summaryrefslogtreecommitdiff
path: root/chromium/third_party/WebKit/Source/core
diff options
context:
space:
mode:
authorAndras Becsi <andras.becsi@digia.com>2014-03-18 13:16:26 +0100
committerFrederik Gladhorn <frederik.gladhorn@digia.com>2014-03-20 15:55:39 +0100
commit3f0f86b0caed75241fa71c95a5d73bc0164348c5 (patch)
tree92b9fb00f2e9e90b0be2262093876d4f43b6cd13 /chromium/third_party/WebKit/Source/core
parente90d7c4b152c56919d963987e2503f9909a666d2 (diff)
downloadqtwebengine-chromium-3f0f86b0caed75241fa71c95a5d73bc0164348c5.tar.gz
Update to new stable branch 1750
This also includes an updated ninja and chromium dependencies needed on Windows. Change-Id: Icd597d80ed3fa4425933c9f1334c3c2e31291c42 Reviewed-by: Zoltan Arvai <zarvai@inf.u-szeged.hu> Reviewed-by: Zeno Albisser <zeno.albisser@digia.com>
Diffstat (limited to 'chromium/third_party/WebKit/Source/core')
-rw-r--r--chromium/third_party/WebKit/Source/core/.gitattributes1
-rw-r--r--chromium/third_party/WebKit/Source/core/ConvertFileToHeaderWithCharacterArray.gypi63
-rw-r--r--chromium/third_party/WebKit/Source/core/DEPS28
-rw-r--r--chromium/third_party/WebKit/Source/core/Init.cpp21
-rw-r--r--chromium/third_party/WebKit/Source/core/OWNERS8
-rw-r--r--chromium/third_party/WebKit/Source/core/Resources/aliasCursor.pngbin752 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/Resources/cellCursor.pngbin183 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/Resources/contextMenuCursor.pngbin523 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/Resources/copyCursor.pngbin1652 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/Resources/deleteButton.pngbin2230 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/Resources/deleteButton.tiffbin2546 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/Resources/deleteButton@2x.pngbin5965 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/Resources/deleteButtonPressed.pngbin2319 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/Resources/deleteButtonPressed.tiffbin2550 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/Resources/deleteButtonPressed@2x.pngbin6176 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/Resources/eastResizeCursor.pngbin123 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/Resources/eastWestResizeCursor.pngbin126 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/Resources/helpCursor.pngbin239 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/Resources/inputSpeech.pngbin1685 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/Resources/inputSpeech.tiffbin5184 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/Resources/linearSRGB.iccbin460 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/Resources/linkCursor.pngbin341 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/Resources/missingImage.pngbin411 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/Resources/missingImage.tiffbin654 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/Resources/missingImage@2x.pngbin3385 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/Resources/moveCursor.pngbin175 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/Resources/noDropCursor.pngbin1455 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/Resources/noneCursor.pngbin90 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/Resources/northEastResizeCursor.pngbin209 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/Resources/northEastSouthWestResizeCursor.pngbin212 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/Resources/northResizeCursor.pngbin125 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/Resources/northSouthResizeCursor.pngbin144 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/Resources/northWestResizeCursor.pngbin174 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/Resources/northWestSouthEastResizeCursor.pngbin193 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/Resources/nullPlugin.pngbin1286 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/Resources/nullPlugin@2x.pngbin7181 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/Resources/pagepopups/calendarPicker.css296
-rw-r--r--chromium/third_party/WebKit/Source/core/Resources/pagepopups/calendarPicker.js4009
-rw-r--r--chromium/third_party/WebKit/Source/core/Resources/pagepopups/chromium/calendarPickerChromium.css46
-rw-r--r--chromium/third_party/WebKit/Source/core/Resources/pagepopups/chromium/pickerCommonChromium.css70
-rw-r--r--chromium/third_party/WebKit/Source/core/Resources/pagepopups/colorSuggestionPicker.css69
-rw-r--r--chromium/third_party/WebKit/Source/core/Resources/pagepopups/colorSuggestionPicker.js189
-rw-r--r--chromium/third_party/WebKit/Source/core/Resources/pagepopups/pickerCommon.css35
-rw-r--r--chromium/third_party/WebKit/Source/core/Resources/pagepopups/pickerCommon.js257
-rw-r--r--chromium/third_party/WebKit/Source/core/Resources/pagepopups/suggestionPicker.css56
-rw-r--r--chromium/third_party/WebKit/Source/core/Resources/pagepopups/suggestionPicker.js325
-rw-r--r--chromium/third_party/WebKit/Source/core/Resources/panIcon.pngbin175 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/Resources/progressCursor.pngbin1791 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/Resources/southEastResizeCursor.pngbin166 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/Resources/southResizeCursor.pngbin128 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/Resources/southWestResizeCursor.pngbin177 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/Resources/textAreaResizeCorner.pngbin146 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/Resources/textAreaResizeCorner.tiffbin254 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/Resources/textAreaResizeCorner@2x.pngbin2907 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/Resources/urlIcon.pngbin819 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/Resources/verticalTextCursor.pngbin120 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/Resources/waitCursor.pngbin125 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/Resources/westResizeCursor.pngbin122 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/Resources/zoomInCursor.pngbin199 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/Resources/zoomOutCursor.pngbin182 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AXARIAGrid.cpp133
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AXARIAGrid.h63
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AXARIAGridCell.cpp124
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AXARIAGridCell.h55
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AXARIAGridRow.cpp130
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AXARIAGridRow.h55
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AXImageMapLink.cpp158
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AXImageMapLink.h82
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AXInlineTextBox.cpp154
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AXInlineTextBox.h68
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AXList.cpp98
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AXList.h56
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AXListBox.cpp169
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AXListBox.h59
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AXListBoxOption.cpp229
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AXListBoxOption.h82
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AXMediaControls.cpp335
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AXMediaControls.h110
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AXMenuList.cpp117
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AXMenuList.h62
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AXMenuListOption.cpp112
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AXMenuListOption.h68
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AXMenuListPopup.cpp146
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AXMenuListPopup.h68
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AXMockObject.cpp45
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AXMockObject.h62
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AXNodeObject.cpp1813
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AXNodeObject.h220
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AXObject.cpp907
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AXObject.h584
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AXObjectCache.cpp291
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AXObjectCache.h122
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AXProgressIndicator.cpp80
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AXProgressIndicator.h53
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AXRenderObject.cpp2368
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AXRenderObject.h238
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AXSVGRoot.cpp61
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AXSVGRoot.h57
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AXScrollView.cpp242
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AXScrollView.h88
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AXScrollbar.cpp109
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AXScrollbar.h71
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AXSlider.cpp159
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AXSlider.h84
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AXSpinButton.cpp127
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AXSpinButton.h78
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AXTable.cpp551
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AXTable.h96
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AXTableCell.cpp178
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AXTableCell.h67
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AXTableColumn.cpp185
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AXTableColumn.h72
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AXTableHeaderContainer.cpp79
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AXTableHeaderContainer.h59
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AXTableRow.cpp132
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AXTableRow.h71
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AccessibilityARIAGrid.cpp133
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AccessibilityARIAGrid.h63
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AccessibilityARIAGridCell.cpp124
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AccessibilityARIAGridCell.h55
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AccessibilityARIAGridRow.cpp130
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AccessibilityARIAGridRow.h55
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AccessibilityImageMapLink.cpp158
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AccessibilityImageMapLink.h80
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AccessibilityList.cpp98
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AccessibilityList.h56
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AccessibilityListBox.cpp169
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AccessibilityListBox.h59
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AccessibilityListBoxOption.cpp228
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AccessibilityListBoxOption.h79
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AccessibilityMediaControls.cpp304
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AccessibilityMediaControls.h112
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AccessibilityMenuList.cpp117
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AccessibilityMenuList.h66
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AccessibilityMenuListOption.cpp112
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AccessibilityMenuListOption.h66
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AccessibilityMenuListPopup.cpp140
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AccessibilityMenuListPopup.h67
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AccessibilityMockObject.cpp45
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AccessibilityMockObject.h66
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AccessibilityNodeObject.cpp1806
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AccessibilityNodeObject.h233
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AccessibilityObject.cpp992
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AccessibilityObject.h594
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AccessibilityProgressIndicator.cpp80
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AccessibilityProgressIndicator.h53
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AccessibilityRenderObject.cpp2384
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AccessibilityRenderObject.h248
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AccessibilitySVGRoot.cpp61
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AccessibilitySVGRoot.h61
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AccessibilityScrollView.cpp242
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AccessibilityScrollView.h95
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AccessibilityScrollbar.cpp109
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AccessibilityScrollbar.h69
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AccessibilitySlider.cpp159
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AccessibilitySlider.h84
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AccessibilitySpinButton.cpp127
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AccessibilitySpinButton.h87
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AccessibilityTable.cpp550
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AccessibilityTable.h100
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AccessibilityTableCell.cpp178
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AccessibilityTableCell.h65
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AccessibilityTableColumn.cpp185
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AccessibilityTableColumn.h69
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AccessibilityTableHeaderContainer.cpp79
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AccessibilityTableHeaderContainer.h59
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AccessibilityTableRow.cpp132
-rw-r--r--chromium/third_party/WebKit/Source/core/accessibility/AccessibilityTableRow.h69
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/ActiveAnimations.cpp101
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/ActiveAnimations.h49
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/AnimatableClipPathOperation.cpp58
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/AnimatableClipPathOperation.h67
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/AnimatableColor.cpp18
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/AnimatableColor.h24
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/AnimatableColorTest.cpp14
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/AnimatableDouble.cpp71
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/AnimatableDouble.h77
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/AnimatableDoubleTest.cpp91
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/AnimatableFilterOperations.cpp71
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/AnimatableFilterOperations.h67
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/AnimatableImage.cpp17
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/AnimatableImage.h11
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/AnimatableLength.cpp241
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/AnimatableLength.h166
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/AnimatableLengthBox.cpp9
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/AnimatableLengthBox.h11
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/AnimatableLengthBoxAndBool.cpp64
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/AnimatableLengthBoxAndBool.h69
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/AnimatableLengthPoint.cpp58
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/AnimatableLengthPoint.h73
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/AnimatableLengthSize.cpp58
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/AnimatableLengthSize.h69
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/AnimatableLengthTest.cpp367
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/AnimatableNeutral.h9
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/AnimatableNeutralTest.cpp4
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/AnimatableNumber.cpp251
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/AnimatableNumber.h137
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/AnimatableNumberTest.cpp310
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/AnimatableRepeatable.cpp100
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/AnimatableRepeatable.h79
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/AnimatableSVGLength.cpp54
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/AnimatableSVGLength.h73
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/AnimatableSVGPaint.cpp64
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/AnimatableSVGPaint.h78
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/AnimatableShadow.cpp55
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/AnimatableShadow.h67
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/AnimatableShapeValue.cpp58
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/AnimatableShapeValue.h67
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/AnimatableStrokeDasharrayList.cpp91
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/AnimatableStrokeDasharrayList.h68
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/AnimatableStrokeDasharrayListTest.cpp60
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/AnimatableTransform.cpp5
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/AnimatableTransform.h13
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/AnimatableUnknown.h20
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/AnimatableUnknownTest.cpp10
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/AnimatableValue.cpp3
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/AnimatableValue.h78
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/AnimatableValueTestHelper.cpp269
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/AnimatableValueTestHelper.h90
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/AnimatableValueTestHelperTest.cpp161
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/AnimatableVisibility.cpp5
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/AnimatableVisibility.h11
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/Animation.cpp143
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/Animation.h39
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/AnimationClock.h78
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/AnimationClockTest.cpp79
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/AnimationEffect.h6
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/AnimationStack.cpp92
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/AnimationStack.h13
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/CompositorAnimations.cpp536
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/CompositorAnimations.h84
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/CompositorAnimationsImpl.h61
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/CompositorAnimationsTest.cpp1088
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/CompositorAnimationsTestHelper.h164
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/CompositorAnimationsTimingFunctionReverserTest.cpp107
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/DocumentAnimations.cpp108
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/DocumentAnimations.h54
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/DocumentTimeline.cpp136
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/DocumentTimeline.h88
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/DocumentTimelineTest.cpp188
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/ElementAnimation.cpp142
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/ElementAnimation.h54
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/ElementAnimation.idl33
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/ElementAnimationTest.cpp208
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/InertAnimation.cpp23
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/InertAnimation.h13
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/KeyframeAnimationEffect.cpp73
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/KeyframeAnimationEffect.h39
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/KeyframeAnimationEffectTest.cpp171
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/Player.cpp103
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/Player.h43
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/PlayerTest.cpp163
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/TimedItem.cpp155
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/TimedItem.h32
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/TimedItemCalculations.h41
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/TimedItemCalculationsTest.cpp144
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/TimedItemTest.cpp542
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/Timing.h3
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/css/CSSAnimatableValueFactory.cpp389
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/css/CSSAnimatableValueFactory.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/css/CSSAnimations.cpp674
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/css/CSSAnimations.h144
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/css/CSSPendingAnimations.cpp94
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/css/CSSPendingAnimations.h56
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/css/TransitionTimeline.cpp52
-rw-r--r--chromium/third_party/WebKit/Source/core/animation/css/TransitionTimeline.h48
-rw-r--r--chromium/third_party/WebKit/Source/core/core.gyp312
-rw-r--r--chromium/third_party/WebKit/Source/core/core.gypi1794
-rw-r--r--chromium/third_party/WebKit/Source/core/core_derived_sources.gyp461
-rw-r--r--chromium/third_party/WebKit/Source/core/css/BasicShapeFunctions.cpp37
-rw-r--r--chromium/third_party/WebKit/Source/core/css/BasicShapeFunctions.h3
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSArrayFunctionValue.cpp4
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSArrayFunctionValue.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSAspectRatioValue.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSAspectRatioValue.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSBasicShapes.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSBorderImageSliceValue.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSBorderImageSliceValue.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSCalculationValue.cpp69
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSCalculationValue.h51
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSCalculationValueTest.cpp62
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSCanvasValue.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSCanvasValue.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSCharsetRule.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSCharsetRule.idl3
-rwxr-xr-x[-rw-r--r--]chromium/third_party/WebKit/Source/core/css/CSSComputedStyleDeclaration.cpp799
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSComputedStyleDeclaration.h34
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSCrossfadeValue.cpp11
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSCrossfadeValue.h6
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSCursorImageValue.cpp12
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSCursorImageValue.h6
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSCustomFontData.h61
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSDefaultStyleSheets.cpp70
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSDefaultStyleSheets.h14
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSFilterRule.cpp3
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSFilterRule.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSFilterValue.cpp6
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSFilterValue.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSFontFace.cpp98
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSFontFace.h34
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSFontFaceLoadEvent.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSFontFaceLoadEvent.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSFontFaceLoadEvent.idl2
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSFontFaceRule.cpp3
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSFontFaceRule.h6
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSFontFaceSource.cpp87
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSFontFaceSource.h16
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSFontFaceSrcValue.cpp4
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSFontFaceSrcValue.h8
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSFontFeatureValue.cpp55
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSFontFeatureValue.h58
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSFontSelector.cpp380
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSFontSelector.h47
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSFontValue.cpp77
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSFontValue.h62
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSFunctionValue.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSFunctionValue.h17
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSGradientValue.cpp135
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSGradientValue.h22
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSGrammar.y1985
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSGrammar.y.in1937
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSGrammar.y.includes60
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSGridLineNamesValue.cpp52
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSGridLineNamesValue.h58
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSGridTemplateValue.cpp3
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSGridTemplateValue.h17
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSGroupingRule.cpp16
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSGroupingRule.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSHelper.h6
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSHostRule.cpp45
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSHostRule.h44
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSHostRule.idl28
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSImageGeneratorValue.cpp50
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSImageGeneratorValue.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSImageSetValue.cpp13
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSImageSetValue.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSImageValue.cpp25
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSImageValue.h21
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSImportRule.h6
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSInheritedValue.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSInheritedValue.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSInitialValue.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSInitialValue.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSKeyframeRule.cpp4
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSKeyframeRule.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSKeyframesRule.cpp3
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSKeyframesRule.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSKeyframesRule.idl4
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSLengthFunctions.cpp149
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSLengthFunctions.h42
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSLineBoxContainValue.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSLineBoxContainValue.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSMatrix.cpp35
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSMatrix.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSMediaRule.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSMediaRule.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSMixFunctionValue.cpp4
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSMixFunctionValue.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSPageRule.cpp3
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSPageRule.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSPageRule.idl6
-rwxr-xr-x[-rw-r--r--]chromium/third_party/WebKit/Source/core/css/CSSParser-in.cpp2418
-rwxr-xr-x[-rw-r--r--]chromium/third_party/WebKit/Source/core/css/CSSParser.h186
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSParserMode.cpp66
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSParserMode.h97
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSParserValues.cpp30
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSParserValues.h28
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSPrimitiveValue.cpp134
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSPrimitiveValue.h42
-rwxr-xr-x[-rw-r--r--]chromium/third_party/WebKit/Source/core/css/CSSPrimitiveValueMappings.h305
-rwxr-xr-x[-rw-r--r--]chromium/third_party/WebKit/Source/core/css/CSSProperties.in38
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSProperty.cpp22
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSProperty.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSPropertyNames.in22
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSPropertySourceData.h1
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSReflectValue.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSReflectValue.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSRegionRule.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSRegionRule.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSRule.cpp4
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSRule.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSRule.idl11
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSSVGDocumentValue.cpp3
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSSVGDocumentValue.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSSegmentedFontFace.cpp89
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSSegmentedFontFace.h22
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSSegmentedFontFaceCache.cpp208
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSSegmentedFontFaceCache.h71
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSSelector.cpp35
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSSelector.h25
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSSelectorList.cpp20
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSSelectorList.h1
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSShaderValue.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSShaderValue.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSShadowValue.cpp91
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSShadowValue.h69
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSShorthands.in1
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSStyleDeclaration.cpp1
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSStyleDeclaration.h8
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSStyleDeclaration.idl4
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSStyleRule.cpp3
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSStyleRule.h6
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSStyleRule.idl6
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSStyleSheet.cpp87
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSStyleSheet.h23
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSStyleSheet.idl15
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSSupportsRule.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSSupportsRule.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSTimingFunctionValue.cpp4
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSTimingFunctionValue.h8
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSToLengthConversionData.cpp45
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSToLengthConversionData.h82
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSToStyleMap.cpp718
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSToStyleMap.h92
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSTokenizer-in.cpp1559
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSTokenizer.h197
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSTransformValue.cpp6
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSTransformValue.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSUnicodeRangeValue.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSUnicodeRangeValue.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSValue.cpp186
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSValue.h34
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSValue.idl7
-rwxr-xr-x[-rw-r--r--]chromium/third_party/WebKit/Source/core/css/CSSValueKeywords.in33
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSValueList.cpp4
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSValueList.h17
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSValuePool.cpp11
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSValuePool.h3
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSValueTestHelper.h76
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSVariableValue.h12
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSVariablesIterator.h49
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSVariablesMap.cpp64
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSVariablesMap.h19
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSVariablesMap.idl1
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSVariablesMapForEachCallback.h48
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSVariablesMapForEachCallback.idl31
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSViewportRule.cpp4
-rw-r--r--chromium/third_party/WebKit/Source/core/css/CSSViewportRule.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/css/DOMWindowCSS.cpp6
-rw-r--r--chromium/third_party/WebKit/Source/core/css/DocumentFontFaceSet.cpp38
-rw-r--r--chromium/third_party/WebKit/Source/core/css/DocumentFontFaceSet.h43
-rw-r--r--chromium/third_party/WebKit/Source/core/css/DocumentFontFaceSet.idl33
-rw-r--r--chromium/third_party/WebKit/Source/core/css/DocumentRuleSets.cpp118
-rw-r--r--chromium/third_party/WebKit/Source/core/css/DocumentRuleSets.h77
-rw-r--r--chromium/third_party/WebKit/Source/core/css/ElementRuleCollector.cpp188
-rw-r--r--chromium/third_party/WebKit/Source/core/css/ElementRuleCollector.h50
-rw-r--r--chromium/third_party/WebKit/Source/core/css/FontFace.cpp176
-rw-r--r--chromium/third_party/WebKit/Source/core/css/FontFace.h20
-rw-r--r--chromium/third_party/WebKit/Source/core/css/FontFace.idl23
-rw-r--r--chromium/third_party/WebKit/Source/core/css/FontFaceSet.cpp244
-rw-r--r--chromium/third_party/WebKit/Source/core/css/FontFaceSet.h64
-rw-r--r--chromium/third_party/WebKit/Source/core/css/FontFaceSet.idl10
-rw-r--r--chromium/third_party/WebKit/Source/core/css/FontFamilyNames.in7
-rw-r--r--chromium/third_party/WebKit/Source/core/css/FontFeatureValue.cpp55
-rw-r--r--chromium/third_party/WebKit/Source/core/css/FontFeatureValue.h56
-rw-r--r--chromium/third_party/WebKit/Source/core/css/FontSize.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/css/FontValue.cpp77
-rw-r--r--chromium/third_party/WebKit/Source/core/css/FontValue.h60
-rw-r--r--chromium/third_party/WebKit/Source/core/css/HashTools.h40
-rw-r--r--chromium/third_party/WebKit/Source/core/css/InspectorCSSOMWrappers.cpp24
-rw-r--r--chromium/third_party/WebKit/Source/core/css/LengthFunctions.cpp145
-rw-r--r--chromium/third_party/WebKit/Source/core/css/LengthFunctions.h41
-rw-r--r--chromium/third_party/WebKit/Source/core/css/MediaList.cpp13
-rw-r--r--chromium/third_party/WebKit/Source/core/css/MediaQuery.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/css/MediaQuery.h6
-rw-r--r--chromium/third_party/WebKit/Source/core/css/MediaQueryEvaluator.cpp82
-rw-r--r--chromium/third_party/WebKit/Source/core/css/MediaQueryEvaluator.h6
-rw-r--r--chromium/third_party/WebKit/Source/core/css/MediaQueryExp.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/css/MediaQueryListListener.idl25
-rw-r--r--chromium/third_party/WebKit/Source/core/css/MediaQueryMatcher.cpp11
-rw-r--r--chromium/third_party/WebKit/Source/core/css/PageRuleCollector.cpp10
-rw-r--r--chromium/third_party/WebKit/Source/core/css/PageRuleCollector.h7
-rw-r--r--chromium/third_party/WebKit/Source/core/css/Pair.h3
-rw-r--r--chromium/third_party/WebKit/Source/core/css/PropertySetCSSStyleDeclaration.cpp36
-rw-r--r--chromium/third_party/WebKit/Source/core/css/PropertySetCSSStyleDeclaration.h7
-rw-r--r--chromium/third_party/WebKit/Source/core/css/PseudoStyleRequest.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/css/RGBColor.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/css/RuleFeature.cpp11
-rw-r--r--chromium/third_party/WebKit/Source/core/css/RuleFeature.h5
-rw-r--r--chromium/third_party/WebKit/Source/core/css/RuleSet.cpp126
-rw-r--r--chromium/third_party/WebKit/Source/core/css/RuleSet.h35
-rw-r--r--chromium/third_party/WebKit/Source/core/css/RuntimeCSSEnabled.cpp173
-rw-r--r--chromium/third_party/WebKit/Source/core/css/RuntimeCSSEnabled.h (renamed from chromium/third_party/WebKit/Source/core/page/RuntimeCSSEnabled.h)0
-rw-r--r--chromium/third_party/WebKit/Source/core/css/SVGCSSComputedStyleDeclaration.cpp16
-rw-r--r--chromium/third_party/WebKit/Source/core/css/SelectorChecker.cpp480
-rw-r--r--chromium/third_party/WebKit/Source/core/css/SelectorChecker.h66
-rw-r--r--chromium/third_party/WebKit/Source/core/css/SelectorCheckerFastPath.cpp24
-rw-r--r--chromium/third_party/WebKit/Source/core/css/SelectorCheckerFastPath.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/css/SelectorFilter.cpp39
-rw-r--r--chromium/third_party/WebKit/Source/core/css/SelectorFilter.h8
-rw-r--r--chromium/third_party/WebKit/Source/core/css/ShadowValue.cpp91
-rw-r--r--chromium/third_party/WebKit/Source/core/css/ShadowValue.h67
-rw-r--r--chromium/third_party/WebKit/Source/core/css/SiblingTraversalStrategies.h29
-rw-r--r--chromium/third_party/WebKit/Source/core/css/StyleColor.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/css/StyleInvalidationAnalysis.cpp57
-rw-r--r--chromium/third_party/WebKit/Source/core/css/StyleInvalidationAnalysis.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/css/StyleMedia.cpp15
-rw-r--r--chromium/third_party/WebKit/Source/core/css/StyleMedia.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/css/StylePropertySerializer.cpp4
-rw-r--r--chromium/third_party/WebKit/Source/core/css/StylePropertySet.cpp87
-rw-r--r--chromium/third_party/WebKit/Source/core/css/StylePropertySet.h54
-rw-r--r--chromium/third_party/WebKit/Source/core/css/StylePropertyShorthandCustom.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/css/StyleRule.cpp75
-rw-r--r--chromium/third_party/WebKit/Source/core/css/StyleRule.h62
-rw-r--r--chromium/third_party/WebKit/Source/core/css/StyleRuleImport.cpp11
-rw-r--r--chromium/third_party/WebKit/Source/core/css/StyleRuleImport.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/css/StyleSheet.h1
-rw-r--r--chromium/third_party/WebKit/Source/core/css/StyleSheet.idl4
-rw-r--r--chromium/third_party/WebKit/Source/core/css/StyleSheetContents.cpp113
-rw-r--r--chromium/third_party/WebKit/Source/core/css/StyleSheetContents.h25
-rw-r--r--chromium/third_party/WebKit/Source/core/css/StyleSheetList.cpp22
-rw-r--r--chromium/third_party/WebKit/Source/core/css/StyleSheetList.h16
-rw-r--r--chromium/third_party/WebKit/Source/core/css/StyleSheetList.idl2
-rw-r--r--chromium/third_party/WebKit/Source/core/css/TreeBoundaryCrossingRules.cpp63
-rw-r--r--chromium/third_party/WebKit/Source/core/css/TreeBoundaryCrossingRules.h58
-rw-r--r--chromium/third_party/WebKit/Source/core/css/WebKitCSSMatrix.idl2
-rw-r--r--chromium/third_party/WebKit/Source/core/css/WebKitCSSRegionRule.idl2
-rw-r--r--chromium/third_party/WebKit/Source/core/css/fullscreen.css2
-rw-r--r--chromium/third_party/WebKit/Source/core/css/html.css39
-rw-r--r--chromium/third_party/WebKit/Source/core/css/makegrammar.pl58
-rw-r--r--chromium/third_party/WebKit/Source/core/css/mediaControls.css6
-rw-r--r--chromium/third_party/WebKit/Source/core/css/mediaControlsAndroid.css9
-rw-r--r--chromium/third_party/WebKit/Source/core/css/resolver/AnimatedStyleBuilder.cpp406
-rw-r--r--chromium/third_party/WebKit/Source/core/css/resolver/CSSToStyleMap.cpp670
-rw-r--r--chromium/third_party/WebKit/Source/core/css/resolver/CSSToStyleMap.h92
-rw-r--r--chromium/third_party/WebKit/Source/core/css/resolver/ElementResolveContext.cpp13
-rw-r--r--chromium/third_party/WebKit/Source/core/css/resolver/ElementResolveContext.h7
-rw-r--r--chromium/third_party/WebKit/Source/core/css/resolver/ElementStyleResources.cpp20
-rw-r--r--chromium/third_party/WebKit/Source/core/css/resolver/ElementStyleResources.h13
-rw-r--r--chromium/third_party/WebKit/Source/core/css/resolver/FilterOperationResolver.cpp117
-rw-r--r--chromium/third_party/WebKit/Source/core/css/resolver/FilterOperationResolver.h6
-rw-r--r--chromium/third_party/WebKit/Source/core/css/resolver/FontBuilder.cpp42
-rw-r--r--chromium/third_party/WebKit/Source/core/css/resolver/FontBuilder.h3
-rw-r--r--chromium/third_party/WebKit/Source/core/css/resolver/MatchRequest.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/css/resolver/MatchedPropertiesCache.cpp3
-rw-r--r--chromium/third_party/WebKit/Source/core/css/resolver/MatchedPropertiesCache.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/css/resolver/MediaQueryResult.h3
-rw-r--r--chromium/third_party/WebKit/Source/core/css/resolver/ScopedStyleResolver.cpp342
-rw-r--r--chromium/third_party/WebKit/Source/core/css/resolver/ScopedStyleResolver.h89
-rw-r--r--chromium/third_party/WebKit/Source/core/css/resolver/ScopedStyleTree.cpp219
-rw-r--r--chromium/third_party/WebKit/Source/core/css/resolver/ScopedStyleTree.h108
-rw-r--r--chromium/third_party/WebKit/Source/core/css/resolver/SharedStyleFinder.cpp268
-rw-r--r--chromium/third_party/WebKit/Source/core/css/resolver/SharedStyleFinder.h33
-rw-r--r--chromium/third_party/WebKit/Source/core/css/resolver/StyleAdjuster.cpp25
-rw-r--r--chromium/third_party/WebKit/Source/core/css/resolver/StyleBuilderConverter.cpp174
-rw-r--r--chromium/third_party/WebKit/Source/core/css/resolver/StyleBuilderConverter.h104
-rwxr-xr-x[-rw-r--r--]chromium/third_party/WebKit/Source/core/css/resolver/StyleBuilderCustom.cpp445
-rw-r--r--chromium/third_party/WebKit/Source/core/css/resolver/StyleBuilderCustom.h99
-rw-r--r--chromium/third_party/WebKit/Source/core/css/resolver/StyleResolver.cpp1028
-rw-r--r--chromium/third_party/WebKit/Source/core/css/resolver/StyleResolver.h226
-rw-r--r--chromium/third_party/WebKit/Source/core/css/resolver/StyleResolverIncludes.h13
-rw-r--r--chromium/third_party/WebKit/Source/core/css/resolver/StyleResolverState.cpp37
-rw-r--r--chromium/third_party/WebKit/Source/core/css/resolver/StyleResolverState.h20
-rw-r--r--chromium/third_party/WebKit/Source/core/css/resolver/StyleResolverStats.cpp87
-rw-r--r--chromium/third_party/WebKit/Source/core/css/resolver/StyleResolverStats.h77
-rw-r--r--chromium/third_party/WebKit/Source/core/css/resolver/StyleResourceLoader.cpp48
-rw-r--r--chromium/third_party/WebKit/Source/core/css/resolver/TransformBuilder.cpp46
-rw-r--r--chromium/third_party/WebKit/Source/core/css/resolver/TransformBuilder.h6
-rw-r--r--chromium/third_party/WebKit/Source/core/css/resolver/ViewportStyleResolver.cpp51
-rw-r--r--chromium/third_party/WebKit/Source/core/css/resolver/ViewportStyleResolver.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/css/themeChromiumLinux.css4
-rw-r--r--chromium/third_party/WebKit/Source/core/css/themeWin.css17
-rw-r--r--chromium/third_party/WebKit/Source/core/css/view-source.css16
-rw-r--r--chromium/third_party/WebKit/Source/core/css/viewportAndroid.css35
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/ActiveDOMObject.cpp27
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/ActiveDOMObject.h31
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/AddConsoleMessageTask.cpp39
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/AddConsoleMessageTask.h59
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/Attr.cpp20
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/Attr.h20
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/Attr.idl10
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/AutocompleteErrorEvent.h83
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/AutocompleteErrorEvent.idl30
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/BeforeLoadEvent.h89
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/BeforeLoadEvent.idl32
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/BeforeTextInsertedEvent.cpp48
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/BeforeTextInsertedEvent.h56
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/BeforeUnloadEvent.cpp46
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/BeforeUnloadEvent.h63
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/CDATASection.h12
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/CSSSelectorWatch.cpp168
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/CSSSelectorWatch.h82
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/CharacterData.cpp57
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/CharacterData.h16
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/ChildListMutationScope.cpp8
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/ChildListMutationScope.h14
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/ChildNode.idl2
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/ChildNodeList.h22
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/ClassNodeList.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/ClientRect.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/ClientRectList.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/Clipboard.cpp453
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/Clipboard.h63
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/Clipboard.idl6
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/ClipboardEvent.cpp55
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/ClipboardEvent.h60
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/Comment.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/Comment.h14
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/Comment.idl2
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/CompositionEvent.cpp76
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/CompositionEvent.h75
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/CompositionEvent.idl39
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/ContainerNode.cpp459
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/ContainerNode.h56
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/ContainerNodeAlgorithms.cpp79
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/ContainerNodeAlgorithms.h173
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/ContextFeatures.cpp6
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/ContextFeatures.h13
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/ContextLifecycleNotifier.cpp43
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/ContextLifecycleNotifier.h19
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/ContextLifecycleObserver.cpp17
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/ContextLifecycleObserver.h14
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/CrossThreadTask.h87
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/CustomElement.cpp180
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/CustomElement.h97
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/CustomElementCallbackDispatcher.cpp124
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/CustomElementCallbackDispatcher.h114
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/CustomElementCallbackInvocation.cpp135
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/CustomElementCallbackInvocation.h68
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/CustomElementCallbackQueue.cpp71
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/CustomElementCallbackQueue.h74
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/CustomElementCallbackScheduler.cpp122
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/CustomElementCallbackScheduler.h71
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/CustomElementDefinition.cpp47
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/CustomElementDefinition.h60
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/CustomElementDescriptorHash.h66
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/CustomElementException.cpp95
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/CustomElementLifecycleCallbacks.h74
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/CustomElementObserver.cpp70
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/CustomElementRegistrationContext.cpp150
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/CustomElementRegistrationContext.h89
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/CustomElementRegistry.cpp126
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/CustomElementRegistry.h69
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/CustomElementUpgradeCandidateMap.cpp110
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/CustomElementUpgradeCandidateMap.h75
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/CustomEvent.cpp64
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/CustomEvent.h72
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/CustomEvent.idl35
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/DOMError.cpp1
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/DOMError.idl2
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/DOMException.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/DOMImplementation.cpp83
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/DOMImplementation.h18
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/DOMImplementation.idl23
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/DOMNamedFlowCollection.cpp4
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/DOMSettableTokenList.cpp8
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/DOMStringMap.h23
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/DOMStringMap.idl7
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/DOMTokenList.cpp46
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/DOMTokenList.idl8
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/DOMURL.cpp94
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/DOMURL.h82
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/DOMURLUtils.cpp142
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/DOMURLUtils.h59
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/DOMURLUtilsReadOnly.cpp81
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/DOMURLUtilsReadOnly.h77
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/DataTransferItem.cpp63
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/DataTransferItem.h29
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/DataTransferItem.idl2
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/DataTransferItemList.cpp110
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/DataTransferItemList.h28
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/DatasetDOMStringMap.cpp13
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/DecodedDataDocumentParser.cpp80
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/DecodedDataDocumentParser.h20
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/DeviceOrientationClient.h50
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/DeviceOrientationController.cpp92
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/DeviceOrientationController.h61
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/Document.cpp1828
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/Document.h420
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/Document.idl194
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/DocumentEncodingData.h52
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/DocumentEventQueue.cpp147
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/DocumentEventQueue.h77
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/DocumentFragment.h14
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/DocumentFragment.idl3
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/DocumentFullscreen.idl14
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/DocumentInit.cpp61
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/DocumentInit.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/DocumentLifecycle.cpp55
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/DocumentLifecycle.h63
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/DocumentLifecycleNotifier.cpp60
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/DocumentLifecycleNotifier.h75
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/DocumentLifecycleObserver.cpp29
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/DocumentLifecycleObserver.h47
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/DocumentMarker.cpp4
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/DocumentMarker.h25
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/DocumentMarkerController.cpp433
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/DocumentMarkerController.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/DocumentMarkerControllerTest.cpp181
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/DocumentOrderedList.cpp4
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/DocumentOrderedList.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/DocumentOrderedMap.cpp3
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/DocumentParser.cpp11
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/DocumentParser.h11
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/DocumentStyleSheetCollection.cpp96
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/DocumentStyleSheetCollection.h8
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/DocumentSupplementable.h42
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/DocumentType.h12
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/Element.cpp1468
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/Element.h380
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/Element.idl164
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/ElementData.cpp225
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/ElementData.h259
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/ElementRareData.h50
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/ElementTraversal.h84
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/Entity.h6
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/ErrorEvent.cpp88
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/ErrorEvent.h101
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/ErrorEvent.idl40
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/Event.cpp204
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/Event.h212
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/Event.idl79
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/EventAliases.in14
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/EventContext.cpp140
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/EventContext.h127
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/EventDispatchMediator.cpp55
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/EventDispatcher.cpp227
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/EventDispatcher.h83
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/EventListener.h67
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/EventListenerMap.cpp272
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/EventListenerMap.h99
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/EventNames.cpp40
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/EventNames.h338
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/EventPathWalker.cpp82
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/EventPathWalker.h50
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/EventRetargeter.cpp283
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/EventRetargeter.h98
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/EventSender.h113
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/EventTarget.cpp366
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/EventTarget.h213
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/EventTarget.idl32
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/EventTargetFactory.in47
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/ExecutionContext.cpp337
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/ExecutionContext.h167
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/ExecutionContextClient.h86
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/ExecutionContextTask.cpp38
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/ExecutionContextTask.h65
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/FocusEvent.cpp134
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/FocusEvent.h117
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/FocusEvent.idl30
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/FullscreenElementStack.cpp47
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/FullscreenElementStack.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/GenericEventQueue.cpp113
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/GenericEventQueue.h65
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/GestureEvent.cpp128
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/GestureEvent.h82
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/GlobalEventHandlers.h99
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/GlobalEventHandlers.idl92
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/HashChangeEvent.h99
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/HashChangeEvent.idl32
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/IconURL.cpp13
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/IconURL.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/KeyboardEvent.cpp240
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/KeyboardEvent.h133
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/KeyboardEvent.idl53
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/LiveNodeList.cpp21
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/LiveNodeList.h6
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/MainThreadTaskRunner.cpp116
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/MainThreadTaskRunner.h77
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/MainThreadTaskRunnerTest.cpp139
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/MessageChannel.cpp22
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/MessageChannel.h6
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/MessageChannel.idl2
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/MessageEvent.cpp158
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/MessageEvent.h134
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/MessageEvent.idl56
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/MessagePort.cpp162
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/MessagePort.h73
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/MessagePortChannel.cpp35
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/MessagePortChannel.h97
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/Microtask.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/MouseEvent.cpp290
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/MouseEvent.h150
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/MouseEvent.idl62
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/MouseRelatedEvent.cpp230
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/MouseRelatedEvent.h91
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/MutationCallback.h5
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/MutationEvent.cpp74
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/MutationEvent.h80
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/MutationObserver.cpp86
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/MutationObserver.h8
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/MutationObserver.idl2
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/MutationObserverInterestGroup.cpp6
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/MutationObserverInterestGroup.h14
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/MutationRecord.cpp8
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/NameNodeList.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/NamedFlow.cpp40
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/NamedFlow.h23
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/NamedFlowCollection.cpp10
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/NamedFlowCollection.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/NamedNodeMap.cpp27
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/NamedNodeMap.idl10
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/NamedNodesCollection.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/Node.cpp599
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/Node.h205
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/Node.idl42
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/NodeChildRemovalTracker.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/NodeFilter.idl1
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/NodeIterator.cpp41
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/NodeIterator.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/NodeIterator.idl2
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/NodeList.h42
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/NodeList.idl4
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/NodeRareData.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/NodeRenderingContext.cpp13
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/NodeRenderingTraversal.cpp12
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/NodeRenderingTraversal.h13
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/NodeTraversal.cpp108
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/NodeTraversal.h84
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/OverflowEvent.cpp89
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/OverflowEvent.h82
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/OverflowEvent.idl37
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/PageTransitionEvent.cpp67
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/PageTransitionEvent.h70
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/PageTransitionEvent.idl31
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/PendingScript.cpp15
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/PendingScript.h13
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/PopStateEvent.cpp83
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/PopStateEvent.h67
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/PopStateEvent.idl31
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/Position.cpp30
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/Position.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/PositionIterator.cpp1
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/PresentationAttributeStyle.cpp208
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/PresentationAttributeStyle.h45
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/ProcessingInstruction.cpp52
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/ProcessingInstruction.h18
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/ProgressEvent.cpp71
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/ProgressEvent.h74
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/ProgressEvent.idl33
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/Promise.idl8
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/PseudoElement.cpp18
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/PseudoElement.h19
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/QualifiedName.cpp23
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/Range.cpp509
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/Range.h8
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/Range.idl67
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/RangeBoundaryPoint.h11
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/RawDataDocumentParser.h5
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/RegisteredEventListener.h51
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/RequestAnimationFrameCallback.h8
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/RequestAnimationFrameCallback.idl2
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/ResourceProgressEvent.cpp54
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/ResourceProgressEvent.h70
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/SandboxFlags.cpp92
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/SandboxFlags.h57
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/ScopedEventQueue.cpp108
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/ScriptExecutionContext.cpp322
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/ScriptExecutionContext.h207
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/ScriptLoader.cpp51
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/ScriptLoader.h8
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/ScriptRunner.cpp17
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/ScriptRunner.h3
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/ScriptableDocumentParser.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/ScriptedAnimationController.cpp112
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/ScriptedAnimationController.h24
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/SecurityContext.cpp83
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/SecurityContext.h31
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/SecurityPolicyViolationEvent.h111
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/SecurityPolicyViolationEvent.idl39
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/SelectorQuery.cpp186
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/SelectorQuery.h36
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/ShadowTreeStyleSheetCollection.cpp55
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/ShadowTreeStyleSheetCollection.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/SimulatedClickOptions.h5
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/StaticNodeList.h40
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/StringCallback.cpp17
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/StringCallback.h9
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/StringCallback.idl2
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/StyleElement.cpp10
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/StyleEngine.cpp394
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/StyleEngine.h111
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/StyleSheetCollection.cpp129
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/StyleSheetCollection.h53
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/StyleSheetScopingNodeList.cpp4
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/StyleSheetScopingNodeList.h5
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/TagNodeList.cpp1
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/TagNodeList.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/TemplateContentDocumentFragment.h8
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/Text.cpp47
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/Text.h19
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/Text.idl4
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/TextEvent.cpp110
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/TextEvent.h88
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/TextLinkColors.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/Touch.cpp4
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/Touch.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/TouchController.cpp162
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/TouchController.h76
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/TouchEvent.cpp114
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/TouchEvent.h104
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/TransitionEvent.cpp87
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/TransitionEvent.h78
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/TransitionEvent.idl34
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/TreeScope.cpp79
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/TreeScope.h25
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/TreeScopeAdopter.cpp68
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/TreeScopeAdopter.h26
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/TreeShared.h121
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/TreeWalker.cpp9
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/TreeWalker.idl4
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/UIEvent.cpp118
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/UIEvent.h89
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/UIEvent.idl41
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/UIEventWithKeyState.cpp34
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/UIEventWithKeyState.h68
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/URL.idl40
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/URLUtils.idl49
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/URLUtilsReadOnly.idl41
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/UserGestureIndicator.cpp211
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/UserGestureIndicator.h85
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/UserTypingGestureIndicator.cpp66
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/UserTypingGestureIndicator.h53
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/ViewportArguments.cpp398
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/ViewportArguments.h130
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/ViewportDescription.cpp179
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/ViewportDescription.h118
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/VisitedLinkState.cpp67
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/VisitedLinkState.h29
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/WebKitAnimationEvent.cpp80
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/WebKitAnimationEvent.h76
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/WebKitAnimationEvent.idl32
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/WebKitNamedFlow.idl6
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/WebKitNamedFlowCollection.idl2
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/WheelController.cpp14
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/WheelController.h9
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/WheelEvent.cpp155
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/WheelEvent.h125
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/WheelEvent.idl55
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/WhitespaceChildList.h71
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/WindowEventContext.cpp64
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/custom/CustomElement.cpp166
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/custom/CustomElement.h97
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/custom/CustomElementBaseElementQueue.cpp64
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/custom/CustomElementBaseElementQueue.h58
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/custom/CustomElementCallbackDispatcher.cpp108
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/custom/CustomElementCallbackDispatcher.h121
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/custom/CustomElementCallbackInvocation.cpp135
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/custom/CustomElementCallbackInvocation.h68
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/custom/CustomElementCallbackQueue.cpp71
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/custom/CustomElementCallbackQueue.h74
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/custom/CustomElementCallbackScheduler.cpp121
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/custom/CustomElementCallbackScheduler.h71
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/custom/CustomElementDefinition.cpp47
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/custom/CustomElementDefinition.h58
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/custom/CustomElementDescriptor.h (renamed from chromium/third_party/WebKit/Source/core/dom/CustomElementDescriptor.h)0
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/custom/CustomElementDescriptorHash.h66
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/custom/CustomElementException.cpp95
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/custom/CustomElementException.h (renamed from chromium/third_party/WebKit/Source/core/dom/CustomElementException.h)0
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/custom/CustomElementLifecycleCallbacks.h74
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/custom/CustomElementObserver.cpp70
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/custom/CustomElementObserver.h (renamed from chromium/third_party/WebKit/Source/core/dom/CustomElementObserver.h)0
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/custom/CustomElementRegistrationContext.cpp150
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/custom/CustomElementRegistrationContext.h83
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/custom/CustomElementRegistry.cpp124
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/custom/CustomElementRegistry.h68
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/custom/CustomElementUpgradeCandidateMap.cpp110
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/custom/CustomElementUpgradeCandidateMap.h75
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/default/PlatformMessagePortChannel.cpp196
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/default/PlatformMessagePortChannel.h115
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/default/chromium/PlatformMessagePortChannelChromium.cpp251
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/default/chromium/PlatformMessagePortChannelChromium.h92
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/shadow/ComposedTreeWalker.cpp97
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/shadow/ComposedTreeWalker.h8
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/shadow/ContentDistribution.cpp3
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/shadow/ElementShadow.cpp271
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/shadow/ElementShadow.h38
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/shadow/InsertionPoint.cpp136
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/shadow/InsertionPoint.h63
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/shadow/ShadowRoot.cpp140
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/shadow/ShadowRoot.h85
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/shadow/ShadowRoot.idl7
-rw-r--r--chromium/third_party/WebKit/Source/core/dom/shadow/ShadowRootRareData.h58
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/AppendNodeCommand.cpp4
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/ApplyBlockElementCommand.cpp18
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/ApplyStyleCommand.cpp126
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/BreakBlockquoteCommand.cpp7
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/Caret.cpp33
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/Caret.h6
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/CompositeEditCommand.cpp67
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/CompositeEditCommand.h8
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/CompositionUnderline.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/CreateLinkCommand.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/DeleteFromTextNodeCommand.cpp8
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/DeleteSelectionCommand.cpp32
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/EditCommand.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/EditCommand.h7
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/EditingBehavior.h11
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/EditingStyle.cpp38
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/Editor.cpp1560
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/Editor.h124
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/EditorCommand.cpp116
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/EditorInsertAction.h40
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/EditorKeyBindings.cpp307
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/FormatBlockCommand.cpp16
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/FrameSelection.cpp283
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/FrameSelection.h21
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/IndentOutdentCommand.cpp20
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/InputMethodController.cpp209
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/InputMethodController.h60
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/InsertIntoTextNodeCommand.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/InsertLineBreakCommand.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/InsertListCommand.cpp10
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/InsertNodeBeforeCommand.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/InsertParagraphSeparatorCommand.cpp4
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/InsertTextCommand.cpp4
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/MarkupAccumulator.cpp8
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/MergeIdenticalElementsCommand.cpp8
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/ModifySelectionListLevel.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/PlainTextRange.cpp185
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/PlainTextRange.h68
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/RemoveFormatCommand.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/RemoveNodeCommand.cpp4
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/RenderedPosition.cpp1
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/ReplaceNodeWithSpanCommand.cpp16
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/ReplaceSelectionCommand.cpp124
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/ReplaceSelectionCommand.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/SelectionType.h35
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/SetNodeAttributeCommand.cpp3
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/SetSelectionCommand.cpp11
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/SimplifyMarkupCommand.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/SpellCheckRequester.cpp30
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/SpellCheckRequester.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/SpellChecker.cpp884
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/SpellChecker.h104
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/SpellingCorrectionCommand.cpp5
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/SplitElementCommand.cpp8
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/SplitTextNodeCommand.cpp10
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/TextCheckingHelper.cpp29
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/TextCheckingHelper.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/TextInsertionBaseCommand.cpp4
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/TextIterator.cpp770
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/TextIterator.h44
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/TextIteratorTest.cpp431
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/TypingCommand.cpp62
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/TypingCommand.h3
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/UndoStack.cpp124
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/UndoStack.h69
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/UndoStep.h3
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/VisiblePosition.cpp14
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/VisiblePosition.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/VisibleSelection.cpp21
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/VisibleSelection.h3
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/VisibleUnits.cpp88
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/VisibleUnits.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/chromium/EditorChromium.cpp49
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/htmlediting.cpp71
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/htmlediting.h5
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/markup.cpp82
-rw-r--r--chromium/third_party/WebKit/Source/core/editing/markup.h3
-rw-r--r--chromium/third_party/WebKit/Source/core/events/AutocompleteErrorEvent.h83
-rw-r--r--chromium/third_party/WebKit/Source/core/events/AutocompleteErrorEvent.idl30
-rw-r--r--chromium/third_party/WebKit/Source/core/events/BeforeLoadEvent.h89
-rw-r--r--chromium/third_party/WebKit/Source/core/events/BeforeLoadEvent.idl32
-rw-r--r--chromium/third_party/WebKit/Source/core/events/BeforeTextInsertedEvent.cpp48
-rw-r--r--chromium/third_party/WebKit/Source/core/events/BeforeTextInsertedEvent.h56
-rw-r--r--chromium/third_party/WebKit/Source/core/events/BeforeUnloadEvent.cpp45
-rw-r--r--chromium/third_party/WebKit/Source/core/events/BeforeUnloadEvent.h59
-rw-r--r--chromium/third_party/WebKit/Source/core/events/BeforeUnloadEvent.idl (renamed from chromium/third_party/WebKit/Source/core/dom/BeforeUnloadEvent.idl)0
-rw-r--r--chromium/third_party/WebKit/Source/core/events/ClipboardEvent.cpp55
-rw-r--r--chromium/third_party/WebKit/Source/core/events/ClipboardEvent.h60
-rw-r--r--chromium/third_party/WebKit/Source/core/events/CompositionEvent.cpp76
-rw-r--r--chromium/third_party/WebKit/Source/core/events/CompositionEvent.h75
-rw-r--r--chromium/third_party/WebKit/Source/core/events/CompositionEvent.idl39
-rw-r--r--chromium/third_party/WebKit/Source/core/events/CustomEvent.cpp64
-rw-r--r--chromium/third_party/WebKit/Source/core/events/CustomEvent.h72
-rw-r--r--chromium/third_party/WebKit/Source/core/events/CustomEvent.idl35
-rw-r--r--chromium/third_party/WebKit/Source/core/events/DOMWindowEventQueue.cpp130
-rw-r--r--chromium/third_party/WebKit/Source/core/events/DOMWindowEventQueue.h69
-rw-r--r--chromium/third_party/WebKit/Source/core/events/ErrorEvent.cpp88
-rw-r--r--chromium/third_party/WebKit/Source/core/events/ErrorEvent.h101
-rw-r--r--chromium/third_party/WebKit/Source/core/events/ErrorEvent.idl40
-rw-r--r--chromium/third_party/WebKit/Source/core/events/Event.cpp211
-rw-r--r--chromium/third_party/WebKit/Source/core/events/Event.h217
-rw-r--r--chromium/third_party/WebKit/Source/core/events/Event.idl77
-rw-r--r--chromium/third_party/WebKit/Source/core/events/EventAliases.in14
-rw-r--r--chromium/third_party/WebKit/Source/core/events/EventContext.cpp100
-rw-r--r--chromium/third_party/WebKit/Source/core/events/EventContext.h117
-rw-r--r--chromium/third_party/WebKit/Source/core/events/EventDispatchMediator.cpp55
-rw-r--r--chromium/third_party/WebKit/Source/core/events/EventDispatchMediator.h (renamed from chromium/third_party/WebKit/Source/core/dom/EventDispatchMediator.h)0
-rw-r--r--chromium/third_party/WebKit/Source/core/events/EventDispatcher.cpp226
-rw-r--r--chromium/third_party/WebKit/Source/core/events/EventDispatcher.h83
-rw-r--r--chromium/third_party/WebKit/Source/core/events/EventFactory.h (renamed from chromium/third_party/WebKit/Source/core/dom/EventFactory.h)0
-rw-r--r--chromium/third_party/WebKit/Source/core/events/EventListener.h65
-rw-r--r--chromium/third_party/WebKit/Source/core/events/EventListener.idl (renamed from chromium/third_party/WebKit/Source/core/dom/EventListener.idl)0
-rw-r--r--chromium/third_party/WebKit/Source/core/events/EventListenerMap.cpp272
-rw-r--r--chromium/third_party/WebKit/Source/core/events/EventListenerMap.h99
-rw-r--r--chromium/third_party/WebKit/Source/core/events/EventPath.cpp257
-rw-r--r--chromium/third_party/WebKit/Source/core/events/EventPath.h82
-rw-r--r--chromium/third_party/WebKit/Source/core/events/EventQueue.h (renamed from chromium/third_party/WebKit/Source/core/dom/EventQueue.h)0
-rw-r--r--chromium/third_party/WebKit/Source/core/events/EventRetargeter.cpp187
-rw-r--r--chromium/third_party/WebKit/Source/core/events/EventRetargeter.h64
-rw-r--r--chromium/third_party/WebKit/Source/core/events/EventSender.h113
-rw-r--r--chromium/third_party/WebKit/Source/core/events/EventTarget.cpp377
-rw-r--r--chromium/third_party/WebKit/Source/core/events/EventTarget.h253
-rw-r--r--chromium/third_party/WebKit/Source/core/events/EventTarget.idl31
-rw-r--r--chromium/third_party/WebKit/Source/core/events/EventTargetFactory.in50
-rw-r--r--chromium/third_party/WebKit/Source/core/events/EventTypeNames.in230
-rw-r--r--chromium/third_party/WebKit/Source/core/events/FocusEvent.cpp134
-rw-r--r--chromium/third_party/WebKit/Source/core/events/FocusEvent.h114
-rw-r--r--chromium/third_party/WebKit/Source/core/events/FocusEvent.idl30
-rw-r--r--chromium/third_party/WebKit/Source/core/events/GenericEventQueue.cpp124
-rw-r--r--chromium/third_party/WebKit/Source/core/events/GenericEventQueue.h65
-rw-r--r--chromium/third_party/WebKit/Source/core/events/GestureEvent.cpp137
-rw-r--r--chromium/third_party/WebKit/Source/core/events/GestureEvent.h78
-rw-r--r--chromium/third_party/WebKit/Source/core/events/HashChangeEvent.h99
-rw-r--r--chromium/third_party/WebKit/Source/core/events/HashChangeEvent.idl32
-rw-r--r--chromium/third_party/WebKit/Source/core/events/KeyboardEvent.cpp245
-rw-r--r--chromium/third_party/WebKit/Source/core/events/KeyboardEvent.h132
-rw-r--r--chromium/third_party/WebKit/Source/core/events/KeyboardEvent.idl54
-rw-r--r--chromium/third_party/WebKit/Source/core/events/MessageEvent.cpp188
-rw-r--r--chromium/third_party/WebKit/Source/core/events/MessageEvent.h144
-rw-r--r--chromium/third_party/WebKit/Source/core/events/MessageEvent.idl56
-rw-r--r--chromium/third_party/WebKit/Source/core/events/MouseEvent.cpp291
-rw-r--r--chromium/third_party/WebKit/Source/core/events/MouseEvent.h147
-rw-r--r--chromium/third_party/WebKit/Source/core/events/MouseEvent.idl62
-rw-r--r--chromium/third_party/WebKit/Source/core/events/MouseRelatedEvent.cpp230
-rw-r--r--chromium/third_party/WebKit/Source/core/events/MouseRelatedEvent.h91
-rw-r--r--chromium/third_party/WebKit/Source/core/events/MutationEvent.cpp74
-rw-r--r--chromium/third_party/WebKit/Source/core/events/MutationEvent.h80
-rw-r--r--chromium/third_party/WebKit/Source/core/events/MutationEvent.idl (renamed from chromium/third_party/WebKit/Source/core/dom/MutationEvent.idl)0
-rw-r--r--chromium/third_party/WebKit/Source/core/events/NavigatorEvents.cpp50
-rw-r--r--chromium/third_party/WebKit/Source/core/events/NavigatorEvents.h45
-rw-r--r--chromium/third_party/WebKit/Source/core/events/NavigatorEvents.idl34
-rw-r--r--chromium/third_party/WebKit/Source/core/events/OverflowEvent.cpp89
-rw-r--r--chromium/third_party/WebKit/Source/core/events/OverflowEvent.h82
-rw-r--r--chromium/third_party/WebKit/Source/core/events/OverflowEvent.idl37
-rw-r--r--chromium/third_party/WebKit/Source/core/events/PageTransitionEvent.cpp67
-rw-r--r--chromium/third_party/WebKit/Source/core/events/PageTransitionEvent.h70
-rw-r--r--chromium/third_party/WebKit/Source/core/events/PageTransitionEvent.idl31
-rw-r--r--chromium/third_party/WebKit/Source/core/events/PopStateEvent.cpp83
-rw-r--r--chromium/third_party/WebKit/Source/core/events/PopStateEvent.h67
-rw-r--r--chromium/third_party/WebKit/Source/core/events/PopStateEvent.idl31
-rw-r--r--chromium/third_party/WebKit/Source/core/events/ProgressEvent.cpp71
-rw-r--r--chromium/third_party/WebKit/Source/core/events/ProgressEvent.h74
-rw-r--r--chromium/third_party/WebKit/Source/core/events/ProgressEvent.idl33
-rw-r--r--chromium/third_party/WebKit/Source/core/events/RegisteredEventListener.h51
-rw-r--r--chromium/third_party/WebKit/Source/core/events/ResourceProgressEvent.cpp54
-rw-r--r--chromium/third_party/WebKit/Source/core/events/ResourceProgressEvent.h70
-rw-r--r--chromium/third_party/WebKit/Source/core/events/ResourceProgressEvent.idl (renamed from chromium/third_party/WebKit/Source/core/dom/ResourceProgressEvent.idl)0
-rw-r--r--chromium/third_party/WebKit/Source/core/events/ScopedEventQueue.cpp107
-rw-r--r--chromium/third_party/WebKit/Source/core/events/ScopedEventQueue.h (renamed from chromium/third_party/WebKit/Source/core/dom/ScopedEventQueue.h)0
-rw-r--r--chromium/third_party/WebKit/Source/core/events/SecurityPolicyViolationEvent.h111
-rw-r--r--chromium/third_party/WebKit/Source/core/events/SecurityPolicyViolationEvent.idl39
-rw-r--r--chromium/third_party/WebKit/Source/core/events/TextEvent.cpp109
-rw-r--r--chromium/third_party/WebKit/Source/core/events/TextEvent.h89
-rw-r--r--chromium/third_party/WebKit/Source/core/events/TextEvent.idl (renamed from chromium/third_party/WebKit/Source/core/dom/TextEvent.idl)0
-rw-r--r--chromium/third_party/WebKit/Source/core/events/TextEventInputType.h (renamed from chromium/third_party/WebKit/Source/core/dom/TextEventInputType.h)0
-rw-r--r--chromium/third_party/WebKit/Source/core/events/ThreadLocalEventNames.h44
-rw-r--r--chromium/third_party/WebKit/Source/core/events/TouchEvent.cpp113
-rw-r--r--chromium/third_party/WebKit/Source/core/events/TouchEvent.h100
-rw-r--r--chromium/third_party/WebKit/Source/core/events/TouchEvent.idl (renamed from chromium/third_party/WebKit/Source/core/dom/TouchEvent.idl)0
-rw-r--r--chromium/third_party/WebKit/Source/core/events/TransitionEvent.cpp87
-rw-r--r--chromium/third_party/WebKit/Source/core/events/TransitionEvent.h78
-rw-r--r--chromium/third_party/WebKit/Source/core/events/TransitionEvent.idl34
-rw-r--r--chromium/third_party/WebKit/Source/core/events/UIEvent.cpp117
-rw-r--r--chromium/third_party/WebKit/Source/core/events/UIEvent.h90
-rw-r--r--chromium/third_party/WebKit/Source/core/events/UIEvent.idl41
-rw-r--r--chromium/third_party/WebKit/Source/core/events/UIEventWithKeyState.cpp34
-rw-r--r--chromium/third_party/WebKit/Source/core/events/UIEventWithKeyState.h68
-rw-r--r--chromium/third_party/WebKit/Source/core/events/WebKitAnimationEvent.cpp80
-rw-r--r--chromium/third_party/WebKit/Source/core/events/WebKitAnimationEvent.h76
-rw-r--r--chromium/third_party/WebKit/Source/core/events/WebKitAnimationEvent.idl32
-rw-r--r--chromium/third_party/WebKit/Source/core/events/WheelEvent.cpp160
-rw-r--r--chromium/third_party/WebKit/Source/core/events/WheelEvent.h128
-rw-r--r--chromium/third_party/WebKit/Source/core/events/WheelEvent.idl55
-rw-r--r--chromium/third_party/WebKit/Source/core/events/WindowEventContext.cpp64
-rw-r--r--chromium/third_party/WebKit/Source/core/events/WindowEventContext.h (renamed from chromium/third_party/WebKit/Source/core/dom/WindowEventContext.h)0
-rw-r--r--chromium/third_party/WebKit/Source/core/features.gypi106
-rw-r--r--chromium/third_party/WebKit/Source/core/fetch/CSSStyleSheetResource.cpp8
-rw-r--r--chromium/third_party/WebKit/Source/core/fetch/CSSStyleSheetResource.h11
-rw-r--r--chromium/third_party/WebKit/Source/core/fetch/CachePolicy.h1
-rw-r--r--chromium/third_party/WebKit/Source/core/fetch/CrossOriginAccessControl.cpp34
-rw-r--r--chromium/third_party/WebKit/Source/core/fetch/CrossOriginAccessControl.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/fetch/DocumentResource.cpp4
-rw-r--r--chromium/third_party/WebKit/Source/core/fetch/DocumentResource.h7
-rw-r--r--chromium/third_party/WebKit/Source/core/fetch/FetchContext.cpp8
-rw-r--r--chromium/third_party/WebKit/Source/core/fetch/FetchContext.h8
-rw-r--r--chromium/third_party/WebKit/Source/core/fetch/FetchInitiatorTypeNames.in4
-rw-r--r--chromium/third_party/WebKit/Source/core/fetch/FetchRequest.cpp9
-rw-r--r--chromium/third_party/WebKit/Source/core/fetch/FetchRequest.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/fetch/FontResource.cpp69
-rw-r--r--chromium/third_party/WebKit/Source/core/fetch/FontResource.h27
-rw-r--r--chromium/third_party/WebKit/Source/core/fetch/ImageResource.cpp39
-rw-r--r--chromium/third_party/WebKit/Source/core/fetch/ImageResource.h24
-rw-r--r--chromium/third_party/WebKit/Source/core/fetch/ImageResourceTest.cpp43
-rw-r--r--chromium/third_party/WebKit/Source/core/fetch/MemoryCache.cpp55
-rw-r--r--chromium/third_party/WebKit/Source/core/fetch/MemoryCache.h38
-rw-r--r--chromium/third_party/WebKit/Source/core/fetch/MemoryCacheTest.cpp64
-rw-r--r--chromium/third_party/WebKit/Source/core/fetch/RawResource.cpp6
-rw-r--r--chromium/third_party/WebKit/Source/core/fetch/RawResource.h16
-rw-r--r--chromium/third_party/WebKit/Source/core/fetch/RawResourceTest.cpp89
-rw-r--r--chromium/third_party/WebKit/Source/core/fetch/Resource.cpp92
-rw-r--r--chromium/third_party/WebKit/Source/core/fetch/Resource.h70
-rw-r--r--chromium/third_party/WebKit/Source/core/fetch/ResourceClient.h1
-rw-r--r--chromium/third_party/WebKit/Source/core/fetch/ResourceFetcher.cpp367
-rw-r--r--chromium/third_party/WebKit/Source/core/fetch/ResourceFetcher.h22
-rw-r--r--chromium/third_party/WebKit/Source/core/fetch/ResourceFetcherTest.cpp4
-rw-r--r--chromium/third_party/WebKit/Source/core/fetch/ResourceLoadPriorityOptimizer.cpp79
-rw-r--r--chromium/third_party/WebKit/Source/core/fetch/ResourceLoadPriorityOptimizer.h69
-rw-r--r--chromium/third_party/WebKit/Source/core/fetch/ResourceLoader.cpp66
-rw-r--r--chromium/third_party/WebKit/Source/core/fetch/ResourceLoader.h23
-rw-r--r--chromium/third_party/WebKit/Source/core/fetch/ResourceLoaderHost.h5
-rw-r--r--chromium/third_party/WebKit/Source/core/fetch/ResourceLoaderOptions.h12
-rw-r--r--chromium/third_party/WebKit/Source/core/fetch/ResourceOwner.h116
-rw-r--r--chromium/third_party/WebKit/Source/core/fetch/ResourcePtr.h1
-rw-r--r--chromium/third_party/WebKit/Source/core/fetch/ScriptResource.cpp8
-rw-r--r--chromium/third_party/WebKit/Source/core/fetch/ScriptResource.h11
-rw-r--r--chromium/third_party/WebKit/Source/core/fetch/ShaderResource.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/fetch/ShaderResource.h8
-rw-r--r--chromium/third_party/WebKit/Source/core/fetch/StyleSheetResource.h51
-rw-r--r--chromium/third_party/WebKit/Source/core/fetch/StyleSheetResourceClient.h3
-rw-r--r--chromium/third_party/WebKit/Source/core/fetch/TextResourceDecoder.cpp271
-rw-r--r--chromium/third_party/WebKit/Source/core/fetch/TextResourceDecoder.h20
-rw-r--r--chromium/third_party/WebKit/Source/core/fetch/TextTrackResource.cpp53
-rw-r--r--chromium/third_party/WebKit/Source/core/fetch/TextTrackResource.h43
-rw-r--r--chromium/third_party/WebKit/Source/core/fetch/XSLStyleSheetResource.cpp6
-rw-r--r--chromium/third_party/WebKit/Source/core/fetch/XSLStyleSheetResource.h9
-rw-r--r--chromium/third_party/WebKit/Source/core/fileapi/Blob.cpp65
-rw-r--r--chromium/third_party/WebKit/Source/core/fileapi/Blob.h49
-rw-r--r--chromium/third_party/WebKit/Source/core/fileapi/Blob.idl6
-rw-r--r--chromium/third_party/WebKit/Source/core/fileapi/BlobBuilder.cpp33
-rw-r--r--chromium/third_party/WebKit/Source/core/fileapi/BlobBuilder.h12
-rw-r--r--chromium/third_party/WebKit/Source/core/fileapi/BlobRegistry.cpp326
-rw-r--r--chromium/third_party/WebKit/Source/core/fileapi/BlobRegistry.h67
-rw-r--r--chromium/third_party/WebKit/Source/core/fileapi/BlobURL.cpp79
-rw-r--r--chromium/third_party/WebKit/Source/core/fileapi/BlobURL.h66
-rw-r--r--chromium/third_party/WebKit/Source/core/fileapi/File.cpp49
-rw-r--r--chromium/third_party/WebKit/Source/core/fileapi/File.h42
-rw-r--r--chromium/third_party/WebKit/Source/core/fileapi/File.idl11
-rw-r--r--chromium/third_party/WebKit/Source/core/fileapi/FileError.cpp6
-rw-r--r--chromium/third_party/WebKit/Source/core/fileapi/FileList.cpp1
-rw-r--r--chromium/third_party/WebKit/Source/core/fileapi/FileReader.cpp203
-rw-r--r--chromium/third_party/WebKit/Source/core/fileapi/FileReader.h32
-rw-r--r--chromium/third_party/WebKit/Source/core/fileapi/FileReader.idl6
-rw-r--r--chromium/third_party/WebKit/Source/core/fileapi/FileReaderLoader.cpp182
-rw-r--r--chromium/third_party/WebKit/Source/core/fileapi/FileReaderLoader.h57
-rw-r--r--chromium/third_party/WebKit/Source/core/fileapi/FileReaderSync.cpp30
-rw-r--r--chromium/third_party/WebKit/Source/core/fileapi/FileReaderSync.h16
-rw-r--r--chromium/third_party/WebKit/Source/core/fileapi/FileReaderSync.idl8
-rw-r--r--chromium/third_party/WebKit/Source/core/fileapi/Stream.cpp27
-rw-r--r--chromium/third_party/WebKit/Source/core/fileapi/Stream.h22
-rw-r--r--chromium/third_party/WebKit/Source/core/fileapi/Stream.idl3
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/AdjustViewSizeOrNot.h (renamed from chromium/third_party/WebKit/Source/core/page/AdjustViewSizeOrNot.h)0
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/BarProp.cpp75
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/BarProp.h57
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/BarProp.idl (renamed from chromium/third_party/WebKit/Source/core/page/BarProp.idl)0
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/Console.cpp87
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/Console.h71
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/Console.idl (renamed from chromium/third_party/WebKit/Source/core/page/Console.idl)0
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/ConsoleBase.cpp185
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/ConsoleBase.h90
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/ConsoleBase.idl60
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/ConsoleTypes.h55
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/ContentSecurityPolicy.cpp2032
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/ContentSecurityPolicy.h171
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/ContentSecurityPolicyResponseHeaders.cpp41
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/ContentSecurityPolicyResponseHeaders.h (renamed from chromium/third_party/WebKit/Source/core/page/ContentSecurityPolicyResponseHeaders.h)0
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/DOMPoint.h66
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/DOMSecurityPolicy.cpp174
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/DOMSecurityPolicy.h72
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/DOMTimer.cpp200
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/DOMTimer.h82
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/DOMWindow.cpp1890
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/DOMWindow.h390
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/DOMWindowBase64.cpp78
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/DOMWindowBase64.h (renamed from chromium/third_party/WebKit/Source/core/page/DOMWindowBase64.h)0
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/DOMWindowEventHandlers.h53
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/DOMWindowLifecycleNotifier.cpp83
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/DOMWindowLifecycleNotifier.h59
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/DOMWindowLifecycleObserver.cpp58
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/DOMWindowLifecycleObserver.h54
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/DOMWindowProperty.cpp79
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/DOMWindowProperty.h (renamed from chromium/third_party/WebKit/Source/core/page/DOMWindowProperty.h)0
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/DOMWindowTimers.cpp67
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/DOMWindowTimers.h (renamed from chromium/third_party/WebKit/Source/core/page/DOMWindowTimers.h)0
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/Frame.cpp708
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/Frame.h338
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/FrameDestructionObserver.cpp66
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/FrameDestructionObserver.h (renamed from chromium/third_party/WebKit/Source/core/page/FrameDestructionObserver.h)0
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/FrameView.cpp3513
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/FrameView.h590
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/GraphicsLayerDebugInfo.cpp46
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/GraphicsLayerDebugInfo.h50
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/History.cpp140
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/History.h72
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/History.idl36
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/ImageBitmap.cpp203
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/ImageBitmap.h72
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/ImageBitmap.idl9
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/ImageBitmapTest.cpp209
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/Location.cpp252
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/Location.h85
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/Location.idl59
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/Navigator.cpp159
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/Navigator.h71
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/Navigator.idl (renamed from chromium/third_party/WebKit/Source/core/page/Navigator.idl)0
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/NavigatorBase.h (renamed from chromium/third_party/WebKit/Source/core/page/NavigatorBase.h)0
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/NavigatorID.cpp92
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/NavigatorID.h (renamed from chromium/third_party/WebKit/Source/core/page/NavigatorID.h)0
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/NavigatorID.idl (renamed from chromium/third_party/WebKit/Source/core/page/NavigatorID.idl)0
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/NavigatorOnLine.h48
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/NavigatorOnLine.idl (renamed from chromium/third_party/WebKit/Source/core/page/NavigatorOnLine.idl)0
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/Screen.cpp123
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/Screen.h61
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/Screen.idl (renamed from chromium/third_party/WebKit/Source/core/page/Screen.idl)0
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/SecurityPolicy.idl (renamed from chromium/third_party/WebKit/Source/core/page/SecurityPolicy.idl)0
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/Settings.cpp167
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/Settings.h115
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/Settings.in289
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/SettingsDelegate.cpp51
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/SettingsDelegate.h73
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/SmartClip.cpp294
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/SmartClip.h86
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/SuspendableTimer.cpp81
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/SuspendableTimer.h59
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/UseCounter.cpp732
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/UseCounter.h338
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/WebKitPoint.idl34
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/Window.idl243
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/WindowBase64.idl34
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/WindowEventHandlers.idl47
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/WindowTimers.idl (renamed from chromium/third_party/WebKit/Source/core/page/WindowTimers.idl)0
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/animation/AnimationBase.cpp585
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/animation/AnimationBase.h228
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/animation/AnimationController.cpp542
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/animation/AnimationController.h104
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/animation/AnimationControllerPrivate.h140
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/animation/CSSPropertyAnimation.cpp1153
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/animation/CSSPropertyAnimation.h (renamed from chromium/third_party/WebKit/Source/core/page/animation/CSSPropertyAnimation.h)0
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/animation/CompositeAnimation.cpp510
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/animation/CompositeAnimation.h96
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/animation/ImplicitAnimation.cpp283
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/animation/ImplicitAnimation.h98
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/animation/KeyframeAnimation.cpp455
-rw-r--r--chromium/third_party/WebKit/Source/core/frame/animation/KeyframeAnimation.h102
-rw-r--r--chromium/third_party/WebKit/Source/core/history/BackForwardClient.h48
-rw-r--r--chromium/third_party/WebKit/Source/core/history/BackForwardController.cpp94
-rw-r--r--chromium/third_party/WebKit/Source/core/history/BackForwardController.h73
-rw-r--r--chromium/third_party/WebKit/Source/core/history/HistoryItem.cpp250
-rw-r--r--chromium/third_party/WebKit/Source/core/history/HistoryItem.h67
-rw-r--r--chromium/third_party/WebKit/Source/core/html/ClassList.cpp1
-rw-r--r--chromium/third_party/WebKit/Source/core/html/DOMURL.cpp69
-rw-r--r--chromium/third_party/WebKit/Source/core/html/DOMURL.h53
-rw-r--r--chromium/third_party/WebKit/Source/core/html/FormAssociatedElement.cpp26
-rw-r--r--chromium/third_party/WebKit/Source/core/html/FormAssociatedElement.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/html/FormData.idl2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/FormDataList.cpp101
-rw-r--r--chromium/third_party/WebKit/Source/core/html/FormDataList.h6
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLAllCollection.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLAllCollection.idl7
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLAnchorElement.cpp307
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLAnchorElement.h41
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLAnchorElement.idl15
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLAppletElement.cpp108
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLAppletElement.h14
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLAppletElement.idl11
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLAreaElement.cpp13
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLAreaElement.h12
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLAreaElement.idl12
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLAttributeNames.in11
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLAudioElement.cpp17
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLAudioElement.h8
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLAudioElement.idl2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLBDIElement.h8
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLBRElement.cpp12
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLBRElement.h3
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLBaseElement.cpp9
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLBaseElement.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLBaseElement.idl2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLBaseFontElement.cpp44
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLBaseFontElement.h40
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLBaseFontElement.idl24
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLBodyElement.cpp139
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLBodyElement.h32
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLBodyElement.idl41
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLButtonElement.cpp31
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLButtonElement.h8
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLButtonElement.idl10
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLCanvasElement.cpp212
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLCanvasElement.h37
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLCanvasElement.idl2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLCollection.cpp93
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLCollection.h6
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLCollection.idl6
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLContentElement.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLDListElement.cpp9
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLDListElement.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLDataListElement.cpp25
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLDataListElement.h12
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLDataListElement.idl2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLDetailsElement.cpp25
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLDetailsElement.h12
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLDialogElement.cpp152
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLDialogElement.h25
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLDialogElement.idl2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLDimension.cpp1
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLDimensionTest.cpp227
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLDirectoryElement.cpp9
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLDirectoryElement.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLDivElement.cpp12
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLDivElement.h9
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLDivElement.idl4
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLDocument.cpp136
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLDocument.h64
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLDocument.idl30
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLElement.cpp444
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLElement.h29
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLElement.idl35
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLEmbedElement.cpp64
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLEmbedElement.h15
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLEmbedElement.idl25
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLFieldSetElement.cpp23
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLFieldSetElement.h12
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLFieldSetElement.idl2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLFontElement.cpp9
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLFontElement.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLFontElement.idl3
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLFormControlElement.cpp128
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLFormControlElement.h48
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLFormControlElementWithState.cpp4
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLFormControlElementWithState.h6
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLFormControlsCollection.h6
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLFormControlsCollection.idl4
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLFormElement.cpp148
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLFormElement.h29
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLFormElement.idl18
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLFrameElement.cpp9
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLFrameElement.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLFrameElement.idl16
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLFrameElementBase.cpp17
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLFrameElementBase.h9
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLFrameOwnerElement.cpp36
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLFrameOwnerElement.h26
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLFrameSetElement.cpp58
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLFrameSetElement.h21
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLFrameSetElement.idl31
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLHRElement.cpp12
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLHRElement.h3
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLHRElement.idl2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLHeadElement.cpp12
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLHeadElement.h9
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLHeadElement.idl3
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLHeadingElement.idl1
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLHtmlElement.cpp16
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLHtmlElement.h9
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLHtmlElement.idl3
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLIFrameElement.cpp11
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLIFrameElement.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLIFrameElement.idl17
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLImageElement.cpp64
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLImageElement.h27
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLImageElement.idl22
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLImageLoader.cpp8
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLImport.cpp93
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLImport.h125
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLImportChild.cpp174
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLImportChild.h97
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLImportChildClient.h45
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLImportLoader.cpp166
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLImportLoader.h42
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLImportLoaderClient.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLImportResourceOwner.cpp60
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLImportResourceOwner.h64
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLImportsController.cpp53
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLImportsController.h27
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLInputElement.cpp337
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLInputElement.h57
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLInputElement.idl51
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLKeygenElement.cpp17
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLKeygenElement.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLKeygenElement.idl3
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLLIElement.cpp18
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLLIElement.h3
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLLIElement.idl1
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLLabelElement.cpp25
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLLabelElement.h17
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLLabelElement.idl3
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLLegendElement.cpp15
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLLegendElement.h13
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLLegendElement.idl1
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLLinkElement.cpp83
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLLinkElement.h27
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLLinkElement.idl7
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLMapElement.cpp14
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLMapElement.h9
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLMapElement.idl1
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLMarqueeElement.cpp40
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLMarqueeElement.h15
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLMarqueeElement.idl6
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLMediaElement.cpp829
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLMediaElement.h174
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLMediaElement.idl141
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLMediaSource.h7
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLMenuElement.cpp9
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLMenuElement.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLMetaElement-in.cpp489
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLMetaElement.cpp110
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLMetaElement.h43
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLMetaElement.idl1
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLMeterElement.cpp64
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLMeterElement.h12
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLMeterElement.idl12
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLModElement.idl3
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLNameCollection.cpp18
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLNameCollection.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLOListElement.cpp14
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLOListElement.h9
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLOListElement.idl1
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLObjectElement.cpp155
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLObjectElement.h45
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLObjectElement.idl15
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLOptGroupElement.cpp11
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLOptGroupElement.h11
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLOptGroupElement.idl1
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLOptionElement.cpp47
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLOptionElement.h25
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLOptionElement.idl4
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLOptionsCollection.cpp29
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLOptionsCollection.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLOptionsCollection.idl6
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLOutputElement.cpp12
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLOutputElement.h6
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLOutputElement.idl8
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLParagraphElement.cpp12
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLParagraphElement.h3
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLParagraphElement.idl1
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLParamElement.cpp13
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLParamElement.h14
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLParamElement.idl1
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLPlugInElement.cpp390
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLPlugInElement.h126
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLPlugInImageElement.cpp330
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLPlugInImageElement.h142
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLProgressElement.cpp37
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLProgressElement.h12
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLProgressElement.idl4
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLQuoteElement.idl2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLScriptElement.cpp19
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLScriptElement.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLScriptElement.idl6
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLSelectElement.cpp130
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLSelectElement.h16
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLSelectElement.idl6
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLSelectElementWin.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLShadowElement.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLSourceElement.cpp35
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLSourceElement.h21
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLSourceElement.idl4
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLSpanElement.cpp9
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLSpanElement.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLStyleElement.cpp24
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLStyleElement.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLStyleElement.idl3
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLSummaryElement.cpp27
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLSummaryElement.h12
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLTableCaptionElement.cpp9
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLTableCaptionElement.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLTableCaptionElement.idl1
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLTableCellElement.cpp12
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLTableCellElement.h22
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLTableCellElement.idl5
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLTableColElement.cpp4
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLTableColElement.h9
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLTableColElement.idl1
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLTableElement.cpp75
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLTableElement.h13
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLTableElement.idl13
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLTableRowElement.cpp31
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLTableRowElement.h12
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLTableRowElement.idl3
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLTableRowsCollection.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLTableSectionElement.cpp32
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLTableSectionElement.h23
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLTableSectionElement.idl1
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLTagNames.in11
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLTemplateElement.cpp14
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLTemplateElement.h18
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLTemplateElement.idl2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLTextAreaElement.cpp65
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLTextAreaElement.h17
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLTextAreaElement.idl8
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLTextFormControlElement.cpp43
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLTextFormControlElement.h9
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLTitleElement.cpp9
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLTitleElement.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLTitleElement.idl3
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLTrackElement.cpp126
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLTrackElement.h42
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLTrackElement.idl8
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLUListElement.cpp12
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLUListElement.h3
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLUListElement.idl1
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLUnknownElement.h7
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLVideoElement.cpp41
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLVideoElement.h37
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLVideoElement.idl20
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLViewSourceDocument.cpp29
-rw-r--r--chromium/third_party/WebKit/Source/core/html/HTMLViewSourceDocument.h1
-rw-r--r--chromium/third_party/WebKit/Source/core/html/ImageData.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/ImageData.idl2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/ImageDocument.cpp66
-rw-r--r--chromium/third_party/WebKit/Source/core/html/ImageDocument.h15
-rw-r--r--chromium/third_party/WebKit/Source/core/html/LabelableElement.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/LabelableElement.h7
-rw-r--r--chromium/third_party/WebKit/Source/core/html/LabelsNodeList.cpp4
-rw-r--r--chromium/third_party/WebKit/Source/core/html/LabelsNodeList.h11
-rw-r--r--chromium/third_party/WebKit/Source/core/html/LinkImport.cpp23
-rw-r--r--chromium/third_party/WebKit/Source/core/html/LinkImport.h14
-rw-r--r--chromium/third_party/WebKit/Source/core/html/LinkRelAttribute.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/LinkRelAttribute.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/html/LinkRelAttributeTest.cpp88
-rw-r--r--chromium/third_party/WebKit/Source/core/html/LinkResource.cpp16
-rw-r--r--chromium/third_party/WebKit/Source/core/html/LinkResource.h13
-rw-r--r--chromium/third_party/WebKit/Source/core/html/MediaController.cpp51
-rw-r--r--chromium/third_party/WebKit/Source/core/html/MediaController.h32
-rw-r--r--chromium/third_party/WebKit/Source/core/html/MediaController.idl8
-rw-r--r--chromium/third_party/WebKit/Source/core/html/MediaDocument.cpp21
-rw-r--r--chromium/third_party/WebKit/Source/core/html/MediaError.idl14
-rw-r--r--chromium/third_party/WebKit/Source/core/html/MediaFragmentURIParser.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/MediaFragmentURIParser.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/MediaKeyError.idl4
-rw-r--r--chromium/third_party/WebKit/Source/core/html/MediaKeyEvent.cpp4
-rw-r--r--chromium/third_party/WebKit/Source/core/html/MediaKeyEvent.h3
-rw-r--r--chromium/third_party/WebKit/Source/core/html/MediaKeyEvent.idl6
-rw-r--r--chromium/third_party/WebKit/Source/core/html/PluginDocument.cpp20
-rw-r--r--chromium/third_party/WebKit/Source/core/html/PluginDocument.h21
-rw-r--r--chromium/third_party/WebKit/Source/core/html/PublicURLManager.cpp6
-rw-r--r--chromium/third_party/WebKit/Source/core/html/PublicURLManager.h6
-rw-r--r--chromium/third_party/WebKit/Source/core/html/RadioNodeList.cpp6
-rw-r--r--chromium/third_party/WebKit/Source/core/html/RadioNodeList.h13
-rw-r--r--chromium/third_party/WebKit/Source/core/html/TimeRanges.cpp19
-rw-r--r--chromium/third_party/WebKit/Source/core/html/TimeRanges.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/TimeRanges.idl2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/TimeRangesTest.cpp10
-rw-r--r--chromium/third_party/WebKit/Source/core/html/URL.idl34
-rw-r--r--chromium/third_party/WebKit/Source/core/html/VoidCallback.h6
-rw-r--r--chromium/third_party/WebKit/Source/core/html/VoidCallback.idl2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/canvas/ANGLEInstancedArrays.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/canvas/ANGLEInstancedArrays.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/canvas/ArrayBufferView.idl2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/canvas/Canvas2DContextAttributes.idl3
-rw-r--r--chromium/third_party/WebKit/Source/core/html/canvas/CanvasGradient.cpp6
-rw-r--r--chromium/third_party/WebKit/Source/core/html/canvas/CanvasGradient.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/canvas/CanvasPathMethods.cpp29
-rw-r--r--chromium/third_party/WebKit/Source/core/html/canvas/CanvasPathMethods.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/canvas/CanvasPattern.cpp4
-rw-r--r--chromium/third_party/WebKit/Source/core/html/canvas/CanvasPattern.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/canvas/CanvasRenderingContext.cpp3
-rw-r--r--chromium/third_party/WebKit/Source/core/html/canvas/CanvasRenderingContext.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/html/canvas/CanvasRenderingContext.idl2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/canvas/CanvasRenderingContext2D.cpp292
-rw-r--r--chromium/third_party/WebKit/Source/core/html/canvas/CanvasRenderingContext2D.h45
-rw-r--r--chromium/third_party/WebKit/Source/core/html/canvas/CanvasRenderingContext2D.idl17
-rw-r--r--chromium/third_party/WebKit/Source/core/html/canvas/CanvasStyle.cpp3
-rw-r--r--chromium/third_party/WebKit/Source/core/html/canvas/CanvasStyle.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/canvas/CheckedInt.h819
-rw-r--r--chromium/third_party/WebKit/Source/core/html/canvas/DataView.cpp74
-rw-r--r--chromium/third_party/WebKit/Source/core/html/canvas/DataView.idl4
-rw-r--r--chromium/third_party/WebKit/Source/core/html/canvas/EXTFragDepth.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/canvas/EXTTextureFilterAnisotropic.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/canvas/OESElementIndexUint.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/canvas/OESStandardDerivatives.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/canvas/OESTextureFloat.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/canvas/OESTextureFloatLinear.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/canvas/OESTextureHalfFloat.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/canvas/OESTextureHalfFloatLinear.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/canvas/OESVertexArrayObject.cpp4
-rw-r--r--chromium/third_party/WebKit/Source/core/html/canvas/OESVertexArrayObject.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/canvas/Path.idl2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/canvas/WebGLActiveInfo.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/canvas/WebGLBuffer.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/canvas/WebGLCompressedTextureATC.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/canvas/WebGLCompressedTexturePVRTC.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/canvas/WebGLCompressedTextureS3TC.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/canvas/WebGLContextAttributes.cpp10
-rw-r--r--chromium/third_party/WebKit/Source/core/html/canvas/WebGLContextAttributes.h7
-rw-r--r--chromium/third_party/WebKit/Source/core/html/canvas/WebGLContextAttributes.idl1
-rw-r--r--chromium/third_party/WebKit/Source/core/html/canvas/WebGLContextEvent.cpp4
-rw-r--r--chromium/third_party/WebKit/Source/core/html/canvas/WebGLContextEvent.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/canvas/WebGLContextEvent.idl2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/canvas/WebGLContextGroup.cpp1
-rw-r--r--chromium/third_party/WebKit/Source/core/html/canvas/WebGLContextGroup.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/html/canvas/WebGLDebugShaders.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/canvas/WebGLDepthTexture.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/canvas/WebGLDrawBuffers.cpp50
-rw-r--r--chromium/third_party/WebKit/Source/core/html/canvas/WebGLFramebuffer.cpp146
-rw-r--r--chromium/third_party/WebKit/Source/core/html/canvas/WebGLGetInfo.cpp14
-rw-r--r--chromium/third_party/WebKit/Source/core/html/canvas/WebGLGetInfo.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/html/canvas/WebGLObject.h3
-rw-r--r--chromium/third_party/WebKit/Source/core/html/canvas/WebGLProgram.cpp16
-rw-r--r--chromium/third_party/WebKit/Source/core/html/canvas/WebGLRenderbuffer.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/canvas/WebGLRenderingContext.cpp1659
-rw-r--r--chromium/third_party/WebKit/Source/core/html/canvas/WebGLRenderingContext.h28
-rw-r--r--chromium/third_party/WebKit/Source/core/html/canvas/WebGLShaderPrecisionFormat.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/canvas/WebGLTexture.cpp78
-rw-r--r--chromium/third_party/WebKit/Source/core/html/canvas/WebGLUniformLocation.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/html/canvas/WebGLVertexArrayObjectOES.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/canvas/WebGLVertexArrayObjectOES.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/BaseButtonInputType.cpp32
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/BaseButtonInputType.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/BaseCheckableInputType.cpp16
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/BaseCheckableInputType.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/BaseChooserOnlyDateAndTimeInputType.cpp31
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/BaseChooserOnlyDateAndTimeInputType.h9
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/BaseClickableWithKeyInputType.cpp14
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/BaseClickableWithKeyInputType.h8
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/BaseDateAndTimeInputType.cpp31
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/BaseDateAndTimeInputType.h7
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/BaseMultipleFieldsDateAndTimeInputType.cpp123
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/BaseMultipleFieldsDateAndTimeInputType.h5
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/BaseTextInputType.cpp8
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/BaseTextInputType.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/ButtonInputType.cpp6
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/ButtonInputType.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/CheckboxInputType.cpp26
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/CheckboxInputType.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/ColorInputType.cpp63
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/ColorInputType.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/DateInputType.cpp37
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/DateInputType.h5
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/DateTimeLocalInputType.cpp39
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/DateTimeLocalInputType.h5
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/EmailInputType.cpp42
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/EmailInputType.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/FileInputType.cpp97
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/FileInputType.h6
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/FormController.cpp27
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/HiddenInputType.cpp16
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/HiddenInputType.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/ImageInputType.cpp67
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/ImageInputType.h9
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/InputType.cpp232
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/InputType.h28
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/InputTypeNames.cpp172
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/InputTypeNames.h59
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/InputTypeNames.in25
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/InputTypeView.cpp29
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/InputTypeView.h17
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/MonthInputType.cpp29
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/MonthInputType.h5
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/NumberInputType.cpp92
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/NumberInputType.h7
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/PasswordInputType.cpp51
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/PasswordInputType.h11
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/RadioInputType.cpp50
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/RadioInputType.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/RangeInputType.cpp88
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/RangeInputType.h5
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/ResetInputType.cpp16
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/ResetInputType.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/SearchInputType.cpp53
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/SearchInputType.h8
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/StepRange.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/SubmitInputType.cpp18
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/SubmitInputType.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/TelephoneInputType.cpp8
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/TelephoneInputType.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/TextFieldInputType.cpp251
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/TextFieldInputType.h13
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/TextInputType.cpp19
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/TextInputType.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/TimeInputType.cpp31
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/TimeInputType.h5
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/TypeAhead.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/URLInputType.cpp14
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/URLInputType.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/WeekInputType.cpp29
-rw-r--r--chromium/third_party/WebKit/Source/core/html/forms/WeekInputType.h5
-rw-r--r--chromium/third_party/WebKit/Source/core/html/ime/Composition.cpp38
-rw-r--r--chromium/third_party/WebKit/Source/core/html/ime/Composition.h30
-rw-r--r--chromium/third_party/WebKit/Source/core/html/ime/InputMethodContext.cpp127
-rw-r--r--chromium/third_party/WebKit/Source/core/html/ime/InputMethodContext.h39
-rw-r--r--chromium/third_party/WebKit/Source/core/html/ime/InputMethodContext.idl12
-rw-r--r--chromium/third_party/WebKit/Source/core/html/parser/AtomicHTMLToken.h16
-rw-r--r--chromium/third_party/WebKit/Source/core/html/parser/BackgroundHTMLInputStream.cpp18
-rw-r--r--chromium/third_party/WebKit/Source/core/html/parser/BackgroundHTMLInputStream.h14
-rw-r--r--chromium/third_party/WebKit/Source/core/html/parser/BackgroundHTMLParser.cpp24
-rw-r--r--chromium/third_party/WebKit/Source/core/html/parser/CSSPreloadScanner.cpp16
-rw-r--r--chromium/third_party/WebKit/Source/core/html/parser/CSSPreloadScanner.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/parser/CompactHTMLToken.cpp12
-rw-r--r--chromium/third_party/WebKit/Source/core/html/parser/CompactHTMLToken.h11
-rw-r--r--chromium/third_party/WebKit/Source/core/html/parser/HTMLConstructionSite.cpp224
-rw-r--r--chromium/third_party/WebKit/Source/core/html/parser/HTMLConstructionSite.h82
-rw-r--r--chromium/third_party/WebKit/Source/core/html/parser/HTMLDocumentParser.cpp26
-rw-r--r--chromium/third_party/WebKit/Source/core/html/parser/HTMLDocumentParser.h5
-rw-r--r--chromium/third_party/WebKit/Source/core/html/parser/HTMLElementStack.cpp1
-rw-r--r--chromium/third_party/WebKit/Source/core/html/parser/HTMLEntityParser.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/parser/HTMLIdentifier.cpp125
-rw-r--r--chromium/third_party/WebKit/Source/core/html/parser/HTMLIdentifier.h82
-rw-r--r--chromium/third_party/WebKit/Source/core/html/parser/HTMLInputStream.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/parser/HTMLMetaCharsetParser.cpp1
-rw-r--r--chromium/third_party/WebKit/Source/core/html/parser/HTMLMetaCharsetParser.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/parser/HTMLParserIdioms.cpp40
-rw-r--r--chromium/third_party/WebKit/Source/core/html/parser/HTMLParserIdioms.h40
-rw-r--r--chromium/third_party/WebKit/Source/core/html/parser/HTMLParserOptions.cpp8
-rw-r--r--chromium/third_party/WebKit/Source/core/html/parser/HTMLParserScheduler.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/parser/HTMLParserScheduler.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/parser/HTMLParserThread.cpp6
-rw-r--r--chromium/third_party/WebKit/Source/core/html/parser/HTMLParserThread.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/parser/HTMLPreloadScanner.cpp56
-rw-r--r--chromium/third_party/WebKit/Source/core/html/parser/HTMLPreloadScanner.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/parser/HTMLResourcePreloader.cpp9
-rw-r--r--chromium/third_party/WebKit/Source/core/html/parser/HTMLResourcePreloader.h17
-rw-r--r--chromium/third_party/WebKit/Source/core/html/parser/HTMLScriptRunner.cpp12
-rw-r--r--chromium/third_party/WebKit/Source/core/html/parser/HTMLSourceTracker.cpp13
-rw-r--r--chromium/third_party/WebKit/Source/core/html/parser/HTMLSourceTracker.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/parser/HTMLSrcsetParser.cpp13
-rw-r--r--chromium/third_party/WebKit/Source/core/html/parser/HTMLSrcsetParser.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/parser/HTMLTokenizer.cpp3
-rw-r--r--chromium/third_party/WebKit/Source/core/html/parser/HTMLTokenizer.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/parser/HTMLTreeBuilder.cpp123
-rw-r--r--chromium/third_party/WebKit/Source/core/html/parser/HTMLTreeBuilder.h9
-rw-r--r--chromium/third_party/WebKit/Source/core/html/parser/HTMLTreeBuilderSimulator.cpp120
-rw-r--r--chromium/third_party/WebKit/Source/core/html/parser/HTMLViewSourceParser.cpp1
-rw-r--r--chromium/third_party/WebKit/Source/core/html/parser/InputStreamPreprocessor.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/parser/MathMLAttributeNames.in (renamed from chromium/third_party/WebKit/Source/core/mathml/mathattrs.in)0
-rw-r--r--chromium/third_party/WebKit/Source/core/html/parser/MathMLTagNames.in12
-rw-r--r--chromium/third_party/WebKit/Source/core/html/parser/XSSAuditor.cpp91
-rw-r--r--chromium/third_party/WebKit/Source/core/html/parser/XSSAuditor.h12
-rw-r--r--chromium/third_party/WebKit/Source/core/html/parser/XSSAuditorDelegate.cpp57
-rw-r--r--chromium/third_party/WebKit/Source/core/html/parser/XSSAuditorDelegate.h5
-rw-r--r--chromium/third_party/WebKit/Source/core/html/shadow/ClearButtonElement.cpp20
-rw-r--r--chromium/third_party/WebKit/Source/core/html/shadow/ClearButtonElement.h6
-rw-r--r--chromium/third_party/WebKit/Source/core/html/shadow/DateTimeEditElement.cpp18
-rw-r--r--chromium/third_party/WebKit/Source/core/html/shadow/DateTimeEditElement.h8
-rw-r--r--chromium/third_party/WebKit/Source/core/html/shadow/DateTimeFieldElement.cpp24
-rw-r--r--chromium/third_party/WebKit/Source/core/html/shadow/DateTimeFieldElements.cpp31
-rw-r--r--chromium/third_party/WebKit/Source/core/html/shadow/DateTimeNumericFieldElement.cpp18
-rw-r--r--chromium/third_party/WebKit/Source/core/html/shadow/DateTimeNumericFieldElement.h1
-rw-r--r--chromium/third_party/WebKit/Source/core/html/shadow/DateTimeSymbolicFieldElement.cpp8
-rw-r--r--chromium/third_party/WebKit/Source/core/html/shadow/DetailsMarkerControl.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/shadow/DetailsMarkerControl.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/shadow/HTMLContentElement.cpp22
-rw-r--r--chromium/third_party/WebKit/Source/core/html/shadow/HTMLContentElement.h15
-rw-r--r--chromium/third_party/WebKit/Source/core/html/shadow/HTMLContentElement.idl2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/shadow/HTMLShadowElement.cpp11
-rw-r--r--chromium/third_party/WebKit/Source/core/html/shadow/HTMLShadowElement.h21
-rw-r--r--chromium/third_party/WebKit/Source/core/html/shadow/HTMLShadowElement.idl1
-rw-r--r--chromium/third_party/WebKit/Source/core/html/shadow/MediaControlElementTypes.cpp16
-rw-r--r--chromium/third_party/WebKit/Source/core/html/shadow/MediaControlElementTypes.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/shadow/MediaControlElements.cpp136
-rw-r--r--chromium/third_party/WebKit/Source/core/html/shadow/MediaControlElements.h28
-rw-r--r--chromium/third_party/WebKit/Source/core/html/shadow/MediaControls.cpp10
-rw-r--r--chromium/third_party/WebKit/Source/core/html/shadow/MediaControls.h15
-rw-r--r--chromium/third_party/WebKit/Source/core/html/shadow/MediaControlsChromium.cpp42
-rw-r--r--chromium/third_party/WebKit/Source/core/html/shadow/MediaControlsChromiumAndroid.cpp10
-rw-r--r--chromium/third_party/WebKit/Source/core/html/shadow/MeterShadowElement.cpp6
-rw-r--r--chromium/third_party/WebKit/Source/core/html/shadow/MeterShadowElement.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/shadow/PasswordGeneratorButtonElement.cpp63
-rw-r--r--chromium/third_party/WebKit/Source/core/html/shadow/PasswordGeneratorButtonElement.h5
-rw-r--r--chromium/third_party/WebKit/Source/core/html/shadow/PickerIndicatorElement.cpp14
-rw-r--r--chromium/third_party/WebKit/Source/core/html/shadow/PickerIndicatorElement.h13
-rw-r--r--chromium/third_party/WebKit/Source/core/html/shadow/ProgressShadowElement.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/shadow/ShadowElementNames.cpp18
-rw-r--r--chromium/third_party/WebKit/Source/core/html/shadow/ShadowElementNames.h3
-rw-r--r--chromium/third_party/WebKit/Source/core/html/shadow/SliderThumbElement.cpp46
-rw-r--r--chromium/third_party/WebKit/Source/core/html/shadow/SliderThumbElement.h6
-rw-r--r--chromium/third_party/WebKit/Source/core/html/shadow/SpinButtonElement.cpp28
-rw-r--r--chromium/third_party/WebKit/Source/core/html/shadow/SpinButtonElement.h22
-rw-r--r--chromium/third_party/WebKit/Source/core/html/shadow/TextControlInnerElements.cpp73
-rw-r--r--chromium/third_party/WebKit/Source/core/html/shadow/TextControlInnerElements.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/html/track/InbandTextTrack.cpp153
-rw-r--r--chromium/third_party/WebKit/Source/core/html/track/InbandTextTrack.h24
-rw-r--r--chromium/third_party/WebKit/Source/core/html/track/LoadableTextTrack.cpp26
-rw-r--r--chromium/third_party/WebKit/Source/core/html/track/LoadableTextTrack.h27
-rw-r--r--chromium/third_party/WebKit/Source/core/html/track/TextTrack.cpp129
-rw-r--r--chromium/third_party/WebKit/Source/core/html/track/TextTrack.h55
-rw-r--r--chromium/third_party/WebKit/Source/core/html/track/TextTrack.idl20
-rw-r--r--chromium/third_party/WebKit/Source/core/html/track/TextTrackCue.cpp1042
-rw-r--r--chromium/third_party/WebKit/Source/core/html/track/TextTrackCue.h205
-rw-r--r--chromium/third_party/WebKit/Source/core/html/track/TextTrackCue.idl23
-rw-r--r--chromium/third_party/WebKit/Source/core/html/track/TextTrackCueGeneric.cpp168
-rw-r--r--chromium/third_party/WebKit/Source/core/html/track/TextTrackCueGeneric.h93
-rw-r--r--chromium/third_party/WebKit/Source/core/html/track/TextTrackCueList.idl2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/track/TextTrackList.cpp89
-rw-r--r--chromium/third_party/WebKit/Source/core/html/track/TextTrackList.h42
-rw-r--r--chromium/third_party/WebKit/Source/core/html/track/TextTrackList.idl7
-rw-r--r--chromium/third_party/WebKit/Source/core/html/track/TextTrackRegion.cpp510
-rw-r--r--chromium/third_party/WebKit/Source/core/html/track/TextTrackRegion.h165
-rw-r--r--chromium/third_party/WebKit/Source/core/html/track/TextTrackRegion.idl43
-rw-r--r--chromium/third_party/WebKit/Source/core/html/track/TextTrackRegionList.cpp86
-rw-r--r--chromium/third_party/WebKit/Source/core/html/track/TextTrackRegionList.h65
-rw-r--r--chromium/third_party/WebKit/Source/core/html/track/TextTrackRegionList.idl35
-rw-r--r--chromium/third_party/WebKit/Source/core/html/track/TrackBase.cpp63
-rw-r--r--chromium/third_party/WebKit/Source/core/html/track/TrackBase.h28
-rw-r--r--chromium/third_party/WebKit/Source/core/html/track/TrackEvent.cpp4
-rw-r--r--chromium/third_party/WebKit/Source/core/html/track/TrackEvent.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/html/track/TrackEvent.idl6
-rw-r--r--chromium/third_party/WebKit/Source/core/html/track/WebVTTElement.cpp121
-rw-r--r--chromium/third_party/WebKit/Source/core/html/track/WebVTTElement.h93
-rw-r--r--chromium/third_party/WebKit/Source/core/html/track/WebVTTParser.cpp575
-rw-r--r--chromium/third_party/WebKit/Source/core/html/track/WebVTTParser.h175
-rw-r--r--chromium/third_party/WebKit/Source/core/html/track/WebVTTToken.h209
-rw-r--r--chromium/third_party/WebKit/Source/core/html/track/WebVTTTokenizer.cpp228
-rw-r--r--chromium/third_party/WebKit/Source/core/html/track/WebVTTTokenizer.h115
-rw-r--r--chromium/third_party/WebKit/Source/core/html/track/vtt/BufferedLineReader.cpp104
-rw-r--r--chromium/third_party/WebKit/Source/core/html/track/vtt/BufferedLineReader.h88
-rw-r--r--chromium/third_party/WebKit/Source/core/html/track/vtt/BufferedLineReaderTest.cpp292
-rw-r--r--chromium/third_party/WebKit/Source/core/html/track/vtt/VTTCue.cpp1110
-rw-r--r--chromium/third_party/WebKit/Source/core/html/track/vtt/VTTCue.h197
-rw-r--r--chromium/third_party/WebKit/Source/core/html/track/vtt/VTTCue.idl44
-rw-r--r--chromium/third_party/WebKit/Source/core/html/track/vtt/VTTElement.cpp121
-rw-r--r--chromium/third_party/WebKit/Source/core/html/track/vtt/VTTElement.h85
-rw-r--r--chromium/third_party/WebKit/Source/core/html/track/vtt/VTTParser.cpp627
-rw-r--r--chromium/third_party/WebKit/Source/core/html/track/vtt/VTTParser.h155
-rw-r--r--chromium/third_party/WebKit/Source/core/html/track/vtt/VTTRegion.cpp466
-rw-r--r--chromium/third_party/WebKit/Source/core/html/track/vtt/VTTRegion.h154
-rw-r--r--chromium/third_party/WebKit/Source/core/html/track/vtt/VTTRegion.idl41
-rw-r--r--chromium/third_party/WebKit/Source/core/html/track/vtt/VTTRegionList.cpp81
-rw-r--r--chromium/third_party/WebKit/Source/core/html/track/vtt/VTTRegionList.h62
-rw-r--r--chromium/third_party/WebKit/Source/core/html/track/vtt/VTTRegionList.idl33
-rw-r--r--chromium/third_party/WebKit/Source/core/html/track/vtt/VTTToken.h92
-rw-r--r--chromium/third_party/WebKit/Source/core/html/track/vtt/VTTTokenizer.cpp265
-rw-r--r--chromium/third_party/WebKit/Source/core/html/track/vtt/VTTTokenizer.h57
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/AsyncCallStackTracker.cpp223
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/AsyncCallStackTracker.h105
-rwxr-xr-xchromium/third_party/WebKit/Source/core/inspector/CodeGeneratorInspector.py17
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/CodeGeneratorInspectorStrings.py33
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/ConsoleAPITypes.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/ConsoleMessage.cpp6
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/ConsoleMessage.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/ContentSearchUtils.cpp18
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/ContentSearchUtils.h6
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/DEPS6
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/DOMEditor.cpp182
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/DOMPatchSupport.cpp47
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/DOMPatchSupport.h3
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InjectedScript.cpp17
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InjectedScript.h1
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InjectedScriptBase.cpp7
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InjectedScriptCanvasModuleSource.js223
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InjectedScriptExterns.js7
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InjectedScriptHost.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InjectedScriptManager.cpp11
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InjectedScriptManager.h3
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InjectedScriptSource.js306
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InspectorAgent.cpp24
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InspectorAgent.h14
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InspectorApplicationCacheAgent.cpp19
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InspectorApplicationCacheAgent.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InspectorCSSAgent.cpp430
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InspectorCSSAgent.h24
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InspectorCanvasAgent.cpp8
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InspectorClient.cpp11
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InspectorClient.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InspectorConsoleAgent.cpp35
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InspectorConsoleAgent.h18
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InspectorController.cpp47
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InspectorController.h15
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InspectorCounters.cpp18
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InspectorCounters.h28
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InspectorDOMAgent.cpp150
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InspectorDOMAgent.h11
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InspectorDOMDebuggerAgent.cpp34
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InspectorDOMDebuggerAgent.h6
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InspectorDOMStorageAgent.cpp45
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InspectorDatabaseAgent.cpp44
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InspectorDatabaseResource.cpp1
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InspectorDebuggerAgent.cpp189
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InspectorDebuggerAgent.h32
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InspectorFileSystemAgent.cpp237
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InspectorFileSystemAgent.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InspectorFrontendHost.cpp101
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InspectorFrontendHost.h15
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InspectorFrontendHost.idl14
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InspectorHeapProfilerAgent.cpp49
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InspectorHeapProfilerAgent.h6
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InspectorHistory.cpp14
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InspectorHistory.h3
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InspectorIndexedDBAgent.cpp138
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InspectorInputAgent.cpp25
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InspectorInstrumentation.cpp35
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InspectorInstrumentation.h64
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InspectorInstrumentation.idl152
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InspectorInstrumentationCustomInl.h21
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InspectorLayerTreeAgent.cpp191
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InspectorLayerTreeAgent.h22
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InspectorMemoryAgent.cpp4
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InspectorMemoryAgent.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InspectorOverlay.cpp122
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InspectorOverlay.h29
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InspectorOverlayPage.html146
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InspectorPageAgent.cpp393
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InspectorPageAgent.h43
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InspectorProfilerAgent.cpp227
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InspectorProfilerAgent.h45
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InspectorResourceAgent.cpp53
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InspectorResourceAgent.h20
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InspectorRuntimeAgent.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InspectorRuntimeAgent.h1
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InspectorState.h5
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InspectorStyleSheet.cpp153
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InspectorStyleSheet.h8
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InspectorTimelineAgent.cpp501
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InspectorTimelineAgent.h175
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/InspectorWorkerAgent.cpp4
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/JSONParser.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/JavaScriptCallFrame.cpp61
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/JavaScriptCallFrame.h7
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/JavaScriptCallFrame.idl11
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/NetworkResourcesData.cpp17
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/NetworkResourcesData.h20
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/PageDebuggerAgent.cpp5
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/PageRuntimeAgent.cpp10
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/ScriptCallStack.cpp1
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/ScriptProfile.cpp7
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/ScriptProfile.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/TimelineRecordFactory.cpp47
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/TimelineRecordFactory.h16
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/TimelineTraceEventProcessor.cpp398
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/TimelineTraceEventProcessor.h269
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/TraceEventDispatcher.cpp159
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/TraceEventDispatcher.h192
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/WorkerDebuggerAgent.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/WorkerDebuggerAgent.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/WorkerInspectorController.cpp7
-rw-r--r--chromium/third_party/WebKit/Source/core/inspector/WorkerInspectorController.h1
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/CookieJar.cpp26
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/CrossOriginPreflightResultCache.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/CrossOriginPreflightResultCache.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/DocumentLoadTiming.cpp3
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/DocumentLoader.cpp135
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/DocumentLoader.h31
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/DocumentThreadableLoader.cpp103
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/DocumentThreadableLoader.h11
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/DocumentWriter.cpp58
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/DocumentWriter.h14
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/EmptyClients.cpp26
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/EmptyClients.h107
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/FormSubmission.cpp52
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/FormSubmission.h11
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/FrameFetchContext.cpp74
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/FrameFetchContext.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/FrameLoadRequest.h40
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/FrameLoader.cpp617
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/FrameLoader.h79
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/FrameLoaderClient.h34
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/FrameLoaderStateMachine.cpp7
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/FrameLoaderStateMachine.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/FrameLoaderTypes.h122
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/HistoryController.cpp781
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/HistoryController.h167
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/IconController.cpp133
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/IconController.h61
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/ImageLoader.cpp35
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/LinkLoader.cpp50
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/LinkLoader.h14
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/MixedContentChecker.cpp12
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/NavigationAction.cpp17
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/NavigationAction.h11
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/NavigationScheduler.cpp143
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/NavigationScheduler.h7
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/PingLoader.cpp50
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/PingLoader.h14
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/PrerenderHandle.cpp108
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/PrerenderHandle.h68
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/Prerenderer.cpp144
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/Prerenderer.h82
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/PrerendererClient.cpp1
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/PrerendererClient.h6
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/ProgressTracker.cpp28
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/ProgressTracker.h3
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/SinkDocument.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/SubstituteData.h14
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/TextResourceDecoderBuilder.cpp27
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/TextResourceDecoderBuilder.h14
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/TextTrackLoader.cpp111
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/TextTrackLoader.h56
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/ThreadableLoader.cpp6
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/ThreadableLoader.h8
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/WorkerThreadableLoader.cpp48
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/WorkerThreadableLoader.h7
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/appcache/ApplicationCache.cpp51
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/appcache/ApplicationCache.h25
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/appcache/ApplicationCacheHost.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/archive/ArchiveResource.cpp64
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/archive/ArchiveResource.h67
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/archive/ArchiveResourceCollection.cpp95
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/archive/ArchiveResourceCollection.h59
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/archive/DEPS9
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/archive/MHTMLArchive.cpp235
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/archive/MHTMLArchive.h84
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/archive/MHTMLParser.cpp247
-rw-r--r--chromium/third_party/WebKit/Source/core/loader/archive/MHTMLParser.h72
-rw-r--r--chromium/third_party/WebKit/Source/core/make_core_derived_sources.xml68
-rw-r--r--chromium/third_party/WebKit/Source/core/mathml/mathtags.in15
-rw-r--r--chromium/third_party/WebKit/Source/core/page/AbstractView.idl34
-rw-r--r--chromium/third_party/WebKit/Source/core/page/AutoscrollController.cpp72
-rw-r--r--chromium/third_party/WebKit/Source/core/page/AutoscrollController.h21
-rw-r--r--chromium/third_party/WebKit/Source/core/page/BackForwardClient.h48
-rw-r--r--chromium/third_party/WebKit/Source/core/page/BarProp.cpp75
-rw-r--r--chromium/third_party/WebKit/Source/core/page/BarProp.h57
-rw-r--r--chromium/third_party/WebKit/Source/core/page/Chrome.cpp46
-rw-r--r--chromium/third_party/WebKit/Source/core/page/Chrome.h15
-rw-r--r--chromium/third_party/WebKit/Source/core/page/ChromeClient.h48
-rw-r--r--chromium/third_party/WebKit/Source/core/page/Console.cpp93
-rw-r--r--chromium/third_party/WebKit/Source/core/page/Console.h72
-rw-r--r--chromium/third_party/WebKit/Source/core/page/ConsoleBase.cpp216
-rw-r--r--chromium/third_party/WebKit/Source/core/page/ConsoleBase.h91
-rw-r--r--chromium/third_party/WebKit/Source/core/page/ConsoleBase.idl62
-rw-r--r--chromium/third_party/WebKit/Source/core/page/ConsoleTypes.h54
-rw-r--r--chromium/third_party/WebKit/Source/core/page/ContentSecurityPolicy.cpp1898
-rw-r--r--chromium/third_party/WebKit/Source/core/page/ContentSecurityPolicy.h165
-rw-r--r--chromium/third_party/WebKit/Source/core/page/ContentSecurityPolicyResponseHeaders.cpp42
-rw-r--r--chromium/third_party/WebKit/Source/core/page/ContextMenuController.cpp21
-rw-r--r--chromium/third_party/WebKit/Source/core/page/ContextMenuController.h1
-rw-r--r--chromium/third_party/WebKit/Source/core/page/CreateWindow.cpp80
-rw-r--r--chromium/third_party/WebKit/Source/core/page/CreateWindow.h9
-rw-r--r--chromium/third_party/WebKit/Source/core/page/DOMPoint.h66
-rw-r--r--chromium/third_party/WebKit/Source/core/page/DOMSecurityPolicy.cpp176
-rw-r--r--chromium/third_party/WebKit/Source/core/page/DOMSecurityPolicy.h72
-rw-r--r--chromium/third_party/WebKit/Source/core/page/DOMSelection.cpp69
-rw-r--r--chromium/third_party/WebKit/Source/core/page/DOMSelection.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/page/DOMTimer.cpp201
-rw-r--r--chromium/third_party/WebKit/Source/core/page/DOMTimer.h82
-rw-r--r--chromium/third_party/WebKit/Source/core/page/DOMWindow.cpp1769
-rw-r--r--chromium/third_party/WebKit/Source/core/page/DOMWindow.h448
-rw-r--r--chromium/third_party/WebKit/Source/core/page/DOMWindowBase64.cpp78
-rw-r--r--chromium/third_party/WebKit/Source/core/page/DOMWindowLifecycleNotifier.cpp83
-rw-r--r--chromium/third_party/WebKit/Source/core/page/DOMWindowLifecycleNotifier.h59
-rw-r--r--chromium/third_party/WebKit/Source/core/page/DOMWindowLifecycleObserver.cpp48
-rw-r--r--chromium/third_party/WebKit/Source/core/page/DOMWindowLifecycleObserver.h51
-rw-r--r--chromium/third_party/WebKit/Source/core/page/DOMWindowPagePopup.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/page/DOMWindowPagePopup.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/page/DOMWindowProperty.cpp79
-rw-r--r--chromium/third_party/WebKit/Source/core/page/DOMWindowTimers.cpp67
-rw-r--r--chromium/third_party/WebKit/Source/core/page/DeviceClient.h42
-rw-r--r--chromium/third_party/WebKit/Source/core/page/DeviceController.cpp114
-rw-r--r--chromium/third_party/WebKit/Source/core/page/DeviceController.h68
-rw-r--r--chromium/third_party/WebKit/Source/core/page/DiagnosticLoggingKeys.cpp97
-rw-r--r--chromium/third_party/WebKit/Source/core/page/DiagnosticLoggingKeys.h53
-rw-r--r--chromium/third_party/WebKit/Source/core/page/DragActions.h11
-rw-r--r--chromium/third_party/WebKit/Source/core/page/DragController.cpp138
-rw-r--r--chromium/third_party/WebKit/Source/core/page/DragController.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/page/DragData.cpp172
-rw-r--r--chromium/third_party/WebKit/Source/core/page/DragData.h88
-rw-r--r--chromium/third_party/WebKit/Source/core/page/DragState.h3
-rw-r--r--chromium/third_party/WebKit/Source/core/page/EditorClient.h71
-rw-r--r--chromium/third_party/WebKit/Source/core/page/EventHandler.cpp1141
-rw-r--r--chromium/third_party/WebKit/Source/core/page/EventHandler.h104
-rw-r--r--chromium/third_party/WebKit/Source/core/page/EventSource.cpp98
-rw-r--r--chromium/third_party/WebKit/Source/core/page/EventSource.h42
-rw-r--r--chromium/third_party/WebKit/Source/core/page/EventSource.idl6
-rw-r--r--chromium/third_party/WebKit/Source/core/page/FocusController.cpp118
-rw-r--r--chromium/third_party/WebKit/Source/core/page/FocusController.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/page/Frame.cpp720
-rw-r--r--chromium/third_party/WebKit/Source/core/page/Frame.h286
-rw-r--r--chromium/third_party/WebKit/Source/core/page/FrameActionScheduler.cpp111
-rw-r--r--chromium/third_party/WebKit/Source/core/page/FrameActionScheduler.h75
-rw-r--r--chromium/third_party/WebKit/Source/core/page/FrameDestructionObserver.cpp66
-rw-r--r--chromium/third_party/WebKit/Source/core/page/FrameTree.cpp90
-rw-r--r--chromium/third_party/WebKit/Source/core/page/FrameView.cpp3420
-rw-r--r--chromium/third_party/WebKit/Source/core/page/FrameView.h583
-rw-r--r--chromium/third_party/WebKit/Source/core/page/History.cpp156
-rw-r--r--chromium/third_party/WebKit/Source/core/page/History.h75
-rw-r--r--chromium/third_party/WebKit/Source/core/page/History.idl36
-rw-r--r--chromium/third_party/WebKit/Source/core/page/ImageBitmap.cpp200
-rw-r--r--chromium/third_party/WebKit/Source/core/page/ImageBitmap.h72
-rw-r--r--chromium/third_party/WebKit/Source/core/page/ImageBitmap.idl9
-rw-r--r--chromium/third_party/WebKit/Source/core/page/ImageBitmapTest.cpp209
-rw-r--r--chromium/third_party/WebKit/Source/core/page/InjectedStyleSheet.h60
-rw-r--r--chromium/third_party/WebKit/Source/core/page/LayoutMilestones.h41
-rw-r--r--chromium/third_party/WebKit/Source/core/page/Location.cpp269
-rw-r--r--chromium/third_party/WebKit/Source/core/page/Location.h87
-rw-r--r--chromium/third_party/WebKit/Source/core/page/Location.idl54
-rw-r--r--chromium/third_party/WebKit/Source/core/page/MemoryInfo.cpp150
-rw-r--r--chromium/third_party/WebKit/Source/core/page/MouseEventWithHitTestResults.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/page/MouseEventWithHitTestResults.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/page/Navigator.cpp163
-rw-r--r--chromium/third_party/WebKit/Source/core/page/Navigator.h71
-rw-r--r--chromium/third_party/WebKit/Source/core/page/NavigatorID.cpp92
-rw-r--r--chromium/third_party/WebKit/Source/core/page/NavigatorOnLine.h48
-rw-r--r--chromium/third_party/WebKit/Source/core/page/NetworkStateNotifier.cpp58
-rw-r--r--chromium/third_party/WebKit/Source/core/page/NetworkStateNotifier.h58
-rw-r--r--chromium/third_party/WebKit/Source/core/page/Page.cpp394
-rw-r--r--chromium/third_party/WebKit/Source/core/page/Page.h96
-rw-r--r--chromium/third_party/WebKit/Source/core/page/PageConsole.cpp8
-rw-r--r--chromium/third_party/WebKit/Source/core/page/PageConsole.h5
-rw-r--r--chromium/third_party/WebKit/Source/core/page/PageGroup.cpp31
-rw-r--r--chromium/third_party/WebKit/Source/core/page/PageGroup.h29
-rw-r--r--chromium/third_party/WebKit/Source/core/page/PageGroupLoadDeferrer.cpp10
-rw-r--r--chromium/third_party/WebKit/Source/core/page/PageLifecycleNotifier.cpp16
-rw-r--r--chromium/third_party/WebKit/Source/core/page/PageLifecycleNotifier.h14
-rw-r--r--chromium/third_party/WebKit/Source/core/page/PageLifecycleObserver.cpp12
-rw-r--r--chromium/third_party/WebKit/Source/core/page/PageLifecycleObserver.h7
-rw-r--r--chromium/third_party/WebKit/Source/core/page/PagePopupClient.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/page/PagePopupController.cpp8
-rw-r--r--chromium/third_party/WebKit/Source/core/page/PagePopupController.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/page/PagePopupController.idl6
-rw-r--r--chromium/third_party/WebKit/Source/core/page/PageScaleConstraints.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/page/PageScaleConstraintsSet.cpp169
-rw-r--r--chromium/third_party/WebKit/Source/core/page/PageScaleConstraintsSet.h88
-rw-r--r--chromium/third_party/WebKit/Source/core/page/PageSerializer.cpp10
-rw-r--r--chromium/third_party/WebKit/Source/core/page/PageSerializer.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/page/PageVisibilityState.cpp3
-rw-r--r--chromium/third_party/WebKit/Source/core/page/PageVisibilityState.h1
-rw-r--r--chromium/third_party/WebKit/Source/core/page/Performance.cpp294
-rw-r--r--chromium/third_party/WebKit/Source/core/page/Performance.h113
-rw-r--r--chromium/third_party/WebKit/Source/core/page/Performance.idl66
-rw-r--r--chromium/third_party/WebKit/Source/core/page/PerformanceEntry.cpp69
-rw-r--r--chromium/third_party/WebKit/Source/core/page/PerformanceEntry.idl39
-rw-r--r--chromium/third_party/WebKit/Source/core/page/PerformanceMark.h52
-rw-r--r--chromium/third_party/WebKit/Source/core/page/PerformanceMeasure.h51
-rw-r--r--chromium/third_party/WebKit/Source/core/page/PerformanceNavigation.cpp82
-rw-r--r--chromium/third_party/WebKit/Source/core/page/PerformanceNavigation.h63
-rw-r--r--chromium/third_party/WebKit/Source/core/page/PerformanceResourceTiming.cpp194
-rw-r--r--chromium/third_party/WebKit/Source/core/page/PerformanceResourceTiming.h92
-rw-r--r--chromium/third_party/WebKit/Source/core/page/PerformanceTiming.cpp356
-rw-r--r--chromium/third_party/WebKit/Source/core/page/PerformanceTiming.h86
-rw-r--r--chromium/third_party/WebKit/Source/core/page/PerformanceUserTiming.cpp209
-rw-r--r--chromium/third_party/WebKit/Source/core/page/PerformanceUserTiming.h72
-rw-r--r--chromium/third_party/WebKit/Source/core/page/PointerLockController.cpp33
-rw-r--r--chromium/third_party/WebKit/Source/core/page/PrintContext.cpp11
-rw-r--r--chromium/third_party/WebKit/Source/core/page/ResourceTimingInfo.h81
-rw-r--r--chromium/third_party/WebKit/Source/core/page/RuntimeCSSEnabled.cpp166
-rw-r--r--chromium/third_party/WebKit/Source/core/page/RuntimeEnabledFeatures.in105
-rw-r--r--chromium/third_party/WebKit/Source/core/page/RuntimeEnabledFeaturesCustom.cpp43
-rw-r--r--chromium/third_party/WebKit/Source/core/page/Screen.cpp107
-rw-r--r--chromium/third_party/WebKit/Source/core/page/Screen.h61
-rw-r--r--chromium/third_party/WebKit/Source/core/page/Selection.idl2
-rw-r--r--chromium/third_party/WebKit/Source/core/page/Settings.cpp382
-rw-r--r--chromium/third_party/WebKit/Source/core/page/Settings.h206
-rw-r--r--chromium/third_party/WebKit/Source/core/page/Settings.in152
-rw-r--r--chromium/third_party/WebKit/Source/core/page/SpatialNavigation.cpp13
-rw-r--r--chromium/third_party/WebKit/Source/core/page/SpatialNavigation.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/page/SpeechInput.cpp131
-rw-r--r--chromium/third_party/WebKit/Source/core/page/SpeechInput.h91
-rw-r--r--chromium/third_party/WebKit/Source/core/page/SpeechInputEvent.cpp74
-rw-r--r--chromium/third_party/WebKit/Source/core/page/SpeechInputEvent.h59
-rw-r--r--chromium/third_party/WebKit/Source/core/page/SpeechInputListener.h67
-rw-r--r--chromium/third_party/WebKit/Source/core/page/SpeechInputResult.cpp62
-rw-r--r--chromium/third_party/WebKit/Source/core/page/SpeechInputResultList.cpp56
-rw-r--r--chromium/third_party/WebKit/Source/core/page/SpeechInputResultList.h56
-rw-r--r--chromium/third_party/WebKit/Source/core/page/SpellCheckerClient.h53
-rw-r--r--chromium/third_party/WebKit/Source/core/page/SuspendableTimer.cpp86
-rw-r--r--chromium/third_party/WebKit/Source/core/page/SuspendableTimer.h61
-rw-r--r--chromium/third_party/WebKit/Source/core/page/TouchAdjustment.cpp21
-rw-r--r--chromium/third_party/WebKit/Source/core/page/TouchAdjustment.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/page/TouchDisambiguation.cpp10
-rw-r--r--chromium/third_party/WebKit/Source/core/page/UseCounter.cpp717
-rw-r--r--chromium/third_party/WebKit/Source/core/page/UseCounter.h270
-rw-r--r--chromium/third_party/WebKit/Source/core/page/UserContentTypes.h35
-rw-r--r--chromium/third_party/WebKit/Source/core/page/UserContentURLPattern.cpp234
-rw-r--r--chromium/third_party/WebKit/Source/core/page/UserContentURLPattern.h76
-rw-r--r--chromium/third_party/WebKit/Source/core/page/UserStyleSheet.h73
-rw-r--r--chromium/third_party/WebKit/Source/core/page/UserStyleSheetTypes.h42
-rw-r--r--chromium/third_party/WebKit/Source/core/page/WebKitPoint.idl34
-rw-r--r--chromium/third_party/WebKit/Source/core/page/Window.idl315
-rw-r--r--chromium/third_party/WebKit/Source/core/page/WindowBase64.idl34
-rw-r--r--chromium/third_party/WebKit/Source/core/page/WindowFeatures.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/page/WindowPagePopup.idl4
-rw-r--r--chromium/third_party/WebKit/Source/core/page/WorkerNavigator.cpp48
-rw-r--r--chromium/third_party/WebKit/Source/core/page/WorkerNavigator.h53
-rw-r--r--chromium/third_party/WebKit/Source/core/page/animation/AnimationBase.cpp594
-rw-r--r--chromium/third_party/WebKit/Source/core/page/animation/AnimationBase.h229
-rw-r--r--chromium/third_party/WebKit/Source/core/page/animation/AnimationController.cpp615
-rw-r--r--chromium/third_party/WebKit/Source/core/page/animation/AnimationController.h103
-rw-r--r--chromium/third_party/WebKit/Source/core/page/animation/AnimationControllerPrivate.h145
-rw-r--r--chromium/third_party/WebKit/Source/core/page/animation/CSSPropertyAnimation.cpp1279
-rw-r--r--chromium/third_party/WebKit/Source/core/page/animation/CompositeAnimation.cpp562
-rw-r--r--chromium/third_party/WebKit/Source/core/page/animation/CompositeAnimation.h102
-rw-r--r--chromium/third_party/WebKit/Source/core/page/animation/ImplicitAnimation.cpp291
-rw-r--r--chromium/third_party/WebKit/Source/core/page/animation/ImplicitAnimation.h98
-rw-r--r--chromium/third_party/WebKit/Source/core/page/animation/KeyframeAnimation.cpp462
-rw-r--r--chromium/third_party/WebKit/Source/core/page/animation/KeyframeAnimation.h102
-rwxr-xr-xchromium/third_party/WebKit/Source/core/page/make_settings.pl531
-rw-r--r--chromium/third_party/WebKit/Source/core/page/scrolling/ScrollingConstraints.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/page/scrolling/ScrollingCoordinator.cpp251
-rw-r--r--chromium/third_party/WebKit/Source/core/page/scrolling/ScrollingCoordinator.h46
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/AsyncFileSystem.h134
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/AsyncFileSystemCallbacks.h94
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/CalculationValue.cpp73
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/CalculationValue.h259
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/Clock.cpp88
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/Clock.h61
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/ColorChooser.h47
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/ColorChooserClient.h58
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/ColorData.gperf175
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/ContentType.cpp94
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/ContentType.h48
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/ContextMenu.cpp51
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/ContextMenu.h48
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/ContextMenuItem.cpp118
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/ContextMenuItem.h88
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/Cookie.h84
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/CrossThreadCopier.cpp133
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/CrossThreadCopier.h179
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/CryptoResult.h58
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/Cursor.cpp446
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/Cursor.h169
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/DEPS9
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/DateComponents.cpp723
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/DateComponents.h213
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/DateTimeChooser.h68
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/DateTimeChooserClient.h47
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/Decimal.cpp1034
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/Decimal.h181
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/DecimalTest.cpp1097
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/DragData.cpp175
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/DragData.h89
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/DragImage.cpp54
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/DragImage.h6
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/EventTracer.cpp70
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/EventTracer.h60
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/FileChooser.cpp111
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/FileChooser.h104
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/FileMetadata.h62
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/FileSystem.h53
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/FloatConversion.h44
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/HashTools.h46
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/HistogramSupport.h44
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/HostWindow.h71
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/JSONValues.cpp386
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/JSONValues.h393
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/KillRing.h45
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/KillRingNone.cpp52
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/Language.cpp117
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/Language.h44
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/LayoutTestSupport.cpp48
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/LayoutTestSupport.h41
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/LayoutUnit.h799
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/Length.cpp219
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/Length.h320
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/LengthBox.cpp92
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/LengthBox.h106
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/LengthPoint.h65
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/LengthSize.h58
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/LifecycleContext.cpp64
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/LifecycleContext.h65
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/LifecycleNotifier.cpp68
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/LifecycleNotifier.h79
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/LifecycleObserver.cpp66
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/LifecycleObserver.h62
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/LinkHash.cpp63
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/LinkHash.h64
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/LocalizedStrings.cpp477
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/LocalizedStrings.h132
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/Logging.cpp156
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/Logging.h72
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/MIMETypeFromURL.cpp59
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/MIMETypeFromURL.h40
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/MIMETypeRegistry.h71
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/MemoryUsageSupport.h69
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/NotImplemented.cpp42
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/NotImplemented.h49
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/PODArena.h201
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/PODFreeListArena.h132
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/PODInterval.h165
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/PODIntervalTree.h266
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/PODRedBlackTree.h827
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/ParsingUtilities.h76
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/Partitions.cpp55
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/Partitions.h53
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/Pasteboard.cpp139
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/Pasteboard.h32
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/PlatformEvent.cpp27
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/PlatformEvent.h142
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/PlatformGestureEvent.h82
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/PlatformInstrumentation.cpp56
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/PlatformInstrumentation.h105
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/PlatformKeyboardEvent.h107
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/PlatformMouseEvent.h77
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/PlatformScreen.h51
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/PlatformSpeechSynthesisUtterance.cpp44
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/PlatformSpeechSynthesisUtterance.h89
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/PlatformSpeechSynthesisVoice.cpp56
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/PlatformSpeechSynthesisVoice.h68
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/PlatformSpeechSynthesizer.cpp44
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/PlatformSpeechSynthesizer.h90
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/PlatformTouchEvent.h45
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/PlatformTouchPoint.h73
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/PlatformWheelEvent.h160
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/PopupMenu.h44
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/PopupMenuClient.h81
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/PopupMenuStyle.h79
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/PrerenderClient.h50
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/PrerenderHandle.h84
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/PurgeableBuffer.cpp97
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/PurgeableBuffer.h71
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/RefCountedSupplement.h73
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/SSLKeyGenerator.h48
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/ScrollAnimator.cpp152
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/ScrollAnimator.h118
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/ScrollAnimatorNone.cpp531
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/ScrollAnimatorNone.h155
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/ScrollTypes.h166
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/ScrollView.cpp1201
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/ScrollView.h365
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/ScrollableArea.cpp420
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/ScrollableArea.h256
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/Scrollbar.cpp604
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/Scrollbar.h197
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/ScrollbarTheme.cpp317
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/ScrollbarTheme.h146
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeAndroid.cpp39
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeAuraOrGtk.cpp153
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeAuraOrGtk.h53
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeClient.h95
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeMacCommon.h71
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeMacCommon.mm428
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeMacNonOverlayAPI.h61
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeMacNonOverlayAPI.mm336
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeMacOverlayAPI.h70
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeMacOverlayAPI.mm196
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeNonMacCommon.cpp130
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeNonMacCommon.h57
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeOverlay.cpp133
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeOverlay.h68
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeWin.cpp255
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeWin.h59
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/SecureTextInput.cpp52
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/SecureTextInput.h48
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/SerializedResource.h56
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/SharedBuffer.cpp440
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/SharedBuffer.h121
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/SharedBufferChunkReader.cpp150
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/SharedBufferChunkReader.h72
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/SharedBufferTest.cpp173
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/SharedTimer.h77
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/Sound.h35
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/StatsCounter.h43
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/SuddenTermination.h38
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/Supplementable.h156
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/Task.h57
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/Theme.cpp58
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/Theme.h115
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/ThemeTypes.h80
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/ThreadGlobalData.cpp72
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/ThreadGlobalData.h88
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/ThreadTimers.cpp154
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/ThreadTimers.h67
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/Timer.cpp416
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/Timer.h175
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/TreeShared.h123
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/UUID.cpp62
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/UUID.h54
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/Widget.cpp191
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/Widget.h145
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/WindowsKeyboardCodes.h320
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/animation/AnimationTranslationUtil.cpp355
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/animation/AnimationTranslationUtil.h63
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/animation/AnimationTranslationUtilTest.cpp352
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/animation/AnimationUtilities.h73
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/animation/AnimationValue.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/animation/CSSAnimationData.cpp37
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/animation/CSSAnimationData.h11
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/animation/TimingFunction.h118
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/animation/TimingFunctionTestHelper.cpp253
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/animation/TimingFunctionTestHelper.h63
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/animation/TimingFunctionTestHelperTest.cpp326
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/AudioArray.h162
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/AudioBus.cpp638
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/AudioBus.h171
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/AudioChannel.cpp133
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/AudioChannel.h139
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/AudioDSPKernel.h76
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/AudioDSPKernelProcessor.cpp157
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/AudioDSPKernelProcessor.h79
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/AudioDestination.h71
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/AudioDestinationConsumer.h50
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/AudioFIFO.cpp144
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/AudioFIFO.h75
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/AudioFileReader.h52
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/AudioIOCallback.h48
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/AudioProcessor.h81
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/AudioPullFIFO.cpp75
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/AudioPullFIFO.h74
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/AudioResampler.cpp128
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/AudioResampler.h68
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/AudioResamplerKernel.cpp143
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/AudioResamplerKernel.h76
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/AudioSourceProvider.h51
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/AudioSourceProviderClient.h39
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/AudioUtilities.cpp66
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/AudioUtilities.h47
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/Biquad.cpp587
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/Biquad.h117
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/Cone.cpp85
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/Cone.h63
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/DenormalDisabler.h125
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/DirectConvolver.cpp386
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/DirectConvolver.h59
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/Distance.cpp92
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/Distance.h81
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/DownSampler.cpp151
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/DownSampler.h74
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/DynamicsCompressor.cpp286
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/DynamicsCompressor.h118
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/DynamicsCompressorKernel.cpp479
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/DynamicsCompressorKernel.h129
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/EqualPowerPanner.cpp159
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/EqualPowerPanner.h56
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/FFTConvolver.cpp120
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/FFTConvolver.h71
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/FFTFrame.cpp274
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/FFTFrame.h159
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/FFTFrameStub.cpp107
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/HRTFDatabase.cpp124
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/HRTFDatabase.h85
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/HRTFDatabaseLoader.cpp131
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/HRTFDatabaseLoader.h93
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/HRTFElevation.cpp342
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/HRTFElevation.h112
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/HRTFKernel.cpp136
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/HRTFKernel.h98
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/HRTFPanner.cpp314
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/HRTFPanner.h109
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/MultiChannelResampler.cpp123
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/MultiChannelResampler.h59
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/Panner.cpp66
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/Panner.h72
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/Reverb.cpp242
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/Reverb.h67
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/ReverbAccumulationBuffer.cpp119
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/ReverbAccumulationBuffer.h67
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/ReverbConvolver.cpp238
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/ReverbConvolver.h96
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/ReverbConvolverStage.cpp185
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/ReverbConvolverStage.h85
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/ReverbInputBuffer.cpp89
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/ReverbInputBuffer.h64
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/SincResampler.cpp474
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/SincResampler.h86
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/UpSampler.cpp134
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/UpSampler.h76
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/VectorMath.cpp690
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/VectorMath.h59
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/ZeroPole.cpp74
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/ZeroPole.h66
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/chromium/AudioBusChromium.cpp79
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/chromium/AudioDestinationChromium.cpp180
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/chromium/AudioDestinationChromium.h79
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/chromium/FFTFrameOpenMAXDLAndroid.cpp208
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/ffmpeg/FFTFrameFFMPEG.cpp253
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/ipp/FFTFrameIPP.cpp189
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/mac/FFTFrameMac.cpp193
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/Composite.wavbin245804 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T000_P000.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T000_P015.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T000_P030.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T000_P045.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T000_P060.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T000_P075.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T000_P090.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T000_P315.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T000_P330.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T000_P345.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T015_P000.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T015_P015.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T015_P030.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T015_P045.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T015_P060.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T015_P075.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T015_P090.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T015_P315.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T015_P330.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T015_P345.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T030_P000.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T030_P015.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T030_P030.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T030_P045.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T030_P060.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T030_P075.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T030_P090.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T030_P315.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T030_P330.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T030_P345.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T045_P000.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T045_P015.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T045_P030.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T045_P045.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T045_P060.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T045_P075.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T045_P090.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T045_P315.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T045_P330.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T045_P345.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T060_P000.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T060_P015.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T060_P030.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T060_P045.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T060_P060.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T060_P075.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T060_P090.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T060_P315.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T060_P330.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T060_P345.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T075_P000.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T075_P015.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T075_P030.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T075_P045.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T075_P060.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T075_P075.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T075_P090.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T075_P315.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T075_P330.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T075_P345.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T090_P000.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T090_P015.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T090_P030.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T090_P045.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T090_P060.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T090_P075.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T090_P090.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T090_P315.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T090_P330.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T090_P345.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T105_P000.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T105_P015.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T105_P030.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T105_P045.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T105_P060.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T105_P075.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T105_P090.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T105_P315.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T105_P330.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T105_P345.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T120_P000.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T120_P015.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T120_P030.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T120_P045.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T120_P060.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T120_P075.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T120_P090.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T120_P315.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T120_P330.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T120_P345.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T135_P000.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T135_P015.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T135_P030.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T135_P045.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T135_P060.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T135_P075.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T135_P090.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T135_P315.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T135_P330.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T135_P345.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T150_P000.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T150_P015.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T150_P030.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T150_P045.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T150_P060.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T150_P075.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T150_P090.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T150_P315.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T150_P330.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T150_P345.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T165_P000.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T165_P015.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T165_P030.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T165_P045.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T165_P060.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T165_P075.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T165_P090.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T165_P315.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T165_P330.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T165_P345.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T180_P000.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T180_P015.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T180_P030.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T180_P045.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T180_P060.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T180_P075.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T180_P090.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T180_P315.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T180_P330.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T180_P345.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T195_P000.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T195_P015.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T195_P030.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T195_P045.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T195_P060.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T195_P075.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T195_P090.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T195_P315.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T195_P330.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T195_P345.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T210_P000.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T210_P015.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T210_P030.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T210_P045.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T210_P060.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T210_P075.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T210_P090.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T210_P315.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T210_P330.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T210_P345.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T225_P000.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T225_P015.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T225_P030.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T225_P045.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T225_P060.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T225_P075.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T225_P090.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T225_P315.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T225_P330.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T225_P345.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T240_P000.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T240_P015.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T240_P030.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T240_P045.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T240_P060.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T240_P075.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T240_P090.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T240_P315.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T240_P330.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T240_P345.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T255_P000.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T255_P015.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T255_P030.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T255_P045.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T255_P060.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T255_P075.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T255_P090.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T255_P315.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T255_P330.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T255_P345.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T270_P000.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T270_P015.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T270_P030.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T270_P045.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T270_P060.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T270_P075.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T270_P090.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T270_P315.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T270_P330.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T270_P345.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T285_P000.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T285_P015.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T285_P030.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T285_P045.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T285_P060.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T285_P075.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T285_P090.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T285_P315.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T285_P330.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T285_P345.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T300_P000.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T300_P015.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T300_P030.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T300_P045.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T300_P060.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T300_P075.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T300_P090.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T300_P315.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T300_P330.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T300_P345.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T315_P000.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T315_P015.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T315_P030.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T315_P045.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T315_P060.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T315_P075.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T315_P090.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T315_P315.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T315_P330.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T315_P345.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T330_P000.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T330_P015.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T330_P030.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T330_P045.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T330_P060.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T330_P075.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T330_P090.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T330_P315.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T330_P330.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T330_P345.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T345_P000.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T345_P015.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T345_P030.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T345_P045.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T345_P060.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T345_P075.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T345_P090.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T345_P315.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T345_P330.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T345_P345.wavbin1068 -> 0 bytes
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/ChromiumDataObject.cpp56
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/ChromiumDataObject.h11
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/ChromiumDataObjectItem.cpp53
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/ChromiumDataObjectItem.h21
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/ClipboardChromium.cpp479
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/ClipboardChromium.h120
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/ClipboardChromiumPosix.cpp58
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/ClipboardChromiumTest.cpp89
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/ClipboardChromiumWin.cpp57
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/ClipboardMimeTypes.cpp46
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/ClipboardMimeTypes.h48
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/ClipboardUtilitiesChromium.cpp93
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/ClipboardUtilitiesChromium.h50
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/FileSystemChromium.cpp78
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/FramelessScrollView.cpp103
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/FramelessScrollView.h94
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/FramelessScrollViewClient.h46
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/HistogramSupportChromium.cpp48
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/KeyCodeConversionAndroid.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/KeyCodeConversionGtk.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/KeyboardCodes.h561
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/LanguageChromium.cpp57
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/MIMETypeRegistryChromium.cpp119
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/MemoryUsageSupportChromium.cpp72
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/PlatformKeyboardEventChromium.cpp109
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/PlatformScreenChromium.cpp99
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/PlatformSpeechSynthesizerChromium.cpp88
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/PlatformThemeChromiumDefault.cpp221
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/PlatformThemeChromiumDefault.h71
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/Prerender.cpp135
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/Prerender.h97
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/PrerenderHandle.cpp109
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/SSLKeyGeneratorChromium.cpp59
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/SharedTimerChromium.cpp48
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/SoundChromiumPosix.cpp43
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/SoundChromiumWin.cpp39
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/StatsCounterChromium.cpp43
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/SuddenTerminationChromium.cpp48
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/TraceEvent.h911
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/support/Platform.cpp53
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/support/WebActiveGestureAnimation.cpp67
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/support/WebActiveGestureAnimation.h63
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/support/WebArrayBuffer.cpp6
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/support/WebAudioBus.cpp151
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/support/WebCString.cpp108
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/support/WebCrypto.cpp11
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/support/WebCryptoAlgorithm.cpp126
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/support/WebCryptoKey.cpp100
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/support/WebCursorInfo.cpp51
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/support/WebData.cpp108
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/support/WebDeviceMotionData.cpp47
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/support/WebDeviceOrientationData.cpp47
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/support/WebFileSystemCallbacks.cpp158
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/support/WebFloatQuad.cpp51
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/support/WebHTTPBody.cpp212
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/support/WebHTTPLoadInfo.cpp147
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/support/WebMediaConstraints.cpp108
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/support/WebMediaStream.cpp10
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/support/WebMediaStreamSource.cpp246
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/support/WebMediaStreamTrack.cpp37
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/support/WebPrerender.cpp133
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/support/WebPrerenderingSupport.cpp52
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/support/WebRTCConfiguration.cpp104
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/support/WebRTCICECandidate.cpp105
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/support/WebRTCSessionDescription.cpp11
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/support/WebRTCSessionDescriptionRequest.cpp6
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/support/WebRTCStatsRequest.cpp4
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/support/WebRTCStatsResponse.cpp69
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/support/WebRTCVoidRequest.cpp97
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/support/WebScrollbarImpl.cpp141
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/support/WebScrollbarImpl.h67
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/support/WebScrollbarThemeClientImpl.cpp231
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/support/WebScrollbarThemeClientImpl.h87
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/support/WebScrollbarThemeGeometryNative.cpp157
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/support/WebScrollbarThemeGeometryNative.h75
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/support/WebSocketStreamError.cpp72
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/support/WebSourceInfo.cpp112
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/support/WebSpeechSynthesisUtterance.cpp104
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/support/WebSpeechSynthesisVoice.cpp81
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/support/WebSpeechSynthesizerClientImpl.cpp87
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/support/WebSpeechSynthesizerClientImpl.h62
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/support/WebString.cpp160
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/support/WebThreadSafeData.cpp75
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/support/WebTransformKeyframe.cpp52
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/support/WebURL.cpp58
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/support/WebURLError.cpp74
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/support/WebURLRequest.cpp352
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/support/WebURLRequestPrivate.h53
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/support/WebURLResponse.cpp447
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/support/WebURLResponsePrivate.h52
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/support/WrappedResourceRequest.h80
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/chromium/support/WrappedResourceResponse.h80
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/cocoa/KeyEventCocoa.h40
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/cocoa/KeyEventCocoa.mm531
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/ANGLEWebKitBridge.cpp227
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/ANGLEWebKitBridge.h96
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/BitmapImage.cpp654
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/BitmapImage.h200
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/BitmapImageTest.cpp119
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/Color.cpp448
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/Color.h169
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/ColorSpace.h39
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/ContentDecryptionModule.cpp80
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/ContentDecryptionModule.h62
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/ContentDecryptionModuleSession.cpp89
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/ContentDecryptionModuleSession.h84
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/CrossfadeGeneratedImage.cpp110
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/CrossfadeGeneratedImage.h74
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/DashArray.h35
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/DrawLooper.cpp108
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/DrawLooper.h78
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/Extensions3D.cpp238
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/Extensions3D.h333
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/FloatPoint.cpp147
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/FloatPoint.h245
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/FloatPoint3D.cpp42
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/FloatPoint3D.h187
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/FloatPolygon.cpp254
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/FloatPolygon.h153
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/FloatQuad.cpp236
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/FloatQuad.h180
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/FloatRect.cpp272
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/FloatRect.h239
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/FloatSize.cpp68
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/FloatSize.h192
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/Font.cpp704
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/Font.h342
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/FontBaseline.h35
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/FontCache.cpp599
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/FontCache.h168
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/FontCustomPlatformData.h88
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/FontData.cpp35
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/FontData.h69
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/FontDescription.cpp105
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/FontDescription.h231
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/FontFallbackList.cpp139
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/FontFallbackList.h123
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/FontFamily.cpp46
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/FontFamily.h94
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/FontFastPath.cpp612
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/FontFeatureSettings.cpp46
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/FontFeatureSettings.h68
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/FontMetrics.h157
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/FontOrientation.h35
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/FontPlatformData.cpp140
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/FontPlatformData.h213
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/FontSelector.h62
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/FontSmoothingMode.h35
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/FontTest.cpp365
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/FontTraitsMask.h70
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/FontWidthVariant.h47
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/FrameData.cpp65
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/FrameData.h71
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/GeneratedImage.cpp45
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/GeneratedImage.h66
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/GeneratorGeneratedImage.cpp152
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/GeneratorGeneratedImage.h82
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/Glyph.h39
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/GlyphBuffer.h149
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/GlyphMetricsMap.h129
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/GlyphPage.h204
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/GlyphPageTreeNode.cpp437
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/GlyphPageTreeNode.h141
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/Gradient.cpp364
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/Gradient.h167
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsContext.cpp1898
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsContext.h479
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsContext3D.cpp1025
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsContext3D.h867
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsContext3DImagePacking.cpp1589
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsContextAnnotation.cpp159
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsContextAnnotation.h103
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsContextState.h149
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsContextStateSaver.h77
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsContextTest.cpp1091
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsLayer.cpp1220
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsLayer.h428
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsLayerClient.h89
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsLayerFactory.h45
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsTypes.cpp226
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsTypes.h138
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsTypes3D.h53
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/Image.cpp241
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/Image.h144
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/ImageBuffer.cpp501
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/ImageBuffer.h159
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/ImageObserver.h51
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/ImageOrientation.cpp62
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/ImageOrientation.h92
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/ImageSource.cpp175
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/ImageSource.h135
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/InbandTextTrackPrivate.h81
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/InbandTextTrackPrivateClient.h124
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/IntPoint.h164
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/IntRect.cpp177
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/IntRect.h205
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/IntRectExtent.h109
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/IntSize.h170
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/IntSizeHash.h48
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/Latin1TextIterator.h67
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/LayoutBoxExtent.cpp198
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/LayoutBoxExtent.h86
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/LayoutPoint.h204
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/LayoutRect.cpp150
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/LayoutRect.h230
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/LayoutSize.h189
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/MediaPlayer.cpp48
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/MediaPlayer.h194
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/MediaSourcePrivate.h57
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/OWNERS3
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/Path.cpp456
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/Path.h132
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/PathTraversalState.cpp224
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/PathTraversalState.h71
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/Pattern.cpp102
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/Pattern.h73
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/Region.cpp611
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/Region.h180
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/RoundedRect.cpp249
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/RoundedRect.h130
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/RoundedRectTest.cpp84
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/SVGGlyph.cpp191
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/SVGGlyph.h113
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/SegmentedFontData.cpp99
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/SegmentedFontData.h91
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/ShadowBlur.cpp198
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/ShadowBlur.h66
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/SimpleFontData.cpp279
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/SimpleFontData.h338
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/SourceBufferPrivate.h54
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/StringTruncator.cpp207
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/StringTruncator.h49
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/StrokeData.cpp111
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/StrokeData.h108
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/SurrogatePairAwareTextIterator.cpp95
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/SurrogatePairAwareTextIterator.h70
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/TextRenderingMode.h35
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/TextRun.cpp71
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/TextRun.h282
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/TextRunIterator.h77
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/TypesettingFeatures.h40
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/UnitBezier.h130
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/UnitBezierTest.cpp74
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/WidthCache.h216
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/WidthIterator.cpp347
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/WidthIterator.h103
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/WindRule.h41
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/cg/FloatPointCG.cpp43
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/cg/FloatRectCG.cpp43
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/cg/FloatSizeCG.cpp43
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/cg/GraphicsContextCG.h41
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/cg/IntPointCG.cpp42
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/cg/IntRectCG.cpp47
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/cg/IntSizeCG.cpp42
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/chromium/AnimationTranslationUtil.cpp303
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/chromium/AnimationTranslationUtil.h56
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/chromium/AnimationTranslationUtilTest.cpp263
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/chromium/Canvas2DLayerBridge.cpp425
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/chromium/Canvas2DLayerBridge.h143
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/chromium/Canvas2DLayerBridgeTest.cpp113
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/chromium/Canvas2DLayerManager.cpp166
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/chromium/Canvas2DLayerManager.h67
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/chromium/Canvas2DLayerManagerTest.cpp268
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/chromium/CrossProcessFontLoading.h95
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/chromium/CrossProcessFontLoading.mm207
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/chromium/DeferredImageDecoder.cpp279
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/chromium/DeferredImageDecoder.h101
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/chromium/DeferredImageDecoderTest.cpp323
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/chromium/DiscardablePixelRef.cpp112
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/chromium/DiscardablePixelRef.h70
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/chromium/FontCacheAndroid.cpp50
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/chromium/FontCacheChromiumLinux.cpp49
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/chromium/FontCacheChromiumWin.cpp647
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/chromium/FontChromiumWin.cpp227
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/chromium/FontPlatformDataChromiumWin.cpp342
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/chromium/FontPlatformDataChromiumWin.h173
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/chromium/FontRenderStyle.h77
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/chromium/FontUtilsChromiumWin.cpp457
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/chromium/FontUtilsChromiumWin.h96
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/chromium/GlyphPageTreeNodeChromiumWin.cpp258
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/chromium/ImageDecodingStore.cpp409
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/chromium/ImageDecodingStore.h323
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/chromium/ImageDecodingStoreTest.cpp460
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/chromium/ImageFrameGenerator.cpp267
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/chromium/ImageFrameGenerator.h118
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/chromium/ImageFrameGeneratorTest.cpp467
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/chromium/LayerPainterChromium.h45
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/chromium/LazyDecodingPixelRef.cpp130
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/chromium/LazyDecodingPixelRef.h84
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/chromium/OpaqueRectTrackingContentLayerDelegate.cpp73
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/chromium/OpaqueRectTrackingContentLayerDelegate.h67
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/chromium/ScaledImageFragment.cpp44
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/chromium/ScaledImageFragment.h74
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/chromium/SimpleFontDataChromiumWin.cpp181
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/chromium/SkSizeHash.h86
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/chromium/TextureUploader.h50
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/chromium/ThreadSafeDataTransport.cpp81
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/chromium/ThreadSafeDataTransport.h72
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/chromium/ThreadSafeDataTransportTest.cpp79
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/chromium/TransformSkMatrix44Conversions.cpp55
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/chromium/TransformSkMatrix44Conversions.h36
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/chromium/TransparencyWin.cpp516
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/chromium/TransparencyWin.h261
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/chromium/UniscribeHelper.cpp1070
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/chromium/UniscribeHelper.h449
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/chromium/UniscribeHelperTextRun.cpp151
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/chromium/UniscribeHelperTextRun.h102
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/chromium/VDMXParser.cpp203
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/chromium/VDMXParser.h42
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/cocoa/FontPlatformDataCocoa.mm321
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/cpu/arm/GraphicsContext3DNEON.h304
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/cpu/arm/filters/FEBlendNEON.h174
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/cpu/arm/filters/FECompositeArithmeticNEON.h99
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/cpu/arm/filters/FEGaussianBlurNEON.h78
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/cpu/arm/filters/FELightingNEON.h202
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/cpu/arm/filters/NEONHelpers.h55
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/DistantLightSource.cpp77
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/DistantLightSource.h62
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEBlend.cpp289
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEBlend.h67
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEColorMatrix.cpp337
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEColorMatrix.h99
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEComponentTransfer.cpp286
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEComponentTransfer.h102
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEComposite.cpp461
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEComposite.h95
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEConvolveMatrix.cpp572
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEConvolveMatrix.h134
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEDiffuseLighting.cpp137
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEDiffuseLighting.h64
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEDisplacementMap.cpp264
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEDisplacementMap.h75
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEDropShadow.cpp134
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEDropShadow.h74
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEFlood.cpp156
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEFlood.h64
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEGaussianBlur.cpp366
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEGaussianBlur.h113
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/FELighting.cpp492
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/FELighting.h128
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEMerge.cpp89
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEMerge.h48
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEMorphology.cpp307
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEMorphology.h91
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEOffset.cpp182
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEOffset.h59
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/FESpecularLighting.cpp152
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/FESpecularLighting.h65
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/FETile.cpp172
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/FETile.h51
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/FETurbulence.cpp475
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/FETurbulence.h140
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/Filter.h83
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/FilterEffect.cpp497
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/FilterEffect.h219
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/FilterOperation.cpp152
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/FilterOperation.h359
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/FilterOperations.cpp188
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/FilterOperations.h81
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/LightSource.h93
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/PointLightSource.cpp88
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/PointLightSource.h59
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/ReferenceFilter.cpp57
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/ReferenceFilter.h68
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/SkiaImageFilterBuilder.cpp305
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/SkiaImageFilterBuilder.h73
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/SourceAlpha.cpp76
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/SourceAlpha.h52
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/SourceGraphic.cpp70
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/SourceGraphic.h54
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/SpotLightSource.cpp195
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/SpotLightSource.h78
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterArrayParameter.h89
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterCompiledProgram.cpp150
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterCompiledProgram.h95
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterConstants.h60
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterGlobalContext.cpp113
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterGlobalContext.h81
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterMesh.cpp68
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterMesh.h76
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterMeshGenerator.cpp173
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterMeshGenerator.h121
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterNumberParameter.h84
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterOperation.cpp77
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterOperation.h95
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterParameter.h77
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterParameterList.cpp102
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterParameterList.h54
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterProgram.cpp87
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterProgram.h92
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterProgramClient.h49
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterProgramInfo.cpp107
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterProgramInfo.h110
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterRenderer.cpp294
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterRenderer.h98
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterTransformParameter.h100
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterValidatedProgram.cpp618
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterValidatedProgram.h123
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/FECustomFilter.cpp370
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/FECustomFilter.h101
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/ValidatedCustomFilterOperation.cpp65
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/ValidatedCustomFilterOperation.h91
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/gpu/DrawingBuffer.cpp703
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/gpu/DrawingBuffer.h213
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/gpu/DrawingBufferTest.cpp83
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/gpu/SharedGraphicsContext3D.cpp86
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/gpu/SharedGraphicsContext3D.h48
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/harfbuzz/FontHarfBuzz.cpp200
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/harfbuzz/FontPlatformDataHarfBuzz.cpp315
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/harfbuzz/FontPlatformDataHarfBuzz.h147
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/harfbuzz/HarfBuzzFace.cpp131
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/harfbuzz/HarfBuzzFace.h75
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/harfbuzz/HarfBuzzFaceCoreText.cpp149
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/harfbuzz/HarfBuzzFaceSkia.cpp196
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/harfbuzz/HarfBuzzShaper.cpp878
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/harfbuzz/HarfBuzzShaper.h161
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/mac/ColorMac.h50
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/mac/ColorMac.mm112
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/mac/ComplexTextController.cpp730
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/mac/ComplexTextController.h184
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/mac/ComplexTextControllerCoreText.mm292
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/mac/FloatPointMac.mm45
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/mac/FloatRectMac.mm45
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/mac/FloatSizeMac.mm45
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/mac/FontCacheMac.mm248
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/mac/FontComplexTextMac.cpp213
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/mac/FontCustomPlatformDataMac.cpp84
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/mac/FontMac.cpp182
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/mac/GlyphPageTreeNodeMac.cpp168
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/mac/IntPointMac.mm44
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/mac/IntRectMac.mm49
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/mac/IntSizeMac.mm44
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/mac/SimpleFontDataCoreText.cpp66
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/mac/SimpleFontDataMac.mm453
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/opentype/OpenTypeSanitizer.cpp76
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/opentype/OpenTypeSanitizer.h57
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/opentype/OpenTypeTypes.h101
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/opentype/OpenTypeUtilities.cpp224
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/opentype/OpenTypeUtilities.h41
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/opentype/OpenTypeVerticalData.cpp574
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/opentype/OpenTypeVerticalData.h77
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/skia/FontCacheSkia.cpp179
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/skia/FontCacheSkiaWin.cpp219
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/skia/FontCustomPlatformDataSkia.cpp86
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/skia/FontPlatformDataSkia.cpp61
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/skia/GlyphPageTreeNodeSkia.cpp78
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/skia/NativeImageSkia.cpp554
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/skia/NativeImageSkia.h205
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/skia/OpaqueRegionSkia.cpp437
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/skia/OpaqueRegionSkia.h102
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/skia/SimpleFontDataSkia.cpp284
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/skia/SkiaFontWin.cpp200
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/skia/SkiaFontWin.h71
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/skia/SkiaSharedBufferStream.cpp120
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/skia/SkiaSharedBufferStream.h80
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/skia/SkiaUtils.cpp184
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/skia/SkiaUtils.h83
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/transforms/AffineTransform.cpp425
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/transforms/AffineTransform.h189
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/transforms/IdentityTransformOperation.h67
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/transforms/InterpolatedTransformOperation.cpp74
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/transforms/InterpolatedTransformOperation.h72
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/transforms/Matrix3DTransformOperation.cpp56
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/transforms/Matrix3DTransformOperation.h74
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/transforms/MatrixTransformOperation.cpp52
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/transforms/MatrixTransformOperation.h101
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/transforms/PerspectiveTransformOperation.cpp66
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/transforms/PerspectiveTransformOperation.h76
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/transforms/RotateTransformOperation.cpp96
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/transforms/RotateTransformOperation.h90
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/transforms/ScaleTransformOperation.cpp48
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/transforms/ScaleTransformOperation.h87
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/transforms/SkewTransformOperation.cpp43
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/transforms/SkewTransformOperation.h77
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/transforms/TransformOperation.h88
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/transforms/TransformOperations.cpp119
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/transforms/TransformOperations.h86
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/transforms/TransformState.cpp209
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/transforms/TransformState.h122
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/transforms/TransformationMatrix.cpp1531
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/transforms/TransformationMatrix.h364
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/transforms/TranslateTransformOperation.cpp43
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/transforms/TranslateTransformOperation.h93
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/graphics/win/FontCustomPlatformDataWin.cpp136
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/image-decoders/ImageDecoder.cpp203
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/image-decoders/ImageDecoder.h476
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/image-decoders/ImageDecoderTest.cpp248
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/image-decoders/ImageFrame.cpp159
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/image-decoders/OWNERS1
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/image-decoders/bmp/BMPImageDecoder.cpp157
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/image-decoders/bmp/BMPImageDecoder.h85
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/image-decoders/bmp/BMPImageReader.cpp737
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/image-decoders/bmp/BMPImageReader.h356
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/image-decoders/gif/GIFImageDecoder.cpp386
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/image-decoders/gif/GIFImageDecoder.h90
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/image-decoders/gif/GIFImageDecoderTest.cpp453
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/image-decoders/gif/GIFImageReader.cpp791
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/image-decoders/gif/GIFImageReader.h367
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/image-decoders/ico/ICOImageDecoder.cpp347
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/image-decoders/ico/ICOImageDecoder.h156
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/image-decoders/jpeg/JPEGImageDecoder.cpp801
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/image-decoders/jpeg/JPEGImageDecoder.h72
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/image-decoders/jpeg/JPEGImageDecoderTest.cpp185
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/image-decoders/png/PNGImageDecoder.cpp531
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/image-decoders/png/PNGImageDecoder.h73
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/image-decoders/webp/WEBPImageDecoder.cpp535
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/image-decoders/webp/WEBPImageDecoder.h89
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/image-decoders/webp/WEBPImageDecoderTest.cpp506
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/image-encoders/skia/JPEGImageEncoder.cpp202
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/image-encoders/skia/JPEGImageEncoder.h54
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/image-encoders/skia/PNGImageEncoder.cpp132
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/image-encoders/skia/PNGImageEncoder.h51
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/image-encoders/skia/WEBPImageEncoder.cpp133
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/image-encoders/skia/WEBPImageEncoder.h54
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/mac/BlockExceptions.h33
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/mac/BlockExceptions.mm38
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/mac/EmptyProtocolDefinitions.h43
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/mac/FoundationExtras.h40
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/mac/KillRingMac.mm83
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/mac/LocalCurrentGraphicsContext.h57
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/mac/LocalCurrentGraphicsContext.mm72
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/mac/NSScrollerImpDetails.h120
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/mac/NSScrollerImpDetails.mm57
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/mac/ScrollAnimatorMac.h162
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/mac/ScrollAnimatorMac.mm1303
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/mac/ScrollElasticityController.h103
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/mac/ScrollElasticityController.mm428
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/mac/ThemeMac.h12
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/mac/ThemeMac.mm75
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/mac/WebCoreNSCellExtras.h37
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/mac/WebFontCache.h37
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/mac/WebFontCache.mm294
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/mediastream/MediaConstraints.h66
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/mediastream/MediaStreamCenter.cpp31
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/mediastream/MediaStreamCenter.h17
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/mediastream/MediaStreamComponent.cpp97
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/mediastream/MediaStreamComponent.h110
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/mediastream/MediaStreamDescriptor.cpp15
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/mediastream/MediaStreamDescriptor.h8
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/mediastream/MediaStreamSource.cpp108
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/mediastream/MediaStreamSource.h119
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/mediastream/RTCConfiguration.h84
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/mediastream/RTCDTMFSenderHandler.cpp80
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/mediastream/RTCDTMFSenderHandler.h64
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/mediastream/RTCDTMFSenderHandlerClient.h42
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/mediastream/RTCDataChannelHandler.cpp11
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/mediastream/RTCDataChannelHandler.h13
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/mediastream/RTCPeerConnectionHandler.cpp49
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/mediastream/RTCPeerConnectionHandler.h39
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/mediastream/RTCPeerConnectionHandlerClient.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/mediastream/RTCSessionDescriptionRequest.h69
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/mediastream/RTCStatsResponseBase.h45
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/mediastream/RTCVoidRequest.h65
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/midi/MIDIAccessor.cpp89
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/midi/MIDIAccessor.h67
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/midi/MIDIAccessorClient.h49
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/midi/OWNERS2
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/mock/DeviceOrientationClientMock.cpp72
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/mock/DeviceOrientationClientMock.h67
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/mock/GeolocationClientMock.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/mock/MIDIClientMock.cpp66
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/mock/MIDIClientMock.h56
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/mock/PlatformSpeechSynthesizerMock.cpp100
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/mock/PlatformSpeechSynthesizerMock.h56
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/mock/ScrollbarThemeMock.cpp63
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/mock/ScrollbarThemeMock.h55
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/mock/ScrollbarThemeOverlayMock.h47
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/network/BlobData.cpp117
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/network/BlobData.h219
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/network/DNS.cpp45
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/network/DNS.h38
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/network/FormData.cpp263
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/network/FormData.h163
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/network/FormDataBuilder.cpp220
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/network/FormDataBuilder.h58
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/network/HTTPHeaderMap.cpp116
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/network/HTTPHeaderMap.h66
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/network/HTTPParsers.cpp687
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/network/HTTPParsers.h90
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/network/HTTPRequest.cpp118
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/network/HTTPRequest.h81
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/network/MIMEHeader.cpp138
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/network/MIMEHeader.h85
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/network/NetworkStateNotifier.cpp60
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/network/NetworkStateNotifier.h62
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/network/ParsedContentType.cpp255
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/network/ParsedContentType.h70
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/network/ProxyServer.cpp75
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/network/ProxyServer.h79
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/network/ResourceError.cpp86
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/network/ResourceError.h92
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/network/ResourceLoadInfo.h51
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/network/ResourceLoadPriority.h46
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/network/ResourceLoadTiming.h123
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/network/ResourceRequest.cpp345
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/network/ResourceRequest.h271
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/network/ResourceResponse.cpp679
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/network/ResourceResponse.h312
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/network/SocketStreamError.cpp56
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/network/SocketStreamError.h75
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/network/SocketStreamHandle.cpp281
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/network/SocketStreamHandle.h81
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/network/SocketStreamHandleClient.h56
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/network/SocketStreamHandleInternal.h85
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/sql/SQLValue.cpp56
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/sql/SQLValue.h58
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/sql/SQLiteAuthorizer.cpp40
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/sql/SQLiteDatabase.cpp499
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/sql/SQLiteDatabase.h170
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/sql/SQLiteFileSystem.h117
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/sql/SQLiteStatement.cpp534
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/sql/SQLiteStatement.h108
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/sql/SQLiteTransaction.cpp103
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/sql/SQLiteTransaction.h57
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/sql/chromium/SQLiteFileSystemChromium.cpp100
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/sql/chromium/SQLiteFileSystemChromiumPosix.cpp197
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/sql/chromium/SQLiteFileSystemChromiumWin.cpp169
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/text/AtomicStringKeyedMRUCache.h73
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/text/BidiContext.cpp111
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/text/BidiContext.h83
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/text/BidiResolver.h928
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/text/BidiRunList.h253
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/text/DateTimeFormat.cpp279
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/text/DateTimeFormat.h110
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/text/DateTimeFormatTest.cpp337
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/text/DecodeEscapeSequences.h158
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/text/LineBreakIteratorPoolICU.h111
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/text/LineEnding.cpp233
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/text/LineEnding.h55
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/text/LocaleICU.cpp434
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/text/LocaleICU.h117
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/text/LocaleToScriptMapping.h44
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/text/LocaleToScriptMappingDefault.cpp404
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/text/NonCJKGlyphOrientation.h35
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/text/ParserUtilities.h68
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/text/PlatformLocale.cpp390
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/text/PlatformLocale.h172
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/text/QuotedPrintable.cpp155
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/text/QuotedPrintable.h46
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/text/RegularExpression.cpp110
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/text/RegularExpression.h57
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/text/SegmentedString.cpp366
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/text/SegmentedString.h422
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/text/SuffixTree.h122
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/text/TextBoundaries.cpp104
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/text/TextBoundaries.h46
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/text/TextBreakIterator.cpp70
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/text/TextBreakIterator.h242
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/text/TextBreakIteratorICU.cpp829
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/text/TextBreakIteratorInternalICU.cpp50
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/text/TextBreakIteratorInternalICU.h34
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/text/TextCheckerClient.h52
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/text/TextChecking.h115
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/text/TextDirection.h37
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/text/TextEncodingDetector.h50
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/text/TextEncodingDetectorICU.cpp117
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/text/TextStream.cpp135
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/text/TextStream.h64
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/text/UnicodeBidi.h52
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/text/UnicodeRange.cpp462
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/text/UnicodeRange.h120
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/text/WritingMode.h60
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/text/cf/AtomicStringCF.cpp56
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/text/cf/StringCF.cpp64
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/text/cf/StringImplCF.cpp162
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/text/mac/LocaleMac.h104
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/text/mac/LocaleMac.mm332
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/text/mac/StringImplMac.mm34
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/text/mac/StringMac.mm51
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/text/transcoder/FontTranscoder.cpp106
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/text/transcoder/FontTranscoder.h71
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/text/win/LocaleWin.cpp587
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/text/win/LocaleWin.h101
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/win/HWndDC.h89
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/win/SystemInfo.cpp166
-rw-r--r--chromium/third_party/WebKit/Source/core/platform/win/SystemInfo.h70
-rw-r--r--chromium/third_party/WebKit/Source/core/plugins/DOMMimeType.cpp8
-rw-r--r--chromium/third_party/WebKit/Source/core/plugins/DOMMimeType.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/plugins/DOMMimeTypeArray.cpp4
-rw-r--r--chromium/third_party/WebKit/Source/core/plugins/DOMMimeTypeArray.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/plugins/DOMPlugin.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/plugins/DOMPlugin.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/plugins/DOMPluginArray.cpp5
-rw-r--r--chromium/third_party/WebKit/Source/core/plugins/DOMPluginArray.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/plugins/PluginData.cpp143
-rw-r--r--chromium/third_party/WebKit/Source/core/plugins/PluginData.h80
-rw-r--r--chromium/third_party/WebKit/Source/core/plugins/PluginListBuilder.cpp63
-rw-r--r--chromium/third_party/WebKit/Source/core/plugins/PluginListBuilder.h55
-rw-r--r--chromium/third_party/WebKit/Source/core/plugins/PluginOcclusionSupport.cpp6
-rw-r--r--chromium/third_party/WebKit/Source/core/plugins/PluginView.h24
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/AbstractInlineTextBox.cpp164
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/AbstractInlineTextBox.h98
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/AutoTableLayout.h9
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/BidiRun.cpp3
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/BidiRun.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/ClipPathOperation.h25
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/ClipRect.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/ColumnInfo.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/CompositedLayerMapping.cpp2228
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/CompositedLayerMapping.h359
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/CompositedLayerMappingPtr.h39
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/CompositingReasons.h38
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/CompositingState.h29
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/CounterNode.cpp6
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/CounterNode.h8
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/EllipsisBox.cpp65
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/EllipsisBox.h8
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/FastTextAutosizer.cpp139
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/FastTextAutosizer.h91
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/FilterEffectRenderer.cpp76
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/FilterEffectRenderer.h18
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/FixedTableLayout.cpp23
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/FixedTableLayout.h7
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/FloatingObjects.cpp134
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/FloatingObjects.h59
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/FlowThreadController.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/GapRects.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/GraphicsContextAnnotator.cpp134
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/GraphicsContextAnnotator.h68
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/HitTestLocation.h8
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/HitTestRequest.h5
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/HitTestResult.cpp71
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/HitTestResult.h20
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/HitTestingTransformState.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/HitTestingTransformState.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/ImageQualityController.cpp6
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/ImageQualityController.h14
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/InlineBox.cpp12
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/InlineBox.h36
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/InlineFlowBox.cpp6
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/InlineFlowBox.h18
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/InlineIterator.h171
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/InlineTextBox.cpp158
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/InlineTextBox.h31
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/LayerPaintingInfo.h100
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/LayoutRectRecorder.cpp76
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/LayoutRectRecorder.h58
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/LayoutRepainter.cpp8
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/LayoutRepainter.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/LayoutState.cpp11
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/LayoutState.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/LineWidth.cpp48
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/LineWidth.h30
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/OrderIterator.cpp44
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/OrderIterator.h19
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/PaintInfo.h8
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/PaintPhase.h3
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/PointerEventsHitRules.cpp9
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/PointerEventsHitRules.h3
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderBR.h16
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderBlock.cpp1572
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderBlock.h331
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderBlockFlow.cpp1424
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderBlockFlow.h290
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderBlockLineLayout.cpp1483
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderBox.cpp571
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderBox.h73
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderBoxModelObject.cpp232
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderBoxModelObject.h37
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderBoxRegionInfo.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderButton.cpp1
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderButton.h17
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderCombineText.cpp4
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderCombineText.h17
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderCounter.cpp137
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderCounter.h15
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderDeprecatedFlexibleBox.cpp22
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderDetailsMarker.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderDetailsMarker.h15
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderEmbeddedObject.cpp53
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderEmbeddedObject.h12
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderFieldset.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderFieldset.h9
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderFileUploadControl.cpp18
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderFileUploadControl.h18
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderFlexibleBox.h15
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderFlowThread.cpp66
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderFlowThread.h21
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderFrame.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderFrame.h9
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderFrameSet.cpp23
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderFrameSet.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderFullScreen.h8
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderGeometryMap.cpp46
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderGeometryMap.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderGrid.cpp302
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderGrid.h81
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderHTMLCanvas.cpp11
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderHTMLCanvas.h9
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderIFrame.cpp6
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderIFrame.h16
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderImage.cpp89
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderImage.h22
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderImageResource.cpp13
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderImageResource.h9
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderImageResourceStyleImage.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderInline.cpp28
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderInline.h15
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderInputSpeech.cpp14
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderLayer.cpp2703
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderLayer.h539
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderLayerBacking.cpp1974
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderLayerBacking.h331
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderLayerClipper.cpp191
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderLayerClipper.h104
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderLayerCompositor.cpp1302
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderLayerCompositor.h109
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderLayerFilterInfo.cpp21
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderLayerFilterInfo.h6
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderLayerModelObject.cpp59
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderLayerModelObject.h33
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderLayerReflectionInfo.cpp148
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderLayerReflectionInfo.h86
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderLayerRepainter.cpp259
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderLayerRepainter.h105
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderLayerScrollableArea.cpp916
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderLayerScrollableArea.h125
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderLayerStackingNode.cpp661
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderLayerStackingNode.h276
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderLayerStackingNodeIterator.cpp140
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderLayerStackingNodeIterator.h92
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderListBox.cpp87
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderListBox.h15
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderListItem.cpp26
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderListItem.h13
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderListMarker.cpp17
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderListMarker.h15
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderMarquee.cpp40
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderMarquee.h28
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderMedia.cpp9
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderMedia.h12
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderMediaControlElements.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderMediaControls.cpp427
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderMediaControls.h11
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderMediaControlsChromium.cpp452
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderMediaControlsChromium.h51
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderMenuList.cpp27
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderMenuList.h18
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderMeter.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderMultiColumnBlock.h17
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderMultiColumnSet.cpp70
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderMultiColumnSet.h15
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderNamedFlowFragment.cpp108
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderNamedFlowFragment.h74
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderNamedFlowThread.cpp21
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderNamedFlowThread.h17
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderObject.cpp763
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderObject.h195
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderObjectChildList.cpp6
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderOverflow.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderOverflowTest.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderPart.cpp6
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderPart.h9
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderProgress.cpp5
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderProgress.h11
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderQuote.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderQuote.h9
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderRegion.cpp76
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderRegion.h43
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderReplaced.cpp24
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderReplica.cpp7
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderRuby.cpp4
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderRubyRun.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderRubyRun.h14
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderRubyText.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderScrollbar.cpp6
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderScrollbar.h13
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderScrollbarPart.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderScrollbarPart.h17
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderScrollbarTheme.cpp4
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderScrollbarTheme.h5
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderSearchField.h9
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderSelectionInfo.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderSlider.cpp7
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderSlider.h11
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderTable.cpp38
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderTable.h15
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderTableCaption.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderTableCaption.h15
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderTableCell.cpp21
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderTableCell.h17
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderTableCol.cpp8
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderTableCol.h15
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderTableRow.cpp4
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderTableRow.h15
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderTableSection.cpp14
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderTableSection.h15
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderText.cpp116
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderText.h24
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderTextControl.cpp11
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderTextControl.h19
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderTextControlMultiLine.cpp6
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderTextControlMultiLine.h14
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderTextControlSingleLine.cpp31
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderTextControlSingleLine.h18
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderTextFragment.cpp26
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderTextFragment.h18
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderTextTrackCue.cpp293
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderTextTrackCue.h65
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderTheme.cpp171
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderTheme.h22
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderThemeChromiumAndroid.cpp26
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderThemeChromiumAndroid.h1
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderThemeChromiumDefault.cpp202
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderThemeChromiumDefault.h14
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderThemeChromiumFontProviderLinux.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderThemeChromiumFontProviderWin.cpp8
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderThemeChromiumMac.h6
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderThemeChromiumMac.mm82
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderThemeChromiumSkia.cpp44
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderThemeChromiumWin.cpp55
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderThemeChromiumWin.h1
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderTreeAsText.cpp175
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderTreeAsText.h33
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderVTTCue.cpp272
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderVTTCue.h65
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderVideo.cpp51
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderVideo.h17
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderView.cpp186
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderView.h55
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderWidget.cpp90
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderWidget.h56
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderingConfiguration.cpp56
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderingConfiguration.h60
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderingNodeProxy.cpp52
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RenderingNodeProxy.h71
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RootInlineBox.cpp31
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/RootInlineBox.h9
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/ScrollBehavior.cpp91
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/ScrollBehavior.h5
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/SubtreeLayoutScope.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/TableLayout.h1
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/TextAutosizer.cpp129
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/TextAutosizer.h23
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/TrailingFloatsRootInlineBox.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/VerticalPositionCache.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/animation/WebAnimationProvider.cpp214
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/animation/WebAnimationProvider.h76
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/break_lines.cpp4
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/line/BreakingContextInlineHeaders.h1145
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/line/LineInfo.h77
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/shapes/BoxShape.cpp130
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/shapes/BoxShape.h63
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/shapes/BoxShapeTest.cpp113
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/shapes/PolygonShape.cpp6
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/shapes/PolygonShape.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/shapes/RasterShape.cpp126
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/shapes/RasterShape.h38
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/shapes/RectangleShape.cpp146
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/shapes/RectangleShape.h48
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/shapes/Shape.cpp42
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/shapes/Shape.h14
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/shapes/ShapeInfo.cpp42
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/shapes/ShapeInfo.h74
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/shapes/ShapeInsideInfo.cpp39
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/shapes/ShapeInsideInfo.h23
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/shapes/ShapeInterval.h1
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/shapes/ShapeOutsideInfo.cpp54
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/shapes/ShapeOutsideInfo.h18
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/style/BasicShapes.cpp48
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/style/BasicShapes.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/style/BorderData.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/style/BorderImageLength.h89
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/style/BorderImageLengthBox.h99
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/style/BorderValue.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/style/CursorData.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/style/FillLayer.cpp49
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/style/FillLayer.h40
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/style/GridCoordinate.h52
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/style/GridLength.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/style/GridPosition.h21
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/style/GridTrackSize.h46
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/style/KeyframeList.cpp31
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/style/KeyframeList.h7
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/style/NinePieceImage.cpp6
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/style/NinePieceImage.h30
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/style/RenderStyle.cpp207
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/style/RenderStyle.h185
-rwxr-xr-x[-rw-r--r--]chromium/third_party/WebKit/Source/core/rendering/style/RenderStyleConstants.h36
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/style/SVGRenderStyle.cpp4
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/style/SVGRenderStyle.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/style/ShadowData.cpp65
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/style/ShadowData.h59
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/style/ShadowList.cpp107
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/style/ShadowList.h76
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/style/ShapeValue.h21
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/style/StyleBackgroundData.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/style/StyleBackgroundData.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/style/StyleBoxData.cpp1
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/style/StyleBoxData.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/style/StyleCustomFilterProgram.h12
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/style/StyleCustomFilterProgramCache.cpp3
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/style/StyleCustomFilterProgramCache.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/style/StyleFetchedImage.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/style/StyleFetchedImageSet.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/style/StyleFilterData.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/style/StyleFlexibleBoxData.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/style/StyleImage.h11
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/style/StyleInheritedData.h6
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/style/StyleMarqueeData.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/style/StyleMultiColData.cpp11
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/style/StyleMultiColData.h3
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/style/StylePendingImage.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/style/StyleRareInheritedData.cpp16
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/style/StyleRareInheritedData.h19
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/style/StyleRareNonInheritedData.cpp14
-rwxr-xr-x[-rw-r--r--]chromium/third_party/WebKit/Source/core/rendering/style/StyleRareNonInheritedData.h14
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/style/StyleReflection.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/style/StyleSurroundData.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/style/StyleTransformData.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/style/StyleVisualData.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/ReferenceFilterBuilder.cpp42
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/ReferenceFilterBuilder.h12
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGBlock.cpp26
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGBlock.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGContainer.cpp14
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGContainer.h15
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGForeignObject.cpp4
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGGradientStop.cpp3
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGGradientStop.h6
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGHiddenContainer.cpp4
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGImage.cpp11
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGImage.h17
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGInline.cpp6
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGInline.h1
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGInlineText.cpp9
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGInlineText.h16
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGModelObject.cpp18
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGModelObject.h1
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGPath.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGPath.h6
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResource.cpp6
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResource.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceClipper.cpp64
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceClipper.h18
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceContainer.cpp43
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceContainer.h21
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceFilter.cpp60
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceFilter.h19
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceFilterPrimitive.cpp43
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceFilterPrimitive.h5
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceGradient.cpp8
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceGradient.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceLinearGradient.cpp3
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceLinearGradient.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceMarker.cpp14
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceMarker.h12
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceMasker.cpp93
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceMasker.h24
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourcePattern.cpp19
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourcePattern.h11
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceRadialGradient.cpp3
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceRadialGradient.h8
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceSolidColor.cpp8
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceSolidColor.h7
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGRoot.cpp32
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGRoot.h21
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGShape.cpp32
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGShape.h22
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGText.cpp26
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGText.h17
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGTextPath.cpp10
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGTextPath.h11
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGViewportContainer.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGViewportContainer.h15
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/SVGInlineFlowBox.h6
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/SVGInlineTextBox.cpp33
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/SVGInlineTextBox.h8
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/SVGMarkerData.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/SVGPathData.cpp6
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/SVGRenderSupport.cpp5
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/SVGRenderTreeAsText.cpp18
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/SVGRenderTreeAsText.h3
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/SVGRenderingContext.cpp56
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/SVGRenderingContext.h6
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/SVGResources.cpp82
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/SVGResources.h5
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/SVGResourcesCache.cpp20
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/SVGResourcesCycleSolver.cpp4
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/SVGRootInlineBox.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/SVGRootInlineBox.h8
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/SVGSubpathData.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/SVGTextFragment.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/SVGTextLayoutEngine.h3
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/SVGTextLayoutEngineBaseline.cpp4
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/SVGTextLayoutEngineSpacing.cpp9
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/SVGTextMetrics.h7
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/SVGTextMetricsBuilder.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/SVGTextQuery.cpp3
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/SVGTextRunRenderingContext.cpp12
-rw-r--r--chromium/third_party/WebKit/Source/core/rendering/svg/SVGTextRunRenderingContext.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/scripts/Hasher.pm93
-rw-r--r--chromium/third_party/WebKit/Source/core/scripts/InFilesCompiler.pm182
-rw-r--r--chromium/third_party/WebKit/Source/core/scripts/InFilesParser.pm154
-rw-r--r--chromium/third_party/WebKit/Source/core/scripts/StaticString.pm49
-rw-r--r--chromium/third_party/WebKit/Source/core/scripts/action_derivedsourcesallinone.py225
-rw-r--r--chromium/third_party/WebKit/Source/core/scripts/action_makenames.py182
-rw-r--r--chromium/third_party/WebKit/Source/core/scripts/action_useragentstylesheets.py124
-rwxr-xr-xchromium/third_party/WebKit/Source/core/scripts/check_objc_rename.sh79
-rw-r--r--chromium/third_party/WebKit/Source/core/scripts/in_file.py160
-rw-r--r--chromium/third_party/WebKit/Source/core/scripts/in_file_unittest.py77
-rw-r--r--chromium/third_party/WebKit/Source/core/scripts/in_generator.py119
-rw-r--r--chromium/third_party/WebKit/Source/core/scripts/license.py62
-rw-r--r--chromium/third_party/WebKit/Source/core/scripts/list_idl_files_with_partial_interface.py44
-rwxr-xr-xchromium/third_party/WebKit/Source/core/scripts/make-file-arrays.py136
-rw-r--r--chromium/third_party/WebKit/Source/core/scripts/make-hash-tools.pl44
-rwxr-xr-xchromium/third_party/WebKit/Source/core/scripts/make_css_property_names.py257
-rwxr-xr-xchromium/third_party/WebKit/Source/core/scripts/make_css_value_keywords.py177
-rw-r--r--chromium/third_party/WebKit/Source/core/scripts/make_event_factory.py100
-rwxr-xr-xchromium/third_party/WebKit/Source/core/scripts/make_internal_runtime_flags.py64
-rwxr-xr-xchromium/third_party/WebKit/Source/core/scripts/make_names.pl1292
-rwxr-xr-xchromium/third_party/WebKit/Source/core/scripts/make_runtime_features.py92
-rwxr-xr-xchromium/third_party/WebKit/Source/core/scripts/make_style_builder.py128
-rw-r--r--chromium/third_party/WebKit/Source/core/scripts/make_style_shorthands.py96
-rwxr-xr-xchromium/third_party/WebKit/Source/core/scripts/make_token_matcher.py231
-rwxr-xr-xchromium/third_party/WebKit/Source/core/scripts/make_token_matcher_unittest.py243
-rw-r--r--chromium/third_party/WebKit/Source/core/scripts/name_macros.py175
-rw-r--r--chromium/third_party/WebKit/Source/core/scripts/name_utilities.py40
-rw-r--r--chromium/third_party/WebKit/Source/core/scripts/preprocessor.pm89
-rw-r--r--chromium/third_party/WebKit/Source/core/scripts/rule_bison.py105
-rw-r--r--chromium/third_party/WebKit/Source/core/scripts/template_expander.py54
-rw-r--r--chromium/third_party/WebKit/Source/core/scripts/templates/InternalRuntimeFlags.h.tmpl39
-rw-r--r--chromium/third_party/WebKit/Source/core/scripts/templates/InternalRuntimeFlags.idl.tmpl14
-rw-r--r--chromium/third_party/WebKit/Source/core/scripts/templates/RuntimeEnabledFeatures.cpp.tmpl24
-rw-r--r--chromium/third_party/WebKit/Source/core/scripts/templates/RuntimeEnabledFeatures.h.tmpl47
-rw-r--r--chromium/third_party/WebKit/Source/core/scripts/templates/StyleBuilder.cpp.tmpl85
-rw-r--r--chromium/third_party/WebKit/Source/core/scripts/templates/StyleBuilderFunctions.cpp.tmpl519
-rw-r--r--chromium/third_party/WebKit/Source/core/scripts/templates/StyleBuilderFunctions.h.tmpl29
-rw-r--r--chromium/third_party/WebKit/Source/core/scripts/templates/StylePropertyShorthand.cpp.tmpl85
-rw-r--r--chromium/third_party/WebKit/Source/core/scripts/templates/StylePropertyShorthand.h.tmpl88
-rw-r--r--chromium/third_party/WebKit/Source/core/scripts/templates/macros.tmpl48
-rw-r--r--chromium/third_party/WebKit/Source/core/scripts/xxd.pl45
-rw-r--r--chromium/third_party/WebKit/Source/core/speech/SpeechInput.cpp130
-rw-r--r--chromium/third_party/WebKit/Source/core/speech/SpeechInput.h90
-rw-r--r--chromium/third_party/WebKit/Source/core/speech/SpeechInputClient.h (renamed from chromium/third_party/WebKit/Source/core/page/SpeechInputClient.h)0
-rw-r--r--chromium/third_party/WebKit/Source/core/speech/SpeechInputEvent.cpp74
-rw-r--r--chromium/third_party/WebKit/Source/core/speech/SpeechInputEvent.h59
-rw-r--r--chromium/third_party/WebKit/Source/core/speech/SpeechInputEvent.idl (renamed from chromium/third_party/WebKit/Source/core/page/SpeechInputEvent.idl)0
-rw-r--r--chromium/third_party/WebKit/Source/core/speech/SpeechInputListener.h67
-rw-r--r--chromium/third_party/WebKit/Source/core/speech/SpeechInputResult.cpp62
-rw-r--r--chromium/third_party/WebKit/Source/core/speech/SpeechInputResult.h (renamed from chromium/third_party/WebKit/Source/core/page/SpeechInputResult.h)0
-rw-r--r--chromium/third_party/WebKit/Source/core/speech/SpeechInputResult.idl (renamed from chromium/third_party/WebKit/Source/core/page/SpeechInputResult.idl)0
-rw-r--r--chromium/third_party/WebKit/Source/core/speech/SpeechInputResultList.cpp56
-rw-r--r--chromium/third_party/WebKit/Source/core/speech/SpeechInputResultList.h56
-rw-r--r--chromium/third_party/WebKit/Source/core/speech/SpeechInputResultList.idl (renamed from chromium/third_party/WebKit/Source/core/page/SpeechInputResultList.idl)0
-rw-r--r--chromium/third_party/WebKit/Source/core/storage/Storage.cpp56
-rw-r--r--chromium/third_party/WebKit/Source/core/storage/Storage.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/storage/Storage.idl10
-rw-r--r--chromium/third_party/WebKit/Source/core/storage/StorageEvent.cpp4
-rw-r--r--chromium/third_party/WebKit/Source/core/storage/StorageEvent.h3
-rw-r--r--chromium/third_party/WebKit/Source/core/storage/StorageEvent.idl4
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/ColorDistance.cpp19
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/ColorDistance.h5
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/PatternAttributes.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGAElement.cpp29
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGAElement.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGAltGlyphDefElement.cpp9
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGAltGlyphDefElement.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGAltGlyphElement.cpp17
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGAltGlyphElement.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGAltGlyphElement.idl4
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGAltGlyphItemElement.cpp9
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGAltGlyphItemElement.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGAngle.cpp12
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGAngle.idl2
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGAnimateColorElement.cpp13
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGAnimateColorElement.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGAnimateElement.cpp20
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGAnimateElement.h16
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGAnimateMotionElement.cpp17
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGAnimateMotionElement.h8
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGAnimateTransformElement.cpp13
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGAnimateTransformElement.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGAnimatedAngle.cpp7
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGAnimatedBoolean.idl2
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGAnimatedEnumeration.idl2
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGAnimatedInteger.idl2
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGAnimatedNumber.idl2
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGAnimatedPointList.cpp1
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGAnimatedString.idl2
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGAnimatedType.cpp6
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGAnimatedType.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGAnimationElement.cpp6
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGAnimationElement.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGAttributeNames.in (renamed from chromium/third_party/WebKit/Source/core/svg/svgattrs.in)0
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGCircleElement.cpp20
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGCircleElement.h14
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGCircleElement.idl2
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGClipPathElement.cpp15
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGClipPathElement.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGColor.cpp14
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGColor.h6
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGComponentTransferFunctionElement.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGCursorElement.cpp16
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGCursorElement.h6
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGDefsElement.cpp9
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGDefsElement.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGDescElement.cpp9
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGDescElement.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGDocument.cpp17
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGDocument.h19
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGDocument.idl4
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGDocumentExtensions.cpp33
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGDocumentExtensions.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGElement.cpp152
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGElement.h64
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGElement.idl3
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGElementInstance.cpp20
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGElementInstance.h24
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGElementInstanceList.cpp4
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGElementInstanceList.h3
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGElementRareData.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGEllipseElement.cpp20
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGEllipseElement.h14
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGEllipseElement.idl2
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGExternalResourcesRequired.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFEBlendElement.cpp11
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFEBlendElement.h6
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFEColorMatrixElement.cpp11
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFEColorMatrixElement.h6
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFEComponentTransferElement.cpp11
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFEComponentTransferElement.h6
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFECompositeElement.cpp11
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFECompositeElement.h6
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFEConvolveMatrixElement.cpp17
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFEConvolveMatrixElement.h6
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFEDiffuseLightingElement.cpp15
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFEDiffuseLightingElement.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFEDisplacementMapElement.cpp11
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFEDisplacementMapElement.h6
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFEDistantLightElement.cpp14
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFEDistantLightElement.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFEDropShadowElement.cpp9
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFEDropShadowElement.h6
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFEFloodElement.cpp9
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFEFloodElement.h6
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFEFuncAElement.cpp10
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFEFuncAElement.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFEFuncBElement.cpp10
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFEFuncBElement.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFEFuncGElement.cpp10
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFEFuncGElement.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFEFuncRElement.cpp10
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFEFuncRElement.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFEGaussianBlurElement.cpp11
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFEGaussianBlurElement.h6
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFEImageElement.cpp13
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFEImageElement.h12
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFELightElement.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFEMergeElement.cpp11
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFEMergeElement.h6
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFEMergeNodeElement.cpp10
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFEMergeNodeElement.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFEMorphologyElement.cpp11
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFEMorphologyElement.h6
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFEOffsetElement.cpp11
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFEOffsetElement.h6
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFEPointLightElement.cpp14
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFEPointLightElement.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFESpecularLightingElement.cpp13
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFESpecularLightingElement.h12
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFESpotLightElement.cpp14
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFESpotLightElement.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFETileElement.cpp11
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFETileElement.h6
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFETurbulenceElement.cpp9
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFETurbulenceElement.h6
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFilterElement.cpp20
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFilterElement.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFilterPrimitiveStandardAttributes.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFitToViewBox.cpp6
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFitToViewBox.h7
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFontData.cpp10
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFontData.h20
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFontElement.cpp14
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFontElement.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFontFaceElement.cpp18
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFontFaceElement.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFontFaceFormatElement.cpp9
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFontFaceFormatElement.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFontFaceNameElement.cpp10
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFontFaceNameElement.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFontFaceSrcElement.cpp9
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFontFaceSrcElement.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFontFaceUriElement.cpp11
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGFontFaceUriElement.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGForeignObjectElement.cpp10
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGForeignObjectElement.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGGElement.cpp12
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGGElement.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGGeometryElement.cpp74
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGGeometryElement.h50
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGGeometryElement.idl34
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGGlyphElement.cpp10
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGGlyphElement.h12
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGGlyphMap.h6
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGGlyphRefElement.cpp10
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGGlyphRefElement.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGGlyphRefElement.idl2
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGGradientElement.cpp7
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGGradientElement.h9
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGGraphicsElement.cpp101
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGGraphicsElement.h27
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGGraphicsElement.idl5
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGHKernElement.cpp11
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGHKernElement.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGImageElement.cpp17
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGImageElement.h12
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGImageLoader.cpp6
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGLangSpace.cpp83
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGLangSpace.h50
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGLength.cpp51
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGLength.h26
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGLength.idl4
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGLengthContext.cpp109
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGLengthContext.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGLengthList.cpp6
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGLineElement.cpp20
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGLineElement.h14
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGLineElement.idl2
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGLinearGradientElement.cpp15
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGLinearGradientElement.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGLocatable.cpp116
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGLocatable.h65
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGMPathElement.cpp10
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGMPathElement.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGMarkerElement.cpp17
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGMarkerElement.h38
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGMaskElement.cpp16
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGMaskElement.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGMatrix.h16
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGMatrix.idl4
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGMetadataElement.cpp9
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGMetadataElement.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGMissingGlyphElement.cpp10
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGMissingGlyphElement.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGPaint.cpp11
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGPaint.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGParserUtilities.cpp207
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGParserUtilities.h17
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGPathBlender.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGPathBuilder.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGPathBuilder.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGPathByteStreamBuilder.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGPathByteStreamSource.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGPathConsumer.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGPathElement.cpp32
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGPathElement.h27
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGPathElement.idl88
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGPathParser.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGPathSeg.idl2
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGPathSegListBuilder.cpp1
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGPathSegListBuilder.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGPathSegListSource.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGPathSegWithContext.h7
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGPathStringBuilder.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGPathStringSource.cpp4
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGPathTraversalStateBuilder.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGPathUtilities.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGPatternElement.cpp24
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGPatternElement.h12
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGPoint.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGPoint.idl2
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGPointList.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGPolyElement.cpp23
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGPolyElement.h19
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGPolygonElement.cpp10
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGPolygonElement.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGPolygonElement.idl2
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGPolylineElement.cpp10
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGPolylineElement.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGPolylineElement.idl2
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGPreserveAspectRatio.cpp12
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGPreserveAspectRatio.idl4
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGRadialGradientElement.cpp15
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGRadialGradientElement.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGRect.h31
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGRectElement.cpp20
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGRectElement.h14
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGRectElement.idl2
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGRenderingIntent.idl5
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGSVGElement.cpp94
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGSVGElement.h21
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGScriptElement.cpp15
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGScriptElement.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGSetElement.cpp9
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGSetElement.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGStopElement.cpp10
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGStopElement.h11
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGStyleElement.cpp10
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGStyleElement.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGSwitchElement.cpp19
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGSwitchElement.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGSymbolElement.cpp10
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGSymbolElement.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGTSpanElement.cpp9
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGTSpanElement.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGTagNames.in95
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGTests.cpp20
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGTests.h1
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGTextContentElement.cpp30
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGTextContentElement.h7
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGTextElement.cpp10
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGTextElement.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGTextPathElement.cpp10
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGTextPathElement.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGTitleElement.cpp10
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGTitleElement.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGTransform.cpp6
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGTransform.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGTransformDistance.cpp6
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGTransformList.cpp9
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGTransformable.cpp240
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGTransformable.h60
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGURIReference.cpp3
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGURIReference.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGUnitTypes.idl5
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGUseElement.cpp51
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGUseElement.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGUseElement.idl2
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGVKernElement.cpp11
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGVKernElement.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGViewElement.cpp13
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGViewElement.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGViewSpec.cpp25
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGViewSpec.h26
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGViewSpec.idl2
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGZoomEvent.cpp7
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/SVGZoomEvent.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/animation/SMILTimeContainer.cpp14
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/animation/SMILTimeContainer.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/animation/SVGSMILElement.cpp61
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/animation/SVGSMILElement.h23
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/graphics/SVGImage.cpp56
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/graphics/SVGImage.h17
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/graphics/SVGImageCache.cpp10
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/graphics/SVGImageCache.h6
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/graphics/SVGImageChromeClient.h8
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/graphics/SVGImageForContainer.cpp11
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/graphics/SVGImageForContainer.h11
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/graphics/filters/SVGFEImage.cpp17
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/graphics/filters/SVGFEImage.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/graphics/filters/SVGFilter.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/graphics/filters/SVGFilterBuilder.cpp7
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/graphics/filters/SVGFilterBuilder.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/properties/SVGAnimatedEnumerationPropertyTearOff.h6
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/properties/SVGAnimatedListPropertyTearOff.h9
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/properties/SVGAnimatedProperty.cpp29
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/properties/SVGAnimatedProperty.h11
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/properties/SVGAnimatedPropertyMacros.h22
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/properties/SVGListProperty.h88
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/properties/SVGListPropertyTearOff.h49
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/properties/SVGMatrixTearOff.h53
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/properties/SVGPathSegListPropertyTearOff.cpp19
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/properties/SVGPathSegListPropertyTearOff.h25
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/properties/SVGPropertyTearOff.h25
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/properties/SVGStaticListPropertyTearOff.h36
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/properties/SVGStaticPropertyTearOff.h1
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/properties/SVGTransformListPropertyTearOff.h8
-rw-r--r--chromium/third_party/WebKit/Source/core/svg/svgtags.in97
-rw-r--r--chromium/third_party/WebKit/Source/core/testing/DummyPageHolder.cpp89
-rw-r--r--chromium/third_party/WebKit/Source/core/testing/DummyPageHolder.h88
-rw-r--r--chromium/third_party/WebKit/Source/core/testing/GCObservation.cpp7
-rw-r--r--chromium/third_party/WebKit/Source/core/testing/InspectorFrontendClientLocal.cpp10
-rw-r--r--chromium/third_party/WebKit/Source/core/testing/InternalProfilers.cpp8
-rw-r--r--chromium/third_party/WebKit/Source/core/testing/InternalSettings.cpp125
-rw-r--r--chromium/third_party/WebKit/Source/core/testing/InternalSettings.h13
-rw-r--r--chromium/third_party/WebKit/Source/core/testing/InternalSettings.idl8
-rw-r--r--chromium/third_party/WebKit/Source/core/testing/Internals.cpp915
-rw-r--r--chromium/third_party/WebKit/Source/core/testing/Internals.h40
-rw-r--r--chromium/third_party/WebKit/Source/core/testing/Internals.idl39
-rw-r--r--chromium/third_party/WebKit/Source/core/testing/MockPagePopupDriver.cpp11
-rw-r--r--chromium/third_party/WebKit/Source/core/testing/TypeConversions.h20
-rw-r--r--chromium/third_party/WebKit/Source/core/testing/TypeConversions.idl17
-rw-r--r--chromium/third_party/WebKit/Source/core/testing/UnitTestHelpers.cpp51
-rw-r--r--chromium/third_party/WebKit/Source/core/testing/UnitTestHelpers.h37
-rw-r--r--chromium/third_party/WebKit/Source/core/testing/v8/WebCoreTestSupport.cpp10
-rw-r--r--chromium/third_party/WebKit/Source/core/timing/MemoryInfo.cpp149
-rw-r--r--chromium/third_party/WebKit/Source/core/timing/MemoryInfo.h (renamed from chromium/third_party/WebKit/Source/core/page/MemoryInfo.h)0
-rw-r--r--chromium/third_party/WebKit/Source/core/timing/MemoryInfo.idl (renamed from chromium/third_party/WebKit/Source/core/page/MemoryInfo.idl)0
-rw-r--r--chromium/third_party/WebKit/Source/core/timing/Performance.cpp280
-rw-r--r--chromium/third_party/WebKit/Source/core/timing/Performance.h105
-rw-r--r--chromium/third_party/WebKit/Source/core/timing/Performance.idl66
-rw-r--r--chromium/third_party/WebKit/Source/core/timing/PerformanceEntry.cpp69
-rw-r--r--chromium/third_party/WebKit/Source/core/timing/PerformanceEntry.h (renamed from chromium/third_party/WebKit/Source/core/page/PerformanceEntry.h)0
-rw-r--r--chromium/third_party/WebKit/Source/core/timing/PerformanceEntry.idl39
-rw-r--r--chromium/third_party/WebKit/Source/core/timing/PerformanceMark.h52
-rw-r--r--chromium/third_party/WebKit/Source/core/timing/PerformanceMark.idl (renamed from chromium/third_party/WebKit/Source/core/page/PerformanceMark.idl)0
-rw-r--r--chromium/third_party/WebKit/Source/core/timing/PerformanceMeasure.h51
-rw-r--r--chromium/third_party/WebKit/Source/core/timing/PerformanceMeasure.idl (renamed from chromium/third_party/WebKit/Source/core/page/PerformanceMeasure.idl)0
-rw-r--r--chromium/third_party/WebKit/Source/core/timing/PerformanceNavigation.cpp82
-rw-r--r--chromium/third_party/WebKit/Source/core/timing/PerformanceNavigation.h63
-rw-r--r--chromium/third_party/WebKit/Source/core/timing/PerformanceNavigation.idl (renamed from chromium/third_party/WebKit/Source/core/page/PerformanceNavigation.idl)0
-rw-r--r--chromium/third_party/WebKit/Source/core/timing/PerformanceResourceTiming.cpp194
-rw-r--r--chromium/third_party/WebKit/Source/core/timing/PerformanceResourceTiming.h92
-rw-r--r--chromium/third_party/WebKit/Source/core/timing/PerformanceResourceTiming.idl (renamed from chromium/third_party/WebKit/Source/core/page/PerformanceResourceTiming.idl)0
-rw-r--r--chromium/third_party/WebKit/Source/core/timing/PerformanceTiming.cpp356
-rw-r--r--chromium/third_party/WebKit/Source/core/timing/PerformanceTiming.h86
-rw-r--r--chromium/third_party/WebKit/Source/core/timing/PerformanceTiming.idl (renamed from chromium/third_party/WebKit/Source/core/page/PerformanceTiming.idl)0
-rw-r--r--chromium/third_party/WebKit/Source/core/timing/PerformanceUserTiming.cpp208
-rw-r--r--chromium/third_party/WebKit/Source/core/timing/PerformanceUserTiming.h72
-rw-r--r--chromium/third_party/WebKit/Source/core/timing/ResourceTimingInfo.h88
-rw-r--r--chromium/third_party/WebKit/Source/core/workers/AbstractWorker.cpp43
-rw-r--r--chromium/third_party/WebKit/Source/core/workers/AbstractWorker.h27
-rw-r--r--chromium/third_party/WebKit/Source/core/workers/DedicatedWorkerGlobalScope.cpp15
-rw-r--r--chromium/third_party/WebKit/Source/core/workers/DedicatedWorkerGlobalScope.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/workers/DedicatedWorkerThread.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/workers/DefaultSharedWorkerRepository.h88
-rw-r--r--chromium/third_party/WebKit/Source/core/workers/SharedWorker.cpp39
-rw-r--r--chromium/third_party/WebKit/Source/core/workers/SharedWorker.h9
-rw-r--r--chromium/third_party/WebKit/Source/core/workers/SharedWorker.idl9
-rw-r--r--chromium/third_party/WebKit/Source/core/workers/SharedWorkerGlobalScope.cpp11
-rw-r--r--chromium/third_party/WebKit/Source/core/workers/SharedWorkerGlobalScope.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/workers/SharedWorkerRepository.h66
-rw-r--r--chromium/third_party/WebKit/Source/core/workers/SharedWorkerRepositoryClient.h61
-rw-r--r--chromium/third_party/WebKit/Source/core/workers/SharedWorkerThread.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/workers/Worker.cpp54
-rw-r--r--chromium/third_party/WebKit/Source/core/workers/Worker.h16
-rw-r--r--chromium/third_party/WebKit/Source/core/workers/Worker.idl7
-rw-r--r--chromium/third_party/WebKit/Source/core/workers/WorkerClients.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/workers/WorkerConsole.cpp23
-rw-r--r--chromium/third_party/WebKit/Source/core/workers/WorkerConsole.h8
-rw-r--r--chromium/third_party/WebKit/Source/core/workers/WorkerEventQueue.cpp19
-rw-r--r--chromium/third_party/WebKit/Source/core/workers/WorkerEventQueue.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/workers/WorkerGlobalScope.cpp75
-rw-r--r--chromium/third_party/WebKit/Source/core/workers/WorkerGlobalScope.h49
-rw-r--r--chromium/third_party/WebKit/Source/core/workers/WorkerGlobalScope.idl3
-rw-r--r--chromium/third_party/WebKit/Source/core/workers/WorkerGlobalScopeProxy.cpp38
-rw-r--r--chromium/third_party/WebKit/Source/core/workers/WorkerGlobalScopeProxy.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/workers/WorkerGlobalScopeProxyProvider.cpp51
-rw-r--r--chromium/third_party/WebKit/Source/core/workers/WorkerGlobalScopeProxyProvider.h61
-rw-r--r--chromium/third_party/WebKit/Source/core/workers/WorkerLoaderProxy.h13
-rw-r--r--chromium/third_party/WebKit/Source/core/workers/WorkerLocation.cpp75
-rw-r--r--chromium/third_party/WebKit/Source/core/workers/WorkerLocation.h25
-rw-r--r--chromium/third_party/WebKit/Source/core/workers/WorkerLocation.idl12
-rw-r--r--chromium/third_party/WebKit/Source/core/workers/WorkerMessagingProxy.cpp291
-rw-r--r--chromium/third_party/WebKit/Source/core/workers/WorkerMessagingProxy.h54
-rw-r--r--chromium/third_party/WebKit/Source/core/workers/WorkerNavigator.cpp48
-rw-r--r--chromium/third_party/WebKit/Source/core/workers/WorkerNavigator.h53
-rw-r--r--chromium/third_party/WebKit/Source/core/workers/WorkerNavigator.idl (renamed from chromium/third_party/WebKit/Source/core/page/WorkerNavigator.idl)0
-rw-r--r--chromium/third_party/WebKit/Source/core/workers/WorkerObjectProxy.cpp99
-rw-r--r--chromium/third_party/WebKit/Source/core/workers/WorkerObjectProxy.h37
-rw-r--r--chromium/third_party/WebKit/Source/core/workers/WorkerReportingProxy.h11
-rw-r--r--chromium/third_party/WebKit/Source/core/workers/WorkerRunLoop.cpp63
-rw-r--r--chromium/third_party/WebKit/Source/core/workers/WorkerRunLoop.h29
-rw-r--r--chromium/third_party/WebKit/Source/core/workers/WorkerScriptLoader.cpp21
-rw-r--r--chromium/third_party/WebKit/Source/core/workers/WorkerScriptLoader.h18
-rw-r--r--chromium/third_party/WebKit/Source/core/workers/WorkerSupplementable.h42
-rw-r--r--chromium/third_party/WebKit/Source/core/workers/WorkerThread.cpp22
-rw-r--r--chromium/third_party/WebKit/Source/core/workers/WorkerThread.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/workers/WorkerThreadStartupData.cpp1
-rw-r--r--chromium/third_party/WebKit/Source/core/workers/WorkerThreadStartupData.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/xml/DOMParser.cpp13
-rw-r--r--chromium/third_party/WebKit/Source/core/xml/DOMParser.h3
-rw-r--r--chromium/third_party/WebKit/Source/core/xml/DOMParser.idl2
-rw-r--r--chromium/third_party/WebKit/Source/core/xml/DocumentXPathEvaluator.cpp32
-rw-r--r--chromium/third_party/WebKit/Source/core/xml/DocumentXPathEvaluator.h19
-rw-r--r--chromium/third_party/WebKit/Source/core/xml/NativeXPathNSResolver.cpp4
-rw-r--r--chromium/third_party/WebKit/Source/core/xml/NativeXPathNSResolver.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/xml/XMLErrors.cpp4
-rw-r--r--chromium/third_party/WebKit/Source/core/xml/XMLHttpRequest.cpp623
-rw-r--r--chromium/third_party/WebKit/Source/core/xml/XMLHttpRequest.h100
-rw-r--r--chromium/third_party/WebKit/Source/core/xml/XMLHttpRequest.idl30
-rw-r--r--chromium/third_party/WebKit/Source/core/xml/XMLHttpRequestEventTarget.h11
-rw-r--r--chromium/third_party/WebKit/Source/core/xml/XMLHttpRequestProgressEvent.h6
-rw-r--r--chromium/third_party/WebKit/Source/core/xml/XMLHttpRequestProgressEventThrottle.cpp38
-rw-r--r--chromium/third_party/WebKit/Source/core/xml/XMLHttpRequestProgressEventThrottle.h9
-rw-r--r--chromium/third_party/WebKit/Source/core/xml/XMLHttpRequestUpload.cpp33
-rw-r--r--chromium/third_party/WebKit/Source/core/xml/XMLHttpRequestUpload.h18
-rw-r--r--chromium/third_party/WebKit/Source/core/xml/XMLSerializer.cpp4
-rw-r--r--chromium/third_party/WebKit/Source/core/xml/XMLTreeViewer.cpp6
-rw-r--r--chromium/third_party/WebKit/Source/core/xml/XMLTreeViewer.h3
-rw-r--r--chromium/third_party/WebKit/Source/core/xml/XPathEvaluator.cpp19
-rw-r--r--chromium/third_party/WebKit/Source/core/xml/XPathEvaluator.h4
-rw-r--r--chromium/third_party/WebKit/Source/core/xml/XPathExpression.cpp19
-rw-r--r--chromium/third_party/WebKit/Source/core/xml/XPathExpression.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/xml/XPathExpressionNode.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/xml/XPathExpressionNode.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/xml/XPathFunctions.cpp17
-rw-r--r--chromium/third_party/WebKit/Source/core/xml/XPathFunctions.h5
-rw-r--r--chromium/third_party/WebKit/Source/core/xml/XPathGrammar.y50
-rw-r--r--chromium/third_party/WebKit/Source/core/xml/XPathNSResolver.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/xml/XPathNodeSet.cpp3
-rw-r--r--chromium/third_party/WebKit/Source/core/xml/XPathParser.cpp36
-rw-r--r--chromium/third_party/WebKit/Source/core/xml/XPathParser.h14
-rw-r--r--chromium/third_party/WebKit/Source/core/xml/XPathPath.cpp9
-rw-r--r--chromium/third_party/WebKit/Source/core/xml/XPathPath.h28
-rw-r--r--chromium/third_party/WebKit/Source/core/xml/XPathPredicate.cpp14
-rw-r--r--chromium/third_party/WebKit/Source/core/xml/XPathPredicate.h10
-rw-r--r--chromium/third_party/WebKit/Source/core/xml/XPathResult.cpp38
-rw-r--r--chromium/third_party/WebKit/Source/core/xml/XPathResult.idl10
-rw-r--r--chromium/third_party/WebKit/Source/core/xml/XPathStep.cpp45
-rw-r--r--chromium/third_party/WebKit/Source/core/xml/XPathStep.h29
-rw-r--r--chromium/third_party/WebKit/Source/core/xml/XPathUtil.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/xml/XSLImportRule.cpp1
-rw-r--r--chromium/third_party/WebKit/Source/core/xml/XSLImportRule.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/xml/XSLStyleSheet.h14
-rw-r--r--chromium/third_party/WebKit/Source/core/xml/XSLStyleSheetLibxslt.cpp2
-rw-r--r--chromium/third_party/WebKit/Source/core/xml/XSLTExtensions.cpp3
-rw-r--r--chromium/third_party/WebKit/Source/core/xml/XSLTProcessor.cpp42
-rw-r--r--chromium/third_party/WebKit/Source/core/xml/XSLTProcessor.h7
-rw-r--r--chromium/third_party/WebKit/Source/core/xml/XSLTProcessor.idl5
-rw-r--r--chromium/third_party/WebKit/Source/core/xml/XSLTProcessorLibxslt.cpp26
-rw-r--r--chromium/third_party/WebKit/Source/core/xml/parser/MarkupTokenizerInlines.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/xml/parser/XMLDocumentParser.cpp75
-rw-r--r--chromium/third_party/WebKit/Source/core/xml/parser/XMLDocumentParser.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/xml/parser/XMLParserInput.h2
-rw-r--r--chromium/third_party/WebKit/Source/core/xml/xmlattrs.in1
4386 files changed, 131812 insertions, 282940 deletions
diff --git a/chromium/third_party/WebKit/Source/core/.gitattributes b/chromium/third_party/WebKit/Source/core/.gitattributes
index 01156ad23b3..6701869bccc 100644
--- a/chromium/third_party/WebKit/Source/core/.gitattributes
+++ b/chromium/third_party/WebKit/Source/core/.gitattributes
@@ -1,3 +1,2 @@
inspector/Inspector.json -crlf
-platform/chromium/SuddenTerminationChromium.cpp -crlf
rendering/RenderThemeChromiumWin.h -crlf
diff --git a/chromium/third_party/WebKit/Source/core/ConvertFileToHeaderWithCharacterArray.gypi b/chromium/third_party/WebKit/Source/core/ConvertFileToHeaderWithCharacterArray.gypi
deleted file mode 100644
index 063e38c297f..00000000000
--- a/chromium/third_party/WebKit/Source/core/ConvertFileToHeaderWithCharacterArray.gypi
+++ /dev/null
@@ -1,63 +0,0 @@
-#
-# Copyright (C) 2013 Igalia S.L.
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions are
-# met:
-#
-# * Redistributions of source code must retain the above copyright
-# notice, this list of conditions and the following disclaimer.
-# * Redistributions in binary form must reproduce the above
-# copyright notice, this list of conditions and the following disclaimer
-# in the documentation and/or other materials provided with the
-# distribution.
-# * Neither the name of Google Inc. nor the names of its
-# contributors may be used to endorse or promote products derived from
-# this software without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-#
-# To use this, create a gyp target with the following form:
-# {
-# 'target_name': 'GenerateInjectedScriptSource',
-# 'type': 'none',
-# 'variables': {
-# 'input_file_path': 'inspector/InjectedScriptSource.js'',
-# 'output_file_path': '<(SHARED_INTERMEDIATE_DIR)/blink/InjectedScriptSource.h',
-# 'character_array_name': 'InjectedScriptSource_js',
-# },
-# 'includes': [ 'ConvertFileToHeaderWithCharacterArray.gypi' ],
-# },
-{
- 'actions': [
- {
- 'action_name': 'ConvertFileToHeaderWithCharacterArray',
- 'inputs': [
- 'scripts/xxd.pl',
- '<(input_file_path)',
- ],
- 'outputs': [ '<@(output_file_path)', ],
- 'action': [
- '<(perl_exe)',
- 'scripts/xxd.pl',
- '<(character_array_name)',
- '<(input_file_path)',
- '<@(_outputs)'
- ],
- 'message': 'Generating <(output_file_path) from <(input_file_path)',
- },
- ],
-
- # Since this target generates header files, it needs to be a hard dependency.
- 'hard_dependency': 1,
-}
diff --git a/chromium/third_party/WebKit/Source/core/DEPS b/chromium/third_party/WebKit/Source/core/DEPS
index 634db903b01..da61cbd2353 100644
--- a/chromium/third_party/WebKit/Source/core/DEPS
+++ b/chromium/third_party/WebKit/Source/core/DEPS
@@ -1,23 +1,25 @@
include_rules = [
"+bindings",
"+core",
+ "+heap",
"+mozilla",
+ "+platform",
"+public/platform",
"+sys",
- "+weborigin",
- "-WebKit",
- "-modules",
# core/ should not depend on modules/ at all, but there are a number of pieces
# of code that do. Please don't add to this list of exceptions.
- "+modules/filesystem",
- "+modules/geolocation",
- "+modules/indexeddb",
- "+modules/mediasource",
- "+modules/mediastream",
- "+modules/speech",
- "+modules/webaudio",
- "+modules/webdatabase",
- "+modules/websockets",
- "+modules/websockets",
+ "!modules/encryptedmedia/MediaKeyNeededEvent.h",
+ "!modules/encryptedmedia/MediaKeys.h",
+ "!modules/filesystem/DraggedIsolatedFileSystem.h",
+ "!modules/geolocation/GeolocationClient.h",
+ "!modules/geolocation/GeolocationController.h",
+ "!modules/geolocation/GeolocationError.h",
+ "!modules/geolocation/GeolocationPosition.h",
+ "!modules/mediastream/MediaStreamRegistry.h",
+ "!modules/mediastream/MediaStreamTrackSourcesRequest.h",
+ "!modules/mediastream/RTCStatsResponse.h",
+ "!modules/webaudio/MediaElementAudioSourceNode.h",
+ "!modules/webdatabase/DatabaseManager.h",
+ "!modules/webdatabase/DatabaseTask.h",
]
diff --git a/chromium/third_party/WebKit/Source/core/Init.cpp b/chromium/third_party/WebKit/Source/core/Init.cpp
index 8aee439ea86..8b7304d14ad 100644
--- a/chromium/third_party/WebKit/Source/core/Init.cpp
+++ b/chromium/third_party/WebKit/Source/core/Init.cpp
@@ -31,17 +31,22 @@
#include "config.h"
#include "Init.h"
+#include "EventNames.h"
+#include "EventTargetNames.h"
+#include "EventTypeNames.h"
#include "FetchInitiatorTypeNames.h"
#include "FontFamilyNames.h"
#include "HTMLNames.h"
+#include "InputTypeNames.h"
#include "MathMLNames.h"
#include "SVGNames.h"
#include "XLinkNames.h"
#include "XMLNSNames.h"
#include "XMLNames.h"
#include "core/css/MediaFeatureNames.h"
-#include "core/platform/EventTracer.h"
-#include "core/platform/Partitions.h"
+#include "platform/EventTracer.h"
+#include "platform/Partitions.h"
+#include "platform/PlatformThreadData.h"
#include "wtf/text/StringStatics.h"
namespace WebCore {
@@ -62,13 +67,23 @@ void init()
MathMLNames::init();
XMLNSNames::init();
XMLNames::init();
- FontFamilyNames::init();
+ EventNames::init();
+ EventTargetNames::init();
+ EventTypeNames::init();
FetchInitiatorTypeNames::init();
+ FontFamilyNames::init();
+ InputTypeNames::init();
MediaFeatureNames::init();
WTF::StringStatics::init();
QualifiedName::init();
Partitions::init();
EventTracer::initialize();
+
+ // Ensure that the main thread's thread-local data is initialized before
+ // starting any worker threads.
+ PlatformThreadData::current();
+
+ StringImpl::freezeStaticStrings();
}
void shutdown()
diff --git a/chromium/third_party/WebKit/Source/core/OWNERS b/chromium/third_party/WebKit/Source/core/OWNERS
index a7741535cc5..c82d8e69312 100644
--- a/chromium/third_party/WebKit/Source/core/OWNERS
+++ b/chromium/third_party/WebKit/Source/core/OWNERS
@@ -3,14 +3,15 @@ adamk@chromium.org
alexis.menard@intel.com
apavlov@chromium.org
arv@chromium.org
-ch.dumez@sisa.samsung.com
+ch.dumez@samsung.com
darin@chromium.org
dglazkov@chromium.org
dimich@chromium.org
-dominicc@chromium.org
dmazzoni@chromium.org
+dominicc@chromium.org
dpranke@chromium.org
dschulze@chromium.org
+dstockwell@chromium.org
eae@chromium.org
enne@chromium.org
eseidel@chromium.org
@@ -26,6 +27,8 @@ jchaffraix@chromium.org
jianli@chromium.org
jochen@chromium.org
kbr@chromium.org
+kenneth.r.christiansen@intel.com
+kinuko@chromium.org
levin@chromium.org
leviw@chromium.org
mkwst@chromium.org
@@ -33,6 +36,7 @@ morrita@chromium.org
ojan@chromium.org
pdr@chromium.org
pfeldman@chromium.org
+pkasting@chromium.org
schenney@chromium.org
senorblanco@chromium.org
steveblock@chromium.org
diff --git a/chromium/third_party/WebKit/Source/core/Resources/aliasCursor.png b/chromium/third_party/WebKit/Source/core/Resources/aliasCursor.png
deleted file mode 100644
index d33d7e98fca..00000000000
--- a/chromium/third_party/WebKit/Source/core/Resources/aliasCursor.png
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/Resources/cellCursor.png b/chromium/third_party/WebKit/Source/core/Resources/cellCursor.png
deleted file mode 100644
index 5c616c47b71..00000000000
--- a/chromium/third_party/WebKit/Source/core/Resources/cellCursor.png
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/Resources/contextMenuCursor.png b/chromium/third_party/WebKit/Source/core/Resources/contextMenuCursor.png
deleted file mode 100644
index ae100c7eaf5..00000000000
--- a/chromium/third_party/WebKit/Source/core/Resources/contextMenuCursor.png
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/Resources/copyCursor.png b/chromium/third_party/WebKit/Source/core/Resources/copyCursor.png
deleted file mode 100644
index 33be332bbfe..00000000000
--- a/chromium/third_party/WebKit/Source/core/Resources/copyCursor.png
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/Resources/deleteButton.png b/chromium/third_party/WebKit/Source/core/Resources/deleteButton.png
deleted file mode 100644
index 67e2240c571..00000000000
--- a/chromium/third_party/WebKit/Source/core/Resources/deleteButton.png
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/Resources/deleteButton.tiff b/chromium/third_party/WebKit/Source/core/Resources/deleteButton.tiff
deleted file mode 100644
index bf4347ef6b5..00000000000
--- a/chromium/third_party/WebKit/Source/core/Resources/deleteButton.tiff
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/Resources/deleteButton@2x.png b/chromium/third_party/WebKit/Source/core/Resources/deleteButton@2x.png
deleted file mode 100644
index e6046d4755c..00000000000
--- a/chromium/third_party/WebKit/Source/core/Resources/deleteButton@2x.png
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/Resources/deleteButtonPressed.png b/chromium/third_party/WebKit/Source/core/Resources/deleteButtonPressed.png
deleted file mode 100644
index 2dbd13df4fb..00000000000
--- a/chromium/third_party/WebKit/Source/core/Resources/deleteButtonPressed.png
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/Resources/deleteButtonPressed.tiff b/chromium/third_party/WebKit/Source/core/Resources/deleteButtonPressed.tiff
deleted file mode 100644
index 6232484d6e8..00000000000
--- a/chromium/third_party/WebKit/Source/core/Resources/deleteButtonPressed.tiff
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/Resources/deleteButtonPressed@2x.png b/chromium/third_party/WebKit/Source/core/Resources/deleteButtonPressed@2x.png
deleted file mode 100644
index 3c999a7db3b..00000000000
--- a/chromium/third_party/WebKit/Source/core/Resources/deleteButtonPressed@2x.png
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/Resources/eastResizeCursor.png b/chromium/third_party/WebKit/Source/core/Resources/eastResizeCursor.png
deleted file mode 100644
index 9c1592e5d6f..00000000000
--- a/chromium/third_party/WebKit/Source/core/Resources/eastResizeCursor.png
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/Resources/eastWestResizeCursor.png b/chromium/third_party/WebKit/Source/core/Resources/eastWestResizeCursor.png
deleted file mode 100644
index f43202ef5ae..00000000000
--- a/chromium/third_party/WebKit/Source/core/Resources/eastWestResizeCursor.png
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/Resources/helpCursor.png b/chromium/third_party/WebKit/Source/core/Resources/helpCursor.png
deleted file mode 100644
index 6828d6a4de9..00000000000
--- a/chromium/third_party/WebKit/Source/core/Resources/helpCursor.png
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/Resources/inputSpeech.png b/chromium/third_party/WebKit/Source/core/Resources/inputSpeech.png
deleted file mode 100644
index 8a5c469da51..00000000000
--- a/chromium/third_party/WebKit/Source/core/Resources/inputSpeech.png
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/Resources/inputSpeech.tiff b/chromium/third_party/WebKit/Source/core/Resources/inputSpeech.tiff
deleted file mode 100644
index 11ba129596e..00000000000
--- a/chromium/third_party/WebKit/Source/core/Resources/inputSpeech.tiff
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/Resources/linearSRGB.icc b/chromium/third_party/WebKit/Source/core/Resources/linearSRGB.icc
deleted file mode 100644
index 5cc4371069e..00000000000
--- a/chromium/third_party/WebKit/Source/core/Resources/linearSRGB.icc
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/Resources/linkCursor.png b/chromium/third_party/WebKit/Source/core/Resources/linkCursor.png
deleted file mode 100644
index e5e274936c0..00000000000
--- a/chromium/third_party/WebKit/Source/core/Resources/linkCursor.png
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/Resources/missingImage.png b/chromium/third_party/WebKit/Source/core/Resources/missingImage.png
deleted file mode 100644
index 5c24d20c2c4..00000000000
--- a/chromium/third_party/WebKit/Source/core/Resources/missingImage.png
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/Resources/missingImage.tiff b/chromium/third_party/WebKit/Source/core/Resources/missingImage.tiff
deleted file mode 100644
index bfde916ea0e..00000000000
--- a/chromium/third_party/WebKit/Source/core/Resources/missingImage.tiff
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/Resources/missingImage@2x.png b/chromium/third_party/WebKit/Source/core/Resources/missingImage@2x.png
deleted file mode 100644
index 6573d174713..00000000000
--- a/chromium/third_party/WebKit/Source/core/Resources/missingImage@2x.png
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/Resources/moveCursor.png b/chromium/third_party/WebKit/Source/core/Resources/moveCursor.png
deleted file mode 100644
index 4ca8d703744..00000000000
--- a/chromium/third_party/WebKit/Source/core/Resources/moveCursor.png
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/Resources/noDropCursor.png b/chromium/third_party/WebKit/Source/core/Resources/noDropCursor.png
deleted file mode 100644
index 54463fc0cdf..00000000000
--- a/chromium/third_party/WebKit/Source/core/Resources/noDropCursor.png
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/Resources/noneCursor.png b/chromium/third_party/WebKit/Source/core/Resources/noneCursor.png
deleted file mode 100644
index bd1ff356f18..00000000000
--- a/chromium/third_party/WebKit/Source/core/Resources/noneCursor.png
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/Resources/northEastResizeCursor.png b/chromium/third_party/WebKit/Source/core/Resources/northEastResizeCursor.png
deleted file mode 100644
index 0e896390730..00000000000
--- a/chromium/third_party/WebKit/Source/core/Resources/northEastResizeCursor.png
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/Resources/northEastSouthWestResizeCursor.png b/chromium/third_party/WebKit/Source/core/Resources/northEastSouthWestResizeCursor.png
deleted file mode 100644
index 9904c7b61e1..00000000000
--- a/chromium/third_party/WebKit/Source/core/Resources/northEastSouthWestResizeCursor.png
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/Resources/northResizeCursor.png b/chromium/third_party/WebKit/Source/core/Resources/northResizeCursor.png
deleted file mode 100644
index 0d020dbabd6..00000000000
--- a/chromium/third_party/WebKit/Source/core/Resources/northResizeCursor.png
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/Resources/northSouthResizeCursor.png b/chromium/third_party/WebKit/Source/core/Resources/northSouthResizeCursor.png
deleted file mode 100644
index 92400e9191f..00000000000
--- a/chromium/third_party/WebKit/Source/core/Resources/northSouthResizeCursor.png
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/Resources/northWestResizeCursor.png b/chromium/third_party/WebKit/Source/core/Resources/northWestResizeCursor.png
deleted file mode 100644
index 6723f614a62..00000000000
--- a/chromium/third_party/WebKit/Source/core/Resources/northWestResizeCursor.png
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/Resources/northWestSouthEastResizeCursor.png b/chromium/third_party/WebKit/Source/core/Resources/northWestSouthEastResizeCursor.png
deleted file mode 100644
index b8de34ce741..00000000000
--- a/chromium/third_party/WebKit/Source/core/Resources/northWestSouthEastResizeCursor.png
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/Resources/nullPlugin.png b/chromium/third_party/WebKit/Source/core/Resources/nullPlugin.png
deleted file mode 100644
index a4195f67d37..00000000000
--- a/chromium/third_party/WebKit/Source/core/Resources/nullPlugin.png
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/Resources/nullPlugin@2x.png b/chromium/third_party/WebKit/Source/core/Resources/nullPlugin@2x.png
deleted file mode 100644
index ccc40188a53..00000000000
--- a/chromium/third_party/WebKit/Source/core/Resources/nullPlugin@2x.png
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/Resources/pagepopups/calendarPicker.css b/chromium/third_party/WebKit/Source/core/Resources/pagepopups/calendarPicker.css
deleted file mode 100644
index a4e6ae9a6ab..00000000000
--- a/chromium/third_party/WebKit/Source/core/Resources/pagepopups/calendarPicker.css
+++ /dev/null
@@ -1,296 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-body {
- -webkit-user-select: none;
- background-color: white;
- font: -webkit-control;
- font-size: 12px;
-}
-
-.rtl {
- direction: rtl;
-}
-
-.scroll-view {
- overflow: hidden;
- width: 0;
- height: 0;
-}
-
-.list-cell {
- position: absolute;
- left: 0;
- top: 0;
- width: 0;
- height: 0;
-}
-
-.list-cell.hidden {
- display: none;
-}
-
-.week-number-cell,
-.day-cell {
- position: static;
- text-align: center;
- box-sizing: border-box;
- display: inline-block;
- cursor: default;
- transition: color 1s;
- padding: 1px;
-}
-
-.week-number-cell {
- box-sizing: border-box;
- color: black;
- padding-right: 0;
- box-shadow: 1px 0 0 #bfbfbf;
- margin-right: 1px;
-}
-
-.day-cell {
- color: #bfbfbf;
-}
-
-.day-cell.highlighted.today,
-.day-cell.today {
- border: 1px solid #bfbfbf;
- padding: 0;
-}
-
-.week-number-cell.highlighted,
-.day-cell.highlighted {
- background-color: #e5ecf8;
-}
-
-.week-number-cell.highlighted.disabled,
-.day-cell.highlighted.disabled {
- border: 1px solid #e5ecf8;
- padding: 0;
-}
-
-.week-number-cell.selected,
-.day-cell.selected {
- background-color: #bccdec;
-}
-
-.week-number-cell.disabled,
-.day-cell.disabled {
- background-color: #f5f5f5;
-}
-
-.day-cell.current-month {
- color: #000000;
-}
-
-.calendar-table-view {
- border: 1px solid #bfbfbf;
- display: inline-block;
- outline: none;
-}
-
-.week-number-label,
-.week-day-label {
- text-align: center;
- display: inline-block;
- line-height: 23px;
- padding-top: 1px;
- box-sizing: padding-box;
-}
-
-.week-number-label {
- box-sizing: border-box;
- border-right: 1px solid #bfbfbf;
-}
-
-.calendar-table-header-view {
- background-color: #f5f5f5;
- border-bottom: 1px solid #bfbfbf;
- height: 24px;
-}
-
-.calendar-picker {
- border: 1px solid #bfbfbf;
- border-radius: 2px;
- position: absolute;
- padding: 10px;
- background-color: white;
- overflow: hidden;
- cursor: default;
-}
-
-.calendar-header-view {
- margin-bottom: 10px;
- display: flex;
- flex-flow: row;
-}
-
-.calendar-title {
- -webkit-align-self: center;
- flex: 1;
- text-align: left;
-}
-
-.rtl .calendar-title {
- text-align: right;
-}
-
-.month-popup-button,
-.month-popup-button:hover,
-.month-popup-button:disabled {
- background-color: transparent !important;
- background-image: none !important;
- box-shadow: none !important;
- color: black;
-}
-
-.month-popup-button:disabled {
- opacity: 0.7;
-}
-
-.month-popup-button {
- font-size: 12px;
- padding: 4px;
- display: inline-block;
- cursor: default;
- border: 1px solid transparent !important;
- height: 24px !important;
-}
-
-.month-popup-button .disclosure-triangle {
- margin: 0 6px;
-}
-
-.month-popup-button .disclosure-triangle svg {
- padding-bottom: 2px;
-}
-
-.today-button::after {
- content: "";
- display: block;
- border-radius: 3px;
- width: 6px;
- height: 6px;
- background-color: #6e6e6e;
- margin: 0 auto;
-}
-
-.calendar-navigation-button {
- -webkit-align-self: center;
- width: 24px;
- height: 24px;
- min-width: 0 !important;
- padding-left: 0 !important;
- padding-right: 0 !important;
- -webkit-margin-start: 4px !important;
-}
-
-.year-list-view {
- border: 1px solid #bfbfbf;
- background-color: white;
- position: absolute;
-}
-
-.year-list-cell {
- box-sizing: border-box;
- border-bottom: 1px solid #bfbfbf;
- background-color: white;
- overflow: hidden;
-}
-
-.year-list-cell .label {
- height: 24px;
- line-height: 24px;
- -webkit-padding-start: 8px;
- background-color: #f5f5f5;
- border-bottom: 1px solid #bfbfbf;
-}
-
-.year-list-cell .month-chooser {
- padding: 0;
-}
-
-.month-buttons-row {
- display: flex;
-}
-
-.month-button {
- flex: 1;
- height: 32px;
- padding: 0 !important;
- margin: 0 !important;
- background-image: none !important;
- background-color: #ffffff;
- border-width: 0 !important;
- box-shadow: none !important;
-}
-
-.month-button.highlighted {
- background-color: #e5ecf8;
-}
-
-.scrubby-scroll-bar {
- width: 14px;
- height: 60px;
- background-color: white;
- border-left: 1px solid #bfbfbf;
- position: absolute;
- top: 0;
-}
-
-.scrubby-scroll-thumb {
- width: 10px;
- margin: 2px;
- height: 30px;
- background-color: #d8d8d8;
- position: absolute;
- left: 0;
- top: 0;
-}
-
-.month-popup-view {
- position: absolute;
- top: 0;
- right: 0;
- bottom: 0;
- left: 0;
-}
-
-.year-list-view .scrubby-scroll-bar {
- right: 0;
-}
-
-.rtl .year-list-view .scrubby-scroll-bar {
- left: 0;
- right: auto;
- border-left-width: 0;
- border-right: 1px solid #bfbfbf;
-}
diff --git a/chromium/third_party/WebKit/Source/core/Resources/pagepopups/calendarPicker.js b/chromium/third_party/WebKit/Source/core/Resources/pagepopups/calendarPicker.js
deleted file mode 100644
index a01c5ba7612..00000000000
--- a/chromium/third_party/WebKit/Source/core/Resources/pagepopups/calendarPicker.js
+++ /dev/null
@@ -1,4009 +0,0 @@
-"use strict";
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-
-/**
- * @enum {number}
- */
-var WeekDay = {
- Sunday: 0,
- Monday: 1,
- Tuesday: 2,
- Wednesday: 3,
- Thursday: 4,
- Friday: 5,
- Saturday: 6
-};
-
-/**
- * @type {Object}
- */
-var global = {
- picker: null,
- params: {
- locale: "en_US",
- weekStartDay: WeekDay.Sunday,
- dayLabels: ["S", "M", "T", "W", "T", "F", "S"],
- shortMonthLabels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec"],
- isLocaleRTL: false,
- mode: "date",
- weekLabel: "Week",
- anchorRectInScreen: new Rectangle(0, 0, 0, 0),
- currentValue: null
- }
-};
-
-// ----------------------------------------------------------------
-// Utility functions
-
-/**
- * @return {!bool}
- */
-function hasInaccuratePointingDevice() {
- return matchMedia("(pointer: coarse)").matches;
-}
-
-/**
- * @return {!string} lowercase locale name. e.g. "en-us"
- */
-function getLocale() {
- return (global.params.locale || "en-us").toLowerCase();
-}
-
-/**
- * @return {!string} lowercase language code. e.g. "en"
- */
-function getLanguage() {
- var locale = getLocale();
- var result = locale.match(/^([a-z]+)/);
- if (!result)
- return "en";
- return result[1];
-}
-
-/**
- * @param {!number} number
- * @return {!string}
- */
-function localizeNumber(number) {
- return window.pagePopupController.localizeNumberString(number);
-}
-
-/**
- * @const
- * @type {number}
- */
-var ImperialEraLimit = 2087;
-
-/**
- * @param {!number} year
- * @param {!number} month
- * @return {!string}
- */
-function formatJapaneseImperialEra(year, month) {
- // We don't show an imperial era if it is greater than 99 becase of space
- // limitation.
- if (year > ImperialEraLimit)
- return "";
- if (year > 1989)
- return "(平成" + localizeNumber(year - 1988) + "年)";
- if (year == 1989)
- return "(平成元年)";
- if (year >= 1927)
- return "(昭和" + localizeNumber(year - 1925) + "年)";
- if (year > 1912)
- return "(大正" + localizeNumber(year - 1911) + "年)";
- if (year == 1912 && month >= 7)
- return "(大正元年)";
- if (year > 1868)
- return "(明治" + localizeNumber(year - 1867) + "年)";
- if (year == 1868)
- return "(明治元年)";
- return "";
-}
-
-function createUTCDate(year, month, date) {
- var newDate = new Date(0);
- newDate.setUTCFullYear(year);
- newDate.setUTCMonth(month);
- newDate.setUTCDate(date);
- return newDate;
-}
-
-/**
- * @param {string} dateString
- * @return {?Day|Week|Month}
- */
-function parseDateString(dateString) {
- var month = Month.parse(dateString);
- if (month)
- return month;
- var week = Week.parse(dateString);
- if (week)
- return week;
- return Day.parse(dateString);
-}
-
-/**
- * @const
- * @type {number}
- */
-var DaysPerWeek = 7;
-
-/**
- * @const
- * @type {number}
- */
-var MonthsPerYear = 12;
-
-/**
- * @const
- * @type {number}
- */
-var MillisecondsPerDay = 24 * 60 * 60 * 1000;
-
-/**
- * @const
- * @type {number}
- */
-var MillisecondsPerWeek = DaysPerWeek * MillisecondsPerDay;
-
-/**
- * @constructor
- */
-function DateType() {
-}
-
-/**
- * @constructor
- * @extends DateType
- * @param {!number} year
- * @param {!number} month
- * @param {!number} date
- */
-function Day(year, month, date) {
- var dateObject = createUTCDate(year, month, date);
- if (isNaN(dateObject.valueOf()))
- throw "Invalid date";
- /**
- * @type {number}
- * @const
- */
- this.year = dateObject.getUTCFullYear();
- /**
- * @type {number}
- * @const
- */
- this.month = dateObject.getUTCMonth();
- /**
- * @type {number}
- * @const
- */
- this.date = dateObject.getUTCDate();
-};
-
-Day.prototype = Object.create(DateType.prototype);
-
-Day.ISOStringRegExp = /^(\d+)-(\d+)-(\d+)/;
-
-/**
- * @param {!string} str
- * @return {?Day}
- */
-Day.parse = function(str) {
- var match = Day.ISOStringRegExp.exec(str);
- if (!match)
- return null;
- var year = parseInt(match[1], 10);
- var month = parseInt(match[2], 10) - 1;
- var date = parseInt(match[3], 10);
- return new Day(year, month, date);
-};
-
-/**
- * @param {!number} value
- * @return {!Day}
- */
-Day.createFromValue = function(millisecondsSinceEpoch) {
- return Day.createFromDate(new Date(millisecondsSinceEpoch))
-};
-
-/**
- * @param {!Date} date
- * @return {!Day}
- */
-Day.createFromDate = function(date) {
- if (isNaN(date.valueOf()))
- throw "Invalid date";
- return new Day(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate());
-};
-
-/**
- * @param {!Day} day
- * @return {!Day}
- */
-Day.createFromDay = function(day) {
- return day;
-};
-
-/**
- * @return {!Day}
- */
-Day.createFromToday = function() {
- var now = new Date();
- return new Day(now.getFullYear(), now.getMonth(), now.getDate());
-};
-
-/**
- * @param {!DateType} other
- * @return {!boolean}
- */
-Day.prototype.equals = function(other) {
- return other instanceof Day && this.year === other.year && this.month === other.month && this.date === other.date;
-};
-
-/**
- * @param {!number=} offset
- * @return {!Day}
- */
-Day.prototype.previous = function(offset) {
- if (typeof offset === "undefined")
- offset = 1;
- return new Day(this.year, this.month, this.date - offset);
-};
-
-/**
- * @param {!number=} offset
- * @return {!Day}
- */
-Day.prototype.next = function(offset) {
- if (typeof offset === "undefined")
- offset = 1;
- return new Day(this.year, this.month, this.date + offset);
-};
-
-/**
- * @return {!Date}
- */
-Day.prototype.startDate = function() {
- return createUTCDate(this.year, this.month, this.date);
-};
-
-/**
- * @return {!Date}
- */
-Day.prototype.endDate = function() {
- return createUTCDate(this.year, this.month, this.date + 1);
-};
-
-/**
- * @return {!Day}
- */
-Day.prototype.firstDay = function() {
- return this;
-};
-
-/**
- * @return {!Day}
- */
-Day.prototype.middleDay = function() {
- return this;
-};
-
-/**
- * @return {!Day}
- */
-Day.prototype.lastDay = function() {
- return this;
-};
-
-/**
- * @return {!number}
- */
-Day.prototype.valueOf = function() {
- return createUTCDate(this.year, this.month, this.date).getTime();
-};
-
-/**
- * @return {!WeekDay}
- */
-Day.prototype.weekDay = function() {
- return createUTCDate(this.year, this.month, this.date).getUTCDay();
-};
-
-/**
- * @return {!string}
- */
-Day.prototype.toString = function() {
- var yearString = String(this.year);
- if (yearString.length < 4)
- yearString = ("000" + yearString).substr(-4, 4);
- return yearString + "-" + ("0" + (this.month + 1)).substr(-2, 2) + "-" + ("0" + this.date).substr(-2, 2);
-};
-
-// See WebCore/platform/DateComponents.h.
-Day.Minimum = Day.createFromValue(-62135596800000.0);
-Day.Maximum = Day.createFromValue(8640000000000000.0);
-
-// See WebCore/html/DayInputType.cpp.
-Day.DefaultStep = 86400000;
-Day.DefaultStepBase = 0;
-
-/**
- * @constructor
- * @extends DateType
- * @param {!number} year
- * @param {!number} week
- */
-function Week(year, week) {
- /**
- * @type {number}
- * @const
- */
- this.year = year;
- /**
- * @type {number}
- * @const
- */
- this.week = week;
- // Number of years per year is either 52 or 53.
- if (this.week < 1 || (this.week > 52 && this.week > Week.numberOfWeeksInYear(this.year))) {
- var normalizedWeek = Week.createFromDay(this.firstDay());
- this.year = normalizedWeek.year;
- this.week = normalizedWeek.week;
- }
-}
-
-Week.ISOStringRegExp = /^(\d+)-[wW](\d+)$/;
-
-// See WebCore/platform/DateComponents.h.
-Week.Minimum = new Week(1, 1);
-Week.Maximum = new Week(275760, 37);
-
-// See WebCore/html/WeekInputType.cpp.
-Week.DefaultStep = 604800000;
-Week.DefaultStepBase = -259200000;
-
-Week.EpochWeekDay = createUTCDate(1970, 0, 0).getUTCDay();
-
-/**
- * @param {!string} str
- * @return {?Week}
- */
-Week.parse = function(str) {
- var match = Week.ISOStringRegExp.exec(str);
- if (!match)
- return null;
- var year = parseInt(match[1], 10);
- var week = parseInt(match[2], 10);
- return new Week(year, week);
-};
-
-/**
- * @param {!number} millisecondsSinceEpoch
- * @return {!Week}
- */
-Week.createFromValue = function(millisecondsSinceEpoch) {
- return Week.createFromDate(new Date(millisecondsSinceEpoch))
-};
-
-/**
- * @param {!Date} date
- * @return {!Week}
- */
-Week.createFromDate = function(date) {
- if (isNaN(date.valueOf()))
- throw "Invalid date";
- var year = date.getUTCFullYear();
- if (year <= Week.Maximum.year && Week.weekOneStartDateForYear(year + 1).getTime() <= date.getTime())
- year++;
- else if (year > 1 && Week.weekOneStartDateForYear(year).getTime() > date.getTime())
- year--;
- var week = 1 + Week._numberOfWeeksSinceDate(Week.weekOneStartDateForYear(year), date);
- return new Week(year, week);
-};
-
-/**
- * @param {!Day} day
- * @return {!Week}
- */
-Week.createFromDay = function(day) {
- var year = day.year;
- if (year <= Week.Maximum.year && Week.weekOneStartDayForYear(year + 1) <= day)
- year++;
- else if (year > 1 && Week.weekOneStartDayForYear(year) > day)
- year--;
- var week = Math.floor(1 + (day.valueOf() - Week.weekOneStartDayForYear(year).valueOf()) / MillisecondsPerWeek);
- return new Week(year, week);
-};
-
-/**
- * @return {!Week}
- */
-Week.createFromToday = function() {
- var now = new Date();
- return Week.createFromDate(createUTCDate(now.getFullYear(), now.getMonth(), now.getDate()));
-};
-
-/**
- * @param {!number} year
- * @return {!Date}
- */
-Week.weekOneStartDateForYear = function(year) {
- if (year < 1)
- return createUTCDate(1, 0, 1);
- // The week containing January 4th is week one.
- var yearStartDay = createUTCDate(year, 0, 4).getUTCDay();
- return createUTCDate(year, 0, 4 - (yearStartDay + 6) % DaysPerWeek);
-};
-
-/**
- * @param {!number} year
- * @return {!Day}
- */
-Week.weekOneStartDayForYear = function(year) {
- if (year < 1)
- return Day.Minimum;
- // The week containing January 4th is week one.
- var yearStartDay = createUTCDate(year, 0, 4).getUTCDay();
- return new Day(year, 0, 4 - (yearStartDay + 6) % DaysPerWeek);
-};
-
-/**
- * @param {!number} year
- * @return {!number}
- */
-Week.numberOfWeeksInYear = function(year) {
- if (year < 1 || year > Week.Maximum.year)
- return 0;
- else if (year === Week.Maximum.year)
- return Week.Maximum.week;
- return Week._numberOfWeeksSinceDate(Week.weekOneStartDateForYear(year), Week.weekOneStartDateForYear(year + 1));
-};
-
-/**
- * @param {!Date} baseDate
- * @param {!Date} date
- * @return {!number}
- */
-Week._numberOfWeeksSinceDate = function(baseDate, date) {
- return Math.floor((date.getTime() - baseDate.getTime()) / MillisecondsPerWeek);
-};
-
-/**
- * @param {!DateType} other
- * @return {!boolean}
- */
-Week.prototype.equals = function(other) {
- return other instanceof Week && this.year === other.year && this.week === other.week;
-};
-
-/**
- * @param {!number=} offset
- * @return {!Week}
- */
-Week.prototype.previous = function(offset) {
- if (typeof offset === "undefined")
- offset = 1;
- return new Week(this.year, this.week - offset);
-};
-
-/**
- * @param {!number=} offset
- * @return {!Week}
- */
-Week.prototype.next = function(offset) {
- if (typeof offset === "undefined")
- offset = 1;
- return new Week(this.year, this.week + offset);
-};
-
-/**
- * @return {!Date}
- */
-Week.prototype.startDate = function() {
- var weekStartDate = Week.weekOneStartDateForYear(this.year);
- weekStartDate.setUTCDate(weekStartDate.getUTCDate() + (this.week - 1) * 7);
- return weekStartDate;
-};
-
-/**
- * @return {!Date}
- */
-Week.prototype.endDate = function() {
- if (this.equals(Week.Maximum))
- return Day.Maximum.startDate();
- return this.next().startDate();
-};
-
-/**
- * @return {!Day}
- */
-Week.prototype.firstDay = function() {
- var weekOneStartDay = Week.weekOneStartDayForYear(this.year);
- return weekOneStartDay.next((this.week - 1) * DaysPerWeek);
-};
-
-/**
- * @return {!Day}
- */
-Week.prototype.middleDay = function() {
- return this.firstDay().next(3);
-};
-
-/**
- * @return {!Day}
- */
-Week.prototype.lastDay = function() {
- if (this.equals(Week.Maximum))
- return Day.Maximum;
- return this.next().firstDay().previous();
-};
-
-/**
- * @return {!number}
- */
-Week.prototype.valueOf = function() {
- return this.firstDay().valueOf() - createUTCDate(1970, 0, 1).getTime();
-};
-
-/**
- * @return {!string}
- */
-Week.prototype.toString = function() {
- var yearString = String(this.year);
- if (yearString.length < 4)
- yearString = ("000" + yearString).substr(-4, 4);
- return yearString + "-W" + ("0" + this.week).substr(-2, 2);
-};
-
-/**
- * @constructor
- * @extends DateType
- * @param {!number} year
- * @param {!number} month
- */
-function Month(year, month) {
- /**
- * @type {number}
- * @const
- */
- this.year = year + Math.floor(month / MonthsPerYear);
- /**
- * @type {number}
- * @const
- */
- this.month = month % MonthsPerYear < 0 ? month % MonthsPerYear + MonthsPerYear : month % MonthsPerYear;
-};
-
-Month.ISOStringRegExp = /^(\d+)-(\d+)$/;
-
-// See WebCore/platform/DateComponents.h.
-Month.Minimum = new Month(1, 0);
-Month.Maximum = new Month(275760, 8);
-
-// See WebCore/html/MonthInputType.cpp.
-Month.DefaultStep = 1;
-Month.DefaultStepBase = 0;
-
-/**
- * @param {!string} str
- * @return {?Month}
- */
-Month.parse = function(str) {
- var match = Month.ISOStringRegExp.exec(str);
- if (!match)
- return null;
- var year = parseInt(match[1], 10);
- var month = parseInt(match[2], 10) - 1;
- return new Month(year, month);
-};
-
-/**
- * @param {!number} value
- * @return {!Month}
- */
-Month.createFromValue = function(monthsSinceEpoch) {
- return new Month(1970, monthsSinceEpoch)
-};
-
-/**
- * @param {!Date} date
- * @return {!Month}
- */
-Month.createFromDate = function(date) {
- if (isNaN(date.valueOf()))
- throw "Invalid date";
- return new Month(date.getUTCFullYear(), date.getUTCMonth());
-};
-
-/**
- * @param {!Day} day
- * @return {!Month}
- */
-Month.createFromDay = function(day) {
- return new Month(day.year, day.month);
-};
-
-/**
- * @return {!Month}
- */
-Month.createFromToday = function() {
- var now = new Date();
- return new Month(now.getFullYear(), now.getMonth());
-};
-
-/**
- * @return {!boolean}
- */
-Month.prototype.containsDay = function(day) {
- return this.year === day.year && this.month === day.month;
-};
-
-/**
- * @param {!Month} other
- * @return {!boolean}
- */
-Month.prototype.equals = function(other) {
- return other instanceof Month && this.year === other.year && this.month === other.month;
-};
-
-/**
- * @param {!number=} offset
- * @return {!Month}
- */
-Month.prototype.previous = function(offset) {
- if (typeof offset === "undefined")
- offset = 1;
- return new Month(this.year, this.month - offset);
-};
-
-/**
- * @param {!number=} offset
- * @return {!Month}
- */
-Month.prototype.next = function(offset) {
- if (typeof offset === "undefined")
- offset = 1;
- return new Month(this.year, this.month + offset);
-};
-
-/**
- * @return {!Date}
- */
-Month.prototype.startDate = function() {
- return createUTCDate(this.year, this.month, 1);
-};
-
-/**
- * @return {!Date}
- */
-Month.prototype.endDate = function() {
- if (this.equals(Month.Maximum))
- return Day.Maximum.startDate();
- return this.next().startDate();
-};
-
-/**
- * @return {!Day}
- */
-Month.prototype.firstDay = function() {
- return new Day(this.year, this.month, 1);
-};
-
-/**
- * @return {!Day}
- */
-Month.prototype.middleDay = function() {
- return new Day(this.year, this.month, this.month === 2 ? 14 : 15);
-};
-
-/**
- * @return {!Day}
- */
-Month.prototype.lastDay = function() {
- if (this.equals(Month.Maximum))
- return Day.Maximum;
- return this.next().firstDay().previous();
-};
-
-/**
- * @return {!number}
- */
-Month.prototype.valueOf = function() {
- return (this.year - 1970) * MonthsPerYear + this.month;
-};
-
-/**
- * @return {!string}
- */
-Month.prototype.toString = function() {
- var yearString = String(this.year);
- if (yearString.length < 4)
- yearString = ("000" + yearString).substr(-4, 4);
- return yearString + "-" + ("0" + (this.month + 1)).substr(-2, 2);
-};
-
-/**
- * @return {!string}
- */
-Month.prototype.toLocaleString = function() {
- if (global.params.locale === "ja")
- return "" + this.year + "年" + formatJapaneseImperialEra(this.year, this.month) + " " + (this.month + 1) + "月";
- return window.pagePopupController.formatMonth(this.year, this.month);
-};
-
-/**
- * @return {!string}
- */
-Month.prototype.toShortLocaleString = function() {
- return window.pagePopupController.formatShortMonth(this.year, this.month);
-};
-
-// ----------------------------------------------------------------
-// Initialization
-
-/**
- * @param {Event} event
- */
-function handleMessage(event) {
- if (global.argumentsReceived)
- return;
- global.argumentsReceived = true;
- initialize(JSON.parse(event.data));
-}
-
-/**
- * @param {!Object} params
- */
-function setGlobalParams(params) {
- var name;
- for (name in global.params) {
- if (typeof params[name] === "undefined")
- console.warn("Missing argument: " + name);
- }
- for (name in params) {
- global.params[name] = params[name];
- }
-};
-
-/**
- * @param {!Object} args
- */
-function initialize(args) {
- setGlobalParams(args);
- if (global.params.suggestionValues && global.params.suggestionValues.length)
- openSuggestionPicker();
- else
- openCalendarPicker();
-}
-
-function closePicker() {
- if (global.picker)
- global.picker.cleanup();
- var main = $("main");
- main.innerHTML = "";
- main.className = "";
-};
-
-function openSuggestionPicker() {
- closePicker();
- global.picker = new SuggestionPicker($("main"), global.params);
-};
-
-function openCalendarPicker() {
- closePicker();
- global.picker = new CalendarPicker(global.params.mode, global.params);
- global.picker.attachTo($("main"));
-};
-
-/**
- * @constructor
- */
-function EventEmitter() {
-};
-
-/**
- * @param {!string} type
- * @param {!function({...*})} callback
- */
-EventEmitter.prototype.on = function(type, callback) {
- console.assert(callback instanceof Function);
- if (!this._callbacks)
- this._callbacks = {};
- if (!this._callbacks[type])
- this._callbacks[type] = [];
- this._callbacks[type].push(callback);
-};
-
-EventEmitter.prototype.hasListener = function(type) {
- if (!this._callbacks)
- return false;
- var callbacksForType = this._callbacks[type];
- if (!callbacksForType)
- return false;
- return callbacksForType.length > 0;
-};
-
-/**
- * @param {!string} type
- * @param {!function(Object)} callback
- */
-EventEmitter.prototype.removeListener = function(type, callback) {
- if (!this._callbacks)
- return;
- var callbacksForType = this._callbacks[type];
- if (!callbacksForType)
- return;
- callbacksForType.splice(callbacksForType.indexOf(callback), 1);
- if (callbacksForType.length === 0)
- delete this._callbacks[type];
-};
-
-/**
- * @param {!string} type
- * @param {...*} var_args
- */
-EventEmitter.prototype.dispatchEvent = function(type) {
- if (!this._callbacks)
- return;
- var callbacksForType = this._callbacks[type];
- if (!callbacksForType)
- return;
- for (var i = 0; i < callbacksForType.length; ++i) {
- callbacksForType[i].apply(this, Array.prototype.slice.call(arguments, 1));
- }
-};
-
-// Parameter t should be a number between 0 and 1.
-var AnimationTimingFunction = {
- Linear: function(t){
- return t;
- },
- EaseInOut: function(t){
- t *= 2;
- if (t < 1)
- return Math.pow(t, 3) / 2;
- t -= 2;
- return Math.pow(t, 3) / 2 + 1;
- }
-};
-
-/**
- * @constructor
- * @extends EventEmitter
- */
-function AnimationManager() {
- EventEmitter.call(this);
-
- this._isRunning = false;
- this._runningAnimatorCount = 0;
- this._runningAnimators = {};
- this._animationFrameCallbackBound = this._animationFrameCallback.bind(this);
-}
-
-AnimationManager.prototype = Object.create(EventEmitter.prototype);
-
-AnimationManager.EventTypeAnimationFrameWillFinish = "animationFrameWillFinish";
-
-AnimationManager.prototype._startAnimation = function() {
- if (this._isRunning)
- return;
- this._isRunning = true;
- window.webkitRequestAnimationFrame(this._animationFrameCallbackBound);
-};
-
-AnimationManager.prototype._stopAnimation = function() {
- if (!this._isRunning)
- return;
- this._isRunning = false;
-};
-
-/**
- * @param {!Animator} animator
- */
-AnimationManager.prototype.add = function(animator) {
- if (this._runningAnimators[animator.id])
- return;
- this._runningAnimators[animator.id] = animator;
- this._runningAnimatorCount++;
- if (this._needsTimer())
- this._startAnimation();
-};
-
-/**
- * @param {!Animator} animator
- */
-AnimationManager.prototype.remove = function(animator) {
- if (!this._runningAnimators[animator.id])
- return;
- delete this._runningAnimators[animator.id];
- this._runningAnimatorCount--;
- if (!this._needsTimer())
- this._stopAnimation();
-};
-
-AnimationManager.prototype._animationFrameCallback = function(now) {
- if (this._runningAnimatorCount > 0) {
- for (var id in this._runningAnimators) {
- this._runningAnimators[id].onAnimationFrame(now);
- }
- }
- this.dispatchEvent(AnimationManager.EventTypeAnimationFrameWillFinish);
- if (this._isRunning)
- window.webkitRequestAnimationFrame(this._animationFrameCallbackBound);
-};
-
-/**
- * @return {!boolean}
- */
-AnimationManager.prototype._needsTimer = function() {
- return this._runningAnimatorCount > 0 || this.hasListener(AnimationManager.EventTypeAnimationFrameWillFinish);
-};
-
-/**
- * @param {!string} type
- * @param {!Function} callback
- * @override
- */
-AnimationManager.prototype.on = function(type, callback) {
- EventEmitter.prototype.on.call(this, type, callback);
- if (this._needsTimer())
- this._startAnimation();
-};
-
-/**
- * @param {!string} type
- * @param {!Function} callback
- * @override
- */
-AnimationManager.prototype.removeListener = function(type, callback) {
- EventEmitter.prototype.removeListener.call(this, type, callback);
- if (!this._needsTimer())
- this._stopAnimation();
-};
-
-AnimationManager.shared = new AnimationManager();
-
-/**
- * @constructor
- * @extends EventEmitter
- */
-function Animator() {
- EventEmitter.call(this);
-
- /**
- * @type {!number}
- * @const
- */
- this.id = Animator._lastId++;
- /**
- * @type {!number}
- */
- this.duration = 100;
- /**
- * @type {?function}
- */
- this.step = null;
- /**
- * @type {!boolean}
- * @protected
- */
- this._isRunning = false;
- /**
- * @type {!number}
- */
- this.currentValue = 0;
- /**
- * @type {!number}
- * @protected
- */
- this._lastStepTime = 0;
-}
-
-Animator.prototype = Object.create(EventEmitter.prototype);
-
-Animator._lastId = 0;
-
-Animator.EventTypeDidAnimationStop = "didAnimationStop";
-
-/**
- * @return {!boolean}
- */
-Animator.prototype.isRunning = function() {
- return this._isRunning;
-};
-
-Animator.prototype.start = function() {
- this._lastStepTime = Date.now();
- this._isRunning = true;
- AnimationManager.shared.add(this);
-};
-
-Animator.prototype.stop = function() {
- if (!this._isRunning)
- return;
- this._isRunning = false;
- AnimationManager.shared.remove(this);
- this.dispatchEvent(Animator.EventTypeDidAnimationStop, this);
-};
-
-/**
- * @param {!number} now
- */
-Animator.prototype.onAnimationFrame = function(now) {
- this._lastStepTime = now;
- this.step(this);
-};
-
-/**
- * @constructor
- * @extends Animator
- */
-function TransitionAnimator() {
- Animator.call(this);
- /**
- * @type {!number}
- * @protected
- */
- this._from = 0;
- /**
- * @type {!number}
- * @protected
- */
- this._to = 0;
- /**
- * @type {!number}
- * @protected
- */
- this._delta = 0;
- /**
- * @type {!number}
- */
- this.progress = 0.0;
- /**
- * @type {!function}
- */
- this.timingFunction = AnimationTimingFunction.Linear;
-}
-
-TransitionAnimator.prototype = Object.create(Animator.prototype);
-
-/**
- * @param {!number} value
- */
-TransitionAnimator.prototype.setFrom = function(value) {
- this._from = value;
- this._delta = this._to - this._from;
-};
-
-TransitionAnimator.prototype.start = function() {
- console.assert(isFinite(this.duration));
- this.progress = 0.0;
- this.currentValue = this._from;
- Animator.prototype.start.call(this);
-};
-
-/**
- * @param {!number} value
- */
-TransitionAnimator.prototype.setTo = function(value) {
- this._to = value;
- this._delta = this._to - this._from;
-};
-
-/**
- * @param {!number} now
- */
-TransitionAnimator.prototype.onAnimationFrame = function(now) {
- this.progress += (now - this._lastStepTime) / this.duration;
- this.progress = Math.min(1.0, this.progress);
- this._lastStepTime = now;
- this.currentValue = this.timingFunction(this.progress) * this._delta + this._from;
- this.step(this);
- if (this.progress === 1.0) {
- this.stop();
- return;
- }
-};
-
-/**
- * @constructor
- * @extends Animator
- * @param {!number} initialVelocity
- * @param {!number} initialValue
- */
-function FlingGestureAnimator(initialVelocity, initialValue) {
- Animator.call(this);
- /**
- * @type {!number}
- */
- this.initialVelocity = initialVelocity;
- /**
- * @type {!number}
- */
- this.initialValue = initialValue;
- /**
- * @type {!number}
- * @protected
- */
- this._elapsedTime = 0;
- var startVelocity = Math.abs(this.initialVelocity);
- if (startVelocity > this._velocityAtTime(0))
- startVelocity = this._velocityAtTime(0);
- if (startVelocity < 0)
- startVelocity = 0;
- /**
- * @type {!number}
- * @protected
- */
- this._timeOffset = this._timeAtVelocity(startVelocity);
- /**
- * @type {!number}
- * @protected
- */
- this._positionOffset = this._valueAtTime(this._timeOffset);
- /**
- * @type {!number}
- */
- this.duration = this._timeAtVelocity(0);
-}
-
-FlingGestureAnimator.prototype = Object.create(Animator.prototype);
-
-// Velocity is subject to exponential decay. These parameters are coefficients
-// that determine the curve.
-FlingGestureAnimator._P0 = -5707.62;
-FlingGestureAnimator._P1 = 0.172;
-FlingGestureAnimator._P2 = 0.0037;
-
-/**
- * @param {!number} t
- */
-FlingGestureAnimator.prototype._valueAtTime = function(t) {
- return FlingGestureAnimator._P0 * Math.exp(-FlingGestureAnimator._P2 * t) - FlingGestureAnimator._P1 * t - FlingGestureAnimator._P0;
-};
-
-/**
- * @param {!number} t
- */
-FlingGestureAnimator.prototype._velocityAtTime = function(t) {
- return -FlingGestureAnimator._P0 * FlingGestureAnimator._P2 * Math.exp(-FlingGestureAnimator._P2 * t) - FlingGestureAnimator._P1;
-};
-
-/**
- * @param {!number} v
- */
-FlingGestureAnimator.prototype._timeAtVelocity = function(v) {
- return -Math.log((v + FlingGestureAnimator._P1) / (-FlingGestureAnimator._P0 * FlingGestureAnimator._P2)) / FlingGestureAnimator._P2;
-};
-
-FlingGestureAnimator.prototype.start = function() {
- this._lastStepTime = Date.now();
- Animator.prototype.start.call(this);
-};
-
-/**
- * @param {!number} now
- */
-FlingGestureAnimator.prototype.onAnimationFrame = function(now) {
- this._elapsedTime += now - this._lastStepTime;
- this._lastStepTime = now;
- if (this._elapsedTime + this._timeOffset >= this.duration) {
- this.stop();
- return;
- }
- var position = this._valueAtTime(this._elapsedTime + this._timeOffset) - this._positionOffset;
- if (this.initialVelocity < 0)
- position = -position;
- this.currentValue = position + this.initialValue;
- this.step(this);
-};
-
-/**
- * @constructor
- * @extends EventEmitter
- * @param {?Element} element
- * View adds itself as a property on the element so we can access it from Event.target.
- */
-function View(element) {
- EventEmitter.call(this);
- /**
- * @type {Element}
- * @const
- */
- this.element = element || createElement("div");
- this.element.$view = this;
- this.bindCallbackMethods();
-}
-
-View.prototype = Object.create(EventEmitter.prototype);
-
-/**
- * @param {!Element} ancestorElement
- * @return {?Object}
- */
-View.prototype.offsetRelativeTo = function(ancestorElement) {
- var x = 0;
- var y = 0;
- var element = this.element;
- while (element) {
- x += element.offsetLeft || 0;
- y += element.offsetTop || 0;
- element = element.offsetParent;
- if (element === ancestorElement)
- return {x: x, y: y};
- }
- return null;
-};
-
-/**
- * @param {!View|Node} parent
- * @param {?View|Node=} before
- */
-View.prototype.attachTo = function(parent, before) {
- if (parent instanceof View)
- return this.attachTo(parent.element, before);
- if (typeof before === "undefined")
- before = null;
- if (before instanceof View)
- before = before.element;
- parent.insertBefore(this.element, before);
-};
-
-View.prototype.bindCallbackMethods = function() {
- for (var methodName in this) {
- if (!/^on[A-Z]/.test(methodName))
- continue;
- if (this.hasOwnProperty(methodName))
- continue;
- var method = this[methodName];
- if (!(method instanceof Function))
- continue;
- this[methodName] = method.bind(this);
- }
-};
-
-/**
- * @constructor
- * @extends View
- */
-function ScrollView() {
- View.call(this, createElement("div", ScrollView.ClassNameScrollView));
- /**
- * @type {Element}
- * @const
- */
- this.contentElement = createElement("div", ScrollView.ClassNameScrollViewContent);
- this.element.appendChild(this.contentElement);
- /**
- * @type {number}
- */
- this.minimumContentOffset = -Infinity;
- /**
- * @type {number}
- */
- this.maximumContentOffset = Infinity;
- /**
- * @type {number}
- * @protected
- */
- this._contentOffset = 0;
- /**
- * @type {number}
- * @protected
- */
- this._width = 0;
- /**
- * @type {number}
- * @protected
- */
- this._height = 0;
- /**
- * @type {Animator}
- * @protected
- */
- this._scrollAnimator = null;
- /**
- * @type {?Object}
- */
- this.delegate = null;
- /**
- * @type {!number}
- */
- this._lastTouchPosition = 0;
- /**
- * @type {!number}
- */
- this._lastTouchVelocity = 0;
- /**
- * @type {!number}
- */
- this._lastTouchTimeStamp = 0;
-
- this.element.addEventListener("mousewheel", this.onMouseWheel, false);
- this.element.addEventListener("touchstart", this.onTouchStart, false);
-
- /**
- * The content offset is partitioned so the it can go beyond the CSS limit
- * of 33554433px.
- * @type {number}
- * @protected
- */
- this._partitionNumber = 0;
-}
-
-ScrollView.prototype = Object.create(View.prototype);
-
-ScrollView.PartitionHeight = 100000;
-ScrollView.ClassNameScrollView = "scroll-view";
-ScrollView.ClassNameScrollViewContent = "scroll-view-content";
-
-/**
- * @param {!Event} event
- */
-ScrollView.prototype.onTouchStart = function(event) {
- var touch = event.touches[0];
- this._lastTouchPosition = touch.clientY;
- this._lastTouchVelocity = 0;
- this._lastTouchTimeStamp = event.timeStamp;
- if (this._scrollAnimator)
- this._scrollAnimator.stop();
- window.addEventListener("touchmove", this.onWindowTouchMove, false);
- window.addEventListener("touchend", this.onWindowTouchEnd, false);
-};
-
-/**
- * @param {!Event} event
- */
-ScrollView.prototype.onWindowTouchMove = function(event) {
- var touch = event.touches[0];
- var deltaTime = event.timeStamp - this._lastTouchTimeStamp;
- var deltaY = this._lastTouchPosition - touch.clientY;
- this.scrollBy(deltaY, false);
- this._lastTouchVelocity = deltaY / deltaTime;
- this._lastTouchPosition = touch.clientY;
- this._lastTouchTimeStamp = event.timeStamp;
- event.stopPropagation();
- event.preventDefault();
-};
-
-/**
- * @param {!Event} event
- */
-ScrollView.prototype.onWindowTouchEnd = function(event) {
- if (Math.abs(this._lastTouchVelocity) > 0.01) {
- this._scrollAnimator = new FlingGestureAnimator(this._lastTouchVelocity, this._contentOffset);
- this._scrollAnimator.step = this.onFlingGestureAnimatorStep;
- this._scrollAnimator.start();
- }
- window.removeEventListener("touchmove", this.onWindowTouchMove, false);
- window.removeEventListener("touchend", this.onWindowTouchEnd, false);
-};
-
-/**
- * @param {!Animator} animator
- */
-ScrollView.prototype.onFlingGestureAnimatorStep = function(animator) {
- this.scrollTo(animator.currentValue, false);
-};
-
-/**
- * @return {!Animator}
- */
-ScrollView.prototype.scrollAnimator = function() {
- return this._scrollAnimator;
-};
-
-/**
- * @param {!number} width
- */
-ScrollView.prototype.setWidth = function(width) {
- console.assert(isFinite(width));
- if (this._width === width)
- return;
- this._width = width;
- this.element.style.width = this._width + "px";
-};
-
-/**
- * @return {!number}
- */
-ScrollView.prototype.width = function() {
- return this._width;
-};
-
-/**
- * @param {!number} height
- */
-ScrollView.prototype.setHeight = function(height) {
- console.assert(isFinite(height));
- if (this._height === height)
- return;
- this._height = height;
- this.element.style.height = height + "px";
- if (this.delegate)
- this.delegate.scrollViewDidChangeHeight(this);
-};
-
-/**
- * @return {!number}
- */
-ScrollView.prototype.height = function() {
- return this._height;
-};
-
-/**
- * @param {!Animator} animator
- */
-ScrollView.prototype.onScrollAnimatorStep = function(animator) {
- this.setContentOffset(animator.currentValue);
-};
-
-/**
- * @param {!number} offset
- * @param {?boolean} animate
- */
-ScrollView.prototype.scrollTo = function(offset, animate) {
- console.assert(isFinite(offset));
- if (!animate) {
- this.setContentOffset(offset);
- return;
- }
- if (this._scrollAnimator)
- this._scrollAnimator.stop();
- this._scrollAnimator = new TransitionAnimator();
- this._scrollAnimator.step = this.onScrollAnimatorStep;
- this._scrollAnimator.setFrom(this._contentOffset);
- this._scrollAnimator.setTo(offset);
- this._scrollAnimator.duration = 300;
- this._scrollAnimator.start();
-};
-
-/**
- * @param {!number} offset
- * @param {?boolean} animate
- */
-ScrollView.prototype.scrollBy = function(offset, animate) {
- this.scrollTo(this._contentOffset + offset, animate);
-};
-
-/**
- * @return {!number}
- */
-ScrollView.prototype.contentOffset = function() {
- return this._contentOffset;
-};
-
-/**
- * @param {?Event} event
- */
-ScrollView.prototype.onMouseWheel = function(event) {
- this.setContentOffset(this._contentOffset - event.wheelDelta / 30);
- event.stopPropagation();
- event.preventDefault();
-};
-
-
-/**
- * @param {!number} value
- */
-ScrollView.prototype.setContentOffset = function(value) {
- console.assert(isFinite(value));
- value = Math.min(this.maximumContentOffset - this._height, Math.max(this.minimumContentOffset, Math.floor(value)));
- if (this._contentOffset === value)
- return;
- var newPartitionNumber = Math.floor(value / ScrollView.PartitionHeight);
- var partitionChanged = this._partitionNumber !== newPartitionNumber;
- this._partitionNumber = newPartitionNumber;
- this._contentOffset = value;
- this.contentElement.style.webkitTransform = "translate(0, " + (-this.contentPositionForContentOffset(this._contentOffset)) + "px)";
- if (this.delegate) {
- this.delegate.scrollViewDidChangeContentOffset(this);
- if (partitionChanged)
- this.delegate.scrollViewDidChangePartition(this);
- }
-};
-
-/**
- * @param {!number} offset
- */
-ScrollView.prototype.contentPositionForContentOffset = function(offset) {
- return offset - this._partitionNumber * ScrollView.PartitionHeight;
-};
-
-/**
- * @constructor
- * @extends View
- */
-function ListCell() {
- View.call(this, createElement("div", ListCell.ClassNameListCell));
-
- /**
- * @type {!number}
- */
- this.row = NaN;
- /**
- * @type {!number}
- */
- this._width = 0;
- /**
- * @type {!number}
- */
- this._position = 0;
-}
-
-ListCell.prototype = Object.create(View.prototype);
-
-ListCell.DefaultRecycleBinLimit = 64;
-ListCell.ClassNameListCell = "list-cell";
-ListCell.ClassNameHidden = "hidden";
-
-/**
- * @return {!Array} An array to keep thrown away cells.
- */
-ListCell.prototype._recycleBin = function() {
- console.assert(false, "NOT REACHED: ListCell.prototype._recycleBin needs to be overridden.");
- return [];
-};
-
-ListCell.prototype.throwAway = function() {
- this.hide();
- var limit = typeof this.constructor.RecycleBinLimit === "undefined" ? ListCell.DefaultRecycleBinLimit : this.constructor.RecycleBinLimit;
- var recycleBin = this._recycleBin();
- if (recycleBin.length < limit)
- recycleBin.push(this);
-};
-
-ListCell.prototype.show = function() {
- this.element.classList.remove(ListCell.ClassNameHidden);
-};
-
-ListCell.prototype.hide = function() {
- this.element.classList.add(ListCell.ClassNameHidden);
-};
-
-/**
- * @return {!number} Width in pixels.
- */
-ListCell.prototype.width = function(){
- return this._width;
-};
-
-/**
- * @param {!number} width Width in pixels.
- */
-ListCell.prototype.setWidth = function(width){
- if (this._width === width)
- return;
- this._width = width;
- this.element.style.width = this._width + "px";
-};
-
-/**
- * @return {!number} Position in pixels.
- */
-ListCell.prototype.position = function(){
- return this._position;
-};
-
-/**
- * @param {!number} y Position in pixels.
- */
-ListCell.prototype.setPosition = function(y) {
- if (this._position === y)
- return;
- this._position = y;
- this.element.style.webkitTransform = "translate(0, " + this._position + "px)";
-};
-
-/**
- * @param {!boolean} selected
- */
-ListCell.prototype.setSelected = function(selected) {
- if (this._selected === selected)
- return;
- this._selected = selected;
- if (this._selected)
- this.element.classList.add("selected");
- else
- this.element.classList.remove("selected");
-};
-
-/**
- * @constructor
- * @extends View
- */
-function ListView() {
- View.call(this, createElement("div", ListView.ClassNameListView));
- this.element.tabIndex = 0;
-
- /**
- * @type {!number}
- * @private
- */
- this._width = 0;
- /**
- * @type {!Object}
- * @private
- */
- this._cells = {};
-
- /**
- * @type {!number}
- */
- this.selectedRow = ListView.NoSelection;
-
- /**
- * @type {!ScrollView}
- */
- this.scrollView = new ScrollView();
- this.scrollView.delegate = this;
- this.scrollView.minimumContentOffset = 0;
- this.scrollView.setWidth(0);
- this.scrollView.setHeight(0);
- this.scrollView.attachTo(this);
-
- this.element.addEventListener("click", this.onClick, false);
-
- /**
- * @type {!boolean}
- * @private
- */
- this._needsUpdateCells = false;
-}
-
-ListView.prototype = Object.create(View.prototype);
-
-ListView.NoSelection = -1;
-ListView.ClassNameListView = "list-view";
-
-ListView.prototype.onAnimationFrameWillFinish = function() {
- if (this._needsUpdateCells)
- this.updateCells();
-};
-
-/**
- * @param {!boolean} needsUpdateCells
- */
-ListView.prototype.setNeedsUpdateCells = function(needsUpdateCells) {
- if (this._needsUpdateCells === needsUpdateCells)
- return;
- this._needsUpdateCells = needsUpdateCells;
- if (this._needsUpdateCells)
- AnimationManager.shared.on(AnimationManager.EventTypeAnimationFrameWillFinish, this.onAnimationFrameWillFinish);
- else
- AnimationManager.shared.removeListener(AnimationManager.EventTypeAnimationFrameWillFinish, this.onAnimationFrameWillFinish);
-};
-
-/**
- * @param {!number} row
- * @return {?ListCell}
- */
-ListView.prototype.cellAtRow = function(row) {
- return this._cells[row];
-};
-
-/**
- * @param {!number} offset Scroll offset in pixels.
- * @return {!number}
- */
-ListView.prototype.rowAtScrollOffset = function(offset) {
- console.assert(false, "NOT REACHED: ListView.prototype.rowAtScrollOffset needs to be overridden.");
- return 0;
-};
-
-/**
- * @param {!number} row
- * @return {!number} Scroll offset in pixels.
- */
-ListView.prototype.scrollOffsetForRow = function(row) {
- console.assert(false, "NOT REACHED: ListView.prototype.scrollOffsetForRow needs to be overridden.");
- return 0;
-};
-
-/**
- * @param {!number} row
- * @return {!ListCell}
- */
-ListView.prototype.addCellIfNecessary = function(row) {
- var cell = this._cells[row];
- if (cell)
- return cell;
- cell = this.prepareNewCell(row);
- cell.attachTo(this.scrollView.contentElement);
- cell.setWidth(this._width);
- cell.setPosition(this.scrollView.contentPositionForContentOffset(this.scrollOffsetForRow(row)));
- this._cells[row] = cell;
- return cell;
-};
-
-/**
- * @param {!number} row
- * @return {!ListCell}
- */
-ListView.prototype.prepareNewCell = function(row) {
- console.assert(false, "NOT REACHED: ListView.prototype.prepareNewCell should be overridden.");
- return new ListCell();
-};
-
-/**
- * @param {!ListCell} cell
- */
-ListView.prototype.throwAwayCell = function(cell) {
- delete this._cells[cell.row];
- cell.throwAway();
-};
-
-/**
- * @return {!number}
- */
-ListView.prototype.firstVisibleRow = function() {
- return this.rowAtScrollOffset(this.scrollView.contentOffset());
-};
-
-/**
- * @return {!number}
- */
-ListView.prototype.lastVisibleRow = function() {
- return this.rowAtScrollOffset(this.scrollView.contentOffset() + this.scrollView.height() - 1);
-};
-
-/**
- * @param {!ScrollView} scrollView
- */
-ListView.prototype.scrollViewDidChangeContentOffset = function(scrollView) {
- this.setNeedsUpdateCells(true);
-};
-
-/**
- * @param {!ScrollView} scrollView
- */
-ListView.prototype.scrollViewDidChangeHeight = function(scrollView) {
- this.setNeedsUpdateCells(true);
-};
-
-/**
- * @param {!ScrollView} scrollView
- */
-ListView.prototype.scrollViewDidChangePartition = function(scrollView) {
- this.setNeedsUpdateCells(true);
-};
-
-ListView.prototype.updateCells = function() {
- var firstVisibleRow = this.firstVisibleRow();
- var lastVisibleRow = this.lastVisibleRow();
- console.assert(firstVisibleRow <= lastVisibleRow);
- for (var c in this._cells) {
- var cell = this._cells[c];
- if (cell.row < firstVisibleRow || cell.row > lastVisibleRow)
- this.throwAwayCell(cell);
- }
- for (var i = firstVisibleRow; i <= lastVisibleRow; ++i) {
- var cell = this._cells[i];
- if (cell)
- cell.setPosition(this.scrollView.contentPositionForContentOffset(this.scrollOffsetForRow(cell.row)));
- else
- this.addCellIfNecessary(i);
- }
- this.setNeedsUpdateCells(false);
-};
-
-/**
- * @return {!number} Width in pixels.
- */
-ListView.prototype.width = function() {
- return this._width;
-};
-
-/**
- * @param {!number} width Width in pixels.
- */
-ListView.prototype.setWidth = function(width) {
- if (this._width === width)
- return;
- this._width = width;
- this.scrollView.setWidth(this._width);
- for (var c in this._cells) {
- this._cells[c].setWidth(this._width);
- }
- this.element.style.width = this._width + "px";
- this.setNeedsUpdateCells(true);
-};
-
-/**
- * @return {!number} Height in pixels.
- */
-ListView.prototype.height = function() {
- return this.scrollView.height();
-};
-
-/**
- * @param {!number} height Height in pixels.
- */
-ListView.prototype.setHeight = function(height) {
- this.scrollView.setHeight(height);
-};
-
-/**
- * @param {?Event} event
- */
-ListView.prototype.onClick = function(event) {
- var clickedCellElement = enclosingNodeOrSelfWithClass(event.target, ListCell.ClassNameListCell);
- if (!clickedCellElement)
- return;
- var clickedCell = clickedCellElement.$view;
- if (clickedCell.row !== this.selectedRow)
- this.select(clickedCell.row);
-};
-
-/**
- * @param {!number} row
- */
-ListView.prototype.select = function(row) {
- if (this.selectedRow === row)
- return;
- this.deselect();
- if (row === ListView.NoSelection)
- return;
- this.selectedRow = row;
- var selectedCell = this._cells[this.selectedRow];
- if (selectedCell)
- selectedCell.setSelected(true);
-};
-
-ListView.prototype.deselect = function() {
- if (this.selectedRow === ListView.NoSelection)
- return;
- var selectedCell = this._cells[this.selectedRow];
- if (selectedCell)
- selectedCell.setSelected(false);
- this.selectedRow = ListView.NoSelection;
-};
-
-/**
- * @param {!number} row
- * @param {!boolean} animate
- */
-ListView.prototype.scrollToRow = function(row, animate) {
- this.scrollView.scrollTo(this.scrollOffsetForRow(row), animate);
-};
-
-/**
- * @constructor
- * @extends View
- * @param {!ScrollView} scrollView
- */
-function ScrubbyScrollBar(scrollView) {
- View.call(this, createElement("div", ScrubbyScrollBar.ClassNameScrubbyScrollBar));
-
- /**
- * @type {!Element}
- * @const
- */
- this.thumb = createElement("div", ScrubbyScrollBar.ClassNameScrubbyScrollThumb);
- this.element.appendChild(this.thumb);
-
- /**
- * @type {!ScrollView}
- * @const
- */
- this.scrollView = scrollView;
-
- /**
- * @type {!number}
- * @protected
- */
- this._height = 0;
- /**
- * @type {!number}
- * @protected
- */
- this._thumbHeight = 0;
- /**
- * @type {!number}
- * @protected
- */
- this._thumbPosition = 0;
-
- this.setHeight(0);
- this.setThumbHeight(ScrubbyScrollBar.ThumbHeight);
-
- /**
- * @type {?Animator}
- * @protected
- */
- this._thumbStyleTopAnimator = null;
-
- /**
- * @type {?number}
- * @protected
- */
- this._timer = null;
-
- this.element.addEventListener("mousedown", this.onMouseDown, false);
- this.element.addEventListener("touchstart", this.onTouchStart, false);
-}
-
-ScrubbyScrollBar.prototype = Object.create(View.prototype);
-
-ScrubbyScrollBar.ScrollInterval = 16;
-ScrubbyScrollBar.ThumbMargin = 2;
-ScrubbyScrollBar.ThumbHeight = 30;
-ScrubbyScrollBar.ClassNameScrubbyScrollBar = "scrubby-scroll-bar";
-ScrubbyScrollBar.ClassNameScrubbyScrollThumb = "scrubby-scroll-thumb";
-
-/**
- * @param {?Event} event
- */
-ScrubbyScrollBar.prototype.onTouchStart = function(event) {
- var touch = event.touches[0];
- this._setThumbPositionFromEventPosition(touch.clientY);
- if (this._thumbStyleTopAnimator)
- this._thumbStyleTopAnimator.stop();
- this._timer = setInterval(this.onScrollTimer, ScrubbyScrollBar.ScrollInterval);
- window.addEventListener("touchmove", this.onWindowTouchMove, false);
- window.addEventListener("touchend", this.onWindowTouchEnd, false);
- event.stopPropagation();
- event.preventDefault();
-};
-
-/**
- * @param {?Event} event
- */
-ScrubbyScrollBar.prototype.onWindowTouchMove = function(event) {
- var touch = event.touches[0];
- this._setThumbPositionFromEventPosition(touch.clientY);
- event.stopPropagation();
- event.preventDefault();
-};
-
-/**
- * @param {?Event} event
- */
-ScrubbyScrollBar.prototype.onWindowTouchEnd = function(event) {
- this._thumbStyleTopAnimator = new TransitionAnimator();
- this._thumbStyleTopAnimator.step = this.onThumbStyleTopAnimationStep;
- this._thumbStyleTopAnimator.setFrom(this.thumb.offsetTop);
- this._thumbStyleTopAnimator.setTo((this._height - this._thumbHeight) / 2);
- this._thumbStyleTopAnimator.timingFunction = AnimationTimingFunction.EaseInOut;
- this._thumbStyleTopAnimator.duration = 100;
- this._thumbStyleTopAnimator.start();
-
- window.removeEventListener("touchmove", this.onWindowTouchMove, false);
- window.removeEventListener("touchend", this.onWindowTouchEnd, false);
- clearInterval(this._timer);
-};
-
-/**
- * @return {!number} Height of the view in pixels.
- */
-ScrubbyScrollBar.prototype.height = function() {
- return this._height;
-};
-
-/**
- * @param {!number} height Height of the view in pixels.
- */
-ScrubbyScrollBar.prototype.setHeight = function(height) {
- if (this._height === height)
- return;
- this._height = height;
- this.element.style.height = this._height + "px";
- this.thumb.style.top = ((this._height - this._thumbHeight) / 2) + "px";
- this._thumbPosition = 0;
-};
-
-/**
- * @param {!number} height Height of the scroll bar thumb in pixels.
- */
-ScrubbyScrollBar.prototype.setThumbHeight = function(height) {
- if (this._thumbHeight === height)
- return;
- this._thumbHeight = height;
- this.thumb.style.height = this._thumbHeight + "px";
- this.thumb.style.top = ((this._height - this._thumbHeight) / 2) + "px";
- this._thumbPosition = 0;
-};
-
-/**
- * @param {number} position
- */
-ScrubbyScrollBar.prototype._setThumbPositionFromEventPosition = function(position) {
- var thumbMin = ScrubbyScrollBar.ThumbMargin;
- var thumbMax = this._height - this._thumbHeight - ScrubbyScrollBar.ThumbMargin * 2;
- var y = position - this.element.getBoundingClientRect().top - this.element.clientTop + this.element.scrollTop;
- var thumbPosition = y - this._thumbHeight / 2;
- thumbPosition = Math.max(thumbPosition, thumbMin);
- thumbPosition = Math.min(thumbPosition, thumbMax);
- this.thumb.style.top = thumbPosition + "px";
- this._thumbPosition = 1.0 - (thumbPosition - thumbMin) / (thumbMax - thumbMin) * 2;
-};
-
-/**
- * @param {?Event} event
- */
-ScrubbyScrollBar.prototype.onMouseDown = function(event) {
- this._setThumbPositionFromEventPosition(event.clientY);
-
- window.addEventListener("mousemove", this.onWindowMouseMove, false);
- window.addEventListener("mouseup", this.onWindowMouseUp, false);
- if (this._thumbStyleTopAnimator)
- this._thumbStyleTopAnimator.stop();
- this._timer = setInterval(this.onScrollTimer, ScrubbyScrollBar.ScrollInterval);
- event.stopPropagation();
- event.preventDefault();
-};
-
-/**
- * @param {?Event} event
- */
-ScrubbyScrollBar.prototype.onWindowMouseMove = function(event) {
- this._setThumbPositionFromEventPosition(event.clientY);
-};
-
-/**
- * @param {?Event} event
- */
-ScrubbyScrollBar.prototype.onWindowMouseUp = function(event) {
- this._thumbStyleTopAnimator = new TransitionAnimator();
- this._thumbStyleTopAnimator.step = this.onThumbStyleTopAnimationStep;
- this._thumbStyleTopAnimator.setFrom(this.thumb.offsetTop);
- this._thumbStyleTopAnimator.setTo((this._height - this._thumbHeight) / 2);
- this._thumbStyleTopAnimator.timingFunction = AnimationTimingFunction.EaseInOut;
- this._thumbStyleTopAnimator.duration = 100;
- this._thumbStyleTopAnimator.start();
-
- window.removeEventListener("mousemove", this.onWindowMouseMove, false);
- window.removeEventListener("mouseup", this.onWindowMouseUp, false);
- clearInterval(this._timer);
-};
-
-/**
- * @param {!Animator} animator
- */
-ScrubbyScrollBar.prototype.onThumbStyleTopAnimationStep = function(animator) {
- this.thumb.style.top = animator.currentValue + "px";
-};
-
-ScrubbyScrollBar.prototype.onScrollTimer = function() {
- var scrollAmount = Math.pow(this._thumbPosition, 2) * 10;
- if (this._thumbPosition > 0)
- scrollAmount = -scrollAmount;
- this.scrollView.scrollBy(scrollAmount, false);
-};
-
-/**
- * @constructor
- * @extends ListCell
- * @param {!Array} shortMonthLabels
- */
-function YearListCell(shortMonthLabels) {
- ListCell.call(this);
- this.element.classList.add(YearListCell.ClassNameYearListCell);
- this.element.style.height = YearListCell.Height + "px";
-
- /**
- * @type {!Element}
- * @const
- */
- this.label = createElement("div", YearListCell.ClassNameLabel, "----");
- this.element.appendChild(this.label);
- this.label.style.height = (YearListCell.Height - YearListCell.BorderBottomWidth) + "px";
- this.label.style.lineHeight = (YearListCell.Height - YearListCell.BorderBottomWidth) + "px";
-
- /**
- * @type {!Array} Array of the 12 month button elements.
- * @const
- */
- this.monthButtons = [];
- var monthChooserElement = createElement("div", YearListCell.ClassNameMonthChooser);
- for (var r = 0; r < YearListCell.ButtonRows; ++r) {
- var buttonsRow = createElement("div", YearListCell.ClassNameMonthButtonsRow);
- for (var c = 0; c < YearListCell.ButtonColumns; ++c) {
- var month = c + r * YearListCell.ButtonColumns;
- var button = createElement("button", YearListCell.ClassNameMonthButton, shortMonthLabels[month]);
- button.dataset.month = month;
- buttonsRow.appendChild(button);
- this.monthButtons.push(button);
- }
- monthChooserElement.appendChild(buttonsRow);
- }
- this.element.appendChild(monthChooserElement);
-
- /**
- * @type {!boolean}
- * @private
- */
- this._selected = false;
- /**
- * @type {!number}
- * @private
- */
- this._height = 0;
-}
-
-YearListCell.prototype = Object.create(ListCell.prototype);
-
-YearListCell.Height = hasInaccuratePointingDevice() ? 31 : 25;
-YearListCell.BorderBottomWidth = 1;
-YearListCell.ButtonRows = 3;
-YearListCell.ButtonColumns = 4;
-YearListCell.SelectedHeight = hasInaccuratePointingDevice() ? 127 : 121;
-YearListCell.ClassNameYearListCell = "year-list-cell";
-YearListCell.ClassNameLabel = "label";
-YearListCell.ClassNameMonthChooser = "month-chooser";
-YearListCell.ClassNameMonthButtonsRow = "month-buttons-row";
-YearListCell.ClassNameMonthButton = "month-button";
-YearListCell.ClassNameHighlighted = "highlighted";
-
-YearListCell._recycleBin = [];
-
-/**
- * @return {!Array}
- * @override
- */
-YearListCell.prototype._recycleBin = function() {
- return YearListCell._recycleBin;
-};
-
-/**
- * @param {!number} row
- */
-YearListCell.prototype.reset = function(row) {
- this.row = row;
- this.label.textContent = row + 1;
- for (var i = 0; i < this.monthButtons.length; ++i) {
- this.monthButtons[i].classList.remove(YearListCell.ClassNameHighlighted);
- }
- this.show();
-};
-
-/**
- * @return {!number} The height in pixels.
- */
-YearListCell.prototype.height = function() {
- return this._height;
-};
-
-/**
- * @param {!number} height Height in pixels.
- */
-YearListCell.prototype.setHeight = function(height) {
- if (this._height === height)
- return;
- this._height = height;
- this.element.style.height = this._height + "px";
-};
-
-/**
- * @constructor
- * @extends ListView
- * @param {!Month} minimumMonth
- * @param {!Month} maximumMonth
- */
-function YearListView(minimumMonth, maximumMonth) {
- ListView.call(this);
- this.element.classList.add("year-list-view");
-
- /**
- * @type {?Month}
- */
- this.highlightedMonth = null;
- /**
- * @type {!Month}
- * @const
- * @protected
- */
- this._minimumMonth = minimumMonth;
- /**
- * @type {!Month}
- * @const
- * @protected
- */
- this._maximumMonth = maximumMonth;
-
- this.scrollView.minimumContentOffset = (this._minimumMonth.year - 1) * YearListCell.Height;
- this.scrollView.maximumContentOffset = (this._maximumMonth.year - 1) * YearListCell.Height + YearListCell.SelectedHeight;
-
- /**
- * @type {!Object}
- * @const
- * @protected
- */
- this._runningAnimators = {};
- /**
- * @type {!Array}
- * @const
- * @protected
- */
- this._animatingRows = [];
- /**
- * @type {!boolean}
- * @protected
- */
- this._ignoreMouseOutUntillNextMouseOver = false;
-
- /**
- * @type {!ScrubbyScrollBar}
- * @const
- */
- this.scrubbyScrollBar = new ScrubbyScrollBar(this.scrollView);
- this.scrubbyScrollBar.attachTo(this);
-
- this.element.addEventListener("mouseover", this.onMouseOver, false);
- this.element.addEventListener("mouseout", this.onMouseOut, false);
- this.element.addEventListener("keydown", this.onKeyDown, false);
- this.element.addEventListener("touchstart", this.onTouchStart, false);
-}
-
-YearListView.prototype = Object.create(ListView.prototype);
-
-YearListView.Height = YearListCell.SelectedHeight - 1;
-YearListView.EventTypeYearListViewDidHide = "yearListViewDidHide";
-YearListView.EventTypeYearListViewDidSelectMonth = "yearListViewDidSelectMonth";
-
-/**
- * @param {?Event} event
- */
-YearListView.prototype.onTouchStart = function(event) {
- var touch = event.touches[0];
- var monthButtonElement = enclosingNodeOrSelfWithClass(touch.target, YearListCell.ClassNameMonthButton);
- if (!monthButtonElement)
- return;
- var cellElement = enclosingNodeOrSelfWithClass(monthButtonElement, YearListCell.ClassNameYearListCell);
- var cell = cellElement.$view;
- this.highlightMonth(new Month(cell.row + 1, parseInt(monthButtonElement.dataset.month, 10)));
-};
-
-/**
- * @param {?Event} event
- */
-YearListView.prototype.onMouseOver = function(event) {
- var monthButtonElement = enclosingNodeOrSelfWithClass(event.target, YearListCell.ClassNameMonthButton);
- if (!monthButtonElement)
- return;
- var cellElement = enclosingNodeOrSelfWithClass(monthButtonElement, YearListCell.ClassNameYearListCell);
- var cell = cellElement.$view;
- this.highlightMonth(new Month(cell.row + 1, parseInt(monthButtonElement.dataset.month, 10)));
- this._ignoreMouseOutUntillNextMouseOver = false;
-};
-
-/**
- * @param {?Event} event
- */
-YearListView.prototype.onMouseOut = function(event) {
- if (this._ignoreMouseOutUntillNextMouseOver)
- return;
- var monthButtonElement = enclosingNodeOrSelfWithClass(event.target, YearListCell.ClassNameMonthButton);
- if (!monthButtonElement) {
- this.dehighlightMonth();
- }
-};
-
-/**
- * @param {!number} width Width in pixels.
- * @override
- */
-YearListView.prototype.setWidth = function(width) {
- ListView.prototype.setWidth.call(this, width - this.scrubbyScrollBar.element.offsetWidth);
- this.element.style.width = width + "px";
-};
-
-/**
- * @param {!number} height Height in pixels.
- * @override
- */
-YearListView.prototype.setHeight = function(height) {
- ListView.prototype.setHeight.call(this, height);
- this.scrubbyScrollBar.setHeight(height);
-};
-
-/**
- * @enum {number}
- */
-YearListView.RowAnimationDirection = {
- Opening: 0,
- Closing: 1
-};
-
-/**
- * @param {!number} row
- * @param {!YearListView.RowAnimationDirection} direction
- */
-YearListView.prototype._animateRow = function(row, direction) {
- var fromValue = direction === YearListView.RowAnimationDirection.Closing ? YearListCell.SelectedHeight : YearListCell.Height;
- var oldAnimator = this._runningAnimators[row];
- if (oldAnimator) {
- oldAnimator.stop();
- fromValue = oldAnimator.currentValue;
- }
- var cell = this.cellAtRow(row);
- var animator = new TransitionAnimator();
- animator.step = this.onCellHeightAnimatorStep;
- animator.setFrom(fromValue);
- animator.setTo(direction === YearListView.RowAnimationDirection.Opening ? YearListCell.SelectedHeight : YearListCell.Height);
- animator.timingFunction = AnimationTimingFunction.EaseInOut;
- animator.duration = 300;
- animator.row = row;
- animator.on(Animator.EventTypeDidAnimationStop, this.onCellHeightAnimatorDidStop);
- this._runningAnimators[row] = animator;
- this._animatingRows.push(row);
- this._animatingRows.sort();
- animator.start();
-};
-
-/**
- * @param {?Animator} animator
- */
-YearListView.prototype.onCellHeightAnimatorDidStop = function(animator) {
- delete this._runningAnimators[animator.row];
- var index = this._animatingRows.indexOf(animator.row);
- this._animatingRows.splice(index, 1);
-};
-
-/**
- * @param {!Animator} animator
- */
-YearListView.prototype.onCellHeightAnimatorStep = function(animator) {
- var cell = this.cellAtRow(animator.row);
- if (cell)
- cell.setHeight(animator.currentValue);
- this.updateCells();
-};
-
-/**
- * @param {?Event} event
- */
-YearListView.prototype.onClick = function(event) {
- var oldSelectedRow = this.selectedRow;
- ListView.prototype.onClick.call(this, event);
- var year = this.selectedRow + 1;
- if (this.selectedRow !== oldSelectedRow) {
- var month = this.highlightedMonth ? this.highlightedMonth.month : 0;
- this.dispatchEvent(YearListView.EventTypeYearListViewDidSelectMonth, this, new Month(year, month));
- this.scrollView.scrollTo(this.selectedRow * YearListCell.Height, true);
- } else {
- var monthButton = enclosingNodeOrSelfWithClass(event.target, YearListCell.ClassNameMonthButton);
- if (!monthButton)
- return;
- var month = parseInt(monthButton.dataset.month, 10);
- this.dispatchEvent(YearListView.EventTypeYearListViewDidSelectMonth, this, new Month(year, month));
- this.hide();
- }
-};
-
-/**
- * @param {!number} scrollOffset
- * @return {!number}
- * @override
- */
-YearListView.prototype.rowAtScrollOffset = function(scrollOffset) {
- var remainingOffset = scrollOffset;
- var lastAnimatingRow = 0;
- var rowsWithIrregularHeight = this._animatingRows.slice();
- if (this.selectedRow > -1 && !this._runningAnimators[this.selectedRow]) {
- rowsWithIrregularHeight.push(this.selectedRow);
- rowsWithIrregularHeight.sort();
- }
- for (var i = 0; i < rowsWithIrregularHeight.length; ++i) {
- var row = rowsWithIrregularHeight[i];
- var animator = this._runningAnimators[row];
- var rowHeight = animator ? animator.currentValue : YearListCell.SelectedHeight;
- if (remainingOffset <= (row - lastAnimatingRow) * YearListCell.Height) {
- return lastAnimatingRow + Math.floor(remainingOffset / YearListCell.Height);
- }
- remainingOffset -= (row - lastAnimatingRow) * YearListCell.Height;
- if (remainingOffset <= (rowHeight - YearListCell.Height))
- return row;
- remainingOffset -= rowHeight - YearListCell.Height;
- lastAnimatingRow = row;
- }
- return lastAnimatingRow + Math.floor(remainingOffset / YearListCell.Height);
-};
-
-/**
- * @param {!number} row
- * @return {!number}
- * @override
- */
-YearListView.prototype.scrollOffsetForRow = function(row) {
- var scrollOffset = row * YearListCell.Height;
- for (var i = 0; i < this._animatingRows.length; ++i) {
- var animatingRow = this._animatingRows[i];
- if (animatingRow >= row)
- break;
- var animator = this._runningAnimators[animatingRow];
- scrollOffset += animator.currentValue - YearListCell.Height;
- }
- if (this.selectedRow > -1 && this.selectedRow < row && !this._runningAnimators[this.selectedRow]) {
- scrollOffset += YearListCell.SelectedHeight - YearListCell.Height;
- }
- return scrollOffset;
-};
-
-/**
- * @param {!number} row
- * @return {!YearListCell}
- * @override
- */
-YearListView.prototype.prepareNewCell = function(row) {
- var cell = YearListCell._recycleBin.pop() || new YearListCell(global.params.shortMonthLabels);
- cell.reset(row);
- cell.setSelected(this.selectedRow === row);
- if (this.highlightedMonth && row === this.highlightedMonth.year - 1) {
- cell.monthButtons[this.highlightedMonth.month].classList.add(YearListCell.ClassNameHighlighted);
- }
- for (var i = 0; i < cell.monthButtons.length; ++i) {
- var month = new Month(row + 1, i);
- cell.monthButtons[i].disabled = this._minimumMonth > month || this._maximumMonth < month;
- }
- var animator = this._runningAnimators[row];
- if (animator)
- cell.setHeight(animator.currentValue);
- else if (row === this.selectedRow)
- cell.setHeight(YearListCell.SelectedHeight);
- else
- cell.setHeight(YearListCell.Height);
- return cell;
-};
-
-/**
- * @override
- */
-YearListView.prototype.updateCells = function() {
- var firstVisibleRow = this.firstVisibleRow();
- var lastVisibleRow = this.lastVisibleRow();
- console.assert(firstVisibleRow <= lastVisibleRow);
- for (var c in this._cells) {
- var cell = this._cells[c];
- if (cell.row < firstVisibleRow || cell.row > lastVisibleRow)
- this.throwAwayCell(cell);
- }
- for (var i = firstVisibleRow; i <= lastVisibleRow; ++i) {
- var cell = this._cells[i];
- if (cell)
- cell.setPosition(this.scrollView.contentPositionForContentOffset(this.scrollOffsetForRow(cell.row)));
- else
- this.addCellIfNecessary(i);
- }
- this.setNeedsUpdateCells(false);
-};
-
-/**
- * @override
- */
-YearListView.prototype.deselect = function() {
- if (this.selectedRow === ListView.NoSelection)
- return;
- var selectedCell = this._cells[this.selectedRow];
- if (selectedCell)
- selectedCell.setSelected(false);
- this._animateRow(this.selectedRow, YearListView.RowAnimationDirection.Closing);
- this.selectedRow = ListView.NoSelection;
- this.setNeedsUpdateCells(true);
-};
-
-YearListView.prototype.deselectWithoutAnimating = function() {
- if (this.selectedRow === ListView.NoSelection)
- return;
- var selectedCell = this._cells[this.selectedRow];
- if (selectedCell) {
- selectedCell.setSelected(false);
- selectedCell.setHeight(YearListCell.Height);
- }
- this.selectedRow = ListView.NoSelection;
- this.setNeedsUpdateCells(true);
-};
-
-/**
- * @param {!number} row
- * @override
- */
-YearListView.prototype.select = function(row) {
- if (this.selectedRow === row)
- return;
- this.deselect();
- if (row === ListView.NoSelection)
- return;
- this.selectedRow = row;
- if (this.selectedRow !== ListView.NoSelection) {
- var selectedCell = this._cells[this.selectedRow];
- this._animateRow(this.selectedRow, YearListView.RowAnimationDirection.Opening);
- if (selectedCell)
- selectedCell.setSelected(true);
- var month = this.highlightedMonth ? this.highlightedMonth.month : 0;
- this.highlightMonth(new Month(this.selectedRow + 1, month));
- }
- this.setNeedsUpdateCells(true);
-};
-
-/**
- * @param {!number} row
- */
-YearListView.prototype.selectWithoutAnimating = function(row) {
- if (this.selectedRow === row)
- return;
- this.deselectWithoutAnimating();
- if (row === ListView.NoSelection)
- return;
- this.selectedRow = row;
- if (this.selectedRow !== ListView.NoSelection) {
- var selectedCell = this._cells[this.selectedRow];
- if (selectedCell) {
- selectedCell.setSelected(true);
- selectedCell.setHeight(YearListCell.SelectedHeight);
- }
- var month = this.highlightedMonth ? this.highlightedMonth.month : 0;
- this.highlightMonth(new Month(this.selectedRow + 1, month));
- }
- this.setNeedsUpdateCells(true);
-};
-
-/**
- * @param {!Month} month
- * @return {?HTMLButtonElement}
- */
-YearListView.prototype.buttonForMonth = function(month) {
- if (!month)
- return null;
- var row = month.year - 1;
- var cell = this.cellAtRow(row);
- if (!cell)
- return null;
- return cell.monthButtons[month.month];
-};
-
-YearListView.prototype.dehighlightMonth = function() {
- if (!this.highlightedMonth)
- return;
- var monthButton = this.buttonForMonth(this.highlightedMonth);
- if (monthButton) {
- monthButton.classList.remove(YearListCell.ClassNameHighlighted);
- }
- this.highlightedMonth = null;
-};
-
-/**
- * @param {!Month} month
- */
-YearListView.prototype.highlightMonth = function(month) {
- if (this.highlightedMonth && this.highlightedMonth.equals(month))
- return;
- this.dehighlightMonth();
- this.highlightedMonth = month;
- if (!this.highlightedMonth)
- return;
- var monthButton = this.buttonForMonth(this.highlightedMonth);
- if (monthButton) {
- monthButton.classList.add(YearListCell.ClassNameHighlighted);
- }
-};
-
-/**
- * @param {!Month} month
- */
-YearListView.prototype.show = function(month) {
- this._ignoreMouseOutUntillNextMouseOver = true;
-
- this.scrollToRow(month.year - 1, false);
- this.selectWithoutAnimating(month.year - 1);
- this.highlightMonth(month);
-};
-
-YearListView.prototype.hide = function() {
- this.dispatchEvent(YearListView.EventTypeYearListViewDidHide, this);
-};
-
-/**
- * @param {!Month} month
- */
-YearListView.prototype._moveHighlightTo = function(month) {
- this.highlightMonth(month);
- this.select(this.highlightedMonth.year - 1);
-
- this.dispatchEvent(YearListView.EventTypeYearListViewDidSelectMonth, this, month);
- this.scrollView.scrollTo(this.selectedRow * YearListCell.Height, true);
- return true;
-};
-
-/**
- * @param {?Event} event
- */
-YearListView.prototype.onKeyDown = function(event) {
- var key = event.keyIdentifier;
- var eventHandled = false;
- if (key == "U+0054") // 't' key.
- eventHandled = this._moveHighlightTo(Month.createFromToday());
- else if (this.highlightedMonth) {
- if (global.params.isLocaleRTL ? key == "Right" : key == "Left")
- eventHandled = this._moveHighlightTo(this.highlightedMonth.previous());
- else if (key == "Up")
- eventHandled = this._moveHighlightTo(this.highlightedMonth.previous(YearListCell.ButtonColumns));
- else if (global.params.isLocaleRTL ? key == "Left" : key == "Right")
- eventHandled = this._moveHighlightTo(this.highlightedMonth.next());
- else if (key == "Down")
- eventHandled = this._moveHighlightTo(this.highlightedMonth.next(YearListCell.ButtonColumns));
- else if (key == "PageUp")
- eventHandled = this._moveHighlightTo(this.highlightedMonth.previous(MonthsPerYear));
- else if (key == "PageDown")
- eventHandled = this._moveHighlightTo(this.highlightedMonth.next(MonthsPerYear));
- else if (key == "Enter") {
- this.dispatchEvent(YearListView.EventTypeYearListViewDidSelectMonth, this, this.highlightedMonth);
- this.hide();
- eventHandled = true;
- }
- } else if (key == "Up") {
- this.scrollView.scrollBy(-YearListCell.Height, true);
- eventHandled = true;
- } else if (key == "Down") {
- this.scrollView.scrollBy(YearListCell.Height, true);
- eventHandled = true;
- } else if (key == "PageUp") {
- this.scrollView.scrollBy(-this.scrollView.height(), true);
- eventHandled = true;
- } else if (key == "PageDown") {
- this.scrollView.scrollBy(this.scrollView.height(), true);
- eventHandled = true;
- }
-
- if (eventHandled) {
- event.stopPropagation();
- event.preventDefault();
- }
-};
-
-/**
- * @constructor
- * @extends View
- * @param {!Month} minimumMonth
- * @param {!Month} maximumMonth
- */
-function MonthPopupView(minimumMonth, maximumMonth) {
- View.call(this, createElement("div", MonthPopupView.ClassNameMonthPopupView));
-
- /**
- * @type {!YearListView}
- * @const
- */
- this.yearListView = new YearListView(minimumMonth, maximumMonth);
- this.yearListView.attachTo(this);
-
- /**
- * @type {!boolean}
- */
- this.isVisible = false;
-
- this.element.addEventListener("click", this.onClick, false);
-}
-
-MonthPopupView.prototype = Object.create(View.prototype);
-
-MonthPopupView.ClassNameMonthPopupView = "month-popup-view";
-
-MonthPopupView.prototype.show = function(initialMonth, calendarTableRect) {
- this.isVisible = true;
- document.body.appendChild(this.element);
- this.yearListView.setWidth(calendarTableRect.width - 2);
- this.yearListView.setHeight(YearListView.Height);
- if (global.params.isLocaleRTL)
- this.yearListView.element.style.right = calendarTableRect.x + "px";
- else
- this.yearListView.element.style.left = calendarTableRect.x + "px";
- this.yearListView.element.style.top = calendarTableRect.y + "px";
- this.yearListView.show(initialMonth);
- this.yearListView.element.focus();
-};
-
-MonthPopupView.prototype.hide = function() {
- if (!this.isVisible)
- return;
- this.isVisible = false;
- this.element.parentNode.removeChild(this.element);
- this.yearListView.hide();
-};
-
-/**
- * @param {?Event} event
- */
-MonthPopupView.prototype.onClick = function(event) {
- if (event.target !== this.element)
- return;
- this.hide();
-};
-
-/**
- * @constructor
- * @extends View
- * @param {!number} maxWidth Maximum width in pixels.
- */
-function MonthPopupButton(maxWidth) {
- View.call(this, createElement("button", MonthPopupButton.ClassNameMonthPopupButton));
-
- /**
- * @type {!Element}
- * @const
- */
- this.labelElement = createElement("span", MonthPopupButton.ClassNameMonthPopupButtonLabel, "-----");
- this.element.appendChild(this.labelElement);
-
- /**
- * @type {!Element}
- * @const
- */
- this.disclosureTriangleIcon = createElement("span", MonthPopupButton.ClassNameDisclosureTriangle);
- this.disclosureTriangleIcon.innerHTML = "<svg width='7' height='5'><polygon points='0,1 7,1 3.5,5' style='fill:#000000;' /></svg>";
- this.element.appendChild(this.disclosureTriangleIcon);
-
- /**
- * @type {!boolean}
- * @protected
- */
- this._useShortMonth = this._shouldUseShortMonth(maxWidth);
- this.element.style.maxWidth = maxWidth + "px";
-
- this.element.addEventListener("click", this.onClick, false);
-}
-
-MonthPopupButton.prototype = Object.create(View.prototype);
-
-MonthPopupButton.ClassNameMonthPopupButton = "month-popup-button";
-MonthPopupButton.ClassNameMonthPopupButtonLabel = "month-popup-button-label";
-MonthPopupButton.ClassNameDisclosureTriangle = "disclosure-triangle";
-MonthPopupButton.EventTypeButtonClick = "buttonClick";
-
-/**
- * @param {!number} maxWidth Maximum available width in pixels.
- * @return {!boolean}
- */
-MonthPopupButton.prototype._shouldUseShortMonth = function(maxWidth) {
- document.body.appendChild(this.element);
- var month = Month.Maximum;
- for (var i = 0; i < MonthsPerYear; ++i) {
- this.labelElement.textContent = month.toLocaleString();
- if (this.element.offsetWidth > maxWidth)
- return true;
- month = month.previous();
- }
- document.body.removeChild(this.element);
- return false;
-};
-
-/**
- * @param {!Month} month
- */
-MonthPopupButton.prototype.setCurrentMonth = function(month) {
- this.labelElement.textContent = this._useShortMonth ? month.toShortLocaleString() : month.toLocaleString();
-};
-
-/**
- * @param {?Event} event
- */
-MonthPopupButton.prototype.onClick = function(event) {
- this.dispatchEvent(MonthPopupButton.EventTypeButtonClick, this);
-};
-
-/**
- * @constructor
- * @extends View
- */
-function CalendarNavigationButton() {
- View.call(this, createElement("button", CalendarNavigationButton.ClassNameCalendarNavigationButton));
- /**
- * @type {number} Threshold for starting repeating clicks in milliseconds.
- */
- this.repeatingClicksStartingThreshold = CalendarNavigationButton.DefaultRepeatingClicksStartingThreshold;
- /**
- * @type {number} Interval between reapeating clicks in milliseconds.
- */
- this.reapeatingClicksInterval = CalendarNavigationButton.DefaultRepeatingClicksInterval;
- /**
- * @type {?number} The ID for the timeout that triggers the repeating clicks.
- */
- this._timer = null;
- this.element.addEventListener("click", this.onClick, false);
- this.element.addEventListener("mousedown", this.onMouseDown, false);
- this.element.addEventListener("touchstart", this.onTouchStart, false);
-};
-
-CalendarNavigationButton.prototype = Object.create(View.prototype);
-
-CalendarNavigationButton.DefaultRepeatingClicksStartingThreshold = 600;
-CalendarNavigationButton.DefaultRepeatingClicksInterval = 300;
-CalendarNavigationButton.LeftMargin = 4;
-CalendarNavigationButton.Width = 24;
-CalendarNavigationButton.ClassNameCalendarNavigationButton = "calendar-navigation-button";
-CalendarNavigationButton.EventTypeButtonClick = "buttonClick";
-CalendarNavigationButton.EventTypeRepeatingButtonClick = "repeatingButtonClick";
-
-/**
- * @param {!boolean} disabled
- */
-CalendarNavigationButton.prototype.setDisabled = function(disabled) {
- this.element.disabled = disabled;
-};
-
-/**
- * @param {?Event} event
- */
-CalendarNavigationButton.prototype.onClick = function(event) {
- this.dispatchEvent(CalendarNavigationButton.EventTypeButtonClick, this);
-};
-
-/**
- * @param {?Event} event
- */
-CalendarNavigationButton.prototype.onTouchStart = function(event) {
- if (this._timer !== null)
- return;
- this._timer = setTimeout(this.onRepeatingClick, this.repeatingClicksStartingThreshold);
- window.addEventListener("touchend", this.onWindowTouchEnd, false);
-};
-
-/**
- * @param {?Event} event
- */
-CalendarNavigationButton.prototype.onWindowTouchEnd = function(event) {
- if (this._timer === null)
- return;
- clearTimeout(this._timer);
- this._timer = null;
- window.removeEventListener("touchend", this.onWindowMouseUp, false);
-};
-
-/**
- * @param {?Event} event
- */
-CalendarNavigationButton.prototype.onMouseDown = function(event) {
- if (this._timer !== null)
- return;
- this._timer = setTimeout(this.onRepeatingClick, this.repeatingClicksStartingThreshold);
- window.addEventListener("mouseup", this.onWindowMouseUp, false);
-};
-
-/**
- * @param {?Event} event
- */
-CalendarNavigationButton.prototype.onWindowMouseUp = function(event) {
- if (this._timer === null)
- return;
- clearTimeout(this._timer);
- this._timer = null;
- window.removeEventListener("mouseup", this.onWindowMouseUp, false);
-};
-
-/**
- * @param {?Event} event
- */
-CalendarNavigationButton.prototype.onRepeatingClick = function(event) {
- this.dispatchEvent(CalendarNavigationButton.EventTypeRepeatingButtonClick, this);
- this._timer = setTimeout(this.onRepeatingClick, this.reapeatingClicksInterval);
-};
-
-/**
- * @constructor
- * @extends View
- * @param {!CalendarPicker} calendarPicker
- */
-function CalendarHeaderView(calendarPicker) {
- View.call(this, createElement("div", CalendarHeaderView.ClassNameCalendarHeaderView));
- this.calendarPicker = calendarPicker;
- this.calendarPicker.on(CalendarPicker.EventTypeCurrentMonthChanged, this.onCurrentMonthChanged);
-
- var titleElement = createElement("div", CalendarHeaderView.ClassNameCalendarTitle);
- this.element.appendChild(titleElement);
-
- /**
- * @type {!MonthPopupButton}
- */
- this.monthPopupButton = new MonthPopupButton(this.calendarPicker.calendarTableView.width() - CalendarTableView.BorderWidth * 2 - CalendarNavigationButton.Width * 3 - CalendarNavigationButton.LeftMargin * 2);
- this.monthPopupButton.attachTo(titleElement);
-
- /**
- * @type {!CalendarNavigationButton}
- * @const
- */
- this._previousMonthButton = new CalendarNavigationButton();
- this._previousMonthButton.attachTo(this);
- this._previousMonthButton.on(CalendarNavigationButton.EventTypeButtonClick, this.onNavigationButtonClick);
- this._previousMonthButton.on(CalendarNavigationButton.EventTypeRepeatingButtonClick, this.onNavigationButtonClick);
-
- /**
- * @type {!CalendarNavigationButton}
- * @const
- */
- this._todayButton = new CalendarNavigationButton();
- this._todayButton.attachTo(this);
- this._todayButton.on(CalendarNavigationButton.EventTypeButtonClick, this.onNavigationButtonClick);
- this._todayButton.element.classList.add(CalendarHeaderView.ClassNameTodayButton);
- var monthContainingToday = Month.createFromToday();
- this._todayButton.setDisabled(monthContainingToday < this.calendarPicker.minimumMonth || monthContainingToday > this.calendarPicker.maximumMonth);
-
- /**
- * @type {!CalendarNavigationButton}
- * @const
- */
- this._nextMonthButton = new CalendarNavigationButton();
- this._nextMonthButton.attachTo(this);
- this._nextMonthButton.on(CalendarNavigationButton.EventTypeButtonClick, this.onNavigationButtonClick);
- this._nextMonthButton.on(CalendarNavigationButton.EventTypeRepeatingButtonClick, this.onNavigationButtonClick);
-
- if (global.params.isLocaleRTL) {
- this._nextMonthButton.element.innerHTML = CalendarHeaderView._BackwardTriangle;
- this._previousMonthButton.element.innerHTML = CalendarHeaderView._ForwardTriangle;
- } else {
- this._nextMonthButton.element.innerHTML = CalendarHeaderView._ForwardTriangle;
- this._previousMonthButton.element.innerHTML = CalendarHeaderView._BackwardTriangle;
- }
-}
-
-CalendarHeaderView.prototype = Object.create(View.prototype);
-
-CalendarHeaderView.Height = 24;
-CalendarHeaderView.BottomMargin = 10;
-CalendarHeaderView._ForwardTriangle = "<svg width='4' height='7'><polygon points='0,7 0,0, 4,3.5' style='fill:#6e6e6e;' /></svg>";
-CalendarHeaderView._BackwardTriangle = "<svg width='4' height='7'><polygon points='0,3.5 4,7 4,0' style='fill:#6e6e6e;' /></svg>";
-CalendarHeaderView.ClassNameCalendarHeaderView = "calendar-header-view";
-CalendarHeaderView.ClassNameCalendarTitle = "calendar-title";
-CalendarHeaderView.ClassNameTodayButton = "today-button";
-
-CalendarHeaderView.prototype.onCurrentMonthChanged = function() {
- this.monthPopupButton.setCurrentMonth(this.calendarPicker.currentMonth());
- this._previousMonthButton.setDisabled(this.disabled || this.calendarPicker.currentMonth() <= this.calendarPicker.minimumMonth);
- this._nextMonthButton.setDisabled(this.disabled || this.calendarPicker.currentMonth() >= this.calendarPicker.maximumMonth);
-};
-
-CalendarHeaderView.prototype.onNavigationButtonClick = function(sender) {
- if (sender === this._previousMonthButton)
- this.calendarPicker.setCurrentMonth(this.calendarPicker.currentMonth().previous(), CalendarPicker.NavigationBehavior.WithAnimation);
- else if (sender === this._nextMonthButton)
- this.calendarPicker.setCurrentMonth(this.calendarPicker.currentMonth().next(), CalendarPicker.NavigationBehavior.WithAnimation);
- else
- this.calendarPicker.selectRangeContainingDay(Day.createFromToday());
-};
-
-/**
- * @param {!boolean} disabled
- */
-CalendarHeaderView.prototype.setDisabled = function(disabled) {
- this.disabled = disabled;
- this.monthPopupButton.element.disabled = this.disabled;
- this._previousMonthButton.setDisabled(this.disabled || this.calendarPicker.currentMonth() <= this.calendarPicker.minimumMonth);
- this._nextMonthButton.setDisabled(this.disabled || this.calendarPicker.currentMonth() >= this.calendarPicker.maximumMonth);
- var monthContainingToday = Month.createFromToday();
- this._todayButton.setDisabled(this.disabled || monthContainingToday < this.calendarPicker.minimumMonth || monthContainingToday > this.calendarPicker.maximumMonth);
-};
-
-/**
- * @constructor
- * @extends ListCell
- */
-function DayCell() {
- ListCell.call(this);
- this.element.classList.add(DayCell.ClassNameDayCell);
- this.element.style.width = DayCell.Width + "px";
- this.element.style.height = DayCell.Height + "px";
- this.element.style.lineHeight = (DayCell.Height - DayCell.PaddingSize * 2) + "px";
- /**
- * @type {?Day}
- */
- this.day = null;
-};
-
-DayCell.prototype = Object.create(ListCell.prototype);
-
-DayCell.Width = 34;
-DayCell.Height = hasInaccuratePointingDevice() ? 34 : 20;
-DayCell.PaddingSize = 1;
-DayCell.ClassNameDayCell = "day-cell";
-DayCell.ClassNameHighlighted = "highlighted";
-DayCell.ClassNameDisabled = "disabled";
-DayCell.ClassNameCurrentMonth = "current-month";
-DayCell.ClassNameToday = "today";
-
-DayCell._recycleBin = [];
-
-DayCell.recycleOrCreate = function() {
- return DayCell._recycleBin.pop() || new DayCell();
-};
-
-/**
- * @return {!Array}
- * @override
- */
-DayCell.prototype._recycleBin = function() {
- return DayCell._recycleBin;
-};
-
-/**
- * @override
- */
-DayCell.prototype.throwAway = function() {
- ListCell.prototype.throwAway.call(this);
- this.day = null;
-};
-
-/**
- * @param {!boolean} highlighted
- */
-DayCell.prototype.setHighlighted = function(highlighted) {
- if (highlighted)
- this.element.classList.add(DayCell.ClassNameHighlighted);
- else
- this.element.classList.remove(DayCell.ClassNameHighlighted);
-};
-
-/**
- * @param {!boolean} disabled
- */
-DayCell.prototype.setDisabled = function(disabled) {
- if (disabled)
- this.element.classList.add(DayCell.ClassNameDisabled);
- else
- this.element.classList.remove(DayCell.ClassNameDisabled);
-};
-
-/**
- * @param {!boolean} selected
- */
-DayCell.prototype.setIsInCurrentMonth = function(selected) {
- if (selected)
- this.element.classList.add(DayCell.ClassNameCurrentMonth);
- else
- this.element.classList.remove(DayCell.ClassNameCurrentMonth);
-};
-
-/**
- * @param {!boolean} selected
- */
-DayCell.prototype.setIsToday = function(selected) {
- if (selected)
- this.element.classList.add(DayCell.ClassNameToday);
- else
- this.element.classList.remove(DayCell.ClassNameToday);
-};
-
-/**
- * @param {!Day} day
- */
-DayCell.prototype.reset = function(day) {
- this.day = day;
- this.element.textContent = localizeNumber(this.day.date.toString());
- this.show();
-};
-
-/**
- * @constructor
- * @extends ListCell
- */
-function WeekNumberCell() {
- ListCell.call(this);
- this.element.classList.add(WeekNumberCell.ClassNameWeekNumberCell);
- this.element.style.width = (WeekNumberCell.Width - WeekNumberCell.SeparatorWidth) + "px";
- this.element.style.height = WeekNumberCell.Height + "px";
- this.element.style.lineHeight = (WeekNumberCell.Height - WeekNumberCell.PaddingSize * 2) + "px";
- /**
- * @type {?Week}
- */
- this.week = null;
-};
-
-WeekNumberCell.prototype = Object.create(ListCell.prototype);
-
-WeekNumberCell.Width = 48;
-WeekNumberCell.Height = DayCell.Height;
-WeekNumberCell.SeparatorWidth = 1;
-WeekNumberCell.PaddingSize = 1;
-WeekNumberCell.ClassNameWeekNumberCell = "week-number-cell";
-WeekNumberCell.ClassNameHighlighted = "highlighted";
-WeekNumberCell.ClassNameDisabled = "disabled";
-
-WeekNumberCell._recycleBin = [];
-
-/**
- * @return {!Array}
- * @override
- */
-WeekNumberCell.prototype._recycleBin = function() {
- return WeekNumberCell._recycleBin;
-};
-
-/**
- * @return {!WeekNumberCell}
- */
-WeekNumberCell.recycleOrCreate = function() {
- return WeekNumberCell._recycleBin.pop() || new WeekNumberCell();
-};
-
-/**
- * @param {!Week} week
- */
-WeekNumberCell.prototype.reset = function(week) {
- this.week = week;
- this.element.textContent = localizeNumber(this.week.week.toString());
- this.show();
-};
-
-/**
- * @override
- */
-WeekNumberCell.prototype.throwAway = function() {
- ListCell.prototype.throwAway.call(this);
- this.week = null;
-};
-
-WeekNumberCell.prototype.setHighlighted = function(highlighted) {
- if (highlighted)
- this.element.classList.add(WeekNumberCell.ClassNameHighlighted);
- else
- this.element.classList.remove(WeekNumberCell.ClassNameHighlighted);
-};
-
-WeekNumberCell.prototype.setDisabled = function(disabled) {
- if (disabled)
- this.element.classList.add(WeekNumberCell.ClassNameDisabled);
- else
- this.element.classList.remove(WeekNumberCell.ClassNameDisabled);
-};
-
-/**
- * @constructor
- * @extends View
- * @param {!boolean} hasWeekNumberColumn
- */
-function CalendarTableHeaderView(hasWeekNumberColumn) {
- View.call(this, createElement("div", "calendar-table-header-view"));
- if (hasWeekNumberColumn) {
- var weekNumberLabelElement = createElement("div", "week-number-label", global.params.weekLabel);
- weekNumberLabelElement.style.width = WeekNumberCell.Width + "px";
- this.element.appendChild(weekNumberLabelElement);
- }
- for (var i = 0; i < DaysPerWeek; ++i) {
- var weekDayNumber = (global.params.weekStartDay + i) % DaysPerWeek;
- var labelElement = createElement("div", "week-day-label", global.params.dayLabels[weekDayNumber]);
- labelElement.style.width = DayCell.Width + "px";
- this.element.appendChild(labelElement);
- if (getLanguage() === "ja") {
- if (weekDayNumber === 0)
- labelElement.style.color = "red";
- else if (weekDayNumber === 6)
- labelElement.style.color = "blue";
- }
- }
-}
-
-CalendarTableHeaderView.prototype = Object.create(View.prototype);
-
-CalendarTableHeaderView.Height = 25;
-
-/**
- * @constructor
- * @extends ListCell
- */
-function CalendarRowCell() {
- ListCell.call(this);
- this.element.classList.add(CalendarRowCell.ClassNameCalendarRowCell);
- this.element.style.height = CalendarRowCell.Height + "px";
-
- /**
- * @type {!Array}
- * @protected
- */
- this._dayCells = [];
- /**
- * @type {!number}
- */
- this.row = 0;
- /**
- * @type {?CalendarTableView}
- */
- this.calendarTableView = null;
-}
-
-CalendarRowCell.prototype = Object.create(ListCell.prototype);
-
-CalendarRowCell.Height = DayCell.Height;
-CalendarRowCell.ClassNameCalendarRowCell = "calendar-row-cell";
-
-CalendarRowCell._recycleBin = [];
-
-/**
- * @return {!Array}
- * @override
- */
-CalendarRowCell.prototype._recycleBin = function() {
- return CalendarRowCell._recycleBin;
-};
-
-/**
- * @param {!number} row
- * @param {!CalendarTableView} calendarTableView
- */
-CalendarRowCell.prototype.reset = function(row, calendarTableView) {
- this.row = row;
- this.calendarTableView = calendarTableView;
- if (this.calendarTableView.hasWeekNumberColumn) {
- var middleDay = this.calendarTableView.dayAtColumnAndRow(3, row);
- var week = Week.createFromDay(middleDay);
- this.weekNumberCell = this.calendarTableView.prepareNewWeekNumberCell(week);
- this.weekNumberCell.attachTo(this);
- }
- var day = calendarTableView.dayAtColumnAndRow(0, row);
- for (var i = 0; i < DaysPerWeek; ++i) {
- var dayCell = this.calendarTableView.prepareNewDayCell(day);
- dayCell.attachTo(this);
- this._dayCells.push(dayCell);
- day = day.next();
- }
- this.show();
-};
-
-/**
- * @override
- */
-CalendarRowCell.prototype.throwAway = function() {
- ListCell.prototype.throwAway.call(this);
- if (this.weekNumberCell)
- this.calendarTableView.throwAwayWeekNumberCell(this.weekNumberCell);
- this._dayCells.forEach(this.calendarTableView.throwAwayDayCell, this.calendarTableView);
- this._dayCells.length = 0;
-};
-
-/**
- * @constructor
- * @extends ListView
- * @param {!CalendarPicker} calendarPicker
- */
-function CalendarTableView(calendarPicker) {
- ListView.call(this);
- this.element.classList.add(CalendarTableView.ClassNameCalendarTableView);
- this.element.tabIndex = 0;
-
- /**
- * @type {!boolean}
- * @const
- */
- this.hasWeekNumberColumn = calendarPicker.type === "week";
- /**
- * @type {!CalendarPicker}
- * @const
- */
- this.calendarPicker = calendarPicker;
- /**
- * @type {!Object}
- * @const
- */
- this._dayCells = {};
- var headerView = new CalendarTableHeaderView(this.hasWeekNumberColumn);
- headerView.attachTo(this, this.scrollView);
-
- if (this.hasWeekNumberColumn) {
- this.setWidth(DayCell.Width * DaysPerWeek + WeekNumberCell.Width);
- /**
- * @type {?Array}
- * @const
- */
- this._weekNumberCells = [];
- } else {
- this.setWidth(DayCell.Width * DaysPerWeek);
- }
-
- /**
- * @type {!boolean}
- * @protected
- */
- this._ignoreMouseOutUntillNextMouseOver = false;
-
- this.element.addEventListener("click", this.onClick, false);
- this.element.addEventListener("mouseover", this.onMouseOver, false);
- this.element.addEventListener("mouseout", this.onMouseOut, false);
-
- // You shouldn't be able to use the mouse wheel to scroll.
- this.scrollView.element.removeEventListener("mousewheel", this.scrollView.onMouseWheel, false);
- // You shouldn't be able to do gesture scroll.
- this.scrollView.element.removeEventListener("touchstart", this.scrollView.onTouchStart, false);
-}
-
-CalendarTableView.prototype = Object.create(ListView.prototype);
-
-CalendarTableView.BorderWidth = 1;
-CalendarTableView.ClassNameCalendarTableView = "calendar-table-view";
-
-/**
- * @param {!number} scrollOffset
- * @return {!number}
- */
-CalendarTableView.prototype.rowAtScrollOffset = function(scrollOffset) {
- return Math.floor(scrollOffset / CalendarRowCell.Height);
-};
-
-/**
- * @param {!number} row
- * @return {!number}
- */
-CalendarTableView.prototype.scrollOffsetForRow = function(row) {
- return row * CalendarRowCell.Height;
-};
-
-/**
- * @param {?Event} event
- */
-CalendarTableView.prototype.onClick = function(event) {
- if (this.hasWeekNumberColumn) {
- var weekNumberCellElement = enclosingNodeOrSelfWithClass(event.target, WeekNumberCell.ClassNameWeekNumberCell);
- if (weekNumberCellElement) {
- var weekNumberCell = weekNumberCellElement.$view;
- this.calendarPicker.selectRangeContainingDay(weekNumberCell.week.firstDay());
- return;
- }
- }
- var dayCellElement = enclosingNodeOrSelfWithClass(event.target, DayCell.ClassNameDayCell);
- if (!dayCellElement)
- return;
- var dayCell = dayCellElement.$view;
- this.calendarPicker.selectRangeContainingDay(dayCell.day);
-};
-
-/**
- * @param {?Event} event
- */
-CalendarTableView.prototype.onMouseOver = function(event) {
- if (this.hasWeekNumberColumn) {
- var weekNumberCellElement = enclosingNodeOrSelfWithClass(event.target, WeekNumberCell.ClassNameWeekNumberCell);
- if (weekNumberCellElement) {
- var weekNumberCell = weekNumberCellElement.$view;
- this.calendarPicker.highlightRangeContainingDay(weekNumberCell.week.firstDay());
- this._ignoreMouseOutUntillNextMouseOver = false;
- return;
- }
- }
- var dayCellElement = enclosingNodeOrSelfWithClass(event.target, DayCell.ClassNameDayCell);
- if (!dayCellElement)
- return;
- var dayCell = dayCellElement.$view;
- this.calendarPicker.highlightRangeContainingDay(dayCell.day);
- this._ignoreMouseOutUntillNextMouseOver = false;
-};
-
-/**
- * @param {?Event} event
- */
-CalendarTableView.prototype.onMouseOut = function(event) {
- if (this._ignoreMouseOutUntillNextMouseOver)
- return;
- var dayCellElement = enclosingNodeOrSelfWithClass(event.target, DayCell.ClassNameDayCell);
- if (!dayCellElement) {
- this.calendarPicker.highlightRangeContainingDay(null);
- }
-};
-
-/**
- * @param {!number} row
- * @return {!CalendarRowCell}
- */
-CalendarTableView.prototype.prepareNewCell = function(row) {
- var cell = CalendarRowCell._recycleBin.pop() || new CalendarRowCell();
- cell.reset(row, this);
- return cell;
-};
-
-/**
- * @return {!number} Height in pixels.
- */
-CalendarTableView.prototype.height = function() {
- return this.scrollView.height() + CalendarTableHeaderView.Height + CalendarTableView.BorderWidth * 2;
-};
-
-/**
- * @param {!number} height Height in pixels.
- */
-CalendarTableView.prototype.setHeight = function(height) {
- this.scrollView.setHeight(height - CalendarTableHeaderView.Height - CalendarTableView.BorderWidth * 2);
-};
-
-/**
- * @param {!Month} month
- * @param {!boolean} animate
- */
-CalendarTableView.prototype.scrollToMonth = function(month, animate) {
- var rowForFirstDayInMonth = this.columnAndRowForDay(month.firstDay()).row;
- this.scrollView.scrollTo(this.scrollOffsetForRow(rowForFirstDayInMonth), animate);
-};
-
-/**
- * @param {!number} column
- * @param {!number} row
- * @return {!Day}
- */
-CalendarTableView.prototype.dayAtColumnAndRow = function(column, row) {
- var daysSinceMinimum = row * DaysPerWeek + column + global.params.weekStartDay - CalendarTableView._MinimumDayWeekDay;
- return Day.createFromValue(daysSinceMinimum * MillisecondsPerDay + CalendarTableView._MinimumDayValue);
-};
-
-CalendarTableView._MinimumDayValue = Day.Minimum.valueOf();
-CalendarTableView._MinimumDayWeekDay = Day.Minimum.weekDay();
-
-/**
- * @param {!Day} day
- * @return {!Object} Object with properties column and row.
- */
-CalendarTableView.prototype.columnAndRowForDay = function(day) {
- var daysSinceMinimum = (day.valueOf() - CalendarTableView._MinimumDayValue) / MillisecondsPerDay;
- var offset = daysSinceMinimum + CalendarTableView._MinimumDayWeekDay - global.params.weekStartDay;
- var row = Math.floor(offset / DaysPerWeek);
- var column = offset - row * DaysPerWeek;
- return {
- column: column,
- row: row
- };
-};
-
-CalendarTableView.prototype.updateCells = function() {
- ListView.prototype.updateCells.call(this);
-
- var selection = this.calendarPicker.selection();
- var firstDayInSelection;
- var lastDayInSelection;
- if (selection) {
- firstDayInSelection = selection.firstDay().valueOf();
- lastDayInSelection = selection.lastDay().valueOf();
- } else {
- firstDayInSelection = Infinity;
- lastDayInSelection = Infinity;
- }
- var highlight = this.calendarPicker.highlight();
- var firstDayInHighlight;
- var lastDayInHighlight;
- if (highlight) {
- firstDayInHighlight = highlight.firstDay().valueOf();
- lastDayInHighlight = highlight.lastDay().valueOf();
- } else {
- firstDayInHighlight = Infinity;
- lastDayInHighlight = Infinity;
- }
- var currentMonth = this.calendarPicker.currentMonth();
- var firstDayInCurrentMonth = currentMonth.firstDay().valueOf();
- var lastDayInCurrentMonth = currentMonth.lastDay().valueOf();
- for (var dayString in this._dayCells) {
- var dayCell = this._dayCells[dayString];
- var day = dayCell.day;
- dayCell.setIsToday(Day.createFromToday().equals(day));
- dayCell.setSelected(day >= firstDayInSelection && day <= lastDayInSelection);
- dayCell.setHighlighted(day >= firstDayInHighlight && day <= lastDayInHighlight);
- dayCell.setIsInCurrentMonth(day >= firstDayInCurrentMonth && day <= lastDayInCurrentMonth);
- dayCell.setDisabled(!this.calendarPicker.isValidDay(day));
- }
- if (this.hasWeekNumberColumn) {
- for (var weekString in this._weekNumberCells) {
- var weekNumberCell = this._weekNumberCells[weekString];
- var week = weekNumberCell.week;
- weekNumberCell.setSelected(selection && selection.equals(week));
- weekNumberCell.setHighlighted(highlight && highlight.equals(week));
- weekNumberCell.setDisabled(!this.calendarPicker.isValid(week));
- }
- }
-};
-
-/**
- * @param {!Day} day
- * @return {!DayCell}
- */
-CalendarTableView.prototype.prepareNewDayCell = function(day) {
- var dayCell = DayCell.recycleOrCreate();
- dayCell.reset(day);
- this._dayCells[dayCell.day.toString()] = dayCell;
- return dayCell;
-};
-
-/**
- * @param {!Week} week
- * @return {!WeekNumberCell}
- */
-CalendarTableView.prototype.prepareNewWeekNumberCell = function(week) {
- var weekNumberCell = WeekNumberCell.recycleOrCreate();
- weekNumberCell.reset(week);
- this._weekNumberCells[weekNumberCell.week.toString()] = weekNumberCell;
- return weekNumberCell;
-};
-
-/**
- * @param {!DayCell} dayCell
- */
-CalendarTableView.prototype.throwAwayDayCell = function(dayCell) {
- delete this._dayCells[dayCell.day.toString()];
- dayCell.throwAway();
-};
-
-/**
- * @param {!WeekNumberCell} weekNumberCell
- */
-CalendarTableView.prototype.throwAwayWeekNumberCell = function(weekNumberCell) {
- delete this._weekNumberCells[weekNumberCell.week.toString()];
- weekNumberCell.throwAway();
-};
-
-/**
- * @constructor
- * @extends View
- * @param {!Object} config
- */
-function CalendarPicker(type, config) {
- View.call(this, createElement("div", CalendarPicker.ClassNameCalendarPicker));
- this.element.classList.add(CalendarPicker.ClassNamePreparing);
-
- /**
- * @type {!string}
- * @const
- */
- this.type = type;
- if (this.type === "week")
- this._dateTypeConstructor = Week;
- else if (this.type === "month")
- this._dateTypeConstructor = Month;
- else
- this._dateTypeConstructor = Day;
- /**
- * @type {!Object}
- * @const
- */
- this.config = {};
- this._setConfig(config);
- /**
- * @type {!Month}
- * @const
- */
- this.minimumMonth = Month.createFromDay(this.config.minimum.firstDay());
- /**
- * @type {!Month}
- * @const
- */
- this.maximumMonth = Month.createFromDay(this.config.maximum.lastDay());
- if (global.params.isLocaleRTL)
- this.element.classList.add("rtl");
- /**
- * @type {!CalendarTableView}
- * @const
- */
- this.calendarTableView = new CalendarTableView(this);
- this.calendarTableView.hasNumberColumn = this.type === "week";
- /**
- * @type {!CalendarHeaderView}
- * @const
- */
- this.calendarHeaderView = new CalendarHeaderView(this);
- this.calendarHeaderView.monthPopupButton.on(MonthPopupButton.EventTypeButtonClick, this.onMonthPopupButtonClick);
- /**
- * @type {!MonthPopupView}
- * @const
- */
- this.monthPopupView = new MonthPopupView(this.minimumMonth, this.maximumMonth);
- this.monthPopupView.yearListView.on(YearListView.EventTypeYearListViewDidSelectMonth, this.onYearListViewDidSelectMonth);
- this.monthPopupView.yearListView.on(YearListView.EventTypeYearListViewDidHide, this.onYearListViewDidHide);
- this.calendarHeaderView.attachTo(this);
- this.calendarTableView.attachTo(this);
- /**
- * @type {!Month}
- * @protected
- */
- this._currentMonth = new Month(NaN, NaN);
- /**
- * @type {?DateType}
- * @protected
- */
- this._selection = null;
- /**
- * @type {?DateType}
- * @protected
- */
- this._highlight = null;
- this.calendarTableView.element.addEventListener("keydown", this.onCalendarTableKeyDown, false);
- document.body.addEventListener("keydown", this.onBodyKeyDown, false);
-
- window.addEventListener("resize", this.onWindowResize, false);
-
- /**
- * @type {!number}
- * @protected
- */
- this._height = -1;
-
- var initialSelection = parseDateString(config.currentValue);
- if (initialSelection) {
- this.setCurrentMonth(Month.createFromDay(initialSelection.middleDay()), CalendarPicker.NavigationBehavior.None);
- this.setSelection(initialSelection);
- } else
- this.setCurrentMonth(Month.createFromToday(), CalendarPicker.NavigationBehavior.None);
-}
-
-CalendarPicker.prototype = Object.create(View.prototype);
-
-CalendarPicker.Padding = 10;
-CalendarPicker.BorderWidth = 1;
-CalendarPicker.ClassNameCalendarPicker = "calendar-picker";
-CalendarPicker.ClassNamePreparing = "preparing";
-CalendarPicker.EventTypeCurrentMonthChanged = "currentMonthChanged";
-
-/**
- * @param {!Event} event
- */
-CalendarPicker.prototype.onWindowResize = function(event) {
- this.element.classList.remove(CalendarPicker.ClassNamePreparing);
- window.removeEventListener("resize", this.onWindowResize, false);
-};
-
-/**
- * @param {!YearListView} sender
- */
-CalendarPicker.prototype.onYearListViewDidHide = function(sender) {
- this.monthPopupView.hide();
- this.calendarHeaderView.setDisabled(false);
- this.adjustHeight();
-};
-
-/**
- * @param {!YearListView} sender
- * @param {!Month} month
- */
-CalendarPicker.prototype.onYearListViewDidSelectMonth = function(sender, month) {
- this.setCurrentMonth(month, CalendarPicker.NavigationBehavior.None);
-};
-
-/**
- * @param {!View|Node} parent
- * @param {?View|Node=} before
- * @override
- */
-CalendarPicker.prototype.attachTo = function(parent, before) {
- View.prototype.attachTo.call(this, parent, before);
- this.calendarTableView.element.focus();
-};
-
-CalendarPicker.prototype.cleanup = function() {
- window.removeEventListener("resize", this.onWindowResize, false);
- this.calendarTableView.element.removeEventListener("keydown", this.onBodyKeyDown, false);
- // Month popup view might be attached to document.body.
- this.monthPopupView.hide();
-};
-
-/**
- * @param {?MonthPopupButton} sender
- */
-CalendarPicker.prototype.onMonthPopupButtonClick = function(sender) {
- var clientRect = this.calendarTableView.element.getBoundingClientRect();
- var calendarTableRect = new Rectangle(clientRect.left + document.body.scrollLeft, clientRect.top + document.body.scrollTop, clientRect.width, clientRect.height);
- this.monthPopupView.show(this.currentMonth(), calendarTableRect);
- this.calendarHeaderView.setDisabled(true);
- this.adjustHeight();
-};
-
-CalendarPicker.prototype._setConfig = function(config) {
- this.config.minimum = (typeof config.min !== "undefined" && config.min) ? parseDateString(config.min) : this._dateTypeConstructor.Minimum;
- this.config.maximum = (typeof config.max !== "undefined" && config.max) ? parseDateString(config.max) : this._dateTypeConstructor.Maximum;
- this.config.minimumValue = this.config.minimum.valueOf();
- this.config.maximumValue = this.config.maximum.valueOf();
- this.config.step = (typeof config.step !== undefined) ? Number(config.step) : this._dateTypeConstructor.DefaultStep;
- this.config.stepBase = (typeof config.stepBase !== "undefined") ? Number(config.stepBase) : this._dateTypeConstructor.DefaultStepBase;
-};
-
-/**
- * @return {!Month}
- */
-CalendarPicker.prototype.currentMonth = function() {
- return this._currentMonth;
-};
-
-/**
- * @enum {number}
- */
-CalendarPicker.NavigationBehavior = {
- None: 0,
- WithAnimation: 1
-};
-
-/**
- * @param {!Month} month
- * @param {!CalendarPicker.NavigationBehavior} animate
- */
-CalendarPicker.prototype.setCurrentMonth = function(month, behavior) {
- if (month > this.maximumMonth)
- month = this.maximumMonth;
- else if (month < this.minimumMonth)
- month = this.minimumMonth;
- if (this._currentMonth.equals(month))
- return;
- this._currentMonth = month;
- this.calendarTableView.scrollToMonth(this._currentMonth, behavior === CalendarPicker.NavigationBehavior.WithAnimation);
- this.adjustHeight();
- this.calendarTableView.setNeedsUpdateCells(true);
- this.dispatchEvent(CalendarPicker.EventTypeCurrentMonthChanged, {
- target: this
- });
-};
-
-CalendarPicker.prototype.adjustHeight = function() {
- var rowForFirstDayInMonth = this.calendarTableView.columnAndRowForDay(this._currentMonth.firstDay()).row;
- var rowForLastDayInMonth = this.calendarTableView.columnAndRowForDay(this._currentMonth.lastDay()).row;
- var numberOfRows = rowForLastDayInMonth - rowForFirstDayInMonth + 1;
- var calendarTableViewHeight = CalendarTableHeaderView.Height + numberOfRows * DayCell.Height + CalendarTableView.BorderWidth * 2;
- var height = (this.monthPopupView.isVisible ? YearListView.Height : calendarTableViewHeight) + CalendarHeaderView.Height + CalendarHeaderView.BottomMargin + CalendarPicker.Padding * 2 + CalendarPicker.BorderWidth * 2;
- this.setHeight(height);
-};
-
-CalendarPicker.prototype.selection = function() {
- return this._selection;
-};
-
-CalendarPicker.prototype.highlight = function() {
- return this._highlight;
-};
-
-/**
- * @return {!Day}
- */
-CalendarPicker.prototype.firstVisibleDay = function() {
- var firstVisibleRow = this.calendarTableView.columnAndRowForDay(this.currentMonth().firstDay()).row;
- var firstVisibleDay = this.calendarTableView.dayAtColumnAndRow(0, firstVisibleRow);
- if (!firstVisibleDay)
- firstVisibleDay = Day.Minimum;
- return firstVisibleDay;
-};
-
-/**
- * @return {!Day}
- */
-CalendarPicker.prototype.lastVisibleDay = function() {
- var lastVisibleRow = this.calendarTableView.columnAndRowForDay(this.currentMonth().lastDay()).row;
- var lastVisibleDay = this.calendarTableView.dayAtColumnAndRow(DaysPerWeek - 1, lastVisibleRow);
- if (!lastVisibleDay)
- lastVisibleDay = Day.Maximum;
- return lastVisibleDay;
-};
-
-/**
- * @param {?Day} day
- */
-CalendarPicker.prototype.selectRangeContainingDay = function(day) {
- var selection = day ? this._dateTypeConstructor.createFromDay(day) : null;
- this.setSelection(selection);
-};
-
-/**
- * @param {?Day} day
- */
-CalendarPicker.prototype.highlightRangeContainingDay = function(day) {
- var highlight = day ? this._dateTypeConstructor.createFromDay(day) : null;
- this._setHighlight(highlight);
-};
-
-/**
- * @param {?DateType} dayOrWeekOrMonth
- */
-CalendarPicker.prototype.setSelection = function(dayOrWeekOrMonth) {
- if (!this._selection && !dayOrWeekOrMonth)
- return;
- if (this._selection && this._selection.equals(dayOrWeekOrMonth))
- return;
- var firstDayInSelection = dayOrWeekOrMonth.firstDay();
- var lastDayInSelection = dayOrWeekOrMonth.lastDay();
- var candidateCurrentMonth = Month.createFromDay(firstDayInSelection);
- if (this.firstVisibleDay() > lastDayInSelection || this.lastVisibleDay() < firstDayInSelection) {
- // Change current month if the selection is not visible at all.
- this.setCurrentMonth(candidateCurrentMonth, CalendarPicker.NavigationBehavior.WithAnimation);
- } else if (this.firstVisibleDay() < firstDayInSelection || this.lastVisibleDay() > lastDayInSelection) {
- // If the selection is partly visible, only change the current month if
- // doing so will make the whole selection visible.
- var firstVisibleRow = this.calendarTableView.columnAndRowForDay(candidateCurrentMonth.firstDay()).row;
- var firstVisibleDay = this.calendarTableView.dayAtColumnAndRow(0, firstVisibleRow);
- var lastVisibleRow = this.calendarTableView.columnAndRowForDay(candidateCurrentMonth.lastDay()).row;
- var lastVisibleDay = this.calendarTableView.dayAtColumnAndRow(DaysPerWeek - 1, lastVisibleRow);
- if (firstDayInSelection >= firstVisibleDay && lastDayInSelection <= lastVisibleDay)
- this.setCurrentMonth(candidateCurrentMonth, CalendarPicker.NavigationBehavior.WithAnimation);
- }
- this._setHighlight(dayOrWeekOrMonth);
- if (!this.isValid(dayOrWeekOrMonth))
- return;
- this._selection = dayOrWeekOrMonth;
- this.calendarTableView.setNeedsUpdateCells(true);
- window.pagePopupController.setValue(this._selection.toString());
-};
-
-/**
- * @param {?DateType} dayOrWeekOrMonth
- */
-CalendarPicker.prototype._setHighlight = function(dayOrWeekOrMonth) {
- if (!this._highlight && !dayOrWeekOrMonth)
- return;
- if (!dayOrWeekOrMonth && !this._highlight)
- return;
- if (this._highlight && this._highlight.equals(dayOrWeekOrMonth))
- return;
- this._highlight = dayOrWeekOrMonth;
- this.calendarTableView.setNeedsUpdateCells(true);
-};
-
-/**
- * @param {!number} value
- * @return {!boolean}
- */
-CalendarPicker.prototype._stepMismatch = function(value) {
- var nextAllowedValue = Math.ceil((value - this.config.stepBase) / this.config.step) * this.config.step + this.config.stepBase;
- return nextAllowedValue >= value + this._dateTypeConstructor.DefaultStep;
-};
-
-/**
- * @param {!number} value
- * @return {!boolean}
- */
-CalendarPicker.prototype._outOfRange = function(value) {
- return value < this.config.minimumValue || value > this.config.maximumValue;
-};
-
-/**
- * @param {!DateType} dayOrWeekOrMonth
- * @return {!boolean}
- */
-CalendarPicker.prototype.isValid = function(dayOrWeekOrMonth) {
- var value = dayOrWeekOrMonth.valueOf();
- return dayOrWeekOrMonth instanceof this._dateTypeConstructor && !this._outOfRange(value) && !this._stepMismatch(value);
-};
-
-/**
- * @param {!Day} day
- * @return {!boolean}
- */
-CalendarPicker.prototype.isValidDay = function(day) {
- return this.isValid(this._dateTypeConstructor.createFromDay(day));
-};
-
-/**
- * @param {!DateType} dateRange
- * @return {!boolean} Returns true if the highlight was changed.
- */
-CalendarPicker.prototype._moveHighlight = function(dateRange) {
- if (!dateRange)
- return false;
- if (this._outOfRange(dateRange.valueOf()))
- return false;
- if (this.firstVisibleDay() > dateRange.middleDay() || this.lastVisibleDay() < dateRange.middleDay())
- this.setCurrentMonth(Month.createFromDay(dateRange.middleDay()), CalendarPicker.NavigationBehavior.WithAnimation);
- this._setHighlight(dateRange);
- return true;
-};
-
-/**
- * @param {?Event} event
- */
-CalendarPicker.prototype.onCalendarTableKeyDown = function(event) {
- var key = event.keyIdentifier;
- var eventHandled = false;
- if (key == "U+0054") { // 't' key.
- this.selectRangeContainingDay(Day.createFromToday());
- eventHandled = true;
- } else if (key == "PageUp") {
- var previousMonth = this.currentMonth().previous();
- if (previousMonth && previousMonth >= this.config.minimumValue) {
- this.setCurrentMonth(previousMonth, CalendarPicker.NavigationBehavior.WithAnimation);
- eventHandled = true;
- }
- } else if (key == "PageDown") {
- var nextMonth = this.currentMonth().next();
- if (nextMonth && nextMonth >= this.config.minimumValue) {
- this.setCurrentMonth(nextMonth, CalendarPicker.NavigationBehavior.WithAnimation);
- eventHandled = true;
- }
- } else if (this._highlight) {
- if (global.params.isLocaleRTL ? key == "Right" : key == "Left") {
- eventHandled = this._moveHighlight(this._highlight.previous());
- } else if (key == "Up") {
- eventHandled = this._moveHighlight(this._highlight.previous(this.type === "date" ? DaysPerWeek : 1));
- } else if (global.params.isLocaleRTL ? key == "Left" : key == "Right") {
- eventHandled = this._moveHighlight(this._highlight.next());
- } else if (key == "Down") {
- eventHandled = this._moveHighlight(this._highlight.next(this.type === "date" ? DaysPerWeek : 1));
- } else if (key == "Enter") {
- this.setSelection(this._highlight);
- }
- } else if (key == "Left" || key == "Up" || key == "Right" || key == "Down") {
- // Highlight range near the middle.
- this.highlightRangeContainingDay(this.currentMonth().middleDay());
- eventHandled = true;
- }
-
- if (eventHandled) {
- event.stopPropagation();
- event.preventDefault();
- }
-};
-
-/**
- * @return {!number} Width in pixels.
- */
-CalendarPicker.prototype.width = function() {
- return this.calendarTableView.width() + (CalendarTableView.BorderWidth + CalendarPicker.BorderWidth + CalendarPicker.Padding) * 2;
-};
-
-/**
- * @return {!number} Height in pixels.
- */
-CalendarPicker.prototype.height = function() {
- return this._height;
-};
-
-/**
- * @param {!number} height Height in pixels.
- */
-CalendarPicker.prototype.setHeight = function(height) {
- if (this._height === height)
- return;
- this._height = height;
- resizeWindow(this.width(), this._height);
- this.calendarTableView.setHeight(this._height - CalendarHeaderView.Height - CalendarHeaderView.BottomMargin - CalendarPicker.Padding * 2 - CalendarTableView.BorderWidth * 2);
-};
-
-/**
- * @param {?Event} event
- */
-CalendarPicker.prototype.onBodyKeyDown = function(event) {
- var key = event.keyIdentifier;
- var eventHandled = false;
- var offset = 0;
- switch (key) {
- case "U+001B": // Esc key.
- window.pagePopupController.closePopup();
- eventHandled = true;
- break;
- case "U+004D": // 'm' key.
- offset = offset || 1; // Fall-through.
- case "U+0059": // 'y' key.
- offset = offset || MonthsPerYear; // Fall-through.
- case "U+0044": // 'd' key.
- offset = offset || MonthsPerYear * 10;
- var oldFirstVisibleRow = this.calendarTableView.columnAndRowForDay(this.currentMonth().firstDay()).row;
- this.setCurrentMonth(event.shiftKey ? this.currentMonth().previous(offset) : this.currentMonth().next(offset), CalendarPicker.NavigationBehavior.WithAnimation);
- var newFirstVisibleRow = this.calendarTableView.columnAndRowForDay(this.currentMonth().firstDay()).row;
- if (this._highlight) {
- var highlightMiddleDay = this._highlight.middleDay();
- this.highlightRangeContainingDay(highlightMiddleDay.next((newFirstVisibleRow - oldFirstVisibleRow) * DaysPerWeek));
- }
- eventHandled =true;
- break;
- }
- if (eventHandled) {
- event.stopPropagation();
- event.preventDefault();
- }
-}
-
-if (window.dialogArguments) {
- initialize(dialogArguments);
-} else {
- window.addEventListener("message", handleMessage, false);
-}
diff --git a/chromium/third_party/WebKit/Source/core/Resources/pagepopups/chromium/calendarPickerChromium.css b/chromium/third_party/WebKit/Source/core/Resources/pagepopups/chromium/calendarPickerChromium.css
deleted file mode 100644
index 167590d1db9..00000000000
--- a/chromium/third_party/WebKit/Source/core/Resources/pagepopups/chromium/calendarPickerChromium.css
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-.year-month-button {
- width: 24px;
- height: 24px;
- min-width: 0;
- padding: 0;
-}
-
-.month-popup-button:focus,
-.year-list-view:focus,
-.calendar-table-view:focus {
- transition: border-color 200ms;
- /* We use border color because it follows the border radius (unlike outline).
- * This is particularly noticeable on mac. */
- border-color: rgb(77, 144, 254) !important;
- outline: none;
-}
-
-.preparing button:focus,
-.preparing .year-list-view:focus,
-.preparing .calendar-table-view:focus {
- transition: none;
-}
diff --git a/chromium/third_party/WebKit/Source/core/Resources/pagepopups/chromium/pickerCommonChromium.css b/chromium/third_party/WebKit/Source/core/Resources/pagepopups/chromium/pickerCommonChromium.css
deleted file mode 100644
index b207a0da95c..00000000000
--- a/chromium/third_party/WebKit/Source/core/Resources/pagepopups/chromium/pickerCommonChromium.css
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-input[type='button'],
-button {
- -webkit-appearance: none;
- -webkit-user-select: none;
- background-image: -webkit-linear-gradient(#ededed, #ededed 38%, #dedede);
- border: 1px solid rgba(0, 0, 0, 0.25);
- border-radius: 2px;
- box-shadow: 0 1px 0 rgba(0, 0, 0, 0.08),
- inset 0 1px 2px rgba(255, 255, 255, 0.75);
- color: #444;
- font: inherit;
- text-shadow: 0 1px 0 rgb(240, 240, 240);
- min-height: 2em;
- min-width: 4em;
- -webkit-padding-end: 10px;
- -webkit-padding-start: 10px;
- margin: 0;
-}
-
-:enabled:hover:-webkit-any(button, input[type='button']) {
- background-image: -webkit-linear-gradient(#f0f0f0, #f0f0f0 38%, #e0e0e0);
- border-color: rgba(0, 0, 0, 0.3);
- box-shadow: 0 1px 0 rgba(0, 0, 0, 0.12), inset 0 1px 2px rgba(255, 255, 255, 0.95);
- color: black;
-}
-
-:enabled:active:-webkit-any(button, input[type='button']) {
- background-image: -webkit-linear-gradient(#e7e7e7, #e7e7e7 38%, #d7d7d7);
- box-shadow: none;
- text-shadow: none;
-}
-
-:disabled:-webkit-any(button, input[type='button']) {
- background-image: -webkit-linear-gradient(#f1f1f1, #f1f1f1 38%, #e6e6e6);
- border-color: rgba(80, 80, 80, 0.2);
- box-shadow: 0 1px 0 rgba(80, 80, 80, 0.08), inset 0 1px 2px rgba(255, 255, 255, 0.75);
- color: #aaa;
-}
-
-:enabled:focus:-webkit-any(button, input[type='button']) {
- transition: border-color 200ms;
- /* We use border color because it follows the border radius (unlike outline).
- * This is particularly noticeable on mac. */
- border-color: rgb(77, 144, 254);
- outline: none;
-}
diff --git a/chromium/third_party/WebKit/Source/core/Resources/pagepopups/colorSuggestionPicker.css b/chromium/third_party/WebKit/Source/core/Resources/pagepopups/colorSuggestionPicker.css
deleted file mode 100644
index 39a162bda85..00000000000
--- a/chromium/third_party/WebKit/Source/core/Resources/pagepopups/colorSuggestionPicker.css
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-body {
- -webkit-user-select: none;
- background-color: white;
- font: -webkit-small-control;
- margin: 0;
- overflow: hidden;
-}
-
-#main {
- background-color: white;
- border: solid 1px #8899aa;
- box-shadow: inset 2px 2px 2px white,
- inset -2px -2px 1px rgba(0,0,0,0.1);
- padding: 6px;
- float: left;
-}
-
-.color-swatch {
- float: left;
- width: 20px;
- height: 20px;
- margin: 1px;
- padding: 0;
- border: 1px solid #e0e0e0;
- box-sizing: content-box;
-}
-
-.color-swatch:focus {
- border: 1px solid #000000;
- outline: none;
-}
-
-.color-swatch-container {
- width: 100%;
- max-height: 104px;
- overflow: auto;
- display: flex;
- flex-flow: row wrap;
- align-items: center;
-}
-
-.other-color {
- width: 100%;
- margin: 4px 0 0 0;
-}
diff --git a/chromium/third_party/WebKit/Source/core/Resources/pagepopups/colorSuggestionPicker.js b/chromium/third_party/WebKit/Source/core/Resources/pagepopups/colorSuggestionPicker.js
deleted file mode 100644
index 559b9e6dc82..00000000000
--- a/chromium/third_party/WebKit/Source/core/Resources/pagepopups/colorSuggestionPicker.js
+++ /dev/null
@@ -1,189 +0,0 @@
-"use strict";
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-var global = {
- argumentsReceived: false,
- params: null
-};
-
-/**
- * @param {Event} event
- */
-function handleMessage(event) {
- initialize(JSON.parse(event.data));
- global.argumentsReceived = true;
-}
-
-/**
- * @param {!Object} args
- */
-function initialize(args) {
- global.params = args;
- var main = $("main");
- main.innerHTML = "";
- var errorString = validateArguments(args);
- if (errorString) {
- main.textContent = "Internal error: " + errorString;
- resizeWindow(main.offsetWidth, main.offsetHeight);
- } else
- new ColorPicker(main, args);
-}
-
-// The DefaultColorPalette is used when the list of values are empty.
-var DefaultColorPalette = ["#000000", "#404040", "#808080", "#c0c0c0",
- "#ffffff", "#980000", "#ff0000", "#ff9900", "#ffff00", "#00ff00", "#00ffff",
- "#4a86e8", "#0000ff", "#9900ff", "#ff00ff"];
-
-function handleArgumentsTimeout() {
- if (global.argumentsReceived)
- return;
- var args = {
- values : DefaultColorPalette,
- otherColorLabel: "Other..."
- };
- initialize(args);
-}
-
-/**
- * @param {!Object} args
- * @return {?string} An error message, or null if the argument has no errors.
- */
-function validateArguments(args) {
- if (!args.values)
- return "No values.";
- if (!args.otherColorLabel)
- return "No otherColorLabel.";
- return null;
-}
-
-function ColorPicker(element, config) {
- Picker.call(this, element, config);
- this._config = config;
- if (this._config.values.length === 0)
- this._config.values = DefaultColorPalette;
- this._container = null;
- this._layout();
- document.body.addEventListener("keydown", this._handleKeyDown.bind(this));
- this._element.addEventListener("mousemove", this._handleMouseMove.bind(this));
- this._element.addEventListener("mousedown", this._handleMouseDown.bind(this));
-}
-ColorPicker.prototype = Object.create(Picker.prototype);
-
-var SwatchBorderBoxWidth = 24; // keep in sync with CSS
-var SwatchBorderBoxHeight = 24; // keep in sync with CSS
-var SwatchesPerRow = 5;
-var SwatchesMaxRow = 4;
-
-ColorPicker.prototype._layout = function() {
- var container = createElement("div", "color-swatch-container");
- container.addEventListener("click", this._handleSwatchClick.bind(this), false);
- for (var i = 0; i < this._config.values.length; ++i) {
- var swatch = createElement("button", "color-swatch");
- swatch.dataset.index = i;
- swatch.dataset.value = this._config.values[i];
- swatch.title = this._config.values[i];
- swatch.style.backgroundColor = this._config.values[i];
- container.appendChild(swatch);
- }
- var containerWidth = SwatchBorderBoxWidth * SwatchesPerRow;
- if (this._config.values.length > SwatchesPerRow * SwatchesMaxRow)
- containerWidth += getScrollbarWidth();
- container.style.width = containerWidth + "px";
- container.style.maxHeight = (SwatchBorderBoxHeight * SwatchesMaxRow) + "px";
- this._element.appendChild(container);
- var otherButton = createElement("button", "other-color", this._config.otherColorLabel);
- otherButton.addEventListener("click", this.chooseOtherColor.bind(this), false);
- this._element.appendChild(otherButton);
- this._container = container;
- this._otherButton = otherButton;
- var elementWidth = this._element.offsetWidth;
- var elementHeight = this._element.offsetHeight;
- resizeWindow(elementWidth, elementHeight);
-};
-
-ColorPicker.prototype.selectColorAtIndex = function(index) {
- index = Math.max(Math.min(this._container.childNodes.length - 1, index), 0);
- this._container.childNodes[index].focus();
-};
-
-ColorPicker.prototype._handleMouseMove = function(event) {
- if (event.target.classList.contains("color-swatch"))
- event.target.focus();
-};
-
-ColorPicker.prototype._handleMouseDown = function(event) {
- // Prevent blur.
- if (event.target.classList.contains("color-swatch"))
- event.preventDefault();
-};
-
-ColorPicker.prototype._handleKeyDown = function(event) {
- var key = event.keyIdentifier;
- if (key === "U+001B") // ESC
- this.handleCancel();
- else if (key == "Left" || key == "Up" || key == "Right" || key == "Down") {
- var selectedElement = document.activeElement;
- var index = 0;
- if (selectedElement.classList.contains("other-color")) {
- if (key != "Right" && key != "Up")
- return;
- index = this._container.childNodes.length - 1;
- } else if (selectedElement.classList.contains("color-swatch")) {
- index = parseInt(selectedElement.dataset.index, 10);
- switch (key) {
- case "Left":
- index--;
- break;
- case "Right":
- index++;
- break;
- case "Up":
- index -= SwatchesPerRow;
- break;
- case "Down":
- index += SwatchesPerRow;
- break;
- }
- if (index > this._container.childNodes.length - 1) {
- this._otherButton.focus();
- return;
- }
- }
- this.selectColorAtIndex(index);
- }
- event.preventDefault();
-};
-
-ColorPicker.prototype._handleSwatchClick = function(event) {
- if (event.target.classList.contains("color-swatch"))
- this.submitValue(event.target.dataset.value);
-};
-
-if (window.dialogArguments) {
- initialize(dialogArguments);
-} else {
- window.addEventListener("message", handleMessage, false);
- window.setTimeout(handleArgumentsTimeout, 1000);
-}
diff --git a/chromium/third_party/WebKit/Source/core/Resources/pagepopups/pickerCommon.css b/chromium/third_party/WebKit/Source/core/Resources/pagepopups/pickerCommon.css
deleted file mode 100644
index 696751a4193..00000000000
--- a/chromium/third_party/WebKit/Source/core/Resources/pagepopups/pickerCommon.css
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-body {
- -webkit-user-select: none;
- background-color: white;
- font: -webkit-small-control;
- margin: 0;
- overflow: hidden;
-}
-
-.rtl {
- direction: rtl;
-}
diff --git a/chromium/third_party/WebKit/Source/core/Resources/pagepopups/pickerCommon.js b/chromium/third_party/WebKit/Source/core/Resources/pagepopups/pickerCommon.js
deleted file mode 100644
index 7034329f830..00000000000
--- a/chromium/third_party/WebKit/Source/core/Resources/pagepopups/pickerCommon.js
+++ /dev/null
@@ -1,257 +0,0 @@
-"use strict";
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-/**
- * @param {!string} id
- */
-function $(id) {
- return document.getElementById(id);
-}
-
-/**
- * @param {!string} tagName
- * @param {string=} opt_class
- * @param {string=} opt_text
- * @return {!Element}
- */
-function createElement(tagName, opt_class, opt_text) {
- var element = document.createElement(tagName);
- if (opt_class)
- element.setAttribute("class", opt_class);
- if (opt_text)
- element.appendChild(document.createTextNode(opt_text));
- return element;
-}
-
-/**
- * @constructor
- * @param {!number|Rectangle|Object} xOrRect
- * @param {!number} y
- * @param {!number} width
- * @param {!number} height
- */
-function Rectangle(xOrRect, y, width, height) {
- if (typeof xOrRect === "object") {
- y = xOrRect.y;
- width = xOrRect.width;
- height = xOrRect.height;
- xOrRect = xOrRect.x;
- }
- this.x = xOrRect;
- this.y = y;
- this.width = width;
- this.height = height;
-}
-
-Rectangle.prototype = {
- get maxX() { return this.x + this.width; },
- get maxY() { return this.y + this.height; },
- toString: function() { return "Rectangle(" + this.x + "," + this.y + "," + this.width + "," + this.height + ")"; }
-};
-
-/**
- * @param {!Rectangle} rect1
- * @param {!Rectangle} rect2
- * @return {?Rectangle}
- */
-Rectangle.intersection = function(rect1, rect2) {
- var x = Math.max(rect1.x, rect2.x);
- var maxX = Math.min(rect1.maxX, rect2.maxX);
- var y = Math.max(rect1.y, rect2.y);
- var maxY = Math.min(rect1.maxY, rect2.maxY);
- var width = maxX - x;
- var height = maxY - y;
- if (width < 0 || height < 0)
- return null;
- return new Rectangle(x, y, width, height);
-};
-
-/**
- * @param {!number} width
- * @param {!number} height
- */
-function resizeWindow(width, height) {
- setWindowRect(adjustWindowRect(width, height, width, height));
-}
-
-/**
- * @param {!number} width
- * @param {!number} height
- * @param {?number} minWidth
- * @param {?number} minHeight
- * @return {!Rectangle}
- */
-function adjustWindowRect(width, height, minWidth, minHeight) {
- if (typeof minWidth !== "number")
- minWidth = 0;
- if (typeof minHeight !== "number")
- minHeight = 0;
-
- var windowRect = new Rectangle(0, 0, width, height);
-
- if (!global.params.anchorRectInScreen)
- return windowRect;
-
- var anchorRect = new Rectangle(global.params.anchorRectInScreen);
- var availRect = new Rectangle(window.screen.availLeft, window.screen.availTop, window.screen.availWidth, window.screen.availHeight);
-
- _adjustWindowRectVertically(windowRect, availRect, anchorRect, minHeight);
- _adjustWindowRectHorizontally(windowRect, availRect, anchorRect, minWidth);
-
- return windowRect;
-}
-
-function _adjustWindowRectVertically(windowRect, availRect, anchorRect, minHeight) {
- var availableSpaceAbove = anchorRect.y - availRect.y;
- availableSpaceAbove = Math.max(0, Math.min(availRect.height, availableSpaceAbove));
-
- var availableSpaceBelow = availRect.maxY - anchorRect.maxY;
- availableSpaceBelow = Math.max(0, Math.min(availRect.height, availableSpaceBelow));
-
- if (windowRect.height > availableSpaceBelow && availableSpaceBelow < availableSpaceAbove) {
- windowRect.height = Math.min(windowRect.height, availableSpaceAbove);
- windowRect.height = Math.max(windowRect.height, minHeight);
- windowRect.y = anchorRect.y - windowRect.height;
- } else {
- windowRect.height = Math.min(windowRect.height, availableSpaceBelow);
- windowRect.height = Math.max(windowRect.height, minHeight);
- windowRect.y = anchorRect.maxY;
- }
- windowRect.y = Math.min(windowRect.y, availRect.maxY - windowRect.height);
- windowRect.y = Math.max(windowRect.y, availRect.y);
-}
-
-function _adjustWindowRectHorizontally(windowRect, availRect, anchorRect, minWidth) {
- windowRect.width = Math.min(windowRect.width, availRect.width);
- windowRect.width = Math.max(windowRect.width, minWidth);
- windowRect.x = anchorRect.x;
- if (global.params.isRTL)
- windowRect.x += anchorRect.width - windowRect.width;
- windowRect.x = Math.min(windowRect.x, availRect.maxX - windowRect.width);
- windowRect.x = Math.max(windowRect.x, availRect.x);
-}
-
-/**
- * @param {!Rectangle} rect
- */
-function setWindowRect(rect) {
- if (window.frameElement) {
- window.frameElement.style.width = rect.width + "px";
- window.frameElement.style.height = rect.height + "px";
- } else {
- if (isWindowHidden()) {
- window.moveTo(rect.x - window.screen.availLeft, rect.y - window.screen.availTop);
- window.resizeTo(rect.width, rect.height);
- } else {
- window.resizeTo(rect.width, rect.height);
- window.moveTo(rect.x - window.screen.availLeft, rect.y - window.screen.availTop);
- }
- }
-}
-
-function hideWindow() {
- resizeWindow(1, 1);
-}
-
-/**
- * @return {!boolean}
- */
-function isWindowHidden() {
- return window.innerWidth === 1 && window.innerHeight === 1;
-}
-
-window.addEventListener("resize", function() {
- if (isWindowHidden())
- window.dispatchEvent(new CustomEvent("didHide"));
- else
- window.dispatchEvent(new CustomEvent("didOpenPicker"));
-}, false);
-
-/**
- * @return {!number}
- */
-function getScrollbarWidth() {
- if (typeof window.scrollbarWidth === "undefined") {
- var scrollDiv = document.createElement("div");
- scrollDiv.style.opacity = "0";
- scrollDiv.style.overflow = "scroll";
- scrollDiv.style.width = "50px";
- scrollDiv.style.height = "50px";
- document.body.appendChild(scrollDiv);
- window.scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth;
- scrollDiv.parentNode.removeChild(scrollDiv);
- }
- return window.scrollbarWidth;
-}
-
-/**
- * @param {!string} className
- * @return {?Element}
- */
-function enclosingNodeOrSelfWithClass(selfNode, className)
-{
- for (var node = selfNode; node && node !== selfNode.ownerDocument; node = node.parentNode) {
- if (node.nodeType === Node.ELEMENT_NODE && node.classList.contains(className))
- return node;
- }
- return null;
-};
-
-/**
- * @constructor
- * @param {!Element} element
- * @param {!Object} config
- */
-function Picker(element, config) {
- this._element = element;
- this._config = config;
-}
-
-/**
- * @enum {number}
- */
-Picker.Actions = {
- SetValue: 0,
- Cancel: -1,
- ChooseOtherColor: -2
-};
-
-/**
- * @param {!string} value
- */
-Picker.prototype.submitValue = function(value) {
- window.pagePopupController.setValue(value);
- window.pagePopupController.closePopup();
-}
-
-Picker.prototype.handleCancel = function() {
- window.pagePopupController.closePopup();
-}
-
-Picker.prototype.chooseOtherColor = function() {
- window.pagePopupController.setValueAndClosePopup(Picker.Actions.ChooseOtherColor, "");
-}
-
-Picker.prototype.cleanup = function() {};
diff --git a/chromium/third_party/WebKit/Source/core/Resources/pagepopups/suggestionPicker.css b/chromium/third_party/WebKit/Source/core/Resources/pagepopups/suggestionPicker.css
deleted file mode 100644
index 0281d0df5bf..00000000000
--- a/chromium/third_party/WebKit/Source/core/Resources/pagepopups/suggestionPicker.css
+++ /dev/null
@@ -1,56 +0,0 @@
-.suggestion-list {
- list-style: none;
- padding: 0;
- margin: 0;
- font: -webkit-small-control;
- border: 1px solid #7f9db9;
- background-color: white;
- overflow: hidden;
-}
-
-.suggestion-list-entry {
- white-space: nowrap;
- height: 1.73em;
- line-height: 1.73em;
- -webkit-select: none;
- cursor: default;
-}
-
-.suggestion-list-entry:focus {
- outline: none;
-}
-
-.suggestion-list-entry .content {
- padding: 0 4px;
-}
-
-.suggestion-list-entry .label {
- text-align: right;
- color: #737373;
- float: right;
- padding: 0 4px 0 20px;
-}
-
-.rtl .suggestion-list-entry .label {
- float: left;
- padding: 0 20px 0 4px;
-}
-
-.suggestion-list-entry .title {
- direction: ltr;
- display: inline-block;
-}
-
-.locale-rtl .suggestion-list-entry .title {
- direction: rtl;
-}
-
-.measuring-width .suggestion-list-entry .label {
- float: none;
- margin-right: 0;
-}
-
-.suggestion-list .separator {
- border-top: 1px solid #dcdcdc;
- height: 0;
-}
diff --git a/chromium/third_party/WebKit/Source/core/Resources/pagepopups/suggestionPicker.js b/chromium/third_party/WebKit/Source/core/Resources/pagepopups/suggestionPicker.js
deleted file mode 100644
index 2d4bada41bf..00000000000
--- a/chromium/third_party/WebKit/Source/core/Resources/pagepopups/suggestionPicker.js
+++ /dev/null
@@ -1,325 +0,0 @@
-"use strict";
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-/**
- * @constructor
- * @param {!Element} element
- * @param {!Object} config
- */
-function SuggestionPicker(element, config) {
- Picker.call(this, element, config);
- this._isFocusByMouse = false;
- this._containerElement = null;
- this._setColors();
- this._layout();
- this._fixWindowSize();
- this._handleBodyKeyDownBound = this._handleBodyKeyDown.bind(this);
- document.body.addEventListener("keydown", this._handleBodyKeyDownBound);
- this._element.addEventListener("mouseout", this._handleMouseOut.bind(this), false);
-};
-SuggestionPicker.prototype = Object.create(Picker.prototype);
-
-SuggestionPicker.NumberOfVisibleEntries = 20;
-
-// An entry needs to be at least this many pixels visible for it to be a visible entry.
-SuggestionPicker.VisibleEntryThresholdHeight = 4;
-
-SuggestionPicker.ActionNames = {
- OpenCalendarPicker: "openCalendarPicker"
-};
-
-SuggestionPicker.ListEntryClass = "suggestion-list-entry";
-
-SuggestionPicker.validateConfig = function(config) {
- if (config.showOtherDateEntry && !config.otherDateLabel)
- return "No otherDateLabel.";
- if (config.suggestionHighlightColor && !config.suggestionHighlightColor)
- return "No suggestionHighlightColor.";
- if (config.suggestionHighlightTextColor && !config.suggestionHighlightTextColor)
- return "No suggestionHighlightTextColor.";
- if (config.suggestionValues.length !== config.localizedSuggestionValues.length)
- return "localizedSuggestionValues.length must equal suggestionValues.length.";
- if (config.suggestionValues.length !== config.suggestionLabels.length)
- return "suggestionLabels.length must equal suggestionValues.length.";
- if (typeof config.inputWidth === "undefined")
- return "No inputWidth.";
- return null;
-};
-
-SuggestionPicker.prototype._setColors = function() {
- var text = "." + SuggestionPicker.ListEntryClass + ":focus {\
- background-color: " + this._config.suggestionHighlightColor + ";\
- color: " + this._config.suggestionHighlightTextColor + "; }";
- text += "." + SuggestionPicker.ListEntryClass + ":focus .label { color: " + this._config.suggestionHighlightTextColor + "; }";
- document.head.appendChild(createElement("style", null, text));
-};
-
-SuggestionPicker.prototype.cleanup = function() {
- document.body.removeEventListener("keydown", this._handleBodyKeyDownBound, false);
-};
-
-/**
- * @param {!string} title
- * @param {!string} label
- * @param {!string} value
- * @return {!Element}
- */
-SuggestionPicker.prototype._createSuggestionEntryElement = function(title, label, value) {
- var entryElement = createElement("li", SuggestionPicker.ListEntryClass);
- entryElement.tabIndex = 0;
- entryElement.dataset.value = value;
- var content = createElement("span", "content");
- entryElement.appendChild(content);
- var titleElement = createElement("span", "title", title);
- content.appendChild(titleElement);
- if (label) {
- var labelElement = createElement("span", "label", label);
- content.appendChild(labelElement);
- }
- entryElement.addEventListener("mouseover", this._handleEntryMouseOver.bind(this), false);
- return entryElement;
-};
-
-/**
- * @param {!string} title
- * @param {!string} actionName
- * @return {!Element}
- */
-SuggestionPicker.prototype._createActionEntryElement = function(title, actionName) {
- var entryElement = createElement("li", SuggestionPicker.ListEntryClass);
- entryElement.tabIndex = 0;
- entryElement.dataset.action = actionName;
- var content = createElement("span", "content");
- entryElement.appendChild(content);
- var titleElement = createElement("span", "title", title);
- content.appendChild(titleElement);
- entryElement.addEventListener("mouseover", this._handleEntryMouseOver.bind(this), false);
- return entryElement;
-};
-
-/**
-* @return {!number}
-*/
-SuggestionPicker.prototype._measureMaxContentWidth = function() {
- // To measure the required width, we first set the class to "measuring-width" which
- // left aligns all the content including label.
- this._containerElement.classList.add("measuring-width");
- var maxContentWidth = 0;
- var contentElements = this._containerElement.getElementsByClassName("content");
- for (var i=0; i < contentElements.length; ++i) {
- maxContentWidth = Math.max(maxContentWidth, contentElements[i].offsetWidth);
- }
- this._containerElement.classList.remove("measuring-width");
- return maxContentWidth;
-};
-
-SuggestionPicker.prototype._fixWindowSize = function() {
- var ListBorder = 2;
- var desiredWindowWidth = this._measureMaxContentWidth() + ListBorder;
- if (typeof this._config.inputWidth === "number")
- desiredWindowWidth = Math.max(this._config.inputWidth, desiredWindowWidth);
- var totalHeight = ListBorder;
- var maxHeight = 0;
- var entryCount = 0;
- for (var i = 0; i < this._containerElement.childNodes.length; ++i) {
- var node = this._containerElement.childNodes[i];
- if (node.classList.contains(SuggestionPicker.ListEntryClass))
- entryCount++;
- totalHeight += node.offsetHeight;
- if (maxHeight === 0 && entryCount == SuggestionPicker.NumberOfVisibleEntries)
- maxHeight = totalHeight;
- }
- var desiredWindowHeight = totalHeight;
- if (maxHeight !== 0 && totalHeight > maxHeight) {
- this._containerElement.style.maxHeight = (maxHeight - ListBorder) + "px";
- desiredWindowWidth += getScrollbarWidth();
- desiredWindowHeight = maxHeight;
- this._containerElement.style.overflowY = "scroll";
- }
-
- var windowRect = adjustWindowRect(desiredWindowWidth, desiredWindowHeight, desiredWindowWidth, 0);
- this._containerElement.style.height = (windowRect.height - ListBorder) + "px";
- setWindowRect(windowRect);
-};
-
-SuggestionPicker.prototype._layout = function() {
- if (this._config.isRTL)
- this._element.classList.add("rtl");
- if (this._config.isLocaleRTL)
- this._element.classList.add("locale-rtl");
- this._containerElement = createElement("ul", "suggestion-list");
- this._containerElement.addEventListener("click", this._handleEntryClick.bind(this), false);
- for (var i = 0; i < this._config.suggestionValues.length; ++i) {
- this._containerElement.appendChild(this._createSuggestionEntryElement(this._config.localizedSuggestionValues[i], this._config.suggestionLabels[i], this._config.suggestionValues[i]));
- }
- if (this._config.showOtherDateEntry) {
- // Add separator
- var separator = createElement("div", "separator");
- this._containerElement.appendChild(separator);
-
- // Add "Other..." entry
- var otherEntry = this._createActionEntryElement(this._config.otherDateLabel, SuggestionPicker.ActionNames.OpenCalendarPicker);
- this._containerElement.appendChild(otherEntry);
- }
- this._element.appendChild(this._containerElement);
-};
-
-/**
- * @param {!Element} entry
- */
-SuggestionPicker.prototype.selectEntry = function(entry) {
- if (typeof entry.dataset.value !== "undefined") {
- this.submitValue(entry.dataset.value);
- } else if (entry.dataset.action === SuggestionPicker.ActionNames.OpenCalendarPicker) {
- window.addEventListener("didHide", SuggestionPicker._handleWindowDidHide, false);
- hideWindow();
- }
-};
-
-SuggestionPicker._handleWindowDidHide = function() {
- openCalendarPicker();
- window.removeEventListener("didHide", SuggestionPicker._handleWindowDidHide);
-};
-
-/**
- * @param {!Event} event
- */
-SuggestionPicker.prototype._handleEntryClick = function(event) {
- var entry = enclosingNodeOrSelfWithClass(event.target, SuggestionPicker.ListEntryClass);
- if (!entry)
- return;
- this.selectEntry(entry);
- event.preventDefault();
-};
-
-/**
- * @return {?Element}
- */
-SuggestionPicker.prototype._findFirstVisibleEntry = function() {
- var scrollTop = this._containerElement.scrollTop;
- var childNodes = this._containerElement.childNodes;
- for (var i = 0; i < childNodes.length; ++i) {
- var node = childNodes[i];
- if (node.nodeType !== Node.ELEMENT_NODE || !node.classList.contains(SuggestionPicker.ListEntryClass))
- continue;
- if (node.offsetTop + node.offsetHeight - scrollTop > SuggestionPicker.VisibleEntryThresholdHeight)
- return node;
- }
- return null;
-};
-
-/**
- * @return {?Element}
- */
-SuggestionPicker.prototype._findLastVisibleEntry = function() {
- var scrollBottom = this._containerElement.scrollTop + this._containerElement.offsetHeight;
- var childNodes = this._containerElement.childNodes;
- for (var i = childNodes.length - 1; i >= 0; --i){
- var node = childNodes[i];
- if (node.nodeType !== Node.ELEMENT_NODE || !node.classList.contains(SuggestionPicker.ListEntryClass))
- continue;
- if (scrollBottom - node.offsetTop > SuggestionPicker.VisibleEntryThresholdHeight)
- return node;
- }
- return null;
-};
-
-/**
- * @param {!Event} event
- */
-SuggestionPicker.prototype._handleBodyKeyDown = function(event) {
- var eventHandled = false;
- var key = event.keyIdentifier;
- if (key === "U+001B") { // ESC
- this.handleCancel();
- eventHandled = true;
- } else if (key == "Up") {
- if (document.activeElement && document.activeElement.classList.contains(SuggestionPicker.ListEntryClass)) {
- for (var node = document.activeElement.previousElementSibling; node; node = node.previousElementSibling) {
- if (node.classList.contains(SuggestionPicker.ListEntryClass)) {
- this._isFocusByMouse = false;
- node.focus();
- break;
- }
- }
- } else {
- this._element.querySelector("." + SuggestionPicker.ListEntryClass + ":last-child").focus();
- }
- eventHandled = true;
- } else if (key == "Down") {
- if (document.activeElement && document.activeElement.classList.contains(SuggestionPicker.ListEntryClass)) {
- for (var node = document.activeElement.nextElementSibling; node; node = node.nextElementSibling) {
- if (node.classList.contains(SuggestionPicker.ListEntryClass)) {
- this._isFocusByMouse = false;
- node.focus();
- break;
- }
- }
- } else {
- this._element.querySelector("." + SuggestionPicker.ListEntryClass + ":first-child").focus();
- }
- eventHandled = true;
- } else if (key === "Enter") {
- this.selectEntry(document.activeElement);
- eventHandled = true;
- } else if (key === "PageUp") {
- this._containerElement.scrollTop -= this._containerElement.clientHeight;
- // Scrolling causes mouseover event to be called and that tries to move the focus too.
- // To prevent flickering we won't focus if the current focus was caused by the mouse.
- if (!this._isFocusByMouse)
- this._findFirstVisibleEntry().focus();
- eventHandled = true;
- } else if (key === "PageDown") {
- this._containerElement.scrollTop += this._containerElement.clientHeight;
- if (!this._isFocusByMouse)
- this._findLastVisibleEntry().focus();
- eventHandled = true;
- }
- if (eventHandled)
- event.preventDefault();
-};
-
-/**
- * @param {!Event} event
- */
-SuggestionPicker.prototype._handleEntryMouseOver = function(event) {
- var entry = enclosingNodeOrSelfWithClass(event.target, SuggestionPicker.ListEntryClass);
- if (!entry)
- return;
- this._isFocusByMouse = true;
- entry.focus();
- event.preventDefault();
-};
-
-/**
- * @param {!Event} event
- */
-SuggestionPicker.prototype._handleMouseOut = function(event) {
- if (!document.activeElement.classList.contains(SuggestionPicker.ListEntryClass))
- return;
- this._isFocusByMouse = false;
- document.activeElement.blur();
- event.preventDefault();
-};
diff --git a/chromium/third_party/WebKit/Source/core/Resources/panIcon.png b/chromium/third_party/WebKit/Source/core/Resources/panIcon.png
deleted file mode 100644
index 4ca8d703744..00000000000
--- a/chromium/third_party/WebKit/Source/core/Resources/panIcon.png
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/Resources/progressCursor.png b/chromium/third_party/WebKit/Source/core/Resources/progressCursor.png
deleted file mode 100644
index 25d70214320..00000000000
--- a/chromium/third_party/WebKit/Source/core/Resources/progressCursor.png
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/Resources/southEastResizeCursor.png b/chromium/third_party/WebKit/Source/core/Resources/southEastResizeCursor.png
deleted file mode 100644
index 415aa633b51..00000000000
--- a/chromium/third_party/WebKit/Source/core/Resources/southEastResizeCursor.png
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/Resources/southResizeCursor.png b/chromium/third_party/WebKit/Source/core/Resources/southResizeCursor.png
deleted file mode 100644
index 60cf722d1ee..00000000000
--- a/chromium/third_party/WebKit/Source/core/Resources/southResizeCursor.png
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/Resources/southWestResizeCursor.png b/chromium/third_party/WebKit/Source/core/Resources/southWestResizeCursor.png
deleted file mode 100644
index 8dc5cdc584b..00000000000
--- a/chromium/third_party/WebKit/Source/core/Resources/southWestResizeCursor.png
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/Resources/textAreaResizeCorner.png b/chromium/third_party/WebKit/Source/core/Resources/textAreaResizeCorner.png
deleted file mode 100644
index 66105dbcd3c..00000000000
--- a/chromium/third_party/WebKit/Source/core/Resources/textAreaResizeCorner.png
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/Resources/textAreaResizeCorner.tiff b/chromium/third_party/WebKit/Source/core/Resources/textAreaResizeCorner.tiff
deleted file mode 100644
index 5eeab606ace..00000000000
--- a/chromium/third_party/WebKit/Source/core/Resources/textAreaResizeCorner.tiff
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/Resources/textAreaResizeCorner@2x.png b/chromium/third_party/WebKit/Source/core/Resources/textAreaResizeCorner@2x.png
deleted file mode 100644
index 7d26fbc42f9..00000000000
--- a/chromium/third_party/WebKit/Source/core/Resources/textAreaResizeCorner@2x.png
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/Resources/urlIcon.png b/chromium/third_party/WebKit/Source/core/Resources/urlIcon.png
deleted file mode 100644
index 53cb3545197..00000000000
--- a/chromium/third_party/WebKit/Source/core/Resources/urlIcon.png
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/Resources/verticalTextCursor.png b/chromium/third_party/WebKit/Source/core/Resources/verticalTextCursor.png
deleted file mode 100644
index 0f2877ccc32..00000000000
--- a/chromium/third_party/WebKit/Source/core/Resources/verticalTextCursor.png
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/Resources/waitCursor.png b/chromium/third_party/WebKit/Source/core/Resources/waitCursor.png
deleted file mode 100644
index 91412b8187b..00000000000
--- a/chromium/third_party/WebKit/Source/core/Resources/waitCursor.png
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/Resources/westResizeCursor.png b/chromium/third_party/WebKit/Source/core/Resources/westResizeCursor.png
deleted file mode 100644
index 544439adc26..00000000000
--- a/chromium/third_party/WebKit/Source/core/Resources/westResizeCursor.png
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/Resources/zoomInCursor.png b/chromium/third_party/WebKit/Source/core/Resources/zoomInCursor.png
deleted file mode 100644
index feec9bcbb5f..00000000000
--- a/chromium/third_party/WebKit/Source/core/Resources/zoomInCursor.png
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/Resources/zoomOutCursor.png b/chromium/third_party/WebKit/Source/core/Resources/zoomOutCursor.png
deleted file mode 100644
index f4a954e32be..00000000000
--- a/chromium/third_party/WebKit/Source/core/Resources/zoomOutCursor.png
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AXARIAGrid.cpp b/chromium/third_party/WebKit/Source/core/accessibility/AXARIAGrid.cpp
new file mode 100644
index 00000000000..beac9c9e6e3
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/accessibility/AXARIAGrid.cpp
@@ -0,0 +1,133 @@
+/*
+ * Copyright (C) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/accessibility/AXARIAGrid.h"
+
+#include "core/accessibility/AXObjectCache.h"
+#include "core/accessibility/AXTableColumn.h"
+#include "core/accessibility/AXTableRow.h"
+#include "core/rendering/RenderObject.h"
+
+using namespace std;
+
+namespace WebCore {
+
+AXARIAGrid::AXARIAGrid(RenderObject* renderer)
+ : AXTable(renderer)
+{
+}
+
+AXARIAGrid::~AXARIAGrid()
+{
+}
+
+PassRefPtr<AXARIAGrid> AXARIAGrid::create(RenderObject* renderer)
+{
+ return adoptRef(new AXARIAGrid(renderer));
+}
+
+bool AXARIAGrid::addTableCellChild(AXObject* child, HashSet<AXObject*>& appendedRows, unsigned& columnCount)
+{
+ if (!child || !child->isTableRow() || child->ariaRoleAttribute() != RowRole)
+ return false;
+
+ AXTableRow* row = toAXTableRow(child);
+ if (appendedRows.contains(row))
+ return false;
+
+ // store the maximum number of columns
+ unsigned rowCellCount = row->children().size();
+ if (rowCellCount > columnCount)
+ columnCount = rowCellCount;
+
+ row->setRowIndex((int)m_rows.size());
+ m_rows.append(row);
+
+ // Try adding the row if it's not ignoring accessibility,
+ // otherwise add its children (the cells) as the grid's children.
+ if (!row->accessibilityIsIgnored())
+ m_children.append(row);
+ else
+ m_children.append(row->children());
+
+ appendedRows.add(row);
+ return true;
+}
+
+void AXARIAGrid::addChildren()
+{
+ ASSERT(!m_haveChildren);
+
+ if (!isAXTable()) {
+ AXRenderObject::addChildren();
+ return;
+ }
+
+ m_haveChildren = true;
+ if (!m_renderer)
+ return;
+
+ AXObjectCache* axCache = m_renderer->document().axObjectCache();
+
+ // add only rows that are labeled as aria rows
+ HashSet<AXObject*> appendedRows;
+ unsigned columnCount = 0;
+ for (RefPtr<AXObject> child = firstChild(); child; child = child->nextSibling()) {
+
+ if (!addTableCellChild(child.get(), appendedRows, columnCount)) {
+
+ // in case the render tree doesn't match the expected ARIA hierarchy, look at the children
+ if (!child->hasChildren())
+ child->addChildren();
+
+ // The children of this non-row will contain all non-ignored elements (recursing to find them).
+ // This allows the table to dive arbitrarily deep to find the rows.
+ AccessibilityChildrenVector children = child->children();
+ size_t length = children.size();
+ for (size_t i = 0; i < length; ++i)
+ addTableCellChild(children[i].get(), appendedRows, columnCount);
+ }
+ }
+
+ // make the columns based on the number of columns in the first body
+ for (unsigned i = 0; i < columnCount; ++i) {
+ AXTableColumn* column = toAXTableColumn(axCache->getOrCreate(ColumnRole));
+ column->setColumnIndex((int)i);
+ column->setParent(this);
+ m_columns.append(column);
+ if (!column->accessibilityIsIgnored())
+ m_children.append(column);
+ }
+
+ AXObject* headerContainerObject = headerContainer();
+ if (headerContainerObject && !headerContainerObject->accessibilityIsIgnored())
+ m_children.append(headerContainerObject);
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AXARIAGrid.h b/chromium/third_party/WebKit/Source/core/accessibility/AXARIAGrid.h
new file mode 100644
index 00000000000..e108151e56f
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/accessibility/AXARIAGrid.h
@@ -0,0 +1,63 @@
+/*
+ * Copyright (C) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef AXARIAGrid_h
+#define AXARIAGrid_h
+
+#include "core/accessibility/AXTable.h"
+#include "wtf/Forward.h"
+
+namespace WebCore {
+
+class AXTableCell;
+class AXTableHeaderContainer;
+
+class AXARIAGrid : public AXTable {
+
+private:
+ explicit AXARIAGrid(RenderObject*);
+public:
+ static PassRefPtr<AXARIAGrid> create(RenderObject*);
+ virtual ~AXARIAGrid();
+
+ virtual bool isAriaTable() const OVERRIDE { return true; }
+
+ virtual void addChildren() OVERRIDE;
+
+private:
+ // ARIA treegrids and grids support selected rows.
+ virtual bool supportsSelectedRows() OVERRIDE { return true; }
+ virtual bool isMultiSelectable() const OVERRIDE { return true; }
+ virtual bool isTableExposableThroughAccessibility() const OVERRIDE { return true; }
+
+ bool addTableCellChild(AXObject*, HashSet<AXObject*>& appendedRows, unsigned& columnCount);
+};
+
+} // namespace WebCore
+
+#endif // AXARIAGrid_h
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AXARIAGridCell.cpp b/chromium/third_party/WebKit/Source/core/accessibility/AXARIAGridCell.cpp
new file mode 100644
index 00000000000..8602bb1fcba
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/accessibility/AXARIAGridCell.cpp
@@ -0,0 +1,124 @@
+/*
+ * Copyright (C) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/accessibility/AXARIAGridCell.h"
+
+#include "core/accessibility/AXTable.h"
+#include "core/accessibility/AXTableRow.h"
+
+using namespace std;
+
+namespace WebCore {
+
+AXARIAGridCell::AXARIAGridCell(RenderObject* renderer)
+ : AXTableCell(renderer)
+{
+}
+
+AXARIAGridCell::~AXARIAGridCell()
+{
+}
+
+PassRefPtr<AXARIAGridCell> AXARIAGridCell::create(RenderObject* renderer)
+{
+ return adoptRef(new AXARIAGridCell(renderer));
+}
+
+AXObject* AXARIAGridCell::parentTable() const
+{
+ AXObject* parent = parentObjectUnignored();
+ if (!parent)
+ return 0;
+
+ if (parent->isAXTable())
+ return parent;
+
+ // It could happen that we hadn't reached the parent table yet (in
+ // case objects for rows were not ignoring accessibility) so for
+ // that reason we need to run parentObjectUnignored once again.
+ parent = parent->parentObjectUnignored();
+ if (!parent || !parent->isAXTable())
+ return 0;
+
+ return parent;
+}
+
+void AXARIAGridCell::rowIndexRange(pair<unsigned, unsigned>& rowRange)
+{
+ AXObject* parent = parentObjectUnignored();
+ if (!parent)
+ return;
+
+ if (parent->isTableRow()) {
+ // We already got a table row, use its API.
+ rowRange.first = toAXTableRow(parent)->rowIndex();
+ } else if (parent->isAXTable()) {
+ // We reached the parent table, so we need to inspect its
+ // children to determine the row index for the cell in it.
+ unsigned columnCount = toAXTable(parent)->columnCount();
+ if (!columnCount)
+ return;
+
+ AccessibilityChildrenVector siblings = parent->children();
+ unsigned childrenSize = siblings.size();
+ for (unsigned k = 0; k < childrenSize; ++k) {
+ if (siblings[k].get() == this) {
+ rowRange.first = k / columnCount;
+ break;
+ }
+ }
+ }
+
+ // as far as I can tell, grid cells cannot span rows
+ rowRange.second = 1;
+}
+
+void AXARIAGridCell::columnIndexRange(pair<unsigned, unsigned>& columnRange)
+{
+ AXObject* parent = parentObjectUnignored();
+ if (!parent)
+ return;
+
+ if (!parent->isTableRow() && !parent->isAXTable())
+ return;
+
+ AccessibilityChildrenVector siblings = parent->children();
+ unsigned childrenSize = siblings.size();
+ for (unsigned k = 0; k < childrenSize; ++k) {
+ if (siblings[k].get() == this) {
+ columnRange.first = k;
+ break;
+ }
+ }
+
+ // as far as I can tell, grid cells cannot span columns
+ columnRange.second = 1;
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AXARIAGridCell.h b/chromium/third_party/WebKit/Source/core/accessibility/AXARIAGridCell.h
new file mode 100644
index 00000000000..0bf53fbbfd7
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/accessibility/AXARIAGridCell.h
@@ -0,0 +1,55 @@
+/*
+ * Copyright (C) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef AXARIAGridCell_h
+#define AXARIAGridCell_h
+
+#include "core/accessibility/AXTableCell.h"
+
+namespace WebCore {
+
+class AXARIAGridCell : public AXTableCell {
+
+private:
+ explicit AXARIAGridCell(RenderObject*);
+public:
+ static PassRefPtr<AXARIAGridCell> create(RenderObject*);
+ virtual ~AXARIAGridCell();
+
+ // fills in the start location and row span of cell
+ virtual void rowIndexRange(pair<unsigned, unsigned>& rowRange) OVERRIDE;
+ // fills in the start location and column span of cell
+ virtual void columnIndexRange(pair<unsigned, unsigned>& columnRange) OVERRIDE;
+
+protected:
+ virtual AXObject* parentTable() const;
+};
+
+} // namespace WebCore
+
+#endif // AXARIAGridCell_h
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AXARIAGridRow.cpp b/chromium/third_party/WebKit/Source/core/accessibility/AXARIAGridRow.cpp
new file mode 100644
index 00000000000..36d0da6bdcc
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/accessibility/AXARIAGridRow.cpp
@@ -0,0 +1,130 @@
+/*
+ * Copyright (C) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/accessibility/AXARIAGridRow.h"
+
+#include "core/accessibility/AXTable.h"
+
+using namespace std;
+
+namespace WebCore {
+
+AXARIAGridRow::AXARIAGridRow(RenderObject* renderer)
+ : AXTableRow(renderer)
+{
+}
+
+AXARIAGridRow::~AXARIAGridRow()
+{
+}
+
+PassRefPtr<AXARIAGridRow> AXARIAGridRow::create(RenderObject* renderer)
+{
+ return adoptRef(new AXARIAGridRow(renderer));
+}
+
+bool AXARIAGridRow::isARIATreeGridRow() const
+{
+ AXObject* parent = parentTable();
+ if (!parent)
+ return false;
+
+ return parent->ariaRoleAttribute() == TreeGridRole;
+}
+
+void AXARIAGridRow::disclosedRows(AccessibilityChildrenVector& disclosedRows)
+{
+ // The contiguous disclosed rows will be the rows in the table that
+ // have an aria-level of plus 1 from this row.
+ AXObject* parent = parentObjectUnignored();
+ if (!parent || !parent->isAXTable())
+ return;
+
+ // Search for rows that match the correct level.
+ // Only take the subsequent rows from this one that are +1 from this row's level.
+ int index = rowIndex();
+ if (index < 0)
+ return;
+
+ unsigned level = hierarchicalLevel();
+ AccessibilityChildrenVector& allRows = toAXTable(parent)->rows();
+ int rowCount = allRows.size();
+ for (int k = index + 1; k < rowCount; ++k) {
+ AXObject* row = allRows[k].get();
+ // Stop at the first row that doesn't match the correct level.
+ if (row->hierarchicalLevel() != level + 1)
+ break;
+
+ disclosedRows.append(row);
+ }
+}
+
+AXObject* AXARIAGridRow::disclosedByRow() const
+{
+ // The row that discloses this one is the row in the table
+ // that is aria-level subtract 1 from this row.
+ AXObject* parent = parentObjectUnignored();
+ if (!parent || !parent->isAXTable())
+ return 0;
+
+ // If the level is 1 or less, than nothing discloses this row.
+ unsigned level = hierarchicalLevel();
+ if (level <= 1)
+ return 0;
+
+ // Search for the previous row that matches the correct level.
+ int index = rowIndex();
+ AccessibilityChildrenVector& allRows = toAXTable(parent)->rows();
+ int rowCount = allRows.size();
+ if (index >= rowCount)
+ return 0;
+
+ for (int k = index - 1; k >= 0; --k) {
+ AXObject* row = allRows[k].get();
+ if (row->hierarchicalLevel() == level - 1)
+ return row;
+ }
+
+ return 0;
+}
+
+AXObject* AXARIAGridRow::headerObject()
+{
+ AccessibilityChildrenVector rowChildren = children();
+ unsigned childrenCount = rowChildren.size();
+ for (unsigned i = 0; i < childrenCount; ++i) {
+ AXObject* cell = rowChildren[i].get();
+ if (cell->ariaRoleAttribute() == RowHeaderRole)
+ return cell;
+ }
+
+ return 0;
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AXARIAGridRow.h b/chromium/third_party/WebKit/Source/core/accessibility/AXARIAGridRow.h
new file mode 100644
index 00000000000..54dc1f0ebfb
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/accessibility/AXARIAGridRow.h
@@ -0,0 +1,55 @@
+/*
+ * Copyright (C) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef AXARIAGridRow_h
+#define AXARIAGridRow_h
+
+#include "core/accessibility/AXTableRow.h"
+
+namespace WebCore {
+
+class AXARIAGridRow : public AXTableRow {
+
+private:
+ explicit AXARIAGridRow(RenderObject*);
+public:
+ static PassRefPtr<AXARIAGridRow> create(RenderObject*);
+ virtual ~AXARIAGridRow();
+
+ void disclosedRows(AccessibilityChildrenVector&);
+ AXObject* disclosedByRow() const;
+
+ virtual AXObject* headerObject() OVERRIDE;
+
+private:
+ virtual bool isARIATreeGridRow() const;
+};
+
+} // namespace WebCore
+
+#endif // AXARIAGridRow_h
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AXImageMapLink.cpp b/chromium/third_party/WebKit/Source/core/accessibility/AXImageMapLink.cpp
new file mode 100644
index 00000000000..e4977049bcb
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/accessibility/AXImageMapLink.cpp
@@ -0,0 +1,158 @@
+/*
+ * Copyright (C) 2008 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/accessibility/AXImageMapLink.h"
+
+#include "core/accessibility/AXObjectCache.h"
+#include "core/accessibility/AXRenderObject.h"
+
+namespace WebCore {
+
+using namespace HTMLNames;
+
+AXImageMapLink::AXImageMapLink()
+ : m_areaElement(0)
+ , m_mapElement(0)
+{
+}
+
+AXImageMapLink::~AXImageMapLink()
+{
+}
+
+void AXImageMapLink::detachFromParent()
+{
+ AXMockObject::detachFromParent();
+ m_areaElement = 0;
+ m_mapElement = 0;
+}
+
+PassRefPtr<AXImageMapLink> AXImageMapLink::create()
+{
+ return adoptRef(new AXImageMapLink());
+}
+
+AXObject* AXImageMapLink::parentObject() const
+{
+ if (m_parent)
+ return m_parent;
+
+ if (!m_mapElement.get() || !m_mapElement->renderer())
+ return 0;
+
+ return m_mapElement->document().axObjectCache()->getOrCreate(m_mapElement->renderer());
+}
+
+AccessibilityRole AXImageMapLink::roleValue() const
+{
+ if (!m_areaElement)
+ return LinkRole;
+
+ const AtomicString& ariaRole = getAttribute(roleAttr);
+ if (!ariaRole.isEmpty())
+ return AXObject::ariaRoleToWebCoreRole(ariaRole);
+
+ return LinkRole;
+}
+
+Element* AXImageMapLink::actionElement() const
+{
+ return anchorElement();
+}
+
+Element* AXImageMapLink::anchorElement() const
+{
+ return m_areaElement.get();
+}
+
+KURL AXImageMapLink::url() const
+{
+ if (!m_areaElement.get())
+ return KURL();
+
+ return m_areaElement->href();
+}
+
+void AXImageMapLink::accessibilityText(Vector<AccessibilityText>& textOrder)
+{
+ String description = accessibilityDescription();
+ if (!description.isEmpty())
+ textOrder.append(AccessibilityText(description, AlternativeText));
+
+ const AtomicString& titleText = getAttribute(titleAttr);
+ if (!titleText.isEmpty())
+ textOrder.append(AccessibilityText(titleText, TitleTagText));
+
+ const AtomicString& summary = getAttribute(summaryAttr);
+ if (!summary.isEmpty())
+ textOrder.append(AccessibilityText(summary, SummaryText));
+}
+
+String AXImageMapLink::accessibilityDescription() const
+{
+ const AtomicString& ariaLabel = getAttribute(aria_labelAttr);
+ if (!ariaLabel.isEmpty())
+ return ariaLabel;
+ const AtomicString& alt = getAttribute(altAttr);
+ if (!alt.isEmpty())
+ return alt;
+
+ return String();
+}
+
+String AXImageMapLink::title() const
+{
+ const AtomicString& title = getAttribute(titleAttr);
+ if (!title.isEmpty())
+ return title;
+ const AtomicString& summary = getAttribute(summaryAttr);
+ if (!summary.isEmpty())
+ return summary;
+
+ return String();
+}
+
+LayoutRect AXImageMapLink::elementRect() const
+{
+ if (!m_mapElement.get() || !m_areaElement.get())
+ return LayoutRect();
+
+ RenderObject* renderer;
+ if (m_parent && m_parent->isAXRenderObject())
+ renderer = toAXRenderObject(m_parent)->renderer();
+ else
+ renderer = m_mapElement->renderer();
+
+ if (!renderer)
+ return LayoutRect();
+
+ return m_areaElement->computeRect(renderer);
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AXImageMapLink.h b/chromium/third_party/WebKit/Source/core/accessibility/AXImageMapLink.h
new file mode 100644
index 00000000000..08276a8e30e
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/accessibility/AXImageMapLink.h
@@ -0,0 +1,82 @@
+/*
+ * Copyright (C) 2008 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef AXImageMapLink_h
+#define AXImageMapLink_h
+
+#include "core/accessibility/AXMockObject.h"
+#include "core/html/HTMLAreaElement.h"
+#include "core/html/HTMLMapElement.h"
+
+namespace WebCore {
+
+class AXImageMapLink : public AXMockObject {
+
+private:
+ AXImageMapLink();
+public:
+ static PassRefPtr<AXImageMapLink> create();
+ virtual ~AXImageMapLink();
+
+ void setHTMLAreaElement(HTMLAreaElement* element) { m_areaElement = element; }
+ HTMLAreaElement* areaElement() const { return m_areaElement.get(); }
+
+ void setHTMLMapElement(HTMLMapElement* element) { m_mapElement = element; }
+ HTMLMapElement* mapElement() const { return m_mapElement.get(); }
+
+ virtual Node* node() const OVERRIDE { return m_areaElement.get(); }
+
+ virtual AccessibilityRole roleValue() const OVERRIDE;
+ virtual bool isEnabled() const OVERRIDE { return true; }
+
+ virtual Element* anchorElement() const OVERRIDE;
+ virtual Element* actionElement() const OVERRIDE;
+ virtual KURL url() const OVERRIDE;
+ virtual bool isLink() const { return true; }
+ virtual bool isLinked() const OVERRIDE { return true; }
+ virtual String title() const OVERRIDE;
+ virtual String accessibilityDescription() const OVERRIDE;
+ virtual AXObject* parentObject() const OVERRIDE;
+
+ virtual LayoutRect elementRect() const OVERRIDE;
+
+private:
+ RefPtr<HTMLAreaElement> m_areaElement;
+ RefPtr<HTMLMapElement> m_mapElement;
+
+ virtual void detachFromParent() OVERRIDE;
+
+ virtual void accessibilityText(Vector<AccessibilityText>&) OVERRIDE;
+ virtual bool isImageMapLink() const OVERRIDE { return true; }
+};
+
+DEFINE_AX_OBJECT_TYPE_CASTS(AXImageMapLink, isImageMapLink());
+
+} // namespace WebCore
+
+#endif // AXImageMapLink_h
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AXInlineTextBox.cpp b/chromium/third_party/WebKit/Source/core/accessibility/AXInlineTextBox.cpp
new file mode 100644
index 00000000000..9c5d7037e9c
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/accessibility/AXInlineTextBox.cpp
@@ -0,0 +1,154 @@
+/*
+ * Copyright (C) 2013, Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/accessibility/AXInlineTextBox.h"
+
+#include "core/accessibility/AXObjectCache.h"
+#include "core/dom/Range.h"
+#include "core/rendering/RenderText.h"
+#include "platform/LayoutUnit.h"
+
+using namespace std;
+
+namespace WebCore {
+
+using namespace HTMLNames;
+
+AXInlineTextBox::AXInlineTextBox(PassRefPtr<AbstractInlineTextBox> inlineTextBox)
+ : m_inlineTextBox(inlineTextBox)
+{
+ RenderText* renderText = m_inlineTextBox->renderText();
+ m_axObjectCache = renderText->document().axObjectCache();
+}
+
+AXInlineTextBox::~AXInlineTextBox()
+{
+ if (m_axObjectCache && m_inlineTextBox)
+ m_axObjectCache->remove(m_inlineTextBox.get());
+}
+
+PassRefPtr<AXInlineTextBox> AXInlineTextBox::create(PassRefPtr<AbstractInlineTextBox> inlineTextBox)
+{
+ return adoptRef(new AXInlineTextBox(inlineTextBox));
+}
+
+void AXInlineTextBox::init()
+{
+}
+
+void AXInlineTextBox::detach()
+{
+ m_inlineTextBox = 0;
+ m_axObjectCache = 0;
+ AXObject::detach();
+}
+
+LayoutRect AXInlineTextBox::elementRect() const
+{
+ if (!m_inlineTextBox)
+ return LayoutRect();
+
+ return m_inlineTextBox->bounds();
+}
+
+bool AXInlineTextBox::computeAccessibilityIsIgnored() const
+{
+ if (AXObject* parent = parentObject())
+ return parent->accessibilityIsIgnored();
+
+ return false;
+}
+
+void AXInlineTextBox::textCharacterOffsets(Vector<int>& offsets) const
+{
+ if (!m_inlineTextBox)
+ return;
+
+ unsigned len = m_inlineTextBox->len();
+ Vector<float> widths;
+ m_inlineTextBox->characterWidths(widths);
+ ASSERT(widths.size() == len);
+ offsets.resize(len);
+
+ float widthSoFar = 0;
+ for (unsigned i = 0; i < len; i++) {
+ widthSoFar += widths[i];
+ offsets[i] = LayoutUnit::fromFloatRound(widthSoFar);
+ }
+}
+
+void AXInlineTextBox::wordBoundaries(Vector<PlainTextRange>& words) const
+{
+ if (!m_inlineTextBox)
+ return;
+
+ Vector<AbstractInlineTextBox::WordBoundaries> wordBoundaries;
+ m_inlineTextBox->wordBoundaries(wordBoundaries);
+ words.resize(wordBoundaries.size());
+ for (unsigned i = 0; i < wordBoundaries.size(); i++)
+ words[i] = PlainTextRange(wordBoundaries[i].startIndex, wordBoundaries[i].endIndex - wordBoundaries[i].startIndex);
+}
+
+String AXInlineTextBox::stringValue() const
+{
+ if (!m_inlineTextBox)
+ return String();
+
+ return m_inlineTextBox->text();
+}
+
+AXObject* AXInlineTextBox::parentObject() const
+{
+ if (!m_inlineTextBox || !m_axObjectCache)
+ return 0;
+
+ RenderText* renderText = m_inlineTextBox->renderText();
+ return m_axObjectCache->getOrCreate(renderText);
+}
+
+AccessibilityTextDirection AXInlineTextBox::textDirection() const
+{
+ if (!m_inlineTextBox)
+ return AccessibilityTextDirectionLeftToRight;
+
+ switch (m_inlineTextBox->direction()) {
+ case AbstractInlineTextBox::LeftToRight:
+ return AccessibilityTextDirectionLeftToRight;
+ case AbstractInlineTextBox::RightToLeft:
+ return AccessibilityTextDirectionRightToLeft;
+ case AbstractInlineTextBox::TopToBottom:
+ return AccessibilityTextDirectionTopToBottom;
+ case AbstractInlineTextBox::BottomToTop:
+ return AccessibilityTextDirectionBottomToTop;
+ }
+
+ return AccessibilityTextDirectionLeftToRight;
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AXInlineTextBox.h b/chromium/third_party/WebKit/Source/core/accessibility/AXInlineTextBox.h
new file mode 100644
index 00000000000..b80b558ed47
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/accessibility/AXInlineTextBox.h
@@ -0,0 +1,68 @@
+/*
+ * Copyright (C) 2013, Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef AXInlineTextBox_h
+#define AXInlineTextBox_h
+
+#include "core/accessibility/AXObject.h"
+#include "core/rendering/AbstractInlineTextBox.h"
+
+namespace WebCore {
+
+class AXInlineTextBox : public AXObject {
+
+private:
+ AXInlineTextBox(PassRefPtr<AbstractInlineTextBox>);
+
+public:
+ static PassRefPtr<AXInlineTextBox> create(PassRefPtr<AbstractInlineTextBox>);
+ virtual ~AXInlineTextBox();
+
+ virtual void init() OVERRIDE;
+ virtual void detach() OVERRIDE;
+
+ void setInlineTextBox(AbstractInlineTextBox* inlineTextBox) { m_inlineTextBox = inlineTextBox; }
+
+ virtual AccessibilityRole roleValue() const OVERRIDE { return InlineTextBoxRole; }
+ virtual String stringValue() const OVERRIDE;
+ virtual void textCharacterOffsets(Vector<int>&) const OVERRIDE;
+ virtual void wordBoundaries(Vector<PlainTextRange>& words) const OVERRIDE;
+ virtual LayoutRect elementRect() const OVERRIDE;
+ virtual AXObject* parentObject() const OVERRIDE;
+ virtual AccessibilityTextDirection textDirection() const OVERRIDE;
+
+private:
+ RefPtr<AbstractInlineTextBox> m_inlineTextBox;
+ AXObjectCache* m_axObjectCache;
+
+ virtual bool computeAccessibilityIsIgnored() const OVERRIDE;
+};
+
+} // namespace WebCore
+
+#endif // AXInlineTextBox_h
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AXList.cpp b/chromium/third_party/WebKit/Source/core/accessibility/AXList.cpp
new file mode 100644
index 00000000000..c1cbe2764de
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/accessibility/AXList.cpp
@@ -0,0 +1,98 @@
+/*
+ * Copyright (C) 2008 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/accessibility/AXList.h"
+
+#include "core/rendering/RenderObject.h"
+
+using namespace std;
+
+namespace WebCore {
+
+using namespace HTMLNames;
+
+AXList::AXList(RenderObject* renderer)
+ : AXRenderObject(renderer)
+{
+}
+
+AXList::~AXList()
+{
+}
+
+PassRefPtr<AXList> AXList::create(RenderObject* renderer)
+{
+ return adoptRef(new AXList(renderer));
+}
+
+bool AXList::computeAccessibilityIsIgnored() const
+{
+ return accessibilityIsIgnoredByDefault();
+}
+
+bool AXList::isUnorderedList() const
+{
+ if (!m_renderer)
+ return false;
+
+ Node* node = m_renderer->node();
+
+ // The ARIA spec says the "list" role is supposed to mimic a UL or OL tag.
+ // Since it can't be both, it's probably OK to say that it's an un-ordered list.
+ // On the Mac, there's no distinction to the client.
+ if (ariaRoleAttribute() == ListRole)
+ return true;
+
+ return node && node->hasTagName(ulTag);
+}
+
+bool AXList::isOrderedList() const
+{
+ if (!m_renderer)
+ return false;
+
+ // ARIA says a directory is like a static table of contents, which sounds like an ordered list.
+ if (ariaRoleAttribute() == DirectoryRole)
+ return true;
+
+ Node* node = m_renderer->node();
+ return node && node->hasTagName(olTag);
+}
+
+bool AXList::isDescriptionList() const
+{
+ if (!m_renderer)
+ return false;
+
+ Node* node = m_renderer->node();
+ return node && node->hasTagName(dlTag);
+}
+
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AXList.h b/chromium/third_party/WebKit/Source/core/accessibility/AXList.h
new file mode 100644
index 00000000000..cba99d50a6d
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/accessibility/AXList.h
@@ -0,0 +1,56 @@
+/*
+ * Copyright (C) 2008 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef AXList_h
+#define AXList_h
+
+#include "core/accessibility/AXRenderObject.h"
+
+namespace WebCore {
+
+class AXList : public AXRenderObject {
+
+private:
+ explicit AXList(RenderObject*);
+public:
+ static PassRefPtr<AXList> create(RenderObject*);
+ virtual ~AXList();
+
+ virtual bool isList() const { return true; }
+ bool isUnorderedList() const;
+ bool isOrderedList() const;
+ bool isDescriptionList() const;
+
+ virtual AccessibilityRole roleValue() const { return ListRole; }
+private:
+ virtual bool computeAccessibilityIsIgnored() const;
+};
+
+} // namespace WebCore
+
+#endif // AXList_h
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AXListBox.cpp b/chromium/third_party/WebKit/Source/core/accessibility/AXListBox.cpp
new file mode 100644
index 00000000000..444c3047fe0
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/accessibility/AXListBox.cpp
@@ -0,0 +1,169 @@
+/*
+ * Copyright (C) 2008 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/accessibility/AXListBox.h"
+
+#include "core/accessibility/AXListBoxOption.h"
+#include "core/accessibility/AXObjectCache.h"
+#include "core/html/HTMLSelectElement.h"
+#include "core/rendering/RenderListBox.h"
+
+using namespace std;
+
+namespace WebCore {
+
+using namespace HTMLNames;
+
+AXListBox::AXListBox(RenderObject* renderer)
+ : AXRenderObject(renderer)
+{
+}
+
+AXListBox::~AXListBox()
+{
+}
+
+PassRefPtr<AXListBox> AXListBox::create(RenderObject* renderer)
+{
+ return adoptRef(new AXListBox(renderer));
+}
+
+bool AXListBox::canSetSelectedChildrenAttribute() const
+{
+ Node* selectNode = m_renderer->node();
+ if (!selectNode)
+ return false;
+
+ return !toHTMLSelectElement(selectNode)->isDisabledFormControl();
+}
+
+void AXListBox::addChildren()
+{
+ Node* selectNode = m_renderer->node();
+ if (!selectNode)
+ return;
+
+ m_haveChildren = true;
+
+ const Vector<HTMLElement*>& listItems = toHTMLSelectElement(selectNode)->listItems();
+ unsigned length = listItems.size();
+ for (unsigned i = 0; i < length; i++) {
+ // The cast to HTMLElement below is safe because the only other possible listItem type
+ // would be a WMLElement, but WML builds don't use accessibility features at all.
+ AXObject* listOption = listBoxOptionAXObject(listItems[i]);
+ if (listOption && !listOption->accessibilityIsIgnored())
+ m_children.append(listOption);
+ }
+}
+
+void AXListBox::setSelectedChildren(AccessibilityChildrenVector& children)
+{
+ if (!canSetSelectedChildrenAttribute())
+ return;
+
+ Node* selectNode = m_renderer->node();
+ if (!selectNode)
+ return;
+
+ // disable any selected options
+ unsigned length = m_children.size();
+ for (unsigned i = 0; i < length; i++) {
+ AXListBoxOption* listBoxOption = toAXListBoxOption(m_children[i].get());
+ if (listBoxOption->isSelected())
+ listBoxOption->setSelected(false);
+ }
+
+ length = children.size();
+ for (unsigned i = 0; i < length; i++) {
+ AXObject* obj = children[i].get();
+ if (obj->roleValue() != ListBoxOptionRole)
+ continue;
+
+ toAXListBoxOption(obj)->setSelected(true);
+ }
+}
+
+void AXListBox::selectedChildren(AccessibilityChildrenVector& result)
+{
+ ASSERT(result.isEmpty());
+
+ if (!hasChildren())
+ addChildren();
+
+ unsigned length = m_children.size();
+ for (unsigned i = 0; i < length; i++) {
+ if (toAXListBoxOption(m_children[i].get())->isSelected())
+ result.append(m_children[i]);
+ }
+}
+
+AXObject* AXListBox::listBoxOptionAXObject(HTMLElement* element) const
+{
+ // skip hr elements
+ if (!element || element->hasTagName(hrTag))
+ return 0;
+
+ AXObject* listBoxObject = m_renderer->document().axObjectCache()->getOrCreate(ListBoxOptionRole);
+ toAXListBoxOption(listBoxObject)->setHTMLElement(element);
+
+ return listBoxObject;
+}
+
+AXObject* AXListBox::elementAccessibilityHitTest(const IntPoint& point) const
+{
+ // the internal HTMLSelectElement methods for returning a listbox option at a point
+ // ignore optgroup elements.
+ if (!m_renderer)
+ return 0;
+
+ Node* node = m_renderer->node();
+ if (!node)
+ return 0;
+
+ LayoutRect parentRect = elementRect();
+
+ AXObject* listBoxOption = 0;
+ unsigned length = m_children.size();
+ for (unsigned i = 0; i < length; i++) {
+ LayoutRect rect = toRenderListBox(m_renderer)->itemBoundingBoxRect(parentRect.location(), i);
+ // The cast to HTMLElement below is safe because the only other possible listItem type
+ // would be a WMLElement, but WML builds don't use accessibility features at all.
+ if (rect.contains(point)) {
+ listBoxOption = m_children[i].get();
+ break;
+ }
+ }
+
+ if (listBoxOption && !listBoxOption->accessibilityIsIgnored())
+ return listBoxOption;
+
+ return axObjectCache()->getOrCreate(m_renderer);
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AXListBox.h b/chromium/third_party/WebKit/Source/core/accessibility/AXListBox.h
new file mode 100644
index 00000000000..6d46e0e8de0
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/accessibility/AXListBox.h
@@ -0,0 +1,59 @@
+/*
+ * Copyright (C) 2008 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef AXListBox_h
+#define AXListBox_h
+
+#include "core/accessibility/AXRenderObject.h"
+
+namespace WebCore {
+
+class AXListBox : public AXRenderObject {
+
+private:
+ explicit AXListBox(RenderObject*);
+public:
+ static PassRefPtr<AXListBox> create(RenderObject*);
+ virtual ~AXListBox();
+
+ virtual bool canSetSelectedChildrenAttribute() const OVERRIDE;
+ void setSelectedChildren(AccessibilityChildrenVector&);
+ virtual AccessibilityRole roleValue() const OVERRIDE { return ListBoxRole; }
+
+ virtual void selectedChildren(AccessibilityChildrenVector&) OVERRIDE;
+
+ virtual void addChildren() OVERRIDE;
+
+private:
+ AXObject* listBoxOptionAXObject(HTMLElement*) const;
+ virtual AXObject* elementAccessibilityHitTest(const IntPoint&) const OVERRIDE;
+};
+
+} // namespace WebCore
+
+#endif // AXListBox_h
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AXListBoxOption.cpp b/chromium/third_party/WebKit/Source/core/accessibility/AXListBoxOption.cpp
new file mode 100644
index 00000000000..31eb9d10c45
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/accessibility/AXListBoxOption.cpp
@@ -0,0 +1,229 @@
+/*
+ * Copyright (C) 2008 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/accessibility/AXListBoxOption.h"
+
+#include "core/accessibility/AXObjectCache.h"
+#include "core/html/HTMLOptGroupElement.h"
+#include "core/html/HTMLOptionElement.h"
+#include "core/html/HTMLSelectElement.h"
+#include "core/rendering/RenderListBox.h"
+
+using namespace std;
+
+namespace WebCore {
+
+using namespace HTMLNames;
+
+AXListBoxOption::AXListBoxOption()
+ : m_optionElement(0)
+{
+}
+
+AXListBoxOption::~AXListBoxOption()
+{
+}
+
+PassRefPtr<AXListBoxOption> AXListBoxOption::create()
+{
+ return adoptRef(new AXListBoxOption());
+}
+
+bool AXListBoxOption::isEnabled() const
+{
+ if (!m_optionElement)
+ return false;
+
+ if (isHTMLOptGroupElement(m_optionElement))
+ return false;
+
+ if (equalIgnoringCase(getAttribute(aria_disabledAttr), "true"))
+ return false;
+
+ if (m_optionElement->hasAttribute(disabledAttr))
+ return false;
+
+ return true;
+}
+
+bool AXListBoxOption::isSelected() const
+{
+ if (!m_optionElement)
+ return false;
+
+ if (!m_optionElement->hasTagName(optionTag))
+ return false;
+
+ return toHTMLOptionElement(m_optionElement)->selected();
+}
+
+bool AXListBoxOption::isSelectedOptionActive() const
+{
+ HTMLSelectElement* listBoxParentNode = listBoxOptionParentNode();
+ if (!listBoxParentNode)
+ return false;
+
+ return listBoxParentNode->activeSelectionEndListIndex() == listBoxOptionIndex();
+}
+
+LayoutRect AXListBoxOption::elementRect() const
+{
+ LayoutRect rect;
+ if (!m_optionElement)
+ return rect;
+
+ HTMLSelectElement* listBoxParentNode = listBoxOptionParentNode();
+ if (!listBoxParentNode)
+ return rect;
+
+ RenderObject* listBoxRenderer = listBoxParentNode->renderer();
+ if (!listBoxRenderer)
+ return rect;
+
+ LayoutRect parentRect = listBoxRenderer->document().axObjectCache()->getOrCreate(listBoxRenderer)->elementRect();
+ int index = listBoxOptionIndex();
+ if (index != -1)
+ rect = toRenderListBox(listBoxRenderer)->itemBoundingBoxRect(parentRect.location(), index);
+
+ return rect;
+}
+
+bool AXListBoxOption::computeAccessibilityIsIgnored() const
+{
+ if (!m_optionElement)
+ return true;
+
+ if (accessibilityIsIgnoredByDefault())
+ return true;
+
+ return parentObject()->accessibilityIsIgnored();
+}
+
+bool AXListBoxOption::canSetSelectedAttribute() const
+{
+ if (!m_optionElement)
+ return false;
+
+ if (!m_optionElement->hasTagName(optionTag))
+ return false;
+
+ if (m_optionElement->isDisabledFormControl())
+ return false;
+
+ HTMLSelectElement* selectElement = listBoxOptionParentNode();
+ if (selectElement && selectElement->isDisabledFormControl())
+ return false;
+
+ return true;
+}
+
+String AXListBoxOption::stringValue() const
+{
+ if (!m_optionElement)
+ return String();
+
+ const AtomicString& ariaLabel = getAttribute(aria_labelAttr);
+ if (!ariaLabel.isNull())
+ return ariaLabel;
+
+ if (m_optionElement->hasTagName(optionTag))
+ return toHTMLOptionElement(m_optionElement)->text();
+
+ if (isHTMLOptGroupElement(m_optionElement))
+ return toHTMLOptGroupElement(m_optionElement)->groupLabelText();
+
+ return String();
+}
+
+Element* AXListBoxOption::actionElement() const
+{
+ return m_optionElement;
+}
+
+AXObject* AXListBoxOption::parentObject() const
+{
+ HTMLSelectElement* parentNode = listBoxOptionParentNode();
+ if (!parentNode)
+ return 0;
+
+ return m_optionElement->document().axObjectCache()->getOrCreate(parentNode);
+}
+
+void AXListBoxOption::setSelected(bool selected)
+{
+ HTMLSelectElement* selectElement = listBoxOptionParentNode();
+ if (!selectElement)
+ return;
+
+ if (!canSetSelectedAttribute())
+ return;
+
+ bool isOptionSelected = isSelected();
+ if ((isOptionSelected && selected) || (!isOptionSelected && !selected))
+ return;
+
+ // Convert from the entire list index to the option index.
+ int optionIndex = selectElement->listToOptionIndex(listBoxOptionIndex());
+ selectElement->accessKeySetSelectedIndex(optionIndex);
+}
+
+HTMLSelectElement* AXListBoxOption::listBoxOptionParentNode() const
+{
+ if (!m_optionElement)
+ return 0;
+
+ if (m_optionElement->hasTagName(optionTag))
+ return toHTMLOptionElement(m_optionElement)->ownerSelectElement();
+
+ if (isHTMLOptGroupElement(m_optionElement))
+ return toHTMLOptGroupElement(m_optionElement)->ownerSelectElement();
+
+ return 0;
+}
+
+int AXListBoxOption::listBoxOptionIndex() const
+{
+ if (!m_optionElement)
+ return -1;
+
+ HTMLSelectElement* selectElement = listBoxOptionParentNode();
+ if (!selectElement)
+ return -1;
+
+ const Vector<HTMLElement*>& listItems = selectElement->listItems();
+ unsigned length = listItems.size();
+ for (unsigned i = 0; i < length; i++) {
+ if (listItems[i] == m_optionElement)
+ return i;
+ }
+
+ return -1;
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AXListBoxOption.h b/chromium/third_party/WebKit/Source/core/accessibility/AXListBoxOption.h
new file mode 100644
index 00000000000..02e04330ebc
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/accessibility/AXListBoxOption.h
@@ -0,0 +1,82 @@
+/*
+ * Copyright (C) 2008 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef AXListBoxOption_h
+#define AXListBoxOption_h
+
+#include "core/accessibility/AXObject.h"
+#include "core/html/HTMLElement.h"
+#include "wtf/Forward.h"
+
+namespace WebCore {
+
+class AXListBox;
+class Element;
+class HTMLElement;
+class HTMLSelectElement;
+
+class AXListBoxOption : public AXObject {
+
+private:
+ AXListBoxOption();
+public:
+ static PassRefPtr<AXListBoxOption> create();
+ virtual ~AXListBoxOption();
+
+ void setHTMLElement(HTMLElement* element) { m_optionElement = element; }
+
+ virtual AccessibilityRole roleValue() const OVERRIDE { return ListBoxOptionRole; }
+ virtual bool isSelected() const OVERRIDE;
+ virtual bool isEnabled() const OVERRIDE;
+ virtual bool isSelectedOptionActive() const OVERRIDE;
+ virtual String stringValue() const OVERRIDE;
+ virtual Element* actionElement() const OVERRIDE;
+ virtual Node* node() const OVERRIDE { return m_optionElement; }
+ virtual void setSelected(bool) OVERRIDE;
+ virtual bool canSetSelectedAttribute() const OVERRIDE;
+
+ virtual LayoutRect elementRect() const OVERRIDE;
+ virtual AXObject* parentObject() const OVERRIDE;
+
+private:
+ HTMLElement* m_optionElement;
+
+ virtual bool isListBoxOption() const OVERRIDE { return true; }
+ virtual bool canHaveChildren() const OVERRIDE { return false; }
+ virtual bool computeAccessibilityIsIgnored() const OVERRIDE;
+
+ HTMLSelectElement* listBoxOptionParentNode() const;
+ int listBoxOptionIndex() const;
+ AXObject* listBoxOptionAXObject(HTMLElement*) const;
+};
+
+DEFINE_AX_OBJECT_TYPE_CASTS(AXListBoxOption, isListBoxOption());
+
+} // namespace WebCore
+
+#endif // AXListBoxOption_h
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AXMediaControls.cpp b/chromium/third_party/WebKit/Source/core/accessibility/AXMediaControls.cpp
new file mode 100644
index 00000000000..5f426306750
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/accessibility/AXMediaControls.cpp
@@ -0,0 +1,335 @@
+/*
+ * Copyright (C) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+
+#include "config.h"
+#include "core/accessibility/AXMediaControls.h"
+
+#include "platform/text/PlatformLocale.h"
+
+namespace WebCore {
+
+using blink::WebLocalizedString;
+using namespace HTMLNames;
+
+
+static inline String queryString(WebLocalizedString::Name name)
+{
+ return Locale::defaultLocale().queryString(name);
+}
+
+AccessibilityMediaControl::AccessibilityMediaControl(RenderObject* renderer)
+ : AXRenderObject(renderer)
+{
+}
+
+PassRefPtr<AXObject> AccessibilityMediaControl::create(RenderObject* renderer)
+{
+ ASSERT(renderer->node());
+
+ switch (mediaControlElementType(renderer->node())) {
+ case MediaSlider:
+ return AccessibilityMediaTimeline::create(renderer);
+
+ case MediaCurrentTimeDisplay:
+ case MediaTimeRemainingDisplay:
+ return AccessibilityMediaTimeDisplay::create(renderer);
+
+ case MediaControlsPanel:
+ return AXMediaControlsContainer::create(renderer);
+
+ default:
+ return adoptRef(new AccessibilityMediaControl(renderer));
+ }
+}
+
+MediaControlElementType AccessibilityMediaControl::controlType() const
+{
+ if (!renderer() || !renderer()->node())
+ return MediaTimelineContainer; // Timeline container is not accessible.
+
+ return mediaControlElementType(renderer()->node());
+}
+
+void AccessibilityMediaControl::accessibilityText(Vector<AccessibilityText>& textOrder)
+{
+ String description = accessibilityDescription();
+ if (!description.isEmpty())
+ textOrder.append(AccessibilityText(description, AlternativeText));
+
+ String title = this->title();
+ if (!title.isEmpty())
+ textOrder.append(AccessibilityText(title, AlternativeText));
+
+ String helptext = helpText();
+ if (!helptext.isEmpty())
+ textOrder.append(AccessibilityText(helptext, HelpText));
+}
+
+
+String AccessibilityMediaControl::title() const
+{
+ // FIXME: the ControlsPanel container should never be visible in the
+ // accessibility hierarchy.
+ if (controlType() == MediaControlsPanel)
+ return queryString(WebLocalizedString::AXMediaDefault);
+
+ return AXRenderObject::title();
+}
+
+String AccessibilityMediaControl::accessibilityDescription() const
+{
+ switch (controlType()) {
+ case MediaEnterFullscreenButton:
+ return queryString(WebLocalizedString::AXMediaEnterFullscreenButton);
+ case MediaExitFullscreenButton:
+ return queryString(WebLocalizedString::AXMediaExitFullscreenButton);
+ case MediaMuteButton:
+ return queryString(WebLocalizedString::AXMediaMuteButton);
+ case MediaPlayButton:
+ return queryString(WebLocalizedString::AXMediaPlayButton);
+ case MediaSeekBackButton:
+ return queryString(WebLocalizedString::AXMediaSeekBackButton);
+ case MediaSeekForwardButton:
+ return queryString(WebLocalizedString::AXMediaSeekForwardButton);
+ case MediaRewindButton:
+ return queryString(WebLocalizedString::AXMediaRewindButton);
+ case MediaReturnToRealtimeButton:
+ return queryString(WebLocalizedString::AXMediaReturnToRealTime);
+ case MediaUnMuteButton:
+ return queryString(WebLocalizedString::AXMediaUnMuteButton);
+ case MediaPauseButton:
+ return queryString(WebLocalizedString::AXMediaPauseButton);
+ case MediaStatusDisplay:
+ return queryString(WebLocalizedString::AXMediaStatusDisplay);
+ case MediaCurrentTimeDisplay:
+ return queryString(WebLocalizedString::AXMediaCurrentTimeDisplay);
+ case MediaTimeRemainingDisplay:
+ return queryString(WebLocalizedString::AXMediaTimeRemainingDisplay);
+ case MediaShowClosedCaptionsButton:
+ return queryString(WebLocalizedString::AXMediaShowClosedCaptionsButton);
+ case MediaHideClosedCaptionsButton:
+ return queryString(WebLocalizedString::AXMediaHideClosedCaptionsButton);
+ default:
+ return queryString(WebLocalizedString::AXMediaDefault);
+ }
+}
+
+String AccessibilityMediaControl::helpText() const
+{
+ switch (controlType()) {
+ case MediaEnterFullscreenButton:
+ return queryString(WebLocalizedString::AXMediaEnterFullscreenButtonHelp);
+ case MediaExitFullscreenButton:
+ return queryString(WebLocalizedString::AXMediaExitFullscreenButtonHelp);
+ case MediaMuteButton:
+ return queryString(WebLocalizedString::AXMediaMuteButtonHelp);
+ case MediaPlayButton:
+ return queryString(WebLocalizedString::AXMediaPlayButtonHelp);
+ case MediaSeekBackButton:
+ return queryString(WebLocalizedString::AXMediaSeekBackButtonHelp);
+ case MediaSeekForwardButton:
+ return queryString(WebLocalizedString::AXMediaSeekForwardButtonHelp);
+ case MediaRewindButton:
+ return queryString(WebLocalizedString::AXMediaRewindButtonHelp);
+ case MediaReturnToRealtimeButton:
+ return queryString(WebLocalizedString::AXMediaReturnToRealTimeHelp);
+ case MediaUnMuteButton:
+ return queryString(WebLocalizedString::AXMediaUnMuteButtonHelp);
+ case MediaPauseButton:
+ return queryString(WebLocalizedString::AXMediaPauseButtonHelp);
+ case MediaStatusDisplay:
+ return queryString(WebLocalizedString::AXMediaStatusDisplayHelp);
+ case MediaCurrentTimeDisplay:
+ return queryString(WebLocalizedString::AXMediaCurrentTimeDisplayHelp);
+ case MediaTimeRemainingDisplay:
+ return queryString(WebLocalizedString::AXMediaTimeRemainingDisplayHelp);
+ case MediaShowClosedCaptionsButton:
+ return queryString(WebLocalizedString::AXMediaShowClosedCaptionsButtonHelp);
+ case MediaHideClosedCaptionsButton:
+ return queryString(WebLocalizedString::AXMediaHideClosedCaptionsButtonHelp);
+ default:
+ return queryString(WebLocalizedString::AXMediaDefault);
+ }
+}
+
+bool AccessibilityMediaControl::computeAccessibilityIsIgnored() const
+{
+ if (!m_renderer || !m_renderer->style() || m_renderer->style()->visibility() != VISIBLE || controlType() == MediaTimelineContainer)
+ return true;
+
+ return accessibilityIsIgnoredByDefault();
+}
+
+AccessibilityRole AccessibilityMediaControl::roleValue() const
+{
+ switch (controlType()) {
+ case MediaEnterFullscreenButton:
+ case MediaExitFullscreenButton:
+ case MediaMuteButton:
+ case MediaPlayButton:
+ case MediaSeekBackButton:
+ case MediaSeekForwardButton:
+ case MediaRewindButton:
+ case MediaReturnToRealtimeButton:
+ case MediaUnMuteButton:
+ case MediaPauseButton:
+ case MediaShowClosedCaptionsButton:
+ case MediaHideClosedCaptionsButton:
+ return ButtonRole;
+
+ case MediaStatusDisplay:
+ return StaticTextRole;
+
+ case MediaTimelineContainer:
+ return GroupRole;
+
+ default:
+ break;
+ }
+
+ return UnknownRole;
+}
+
+
+
+//
+// AXMediaControlsContainer
+
+AXMediaControlsContainer::AXMediaControlsContainer(RenderObject* renderer)
+ : AccessibilityMediaControl(renderer)
+{
+}
+
+PassRefPtr<AXObject> AXMediaControlsContainer::create(RenderObject* renderer)
+{
+ return adoptRef(new AXMediaControlsContainer(renderer));
+}
+
+String AXMediaControlsContainer::accessibilityDescription() const
+{
+ return queryString(controllingVideoElement() ? WebLocalizedString::AXMediaVideoElement : WebLocalizedString::AXMediaAudioElement);
+}
+
+String AXMediaControlsContainer::helpText() const
+{
+ return queryString(controllingVideoElement() ? WebLocalizedString::AXMediaVideoElementHelp : WebLocalizedString::AXMediaAudioElementHelp);
+}
+
+bool AXMediaControlsContainer::controllingVideoElement() const
+{
+ if (!m_renderer->node())
+ return true;
+
+ MediaControlTimeDisplayElement* element = static_cast<MediaControlTimeDisplayElement*>(m_renderer->node());
+
+ return toParentMediaElement(element)->isVideo();
+}
+
+bool AXMediaControlsContainer::computeAccessibilityIsIgnored() const
+{
+ return accessibilityIsIgnoredByDefault();
+}
+
+//
+// AccessibilityMediaTimeline
+
+static String localizedMediaTimeDescription(float /*time*/)
+{
+ // FIXME: To be fixed. See
+ // http://trac.webkit.org/browser/trunk/Source/WebCore/platform/LocalizedStrings.cpp#L928
+ return String();
+}
+
+AccessibilityMediaTimeline::AccessibilityMediaTimeline(RenderObject* renderer)
+ : AXSlider(renderer)
+{
+}
+
+PassRefPtr<AXObject> AccessibilityMediaTimeline::create(RenderObject* renderer)
+{
+ return adoptRef(new AccessibilityMediaTimeline(renderer));
+}
+
+String AccessibilityMediaTimeline::valueDescription() const
+{
+ Node* node = m_renderer->node();
+ if (!node->hasTagName(inputTag))
+ return String();
+
+ return localizedMediaTimeDescription(toHTMLInputElement(node)->value().toFloat());
+}
+
+String AccessibilityMediaTimeline::helpText() const
+{
+ return queryString(WebLocalizedString::AXMediaSliderHelp);
+}
+
+
+//
+// AccessibilityMediaTimeDisplay
+
+AccessibilityMediaTimeDisplay::AccessibilityMediaTimeDisplay(RenderObject* renderer)
+ : AccessibilityMediaControl(renderer)
+{
+}
+
+PassRefPtr<AXObject> AccessibilityMediaTimeDisplay::create(RenderObject* renderer)
+{
+ return adoptRef(new AccessibilityMediaTimeDisplay(renderer));
+}
+
+bool AccessibilityMediaTimeDisplay::computeAccessibilityIsIgnored() const
+{
+ if (!m_renderer || !m_renderer->style() || m_renderer->style()->visibility() != VISIBLE)
+ return true;
+
+ if (!m_renderer->style()->width().value())
+ return true;
+
+ return accessibilityIsIgnoredByDefault();
+}
+
+String AccessibilityMediaTimeDisplay::accessibilityDescription() const
+{
+ if (controlType() == MediaCurrentTimeDisplay)
+ return queryString(WebLocalizedString::AXMediaCurrentTimeDisplay);
+ return queryString(WebLocalizedString::AXMediaTimeRemainingDisplay);
+}
+
+String AccessibilityMediaTimeDisplay::stringValue() const
+{
+ if (!m_renderer || !m_renderer->node())
+ return String();
+
+ MediaControlTimeDisplayElement* element = static_cast<MediaControlTimeDisplayElement*>(m_renderer->node());
+ float time = element->currentValue();
+ return localizedMediaTimeDescription(fabsf(time));
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AXMediaControls.h b/chromium/third_party/WebKit/Source/core/accessibility/AXMediaControls.h
new file mode 100644
index 00000000000..cbf6a2f5662
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/accessibility/AXMediaControls.h
@@ -0,0 +1,110 @@
+/*
+ * Copyright (C) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+
+#ifndef AXMediaControls_h
+#define AXMediaControls_h
+
+#include "core/accessibility/AXSlider.h"
+#include "core/html/shadow/MediaControlElements.h"
+
+namespace WebCore {
+
+class AccessibilityMediaControl : public AXRenderObject {
+
+public:
+ static PassRefPtr<AXObject> create(RenderObject*);
+ virtual ~AccessibilityMediaControl() { }
+
+ virtual AccessibilityRole roleValue() const OVERRIDE;
+
+ virtual String title() const OVERRIDE;
+ virtual String accessibilityDescription() const OVERRIDE;
+ virtual String helpText() const OVERRIDE;
+
+protected:
+ explicit AccessibilityMediaControl(RenderObject*);
+ MediaControlElementType controlType() const;
+ virtual void accessibilityText(Vector<AccessibilityText>&) OVERRIDE;
+ virtual bool computeAccessibilityIsIgnored() const OVERRIDE;
+};
+
+
+class AccessibilityMediaTimeline : public AXSlider {
+
+public:
+ static PassRefPtr<AXObject> create(RenderObject*);
+ virtual ~AccessibilityMediaTimeline() { }
+
+ virtual String helpText() const OVERRIDE;
+ virtual String valueDescription() const OVERRIDE;
+ const AtomicString& getAttribute(const QualifiedName& attribute) const;
+
+private:
+ explicit AccessibilityMediaTimeline(RenderObject*);
+};
+
+
+class AXMediaControlsContainer : public AccessibilityMediaControl {
+
+public:
+ static PassRefPtr<AXObject> create(RenderObject*);
+ virtual ~AXMediaControlsContainer() { }
+
+ virtual AccessibilityRole roleValue() const OVERRIDE { return ToolbarRole; }
+
+ virtual String helpText() const OVERRIDE;
+ virtual String accessibilityDescription() const OVERRIDE;
+
+private:
+ explicit AXMediaControlsContainer(RenderObject*);
+ bool controllingVideoElement() const;
+ virtual bool computeAccessibilityIsIgnored() const OVERRIDE;
+};
+
+
+class AccessibilityMediaTimeDisplay : public AccessibilityMediaControl {
+
+public:
+ static PassRefPtr<AXObject> create(RenderObject*);
+ virtual ~AccessibilityMediaTimeDisplay() { }
+
+ virtual AccessibilityRole roleValue() const OVERRIDE { return StaticTextRole; }
+
+ virtual String stringValue() const OVERRIDE;
+ virtual String accessibilityDescription() const OVERRIDE;
+
+private:
+ explicit AccessibilityMediaTimeDisplay(RenderObject*);
+ virtual bool computeAccessibilityIsIgnored() const OVERRIDE;
+};
+
+
+} // namespace WebCore
+
+#endif // AXMediaControls_h
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AXMenuList.cpp b/chromium/third_party/WebKit/Source/core/accessibility/AXMenuList.cpp
new file mode 100644
index 00000000000..990d6c84601
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/accessibility/AXMenuList.cpp
@@ -0,0 +1,117 @@
+/*
+ * Copyright (C) 2010 Apple Inc. All Rights Reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/accessibility/AXMenuList.h"
+
+#include "core/accessibility/AXMenuListPopup.h"
+#include "core/accessibility/AXObjectCache.h"
+#include "core/rendering/RenderMenuList.h"
+
+namespace WebCore {
+
+AXMenuList::AXMenuList(RenderMenuList* renderer)
+ : AXRenderObject(renderer)
+{
+}
+
+PassRefPtr<AXMenuList> AXMenuList::create(RenderMenuList* renderer)
+{
+ return adoptRef(new AXMenuList(renderer));
+}
+
+bool AXMenuList::press() const
+{
+ RenderMenuList* menuList = toRenderMenuList(m_renderer);
+ if (menuList->popupIsVisible())
+ menuList->hidePopup();
+ else
+ menuList->showPopup();
+ return true;
+}
+
+void AXMenuList::addChildren()
+{
+ m_haveChildren = true;
+
+ AXObjectCache* cache = m_renderer->document().axObjectCache();
+
+ AXObject* list = cache->getOrCreate(MenuListPopupRole);
+ if (!list)
+ return;
+
+ toAXMockObject(list)->setParent(this);
+ if (list->accessibilityIsIgnored()) {
+ cache->remove(list->axObjectID());
+ return;
+ }
+
+ m_children.append(list);
+
+ list->addChildren();
+}
+
+void AXMenuList::childrenChanged()
+{
+ if (m_children.isEmpty())
+ return;
+
+ ASSERT(m_children.size() == 1);
+ m_children[0]->childrenChanged();
+}
+
+bool AXMenuList::isCollapsed() const
+{
+ return !toRenderMenuList(m_renderer)->popupIsVisible();
+}
+
+bool AXMenuList::canSetFocusAttribute() const
+{
+ if (!node())
+ return false;
+
+ return !toElement(node())->isDisabledFormControl();
+}
+
+void AXMenuList::didUpdateActiveOption(int optionIndex)
+{
+ RefPtr<Document> document(m_renderer->document());
+ AXObjectCache* cache = document->axObjectCache();
+
+ const AccessibilityChildrenVector& childObjects = children();
+ if (!childObjects.isEmpty()) {
+ ASSERT(childObjects.size() == 1);
+ ASSERT(childObjects[0]->isMenuListPopup());
+
+ if (childObjects[0]->isMenuListPopup()) {
+ if (AXMenuListPopup* popup = toAXMenuListPopup(childObjects[0].get()))
+ popup->didUpdateActiveOption(optionIndex);
+ }
+ }
+
+ cache->postNotification(this, document.get(), AXObjectCache::AXMenuListValueChanged, true, PostSynchronously);
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AXMenuList.h b/chromium/third_party/WebKit/Source/core/accessibility/AXMenuList.h
new file mode 100644
index 00000000000..b7e3be0863f
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/accessibility/AXMenuList.h
@@ -0,0 +1,62 @@
+/*
+ * Copyright (C) 2010 Apple Inc. All Rights Reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef AXMenuList_h
+#define AXMenuList_h
+
+#include "core/accessibility/AXRenderObject.h"
+
+namespace WebCore {
+
+class AXMenuList;
+class AXMenuListPopup;
+class HTMLOptionElement;
+class RenderMenuList;
+
+class AXMenuList : public AXRenderObject {
+public:
+ static PassRefPtr<AXMenuList> create(RenderMenuList* renderer);
+
+ virtual bool isCollapsed() const OVERRIDE;
+ virtual bool press() const OVERRIDE;
+
+ void didUpdateActiveOption(int optionIndex);
+
+private:
+ explicit AXMenuList(RenderMenuList*);
+
+ virtual bool isMenuList() const OVERRIDE { return true; }
+ virtual AccessibilityRole roleValue() const OVERRIDE { return PopUpButtonRole; }
+ virtual bool canSetFocusAttribute() const OVERRIDE;
+
+ virtual void addChildren() OVERRIDE;
+ virtual void childrenChanged() OVERRIDE;
+};
+
+DEFINE_AX_OBJECT_TYPE_CASTS(AXMenuList, isMenuList());
+
+} // namespace WebCore
+
+#endif // AXMenuList_h
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AXMenuListOption.cpp b/chromium/third_party/WebKit/Source/core/accessibility/AXMenuListOption.cpp
new file mode 100644
index 00000000000..7dc61b759b4
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/accessibility/AXMenuListOption.cpp
@@ -0,0 +1,112 @@
+/*
+ * Copyright (C) 2010 Apple Inc. All Rights Reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/accessibility/AXMenuListOption.h"
+
+#include "core/html/HTMLOptionElement.h"
+
+namespace WebCore {
+
+using namespace HTMLNames;
+
+AXMenuListOption::AXMenuListOption()
+{
+}
+
+void AXMenuListOption::setElement(HTMLElement* element)
+{
+ ASSERT_ARG(element, element->hasTagName(optionTag));
+ m_element = element;
+}
+
+Element* AXMenuListOption::actionElement() const
+{
+ return m_element.get();
+}
+
+bool AXMenuListOption::isEnabled() const
+{
+ // isDisabledFormControl() returns true if the parent <select> element is disabled,
+ // which we don't want.
+ return !toHTMLOptionElement(m_element)->ownElementDisabled();
+}
+
+bool AXMenuListOption::isVisible() const
+{
+ if (!m_parent)
+ return false;
+
+ // In a single-option select with the popup collapsed, only the selected
+ // item is considered visible.
+ return !m_parent->isOffScreen() || isSelected();
+}
+
+bool AXMenuListOption::isOffScreen() const
+{
+ // Invisible list options are considered to be offscreen.
+ return !isVisible();
+}
+
+bool AXMenuListOption::isSelected() const
+{
+ return toHTMLOptionElement(m_element)->selected();
+}
+
+void AXMenuListOption::setSelected(bool b)
+{
+ if (!canSetSelectedAttribute())
+ return;
+
+ toHTMLOptionElement(m_element)->setSelected(b);
+}
+
+bool AXMenuListOption::canSetSelectedAttribute() const
+{
+ return isEnabled();
+}
+
+bool AXMenuListOption::computeAccessibilityIsIgnored() const
+{
+ return accessibilityIsIgnoredByDefault();
+}
+
+LayoutRect AXMenuListOption::elementRect() const
+{
+ AXObject* parent = parentObject();
+ ASSERT(parent->isMenuListPopup());
+
+ AXObject* grandparent = parent->parentObject();
+ ASSERT(grandparent->isMenuList());
+
+ return grandparent->elementRect();
+}
+
+String AXMenuListOption::stringValue() const
+{
+ return toHTMLOptionElement(m_element)->text();
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AXMenuListOption.h b/chromium/third_party/WebKit/Source/core/accessibility/AXMenuListOption.h
new file mode 100644
index 00000000000..8c20d8d3067
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/accessibility/AXMenuListOption.h
@@ -0,0 +1,68 @@
+/*
+ * Copyright (C) 2010 Apple Inc. All Rights Reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef AXMenuListOption_h
+#define AXMenuListOption_h
+
+#include "core/accessibility/AXMockObject.h"
+
+namespace WebCore {
+
+class AXMenuListPopup;
+class HTMLElement;
+
+class AXMenuListOption : public AXMockObject {
+public:
+ static PassRefPtr<AXMenuListOption> create() { return adoptRef(new AXMenuListOption); }
+
+ void setElement(HTMLElement*);
+
+private:
+ AXMenuListOption();
+
+ virtual bool isMenuListOption() const OVERRIDE { return true; }
+
+ virtual AccessibilityRole roleValue() const OVERRIDE { return MenuListOptionRole; }
+ virtual bool canHaveChildren() const OVERRIDE { return false; }
+
+ virtual Element* actionElement() const OVERRIDE;
+ virtual bool isEnabled() const OVERRIDE;
+ virtual bool isVisible() const OVERRIDE;
+ virtual bool isOffScreen() const OVERRIDE;
+ virtual bool isSelected() const OVERRIDE;
+ virtual void setSelected(bool) OVERRIDE;
+ virtual bool canSetSelectedAttribute() const OVERRIDE;
+ virtual LayoutRect elementRect() const OVERRIDE;
+ virtual String stringValue() const OVERRIDE;
+ virtual bool computeAccessibilityIsIgnored() const OVERRIDE;
+
+ RefPtr<HTMLElement> m_element;
+};
+
+DEFINE_AX_OBJECT_TYPE_CASTS(AXMenuListOption, isMenuListOption());
+
+} // namespace WebCore
+
+#endif // AXMenuListOption_h
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AXMenuListPopup.cpp b/chromium/third_party/WebKit/Source/core/accessibility/AXMenuListPopup.cpp
new file mode 100644
index 00000000000..145792aa05f
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/accessibility/AXMenuListPopup.cpp
@@ -0,0 +1,146 @@
+/*
+ * Copyright (C) 2010 Apple Inc. All Rights Reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/accessibility/AXMenuListPopup.h"
+
+#include "core/accessibility/AXMenuListOption.h"
+#include "core/accessibility/AXObjectCache.h"
+#include "core/html/HTMLSelectElement.h"
+
+namespace WebCore {
+
+using namespace HTMLNames;
+
+AXMenuListPopup::AXMenuListPopup()
+{
+}
+
+bool AXMenuListPopup::isVisible() const
+{
+ return false;
+}
+
+bool AXMenuListPopup::isOffScreen() const
+{
+ if (!m_parent)
+ return true;
+
+ return m_parent->isCollapsed();
+}
+
+bool AXMenuListPopup::isEnabled() const
+{
+ if (!m_parent)
+ return false;
+
+ return m_parent->isEnabled();
+}
+
+bool AXMenuListPopup::computeAccessibilityIsIgnored() const
+{
+ return accessibilityIsIgnoredByDefault();
+}
+
+AXMenuListOption* AXMenuListPopup::menuListOptionAXObject(HTMLElement* element) const
+{
+ if (!element->hasTagName(optionTag))
+ return 0;
+
+ AXObject* object = document()->axObjectCache()->getOrCreate(MenuListOptionRole);
+ ASSERT_WITH_SECURITY_IMPLICATION(object->isMenuListOption());
+
+ AXMenuListOption* option = toAXMenuListOption(object);
+ option->setElement(element);
+
+ return option;
+}
+
+bool AXMenuListPopup::press() const
+{
+ if (!m_parent)
+ return false;
+
+ m_parent->press();
+ return true;
+}
+
+void AXMenuListPopup::addChildren()
+{
+ if (!m_parent)
+ return;
+
+ Node* selectNode = m_parent->node();
+ if (!selectNode)
+ return;
+
+ m_haveChildren = true;
+
+ const Vector<HTMLElement*>& listItems = toHTMLSelectElement(selectNode)->listItems();
+ unsigned length = listItems.size();
+ for (unsigned i = 0; i < length; i++) {
+ AXMenuListOption* option = menuListOptionAXObject(listItems[i]);
+ if (option) {
+ option->setParent(this);
+ m_children.append(option);
+ }
+ }
+}
+
+void AXMenuListPopup::childrenChanged()
+{
+ AXObjectCache* cache = axObjectCache();
+ for (size_t i = m_children.size(); i > 0 ; --i) {
+ AXObject* child = m_children[i - 1].get();
+ // FIXME: How could children end up in here that have no actionElement(), the check
+ // in menuListOptionAXObject would seem to prevent that.
+ if (child->actionElement()) {
+ child->detachFromParent();
+ cache->remove(child->axObjectID());
+ }
+ }
+
+ m_children.clear();
+ m_haveChildren = false;
+}
+
+void AXMenuListPopup::didUpdateActiveOption(int optionIndex)
+{
+ // We defer creation of the children until updating the active option so that we don't
+ // create AXObjects for <option> elements while they're in the middle of removal.
+ if (!m_haveChildren)
+ addChildren();
+
+ ASSERT_ARG(optionIndex, optionIndex >= 0);
+ ASSERT_ARG(optionIndex, optionIndex < static_cast<int>(m_children.size()));
+
+ AXObjectCache* cache = axObjectCache();
+ RefPtr<AXObject> child = m_children[optionIndex].get();
+
+ cache->postNotification(child.get(), document(), AXObjectCache::AXFocusedUIElementChanged, true, PostSynchronously);
+ cache->postNotification(child.get(), document(), AXObjectCache::AXMenuListItemSelected, true, PostSynchronously);
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AXMenuListPopup.h b/chromium/third_party/WebKit/Source/core/accessibility/AXMenuListPopup.h
new file mode 100644
index 00000000000..44b8917aefa
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/accessibility/AXMenuListPopup.h
@@ -0,0 +1,68 @@
+/*
+ * Copyright (C) 2010 Apple Inc. All Rights Reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef AXMenuListPopup_h
+#define AXMenuListPopup_h
+
+#include "core/accessibility/AXMockObject.h"
+
+namespace WebCore {
+
+class AXMenuList;
+class AXMenuListOption;
+class HTMLElement;
+class HTMLSelectElement;
+
+class AXMenuListPopup : public AXMockObject {
+public:
+ static PassRefPtr<AXMenuListPopup> create() { return adoptRef(new AXMenuListPopup); }
+
+ virtual bool isEnabled() const OVERRIDE;
+ virtual bool isOffScreen() const OVERRIDE;
+
+ void didUpdateActiveOption(int optionIndex);
+
+private:
+ AXMenuListPopup();
+
+ virtual bool isMenuListPopup() const OVERRIDE { return true; }
+
+ virtual LayoutRect elementRect() const OVERRIDE { return LayoutRect(); }
+ virtual AccessibilityRole roleValue() const OVERRIDE { return MenuListPopupRole; }
+
+ virtual bool isVisible() const OVERRIDE;
+ virtual bool press() const OVERRIDE;
+ virtual void addChildren() OVERRIDE;
+ virtual void childrenChanged() OVERRIDE;
+ virtual bool computeAccessibilityIsIgnored() const OVERRIDE;
+
+ AXMenuListOption* menuListOptionAXObject(HTMLElement*) const;
+};
+
+DEFINE_AX_OBJECT_TYPE_CASTS(AXMenuListPopup, isMenuListPopup());
+
+} // namespace WebCore
+
+#endif // AXMenuListPopup_h
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AXMockObject.cpp b/chromium/third_party/WebKit/Source/core/accessibility/AXMockObject.cpp
new file mode 100644
index 00000000000..1e7de04b4f4
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/accessibility/AXMockObject.cpp
@@ -0,0 +1,45 @@
+/*
+ * Copyright (C) 2011 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/accessibility/AXMockObject.h"
+
+namespace WebCore {
+
+AXMockObject::AXMockObject()
+ : m_parent(0)
+{
+}
+
+AXMockObject::~AXMockObject()
+{
+}
+
+bool AXMockObject::computeAccessibilityIsIgnored() const
+{
+ return accessibilityIsIgnoredByDefault();
+}
+
+}
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AXMockObject.h b/chromium/third_party/WebKit/Source/core/accessibility/AXMockObject.h
new file mode 100644
index 00000000000..edd6179713c
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/accessibility/AXMockObject.h
@@ -0,0 +1,62 @@
+/*
+ * Copyright (C) 2011 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef AXMockObject_h
+#define AXMockObject_h
+
+#include "core/accessibility/AXObject.h"
+
+namespace WebCore {
+
+class AXMockObject : public AXObject {
+
+protected:
+ AXMockObject();
+public:
+ virtual ~AXMockObject();
+
+ virtual void setParent(AXObject* parent) { m_parent = parent; };
+
+ // AXObject overrides.
+ virtual AXObject* parentObject() const OVERRIDE { return m_parent; }
+ virtual bool isEnabled() const OVERRIDE { return true; }
+
+protected:
+ AXObject* m_parent;
+
+ // Must be called when the parent object clears its children.
+ virtual void detachFromParent() OVERRIDE { m_parent = 0; }
+
+private:
+ virtual bool isMockObject() const OVERRIDE { return true; }
+
+ virtual bool computeAccessibilityIsIgnored() const OVERRIDE;
+};
+
+DEFINE_AX_OBJECT_TYPE_CASTS(AXMockObject, isMockObject());
+
+} // namespace WebCore
+
+#endif // AXMockObject_h
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AXNodeObject.cpp b/chromium/third_party/WebKit/Source/core/accessibility/AXNodeObject.cpp
new file mode 100644
index 00000000000..439e7cd4985
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/accessibility/AXNodeObject.cpp
@@ -0,0 +1,1813 @@
+/*
+* Copyright (C) 2012, Google Inc. All rights reserved.
+*
+* Redistribution and use in source and binary forms, with or without
+* modification, are permitted provided that the following conditions
+* are met:
+*
+* 1. Redistributions of source code must retain the above copyright
+* notice, this list of conditions and the following disclaimer.
+* 2. Redistributions in binary form must reproduce the above copyright
+* notice, this list of conditions and the following disclaimer in the
+* documentation and/or other materials provided with the distribution.
+* 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+* its contributors may be used to endorse or promote products derived
+* from this software without specific prior written permission.
+*
+* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+#include "config.h"
+#include "core/accessibility/AXNodeObject.h"
+
+#include "core/accessibility/AXObjectCache.h"
+#include "core/dom/NodeTraversal.h"
+#include "core/dom/Text.h"
+#include "core/html/HTMLAnchorElement.h"
+#include "core/html/HTMLFieldSetElement.h"
+#include "core/html/HTMLFrameElementBase.h"
+#include "core/html/HTMLInputElement.h"
+#include "core/html/HTMLLabelElement.h"
+#include "core/html/HTMLLegendElement.h"
+#include "core/html/HTMLSelectElement.h"
+#include "core/html/HTMLTextAreaElement.h"
+#include "core/rendering/RenderObject.h"
+#include "platform/UserGestureIndicator.h"
+#include "wtf/text/StringBuilder.h"
+
+using namespace std;
+
+namespace WebCore {
+
+using namespace HTMLNames;
+
+AXNodeObject::AXNodeObject(Node* node)
+ : AXObject()
+ , m_ariaRole(UnknownRole)
+ , m_childrenDirty(false)
+#ifndef NDEBUG
+ , m_initialized(false)
+#endif
+ , m_node(node)
+{
+}
+
+PassRefPtr<AXNodeObject> AXNodeObject::create(Node* node)
+{
+ return adoptRef(new AXNodeObject(node));
+}
+
+AXNodeObject::~AXNodeObject()
+{
+ ASSERT(isDetached());
+}
+
+// This function implements the ARIA accessible name as described by the Mozilla
+// ARIA Implementer's Guide.
+static String accessibleNameForNode(Node* node)
+{
+ if (node->isTextNode())
+ return toText(node)->data();
+
+ if (node->hasTagName(inputTag))
+ return toHTMLInputElement(node)->value();
+
+ if (node->isHTMLElement()) {
+ const AtomicString& alt = toHTMLElement(node)->getAttribute(altAttr);
+ if (!alt.isEmpty())
+ return alt;
+ }
+
+ return String();
+}
+
+String AXNodeObject::accessibilityDescriptionForElements(Vector<Element*> &elements) const
+{
+ StringBuilder builder;
+ unsigned size = elements.size();
+ for (unsigned i = 0; i < size; ++i) {
+ Element* idElement = elements[i];
+
+ builder.append(accessibleNameForNode(idElement));
+ for (Node* n = idElement->firstChild(); n; n = NodeTraversal::next(*n, idElement))
+ builder.append(accessibleNameForNode(n));
+
+ if (i != size - 1)
+ builder.append(' ');
+ }
+ return builder.toString();
+}
+
+void AXNodeObject::alterSliderValue(bool increase)
+{
+ if (roleValue() != SliderRole)
+ return;
+
+ if (!getAttribute(stepAttr).isEmpty())
+ changeValueByStep(increase);
+ else
+ changeValueByPercent(increase ? 5 : -5);
+}
+
+String AXNodeObject::ariaAccessibilityDescription() const
+{
+ String ariaLabeledBy = ariaLabeledByAttribute();
+ if (!ariaLabeledBy.isEmpty())
+ return ariaLabeledBy;
+
+ const AtomicString& ariaLabel = getAttribute(aria_labelAttr);
+ if (!ariaLabel.isEmpty())
+ return ariaLabel;
+
+ return String();
+}
+
+
+void AXNodeObject::ariaLabeledByElements(Vector<Element*>& elements) const
+{
+ elementsFromAttribute(elements, aria_labeledbyAttr);
+ if (!elements.size())
+ elementsFromAttribute(elements, aria_labelledbyAttr);
+}
+
+void AXNodeObject::changeValueByStep(bool increase)
+{
+ float step = stepValueForRange();
+ float value = valueForRange();
+
+ value += increase ? step : -step;
+
+ setValue(String::number(value));
+
+ axObjectCache()->postNotification(node(), AXObjectCache::AXValueChanged, true);
+}
+
+bool AXNodeObject::computeAccessibilityIsIgnored() const
+{
+#ifndef NDEBUG
+ // Double-check that an AXObject is never accessed before
+ // it's been initialized.
+ ASSERT(m_initialized);
+#endif
+
+ // If this element is within a parent that cannot have children, it should not be exposed.
+ if (isDescendantOfBarrenParent())
+ return true;
+
+ // Ignore labels that are already referenced by a control's title UI element.
+ AXObject* controlObject = correspondingControlForLabelElement();
+ if (controlObject && !controlObject->exposesTitleUIElement() && controlObject->isCheckboxOrRadio())
+ return true;
+
+ return m_role == UnknownRole;
+}
+
+AccessibilityRole AXNodeObject::determineAccessibilityRole()
+{
+ if (!node())
+ return UnknownRole;
+
+ m_ariaRole = determineAriaRoleAttribute();
+
+ AccessibilityRole ariaRole = ariaRoleAttribute();
+ if (ariaRole != UnknownRole)
+ return ariaRole;
+
+ if (node()->isLink())
+ return LinkRole;
+ if (node()->isTextNode())
+ return StaticTextRole;
+ if (node()->hasTagName(buttonTag))
+ return buttonRoleType();
+ if (node()->hasTagName(inputTag)) {
+ HTMLInputElement* input = toHTMLInputElement(node());
+ if (input->isCheckbox())
+ return CheckBoxRole;
+ if (input->isRadioButton())
+ return RadioButtonRole;
+ if (input->isTextButton())
+ return buttonRoleType();
+ if (input->isRangeControl())
+ return SliderRole;
+
+ const AtomicString& type = input->getAttribute(typeAttr);
+ if (equalIgnoringCase(type, "color"))
+ return ColorWellRole;
+
+ return TextFieldRole;
+ }
+ if (node()->hasTagName(selectTag)) {
+ HTMLSelectElement* selectElement = toHTMLSelectElement(node());
+ return selectElement->multiple() ? ListBoxRole : PopUpButtonRole;
+ }
+ if (isHTMLTextAreaElement(node()))
+ return TextAreaRole;
+ if (headingLevel())
+ return HeadingRole;
+ if (node()->hasTagName(divTag))
+ return DivRole;
+ if (node()->hasTagName(pTag))
+ return ParagraphRole;
+ if (isHTMLLabelElement(node()))
+ return LabelRole;
+ if (node()->isElementNode() && toElement(node())->isFocusable())
+ return GroupRole;
+ if (node()->hasTagName(aTag) && isClickable())
+ return LinkRole;
+
+ return UnknownRole;
+}
+
+AccessibilityRole AXNodeObject::determineAriaRoleAttribute() const
+{
+ const AtomicString& ariaRole = getAttribute(roleAttr);
+ if (ariaRole.isNull() || ariaRole.isEmpty())
+ return UnknownRole;
+
+ AccessibilityRole role = ariaRoleToWebCoreRole(ariaRole);
+
+ // ARIA states if an item can get focus, it should not be presentational.
+ if (role == PresentationalRole && canSetFocusAttribute())
+ return UnknownRole;
+
+ if (role == ButtonRole)
+ role = buttonRoleType();
+
+ if (role == TextAreaRole && !ariaIsMultiline())
+ role = TextFieldRole;
+
+ role = remapAriaRoleDueToParent(role);
+
+ if (role)
+ return role;
+
+ return UnknownRole;
+}
+
+void AXNodeObject::elementsFromAttribute(Vector<Element*>& elements, const QualifiedName& attribute) const
+{
+ Node* node = this->node();
+ if (!node || !node->isElementNode())
+ return;
+
+ TreeScope& scope = node->treeScope();
+
+ String idList = getAttribute(attribute).string();
+ if (idList.isEmpty())
+ return;
+
+ idList.replace('\n', ' ');
+ Vector<String> idVector;
+ idList.split(' ', idVector);
+
+ unsigned size = idVector.size();
+ for (unsigned i = 0; i < size; ++i) {
+ AtomicString idName(idVector[i]);
+ Element* idElement = scope.getElementById(idName);
+ if (idElement)
+ elements.append(idElement);
+ }
+}
+
+// If you call node->rendererIsEditable() since that will return true if an ancestor is editable.
+// This only returns true if this is the element that actually has the contentEditable attribute set.
+bool AXNodeObject::hasContentEditableAttributeSet() const
+{
+ if (!hasAttribute(contenteditableAttr))
+ return false;
+ const AtomicString& contentEditableValue = getAttribute(contenteditableAttr);
+ // Both "true" (case-insensitive) and the empty string count as true.
+ return contentEditableValue.isEmpty() || equalIgnoringCase(contentEditableValue, "true");
+}
+
+bool AXNodeObject::isDescendantOfBarrenParent() const
+{
+ for (AXObject* object = parentObject(); object; object = object->parentObject()) {
+ if (!object->canHaveChildren())
+ return true;
+ }
+
+ return false;
+}
+
+bool AXNodeObject::isGenericFocusableElement() const
+{
+ if (!canSetFocusAttribute())
+ return false;
+
+ // If it's a control, it's not generic.
+ if (isControl())
+ return false;
+
+ // If it has an aria role, it's not generic.
+ if (m_ariaRole != UnknownRole)
+ return false;
+
+ // If the content editable attribute is set on this element, that's the reason
+ // it's focusable, and existing logic should handle this case already - so it's not a
+ // generic focusable element.
+
+ if (hasContentEditableAttributeSet())
+ return false;
+
+ // The web area and body element are both focusable, but existing logic handles these
+ // cases already, so we don't need to include them here.
+ if (roleValue() == WebAreaRole)
+ return false;
+ if (node() && node()->hasTagName(bodyTag))
+ return false;
+
+ // An SVG root is focusable by default, but it's probably not interactive, so don't
+ // include it. It can still be made accessible by giving it an ARIA role.
+ if (roleValue() == SVGRootRole)
+ return false;
+
+ return true;
+}
+
+HTMLLabelElement* AXNodeObject::labelForElement(Element* element) const
+{
+ if (!element->isHTMLElement() || !toHTMLElement(element)->isLabelable())
+ return 0;
+
+ const AtomicString& id = element->getIdAttribute();
+ if (!id.isEmpty()) {
+ if (HTMLLabelElement* label = element->treeScope().labelElementForId(id))
+ return label;
+ }
+
+ for (Element* parent = element->parentElement(); parent; parent = parent->parentElement()) {
+ if (isHTMLLabelElement(parent))
+ return toHTMLLabelElement(parent);
+ }
+
+ return 0;
+}
+
+AXObject* AXNodeObject::menuButtonForMenu() const
+{
+ Element* menuItem = menuItemElementForMenu();
+
+ if (menuItem) {
+ // ARIA just has generic menu items. AppKit needs to know if this is a top level items like MenuBarButton or MenuBarItem
+ AXObject* menuItemAX = axObjectCache()->getOrCreate(menuItem);
+ if (menuItemAX && menuItemAX->isMenuButton())
+ return menuItemAX;
+ }
+ return 0;
+}
+
+static Element* siblingWithAriaRole(String role, Node* node)
+{
+ Node* parent = node->parentNode();
+ if (!parent)
+ return 0;
+
+ for (Node* sibling = parent->firstChild(); sibling; sibling = sibling->nextSibling()) {
+ if (sibling->isElementNode()) {
+ const AtomicString& siblingAriaRole = toElement(sibling)->getAttribute(roleAttr);
+ if (equalIgnoringCase(siblingAriaRole, role))
+ return toElement(sibling);
+ }
+ }
+
+ return 0;
+}
+
+Element* AXNodeObject::menuItemElementForMenu() const
+{
+ if (ariaRoleAttribute() != MenuRole)
+ return 0;
+
+ return siblingWithAriaRole("menuitem", node());
+}
+
+Element* AXNodeObject::mouseButtonListener() const
+{
+ Node* node = this->node();
+ if (!node)
+ return 0;
+
+ // check if our parent is a mouse button listener
+ while (node && !node->isElementNode())
+ node = node->parentNode();
+
+ if (!node)
+ return 0;
+
+ // FIXME: Do the continuation search like anchorElement does
+ for (Element* element = toElement(node); element; element = element->parentElement()) {
+ if (element->getAttributeEventListener(EventTypeNames::click) || element->getAttributeEventListener(EventTypeNames::mousedown) || element->getAttributeEventListener(EventTypeNames::mouseup))
+ return element;
+ }
+
+ return 0;
+}
+
+AccessibilityRole AXNodeObject::remapAriaRoleDueToParent(AccessibilityRole role) const
+{
+ // Some objects change their role based on their parent.
+ // However, asking for the unignoredParent calls accessibilityIsIgnored(), which can trigger a loop.
+ // While inside the call stack of creating an element, we need to avoid accessibilityIsIgnored().
+ // https://bugs.webkit.org/show_bug.cgi?id=65174
+
+ if (role != ListBoxOptionRole && role != MenuItemRole)
+ return role;
+
+ for (AXObject* parent = parentObject(); parent && !parent->accessibilityIsIgnored(); parent = parent->parentObject()) {
+ AccessibilityRole parentAriaRole = parent->ariaRoleAttribute();
+
+ // Selects and listboxes both have options as child roles, but they map to different roles within WebCore.
+ if (role == ListBoxOptionRole && parentAriaRole == MenuRole)
+ return MenuItemRole;
+ // An aria "menuitem" may map to MenuButton or MenuItem depending on its parent.
+ if (role == MenuItemRole && parentAriaRole == GroupRole)
+ return MenuButtonRole;
+
+ // If the parent had a different role, then we don't need to continue searching up the chain.
+ if (parentAriaRole)
+ break;
+ }
+
+ return role;
+}
+
+void AXNodeObject::init()
+{
+#ifndef NDEBUG
+ ASSERT(!m_initialized);
+ m_initialized = true;
+#endif
+ m_role = determineAccessibilityRole();
+}
+
+void AXNodeObject::detach()
+{
+ clearChildren();
+ AXObject::detach();
+ m_node = 0;
+}
+
+bool AXNodeObject::isAnchor() const
+{
+ return !isNativeImage() && isLink();
+}
+
+bool AXNodeObject::isControl() const
+{
+ Node* node = this->node();
+ if (!node)
+ return false;
+
+ return ((node->isElementNode() && toElement(node)->isFormControlElement())
+ || AXObject::isARIAControl(ariaRoleAttribute()));
+}
+
+bool AXNodeObject::isFieldset() const
+{
+ Node* node = this->node();
+ if (!node)
+ return false;
+
+ return node->hasTagName(fieldsetTag);
+}
+
+bool AXNodeObject::isHeading() const
+{
+ return roleValue() == HeadingRole;
+}
+
+bool AXNodeObject::isHovered() const
+{
+ Node* node = this->node();
+ if (!node)
+ return false;
+
+ return node->hovered();
+}
+
+bool AXNodeObject::isImage() const
+{
+ return roleValue() == ImageRole;
+}
+
+bool AXNodeObject::isImageButton() const
+{
+ return isNativeImage() && isButton();
+}
+
+bool AXNodeObject::isInputImage() const
+{
+ Node* node = this->node();
+ if (!node)
+ return false;
+
+ if (roleValue() == ButtonRole && node->hasTagName(inputTag))
+ return toHTMLInputElement(node)->isImageButton();
+
+ return false;
+}
+
+bool AXNodeObject::isLink() const
+{
+ return roleValue() == LinkRole;
+}
+
+bool AXNodeObject::isMenu() const
+{
+ return roleValue() == MenuRole;
+}
+
+bool AXNodeObject::isMenuButton() const
+{
+ return roleValue() == MenuButtonRole;
+}
+
+bool AXNodeObject::isMultiSelectable() const
+{
+ const AtomicString& ariaMultiSelectable = getAttribute(aria_multiselectableAttr);
+ if (equalIgnoringCase(ariaMultiSelectable, "true"))
+ return true;
+ if (equalIgnoringCase(ariaMultiSelectable, "false"))
+ return false;
+
+ return node() && node()->hasTagName(selectTag) && toHTMLSelectElement(node())->multiple();
+}
+
+bool AXNodeObject::isNativeCheckboxOrRadio() const
+{
+ Node* node = this->node();
+ if (!node || !node->hasTagName(inputTag))
+ return false;
+
+ HTMLInputElement* input = toHTMLInputElement(node);
+ return input->isCheckbox() || input->isRadioButton();
+}
+
+bool AXNodeObject::isNativeImage() const
+{
+ Node* node = this->node();
+ if (!node)
+ return false;
+
+ if (node->hasTagName(imgTag))
+ return true;
+
+ if (node->hasTagName(appletTag) || node->hasTagName(embedTag) || node->hasTagName(objectTag))
+ return true;
+
+ if (node->hasTagName(inputTag))
+ return toHTMLInputElement(node)->isImageButton();
+
+ return false;
+}
+
+bool AXNodeObject::isNativeTextControl() const
+{
+ Node* node = this->node();
+ if (!node)
+ return false;
+
+ if (isHTMLTextAreaElement(node))
+ return true;
+
+ if (node->hasTagName(inputTag)) {
+ HTMLInputElement* input = toHTMLInputElement(node);
+ return input->isText() || input->isNumberField();
+ }
+
+ return false;
+}
+
+bool AXNodeObject::isNonNativeTextControl() const
+{
+ if (isNativeTextControl())
+ return false;
+
+ if (hasContentEditableAttributeSet())
+ return true;
+
+ if (isARIATextControl())
+ return true;
+
+ return false;
+}
+
+bool AXNodeObject::isPasswordField() const
+{
+ Node* node = this->node();
+ if (!node || !node->hasTagName(inputTag))
+ return false;
+
+ if (ariaRoleAttribute() != UnknownRole)
+ return false;
+
+ return toHTMLInputElement(node)->isPasswordField();
+}
+
+bool AXNodeObject::isProgressIndicator() const
+{
+ return roleValue() == ProgressIndicatorRole;
+}
+
+bool AXNodeObject::isSlider() const
+{
+ return roleValue() == SliderRole;
+}
+
+bool AXNodeObject::isChecked() const
+{
+ Node* node = this->node();
+ if (!node)
+ return false;
+
+ // First test for native checkedness semantics
+ if (node->hasTagName(inputTag))
+ return toHTMLInputElement(node)->shouldAppearChecked();
+
+ // Else, if this is an ARIA checkbox or radio, respect the aria-checked attribute
+ AccessibilityRole ariaRole = ariaRoleAttribute();
+ if (ariaRole == RadioButtonRole || ariaRole == CheckBoxRole) {
+ if (equalIgnoringCase(getAttribute(aria_checkedAttr), "true"))
+ return true;
+ return false;
+ }
+
+ // Otherwise it's not checked
+ return false;
+}
+
+bool AXNodeObject::isClickable() const
+{
+ if (node()) {
+ if (node()->isElementNode() && toElement(node())->isDisabledFormControl())
+ return false;
+
+ // Note: we can't call node()->willRespondToMouseClickEvents() because that triggers a style recalc and can delete this.
+ if (node()->hasEventListeners(EventTypeNames::mouseup) || node()->hasEventListeners(EventTypeNames::mousedown) || node()->hasEventListeners(EventTypeNames::click) || node()->hasEventListeners(EventTypeNames::DOMActivate))
+ return true;
+ }
+
+ return AXObject::isClickable();
+}
+
+bool AXNodeObject::isEnabled() const
+{
+ if (equalIgnoringCase(getAttribute(aria_disabledAttr), "true"))
+ return false;
+
+ Node* node = this->node();
+ if (!node || !node->isElementNode())
+ return true;
+
+ return !toElement(node)->isDisabledFormControl();
+}
+
+bool AXNodeObject::isIndeterminate() const
+{
+ Node* node = this->node();
+ if (!node || !node->hasTagName(inputTag))
+ return false;
+
+ return toHTMLInputElement(node)->shouldAppearIndeterminate();
+}
+
+bool AXNodeObject::isPressed() const
+{
+ if (!isButton())
+ return false;
+
+ Node* node = this->node();
+ if (!node)
+ return false;
+
+ // If this is an ARIA button, check the aria-pressed attribute rather than node()->active()
+ if (ariaRoleAttribute() == ButtonRole) {
+ if (equalIgnoringCase(getAttribute(aria_pressedAttr), "true"))
+ return true;
+ return false;
+ }
+
+ return node->active();
+}
+
+bool AXNodeObject::isReadOnly() const
+{
+ Node* node = this->node();
+ if (!node)
+ return true;
+
+ if (isHTMLTextAreaElement(node))
+ return toHTMLFormControlElement(node)->isReadOnly();
+
+ if (node->hasTagName(inputTag)) {
+ HTMLInputElement* input = toHTMLInputElement(node);
+ if (input->isTextField())
+ return input->isReadOnly();
+ }
+
+ return !node->rendererIsEditable();
+}
+
+bool AXNodeObject::isRequired() const
+{
+ if (equalIgnoringCase(getAttribute(aria_requiredAttr), "true"))
+ return true;
+
+ Node* n = this->node();
+ if (n && (n->isElementNode() && toElement(n)->isFormControlElement()))
+ return toHTMLFormControlElement(n)->isRequired();
+
+ return false;
+}
+
+bool AXNodeObject::canSetFocusAttribute() const
+{
+ Node* node = this->node();
+ if (!node)
+ return false;
+
+ if (isWebArea())
+ return true;
+
+ // NOTE: It would be more accurate to ask the document whether setFocusedNode() would
+ // do anything. For example, setFocusedNode() will do nothing if the current focused
+ // node will not relinquish the focus.
+ if (!node)
+ return false;
+
+ if (isDisabledFormControl(node))
+ return false;
+
+ return node->isElementNode() && toElement(node)->supportsFocus();
+}
+
+bool AXNodeObject::canSetValueAttribute() const
+{
+ if (equalIgnoringCase(getAttribute(aria_readonlyAttr), "true"))
+ return false;
+
+ if (isProgressIndicator() || isSlider())
+ return true;
+
+ if (isTextControl() && !isNativeTextControl())
+ return true;
+
+ // Any node could be contenteditable, so isReadOnly should be relied upon
+ // for this information for all elements.
+ return !isReadOnly();
+}
+
+bool AXNodeObject::canvasHasFallbackContent() const
+{
+ Node* node = this->node();
+ if (!node || !node->hasTagName(canvasTag))
+ return false;
+
+ // If it has any children that are elements, we'll assume it might be fallback
+ // content. If it has no children or its only children are not elements
+ // (e.g. just text nodes), it doesn't have fallback content.
+ for (Node* child = node->firstChild(); child; child = child->nextSibling()) {
+ if (child->isElementNode())
+ return true;
+ }
+
+ return false;
+}
+
+bool AXNodeObject::exposesTitleUIElement() const
+{
+ if (!isControl())
+ return false;
+
+ // If this control is ignored (because it's invisible),
+ // then the label needs to be exposed so it can be visible to accessibility.
+ if (accessibilityIsIgnored())
+ return true;
+
+ // ARIA: section 2A, bullet #3 says if aria-labeledby or aria-label appears, it should
+ // override the "label" element association.
+ bool hasTextAlternative = (!ariaLabeledByAttribute().isEmpty() || !getAttribute(aria_labelAttr).isEmpty());
+
+ // Checkboxes and radio buttons use the text of their title ui element as their own AXTitle.
+ // This code controls whether the title ui element should appear in the AX tree (usually, no).
+ // It should appear if the control already has a label (which will be used as the AXTitle instead).
+ if (isCheckboxOrRadio())
+ return hasTextAlternative;
+
+ // When controls have their own descriptions, the title element should be ignored.
+ if (hasTextAlternative)
+ return false;
+
+ return true;
+}
+
+int AXNodeObject::headingLevel() const
+{
+ // headings can be in block flow and non-block flow
+ Node* node = this->node();
+ if (!node)
+ return false;
+
+ if (ariaRoleAttribute() == HeadingRole)
+ return getAttribute(aria_levelAttr).toInt();
+
+ if (node->hasTagName(h1Tag))
+ return 1;
+
+ if (node->hasTagName(h2Tag))
+ return 2;
+
+ if (node->hasTagName(h3Tag))
+ return 3;
+
+ if (node->hasTagName(h4Tag))
+ return 4;
+
+ if (node->hasTagName(h5Tag))
+ return 5;
+
+ if (node->hasTagName(h6Tag))
+ return 6;
+
+ return 0;
+}
+
+unsigned AXNodeObject::hierarchicalLevel() const
+{
+ Node* node = this->node();
+ if (!node || !node->isElementNode())
+ return 0;
+ Element* element = toElement(node);
+ String ariaLevel = element->getAttribute(aria_levelAttr);
+ if (!ariaLevel.isEmpty())
+ return ariaLevel.toInt();
+
+ // Only tree item will calculate its level through the DOM currently.
+ if (roleValue() != TreeItemRole)
+ return 0;
+
+ // Hierarchy leveling starts at 1, to match the aria-level spec.
+ // We measure tree hierarchy by the number of groups that the item is within.
+ unsigned level = 1;
+ for (AXObject* parent = parentObject(); parent; parent = parent->parentObject()) {
+ AccessibilityRole parentRole = parent->roleValue();
+ if (parentRole == GroupRole)
+ level++;
+ else if (parentRole == TreeRole)
+ break;
+ }
+
+ return level;
+}
+
+String AXNodeObject::text() const
+{
+ // If this is a user defined static text, use the accessible name computation.
+ if (ariaRoleAttribute() == StaticTextRole)
+ return ariaAccessibilityDescription();
+
+ if (!isTextControl())
+ return String();
+
+ Node* node = this->node();
+ if (!node)
+ return String();
+
+ if (isNativeTextControl() && (isHTMLTextAreaElement(node) || node->hasTagName(inputTag)))
+ return toHTMLTextFormControlElement(node)->value();
+
+ if (!node->isElementNode())
+ return String();
+
+ return toElement(node)->innerText();
+}
+
+AXObject* AXNodeObject::titleUIElement() const
+{
+ if (!node() || !node()->isElementNode())
+ return 0;
+
+ if (isFieldset())
+ return axObjectCache()->getOrCreate(toHTMLFieldSetElement(node())->legend());
+
+ HTMLLabelElement* label = labelForElement(toElement(node()));
+ if (label)
+ return axObjectCache()->getOrCreate(label);
+
+ return 0;
+}
+
+AccessibilityButtonState AXNodeObject::checkboxOrRadioValue() const
+{
+ if (isNativeCheckboxOrRadio())
+ return isChecked() ? ButtonStateOn : ButtonStateOff;
+
+ return AXObject::checkboxOrRadioValue();
+}
+
+void AXNodeObject::colorValue(int& r, int& g, int& b) const
+{
+ r = 0;
+ g = 0;
+ b = 0;
+
+ if (!isColorWell())
+ return;
+
+ if (!node() || !node()->hasTagName(inputTag))
+ return;
+
+ HTMLInputElement* input = toHTMLInputElement(node());
+ const AtomicString& type = input->getAttribute(typeAttr);
+ if (!equalIgnoringCase(type, "color"))
+ return;
+
+ // HTMLInputElement::value always returns a string parseable by Color().
+ Color color(input->value());
+ r = color.red();
+ g = color.green();
+ b = color.blue();
+}
+
+String AXNodeObject::valueDescription() const
+{
+ if (!supportsRangeValue())
+ return String();
+
+ return getAttribute(aria_valuetextAttr).string();
+}
+
+float AXNodeObject::valueForRange() const
+{
+ if (hasAttribute(aria_valuenowAttr))
+ return getAttribute(aria_valuenowAttr).toFloat();
+
+ if (node() && node()->hasTagName(inputTag)) {
+ HTMLInputElement* input = toHTMLInputElement(node());
+ if (input->isRangeControl())
+ return input->valueAsNumber();
+ }
+
+ return 0.0;
+}
+
+float AXNodeObject::maxValueForRange() const
+{
+ if (hasAttribute(aria_valuemaxAttr))
+ return getAttribute(aria_valuemaxAttr).toFloat();
+
+ if (node() && node()->hasTagName(inputTag)) {
+ HTMLInputElement* input = toHTMLInputElement(node());
+ if (input->isRangeControl())
+ return input->maximum();
+ }
+
+ return 0.0;
+}
+
+float AXNodeObject::minValueForRange() const
+{
+ if (hasAttribute(aria_valueminAttr))
+ return getAttribute(aria_valueminAttr).toFloat();
+
+ if (node() && node()->hasTagName(inputTag)) {
+ HTMLInputElement* input = toHTMLInputElement(node());
+ if (input->isRangeControl())
+ return input->minimum();
+ }
+
+ return 0.0;
+}
+
+float AXNodeObject::stepValueForRange() const
+{
+ return getAttribute(stepAttr).toFloat();
+}
+
+String AXNodeObject::stringValue() const
+{
+ Node* node = this->node();
+ if (!node)
+ return String();
+
+ if (ariaRoleAttribute() == StaticTextRole) {
+ String staticText = text();
+ if (!staticText.length())
+ staticText = textUnderElement();
+ return staticText;
+ }
+
+ if (node->isTextNode())
+ return textUnderElement();
+
+ if (node->hasTagName(selectTag)) {
+ HTMLSelectElement* selectElement = toHTMLSelectElement(node);
+ int selectedIndex = selectElement->selectedIndex();
+ const Vector<HTMLElement*> listItems = selectElement->listItems();
+ if (selectedIndex >= 0 && static_cast<size_t>(selectedIndex) < listItems.size()) {
+ const AtomicString& overriddenDescription = listItems[selectedIndex]->fastGetAttribute(aria_labelAttr);
+ if (!overriddenDescription.isNull())
+ return overriddenDescription;
+ }
+ if (!selectElement->multiple())
+ return selectElement->value();
+ return String();
+ }
+
+ if (isTextControl())
+ return text();
+
+ // FIXME: We might need to implement a value here for more types
+ // FIXME: It would be better not to advertise a value at all for the types for which we don't implement one;
+ // this would require subclassing or making accessibilityAttributeNames do something other than return a
+ // single static array.
+ return String();
+}
+
+String AXNodeObject::ariaDescribedByAttribute() const
+{
+ Vector<Element*> elements;
+ elementsFromAttribute(elements, aria_describedbyAttr);
+
+ return accessibilityDescriptionForElements(elements);
+}
+
+
+String AXNodeObject::ariaLabeledByAttribute() const
+{
+ Vector<Element*> elements;
+ ariaLabeledByElements(elements);
+
+ return accessibilityDescriptionForElements(elements);
+}
+
+AccessibilityRole AXNodeObject::ariaRoleAttribute() const
+{
+ return m_ariaRole;
+}
+
+void AXNodeObject::accessibilityText(Vector<AccessibilityText>& textOrder)
+{
+ titleElementText(textOrder);
+ alternativeText(textOrder);
+ visibleText(textOrder);
+ helpText(textOrder);
+
+ String placeholder = placeholderValue();
+ if (!placeholder.isEmpty())
+ textOrder.append(AccessibilityText(placeholder, PlaceholderText));
+}
+
+// When building the textUnderElement for an object, determine whether or not
+// we should include the inner text of this given descendant object or skip it.
+static bool shouldUseAccessiblityObjectInnerText(AXObject* obj)
+{
+ // Consider this hypothetical example:
+ // <div tabindex=0>
+ // <h2>
+ // Table of contents
+ // </h2>
+ // <a href="#start">Jump to start of book</a>
+ // <ul>
+ // <li><a href="#1">Chapter 1</a></li>
+ // <li><a href="#1">Chapter 2</a></li>
+ // </ul>
+ // </div>
+ //
+ // The goal is to return a reasonable title for the outer container div, because
+ // it's focusable - but without making its title be the full inner text, which is
+ // quite long. As a heuristic, skip links, controls, and elements that are usually
+ // containers with lots of children.
+
+ // Skip hidden children
+ if (obj->isInertOrAriaHidden())
+ return false;
+
+ // Skip focusable children, so we don't include the text of links and controls.
+ if (obj->canSetFocusAttribute())
+ return false;
+
+ // Skip big container elements like lists, tables, etc.
+ if (obj->isList() || obj->isAXTable() || obj->isTree() || obj->isCanvas())
+ return false;
+
+ return true;
+}
+
+String AXNodeObject::textUnderElement() const
+{
+ Node* node = this->node();
+ if (node && node->isTextNode())
+ return toText(node)->wholeText();
+
+ StringBuilder builder;
+ for (AXObject* child = firstChild(); child; child = child->nextSibling()) {
+ if (!shouldUseAccessiblityObjectInnerText(child))
+ continue;
+
+ if (child->isAXNodeObject()) {
+ Vector<AccessibilityText> textOrder;
+ toAXNodeObject(child)->alternativeText(textOrder);
+ if (textOrder.size() > 0) {
+ builder.append(textOrder[0].text);
+ continue;
+ }
+ }
+
+ builder.append(child->textUnderElement());
+ }
+
+ return builder.toString();
+}
+
+String AXNodeObject::accessibilityDescription() const
+{
+ // Static text should not have a description, it should only have a stringValue.
+ if (roleValue() == StaticTextRole)
+ return String();
+
+ String ariaDescription = ariaAccessibilityDescription();
+ if (!ariaDescription.isEmpty())
+ return ariaDescription;
+
+ if (isImage() || isInputImage() || isNativeImage() || isCanvas()) {
+ // Images should use alt as long as the attribute is present, even if empty.
+ // Otherwise, it should fallback to other methods, like the title attribute.
+ const AtomicString& alt = getAttribute(altAttr);
+ if (!alt.isNull())
+ return alt;
+ }
+
+ // An element's descriptive text is comprised of title() (what's visible on the screen) and accessibilityDescription() (other descriptive text).
+ // Both are used to generate what a screen reader speaks.
+ // If this point is reached (i.e. there's no accessibilityDescription) and there's no title(), we should fallback to using the title attribute.
+ // The title attribute is normally used as help text (because it is a tooltip), but if there is nothing else available, this should be used (according to ARIA).
+ if (title().isEmpty())
+ return getAttribute(titleAttr);
+
+ return String();
+}
+
+String AXNodeObject::title() const
+{
+ Node* node = this->node();
+ if (!node)
+ return String();
+
+ bool isInputTag = node->hasTagName(inputTag);
+ if (isInputTag) {
+ HTMLInputElement* input = toHTMLInputElement(node);
+ if (input->isTextButton())
+ return input->valueWithDefault();
+ }
+
+ if (isInputTag || AXObject::isARIAInput(ariaRoleAttribute()) || isControl()) {
+ HTMLLabelElement* label = labelForElement(toElement(node));
+ if (label && !exposesTitleUIElement())
+ return label->innerText();
+ }
+
+ // If this node isn't rendered, there's no inner text we can extract from a select element.
+ if (!isAXRenderObject() && node->hasTagName(selectTag))
+ return String();
+
+ switch (roleValue()) {
+ case PopUpButtonRole:
+ // Native popup buttons should not use their button children's text as a title. That value is retrieved through stringValue().
+ if (node->hasTagName(selectTag))
+ return String();
+ case ButtonRole:
+ case ToggleButtonRole:
+ case CheckBoxRole:
+ case ListBoxOptionRole:
+ case MenuButtonRole:
+ case MenuItemRole:
+ case RadioButtonRole:
+ case TabRole:
+ return textUnderElement();
+ // SVGRoots should not use the text under itself as a title. That could include the text of objects like <text>.
+ case SVGRootRole:
+ return String();
+ default:
+ break;
+ }
+
+ if (isHeading() || isLink())
+ return textUnderElement();
+
+ // If it's focusable but it's not content editable or a known control type, then it will appear to
+ // the user as a single atomic object, so we should use its text as the default title.
+ if (isGenericFocusableElement())
+ return textUnderElement();
+
+ return String();
+}
+
+String AXNodeObject::helpText() const
+{
+ Node* node = this->node();
+ if (!node)
+ return String();
+
+ const AtomicString& ariaHelp = getAttribute(aria_helpAttr);
+ if (!ariaHelp.isEmpty())
+ return ariaHelp;
+
+ String describedBy = ariaDescribedByAttribute();
+ if (!describedBy.isEmpty())
+ return describedBy;
+
+ String description = accessibilityDescription();
+ for (Node* curr = node; curr; curr = curr->parentNode()) {
+ if (curr->isHTMLElement()) {
+ const AtomicString& summary = toElement(curr)->getAttribute(summaryAttr);
+ if (!summary.isEmpty())
+ return summary;
+
+ // The title attribute should be used as help text unless it is already being used as descriptive text.
+ const AtomicString& title = toElement(curr)->getAttribute(titleAttr);
+ if (!title.isEmpty() && description != title)
+ return title;
+ }
+
+ // Only take help text from an ancestor element if its a group or an unknown role. If help was
+ // added to those kinds of elements, it is likely it was meant for a child element.
+ AXObject* axObj = axObjectCache()->getOrCreate(curr);
+ if (axObj) {
+ AccessibilityRole role = axObj->roleValue();
+ if (role != GroupRole && role != UnknownRole)
+ break;
+ }
+ }
+
+ return String();
+}
+
+LayoutRect AXNodeObject::elementRect() const
+{
+ // First check if it has a custom rect, for example if this element is tied to a canvas path.
+ if (!m_explicitElementRect.isEmpty())
+ return m_explicitElementRect;
+
+ // AXNodeObjects have no mechanism yet to return a size or position.
+ // For now, let's return the position of the ancestor that does have a position,
+ // and make it the width of that parent, and about the height of a line of text, so that it's clear the object is a child of the parent.
+
+ LayoutRect boundingBox;
+
+ for (AXObject* positionProvider = parentObject(); positionProvider; positionProvider = positionProvider->parentObject()) {
+ if (positionProvider->isAXRenderObject()) {
+ LayoutRect parentRect = positionProvider->elementRect();
+ boundingBox.setSize(LayoutSize(parentRect.width(), LayoutUnit(std::min(10.0f, parentRect.height().toFloat()))));
+ boundingBox.setLocation(parentRect.location());
+ break;
+ }
+ }
+
+ return boundingBox;
+}
+
+AXObject* AXNodeObject::parentObject() const
+{
+ if (!node())
+ return 0;
+
+ Node* parentObj = node()->parentNode();
+ if (parentObj)
+ return axObjectCache()->getOrCreate(parentObj);
+
+ return 0;
+}
+
+AXObject* AXNodeObject::parentObjectIfExists() const
+{
+ return parentObject();
+}
+
+AXObject* AXNodeObject::firstChild() const
+{
+ if (!node())
+ return 0;
+
+ Node* firstChild = node()->firstChild();
+
+ if (!firstChild)
+ return 0;
+
+ return axObjectCache()->getOrCreate(firstChild);
+}
+
+AXObject* AXNodeObject::nextSibling() const
+{
+ if (!node())
+ return 0;
+
+ Node* nextSibling = node()->nextSibling();
+ if (!nextSibling)
+ return 0;
+
+ return axObjectCache()->getOrCreate(nextSibling);
+}
+
+void AXNodeObject::addChildren()
+{
+ // If the need to add more children in addition to existing children arises,
+ // childrenChanged should have been called, leaving the object with no children.
+ ASSERT(!m_haveChildren);
+
+ if (!m_node)
+ return;
+
+ m_haveChildren = true;
+
+ // The only time we add children from the DOM tree to a node with a renderer is when it's a canvas.
+ if (renderer() && !m_node->hasTagName(canvasTag))
+ return;
+
+ for (Node* child = m_node->firstChild(); child; child = child->nextSibling())
+ addChild(axObjectCache()->getOrCreate(child));
+}
+
+void AXNodeObject::addChild(AXObject* child)
+{
+ insertChild(child, m_children.size());
+}
+
+void AXNodeObject::insertChild(AXObject* child, unsigned index)
+{
+ if (!child)
+ return;
+
+ // If the parent is asking for this child's children, then either it's the first time (and clearing is a no-op),
+ // or its visibility has changed. In the latter case, this child may have a stale child cached.
+ // This can prevent aria-hidden changes from working correctly. Hence, whenever a parent is getting children, ensure data is not stale.
+ child->clearChildren();
+
+ if (child->accessibilityIsIgnored()) {
+ AccessibilityChildrenVector children = child->children();
+ size_t length = children.size();
+ for (size_t i = 0; i < length; ++i)
+ m_children.insert(index + i, children[i]);
+ } else {
+ ASSERT(child->parentObject() == this);
+ m_children.insert(index, child);
+ }
+}
+
+bool AXNodeObject::canHaveChildren() const
+{
+ // If this is an AXRenderObject, then it's okay if this object
+ // doesn't have a node - there are some renderers that don't have associated
+ // nodes, like scroll areas and css-generated text.
+ if (!node() && !isAXRenderObject())
+ return false;
+
+ // Elements that should not have children
+ switch (roleValue()) {
+ case ImageRole:
+ case ButtonRole:
+ case PopUpButtonRole:
+ case CheckBoxRole:
+ case RadioButtonRole:
+ case TabRole:
+ case ToggleButtonRole:
+ case ListBoxOptionRole:
+ case ScrollBarRole:
+ return false;
+ case StaticTextRole:
+ if (!axObjectCache()->inlineTextBoxAccessibility())
+ return false;
+ default:
+ return true;
+ }
+}
+
+Element* AXNodeObject::actionElement() const
+{
+ Node* node = this->node();
+ if (!node)
+ return 0;
+
+ if (node->hasTagName(inputTag)) {
+ HTMLInputElement* input = toHTMLInputElement(node);
+ if (!input->isDisabledFormControl() && (isCheckboxOrRadio() || input->isTextButton()))
+ return input;
+ } else if (node->hasTagName(buttonTag)) {
+ return toElement(node);
+ }
+
+ if (isFileUploadButton())
+ return toElement(node);
+
+ if (AXObject::isARIAInput(ariaRoleAttribute()))
+ return toElement(node);
+
+ if (isImageButton())
+ return toElement(node);
+
+ if (node->hasTagName(selectTag))
+ return toElement(node);
+
+ switch (roleValue()) {
+ case ButtonRole:
+ case PopUpButtonRole:
+ case ToggleButtonRole:
+ case TabRole:
+ case MenuItemRole:
+ case ListItemRole:
+ return toElement(node);
+ default:
+ break;
+ }
+
+ Element* elt = anchorElement();
+ if (!elt)
+ elt = mouseButtonListener();
+ return elt;
+}
+
+Element* AXNodeObject::anchorElement() const
+{
+ Node* node = this->node();
+ if (!node)
+ return 0;
+
+ AXObjectCache* cache = axObjectCache();
+
+ // search up the DOM tree for an anchor element
+ // NOTE: this assumes that any non-image with an anchor is an HTMLAnchorElement
+ for ( ; node; node = node->parentNode()) {
+ if (isHTMLAnchorElement(node) || (node->renderer() && cache->getOrCreate(node->renderer())->isAnchor()))
+ return toElement(node);
+ }
+
+ return 0;
+}
+
+Document* AXNodeObject::document() const
+{
+ if (!node())
+ return 0;
+ return &node()->document();
+}
+
+void AXNodeObject::setNode(Node* node)
+{
+ m_node = node;
+}
+
+AXObject* AXNodeObject::correspondingControlForLabelElement() const
+{
+ HTMLLabelElement* labelElement = labelElementContainer();
+ if (!labelElement)
+ return 0;
+
+ HTMLElement* correspondingControl = labelElement->control();
+ if (!correspondingControl)
+ return 0;
+
+ // Make sure the corresponding control isn't a descendant of this label
+ // that's in the middle of being destroyed.
+ if (correspondingControl->renderer() && !correspondingControl->renderer()->parent())
+ return 0;
+
+ return axObjectCache()->getOrCreate(correspondingControl);
+}
+
+HTMLLabelElement* AXNodeObject::labelElementContainer() const
+{
+ if (!node())
+ return 0;
+
+ // the control element should not be considered part of the label
+ if (isControl())
+ return 0;
+
+ // find if this has a parent that is a label
+ for (Node* parentNode = node(); parentNode; parentNode = parentNode->parentNode()) {
+ if (isHTMLLabelElement(parentNode))
+ return toHTMLLabelElement(parentNode);
+ }
+
+ return 0;
+}
+
+void AXNodeObject::setFocused(bool on)
+{
+ if (!canSetFocusAttribute())
+ return;
+
+ Document* document = this->document();
+ if (!on) {
+ document->setFocusedElement(0);
+ } else {
+ Node* node = this->node();
+ if (node && node->isElementNode()) {
+ // If this node is already the currently focused node, then calling focus() won't do anything.
+ // That is a problem when focus is removed from the webpage to chrome, and then returns.
+ // In these cases, we need to do what keyboard and mouse focus do, which is reset focus first.
+ if (document->focusedElement() == node)
+ document->setFocusedElement(0);
+
+ toElement(node)->focus();
+ } else {
+ document->setFocusedElement(0);
+ }
+ }
+}
+
+void AXNodeObject::increment()
+{
+ UserGestureIndicator gestureIndicator(DefinitelyProcessingNewUserGesture);
+ alterSliderValue(true);
+}
+
+void AXNodeObject::decrement()
+{
+ UserGestureIndicator gestureIndicator(DefinitelyProcessingNewUserGesture);
+ alterSliderValue(false);
+}
+
+void AXNodeObject::childrenChanged()
+{
+ // This method is meant as a quick way of marking a portion of the accessibility tree dirty.
+ if (!node() && !renderer())
+ return;
+
+ axObjectCache()->postNotification(this, document(), AXObjectCache::AXChildrenChanged, true);
+
+ // Go up the accessibility parent chain, but only if the element already exists. This method is
+ // called during render layouts, minimal work should be done.
+ // If AX elements are created now, they could interrogate the render tree while it's in a funky state.
+ // At the same time, process ARIA live region changes.
+ for (AXObject* parent = this; parent; parent = parent->parentObjectIfExists()) {
+ parent->setNeedsToUpdateChildren();
+
+ // These notifications always need to be sent because screenreaders are reliant on them to perform.
+ // In other words, they need to be sent even when the screen reader has not accessed this live region since the last update.
+
+ // If this element supports ARIA live regions, then notify the AT of changes.
+ if (parent->supportsARIALiveRegion())
+ axObjectCache()->postNotification(parent, parent->document(), AXObjectCache::AXLiveRegionChanged, true);
+
+ // If this element is an ARIA text box or content editable, post a "value changed" notification on it
+ // so that it behaves just like a native input element or textarea.
+ if (isNonNativeTextControl())
+ axObjectCache()->postNotification(parent, parent->document(), AXObjectCache::AXValueChanged, true);
+ }
+}
+
+void AXNodeObject::selectionChanged()
+{
+ // When the selection changes, post the notification on the first ancestor that's an
+ // ARIA text box, or that's marked as contentEditable, otherwise post the notification
+ // on the web area.
+ if (isNonNativeTextControl() || isWebArea())
+ axObjectCache()->postNotification(this, document(), AXObjectCache::AXSelectedTextChanged, true);
+ else
+ AXObject::selectionChanged(); // Calls selectionChanged on parent.
+}
+
+void AXNodeObject::textChanged()
+{
+ // If this element supports ARIA live regions, or is part of a region with an ARIA editable role,
+ // then notify the AT of changes.
+ AXObjectCache* cache = axObjectCache();
+ for (Node* parentNode = node(); parentNode; parentNode = parentNode->parentNode()) {
+ AXObject* parent = cache->get(parentNode);
+ if (!parent)
+ continue;
+
+ if (parent->supportsARIALiveRegion())
+ cache->postNotification(parentNode, AXObjectCache::AXLiveRegionChanged, true);
+
+ // If this element is an ARIA text box or content editable, post a "value changed" notification on it
+ // so that it behaves just like a native input element or textarea.
+ if (parent->isNonNativeTextControl())
+ cache->postNotification(parentNode, AXObjectCache::AXValueChanged, true);
+ }
+}
+
+void AXNodeObject::updateAccessibilityRole()
+{
+ bool ignoredStatus = accessibilityIsIgnored();
+ m_role = determineAccessibilityRole();
+
+ // The AX hierarchy only needs to be updated if the ignored status of an element has changed.
+ if (ignoredStatus != accessibilityIsIgnored())
+ childrenChanged();
+}
+
+String AXNodeObject::alternativeTextForWebArea() const
+{
+ // The WebArea description should follow this order:
+ // aria-label on the <html>
+ // title on the <html>
+ // <title> inside the <head> (of it was set through JS)
+ // name on the <html>
+ // For iframes:
+ // aria-label on the <iframe>
+ // title on the <iframe>
+ // name on the <iframe>
+
+ Document* document = this->document();
+ if (!document)
+ return String();
+
+ // Check if the HTML element has an aria-label for the webpage.
+ if (Element* documentElement = document->documentElement()) {
+ const AtomicString& ariaLabel = documentElement->getAttribute(aria_labelAttr);
+ if (!ariaLabel.isEmpty())
+ return ariaLabel;
+ }
+
+ Node* owner = document->ownerElement();
+ if (owner) {
+ if (owner->hasTagName(frameTag) || owner->hasTagName(iframeTag)) {
+ const AtomicString& title = toElement(owner)->getAttribute(titleAttr);
+ if (!title.isEmpty())
+ return title;
+ return toElement(owner)->getNameAttribute();
+ }
+ if (owner->isHTMLElement())
+ return toHTMLElement(owner)->getNameAttribute();
+ }
+
+ String documentTitle = document->title();
+ if (!documentTitle.isEmpty())
+ return documentTitle;
+
+ owner = document->body();
+ if (owner && owner->isHTMLElement())
+ return toHTMLElement(owner)->getNameAttribute();
+
+ return String();
+}
+
+void AXNodeObject::alternativeText(Vector<AccessibilityText>& textOrder) const
+{
+ if (isWebArea()) {
+ String webAreaText = alternativeTextForWebArea();
+ if (!webAreaText.isEmpty())
+ textOrder.append(AccessibilityText(webAreaText, AlternativeText));
+ return;
+ }
+
+ ariaLabeledByText(textOrder);
+
+ const AtomicString& ariaLabel = getAttribute(aria_labelAttr);
+ if (!ariaLabel.isEmpty())
+ textOrder.append(AccessibilityText(ariaLabel, AlternativeText));
+
+ if (isImage() || isInputImage() || isNativeImage() || isCanvas()) {
+ // Images should use alt as long as the attribute is present, even if empty.
+ // Otherwise, it should fallback to other methods, like the title attribute.
+ const AtomicString& alt = getAttribute(altAttr);
+ if (!alt.isNull())
+ textOrder.append(AccessibilityText(alt, AlternativeText));
+ }
+}
+
+void AXNodeObject::ariaLabeledByText(Vector<AccessibilityText>& textOrder) const
+{
+ String ariaLabeledBy = ariaLabeledByAttribute();
+ if (!ariaLabeledBy.isEmpty()) {
+ Vector<Element*> elements;
+ ariaLabeledByElements(elements);
+
+ unsigned length = elements.size();
+ for (unsigned k = 0; k < length; k++) {
+ RefPtr<AXObject> axElement = axObjectCache()->getOrCreate(elements[k]);
+ textOrder.append(AccessibilityText(ariaLabeledBy, AlternativeText, axElement));
+ }
+ }
+}
+
+void AXNodeObject::changeValueByPercent(float percentChange)
+{
+ float range = maxValueForRange() - minValueForRange();
+ float value = valueForRange();
+
+ value += range * (percentChange / 100);
+ setValue(String::number(value));
+
+ axObjectCache()->postNotification(node(), AXObjectCache::AXValueChanged, true);
+}
+
+void AXNodeObject::helpText(Vector<AccessibilityText>& textOrder) const
+{
+ const AtomicString& ariaHelp = getAttribute(aria_helpAttr);
+ if (!ariaHelp.isEmpty())
+ textOrder.append(AccessibilityText(ariaHelp, HelpText));
+
+ String describedBy = ariaDescribedByAttribute();
+ if (!describedBy.isEmpty())
+ textOrder.append(AccessibilityText(describedBy, SummaryText));
+
+ // Add help type text that is derived from ancestors.
+ for (Node* curr = node(); curr; curr = curr->parentNode()) {
+ const AtomicString& summary = getAttribute(summaryAttr);
+ if (!summary.isEmpty())
+ textOrder.append(AccessibilityText(summary, SummaryText));
+
+ // The title attribute should be used as help text unless it is already being used as descriptive text.
+ const AtomicString& title = getAttribute(titleAttr);
+ if (!title.isEmpty())
+ textOrder.append(AccessibilityText(title, TitleTagText));
+
+ // Only take help text from an ancestor element if its a group or an unknown role. If help was
+ // added to those kinds of elements, it is likely it was meant for a child element.
+ AXObject* axObj = axObjectCache()->getOrCreate(curr);
+ if (!axObj)
+ return;
+
+ AccessibilityRole role = axObj->roleValue();
+ if (role != GroupRole && role != UnknownRole)
+ break;
+ }
+}
+
+void AXNodeObject::titleElementText(Vector<AccessibilityText>& textOrder)
+{
+ Node* node = this->node();
+ if (!node)
+ return;
+
+ bool isInputTag = node->hasTagName(inputTag);
+ if (isInputTag || AXObject::isARIAInput(ariaRoleAttribute()) || isControl()) {
+ HTMLLabelElement* label = labelForElement(toElement(node));
+ if (label) {
+ AXObject* labelObject = axObjectCache()->getOrCreate(label);
+ textOrder.append(AccessibilityText(label->innerText(), LabelByElementText, labelObject));
+ return;
+ }
+ }
+
+ AXObject* titleUIElement = this->titleUIElement();
+ if (titleUIElement)
+ textOrder.append(AccessibilityText(String(), LabelByElementText, titleUIElement));
+}
+
+void AXNodeObject::visibleText(Vector<AccessibilityText>& textOrder) const
+{
+ Node* node = this->node();
+ if (!node)
+ return;
+
+ bool isInputTag = node->hasTagName(inputTag);
+ if (isInputTag) {
+ HTMLInputElement* input = toHTMLInputElement(node);
+ if (input->isTextButton()) {
+ textOrder.append(AccessibilityText(input->valueWithDefault(), VisibleText));
+ return;
+ }
+ }
+
+ // If this node isn't rendered, there's no inner text we can extract from a select element.
+ if (!isAXRenderObject() && node->hasTagName(selectTag))
+ return;
+
+ bool useTextUnderElement = false;
+
+ switch (roleValue()) {
+ case PopUpButtonRole:
+ // Native popup buttons should not use their button children's text as a title. That value is retrieved through stringValue().
+ if (node->hasTagName(selectTag))
+ break;
+ case ButtonRole:
+ case ToggleButtonRole:
+ case CheckBoxRole:
+ case ListBoxOptionRole:
+ case MenuButtonRole:
+ case MenuItemRole:
+ case RadioButtonRole:
+ case TabRole:
+ useTextUnderElement = true;
+ break;
+ default:
+ break;
+ }
+
+ // If it's focusable but it's not content editable or a known control type, then it will appear to
+ // the user as a single atomic object, so we should use its text as the default title.
+ if (isHeading() || isLink() || isGenericFocusableElement())
+ useTextUnderElement = true;
+
+ if (useTextUnderElement) {
+ String text = textUnderElement();
+ if (!text.isEmpty())
+ textOrder.append(AccessibilityText(text, ChildrenText));
+ }
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AXNodeObject.h b/chromium/third_party/WebKit/Source/core/accessibility/AXNodeObject.h
new file mode 100644
index 00000000000..829aaf1bc76
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/accessibility/AXNodeObject.h
@@ -0,0 +1,220 @@
+/*
+ * Copyright (C) 2012, Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef AXNodeObject_h
+#define AXNodeObject_h
+
+#include "core/accessibility/AXObject.h"
+#include "platform/geometry/LayoutRect.h"
+#include "wtf/Forward.h"
+
+namespace WebCore {
+
+class AXObjectCache;
+class Element;
+class Frame;
+class FrameView;
+class HitTestResult;
+class HTMLAnchorElement;
+class HTMLAreaElement;
+class HTMLElement;
+class HTMLLabelElement;
+class HTMLMapElement;
+class HTMLSelectElement;
+class IntPoint;
+class IntSize;
+class Node;
+class RenderListBox;
+class RenderTextControl;
+class RenderView;
+class VisibleSelection;
+class Widget;
+
+class AXNodeObject : public AXObject {
+protected:
+ explicit AXNodeObject(Node*);
+
+public:
+ static PassRefPtr<AXNodeObject> create(Node*);
+ virtual ~AXNodeObject();
+
+protected:
+ // Protected data.
+ AccessibilityRole m_ariaRole;
+ bool m_childrenDirty;
+#ifndef NDEBUG
+ bool m_initialized;
+#endif
+
+ virtual bool computeAccessibilityIsIgnored() const OVERRIDE;
+ virtual AccessibilityRole determineAccessibilityRole();
+
+ String accessibilityDescriptionForElements(Vector<Element*> &elements) const;
+ void alterSliderValue(bool increase);
+ String ariaAccessibilityDescription() const;
+ void ariaLabeledByElements(Vector<Element*>& elements) const;
+ void changeValueByStep(bool increase);
+ AccessibilityRole determineAriaRoleAttribute() const;
+ void elementsFromAttribute(Vector<Element*>& elements, const QualifiedName&) const;
+ bool hasContentEditableAttributeSet() const;
+ bool isDescendantOfBarrenParent() const;
+ // This returns true if it's focusable but it's not content editable and it's not a control or ARIA control.
+ bool isGenericFocusableElement() const;
+ HTMLLabelElement* labelForElement(Element*) const;
+ AXObject* menuButtonForMenu() const;
+ Element* menuItemElementForMenu() const;
+ Element* mouseButtonListener() const;
+ AccessibilityRole remapAriaRoleDueToParent(AccessibilityRole) const;
+ bool isNativeCheckboxOrRadio() const;
+ void setNode(Node*);
+ AXObject* correspondingControlForLabelElement() const;
+ HTMLLabelElement* labelElementContainer() const;
+
+ //
+ // Overridden from AXObject.
+ //
+
+ virtual void init() OVERRIDE;
+ virtual void detach() OVERRIDE;
+ virtual bool isDetached() const OVERRIDE { return !m_node; }
+ virtual bool isAXNodeObject() const OVERRIDE { return true; }
+
+ // Check object role or purpose.
+ virtual bool isAnchor() const OVERRIDE;
+ virtual bool isControl() const OVERRIDE;
+ virtual bool isFieldset() const OVERRIDE;
+ virtual bool isHeading() const OVERRIDE;
+ virtual bool isHovered() const OVERRIDE;
+ virtual bool isImage() const OVERRIDE;
+ bool isImageButton() const;
+ virtual bool isInputImage() const OVERRIDE;
+ virtual bool isLink() const;
+ virtual bool isMenu() const OVERRIDE;
+ virtual bool isMenuButton() const OVERRIDE;
+ virtual bool isMultiSelectable() const OVERRIDE;
+ bool isNativeImage() const;
+ virtual bool isNativeTextControl() const OVERRIDE;
+ virtual bool isNonNativeTextControl() const OVERRIDE;
+ virtual bool isPasswordField() const OVERRIDE;
+ virtual bool isProgressIndicator() const OVERRIDE;
+ virtual bool isSlider() const OVERRIDE;
+
+ // Check object state.
+ virtual bool isChecked() const OVERRIDE;
+ virtual bool isClickable() const OVERRIDE;
+ virtual bool isEnabled() const OVERRIDE;
+ virtual bool isIndeterminate() const OVERRIDE;
+ virtual bool isPressed() const OVERRIDE;
+ virtual bool isReadOnly() const OVERRIDE;
+ virtual bool isRequired() const OVERRIDE;
+
+ // Check whether certain properties can be modified.
+ virtual bool canSetFocusAttribute() const OVERRIDE;
+ virtual bool canSetValueAttribute() const OVERRIDE;
+
+ // Properties of static elements.
+ virtual bool canvasHasFallbackContent() const OVERRIDE;
+ virtual bool exposesTitleUIElement() const OVERRIDE;
+ virtual int headingLevel() const OVERRIDE;
+ virtual unsigned hierarchicalLevel() const OVERRIDE;
+ virtual String text() const OVERRIDE;
+ virtual AXObject* titleUIElement() const OVERRIDE;
+
+ // Properties of interactive elements.
+ virtual AccessibilityButtonState checkboxOrRadioValue() const OVERRIDE;
+ virtual void colorValue(int& r, int& g, int& b) const OVERRIDE;
+ virtual String valueDescription() const OVERRIDE;
+ virtual float valueForRange() const OVERRIDE;
+ virtual float maxValueForRange() const OVERRIDE;
+ virtual float minValueForRange() const OVERRIDE;
+ virtual String stringValue() const OVERRIDE;
+
+ // ARIA attributes.
+ virtual String ariaDescribedByAttribute() const;
+ virtual String ariaLabeledByAttribute() const OVERRIDE;
+ virtual AccessibilityRole ariaRoleAttribute() const OVERRIDE;
+
+ // Accessibility Text.
+ virtual void accessibilityText(Vector<AccessibilityText>&) OVERRIDE;
+ virtual String textUnderElement() const OVERRIDE;
+
+ // Accessibility Text - (To be deprecated).
+ virtual String accessibilityDescription() const OVERRIDE;
+ virtual String title() const OVERRIDE;
+ virtual String helpText() const OVERRIDE;
+
+ // Location and click point in frame-relative coordinates.
+ virtual LayoutRect elementRect() const OVERRIDE;
+
+ // High-level accessibility tree access.
+ virtual AXObject* parentObject() const OVERRIDE;
+ virtual AXObject* parentObjectIfExists() const OVERRIDE;
+
+ // Low-level accessibility tree exploration.
+ virtual AXObject* firstChild() const OVERRIDE;
+ virtual AXObject* nextSibling() const OVERRIDE;
+ virtual void addChildren() OVERRIDE;
+ virtual bool canHaveChildren() const OVERRIDE;
+ void addChild(AXObject*);
+ void insertChild(AXObject*, unsigned index);
+
+ // DOM and Render tree access.
+ virtual Element* actionElement() const OVERRIDE;
+ virtual Element* anchorElement() const OVERRIDE;
+ virtual Document* document() const OVERRIDE;
+ virtual Node* node() const OVERRIDE { return m_node; }
+
+ // Modify or take an action on an object.
+ virtual void setFocused(bool) OVERRIDE;
+ virtual void increment() OVERRIDE;
+ virtual void decrement() OVERRIDE;
+
+ // Notifications that this object may have changed.
+ virtual void childrenChanged() OVERRIDE;
+ virtual void selectionChanged() OVERRIDE;
+ virtual void textChanged() OVERRIDE;
+ virtual void updateAccessibilityRole() OVERRIDE;
+
+private:
+ Node* m_node;
+
+ String alternativeTextForWebArea() const;
+ void alternativeText(Vector<AccessibilityText>&) const;
+ void ariaLabeledByText(Vector<AccessibilityText>&) const;
+ void changeValueByPercent(float percentChange);
+ void helpText(Vector<AccessibilityText>&) const;
+ void titleElementText(Vector<AccessibilityText>&);
+ void visibleText(Vector<AccessibilityText>&) const;
+ float stepValueForRange() const;
+};
+
+DEFINE_AX_OBJECT_TYPE_CASTS(AXNodeObject, isAXNodeObject());
+
+} // namespace WebCore
+
+#endif // AXNodeObject_h
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AXObject.cpp b/chromium/third_party/WebKit/Source/core/accessibility/AXObject.cpp
new file mode 100644
index 00000000000..24f3285b863
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/accessibility/AXObject.cpp
@@ -0,0 +1,907 @@
+/*
+ * Copyright (C) 2008, 2009, 2011 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/accessibility/AXObject.h"
+
+#include "core/accessibility/AXObjectCache.h"
+#include "core/dom/NodeTraversal.h"
+#include "core/editing/VisibleUnits.h"
+#include "core/editing/htmlediting.h"
+#include "core/frame/Frame.h"
+#include "core/rendering/RenderListItem.h"
+#include "core/rendering/RenderTheme.h"
+#include "core/rendering/RenderView.h"
+#include "platform/UserGestureIndicator.h"
+#include "platform/text/PlatformLocale.h"
+#include "wtf/StdLibExtras.h"
+#include "wtf/text/WTFString.h"
+
+using blink::WebLocalizedString;
+using namespace std;
+
+namespace WebCore {
+
+using namespace HTMLNames;
+
+typedef HashMap<String, AccessibilityRole, CaseFoldingHash> ARIARoleMap;
+
+struct RoleEntry {
+ String ariaRole;
+ AccessibilityRole webcoreRole;
+};
+
+static ARIARoleMap* createARIARoleMap()
+{
+ const RoleEntry roles[] = {
+ { "alert", AlertRole },
+ { "alertdialog", AlertDialogRole },
+ { "application", ApplicationRole },
+ { "article", ArticleRole },
+ { "banner", BannerRole },
+ { "button", ButtonRole },
+ { "checkbox", CheckBoxRole },
+ { "complementary", ComplementaryRole },
+ { "contentinfo", ContentInfoRole },
+ { "dialog", DialogRole },
+ { "directory", DirectoryRole },
+ { "grid", TableRole },
+ { "gridcell", CellRole },
+ { "columnheader", ColumnHeaderRole },
+ { "combobox", ComboBoxRole },
+ { "definition", DefinitionRole },
+ { "document", DocumentRole },
+ { "rowheader", RowHeaderRole },
+ { "group", GroupRole },
+ { "heading", HeadingRole },
+ { "img", ImageRole },
+ { "link", LinkRole },
+ { "list", ListRole },
+ { "listitem", ListItemRole },
+ { "listbox", ListBoxRole },
+ { "log", LogRole },
+ // "option" isn't here because it may map to different roles depending on the parent element's role
+ { "main", MainRole },
+ { "marquee", MarqueeRole },
+ { "math", MathRole },
+ { "menu", MenuRole },
+ { "menubar", MenuBarRole },
+ { "menuitem", MenuItemRole },
+ { "menuitemcheckbox", MenuItemRole },
+ { "menuitemradio", MenuItemRole },
+ { "note", NoteRole },
+ { "navigation", NavigationRole },
+ { "option", ListBoxOptionRole },
+ { "presentation", PresentationalRole },
+ { "progressbar", ProgressIndicatorRole },
+ { "radio", RadioButtonRole },
+ { "radiogroup", RadioGroupRole },
+ { "region", RegionRole },
+ { "row", RowRole },
+ { "scrollbar", ScrollBarRole },
+ { "search", SearchRole },
+ { "separator", SplitterRole },
+ { "slider", SliderRole },
+ { "spinbutton", SpinButtonRole },
+ { "status", StatusRole },
+ { "tab", TabRole },
+ { "tablist", TabListRole },
+ { "tabpanel", TabPanelRole },
+ { "text", StaticTextRole },
+ { "textbox", TextAreaRole },
+ { "timer", TimerRole },
+ { "toolbar", ToolbarRole },
+ { "tooltip", UserInterfaceTooltipRole },
+ { "tree", TreeRole },
+ { "treegrid", TreeGridRole },
+ { "treeitem", TreeItemRole }
+ };
+ ARIARoleMap* roleMap = new ARIARoleMap;
+
+ for (size_t i = 0; i < WTF_ARRAY_LENGTH(roles); ++i)
+ roleMap->set(roles[i].ariaRole, roles[i].webcoreRole);
+ return roleMap;
+}
+
+AXObject::AXObject()
+ : m_id(0)
+ , m_haveChildren(false)
+ , m_role(UnknownRole)
+ , m_lastKnownIsIgnoredValue(DefaultBehavior)
+ , m_detached(false)
+{
+}
+
+AXObject::~AXObject()
+{
+ ASSERT(isDetached());
+}
+
+void AXObject::detach()
+{
+ // Clear any children and call detachFromParent on them so that
+ // no children are left with dangling pointers to their parent.
+ clearChildren();
+
+ m_detached = true;
+}
+
+bool AXObject::isDetached() const
+{
+ return m_detached;
+}
+
+AXObjectCache* AXObject::axObjectCache() const
+{
+ Document* doc = document();
+ if (doc)
+ return doc->axObjectCache();
+ return 0;
+}
+
+void AXObject::updateBackingStore()
+{
+ // Updating the layout may delete this object.
+ if (Document* document = this->document())
+ document->updateLayoutIgnorePendingStylesheets();
+}
+
+bool AXObject::isARIATextControl() const
+{
+ return ariaRoleAttribute() == TextAreaRole || ariaRoleAttribute() == TextFieldRole;
+}
+
+bool AXObject::isButton() const
+{
+ AccessibilityRole role = roleValue();
+
+ return role == ButtonRole || role == PopUpButtonRole || role == ToggleButtonRole;
+}
+
+bool AXObject::isMenuRelated() const
+{
+ switch (roleValue()) {
+ case MenuRole:
+ case MenuBarRole:
+ case MenuButtonRole:
+ case MenuItemRole:
+ return true;
+ default:
+ return false;
+ }
+}
+
+bool AXObject::isTextControl() const
+{
+ switch (roleValue()) {
+ case TextAreaRole:
+ case TextFieldRole:
+ case ComboBoxRole:
+ return true;
+ default:
+ return false;
+ }
+}
+
+bool AXObject::isClickable() const
+{
+ switch (roleValue()) {
+ case ButtonRole:
+ case CheckBoxRole:
+ case ColorWellRole:
+ case ComboBoxRole:
+ case EditableTextRole:
+ case ImageMapLinkRole:
+ case LinkRole:
+ case ListBoxOptionRole:
+ case MenuButtonRole:
+ case PopUpButtonRole:
+ case RadioButtonRole:
+ case TabRole:
+ case TextAreaRole:
+ case TextFieldRole:
+ case ToggleButtonRole:
+ return true;
+ default:
+ return false;
+ }
+}
+
+bool AXObject::isExpanded() const
+{
+ if (equalIgnoringCase(getAttribute(aria_expandedAttr), "true"))
+ return true;
+
+ return false;
+}
+
+bool AXObject::accessibilityIsIgnored() const
+{
+ AXComputedObjectAttributeCache* attributeCache = axObjectCache()->computedObjectAttributeCache();
+ if (attributeCache) {
+ AXObjectInclusion ignored = attributeCache->getIgnored(axObjectID());
+ switch (ignored) {
+ case IgnoreObject:
+ return true;
+ case IncludeObject:
+ return false;
+ case DefaultBehavior:
+ break;
+ }
+ }
+
+ bool result = computeAccessibilityIsIgnored();
+
+ if (attributeCache)
+ attributeCache->setIgnored(axObjectID(), result ? IgnoreObject : IncludeObject);
+
+ return result;
+}
+
+bool AXObject::accessibilityIsIgnoredByDefault() const
+{
+ return defaultObjectInclusion() == IgnoreObject;
+}
+
+AXObjectInclusion AXObject::accessibilityPlatformIncludesObject() const
+{
+ if (isMenuListPopup() || isMenuListOption())
+ return IncludeObject;
+
+ return DefaultBehavior;
+}
+
+AXObjectInclusion AXObject::defaultObjectInclusion() const
+{
+ if (isInertOrAriaHidden())
+ return IgnoreObject;
+
+ if (isPresentationalChildOfAriaRole())
+ return IgnoreObject;
+
+ return accessibilityPlatformIncludesObject();
+}
+
+bool AXObject::isInertOrAriaHidden() const
+{
+ bool mightBeInInertSubtree = true;
+ for (const AXObject* object = this; object; object = object->parentObject()) {
+ if (equalIgnoringCase(object->getAttribute(aria_hiddenAttr), "true"))
+ return true;
+ if (mightBeInInertSubtree && object->node()) {
+ if (object->node()->isInert())
+ return true;
+ mightBeInInertSubtree = false;
+ }
+ }
+
+ return false;
+}
+
+bool AXObject::lastKnownIsIgnoredValue()
+{
+ if (m_lastKnownIsIgnoredValue == DefaultBehavior)
+ m_lastKnownIsIgnoredValue = accessibilityIsIgnored() ? IgnoreObject : IncludeObject;
+
+ return m_lastKnownIsIgnoredValue == IgnoreObject;
+}
+
+void AXObject::setLastKnownIsIgnoredValue(bool isIgnored)
+{
+ m_lastKnownIsIgnoredValue = isIgnored ? IgnoreObject : IncludeObject;
+}
+
+// Lacking concrete evidence of orientation, horizontal means width > height. vertical is height > width;
+AccessibilityOrientation AXObject::orientation() const
+{
+ LayoutRect bounds = elementRect();
+ if (bounds.size().width() > bounds.size().height())
+ return AccessibilityOrientationHorizontal;
+ if (bounds.size().height() > bounds.size().width())
+ return AccessibilityOrientationVertical;
+
+ // A tie goes to horizontal.
+ return AccessibilityOrientationHorizontal;
+}
+
+static String queryString(WebLocalizedString::Name name)
+{
+ return Locale::defaultLocale().queryString(name);
+}
+
+String AXObject::actionVerb() const
+{
+ // FIXME: Need to add verbs for select elements.
+
+ switch (roleValue()) {
+ case ButtonRole:
+ case ToggleButtonRole:
+ return queryString(WebLocalizedString::AXButtonActionVerb);
+ case TextFieldRole:
+ case TextAreaRole:
+ return queryString(WebLocalizedString::AXTextFieldActionVerb);
+ case RadioButtonRole:
+ return queryString(WebLocalizedString::AXRadioButtonActionVerb);
+ case CheckBoxRole:
+ return queryString(isChecked() ? WebLocalizedString::AXCheckedCheckBoxActionVerb : WebLocalizedString::AXUncheckedCheckBoxActionVerb);
+ case LinkRole:
+ return queryString(WebLocalizedString::AXLinkActionVerb);
+ case PopUpButtonRole:
+ // FIXME: Implement.
+ return String();
+ case MenuListPopupRole:
+ // FIXME: Implement.
+ return String();
+ default:
+ return emptyString();
+ }
+}
+
+AccessibilityButtonState AXObject::checkboxOrRadioValue() const
+{
+ // If this is a real checkbox or radio button, AXRenderObject will handle.
+ // If it's an ARIA checkbox or radio, the aria-checked attribute should be used.
+
+ const AtomicString& result = getAttribute(aria_checkedAttr);
+ if (equalIgnoringCase(result, "true"))
+ return ButtonStateOn;
+ if (equalIgnoringCase(result, "mixed"))
+ return ButtonStateMixed;
+
+ return ButtonStateOff;
+}
+
+const AtomicString& AXObject::placeholderValue() const
+{
+ const AtomicString& placeholder = getAttribute(placeholderAttr);
+ if (!placeholder.isEmpty())
+ return placeholder;
+
+ return nullAtom;
+}
+
+bool AXObject::ariaIsMultiline() const
+{
+ return equalIgnoringCase(getAttribute(aria_multilineAttr), "true");
+}
+
+bool AXObject::ariaPressedIsPresent() const
+{
+ return !getAttribute(aria_pressedAttr).isEmpty();
+}
+
+const AtomicString& AXObject::invalidStatus() const
+{
+ DEFINE_STATIC_LOCAL(const AtomicString, invalidStatusFalse, ("false", AtomicString::ConstructFromLiteral));
+
+ // aria-invalid can return false (default), grammer, spelling, or true.
+ const AtomicString& ariaInvalid = getAttribute(aria_invalidAttr);
+
+ // If empty or not present, it should return false.
+ if (ariaInvalid.isEmpty())
+ return invalidStatusFalse;
+
+ return ariaInvalid;
+}
+
+bool AXObject::supportsARIAAttributes() const
+{
+ return supportsARIALiveRegion()
+ || supportsARIADragging()
+ || supportsARIADropping()
+ || supportsARIAFlowTo()
+ || supportsARIAOwns()
+ || hasAttribute(aria_labelAttr);
+}
+
+bool AXObject::supportsRangeValue() const
+{
+ return isProgressIndicator()
+ || isSlider()
+ || isScrollbar()
+ || isSpinButton();
+}
+
+void AXObject::ariaTreeRows(AccessibilityChildrenVector& result)
+{
+ AccessibilityChildrenVector axChildren = children();
+ unsigned count = axChildren.size();
+ for (unsigned k = 0; k < count; ++k) {
+ AXObject* obj = axChildren[k].get();
+
+ // Add tree items as the rows.
+ if (obj->roleValue() == TreeItemRole)
+ result.append(obj);
+
+ // Now see if this item also has rows hiding inside of it.
+ obj->ariaTreeRows(result);
+ }
+}
+
+bool AXObject::supportsARIALiveRegion() const
+{
+ const AtomicString& liveRegion = ariaLiveRegionStatus();
+ return equalIgnoringCase(liveRegion, "polite") || equalIgnoringCase(liveRegion, "assertive");
+}
+
+void AXObject::markCachedElementRectDirty() const
+{
+ for (unsigned i = 0; i < m_children.size(); ++i)
+ m_children[i].get()->markCachedElementRectDirty();
+}
+
+IntPoint AXObject::clickPoint()
+{
+ LayoutRect rect = elementRect();
+ return roundedIntPoint(LayoutPoint(rect.x() + rect.width() / 2, rect.y() + rect.height() / 2));
+}
+
+IntRect AXObject::boundingBoxForQuads(RenderObject* obj, const Vector<FloatQuad>& quads)
+{
+ ASSERT(obj);
+ if (!obj)
+ return IntRect();
+
+ size_t count = quads.size();
+ if (!count)
+ return IntRect();
+
+ IntRect result;
+ for (size_t i = 0; i < count; ++i) {
+ IntRect r = quads[i].enclosingBoundingBox();
+ if (!r.isEmpty()) {
+ if (obj->style()->hasAppearance())
+ RenderTheme::theme().adjustRepaintRect(obj, r);
+ result.unite(r);
+ }
+ }
+ return result;
+}
+
+AXObject* AXObject::elementAccessibilityHitTest(const IntPoint& point) const
+{
+ // Send the hit test back into the sub-frame if necessary.
+ if (isAttachment()) {
+ Widget* widget = widgetForAttachmentView();
+ // Normalize the point for the widget's bounds.
+ if (widget && widget->isFrameView())
+ return axObjectCache()->getOrCreate(widget)->accessibilityHitTest(IntPoint(point - widget->frameRect().location()));
+ }
+
+ // Check if there are any mock elements that need to be handled.
+ size_t count = m_children.size();
+ for (size_t k = 0; k < count; k++) {
+ if (m_children[k]->isMockObject() && m_children[k]->elementRect().contains(point))
+ return m_children[k]->elementAccessibilityHitTest(point);
+ }
+
+ return const_cast<AXObject*>(this);
+}
+
+const AXObject::AccessibilityChildrenVector& AXObject::children()
+{
+ updateChildrenIfNecessary();
+
+ return m_children;
+}
+
+AXObject* AXObject::parentObjectUnignored() const
+{
+ AXObject* parent;
+ for (parent = parentObject(); parent && parent->accessibilityIsIgnored(); parent = parent->parentObject()) {
+ }
+
+ return parent;
+}
+
+AXObject* AXObject::firstAccessibleObjectFromNode(const Node* node)
+{
+ if (!node)
+ return 0;
+
+ AXObjectCache* cache = node->document().axObjectCache();
+ AXObject* accessibleObject = cache->getOrCreate(node->renderer());
+ while (accessibleObject && accessibleObject->accessibilityIsIgnored()) {
+ node = NodeTraversal::next(*node);
+
+ while (node && !node->renderer())
+ node = NodeTraversal::nextSkippingChildren(*node);
+
+ if (!node)
+ return 0;
+
+ accessibleObject = cache->getOrCreate(node->renderer());
+ }
+
+ return accessibleObject;
+}
+
+void AXObject::updateChildrenIfNecessary()
+{
+ if (!hasChildren())
+ addChildren();
+}
+
+void AXObject::clearChildren()
+{
+ // Some objects have weak pointers to their parents and those associations need to be detached.
+ size_t length = m_children.size();
+ for (size_t i = 0; i < length; i++)
+ m_children[i]->detachFromParent();
+
+ m_children.clear();
+ m_haveChildren = false;
+}
+
+AXObject* AXObject::focusedUIElement() const
+{
+ Document* doc = document();
+ if (!doc)
+ return 0;
+
+ Page* page = doc->page();
+ if (!page)
+ return 0;
+
+ return AXObjectCache::focusedUIElementForPage(page);
+}
+
+Document* AXObject::document() const
+{
+ FrameView* frameView = documentFrameView();
+ if (!frameView)
+ return 0;
+
+ return frameView->frame().document();
+}
+
+FrameView* AXObject::documentFrameView() const
+{
+ const AXObject* object = this;
+ while (object && !object->isAXRenderObject())
+ object = object->parentObject();
+
+ if (!object)
+ return 0;
+
+ return object->documentFrameView();
+}
+
+String AXObject::language() const
+{
+ const AtomicString& lang = getAttribute(langAttr);
+ if (!lang.isEmpty())
+ return lang;
+
+ AXObject* parent = parentObject();
+
+ // as a last resort, fall back to the content language specified in the meta tag
+ if (!parent) {
+ Document* doc = document();
+ if (doc)
+ return doc->contentLanguage();
+ return nullAtom;
+ }
+
+ return parent->language();
+}
+
+bool AXObject::hasAttribute(const QualifiedName& attribute) const
+{
+ Node* elementNode = node();
+ if (!elementNode)
+ return false;
+
+ if (!elementNode->isElementNode())
+ return false;
+
+ Element* element = toElement(elementNode);
+ return element->fastHasAttribute(attribute);
+}
+
+const AtomicString& AXObject::getAttribute(const QualifiedName& attribute) const
+{
+ Node* elementNode = node();
+ if (!elementNode)
+ return nullAtom;
+
+ if (!elementNode->isElementNode())
+ return nullAtom;
+
+ Element* element = toElement(elementNode);
+ return element->fastGetAttribute(attribute);
+}
+
+bool AXObject::press() const
+{
+ Element* actionElem = actionElement();
+ if (!actionElem)
+ return false;
+ UserGestureIndicator gestureIndicator(DefinitelyProcessingNewUserGesture);
+ actionElem->accessKeyAction(true);
+ return true;
+}
+
+void AXObject::scrollToMakeVisible() const
+{
+ IntRect objectRect = pixelSnappedIntRect(elementRect());
+ objectRect.setLocation(IntPoint());
+ scrollToMakeVisibleWithSubFocus(objectRect);
+}
+
+// This is a 1-dimensional scroll offset helper function that's applied
+// separately in the horizontal and vertical directions, because the
+// logic is the same. The goal is to compute the best scroll offset
+// in order to make an object visible within a viewport.
+//
+// In case the whole object cannot fit, you can specify a
+// subfocus - a smaller region within the object that should
+// be prioritized. If the whole object can fit, the subfocus is
+// ignored.
+//
+// Example: the viewport is scrolled to the right just enough
+// that the object is in view.
+// Before:
+// +----------Viewport---------+
+// +---Object---+
+// +--SubFocus--+
+//
+// After:
+// +----------Viewport---------+
+// +---Object---+
+// +--SubFocus--+
+//
+// When constraints cannot be fully satisfied, the min
+// (left/top) position takes precedence over the max (right/bottom).
+//
+// Note that the return value represents the ideal new scroll offset.
+// This may be out of range - the calling function should clip this
+// to the available range.
+static int computeBestScrollOffset(int currentScrollOffset, int subfocusMin, int subfocusMax, int objectMin, int objectMax, int viewportMin, int viewportMax)
+{
+ int viewportSize = viewportMax - viewportMin;
+
+ // If the focus size is larger than the viewport size, shrink it in the
+ // direction of subfocus.
+ if (objectMax - objectMin > viewportSize) {
+ // Subfocus must be within focus:
+ subfocusMin = std::max(subfocusMin, objectMin);
+ subfocusMax = std::min(subfocusMax, objectMax);
+
+ // Subfocus must be no larger than the viewport size; favor top/left.
+ if (subfocusMax - subfocusMin > viewportSize)
+ subfocusMax = subfocusMin + viewportSize;
+
+ if (subfocusMin + viewportSize > objectMax) {
+ objectMin = objectMax - viewportSize;
+ } else {
+ objectMin = subfocusMin;
+ objectMax = subfocusMin + viewportSize;
+ }
+ }
+
+ // Exit now if the focus is already within the viewport.
+ if (objectMin - currentScrollOffset >= viewportMin
+ && objectMax - currentScrollOffset <= viewportMax)
+ return currentScrollOffset;
+
+ // Scroll left if we're too far to the right.
+ if (objectMax - currentScrollOffset > viewportMax)
+ return objectMax - viewportMax;
+
+ // Scroll right if we're too far to the left.
+ if (objectMin - currentScrollOffset < viewportMin)
+ return objectMin - viewportMin;
+
+ ASSERT_NOT_REACHED();
+
+ // This shouldn't happen.
+ return currentScrollOffset;
+}
+
+void AXObject::scrollToMakeVisibleWithSubFocus(const IntRect& subfocus) const
+{
+ // Search up the parent chain until we find the first one that's scrollable.
+ AXObject* scrollParent = parentObject();
+ ScrollableArea* scrollableArea;
+ for (scrollableArea = 0;
+ scrollParent && !(scrollableArea = scrollParent->getScrollableAreaIfScrollable());
+ scrollParent = scrollParent->parentObject()) { }
+ if (!scrollableArea)
+ return;
+
+ LayoutRect objectRect = elementRect();
+ IntPoint scrollPosition = scrollableArea->scrollPosition();
+ IntRect scrollVisibleRect = scrollableArea->visibleContentRect();
+
+ int desiredX = computeBestScrollOffset(
+ scrollPosition.x(),
+ objectRect.x() + subfocus.x(), objectRect.x() + subfocus.maxX(),
+ objectRect.x(), objectRect.maxX(),
+ 0, scrollVisibleRect.width());
+ int desiredY = computeBestScrollOffset(
+ scrollPosition.y(),
+ objectRect.y() + subfocus.y(), objectRect.y() + subfocus.maxY(),
+ objectRect.y(), objectRect.maxY(),
+ 0, scrollVisibleRect.height());
+
+ scrollParent->scrollTo(IntPoint(desiredX, desiredY));
+
+ // Recursively make sure the scroll parent itself is visible.
+ if (scrollParent->parentObject())
+ scrollParent->scrollToMakeVisible();
+}
+
+void AXObject::scrollToGlobalPoint(const IntPoint& globalPoint) const
+{
+ // Search up the parent chain and create a vector of all scrollable parent objects
+ // and ending with this object itself.
+ Vector<const AXObject*> objects;
+ AXObject* parentObject;
+ for (parentObject = this->parentObject(); parentObject; parentObject = parentObject->parentObject()) {
+ if (parentObject->getScrollableAreaIfScrollable())
+ objects.prepend(parentObject);
+ }
+ objects.append(this);
+
+ // Start with the outermost scrollable (the main window) and try to scroll the
+ // next innermost object to the given point.
+ int offsetX = 0, offsetY = 0;
+ IntPoint point = globalPoint;
+ size_t levels = objects.size() - 1;
+ for (size_t i = 0; i < levels; i++) {
+ const AXObject* outer = objects[i];
+ const AXObject* inner = objects[i + 1];
+
+ ScrollableArea* scrollableArea = outer->getScrollableAreaIfScrollable();
+
+ LayoutRect innerRect = inner->isAXScrollView() ? inner->parentObject()->elementRect() : inner->elementRect();
+ LayoutRect objectRect = innerRect;
+ IntPoint scrollPosition = scrollableArea->scrollPosition();
+
+ // Convert the object rect into local coordinates.
+ objectRect.move(offsetX, offsetY);
+ if (!outer->isAXScrollView())
+ objectRect.move(scrollPosition.x(), scrollPosition.y());
+
+ int desiredX = computeBestScrollOffset(
+ 0,
+ objectRect.x(), objectRect.maxX(),
+ objectRect.x(), objectRect.maxX(),
+ point.x(), point.x());
+ int desiredY = computeBestScrollOffset(
+ 0,
+ objectRect.y(), objectRect.maxY(),
+ objectRect.y(), objectRect.maxY(),
+ point.y(), point.y());
+ outer->scrollTo(IntPoint(desiredX, desiredY));
+
+ if (outer->isAXScrollView() && !inner->isAXScrollView()) {
+ // If outer object we just scrolled is a scroll view (main window or iframe) but the
+ // inner object is not, keep track of the coordinate transformation to apply to
+ // future nested calculations.
+ scrollPosition = scrollableArea->scrollPosition();
+ offsetX -= (scrollPosition.x() + point.x());
+ offsetY -= (scrollPosition.y() + point.y());
+ point.move(scrollPosition.x() - innerRect.x(), scrollPosition.y() - innerRect.y());
+ } else if (inner->isAXScrollView()) {
+ // Otherwise, if the inner object is a scroll view, reset the coordinate transformation.
+ offsetX = 0;
+ offsetY = 0;
+ }
+ }
+}
+
+void AXObject::notifyIfIgnoredValueChanged()
+{
+ bool isIgnored = accessibilityIsIgnored();
+ if (lastKnownIsIgnoredValue() != isIgnored) {
+ axObjectCache()->childrenChanged(parentObject());
+ setLastKnownIsIgnoredValue(isIgnored);
+ }
+}
+
+void AXObject::selectionChanged()
+{
+ if (AXObject* parent = parentObjectIfExists())
+ parent->selectionChanged();
+}
+
+int AXObject::lineForPosition(const VisiblePosition& visiblePos) const
+{
+ if (visiblePos.isNull() || !node())
+ return -1;
+
+ // If the position is not in the same editable region as this AX object, return -1.
+ Node* containerNode = visiblePos.deepEquivalent().containerNode();
+ if (!containerNode->containsIncludingShadowDOM(node()) && !node()->containsIncludingShadowDOM(containerNode))
+ return -1;
+
+ int lineCount = -1;
+ VisiblePosition currentVisiblePos = visiblePos;
+ VisiblePosition savedVisiblePos;
+
+ // move up until we get to the top
+ // FIXME: This only takes us to the top of the rootEditableElement, not the top of the
+ // top document.
+ do {
+ savedVisiblePos = currentVisiblePos;
+ VisiblePosition prevVisiblePos = previousLinePosition(currentVisiblePos, 0, HasEditableAXRole);
+ currentVisiblePos = prevVisiblePos;
+ ++lineCount;
+ } while (currentVisiblePos.isNotNull() && !(inSameLine(currentVisiblePos, savedVisiblePos)));
+
+ return lineCount;
+}
+
+bool AXObject::isARIAControl(AccessibilityRole ariaRole)
+{
+ return isARIAInput(ariaRole) || ariaRole == TextAreaRole || ariaRole == ButtonRole
+ || ariaRole == ComboBoxRole || ariaRole == SliderRole;
+}
+
+bool AXObject::isARIAInput(AccessibilityRole ariaRole)
+{
+ return ariaRole == RadioButtonRole || ariaRole == CheckBoxRole || ariaRole == TextFieldRole;
+}
+
+AccessibilityRole AXObject::ariaRoleToWebCoreRole(const String& value)
+{
+ ASSERT(!value.isEmpty());
+
+ static const ARIARoleMap* roleMap = createARIARoleMap();
+
+ Vector<String> roleVector;
+ value.split(' ', roleVector);
+ AccessibilityRole role = UnknownRole;
+ unsigned size = roleVector.size();
+ for (unsigned i = 0; i < size; ++i) {
+ String roleName = roleVector[i];
+ role = roleMap->get(roleName);
+ if (role)
+ return role;
+ }
+
+ return role;
+}
+
+AccessibilityRole AXObject::buttonRoleType() const
+{
+ // If aria-pressed is present, then it should be exposed as a toggle button.
+ // http://www.w3.org/TR/wai-aria/states_and_properties#aria-pressed
+ if (ariaPressedIsPresent())
+ return ToggleButtonRole;
+ if (ariaHasPopup())
+ return PopUpButtonRole;
+ // We don't contemplate RadioButtonRole, as it depends on the input
+ // type.
+
+ return ButtonRole;
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AXObject.h b/chromium/third_party/WebKit/Source/core/accessibility/AXObject.h
new file mode 100644
index 00000000000..e66ba18dd7b
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/accessibility/AXObject.h
@@ -0,0 +1,584 @@
+/*
+ * Copyright (C) 2008, 2009, 2011 Apple Inc. All rights reserved.
+ * Copyright (C) 2008 Nuanti Ltd.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef AXObject_h
+#define AXObject_h
+
+#include "core/editing/VisiblePosition.h"
+#include "platform/geometry/FloatQuad.h"
+#include "platform/geometry/LayoutRect.h"
+#include "wtf/Forward.h"
+#include "wtf/RefPtr.h"
+#include "wtf/Vector.h"
+
+namespace WebCore {
+
+class AXObject;
+class AXObjectCache;
+class Element;
+class Frame;
+class FrameView;
+class HTMLAnchorElement;
+class HTMLAreaElement;
+class IntPoint;
+class IntSize;
+class Node;
+class RenderObject;
+class RenderListItem;
+class ScrollableArea;
+class VisibleSelection;
+class Widget;
+
+typedef unsigned AXID;
+
+enum AccessibilityRole {
+ AlertDialogRole = 1,
+ AlertRole,
+ AnnotationRole,
+ ApplicationRole,
+ ArticleRole,
+ BannerRole,
+ BrowserRole,
+ BusyIndicatorRole,
+ ButtonRole,
+ CanvasRole,
+ CellRole,
+ CheckBoxRole,
+ ColorWellRole,
+ ColumnHeaderRole,
+ ColumnRole,
+ ComboBoxRole,
+ ComplementaryRole,
+ ContentInfoRole,
+ DefinitionRole,
+ DescriptionListDetailRole,
+ DescriptionListTermRole,
+ DialogRole,
+ DirectoryRole,
+ DisclosureTriangleRole,
+ DivRole,
+ DocumentRole,
+ DrawerRole,
+ EditableTextRole,
+ FooterRole,
+ FormRole,
+ GridRole,
+ GroupRole,
+ GrowAreaRole,
+ HeadingRole,
+ HelpTagRole,
+ HorizontalRuleRole,
+ IgnoredRole,
+ ImageMapLinkRole,
+ ImageMapRole,
+ ImageRole,
+ IncrementorRole,
+ InlineTextBoxRole,
+ LabelRole,
+ LegendRole,
+ LinkRole,
+ ListBoxOptionRole,
+ ListBoxRole,
+ ListItemRole,
+ ListMarkerRole,
+ ListRole,
+ LogRole,
+ MainRole,
+ MarqueeRole,
+ MathElementRole,
+ MathRole,
+ MatteRole,
+ MenuBarRole,
+ MenuButtonRole,
+ MenuItemRole,
+ MenuListOptionRole,
+ MenuListPopupRole,
+ MenuRole,
+ NavigationRole,
+ NoteRole,
+ OutlineRole,
+ ParagraphRole,
+ PopUpButtonRole,
+ PresentationalRole,
+ ProgressIndicatorRole,
+ RadioButtonRole,
+ RadioGroupRole,
+ RegionRole,
+ RootWebAreaRole,
+ RowHeaderRole,
+ RowRole,
+ RulerMarkerRole,
+ RulerRole,
+ SVGRootRole,
+ ScrollAreaRole,
+ ScrollBarRole,
+ SeamlessWebAreaRole,
+ SearchRole,
+ SheetRole,
+ SliderRole,
+ SliderThumbRole,
+ SpinButtonPartRole,
+ SpinButtonRole,
+ SplitGroupRole,
+ SplitterRole,
+ StaticTextRole,
+ StatusRole,
+ SystemWideRole,
+ TabGroupRole,
+ TabListRole,
+ TabPanelRole,
+ TabRole,
+ TableHeaderContainerRole,
+ TableRole,
+ TextAreaRole,
+ TextFieldRole,
+ TimerRole,
+ ToggleButtonRole,
+ ToolbarRole,
+ TreeGridRole,
+ TreeItemRole,
+ TreeRole,
+ UnknownRole,
+ UserInterfaceTooltipRole,
+ ValueIndicatorRole,
+ WebAreaRole,
+ WindowRole,
+};
+
+enum AccessibilityTextSource {
+ AlternativeText,
+ ChildrenText,
+ SummaryText,
+ HelpText,
+ VisibleText,
+ TitleTagText,
+ PlaceholderText,
+ LabelByElementText,
+};
+
+enum AccessibilityState {
+ AXBusyState,
+ AXCheckedState,
+ AXCollapsedState,
+ AXEnabledState,
+ AXExpandedState,
+ AXFocusableState,
+ AXFocusedState,
+ AXHaspopupState,
+ AXHoveredState,
+ AXIndeterminateState,
+ AXInvisibleState,
+ AXLinkedState,
+ AXMultiselectableState,
+ AXOffscreenState,
+ AXPressedState,
+ AXProtectedState,
+ AXReadonlyState,
+ AXRequiredState,
+ AXSelectableState,
+ AXSelectedState,
+ AXVerticalState,
+ AXVisitedState
+};
+
+struct AccessibilityText {
+ String text;
+ AccessibilityTextSource textSource;
+ RefPtr<AXObject> textElement;
+
+ AccessibilityText(const String& t, const AccessibilityTextSource& s)
+ : text(t)
+ , textSource(s)
+ { }
+
+ AccessibilityText(const String& t, const AccessibilityTextSource& s, const RefPtr<AXObject> element)
+ : text(t)
+ , textSource(s)
+ , textElement(element)
+ { }
+};
+
+enum AccessibilityOrientation {
+ AccessibilityOrientationVertical,
+ AccessibilityOrientationHorizontal,
+};
+
+enum AXObjectInclusion {
+ IncludeObject,
+ IgnoreObject,
+ DefaultBehavior,
+};
+
+enum AccessibilityButtonState {
+ ButtonStateOff = 0,
+ ButtonStateOn,
+ ButtonStateMixed,
+};
+
+enum AccessibilityTextDirection {
+ AccessibilityTextDirectionLeftToRight,
+ AccessibilityTextDirectionRightToLeft,
+ AccessibilityTextDirectionTopToBottom,
+ AccessibilityTextDirectionBottomToTop
+};
+
+class AXObject : public RefCounted<AXObject> {
+public:
+ typedef Vector<RefPtr<AXObject> > AccessibilityChildrenVector;
+
+ struct PlainTextRange {
+
+ unsigned start;
+ unsigned length;
+
+ PlainTextRange()
+ : start(0)
+ , length(0)
+ { }
+
+ PlainTextRange(unsigned s, unsigned l)
+ : start(s)
+ , length(l)
+ { }
+
+ bool isNull() const { return !start && !length; }
+ };
+
+protected:
+ AXObject();
+
+public:
+ virtual ~AXObject();
+
+ // After constructing an AXObject, it must be given a
+ // unique ID, then added to AXObjectCache, and finally init() must
+ // be called last.
+ void setAXObjectID(AXID axObjectID) { m_id = axObjectID; }
+ virtual void init() { }
+
+ // When the corresponding WebCore object that this AXObject
+ // wraps is deleted, it must be detached.
+ virtual void detach();
+ virtual bool isDetached() const;
+
+ // The AXObjectCache that owns this object, and its unique ID within this cache.
+ AXObjectCache* axObjectCache() const;
+ AXID axObjectID() const { return m_id; }
+
+ // Lays out the page so that the accessibility tree is based on up-to-date information.
+ void updateBackingStore();
+
+ // Determine subclass type.
+ virtual bool isAXNodeObject() const { return false; }
+ virtual bool isAXRenderObject() const { return false; }
+ virtual bool isAXScrollbar() const { return false; }
+ virtual bool isAXScrollView() const { return false; }
+ virtual bool isAXSVGRoot() const { return false; }
+
+ // Check object role or purpose.
+ virtual AccessibilityRole roleValue() const { return m_role; }
+ bool isARIATextControl() const;
+ virtual bool isARIATreeGridRow() const { return false; }
+ virtual bool isAXTable() const { return false; }
+ virtual bool isAnchor() const { return false; }
+ virtual bool isAttachment() const { return false; }
+ bool isButton() const;
+ bool isCanvas() const { return roleValue() == CanvasRole; }
+ bool isCheckbox() const { return roleValue() == CheckBoxRole; }
+ bool isCheckboxOrRadio() const { return isCheckbox() || isRadioButton(); }
+ bool isColorWell() const { return roleValue() == ColorWellRole; }
+ bool isComboBox() const { return roleValue() == ComboBoxRole; }
+ virtual bool isControl() const { return false; }
+ virtual bool isDataTable() const { return false; }
+ virtual bool isFieldset() const { return false; }
+ virtual bool isFileUploadButton() const { return false; }
+ virtual bool isHeading() const { return false; }
+ virtual bool isImage() const { return false; }
+ virtual bool isImageMapLink() const { return false; }
+ virtual bool isInputImage() const { return false; }
+ virtual bool isLink() const { return false; }
+ virtual bool isList() const { return false; }
+ bool isListItem() const { return roleValue() == ListItemRole; }
+ virtual bool isListBoxOption() const { return false; }
+ virtual bool isMenu() const { return false; }
+ virtual bool isMenuButton() const { return false; }
+ virtual bool isMenuList() const { return false; }
+ virtual bool isMenuListOption() const { return false; }
+ virtual bool isMenuListPopup() const { return false; }
+ bool isMenuRelated() const;
+ virtual bool isMockObject() const { return false; }
+ virtual bool isNativeSpinButton() const { return false; }
+ virtual bool isNativeTextControl() const { return false; } // input or textarea
+ virtual bool isNonNativeTextControl() const { return false; } // contenteditable or role=textbox
+ virtual bool isPasswordField() const { return false; }
+ virtual bool isProgressIndicator() const { return false; }
+ bool isRadioButton() const { return roleValue() == RadioButtonRole; }
+ bool isScrollbar() const { return roleValue() == ScrollBarRole; }
+ bool isSeamlessWebArea() const { return roleValue() == SeamlessWebAreaRole; }
+ virtual bool isSlider() const { return false; }
+ virtual bool isSpinButton() const { return roleValue() == SpinButtonRole; }
+ virtual bool isSpinButtonPart() const { return false; }
+ bool isTabItem() const { return roleValue() == TabRole; }
+ virtual bool isTableCell() const { return false; }
+ virtual bool isTableRow() const { return false; }
+ virtual bool isTableCol() const { return false; }
+ bool isTextControl() const;
+ bool isTree() const { return roleValue() == TreeRole; }
+ bool isTreeItem() const { return roleValue() == TreeItemRole; }
+ bool isWebArea() const { return roleValue() == WebAreaRole; }
+
+ // Check object state.
+ virtual bool isChecked() const { return false; }
+ virtual bool isClickable() const;
+ virtual bool isCollapsed() const { return false; }
+ virtual bool isEnabled() const { return false; }
+ bool isExpanded() const;
+ virtual bool isFocused() const { return false; }
+ virtual bool isHovered() const { return false; }
+ virtual bool isIndeterminate() const { return false; }
+ virtual bool isLinked() const { return false; }
+ virtual bool isLoaded() const { return false; }
+ virtual bool isMultiSelectable() const { return false; }
+ virtual bool isOffScreen() const { return false; }
+ virtual bool isPressed() const { return false; }
+ virtual bool isReadOnly() const { return false; }
+ virtual bool isRequired() const { return false; }
+ virtual bool isSelected() const { return false; }
+ virtual bool isSelectedOptionActive() const { return false; }
+ virtual bool isVisible() const { return true; }
+ virtual bool isVisited() const { return false; }
+
+ // Check whether certain properties can be modified.
+ virtual bool canSetFocusAttribute() const { return false; }
+ virtual bool canSetValueAttribute() const { return false; }
+ virtual bool canSetSelectedAttribute() const { return false; }
+ virtual bool canSetSelectedChildrenAttribute() const { return false; }
+
+ // Whether objects are ignored, i.e. not included in the tree.
+ bool accessibilityIsIgnored() const;
+ bool accessibilityIsIgnoredByDefault() const;
+ AXObjectInclusion accessibilityPlatformIncludesObject() const;
+ virtual AXObjectInclusion defaultObjectInclusion() const;
+ bool isInertOrAriaHidden() const;
+ bool lastKnownIsIgnoredValue();
+ void setLastKnownIsIgnoredValue(bool);
+
+ // Properties of static elements.
+ virtual const AtomicString& accessKey() const { return nullAtom; }
+ virtual bool canvasHasFallbackContent() const { return false; }
+ virtual bool exposesTitleUIElement() const { return true; }
+ virtual int headingLevel() const { return 0; }
+ // 1-based, to match the aria-level spec.
+ virtual unsigned hierarchicalLevel() const { return 0; }
+ virtual AccessibilityOrientation orientation() const;
+ virtual int tableLevel() const { return 0; }
+ virtual String text() const { return String(); }
+ virtual int textLength() const { return 0; }
+ virtual AXObject* titleUIElement() const { return 0; }
+ virtual KURL url() const { return KURL(); }
+
+ // For an inline text box.
+ virtual AccessibilityTextDirection textDirection() const { return AccessibilityTextDirectionLeftToRight; }
+ // The integer horizontal pixel offset of each character in the string; negative values for RTL.
+ virtual void textCharacterOffsets(Vector<int>&) const { }
+ // The start and end character offset of each word in the inline text box.
+ virtual void wordBoundaries(Vector<PlainTextRange>& words) const { }
+
+ // Properties of interactive elements.
+ virtual String actionVerb() const;
+ virtual AccessibilityButtonState checkboxOrRadioValue() const;
+ virtual void colorValue(int& r, int& g, int& b) const { r = 0; g = 0; b = 0; }
+ virtual String valueDescription() const { return String(); }
+ virtual float valueForRange() const { return 0.0f; }
+ virtual float maxValueForRange() const { return 0.0f; }
+ virtual float minValueForRange() const { return 0.0f; }
+ const AtomicString& placeholderValue() const;
+ virtual void selectedChildren(AccessibilityChildrenVector&) { }
+ virtual String stringValue() const { return String(); }
+
+ // ARIA attributes.
+ virtual AXObject* activeDescendant() const { return 0; }
+ virtual String ariaDescribedByAttribute() const { return String(); }
+ virtual void ariaFlowToElements(AccessibilityChildrenVector&) const { }
+ virtual bool ariaHasPopup() const { return false; }
+ bool ariaIsMultiline() const;
+ virtual String ariaLabeledByAttribute() const { return String(); }
+ bool ariaPressedIsPresent() const;
+ virtual AccessibilityRole ariaRoleAttribute() const { return UnknownRole; }
+ virtual bool ariaRoleHasPresentationalChildren() const { return false; }
+ const AtomicString& invalidStatus() const;
+ virtual bool isARIAGrabbed() { return false; }
+ virtual bool isPresentationalChildOfAriaRole() const { return false; }
+ virtual bool shouldFocusActiveDescendant() const { return false; }
+ bool supportsARIAAttributes() const;
+ virtual bool supportsARIADragging() const { return false; }
+ virtual bool supportsARIADropping() const { return false; }
+ virtual bool supportsARIAFlowTo() const { return false; }
+ virtual bool supportsARIAOwns() const { return false; }
+ bool supportsRangeValue() const;
+
+ // ARIA trees.
+ // Used by an ARIA tree to get all its rows.
+ void ariaTreeRows(AccessibilityChildrenVector&);
+
+ // ARIA live-region features.
+ bool supportsARIALiveRegion() const;
+ virtual const AtomicString& ariaLiveRegionStatus() const { return nullAtom; }
+ virtual const AtomicString& ariaLiveRegionRelevant() const { return nullAtom; }
+ virtual bool ariaLiveRegionAtomic() const { return false; }
+ virtual bool ariaLiveRegionBusy() const { return false; }
+
+ // Accessibility Text.
+ virtual void accessibilityText(Vector<AccessibilityText>&) { };
+ virtual String textUnderElement() const { return String(); }
+
+ // Accessibility Text - (To be deprecated).
+ virtual String accessibilityDescription() const { return String(); }
+ virtual String title() const { return String(); }
+ virtual String helpText() const { return String(); }
+
+ // Location and click point in frame-relative coordinates.
+ virtual LayoutRect elementRect() const { return m_explicitElementRect; }
+ void setElementRect(LayoutRect r) { m_explicitElementRect = r; }
+ virtual void markCachedElementRectDirty() const;
+ virtual IntPoint clickPoint();
+
+ // Hit testing.
+ // Called on the root AX object to return the deepest available element.
+ virtual AXObject* accessibilityHitTest(const IntPoint&) const { return 0; }
+ // Called on the AX object after the render tree determines which is the right AXRenderObject.
+ virtual AXObject* elementAccessibilityHitTest(const IntPoint&) const;
+
+ // High-level accessibility tree access. Other modules should only use these functions.
+ const AccessibilityChildrenVector& children();
+ virtual AXObject* parentObject() const = 0;
+ AXObject* parentObjectUnignored() const;
+ virtual AXObject* parentObjectIfExists() const { return 0; }
+
+ // Low-level accessibility tree exploration, only for use within the accessibility module.
+ virtual AXObject* firstChild() const { return 0; }
+ virtual AXObject* nextSibling() const { return 0; }
+ static AXObject* firstAccessibleObjectFromNode(const Node*);
+ virtual void addChildren() { }
+ virtual bool canHaveChildren() const { return true; }
+ bool hasChildren() const { return m_haveChildren; }
+ virtual void updateChildrenIfNecessary();
+ virtual void setNeedsToUpdateChildren() { }
+ virtual void clearChildren();
+ virtual void detachFromParent() { }
+ virtual AXObject* observableObject() const { return 0; }
+ virtual AXObject* scrollBar(AccessibilityOrientation) { return 0; }
+
+ // Properties of the object's owning document or page.
+ virtual double estimatedLoadingProgress() const { return 0; }
+ AXObject* focusedUIElement() const;
+
+ // DOM and Render tree access.
+ virtual Node* node() const { return 0; }
+ virtual RenderObject* renderer() const { return 0; }
+ virtual Document* document() const;
+ virtual FrameView* documentFrameView() const;
+ virtual Element* anchorElement() const { return 0; }
+ virtual Element* actionElement() const { return 0; }
+ virtual Widget* widgetForAttachmentView() const { return 0; }
+ String language() const;
+ bool hasAttribute(const QualifiedName&) const;
+ const AtomicString& getAttribute(const QualifiedName&) const;
+
+ // Selected text.
+ virtual PlainTextRange selectedTextRange() const { return PlainTextRange(); }
+ virtual String selectedText() const { return String(); }
+
+ // Modify or take an action on an object.
+ virtual void increment() { }
+ virtual void decrement() { }
+ bool performDefaultAction() const { return press(); }
+ virtual bool press() const;
+ // Make this object visible by scrolling as many nested scrollable views as needed.
+ void scrollToMakeVisible() const;
+ // Same, but if the whole object can't be made visible, try for this subrect, in local coordinates.
+ void scrollToMakeVisibleWithSubFocus(const IntRect&) const;
+ // Scroll this object to a given point in global coordinates of the top-level window.
+ void scrollToGlobalPoint(const IntPoint&) const;
+ virtual void setFocused(bool) { }
+ virtual void setSelected(bool) { }
+ void setSelectedText(const String&) { }
+ virtual void setSelectedTextRange(const PlainTextRange&) { }
+ virtual void setValue(const String&) { }
+ virtual void setValue(float) { }
+
+ // Notifications that this object may have changed.
+ virtual void childrenChanged() { }
+ virtual void handleActiveDescendantChanged() { }
+ virtual void handleAriaExpandedChanged() { }
+ void notifyIfIgnoredValueChanged();
+ virtual void selectionChanged();
+ virtual void textChanged() { }
+ virtual void updateAccessibilityRole() { }
+
+ // Text metrics. Most of these should be deprecated, needs major cleanup.
+ virtual VisiblePosition visiblePositionForIndex(int) const { return VisiblePosition(); }
+ int lineForPosition(const VisiblePosition&) const;
+ virtual int index(const VisiblePosition&) const { return -1; }
+ virtual void lineBreaks(Vector<int>&) const { }
+
+ // Static helper functions.
+ static bool isARIAControl(AccessibilityRole);
+ static bool isARIAInput(AccessibilityRole);
+ static AccessibilityRole ariaRoleToWebCoreRole(const String&);
+ static IntRect boundingBoxForQuads(RenderObject*, const Vector<FloatQuad>&);
+
+protected:
+ AXID m_id;
+ AccessibilityChildrenVector m_children;
+ mutable bool m_haveChildren;
+ AccessibilityRole m_role;
+ AXObjectInclusion m_lastKnownIsIgnoredValue;
+ LayoutRect m_explicitElementRect;
+
+ virtual bool computeAccessibilityIsIgnored() const { return true; }
+
+ // If this object itself scrolls, return its ScrollableArea.
+ virtual ScrollableArea* getScrollableAreaIfScrollable() const { return 0; }
+ virtual void scrollTo(const IntPoint&) const { }
+
+ AccessibilityRole buttonRoleType() const;
+
+ bool allowsTextRanges() const { return isTextControl(); }
+ unsigned getLengthForTextRange() const { return text().length(); }
+
+ bool m_detached;
+};
+
+#define DEFINE_AX_OBJECT_TYPE_CASTS(thisType, predicate) \
+ DEFINE_TYPE_CASTS(thisType, AXObject, object, object->predicate, object.predicate)
+
+} // namespace WebCore
+
+#endif // AXObject_h
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AXObjectCache.cpp b/chromium/third_party/WebKit/Source/core/accessibility/AXObjectCache.cpp
index 6b1048cb72f..34d6f630f5c 100644
--- a/chromium/third_party/WebKit/Source/core/accessibility/AXObjectCache.cpp
+++ b/chromium/third_party/WebKit/Source/core/accessibility/AXObjectCache.cpp
@@ -28,35 +28,35 @@
#include "config.h"
-#if HAVE(ACCESSIBILITY)
-
#include "core/accessibility/AXObjectCache.h"
#include "HTMLNames.h"
-#include "core/accessibility/AccessibilityARIAGrid.h"
-#include "core/accessibility/AccessibilityARIAGridCell.h"
-#include "core/accessibility/AccessibilityARIAGridRow.h"
-#include "core/accessibility/AccessibilityImageMapLink.h"
-#include "core/accessibility/AccessibilityList.h"
-#include "core/accessibility/AccessibilityListBox.h"
-#include "core/accessibility/AccessibilityListBoxOption.h"
-#include "core/accessibility/AccessibilityMediaControls.h"
-#include "core/accessibility/AccessibilityMenuList.h"
-#include "core/accessibility/AccessibilityMenuListOption.h"
-#include "core/accessibility/AccessibilityMenuListPopup.h"
-#include "core/accessibility/AccessibilityProgressIndicator.h"
-#include "core/accessibility/AccessibilityRenderObject.h"
-#include "core/accessibility/AccessibilitySVGRoot.h"
-#include "core/accessibility/AccessibilityScrollView.h"
-#include "core/accessibility/AccessibilityScrollbar.h"
-#include "core/accessibility/AccessibilitySlider.h"
-#include "core/accessibility/AccessibilitySpinButton.h"
-#include "core/accessibility/AccessibilityTable.h"
-#include "core/accessibility/AccessibilityTableCell.h"
-#include "core/accessibility/AccessibilityTableColumn.h"
-#include "core/accessibility/AccessibilityTableHeaderContainer.h"
-#include "core/accessibility/AccessibilityTableRow.h"
+#include "core/accessibility/AXARIAGrid.h"
+#include "core/accessibility/AXARIAGridCell.h"
+#include "core/accessibility/AXARIAGridRow.h"
+#include "core/accessibility/AXImageMapLink.h"
+#include "core/accessibility/AXInlineTextBox.h"
+#include "core/accessibility/AXList.h"
+#include "core/accessibility/AXListBox.h"
+#include "core/accessibility/AXListBoxOption.h"
+#include "core/accessibility/AXMediaControls.h"
+#include "core/accessibility/AXMenuList.h"
+#include "core/accessibility/AXMenuListOption.h"
+#include "core/accessibility/AXMenuListPopup.h"
+#include "core/accessibility/AXProgressIndicator.h"
+#include "core/accessibility/AXRenderObject.h"
+#include "core/accessibility/AXSVGRoot.h"
+#include "core/accessibility/AXScrollView.h"
+#include "core/accessibility/AXScrollbar.h"
+#include "core/accessibility/AXSlider.h"
+#include "core/accessibility/AXSpinButton.h"
+#include "core/accessibility/AXTable.h"
+#include "core/accessibility/AXTableCell.h"
+#include "core/accessibility/AXTableColumn.h"
+#include "core/accessibility/AXTableHeaderContainer.h"
+#include "core/accessibility/AXTableRow.h"
#include "core/dom/Document.h"
+#include "core/frame/Frame.h"
#include "core/html/HTMLAreaElement.h"
#include "core/html/HTMLImageElement.h"
#include "core/html/HTMLInputElement.h"
@@ -64,9 +64,8 @@
#include "core/page/Chrome.h"
#include "core/page/ChromeClient.h"
#include "core/page/FocusController.h"
-#include "core/page/Frame.h"
#include "core/page/Page.h"
-#include "core/platform/ScrollView.h"
+#include "core/rendering/AbstractInlineTextBox.h"
#include "core/rendering/RenderListBox.h"
#include "core/rendering/RenderMenuList.h"
#include "core/rendering/RenderProgress.h"
@@ -75,24 +74,25 @@
#include "core/rendering/RenderTableCell.h"
#include "core/rendering/RenderTableRow.h"
#include "core/rendering/RenderView.h"
+#include "platform/scroll/ScrollView.h"
#include "wtf/PassRefPtr.h"
namespace WebCore {
using namespace HTMLNames;
-AccessibilityObjectInclusion AXComputedObjectAttributeCache::getIgnored(AXID id) const
+AXObjectInclusion AXComputedObjectAttributeCache::getIgnored(AXID id) const
{
HashMap<AXID, CachedAXObjectAttributes>::const_iterator it = m_idMapping.find(id);
return it != m_idMapping.end() ? it->value.ignored : DefaultBehavior;
}
-void AXComputedObjectAttributeCache::setIgnored(AXID id, AccessibilityObjectInclusion inclusion)
+void AXComputedObjectAttributeCache::setIgnored(AXID id, AXObjectInclusion inclusion)
{
HashMap<AXID, CachedAXObjectAttributes>::iterator it = m_idMapping.find(id);
- if (it != m_idMapping.end())
+ if (it != m_idMapping.end()) {
it->value.ignored = inclusion;
- else {
+ } else {
CachedAXObjectAttributes attributes;
attributes.ignored = inclusion;
m_idMapping.set(id, attributes);
@@ -105,6 +105,7 @@ void AXComputedObjectAttributeCache::clear()
}
bool AXObjectCache::gAccessibilityEnabled = false;
+bool AXObjectCache::gInlineTextBoxAccessibility = false;
AXObjectCache::AXObjectCache(const Document* doc)
: m_notificationPostTimer(this, &AXObjectCache::notificationPostTimerFired)
@@ -117,16 +118,16 @@ AXObjectCache::~AXObjectCache()
{
m_notificationPostTimer.stop();
- HashMap<AXID, RefPtr<AccessibilityObject> >::iterator end = m_objects.end();
- for (HashMap<AXID, RefPtr<AccessibilityObject> >::iterator it = m_objects.begin(); it != end; ++it) {
- AccessibilityObject* obj = (*it).value.get();
+ HashMap<AXID, RefPtr<AXObject> >::iterator end = m_objects.end();
+ for (HashMap<AXID, RefPtr<AXObject> >::iterator it = m_objects.begin(); it != end; ++it) {
+ AXObject* obj = (*it).value.get();
detachWrapper(obj);
obj->detach();
removeAXID(obj);
}
}
-AccessibilityObject* AXObjectCache::focusedImageMapUIElement(HTMLAreaElement* areaElement)
+AXObject* AXObjectCache::focusedImageMapUIElement(HTMLAreaElement* areaElement)
{
// Find the corresponding accessibility object for the HTMLAreaElement. This should be
// in the list of children for its corresponding image.
@@ -137,25 +138,25 @@ AccessibilityObject* AXObjectCache::focusedImageMapUIElement(HTMLAreaElement* ar
if (!imageElement)
return 0;
- AccessibilityObject* axRenderImage = areaElement->document().axObjectCache()->getOrCreate(imageElement);
+ AXObject* axRenderImage = areaElement->document().axObjectCache()->getOrCreate(imageElement);
if (!axRenderImage)
return 0;
- AccessibilityObject::AccessibilityChildrenVector imageChildren = axRenderImage->children();
+ AXObject::AccessibilityChildrenVector imageChildren = axRenderImage->children();
unsigned count = imageChildren.size();
for (unsigned k = 0; k < count; ++k) {
- AccessibilityObject* child = imageChildren[k].get();
+ AXObject* child = imageChildren[k].get();
if (!child->isImageMapLink())
continue;
- if (static_cast<AccessibilityImageMapLink*>(child)->areaElement() == areaElement)
+ if (toAXImageMapLink(child)->areaElement() == areaElement)
return child;
}
return 0;
}
-AccessibilityObject* AXObjectCache::focusedUIElementForPage(const Page* page)
+AXObject* AXObjectCache::focusedUIElementForPage(const Page* page)
{
if (!gAccessibilityEnabled)
return 0;
@@ -169,12 +170,12 @@ AccessibilityObject* AXObjectCache::focusedUIElementForPage(const Page* page)
if (isHTMLAreaElement(focusedNode))
return focusedImageMapUIElement(toHTMLAreaElement(focusedNode));
- AccessibilityObject* obj = focusedNode->document().axObjectCache()->getOrCreate(focusedNode);
+ AXObject* obj = focusedNode->document().axObjectCache()->getOrCreate(focusedNode);
if (!obj)
return 0;
if (obj->shouldFocusActiveDescendant()) {
- if (AccessibilityObject* descendant = obj->activeDescendant())
+ if (AXObject* descendant = obj->activeDescendant())
obj = descendant;
}
@@ -185,7 +186,7 @@ AccessibilityObject* AXObjectCache::focusedUIElementForPage(const Page* page)
return obj;
}
-AccessibilityObject* AXObjectCache::get(Widget* widget)
+AXObject* AXObjectCache::get(Widget* widget)
{
if (!widget)
return 0;
@@ -198,7 +199,7 @@ AccessibilityObject* AXObjectCache::get(Widget* widget)
return m_objects.get(axID);
}
-AccessibilityObject* AXObjectCache::get(RenderObject* renderer)
+AXObject* AXObjectCache::get(RenderObject* renderer)
{
if (!renderer)
return 0;
@@ -211,7 +212,7 @@ AccessibilityObject* AXObjectCache::get(RenderObject* renderer)
return m_objects.get(axID);
}
-AccessibilityObject* AXObjectCache::get(Node* node)
+AXObject* AXObjectCache::get(Node* node)
{
if (!node)
return 0;
@@ -223,7 +224,7 @@ AccessibilityObject* AXObjectCache::get(Node* node)
ASSERT(!HashTraits<AXID>::isDeletedValue(nodeID));
if (node->renderer() && nodeID && !renderID) {
- // This can happen if an AccessibilityNodeObject is created for a node that's not
+ // This can happen if an AXNodeObject is created for a node that's not
// rendered, but later something changes and it gets a renderer (like if it's
// reparented).
remove(nodeID);
@@ -239,6 +240,19 @@ AccessibilityObject* AXObjectCache::get(Node* node)
return m_objects.get(nodeID);
}
+AXObject* AXObjectCache::get(AbstractInlineTextBox* inlineTextBox)
+{
+ if (!inlineTextBox)
+ return 0;
+
+ AXID axID = m_inlineTextBoxObjectMapping.get(inlineTextBox);
+ ASSERT(!HashTraits<AXID>::isDeletedValue(axID));
+ if (!axID)
+ return 0;
+
+ return m_objects.get(axID);
+}
+
// FIXME: This probably belongs on Node.
// FIXME: This should take a const char*, but one caller passes nullAtom.
bool nodeHasRole(Node* node, const String& role)
@@ -249,7 +263,7 @@ bool nodeHasRole(Node* node, const String& role)
return equalIgnoringCase(toElement(node)->getAttribute(roleAttr), role);
}
-static PassRefPtr<AccessibilityObject> createFromRenderer(RenderObject* renderer)
+static PassRefPtr<AXObject> createFromRenderer(RenderObject* renderer)
{
// FIXME: How could renderer->node() ever not be an Element?
Node* node = renderer->node();
@@ -257,69 +271,74 @@ static PassRefPtr<AccessibilityObject> createFromRenderer(RenderObject* renderer
// If the node is aria role="list" or the aria role is empty and its a
// ul/ol/dl type (it shouldn't be a list if aria says otherwise).
if (node && ((nodeHasRole(node, "list") || nodeHasRole(node, "directory"))
- || (nodeHasRole(node, nullAtom) && (node->hasTagName(ulTag) || node->hasTagName(olTag) || node->hasTagName(dlTag)))))
- return AccessibilityList::create(renderer);
+ || (nodeHasRole(node, nullAtom) && (node->hasTagName(ulTag) || node->hasTagName(olTag) || node->hasTagName(dlTag)))))
+ return AXList::create(renderer);
// aria tables
if (nodeHasRole(node, "grid") || nodeHasRole(node, "treegrid"))
- return AccessibilityARIAGrid::create(renderer);
+ return AXARIAGrid::create(renderer);
if (nodeHasRole(node, "row"))
- return AccessibilityARIAGridRow::create(renderer);
+ return AXARIAGridRow::create(renderer);
if (nodeHasRole(node, "gridcell") || nodeHasRole(node, "columnheader") || nodeHasRole(node, "rowheader"))
- return AccessibilityARIAGridCell::create(renderer);
+ return AXARIAGridCell::create(renderer);
// media controls
if (node && node->isMediaControlElement())
return AccessibilityMediaControl::create(renderer);
if (renderer->isSVGRoot())
- return AccessibilitySVGRoot::create(renderer);
+ return AXSVGRoot::create(renderer);
if (renderer->isBoxModelObject()) {
RenderBoxModelObject* cssBox = toRenderBoxModelObject(renderer);
if (cssBox->isListBox())
- return AccessibilityListBox::create(toRenderListBox(cssBox));
+ return AXListBox::create(toRenderListBox(cssBox));
if (cssBox->isMenuList())
- return AccessibilityMenuList::create(toRenderMenuList(cssBox));
+ return AXMenuList::create(toRenderMenuList(cssBox));
// standard tables
if (cssBox->isTable())
- return AccessibilityTable::create(toRenderTable(cssBox));
+ return AXTable::create(toRenderTable(cssBox));
if (cssBox->isTableRow())
- return AccessibilityTableRow::create(toRenderTableRow(cssBox));
+ return AXTableRow::create(toRenderTableRow(cssBox));
if (cssBox->isTableCell())
- return AccessibilityTableCell::create(toRenderTableCell(cssBox));
+ return AXTableCell::create(toRenderTableCell(cssBox));
// progress bar
if (cssBox->isProgress())
- return AccessibilityProgressIndicator::create(toRenderProgress(cssBox));
+ return AXProgressIndicator::create(toRenderProgress(cssBox));
// input type=range
if (cssBox->isSlider())
- return AccessibilitySlider::create(toRenderSlider(cssBox));
+ return AXSlider::create(toRenderSlider(cssBox));
}
- return AccessibilityRenderObject::create(renderer);
+ return AXRenderObject::create(renderer);
}
-static PassRefPtr<AccessibilityObject> createFromNode(Node* node)
+static PassRefPtr<AXObject> createFromNode(Node* node)
{
- return AccessibilityNodeObject::create(node);
+ return AXNodeObject::create(node);
}
-AccessibilityObject* AXObjectCache::getOrCreate(Widget* widget)
+static PassRefPtr<AXObject> createFromInlineTextBox(AbstractInlineTextBox* inlineTextBox)
+{
+ return AXInlineTextBox::create(inlineTextBox);
+}
+
+AXObject* AXObjectCache::getOrCreate(Widget* widget)
{
if (!widget)
return 0;
- if (AccessibilityObject* obj = get(widget))
+ if (AXObject* obj = get(widget))
return obj;
- RefPtr<AccessibilityObject> newObj = 0;
+ RefPtr<AXObject> newObj = 0;
if (widget->isFrameView())
- newObj = AccessibilityScrollView::create(toScrollView(widget));
+ newObj = AXScrollView::create(toScrollView(widget));
else if (widget->isScrollbar())
- newObj = AccessibilityScrollbar::create(static_cast<Scrollbar*>(widget));
+ newObj = AXScrollbar::create(toScrollbar(widget));
// Will crash later if we have two objects for the same widget.
ASSERT(!get(widget));
@@ -333,12 +352,12 @@ AccessibilityObject* AXObjectCache::getOrCreate(Widget* widget)
return newObj.get();
}
-AccessibilityObject* AXObjectCache::getOrCreate(Node* node)
+AXObject* AXObjectCache::getOrCreate(Node* node)
{
if (!node)
return 0;
- if (AccessibilityObject* obj = get(node))
+ if (AXObject* obj = get(node))
return obj;
if (node->renderer())
@@ -347,14 +366,14 @@ AccessibilityObject* AXObjectCache::getOrCreate(Node* node)
if (!node->parentElement())
return 0;
- // It's only allowed to create an AccessibilityObject from a Node if it's in a canvas subtree.
+ // It's only allowed to create an AXObject from a Node if it's in a canvas subtree.
// Or if it's a hidden element, but we still want to expose it because of other ARIA attributes.
bool inCanvasSubtree = node->parentElement()->isInCanvasSubtree();
bool isHidden = !node->renderer() && isNodeAriaVisible(node);
if (!inCanvasSubtree && !isHidden)
return 0;
- RefPtr<AccessibilityObject> newObj = createFromNode(node);
+ RefPtr<AXObject> newObj = createFromNode(node);
// Will crash later if we have two objects for the same node.
ASSERT(!get(node));
@@ -370,15 +389,15 @@ AccessibilityObject* AXObjectCache::getOrCreate(Node* node)
return newObj.get();
}
-AccessibilityObject* AXObjectCache::getOrCreate(RenderObject* renderer)
+AXObject* AXObjectCache::getOrCreate(RenderObject* renderer)
{
if (!renderer)
return 0;
- if (AccessibilityObject* obj = get(renderer))
+ if (AXObject* obj = get(renderer))
return obj;
- RefPtr<AccessibilityObject> newObj = createFromRenderer(renderer);
+ RefPtr<AXObject> newObj = createFromRenderer(renderer);
// Will crash later if we have two objects for the same renderer.
ASSERT(!get(renderer));
@@ -394,7 +413,31 @@ AccessibilityObject* AXObjectCache::getOrCreate(RenderObject* renderer)
return newObj.get();
}
-AccessibilityObject* AXObjectCache::rootObject()
+AXObject* AXObjectCache::getOrCreate(AbstractInlineTextBox* inlineTextBox)
+{
+ if (!inlineTextBox)
+ return 0;
+
+ if (AXObject* obj = get(inlineTextBox))
+ return obj;
+
+ RefPtr<AXObject> newObj = createFromInlineTextBox(inlineTextBox);
+
+ // Will crash later if we have two objects for the same inlineTextBox.
+ ASSERT(!get(inlineTextBox));
+
+ getAXID(newObj.get());
+
+ m_inlineTextBoxObjectMapping.set(inlineTextBox, newObj->axObjectID());
+ m_objects.set(newObj->axObjectID(), newObj);
+ newObj->init();
+ attachWrapper(newObj.get());
+ newObj->setLastKnownIsIgnoredValue(newObj->accessibilityIsIgnored());
+
+ return newObj.get();
+}
+
+AXObject* AXObjectCache::rootObject()
{
if (!gAccessibilityEnabled)
return 0;
@@ -402,38 +445,38 @@ AccessibilityObject* AXObjectCache::rootObject()
return getOrCreate(m_document->view());
}
-AccessibilityObject* AXObjectCache::getOrCreate(AccessibilityRole role)
+AXObject* AXObjectCache::getOrCreate(AccessibilityRole role)
{
- RefPtr<AccessibilityObject> obj = 0;
+ RefPtr<AXObject> obj = 0;
// will be filled in...
switch (role) {
case ListBoxOptionRole:
- obj = AccessibilityListBoxOption::create();
+ obj = AXListBoxOption::create();
break;
case ImageMapLinkRole:
- obj = AccessibilityImageMapLink::create();
+ obj = AXImageMapLink::create();
break;
case ColumnRole:
- obj = AccessibilityTableColumn::create();
+ obj = AXTableColumn::create();
break;
case TableHeaderContainerRole:
- obj = AccessibilityTableHeaderContainer::create();
+ obj = AXTableHeaderContainer::create();
break;
case SliderThumbRole:
- obj = AccessibilitySliderThumb::create();
+ obj = AXSliderThumb::create();
break;
case MenuListPopupRole:
- obj = AccessibilityMenuListPopup::create();
+ obj = AXMenuListPopup::create();
break;
case MenuListOptionRole:
- obj = AccessibilityMenuListOption::create();
+ obj = AXMenuListOption::create();
break;
case SpinButtonRole:
- obj = AccessibilitySpinButton::create();
+ obj = AXSpinButton::create();
break;
case SpinButtonPartRole:
- obj = AccessibilitySpinButtonPart::create();
+ obj = AXSpinButtonPart::create();
break;
default:
obj = 0;
@@ -456,7 +499,7 @@ void AXObjectCache::remove(AXID axID)
return;
// first fetch object to operate some cleanup functions on it
- AccessibilityObject* obj = m_objects.get(axID);
+ AXObject* obj = m_objects.get(axID);
if (!obj)
return;
@@ -509,6 +552,15 @@ void AXObjectCache::remove(Widget* view)
m_widgetObjectMapping.remove(view);
}
+void AXObjectCache::remove(AbstractInlineTextBox* inlineTextBox)
+{
+ if (!inlineTextBox)
+ return;
+
+ AXID axID = m_inlineTextBoxObjectMapping.get(inlineTextBox);
+ remove(axID);
+ m_inlineTextBoxObjectMapping.remove(inlineTextBox);
+}
AXID AXObjectCache::platformGenerateAXID() const
{
@@ -525,7 +577,7 @@ AXID AXObjectCache::platformGenerateAXID() const
return objID;
}
-AXID AXObjectCache::getAXID(AccessibilityObject* obj)
+AXID AXObjectCache::getAXID(AXObject* obj)
{
// check for already-assigned ID
AXID objID = obj->axObjectID();
@@ -542,7 +594,7 @@ AXID AXObjectCache::getAXID(AccessibilityObject* obj)
return objID;
}
-void AXObjectCache::removeAXID(AccessibilityObject* object)
+void AXObjectCache::removeAXID(AXObject* object)
{
if (!object)
return;
@@ -561,7 +613,7 @@ void AXObjectCache::selectionChanged(Node* node)
// Find the nearest ancestor that already has an accessibility object, since we
// might be in the middle of a layout.
while (node) {
- if (AccessibilityObject* obj = get(node)) {
+ if (AXObject* obj = get(node)) {
obj->selectionChanged();
return;
}
@@ -579,7 +631,7 @@ void AXObjectCache::textChanged(RenderObject* renderer)
textChanged(getOrCreate(renderer));
}
-void AXObjectCache::textChanged(AccessibilityObject* obj)
+void AXObjectCache::textChanged(AXObject* obj)
{
if (!obj)
return;
@@ -593,8 +645,8 @@ void AXObjectCache::textChanged(AccessibilityObject* obj)
void AXObjectCache::updateCacheAfterNodeIsAttached(Node* node)
{
- // Calling get() will update the AX object if we had an AccessibilityNodeObject but now we need
- // an AccessibilityRenderObject, because it was reparented to a location outside of a canvas.
+ // Calling get() will update the AX object if we had an AXNodeObject but now we need
+ // an AXRenderObject, because it was reparented to a location outside of a canvas.
get(node);
}
@@ -608,7 +660,7 @@ void AXObjectCache::childrenChanged(RenderObject* renderer)
childrenChanged(get(renderer));
}
-void AXObjectCache::childrenChanged(AccessibilityObject* obj)
+void AXObjectCache::childrenChanged(AXObject* obj)
{
if (!obj)
return;
@@ -624,7 +676,7 @@ void AXObjectCache::notificationPostTimerFired(Timer<AXObjectCache>*)
unsigned i = 0, count = m_notificationsToPost.size();
for (i = 0; i < count; ++i) {
- AccessibilityObject* obj = m_notificationsToPost[i].first.get();
+ AXObject* obj = m_notificationsToPost[i].first.get();
if (!obj->axObjectID())
continue;
@@ -634,8 +686,8 @@ void AXObjectCache::notificationPostTimerFired(Timer<AXObjectCache>*)
#ifndef NDEBUG
// Make sure none of the render views are in the process of being layed out.
// Notifications should only be sent after the renderer has finished
- if (obj->isAccessibilityRenderObject()) {
- AccessibilityRenderObject* renderObj = toAccessibilityRenderObject(obj);
+ if (obj->isAXRenderObject()) {
+ AXRenderObject* renderObj = toAXRenderObject(obj);
RenderObject* renderer = renderObj->renderer();
if (renderer && renderer->view())
ASSERT(!renderer->view()->layoutState());
@@ -661,7 +713,7 @@ void AXObjectCache::postNotification(RenderObject* renderer, AXNotification noti
// Get an accessibility object that already exists. One should not be created here
// because a render update may be in progress and creating an AX object can re-trigger a layout
- RefPtr<AccessibilityObject> object = get(renderer);
+ RefPtr<AXObject> object = get(renderer);
while (!object && renderer) {
renderer = renderer->parent();
object = get(renderer);
@@ -682,7 +734,7 @@ void AXObjectCache::postNotification(Node* node, AXNotification notification, bo
// Get an accessibility object that already exists. One should not be created here
// because a render update may be in progress and creating an AX object can re-trigger a layout
- RefPtr<AccessibilityObject> object = get(node);
+ RefPtr<AXObject> object = get(node);
while (!object && node) {
node = node->parentNode();
object = get(node);
@@ -694,7 +746,7 @@ void AXObjectCache::postNotification(Node* node, AXNotification notification, bo
postNotification(object.get(), &node->document(), notification, postToElement, postType);
}
-void AXObjectCache::postNotification(AccessibilityObject* object, Document* document, AXNotification notification, bool postToElement, PostType postType)
+void AXObjectCache::postNotification(AXObject* object, Document* document, AXNotification notification, bool postToElement, PostType postType)
{
m_computedObjectAttributeCache->clear();
@@ -711,8 +763,9 @@ void AXObjectCache::postNotification(AccessibilityObject* object, Document* docu
m_notificationsToPost.append(std::make_pair(object, notification));
if (!m_notificationPostTimer.isActive())
m_notificationPostTimer.startOneShot(0);
- } else
+ } else {
postPlatformNotification(object, notification);
+ }
}
void AXObjectCache::checkedStateChanged(Node* node)
@@ -740,7 +793,7 @@ void AXObjectCache::handleScrollbarUpdate(ScrollView* view)
return;
// We don't want to create a scroll view from this method, only update an existing one.
- if (AccessibilityObject* scrollViewObject = get(view)) {
+ if (AXObject* scrollViewObject = get(view)) {
m_computedObjectAttributeCache->clear();
scrollViewObject->updateChildrenIfNecessary();
}
@@ -748,19 +801,19 @@ void AXObjectCache::handleScrollbarUpdate(ScrollView* view)
void AXObjectCache::handleAriaExpandedChange(Node* node)
{
- if (AccessibilityObject* obj = getOrCreate(node))
+ if (AXObject* obj = getOrCreate(node))
obj->handleAriaExpandedChanged();
}
void AXObjectCache::handleActiveDescendantChanged(Node* node)
{
- if (AccessibilityObject* obj = getOrCreate(node))
+ if (AXObject* obj = getOrCreate(node))
obj->handleActiveDescendantChanged();
}
void AXObjectCache::handleAriaRoleChanged(Node* node)
{
- if (AccessibilityObject* obj = getOrCreate(node)) {
+ if (AXObject* obj = getOrCreate(node)) {
obj->updateAccessibilityRole();
m_computedObjectAttributeCache->clear();
obj->notifyIfIgnoredValueChanged();
@@ -806,7 +859,7 @@ void AXObjectCache::labelChanged(Element* element)
void AXObjectCache::recomputeIsIgnored(RenderObject* renderer)
{
- if (AccessibilityObject* obj = get(renderer))
+ if (AXObject* obj = get(renderer))
obj->notifyIfIgnoredValueChanged();
}
@@ -867,7 +920,7 @@ void AXObjectCache::textMarkerDataForVisiblePosition(TextMarkerData& textMarkerD
// find or create an accessibility object for this node
AXObjectCache* cache = domNode->document().axObjectCache();
- RefPtr<AccessibilityObject> obj = cache->getOrCreate(domNode);
+ RefPtr<AXObject> obj = cache->getOrCreate(domNode);
textMarkerData.axID = obj.get()->axObjectID();
textMarkerData.node = domNode;
@@ -895,7 +948,7 @@ bool AXObjectCache::nodeIsTextControl(const Node* node)
if (!node)
return false;
- const AccessibilityObject* axObject = getOrCreate(const_cast<Node*>(node));
+ const AXObject* axObject = getOrCreate(const_cast<Node*>(node));
return axObject && axObject->isTextControl();
}
@@ -910,21 +963,21 @@ bool isNodeAriaVisible(Node* node)
return equalIgnoringCase(toElement(node)->getAttribute(aria_hiddenAttr), "false");
}
-void AXObjectCache::detachWrapper(AccessibilityObject* obj)
+void AXObjectCache::detachWrapper(AXObject* obj)
{
- // In Chromium, AccessibilityObjects are not wrapped.
+ // In Chromium, AXObjects are not wrapped.
}
-void AXObjectCache::attachWrapper(AccessibilityObject*)
+void AXObjectCache::attachWrapper(AXObject*)
{
- // In Chromium, AccessibilityObjects are not wrapped.
+ // In Chromium, AXObjects are not wrapped.
}
-void AXObjectCache::postPlatformNotification(AccessibilityObject* obj, AXNotification notification)
+void AXObjectCache::postPlatformNotification(AXObject* obj, AXNotification notification)
{
- if (obj && obj->isAccessibilityScrollbar() && notification == AXValueChanged) {
+ if (obj && obj->isAXScrollbar() && notification == AXValueChanged) {
// Send document value changed on scrollbar value changed notification.
- Scrollbar* scrollBar = static_cast<AccessibilityScrollbar*>(obj)->scrollbar();
+ Scrollbar* scrollBar = toAXScrollbar(obj)->scrollbar();
if (!scrollBar || !scrollBar->parent() || !scrollBar->parent()->isFrameView())
return;
Document* document = toFrameView(scrollBar->parent())->frame().document();
@@ -958,7 +1011,7 @@ void AXObjectCache::handleFocusedUIElementChanged(Node*, Node* newFocusedNode)
if (!page)
return;
- AccessibilityObject* focusedObject = focusedUIElementForPage(page);
+ AXObject* focusedObject = focusedUIElementForPage(page);
if (!focusedObject)
return;
@@ -969,9 +1022,7 @@ void AXObjectCache::handleScrolledToAnchor(const Node* anchorNode)
{
// The anchor node may not be accessible. Post the notification for the
// first accessible object.
- postPlatformNotification(AccessibilityObject::firstAccessibleObjectFromNode(anchorNode), AXScrolledToAnchor);
+ postPlatformNotification(AXObject::firstAccessibleObjectFromNode(anchorNode), AXScrolledToAnchor);
}
} // namespace WebCore
-
-#endif // HAVE(ACCESSIBILITY)
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AXObjectCache.h b/chromium/third_party/WebKit/Source/core/accessibility/AXObjectCache.h
index 52caa5c156f..11df342365f 100644
--- a/chromium/third_party/WebKit/Source/core/accessibility/AXObjectCache.h
+++ b/chromium/third_party/WebKit/Source/core/accessibility/AXObjectCache.h
@@ -26,8 +26,9 @@
#ifndef AXObjectCache_h
#define AXObjectCache_h
-#include "core/accessibility/AccessibilityObject.h"
-#include "core/platform/Timer.h"
+#include "core/accessibility/AXObject.h"
+#include "core/rendering/RenderText.h"
+#include "platform/Timer.h"
#include "wtf/Forward.h"
#include "wtf/HashMap.h"
#include "wtf/HashSet.h"
@@ -35,6 +36,7 @@
namespace WebCore {
+class AbstractInlineTextBox;
class Document;
class HTMLAreaElement;
class Node;
@@ -55,8 +57,8 @@ class AXComputedObjectAttributeCache {
public:
static PassOwnPtr<AXComputedObjectAttributeCache> create() { return adoptPtr(new AXComputedObjectAttributeCache()); }
- AccessibilityObjectInclusion getIgnored(AXID) const;
- void setIgnored(AXID, AccessibilityObjectInclusion);
+ AXObjectInclusion getIgnored(AXID) const;
+ void setIgnored(AXID, AXObjectInclusion);
void clear();
@@ -66,7 +68,7 @@ private:
struct CachedAXObjectAttributes {
CachedAXObjectAttributes() : ignored(DefaultBehavior) { }
- AccessibilityObjectInclusion ignored;
+ AXObjectInclusion ignored;
};
HashMap<AXID, CachedAXObjectAttributes> m_idMapping;
@@ -80,34 +82,37 @@ public:
explicit AXObjectCache(const Document*);
~AXObjectCache();
- static AccessibilityObject* focusedUIElementForPage(const Page*);
+ static AXObject* focusedUIElementForPage(const Page*);
// Returns the root object for the entire document.
- AccessibilityObject* rootObject();
+ AXObject* rootObject();
// For AX objects with elements that back them.
- AccessibilityObject* getOrCreate(RenderObject*);
- AccessibilityObject* getOrCreate(Widget*);
- AccessibilityObject* getOrCreate(Node*);
+ AXObject* getOrCreate(RenderObject*);
+ AXObject* getOrCreate(Widget*);
+ AXObject* getOrCreate(Node*);
+ AXObject* getOrCreate(AbstractInlineTextBox*);
// used for objects without backing elements
- AccessibilityObject* getOrCreate(AccessibilityRole);
+ AXObject* getOrCreate(AccessibilityRole);
- // will only return the AccessibilityObject if it already exists
- AccessibilityObject* get(RenderObject*);
- AccessibilityObject* get(Widget*);
- AccessibilityObject* get(Node*);
+ // will only return the AXObject if it already exists
+ AXObject* get(RenderObject*);
+ AXObject* get(Widget*);
+ AXObject* get(Node*);
+ AXObject* get(AbstractInlineTextBox*);
void remove(RenderObject*);
void remove(Node*);
void remove(Widget*);
+ void remove(AbstractInlineTextBox*);
void remove(AXID);
- void detachWrapper(AccessibilityObject*);
- void attachWrapper(AccessibilityObject*);
+ void detachWrapper(AXObject*);
+ void attachWrapper(AXObject*);
void childrenChanged(Node*);
void childrenChanged(RenderObject*);
- void childrenChanged(AccessibilityObject*);
+ void childrenChanged(AXObject*);
void checkedStateChanged(Node*);
void selectedChildrenChanged(Node*);
void selectedChildrenChanged(RenderObject*);
@@ -115,7 +120,7 @@ public:
// Called by a node when text or a text equivalent (e.g. alt) attribute is changed.
void textChanged(Node*);
void textChanged(RenderObject*);
- // Called when a node has just been attached, so we can make sure we have the right subclass of AccessibilityObject.
+ // Called when a node has just been attached, so we can make sure we have the right subclass of AXObject.
void updateCacheAfterNodeIsAttached(Node*);
void handleActiveDescendantChanged(Node*);
@@ -128,15 +133,12 @@ public:
void handleAttributeChanged(const QualifiedName& attrName, Element*);
void recomputeIsIgnored(RenderObject* renderer);
-#if HAVE(ACCESSIBILITY)
static void enableAccessibility() { gAccessibilityEnabled = true; }
static bool accessibilityEnabled() { return gAccessibilityEnabled; }
-#else
- static void enableAccessibility() { }
- static bool accessibilityEnabled() { return false; }
-#endif
+ static void setInlineTextBoxAccessibility(bool flag) { gInlineTextBoxAccessibility = flag; }
+ static bool inlineTextBoxAccessibility() { return gInlineTextBoxAccessibility; }
- void removeAXID(AccessibilityObject*);
+ void removeAXID(AXObject*);
bool isIDinUse(AXID id) const { return m_idsInUse.contains(id); }
Element* rootAXEditableElement(Node*);
@@ -144,7 +146,7 @@ public:
bool nodeIsTextControl(const Node*);
AXID platformGenerateAXID() const;
- AccessibilityObject* objectFromAXID(AXID id) const { return m_objects.get(id); }
+ AXObject* objectFromAXID(AXID id) const { return m_objects.get(id); }
// Text marker utilities.
void textMarkerDataForVisiblePosition(TextMarkerData&, const VisiblePosition&);
@@ -182,7 +184,7 @@ public:
void postNotification(RenderObject*, AXNotification, bool postToElement, PostType = PostAsynchronously);
void postNotification(Node*, AXNotification, bool postToElement, PostType = PostAsynchronously);
- void postNotification(AccessibilityObject*, Document*, AXNotification, bool postToElement, PostType = PostAsynchronously);
+ void postNotification(AXObject*, Document*, AXNotification, bool postToElement, PostType = PostAsynchronously);
bool nodeHasRole(Node*, const AtomicString& role);
@@ -192,8 +194,8 @@ public:
AXComputedObjectAttributeCache* computedObjectAttributeCache() { return m_computedObjectAttributeCache.get(); }
protected:
- void postPlatformNotification(AccessibilityObject*, AXNotification);
- void textChanged(AccessibilityObject*);
+ void postPlatformNotification(AXObject*, AXNotification);
+ void textChanged(AXObject*);
void labelChanged(Element*);
// This is a weak reference cache for knowing if Nodes used by TextMarkers are valid.
@@ -203,81 +205,31 @@ protected:
private:
Document* m_document;
- HashMap<AXID, RefPtr<AccessibilityObject> > m_objects;
+ HashMap<AXID, RefPtr<AXObject> > m_objects;
HashMap<RenderObject*, AXID> m_renderObjectMapping;
HashMap<Widget*, AXID> m_widgetObjectMapping;
HashMap<Node*, AXID> m_nodeObjectMapping;
+ HashMap<AbstractInlineTextBox*, AXID> m_inlineTextBoxObjectMapping;
HashSet<Node*> m_textMarkerNodes;
OwnPtr<AXComputedObjectAttributeCache> m_computedObjectAttributeCache;
static bool gAccessibilityEnabled;
+ static bool gInlineTextBoxAccessibility;
HashSet<AXID> m_idsInUse;
Timer<AXObjectCache> m_notificationPostTimer;
- Vector<pair<RefPtr<AccessibilityObject>, AXNotification> > m_notificationsToPost;
+ Vector<pair<RefPtr<AXObject>, AXNotification> > m_notificationsToPost;
void notificationPostTimerFired(Timer<AXObjectCache>*);
- static AccessibilityObject* focusedImageMapUIElement(HTMLAreaElement*);
+ static AXObject* focusedImageMapUIElement(HTMLAreaElement*);
- AXID getAXID(AccessibilityObject*);
+ AXID getAXID(AXObject*);
};
bool nodeHasRole(Node*, const String& role);
// This will let you know if aria-hidden was explicitly set to false.
bool isNodeAriaVisible(Node*);
-#if !HAVE(ACCESSIBILITY)
-inline AccessibilityObjectInclusion AXComputedObjectAttributeCache::getIgnored(AXID) const { return DefaultBehavior; }
-inline void AXComputedObjectAttributeCache::setIgnored(AXID, AccessibilityObjectInclusion) { }
-inline AXObjectCache::AXObjectCache(const Document* doc) : m_document(const_cast<Document*>(doc)), m_notificationPostTimer(this, 0) { }
-inline AXObjectCache::~AXObjectCache() { }
-inline AccessibilityObject* AXObjectCache::focusedUIElementForPage(const Page*) { return 0; }
-inline AccessibilityObject* AXObjectCache::get(RenderObject*) { return 0; }
-inline AccessibilityObject* AXObjectCache::get(Node*) { return 0; }
-inline AccessibilityObject* AXObjectCache::get(Widget*) { return 0; }
-inline AccessibilityObject* AXObjectCache::getOrCreate(AccessibilityRole) { return 0; }
-inline AccessibilityObject* AXObjectCache::getOrCreate(RenderObject*) { return 0; }
-inline AccessibilityObject* AXObjectCache::getOrCreate(Node*) { return 0; }
-inline AccessibilityObject* AXObjectCache::getOrCreate(Widget*) { return 0; }
-inline AccessibilityObject* AXObjectCache::rootObject() { return 0; }
-inline Element* AXObjectCache::rootAXEditableElement(Node*) { return 0; }
-inline bool nodeHasRole(Node*, const String&) { return false; }
-inline void AXObjectCache::startCachingComputedObjectAttributesUntilTreeMutates() { }
-inline void AXObjectCache::stopCachingComputedObjectAttributes() { }
-inline bool isNodeAriaVisible(Node*) { return true; }
-inline const Element* AXObjectCache::rootAXEditableElement(const Node*) { return 0; }
-inline void AXObjectCache::attachWrapper(AccessibilityObject*) { }
-inline void AXObjectCache::checkedStateChanged(Node*) { }
-inline void AXObjectCache::childrenChanged(RenderObject*) { }
-inline void AXObjectCache::childrenChanged(Node*) { }
-inline void AXObjectCache::childrenChanged(AccessibilityObject*) { }
-inline void AXObjectCache::textChanged(RenderObject*) { }
-inline void AXObjectCache::textChanged(Node*) { }
-inline void AXObjectCache::textChanged(AccessibilityObject*) { }
-inline void AXObjectCache::updateCacheAfterNodeIsAttached(Node*) { }
-inline void AXObjectCache::detachWrapper(AccessibilityObject*) { }
-inline void AXObjectCache::handleActiveDescendantChanged(Node*) { }
-inline void AXObjectCache::handleAriaExpandedChange(Node*) { }
-inline void AXObjectCache::handleAriaRoleChanged(Node*) { }
-inline void AXObjectCache::handleFocusedUIElementChanged(Node*, Node*) { }
-inline void AXObjectCache::handleScrollbarUpdate(ScrollView*) { }
-inline void AXObjectCache::handleAttributeChanged(const QualifiedName&, Element*) { }
-inline void AXObjectCache::recomputeIsIgnored(RenderObject*) { }
-inline void AXObjectCache::handleScrolledToAnchor(const Node*) { }
-inline void AXObjectCache::nodeTextChangeNotification(Node*, AXTextChange, unsigned, const String&) { }
-inline void AXObjectCache::nodeTextChangePlatformNotification(AccessibilityObject*, AXTextChange, unsigned, const String&) { }
-inline void AXObjectCache::postNotification(AccessibilityObject*, Document*, AXNotification, bool, PostType) { }
-inline void AXObjectCache::postNotification(RenderObject*, AXNotification, bool, PostType) { }
-inline void AXObjectCache::postNotification(Node*, AXNotification, bool, PostType) { }
-inline void AXObjectCache::postPlatformNotification(AccessibilityObject*, AXNotification) { }
-inline void AXObjectCache::remove(AXID) { }
-inline void AXObjectCache::remove(RenderObject*) { }
-inline void AXObjectCache::remove(Node*) { }
-inline void AXObjectCache::remove(Widget*) { }
-inline void AXObjectCache::selectedChildrenChanged(RenderObject*) { }
-inline void AXObjectCache::selectedChildrenChanged(Node*) { }
-#endif
-
}
#endif
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AXProgressIndicator.cpp b/chromium/third_party/WebKit/Source/core/accessibility/AXProgressIndicator.cpp
new file mode 100644
index 00000000000..72a1482233d
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/accessibility/AXProgressIndicator.cpp
@@ -0,0 +1,80 @@
+/*
+ * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ */
+
+#include "config.h"
+#include "core/accessibility/AXProgressIndicator.h"
+
+#include "core/html/HTMLProgressElement.h"
+#include "core/rendering/RenderProgress.h"
+#include "platform/FloatConversion.h"
+
+namespace WebCore {
+
+using namespace HTMLNames;
+
+AXProgressIndicator::AXProgressIndicator(RenderProgress* renderer)
+ : AXRenderObject(renderer)
+{
+}
+
+PassRefPtr<AXProgressIndicator> AXProgressIndicator::create(RenderProgress* renderer)
+{
+ return adoptRef(new AXProgressIndicator(renderer));
+}
+
+bool AXProgressIndicator::computeAccessibilityIsIgnored() const
+{
+ return accessibilityIsIgnoredByDefault();
+}
+
+float AXProgressIndicator::valueForRange() const
+{
+ if (hasAttribute(aria_valuenowAttr))
+ return getAttribute(aria_valuenowAttr).toFloat();
+
+ if (element()->position() >= 0)
+ return narrowPrecisionToFloat(element()->value());
+ // Indeterminate progress bar should return 0.
+ return 0.0f;
+}
+
+float AXProgressIndicator::maxValueForRange() const
+{
+ if (hasAttribute(aria_valuemaxAttr))
+ return getAttribute(aria_valuemaxAttr).toFloat();
+
+ return narrowPrecisionToFloat(element()->max());
+}
+
+float AXProgressIndicator::minValueForRange() const
+{
+ if (hasAttribute(aria_valueminAttr))
+ return getAttribute(aria_valueminAttr).toFloat();
+
+ return 0.0f;
+}
+
+HTMLProgressElement* AXProgressIndicator::element() const
+{
+ return toRenderProgress(m_renderer)->progressElement();
+}
+
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AXProgressIndicator.h b/chromium/third_party/WebKit/Source/core/accessibility/AXProgressIndicator.h
new file mode 100644
index 00000000000..13ea890b43b
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/accessibility/AXProgressIndicator.h
@@ -0,0 +1,53 @@
+/*
+ * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ */
+
+#ifndef AXProgressIndicator_h
+#define AXProgressIndicator_h
+
+#include "core/accessibility/AXRenderObject.h"
+
+namespace WebCore {
+
+class HTMLProgressElement;
+class RenderProgress;
+
+class AXProgressIndicator : public AXRenderObject {
+public:
+ static PassRefPtr<AXProgressIndicator> create(RenderProgress*);
+
+private:
+ virtual AccessibilityRole roleValue() const { return ProgressIndicatorRole; }
+
+ virtual bool isProgressIndicator() const OVERRIDE { return true; }
+
+ virtual float valueForRange() const OVERRIDE;
+ virtual float maxValueForRange() const OVERRIDE;
+ virtual float minValueForRange() const OVERRIDE;
+
+ explicit AXProgressIndicator(RenderProgress*);
+
+ HTMLProgressElement* element() const;
+ virtual bool computeAccessibilityIsIgnored() const OVERRIDE;
+};
+
+
+} // namespace WebCore
+
+#endif // AXProgressIndicator_h
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AXRenderObject.cpp b/chromium/third_party/WebKit/Source/core/accessibility/AXRenderObject.cpp
new file mode 100644
index 00000000000..595135959b6
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/accessibility/AXRenderObject.cpp
@@ -0,0 +1,2368 @@
+/*
+* Copyright (C) 2008 Apple Inc. All rights reserved.
+*
+* Redistribution and use in source and binary forms, with or without
+* modification, are permitted provided that the following conditions
+* are met:
+*
+* 1. Redistributions of source code must retain the above copyright
+* notice, this list of conditions and the following disclaimer.
+* 2. Redistributions in binary form must reproduce the above copyright
+* notice, this list of conditions and the following disclaimer in the
+* documentation and/or other materials provided with the distribution.
+* 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+* its contributors may be used to endorse or promote products derived
+* from this software without specific prior written permission.
+*
+* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+#include "config.h"
+#include "core/accessibility/AXRenderObject.h"
+
+#include "bindings/v8/ExceptionStatePlaceholder.h"
+#include "core/accessibility/AXImageMapLink.h"
+#include "core/accessibility/AXInlineTextBox.h"
+#include "core/accessibility/AXObjectCache.h"
+#include "core/accessibility/AXSVGRoot.h"
+#include "core/accessibility/AXSpinButton.h"
+#include "core/accessibility/AXTable.h"
+#include "core/dom/ElementTraversal.h"
+#include "core/dom/shadow/ShadowRoot.h"
+#include "core/editing/FrameSelection.h"
+#include "core/editing/RenderedPosition.h"
+#include "core/editing/TextIterator.h"
+#include "core/editing/VisibleUnits.h"
+#include "core/editing/htmlediting.h"
+#include "core/frame/Frame.h"
+#include "core/html/HTMLHtmlElement.h"
+#include "core/html/HTMLImageElement.h"
+#include "core/html/HTMLLabelElement.h"
+#include "core/html/HTMLOptionElement.h"
+#include "core/html/HTMLSelectElement.h"
+#include "core/html/HTMLTextAreaElement.h"
+#include "core/html/shadow/ShadowElementNames.h"
+#include "core/loader/ProgressTracker.h"
+#include "core/page/Page.h"
+#include "core/rendering/HitTestResult.h"
+#include "core/rendering/RenderFieldset.h"
+#include "core/rendering/RenderFileUploadControl.h"
+#include "core/rendering/RenderHTMLCanvas.h"
+#include "core/rendering/RenderImage.h"
+#include "core/rendering/RenderInline.h"
+#include "core/rendering/RenderLayer.h"
+#include "core/rendering/RenderListMarker.h"
+#include "core/rendering/RenderMenuList.h"
+#include "core/rendering/RenderTextControlSingleLine.h"
+#include "core/rendering/RenderTextFragment.h"
+#include "core/rendering/RenderView.h"
+#include "core/rendering/RenderWidget.h"
+#include "core/svg/SVGDocument.h"
+#include "core/svg/SVGSVGElement.h"
+#include "core/svg/graphics/SVGImage.h"
+#include "platform/text/PlatformLocale.h"
+#include "wtf/StdLibExtras.h"
+
+using blink::WebLocalizedString;
+using namespace std;
+
+namespace WebCore {
+
+using namespace HTMLNames;
+
+static inline RenderObject* firstChildInContinuation(RenderObject* renderer)
+{
+ RenderObject* r = toRenderInline(renderer)->continuation();
+
+ while (r) {
+ if (r->isRenderBlock())
+ return r;
+ if (RenderObject* child = r->firstChild())
+ return child;
+ r = toRenderInline(r)->continuation();
+ }
+
+ return 0;
+}
+
+static inline bool isInlineWithContinuation(RenderObject* object)
+{
+ if (!object->isBoxModelObject())
+ return false;
+
+ RenderBoxModelObject* renderer = toRenderBoxModelObject(object);
+ if (!renderer->isRenderInline())
+ return false;
+
+ return toRenderInline(renderer)->continuation();
+}
+
+static inline RenderObject* firstChildConsideringContinuation(RenderObject* renderer)
+{
+ RenderObject* firstChild = renderer->firstChild();
+
+ if (!firstChild && isInlineWithContinuation(renderer))
+ firstChild = firstChildInContinuation(renderer);
+
+ return firstChild;
+}
+
+static inline RenderInline* startOfContinuations(RenderObject* r)
+{
+ if (r->isInlineElementContinuation()) {
+ return toRenderInline(r->node()->renderer());
+ }
+
+ // Blocks with a previous continuation always have a next continuation
+ if (r->isRenderBlock() && toRenderBlock(r)->inlineElementContinuation())
+ return toRenderInline(toRenderBlock(r)->inlineElementContinuation()->node()->renderer());
+
+ return 0;
+}
+
+static inline RenderObject* endOfContinuations(RenderObject* renderer)
+{
+ RenderObject* prev = renderer;
+ RenderObject* cur = renderer;
+
+ if (!cur->isRenderInline() && !cur->isRenderBlock())
+ return renderer;
+
+ while (cur) {
+ prev = cur;
+ if (cur->isRenderInline()) {
+ cur = toRenderInline(cur)->inlineElementContinuation();
+ ASSERT(cur || !toRenderInline(prev)->continuation());
+ } else {
+ cur = toRenderBlock(cur)->inlineElementContinuation();
+ }
+ }
+
+ return prev;
+}
+
+static inline bool lastChildHasContinuation(RenderObject* renderer)
+{
+ return renderer->lastChild() && isInlineWithContinuation(renderer->lastChild());
+}
+
+static RenderBoxModelObject* nextContinuation(RenderObject* renderer)
+{
+ ASSERT(renderer);
+ if (renderer->isRenderInline() && !renderer->isReplaced())
+ return toRenderInline(renderer)->continuation();
+ if (renderer->isRenderBlock())
+ return toRenderBlock(renderer)->inlineElementContinuation();
+ return 0;
+}
+
+AXRenderObject::AXRenderObject(RenderObject* renderer)
+ : AXNodeObject(renderer->node())
+ , m_renderer(renderer)
+ , m_cachedElementRectDirty(true)
+{
+#ifndef NDEBUG
+ m_renderer->setHasAXObject(true);
+#endif
+}
+
+PassRefPtr<AXRenderObject> AXRenderObject::create(RenderObject* renderer)
+{
+ return adoptRef(new AXRenderObject(renderer));
+}
+
+AXRenderObject::~AXRenderObject()
+{
+ ASSERT(isDetached());
+}
+
+LayoutRect AXRenderObject::elementRect() const
+{
+ if (!m_explicitElementRect.isEmpty())
+ return m_explicitElementRect;
+ if (!m_renderer)
+ return LayoutRect();
+ if (!m_renderer->isBox())
+ return computeElementRect();
+
+ for (const AXObject* obj = this; obj; obj = obj->parentObject()) {
+ if (obj->isAXRenderObject())
+ toAXRenderObject(obj)->checkCachedElementRect();
+ }
+ for (const AXObject* obj = this; obj; obj = obj->parentObject()) {
+ if (obj->isAXRenderObject())
+ toAXRenderObject(obj)->updateCachedElementRect();
+ }
+
+ return m_cachedElementRect;
+}
+
+void AXRenderObject::setRenderer(RenderObject* renderer)
+{
+ m_renderer = renderer;
+ setNode(renderer->node());
+}
+
+RenderBoxModelObject* AXRenderObject::renderBoxModelObject() const
+{
+ if (!m_renderer || !m_renderer->isBoxModelObject())
+ return 0;
+ return toRenderBoxModelObject(m_renderer);
+}
+
+RenderView* AXRenderObject::topRenderer() const
+{
+ Document* topDoc = topDocument();
+ if (!topDoc)
+ return 0;
+
+ return topDoc->renderView();
+}
+
+Document* AXRenderObject::topDocument() const
+{
+ if (!document())
+ return 0;
+ return document()->topDocument();
+}
+
+bool AXRenderObject::shouldNotifyActiveDescendant() const
+{
+ // We want to notify that the combo box has changed its active descendant,
+ // but we do not want to change the focus, because focus should remain with the combo box.
+ if (isComboBox())
+ return true;
+
+ return shouldFocusActiveDescendant();
+}
+
+ScrollableArea* AXRenderObject::getScrollableAreaIfScrollable() const
+{
+ // If the parent is a scroll view, then this object isn't really scrollable, the parent ScrollView should handle the scrolling.
+ if (parentObject() && parentObject()->isAXScrollView())
+ return 0;
+
+ if (!m_renderer || !m_renderer->isBox())
+ return 0;
+
+ RenderBox* box = toRenderBox(m_renderer);
+ if (!box->canBeScrolledAndHasScrollableArea())
+ return 0;
+
+ return box->scrollableArea();
+}
+
+AccessibilityRole AXRenderObject::determineAccessibilityRole()
+{
+ if (!m_renderer)
+ return UnknownRole;
+
+ m_ariaRole = determineAriaRoleAttribute();
+
+ Node* node = m_renderer->node();
+ AccessibilityRole ariaRole = ariaRoleAttribute();
+ if (ariaRole != UnknownRole)
+ return ariaRole;
+
+ RenderBoxModelObject* cssBox = renderBoxModelObject();
+
+ if (node && node->isLink()) {
+ if (cssBox && cssBox->isImage())
+ return ImageMapRole;
+ return LinkRole;
+ }
+ if (cssBox && cssBox->isListItem())
+ return ListItemRole;
+ if (m_renderer->isListMarker())
+ return ListMarkerRole;
+ if (node && node->hasTagName(buttonTag))
+ return buttonRoleType();
+ if (node && node->hasTagName(legendTag))
+ return LegendRole;
+ if (m_renderer->isText())
+ return StaticTextRole;
+ if (cssBox && cssBox->isImage()) {
+ if (node && node->hasTagName(inputTag))
+ return ariaHasPopup() ? PopUpButtonRole : ButtonRole;
+ if (isSVGImage())
+ return SVGRootRole;
+ return ImageRole;
+ }
+
+ // Note: if JavaScript is disabled, the renderer won't be a RenderHTMLCanvas.
+ if (node && node->hasTagName(canvasTag) && m_renderer->isCanvas())
+ return CanvasRole;
+
+ if (cssBox && cssBox->isRenderView()) {
+ // If the iframe is seamless, it should not be announced as a web area to AT clients.
+ if (document() && document()->shouldDisplaySeamlesslyWithParent())
+ return SeamlessWebAreaRole;
+ return WebAreaRole;
+ }
+
+ if (cssBox && cssBox->isTextField())
+ return TextFieldRole;
+
+ if (cssBox && cssBox->isTextArea())
+ return TextAreaRole;
+
+ if (node && node->hasTagName(inputTag)) {
+ HTMLInputElement* input = toHTMLInputElement(node);
+ if (input->isCheckbox())
+ return CheckBoxRole;
+ if (input->isRadioButton())
+ return RadioButtonRole;
+ if (input->isTextButton())
+ return buttonRoleType();
+
+ const AtomicString& type = input->getAttribute(typeAttr);
+ if (equalIgnoringCase(type, "color"))
+ return ColorWellRole;
+ }
+
+ if (isFileUploadButton())
+ return ButtonRole;
+
+ if (cssBox && cssBox->isMenuList())
+ return PopUpButtonRole;
+
+ if (headingLevel())
+ return HeadingRole;
+
+ if (m_renderer->isSVGImage())
+ return ImageRole;
+ if (m_renderer->isSVGRoot())
+ return SVGRootRole;
+
+ if (node && node->hasTagName(ddTag))
+ return DescriptionListDetailRole;
+
+ if (node && node->hasTagName(dtTag))
+ return DescriptionListTermRole;
+
+ if (node && (node->hasTagName(rpTag) || node->hasTagName(rtTag)))
+ return AnnotationRole;
+
+ // Table sections should be ignored.
+ if (m_renderer->isTableSection())
+ return IgnoredRole;
+
+ if (m_renderer->isHR())
+ return HorizontalRuleRole;
+
+ if (node && node->hasTagName(pTag))
+ return ParagraphRole;
+
+ if (node && isHTMLLabelElement(node))
+ return LabelRole;
+
+ if (node && node->hasTagName(divTag))
+ return DivRole;
+
+ if (node && node->hasTagName(formTag))
+ return FormRole;
+
+ if (node && node->hasTagName(articleTag))
+ return ArticleRole;
+
+ if (node && node->hasTagName(mainTag))
+ return MainRole;
+
+ if (node && node->hasTagName(navTag))
+ return NavigationRole;
+
+ if (node && node->hasTagName(asideTag))
+ return ComplementaryRole;
+
+ if (node && node->hasTagName(sectionTag))
+ return RegionRole;
+
+ if (node && node->hasTagName(addressTag))
+ return ContentInfoRole;
+
+ if (node && node->hasTagName(dialogTag))
+ return DialogRole;
+
+ // The HTML element should not be exposed as an element. That's what the RenderView element does.
+ if (node && isHTMLHtmlElement(node))
+ return IgnoredRole;
+
+ // There should only be one banner/contentInfo per page. If header/footer are being used within an article or section
+ // then it should not be exposed as whole page's banner/contentInfo
+ if (node && node->hasTagName(headerTag) && !isDescendantOfElementType(articleTag) && !isDescendantOfElementType(sectionTag))
+ return BannerRole;
+ if (node && node->hasTagName(footerTag) && !isDescendantOfElementType(articleTag) && !isDescendantOfElementType(sectionTag))
+ return FooterRole;
+
+ if (node && node->hasTagName(aTag) && isClickable())
+ return LinkRole;
+
+ if (m_renderer->isRenderBlockFlow())
+ return GroupRole;
+
+ // If the element does not have role, but it has ARIA attributes, accessibility should fallback to exposing it as a group.
+ if (supportsARIAAttributes())
+ return GroupRole;
+
+ return UnknownRole;
+}
+
+void AXRenderObject::init()
+{
+ AXNodeObject::init();
+}
+
+void AXRenderObject::detach()
+{
+ AXNodeObject::detach();
+
+ detachRemoteSVGRoot();
+
+#ifndef NDEBUG
+ if (m_renderer)
+ m_renderer->setHasAXObject(false);
+#endif
+ m_renderer = 0;
+}
+
+//
+// Check object role or purpose.
+//
+
+bool AXRenderObject::isAttachment() const
+{
+ RenderBoxModelObject* renderer = renderBoxModelObject();
+ if (!renderer)
+ return false;
+ // Widgets are the replaced elements that we represent to AX as attachments
+ bool isWidget = renderer->isWidget();
+ ASSERT(!isWidget || (renderer->isReplaced() && !isImage()));
+ return isWidget;
+}
+
+bool AXRenderObject::isFileUploadButton() const
+{
+ if (m_renderer && m_renderer->node() && m_renderer->node()->hasTagName(inputTag)) {
+ HTMLInputElement* input = toHTMLInputElement(m_renderer->node());
+ return input->isFileUpload();
+ }
+
+ return false;
+}
+
+static bool isLinkable(const AXObject& object)
+{
+ if (!object.renderer())
+ return false;
+
+ // See https://wiki.mozilla.org/Accessibility/AT-Windows-API for the elements
+ // Mozilla considers linkable.
+ return object.isLink() || object.isImage() || object.renderer()->isText();
+}
+
+bool AXRenderObject::isLinked() const
+{
+ if (!isLinkable(*this))
+ return false;
+
+ Element* anchor = anchorElement();
+ if (!anchor || !isHTMLAnchorElement(anchor))
+ return false;
+
+ return !toHTMLAnchorElement(anchor)->href().isEmpty();
+}
+
+bool AXRenderObject::isLoaded() const
+{
+ return !m_renderer->document().parser();
+}
+
+bool AXRenderObject::isOffScreen() const
+{
+ ASSERT(m_renderer);
+ IntRect contentRect = pixelSnappedIntRect(m_renderer->absoluteClippedOverflowRect());
+ FrameView* view = m_renderer->frame()->view();
+ IntRect viewRect = view->visibleContentRect();
+ viewRect.intersect(contentRect);
+ return viewRect.isEmpty();
+}
+
+bool AXRenderObject::isReadOnly() const
+{
+ ASSERT(m_renderer);
+
+ if (isWebArea()) {
+ Document& document = m_renderer->document();
+ HTMLElement* body = document.body();
+ if (body && body->rendererIsEditable())
+ return false;
+
+ return !document.rendererIsEditable();
+ }
+
+ return AXNodeObject::isReadOnly();
+}
+
+bool AXRenderObject::isVisited() const
+{
+ // FIXME: Is it a privacy violation to expose visited information to accessibility APIs?
+ return m_renderer->style()->isLink() && m_renderer->style()->insideLink() == InsideVisitedLink;
+}
+
+//
+// Check object state.
+//
+
+bool AXRenderObject::isFocused() const
+{
+ if (!m_renderer)
+ return false;
+
+ Document& document = m_renderer->document();
+ Element* focusedElement = document.focusedElement();
+ if (!focusedElement)
+ return false;
+
+ // A web area is represented by the Document node in the DOM tree, which isn't focusable.
+ // Check instead if the frame's selection controller is focused
+ if (focusedElement == m_renderer->node()
+ || (roleValue() == WebAreaRole && document.frame()->selection().isFocusedAndActive()))
+ return true;
+
+ return false;
+}
+
+bool AXRenderObject::isSelected() const
+{
+ if (!m_renderer)
+ return false;
+
+ Node* node = m_renderer->node();
+ if (!node)
+ return false;
+
+ const AtomicString& ariaSelected = getAttribute(aria_selectedAttr);
+ if (equalIgnoringCase(ariaSelected, "true"))
+ return true;
+
+ if (isTabItem() && isTabItemSelected())
+ return true;
+
+ return false;
+}
+
+//
+// Whether objects are ignored, i.e. not included in the tree.
+//
+
+AXObjectInclusion AXRenderObject::defaultObjectInclusion() const
+{
+ // The following cases can apply to any element that's a subclass of AXRenderObject.
+
+ if (!m_renderer)
+ return IgnoreObject;
+
+ if (m_renderer->style()->visibility() != VISIBLE) {
+ // aria-hidden is meant to override visibility as the determinant in AX hierarchy inclusion.
+ if (equalIgnoringCase(getAttribute(aria_hiddenAttr), "false"))
+ return DefaultBehavior;
+
+ return IgnoreObject;
+ }
+
+ return AXObject::defaultObjectInclusion();
+}
+
+bool AXRenderObject::computeAccessibilityIsIgnored() const
+{
+#ifndef NDEBUG
+ ASSERT(m_initialized);
+#endif
+
+ // Check first if any of the common reasons cause this element to be ignored.
+ // Then process other use cases that need to be applied to all the various roles
+ // that AXRenderObjects take on.
+ AXObjectInclusion decision = defaultObjectInclusion();
+ if (decision == IncludeObject)
+ return false;
+ if (decision == IgnoreObject)
+ return true;
+
+ // If this element is within a parent that cannot have children, it should not be exposed.
+ if (isDescendantOfBarrenParent())
+ return true;
+
+ if (roleValue() == IgnoredRole)
+ return true;
+
+ if (roleValue() == PresentationalRole || inheritsPresentationalRole())
+ return true;
+
+ // An ARIA tree can only have tree items and static text as children.
+ if (!isAllowedChildOfTree())
+ return true;
+
+ // TODO: we should refactor this - but right now this is necessary to make
+ // sure scroll areas stay in the tree.
+ if (isAttachment())
+ return false;
+
+ // ignore popup menu items because AppKit does
+ for (RenderObject* parent = m_renderer->parent(); parent; parent = parent->parent()) {
+ if (parent->isBoxModelObject() && toRenderBoxModelObject(parent)->isMenuList())
+ return true;
+ }
+
+ // find out if this element is inside of a label element.
+ // if so, it may be ignored because it's the label for a checkbox or radio button
+ AXObject* controlObject = correspondingControlForLabelElement();
+ if (controlObject && !controlObject->exposesTitleUIElement() && controlObject->isCheckboxOrRadio())
+ return true;
+
+ // NOTE: BRs always have text boxes now, so the text box check here can be removed
+ if (m_renderer->isText()) {
+ // static text beneath MenuItems and MenuButtons are just reported along with the menu item, so it's ignored on an individual level
+ AXObject* parent = parentObjectUnignored();
+ if (parent && (parent->ariaRoleAttribute() == MenuItemRole || parent->ariaRoleAttribute() == MenuButtonRole))
+ return true;
+ RenderText* renderText = toRenderText(m_renderer);
+ if (m_renderer->isBR() || !renderText->firstTextBox())
+ return true;
+
+ // static text beneath TextControls is reported along with the text control text so it's ignored.
+ for (AXObject* parent = parentObject(); parent; parent = parent->parentObject()) {
+ if (parent->roleValue() == TextFieldRole)
+ return true;
+ }
+
+ // text elements that are just empty whitespace should not be returned
+ return renderText->text().impl()->containsOnlyWhitespace();
+ }
+
+ if (isHeading())
+ return false;
+
+ if (isLink())
+ return false;
+
+ // all controls are accessible
+ if (isControl())
+ return false;
+
+ if (ariaRoleAttribute() != UnknownRole)
+ return false;
+
+ // don't ignore labels, because they serve as TitleUIElements
+ Node* node = m_renderer->node();
+ if (node && isHTMLLabelElement(node))
+ return false;
+
+ // Anything that is content editable should not be ignored.
+ // However, one cannot just call node->rendererIsEditable() since that will ask if its parents
+ // are also editable. Only the top level content editable region should be exposed.
+ if (hasContentEditableAttributeSet())
+ return false;
+
+ // List items play an important role in defining the structure of lists. They should not be ignored.
+ if (roleValue() == ListItemRole)
+ return false;
+
+ if (roleValue() == DialogRole)
+ return false;
+
+ // if this element has aria attributes on it, it should not be ignored.
+ if (supportsARIAAttributes())
+ return false;
+
+ // <span> tags are inline tags and not meant to convey information if they have no other aria
+ // information on them. If we don't ignore them, they may emit signals expected to come from
+ // their parent. In addition, because included spans are GroupRole objects, and GroupRole
+ // objects are often containers with meaningful information, the inclusion of a span can have
+ // the side effect of causing the immediate parent accessible to be ignored. This is especially
+ // problematic for platforms which have distinct roles for textual block elements.
+ if (node && node->hasTagName(spanTag))
+ return true;
+
+ if (m_renderer->isRenderBlockFlow() && m_renderer->childrenInline() && !canSetFocusAttribute())
+ return !toRenderBlock(m_renderer)->firstLineBox() && !mouseButtonListener();
+
+ // ignore images seemingly used as spacers
+ if (isImage()) {
+
+ // If the image can take focus, it should not be ignored, lest the user not be able to interact with something important.
+ if (canSetFocusAttribute())
+ return false;
+
+ if (node && node->isElementNode()) {
+ Element* elt = toElement(node);
+ const AtomicString& alt = elt->getAttribute(altAttr);
+ // don't ignore an image that has an alt tag
+ if (!alt.string().containsOnlyWhitespace())
+ return false;
+ // informal standard is to ignore images with zero-length alt strings
+ if (!alt.isNull())
+ return true;
+ }
+
+ if (isNativeImage() && m_renderer->isImage()) {
+ // check for one-dimensional image
+ RenderImage* image = toRenderImage(m_renderer);
+ if (image->height() <= 1 || image->width() <= 1)
+ return true;
+
+ // check whether rendered image was stretched from one-dimensional file image
+ if (image->cachedImage()) {
+ LayoutSize imageSize = image->cachedImage()->imageSizeForRenderer(m_renderer, image->view()->zoomFactor());
+ return imageSize.height() <= 1 || imageSize.width() <= 1;
+ }
+ }
+ return false;
+ }
+
+ if (isCanvas()) {
+ if (canvasHasFallbackContent())
+ return false;
+ RenderHTMLCanvas* canvas = toRenderHTMLCanvas(m_renderer);
+ if (canvas->height() <= 1 || canvas->width() <= 1)
+ return true;
+ // Otherwise fall through; use presence of help text, title, or description to decide.
+ }
+
+ if (isWebArea() || isSeamlessWebArea() || m_renderer->isListMarker())
+ return false;
+
+ // Using the help text, title or accessibility description (so we
+ // check if there's some kind of accessible name for the element)
+ // to decide an element's visibility is not as definitive as
+ // previous checks, so this should remain as one of the last.
+ //
+ // These checks are simplified in the interest of execution speed;
+ // for example, any element having an alt attribute will make it
+ // not ignored, rather than just images.
+ if (!getAttribute(aria_helpAttr).isEmpty() || !getAttribute(aria_describedbyAttr).isEmpty() || !getAttribute(altAttr).isEmpty() || !getAttribute(titleAttr).isEmpty())
+ return false;
+
+ // Don't ignore generic focusable elements like <div tabindex=0>
+ // unless they're completely empty, with no children.
+ if (isGenericFocusableElement() && node->firstChild())
+ return false;
+
+ if (!ariaAccessibilityDescription().isEmpty())
+ return false;
+
+ // By default, objects should be ignored so that the AX hierarchy is not
+ // filled with unnecessary items.
+ return true;
+}
+
+//
+// Properties of static elements.
+//
+
+const AtomicString& AXRenderObject::accessKey() const
+{
+ Node* node = m_renderer->node();
+ if (!node)
+ return nullAtom;
+ if (!node->isElementNode())
+ return nullAtom;
+ return toElement(node)->getAttribute(accesskeyAttr);
+}
+
+AccessibilityOrientation AXRenderObject::orientation() const
+{
+ const AtomicString& ariaOrientation = getAttribute(aria_orientationAttr);
+ if (equalIgnoringCase(ariaOrientation, "horizontal"))
+ return AccessibilityOrientationHorizontal;
+ if (equalIgnoringCase(ariaOrientation, "vertical"))
+ return AccessibilityOrientationVertical;
+
+ return AXObject::orientation();
+}
+
+String AXRenderObject::text() const
+{
+ if (isPasswordField())
+ return String();
+
+ return AXNodeObject::text();
+}
+
+int AXRenderObject::textLength() const
+{
+ ASSERT(isTextControl());
+
+ if (isPasswordField())
+ return -1; // need to return something distinct from 0
+
+ return text().length();
+}
+
+KURL AXRenderObject::url() const
+{
+ if (isAnchor() && isHTMLAnchorElement(m_renderer->node())) {
+ if (HTMLAnchorElement* anchor = toHTMLAnchorElement(anchorElement()))
+ return anchor->href();
+ }
+
+ if (isWebArea())
+ return m_renderer->document().url();
+
+ if (isImage() && m_renderer->node() && m_renderer->node()->hasTagName(imgTag))
+ return toHTMLImageElement(m_renderer->node())->src();
+
+ if (isInputImage())
+ return toHTMLInputElement(m_renderer->node())->src();
+
+ return KURL();
+}
+
+//
+// Properties of interactive elements.
+//
+
+static String queryString(WebLocalizedString::Name name)
+{
+ return Locale::defaultLocale().queryString(name);
+}
+
+String AXRenderObject::actionVerb() const
+{
+ switch (roleValue()) {
+ case ButtonRole:
+ case ToggleButtonRole:
+ return queryString(WebLocalizedString::AXButtonActionVerb);
+ case TextFieldRole:
+ case TextAreaRole:
+ return queryString(WebLocalizedString::AXTextFieldActionVerb);
+ case RadioButtonRole:
+ return queryString(WebLocalizedString::AXRadioButtonActionVerb);
+ case CheckBoxRole:
+ return queryString(isChecked() ? WebLocalizedString::AXCheckedCheckBoxActionVerb : WebLocalizedString::AXUncheckedCheckBoxActionVerb);
+ case LinkRole:
+ return queryString(WebLocalizedString::AXLinkActionVerb);
+ default:
+ return emptyString();
+ }
+}
+
+void AXRenderObject::selectedChildren(AccessibilityChildrenVector& result)
+{
+ ASSERT(result.isEmpty());
+
+ // only listboxes should be asked for their selected children.
+ AccessibilityRole role = roleValue();
+ if (role == ListBoxRole) // native list boxes would be AXListBoxes, so only check for aria list boxes
+ ariaListboxSelectedChildren(result);
+ else if (role == TreeRole || role == TreeGridRole || role == TableRole)
+ ariaSelectedRows(result);
+}
+
+String AXRenderObject::stringValue() const
+{
+ if (!m_renderer)
+ return String();
+
+ if (isPasswordField())
+ return String();
+
+ RenderBoxModelObject* cssBox = renderBoxModelObject();
+
+ if (ariaRoleAttribute() == StaticTextRole) {
+ String staticText = text();
+ if (!staticText.length())
+ staticText = textUnderElement();
+ return staticText;
+ }
+
+ if (m_renderer->isText())
+ return textUnderElement();
+
+ if (cssBox && cssBox->isMenuList()) {
+ // RenderMenuList will go straight to the text() of its selected item.
+ // This has to be overridden in the case where the selected item has an ARIA label.
+ HTMLSelectElement* selectElement = toHTMLSelectElement(m_renderer->node());
+ int selectedIndex = selectElement->selectedIndex();
+ const Vector<HTMLElement*> listItems = selectElement->listItems();
+ if (selectedIndex >= 0 && static_cast<size_t>(selectedIndex) < listItems.size()) {
+ const AtomicString& overriddenDescription = listItems[selectedIndex]->fastGetAttribute(aria_labelAttr);
+ if (!overriddenDescription.isNull())
+ return overriddenDescription;
+ }
+ return toRenderMenuList(m_renderer)->text();
+ }
+
+ if (m_renderer->isListMarker())
+ return toRenderListMarker(m_renderer)->text();
+
+ if (isWebArea()) {
+ // FIXME: Why would a renderer exist when the Document isn't attached to a frame?
+ if (m_renderer->frame())
+ return String();
+
+ ASSERT_NOT_REACHED();
+ }
+
+ if (isTextControl())
+ return text();
+
+ if (m_renderer->isFileUploadControl())
+ return toRenderFileUploadControl(m_renderer)->fileTextValue();
+
+ // FIXME: We might need to implement a value here for more types
+ // FIXME: It would be better not to advertise a value at all for the types for which we don't implement one;
+ // this would require subclassing or making accessibilityAttributeNames do something other than return a
+ // single static array.
+ return String();
+}
+
+//
+// ARIA attributes.
+//
+
+AXObject* AXRenderObject::activeDescendant() const
+{
+ if (!m_renderer)
+ return 0;
+
+ if (m_renderer->node() && !m_renderer->node()->isElementNode())
+ return 0;
+ Element* element = toElement(m_renderer->node());
+
+ const AtomicString& activeDescendantAttrStr = element->getAttribute(aria_activedescendantAttr);
+ if (activeDescendantAttrStr.isNull() || activeDescendantAttrStr.isEmpty())
+ return 0;
+
+ Element* target = element->treeScope().getElementById(activeDescendantAttrStr);
+ if (!target)
+ return 0;
+
+ AXObject* obj = axObjectCache()->getOrCreate(target);
+
+ // An activedescendant is only useful if it has a renderer, because that's what's needed to post the notification.
+ if (obj && obj->isAXRenderObject())
+ return obj;
+
+ return 0;
+}
+
+void AXRenderObject::ariaFlowToElements(AccessibilityChildrenVector& flowTo) const
+{
+ Vector<Element*> elements;
+ elementsFromAttribute(elements, aria_flowtoAttr);
+
+ AXObjectCache* cache = axObjectCache();
+ unsigned count = elements.size();
+ for (unsigned k = 0; k < count; ++k) {
+ Element* element = elements[k];
+ AXObject* flowToElement = cache->getOrCreate(element);
+ if (flowToElement)
+ flowTo.append(flowToElement);
+ }
+}
+
+bool AXRenderObject::ariaHasPopup() const
+{
+ return elementAttributeValue(aria_haspopupAttr);
+}
+
+bool AXRenderObject::ariaRoleHasPresentationalChildren() const
+{
+ switch (m_ariaRole) {
+ case ButtonRole:
+ case SliderRole:
+ case ImageRole:
+ case ProgressIndicatorRole:
+ case SpinButtonRole:
+ // case SeparatorRole:
+ return true;
+ default:
+ return false;
+ }
+}
+
+bool AXRenderObject::isPresentationalChildOfAriaRole() const
+{
+ // Walk the parent chain looking for a parent that has presentational children
+ AXObject* parent;
+ for (parent = parentObject(); parent && !parent->ariaRoleHasPresentationalChildren(); parent = parent->parentObject())
+ { }
+
+ return parent;
+}
+
+bool AXRenderObject::shouldFocusActiveDescendant() const
+{
+ switch (ariaRoleAttribute()) {
+ case GroupRole:
+ case ListBoxRole:
+ case MenuRole:
+ case MenuBarRole:
+ case RadioGroupRole:
+ case RowRole:
+ case PopUpButtonRole:
+ case ProgressIndicatorRole:
+ case ToolbarRole:
+ case OutlineRole:
+ case TreeRole:
+ case GridRole:
+ /* FIXME: replace these with actual roles when they are added to AccessibilityRole
+ composite
+ alert
+ alertdialog
+ status
+ timer
+ */
+ return true;
+ default:
+ return false;
+ }
+}
+
+bool AXRenderObject::supportsARIADragging() const
+{
+ const AtomicString& grabbed = getAttribute(aria_grabbedAttr);
+ return equalIgnoringCase(grabbed, "true") || equalIgnoringCase(grabbed, "false");
+}
+
+bool AXRenderObject::supportsARIADropping() const
+{
+ const AtomicString& dropEffect = getAttribute(aria_dropeffectAttr);
+ return !dropEffect.isEmpty();
+}
+
+bool AXRenderObject::supportsARIAFlowTo() const
+{
+ return !getAttribute(aria_flowtoAttr).isEmpty();
+}
+
+bool AXRenderObject::supportsARIAOwns() const
+{
+ if (!m_renderer)
+ return false;
+ const AtomicString& ariaOwns = getAttribute(aria_ownsAttr);
+
+ return !ariaOwns.isEmpty();
+}
+
+//
+// ARIA live-region features.
+//
+
+const AtomicString& AXRenderObject::ariaLiveRegionStatus() const
+{
+ DEFINE_STATIC_LOCAL(const AtomicString, liveRegionStatusAssertive, ("assertive", AtomicString::ConstructFromLiteral));
+ DEFINE_STATIC_LOCAL(const AtomicString, liveRegionStatusPolite, ("polite", AtomicString::ConstructFromLiteral));
+ DEFINE_STATIC_LOCAL(const AtomicString, liveRegionStatusOff, ("off", AtomicString::ConstructFromLiteral));
+
+ const AtomicString& liveRegionStatus = getAttribute(aria_liveAttr);
+ // These roles have implicit live region status.
+ if (liveRegionStatus.isEmpty()) {
+ switch (roleValue()) {
+ case AlertDialogRole:
+ case AlertRole:
+ return liveRegionStatusAssertive;
+ case LogRole:
+ case StatusRole:
+ return liveRegionStatusPolite;
+ case TimerRole:
+ case MarqueeRole:
+ return liveRegionStatusOff;
+ default:
+ break;
+ }
+ }
+
+ return liveRegionStatus;
+}
+
+const AtomicString& AXRenderObject::ariaLiveRegionRelevant() const
+{
+ DEFINE_STATIC_LOCAL(const AtomicString, defaultLiveRegionRelevant, ("additions text", AtomicString::ConstructFromLiteral));
+ const AtomicString& relevant = getAttribute(aria_relevantAttr);
+
+ // Default aria-relevant = "additions text".
+ if (relevant.isEmpty())
+ return defaultLiveRegionRelevant;
+
+ return relevant;
+}
+
+bool AXRenderObject::ariaLiveRegionAtomic() const
+{
+ return elementAttributeValue(aria_atomicAttr);
+}
+
+bool AXRenderObject::ariaLiveRegionBusy() const
+{
+ return elementAttributeValue(aria_busyAttr);
+}
+
+//
+// Accessibility Text.
+//
+
+String AXRenderObject::textUnderElement() const
+{
+ if (!m_renderer)
+ return String();
+
+ if (m_renderer->isFileUploadControl())
+ return toRenderFileUploadControl(m_renderer)->buttonValue();
+
+ if (m_renderer->isText())
+ return toRenderText(m_renderer)->plainText();
+
+ return AXNodeObject::textUnderElement();
+}
+
+//
+// Accessibility Text - (To be deprecated).
+//
+
+String AXRenderObject::helpText() const
+{
+ if (!m_renderer)
+ return String();
+
+ const AtomicString& ariaHelp = getAttribute(aria_helpAttr);
+ if (!ariaHelp.isEmpty())
+ return ariaHelp;
+
+ String describedBy = ariaDescribedByAttribute();
+ if (!describedBy.isEmpty())
+ return describedBy;
+
+ String description = accessibilityDescription();
+ for (RenderObject* curr = m_renderer; curr; curr = curr->parent()) {
+ if (curr->node() && curr->node()->isHTMLElement()) {
+ const AtomicString& summary = toElement(curr->node())->getAttribute(summaryAttr);
+ if (!summary.isEmpty())
+ return summary;
+
+ // The title attribute should be used as help text unless it is already being used as descriptive text.
+ const AtomicString& title = toElement(curr->node())->getAttribute(titleAttr);
+ if (!title.isEmpty() && description != title)
+ return title;
+ }
+
+ // Only take help text from an ancestor element if its a group or an unknown role. If help was
+ // added to those kinds of elements, it is likely it was meant for a child element.
+ AXObject* axObj = axObjectCache()->getOrCreate(curr);
+ if (axObj) {
+ AccessibilityRole role = axObj->roleValue();
+ if (role != GroupRole && role != UnknownRole)
+ break;
+ }
+ }
+
+ return String();
+}
+
+//
+// Position and size.
+//
+
+void AXRenderObject::checkCachedElementRect() const
+{
+ if (m_cachedElementRectDirty)
+ return;
+
+ if (!m_renderer)
+ return;
+
+ if (!m_renderer->isBox())
+ return;
+
+ bool dirty = false;
+ RenderBox* box = toRenderBox(m_renderer);
+ if (box->frameRect() != m_cachedFrameRect)
+ dirty = true;
+
+ if (box->canBeScrolledAndHasScrollableArea()) {
+ ScrollableArea* scrollableArea = box->scrollableArea();
+ if (scrollableArea && scrollableArea->scrollPosition() != m_cachedScrollPosition)
+ dirty = true;
+ }
+
+ if (dirty)
+ markCachedElementRectDirty();
+}
+
+void AXRenderObject::updateCachedElementRect() const
+{
+ if (!m_cachedElementRectDirty)
+ return;
+
+ if (!m_renderer)
+ return;
+
+ if (!m_renderer->isBox())
+ return;
+
+ RenderBox* box = toRenderBox(m_renderer);
+ m_cachedFrameRect = box->frameRect();
+
+ if (box->canBeScrolledAndHasScrollableArea()) {
+ ScrollableArea* scrollableArea = box->scrollableArea();
+ if (scrollableArea)
+ m_cachedScrollPosition = scrollableArea->scrollPosition();
+ }
+
+ m_cachedElementRect = computeElementRect();
+ m_cachedElementRectDirty = false;
+}
+
+void AXRenderObject::markCachedElementRectDirty() const
+{
+ if (m_cachedElementRectDirty)
+ return;
+
+ // Marks children recursively, if this element changed.
+ m_cachedElementRectDirty = true;
+ for (AXObject* child = firstChild(); child; child = child->nextSibling())
+ child->markCachedElementRectDirty();
+}
+
+IntPoint AXRenderObject::clickPoint()
+{
+ // Headings are usually much wider than their textual content. If the mid point is used, often it can be wrong.
+ if (isHeading() && children().size() == 1)
+ return children()[0]->clickPoint();
+
+ // use the default position unless this is an editable web area, in which case we use the selection bounds.
+ if (!isWebArea() || isReadOnly())
+ return AXObject::clickPoint();
+
+ LayoutRect bounds = elementRect();
+ return IntPoint(bounds.x() + (bounds.width() / 2), bounds.y() - (bounds.height() / 2));
+}
+
+//
+// Hit testing.
+//
+
+AXObject* AXRenderObject::accessibilityHitTest(const IntPoint& point) const
+{
+ if (!m_renderer || !m_renderer->hasLayer())
+ return 0;
+
+ RenderLayer* layer = toRenderBox(m_renderer)->layer();
+
+ HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::Active);
+ HitTestResult hitTestResult = HitTestResult(point);
+ layer->hitTest(request, hitTestResult);
+ if (!hitTestResult.innerNode())
+ return 0;
+ Node* node = hitTestResult.innerNode()->deprecatedShadowAncestorNode();
+
+ if (isHTMLAreaElement(node))
+ return accessibilityImageMapHitTest(toHTMLAreaElement(node), point);
+
+ if (node->hasTagName(optionTag))
+ node = toHTMLOptionElement(node)->ownerSelectElement();
+
+ RenderObject* obj = node->renderer();
+ if (!obj)
+ return 0;
+
+ AXObject* result = obj->document().axObjectCache()->getOrCreate(obj);
+ result->updateChildrenIfNecessary();
+
+ // Allow the element to perform any hit-testing it might need to do to reach non-render children.
+ result = result->elementAccessibilityHitTest(point);
+
+ if (result && result->accessibilityIsIgnored()) {
+ // If this element is the label of a control, a hit test should return the control.
+ if (result->isAXRenderObject()) {
+ AXObject* controlObject = toAXRenderObject(result)->correspondingControlForLabelElement();
+ if (controlObject && !controlObject->exposesTitleUIElement())
+ return controlObject;
+ }
+
+ result = result->parentObjectUnignored();
+ }
+
+ return result;
+}
+
+AXObject* AXRenderObject::elementAccessibilityHitTest(const IntPoint& point) const
+{
+ if (isSVGImage())
+ return remoteSVGElementHitTest(point);
+
+ return AXObject::elementAccessibilityHitTest(point);
+}
+
+//
+// High-level accessibility tree access.
+//
+
+AXObject* AXRenderObject::parentObject() const
+{
+ if (!m_renderer)
+ return 0;
+
+ if (ariaRoleAttribute() == MenuBarRole)
+ return axObjectCache()->getOrCreate(m_renderer->parent());
+
+ // menuButton and its corresponding menu are DOM siblings, but Accessibility needs them to be parent/child
+ if (ariaRoleAttribute() == MenuRole) {
+ AXObject* parent = menuButtonForMenu();
+ if (parent)
+ return parent;
+ }
+
+ RenderObject* parentObj = renderParentObject();
+ if (parentObj)
+ return axObjectCache()->getOrCreate(parentObj);
+
+ // WebArea's parent should be the scroll view containing it.
+ if (isWebArea() || isSeamlessWebArea())
+ return axObjectCache()->getOrCreate(m_renderer->frame()->view());
+
+ return 0;
+}
+
+AXObject* AXRenderObject::parentObjectIfExists() const
+{
+ // WebArea's parent should be the scroll view containing it.
+ if (isWebArea() || isSeamlessWebArea())
+ return axObjectCache()->get(m_renderer->frame()->view());
+
+ return axObjectCache()->get(renderParentObject());
+}
+
+//
+// Low-level accessibility tree exploration, only for use within the accessibility module.
+//
+
+AXObject* AXRenderObject::firstChild() const
+{
+ if (!m_renderer)
+ return 0;
+
+ RenderObject* firstChild = firstChildConsideringContinuation(m_renderer);
+
+ if (!firstChild)
+ return 0;
+
+ return axObjectCache()->getOrCreate(firstChild);
+}
+
+AXObject* AXRenderObject::nextSibling() const
+{
+ if (!m_renderer)
+ return 0;
+
+ RenderObject* nextSibling = 0;
+
+ RenderInline* inlineContinuation;
+ if (m_renderer->isRenderBlock() && (inlineContinuation = toRenderBlock(m_renderer)->inlineElementContinuation())) {
+ // Case 1: node is a block and has an inline continuation. Next sibling is the inline continuation's first child.
+ nextSibling = firstChildConsideringContinuation(inlineContinuation);
+ } else if (m_renderer->isAnonymousBlock() && lastChildHasContinuation(m_renderer)) {
+ // Case 2: Anonymous block parent of the start of a continuation - skip all the way to
+ // after the parent of the end, since everything in between will be linked up via the continuation.
+ RenderObject* lastParent = endOfContinuations(m_renderer->lastChild())->parent();
+ while (lastChildHasContinuation(lastParent))
+ lastParent = endOfContinuations(lastParent->lastChild())->parent();
+ nextSibling = lastParent->nextSibling();
+ } else if (RenderObject* ns = m_renderer->nextSibling()) {
+ // Case 3: node has an actual next sibling
+ nextSibling = ns;
+ } else if (isInlineWithContinuation(m_renderer)) {
+ // Case 4: node is an inline with a continuation. Next sibling is the next sibling of the end
+ // of the continuation chain.
+ nextSibling = endOfContinuations(m_renderer)->nextSibling();
+ } else if (isInlineWithContinuation(m_renderer->parent())) {
+ // Case 5: node has no next sibling, and its parent is an inline with a continuation.
+ RenderObject* continuation = toRenderInline(m_renderer->parent())->continuation();
+
+ if (continuation->isRenderBlock()) {
+ // Case 5a: continuation is a block - in this case the block itself is the next sibling.
+ nextSibling = continuation;
+ } else {
+ // Case 5b: continuation is an inline - in this case the inline's first child is the next sibling.
+ nextSibling = firstChildConsideringContinuation(continuation);
+ }
+ }
+
+ if (!nextSibling)
+ return 0;
+
+ return axObjectCache()->getOrCreate(nextSibling);
+}
+
+void AXRenderObject::addChildren()
+{
+ // If the need to add more children in addition to existing children arises,
+ // childrenChanged should have been called, leaving the object with no children.
+ ASSERT(!m_haveChildren);
+
+ m_haveChildren = true;
+
+ if (!canHaveChildren())
+ return;
+
+ for (RefPtr<AXObject> obj = firstChild(); obj; obj = obj->nextSibling())
+ addChild(obj.get());
+
+ addHiddenChildren();
+ addAttachmentChildren();
+ addImageMapChildren();
+ addTextFieldChildren();
+ addCanvasChildren();
+ addRemoteSVGChildren();
+ addInlineTextBoxChildren();
+}
+
+bool AXRenderObject::canHaveChildren() const
+{
+ if (!m_renderer)
+ return false;
+
+ return AXNodeObject::canHaveChildren();
+}
+
+void AXRenderObject::updateChildrenIfNecessary()
+{
+ if (needsToUpdateChildren())
+ clearChildren();
+
+ AXObject::updateChildrenIfNecessary();
+}
+
+void AXRenderObject::clearChildren()
+{
+ AXObject::clearChildren();
+ m_childrenDirty = false;
+}
+
+AXObject* AXRenderObject::observableObject() const
+{
+ // Find the object going up the parent chain that is used in accessibility to monitor certain notifications.
+ for (RenderObject* renderer = m_renderer; renderer && renderer->node(); renderer = renderer->parent()) {
+ if (renderObjectIsObservable(renderer))
+ return axObjectCache()->getOrCreate(renderer);
+ }
+
+ return 0;
+}
+
+//
+// Properties of the object's owning document or page.
+//
+
+double AXRenderObject::estimatedLoadingProgress() const
+{
+ if (!m_renderer)
+ return 0;
+
+ if (isLoaded())
+ return 1.0;
+
+ if (Page* page = m_renderer->document().page())
+ return page->progress().estimatedProgress();
+ return 0;
+}
+
+//
+// DOM and Render tree access.
+//
+
+Node* AXRenderObject::node() const
+{
+ return m_renderer ? m_renderer->node() : 0;
+}
+
+Document* AXRenderObject::document() const
+{
+ if (!m_renderer)
+ return 0;
+ return &m_renderer->document();
+}
+
+FrameView* AXRenderObject::documentFrameView() const
+{
+ if (!m_renderer)
+ return 0;
+
+ // this is the RenderObject's Document's Frame's FrameView
+ return m_renderer->document().view();
+}
+
+Element* AXRenderObject::anchorElement() const
+{
+ if (!m_renderer)
+ return 0;
+
+ AXObjectCache* cache = axObjectCache();
+ RenderObject* currRenderer;
+
+ // Search up the render tree for a RenderObject with a DOM node. Defer to an earlier continuation, though.
+ for (currRenderer = m_renderer; currRenderer && !currRenderer->node(); currRenderer = currRenderer->parent()) {
+ if (currRenderer->isAnonymousBlock()) {
+ RenderObject* continuation = toRenderBlock(currRenderer)->continuation();
+ if (continuation)
+ return cache->getOrCreate(continuation)->anchorElement();
+ }
+ }
+
+ // bail if none found
+ if (!currRenderer)
+ return 0;
+
+ // search up the DOM tree for an anchor element
+ // NOTE: this assumes that any non-image with an anchor is an HTMLAnchorElement
+ Node* node = currRenderer->node();
+ for ( ; node; node = node->parentNode()) {
+ if (isHTMLAnchorElement(node) || (node->renderer() && cache->getOrCreate(node->renderer())->isAnchor()))
+ return toElement(node);
+ }
+
+ return 0;
+}
+
+Widget* AXRenderObject::widgetForAttachmentView() const
+{
+ if (!isAttachment())
+ return 0;
+ return toRenderWidget(m_renderer)->widget();
+}
+
+//
+// Selected text.
+//
+
+AXObject::PlainTextRange AXRenderObject::selectedTextRange() const
+{
+ ASSERT(isTextControl());
+
+ if (isPasswordField())
+ return PlainTextRange();
+
+ AccessibilityRole ariaRole = ariaRoleAttribute();
+ if (isNativeTextControl() && ariaRole == UnknownRole && m_renderer->isTextControl()) {
+ HTMLTextFormControlElement* textControl = toRenderTextControl(m_renderer)->textFormControlElement();
+ return PlainTextRange(textControl->selectionStart(), textControl->selectionEnd() - textControl->selectionStart());
+ }
+
+ if (ariaRole == UnknownRole)
+ return PlainTextRange();
+
+ return ariaSelectedTextRange();
+}
+
+VisibleSelection AXRenderObject::selection() const
+{
+ return m_renderer->frame()->selection().selection();
+}
+
+String AXRenderObject::selectedText() const
+{
+ ASSERT(isTextControl());
+
+ if (isPasswordField())
+ return String(); // need to return something distinct from empty string
+
+ if (isNativeTextControl() && m_renderer->isTextControl()) {
+ HTMLTextFormControlElement* textControl = toRenderTextControl(m_renderer)->textFormControlElement();
+ return textControl->selectedText();
+ }
+
+ if (ariaRoleAttribute() == UnknownRole)
+ return String();
+
+ return stringForRange(ariaSelectedTextRange());
+}
+
+//
+// Modify or take an action on an object.
+//
+
+void AXRenderObject::setSelectedTextRange(const PlainTextRange& range)
+{
+ if (isNativeTextControl() && m_renderer->isTextControl()) {
+ HTMLTextFormControlElement* textControl = toRenderTextControl(m_renderer)->textFormControlElement();
+ textControl->setSelectionRange(range.start, range.start + range.length);
+ return;
+ }
+
+ Document& document = m_renderer->document();
+ Frame* frame = document.frame();
+ if (!frame)
+ return;
+ Node* node = m_renderer->node();
+ frame->selection().setSelection(VisibleSelection(Position(node, range.start, Position::PositionIsOffsetInAnchor),
+ Position(node, range.start + range.length, Position::PositionIsOffsetInAnchor), DOWNSTREAM));
+}
+
+void AXRenderObject::setValue(const String& string)
+{
+ if (!node() || !node()->isElementNode())
+ return;
+ if (!m_renderer || !m_renderer->isBoxModelObject())
+ return;
+
+ RenderBoxModelObject* renderer = toRenderBoxModelObject(m_renderer);
+ if (renderer->isTextField() && node()->hasTagName(inputTag)) {
+ toHTMLInputElement(node())->setValue(string);
+ } else if (renderer->isTextArea() && node()->hasTagName(textareaTag)) {
+ toHTMLTextAreaElement(node())->setValue(string);
+ }
+}
+
+// FIXME: This function should use an IntSize to avoid the conversion below.
+void AXRenderObject::scrollTo(const IntPoint& point) const
+{
+ if (!m_renderer || !m_renderer->isBox())
+ return;
+
+ RenderBox* box = toRenderBox(m_renderer);
+ if (!box->canBeScrolledAndHasScrollableArea())
+ return;
+
+ box->scrollToOffset(IntSize(point.x(), point.y()));
+}
+
+//
+// Notifications that this object may have changed.
+//
+
+void AXRenderObject::handleActiveDescendantChanged()
+{
+ Element* element = toElement(renderer()->node());
+ if (!element)
+ return;
+ Document& doc = renderer()->document();
+ if (!doc.frame()->selection().isFocusedAndActive() || doc.focusedElement() != element)
+ return;
+ AXRenderObject* activedescendant = toAXRenderObject(activeDescendant());
+
+ if (activedescendant && shouldNotifyActiveDescendant())
+ doc.axObjectCache()->postNotification(m_renderer, AXObjectCache::AXActiveDescendantChanged, true);
+}
+
+void AXRenderObject::handleAriaExpandedChanged()
+{
+ // Find if a parent of this object should handle aria-expanded changes.
+ AXObject* containerParent = this->parentObject();
+ while (containerParent) {
+ bool foundParent = false;
+
+ switch (containerParent->roleValue()) {
+ case TreeRole:
+ case TreeGridRole:
+ case GridRole:
+ case TableRole:
+ case BrowserRole:
+ foundParent = true;
+ break;
+ default:
+ break;
+ }
+
+ if (foundParent)
+ break;
+
+ containerParent = containerParent->parentObject();
+ }
+
+ // Post that the row count changed.
+ if (containerParent)
+ axObjectCache()->postNotification(containerParent, document(), AXObjectCache::AXRowCountChanged, true);
+
+ // Post that the specific row either collapsed or expanded.
+ if (roleValue() == RowRole || roleValue() == TreeItemRole)
+ axObjectCache()->postNotification(this, document(), isExpanded() ? AXObjectCache::AXRowExpanded : AXObjectCache::AXRowCollapsed, true);
+}
+
+void AXRenderObject::textChanged()
+{
+ if (!m_renderer)
+ return;
+
+ if (AXObjectCache::inlineTextBoxAccessibility() && roleValue() == StaticTextRole)
+ childrenChanged();
+
+ // Do this last - AXNodeObject::textChanged posts live region announcements,
+ // and we should update the inline text boxes first.
+ AXNodeObject::textChanged();
+}
+
+//
+// Text metrics. Most of these should be deprecated, needs major cleanup.
+//
+
+// NOTE: Consider providing this utility method as AX API
+int AXRenderObject::index(const VisiblePosition& position) const
+{
+ if (position.isNull() || !isTextControl())
+ return -1;
+
+ if (renderObjectContainsPosition(m_renderer, position.deepEquivalent()))
+ return indexForVisiblePosition(position);
+
+ return -1;
+}
+
+VisiblePosition AXRenderObject::visiblePositionForIndex(int index) const
+{
+ if (!m_renderer)
+ return VisiblePosition();
+
+ if (isNativeTextControl() && m_renderer->isTextControl())
+ return toRenderTextControl(m_renderer)->textFormControlElement()->visiblePositionForIndex(index);
+
+ if (!allowsTextRanges() && !m_renderer->isText())
+ return VisiblePosition();
+
+ Node* node = m_renderer->node();
+ if (!node)
+ return VisiblePosition();
+
+ if (index <= 0)
+ return VisiblePosition(firstPositionInOrBeforeNode(node), DOWNSTREAM);
+
+ RefPtr<Range> range = Range::create(m_renderer->document());
+ range->selectNodeContents(node, IGNORE_EXCEPTION);
+ CharacterIterator it(range.get());
+ it.advance(index - 1);
+ return VisiblePosition(Position(it.range()->endContainer(), it.range()->endOffset(), Position::PositionIsOffsetInAnch\
+or), UPSTREAM);
+}
+
+int AXRenderObject::indexForVisiblePosition(const VisiblePosition& pos) const
+{
+ if (isNativeTextControl() && m_renderer->isTextControl()) {
+ HTMLTextFormControlElement* textControl = toRenderTextControl(m_renderer)->textFormControlElement();
+ return textControl->indexForVisiblePosition(pos);
+ }
+
+ if (!isTextControl())
+ return 0;
+
+ Node* node = m_renderer->node();
+ if (!node)
+ return 0;
+
+ Position indexPosition = pos.deepEquivalent();
+ if (indexPosition.isNull() || highestEditableRoot(indexPosition, HasEditableAXRole) != node)
+ return 0;
+
+ RefPtr<Range> range = Range::create(m_renderer->document());
+ range->setStart(node, 0, IGNORE_EXCEPTION);
+ range->setEnd(indexPosition, IGNORE_EXCEPTION);
+
+ return TextIterator::rangeLength(range.get());
+}
+
+void AXRenderObject::addInlineTextBoxChildren()
+{
+ if (!axObjectCache()->inlineTextBoxAccessibility())
+ return;
+
+ if (!renderer() || !renderer()->isText())
+ return;
+
+ RenderText* renderText = toRenderText(renderer());
+ if (renderText->needsLayout())
+ renderText->document().updateLayoutIgnorePendingStylesheets();
+
+ for (RefPtr<AbstractInlineTextBox> box = renderText->firstAbstractInlineTextBox(); box.get(); box = box->nextInlineTextBox()) {
+ AXObject* axObject = axObjectCache()->getOrCreate(box.get());
+ if (!axObject->accessibilityIsIgnored())
+ m_children.append(axObject);
+ }
+}
+
+void AXRenderObject::lineBreaks(Vector<int>& lineBreaks) const
+{
+ if (!isTextControl())
+ return;
+
+ VisiblePosition visiblePos = visiblePositionForIndex(0);
+ VisiblePosition savedVisiblePos = visiblePos;
+ visiblePos = nextLinePosition(visiblePos, 0);
+ while (!visiblePos.isNull() && visiblePos != savedVisiblePos) {
+ lineBreaks.append(indexForVisiblePosition(visiblePos));
+ savedVisiblePos = visiblePos;
+ visiblePos = nextLinePosition(visiblePos, 0);
+ }
+}
+
+// A substring of the text associated with this accessibility object that is
+// specified by the given character range.
+String AXRenderObject::stringForRange(const PlainTextRange& range) const
+{
+ if (!range.length)
+ return String();
+
+ if (!isTextControl())
+ return String();
+
+ String elementText = isPasswordField() ? String() : text();
+ if (range.start + range.length > elementText.length())
+ return String();
+
+ return elementText.substring(range.start, range.length);
+}
+
+//
+// Private.
+//
+
+bool AXRenderObject::isAllowedChildOfTree() const
+{
+ // Determine if this is in a tree. If so, we apply special behavior to make it work like an AXOutline.
+ AXObject* axObj = parentObject();
+ bool isInTree = false;
+ while (axObj) {
+ if (axObj->isTree()) {
+ isInTree = true;
+ break;
+ }
+ axObj = axObj->parentObject();
+ }
+
+ // If the object is in a tree, only tree items should be exposed (and the children of tree items).
+ if (isInTree) {
+ AccessibilityRole role = roleValue();
+ if (role != TreeItemRole && role != StaticTextRole)
+ return false;
+ }
+ return true;
+}
+
+void AXRenderObject::ariaListboxSelectedChildren(AccessibilityChildrenVector& result)
+{
+ bool isMulti = isMultiSelectable();
+
+ AccessibilityChildrenVector childObjects = children();
+ unsigned childrenSize = childObjects.size();
+ for (unsigned k = 0; k < childrenSize; ++k) {
+ // Every child should have aria-role option, and if so, check for selected attribute/state.
+ AXObject* child = childObjects[k].get();
+ if (child->isSelected() && child->ariaRoleAttribute() == ListBoxOptionRole) {
+ result.append(child);
+ if (!isMulti)
+ return;
+ }
+ }
+}
+
+AXObject::PlainTextRange AXRenderObject::ariaSelectedTextRange() const
+{
+ Node* node = m_renderer->node();
+ if (!node)
+ return PlainTextRange();
+
+ VisibleSelection visibleSelection = selection();
+ RefPtr<Range> currentSelectionRange = visibleSelection.toNormalizedRange();
+ if (!currentSelectionRange || !currentSelectionRange->intersectsNode(node, IGNORE_EXCEPTION))
+ return PlainTextRange();
+
+ int start = indexForVisiblePosition(visibleSelection.start());
+ int end = indexForVisiblePosition(visibleSelection.end());
+
+ return PlainTextRange(start, end - start);
+}
+
+bool AXRenderObject::nodeIsTextControl(const Node* node) const
+{
+ if (!node)
+ return false;
+
+ const AXObject* axObjectForNode = axObjectCache()->getOrCreate(const_cast<Node*>(node));
+ if (!axObjectForNode)
+ return false;
+
+ return axObjectForNode->isTextControl();
+}
+
+bool AXRenderObject::isTabItemSelected() const
+{
+ if (!isTabItem() || !m_renderer)
+ return false;
+
+ Node* node = m_renderer->node();
+ if (!node || !node->isElementNode())
+ return false;
+
+ // The ARIA spec says a tab item can also be selected if it is aria-labeled by a tabpanel
+ // that has keyboard focus inside of it, or if a tabpanel in its aria-controls list has KB
+ // focus inside of it.
+ AXObject* focusedElement = focusedUIElement();
+ if (!focusedElement)
+ return false;
+
+ Vector<Element*> elements;
+ elementsFromAttribute(elements, aria_controlsAttr);
+
+ unsigned count = elements.size();
+ for (unsigned k = 0; k < count; ++k) {
+ Element* element = elements[k];
+ AXObject* tabPanel = axObjectCache()->getOrCreate(element);
+
+ // A tab item should only control tab panels.
+ if (!tabPanel || tabPanel->roleValue() != TabPanelRole)
+ continue;
+
+ AXObject* checkFocusElement = focusedElement;
+ // Check if the focused element is a descendant of the element controlled by the tab item.
+ while (checkFocusElement) {
+ if (tabPanel == checkFocusElement)
+ return true;
+ checkFocusElement = checkFocusElement->parentObject();
+ }
+ }
+
+ return false;
+}
+
+AXObject* AXRenderObject::internalLinkElement() const
+{
+ Element* element = anchorElement();
+ if (!element)
+ return 0;
+
+ // Right now, we do not support ARIA links as internal link elements
+ if (!isHTMLAnchorElement(element))
+ return 0;
+ HTMLAnchorElement* anchor = toHTMLAnchorElement(element);
+
+ KURL linkURL = anchor->href();
+ String fragmentIdentifier = linkURL.fragmentIdentifier();
+ if (fragmentIdentifier.isEmpty())
+ return 0;
+
+ // check if URL is the same as current URL
+ KURL documentURL = m_renderer->document().url();
+ if (!equalIgnoringFragmentIdentifier(documentURL, linkURL))
+ return 0;
+
+ Node* linkedNode = m_renderer->document().findAnchor(fragmentIdentifier);
+ if (!linkedNode)
+ return 0;
+
+ // The element we find may not be accessible, so find the first accessible object.
+ return firstAccessibleObjectFromNode(linkedNode);
+}
+
+AXObject* AXRenderObject::accessibilityImageMapHitTest(HTMLAreaElement* area, const IntPoint& point) const
+{
+ if (!area)
+ return 0;
+
+ AXObject* parent = axObjectCache()->getOrCreate(area->imageElement());
+ if (!parent)
+ return 0;
+
+ AXObject::AccessibilityChildrenVector children = parent->children();
+ unsigned count = children.size();
+ for (unsigned k = 0; k < count; ++k) {
+ if (children[k]->elementRect().contains(point))
+ return children[k].get();
+ }
+
+ return 0;
+}
+
+bool AXRenderObject::renderObjectIsObservable(RenderObject* renderer) const
+{
+ // AX clients will listen for AXValueChange on a text control.
+ if (renderer->isTextControl())
+ return true;
+
+ // AX clients will listen for AXSelectedChildrenChanged on listboxes.
+ Node* node = renderer->node();
+ if (nodeHasRole(node, "listbox") || (renderer->isBoxModelObject() && toRenderBoxModelObject(renderer)->isListBox()))
+ return true;
+
+ // Textboxes should send out notifications.
+ if (nodeHasRole(node, "textbox"))
+ return true;
+
+ return false;
+}
+
+RenderObject* AXRenderObject::renderParentObject() const
+{
+ if (!m_renderer)
+ return 0;
+
+ RenderObject* parent = m_renderer->parent();
+
+ RenderObject* startOfConts = 0;
+ RenderObject* firstChild = 0;
+ if (m_renderer->isRenderBlock() && (startOfConts = startOfContinuations(m_renderer))) {
+ // Case 1: node is a block and is an inline's continuation. Parent
+ // is the start of the continuation chain.
+ parent = startOfConts;
+ } else if (parent && parent->isRenderInline() && (startOfConts = startOfContinuations(parent))) {
+ // Case 2: node's parent is an inline which is some node's continuation; parent is
+ // the earliest node in the continuation chain.
+ parent = startOfConts;
+ } else if (parent && (firstChild = parent->firstChild()) && firstChild->node()) {
+ // Case 3: The first sibling is the beginning of a continuation chain. Find the origin of that continuation.
+ // Get the node's renderer and follow that continuation chain until the first child is found.
+ RenderObject* nodeRenderFirstChild = firstChild->node()->renderer();
+ while (nodeRenderFirstChild != firstChild) {
+ for (RenderObject* contsTest = nodeRenderFirstChild; contsTest; contsTest = nextContinuation(contsTest)) {
+ if (contsTest == firstChild) {
+ parent = nodeRenderFirstChild->parent();
+ break;
+ }
+ }
+ if (firstChild == parent->firstChild())
+ break;
+ firstChild = parent->firstChild();
+ if (!firstChild->node())
+ break;
+ nodeRenderFirstChild = firstChild->node()->renderer();
+ }
+ }
+
+ return parent;
+}
+
+bool AXRenderObject::isDescendantOfElementType(const QualifiedName& tagName) const
+{
+ for (RenderObject* parent = m_renderer->parent(); parent; parent = parent->parent()) {
+ if (parent->node() && parent->node()->hasTagName(tagName))
+ return true;
+ }
+ return false;
+}
+
+bool AXRenderObject::isSVGImage() const
+{
+ return remoteSVGRootElement();
+}
+
+void AXRenderObject::detachRemoteSVGRoot()
+{
+ if (AXSVGRoot* root = remoteSVGRootElement())
+ root->setParent(0);
+}
+
+AXSVGRoot* AXRenderObject::remoteSVGRootElement() const
+{
+ if (!m_renderer || !m_renderer->isRenderImage())
+ return 0;
+
+ ImageResource* cachedImage = toRenderImage(m_renderer)->cachedImage();
+ if (!cachedImage)
+ return 0;
+
+ Image* image = cachedImage->image();
+ if (!image || !image->isSVGImage())
+ return 0;
+
+ FrameView* frameView = toSVGImage(image)->frameView();
+ if (!frameView)
+ return 0;
+ Document* doc = frameView->frame().document();
+ if (!doc || !doc->isSVGDocument())
+ return 0;
+
+ SVGSVGElement* rootElement = toSVGDocument(doc)->rootElement();
+ if (!rootElement)
+ return 0;
+ RenderObject* rendererRoot = rootElement->renderer();
+ if (!rendererRoot)
+ return 0;
+
+ AXObject* rootSVGObject = doc->axObjectCache()->getOrCreate(rendererRoot);
+
+ // In order to connect the AX hierarchy from the SVG root element from the loaded resource
+ // the parent must be set, because there's no other way to get back to who created the image.
+ ASSERT(rootSVGObject && rootSVGObject->isAXSVGRoot());
+ if (!rootSVGObject->isAXSVGRoot())
+ return 0;
+
+ return toAXSVGRoot(rootSVGObject);
+}
+
+AXObject* AXRenderObject::remoteSVGElementHitTest(const IntPoint& point) const
+{
+ AXObject* remote = remoteSVGRootElement();
+ if (!remote)
+ return 0;
+
+ IntSize offset = point - roundedIntPoint(elementRect().location());
+ return remote->accessibilityHitTest(IntPoint(offset));
+}
+
+// The boundingBox for elements within the remote SVG element needs to be offset by its position
+// within the parent page, otherwise they are in relative coordinates only.
+void AXRenderObject::offsetBoundingBoxForRemoteSVGElement(LayoutRect& rect) const
+{
+ for (AXObject* parent = parentObject(); parent; parent = parent->parentObject()) {
+ if (parent->isAXSVGRoot()) {
+ rect.moveBy(parent->parentObject()->elementRect().location());
+ break;
+ }
+ }
+}
+
+// Hidden children are those that are not rendered or visible, but are specifically marked as aria-hidden=false,
+// meaning that they should be exposed to the AX hierarchy.
+void AXRenderObject::addHiddenChildren()
+{
+ Node* node = this->node();
+ if (!node)
+ return;
+
+ // First do a quick run through to determine if we have any hidden nodes (most often we will not).
+ // If we do have hidden nodes, we need to determine where to insert them so they match DOM order as close as possible.
+ bool shouldInsertHiddenNodes = false;
+ for (Node* child = node->firstChild(); child; child = child->nextSibling()) {
+ if (!child->renderer() && isNodeAriaVisible(child)) {
+ shouldInsertHiddenNodes = true;
+ break;
+ }
+ }
+
+ if (!shouldInsertHiddenNodes)
+ return;
+
+ // Iterate through all of the children, including those that may have already been added, and
+ // try to insert hidden nodes in the correct place in the DOM order.
+ unsigned insertionIndex = 0;
+ for (Node* child = node->firstChild(); child; child = child->nextSibling()) {
+ if (child->renderer()) {
+ // Find out where the last render sibling is located within m_children.
+ AXObject* childObject = axObjectCache()->get(child->renderer());
+ if (childObject && childObject->accessibilityIsIgnored()) {
+ AccessibilityChildrenVector children = childObject->children();
+ if (children.size())
+ childObject = children.last().get();
+ else
+ childObject = 0;
+ }
+
+ if (childObject)
+ insertionIndex = m_children.find(childObject) + 1;
+ continue;
+ }
+
+ if (!isNodeAriaVisible(child))
+ continue;
+
+ unsigned previousSize = m_children.size();
+ if (insertionIndex > previousSize)
+ insertionIndex = previousSize;
+
+ insertChild(axObjectCache()->getOrCreate(child), insertionIndex);
+ insertionIndex += (m_children.size() - previousSize);
+ }
+}
+
+void AXRenderObject::addTextFieldChildren()
+{
+ Node* node = this->node();
+ if (!node || !node->hasTagName(inputTag))
+ return;
+
+ HTMLInputElement* input = toHTMLInputElement(node);
+ Element* spinButtonElement = input->userAgentShadowRoot()->getElementById(ShadowElementNames::spinButton());
+ if (!spinButtonElement || !spinButtonElement->isSpinButtonElement())
+ return;
+
+ AXSpinButton* axSpinButton = toAXSpinButton(axObjectCache()->getOrCreate(SpinButtonRole));
+ axSpinButton->setSpinButtonElement(toSpinButtonElement(spinButtonElement));
+ axSpinButton->setParent(this);
+ m_children.append(axSpinButton);
+}
+
+void AXRenderObject::addImageMapChildren()
+{
+ RenderBoxModelObject* cssBox = renderBoxModelObject();
+ if (!cssBox || !cssBox->isRenderImage())
+ return;
+
+ HTMLMapElement* map = toRenderImage(cssBox)->imageMap();
+ if (!map)
+ return;
+
+ for (Element* current = ElementTraversal::firstWithin(*map); current; current = ElementTraversal::next(*current, map)) {
+ // add an <area> element for this child if it has a link
+ if (isHTMLAreaElement(current) && current->isLink()) {
+ AXImageMapLink* areaObject = toAXImageMapLink(axObjectCache()->getOrCreate(ImageMapLinkRole));
+ areaObject->setHTMLAreaElement(toHTMLAreaElement(current));
+ areaObject->setHTMLMapElement(map);
+ areaObject->setParent(this);
+ if (!areaObject->accessibilityIsIgnored())
+ m_children.append(areaObject);
+ else
+ axObjectCache()->remove(areaObject->axObjectID());
+ }
+ }
+}
+
+void AXRenderObject::addCanvasChildren()
+{
+ if (!node() || !node()->hasTagName(canvasTag))
+ return;
+
+ // If it's a canvas, it won't have rendered children, but it might have accessible fallback content.
+ // Clear m_haveChildren because AXNodeObject::addChildren will expect it to be false.
+ ASSERT(!m_children.size());
+ m_haveChildren = false;
+ AXNodeObject::addChildren();
+}
+
+void AXRenderObject::addAttachmentChildren()
+{
+ if (!isAttachment())
+ return;
+
+ // FrameView's need to be inserted into the AX hierarchy when encountered.
+ Widget* widget = widgetForAttachmentView();
+ if (!widget || !widget->isFrameView())
+ return;
+
+ AXObject* axWidget = axObjectCache()->getOrCreate(widget);
+ if (!axWidget->accessibilityIsIgnored())
+ m_children.append(axWidget);
+}
+
+void AXRenderObject::addRemoteSVGChildren()
+{
+ AXSVGRoot* root = remoteSVGRootElement();
+ if (!root)
+ return;
+
+ root->setParent(this);
+
+ if (root->accessibilityIsIgnored()) {
+ AccessibilityChildrenVector children = root->children();
+ unsigned length = children.size();
+ for (unsigned i = 0; i < length; ++i)
+ m_children.append(children[i]);
+ } else {
+ m_children.append(root);
+ }
+}
+
+void AXRenderObject::ariaSelectedRows(AccessibilityChildrenVector& result)
+{
+ // Get all the rows.
+ AccessibilityChildrenVector allRows;
+ if (isTree())
+ ariaTreeRows(allRows);
+ else if (isAXTable() && toAXTable(this)->supportsSelectedRows())
+ allRows = toAXTable(this)->rows();
+
+ // Determine which rows are selected.
+ bool isMulti = isMultiSelectable();
+
+ // Prefer active descendant over aria-selected.
+ AXObject* activeDesc = activeDescendant();
+ if (activeDesc && (activeDesc->isTreeItem() || activeDesc->isTableRow())) {
+ result.append(activeDesc);
+ if (!isMulti)
+ return;
+ }
+
+ unsigned count = allRows.size();
+ for (unsigned k = 0; k < count; ++k) {
+ if (allRows[k]->isSelected()) {
+ result.append(allRows[k]);
+ if (!isMulti)
+ break;
+ }
+ }
+}
+
+bool AXRenderObject::elementAttributeValue(const QualifiedName& attributeName) const
+{
+ if (!m_renderer)
+ return false;
+
+ return equalIgnoringCase(getAttribute(attributeName), "true");
+}
+
+bool AXRenderObject::inheritsPresentationalRole() const
+{
+ // ARIA states if an item can get focus, it should not be presentational.
+ if (canSetFocusAttribute())
+ return false;
+
+ // ARIA spec says that when a parent object is presentational, and it has required child elements,
+ // those child elements are also presentational. For example, <li> becomes presentational from <ul>.
+ // http://www.w3.org/WAI/PF/aria/complete#presentation
+ if (roleValue() != ListItemRole && roleValue() != ListMarkerRole)
+ return false;
+
+ AXObject* parent = parentObject();
+ if (!parent->isAXRenderObject())
+ return false;
+
+ Node* elementNode = toAXRenderObject(parent)->node();
+ if (!elementNode || !elementNode->isElementNode())
+ return false;
+
+ QualifiedName tagName = toElement(elementNode)->tagQName();
+ if (tagName == ulTag || tagName == olTag || tagName == dlTag)
+ return parent->roleValue() == PresentationalRole;
+
+ return false;
+}
+
+LayoutRect AXRenderObject::computeElementRect() const
+{
+ RenderObject* obj = m_renderer;
+
+ if (!obj)
+ return LayoutRect();
+
+ if (obj->node()) // If we are a continuation, we want to make sure to use the primary renderer.
+ obj = obj->node()->renderer();
+
+ // absoluteFocusRingQuads will query the hierarchy below this element, which for large webpages can be very slow.
+ // For a web area, which will have the most elements of any element, absoluteQuads should be used.
+ // We should also use absoluteQuads for SVG elements, otherwise transforms won't be applied.
+ Vector<FloatQuad> quads;
+
+ if (obj->isText())
+ toRenderText(obj)->absoluteQuads(quads, 0, RenderText::ClipToEllipsis);
+ else if (isWebArea() || isSeamlessWebArea() || obj->isSVGRoot())
+ obj->absoluteQuads(quads);
+ else
+ obj->absoluteFocusRingQuads(quads);
+
+ LayoutRect result = boundingBoxForQuads(obj, quads);
+
+ Document* document = this->document();
+ if (document && document->isSVGDocument())
+ offsetBoundingBoxForRemoteSVGElement(result);
+
+ // The size of the web area should be the content size, not the clipped size.
+ if ((isWebArea() || isSeamlessWebArea()) && obj->frame()->view())
+ result.setSize(obj->frame()->view()->contentsSize());
+
+ // Checkboxes and radio buttons include their label as part of their rect.
+ if (isCheckboxOrRadio()) {
+ HTMLLabelElement* label = labelForElement(toElement(m_renderer->node()));
+ if (label && label->renderer()) {
+ LayoutRect labelRect = axObjectCache()->getOrCreate(label)->elementRect();
+ result.unite(labelRect);
+ }
+ }
+
+ return result;
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AXRenderObject.h b/chromium/third_party/WebKit/Source/core/accessibility/AXRenderObject.h
new file mode 100644
index 00000000000..160d0d7db3a
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/accessibility/AXRenderObject.h
@@ -0,0 +1,238 @@
+/*
+ * Copyright (C) 2008 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef AXRenderObject_h
+#define AXRenderObject_h
+
+#include "core/accessibility/AXNodeObject.h"
+#include "platform/geometry/LayoutRect.h"
+#include "wtf/Forward.h"
+
+namespace WebCore {
+
+class AXSVGRoot;
+class AXObjectCache;
+class Element;
+class Frame;
+class FrameView;
+class HitTestResult;
+class HTMLAnchorElement;
+class HTMLAreaElement;
+class HTMLElement;
+class HTMLLabelElement;
+class HTMLMapElement;
+class HTMLSelectElement;
+class IntPoint;
+class IntSize;
+class Node;
+class RenderListBox;
+class RenderTextControl;
+class RenderView;
+class VisibleSelection;
+class Widget;
+
+class AXRenderObject : public AXNodeObject {
+protected:
+ explicit AXRenderObject(RenderObject*);
+public:
+ static PassRefPtr<AXRenderObject> create(RenderObject*);
+ virtual ~AXRenderObject();
+
+ // Public, overridden from AXObject.
+ virtual RenderObject* renderer() const OVERRIDE { return m_renderer; }
+ virtual LayoutRect elementRect() const OVERRIDE;
+
+ void setRenderer(RenderObject*);
+ RenderBoxModelObject* renderBoxModelObject() const;
+ RenderView* topRenderer() const;
+ Document* topDocument() const;
+ bool shouldNotifyActiveDescendant() const;
+ bool needsToUpdateChildren() const { return m_childrenDirty; }
+ ScrollableArea* getScrollableAreaIfScrollable() const;
+ virtual AccessibilityRole determineAccessibilityRole() OVERRIDE;
+ void checkCachedElementRect() const;
+ void updateCachedElementRect() const;
+
+protected:
+ RenderObject* m_renderer;
+ mutable LayoutRect m_cachedElementRect;
+ mutable LayoutRect m_cachedFrameRect;
+ mutable IntPoint m_cachedScrollPosition;
+ mutable bool m_cachedElementRectDirty;
+
+ //
+ // Overridden from AXObject.
+ //
+
+ virtual void init() OVERRIDE;
+ virtual void detach() OVERRIDE;
+ virtual bool isDetached() const OVERRIDE { return !m_renderer; }
+ virtual bool isAXRenderObject() const OVERRIDE { return true; }
+
+ // Check object role or purpose.
+ virtual bool isAttachment() const OVERRIDE;
+ virtual bool isFileUploadButton() const OVERRIDE;
+ virtual bool isLinked() const OVERRIDE;
+ virtual bool isLoaded() const OVERRIDE;
+ virtual bool isOffScreen() const OVERRIDE;
+ virtual bool isReadOnly() const OVERRIDE;
+ virtual bool isVisited() const OVERRIDE;
+
+ // Check object state.
+ virtual bool isFocused() const OVERRIDE;
+ virtual bool isSelected() const OVERRIDE;
+
+ // Whether objects are ignored, i.e. not included in the tree.
+ virtual AXObjectInclusion defaultObjectInclusion() const OVERRIDE;
+ virtual bool computeAccessibilityIsIgnored() const OVERRIDE;
+
+ // Properties of static elements.
+ virtual const AtomicString& accessKey() const OVERRIDE;
+ virtual AccessibilityOrientation orientation() const OVERRIDE;
+ virtual String text() const OVERRIDE;
+ virtual int textLength() const OVERRIDE;
+ virtual KURL url() const OVERRIDE;
+
+ // Properties of interactive elements.
+ virtual String actionVerb() const OVERRIDE;
+ virtual void selectedChildren(AccessibilityChildrenVector&) OVERRIDE;
+ virtual String stringValue() const OVERRIDE;
+
+ // ARIA attributes.
+ virtual AXObject* activeDescendant() const OVERRIDE;
+ virtual void ariaFlowToElements(AccessibilityChildrenVector&) const OVERRIDE;
+ virtual bool ariaHasPopup() const OVERRIDE;
+ virtual bool ariaRoleHasPresentationalChildren() const OVERRIDE;
+ virtual bool isPresentationalChildOfAriaRole() const OVERRIDE;
+ virtual bool shouldFocusActiveDescendant() const OVERRIDE;
+ virtual bool supportsARIADragging() const OVERRIDE;
+ virtual bool supportsARIADropping() const OVERRIDE;
+ virtual bool supportsARIAFlowTo() const OVERRIDE;
+ virtual bool supportsARIAOwns() const OVERRIDE;
+
+ // ARIA live-region features.
+ virtual const AtomicString& ariaLiveRegionStatus() const OVERRIDE;
+ virtual const AtomicString& ariaLiveRegionRelevant() const OVERRIDE;
+ virtual bool ariaLiveRegionAtomic() const OVERRIDE;
+ virtual bool ariaLiveRegionBusy() const OVERRIDE;
+
+ // Accessibility Text.
+ virtual String textUnderElement() const OVERRIDE;
+
+ // Accessibility Text - (To be deprecated).
+ virtual String helpText() const OVERRIDE;
+
+ // Location and click point in frame-relative coordinates.
+ virtual void markCachedElementRectDirty() const OVERRIDE;
+ virtual IntPoint clickPoint() OVERRIDE;
+
+ // Hit testing.
+ virtual AXObject* accessibilityHitTest(const IntPoint&) const OVERRIDE;
+ virtual AXObject* elementAccessibilityHitTest(const IntPoint&) const OVERRIDE;
+
+ // High-level accessibility tree access. Other modules should only use these functions.
+ virtual AXObject* parentObject() const OVERRIDE;
+ virtual AXObject* parentObjectIfExists() const OVERRIDE;
+
+ // Low-level accessibility tree exploration, only for use within the accessibility module.
+ virtual AXObject* firstChild() const OVERRIDE;
+ virtual AXObject* nextSibling() const OVERRIDE;
+ virtual void addChildren() OVERRIDE;
+ virtual bool canHaveChildren() const OVERRIDE;
+ virtual void updateChildrenIfNecessary() OVERRIDE;
+ virtual void setNeedsToUpdateChildren() OVERRIDE { m_childrenDirty = true; }
+ virtual void clearChildren() OVERRIDE;
+ virtual AXObject* observableObject() const OVERRIDE;
+
+ // Properties of the object's owning document or page.
+ virtual double estimatedLoadingProgress() const OVERRIDE;
+
+ // DOM and Render tree access.
+ virtual Node* node() const OVERRIDE;
+ virtual Document* document() const OVERRIDE;
+ virtual FrameView* documentFrameView() const OVERRIDE;
+ virtual Element* anchorElement() const OVERRIDE;
+ virtual Widget* widgetForAttachmentView() const OVERRIDE;
+
+ // Selected text.
+ virtual PlainTextRange selectedTextRange() const OVERRIDE;
+ virtual String selectedText() const OVERRIDE;
+
+ // Modify or take an action on an object.
+ virtual void setSelectedTextRange(const PlainTextRange&) OVERRIDE;
+ virtual void setValue(const String&) OVERRIDE;
+ virtual void scrollTo(const IntPoint&) const OVERRIDE;
+
+ // Notifications that this object may have changed.
+ virtual void handleActiveDescendantChanged() OVERRIDE;
+ virtual void handleAriaExpandedChanged() OVERRIDE;
+ virtual void textChanged() OVERRIDE;
+
+ // Text metrics. Most of these should be deprecated, needs major cleanup.
+ virtual int index(const VisiblePosition&) const OVERRIDE;
+ virtual VisiblePosition visiblePositionForIndex(int) const OVERRIDE;
+ virtual void lineBreaks(Vector<int>&) const OVERRIDE;
+
+private:
+ bool isAllowedChildOfTree() const;
+ void ariaListboxSelectedChildren(AccessibilityChildrenVector&);
+ PlainTextRange ariaSelectedTextRange() const;
+ bool nodeIsTextControl(const Node*) const;
+ bool isTabItemSelected() const;
+ AXObject* internalLinkElement() const;
+ AXObject* accessibilityImageMapHitTest(HTMLAreaElement*, const IntPoint&) const;
+ bool renderObjectIsObservable(RenderObject*) const;
+ RenderObject* renderParentObject() const;
+ bool isDescendantOfElementType(const QualifiedName& tagName) const;
+ bool isSVGImage() const;
+ void detachRemoteSVGRoot();
+ AXSVGRoot* remoteSVGRootElement() const;
+ AXObject* remoteSVGElementHitTest(const IntPoint&) const;
+ void offsetBoundingBoxForRemoteSVGElement(LayoutRect&) const;
+ void addHiddenChildren();
+ void addTextFieldChildren();
+ void addImageMapChildren();
+ void addCanvasChildren();
+ void addAttachmentChildren();
+ void addRemoteSVGChildren();
+ void addInlineTextBoxChildren();
+
+ void ariaSelectedRows(AccessibilityChildrenVector&);
+ bool elementAttributeValue(const QualifiedName&) const;
+ bool inheritsPresentationalRole() const;
+ LayoutRect computeElementRect() const;
+ VisibleSelection selection() const;
+ String stringForRange(const PlainTextRange&) const;
+ int indexForVisiblePosition(const VisiblePosition&) const;
+};
+
+DEFINE_AX_OBJECT_TYPE_CASTS(AXRenderObject, isAXRenderObject());
+
+} // namespace WebCore
+
+#endif // AXRenderObject_h
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AXSVGRoot.cpp b/chromium/third_party/WebKit/Source/core/accessibility/AXSVGRoot.cpp
new file mode 100644
index 00000000000..7c2efa2cc2e
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/accessibility/AXSVGRoot.cpp
@@ -0,0 +1,61 @@
+/*
+ * Copyright (C) 2012 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/accessibility/AXSVGRoot.h"
+
+
+namespace WebCore {
+
+AXSVGRoot::AXSVGRoot(RenderObject* renderer)
+ : AXRenderObject(renderer)
+ , m_parent(0)
+{
+}
+
+AXSVGRoot::~AXSVGRoot()
+{
+}
+
+PassRefPtr<AXSVGRoot> AXSVGRoot::create(RenderObject* renderer)
+{
+ return adoptRef(new AXSVGRoot(renderer));
+}
+
+AXObject* AXSVGRoot::parentObject() const
+{
+ // If a parent was set because this is a remote SVG resource, use that
+ // but otherwise, we should rely on the standard render tree for the parent.
+ if (m_parent)
+ return m_parent;
+
+ return AXRenderObject::parentObject();
+}
+
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AXSVGRoot.h b/chromium/third_party/WebKit/Source/core/accessibility/AXSVGRoot.h
new file mode 100644
index 00000000000..4febd09f851
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/accessibility/AXSVGRoot.h
@@ -0,0 +1,57 @@
+/*
+ * Copyright (C) 2012 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef AXSVGRoot_h
+#define AXSVGRoot_h
+
+#include "core/accessibility/AXRenderObject.h"
+
+namespace WebCore {
+
+class AXSVGRoot : public AXRenderObject {
+
+protected:
+ explicit AXSVGRoot(RenderObject*);
+public:
+ static PassRefPtr<AXSVGRoot> create(RenderObject*);
+ virtual ~AXSVGRoot();
+
+ void setParent(AXObject* parent) { m_parent = parent; }
+
+private:
+ AXObject* m_parent;
+
+ virtual AXObject* parentObject() const OVERRIDE;
+ virtual bool isAXSVGRoot() const OVERRIDE { return true; }
+};
+
+DEFINE_AX_OBJECT_TYPE_CASTS(AXSVGRoot, isAXSVGRoot());
+
+} // namespace WebCore
+
+#endif // AXSVGRoot_h
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AXScrollView.cpp b/chromium/third_party/WebKit/Source/core/accessibility/AXScrollView.cpp
new file mode 100644
index 00000000000..2626bb6fdfc
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/accessibility/AXScrollView.cpp
@@ -0,0 +1,242 @@
+/*
+ * Copyright (C) 2011 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/accessibility/AXScrollView.h"
+
+#include "core/accessibility/AXObjectCache.h"
+#include "core/accessibility/AXScrollbar.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
+#include "core/html/HTMLFrameOwnerElement.h"
+
+namespace WebCore {
+
+AXScrollView::AXScrollView(ScrollView* view)
+ : m_scrollView(view)
+ , m_childrenDirty(false)
+{
+}
+
+AXScrollView::~AXScrollView()
+{
+ ASSERT(isDetached());
+}
+
+void AXScrollView::detach()
+{
+ AXObject::detach();
+ m_scrollView = 0;
+}
+
+PassRefPtr<AXScrollView> AXScrollView::create(ScrollView* view)
+{
+ return adoptRef(new AXScrollView(view));
+}
+
+AXObject* AXScrollView::scrollBar(AccessibilityOrientation orientation)
+{
+ updateScrollbars();
+
+ switch (orientation) {
+ case AccessibilityOrientationVertical:
+ return m_verticalScrollbar ? m_verticalScrollbar.get() : 0;
+ case AccessibilityOrientationHorizontal:
+ return m_horizontalScrollbar ? m_horizontalScrollbar.get() : 0;
+ }
+
+ return 0;
+}
+
+// If this is WebKit1 then the native scroll view needs to return the
+// AX information (because there are no scroll bar children in the ScrollView object in WK1).
+// In WebKit2, the ScrollView object will return the AX information (because there are no platform widgets).
+bool AXScrollView::isAttachment() const
+{
+ return false;
+}
+
+Widget* AXScrollView::widgetForAttachmentView() const
+{
+ return m_scrollView;
+}
+
+void AXScrollView::updateChildrenIfNecessary()
+{
+ if (m_childrenDirty)
+ clearChildren();
+
+ if (!m_haveChildren)
+ addChildren();
+
+ updateScrollbars();
+}
+
+void AXScrollView::updateScrollbars()
+{
+ if (!m_scrollView)
+ return;
+
+ if (m_scrollView->horizontalScrollbar() && !m_horizontalScrollbar) {
+ m_horizontalScrollbar = addChildScrollbar(m_scrollView->horizontalScrollbar());
+ } else if (!m_scrollView->horizontalScrollbar() && m_horizontalScrollbar) {
+ removeChildScrollbar(m_horizontalScrollbar.get());
+ m_horizontalScrollbar = 0;
+ }
+
+ if (m_scrollView->verticalScrollbar() && !m_verticalScrollbar) {
+ m_verticalScrollbar = addChildScrollbar(m_scrollView->verticalScrollbar());
+ } else if (!m_scrollView->verticalScrollbar() && m_verticalScrollbar) {
+ removeChildScrollbar(m_verticalScrollbar.get());
+ m_verticalScrollbar = 0;
+ }
+}
+
+void AXScrollView::removeChildScrollbar(AXObject* scrollbar)
+{
+ size_t pos = m_children.find(scrollbar);
+ if (pos != kNotFound) {
+ m_children[pos]->detachFromParent();
+ m_children.remove(pos);
+ }
+}
+
+AXScrollbar* AXScrollView::addChildScrollbar(Scrollbar* scrollbar)
+{
+ if (!scrollbar)
+ return 0;
+
+ AXScrollbar* scrollBarObject = toAXScrollbar(axObjectCache()->getOrCreate(scrollbar));
+ scrollBarObject->setParent(this);
+ m_children.append(scrollBarObject);
+ return scrollBarObject;
+}
+
+void AXScrollView::clearChildren()
+{
+ AXObject::clearChildren();
+ m_verticalScrollbar = 0;
+ m_horizontalScrollbar = 0;
+}
+
+bool AXScrollView::computeAccessibilityIsIgnored() const
+{
+ AXObject* webArea = webAreaObject();
+ if (!webArea)
+ return true;
+
+ return webArea->accessibilityIsIgnored();
+}
+
+void AXScrollView::addChildren()
+{
+ ASSERT(!m_haveChildren);
+ m_haveChildren = true;
+
+ AXObject* webArea = webAreaObject();
+ if (webArea && !webArea->accessibilityIsIgnored())
+ m_children.append(webArea);
+
+ updateScrollbars();
+}
+
+AXObject* AXScrollView::webAreaObject() const
+{
+ if (!m_scrollView || !m_scrollView->isFrameView())
+ return 0;
+
+ Document* doc = toFrameView(m_scrollView)->frame().document();
+ if (!doc || !doc->renderer())
+ return 0;
+
+ return axObjectCache()->getOrCreate(doc);
+}
+
+AXObject* AXScrollView::accessibilityHitTest(const IntPoint& point) const
+{
+ AXObject* webArea = webAreaObject();
+ if (!webArea)
+ return 0;
+
+ if (m_horizontalScrollbar && m_horizontalScrollbar->elementRect().contains(point))
+ return m_horizontalScrollbar.get();
+ if (m_verticalScrollbar && m_verticalScrollbar->elementRect().contains(point))
+ return m_verticalScrollbar.get();
+
+ return webArea->accessibilityHitTest(point);
+}
+
+LayoutRect AXScrollView::elementRect() const
+{
+ if (!m_scrollView)
+ return LayoutRect();
+
+ return m_scrollView->frameRect();
+}
+
+FrameView* AXScrollView::documentFrameView() const
+{
+ if (!m_scrollView || !m_scrollView->isFrameView())
+ return 0;
+
+ return toFrameView(m_scrollView);
+}
+
+AXObject* AXScrollView::parentObject() const
+{
+ if (!m_scrollView || !m_scrollView->isFrameView())
+ return 0;
+
+ HTMLFrameOwnerElement* owner = toFrameView(m_scrollView)->frame().ownerElement();
+ if (owner && owner->renderer())
+ return axObjectCache()->getOrCreate(owner);
+
+ return 0;
+}
+
+AXObject* AXScrollView::parentObjectIfExists() const
+{
+ if (!m_scrollView || !m_scrollView->isFrameView())
+ return 0;
+
+ HTMLFrameOwnerElement* owner = toFrameView(m_scrollView)->frame().ownerElement();
+ if (owner && owner->renderer())
+ return axObjectCache()->get(owner);
+
+ return 0;
+}
+
+ScrollableArea* AXScrollView::getScrollableAreaIfScrollable() const
+{
+ return m_scrollView;
+}
+
+void AXScrollView::scrollTo(const IntPoint& point) const
+{
+ if (m_scrollView)
+ m_scrollView->setScrollPosition(point);
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AXScrollView.h b/chromium/third_party/WebKit/Source/core/accessibility/AXScrollView.h
new file mode 100644
index 00000000000..cf7e291024e
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/accessibility/AXScrollView.h
@@ -0,0 +1,88 @@
+/*
+ * Copyright (C) 2011 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef AXScrollView_h
+#define AXScrollView_h
+
+#include "core/accessibility/AXObject.h"
+
+namespace WebCore {
+
+class AXScrollbar;
+class Scrollbar;
+class ScrollView;
+
+class AXScrollView : public AXObject {
+public:
+ static PassRefPtr<AXScrollView> create(ScrollView*);
+ virtual AccessibilityRole roleValue() const { return ScrollAreaRole; }
+ ScrollView* scrollView() const { return m_scrollView; }
+
+ virtual ~AXScrollView();
+ virtual void detach() OVERRIDE;
+
+protected:
+ virtual ScrollableArea* getScrollableAreaIfScrollable() const OVERRIDE;
+ virtual void scrollTo(const IntPoint&) const OVERRIDE;
+
+private:
+ explicit AXScrollView(ScrollView*);
+
+ virtual bool computeAccessibilityIsIgnored() const OVERRIDE;
+ virtual bool isAXScrollView() const OVERRIDE { return true; }
+ virtual bool isEnabled() const OVERRIDE { return true; }
+
+ virtual bool isAttachment() const OVERRIDE;
+ virtual Widget* widgetForAttachmentView() const OVERRIDE;
+
+ virtual AXObject* scrollBar(AccessibilityOrientation) OVERRIDE;
+ virtual void addChildren() OVERRIDE;
+ virtual void clearChildren() OVERRIDE;
+ virtual AXObject* accessibilityHitTest(const IntPoint&) const OVERRIDE;
+ virtual void updateChildrenIfNecessary() OVERRIDE;
+ virtual void setNeedsToUpdateChildren() OVERRIDE { m_childrenDirty = true; }
+ void updateScrollbars();
+
+ virtual FrameView* documentFrameView() const OVERRIDE;
+ virtual LayoutRect elementRect() const OVERRIDE;
+ virtual AXObject* parentObject() const OVERRIDE;
+ virtual AXObject* parentObjectIfExists() const OVERRIDE;
+
+ AXObject* webAreaObject() const;
+ virtual AXObject* firstChild() const OVERRIDE { return webAreaObject(); }
+ AXScrollbar* addChildScrollbar(Scrollbar*);
+ void removeChildScrollbar(AXObject*);
+
+ ScrollView* m_scrollView;
+ RefPtr<AXObject> m_horizontalScrollbar;
+ RefPtr<AXObject> m_verticalScrollbar;
+ bool m_childrenDirty;
+};
+
+DEFINE_AX_OBJECT_TYPE_CASTS(AXScrollView, isAXScrollView());
+
+} // namespace WebCore
+
+#endif // AXScrollView_h
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AXScrollbar.cpp b/chromium/third_party/WebKit/Source/core/accessibility/AXScrollbar.cpp
new file mode 100644
index 00000000000..0b478487330
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/accessibility/AXScrollbar.cpp
@@ -0,0 +1,109 @@
+/*
+ * Copyright (C) 2010 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/accessibility/AXScrollbar.h"
+
+#include "platform/scroll/ScrollView.h"
+
+namespace WebCore {
+
+AXScrollbar::AXScrollbar(Scrollbar* scrollbar)
+ : m_scrollbar(scrollbar)
+{
+ ASSERT(scrollbar);
+}
+
+void AXScrollbar::detachFromParent()
+{
+ m_scrollbar = 0;
+ AXMockObject::detachFromParent();
+}
+
+PassRefPtr<AXScrollbar> AXScrollbar::create(Scrollbar* scrollbar)
+{
+ return adoptRef(new AXScrollbar(scrollbar));
+}
+
+LayoutRect AXScrollbar::elementRect() const
+{
+ if (!m_scrollbar)
+ return LayoutRect();
+
+ return m_scrollbar->frameRect();
+}
+
+Document* AXScrollbar::document() const
+{
+ AXObject* parent = parentObject();
+ if (!parent)
+ return 0;
+ return parent->document();
+}
+
+AccessibilityOrientation AXScrollbar::orientation() const
+{
+ if (!m_scrollbar)
+ return AccessibilityOrientationHorizontal;
+
+ if (m_scrollbar->orientation() == HorizontalScrollbar)
+ return AccessibilityOrientationHorizontal;
+ if (m_scrollbar->orientation() == VerticalScrollbar)
+ return AccessibilityOrientationVertical;
+
+ return AccessibilityOrientationHorizontal;
+}
+
+bool AXScrollbar::isEnabled() const
+{
+ if (!m_scrollbar)
+ return false;
+ return m_scrollbar->enabled();
+}
+
+float AXScrollbar::valueForRange() const
+{
+ if (!m_scrollbar)
+ return 0;
+
+ return m_scrollbar->currentPos() / m_scrollbar->maximum();
+}
+
+void AXScrollbar::setValue(float value)
+{
+ if (!m_scrollbar)
+ return;
+
+ if (!m_scrollbar->scrollableArea())
+ return;
+
+ float newValue = value * m_scrollbar->maximum();
+ m_scrollbar->scrollableArea()->scrollToOffsetWithoutAnimation(m_scrollbar->orientation(), newValue);
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AXScrollbar.h b/chromium/third_party/WebKit/Source/core/accessibility/AXScrollbar.h
new file mode 100644
index 00000000000..42eaca23470
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/accessibility/AXScrollbar.h
@@ -0,0 +1,71 @@
+/*
+ * Copyright (C) 2010 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef AXScrollbar_h
+#define AXScrollbar_h
+
+#include "core/accessibility/AXMockObject.h"
+
+namespace WebCore {
+
+class Scrollbar;
+
+class AXScrollbar : public AXMockObject {
+public:
+ static PassRefPtr<AXScrollbar> create(Scrollbar*);
+
+ Scrollbar* scrollbar() const { return m_scrollbar.get(); }
+
+private:
+ explicit AXScrollbar(Scrollbar*);
+
+ virtual void detachFromParent();
+
+ virtual bool canSetValueAttribute() const OVERRIDE { return true; }
+
+ virtual bool isAXScrollbar() const OVERRIDE { return true; }
+ virtual LayoutRect elementRect() const OVERRIDE;
+
+ virtual AccessibilityRole roleValue() const OVERRIDE { return ScrollBarRole; }
+ virtual AccessibilityOrientation orientation() const OVERRIDE;
+ virtual Document* document() const OVERRIDE;
+
+ virtual bool isEnabled() const OVERRIDE;
+
+ // Assumes float [0..1]
+ virtual void setValue(float) OVERRIDE;
+ virtual float valueForRange() const OVERRIDE;
+
+ RefPtr<Scrollbar> m_scrollbar;
+};
+
+DEFINE_AX_OBJECT_TYPE_CASTS(AXScrollbar, isAXScrollbar());
+
+} // namespace WebCore
+
+#endif // AXScrollbar_h
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AXSlider.cpp b/chromium/third_party/WebKit/Source/core/accessibility/AXSlider.cpp
new file mode 100644
index 00000000000..4cfdc8f377b
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/accessibility/AXSlider.cpp
@@ -0,0 +1,159 @@
+/*
+ * Copyright (C) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/accessibility/AXSlider.h"
+
+#include "core/accessibility/AXObjectCache.h"
+#include "core/dom/shadow/ShadowRoot.h"
+#include "core/html/HTMLInputElement.h"
+#include "core/html/shadow/ShadowElementNames.h"
+#include "core/rendering/RenderObject.h"
+
+namespace WebCore {
+
+using namespace HTMLNames;
+
+AXSlider::AXSlider(RenderObject* renderer)
+ : AXRenderObject(renderer)
+{
+}
+
+PassRefPtr<AXSlider> AXSlider::create(RenderObject* renderer)
+{
+ return adoptRef(new AXSlider(renderer));
+}
+
+AccessibilityOrientation AXSlider::orientation() const
+{
+ // Default to horizontal in the unknown case.
+ if (!m_renderer)
+ return AccessibilityOrientationHorizontal;
+
+ RenderStyle* style = m_renderer->style();
+ if (!style)
+ return AccessibilityOrientationHorizontal;
+
+ ControlPart styleAppearance = style->appearance();
+ switch (styleAppearance) {
+ case SliderThumbHorizontalPart:
+ case SliderHorizontalPart:
+ case MediaSliderPart:
+ case MediaFullScreenVolumeSliderPart:
+ return AccessibilityOrientationHorizontal;
+
+ case SliderThumbVerticalPart:
+ case SliderVerticalPart:
+ case MediaVolumeSliderPart:
+ return AccessibilityOrientationVertical;
+
+ default:
+ return AccessibilityOrientationHorizontal;
+ }
+}
+
+void AXSlider::addChildren()
+{
+ ASSERT(!m_haveChildren);
+
+ m_haveChildren = true;
+
+ AXObjectCache* cache = m_renderer->document().axObjectCache();
+
+ AXSliderThumb* thumb = static_cast<AXSliderThumb*>(cache->getOrCreate(SliderThumbRole));
+ thumb->setParent(this);
+
+ // Before actually adding the value indicator to the hierarchy,
+ // allow the platform to make a final decision about it.
+ if (thumb->accessibilityIsIgnored())
+ cache->remove(thumb->axObjectID());
+ else
+ m_children.append(thumb);
+}
+
+const AtomicString& AXSlider::getAttribute(const QualifiedName& attribute) const
+{
+ return element()->getAttribute(attribute);
+}
+
+AXObject* AXSlider::elementAccessibilityHitTest(const IntPoint& point) const
+{
+ if (m_children.size()) {
+ ASSERT(m_children.size() == 1);
+ if (m_children[0]->elementRect().contains(point))
+ return m_children[0].get();
+ }
+
+ return axObjectCache()->getOrCreate(m_renderer);
+}
+
+void AXSlider::setValue(const String& value)
+{
+ HTMLInputElement* input = element();
+
+ if (input->value() == value)
+ return;
+
+ input->setValue(value);
+
+ // Fire change event manually, as RenderSlider::setValueForPosition does.
+ input->dispatchFormControlChangeEvent();
+}
+
+HTMLInputElement* AXSlider::element() const
+{
+ return toHTMLInputElement(m_renderer->node());
+}
+
+
+AXSliderThumb::AXSliderThumb()
+{
+}
+
+PassRefPtr<AXSliderThumb> AXSliderThumb::create()
+{
+ return adoptRef(new AXSliderThumb());
+}
+
+LayoutRect AXSliderThumb::elementRect() const
+{
+ if (!m_parent)
+ return LayoutRect();
+
+ RenderObject* sliderRenderer = m_parent->renderer();
+ if (!sliderRenderer || !sliderRenderer->isSlider())
+ return LayoutRect();
+ return toElement(sliderRenderer->node())->userAgentShadowRoot()->getElementById(ShadowElementNames::sliderThumb())->boundingBox();
+}
+
+bool AXSliderThumb::computeAccessibilityIsIgnored() const
+{
+ return accessibilityIsIgnoredByDefault();
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AXSlider.h b/chromium/third_party/WebKit/Source/core/accessibility/AXSlider.h
new file mode 100644
index 00000000000..54b8a1b2a53
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/accessibility/AXSlider.h
@@ -0,0 +1,84 @@
+/*
+ * Copyright (C) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef AXSlider_h
+#define AXSlider_h
+
+#include "core/accessibility/AXMockObject.h"
+#include "core/accessibility/AXRenderObject.h"
+
+namespace WebCore {
+
+class HTMLInputElement;
+
+class AXSlider : public AXRenderObject {
+
+public:
+ static PassRefPtr<AXSlider> create(RenderObject*);
+ virtual ~AXSlider() { }
+
+protected:
+ explicit AXSlider(RenderObject*);
+
+private:
+ HTMLInputElement* element() const;
+ virtual AXObject* elementAccessibilityHitTest(const IntPoint&) const OVERRIDE;
+
+ virtual AccessibilityRole roleValue() const OVERRIDE { return SliderRole; }
+ virtual bool isSlider() const OVERRIDE { return true; }
+ virtual bool isControl() const OVERRIDE { return true; }
+
+ virtual void addChildren() OVERRIDE;
+
+ virtual bool canSetValueAttribute() const OVERRIDE { return true; }
+ const AtomicString& getAttribute(const QualifiedName& attribute) const;
+
+ virtual void setValue(const String&) OVERRIDE;
+ virtual AccessibilityOrientation orientation() const OVERRIDE;
+};
+
+class AXSliderThumb : public AXMockObject {
+
+public:
+ static PassRefPtr<AXSliderThumb> create();
+ virtual ~AXSliderThumb() { }
+
+ virtual AccessibilityRole roleValue() const OVERRIDE { return SliderThumbRole; }
+
+ virtual LayoutRect elementRect() const OVERRIDE;
+
+private:
+ AXSliderThumb();
+
+ virtual bool computeAccessibilityIsIgnored() const OVERRIDE;
+};
+
+
+} // namespace WebCore
+
+#endif // AXSlider_h
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AXSpinButton.cpp b/chromium/third_party/WebKit/Source/core/accessibility/AXSpinButton.cpp
new file mode 100644
index 00000000000..e73482ed419
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/accessibility/AXSpinButton.cpp
@@ -0,0 +1,127 @@
+/*
+ * Copyright (C) 2011 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/accessibility/AXSpinButton.h"
+
+#include "core/accessibility/AXObjectCache.h"
+#include "core/rendering/RenderObject.h"
+
+namespace WebCore {
+
+PassRefPtr<AXSpinButton> AXSpinButton::create()
+{
+ return adoptRef(new AXSpinButton);
+}
+
+AXSpinButton::AXSpinButton()
+ : m_spinButtonElement(0)
+{
+}
+
+AXSpinButton::~AXSpinButton()
+{
+}
+
+LayoutRect AXSpinButton::elementRect() const
+{
+ ASSERT(m_spinButtonElement);
+
+ if (!m_spinButtonElement || !m_spinButtonElement->renderer())
+ return LayoutRect();
+
+ Vector<FloatQuad> quads;
+ m_spinButtonElement->renderer()->absoluteFocusRingQuads(quads);
+
+ return boundingBoxForQuads(m_spinButtonElement->renderer(), quads);
+}
+
+void AXSpinButton::addChildren()
+{
+ m_haveChildren = true;
+
+ AXSpinButtonPart* incrementor = static_cast<AXSpinButtonPart*>(axObjectCache()->getOrCreate(SpinButtonPartRole));
+ incrementor->setIsIncrementor(true);
+ incrementor->setParent(this);
+ m_children.append(incrementor);
+
+ AXSpinButtonPart* decrementor = static_cast<AXSpinButtonPart*>(axObjectCache()->getOrCreate(SpinButtonPartRole));
+ decrementor->setIsIncrementor(false);
+ decrementor->setParent(this);
+ m_children.append(decrementor);
+}
+
+void AXSpinButton::step(int amount)
+{
+ ASSERT(m_spinButtonElement);
+ if (!m_spinButtonElement)
+ return;
+
+ m_spinButtonElement->step(amount);
+}
+
+// AXSpinButtonPart
+
+AXSpinButtonPart::AXSpinButtonPart()
+ : m_isIncrementor(false)
+{
+}
+
+PassRefPtr<AXSpinButtonPart> AXSpinButtonPart::create()
+{
+ return adoptRef(new AXSpinButtonPart);
+}
+
+LayoutRect AXSpinButtonPart::elementRect() const
+{
+ // FIXME: This logic should exist in the render tree or elsewhere, but there is no
+ // relationship that exists that can be queried.
+
+ LayoutRect parentRect = parentObject()->elementRect();
+ if (m_isIncrementor) {
+ parentRect.setHeight(parentRect.height() / 2);
+ } else {
+ parentRect.setY(parentRect.y() + parentRect.height() / 2);
+ parentRect.setHeight(parentRect.height() / 2);
+ }
+
+ return parentRect;
+}
+
+bool AXSpinButtonPart::press() const
+{
+ if (!m_parent || !m_parent->isSpinButton())
+ return false;
+
+ AXSpinButton* spinButton = toAXSpinButton(parentObject());
+ if (m_isIncrementor)
+ spinButton->step(1);
+ else
+ spinButton->step(-1);
+
+ return true;
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AXSpinButton.h b/chromium/third_party/WebKit/Source/core/accessibility/AXSpinButton.h
new file mode 100644
index 00000000000..12ae3adb23b
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/accessibility/AXSpinButton.h
@@ -0,0 +1,78 @@
+/*
+ * Copyright (C) 2011 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef AXSpinButton_h
+#define AXSpinButton_h
+
+#include "core/accessibility/AXMockObject.h"
+
+#include "core/html/shadow/SpinButtonElement.h"
+
+namespace WebCore {
+
+class AXSpinButton : public AXMockObject {
+public:
+ static PassRefPtr<AXSpinButton> create();
+ virtual ~AXSpinButton();
+
+ void setSpinButtonElement(SpinButtonElement* spinButton) { m_spinButtonElement = spinButton; }
+ void step(int amount);
+
+private:
+ AXSpinButton();
+
+ virtual AccessibilityRole roleValue() const OVERRIDE { return SpinButtonRole; }
+ virtual bool isSpinButton() const OVERRIDE { return true; }
+ virtual bool isNativeSpinButton() const OVERRIDE { return true; }
+ virtual void addChildren() OVERRIDE;
+ virtual LayoutRect elementRect() const OVERRIDE;
+
+ SpinButtonElement* m_spinButtonElement;
+};
+
+class AXSpinButtonPart : public AXMockObject {
+public:
+ static PassRefPtr<AXSpinButtonPart> create();
+ virtual ~AXSpinButtonPart() { }
+
+ bool isIncrementor() const { return m_isIncrementor; }
+ void setIsIncrementor(bool value) { m_isIncrementor = value; }
+
+private:
+ AXSpinButtonPart();
+ bool m_isIncrementor : 1;
+
+ virtual bool press() const OVERRIDE;
+ virtual AccessibilityRole roleValue() const OVERRIDE { return ButtonRole; }
+ virtual bool isSpinButtonPart() const OVERRIDE { return true; }
+ virtual LayoutRect elementRect() const OVERRIDE;
+};
+
+DEFINE_AX_OBJECT_TYPE_CASTS(AXSpinButton, isNativeSpinButton());
+DEFINE_AX_OBJECT_TYPE_CASTS(AXSpinButtonPart, isSpinButtonPart());
+
+} // namespace WebCore
+
+#endif // AXSpinButton_h
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AXTable.cpp b/chromium/third_party/WebKit/Source/core/accessibility/AXTable.cpp
new file mode 100644
index 00000000000..f9f753096c1
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/accessibility/AXTable.cpp
@@ -0,0 +1,551 @@
+/*
+ * Copyright (C) 2008 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/accessibility/AXTable.h"
+
+#include "core/accessibility/AXObjectCache.h"
+#include "core/accessibility/AXTableCell.h"
+#include "core/accessibility/AXTableColumn.h"
+#include "core/accessibility/AXTableRow.h"
+#include "core/html/HTMLTableCaptionElement.h"
+#include "core/html/HTMLTableCellElement.h"
+#include "core/html/HTMLTableElement.h"
+#include "core/rendering/RenderTableCell.h"
+
+namespace WebCore {
+
+using namespace HTMLNames;
+
+AXTable::AXTable(RenderObject* renderer)
+ : AXRenderObject(renderer)
+ , m_headerContainer(0)
+ , m_isAXTable(true)
+{
+}
+
+AXTable::~AXTable()
+{
+}
+
+void AXTable::init()
+{
+ AXRenderObject::init();
+ m_isAXTable = isTableExposableThroughAccessibility();
+}
+
+PassRefPtr<AXTable> AXTable::create(RenderObject* renderer)
+{
+ return adoptRef(new AXTable(renderer));
+}
+
+bool AXTable::hasARIARole() const
+{
+ if (!m_renderer)
+ return false;
+
+ AccessibilityRole ariaRole = ariaRoleAttribute();
+ if (ariaRole != UnknownRole)
+ return true;
+
+ return false;
+}
+
+bool AXTable::isAXTable() const
+{
+ if (!m_renderer)
+ return false;
+
+ return m_isAXTable;
+}
+
+bool AXTable::isDataTable() const
+{
+ if (!m_renderer)
+ return false;
+
+ // Do not consider it a data table is it has an ARIA role.
+ if (hasARIARole())
+ return false;
+
+ // When a section of the document is contentEditable, all tables should be
+ // treated as data tables, otherwise users may not be able to work with rich
+ // text editors that allow creating and editing tables.
+ if (node() && node()->rendererIsEditable())
+ return true;
+
+ // This employs a heuristic to determine if this table should appear.
+ // Only "data" tables should be exposed as tables.
+ // Unfortunately, there is no good way to determine the difference
+ // between a "layout" table and a "data" table.
+
+ RenderTable* table = toRenderTable(m_renderer);
+ Node* tableNode = table->node();
+ if (!tableNode || !isHTMLTableElement(tableNode))
+ return false;
+
+ // if there is a caption element, summary, THEAD, or TFOOT section, it's most certainly a data table
+ HTMLTableElement* tableElement = toHTMLTableElement(tableNode);
+ if (!tableElement->summary().isEmpty() || tableElement->tHead() || tableElement->tFoot() || tableElement->caption())
+ return true;
+
+ // if someone used "rules" attribute than the table should appear
+ if (!tableElement->rules().isEmpty())
+ return true;
+
+ // if there's a colgroup or col element, it's probably a data table.
+ for (Node* child = tableElement->firstChild(); child; child = child->nextSibling()) {
+ if (child->hasTagName(colTag) || child->hasTagName(colgroupTag))
+ return true;
+ }
+
+ // go through the cell's and check for tell-tale signs of "data" table status
+ // cells have borders, or use attributes like headers, abbr, scope or axis
+ table->recalcSectionsIfNeeded();
+ RenderTableSection* firstBody = table->firstBody();
+ if (!firstBody)
+ return false;
+
+ int numCols = firstBody->numColumns();
+ int numRows = firstBody->numRows();
+
+ // If there's only one cell, it's not a good AXTable candidate.
+ if (numRows == 1 && numCols == 1)
+ return false;
+
+ // If there are at least 20 rows, we'll call it a data table.
+ if (numRows >= 20)
+ return true;
+
+ // Store the background color of the table to check against cell's background colors.
+ RenderStyle* tableStyle = table->style();
+ if (!tableStyle)
+ return false;
+ Color tableBGColor = tableStyle->visitedDependentColor(CSSPropertyBackgroundColor);
+
+ // check enough of the cells to find if the table matches our criteria
+ // Criteria:
+ // 1) must have at least one valid cell (and)
+ // 2) at least half of cells have borders (or)
+ // 3) at least half of cells have different bg colors than the table, and there is cell spacing
+ unsigned validCellCount = 0;
+ unsigned borderedCellCount = 0;
+ unsigned backgroundDifferenceCellCount = 0;
+ unsigned cellsWithTopBorder = 0;
+ unsigned cellsWithBottomBorder = 0;
+ unsigned cellsWithLeftBorder = 0;
+ unsigned cellsWithRightBorder = 0;
+
+ Color alternatingRowColors[5];
+ int alternatingRowColorCount = 0;
+
+ int headersInFirstColumnCount = 0;
+ for (int row = 0; row < numRows; ++row) {
+
+ int headersInFirstRowCount = 0;
+ for (int col = 0; col < numCols; ++col) {
+ RenderTableCell* cell = firstBody->primaryCellAt(row, col);
+ if (!cell)
+ continue;
+ Node* cellNode = cell->node();
+ if (!cellNode)
+ continue;
+
+ if (cell->width() < 1 || cell->height() < 1)
+ continue;
+
+ validCellCount++;
+
+ bool isTHCell = cellNode->hasTagName(thTag);
+ // If the first row is comprised of all <th> tags, assume it is a data table.
+ if (!row && isTHCell)
+ headersInFirstRowCount++;
+
+ // If the first column is comprised of all <th> tags, assume it is a data table.
+ if (!col && isTHCell)
+ headersInFirstColumnCount++;
+
+ // in this case, the developer explicitly assigned a "data" table attribute
+ if (cellNode->hasTagName(tdTag) || cellNode->hasTagName(thTag)) {
+ HTMLTableCellElement* cellElement = toHTMLTableCellElement(cellNode);
+ if (!cellElement->headers().isEmpty() || !cellElement->abbr().isEmpty()
+ || !cellElement->axis().isEmpty() || !cellElement->scope().isEmpty())
+ return true;
+ }
+
+ RenderStyle* renderStyle = cell->style();
+ if (!renderStyle)
+ continue;
+
+ // If the empty-cells style is set, we'll call it a data table.
+ if (renderStyle->emptyCells() == HIDE)
+ return true;
+
+ // If a cell has matching bordered sides, call it a (fully) bordered cell.
+ if ((cell->borderTop() > 0 && cell->borderBottom() > 0)
+ || (cell->borderLeft() > 0 && cell->borderRight() > 0))
+ borderedCellCount++;
+
+ // Also keep track of each individual border, so we can catch tables where most
+ // cells have a bottom border, for example.
+ if (cell->borderTop() > 0)
+ cellsWithTopBorder++;
+ if (cell->borderBottom() > 0)
+ cellsWithBottomBorder++;
+ if (cell->borderLeft() > 0)
+ cellsWithLeftBorder++;
+ if (cell->borderRight() > 0)
+ cellsWithRightBorder++;
+
+ // If the cell has a different color from the table and there is cell spacing,
+ // then it is probably a data table cell (spacing and colors take the place of borders).
+ Color cellColor = renderStyle->visitedDependentColor(CSSPropertyBackgroundColor);
+ if (table->hBorderSpacing() > 0 && table->vBorderSpacing() > 0
+ && tableBGColor != cellColor && cellColor.alpha() != 1)
+ backgroundDifferenceCellCount++;
+
+ // If we've found 10 "good" cells, we don't need to keep searching.
+ if (borderedCellCount >= 10 || backgroundDifferenceCellCount >= 10)
+ return true;
+
+ // For the first 5 rows, cache the background color so we can check if this table has zebra-striped rows.
+ if (row < 5 && row == alternatingRowColorCount) {
+ RenderObject* renderRow = cell->parent();
+ if (!renderRow || !renderRow->isBoxModelObject() || !toRenderBoxModelObject(renderRow)->isTableRow())
+ continue;
+ RenderStyle* rowRenderStyle = renderRow->style();
+ if (!rowRenderStyle)
+ continue;
+ Color rowColor = rowRenderStyle->visitedDependentColor(CSSPropertyBackgroundColor);
+ alternatingRowColors[alternatingRowColorCount] = rowColor;
+ alternatingRowColorCount++;
+ }
+ }
+
+ if (!row && headersInFirstRowCount == numCols && numCols > 1)
+ return true;
+ }
+
+ if (headersInFirstColumnCount == numRows && numRows > 1)
+ return true;
+
+ // if there is less than two valid cells, it's not a data table
+ if (validCellCount <= 1)
+ return false;
+
+ // half of the cells had borders, it's a data table
+ unsigned neededCellCount = validCellCount / 2;
+ if (borderedCellCount >= neededCellCount
+ || cellsWithTopBorder >= neededCellCount
+ || cellsWithBottomBorder >= neededCellCount
+ || cellsWithLeftBorder >= neededCellCount
+ || cellsWithRightBorder >= neededCellCount)
+ return true;
+
+ // half had different background colors, it's a data table
+ if (backgroundDifferenceCellCount >= neededCellCount)
+ return true;
+
+ // Check if there is an alternating row background color indicating a zebra striped style pattern.
+ if (alternatingRowColorCount > 2) {
+ Color firstColor = alternatingRowColors[0];
+ for (int k = 1; k < alternatingRowColorCount; k++) {
+ // If an odd row was the same color as the first row, its not alternating.
+ if (k % 2 == 1 && alternatingRowColors[k] == firstColor)
+ return false;
+ // If an even row is not the same as the first row, its not alternating.
+ if (!(k % 2) && alternatingRowColors[k] != firstColor)
+ return false;
+ }
+ return true;
+ }
+
+ return false;
+}
+
+bool AXTable::isTableExposableThroughAccessibility() const
+{
+ // The following is a heuristic used to determine if a
+ // <table> should be exposed as an AXTable. The goal
+ // is to only show "data" tables.
+
+ if (!m_renderer)
+ return false;
+
+ // If the developer assigned an aria role to this, then we
+ // shouldn't expose it as a table, unless, of course, the aria
+ // role is a table.
+ if (hasARIARole())
+ return false;
+
+ return isDataTable();
+}
+
+void AXTable::clearChildren()
+{
+ AXRenderObject::clearChildren();
+ m_rows.clear();
+ m_columns.clear();
+
+ if (m_headerContainer) {
+ m_headerContainer->detachFromParent();
+ m_headerContainer = 0;
+ }
+}
+
+void AXTable::addChildren()
+{
+ if (!isAXTable()) {
+ AXRenderObject::addChildren();
+ return;
+ }
+
+ ASSERT(!m_haveChildren);
+
+ m_haveChildren = true;
+ if (!m_renderer || !m_renderer->isTable())
+ return;
+
+ RenderTable* table = toRenderTable(m_renderer);
+ AXObjectCache* axCache = m_renderer->document().axObjectCache();
+
+ // Go through all the available sections to pull out the rows and add them as children.
+ table->recalcSectionsIfNeeded();
+ RenderTableSection* tableSection = table->topSection();
+ if (!tableSection)
+ return;
+
+ RenderTableSection* initialTableSection = tableSection;
+ while (tableSection) {
+
+ HashSet<AXObject*> appendedRows;
+ unsigned numRows = tableSection->numRows();
+ for (unsigned rowIndex = 0; rowIndex < numRows; ++rowIndex) {
+
+ RenderTableRow* renderRow = tableSection->rowRendererAt(rowIndex);
+ if (!renderRow)
+ continue;
+
+ AXObject* rowObject = axCache->getOrCreate(renderRow);
+ if (!rowObject->isTableRow())
+ continue;
+
+ AXTableRow* row = toAXTableRow(rowObject);
+ // We need to check every cell for a new row, because cell spans
+ // can cause us to miss rows if we just check the first column.
+ if (appendedRows.contains(row))
+ continue;
+
+ row->setRowIndex(static_cast<int>(m_rows.size()));
+ m_rows.append(row);
+ if (!row->accessibilityIsIgnored())
+ m_children.append(row);
+ appendedRows.add(row);
+ }
+
+ tableSection = table->sectionBelow(tableSection, SkipEmptySections);
+ }
+
+ // make the columns based on the number of columns in the first body
+ unsigned length = initialTableSection->numColumns();
+ for (unsigned i = 0; i < length; ++i) {
+ AXTableColumn* column = toAXTableColumn(axCache->getOrCreate(ColumnRole));
+ column->setColumnIndex((int)i);
+ column->setParent(this);
+ m_columns.append(column);
+ if (!column->accessibilityIsIgnored())
+ m_children.append(column);
+ }
+
+ AXObject* headerContainerObject = headerContainer();
+ if (headerContainerObject && !headerContainerObject->accessibilityIsIgnored())
+ m_children.append(headerContainerObject);
+}
+
+AXObject* AXTable::headerContainer()
+{
+ if (m_headerContainer)
+ return m_headerContainer.get();
+
+ AXMockObject* tableHeader = toAXMockObject(axObjectCache()->getOrCreate(TableHeaderContainerRole));
+ tableHeader->setParent(this);
+
+ m_headerContainer = tableHeader;
+ return m_headerContainer.get();
+}
+
+AXObject::AccessibilityChildrenVector& AXTable::columns()
+{
+ updateChildrenIfNecessary();
+
+ return m_columns;
+}
+
+AXObject::AccessibilityChildrenVector& AXTable::rows()
+{
+ updateChildrenIfNecessary();
+
+ return m_rows;
+}
+
+void AXTable::columnHeaders(AccessibilityChildrenVector& headers)
+{
+ if (!m_renderer)
+ return;
+
+ updateChildrenIfNecessary();
+
+ unsigned colCount = m_columns.size();
+ for (unsigned k = 0; k < colCount; ++k) {
+ AXObject* header = toAXTableColumn(m_columns[k].get())->headerObject();
+ if (!header)
+ continue;
+ headers.append(header);
+ }
+}
+
+void AXTable::cells(AXObject::AccessibilityChildrenVector& cells)
+{
+ if (!m_renderer)
+ return;
+
+ updateChildrenIfNecessary();
+
+ int numRows = m_rows.size();
+ for (int row = 0; row < numRows; ++row) {
+ AccessibilityChildrenVector rowChildren = m_rows[row]->children();
+ cells.append(rowChildren);
+ }
+}
+
+unsigned AXTable::columnCount()
+{
+ updateChildrenIfNecessary();
+
+ return m_columns.size();
+}
+
+unsigned AXTable::rowCount()
+{
+ updateChildrenIfNecessary();
+
+ return m_rows.size();
+}
+
+int AXTable::tableLevel() const
+{
+ int level = 0;
+ for (AXObject* obj = static_cast<AXObject*>(const_cast<AXTable*>(this)); obj; obj = obj->parentObject()) {
+ if (obj->isAXTable())
+ ++level;
+ }
+
+ return level;
+}
+
+AXTableCell* AXTable::cellForColumnAndRow(unsigned column, unsigned row)
+{
+ updateChildrenIfNecessary();
+ if (column >= columnCount() || row >= rowCount())
+ return 0;
+
+ // Iterate backwards through the rows in case the desired cell has a rowspan and exists in a previous row.
+ for (unsigned rowIndexCounter = row + 1; rowIndexCounter > 0; --rowIndexCounter) {
+ unsigned rowIndex = rowIndexCounter - 1;
+ AccessibilityChildrenVector children = m_rows[rowIndex]->children();
+ // Since some cells may have colspans, we have to check the actual range of each
+ // cell to determine which is the right one.
+ for (unsigned colIndexCounter = std::min(static_cast<unsigned>(children.size()), column + 1); colIndexCounter > 0; --colIndexCounter) {
+ unsigned colIndex = colIndexCounter - 1;
+ AXObject* child = children[colIndex].get();
+ ASSERT(child->isTableCell());
+ if (!child->isTableCell())
+ continue;
+
+ pair<unsigned, unsigned> columnRange;
+ pair<unsigned, unsigned> rowRange;
+ AXTableCell* tableCellChild = toAXTableCell(child);
+ tableCellChild->columnIndexRange(columnRange);
+ tableCellChild->rowIndexRange(rowRange);
+
+ if ((column >= columnRange.first && column < (columnRange.first + columnRange.second))
+ && (row >= rowRange.first && row < (rowRange.first + rowRange.second)))
+ return tableCellChild;
+ }
+ }
+
+ return 0;
+}
+
+AccessibilityRole AXTable::roleValue() const
+{
+ if (!isAXTable())
+ return AXRenderObject::roleValue();
+
+ return TableRole;
+}
+
+bool AXTable::computeAccessibilityIsIgnored() const
+{
+ AXObjectInclusion decision = defaultObjectInclusion();
+ if (decision == IncludeObject)
+ return false;
+ if (decision == IgnoreObject)
+ return true;
+
+ if (!isAXTable())
+ return AXRenderObject::computeAccessibilityIsIgnored();
+
+ return false;
+}
+
+String AXTable::title() const
+{
+ if (!isAXTable())
+ return AXRenderObject::title();
+
+ String title;
+ if (!m_renderer)
+ return title;
+
+ // see if there is a caption
+ Node* tableElement = m_renderer->node();
+ if (tableElement && isHTMLTableElement(tableElement)) {
+ HTMLTableCaptionElement* caption = toHTMLTableElement(tableElement)->caption();
+ if (caption)
+ title = caption->innerText();
+ }
+
+ // try the standard
+ if (title.isEmpty())
+ title = AXRenderObject::title();
+
+ return title;
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AXTable.h b/chromium/third_party/WebKit/Source/core/accessibility/AXTable.h
new file mode 100644
index 00000000000..bca782cba82
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/accessibility/AXTable.h
@@ -0,0 +1,96 @@
+/*
+ * Copyright (C) 2008 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef AXTable_h
+#define AXTable_h
+
+#include "core/accessibility/AXRenderObject.h"
+#include "wtf/Forward.h"
+
+namespace WebCore {
+
+class AXTableCell;
+class RenderTableSection;
+
+class AXTable : public AXRenderObject {
+
+protected:
+ explicit AXTable(RenderObject*);
+public:
+ static PassRefPtr<AXTable> create(RenderObject*);
+ virtual ~AXTable();
+
+ virtual void init() OVERRIDE;
+
+ virtual bool isAXTable() const OVERRIDE;
+ virtual bool isDataTable() const OVERRIDE;
+
+ virtual AccessibilityRole roleValue() const OVERRIDE;
+
+ virtual void addChildren() OVERRIDE;
+ virtual void clearChildren() OVERRIDE;
+
+ // To be overridden by AXARIAGrid.
+ virtual bool isAriaTable() const { return false; }
+ virtual bool supportsSelectedRows() { return false; }
+
+ AccessibilityChildrenVector& columns();
+ AccessibilityChildrenVector& rows();
+
+ unsigned columnCount();
+ unsigned rowCount();
+ virtual int tableLevel() const OVERRIDE;
+
+ virtual String title() const OVERRIDE;
+
+ // all the cells in the table
+ void cells(AccessibilityChildrenVector&);
+ AXTableCell* cellForColumnAndRow(unsigned column, unsigned row);
+
+ void columnHeaders(AccessibilityChildrenVector&);
+
+ // an object that contains, as children, all the objects that act as headers
+ AXObject* headerContainer();
+
+protected:
+ AccessibilityChildrenVector m_rows;
+ AccessibilityChildrenVector m_columns;
+
+ RefPtr<AXObject> m_headerContainer;
+ bool m_isAXTable;
+
+ bool hasARIARole() const;
+ virtual bool isTableExposableThroughAccessibility() const;
+ virtual bool computeAccessibilityIsIgnored() const OVERRIDE;
+};
+
+DEFINE_AX_OBJECT_TYPE_CASTS(AXTable, isAXTable());
+
+} // namespace WebCore
+
+#endif // AXTable_h
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AXTableCell.cpp b/chromium/third_party/WebKit/Source/core/accessibility/AXTableCell.cpp
new file mode 100644
index 00000000000..7335a272db6
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/accessibility/AXTableCell.cpp
@@ -0,0 +1,178 @@
+/*
+ * Copyright (C) 2008 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/accessibility/AXTableCell.h"
+
+#include "core/accessibility/AXObjectCache.h"
+#include "core/rendering/RenderTableCell.h"
+
+using namespace std;
+
+namespace WebCore {
+
+using namespace HTMLNames;
+
+AXTableCell::AXTableCell(RenderObject* renderer)
+ : AXRenderObject(renderer)
+{
+}
+
+AXTableCell::~AXTableCell()
+{
+}
+
+PassRefPtr<AXTableCell> AXTableCell::create(RenderObject* renderer)
+{
+ return adoptRef(new AXTableCell(renderer));
+}
+
+bool AXTableCell::computeAccessibilityIsIgnored() const
+{
+ AXObjectInclusion decision = defaultObjectInclusion();
+ if (decision == IncludeObject)
+ return false;
+ if (decision == IgnoreObject)
+ return true;
+
+ if (!isTableCell())
+ return AXRenderObject::computeAccessibilityIsIgnored();
+
+ return false;
+}
+
+AXObject* AXTableCell::parentTable() const
+{
+ if (!m_renderer || !m_renderer->isTableCell())
+ return 0;
+
+ // If the document no longer exists, we might not have an axObjectCache.
+ if (!axObjectCache())
+ return 0;
+
+ // Do not use getOrCreate. parentTable() can be called while the render tree is being modified
+ // by javascript, and creating a table element may try to access the render tree while in a bad state.
+ // By using only get() implies that the AXTable must be created before AXTableCells. This should
+ // always be the case when AT clients access a table.
+ // https://bugs.webkit.org/show_bug.cgi?id=42652
+ return axObjectCache()->get(toRenderTableCell(m_renderer)->table());
+}
+
+bool AXTableCell::isTableCell() const
+{
+ AXObject* parent = parentObjectUnignored();
+ if (!parent || !parent->isTableRow())
+ return false;
+
+ return true;
+}
+
+AccessibilityRole AXTableCell::determineAccessibilityRole()
+{
+ if (!isTableCell())
+ return AXRenderObject::determineAccessibilityRole();
+
+ return CellRole;
+}
+
+void AXTableCell::rowIndexRange(pair<unsigned, unsigned>& rowRange)
+{
+ if (!m_renderer || !m_renderer->isTableCell())
+ return;
+
+ RenderTableCell* renderCell = toRenderTableCell(m_renderer);
+ rowRange.first = renderCell->rowIndex();
+ rowRange.second = renderCell->rowSpan();
+
+ // since our table might have multiple sections, we have to offset our row appropriately
+ RenderTableSection* section = renderCell->section();
+ RenderTable* table = renderCell->table();
+ if (!table || !section)
+ return;
+
+ RenderTableSection* tableSection = table->topSection();
+ unsigned rowOffset = 0;
+ while (tableSection) {
+ if (tableSection == section)
+ break;
+ rowOffset += tableSection->numRows();
+ tableSection = table->sectionBelow(tableSection, SkipEmptySections);
+ }
+
+ rowRange.first += rowOffset;
+}
+
+void AXTableCell::columnIndexRange(pair<unsigned, unsigned>& columnRange)
+{
+ if (!m_renderer || !m_renderer->isTableCell())
+ return;
+
+ RenderTableCell* renderCell = toRenderTableCell(m_renderer);
+ columnRange.first = renderCell->col();
+ columnRange.second = renderCell->colSpan();
+}
+
+AXObject* AXTableCell::titleUIElement() const
+{
+ // Try to find if the first cell in this row is a <th>. If it is,
+ // then it can act as the title ui element. (This is only in the
+ // case when the table is not appearing as an AXTable.)
+ if (isTableCell() || !m_renderer || !m_renderer->isTableCell())
+ return 0;
+
+ // Table cells that are th cannot have title ui elements, since by definition
+ // they are title ui elements
+ Node* node = m_renderer->node();
+ if (node && node->hasTagName(thTag))
+ return 0;
+
+ RenderTableCell* renderCell = toRenderTableCell(m_renderer);
+
+ // If this cell is in the first column, there is no need to continue.
+ int col = renderCell->col();
+ if (!col)
+ return 0;
+
+ int row = renderCell->rowIndex();
+
+ RenderTableSection* section = renderCell->section();
+ if (!section)
+ return 0;
+
+ RenderTableCell* headerCell = section->primaryCellAt(row, 0);
+ if (!headerCell || headerCell == renderCell)
+ return 0;
+
+ Node* cellElement = headerCell->node();
+ if (!cellElement || !cellElement->hasTagName(thTag))
+ return 0;
+
+ return axObjectCache()->getOrCreate(headerCell);
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AXTableCell.h b/chromium/third_party/WebKit/Source/core/accessibility/AXTableCell.h
new file mode 100644
index 00000000000..c62d0d32c5a
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/accessibility/AXTableCell.h
@@ -0,0 +1,67 @@
+/*
+ * Copyright (C) 2008 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef AXTableCell_h
+#define AXTableCell_h
+
+#include "core/accessibility/AXRenderObject.h"
+
+namespace WebCore {
+
+class AXTableCell : public AXRenderObject {
+
+protected:
+ explicit AXTableCell(RenderObject*);
+public:
+ static PassRefPtr<AXTableCell> create(RenderObject*);
+ virtual ~AXTableCell();
+
+ virtual bool isTableCell() const OVERRIDE;
+
+ // fills in the start location and row span of cell
+ virtual void rowIndexRange(pair<unsigned, unsigned>& rowRange);
+ // fills in the start location and column span of cell
+ virtual void columnIndexRange(pair<unsigned, unsigned>& columnRange);
+
+protected:
+ virtual AXObject* parentTable() const;
+ int m_rowIndex;
+ virtual AccessibilityRole determineAccessibilityRole() OVERRIDE;
+
+private:
+ // If a table cell is not exposed as a table cell, a TH element can serve as its title UI element.
+ virtual AXObject* titleUIElement() const OVERRIDE;
+ virtual bool exposesTitleUIElement() const OVERRIDE { return true; }
+ virtual bool computeAccessibilityIsIgnored() const OVERRIDE;
+};
+
+DEFINE_AX_OBJECT_TYPE_CASTS(AXTableCell, isTableCell());
+
+} // namespace WebCore
+
+#endif // AXTableCell_h
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AXTableColumn.cpp b/chromium/third_party/WebKit/Source/core/accessibility/AXTableColumn.cpp
new file mode 100644
index 00000000000..1b58379accd
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/accessibility/AXTableColumn.cpp
@@ -0,0 +1,185 @@
+/*
+ * Copyright (C) 2008 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/accessibility/AXTableColumn.h"
+
+#include "core/accessibility/AXObjectCache.h"
+#include "core/accessibility/AXTableCell.h"
+#include "core/rendering/RenderTableCell.h"
+
+using namespace std;
+
+namespace WebCore {
+
+using namespace HTMLNames;
+
+AXTableColumn::AXTableColumn()
+{
+}
+
+AXTableColumn::~AXTableColumn()
+{
+}
+
+PassRefPtr<AXTableColumn> AXTableColumn::create()
+{
+ return adoptRef(new AXTableColumn());
+}
+
+void AXTableColumn::setParent(AXObject* parent)
+{
+ AXMockObject::setParent(parent);
+
+ clearChildren();
+}
+
+LayoutRect AXTableColumn::elementRect() const
+{
+ // this will be filled in when addChildren is called
+ return m_columnRect;
+}
+
+AXObject* AXTableColumn::headerObject()
+{
+ if (!m_parent)
+ return 0;
+
+ RenderObject* renderer = m_parent->renderer();
+ if (!renderer)
+ return 0;
+
+ if (!m_parent->isAXTable())
+ return 0;
+
+ AXTable* parentTable = toAXTable(m_parent);
+ if (parentTable->isAriaTable()) {
+ AccessibilityChildrenVector rowChildren = children();
+ unsigned childrenCount = rowChildren.size();
+ for (unsigned i = 0; i < childrenCount; ++i) {
+ AXObject* cell = rowChildren[i].get();
+ if (cell->ariaRoleAttribute() == ColumnHeaderRole)
+ return cell;
+ }
+
+ return 0;
+ }
+
+ if (!renderer->isTable())
+ return 0;
+
+ RenderTable* table = toRenderTable(renderer);
+
+ AXObject* headerObject = 0;
+
+ // try the <thead> section first. this doesn't require th tags
+ headerObject = headerObjectForSection(table->header(), false);
+
+ if (headerObject)
+ return headerObject;
+
+ // now try for <th> tags in the first body
+ headerObject = headerObjectForSection(table->firstBody(), true);
+
+ return headerObject;
+}
+
+AXObject* AXTableColumn::headerObjectForSection(RenderTableSection* section, bool thTagRequired)
+{
+ if (!section)
+ return 0;
+
+ unsigned numCols = section->numColumns();
+ if (m_columnIndex >= numCols)
+ return 0;
+
+ if (!section->numRows())
+ return 0;
+
+ RenderTableCell* cell = 0;
+ // also account for cells that have a span
+ for (int testCol = m_columnIndex; testCol >= 0; --testCol) {
+ RenderTableCell* testCell = section->primaryCellAt(0, testCol);
+ if (!testCell)
+ continue;
+
+ // we've reached a cell that doesn't even overlap our column
+ // it can't be our header
+ if ((testCell->col() + (testCell->colSpan()-1)) < m_columnIndex)
+ break;
+
+ Node* node = testCell->node();
+ if (!node)
+ continue;
+
+ if (thTagRequired && !node->hasTagName(thTag))
+ continue;
+
+ cell = testCell;
+ }
+
+ if (!cell)
+ return 0;
+
+ return axObjectCache()->getOrCreate(cell);
+}
+
+bool AXTableColumn::computeAccessibilityIsIgnored() const
+{
+ if (!m_parent)
+ return true;
+
+ return m_parent->accessibilityIsIgnored();
+}
+
+void AXTableColumn::addChildren()
+{
+ ASSERT(!m_haveChildren);
+
+ m_haveChildren = true;
+ if (!m_parent || !m_parent->isAXTable())
+ return;
+
+ AXTable* parentTable = toAXTable(m_parent);
+ int numRows = parentTable->rowCount();
+
+ for (int i = 0; i < numRows; i++) {
+ AXTableCell* cell = parentTable->cellForColumnAndRow(m_columnIndex, i);
+ if (!cell)
+ continue;
+
+ // make sure the last one isn't the same as this one (rowspan cells)
+ if (m_children.size() > 0 && m_children.last() == cell)
+ continue;
+
+ m_children.append(cell);
+ m_columnRect.unite(cell->elementRect());
+ }
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AXTableColumn.h b/chromium/third_party/WebKit/Source/core/accessibility/AXTableColumn.h
new file mode 100644
index 00000000000..9da318774da
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/accessibility/AXTableColumn.h
@@ -0,0 +1,72 @@
+/*
+ * Copyright (C) 2008 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef AXTableColumn_h
+#define AXTableColumn_h
+
+#include "core/accessibility/AXMockObject.h"
+#include "core/accessibility/AXTable.h"
+
+namespace WebCore {
+
+class RenderTableSection;
+
+class AXTableColumn : public AXMockObject {
+
+private:
+ AXTableColumn();
+public:
+ static PassRefPtr<AXTableColumn> create();
+ virtual ~AXTableColumn();
+
+ AXObject* headerObject();
+
+ virtual AccessibilityRole roleValue() const OVERRIDE { return ColumnRole; }
+
+ void setColumnIndex(int columnIndex) { m_columnIndex = columnIndex; }
+ int columnIndex() const { return m_columnIndex; }
+
+ virtual void addChildren() OVERRIDE;
+ virtual void setParent(AXObject*) OVERRIDE;
+
+ virtual LayoutRect elementRect() const OVERRIDE;
+
+private:
+ unsigned m_columnIndex;
+ LayoutRect m_columnRect;
+
+ virtual bool isTableCol() const OVERRIDE { return true; }
+ AXObject* headerObjectForSection(RenderTableSection*, bool thTagRequired);
+ virtual bool computeAccessibilityIsIgnored() const OVERRIDE;
+};
+
+DEFINE_AX_OBJECT_TYPE_CASTS(AXTableColumn, isTableCol());
+
+} // namespace WebCore
+
+#endif // AXTableColumn_h
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AXTableHeaderContainer.cpp b/chromium/third_party/WebKit/Source/core/accessibility/AXTableHeaderContainer.cpp
new file mode 100644
index 00000000000..5abb0a3857c
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/accessibility/AXTableHeaderContainer.cpp
@@ -0,0 +1,79 @@
+/*
+ * Copyright (C) 2008 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/accessibility/AXTableHeaderContainer.h"
+
+
+using namespace std;
+
+namespace WebCore {
+
+AXTableHeaderContainer::AXTableHeaderContainer()
+{
+}
+
+AXTableHeaderContainer::~AXTableHeaderContainer()
+{
+}
+
+PassRefPtr<AXTableHeaderContainer> AXTableHeaderContainer::create()
+{
+ return adoptRef(new AXTableHeaderContainer());
+}
+
+LayoutRect AXTableHeaderContainer::elementRect() const
+{
+ // this will be filled in when addChildren is called
+ return m_headerRect;
+}
+
+bool AXTableHeaderContainer::computeAccessibilityIsIgnored() const
+{
+ if (!m_parent)
+ return true;
+
+ return m_parent->accessibilityIsIgnored();
+}
+
+void AXTableHeaderContainer::addChildren()
+{
+ ASSERT(!m_haveChildren);
+
+ m_haveChildren = true;
+ if (!m_parent || !m_parent->isAXTable())
+ return;
+
+ toAXTable(m_parent)->columnHeaders(m_children);
+
+ unsigned length = m_children.size();
+ for (unsigned k = 0; k < length; ++k)
+ m_headerRect.unite(m_children[k]->elementRect());
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AXTableHeaderContainer.h b/chromium/third_party/WebKit/Source/core/accessibility/AXTableHeaderContainer.h
new file mode 100644
index 00000000000..3870aa7d67c
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/accessibility/AXTableHeaderContainer.h
@@ -0,0 +1,59 @@
+/*
+ * Copyright (C) 2008 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef AXTableHeaderContainer_h
+#define AXTableHeaderContainer_h
+
+#include "core/accessibility/AXMockObject.h"
+#include "core/accessibility/AXTable.h"
+
+namespace WebCore {
+
+class AXTableHeaderContainer : public AXMockObject {
+
+private:
+ AXTableHeaderContainer();
+public:
+ static PassRefPtr<AXTableHeaderContainer> create();
+ virtual ~AXTableHeaderContainer();
+
+ virtual AccessibilityRole roleValue() const OVERRIDE { return TableHeaderContainerRole; }
+
+ virtual void addChildren() OVERRIDE;
+
+ virtual LayoutRect elementRect() const OVERRIDE;
+
+private:
+ LayoutRect m_headerRect;
+
+ virtual bool computeAccessibilityIsIgnored() const OVERRIDE;
+};
+
+} // namespace WebCore
+
+#endif // AXTableHeaderContainer_h
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AXTableRow.cpp b/chromium/third_party/WebKit/Source/core/accessibility/AXTableRow.cpp
new file mode 100644
index 00000000000..bf3dabb4065
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/accessibility/AXTableRow.cpp
@@ -0,0 +1,132 @@
+/*
+ * Copyright (C) 2008 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/accessibility/AXTableRow.h"
+
+#include "core/accessibility/AXTableCell.h"
+#include "core/rendering/RenderTableRow.h"
+
+using namespace std;
+
+namespace WebCore {
+
+using namespace HTMLNames;
+
+AXTableRow::AXTableRow(RenderObject* renderer)
+ : AXRenderObject(renderer)
+{
+}
+
+AXTableRow::~AXTableRow()
+{
+}
+
+PassRefPtr<AXTableRow> AXTableRow::create(RenderObject* renderer)
+{
+ return adoptRef(new AXTableRow(renderer));
+}
+
+AccessibilityRole AXTableRow::determineAccessibilityRole()
+{
+ if (!isTableRow())
+ return AXRenderObject::determineAccessibilityRole();
+
+ m_ariaRole = determineAriaRoleAttribute();
+
+ AccessibilityRole ariaRole = ariaRoleAttribute();
+ if (ariaRole != UnknownRole)
+ return ariaRole;
+
+ return RowRole;
+}
+
+bool AXTableRow::isTableRow() const
+{
+ AXObject* table = parentTable();
+ if (!table || !table->isAXTable())
+ return false;
+
+ return true;
+}
+
+AXObject* AXTableRow::observableObject() const
+{
+ // This allows the table to be the one who sends notifications about tables.
+ return parentTable();
+}
+
+bool AXTableRow::computeAccessibilityIsIgnored() const
+{
+ AXObjectInclusion decision = defaultObjectInclusion();
+ if (decision == IncludeObject)
+ return false;
+ if (decision == IgnoreObject)
+ return true;
+
+ if (!isTableRow())
+ return AXRenderObject::computeAccessibilityIsIgnored();
+
+ return false;
+}
+
+AXObject* AXTableRow::parentTable() const
+{
+ AXObject* parent = parentObjectUnignored();
+ if (!parent || !parent->isAXTable())
+ return 0;
+
+ return parent;
+}
+
+AXObject* AXTableRow::headerObject()
+{
+ if (!m_renderer || !m_renderer->isTableRow())
+ return 0;
+
+ AccessibilityChildrenVector rowChildren = children();
+ if (!rowChildren.size())
+ return 0;
+
+ // check the first element in the row to see if it is a TH element
+ AXObject* cell = rowChildren[0].get();
+ if (!cell->isTableCell())
+ return 0;
+
+ RenderObject* cellRenderer = toAXTableCell(cell)->renderer();
+ if (!cellRenderer)
+ return 0;
+
+ Node* cellNode = cellRenderer->node();
+ if (!cellNode || !cellNode->hasTagName(thTag))
+ return 0;
+
+ return cell;
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AXTableRow.h b/chromium/third_party/WebKit/Source/core/accessibility/AXTableRow.h
new file mode 100644
index 00000000000..90eca7fba49
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/accessibility/AXTableRow.h
@@ -0,0 +1,71 @@
+/*
+ * Copyright (C) 2008 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef AXTableRow_h
+#define AXTableRow_h
+
+#include "core/accessibility/AXRenderObject.h"
+
+namespace WebCore {
+
+class AXTableRow : public AXRenderObject {
+
+protected:
+ explicit AXTableRow(RenderObject*);
+public:
+ static PassRefPtr<AXTableRow> create(RenderObject*);
+ virtual ~AXTableRow();
+
+ virtual bool isTableRow() const OVERRIDE;
+
+ // retrieves the "row" header (a th tag in the rightmost column)
+ virtual AXObject* headerObject();
+ virtual AXObject* parentTable() const;
+
+ void setRowIndex(int rowIndex) { m_rowIndex = rowIndex; }
+ int rowIndex() const { return m_rowIndex; }
+
+ // allows the table to add other children that may not originate
+ // in the row, but their col/row spans overlap into it
+ void appendChild(AXObject*);
+
+protected:
+ virtual AccessibilityRole determineAccessibilityRole() OVERRIDE;
+
+private:
+ int m_rowIndex;
+
+ virtual AXObject* observableObject() const OVERRIDE;
+ virtual bool computeAccessibilityIsIgnored() const OVERRIDE;
+};
+
+DEFINE_AX_OBJECT_TYPE_CASTS(AXTableRow, isTableRow());
+
+} // namespace WebCore
+
+#endif // AXTableRow_h
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityARIAGrid.cpp b/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityARIAGrid.cpp
deleted file mode 100644
index 73b2fb7f2b8..00000000000
--- a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityARIAGrid.cpp
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
- * Copyright (C) 2009 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/accessibility/AccessibilityARIAGrid.h"
-
-#include "core/accessibility/AXObjectCache.h"
-#include "core/accessibility/AccessibilityTableColumn.h"
-#include "core/accessibility/AccessibilityTableRow.h"
-#include "core/rendering/RenderObject.h"
-
-using namespace std;
-
-namespace WebCore {
-
-AccessibilityARIAGrid::AccessibilityARIAGrid(RenderObject* renderer)
- : AccessibilityTable(renderer)
-{
-}
-
-AccessibilityARIAGrid::~AccessibilityARIAGrid()
-{
-}
-
-PassRefPtr<AccessibilityARIAGrid> AccessibilityARIAGrid::create(RenderObject* renderer)
-{
- return adoptRef(new AccessibilityARIAGrid(renderer));
-}
-
-bool AccessibilityARIAGrid::addTableCellChild(AccessibilityObject* child, HashSet<AccessibilityObject*>& appendedRows, unsigned& columnCount)
-{
- if (!child || !child->isTableRow() || child->ariaRoleAttribute() != RowRole)
- return false;
-
- AccessibilityTableRow* row = static_cast<AccessibilityTableRow*>(child);
- if (appendedRows.contains(row))
- return false;
-
- // store the maximum number of columns
- unsigned rowCellCount = row->children().size();
- if (rowCellCount > columnCount)
- columnCount = rowCellCount;
-
- row->setRowIndex((int)m_rows.size());
- m_rows.append(row);
-
- // Try adding the row if it's not ignoring accessibility,
- // otherwise add its children (the cells) as the grid's children.
- if (!row->accessibilityIsIgnored())
- m_children.append(row);
- else
- m_children.append(row->children());
-
- appendedRows.add(row);
- return true;
-}
-
-void AccessibilityARIAGrid::addChildren()
-{
- ASSERT(!m_haveChildren);
-
- if (!isAccessibilityTable()) {
- AccessibilityRenderObject::addChildren();
- return;
- }
-
- m_haveChildren = true;
- if (!m_renderer)
- return;
-
- AXObjectCache* axCache = m_renderer->document().axObjectCache();
-
- // add only rows that are labeled as aria rows
- HashSet<AccessibilityObject*> appendedRows;
- unsigned columnCount = 0;
- for (RefPtr<AccessibilityObject> child = firstChild(); child; child = child->nextSibling()) {
-
- if (!addTableCellChild(child.get(), appendedRows, columnCount)) {
-
- // in case the render tree doesn't match the expected ARIA hierarchy, look at the children
- if (!child->hasChildren())
- child->addChildren();
-
- // The children of this non-row will contain all non-ignored elements (recursing to find them).
- // This allows the table to dive arbitrarily deep to find the rows.
- AccessibilityChildrenVector children = child->children();
- size_t length = children.size();
- for (size_t i = 0; i < length; ++i)
- addTableCellChild(children[i].get(), appendedRows, columnCount);
- }
- }
-
- // make the columns based on the number of columns in the first body
- for (unsigned i = 0; i < columnCount; ++i) {
- AccessibilityTableColumn* column = static_cast<AccessibilityTableColumn*>(axCache->getOrCreate(ColumnRole));
- column->setColumnIndex((int)i);
- column->setParent(this);
- m_columns.append(column);
- if (!column->accessibilityIsIgnored())
- m_children.append(column);
- }
-
- AccessibilityObject* headerContainerObject = headerContainer();
- if (headerContainerObject && !headerContainerObject->accessibilityIsIgnored())
- m_children.append(headerContainerObject);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityARIAGrid.h b/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityARIAGrid.h
deleted file mode 100644
index cfb34894cea..00000000000
--- a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityARIAGrid.h
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Copyright (C) 2009 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef AccessibilityARIAGrid_h
-#define AccessibilityARIAGrid_h
-
-#include "core/accessibility/AccessibilityTable.h"
-#include "wtf/Forward.h"
-
-namespace WebCore {
-
-class AccessibilityTableCell;
-class AccessibilityTableHeaderContainer;
-
-class AccessibilityARIAGrid : public AccessibilityTable {
-
-private:
- explicit AccessibilityARIAGrid(RenderObject*);
-public:
- static PassRefPtr<AccessibilityARIAGrid> create(RenderObject*);
- virtual ~AccessibilityARIAGrid();
-
- virtual bool isAriaTable() const OVERRIDE { return true; }
-
- virtual void addChildren() OVERRIDE;
-
-private:
- // ARIA treegrids and grids support selected rows.
- virtual bool supportsSelectedRows() OVERRIDE { return true; }
- virtual bool isMultiSelectable() const OVERRIDE { return true; }
- virtual bool isTableExposableThroughAccessibility() const OVERRIDE { return true; }
-
- bool addTableCellChild(AccessibilityObject*, HashSet<AccessibilityObject*>& appendedRows, unsigned& columnCount);
-};
-
-} // namespace WebCore
-
-#endif // AccessibilityARIAGrid_h
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityARIAGridCell.cpp b/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityARIAGridCell.cpp
deleted file mode 100644
index c2c17a23851..00000000000
--- a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityARIAGridCell.cpp
+++ /dev/null
@@ -1,124 +0,0 @@
-/*
- * Copyright (C) 2009 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/accessibility/AccessibilityARIAGridCell.h"
-
-#include "core/accessibility/AccessibilityTable.h"
-#include "core/accessibility/AccessibilityTableRow.h"
-
-using namespace std;
-
-namespace WebCore {
-
-AccessibilityARIAGridCell::AccessibilityARIAGridCell(RenderObject* renderer)
- : AccessibilityTableCell(renderer)
-{
-}
-
-AccessibilityARIAGridCell::~AccessibilityARIAGridCell()
-{
-}
-
-PassRefPtr<AccessibilityARIAGridCell> AccessibilityARIAGridCell::create(RenderObject* renderer)
-{
- return adoptRef(new AccessibilityARIAGridCell(renderer));
-}
-
-AccessibilityObject* AccessibilityARIAGridCell::parentTable() const
-{
- AccessibilityObject* parent = parentObjectUnignored();
- if (!parent)
- return 0;
-
- if (parent->isAccessibilityTable())
- return parent;
-
- // It could happen that we hadn't reached the parent table yet (in
- // case objects for rows were not ignoring accessibility) so for
- // that reason we need to run parentObjectUnignored once again.
- parent = parent->parentObjectUnignored();
- if (!parent || !parent->isAccessibilityTable())
- return 0;
-
- return parent;
-}
-
-void AccessibilityARIAGridCell::rowIndexRange(pair<unsigned, unsigned>& rowRange)
-{
- AccessibilityObject* parent = parentObjectUnignored();
- if (!parent)
- return;
-
- if (parent->isTableRow()) {
- // We already got a table row, use its API.
- rowRange.first = static_cast<AccessibilityTableRow*>(parent)->rowIndex();
- } else if (parent->isAccessibilityTable()) {
- // We reached the parent table, so we need to inspect its
- // children to determine the row index for the cell in it.
- unsigned columnCount = toAccessibilityTable(parent)->columnCount();
- if (!columnCount)
- return;
-
- AccessibilityChildrenVector siblings = parent->children();
- unsigned childrenSize = siblings.size();
- for (unsigned k = 0; k < childrenSize; ++k) {
- if (siblings[k].get() == this) {
- rowRange.first = k / columnCount;
- break;
- }
- }
- }
-
- // as far as I can tell, grid cells cannot span rows
- rowRange.second = 1;
-}
-
-void AccessibilityARIAGridCell::columnIndexRange(pair<unsigned, unsigned>& columnRange)
-{
- AccessibilityObject* parent = parentObjectUnignored();
- if (!parent)
- return;
-
- if (!parent->isTableRow() && !parent->isAccessibilityTable())
- return;
-
- AccessibilityChildrenVector siblings = parent->children();
- unsigned childrenSize = siblings.size();
- for (unsigned k = 0; k < childrenSize; ++k) {
- if (siblings[k].get() == this) {
- columnRange.first = k;
- break;
- }
- }
-
- // as far as I can tell, grid cells cannot span columns
- columnRange.second = 1;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityARIAGridCell.h b/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityARIAGridCell.h
deleted file mode 100644
index dab5f0fb9ae..00000000000
--- a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityARIAGridCell.h
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Copyright (C) 2009 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef AccessibilityARIAGridCell_h
-#define AccessibilityARIAGridCell_h
-
-#include "core/accessibility/AccessibilityTableCell.h"
-
-namespace WebCore {
-
-class AccessibilityARIAGridCell : public AccessibilityTableCell {
-
-private:
- explicit AccessibilityARIAGridCell(RenderObject*);
-public:
- static PassRefPtr<AccessibilityARIAGridCell> create(RenderObject*);
- virtual ~AccessibilityARIAGridCell();
-
- // fills in the start location and row span of cell
- virtual void rowIndexRange(pair<unsigned, unsigned>& rowRange) OVERRIDE;
- // fills in the start location and column span of cell
- virtual void columnIndexRange(pair<unsigned, unsigned>& columnRange) OVERRIDE;
-
-protected:
- virtual AccessibilityObject* parentTable() const;
-};
-
-} // namespace WebCore
-
-#endif // AccessibilityARIAGridCell_h
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityARIAGridRow.cpp b/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityARIAGridRow.cpp
deleted file mode 100644
index a7ddd2682b1..00000000000
--- a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityARIAGridRow.cpp
+++ /dev/null
@@ -1,130 +0,0 @@
-/*
- * Copyright (C) 2009 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/accessibility/AccessibilityARIAGridRow.h"
-
-#include "core/accessibility/AccessibilityTable.h"
-
-using namespace std;
-
-namespace WebCore {
-
-AccessibilityARIAGridRow::AccessibilityARIAGridRow(RenderObject* renderer)
- : AccessibilityTableRow(renderer)
-{
-}
-
-AccessibilityARIAGridRow::~AccessibilityARIAGridRow()
-{
-}
-
-PassRefPtr<AccessibilityARIAGridRow> AccessibilityARIAGridRow::create(RenderObject* renderer)
-{
- return adoptRef(new AccessibilityARIAGridRow(renderer));
-}
-
-bool AccessibilityARIAGridRow::isARIATreeGridRow() const
-{
- AccessibilityObject* parent = parentTable();
- if (!parent)
- return false;
-
- return parent->ariaRoleAttribute() == TreeGridRole;
-}
-
-void AccessibilityARIAGridRow::disclosedRows(AccessibilityChildrenVector& disclosedRows)
-{
- // The contiguous disclosed rows will be the rows in the table that
- // have an aria-level of plus 1 from this row.
- AccessibilityObject* parent = parentObjectUnignored();
- if (!parent || !parent->isAccessibilityTable())
- return;
-
- // Search for rows that match the correct level.
- // Only take the subsequent rows from this one that are +1 from this row's level.
- int index = rowIndex();
- if (index < 0)
- return;
-
- unsigned level = hierarchicalLevel();
- AccessibilityChildrenVector& allRows = toAccessibilityTable(parent)->rows();
- int rowCount = allRows.size();
- for (int k = index + 1; k < rowCount; ++k) {
- AccessibilityObject* row = allRows[k].get();
- // Stop at the first row that doesn't match the correct level.
- if (row->hierarchicalLevel() != level + 1)
- break;
-
- disclosedRows.append(row);
- }
-}
-
-AccessibilityObject* AccessibilityARIAGridRow::disclosedByRow() const
-{
- // The row that discloses this one is the row in the table
- // that is aria-level subtract 1 from this row.
- AccessibilityObject* parent = parentObjectUnignored();
- if (!parent || !parent->isAccessibilityTable())
- return 0;
-
- // If the level is 1 or less, than nothing discloses this row.
- unsigned level = hierarchicalLevel();
- if (level <= 1)
- return 0;
-
- // Search for the previous row that matches the correct level.
- int index = rowIndex();
- AccessibilityChildrenVector& allRows = toAccessibilityTable(parent)->rows();
- int rowCount = allRows.size();
- if (index >= rowCount)
- return 0;
-
- for (int k = index - 1; k >= 0; --k) {
- AccessibilityObject* row = allRows[k].get();
- if (row->hierarchicalLevel() == level - 1)
- return row;
- }
-
- return 0;
-}
-
-AccessibilityObject* AccessibilityARIAGridRow::headerObject()
-{
- AccessibilityChildrenVector rowChildren = children();
- unsigned childrenCount = rowChildren.size();
- for (unsigned i = 0; i < childrenCount; ++i) {
- AccessibilityObject* cell = rowChildren[i].get();
- if (cell->ariaRoleAttribute() == RowHeaderRole)
- return cell;
- }
-
- return 0;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityARIAGridRow.h b/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityARIAGridRow.h
deleted file mode 100644
index ab8fb9c5913..00000000000
--- a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityARIAGridRow.h
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Copyright (C) 2009 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef AccessibilityARIAGridRow_h
-#define AccessibilityARIAGridRow_h
-
-#include "core/accessibility/AccessibilityTableRow.h"
-
-namespace WebCore {
-
-class AccessibilityARIAGridRow : public AccessibilityTableRow {
-
-private:
- explicit AccessibilityARIAGridRow(RenderObject*);
-public:
- static PassRefPtr<AccessibilityARIAGridRow> create(RenderObject*);
- virtual ~AccessibilityARIAGridRow();
-
- void disclosedRows(AccessibilityChildrenVector&);
- AccessibilityObject* disclosedByRow() const;
-
- virtual AccessibilityObject* headerObject() OVERRIDE;
-
-private:
- virtual bool isARIATreeGridRow() const;
-};
-
-} // namespace WebCore
-
-#endif // AccessibilityARIAGridRow_h
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityImageMapLink.cpp b/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityImageMapLink.cpp
deleted file mode 100644
index cc7e052fc9d..00000000000
--- a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityImageMapLink.cpp
+++ /dev/null
@@ -1,158 +0,0 @@
-/*
- * Copyright (C) 2008 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/accessibility/AccessibilityImageMapLink.h"
-
-#include "core/accessibility/AXObjectCache.h"
-#include "core/accessibility/AccessibilityRenderObject.h"
-
-namespace WebCore {
-
-using namespace HTMLNames;
-
-AccessibilityImageMapLink::AccessibilityImageMapLink()
- : m_areaElement(0)
- , m_mapElement(0)
-{
-}
-
-AccessibilityImageMapLink::~AccessibilityImageMapLink()
-{
-}
-
-void AccessibilityImageMapLink::detachFromParent()
-{
- AccessibilityMockObject::detachFromParent();
- m_areaElement = 0;
- m_mapElement = 0;
-}
-
-PassRefPtr<AccessibilityImageMapLink> AccessibilityImageMapLink::create()
-{
- return adoptRef(new AccessibilityImageMapLink());
-}
-
-AccessibilityObject* AccessibilityImageMapLink::parentObject() const
-{
- if (m_parent)
- return m_parent;
-
- if (!m_mapElement.get() || !m_mapElement->renderer())
- return 0;
-
- return m_mapElement->document().axObjectCache()->getOrCreate(m_mapElement->renderer());
-}
-
-AccessibilityRole AccessibilityImageMapLink::roleValue() const
-{
- if (!m_areaElement)
- return LinkRole;
-
- const AtomicString& ariaRole = getAttribute(roleAttr);
- if (!ariaRole.isEmpty())
- return AccessibilityObject::ariaRoleToWebCoreRole(ariaRole);
-
- return LinkRole;
-}
-
-Element* AccessibilityImageMapLink::actionElement() const
-{
- return anchorElement();
-}
-
-Element* AccessibilityImageMapLink::anchorElement() const
-{
- return m_areaElement.get();
-}
-
-KURL AccessibilityImageMapLink::url() const
-{
- if (!m_areaElement.get())
- return KURL();
-
- return m_areaElement->href();
-}
-
-void AccessibilityImageMapLink::accessibilityText(Vector<AccessibilityText>& textOrder)
-{
- String description = accessibilityDescription();
- if (!description.isEmpty())
- textOrder.append(AccessibilityText(description, AlternativeText));
-
- const AtomicString& titleText = getAttribute(titleAttr);
- if (!titleText.isEmpty())
- textOrder.append(AccessibilityText(titleText, TitleTagText));
-
- const AtomicString& summary = getAttribute(summaryAttr);
- if (!summary.isEmpty())
- textOrder.append(AccessibilityText(summary, SummaryText));
-}
-
-String AccessibilityImageMapLink::accessibilityDescription() const
-{
- const AtomicString& ariaLabel = getAttribute(aria_labelAttr);
- if (!ariaLabel.isEmpty())
- return ariaLabel;
- const AtomicString& alt = getAttribute(altAttr);
- if (!alt.isEmpty())
- return alt;
-
- return String();
-}
-
-String AccessibilityImageMapLink::title() const
-{
- const AtomicString& title = getAttribute(titleAttr);
- if (!title.isEmpty())
- return title;
- const AtomicString& summary = getAttribute(summaryAttr);
- if (!summary.isEmpty())
- return summary;
-
- return String();
-}
-
-LayoutRect AccessibilityImageMapLink::elementRect() const
-{
- if (!m_mapElement.get() || !m_areaElement.get())
- return LayoutRect();
-
- RenderObject* renderer;
- if (m_parent && m_parent->isAccessibilityRenderObject())
- renderer = toAccessibilityRenderObject(m_parent)->renderer();
- else
- renderer = m_mapElement->renderer();
-
- if (!renderer)
- return LayoutRect();
-
- return m_areaElement->computeRect(renderer);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityImageMapLink.h b/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityImageMapLink.h
deleted file mode 100644
index 92345dcab1f..00000000000
--- a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityImageMapLink.h
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * Copyright (C) 2008 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef AccessibilityImageMapLink_h
-#define AccessibilityImageMapLink_h
-
-#include "core/accessibility/AccessibilityMockObject.h"
-#include "core/html/HTMLAreaElement.h"
-#include "core/html/HTMLMapElement.h"
-
-namespace WebCore {
-
-class AccessibilityImageMapLink : public AccessibilityMockObject {
-
-private:
- AccessibilityImageMapLink();
-public:
- static PassRefPtr<AccessibilityImageMapLink> create();
- virtual ~AccessibilityImageMapLink();
-
- void setHTMLAreaElement(HTMLAreaElement* element) { m_areaElement = element; }
- HTMLAreaElement* areaElement() const { return m_areaElement.get(); }
-
- void setHTMLMapElement(HTMLMapElement* element) { m_mapElement = element; }
- HTMLMapElement* mapElement() const { return m_mapElement.get(); }
-
- virtual Node* node() const OVERRIDE { return m_areaElement.get(); }
-
- virtual AccessibilityRole roleValue() const OVERRIDE;
- virtual bool isEnabled() const OVERRIDE { return true; }
-
- virtual Element* anchorElement() const OVERRIDE;
- virtual Element* actionElement() const OVERRIDE;
- virtual KURL url() const OVERRIDE;
- virtual bool isLink() const { return true; }
- virtual bool isLinked() const OVERRIDE { return true; }
- virtual String title() const OVERRIDE;
- virtual String accessibilityDescription() const OVERRIDE;
- virtual AccessibilityObject* parentObject() const OVERRIDE;
-
- virtual LayoutRect elementRect() const OVERRIDE;
-
-private:
- RefPtr<HTMLAreaElement> m_areaElement;
- RefPtr<HTMLMapElement> m_mapElement;
-
- virtual void detachFromParent() OVERRIDE;
-
- virtual void accessibilityText(Vector<AccessibilityText>&) OVERRIDE;
- virtual bool isImageMapLink() const OVERRIDE { return true; }
-};
-
-} // namespace WebCore
-
-#endif // AccessibilityImageMapLink_h
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityList.cpp b/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityList.cpp
deleted file mode 100644
index 5fb32b50996..00000000000
--- a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityList.cpp
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
- * Copyright (C) 2008 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/accessibility/AccessibilityList.h"
-
-#include "core/rendering/RenderObject.h"
-
-using namespace std;
-
-namespace WebCore {
-
-using namespace HTMLNames;
-
-AccessibilityList::AccessibilityList(RenderObject* renderer)
- : AccessibilityRenderObject(renderer)
-{
-}
-
-AccessibilityList::~AccessibilityList()
-{
-}
-
-PassRefPtr<AccessibilityList> AccessibilityList::create(RenderObject* renderer)
-{
- return adoptRef(new AccessibilityList(renderer));
-}
-
-bool AccessibilityList::computeAccessibilityIsIgnored() const
-{
- return accessibilityIsIgnoredByDefault();
-}
-
-bool AccessibilityList::isUnorderedList() const
-{
- if (!m_renderer)
- return false;
-
- Node* node = m_renderer->node();
-
- // The ARIA spec says the "list" role is supposed to mimic a UL or OL tag.
- // Since it can't be both, it's probably OK to say that it's an un-ordered list.
- // On the Mac, there's no distinction to the client.
- if (ariaRoleAttribute() == ListRole)
- return true;
-
- return node && node->hasTagName(ulTag);
-}
-
-bool AccessibilityList::isOrderedList() const
-{
- if (!m_renderer)
- return false;
-
- // ARIA says a directory is like a static table of contents, which sounds like an ordered list.
- if (ariaRoleAttribute() == DirectoryRole)
- return true;
-
- Node* node = m_renderer->node();
- return node && node->hasTagName(olTag);
-}
-
-bool AccessibilityList::isDescriptionList() const
-{
- if (!m_renderer)
- return false;
-
- Node* node = m_renderer->node();
- return node && node->hasTagName(dlTag);
-}
-
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityList.h b/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityList.h
deleted file mode 100644
index 71d66c958c6..00000000000
--- a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityList.h
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright (C) 2008 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef AccessibilityList_h
-#define AccessibilityList_h
-
-#include "core/accessibility/AccessibilityRenderObject.h"
-
-namespace WebCore {
-
-class AccessibilityList : public AccessibilityRenderObject {
-
-private:
- explicit AccessibilityList(RenderObject*);
-public:
- static PassRefPtr<AccessibilityList> create(RenderObject*);
- virtual ~AccessibilityList();
-
- virtual bool isList() const { return true; }
- bool isUnorderedList() const;
- bool isOrderedList() const;
- bool isDescriptionList() const;
-
- virtual AccessibilityRole roleValue() const { return ListRole; }
-private:
- virtual bool computeAccessibilityIsIgnored() const;
-};
-
-} // namespace WebCore
-
-#endif // AccessibilityList_h
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityListBox.cpp b/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityListBox.cpp
deleted file mode 100644
index 3b5e578fa05..00000000000
--- a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityListBox.cpp
+++ /dev/null
@@ -1,169 +0,0 @@
-/*
- * Copyright (C) 2008 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/accessibility/AccessibilityListBox.h"
-
-#include "core/accessibility/AXObjectCache.h"
-#include "core/accessibility/AccessibilityListBoxOption.h"
-#include "core/html/HTMLSelectElement.h"
-#include "core/rendering/RenderListBox.h"
-
-using namespace std;
-
-namespace WebCore {
-
-using namespace HTMLNames;
-
-AccessibilityListBox::AccessibilityListBox(RenderObject* renderer)
- : AccessibilityRenderObject(renderer)
-{
-}
-
-AccessibilityListBox::~AccessibilityListBox()
-{
-}
-
-PassRefPtr<AccessibilityListBox> AccessibilityListBox::create(RenderObject* renderer)
-{
- return adoptRef(new AccessibilityListBox(renderer));
-}
-
-bool AccessibilityListBox::canSetSelectedChildrenAttribute() const
-{
- Node* selectNode = m_renderer->node();
- if (!selectNode)
- return false;
-
- return !toHTMLSelectElement(selectNode)->isDisabledFormControl();
-}
-
-void AccessibilityListBox::addChildren()
-{
- Node* selectNode = m_renderer->node();
- if (!selectNode)
- return;
-
- m_haveChildren = true;
-
- const Vector<HTMLElement*>& listItems = toHTMLSelectElement(selectNode)->listItems();
- unsigned length = listItems.size();
- for (unsigned i = 0; i < length; i++) {
- // The cast to HTMLElement below is safe because the only other possible listItem type
- // would be a WMLElement, but WML builds don't use accessibility features at all.
- AccessibilityObject* listOption = listBoxOptionAccessibilityObject(listItems[i]);
- if (listOption && !listOption->accessibilityIsIgnored())
- m_children.append(listOption);
- }
-}
-
-void AccessibilityListBox::setSelectedChildren(AccessibilityChildrenVector& children)
-{
- if (!canSetSelectedChildrenAttribute())
- return;
-
- Node* selectNode = m_renderer->node();
- if (!selectNode)
- return;
-
- // disable any selected options
- unsigned length = m_children.size();
- for (unsigned i = 0; i < length; i++) {
- AccessibilityListBoxOption* listBoxOption = static_cast<AccessibilityListBoxOption*>(m_children[i].get());
- if (listBoxOption->isSelected())
- listBoxOption->setSelected(false);
- }
-
- length = children.size();
- for (unsigned i = 0; i < length; i++) {
- AccessibilityObject* obj = children[i].get();
- if (obj->roleValue() != ListBoxOptionRole)
- continue;
-
- static_cast<AccessibilityListBoxOption*>(obj)->setSelected(true);
- }
-}
-
-void AccessibilityListBox::selectedChildren(AccessibilityChildrenVector& result)
-{
- ASSERT(result.isEmpty());
-
- if (!hasChildren())
- addChildren();
-
- unsigned length = m_children.size();
- for (unsigned i = 0; i < length; i++) {
- if (static_cast<AccessibilityListBoxOption*>(m_children[i].get())->isSelected())
- result.append(m_children[i]);
- }
-}
-
-AccessibilityObject* AccessibilityListBox::listBoxOptionAccessibilityObject(HTMLElement* element) const
-{
- // skip hr elements
- if (!element || element->hasTagName(hrTag))
- return 0;
-
- AccessibilityObject* listBoxObject = m_renderer->document().axObjectCache()->getOrCreate(ListBoxOptionRole);
- static_cast<AccessibilityListBoxOption*>(listBoxObject)->setHTMLElement(element);
-
- return listBoxObject;
-}
-
-AccessibilityObject* AccessibilityListBox::elementAccessibilityHitTest(const IntPoint& point) const
-{
- // the internal HTMLSelectElement methods for returning a listbox option at a point
- // ignore optgroup elements.
- if (!m_renderer)
- return 0;
-
- Node* node = m_renderer->node();
- if (!node)
- return 0;
-
- LayoutRect parentRect = elementRect();
-
- AccessibilityObject* listBoxOption = 0;
- unsigned length = m_children.size();
- for (unsigned i = 0; i < length; i++) {
- LayoutRect rect = toRenderListBox(m_renderer)->itemBoundingBoxRect(parentRect.location(), i);
- // The cast to HTMLElement below is safe because the only other possible listItem type
- // would be a WMLElement, but WML builds don't use accessibility features at all.
- if (rect.contains(point)) {
- listBoxOption = m_children[i].get();
- break;
- }
- }
-
- if (listBoxOption && !listBoxOption->accessibilityIsIgnored())
- return listBoxOption;
-
- return axObjectCache()->getOrCreate(m_renderer);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityListBox.h b/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityListBox.h
deleted file mode 100644
index 6eb2b7d2ed5..00000000000
--- a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityListBox.h
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Copyright (C) 2008 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef AccessibilityListBox_h
-#define AccessibilityListBox_h
-
-#include "core/accessibility/AccessibilityRenderObject.h"
-
-namespace WebCore {
-
-class AccessibilityListBox : public AccessibilityRenderObject {
-
-private:
- explicit AccessibilityListBox(RenderObject*);
-public:
- static PassRefPtr<AccessibilityListBox> create(RenderObject*);
- virtual ~AccessibilityListBox();
-
- virtual bool canSetSelectedChildrenAttribute() const OVERRIDE;
- void setSelectedChildren(AccessibilityChildrenVector&);
- virtual AccessibilityRole roleValue() const OVERRIDE { return ListBoxRole; }
-
- virtual void selectedChildren(AccessibilityChildrenVector&) OVERRIDE;
-
- virtual void addChildren() OVERRIDE;
-
-private:
- AccessibilityObject* listBoxOptionAccessibilityObject(HTMLElement*) const;
- virtual AccessibilityObject* elementAccessibilityHitTest(const IntPoint&) const OVERRIDE;
-};
-
-} // namespace WebCore
-
-#endif // AccessibilityListBox_h
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityListBoxOption.cpp b/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityListBoxOption.cpp
deleted file mode 100644
index fffc7916f98..00000000000
--- a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityListBoxOption.cpp
+++ /dev/null
@@ -1,228 +0,0 @@
-/*
- * Copyright (C) 2008 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/accessibility/AccessibilityListBoxOption.h"
-
-#include "core/accessibility/AXObjectCache.h"
-#include "core/html/HTMLOptGroupElement.h"
-#include "core/html/HTMLOptionElement.h"
-#include "core/html/HTMLSelectElement.h"
-#include "core/rendering/RenderListBox.h"
-
-using namespace std;
-
-namespace WebCore {
-
-using namespace HTMLNames;
-
-AccessibilityListBoxOption::AccessibilityListBoxOption()
- : m_optionElement(0)
-{
-}
-
-AccessibilityListBoxOption::~AccessibilityListBoxOption()
-{
-}
-
-PassRefPtr<AccessibilityListBoxOption> AccessibilityListBoxOption::create()
-{
- return adoptRef(new AccessibilityListBoxOption());
-}
-
-bool AccessibilityListBoxOption::isEnabled() const
-{
- if (!m_optionElement)
- return false;
-
- if (isHTMLOptGroupElement(m_optionElement))
- return false;
-
- if (equalIgnoringCase(getAttribute(aria_disabledAttr), "true"))
- return false;
-
- if (m_optionElement->hasAttribute(disabledAttr))
- return false;
-
- return true;
-}
-
-bool AccessibilityListBoxOption::isSelected() const
-{
- if (!m_optionElement)
- return false;
-
- if (!m_optionElement->hasTagName(optionTag))
- return false;
-
- return toHTMLOptionElement(m_optionElement)->selected();
-}
-
-bool AccessibilityListBoxOption::isSelectedOptionActive() const
-{
- HTMLSelectElement* listBoxParentNode = listBoxOptionParentNode();
- if (!listBoxParentNode)
- return false;
-
- return listBoxParentNode->activeSelectionEndListIndex() == listBoxOptionIndex();
-}
-
-LayoutRect AccessibilityListBoxOption::elementRect() const
-{
- LayoutRect rect;
- if (!m_optionElement)
- return rect;
-
- HTMLSelectElement* listBoxParentNode = listBoxOptionParentNode();
- if (!listBoxParentNode)
- return rect;
-
- RenderObject* listBoxRenderer = listBoxParentNode->renderer();
- if (!listBoxRenderer)
- return rect;
-
- LayoutRect parentRect = listBoxRenderer->document().axObjectCache()->getOrCreate(listBoxRenderer)->elementRect();
- int index = listBoxOptionIndex();
- if (index != -1)
- rect = toRenderListBox(listBoxRenderer)->itemBoundingBoxRect(parentRect.location(), index);
-
- return rect;
-}
-
-bool AccessibilityListBoxOption::computeAccessibilityIsIgnored() const
-{
- if (!m_optionElement)
- return true;
-
- if (accessibilityIsIgnoredByDefault())
- return true;
-
- return parentObject()->accessibilityIsIgnored();
-}
-
-bool AccessibilityListBoxOption::canSetSelectedAttribute() const
-{
- if (!m_optionElement)
- return false;
-
- if (!m_optionElement->hasTagName(optionTag))
- return false;
-
- if (m_optionElement->isDisabledFormControl())
- return false;
-
- HTMLSelectElement* selectElement = listBoxOptionParentNode();
- if (selectElement && selectElement->isDisabledFormControl())
- return false;
-
- return true;
-}
-
-String AccessibilityListBoxOption::stringValue() const
-{
- if (!m_optionElement)
- return String();
-
- const AtomicString& ariaLabel = getAttribute(aria_labelAttr);
- if (!ariaLabel.isNull())
- return ariaLabel;
-
- if (m_optionElement->hasTagName(optionTag))
- return toHTMLOptionElement(m_optionElement)->text();
-
- if (isHTMLOptGroupElement(m_optionElement))
- return toHTMLOptGroupElement(m_optionElement)->groupLabelText();
-
- return String();
-}
-
-Element* AccessibilityListBoxOption::actionElement() const
-{
- return m_optionElement;
-}
-
-AccessibilityObject* AccessibilityListBoxOption::parentObject() const
-{
- HTMLSelectElement* parentNode = listBoxOptionParentNode();
- if (!parentNode)
- return 0;
-
- return m_optionElement->document().axObjectCache()->getOrCreate(parentNode);
-}
-
-void AccessibilityListBoxOption::setSelected(bool selected)
-{
- HTMLSelectElement* selectElement = listBoxOptionParentNode();
- if (!selectElement)
- return;
-
- if (!canSetSelectedAttribute())
- return;
-
- bool isOptionSelected = isSelected();
- if ((isOptionSelected && selected) || (!isOptionSelected && !selected))
- return;
-
- // Convert from the entire list index to the option index.
- int optionIndex = selectElement->listToOptionIndex(listBoxOptionIndex());
- selectElement->accessKeySetSelectedIndex(optionIndex);
-}
-
-HTMLSelectElement* AccessibilityListBoxOption::listBoxOptionParentNode() const
-{
- if (!m_optionElement)
- return 0;
-
- if (m_optionElement->hasTagName(optionTag))
- return toHTMLOptionElement(m_optionElement)->ownerSelectElement();
-
- if (isHTMLOptGroupElement(m_optionElement))
- return toHTMLOptGroupElement(m_optionElement)->ownerSelectElement();
-
- return 0;
-}
-
-int AccessibilityListBoxOption::listBoxOptionIndex() const
-{
- if (!m_optionElement)
- return -1;
-
- HTMLSelectElement* selectElement = listBoxOptionParentNode();
- if (!selectElement)
- return -1;
-
- const Vector<HTMLElement*>& listItems = selectElement->listItems();
- unsigned length = listItems.size();
- for (unsigned i = 0; i < length; i++)
- if (listItems[i] == m_optionElement)
- return i;
-
- return -1;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityListBoxOption.h b/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityListBoxOption.h
deleted file mode 100644
index 987b5bc7754..00000000000
--- a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityListBoxOption.h
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * Copyright (C) 2008 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef AccessibilityListBoxOption_h
-#define AccessibilityListBoxOption_h
-
-#include "core/accessibility/AccessibilityObject.h"
-#include "core/html/HTMLElement.h"
-#include "wtf/Forward.h"
-
-namespace WebCore {
-
-class AccessibilityListBox;
-class Element;
-class HTMLElement;
-class HTMLSelectElement;
-
-class AccessibilityListBoxOption : public AccessibilityObject {
-
-private:
- AccessibilityListBoxOption();
-public:
- static PassRefPtr<AccessibilityListBoxOption> create();
- virtual ~AccessibilityListBoxOption();
-
- void setHTMLElement(HTMLElement* element) { m_optionElement = element; }
-
- virtual AccessibilityRole roleValue() const OVERRIDE { return ListBoxOptionRole; }
- virtual bool isSelected() const OVERRIDE;
- virtual bool isEnabled() const OVERRIDE;
- virtual bool isSelectedOptionActive() const OVERRIDE;
- virtual String stringValue() const OVERRIDE;
- virtual Element* actionElement() const OVERRIDE;
- virtual Node* node() const OVERRIDE { return m_optionElement; }
- virtual void setSelected(bool) OVERRIDE;
- virtual bool canSetSelectedAttribute() const OVERRIDE;
-
- virtual LayoutRect elementRect() const OVERRIDE;
- virtual AccessibilityObject* parentObject() const OVERRIDE;
-
-private:
- HTMLElement* m_optionElement;
-
- virtual bool canHaveChildren() const OVERRIDE { return false; }
- virtual bool computeAccessibilityIsIgnored() const OVERRIDE;
-
- HTMLSelectElement* listBoxOptionParentNode() const;
- int listBoxOptionIndex() const;
- AccessibilityObject* listBoxOptionAccessibilityObject(HTMLElement*) const;
-};
-
-} // namespace WebCore
-
-#endif // AccessibilityListBoxOption_h
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityMediaControls.cpp b/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityMediaControls.cpp
deleted file mode 100644
index cf694b95db6..00000000000
--- a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityMediaControls.cpp
+++ /dev/null
@@ -1,304 +0,0 @@
-/*
- * Copyright (C) 2009 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-
-#include "config.h"
-
-#include "core/accessibility/AccessibilityMediaControls.h"
-
-#include "core/platform/LocalizedStrings.h"
-
-namespace WebCore {
-
-using namespace HTMLNames;
-
-
-AccessibilityMediaControl::AccessibilityMediaControl(RenderObject* renderer)
- : AccessibilityRenderObject(renderer)
-{
-}
-
-PassRefPtr<AccessibilityObject> AccessibilityMediaControl::create(RenderObject* renderer)
-{
- ASSERT(renderer->node());
-
- switch (mediaControlElementType(renderer->node())) {
- case MediaSlider:
- return AccessibilityMediaTimeline::create(renderer);
-
- case MediaCurrentTimeDisplay:
- case MediaTimeRemainingDisplay:
- return AccessibilityMediaTimeDisplay::create(renderer);
-
- case MediaControlsPanel:
- return AccessibilityMediaControlsContainer::create(renderer);
-
- default:
- return adoptRef(new AccessibilityMediaControl(renderer));
- }
-}
-
-MediaControlElementType AccessibilityMediaControl::controlType() const
-{
- if (!renderer() || !renderer()->node())
- return MediaTimelineContainer; // Timeline container is not accessible.
-
- return mediaControlElementType(renderer()->node());
-}
-
-String AccessibilityMediaControl::controlTypeName() const
-{
- switch (controlType()) {
- case MediaEnterFullscreenButton:
- return "EnterFullscreenButton";
- case MediaExitFullscreenButton:
- return "ExitFullscreenButton";
- case MediaMuteButton:
- return "MuteButton";
- case MediaPlayButton:
- return "PlayButton";
- case MediaSeekBackButton:
- return "SeekBackButton";
- case MediaSeekForwardButton:
- return "SeekForwardButton";
- case MediaRewindButton:
- return "RewindButton";
- case MediaReturnToRealtimeButton:
- return "ReturnToRealtimeButton";
- case MediaUnMuteButton:
- return "UnMuteButton";
- case MediaPauseButton:
- return "PauseButton";
- case MediaStatusDisplay:
- return "StatusDisplay";
- case MediaCurrentTimeDisplay:
- return "CurrentTimeDisplay";
- case MediaTimeRemainingDisplay:
- return "TimeRemainingDisplay";
- case MediaShowClosedCaptionsButton:
- return "ShowClosedCaptionsButton";
- case MediaHideClosedCaptionsButton:
- return "HideClosedCaptionsButton";
-
- default:
- break;
- }
-
- return String();
-}
-
-void AccessibilityMediaControl::accessibilityText(Vector<AccessibilityText>& textOrder)
-{
- String description = accessibilityDescription();
- if (!description.isEmpty())
- textOrder.append(AccessibilityText(description, AlternativeText));
-
- String title = this->title();
- if (!title.isEmpty())
- textOrder.append(AccessibilityText(title, AlternativeText));
-
- String helptext = helpText();
- if (!helptext.isEmpty())
- textOrder.append(AccessibilityText(helptext, HelpText));
-}
-
-
-String AccessibilityMediaControl::title() const
-{
- if (controlType() == MediaControlsPanel)
- return localizedMediaControlElementString("ControlsPanel");
-
- return AccessibilityRenderObject::title();
-}
-
-String AccessibilityMediaControl::accessibilityDescription() const
-{
- return localizedMediaControlElementString(controlTypeName());
-}
-
-String AccessibilityMediaControl::helpText() const
-{
- return localizedMediaControlElementHelpText(controlTypeName());
-}
-
-bool AccessibilityMediaControl::computeAccessibilityIsIgnored() const
-{
- if (!m_renderer || !m_renderer->style() || m_renderer->style()->visibility() != VISIBLE || controlType() == MediaTimelineContainer)
- return true;
-
- return accessibilityIsIgnoredByDefault();
-}
-
-AccessibilityRole AccessibilityMediaControl::roleValue() const
-{
- switch (controlType()) {
- case MediaEnterFullscreenButton:
- case MediaExitFullscreenButton:
- case MediaMuteButton:
- case MediaPlayButton:
- case MediaSeekBackButton:
- case MediaSeekForwardButton:
- case MediaRewindButton:
- case MediaReturnToRealtimeButton:
- case MediaUnMuteButton:
- case MediaPauseButton:
- case MediaShowClosedCaptionsButton:
- case MediaHideClosedCaptionsButton:
- return ButtonRole;
-
- case MediaStatusDisplay:
- return StaticTextRole;
-
- case MediaTimelineContainer:
- return GroupRole;
-
- default:
- break;
- }
-
- return UnknownRole;
-}
-
-
-
-//
-// AccessibilityMediaControlsContainer
-
-AccessibilityMediaControlsContainer::AccessibilityMediaControlsContainer(RenderObject* renderer)
- : AccessibilityMediaControl(renderer)
-{
-}
-
-PassRefPtr<AccessibilityObject> AccessibilityMediaControlsContainer::create(RenderObject* renderer)
-{
- return adoptRef(new AccessibilityMediaControlsContainer(renderer));
-}
-
-String AccessibilityMediaControlsContainer::accessibilityDescription() const
-{
- return localizedMediaControlElementString(elementTypeName());
-}
-
-String AccessibilityMediaControlsContainer::helpText() const
-{
- return localizedMediaControlElementHelpText(elementTypeName());
-}
-
-bool AccessibilityMediaControlsContainer::controllingVideoElement() const
-{
- if (!m_renderer->node())
- return true;
-
- MediaControlTimeDisplayElement* element = static_cast<MediaControlTimeDisplayElement*>(m_renderer->node());
-
- return toParentMediaElement(element)->isVideo();
-}
-
-const String AccessibilityMediaControlsContainer::elementTypeName() const
-{
- if (controllingVideoElement())
- return "VideoElement";
- return "AudioElement";
-}
-
-bool AccessibilityMediaControlsContainer::computeAccessibilityIsIgnored() const
-{
- return accessibilityIsIgnoredByDefault();
-}
-
-//
-// AccessibilityMediaTimeline
-
-AccessibilityMediaTimeline::AccessibilityMediaTimeline(RenderObject* renderer)
- : AccessibilitySlider(renderer)
-{
-}
-
-PassRefPtr<AccessibilityObject> AccessibilityMediaTimeline::create(RenderObject* renderer)
-{
- return adoptRef(new AccessibilityMediaTimeline(renderer));
-}
-
-String AccessibilityMediaTimeline::valueDescription() const
-{
- Node* node = m_renderer->node();
- if (!node->hasTagName(inputTag))
- return String();
-
- return localizedMediaTimeDescription(toHTMLInputElement(node)->value().toFloat());
-}
-
-String AccessibilityMediaTimeline::helpText() const
-{
- return localizedMediaControlElementHelpText("Slider");
-}
-
-
-//
-// AccessibilityMediaTimeDisplay
-
-AccessibilityMediaTimeDisplay::AccessibilityMediaTimeDisplay(RenderObject* renderer)
- : AccessibilityMediaControl(renderer)
-{
-}
-
-PassRefPtr<AccessibilityObject> AccessibilityMediaTimeDisplay::create(RenderObject* renderer)
-{
- return adoptRef(new AccessibilityMediaTimeDisplay(renderer));
-}
-
-bool AccessibilityMediaTimeDisplay::computeAccessibilityIsIgnored() const
-{
- if (!m_renderer || !m_renderer->style() || m_renderer->style()->visibility() != VISIBLE)
- return true;
-
- if (!m_renderer->style()->width().value())
- return true;
-
- return accessibilityIsIgnoredByDefault();
-}
-
-String AccessibilityMediaTimeDisplay::accessibilityDescription() const
-{
- if (controlType() == MediaCurrentTimeDisplay)
- return localizedMediaControlElementString("CurrentTimeDisplay");
-
- return localizedMediaControlElementString("TimeRemainingDisplay");
-}
-
-String AccessibilityMediaTimeDisplay::stringValue() const
-{
- if (!m_renderer || !m_renderer->node())
- return String();
-
- MediaControlTimeDisplayElement* element = static_cast<MediaControlTimeDisplayElement*>(m_renderer->node());
- float time = element->currentValue();
- return localizedMediaTimeDescription(fabsf(time));
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityMediaControls.h b/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityMediaControls.h
deleted file mode 100644
index 4f61bb7a87d..00000000000
--- a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityMediaControls.h
+++ /dev/null
@@ -1,112 +0,0 @@
-/*
- * Copyright (C) 2009 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-
-#ifndef AccessibilityMediaControls_h
-#define AccessibilityMediaControls_h
-
-#include "core/accessibility/AccessibilitySlider.h"
-#include "core/html/shadow/MediaControlElements.h"
-
-namespace WebCore {
-
-class AccessibilityMediaControl : public AccessibilityRenderObject {
-
-public:
- static PassRefPtr<AccessibilityObject> create(RenderObject*);
- virtual ~AccessibilityMediaControl() { }
-
- virtual AccessibilityRole roleValue() const OVERRIDE;
-
- virtual String title() const OVERRIDE;
- virtual String accessibilityDescription() const OVERRIDE;
- virtual String helpText() const OVERRIDE;
-
-protected:
- explicit AccessibilityMediaControl(RenderObject*);
- MediaControlElementType controlType() const;
- String controlTypeName() const;
- virtual void accessibilityText(Vector<AccessibilityText>&) OVERRIDE;
- virtual bool computeAccessibilityIsIgnored() const OVERRIDE;
-};
-
-
-class AccessibilityMediaTimeline : public AccessibilitySlider {
-
-public:
- static PassRefPtr<AccessibilityObject> create(RenderObject*);
- virtual ~AccessibilityMediaTimeline() { }
-
- virtual String helpText() const OVERRIDE;
- virtual String valueDescription() const OVERRIDE;
- const AtomicString& getAttribute(const QualifiedName& attribute) const;
-
-private:
- explicit AccessibilityMediaTimeline(RenderObject*);
-};
-
-
-class AccessibilityMediaControlsContainer : public AccessibilityMediaControl {
-
-public:
- static PassRefPtr<AccessibilityObject> create(RenderObject*);
- virtual ~AccessibilityMediaControlsContainer() { }
-
- virtual AccessibilityRole roleValue() const OVERRIDE { return ToolbarRole; }
-
- virtual String helpText() const OVERRIDE;
- virtual String accessibilityDescription() const OVERRIDE;
-
-private:
- explicit AccessibilityMediaControlsContainer(RenderObject*);
- bool controllingVideoElement() const;
- const String elementTypeName() const;
- virtual bool computeAccessibilityIsIgnored() const OVERRIDE;
-};
-
-
-class AccessibilityMediaTimeDisplay : public AccessibilityMediaControl {
-
-public:
- static PassRefPtr<AccessibilityObject> create(RenderObject*);
- virtual ~AccessibilityMediaTimeDisplay() { }
-
- virtual AccessibilityRole roleValue() const OVERRIDE { return StaticTextRole; }
-
- virtual String stringValue() const OVERRIDE;
- virtual String accessibilityDescription() const OVERRIDE;
-
-private:
- explicit AccessibilityMediaTimeDisplay(RenderObject*);
- virtual bool computeAccessibilityIsIgnored() const OVERRIDE;
-};
-
-
-} // namespace WebCore
-
-#endif // AccessibilityMediaControls_h
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityMenuList.cpp b/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityMenuList.cpp
deleted file mode 100644
index 0cdb6c82623..00000000000
--- a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityMenuList.cpp
+++ /dev/null
@@ -1,117 +0,0 @@
-/*
- * Copyright (C) 2010 Apple Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/accessibility/AccessibilityMenuList.h"
-
-#include "core/accessibility/AXObjectCache.h"
-#include "core/accessibility/AccessibilityMenuListPopup.h"
-#include "core/rendering/RenderMenuList.h"
-
-namespace WebCore {
-
-AccessibilityMenuList::AccessibilityMenuList(RenderMenuList* renderer)
- : AccessibilityRenderObject(renderer)
-{
-}
-
-PassRefPtr<AccessibilityMenuList> AccessibilityMenuList::create(RenderMenuList* renderer)
-{
- return adoptRef(new AccessibilityMenuList(renderer));
-}
-
-bool AccessibilityMenuList::press() const
-{
- RenderMenuList* menuList = toRenderMenuList(m_renderer);
- if (menuList->popupIsVisible())
- menuList->hidePopup();
- else
- menuList->showPopup();
- return true;
-}
-
-void AccessibilityMenuList::addChildren()
-{
- m_haveChildren = true;
-
- AXObjectCache* cache = m_renderer->document().axObjectCache();
-
- AccessibilityObject* list = cache->getOrCreate(MenuListPopupRole);
- if (!list)
- return;
-
- toAccessibilityMockObject(list)->setParent(this);
- if (list->accessibilityIsIgnored()) {
- cache->remove(list->axObjectID());
- return;
- }
-
- m_children.append(list);
-
- list->addChildren();
-}
-
-void AccessibilityMenuList::childrenChanged()
-{
- if (m_children.isEmpty())
- return;
-
- ASSERT(m_children.size() == 1);
- m_children[0]->childrenChanged();
-}
-
-bool AccessibilityMenuList::isCollapsed() const
-{
- return !toRenderMenuList(m_renderer)->popupIsVisible();
-}
-
-bool AccessibilityMenuList::canSetFocusAttribute() const
-{
- if (!node())
- return false;
-
- return !toElement(node())->isDisabledFormControl();
-}
-
-void AccessibilityMenuList::didUpdateActiveOption(int optionIndex)
-{
- RefPtr<Document> document = &m_renderer->document();
- AXObjectCache* cache = document->axObjectCache();
-
- const AccessibilityChildrenVector& childObjects = children();
- if (!childObjects.isEmpty()) {
- ASSERT(childObjects.size() == 1);
- ASSERT(childObjects[0]->isMenuListPopup());
-
- if (childObjects[0]->isMenuListPopup()) {
- if (AccessibilityMenuListPopup* popup = static_cast<AccessibilityMenuListPopup*>(childObjects[0].get()))
- popup->didUpdateActiveOption(optionIndex);
- }
- }
-
- cache->postNotification(this, document.get(), AXObjectCache::AXMenuListValueChanged, true, PostSynchronously);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityMenuList.h b/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityMenuList.h
deleted file mode 100644
index eba07f842cf..00000000000
--- a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityMenuList.h
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright (C) 2010 Apple Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef AccessibilityMenuList_h
-#define AccessibilityMenuList_h
-
-#include "core/accessibility/AccessibilityRenderObject.h"
-
-namespace WebCore {
-
-class AccessibilityMenuList;
-class AccessibilityMenuListPopup;
-class HTMLOptionElement;
-class RenderMenuList;
-
-class AccessibilityMenuList : public AccessibilityRenderObject {
-public:
- static PassRefPtr<AccessibilityMenuList> create(RenderMenuList* renderer);
-
- virtual bool isCollapsed() const OVERRIDE;
- virtual bool press() const OVERRIDE;
-
- void didUpdateActiveOption(int optionIndex);
-
-private:
- explicit AccessibilityMenuList(RenderMenuList*);
-
- virtual bool isMenuList() const OVERRIDE { return true; }
- virtual AccessibilityRole roleValue() const OVERRIDE { return PopUpButtonRole; }
- virtual bool canSetFocusAttribute() const OVERRIDE;
-
- virtual void addChildren() OVERRIDE;
- virtual void childrenChanged() OVERRIDE;
-};
-
-inline AccessibilityMenuList* toAccessibilityMenuList(AccessibilityObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isMenuList());
- return static_cast<AccessibilityMenuList*>(object);
-}
-
-} // namespace WebCore
-
-#endif // AccessibilityMenuList_h
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityMenuListOption.cpp b/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityMenuListOption.cpp
deleted file mode 100644
index 45e9ca865c5..00000000000
--- a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityMenuListOption.cpp
+++ /dev/null
@@ -1,112 +0,0 @@
-/*
- * Copyright (C) 2010 Apple Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/accessibility/AccessibilityMenuListOption.h"
-
-#include "core/html/HTMLOptionElement.h"
-
-namespace WebCore {
-
-using namespace HTMLNames;
-
-AccessibilityMenuListOption::AccessibilityMenuListOption()
-{
-}
-
-void AccessibilityMenuListOption::setElement(HTMLElement* element)
-{
- ASSERT_ARG(element, element->hasTagName(optionTag));
- m_element = element;
-}
-
-Element* AccessibilityMenuListOption::actionElement() const
-{
- return m_element.get();
-}
-
-bool AccessibilityMenuListOption::isEnabled() const
-{
- // isDisabledFormControl() returns true if the parent <select> element is disabled,
- // which we don't want.
- return !toHTMLOptionElement(m_element.get())->ownElementDisabled();
-}
-
-bool AccessibilityMenuListOption::isVisible() const
-{
- if (!m_parent)
- return false;
-
- // In a single-option select with the popup collapsed, only the selected
- // item is considered visible.
- return !m_parent->isOffScreen() || isSelected();
-}
-
-bool AccessibilityMenuListOption::isOffScreen() const
-{
- // Invisible list options are considered to be offscreen.
- return !isVisible();
-}
-
-bool AccessibilityMenuListOption::isSelected() const
-{
- return toHTMLOptionElement(m_element.get())->selected();
-}
-
-void AccessibilityMenuListOption::setSelected(bool b)
-{
- if (!canSetSelectedAttribute())
- return;
-
- toHTMLOptionElement(m_element.get())->setSelected(b);
-}
-
-bool AccessibilityMenuListOption::canSetSelectedAttribute() const
-{
- return isEnabled();
-}
-
-bool AccessibilityMenuListOption::computeAccessibilityIsIgnored() const
-{
- return accessibilityIsIgnoredByDefault();
-}
-
-LayoutRect AccessibilityMenuListOption::elementRect() const
-{
- AccessibilityObject* parent = parentObject();
- ASSERT(parent->isMenuListPopup());
-
- AccessibilityObject* grandparent = parent->parentObject();
- ASSERT(grandparent->isMenuList());
-
- return grandparent->elementRect();
-}
-
-String AccessibilityMenuListOption::stringValue() const
-{
- return toHTMLOptionElement(m_element.get())->text();
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityMenuListOption.h b/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityMenuListOption.h
deleted file mode 100644
index 91ca5ef6483..00000000000
--- a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityMenuListOption.h
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright (C) 2010 Apple Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef AccessibilityMenuListOption_h
-#define AccessibilityMenuListOption_h
-
-#include "core/accessibility/AccessibilityMockObject.h"
-
-namespace WebCore {
-
-class AccessibilityMenuListPopup;
-class HTMLElement;
-
-class AccessibilityMenuListOption : public AccessibilityMockObject {
-public:
- static PassRefPtr<AccessibilityMenuListOption> create() { return adoptRef(new AccessibilityMenuListOption); }
-
- void setElement(HTMLElement*);
-
-private:
- AccessibilityMenuListOption();
-
- virtual bool isMenuListOption() const OVERRIDE { return true; }
-
- virtual AccessibilityRole roleValue() const OVERRIDE { return MenuListOptionRole; }
- virtual bool canHaveChildren() const OVERRIDE { return false; }
-
- virtual Element* actionElement() const OVERRIDE;
- virtual bool isEnabled() const OVERRIDE;
- virtual bool isVisible() const OVERRIDE;
- virtual bool isOffScreen() const OVERRIDE;
- virtual bool isSelected() const OVERRIDE;
- virtual void setSelected(bool) OVERRIDE;
- virtual bool canSetSelectedAttribute() const OVERRIDE;
- virtual LayoutRect elementRect() const OVERRIDE;
- virtual String stringValue() const OVERRIDE;
- virtual bool computeAccessibilityIsIgnored() const OVERRIDE;
-
- RefPtr<HTMLElement> m_element;
-};
-
-} // namespace WebCore
-
-#endif // AccessibilityMenuListOption_h
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityMenuListPopup.cpp b/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityMenuListPopup.cpp
deleted file mode 100644
index 53fe8fdbcc1..00000000000
--- a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityMenuListPopup.cpp
+++ /dev/null
@@ -1,140 +0,0 @@
-/*
- * Copyright (C) 2010 Apple Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/accessibility/AccessibilityMenuListPopup.h"
-
-#include "core/accessibility/AXObjectCache.h"
-#include "core/accessibility/AccessibilityMenuListOption.h"
-#include "core/html/HTMLSelectElement.h"
-
-namespace WebCore {
-
-using namespace HTMLNames;
-
-AccessibilityMenuListPopup::AccessibilityMenuListPopup()
-{
-}
-
-bool AccessibilityMenuListPopup::isVisible() const
-{
- return false;
-}
-
-bool AccessibilityMenuListPopup::isOffScreen() const
-{
- if (!m_parent)
- return true;
-
- return m_parent->isCollapsed();
-}
-
-bool AccessibilityMenuListPopup::isEnabled() const
-{
- if (!m_parent)
- return false;
-
- return m_parent->isEnabled();
-}
-
-bool AccessibilityMenuListPopup::computeAccessibilityIsIgnored() const
-{
- return accessibilityIsIgnoredByDefault();
-}
-
-AccessibilityMenuListOption* AccessibilityMenuListPopup::menuListOptionAccessibilityObject(HTMLElement* element) const
-{
- if (!element || !element->hasTagName(optionTag) || !element->attached())
- return 0;
-
- AccessibilityObject* object = document()->axObjectCache()->getOrCreate(MenuListOptionRole);
- ASSERT_WITH_SECURITY_IMPLICATION(object->isMenuListOption());
-
- AccessibilityMenuListOption* option = static_cast<AccessibilityMenuListOption*>(object);
- option->setElement(element);
-
- return option;
-}
-
-bool AccessibilityMenuListPopup::press() const
-{
- if (!m_parent)
- return false;
-
- m_parent->press();
- return true;
-}
-
-void AccessibilityMenuListPopup::addChildren()
-{
- if (!m_parent)
- return;
-
- Node* selectNode = m_parent->node();
- if (!selectNode)
- return;
-
- m_haveChildren = true;
-
- const Vector<HTMLElement*>& listItems = toHTMLSelectElement(selectNode)->listItems();
- unsigned length = listItems.size();
- for (unsigned i = 0; i < length; i++) {
- AccessibilityMenuListOption* option = menuListOptionAccessibilityObject(listItems[i]);
- if (option) {
- option->setParent(this);
- m_children.append(option);
- }
- }
-}
-
-void AccessibilityMenuListPopup::childrenChanged()
-{
- AXObjectCache* cache = axObjectCache();
- for (size_t i = m_children.size(); i > 0 ; --i) {
- AccessibilityObject* child = m_children[i - 1].get();
- if (child->actionElement() && !child->actionElement()->attached()) {
- child->detachFromParent();
- cache->remove(child->axObjectID());
- }
- }
-
- m_children.clear();
- m_haveChildren = false;
- addChildren();
-}
-
-void AccessibilityMenuListPopup::didUpdateActiveOption(int optionIndex)
-{
- ASSERT_ARG(optionIndex, optionIndex >= 0);
- ASSERT_ARG(optionIndex, optionIndex < static_cast<int>(m_children.size()));
-
- AXObjectCache* cache = axObjectCache();
- RefPtr<AccessibilityObject> child = m_children[optionIndex].get();
-
- cache->postNotification(child.get(), document(), AXObjectCache::AXFocusedUIElementChanged, true, PostSynchronously);
- cache->postNotification(child.get(), document(), AXObjectCache::AXMenuListItemSelected, true, PostSynchronously);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityMenuListPopup.h b/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityMenuListPopup.h
deleted file mode 100644
index 1f53a0f6a35..00000000000
--- a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityMenuListPopup.h
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Copyright (C) 2010 Apple Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef AccessibilityMenuListPopup_h
-#define AccessibilityMenuListPopup_h
-
-#include "core/accessibility/AccessibilityMockObject.h"
-
-namespace WebCore {
-
-class AccessibilityMenuList;
-class AccessibilityMenuListOption;
-class HTMLElement;
-class HTMLSelectElement;
-
-class AccessibilityMenuListPopup : public AccessibilityMockObject {
-public:
- static PassRefPtr<AccessibilityMenuListPopup> create() { return adoptRef(new AccessibilityMenuListPopup); }
-
- virtual bool isEnabled() const OVERRIDE;
- virtual bool isOffScreen() const OVERRIDE;
-
- void didUpdateActiveOption(int optionIndex);
-
-
-private:
- AccessibilityMenuListPopup();
-
- virtual bool isMenuListPopup() const OVERRIDE { return true; }
-
- virtual LayoutRect elementRect() const OVERRIDE { return LayoutRect(); }
- virtual AccessibilityRole roleValue() const OVERRIDE { return MenuListPopupRole; }
-
- virtual bool isVisible() const OVERRIDE;
- virtual bool press() const OVERRIDE;
- virtual void addChildren() OVERRIDE;
- virtual void childrenChanged() OVERRIDE;
- virtual bool computeAccessibilityIsIgnored() const OVERRIDE;
-
- AccessibilityMenuListOption* menuListOptionAccessibilityObject(HTMLElement*) const;
-};
-
-} // namespace WebCore
-
-#endif // AccessibilityMenuListPopup_h
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityMockObject.cpp b/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityMockObject.cpp
deleted file mode 100644
index f826e52fc8e..00000000000
--- a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityMockObject.cpp
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright (C) 2011 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/accessibility/AccessibilityMockObject.h"
-
-namespace WebCore {
-
-AccessibilityMockObject::AccessibilityMockObject()
- : m_parent(0)
-{
-}
-
-AccessibilityMockObject::~AccessibilityMockObject()
-{
-}
-
-bool AccessibilityMockObject::computeAccessibilityIsIgnored() const
-{
- return accessibilityIsIgnoredByDefault();
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityMockObject.h b/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityMockObject.h
deleted file mode 100644
index 6ea6a590fe7..00000000000
--- a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityMockObject.h
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright (C) 2011 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef AccessibilityMockObject_h
-#define AccessibilityMockObject_h
-
-#include "core/accessibility/AccessibilityObject.h"
-
-namespace WebCore {
-
-class AccessibilityMockObject : public AccessibilityObject {
-
-protected:
- AccessibilityMockObject();
-public:
- virtual ~AccessibilityMockObject();
-
- virtual void setParent(AccessibilityObject* parent) { m_parent = parent; };
-
- // AccessibilityObject overrides.
- virtual AccessibilityObject* parentObject() const OVERRIDE { return m_parent; }
- virtual bool isEnabled() const OVERRIDE { return true; }
-
-protected:
- AccessibilityObject* m_parent;
-
- // Must be called when the parent object clears its children.
- virtual void detachFromParent() OVERRIDE { m_parent = 0; }
-
-private:
- virtual bool isMockObject() const OVERRIDE { return true; }
-
- virtual bool computeAccessibilityIsIgnored() const OVERRIDE;
-};
-
-inline AccessibilityMockObject* toAccessibilityMockObject(AccessibilityObject* object)
-{
- ASSERT(!object || object->isMockObject());
- return static_cast<AccessibilityMockObject*>(object);
-}
-
-} // namespace WebCore
-
-#endif // AccessibilityMockObject_h
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityNodeObject.cpp b/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityNodeObject.cpp
deleted file mode 100644
index 7e7bc64e613..00000000000
--- a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityNodeObject.cpp
+++ /dev/null
@@ -1,1806 +0,0 @@
-/*
-* Copyright (C) 2012, Google Inc. All rights reserved.
-*
-* Redistribution and use in source and binary forms, with or without
-* modification, are permitted provided that the following conditions
-* are met:
-*
-* 1. Redistributions of source code must retain the above copyright
-* notice, this list of conditions and the following disclaimer.
-* 2. Redistributions in binary form must reproduce the above copyright
-* notice, this list of conditions and the following disclaimer in the
-* documentation and/or other materials provided with the distribution.
-* 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
-* its contributors may be used to endorse or promote products derived
-* from this software without specific prior written permission.
-*
-* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
-* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
-* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
-* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
-* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
-* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
-* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-*/
-
-#include "config.h"
-#include "core/accessibility/AccessibilityNodeObject.h"
-
-#include "core/accessibility/AXObjectCache.h"
-#include "core/dom/NodeTraversal.h"
-#include "core/dom/Text.h"
-#include "core/dom/UserGestureIndicator.h"
-#include "core/html/HTMLAnchorElement.h"
-#include "core/html/HTMLFieldSetElement.h"
-#include "core/html/HTMLFrameElementBase.h"
-#include "core/html/HTMLInputElement.h"
-#include "core/html/HTMLLabelElement.h"
-#include "core/html/HTMLLegendElement.h"
-#include "core/html/HTMLSelectElement.h"
-#include "core/html/HTMLTextAreaElement.h"
-#include "core/rendering/RenderObject.h"
-#include "wtf/text/StringBuilder.h"
-
-using namespace std;
-
-namespace WebCore {
-
-using namespace HTMLNames;
-
-AccessibilityNodeObject::AccessibilityNodeObject(Node* node)
- : AccessibilityObject()
- , m_ariaRole(UnknownRole)
- , m_childrenDirty(false)
-#ifndef NDEBUG
- , m_initialized(false)
-#endif
- , m_node(node)
-{
-}
-
-PassRefPtr<AccessibilityNodeObject> AccessibilityNodeObject::create(Node* node)
-{
- return adoptRef(new AccessibilityNodeObject(node));
-}
-
-AccessibilityNodeObject::~AccessibilityNodeObject()
-{
- ASSERT(isDetached());
-}
-
-// This function implements the ARIA accessible name as described by the Mozilla
-// ARIA Implementer's Guide.
-static String accessibleNameForNode(Node* node)
-{
- if (node->isTextNode())
- return toText(node)->data();
-
- if (node->hasTagName(inputTag))
- return toHTMLInputElement(node)->value();
-
- if (node->isHTMLElement()) {
- const AtomicString& alt = toHTMLElement(node)->getAttribute(altAttr);
- if (!alt.isEmpty())
- return alt;
- }
-
- return String();
-}
-
-String AccessibilityNodeObject::accessibilityDescriptionForElements(Vector<Element*> &elements) const
-{
- StringBuilder builder;
- unsigned size = elements.size();
- for (unsigned i = 0; i < size; ++i) {
- Element* idElement = elements[i];
-
- builder.append(accessibleNameForNode(idElement));
- for (Node* n = idElement->firstChild(); n; n = NodeTraversal::next(n, idElement))
- builder.append(accessibleNameForNode(n));
-
- if (i != size - 1)
- builder.append(' ');
- }
- return builder.toString();
-}
-
-void AccessibilityNodeObject::alterSliderValue(bool increase)
-{
- if (roleValue() != SliderRole)
- return;
-
- if (!getAttribute(stepAttr).isEmpty())
- changeValueByStep(increase);
- else
- changeValueByPercent(increase ? 5 : -5);
-}
-
-String AccessibilityNodeObject::ariaAccessibilityDescription() const
-{
- String ariaLabeledBy = ariaLabeledByAttribute();
- if (!ariaLabeledBy.isEmpty())
- return ariaLabeledBy;
-
- const AtomicString& ariaLabel = getAttribute(aria_labelAttr);
- if (!ariaLabel.isEmpty())
- return ariaLabel;
-
- return String();
-}
-
-
-void AccessibilityNodeObject::ariaLabeledByElements(Vector<Element*>& elements) const
-{
- elementsFromAttribute(elements, aria_labeledbyAttr);
- if (!elements.size())
- elementsFromAttribute(elements, aria_labelledbyAttr);
-}
-
-void AccessibilityNodeObject::changeValueByStep(bool increase)
-{
- float step = stepValueForRange();
- float value = valueForRange();
-
- value += increase ? step : -step;
-
- setValue(String::number(value));
-
- axObjectCache()->postNotification(node(), AXObjectCache::AXValueChanged, true);
-}
-
-bool AccessibilityNodeObject::computeAccessibilityIsIgnored() const
-{
-#ifndef NDEBUG
- // Double-check that an AccessibilityObject is never accessed before
- // it's been initialized.
- ASSERT(m_initialized);
-#endif
-
- // If this element is within a parent that cannot have children, it should not be exposed.
- if (isDescendantOfBarrenParent())
- return true;
-
- // Ignore labels that are already referenced by a control's title UI element.
- AccessibilityObject* controlObject = correspondingControlForLabelElement();
- if (controlObject && !controlObject->exposesTitleUIElement() && controlObject->isCheckboxOrRadio())
- return true;
-
- return m_role == UnknownRole;
-}
-
-AccessibilityRole AccessibilityNodeObject::determineAccessibilityRole()
-{
- if (!node())
- return UnknownRole;
-
- m_ariaRole = determineAriaRoleAttribute();
-
- AccessibilityRole ariaRole = ariaRoleAttribute();
- if (ariaRole != UnknownRole)
- return ariaRole;
-
- if (node()->isLink())
- return LinkRole;
- if (node()->isTextNode())
- return StaticTextRole;
- if (node()->hasTagName(buttonTag))
- return buttonRoleType();
- if (node()->hasTagName(inputTag)) {
- HTMLInputElement* input = toHTMLInputElement(node());
- if (input->isCheckbox())
- return CheckBoxRole;
- if (input->isRadioButton())
- return RadioButtonRole;
- if (input->isTextButton())
- return buttonRoleType();
- if (input->isRangeControl())
- return SliderRole;
-
- const AtomicString& type = input->getAttribute(typeAttr);
- if (equalIgnoringCase(type, "color"))
- return ColorWellRole;
-
- return TextFieldRole;
- }
- if (node()->hasTagName(selectTag)) {
- HTMLSelectElement* selectElement = toHTMLSelectElement(node());
- return selectElement->multiple() ? ListBoxRole : PopUpButtonRole;
- }
- if (isHTMLTextAreaElement(node()))
- return TextAreaRole;
- if (headingLevel())
- return HeadingRole;
- if (node()->hasTagName(divTag))
- return DivRole;
- if (node()->hasTagName(pTag))
- return ParagraphRole;
- if (isHTMLLabelElement(node()))
- return LabelRole;
- if (node()->isElementNode() && toElement(node())->isFocusable())
- return GroupRole;
- if (node()->hasTagName(aTag) && isClickable())
- return LinkRole;
-
- return UnknownRole;
-}
-
-AccessibilityRole AccessibilityNodeObject::determineAriaRoleAttribute() const
-{
- const AtomicString& ariaRole = getAttribute(roleAttr);
- if (ariaRole.isNull() || ariaRole.isEmpty())
- return UnknownRole;
-
- AccessibilityRole role = ariaRoleToWebCoreRole(ariaRole);
-
- // ARIA states if an item can get focus, it should not be presentational.
- if (role == PresentationalRole && canSetFocusAttribute())
- return UnknownRole;
-
- if (role == ButtonRole)
- role = buttonRoleType();
-
- if (role == TextAreaRole && !ariaIsMultiline())
- role = TextFieldRole;
-
- role = remapAriaRoleDueToParent(role);
-
- if (role)
- return role;
-
- return UnknownRole;
-}
-
-void AccessibilityNodeObject::elementsFromAttribute(Vector<Element*>& elements, const QualifiedName& attribute) const
-{
- Node* node = this->node();
- if (!node || !node->isElementNode())
- return;
-
- TreeScope& scope = node->treeScope();
-
- String idList = getAttribute(attribute).string();
- if (idList.isEmpty())
- return;
-
- idList.replace('\n', ' ');
- Vector<String> idVector;
- idList.split(' ', idVector);
-
- unsigned size = idVector.size();
- for (unsigned i = 0; i < size; ++i) {
- AtomicString idName(idVector[i]);
- Element* idElement = scope.getElementById(idName);
- if (idElement)
- elements.append(idElement);
- }
-}
-
-// If you call node->rendererIsEditable() since that will return true if an ancestor is editable.
-// This only returns true if this is the element that actually has the contentEditable attribute set.
-bool AccessibilityNodeObject::hasContentEditableAttributeSet() const
-{
- if (!hasAttribute(contenteditableAttr))
- return false;
- const AtomicString& contentEditableValue = getAttribute(contenteditableAttr);
- // Both "true" (case-insensitive) and the empty string count as true.
- return contentEditableValue.isEmpty() || equalIgnoringCase(contentEditableValue, "true");
-}
-
-bool AccessibilityNodeObject::isDescendantOfBarrenParent() const
-{
- for (AccessibilityObject* object = parentObject(); object; object = object->parentObject()) {
- if (!object->canHaveChildren())
- return true;
- }
-
- return false;
-}
-
-bool AccessibilityNodeObject::isGenericFocusableElement() const
-{
- if (!canSetFocusAttribute())
- return false;
-
- // If it's a control, it's not generic.
- if (isControl())
- return false;
-
- // If it has an aria role, it's not generic.
- if (m_ariaRole != UnknownRole)
- return false;
-
- // If the content editable attribute is set on this element, that's the reason
- // it's focusable, and existing logic should handle this case already - so it's not a
- // generic focusable element.
-
- if (hasContentEditableAttributeSet())
- return false;
-
- // The web area and body element are both focusable, but existing logic handles these
- // cases already, so we don't need to include them here.
- if (roleValue() == WebAreaRole)
- return false;
- if (node() && node()->hasTagName(bodyTag))
- return false;
-
- // An SVG root is focusable by default, but it's probably not interactive, so don't
- // include it. It can still be made accessible by giving it an ARIA role.
- if (roleValue() == SVGRootRole)
- return false;
-
- return true;
-}
-
-HTMLLabelElement* AccessibilityNodeObject::labelForElement(Element* element) const
-{
- if (!element->isHTMLElement() || !toHTMLElement(element)->isLabelable())
- return 0;
-
- const AtomicString& id = element->getIdAttribute();
- if (!id.isEmpty()) {
- if (HTMLLabelElement* label = element->treeScope().labelElementForId(id))
- return label;
- }
-
- for (Element* parent = element->parentElement(); parent; parent = parent->parentElement()) {
- if (isHTMLLabelElement(parent))
- return toHTMLLabelElement(parent);
- }
-
- return 0;
-}
-
-AccessibilityObject* AccessibilityNodeObject::menuButtonForMenu() const
-{
- Element* menuItem = menuItemElementForMenu();
-
- if (menuItem) {
- // ARIA just has generic menu items. AppKit needs to know if this is a top level items like MenuBarButton or MenuBarItem
- AccessibilityObject* menuItemAX = axObjectCache()->getOrCreate(menuItem);
- if (menuItemAX && menuItemAX->isMenuButton())
- return menuItemAX;
- }
- return 0;
-}
-
-static Element* siblingWithAriaRole(String role, Node* node)
-{
- Node* parent = node->parentNode();
- if (!parent)
- return 0;
-
- for (Node* sibling = parent->firstChild(); sibling; sibling = sibling->nextSibling()) {
- if (sibling->isElementNode()) {
- const AtomicString& siblingAriaRole = toElement(sibling)->getAttribute(roleAttr);
- if (equalIgnoringCase(siblingAriaRole, role))
- return toElement(sibling);
- }
- }
-
- return 0;
-}
-
-Element* AccessibilityNodeObject::menuItemElementForMenu() const
-{
- if (ariaRoleAttribute() != MenuRole)
- return 0;
-
- return siblingWithAriaRole("menuitem", node());
-}
-
-Element* AccessibilityNodeObject::mouseButtonListener() const
-{
- Node* node = this->node();
- if (!node)
- return 0;
-
- // check if our parent is a mouse button listener
- while (node && !node->isElementNode())
- node = node->parentNode();
-
- if (!node)
- return 0;
-
- // FIXME: Do the continuation search like anchorElement does
- for (Element* element = toElement(node); element; element = element->parentElement()) {
- if (element->getAttributeEventListener(eventNames().clickEvent) || element->getAttributeEventListener(eventNames().mousedownEvent) || element->getAttributeEventListener(eventNames().mouseupEvent))
- return element;
- }
-
- return 0;
-}
-
-AccessibilityRole AccessibilityNodeObject::remapAriaRoleDueToParent(AccessibilityRole role) const
-{
- // Some objects change their role based on their parent.
- // However, asking for the unignoredParent calls accessibilityIsIgnored(), which can trigger a loop.
- // While inside the call stack of creating an element, we need to avoid accessibilityIsIgnored().
- // https://bugs.webkit.org/show_bug.cgi?id=65174
-
- if (role != ListBoxOptionRole && role != MenuItemRole)
- return role;
-
- for (AccessibilityObject* parent = parentObject(); parent && !parent->accessibilityIsIgnored(); parent = parent->parentObject()) {
- AccessibilityRole parentAriaRole = parent->ariaRoleAttribute();
-
- // Selects and listboxes both have options as child roles, but they map to different roles within WebCore.
- if (role == ListBoxOptionRole && parentAriaRole == MenuRole)
- return MenuItemRole;
- // An aria "menuitem" may map to MenuButton or MenuItem depending on its parent.
- if (role == MenuItemRole && parentAriaRole == GroupRole)
- return MenuButtonRole;
-
- // If the parent had a different role, then we don't need to continue searching up the chain.
- if (parentAriaRole)
- break;
- }
-
- return role;
-}
-
-void AccessibilityNodeObject::init()
-{
-#ifndef NDEBUG
- ASSERT(!m_initialized);
- m_initialized = true;
-#endif
- m_role = determineAccessibilityRole();
-}
-
-void AccessibilityNodeObject::detach()
-{
- clearChildren();
- AccessibilityObject::detach();
- m_node = 0;
-}
-
-bool AccessibilityNodeObject::isAnchor() const
-{
- return !isNativeImage() && isLink();
-}
-
-bool AccessibilityNodeObject::isControl() const
-{
- Node* node = this->node();
- if (!node)
- return false;
-
- return ((node->isElementNode() && toElement(node)->isFormControlElement())
- || AccessibilityObject::isARIAControl(ariaRoleAttribute()));
-}
-
-bool AccessibilityNodeObject::isFieldset() const
-{
- Node* node = this->node();
- if (!node)
- return false;
-
- return node->hasTagName(fieldsetTag);
-}
-
-bool AccessibilityNodeObject::isHeading() const
-{
- return roleValue() == HeadingRole;
-}
-
-bool AccessibilityNodeObject::isHovered() const
-{
- Node* node = this->node();
- if (!node)
- return false;
-
- return node->hovered();
-}
-
-bool AccessibilityNodeObject::isImage() const
-{
- return roleValue() == ImageRole;
-}
-
-bool AccessibilityNodeObject::isImageButton() const
-{
- return isNativeImage() && isButton();
-}
-
-bool AccessibilityNodeObject::isInputImage() const
-{
- Node* node = this->node();
- if (!node)
- return false;
-
- if (roleValue() == ButtonRole && node->hasTagName(inputTag))
- return toHTMLInputElement(node)->isImageButton();
-
- return false;
-}
-
-bool AccessibilityNodeObject::isLink() const
-{
- return roleValue() == LinkRole;
-}
-
-bool AccessibilityNodeObject::isMenu() const
-{
- return roleValue() == MenuRole;
-}
-
-bool AccessibilityNodeObject::isMenuButton() const
-{
- return roleValue() == MenuButtonRole;
-}
-
-bool AccessibilityNodeObject::isMultiSelectable() const
-{
- const AtomicString& ariaMultiSelectable = getAttribute(aria_multiselectableAttr);
- if (equalIgnoringCase(ariaMultiSelectable, "true"))
- return true;
- if (equalIgnoringCase(ariaMultiSelectable, "false"))
- return false;
-
- return node() && node()->hasTagName(selectTag) && toHTMLSelectElement(node())->multiple();
-}
-
-bool AccessibilityNodeObject::isNativeCheckboxOrRadio() const
-{
- Node* node = this->node();
- if (!node || !node->hasTagName(inputTag))
- return false;
-
- HTMLInputElement* input = toHTMLInputElement(node);
- return input->isCheckbox() || input->isRadioButton();
-}
-
-bool AccessibilityNodeObject::isNativeImage() const
-{
- Node* node = this->node();
- if (!node)
- return false;
-
- if (node->hasTagName(imgTag))
- return true;
-
- if (node->hasTagName(appletTag) || node->hasTagName(embedTag) || node->hasTagName(objectTag))
- return true;
-
- if (node->hasTagName(inputTag))
- return toHTMLInputElement(node)->isImageButton();
-
- return false;
-}
-
-bool AccessibilityNodeObject::isNativeTextControl() const
-{
- Node* node = this->node();
- if (!node)
- return false;
-
- if (isHTMLTextAreaElement(node))
- return true;
-
- if (node->hasTagName(inputTag)) {
- HTMLInputElement* input = toHTMLInputElement(node);
- return input->isText() || input->isNumberField();
- }
-
- return false;
-}
-
-bool AccessibilityNodeObject::isNonNativeTextControl() const
-{
- if (isNativeTextControl())
- return false;
-
- if (hasContentEditableAttributeSet())
- return true;
-
- if (isARIATextControl())
- return true;
-
- return false;
-}
-
-bool AccessibilityNodeObject::isPasswordField() const
-{
- Node* node = this->node();
- if (!node || !node->hasTagName(inputTag))
- return false;
-
- if (ariaRoleAttribute() != UnknownRole)
- return false;
-
- return toHTMLInputElement(node)->isPasswordField();
-}
-
-bool AccessibilityNodeObject::isProgressIndicator() const
-{
- return roleValue() == ProgressIndicatorRole;
-}
-
-bool AccessibilityNodeObject::isSlider() const
-{
- return roleValue() == SliderRole;
-}
-
-bool AccessibilityNodeObject::isChecked() const
-{
- Node* node = this->node();
- if (!node)
- return false;
-
- // First test for native checkedness semantics
- if (node->hasTagName(inputTag))
- return toHTMLInputElement(node)->shouldAppearChecked();
-
- // Else, if this is an ARIA checkbox or radio, respect the aria-checked attribute
- AccessibilityRole ariaRole = ariaRoleAttribute();
- if (ariaRole == RadioButtonRole || ariaRole == CheckBoxRole) {
- if (equalIgnoringCase(getAttribute(aria_checkedAttr), "true"))
- return true;
- return false;
- }
-
- // Otherwise it's not checked
- return false;
-}
-
-bool AccessibilityNodeObject::isClickable() const
-{
- if (node()) {
- if (node()->isElementNode() && toElement(node())->isDisabledFormControl())
- return false;
-
- // Note: we can't call node()->willRespondToMouseClickEvents() because that triggers a style recalc and can delete this.
- if (node()->hasEventListeners(eventNames().mouseupEvent) || node()->hasEventListeners(eventNames().mousedownEvent) || node()->hasEventListeners(eventNames().clickEvent) || node()->hasEventListeners(eventNames().DOMActivateEvent))
- return true;
- }
-
- return AccessibilityObject::isClickable();
-}
-
-bool AccessibilityNodeObject::isEnabled() const
-{
- if (equalIgnoringCase(getAttribute(aria_disabledAttr), "true"))
- return false;
-
- Node* node = this->node();
- if (!node || !node->isElementNode())
- return true;
-
- return !node->isInert() && !toElement(node)->isDisabledFormControl();
-}
-
-bool AccessibilityNodeObject::isIndeterminate() const
-{
- Node* node = this->node();
- if (!node || !node->hasTagName(inputTag))
- return false;
-
- return toHTMLInputElement(node)->shouldAppearIndeterminate();
-}
-
-bool AccessibilityNodeObject::isPressed() const
-{
- if (!isButton())
- return false;
-
- Node* node = this->node();
- if (!node)
- return false;
-
- // If this is an ARIA button, check the aria-pressed attribute rather than node()->active()
- if (ariaRoleAttribute() == ButtonRole) {
- if (equalIgnoringCase(getAttribute(aria_pressedAttr), "true"))
- return true;
- return false;
- }
-
- return node->active();
-}
-
-bool AccessibilityNodeObject::isReadOnly() const
-{
- Node* node = this->node();
- if (!node)
- return true;
-
- if (isHTMLTextAreaElement(node))
- return toHTMLFormControlElement(node)->isReadOnly();
-
- if (node->hasTagName(inputTag)) {
- HTMLInputElement* input = toHTMLInputElement(node);
- if (input->isTextField())
- return input->isReadOnly();
- }
-
- return !node->rendererIsEditable();
-}
-
-bool AccessibilityNodeObject::isRequired() const
-{
- if (equalIgnoringCase(getAttribute(aria_requiredAttr), "true"))
- return true;
-
- Node* n = this->node();
- if (n && (n->isElementNode() && toElement(n)->isFormControlElement()))
- return toHTMLFormControlElement(n)->isRequired();
-
- return false;
-}
-
-bool AccessibilityNodeObject::canSetFocusAttribute() const
-{
- Node* node = this->node();
- if (!node)
- return false;
-
- if (isWebArea())
- return true;
-
- // NOTE: It would be more accurate to ask the document whether setFocusedNode() would
- // do anything. For example, setFocusedNode() will do nothing if the current focused
- // node will not relinquish the focus.
- if (!node)
- return false;
-
- if (isDisabledFormControl(node))
- return false;
-
- return node->isElementNode() && toElement(node)->supportsFocus();
-}
-
-bool AccessibilityNodeObject::canSetValueAttribute() const
-{
- if (equalIgnoringCase(getAttribute(aria_readonlyAttr), "true"))
- return false;
-
- if (isProgressIndicator() || isSlider())
- return true;
-
- if (isTextControl() && !isNativeTextControl())
- return true;
-
- // Any node could be contenteditable, so isReadOnly should be relied upon
- // for this information for all elements.
- return !isReadOnly();
-}
-
-bool AccessibilityNodeObject::canvasHasFallbackContent() const
-{
- Node* node = this->node();
- if (!node || !node->hasTagName(canvasTag))
- return false;
-
- // If it has any children that are elements, we'll assume it might be fallback
- // content. If it has no children or its only children are not elements
- // (e.g. just text nodes), it doesn't have fallback content.
- for (Node* child = node->firstChild(); child; child = child->nextSibling()) {
- if (child->isElementNode())
- return true;
- }
-
- return false;
-}
-
-bool AccessibilityNodeObject::exposesTitleUIElement() const
-{
- if (!isControl())
- return false;
-
- // If this control is ignored (because it's invisible),
- // then the label needs to be exposed so it can be visible to accessibility.
- if (accessibilityIsIgnored())
- return true;
-
- // ARIA: section 2A, bullet #3 says if aria-labeledby or aria-label appears, it should
- // override the "label" element association.
- bool hasTextAlternative = (!ariaLabeledByAttribute().isEmpty() || !getAttribute(aria_labelAttr).isEmpty());
-
- // Checkboxes and radio buttons use the text of their title ui element as their own AXTitle.
- // This code controls whether the title ui element should appear in the AX tree (usually, no).
- // It should appear if the control already has a label (which will be used as the AXTitle instead).
- if (isCheckboxOrRadio())
- return hasTextAlternative;
-
- // When controls have their own descriptions, the title element should be ignored.
- if (hasTextAlternative)
- return false;
-
- return true;
-}
-
-int AccessibilityNodeObject::headingLevel() const
-{
- // headings can be in block flow and non-block flow
- Node* node = this->node();
- if (!node)
- return false;
-
- if (ariaRoleAttribute() == HeadingRole)
- return getAttribute(aria_levelAttr).toInt();
-
- if (node->hasTagName(h1Tag))
- return 1;
-
- if (node->hasTagName(h2Tag))
- return 2;
-
- if (node->hasTagName(h3Tag))
- return 3;
-
- if (node->hasTagName(h4Tag))
- return 4;
-
- if (node->hasTagName(h5Tag))
- return 5;
-
- if (node->hasTagName(h6Tag))
- return 6;
-
- return 0;
-}
-
-unsigned AccessibilityNodeObject::hierarchicalLevel() const
-{
- Node* node = this->node();
- if (!node || !node->isElementNode())
- return 0;
- Element* element = toElement(node);
- String ariaLevel = element->getAttribute(aria_levelAttr);
- if (!ariaLevel.isEmpty())
- return ariaLevel.toInt();
-
- // Only tree item will calculate its level through the DOM currently.
- if (roleValue() != TreeItemRole)
- return 0;
-
- // Hierarchy leveling starts at 1, to match the aria-level spec.
- // We measure tree hierarchy by the number of groups that the item is within.
- unsigned level = 1;
- for (AccessibilityObject* parent = parentObject(); parent; parent = parent->parentObject()) {
- AccessibilityRole parentRole = parent->roleValue();
- if (parentRole == GroupRole)
- level++;
- else if (parentRole == TreeRole)
- break;
- }
-
- return level;
-}
-
-String AccessibilityNodeObject::text() const
-{
- // If this is a user defined static text, use the accessible name computation.
- if (ariaRoleAttribute() == StaticTextRole)
- return ariaAccessibilityDescription();
-
- if (!isTextControl())
- return String();
-
- Node* node = this->node();
- if (!node)
- return String();
-
- if (isNativeTextControl() && (isHTMLTextAreaElement(node) || node->hasTagName(inputTag)))
- return toHTMLTextFormControlElement(node)->value();
-
- if (!node->isElementNode())
- return String();
-
- return toElement(node)->innerText();
-}
-
-AccessibilityObject* AccessibilityNodeObject::titleUIElement() const
-{
- if (!node() || !node()->isElementNode())
- return 0;
-
- if (isFieldset())
- return axObjectCache()->getOrCreate(toHTMLFieldSetElement(node())->legend());
-
- HTMLLabelElement* label = labelForElement(toElement(node()));
- if (label)
- return axObjectCache()->getOrCreate(label);
-
- return 0;
-}
-
-AccessibilityButtonState AccessibilityNodeObject::checkboxOrRadioValue() const
-{
- if (isNativeCheckboxOrRadio())
- return isChecked() ? ButtonStateOn : ButtonStateOff;
-
- return AccessibilityObject::checkboxOrRadioValue();
-}
-
-void AccessibilityNodeObject::colorValue(int& r, int& g, int& b) const
-{
- r = 0;
- g = 0;
- b = 0;
-
- if (!isColorWell())
- return;
-
- if (!node() || !node()->hasTagName(inputTag))
- return;
-
- HTMLInputElement* input = toHTMLInputElement(node());
- const AtomicString& type = input->getAttribute(typeAttr);
- if (!equalIgnoringCase(type, "color"))
- return;
-
- // HTMLInputElement::value always returns a string parseable by Color().
- Color color(input->value());
- r = color.red();
- g = color.green();
- b = color.blue();
-}
-
-String AccessibilityNodeObject::valueDescription() const
-{
- if (!supportsRangeValue())
- return String();
-
- return getAttribute(aria_valuetextAttr).string();
-}
-
-float AccessibilityNodeObject::valueForRange() const
-{
- if (hasAttribute(aria_valuenowAttr))
- return getAttribute(aria_valuenowAttr).toFloat();
-
- if (node() && node()->hasTagName(inputTag)) {
- HTMLInputElement* input = toHTMLInputElement(node());
- if (input->isRangeControl())
- return input->valueAsNumber();
- }
-
- return 0.0;
-}
-
-float AccessibilityNodeObject::maxValueForRange() const
-{
- if (hasAttribute(aria_valuemaxAttr))
- return getAttribute(aria_valuemaxAttr).toFloat();
-
- if (node() && node()->hasTagName(inputTag)) {
- HTMLInputElement* input = toHTMLInputElement(node());
- if (input->isRangeControl())
- return input->maximum();
- }
-
- return 0.0;
-}
-
-float AccessibilityNodeObject::minValueForRange() const
-{
- if (hasAttribute(aria_valueminAttr))
- return getAttribute(aria_valueminAttr).toFloat();
-
- if (node() && node()->hasTagName(inputTag)) {
- HTMLInputElement* input = toHTMLInputElement(node());
- if (input->isRangeControl())
- return input->minimum();
- }
-
- return 0.0;
-}
-
-float AccessibilityNodeObject::stepValueForRange() const
-{
- return getAttribute(stepAttr).toFloat();
-}
-
-String AccessibilityNodeObject::stringValue() const
-{
- Node* node = this->node();
- if (!node)
- return String();
-
- if (ariaRoleAttribute() == StaticTextRole) {
- String staticText = text();
- if (!staticText.length())
- staticText = textUnderElement();
- return staticText;
- }
-
- if (node->isTextNode())
- return textUnderElement();
-
- if (node->hasTagName(selectTag)) {
- HTMLSelectElement* selectElement = toHTMLSelectElement(node);
- int selectedIndex = selectElement->selectedIndex();
- const Vector<HTMLElement*> listItems = selectElement->listItems();
- if (selectedIndex >= 0 && static_cast<size_t>(selectedIndex) < listItems.size()) {
- const AtomicString& overriddenDescription = listItems[selectedIndex]->fastGetAttribute(aria_labelAttr);
- if (!overriddenDescription.isNull())
- return overriddenDescription;
- }
- if (!selectElement->multiple())
- return selectElement->value();
- return String();
- }
-
- if (isTextControl())
- return text();
-
- // FIXME: We might need to implement a value here for more types
- // FIXME: It would be better not to advertise a value at all for the types for which we don't implement one;
- // this would require subclassing or making accessibilityAttributeNames do something other than return a
- // single static array.
- return String();
-}
-
-String AccessibilityNodeObject::ariaDescribedByAttribute() const
-{
- Vector<Element*> elements;
- elementsFromAttribute(elements, aria_describedbyAttr);
-
- return accessibilityDescriptionForElements(elements);
-}
-
-
-String AccessibilityNodeObject::ariaLabeledByAttribute() const
-{
- Vector<Element*> elements;
- ariaLabeledByElements(elements);
-
- return accessibilityDescriptionForElements(elements);
-}
-
-AccessibilityRole AccessibilityNodeObject::ariaRoleAttribute() const
-{
- return m_ariaRole;
-}
-
-void AccessibilityNodeObject::accessibilityText(Vector<AccessibilityText>& textOrder)
-{
- titleElementText(textOrder);
- alternativeText(textOrder);
- visibleText(textOrder);
- helpText(textOrder);
-
- String placeholder = placeholderValue();
- if (!placeholder.isEmpty())
- textOrder.append(AccessibilityText(placeholder, PlaceholderText));
-}
-
-// When building the textUnderElement for an object, determine whether or not
-// we should include the inner text of this given descendant object or skip it.
-static bool shouldUseAccessiblityObjectInnerText(AccessibilityObject* obj)
-{
- // Consider this hypothetical example:
- // <div tabindex=0>
- // <h2>
- // Table of contents
- // </h2>
- // <a href="#start">Jump to start of book</a>
- // <ul>
- // <li><a href="#1">Chapter 1</a></li>
- // <li><a href="#1">Chapter 2</a></li>
- // </ul>
- // </div>
- //
- // The goal is to return a reasonable title for the outer container div, because
- // it's focusable - but without making its title be the full inner text, which is
- // quite long. As a heuristic, skip links, controls, and elements that are usually
- // containers with lots of children.
-
- // Skip focusable children, so we don't include the text of links and controls.
- if (obj->canSetFocusAttribute())
- return false;
-
- // Skip big container elements like lists, tables, etc.
- if (obj->isList() || obj->isAccessibilityTable() || obj->isTree() || obj->isCanvas())
- return false;
-
- return true;
-}
-
-String AccessibilityNodeObject::textUnderElement() const
-{
- Node* node = this->node();
- if (node && node->isTextNode())
- return toText(node)->wholeText();
-
- StringBuilder builder;
- for (AccessibilityObject* child = firstChild(); child; child = child->nextSibling()) {
- if (!shouldUseAccessiblityObjectInnerText(child))
- continue;
-
- if (child->isAccessibilityNodeObject()) {
- Vector<AccessibilityText> textOrder;
- toAccessibilityNodeObject(child)->alternativeText(textOrder);
- if (textOrder.size() > 0) {
- builder.append(textOrder[0].text);
- continue;
- }
- }
-
- builder.append(child->textUnderElement());
- }
-
- return builder.toString();
-}
-
-String AccessibilityNodeObject::accessibilityDescription() const
-{
- // Static text should not have a description, it should only have a stringValue.
- if (roleValue() == StaticTextRole)
- return String();
-
- String ariaDescription = ariaAccessibilityDescription();
- if (!ariaDescription.isEmpty())
- return ariaDescription;
-
- if (isImage() || isInputImage() || isNativeImage() || isCanvas()) {
- // Images should use alt as long as the attribute is present, even if empty.
- // Otherwise, it should fallback to other methods, like the title attribute.
- const AtomicString& alt = getAttribute(altAttr);
- if (!alt.isNull())
- return alt;
- }
-
- // An element's descriptive text is comprised of title() (what's visible on the screen) and accessibilityDescription() (other descriptive text).
- // Both are used to generate what a screen reader speaks.
- // If this point is reached (i.e. there's no accessibilityDescription) and there's no title(), we should fallback to using the title attribute.
- // The title attribute is normally used as help text (because it is a tooltip), but if there is nothing else available, this should be used (according to ARIA).
- if (title().isEmpty())
- return getAttribute(titleAttr);
-
- return String();
-}
-
-String AccessibilityNodeObject::title() const
-{
- Node* node = this->node();
- if (!node)
- return String();
-
- bool isInputTag = node->hasTagName(inputTag);
- if (isInputTag) {
- HTMLInputElement* input = toHTMLInputElement(node);
- if (input->isTextButton())
- return input->valueWithDefault();
- }
-
- if (isInputTag || AccessibilityObject::isARIAInput(ariaRoleAttribute()) || isControl()) {
- HTMLLabelElement* label = labelForElement(toElement(node));
- if (label && !exposesTitleUIElement())
- return label->innerText();
- }
-
- // If this node isn't rendered, there's no inner text we can extract from a select element.
- if (!isAccessibilityRenderObject() && node->hasTagName(selectTag))
- return String();
-
- switch (roleValue()) {
- case PopUpButtonRole:
- // Native popup buttons should not use their button children's text as a title. That value is retrieved through stringValue().
- if (node->hasTagName(selectTag))
- return String();
- case ButtonRole:
- case ToggleButtonRole:
- case CheckBoxRole:
- case ListBoxOptionRole:
- case MenuButtonRole:
- case MenuItemRole:
- case RadioButtonRole:
- case TabRole:
- return textUnderElement();
- // SVGRoots should not use the text under itself as a title. That could include the text of objects like <text>.
- case SVGRootRole:
- return String();
- default:
- break;
- }
-
- if (isHeading() || isLink())
- return textUnderElement();
-
- // If it's focusable but it's not content editable or a known control type, then it will appear to
- // the user as a single atomic object, so we should use its text as the default title.
- if (isGenericFocusableElement())
- return textUnderElement();
-
- return String();
-}
-
-String AccessibilityNodeObject::helpText() const
-{
- Node* node = this->node();
- if (!node)
- return String();
-
- const AtomicString& ariaHelp = getAttribute(aria_helpAttr);
- if (!ariaHelp.isEmpty())
- return ariaHelp;
-
- String describedBy = ariaDescribedByAttribute();
- if (!describedBy.isEmpty())
- return describedBy;
-
- String description = accessibilityDescription();
- for (Node* curr = node; curr; curr = curr->parentNode()) {
- if (curr->isHTMLElement()) {
- const AtomicString& summary = toElement(curr)->getAttribute(summaryAttr);
- if (!summary.isEmpty())
- return summary;
-
- // The title attribute should be used as help text unless it is already being used as descriptive text.
- const AtomicString& title = toElement(curr)->getAttribute(titleAttr);
- if (!title.isEmpty() && description != title)
- return title;
- }
-
- // Only take help text from an ancestor element if its a group or an unknown role. If help was
- // added to those kinds of elements, it is likely it was meant for a child element.
- AccessibilityObject* axObj = axObjectCache()->getOrCreate(curr);
- if (axObj) {
- AccessibilityRole role = axObj->roleValue();
- if (role != GroupRole && role != UnknownRole)
- break;
- }
- }
-
- return String();
-}
-
-LayoutRect AccessibilityNodeObject::elementRect() const
-{
- // First check if it has a custom rect, for example if this element is tied to a canvas path.
- if (!m_explicitElementRect.isEmpty())
- return m_explicitElementRect;
-
- // AccessibilityNodeObjects have no mechanism yet to return a size or position.
- // For now, let's return the position of the ancestor that does have a position,
- // and make it the width of that parent, and about the height of a line of text, so that it's clear the object is a child of the parent.
-
- LayoutRect boundingBox;
-
- for (AccessibilityObject* positionProvider = parentObject(); positionProvider; positionProvider = positionProvider->parentObject()) {
- if (positionProvider->isAccessibilityRenderObject()) {
- LayoutRect parentRect = positionProvider->elementRect();
- boundingBox.setSize(LayoutSize(parentRect.width(), LayoutUnit(std::min(10.0f, parentRect.height().toFloat()))));
- boundingBox.setLocation(parentRect.location());
- break;
- }
- }
-
- return boundingBox;
-}
-
-AccessibilityObject* AccessibilityNodeObject::parentObject() const
-{
- if (!node())
- return 0;
-
- Node* parentObj = node()->parentNode();
- if (parentObj)
- return axObjectCache()->getOrCreate(parentObj);
-
- return 0;
-}
-
-AccessibilityObject* AccessibilityNodeObject::parentObjectIfExists() const
-{
- return parentObject();
-}
-
-AccessibilityObject* AccessibilityNodeObject::firstChild() const
-{
- if (!node())
- return 0;
-
- Node* firstChild = node()->firstChild();
-
- if (!firstChild)
- return 0;
-
- return axObjectCache()->getOrCreate(firstChild);
-}
-
-AccessibilityObject* AccessibilityNodeObject::nextSibling() const
-{
- if (!node())
- return 0;
-
- Node* nextSibling = node()->nextSibling();
- if (!nextSibling)
- return 0;
-
- return axObjectCache()->getOrCreate(nextSibling);
-}
-
-void AccessibilityNodeObject::addChildren()
-{
- // If the need to add more children in addition to existing children arises,
- // childrenChanged should have been called, leaving the object with no children.
- ASSERT(!m_haveChildren);
-
- if (!m_node)
- return;
-
- m_haveChildren = true;
-
- // The only time we add children from the DOM tree to a node with a renderer is when it's a canvas.
- if (renderer() && !m_node->hasTagName(canvasTag))
- return;
-
- for (Node* child = m_node->firstChild(); child; child = child->nextSibling())
- addChild(axObjectCache()->getOrCreate(child));
-}
-
-void AccessibilityNodeObject::addChild(AccessibilityObject* child)
-{
- insertChild(child, m_children.size());
-}
-
-void AccessibilityNodeObject::insertChild(AccessibilityObject* child, unsigned index)
-{
- if (!child)
- return;
-
- // If the parent is asking for this child's children, then either it's the first time (and clearing is a no-op),
- // or its visibility has changed. In the latter case, this child may have a stale child cached.
- // This can prevent aria-hidden changes from working correctly. Hence, whenever a parent is getting children, ensure data is not stale.
- child->clearChildren();
-
- if (child->accessibilityIsIgnored()) {
- AccessibilityChildrenVector children = child->children();
- size_t length = children.size();
- for (size_t i = 0; i < length; ++i)
- m_children.insert(index + i, children[i]);
- } else {
- ASSERT(child->parentObject() == this);
- m_children.insert(index, child);
- }
-}
-
-bool AccessibilityNodeObject::canHaveChildren() const
-{
- // If this is an AccessibilityRenderObject, then it's okay if this object
- // doesn't have a node - there are some renderers that don't have associated
- // nodes, like scroll areas and css-generated text.
- if (!node() && !isAccessibilityRenderObject())
- return false;
-
- // Elements that should not have children
- switch (roleValue()) {
- case ImageRole:
- case ButtonRole:
- case PopUpButtonRole:
- case CheckBoxRole:
- case RadioButtonRole:
- case TabRole:
- case ToggleButtonRole:
- case StaticTextRole:
- case ListBoxOptionRole:
- case ScrollBarRole:
- return false;
- default:
- return true;
- }
-}
-
-Element* AccessibilityNodeObject::actionElement() const
-{
- Node* node = this->node();
- if (!node)
- return 0;
-
- if (node->hasTagName(inputTag)) {
- HTMLInputElement* input = toHTMLInputElement(node);
- if (!input->isDisabledFormControl() && (isCheckboxOrRadio() || input->isTextButton()))
- return input;
- } else if (node->hasTagName(buttonTag))
- return toElement(node);
-
- if (isFileUploadButton())
- return toElement(node);
-
- if (AccessibilityObject::isARIAInput(ariaRoleAttribute()))
- return toElement(node);
-
- if (isImageButton())
- return toElement(node);
-
- if (node->hasTagName(selectTag))
- return toElement(node);
-
- switch (roleValue()) {
- case ButtonRole:
- case PopUpButtonRole:
- case ToggleButtonRole:
- case TabRole:
- case MenuItemRole:
- case ListItemRole:
- return toElement(node);
- default:
- break;
- }
-
- Element* elt = anchorElement();
- if (!elt)
- elt = mouseButtonListener();
- return elt;
-}
-
-Element* AccessibilityNodeObject::anchorElement() const
-{
- Node* node = this->node();
- if (!node)
- return 0;
-
- AXObjectCache* cache = axObjectCache();
-
- // search up the DOM tree for an anchor element
- // NOTE: this assumes that any non-image with an anchor is an HTMLAnchorElement
- for ( ; node; node = node->parentNode()) {
- if (isHTMLAnchorElement(node) || (node->renderer() && cache->getOrCreate(node->renderer())->isAnchor()))
- return toElement(node);
- }
-
- return 0;
-}
-
-Document* AccessibilityNodeObject::document() const
-{
- if (!node())
- return 0;
- return &node()->document();
-}
-
-void AccessibilityNodeObject::setNode(Node* node)
-{
- m_node = node;
-}
-
-AccessibilityObject* AccessibilityNodeObject::correspondingControlForLabelElement() const
-{
- HTMLLabelElement* labelElement = labelElementContainer();
- if (!labelElement)
- return 0;
-
- HTMLElement* correspondingControl = labelElement->control();
- if (!correspondingControl)
- return 0;
-
- // Make sure the corresponding control isn't a descendant of this label
- // that's in the middle of being destroyed.
- if (correspondingControl->renderer() && !correspondingControl->renderer()->parent())
- return 0;
-
- return axObjectCache()->getOrCreate(correspondingControl);
-}
-
-HTMLLabelElement* AccessibilityNodeObject::labelElementContainer() const
-{
- if (!node())
- return 0;
-
- // the control element should not be considered part of the label
- if (isControl())
- return 0;
-
- // find if this has a parent that is a label
- for (Node* parentNode = node(); parentNode; parentNode = parentNode->parentNode()) {
- if (isHTMLLabelElement(parentNode))
- return toHTMLLabelElement(parentNode);
- }
-
- return 0;
-}
-
-void AccessibilityNodeObject::setFocused(bool on)
-{
- if (!canSetFocusAttribute())
- return;
-
- Document* document = this->document();
- if (!on) {
- document->setFocusedElement(0);
- } else {
- Node* node = this->node();
- if (node && node->isElementNode()) {
- // If this node is already the currently focused node, then calling focus() won't do anything.
- // That is a problem when focus is removed from the webpage to chrome, and then returns.
- // In these cases, we need to do what keyboard and mouse focus do, which is reset focus first.
- if (document->focusedElement() == node)
- document->setFocusedElement(0);
-
- toElement(node)->focus();
- } else {
- document->setFocusedElement(0);
- }
- }
-}
-
-void AccessibilityNodeObject::increment()
-{
- UserGestureIndicator gestureIndicator(DefinitelyProcessingNewUserGesture);
- alterSliderValue(true);
-}
-
-void AccessibilityNodeObject::decrement()
-{
- UserGestureIndicator gestureIndicator(DefinitelyProcessingNewUserGesture);
- alterSliderValue(false);
-}
-
-void AccessibilityNodeObject::childrenChanged()
-{
- // This method is meant as a quick way of marking a portion of the accessibility tree dirty.
- if (!node() && !renderer())
- return;
-
- axObjectCache()->postNotification(this, document(), AXObjectCache::AXChildrenChanged, true);
-
- // Go up the accessibility parent chain, but only if the element already exists. This method is
- // called during render layouts, minimal work should be done.
- // If AX elements are created now, they could interrogate the render tree while it's in a funky state.
- // At the same time, process ARIA live region changes.
- for (AccessibilityObject* parent = this; parent; parent = parent->parentObjectIfExists()) {
- parent->setNeedsToUpdateChildren();
-
- // These notifications always need to be sent because screenreaders are reliant on them to perform.
- // In other words, they need to be sent even when the screen reader has not accessed this live region since the last update.
-
- // If this element supports ARIA live regions, then notify the AT of changes.
- if (parent->supportsARIALiveRegion())
- axObjectCache()->postNotification(parent, parent->document(), AXObjectCache::AXLiveRegionChanged, true);
-
- // If this element is an ARIA text box or content editable, post a "value changed" notification on it
- // so that it behaves just like a native input element or textarea.
- if (isNonNativeTextControl())
- axObjectCache()->postNotification(parent, parent->document(), AXObjectCache::AXValueChanged, true);
- }
-}
-
-void AccessibilityNodeObject::selectionChanged()
-{
- // When the selection changes, post the notification on the first ancestor that's an
- // ARIA text box, or that's marked as contentEditable, otherwise post the notification
- // on the web area.
- if (isNonNativeTextControl() || isWebArea())
- axObjectCache()->postNotification(this, document(), AXObjectCache::AXSelectedTextChanged, true);
- else
- AccessibilityObject::selectionChanged(); // Calls selectionChanged on parent.
-}
-
-void AccessibilityNodeObject::textChanged()
-{
- // If this element supports ARIA live regions, or is part of a region with an ARIA editable role,
- // then notify the AT of changes.
- AXObjectCache* cache = axObjectCache();
- for (Node* parentNode = node(); parentNode; parentNode = parentNode->parentNode()) {
- AccessibilityObject* parent = cache->get(parentNode);
- if (!parent)
- continue;
-
- if (parent->supportsARIALiveRegion())
- cache->postNotification(parentNode, AXObjectCache::AXLiveRegionChanged, true);
-
- // If this element is an ARIA text box or content editable, post a "value changed" notification on it
- // so that it behaves just like a native input element or textarea.
- if (parent->isNonNativeTextControl())
- cache->postNotification(parentNode, AXObjectCache::AXValueChanged, true);
- }
-}
-
-void AccessibilityNodeObject::updateAccessibilityRole()
-{
- bool ignoredStatus = accessibilityIsIgnored();
- m_role = determineAccessibilityRole();
-
- // The AX hierarchy only needs to be updated if the ignored status of an element has changed.
- if (ignoredStatus != accessibilityIsIgnored())
- childrenChanged();
-}
-
-String AccessibilityNodeObject::alternativeTextForWebArea() const
-{
- // The WebArea description should follow this order:
- // aria-label on the <html>
- // title on the <html>
- // <title> inside the <head> (of it was set through JS)
- // name on the <html>
- // For iframes:
- // aria-label on the <iframe>
- // title on the <iframe>
- // name on the <iframe>
-
- Document* document = this->document();
- if (!document)
- return String();
-
- // Check if the HTML element has an aria-label for the webpage.
- if (Element* documentElement = document->documentElement()) {
- const AtomicString& ariaLabel = documentElement->getAttribute(aria_labelAttr);
- if (!ariaLabel.isEmpty())
- return ariaLabel;
- }
-
- Node* owner = document->ownerElement();
- if (owner) {
- if (owner->hasTagName(frameTag) || owner->hasTagName(iframeTag)) {
- const AtomicString& title = toElement(owner)->getAttribute(titleAttr);
- if (!title.isEmpty())
- return title;
- return toElement(owner)->getNameAttribute();
- }
- if (owner->isHTMLElement())
- return toHTMLElement(owner)->getNameAttribute();
- }
-
- String documentTitle = document->title();
- if (!documentTitle.isEmpty())
- return documentTitle;
-
- owner = document->body();
- if (owner && owner->isHTMLElement())
- return toHTMLElement(owner)->getNameAttribute();
-
- return String();
-}
-
-void AccessibilityNodeObject::alternativeText(Vector<AccessibilityText>& textOrder) const
-{
- if (isWebArea()) {
- String webAreaText = alternativeTextForWebArea();
- if (!webAreaText.isEmpty())
- textOrder.append(AccessibilityText(webAreaText, AlternativeText));
- return;
- }
-
- ariaLabeledByText(textOrder);
-
- const AtomicString& ariaLabel = getAttribute(aria_labelAttr);
- if (!ariaLabel.isEmpty())
- textOrder.append(AccessibilityText(ariaLabel, AlternativeText));
-
- if (isImage() || isInputImage() || isNativeImage() || isCanvas()) {
- // Images should use alt as long as the attribute is present, even if empty.
- // Otherwise, it should fallback to other methods, like the title attribute.
- const AtomicString& alt = getAttribute(altAttr);
- if (!alt.isNull())
- textOrder.append(AccessibilityText(alt, AlternativeText));
- }
-}
-
-void AccessibilityNodeObject::ariaLabeledByText(Vector<AccessibilityText>& textOrder) const
-{
- String ariaLabeledBy = ariaLabeledByAttribute();
- if (!ariaLabeledBy.isEmpty()) {
- Vector<Element*> elements;
- ariaLabeledByElements(elements);
-
- unsigned length = elements.size();
- for (unsigned k = 0; k < length; k++) {
- RefPtr<AccessibilityObject> axElement = axObjectCache()->getOrCreate(elements[k]);
- textOrder.append(AccessibilityText(ariaLabeledBy, AlternativeText, axElement));
- }
- }
-}
-
-void AccessibilityNodeObject::changeValueByPercent(float percentChange)
-{
- float range = maxValueForRange() - minValueForRange();
- float value = valueForRange();
-
- value += range * (percentChange / 100);
- setValue(String::number(value));
-
- axObjectCache()->postNotification(node(), AXObjectCache::AXValueChanged, true);
-}
-
-void AccessibilityNodeObject::helpText(Vector<AccessibilityText>& textOrder) const
-{
- const AtomicString& ariaHelp = getAttribute(aria_helpAttr);
- if (!ariaHelp.isEmpty())
- textOrder.append(AccessibilityText(ariaHelp, HelpText));
-
- String describedBy = ariaDescribedByAttribute();
- if (!describedBy.isEmpty())
- textOrder.append(AccessibilityText(describedBy, SummaryText));
-
- // Add help type text that is derived from ancestors.
- for (Node* curr = node(); curr; curr = curr->parentNode()) {
- const AtomicString& summary = getAttribute(summaryAttr);
- if (!summary.isEmpty())
- textOrder.append(AccessibilityText(summary, SummaryText));
-
- // The title attribute should be used as help text unless it is already being used as descriptive text.
- const AtomicString& title = getAttribute(titleAttr);
- if (!title.isEmpty())
- textOrder.append(AccessibilityText(title, TitleTagText));
-
- // Only take help text from an ancestor element if its a group or an unknown role. If help was
- // added to those kinds of elements, it is likely it was meant for a child element.
- AccessibilityObject* axObj = axObjectCache()->getOrCreate(curr);
- if (!axObj)
- return;
-
- AccessibilityRole role = axObj->roleValue();
- if (role != GroupRole && role != UnknownRole)
- break;
- }
-}
-
-void AccessibilityNodeObject::titleElementText(Vector<AccessibilityText>& textOrder)
-{
- Node* node = this->node();
- if (!node)
- return;
-
- bool isInputTag = node->hasTagName(inputTag);
- if (isInputTag || AccessibilityObject::isARIAInput(ariaRoleAttribute()) || isControl()) {
- HTMLLabelElement* label = labelForElement(toElement(node));
- if (label) {
- AccessibilityObject* labelObject = axObjectCache()->getOrCreate(label);
- textOrder.append(AccessibilityText(label->innerText(), LabelByElementText, labelObject));
- return;
- }
- }
-
- AccessibilityObject* titleUIElement = this->titleUIElement();
- if (titleUIElement)
- textOrder.append(AccessibilityText(String(), LabelByElementText, titleUIElement));
-}
-
-void AccessibilityNodeObject::visibleText(Vector<AccessibilityText>& textOrder) const
-{
- Node* node = this->node();
- if (!node)
- return;
-
- bool isInputTag = node->hasTagName(inputTag);
- if (isInputTag) {
- HTMLInputElement* input = toHTMLInputElement(node);
- if (input->isTextButton()) {
- textOrder.append(AccessibilityText(input->valueWithDefault(), VisibleText));
- return;
- }
- }
-
- // If this node isn't rendered, there's no inner text we can extract from a select element.
- if (!isAccessibilityRenderObject() && node->hasTagName(selectTag))
- return;
-
- bool useTextUnderElement = false;
-
- switch (roleValue()) {
- case PopUpButtonRole:
- // Native popup buttons should not use their button children's text as a title. That value is retrieved through stringValue().
- if (node->hasTagName(selectTag))
- break;
- case ButtonRole:
- case ToggleButtonRole:
- case CheckBoxRole:
- case ListBoxOptionRole:
- case MenuButtonRole:
- case MenuItemRole:
- case RadioButtonRole:
- case TabRole:
- useTextUnderElement = true;
- break;
- default:
- break;
- }
-
- // If it's focusable but it's not content editable or a known control type, then it will appear to
- // the user as a single atomic object, so we should use its text as the default title.
- if (isHeading() || isLink() || isGenericFocusableElement())
- useTextUnderElement = true;
-
- if (useTextUnderElement) {
- String text = textUnderElement();
- if (!text.isEmpty())
- textOrder.append(AccessibilityText(text, ChildrenText));
- }
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityNodeObject.h b/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityNodeObject.h
deleted file mode 100644
index f49413a3cfe..00000000000
--- a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityNodeObject.h
+++ /dev/null
@@ -1,233 +0,0 @@
-/*
- * Copyright (C) 2012, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef AccessibilityNodeObject_h
-#define AccessibilityNodeObject_h
-
-#include "core/accessibility/AccessibilityObject.h"
-#include "core/platform/graphics/LayoutRect.h"
-#include "wtf/Forward.h"
-
-namespace WebCore {
-
-class AXObjectCache;
-class Element;
-class Frame;
-class FrameView;
-class HitTestResult;
-class HTMLAnchorElement;
-class HTMLAreaElement;
-class HTMLElement;
-class HTMLLabelElement;
-class HTMLMapElement;
-class HTMLSelectElement;
-class IntPoint;
-class IntSize;
-class Node;
-class RenderListBox;
-class RenderTextControl;
-class RenderView;
-class VisibleSelection;
-class Widget;
-
-class AccessibilityNodeObject : public AccessibilityObject {
-protected:
- explicit AccessibilityNodeObject(Node*);
-
-public:
- static PassRefPtr<AccessibilityNodeObject> create(Node*);
- virtual ~AccessibilityNodeObject();
-
-protected:
- // Protected data.
- AccessibilityRole m_ariaRole;
- bool m_childrenDirty;
-#ifndef NDEBUG
- bool m_initialized;
-#endif
-
- virtual bool computeAccessibilityIsIgnored() const OVERRIDE;
- virtual AccessibilityRole determineAccessibilityRole();
-
- String accessibilityDescriptionForElements(Vector<Element*> &elements) const;
- void alterSliderValue(bool increase);
- String ariaAccessibilityDescription() const;
- void ariaLabeledByElements(Vector<Element*>& elements) const;
- void changeValueByStep(bool increase);
- AccessibilityRole determineAriaRoleAttribute() const;
- void elementsFromAttribute(Vector<Element*>& elements, const QualifiedName&) const;
- bool hasContentEditableAttributeSet() const;
- bool isDescendantOfBarrenParent() const;
- // This returns true if it's focusable but it's not content editable and it's not a control or ARIA control.
- bool isGenericFocusableElement() const;
- HTMLLabelElement* labelForElement(Element*) const;
- AccessibilityObject* menuButtonForMenu() const;
- Element* menuItemElementForMenu() const;
- Element* mouseButtonListener() const;
- AccessibilityRole remapAriaRoleDueToParent(AccessibilityRole) const;
- bool isNativeCheckboxOrRadio() const;
- void setNode(Node*);
- AccessibilityObject* correspondingControlForLabelElement() const;
- HTMLLabelElement* labelElementContainer() const;
-
- //
- // Overridden from AccessibilityObject.
- //
-
- virtual void init() OVERRIDE;
- virtual void detach() OVERRIDE;
- virtual bool isDetached() const OVERRIDE { return !m_node; }
- virtual bool isAccessibilityNodeObject() const OVERRIDE { return true; }
-
- // Check object role or purpose.
- virtual bool isAnchor() const OVERRIDE;
- virtual bool isControl() const OVERRIDE;
- virtual bool isFieldset() const OVERRIDE;
- virtual bool isHeading() const OVERRIDE;
- virtual bool isHovered() const OVERRIDE;
- virtual bool isImage() const OVERRIDE;
- bool isImageButton() const;
- virtual bool isInputImage() const OVERRIDE;
- virtual bool isLink() const;
- virtual bool isMenu() const OVERRIDE;
- virtual bool isMenuButton() const OVERRIDE;
- virtual bool isMultiSelectable() const OVERRIDE;
- bool isNativeImage() const;
- virtual bool isNativeTextControl() const OVERRIDE;
- virtual bool isNonNativeTextControl() const OVERRIDE;
- virtual bool isPasswordField() const OVERRIDE;
- virtual bool isProgressIndicator() const OVERRIDE;
- virtual bool isSlider() const OVERRIDE;
-
- // Check object state.
- virtual bool isChecked() const OVERRIDE;
- virtual bool isClickable() const OVERRIDE;
- virtual bool isEnabled() const OVERRIDE;
- virtual bool isIndeterminate() const OVERRIDE;
- virtual bool isPressed() const OVERRIDE;
- virtual bool isReadOnly() const OVERRIDE;
- virtual bool isRequired() const OVERRIDE;
-
- // Check whether certain properties can be modified.
- virtual bool canSetFocusAttribute() const OVERRIDE;
- virtual bool canSetValueAttribute() const OVERRIDE;
-
- // Properties of static elements.
- virtual bool canvasHasFallbackContent() const OVERRIDE;
- virtual bool exposesTitleUIElement() const OVERRIDE;
- virtual int headingLevel() const OVERRIDE;
- virtual unsigned hierarchicalLevel() const OVERRIDE;
- virtual String text() const OVERRIDE;
- virtual AccessibilityObject* titleUIElement() const OVERRIDE;
-
- // Properties of interactive elements.
- virtual AccessibilityButtonState checkboxOrRadioValue() const OVERRIDE;
- virtual void colorValue(int& r, int& g, int& b) const OVERRIDE;
- virtual String valueDescription() const OVERRIDE;
- virtual float valueForRange() const OVERRIDE;
- virtual float maxValueForRange() const OVERRIDE;
- virtual float minValueForRange() const OVERRIDE;
- virtual String stringValue() const OVERRIDE;
-
- // ARIA attributes.
- virtual String ariaDescribedByAttribute() const;
- virtual String ariaLabeledByAttribute() const OVERRIDE;
- virtual AccessibilityRole ariaRoleAttribute() const OVERRIDE;
-
- // Accessibility Text.
- virtual void accessibilityText(Vector<AccessibilityText>&) OVERRIDE;
- virtual String textUnderElement() const OVERRIDE;
-
- // Accessibility Text - (To be deprecated).
- virtual String accessibilityDescription() const OVERRIDE;
- virtual String title() const OVERRIDE;
- virtual String helpText() const OVERRIDE;
-
- // Location and click point in frame-relative coordinates.
- virtual LayoutRect elementRect() const OVERRIDE;
-
- // High-level accessibility tree access.
- virtual AccessibilityObject* parentObject() const OVERRIDE;
- virtual AccessibilityObject* parentObjectIfExists() const OVERRIDE;
-
- // Low-level accessibility tree exploration.
- virtual AccessibilityObject* firstChild() const OVERRIDE;
- virtual AccessibilityObject* nextSibling() const OVERRIDE;
- virtual void addChildren() OVERRIDE;
- virtual bool canHaveChildren() const OVERRIDE;
- void addChild(AccessibilityObject*);
- void insertChild(AccessibilityObject*, unsigned index);
-
- // DOM and Render tree access.
- virtual Element* actionElement() const OVERRIDE;
- virtual Element* anchorElement() const OVERRIDE;
- virtual Document* document() const OVERRIDE;
- virtual Node* node() const OVERRIDE { return m_node; }
-
- // Modify or take an action on an object.
- virtual void setFocused(bool) OVERRIDE;
- virtual void increment() OVERRIDE;
- virtual void decrement() OVERRIDE;
-
- // Notifications that this object may have changed.
- virtual void childrenChanged() OVERRIDE;
- virtual void selectionChanged() OVERRIDE;
- virtual void textChanged() OVERRIDE;
- virtual void updateAccessibilityRole() OVERRIDE;
-
-private:
- Node* m_node;
-
- String alternativeTextForWebArea() const;
- void alternativeText(Vector<AccessibilityText>&) const;
- void ariaLabeledByText(Vector<AccessibilityText>&) const;
- void changeValueByPercent(float percentChange);
- void helpText(Vector<AccessibilityText>&) const;
- void titleElementText(Vector<AccessibilityText>&);
- void visibleText(Vector<AccessibilityText>&) const;
- float stepValueForRange() const;
-};
-
-inline AccessibilityNodeObject* toAccessibilityNodeObject(AccessibilityObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isAccessibilityNodeObject());
- return static_cast<AccessibilityNodeObject*>(object);
-}
-
-inline const AccessibilityNodeObject* toAccessibilityNodeObject(const AccessibilityObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isAccessibilityNodeObject());
- return static_cast<const AccessibilityNodeObject*>(object);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toAccessibilityNodeObject(const AccessibilityNodeObject*);
-
-} // namespace WebCore
-
-#endif // AccessibilityNodeObject_h
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityObject.cpp b/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityObject.cpp
deleted file mode 100644
index 64f7800cee3..00000000000
--- a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityObject.cpp
+++ /dev/null
@@ -1,992 +0,0 @@
-/*
- * Copyright (C) 2008, 2009, 2011 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/accessibility/AccessibilityObject.h"
-
-#include "core/accessibility/AXObjectCache.h"
-#include "core/dom/NodeTraversal.h"
-#include "core/dom/UserGestureIndicator.h"
-#include "core/editing/VisibleUnits.h"
-#include "core/editing/htmlediting.h"
-#include "core/page/Frame.h"
-#include "core/platform/LocalizedStrings.h"
-#include "core/rendering/RenderListItem.h"
-#include "core/rendering/RenderTheme.h"
-#include "core/rendering/RenderView.h"
-#include "wtf/StdLibExtras.h"
-#include "wtf/text/WTFString.h"
-
-using namespace std;
-
-namespace WebCore {
-
-using namespace HTMLNames;
-
-typedef HashMap<String, AccessibilityRole, CaseFoldingHash> ARIARoleMap;
-
-struct RoleEntry {
- String ariaRole;
- AccessibilityRole webcoreRole;
-};
-
-static ARIARoleMap* createARIARoleMap()
-{
- const RoleEntry roles[] = {
- { "alert", AlertRole },
- { "alertdialog", AlertDialogRole },
- { "application", ApplicationRole },
- { "article", ArticleRole },
- { "banner", BannerRole },
- { "button", ButtonRole },
- { "checkbox", CheckBoxRole },
- { "complementary", ComplementaryRole },
- { "contentinfo", ContentInfoRole },
- { "dialog", DialogRole },
- { "directory", DirectoryRole },
- { "grid", TableRole },
- { "gridcell", CellRole },
- { "columnheader", ColumnHeaderRole },
- { "combobox", ComboBoxRole },
- { "definition", DefinitionRole },
- { "document", DocumentRole },
- { "rowheader", RowHeaderRole },
- { "group", GroupRole },
- { "heading", HeadingRole },
- { "img", ImageRole },
- { "link", LinkRole },
- { "list", ListRole },
- { "listitem", ListItemRole },
- { "listbox", ListBoxRole },
- { "log", LogRole },
- // "option" isn't here because it may map to different roles depending on the parent element's role
- { "main", MainRole },
- { "marquee", MarqueeRole },
- { "math", MathRole },
- { "menu", MenuRole },
- { "menubar", MenuBarRole },
- { "menuitem", MenuItemRole },
- { "menuitemcheckbox", MenuItemRole },
- { "menuitemradio", MenuItemRole },
- { "note", NoteRole },
- { "navigation", NavigationRole },
- { "option", ListBoxOptionRole },
- { "presentation", PresentationalRole },
- { "progressbar", ProgressIndicatorRole },
- { "radio", RadioButtonRole },
- { "radiogroup", RadioGroupRole },
- { "region", RegionRole },
- { "row", RowRole },
- { "scrollbar", ScrollBarRole },
- { "search", SearchRole },
- { "separator", SplitterRole },
- { "slider", SliderRole },
- { "spinbutton", SpinButtonRole },
- { "status", StatusRole },
- { "tab", TabRole },
- { "tablist", TabListRole },
- { "tabpanel", TabPanelRole },
- { "text", StaticTextRole },
- { "textbox", TextAreaRole },
- { "timer", TimerRole },
- { "toolbar", ToolbarRole },
- { "tooltip", UserInterfaceTooltipRole },
- { "tree", TreeRole },
- { "treegrid", TreeGridRole },
- { "treeitem", TreeItemRole }
- };
- ARIARoleMap* roleMap = new ARIARoleMap;
-
- for (size_t i = 0; i < WTF_ARRAY_LENGTH(roles); ++i)
- roleMap->set(roles[i].ariaRole, roles[i].webcoreRole);
- return roleMap;
-}
-
-AccessibilityObject::AccessibilityObject()
- : m_id(0)
- , m_haveChildren(false)
- , m_role(UnknownRole)
- , m_lastKnownIsIgnoredValue(DefaultBehavior)
- , m_detached(false)
-{
-}
-
-AccessibilityObject::~AccessibilityObject()
-{
- ASSERT(isDetached());
-}
-
-void AccessibilityObject::detach()
-{
- // Clear any children and call detachFromParent on them so that
- // no children are left with dangling pointers to their parent.
- clearChildren();
-
- m_detached = true;
-}
-
-bool AccessibilityObject::isDetached() const
-{
- return m_detached;
-}
-
-AXObjectCache* AccessibilityObject::axObjectCache() const
-{
- Document* doc = document();
- if (doc)
- return doc->axObjectCache();
- return 0;
-}
-
-#if HAVE(ACCESSIBILITY)
-void AccessibilityObject::updateBackingStore()
-{
- // Updating the layout may delete this object.
- if (Document* document = this->document())
- document->updateLayoutIgnorePendingStylesheets();
-}
-#endif
-
-bool AccessibilityObject::isARIATextControl() const
-{
- return ariaRoleAttribute() == TextAreaRole || ariaRoleAttribute() == TextFieldRole;
-}
-
-bool AccessibilityObject::isButton() const
-{
- AccessibilityRole role = roleValue();
-
- return role == ButtonRole || role == PopUpButtonRole || role == ToggleButtonRole;
-}
-
-bool AccessibilityObject::isMenuRelated() const
-{
- switch (roleValue()) {
- case MenuRole:
- case MenuBarRole:
- case MenuButtonRole:
- case MenuItemRole:
- return true;
- default:
- return false;
- }
-}
-
-bool AccessibilityObject::isTextControl() const
-{
- switch (roleValue()) {
- case TextAreaRole:
- case TextFieldRole:
- case ComboBoxRole:
- return true;
- default:
- return false;
- }
-}
-
-bool AccessibilityObject::isClickable() const
-{
- switch (roleValue()) {
- case ButtonRole:
- case CheckBoxRole:
- case ColorWellRole:
- case ComboBoxRole:
- case EditableTextRole:
- case ImageMapLinkRole:
- case LinkRole:
- case ListBoxOptionRole:
- case MenuButtonRole:
- case PopUpButtonRole:
- case RadioButtonRole:
- case TabRole:
- case TextAreaRole:
- case TextFieldRole:
- case ToggleButtonRole:
- return true;
- default:
- return false;
- }
-}
-
-bool AccessibilityObject::isExpanded() const
-{
- if (equalIgnoringCase(getAttribute(aria_expandedAttr), "true"))
- return true;
-
- return false;
-}
-
-bool AccessibilityObject::accessibilityIsIgnored() const
-{
- AXComputedObjectAttributeCache* attributeCache = axObjectCache()->computedObjectAttributeCache();
- if (attributeCache) {
- AccessibilityObjectInclusion ignored = attributeCache->getIgnored(axObjectID());
- switch (ignored) {
- case IgnoreObject:
- return true;
- case IncludeObject:
- return false;
- case DefaultBehavior:
- break;
- }
- }
-
- bool result = computeAccessibilityIsIgnored();
-
- if (attributeCache)
- attributeCache->setIgnored(axObjectID(), result ? IgnoreObject : IncludeObject);
-
- return result;
-}
-
-bool AccessibilityObject::accessibilityIsIgnoredByDefault() const
-{
- return defaultObjectInclusion() == IgnoreObject;
-}
-
-AccessibilityObjectInclusion AccessibilityObject::accessibilityPlatformIncludesObject() const
-{
- if (isMenuListPopup() || isMenuListOption())
- return IncludeObject;
-
- return DefaultBehavior;
-}
-
-AccessibilityObjectInclusion AccessibilityObject::defaultObjectInclusion() const
-{
- if (ariaIsHidden())
- return IgnoreObject;
-
- if (isPresentationalChildOfAriaRole())
- return IgnoreObject;
-
- return accessibilityPlatformIncludesObject();
-}
-
-bool AccessibilityObject::lastKnownIsIgnoredValue()
-{
- if (m_lastKnownIsIgnoredValue == DefaultBehavior)
- m_lastKnownIsIgnoredValue = accessibilityIsIgnored() ? IgnoreObject : IncludeObject;
-
- return m_lastKnownIsIgnoredValue == IgnoreObject;
-}
-
-void AccessibilityObject::setLastKnownIsIgnoredValue(bool isIgnored)
-{
- m_lastKnownIsIgnoredValue = isIgnored ? IgnoreObject : IncludeObject;
-}
-
-// Lacking concrete evidence of orientation, horizontal means width > height. vertical is height > width;
-AccessibilityOrientation AccessibilityObject::orientation() const
-{
- LayoutRect bounds = elementRect();
- if (bounds.size().width() > bounds.size().height())
- return AccessibilityOrientationHorizontal;
- if (bounds.size().height() > bounds.size().width())
- return AccessibilityOrientationVertical;
-
- // A tie goes to horizontal.
- return AccessibilityOrientationHorizontal;
-}
-
-#if HAVE(ACCESSIBILITY)
-String AccessibilityObject::actionVerb() const
-{
- // FIXME: Need to add verbs for select elements.
-
- switch (roleValue()) {
- case ButtonRole:
- case ToggleButtonRole:
- return AXButtonActionVerb();
- case TextFieldRole:
- case TextAreaRole:
- return AXTextFieldActionVerb();
- case RadioButtonRole:
- return AXRadioButtonActionVerb();
- case CheckBoxRole:
- return isChecked() ? AXCheckedCheckBoxActionVerb() : AXUncheckedCheckBoxActionVerb();
- case LinkRole:
- return AXLinkActionVerb();
- case PopUpButtonRole:
- return AXMenuListActionVerb();
- case MenuListPopupRole:
- return AXMenuListPopupActionVerb();
- default:
- return emptyString();
- }
-}
-#endif
-
-AccessibilityButtonState AccessibilityObject::checkboxOrRadioValue() const
-{
- // If this is a real checkbox or radio button, AccessibilityRenderObject will handle.
- // If it's an ARIA checkbox or radio, the aria-checked attribute should be used.
-
- const AtomicString& result = getAttribute(aria_checkedAttr);
- if (equalIgnoringCase(result, "true"))
- return ButtonStateOn;
- if (equalIgnoringCase(result, "mixed"))
- return ButtonStateMixed;
-
- return ButtonStateOff;
-}
-
-const AtomicString& AccessibilityObject::placeholderValue() const
-{
- const AtomicString& placeholder = getAttribute(placeholderAttr);
- if (!placeholder.isEmpty())
- return placeholder;
-
- return nullAtom;
-}
-
-bool AccessibilityObject::ariaIsMultiline() const
-{
- return equalIgnoringCase(getAttribute(aria_multilineAttr), "true");
-}
-
-bool AccessibilityObject::ariaPressedIsPresent() const
-{
- return !getAttribute(aria_pressedAttr).isEmpty();
-}
-
-const AtomicString& AccessibilityObject::invalidStatus() const
-{
- DEFINE_STATIC_LOCAL(const AtomicString, invalidStatusFalse, ("false", AtomicString::ConstructFromLiteral));
-
- // aria-invalid can return false (default), grammer, spelling, or true.
- const AtomicString& ariaInvalid = getAttribute(aria_invalidAttr);
-
- // If empty or not present, it should return false.
- if (ariaInvalid.isEmpty())
- return invalidStatusFalse;
-
- return ariaInvalid;
-}
-
-bool AccessibilityObject::supportsARIAAttributes() const
-{
- return supportsARIALiveRegion()
- || supportsARIADragging()
- || supportsARIADropping()
- || supportsARIAFlowTo()
- || supportsARIAOwns()
- || hasAttribute(aria_labelAttr);
-}
-
-bool AccessibilityObject::supportsRangeValue() const
-{
- return isProgressIndicator()
- || isSlider()
- || isScrollbar()
- || isSpinButton();
-}
-
-void AccessibilityObject::ariaTreeRows(AccessibilityChildrenVector& result)
-{
- AccessibilityChildrenVector axChildren = children();
- unsigned count = axChildren.size();
- for (unsigned k = 0; k < count; ++k) {
- AccessibilityObject* obj = axChildren[k].get();
-
- // Add tree items as the rows.
- if (obj->roleValue() == TreeItemRole)
- result.append(obj);
-
- // Now see if this item also has rows hiding inside of it.
- obj->ariaTreeRows(result);
- }
-}
-
-bool AccessibilityObject::supportsARIALiveRegion() const
-{
- const AtomicString& liveRegion = ariaLiveRegionStatus();
- return equalIgnoringCase(liveRegion, "polite") || equalIgnoringCase(liveRegion, "assertive");
-}
-
-void AccessibilityObject::markCachedElementRectDirty() const
-{
- for (unsigned i = 0; i < m_children.size(); ++i)
- m_children[i].get()->markCachedElementRectDirty();
-}
-
-IntPoint AccessibilityObject::clickPoint()
-{
- LayoutRect rect = elementRect();
- return roundedIntPoint(LayoutPoint(rect.x() + rect.width() / 2, rect.y() + rect.height() / 2));
-}
-
-IntRect AccessibilityObject::boundingBoxForQuads(RenderObject* obj, const Vector<FloatQuad>& quads)
-{
- ASSERT(obj);
- if (!obj)
- return IntRect();
-
- size_t count = quads.size();
- if (!count)
- return IntRect();
-
- IntRect result;
- for (size_t i = 0; i < count; ++i) {
- IntRect r = quads[i].enclosingBoundingBox();
- if (!r.isEmpty()) {
- if (obj->style()->hasAppearance())
- RenderTheme::theme().adjustRepaintRect(obj, r);
- result.unite(r);
- }
- }
- return result;
-}
-
-AccessibilityObject* AccessibilityObject::elementAccessibilityHitTest(const IntPoint& point) const
-{
- // Send the hit test back into the sub-frame if necessary.
- if (isAttachment()) {
- Widget* widget = widgetForAttachmentView();
- // Normalize the point for the widget's bounds.
- if (widget && widget->isFrameView())
- return axObjectCache()->getOrCreate(widget)->accessibilityHitTest(IntPoint(point - widget->frameRect().location()));
- }
-
- // Check if there are any mock elements that need to be handled.
- size_t count = m_children.size();
- for (size_t k = 0; k < count; k++) {
- if (m_children[k]->isMockObject() && m_children[k]->elementRect().contains(point))
- return m_children[k]->elementAccessibilityHitTest(point);
- }
-
- return const_cast<AccessibilityObject*>(this);
-}
-
-#if HAVE(ACCESSIBILITY)
-const AccessibilityObject::AccessibilityChildrenVector& AccessibilityObject::children()
-{
- updateChildrenIfNecessary();
-
- return m_children;
-}
-#endif
-
-AccessibilityObject* AccessibilityObject::parentObjectUnignored() const
-{
- AccessibilityObject* parent;
- for (parent = parentObject(); parent && parent->accessibilityIsIgnored(); parent = parent->parentObject()) {
- }
-
- return parent;
-}
-
-AccessibilityObject* AccessibilityObject::firstAccessibleObjectFromNode(const Node* node)
-{
- if (!node)
- return 0;
-
- AXObjectCache* cache = node->document().axObjectCache();
- AccessibilityObject* accessibleObject = cache->getOrCreate(node->renderer());
- while (accessibleObject && accessibleObject->accessibilityIsIgnored()) {
- node = NodeTraversal::next(node);
-
- while (node && !node->renderer())
- node = NodeTraversal::nextSkippingChildren(node);
-
- if (!node)
- return 0;
-
- accessibleObject = cache->getOrCreate(node->renderer());
- }
-
- return accessibleObject;
-}
-
-void AccessibilityObject::updateChildrenIfNecessary()
-{
- if (!hasChildren())
- addChildren();
-}
-
-void AccessibilityObject::clearChildren()
-{
- // Some objects have weak pointers to their parents and those associations need to be detached.
- size_t length = m_children.size();
- for (size_t i = 0; i < length; i++)
- m_children[i]->detachFromParent();
-
- m_children.clear();
- m_haveChildren = false;
-}
-
-AccessibilityObject* AccessibilityObject::focusedUIElement() const
-{
- Document* doc = document();
- if (!doc)
- return 0;
-
- Page* page = doc->page();
- if (!page)
- return 0;
-
- return AXObjectCache::focusedUIElementForPage(page);
-}
-
-Document* AccessibilityObject::document() const
-{
- FrameView* frameView = documentFrameView();
- if (!frameView)
- return 0;
-
- return frameView->frame().document();
-}
-
-FrameView* AccessibilityObject::documentFrameView() const
-{
- const AccessibilityObject* object = this;
- while (object && !object->isAccessibilityRenderObject())
- object = object->parentObject();
-
- if (!object)
- return 0;
-
- return object->documentFrameView();
-}
-
-Page* AccessibilityObject::page() const
-{
- Document* document = this->document();
- if (!document)
- return 0;
- return document->page();
-}
-
-String AccessibilityObject::language() const
-{
- const AtomicString& lang = getAttribute(langAttr);
- if (!lang.isEmpty())
- return lang;
-
- AccessibilityObject* parent = parentObject();
-
- // as a last resort, fall back to the content language specified in the meta tag
- if (!parent) {
- Document* doc = document();
- if (doc)
- return doc->contentLanguage();
- return nullAtom;
- }
-
- return parent->language();
-}
-
-bool AccessibilityObject::hasAttribute(const QualifiedName& attribute) const
-{
- Node* elementNode = node();
- if (!elementNode)
- return false;
-
- if (!elementNode->isElementNode())
- return false;
-
- Element* element = toElement(elementNode);
- return element->fastHasAttribute(attribute);
-}
-
-const AtomicString& AccessibilityObject::getAttribute(const QualifiedName& attribute) const
-{
- Node* elementNode = node();
- if (!elementNode)
- return nullAtom;
-
- if (!elementNode->isElementNode())
- return nullAtom;
-
- Element* element = toElement(elementNode);
- return element->fastGetAttribute(attribute);
-}
-
-TextIteratorBehavior AccessibilityObject::textIteratorBehaviorForTextRange() const
-{
- return TextIteratorIgnoresStyleVisibility;
-}
-
-bool AccessibilityObject::press() const
-{
- Element* actionElem = actionElement();
- if (!actionElem)
- return false;
- UserGestureIndicator gestureIndicator(DefinitelyProcessingNewUserGesture);
- actionElem->accessKeyAction(true);
- return true;
-}
-
-void AccessibilityObject::scrollToMakeVisible() const
-{
- IntRect objectRect = pixelSnappedIntRect(elementRect());
- objectRect.setLocation(IntPoint());
- scrollToMakeVisibleWithSubFocus(objectRect);
-}
-
-// This is a 1-dimensional scroll offset helper function that's applied
-// separately in the horizontal and vertical directions, because the
-// logic is the same. The goal is to compute the best scroll offset
-// in order to make an object visible within a viewport.
-//
-// In case the whole object cannot fit, you can specify a
-// subfocus - a smaller region within the object that should
-// be prioritized. If the whole object can fit, the subfocus is
-// ignored.
-//
-// Example: the viewport is scrolled to the right just enough
-// that the object is in view.
-// Before:
-// +----------Viewport---------+
-// +---Object---+
-// +--SubFocus--+
-//
-// After:
-// +----------Viewport---------+
-// +---Object---+
-// +--SubFocus--+
-//
-// When constraints cannot be fully satisfied, the min
-// (left/top) position takes precedence over the max (right/bottom).
-//
-// Note that the return value represents the ideal new scroll offset.
-// This may be out of range - the calling function should clip this
-// to the available range.
-static int computeBestScrollOffset(int currentScrollOffset,
- int subfocusMin, int subfocusMax,
- int objectMin, int objectMax,
- int viewportMin, int viewportMax) {
- int viewportSize = viewportMax - viewportMin;
-
- // If the focus size is larger than the viewport size, shrink it in the
- // direction of subfocus.
- if (objectMax - objectMin > viewportSize) {
- // Subfocus must be within focus:
- subfocusMin = std::max(subfocusMin, objectMin);
- subfocusMax = std::min(subfocusMax, objectMax);
-
- // Subfocus must be no larger than the viewport size; favor top/left.
- if (subfocusMax - subfocusMin > viewportSize)
- subfocusMax = subfocusMin + viewportSize;
-
- if (subfocusMin + viewportSize > objectMax)
- objectMin = objectMax - viewportSize;
- else {
- objectMin = subfocusMin;
- objectMax = subfocusMin + viewportSize;
- }
- }
-
- // Exit now if the focus is already within the viewport.
- if (objectMin - currentScrollOffset >= viewportMin
- && objectMax - currentScrollOffset <= viewportMax)
- return currentScrollOffset;
-
- // Scroll left if we're too far to the right.
- if (objectMax - currentScrollOffset > viewportMax)
- return objectMax - viewportMax;
-
- // Scroll right if we're too far to the left.
- if (objectMin - currentScrollOffset < viewportMin)
- return objectMin - viewportMin;
-
- ASSERT_NOT_REACHED();
-
- // This shouldn't happen.
- return currentScrollOffset;
-}
-
-void AccessibilityObject::scrollToMakeVisibleWithSubFocus(const IntRect& subfocus) const
-{
- // Search up the parent chain until we find the first one that's scrollable.
- AccessibilityObject* scrollParent = parentObject();
- ScrollableArea* scrollableArea;
- for (scrollableArea = 0;
- scrollParent && !(scrollableArea = scrollParent->getScrollableAreaIfScrollable());
- scrollParent = scrollParent->parentObject()) { }
- if (!scrollableArea)
- return;
-
- LayoutRect objectRect = elementRect();
- IntPoint scrollPosition = scrollableArea->scrollPosition();
- IntRect scrollVisibleRect = scrollableArea->visibleContentRect();
-
- int desiredX = computeBestScrollOffset(
- scrollPosition.x(),
- objectRect.x() + subfocus.x(), objectRect.x() + subfocus.maxX(),
- objectRect.x(), objectRect.maxX(),
- 0, scrollVisibleRect.width());
- int desiredY = computeBestScrollOffset(
- scrollPosition.y(),
- objectRect.y() + subfocus.y(), objectRect.y() + subfocus.maxY(),
- objectRect.y(), objectRect.maxY(),
- 0, scrollVisibleRect.height());
-
- scrollParent->scrollTo(IntPoint(desiredX, desiredY));
-
- // Recursively make sure the scroll parent itself is visible.
- if (scrollParent->parentObject())
- scrollParent->scrollToMakeVisible();
-}
-
-void AccessibilityObject::scrollToGlobalPoint(const IntPoint& globalPoint) const
-{
- // Search up the parent chain and create a vector of all scrollable parent objects
- // and ending with this object itself.
- Vector<const AccessibilityObject*> objects;
- AccessibilityObject* parentObject;
- for (parentObject = this->parentObject(); parentObject; parentObject = parentObject->parentObject()) {
- if (parentObject->getScrollableAreaIfScrollable())
- objects.prepend(parentObject);
- }
- objects.append(this);
-
- // Start with the outermost scrollable (the main window) and try to scroll the
- // next innermost object to the given point.
- int offsetX = 0, offsetY = 0;
- IntPoint point = globalPoint;
- size_t levels = objects.size() - 1;
- for (size_t i = 0; i < levels; i++) {
- const AccessibilityObject* outer = objects[i];
- const AccessibilityObject* inner = objects[i + 1];
-
- ScrollableArea* scrollableArea = outer->getScrollableAreaIfScrollable();
-
- LayoutRect innerRect = inner->isAccessibilityScrollView() ? inner->parentObject()->elementRect() : inner->elementRect();
- LayoutRect objectRect = innerRect;
- IntPoint scrollPosition = scrollableArea->scrollPosition();
-
- // Convert the object rect into local coordinates.
- objectRect.move(offsetX, offsetY);
- if (!outer->isAccessibilityScrollView())
- objectRect.move(scrollPosition.x(), scrollPosition.y());
-
- int desiredX = computeBestScrollOffset(
- 0,
- objectRect.x(), objectRect.maxX(),
- objectRect.x(), objectRect.maxX(),
- point.x(), point.x());
- int desiredY = computeBestScrollOffset(
- 0,
- objectRect.y(), objectRect.maxY(),
- objectRect.y(), objectRect.maxY(),
- point.y(), point.y());
- outer->scrollTo(IntPoint(desiredX, desiredY));
-
- if (outer->isAccessibilityScrollView() && !inner->isAccessibilityScrollView()) {
- // If outer object we just scrolled is a scroll view (main window or iframe) but the
- // inner object is not, keep track of the coordinate transformation to apply to
- // future nested calculations.
- scrollPosition = scrollableArea->scrollPosition();
- offsetX -= (scrollPosition.x() + point.x());
- offsetY -= (scrollPosition.y() + point.y());
- point.move(scrollPosition.x() - innerRect.x(),
- scrollPosition.y() - innerRect.y());
- } else if (inner->isAccessibilityScrollView()) {
- // Otherwise, if the inner object is a scroll view, reset the coordinate transformation.
- offsetX = 0;
- offsetY = 0;
- }
- }
-}
-
-void AccessibilityObject::notifyIfIgnoredValueChanged()
-{
- bool isIgnored = accessibilityIsIgnored();
- if (lastKnownIsIgnoredValue() != isIgnored) {
- axObjectCache()->childrenChanged(parentObject());
- setLastKnownIsIgnoredValue(isIgnored);
- }
-}
-
-void AccessibilityObject::selectionChanged()
-{
- if (AccessibilityObject* parent = parentObjectIfExists())
- parent->selectionChanged();
-}
-
-static VisiblePosition startOfStyleRange(const VisiblePosition& visiblePos)
-{
- RenderObject* renderer = visiblePos.deepEquivalent().deprecatedNode()->renderer();
- RenderObject* startRenderer = renderer;
- RenderStyle* style = renderer->style();
-
- // traverse backward by renderer to look for style change
- for (RenderObject* r = renderer->previousInPreOrder(); r; r = r->previousInPreOrder()) {
- // skip non-leaf nodes
- if (r->firstChild())
- continue;
-
- // stop at style change
- if (r->style() != style)
- break;
-
- // remember match
- startRenderer = r;
- }
-
- return firstPositionInOrBeforeNode(startRenderer->node());
-}
-
-static VisiblePosition endOfStyleRange(const VisiblePosition& visiblePos)
-{
- RenderObject* renderer = visiblePos.deepEquivalent().deprecatedNode()->renderer();
- RenderObject* endRenderer = renderer;
- RenderStyle* style = renderer->style();
-
- // traverse forward by renderer to look for style change
- for (RenderObject* r = renderer->nextInPreOrder(); r; r = r->nextInPreOrder()) {
- // skip non-leaf nodes
- if (r->firstChild())
- continue;
-
- // stop at style change
- if (r->style() != style)
- break;
-
- // remember match
- endRenderer = r;
- }
-
- return lastPositionInOrAfterNode(endRenderer->node());
-}
-
-static bool replacedNodeNeedsCharacter(Node* replacedNode)
-{
- // we should always be given a rendered node and a replaced node, but be safe
- // replaced nodes are either attachments (widgets) or images
- if (!replacedNode || !replacedNode->renderer() || !replacedNode->renderer()->isReplaced() || replacedNode->isTextNode())
- return false;
-
- // create an AX object, but skip it if it is not supposed to be seen
- AccessibilityObject* object = replacedNode->renderer()->document().axObjectCache()->getOrCreate(replacedNode);
- if (object->accessibilityIsIgnored())
- return false;
-
- return true;
-}
-
-#if HAVE(ACCESSIBILITY)
-int AccessibilityObject::lineForPosition(const VisiblePosition& visiblePos) const
-{
- if (visiblePos.isNull() || !node())
- return -1;
-
- // If the position is not in the same editable region as this AX object, return -1.
- Node* containerNode = visiblePos.deepEquivalent().containerNode();
- if (!containerNode->containsIncludingShadowDOM(node()) && !node()->containsIncludingShadowDOM(containerNode))
- return -1;
-
- int lineCount = -1;
- VisiblePosition currentVisiblePos = visiblePos;
- VisiblePosition savedVisiblePos;
-
- // move up until we get to the top
- // FIXME: This only takes us to the top of the rootEditableElement, not the top of the
- // top document.
- do {
- savedVisiblePos = currentVisiblePos;
- VisiblePosition prevVisiblePos = previousLinePosition(currentVisiblePos, 0, HasEditableAXRole);
- currentVisiblePos = prevVisiblePos;
- ++lineCount;
- } while (currentVisiblePos.isNotNull() && !(inSameLine(currentVisiblePos, savedVisiblePos)));
-
- return lineCount;
-}
-#endif
-
-// Finds a RenderListItem parent give a node.
-static RenderListItem* renderListItemContainerForNode(Node* node)
-{
- for (; node; node = node->parentNode()) {
- RenderBoxModelObject* renderer = node->renderBoxModelObject();
- if (renderer && renderer->isListItem())
- return toRenderListItem(renderer);
- }
- return 0;
-}
-
-bool AccessibilityObject::isARIAControl(AccessibilityRole ariaRole)
-{
- return isARIAInput(ariaRole) || ariaRole == TextAreaRole || ariaRole == ButtonRole
- || ariaRole == ComboBoxRole || ariaRole == SliderRole;
-}
-
-bool AccessibilityObject::isARIAInput(AccessibilityRole ariaRole)
-{
- return ariaRole == RadioButtonRole || ariaRole == CheckBoxRole || ariaRole == TextFieldRole;
-}
-
-AccessibilityRole AccessibilityObject::ariaRoleToWebCoreRole(const String& value)
-{
- ASSERT(!value.isEmpty());
-
- static const ARIARoleMap* roleMap = createARIARoleMap();
-
- Vector<String> roleVector;
- value.split(' ', roleVector);
- AccessibilityRole role = UnknownRole;
- unsigned size = roleVector.size();
- for (unsigned i = 0; i < size; ++i) {
- String roleName = roleVector[i];
- role = roleMap->get(roleName);
- if (role)
- return role;
- }
-
- return role;
-}
-
-AccessibilityRole AccessibilityObject::buttonRoleType() const
-{
- // If aria-pressed is present, then it should be exposed as a toggle button.
- // http://www.w3.org/TR/wai-aria/states_and_properties#aria-pressed
- if (ariaPressedIsPresent())
- return ToggleButtonRole;
- if (ariaHasPopup())
- return PopUpButtonRole;
- // We don't contemplate RadioButtonRole, as it depends on the input
- // type.
-
- return ButtonRole;
-}
-
-bool AccessibilityObject::ariaIsHidden() const
-{
- if (equalIgnoringCase(getAttribute(aria_hiddenAttr), "true"))
- return true;
-
- for (AccessibilityObject* object = parentObject(); object; object = object->parentObject()) {
- if (equalIgnoringCase(object->getAttribute(aria_hiddenAttr), "true"))
- return true;
- }
-
- return false;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityObject.h b/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityObject.h
deleted file mode 100644
index 72bc24e5d8f..00000000000
--- a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityObject.h
+++ /dev/null
@@ -1,594 +0,0 @@
-/*
- * Copyright (C) 2008, 2009, 2011 Apple Inc. All rights reserved.
- * Copyright (C) 2008 Nuanti Ltd.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef AccessibilityObject_h
-#define AccessibilityObject_h
-
-#include "core/editing/TextIterator.h"
-#include "core/editing/VisiblePosition.h"
-#include "core/platform/graphics/FloatQuad.h"
-#include "core/platform/graphics/LayoutRect.h"
-#include "wtf/Forward.h"
-#include "wtf/RefPtr.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-class AccessibilityObject;
-class AXObjectCache;
-class Element;
-class Frame;
-class FrameView;
-class HTMLAnchorElement;
-class HTMLAreaElement;
-class IntPoint;
-class IntSize;
-class Node;
-class Page;
-class RenderObject;
-class RenderListItem;
-class ScrollableArea;
-class VisibleSelection;
-class Widget;
-
-typedef unsigned AXID;
-
-enum AccessibilityRole {
- AlertDialogRole = 1,
- AlertRole,
- AnnotationRole,
- ApplicationRole,
- ArticleRole,
- BannerRole,
- BrowserRole,
- BusyIndicatorRole,
- ButtonRole,
- CanvasRole,
- CellRole,
- CheckBoxRole,
- ColorWellRole,
- ColumnHeaderRole,
- ColumnRole,
- ComboBoxRole,
- ComplementaryRole,
- ContentInfoRole,
- DefinitionRole,
- DescriptionListDetailRole,
- DescriptionListTermRole,
- DialogRole,
- DirectoryRole,
- DisclosureTriangleRole,
- DivRole,
- DocumentRole,
- DrawerRole,
- EditableTextRole,
- FooterRole,
- FormRole,
- GridRole,
- GroupRole,
- GrowAreaRole,
- HeadingRole,
- HelpTagRole,
- HorizontalRuleRole,
- IgnoredRole,
- ImageMapLinkRole,
- ImageMapRole,
- ImageRole,
- IncrementorRole,
- LabelRole,
- LegendRole,
- LinkRole,
- ListBoxOptionRole,
- ListBoxRole,
- ListItemRole,
- ListMarkerRole,
- ListRole,
- LogRole,
- MainRole,
- MarqueeRole,
- MathElementRole,
- MathRole,
- MatteRole,
- MenuBarRole,
- MenuButtonRole,
- MenuItemRole,
- MenuListOptionRole,
- MenuListPopupRole,
- MenuRole,
- NavigationRole,
- NoteRole,
- OutlineRole,
- ParagraphRole,
- PopUpButtonRole,
- PresentationalRole,
- ProgressIndicatorRole,
- RadioButtonRole,
- RadioGroupRole,
- RegionRole,
- RootWebAreaRole,
- RowHeaderRole,
- RowRole,
- RulerMarkerRole,
- RulerRole,
- SVGRootRole,
- ScrollAreaRole,
- ScrollBarRole,
- SeamlessWebAreaRole,
- SearchRole,
- SheetRole,
- SliderRole,
- SliderThumbRole,
- SpinButtonPartRole,
- SpinButtonRole,
- SplitGroupRole,
- SplitterRole,
- StaticTextRole,
- StatusRole,
- SystemWideRole,
- TabGroupRole,
- TabListRole,
- TabPanelRole,
- TabRole,
- TableHeaderContainerRole,
- TableRole,
- TextAreaRole,
- TextFieldRole,
- TimerRole,
- ToggleButtonRole,
- ToolbarRole,
- TreeGridRole,
- TreeItemRole,
- TreeRole,
- UnknownRole,
- UserInterfaceTooltipRole,
- ValueIndicatorRole,
- WebAreaRole,
- WindowRole,
-};
-
-enum AccessibilityTextSource {
- AlternativeText,
- ChildrenText,
- SummaryText,
- HelpText,
- VisibleText,
- TitleTagText,
- PlaceholderText,
- LabelByElementText,
-};
-
-enum AccessibilityState {
- AXBusyState,
- AXCheckedState,
- AXCollapsedState,
- AXEnabledState,
- AXExpandedState,
- AXFocusableState,
- AXFocusedState,
- AXHaspopupState,
- AXHoveredState,
- AXIndeterminateState,
- AXInvisibleState,
- AXLinkedState,
- AXMultiselectableState,
- AXOffscreenState,
- AXPressedState,
- AXProtectedState,
- AXReadonlyState,
- AXRequiredState,
- AXSelectableState,
- AXSelectedState,
- AXVerticalState,
- AXVisitedState
-};
-
-struct AccessibilityText {
- String text;
- AccessibilityTextSource textSource;
- RefPtr<AccessibilityObject> textElement;
-
- AccessibilityText(const String& t, const AccessibilityTextSource& s)
- : text(t)
- , textSource(s)
- { }
-
- AccessibilityText(const String& t, const AccessibilityTextSource& s, const RefPtr<AccessibilityObject> element)
- : text(t)
- , textSource(s)
- , textElement(element)
- { }
-};
-
-enum AccessibilityOrientation {
- AccessibilityOrientationVertical,
- AccessibilityOrientationHorizontal,
-};
-
-enum AccessibilityObjectInclusion {
- IncludeObject,
- IgnoreObject,
- DefaultBehavior,
-};
-
-enum AccessibilityButtonState {
- ButtonStateOff = 0,
- ButtonStateOn,
- ButtonStateMixed,
-};
-
-struct VisiblePositionRange {
-
- VisiblePosition start;
- VisiblePosition end;
-
- VisiblePositionRange() {}
-
- VisiblePositionRange(const VisiblePosition& s, const VisiblePosition& e)
- : start(s)
- , end(e)
- { }
-
- bool isNull() const { return start.isNull() || end.isNull(); }
-};
-
-struct PlainTextRange {
-
- unsigned start;
- unsigned length;
-
- PlainTextRange()
- : start(0)
- , length(0)
- { }
-
- PlainTextRange(unsigned s, unsigned l)
- : start(s)
- , length(l)
- { }
-
- bool isNull() const { return !start && !length; }
-};
-
-class AccessibilityObject : public RefCounted<AccessibilityObject> {
-public:
- typedef Vector<RefPtr<AccessibilityObject> > AccessibilityChildrenVector;
-
-protected:
- AccessibilityObject();
-
-public:
- virtual ~AccessibilityObject();
-
- // After constructing an AccessibilityObject, it must be given a
- // unique ID, then added to AXObjectCache, and finally init() must
- // be called last.
- void setAXObjectID(AXID axObjectID) { m_id = axObjectID; }
- virtual void init() { }
-
- // When the corresponding WebCore object that this AccessibilityObject
- // wraps is deleted, it must be detached.
- virtual void detach();
- virtual bool isDetached() const;
-
- // The AXObjectCache that owns this object, and its unique ID within this cache.
- AXObjectCache* axObjectCache() const;
- AXID axObjectID() const { return m_id; }
-
- // Lays out the page so that the accessibility tree is based on up-to-date information.
- void updateBackingStore();
-
- // Determine subclass type.
- virtual bool isAccessibilityNodeObject() const { return false; }
- virtual bool isAccessibilityRenderObject() const { return false; }
- virtual bool isAccessibilityScrollbar() const { return false; }
- virtual bool isAccessibilityScrollView() const { return false; }
- virtual bool isAccessibilitySVGRoot() const { return false; }
-
- // Check object role or purpose.
- virtual AccessibilityRole roleValue() const { return m_role; }
- bool isARIATextControl() const;
- virtual bool isARIATreeGridRow() const { return false; }
- virtual bool isAccessibilityTable() const { return false; }
- virtual bool isAnchor() const { return false; }
- virtual bool isAttachment() const { return false; }
- bool isButton() const;
- bool isCanvas() const { return roleValue() == CanvasRole; }
- bool isCheckbox() const { return roleValue() == CheckBoxRole; }
- bool isCheckboxOrRadio() const { return isCheckbox() || isRadioButton(); }
- bool isColorWell() const { return roleValue() == ColorWellRole; }
- bool isComboBox() const { return roleValue() == ComboBoxRole; }
- virtual bool isControl() const { return false; }
- virtual bool isDataTable() const { return false; }
- virtual bool isFieldset() const { return false; }
- virtual bool isFileUploadButton() const { return false; }
- virtual bool isHeading() const { return false; }
- virtual bool isImage() const { return false; }
- virtual bool isImageMapLink() const { return false; }
- virtual bool isInputImage() const { return false; }
- virtual bool isLink() const { return false; }
- virtual bool isList() const { return false; }
- bool isListItem() const { return roleValue() == ListItemRole; }
- virtual bool isMenu() const { return false; }
- virtual bool isMenuButton() const { return false; }
- virtual bool isMenuList() const { return false; }
- virtual bool isMenuListOption() const { return false; }
- virtual bool isMenuListPopup() const { return false; }
- bool isMenuRelated() const;
- virtual bool isMockObject() const { return false; }
- virtual bool isNativeSpinButton() const { return false; }
- virtual bool isNativeTextControl() const { return false; } // input or textarea
- virtual bool isNonNativeTextControl() const { return false; } // contenteditable or role=textbox
- virtual bool isPasswordField() const { return false; }
- virtual bool isProgressIndicator() const { return false; }
- bool isRadioButton() const { return roleValue() == RadioButtonRole; }
- bool isScrollbar() const { return roleValue() == ScrollBarRole; }
- bool isSeamlessWebArea() const { return roleValue() == SeamlessWebAreaRole; }
- virtual bool isSlider() const { return false; }
- virtual bool isSpinButton() const { return roleValue() == SpinButtonRole; }
- virtual bool isSpinButtonPart() const { return false; }
- bool isTabItem() const { return roleValue() == TabRole; }
- virtual bool isTableCell() const { return false; }
- virtual bool isTableRow() const { return false; }
- bool isTextControl() const;
- bool isTree() const { return roleValue() == TreeRole; }
- bool isTreeItem() const { return roleValue() == TreeItemRole; }
- bool isWebArea() const { return roleValue() == WebAreaRole; }
-
- // Check object state.
- virtual bool isChecked() const { return false; }
- virtual bool isClickable() const;
- virtual bool isCollapsed() const { return false; }
- virtual bool isEnabled() const { return false; }
- bool isExpanded() const;
- virtual bool isFocused() const { return false; }
- virtual bool isHovered() const { return false; }
- virtual bool isIndeterminate() const { return false; }
- virtual bool isLinked() const { return false; }
- virtual bool isLoaded() const { return false; }
- virtual bool isMultiSelectable() const { return false; }
- virtual bool isOffScreen() const { return false; }
- virtual bool isPressed() const { return false; }
- virtual bool isReadOnly() const { return false; }
- virtual bool isRequired() const { return false; }
- virtual bool isSelected() const { return false; }
- virtual bool isSelectedOptionActive() const { return false; }
- virtual bool isVisible() const { return true; }
- virtual bool isVisited() const { return false; }
-
- // Check whether certain properties can be modified.
- virtual bool canSetFocusAttribute() const { return false; }
- virtual bool canSetValueAttribute() const { return false; }
- virtual bool canSetSelectedAttribute() const { return false; }
- virtual bool canSetSelectedChildrenAttribute() const { return false; }
-
- // Whether objects are ignored, i.e. not included in the tree.
- bool accessibilityIsIgnored() const;
- bool accessibilityIsIgnoredByDefault() const;
- AccessibilityObjectInclusion accessibilityPlatformIncludesObject() const;
- virtual AccessibilityObjectInclusion defaultObjectInclusion() const;
- bool lastKnownIsIgnoredValue();
- void setLastKnownIsIgnoredValue(bool);
-
- // Properties of static elements.
- virtual const AtomicString& accessKey() const { return nullAtom; }
- virtual bool canvasHasFallbackContent() const { return false; }
- virtual bool exposesTitleUIElement() const { return true; }
- virtual int headingLevel() const { return 0; }
- // 1-based, to match the aria-level spec.
- virtual unsigned hierarchicalLevel() const { return 0; }
- virtual AccessibilityOrientation orientation() const;
- virtual int tableLevel() const { return 0; }
- virtual String text() const { return String(); }
- virtual int textLength() const { return 0; }
- virtual AccessibilityObject* titleUIElement() const { return 0; }
- virtual KURL url() const { return KURL(); }
-
- // Properties of interactive elements.
- virtual String actionVerb() const;
- virtual AccessibilityButtonState checkboxOrRadioValue() const;
- virtual void colorValue(int& r, int& g, int& b) const { r = 0; g = 0; b = 0; }
- virtual String valueDescription() const { return String(); }
- virtual float valueForRange() const { return 0.0f; }
- virtual float maxValueForRange() const { return 0.0f; }
- virtual float minValueForRange() const { return 0.0f; }
- const AtomicString& placeholderValue() const;
- virtual void selectedChildren(AccessibilityChildrenVector&) { }
- virtual String stringValue() const { return String(); }
-
- // ARIA attributes.
- virtual AccessibilityObject* activeDescendant() const { return 0; }
- virtual String ariaDescribedByAttribute() const { return String(); }
- virtual void ariaFlowToElements(AccessibilityChildrenVector&) const { }
- virtual bool ariaHasPopup() const { return false; }
- bool ariaIsMultiline() const;
- virtual String ariaLabeledByAttribute() const { return String(); }
- bool ariaPressedIsPresent() const;
- virtual AccessibilityRole ariaRoleAttribute() const { return UnknownRole; }
- virtual bool ariaRoleHasPresentationalChildren() const { return false; }
- const AtomicString& invalidStatus() const;
- virtual bool isARIAGrabbed() { return false; }
- virtual bool isPresentationalChildOfAriaRole() const { return false; }
- virtual bool shouldFocusActiveDescendant() const { return false; }
- bool supportsARIAAttributes() const;
- virtual bool supportsARIADragging() const { return false; }
- virtual bool supportsARIADropping() const { return false; }
- virtual bool supportsARIAFlowTo() const { return false; }
- virtual bool supportsARIAOwns() const { return false; }
- bool supportsRangeValue() const;
-
- // ARIA trees.
- // Used by an ARIA tree to get all its rows.
- void ariaTreeRows(AccessibilityChildrenVector&);
-
- // ARIA live-region features.
- bool supportsARIALiveRegion() const;
- virtual const AtomicString& ariaLiveRegionStatus() const { return nullAtom; }
- virtual const AtomicString& ariaLiveRegionRelevant() const { return nullAtom; }
- virtual bool ariaLiveRegionAtomic() const { return false; }
- virtual bool ariaLiveRegionBusy() const { return false; }
-
- // Accessibility Text.
- virtual void accessibilityText(Vector<AccessibilityText>&) { };
- virtual String textUnderElement() const { return String(); }
-
- // Accessibility Text - (To be deprecated).
- virtual String accessibilityDescription() const { return String(); }
- virtual String title() const { return String(); }
- virtual String helpText() const { return String(); }
-
- // Location and click point in frame-relative coordinates.
- virtual LayoutRect elementRect() const { return m_explicitElementRect; }
- void setElementRect(LayoutRect r) { m_explicitElementRect = r; }
- virtual void markCachedElementRectDirty() const;
- virtual IntPoint clickPoint();
-
- // Hit testing.
- // Called on the root AX object to return the deepest available element.
- virtual AccessibilityObject* accessibilityHitTest(const IntPoint&) const { return 0; }
- // Called on the AX object after the render tree determines which is the right AccessibilityRenderObject.
- virtual AccessibilityObject* elementAccessibilityHitTest(const IntPoint&) const;
-
- // High-level accessibility tree access. Other modules should only use these functions.
- const AccessibilityChildrenVector& children();
- virtual AccessibilityObject* parentObject() const = 0;
- AccessibilityObject* parentObjectUnignored() const;
- virtual AccessibilityObject* parentObjectIfExists() const { return 0; }
-
- // Low-level accessibility tree exploration, only for use within the accessibility module.
- virtual AccessibilityObject* firstChild() const { return 0; }
- virtual AccessibilityObject* nextSibling() const { return 0; }
- static AccessibilityObject* firstAccessibleObjectFromNode(const Node*);
- virtual void addChildren() { }
- virtual bool canHaveChildren() const { return true; }
- bool hasChildren() const { return m_haveChildren; }
- virtual void updateChildrenIfNecessary();
- virtual void setNeedsToUpdateChildren() { }
- virtual void clearChildren();
- virtual void detachFromParent() { }
- virtual AccessibilityObject* observableObject() const { return 0; }
- virtual AccessibilityObject* scrollBar(AccessibilityOrientation) { return 0; }
-
- // Properties of the object's owning document or page.
- virtual double estimatedLoadingProgress() const { return 0; }
- AccessibilityObject* focusedUIElement() const;
-
- // DOM and Render tree access.
- virtual Node* node() const { return 0; }
- virtual RenderObject* renderer() const { return 0; }
- virtual Document* document() const;
- virtual FrameView* documentFrameView() const;
- virtual Element* anchorElement() const { return 0; }
- virtual Element* actionElement() const { return 0; }
- virtual Widget* widgetForAttachmentView() const { return 0; }
- Page* page() const;
- String language() const;
- bool hasAttribute(const QualifiedName&) const;
- const AtomicString& getAttribute(const QualifiedName&) const;
-
- // Selected text.
- TextIteratorBehavior textIteratorBehaviorForTextRange() const;
- virtual PlainTextRange selectedTextRange() const { return PlainTextRange(); }
- unsigned selectionStart() const { return selectedTextRange().start; }
- unsigned selectionEnd() const { return selectedTextRange().length; }
- virtual String selectedText() const { return String(); }
-
- // Modify or take an action on an object.
- virtual void increment() { }
- virtual void decrement() { }
- bool performDefaultAction() const { return press(); }
- virtual bool press() const;
- // Make this object visible by scrolling as many nested scrollable views as needed.
- void scrollToMakeVisible() const;
- // Same, but if the whole object can't be made visible, try for this subrect, in local coordinates.
- void scrollToMakeVisibleWithSubFocus(const IntRect&) const;
- // Scroll this object to a given point in global coordinates of the top-level window.
- void scrollToGlobalPoint(const IntPoint&) const;
- virtual void setFocused(bool) { }
- virtual void setSelected(bool) { }
- void setSelectedText(const String&) { }
- virtual void setSelectedTextRange(const PlainTextRange&) { }
- virtual void setValue(const String&) { }
- virtual void setValue(float) { }
-
- // Notifications that this object may have changed.
- virtual void childrenChanged() { }
- virtual void handleActiveDescendantChanged() { }
- virtual void handleAriaExpandedChanged() { }
- void notifyIfIgnoredValueChanged();
- virtual void selectionChanged();
- virtual void textChanged() { }
- virtual void updateAccessibilityRole() { }
-
- // Text metrics. Most of these should be deprecated, needs major cleanup.
- virtual VisiblePositionRange visiblePositionRange() const { return VisiblePositionRange(); }
- virtual IntRect boundsForVisiblePositionRange(const VisiblePositionRange&) const { return IntRect(); }
- virtual VisiblePosition visiblePositionForIndex(int) const { return VisiblePosition(); }
- int lineForPosition(const VisiblePosition&) const;
- virtual int index(const VisiblePosition&) const { return -1; }
- virtual void lineBreaks(Vector<int>&) const { }
-
- // Static helper functions.
- static bool isARIAControl(AccessibilityRole);
- static bool isARIAInput(AccessibilityRole);
- static AccessibilityRole ariaRoleToWebCoreRole(const String&);
- static IntRect boundingBoxForQuads(RenderObject*, const Vector<FloatQuad>&);
-
-protected:
- AXID m_id;
- AccessibilityChildrenVector m_children;
- mutable bool m_haveChildren;
- AccessibilityRole m_role;
- AccessibilityObjectInclusion m_lastKnownIsIgnoredValue;
- LayoutRect m_explicitElementRect;
-
- virtual bool computeAccessibilityIsIgnored() const { return true; }
-
- // If this object itself scrolls, return its ScrollableArea.
- virtual ScrollableArea* getScrollableAreaIfScrollable() const { return 0; }
- virtual void scrollTo(const IntPoint&) const { }
-
- AccessibilityRole buttonRoleType() const;
- bool ariaIsHidden() const;
-
- bool allowsTextRanges() const { return isTextControl(); }
- unsigned getLengthForTextRange() const { return text().length(); }
-
- bool m_detached;
-};
-
-#if !HAVE(ACCESSIBILITY)
-inline const AccessibilityObject::AccessibilityChildrenVector& AccessibilityObject::children() { return m_children; }
-inline String AccessibilityObject::actionVerb() const { return emptyString(); }
-inline int AccessibilityObject::lineForPosition(const VisiblePosition&) const { return -1; }
-inline void AccessibilityObject::updateBackingStore() { }
-#endif
-
-} // namespace WebCore
-
-#endif // AccessibilityObject_h
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityProgressIndicator.cpp b/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityProgressIndicator.cpp
deleted file mode 100644
index 04ed2189b16..00000000000
--- a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityProgressIndicator.cpp
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#include "config.h"
-#include "core/accessibility/AccessibilityProgressIndicator.h"
-
-#include "core/html/HTMLProgressElement.h"
-#include "core/platform/FloatConversion.h"
-#include "core/rendering/RenderProgress.h"
-
-namespace WebCore {
-
-using namespace HTMLNames;
-
-AccessibilityProgressIndicator::AccessibilityProgressIndicator(RenderProgress* renderer)
- : AccessibilityRenderObject(renderer)
-{
-}
-
-PassRefPtr<AccessibilityProgressIndicator> AccessibilityProgressIndicator::create(RenderProgress* renderer)
-{
- return adoptRef(new AccessibilityProgressIndicator(renderer));
-}
-
-bool AccessibilityProgressIndicator::computeAccessibilityIsIgnored() const
-{
- return accessibilityIsIgnoredByDefault();
-}
-
-float AccessibilityProgressIndicator::valueForRange() const
-{
- if (hasAttribute(aria_valuenowAttr))
- return getAttribute(aria_valuenowAttr).toFloat();
-
- if (element()->position() >= 0)
- return narrowPrecisionToFloat(element()->value());
- // Indeterminate progress bar should return 0.
- return 0.0f;
-}
-
-float AccessibilityProgressIndicator::maxValueForRange() const
-{
- if (hasAttribute(aria_valuemaxAttr))
- return getAttribute(aria_valuemaxAttr).toFloat();
-
- return narrowPrecisionToFloat(element()->max());
-}
-
-float AccessibilityProgressIndicator::minValueForRange() const
-{
- if (hasAttribute(aria_valueminAttr))
- return getAttribute(aria_valueminAttr).toFloat();
-
- return 0.0f;
-}
-
-HTMLProgressElement* AccessibilityProgressIndicator::element() const
-{
- return toRenderProgress(m_renderer)->progressElement();
-}
-
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityProgressIndicator.h b/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityProgressIndicator.h
deleted file mode 100644
index e8ecce5117b..00000000000
--- a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityProgressIndicator.h
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#ifndef AccessibilityProgressIndicator_h
-#define AccessibilityProgressIndicator_h
-
-#include "core/accessibility/AccessibilityRenderObject.h"
-
-namespace WebCore {
-
-class HTMLProgressElement;
-class RenderProgress;
-
-class AccessibilityProgressIndicator : public AccessibilityRenderObject {
-public:
- static PassRefPtr<AccessibilityProgressIndicator> create(RenderProgress*);
-
-private:
- virtual AccessibilityRole roleValue() const { return ProgressIndicatorRole; }
-
- virtual bool isProgressIndicator() const OVERRIDE { return true; }
-
- virtual float valueForRange() const OVERRIDE;
- virtual float maxValueForRange() const OVERRIDE;
- virtual float minValueForRange() const OVERRIDE;
-
- explicit AccessibilityProgressIndicator(RenderProgress*);
-
- HTMLProgressElement* element() const;
- virtual bool computeAccessibilityIsIgnored() const OVERRIDE;
-};
-
-
-} // namespace WebCore
-
-#endif // AccessibilityProgressIndicator_h
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityRenderObject.cpp b/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityRenderObject.cpp
deleted file mode 100644
index e70aaf1d761..00000000000
--- a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityRenderObject.cpp
+++ /dev/null
@@ -1,2384 +0,0 @@
-/*
-* Copyright (C) 2008 Apple Inc. All rights reserved.
-*
-* Redistribution and use in source and binary forms, with or without
-* modification, are permitted provided that the following conditions
-* are met:
-*
-* 1. Redistributions of source code must retain the above copyright
-* notice, this list of conditions and the following disclaimer.
-* 2. Redistributions in binary form must reproduce the above copyright
-* notice, this list of conditions and the following disclaimer in the
-* documentation and/or other materials provided with the distribution.
-* 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
-* its contributors may be used to endorse or promote products derived
-* from this software without specific prior written permission.
-*
-* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
-* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
-* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
-* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
-* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
-* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
-* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-*/
-
-#include "config.h"
-#include "core/accessibility/AccessibilityRenderObject.h"
-
-#include "bindings/v8/ExceptionStatePlaceholder.h"
-#include "core/accessibility/AXObjectCache.h"
-#include "core/accessibility/AccessibilityImageMapLink.h"
-#include "core/accessibility/AccessibilitySVGRoot.h"
-#include "core/accessibility/AccessibilitySpinButton.h"
-#include "core/accessibility/AccessibilityTable.h"
-#include "core/dom/ElementTraversal.h"
-#include "core/dom/shadow/ShadowRoot.h"
-#include "core/editing/FrameSelection.h"
-#include "core/editing/RenderedPosition.h"
-#include "core/editing/VisibleUnits.h"
-#include "core/editing/htmlediting.h"
-#include "core/html/HTMLHtmlElement.h"
-#include "core/html/HTMLImageElement.h"
-#include "core/html/HTMLLabelElement.h"
-#include "core/html/HTMLOptionElement.h"
-#include "core/html/HTMLSelectElement.h"
-#include "core/html/HTMLTextAreaElement.h"
-#include "core/html/shadow/ShadowElementNames.h"
-#include "core/loader/ProgressTracker.h"
-#include "core/page/Frame.h"
-#include "core/page/Page.h"
-#include "core/platform/LocalizedStrings.h"
-#include "core/rendering/HitTestResult.h"
-#include "core/rendering/RenderFileUploadControl.h"
-#include "core/rendering/RenderHTMLCanvas.h"
-#include "core/rendering/RenderImage.h"
-#include "core/rendering/RenderInline.h"
-#include "core/rendering/RenderLayer.h"
-#include "core/rendering/RenderListMarker.h"
-#include "core/rendering/RenderMenuList.h"
-#include "core/rendering/RenderTextControlSingleLine.h"
-#include "core/rendering/RenderTextFragment.h"
-#include "core/rendering/RenderView.h"
-#include "core/rendering/RenderWidget.h"
-#include "core/svg/SVGDocument.h"
-#include "core/svg/SVGSVGElement.h"
-#include "core/svg/graphics/SVGImage.h"
-#include "wtf/StdLibExtras.h"
-
-using namespace std;
-
-namespace WebCore {
-
-using namespace HTMLNames;
-
-static inline RenderObject* firstChildInContinuation(RenderObject* renderer)
-{
- RenderObject* r = toRenderInline(renderer)->continuation();
-
- while (r) {
- if (r->isRenderBlock())
- return r;
- if (RenderObject* child = r->firstChild())
- return child;
- r = toRenderInline(r)->continuation();
- }
-
- return 0;
-}
-
-static inline bool isInlineWithContinuation(RenderObject* object)
-{
- if (!object->isBoxModelObject())
- return false;
-
- RenderBoxModelObject* renderer = toRenderBoxModelObject(object);
- if (!renderer->isRenderInline())
- return false;
-
- return toRenderInline(renderer)->continuation();
-}
-
-static inline RenderObject* firstChildConsideringContinuation(RenderObject* renderer)
-{
- RenderObject* firstChild = renderer->firstChild();
-
- if (!firstChild && isInlineWithContinuation(renderer))
- firstChild = firstChildInContinuation(renderer);
-
- return firstChild;
-}
-
-static inline RenderInline* startOfContinuations(RenderObject* r)
-{
- if (r->isInlineElementContinuation()) {
- return toRenderInline(r->node()->renderer());
- }
-
- // Blocks with a previous continuation always have a next continuation
- if (r->isRenderBlock() && toRenderBlock(r)->inlineElementContinuation())
- return toRenderInline(toRenderBlock(r)->inlineElementContinuation()->node()->renderer());
-
- return 0;
-}
-
-static inline RenderObject* endOfContinuations(RenderObject* renderer)
-{
- RenderObject* prev = renderer;
- RenderObject* cur = renderer;
-
- if (!cur->isRenderInline() && !cur->isRenderBlock())
- return renderer;
-
- while (cur) {
- prev = cur;
- if (cur->isRenderInline()) {
- cur = toRenderInline(cur)->inlineElementContinuation();
- ASSERT(cur || !toRenderInline(prev)->continuation());
- } else
- cur = toRenderBlock(cur)->inlineElementContinuation();
- }
-
- return prev;
-}
-
-static inline RenderObject* childBeforeConsideringContinuations(RenderInline* r, RenderObject* child)
-{
- RenderBoxModelObject* curContainer = r;
- RenderObject* cur = 0;
- RenderObject* prev = 0;
-
- while (curContainer) {
- if (curContainer->isRenderInline()) {
- cur = curContainer->firstChild();
- while (cur) {
- if (cur == child)
- return prev;
- prev = cur;
- cur = cur->nextSibling();
- }
-
- curContainer = toRenderInline(curContainer)->continuation();
- } else if (curContainer->isRenderBlock()) {
- if (curContainer == child)
- return prev;
-
- prev = curContainer;
- curContainer = toRenderBlock(curContainer)->inlineElementContinuation();
- }
- }
-
- ASSERT_NOT_REACHED();
-
- return 0;
-}
-
-static inline bool firstChildIsInlineContinuation(RenderObject* renderer)
-{
- return renderer->firstChild() && renderer->firstChild()->isInlineElementContinuation();
-}
-
-static inline bool lastChildHasContinuation(RenderObject* renderer)
-{
- return renderer->lastChild() && isInlineWithContinuation(renderer->lastChild());
-}
-
-static RenderBoxModelObject* nextContinuation(RenderObject* renderer)
-{
- ASSERT(renderer);
- if (renderer->isRenderInline() && !renderer->isReplaced())
- return toRenderInline(renderer)->continuation();
- if (renderer->isRenderBlock())
- return toRenderBlock(renderer)->inlineElementContinuation();
- return 0;
-}
-
-AccessibilityRenderObject::AccessibilityRenderObject(RenderObject* renderer)
- : AccessibilityNodeObject(renderer->node())
- , m_renderer(renderer)
- , m_cachedElementRectDirty(true)
-{
-#ifndef NDEBUG
- m_renderer->setHasAXObject(true);
-#endif
-}
-
-PassRefPtr<AccessibilityRenderObject> AccessibilityRenderObject::create(RenderObject* renderer)
-{
- return adoptRef(new AccessibilityRenderObject(renderer));
-}
-
-AccessibilityRenderObject::~AccessibilityRenderObject()
-{
- ASSERT(isDetached());
-}
-
-LayoutRect AccessibilityRenderObject::elementRect() const
-{
- if (!m_explicitElementRect.isEmpty())
- return m_explicitElementRect;
- if (!m_renderer)
- return LayoutRect();
- if (!m_renderer->isBox())
- return computeElementRect();
-
- for (const AccessibilityObject* obj = this; obj; obj = obj->parentObject()) {
- if (obj->isAccessibilityRenderObject())
- toAccessibilityRenderObject(obj)->checkCachedElementRect();
- }
- for (const AccessibilityObject* obj = this; obj; obj = obj->parentObject()) {
- if (obj->isAccessibilityRenderObject())
- toAccessibilityRenderObject(obj)->updateCachedElementRect();
- }
-
- return m_cachedElementRect;
-}
-
-void AccessibilityRenderObject::setRenderer(RenderObject* renderer)
-{
- m_renderer = renderer;
- setNode(renderer->node());
-}
-
-RenderBoxModelObject* AccessibilityRenderObject::renderBoxModelObject() const
-{
- if (!m_renderer || !m_renderer->isBoxModelObject())
- return 0;
- return toRenderBoxModelObject(m_renderer);
-}
-
-RenderView* AccessibilityRenderObject::topRenderer() const
-{
- Document* topDoc = topDocument();
- if (!topDoc)
- return 0;
-
- return topDoc->renderView();
-}
-
-Document* AccessibilityRenderObject::topDocument() const
-{
- if (!document())
- return 0;
- return document()->topDocument();
-}
-
-bool AccessibilityRenderObject::shouldNotifyActiveDescendant() const
-{
- // We want to notify that the combo box has changed its active descendant,
- // but we do not want to change the focus, because focus should remain with the combo box.
- if (isComboBox())
- return true;
-
- return shouldFocusActiveDescendant();
-}
-
-ScrollableArea* AccessibilityRenderObject::getScrollableAreaIfScrollable() const
-{
- // If the parent is a scroll view, then this object isn't really scrollable, the parent ScrollView should handle the scrolling.
- if (parentObject() && parentObject()->isAccessibilityScrollView())
- return 0;
-
- if (!m_renderer || !m_renderer->isBox())
- return 0;
-
- RenderBox* box = toRenderBox(m_renderer);
- if (!box->canBeScrolledAndHasScrollableArea())
- return 0;
-
- return box->scrollableArea();
-}
-
-AccessibilityRole AccessibilityRenderObject::determineAccessibilityRole()
-{
- if (!m_renderer)
- return UnknownRole;
-
- m_ariaRole = determineAriaRoleAttribute();
-
- Node* node = m_renderer->node();
- AccessibilityRole ariaRole = ariaRoleAttribute();
- if (ariaRole != UnknownRole)
- return ariaRole;
-
- RenderBoxModelObject* cssBox = renderBoxModelObject();
-
- if (node && node->isLink()) {
- if (cssBox && cssBox->isImage())
- return ImageMapRole;
- return LinkRole;
- }
- if (cssBox && cssBox->isListItem())
- return ListItemRole;
- if (m_renderer->isListMarker())
- return ListMarkerRole;
- if (node && node->hasTagName(buttonTag))
- return buttonRoleType();
- if (node && node->hasTagName(legendTag))
- return LegendRole;
- if (m_renderer->isText())
- return StaticTextRole;
- if (cssBox && cssBox->isImage()) {
- if (node && node->hasTagName(inputTag))
- return ariaHasPopup() ? PopUpButtonRole : ButtonRole;
- if (isSVGImage())
- return SVGRootRole;
- return ImageRole;
- }
-
- // Note: if JavaScript is disabled, the renderer won't be a RenderHTMLCanvas.
- if (node && node->hasTagName(canvasTag) && m_renderer->isCanvas())
- return CanvasRole;
-
- if (cssBox && cssBox->isRenderView()) {
- // If the iframe is seamless, it should not be announced as a web area to AT clients.
- if (document() && document()->shouldDisplaySeamlesslyWithParent())
- return SeamlessWebAreaRole;
- return WebAreaRole;
- }
-
- if (cssBox && cssBox->isTextField())
- return TextFieldRole;
-
- if (cssBox && cssBox->isTextArea())
- return TextAreaRole;
-
- if (node && node->hasTagName(inputTag)) {
- HTMLInputElement* input = toHTMLInputElement(node);
- if (input->isCheckbox())
- return CheckBoxRole;
- if (input->isRadioButton())
- return RadioButtonRole;
- if (input->isTextButton())
- return buttonRoleType();
-
- const AtomicString& type = input->getAttribute(typeAttr);
- if (equalIgnoringCase(type, "color"))
- return ColorWellRole;
- }
-
- if (isFileUploadButton())
- return ButtonRole;
-
- if (cssBox && cssBox->isMenuList())
- return PopUpButtonRole;
-
- if (headingLevel())
- return HeadingRole;
-
- if (m_renderer->isSVGImage())
- return ImageRole;
- if (m_renderer->isSVGRoot())
- return SVGRootRole;
-
- if (node && node->hasTagName(ddTag))
- return DescriptionListDetailRole;
-
- if (node && node->hasTagName(dtTag))
- return DescriptionListTermRole;
-
- if (node && (node->hasTagName(rpTag) || node->hasTagName(rtTag)))
- return AnnotationRole;
-
- // Table sections should be ignored.
- if (m_renderer->isTableSection())
- return IgnoredRole;
-
- if (m_renderer->isHR())
- return HorizontalRuleRole;
-
- if (node && node->hasTagName(pTag))
- return ParagraphRole;
-
- if (node && isHTMLLabelElement(node))
- return LabelRole;
-
- if (node && node->hasTagName(divTag))
- return DivRole;
-
- if (node && node->hasTagName(formTag))
- return FormRole;
-
- if (node && node->hasTagName(articleTag))
- return ArticleRole;
-
- if (node && node->hasTagName(mainTag))
- return MainRole;
-
- if (node && node->hasTagName(navTag))
- return NavigationRole;
-
- if (node && node->hasTagName(asideTag))
- return ComplementaryRole;
-
- if (node && node->hasTagName(sectionTag))
- return RegionRole;
-
- if (node && node->hasTagName(addressTag))
- return ContentInfoRole;
-
- if (node && node->hasTagName(dialogTag))
- return DialogRole;
-
- // The HTML element should not be exposed as an element. That's what the RenderView element does.
- if (node && isHTMLHtmlElement(node))
- return IgnoredRole;
-
- // There should only be one banner/contentInfo per page. If header/footer are being used within an article or section
- // then it should not be exposed as whole page's banner/contentInfo
- if (node && node->hasTagName(headerTag) && !isDescendantOfElementType(articleTag) && !isDescendantOfElementType(sectionTag))
- return BannerRole;
- if (node && node->hasTagName(footerTag) && !isDescendantOfElementType(articleTag) && !isDescendantOfElementType(sectionTag))
- return FooterRole;
-
- if (node && node->hasTagName(aTag) && isClickable())
- return LinkRole;
-
- if (m_renderer->isRenderBlockFlow())
- return GroupRole;
-
- // If the element does not have role, but it has ARIA attributes, accessibility should fallback to exposing it as a group.
- if (supportsARIAAttributes())
- return GroupRole;
-
- return UnknownRole;
-}
-
-void AccessibilityRenderObject::init()
-{
- AccessibilityNodeObject::init();
-}
-
-void AccessibilityRenderObject::detach()
-{
- AccessibilityNodeObject::detach();
-
- detachRemoteSVGRoot();
-
-#ifndef NDEBUG
- if (m_renderer)
- m_renderer->setHasAXObject(false);
-#endif
- m_renderer = 0;
-}
-
-//
-// Check object role or purpose.
-//
-
-bool AccessibilityRenderObject::isAttachment() const
-{
- RenderBoxModelObject* renderer = renderBoxModelObject();
- if (!renderer)
- return false;
- // Widgets are the replaced elements that we represent to AX as attachments
- bool isWidget = renderer->isWidget();
- ASSERT(!isWidget || (renderer->isReplaced() && !isImage()));
- return isWidget;
-}
-
-bool AccessibilityRenderObject::isFileUploadButton() const
-{
- if (m_renderer && m_renderer->node() && m_renderer->node()->hasTagName(inputTag)) {
- HTMLInputElement* input = toHTMLInputElement(m_renderer->node());
- return input->isFileUpload();
- }
-
- return false;
-}
-
-static bool isLinkable(const AccessibilityObject& object)
-{
- if (!object.renderer())
- return false;
-
- // See https://wiki.mozilla.org/Accessibility/AT-Windows-API for the elements
- // Mozilla considers linkable.
- return object.isLink() || object.isImage() || object.renderer()->isText();
-}
-
-bool AccessibilityRenderObject::isLinked() const
-{
- if (!isLinkable(*this))
- return false;
-
- Element* anchor = anchorElement();
- if (!anchor || !isHTMLAnchorElement(anchor))
- return false;
-
- return !toHTMLAnchorElement(anchor)->href().isEmpty();
-}
-
-bool AccessibilityRenderObject::isLoaded() const
-{
- return !m_renderer->document().parser();
-}
-
-bool AccessibilityRenderObject::isOffScreen() const
-{
- ASSERT(m_renderer);
- IntRect contentRect = pixelSnappedIntRect(m_renderer->absoluteClippedOverflowRect());
- FrameView* view = m_renderer->frame()->view();
- IntRect viewRect = view->visibleContentRect();
- viewRect.intersect(contentRect);
- return viewRect.isEmpty();
-}
-
-bool AccessibilityRenderObject::isReadOnly() const
-{
- ASSERT(m_renderer);
-
- if (isWebArea()) {
- Document& document = m_renderer->document();
- HTMLElement* body = document.body();
- if (body && body->rendererIsEditable())
- return false;
-
- return !document.rendererIsEditable();
- }
-
- return AccessibilityNodeObject::isReadOnly();
-}
-
-bool AccessibilityRenderObject::isVisited() const
-{
- // FIXME: Is it a privacy violation to expose visited information to accessibility APIs?
- return m_renderer->style()->isLink() && m_renderer->style()->insideLink() == InsideVisitedLink;
-}
-
-//
-// Check object state.
-//
-
-bool AccessibilityRenderObject::isFocused() const
-{
- if (!m_renderer)
- return false;
-
- Document& document = m_renderer->document();
- Element* focusedElement = document.focusedElement();
- if (!focusedElement)
- return false;
-
- // A web area is represented by the Document node in the DOM tree, which isn't focusable.
- // Check instead if the frame's selection controller is focused
- if (focusedElement == m_renderer->node()
- || (roleValue() == WebAreaRole && document.frame()->selection().isFocusedAndActive()))
- return true;
-
- return false;
-}
-
-bool AccessibilityRenderObject::isSelected() const
-{
- if (!m_renderer)
- return false;
-
- Node* node = m_renderer->node();
- if (!node)
- return false;
-
- const AtomicString& ariaSelected = getAttribute(aria_selectedAttr);
- if (equalIgnoringCase(ariaSelected, "true"))
- return true;
-
- if (isTabItem() && isTabItemSelected())
- return true;
-
- return false;
-}
-
-//
-// Whether objects are ignored, i.e. not included in the tree.
-//
-
-AccessibilityObjectInclusion AccessibilityRenderObject::defaultObjectInclusion() const
-{
- // The following cases can apply to any element that's a subclass of AccessibilityRenderObject.
-
- if (!m_renderer)
- return IgnoreObject;
-
- if (m_renderer->style()->visibility() != VISIBLE) {
- // aria-hidden is meant to override visibility as the determinant in AX hierarchy inclusion.
- if (equalIgnoringCase(getAttribute(aria_hiddenAttr), "false"))
- return DefaultBehavior;
-
- return IgnoreObject;
- }
-
- return AccessibilityObject::defaultObjectInclusion();
-}
-
-bool AccessibilityRenderObject::computeAccessibilityIsIgnored() const
-{
-#ifndef NDEBUG
- ASSERT(m_initialized);
-#endif
-
- // Check first if any of the common reasons cause this element to be ignored.
- // Then process other use cases that need to be applied to all the various roles
- // that AccessibilityRenderObjects take on.
- AccessibilityObjectInclusion decision = defaultObjectInclusion();
- if (decision == IncludeObject)
- return false;
- if (decision == IgnoreObject)
- return true;
-
- // If this element is within a parent that cannot have children, it should not be exposed.
- if (isDescendantOfBarrenParent())
- return true;
-
- if (roleValue() == IgnoredRole)
- return true;
-
- if (roleValue() == PresentationalRole || inheritsPresentationalRole())
- return true;
-
- // An ARIA tree can only have tree items and static text as children.
- if (!isAllowedChildOfTree())
- return true;
-
- // TODO: we should refactor this - but right now this is necessary to make
- // sure scroll areas stay in the tree.
- if (isAttachment())
- return false;
-
- // ignore popup menu items because AppKit does
- for (RenderObject* parent = m_renderer->parent(); parent; parent = parent->parent()) {
- if (parent->isBoxModelObject() && toRenderBoxModelObject(parent)->isMenuList())
- return true;
- }
-
- // find out if this element is inside of a label element.
- // if so, it may be ignored because it's the label for a checkbox or radio button
- AccessibilityObject* controlObject = correspondingControlForLabelElement();
- if (controlObject && !controlObject->exposesTitleUIElement() && controlObject->isCheckboxOrRadio())
- return true;
-
- // NOTE: BRs always have text boxes now, so the text box check here can be removed
- if (m_renderer->isText()) {
- // static text beneath MenuItems and MenuButtons are just reported along with the menu item, so it's ignored on an individual level
- AccessibilityObject* parent = parentObjectUnignored();
- if (parent && (parent->ariaRoleAttribute() == MenuItemRole || parent->ariaRoleAttribute() == MenuButtonRole))
- return true;
- RenderText* renderText = toRenderText(m_renderer);
- if (m_renderer->isBR() || !renderText->firstTextBox())
- return true;
-
- // static text beneath TextControls is reported along with the text control text so it's ignored.
- for (AccessibilityObject* parent = parentObject(); parent; parent = parent->parentObject()) {
- if (parent->roleValue() == TextFieldRole)
- return true;
- }
-
- // text elements that are just empty whitespace should not be returned
- return renderText->text().impl()->containsOnlyWhitespace();
- }
-
- if (isHeading())
- return false;
-
- if (isLink())
- return false;
-
- // all controls are accessible
- if (isControl())
- return false;
-
- if (ariaRoleAttribute() != UnknownRole)
- return false;
-
- // don't ignore labels, because they serve as TitleUIElements
- Node* node = m_renderer->node();
- if (node && isHTMLLabelElement(node))
- return false;
-
- // Anything that is content editable should not be ignored.
- // However, one cannot just call node->rendererIsEditable() since that will ask if its parents
- // are also editable. Only the top level content editable region should be exposed.
- if (hasContentEditableAttributeSet())
- return false;
-
- // List items play an important role in defining the structure of lists. They should not be ignored.
- if (roleValue() == ListItemRole)
- return false;
-
- // if this element has aria attributes on it, it should not be ignored.
- if (supportsARIAAttributes())
- return false;
-
- // <span> tags are inline tags and not meant to convey information if they have no other aria
- // information on them. If we don't ignore them, they may emit signals expected to come from
- // their parent. In addition, because included spans are GroupRole objects, and GroupRole
- // objects are often containers with meaningful information, the inclusion of a span can have
- // the side effect of causing the immediate parent accessible to be ignored. This is especially
- // problematic for platforms which have distinct roles for textual block elements.
- if (node && node->hasTagName(spanTag))
- return true;
-
- if (m_renderer->isRenderBlockFlow() && m_renderer->childrenInline() && !canSetFocusAttribute())
- return !toRenderBlock(m_renderer)->firstLineBox() && !mouseButtonListener();
-
- // ignore images seemingly used as spacers
- if (isImage()) {
-
- // If the image can take focus, it should not be ignored, lest the user not be able to interact with something important.
- if (canSetFocusAttribute())
- return false;
-
- if (node && node->isElementNode()) {
- Element* elt = toElement(node);
- const AtomicString& alt = elt->getAttribute(altAttr);
- // don't ignore an image that has an alt tag
- if (!alt.string().containsOnlyWhitespace())
- return false;
- // informal standard is to ignore images with zero-length alt strings
- if (!alt.isNull())
- return true;
- }
-
- if (isNativeImage() && m_renderer->isImage()) {
- // check for one-dimensional image
- RenderImage* image = toRenderImage(m_renderer);
- if (image->height() <= 1 || image->width() <= 1)
- return true;
-
- // check whether rendered image was stretched from one-dimensional file image
- if (image->cachedImage()) {
- LayoutSize imageSize = image->cachedImage()->imageSizeForRenderer(m_renderer, image->view()->zoomFactor());
- return imageSize.height() <= 1 || imageSize.width() <= 1;
- }
- }
- return false;
- }
-
- if (isCanvas()) {
- if (canvasHasFallbackContent())
- return false;
- RenderHTMLCanvas* canvas = toRenderHTMLCanvas(m_renderer);
- if (canvas->height() <= 1 || canvas->width() <= 1)
- return true;
- // Otherwise fall through; use presence of help text, title, or description to decide.
- }
-
- if (isWebArea() || isSeamlessWebArea() || m_renderer->isListMarker())
- return false;
-
- // Using the help text, title or accessibility description (so we
- // check if there's some kind of accessible name for the element)
- // to decide an element's visibility is not as definitive as
- // previous checks, so this should remain as one of the last.
- //
- // These checks are simplified in the interest of execution speed;
- // for example, any element having an alt attribute will make it
- // not ignored, rather than just images.
- if (!getAttribute(aria_helpAttr).isEmpty() || !getAttribute(aria_describedbyAttr).isEmpty() || !getAttribute(altAttr).isEmpty() || !getAttribute(titleAttr).isEmpty())
- return false;
-
- // Don't ignore generic focusable elements like <div tabindex=0>
- // unless they're completely empty, with no children.
- if (isGenericFocusableElement() && node->firstChild())
- return false;
-
- if (!ariaAccessibilityDescription().isEmpty())
- return false;
-
- // By default, objects should be ignored so that the AX hierarchy is not
- // filled with unnecessary items.
- return true;
-}
-
-//
-// Properties of static elements.
-//
-
-const AtomicString& AccessibilityRenderObject::accessKey() const
-{
- Node* node = m_renderer->node();
- if (!node)
- return nullAtom;
- if (!node->isElementNode())
- return nullAtom;
- return toElement(node)->getAttribute(accesskeyAttr);
-}
-
-AccessibilityOrientation AccessibilityRenderObject::orientation() const
-{
- const AtomicString& ariaOrientation = getAttribute(aria_orientationAttr);
- if (equalIgnoringCase(ariaOrientation, "horizontal"))
- return AccessibilityOrientationHorizontal;
- if (equalIgnoringCase(ariaOrientation, "vertical"))
- return AccessibilityOrientationVertical;
-
- return AccessibilityObject::orientation();
-}
-
-String AccessibilityRenderObject::text() const
-{
- if (isPasswordField())
- return String();
-
- return AccessibilityNodeObject::text();
-}
-
-int AccessibilityRenderObject::textLength() const
-{
- ASSERT(isTextControl());
-
- if (isPasswordField())
- return -1; // need to return something distinct from 0
-
- return text().length();
-}
-
-KURL AccessibilityRenderObject::url() const
-{
- if (isAnchor() && isHTMLAnchorElement(m_renderer->node())) {
- if (HTMLAnchorElement* anchor = toHTMLAnchorElement(anchorElement()))
- return anchor->href();
- }
-
- if (isWebArea())
- return m_renderer->document().url();
-
- if (isImage() && m_renderer->node() && m_renderer->node()->hasTagName(imgTag))
- return toHTMLImageElement(m_renderer->node())->src();
-
- if (isInputImage())
- return toHTMLInputElement(m_renderer->node())->src();
-
- return KURL();
-}
-
-//
-// Properties of interactive elements.
-//
-
-String AccessibilityRenderObject::actionVerb() const
-{
- switch (roleValue()) {
- case ButtonRole:
- case ToggleButtonRole:
- return AXButtonActionVerb();
- case TextFieldRole:
- case TextAreaRole:
- return AXTextFieldActionVerb();
- case RadioButtonRole:
- return AXRadioButtonActionVerb();
- case CheckBoxRole:
- return isChecked() ? AXCheckedCheckBoxActionVerb() : AXUncheckedCheckBoxActionVerb();
- case LinkRole:
- return AXLinkActionVerb();
- default:
- return emptyString();
- }
-}
-
-void AccessibilityRenderObject::selectedChildren(AccessibilityChildrenVector& result)
-{
- ASSERT(result.isEmpty());
-
- // only listboxes should be asked for their selected children.
- AccessibilityRole role = roleValue();
- if (role == ListBoxRole) // native list boxes would be AccessibilityListBoxes, so only check for aria list boxes
- ariaListboxSelectedChildren(result);
- else if (role == TreeRole || role == TreeGridRole || role == TableRole)
- ariaSelectedRows(result);
-}
-
-String AccessibilityRenderObject::stringValue() const
-{
- if (!m_renderer)
- return String();
-
- if (isPasswordField())
- return String();
-
- RenderBoxModelObject* cssBox = renderBoxModelObject();
-
- if (ariaRoleAttribute() == StaticTextRole) {
- String staticText = text();
- if (!staticText.length())
- staticText = textUnderElement();
- return staticText;
- }
-
- if (m_renderer->isText())
- return textUnderElement();
-
- if (cssBox && cssBox->isMenuList()) {
- // RenderMenuList will go straight to the text() of its selected item.
- // This has to be overridden in the case where the selected item has an ARIA label.
- HTMLSelectElement* selectElement = toHTMLSelectElement(m_renderer->node());
- int selectedIndex = selectElement->selectedIndex();
- const Vector<HTMLElement*> listItems = selectElement->listItems();
- if (selectedIndex >= 0 && static_cast<size_t>(selectedIndex) < listItems.size()) {
- const AtomicString& overriddenDescription = listItems[selectedIndex]->fastGetAttribute(aria_labelAttr);
- if (!overriddenDescription.isNull())
- return overriddenDescription;
- }
- return toRenderMenuList(m_renderer)->text();
- }
-
- if (m_renderer->isListMarker())
- return toRenderListMarker(m_renderer)->text();
-
- if (isWebArea()) {
- // FIXME: Why would a renderer exist when the Document isn't attached to a frame?
- if (m_renderer->frame())
- return String();
-
- ASSERT_NOT_REACHED();
- }
-
- if (isTextControl())
- return text();
-
- if (m_renderer->isFileUploadControl())
- return toRenderFileUploadControl(m_renderer)->fileTextValue();
-
- // FIXME: We might need to implement a value here for more types
- // FIXME: It would be better not to advertise a value at all for the types for which we don't implement one;
- // this would require subclassing or making accessibilityAttributeNames do something other than return a
- // single static array.
- return String();
-}
-
-//
-// ARIA attributes.
-//
-
-AccessibilityObject* AccessibilityRenderObject::activeDescendant() const
-{
- if (!m_renderer)
- return 0;
-
- if (m_renderer->node() && !m_renderer->node()->isElementNode())
- return 0;
- Element* element = toElement(m_renderer->node());
-
- const AtomicString& activeDescendantAttrStr = element->getAttribute(aria_activedescendantAttr);
- if (activeDescendantAttrStr.isNull() || activeDescendantAttrStr.isEmpty())
- return 0;
-
- Element* target = element->treeScope().getElementById(activeDescendantAttrStr);
- if (!target)
- return 0;
-
- AccessibilityObject* obj = axObjectCache()->getOrCreate(target);
- if (obj && obj->isAccessibilityRenderObject())
- // an activedescendant is only useful if it has a renderer, because that's what's needed to post the notification
- return obj;
- return 0;
-}
-
-void AccessibilityRenderObject::ariaFlowToElements(AccessibilityChildrenVector& flowTo) const
-{
- Vector<Element*> elements;
- elementsFromAttribute(elements, aria_flowtoAttr);
-
- AXObjectCache* cache = axObjectCache();
- unsigned count = elements.size();
- for (unsigned k = 0; k < count; ++k) {
- Element* element = elements[k];
- AccessibilityObject* flowToElement = cache->getOrCreate(element);
- if (flowToElement)
- flowTo.append(flowToElement);
- }
-}
-
-bool AccessibilityRenderObject::ariaHasPopup() const
-{
- return elementAttributeValue(aria_haspopupAttr);
-}
-
-bool AccessibilityRenderObject::ariaRoleHasPresentationalChildren() const
-{
- switch (m_ariaRole) {
- case ButtonRole:
- case SliderRole:
- case ImageRole:
- case ProgressIndicatorRole:
- case SpinButtonRole:
- // case SeparatorRole:
- return true;
- default:
- return false;
- }
-}
-
-bool AccessibilityRenderObject::isPresentationalChildOfAriaRole() const
-{
- // Walk the parent chain looking for a parent that has presentational children
- AccessibilityObject* parent;
- for (parent = parentObject(); parent && !parent->ariaRoleHasPresentationalChildren(); parent = parent->parentObject())
- { }
-
- return parent;
-}
-
-bool AccessibilityRenderObject::shouldFocusActiveDescendant() const
-{
- switch (ariaRoleAttribute()) {
- case GroupRole:
- case ListBoxRole:
- case MenuRole:
- case MenuBarRole:
- case RadioGroupRole:
- case RowRole:
- case PopUpButtonRole:
- case ProgressIndicatorRole:
- case ToolbarRole:
- case OutlineRole:
- case TreeRole:
- case GridRole:
- /* FIXME: replace these with actual roles when they are added to AccessibilityRole
- composite
- alert
- alertdialog
- status
- timer
- */
- return true;
- default:
- return false;
- }
-}
-
-bool AccessibilityRenderObject::supportsARIADragging() const
-{
- const AtomicString& grabbed = getAttribute(aria_grabbedAttr);
- return equalIgnoringCase(grabbed, "true") || equalIgnoringCase(grabbed, "false");
-}
-
-bool AccessibilityRenderObject::supportsARIADropping() const
-{
- const AtomicString& dropEffect = getAttribute(aria_dropeffectAttr);
- return !dropEffect.isEmpty();
-}
-
-bool AccessibilityRenderObject::supportsARIAFlowTo() const
-{
- return !getAttribute(aria_flowtoAttr).isEmpty();
-}
-
-bool AccessibilityRenderObject::supportsARIAOwns() const
-{
- if (!m_renderer)
- return false;
- const AtomicString& ariaOwns = getAttribute(aria_ownsAttr);
-
- return !ariaOwns.isEmpty();
-}
-
-//
-// ARIA live-region features.
-//
-
-const AtomicString& AccessibilityRenderObject::ariaLiveRegionStatus() const
-{
- DEFINE_STATIC_LOCAL(const AtomicString, liveRegionStatusAssertive, ("assertive", AtomicString::ConstructFromLiteral));
- DEFINE_STATIC_LOCAL(const AtomicString, liveRegionStatusPolite, ("polite", AtomicString::ConstructFromLiteral));
- DEFINE_STATIC_LOCAL(const AtomicString, liveRegionStatusOff, ("off", AtomicString::ConstructFromLiteral));
-
- const AtomicString& liveRegionStatus = getAttribute(aria_liveAttr);
- // These roles have implicit live region status.
- if (liveRegionStatus.isEmpty()) {
- switch (roleValue()) {
- case AlertDialogRole:
- case AlertRole:
- return liveRegionStatusAssertive;
- case LogRole:
- case StatusRole:
- return liveRegionStatusPolite;
- case TimerRole:
- case MarqueeRole:
- return liveRegionStatusOff;
- default:
- break;
- }
- }
-
- return liveRegionStatus;
-}
-
-const AtomicString& AccessibilityRenderObject::ariaLiveRegionRelevant() const
-{
- DEFINE_STATIC_LOCAL(const AtomicString, defaultLiveRegionRelevant, ("additions text", AtomicString::ConstructFromLiteral));
- const AtomicString& relevant = getAttribute(aria_relevantAttr);
-
- // Default aria-relevant = "additions text".
- if (relevant.isEmpty())
- return defaultLiveRegionRelevant;
-
- return relevant;
-}
-
-bool AccessibilityRenderObject::ariaLiveRegionAtomic() const
-{
- return elementAttributeValue(aria_atomicAttr);
-}
-
-bool AccessibilityRenderObject::ariaLiveRegionBusy() const
-{
- return elementAttributeValue(aria_busyAttr);
-}
-
-//
-// Accessibility Text.
-//
-
-String AccessibilityRenderObject::textUnderElement() const
-{
- if (!m_renderer)
- return String();
-
- if (m_renderer->isFileUploadControl())
- return toRenderFileUploadControl(m_renderer)->buttonValue();
-
- if (m_renderer->isText()) {
- // If possible, use a text iterator to get the text, so that whitespace
- // is handled consistently.
- if (Node* node = this->node()) {
- if (Frame* frame = node->document().frame()) {
- // catch stale WebCoreAXObject (see <rdar://problem/3960196>)
- if (frame->document() != &node->document())
- return String();
-
- return plainText(rangeOfContents(node).get(), textIteratorBehaviorForTextRange());
- }
- }
-
- // Sometimes text fragments don't have Nodes associated with them (like when
- // CSS content is used to insert text or when a RenderCounter is used.)
- RenderText* renderTextObject = toRenderText(m_renderer);
- if (renderTextObject->isTextFragment())
- return String(toRenderTextFragment(m_renderer)->contentString());
- else
- return String(renderTextObject->text());
- }
-
- return AccessibilityNodeObject::textUnderElement();
-}
-
-//
-// Accessibility Text - (To be deprecated).
-//
-
-String AccessibilityRenderObject::helpText() const
-{
- if (!m_renderer)
- return String();
-
- const AtomicString& ariaHelp = getAttribute(aria_helpAttr);
- if (!ariaHelp.isEmpty())
- return ariaHelp;
-
- String describedBy = ariaDescribedByAttribute();
- if (!describedBy.isEmpty())
- return describedBy;
-
- String description = accessibilityDescription();
- for (RenderObject* curr = m_renderer; curr; curr = curr->parent()) {
- if (curr->node() && curr->node()->isHTMLElement()) {
- const AtomicString& summary = toElement(curr->node())->getAttribute(summaryAttr);
- if (!summary.isEmpty())
- return summary;
-
- // The title attribute should be used as help text unless it is already being used as descriptive text.
- const AtomicString& title = toElement(curr->node())->getAttribute(titleAttr);
- if (!title.isEmpty() && description != title)
- return title;
- }
-
- // Only take help text from an ancestor element if its a group or an unknown role. If help was
- // added to those kinds of elements, it is likely it was meant for a child element.
- AccessibilityObject* axObj = axObjectCache()->getOrCreate(curr);
- if (axObj) {
- AccessibilityRole role = axObj->roleValue();
- if (role != GroupRole && role != UnknownRole)
- break;
- }
- }
-
- return String();
-}
-
-//
-// Position and size.
-//
-
-void AccessibilityRenderObject::checkCachedElementRect() const
-{
- if (m_cachedElementRectDirty)
- return;
-
- if (!m_renderer)
- return;
-
- if (!m_renderer->isBox())
- return;
-
- bool dirty = false;
- RenderBox* box = toRenderBox(m_renderer);
- if (box->frameRect() != m_cachedFrameRect)
- dirty = true;
-
- if (box->canBeScrolledAndHasScrollableArea()) {
- ScrollableArea* scrollableArea = box->scrollableArea();
- if (scrollableArea && scrollableArea->scrollPosition() != m_cachedScrollPosition)
- dirty = true;
- }
-
- if (dirty)
- markCachedElementRectDirty();
-}
-
-void AccessibilityRenderObject::updateCachedElementRect() const
-{
- if (!m_cachedElementRectDirty)
- return;
-
- if (!m_renderer)
- return;
-
- if (!m_renderer->isBox())
- return;
-
- RenderBox* box = toRenderBox(m_renderer);
- m_cachedFrameRect = box->frameRect();
-
- if (box->canBeScrolledAndHasScrollableArea()) {
- ScrollableArea* scrollableArea = box->scrollableArea();
- if (scrollableArea)
- m_cachedScrollPosition = scrollableArea->scrollPosition();
- }
-
- m_cachedElementRect = computeElementRect();
- m_cachedElementRectDirty = false;
-}
-
-void AccessibilityRenderObject::markCachedElementRectDirty() const
-{
- if (m_cachedElementRectDirty)
- return;
-
- // Marks children recursively, if this element changed.
- m_cachedElementRectDirty = true;
- for (AccessibilityObject* child = firstChild(); child; child = child->nextSibling())
- child->markCachedElementRectDirty();
-}
-
-IntPoint AccessibilityRenderObject::clickPoint()
-{
- // Headings are usually much wider than their textual content. If the mid point is used, often it can be wrong.
- if (isHeading() && children().size() == 1)
- return children()[0]->clickPoint();
-
- // use the default position unless this is an editable web area, in which case we use the selection bounds.
- if (!isWebArea() || isReadOnly())
- return AccessibilityObject::clickPoint();
-
- LayoutRect bounds = elementRect();
- return IntPoint(bounds.x() + (bounds.width() / 2), bounds.y() - (bounds.height() / 2));
-}
-
-//
-// Hit testing.
-//
-
-AccessibilityObject* AccessibilityRenderObject::accessibilityHitTest(const IntPoint& point) const
-{
- if (!m_renderer || !m_renderer->hasLayer())
- return 0;
-
- RenderLayer* layer = toRenderBox(m_renderer)->layer();
-
- HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::Active);
- HitTestResult hitTestResult = HitTestResult(point);
- layer->hitTest(request, hitTestResult);
- if (!hitTestResult.innerNode())
- return 0;
- Node* node = hitTestResult.innerNode()->deprecatedShadowAncestorNode();
-
- if (isHTMLAreaElement(node))
- return accessibilityImageMapHitTest(toHTMLAreaElement(node), point);
-
- if (node->hasTagName(optionTag))
- node = toHTMLOptionElement(node)->ownerSelectElement();
-
- RenderObject* obj = node->renderer();
- if (!obj)
- return 0;
-
- AccessibilityObject* result = obj->document().axObjectCache()->getOrCreate(obj);
- result->updateChildrenIfNecessary();
-
- // Allow the element to perform any hit-testing it might need to do to reach non-render children.
- result = result->elementAccessibilityHitTest(point);
-
- if (result && result->accessibilityIsIgnored()) {
- // If this element is the label of a control, a hit test should return the control.
- if (result->isAccessibilityRenderObject()) {
- AccessibilityObject* controlObject = toAccessibilityRenderObject(result)->correspondingControlForLabelElement();
- if (controlObject && !controlObject->exposesTitleUIElement())
- return controlObject;
- }
-
- result = result->parentObjectUnignored();
- }
-
- return result;
-}
-
-AccessibilityObject* AccessibilityRenderObject::elementAccessibilityHitTest(const IntPoint& point) const
-{
- if (isSVGImage())
- return remoteSVGElementHitTest(point);
-
- return AccessibilityObject::elementAccessibilityHitTest(point);
-}
-
-//
-// High-level accessibility tree access.
-//
-
-AccessibilityObject* AccessibilityRenderObject::parentObject() const
-{
- if (!m_renderer)
- return 0;
-
- if (ariaRoleAttribute() == MenuBarRole)
- return axObjectCache()->getOrCreate(m_renderer->parent());
-
- // menuButton and its corresponding menu are DOM siblings, but Accessibility needs them to be parent/child
- if (ariaRoleAttribute() == MenuRole) {
- AccessibilityObject* parent = menuButtonForMenu();
- if (parent)
- return parent;
- }
-
- RenderObject* parentObj = renderParentObject();
- if (parentObj)
- return axObjectCache()->getOrCreate(parentObj);
-
- // WebArea's parent should be the scroll view containing it.
- if (isWebArea() || isSeamlessWebArea())
- return axObjectCache()->getOrCreate(m_renderer->frame()->view());
-
- return 0;
-}
-
-AccessibilityObject* AccessibilityRenderObject::parentObjectIfExists() const
-{
- // WebArea's parent should be the scroll view containing it.
- if (isWebArea() || isSeamlessWebArea())
- return axObjectCache()->get(m_renderer->frame()->view());
-
- return axObjectCache()->get(renderParentObject());
-}
-
-//
-// Low-level accessibility tree exploration, only for use within the accessibility module.
-//
-
-AccessibilityObject* AccessibilityRenderObject::firstChild() const
-{
- if (!m_renderer)
- return 0;
-
- RenderObject* firstChild = firstChildConsideringContinuation(m_renderer);
-
- if (!firstChild)
- return 0;
-
- return axObjectCache()->getOrCreate(firstChild);
-}
-
-AccessibilityObject* AccessibilityRenderObject::nextSibling() const
-{
- if (!m_renderer)
- return 0;
-
- RenderObject* nextSibling = 0;
-
- // Case 1: node is a block and has an inline continuation. Next sibling is the inline continuation's
- // first child.
- RenderInline* inlineContinuation;
- if (m_renderer->isRenderBlock() && (inlineContinuation = toRenderBlock(m_renderer)->inlineElementContinuation()))
- nextSibling = firstChildConsideringContinuation(inlineContinuation);
-
- // Case 2: Anonymous block parent of the start of a continuation - skip all the way to
- // after the parent of the end, since everything in between will be linked up via the continuation.
- else if (m_renderer->isAnonymousBlock() && lastChildHasContinuation(m_renderer)) {
- RenderObject* lastParent = endOfContinuations(m_renderer->lastChild())->parent();
- while (lastChildHasContinuation(lastParent))
- lastParent = endOfContinuations(lastParent->lastChild())->parent();
- nextSibling = lastParent->nextSibling();
- }
-
- // Case 3: node has an actual next sibling
- else if (RenderObject* ns = m_renderer->nextSibling())
- nextSibling = ns;
-
- // Case 4: node is an inline with a continuation. Next sibling is the next sibling of the end
- // of the continuation chain.
- else if (isInlineWithContinuation(m_renderer))
- nextSibling = endOfContinuations(m_renderer)->nextSibling();
-
- // Case 5: node has no next sibling, and its parent is an inline with a continuation.
- else if (isInlineWithContinuation(m_renderer->parent())) {
- RenderObject* continuation = toRenderInline(m_renderer->parent())->continuation();
-
- // Case 5a: continuation is a block - in this case the block itself is the next sibling.
- if (continuation->isRenderBlock())
- nextSibling = continuation;
- // Case 5b: continuation is an inline - in this case the inline's first child is the next sibling
- else
- nextSibling = firstChildConsideringContinuation(continuation);
- }
-
- if (!nextSibling)
- return 0;
-
- return axObjectCache()->getOrCreate(nextSibling);
-}
-
-void AccessibilityRenderObject::addChildren()
-{
- // If the need to add more children in addition to existing children arises,
- // childrenChanged should have been called, leaving the object with no children.
- ASSERT(!m_haveChildren);
-
- m_haveChildren = true;
-
- if (!canHaveChildren())
- return;
-
- for (RefPtr<AccessibilityObject> obj = firstChild(); obj; obj = obj->nextSibling())
- addChild(obj.get());
-
- addHiddenChildren();
- addAttachmentChildren();
- addImageMapChildren();
- addTextFieldChildren();
- addCanvasChildren();
- addRemoteSVGChildren();
-}
-
-bool AccessibilityRenderObject::canHaveChildren() const
-{
- if (!m_renderer)
- return false;
-
- return AccessibilityNodeObject::canHaveChildren();
-}
-
-void AccessibilityRenderObject::updateChildrenIfNecessary()
-{
- if (needsToUpdateChildren())
- clearChildren();
-
- AccessibilityObject::updateChildrenIfNecessary();
-}
-
-void AccessibilityRenderObject::clearChildren()
-{
- AccessibilityObject::clearChildren();
- m_childrenDirty = false;
-}
-
-AccessibilityObject* AccessibilityRenderObject::observableObject() const
-{
- // Find the object going up the parent chain that is used in accessibility to monitor certain notifications.
- for (RenderObject* renderer = m_renderer; renderer && renderer->node(); renderer = renderer->parent()) {
- if (renderObjectIsObservable(renderer))
- return axObjectCache()->getOrCreate(renderer);
- }
-
- return 0;
-}
-
-//
-// Properties of the object's owning document or page.
-//
-
-double AccessibilityRenderObject::estimatedLoadingProgress() const
-{
- if (!m_renderer)
- return 0;
-
- if (isLoaded())
- return 1.0;
-
- if (Page* page = m_renderer->document().page())
- return page->progress().estimatedProgress();
- return 0;
-}
-
-//
-// DOM and Render tree access.
-//
-
-Node* AccessibilityRenderObject::node() const
-{
- return m_renderer ? m_renderer->node() : 0;
-}
-
-Document* AccessibilityRenderObject::document() const
-{
- if (!m_renderer)
- return 0;
- return &m_renderer->document();
-}
-
-FrameView* AccessibilityRenderObject::documentFrameView() const
-{
- if (!m_renderer)
- return 0;
-
- // this is the RenderObject's Document's Frame's FrameView
- return m_renderer->document().view();
-}
-
-Element* AccessibilityRenderObject::anchorElement() const
-{
- if (!m_renderer)
- return 0;
-
- AXObjectCache* cache = axObjectCache();
- RenderObject* currRenderer;
-
- // Search up the render tree for a RenderObject with a DOM node. Defer to an earlier continuation, though.
- for (currRenderer = m_renderer; currRenderer && !currRenderer->node(); currRenderer = currRenderer->parent()) {
- if (currRenderer->isAnonymousBlock()) {
- RenderObject* continuation = toRenderBlock(currRenderer)->continuation();
- if (continuation)
- return cache->getOrCreate(continuation)->anchorElement();
- }
- }
-
- // bail if none found
- if (!currRenderer)
- return 0;
-
- // search up the DOM tree for an anchor element
- // NOTE: this assumes that any non-image with an anchor is an HTMLAnchorElement
- Node* node = currRenderer->node();
- for ( ; node; node = node->parentNode()) {
- if (isHTMLAnchorElement(node) || (node->renderer() && cache->getOrCreate(node->renderer())->isAnchor()))
- return toElement(node);
- }
-
- return 0;
-}
-
-Widget* AccessibilityRenderObject::widgetForAttachmentView() const
-{
- if (!isAttachment())
- return 0;
- return toRenderWidget(m_renderer)->widget();
-}
-
-//
-// Selected text.
-//
-
-PlainTextRange AccessibilityRenderObject::selectedTextRange() const
-{
- ASSERT(isTextControl());
-
- if (isPasswordField())
- return PlainTextRange();
-
- AccessibilityRole ariaRole = ariaRoleAttribute();
- if (isNativeTextControl() && ariaRole == UnknownRole && m_renderer->isTextControl()) {
- HTMLTextFormControlElement* textControl = toRenderTextControl(m_renderer)->textFormControlElement();
- return PlainTextRange(textControl->selectionStart(), textControl->selectionEnd() - textControl->selectionStart());
- }
-
- if (ariaRole == UnknownRole)
- return PlainTextRange();
-
- return ariaSelectedTextRange();
-}
-
-VisibleSelection AccessibilityRenderObject::selection() const
-{
- return m_renderer->frame()->selection().selection();
-}
-
-String AccessibilityRenderObject::selectedText() const
-{
- ASSERT(isTextControl());
-
- if (isPasswordField())
- return String(); // need to return something distinct from empty string
-
- if (isNativeTextControl() && m_renderer->isTextControl()) {
- HTMLTextFormControlElement* textControl = toRenderTextControl(m_renderer)->textFormControlElement();
- return textControl->selectedText();
- }
-
- if (ariaRoleAttribute() == UnknownRole)
- return String();
-
- return stringForRange(ariaSelectedTextRange());
-}
-
-//
-// Modify or take an action on an object.
-//
-
-void AccessibilityRenderObject::setSelectedTextRange(const PlainTextRange& range)
-{
- if (isNativeTextControl() && m_renderer->isTextControl()) {
- HTMLTextFormControlElement* textControl = toRenderTextControl(m_renderer)->textFormControlElement();
- textControl->setSelectionRange(range.start, range.start + range.length);
- return;
- }
-
- Document& document = m_renderer->document();
- Frame* frame = document.frame();
- if (!frame)
- return;
- Node* node = m_renderer->node();
- frame->selection().setSelection(VisibleSelection(Position(node, range.start, Position::PositionIsOffsetInAnchor),
- Position(node, range.start + range.length, Position::PositionIsOffsetInAnchor), DOWNSTREAM));
-}
-
-void AccessibilityRenderObject::setValue(const String& string)
-{
- if (!m_renderer || !m_renderer->node() || !m_renderer->node()->isElementNode())
- return;
- if (!m_renderer->isBoxModelObject())
- return;
- RenderBoxModelObject* renderer = toRenderBoxModelObject(m_renderer);
-
- // FIXME: Do we want to do anything here for ARIA textboxes?
- if (renderer->isTextField()) {
- // FIXME: This is not safe! Other elements could have a TextField renderer.
- toHTMLInputElement(m_renderer->node())->setValue(string);
- } else if (renderer->isTextArea()) {
- // FIXME: This is not safe! Other elements could have a TextArea renderer.
- toHTMLTextAreaElement(m_renderer->node())->setValue(string);
- }
-}
-
-void AccessibilityRenderObject::scrollTo(const IntPoint& point) const
-{
- if (!m_renderer || !m_renderer->isBox())
- return;
-
- RenderBox* box = toRenderBox(m_renderer);
- if (!box->canBeScrolledAndHasScrollableArea())
- return;
-
- RenderLayer* layer = box->layer();
- layer->scrollToOffset(toIntSize(point), ScrollOffsetClamped);
-}
-
-//
-// Notifications that this object may have changed.
-//
-
-void AccessibilityRenderObject::handleActiveDescendantChanged()
-{
- Element* element = toElement(renderer()->node());
- if (!element)
- return;
- Document& doc = renderer()->document();
- if (!doc.frame()->selection().isFocusedAndActive() || doc.focusedElement() != element)
- return;
- AccessibilityRenderObject* activedescendant = toAccessibilityRenderObject(activeDescendant());
-
- if (activedescendant && shouldNotifyActiveDescendant())
- doc.axObjectCache()->postNotification(m_renderer, AXObjectCache::AXActiveDescendantChanged, true);
-}
-
-void AccessibilityRenderObject::handleAriaExpandedChanged()
-{
- // Find if a parent of this object should handle aria-expanded changes.
- AccessibilityObject* containerParent = this->parentObject();
- while (containerParent) {
- bool foundParent = false;
-
- switch (containerParent->roleValue()) {
- case TreeRole:
- case TreeGridRole:
- case GridRole:
- case TableRole:
- case BrowserRole:
- foundParent = true;
- break;
- default:
- break;
- }
-
- if (foundParent)
- break;
-
- containerParent = containerParent->parentObject();
- }
-
- // Post that the row count changed.
- if (containerParent)
- axObjectCache()->postNotification(containerParent, document(), AXObjectCache::AXRowCountChanged, true);
-
- // Post that the specific row either collapsed or expanded.
- if (roleValue() == RowRole || roleValue() == TreeItemRole)
- axObjectCache()->postNotification(this, document(), isExpanded() ? AXObjectCache::AXRowExpanded : AXObjectCache::AXRowCollapsed, true);
-}
-
-//
-// Text metrics. Most of these should be deprecated, needs major cleanup.
-//
-
-// NOTE: Consider providing this utility method as AX API
-int AccessibilityRenderObject::index(const VisiblePosition& position) const
-{
- if (position.isNull() || !isTextControl())
- return -1;
-
- if (renderObjectContainsPosition(m_renderer, position.deepEquivalent()))
- return indexForVisiblePosition(position);
-
- return -1;
-}
-
-VisiblePosition AccessibilityRenderObject::visiblePositionForIndex(int index) const
-{
- if (!m_renderer)
- return VisiblePosition();
-
- if (isNativeTextControl() && m_renderer->isTextControl())
- return toRenderTextControl(m_renderer)->textFormControlElement()->visiblePositionForIndex(index);
-
- if (!allowsTextRanges() && !m_renderer->isText())
- return VisiblePosition();
-
- Node* node = m_renderer->node();
- if (!node)
- return VisiblePosition();
-
- if (index <= 0)
- return VisiblePosition(firstPositionInOrBeforeNode(node), DOWNSTREAM);
-
- RefPtr<Range> range = Range::create(m_renderer->document());
- range->selectNodeContents(node, IGNORE_EXCEPTION);
- CharacterIterator it(range.get());
- it.advance(index - 1);
- return VisiblePosition(Position(it.range()->endContainer(), it.range()->endOffset(), Position::PositionIsOffsetInAnch\
-or), UPSTREAM);
-}
-
-int AccessibilityRenderObject::indexForVisiblePosition(const VisiblePosition& pos) const
-{
- if (isNativeTextControl() && m_renderer->isTextControl()) {
- HTMLTextFormControlElement* textControl = toRenderTextControl(m_renderer)->textFormControlElement();
- return textControl->indexForVisiblePosition(pos);
- }
-
- if (!isTextControl())
- return 0;
-
- Node* node = m_renderer->node();
- if (!node)
- return 0;
-
- Position indexPosition = pos.deepEquivalent();
- if (indexPosition.isNull() || highestEditableRoot(indexPosition, HasEditableAXRole) != node)
- return 0;
-
- RefPtr<Range> range = Range::create(m_renderer->document());
- range->setStart(node, 0, IGNORE_EXCEPTION);
- range->setEnd(indexPosition, IGNORE_EXCEPTION);
-
- return TextIterator::rangeLength(range.get());
-}
-
-void AccessibilityRenderObject::lineBreaks(Vector<int>& lineBreaks) const
-{
- if (!isTextControl())
- return;
-
- VisiblePosition visiblePos = visiblePositionForIndex(0);
- VisiblePosition savedVisiblePos = visiblePos;
- visiblePos = nextLinePosition(visiblePos, 0);
- while (!visiblePos.isNull() && visiblePos != savedVisiblePos) {
- lineBreaks.append(indexForVisiblePosition(visiblePos));
- savedVisiblePos = visiblePos;
- visiblePos = nextLinePosition(visiblePos, 0);
- }
-}
-
-// A substring of the text associated with this accessibility object that is
-// specified by the given character range.
-String AccessibilityRenderObject::stringForRange(const PlainTextRange& range) const
-{
- if (!range.length)
- return String();
-
- if (!isTextControl())
- return String();
-
- String elementText = isPasswordField() ? String() : text();
- if (range.start + range.length > elementText.length())
- return String();
-
- return elementText.substring(range.start, range.length);
-}
-
-//
-// Private.
-//
-
-bool AccessibilityRenderObject::isAllowedChildOfTree() const
-{
- // Determine if this is in a tree. If so, we apply special behavior to make it work like an AXOutline.
- AccessibilityObject* axObj = parentObject();
- bool isInTree = false;
- while (axObj) {
- if (axObj->isTree()) {
- isInTree = true;
- break;
- }
- axObj = axObj->parentObject();
- }
-
- // If the object is in a tree, only tree items should be exposed (and the children of tree items).
- if (isInTree) {
- AccessibilityRole role = roleValue();
- if (role != TreeItemRole && role != StaticTextRole)
- return false;
- }
- return true;
-}
-
-void AccessibilityRenderObject::ariaListboxSelectedChildren(AccessibilityChildrenVector& result)
-{
- bool isMulti = isMultiSelectable();
-
- AccessibilityChildrenVector childObjects = children();
- unsigned childrenSize = childObjects.size();
- for (unsigned k = 0; k < childrenSize; ++k) {
- // Every child should have aria-role option, and if so, check for selected attribute/state.
- AccessibilityObject* child = childObjects[k].get();
- if (child->isSelected() && child->ariaRoleAttribute() == ListBoxOptionRole) {
- result.append(child);
- if (!isMulti)
- return;
- }
- }
-}
-
-PlainTextRange AccessibilityRenderObject::ariaSelectedTextRange() const
-{
- Node* node = m_renderer->node();
- if (!node)
- return PlainTextRange();
-
- VisibleSelection visibleSelection = selection();
- RefPtr<Range> currentSelectionRange = visibleSelection.toNormalizedRange();
- if (!currentSelectionRange || !currentSelectionRange->intersectsNode(node, IGNORE_EXCEPTION))
- return PlainTextRange();
-
- int start = indexForVisiblePosition(visibleSelection.start());
- int end = indexForVisiblePosition(visibleSelection.end());
-
- return PlainTextRange(start, end - start);
-}
-
-bool AccessibilityRenderObject::nodeIsTextControl(const Node* node) const
-{
- if (!node)
- return false;
-
- const AccessibilityObject* axObjectForNode = axObjectCache()->getOrCreate(const_cast<Node*>(node));
- if (!axObjectForNode)
- return false;
-
- return axObjectForNode->isTextControl();
-}
-
-bool AccessibilityRenderObject::isTabItemSelected() const
-{
- if (!isTabItem() || !m_renderer)
- return false;
-
- Node* node = m_renderer->node();
- if (!node || !node->isElementNode())
- return false;
-
- // The ARIA spec says a tab item can also be selected if it is aria-labeled by a tabpanel
- // that has keyboard focus inside of it, or if a tabpanel in its aria-controls list has KB
- // focus inside of it.
- AccessibilityObject* focusedElement = focusedUIElement();
- if (!focusedElement)
- return false;
-
- Vector<Element*> elements;
- elementsFromAttribute(elements, aria_controlsAttr);
-
- unsigned count = elements.size();
- for (unsigned k = 0; k < count; ++k) {
- Element* element = elements[k];
- AccessibilityObject* tabPanel = axObjectCache()->getOrCreate(element);
-
- // A tab item should only control tab panels.
- if (!tabPanel || tabPanel->roleValue() != TabPanelRole)
- continue;
-
- AccessibilityObject* checkFocusElement = focusedElement;
- // Check if the focused element is a descendant of the element controlled by the tab item.
- while (checkFocusElement) {
- if (tabPanel == checkFocusElement)
- return true;
- checkFocusElement = checkFocusElement->parentObject();
- }
- }
-
- return false;
-}
-
-AccessibilityObject* AccessibilityRenderObject::internalLinkElement() const
-{
- Element* element = anchorElement();
- if (!element)
- return 0;
-
- // Right now, we do not support ARIA links as internal link elements
- if (!isHTMLAnchorElement(element))
- return 0;
- HTMLAnchorElement* anchor = toHTMLAnchorElement(element);
-
- KURL linkURL = anchor->href();
- String fragmentIdentifier = linkURL.fragmentIdentifier();
- if (fragmentIdentifier.isEmpty())
- return 0;
-
- // check if URL is the same as current URL
- KURL documentURL = m_renderer->document().url();
- if (!equalIgnoringFragmentIdentifier(documentURL, linkURL))
- return 0;
-
- Node* linkedNode = m_renderer->document().findAnchor(fragmentIdentifier);
- if (!linkedNode)
- return 0;
-
- // The element we find may not be accessible, so find the first accessible object.
- return firstAccessibleObjectFromNode(linkedNode);
-}
-
-AccessibilityObject* AccessibilityRenderObject::accessibilityImageMapHitTest(HTMLAreaElement* area, const IntPoint& point) const
-{
- if (!area)
- return 0;
-
- AccessibilityObject* parent = axObjectCache()->getOrCreate(area->imageElement());
- if (!parent)
- return 0;
-
- AccessibilityObject::AccessibilityChildrenVector children = parent->children();
- unsigned count = children.size();
- for (unsigned k = 0; k < count; ++k) {
- if (children[k]->elementRect().contains(point))
- return children[k].get();
- }
-
- return 0;
-}
-
-bool AccessibilityRenderObject::renderObjectIsObservable(RenderObject* renderer) const
-{
- // AX clients will listen for AXValueChange on a text control.
- if (renderer->isTextControl())
- return true;
-
- // AX clients will listen for AXSelectedChildrenChanged on listboxes.
- Node* node = renderer->node();
- if (nodeHasRole(node, "listbox") || (renderer->isBoxModelObject() && toRenderBoxModelObject(renderer)->isListBox()))
- return true;
-
- // Textboxes should send out notifications.
- if (nodeHasRole(node, "textbox"))
- return true;
-
- return false;
-}
-
-RenderObject* AccessibilityRenderObject::renderParentObject() const
-{
- if (!m_renderer)
- return 0;
-
- RenderObject* parent = m_renderer->parent();
-
- // Case 1: node is a block and is an inline's continuation. Parent
- // is the start of the continuation chain.
- RenderObject* startOfConts = 0;
- RenderObject* firstChild = 0;
- if (m_renderer->isRenderBlock() && (startOfConts = startOfContinuations(m_renderer)))
- parent = startOfConts;
-
- // Case 2: node's parent is an inline which is some node's continuation; parent is
- // the earliest node in the continuation chain.
- else if (parent && parent->isRenderInline() && (startOfConts = startOfContinuations(parent)))
- parent = startOfConts;
-
- // Case 3: The first sibling is the beginning of a continuation chain. Find the origin of that continuation.
- else if (parent && (firstChild = parent->firstChild()) && firstChild->node()) {
- // Get the node's renderer and follow that continuation chain until the first child is found
- RenderObject* nodeRenderFirstChild = firstChild->node()->renderer();
- while (nodeRenderFirstChild != firstChild) {
- for (RenderObject* contsTest = nodeRenderFirstChild; contsTest; contsTest = nextContinuation(contsTest)) {
- if (contsTest == firstChild) {
- parent = nodeRenderFirstChild->parent();
- break;
- }
- }
- if (firstChild == parent->firstChild())
- break;
- firstChild = parent->firstChild();
- if (!firstChild->node())
- break;
- nodeRenderFirstChild = firstChild->node()->renderer();
- }
- }
-
- return parent;
-}
-
-bool AccessibilityRenderObject::isDescendantOfElementType(const QualifiedName& tagName) const
-{
- for (RenderObject* parent = m_renderer->parent(); parent; parent = parent->parent()) {
- if (parent->node() && parent->node()->hasTagName(tagName))
- return true;
- }
- return false;
-}
-
-bool AccessibilityRenderObject::isSVGImage() const
-{
- return remoteSVGRootElement();
-}
-
-void AccessibilityRenderObject::detachRemoteSVGRoot()
-{
- if (AccessibilitySVGRoot* root = remoteSVGRootElement())
- root->setParent(0);
-}
-
-AccessibilitySVGRoot* AccessibilityRenderObject::remoteSVGRootElement() const
-{
- if (!m_renderer || !m_renderer->isRenderImage())
- return 0;
-
- ImageResource* cachedImage = toRenderImage(m_renderer)->cachedImage();
- if (!cachedImage)
- return 0;
-
- Image* image = cachedImage->image();
- if (!image || !image->isSVGImage())
- return 0;
-
- FrameView* frameView = toSVGImage(image)->frameView();
- if (!frameView)
- return 0;
- Document* doc = frameView->frame().document();
- if (!doc || !doc->isSVGDocument())
- return 0;
-
- SVGSVGElement* rootElement = toSVGDocument(doc)->rootElement();
- if (!rootElement)
- return 0;
- RenderObject* rendererRoot = rootElement->renderer();
- if (!rendererRoot)
- return 0;
-
- AccessibilityObject* rootSVGObject = doc->axObjectCache()->getOrCreate(rendererRoot);
-
- // In order to connect the AX hierarchy from the SVG root element from the loaded resource
- // the parent must be set, because there's no other way to get back to who created the image.
- ASSERT(rootSVGObject && rootSVGObject->isAccessibilitySVGRoot());
- if (!rootSVGObject->isAccessibilitySVGRoot())
- return 0;
-
- return toAccessibilitySVGRoot(rootSVGObject);
-}
-
-AccessibilityObject* AccessibilityRenderObject::remoteSVGElementHitTest(const IntPoint& point) const
-{
- AccessibilityObject* remote = remoteSVGRootElement();
- if (!remote)
- return 0;
-
- IntSize offset = point - roundedIntPoint(elementRect().location());
- return remote->accessibilityHitTest(IntPoint(offset));
-}
-
-// The boundingBox for elements within the remote SVG element needs to be offset by its position
-// within the parent page, otherwise they are in relative coordinates only.
-void AccessibilityRenderObject::offsetBoundingBoxForRemoteSVGElement(LayoutRect& rect) const
-{
- for (AccessibilityObject* parent = parentObject(); parent; parent = parent->parentObject()) {
- if (parent->isAccessibilitySVGRoot()) {
- rect.moveBy(parent->parentObject()->elementRect().location());
- break;
- }
- }
-}
-
-// Hidden children are those that are not rendered or visible, but are specifically marked as aria-hidden=false,
-// meaning that they should be exposed to the AX hierarchy.
-void AccessibilityRenderObject::addHiddenChildren()
-{
- Node* node = this->node();
- if (!node)
- return;
-
- // First do a quick run through to determine if we have any hidden nodes (most often we will not).
- // If we do have hidden nodes, we need to determine where to insert them so they match DOM order as close as possible.
- bool shouldInsertHiddenNodes = false;
- for (Node* child = node->firstChild(); child; child = child->nextSibling()) {
- if (!child->renderer() && isNodeAriaVisible(child)) {
- shouldInsertHiddenNodes = true;
- break;
- }
- }
-
- if (!shouldInsertHiddenNodes)
- return;
-
- // Iterate through all of the children, including those that may have already been added, and
- // try to insert hidden nodes in the correct place in the DOM order.
- unsigned insertionIndex = 0;
- for (Node* child = node->firstChild(); child; child = child->nextSibling()) {
- if (child->renderer()) {
- // Find out where the last render sibling is located within m_children.
- AccessibilityObject* childObject = axObjectCache()->get(child->renderer());
- if (childObject && childObject->accessibilityIsIgnored()) {
- AccessibilityChildrenVector children = childObject->children();
- if (children.size())
- childObject = children.last().get();
- else
- childObject = 0;
- }
-
- if (childObject)
- insertionIndex = m_children.find(childObject) + 1;
- continue;
- }
-
- if (!isNodeAriaVisible(child))
- continue;
-
- unsigned previousSize = m_children.size();
- if (insertionIndex > previousSize)
- insertionIndex = previousSize;
-
- insertChild(axObjectCache()->getOrCreate(child), insertionIndex);
- insertionIndex += (m_children.size() - previousSize);
- }
-}
-
-void AccessibilityRenderObject::addTextFieldChildren()
-{
- Node* node = this->node();
- if (!node || !node->hasTagName(inputTag))
- return;
-
- HTMLInputElement* input = toHTMLInputElement(node);
- Element* spinButtonElement = input->userAgentShadowRoot()->getElementById(ShadowElementNames::spinButton());
- if (!spinButtonElement || !spinButtonElement->isSpinButtonElement())
- return;
-
- AccessibilitySpinButton* axSpinButton = toAccessibilitySpinButton(axObjectCache()->getOrCreate(SpinButtonRole));
- axSpinButton->setSpinButtonElement(toSpinButtonElement(spinButtonElement));
- axSpinButton->setParent(this);
- m_children.append(axSpinButton);
-}
-
-void AccessibilityRenderObject::addImageMapChildren()
-{
- RenderBoxModelObject* cssBox = renderBoxModelObject();
- if (!cssBox || !cssBox->isRenderImage())
- return;
-
- HTMLMapElement* map = toRenderImage(cssBox)->imageMap();
- if (!map)
- return;
-
- for (Element* current = ElementTraversal::firstWithin(map); current; current = ElementTraversal::next(current, map)) {
- // add an <area> element for this child if it has a link
- if (isHTMLAreaElement(current) && current->isLink()) {
- AccessibilityImageMapLink* areaObject = static_cast<AccessibilityImageMapLink*>(axObjectCache()->getOrCreate(ImageMapLinkRole));
- areaObject->setHTMLAreaElement(toHTMLAreaElement(current));
- areaObject->setHTMLMapElement(map);
- areaObject->setParent(this);
- if (!areaObject->accessibilityIsIgnored())
- m_children.append(areaObject);
- else
- axObjectCache()->remove(areaObject->axObjectID());
- }
- }
-}
-
-void AccessibilityRenderObject::addCanvasChildren()
-{
- if (!node() || !node()->hasTagName(canvasTag))
- return;
-
- // If it's a canvas, it won't have rendered children, but it might have accessible fallback content.
- // Clear m_haveChildren because AccessibilityNodeObject::addChildren will expect it to be false.
- ASSERT(!m_children.size());
- m_haveChildren = false;
- AccessibilityNodeObject::addChildren();
-}
-
-void AccessibilityRenderObject::addAttachmentChildren()
-{
- if (!isAttachment())
- return;
-
- // FrameView's need to be inserted into the AX hierarchy when encountered.
- Widget* widget = widgetForAttachmentView();
- if (!widget || !widget->isFrameView())
- return;
-
- AccessibilityObject* axWidget = axObjectCache()->getOrCreate(widget);
- if (!axWidget->accessibilityIsIgnored())
- m_children.append(axWidget);
-}
-
-void AccessibilityRenderObject::addRemoteSVGChildren()
-{
- AccessibilitySVGRoot* root = remoteSVGRootElement();
- if (!root)
- return;
-
- root->setParent(this);
-
- if (root->accessibilityIsIgnored()) {
- AccessibilityChildrenVector children = root->children();
- unsigned length = children.size();
- for (unsigned i = 0; i < length; ++i)
- m_children.append(children[i]);
- } else
- m_children.append(root);
-}
-
-void AccessibilityRenderObject::ariaSelectedRows(AccessibilityChildrenVector& result)
-{
- // Get all the rows.
- AccessibilityChildrenVector allRows;
- if (isTree())
- ariaTreeRows(allRows);
- else if (isAccessibilityTable() && toAccessibilityTable(this)->supportsSelectedRows())
- allRows = toAccessibilityTable(this)->rows();
-
- // Determine which rows are selected.
- bool isMulti = isMultiSelectable();
-
- // Prefer active descendant over aria-selected.
- AccessibilityObject* activeDesc = activeDescendant();
- if (activeDesc && (activeDesc->isTreeItem() || activeDesc->isTableRow())) {
- result.append(activeDesc);
- if (!isMulti)
- return;
- }
-
- unsigned count = allRows.size();
- for (unsigned k = 0; k < count; ++k) {
- if (allRows[k]->isSelected()) {
- result.append(allRows[k]);
- if (!isMulti)
- break;
- }
- }
-}
-
-bool AccessibilityRenderObject::elementAttributeValue(const QualifiedName& attributeName) const
-{
- if (!m_renderer)
- return false;
-
- return equalIgnoringCase(getAttribute(attributeName), "true");
-}
-
-bool AccessibilityRenderObject::inheritsPresentationalRole() const
-{
- // ARIA states if an item can get focus, it should not be presentational.
- if (canSetFocusAttribute())
- return false;
-
- // ARIA spec says that when a parent object is presentational, and it has required child elements,
- // those child elements are also presentational. For example, <li> becomes presentational from <ul>.
- // http://www.w3.org/WAI/PF/aria/complete#presentation
- if (roleValue() != ListItemRole && roleValue() != ListMarkerRole)
- return false;
-
- AccessibilityObject* parent = parentObject();
- if (!parent->isAccessibilityRenderObject())
- return false;
-
- Node* elementNode = toAccessibilityRenderObject(parent)->node();
- if (!elementNode || !elementNode->isElementNode())
- return false;
-
- QualifiedName tagName = toElement(elementNode)->tagQName();
- if (tagName == ulTag || tagName == olTag || tagName == dlTag)
- return parent->roleValue() == PresentationalRole;
-
- return false;
-}
-
-LayoutRect AccessibilityRenderObject::computeElementRect() const
-{
- RenderObject* obj = m_renderer;
-
- if (!obj)
- return LayoutRect();
-
- if (obj->node()) // If we are a continuation, we want to make sure to use the primary renderer.
- obj = obj->node()->renderer();
-
- // absoluteFocusRingQuads will query the hierarchy below this element, which for large webpages can be very slow.
- // For a web area, which will have the most elements of any element, absoluteQuads should be used.
- // We should also use absoluteQuads for SVG elements, otherwise transforms won't be applied.
- Vector<FloatQuad> quads;
-
- if (obj->isText())
- toRenderText(obj)->absoluteQuads(quads, 0, RenderText::ClipToEllipsis);
- else if (isWebArea() || isSeamlessWebArea() || obj->isSVGRoot())
- obj->absoluteQuads(quads);
- else
- obj->absoluteFocusRingQuads(quads);
-
- LayoutRect result = boundingBoxForQuads(obj, quads);
-
- Document* document = this->document();
- if (document && document->isSVGDocument())
- offsetBoundingBoxForRemoteSVGElement(result);
-
- // The size of the web area should be the content size, not the clipped size.
- if ((isWebArea() || isSeamlessWebArea()) && obj->frame()->view())
- result.setSize(obj->frame()->view()->contentsSize());
-
- // Checkboxes and radio buttons include their label as part of their rect.
- if (isCheckboxOrRadio()) {
- HTMLLabelElement* label = labelForElement(toElement(m_renderer->node()));
- if (label && label->renderer()) {
- LayoutRect labelRect = axObjectCache()->getOrCreate(label)->elementRect();
- result.unite(labelRect);
- }
- }
-
- return result;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityRenderObject.h b/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityRenderObject.h
deleted file mode 100644
index d11a61e701b..00000000000
--- a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityRenderObject.h
+++ /dev/null
@@ -1,248 +0,0 @@
-/*
- * Copyright (C) 2008 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef AccessibilityRenderObject_h
-#define AccessibilityRenderObject_h
-
-#include "core/accessibility/AccessibilityNodeObject.h"
-#include "core/platform/graphics/LayoutRect.h"
-#include "wtf/Forward.h"
-
-namespace WebCore {
-
-class AccessibilitySVGRoot;
-class AXObjectCache;
-class Element;
-class Frame;
-class FrameView;
-class HitTestResult;
-class HTMLAnchorElement;
-class HTMLAreaElement;
-class HTMLElement;
-class HTMLLabelElement;
-class HTMLMapElement;
-class HTMLSelectElement;
-class IntPoint;
-class IntSize;
-class Node;
-class RenderListBox;
-class RenderTextControl;
-class RenderView;
-class VisibleSelection;
-class Widget;
-
-class AccessibilityRenderObject : public AccessibilityNodeObject {
-protected:
- explicit AccessibilityRenderObject(RenderObject*);
-public:
- static PassRefPtr<AccessibilityRenderObject> create(RenderObject*);
- virtual ~AccessibilityRenderObject();
-
- // Public, overridden from AccessibilityObject.
- virtual RenderObject* renderer() const OVERRIDE { return m_renderer; }
- virtual LayoutRect elementRect() const OVERRIDE;
-
- void setRenderer(RenderObject*);
- RenderBoxModelObject* renderBoxModelObject() const;
- RenderView* topRenderer() const;
- Document* topDocument() const;
- bool shouldNotifyActiveDescendant() const;
- bool needsToUpdateChildren() const { return m_childrenDirty; }
- ScrollableArea* getScrollableAreaIfScrollable() const;
- virtual AccessibilityRole determineAccessibilityRole() OVERRIDE;
- void checkCachedElementRect() const;
- void updateCachedElementRect() const;
-
-protected:
- RenderObject* m_renderer;
- mutable LayoutRect m_cachedElementRect;
- mutable LayoutRect m_cachedFrameRect;
- mutable IntPoint m_cachedScrollPosition;
- mutable bool m_cachedElementRectDirty;
-
- //
- // Overridden from AccessibilityObject.
- //
-
- virtual void init() OVERRIDE;
- virtual void detach() OVERRIDE;
- virtual bool isDetached() const OVERRIDE { return !m_renderer; }
- virtual bool isAccessibilityRenderObject() const OVERRIDE { return true; }
-
- // Check object role or purpose.
- virtual bool isAttachment() const OVERRIDE;
- virtual bool isFileUploadButton() const OVERRIDE;
- virtual bool isLinked() const OVERRIDE;
- virtual bool isLoaded() const OVERRIDE;
- virtual bool isOffScreen() const OVERRIDE;
- virtual bool isReadOnly() const OVERRIDE;
- virtual bool isVisited() const OVERRIDE;
-
- // Check object state.
- virtual bool isFocused() const OVERRIDE;
- virtual bool isSelected() const OVERRIDE;
-
- // Whether objects are ignored, i.e. not included in the tree.
- virtual AccessibilityObjectInclusion defaultObjectInclusion() const OVERRIDE;
- virtual bool computeAccessibilityIsIgnored() const OVERRIDE;
-
- // Properties of static elements.
- virtual const AtomicString& accessKey() const OVERRIDE;
- virtual AccessibilityOrientation orientation() const OVERRIDE;
- virtual String text() const OVERRIDE;
- virtual int textLength() const OVERRIDE;
- virtual KURL url() const OVERRIDE;
-
- // Properties of interactive elements.
- virtual String actionVerb() const OVERRIDE;
- virtual void selectedChildren(AccessibilityChildrenVector&) OVERRIDE;
- virtual String stringValue() const OVERRIDE;
-
- // ARIA attributes.
- virtual AccessibilityObject* activeDescendant() const OVERRIDE;
- virtual void ariaFlowToElements(AccessibilityChildrenVector&) const OVERRIDE;
- virtual bool ariaHasPopup() const OVERRIDE;
- virtual bool ariaRoleHasPresentationalChildren() const OVERRIDE;
- virtual bool isPresentationalChildOfAriaRole() const OVERRIDE;
- virtual bool shouldFocusActiveDescendant() const OVERRIDE;
- virtual bool supportsARIADragging() const OVERRIDE;
- virtual bool supportsARIADropping() const OVERRIDE;
- virtual bool supportsARIAFlowTo() const OVERRIDE;
- virtual bool supportsARIAOwns() const OVERRIDE;
-
- // ARIA live-region features.
- virtual const AtomicString& ariaLiveRegionStatus() const OVERRIDE;
- virtual const AtomicString& ariaLiveRegionRelevant() const OVERRIDE;
- virtual bool ariaLiveRegionAtomic() const OVERRIDE;
- virtual bool ariaLiveRegionBusy() const OVERRIDE;
-
- // Accessibility Text.
- virtual String textUnderElement() const OVERRIDE;
-
- // Accessibility Text - (To be deprecated).
- virtual String helpText() const OVERRIDE;
-
- // Location and click point in frame-relative coordinates.
- virtual void markCachedElementRectDirty() const OVERRIDE;
- virtual IntPoint clickPoint() OVERRIDE;
-
- // Hit testing.
- virtual AccessibilityObject* accessibilityHitTest(const IntPoint&) const OVERRIDE;
- virtual AccessibilityObject* elementAccessibilityHitTest(const IntPoint&) const OVERRIDE;
-
- // High-level accessibility tree access. Other modules should only use these functions.
- virtual AccessibilityObject* parentObject() const OVERRIDE;
- virtual AccessibilityObject* parentObjectIfExists() const OVERRIDE;
-
- // Low-level accessibility tree exploration, only for use within the accessibility module.
- virtual AccessibilityObject* firstChild() const OVERRIDE;
- virtual AccessibilityObject* nextSibling() const OVERRIDE;
- virtual void addChildren() OVERRIDE;
- virtual bool canHaveChildren() const OVERRIDE;
- virtual void updateChildrenIfNecessary() OVERRIDE;
- virtual void setNeedsToUpdateChildren() OVERRIDE { m_childrenDirty = true; }
- virtual void clearChildren() OVERRIDE;
- virtual AccessibilityObject* observableObject() const OVERRIDE;
-
- // Properties of the object's owning document or page.
- virtual double estimatedLoadingProgress() const OVERRIDE;
-
- // DOM and Render tree access.
- virtual Node* node() const OVERRIDE;
- virtual Document* document() const OVERRIDE;
- virtual FrameView* documentFrameView() const OVERRIDE;
- virtual Element* anchorElement() const OVERRIDE;
- virtual Widget* widgetForAttachmentView() const OVERRIDE;
-
- // Selected text.
- virtual PlainTextRange selectedTextRange() const OVERRIDE;
- virtual String selectedText() const OVERRIDE;
-
- // Modify or take an action on an object.
- virtual void setSelectedTextRange(const PlainTextRange&) OVERRIDE;
- virtual void setValue(const String&) OVERRIDE;
- virtual void scrollTo(const IntPoint&) const OVERRIDE;
-
- // Notifications that this object may have changed.
- virtual void handleActiveDescendantChanged() OVERRIDE;
- virtual void handleAriaExpandedChanged() OVERRIDE;
-
- // Text metrics. Most of these should be deprecated, needs major cleanup.
- virtual int index(const VisiblePosition&) const OVERRIDE;
- virtual VisiblePosition visiblePositionForIndex(int) const OVERRIDE;
- virtual void lineBreaks(Vector<int>&) const OVERRIDE;
-
-private:
- bool isAllowedChildOfTree() const;
- void ariaListboxSelectedChildren(AccessibilityChildrenVector&);
- PlainTextRange ariaSelectedTextRange() const;
- bool nodeIsTextControl(const Node*) const;
- bool isTabItemSelected() const;
- AccessibilityObject* internalLinkElement() const;
- AccessibilityObject* accessibilityImageMapHitTest(HTMLAreaElement*, const IntPoint&) const;
- bool renderObjectIsObservable(RenderObject*) const;
- RenderObject* renderParentObject() const;
- bool isDescendantOfElementType(const QualifiedName& tagName) const;
- bool isSVGImage() const;
- void detachRemoteSVGRoot();
- AccessibilitySVGRoot* remoteSVGRootElement() const;
- AccessibilityObject* remoteSVGElementHitTest(const IntPoint&) const;
- void offsetBoundingBoxForRemoteSVGElement(LayoutRect&) const;
- void addHiddenChildren();
- void addTextFieldChildren();
- void addImageMapChildren();
- void addCanvasChildren();
- void addAttachmentChildren();
- void addRemoteSVGChildren();
- void ariaSelectedRows(AccessibilityChildrenVector&);
- bool elementAttributeValue(const QualifiedName&) const;
- bool inheritsPresentationalRole() const;
- LayoutRect computeElementRect() const;
- VisibleSelection selection() const;
- String stringForRange(const PlainTextRange&) const;
- int indexForVisiblePosition(const VisiblePosition&) const;
-};
-
-inline AccessibilityRenderObject* toAccessibilityRenderObject(AccessibilityObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isAccessibilityRenderObject());
- return static_cast<AccessibilityRenderObject*>(object);
-}
-
-inline const AccessibilityRenderObject* toAccessibilityRenderObject(const AccessibilityObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isAccessibilityRenderObject());
- return static_cast<const AccessibilityRenderObject*>(object);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toAccessibilityRenderObject(const AccessibilityRenderObject*);
-
-} // namespace WebCore
-
-#endif // AccessibilityRenderObject_h
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilitySVGRoot.cpp b/chromium/third_party/WebKit/Source/core/accessibility/AccessibilitySVGRoot.cpp
deleted file mode 100644
index 4d811207212..00000000000
--- a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilitySVGRoot.cpp
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Copyright (C) 2012 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/accessibility/AccessibilitySVGRoot.h"
-
-
-namespace WebCore {
-
-AccessibilitySVGRoot::AccessibilitySVGRoot(RenderObject* renderer)
- : AccessibilityRenderObject(renderer)
- , m_parent(0)
-{
-}
-
-AccessibilitySVGRoot::~AccessibilitySVGRoot()
-{
-}
-
-PassRefPtr<AccessibilitySVGRoot> AccessibilitySVGRoot::create(RenderObject* renderer)
-{
- return adoptRef(new AccessibilitySVGRoot(renderer));
-}
-
-AccessibilityObject* AccessibilitySVGRoot::parentObject() const
-{
- // If a parent was set because this is a remote SVG resource, use that
- // but otherwise, we should rely on the standard render tree for the parent.
- if (m_parent)
- return m_parent;
-
- return AccessibilityRenderObject::parentObject();
-}
-
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilitySVGRoot.h b/chromium/third_party/WebKit/Source/core/accessibility/AccessibilitySVGRoot.h
deleted file mode 100644
index 0aa4512ebff..00000000000
--- a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilitySVGRoot.h
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Copyright (C) 2012 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef AccessibilitySVGRoot_h
-#define AccessibilitySVGRoot_h
-
-#include "core/accessibility/AccessibilityRenderObject.h"
-
-namespace WebCore {
-
-class AccessibilitySVGRoot : public AccessibilityRenderObject {
-
-protected:
- explicit AccessibilitySVGRoot(RenderObject*);
-public:
- static PassRefPtr<AccessibilitySVGRoot> create(RenderObject*);
- virtual ~AccessibilitySVGRoot();
-
- void setParent(AccessibilityObject* parent) { m_parent = parent; }
-
-private:
- AccessibilityObject* m_parent;
-
- virtual AccessibilityObject* parentObject() const OVERRIDE;
- virtual bool isAccessibilitySVGRoot() const OVERRIDE { return true; }
-};
-
-inline AccessibilitySVGRoot* toAccessibilitySVGRoot(AccessibilityObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isAccessibilitySVGRoot());
- return static_cast<AccessibilitySVGRoot*>(object);
-}
-
-} // namespace WebCore
-
-#endif // AccessibilitySVGRoot_h
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityScrollView.cpp b/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityScrollView.cpp
deleted file mode 100644
index 3e13f5bae71..00000000000
--- a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityScrollView.cpp
+++ /dev/null
@@ -1,242 +0,0 @@
-/*
- * Copyright (C) 2011 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/accessibility/AccessibilityScrollView.h"
-
-#include "core/accessibility/AXObjectCache.h"
-#include "core/accessibility/AccessibilityScrollbar.h"
-#include "core/html/HTMLFrameOwnerElement.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameView.h"
-
-namespace WebCore {
-
-AccessibilityScrollView::AccessibilityScrollView(ScrollView* view)
- : m_scrollView(view)
- , m_childrenDirty(false)
-{
-}
-
-AccessibilityScrollView::~AccessibilityScrollView()
-{
- ASSERT(isDetached());
-}
-
-void AccessibilityScrollView::detach()
-{
- AccessibilityObject::detach();
- m_scrollView = 0;
-}
-
-PassRefPtr<AccessibilityScrollView> AccessibilityScrollView::create(ScrollView* view)
-{
- return adoptRef(new AccessibilityScrollView(view));
-}
-
-AccessibilityObject* AccessibilityScrollView::scrollBar(AccessibilityOrientation orientation)
-{
- updateScrollbars();
-
- switch (orientation) {
- case AccessibilityOrientationVertical:
- return m_verticalScrollbar ? m_verticalScrollbar.get() : 0;
- case AccessibilityOrientationHorizontal:
- return m_horizontalScrollbar ? m_horizontalScrollbar.get() : 0;
- }
-
- return 0;
-}
-
-// If this is WebKit1 then the native scroll view needs to return the
-// AX information (because there are no scroll bar children in the ScrollView object in WK1).
-// In WebKit2, the ScrollView object will return the AX information (because there are no platform widgets).
-bool AccessibilityScrollView::isAttachment() const
-{
- return false;
-}
-
-Widget* AccessibilityScrollView::widgetForAttachmentView() const
-{
- return m_scrollView;
-}
-
-void AccessibilityScrollView::updateChildrenIfNecessary()
-{
- if (m_childrenDirty)
- clearChildren();
-
- if (!m_haveChildren)
- addChildren();
-
- updateScrollbars();
-}
-
-void AccessibilityScrollView::updateScrollbars()
-{
- if (!m_scrollView)
- return;
-
- if (m_scrollView->horizontalScrollbar() && !m_horizontalScrollbar)
- m_horizontalScrollbar = addChildScrollbar(m_scrollView->horizontalScrollbar());
- else if (!m_scrollView->horizontalScrollbar() && m_horizontalScrollbar) {
- removeChildScrollbar(m_horizontalScrollbar.get());
- m_horizontalScrollbar = 0;
- }
-
- if (m_scrollView->verticalScrollbar() && !m_verticalScrollbar)
- m_verticalScrollbar = addChildScrollbar(m_scrollView->verticalScrollbar());
- else if (!m_scrollView->verticalScrollbar() && m_verticalScrollbar) {
- removeChildScrollbar(m_verticalScrollbar.get());
- m_verticalScrollbar = 0;
- }
-}
-
-void AccessibilityScrollView::removeChildScrollbar(AccessibilityObject* scrollbar)
-{
- size_t pos = m_children.find(scrollbar);
- if (pos != kNotFound) {
- m_children[pos]->detachFromParent();
- m_children.remove(pos);
- }
-}
-
-AccessibilityScrollbar* AccessibilityScrollView::addChildScrollbar(Scrollbar* scrollbar)
-{
- if (!scrollbar)
- return 0;
-
- AccessibilityScrollbar* scrollBarObject = static_cast<AccessibilityScrollbar*>(axObjectCache()->getOrCreate(scrollbar));
- scrollBarObject->setParent(this);
- m_children.append(scrollBarObject);
- return scrollBarObject;
-}
-
-void AccessibilityScrollView::clearChildren()
-{
- AccessibilityObject::clearChildren();
- m_verticalScrollbar = 0;
- m_horizontalScrollbar = 0;
-}
-
-bool AccessibilityScrollView::computeAccessibilityIsIgnored() const
-{
- AccessibilityObject* webArea = webAreaObject();
- if (!webArea)
- return true;
-
- return webArea->accessibilityIsIgnored();
-}
-
-void AccessibilityScrollView::addChildren()
-{
- ASSERT(!m_haveChildren);
- m_haveChildren = true;
-
- AccessibilityObject* webArea = webAreaObject();
- if (webArea && !webArea->accessibilityIsIgnored())
- m_children.append(webArea);
-
- updateScrollbars();
-}
-
-AccessibilityObject* AccessibilityScrollView::webAreaObject() const
-{
- if (!m_scrollView || !m_scrollView->isFrameView())
- return 0;
-
- Document* doc = toFrameView(m_scrollView)->frame().document();
- if (!doc || !doc->renderer())
- return 0;
-
- return axObjectCache()->getOrCreate(doc);
-}
-
-AccessibilityObject* AccessibilityScrollView::accessibilityHitTest(const IntPoint& point) const
-{
- AccessibilityObject* webArea = webAreaObject();
- if (!webArea)
- return 0;
-
- if (m_horizontalScrollbar && m_horizontalScrollbar->elementRect().contains(point))
- return m_horizontalScrollbar.get();
- if (m_verticalScrollbar && m_verticalScrollbar->elementRect().contains(point))
- return m_verticalScrollbar.get();
-
- return webArea->accessibilityHitTest(point);
-}
-
-LayoutRect AccessibilityScrollView::elementRect() const
-{
- if (!m_scrollView)
- return LayoutRect();
-
- return m_scrollView->frameRect();
-}
-
-FrameView* AccessibilityScrollView::documentFrameView() const
-{
- if (!m_scrollView || !m_scrollView->isFrameView())
- return 0;
-
- return toFrameView(m_scrollView);
-}
-
-AccessibilityObject* AccessibilityScrollView::parentObject() const
-{
- if (!m_scrollView || !m_scrollView->isFrameView())
- return 0;
-
- HTMLFrameOwnerElement* owner = toFrameView(m_scrollView)->frame().ownerElement();
- if (owner && owner->renderer())
- return axObjectCache()->getOrCreate(owner);
-
- return 0;
-}
-
-AccessibilityObject* AccessibilityScrollView::parentObjectIfExists() const
-{
- if (!m_scrollView || !m_scrollView->isFrameView())
- return 0;
-
- HTMLFrameOwnerElement* owner = toFrameView(m_scrollView)->frame().ownerElement();
- if (owner && owner->renderer())
- return axObjectCache()->get(owner);
-
- return 0;
-}
-
-ScrollableArea* AccessibilityScrollView::getScrollableAreaIfScrollable() const
-{
- return m_scrollView;
-}
-
-void AccessibilityScrollView::scrollTo(const IntPoint& point) const
-{
- if (m_scrollView)
- m_scrollView->setScrollPosition(point);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityScrollView.h b/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityScrollView.h
deleted file mode 100644
index c23a121c2f7..00000000000
--- a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityScrollView.h
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * Copyright (C) 2011 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef AccessibilityScrollView_h
-#define AccessibilityScrollView_h
-
-#include "core/accessibility/AccessibilityObject.h"
-
-namespace WebCore {
-
-class AccessibilityScrollbar;
-class Scrollbar;
-class ScrollView;
-
-class AccessibilityScrollView : public AccessibilityObject {
-public:
- static PassRefPtr<AccessibilityScrollView> create(ScrollView*);
- virtual AccessibilityRole roleValue() const { return ScrollAreaRole; }
- ScrollView* scrollView() const { return m_scrollView; }
-
- virtual ~AccessibilityScrollView();
- virtual void detach() OVERRIDE;
-
-protected:
- virtual ScrollableArea* getScrollableAreaIfScrollable() const OVERRIDE;
- virtual void scrollTo(const IntPoint&) const OVERRIDE;
-
-private:
- explicit AccessibilityScrollView(ScrollView*);
-
- virtual bool computeAccessibilityIsIgnored() const OVERRIDE;
- virtual bool isAccessibilityScrollView() const OVERRIDE { return true; }
- virtual bool isEnabled() const OVERRIDE { return true; }
-
- virtual bool isAttachment() const OVERRIDE;
- virtual Widget* widgetForAttachmentView() const OVERRIDE;
-
- virtual AccessibilityObject* scrollBar(AccessibilityOrientation) OVERRIDE;
- virtual void addChildren() OVERRIDE;
- virtual void clearChildren() OVERRIDE;
- virtual AccessibilityObject* accessibilityHitTest(const IntPoint&) const OVERRIDE;
- virtual void updateChildrenIfNecessary() OVERRIDE;
- virtual void setNeedsToUpdateChildren() OVERRIDE { m_childrenDirty = true; }
- void updateScrollbars();
-
- virtual FrameView* documentFrameView() const OVERRIDE;
- virtual LayoutRect elementRect() const OVERRIDE;
- virtual AccessibilityObject* parentObject() const OVERRIDE;
- virtual AccessibilityObject* parentObjectIfExists() const OVERRIDE;
-
- AccessibilityObject* webAreaObject() const;
- virtual AccessibilityObject* firstChild() const OVERRIDE { return webAreaObject(); }
- AccessibilityScrollbar* addChildScrollbar(Scrollbar*);
- void removeChildScrollbar(AccessibilityObject*);
-
- ScrollView* m_scrollView;
- RefPtr<AccessibilityObject> m_horizontalScrollbar;
- RefPtr<AccessibilityObject> m_verticalScrollbar;
- bool m_childrenDirty;
-};
-
-inline AccessibilityScrollView* toAccessibilityScrollView(AccessibilityObject* object)
-{
- ASSERT(!object || object->isAccessibilityScrollView());
- if (!object->isAccessibilityScrollView())
- return 0;
-
- return static_cast<AccessibilityScrollView*>(object);
-}
-
-} // namespace WebCore
-
-#endif // AccessibilityScrollView_h
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityScrollbar.cpp b/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityScrollbar.cpp
deleted file mode 100644
index a7ed3efb7a7..00000000000
--- a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityScrollbar.cpp
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * Copyright (C) 2010 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/accessibility/AccessibilityScrollbar.h"
-
-#include "core/platform/ScrollView.h"
-
-namespace WebCore {
-
-AccessibilityScrollbar::AccessibilityScrollbar(Scrollbar* scrollbar)
- : m_scrollbar(scrollbar)
-{
- ASSERT(scrollbar);
-}
-
-void AccessibilityScrollbar::detachFromParent()
-{
- m_scrollbar = 0;
- AccessibilityMockObject::detachFromParent();
-}
-
-PassRefPtr<AccessibilityScrollbar> AccessibilityScrollbar::create(Scrollbar* scrollbar)
-{
- return adoptRef(new AccessibilityScrollbar(scrollbar));
-}
-
-LayoutRect AccessibilityScrollbar::elementRect() const
-{
- if (!m_scrollbar)
- return LayoutRect();
-
- return m_scrollbar->frameRect();
-}
-
-Document* AccessibilityScrollbar::document() const
-{
- AccessibilityObject* parent = parentObject();
- if (!parent)
- return 0;
- return parent->document();
-}
-
-AccessibilityOrientation AccessibilityScrollbar::orientation() const
-{
- if (!m_scrollbar)
- return AccessibilityOrientationHorizontal;
-
- if (m_scrollbar->orientation() == HorizontalScrollbar)
- return AccessibilityOrientationHorizontal;
- if (m_scrollbar->orientation() == VerticalScrollbar)
- return AccessibilityOrientationVertical;
-
- return AccessibilityOrientationHorizontal;
-}
-
-bool AccessibilityScrollbar::isEnabled() const
-{
- if (!m_scrollbar)
- return false;
- return m_scrollbar->enabled();
-}
-
-float AccessibilityScrollbar::valueForRange() const
-{
- if (!m_scrollbar)
- return 0;
-
- return m_scrollbar->currentPos() / m_scrollbar->maximum();
-}
-
-void AccessibilityScrollbar::setValue(float value)
-{
- if (!m_scrollbar)
- return;
-
- if (!m_scrollbar->scrollableArea())
- return;
-
- float newValue = value * m_scrollbar->maximum();
- m_scrollbar->scrollableArea()->scrollToOffsetWithoutAnimation(m_scrollbar->orientation(), newValue);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityScrollbar.h b/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityScrollbar.h
deleted file mode 100644
index fe0714aa3eb..00000000000
--- a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityScrollbar.h
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * Copyright (C) 2010 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef AccessibilityScrollbar_h
-#define AccessibilityScrollbar_h
-
-#include "core/accessibility/AccessibilityMockObject.h"
-
-namespace WebCore {
-
-class Scrollbar;
-
-class AccessibilityScrollbar : public AccessibilityMockObject {
-public:
- static PassRefPtr<AccessibilityScrollbar> create(Scrollbar*);
-
- Scrollbar* scrollbar() const { return m_scrollbar.get(); }
-
-private:
- explicit AccessibilityScrollbar(Scrollbar*);
-
- virtual void detachFromParent();
-
- virtual bool canSetValueAttribute() const OVERRIDE { return true; }
-
- virtual bool isAccessibilityScrollbar() const OVERRIDE { return true; }
- virtual LayoutRect elementRect() const OVERRIDE;
-
- virtual AccessibilityRole roleValue() const OVERRIDE { return ScrollBarRole; }
- virtual AccessibilityOrientation orientation() const OVERRIDE;
- virtual Document* document() const OVERRIDE;
-
- virtual bool isEnabled() const OVERRIDE;
-
- // Assumes float [0..1]
- virtual void setValue(float) OVERRIDE;
- virtual float valueForRange() const OVERRIDE;
-
- RefPtr<Scrollbar> m_scrollbar;
-};
-
-} // namespace WebCore
-
-#endif // AccessibilityScrollbar_h
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilitySlider.cpp b/chromium/third_party/WebKit/Source/core/accessibility/AccessibilitySlider.cpp
deleted file mode 100644
index 5873bd7865c..00000000000
--- a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilitySlider.cpp
+++ /dev/null
@@ -1,159 +0,0 @@
-/*
- * Copyright (C) 2009 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/accessibility/AccessibilitySlider.h"
-
-#include "core/accessibility/AXObjectCache.h"
-#include "core/dom/shadow/ShadowRoot.h"
-#include "core/html/HTMLInputElement.h"
-#include "core/html/shadow/ShadowElementNames.h"
-#include "core/rendering/RenderObject.h"
-
-namespace WebCore {
-
-using namespace HTMLNames;
-
-AccessibilitySlider::AccessibilitySlider(RenderObject* renderer)
- : AccessibilityRenderObject(renderer)
-{
-}
-
-PassRefPtr<AccessibilitySlider> AccessibilitySlider::create(RenderObject* renderer)
-{
- return adoptRef(new AccessibilitySlider(renderer));
-}
-
-AccessibilityOrientation AccessibilitySlider::orientation() const
-{
- // Default to horizontal in the unknown case.
- if (!m_renderer)
- return AccessibilityOrientationHorizontal;
-
- RenderStyle* style = m_renderer->style();
- if (!style)
- return AccessibilityOrientationHorizontal;
-
- ControlPart styleAppearance = style->appearance();
- switch (styleAppearance) {
- case SliderThumbHorizontalPart:
- case SliderHorizontalPart:
- case MediaSliderPart:
- case MediaFullScreenVolumeSliderPart:
- return AccessibilityOrientationHorizontal;
-
- case SliderThumbVerticalPart:
- case SliderVerticalPart:
- case MediaVolumeSliderPart:
- return AccessibilityOrientationVertical;
-
- default:
- return AccessibilityOrientationHorizontal;
- }
-}
-
-void AccessibilitySlider::addChildren()
-{
- ASSERT(!m_haveChildren);
-
- m_haveChildren = true;
-
- AXObjectCache* cache = m_renderer->document().axObjectCache();
-
- AccessibilitySliderThumb* thumb = static_cast<AccessibilitySliderThumb*>(cache->getOrCreate(SliderThumbRole));
- thumb->setParent(this);
-
- // Before actually adding the value indicator to the hierarchy,
- // allow the platform to make a final decision about it.
- if (thumb->accessibilityIsIgnored())
- cache->remove(thumb->axObjectID());
- else
- m_children.append(thumb);
-}
-
-const AtomicString& AccessibilitySlider::getAttribute(const QualifiedName& attribute) const
-{
- return element()->getAttribute(attribute);
-}
-
-AccessibilityObject* AccessibilitySlider::elementAccessibilityHitTest(const IntPoint& point) const
-{
- if (m_children.size()) {
- ASSERT(m_children.size() == 1);
- if (m_children[0]->elementRect().contains(point))
- return m_children[0].get();
- }
-
- return axObjectCache()->getOrCreate(m_renderer);
-}
-
-void AccessibilitySlider::setValue(const String& value)
-{
- HTMLInputElement* input = element();
-
- if (input->value() == value)
- return;
-
- input->setValue(value);
-
- // Fire change event manually, as RenderSlider::setValueForPosition does.
- input->dispatchFormControlChangeEvent();
-}
-
-HTMLInputElement* AccessibilitySlider::element() const
-{
- return toHTMLInputElement(m_renderer->node());
-}
-
-
-AccessibilitySliderThumb::AccessibilitySliderThumb()
-{
-}
-
-PassRefPtr<AccessibilitySliderThumb> AccessibilitySliderThumb::create()
-{
- return adoptRef(new AccessibilitySliderThumb());
-}
-
-LayoutRect AccessibilitySliderThumb::elementRect() const
-{
- if (!m_parent)
- return LayoutRect();
-
- RenderObject* sliderRenderer = m_parent->renderer();
- if (!sliderRenderer || !sliderRenderer->isSlider())
- return LayoutRect();
- return toElement(sliderRenderer->node())->userAgentShadowRoot()->getElementById(ShadowElementNames::sliderThumb())->boundingBox();
-}
-
-bool AccessibilitySliderThumb::computeAccessibilityIsIgnored() const
-{
- return accessibilityIsIgnoredByDefault();
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilitySlider.h b/chromium/third_party/WebKit/Source/core/accessibility/AccessibilitySlider.h
deleted file mode 100644
index 39c4bb2832b..00000000000
--- a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilitySlider.h
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * Copyright (C) 2009 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef AccessibilitySlider_h
-#define AccessibilitySlider_h
-
-#include "core/accessibility/AccessibilityMockObject.h"
-#include "core/accessibility/AccessibilityRenderObject.h"
-
-namespace WebCore {
-
-class HTMLInputElement;
-
-class AccessibilitySlider : public AccessibilityRenderObject {
-
-public:
- static PassRefPtr<AccessibilitySlider> create(RenderObject*);
- virtual ~AccessibilitySlider() { }
-
-protected:
- explicit AccessibilitySlider(RenderObject*);
-
-private:
- HTMLInputElement* element() const;
- virtual AccessibilityObject* elementAccessibilityHitTest(const IntPoint&) const OVERRIDE;
-
- virtual AccessibilityRole roleValue() const OVERRIDE { return SliderRole; }
- virtual bool isSlider() const OVERRIDE { return true; }
- virtual bool isControl() const OVERRIDE { return true; }
-
- virtual void addChildren() OVERRIDE;
-
- virtual bool canSetValueAttribute() const OVERRIDE { return true; }
- const AtomicString& getAttribute(const QualifiedName& attribute) const;
-
- virtual void setValue(const String&) OVERRIDE;
- virtual AccessibilityOrientation orientation() const OVERRIDE;
-};
-
-class AccessibilitySliderThumb : public AccessibilityMockObject {
-
-public:
- static PassRefPtr<AccessibilitySliderThumb> create();
- virtual ~AccessibilitySliderThumb() { }
-
- virtual AccessibilityRole roleValue() const OVERRIDE { return SliderThumbRole; }
-
- virtual LayoutRect elementRect() const OVERRIDE;
-
-private:
- AccessibilitySliderThumb();
-
- virtual bool computeAccessibilityIsIgnored() const OVERRIDE;
-};
-
-
-} // namespace WebCore
-
-#endif // AccessibilitySlider_h
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilitySpinButton.cpp b/chromium/third_party/WebKit/Source/core/accessibility/AccessibilitySpinButton.cpp
deleted file mode 100644
index 427b7a11d30..00000000000
--- a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilitySpinButton.cpp
+++ /dev/null
@@ -1,127 +0,0 @@
-/*
- * Copyright (C) 2011 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/accessibility/AccessibilitySpinButton.h"
-
-#include "core/accessibility/AXObjectCache.h"
-#include "core/rendering/RenderObject.h"
-
-namespace WebCore {
-
-PassRefPtr<AccessibilitySpinButton> AccessibilitySpinButton::create()
-{
- return adoptRef(new AccessibilitySpinButton);
-}
-
-AccessibilitySpinButton::AccessibilitySpinButton()
- : m_spinButtonElement(0)
-{
-}
-
-AccessibilitySpinButton::~AccessibilitySpinButton()
-{
-}
-
-LayoutRect AccessibilitySpinButton::elementRect() const
-{
- ASSERT(m_spinButtonElement);
-
- if (!m_spinButtonElement || !m_spinButtonElement->renderer())
- return LayoutRect();
-
- Vector<FloatQuad> quads;
- m_spinButtonElement->renderer()->absoluteFocusRingQuads(quads);
-
- return boundingBoxForQuads(m_spinButtonElement->renderer(), quads);
-}
-
-void AccessibilitySpinButton::addChildren()
-{
- m_haveChildren = true;
-
- AccessibilitySpinButtonPart* incrementor = static_cast<AccessibilitySpinButtonPart*>(axObjectCache()->getOrCreate(SpinButtonPartRole));
- incrementor->setIsIncrementor(true);
- incrementor->setParent(this);
- m_children.append(incrementor);
-
- AccessibilitySpinButtonPart* decrementor = static_cast<AccessibilitySpinButtonPart*>(axObjectCache()->getOrCreate(SpinButtonPartRole));
- decrementor->setIsIncrementor(false);
- decrementor->setParent(this);
- m_children.append(decrementor);
-}
-
-void AccessibilitySpinButton::step(int amount)
-{
- ASSERT(m_spinButtonElement);
- if (!m_spinButtonElement)
- return;
-
- m_spinButtonElement->step(amount);
-}
-
-// AccessibilitySpinButtonPart
-
-AccessibilitySpinButtonPart::AccessibilitySpinButtonPart()
- : m_isIncrementor(false)
-{
-}
-
-PassRefPtr<AccessibilitySpinButtonPart> AccessibilitySpinButtonPart::create()
-{
- return adoptRef(new AccessibilitySpinButtonPart);
-}
-
-LayoutRect AccessibilitySpinButtonPart::elementRect() const
-{
- // FIXME: This logic should exist in the render tree or elsewhere, but there is no
- // relationship that exists that can be queried.
-
- LayoutRect parentRect = parentObject()->elementRect();
- if (m_isIncrementor)
- parentRect.setHeight(parentRect.height() / 2);
- else {
- parentRect.setY(parentRect.y() + parentRect.height() / 2);
- parentRect.setHeight(parentRect.height() / 2);
- }
-
- return parentRect;
-}
-
-bool AccessibilitySpinButtonPart::press() const
-{
- if (!m_parent || !m_parent->isSpinButton())
- return false;
-
- AccessibilitySpinButton* spinButton = toAccessibilitySpinButton(parentObject());
- if (m_isIncrementor)
- spinButton->step(1);
- else
- spinButton->step(-1);
-
- return true;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilitySpinButton.h b/chromium/third_party/WebKit/Source/core/accessibility/AccessibilitySpinButton.h
deleted file mode 100644
index ca9704d269e..00000000000
--- a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilitySpinButton.h
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * Copyright (C) 2011 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef AccessibilitySpinButton_h
-#define AccessibilitySpinButton_h
-
-#include "core/accessibility/AccessibilityMockObject.h"
-
-#include "core/html/shadow/SpinButtonElement.h"
-
-namespace WebCore {
-
-class AccessibilitySpinButton : public AccessibilityMockObject {
-public:
- static PassRefPtr<AccessibilitySpinButton> create();
- virtual ~AccessibilitySpinButton();
-
- void setSpinButtonElement(SpinButtonElement* spinButton) { m_spinButtonElement = spinButton; }
- void step(int amount);
-
-private:
- AccessibilitySpinButton();
-
- virtual AccessibilityRole roleValue() const OVERRIDE { return SpinButtonRole; }
- virtual bool isSpinButton() const OVERRIDE { return true; }
- virtual bool isNativeSpinButton() const OVERRIDE { return true; }
- virtual void addChildren() OVERRIDE;
- virtual LayoutRect elementRect() const OVERRIDE;
-
- SpinButtonElement* m_spinButtonElement;
-};
-
-class AccessibilitySpinButtonPart : public AccessibilityMockObject {
-public:
- static PassRefPtr<AccessibilitySpinButtonPart> create();
- virtual ~AccessibilitySpinButtonPart() { }
-
- bool isIncrementor() const { return m_isIncrementor; }
- void setIsIncrementor(bool value) { m_isIncrementor = value; }
-
-private:
- AccessibilitySpinButtonPart();
- bool m_isIncrementor : 1;
-
- virtual bool press() const OVERRIDE;
- virtual AccessibilityRole roleValue() const OVERRIDE { return ButtonRole; }
- virtual bool isSpinButtonPart() const OVERRIDE { return true; }
- virtual LayoutRect elementRect() const OVERRIDE;
-};
-
-inline AccessibilitySpinButton* toAccessibilitySpinButton(AccessibilityObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isNativeSpinButton());
- return static_cast<AccessibilitySpinButton*>(object);
-}
-
-inline AccessibilitySpinButtonPart* toAccessibilitySpinButtonPart(AccessibilityObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isSpinButtonPart());
- return static_cast<AccessibilitySpinButtonPart*>(object);
-}
-
-} // namespace WebCore
-
-#endif // AccessibilitySpinButton_h
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityTable.cpp b/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityTable.cpp
deleted file mode 100644
index 0eb08321ed0..00000000000
--- a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityTable.cpp
+++ /dev/null
@@ -1,550 +0,0 @@
-/*
- * Copyright (C) 2008 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/accessibility/AccessibilityTable.h"
-
-#include "core/accessibility/AXObjectCache.h"
-#include "core/accessibility/AccessibilityTableCell.h"
-#include "core/accessibility/AccessibilityTableColumn.h"
-#include "core/accessibility/AccessibilityTableRow.h"
-#include "core/html/HTMLTableCaptionElement.h"
-#include "core/html/HTMLTableCellElement.h"
-#include "core/html/HTMLTableElement.h"
-#include "core/rendering/RenderTableCell.h"
-
-namespace WebCore {
-
-using namespace HTMLNames;
-
-AccessibilityTable::AccessibilityTable(RenderObject* renderer)
- : AccessibilityRenderObject(renderer)
- , m_headerContainer(0)
- , m_isAccessibilityTable(true)
-{
-}
-
-AccessibilityTable::~AccessibilityTable()
-{
-}
-
-void AccessibilityTable::init()
-{
- AccessibilityRenderObject::init();
- m_isAccessibilityTable = isTableExposableThroughAccessibility();
-}
-
-PassRefPtr<AccessibilityTable> AccessibilityTable::create(RenderObject* renderer)
-{
- return adoptRef(new AccessibilityTable(renderer));
-}
-
-bool AccessibilityTable::hasARIARole() const
-{
- if (!m_renderer)
- return false;
-
- AccessibilityRole ariaRole = ariaRoleAttribute();
- if (ariaRole != UnknownRole)
- return true;
-
- return false;
-}
-
-bool AccessibilityTable::isAccessibilityTable() const
-{
- if (!m_renderer)
- return false;
-
- return m_isAccessibilityTable;
-}
-
-bool AccessibilityTable::isDataTable() const
-{
- if (!m_renderer)
- return false;
-
- // Do not consider it a data table is it has an ARIA role.
- if (hasARIARole())
- return false;
-
- // When a section of the document is contentEditable, all tables should be
- // treated as data tables, otherwise users may not be able to work with rich
- // text editors that allow creating and editing tables.
- if (node() && node()->rendererIsEditable())
- return true;
-
- // This employs a heuristic to determine if this table should appear.
- // Only "data" tables should be exposed as tables.
- // Unfortunately, there is no good way to determine the difference
- // between a "layout" table and a "data" table.
-
- RenderTable* table = toRenderTable(m_renderer);
- Node* tableNode = table->node();
- if (!tableNode || !isHTMLTableElement(tableNode))
- return false;
-
- // if there is a caption element, summary, THEAD, or TFOOT section, it's most certainly a data table
- HTMLTableElement* tableElement = toHTMLTableElement(tableNode);
- if (!tableElement->summary().isEmpty() || tableElement->tHead() || tableElement->tFoot() || tableElement->caption())
- return true;
-
- // if someone used "rules" attribute than the table should appear
- if (!tableElement->rules().isEmpty())
- return true;
-
- // if there's a colgroup or col element, it's probably a data table.
- for (Node* child = tableElement->firstChild(); child; child = child->nextSibling()) {
- if (child->hasTagName(colTag) || child->hasTagName(colgroupTag))
- return true;
- }
-
- // go through the cell's and check for tell-tale signs of "data" table status
- // cells have borders, or use attributes like headers, abbr, scope or axis
- table->recalcSectionsIfNeeded();
- RenderTableSection* firstBody = table->firstBody();
- if (!firstBody)
- return false;
-
- int numCols = firstBody->numColumns();
- int numRows = firstBody->numRows();
-
- // If there's only one cell, it's not a good AXTable candidate.
- if (numRows == 1 && numCols == 1)
- return false;
-
- // If there are at least 20 rows, we'll call it a data table.
- if (numRows >= 20)
- return true;
-
- // Store the background color of the table to check against cell's background colors.
- RenderStyle* tableStyle = table->style();
- if (!tableStyle)
- return false;
- Color tableBGColor = tableStyle->visitedDependentColor(CSSPropertyBackgroundColor);
-
- // check enough of the cells to find if the table matches our criteria
- // Criteria:
- // 1) must have at least one valid cell (and)
- // 2) at least half of cells have borders (or)
- // 3) at least half of cells have different bg colors than the table, and there is cell spacing
- unsigned validCellCount = 0;
- unsigned borderedCellCount = 0;
- unsigned backgroundDifferenceCellCount = 0;
- unsigned cellsWithTopBorder = 0;
- unsigned cellsWithBottomBorder = 0;
- unsigned cellsWithLeftBorder = 0;
- unsigned cellsWithRightBorder = 0;
-
- Color alternatingRowColors[5];
- int alternatingRowColorCount = 0;
-
- int headersInFirstColumnCount = 0;
- for (int row = 0; row < numRows; ++row) {
-
- int headersInFirstRowCount = 0;
- for (int col = 0; col < numCols; ++col) {
- RenderTableCell* cell = firstBody->primaryCellAt(row, col);
- if (!cell)
- continue;
- Node* cellNode = cell->node();
- if (!cellNode)
- continue;
-
- if (cell->width() < 1 || cell->height() < 1)
- continue;
-
- validCellCount++;
-
- HTMLTableCellElement* cellElement = toHTMLTableCellElement(cellNode);
-
- bool isTHCell = cellElement->hasTagName(thTag);
- // If the first row is comprised of all <th> tags, assume it is a data table.
- if (!row && isTHCell)
- headersInFirstRowCount++;
-
- // If the first column is comprised of all <th> tags, assume it is a data table.
- if (!col && isTHCell)
- headersInFirstColumnCount++;
-
- // in this case, the developer explicitly assigned a "data" table attribute
- if (!cellElement->headers().isEmpty() || !cellElement->abbr().isEmpty()
- || !cellElement->axis().isEmpty() || !cellElement->scope().isEmpty())
- return true;
-
- RenderStyle* renderStyle = cell->style();
- if (!renderStyle)
- continue;
-
- // If the empty-cells style is set, we'll call it a data table.
- if (renderStyle->emptyCells() == HIDE)
- return true;
-
- // If a cell has matching bordered sides, call it a (fully) bordered cell.
- if ((cell->borderTop() > 0 && cell->borderBottom() > 0)
- || (cell->borderLeft() > 0 && cell->borderRight() > 0))
- borderedCellCount++;
-
- // Also keep track of each individual border, so we can catch tables where most
- // cells have a bottom border, for example.
- if (cell->borderTop() > 0)
- cellsWithTopBorder++;
- if (cell->borderBottom() > 0)
- cellsWithBottomBorder++;
- if (cell->borderLeft() > 0)
- cellsWithLeftBorder++;
- if (cell->borderRight() > 0)
- cellsWithRightBorder++;
-
- // If the cell has a different color from the table and there is cell spacing,
- // then it is probably a data table cell (spacing and colors take the place of borders).
- Color cellColor = renderStyle->visitedDependentColor(CSSPropertyBackgroundColor);
- if (table->hBorderSpacing() > 0 && table->vBorderSpacing() > 0
- && tableBGColor != cellColor && cellColor.alpha() != 1)
- backgroundDifferenceCellCount++;
-
- // If we've found 10 "good" cells, we don't need to keep searching.
- if (borderedCellCount >= 10 || backgroundDifferenceCellCount >= 10)
- return true;
-
- // For the first 5 rows, cache the background color so we can check if this table has zebra-striped rows.
- if (row < 5 && row == alternatingRowColorCount) {
- RenderObject* renderRow = cell->parent();
- if (!renderRow || !renderRow->isBoxModelObject() || !toRenderBoxModelObject(renderRow)->isTableRow())
- continue;
- RenderStyle* rowRenderStyle = renderRow->style();
- if (!rowRenderStyle)
- continue;
- Color rowColor = rowRenderStyle->visitedDependentColor(CSSPropertyBackgroundColor);
- alternatingRowColors[alternatingRowColorCount] = rowColor;
- alternatingRowColorCount++;
- }
- }
-
- if (!row && headersInFirstRowCount == numCols && numCols > 1)
- return true;
- }
-
- if (headersInFirstColumnCount == numRows && numRows > 1)
- return true;
-
- // if there is less than two valid cells, it's not a data table
- if (validCellCount <= 1)
- return false;
-
- // half of the cells had borders, it's a data table
- unsigned neededCellCount = validCellCount / 2;
- if (borderedCellCount >= neededCellCount
- || cellsWithTopBorder >= neededCellCount
- || cellsWithBottomBorder >= neededCellCount
- || cellsWithLeftBorder >= neededCellCount
- || cellsWithRightBorder >= neededCellCount)
- return true;
-
- // half had different background colors, it's a data table
- if (backgroundDifferenceCellCount >= neededCellCount)
- return true;
-
- // Check if there is an alternating row background color indicating a zebra striped style pattern.
- if (alternatingRowColorCount > 2) {
- Color firstColor = alternatingRowColors[0];
- for (int k = 1; k < alternatingRowColorCount; k++) {
- // If an odd row was the same color as the first row, its not alternating.
- if (k % 2 == 1 && alternatingRowColors[k] == firstColor)
- return false;
- // If an even row is not the same as the first row, its not alternating.
- if (!(k % 2) && alternatingRowColors[k] != firstColor)
- return false;
- }
- return true;
- }
-
- return false;
-}
-
-bool AccessibilityTable::isTableExposableThroughAccessibility() const
-{
- // The following is a heuristic used to determine if a
- // <table> should be exposed as an AXTable. The goal
- // is to only show "data" tables.
-
- if (!m_renderer)
- return false;
-
- // If the developer assigned an aria role to this, then we
- // shouldn't expose it as a table, unless, of course, the aria
- // role is a table.
- if (hasARIARole())
- return false;
-
- return isDataTable();
-}
-
-void AccessibilityTable::clearChildren()
-{
- AccessibilityRenderObject::clearChildren();
- m_rows.clear();
- m_columns.clear();
-
- if (m_headerContainer) {
- m_headerContainer->detachFromParent();
- m_headerContainer = 0;
- }
-}
-
-void AccessibilityTable::addChildren()
-{
- if (!isAccessibilityTable()) {
- AccessibilityRenderObject::addChildren();
- return;
- }
-
- ASSERT(!m_haveChildren);
-
- m_haveChildren = true;
- if (!m_renderer || !m_renderer->isTable())
- return;
-
- RenderTable* table = toRenderTable(m_renderer);
- AXObjectCache* axCache = m_renderer->document().axObjectCache();
-
- // Go through all the available sections to pull out the rows and add them as children.
- table->recalcSectionsIfNeeded();
- RenderTableSection* tableSection = table->topSection();
- if (!tableSection)
- return;
-
- RenderTableSection* initialTableSection = tableSection;
- while (tableSection) {
-
- HashSet<AccessibilityObject*> appendedRows;
- unsigned numRows = tableSection->numRows();
- for (unsigned rowIndex = 0; rowIndex < numRows; ++rowIndex) {
-
- RenderTableRow* renderRow = tableSection->rowRendererAt(rowIndex);
- if (!renderRow)
- continue;
-
- AccessibilityObject* rowObject = axCache->getOrCreate(renderRow);
- if (!rowObject->isTableRow())
- continue;
-
- AccessibilityTableRow* row = static_cast<AccessibilityTableRow*>(rowObject);
- // We need to check every cell for a new row, because cell spans
- // can cause us to miss rows if we just check the first column.
- if (appendedRows.contains(row))
- continue;
-
- row->setRowIndex(static_cast<int>(m_rows.size()));
- m_rows.append(row);
- if (!row->accessibilityIsIgnored())
- m_children.append(row);
- appendedRows.add(row);
- }
-
- tableSection = table->sectionBelow(tableSection, SkipEmptySections);
- }
-
- // make the columns based on the number of columns in the first body
- unsigned length = initialTableSection->numColumns();
- for (unsigned i = 0; i < length; ++i) {
- AccessibilityTableColumn* column = static_cast<AccessibilityTableColumn*>(axCache->getOrCreate(ColumnRole));
- column->setColumnIndex((int)i);
- column->setParent(this);
- m_columns.append(column);
- if (!column->accessibilityIsIgnored())
- m_children.append(column);
- }
-
- AccessibilityObject* headerContainerObject = headerContainer();
- if (headerContainerObject && !headerContainerObject->accessibilityIsIgnored())
- m_children.append(headerContainerObject);
-}
-
-AccessibilityObject* AccessibilityTable::headerContainer()
-{
- if (m_headerContainer)
- return m_headerContainer.get();
-
- AccessibilityMockObject* tableHeader = toAccessibilityMockObject(axObjectCache()->getOrCreate(TableHeaderContainerRole));
- tableHeader->setParent(this);
-
- m_headerContainer = tableHeader;
- return m_headerContainer.get();
-}
-
-AccessibilityObject::AccessibilityChildrenVector& AccessibilityTable::columns()
-{
- updateChildrenIfNecessary();
-
- return m_columns;
-}
-
-AccessibilityObject::AccessibilityChildrenVector& AccessibilityTable::rows()
-{
- updateChildrenIfNecessary();
-
- return m_rows;
-}
-
-void AccessibilityTable::columnHeaders(AccessibilityChildrenVector& headers)
-{
- if (!m_renderer)
- return;
-
- updateChildrenIfNecessary();
-
- unsigned colCount = m_columns.size();
- for (unsigned k = 0; k < colCount; ++k) {
- AccessibilityObject* header = static_cast<AccessibilityTableColumn*>(m_columns[k].get())->headerObject();
- if (!header)
- continue;
- headers.append(header);
- }
-}
-
-void AccessibilityTable::cells(AccessibilityObject::AccessibilityChildrenVector& cells)
-{
- if (!m_renderer)
- return;
-
- updateChildrenIfNecessary();
-
- int numRows = m_rows.size();
- for (int row = 0; row < numRows; ++row) {
- AccessibilityChildrenVector rowChildren = m_rows[row]->children();
- cells.append(rowChildren);
- }
-}
-
-unsigned AccessibilityTable::columnCount()
-{
- updateChildrenIfNecessary();
-
- return m_columns.size();
-}
-
-unsigned AccessibilityTable::rowCount()
-{
- updateChildrenIfNecessary();
-
- return m_rows.size();
-}
-
-int AccessibilityTable::tableLevel() const
-{
- int level = 0;
- for (AccessibilityObject* obj = static_cast<AccessibilityObject*>(const_cast<AccessibilityTable*>(this)); obj; obj = obj->parentObject()) {
- if (obj->isAccessibilityTable())
- ++level;
- }
-
- return level;
-}
-
-AccessibilityTableCell* AccessibilityTable::cellForColumnAndRow(unsigned column, unsigned row)
-{
- updateChildrenIfNecessary();
- if (column >= columnCount() || row >= rowCount())
- return 0;
-
- // Iterate backwards through the rows in case the desired cell has a rowspan and exists in a previous row.
- for (unsigned rowIndexCounter = row + 1; rowIndexCounter > 0; --rowIndexCounter) {
- unsigned rowIndex = rowIndexCounter - 1;
- AccessibilityChildrenVector children = m_rows[rowIndex]->children();
- // Since some cells may have colspans, we have to check the actual range of each
- // cell to determine which is the right one.
- for (unsigned colIndexCounter = std::min(static_cast<unsigned>(children.size()), column + 1); colIndexCounter > 0; --colIndexCounter) {
- unsigned colIndex = colIndexCounter - 1;
- AccessibilityObject* child = children[colIndex].get();
- ASSERT(child->isTableCell());
- if (!child->isTableCell())
- continue;
-
- pair<unsigned, unsigned> columnRange;
- pair<unsigned, unsigned> rowRange;
- AccessibilityTableCell* tableCellChild = static_cast<AccessibilityTableCell*>(child);
- tableCellChild->columnIndexRange(columnRange);
- tableCellChild->rowIndexRange(rowRange);
-
- if ((column >= columnRange.first && column < (columnRange.first + columnRange.second))
- && (row >= rowRange.first && row < (rowRange.first + rowRange.second)))
- return tableCellChild;
- }
- }
-
- return 0;
-}
-
-AccessibilityRole AccessibilityTable::roleValue() const
-{
- if (!isAccessibilityTable())
- return AccessibilityRenderObject::roleValue();
-
- return TableRole;
-}
-
-bool AccessibilityTable::computeAccessibilityIsIgnored() const
-{
- AccessibilityObjectInclusion decision = defaultObjectInclusion();
- if (decision == IncludeObject)
- return false;
- if (decision == IgnoreObject)
- return true;
-
- if (!isAccessibilityTable())
- return AccessibilityRenderObject::computeAccessibilityIsIgnored();
-
- return false;
-}
-
-String AccessibilityTable::title() const
-{
- if (!isAccessibilityTable())
- return AccessibilityRenderObject::title();
-
- String title;
- if (!m_renderer)
- return title;
-
- // see if there is a caption
- Node* tableElement = m_renderer->node();
- if (tableElement && isHTMLTableElement(tableElement)) {
- HTMLTableCaptionElement* caption = toHTMLTableElement(tableElement)->caption();
- if (caption)
- title = caption->innerText();
- }
-
- // try the standard
- if (title.isEmpty())
- title = AccessibilityRenderObject::title();
-
- return title;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityTable.h b/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityTable.h
deleted file mode 100644
index 4833556748a..00000000000
--- a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityTable.h
+++ /dev/null
@@ -1,100 +0,0 @@
-/*
- * Copyright (C) 2008 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef AccessibilityTable_h
-#define AccessibilityTable_h
-
-#include "core/accessibility/AccessibilityRenderObject.h"
-#include "wtf/Forward.h"
-
-namespace WebCore {
-
-class AccessibilityTableCell;
-class RenderTableSection;
-
-class AccessibilityTable : public AccessibilityRenderObject {
-
-protected:
- explicit AccessibilityTable(RenderObject*);
-public:
- static PassRefPtr<AccessibilityTable> create(RenderObject*);
- virtual ~AccessibilityTable();
-
- virtual void init() OVERRIDE;
-
- virtual bool isAccessibilityTable() const OVERRIDE;
- virtual bool isDataTable() const OVERRIDE;
-
- virtual AccessibilityRole roleValue() const OVERRIDE;
-
- virtual void addChildren() OVERRIDE;
- virtual void clearChildren() OVERRIDE;
-
- // To be overridden by AccessibilityARIAGrid.
- virtual bool isAriaTable() const { return false; }
- virtual bool supportsSelectedRows() { return false; }
-
- AccessibilityChildrenVector& columns();
- AccessibilityChildrenVector& rows();
-
- unsigned columnCount();
- unsigned rowCount();
- virtual int tableLevel() const OVERRIDE;
-
- virtual String title() const OVERRIDE;
-
- // all the cells in the table
- void cells(AccessibilityChildrenVector&);
- AccessibilityTableCell* cellForColumnAndRow(unsigned column, unsigned row);
-
- void columnHeaders(AccessibilityChildrenVector&);
-
- // an object that contains, as children, all the objects that act as headers
- AccessibilityObject* headerContainer();
-
-protected:
- AccessibilityChildrenVector m_rows;
- AccessibilityChildrenVector m_columns;
-
- RefPtr<AccessibilityObject> m_headerContainer;
- bool m_isAccessibilityTable;
-
- bool hasARIARole() const;
- virtual bool isTableExposableThroughAccessibility() const;
- virtual bool computeAccessibilityIsIgnored() const OVERRIDE;
-};
-
-inline AccessibilityTable* toAccessibilityTable(AccessibilityObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isAccessibilityTable());
- return static_cast<AccessibilityTable*>(object);
-}
-
-} // namespace WebCore
-
-#endif // AccessibilityTable_h
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityTableCell.cpp b/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityTableCell.cpp
deleted file mode 100644
index 54757d2c3a1..00000000000
--- a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityTableCell.cpp
+++ /dev/null
@@ -1,178 +0,0 @@
-/*
- * Copyright (C) 2008 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/accessibility/AccessibilityTableCell.h"
-
-#include "core/accessibility/AXObjectCache.h"
-#include "core/rendering/RenderTableCell.h"
-
-using namespace std;
-
-namespace WebCore {
-
-using namespace HTMLNames;
-
-AccessibilityTableCell::AccessibilityTableCell(RenderObject* renderer)
- : AccessibilityRenderObject(renderer)
-{
-}
-
-AccessibilityTableCell::~AccessibilityTableCell()
-{
-}
-
-PassRefPtr<AccessibilityTableCell> AccessibilityTableCell::create(RenderObject* renderer)
-{
- return adoptRef(new AccessibilityTableCell(renderer));
-}
-
-bool AccessibilityTableCell::computeAccessibilityIsIgnored() const
-{
- AccessibilityObjectInclusion decision = defaultObjectInclusion();
- if (decision == IncludeObject)
- return false;
- if (decision == IgnoreObject)
- return true;
-
- if (!isTableCell())
- return AccessibilityRenderObject::computeAccessibilityIsIgnored();
-
- return false;
-}
-
-AccessibilityObject* AccessibilityTableCell::parentTable() const
-{
- if (!m_renderer || !m_renderer->isTableCell())
- return 0;
-
- // If the document no longer exists, we might not have an axObjectCache.
- if (!axObjectCache())
- return 0;
-
- // Do not use getOrCreate. parentTable() can be called while the render tree is being modified
- // by javascript, and creating a table element may try to access the render tree while in a bad state.
- // By using only get() implies that the AXTable must be created before AXTableCells. This should
- // always be the case when AT clients access a table.
- // https://bugs.webkit.org/show_bug.cgi?id=42652
- return axObjectCache()->get(toRenderTableCell(m_renderer)->table());
-}
-
-bool AccessibilityTableCell::isTableCell() const
-{
- AccessibilityObject* parent = parentObjectUnignored();
- if (!parent || !parent->isTableRow())
- return false;
-
- return true;
-}
-
-AccessibilityRole AccessibilityTableCell::determineAccessibilityRole()
-{
- if (!isTableCell())
- return AccessibilityRenderObject::determineAccessibilityRole();
-
- return CellRole;
-}
-
-void AccessibilityTableCell::rowIndexRange(pair<unsigned, unsigned>& rowRange)
-{
- if (!m_renderer || !m_renderer->isTableCell())
- return;
-
- RenderTableCell* renderCell = toRenderTableCell(m_renderer);
- rowRange.first = renderCell->rowIndex();
- rowRange.second = renderCell->rowSpan();
-
- // since our table might have multiple sections, we have to offset our row appropriately
- RenderTableSection* section = renderCell->section();
- RenderTable* table = renderCell->table();
- if (!table || !section)
- return;
-
- RenderTableSection* tableSection = table->topSection();
- unsigned rowOffset = 0;
- while (tableSection) {
- if (tableSection == section)
- break;
- rowOffset += tableSection->numRows();
- tableSection = table->sectionBelow(tableSection, SkipEmptySections);
- }
-
- rowRange.first += rowOffset;
-}
-
-void AccessibilityTableCell::columnIndexRange(pair<unsigned, unsigned>& columnRange)
-{
- if (!m_renderer || !m_renderer->isTableCell())
- return;
-
- RenderTableCell* renderCell = toRenderTableCell(m_renderer);
- columnRange.first = renderCell->col();
- columnRange.second = renderCell->colSpan();
-}
-
-AccessibilityObject* AccessibilityTableCell::titleUIElement() const
-{
- // Try to find if the first cell in this row is a <th>. If it is,
- // then it can act as the title ui element. (This is only in the
- // case when the table is not appearing as an AXTable.)
- if (isTableCell() || !m_renderer || !m_renderer->isTableCell())
- return 0;
-
- // Table cells that are th cannot have title ui elements, since by definition
- // they are title ui elements
- Node* node = m_renderer->node();
- if (node && node->hasTagName(thTag))
- return 0;
-
- RenderTableCell* renderCell = toRenderTableCell(m_renderer);
-
- // If this cell is in the first column, there is no need to continue.
- int col = renderCell->col();
- if (!col)
- return 0;
-
- int row = renderCell->rowIndex();
-
- RenderTableSection* section = renderCell->section();
- if (!section)
- return 0;
-
- RenderTableCell* headerCell = section->primaryCellAt(row, 0);
- if (!headerCell || headerCell == renderCell)
- return 0;
-
- Node* cellElement = headerCell->node();
- if (!cellElement || !cellElement->hasTagName(thTag))
- return 0;
-
- return axObjectCache()->getOrCreate(headerCell);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityTableCell.h b/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityTableCell.h
deleted file mode 100644
index 844c56ab59e..00000000000
--- a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityTableCell.h
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * Copyright (C) 2008 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef AccessibilityTableCell_h
-#define AccessibilityTableCell_h
-
-#include "core/accessibility/AccessibilityRenderObject.h"
-
-namespace WebCore {
-
-class AccessibilityTableCell : public AccessibilityRenderObject {
-
-protected:
- explicit AccessibilityTableCell(RenderObject*);
-public:
- static PassRefPtr<AccessibilityTableCell> create(RenderObject*);
- virtual ~AccessibilityTableCell();
-
- virtual bool isTableCell() const OVERRIDE;
-
- // fills in the start location and row span of cell
- virtual void rowIndexRange(pair<unsigned, unsigned>& rowRange);
- // fills in the start location and column span of cell
- virtual void columnIndexRange(pair<unsigned, unsigned>& columnRange);
-
-protected:
- virtual AccessibilityObject* parentTable() const;
- int m_rowIndex;
- virtual AccessibilityRole determineAccessibilityRole() OVERRIDE;
-
-private:
- // If a table cell is not exposed as a table cell, a TH element can serve as its title UI element.
- virtual AccessibilityObject* titleUIElement() const OVERRIDE;
- virtual bool exposesTitleUIElement() const OVERRIDE { return true; }
- virtual bool computeAccessibilityIsIgnored() const OVERRIDE;
-};
-
-} // namespace WebCore
-
-#endif // AccessibilityTableCell_h
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityTableColumn.cpp b/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityTableColumn.cpp
deleted file mode 100644
index 6b5617e5af1..00000000000
--- a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityTableColumn.cpp
+++ /dev/null
@@ -1,185 +0,0 @@
-/*
- * Copyright (C) 2008 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/accessibility/AccessibilityTableColumn.h"
-
-#include "core/accessibility/AXObjectCache.h"
-#include "core/accessibility/AccessibilityTableCell.h"
-#include "core/rendering/RenderTableCell.h"
-
-using namespace std;
-
-namespace WebCore {
-
-using namespace HTMLNames;
-
-AccessibilityTableColumn::AccessibilityTableColumn()
-{
-}
-
-AccessibilityTableColumn::~AccessibilityTableColumn()
-{
-}
-
-PassRefPtr<AccessibilityTableColumn> AccessibilityTableColumn::create()
-{
- return adoptRef(new AccessibilityTableColumn());
-}
-
-void AccessibilityTableColumn::setParent(AccessibilityObject* parent)
-{
- AccessibilityMockObject::setParent(parent);
-
- clearChildren();
-}
-
-LayoutRect AccessibilityTableColumn::elementRect() const
-{
- // this will be filled in when addChildren is called
- return m_columnRect;
-}
-
-AccessibilityObject* AccessibilityTableColumn::headerObject()
-{
- if (!m_parent)
- return 0;
-
- RenderObject* renderer = m_parent->renderer();
- if (!renderer)
- return 0;
-
- if (!m_parent->isAccessibilityTable())
- return 0;
-
- AccessibilityTable* parentTable = toAccessibilityTable(m_parent);
- if (parentTable->isAriaTable()) {
- AccessibilityChildrenVector rowChildren = children();
- unsigned childrenCount = rowChildren.size();
- for (unsigned i = 0; i < childrenCount; ++i) {
- AccessibilityObject* cell = rowChildren[i].get();
- if (cell->ariaRoleAttribute() == ColumnHeaderRole)
- return cell;
- }
-
- return 0;
- }
-
- if (!renderer->isTable())
- return 0;
-
- RenderTable* table = toRenderTable(renderer);
-
- AccessibilityObject* headerObject = 0;
-
- // try the <thead> section first. this doesn't require th tags
- headerObject = headerObjectForSection(table->header(), false);
-
- if (headerObject)
- return headerObject;
-
- // now try for <th> tags in the first body
- headerObject = headerObjectForSection(table->firstBody(), true);
-
- return headerObject;
-}
-
-AccessibilityObject* AccessibilityTableColumn::headerObjectForSection(RenderTableSection* section, bool thTagRequired)
-{
- if (!section)
- return 0;
-
- unsigned numCols = section->numColumns();
- if (m_columnIndex >= numCols)
- return 0;
-
- if (!section->numRows())
- return 0;
-
- RenderTableCell* cell = 0;
- // also account for cells that have a span
- for (int testCol = m_columnIndex; testCol >= 0; --testCol) {
- RenderTableCell* testCell = section->primaryCellAt(0, testCol);
- if (!testCell)
- continue;
-
- // we've reached a cell that doesn't even overlap our column
- // it can't be our header
- if ((testCell->col() + (testCell->colSpan()-1)) < m_columnIndex)
- break;
-
- Node* node = testCell->node();
- if (!node)
- continue;
-
- if (thTagRequired && !node->hasTagName(thTag))
- continue;
-
- cell = testCell;
- }
-
- if (!cell)
- return 0;
-
- return axObjectCache()->getOrCreate(cell);
-}
-
-bool AccessibilityTableColumn::computeAccessibilityIsIgnored() const
-{
- if (!m_parent)
- return true;
-
- return m_parent->accessibilityIsIgnored();
-}
-
-void AccessibilityTableColumn::addChildren()
-{
- ASSERT(!m_haveChildren);
-
- m_haveChildren = true;
- if (!m_parent || !m_parent->isAccessibilityTable())
- return;
-
- AccessibilityTable* parentTable = toAccessibilityTable(m_parent);
- int numRows = parentTable->rowCount();
-
- for (int i = 0; i < numRows; i++) {
- AccessibilityTableCell* cell = parentTable->cellForColumnAndRow(m_columnIndex, i);
- if (!cell)
- continue;
-
- // make sure the last one isn't the same as this one (rowspan cells)
- if (m_children.size() > 0 && m_children.last() == cell)
- continue;
-
- m_children.append(cell);
- m_columnRect.unite(cell->elementRect());
- }
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityTableColumn.h b/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityTableColumn.h
deleted file mode 100644
index 09de7ecab27..00000000000
--- a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityTableColumn.h
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * Copyright (C) 2008 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef AccessibilityTableColumn_h
-#define AccessibilityTableColumn_h
-
-#include "core/accessibility/AccessibilityMockObject.h"
-#include "core/accessibility/AccessibilityTable.h"
-
-namespace WebCore {
-
-class RenderTableSection;
-
-class AccessibilityTableColumn : public AccessibilityMockObject {
-
-private:
- AccessibilityTableColumn();
-public:
- static PassRefPtr<AccessibilityTableColumn> create();
- virtual ~AccessibilityTableColumn();
-
- AccessibilityObject* headerObject();
-
- virtual AccessibilityRole roleValue() const OVERRIDE { return ColumnRole; }
-
- void setColumnIndex(int columnIndex) { m_columnIndex = columnIndex; }
- int columnIndex() const { return m_columnIndex; }
-
- virtual void addChildren() OVERRIDE;
- virtual void setParent(AccessibilityObject*) OVERRIDE;
-
- virtual LayoutRect elementRect() const OVERRIDE;
-
-private:
- unsigned m_columnIndex;
- LayoutRect m_columnRect;
-
- AccessibilityObject* headerObjectForSection(RenderTableSection*, bool thTagRequired);
- virtual bool computeAccessibilityIsIgnored() const OVERRIDE;
-};
-
-} // namespace WebCore
-
-#endif // AccessibilityTableColumn_h
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityTableHeaderContainer.cpp b/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityTableHeaderContainer.cpp
deleted file mode 100644
index ab946f28d2c..00000000000
--- a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityTableHeaderContainer.cpp
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * Copyright (C) 2008 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/accessibility/AccessibilityTableHeaderContainer.h"
-
-
-using namespace std;
-
-namespace WebCore {
-
-AccessibilityTableHeaderContainer::AccessibilityTableHeaderContainer()
-{
-}
-
-AccessibilityTableHeaderContainer::~AccessibilityTableHeaderContainer()
-{
-}
-
-PassRefPtr<AccessibilityTableHeaderContainer> AccessibilityTableHeaderContainer::create()
-{
- return adoptRef(new AccessibilityTableHeaderContainer());
-}
-
-LayoutRect AccessibilityTableHeaderContainer::elementRect() const
-{
- // this will be filled in when addChildren is called
- return m_headerRect;
-}
-
-bool AccessibilityTableHeaderContainer::computeAccessibilityIsIgnored() const
-{
- if (!m_parent)
- return true;
-
- return m_parent->accessibilityIsIgnored();
-}
-
-void AccessibilityTableHeaderContainer::addChildren()
-{
- ASSERT(!m_haveChildren);
-
- m_haveChildren = true;
- if (!m_parent || !m_parent->isAccessibilityTable())
- return;
-
- toAccessibilityTable(m_parent)->columnHeaders(m_children);
-
- unsigned length = m_children.size();
- for (unsigned k = 0; k < length; ++k)
- m_headerRect.unite(m_children[k]->elementRect());
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityTableHeaderContainer.h b/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityTableHeaderContainer.h
deleted file mode 100644
index 2fe679ad8bc..00000000000
--- a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityTableHeaderContainer.h
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Copyright (C) 2008 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef AccessibilityTableHeaderContainer_h
-#define AccessibilityTableHeaderContainer_h
-
-#include "core/accessibility/AccessibilityMockObject.h"
-#include "core/accessibility/AccessibilityTable.h"
-
-namespace WebCore {
-
-class AccessibilityTableHeaderContainer : public AccessibilityMockObject {
-
-private:
- AccessibilityTableHeaderContainer();
-public:
- static PassRefPtr<AccessibilityTableHeaderContainer> create();
- virtual ~AccessibilityTableHeaderContainer();
-
- virtual AccessibilityRole roleValue() const OVERRIDE { return TableHeaderContainerRole; }
-
- virtual void addChildren() OVERRIDE;
-
- virtual LayoutRect elementRect() const OVERRIDE;
-
-private:
- LayoutRect m_headerRect;
-
- virtual bool computeAccessibilityIsIgnored() const OVERRIDE;
-};
-
-} // namespace WebCore
-
-#endif // AccessibilityTableHeaderContainer_h
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityTableRow.cpp b/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityTableRow.cpp
deleted file mode 100644
index 89da3f7963f..00000000000
--- a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityTableRow.cpp
+++ /dev/null
@@ -1,132 +0,0 @@
-/*
- * Copyright (C) 2008 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/accessibility/AccessibilityTableRow.h"
-
-#include "core/accessibility/AccessibilityTableCell.h"
-#include "core/rendering/RenderTableRow.h"
-
-using namespace std;
-
-namespace WebCore {
-
-using namespace HTMLNames;
-
-AccessibilityTableRow::AccessibilityTableRow(RenderObject* renderer)
- : AccessibilityRenderObject(renderer)
-{
-}
-
-AccessibilityTableRow::~AccessibilityTableRow()
-{
-}
-
-PassRefPtr<AccessibilityTableRow> AccessibilityTableRow::create(RenderObject* renderer)
-{
- return adoptRef(new AccessibilityTableRow(renderer));
-}
-
-AccessibilityRole AccessibilityTableRow::determineAccessibilityRole()
-{
- if (!isTableRow())
- return AccessibilityRenderObject::determineAccessibilityRole();
-
- m_ariaRole = determineAriaRoleAttribute();
-
- AccessibilityRole ariaRole = ariaRoleAttribute();
- if (ariaRole != UnknownRole)
- return ariaRole;
-
- return RowRole;
-}
-
-bool AccessibilityTableRow::isTableRow() const
-{
- AccessibilityObject* table = parentTable();
- if (!table || !table->isAccessibilityTable())
- return false;
-
- return true;
-}
-
-AccessibilityObject* AccessibilityTableRow::observableObject() const
-{
- // This allows the table to be the one who sends notifications about tables.
- return parentTable();
-}
-
-bool AccessibilityTableRow::computeAccessibilityIsIgnored() const
-{
- AccessibilityObjectInclusion decision = defaultObjectInclusion();
- if (decision == IncludeObject)
- return false;
- if (decision == IgnoreObject)
- return true;
-
- if (!isTableRow())
- return AccessibilityRenderObject::computeAccessibilityIsIgnored();
-
- return false;
-}
-
-AccessibilityObject* AccessibilityTableRow::parentTable() const
-{
- AccessibilityObject* parent = parentObjectUnignored();
- if (!parent || !parent->isAccessibilityTable())
- return 0;
-
- return parent;
-}
-
-AccessibilityObject* AccessibilityTableRow::headerObject()
-{
- if (!m_renderer || !m_renderer->isTableRow())
- return 0;
-
- AccessibilityChildrenVector rowChildren = children();
- if (!rowChildren.size())
- return 0;
-
- // check the first element in the row to see if it is a TH element
- AccessibilityObject* cell = rowChildren[0].get();
- if (!cell->isTableCell())
- return 0;
-
- RenderObject* cellRenderer = static_cast<AccessibilityTableCell*>(cell)->renderer();
- if (!cellRenderer)
- return 0;
-
- Node* cellNode = cellRenderer->node();
- if (!cellNode || !cellNode->hasTagName(thTag))
- return 0;
-
- return cell;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityTableRow.h b/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityTableRow.h
deleted file mode 100644
index 3f9faa9f0c3..00000000000
--- a/chromium/third_party/WebKit/Source/core/accessibility/AccessibilityTableRow.h
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * Copyright (C) 2008 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef AccessibilityTableRow_h
-#define AccessibilityTableRow_h
-
-#include "core/accessibility/AccessibilityRenderObject.h"
-
-namespace WebCore {
-
-class AccessibilityTableRow : public AccessibilityRenderObject {
-
-protected:
- explicit AccessibilityTableRow(RenderObject*);
-public:
- static PassRefPtr<AccessibilityTableRow> create(RenderObject*);
- virtual ~AccessibilityTableRow();
-
- virtual bool isTableRow() const OVERRIDE;
-
- // retrieves the "row" header (a th tag in the rightmost column)
- virtual AccessibilityObject* headerObject();
- virtual AccessibilityObject* parentTable() const;
-
- void setRowIndex(int rowIndex) { m_rowIndex = rowIndex; }
- int rowIndex() const { return m_rowIndex; }
-
- // allows the table to add other children that may not originate
- // in the row, but their col/row spans overlap into it
- void appendChild(AccessibilityObject*);
-
-protected:
- virtual AccessibilityRole determineAccessibilityRole() OVERRIDE;
-
-private:
- int m_rowIndex;
-
- virtual AccessibilityObject* observableObject() const OVERRIDE;
- virtual bool computeAccessibilityIsIgnored() const OVERRIDE;
-};
-
-} // namespace WebCore
-
-#endif // AccessibilityTableRow_h
diff --git a/chromium/third_party/WebKit/Source/core/animation/ActiveAnimations.cpp b/chromium/third_party/WebKit/Source/core/animation/ActiveAnimations.cpp
new file mode 100644
index 00000000000..d27161d6a10
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/animation/ActiveAnimations.cpp
@@ -0,0 +1,101 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/animation/ActiveAnimations.h"
+
+#include "core/frame/animation/AnimationController.h"
+#include "core/rendering/RenderObject.h"
+
+namespace WebCore {
+
+bool shouldCompositeForActiveAnimations(const RenderObject& renderer)
+{
+ ASSERT(RuntimeEnabledFeatures::webAnimationsCSSEnabled());
+
+ if (!renderer.node() || !renderer.node()->isElementNode())
+ return false;
+
+ const Element* element = toElement(renderer.node());
+ if (const ActiveAnimations* activeAnimations = element->activeAnimations()) {
+ if (activeAnimations->hasActiveAnimations(CSSPropertyOpacity)
+ || activeAnimations->hasActiveAnimations(CSSPropertyWebkitTransform)
+ || activeAnimations->hasActiveAnimations(CSSPropertyWebkitFilter))
+ return true;
+ }
+
+ return false;
+}
+
+bool hasActiveAnimations(const RenderObject& renderer, CSSPropertyID property)
+{
+ ASSERT(RuntimeEnabledFeatures::webAnimationsCSSEnabled());
+
+ if (!renderer.node() || !renderer.node()->isElementNode())
+ return false;
+
+ const Element* element = toElement(renderer.node());
+ if (const ActiveAnimations* activeAnimations = element->activeAnimations())
+ return activeAnimations->hasActiveAnimations(property);
+
+ return false;
+}
+
+bool hasActiveAnimationsOnCompositor(const RenderObject& renderer, CSSPropertyID property)
+{
+ ASSERT(RuntimeEnabledFeatures::webAnimationsCSSEnabled());
+
+ if (!renderer.node() || !renderer.node()->isElementNode())
+ return false;
+
+ const Element* element = toElement(renderer.node());
+ if (const ActiveAnimations* activeAnimations = element->activeAnimations())
+ return activeAnimations->hasActiveAnimationsOnCompositor(property);
+
+ return false;
+}
+
+bool ActiveAnimations::hasActiveAnimations(CSSPropertyID property) const
+{
+ return m_defaultStack.affects(property);
+}
+
+bool ActiveAnimations::hasActiveAnimationsOnCompositor(CSSPropertyID property) const
+{
+ return m_defaultStack.hasActiveAnimationsOnCompositor(property);
+}
+
+void ActiveAnimations::cancelAnimationOnCompositor()
+{
+ for (PlayerSet::iterator it = m_players.begin(); it != players().end(); ++it)
+ it->key->cancelAnimationOnCompositor();
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/animation/ActiveAnimations.h b/chromium/third_party/WebKit/Source/core/animation/ActiveAnimations.h
index b57283b7706..b12a9bf95dd 100644
--- a/chromium/third_party/WebKit/Source/core/animation/ActiveAnimations.h
+++ b/chromium/third_party/WebKit/Source/core/animation/ActiveAnimations.h
@@ -33,28 +33,59 @@
#include "core/animation/AnimationStack.h"
#include "core/animation/css/CSSAnimations.h"
+#include "wtf/HashCountedSet.h"
#include "wtf/HashMap.h"
#include "wtf/RefPtr.h"
#include "wtf/Vector.h"
namespace WebCore {
+class CSSAnimations;
+class RenderObject;
+class Element;
+
+// FIXME: Move these to CompositorAnimations
+bool shouldCompositeForActiveAnimations(const RenderObject&);
+bool hasActiveAnimations(const RenderObject&, CSSPropertyID);
+bool hasActiveAnimationsOnCompositor(const RenderObject&, CSSPropertyID);
+
class ActiveAnimations {
public:
+ ActiveAnimations()
+ : m_animationStyleChange(false) { }
+
// Animations that are currently active for this element, their effects will be applied
- // during a style recalc.
- AnimationStack* defaultStack() { return &m_defaultStack; }
- // Tracks the state of active CSS Animations. The individual animations will also be
- // part of the default stack, but the mapping betwen animation name and player is kept
- // here.
- CSSAnimations* cssAnimations() { return &m_cssAnimations; }
- // FIXME: Add AnimationStack for CSS Transitions
- // CSS Transitions form a separate animation stack as they apply at a different level of
- // the style cascade. Active transitions will not be present in the default stack.
+ // during a style recalc. CSS Transitions are included in this stack.
+ AnimationStack& defaultStack() { return m_defaultStack; }
+ // Tracks the state of active CSS Animations and Transitions. The individual animations
+ // will also be part of the default stack, but the mapping betwen animation name and
+ // player is kept here.
+ CSSAnimations& cssAnimations() { return m_cssAnimations; }
+ const CSSAnimations& cssAnimations() const { return m_cssAnimations; }
+
+ typedef HashCountedSet<Player*> PlayerSet;
+ // Players which have animations targeting this element.
+ const PlayerSet& players() const { return m_players; }
+ PlayerSet& players() { return m_players; }
+
bool isEmpty() const { return m_defaultStack.isEmpty() && m_cssAnimations.isEmpty(); }
+
+ bool hasActiveAnimations(CSSPropertyID) const;
+ bool hasActiveAnimationsOnCompositor(CSSPropertyID) const;
+ void cancelAnimationOnCompositor();
+
+ void setAnimationStyleChange(bool animationStyleChange) { m_animationStyleChange = animationStyleChange; }
+
private:
+ bool isAnimationStyleChange() const { return m_animationStyleChange; }
+
AnimationStack m_defaultStack;
CSSAnimations m_cssAnimations;
+ PlayerSet m_players;
+ bool m_animationStyleChange;
+
+ // CSSAnimations checks if a style change is due to animation.
+ friend class CSSAnimations;
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/animation/AnimatableClipPathOperation.cpp b/chromium/third_party/WebKit/Source/core/animation/AnimatableClipPathOperation.cpp
new file mode 100644
index 00000000000..f539df4d1fb
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/animation/AnimatableClipPathOperation.cpp
@@ -0,0 +1,58 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/animation/AnimatableClipPathOperation.h"
+
+namespace WebCore {
+
+PassRefPtr<AnimatableValue> AnimatableClipPathOperation::interpolateTo(const AnimatableValue* value, double fraction) const
+{
+ const AnimatableClipPathOperation* toOperation = toAnimatableClipPathOperation(value);
+
+ if (m_operation->type() != ClipPathOperation::SHAPE || toOperation->m_operation->type() != ClipPathOperation::SHAPE)
+ return defaultInterpolateTo(this, value, fraction);
+
+ const BasicShape* fromShape = toShapeClipPathOperation(clipPathOperation())->basicShape();
+ const BasicShape* toShape = toShapeClipPathOperation(toOperation->clipPathOperation())->basicShape();
+
+ if (!fromShape->canBlend(toShape))
+ return defaultInterpolateTo(this, value, fraction);
+
+ return AnimatableClipPathOperation::create(ShapeClipPathOperation::create(toShape->blend(fromShape, fraction)).get());
+}
+
+bool AnimatableClipPathOperation::equalTo(const AnimatableValue* value) const
+{
+ const ClipPathOperation* operation = toAnimatableClipPathOperation(value)->m_operation.get();
+ return m_operation == operation || (m_operation && operation && *m_operation == *operation);
+}
+
+}
diff --git a/chromium/third_party/WebKit/Source/core/animation/AnimatableClipPathOperation.h b/chromium/third_party/WebKit/Source/core/animation/AnimatableClipPathOperation.h
new file mode 100644
index 00000000000..0a2401f2bdb
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/animation/AnimatableClipPathOperation.h
@@ -0,0 +1,67 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef AnimatableClipPathOperation_h
+#define AnimatableClipPathOperation_h
+
+#include "core/animation/AnimatableValue.h"
+#include "core/rendering/ClipPathOperation.h"
+
+namespace WebCore {
+
+class AnimatableClipPathOperation : public AnimatableValue {
+public:
+ virtual ~AnimatableClipPathOperation() { }
+ static PassRefPtr<AnimatableClipPathOperation> create(ClipPathOperation* operation)
+ {
+ return adoptRef(new AnimatableClipPathOperation(operation));
+ }
+ ClipPathOperation* clipPathOperation() const { return m_operation.get(); }
+
+protected:
+ virtual PassRefPtr<AnimatableValue> interpolateTo(const AnimatableValue*, double fraction) const OVERRIDE;
+
+private:
+ AnimatableClipPathOperation(ClipPathOperation* operation)
+ : m_operation(operation)
+ {
+ ASSERT(m_operation);
+ }
+ virtual AnimatableType type() const OVERRIDE { return TypeClipPathOperation; }
+ virtual bool equalTo(const AnimatableValue*) const OVERRIDE;
+
+ RefPtr<ClipPathOperation> m_operation;
+};
+
+DEFINE_ANIMATABLE_VALUE_TYPE_CASTS(AnimatableClipPathOperation, isClipPathOperation());
+
+} // namespace WebCore
+
+#endif // AnimatableClipPathOperation_h
diff --git a/chromium/third_party/WebKit/Source/core/animation/AnimatableColor.cpp b/chromium/third_party/WebKit/Source/core/animation/AnimatableColor.cpp
index c1da47b90df..d501a81f4c1 100644
--- a/chromium/third_party/WebKit/Source/core/animation/AnimatableColor.cpp
+++ b/chromium/third_party/WebKit/Source/core/animation/AnimatableColor.cpp
@@ -31,7 +31,7 @@
#include "config.h"
#include "core/animation/AnimatableColor.h"
-#include "core/platform/animation/AnimationUtilities.h"
+#include "platform/animation/AnimationUtilities.h"
#include "wtf/MathExtras.h"
namespace WebCore {
@@ -55,7 +55,7 @@ AnimatableColorImpl::AnimatableColorImpl(Color color)
Color AnimatableColorImpl::toColor() const
{
if (!m_alpha)
- return Color();
+ return Color::transparent;
return Color(m_red / m_alpha, m_green / m_alpha, m_blue / m_alpha, m_alpha);
}
@@ -75,6 +75,14 @@ AnimatableColorImpl AnimatableColorImpl::addWith(const AnimatableColorImpl& adde
m_alpha + addend.m_alpha);
}
+bool AnimatableColorImpl::operator==(const AnimatableColorImpl& other) const
+{
+ return m_red == other.m_red
+ && m_green == other.m_green
+ && m_blue == other.m_blue
+ && m_alpha == other.m_alpha;
+}
+
PassRefPtr<AnimatableColor> AnimatableColor::create(const AnimatableColorImpl& color, const AnimatableColorImpl& visitedLinkColor)
{
return adoptRef(new AnimatableColor(color, visitedLinkColor));
@@ -94,4 +102,10 @@ PassRefPtr<AnimatableValue> AnimatableColor::addWith(const AnimatableValue* valu
m_visitedLinkColor.addWith(color->m_visitedLinkColor));
}
+bool AnimatableColor::equalTo(const AnimatableValue* value) const
+{
+ const AnimatableColor* color = toAnimatableColor(value);
+ return m_color == color->m_color && m_visitedLinkColor == color->m_visitedLinkColor;
+}
+
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/animation/AnimatableColor.h b/chromium/third_party/WebKit/Source/core/animation/AnimatableColor.h
index 63db66783ff..57c8fd3cfeb 100644
--- a/chromium/third_party/WebKit/Source/core/animation/AnimatableColor.h
+++ b/chromium/third_party/WebKit/Source/core/animation/AnimatableColor.h
@@ -32,7 +32,7 @@
#define AnimatableColor_h
#include "core/animation/AnimatableValue.h"
-#include "core/platform/graphics/Color.h"
+#include "platform/graphics/Color.h"
namespace WebCore {
@@ -43,6 +43,7 @@ public:
Color toColor() const;
AnimatableColorImpl interpolateTo(const AnimatableColorImpl&, double fraction) const;
AnimatableColorImpl addWith(const AnimatableColorImpl&) const;
+ bool operator==(const AnimatableColorImpl&) const;
private:
float m_alpha;
@@ -51,30 +52,33 @@ private:
float m_blue;
};
+// This class handles both the regular and 'visted link' colors for a given
+// property. Currently it is used for all properties, even those which do not
+// support a separate 'visited link' color (eg SVG properties). This is correct
+// but inefficient.
class AnimatableColor : public AnimatableValue {
public:
static PassRefPtr<AnimatableColor> create(const AnimatableColorImpl&, const AnimatableColorImpl& visitedLinkColor);
- virtual PassRefPtr<AnimatableValue> interpolateTo(const AnimatableValue*, double fraction) const OVERRIDE;
- virtual PassRefPtr<AnimatableValue> addWith(const AnimatableValue*) const OVERRIDE;
Color color() const { return m_color.toColor(); }
Color visitedLinkColor() const { return m_visitedLinkColor.toColor(); }
+protected:
+ virtual PassRefPtr<AnimatableValue> interpolateTo(const AnimatableValue*, double fraction) const OVERRIDE;
+ virtual PassRefPtr<AnimatableValue> addWith(const AnimatableValue*) const OVERRIDE;
+
private:
AnimatableColor(const AnimatableColorImpl& color, const AnimatableColorImpl& visitedLinkColor)
- : AnimatableValue(TypeColor)
- , m_color(color)
+ : m_color(color)
, m_visitedLinkColor(visitedLinkColor)
{
}
+ virtual AnimatableType type() const OVERRIDE { return TypeColor; }
+ virtual bool equalTo(const AnimatableValue*) const OVERRIDE;
const AnimatableColorImpl m_color;
const AnimatableColorImpl m_visitedLinkColor;
};
-inline const AnimatableColor* toAnimatableColor(const AnimatableValue* value)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(value && value->isColor());
- return static_cast<const AnimatableColor*>(value);
-}
+DEFINE_ANIMATABLE_VALUE_TYPE_CASTS(AnimatableColor, isColor());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/animation/AnimatableColorTest.cpp b/chromium/third_party/WebKit/Source/core/animation/AnimatableColorTest.cpp
index 452c1724fb6..1e6ae355430 100644
--- a/chromium/third_party/WebKit/Source/core/animation/AnimatableColorTest.cpp
+++ b/chromium/third_party/WebKit/Source/core/animation/AnimatableColorTest.cpp
@@ -37,7 +37,17 @@ using namespace WebCore;
namespace {
-TEST(AnimatableColorImpl, Interpolate)
+TEST(AnimationAnimatableColorTest, ToColor)
+{
+ Color transparent = AnimatableColorImpl(Color::transparent).toColor();
+ EXPECT_TRUE(transparent.isValid());
+ EXPECT_EQ(transparent.rgb(), Color::transparent);
+ Color red = AnimatableColorImpl(Color(0xFFFF0000)).toColor();
+ EXPECT_TRUE(red.isValid());
+ EXPECT_EQ(red.rgb(), 0xFFFF0000);
+}
+
+TEST(AnimationAnimatableColorTest, Interpolate)
{
EXPECT_EQ(AnimatableColorImpl(Color(0xFF00FF00)).interpolateTo(Color(0xFF00FF00), -10).toColor().rgb(), 0xFF00FF00);
EXPECT_EQ(AnimatableColorImpl(Color(0xFF00FF00)).interpolateTo(Color(0xFFFF00FF), -10).toColor().rgb(), 0xFF00FF00);
@@ -57,7 +67,7 @@ TEST(AnimatableColorImpl, Interpolate)
EXPECT_EQ(AnimatableColorImpl(Color(0x10204080)).interpolateTo(Color(0x104080C0), 0.5).toColor().rgb(), 0x103060A0u);
}
-TEST(AnimatableColorImpl, Add)
+TEST(AnimationAnimatableColorTest, Add)
{
EXPECT_EQ(AnimatableColorImpl(Color(0xFF012345)).addWith(Color(0xFF543210)).toColor().rgb(), 0xFF555555);
EXPECT_EQ(AnimatableColorImpl(Color(0xFF808080)).addWith(Color(0xFF808080)).toColor().rgb(), 0xFFFFFFFF);
diff --git a/chromium/third_party/WebKit/Source/core/animation/AnimatableDouble.cpp b/chromium/third_party/WebKit/Source/core/animation/AnimatableDouble.cpp
new file mode 100644
index 00000000000..0e6cc0e2851
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/animation/AnimatableDouble.cpp
@@ -0,0 +1,71 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/animation/AnimatableDouble.h"
+
+#include "core/css/CSSPrimitiveValue.h"
+#include "core/css/CSSValuePool.h"
+#include "platform/animation/AnimationUtilities.h"
+
+namespace WebCore {
+
+PassRefPtr<CSSValue> AnimatableDouble::toCSSValue() const
+{
+ return cssValuePool().createValue(m_number, CSSPrimitiveValue::CSS_NUMBER);
+}
+
+PassRefPtr<AnimatableValue> AnimatableDouble::interpolateTo(const AnimatableValue* value, double fraction) const
+{
+ const AnimatableDouble* other = toAnimatableDouble(value);
+ ASSERT(m_constraint == other->m_constraint);
+ if ((m_constraint == InterpolationIsNonContinuousWithZero) && (!m_number || !other->m_number))
+ return defaultInterpolateTo(this, value, fraction);
+ return AnimatableDouble::create(blend(m_number, other->m_number, fraction));
+}
+
+PassRefPtr<AnimatableValue> AnimatableDouble::addWith(const AnimatableValue* value) const
+{
+ // Optimization for adding with 0.
+ if (!m_number)
+ return takeConstRef(value);
+ const AnimatableDouble* other = toAnimatableDouble(value);
+ if (!other->m_number)
+ return takeConstRef(this);
+
+ return AnimatableDouble::create(m_number + other->m_number);
+}
+
+bool AnimatableDouble::equalTo(const AnimatableValue* value) const
+{
+ return m_number == toAnimatableDouble(value)->m_number;
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/animation/AnimatableDouble.h b/chromium/third_party/WebKit/Source/core/animation/AnimatableDouble.h
new file mode 100644
index 00000000000..b2b71165a6a
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/animation/AnimatableDouble.h
@@ -0,0 +1,77 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef AnimatableDouble_h
+#define AnimatableDouble_h
+
+#include "core/animation/AnimatableValue.h"
+#include "core/css/CSSValue.h"
+
+namespace WebCore {
+
+class AnimatableDouble : public AnimatableValue {
+public:
+ virtual ~AnimatableDouble() { }
+
+ enum Constraint {
+ Unconstrained,
+ InterpolationIsNonContinuousWithZero,
+ };
+
+ static PassRefPtr<AnimatableDouble> create(double number, Constraint constraint = Unconstrained)
+ {
+ return adoptRef(new AnimatableDouble(number, constraint));
+ }
+
+ PassRefPtr<CSSValue> toCSSValue() const;
+ double toDouble() const { return m_number; }
+
+protected:
+ virtual PassRefPtr<AnimatableValue> interpolateTo(const AnimatableValue*, double fraction) const OVERRIDE;
+ virtual PassRefPtr<AnimatableValue> addWith(const AnimatableValue*) const OVERRIDE;
+
+private:
+ AnimatableDouble(double number, Constraint constraint)
+ : m_number(number)
+ , m_constraint(constraint)
+ {
+ }
+ virtual AnimatableType type() const OVERRIDE { return TypeDouble; }
+ virtual bool equalTo(const AnimatableValue*) const OVERRIDE;
+
+ double m_number;
+ Constraint m_constraint;
+};
+
+DEFINE_ANIMATABLE_VALUE_TYPE_CASTS(AnimatableDouble, isDouble());
+
+} // namespace WebCore
+
+#endif // AnimatableDouble_h
diff --git a/chromium/third_party/WebKit/Source/core/animation/AnimatableDoubleTest.cpp b/chromium/third_party/WebKit/Source/core/animation/AnimatableDoubleTest.cpp
new file mode 100644
index 00000000000..ce8510bd544
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/animation/AnimatableDoubleTest.cpp
@@ -0,0 +1,91 @@
+/*
+ * Copyright (c) 2013, Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/animation/AnimatableDouble.h"
+
+#include "core/css/CSSPrimitiveValue.h"
+
+#include <gtest/gtest.h>
+
+using namespace WebCore;
+
+namespace {
+
+TEST(AnimationAnimatableDoubleTest, Create)
+{
+ EXPECT_TRUE(static_cast<bool>(AnimatableDouble::create(5).get()));
+ EXPECT_TRUE(static_cast<bool>(AnimatableDouble::create(10).get()));
+}
+
+TEST(AnimationAnimatableDoubleTest, Equal)
+{
+ EXPECT_TRUE(AnimatableDouble::create(10)->equals(AnimatableDouble::create(10).get()));
+ EXPECT_FALSE(AnimatableDouble::create(5)->equals(AnimatableDouble::create(10).get()));
+}
+
+TEST(AnimationAnimatableDoubleTest, ToCSSValue)
+{
+ RefPtr<CSSValue> cssValue5 = CSSPrimitiveValue::create(5, CSSPrimitiveValue::CSS_NUMBER);
+ RefPtr<CSSValue> cssValue10 = CSSPrimitiveValue::create(10, CSSPrimitiveValue::CSS_NUMBER);
+ EXPECT_TRUE(AnimatableDouble::create(5)->toCSSValue()->equals(*cssValue5.get()));
+ EXPECT_FALSE(AnimatableDouble::create(5)->toCSSValue()->equals(*cssValue10.get()));
+}
+
+TEST(AnimationAnimatableDoubleTest, ToDouble)
+{
+ EXPECT_EQ(5.9, AnimatableDouble::create(5.9)->toDouble());
+ EXPECT_EQ(-10, AnimatableDouble::create(-10)->toDouble());
+}
+
+
+TEST(AnimationAnimatableDoubleTest, Interpolate)
+{
+ RefPtr<AnimatableDouble> from10 = AnimatableDouble::create(10);
+ RefPtr<AnimatableDouble> to20 = AnimatableDouble::create(20);
+ EXPECT_EQ(5, toAnimatableDouble(AnimatableValue::interpolate(from10.get(), to20.get(), -0.5).get())->toDouble());
+ EXPECT_EQ(10, toAnimatableDouble(AnimatableValue::interpolate(from10.get(), to20.get(), 0).get())->toDouble());
+ EXPECT_EQ(14, toAnimatableDouble(AnimatableValue::interpolate(from10.get(), to20.get(), 0.4).get())->toDouble());
+ EXPECT_EQ(15, toAnimatableDouble(AnimatableValue::interpolate(from10.get(), to20.get(), 0.5).get())->toDouble());
+ EXPECT_EQ(16, toAnimatableDouble(AnimatableValue::interpolate(from10.get(), to20.get(), 0.6).get())->toDouble());
+ EXPECT_EQ(20, toAnimatableDouble(AnimatableValue::interpolate(from10.get(), to20.get(), 1).get())->toDouble());
+ EXPECT_EQ(25, toAnimatableDouble(AnimatableValue::interpolate(from10.get(), to20.get(), 1.5).get())->toDouble());
+}
+
+TEST(AnimationAnimatableDoubleTest, Add)
+{
+ EXPECT_EQ(-10, toAnimatableDouble(AnimatableValue::add(AnimatableDouble::create(-2).get(), AnimatableDouble::create(-8).get()).get())->toDouble());
+ EXPECT_EQ(0, toAnimatableDouble(AnimatableValue::add(AnimatableDouble::create(50).get(), AnimatableDouble::create(-50).get()).get())->toDouble());
+ EXPECT_EQ(10, toAnimatableDouble(AnimatableValue::add(AnimatableDouble::create(4).get(), AnimatableDouble::create(6).get()).get())->toDouble());
+ EXPECT_EQ(20, toAnimatableDouble(AnimatableValue::add(AnimatableDouble::create(0).get(), AnimatableDouble::create(20).get()).get())->toDouble());
+ EXPECT_EQ(30, toAnimatableDouble(AnimatableValue::add(AnimatableDouble::create(30).get(), AnimatableDouble::create(0).get()).get())->toDouble());
+}
+
+}
diff --git a/chromium/third_party/WebKit/Source/core/animation/AnimatableFilterOperations.cpp b/chromium/third_party/WebKit/Source/core/animation/AnimatableFilterOperations.cpp
new file mode 100644
index 00000000000..31edeabb24b
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/animation/AnimatableFilterOperations.cpp
@@ -0,0 +1,71 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/animation/AnimatableFilterOperations.h"
+
+#include <algorithm>
+
+namespace WebCore {
+
+PassRefPtr<AnimatableValue> AnimatableFilterOperations::interpolateTo(const AnimatableValue* value, double fraction) const
+{
+ const AnimatableFilterOperations* target = toAnimatableFilterOperations(value);
+ if (!operations().canInterpolateWith(target->operations()))
+ return defaultInterpolateTo(this, value, fraction);
+
+ FilterOperations result;
+ size_t fromSize = operations().size();
+ size_t toSize = target->operations().size();
+ size_t size = std::max(fromSize, toSize);
+ for (size_t i = 0; i < size; i++) {
+ FilterOperation* from = (i < fromSize) ? m_operations.operations()[i].get() : 0;
+ FilterOperation* to = (i < toSize) ? target->m_operations.operations()[i].get() : 0;
+ RefPtr<FilterOperation> blendedOp = FilterOperation::blend(from, to, fraction);
+ if (blendedOp)
+ result.operations().append(blendedOp);
+ else
+ ASSERT_NOT_REACHED();
+ }
+ return AnimatableFilterOperations::create(result);
+}
+
+PassRefPtr<AnimatableValue> AnimatableFilterOperations::addWith(const AnimatableValue* value) const
+{
+ ASSERT_WITH_MESSAGE(false, "Web Animations not yet implemented: AnimatableFilterOperations::addWith()");
+ return defaultAddWith(this, value);
+}
+
+bool AnimatableFilterOperations::equalTo(const AnimatableValue* value) const
+{
+ return operations() == toAnimatableFilterOperations(value)->operations();
+}
+
+}
diff --git a/chromium/third_party/WebKit/Source/core/animation/AnimatableFilterOperations.h b/chromium/third_party/WebKit/Source/core/animation/AnimatableFilterOperations.h
new file mode 100644
index 00000000000..17c694474ce
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/animation/AnimatableFilterOperations.h
@@ -0,0 +1,67 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef AnimatableFilterOperations_h
+#define AnimatableFilterOperations_h
+
+#include "core/animation/AnimatableValue.h"
+#include "platform/graphics/filters/FilterOperations.h"
+
+namespace WebCore {
+
+class AnimatableFilterOperations : public AnimatableValue {
+public:
+ virtual ~AnimatableFilterOperations() { }
+ static PassRefPtr<AnimatableFilterOperations> create(const FilterOperations& operations)
+ {
+ return adoptRef(new AnimatableFilterOperations(operations));
+ }
+ const FilterOperations& operations() const { return m_operations; }
+
+protected:
+ virtual PassRefPtr<AnimatableValue> interpolateTo(const AnimatableValue*, double fraction) const OVERRIDE;
+ virtual PassRefPtr<AnimatableValue> addWith(const AnimatableValue*) const OVERRIDE;
+
+private:
+ AnimatableFilterOperations(const FilterOperations& operations)
+ : m_operations(operations)
+ {
+ }
+ virtual bool equalTo(const AnimatableValue*) const OVERRIDE;
+ virtual AnimatableType type() const OVERRIDE { return TypeFilterOperations; }
+
+ FilterOperations m_operations;
+};
+
+DEFINE_ANIMATABLE_VALUE_TYPE_CASTS(AnimatableFilterOperations, isFilterOperations());
+
+} // namespace WebCore
+
+#endif // AnimatableFilterOperations_h
diff --git a/chromium/third_party/WebKit/Source/core/animation/AnimatableImage.cpp b/chromium/third_party/WebKit/Source/core/animation/AnimatableImage.cpp
index 3eaf0c76386..eee86c39987 100644
--- a/chromium/third_party/WebKit/Source/core/animation/AnimatableImage.cpp
+++ b/chromium/third_party/WebKit/Source/core/animation/AnimatableImage.cpp
@@ -39,15 +39,23 @@ namespace WebCore {
PassRefPtr<AnimatableValue> AnimatableImage::interpolateTo(const AnimatableValue* value, double fraction) const
{
- const AnimatableImage* image = toAnimatableImage(value);
+ if (fraction <= 0 || fraction >= 1)
+ return defaultInterpolateTo(this, value, fraction);
RefPtr<CSSValue> fromValue = this->toCSSValue();
+ // FIXME: Once cross-fade works on generated image types, remove this check.
+ if (fromValue->isImageGeneratorValue())
+ return defaultInterpolateTo(this, value, fraction);
if (!fromValue->isImageValue() && !fromValue->isImageGeneratorValue()) {
if (!m_image->isImageResource())
return defaultInterpolateTo(this, value, fraction);
ImageResource* resource = static_cast<ImageResource*>(m_image->data());
fromValue = CSSImageValue::create(resource->url(), m_image.get());
}
+ const AnimatableImage* image = toAnimatableImage(value);
RefPtr<CSSValue> toValue = image->toCSSValue();
+ // FIXME: Once cross-fade works on generated image types, remove this check.
+ if (toValue->isImageGeneratorValue())
+ return defaultInterpolateTo(this, value, fraction);
if (!toValue->isImageValue() && !toValue->isImageGeneratorValue()) {
if (!image->m_image->isImageResource())
return defaultInterpolateTo(this, value, fraction);
@@ -55,7 +63,7 @@ PassRefPtr<AnimatableValue> AnimatableImage::interpolateTo(const AnimatableValue
toValue = CSSImageValue::create(resource->url(), image->m_image.get());
}
RefPtr<CSSCrossfadeValue> crossfadeValue = CSSCrossfadeValue::create(fromValue, toValue);
- crossfadeValue->setPercentage(CSSPrimitiveValue::create(clampTo<double>(fraction, 0.0, 1.0), CSSPrimitiveValue::CSS_NUMBER));
+ crossfadeValue->setPercentage(CSSPrimitiveValue::create(fraction, CSSPrimitiveValue::CSS_NUMBER));
return create(StyleGeneratedImage::create(crossfadeValue.get()).get());
}
@@ -65,4 +73,9 @@ PassRefPtr<AnimatableValue> AnimatableImage::addWith(const AnimatableValue* valu
return defaultAddWith(this, value);
}
+bool AnimatableImage::equalTo(const AnimatableValue* value) const
+{
+ return StyleImage::imagesEquivalent(m_image.get(), toAnimatableImage(value)->m_image.get());
+}
+
}
diff --git a/chromium/third_party/WebKit/Source/core/animation/AnimatableImage.h b/chromium/third_party/WebKit/Source/core/animation/AnimatableImage.h
index 81e24632f3c..40152f95c5e 100644
--- a/chromium/third_party/WebKit/Source/core/animation/AnimatableImage.h
+++ b/chromium/third_party/WebKit/Source/core/animation/AnimatableImage.h
@@ -53,20 +53,17 @@ protected:
private:
AnimatableImage(StyleImage* image)
- : AnimatableValue(TypeImage)
- , m_image(image)
+ : m_image(image)
{
ASSERT(m_image);
}
+ virtual AnimatableType type() const OVERRIDE { return TypeImage; }
+ virtual bool equalTo(const AnimatableValue*) const OVERRIDE;
const RefPtr<StyleImage> m_image;
};
-inline const AnimatableImage* toAnimatableImage(const AnimatableValue* value)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(value && value->isImage());
- return static_cast<const AnimatableImage*>(value);
-}
+DEFINE_ANIMATABLE_VALUE_TYPE_CASTS(AnimatableImage, isImage());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/animation/AnimatableLength.cpp b/chromium/third_party/WebKit/Source/core/animation/AnimatableLength.cpp
new file mode 100644
index 00000000000..38a46590dbb
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/animation/AnimatableLength.cpp
@@ -0,0 +1,241 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/animation/AnimatableLength.h"
+
+#include "core/css/CSSPrimitiveValueMappings.h"
+#include "platform/CalculationValue.h"
+#include "platform/animation/AnimationUtilities.h"
+
+namespace WebCore {
+
+PassRefPtr<AnimatableLength> AnimatableLength::create(CSSValue* value)
+{
+ ASSERT(canCreateFrom(value));
+ if (value->isPrimitiveValue()) {
+ CSSPrimitiveValue* primitiveValue = WebCore::toCSSPrimitiveValue(value);
+ const CSSCalcValue* calcValue = primitiveValue->cssCalcValue();
+ if (calcValue)
+ return create(calcValue->expressionNode(), primitiveValue);
+ NumberUnitType unitType;
+ bool isPrimitiveLength = primitiveUnitToNumberType(primitiveValue->primitiveType(), unitType);
+ ASSERT_UNUSED(isPrimitiveLength, isPrimitiveLength);
+ const double scale = CSSPrimitiveValue::conversionToCanonicalUnitsScaleFactor(primitiveValue->primitiveType());
+ return create(primitiveValue->getDoubleValue() * scale, unitType, primitiveValue);
+ }
+
+ if (value->isCalcValue())
+ return create(toCSSCalcValue(value)->expressionNode());
+
+ ASSERT_NOT_REACHED();
+ return 0;
+}
+
+bool AnimatableLength::canCreateFrom(const CSSValue* value)
+{
+ ASSERT(value);
+ if (value->isPrimitiveValue()) {
+ const CSSPrimitiveValue* primitiveValue = WebCore::toCSSPrimitiveValue(value);
+ if (primitiveValue->cssCalcValue())
+ return true;
+
+ NumberUnitType unitType;
+ // Only returns true if the type is a primitive length unit.
+ return primitiveUnitToNumberType(primitiveValue->primitiveType(), unitType);
+ }
+ return value->isCalcValue();
+}
+
+PassRefPtr<CSSValue> AnimatableLength::toCSSValue(NumberRange range) const
+{
+ return toCSSPrimitiveValue(range);
+}
+
+Length AnimatableLength::toLength(const CSSToLengthConversionData& conversionData, NumberRange range) const
+{
+ // Avoid creating a CSSValue in the common cases
+ if (m_unitType == UnitTypePixels)
+ return Length(clampedNumber(range) * conversionData.zoom(), Fixed);
+ if (m_unitType == UnitTypePercentage)
+ return Length(clampedNumber(range), Percent);
+
+ return toCSSPrimitiveValue(range)->convertToLength<AnyConversion>(conversionData);
+}
+
+PassRefPtr<AnimatableValue> AnimatableLength::interpolateTo(const AnimatableValue* value, double fraction) const
+{
+ const AnimatableLength* length = toAnimatableLength(value);
+ NumberUnitType type = commonUnitType(length);
+ if (type != UnitTypeCalc)
+ return AnimatableLength::create(blend(m_number, length->m_number, fraction), type);
+
+ // FIXME(crbug.com/168840): Support for viewport units in calc needs to be added before we can blend them with other units.
+ if (isViewportUnit() || length->isViewportUnit())
+ return defaultInterpolateTo(this, value, fraction);
+
+ return AnimatableLength::create(scale(1 - fraction).get(), length->scale(fraction).get());
+}
+
+PassRefPtr<AnimatableValue> AnimatableLength::addWith(const AnimatableValue* value) const
+{
+ // Optimization for adding with 0.
+ if (isUnitlessZero())
+ return takeConstRef(value);
+
+ const AnimatableLength* length = toAnimatableLength(value);
+ if (length->isUnitlessZero())
+ return takeConstRef(this);
+
+ NumberUnitType type = commonUnitType(length);
+ if (type != UnitTypeCalc)
+ return AnimatableLength::create(m_number + length->m_number, type);
+
+ return AnimatableLength::create(this, length);
+}
+
+bool AnimatableLength::equalTo(const AnimatableValue* value) const
+{
+ const AnimatableLength* length = toAnimatableLength(value);
+ if (m_unitType != length->m_unitType)
+ return false;
+ if (isCalc())
+ return m_calcExpression == length->m_calcExpression || m_calcExpression->equals(*length->m_calcExpression);
+ return m_number == length->m_number;
+}
+
+PassRefPtr<CSSCalcExpressionNode> AnimatableLength::toCSSCalcExpressionNode() const
+{
+ if (isCalc())
+ return m_calcExpression;
+ return CSSCalcValue::createExpressionNode(toCSSPrimitiveValue(AllValues), m_number == trunc(m_number));
+}
+
+static bool isCompatibleWithRange(const CSSPrimitiveValue* primitiveValue, NumberRange range)
+{
+ ASSERT(primitiveValue);
+ if (range == AllValues)
+ return true;
+ if (primitiveValue->isCalculated())
+ return primitiveValue->cssCalcValue()->permittedValueRange() == ValueRangeNonNegative;
+ return primitiveValue->getDoubleValue() >= 0;
+}
+
+PassRefPtr<CSSPrimitiveValue> AnimatableLength::toCSSPrimitiveValue(NumberRange range) const
+{
+ if (!m_cachedCSSPrimitiveValue || !isCompatibleWithRange(m_cachedCSSPrimitiveValue.get(), range)) {
+ if (isCalc())
+ m_cachedCSSPrimitiveValue = CSSPrimitiveValue::create(CSSCalcValue::create(m_calcExpression, range == AllValues ? ValueRangeAll : ValueRangeNonNegative));
+ else
+ m_cachedCSSPrimitiveValue = CSSPrimitiveValue::create(clampedNumber(range), static_cast<CSSPrimitiveValue::UnitTypes>(numberTypeToPrimitiveUnit(m_unitType)));
+ }
+ return m_cachedCSSPrimitiveValue;
+}
+
+PassRefPtr<AnimatableLength> AnimatableLength::scale(double factor) const
+{
+ if (isCalc()) {
+ return AnimatableLength::create(CSSCalcValue::createExpressionNode(
+ m_calcExpression,
+ CSSCalcValue::createExpressionNode(CSSPrimitiveValue::create(factor, CSSPrimitiveValue::CSS_NUMBER)),
+ CalcMultiply));
+ }
+ return AnimatableLength::create(m_number * factor, m_unitType);
+}
+
+bool AnimatableLength::primitiveUnitToNumberType(unsigned short primitiveUnit, NumberUnitType& numberType)
+{
+ switch (primitiveUnit) {
+ case CSSPrimitiveValue::CSS_PX:
+ case CSSPrimitiveValue::CSS_CM:
+ case CSSPrimitiveValue::CSS_MM:
+ case CSSPrimitiveValue::CSS_IN:
+ case CSSPrimitiveValue::CSS_PT:
+ case CSSPrimitiveValue::CSS_PC:
+ numberType = UnitTypePixels;
+ return true;
+ case CSSPrimitiveValue::CSS_EMS:
+ numberType = UnitTypeFontSize;
+ return true;
+ case CSSPrimitiveValue::CSS_EXS:
+ numberType = UnitTypeFontXSize;
+ return true;
+ case CSSPrimitiveValue::CSS_REMS:
+ numberType = UnitTypeRootFontSize;
+ return true;
+ case CSSPrimitiveValue::CSS_PERCENTAGE:
+ numberType = UnitTypePercentage;
+ return true;
+ case CSSPrimitiveValue::CSS_VW:
+ numberType = UnitTypeViewportWidth;
+ return true;
+ case CSSPrimitiveValue::CSS_VH:
+ numberType = UnitTypeViewportHeight;
+ return true;
+ case CSSPrimitiveValue::CSS_VMIN:
+ numberType = UnitTypeViewportMin;
+ return true;
+ case CSSPrimitiveValue::CSS_VMAX:
+ numberType = UnitTypeViewportMax;
+ return true;
+ default:
+ return false;
+ }
+}
+
+unsigned short AnimatableLength::numberTypeToPrimitiveUnit(NumberUnitType numberType)
+{
+ switch (numberType) {
+ case UnitTypePixels:
+ return CSSPrimitiveValue::CSS_PX;
+ case UnitTypeFontSize:
+ return CSSPrimitiveValue::CSS_EMS;
+ case UnitTypeFontXSize:
+ return CSSPrimitiveValue::CSS_EXS;
+ case UnitTypeRootFontSize:
+ return CSSPrimitiveValue::CSS_REMS;
+ case UnitTypePercentage:
+ return CSSPrimitiveValue::CSS_PERCENTAGE;
+ case UnitTypeViewportWidth:
+ return CSSPrimitiveValue::CSS_VW;
+ case UnitTypeViewportHeight:
+ return CSSPrimitiveValue::CSS_VH;
+ case UnitTypeViewportMin:
+ return CSSPrimitiveValue::CSS_VMIN;
+ case UnitTypeViewportMax:
+ return CSSPrimitiveValue::CSS_VMAX;
+ case UnitTypeCalc:
+ return CSSPrimitiveValue::CSS_UNKNOWN;
+ }
+ ASSERT_NOT_REACHED();
+ return CSSPrimitiveValue::CSS_UNKNOWN;
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/animation/AnimatableLength.h b/chromium/third_party/WebKit/Source/core/animation/AnimatableLength.h
new file mode 100644
index 00000000000..14745761248
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/animation/AnimatableLength.h
@@ -0,0 +1,166 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef AnimatableLength_h
+#define AnimatableLength_h
+
+#include "core/animation/AnimatableValue.h"
+#include "core/css/CSSCalculationValue.h"
+#include "core/css/CSSPrimitiveValue.h"
+#include "platform/Length.h"
+
+namespace WebCore {
+
+enum NumberRange {
+ AllValues,
+ NonNegativeValues,
+};
+
+// Handles animation of CSS length and percentage values including CSS calc.
+// See primitiveUnitToNumberType() for the list of supported units.
+// If created from a CSSPrimitiveValue this class will cache it to be returned in toCSSValue().
+class AnimatableLength : public AnimatableValue {
+public:
+ enum NumberUnitType {
+ UnitTypeCalc,
+ UnitTypePixels,
+ UnitTypePercentage,
+ UnitTypeFontSize,
+ UnitTypeFontXSize,
+ UnitTypeRootFontSize,
+ UnitTypeViewportWidth,
+ UnitTypeViewportHeight,
+ UnitTypeViewportMin,
+ UnitTypeViewportMax,
+ };
+
+ virtual ~AnimatableLength() { }
+ static bool canCreateFrom(const CSSValue*);
+ static PassRefPtr<AnimatableLength> create(CSSValue*);
+ static PassRefPtr<AnimatableLength> create(double number, NumberUnitType unitType, CSSPrimitiveValue* cssPrimitiveValue = 0)
+ {
+ return adoptRef(new AnimatableLength(number, unitType, cssPrimitiveValue));
+ }
+ static PassRefPtr<AnimatableLength> create(PassRefPtr<CSSCalcExpressionNode> calcExpression, CSSPrimitiveValue* cssPrimitiveValue = 0)
+ {
+ return adoptRef(new AnimatableLength(calcExpression, cssPrimitiveValue));
+ }
+ PassRefPtr<CSSValue> toCSSValue(NumberRange = AllValues) const;
+ Length toLength(const CSSToLengthConversionData&, NumberRange = AllValues) const;
+
+protected:
+ virtual PassRefPtr<AnimatableValue> interpolateTo(const AnimatableValue*, double fraction) const OVERRIDE;
+ virtual PassRefPtr<AnimatableValue> addWith(const AnimatableValue*) const OVERRIDE;
+
+private:
+ AnimatableLength(double number, NumberUnitType unitType, CSSPrimitiveValue* cssPrimitiveValue)
+ : m_number(number)
+ , m_unitType(unitType)
+ , m_cachedCSSPrimitiveValue(cssPrimitiveValue)
+ {
+ ASSERT(m_unitType != UnitTypeCalc);
+ }
+ AnimatableLength(PassRefPtr<CSSCalcExpressionNode> calcExpression, CSSPrimitiveValue* cssPrimitiveValue)
+ : m_unitType(UnitTypeCalc)
+ , m_calcExpression(calcExpression)
+ , m_cachedCSSPrimitiveValue(cssPrimitiveValue)
+ {
+ ASSERT(m_calcExpression);
+ }
+ virtual AnimatableType type() const OVERRIDE { return TypeLength; }
+ virtual bool equalTo(const AnimatableValue*) const OVERRIDE;
+
+ bool isCalc() const
+ {
+ return m_unitType == UnitTypeCalc;
+ }
+
+ bool isViewportUnit() const
+ {
+ return m_unitType == UnitTypeViewportWidth || m_unitType == UnitTypeViewportHeight || m_unitType == UnitTypeViewportMin || m_unitType == UnitTypeViewportMax;
+ }
+
+ static PassRefPtr<AnimatableLength> create(const AnimatableLength* leftAddend, const AnimatableLength* rightAddend)
+ {
+ ASSERT(leftAddend && rightAddend);
+ return create(CSSCalcValue::createExpressionNode(leftAddend->toCSSCalcExpressionNode(), rightAddend->toCSSCalcExpressionNode(), CalcAdd));
+ }
+
+ PassRefPtr<CSSPrimitiveValue> toCSSPrimitiveValue(NumberRange) const;
+ PassRefPtr<CSSCalcExpressionNode> toCSSCalcExpressionNode() const;
+
+ PassRefPtr<AnimatableLength> scale(double) const;
+ double clampedNumber(NumberRange range) const
+ {
+ ASSERT(!isCalc());
+ return (range == NonNegativeValues && m_number <= 0) ? 0 : m_number;
+ }
+
+ // Returns true and populates numberType, if primitiveUnit is a primitive length unit. Otherwise, returns false.
+ static bool primitiveUnitToNumberType(unsigned short primitiveUnit, NumberUnitType& numberType);
+
+ static unsigned short numberTypeToPrimitiveUnit(NumberUnitType numberType);
+
+ // Zero is effectively unitless, except in the case of percentage.
+ // http://www.w3.org/TR/css3-values/#calc-computed-value
+ // e.g. calc(100% - 100% + 1em) resolves to calc(0% + 1em), not to calc(1em)
+ bool isUnitlessZero() const
+ {
+ return !isCalc() && !m_number && m_unitType != UnitTypePercentage;
+ }
+
+ NumberUnitType commonUnitType(const AnimatableLength* length) const
+ {
+ if (m_unitType == length->m_unitType)
+ return m_unitType;
+
+ if (isUnitlessZero())
+ return length->m_unitType;
+ if (length->isUnitlessZero())
+ return m_unitType;
+
+ return UnitTypeCalc;
+ }
+
+ double m_number;
+ const NumberUnitType m_unitType;
+
+ RefPtr<CSSCalcExpressionNode> m_calcExpression;
+
+ mutable RefPtr<CSSPrimitiveValue> m_cachedCSSPrimitiveValue;
+
+ friend class AnimationAnimatableLengthTest;
+};
+
+DEFINE_ANIMATABLE_VALUE_TYPE_CASTS(AnimatableLength, isLength());
+
+} // namespace WebCore
+
+#endif // AnimatableLength_h
diff --git a/chromium/third_party/WebKit/Source/core/animation/AnimatableLengthBox.cpp b/chromium/third_party/WebKit/Source/core/animation/AnimatableLengthBox.cpp
index 489882605c3..825a1351655 100644
--- a/chromium/third_party/WebKit/Source/core/animation/AnimatableLengthBox.cpp
+++ b/chromium/third_party/WebKit/Source/core/animation/AnimatableLengthBox.cpp
@@ -53,4 +53,13 @@ PassRefPtr<AnimatableValue> AnimatableLengthBox::addWith(const AnimatableValue*
AnimatableValue::add(this->bottom(), lengthBox->bottom()));
}
+bool AnimatableLengthBox::equalTo(const AnimatableValue* value) const
+{
+ const AnimatableLengthBox* lengthBox = toAnimatableLengthBox(value);
+ return left()->equals(lengthBox->left())
+ && right()->equals(lengthBox->right())
+ && top()->equals(lengthBox->top())
+ && bottom()->equals(lengthBox->bottom());
+}
+
}
diff --git a/chromium/third_party/WebKit/Source/core/animation/AnimatableLengthBox.h b/chromium/third_party/WebKit/Source/core/animation/AnimatableLengthBox.h
index 1582e865237..b7ea5be5f6a 100644
--- a/chromium/third_party/WebKit/Source/core/animation/AnimatableLengthBox.h
+++ b/chromium/third_party/WebKit/Source/core/animation/AnimatableLengthBox.h
@@ -53,13 +53,14 @@ protected:
private:
AnimatableLengthBox(PassRefPtr<AnimatableValue> left, PassRefPtr<AnimatableValue> right, PassRefPtr<AnimatableValue> top, PassRefPtr<AnimatableValue> bottom)
- : AnimatableValue(TypeLengthBox)
- , m_left(left)
+ : m_left(left)
, m_right(right)
, m_top(top)
, m_bottom(bottom)
{
}
+ virtual AnimatableType type() const OVERRIDE { return TypeLengthBox; }
+ virtual bool equalTo(const AnimatableValue*) const OVERRIDE;
RefPtr<AnimatableValue> m_left;
RefPtr<AnimatableValue> m_right;
@@ -67,11 +68,7 @@ private:
RefPtr<AnimatableValue> m_bottom;
};
-inline const AnimatableLengthBox* toAnimatableLengthBox(const AnimatableValue* value)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(value && value->isLengthBox());
- return static_cast<const AnimatableLengthBox*>(value);
-}
+DEFINE_ANIMATABLE_VALUE_TYPE_CASTS(AnimatableLengthBox, isLengthBox());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/animation/AnimatableLengthBoxAndBool.cpp b/chromium/third_party/WebKit/Source/core/animation/AnimatableLengthBoxAndBool.cpp
new file mode 100644
index 00000000000..da92ac24181
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/animation/AnimatableLengthBoxAndBool.cpp
@@ -0,0 +1,64 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/animation/AnimatableLengthBoxAndBool.h"
+
+namespace WebCore {
+
+PassRefPtr<AnimatableValue> AnimatableLengthBoxAndBool::interpolateTo(const AnimatableValue* value, double fraction) const
+{
+ const AnimatableLengthBoxAndBool* lengthBox = toAnimatableLengthBoxAndBool(value);
+ if (lengthBox->flag() == flag()) {
+ return AnimatableLengthBoxAndBool::create(
+ AnimatableValue::interpolate(box(), lengthBox->box(), fraction),
+ flag());
+ }
+ return defaultInterpolateTo(this, value, fraction);
+}
+
+PassRefPtr<AnimatableValue> AnimatableLengthBoxAndBool::addWith(const AnimatableValue* value) const
+{
+ const AnimatableLengthBoxAndBool* lengthBox = toAnimatableLengthBoxAndBool(value);
+ if (lengthBox->flag() == flag()) {
+ return AnimatableLengthBoxAndBool::create(
+ AnimatableValue::add(box(), lengthBox->box()),
+ flag());
+ }
+ return defaultAddWith(this, value);
+}
+
+bool AnimatableLengthBoxAndBool::equalTo(const AnimatableValue* value) const
+{
+ const AnimatableLengthBoxAndBool* lengthBox = toAnimatableLengthBoxAndBool(value);
+ return box()->equals(lengthBox->box()) && flag() == lengthBox->flag();
+}
+
+}
diff --git a/chromium/third_party/WebKit/Source/core/animation/AnimatableLengthBoxAndBool.h b/chromium/third_party/WebKit/Source/core/animation/AnimatableLengthBoxAndBool.h
new file mode 100644
index 00000000000..9e3379791fd
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/animation/AnimatableLengthBoxAndBool.h
@@ -0,0 +1,69 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef AnimatableLengthBoxAndBool_h
+#define AnimatableLengthBoxAndBool_h
+
+#include "core/animation/AnimatableValue.h"
+
+namespace WebCore {
+
+class AnimatableLengthBoxAndBool : public AnimatableValue {
+public:
+ virtual ~AnimatableLengthBoxAndBool() { }
+ static PassRefPtr<AnimatableLengthBoxAndBool> create(PassRefPtr<AnimatableValue> box, bool flag)
+ {
+ return adoptRef(new AnimatableLengthBoxAndBool(box, flag));
+ }
+ const AnimatableValue* box() const { return m_box.get(); }
+ bool flag() const { return m_flag; }
+
+protected:
+ virtual PassRefPtr<AnimatableValue> interpolateTo(const AnimatableValue*, double fraction) const OVERRIDE;
+ virtual PassRefPtr<AnimatableValue> addWith(const AnimatableValue*) const OVERRIDE;
+
+private:
+ AnimatableLengthBoxAndBool(PassRefPtr<AnimatableValue> box, bool flag)
+ : m_box(box)
+ , m_flag(flag)
+ {
+ }
+ virtual AnimatableType type() const OVERRIDE { return TypeLengthBoxAndBool; }
+ virtual bool equalTo(const AnimatableValue*) const OVERRIDE;
+
+ RefPtr<AnimatableValue> m_box;
+ bool m_flag;
+};
+
+DEFINE_ANIMATABLE_VALUE_TYPE_CASTS(AnimatableLengthBoxAndBool, isLengthBoxAndBool());
+
+} // namespace WebCore
+
+#endif // AnimatableLengthBoxAndBool_h
diff --git a/chromium/third_party/WebKit/Source/core/animation/AnimatableLengthPoint.cpp b/chromium/third_party/WebKit/Source/core/animation/AnimatableLengthPoint.cpp
new file mode 100644
index 00000000000..e779699d93d
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/animation/AnimatableLengthPoint.cpp
@@ -0,0 +1,58 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/animation/AnimatableLengthPoint.h"
+
+namespace WebCore {
+
+PassRefPtr<AnimatableValue> AnimatableLengthPoint::interpolateTo(const AnimatableValue* value, double fraction) const
+{
+ const AnimatableLengthPoint* lengthPoint = toAnimatableLengthPoint(value);
+ return AnimatableLengthPoint::create(
+ AnimatableValue::interpolate(this->x(), lengthPoint->x(), fraction),
+ AnimatableValue::interpolate(this->y(), lengthPoint->y(), fraction));
+}
+
+PassRefPtr<AnimatableValue> AnimatableLengthPoint::addWith(const AnimatableValue* value) const
+{
+ const AnimatableLengthPoint* lengthPoint = toAnimatableLengthPoint(value);
+ return AnimatableLengthPoint::create(
+ AnimatableValue::add(this->x(), lengthPoint->x()),
+ AnimatableValue::add(this->y(), lengthPoint->y()));
+}
+
+bool AnimatableLengthPoint::equalTo(const AnimatableValue* value) const
+{
+ const AnimatableLengthPoint* lengthPoint = toAnimatableLengthPoint(value);
+ return x()->equals(lengthPoint->x()) && y()->equals(lengthPoint->y());
+}
+
+}
diff --git a/chromium/third_party/WebKit/Source/core/animation/AnimatableLengthPoint.h b/chromium/third_party/WebKit/Source/core/animation/AnimatableLengthPoint.h
new file mode 100644
index 00000000000..60b3e03f152
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/animation/AnimatableLengthPoint.h
@@ -0,0 +1,73 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef AnimatableLengthPoint_h
+#define AnimatableLengthPoint_h
+
+#include "core/animation/AnimatableValue.h"
+
+namespace WebCore {
+
+class AnimatableLengthPoint : public AnimatableValue {
+public:
+ virtual ~AnimatableLengthPoint() { }
+ static PassRefPtr<AnimatableLengthPoint> create(PassRefPtr<AnimatableValue> x, PassRefPtr<AnimatableValue> y)
+ {
+ return adoptRef(new AnimatableLengthPoint(x, y));
+ }
+ const AnimatableValue* x() const { return m_x.get(); }
+ const AnimatableValue* y() const { return m_y.get(); }
+
+protected:
+ virtual PassRefPtr<AnimatableValue> interpolateTo(const AnimatableValue*, double fraction) const OVERRIDE;
+ virtual PassRefPtr<AnimatableValue> addWith(const AnimatableValue*) const OVERRIDE;
+
+private:
+ AnimatableLengthPoint(PassRefPtr<AnimatableValue> x, PassRefPtr<AnimatableValue> y)
+ : m_x(x)
+ , m_y(y)
+ {
+ }
+ virtual AnimatableType type() const OVERRIDE { return TypeLengthPoint; }
+ virtual bool equalTo(const AnimatableValue*) const OVERRIDE;
+
+ RefPtr<AnimatableValue> m_x;
+ RefPtr<AnimatableValue> m_y;
+};
+
+inline const AnimatableLengthPoint* toAnimatableLengthPoint(const AnimatableValue* value)
+{
+ ASSERT_WITH_SECURITY_IMPLICATION(value && value->isLengthPoint());
+ return static_cast<const AnimatableLengthPoint*>(value);
+}
+
+} // namespace WebCore
+
+#endif // AnimatableLengthPoint_h
diff --git a/chromium/third_party/WebKit/Source/core/animation/AnimatableLengthSize.cpp b/chromium/third_party/WebKit/Source/core/animation/AnimatableLengthSize.cpp
new file mode 100644
index 00000000000..b422f39a931
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/animation/AnimatableLengthSize.cpp
@@ -0,0 +1,58 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/animation/AnimatableLengthSize.h"
+
+namespace WebCore {
+
+PassRefPtr<AnimatableValue> AnimatableLengthSize::interpolateTo(const AnimatableValue* value, double fraction) const
+{
+ const AnimatableLengthSize* lengthSize = toAnimatableLengthSize(value);
+ return AnimatableLengthSize::create(
+ AnimatableValue::interpolate(this->width(), lengthSize->width(), fraction),
+ AnimatableValue::interpolate(this->height(), lengthSize->height(), fraction));
+}
+
+PassRefPtr<AnimatableValue> AnimatableLengthSize::addWith(const AnimatableValue* value) const
+{
+ const AnimatableLengthSize* lengthSize = toAnimatableLengthSize(value);
+ return AnimatableLengthSize::create(
+ AnimatableValue::add(this->width(), lengthSize->width()),
+ AnimatableValue::add(this->height(), lengthSize->height()));
+}
+
+bool AnimatableLengthSize::equalTo(const AnimatableValue* value) const
+{
+ const AnimatableLengthSize* lengthSize = toAnimatableLengthSize(value);
+ return width()->equals(lengthSize->width()) && height()->equals(lengthSize->height());
+}
+
+}
diff --git a/chromium/third_party/WebKit/Source/core/animation/AnimatableLengthSize.h b/chromium/third_party/WebKit/Source/core/animation/AnimatableLengthSize.h
new file mode 100644
index 00000000000..55dcc4090d3
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/animation/AnimatableLengthSize.h
@@ -0,0 +1,69 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef AnimatableLengthSize_h
+#define AnimatableLengthSize_h
+
+#include "core/animation/AnimatableValue.h"
+
+namespace WebCore {
+
+class AnimatableLengthSize : public AnimatableValue {
+public:
+ virtual ~AnimatableLengthSize() { }
+ static PassRefPtr<AnimatableLengthSize> create(PassRefPtr<AnimatableValue> width, PassRefPtr<AnimatableValue> height)
+ {
+ return adoptRef(new AnimatableLengthSize(width, height));
+ }
+ const AnimatableValue* width() const { return m_width.get(); }
+ const AnimatableValue* height() const { return m_height.get(); }
+
+protected:
+ virtual PassRefPtr<AnimatableValue> interpolateTo(const AnimatableValue*, double fraction) const OVERRIDE;
+ virtual PassRefPtr<AnimatableValue> addWith(const AnimatableValue*) const OVERRIDE;
+
+private:
+ AnimatableLengthSize(PassRefPtr<AnimatableValue> width, PassRefPtr<AnimatableValue> height)
+ : m_width(width)
+ , m_height(height)
+ {
+ }
+ virtual AnimatableType type() const OVERRIDE { return TypeLengthSize; }
+ virtual bool equalTo(const AnimatableValue*) const OVERRIDE;
+
+ RefPtr<AnimatableValue> m_width;
+ RefPtr<AnimatableValue> m_height;
+};
+
+DEFINE_ANIMATABLE_VALUE_TYPE_CASTS(AnimatableLengthSize, isLengthSize());
+
+} // namespace WebCore
+
+#endif // AnimatableLengthSize_h
diff --git a/chromium/third_party/WebKit/Source/core/animation/AnimatableLengthTest.cpp b/chromium/third_party/WebKit/Source/core/animation/AnimatableLengthTest.cpp
new file mode 100644
index 00000000000..3574a66279b
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/animation/AnimatableLengthTest.cpp
@@ -0,0 +1,367 @@
+/*
+ * Copyright (c) 2013, Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+
+#include "core/animation/AnimatableLength.h"
+
+#include "core/animation/AnimatableValueTestHelper.h"
+#include "core/css/CSSCalculationValue.h"
+#include "core/css/CSSPrimitiveValue.h"
+#include "core/css/CSSToLengthConversionData.h"
+#include "core/rendering/style/RenderStyle.h"
+#include "core/rendering/style/StyleInheritedData.h"
+#include "platform/CalculationValue.h"
+#include "wtf/MathExtras.h"
+
+#include <gtest/gtest.h>
+
+#define EXPECT_ROUNDTRIP(a, f) EXPECT_REFV_EQ(a, f(a.get()))
+
+namespace WebCore {
+
+class AnimationAnimatableLengthTest : public ::testing::Test {
+protected:
+ AnimationAnimatableLengthTest()
+ : style(RenderStyle::createDefaultStyle())
+ , conversionDataZoom1(style.get(), style.get(), 1.0f)
+ , conversionDataZoom3(style.get(), style.get(), 3.0f)
+ {
+ }
+
+ PassRefPtr<AnimatableLength> create(double value, CSSPrimitiveValue::UnitTypes type)
+ {
+ return AnimatableLength::create(CSSPrimitiveValue::create(value, type).get());
+ }
+
+ PassRefPtr<AnimatableLength> create(double valueLeft, CSSPrimitiveValue::UnitTypes typeLeft, double valueRight, CSSPrimitiveValue::UnitTypes typeRight)
+ {
+ return AnimatableLength::create(createCalc(valueLeft, typeLeft, valueRight, typeRight).get());
+ }
+
+ PassRefPtr<CSSCalcValue> createCalc(double valueLeft, CSSPrimitiveValue::UnitTypes typeLeft, double valueRight, CSSPrimitiveValue::UnitTypes typeRight)
+ {
+ return CSSCalcValue::create(CSSCalcValue::createExpressionNode(
+ CSSCalcValue::createExpressionNode(CSSPrimitiveValue::create(valueLeft, typeLeft), valueLeft == trunc(valueLeft)),
+ CSSCalcValue::createExpressionNode(CSSPrimitiveValue::create(valueRight, typeRight), valueRight == trunc(valueRight)),
+ CalcAdd
+ ));
+ }
+
+ PassRefPtr<CSSValue> toCSSValue(CSSValue* cssValue)
+ {
+ return AnimatableLength::create(cssValue)->toCSSValue();
+ }
+
+ AnimatableLength::NumberUnitType commonUnitType(PassRefPtr<AnimatableLength> a, PassRefPtr<AnimatableLength> b)
+ {
+ return a->commonUnitType(b.get());
+ }
+
+ bool isUnitlessZero(PassRefPtr<AnimatableLength> a)
+ {
+ return a->isUnitlessZero();
+ }
+
+ RefPtr<RenderStyle> style;
+ CSSToLengthConversionData conversionDataZoom1;
+ CSSToLengthConversionData conversionDataZoom3;
+};
+
+TEST_F(AnimationAnimatableLengthTest, CanCreateFrom)
+{
+ EXPECT_TRUE(AnimatableLength::canCreateFrom(CSSPrimitiveValue::create(5, CSSPrimitiveValue::CSS_PX).get()));
+ EXPECT_TRUE(AnimatableLength::canCreateFrom(CSSPrimitiveValue::create(5, CSSPrimitiveValue::CSS_CM).get()));
+ EXPECT_TRUE(AnimatableLength::canCreateFrom(CSSPrimitiveValue::create(5, CSSPrimitiveValue::CSS_MM).get()));
+ EXPECT_TRUE(AnimatableLength::canCreateFrom(CSSPrimitiveValue::create(5, CSSPrimitiveValue::CSS_IN).get()));
+ EXPECT_TRUE(AnimatableLength::canCreateFrom(CSSPrimitiveValue::create(5, CSSPrimitiveValue::CSS_PT).get()));
+ EXPECT_TRUE(AnimatableLength::canCreateFrom(CSSPrimitiveValue::create(5, CSSPrimitiveValue::CSS_PC).get()));
+ EXPECT_TRUE(AnimatableLength::canCreateFrom(CSSPrimitiveValue::create(5, CSSPrimitiveValue::CSS_EMS).get()));
+ EXPECT_TRUE(AnimatableLength::canCreateFrom(CSSPrimitiveValue::create(5, CSSPrimitiveValue::CSS_EXS).get()));
+ EXPECT_TRUE(AnimatableLength::canCreateFrom(CSSPrimitiveValue::create(5, CSSPrimitiveValue::CSS_REMS).get()));
+ EXPECT_TRUE(AnimatableLength::canCreateFrom(CSSPrimitiveValue::create(5, CSSPrimitiveValue::CSS_PERCENTAGE).get()));
+ EXPECT_TRUE(AnimatableLength::canCreateFrom(CSSPrimitiveValue::create(5, CSSPrimitiveValue::CSS_VW).get()));
+ EXPECT_TRUE(AnimatableLength::canCreateFrom(CSSPrimitiveValue::create(5, CSSPrimitiveValue::CSS_VH).get()));
+ EXPECT_TRUE(AnimatableLength::canCreateFrom(CSSPrimitiveValue::create(5, CSSPrimitiveValue::CSS_VMIN).get()));
+ EXPECT_TRUE(AnimatableLength::canCreateFrom(CSSPrimitiveValue::create(5, CSSPrimitiveValue::CSS_VMAX).get()));
+
+ EXPECT_TRUE(AnimatableLength::canCreateFrom(createCalc(3, CSSPrimitiveValue::CSS_PX, 5, CSSPrimitiveValue::CSS_CM).get()));
+ EXPECT_TRUE(AnimatableLength::canCreateFrom(CSSPrimitiveValue::create(createCalc(3, CSSPrimitiveValue::CSS_PX, 5, CSSPrimitiveValue::CSS_CM)).get()));
+
+ EXPECT_FALSE(AnimatableLength::canCreateFrom(CSSPrimitiveValue::create("NaN", CSSPrimitiveValue::CSS_STRING).get()));
+}
+
+TEST_F(AnimationAnimatableLengthTest, Create)
+{
+ EXPECT_TRUE(static_cast<bool>(create(5, CSSPrimitiveValue::CSS_PX).get()));
+ EXPECT_TRUE(static_cast<bool>(create(5, CSSPrimitiveValue::CSS_CM).get()));
+ EXPECT_TRUE(static_cast<bool>(create(5, CSSPrimitiveValue::CSS_MM).get()));
+ EXPECT_TRUE(static_cast<bool>(create(5, CSSPrimitiveValue::CSS_IN).get()));
+ EXPECT_TRUE(static_cast<bool>(create(5, CSSPrimitiveValue::CSS_PT).get()));
+ EXPECT_TRUE(static_cast<bool>(create(5, CSSPrimitiveValue::CSS_PC).get()));
+ EXPECT_TRUE(static_cast<bool>(create(5, CSSPrimitiveValue::CSS_EMS).get()));
+ EXPECT_TRUE(static_cast<bool>(create(5, CSSPrimitiveValue::CSS_EXS).get()));
+ EXPECT_TRUE(static_cast<bool>(create(5, CSSPrimitiveValue::CSS_REMS).get()));
+ EXPECT_TRUE(static_cast<bool>(create(5, CSSPrimitiveValue::CSS_PERCENTAGE).get()));
+ EXPECT_TRUE(static_cast<bool>(create(5, CSSPrimitiveValue::CSS_VW).get()));
+ EXPECT_TRUE(static_cast<bool>(create(5, CSSPrimitiveValue::CSS_VH).get()));
+ EXPECT_TRUE(static_cast<bool>(create(5, CSSPrimitiveValue::CSS_VMIN).get()));
+ EXPECT_TRUE(static_cast<bool>(create(5, CSSPrimitiveValue::CSS_VMAX).get()));
+
+ EXPECT_TRUE(static_cast<bool>(
+ AnimatableLength::create(createCalc(3, CSSPrimitiveValue::CSS_PX, 5, CSSPrimitiveValue::CSS_CM).get()).get()
+ ));
+ EXPECT_TRUE(static_cast<bool>(
+ AnimatableLength::create(CSSPrimitiveValue::create(createCalc(3, CSSPrimitiveValue::CSS_PX, 5, CSSPrimitiveValue::CSS_CM)).get()).get()
+ ));
+}
+
+
+TEST_F(AnimationAnimatableLengthTest, ToCSSValue)
+{
+
+ EXPECT_ROUNDTRIP(CSSPrimitiveValue::create(-5, CSSPrimitiveValue::CSS_PX), toCSSValue);
+ EXPECT_ROUNDTRIP(CSSPrimitiveValue::create(-5, CSSPrimitiveValue::CSS_CM), toCSSValue);
+ EXPECT_ROUNDTRIP(CSSPrimitiveValue::create(-5, CSSPrimitiveValue::CSS_MM), toCSSValue);
+ EXPECT_ROUNDTRIP(CSSPrimitiveValue::create(-5, CSSPrimitiveValue::CSS_IN), toCSSValue);
+ EXPECT_ROUNDTRIP(CSSPrimitiveValue::create(-5, CSSPrimitiveValue::CSS_PT), toCSSValue);
+ EXPECT_ROUNDTRIP(CSSPrimitiveValue::create(-5, CSSPrimitiveValue::CSS_PC), toCSSValue);
+ EXPECT_ROUNDTRIP(CSSPrimitiveValue::create(-5, CSSPrimitiveValue::CSS_EMS), toCSSValue);
+ EXPECT_ROUNDTRIP(CSSPrimitiveValue::create(-5, CSSPrimitiveValue::CSS_EXS), toCSSValue);
+ EXPECT_ROUNDTRIP(CSSPrimitiveValue::create(-5, CSSPrimitiveValue::CSS_REMS), toCSSValue);
+ EXPECT_ROUNDTRIP(CSSPrimitiveValue::create(-5, CSSPrimitiveValue::CSS_PERCENTAGE), toCSSValue);
+ EXPECT_ROUNDTRIP(CSSPrimitiveValue::create(-5, CSSPrimitiveValue::CSS_VW), toCSSValue);
+ EXPECT_ROUNDTRIP(CSSPrimitiveValue::create(-5, CSSPrimitiveValue::CSS_VH), toCSSValue);
+ EXPECT_ROUNDTRIP(CSSPrimitiveValue::create(-5, CSSPrimitiveValue::CSS_VMIN), toCSSValue);
+ EXPECT_ROUNDTRIP(CSSPrimitiveValue::create(-5, CSSPrimitiveValue::CSS_VMAX), toCSSValue);
+
+ EXPECT_ROUNDTRIP(CSSPrimitiveValue::create(createCalc(3, CSSPrimitiveValue::CSS_PX, 5, CSSPrimitiveValue::CSS_IN)), toCSSValue);
+ EXPECT_ROUNDTRIP(CSSPrimitiveValue::create(createCalc(3, CSSPrimitiveValue::CSS_PX, 5, CSSPrimitiveValue::CSS_IN)), toCSSValue);
+}
+
+
+TEST_F(AnimationAnimatableLengthTest, ToLength)
+{
+ EXPECT_EQ(Length(-5, WebCore::Fixed), create(-5, CSSPrimitiveValue::CSS_PX)->toLength(conversionDataZoom1));
+ EXPECT_EQ(Length(-15, WebCore::Fixed), create(-5, CSSPrimitiveValue::CSS_PX)->toLength(conversionDataZoom3));
+ EXPECT_EQ(Length(0, WebCore::Fixed), create(-5, CSSPrimitiveValue::CSS_PX)->toLength(conversionDataZoom1, NonNegativeValues));
+ EXPECT_EQ(Length(0, WebCore::Fixed), create(-5, CSSPrimitiveValue::CSS_PX)->toLength(conversionDataZoom3, NonNegativeValues));
+
+ EXPECT_EQ(Length(-5, Percent), create(-5, CSSPrimitiveValue::CSS_PERCENTAGE)->toLength(conversionDataZoom1));
+ EXPECT_EQ(Length(-5, Percent), create(-5, CSSPrimitiveValue::CSS_PERCENTAGE)->toLength(conversionDataZoom3));
+ EXPECT_EQ(Length(0, Percent), create(-5, CSSPrimitiveValue::CSS_PERCENTAGE)->toLength(conversionDataZoom1, NonNegativeValues));
+ EXPECT_EQ(Length(0, Percent), create(-5, CSSPrimitiveValue::CSS_PERCENTAGE)->toLength(conversionDataZoom3, NonNegativeValues));
+
+ EXPECT_EQ(
+ Length(CalculationValue::create(
+ adoptPtr(new CalcExpressionBinaryOperation(
+ adoptPtr(new CalcExpressionLength(Length(-5, WebCore::Fixed))),
+ adoptPtr(new CalcExpressionLength(Length(-5, Percent))),
+ CalcAdd)),
+ ValueRangeAll)),
+ create(-5, CSSPrimitiveValue::CSS_PX, -5, CSSPrimitiveValue::CSS_PERCENTAGE)->toLength(conversionDataZoom1));
+ EXPECT_EQ(
+ Length(CalculationValue::create(
+ adoptPtr(new CalcExpressionBinaryOperation(
+ adoptPtr(new CalcExpressionLength(Length(-15, WebCore::Fixed))),
+ adoptPtr(new CalcExpressionLength(Length(-5, Percent))),
+ CalcAdd)),
+ ValueRangeAll)),
+ create(-5, CSSPrimitiveValue::CSS_PX, -5, CSSPrimitiveValue::CSS_PERCENTAGE)->toLength(conversionDataZoom3));
+ EXPECT_EQ(
+ Length(CalculationValue::create(
+ adoptPtr(new CalcExpressionBinaryOperation(
+ adoptPtr(new CalcExpressionLength(Length(-5, WebCore::Fixed))),
+ adoptPtr(new CalcExpressionLength(Length(-5, Percent))),
+ CalcAdd)),
+ ValueRangeNonNegative)),
+ create(-5, CSSPrimitiveValue::CSS_PX, -5, CSSPrimitiveValue::CSS_PERCENTAGE)->toLength(conversionDataZoom1, NonNegativeValues));
+ EXPECT_EQ(
+ Length(CalculationValue::create(
+ adoptPtr(new CalcExpressionBinaryOperation(
+ adoptPtr(new CalcExpressionLength(Length(-15, WebCore::Fixed))),
+ adoptPtr(new CalcExpressionLength(Length(-5, Percent))),
+ CalcAdd)),
+ ValueRangeNonNegative)),
+ create(-5, CSSPrimitiveValue::CSS_PX, -5, CSSPrimitiveValue::CSS_PERCENTAGE)->toLength(conversionDataZoom3, NonNegativeValues));
+}
+
+TEST_F(AnimationAnimatableLengthTest, Interpolate)
+{
+ RefPtr<AnimatableLength> from10px = create(10, CSSPrimitiveValue::CSS_PX);
+ RefPtr<AnimatableLength> to20pxAsInches = create(20.0 / 96, CSSPrimitiveValue::CSS_IN);
+
+ EXPECT_REFV_EQ(create(5, CSSPrimitiveValue::CSS_PX),
+ AnimatableValue::interpolate(from10px.get(), to20pxAsInches.get(), -0.5));
+
+ EXPECT_REFV_EQ(create(10, CSSPrimitiveValue::CSS_PX),
+ AnimatableValue::interpolate(from10px.get(), to20pxAsInches.get(), 0));
+ EXPECT_REFV_EQ(create(14, CSSPrimitiveValue::CSS_PX),
+ AnimatableValue::interpolate(from10px.get(), to20pxAsInches.get(), 0.4));
+ EXPECT_REFV_EQ(create(15, CSSPrimitiveValue::CSS_PX),
+ AnimatableValue::interpolate(from10px.get(), to20pxAsInches.get(), 0.5));
+ EXPECT_REFV_EQ(create(16, CSSPrimitiveValue::CSS_PX),
+ AnimatableValue::interpolate(from10px.get(), to20pxAsInches.get(), 0.6));
+ EXPECT_REFV_EQ(create(20.0 / 96, CSSPrimitiveValue::CSS_IN),
+ AnimatableValue::interpolate(from10px.get(), to20pxAsInches.get(), 1));
+ EXPECT_REFV_EQ(create(25, CSSPrimitiveValue::CSS_PX),
+ AnimatableValue::interpolate(from10px.get(), to20pxAsInches.get(), 1.5));
+
+ RefPtr<AnimatableLength> from10em = create(10, CSSPrimitiveValue::CSS_EMS);
+ RefPtr<AnimatableLength> to20rem = create(20, CSSPrimitiveValue::CSS_REMS);
+ EXPECT_REFV_EQ(create(15, CSSPrimitiveValue::CSS_EMS, -10, CSSPrimitiveValue::CSS_REMS),
+ AnimatableValue::interpolate(from10em.get(), to20rem.get(), -0.5));
+ EXPECT_REFV_EQ(create(10, CSSPrimitiveValue::CSS_EMS),
+ AnimatableValue::interpolate(from10em.get(), to20rem.get(), 0));
+ EXPECT_REFV_EQ(create(6, CSSPrimitiveValue::CSS_EMS, 8, CSSPrimitiveValue::CSS_REMS),
+ AnimatableValue::interpolate(from10em.get(), to20rem.get(), 0.4));
+ EXPECT_REFV_EQ(create(5, CSSPrimitiveValue::CSS_EMS, 10, CSSPrimitiveValue::CSS_REMS),
+ AnimatableValue::interpolate(from10em.get(), to20rem.get(), 0.5));
+ EXPECT_REFV_EQ(create(4, CSSPrimitiveValue::CSS_EMS, 12, CSSPrimitiveValue::CSS_REMS),
+ AnimatableValue::interpolate(from10em.get(), to20rem.get(), 0.6));
+ EXPECT_REFV_EQ(create(20, CSSPrimitiveValue::CSS_REMS),
+ AnimatableValue::interpolate(from10em.get(), to20rem.get(), 1));
+ EXPECT_REFV_EQ(create(-5, CSSPrimitiveValue::CSS_EMS, 30, CSSPrimitiveValue::CSS_REMS),
+ AnimatableValue::interpolate(from10em.get(), to20rem.get(), 1.5));
+
+ // Zero values are typeless and hence we can don't get a calc
+ RefPtr<AnimatableLength> from0px = create(0, CSSPrimitiveValue::CSS_PX);
+ EXPECT_REFV_EQ(create(-10, CSSPrimitiveValue::CSS_REMS),
+ AnimatableValue::interpolate(from0px.get(), to20rem.get(), -0.5));
+ // At t=0, interpolate always returns the "from" value.
+ EXPECT_REFV_EQ(create(0, CSSPrimitiveValue::CSS_PX),
+ AnimatableValue::interpolate(from0px.get(), to20rem.get(), 0));
+ EXPECT_REFV_EQ(create(10, CSSPrimitiveValue::CSS_REMS),
+ AnimatableValue::interpolate(from0px.get(), to20rem.get(), 0.5));
+ EXPECT_REFV_EQ(create(20, CSSPrimitiveValue::CSS_REMS),
+ AnimatableValue::interpolate(from0px.get(), to20rem.get(), 1.0));
+ EXPECT_REFV_EQ(create(30, CSSPrimitiveValue::CSS_REMS),
+ AnimatableValue::interpolate(from0px.get(), to20rem.get(), 1.5));
+
+ // Except 0% which is special
+ RefPtr<AnimatableLength> from0percent = create(0, CSSPrimitiveValue::CSS_PERCENTAGE);
+ EXPECT_REFV_EQ(create(0, CSSPrimitiveValue::CSS_PERCENTAGE, -10, CSSPrimitiveValue::CSS_REMS),
+ AnimatableValue::interpolate(from0percent.get(), to20rem.get(), -0.5));
+ // At t=0, interpolate always returns the "from" value.
+ EXPECT_REFV_EQ(create(0, CSSPrimitiveValue::CSS_PERCENTAGE),
+ AnimatableValue::interpolate(from0percent.get(), to20rem.get(), 0));
+ EXPECT_REFV_EQ(create(0, CSSPrimitiveValue::CSS_PERCENTAGE, 10, CSSPrimitiveValue::CSS_REMS),
+ AnimatableValue::interpolate(from0percent.get(), to20rem.get(), 0.5));
+ // At t=1, interpolate always returns the "to" value.
+ EXPECT_REFV_EQ(create(20, CSSPrimitiveValue::CSS_REMS),
+ AnimatableValue::interpolate(from0percent.get(), to20rem.get(), 1.0));
+ EXPECT_REFV_EQ(create(0, CSSPrimitiveValue::CSS_PERCENTAGE, 30, CSSPrimitiveValue::CSS_REMS),
+ AnimatableValue::interpolate(from0percent.get(), to20rem.get(), 1.5));
+}
+
+TEST_F(AnimationAnimatableLengthTest, Add)
+{
+ EXPECT_REFV_EQ(create(10, CSSPrimitiveValue::CSS_PX),
+ AnimatableValue::add(create(10, CSSPrimitiveValue::CSS_PX).get(), create(0, CSSPrimitiveValue::CSS_MM).get()));
+ EXPECT_REFV_EQ(create(100, CSSPrimitiveValue::CSS_PX),
+ AnimatableValue::add(create(4, CSSPrimitiveValue::CSS_PX).get(), create(1, CSSPrimitiveValue::CSS_IN).get()));
+ EXPECT_REFV_EQ(
+ create(10, CSSPrimitiveValue::CSS_EMS, 20, CSSPrimitiveValue::CSS_REMS),
+ AnimatableValue::add(create(10, CSSPrimitiveValue::CSS_EMS).get(), create(20, CSSPrimitiveValue::CSS_REMS).get()));
+ EXPECT_REFV_EQ(
+ create(10, CSSPrimitiveValue::CSS_EMS),
+ AnimatableValue::add(create(10, CSSPrimitiveValue::CSS_EMS).get(), create(0, CSSPrimitiveValue::CSS_REMS).get()));
+ EXPECT_REFV_EQ(
+ create(20, CSSPrimitiveValue::CSS_REMS),
+ AnimatableValue::add(create(0, CSSPrimitiveValue::CSS_EMS).get(), create(20, CSSPrimitiveValue::CSS_REMS).get()));
+
+ // Check you actually get the reference back for zero optimization
+ RefPtr<AnimatableLength> rems20 = create(20, CSSPrimitiveValue::CSS_REMS);
+ EXPECT_EQ(rems20.get(), AnimatableValue::add(create(0, CSSPrimitiveValue::CSS_EMS).get(), rems20.get()).get());
+ EXPECT_EQ(rems20.get(), AnimatableValue::add(rems20.get(), create(0, CSSPrimitiveValue::CSS_EMS).get()).get());
+
+ // Except 0% which is special
+ RefPtr<AnimatableLength> zeropercent = create(0, CSSPrimitiveValue::CSS_PERCENTAGE);
+ EXPECT_REFV_EQ(create(0, CSSPrimitiveValue::CSS_PERCENTAGE, -10, CSSPrimitiveValue::CSS_REMS),
+ AnimatableValue::add(zeropercent.get(), create(-10, CSSPrimitiveValue::CSS_REMS).get()));
+ EXPECT_REFV_EQ(create(-10, CSSPrimitiveValue::CSS_REMS, 0, CSSPrimitiveValue::CSS_PERCENTAGE),
+ AnimatableValue::add(create(-10, CSSPrimitiveValue::CSS_REMS).get(), zeropercent.get()));
+}
+
+TEST_F(AnimationAnimatableLengthTest, IsUnitless)
+{
+ EXPECT_TRUE(isUnitlessZero(create(0, CSSPrimitiveValue::CSS_PX)));
+ EXPECT_FALSE(isUnitlessZero(create(0, CSSPrimitiveValue::CSS_PERCENTAGE)));
+ EXPECT_TRUE(isUnitlessZero(create(0, CSSPrimitiveValue::CSS_EMS)));
+ EXPECT_TRUE(isUnitlessZero(create(0, CSSPrimitiveValue::CSS_EXS)));
+ EXPECT_TRUE(isUnitlessZero(create(0, CSSPrimitiveValue::CSS_REMS)));
+ EXPECT_TRUE(isUnitlessZero(create(0, CSSPrimitiveValue::CSS_VW)));
+ EXPECT_TRUE(isUnitlessZero(create(0, CSSPrimitiveValue::CSS_VH)));
+ EXPECT_TRUE(isUnitlessZero(create(0, CSSPrimitiveValue::CSS_VMIN)));
+ EXPECT_TRUE(isUnitlessZero(create(0, CSSPrimitiveValue::CSS_VMAX)));
+
+ EXPECT_FALSE(isUnitlessZero(create(1, CSSPrimitiveValue::CSS_PX)));
+ EXPECT_FALSE(isUnitlessZero(create(2, CSSPrimitiveValue::CSS_PERCENTAGE)));
+ EXPECT_FALSE(isUnitlessZero(create(3, CSSPrimitiveValue::CSS_EMS)));
+ EXPECT_FALSE(isUnitlessZero(create(4, CSSPrimitiveValue::CSS_EXS)));
+ EXPECT_FALSE(isUnitlessZero(create(5, CSSPrimitiveValue::CSS_REMS)));
+ EXPECT_FALSE(isUnitlessZero(create(6, CSSPrimitiveValue::CSS_VW)));
+ EXPECT_FALSE(isUnitlessZero(create(7, CSSPrimitiveValue::CSS_VH)));
+ EXPECT_FALSE(isUnitlessZero(create(8, CSSPrimitiveValue::CSS_VMIN)));
+ EXPECT_FALSE(isUnitlessZero(create(9, CSSPrimitiveValue::CSS_VMAX)));
+}
+
+TEST_F(AnimationAnimatableLengthTest, CommonUnitType)
+{
+ RefPtr<AnimatableLength> length10px = create(10, CSSPrimitiveValue::CSS_PX);
+ EXPECT_EQ(AnimatableLength::UnitTypePixels, commonUnitType(length10px, create(1, CSSPrimitiveValue::CSS_PX).get()));
+ EXPECT_EQ(AnimatableLength::UnitTypeCalc, commonUnitType(length10px, create(2, CSSPrimitiveValue::CSS_PERCENTAGE).get()));
+ EXPECT_EQ(AnimatableLength::UnitTypeCalc, commonUnitType(length10px, create(3, CSSPrimitiveValue::CSS_EMS).get()));
+ EXPECT_EQ(AnimatableLength::UnitTypeCalc, commonUnitType(length10px, create(4, CSSPrimitiveValue::CSS_PX, 5, CSSPrimitiveValue::CSS_CM).get()));
+ EXPECT_EQ(AnimatableLength::UnitTypeCalc, commonUnitType(length10px, create(0, CSSPrimitiveValue::CSS_PERCENTAGE).get()));
+
+ RefPtr<AnimatableLength> length0px = create(0, CSSPrimitiveValue::CSS_PX);
+ EXPECT_EQ(AnimatableLength::UnitTypePixels, commonUnitType(length0px, create(1, CSSPrimitiveValue::CSS_PX).get()));
+ EXPECT_EQ(AnimatableLength::UnitTypePercentage, commonUnitType(length0px, create(2, CSSPrimitiveValue::CSS_PERCENTAGE).get()));
+ EXPECT_EQ(AnimatableLength::UnitTypeFontSize, commonUnitType(length0px, create(3, CSSPrimitiveValue::CSS_EMS).get()));
+ EXPECT_EQ(AnimatableLength::UnitTypeCalc, commonUnitType(length0px, create(4, CSSPrimitiveValue::CSS_PX, 5, CSSPrimitiveValue::CSS_CM).get()));
+ EXPECT_EQ(AnimatableLength::UnitTypePercentage, commonUnitType(length0px, create(0, CSSPrimitiveValue::CSS_PERCENTAGE).get()));
+
+ RefPtr<AnimatableLength> length0percent = create(0, CSSPrimitiveValue::CSS_PERCENTAGE);
+ EXPECT_EQ(AnimatableLength::UnitTypeCalc, commonUnitType(length0percent, create(1, CSSPrimitiveValue::CSS_PX).get()));
+ EXPECT_EQ(AnimatableLength::UnitTypePercentage, commonUnitType(length0percent, create(2, CSSPrimitiveValue::CSS_PERCENTAGE).get()));
+ EXPECT_EQ(AnimatableLength::UnitTypeCalc, commonUnitType(length0percent, create(3, CSSPrimitiveValue::CSS_EMS).get()));
+ EXPECT_EQ(AnimatableLength::UnitTypeCalc, commonUnitType(length0percent, create(4, CSSPrimitiveValue::CSS_PX, 5, CSSPrimitiveValue::CSS_CM).get()));
+ EXPECT_EQ(AnimatableLength::UnitTypePercentage, commonUnitType(length0percent, create(0, CSSPrimitiveValue::CSS_PERCENTAGE).get()));
+
+ RefPtr<AnimatableLength> lengthCalc = create(3, CSSPrimitiveValue::CSS_PX, 5, CSSPrimitiveValue::CSS_CM);
+ EXPECT_EQ(AnimatableLength::UnitTypeCalc, commonUnitType(lengthCalc, create(1, CSSPrimitiveValue::CSS_PX).get()));
+ EXPECT_EQ(AnimatableLength::UnitTypeCalc, commonUnitType(lengthCalc, create(2, CSSPrimitiveValue::CSS_PERCENTAGE).get()));
+ EXPECT_EQ(AnimatableLength::UnitTypeCalc, commonUnitType(lengthCalc, create(3, CSSPrimitiveValue::CSS_EMS).get()));
+ EXPECT_EQ(AnimatableLength::UnitTypeCalc, commonUnitType(lengthCalc, create(4, CSSPrimitiveValue::CSS_PX, 5, CSSPrimitiveValue::CSS_CM).get()));
+ EXPECT_EQ(AnimatableLength::UnitTypeCalc, commonUnitType(lengthCalc, create(0, CSSPrimitiveValue::CSS_PERCENTAGE).get()));
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/animation/AnimatableNeutral.h b/chromium/third_party/WebKit/Source/core/animation/AnimatableNeutral.h
index 91b702d5161..5b8759ce45b 100644
--- a/chromium/third_party/WebKit/Source/core/animation/AnimatableNeutral.h
+++ b/chromium/third_party/WebKit/Source/core/animation/AnimatableNeutral.h
@@ -41,7 +41,6 @@ public:
protected:
static PassRefPtr<AnimatableNeutral> create() { return adoptRef(new AnimatableNeutral()); }
-
virtual PassRefPtr<AnimatableValue> interpolateTo(const AnimatableValue* value, double fraction) const OVERRIDE
{
ASSERT_NOT_REACHED();
@@ -49,9 +48,13 @@ protected:
}
private:
- AnimatableNeutral() : AnimatableValue(TypeNeutral) { }
-
friend class AnimatableValue;
+ virtual AnimatableType type() const OVERRIDE { return TypeNeutral; }
+ virtual bool equalTo(const AnimatableValue* value) const OVERRIDE
+ {
+ ASSERT_NOT_REACHED();
+ return true;
+ }
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/animation/AnimatableNeutralTest.cpp b/chromium/third_party/WebKit/Source/core/animation/AnimatableNeutralTest.cpp
index 07469620675..dbf685ab8fd 100644
--- a/chromium/third_party/WebKit/Source/core/animation/AnimatableNeutralTest.cpp
+++ b/chromium/third_party/WebKit/Source/core/animation/AnimatableNeutralTest.cpp
@@ -40,12 +40,12 @@ using namespace WebCore;
namespace {
-TEST(AnimatableNeutral, Create)
+TEST(AnimationAnimatableNeutralTest, Create)
{
EXPECT_TRUE(AnimatableValue::neutralValue());
}
-TEST(AnimatableNeutral, Add)
+TEST(AnimationAnimatableNeutralTest, Add)
{
RefPtr<CSSValue> cssValue = CSSArrayFunctionValue::create();
RefPtr<AnimatableValue> animatableUnknown = AnimatableUnknown::create(cssValue);
diff --git a/chromium/third_party/WebKit/Source/core/animation/AnimatableNumber.cpp b/chromium/third_party/WebKit/Source/core/animation/AnimatableNumber.cpp
deleted file mode 100644
index 415fc8bed44..00000000000
--- a/chromium/third_party/WebKit/Source/core/animation/AnimatableNumber.cpp
+++ /dev/null
@@ -1,251 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/animation/AnimatableNumber.h"
-
-#include "core/css/CSSPrimitiveValueMappings.h"
-#include "core/platform/CalculationValue.h"
-#include "core/platform/Length.h"
-#include "wtf/MathExtras.h"
-
-namespace WebCore {
-
-PassRefPtr<AnimatableNumber> AnimatableNumber::create(CSSValue* value)
-{
- ASSERT(canCreateFrom(value));
- if (value->isPrimitiveValue()) {
- CSSPrimitiveValue* primitiveValue = WebCore::toCSSPrimitiveValue(value);
- const CSSCalcValue* calcValue = primitiveValue->cssCalcValue();
- if (calcValue)
- return create(calcValue->expressionNode(), primitiveValue);
- NumberUnitType unitType = primitiveUnitToNumberType(primitiveValue->primitiveType());
- ASSERT(unitType != UnitTypeInvalid);
- const double scale = CSSPrimitiveValue::conversionToCanonicalUnitsScaleFactor(primitiveValue->primitiveType());
- return create(primitiveValue->getDoubleValue() * scale, unitType, primitiveValue);
- }
-
- if (value->isCalculationValue())
- return create(toCSSCalcValue(value)->expressionNode());
-
- ASSERT_NOT_REACHED();
- return 0;
-}
-
-PassRefPtr<AnimatableNumber> AnimatableNumber::create(const AnimatableNumber* leftAddend, const AnimatableNumber* rightAddend)
-{
- ASSERT(leftAddend);
- ASSERT(rightAddend);
-
- if (!leftAddend->m_isCalc && !rightAddend->m_isCalc && leftAddend->m_unitType == rightAddend->m_unitType)
- return create(leftAddend->m_number + rightAddend->m_number, leftAddend->m_unitType);
- return create(CSSCalcValue::createExpressionNode(leftAddend->toCSSCalcExpressionNode(), rightAddend->toCSSCalcExpressionNode(), CalcAdd));
-}
-
-bool AnimatableNumber::canCreateFrom(const CSSValue* value)
-{
- ASSERT(value);
- if (value->isPrimitiveValue()) {
- const CSSPrimitiveValue* primitiveValue = WebCore::toCSSPrimitiveValue(value);
- if (primitiveValue->cssCalcValue())
- return true;
- return primitiveUnitToNumberType(primitiveValue->primitiveType()) != UnitTypeInvalid;
- }
- return value->isCalculationValue();
-}
-
-PassRefPtr<CSSValue> AnimatableNumber::toCSSValue(NumberRange range) const
-{
- return toCSSPrimitiveValue(range);
-}
-
-double AnimatableNumber::toDouble() const
-{
- ASSERT(m_unitType == UnitTypeNumber);
- return m_number;
-}
-
-Length AnimatableNumber::toLength(const RenderStyle* style, const RenderStyle* rootStyle, double zoom, NumberRange range) const
-{
- if (!m_isCalc) {
- // Avoid creating a CSSValue in the common cases
- if (m_unitType == UnitTypeLength)
- return Length(clampedNumber(range) * zoom, Fixed);
- if (m_unitType == UnitTypePercentage)
- return Length(clampedNumber(range), Percent);
- }
- return toCSSPrimitiveValue(range)->convertToLength<AnyConversion>(style, rootStyle, zoom);
-}
-
-PassRefPtr<AnimatableValue> AnimatableNumber::interpolateTo(const AnimatableValue* value, double fraction) const
-{
- const AnimatableNumber* number = toAnimatableNumber(value);
- return AnimatableNumber::create(scale(1 - fraction).get(), number->scale(fraction).get());
-}
-
-PassRefPtr<AnimatableValue> AnimatableNumber::addWith(const AnimatableValue* value) const
-{
- // Optimization for adding with 0.
- if (!m_isCalc && !m_number)
- return takeConstRef(value);
- const AnimatableNumber* number = toAnimatableNumber(value);
- if (!number->m_isCalc && !number->m_number)
- return takeConstRef(this);
-
- return AnimatableNumber::create(this, number);
-}
-
-PassRefPtr<CSSCalcExpressionNode> AnimatableNumber::toCSSCalcExpressionNode() const
-{
- if (m_isCalc)
- return m_calcExpression;
- return CSSCalcValue::createExpressionNode(toCSSPrimitiveValue(AllValues), m_number == trunc(m_number));
-}
-
-static bool isCompatibleWithRange(const CSSPrimitiveValue* primitiveValue, NumberRange range)
-{
- ASSERT(primitiveValue);
- if (range == AllValues)
- return true;
- if (primitiveValue->isCalculated())
- return primitiveValue->cssCalcValue()->permittedValueRange() == CalculationRangeNonNegative;
- return primitiveValue->getDoubleValue() >= 0;
-}
-
-PassRefPtr<CSSPrimitiveValue> AnimatableNumber::toCSSPrimitiveValue(NumberRange range) const
-{
- ASSERT(m_unitType != UnitTypeInvalid);
- if (!m_cachedCSSPrimitiveValue || !isCompatibleWithRange(m_cachedCSSPrimitiveValue.get(), range)) {
- if (m_isCalc)
- m_cachedCSSPrimitiveValue = CSSPrimitiveValue::create(CSSCalcValue::create(m_calcExpression, range == AllValues ? CalculationRangeAll : CalculationRangeNonNegative));
- else
- m_cachedCSSPrimitiveValue = CSSPrimitiveValue::create(clampedNumber(range), static_cast<CSSPrimitiveValue::UnitTypes>(numberTypeToPrimitiveUnit(m_unitType)));
- }
- return m_cachedCSSPrimitiveValue;
-}
-
-PassRefPtr<AnimatableNumber> AnimatableNumber::scale(double factor) const
-{
- if (m_isCalc) {
- return AnimatableNumber::create(CSSCalcValue::createExpressionNode(
- m_calcExpression,
- CSSCalcValue::createExpressionNode(CSSPrimitiveValue::create(factor, CSSPrimitiveValue::CSS_NUMBER)),
- CalcMultiply));
- }
- return AnimatableNumber::create(m_number * factor, m_unitType);
-}
-
-AnimatableNumber::NumberUnitType AnimatableNumber::primitiveUnitToNumberType(unsigned short primitiveUnit)
-{
- switch (primitiveUnit) {
- case CSSPrimitiveValue::CSS_NUMBER:
- return UnitTypeNumber;
- case CSSPrimitiveValue::CSS_PX:
- case CSSPrimitiveValue::CSS_CM:
- case CSSPrimitiveValue::CSS_MM:
- case CSSPrimitiveValue::CSS_IN:
- case CSSPrimitiveValue::CSS_PT:
- case CSSPrimitiveValue::CSS_PC:
- return UnitTypeLength;
- case CSSPrimitiveValue::CSS_EMS:
- return UnitTypeFontSize;
- case CSSPrimitiveValue::CSS_EXS:
- return UnitTypeFontXSize;
- case CSSPrimitiveValue::CSS_REMS:
- return UnitTypeRootFontSize;
- case CSSPrimitiveValue::CSS_DEG:
- case CSSPrimitiveValue::CSS_RAD:
- case CSSPrimitiveValue::CSS_GRAD:
- case CSSPrimitiveValue::CSS_TURN:
- return UnitTypeAngle;
- case CSSPrimitiveValue::CSS_PERCENTAGE:
- return UnitTypePercentage;
- case CSSPrimitiveValue::CSS_VW:
- return UnitTypeViewportWidth;
- case CSSPrimitiveValue::CSS_VH:
- return UnitTypeViewportHeight;
- case CSSPrimitiveValue::CSS_VMIN:
- return UnitTypeViewportMin;
- case CSSPrimitiveValue::CSS_VMAX:
- return UnitTypeViewportMax;
- case CSSPrimitiveValue::CSS_MS:
- case CSSPrimitiveValue::CSS_S:
- return UnitTypeTime;
- case CSSPrimitiveValue::CSS_HZ:
- case CSSPrimitiveValue::CSS_KHZ:
- return UnitTypeFrequency;
- case CSSPrimitiveValue::CSS_DPPX:
- case CSSPrimitiveValue::CSS_DPI:
- case CSSPrimitiveValue::CSS_DPCM:
- return UnitTypeResolution;
- default:
- return UnitTypeInvalid;
- }
-}
-
-unsigned short AnimatableNumber::numberTypeToPrimitiveUnit(NumberUnitType numberType)
-{
- switch (numberType) {
- case UnitTypeNumber:
- return CSSPrimitiveValue::CSS_NUMBER;
- case UnitTypeLength:
- return CSSPrimitiveValue::CSS_PX;
- case UnitTypeFontSize:
- return CSSPrimitiveValue::CSS_EMS;
- case UnitTypeFontXSize:
- return CSSPrimitiveValue::CSS_EXS;
- case UnitTypeRootFontSize:
- return CSSPrimitiveValue::CSS_REMS;
- case UnitTypePercentage:
- return CSSPrimitiveValue::CSS_PERCENTAGE;
- case UnitTypeViewportWidth:
- return CSSPrimitiveValue::CSS_VW;
- case UnitTypeViewportHeight:
- return CSSPrimitiveValue::CSS_VH;
- case UnitTypeViewportMin:
- return CSSPrimitiveValue::CSS_VMIN;
- case UnitTypeViewportMax:
- return CSSPrimitiveValue::CSS_VMAX;
- case UnitTypeTime:
- return CSSPrimitiveValue::CSS_MS;
- case UnitTypeAngle:
- return CSSPrimitiveValue::CSS_DEG;
- case UnitTypeFrequency:
- return CSSPrimitiveValue::CSS_HZ;
- case UnitTypeResolution:
- return CSSPrimitiveValue::CSS_DPPX;
- case UnitTypeInvalid:
- return CSSPrimitiveValue::CSS_UNKNOWN;
- }
- ASSERT_NOT_REACHED();
- return CSSPrimitiveValue::CSS_UNKNOWN;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/animation/AnimatableNumber.h b/chromium/third_party/WebKit/Source/core/animation/AnimatableNumber.h
deleted file mode 100644
index 9da6a7dee84..00000000000
--- a/chromium/third_party/WebKit/Source/core/animation/AnimatableNumber.h
+++ /dev/null
@@ -1,137 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef AnimatableNumber_h
-#define AnimatableNumber_h
-
-#include "core/animation/AnimatableValue.h"
-#include "core/css/CSSCalculationValue.h"
-#include "core/css/CSSPrimitiveValue.h"
-
-namespace WebCore {
-
-enum NumberRange {
- AllValues,
- NonNegativeValues,
-};
-
-// Handles animation of CSSPrimitiveValues that can be represented by doubles including CSSCalcValue.
-// See primitiveUnitToNumberType() for the list of supported units (with the exception of calc).
-// If created from a CSSPrimitiveValue this class will cache it to be returned in toCSSValue().
-class AnimatableNumber : public AnimatableValue {
-public:
- enum NumberUnitType {
- UnitTypeNumber,
- UnitTypeLength,
- UnitTypeFontSize,
- UnitTypeFontXSize,
- UnitTypeRootFontSize,
- UnitTypePercentage,
- UnitTypeViewportWidth,
- UnitTypeViewportHeight,
- UnitTypeViewportMin,
- UnitTypeViewportMax,
- UnitTypeTime,
- UnitTypeAngle,
- UnitTypeFrequency,
- UnitTypeResolution,
- UnitTypeInvalid,
- };
-
- virtual ~AnimatableNumber() { }
- static bool canCreateFrom(const CSSValue*);
- static PassRefPtr<AnimatableNumber> create(CSSValue*);
- static PassRefPtr<AnimatableNumber> create(double number, NumberUnitType unitType, CSSPrimitiveValue* cssPrimitiveValue = 0)
- {
- return adoptRef(new AnimatableNumber(number, unitType, cssPrimitiveValue));
- }
- PassRefPtr<CSSValue> toCSSValue(NumberRange = AllValues) const;
- double toDouble() const;
- Length toLength(const RenderStyle* currStyle, const RenderStyle* rootStyle, double zoom, NumberRange = AllValues) const;
-
-protected:
- virtual PassRefPtr<AnimatableValue> interpolateTo(const AnimatableValue*, double fraction) const OVERRIDE;
- virtual PassRefPtr<AnimatableValue> addWith(const AnimatableValue*) const OVERRIDE;
-
-private:
- AnimatableNumber(double number, NumberUnitType unitType, CSSPrimitiveValue* cssPrimitiveValue)
- : AnimatableValue(TypeNumber)
- , m_number(number)
- , m_unitType(unitType)
- , m_isCalc(false)
- , m_cachedCSSPrimitiveValue(cssPrimitiveValue)
- {
- ASSERT(m_unitType != UnitTypeInvalid);
- }
- AnimatableNumber(PassRefPtr<CSSCalcExpressionNode> calcExpression, CSSPrimitiveValue* cssPrimitiveValue)
- : AnimatableValue(TypeNumber)
- , m_isCalc(true)
- , m_calcExpression(calcExpression)
- , m_cachedCSSPrimitiveValue(cssPrimitiveValue)
- {
- ASSERT(m_calcExpression);
- }
-
- static PassRefPtr<AnimatableNumber> create(PassRefPtr<CSSCalcExpressionNode> calcExpression, CSSPrimitiveValue* cssPrimitiveValue = 0)
- {
- return adoptRef(new AnimatableNumber(calcExpression, cssPrimitiveValue));
- }
- static PassRefPtr<AnimatableNumber> create(const AnimatableNumber* leftAddend, const AnimatableNumber* rightAddend);
-
- PassRefPtr<CSSPrimitiveValue> toCSSPrimitiveValue(NumberRange) const;
- PassRefPtr<CSSCalcExpressionNode> toCSSCalcExpressionNode() const;
-
- PassRefPtr<AnimatableNumber> scale(double) const;
- double clampedNumber(NumberRange range) const
- {
- ASSERT(!m_isCalc);
- return (range == NonNegativeValues && m_number <= 0) ? 0 : m_number;
- }
- static NumberUnitType primitiveUnitToNumberType(unsigned short primitiveUnit);
- static unsigned short numberTypeToPrimitiveUnit(NumberUnitType numberType);
-
- double m_number;
- NumberUnitType m_unitType;
-
- bool m_isCalc;
- RefPtr<CSSCalcExpressionNode> m_calcExpression;
-
- mutable RefPtr<CSSPrimitiveValue> m_cachedCSSPrimitiveValue;
-};
-
-inline const AnimatableNumber* toAnimatableNumber(const AnimatableValue* value)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(value && value->isNumber());
- return static_cast<const AnimatableNumber*>(value);
-}
-
-} // namespace WebCore
-
-#endif // AnimatableNumber_h
diff --git a/chromium/third_party/WebKit/Source/core/animation/AnimatableNumberTest.cpp b/chromium/third_party/WebKit/Source/core/animation/AnimatableNumberTest.cpp
deleted file mode 100644
index 48729192f73..00000000000
--- a/chromium/third_party/WebKit/Source/core/animation/AnimatableNumberTest.cpp
+++ /dev/null
@@ -1,310 +0,0 @@
-/*
- * Copyright (c) 2013, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/animation/AnimatableNumber.h"
-
-#include "core/css/CSSCalculationValue.h"
-#include "core/css/CSSPrimitiveValue.h"
-#include "core/platform/CalculationValue.h"
-#include "core/rendering/style/RenderStyle.h"
-#include "core/rendering/style/StyleInheritedData.h"
-#include "wtf/MathExtras.h"
-
-#include <gtest/gtest.h>
-
-using namespace WebCore;
-
-namespace {
-
-class AnimatableNumberTest : public ::testing::Test {
-protected:
- virtual void SetUp()
- {
- style = RenderStyle::createDefaultStyle();
- }
-
- PassRefPtr<AnimatableNumber> create(double value)
- {
- return create(value, CSSPrimitiveValue::CSS_NUMBER);
- }
-
- PassRefPtr<AnimatableNumber> create(double value, CSSPrimitiveValue::UnitTypes type)
- {
- return AnimatableNumber::create(CSSPrimitiveValue::create(value, type).get());
- }
-
- PassRefPtr<AnimatableNumber> create(double valueLeft, CSSPrimitiveValue::UnitTypes typeLeft, double valueRight, CSSPrimitiveValue::UnitTypes typeRight)
- {
- return AnimatableNumber::create(createCalc(valueLeft, typeLeft, valueRight, typeRight).get());
- }
-
- PassRefPtr<CSSCalcValue> createCalc(double valueLeft, CSSPrimitiveValue::UnitTypes typeLeft, double valueRight, CSSPrimitiveValue::UnitTypes typeRight)
- {
- return CSSCalcValue::create(CSSCalcValue::createExpressionNode(
- CSSCalcValue::createExpressionNode(CSSPrimitiveValue::create(valueLeft, typeLeft), valueLeft == trunc(valueLeft)),
- CSSCalcValue::createExpressionNode(CSSPrimitiveValue::create(valueRight, typeRight), valueRight == trunc(valueRight)),
- CalcAdd
- ));
- }
-
- bool testToCSSValue(CSSValue* cssValue)
- {
- return testToCSSValue(cssValue, cssValue);
- }
- bool testToCSSValue(CSSValue* cssValueExpected, CSSValue* cssValue)
- {
- return AnimatableNumber::create(cssValue)->toCSSValue()->equals(*cssValueExpected);
- }
- bool testInterpolate(CSSValue* cssValueExpected, AnimatableNumber* numberA, AnimatableNumber* numberB, double fraction)
- {
- return toAnimatableNumber(AnimatableValue::interpolate(numberA, numberB, fraction).get())->toCSSValue()->equals(*cssValueExpected);
- }
- bool testAdd(CSSValue* cssValueExpected, AnimatableNumber* numberA, AnimatableNumber* numberB)
- {
- return toAnimatableNumber(AnimatableValue::add(numberA, numberB).get())->toCSSValue()->equals(*cssValueExpected);
- }
-
- RefPtr<RenderStyle> style;
-};
-
-TEST_F(AnimatableNumberTest, CanCreateFrom)
-{
- EXPECT_TRUE(AnimatableNumber::canCreateFrom(CSSPrimitiveValue::create(5, CSSPrimitiveValue::CSS_NUMBER).get()));
- EXPECT_TRUE(AnimatableNumber::canCreateFrom(CSSPrimitiveValue::create(5, CSSPrimitiveValue::CSS_PX).get()));
- EXPECT_TRUE(AnimatableNumber::canCreateFrom(CSSPrimitiveValue::create(5, CSSPrimitiveValue::CSS_CM).get()));
- EXPECT_TRUE(AnimatableNumber::canCreateFrom(CSSPrimitiveValue::create(5, CSSPrimitiveValue::CSS_MM).get()));
- EXPECT_TRUE(AnimatableNumber::canCreateFrom(CSSPrimitiveValue::create(5, CSSPrimitiveValue::CSS_IN).get()));
- EXPECT_TRUE(AnimatableNumber::canCreateFrom(CSSPrimitiveValue::create(5, CSSPrimitiveValue::CSS_PT).get()));
- EXPECT_TRUE(AnimatableNumber::canCreateFrom(CSSPrimitiveValue::create(5, CSSPrimitiveValue::CSS_PC).get()));
- EXPECT_TRUE(AnimatableNumber::canCreateFrom(CSSPrimitiveValue::create(5, CSSPrimitiveValue::CSS_EMS).get()));
- EXPECT_TRUE(AnimatableNumber::canCreateFrom(CSSPrimitiveValue::create(5, CSSPrimitiveValue::CSS_EXS).get()));
- EXPECT_TRUE(AnimatableNumber::canCreateFrom(CSSPrimitiveValue::create(5, CSSPrimitiveValue::CSS_REMS).get()));
- EXPECT_TRUE(AnimatableNumber::canCreateFrom(CSSPrimitiveValue::create(5, CSSPrimitiveValue::CSS_DEG).get()));
- EXPECT_TRUE(AnimatableNumber::canCreateFrom(CSSPrimitiveValue::create(5, CSSPrimitiveValue::CSS_RAD).get()));
- EXPECT_TRUE(AnimatableNumber::canCreateFrom(CSSPrimitiveValue::create(5, CSSPrimitiveValue::CSS_GRAD).get()));
- EXPECT_TRUE(AnimatableNumber::canCreateFrom(CSSPrimitiveValue::create(5, CSSPrimitiveValue::CSS_TURN).get()));
- EXPECT_TRUE(AnimatableNumber::canCreateFrom(CSSPrimitiveValue::create(5, CSSPrimitiveValue::CSS_PERCENTAGE).get()));
- EXPECT_TRUE(AnimatableNumber::canCreateFrom(CSSPrimitiveValue::create(5, CSSPrimitiveValue::CSS_VW).get()));
- EXPECT_TRUE(AnimatableNumber::canCreateFrom(CSSPrimitiveValue::create(5, CSSPrimitiveValue::CSS_VH).get()));
- EXPECT_TRUE(AnimatableNumber::canCreateFrom(CSSPrimitiveValue::create(5, CSSPrimitiveValue::CSS_VMIN).get()));
- EXPECT_TRUE(AnimatableNumber::canCreateFrom(CSSPrimitiveValue::create(5, CSSPrimitiveValue::CSS_VMAX).get()));
- EXPECT_TRUE(AnimatableNumber::canCreateFrom(CSSPrimitiveValue::create(5, CSSPrimitiveValue::CSS_MS).get()));
- EXPECT_TRUE(AnimatableNumber::canCreateFrom(CSSPrimitiveValue::create(5, CSSPrimitiveValue::CSS_S).get()));
- EXPECT_TRUE(AnimatableNumber::canCreateFrom(CSSPrimitiveValue::create(5, CSSPrimitiveValue::CSS_HZ).get()));
- EXPECT_TRUE(AnimatableNumber::canCreateFrom(CSSPrimitiveValue::create(5, CSSPrimitiveValue::CSS_KHZ).get()));
- EXPECT_TRUE(AnimatableNumber::canCreateFrom(CSSPrimitiveValue::create(5, CSSPrimitiveValue::CSS_DPPX).get()));
- EXPECT_TRUE(AnimatableNumber::canCreateFrom(CSSPrimitiveValue::create(5, CSSPrimitiveValue::CSS_DPI).get()));
- EXPECT_TRUE(AnimatableNumber::canCreateFrom(CSSPrimitiveValue::create(5, CSSPrimitiveValue::CSS_DPCM).get()));
-
- EXPECT_TRUE(AnimatableNumber::canCreateFrom(createCalc(3, CSSPrimitiveValue::CSS_PX, 5, CSSPrimitiveValue::CSS_CM).get()));
- EXPECT_TRUE(AnimatableNumber::canCreateFrom(CSSPrimitiveValue::create(createCalc(3, CSSPrimitiveValue::CSS_PX, 5, CSSPrimitiveValue::CSS_CM)).get()));
-
- EXPECT_FALSE(AnimatableNumber::canCreateFrom(CSSPrimitiveValue::create("NaN", CSSPrimitiveValue::CSS_STRING).get()));
-}
-
-TEST_F(AnimatableNumberTest, Create)
-{
- EXPECT_TRUE(static_cast<bool>(create(5, CSSPrimitiveValue::CSS_NUMBER).get()));
- EXPECT_TRUE(static_cast<bool>(create(5, CSSPrimitiveValue::CSS_PX).get()));
- EXPECT_TRUE(static_cast<bool>(create(5, CSSPrimitiveValue::CSS_CM).get()));
- EXPECT_TRUE(static_cast<bool>(create(5, CSSPrimitiveValue::CSS_MM).get()));
- EXPECT_TRUE(static_cast<bool>(create(5, CSSPrimitiveValue::CSS_IN).get()));
- EXPECT_TRUE(static_cast<bool>(create(5, CSSPrimitiveValue::CSS_PT).get()));
- EXPECT_TRUE(static_cast<bool>(create(5, CSSPrimitiveValue::CSS_PC).get()));
- EXPECT_TRUE(static_cast<bool>(create(5, CSSPrimitiveValue::CSS_EMS).get()));
- EXPECT_TRUE(static_cast<bool>(create(5, CSSPrimitiveValue::CSS_EXS).get()));
- EXPECT_TRUE(static_cast<bool>(create(5, CSSPrimitiveValue::CSS_REMS).get()));
- EXPECT_TRUE(static_cast<bool>(create(5, CSSPrimitiveValue::CSS_DEG).get()));
- EXPECT_TRUE(static_cast<bool>(create(5, CSSPrimitiveValue::CSS_RAD).get()));
- EXPECT_TRUE(static_cast<bool>(create(5, CSSPrimitiveValue::CSS_GRAD).get()));
- EXPECT_TRUE(static_cast<bool>(create(5, CSSPrimitiveValue::CSS_TURN).get()));
- EXPECT_TRUE(static_cast<bool>(create(5, CSSPrimitiveValue::CSS_PERCENTAGE).get()));
- EXPECT_TRUE(static_cast<bool>(create(5, CSSPrimitiveValue::CSS_VW).get()));
- EXPECT_TRUE(static_cast<bool>(create(5, CSSPrimitiveValue::CSS_VH).get()));
- EXPECT_TRUE(static_cast<bool>(create(5, CSSPrimitiveValue::CSS_VMIN).get()));
- EXPECT_TRUE(static_cast<bool>(create(5, CSSPrimitiveValue::CSS_VMAX).get()));
- EXPECT_TRUE(static_cast<bool>(create(5, CSSPrimitiveValue::CSS_MS).get()));
- EXPECT_TRUE(static_cast<bool>(create(5, CSSPrimitiveValue::CSS_S).get()));
- EXPECT_TRUE(static_cast<bool>(create(5, CSSPrimitiveValue::CSS_HZ).get()));
- EXPECT_TRUE(static_cast<bool>(create(5, CSSPrimitiveValue::CSS_KHZ).get()));
- EXPECT_TRUE(static_cast<bool>(create(5, CSSPrimitiveValue::CSS_DPPX).get()));
- EXPECT_TRUE(static_cast<bool>(create(5, CSSPrimitiveValue::CSS_DPI).get()));
- EXPECT_TRUE(static_cast<bool>(create(5, CSSPrimitiveValue::CSS_DPCM).get()));
-
- EXPECT_TRUE(static_cast<bool>(
- AnimatableNumber::create(createCalc(3, CSSPrimitiveValue::CSS_PX, 5, CSSPrimitiveValue::CSS_CM).get()).get()
- ));
- EXPECT_TRUE(static_cast<bool>(
- AnimatableNumber::create(CSSPrimitiveValue::create(createCalc(3, CSSPrimitiveValue::CSS_PX, 5, CSSPrimitiveValue::CSS_CM)).get()).get()
- ));
-}
-
-TEST_F(AnimatableNumberTest, ToCSSValue)
-{
- EXPECT_TRUE(testToCSSValue(CSSPrimitiveValue::create(-5, CSSPrimitiveValue::CSS_NUMBER).get()));
- EXPECT_TRUE(testToCSSValue(CSSPrimitiveValue::create(-5, CSSPrimitiveValue::CSS_PX).get()));
- EXPECT_TRUE(testToCSSValue(CSSPrimitiveValue::create(-5, CSSPrimitiveValue::CSS_CM).get()));
- EXPECT_TRUE(testToCSSValue(CSSPrimitiveValue::create(-5, CSSPrimitiveValue::CSS_MM).get()));
- EXPECT_TRUE(testToCSSValue(CSSPrimitiveValue::create(-5, CSSPrimitiveValue::CSS_IN).get()));
- EXPECT_TRUE(testToCSSValue(CSSPrimitiveValue::create(-5, CSSPrimitiveValue::CSS_PT).get()));
- EXPECT_TRUE(testToCSSValue(CSSPrimitiveValue::create(-5, CSSPrimitiveValue::CSS_PC).get()));
- EXPECT_TRUE(testToCSSValue(CSSPrimitiveValue::create(-5, CSSPrimitiveValue::CSS_EMS).get()));
- EXPECT_TRUE(testToCSSValue(CSSPrimitiveValue::create(-5, CSSPrimitiveValue::CSS_EXS).get()));
- EXPECT_TRUE(testToCSSValue(CSSPrimitiveValue::create(-5, CSSPrimitiveValue::CSS_REMS).get()));
- EXPECT_TRUE(testToCSSValue(CSSPrimitiveValue::create(-5, CSSPrimitiveValue::CSS_DEG).get()));
- EXPECT_TRUE(testToCSSValue(CSSPrimitiveValue::create(-5, CSSPrimitiveValue::CSS_RAD).get()));
- EXPECT_TRUE(testToCSSValue(CSSPrimitiveValue::create(-5, CSSPrimitiveValue::CSS_GRAD).get()));
- EXPECT_TRUE(testToCSSValue(CSSPrimitiveValue::create(-5, CSSPrimitiveValue::CSS_TURN).get()));
- EXPECT_TRUE(testToCSSValue(CSSPrimitiveValue::create(-5, CSSPrimitiveValue::CSS_PERCENTAGE).get()));
- EXPECT_TRUE(testToCSSValue(CSSPrimitiveValue::create(-5, CSSPrimitiveValue::CSS_VW).get()));
- EXPECT_TRUE(testToCSSValue(CSSPrimitiveValue::create(-5, CSSPrimitiveValue::CSS_VH).get()));
- EXPECT_TRUE(testToCSSValue(CSSPrimitiveValue::create(-5, CSSPrimitiveValue::CSS_VMIN).get()));
- EXPECT_TRUE(testToCSSValue(CSSPrimitiveValue::create(-5, CSSPrimitiveValue::CSS_VMAX).get()));
- EXPECT_TRUE(testToCSSValue(CSSPrimitiveValue::create(-5, CSSPrimitiveValue::CSS_MS).get()));
- EXPECT_TRUE(testToCSSValue(CSSPrimitiveValue::create(-5, CSSPrimitiveValue::CSS_S).get()));
- EXPECT_TRUE(testToCSSValue(CSSPrimitiveValue::create(-5, CSSPrimitiveValue::CSS_HZ).get()));
- EXPECT_TRUE(testToCSSValue(CSSPrimitiveValue::create(-5, CSSPrimitiveValue::CSS_KHZ).get()));
- EXPECT_TRUE(testToCSSValue(CSSPrimitiveValue::create(-5, CSSPrimitiveValue::CSS_DPPX).get()));
- EXPECT_TRUE(testToCSSValue(CSSPrimitiveValue::create(-5, CSSPrimitiveValue::CSS_DPI).get()));
- EXPECT_TRUE(testToCSSValue(CSSPrimitiveValue::create(-5, CSSPrimitiveValue::CSS_DPCM).get()));
-
- EXPECT_TRUE(testToCSSValue(CSSPrimitiveValue::create(createCalc(3, CSSPrimitiveValue::CSS_PX, 5, CSSPrimitiveValue::CSS_IN)).get()));
- EXPECT_TRUE(testToCSSValue(CSSPrimitiveValue::create(createCalc(3, CSSPrimitiveValue::CSS_PX, 5, CSSPrimitiveValue::CSS_IN)).get(),
- createCalc(3, CSSPrimitiveValue::CSS_PX, 5, CSSPrimitiveValue::CSS_IN).get()));
-}
-
-TEST_F(AnimatableNumberTest, ToLength)
-{
- EXPECT_EQ(Length(-5, WebCore::Fixed), create(-5, CSSPrimitiveValue::CSS_PX)->toLength(style.get(), style.get(), 1));
- EXPECT_EQ(Length(-15, WebCore::Fixed), create(-5, CSSPrimitiveValue::CSS_PX)->toLength(style.get(), style.get(), 3));
- EXPECT_EQ(Length(0, WebCore::Fixed), create(-5, CSSPrimitiveValue::CSS_PX)->toLength(style.get(), style.get(), 1, NonNegativeValues));
- EXPECT_EQ(Length(0, WebCore::Fixed), create(-5, CSSPrimitiveValue::CSS_PX)->toLength(style.get(), style.get(), 3, NonNegativeValues));
-
- EXPECT_EQ(Length(-5, Percent), create(-5, CSSPrimitiveValue::CSS_PERCENTAGE)->toLength(style.get(), style.get(), 1));
- EXPECT_EQ(Length(-5, Percent), create(-5, CSSPrimitiveValue::CSS_PERCENTAGE)->toLength(style.get(), style.get(), 3));
- EXPECT_EQ(Length(0, Percent), create(-5, CSSPrimitiveValue::CSS_PERCENTAGE)->toLength(style.get(), style.get(), 1, NonNegativeValues));
- EXPECT_EQ(Length(0, Percent), create(-5, CSSPrimitiveValue::CSS_PERCENTAGE)->toLength(style.get(), style.get(), 3, NonNegativeValues));
-
- EXPECT_EQ(
- Length(CalculationValue::create(
- adoptPtr(new CalcExpressionBinaryOperation(
- adoptPtr(new CalcExpressionNumber(-5)),
- adoptPtr(new CalcExpressionLength(Length(-5, Percent))),
- CalcAdd)),
- CalculationRangeAll)),
- create(-5, CSSPrimitiveValue::CSS_PX, -5, CSSPrimitiveValue::CSS_PERCENTAGE)->toLength(style.get(), style.get(), 1));
- EXPECT_EQ(
- Length(CalculationValue::create(
- adoptPtr(new CalcExpressionBinaryOperation(
- adoptPtr(new CalcExpressionNumber(-15)),
- adoptPtr(new CalcExpressionLength(Length(-5, Percent))),
- CalcAdd)),
- CalculationRangeAll)),
- create(-5, CSSPrimitiveValue::CSS_PX, -5, CSSPrimitiveValue::CSS_PERCENTAGE)->toLength(style.get(), style.get(), 3));
- EXPECT_EQ(
- Length(CalculationValue::create(
- adoptPtr(new CalcExpressionBinaryOperation(
- adoptPtr(new CalcExpressionNumber(-5)),
- adoptPtr(new CalcExpressionLength(Length(-5, Percent))),
- CalcAdd)),
- CalculationRangeNonNegative)),
- create(-5, CSSPrimitiveValue::CSS_PX, -5, CSSPrimitiveValue::CSS_PERCENTAGE)->toLength(style.get(), style.get(), 1, NonNegativeValues));
- EXPECT_EQ(
- Length(CalculationValue::create(
- adoptPtr(new CalcExpressionBinaryOperation(
- adoptPtr(new CalcExpressionNumber(-15)),
- adoptPtr(new CalcExpressionLength(Length(-5, Percent))),
- CalcAdd)),
- CalculationRangeNonNegative)),
- create(-5, CSSPrimitiveValue::CSS_PX, -5, CSSPrimitiveValue::CSS_PERCENTAGE)->toLength(style.get(), style.get(), 3, NonNegativeValues));
-}
-
-TEST_F(AnimatableNumberTest, Interpolate)
-{
- RefPtr<AnimatableNumber> from10 = create(10);
- RefPtr<AnimatableNumber> to20 = create(20);
- EXPECT_TRUE(testInterpolate(CSSPrimitiveValue::create(5, CSSPrimitiveValue::CSS_NUMBER).get(), from10.get(), to20.get(), -0.5));
- EXPECT_TRUE(testInterpolate(CSSPrimitiveValue::create(10, CSSPrimitiveValue::CSS_NUMBER).get(), from10.get(), to20.get(), 0));
- EXPECT_TRUE(testInterpolate(CSSPrimitiveValue::create(14, CSSPrimitiveValue::CSS_NUMBER).get(), from10.get(), to20.get(), 0.4));
- EXPECT_TRUE(testInterpolate(CSSPrimitiveValue::create(15, CSSPrimitiveValue::CSS_NUMBER).get(), from10.get(), to20.get(), 0.5));
- EXPECT_TRUE(testInterpolate(CSSPrimitiveValue::create(16, CSSPrimitiveValue::CSS_NUMBER).get(), from10.get(), to20.get(), 0.6));
- EXPECT_TRUE(testInterpolate(CSSPrimitiveValue::create(20, CSSPrimitiveValue::CSS_NUMBER).get(), from10.get(), to20.get(), 1));
- EXPECT_TRUE(testInterpolate(CSSPrimitiveValue::create(25, CSSPrimitiveValue::CSS_NUMBER).get(), from10.get(), to20.get(), 1.5));
-
- RefPtr<AnimatableNumber> from10px = create(10, CSSPrimitiveValue::CSS_PX);
- RefPtr<AnimatableNumber> to20pxAsInches = create(20.0 / 96, CSSPrimitiveValue::CSS_IN);
- EXPECT_TRUE(testInterpolate(CSSPrimitiveValue::create(5, CSSPrimitiveValue::CSS_PX).get(), from10px.get(), to20pxAsInches.get(), -0.5));
- EXPECT_TRUE(testInterpolate(CSSPrimitiveValue::create(10, CSSPrimitiveValue::CSS_PX).get(), from10px.get(), to20pxAsInches.get(), 0));
- EXPECT_TRUE(testInterpolate(CSSPrimitiveValue::create(14, CSSPrimitiveValue::CSS_PX).get(), from10px.get(), to20pxAsInches.get(), 0.4));
- EXPECT_TRUE(testInterpolate(CSSPrimitiveValue::create(15, CSSPrimitiveValue::CSS_PX).get(), from10px.get(), to20pxAsInches.get(), 0.5));
- EXPECT_TRUE(testInterpolate(CSSPrimitiveValue::create(16, CSSPrimitiveValue::CSS_PX).get(), from10px.get(), to20pxAsInches.get(), 0.6));
- EXPECT_TRUE(testInterpolate(CSSPrimitiveValue::create(20.0 / 96, CSSPrimitiveValue::CSS_IN).get(), from10px.get(), to20pxAsInches.get(), 1));
- EXPECT_TRUE(testInterpolate(CSSPrimitiveValue::create(25, CSSPrimitiveValue::CSS_PX).get(), from10px.get(), to20pxAsInches.get(), 1.5));
-
- RefPtr<AnimatableNumber> from10em = create(10, CSSPrimitiveValue::CSS_EMS);
- RefPtr<AnimatableNumber> to20rem = create(20, CSSPrimitiveValue::CSS_REMS);
- EXPECT_TRUE(testInterpolate(CSSPrimitiveValue::create(createCalc(15, CSSPrimitiveValue::CSS_EMS, -10, CSSPrimitiveValue::CSS_REMS)).get(),
- from10em.get(), to20rem.get(), -0.5));
- EXPECT_TRUE(testInterpolate(CSSPrimitiveValue::create(10, CSSPrimitiveValue::CSS_EMS).get(),
- from10em.get(), to20rem.get(), 0));
- EXPECT_TRUE(testInterpolate(CSSPrimitiveValue::create(createCalc(6, CSSPrimitiveValue::CSS_EMS, 8, CSSPrimitiveValue::CSS_REMS)).get(),
- from10em.get(), to20rem.get(), 0.4));
- EXPECT_TRUE(testInterpolate(CSSPrimitiveValue::create(createCalc(5, CSSPrimitiveValue::CSS_EMS, 10, CSSPrimitiveValue::CSS_REMS)).get(),
- from10em.get(), to20rem.get(), 0.5));
- EXPECT_TRUE(testInterpolate(CSSPrimitiveValue::create(createCalc(4, CSSPrimitiveValue::CSS_EMS, 12, CSSPrimitiveValue::CSS_REMS)).get(),
- from10em.get(), to20rem.get(), 0.6));
- EXPECT_TRUE(testInterpolate(CSSPrimitiveValue::create(20, CSSPrimitiveValue::CSS_REMS).get(),
- from10em.get(), to20rem.get(), 1));
- EXPECT_TRUE(testInterpolate(CSSPrimitiveValue::create(createCalc(-5, CSSPrimitiveValue::CSS_EMS, 30, CSSPrimitiveValue::CSS_REMS)).get(),
- from10em.get(), to20rem.get(), 1.5));
-}
-
-TEST_F(AnimatableNumberTest, Add)
-{
- EXPECT_TRUE(testAdd(CSSPrimitiveValue::create(10, CSSPrimitiveValue::CSS_NUMBER).get(), create(4).get(), create(6).get()));
- EXPECT_TRUE(testAdd(CSSPrimitiveValue::create(10, CSSPrimitiveValue::CSS_NUMBER).get(), create(0).get(), create(10).get()));
- EXPECT_TRUE(testAdd(CSSPrimitiveValue::create(10, CSSPrimitiveValue::CSS_PX).get(), create(10, CSSPrimitiveValue::CSS_PX).get(), create(0, CSSPrimitiveValue::CSS_MM).get()));
- EXPECT_TRUE(testAdd(CSSPrimitiveValue::create(100, CSSPrimitiveValue::CSS_PX).get(), create(4, CSSPrimitiveValue::CSS_PX).get(), create(1, CSSPrimitiveValue::CSS_IN).get()));
- EXPECT_TRUE(testAdd(
- CSSPrimitiveValue::create(createCalc(10, CSSPrimitiveValue::CSS_EMS, 20, CSSPrimitiveValue::CSS_REMS)).get(),
- create(10, CSSPrimitiveValue::CSS_EMS).get(),
- create(20, CSSPrimitiveValue::CSS_REMS).get()));
- EXPECT_TRUE(testAdd(
- CSSPrimitiveValue::create(10, CSSPrimitiveValue::CSS_EMS).get(),
- create(10, CSSPrimitiveValue::CSS_EMS).get(),
- create(0, CSSPrimitiveValue::CSS_REMS).get()));
- EXPECT_TRUE(testAdd(
- CSSPrimitiveValue::create(20, CSSPrimitiveValue::CSS_REMS).get(),
- create(0, CSSPrimitiveValue::CSS_EMS).get(),
- create(20, CSSPrimitiveValue::CSS_REMS).get()));
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/animation/AnimatableRepeatable.cpp b/chromium/third_party/WebKit/Source/core/animation/AnimatableRepeatable.cpp
new file mode 100644
index 00000000000..a9f1ae6d982
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/animation/AnimatableRepeatable.cpp
@@ -0,0 +1,100 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/animation/AnimatableRepeatable.h"
+
+namespace {
+
+size_t greatestCommonDivisor(size_t a, size_t b)
+{
+ return b ? greatestCommonDivisor(b, a % b) : a;
+}
+
+size_t lowestCommonMultiple(size_t a, size_t b)
+{
+ ASSERT(a && b);
+ return a / greatestCommonDivisor(a, b) * b;
+}
+
+} // namespace
+
+namespace WebCore {
+
+bool AnimatableRepeatable::interpolateLists(const Vector<RefPtr<AnimatableValue> >& fromValues, const Vector<RefPtr<AnimatableValue> >& toValues, double fraction, Vector<RefPtr<AnimatableValue> >& interpolatedValues)
+{
+ // Interpolation behaviour spec: http://www.w3.org/TR/css3-transitions/#animtype-repeatable-list
+ ASSERT(interpolatedValues.isEmpty());
+ ASSERT(!fromValues.isEmpty() && !toValues.isEmpty());
+ size_t size = lowestCommonMultiple(fromValues.size(), toValues.size());
+ for (size_t i = 0; i < size; ++i) {
+ const AnimatableValue* from = fromValues[i % fromValues.size()].get();
+ const AnimatableValue* to = toValues[i % toValues.size()].get();
+ // Spec: If a pair of values cannot be interpolated, then the lists are not interpolable.
+ if (!from->usesNonDefaultInterpolationWith(to))
+ return false;
+ interpolatedValues.append(interpolate(from, to, fraction));
+ }
+ return true;
+}
+
+PassRefPtr<AnimatableValue> AnimatableRepeatable::interpolateTo(const AnimatableValue* value, double fraction) const
+{
+ Vector<RefPtr<AnimatableValue> > interpolatedValues;
+ bool success = interpolateLists(m_values, toAnimatableRepeatable(value)->m_values, fraction, interpolatedValues);
+ return success ? create(interpolatedValues) : defaultInterpolateTo(this, value, fraction);
+}
+
+PassRefPtr<AnimatableValue> AnimatableRepeatable::addWith(const AnimatableValue* value) const
+{
+ const Vector<RefPtr<AnimatableValue> >& otherValues = toAnimatableRepeatable(value)->m_values;
+ ASSERT(!m_values.isEmpty() && !otherValues.isEmpty());
+ Vector<RefPtr<AnimatableValue> > addedValues(lowestCommonMultiple(m_values.size(), otherValues.size()));
+ for (size_t i = 0; i < addedValues.size(); ++i) {
+ const AnimatableValue* left = m_values[i % m_values.size()].get();
+ const AnimatableValue* right = otherValues[i % otherValues.size()].get();
+ addedValues[i] = add(left, right);
+ }
+ return create(addedValues);
+}
+
+bool AnimatableRepeatable::equalTo(const AnimatableValue* value) const
+{
+ const Vector<RefPtr<AnimatableValue> >& otherValues = toAnimatableRepeatable(value)->m_values;
+ if (m_values.size() != otherValues.size())
+ return false;
+ for (size_t i = 0; i < m_values.size(); ++i) {
+ if (!m_values[i]->equals(otherValues[i].get()))
+ return false;
+ }
+ return true;
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/animation/AnimatableRepeatable.h b/chromium/third_party/WebKit/Source/core/animation/AnimatableRepeatable.h
new file mode 100644
index 00000000000..b1c74949c11
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/animation/AnimatableRepeatable.h
@@ -0,0 +1,79 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef AnimatableRepeatable_h
+#define AnimatableRepeatable_h
+
+#include "core/animation/AnimatableValue.h"
+#include "wtf/Vector.h"
+
+namespace WebCore {
+
+// This class represents collections of values that animate in a repeated fashion as described by the CSS Transitions spec:
+// http://www.w3.org/TR/css3-transitions/#animtype-repeatable-list
+class AnimatableRepeatable : public AnimatableValue {
+public:
+ virtual ~AnimatableRepeatable() { }
+
+ // This will consume the vector passed into it.
+ static PassRefPtr<AnimatableRepeatable> create(Vector<RefPtr<AnimatableValue> >& values)
+ {
+ return adoptRef(new AnimatableRepeatable(values));
+ }
+
+ const Vector<RefPtr<AnimatableValue> >& values() const { return m_values; }
+
+protected:
+ AnimatableRepeatable()
+ {
+ }
+ AnimatableRepeatable(Vector<RefPtr<AnimatableValue> >& values)
+ {
+ ASSERT(!values.isEmpty());
+ m_values.swap(values);
+ }
+
+ static bool interpolateLists(const Vector<RefPtr<AnimatableValue> >& fromValues, const Vector<RefPtr<AnimatableValue> >& toValues, double fraction, Vector<RefPtr<AnimatableValue> >& interpolatedValues);
+
+ Vector<RefPtr<AnimatableValue> > m_values;
+
+private:
+ virtual PassRefPtr<AnimatableValue> interpolateTo(const AnimatableValue*, double fraction) const OVERRIDE;
+ virtual PassRefPtr<AnimatableValue> addWith(const AnimatableValue*) const OVERRIDE;
+
+ virtual AnimatableType type() const OVERRIDE { return TypeRepeatable; }
+ virtual bool equalTo(const AnimatableValue*) const OVERRIDE;
+};
+
+DEFINE_TYPE_CASTS(AnimatableRepeatable, AnimatableValue, value, (value->isRepeatable() || value->isStrokeDasharrayList()), (value.isRepeatable() || value.isStrokeDasharrayList()));
+
+} // namespace WebCore
+
+#endif // AnimatableRepeatable_h
diff --git a/chromium/third_party/WebKit/Source/core/animation/AnimatableSVGLength.cpp b/chromium/third_party/WebKit/Source/core/animation/AnimatableSVGLength.cpp
new file mode 100644
index 00000000000..97f4158d0b3
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/animation/AnimatableSVGLength.cpp
@@ -0,0 +1,54 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/animation/AnimatableSVGLength.h"
+
+#include "platform/FloatConversion.h"
+
+namespace WebCore {
+
+PassRefPtr<AnimatableValue> AnimatableSVGLength::interpolateTo(const AnimatableValue* value, double fraction) const
+{
+ return create(toAnimatableSVGLength(value)->toSVGLength().blend(m_length, narrowPrecisionToFloat(fraction)));
+}
+
+PassRefPtr<AnimatableValue> AnimatableSVGLength::addWith(const AnimatableValue* value) const
+{
+ ASSERT_WITH_MESSAGE(false, "Web Animations not yet implemented: AnimatableSVGLength::addWith()");
+ return defaultAddWith(this, value);
+}
+
+bool AnimatableSVGLength::equalTo(const AnimatableValue* value) const
+{
+ return m_length == toAnimatableSVGLength(value)->m_length;
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/animation/AnimatableSVGLength.h b/chromium/third_party/WebKit/Source/core/animation/AnimatableSVGLength.h
new file mode 100644
index 00000000000..27dba9a48c1
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/animation/AnimatableSVGLength.h
@@ -0,0 +1,73 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef AnimatableSVGLength_h
+#define AnimatableSVGLength_h
+
+#include "core/animation/AnimatableValue.h"
+#include "core/svg/SVGLength.h"
+
+namespace WebCore {
+
+class AnimatableSVGLength: public AnimatableValue {
+public:
+ virtual ~AnimatableSVGLength() { }
+
+ static PassRefPtr<AnimatableSVGLength> create(const SVGLength& length)
+ {
+ return adoptRef(new AnimatableSVGLength(length));
+ }
+
+ const SVGLength& toSVGLength() const
+ {
+ return m_length;
+ }
+
+protected:
+ virtual PassRefPtr<AnimatableValue> interpolateTo(const AnimatableValue*, double fraction) const OVERRIDE;
+ virtual PassRefPtr<AnimatableValue> addWith(const AnimatableValue*) const OVERRIDE;
+
+private:
+ AnimatableSVGLength(const SVGLength& length)
+ : m_length(length)
+ {
+ }
+
+ virtual AnimatableType type() const { return TypeSVGLength; }
+ virtual bool equalTo(const AnimatableValue*) const OVERRIDE;
+
+ SVGLength m_length;
+};
+
+DEFINE_ANIMATABLE_VALUE_TYPE_CASTS(AnimatableSVGLength, isSVGLength());
+
+} // namespace WebCore
+
+#endif // AnimatableSVGLength_h
diff --git a/chromium/third_party/WebKit/Source/core/animation/AnimatableSVGPaint.cpp b/chromium/third_party/WebKit/Source/core/animation/AnimatableSVGPaint.cpp
new file mode 100644
index 00000000000..784c9d32558
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/animation/AnimatableSVGPaint.cpp
@@ -0,0 +1,64 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/animation/AnimatableSVGPaint.h"
+
+namespace WebCore {
+
+PassRefPtr<AnimatableValue> AnimatableSVGPaint::interpolateTo(const AnimatableValue* value, double fraction) const
+{
+ const AnimatableSVGPaint* svgPaint = toAnimatableSVGPaint(value);
+ if (paintType() == SVGPaint::SVG_PAINTTYPE_RGBCOLOR && svgPaint->paintType() == SVGPaint::SVG_PAINTTYPE_RGBCOLOR) {
+ ASSERT(uri().isNull());
+ return AnimatableSVGPaint::create(SVGPaint::SVG_PAINTTYPE_RGBCOLOR, m_color.interpolateTo(svgPaint->m_color, fraction), String());
+ }
+ return defaultInterpolateTo(this, value, fraction);
+}
+
+PassRefPtr<AnimatableValue> AnimatableSVGPaint::addWith(const AnimatableValue* value) const
+{
+ const AnimatableSVGPaint* svgPaint = toAnimatableSVGPaint(value);
+ if (paintType() != SVGPaint::SVG_PAINTTYPE_RGBCOLOR || svgPaint->paintType() != SVGPaint::SVG_PAINTTYPE_RGBCOLOR) {
+ ASSERT(uri().isNull());
+ return AnimatableSVGPaint::create(SVGPaint::SVG_PAINTTYPE_RGBCOLOR, m_color.addWith(svgPaint->m_color), String());
+ }
+ return defaultAddWith(this, value);
+}
+
+bool AnimatableSVGPaint::equalTo(const AnimatableValue* value) const
+{
+ const AnimatableSVGPaint* svgPaint = toAnimatableSVGPaint(value);
+ return paintType() == svgPaint->paintType()
+ && color() == svgPaint->color()
+ && uri() == svgPaint->uri();
+}
+
+}
diff --git a/chromium/third_party/WebKit/Source/core/animation/AnimatableSVGPaint.h b/chromium/third_party/WebKit/Source/core/animation/AnimatableSVGPaint.h
new file mode 100644
index 00000000000..93ebd2e8ca6
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/animation/AnimatableSVGPaint.h
@@ -0,0 +1,78 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef AnimatableSVGPaint_h
+#define AnimatableSVGPaint_h
+
+#include "core/animation/AnimatableColor.h"
+#include "core/animation/AnimatableValue.h"
+#include "core/svg/SVGPaint.h"
+
+namespace WebCore {
+
+class AnimatableSVGPaint : public AnimatableValue {
+public:
+ virtual ~AnimatableSVGPaint() { }
+ static PassRefPtr<AnimatableSVGPaint> create(SVGPaint::SVGPaintType type, const Color& color, const String& uri)
+ {
+ return create(type, AnimatableColorImpl(color), uri);
+ }
+ static PassRefPtr<AnimatableSVGPaint> create(SVGPaint::SVGPaintType type, const AnimatableColorImpl& color, const String& uri)
+ {
+ return adoptRef(new AnimatableSVGPaint(type, color, uri));
+ }
+ SVGPaint::SVGPaintType paintType() const { return m_type; };
+ Color color() const { return m_color.toColor(); };
+ const String& uri() const { return m_uri; };
+
+protected:
+ virtual PassRefPtr<AnimatableValue> interpolateTo(const AnimatableValue*, double fraction) const OVERRIDE;
+ virtual PassRefPtr<AnimatableValue> addWith(const AnimatableValue*) const OVERRIDE;
+
+private:
+ AnimatableSVGPaint(SVGPaint::SVGPaintType type, const AnimatableColorImpl& color, const String& uri)
+ : m_type(type)
+ , m_color(color)
+ , m_uri(uri)
+ {
+ }
+ virtual AnimatableType type() const OVERRIDE { return TypeSVGPaint; }
+ virtual bool equalTo(const AnimatableValue*) const OVERRIDE;
+
+ SVGPaint::SVGPaintType m_type;
+ AnimatableColorImpl m_color;
+ String m_uri;
+};
+
+DEFINE_ANIMATABLE_VALUE_TYPE_CASTS(AnimatableSVGPaint, isSVGPaint());
+
+} // namespace WebCore
+
+#endif // AnimatableSVGPaint_h
diff --git a/chromium/third_party/WebKit/Source/core/animation/AnimatableShadow.cpp b/chromium/third_party/WebKit/Source/core/animation/AnimatableShadow.cpp
new file mode 100644
index 00000000000..4d1a847f319
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/animation/AnimatableShadow.cpp
@@ -0,0 +1,55 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/animation/AnimatableShadow.h"
+
+namespace WebCore {
+
+PassRefPtr<AnimatableValue> AnimatableShadow::interpolateTo(const AnimatableValue* value, double fraction) const
+{
+ const AnimatableShadow* shadowList = toAnimatableShadow(value);
+ return AnimatableShadow::create(ShadowList::blend(m_shadowList.get(), shadowList->m_shadowList.get(), fraction));
+}
+
+PassRefPtr<AnimatableValue> AnimatableShadow::addWith(const AnimatableValue* value) const
+{
+ // FIXME: The spec doesn't specify anything for shadow in particular, but
+ // the default behaviour is probably not what one would expect.
+ return AnimatableValue::defaultAddWith(this, value);
+}
+
+bool AnimatableShadow::equalTo(const AnimatableValue* value) const
+{
+ const ShadowList* shadowList = toAnimatableShadow(value)->m_shadowList.get();
+ return m_shadowList == shadowList || (m_shadowList && shadowList && *m_shadowList == *shadowList);
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/animation/AnimatableShadow.h b/chromium/third_party/WebKit/Source/core/animation/AnimatableShadow.h
new file mode 100644
index 00000000000..23fb59b7a08
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/animation/AnimatableShadow.h
@@ -0,0 +1,67 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef AnimatableShadow_h
+#define AnimatableShadow_h
+
+#include "core/animation/AnimatableValue.h"
+#include "core/rendering/style/ShadowList.h"
+
+namespace WebCore {
+
+class AnimatableShadow : public AnimatableValue {
+public:
+ virtual ~AnimatableShadow() { }
+ static PassRefPtr<AnimatableShadow> create(PassRefPtr<ShadowList> shadowList)
+ {
+ return adoptRef(new AnimatableShadow(shadowList));
+ }
+ ShadowList* shadowList() const { return m_shadowList.get(); }
+
+protected:
+ virtual PassRefPtr<AnimatableValue> interpolateTo(const AnimatableValue*, double fraction) const OVERRIDE;
+ virtual PassRefPtr<AnimatableValue> addWith(const AnimatableValue*) const OVERRIDE;
+
+private:
+ explicit AnimatableShadow(PassRefPtr<ShadowList> shadowList)
+ : m_shadowList(shadowList)
+ {
+ }
+ virtual AnimatableType type() const OVERRIDE { return TypeShadow; }
+ virtual bool equalTo(const AnimatableValue*) const OVERRIDE;
+
+ const RefPtr<ShadowList> m_shadowList;
+};
+
+DEFINE_ANIMATABLE_VALUE_TYPE_CASTS(AnimatableShadow, isShadow());
+
+} // namespace WebCore
+
+#endif // AnimatableShadow_h
diff --git a/chromium/third_party/WebKit/Source/core/animation/AnimatableShapeValue.cpp b/chromium/third_party/WebKit/Source/core/animation/AnimatableShapeValue.cpp
new file mode 100644
index 00000000000..9b17295c273
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/animation/AnimatableShapeValue.cpp
@@ -0,0 +1,58 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/animation/AnimatableShapeValue.h"
+
+namespace WebCore {
+
+PassRefPtr<AnimatableValue> AnimatableShapeValue::interpolateTo(const AnimatableValue* value, double fraction) const
+{
+ const AnimatableShapeValue* shapeValue = toAnimatableShapeValue(value);
+
+ if (m_shape->type() != ShapeValue::Shape || shapeValue->m_shape->type() != ShapeValue::Shape)
+ return defaultInterpolateTo(this, value, fraction);
+
+ const BasicShape* fromShape = this->m_shape->shape();
+ const BasicShape* toShape = shapeValue->m_shape->shape();
+
+ if (!fromShape->canBlend(toShape))
+ return defaultInterpolateTo(this, value, fraction);
+
+ return AnimatableShapeValue::create(ShapeValue::createShapeValue(toShape->blend(fromShape, fraction)).get());
+}
+
+bool AnimatableShapeValue::equalTo(const AnimatableValue* value) const
+{
+ const ShapeValue* shape = toAnimatableShapeValue(value)->m_shape.get();
+ return m_shape == shape || (m_shape && shape && *m_shape == *shape);
+}
+
+}
diff --git a/chromium/third_party/WebKit/Source/core/animation/AnimatableShapeValue.h b/chromium/third_party/WebKit/Source/core/animation/AnimatableShapeValue.h
new file mode 100644
index 00000000000..1d5382b0548
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/animation/AnimatableShapeValue.h
@@ -0,0 +1,67 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef AnimatableShapeValue_h
+#define AnimatableShapeValue_h
+
+#include "core/animation/AnimatableValue.h"
+#include "core/rendering/style/ShapeValue.h"
+
+namespace WebCore {
+
+class AnimatableShapeValue : public AnimatableValue {
+public:
+ virtual ~AnimatableShapeValue() { }
+ static PassRefPtr<AnimatableShapeValue> create(ShapeValue* shape)
+ {
+ return adoptRef(new AnimatableShapeValue(shape));
+ }
+ ShapeValue* shapeValue() const { return m_shape.get(); }
+
+protected:
+ virtual PassRefPtr<AnimatableValue> interpolateTo(const AnimatableValue*, double fraction) const OVERRIDE;
+
+private:
+ AnimatableShapeValue(ShapeValue* shape)
+ : m_shape(shape)
+ {
+ ASSERT(m_shape);
+ }
+ virtual AnimatableType type() const OVERRIDE { return TypeShapeValue; }
+ virtual bool equalTo(const AnimatableValue*) const OVERRIDE;
+
+ RefPtr<ShapeValue> m_shape;
+};
+
+DEFINE_ANIMATABLE_VALUE_TYPE_CASTS(AnimatableShapeValue, isShapeValue());
+
+} // namespace WebCore
+
+#endif // AnimatableShapeValue_h
diff --git a/chromium/third_party/WebKit/Source/core/animation/AnimatableStrokeDasharrayList.cpp b/chromium/third_party/WebKit/Source/core/animation/AnimatableStrokeDasharrayList.cpp
new file mode 100644
index 00000000000..b8951cc4cad
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/animation/AnimatableStrokeDasharrayList.cpp
@@ -0,0 +1,91 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/animation/AnimatableStrokeDasharrayList.h"
+
+#include "bindings/v8/ExceptionStatePlaceholder.h"
+#include "core/animation/AnimatableSVGLength.h"
+
+namespace WebCore {
+
+AnimatableStrokeDasharrayList::AnimatableStrokeDasharrayList(const Vector<SVGLength>& lengths)
+{
+ for (size_t i = 0; i < lengths.size(); ++i)
+ m_values.append(AnimatableSVGLength::create(lengths[i]));
+}
+
+Vector<SVGLength> AnimatableStrokeDasharrayList::toSVGLengthVector() const
+{
+ Vector<SVGLength> lengths(m_values.size());
+ for (size_t i = 0; i < m_values.size(); ++i) {
+ lengths[i] = toAnimatableSVGLength(m_values[i].get())->toSVGLength();
+ if (lengths[i].valueInSpecifiedUnits() < 0)
+ lengths[i].setValueInSpecifiedUnits(0);
+ }
+ return lengths;
+}
+
+PassRefPtr<AnimatableValue> AnimatableStrokeDasharrayList::interpolateTo(const AnimatableValue* value, double fraction) const
+{
+ Vector<RefPtr<AnimatableValue> > from = m_values;
+ Vector<RefPtr<AnimatableValue> > to = toAnimatableStrokeDasharrayList(value)->m_values;
+
+ // The spec states that if the sum of all values is zero, this should be
+ // treated like a value of 'none', which means that a solid line is drawn.
+ // Since we animate to and from values of zero, treat a value of 'none' the
+ // same. If both the two and from values are 'none', we return 'none'
+ // rather than '0 0'.
+ if (from.isEmpty() && to.isEmpty())
+ return takeConstRef(this);
+ if (from.isEmpty() || to.isEmpty()) {
+ DEFINE_STATIC_REF(AnimatableSVGLength, zeroPixels, 0);
+ if (!zeroPixels) {
+ SVGLength length;
+ length.newValueSpecifiedUnits(LengthTypePX, 0, IGNORE_EXCEPTION);
+ zeroPixels = AnimatableSVGLength::create(length).leakRef();
+ }
+ if (from.isEmpty()) {
+ from.append(zeroPixels);
+ from.append(zeroPixels);
+ }
+ if (to.isEmpty()) {
+ to.append(zeroPixels);
+ to.append(zeroPixels);
+ }
+ }
+
+ Vector<RefPtr<AnimatableValue> > interpolatedValues;
+ bool success = interpolateLists(from, to, fraction, interpolatedValues);
+ ASSERT_UNUSED(success, success);
+ return adoptRef(new AnimatableStrokeDasharrayList(interpolatedValues));
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/animation/AnimatableStrokeDasharrayList.h b/chromium/third_party/WebKit/Source/core/animation/AnimatableStrokeDasharrayList.h
new file mode 100644
index 00000000000..d19b2e017ac
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/animation/AnimatableStrokeDasharrayList.h
@@ -0,0 +1,68 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef AnimatableStrokeDasharrayList_h
+#define AnimatableStrokeDasharrayList_h
+
+#include "core/animation/AnimatableRepeatable.h"
+#include "core/svg/SVGLength.h"
+
+namespace WebCore {
+
+class AnimatableStrokeDasharrayList: public AnimatableRepeatable {
+public:
+ virtual ~AnimatableStrokeDasharrayList() { }
+
+ static PassRefPtr<AnimatableStrokeDasharrayList> create(const Vector<SVGLength>& lengths)
+ {
+ return adoptRef(new AnimatableStrokeDasharrayList(lengths));
+ }
+
+ Vector<SVGLength> toSVGLengthVector() const;
+
+protected:
+ virtual PassRefPtr<AnimatableValue> interpolateTo(const AnimatableValue*, double fraction) const OVERRIDE;
+
+private:
+ AnimatableStrokeDasharrayList(const Vector<SVGLength>&);
+ // This will consume the vector passed into it.
+ AnimatableStrokeDasharrayList(Vector<RefPtr<AnimatableValue> >& values)
+ : AnimatableRepeatable(values)
+ {
+ }
+
+ virtual AnimatableType type() const { return TypeStrokeDasharrayList; }
+};
+
+DEFINE_ANIMATABLE_VALUE_TYPE_CASTS(AnimatableStrokeDasharrayList, isStrokeDasharrayList());
+
+} // namespace WebCore
+
+#endif // AnimatableStrokeDasharrayList_h
diff --git a/chromium/third_party/WebKit/Source/core/animation/AnimatableStrokeDasharrayListTest.cpp b/chromium/third_party/WebKit/Source/core/animation/AnimatableStrokeDasharrayListTest.cpp
new file mode 100644
index 00000000000..6a2756d2504
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/animation/AnimatableStrokeDasharrayListTest.cpp
@@ -0,0 +1,60 @@
+/*
+ * Copyright (c) 2013, Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/animation/AnimatableStrokeDasharrayList.h"
+
+#include "core/svg/SVGLength.h"
+
+#include <gtest/gtest.h>
+
+using namespace WebCore;
+
+namespace {
+
+TEST(AnimationAnimatableStrokeDasharrayListTest, EqualTo)
+{
+ Vector<SVGLength> vectorA(4);
+ Vector<SVGLength> vectorB(4);
+ RefPtr<AnimatableStrokeDasharrayList> listA = AnimatableStrokeDasharrayList::create(vectorA);
+ RefPtr<AnimatableStrokeDasharrayList> listB = AnimatableStrokeDasharrayList::create(vectorB);
+ EXPECT_TRUE(listA->equals(listB.get()));
+
+ TrackExceptionState exceptionState;
+ vectorB[3].newValueSpecifiedUnits(LengthTypePX, 50, exceptionState);
+ listB = AnimatableStrokeDasharrayList::create(vectorB);
+ EXPECT_FALSE(listA->equals(listB.get()));
+
+ vectorB = Vector<SVGLength>(5);
+ listB = AnimatableStrokeDasharrayList::create(vectorB);
+ EXPECT_FALSE(listA->equals(listB.get()));
+}
+
+} // namespace
diff --git a/chromium/third_party/WebKit/Source/core/animation/AnimatableTransform.cpp b/chromium/third_party/WebKit/Source/core/animation/AnimatableTransform.cpp
index 8606a25a179..542d8c315b0 100644
--- a/chromium/third_party/WebKit/Source/core/animation/AnimatableTransform.cpp
+++ b/chromium/third_party/WebKit/Source/core/animation/AnimatableTransform.cpp
@@ -50,5 +50,10 @@ PassRefPtr<AnimatableValue> AnimatableTransform::addWith(const AnimatableValue*
return AnimatableTransform::create(m_transform.add(transform->m_transform));
}
+bool AnimatableTransform::equalTo(const AnimatableValue* value) const
+{
+ return m_transform == toAnimatableTransform(value)->m_transform;
+}
+
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/animation/AnimatableTransform.h b/chromium/third_party/WebKit/Source/core/animation/AnimatableTransform.h
index a0e71dfb61f..7fa85323fbc 100644
--- a/chromium/third_party/WebKit/Source/core/animation/AnimatableTransform.h
+++ b/chromium/third_party/WebKit/Source/core/animation/AnimatableTransform.h
@@ -32,7 +32,7 @@
#define AnimatableTransform_h
#include "core/animation/AnimatableValue.h"
-#include "core/platform/graphics/transforms/TransformOperations.h"
+#include "platform/transforms/TransformOperations.h"
namespace WebCore {
@@ -51,18 +51,15 @@ protected:
private:
explicit AnimatableTransform(const TransformOperations& transform)
- : AnimatableValue(TypeTransform)
- , m_transform(transform)
+ : m_transform(transform)
{
}
+ virtual AnimatableType type() const OVERRIDE { return TypeTransform; }
+ virtual bool equalTo(const AnimatableValue*) const OVERRIDE;
const TransformOperations m_transform;
};
-inline const AnimatableTransform* toAnimatableTransform(const AnimatableValue* value)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(value && value->isTransform());
- return static_cast<const AnimatableTransform*>(value);
-}
+DEFINE_ANIMATABLE_VALUE_TYPE_CASTS(AnimatableTransform, isTransform());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/animation/AnimatableUnknown.h b/chromium/third_party/WebKit/Source/core/animation/AnimatableUnknown.h
index 1c0d2c6ae08..43be1c8568c 100644
--- a/chromium/third_party/WebKit/Source/core/animation/AnimatableUnknown.h
+++ b/chromium/third_party/WebKit/Source/core/animation/AnimatableUnknown.h
@@ -31,7 +31,9 @@
#ifndef AnimatableUnknown_h
#define AnimatableUnknown_h
+#include "CSSValueKeywords.h"
#include "core/animation/AnimatableValue.h"
+#include "core/css/CSSValuePool.h"
namespace WebCore {
@@ -43,8 +45,13 @@ public:
{
return adoptRef(new AnimatableUnknown(value));
}
+ static PassRefPtr<AnimatableUnknown> create(CSSValueID value)
+ {
+ return adoptRef(new AnimatableUnknown(cssValuePool().createIdentifierValue(value)));
+ }
PassRefPtr<CSSValue> toCSSValue() const { return m_value; }
+ CSSValueID toCSSValueID() const { return toCSSPrimitiveValue(m_value.get())->getValueID(); }
protected:
virtual PassRefPtr<AnimatableValue> interpolateTo(const AnimatableValue* value, double fraction) const OVERRIDE
@@ -54,19 +61,22 @@ protected:
private:
explicit AnimatableUnknown(PassRefPtr<CSSValue> value)
- : AnimatableValue(TypeUnknown)
- , m_value(value)
+ : m_value(value)
{
ASSERT(m_value);
}
+ virtual AnimatableType type() const OVERRIDE { return TypeUnknown; }
+ virtual bool equalTo(const AnimatableValue*) const OVERRIDE;
const RefPtr<CSSValue> m_value;
};
-inline const AnimatableUnknown* toAnimatableUnknown(const AnimatableValue* value)
+DEFINE_ANIMATABLE_VALUE_TYPE_CASTS(AnimatableUnknown, isUnknown());
+
+inline bool AnimatableUnknown::equalTo(const AnimatableValue* value) const
{
- ASSERT_WITH_SECURITY_IMPLICATION(value && value->isUnknown());
- return static_cast<const AnimatableUnknown*>(value);
+ const AnimatableUnknown* unknown = toAnimatableUnknown(value);
+ return m_value == unknown->m_value || m_value->equals(*unknown->m_value);
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/animation/AnimatableUnknownTest.cpp b/chromium/third_party/WebKit/Source/core/animation/AnimatableUnknownTest.cpp
index 60557e406f5..5ca17607108 100644
--- a/chromium/third_party/WebKit/Source/core/animation/AnimatableUnknownTest.cpp
+++ b/chromium/third_party/WebKit/Source/core/animation/AnimatableUnknownTest.cpp
@@ -40,7 +40,7 @@ using namespace WebCore;
namespace {
-class AnimatableUnknownTest : public ::testing::Test {
+class AnimationAnimatableUnknownTest : public ::testing::Test {
protected:
virtual void SetUp()
{
@@ -58,17 +58,17 @@ protected:
RefPtr<AnimatableValue> otherAnimatableUnknown;
};
-TEST_F(AnimatableUnknownTest, Create)
+TEST_F(AnimationAnimatableUnknownTest, Create)
{
EXPECT_TRUE(animatableUnknown);
}
-TEST_F(AnimatableUnknownTest, ToCSSValue)
+TEST_F(AnimationAnimatableUnknownTest, ToCSSValue)
{
EXPECT_EQ(cssValue, toAnimatableUnknown(animatableUnknown.get())->toCSSValue());
}
-TEST_F(AnimatableUnknownTest, Interpolate)
+TEST_F(AnimationAnimatableUnknownTest, Interpolate)
{
EXPECT_EQ(cssValue, toAnimatableUnknown(AnimatableValue::interpolate(animatableUnknown.get(), otherAnimatableUnknown.get(), 0).get())->toCSSValue());
EXPECT_EQ(cssValue, toAnimatableUnknown(AnimatableValue::interpolate(animatableUnknown.get(), otherAnimatableUnknown.get(), 0.4).get())->toCSSValue());
@@ -83,7 +83,7 @@ TEST_F(AnimatableUnknownTest, Interpolate)
EXPECT_EQ(cssValue, toAnimatableUnknown(AnimatableValue::interpolate(otherAnimatableUnknown.get(), animatableUnknown.get(), 1).get())->toCSSValue());
}
-TEST_F(AnimatableUnknownTest, Add)
+TEST_F(AnimationAnimatableUnknownTest, Add)
{
EXPECT_EQ(otherCSSValue, toAnimatableUnknown(AnimatableValue::add(animatableUnknown.get(), otherAnimatableUnknown.get()).get())->toCSSValue());
EXPECT_EQ(cssValue, toAnimatableUnknown(AnimatableValue::add(otherAnimatableUnknown.get(), animatableUnknown.get()).get())->toCSSValue());
diff --git a/chromium/third_party/WebKit/Source/core/animation/AnimatableValue.cpp b/chromium/third_party/WebKit/Source/core/animation/AnimatableValue.cpp
index 5c0d57bec91..1c9d1751ca0 100644
--- a/chromium/third_party/WebKit/Source/core/animation/AnimatableValue.cpp
+++ b/chromium/third_party/WebKit/Source/core/animation/AnimatableValue.cpp
@@ -31,13 +31,14 @@
#include "config.h"
#include "core/animation/AnimatableValue.h"
#include "core/animation/AnimatableNeutral.h"
+#include "wtf/StdLibExtras.h"
#include <algorithm>
namespace WebCore {
const AnimatableValue* AnimatableValue::neutralValue()
{
- static AnimatableNeutral* neutralSentinelValue = AnimatableNeutral::create().leakRef();
+ DEFINE_STATIC_REF(AnimatableNeutral, neutralSentinelValue, (AnimatableNeutral::create()));
return neutralSentinelValue;
}
diff --git a/chromium/third_party/WebKit/Source/core/animation/AnimatableValue.h b/chromium/third_party/WebKit/Source/core/animation/AnimatableValue.h
index 3c1659318ff..2e52c321e95 100644
--- a/chromium/third_party/WebKit/Source/core/animation/AnimatableValue.h
+++ b/chromium/third_party/WebKit/Source/core/animation/AnimatableValue.h
@@ -46,35 +46,71 @@ public:
// For noncommutative values read add(A, B) to mean the value A with B composed onto it.
static PassRefPtr<AnimatableValue> add(const AnimatableValue*, const AnimatableValue*);
- bool isColor() const { return m_type == TypeColor; }
- bool isImage() const { return m_type == TypeImage; }
- bool isLengthBox() const { return m_type == TypeLengthBox; }
- bool isNumber() const { return m_type == TypeNumber; }
- bool isNeutral() const { return m_type == TypeNeutral; }
- bool isTransform() const { return m_type == TypeTransform; }
- bool isUnknown() const { return m_type == TypeUnknown; }
- bool isVisibility() const { return m_type == TypeVisibility; }
+ bool equals(const AnimatableValue* value) const
+ {
+ return isSameType(value) && equalTo(value);
+ }
+ bool equals(const AnimatableValue& value) const
+ {
+ return equals(&value);
+ }
+
+ bool isClipPathOperation() const { return type() == TypeClipPathOperation; }
+ bool isColor() const { return type() == TypeColor; }
+ bool isDouble() const { return type() == TypeDouble; }
+ bool isFilterOperations() const { return type() == TypeFilterOperations; }
+ bool isImage() const { return type() == TypeImage; }
+ bool isLength() const { return type() == TypeLength; }
+ bool isLengthBox() const { return type() == TypeLengthBox; }
+ bool isLengthBoxAndBool() const { return type() == TypeLengthBoxAndBool; }
+ bool isLengthPoint() const { return type() == TypeLengthPoint; }
+ bool isLengthSize() const { return type() == TypeLengthSize; }
+ bool isNeutral() const { return type() == TypeNeutral; }
+ bool isRepeatable() const { return type() == TypeRepeatable; }
+ bool isSVGLength() const { return type() == TypeSVGLength; }
+ bool isSVGPaint() const { return type() == TypeSVGPaint; }
+ bool isShadow() const { return type() == TypeShadow; }
+ bool isShapeValue() const { return type() == TypeShapeValue; }
+ bool isStrokeDasharrayList() const { return type() == TypeStrokeDasharrayList; }
+ bool isTransform() const { return type() == TypeTransform; }
+ bool isUnknown() const { return type() == TypeUnknown; }
+ bool isVisibility() const { return type() == TypeVisibility; }
+
+ bool isSameType(const AnimatableValue* value) const
+ {
+ ASSERT(value);
+ return value->type() == type();
+ }
+
+ bool usesNonDefaultInterpolationWith(const AnimatableValue* value) const
+ {
+ return isSameType(value) && !isUnknown();
+ }
protected:
enum AnimatableType {
+ TypeClipPathOperation,
TypeColor,
+ TypeDouble,
+ TypeFilterOperations,
TypeImage,
+ TypeLength,
TypeLengthBox,
+ TypeLengthBoxAndBool,
+ TypeLengthPoint,
+ TypeLengthSize,
TypeNeutral,
- TypeNumber,
+ TypeRepeatable,
+ TypeSVGLength,
+ TypeSVGPaint,
+ TypeShadow,
+ TypeShapeValue,
+ TypeStrokeDasharrayList,
TypeTransform,
TypeUnknown,
TypeVisibility,
};
- AnimatableValue(AnimatableType type) : m_type(type) { }
-
- bool isSameType(const AnimatableValue* value) const
- {
- ASSERT(value);
- return value->m_type == m_type;
- }
-
virtual PassRefPtr<AnimatableValue> interpolateTo(const AnimatableValue*, double fraction) const = 0;
static PassRefPtr<AnimatableValue> defaultInterpolateTo(const AnimatableValue* left, const AnimatableValue* right, double fraction) { return takeConstRef((fraction < 0.5) ? left : right); }
@@ -85,9 +121,15 @@ protected:
template <class T>
static PassRefPtr<T> takeConstRef(const T* value) { return PassRefPtr<T>(const_cast<T*>(value)); }
- const AnimatableType m_type;
+private:
+ virtual AnimatableType type() const = 0;
+ // Implementations can assume that the object being compared has the same type as the object this is called on
+ virtual bool equalTo(const AnimatableValue*) const = 0;
};
+#define DEFINE_ANIMATABLE_VALUE_TYPE_CASTS(thisType, predicate) \
+ DEFINE_TYPE_CASTS(thisType, AnimatableValue, value, value->predicate, value.predicate)
+
} // namespace WebCore
#endif // AnimatableValue_h
diff --git a/chromium/third_party/WebKit/Source/core/animation/AnimatableValueTestHelper.cpp b/chromium/third_party/WebKit/Source/core/animation/AnimatableValueTestHelper.cpp
new file mode 100644
index 00000000000..da6958cfc21
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/animation/AnimatableValueTestHelper.cpp
@@ -0,0 +1,269 @@
+/*
+ * Copyright (c) 2013, Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+
+#include "core/animation/AnimatableValueTestHelper.h"
+
+
+
+namespace WebCore {
+
+bool operator==(const AnimatableValue& a, const AnimatableValue& b)
+{
+ return a.equals(b);
+}
+
+void PrintTo(const AnimatableClipPathOperation& animValue, ::std::ostream* os)
+{
+ *os << "AnimatableClipPathOperation@" << &animValue;
+}
+
+void PrintTo(const AnimatableColor& animColor, ::std::ostream* os)
+{
+ *os << "AnimatableColor("
+ << animColor.color().serialized().utf8().data() << ", "
+ << animColor.visitedLinkColor().serialized().utf8().data() << ")";
+}
+
+void PrintTo(const AnimatableDouble& animDouble, ::std::ostream* os)
+{
+ PrintTo(*(animDouble.toCSSValue().get()), os, "AnimatableDouble");
+}
+
+void PrintTo(const AnimatableImage& animImage, ::std::ostream* os)
+{
+ PrintTo(*(animImage.toCSSValue().get()), os, "AnimatableImage");
+}
+
+void PrintTo(const AnimatableLength& animLength, ::std::ostream* os)
+{
+ PrintTo(*(animLength.toCSSValue().get()), os, "AnimatableLength");
+}
+
+void PrintTo(const AnimatableLengthBox& animLengthBox, ::std::ostream* os)
+{
+ *os << "AnimatableLengthBox(";
+ PrintTo(*(animLengthBox.left()), os);
+ *os << ", ";
+ PrintTo(*(animLengthBox.right()), os);
+ *os << ", ";
+ PrintTo(*(animLengthBox.top()), os);
+ *os << ", ";
+ PrintTo(*(animLengthBox.bottom()), os);
+ *os << ")";
+}
+
+void PrintTo(const AnimatableLengthPoint& animLengthPoint, ::std::ostream* os)
+{
+ *os << "AnimatableLengthPoint(";
+ PrintTo(*(animLengthPoint.x()), os);
+ *os << ", ";
+ PrintTo(*(animLengthPoint.y()), os);
+ *os << ")";
+}
+
+void PrintTo(const AnimatableLengthSize& animLengthSize, ::std::ostream* os)
+{
+ *os << "AnimatableLengthSize(";
+ PrintTo(*(animLengthSize.width()), os);
+ *os << ", ";
+ PrintTo(*(animLengthSize.height()), os);
+ *os << ")";
+}
+
+void PrintTo(const AnimatableNeutral& animValue, ::std::ostream* os)
+{
+ *os << "AnimatableNeutral@" << &animValue;
+}
+
+void PrintTo(const AnimatableRepeatable& animValue, ::std::ostream* os)
+{
+ *os << "AnimatableRepeatable(";
+
+ const Vector<RefPtr<AnimatableValue> > v = animValue.values();
+ for (Vector<RefPtr<AnimatableValue> >::const_iterator it = v.begin(); it != v.end(); ++it) {
+ PrintTo(*(it->get()), os);
+ if (it+1 != v.end())
+ *os << ", ";
+ }
+ *os << ")";
+}
+
+void PrintTo(const AnimatableSVGLength& animSVGLength, ::std::ostream* os)
+{
+ *os << "AnimatableSVGLength("
+ << animSVGLength.toSVGLength().valueAsString().utf8().data() << ")";
+}
+
+void PrintTo(const AnimatableSVGPaint& animSVGPaint, ::std::ostream* os)
+{
+ *os << "AnimatableSVGPaint(";
+ if (animSVGPaint.paintType() == SVGPaint::SVG_PAINTTYPE_RGBCOLOR)
+ *os << animSVGPaint.color().serialized().utf8().data();
+ else if (animSVGPaint.paintType() == SVGPaint::SVG_PAINTTYPE_URI)
+ *os << "url(" << animSVGPaint.uri().utf8().data() << ")";
+ else
+ *os << animSVGPaint.paintType();
+ *os << ")";
+}
+
+void PrintTo(const AnimatableShapeValue& animValue, ::std::ostream* os)
+{
+ *os << "AnimatableShapeValue@" << &animValue;
+}
+
+void PrintTo(const AnimatableStrokeDasharrayList& animValue, ::std::ostream* os)
+{
+ *os << "AnimatableStrokeDasharrayList(";
+ const Vector<SVGLength> v = animValue.toSVGLengthVector();
+ for (Vector<SVGLength>::const_iterator it = v.begin(); it != v.end(); ++it) {
+ *os << it->valueAsString().utf8().data();
+ if (it+1 != v.end())
+ *os << ", ";
+ }
+ *os << ")";
+}
+
+void PrintTo(const AnimatableTransform& animTransform, ::std::ostream* os)
+{
+ TransformOperations ops = animTransform.transformOperations();
+
+ *os << "AnimatableTransform(";
+ // FIXME: TransformOperations should really have it's own pretty-printer
+ // then we could just call that.
+ // FIXME: Output useful names not just the raw matrixes.
+ for (unsigned i = 0; i < ops.size(); i++) {
+ const TransformOperation* op = ops.at(i);
+
+ TransformationMatrix matrix;
+ op->apply(matrix, FloatSize(1.0, 1.0));
+
+ *os << "[";
+ if (matrix.isAffine()) {
+ *os << matrix.a();
+ *os << " " << matrix.b();
+ *os << " " << matrix.c();
+ *os << " " << matrix.d();
+ *os << " " << matrix.e();
+ *os << " " << matrix.f();
+ } else {
+ *os << matrix.m11();
+ *os << " " << matrix.m12();
+ *os << " " << matrix.m13();
+ *os << " " << matrix.m14();
+ *os << " ";
+ *os << " " << matrix.m21();
+ *os << " " << matrix.m22();
+ *os << " " << matrix.m23();
+ *os << " " << matrix.m24();
+ *os << " ";
+ *os << " " << matrix.m31();
+ *os << " " << matrix.m32();
+ *os << " " << matrix.m33();
+ *os << " " << matrix.m34();
+ *os << " ";
+ *os << " " << matrix.m41();
+ *os << " " << matrix.m42();
+ *os << " " << matrix.m43();
+ *os << " " << matrix.m44();
+ }
+ *os << "]";
+ if (i < ops.size() - 1)
+ *os << ", ";
+ }
+ *os << ")";
+}
+
+void PrintTo(const AnimatableUnknown& animUnknown, ::std::ostream* os)
+{
+ PrintTo(*(animUnknown.toCSSValue().get()), os, "AnimatableUnknown");
+}
+
+void PrintTo(const AnimatableVisibility& animVisibility, ::std::ostream* os)
+{
+ *os << "AnimatableVisibility(";
+ switch (animVisibility.visibility()) {
+ case VISIBLE:
+ *os << "VISIBLE";
+ break;
+ case HIDDEN:
+ *os << "HIDDEN";
+ break;
+ case COLLAPSE:
+ *os << "COLLAPSE";
+ break;
+ default:
+ *os << "Unknown Visbilility - update switch in AnimatableValueTestHelper.h";
+ }
+ *os << ")";
+}
+
+void PrintTo(const AnimatableValue& animValue, ::std::ostream* os)
+{
+ if (animValue.isClipPathOperation())
+ PrintTo(*(toAnimatableClipPathOperation(&animValue)), os);
+ else if (animValue.isColor())
+ PrintTo(*(toAnimatableColor(&animValue)), os);
+ else if (animValue.isDouble())
+ PrintTo(*(toAnimatableDouble(&animValue)), os);
+ else if (animValue.isImage())
+ PrintTo(*(toAnimatableImage(&animValue)), os);
+ else if (animValue.isLength())
+ PrintTo(*(toAnimatableLength(&animValue)), os);
+ else if (animValue.isLengthBox())
+ PrintTo(*(toAnimatableLengthBox(&animValue)), os);
+ else if (animValue.isLengthPoint())
+ PrintTo(*(toAnimatableLengthPoint(&animValue)), os);
+ else if (animValue.isLengthSize())
+ PrintTo(*(toAnimatableLengthSize(&animValue)), os);
+ else if (animValue.isNeutral())
+ PrintTo(*(static_cast<const AnimatableNeutral*>(&animValue)), os);
+ else if (animValue.isRepeatable())
+ PrintTo(*(toAnimatableRepeatable(&animValue)), os);
+ else if (animValue.isSVGLength())
+ PrintTo(*(toAnimatableSVGLength(&animValue)), os);
+ else if (animValue.isSVGPaint())
+ PrintTo(*(toAnimatableSVGPaint(&animValue)), os);
+ else if (animValue.isShapeValue())
+ PrintTo(*(toAnimatableShapeValue(&animValue)), os);
+ else if (animValue.isStrokeDasharrayList())
+ PrintTo(*(toAnimatableStrokeDasharrayList(&animValue)), os);
+ else if (animValue.isTransform())
+ PrintTo(*(toAnimatableTransform(&animValue)), os);
+ else if (animValue.isUnknown())
+ PrintTo(*(toAnimatableUnknown(&animValue)), os);
+ else if (animValue.isVisibility())
+ PrintTo(*(toAnimatableVisibility(&animValue)), os);
+ else
+ *os << "Unknown AnimatableValue - update ifelse chain in AnimatableValueTestHelper.h";
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/animation/AnimatableValueTestHelper.h b/chromium/third_party/WebKit/Source/core/animation/AnimatableValueTestHelper.h
new file mode 100644
index 00000000000..65a86606768
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/animation/AnimatableValueTestHelper.h
@@ -0,0 +1,90 @@
+/*
+ * Copyright (c) 2013, Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * Make testing with gtest and gmock nicer by adding pretty print and other
+ * helper functions.
+ */
+
+#ifndef AnimatableValueTestHelper_h
+#define AnimatableValueTestHelper_h
+
+#include "core/animation/AnimatableClipPathOperation.h"
+#include "core/animation/AnimatableColor.h"
+#include "core/animation/AnimatableDouble.h"
+#include "core/animation/AnimatableImage.h"
+#include "core/animation/AnimatableLength.h"
+#include "core/animation/AnimatableLengthBox.h"
+#include "core/animation/AnimatableLengthPoint.h"
+#include "core/animation/AnimatableLengthSize.h"
+#include "core/animation/AnimatableNeutral.h"
+#include "core/animation/AnimatableRepeatable.h"
+#include "core/animation/AnimatableSVGLength.h"
+#include "core/animation/AnimatableSVGPaint.h"
+#include "core/animation/AnimatableShapeValue.h"
+#include "core/animation/AnimatableStrokeDasharrayList.h"
+#include "core/animation/AnimatableTransform.h"
+#include "core/animation/AnimatableUnknown.h"
+#include "core/animation/AnimatableValue.h"
+#include "core/animation/AnimatableVisibility.h"
+
+#include "core/css/CSSValueTestHelper.h"
+
+// FIXME: Move to something like core/wtf/WTFTestHelpers.h
+// Compares the targets of two RefPtrs for equality.
+// (Objects still need an operator== defined for this to work).
+#define EXPECT_REFV_EQ(a, b) EXPECT_EQ(*(a.get()), *(b.get()))
+
+namespace WebCore {
+
+bool operator==(const AnimatableValue&, const AnimatableValue&);
+
+void PrintTo(const AnimatableClipPathOperation&, ::std::ostream*);
+void PrintTo(const AnimatableColor&, ::std::ostream*);
+void PrintTo(const AnimatableDouble&, ::std::ostream*);
+void PrintTo(const AnimatableImage&, ::std::ostream*);
+void PrintTo(const AnimatableLength&, ::std::ostream*);
+void PrintTo(const AnimatableLengthBox&, ::std::ostream*);
+void PrintTo(const AnimatableLengthPoint&, ::std::ostream*);
+void PrintTo(const AnimatableLengthSize&, ::std::ostream*);
+void PrintTo(const AnimatableNeutral&, ::std::ostream*);
+void PrintTo(const AnimatableRepeatable&, ::std::ostream*);
+void PrintTo(const AnimatableSVGLength&, ::std::ostream*);
+void PrintTo(const AnimatableSVGPaint&, ::std::ostream*);
+void PrintTo(const AnimatableShapeValue&, ::std::ostream*);
+void PrintTo(const AnimatableStrokeDasharrayList&, ::std::ostream*);
+void PrintTo(const AnimatableTransform&, ::std::ostream*);
+void PrintTo(const AnimatableUnknown&, ::std::ostream*);
+void PrintTo(const AnimatableValue&, ::std::ostream*);
+void PrintTo(const AnimatableVisibility&, ::std::ostream*);
+
+} // namespace WebCore
+
+#endif
diff --git a/chromium/third_party/WebKit/Source/core/animation/AnimatableValueTestHelperTest.cpp b/chromium/third_party/WebKit/Source/core/animation/AnimatableValueTestHelperTest.cpp
new file mode 100644
index 00000000000..fad1a5a55e4
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/animation/AnimatableValueTestHelperTest.cpp
@@ -0,0 +1,161 @@
+/*
+ * Copyright (c) 2013, Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+
+#include "core/animation/AnimatableValueTestHelper.h"
+
+#include "core/rendering/ClipPathOperation.h"
+#include "core/rendering/style/BasicShapes.h"
+#include "core/svg/SVGLengthContext.h"
+#include "platform/transforms/ScaleTransformOperation.h"
+#include "platform/transforms/TranslateTransformOperation.h"
+
+#include <gmock/gmock.h>
+#include <gtest/gtest.h>
+#include <sstream>
+#include <string>
+
+
+using namespace WebCore;
+
+namespace {
+
+class AnimationAnimatableValueTestHelperTest : public ::testing::Test {
+protected:
+ ::std::string PrintToString(PassRefPtr<AnimatableValue> animValue)
+ {
+ return PrintToString(animValue.get());
+ }
+
+ ::std::string PrintToString(const AnimatableValue* animValue)
+ {
+ return ::testing::PrintToString(*animValue);
+ }
+};
+
+TEST_F(AnimationAnimatableValueTestHelperTest, PrintTo)
+{
+ EXPECT_THAT(
+ PrintToString(AnimatableClipPathOperation::create(ShapeClipPathOperation::create(BasicShapeCircle::create().get()).get())),
+ testing::StartsWith("AnimatableClipPathOperation")
+ );
+
+ EXPECT_EQ(
+ ::std::string("AnimatableColor(rgba(0, 0, 0, 0), #ff0000)"),
+ PrintToString(AnimatableColor::create(Color(0x000000FF), Color(0xFFFF0000))));
+
+ EXPECT_EQ(
+ ::std::string("AnimatableDouble(1)"),
+ PrintToString(AnimatableDouble::create(1.0)));
+
+ EXPECT_EQ(
+ ::std::string("AnimatableLength(5px)"),
+ PrintToString(AnimatableLength::create(CSSPrimitiveValue::create(5, CSSPrimitiveValue::CSS_PX).get())));
+
+ EXPECT_EQ(
+ ::std::string("AnimatableLengthBox(AnimatableLength(1px), AnimatableLength(2em), AnimatableLength(3rem), AnimatableLength(4pt))"),
+ PrintToString(AnimatableLengthBox::create(
+ AnimatableLength::create(CSSPrimitiveValue::create(1, CSSPrimitiveValue::CSS_PX).get()),
+ AnimatableLength::create(CSSPrimitiveValue::create(2, CSSPrimitiveValue::CSS_EMS).get()),
+ AnimatableLength::create(CSSPrimitiveValue::create(3, CSSPrimitiveValue::CSS_REMS).get()),
+ AnimatableLength::create(CSSPrimitiveValue::create(4, CSSPrimitiveValue::CSS_PT).get())
+ )));
+
+ EXPECT_EQ(
+ ::std::string("AnimatableLengthPoint(AnimatableLength(5%), AnimatableLength(6px))"),
+ PrintToString(AnimatableLengthPoint::create(
+ AnimatableLength::create(CSSPrimitiveValue::create(5, CSSPrimitiveValue::CSS_PERCENTAGE).get()),
+ AnimatableLength::create(CSSPrimitiveValue::create(6, CSSPrimitiveValue::CSS_PX).get())
+ )));
+
+ EXPECT_EQ(
+ ::std::string("AnimatableLengthSize(AnimatableLength(3rem), AnimatableLength(4pt))"),
+ PrintToString(AnimatableLengthSize::create(
+ AnimatableLength::create(CSSPrimitiveValue::create(3, CSSPrimitiveValue::CSS_REMS).get()),
+ AnimatableLength::create(CSSPrimitiveValue::create(4, CSSPrimitiveValue::CSS_PT).get())
+ )));
+
+ EXPECT_THAT(
+ PrintToString(AnimatableValue::neutralValue()),
+ testing::StartsWith("AnimatableNeutral@"));
+
+ Vector<RefPtr<AnimatableValue> > v1;
+ v1.append(AnimatableLength::create(CSSPrimitiveValue::create(3, CSSPrimitiveValue::CSS_REMS).get()));
+ v1.append(AnimatableLength::create(CSSPrimitiveValue::create(4, CSSPrimitiveValue::CSS_PT).get()));
+ EXPECT_EQ(
+ ::std::string("AnimatableRepeatable(AnimatableLength(3rem), AnimatableLength(4pt))"),
+ PrintToString(AnimatableRepeatable::create(v1)));
+
+ EXPECT_EQ(
+ ::std::string("AnimatableSVGLength(1cm)"),
+ PrintToString(AnimatableSVGLength::create(SVGLength(LengthModeOther, "1cm"))));
+
+ EXPECT_EQ(
+ ::std::string("AnimatableSVGPaint(#ff0000)"),
+ PrintToString(AnimatableSVGPaint::create(SVGPaint::SVG_PAINTTYPE_RGBCOLOR, Color(0xFFFF0000), "")));
+
+ EXPECT_EQ(
+ ::std::string("AnimatableSVGPaint(url(abc))"),
+ PrintToString(AnimatableSVGPaint::create(SVGPaint::SVG_PAINTTYPE_URI, Color(0xFFFF0000), "abc")));
+
+ EXPECT_THAT(
+ PrintToString(AnimatableShapeValue::create(ShapeValue::createShapeValue(BasicShapeCircle::create().get()).get())),
+ testing::StartsWith("AnimatableShapeValue@"));
+
+ Vector<SVGLength> v2;
+ v2.append(SVGLength(LengthModeOther, "1cm"));
+ v2.append(SVGLength(LengthModeOther, "2cm"));
+ EXPECT_EQ(
+ ::std::string("AnimatableStrokeDasharrayList(1cm, 2cm)"),
+ PrintToString(AnimatableStrokeDasharrayList::create(v2)));
+
+ TransformOperations operations1;
+ operations1.operations().append(TranslateTransformOperation::create(Length(2, WebCore::Fixed), Length(0, WebCore::Fixed), TransformOperation::TranslateX));
+ EXPECT_EQ(
+ ::std::string("AnimatableTransform([1 0 0 1 2 0])"),
+ PrintToString(AnimatableTransform::create(operations1)));
+
+ TransformOperations operations2;
+ operations2.operations().append(ScaleTransformOperation::create(1, 1, 1, TransformOperation::Scale3D));
+ EXPECT_EQ(
+ ::std::string("AnimatableTransform([1 0 0 1 0 0])"),
+ PrintToString(AnimatableTransform::create(operations2)));
+
+ EXPECT_EQ(
+ ::std::string("AnimatableUnknown(none)"),
+ PrintToString(AnimatableUnknown::create(CSSPrimitiveValue::createIdentifier(CSSValueNone).get())));
+
+ EXPECT_EQ(
+ ::std::string("AnimatableVisibility(VISIBLE)"),
+ PrintToString(AnimatableVisibility::create(VISIBLE)));
+}
+
+} // namespace
diff --git a/chromium/third_party/WebKit/Source/core/animation/AnimatableVisibility.cpp b/chromium/third_party/WebKit/Source/core/animation/AnimatableVisibility.cpp
index 2cfc097ada7..a395efa2b2c 100644
--- a/chromium/third_party/WebKit/Source/core/animation/AnimatableVisibility.cpp
+++ b/chromium/third_party/WebKit/Source/core/animation/AnimatableVisibility.cpp
@@ -46,4 +46,9 @@ PassRefPtr<AnimatableValue> AnimatableVisibility::interpolateTo(const Animatable
return takeConstRef(from == VISIBLE ? this : value);
}
+bool AnimatableVisibility::equalTo(const AnimatableValue* value) const
+{
+ return m_visibility == toAnimatableVisibility(value)->m_visibility;
+}
+
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/animation/AnimatableVisibility.h b/chromium/third_party/WebKit/Source/core/animation/AnimatableVisibility.h
index d24058f57f2..bbd377105d0 100644
--- a/chromium/third_party/WebKit/Source/core/animation/AnimatableVisibility.h
+++ b/chromium/third_party/WebKit/Source/core/animation/AnimatableVisibility.h
@@ -51,18 +51,15 @@ protected:
private:
explicit AnimatableVisibility(EVisibility visibility)
- : AnimatableValue(TypeVisibility)
- , m_visibility(visibility)
+ : m_visibility(visibility)
{
}
+ virtual AnimatableType type() const OVERRIDE { return TypeVisibility; }
+ virtual bool equalTo(const AnimatableValue*) const OVERRIDE;
const EVisibility m_visibility;
};
-inline const AnimatableVisibility* toAnimatableVisibility(const AnimatableValue* value)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(value && value->isVisibility());
- return static_cast<const AnimatableVisibility*>(value);
-}
+DEFINE_ANIMATABLE_VALUE_TYPE_CASTS(AnimatableVisibility, isVisibility());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/animation/Animation.cpp b/chromium/third_party/WebKit/Source/core/animation/Animation.cpp
index 0e801bb0dfe..6e40086d6f2 100644
--- a/chromium/third_party/WebKit/Source/core/animation/Animation.cpp
+++ b/chromium/third_party/WebKit/Source/core/animation/Animation.cpp
@@ -31,63 +31,174 @@
#include "config.h"
#include "core/animation/Animation.h"
-#include "core/animation/DocumentTimeline.h"
+#include "core/animation/ActiveAnimations.h"
+#include "core/animation/CompositorAnimations.h"
+#include "core/animation/KeyframeAnimationEffect.h"
#include "core/animation/Player.h"
#include "core/dom/Element.h"
namespace WebCore {
-PassRefPtr<Animation> Animation::create(PassRefPtr<Element> target, PassRefPtr<AnimationEffect> effect, const Timing& timing, PassOwnPtr<EventDelegate> eventDelegate)
+PassRefPtr<Animation> Animation::create(PassRefPtr<Element> target, PassRefPtr<AnimationEffect> effect, const Timing& timing, Priority priority, PassOwnPtr<EventDelegate> eventDelegate)
{
- return adoptRef(new Animation(target, effect, timing, eventDelegate));
+ return adoptRef(new Animation(target, effect, timing, priority, eventDelegate));
}
-Animation::Animation(PassRefPtr<Element> target, PassRefPtr<AnimationEffect> effect, const Timing& timing, PassOwnPtr<EventDelegate> eventDelegate)
+Animation::Animation(PassRefPtr<Element> target, PassRefPtr<AnimationEffect> effect, const Timing& timing, Priority priority, PassOwnPtr<EventDelegate> eventDelegate)
: TimedItem(timing, eventDelegate)
, m_target(target)
, m_effect(effect)
, m_activeInAnimationStack(false)
+ , m_priority(priority)
{
}
+void Animation::didAttach()
+{
+ if (m_target)
+ m_target->ensureActiveAnimations()->players().add(player());
+}
+
void Animation::willDetach()
{
+ if (m_target)
+ m_target->activeAnimations()->players().remove(player());
if (m_activeInAnimationStack)
clearEffects();
}
-static AnimationStack* ensureAnimationStack(Element* element)
+static AnimationStack& ensureAnimationStack(Element* element)
{
return element->ensureActiveAnimations()->defaultStack();
}
-void Animation::applyEffects(bool previouslyInEffect)
+bool Animation::applyEffects(bool previouslyInEffect)
{
- ASSERT(player());
- if (!previouslyInEffect) {
- ensureAnimationStack(m_target.get())->add(this);
+ ASSERT(isInEffect());
+ if (!m_target || !m_effect)
+ return false;
+
+ if (player() && !previouslyInEffect) {
+ ensureAnimationStack(m_target.get()).add(this);
m_activeInAnimationStack = true;
}
- m_compositableValues = m_effect->sample(currentIteration(), timeFraction());
- m_target->setNeedsStyleRecalc(LocalStyleChange, StyleChangeFromRenderer);
+
+ double iteration = currentIteration();
+ ASSERT(iteration >= 0);
+ // FIXME: Handle iteration values which overflow int.
+ m_compositableValues = m_effect->sample(static_cast<int>(iteration), timeFraction());
+ if (player()) {
+ m_target->setNeedsAnimationStyleRecalc();
+ return true;
+ }
+ return false;
}
void Animation::clearEffects()
{
ASSERT(player());
ASSERT(m_activeInAnimationStack);
- ensureAnimationStack(m_target.get())->remove(this);
+ ensureAnimationStack(m_target.get()).remove(this);
+ cancelAnimationOnCompositor();
m_activeInAnimationStack = false;
m_compositableValues.clear();
+ m_target->setNeedsAnimationStyleRecalc();
+ invalidate();
}
-void Animation::updateChildrenAndEffects(bool wasInEffect) const
+bool Animation::updateChildrenAndEffects() const
{
- ASSERT(m_activeInAnimationStack == wasInEffect);
+ if (!m_effect)
+ return false;
+
if (isInEffect())
- const_cast<Animation*>(this)->applyEffects(wasInEffect);
- else if (wasInEffect)
+ return const_cast<Animation*>(this)->applyEffects(m_activeInAnimationStack);
+
+ if (m_activeInAnimationStack) {
const_cast<Animation*>(this)->clearEffects();
+ return true;
+ }
+ return false;
+}
+
+double Animation::calculateTimeToEffectChange(double localTime, double timeToNextIteration) const
+{
+ const double activeStartTime = startTime() + specified().startDelay;
+ switch (phase()) {
+ case PhaseBefore:
+ return activeStartTime - localTime;
+ case PhaseActive:
+ if (hasActiveAnimationsOnCompositor()) {
+ // Need service to apply fill / fire events.
+ const double activeEndTime = activeStartTime + activeDuration();
+ return std::min(activeEndTime - localTime, timeToNextIteration);
+ }
+ return 0;
+ case PhaseAfter:
+ // If this Animation is still in effect then it will need to update
+ // when its parent goes out of effect. We have no way of knowing when
+ // that will be, however, so the parent will need to supply it.
+ return std::numeric_limits<double>::infinity();
+ case PhaseNone:
+ default:
+ ASSERT_NOT_REACHED();
+ return 0;
+ }
+}
+
+bool Animation::isCandidateForAnimationOnCompositor() const
+{
+ if (!effect() || !m_target)
+ return false;
+ return CompositorAnimations::instance()->isCandidateForAnimationOnCompositor(specified(), *effect());
+}
+
+bool Animation::maybeStartAnimationOnCompositor()
+{
+ ASSERT(!hasActiveAnimationsOnCompositor());
+ if (!isCandidateForAnimationOnCompositor())
+ return false;
+ if (!CompositorAnimations::instance()->canStartAnimationOnCompositor(*m_target.get()))
+ return false;
+ if (!CompositorAnimations::instance()->startAnimationOnCompositor(*m_target.get(), specified(), *effect(), m_compositorAnimationIds))
+ return false;
+ ASSERT(!m_compositorAnimationIds.isEmpty());
+ return true;
+}
+
+bool Animation::hasActiveAnimationsOnCompositor() const
+{
+ return !m_compositorAnimationIds.isEmpty();
+}
+
+bool Animation::hasActiveAnimationsOnCompositor(CSSPropertyID property) const
+{
+ return hasActiveAnimationsOnCompositor() && affects(property);
+}
+
+bool Animation::affects(CSSPropertyID property) const
+{
+ return m_effect && m_effect->affects(property);
+}
+
+void Animation::cancelAnimationOnCompositor()
+{
+ if (!hasActiveAnimationsOnCompositor())
+ return;
+ if (!m_target || !m_target->renderer())
+ return;
+ for (size_t i = 0; i < m_compositorAnimationIds.size(); ++i)
+ CompositorAnimations::instance()->cancelAnimationOnCompositor(*m_target.get(), m_compositorAnimationIds[i]);
+ m_compositorAnimationIds.clear();
+}
+
+void Animation::pauseAnimationForTestingOnCompositor(double pauseTime)
+{
+ ASSERT(hasActiveAnimationsOnCompositor());
+ if (!m_target || !m_target->renderer())
+ return;
+ for (size_t i = 0; i < m_compositorAnimationIds.size(); ++i)
+ CompositorAnimations::instance()->pauseAnimationForTestingOnCompositor(*m_target.get(), m_compositorAnimationIds[i], pauseTime);
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/animation/Animation.h b/chromium/third_party/WebKit/Source/core/animation/Animation.h
index 2635c9e8588..f4ad206d503 100644
--- a/chromium/third_party/WebKit/Source/core/animation/Animation.h
+++ b/chromium/third_party/WebKit/Source/core/animation/Animation.h
@@ -42,30 +42,57 @@ class Element;
class Animation FINAL : public TimedItem {
public:
- static PassRefPtr<Animation> create(PassRefPtr<Element>, PassRefPtr<AnimationEffect>, const Timing&, PassOwnPtr<EventDelegate> = nullptr);
+ enum Priority { DefaultPriority, TransitionPriority };
- const AnimationEffect::CompositableValueMap* compositableValues() const
+ static PassRefPtr<Animation> create(PassRefPtr<Element>, PassRefPtr<AnimationEffect>, const Timing&, Priority = DefaultPriority, PassOwnPtr<EventDelegate> = nullptr);
+ virtual bool isAnimation() const OVERRIDE FINAL { return true; }
+
+ const AnimationEffect::CompositableValueList* compositableValues() const
{
ASSERT(m_compositableValues);
return m_compositableValues.get();
}
+ bool affects(CSSPropertyID) const;
+ const AnimationEffect* effect() const { return m_effect.get(); }
+ Priority priority() const { return m_priority; }
+ Element* target() { return m_target.get(); }
+
+ bool isCandidateForAnimationOnCompositor() const;
+ // Must only be called once and assumes to be part of a player without a start time.
+ bool maybeStartAnimationOnCompositor();
+ bool hasActiveAnimationsOnCompositor() const;
+ bool hasActiveAnimationsOnCompositor(CSSPropertyID) const;
+ void cancelAnimationOnCompositor();
+ void pauseAnimationForTestingOnCompositor(double pauseTime);
+
protected:
- virtual void applyEffects(bool previouslyInEffect);
+ // Returns whether style recalc was triggered.
+ virtual bool applyEffects(bool previouslyInEffect);
virtual void clearEffects();
- virtual void updateChildrenAndEffects(bool) const OVERRIDE FINAL;
+ virtual bool updateChildrenAndEffects() const OVERRIDE FINAL;
+ virtual void didAttach() OVERRIDE FINAL;
virtual void willDetach() OVERRIDE FINAL;
+ virtual double calculateTimeToEffectChange(double inheritedTime, double timeToNextIteration) const OVERRIDE FINAL;
private:
- Animation(PassRefPtr<Element>, PassRefPtr<AnimationEffect>, const Timing&, PassOwnPtr<EventDelegate>);
+ Animation(PassRefPtr<Element>, PassRefPtr<AnimationEffect>, const Timing&, Priority, PassOwnPtr<EventDelegate>);
RefPtr<Element> m_target;
RefPtr<AnimationEffect> m_effect;
bool m_activeInAnimationStack;
- OwnPtr<AnimationEffect::CompositableValueMap> m_compositableValues;
+ OwnPtr<AnimationEffect::CompositableValueList> m_compositableValues;
+
+ Priority m_priority;
+
+ Vector<int> m_compositorAnimationIds;
+
+ friend class CSSAnimations;
};
+DEFINE_TYPE_CASTS(Animation, TimedItem, timedItem, timedItem->isAnimation(), timedItem.isAnimation());
+
} // namespace WebCore
#endif
diff --git a/chromium/third_party/WebKit/Source/core/animation/AnimationClock.h b/chromium/third_party/WebKit/Source/core/animation/AnimationClock.h
new file mode 100644
index 00000000000..f6a2cdb8499
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/animation/AnimationClock.h
@@ -0,0 +1,78 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef AnimationClock_h
+#define AnimationClock_h
+
+#include "wtf/CurrentTime.h"
+#include "wtf/PassOwnPtr.h"
+
+namespace WebCore {
+
+class AnimationClock {
+public:
+ static PassOwnPtr<AnimationClock> create(WTF::TimeFunction monotonicallyIncreasingTime = WTF::monotonicallyIncreasingTime)
+ {
+ return adoptPtr(new AnimationClock(monotonicallyIncreasingTime));
+ }
+
+ void updateTime(double time)
+ {
+ if (time > m_time)
+ m_time = time;
+ m_frozen = true;
+ }
+
+ double currentTime()
+ {
+ if (!m_frozen)
+ updateTime(m_monotonicallyIncreasingTime());
+ return m_time;
+ }
+
+ void unfreeze() { m_frozen = false; }
+
+ void resetTimeForTesting() { m_time = 0; m_frozen = true; }
+
+private:
+ AnimationClock(WTF::TimeFunction monotonicallyIncreasingTime)
+ : m_monotonicallyIncreasingTime(monotonicallyIncreasingTime)
+ , m_time(0)
+ , m_frozen(false)
+ {
+ }
+ WTF::TimeFunction m_monotonicallyIncreasingTime;
+ double m_time;
+ bool m_frozen;
+};
+
+} // namespace WebCore
+
+#endif // AnimationClock_h
diff --git a/chromium/third_party/WebKit/Source/core/animation/AnimationClockTest.cpp b/chromium/third_party/WebKit/Source/core/animation/AnimationClockTest.cpp
new file mode 100644
index 00000000000..248da7badee
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/animation/AnimationClockTest.cpp
@@ -0,0 +1,79 @@
+/*
+ * Copyright (c) 2013, Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/animation/AnimationClock.h"
+
+#include "wtf/OwnPtr.h"
+#include <gtest/gtest.h>
+
+using namespace WebCore;
+
+namespace {
+
+class AnimationAnimationClockTest : public ::testing::Test {
+protected:
+ virtual void SetUp()
+ {
+ animationClock = AnimationClock::create(mockTimeFunction);
+ mockTime = 200;
+ }
+
+ static double mockTimeFunction()
+ {
+ return mockTime++;
+ }
+
+ static double mockTime;
+ OwnPtr<AnimationClock> animationClock;
+};
+
+double AnimationAnimationClockTest::mockTime;
+
+TEST_F(AnimationAnimationClockTest, CurrentTime)
+{
+ EXPECT_EQ(200, animationClock->currentTime());
+ EXPECT_EQ(200, animationClock->currentTime());
+ animationClock->unfreeze();
+ EXPECT_EQ(201, animationClock->currentTime());
+ EXPECT_EQ(201, animationClock->currentTime());
+}
+
+TEST_F(AnimationAnimationClockTest, UpdateTime)
+{
+ animationClock->updateTime(100);
+ EXPECT_EQ(100, animationClock->currentTime());
+ EXPECT_EQ(100, animationClock->currentTime());
+ animationClock->updateTime(150);
+ EXPECT_EQ(150, animationClock->currentTime());
+ EXPECT_EQ(150, animationClock->currentTime());
+}
+
+}
diff --git a/chromium/third_party/WebKit/Source/core/animation/AnimationEffect.h b/chromium/third_party/WebKit/Source/core/animation/AnimationEffect.h
index 89b3494c557..d675a5f4a9e 100644
--- a/chromium/third_party/WebKit/Source/core/animation/AnimationEffect.h
+++ b/chromium/third_party/WebKit/Source/core/animation/AnimationEffect.h
@@ -58,7 +58,11 @@ public:
virtual ~AnimationEffect() { }
typedef HashMap<CSSPropertyID, RefPtr<CompositableValue> > CompositableValueMap;
- virtual PassOwnPtr<CompositableValueMap> sample(int iteration, double fraction) const = 0;
+ typedef Vector<std::pair<CSSPropertyID, RefPtr<CompositableValue> > > CompositableValueList;
+ virtual PassOwnPtr<CompositableValueList> sample(int iteration, double fraction) const = 0;
+
+ virtual bool affects(CSSPropertyID) { return false; };
+ virtual bool isKeyframeAnimationEffect() const { return false; }
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/animation/AnimationStack.cpp b/chromium/third_party/WebKit/Source/core/animation/AnimationStack.cpp
new file mode 100644
index 00000000000..601e7e598e4
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/animation/AnimationStack.cpp
@@ -0,0 +1,92 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/animation/AnimationStack.h"
+
+#include "core/animation/css/CSSAnimations.h"
+
+namespace WebCore {
+
+namespace {
+
+void copyToCompositableValueMap(const AnimationEffect::CompositableValueList* source, AnimationEffect::CompositableValueMap& target)
+{
+ if (!source)
+ return;
+ for (AnimationEffect::CompositableValueList::const_iterator iter = source->begin(); iter != source->end(); ++iter)
+ target.set(iter->first, iter->second);
+}
+
+} // namespace
+
+bool AnimationStack::affects(CSSPropertyID property) const
+{
+ for (size_t i = 0; i < m_activeAnimations.size(); ++i) {
+ if (m_activeAnimations[i]->affects(property))
+ return true;
+ }
+ return false;
+}
+
+bool AnimationStack::hasActiveAnimationsOnCompositor(CSSPropertyID property) const
+{
+ for (size_t i = 0; i < m_activeAnimations.size(); ++i) {
+ if (m_activeAnimations[i]->hasActiveAnimationsOnCompositor(property))
+ return true;
+ }
+ return false;
+}
+
+AnimationEffect::CompositableValueMap AnimationStack::compositableValues(const AnimationStack* animationStack, const Vector<InertAnimation*>* newAnimations, const HashSet<const Player*>* cancelledPlayers, Animation::Priority priority)
+{
+ AnimationEffect::CompositableValueMap result;
+
+ if (animationStack) {
+ const Vector<Animation*>& animations = animationStack->m_activeAnimations;
+ for (size_t i = 0; i < animations.size(); ++i) {
+ Animation* animation = animations[i];
+ if (animation->priority() != priority)
+ continue;
+ if (cancelledPlayers && cancelledPlayers->contains(animation->player()))
+ continue;
+ copyToCompositableValueMap(animation->compositableValues(), result);
+ }
+ }
+
+ if (newAnimations) {
+ for (size_t i = 0; i < newAnimations->size(); ++i)
+ copyToCompositableValueMap(newAnimations->at(i)->sample().get(), result);
+ }
+
+ return result;
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/animation/AnimationStack.h b/chromium/third_party/WebKit/Source/core/animation/AnimationStack.h
index b046cd4c46d..e7ad32f10b5 100644
--- a/chromium/third_party/WebKit/Source/core/animation/AnimationStack.h
+++ b/chromium/third_party/WebKit/Source/core/animation/AnimationStack.h
@@ -31,14 +31,14 @@
#ifndef AnimationStack_h
#define AnimationStack_h
-#include "wtf/HashMap.h"
-#include "wtf/RefPtr.h"
+#include "core/animation/Animation.h"
+#include "core/animation/AnimationEffect.h"
+#include "wtf/HashSet.h"
#include "wtf/Vector.h"
namespace WebCore {
-class Element;
-class Animation;
+class InertAnimation;
class AnimationStack {
@@ -51,8 +51,9 @@ public:
m_activeAnimations.remove(position);
}
bool isEmpty() const { return m_activeAnimations.isEmpty(); }
- // FIXME: This should be PassRefPtr<CompositableValue> composite(Element*, CSSPropertyId)
- const Vector<Animation*>& activeAnimations(const Element* element) const { return m_activeAnimations; }
+ bool affects(CSSPropertyID) const;
+ bool hasActiveAnimationsOnCompositor(CSSPropertyID) const;
+ static AnimationEffect::CompositableValueMap compositableValues(const AnimationStack*, const Vector<InertAnimation*>* newAnimations, const HashSet<const Player*>* cancelledPlayers, Animation::Priority);
private:
Vector<Animation*> m_activeAnimations;
diff --git a/chromium/third_party/WebKit/Source/core/animation/CompositorAnimations.cpp b/chromium/third_party/WebKit/Source/core/animation/CompositorAnimations.cpp
new file mode 100644
index 00000000000..929f0737165
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/animation/CompositorAnimations.cpp
@@ -0,0 +1,536 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/animation/CompositorAnimations.h"
+
+#include "core/animation/AnimatableDouble.h"
+#include "core/animation/AnimatableFilterOperations.h"
+#include "core/animation/AnimatableTransform.h"
+#include "core/animation/AnimatableValue.h"
+#include "core/animation/CompositorAnimationsImpl.h"
+#include "core/platform/animation/AnimationTranslationUtil.h"
+#include "core/rendering/CompositedLayerMapping.h"
+#include "core/rendering/RenderBoxModelObject.h"
+#include "core/rendering/RenderLayer.h"
+#include "core/rendering/RenderObject.h"
+#include "public/platform/Platform.h"
+#include "public/platform/WebAnimation.h"
+#include "public/platform/WebCompositorSupport.h"
+#include "public/platform/WebFilterAnimationCurve.h"
+#include "public/platform/WebFilterKeyframe.h"
+#include "public/platform/WebFloatAnimationCurve.h"
+#include "public/platform/WebFloatKeyframe.h"
+#include "public/platform/WebTransformAnimationCurve.h"
+#include "public/platform/WebTransformKeyframe.h"
+
+#include <algorithm>
+#include <cmath>
+
+namespace WebCore {
+
+namespace {
+
+void getKeyframeValuesForProperty(const KeyframeAnimationEffect* effect, CSSPropertyID id, double scale, bool reverse, KeyframeVector& values)
+{
+ ASSERT(values.isEmpty());
+ const KeyframeVector& group = effect->getPropertySpecificKeyframes(id);
+
+ if (reverse) {
+ for (size_t i = group.size(); i--;) {
+ double offset = (1 - group[i]->offset()) * scale;
+ values.append(group[i]->cloneWithOffset(offset));
+ }
+ } else {
+ for (size_t i = 0; i < group.size(); ++i) {
+ double offset = group[i]->offset() * scale;
+ values.append(group[i]->cloneWithOffset(offset));
+ }
+ }
+}
+
+}
+
+// -----------------------------------------------------------------------
+// TimingFunctionReverser methods
+// -----------------------------------------------------------------------
+
+PassRefPtr<TimingFunction> CompositorAnimationsTimingFunctionReverser::reverse(const LinearTimingFunction* timefunc)
+{
+ return const_cast<LinearTimingFunction*>(timefunc);
+}
+
+PassRefPtr<TimingFunction> CompositorAnimationsTimingFunctionReverser::reverse(const CubicBezierTimingFunction* timefunc)
+{
+ switch (timefunc->subType()) {
+ case CubicBezierTimingFunction::EaseIn:
+ return CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseOut);
+ case CubicBezierTimingFunction::EaseOut:
+ return CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseIn);
+ case CubicBezierTimingFunction::EaseInOut:
+ return const_cast<CubicBezierTimingFunction*>(timefunc);
+ case CubicBezierTimingFunction::Ease: // Ease is not symmetrical
+ case CubicBezierTimingFunction::Custom:
+ return CubicBezierTimingFunction::create(1 - timefunc->x2(), 1 - timefunc->y2(), 1 - timefunc->x1(), 1 - timefunc->y1());
+ default:
+ ASSERT_NOT_REACHED();
+ return PassRefPtr<TimingFunction>();
+ }
+}
+
+PassRefPtr<TimingFunction> CompositorAnimationsTimingFunctionReverser::reverse(const ChainedTimingFunction* timefunc)
+{
+ RefPtr<ChainedTimingFunction> reversed = ChainedTimingFunction::create();
+ for (size_t i = 0; i < timefunc->m_segments.size(); i++) {
+ size_t index = timefunc->m_segments.size() - i - 1;
+
+ RefPtr<TimingFunction> rtf = reverse(timefunc->m_segments[index].m_timingFunction.get());
+ reversed->appendSegment(1 - timefunc->m_segments[index].m_min, rtf.get());
+ }
+ return reversed;
+}
+
+PassRefPtr<TimingFunction> CompositorAnimationsTimingFunctionReverser::reverse(const TimingFunction* timefunc)
+{
+ switch (timefunc->type()) {
+ case TimingFunction::LinearFunction: {
+ const LinearTimingFunction* linear = toLinearTimingFunction(timefunc);
+ return reverse(linear);
+ }
+ case TimingFunction::CubicBezierFunction: {
+ const CubicBezierTimingFunction* cubic = toCubicBezierTimingFunction(timefunc);
+ return reverse(cubic);
+ }
+ case TimingFunction::ChainedFunction: {
+ const ChainedTimingFunction* chained = toChainedTimingFunction(timefunc);
+ return reverse(chained);
+ }
+
+ // Steps function can not be reversed.
+ case TimingFunction::StepsFunction:
+ default:
+ ASSERT_NOT_REACHED();
+ return PassRefPtr<TimingFunction>();
+ }
+}
+
+// -----------------------------------------------------------------------
+// CompositorAnimations public API
+// -----------------------------------------------------------------------
+
+bool CompositorAnimations::isCandidateForAnimationOnCompositor(const Timing& timing, const AnimationEffect& effect)
+{
+ const KeyframeAnimationEffect& keyframeEffect = *toKeyframeAnimationEffect(&effect);
+
+ // Are the keyframes convertible?
+ const KeyframeAnimationEffect::KeyframeVector frames = keyframeEffect.getFrames();
+ for (size_t i = 0; i < frames.size(); ++i) {
+ // Only replace mode can be accelerated
+ if (frames[i]->composite() != AnimationEffect::CompositeReplace)
+ return false;
+
+ // Check all the properties can be accelerated
+ const PropertySet properties = frames[i]->properties(); // FIXME: properties creates a whole new PropertySet!
+
+ if (properties.isEmpty())
+ return false;
+
+ for (PropertySet::const_iterator it = properties.begin(); it != properties.end(); ++it) {
+ switch (*it) {
+ case CSSPropertyOpacity:
+ continue;
+ case CSSPropertyWebkitTransform:
+ if (toAnimatableTransform(frames[i]->propertyValue(CSSPropertyWebkitTransform))->transformOperations().dependsOnBoxSize())
+ return false;
+ continue;
+ case CSSPropertyWebkitFilter: {
+ const FilterOperations& operations = toAnimatableFilterOperations(frames[i]->propertyValue(CSSPropertyWebkitFilter))->operations();
+ if (operations.hasFilterThatMovesPixels())
+ return false;
+ for (size_t i = 0; i < operations.size(); i++) {
+ const FilterOperation& op = *operations.at(i);
+ if (op.type() == FilterOperation::VALIDATED_CUSTOM || op.type() == FilterOperation::CUSTOM)
+ return false;
+ }
+ continue;
+ }
+ default:
+ return false;
+ }
+ }
+ }
+
+ // Is the timing object convertible?
+ CompositorAnimationsImpl::CompositorTiming out;
+ if (!CompositorAnimationsImpl::convertTimingForCompositor(timing, out))
+ return false;
+
+ // Is the timing function convertible?
+ switch (timing.timingFunction->type()) {
+ case TimingFunction::LinearFunction:
+ break;
+
+ case TimingFunction::CubicBezierFunction:
+ // Can have a cubic if we don't have to split it (IE only have two frames).
+ if (frames.size() != 2)
+ return false;
+
+ ASSERT(frames[0]->offset() == 0.0 && frames[1]->offset() == 1.0);
+ break;
+
+ case TimingFunction::StepsFunction:
+ return false;
+
+ case TimingFunction::ChainedFunction: {
+ // Currently we only support chained segments in the form the CSS code
+ // generates. These chained segments are only one level deep and have
+ // one timing function per frame.
+ const ChainedTimingFunction* chained = static_cast<const ChainedTimingFunction*>(timing.timingFunction.get());
+ if (!chained->m_segments.size())
+ return false;
+
+ if (frames.size() != chained->m_segments.size() + 1)
+ return false;
+
+ for (size_t timeIndex = 0; timeIndex < chained->m_segments.size(); timeIndex++) {
+ const ChainedTimingFunction::Segment& segment = chained->m_segments[timeIndex];
+
+ if (frames[timeIndex]->offset() != segment.m_min || frames[timeIndex + 1]->offset() != segment.m_max)
+ return false;
+
+ switch (segment.m_timingFunction->type()) {
+ case TimingFunction::LinearFunction:
+ case TimingFunction::CubicBezierFunction:
+ continue;
+
+ case TimingFunction::StepsFunction:
+ case TimingFunction::ChainedFunction:
+ default:
+ return false;
+ }
+ }
+
+ break;
+ }
+ default:
+ ASSERT_NOT_REACHED();
+ return false;
+ }
+
+ return true;
+}
+
+bool CompositorAnimations::canStartAnimationOnCompositor(const Element& element)
+{
+ return element.renderer() && element.renderer()->compositingState() == PaintsIntoOwnBacking;
+}
+
+bool CompositorAnimations::startAnimationOnCompositor(const Element& element, const Timing& timing, const AnimationEffect& effect, Vector<int>& startedAnimationIds)
+{
+ ASSERT(startedAnimationIds.isEmpty());
+ ASSERT(isCandidateForAnimationOnCompositor(timing, effect));
+ ASSERT(canStartAnimationOnCompositor(element));
+
+ const KeyframeAnimationEffect& keyframeEffect = *toKeyframeAnimationEffect(&effect);
+
+ RenderLayer* layer = toRenderBoxModelObject(element.renderer())->layer();
+ ASSERT(layer);
+
+ Vector<OwnPtr<blink::WebAnimation> > animations;
+ CompositorAnimationsImpl::getAnimationOnCompositor(timing, keyframeEffect, animations);
+ ASSERT(!animations.isEmpty());
+ for (size_t i = 0; i < animations.size(); ++i) {
+ int id = animations[i]->id();
+ if (!layer->compositedLayerMapping()->mainGraphicsLayer()->addAnimation(animations[i].release())) {
+ // FIXME: We should know ahead of time whether these animations can be started.
+ for (size_t j = 0; j < startedAnimationIds.size(); ++j)
+ cancelAnimationOnCompositor(element, startedAnimationIds[j]);
+ startedAnimationIds.clear();
+ return false;
+ }
+ startedAnimationIds.append(id);
+ }
+ ASSERT(!startedAnimationIds.isEmpty());
+ return true;
+}
+
+void CompositorAnimations::cancelAnimationOnCompositor(const Element& element, int id)
+{
+ if (!canStartAnimationOnCompositor(element)) {
+ ASSERT_NOT_REACHED();
+ return;
+ }
+ toRenderBoxModelObject(element.renderer())->layer()->compositedLayerMapping()->mainGraphicsLayer()->removeAnimation(id);
+}
+
+void CompositorAnimations::pauseAnimationForTestingOnCompositor(const Element& element, int id, double pauseTime)
+{
+ if (!canStartAnimationOnCompositor(element)) {
+ ASSERT_NOT_REACHED();
+ return;
+ }
+ toRenderBoxModelObject(element.renderer())->layer()->compositedLayerMapping()->mainGraphicsLayer()->pauseAnimation(id, pauseTime);
+}
+
+// -----------------------------------------------------------------------
+// CompositorAnimationsImpl
+// -----------------------------------------------------------------------
+
+bool CompositorAnimationsImpl::convertTimingForCompositor(const Timing& timing, CompositorTiming& out)
+{
+ timing.assertValid();
+
+ // All fill modes are supported (the calling code handles them).
+
+ // FIXME: Support non-zero iteration start.
+ if (timing.iterationStart)
+ return false;
+
+ // FIXME: Compositor only supports positive, integer iteration counts.
+ // Zero iterations could be converted, but silly.
+ if ((std::floor(timing.iterationCount) != timing.iterationCount) || timing.iterationCount <= 0)
+ return false;
+
+ if (!timing.iterationDuration)
+ return false;
+
+ // FIXME: Support other playback rates
+ if (timing.playbackRate != 1)
+ return false;
+
+ // All directions are supported.
+
+ // Now attempt an actual conversion
+ out.scaledDuration = timing.iterationDuration;
+ ASSERT(out.scaledDuration > 0);
+
+ double scaledStartDelay = timing.startDelay;
+ if (scaledStartDelay > 0 && scaledStartDelay > out.scaledDuration * timing.iterationCount)
+ return false;
+
+ out.reverse = (timing.direction == Timing::PlaybackDirectionReverse
+ || timing.direction == Timing::PlaybackDirectionAlternateReverse);
+ out.alternate = (timing.direction == Timing::PlaybackDirectionAlternate
+ || timing.direction == Timing::PlaybackDirectionAlternateReverse);
+
+ if (!std::isfinite(timing.iterationCount)) {
+ out.adjustedIterationCount = -1;
+ } else {
+ out.adjustedIterationCount = std::floor(timing.iterationCount);
+ ASSERT(out.adjustedIterationCount > 0);
+ }
+
+ // Compositor's time offset is positive for seeking into the animation.
+ out.scaledTimeOffset = -scaledStartDelay;
+ return true;
+}
+
+namespace {
+
+template<typename PlatformAnimationCurveType, typename PlatformAnimationKeyframeType>
+void addKeyframeWithTimingFunction(PlatformAnimationCurveType& curve, const PlatformAnimationKeyframeType& keyframe, const TimingFunction* timingFunction)
+{
+ if (!timingFunction) {
+ curve.add(keyframe);
+ return;
+ }
+
+ switch (timingFunction->type()) {
+ case TimingFunction::LinearFunction:
+ curve.add(keyframe, blink::WebAnimationCurve::TimingFunctionTypeLinear);
+ return;
+
+ case TimingFunction::CubicBezierFunction: {
+ const CubicBezierTimingFunction* cubic = toCubicBezierTimingFunction(timingFunction);
+
+ if (cubic->subType() == CubicBezierTimingFunction::Custom) {
+ curve.add(keyframe, cubic->x1(), cubic->y1(), cubic->x2(), cubic->y2());
+ } else {
+
+ blink::WebAnimationCurve::TimingFunctionType easeType;
+ switch (cubic->subType()) {
+ case CubicBezierTimingFunction::Ease:
+ easeType = blink::WebAnimationCurve::TimingFunctionTypeEase;
+ break;
+ case CubicBezierTimingFunction::EaseIn:
+ easeType = blink::WebAnimationCurve::TimingFunctionTypeEaseIn;
+ break;
+ case CubicBezierTimingFunction::EaseOut:
+ easeType = blink::WebAnimationCurve::TimingFunctionTypeEaseOut;
+ break;
+ case CubicBezierTimingFunction::EaseInOut:
+ easeType = blink::WebAnimationCurve::TimingFunctionTypeEaseInOut;
+ break;
+
+ // Custom Bezier are handled seperately.
+ case CubicBezierTimingFunction::Custom:
+ default:
+ ASSERT_NOT_REACHED();
+ return;
+ }
+
+ curve.add(keyframe, easeType);
+ }
+ return;
+ }
+
+ case TimingFunction::StepsFunction:
+ case TimingFunction::ChainedFunction:
+ default:
+ ASSERT_NOT_REACHED();
+ return;
+ }
+}
+
+} // namespace anoymous
+
+void CompositorAnimationsImpl::addKeyframesToCurve(blink::WebAnimationCurve& curve, const KeyframeVector& keyframes, const TimingFunction& timingFunction)
+{
+ for (size_t i = 0; i < keyframes.size(); i++) {
+ const TimingFunction* keyframeTimingFunction = 0;
+ if (i + 1 < keyframes.size()) { // Last keyframe has no timing function
+ switch (timingFunction.type()) {
+ case TimingFunction::LinearFunction:
+ case TimingFunction::CubicBezierFunction:
+ keyframeTimingFunction = &timingFunction;
+ break;
+
+ case TimingFunction::ChainedFunction: {
+ const ChainedTimingFunction& chained = toChainedTimingFunction(timingFunction);
+ // ChainedTimingFunction criteria was checked in isCandidate,
+ // assert it is valid.
+ ASSERT(keyframes.size() == chained.m_segments.size() + 1);
+
+ keyframeTimingFunction = chained.m_segments[i].m_timingFunction.get();
+ break;
+ }
+ case TimingFunction::StepsFunction:
+ default:
+ ASSERT_NOT_REACHED();
+ }
+ }
+
+ ASSERT(!keyframes[i]->value()->dependsOnUnderlyingValue());
+ RefPtr<AnimatableValue> value = keyframes[i]->value()->compositeOnto(0);
+
+ switch (curve.type()) {
+ case blink::WebAnimationCurve::AnimationCurveTypeFilter: {
+ OwnPtr<blink::WebFilterOperations> ops = adoptPtr(blink::Platform::current()->compositorSupport()->createFilterOperations());
+ bool converted = toWebFilterOperations(toAnimatableFilterOperations(value.get())->operations(), ops.get());
+ ASSERT_UNUSED(converted, converted);
+
+ blink::WebFilterKeyframe filterKeyframe(keyframes[i]->offset(), ops.release());
+ blink::WebFilterAnimationCurve* filterCurve = static_cast<blink::WebFilterAnimationCurve*>(&curve);
+ addKeyframeWithTimingFunction(*filterCurve, filterKeyframe, keyframeTimingFunction);
+ break;
+ }
+ case blink::WebAnimationCurve::AnimationCurveTypeFloat: {
+ blink::WebFloatKeyframe floatKeyframe(keyframes[i]->offset(), toAnimatableDouble(value.get())->toDouble());
+ blink::WebFloatAnimationCurve* floatCurve = static_cast<blink::WebFloatAnimationCurve*>(&curve);
+ addKeyframeWithTimingFunction(*floatCurve, floatKeyframe, keyframeTimingFunction);
+ break;
+ }
+ case blink::WebAnimationCurve::AnimationCurveTypeTransform: {
+ OwnPtr<blink::WebTransformOperations> ops = adoptPtr(blink::Platform::current()->compositorSupport()->createTransformOperations());
+ toWebTransformOperations(toAnimatableTransform(value.get())->transformOperations(), FloatSize(), ops.get());
+
+ blink::WebTransformKeyframe transformKeyframe(keyframes[i]->offset(), ops.release());
+ blink::WebTransformAnimationCurve* transformCurve = static_cast<blink::WebTransformAnimationCurve*>(&curve);
+ addKeyframeWithTimingFunction(*transformCurve, transformKeyframe, keyframeTimingFunction);
+ break;
+ }
+ default:
+ ASSERT_NOT_REACHED();
+ }
+ }
+}
+
+void CompositorAnimationsImpl::getAnimationOnCompositor(
+ const Timing& timing, const KeyframeAnimationEffect& effect, Vector<OwnPtr<blink::WebAnimation> >& animations)
+{
+ ASSERT(animations.isEmpty());
+ CompositorTiming compositorTiming;
+ bool timingValid = convertTimingForCompositor(timing, compositorTiming);
+ ASSERT_UNUSED(timingValid, timingValid);
+
+ RefPtr<TimingFunction> timingFunction = timing.timingFunction;
+ if (compositorTiming.reverse)
+ timingFunction = CompositorAnimationsTimingFunctionReverser::reverse(timingFunction.get());
+
+ PropertySet properties = effect.properties();
+ ASSERT(!properties.isEmpty());
+ for (PropertySet::iterator it = properties.begin(); it != properties.end(); ++it) {
+
+ KeyframeVector values;
+ getKeyframeValuesForProperty(&effect, *it, compositorTiming.scaledDuration, compositorTiming.reverse, values);
+
+ blink::WebAnimation::TargetProperty targetProperty;
+ OwnPtr<blink::WebAnimationCurve> curve;
+ switch (*it) {
+ case CSSPropertyOpacity: {
+ targetProperty = blink::WebAnimation::TargetPropertyOpacity;
+
+ blink::WebFloatAnimationCurve* floatCurve = blink::Platform::current()->compositorSupport()->createFloatAnimationCurve();
+ addKeyframesToCurve(*floatCurve, values, *timingFunction.get());
+ curve = adoptPtr(floatCurve);
+ break;
+ }
+ case CSSPropertyWebkitFilter: {
+ targetProperty = blink::WebAnimation::TargetPropertyFilter;
+ blink::WebFilterAnimationCurve* filterCurve = blink::Platform::current()->compositorSupport()->createFilterAnimationCurve();
+ addKeyframesToCurve(*filterCurve, values, *timingFunction);
+ curve = adoptPtr(filterCurve);
+ break;
+ }
+ case CSSPropertyWebkitTransform: {
+ targetProperty = blink::WebAnimation::TargetPropertyTransform;
+ blink::WebTransformAnimationCurve* transformCurve = blink::Platform::current()->compositorSupport()->createTransformAnimationCurve();
+ addKeyframesToCurve(*transformCurve, values, *timingFunction.get());
+ curve = adoptPtr(transformCurve);
+ break;
+ }
+ default:
+ ASSERT_NOT_REACHED();
+ continue;
+ }
+ ASSERT(curve.get());
+
+ OwnPtr<blink::WebAnimation> animation = adoptPtr(blink::Platform::current()->compositorSupport()->createAnimation(*curve, targetProperty));
+
+ animation->setIterations(compositorTiming.adjustedIterationCount);
+ animation->setTimeOffset(compositorTiming.scaledTimeOffset);
+ animation->setAlternatesDirection(compositorTiming.alternate);
+
+ animations.append(animation.release());
+ }
+ ASSERT(!animations.isEmpty());
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/animation/CompositorAnimations.h b/chromium/third_party/WebKit/Source/core/animation/CompositorAnimations.h
new file mode 100644
index 00000000000..9a529731fa0
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/animation/CompositorAnimations.h
@@ -0,0 +1,84 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef CompositorAnimations_h
+#define CompositorAnimations_h
+
+#include "core/animation/AnimationEffect.h"
+#include "core/animation/Timing.h"
+#include "core/platform/animation/TimingFunction.h"
+#include "wtf/Vector.h"
+
+namespace WebCore {
+
+class Element;
+
+// Given an input timing function between keyframe at 0 and keyframe at 1.0, we
+// need a timing function such that the behavior with the keyframes swapped is
+// equivalent to reversing time with the input timing function and keyframes.
+// This means flipping the timing function about x=0.5 and about y=0.5.
+// FIXME: Remove once the Compositor natively understands reversing time.
+class CompositorAnimationsTimingFunctionReverser {
+public:
+ static PassRefPtr<TimingFunction> reverse(const LinearTimingFunction* timefunc);
+ static PassRefPtr<TimingFunction> reverse(const CubicBezierTimingFunction* timefunc);
+ static PassRefPtr<TimingFunction> reverse(const ChainedTimingFunction* timefunc);
+ static PassRefPtr<TimingFunction> reverse(const TimingFunction* timefunc);
+};
+
+class CompositorAnimations {
+public:
+ static CompositorAnimations* instance() { return instance(0); }
+ static void setInstanceForTesting(CompositorAnimations* newInstance) { instance(newInstance); }
+
+ virtual bool isCandidateForAnimationOnCompositor(const Timing&, const AnimationEffect&);
+ virtual bool canStartAnimationOnCompositor(const Element&);
+ // FIXME: This should return void. We should know ahead of time whether these animations can be started.
+ virtual bool startAnimationOnCompositor(const Element&, const Timing&, const AnimationEffect&, Vector<int>& startedAnimationIds);
+ virtual void cancelAnimationOnCompositor(const Element&, int id);
+ virtual void pauseAnimationForTestingOnCompositor(const Element&, int id, double pauseTime);
+
+protected:
+ CompositorAnimations() { }
+
+private:
+ static CompositorAnimations* instance(CompositorAnimations* newInstance)
+ {
+ static CompositorAnimations* instance = new CompositorAnimations();
+ if (newInstance) {
+ instance = newInstance;
+ }
+ return instance;
+ }
+};
+
+} // namespace WebCore
+
+#endif
diff --git a/chromium/third_party/WebKit/Source/core/animation/CompositorAnimationsImpl.h b/chromium/third_party/WebKit/Source/core/animation/CompositorAnimationsImpl.h
new file mode 100644
index 00000000000..7c32705f23b
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/animation/CompositorAnimationsImpl.h
@@ -0,0 +1,61 @@
+/*
+ * Copyright (c) 2013, Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "core/animation/AnimationEffect.h"
+#include "core/animation/KeyframeAnimationEffect.h"
+#include "core/animation/Timing.h"
+#include "core/platform/animation/TimingFunction.h"
+#include "public/platform/WebAnimation.h"
+
+namespace WebCore {
+
+typedef KeyframeAnimationEffect::PropertySpecificKeyframeVector KeyframeVector;
+
+class CompositorAnimationsImpl {
+private:
+ struct CompositorTiming {
+ bool reverse;
+ bool alternate;
+ double scaledDuration;
+ double scaledTimeOffset;
+ int adjustedIterationCount;
+ };
+
+ static bool convertTimingForCompositor(const Timing&, CompositorTiming& out);
+
+ static void getAnimationOnCompositor(const Timing&, const KeyframeAnimationEffect&, Vector<OwnPtr<blink::WebAnimation> >& animations);
+
+ static void addKeyframesToCurve(blink::WebAnimationCurve&, const KeyframeVector&, const TimingFunction&);
+
+ friend class CompositorAnimations;
+ friend class AnimationCompositorAnimationsTest;
+};
+
+} // WebCore
diff --git a/chromium/third_party/WebKit/Source/core/animation/CompositorAnimationsTest.cpp b/chromium/third_party/WebKit/Source/core/animation/CompositorAnimationsTest.cpp
new file mode 100644
index 00000000000..db0d9a6c4bd
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/animation/CompositorAnimationsTest.cpp
@@ -0,0 +1,1088 @@
+/*
+ * Copyright (c) 2013, Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+
+#include "core/animation/CompositorAnimations.h"
+
+#include "core/animation/AnimatableDouble.h"
+#include "core/animation/AnimatableFilterOperations.h"
+#include "core/animation/AnimatableTransform.h"
+#include "core/animation/AnimatableValueTestHelper.h"
+#include "core/animation/CompositorAnimationsImpl.h"
+#include "core/animation/CompositorAnimationsTestHelper.h"
+#include "core/platform/animation/TimingFunctionTestHelper.h"
+#include "platform/geometry/IntSize.h"
+#include "platform/graphics/filters/FilterOperations.h"
+#include "platform/transforms/TransformOperations.h"
+#include "platform/transforms/TranslateTransformOperation.h"
+#include "public/platform/WebAnimation.h"
+#include "wtf/HashFunctions.h"
+#include "wtf/OwnPtr.h"
+#include "wtf/PassOwnPtr.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefPtr.h"
+
+#include <gmock/gmock.h>
+#include <gtest/gtest.h>
+
+namespace WebCore {
+
+using ::testing::CloneToPassOwnPtr;
+using ::testing::ExpectationSet;
+using ::testing::Ref;
+using ::testing::Return;
+using ::testing::_;
+
+class AnimationCompositorAnimationsTest : public AnimationCompositorAnimationsTestBase {
+
+protected:
+ RefPtr<TimingFunction> m_linearTimingFunction;
+ RefPtr<TimingFunction> m_cubicEaseTimingFunction;
+ RefPtr<TimingFunction> m_cubicCustomTimingFunction;
+ RefPtr<TimingFunction> m_stepTimingFunction;
+
+ Timing m_timing;
+ CompositorAnimationsImpl::CompositorTiming m_compositorTiming;
+ KeyframeAnimationEffect::KeyframeVector m_keyframeVector2;
+ RefPtr<KeyframeAnimationEffect> m_keyframeAnimationEffect2;
+ KeyframeAnimationEffect::KeyframeVector m_keyframeVector5;
+ RefPtr<KeyframeAnimationEffect> m_keyframeAnimationEffect5;
+
+ virtual void SetUp()
+ {
+ AnimationCompositorAnimationsTestBase::SetUp();
+
+ m_linearTimingFunction = LinearTimingFunction::create();
+ m_cubicEaseTimingFunction = CubicBezierTimingFunction::preset(CubicBezierTimingFunction::Ease);
+ m_cubicCustomTimingFunction = CubicBezierTimingFunction::create(1, 2, 3, 4);
+ m_stepTimingFunction = StepsTimingFunction::create(1, false);
+
+ m_timing = createCompositableTiming();
+ m_compositorTiming = CompositorAnimationsImpl::CompositorTiming();
+ // Make sure the CompositableTiming is really compositable, otherwise
+ // most other tests will fail.
+ ASSERT(convertTimingForCompositor(m_timing, m_compositorTiming));
+
+ m_keyframeVector2 = createCompositableFloatKeyframeVector(2);
+ m_keyframeAnimationEffect2 = KeyframeAnimationEffect::create(m_keyframeVector2);
+
+ m_keyframeVector5 = createCompositableFloatKeyframeVector(5);
+ m_keyframeAnimationEffect5 = KeyframeAnimationEffect::create(m_keyframeVector5);
+ }
+
+public:
+
+ bool convertTimingForCompositor(const Timing& t, CompositorAnimationsImpl::CompositorTiming& out)
+ {
+ return CompositorAnimationsImpl::convertTimingForCompositor(t, out);
+ }
+ bool isCandidateForAnimationOnCompositor(const Timing& timing, const AnimationEffect& effect)
+ {
+ return CompositorAnimations::instance()->isCandidateForAnimationOnCompositor(timing, effect);
+ }
+ void getAnimationOnCompositor(Timing& timing, KeyframeAnimationEffect& effect, Vector<OwnPtr<blink::WebAnimation> >& animations)
+ {
+ return CompositorAnimationsImpl::getAnimationOnCompositor(timing, effect, animations);
+ }
+
+ bool isCandidateHelperForSingleKeyframe(Keyframe* frame)
+ {
+ EXPECT_EQ(frame->offset(), 0);
+ KeyframeAnimationEffect::KeyframeVector frames;
+ frames.append(frame);
+ EXPECT_EQ(m_keyframeVector2[1]->offset(), 1.0);
+ frames.append(m_keyframeVector2[1]);
+ return isCandidateForAnimationOnCompositor(m_timing, *KeyframeAnimationEffect::create(frames).get());
+ }
+
+ // -------------------------------------------------------------------
+
+ Timing createCompositableTiming()
+ {
+ Timing timing;
+ timing.startDelay = 0;
+ timing.fillMode = Timing::FillModeNone;
+ timing.iterationStart = 0;
+ timing.iterationCount = 1;
+ timing.hasIterationDuration = true;
+ timing.iterationDuration = 1.0;
+ timing.playbackRate = 1.0;
+ timing.direction = Timing::PlaybackDirectionNormal;
+ ASSERT(m_linearTimingFunction);
+ timing.timingFunction = m_linearTimingFunction;
+ return timing;
+ }
+
+ PassRefPtr<Keyframe> createReplaceOpKeyframe(CSSPropertyID id, AnimatableValue* value, double offset = 0)
+ {
+ RefPtr<Keyframe> keyframe = Keyframe::create();
+ keyframe->setPropertyValue(id, value);
+ keyframe->setComposite(AnimationEffect::CompositeReplace);
+ keyframe->setOffset(offset);
+ return keyframe;
+ }
+
+ PassRefPtr<Keyframe> createDefaultKeyframe(CSSPropertyID id, AnimationEffect::CompositeOperation op, double offset = 0)
+ {
+ RefPtr<AnimatableValue> value;
+ if (id == CSSPropertyWebkitTransform)
+ value = AnimatableTransform::create(TransformOperations());
+ else
+ value = AnimatableDouble::create(10.0);
+
+ RefPtr<Keyframe> keyframe = createReplaceOpKeyframe(id, value.get(), offset);
+ keyframe->setComposite(op);
+ return keyframe;
+ }
+
+ KeyframeAnimationEffect::KeyframeVector createCompositableFloatKeyframeVector(size_t n)
+ {
+ Vector<double> values;
+ for (size_t i = 0; i < n; i++) {
+ values.append(static_cast<double>(i));
+ }
+ return createCompositableFloatKeyframeVector(values);
+ }
+
+ KeyframeAnimationEffect::KeyframeVector createCompositableFloatKeyframeVector(Vector<double>& values)
+ {
+ KeyframeAnimationEffect::KeyframeVector frames;
+ for (size_t i = 0; i < values.size(); i++) {
+ double offset = 1.0 / (values.size() - 1) * i;
+ RefPtr<AnimatableDouble> value = AnimatableDouble::create(values[i]);
+ frames.append(createReplaceOpKeyframe(CSSPropertyOpacity, value.get(), offset).get());
+ }
+ return frames;
+ }
+
+ PassRefPtr<KeyframeAnimationEffect> createKeyframeAnimationEffect(PassRefPtr<Keyframe> prpFrom, PassRefPtr<Keyframe> prpTo, PassRefPtr<Keyframe> prpC = 0, PassRefPtr<Keyframe> prpD = 0)
+ {
+ RefPtr<Keyframe> from = prpFrom;
+ RefPtr<Keyframe> to = prpTo;
+ RefPtr<Keyframe> c = prpC;
+ RefPtr<Keyframe> d = prpD;
+
+ EXPECT_EQ(from->offset(), 0);
+ KeyframeAnimationEffect::KeyframeVector frames;
+ frames.append(from);
+ EXPECT_LE(from->offset(), to->offset());
+ frames.append(to);
+ if (c) {
+ EXPECT_LE(to->offset(), c->offset());
+ frames.append(c);
+ }
+ if (d) {
+ frames.append(d);
+ EXPECT_LE(c->offset(), d->offset());
+ EXPECT_EQ(d->offset(), 1.0);
+ } else {
+ EXPECT_EQ(to->offset(), 1.0);
+ }
+ if (!HasFatalFailure()) {
+ return KeyframeAnimationEffect::create(frames);
+ }
+ return PassRefPtr<KeyframeAnimationEffect>();
+ }
+
+};
+
+class CustomFilterOperationMock : public FilterOperation {
+public:
+ virtual bool operator==(const FilterOperation&) const OVERRIDE FINAL {
+ ASSERT_NOT_REACHED();
+ return false;
+ }
+
+ MOCK_CONST_METHOD2(blend, PassRefPtr<FilterOperation>(const FilterOperation*, double));
+
+ static PassRefPtr<CustomFilterOperationMock> create()
+ {
+ return adoptRef(new CustomFilterOperationMock());
+ }
+
+ CustomFilterOperationMock()
+ : FilterOperation(FilterOperation::CUSTOM)
+ {
+ }
+};
+
+// -----------------------------------------------------------------------
+// -----------------------------------------------------------------------
+
+TEST_F(AnimationCompositorAnimationsTest, isCandidateForAnimationOnCompositorKeyframeMultipleCSSProperties)
+{
+ RefPtr<Keyframe> keyframeGoodMultiple = createDefaultKeyframe(CSSPropertyOpacity, AnimationEffect::CompositeReplace);
+ keyframeGoodMultiple->setPropertyValue(CSSPropertyWebkitTransform, AnimatableTransform::create(TransformOperations()).get());
+ EXPECT_TRUE(isCandidateHelperForSingleKeyframe(keyframeGoodMultiple.get()));
+
+ RefPtr<Keyframe> keyframeBadMultipleOp = createDefaultKeyframe(CSSPropertyOpacity, AnimationEffect::CompositeAdd);
+ keyframeBadMultipleOp->setPropertyValue(CSSPropertyWebkitTransform, AnimatableDouble::create(10.0).get());
+ EXPECT_FALSE(isCandidateHelperForSingleKeyframe(keyframeBadMultipleOp.get()));
+
+ // Check both an unsupported property which hashes before and after the
+ // supported property.
+ typedef DefaultHash<CSSPropertyID>::Hash HashFunctions;
+
+ RefPtr<Keyframe> keyframeBadMultiple1ID = createDefaultKeyframe(CSSPropertyColor, AnimationEffect::CompositeReplace);
+ keyframeBadMultiple1ID->setPropertyValue(CSSPropertyOpacity, AnimatableDouble::create(10.0).get());
+ EXPECT_FALSE(isCandidateHelperForSingleKeyframe(keyframeBadMultiple1ID.get()));
+ EXPECT_LT(HashFunctions::hash(CSSPropertyColor), HashFunctions::hash(CSSPropertyOpacity));
+
+ RefPtr<Keyframe> keyframeBadMultiple2ID = createDefaultKeyframe(CSSPropertyWebkitTransform, AnimationEffect::CompositeReplace);
+ keyframeBadMultiple2ID->setPropertyValue(CSSPropertyWidth, AnimatableDouble::create(10.0).get());
+ EXPECT_FALSE(isCandidateHelperForSingleKeyframe(keyframeBadMultiple2ID.get()));
+ EXPECT_GT(HashFunctions::hash(CSSPropertyWebkitTransform), HashFunctions::hash(CSSPropertyWidth));
+}
+
+TEST_F(AnimationCompositorAnimationsTest, isNotCandidateForCompositorAnimationTransformDependsOnBoxSize)
+{
+ TransformOperations ops;
+ ops.operations().append(TranslateTransformOperation::create(Length(2, WebCore::Fixed), Length(2, WebCore::Fixed), TransformOperation::TranslateX));
+ RefPtr<Keyframe> goodKeyframe = createReplaceOpKeyframe(CSSPropertyWebkitTransform, AnimatableTransform::create(ops).get());
+ EXPECT_TRUE(isCandidateHelperForSingleKeyframe(goodKeyframe.get()));
+
+ ops.operations().append(TranslateTransformOperation::create(Length(50, WebCore::Percent), Length(2, WebCore::Fixed), TransformOperation::TranslateX));
+ RefPtr<Keyframe> badKeyframe = createReplaceOpKeyframe(CSSPropertyWebkitTransform, AnimatableTransform::create(ops).get());
+ EXPECT_FALSE(isCandidateHelperForSingleKeyframe(badKeyframe.get()));
+
+ TransformOperations ops2;
+ Length calcLength = Length(100, WebCore::Percent).blend(Length(100, WebCore::Fixed), 0.5, WebCore::ValueRangeAll);
+ ops2.operations().append(TranslateTransformOperation::create(calcLength, Length(0, WebCore::Fixed), TransformOperation::TranslateX));
+ RefPtr<Keyframe> badKeyframe2 = createReplaceOpKeyframe(CSSPropertyWebkitTransform, AnimatableTransform::create(ops2).get());
+ EXPECT_FALSE(isCandidateHelperForSingleKeyframe(badKeyframe2.get()));
+}
+
+TEST_F(AnimationCompositorAnimationsTest, isNotCandidateForCompositorAnimationCustomFilter)
+{
+ FilterOperations ops;
+ ops.operations().append(BasicColorMatrixFilterOperation::create(0.5, FilterOperation::SATURATE));
+ RefPtr<Keyframe> goodKeyframe = createReplaceOpKeyframe(CSSPropertyWebkitFilter, AnimatableFilterOperations::create(ops).get());
+ EXPECT_TRUE(isCandidateHelperForSingleKeyframe(goodKeyframe.get()));
+
+ ops.operations().append(CustomFilterOperationMock::create());
+ RefPtr<Keyframe> badKeyframe = createReplaceOpKeyframe(CSSPropertyFilter, AnimatableFilterOperations::create(ops).get());
+ EXPECT_FALSE(isCandidateHelperForSingleKeyframe(badKeyframe.get()));
+}
+
+TEST_F(AnimationCompositorAnimationsTest, isCandidateForAnimationOnCompositorKeyframeEffectMultipleFramesOkay)
+{
+ KeyframeAnimationEffect::KeyframeVector framesSame;
+ framesSame.append(createDefaultKeyframe(CSSPropertyOpacity, AnimationEffect::CompositeReplace, 0.0).get());
+ framesSame.append(createDefaultKeyframe(CSSPropertyOpacity, AnimationEffect::CompositeReplace, 1.0).get());
+ EXPECT_TRUE(isCandidateForAnimationOnCompositor(m_timing, *KeyframeAnimationEffect::create(framesSame).get()));
+
+ KeyframeAnimationEffect::KeyframeVector framesMixed;
+ framesMixed.append(createDefaultKeyframe(CSSPropertyOpacity, AnimationEffect::CompositeReplace, 0.0).get());
+ framesMixed.append(createDefaultKeyframe(CSSPropertyWebkitTransform, AnimationEffect::CompositeReplace, 1.0).get());
+ EXPECT_TRUE(isCandidateForAnimationOnCompositor(m_timing, *KeyframeAnimationEffect::create(framesMixed).get()));
+}
+
+TEST_F(AnimationCompositorAnimationsTest, isCandidateForAnimationOnCompositorKeyframeEffectMultipleFramesNotOkay)
+{
+ KeyframeAnimationEffect::KeyframeVector framesSame;
+ framesSame.append(createDefaultKeyframe(CSSPropertyColor, AnimationEffect::CompositeReplace, 0.0).get());
+ framesSame.append(createDefaultKeyframe(CSSPropertyColor, AnimationEffect::CompositeReplace, 1.0).get());
+ EXPECT_FALSE(isCandidateForAnimationOnCompositor(m_timing, *KeyframeAnimationEffect::create(framesSame).get()));
+
+ KeyframeAnimationEffect::KeyframeVector framesMixedProperties;
+ framesMixedProperties.append(createDefaultKeyframe(CSSPropertyOpacity, AnimationEffect::CompositeReplace, 0.0).get());
+ framesMixedProperties.append(createDefaultKeyframe(CSSPropertyColor, AnimationEffect::CompositeReplace, 1.0).get());
+ EXPECT_FALSE(isCandidateForAnimationOnCompositor(m_timing, *KeyframeAnimationEffect::create(framesMixedProperties).get()));
+
+ KeyframeAnimationEffect::KeyframeVector framesMixedOps;
+ framesMixedOps.append(createDefaultKeyframe(CSSPropertyOpacity, AnimationEffect::CompositeReplace, 0.0).get());
+ framesMixedOps.append(createDefaultKeyframe(CSSPropertyOpacity, AnimationEffect::CompositeAdd, 1.0).get());
+ EXPECT_FALSE(isCandidateForAnimationOnCompositor(m_timing, *KeyframeAnimationEffect::create(framesMixedOps).get()));
+}
+
+TEST_F(AnimationCompositorAnimationsTest, ConvertTimingForCompositorStartDelay)
+{
+ m_timing.iterationDuration = 20.0;
+
+ m_timing.startDelay = 2.0;
+ EXPECT_TRUE(convertTimingForCompositor(m_timing, m_compositorTiming));
+ EXPECT_DOUBLE_EQ(-2.0, m_compositorTiming.scaledTimeOffset);
+
+ m_timing.startDelay = -2.0;
+ EXPECT_TRUE(convertTimingForCompositor(m_timing, m_compositorTiming));
+ EXPECT_DOUBLE_EQ(2.0, m_compositorTiming.scaledTimeOffset);
+}
+
+TEST_F(AnimationCompositorAnimationsTest, ConvertTimingForCompositorIterationStart)
+{
+ m_timing.iterationStart = 2.2;
+ EXPECT_FALSE(convertTimingForCompositor(m_timing, m_compositorTiming));
+}
+
+TEST_F(AnimationCompositorAnimationsTest, ConvertTimingForCompositorIterationCount)
+{
+ m_timing.iterationCount = 5.0;
+ EXPECT_TRUE(convertTimingForCompositor(m_timing, m_compositorTiming));
+ EXPECT_EQ(5, m_compositorTiming.adjustedIterationCount);
+
+ m_timing.iterationCount = 5.5;
+ EXPECT_FALSE(convertTimingForCompositor(m_timing, m_compositorTiming));
+
+ // Asserts will only trigger on DEBUG build.
+ // EXPECT_DEATH tests are flaky on Android.
+#if !defined(NDEBUG) && !OS(ANDROID)
+ m_timing.iterationCount = -1;
+ EXPECT_DEATH(convertTimingForCompositor(m_timing, m_compositorTiming), "");
+#endif
+
+ m_timing.iterationCount = std::numeric_limits<double>::infinity();
+ EXPECT_TRUE(convertTimingForCompositor(m_timing, m_compositorTiming));
+ EXPECT_EQ(-1, m_compositorTiming.adjustedIterationCount);
+
+ m_timing.iterationCount = std::numeric_limits<double>::infinity();
+ m_timing.iterationDuration = 5.0;
+ m_timing.startDelay = -6.0;
+ EXPECT_TRUE(convertTimingForCompositor(m_timing, m_compositorTiming));
+ EXPECT_DOUBLE_EQ(6.0, m_compositorTiming.scaledTimeOffset);
+ EXPECT_EQ(-1, m_compositorTiming.adjustedIterationCount);
+}
+
+TEST_F(AnimationCompositorAnimationsTest, ConvertTimingForCompositorIterationsAndStartDelay)
+{
+ m_timing.iterationCount = 4.0;
+ m_timing.iterationDuration = 5.0;
+
+ m_timing.startDelay = 6.0;
+ EXPECT_TRUE(convertTimingForCompositor(m_timing, m_compositorTiming));
+ EXPECT_DOUBLE_EQ(-6.0, m_compositorTiming.scaledTimeOffset);
+ EXPECT_DOUBLE_EQ(4.0, m_compositorTiming.adjustedIterationCount);
+
+ m_timing.startDelay = -6.0;
+ EXPECT_TRUE(convertTimingForCompositor(m_timing, m_compositorTiming));
+ EXPECT_DOUBLE_EQ(6.0, m_compositorTiming.scaledTimeOffset);
+ EXPECT_DOUBLE_EQ(4.0, m_compositorTiming.adjustedIterationCount);
+
+ m_timing.startDelay = 21.0;
+ EXPECT_FALSE(convertTimingForCompositor(m_timing, m_compositorTiming));
+}
+
+TEST_F(AnimationCompositorAnimationsTest, ConvertTimingForCompositorPlaybackRate)
+{
+ m_timing.playbackRate = 2.0;
+ EXPECT_FALSE(convertTimingForCompositor(m_timing, m_compositorTiming));
+
+ m_timing.playbackRate = 0.0;
+ EXPECT_FALSE(convertTimingForCompositor(m_timing, m_compositorTiming));
+
+ m_timing.playbackRate = -2.0;
+ EXPECT_FALSE(convertTimingForCompositor(m_timing, m_compositorTiming));
+}
+
+TEST_F(AnimationCompositorAnimationsTest, ConvertTimingForCompositorDirection)
+{
+ m_timing.direction = Timing::PlaybackDirectionAlternate;
+ EXPECT_TRUE(convertTimingForCompositor(m_timing, m_compositorTiming));
+ EXPECT_TRUE(m_compositorTiming.alternate);
+ EXPECT_FALSE(m_compositorTiming.reverse);
+
+ m_timing.direction = Timing::PlaybackDirectionAlternateReverse;
+ EXPECT_TRUE(convertTimingForCompositor(m_timing, m_compositorTiming));
+ EXPECT_TRUE(m_compositorTiming.alternate);
+ EXPECT_TRUE(m_compositorTiming.reverse);
+
+ m_timing.direction = Timing::PlaybackDirectionReverse;
+ EXPECT_TRUE(convertTimingForCompositor(m_timing, m_compositorTiming));
+ EXPECT_FALSE(m_compositorTiming.alternate);
+ EXPECT_TRUE(m_compositorTiming.reverse);
+}
+
+TEST_F(AnimationCompositorAnimationsTest, ConvertTimingForCompositorDirectionIterationsAndStartDelay)
+{
+ m_timing.direction = Timing::PlaybackDirectionAlternate;
+ m_timing.iterationCount = 4.0;
+ m_timing.iterationDuration = 5.0;
+ m_timing.startDelay = -6.0;
+ EXPECT_TRUE(convertTimingForCompositor(m_timing, m_compositorTiming));
+ EXPECT_DOUBLE_EQ(6.0, m_compositorTiming.scaledTimeOffset);
+ EXPECT_EQ(4, m_compositorTiming.adjustedIterationCount);
+ EXPECT_TRUE(m_compositorTiming.alternate);
+ EXPECT_FALSE(m_compositorTiming.reverse);
+
+ m_timing.direction = Timing::PlaybackDirectionAlternate;
+ m_timing.iterationCount = 4.0;
+ m_timing.iterationDuration = 5.0;
+ m_timing.startDelay = -11.0;
+ EXPECT_TRUE(convertTimingForCompositor(m_timing, m_compositorTiming));
+ EXPECT_DOUBLE_EQ(11.0, m_compositorTiming.scaledTimeOffset);
+ EXPECT_EQ(4, m_compositorTiming.adjustedIterationCount);
+ EXPECT_TRUE(m_compositorTiming.alternate);
+ EXPECT_FALSE(m_compositorTiming.reverse);
+
+ m_timing.direction = Timing::PlaybackDirectionAlternateReverse;
+ m_timing.iterationCount = 4.0;
+ m_timing.iterationDuration = 5.0;
+ m_timing.startDelay = -6.0;
+ EXPECT_TRUE(convertTimingForCompositor(m_timing, m_compositorTiming));
+ EXPECT_DOUBLE_EQ(6.0, m_compositorTiming.scaledTimeOffset);
+ EXPECT_EQ(4, m_compositorTiming.adjustedIterationCount);
+ EXPECT_TRUE(m_compositorTiming.alternate);
+ EXPECT_TRUE(m_compositorTiming.reverse);
+
+ m_timing.direction = Timing::PlaybackDirectionAlternateReverse;
+ m_timing.iterationCount = 4.0;
+ m_timing.iterationDuration = 5.0;
+ m_timing.startDelay = -11.0;
+ EXPECT_TRUE(convertTimingForCompositor(m_timing, m_compositorTiming));
+ EXPECT_DOUBLE_EQ(11.0, m_compositorTiming.scaledTimeOffset);
+ EXPECT_EQ(4, m_compositorTiming.adjustedIterationCount);
+ EXPECT_TRUE(m_compositorTiming.alternate);
+ EXPECT_TRUE(m_compositorTiming.reverse);
+}
+
+TEST_F(AnimationCompositorAnimationsTest, isCandidateForAnimationOnCompositorTimingTimingFunctionPassThru)
+{
+ m_timing.timingFunction = m_stepTimingFunction;
+ EXPECT_FALSE(isCandidateForAnimationOnCompositor(m_timing, *m_keyframeAnimationEffect2.get()));
+}
+
+TEST_F(AnimationCompositorAnimationsTest, isCandidateForAnimationOnCompositorTimingFunctionLinear)
+{
+ m_timing.timingFunction = m_linearTimingFunction;
+ EXPECT_TRUE(isCandidateForAnimationOnCompositor(m_timing, *m_keyframeAnimationEffect2.get()));
+ EXPECT_TRUE(isCandidateForAnimationOnCompositor(m_timing, *m_keyframeAnimationEffect5.get()));
+}
+
+TEST_F(AnimationCompositorAnimationsTest, isCandidateForAnimationOnCompositorTimingFunctionCubic)
+{
+ // Cubic bezier are okay if we only have two keyframes
+ m_timing.timingFunction = m_cubicEaseTimingFunction;
+ EXPECT_TRUE(isCandidateForAnimationOnCompositor(m_timing, *m_keyframeAnimationEffect2.get()));
+ EXPECT_FALSE(isCandidateForAnimationOnCompositor(m_timing, *m_keyframeAnimationEffect5.get()));
+
+ m_timing.timingFunction = m_cubicCustomTimingFunction;
+ EXPECT_TRUE(isCandidateForAnimationOnCompositor(m_timing, *m_keyframeAnimationEffect2.get()));
+ EXPECT_FALSE(isCandidateForAnimationOnCompositor(m_timing, *m_keyframeAnimationEffect5.get()));
+}
+
+TEST_F(AnimationCompositorAnimationsTest, isCandidateForAnimationOnCompositorTimingFunctionSteps)
+{
+ m_timing.timingFunction = m_stepTimingFunction;
+ EXPECT_FALSE(isCandidateForAnimationOnCompositor(m_timing, *m_keyframeAnimationEffect2.get()));
+ EXPECT_FALSE(isCandidateForAnimationOnCompositor(m_timing, *m_keyframeAnimationEffect5.get()));
+}
+
+TEST_F(AnimationCompositorAnimationsTest, isCandidateForAnimationOnCompositorTimingFunctionChainedEmpty)
+{
+ RefPtr<ChainedTimingFunction> chainedEmpty = ChainedTimingFunction::create();
+ m_timing.timingFunction = chainedEmpty;
+ EXPECT_FALSE(isCandidateForAnimationOnCompositor(m_timing, *m_keyframeAnimationEffect2.get()));
+ EXPECT_FALSE(isCandidateForAnimationOnCompositor(m_timing, *m_keyframeAnimationEffect5.get()));
+}
+
+TEST_F(AnimationCompositorAnimationsTest, isCandidateForAnimationOnCompositorTimingFunctionChainedLinear)
+{
+ RefPtr<ChainedTimingFunction> chainedLinearSingle = ChainedTimingFunction::create();
+ chainedLinearSingle->appendSegment(1.0, m_linearTimingFunction.get());
+ m_timing.timingFunction = chainedLinearSingle;
+ EXPECT_TRUE(isCandidateForAnimationOnCompositor(m_timing, *m_keyframeAnimationEffect2.get()));
+
+ RefPtr<ChainedTimingFunction> chainedLinearMultiple = ChainedTimingFunction::create();
+ chainedLinearMultiple->appendSegment(0.25, m_linearTimingFunction.get());
+ chainedLinearMultiple->appendSegment(0.5, m_linearTimingFunction.get());
+ chainedLinearMultiple->appendSegment(0.75, m_linearTimingFunction.get());
+ chainedLinearMultiple->appendSegment(1.0, m_linearTimingFunction.get());
+ m_timing.timingFunction = chainedLinearMultiple;
+ EXPECT_TRUE(isCandidateForAnimationOnCompositor(m_timing, *m_keyframeAnimationEffect5.get()));
+
+ // FIXME: Technically a chained timing function of linear functions don't
+ // have to be aligned to keyframes. We don't support that currently as
+ // nothing generates that yet.
+}
+
+TEST_F(AnimationCompositorAnimationsTest, isCandidateForAnimationOnCompositorTimingFunctionChainedCubicMatchingOffsets)
+{
+ RefPtr<ChainedTimingFunction> chainedSingleAGood = ChainedTimingFunction::create();
+ chainedSingleAGood->appendSegment(1.0, m_cubicEaseTimingFunction.get());
+ m_timing.timingFunction = chainedSingleAGood;
+ EXPECT_TRUE(isCandidateForAnimationOnCompositor(m_timing, *m_keyframeAnimationEffect2.get()));
+
+ RefPtr<ChainedTimingFunction> chainedSingleBGood = ChainedTimingFunction::create();
+ chainedSingleBGood->appendSegment(1.0, m_cubicCustomTimingFunction.get());
+ m_timing.timingFunction = chainedSingleBGood;
+ EXPECT_TRUE(isCandidateForAnimationOnCompositor(m_timing, *m_keyframeAnimationEffect2.get()));
+
+ RefPtr<ChainedTimingFunction> chainedMultipleGood = ChainedTimingFunction::create();
+ chainedMultipleGood->appendSegment(0.25, m_cubicEaseTimingFunction.get());
+ chainedMultipleGood->appendSegment(0.5, m_cubicCustomTimingFunction.get());
+ chainedMultipleGood->appendSegment(0.75, m_cubicCustomTimingFunction.get());
+ chainedMultipleGood->appendSegment(1.0, m_cubicCustomTimingFunction.get());
+ m_timing.timingFunction = chainedMultipleGood;
+ EXPECT_TRUE(isCandidateForAnimationOnCompositor(m_timing, *m_keyframeAnimationEffect5.get()));
+}
+
+TEST_F(AnimationCompositorAnimationsTest, isCandidateForAnimationOnCompositorTimingFunctionChainedCubicNonMatchingOffsets)
+{
+ RefPtr<ChainedTimingFunction> chained0 = ChainedTimingFunction::create();
+ chained0->appendSegment(0.5, m_cubicEaseTimingFunction.get());
+ m_timing.timingFunction = chained0;
+ EXPECT_FALSE(isCandidateForAnimationOnCompositor(m_timing, *m_keyframeAnimationEffect2.get()));
+
+ RefPtr<ChainedTimingFunction> chained1 = ChainedTimingFunction::create();
+ chained1->appendSegment(0.24, m_cubicEaseTimingFunction.get());
+ chained1->appendSegment(0.5, m_cubicEaseTimingFunction.get());
+ chained1->appendSegment(0.75, m_cubicEaseTimingFunction.get());
+ chained1->appendSegment(1.0, m_cubicEaseTimingFunction.get());
+ m_timing.timingFunction = chained1;
+ EXPECT_FALSE(isCandidateForAnimationOnCompositor(m_timing, *m_keyframeAnimationEffect5.get()));
+
+ RefPtr<ChainedTimingFunction> chained2 = ChainedTimingFunction::create();
+ chained2->appendSegment(0.25, m_cubicEaseTimingFunction.get());
+ chained2->appendSegment(0.51, m_cubicEaseTimingFunction.get());
+ chained2->appendSegment(0.75, m_cubicEaseTimingFunction.get());
+ chained2->appendSegment(1.0, m_cubicEaseTimingFunction.get());
+ m_timing.timingFunction = chained2;
+ EXPECT_FALSE(isCandidateForAnimationOnCompositor(m_timing, *m_keyframeAnimationEffect5.get()));
+
+ RefPtr<ChainedTimingFunction> chained3 = ChainedTimingFunction::create();
+ chained3->appendSegment(0.25, m_cubicEaseTimingFunction.get());
+ chained3->appendSegment(0.5, m_cubicEaseTimingFunction.get());
+ chained3->appendSegment(0.75, m_cubicEaseTimingFunction.get());
+ chained3->appendSegment(0.8, m_cubicEaseTimingFunction.get());
+ m_timing.timingFunction = chained3;
+ EXPECT_FALSE(isCandidateForAnimationOnCompositor(m_timing, *m_keyframeAnimationEffect5.get()));
+
+ RefPtr<ChainedTimingFunction> chained4 = ChainedTimingFunction::create();
+ chained4->appendSegment(0.25, m_cubicEaseTimingFunction.get());
+ chained4->appendSegment(0.5, m_cubicEaseTimingFunction.get());
+ chained4->appendSegment(0.75, m_cubicEaseTimingFunction.get());
+ chained4->appendSegment(1.1, m_cubicEaseTimingFunction.get());
+ m_timing.timingFunction = chained4;
+ EXPECT_FALSE(isCandidateForAnimationOnCompositor(m_timing, *m_keyframeAnimationEffect5.get()));
+}
+
+TEST_F(AnimationCompositorAnimationsTest, isCandidateForAnimationOnCompositorTimingFunctionMissingFrames)
+{
+ // Missing first
+ RefPtr<ChainedTimingFunction> chained1 = ChainedTimingFunction::create();
+ chained1->appendSegment(0.5, m_cubicEaseTimingFunction.get());
+ chained1->appendSegment(0.75, m_cubicEaseTimingFunction.get());
+ chained1->appendSegment(1.0, m_cubicEaseTimingFunction.get());
+ m_timing.timingFunction = chained1;
+ EXPECT_FALSE(isCandidateForAnimationOnCompositor(m_timing, *m_keyframeAnimationEffect5.get()));
+
+ // Missing middle
+ RefPtr<ChainedTimingFunction> chained2 = ChainedTimingFunction::create();
+ chained2->appendSegment(0.25, m_cubicEaseTimingFunction.get());
+ chained2->appendSegment(0.75, m_cubicEaseTimingFunction.get());
+ chained2->appendSegment(1.0, m_cubicEaseTimingFunction.get());
+ m_timing.timingFunction = chained2;
+ EXPECT_FALSE(isCandidateForAnimationOnCompositor(m_timing, *m_keyframeAnimationEffect5.get()));
+
+ // Missing last
+ RefPtr<ChainedTimingFunction> chained3 = ChainedTimingFunction::create();
+ chained3->appendSegment(0.25, m_cubicEaseTimingFunction.get());
+ chained3->appendSegment(0.5, m_cubicEaseTimingFunction.get());
+ chained3->appendSegment(0.75, m_cubicEaseTimingFunction.get());
+ m_timing.timingFunction = chained3;
+ EXPECT_FALSE(isCandidateForAnimationOnCompositor(m_timing, *m_keyframeAnimationEffect5.get()));
+}
+
+TEST_F(AnimationCompositorAnimationsTest, isCandidateForAnimationOnCompositorTimingFunctionToManyFrames)
+{
+ RefPtr<ChainedTimingFunction> chained1 = ChainedTimingFunction::create();
+ chained1->appendSegment(0.1, m_cubicEaseTimingFunction.get());
+ chained1->appendSegment(0.5, m_cubicEaseTimingFunction.get());
+ m_timing.timingFunction = chained1;
+ EXPECT_FALSE(isCandidateForAnimationOnCompositor(m_timing, *m_keyframeAnimationEffect2.get()));
+
+ RefPtr<ChainedTimingFunction> chained2 = ChainedTimingFunction::create();
+ chained2->appendSegment(0.1, m_cubicEaseTimingFunction.get());
+ chained2->appendSegment(0.25, m_cubicEaseTimingFunction.get());
+ chained2->appendSegment(0.5, m_cubicEaseTimingFunction.get());
+ chained2->appendSegment(0.75, m_cubicEaseTimingFunction.get());
+ chained2->appendSegment(1.0, m_cubicEaseTimingFunction.get());
+ m_timing.timingFunction = chained2;
+ EXPECT_FALSE(isCandidateForAnimationOnCompositor(m_timing, *m_keyframeAnimationEffect5.get()));
+}
+
+TEST_F(AnimationCompositorAnimationsTest, isCandidateForAnimationOnCompositorTimingFunctionMixedGood)
+{
+ RefPtr<ChainedTimingFunction> chainedMixed = ChainedTimingFunction::create();
+ chainedMixed->appendSegment(0.25, m_linearTimingFunction.get());
+ chainedMixed->appendSegment(0.5, m_cubicEaseTimingFunction.get());
+ chainedMixed->appendSegment(0.75, m_cubicEaseTimingFunction.get());
+ chainedMixed->appendSegment(1.0, m_linearTimingFunction.get());
+ m_timing.timingFunction = chainedMixed;
+ EXPECT_TRUE(isCandidateForAnimationOnCompositor(m_timing, *m_keyframeAnimationEffect5.get()));
+}
+
+TEST_F(AnimationCompositorAnimationsTest, isCandidateForAnimationOnCompositorTimingFunctionWithStepNotOkay)
+{
+ RefPtr<ChainedTimingFunction> chainedStepSingle = ChainedTimingFunction::create();
+ chainedStepSingle->appendSegment(1.0, m_stepTimingFunction.get());
+ m_timing.timingFunction = chainedStepSingle;
+ EXPECT_FALSE(isCandidateForAnimationOnCompositor(m_timing, *m_keyframeAnimationEffect2.get()));
+
+ RefPtr<ChainedTimingFunction> chainedStepMixedA = ChainedTimingFunction::create();
+ chainedStepMixedA->appendSegment(0.25, m_stepTimingFunction.get());
+ chainedStepMixedA->appendSegment(0.5, m_linearTimingFunction.get());
+ chainedStepMixedA->appendSegment(1.0, m_cubicEaseTimingFunction.get());
+ m_timing.timingFunction = chainedStepMixedA;
+ EXPECT_FALSE(isCandidateForAnimationOnCompositor(m_timing, *m_keyframeAnimationEffect5.get()));
+
+ RefPtr<ChainedTimingFunction> chainedStepMixedB = ChainedTimingFunction::create();
+ chainedStepMixedB->appendSegment(0.25, m_linearTimingFunction.get());
+ chainedStepMixedB->appendSegment(0.5, m_stepTimingFunction.get());
+ chainedStepMixedB->appendSegment(1.0, m_cubicEaseTimingFunction.get());
+ m_timing.timingFunction = chainedStepMixedB;
+ EXPECT_FALSE(isCandidateForAnimationOnCompositor(m_timing, *m_keyframeAnimationEffect5.get()));
+
+ RefPtr<ChainedTimingFunction> chainedStepMixedC = ChainedTimingFunction::create();
+ chainedStepMixedC->appendSegment(0.25, m_linearTimingFunction.get());
+ chainedStepMixedC->appendSegment(0.5, m_cubicEaseTimingFunction.get());
+ chainedStepMixedC->appendSegment(1.0, m_stepTimingFunction.get());
+ m_timing.timingFunction = chainedStepMixedC;
+ EXPECT_FALSE(isCandidateForAnimationOnCompositor(m_timing, *m_keyframeAnimationEffect5.get()));
+}
+
+TEST_F(AnimationCompositorAnimationsTest, isCandidateForAnimationOnCompositorTimingFunctionNestedNotOkay)
+{
+ RefPtr<ChainedTimingFunction> chainedChild = ChainedTimingFunction::create();
+ chainedChild->appendSegment(1.0, m_linearTimingFunction.get());
+
+ RefPtr<ChainedTimingFunction> chainedParent = ChainedTimingFunction::create();
+ chainedParent->appendSegment(0.25, m_linearTimingFunction.get());
+ chainedParent->appendSegment(0.5, chainedChild.get());
+ chainedParent->appendSegment(0.75, m_linearTimingFunction.get());
+ chainedParent->appendSegment(1.0, m_linearTimingFunction.get());
+ m_timing.timingFunction = chainedParent;
+ EXPECT_FALSE(isCandidateForAnimationOnCompositor(m_timing, *m_keyframeAnimationEffect5.get()));
+}
+
+TEST_F(AnimationCompositorAnimationsTest, isCandidateForAnimationOnCompositor)
+{
+ Timing linearTiming(createCompositableTiming());
+
+ RefPtr<TimingFunction> cubicTimingFunc = CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseIn);
+ Timing cubicTiming(createCompositableTiming());
+ cubicTiming.timingFunction = cubicTimingFunc;
+
+ RefPtr<ChainedTimingFunction> chainedTimingFunc = ChainedTimingFunction::create();
+ chainedTimingFunc->appendSegment(0.5, m_linearTimingFunction.get());
+ chainedTimingFunc->appendSegment(1.0, cubicTimingFunc.get());
+ Timing chainedTiming(createCompositableTiming());
+ chainedTiming.timingFunction = chainedTimingFunc;
+
+ KeyframeAnimationEffect::KeyframeVector basicFramesVector;
+ basicFramesVector.append(createDefaultKeyframe(CSSPropertyOpacity, AnimationEffect::CompositeReplace, 0.0).get());
+ basicFramesVector.append(createDefaultKeyframe(CSSPropertyOpacity, AnimationEffect::CompositeReplace, 1.0).get());
+ RefPtr<KeyframeAnimationEffect> basicFrames = KeyframeAnimationEffect::create(basicFramesVector).get();
+
+ EXPECT_TRUE(isCandidateForAnimationOnCompositor(linearTiming, *basicFrames.get()));
+ EXPECT_TRUE(isCandidateForAnimationOnCompositor(cubicTiming, *basicFrames.get()));
+ // number of timing function and keyframes don't match
+ EXPECT_FALSE(isCandidateForAnimationOnCompositor(chainedTiming, *basicFrames.get()));
+
+ KeyframeAnimationEffect::KeyframeVector nonBasicFramesVector;
+ nonBasicFramesVector.append(createDefaultKeyframe(CSSPropertyOpacity, AnimationEffect::CompositeReplace, 0.0).get());
+ nonBasicFramesVector.append(createDefaultKeyframe(CSSPropertyOpacity, AnimationEffect::CompositeReplace, 0.5).get());
+ nonBasicFramesVector.append(createDefaultKeyframe(CSSPropertyOpacity, AnimationEffect::CompositeReplace, 1.0).get());
+ RefPtr<KeyframeAnimationEffect> nonBasicFrames = KeyframeAnimationEffect::create(nonBasicFramesVector).get();
+
+ EXPECT_TRUE(CompositorAnimations::instance()->isCandidateForAnimationOnCompositor(linearTiming, *nonBasicFrames.get()));
+ EXPECT_FALSE(CompositorAnimations::instance()->isCandidateForAnimationOnCompositor(cubicTiming, *nonBasicFrames.get()));
+ EXPECT_TRUE(CompositorAnimations::instance()->isCandidateForAnimationOnCompositor(chainedTiming, *nonBasicFrames.get()));
+}
+
+// -----------------------------------------------------------------------
+// -----------------------------------------------------------------------
+
+TEST_F(AnimationCompositorAnimationsTest, createSimpleOpacityAnimation)
+{
+ // Animation to convert
+ RefPtr<KeyframeAnimationEffect> effect = createKeyframeAnimationEffect(
+ createReplaceOpKeyframe(CSSPropertyOpacity, AnimatableDouble::create(2.0).get(), 0),
+ createReplaceOpKeyframe(CSSPropertyOpacity, AnimatableDouble::create(5.0).get(), 1.0));
+ // --
+
+ WebCompositorSupportMock mockCompositor;
+
+ // Curve is created
+ blink::WebFloatAnimationCurveMock* mockCurvePtr = new blink::WebFloatAnimationCurveMock;
+ ExpectationSet usesMockCurve;
+ EXPECT_CALL(mockCompositor, createFloatAnimationCurve())
+ .WillOnce(Return(mockCurvePtr));
+
+ usesMockCurve += EXPECT_CALL(*mockCurvePtr, add(blink::WebFloatKeyframe(0.0, 2.0), blink::WebAnimationCurve::TimingFunctionTypeLinear));
+ usesMockCurve += EXPECT_CALL(*mockCurvePtr, add(blink::WebFloatKeyframe(1.0, 5.0)));
+
+ // Create animation
+ blink::WebAnimationMock* mockAnimationPtr = new blink::WebAnimationMock(blink::WebAnimation::TargetPropertyOpacity);
+ ExpectationSet usesMockAnimation;
+
+ usesMockCurve += EXPECT_CALL(mockCompositor, createAnimation(Ref(*mockCurvePtr), blink::WebAnimation::TargetPropertyOpacity, _))
+ .WillOnce(Return(mockAnimationPtr));
+
+ usesMockAnimation += EXPECT_CALL(*mockAnimationPtr, setIterations(1));
+ usesMockAnimation += EXPECT_CALL(*mockAnimationPtr, setTimeOffset(0.0));
+ usesMockAnimation += EXPECT_CALL(*mockAnimationPtr, setAlternatesDirection(false));
+
+ EXPECT_CALL(*mockAnimationPtr, delete_())
+ .Times(1)
+ .After(usesMockAnimation);
+ EXPECT_CALL(*mockCurvePtr, delete_())
+ .Times(1)
+ .After(usesMockCurve);
+
+ // Go!
+ setCompositorForTesting(mockCompositor);
+ Vector<OwnPtr<blink::WebAnimation> > result;
+ getAnimationOnCompositor(m_timing, *effect.get(), result);
+ EXPECT_EQ(1U, result.size());
+ result[0].clear();
+}
+
+TEST_F(AnimationCompositorAnimationsTest, createSimpleOpacityAnimationDuration)
+{
+ // Animation to convert
+ RefPtr<KeyframeAnimationEffect> effect = createKeyframeAnimationEffect(
+ createReplaceOpKeyframe(CSSPropertyOpacity, AnimatableDouble::create(2.0).get(), 0),
+ createReplaceOpKeyframe(CSSPropertyOpacity, AnimatableDouble::create(5.0).get(), 1.0));
+
+ m_timing.iterationDuration = 10.0;
+ // --
+
+ WebCompositorSupportMock mockCompositor;
+
+ // Curve is created
+ blink::WebFloatAnimationCurveMock* mockCurvePtr = new blink::WebFloatAnimationCurveMock;
+ ExpectationSet usesMockCurve;
+ EXPECT_CALL(mockCompositor, createFloatAnimationCurve())
+ .WillOnce(Return(mockCurvePtr));
+
+ usesMockCurve += EXPECT_CALL(*mockCurvePtr, add(blink::WebFloatKeyframe(0.0, 2.0), blink::WebAnimationCurve::TimingFunctionTypeLinear));
+ usesMockCurve += EXPECT_CALL(*mockCurvePtr, add(blink::WebFloatKeyframe(10.0, 5.0)));
+
+ // Create animation
+ blink::WebAnimationMock* mockAnimationPtr = new blink::WebAnimationMock(blink::WebAnimation::TargetPropertyOpacity);
+ ExpectationSet usesMockAnimation;
+
+ usesMockCurve += EXPECT_CALL(mockCompositor, createAnimation(Ref(*mockCurvePtr), blink::WebAnimation::TargetPropertyOpacity, _))
+ .WillOnce(Return(mockAnimationPtr));
+
+ usesMockAnimation += EXPECT_CALL(*mockAnimationPtr, setIterations(1));
+ usesMockAnimation += EXPECT_CALL(*mockAnimationPtr, setTimeOffset(0.0));
+ usesMockAnimation += EXPECT_CALL(*mockAnimationPtr, setAlternatesDirection(false));
+
+ EXPECT_CALL(*mockAnimationPtr, delete_())
+ .Times(1)
+ .After(usesMockAnimation);
+ EXPECT_CALL(*mockCurvePtr, delete_())
+ .Times(1)
+ .After(usesMockCurve);
+
+ // Go!
+ setCompositorForTesting(mockCompositor);
+ Vector<OwnPtr<blink::WebAnimation> > result;
+ getAnimationOnCompositor(m_timing, *effect.get(), result);
+ EXPECT_EQ(1U, result.size());
+ result[0].clear();
+}
+
+TEST_F(AnimationCompositorAnimationsTest, createMultipleKeyframeOpacityAnimationLinear)
+{
+ // Animation to convert
+ RefPtr<KeyframeAnimationEffect> effect = createKeyframeAnimationEffect(
+ createReplaceOpKeyframe(CSSPropertyOpacity, AnimatableDouble::create(2.0).get(), 0),
+ createReplaceOpKeyframe(CSSPropertyOpacity, AnimatableDouble::create(-1.0).get(), 0.25),
+ createReplaceOpKeyframe(CSSPropertyOpacity, AnimatableDouble::create(20.0).get(), 0.5),
+ createReplaceOpKeyframe(CSSPropertyOpacity, AnimatableDouble::create(5.0).get(), 1.0));
+
+ m_timing.iterationCount = 5;
+ m_timing.direction = Timing::PlaybackDirectionAlternate;
+ // --
+
+ WebCompositorSupportMock mockCompositor;
+
+ // Curve is created
+ blink::WebFloatAnimationCurveMock* mockCurvePtr = new blink::WebFloatAnimationCurveMock();
+ ExpectationSet usesMockCurve;
+
+ EXPECT_CALL(mockCompositor, createFloatAnimationCurve())
+ .WillOnce(Return(mockCurvePtr));
+
+ usesMockCurve += EXPECT_CALL(*mockCurvePtr, add(blink::WebFloatKeyframe(0.0, 2.0), blink::WebAnimationCurve::TimingFunctionTypeLinear));
+ usesMockCurve += EXPECT_CALL(*mockCurvePtr, add(blink::WebFloatKeyframe(0.25, -1.0), blink::WebAnimationCurve::TimingFunctionTypeLinear));
+ usesMockCurve += EXPECT_CALL(*mockCurvePtr, add(blink::WebFloatKeyframe(0.5, 20.0), blink::WebAnimationCurve::TimingFunctionTypeLinear));
+ usesMockCurve += EXPECT_CALL(*mockCurvePtr, add(blink::WebFloatKeyframe(1.0, 5.0)));
+
+ // Animation is created
+ blink::WebAnimationMock* mockAnimationPtr = new blink::WebAnimationMock(blink::WebAnimation::TargetPropertyOpacity);
+ ExpectationSet usesMockAnimation;
+
+ usesMockCurve += EXPECT_CALL(mockCompositor, createAnimation(Ref(*mockCurvePtr), blink::WebAnimation::TargetPropertyOpacity, _))
+ .WillOnce(Return(mockAnimationPtr));
+
+ usesMockAnimation += EXPECT_CALL(*mockAnimationPtr, setIterations(5));
+ usesMockAnimation += EXPECT_CALL(*mockAnimationPtr, setTimeOffset(0.0));
+ usesMockAnimation += EXPECT_CALL(*mockAnimationPtr, setAlternatesDirection(true));
+
+ EXPECT_CALL(*mockAnimationPtr, delete_())
+ .Times(1)
+ .After(usesMockAnimation);
+ EXPECT_CALL(*mockCurvePtr, delete_())
+ .Times(1)
+ .After(usesMockCurve);
+
+ // Go!
+ setCompositorForTesting(mockCompositor);
+ Vector<OwnPtr<blink::WebAnimation> > result;
+ getAnimationOnCompositor(m_timing, *effect.get(), result);
+ EXPECT_EQ(1U, result.size());
+ result[0].clear();
+}
+
+TEST_F(AnimationCompositorAnimationsTest, createSimpleOpacityAnimationStartDelay)
+{
+ // Animation to convert
+ RefPtr<KeyframeAnimationEffect> effect = createKeyframeAnimationEffect(
+ createReplaceOpKeyframe(CSSPropertyOpacity, AnimatableDouble::create(2.0).get(), 0),
+ createReplaceOpKeyframe(CSSPropertyOpacity, AnimatableDouble::create(5.0).get(), 1.0));
+
+ m_timing.iterationCount = 5.0;
+ m_timing.iterationDuration = 1.75;
+ m_timing.startDelay = 3.25;
+ // --
+
+ WebCompositorSupportMock mockCompositor;
+
+ // Curve is created
+ blink::WebFloatAnimationCurveMock* mockCurvePtr = new blink::WebFloatAnimationCurveMock;
+ ExpectationSet usesMockCurve;
+ EXPECT_CALL(mockCompositor, createFloatAnimationCurve())
+ .WillOnce(Return(mockCurvePtr));
+
+ usesMockCurve += EXPECT_CALL(*mockCurvePtr, add(blink::WebFloatKeyframe(0.0, 2.0), blink::WebAnimationCurve::TimingFunctionTypeLinear));
+ usesMockCurve += EXPECT_CALL(*mockCurvePtr, add(blink::WebFloatKeyframe(1.75, 5.0)));
+
+ // Create animation
+ blink::WebAnimationMock* mockAnimationPtr = new blink::WebAnimationMock(blink::WebAnimation::TargetPropertyOpacity);
+ ExpectationSet usesMockAnimation;
+
+ usesMockCurve += EXPECT_CALL(mockCompositor, createAnimation(Ref(*mockCurvePtr), blink::WebAnimation::TargetPropertyOpacity, _))
+ .WillOnce(Return(mockAnimationPtr));
+
+ usesMockAnimation += EXPECT_CALL(*mockAnimationPtr, setIterations(5));
+ usesMockAnimation += EXPECT_CALL(*mockAnimationPtr, setTimeOffset(-3.25));
+ usesMockAnimation += EXPECT_CALL(*mockAnimationPtr, setAlternatesDirection(false));
+
+ EXPECT_CALL(*mockAnimationPtr, delete_())
+ .Times(1)
+ .After(usesMockAnimation);
+ EXPECT_CALL(*mockCurvePtr, delete_())
+ .Times(1)
+ .After(usesMockCurve);
+
+ // Go!
+ setCompositorForTesting(mockCompositor);
+ Vector<OwnPtr<blink::WebAnimation> > result;
+ getAnimationOnCompositor(m_timing, *effect.get(), result);
+ EXPECT_EQ(1U, result.size());
+ result[0].clear();
+}
+
+TEST_F(AnimationCompositorAnimationsTest, createMultipleKeyframeOpacityAnimationChained)
+{
+ // Animation to convert
+ RefPtr<KeyframeAnimationEffect> effect = createKeyframeAnimationEffect(
+ createReplaceOpKeyframe(CSSPropertyOpacity, AnimatableDouble::create(2.0).get(), 0),
+ createReplaceOpKeyframe(CSSPropertyOpacity, AnimatableDouble::create(-1.0).get(), 0.25),
+ createReplaceOpKeyframe(CSSPropertyOpacity, AnimatableDouble::create(20.0).get(), 0.5),
+ createReplaceOpKeyframe(CSSPropertyOpacity, AnimatableDouble::create(5.0).get(), 1.0));
+
+ RefPtr<ChainedTimingFunction> chainedTimingFunction = ChainedTimingFunction::create();
+ chainedTimingFunction->appendSegment(0.25, m_cubicEaseTimingFunction.get());
+ chainedTimingFunction->appendSegment(0.5, m_linearTimingFunction.get());
+ chainedTimingFunction->appendSegment(1.0, m_cubicCustomTimingFunction.get());
+
+ m_timing.timingFunction = chainedTimingFunction;
+ m_timing.iterationDuration = 2.0;
+ m_timing.iterationCount = 10;
+ m_timing.direction = Timing::PlaybackDirectionAlternate;
+ // --
+
+ WebCompositorSupportMock mockCompositor;
+
+ // Curve is created
+ blink::WebFloatAnimationCurveMock* mockCurvePtr = new blink::WebFloatAnimationCurveMock();
+ ExpectationSet usesMockCurve;
+
+ EXPECT_CALL(mockCompositor, createFloatAnimationCurve())
+ .WillOnce(Return(mockCurvePtr));
+
+ usesMockCurve += EXPECT_CALL(*mockCurvePtr, add(blink::WebFloatKeyframe(0.0, 2.0), blink::WebAnimationCurve::TimingFunctionTypeEase));
+ usesMockCurve += EXPECT_CALL(*mockCurvePtr, add(blink::WebFloatKeyframe(0.5, -1.0), blink::WebAnimationCurve::TimingFunctionTypeLinear));
+ usesMockCurve += EXPECT_CALL(*mockCurvePtr, add(blink::WebFloatKeyframe(1.0, 20.0), 1.0, 2.0, 3.0, 4.0));
+ usesMockCurve += EXPECT_CALL(*mockCurvePtr, add(blink::WebFloatKeyframe(2.0, 5.0)));
+
+ // Animation is created
+ blink::WebAnimationMock* mockAnimationPtr = new blink::WebAnimationMock(blink::WebAnimation::TargetPropertyOpacity);
+ ExpectationSet usesMockAnimation;
+
+ usesMockCurve += EXPECT_CALL(mockCompositor, createAnimation(Ref(*mockCurvePtr), blink::WebAnimation::TargetPropertyOpacity, _))
+ .WillOnce(Return(mockAnimationPtr));
+
+ usesMockAnimation += EXPECT_CALL(*mockAnimationPtr, setIterations(10));
+ usesMockAnimation += EXPECT_CALL(*mockAnimationPtr, setTimeOffset(0.0));
+ usesMockAnimation += EXPECT_CALL(*mockAnimationPtr, setAlternatesDirection(true));
+
+ EXPECT_CALL(*mockAnimationPtr, delete_())
+ .Times(1)
+ .After(usesMockAnimation);
+ EXPECT_CALL(*mockCurvePtr, delete_())
+ .Times(1)
+ .After(usesMockCurve);
+
+ // Go!
+ setCompositorForTesting(mockCompositor);
+ Vector<OwnPtr<blink::WebAnimation> > result;
+ getAnimationOnCompositor(m_timing, *effect.get(), result);
+ EXPECT_EQ(1U, result.size());
+ result[0].clear();
+}
+
+TEST_F(AnimationCompositorAnimationsTest, createReversedOpacityAnimation)
+{
+ // Animation to convert
+ RefPtr<KeyframeAnimationEffect> effect = createKeyframeAnimationEffect(
+ createReplaceOpKeyframe(CSSPropertyOpacity, AnimatableDouble::create(2.0).get(), 0),
+ createReplaceOpKeyframe(CSSPropertyOpacity, AnimatableDouble::create(-1.0).get(), 0.25),
+ createReplaceOpKeyframe(CSSPropertyOpacity, AnimatableDouble::create(20.0).get(), 0.5),
+ createReplaceOpKeyframe(CSSPropertyOpacity, AnimatableDouble::create(5.0).get(), 1.0));
+
+ RefPtr<TimingFunction> cubicEasyFlipTimingFunction = CubicBezierTimingFunction::create(0.0, 0.0, 0.0, 1.0);
+ RefPtr<ChainedTimingFunction> chainedTimingFunction = ChainedTimingFunction::create();
+ chainedTimingFunction->appendSegment(0.25, CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseIn));
+ chainedTimingFunction->appendSegment(0.5, m_linearTimingFunction.get());
+ chainedTimingFunction->appendSegment(1.0, cubicEasyFlipTimingFunction.get());
+
+ m_timing.timingFunction = chainedTimingFunction;
+ m_timing.iterationCount = 10;
+ m_timing.direction = Timing::PlaybackDirectionAlternateReverse;
+ // --
+
+ WebCompositorSupportMock mockCompositor;
+
+ // Curve is created
+ blink::WebFloatAnimationCurveMock* mockCurvePtr = new blink::WebFloatAnimationCurveMock();
+ ExpectationSet usesMockCurve;
+
+ EXPECT_CALL(mockCompositor, createFloatAnimationCurve())
+ .WillOnce(Return(mockCurvePtr));
+
+ usesMockCurve += EXPECT_CALL(*mockCurvePtr, add(blink::WebFloatKeyframe(0.0, 5.0), 1.0, 0.0, 1.0, 1.0));
+ usesMockCurve += EXPECT_CALL(*mockCurvePtr, add(blink::WebFloatKeyframe(0.5, 20.0), blink::WebAnimationCurve::TimingFunctionTypeLinear));
+ usesMockCurve += EXPECT_CALL(*mockCurvePtr, add(blink::WebFloatKeyframe(0.75, -1.0), blink::WebAnimationCurve::TimingFunctionTypeEaseOut));
+ usesMockCurve += EXPECT_CALL(*mockCurvePtr, add(blink::WebFloatKeyframe(1.0, 2.0)));
+
+ // Create the animation
+ blink::WebAnimationMock* mockAnimationPtr = new blink::WebAnimationMock(blink::WebAnimation::TargetPropertyOpacity);
+ ExpectationSet usesMockAnimation;
+
+ usesMockCurve += EXPECT_CALL(mockCompositor, createAnimation(Ref(*mockCurvePtr), blink::WebAnimation::TargetPropertyOpacity, _))
+ .WillOnce(Return(mockAnimationPtr));
+
+ usesMockAnimation += EXPECT_CALL(*mockAnimationPtr, setIterations(10));
+ usesMockAnimation += EXPECT_CALL(*mockAnimationPtr, setTimeOffset(0.0));
+ usesMockAnimation += EXPECT_CALL(*mockAnimationPtr, setAlternatesDirection(true));
+
+ EXPECT_CALL(*mockAnimationPtr, delete_())
+ .Times(1)
+ .After(usesMockAnimation);
+ EXPECT_CALL(*mockCurvePtr, delete_())
+ .Times(1)
+ .After(usesMockCurve);
+
+ // Go!
+ setCompositorForTesting(mockCompositor);
+ Vector<OwnPtr<blink::WebAnimation> > result;
+ getAnimationOnCompositor(m_timing, *effect.get(), result);
+ EXPECT_EQ(1U, result.size());
+ result[0].clear();
+}
+
+TEST_F(AnimationCompositorAnimationsTest, createReversedOpacityAnimationNegativeStartDelay)
+{
+ // Animation to convert
+ RefPtr<KeyframeAnimationEffect> effect = createKeyframeAnimationEffect(
+ createReplaceOpKeyframe(CSSPropertyOpacity, AnimatableDouble::create(2.0).get(), 0),
+ createReplaceOpKeyframe(CSSPropertyOpacity, AnimatableDouble::create(5.0).get(), 1.0));
+
+ m_timing.iterationCount = 5.0;
+ m_timing.iterationDuration = 1.5;
+ m_timing.startDelay = -3;
+ m_timing.direction = Timing::PlaybackDirectionAlternateReverse;
+ // --
+
+ WebCompositorSupportMock mockCompositor;
+
+ // Curve is created
+ blink::WebFloatAnimationCurveMock* mockCurvePtr = new blink::WebFloatAnimationCurveMock;
+ ExpectationSet usesMockCurve;
+ EXPECT_CALL(mockCompositor, createFloatAnimationCurve())
+ .WillOnce(Return(mockCurvePtr));
+
+ usesMockCurve += EXPECT_CALL(*mockCurvePtr, add(blink::WebFloatKeyframe(0.0, 5.0), blink::WebAnimationCurve::TimingFunctionTypeLinear));
+ usesMockCurve += EXPECT_CALL(*mockCurvePtr, add(blink::WebFloatKeyframe(1.5, 2.0)));
+
+ // Create animation
+ blink::WebAnimationMock* mockAnimationPtr = new blink::WebAnimationMock(blink::WebAnimation::TargetPropertyOpacity);
+ ExpectationSet usesMockAnimation;
+
+ usesMockCurve += EXPECT_CALL(mockCompositor, createAnimation(Ref(*mockCurvePtr), blink::WebAnimation::TargetPropertyOpacity, _))
+ .WillOnce(Return(mockAnimationPtr));
+
+ usesMockAnimation += EXPECT_CALL(*mockAnimationPtr, setIterations(5));
+ usesMockAnimation += EXPECT_CALL(*mockAnimationPtr, setTimeOffset(3.0));
+ usesMockAnimation += EXPECT_CALL(*mockAnimationPtr, setAlternatesDirection(true));
+
+ EXPECT_CALL(*mockAnimationPtr, delete_())
+ .Times(1)
+ .After(usesMockAnimation);
+ EXPECT_CALL(*mockCurvePtr, delete_())
+ .Times(1)
+ .After(usesMockCurve);
+
+ // Go!
+ setCompositorForTesting(mockCompositor);
+ Vector<OwnPtr<blink::WebAnimation> > result;
+ getAnimationOnCompositor(m_timing, *effect.get(), result);
+ EXPECT_EQ(1U, result.size());
+ result[0].clear();
+}
+
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/animation/CompositorAnimationsTestHelper.h b/chromium/third_party/WebKit/Source/core/animation/CompositorAnimationsTestHelper.h
new file mode 100644
index 00000000000..732d34662e5
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/animation/CompositorAnimationsTestHelper.h
@@ -0,0 +1,164 @@
+/*
+ * Copyright (C) 2012 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef CompositorAnimationsTestHelper_h
+#define CompositorAnimationsTestHelper_h
+
+#include "core/animation/CompositorAnimations.h"
+#include "public/platform/Platform.h"
+#include "public/platform/WebCompositorSupport.h"
+#include "public/platform/WebFloatAnimationCurve.h"
+#include "public/platform/WebFloatKeyframe.h"
+#include "wtf/PassOwnPtr.h"
+
+#include <gmock/gmock.h>
+#include <gtest/gtest.h>
+
+
+namespace testing {
+
+template<typename T>
+PassOwnPtr<T> CloneToPassOwnPtr(T& o)
+{
+ return adoptPtr(new T(o));
+}
+
+} // namespace testing
+
+
+// Test helpers and mocks for blink::Web* types
+// -----------------------------------------------------------------------
+namespace blink {
+
+// blink::WebFloatKeyframe is a plain struct, so we just create an == operator
+// for it.
+inline bool operator==(const WebFloatKeyframe& a, const WebFloatKeyframe& b)
+{
+ return a.time == b.time && a.value == b.value;
+}
+
+inline void PrintTo(const WebFloatKeyframe& frame, ::std::ostream* os)
+{
+ *os << "WebFloatKeyframe@" << &frame << "(" << frame.time << ", " << frame.value << ")";
+}
+
+// -----------------------------------------------------------------------
+
+class WebAnimationMock : public blink::WebAnimation {
+private:
+ blink::WebAnimation::TargetProperty m_property;
+
+public:
+ // Target Property is set through the constructor.
+ WebAnimationMock(blink::WebAnimation::TargetProperty p) : m_property(p) { }
+ virtual blink::WebAnimation::TargetProperty targetProperty() const { return m_property; };
+
+ MOCK_METHOD0(id, int());
+
+ MOCK_CONST_METHOD0(iterations, int());
+ MOCK_METHOD1(setIterations, void(int));
+
+ MOCK_CONST_METHOD0(startTime, double());
+ MOCK_METHOD1(setStartTime, void(double));
+
+ MOCK_CONST_METHOD0(timeOffset, double());
+ MOCK_METHOD1(setTimeOffset, void(double));
+
+ MOCK_CONST_METHOD0(alternatesDirection, bool());
+ MOCK_METHOD1(setAlternatesDirection, void(bool));
+
+ MOCK_METHOD0(delete_, void());
+ ~WebAnimationMock() { delete_(); }
+};
+
+template<typename CurveType, blink::WebAnimationCurve::AnimationCurveType CurveId, typename KeyframeType>
+class WebAnimationCurveMock : public CurveType {
+public:
+ MOCK_METHOD1_T(add, void(const KeyframeType&));
+ MOCK_METHOD2_T(add, void(const KeyframeType&, blink::WebAnimationCurve::TimingFunctionType));
+ MOCK_METHOD5_T(add, void(const KeyframeType&, double, double, double, double));
+
+ MOCK_CONST_METHOD1_T(getValue, float(double)); // Only on WebFloatAnimationCurve, but can't hurt to have here.
+
+ virtual blink::WebAnimationCurve::AnimationCurveType type() const { return CurveId; };
+
+ MOCK_METHOD0(delete_, void());
+ ~WebAnimationCurveMock() { delete_(); }
+};
+
+typedef WebAnimationCurveMock<blink::WebFloatAnimationCurve, blink::WebAnimationCurve::AnimationCurveTypeFloat, blink::WebFloatKeyframe> WebFloatAnimationCurveMock;
+
+} // namespace blink
+
+namespace WebCore {
+
+class AnimationCompositorAnimationsTestBase : public ::testing::Test {
+public:
+ AnimationCompositorAnimationsTestBase() : m_proxyPlatform(&m_mockCompositor) { };
+
+ class WebCompositorSupportMock : public blink::WebCompositorSupport {
+ public:
+ MOCK_METHOD3(createAnimation, blink::WebAnimation*(const blink::WebAnimationCurve& curve, blink::WebAnimation::TargetProperty target, int animationId));
+ MOCK_METHOD0(createFloatAnimationCurve, blink::WebFloatAnimationCurve*());
+ };
+
+private:
+ class PlatformProxy : public blink::Platform {
+ public:
+ PlatformProxy(WebCompositorSupportMock** compositor) : m_compositor(compositor) { }
+
+ virtual void cryptographicallyRandomValues(unsigned char* buffer, size_t length) { ASSERT_NOT_REACHED(); }
+ private:
+ WebCompositorSupportMock** m_compositor;
+ blink::WebCompositorSupport* compositorSupport() OVERRIDE { return *m_compositor; }
+ };
+
+ WebCompositorSupportMock* m_mockCompositor;
+ PlatformProxy m_proxyPlatform;
+
+protected:
+ blink::Platform* m_platform;
+
+ virtual void SetUp()
+ {
+ m_mockCompositor = 0;
+ m_platform = blink::Platform::current();
+ blink::Platform::initialize(&m_proxyPlatform);
+ }
+
+ virtual void TearDown()
+ {
+ blink::Platform::initialize(m_platform);
+ }
+
+ void setCompositorForTesting(WebCompositorSupportMock& mock)
+ {
+ ASSERT(!m_mockCompositor);
+ m_mockCompositor = &mock;
+ }
+};
+
+}
+
+#endif
diff --git a/chromium/third_party/WebKit/Source/core/animation/CompositorAnimationsTimingFunctionReverserTest.cpp b/chromium/third_party/WebKit/Source/core/animation/CompositorAnimationsTimingFunctionReverserTest.cpp
new file mode 100644
index 00000000000..550b7f562c2
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/animation/CompositorAnimationsTimingFunctionReverserTest.cpp
@@ -0,0 +1,107 @@
+/*
+ * Copyright (c) 2013, Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+
+#include "core/animation/CompositorAnimations.h"
+
+#include "core/platform/animation/TimingFunctionTestHelper.h"
+
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefPtr.h"
+
+#include <gmock/gmock.h>
+#include <gtest/gtest.h>
+
+// FIXME: Remove once https://codereview.chromium.org/50603011/ lands.
+#define EXPECT_REFV_EQ(a, b) EXPECT_EQ(*(a.get()), *(b.get()))
+#define EXPECT_REFV_NE(a, b) EXPECT_NE(*(a.get()), *(b.get()))
+
+namespace {
+
+using namespace WebCore;
+
+class AnimationCompositorAnimationsTimingFunctionReverserTest : public ::testing::Test {
+protected:
+
+public:
+ PassRefPtr<TimingFunction> reverse(const RefPtr<TimingFunction>& timefunc)
+ {
+ return CompositorAnimationsTimingFunctionReverser::reverse(timefunc.get());
+ }
+};
+
+TEST_F(AnimationCompositorAnimationsTimingFunctionReverserTest, LinearReverse)
+{
+ RefPtr<TimingFunction> linearTiming = LinearTimingFunction::create();
+ EXPECT_REFV_EQ(linearTiming, reverse(linearTiming));
+}
+
+TEST_F(AnimationCompositorAnimationsTimingFunctionReverserTest, CubicReverse)
+{
+ RefPtr<TimingFunction> cubicEaseInTiming = CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseIn);
+ RefPtr<TimingFunction> cubicEaseOutTiming = CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseOut);
+ RefPtr<TimingFunction> cubicEaseInOutTiming = CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseInOut);
+
+ EXPECT_REFV_EQ(cubicEaseOutTiming, reverse(cubicEaseInTiming));
+ EXPECT_REFV_EQ(cubicEaseInTiming, reverse(cubicEaseOutTiming));
+ EXPECT_REFV_EQ(cubicEaseInOutTiming, reverse(cubicEaseInOutTiming));
+
+ RefPtr<TimingFunction> cubicCustomTiming = CubicBezierTimingFunction::create(0.17, 0.67, 1, -1.73);
+ // Due to floating point, 1.0-(-1.73) != 2.73
+ RefPtr<TimingFunction> cubicCustomTimingReversed = CubicBezierTimingFunction::create(0, 1.0 - (-1.73), 1.0 - 0.17, 1.0 - 0.67);
+ EXPECT_REFV_EQ(cubicCustomTimingReversed, reverse(cubicCustomTiming));
+
+ RefPtr<TimingFunction> cubicEaseTiming = CubicBezierTimingFunction::preset(CubicBezierTimingFunction::Ease);
+ RefPtr<TimingFunction> cubicEaseTimingReversed = CubicBezierTimingFunction::create(1.0 - 0.25, 0.0, 1.0 - 0.25, 1.0 - 0.1);
+ EXPECT_REFV_EQ(cubicEaseTimingReversed, reverse(cubicEaseTiming));
+}
+
+TEST_F(AnimationCompositorAnimationsTimingFunctionReverserTest, ChainedReverse)
+{
+ RefPtr<TimingFunction> linearTiming = LinearTimingFunction::create();
+ RefPtr<ChainedTimingFunction> chainedLinearSingle = ChainedTimingFunction::create();
+ chainedLinearSingle->appendSegment(1.0, linearTiming.get());
+ EXPECT_REFV_EQ(chainedLinearSingle, reverse(chainedLinearSingle));
+
+ RefPtr<TimingFunction> cubicEaseInTiming = CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseIn);
+ RefPtr<TimingFunction> cubicEaseOutTiming = CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseOut);
+
+ RefPtr<ChainedTimingFunction> chainedMixed = ChainedTimingFunction::create();
+ chainedMixed->appendSegment(0.75, chainedLinearSingle.get());
+ chainedMixed->appendSegment(1.0, cubicEaseInTiming.get());
+
+ RefPtr<ChainedTimingFunction> chainedMixedReversed = ChainedTimingFunction::create();
+ chainedMixedReversed->appendSegment(0.25, cubicEaseOutTiming.get());
+ chainedMixedReversed->appendSegment(1.0, chainedLinearSingle.get());
+ EXPECT_REFV_EQ(chainedMixedReversed, reverse(chainedMixed));
+}
+
+} // namespace
diff --git a/chromium/third_party/WebKit/Source/core/animation/DocumentAnimations.cpp b/chromium/third_party/WebKit/Source/core/animation/DocumentAnimations.cpp
new file mode 100644
index 00000000000..34ea5ca4546
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/animation/DocumentAnimations.cpp
@@ -0,0 +1,108 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/animation/DocumentAnimations.h"
+
+#include "core/animation/ActiveAnimations.h"
+#include "core/animation/AnimationClock.h"
+#include "core/animation/DocumentTimeline.h"
+#include "core/dom/Document.h"
+#include "core/dom/Element.h"
+#include "core/dom/Node.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
+#include "core/rendering/RenderLayerCompositor.h"
+#include "core/rendering/RenderView.h"
+
+namespace WebCore {
+
+namespace {
+
+void updateAnimationTiming(Document& document, double monotonicAnimationStartTime)
+{
+ document.animationClock().updateTime(monotonicAnimationStartTime);
+ bool didTriggerStyleRecalc = document.timeline()->serviceAnimations();
+ didTriggerStyleRecalc |= document.transitionTimeline()->serviceAnimations();
+ if (!didTriggerStyleRecalc)
+ document.animationClock().unfreeze();
+}
+
+void dispatchAnimationEvents(Document& document)
+{
+ document.timeline()->dispatchEvents();
+ document.transitionTimeline()->dispatchEvents();
+}
+
+void dispatchAnimationEventsAsync(Document& document)
+{
+ document.timeline()->dispatchEventsAsync();
+ document.transitionTimeline()->dispatchEventsAsync();
+}
+
+} // namespace
+
+void DocumentAnimations::serviceOnAnimationFrame(Document& document, double monotonicAnimationStartTime)
+{
+ if (!RuntimeEnabledFeatures::webAnimationsCSSEnabled())
+ return;
+
+ updateAnimationTiming(document, monotonicAnimationStartTime);
+ dispatchAnimationEvents(document);
+}
+
+void DocumentAnimations::serviceBeforeGetComputedStyle(Node& node, CSSPropertyID property)
+{
+ if (!RuntimeEnabledFeatures::webAnimationsCSSEnabled())
+ return;
+
+ if (node.isElementNode()) {
+ const Element& element = toElement(node);
+ if (const ActiveAnimations* activeAnimations = element.activeAnimations()) {
+ if (activeAnimations->hasActiveAnimationsOnCompositor(property))
+ updateAnimationTiming(element.document(), monotonicallyIncreasingTime());
+ }
+ }
+
+}
+
+void DocumentAnimations::serviceAfterStyleRecalc(Document& document)
+{
+ if (!RuntimeEnabledFeatures::webAnimationsCSSEnabled())
+ return;
+
+ if (document.cssPendingAnimations().startPendingAnimations() && document.view())
+ document.view()->scheduleAnimation();
+
+ document.animationClock().unfreeze();
+ dispatchAnimationEventsAsync(document);
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/animation/DocumentAnimations.h b/chromium/third_party/WebKit/Source/core/animation/DocumentAnimations.h
new file mode 100644
index 00000000000..b952c532ec1
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/animation/DocumentAnimations.h
@@ -0,0 +1,54 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef DocumentAnimations_h
+#define DocumentAnimations_h
+
+#include "CSSPropertyNames.h"
+
+namespace WebCore {
+
+class Document;
+class FrameView;
+class Node;
+
+class DocumentAnimations {
+public:
+ static void serviceOnAnimationFrame(Document&, double monotonicAnimationStartTime);
+ static void serviceBeforeGetComputedStyle(Node&, CSSPropertyID);
+ static void serviceAfterStyleRecalc(Document&);
+
+private:
+ DocumentAnimations() { }
+};
+
+} // namespace
+
+#endif
diff --git a/chromium/third_party/WebKit/Source/core/animation/DocumentTimeline.cpp b/chromium/third_party/WebKit/Source/core/animation/DocumentTimeline.cpp
index 902897d0a1a..21027f8b073 100644
--- a/chromium/third_party/WebKit/Source/core/animation/DocumentTimeline.cpp
+++ b/chromium/third_party/WebKit/Source/core/animation/DocumentTimeline.cpp
@@ -31,70 +31,118 @@
#include "config.h"
#include "core/animation/DocumentTimeline.h"
-#include "core/animation/Player.h"
+#include "core/animation/ActiveAnimations.h"
+#include "core/animation/AnimationClock.h"
#include "core/dom/Document.h"
-#include "core/page/FrameView.h"
+#include "core/frame/FrameView.h"
namespace WebCore {
-PassRefPtr<DocumentTimeline> DocumentTimeline::create(Document* document)
+// This value represents 1 frame at 30Hz plus a little bit of wiggle room.
+// TODO: Plumb a nominal framerate through and derive this value from that.
+const double DocumentTimeline::s_minimumDelay = 0.04;
+
+
+PassRefPtr<DocumentTimeline> DocumentTimeline::create(Document* document, PassOwnPtr<PlatformTiming> timing)
{
- return adoptRef(new DocumentTimeline(document));
+ return adoptRef(new DocumentTimeline(document, timing));
}
-DocumentTimeline::DocumentTimeline(Document* document)
- : m_currentTime(nullValue())
+DocumentTimeline::DocumentTimeline(Document* document, PassOwnPtr<PlatformTiming> timing)
+ : m_zeroTime(nullValue())
, m_document(document)
- , m_zeroTimeAsPerfTime(nullValue())
+ , m_eventDistpachTimer(this, &DocumentTimeline::eventDispatchTimerFired)
{
+ if (!timing)
+ m_timing = adoptPtr(new DocumentTimelineTiming(this));
+ else
+ m_timing = timing;
+
ASSERT(document);
}
-PassRefPtr<Player> DocumentTimeline::play(TimedItem* child)
+Player* DocumentTimeline::createPlayer(TimedItem* child)
{
- RefPtr<Player> player = Player::create(this, child);
- m_players.append(player);
-
+ RefPtr<Player> player = Player::create(*this, child);
+ Player* result = player.get();
+ m_players.append(player.release());
if (m_document->view())
- m_document->view()->scheduleAnimation();
+ m_timing->serviceOnNextFrame();
+ return result;
+}
- return player.release();
+Player* DocumentTimeline::play(TimedItem* child)
+{
+ Player* player = createPlayer(child);
+ player->setStartTime(currentTime());
+ return player;
}
-void DocumentTimeline::serviceAnimations(double monotonicAnimationStartTime)
+void DocumentTimeline::wake()
{
- // FIXME: The below ASSERT fires on Windows when running chrome.exe.
- // Does not fire with --single-process, or on Linux, or in
- // content_shell.exe. The assert condition has been moved up into the
- // outer 'if' to work around this. http://crbug.com/280439.
- if (!isNull(m_zeroTimeAsPerfTime) && (m_currentTime <= monotonicAnimationStartTime - m_zeroTimeAsPerfTime)) {
- ASSERT(m_currentTime <= monotonicAnimationStartTime - m_zeroTimeAsPerfTime);
- m_currentTime = monotonicAnimationStartTime - m_zeroTimeAsPerfTime;
- }
+ m_timing->serviceOnNextFrame();
+}
+bool DocumentTimeline::serviceAnimations()
+{
+ TRACE_EVENT0("webkit", "DocumentTimeline::serviceAnimations");
+
+ m_timing->cancelWake();
+
+ double timeToNextEffect = std::numeric_limits<double>::infinity();
+ bool didTriggerStyleRecalc = false;
for (int i = m_players.size() - 1; i >= 0; --i) {
- if (!m_players[i]->update())
+ double playerNextEffect;
+ bool playerDidTriggerStyleRecalc;
+ if (!m_players[i]->update(&playerNextEffect, &playerDidTriggerStyleRecalc))
m_players.remove(i);
+ didTriggerStyleRecalc |= playerDidTriggerStyleRecalc;
+ if (playerNextEffect < timeToNextEffect)
+ timeToNextEffect = playerNextEffect;
}
- if (m_document->view() && !m_players.isEmpty())
- m_document->view()->scheduleAnimation();
+ if (!m_players.isEmpty()) {
+ if (timeToNextEffect < s_minimumDelay)
+ m_timing->serviceOnNextFrame();
+ else if (timeToNextEffect != std::numeric_limits<double>::infinity())
+ m_timing->wakeAfter(timeToNextEffect - s_minimumDelay);
+ }
- dispatchEvents();
+ return didTriggerStyleRecalc;
}
-void DocumentTimeline::setZeroTimeAsPerfTime(double zeroTime)
+void DocumentTimeline::setZeroTime(double zeroTime)
{
- ASSERT(isNull(m_zeroTimeAsPerfTime));
- m_zeroTimeAsPerfTime = zeroTime;
- ASSERT(!isNull(m_zeroTimeAsPerfTime));
- m_currentTime = 0;
+ ASSERT(isNull(m_zeroTime));
+ m_zeroTime = zeroTime;
+ ASSERT(!isNull(m_zeroTime));
+}
+
+void DocumentTimeline::DocumentTimelineTiming::wakeAfter(double duration)
+{
+ m_timer.startOneShot(duration);
+}
+
+void DocumentTimeline::DocumentTimelineTiming::cancelWake()
+{
+ m_timer.stop();
+}
+
+void DocumentTimeline::DocumentTimelineTiming::serviceOnNextFrame()
+{
+ if (m_timeline->m_document->view())
+ m_timeline->m_document->view()->scheduleAnimation();
+}
+
+double DocumentTimeline::currentTime()
+{
+ return m_document->animationClock().currentTime() - m_zeroTime;
}
void DocumentTimeline::pauseAnimationsForTesting(double pauseTime)
{
for (size_t i = 0; i < m_players.size(); i++) {
- m_players[i]->setPaused(true);
+ m_players[i]->pauseForTesting();
m_players[i]->setCurrentTime(pauseTime);
}
}
@@ -107,11 +155,33 @@ void DocumentTimeline::dispatchEvents()
events[i].target->dispatchEvent(events[i].event.release());
}
+void DocumentTimeline::dispatchEventsAsync()
+{
+ if (m_events.isEmpty() || m_eventDistpachTimer.isActive())
+ return;
+ m_eventDistpachTimer.startOneShot(0);
+}
+
+void DocumentTimeline::eventDispatchTimerFired(Timer<DocumentTimeline>*)
+{
+ dispatchEvents();
+}
+
size_t DocumentTimeline::numberOfActiveAnimationsForTesting() const
{
+ if (isNull(m_zeroTime))
+ return 0;
// Includes all players whose directly associated timed items
// are current or in effect.
- return isNull(m_currentTime) ? 0 : m_players.size();
+ if (isNull(m_zeroTime))
+ return 0;
+ size_t count = 0;
+ for (size_t i = 0; i < m_players.size(); ++i) {
+ const TimedItem* timedItem = m_players[i]->source();
+ if (m_players[i]->hasStartTime())
+ count += (timedItem && (timedItem->isCurrent() || timedItem->isInEffect()));
+ }
+ return count;
}
} // namespace
diff --git a/chromium/third_party/WebKit/Source/core/animation/DocumentTimeline.h b/chromium/third_party/WebKit/Source/core/animation/DocumentTimeline.h
index 56c4c388028..2bf58f852c6 100644
--- a/chromium/third_party/WebKit/Source/core/animation/DocumentTimeline.h
+++ b/chromium/third_party/WebKit/Source/core/animation/DocumentTimeline.h
@@ -31,10 +31,11 @@
#ifndef DocumentTimeline_h
#define DocumentTimeline_h
-#include "core/animation/ActiveAnimations.h"
+#include "core/animation/AnimationEffect.h"
#include "core/animation/Player.h"
#include "core/dom/Element.h"
-#include "core/dom/Event.h"
+#include "core/events/Event.h"
+#include "platform/Timer.h"
#include "wtf/RefCounted.h"
#include "wtf/RefPtr.h"
#include "wtf/Vector.h"
@@ -46,36 +47,56 @@ class TimedItem;
// DocumentTimeline is constructed and owned by Document, and tied to its lifecycle.
class DocumentTimeline : public RefCounted<DocumentTimeline> {
-
public:
- static PassRefPtr<DocumentTimeline> create(Document*);
- void serviceAnimations(double);
- PassRefPtr<Player> play(TimedItem*);
- // Called from setReadyState() in Document.cpp to set m_zeroTimeAsPerfTime to
- // performance.timing.domInteractive.
- void setZeroTimeAsPerfTime(double);
- double currentTime() { return m_currentTime; }
+ class PlatformTiming {
+
+ public:
+ // Calls DocumentTimeline's wake() method after duration seconds.
+ virtual void wakeAfter(double duration) = 0;
+ virtual void cancelWake() = 0;
+ virtual void serviceOnNextFrame() = 0;
+ virtual ~PlatformTiming() { }
+
+ };
+
+ static PassRefPtr<DocumentTimeline> create(Document*, PassOwnPtr<PlatformTiming> = nullptr);
+ // Returns whether style recalc was triggered.
+ bool serviceAnimations();
+
+ // Creates a player attached to this timeline, but without a start time.
+ Player* createPlayer(TimedItem*);
+ Player* play(TimedItem*);
+
+ // Called from setReadyState() in Document.cpp to set m_zeroTime to
+ // performance.timing.domInteractive
+ void setZeroTime(double);
+ bool hasStarted() const { return !isNull(m_zeroTime); }
+ double zeroTime() const { return m_zeroTime; }
+ double currentTime();
void pauseAnimationsForTesting(double);
size_t numberOfActiveAnimationsForTesting() const;
- AnimationStack* animationStack(const Element* element) const
- {
- if (ActiveAnimations* animations = element->activeAnimations())
- return animations->defaultStack();
- return 0;
- }
+ const Vector<RefPtr<Player> >& players() const { return m_players; }
+
void addEventToDispatch(EventTarget* target, PassRefPtr<Event> event)
{
m_events.append(EventToDispatch(target, event));
}
-private:
- DocumentTimeline(Document*);
void dispatchEvents();
- double m_currentTime;
- double m_zeroTimeAsPerfTime;
+ void dispatchEventsAsync();
+
+protected:
+ DocumentTimeline(Document*, PassOwnPtr<PlatformTiming>);
+
+private:
+ double m_zeroTime;
Document* m_document;
+ Timer<DocumentTimeline> m_eventDistpachTimer;
Vector<RefPtr<Player> > m_players;
+ void eventDispatchTimerFired(Timer<DocumentTimeline>*);
+ void wake();
+
struct EventToDispatch {
EventToDispatch(EventTarget* target, PassRefPtr<Event> event)
: target(target)
@@ -86,6 +107,33 @@ private:
RefPtr<Event> event;
};
Vector<EventToDispatch> m_events;
+
+ static const double s_minimumDelay;
+
+ OwnPtr<PlatformTiming> m_timing;
+
+ class DocumentTimelineTiming : public PlatformTiming {
+ public:
+ DocumentTimelineTiming(DocumentTimeline* documentTimeline)
+ : m_timeline(documentTimeline)
+ , m_timer(this, &DocumentTimelineTiming::timerFired)
+ {
+ ASSERT(m_timeline);
+ }
+
+ virtual void wakeAfter(double duration) OVERRIDE;
+ virtual void cancelWake() OVERRIDE;
+ virtual void serviceOnNextFrame() OVERRIDE;
+
+ void timerFired(Timer<DocumentTimelineTiming>*) { m_timeline->wake(); }
+
+ private:
+ DocumentTimeline* m_timeline;
+ Timer<DocumentTimelineTiming> m_timer;
+
+ };
+
+ friend class AnimationDocumentTimelineTest;
};
} // namespace
diff --git a/chromium/third_party/WebKit/Source/core/animation/DocumentTimelineTest.cpp b/chromium/third_party/WebKit/Source/core/animation/DocumentTimelineTest.cpp
index 9c2bf18eef1..41fad8ce2c4 100644
--- a/chromium/third_party/WebKit/Source/core/animation/DocumentTimelineTest.cpp
+++ b/chromium/third_party/WebKit/Source/core/animation/DocumentTimelineTest.cpp
@@ -32,82 +32,188 @@
#include "core/animation/DocumentTimeline.h"
#include "core/animation/Animation.h"
+#include "core/animation/AnimationClock.h"
#include "core/animation/KeyframeAnimationEffect.h"
#include "core/animation/TimedItem.h"
#include "core/dom/Document.h"
#include "core/dom/Element.h"
#include "core/dom/QualifiedName.h"
-#include "weborigin/KURL.h"
+#include "platform/weborigin/KURL.h"
+
+#include <gmock/gmock.h>
#include <gtest/gtest.h>
-using namespace WebCore;
+namespace WebCore {
+
+class MockPlatformTiming : public DocumentTimeline::PlatformTiming {
+public:
+
+ MOCK_METHOD1(wakeAfter, void(double));
+ MOCK_METHOD0(cancelWake, void());
+ MOCK_METHOD0(serviceOnNextFrame, void());
+
+ /**
+ * DocumentTimelines should do one of the following things after servicing animations:
+ * - cancel the timer and not request to be woken again (expectNoMoreActions)
+ * - cancel the timer and request to be woken on the next frame (expectNextFrameAction)
+ * - cancel the timer and request to be woken at some point in the future (expectDelayedAction)
+ */
+
+ void expectNoMoreActions()
+ {
+ EXPECT_CALL(*this, cancelWake());
+ }
+
+ void expectNextFrameAction()
+ {
+ ::testing::Sequence sequence;
+ EXPECT_CALL(*this, cancelWake()).InSequence(sequence);
+ EXPECT_CALL(*this, serviceOnNextFrame()).InSequence(sequence);
+ }
-namespace {
+ void expectDelayedAction(double when)
+ {
+ ::testing::Sequence sequence;
+ EXPECT_CALL(*this, cancelWake()).InSequence(sequence);
+ EXPECT_CALL(*this, wakeAfter(when)).InSequence(sequence);
+ }
+};
-class DocumentTimelineTest : public ::testing::Test {
+class AnimationDocumentTimelineTest : public ::testing::Test {
protected:
virtual void SetUp()
{
document = Document::create();
+ document->animationClock().resetTimeForTesting();
element = Element::create(nullQName() , document.get());
- timeline = DocumentTimeline::create(document.get());
- timeline->setZeroTimeAsPerfTime(0);
+ platformTiming = new MockPlatformTiming;
+ timeline = DocumentTimeline::create(document.get(), adoptPtr(platformTiming));
+ timeline->setZeroTime(0);
ASSERT_EQ(0, timeline->currentTime());
}
+ virtual void TearDown()
+ {
+ timeline.release();
+ document.release();
+ element.release();
+ }
+
+ void updateClockAndService(double time)
+ {
+ document->animationClock().updateTime(time);
+ timeline->serviceAnimations();
+ }
+
RefPtr<Document> document;
RefPtr<Element> element;
RefPtr<DocumentTimeline> timeline;
Timing timing;
+ MockPlatformTiming* platformTiming;
+
+ void wake()
+ {
+ timeline->wake();
+ }
+
+ double minimumDelay()
+ {
+ return DocumentTimeline::s_minimumDelay;
+ }
};
-TEST_F(DocumentTimelineTest, EmptyKeyframeAnimation)
+TEST_F(AnimationDocumentTimelineTest, HasStarted)
+{
+ timeline = DocumentTimeline::create(document.get());
+ EXPECT_FALSE(timeline->hasStarted());
+ timeline->setZeroTime(0);
+ EXPECT_TRUE(timeline->hasStarted());
+}
+
+TEST_F(AnimationDocumentTimelineTest, EmptyKeyframeAnimation)
{
RefPtr<KeyframeAnimationEffect> effect = KeyframeAnimationEffect::create(KeyframeAnimationEffect::KeyframeVector());
RefPtr<Animation> anim = Animation::create(element.get(), effect, timing);
timeline->play(anim.get());
- timeline->serviceAnimations(0);
+ platformTiming->expectNoMoreActions();
+ updateClockAndService(0);
EXPECT_FLOAT_EQ(0, timeline->currentTime());
EXPECT_TRUE(anim->compositableValues()->isEmpty());
- timeline->serviceAnimations(100);
+ platformTiming->expectNoMoreActions();
+ updateClockAndService(100);
EXPECT_FLOAT_EQ(100, timeline->currentTime());
}
-TEST_F(DocumentTimelineTest, ZeroTimeAsPerfTime)
+TEST_F(AnimationDocumentTimelineTest, EmptyTimelineDoesNotTriggerStyleRecalc)
+{
+ document->animationClock().updateTime(100);
+ EXPECT_FALSE(timeline->serviceAnimations());
+}
+
+TEST_F(AnimationDocumentTimelineTest, EmptyPlayerDoesNotTriggerStyleRecalc)
+{
+ timeline->play(0);
+ document->animationClock().updateTime(100);
+ EXPECT_FALSE(timeline->serviceAnimations());
+}
+
+TEST_F(AnimationDocumentTimelineTest, EmptyTargetDoesNotTriggerStyleRecalc)
+{
+ timing.iterationDuration = 200;
+ timeline->play(Animation::create(0, KeyframeAnimationEffect::create(KeyframeAnimationEffect::KeyframeVector()), timing).get());
+ document->animationClock().updateTime(100);
+ EXPECT_FALSE(timeline->serviceAnimations());
+}
+
+TEST_F(AnimationDocumentTimelineTest, EmptyEffectDoesNotTriggerStyleRecalc)
+{
+ timeline->play(Animation::create(element.get(), 0, timing).get());
+ document->animationClock().updateTime(100);
+ EXPECT_FALSE(timeline->serviceAnimations());
+}
+
+TEST_F(AnimationDocumentTimelineTest, TriggerStyleRecalc)
+{
+ timeline->play(Animation::create(element.get(), KeyframeAnimationEffect::create(KeyframeAnimationEffect::KeyframeVector()), timing).get());
+ document->animationClock().updateTime(100);
+ EXPECT_TRUE(timeline->serviceAnimations());
+}
+
+TEST_F(AnimationDocumentTimelineTest, ZeroTime)
{
timeline = DocumentTimeline::create(document.get());
- timeline->serviceAnimations(100);
+ document->animationClock().updateTime(100);
EXPECT_TRUE(isNull(timeline->currentTime()));
- timeline->serviceAnimations(200);
+ document->animationClock().updateTime(200);
EXPECT_TRUE(isNull(timeline->currentTime()));
- timeline->setZeroTimeAsPerfTime(300);
- timeline->serviceAnimations(300);
+ timeline->setZeroTime(300);
+ document->animationClock().updateTime(300);
EXPECT_EQ(0, timeline->currentTime());
- timeline->serviceAnimations(400);
+ document->animationClock().updateTime(400);
EXPECT_EQ(100, timeline->currentTime());
}
-TEST_F(DocumentTimelineTest, PauseForTesting)
+TEST_F(AnimationDocumentTimelineTest, PauseForTesting)
{
float seekTime = 1;
RefPtr<Animation> anim1 = Animation::create(element.get(), KeyframeAnimationEffect::create(KeyframeAnimationEffect::KeyframeVector()), timing);
RefPtr<Animation> anim2 = Animation::create(element.get(), KeyframeAnimationEffect::create(KeyframeAnimationEffect::KeyframeVector()), timing);
- RefPtr<Player> player1 = timeline->play(anim1.get());
- RefPtr<Player> player2 = timeline->play(anim2.get());
+ Player* player1 = timeline->play(anim1.get());
+ Player* player2 = timeline->play(anim2.get());
timeline->pauseAnimationsForTesting(seekTime);
EXPECT_FLOAT_EQ(seekTime, player1->currentTime());
EXPECT_FLOAT_EQ(seekTime, player2->currentTime());
}
-TEST_F(DocumentTimelineTest, NumberOfActiveAnimations)
+TEST_F(AnimationDocumentTimelineTest, NumberOfActiveAnimations)
{
Timing timingForwardFill;
timingForwardFill.hasIterationDuration = true;
@@ -135,19 +241,47 @@ TEST_F(DocumentTimelineTest, NumberOfActiveAnimations)
RefPtr<Animation> anim3 = Animation::create(element.get(), KeyframeAnimationEffect::create(KeyframeAnimationEffect::KeyframeVector()), timingBackwardFillDelay);
RefPtr<Animation> anim4 = Animation::create(element.get(), KeyframeAnimationEffect::create(KeyframeAnimationEffect::KeyframeVector()), timingNoFillDelay);
- RefPtr<Player> player1 = timeline->play(anim1.get());
- RefPtr<Player> player2 = timeline->play(anim2.get());
- RefPtr<Player> player3 = timeline->play(anim3.get());
- RefPtr<Player> player4 = timeline->play(anim4.get());
+ timeline->play(anim1.get());
+ timeline->play(anim2.get());
+ timeline->play(anim3.get());
+ timeline->play(anim4.get());
- timeline->serviceAnimations(0);
+ platformTiming->expectNextFrameAction();
+ updateClockAndService(0);
EXPECT_EQ(4U, timeline->numberOfActiveAnimationsForTesting());
- timeline->serviceAnimations(0.5);
+ platformTiming->expectNextFrameAction();
+ updateClockAndService(0.5);
EXPECT_EQ(4U, timeline->numberOfActiveAnimationsForTesting());
- timeline->serviceAnimations(1.5);
+ platformTiming->expectNextFrameAction();
+ updateClockAndService(1.5);
EXPECT_EQ(4U, timeline->numberOfActiveAnimationsForTesting());
- timeline->serviceAnimations(3);
+ platformTiming->expectNoMoreActions();
+ updateClockAndService(3);
EXPECT_EQ(1U, timeline->numberOfActiveAnimationsForTesting());
}
+TEST_F(AnimationDocumentTimelineTest, DelayBeforeAnimationStart)
+{
+ timing.hasIterationDuration = true;
+ timing.iterationDuration = 2;
+ timing.startDelay = 5;
+
+ RefPtr<Animation> anim = Animation::create(element.get(), 0, timing);
+
+ timeline->play(anim.get());
+
+ // TODO: Put the player startTime in the future when we add the capability to change player startTime
+ platformTiming->expectDelayedAction(timing.startDelay - minimumDelay());
+ updateClockAndService(0);
+
+ platformTiming->expectDelayedAction(timing.startDelay - minimumDelay() - 1.5);
+ updateClockAndService(1.5);
+
+ EXPECT_CALL(*platformTiming, serviceOnNextFrame());
+ wake();
+
+ platformTiming->expectNextFrameAction();
+ updateClockAndService(4.98);
+}
+
}
diff --git a/chromium/third_party/WebKit/Source/core/animation/ElementAnimation.cpp b/chromium/third_party/WebKit/Source/core/animation/ElementAnimation.cpp
new file mode 100644
index 00000000000..0beb346f7d6
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/animation/ElementAnimation.cpp
@@ -0,0 +1,142 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/animation/ElementAnimation.h"
+
+#include "core/animation/DocumentTimeline.h"
+#include "core/css/RuntimeCSSEnabled.h"
+#include "core/css/resolver/StyleResolver.h"
+#include "wtf/text/StringBuilder.h"
+#include <algorithm>
+
+namespace WebCore {
+
+CSSPropertyID ElementAnimation::camelCaseCSSPropertyNameToID(const String& propertyName)
+{
+ if (propertyName.find('-') != kNotFound)
+ return CSSPropertyInvalid;
+
+ StringBuilder builder;
+ size_t position = 0;
+ size_t end;
+ while ((end = propertyName.find(isASCIIUpper, position)) != kNotFound) {
+ builder.append(propertyName.substring(position, end - position) + "-" + toASCIILower((propertyName)[end]));
+ position = end + 1;
+ }
+ builder.append(propertyName.substring(position));
+ // Doesn't handle prefixed properties.
+ CSSPropertyID id = cssPropertyID(builder.toString());
+ return id;
+}
+
+void ElementAnimation::animate(Element* element, Vector<Dictionary> keyframeDictionaryVector, double duration)
+{
+ ASSERT(RuntimeEnabledFeatures::webAnimationsAPIEnabled());
+
+ // FIXME: This test will not be neccessary once resolution of keyframe values occurs at
+ // animation application time.
+ if (!element->inActiveDocument())
+ return;
+ element->document().updateStyleIfNeeded();
+ if (!element->renderer())
+ return;
+
+ startAnimation(element, keyframeDictionaryVector, duration);
+}
+
+void ElementAnimation::startAnimation(Element* element, Vector<Dictionary> keyframeDictionaryVector, double duration)
+{
+ KeyframeAnimationEffect::KeyframeVector keyframes;
+ Vector<RefPtr<MutableStylePropertySet> > propertySetVector;
+
+ for (size_t i = 0; i < keyframeDictionaryVector.size(); ++i) {
+ RefPtr<MutableStylePropertySet> propertySet = MutableStylePropertySet::create();
+ propertySetVector.append(propertySet);
+
+ RefPtr<Keyframe> keyframe = Keyframe::create();
+ keyframes.append(keyframe);
+
+ double offset;
+ if (keyframeDictionaryVector[i].get("offset", offset)) {
+ keyframe->setOffset(offset);
+ } else {
+ // FIXME: Web Animations CSS engine does not yet implement handling of
+ // keyframes without specified offsets. This check can be removed when
+ // that funcitonality is implemented.
+ ASSERT_NOT_REACHED();
+ return;
+ }
+
+ String compositeString;
+ keyframeDictionaryVector[i].get("composite", compositeString);
+ if (compositeString == "add")
+ keyframe->setComposite(AnimationEffect::CompositeAdd);
+
+ Vector<String> keyframeProperties;
+ keyframeDictionaryVector[i].getOwnPropertyNames(keyframeProperties);
+
+ for (size_t j = 0; j < keyframeProperties.size(); ++j) {
+ String property = keyframeProperties[j];
+ CSSPropertyID id = camelCaseCSSPropertyNameToID(property);
+
+ // FIXME: There is no way to store invalid properties or invalid values
+ // in a Keyframe object, so for now I just skip over them. Eventually we
+ // will need to support getFrames(), which should return exactly the
+ // keyframes that were input through the API. We will add a layer to wrap
+ // KeyframeAnimationEffect, store input keyframes and implement getFrames.
+ if (id == CSSPropertyInvalid || !CSSAnimations::isAnimatableProperty(id))
+ continue;
+
+ String value;
+ keyframeDictionaryVector[i].get(property, value);
+ propertySet->setProperty(id, value);
+ }
+ }
+
+ // FIXME: Replace this with code that just parses, when that code is available.
+ RefPtr<KeyframeAnimationEffect> effect = StyleResolver::createKeyframeAnimationEffect(*element, propertySetVector, keyframes);
+
+ // FIXME: Totally hardcoded Timing for now. Will handle timing parameters later.
+ Timing timing;
+ // FIXME: Currently there is no way to tell whether or not an iterationDuration
+ // has been specified (becauser the default argument is 0). So any animation
+ // created using Element.animate() will have a timing with hasIterationDuration()
+ // == true.
+ timing.hasIterationDuration = true;
+ timing.iterationDuration = std::max<double>(duration, 0);
+
+ RefPtr<Animation> animation = Animation::create(element, effect, timing);
+ DocumentTimeline* timeline = element->document().timeline();
+ ASSERT(timeline);
+ timeline->play(animation.get());
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/animation/ElementAnimation.h b/chromium/third_party/WebKit/Source/core/animation/ElementAnimation.h
new file mode 100644
index 00000000000..cfc8f6999fa
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/animation/ElementAnimation.h
@@ -0,0 +1,54 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef ElementAnimation_h
+#define ElementAnimation_h
+
+#include "bindings/v8/Dictionary.h"
+#include "core/css/CSSParser.h"
+
+namespace WebCore {
+
+class Element;
+
+class ElementAnimation {
+public:
+ static CSSPropertyID camelCaseCSSPropertyNameToID(const String& propertyName);
+ static void animate(Element*, Vector<Dictionary> keyframesDictionaryVector, double duration = 0);
+
+private:
+ static void startAnimation(Element*, Vector<Dictionary> keyframesDictionaryVector, double duration = 0);
+
+ friend class AnimationElementAnimationTest;
+};
+
+} // namespace WebCore
+
+#endif // ElementAnimation_h
diff --git a/chromium/third_party/WebKit/Source/core/animation/ElementAnimation.idl b/chromium/third_party/WebKit/Source/core/animation/ElementAnimation.idl
new file mode 100644
index 00000000000..e191d950bc0
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/animation/ElementAnimation.idl
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+partial interface Element {
+ [RuntimeEnabled=WebAnimationsAPI] void animate(sequence<Dictionary> keyframes, optional double duration);
+}; \ No newline at end of file
diff --git a/chromium/third_party/WebKit/Source/core/animation/ElementAnimationTest.cpp b/chromium/third_party/WebKit/Source/core/animation/ElementAnimationTest.cpp
new file mode 100644
index 00000000000..bb3f0d4f0ad
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/animation/ElementAnimationTest.cpp
@@ -0,0 +1,208 @@
+/*
+ * Copyright (c) 2013, Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/animation/ElementAnimation.h"
+
+#include "core/animation/AnimatableLength.h"
+#include "core/animation/Animation.h"
+#include "core/animation/AnimationClock.h"
+#include "core/animation/DocumentTimeline.h"
+#include "core/animation/KeyframeAnimationEffect.h"
+#include "core/dom/Document.h"
+#include "core/dom/Element.h"
+
+#include <gtest/gtest.h>
+
+namespace WebCore {
+
+namespace {
+
+v8::Handle<v8::Value> stringToV8Value(String string)
+{
+ return v8::Handle<v8::Value>::Cast(v8String(v8::Isolate::GetCurrent(), string));
+}
+
+void setV8ObjectProperty(v8::Handle<v8::Object> object, String name, String value)
+{
+ object->Set(stringToV8Value(name), stringToV8Value(value));
+}
+
+} // namespace
+
+class AnimationElementAnimationTest : public ::testing::Test {
+protected:
+ virtual void SetUp()
+ {
+ document = Document::create();
+ document->animationClock().resetTimeForTesting();
+ element = document->createElement("foo", ASSERT_NO_EXCEPTION);
+ document->timeline()->setZeroTime(0);
+ ASSERT_EQ(0, document->timeline()->currentTime());
+ }
+
+ RefPtr<Document> document;
+ RefPtr<Element> element;
+
+ void startAnimation(Element* element, Vector<Dictionary> keyframesDictionaryVector)
+ {
+ ElementAnimation::startAnimation(element, keyframesDictionaryVector);
+ }
+
+ void startAnimationWithSpecifiedDuration(Element* element, Vector<Dictionary> keyframesDictionaryVector, double duration)
+ {
+ ElementAnimation::startAnimation(element, keyframesDictionaryVector, duration);
+ }
+};
+
+TEST_F(AnimationElementAnimationTest, CanStartAnAnimation)
+{
+ v8::Isolate* isolate = v8::Isolate::GetCurrent();
+ v8::HandleScope scope(isolate);
+ v8::Local<v8::Context> context = v8::Context::New(isolate);
+ v8::Context::Scope contextScope(context);
+
+ Vector<Dictionary> jsKeyframes;
+ v8::Handle<v8::Object> keyframe1 = v8::Object::New();
+ v8::Handle<v8::Object> keyframe2 = v8::Object::New();
+
+ setV8ObjectProperty(keyframe1, "width", "100px");
+ setV8ObjectProperty(keyframe1, "offset", "0");
+ setV8ObjectProperty(keyframe2, "width", "0px");
+ setV8ObjectProperty(keyframe2, "offset", "1");
+
+ jsKeyframes.append(Dictionary(keyframe1, isolate));
+ jsKeyframes.append(Dictionary(keyframe2, isolate));
+
+ String value1;
+ ASSERT_TRUE(jsKeyframes[0].get("width", value1));
+ ASSERT_EQ("100px", value1);
+
+ String value2;
+ ASSERT_TRUE(jsKeyframes[1].get("width", value2));
+ ASSERT_EQ("0px", value2);
+
+ startAnimationWithSpecifiedDuration(element.get(), jsKeyframes, 0);
+
+ Player* player = document->timeline()->players().at(0).get();
+
+ Animation* animation = toAnimation(player->source());
+
+ Element* target = animation->target();
+ EXPECT_EQ(*element.get(), *target);
+
+ const KeyframeAnimationEffect::KeyframeVector keyframes =
+ toKeyframeAnimationEffect(animation->effect())->getFrames();
+
+ EXPECT_EQ(0, keyframes[0]->offset());
+ EXPECT_EQ(1, keyframes[1]->offset());
+
+ const AnimatableValue* keyframe1Width = keyframes[0]->propertyValue(CSSPropertyWidth);
+ const AnimatableValue* keyframe2Width = keyframes[1]->propertyValue(CSSPropertyWidth);
+ ASSERT(keyframe1Width);
+ ASSERT(keyframe2Width);
+
+ EXPECT_TRUE(keyframe1Width->isLength());
+ EXPECT_TRUE(keyframe2Width->isLength());
+
+ EXPECT_EQ("100px", toAnimatableLength(keyframe1Width)->toCSSValue()->cssText());
+ EXPECT_EQ("0px", toAnimatableLength(keyframe2Width)->toCSSValue()->cssText());
+}
+
+TEST_F(AnimationElementAnimationTest, ParseCamelCasePropertyNames)
+{
+ EXPECT_EQ(CSSPropertyInvalid, ElementAnimation::camelCaseCSSPropertyNameToID(String("line-height")));
+ EXPECT_EQ(CSSPropertyLineHeight, ElementAnimation::camelCaseCSSPropertyNameToID(String("lineHeight")));
+ EXPECT_EQ(CSSPropertyBorderTopWidth, ElementAnimation::camelCaseCSSPropertyNameToID(String("borderTopWidth")));
+ EXPECT_EQ(CSSPropertyWidth, ElementAnimation::camelCaseCSSPropertyNameToID(String("width")));
+ EXPECT_EQ(CSSPropertyInvalid, ElementAnimation::camelCaseCSSPropertyNameToID(String("Width")));
+ EXPECT_EQ(CSSPropertyInvalid, ElementAnimation::camelCaseCSSPropertyNameToID(String("-webkit-transform")));
+ EXPECT_EQ(CSSPropertyInvalid, ElementAnimation::camelCaseCSSPropertyNameToID(String("webkitTransform")));
+ EXPECT_EQ(CSSPropertyInvalid, ElementAnimation::camelCaseCSSPropertyNameToID(String("cssFloat")));
+}
+
+TEST_F(AnimationElementAnimationTest, CanSetDuration)
+{
+ v8::Isolate* isolate = v8::Isolate::GetCurrent();
+ v8::HandleScope scope(isolate);
+ v8::Local<v8::Context> context = v8::Context::New(isolate);
+ v8::Context::Scope contextScope(context);
+
+ Vector<Dictionary, 0> jsKeyframes;
+ double duration = 2;
+
+ startAnimationWithSpecifiedDuration(element.get(), jsKeyframes, duration);
+
+ Player* player = document->timeline()->players().at(0).get();
+
+ EXPECT_TRUE(player->source()->specified().hasIterationDuration);
+ EXPECT_EQ(duration, player->source()->specified().iterationDuration);
+}
+
+TEST_F(AnimationElementAnimationTest, CanOmitSpecifiedDuration)
+{
+ v8::Isolate* isolate = v8::Isolate::GetCurrent();
+ v8::HandleScope scope(isolate);
+ v8::Local<v8::Context> context = v8::Context::New(isolate);
+ v8::Context::Scope contextScope(context);
+
+ Vector<Dictionary, 0> jsKeyframes;
+
+ startAnimation(element.get(), jsKeyframes);
+
+ Player* player = document->timeline()->players().at(0).get();
+
+ // FIXME: This is correct for the moment, as using c++ default arguments means
+ // there is no way to tell whether a duration has been specified by the user.
+ // Once we implment timing object arguments we should be able to tell, and this
+ // check should be changed to EXPECT_FALSE.
+ EXPECT_TRUE(player->source()->specified().hasIterationDuration);
+ EXPECT_EQ(0, player->source()->specified().iterationDuration);
+}
+
+TEST_F(AnimationElementAnimationTest, ClipNegativeDurationToZero)
+{
+ v8::Isolate* isolate = v8::Isolate::GetCurrent();
+ v8::HandleScope scope(isolate);
+ v8::Local<v8::Context> context = v8::Context::New(isolate);
+ v8::Context::Scope contextScope(context);
+
+ Vector<Dictionary, 0> jsKeyframes;
+ double duration = -2;
+
+ startAnimationWithSpecifiedDuration(element.get(), jsKeyframes, duration);
+
+ Player* player = document->timeline()->players().at(0).get();
+
+ EXPECT_TRUE(player->source()->specified().hasIterationDuration);
+ EXPECT_EQ(0, player->source()->specified().iterationDuration);
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/animation/InertAnimation.cpp b/chromium/third_party/WebKit/Source/core/animation/InertAnimation.cpp
index 8e96e074072..3cb21505300 100644
--- a/chromium/third_party/WebKit/Source/core/animation/InertAnimation.cpp
+++ b/chromium/third_party/WebKit/Source/core/animation/InertAnimation.cpp
@@ -33,21 +33,34 @@
namespace WebCore {
-PassRefPtr<InertAnimation> InertAnimation::create(PassRefPtr<AnimationEffect> effect, const Timing& timing)
+PassRefPtr<InertAnimation> InertAnimation::create(PassRefPtr<AnimationEffect> effect, const Timing& timing, bool paused)
{
- return adoptRef(new InertAnimation(effect, timing));
+ return adoptRef(new InertAnimation(effect, timing, paused));
}
-InertAnimation::InertAnimation(PassRefPtr<AnimationEffect> effect, const Timing& timing)
+InertAnimation::InertAnimation(PassRefPtr<AnimationEffect> effect, const Timing& timing, bool paused)
: TimedItem(timing)
, m_effect(effect)
+ , m_paused(paused)
{
}
-PassOwnPtr<AnimationEffect::CompositableValueMap> InertAnimation::sample()
+PassOwnPtr<AnimationEffect::CompositableValueList> InertAnimation::sample()
{
updateInheritedTime(0);
- return isInEffect() ? m_effect->sample(currentIteration(), timeFraction()) : nullptr;
+ if (!isInEffect())
+ return nullptr;
+
+ double iteration = currentIteration();
+ ASSERT(iteration >= 0);
+ // FIXME: Handle iteration values which overflow int.
+ return m_effect->sample(static_cast<int>(iteration), timeFraction());
+}
+
+
+double InertAnimation::calculateTimeToEffectChange(double, double) const
+{
+ return std::numeric_limits<double>::infinity();
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/animation/InertAnimation.h b/chromium/third_party/WebKit/Source/core/animation/InertAnimation.h
index e6cd2ea7c37..a52ba532ec6 100644
--- a/chromium/third_party/WebKit/Source/core/animation/InertAnimation.h
+++ b/chromium/third_party/WebKit/Source/core/animation/InertAnimation.h
@@ -40,17 +40,20 @@ namespace WebCore {
class InertAnimation FINAL : public TimedItem {
public:
- static PassRefPtr<InertAnimation> create(PassRefPtr<AnimationEffect>, const Timing&);
- PassOwnPtr<AnimationEffect::CompositableValueMap> sample();
- AnimationEffect* effect() { return m_effect.get(); }
+ static PassRefPtr<InertAnimation> create(PassRefPtr<AnimationEffect>, const Timing&, bool paused);
+ PassOwnPtr<AnimationEffect::CompositableValueList> sample();
+ AnimationEffect* effect() const { return m_effect.get(); }
+ bool paused() const { return m_paused; }
protected:
- virtual void updateChildrenAndEffects(bool) const OVERRIDE { };
+ virtual bool updateChildrenAndEffects() const OVERRIDE { return false; };
virtual void willDetach() OVERRIDE { };
+ virtual double calculateTimeToEffectChange(double inheritedTime, double timeToNextIteration) const OVERRIDE FINAL;
private:
- InertAnimation(PassRefPtr<AnimationEffect>, const Timing&);
+ InertAnimation(PassRefPtr<AnimationEffect>, const Timing&, bool paused);
RefPtr<AnimationEffect> m_effect;
+ bool m_paused;
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/animation/KeyframeAnimationEffect.cpp b/chromium/third_party/WebKit/Source/core/animation/KeyframeAnimationEffect.cpp
index 7c708314da6..dd6ffa3a832 100644
--- a/chromium/third_party/WebKit/Source/core/animation/KeyframeAnimationEffect.cpp
+++ b/chromium/third_party/WebKit/Source/core/animation/KeyframeAnimationEffect.cpp
@@ -31,7 +31,7 @@
#include "config.h"
#include "core/animation/KeyframeAnimationEffect.h"
-#include "wtf/MathExtras.h"
+#include "core/animation/TimedItem.h"
#include "wtf/text/StringHash.h"
namespace {
@@ -115,15 +115,28 @@ private:
namespace WebCore {
Keyframe::Keyframe()
- : m_offset(std::numeric_limits<double>::quiet_NaN())
+ : m_offset(nullValue())
, m_composite(AnimationEffect::CompositeReplace)
{ }
+Keyframe::Keyframe(const Keyframe& copyFrom)
+ : m_offset(copyFrom.m_offset)
+ , m_composite(copyFrom.m_composite)
+{
+ for (PropertyValueMap::const_iterator iter = copyFrom.m_propertyValues.begin(); iter != copyFrom.m_propertyValues.end(); ++iter)
+ setPropertyValue(iter->key, iter->value.get());
+}
+
void Keyframe::setPropertyValue(CSSPropertyID property, const AnimatableValue* value)
{
m_propertyValues.add(property, const_cast<AnimatableValue*>(value));
}
+void Keyframe::clearPropertyValue(CSSPropertyID property)
+{
+ m_propertyValues.remove(property);
+}
+
const AnimatableValue* Keyframe::propertyValue(CSSPropertyID property) const
{
ASSERT(m_propertyValues.contains(property));
@@ -132,8 +145,8 @@ const AnimatableValue* Keyframe::propertyValue(CSSPropertyID property) const
PropertySet Keyframe::properties() const
{
- // This is only used when setting up the keyframe groups, so there's no
- // need to cache the result.
+ // This is not used in time-critical code, so we probably don't need to
+ // worry about caching this result.
PropertySet properties;
for (PropertyValueMap::const_iterator iter = m_propertyValues.begin(); iter != m_propertyValues.end(); ++iter)
properties.add(*iter.keys());
@@ -142,26 +155,41 @@ PropertySet Keyframe::properties() const
PassRefPtr<Keyframe> Keyframe::cloneWithOffset(double offset) const
{
- RefPtr<Keyframe> clone = Keyframe::create();
- clone->setOffset(offset);
- clone->setComposite(m_composite);
- for (PropertyValueMap::const_iterator iter = m_propertyValues.begin(); iter != m_propertyValues.end(); ++iter)
- clone->setPropertyValue(iter->key, iter->value.get());
- return clone.release();
+ RefPtr<Keyframe> theClone = clone();
+ theClone->setOffset(offset);
+ return theClone.release();
}
-
KeyframeAnimationEffect::KeyframeAnimationEffect(const KeyframeVector& keyframes)
: m_keyframes(keyframes)
{
}
-PassOwnPtr<AnimationEffect::CompositableValueMap> KeyframeAnimationEffect::sample(int iteration, double fraction) const
+PropertySet KeyframeAnimationEffect::properties() const
{
+ PropertySet result;
+ const KeyframeVector& frames = getFrames();
+ if (!frames.size()) {
+ return result;
+ }
+ result = frames[0]->properties();
+ for (size_t i = 1; i < frames.size(); i++) {
+ PropertySet extras = frames[i]->properties();
+ for (PropertySet::const_iterator it = extras.begin(); it != extras.end(); ++it) {
+ result.add(*it);
+ }
+ }
+ return result;
+}
+
+PassOwnPtr<AnimationEffect::CompositableValueList> KeyframeAnimationEffect::sample(int iteration, double fraction) const
+{
+ ASSERT(iteration >= 0);
+ ASSERT(!isNull(fraction));
const_cast<KeyframeAnimationEffect*>(this)->ensureKeyframeGroups();
- OwnPtr<CompositableValueMap> map = adoptPtr(new CompositableValueMap());
+ OwnPtr<CompositableValueList> map = adoptPtr(new CompositableValueList());
for (KeyframeGroupMap::const_iterator iter = m_keyframeGroups->begin(); iter != m_keyframeGroups->end(); ++iter)
- map->add(iter->key, iter->value->sample(iteration, fraction));
+ map->append(std::make_pair(iter->key, iter->value->sample(iteration, fraction)));
return map.release();
}
@@ -172,25 +200,25 @@ KeyframeAnimationEffect::KeyframeVector KeyframeAnimationEffect::normalizedKeyfr
// Set offsets at 0.0 and 1.0 at ends if unset.
if (keyframes.size() >= 2) {
Keyframe* firstKeyframe = keyframes.first().get();
- if (std::isnan(firstKeyframe->offset()))
+ if (isNull(firstKeyframe->offset()))
firstKeyframe->setOffset(0.0);
}
if (keyframes.size() >= 1) {
Keyframe* lastKeyframe = keyframes.last().get();
- if (lastKeyframe && std::isnan(lastKeyframe->offset()))
+ if (lastKeyframe && isNull(lastKeyframe->offset()))
lastKeyframe->setOffset(1.0);
}
// FIXME: Distribute offsets where missing.
for (KeyframeVector::iterator iter = keyframes.begin(); iter != keyframes.end(); ++iter)
- ASSERT(!std::isnan((*iter)->offset()));
+ ASSERT(!isNull((*iter)->offset()));
// Sort by offset.
std::stable_sort(keyframes.begin(), keyframes.end(), Keyframe::compareOffsets);
return keyframes;
}
-void KeyframeAnimationEffect::ensureKeyframeGroups()
+void KeyframeAnimationEffect::ensureKeyframeGroups() const
{
if (m_keyframeGroups)
return;
@@ -233,7 +261,7 @@ KeyframeAnimationEffect::PropertySpecificKeyframe::PropertySpecificKeyframe(doub
: m_offset(offset)
, m_value(value)
{
- ASSERT(!std::isnan(m_offset));
+ ASSERT(!isNull(m_offset));
}
PassOwnPtr<KeyframeAnimationEffect::PropertySpecificKeyframe> KeyframeAnimationEffect::PropertySpecificKeyframe::cloneWithOffset(double offset) const
@@ -260,7 +288,7 @@ void KeyframeAnimationEffect::PropertySpecificKeyframeGroup::removeRedundantKeyf
for (int i = m_keyframes.size() - 1; i >= 0; --i) {
double offset = m_keyframes[i]->offset();
bool hasSameOffsetAsPreviousNeighbor = !i || m_keyframes[i - 1]->offset() == offset;
- bool hasSameOffsetAsNextNeighbor = i == m_keyframes.size() - 1 || m_keyframes[i + 1]->offset() == offset;
+ bool hasSameOffsetAsNextNeighbor = i == static_cast<int>(m_keyframes.size() - 1) || m_keyframes[i + 1]->offset() == offset;
if (hasSameOffsetAsPreviousNeighbor && hasSameOffsetAsNextNeighbor)
m_keyframes.remove(i);
}
@@ -291,6 +319,11 @@ PassRefPtr<AnimationEffect::CompositableValue> KeyframeAnimationEffect::Property
{
// FIXME: Implement accumulation.
ASSERT_UNUSED(iteration, iteration >= 0);
+ ASSERT(!isNull(offset));
+
+ // Bail if offset is null, as this can lead to buffer overflow below.
+ if (isNull(offset))
+ return const_cast<CompositableValue*>(m_keyframes.first()->value());
double minimumOffset = m_keyframes.first()->offset();
double maximumOffset = m_keyframes.last()->offset();
diff --git a/chromium/third_party/WebKit/Source/core/animation/KeyframeAnimationEffect.h b/chromium/third_party/WebKit/Source/core/animation/KeyframeAnimationEffect.h
index d826c1d2843..ee784299dc4 100644
--- a/chromium/third_party/WebKit/Source/core/animation/KeyframeAnimationEffect.h
+++ b/chromium/third_party/WebKit/Source/core/animation/KeyframeAnimationEffect.h
@@ -60,11 +60,14 @@ public:
void setComposite(AnimationEffect::CompositeOperation composite) { m_composite = composite; }
AnimationEffect::CompositeOperation composite() const { return m_composite; }
void setPropertyValue(CSSPropertyID, const AnimatableValue*);
+ void clearPropertyValue(CSSPropertyID);
const AnimatableValue* propertyValue(CSSPropertyID) const;
PropertySet properties() const;
+ PassRefPtr<Keyframe> clone() const { return adoptRef(new Keyframe(*this)); }
PassRefPtr<Keyframe> cloneWithOffset(double offset) const;
private:
Keyframe();
+ Keyframe(const Keyframe&);
double m_offset;
AnimationEffect::CompositeOperation m_composite;
typedef HashMap<CSSPropertyID, RefPtr<AnimatableValue> > PropertyValueMap;
@@ -73,20 +76,31 @@ private:
class KeyframeAnimationEffect : public AnimationEffect {
public:
+ class PropertySpecificKeyframe;
typedef Vector<RefPtr<Keyframe> > KeyframeVector;
+ typedef Vector<OwnPtr<KeyframeAnimationEffect::PropertySpecificKeyframe> > PropertySpecificKeyframeVector;
// FIXME: Implement accumulation.
static PassRefPtr<KeyframeAnimationEffect> create(const KeyframeVector& keyframes)
{
return adoptRef(new KeyframeAnimationEffect(keyframes));
}
+ virtual bool affects(CSSPropertyID property) OVERRIDE
+ {
+ ensureKeyframeGroups();
+ return m_keyframeGroups->contains(property);
+ }
+
// AnimationEffect implementation.
- virtual PassOwnPtr<CompositableValueMap> sample(int iteration, double fraction) const OVERRIDE;
+ virtual PassOwnPtr<CompositableValueList> sample(int iteration, double fraction) const OVERRIDE;
// FIXME: Implement setFrames()
const KeyframeVector& getFrames() const { return m_keyframes; }
-private:
+ virtual bool isKeyframeAnimationEffect() const OVERRIDE { return true; }
+
+ PropertySet properties() const;
+
class PropertySpecificKeyframe {
public:
PropertySpecificKeyframe(double offset, const AnimatableValue*, CompositeOperation);
@@ -103,28 +117,39 @@ private:
class PropertySpecificKeyframeGroup {
public:
void appendKeyframe(PassOwnPtr<PropertySpecificKeyframe>);
- void removeRedundantKeyframes();
- void addSyntheticKeyframeIfRequired();
PassRefPtr<CompositableValue> sample(int iteration, double offset) const;
+ const PropertySpecificKeyframeVector& keyframes() const { return m_keyframes; }
private:
- typedef Vector<OwnPtr<PropertySpecificKeyframe> > PropertySpecificKeyframeVector;
PropertySpecificKeyframeVector m_keyframes;
+ void removeRedundantKeyframes();
+ void addSyntheticKeyframeIfRequired();
+
+ friend class KeyframeAnimationEffect;
};
+ const PropertySpecificKeyframeVector& getPropertySpecificKeyframes(CSSPropertyID id) const
+ {
+ ensureKeyframeGroups();
+ return m_keyframeGroups->get(id)->keyframes();
+ }
+
+private:
KeyframeAnimationEffect(const KeyframeVector& keyframes);
KeyframeVector normalizedKeyframes() const;
// Lazily computes the groups of property-specific keyframes.
- void ensureKeyframeGroups();
+ void ensureKeyframeGroups() const;
KeyframeVector m_keyframes;
// The spec describes filtering the normalized keyframes at sampling time
// to get the 'property-specific keyframes'. For efficiency, we cache the
// property-specific lists.
typedef HashMap<CSSPropertyID, OwnPtr<PropertySpecificKeyframeGroup> > KeyframeGroupMap;
- OwnPtr<KeyframeGroupMap> m_keyframeGroups;
+ mutable OwnPtr<KeyframeGroupMap> m_keyframeGroups;
};
+DEFINE_TYPE_CASTS(KeyframeAnimationEffect, AnimationEffect, value, value->isKeyframeAnimationEffect(), value.isKeyframeAnimationEffect());
+
} // namespace WebCore
#endif // KeyframeAnimationEffect_h
diff --git a/chromium/third_party/WebKit/Source/core/animation/KeyframeAnimationEffectTest.cpp b/chromium/third_party/WebKit/Source/core/animation/KeyframeAnimationEffectTest.cpp
index 03787a51798..4a493bd4f27 100644
--- a/chromium/third_party/WebKit/Source/core/animation/KeyframeAnimationEffectTest.cpp
+++ b/chromium/third_party/WebKit/Source/core/animation/KeyframeAnimationEffectTest.cpp
@@ -31,7 +31,7 @@
#include "config.h"
#include "core/animation/KeyframeAnimationEffect.h"
-#include "core/animation/AnimatableNumber.h"
+#include "core/animation/AnimatableLength.h"
#include "core/animation/AnimatableUnknown.h"
#include "core/css/CSSPrimitiveValue.h"
#include <gtest/gtest.h>
@@ -47,7 +47,7 @@ AnimatableValue* unknownAnimatableValue(double n)
AnimatableValue* pixelAnimatableValue(double n)
{
- return AnimatableNumber::create(CSSPrimitiveValue::create(n, CSSPrimitiveValue::CSS_PX).get()).leakRef();
+ return AnimatableLength::create(CSSPrimitiveValue::create(n, CSSPrimitiveValue::CSS_PX).get()).leakRef();
}
KeyframeAnimationEffect::KeyframeVector keyframesAtZeroAndOne(AnimatableValue* zeroValue, AnimatableValue* oneValue)
@@ -64,11 +64,11 @@ KeyframeAnimationEffect::KeyframeVector keyframesAtZeroAndOne(AnimatableValue* z
void expectDoubleValue(double expectedValue, PassRefPtr<AnimatableValue> value)
{
- ASSERT_TRUE(value->isNumber() || value->isUnknown());
+ ASSERT_TRUE(value->isLength() || value->isUnknown());
double actualValue;
- if (value->isNumber())
- actualValue = toCSSPrimitiveValue(toAnimatableNumber(value.get())->toCSSValue().get())->getDoubleValue();
+ if (value->isLength())
+ actualValue = toCSSPrimitiveValue(toAnimatableLength(value.get())->toCSSValue().get())->getDoubleValue();
else
actualValue = toCSSPrimitiveValue(toAnimatableUnknown(value.get())->toCSSValue().get())->getDoubleValue();
@@ -76,77 +76,77 @@ void expectDoubleValue(double expectedValue, PassRefPtr<AnimatableValue> value)
}
-TEST(KeyframeAnimationEffect, BasicOperation)
+TEST(AnimationKeyframeAnimationEffectTest, BasicOperation)
{
KeyframeAnimationEffect::KeyframeVector keyframes = keyframesAtZeroAndOne(unknownAnimatableValue(3.0), unknownAnimatableValue(5.0));
RefPtr<KeyframeAnimationEffect> effect = KeyframeAnimationEffect::create(keyframes);
- OwnPtr<AnimationEffect::CompositableValueMap> values = effect->sample(0, 0.6);
- ASSERT_EQ(1, values->size());
- EXPECT_EQ(CSSPropertyLeft, values->begin()->key);
- expectDoubleValue(5.0, values->begin()->value->compositeOnto(unknownAnimatableValue(7.0)));
+ OwnPtr<AnimationEffect::CompositableValueList> values = effect->sample(0, 0.6);
+ ASSERT_EQ(1UL, values->size());
+ EXPECT_EQ(CSSPropertyLeft, values->at(0).first);
+ expectDoubleValue(5.0, values->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
}
-TEST(KeyframeAnimationEffect, CompositeReplaceNonInterpolable)
+TEST(AnimationKeyframeAnimationEffectTest, CompositeReplaceNonInterpolable)
{
KeyframeAnimationEffect::KeyframeVector keyframes = keyframesAtZeroAndOne(unknownAnimatableValue(3.0), unknownAnimatableValue(5.0));
keyframes[0]->setComposite(AnimationEffect::CompositeReplace);
keyframes[1]->setComposite(AnimationEffect::CompositeReplace);
RefPtr<KeyframeAnimationEffect> effect = KeyframeAnimationEffect::create(keyframes);
- expectDoubleValue(5.0, effect->sample(0, 0.6)->begin()->value->compositeOnto(unknownAnimatableValue(7.0)));
+ expectDoubleValue(5.0, effect->sample(0, 0.6)->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
}
-TEST(KeyframeAnimationEffect, CompositeReplace)
+TEST(AnimationKeyframeAnimationEffectTest, CompositeReplace)
{
KeyframeAnimationEffect::KeyframeVector keyframes = keyframesAtZeroAndOne(pixelAnimatableValue(3.0), pixelAnimatableValue(5.0));
keyframes[0]->setComposite(AnimationEffect::CompositeReplace);
keyframes[1]->setComposite(AnimationEffect::CompositeReplace);
RefPtr<KeyframeAnimationEffect> effect = KeyframeAnimationEffect::create(keyframes);
- expectDoubleValue(3.0 * 0.4 + 5.0 * 0.6, effect->sample(0, 0.6)->begin()->value->compositeOnto(unknownAnimatableValue(7.0)));
+ expectDoubleValue(3.0 * 0.4 + 5.0 * 0.6, effect->sample(0, 0.6)->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
}
-TEST(KeyframeAnimationEffect, CompositeAdd)
+TEST(AnimationKeyframeAnimationEffectTest, CompositeAdd)
{
KeyframeAnimationEffect::KeyframeVector keyframes = keyframesAtZeroAndOne(pixelAnimatableValue(3.0), pixelAnimatableValue(5.0));
keyframes[0]->setComposite(AnimationEffect::CompositeAdd);
keyframes[1]->setComposite(AnimationEffect::CompositeAdd);
RefPtr<KeyframeAnimationEffect> effect = KeyframeAnimationEffect::create(keyframes);
- expectDoubleValue((7.0 + 3.0) * 0.4 + (7.0 + 5.0) * 0.6, effect->sample(0, 0.6)->begin()->value->compositeOnto(pixelAnimatableValue(7.0)));
+ expectDoubleValue((7.0 + 3.0) * 0.4 + (7.0 + 5.0) * 0.6, effect->sample(0, 0.6)->at(0).second->compositeOnto(pixelAnimatableValue(7.0)));
}
-TEST(KeyframeAnimationEffect, ExtrapolateReplaceNonInterpolable)
+TEST(AnimationKeyframeAnimationEffectTest, ExtrapolateReplaceNonInterpolable)
{
KeyframeAnimationEffect::KeyframeVector keyframes = keyframesAtZeroAndOne(unknownAnimatableValue(3.0), unknownAnimatableValue(5.0));
RefPtr<KeyframeAnimationEffect> effect = KeyframeAnimationEffect::create(keyframes);
keyframes[0]->setComposite(AnimationEffect::CompositeReplace);
keyframes[1]->setComposite(AnimationEffect::CompositeReplace);
- expectDoubleValue(5.0, effect->sample(0, 1.6)->begin()->value->compositeOnto(unknownAnimatableValue(7.0)));
+ expectDoubleValue(5.0, effect->sample(0, 1.6)->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
}
-TEST(KeyframeAnimationEffect, ExtrapolateReplace)
+TEST(AnimationKeyframeAnimationEffectTest, ExtrapolateReplace)
{
KeyframeAnimationEffect::KeyframeVector keyframes = keyframesAtZeroAndOne(pixelAnimatableValue(3.0), pixelAnimatableValue(5.0));
RefPtr<KeyframeAnimationEffect> effect = KeyframeAnimationEffect::create(keyframes);
keyframes[0]->setComposite(AnimationEffect::CompositeReplace);
keyframes[1]->setComposite(AnimationEffect::CompositeReplace);
- expectDoubleValue(3.0 * -0.6 + 5.0 * 1.6, effect->sample(0, 1.6)->begin()->value->compositeOnto(pixelAnimatableValue(7.0)));
+ expectDoubleValue(3.0 * -0.6 + 5.0 * 1.6, effect->sample(0, 1.6)->at(0).second->compositeOnto(pixelAnimatableValue(7.0)));
}
-TEST(KeyframeAnimationEffect, ExtrapolateAdd)
+TEST(AnimationKeyframeAnimationEffectTest, ExtrapolateAdd)
{
KeyframeAnimationEffect::KeyframeVector keyframes = keyframesAtZeroAndOne(pixelAnimatableValue(3.0), pixelAnimatableValue(5.0));
keyframes[0]->setComposite(AnimationEffect::CompositeAdd);
keyframes[1]->setComposite(AnimationEffect::CompositeAdd);
RefPtr<KeyframeAnimationEffect> effect = KeyframeAnimationEffect::create(keyframes);
- expectDoubleValue((7.0 + 3.0) * -0.6 + (7.0 + 5.0) * 1.6, effect->sample(0, 1.6)->begin()->value->compositeOnto(pixelAnimatableValue(7.0)));
+ expectDoubleValue((7.0 + 3.0) * -0.6 + (7.0 + 5.0) * 1.6, effect->sample(0, 1.6)->at(0).second->compositeOnto(pixelAnimatableValue(7.0)));
}
-TEST(KeyframeAnimationEffect, ZeroKeyframes)
+TEST(AnimationKeyframeAnimationEffectTest, ZeroKeyframes)
{
RefPtr<KeyframeAnimationEffect> effect = KeyframeAnimationEffect::create(KeyframeAnimationEffect::KeyframeVector());
EXPECT_TRUE(effect->sample(0, 0.5)->isEmpty());
}
-TEST(KeyframeAnimationEffect, SingleKeyframeAtOffsetZero)
+TEST(AnimationKeyframeAnimationEffectTest, SingleKeyframeAtOffsetZero)
{
KeyframeAnimationEffect::KeyframeVector keyframes(1);
keyframes[0] = Keyframe::create();
@@ -154,10 +154,10 @@ TEST(KeyframeAnimationEffect, SingleKeyframeAtOffsetZero)
keyframes[0]->setPropertyValue(CSSPropertyLeft, unknownAnimatableValue(3.0));
RefPtr<KeyframeAnimationEffect> effect = KeyframeAnimationEffect::create(keyframes);
- expectDoubleValue(3.0, effect->sample(0, 0.6)->begin()->value->compositeOnto(unknownAnimatableValue(7.0)));
+ expectDoubleValue(3.0, effect->sample(0, 0.6)->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
}
-TEST(KeyframeAnimationEffect, SingleKeyframeAtOffsetOne)
+TEST(AnimationKeyframeAnimationEffectTest, SingleKeyframeAtOffsetOne)
{
KeyframeAnimationEffect::KeyframeVector keyframes(1);
keyframes[0] = Keyframe::create();
@@ -165,10 +165,10 @@ TEST(KeyframeAnimationEffect, SingleKeyframeAtOffsetOne)
keyframes[0]->setPropertyValue(CSSPropertyLeft, pixelAnimatableValue(5.0));
RefPtr<KeyframeAnimationEffect> effect = KeyframeAnimationEffect::create(keyframes);
- expectDoubleValue(7.0 * 0.4 + 5.0 * 0.6, effect->sample(0, 0.6)->begin()->value->compositeOnto(pixelAnimatableValue(7.0)));
+ expectDoubleValue(7.0 * 0.4 + 5.0 * 0.6, effect->sample(0, 0.6)->at(0).second->compositeOnto(pixelAnimatableValue(7.0)));
}
-TEST(KeyframeAnimationEffect, MoreThanTwoKeyframes)
+TEST(AnimationKeyframeAnimationEffectTest, MoreThanTwoKeyframes)
{
KeyframeAnimationEffect::KeyframeVector keyframes(3);
keyframes[0] = Keyframe::create();
@@ -182,11 +182,11 @@ TEST(KeyframeAnimationEffect, MoreThanTwoKeyframes)
keyframes[2]->setPropertyValue(CSSPropertyLeft, unknownAnimatableValue(5.0));
RefPtr<KeyframeAnimationEffect> effect = KeyframeAnimationEffect::create(keyframes);
- expectDoubleValue(4.0, effect->sample(0, 0.3)->begin()->value->compositeOnto(unknownAnimatableValue(7.0)));
- expectDoubleValue(5.0, effect->sample(0, 0.8)->begin()->value->compositeOnto(unknownAnimatableValue(7.0)));
+ expectDoubleValue(4.0, effect->sample(0, 0.3)->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
+ expectDoubleValue(5.0, effect->sample(0, 0.8)->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
}
-TEST(KeyframeAnimationEffect, EndKeyframeOffsetsUnspecified)
+TEST(AnimationKeyframeAnimationEffectTest, EndKeyframeOffsetsUnspecified)
{
KeyframeAnimationEffect::KeyframeVector keyframes(3);
keyframes[0] = Keyframe::create();
@@ -198,12 +198,12 @@ TEST(KeyframeAnimationEffect, EndKeyframeOffsetsUnspecified)
keyframes[2]->setPropertyValue(CSSPropertyLeft, unknownAnimatableValue(5.0));
RefPtr<KeyframeAnimationEffect> effect = KeyframeAnimationEffect::create(keyframes);
- expectDoubleValue(3.0, effect->sample(0, 0.1)->begin()->value->compositeOnto(unknownAnimatableValue(7.0)));
- expectDoubleValue(4.0, effect->sample(0, 0.6)->begin()->value->compositeOnto(unknownAnimatableValue(7.0)));
- expectDoubleValue(5.0, effect->sample(0, 0.9)->begin()->value->compositeOnto(unknownAnimatableValue(7.0)));
+ expectDoubleValue(3.0, effect->sample(0, 0.1)->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
+ expectDoubleValue(4.0, effect->sample(0, 0.6)->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
+ expectDoubleValue(5.0, effect->sample(0, 0.9)->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
}
-TEST(KeyframeAnimationEffect, SampleOnKeyframe)
+TEST(AnimationKeyframeAnimationEffectTest, SampleOnKeyframe)
{
KeyframeAnimationEffect::KeyframeVector keyframes(3);
keyframes[0] = Keyframe::create();
@@ -217,13 +217,13 @@ TEST(KeyframeAnimationEffect, SampleOnKeyframe)
keyframes[2]->setPropertyValue(CSSPropertyLeft, unknownAnimatableValue(5.0));
RefPtr<KeyframeAnimationEffect> effect = KeyframeAnimationEffect::create(keyframes);
- expectDoubleValue(3.0, effect->sample(0, 0.0)->begin()->value->compositeOnto(unknownAnimatableValue(7.0)));
- expectDoubleValue(4.0, effect->sample(0, 0.5)->begin()->value->compositeOnto(unknownAnimatableValue(7.0)));
- expectDoubleValue(5.0, effect->sample(0, 1.0)->begin()->value->compositeOnto(unknownAnimatableValue(7.0)));
+ expectDoubleValue(3.0, effect->sample(0, 0.0)->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
+ expectDoubleValue(4.0, effect->sample(0, 0.5)->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
+ expectDoubleValue(5.0, effect->sample(0, 1.0)->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
}
// Note that this tests an implementation detail, not behaviour defined by the spec.
-TEST(KeyframeAnimationEffect, SampleReturnsSameAnimatableValueInstance)
+TEST(AnimationKeyframeAnimationEffectTest, SampleReturnsSameAnimatableValueInstance)
{
AnimatableValue* threePixelsValue = unknownAnimatableValue(3.0);
AnimatableValue* fourPixelsValue = unknownAnimatableValue(4.0);
@@ -241,16 +241,16 @@ TEST(KeyframeAnimationEffect, SampleReturnsSameAnimatableValueInstance)
keyframes[2]->setPropertyValue(CSSPropertyLeft, fivePixelsValue);
RefPtr<KeyframeAnimationEffect> effect = KeyframeAnimationEffect::create(keyframes);
- EXPECT_EQ(threePixelsValue, effect->sample(0, 0.0)->begin()->value->compositeOnto(unknownAnimatableValue(7.0)));
- EXPECT_EQ(threePixelsValue, effect->sample(0, 0.1)->begin()->value->compositeOnto(unknownAnimatableValue(7.0)));
- EXPECT_EQ(fourPixelsValue, effect->sample(0, 0.4)->begin()->value->compositeOnto(unknownAnimatableValue(7.0)));
- EXPECT_EQ(fourPixelsValue, effect->sample(0, 0.5)->begin()->value->compositeOnto(unknownAnimatableValue(7.0)));
- EXPECT_EQ(fourPixelsValue, effect->sample(0, 0.6)->begin()->value->compositeOnto(unknownAnimatableValue(7.0)));
- EXPECT_EQ(fivePixelsValue, effect->sample(0, 0.9)->begin()->value->compositeOnto(unknownAnimatableValue(7.0)));
- EXPECT_EQ(fivePixelsValue, effect->sample(0, 1.0)->begin()->value->compositeOnto(unknownAnimatableValue(7.0)));
+ EXPECT_EQ(threePixelsValue, effect->sample(0, 0.0)->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
+ EXPECT_EQ(threePixelsValue, effect->sample(0, 0.1)->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
+ EXPECT_EQ(fourPixelsValue, effect->sample(0, 0.4)->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
+ EXPECT_EQ(fourPixelsValue, effect->sample(0, 0.5)->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
+ EXPECT_EQ(fourPixelsValue, effect->sample(0, 0.6)->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
+ EXPECT_EQ(fivePixelsValue, effect->sample(0, 0.9)->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
+ EXPECT_EQ(fivePixelsValue, effect->sample(0, 1.0)->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
}
-TEST(KeyframeAnimationEffect, MultipleKeyframesWithSameOffset)
+TEST(AnimationKeyframeAnimationEffectTest, MultipleKeyframesWithSameOffset)
{
KeyframeAnimationEffect::KeyframeVector keyframes(7);
keyframes[0] = Keyframe::create();
@@ -276,16 +276,16 @@ TEST(KeyframeAnimationEffect, MultipleKeyframesWithSameOffset)
keyframes[6]->setPropertyValue(CSSPropertyLeft, unknownAnimatableValue(7.0));
RefPtr<KeyframeAnimationEffect> effect = KeyframeAnimationEffect::create(keyframes);
- expectDoubleValue(2.0, effect->sample(0, 0.0)->begin()->value->compositeOnto(unknownAnimatableValue(8.0)));
- expectDoubleValue(2.0, effect->sample(0, 0.2)->begin()->value->compositeOnto(unknownAnimatableValue(8.0)));
- expectDoubleValue(3.0, effect->sample(0, 0.4)->begin()->value->compositeOnto(unknownAnimatableValue(8.0)));
- expectDoubleValue(5.0, effect->sample(0, 0.5)->begin()->value->compositeOnto(unknownAnimatableValue(8.0)));
- expectDoubleValue(5.0, effect->sample(0, 0.6)->begin()->value->compositeOnto(unknownAnimatableValue(8.0)));
- expectDoubleValue(6.0, effect->sample(0, 0.8)->begin()->value->compositeOnto(unknownAnimatableValue(8.0)));
- expectDoubleValue(6.0, effect->sample(0, 1.0)->begin()->value->compositeOnto(unknownAnimatableValue(8.0)));
+ expectDoubleValue(2.0, effect->sample(0, 0.0)->at(0).second->compositeOnto(unknownAnimatableValue(8.0)));
+ expectDoubleValue(2.0, effect->sample(0, 0.2)->at(0).second->compositeOnto(unknownAnimatableValue(8.0)));
+ expectDoubleValue(3.0, effect->sample(0, 0.4)->at(0).second->compositeOnto(unknownAnimatableValue(8.0)));
+ expectDoubleValue(5.0, effect->sample(0, 0.5)->at(0).second->compositeOnto(unknownAnimatableValue(8.0)));
+ expectDoubleValue(5.0, effect->sample(0, 0.6)->at(0).second->compositeOnto(unknownAnimatableValue(8.0)));
+ expectDoubleValue(6.0, effect->sample(0, 0.8)->at(0).second->compositeOnto(unknownAnimatableValue(8.0)));
+ expectDoubleValue(6.0, effect->sample(0, 1.0)->at(0).second->compositeOnto(unknownAnimatableValue(8.0)));
}
-TEST(KeyframeAnimationEffect, PerKeyframeComposite)
+TEST(AnimationKeyframeAnimationEffectTest, PerKeyframeComposite)
{
KeyframeAnimationEffect::KeyframeVector keyframes(2);
keyframes[0] = Keyframe::create();
@@ -297,10 +297,10 @@ TEST(KeyframeAnimationEffect, PerKeyframeComposite)
keyframes[1]->setComposite(AnimationEffect::CompositeAdd);
RefPtr<KeyframeAnimationEffect> effect = KeyframeAnimationEffect::create(keyframes);
- expectDoubleValue(3.0 * 0.4 + (7.0 + 5.0) * 0.6, effect->sample(0, 0.6)->begin()->value->compositeOnto(pixelAnimatableValue(7.0)));
+ expectDoubleValue(3.0 * 0.4 + (7.0 + 5.0) * 0.6, effect->sample(0, 0.6)->at(0).second->compositeOnto(pixelAnimatableValue(7.0)));
}
-TEST(KeyframeAnimationEffect, MultipleProperties)
+TEST(AnimationKeyframeAnimationEffectTest, MultipleProperties)
{
KeyframeAnimationEffect::KeyframeVector keyframes(2);
keyframes[0] = Keyframe::create();
@@ -313,35 +313,35 @@ TEST(KeyframeAnimationEffect, MultipleProperties)
keyframes[1]->setPropertyValue(CSSPropertyRight, unknownAnimatableValue(6.0));
RefPtr<KeyframeAnimationEffect> effect = KeyframeAnimationEffect::create(keyframes);
- OwnPtr<AnimationEffect::CompositableValueMap> values = effect->sample(0, 0.6);
- ASSERT_EQ(2, values->size());
- ASSERT_TRUE(values->contains(CSSPropertyLeft));
- expectDoubleValue(5.0, values->get(CSSPropertyLeft)->compositeOnto(unknownAnimatableValue(7.0)));
- ASSERT_TRUE(values->contains(CSSPropertyRight));
- expectDoubleValue(6.0, values->get(CSSPropertyRight)->compositeOnto(unknownAnimatableValue(7.0)));
+ OwnPtr<AnimationEffect::CompositableValueList> values = effect->sample(0, 0.6);
+ ASSERT_EQ(2UL, values->size());
+ EXPECT_TRUE(values->at(0).first == CSSPropertyLeft);
+ expectDoubleValue(5.0, values->at(0).second->compositeOnto(unknownAnimatableValue(7.0)));
+ EXPECT_TRUE(values->at(1).first == CSSPropertyRight);
+ expectDoubleValue(6.0, values->at(1).second->compositeOnto(unknownAnimatableValue(7.0)));
}
-TEST(KeyframeAnimationEffect, RecompositeCompositableValue)
+TEST(AnimationKeyframeAnimationEffectTest, RecompositeCompositableValue)
{
KeyframeAnimationEffect::KeyframeVector keyframes = keyframesAtZeroAndOne(pixelAnimatableValue(3.0), pixelAnimatableValue(5.0));
keyframes[0]->setComposite(AnimationEffect::CompositeAdd);
keyframes[1]->setComposite(AnimationEffect::CompositeAdd);
RefPtr<KeyframeAnimationEffect> effect = KeyframeAnimationEffect::create(keyframes);
- OwnPtr<AnimationEffect::CompositableValueMap> values = effect->sample(0, 0.6);
- expectDoubleValue((7.0 + 3.0) * 0.4 + (7.0 + 5.0) * 0.6, values->begin()->value->compositeOnto(pixelAnimatableValue(7.0)));
- expectDoubleValue((9.0 + 3.0) * 0.4 + (9.0 + 5.0) * 0.6, values->begin()->value->compositeOnto(pixelAnimatableValue(9.0)));
+ OwnPtr<AnimationEffect::CompositableValueList> values = effect->sample(0, 0.6);
+ expectDoubleValue((7.0 + 3.0) * 0.4 + (7.0 + 5.0) * 0.6, values->at(0).second->compositeOnto(pixelAnimatableValue(7.0)));
+ expectDoubleValue((9.0 + 3.0) * 0.4 + (9.0 + 5.0) * 0.6, values->at(0).second->compositeOnto(pixelAnimatableValue(9.0)));
}
-TEST(KeyframeAnimationEffect, MultipleIterations)
+TEST(AnimationKeyframeAnimationEffectTest, MultipleIterations)
{
KeyframeAnimationEffect::KeyframeVector keyframes = keyframesAtZeroAndOne(pixelAnimatableValue(1.0), pixelAnimatableValue(3.0));
RefPtr<KeyframeAnimationEffect> effect = KeyframeAnimationEffect::create(keyframes);
- expectDoubleValue(2.0, effect->sample(0, 0.5)->begin()->value->compositeOnto(unknownAnimatableValue(0.0)));
- expectDoubleValue(2.0, effect->sample(1, 0.5)->begin()->value->compositeOnto(unknownAnimatableValue(0.0)));
- expectDoubleValue(2.0, effect->sample(2, 0.5)->begin()->value->compositeOnto(unknownAnimatableValue(0.0)));
+ expectDoubleValue(2.0, effect->sample(0, 0.5)->at(0).second->compositeOnto(unknownAnimatableValue(0.0)));
+ expectDoubleValue(2.0, effect->sample(1, 0.5)->at(0).second->compositeOnto(unknownAnimatableValue(0.0)));
+ expectDoubleValue(2.0, effect->sample(2, 0.5)->at(0).second->compositeOnto(unknownAnimatableValue(0.0)));
}
-TEST(KeyframeAnimationEffect, DependsOnUnderlyingValue)
+TEST(AnimationKeyframeAnimationEffectTest, DependsOnUnderlyingValue)
{
KeyframeAnimationEffect::KeyframeVector keyframes(3);
keyframes[0] = Keyframe::create();
@@ -356,15 +356,24 @@ TEST(KeyframeAnimationEffect, DependsOnUnderlyingValue)
keyframes[2]->setPropertyValue(CSSPropertyLeft, pixelAnimatableValue(1.0));
RefPtr<KeyframeAnimationEffect> effect = KeyframeAnimationEffect::create(keyframes);
- EXPECT_TRUE(effect->sample(0, 0)->begin()->value->dependsOnUnderlyingValue());
- EXPECT_TRUE(effect->sample(0, 0.1)->begin()->value->dependsOnUnderlyingValue());
- EXPECT_TRUE(effect->sample(0, 0.25)->begin()->value->dependsOnUnderlyingValue());
- EXPECT_TRUE(effect->sample(0, 0.4)->begin()->value->dependsOnUnderlyingValue());
- EXPECT_FALSE(effect->sample(0, 0.5)->begin()->value->dependsOnUnderlyingValue());
- EXPECT_FALSE(effect->sample(0, 0.6)->begin()->value->dependsOnUnderlyingValue());
- EXPECT_FALSE(effect->sample(0, 0.75)->begin()->value->dependsOnUnderlyingValue());
- EXPECT_FALSE(effect->sample(0, 0.8)->begin()->value->dependsOnUnderlyingValue());
- EXPECT_FALSE(effect->sample(0, 1)->begin()->value->dependsOnUnderlyingValue());
+ EXPECT_TRUE(effect->sample(0, 0)->at(0).second->dependsOnUnderlyingValue());
+ EXPECT_TRUE(effect->sample(0, 0.1)->at(0).second->dependsOnUnderlyingValue());
+ EXPECT_TRUE(effect->sample(0, 0.25)->at(0).second->dependsOnUnderlyingValue());
+ EXPECT_TRUE(effect->sample(0, 0.4)->at(0).second->dependsOnUnderlyingValue());
+ EXPECT_FALSE(effect->sample(0, 0.5)->at(0).second->dependsOnUnderlyingValue());
+ EXPECT_FALSE(effect->sample(0, 0.6)->at(0).second->dependsOnUnderlyingValue());
+ EXPECT_FALSE(effect->sample(0, 0.75)->at(0).second->dependsOnUnderlyingValue());
+ EXPECT_FALSE(effect->sample(0, 0.8)->at(0).second->dependsOnUnderlyingValue());
+ EXPECT_FALSE(effect->sample(0, 1)->at(0).second->dependsOnUnderlyingValue());
+}
+
+TEST(AnimationKeyframeAnimationEffectTest, ToKeyframeAnimationEffect)
+{
+ KeyframeAnimationEffect::KeyframeVector keyframes(0);
+ RefPtr<KeyframeAnimationEffect> effect = KeyframeAnimationEffect::create(keyframes);
+
+ AnimationEffect* baseEffect = effect.get();
+ EXPECT_TRUE(toKeyframeAnimationEffect(baseEffect));
}
} // namespace
diff --git a/chromium/third_party/WebKit/Source/core/animation/Player.cpp b/chromium/third_party/WebKit/Source/core/animation/Player.cpp
index 0d44da78a69..2fabdd15e17 100644
--- a/chromium/third_party/WebKit/Source/core/animation/Player.cpp
+++ b/chromium/third_party/WebKit/Source/core/animation/Player.cpp
@@ -32,29 +32,33 @@
#include "config.h"
#include "core/animation/Player.h"
+#include "core/animation/Animation.h"
#include "core/animation/DocumentTimeline.h"
-#include "core/animation/TimedItem.h"
namespace WebCore {
-PassRefPtr<Player> Player::create(DocumentTimeline* timeline, TimedItem* content)
+namespace {
+
+double effectiveTime(double time) { return isNull(time) ? 0 : time; }
+
+} // namespace
+
+PassRefPtr<Player> Player::create(DocumentTimeline& timeline, TimedItem* content)
{
- ASSERT(timeline);
return adoptRef(new Player(timeline, content));
}
-Player::Player(DocumentTimeline* timeline, TimedItem* content)
+Player::Player(DocumentTimeline& timeline, TimedItem* content)
: m_pauseStartTime(nullValue())
, m_playbackRate(1)
, m_timeDrift(0)
- , m_startTime(effectiveTime(timeline->currentTime()))
+ , m_startTime(nullValue())
, m_content(content)
, m_timeline(timeline)
+ , m_isPausedForTesting(false)
{
- ASSERT(m_startTime >= 0);
if (m_content)
m_content->attach(this);
- update();
}
Player::~Player()
@@ -63,20 +67,54 @@ Player::~Player()
m_content->detach();
}
+void Player::setStartTime(double startTime)
+{
+ ASSERT(!isNull(startTime));
+ ASSERT(!hasStartTime());
+ m_startTime = startTime;
+ update();
+}
+
double Player::currentTimeBeforeDrift() const
{
- return (effectiveTime(m_timeline->currentTime()) - m_startTime) * m_playbackRate;
+ if (isNull(m_startTime))
+ return 0;
+ return (effectiveTime(m_timeline.currentTime()) - startTime()) * m_playbackRate;
+}
+
+bool Player::maybeStartAnimationOnCompositor()
+{
+ // FIXME: Support starting compositor animations that have a fixed
+ // start time.
+ ASSERT(!hasStartTime());
+ if (!m_content || !m_content->isAnimation())
+ return false;
+
+ return toAnimation(m_content.get())->maybeStartAnimationOnCompositor();
+}
+
+bool Player::hasActiveAnimationsOnCompositor()
+{
+ if (!m_content || !m_content->isAnimation())
+ return false;
+ return toAnimation(m_content.get())->hasActiveAnimationsOnCompositor();
+}
+
+void Player::cancelAnimationOnCompositor()
+{
+ if (hasActiveAnimationsOnCompositor())
+ toAnimation(m_content.get())->cancelAnimationOnCompositor();
}
double Player::pausedTimeDrift() const
{
- ASSERT(paused());
+ ASSERT(pausedInternal());
return currentTimeBeforeDrift() - m_pauseStartTime;
}
double Player::timeDrift() const
{
- return paused() ? pausedTimeDrift() : m_timeDrift;
+ return pausedInternal() ? pausedTimeDrift() : m_timeDrift;
}
double Player::currentTime() const
@@ -84,13 +122,23 @@ double Player::currentTime() const
return currentTimeBeforeDrift() - timeDrift();
}
-bool Player::update()
+bool Player::update(double* timeToEffectChange, bool* didTriggerStyleRecalc)
{
- if (!m_content)
+ if (!m_content) {
+ if (timeToEffectChange)
+ *timeToEffectChange = std::numeric_limits<double>::infinity();
+ if (didTriggerStyleRecalc)
+ *didTriggerStyleRecalc = false;
return false;
+ }
- double newTime = isNull(m_timeline->currentTime()) ? nullValue() : currentTime();
- m_content->updateInheritedTime(newTime);
+ double inheritedTime = isNull(m_timeline.currentTime()) ? nullValue() : currentTime();
+ bool didTriggerStyleRecalcLocal = m_content->updateInheritedTime(inheritedTime);
+
+ if (timeToEffectChange)
+ *timeToEffectChange = m_content->timeToEffectChange();
+ if (didTriggerStyleRecalc)
+ *didTriggerStyleRecalc = didTriggerStyleRecalcLocal;
return m_content->isCurrent() || m_content->isInEffect();
}
@@ -106,22 +154,41 @@ void Player::cancel()
void Player::setCurrentTime(double seekTime)
{
- if (paused())
+ if (pausedInternal())
m_pauseStartTime = seekTime;
else
m_timeDrift = currentTimeBeforeDrift() - seekTime;
+ if (m_isPausedForTesting && hasActiveAnimationsOnCompositor())
+ toAnimation(m_content.get())->pauseAnimationForTestingOnCompositor(currentTime());
update();
}
+void Player::pauseForTesting()
+{
+ RELEASE_ASSERT(!paused());
+ if (!m_isPausedForTesting && hasActiveAnimationsOnCompositor())
+ toAnimation(m_content.get())->pauseAnimationForTestingOnCompositor(currentTime());
+ m_isPausedForTesting = true;
+ setPausedImpl(true);
+}
+
void Player::setPaused(bool newValue)
{
- if (paused() == newValue)
+ ASSERT(!m_isPausedForTesting);
+ setPausedImpl(newValue);
+}
+
+void Player::setPausedImpl(bool newValue)
+{
+ if (pausedInternal() == newValue)
return;
- if (newValue)
+ if (newValue) {
+ // FIXME: resume compositor animation rather than pull back to main-thread
+ cancelAnimationOnCompositor();
m_pauseStartTime = currentTime();
- else {
+ } else {
m_timeDrift = pausedTimeDrift();
m_pauseStartTime = nullValue();
}
diff --git a/chromium/third_party/WebKit/Source/core/animation/Player.h b/chromium/third_party/WebKit/Source/core/animation/Player.h
index 985fb45c32e..df80447d51e 100644
--- a/chromium/third_party/WebKit/Source/core/animation/Player.h
+++ b/chromium/third_party/WebKit/Source/core/animation/Player.h
@@ -42,34 +42,59 @@ class Player FINAL : public RefCounted<Player> {
public:
~Player();
- static PassRefPtr<Player> create(DocumentTimeline*, TimedItem*);
+ static PassRefPtr<Player> create(DocumentTimeline&, TimedItem*);
// Returns whether this player is still current or in effect.
- bool update();
+ // timeToEffectChange returns:
+ // infinity - if this player is no longer in effect
+ // 0 - if this player requires an update on the next frame
+ // n - if this player requires an update after 'n' units of time
+ bool update(double* timeToEffectChange = 0, bool* didTriggerStyleRecalc = 0);
void cancel();
+
double currentTime() const;
void setCurrentTime(double);
- bool paused() const { return !isNull(m_pauseStartTime); }
+
+ bool paused() const { return !m_isPausedForTesting && pausedInternal(); }
void setPaused(bool);
+
double playbackRate() const { return m_playbackRate; }
void setPlaybackRate(double);
- double startTime() const { return m_startTime; }
double timeDrift() const;
- DocumentTimeline* timeline() { return m_timeline; }
+ DocumentTimeline& timeline() { return m_timeline; }
+
+ bool hasStartTime() const { return !isNull(m_startTime); }
+ double startTime() const { return m_startTime; }
+ void setStartTime(double);
+
+ TimedItem* source() { return m_content.get(); }
+
+ // Pausing via this method is not reflected in the value returned by
+ // paused() and must never overlap with pausing via setPaused().
+ void pauseForTesting();
+
+ bool maybeStartAnimationOnCompositor();
+ void cancelAnimationOnCompositor();
+ bool hasActiveAnimationsOnCompositor();
private:
- Player(DocumentTimeline*, TimedItem*);
- static double effectiveTime(double time) { return isNull(time) ? 0 : time; }
+ Player(DocumentTimeline&, TimedItem*);
inline double pausedTimeDrift() const;
inline double currentTimeBeforeDrift() const;
+
+ void setPausedImpl(bool);
+ // Reflects all pausing, including via pauseForTesting().
+ bool pausedInternal() const { return !isNull(m_pauseStartTime); }
+
double m_pauseStartTime;
double m_playbackRate;
double m_timeDrift;
- const double m_startTime;
+ double m_startTime;
RefPtr<TimedItem> m_content;
- DocumentTimeline* const m_timeline;
+ DocumentTimeline& m_timeline;
+ bool m_isPausedForTesting;
};
} // namespace
diff --git a/chromium/third_party/WebKit/Source/core/animation/PlayerTest.cpp b/chromium/third_party/WebKit/Source/core/animation/PlayerTest.cpp
index c4ff23e8131..4ff5badddba 100644
--- a/chromium/third_party/WebKit/Source/core/animation/PlayerTest.cpp
+++ b/chromium/third_party/WebKit/Source/core/animation/PlayerTest.cpp
@@ -31,31 +31,36 @@
#include "config.h"
#include "core/animation/Player.h"
+#include "core/animation/ActiveAnimations.h"
+#include "core/animation/Animation.h"
+#include "core/animation/AnimationClock.h"
#include "core/animation/DocumentTimeline.h"
#include "core/dom/Document.h"
#include "core/dom/QualifiedName.h"
-#include "weborigin/KURL.h"
+#include "platform/weborigin/KURL.h"
#include <gtest/gtest.h>
using namespace WebCore;
namespace {
-class PlayerTest : public ::testing::Test {
+class AnimationPlayerTest : public ::testing::Test {
protected:
virtual void SetUp()
{
document = Document::create();
+ document->animationClock().resetTimeForTesting();
timeline = DocumentTimeline::create(document.get());
- player = Player::create(timeline.get(), 0);
- timeline->setZeroTimeAsPerfTime(0);
+ player = Player::create(*timeline, 0);
+ player->setStartTime(0);
+ timeline->setZeroTime(0);
}
- bool updateTimeline(double time)
+ bool updateTimeline(double time, double* timeToEffectChange = 0)
{
- timeline->serviceAnimations(time);
+ document->animationClock().updateTime(time);
// The timeline does not know about our player, so we have to explicitly call update().
- return player->update();
+ return player->update(timeToEffectChange);
}
RefPtr<Document> document;
@@ -63,7 +68,7 @@ protected:
RefPtr<Player> player;
};
-TEST_F(PlayerTest, InitialState)
+TEST_F(AnimationPlayerTest, InitialState)
{
EXPECT_EQ(0, timeline->currentTime());
EXPECT_EQ(0, player->currentTime());
@@ -73,16 +78,7 @@ TEST_F(PlayerTest, InitialState)
EXPECT_EQ(0, player->timeDrift());
}
-TEST_F(PlayerTest, CreatePlayerAfterTimelineStarted)
-{
- updateTimeline(1234);
- EXPECT_EQ(1234, timeline->currentTime());
- RefPtr<Player> player = Player::create(timeline.get(), 0);
- EXPECT_EQ(1234, player->startTime());
- EXPECT_EQ(0, player->currentTime());
-}
-
-TEST_F(PlayerTest, PauseUnpause)
+TEST_F(AnimationPlayerTest, PauseUnpause)
{
updateTimeline(200);
player->setPaused(true);
@@ -101,7 +97,7 @@ TEST_F(PlayerTest, PauseUnpause)
EXPECT_EQ(200, player->timeDrift());
}
-TEST_F(PlayerTest, PauseBeforeTimelineStarted)
+TEST_F(AnimationPlayerTest, PauseBeforeTimelineStarted)
{
player->setPaused(true);
EXPECT_TRUE(player->paused());
@@ -124,7 +120,27 @@ TEST_F(PlayerTest, PauseBeforeTimelineStarted)
EXPECT_EQ(100, player->timeDrift());
}
-TEST_F(PlayerTest, SetCurrentTime)
+TEST_F(AnimationPlayerTest, PauseBeforeStartTimeSet)
+{
+ player = Player::create(*timeline, 0);
+ updateTimeline(100);
+ EXPECT_EQ(0, player->currentTime());
+
+ player->setPaused(true);
+ updateTimeline(200);
+ EXPECT_EQ(0, player->currentTime());
+
+ player->setStartTime(150);
+ EXPECT_EQ(0, player->currentTime());
+
+ player->setPaused(false);
+ EXPECT_EQ(0, player->currentTime());
+
+ updateTimeline(300);
+ EXPECT_EQ(100, player->currentTime());
+}
+
+TEST_F(AnimationPlayerTest, SetCurrentTime)
{
updateTimeline(0);
player->setCurrentTime(250);
@@ -132,7 +148,26 @@ TEST_F(PlayerTest, SetCurrentTime)
EXPECT_EQ(-250, player->timeDrift());
}
-TEST_F(PlayerTest, SetCurrentTimeBeforeTimelineStarted)
+TEST_F(AnimationPlayerTest, SetStartTime)
+{
+ updateTimeline(0);
+ player = Player::create(*timeline, 0);
+ EXPECT_FALSE(player->hasStartTime());
+ EXPECT_TRUE(isNull(player->startTime()));
+ EXPECT_EQ(0, player->currentTime());
+
+ updateTimeline(100);
+ player->setStartTime(50);
+ EXPECT_TRUE(player->hasStartTime());
+ EXPECT_EQ(50, player->startTime());
+ EXPECT_EQ(50, player->currentTime());
+
+ updateTimeline(200);
+ EXPECT_EQ(150, player->currentTime());
+}
+
+
+TEST_F(AnimationPlayerTest, SetCurrentTimeBeforeTimelineStarted)
{
player->setCurrentTime(250);
EXPECT_EQ(250, player->currentTime());
@@ -142,7 +177,21 @@ TEST_F(PlayerTest, SetCurrentTimeBeforeTimelineStarted)
EXPECT_EQ(250, player->currentTime());
}
-TEST_F(PlayerTest, SetPlaybackRate)
+TEST_F(AnimationPlayerTest, SetCurrentTimeBeforeStartTimeSet)
+{
+ updateTimeline(0);
+ player = Player::create(*timeline, 0);
+
+ player->setCurrentTime(250);
+ EXPECT_EQ(250, player->currentTime());
+ EXPECT_EQ(-250, player->timeDrift());
+
+ updateTimeline(100);
+ player->setStartTime(50);
+ EXPECT_EQ(300, player->currentTime());
+}
+
+TEST_F(AnimationPlayerTest, SetPlaybackRate)
{
updateTimeline(0);
player->setPlaybackRate(2);
@@ -155,7 +204,7 @@ TEST_F(PlayerTest, SetPlaybackRate)
EXPECT_EQ(0, player->timeDrift());
}
-TEST_F(PlayerTest, SetPlaybackRateBeforeTimelineStarted)
+TEST_F(AnimationPlayerTest, SetPlaybackRateBeforeTimelineStarted)
{
player->setPlaybackRate(2);
EXPECT_EQ(0, player->currentTime());
@@ -166,7 +215,7 @@ TEST_F(PlayerTest, SetPlaybackRateBeforeTimelineStarted)
EXPECT_EQ(0, player->timeDrift());
}
-TEST_F(PlayerTest, SetPlaybackRateWhilePaused)
+TEST_F(AnimationPlayerTest, SetPlaybackRateWhilePaused)
{
updateTimeline(100);
player->setPaused(true);
@@ -184,7 +233,7 @@ TEST_F(PlayerTest, SetPlaybackRateWhilePaused)
EXPECT_EQ(300, player->timeDrift());
}
-TEST_F(PlayerTest, SetPlaybackRateNaN)
+TEST_F(AnimationPlayerTest, SetPlaybackRateNaN)
{
updateTimeline(0);
player->setPlaybackRate(nullValue());
@@ -197,7 +246,7 @@ TEST_F(PlayerTest, SetPlaybackRateNaN)
EXPECT_TRUE(isNull(player->timeDrift()));
}
-TEST_F(PlayerTest, SetPlaybackRateInfinity)
+TEST_F(AnimationPlayerTest, SetPlaybackRateInfinity)
{
updateTimeline(0);
player->setPlaybackRate(std::numeric_limits<double>::infinity());
@@ -210,7 +259,7 @@ TEST_F(PlayerTest, SetPlaybackRateInfinity)
EXPECT_TRUE(isNull(player->timeDrift()));
}
-TEST_F(PlayerTest, SetPlaybackRateMax)
+TEST_F(AnimationPlayerTest, SetPlaybackRateMax)
{
updateTimeline(0);
player->setPlaybackRate(std::numeric_limits<double>::max());
@@ -222,7 +271,7 @@ TEST_F(PlayerTest, SetPlaybackRateMax)
EXPECT_EQ(std::numeric_limits<double>::infinity(), player->currentTime());
}
-TEST_F(PlayerTest, SetCurrentTimeNan)
+TEST_F(AnimationPlayerTest, SetCurrentTimeNan)
{
updateTimeline(0);
player->setCurrentTime(nullValue());
@@ -234,7 +283,7 @@ TEST_F(PlayerTest, SetCurrentTimeNan)
EXPECT_TRUE(isNull(player->timeDrift()));
}
-TEST_F(PlayerTest, SetCurrentTimeInfinity)
+TEST_F(AnimationPlayerTest, SetCurrentTimeInfinity)
{
updateTimeline(0);
player->setCurrentTime(std::numeric_limits<double>::infinity());
@@ -246,7 +295,7 @@ TEST_F(PlayerTest, SetCurrentTimeInfinity)
EXPECT_EQ(-std::numeric_limits<double>::infinity(), player->timeDrift());
}
-TEST_F(PlayerTest, SetCurrentTimeMax)
+TEST_F(AnimationPlayerTest, SetCurrentTimeMax)
{
updateTimeline(0);
player->setCurrentTime(std::numeric_limits<double>::max());
@@ -258,4 +307,58 @@ TEST_F(PlayerTest, SetCurrentTimeMax)
EXPECT_EQ(-std::numeric_limits<double>::max(), player->timeDrift());
}
+TEST_F(AnimationPlayerTest, EmptyPlayersDontUpdateEffects)
+{
+ double timeToNextEffect;
+ updateTimeline(0, &timeToNextEffect);
+ EXPECT_EQ(std::numeric_limits<double>::infinity(), timeToNextEffect);
+
+ timeToNextEffect = 0;
+ updateTimeline(1234, &timeToNextEffect);
+ EXPECT_EQ(std::numeric_limits<double>::infinity(), timeToNextEffect);
+}
+
+TEST_F(AnimationPlayerTest, PlayersReturnTimeToNextEffect)
+{
+ Timing timing;
+ timing.startDelay = 1;
+ timing.iterationDuration = 1;
+ timing.hasIterationDuration = true;
+ RefPtr<Animation> animation = Animation::create(0, 0, timing);
+ player = Player::create(*timeline, animation.get());
+ player->setStartTime(0);
+
+ double timeToNextEffect;
+ updateTimeline(0, &timeToNextEffect);
+ EXPECT_EQ(1, timeToNextEffect);
+
+ updateTimeline(0.5, &timeToNextEffect);
+ EXPECT_EQ(0.5, timeToNextEffect);
+
+ updateTimeline(1, &timeToNextEffect);
+ EXPECT_EQ(0, timeToNextEffect);
+
+ updateTimeline(1.5, &timeToNextEffect);
+ EXPECT_EQ(0, timeToNextEffect);
+
+ updateTimeline(2, &timeToNextEffect);
+ EXPECT_EQ(std::numeric_limits<double>::infinity(), timeToNextEffect);
+
+ updateTimeline(3, &timeToNextEffect);
+ EXPECT_EQ(std::numeric_limits<double>::infinity(), timeToNextEffect);
+}
+
+TEST_F(AnimationPlayerTest, AttachedPlayers)
+{
+ RefPtr<Element> element = document->createElement("foo", ASSERT_NO_EXCEPTION);
+
+ Timing timing;
+ RefPtr<Animation> animation = Animation::create(element, 0, timing);
+ RefPtr<Player> player = Player::create(*timeline, animation.get());
+ EXPECT_EQ(1U, element->activeAnimations()->players().find(player.get())->value);
+
+ player.release();
+ EXPECT_TRUE(element->activeAnimations()->players().isEmpty());
+}
+
}
diff --git a/chromium/third_party/WebKit/Source/core/animation/TimedItem.cpp b/chromium/third_party/WebKit/Source/core/animation/TimedItem.cpp
index 1ef24520016..3b7aa948c1f 100644
--- a/chromium/third_party/WebKit/Source/core/animation/TimedItem.cpp
+++ b/chromium/third_party/WebKit/Source/core/animation/TimedItem.cpp
@@ -30,84 +30,119 @@
#include "config.h"
#include "core/animation/TimedItem.h"
+
+#include "core/animation/Player.h"
#include "core/animation/TimedItemCalculations.h"
namespace WebCore {
TimedItem::TimedItem(const Timing& timing, PassOwnPtr<EventDelegate> eventDelegate)
: m_parent(0)
- , m_player(0)
, m_startTime(0)
+ , m_player(0)
, m_specified(timing)
- , m_calculated()
, m_eventDelegate(eventDelegate)
+ , m_calculated()
, m_isFirstSample(true)
+ , m_needsUpdate(true)
+ , m_lastUpdateTime(nullValue())
{
- timing.assertValid();
+ m_specified.assertValid();
}
-void TimedItem::updateInheritedTime(double inheritedTime) const
+bool TimedItem::updateInheritedTime(double inheritedTime) const
{
+ bool needsUpdate = m_needsUpdate || (m_lastUpdateTime != inheritedTime && !(isNull(m_lastUpdateTime) && isNull(inheritedTime)));
+ m_needsUpdate = false;
+ m_lastUpdateTime = inheritedTime;
+
+ const double previousIteration = m_calculated.currentIteration;
+ const Phase previousPhase = m_calculated.phase;
+
const double localTime = inheritedTime - m_startTime;
- const double iterationDuration = m_specified.hasIterationDuration
- ? m_specified.iterationDuration
- : intrinsicIterationDuration();
-
- const double repeatedDuration = iterationDuration * m_specified.iterationCount;
- const double activeDuration = m_specified.playbackRate
- ? repeatedDuration / abs(m_specified.playbackRate)
- : std::numeric_limits<double>::infinity();
-
- const Phase currentPhase = calculatePhase(activeDuration, localTime, m_specified);
- // FIXME: parentPhase depends on groups being implemented.
- const TimedItem::Phase parentPhase = TimedItem::PhaseActive;
- const double activeTime = calculateActiveTime(activeDuration, localTime, parentPhase, currentPhase, m_specified);
-
- double currentIteration = nullValue();
- double timeFraction = nullValue();
- ASSERT(iterationDuration >= 0);
- if (iterationDuration) {
- const double startOffset = m_specified.iterationStart * iterationDuration;
- const double scaledActiveTime = calculateScaledActiveTime(activeDuration, activeTime, startOffset, m_specified);
- const double iterationTime = calculateIterationTime(iterationDuration, repeatedDuration, scaledActiveTime, startOffset, m_specified);
-
- currentIteration = calculateCurrentIteration(iterationDuration, iterationTime, scaledActiveTime, m_specified);
- timeFraction = calculateTransformedTime(currentIteration, iterationDuration, iterationTime, m_specified) / iterationDuration;
- } else {
- const double iterationDuration = 1;
- const double repeatedDuration = iterationDuration * m_specified.iterationCount;
- const double activeDuration = m_specified.playbackRate ? repeatedDuration / abs(m_specified.playbackRate) : std::numeric_limits<double>::infinity();
- const double newLocalTime = localTime < m_specified.startDelay ? m_specified.startDelay - 1 : activeDuration + m_specified.startDelay;
- const TimedItem::Phase localPhase = calculatePhase(activeDuration, newLocalTime, m_specified);
- const double activeTime = calculateActiveTime(activeDuration, newLocalTime, parentPhase, localPhase, m_specified);
- const double startOffset = m_specified.iterationStart * iterationDuration;
- const double scaledActiveTime = calculateScaledActiveTime(activeDuration, activeTime, startOffset, m_specified);
- const double iterationTime = calculateIterationTime(iterationDuration, repeatedDuration, scaledActiveTime, startOffset, m_specified);
-
- currentIteration = calculateCurrentIteration(iterationDuration, iterationTime, scaledActiveTime, m_specified);
- timeFraction = calculateTransformedTime(currentIteration, iterationDuration, iterationTime, m_specified);
+ double timeToNextIteration = std::numeric_limits<double>::infinity();
+ if (needsUpdate) {
+ const double iterationDuration = m_specified.hasIterationDuration
+ ? m_specified.iterationDuration
+ : intrinsicIterationDuration();
+ ASSERT(iterationDuration >= 0);
+
+ // When iterationDuration = 0 and iterationCount = infinity, or vice-
+ // versa, repeatedDuration should be 0, not NaN as operator*() would give.
+ // FIXME: The spec is unclear about this.
+ const double repeatedDuration = multiplyZeroAlwaysGivesZero(iterationDuration, m_specified.iterationCount);
+ ASSERT(repeatedDuration >= 0);
+ const double activeDuration = m_specified.playbackRate
+ ? repeatedDuration / abs(m_specified.playbackRate)
+ : std::numeric_limits<double>::infinity();
+ ASSERT(activeDuration >= 0);
+
+ const Phase currentPhase = calculatePhase(activeDuration, localTime, m_specified);
+ // FIXME: parentPhase depends on groups being implemented.
+ const TimedItem::Phase parentPhase = TimedItem::PhaseActive;
+ const double activeTime = calculateActiveTime(activeDuration, localTime, parentPhase, currentPhase, m_specified);
+
+ double currentIteration;
+ double timeFraction;
+ if (iterationDuration) {
+ const double startOffset = multiplyZeroAlwaysGivesZero(m_specified.iterationStart, iterationDuration);
+ ASSERT(startOffset >= 0);
+ const double scaledActiveTime = calculateScaledActiveTime(activeDuration, activeTime, startOffset, m_specified);
+ const double iterationTime = calculateIterationTime(iterationDuration, repeatedDuration, scaledActiveTime, startOffset, m_specified);
+
+ currentIteration = calculateCurrentIteration(iterationDuration, iterationTime, scaledActiveTime, m_specified);
+ timeFraction = calculateTransformedTime(currentIteration, iterationDuration, iterationTime, m_specified) / iterationDuration;
+
+ if (!isNull(iterationTime)) {
+ timeToNextIteration = (iterationDuration - iterationTime) / abs(m_specified.playbackRate);
+ if (activeDuration - activeTime < timeToNextIteration)
+ timeToNextIteration = std::numeric_limits<double>::infinity();
+ }
+ } else {
+ const double localIterationDuration = 1;
+ const double localRepeatedDuration = localIterationDuration * m_specified.iterationCount;
+ ASSERT(localRepeatedDuration >= 0);
+ const double localActiveDuration = m_specified.playbackRate ? localRepeatedDuration / abs(m_specified.playbackRate) : std::numeric_limits<double>::infinity();
+ ASSERT(localActiveDuration >= 0);
+ const double localLocalTime = localTime < m_specified.startDelay ? localTime : localActiveDuration + m_specified.startDelay;
+ const TimedItem::Phase localCurrentPhase = calculatePhase(localActiveDuration, localLocalTime, m_specified);
+ const double localActiveTime = calculateActiveTime(localActiveDuration, localLocalTime, parentPhase, localCurrentPhase, m_specified);
+ const double startOffset = m_specified.iterationStart * localIterationDuration;
+ ASSERT(startOffset >= 0);
+ const double scaledActiveTime = calculateScaledActiveTime(localActiveDuration, localActiveTime, startOffset, m_specified);
+ const double iterationTime = calculateIterationTime(localIterationDuration, localRepeatedDuration, scaledActiveTime, startOffset, m_specified);
+
+ currentIteration = calculateCurrentIteration(localIterationDuration, iterationTime, scaledActiveTime, m_specified);
+ timeFraction = calculateTransformedTime(currentIteration, localIterationDuration, iterationTime, m_specified);
+ }
+
+ m_calculated.currentIteration = currentIteration;
+ m_calculated.activeDuration = activeDuration;
+ m_calculated.timeFraction = timeFraction;
+
+ m_calculated.phase = currentPhase;
+ m_calculated.isInEffect = !isNull(activeTime);
+ m_calculated.isInPlay = phase() == PhaseActive && (!m_parent || m_parent->isInPlay());
+ m_calculated.isCurrent = phase() == PhaseBefore || isInPlay() || (m_parent && m_parent->isCurrent());
}
- const double previousIteration = m_calculated.currentIteration;
- m_calculated.currentIteration = currentIteration;
- m_calculated.activeDuration = activeDuration;
- m_calculated.timeFraction = timeFraction;
+ // Test for events even if timing didn't need an update as the player may have gained a start time.
+ // FIXME: Refactor so that we can ASSERT(m_player) here, this is currently required to be nullable for testing.
+ if (!m_player || m_player->hasStartTime()) {
+ // This logic is specific to CSS animation events and assumes that all
+ // animations start after the DocumentTimeline has started.
+ if (m_eventDelegate && (m_isFirstSample || previousPhase != phase() || (phase() == PhaseActive && previousIteration != m_calculated.currentIteration)))
+ m_eventDelegate->onEventCondition(this, m_isFirstSample, previousPhase, previousIteration);
+ m_isFirstSample = false;
+ }
- const Phase previousPhase = m_calculated.phase;
- const bool wasInEffect = m_calculated.isInEffect;
- m_calculated.phase = currentPhase;
- m_calculated.isInEffect = !isNull(activeTime);
- m_calculated.isInPlay = phase() == PhaseActive && (!m_parent || m_parent->isInPlay());
- m_calculated.isCurrent = phase() == PhaseBefore || isInPlay() || (m_parent && m_parent->isCurrent());
-
- // This logic is specific to CSS animation events and assumes that all
- // animations start after the DocumentTimeline has started.
- if (m_eventDelegate && (m_isFirstSample || previousPhase != phase() || (phase() == PhaseActive && previousIteration != currentIteration)))
- m_eventDelegate->onEventCondition(this, m_isFirstSample, previousPhase, previousIteration);
- m_isFirstSample = false;
-
- // FIXME: This probably shouldn't be recursive.
- updateChildrenAndEffects(wasInEffect);
+ bool didTriggerStyleRecalc = false;
+ if (needsUpdate) {
+ // FIXME: This probably shouldn't be recursive.
+ didTriggerStyleRecalc = updateChildrenAndEffects();
+ m_calculated.timeToEffectChange = calculateTimeToEffectChange(localTime, timeToNextIteration);
+ }
+ return didTriggerStyleRecalc;
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/animation/TimedItem.h b/chromium/third_party/WebKit/Source/core/animation/TimedItem.h
index 31520fc4ebe..82da5133f58 100644
--- a/chromium/third_party/WebKit/Source/core/animation/TimedItem.h
+++ b/chromium/third_party/WebKit/Source/core/animation/TimedItem.h
@@ -70,18 +70,20 @@ public:
virtual ~TimedItem() { }
+ virtual bool isAnimation() const { return false; }
+
Phase phase() const { return ensureCalculated().phase; }
bool isCurrent() const { return ensureCalculated().isCurrent; }
bool isInEffect() const { return ensureCalculated().isInEffect; }
bool isInPlay() const { return ensureCalculated().isInPlay; }
-
- double startTime() const { return m_startTime; }
+ double timeToEffectChange() const { return ensureCalculated().timeToEffectChange; }
double currentIteration() const { return ensureCalculated().currentIteration; }
double activeDuration() const { return ensureCalculated().activeDuration; }
double timeFraction() const { return ensureCalculated().timeFraction; }
+ double startTime() const { return m_startTime; }
const Player* player() const { return m_player; }
-
+ Player* player() { return m_player; }
const Timing& specified() const { return m_specified; }
protected:
@@ -90,13 +92,24 @@ protected:
// When TimedItem receives a new inherited time via updateInheritedTime
// it will (if necessary) recalculate timings and (if necessary) call
// updateChildrenAndEffects.
- void updateInheritedTime(double inheritedTime) const;
- virtual void updateChildrenAndEffects(bool wasInEffect) const = 0;
- virtual double intrinsicIterationDuration() const { return 0; };
- virtual void willDetach() = 0;
+ // Returns whether style recalc was triggered.
+ bool updateInheritedTime(double inheritedTime) const;
+ void invalidate() const { m_needsUpdate = true; };
private:
- void attach(Player* player) { m_player = player; };
+ // Returns whether style recalc was triggered.
+ virtual bool updateChildrenAndEffects() const = 0;
+ virtual double intrinsicIterationDuration() const { return 0; };
+ virtual double calculateTimeToEffectChange(double localTime, double timeToNextIteration) const = 0;
+ virtual void didAttach() { };
+ virtual void willDetach() { };
+
+ void attach(Player* player)
+ {
+ m_player = player;
+ didAttach();
+ };
+
void detach()
{
ASSERT(m_player);
@@ -120,8 +133,11 @@ private:
bool isCurrent;
bool isInEffect;
bool isInPlay;
+ double timeToEffectChange;
} m_calculated;
mutable bool m_isFirstSample;
+ mutable bool m_needsUpdate;
+ mutable double m_lastUpdateTime;
// FIXME: Should check the version and reinherit time if inconsistent.
const CalculatedTiming& ensureCalculated() const { return m_calculated; }
diff --git a/chromium/third_party/WebKit/Source/core/animation/TimedItemCalculations.h b/chromium/third_party/WebKit/Source/core/animation/TimedItemCalculations.h
index ef6d5eb1587..28a6228554a 100644
--- a/chromium/third_party/WebKit/Source/core/animation/TimedItemCalculations.h
+++ b/chromium/third_party/WebKit/Source/core/animation/TimedItemCalculations.h
@@ -33,11 +33,18 @@
#include "core/animation/TimedItem.h"
#include "core/animation/Timing.h"
-#include "core/platform/animation/AnimationUtilities.h"
+#include "platform/animation/AnimationUtilities.h"
#include "wtf/MathExtras.h"
namespace WebCore {
+static inline double multiplyZeroAlwaysGivesZero(double x, double y)
+{
+ ASSERT(!isNull(x));
+ ASSERT(!isNull(y));
+ return x && y ? x * y : 0;
+}
+
static inline TimedItem::Phase calculatePhase(double activeDuration, double localTime, const Timing& specified)
{
ASSERT(activeDuration >= 0);
@@ -100,20 +107,20 @@ static inline double calculateScaledActiveTime(double activeDuration, double act
if (isNull(activeTime))
return nullValue();
- ASSERT(activeTime >= 0);
-
- return (specified.playbackRate < 0 ? activeTime - activeDuration : activeTime) * specified.playbackRate + startOffset;
+ ASSERT(activeTime >= 0 && activeTime <= activeDuration);
+ return multiplyZeroAlwaysGivesZero(specified.playbackRate < 0 ? activeTime - activeDuration : activeTime, specified.playbackRate) + startOffset;
}
static inline bool endsOnIterationBoundary(double iterationCount, double iterationStart)
{
+ ASSERT(std::isfinite(iterationCount));
return !fmod(iterationCount + iterationStart, 1);
}
static inline double calculateIterationTime(double iterationDuration, double repeatedDuration, double scaledActiveTime, double startOffset, const Timing& specified)
{
- ASSERT(iterationDuration >= 0);
- ASSERT(repeatedDuration == iterationDuration * specified.iterationCount);
+ ASSERT(iterationDuration > 0);
+ ASSERT(repeatedDuration == multiplyZeroAlwaysGivesZero(iterationDuration, specified.iterationCount));
if (isNull(scaledActiveTime))
return nullValue();
@@ -121,18 +128,17 @@ static inline double calculateIterationTime(double iterationDuration, double rep
ASSERT(scaledActiveTime >= 0);
ASSERT(scaledActiveTime <= repeatedDuration + startOffset);
- if (!iterationDuration)
- return 0;
-
- if (scaledActiveTime - startOffset == repeatedDuration && specified.iterationCount && endsOnIterationBoundary(specified.iterationCount, specified.iterationStart))
+ if (!std::isfinite(scaledActiveTime)
+ || (scaledActiveTime - startOffset == repeatedDuration && specified.iterationCount && endsOnIterationBoundary(specified.iterationCount, specified.iterationStart)))
return iterationDuration;
+ ASSERT(std::isfinite(scaledActiveTime));
return fmod(scaledActiveTime, iterationDuration);
}
static inline double calculateCurrentIteration(double iterationDuration, double iterationTime, double scaledActiveTime, const Timing& specified)
{
- ASSERT(iterationDuration >= 0);
+ ASSERT(iterationDuration > 0);
ASSERT(isNull(iterationTime) || iterationTime >= 0);
if (isNull(scaledActiveTime))
@@ -145,9 +151,6 @@ static inline double calculateCurrentIteration(double iterationDuration, double
if (!scaledActiveTime)
return 0;
- if (!iterationDuration)
- return floor(specified.iterationStart + specified.iterationCount);
-
if (iterationTime == iterationDuration)
return specified.iterationStart + specified.iterationCount - 1;
@@ -183,9 +186,13 @@ static inline double calculateTransformedTime(double currentIteration, double it
double directedTime = calculateDirectedTime(currentIteration, iterationDuration, iterationTime, specified);
if (isNull(directedTime))
return nullValue();
- return specified.timingFunction ?
- iterationDuration * specified.timingFunction->evaluate(directedTime / iterationDuration, accuracyForDuration(iterationDuration)) :
- directedTime;
+ if (!std::isfinite(iterationDuration))
+ return directedTime;
+ double timeFraction = directedTime / iterationDuration;
+ ASSERT(timeFraction >= 0 && timeFraction <= 1);
+ return specified.timingFunction
+ ? multiplyZeroAlwaysGivesZero(iterationDuration, specified.timingFunction->evaluate(timeFraction, accuracyForDuration(iterationDuration)))
+ : directedTime;
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/animation/TimedItemCalculationsTest.cpp b/chromium/third_party/WebKit/Source/core/animation/TimedItemCalculationsTest.cpp
index 734dd7ec093..6e053cdde8f 100644
--- a/chromium/third_party/WebKit/Source/core/animation/TimedItemCalculationsTest.cpp
+++ b/chromium/third_party/WebKit/Source/core/animation/TimedItemCalculationsTest.cpp
@@ -37,183 +37,191 @@ using namespace WebCore;
namespace {
-TEST(TimedItemCalculations, ActiveTime)
+TEST(AnimationTimedItemCalculationsTest, ActiveTime)
{
Timing timing;
- // calculateActiveTime(activeDuration, localTime, startTime)
+ // calculateActiveTime(activeDuration, localTime, parentPhase, phase, timing)
// Before Phase
timing.startDelay = 10;
timing.fillMode = Timing::FillModeForwards;
- ASSERT_TRUE(isNull(calculateActiveTime(20, 0, TimedItem::PhaseActive, TimedItem::PhaseBefore, timing)));
+ EXPECT_TRUE(isNull(calculateActiveTime(20, 0, TimedItem::PhaseActive, TimedItem::PhaseBefore, timing)));
timing.fillMode = Timing::FillModeNone;
- ASSERT_TRUE(isNull(calculateActiveTime(20, 0, TimedItem::PhaseActive, TimedItem::PhaseBefore, timing)));
+ EXPECT_TRUE(isNull(calculateActiveTime(20, 0, TimedItem::PhaseActive, TimedItem::PhaseBefore, timing)));
timing.fillMode = Timing::FillModeBackwards;
- ASSERT_EQ(0, calculateActiveTime(20, 0, TimedItem::PhaseActive, TimedItem::PhaseBefore, timing));
+ EXPECT_EQ(0, calculateActiveTime(20, 0, TimedItem::PhaseActive, TimedItem::PhaseBefore, timing));
timing.fillMode = Timing::FillModeBoth;
- ASSERT_EQ(0, calculateActiveTime(20, 0, TimedItem::PhaseActive, TimedItem::PhaseBefore, timing));
+ EXPECT_EQ(0, calculateActiveTime(20, 0, TimedItem::PhaseActive, TimedItem::PhaseBefore, timing));
// Active Phase
timing.startDelay = 10;
// Active, and parent Before
timing.fillMode = Timing::FillModeNone;
- ASSERT_TRUE(isNull(calculateActiveTime(20, 15, TimedItem::PhaseBefore, TimedItem::PhaseActive, timing)));
+ EXPECT_TRUE(isNull(calculateActiveTime(20, 15, TimedItem::PhaseBefore, TimedItem::PhaseActive, timing)));
timing.fillMode = Timing::FillModeForwards;
- ASSERT_TRUE(isNull(calculateActiveTime(20, 15, TimedItem::PhaseBefore, TimedItem::PhaseActive, timing)));
+ EXPECT_TRUE(isNull(calculateActiveTime(20, 15, TimedItem::PhaseBefore, TimedItem::PhaseActive, timing)));
// Active, and parent After
timing.fillMode = Timing::FillModeNone;
- ASSERT_TRUE(isNull(calculateActiveTime(20, 15, TimedItem::PhaseAfter, TimedItem::PhaseActive, timing)));
+ EXPECT_TRUE(isNull(calculateActiveTime(20, 15, TimedItem::PhaseAfter, TimedItem::PhaseActive, timing)));
timing.fillMode = Timing::FillModeBackwards;
- ASSERT_TRUE(isNull(calculateActiveTime(20, 15, TimedItem::PhaseAfter, TimedItem::PhaseActive, timing)));
+ EXPECT_TRUE(isNull(calculateActiveTime(20, 15, TimedItem::PhaseAfter, TimedItem::PhaseActive, timing)));
// Active, and parent Active
timing.fillMode = Timing::FillModeForwards;
- ASSERT_EQ(5, calculateActiveTime(20, 15, TimedItem::PhaseActive, TimedItem::PhaseActive, timing));
+ EXPECT_EQ(5, calculateActiveTime(20, 15, TimedItem::PhaseActive, TimedItem::PhaseActive, timing));
// After Phase
timing.startDelay = 10;
timing.fillMode = Timing::FillModeForwards;
- ASSERT_EQ(21, calculateActiveTime(21, 45, TimedItem::PhaseActive, TimedItem::PhaseAfter, timing));
+ EXPECT_EQ(21, calculateActiveTime(21, 45, TimedItem::PhaseActive, TimedItem::PhaseAfter, timing));
timing.fillMode = Timing::FillModeBoth;
- ASSERT_EQ(21, calculateActiveTime(21, 45, TimedItem::PhaseActive, TimedItem::PhaseAfter, timing));
+ EXPECT_EQ(21, calculateActiveTime(21, 45, TimedItem::PhaseActive, TimedItem::PhaseAfter, timing));
timing.fillMode = Timing::FillModeBackwards;
- ASSERT_TRUE(isNull(calculateActiveTime(21, 45, TimedItem::PhaseActive, TimedItem::PhaseAfter, timing)));
+ EXPECT_TRUE(isNull(calculateActiveTime(21, 45, TimedItem::PhaseActive, TimedItem::PhaseAfter, timing)));
timing.fillMode = Timing::FillModeNone;
- ASSERT_TRUE(isNull(calculateActiveTime(21, 45, TimedItem::PhaseActive, TimedItem::PhaseAfter, timing)));
+ EXPECT_TRUE(isNull(calculateActiveTime(21, 45, TimedItem::PhaseActive, TimedItem::PhaseAfter, timing)));
// None
- ASSERT_TRUE(isNull(calculateActiveTime(32, nullValue(), TimedItem::PhaseNone, TimedItem::PhaseNone, timing)));
+ EXPECT_TRUE(isNull(calculateActiveTime(32, nullValue(), TimedItem::PhaseNone, TimedItem::PhaseNone, timing)));
}
-TEST(TimedItemCalculations, ScaledActiveTime)
+TEST(AnimationTimedItemCalculationsTest, ScaledActiveTime)
{
Timing timing;
- // calculateScaledActiveTime(activeDuration, activeTime, startOffset)
+ // calculateScaledActiveTime(activeDuration, activeTime, startOffset, timing)
// if the active time is null
- ASSERT_TRUE(isNull(calculateScaledActiveTime(4, nullValue(), 5, timing)));
+ EXPECT_TRUE(isNull(calculateScaledActiveTime(4, nullValue(), 5, timing)));
// if the playback rate is negative
timing.playbackRate = -1;
- ASSERT_EQ(-5, calculateScaledActiveTime(10, 20, 5, timing));
+ EXPECT_EQ(35, calculateScaledActiveTime(40, 10, 5, timing));
// otherwise
timing.playbackRate = 0;
- ASSERT_EQ(5, calculateScaledActiveTime(10, 20, 5, timing));
+ EXPECT_EQ(5, calculateScaledActiveTime(40, 10, 5, timing));
timing.playbackRate = 1;
- ASSERT_EQ(25, calculateScaledActiveTime(10, 20, 5, timing));
+ EXPECT_EQ(15, calculateScaledActiveTime(40, 10, 5, timing));
+
+ // infinte activeTime
+ timing.playbackRate = 0;
+ EXPECT_EQ(0, calculateScaledActiveTime(std::numeric_limits<double>::infinity(), std::numeric_limits<double>::infinity(), 0, timing));
+ timing.playbackRate = 1;
+ EXPECT_EQ(std::numeric_limits<double>::infinity(), calculateScaledActiveTime(std::numeric_limits<double>::infinity(), std::numeric_limits<double>::infinity(), 0, timing));
}
-TEST(TimedItemCalculations, IterationTime)
+TEST(AnimationTimedItemCalculationsTest, IterationTime)
{
Timing timing;
- // calculateIterationTime(iterationDuration, repeatedDuration, scaledActiveTime, startOffset)
+ // calculateIterationTime(iterationDuration, repeatedDuration, scaledActiveTime, startOffset, timing)
// if the scaled active time is null
- ASSERT_TRUE(isNull(calculateIterationTime(1, 1, nullValue(), 1, timing)));
-
- // if the iteration duration is zero
- ASSERT_EQ(0, calculateIterationTime(0, 0, 0, 4, timing));
+ EXPECT_TRUE(isNull(calculateIterationTime(1, 1, nullValue(), 1, timing)));
// if (complex-conditions)...
- ASSERT_EQ(12, calculateIterationTime(12, 12, 12, 0, timing));
+ EXPECT_EQ(12, calculateIterationTime(12, 12, 12, 0, timing));
// otherwise
timing.iterationCount = 10;
- ASSERT_EQ(5, calculateIterationTime(10, 100, 25, 4, timing));
- ASSERT_EQ(7, calculateIterationTime(11, 110, 29, 1, timing));
+ EXPECT_EQ(5, calculateIterationTime(10, 100, 25, 4, timing));
+ EXPECT_EQ(7, calculateIterationTime(11, 110, 29, 1, timing));
timing.iterationStart = 1.1;
- ASSERT_EQ(8, calculateIterationTime(12, 120, 20, 7, timing));
+ EXPECT_EQ(8, calculateIterationTime(12, 120, 20, 7, timing));
}
-TEST(TimedItemCalculations, CurrentIteration)
+TEST(AnimationTimedItemCalculationsTest, CurrentIteration)
{
Timing timing;
- // calculateCurrentIteration(iterationDuration, iterationTime, scaledActiveTime)
+ // calculateCurrentIteration(iterationDuration, iterationTime, scaledActiveTime, timing)
// if the scaled active time is null
- ASSERT_TRUE(isNull(calculateCurrentIteration(1, 1, nullValue(), timing)));
+ EXPECT_TRUE(isNull(calculateCurrentIteration(1, 1, nullValue(), timing)));
// if the scaled active time is zero
- ASSERT_EQ(0, calculateCurrentIteration(1, 1, 0, timing));
-
- // if iterationDuration is zero
- ASSERT_EQ(1, calculateCurrentIteration(0, 0, 9, timing));
+ EXPECT_EQ(0, calculateCurrentIteration(1, 1, 0, timing));
// if the iteration time equals the iteration duration
timing.iterationStart = 4;
timing.iterationCount = 7;
- ASSERT_EQ(10, calculateCurrentIteration(5, 5, 9, timing));
+ EXPECT_EQ(10, calculateCurrentIteration(5, 5, 9, timing));
// otherwise
- ASSERT_EQ(3, calculateCurrentIteration(3.2, 3.1, 10, timing));
+ EXPECT_EQ(3, calculateCurrentIteration(3.2, 3.1, 10, timing));
}
-TEST(TimedItemCalculations, DirectedTime)
+TEST(AnimationTimedItemCalculationsTest, DirectedTime)
{
Timing timing;
- // calculateDirectedTime(currentIteration, iterationDuration, iterationTime)
+ // calculateDirectedTime(currentIteration, iterationDuration, iterationTime, timing)
// if the iteration time is null
- ASSERT_TRUE(isNull(calculateDirectedTime(1, 2, nullValue(), timing)));
+ EXPECT_TRUE(isNull(calculateDirectedTime(1, 2, nullValue(), timing)));
// forwards
- ASSERT_EQ(17, calculateDirectedTime(0, 20, 17, timing));
- ASSERT_EQ(17, calculateDirectedTime(1, 20, 17, timing));
+ EXPECT_EQ(17, calculateDirectedTime(0, 20, 17, timing));
+ EXPECT_EQ(17, calculateDirectedTime(1, 20, 17, timing));
timing.direction = Timing::PlaybackDirectionAlternate;
- ASSERT_EQ(17, calculateDirectedTime(0, 20, 17, timing));
- ASSERT_EQ(17, calculateDirectedTime(2, 20, 17, timing));
+ EXPECT_EQ(17, calculateDirectedTime(0, 20, 17, timing));
+ EXPECT_EQ(17, calculateDirectedTime(2, 20, 17, timing));
timing.direction = Timing::PlaybackDirectionAlternateReverse;
- ASSERT_EQ(17, calculateDirectedTime(1, 20, 17, timing));
- ASSERT_EQ(17, calculateDirectedTime(3, 20, 17, timing));
+ EXPECT_EQ(17, calculateDirectedTime(1, 20, 17, timing));
+ EXPECT_EQ(17, calculateDirectedTime(3, 20, 17, timing));
// reverse
timing.direction = Timing::PlaybackDirectionReverse;
- ASSERT_EQ(3, calculateDirectedTime(0, 20, 17, timing));
- ASSERT_EQ(3, calculateDirectedTime(1, 20, 17, timing));
+ EXPECT_EQ(3, calculateDirectedTime(0, 20, 17, timing));
+ EXPECT_EQ(3, calculateDirectedTime(1, 20, 17, timing));
timing.direction = Timing::PlaybackDirectionAlternate;
- ASSERT_EQ(3, calculateDirectedTime(1, 20, 17, timing));
- ASSERT_EQ(3, calculateDirectedTime(3, 20, 17, timing));
+ EXPECT_EQ(3, calculateDirectedTime(1, 20, 17, timing));
+ EXPECT_EQ(3, calculateDirectedTime(3, 20, 17, timing));
timing.direction = Timing::PlaybackDirectionAlternateReverse;
- ASSERT_EQ(3, calculateDirectedTime(0, 20, 17, timing));
- ASSERT_EQ(3, calculateDirectedTime(2, 20, 17, timing));
+ EXPECT_EQ(3, calculateDirectedTime(0, 20, 17, timing));
+ EXPECT_EQ(3, calculateDirectedTime(2, 20, 17, timing));
}
-TEST(TimedItemCalculations, TransformedTime)
+TEST(AnimationTimedItemCalculationsTest, TransformedTime)
{
Timing timing;
- // calculateTransformedTime(currentIteration, iterationDuration, iterationTime)
+ // calculateTransformedTime(currentIteration, iterationDuration, iterationTime, timing)
// Iteration time is null
- ASSERT_TRUE(isNull(calculateTransformedTime(1, 2, nullValue(), timing)));
+ EXPECT_TRUE(isNull(calculateTransformedTime(1, 2, nullValue(), timing)));
// PlaybackDirectionForwards
- ASSERT_EQ(12, calculateTransformedTime(0, 20, 12, timing));
- ASSERT_EQ(12, calculateTransformedTime(1, 20, 12, timing));
+ EXPECT_EQ(12, calculateTransformedTime(0, 20, 12, timing));
+ EXPECT_EQ(12, calculateTransformedTime(1, 20, 12, timing));
// PlaybackDirectionForwards with timing function
timing.timingFunction = StepsTimingFunction::create(4, false /* stepAtStart */);
- ASSERT_EQ(10, calculateTransformedTime(0, 20, 12, timing));
- ASSERT_EQ(10, calculateTransformedTime(1, 20, 12, timing));
+ EXPECT_EQ(10, calculateTransformedTime(0, 20, 12, timing));
+ EXPECT_EQ(10, calculateTransformedTime(1, 20, 12, timing));
// PlaybackDirectionReverse
timing.timingFunction = 0;
timing.direction = Timing::PlaybackDirectionReverse;
- ASSERT_EQ(8, calculateTransformedTime(0, 20, 12, timing));
- ASSERT_EQ(8, calculateTransformedTime(1, 20, 12, timing));
+ EXPECT_EQ(8, calculateTransformedTime(0, 20, 12, timing));
+ EXPECT_EQ(8, calculateTransformedTime(1, 20, 12, timing));
// PlaybackDirectionReverse with timing function
timing.timingFunction = StepsTimingFunction::create(4, false /* stepAtStart */);
- ASSERT_EQ(5, calculateTransformedTime(0, 20, 12, timing));
- ASSERT_EQ(5, calculateTransformedTime(1, 20, 12, timing));
+ EXPECT_EQ(5, calculateTransformedTime(0, 20, 12, timing));
+ EXPECT_EQ(5, calculateTransformedTime(1, 20, 12, timing));
// Timing function when directed time is null.
- ASSERT_TRUE(isNull(calculateTransformedTime(1, 2, nullValue(), timing)));
+ EXPECT_TRUE(isNull(calculateTransformedTime(1, 2, nullValue(), timing)));
+
+ // Timing function when iterationDuration is infinity
+ timing.direction = Timing::PlaybackDirectionNormal;
+ EXPECT_EQ(0, calculateTransformedTime(0, std::numeric_limits<double>::infinity(), 0, timing));
+ EXPECT_EQ(1, calculateTransformedTime(0, std::numeric_limits<double>::infinity(), 1, timing));
+ timing.direction = Timing::PlaybackDirectionReverse;
+ EXPECT_EQ(std::numeric_limits<double>::infinity(), calculateTransformedTime(0, std::numeric_limits<double>::infinity(), 0, timing));
+ EXPECT_EQ(std::numeric_limits<double>::infinity(), calculateTransformedTime(0, std::numeric_limits<double>::infinity(), 1, timing));
}
}
diff --git a/chromium/third_party/WebKit/Source/core/animation/TimedItemTest.cpp b/chromium/third_party/WebKit/Source/core/animation/TimedItemTest.cpp
index 45caec489a3..6bd34ab67cc 100644
--- a/chromium/third_party/WebKit/Source/core/animation/TimedItemTest.cpp
+++ b/chromium/third_party/WebKit/Source/core/animation/TimedItemTest.cpp
@@ -75,9 +75,29 @@ public:
TimedItem::updateInheritedTime(time);
}
- void updateChildrenAndEffects(bool wasActiveOrInEffect) const FINAL OVERRIDE { }
+ bool updateChildrenAndEffects() const OVERRIDE { return false; }
void willDetach() { }
TestTimedItemEventDelegate* eventDelegate() { return m_eventDelegate; }
+ double calculateTimeToEffectChange(double localTime, double timeToNextIteration) const OVERRIDE
+ {
+ m_localTime = localTime;
+ m_timeToNextIteration = timeToNextIteration;
+ return -1;
+ }
+
+ double takeLocalTime()
+ {
+ const double result = m_localTime;
+ m_localTime = nullValue();
+ return result;
+ }
+
+ double takeTimeToNextIteration()
+ {
+ const double result = m_timeToNextIteration;
+ m_timeToNextIteration = nullValue();
+ return result;
+ }
private:
TestTimedItem(const Timing& specified, TestTimedItemEventDelegate* eventDelegate)
@@ -87,63 +107,65 @@ private:
}
TestTimedItemEventDelegate* m_eventDelegate;
+ mutable double m_localTime;
+ mutable double m_timeToNextIteration;
};
-TEST(TimedItem, Sanity)
+TEST(AnimationTimedItemTest, Sanity)
{
Timing timing;
timing.hasIterationDuration = true;
timing.iterationDuration = 2;
RefPtr<TestTimedItem> timedItem = TestTimedItem::create(timing);
- ASSERT_EQ(0, timedItem->startTime());
+ EXPECT_EQ(0, timedItem->startTime());
timedItem->updateInheritedTime(0);
- ASSERT_EQ(TimedItem::PhaseActive, timedItem->phase());
- ASSERT_TRUE(timedItem->isInPlay());
- ASSERT_TRUE(timedItem->isCurrent());
- ASSERT_TRUE(timedItem->isInEffect());
- ASSERT_EQ(0, timedItem->currentIteration());
- ASSERT_EQ(0, timedItem->startTime());
- ASSERT_EQ(2, timedItem->activeDuration());
- ASSERT_EQ(0, timedItem->timeFraction());
+ EXPECT_EQ(TimedItem::PhaseActive, timedItem->phase());
+ EXPECT_TRUE(timedItem->isInPlay());
+ EXPECT_TRUE(timedItem->isCurrent());
+ EXPECT_TRUE(timedItem->isInEffect());
+ EXPECT_EQ(0, timedItem->currentIteration());
+ EXPECT_EQ(0, timedItem->startTime());
+ EXPECT_EQ(2, timedItem->activeDuration());
+ EXPECT_EQ(0, timedItem->timeFraction());
timedItem->updateInheritedTime(1);
- ASSERT_EQ(TimedItem::PhaseActive, timedItem->phase());
- ASSERT_TRUE(timedItem->isInPlay());
- ASSERT_TRUE(timedItem->isCurrent());
- ASSERT_TRUE(timedItem->isInEffect());
- ASSERT_EQ(0, timedItem->currentIteration());
- ASSERT_EQ(0, timedItem->startTime());
- ASSERT_EQ(2, timedItem->activeDuration());
- ASSERT_EQ(0.5, timedItem->timeFraction());
+ EXPECT_EQ(TimedItem::PhaseActive, timedItem->phase());
+ EXPECT_TRUE(timedItem->isInPlay());
+ EXPECT_TRUE(timedItem->isCurrent());
+ EXPECT_TRUE(timedItem->isInEffect());
+ EXPECT_EQ(0, timedItem->currentIteration());
+ EXPECT_EQ(0, timedItem->startTime());
+ EXPECT_EQ(2, timedItem->activeDuration());
+ EXPECT_EQ(0.5, timedItem->timeFraction());
timedItem->updateInheritedTime(2);
- ASSERT_EQ(TimedItem::PhaseAfter, timedItem->phase());
- ASSERT_FALSE(timedItem->isInPlay());
- ASSERT_FALSE(timedItem->isCurrent());
- ASSERT_TRUE(timedItem->isInEffect());
- ASSERT_EQ(0, timedItem->currentIteration());
- ASSERT_EQ(0, timedItem->startTime());
- ASSERT_EQ(2, timedItem->activeDuration());
- ASSERT_EQ(1, timedItem->timeFraction());
+ EXPECT_EQ(TimedItem::PhaseAfter, timedItem->phase());
+ EXPECT_FALSE(timedItem->isInPlay());
+ EXPECT_FALSE(timedItem->isCurrent());
+ EXPECT_TRUE(timedItem->isInEffect());
+ EXPECT_EQ(0, timedItem->currentIteration());
+ EXPECT_EQ(0, timedItem->startTime());
+ EXPECT_EQ(2, timedItem->activeDuration());
+ EXPECT_EQ(1, timedItem->timeFraction());
timedItem->updateInheritedTime(3);
- ASSERT_EQ(TimedItem::PhaseAfter, timedItem->phase());
- ASSERT_FALSE(timedItem->isInPlay());
- ASSERT_FALSE(timedItem->isCurrent());
- ASSERT_TRUE(timedItem->isInEffect());
- ASSERT_EQ(0, timedItem->currentIteration());
- ASSERT_EQ(0, timedItem->startTime());
- ASSERT_EQ(2, timedItem->activeDuration());
- ASSERT_EQ(1, timedItem->timeFraction());
+ EXPECT_EQ(TimedItem::PhaseAfter, timedItem->phase());
+ EXPECT_FALSE(timedItem->isInPlay());
+ EXPECT_FALSE(timedItem->isCurrent());
+ EXPECT_TRUE(timedItem->isInEffect());
+ EXPECT_EQ(0, timedItem->currentIteration());
+ EXPECT_EQ(0, timedItem->startTime());
+ EXPECT_EQ(2, timedItem->activeDuration());
+ EXPECT_EQ(1, timedItem->timeFraction());
}
-TEST(TimedItem, FillForwards)
+TEST(AnimationTimedItemTest, FillForwards)
{
Timing timing;
timing.hasIterationDuration = true;
@@ -151,13 +173,13 @@ TEST(TimedItem, FillForwards)
RefPtr<TestTimedItem> timedItem = TestTimedItem::create(timing);
timedItem->updateInheritedTime(-1);
- ASSERT_TRUE(isNull(timedItem->timeFraction()));
+ EXPECT_TRUE(isNull(timedItem->timeFraction()));
timedItem->updateInheritedTime(2);
- ASSERT_EQ(1, timedItem->timeFraction());
+ EXPECT_EQ(1, timedItem->timeFraction());
}
-TEST(TimedItem, FillBackwards)
+TEST(AnimationTimedItemTest, FillBackwards)
{
Timing timing;
timing.hasIterationDuration = true;
@@ -166,13 +188,13 @@ TEST(TimedItem, FillBackwards)
RefPtr<TestTimedItem> timedItem = TestTimedItem::create(timing);
timedItem->updateInheritedTime(-1);
- ASSERT_EQ(0, timedItem->timeFraction());
+ EXPECT_EQ(0, timedItem->timeFraction());
timedItem->updateInheritedTime(2);
- ASSERT_TRUE(isNull(timedItem->timeFraction()));
+ EXPECT_TRUE(isNull(timedItem->timeFraction()));
}
-TEST(TimedItem, FillBoth)
+TEST(AnimationTimedItemTest, FillBoth)
{
Timing timing;
timing.hasIterationDuration = true;
@@ -181,13 +203,13 @@ TEST(TimedItem, FillBoth)
RefPtr<TestTimedItem> timedItem = TestTimedItem::create(timing);
timedItem->updateInheritedTime(-1);
- ASSERT_EQ(0, timedItem->timeFraction());
+ EXPECT_EQ(0, timedItem->timeFraction());
timedItem->updateInheritedTime(2);
- ASSERT_EQ(1, timedItem->timeFraction());
+ EXPECT_EQ(1, timedItem->timeFraction());
}
-TEST(TimedItem, StartDelay)
+TEST(AnimationTimedItemTest, StartDelay)
{
Timing timing;
timing.hasIterationDuration = true;
@@ -196,16 +218,35 @@ TEST(TimedItem, StartDelay)
RefPtr<TestTimedItem> timedItem = TestTimedItem::create(timing);
timedItem->updateInheritedTime(0);
- ASSERT_TRUE(isNull(timedItem->timeFraction()));
+ EXPECT_TRUE(isNull(timedItem->timeFraction()));
timedItem->updateInheritedTime(0.5);
- ASSERT_EQ(0, timedItem->timeFraction());
+ EXPECT_EQ(0, timedItem->timeFraction());
timedItem->updateInheritedTime(1.5);
- ASSERT_EQ(1, timedItem->timeFraction());
+ EXPECT_EQ(1, timedItem->timeFraction());
+}
+
+TEST(AnimationTimedItemTest, ZeroIteration)
+{
+ Timing timing;
+ timing.hasIterationDuration = true;
+ timing.iterationDuration = 1;
+ timing.iterationCount = 0;
+ RefPtr<TestTimedItem> timedItem = TestTimedItem::create(timing);
+
+ timedItem->updateInheritedTime(-1);
+ EXPECT_EQ(0, timedItem->activeDuration());
+ EXPECT_TRUE(isNull(timedItem->currentIteration()));
+ EXPECT_TRUE(isNull(timedItem->timeFraction()));
+
+ timedItem->updateInheritedTime(0);
+ EXPECT_EQ(0, timedItem->activeDuration());
+ EXPECT_EQ(0, timedItem->currentIteration());
+ EXPECT_EQ(0, timedItem->timeFraction());
}
-TEST(TimedItem, InfiniteIteration)
+TEST(AnimationTimedItemTest, InfiniteIteration)
{
Timing timing;
timing.hasIterationDuration = true;
@@ -214,17 +255,17 @@ TEST(TimedItem, InfiniteIteration)
RefPtr<TestTimedItem> timedItem = TestTimedItem::create(timing);
timedItem->updateInheritedTime(-1);
- ASSERT_TRUE(isNull(timedItem->currentIteration()));
- ASSERT_TRUE(isNull(timedItem->timeFraction()));
+ EXPECT_TRUE(isNull(timedItem->currentIteration()));
+ EXPECT_TRUE(isNull(timedItem->timeFraction()));
- ASSERT_EQ(std::numeric_limits<double>::infinity(), timedItem->activeDuration());
+ EXPECT_EQ(std::numeric_limits<double>::infinity(), timedItem->activeDuration());
timedItem->updateInheritedTime(0);
- ASSERT_EQ(0, timedItem->currentIteration());
- ASSERT_EQ(0, timedItem->timeFraction());
+ EXPECT_EQ(0, timedItem->currentIteration());
+ EXPECT_EQ(0, timedItem->timeFraction());
}
-TEST(TimedItem, Iteration)
+TEST(AnimationTimedItemTest, Iteration)
{
Timing timing;
timing.iterationCount = 2;
@@ -233,27 +274,27 @@ TEST(TimedItem, Iteration)
RefPtr<TestTimedItem> timedItem = TestTimedItem::create(timing);
timedItem->updateInheritedTime(0);
- ASSERT_EQ(0, timedItem->currentIteration());
- ASSERT_EQ(0, timedItem->timeFraction());
+ EXPECT_EQ(0, timedItem->currentIteration());
+ EXPECT_EQ(0, timedItem->timeFraction());
timedItem->updateInheritedTime(1);
- ASSERT_EQ(0, timedItem->currentIteration());
- ASSERT_EQ(0.5, timedItem->timeFraction());
+ EXPECT_EQ(0, timedItem->currentIteration());
+ EXPECT_EQ(0.5, timedItem->timeFraction());
timedItem->updateInheritedTime(2);
- ASSERT_EQ(1, timedItem->currentIteration());
- ASSERT_EQ(0, timedItem->timeFraction());
+ EXPECT_EQ(1, timedItem->currentIteration());
+ EXPECT_EQ(0, timedItem->timeFraction());
timedItem->updateInheritedTime(2);
- ASSERT_EQ(1, timedItem->currentIteration());
- ASSERT_EQ(0, timedItem->timeFraction());
+ EXPECT_EQ(1, timedItem->currentIteration());
+ EXPECT_EQ(0, timedItem->timeFraction());
timedItem->updateInheritedTime(5);
- ASSERT_EQ(1, timedItem->currentIteration());
- ASSERT_EQ(1, timedItem->timeFraction());
+ EXPECT_EQ(1, timedItem->currentIteration());
+ EXPECT_EQ(1, timedItem->timeFraction());
}
-TEST(TimedItem, IterationStart)
+TEST(AnimationTimedItemTest, IterationStart)
{
Timing timing;
timing.iterationStart = 1.2;
@@ -264,19 +305,19 @@ TEST(TimedItem, IterationStart)
RefPtr<TestTimedItem> timedItem = TestTimedItem::create(timing);
timedItem->updateInheritedTime(-1);
- ASSERT_EQ(1, timedItem->currentIteration());
- ASSERT_NEAR(0.2, timedItem->timeFraction(), 0.000000000000001);
+ EXPECT_EQ(1, timedItem->currentIteration());
+ EXPECT_NEAR(0.2, timedItem->timeFraction(), 0.000000000000001);
timedItem->updateInheritedTime(0);
- ASSERT_EQ(1, timedItem->currentIteration());
- ASSERT_NEAR(0.2, timedItem->timeFraction(), 0.000000000000001);
+ EXPECT_EQ(1, timedItem->currentIteration());
+ EXPECT_NEAR(0.2, timedItem->timeFraction(), 0.000000000000001);
timedItem->updateInheritedTime(10);
- ASSERT_EQ(3, timedItem->currentIteration());
- ASSERT_NEAR(0.4, timedItem->timeFraction(), 0.000000000000001);
+ EXPECT_EQ(3, timedItem->currentIteration());
+ EXPECT_NEAR(0.4, timedItem->timeFraction(), 0.000000000000001);
}
-TEST(TimedItem, IterationAlternate)
+TEST(AnimationTimedItemTest, IterationAlternate)
{
Timing timing;
timing.iterationCount = 10;
@@ -286,19 +327,19 @@ TEST(TimedItem, IterationAlternate)
RefPtr<TestTimedItem> timedItem = TestTimedItem::create(timing);
timedItem->updateInheritedTime(0.75);
- ASSERT_EQ(0, timedItem->currentIteration());
- ASSERT_EQ(0.75, timedItem->timeFraction());
+ EXPECT_EQ(0, timedItem->currentIteration());
+ EXPECT_EQ(0.75, timedItem->timeFraction());
timedItem->updateInheritedTime(1.75);
- ASSERT_EQ(1, timedItem->currentIteration());
- ASSERT_EQ(0.25, timedItem->timeFraction());
+ EXPECT_EQ(1, timedItem->currentIteration());
+ EXPECT_EQ(0.25, timedItem->timeFraction());
timedItem->updateInheritedTime(2.75);
- ASSERT_EQ(2, timedItem->currentIteration());
- ASSERT_EQ(0.75, timedItem->timeFraction());
+ EXPECT_EQ(2, timedItem->currentIteration());
+ EXPECT_EQ(0.75, timedItem->timeFraction());
}
-TEST(TimedItem, IterationAlternateReverse)
+TEST(AnimationTimedItemTest, IterationAlternateReverse)
{
Timing timing;
timing.iterationCount = 10;
@@ -308,112 +349,112 @@ TEST(TimedItem, IterationAlternateReverse)
RefPtr<TestTimedItem> timedItem = TestTimedItem::create(timing);
timedItem->updateInheritedTime(0.75);
- ASSERT_EQ(0, timedItem->currentIteration());
- ASSERT_EQ(0.25, timedItem->timeFraction());
+ EXPECT_EQ(0, timedItem->currentIteration());
+ EXPECT_EQ(0.25, timedItem->timeFraction());
timedItem->updateInheritedTime(1.75);
- ASSERT_EQ(1, timedItem->currentIteration());
- ASSERT_EQ(0.75, timedItem->timeFraction());
+ EXPECT_EQ(1, timedItem->currentIteration());
+ EXPECT_EQ(0.75, timedItem->timeFraction());
timedItem->updateInheritedTime(2.75);
- ASSERT_EQ(2, timedItem->currentIteration());
- ASSERT_EQ(0.25, timedItem->timeFraction());
+ EXPECT_EQ(2, timedItem->currentIteration());
+ EXPECT_EQ(0.25, timedItem->timeFraction());
}
-TEST(TimedItem, ZeroDurationSanity)
+TEST(AnimationTimedItemTest, ZeroDurationSanity)
{
Timing timing;
RefPtr<TestTimedItem> timedItem = TestTimedItem::create(timing);
- ASSERT_EQ(0, timedItem->startTime());
+ EXPECT_EQ(0, timedItem->startTime());
timedItem->updateInheritedTime(0);
- ASSERT_EQ(TimedItem::PhaseAfter, timedItem->phase());
- ASSERT_FALSE(timedItem->isInPlay());
- ASSERT_FALSE(timedItem->isCurrent());
- ASSERT_TRUE(timedItem->isInEffect());
- ASSERT_EQ(0, timedItem->currentIteration());
- ASSERT_EQ(0, timedItem->startTime());
- ASSERT_EQ(0, timedItem->activeDuration());
- ASSERT_EQ(1, timedItem->timeFraction());
+ EXPECT_EQ(TimedItem::PhaseAfter, timedItem->phase());
+ EXPECT_FALSE(timedItem->isInPlay());
+ EXPECT_FALSE(timedItem->isCurrent());
+ EXPECT_TRUE(timedItem->isInEffect());
+ EXPECT_EQ(0, timedItem->currentIteration());
+ EXPECT_EQ(0, timedItem->startTime());
+ EXPECT_EQ(0, timedItem->activeDuration());
+ EXPECT_EQ(1, timedItem->timeFraction());
timedItem->updateInheritedTime(1);
- ASSERT_EQ(TimedItem::PhaseAfter, timedItem->phase());
- ASSERT_FALSE(timedItem->isInPlay());
- ASSERT_FALSE(timedItem->isCurrent());
- ASSERT_TRUE(timedItem->isInEffect());
- ASSERT_EQ(0, timedItem->currentIteration());
- ASSERT_EQ(0, timedItem->startTime());
- ASSERT_EQ(0, timedItem->activeDuration());
- ASSERT_EQ(1, timedItem->timeFraction());
+ EXPECT_EQ(TimedItem::PhaseAfter, timedItem->phase());
+ EXPECT_FALSE(timedItem->isInPlay());
+ EXPECT_FALSE(timedItem->isCurrent());
+ EXPECT_TRUE(timedItem->isInEffect());
+ EXPECT_EQ(0, timedItem->currentIteration());
+ EXPECT_EQ(0, timedItem->startTime());
+ EXPECT_EQ(0, timedItem->activeDuration());
+ EXPECT_EQ(1, timedItem->timeFraction());
}
-TEST(TimedItem, ZeroDurationFillForwards)
+TEST(AnimationTimedItemTest, ZeroDurationFillForwards)
{
Timing timing;
RefPtr<TestTimedItem> timedItem = TestTimedItem::create(timing);
timedItem->updateInheritedTime(-1);
- ASSERT_TRUE(isNull(timedItem->timeFraction()));
+ EXPECT_TRUE(isNull(timedItem->timeFraction()));
timedItem->updateInheritedTime(0);
- ASSERT_EQ(1, timedItem->timeFraction());
+ EXPECT_EQ(1, timedItem->timeFraction());
timedItem->updateInheritedTime(1);
- ASSERT_EQ(1, timedItem->timeFraction());
+ EXPECT_EQ(1, timedItem->timeFraction());
}
-TEST(TimedItem, ZeroDurationFillBackwards)
+TEST(AnimationTimedItemTest, ZeroDurationFillBackwards)
{
Timing timing;
timing.fillMode = Timing::FillModeBackwards;
RefPtr<TestTimedItem> timedItem = TestTimedItem::create(timing);
timedItem->updateInheritedTime(-1);
- ASSERT_EQ(0, timedItem->timeFraction());
+ EXPECT_EQ(0, timedItem->timeFraction());
timedItem->updateInheritedTime(0);
- ASSERT_TRUE(isNull(timedItem->timeFraction()));
+ EXPECT_TRUE(isNull(timedItem->timeFraction()));
timedItem->updateInheritedTime(1);
- ASSERT_TRUE(isNull(timedItem->timeFraction()));
+ EXPECT_TRUE(isNull(timedItem->timeFraction()));
}
-TEST(TimedItem, ZeroDurationFillBoth)
+TEST(AnimationTimedItemTest, ZeroDurationFillBoth)
{
Timing timing;
timing.fillMode = Timing::FillModeBoth;
RefPtr<TestTimedItem> timedItem = TestTimedItem::create(timing);
timedItem->updateInheritedTime(-1);
- ASSERT_EQ(0, timedItem->timeFraction());
+ EXPECT_EQ(0, timedItem->timeFraction());
timedItem->updateInheritedTime(0);
- ASSERT_EQ(1, timedItem->timeFraction());
+ EXPECT_EQ(1, timedItem->timeFraction());
timedItem->updateInheritedTime(1);
- ASSERT_EQ(1, timedItem->timeFraction());
+ EXPECT_EQ(1, timedItem->timeFraction());
}
-TEST(TimedItem, ZeroDurationStartDelay)
+TEST(AnimationTimedItemTest, ZeroDurationStartDelay)
{
Timing timing;
timing.startDelay = 0.5;
RefPtr<TestTimedItem> timedItem = TestTimedItem::create(timing);
timedItem->updateInheritedTime(0);
- ASSERT_TRUE(isNull(timedItem->timeFraction()));
+ EXPECT_TRUE(isNull(timedItem->timeFraction()));
timedItem->updateInheritedTime(0.5);
- ASSERT_EQ(1, timedItem->timeFraction());
+ EXPECT_EQ(1, timedItem->timeFraction());
timedItem->updateInheritedTime(1.5);
- ASSERT_EQ(1, timedItem->timeFraction());
+ EXPECT_EQ(1, timedItem->timeFraction());
}
-TEST(TimedItem, ZeroDurationIterationStartAndCount)
+TEST(AnimationTimedItemTest, ZeroDurationIterationStartAndCount)
{
Timing timing;
timing.iterationStart = 0.1;
@@ -423,52 +464,53 @@ TEST(TimedItem, ZeroDurationIterationStartAndCount)
RefPtr<TestTimedItem> timedItem = TestTimedItem::create(timing);
timedItem->updateInheritedTime(0);
- ASSERT_EQ(0.1, timedItem->timeFraction());
+ EXPECT_EQ(0.1, timedItem->timeFraction());
timedItem->updateInheritedTime(0.3);
- ASSERT_DOUBLE_EQ(0.3, timedItem->timeFraction());
+ EXPECT_DOUBLE_EQ(0.3, timedItem->timeFraction());
timedItem->updateInheritedTime(1);
- ASSERT_DOUBLE_EQ(0.3, timedItem->timeFraction());
+ EXPECT_DOUBLE_EQ(0.3, timedItem->timeFraction());
}
-// FIXME: Needs specification work -- ASSERTION FAILED: activeDuration >= 0
-TEST(TimedItem, DISABLED_ZeroDurationInfiniteIteration)
+// FIXME: Needs specification work.
+TEST(AnimationTimedItemTest, ZeroDurationInfiniteIteration)
{
Timing timing;
timing.iterationCount = std::numeric_limits<double>::infinity();
RefPtr<TestTimedItem> timedItem = TestTimedItem::create(timing);
timedItem->updateInheritedTime(-1);
- ASSERT_TRUE(isNull(timedItem->currentIteration()));
- ASSERT_TRUE(isNull(timedItem->timeFraction()));
- ASSERT_TRUE(isNull(timedItem->activeDuration()));
+ EXPECT_EQ(0, timedItem->activeDuration());
+ EXPECT_TRUE(isNull(timedItem->currentIteration()));
+ EXPECT_TRUE(isNull(timedItem->timeFraction()));
timedItem->updateInheritedTime(0);
- ASSERT_EQ(std::numeric_limits<double>::infinity(), timedItem->currentIteration());
- ASSERT_EQ(1, timedItem->timeFraction());
+ EXPECT_EQ(0, timedItem->activeDuration());
+ EXPECT_EQ(std::numeric_limits<double>::infinity(), timedItem->currentIteration());
+ EXPECT_EQ(1, timedItem->timeFraction());
}
-TEST(TimedItem, ZeroDurationIteration)
+TEST(AnimationTimedItemTest, ZeroDurationIteration)
{
Timing timing;
timing.iterationCount = 2;
RefPtr<TestTimedItem> timedItem = TestTimedItem::create(timing);
timedItem->updateInheritedTime(-1);
- ASSERT_TRUE(isNull(timedItem->currentIteration()));
- ASSERT_TRUE(isNull(timedItem->timeFraction()));
+ EXPECT_TRUE(isNull(timedItem->currentIteration()));
+ EXPECT_TRUE(isNull(timedItem->timeFraction()));
timedItem->updateInheritedTime(0);
- ASSERT_EQ(1, timedItem->currentIteration());
- ASSERT_EQ(1, timedItem->timeFraction());
+ EXPECT_EQ(1, timedItem->currentIteration());
+ EXPECT_EQ(1, timedItem->timeFraction());
timedItem->updateInheritedTime(1);
- ASSERT_EQ(1, timedItem->currentIteration());
- ASSERT_EQ(1, timedItem->timeFraction());
+ EXPECT_EQ(1, timedItem->currentIteration());
+ EXPECT_EQ(1, timedItem->timeFraction());
}
-TEST(TimedItem, ZeroDurationIterationStart)
+TEST(AnimationTimedItemTest, ZeroDurationIterationStart)
{
Timing timing;
timing.iterationStart = 1.2;
@@ -477,19 +519,19 @@ TEST(TimedItem, ZeroDurationIterationStart)
RefPtr<TestTimedItem> timedItem = TestTimedItem::create(timing);
timedItem->updateInheritedTime(-1);
- ASSERT_EQ(1, timedItem->currentIteration());
- ASSERT_NEAR(0.2, timedItem->timeFraction(), 0.000000000000001);
+ EXPECT_EQ(1, timedItem->currentIteration());
+ EXPECT_NEAR(0.2, timedItem->timeFraction(), 0.000000000000001);
timedItem->updateInheritedTime(0);
- ASSERT_EQ(3, timedItem->currentIteration());
- ASSERT_NEAR(0.4, timedItem->timeFraction(), 0.000000000000001);
+ EXPECT_EQ(3, timedItem->currentIteration());
+ EXPECT_NEAR(0.4, timedItem->timeFraction(), 0.000000000000001);
timedItem->updateInheritedTime(10);
- ASSERT_EQ(3, timedItem->currentIteration());
- ASSERT_NEAR(0.4, timedItem->timeFraction(), 0.000000000000001);
+ EXPECT_EQ(3, timedItem->currentIteration());
+ EXPECT_NEAR(0.4, timedItem->timeFraction(), 0.000000000000001);
}
-TEST(TimedItem, ZeroDurationIterationAlternate)
+TEST(AnimationTimedItemTest, ZeroDurationIterationAlternate)
{
Timing timing;
timing.iterationCount = 2;
@@ -497,19 +539,19 @@ TEST(TimedItem, ZeroDurationIterationAlternate)
RefPtr<TestTimedItem> timedItem = TestTimedItem::create(timing);
timedItem->updateInheritedTime(-1);
- ASSERT_TRUE(isNull(timedItem->currentIteration()));
- ASSERT_TRUE(isNull(timedItem->timeFraction()));
+ EXPECT_TRUE(isNull(timedItem->currentIteration()));
+ EXPECT_TRUE(isNull(timedItem->timeFraction()));
timedItem->updateInheritedTime(0);
- ASSERT_EQ(1, timedItem->currentIteration());
- ASSERT_EQ(0, timedItem->timeFraction());
+ EXPECT_EQ(1, timedItem->currentIteration());
+ EXPECT_EQ(0, timedItem->timeFraction());
timedItem->updateInheritedTime(1);
- ASSERT_EQ(1, timedItem->currentIteration());
- ASSERT_EQ(0, timedItem->timeFraction());
+ EXPECT_EQ(1, timedItem->currentIteration());
+ EXPECT_EQ(0, timedItem->timeFraction());
}
-TEST(TimedItem, ZeroDurationIterationAlternateReverse)
+TEST(AnimationTimedItemTest, ZeroDurationIterationAlternateReverse)
{
Timing timing;
timing.iterationCount = 2;
@@ -517,19 +559,144 @@ TEST(TimedItem, ZeroDurationIterationAlternateReverse)
RefPtr<TestTimedItem> timedItem = TestTimedItem::create(timing);
timedItem->updateInheritedTime(-1);
- ASSERT_TRUE(isNull(timedItem->currentIteration()));
- ASSERT_TRUE(isNull(timedItem->timeFraction()));
+ EXPECT_TRUE(isNull(timedItem->currentIteration()));
+ EXPECT_TRUE(isNull(timedItem->timeFraction()));
+
+ timedItem->updateInheritedTime(0);
+ EXPECT_EQ(1, timedItem->currentIteration());
+ EXPECT_EQ(1, timedItem->timeFraction());
+
+ timedItem->updateInheritedTime(1);
+ EXPECT_EQ(1, timedItem->currentIteration());
+ EXPECT_EQ(1, timedItem->timeFraction());
+}
+
+TEST(AnimationTimedItemTest, InfiniteDurationSanity)
+{
+ Timing timing;
+ timing.hasIterationDuration = true;
+ timing.iterationDuration = std::numeric_limits<double>::infinity();
+ timing.iterationCount = 1;
+ RefPtr<TestTimedItem> timedItem = TestTimedItem::create(timing);
+
+ EXPECT_EQ(0, timedItem->startTime());
+
+ timedItem->updateInheritedTime(0);
+
+ EXPECT_EQ(std::numeric_limits<double>::infinity(), timedItem->activeDuration());
+ EXPECT_EQ(TimedItem::PhaseActive, timedItem->phase());
+ EXPECT_TRUE(timedItem->isInPlay());
+ EXPECT_TRUE(timedItem->isCurrent());
+ EXPECT_TRUE(timedItem->isInEffect());
+ EXPECT_EQ(0, timedItem->currentIteration());
+ EXPECT_EQ(0, timedItem->timeFraction());
+
+ timedItem->updateInheritedTime(1);
+
+ EXPECT_EQ(std::numeric_limits<double>::infinity(), timedItem->activeDuration());
+ EXPECT_EQ(TimedItem::PhaseActive, timedItem->phase());
+ EXPECT_TRUE(timedItem->isInPlay());
+ EXPECT_TRUE(timedItem->isCurrent());
+ EXPECT_TRUE(timedItem->isInEffect());
+ EXPECT_EQ(0, timedItem->currentIteration());
+ EXPECT_EQ(0, timedItem->timeFraction());
+}
+
+// FIXME: Needs specification work.
+TEST(AnimationTimedItemTest, InfiniteDurationZeroIterations)
+{
+ Timing timing;
+ timing.hasIterationDuration = true;
+ timing.iterationDuration = std::numeric_limits<double>::infinity();
+ timing.iterationCount = 0;
+ RefPtr<TestTimedItem> timedItem = TestTimedItem::create(timing);
+
+ EXPECT_EQ(0, timedItem->startTime());
+
+ timedItem->updateInheritedTime(0);
+
+ EXPECT_EQ(0, timedItem->activeDuration());
+ EXPECT_EQ(TimedItem::PhaseAfter, timedItem->phase());
+ EXPECT_FALSE(timedItem->isInPlay());
+ EXPECT_FALSE(timedItem->isCurrent());
+ EXPECT_TRUE(timedItem->isInEffect());
+ EXPECT_EQ(0, timedItem->currentIteration());
+ EXPECT_EQ(0, timedItem->timeFraction());
+
+ timedItem->updateInheritedTime(1);
+
+ EXPECT_EQ(TimedItem::PhaseAfter, timedItem->phase());
+ EXPECT_EQ(TimedItem::PhaseAfter, timedItem->phase());
+ EXPECT_FALSE(timedItem->isInPlay());
+ EXPECT_FALSE(timedItem->isCurrent());
+ EXPECT_TRUE(timedItem->isInEffect());
+ EXPECT_EQ(0, timedItem->currentIteration());
+ EXPECT_EQ(0, timedItem->timeFraction());
+}
+
+TEST(AnimationTimedItemTest, InfiniteDurationInfiniteIterations)
+{
+ Timing timing;
+ timing.hasIterationDuration = true;
+ timing.iterationDuration = std::numeric_limits<double>::infinity();
+ timing.iterationCount = std::numeric_limits<double>::infinity();
+ RefPtr<TestTimedItem> timedItem = TestTimedItem::create(timing);
+
+ EXPECT_EQ(0, timedItem->startTime());
timedItem->updateInheritedTime(0);
- ASSERT_EQ(1, timedItem->currentIteration());
- ASSERT_EQ(1, timedItem->timeFraction());
+
+ EXPECT_EQ(std::numeric_limits<double>::infinity(), timedItem->activeDuration());
+ EXPECT_EQ(TimedItem::PhaseActive, timedItem->phase());
+ EXPECT_TRUE(timedItem->isInPlay());
+ EXPECT_TRUE(timedItem->isCurrent());
+ EXPECT_TRUE(timedItem->isInEffect());
+ EXPECT_EQ(0, timedItem->currentIteration());
+ EXPECT_EQ(0, timedItem->timeFraction());
timedItem->updateInheritedTime(1);
- ASSERT_EQ(1, timedItem->currentIteration());
- ASSERT_EQ(1, timedItem->timeFraction());
+
+ EXPECT_EQ(std::numeric_limits<double>::infinity(), timedItem->activeDuration());
+ EXPECT_EQ(TimedItem::PhaseActive, timedItem->phase());
+ EXPECT_TRUE(timedItem->isInPlay());
+ EXPECT_TRUE(timedItem->isCurrent());
+ EXPECT_TRUE(timedItem->isInEffect());
+ EXPECT_EQ(0, timedItem->currentIteration());
+ EXPECT_EQ(0, timedItem->timeFraction());
+}
+
+TEST(AnimationTimedItemTest, InfiniteDurationZeroPlaybackRate)
+{
+ Timing timing;
+ timing.hasIterationDuration = true;
+ timing.iterationDuration = std::numeric_limits<double>::infinity();
+ timing.playbackRate = 0;
+ RefPtr<TestTimedItem> timedItem = TestTimedItem::create(timing);
+
+ EXPECT_EQ(0, timedItem->startTime());
+
+ timedItem->updateInheritedTime(0);
+
+ EXPECT_EQ(std::numeric_limits<double>::infinity(), timedItem->activeDuration());
+ EXPECT_EQ(TimedItem::PhaseActive, timedItem->phase());
+ EXPECT_TRUE(timedItem->isInPlay());
+ EXPECT_TRUE(timedItem->isCurrent());
+ EXPECT_TRUE(timedItem->isInEffect());
+ EXPECT_EQ(0, timedItem->currentIteration());
+ EXPECT_EQ(0, timedItem->timeFraction());
+
+ timedItem->updateInheritedTime(std::numeric_limits<double>::infinity());
+
+ EXPECT_EQ(std::numeric_limits<double>::infinity(), timedItem->activeDuration());
+ EXPECT_EQ(TimedItem::PhaseAfter, timedItem->phase());
+ EXPECT_FALSE(timedItem->isInPlay());
+ EXPECT_FALSE(timedItem->isCurrent());
+ EXPECT_TRUE(timedItem->isInEffect());
+ EXPECT_EQ(0, timedItem->currentIteration());
+ EXPECT_EQ(0, timedItem->timeFraction());
}
-TEST(TimedItem, Events)
+TEST(AnimationTimedItemTest, Events)
{
Timing timing;
timing.hasIterationDuration = true;
@@ -540,37 +707,76 @@ TEST(TimedItem, Events)
// First sample
timedItem->updateInheritedTime(0.0);
- ASSERT_TRUE(timedItem->eventDelegate()->eventTriggered());
+ EXPECT_TRUE(timedItem->eventDelegate()->eventTriggered());
// Before start
timedItem->updateInheritedTime(0.5);
- ASSERT_FALSE(timedItem->eventDelegate()->eventTriggered());
+ EXPECT_FALSE(timedItem->eventDelegate()->eventTriggered());
// First iteration
timedItem->updateInheritedTime(1.5);
- ASSERT_TRUE(timedItem->eventDelegate()->eventTriggered());
+ EXPECT_TRUE(timedItem->eventDelegate()->eventTriggered());
EXPECT_TRUE(timedItem->eventDelegate()->phaseChanged());
EXPECT_TRUE(timedItem->eventDelegate()->iterationChanged());
timedItem->updateInheritedTime(1.6);
- ASSERT_FALSE(timedItem->eventDelegate()->eventTriggered());
+ EXPECT_FALSE(timedItem->eventDelegate()->eventTriggered());
// Second iteration
timedItem->updateInheritedTime(2.5);
- ASSERT_TRUE(timedItem->eventDelegate()->eventTriggered());
+ EXPECT_TRUE(timedItem->eventDelegate()->eventTriggered());
EXPECT_FALSE(timedItem->eventDelegate()->phaseChanged());
EXPECT_TRUE(timedItem->eventDelegate()->iterationChanged());
timedItem->updateInheritedTime(2.6);
- ASSERT_FALSE(timedItem->eventDelegate()->eventTriggered());
+ EXPECT_FALSE(timedItem->eventDelegate()->eventTriggered());
// After end
timedItem->updateInheritedTime(3.5);
- ASSERT_TRUE(timedItem->eventDelegate()->eventTriggered());
+ EXPECT_TRUE(timedItem->eventDelegate()->eventTriggered());
EXPECT_TRUE(timedItem->eventDelegate()->phaseChanged());
EXPECT_FALSE(timedItem->eventDelegate()->iterationChanged());
timedItem->updateInheritedTime(3.6);
- ASSERT_FALSE(timedItem->eventDelegate()->eventTriggered());
+ EXPECT_FALSE(timedItem->eventDelegate()->eventTriggered());
+}
+
+TEST(AnimationTimedItemTest, TimeToEffectChange)
+{
+ Timing timing;
+ timing.hasIterationDuration = true;
+ timing.iterationDuration = 1;
+ timing.iterationStart = 0.2;
+ timing.iterationCount = 2.5;
+ timing.startDelay = 1;
+ timing.direction = Timing::PlaybackDirectionAlternate;
+ RefPtr<TestTimedItem> timedItem = TestTimedItem::create(timing);
+
+ timedItem->updateInheritedTime(0);
+ EXPECT_EQ(0, timedItem->takeLocalTime());
+ EXPECT_TRUE(std::isinf(timedItem->takeTimeToNextIteration()));
+
+ // Normal iteration.
+ timedItem->updateInheritedTime(1.75);
+ EXPECT_EQ(1.75, timedItem->takeLocalTime());
+ EXPECT_NEAR(0.05, timedItem->takeTimeToNextIteration(), 0.000000000000001);
+
+ // Reverse iteration.
+ timedItem->updateInheritedTime(2.75);
+ EXPECT_EQ(2.75, timedItem->takeLocalTime());
+ EXPECT_NEAR(0.05, timedItem->takeTimeToNextIteration(), 0.000000000000001);
+
+ // Item ends before iteration finishes.
+ timedItem->updateInheritedTime(3.4);
+ EXPECT_EQ(TimedItem::PhaseActive, timedItem->phase());
+ EXPECT_EQ(3.4, timedItem->takeLocalTime());
+ EXPECT_TRUE(std::isinf(timedItem->takeTimeToNextIteration()));
+
+ // Item has finished.
+ timedItem->updateInheritedTime(3.5);
+ EXPECT_EQ(TimedItem::PhaseAfter, timedItem->phase());
+ EXPECT_EQ(3.5, timedItem->takeLocalTime());
+ EXPECT_TRUE(std::isinf(timedItem->takeTimeToNextIteration()));
}
+
}
diff --git a/chromium/third_party/WebKit/Source/core/animation/Timing.h b/chromium/third_party/WebKit/Source/core/animation/Timing.h
index 43b04c062db..9a3bc4e6235 100644
--- a/chromium/third_party/WebKit/Source/core/animation/Timing.h
+++ b/chromium/third_party/WebKit/Source/core/animation/Timing.h
@@ -61,7 +61,7 @@ struct Timing {
, iterationDuration(0)
, playbackRate(1)
, direction(PlaybackDirectionNormal)
- , timingFunction(0)
+ , timingFunction(LinearTimingFunction::create())
{
}
@@ -73,6 +73,7 @@ struct Timing {
ASSERT(iterationCount >= 0);
ASSERT(iterationDuration >= 0);
ASSERT(std::isfinite(playbackRate));
+ ASSERT(timingFunction);
}
double startDelay;
diff --git a/chromium/third_party/WebKit/Source/core/animation/css/CSSAnimatableValueFactory.cpp b/chromium/third_party/WebKit/Source/core/animation/css/CSSAnimatableValueFactory.cpp
index bf22b53a493..41138cdd177 100644
--- a/chromium/third_party/WebKit/Source/core/animation/css/CSSAnimatableValueFactory.cpp
+++ b/chromium/third_party/WebKit/Source/core/animation/css/CSSAnimatableValueFactory.cpp
@@ -32,43 +32,52 @@
#include "core/animation/css/CSSAnimatableValueFactory.h"
#include "CSSValueKeywords.h"
+#include "core/animation/AnimatableClipPathOperation.h"
#include "core/animation/AnimatableColor.h"
+#include "core/animation/AnimatableDouble.h"
+#include "core/animation/AnimatableFilterOperations.h"
#include "core/animation/AnimatableImage.h"
+#include "core/animation/AnimatableLength.h"
#include "core/animation/AnimatableLengthBox.h"
-#include "core/animation/AnimatableNumber.h"
+#include "core/animation/AnimatableLengthBoxAndBool.h"
+#include "core/animation/AnimatableLengthPoint.h"
+#include "core/animation/AnimatableLengthSize.h"
+#include "core/animation/AnimatableRepeatable.h"
+#include "core/animation/AnimatableSVGLength.h"
+#include "core/animation/AnimatableSVGPaint.h"
+#include "core/animation/AnimatableShadow.h"
+#include "core/animation/AnimatableShapeValue.h"
+#include "core/animation/AnimatableStrokeDasharrayList.h"
#include "core/animation/AnimatableTransform.h"
#include "core/animation/AnimatableUnknown.h"
#include "core/animation/AnimatableVisibility.h"
#include "core/animation/css/CSSAnimations.h"
+#include "core/css/CSSCalculationValue.h"
#include "core/css/CSSPrimitiveValue.h"
-#include "core/platform/Length.h"
-#include "core/platform/LengthBox.h"
+#include "core/css/CSSPrimitiveValueMappings.h"
#include "core/rendering/style/RenderStyle.h"
-
+#include "platform/Length.h"
+#include "platform/LengthBox.h"
namespace WebCore {
-static PassRefPtr<AnimatableValue> createFromLength(const Length& length, const RenderStyle* style)
+static PassRefPtr<AnimatableValue> createFromLength(const Length& length, const RenderStyle& style)
{
switch (length.type()) {
- case Relative:
- return AnimatableNumber::create(length.value(), AnimatableNumber::UnitTypeNumber);
case Fixed:
- return AnimatableNumber::create(adjustFloatForAbsoluteZoom(length.value(), style), AnimatableNumber::UnitTypeLength);
+ return AnimatableLength::create(adjustFloatForAbsoluteZoom(length.value(), style), AnimatableLength::UnitTypePixels);
case Percent:
- return AnimatableNumber::create(length.value(), AnimatableNumber::UnitTypePercentage);
+ return AnimatableLength::create(length.value(), AnimatableLength::UnitTypePercentage);
case ViewportPercentageWidth:
- return AnimatableNumber::create(length.value(), AnimatableNumber::UnitTypeViewportWidth);
+ return AnimatableLength::create(length.value(), AnimatableLength::UnitTypeViewportWidth);
case ViewportPercentageHeight:
- return AnimatableNumber::create(length.value(), AnimatableNumber::UnitTypeViewportHeight);
+ return AnimatableLength::create(length.value(), AnimatableLength::UnitTypeViewportHeight);
case ViewportPercentageMin:
- return AnimatableNumber::create(length.value(), AnimatableNumber::UnitTypeViewportMin);
+ return AnimatableLength::create(length.value(), AnimatableLength::UnitTypeViewportMin);
case ViewportPercentageMax:
- return AnimatableNumber::create(length.value(), AnimatableNumber::UnitTypeViewportMax);
+ return AnimatableLength::create(length.value(), AnimatableLength::UnitTypeViewportMax);
case Calculated:
- // FIXME: Convert platform calcs to CSS calcs.
- ASSERT_WITH_MESSAGE(false, "Web Animations not yet implemented: Convert platform CalculationValue to AnimatableValue");
- return 0;
+ return AnimatableLength::create(CSSCalcValue::createExpressionNode(length.calculationValue()->expression(), style.effectiveZoom()));
case Auto:
case Intrinsic:
case MinIntrinsic:
@@ -78,7 +87,7 @@ static PassRefPtr<AnimatableValue> createFromLength(const Length& length, const
case FitContent:
return AnimatableUnknown::create(CSSPrimitiveValue::create(length));
case Undefined:
- return AnimatableUnknown::create(CSSPrimitiveValue::create(CSSValueNone));
+ return AnimatableUnknown::create(CSSValueNone);
case ExtendToZoom: // Does not apply to elements.
ASSERT_NOT_REACHED();
return 0;
@@ -87,12 +96,24 @@ static PassRefPtr<AnimatableValue> createFromLength(const Length& length, const
return 0;
}
-inline static PassRefPtr<AnimatableValue> createFromDouble(double value)
+static PassRefPtr<AnimatableValue> createFromLineHeight(const Length& length, const RenderStyle& style)
+{
+ if (length.type() == Percent) {
+ double value = length.value();
+ // -100% is used to represent "normal" line height.
+ if (value == -100)
+ return AnimatableUnknown::create(CSSValueNormal);
+ return AnimatableDouble::create(value);
+ }
+ return createFromLength(length, style);
+}
+
+inline static PassRefPtr<AnimatableValue> createFromDouble(double value, AnimatableDouble::Constraint constraint = AnimatableDouble::Unconstrained)
{
- return AnimatableNumber::create(value, AnimatableNumber::UnitTypeNumber);
+ return AnimatableDouble::create(value, constraint);
}
-inline static PassRefPtr<AnimatableValue> createFromLengthBox(const LengthBox lengthBox, const RenderStyle* style)
+inline static PassRefPtr<AnimatableValue> createFromLengthBox(const LengthBox& lengthBox, const RenderStyle& style)
{
return AnimatableLengthBox::create(
createFromLength(lengthBox.left(), style),
@@ -101,13 +122,109 @@ inline static PassRefPtr<AnimatableValue> createFromLengthBox(const LengthBox le
createFromLength(lengthBox.bottom(), style));
}
-PassRefPtr<AnimatableValue> CSSAnimatableValueFactory::createFromColor(CSSPropertyID property, const RenderStyle* style)
+static PassRefPtr<AnimatableValue> createFromBorderImageLength(const BorderImageLength& borderImageLength, const RenderStyle& style)
+{
+ if (borderImageLength.isNumber())
+ return createFromDouble(borderImageLength.number());
+ return createFromLength(borderImageLength.length(), style);
+}
+
+inline static PassRefPtr<AnimatableValue> createFromBorderImageLengthBox(const BorderImageLengthBox& borderImageLengthBox, const RenderStyle& style)
+{
+ return AnimatableLengthBox::create(
+ createFromBorderImageLength(borderImageLengthBox.left(), style),
+ createFromBorderImageLength(borderImageLengthBox.right(), style),
+ createFromBorderImageLength(borderImageLengthBox.top(), style),
+ createFromBorderImageLength(borderImageLengthBox.bottom(), style));
+}
+
+inline static PassRefPtr<AnimatableValue> createFromLengthBoxAndBool(const LengthBox lengthBox, const bool flag, const RenderStyle& style)
+{
+ return AnimatableLengthBoxAndBool::create(
+ createFromLengthBox(lengthBox, style),
+ flag);
+}
+
+inline static PassRefPtr<AnimatableValue> createFromLengthPoint(const LengthPoint& lengthPoint, const RenderStyle& style)
+{
+ return AnimatableLengthPoint::create(
+ createFromLength(lengthPoint.x(), style),
+ createFromLength(lengthPoint.y(), style));
+}
+
+inline static PassRefPtr<AnimatableValue> createFromLengthSize(const LengthSize& lengthSize, const RenderStyle& style)
+{
+ return AnimatableLengthSize::create(
+ createFromLength(lengthSize.width(), style),
+ createFromLength(lengthSize.height(), style));
+}
+
+inline static PassRefPtr<AnimatableValue> createFromStyleImage(StyleImage* image)
+{
+ if (image)
+ return AnimatableImage::create(image);
+ return AnimatableUnknown::create(CSSValueNone);
+}
+
+inline static PassRefPtr<AnimatableValue> createFromFillSize(const FillSize& fillSize, const RenderStyle& style)
+{
+ switch (fillSize.type) {
+ case SizeLength:
+ return createFromLengthSize(fillSize.size, style);
+ case Contain:
+ case Cover:
+ case SizeNone:
+ return AnimatableUnknown::create(CSSPrimitiveValue::create(fillSize.type));
+ default:
+ ASSERT_NOT_REACHED();
+ return 0;
+ }
+}
+
+template<CSSPropertyID property>
+inline static PassRefPtr<AnimatableValue> createFromFillLayers(const FillLayer* fillLayer, const RenderStyle& style)
+{
+ ASSERT(fillLayer);
+ Vector<RefPtr<AnimatableValue> > values;
+ while (fillLayer) {
+ if (property == CSSPropertyBackgroundImage || property == CSSPropertyWebkitMaskImage) {
+ if (!fillLayer->isImageSet())
+ break;
+ values.append(createFromStyleImage(fillLayer->image()));
+ } else if (property == CSSPropertyBackgroundPositionX || property == CSSPropertyWebkitMaskPositionX) {
+ if (!fillLayer->isXPositionSet())
+ break;
+ values.append(createFromLength(fillLayer->xPosition(), style));
+ } else if (property == CSSPropertyBackgroundPositionY || property == CSSPropertyWebkitMaskPositionY) {
+ if (!fillLayer->isYPositionSet())
+ break;
+ values.append(createFromLength(fillLayer->yPosition(), style));
+ } else if (property == CSSPropertyBackgroundSize || property == CSSPropertyWebkitMaskSize) {
+ if (!fillLayer->isSizeSet())
+ break;
+ values.append(createFromFillSize(fillLayer->size(), style));
+ } else {
+ ASSERT_NOT_REACHED();
+ }
+ fillLayer = fillLayer->next();
+ }
+ return AnimatableRepeatable::create(values);
+}
+
+PassRefPtr<AnimatableValue> CSSAnimatableValueFactory::createFromColor(CSSPropertyID property, const RenderStyle& style)
{
- Color color = style->colorIncludingFallback(property, false);
- Color visitedLinkColor = style->colorIncludingFallback(property, true);
- Color fallbackColor = style->color();
- Color fallbackVisitedLinkColor = style->visitedLinkColor();
+ Color color = style.colorIncludingFallback(property, false);
+ Color visitedLinkColor = style.colorIncludingFallback(property, true);
+ Color fallbackColor = style.color();
+ Color fallbackVisitedLinkColor = style.visitedLinkColor();
Color resolvedColor;
+
+ if (property == CSSPropertyBackgroundColor) {
+ // For background-color, invalid color means transparent and not currentColor.
+ fallbackColor = Color::transparent;
+ fallbackVisitedLinkColor = Color::transparent;
+ }
+
if (color.isValid())
resolvedColor = color;
else
@@ -120,118 +237,246 @@ PassRefPtr<AnimatableValue> CSSAnimatableValueFactory::createFromColor(CSSProper
return AnimatableColor::create(resolvedColor, resolvedVisitedLinkColor);
}
+inline static PassRefPtr<AnimatableValue> createFromShapeValue(ShapeValue* value)
+{
+ if (value)
+ return AnimatableShapeValue::create(value);
+ return AnimatableUnknown::create(CSSValueAuto);
+}
+
// FIXME: Generate this function.
-PassRefPtr<AnimatableValue> CSSAnimatableValueFactory::create(CSSPropertyID property, const RenderStyle* style)
+PassRefPtr<AnimatableValue> CSSAnimatableValueFactory::create(CSSPropertyID property, const RenderStyle& style)
{
switch (property) {
case CSSPropertyBackgroundColor:
return createFromColor(property, style);
+ case CSSPropertyBackgroundImage:
+ return createFromFillLayers<CSSPropertyBackgroundImage>(style.backgroundLayers(), style);
+ case CSSPropertyBackgroundPositionX:
+ return createFromFillLayers<CSSPropertyBackgroundPositionX>(style.backgroundLayers(), style);
+ case CSSPropertyBackgroundPositionY:
+ return createFromFillLayers<CSSPropertyBackgroundPositionY>(style.backgroundLayers(), style);
+ case CSSPropertyBackgroundSize:
+ case CSSPropertyWebkitBackgroundSize:
+ return createFromFillLayers<CSSPropertyBackgroundSize>(style.backgroundLayers(), style);
+ case CSSPropertyBaselineShift:
+ return AnimatableSVGLength::create(style.baselineShiftValue());
case CSSPropertyBorderBottomColor:
return createFromColor(property, style);
+ case CSSPropertyBorderBottomLeftRadius:
+ return createFromLengthSize(style.borderBottomLeftRadius(), style);
+ case CSSPropertyBorderBottomRightRadius:
+ return createFromLengthSize(style.borderBottomRightRadius(), style);
case CSSPropertyBorderBottomWidth:
- return createFromDouble(style->borderBottomWidth());
+ return createFromDouble(style.borderBottomWidth());
case CSSPropertyBorderImageOutset:
- return createFromLengthBox(style->borderImageOutset(), style);
+ return createFromBorderImageLengthBox(style.borderImageOutset(), style);
case CSSPropertyBorderImageSlice:
- return createFromLengthBox(style->borderImageSlices(), style);
+ return createFromLengthBox(style.borderImageSlices(), style);
case CSSPropertyBorderImageSource:
- return AnimatableImage::create(style->borderImageSource());
+ return createFromStyleImage(style.borderImageSource());
case CSSPropertyBorderImageWidth:
- return createFromLengthBox(style->borderImageWidth(), style);
+ return createFromBorderImageLengthBox(style.borderImageWidth(), style);
case CSSPropertyBorderLeftColor:
return createFromColor(property, style);
case CSSPropertyBorderLeftWidth:
- return createFromDouble(style->borderLeftWidth());
+ return createFromDouble(style.borderLeftWidth());
case CSSPropertyBorderRightColor:
return createFromColor(property, style);
case CSSPropertyBorderRightWidth:
- return createFromDouble(style->borderRightWidth());
+ return createFromDouble(style.borderRightWidth());
case CSSPropertyBorderTopColor:
return createFromColor(property, style);
+ case CSSPropertyBorderTopLeftRadius:
+ return createFromLengthSize(style.borderTopLeftRadius(), style);
+ case CSSPropertyBorderTopRightRadius:
+ return createFromLengthSize(style.borderTopRightRadius(), style);
case CSSPropertyBorderTopWidth:
- return createFromDouble(style->borderTopWidth());
+ return createFromDouble(style.borderTopWidth());
case CSSPropertyBottom:
- return createFromLength(style->bottom(), style);
+ return createFromLength(style.bottom(), style);
+ case CSSPropertyBoxShadow:
+ case CSSPropertyWebkitBoxShadow:
+ return AnimatableShadow::create(style.boxShadow());
case CSSPropertyClip:
- return createFromLengthBox(style->clip(), style);
+ if (style.hasClip())
+ return createFromLengthBox(style.clip(), style);
+ return AnimatableUnknown::create(CSSPrimitiveValue::create(CSSValueAuto));
case CSSPropertyColor:
return createFromColor(property, style);
+ case CSSPropertyFillOpacity:
+ return createFromDouble(style.fillOpacity());
+ case CSSPropertyFill:
+ return AnimatableSVGPaint::create(style.svgStyle()->fillPaintType(), style.svgStyle()->fillPaintColor(), style.svgStyle()->fillPaintUri());
+ case CSSPropertyFlexGrow:
+ return createFromDouble(style.flexGrow(), AnimatableDouble::InterpolationIsNonContinuousWithZero);
+ case CSSPropertyFlexShrink:
+ return createFromDouble(style.flexShrink(), AnimatableDouble::InterpolationIsNonContinuousWithZero);
+ case CSSPropertyFlexBasis:
+ return createFromLength(style.flexBasis(), style);
+ case CSSPropertyFloodColor:
+ return createFromColor(property, style);
+ case CSSPropertyFloodOpacity:
+ return createFromDouble(style.floodOpacity());
+ case CSSPropertyFontSize:
+ // Must pass a specified size to setFontSize if Text Autosizing is enabled, but a computed size
+ // if text zoom is enabled (if neither is enabled it's irrelevant as they're probably the same).
+ // FIXME: Should we introduce an option to pass the computed font size here, allowing consumers to
+ // enable text zoom rather than Text Autosizing? See http://crbug.com/227545.
+ return createFromDouble(style.specifiedFontSize());
case CSSPropertyHeight:
- return createFromLength(style->height(), style);
+ return createFromLength(style.height(), style);
+ case CSSPropertyKerning:
+ return AnimatableSVGLength::create(style.kerning());
+ case CSSPropertyLightingColor:
+ return createFromColor(property, style);
case CSSPropertyListStyleImage:
- return AnimatableImage::create(style->listStyleImage());
+ return createFromStyleImage(style.listStyleImage());
case CSSPropertyLeft:
- return createFromLength(style->left(), style);
+ return createFromLength(style.left(), style);
+ case CSSPropertyLetterSpacing:
+ return createFromDouble(style.letterSpacing());
+ case CSSPropertyLineHeight:
+ return createFromLineHeight(style.specifiedLineHeight(), style);
case CSSPropertyMarginBottom:
- return createFromLength(style->marginBottom(), style);
+ return createFromLength(style.marginBottom(), style);
case CSSPropertyMarginLeft:
- return createFromLength(style->marginLeft(), style);
+ return createFromLength(style.marginLeft(), style);
case CSSPropertyMarginRight:
- return createFromLength(style->marginRight(), style);
+ return createFromLength(style.marginRight(), style);
case CSSPropertyMarginTop:
- return createFromLength(style->marginTop(), style);
+ return createFromLength(style.marginTop(), style);
case CSSPropertyMaxHeight:
- return createFromLength(style->maxHeight(), style);
+ return createFromLength(style.maxHeight(), style);
case CSSPropertyMaxWidth:
- return createFromLength(style->maxWidth(), style);
+ return createFromLength(style.maxWidth(), style);
case CSSPropertyMinHeight:
- return createFromLength(style->minHeight(), style);
+ return createFromLength(style.minHeight(), style);
case CSSPropertyMinWidth:
- return createFromLength(style->minWidth(), style);
+ return createFromLength(style.minWidth(), style);
+ case CSSPropertyObjectPosition:
+ return createFromLengthPoint(style.objectPosition(), style);
case CSSPropertyOpacity:
- return createFromDouble(style->opacity());
+ return createFromDouble(style.opacity());
+ case CSSPropertyOrphans:
+ return createFromDouble(style.orphans());
case CSSPropertyOutlineColor:
return createFromColor(property, style);
case CSSPropertyOutlineOffset:
- return createFromDouble(style->outlineOffset());
+ return createFromDouble(style.outlineOffset());
case CSSPropertyOutlineWidth:
- return createFromDouble(style->outlineWidth());
+ return createFromDouble(style.outlineWidth());
case CSSPropertyPaddingBottom:
- return createFromLength(style->paddingBottom(), style);
+ return createFromLength(style.paddingBottom(), style);
case CSSPropertyPaddingLeft:
- return createFromLength(style->paddingLeft(), style);
+ return createFromLength(style.paddingLeft(), style);
case CSSPropertyPaddingRight:
- return createFromLength(style->paddingRight(), style);
+ return createFromLength(style.paddingRight(), style);
case CSSPropertyPaddingTop:
- return createFromLength(style->paddingTop(), style);
+ return createFromLength(style.paddingTop(), style);
case CSSPropertyRight:
- return createFromLength(style->right(), style);
+ return createFromLength(style.right(), style);
+ case CSSPropertyStrokeWidth:
+ return AnimatableSVGLength::create(style.strokeWidth());
+ case CSSPropertyStopColor:
+ return createFromColor(property, style);
+ case CSSPropertyStopOpacity:
+ return createFromDouble(style.stopOpacity());
+ case CSSPropertyStrokeDasharray:
+ return AnimatableStrokeDasharrayList::create(style.strokeDashArray());
+ case CSSPropertyStrokeDashoffset:
+ return AnimatableSVGLength::create(style.strokeDashOffset());
+ case CSSPropertyStrokeMiterlimit:
+ return createFromDouble(style.strokeMiterLimit());
+ case CSSPropertyStrokeOpacity:
+ return createFromDouble(style.strokeOpacity());
+ case CSSPropertyStroke:
+ return AnimatableSVGPaint::create(style.svgStyle()->strokePaintType(), style.svgStyle()->strokePaintColor(), style.svgStyle()->strokePaintUri());
case CSSPropertyTextDecorationColor:
return createFromColor(property, style);
+ case CSSPropertyTextIndent:
+ return createFromLength(style.textIndent(), style);
+ case CSSPropertyTextShadow:
+ return AnimatableShadow::create(style.textShadow());
case CSSPropertyTop:
- return createFromLength(style->top(), style);
+ return createFromLength(style.top(), style);
+ case CSSPropertyWebkitBorderHorizontalSpacing:
+ return createFromDouble(style.horizontalBorderSpacing());
+ case CSSPropertyWebkitBorderVerticalSpacing:
+ return createFromDouble(style.verticalBorderSpacing());
+ case CSSPropertyWebkitClipPath:
+ if (ClipPathOperation* operation = style.clipPath())
+ return AnimatableClipPathOperation::create(operation);
+ return AnimatableUnknown::create(CSSValueNone);
+ case CSSPropertyWebkitColumnCount:
+ return createFromDouble(style.columnCount());
+ case CSSPropertyWebkitColumnGap:
+ return createFromDouble(style.columnGap());
case CSSPropertyWebkitColumnRuleColor:
return createFromColor(property, style);
+ case CSSPropertyWebkitColumnRuleWidth:
+ return createFromDouble(style.columnRuleWidth());
+ case CSSPropertyWebkitColumnWidth:
+ return createFromDouble(style.columnWidth());
+ case CSSPropertyWebkitFilter:
+ return AnimatableFilterOperations::create(style.filter());
+ case CSSPropertyWebkitMaskBoxImageOutset:
+ return createFromBorderImageLengthBox(style.maskBoxImageOutset(), style);
+ case CSSPropertyWebkitMaskBoxImageSlice:
+ return createFromLengthBoxAndBool(style.maskBoxImageSlices(), style.maskBoxImageSlicesFill(), style);
case CSSPropertyWebkitMaskBoxImageSource:
- return AnimatableImage::create(style->maskBoxImageSource());
+ return createFromStyleImage(style.maskBoxImageSource());
+ case CSSPropertyWebkitMaskBoxImageWidth:
+ return createFromBorderImageLengthBox(style.maskBoxImageWidth(), style);
case CSSPropertyWebkitMaskImage:
- return AnimatableImage::create(style->maskImage());
+ return createFromFillLayers<CSSPropertyWebkitMaskImage>(style.maskLayers(), style);
+ case CSSPropertyWebkitMaskPositionX:
+ return createFromFillLayers<CSSPropertyWebkitMaskPositionX>(style.maskLayers(), style);
+ case CSSPropertyWebkitMaskPositionY:
+ return createFromFillLayers<CSSPropertyWebkitMaskPositionY>(style.maskLayers(), style);
+ case CSSPropertyWebkitMaskSize:
+ return createFromFillLayers<CSSPropertyWebkitMaskSize>(style.maskLayers(), style);
+ case CSSPropertyWebkitPerspective:
+ return createFromDouble(style.perspective());
case CSSPropertyWebkitPerspectiveOriginX:
- return createFromLength(style->perspectiveOriginX(), style);
+ return createFromLength(style.perspectiveOriginX(), style);
case CSSPropertyWebkitPerspectiveOriginY:
- return createFromLength(style->perspectiveOriginY(), style);
- case CSSPropertyWebkitTextEmphasisColor:
- return createFromColor(property, style);
- case CSSPropertyWebkitTextFillColor:
- return createFromColor(property, style);
+ return createFromLength(style.perspectiveOriginY(), style);
+ case CSSPropertyShapeInside:
+ return createFromShapeValue(style.shapeInside());
+ case CSSPropertyShapeOutside:
+ return createFromShapeValue(style.shapeOutside());
+ case CSSPropertyShapeMargin:
+ return createFromLength(style.shapeMargin(), style);
+ case CSSPropertyShapeImageThreshold:
+ return createFromDouble(style.shapeImageThreshold());
case CSSPropertyWebkitTextStrokeColor:
return createFromColor(property, style);
case CSSPropertyWebkitTransform:
- return AnimatableTransform::create(style->transform());
+ return AnimatableTransform::create(style.transform());
case CSSPropertyWebkitTransformOriginX:
- return createFromLength(style->transformOriginX(), style);
+ return createFromLength(style.transformOriginX(), style);
case CSSPropertyWebkitTransformOriginY:
- return createFromLength(style->transformOriginY(), style);
+ return createFromLength(style.transformOriginY(), style);
+ case CSSPropertyWebkitTransformOriginZ:
+ return createFromDouble(style.transformOriginZ());
+ case CSSPropertyWidows:
+ return createFromDouble(style.widows());
case CSSPropertyWidth:
- return createFromLength(style->width(), style);
+ return createFromLength(style.width(), style);
+ case CSSPropertyWordSpacing:
+ return createFromDouble(style.wordSpacing());
case CSSPropertyVisibility:
- return AnimatableVisibility::create(style->visibility());
+ return AnimatableVisibility::create(style.visibility());
case CSSPropertyZIndex:
- return createFromDouble(style->zIndex());
+ return createFromDouble(style.zIndex());
+ case CSSPropertyZoom:
+ return createFromDouble(style.zoom());
default:
- RELEASE_ASSERT_WITH_MESSAGE(!CSSAnimations::isAnimatableProperty(property), "Web Animations not yet implemented: Create AnimatableValue from render style: %s", getPropertyNameString(property).utf8().data());
+ ASSERT_WITH_MESSAGE(!CSSAnimations::isAnimatableProperty(property), "Web Animations not yet implemented: Create AnimatableValue from render style: %s", getPropertyNameString(property).utf8().data());
ASSERT_NOT_REACHED();
- return 0;
+ // This return value is to avoid a release crash if possible.
+ return AnimatableUnknown::create(0);
}
}
diff --git a/chromium/third_party/WebKit/Source/core/animation/css/CSSAnimatableValueFactory.h b/chromium/third_party/WebKit/Source/core/animation/css/CSSAnimatableValueFactory.h
index d9e6ce2d9c9..bac18c19241 100644
--- a/chromium/third_party/WebKit/Source/core/animation/css/CSSAnimatableValueFactory.h
+++ b/chromium/third_party/WebKit/Source/core/animation/css/CSSAnimatableValueFactory.h
@@ -41,9 +41,9 @@ class RenderStyle;
class CSSAnimatableValueFactory {
public:
- static PassRefPtr<AnimatableValue> create(CSSPropertyID, const RenderStyle*);
+ static PassRefPtr<AnimatableValue> create(CSSPropertyID, const RenderStyle&);
private:
- static PassRefPtr<AnimatableValue> createFromColor(CSSPropertyID, const RenderStyle*);
+ static PassRefPtr<AnimatableValue> createFromColor(CSSPropertyID, const RenderStyle&);
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/animation/css/CSSAnimations.cpp b/chromium/third_party/WebKit/Source/core/animation/css/CSSAnimations.cpp
index 6584765e230..807c59096b5 100644
--- a/chromium/third_party/WebKit/Source/core/animation/css/CSSAnimations.cpp
+++ b/chromium/third_party/WebKit/Source/core/animation/css/CSSAnimations.cpp
@@ -31,21 +31,32 @@
#include "config.h"
#include "core/animation/css/CSSAnimations.h"
+#include "StylePropertyShorthand.h"
#include "core/animation/ActiveAnimations.h"
+#include "core/animation/CompositorAnimations.h"
#include "core/animation/DocumentTimeline.h"
#include "core/animation/KeyframeAnimationEffect.h"
+#include "core/animation/css/CSSAnimatableValueFactory.h"
#include "core/css/CSSKeyframeRule.h"
#include "core/css/resolver/StyleResolver.h"
#include "core/dom/Element.h"
-#include "core/dom/EventNames.h"
-#include "core/dom/WebKitAnimationEvent.h"
+#include "core/dom/PseudoElement.h"
+#include "core/events/ThreadLocalEventNames.h"
+#include "core/events/TransitionEvent.h"
+#include "core/events/WebKitAnimationEvent.h"
+#include "core/frame/UseCounter.h"
+#include "core/frame/animation/CSSPropertyAnimation.h"
#include "core/platform/animation/CSSAnimationDataList.h"
#include "core/platform/animation/TimingFunction.h"
+#include "core/rendering/RenderObject.h"
+#include "core/rendering/style/KeyframeList.h"
+#include "public/platform/Platform.h"
+#include "wtf/BitArray.h"
#include "wtf/HashSet.h"
-namespace {
+namespace WebCore {
-using namespace WebCore;
+namespace {
bool isEarlierPhase(TimedItem::Phase target, TimedItem::Phase reference)
{
@@ -61,12 +72,199 @@ bool isLaterPhase(TimedItem::Phase target, TimedItem::Phase reference)
return target > reference;
}
-} // namespace
+static PassRefPtr<TimingFunction> generateTimingFunction(const KeyframeAnimationEffect::KeyframeVector keyframes, const HashMap<double, RefPtr<TimingFunction> > perKeyframeTimingFunctions)
+{
+ // Generate the chained timing function. Note that timing functions apply
+ // from the keyframe in which they're specified to the next keyframe.
+ bool isTimingFunctionLinearThroughout = true;
+ RefPtr<ChainedTimingFunction> chainedTimingFunction = ChainedTimingFunction::create();
+ for (size_t i = 0; i < keyframes.size() - 1; ++i) {
+ double lowerBound = keyframes[i]->offset();
+ ASSERT(lowerBound >=0 && lowerBound < 1);
+ double upperBound = keyframes[i + 1]->offset();
+ ASSERT(upperBound > 0 && upperBound <= 1);
+ TimingFunction* timingFunction = perKeyframeTimingFunctions.get(lowerBound);
+ isTimingFunctionLinearThroughout &= timingFunction->type() == TimingFunction::LinearFunction;
+ chainedTimingFunction->appendSegment(upperBound, timingFunction);
+ }
+ if (isTimingFunctionLinearThroughout)
+ return LinearTimingFunction::create();
+ return chainedTimingFunction;
+}
-namespace WebCore {
+static void resolveKeyframes(StyleResolver* resolver, Element* element, const Element& parentElement, const RenderStyle& style, RenderStyle* parentStyle, const AtomicString& name, TimingFunction* defaultTimingFunction,
+ Vector<std::pair<KeyframeAnimationEffect::KeyframeVector, RefPtr<TimingFunction> > >& keyframesAndTimingFunctions)
+{
+ ASSERT(RuntimeEnabledFeatures::webAnimationsCSSEnabled());
+ // When the element is null, use its parent for scoping purposes.
+ const Element* elementForScoping = element ? element : &parentElement;
+ const StyleRuleKeyframes* keyframesRule = CSSAnimations::matchScopedKeyframesRule(resolver, elementForScoping, name.impl());
+ if (!keyframesRule)
+ return;
+
+ const Vector<RefPtr<StyleKeyframe> >& styleKeyframes = keyframesRule->keyframes();
+ if (styleKeyframes.isEmpty())
+ return;
+
+ // Construct and populate the style for each keyframe
+ PropertySet specifiedProperties;
+ KeyframeAnimationEffect::KeyframeVector keyframes;
+ HashMap<double, RefPtr<TimingFunction> > perKeyframeTimingFunctions;
+ for (size_t i = 0; i < styleKeyframes.size(); ++i) {
+ const StyleKeyframe* styleKeyframe = styleKeyframes[i].get();
+ // It's OK to pass a null element here.
+ RefPtr<RenderStyle> keyframeStyle = resolver->styleForKeyframe(element, style, parentStyle, styleKeyframe, name);
+ RefPtr<Keyframe> keyframe = Keyframe::create();
+ const Vector<double>& offsets = styleKeyframe->keys();
+ ASSERT(!offsets.isEmpty());
+ keyframe->setOffset(offsets[0]);
+ TimingFunction* timingFunction = defaultTimingFunction;
+ const StylePropertySet* properties = styleKeyframe->properties();
+ for (unsigned j = 0; j < properties->propertyCount(); j++) {
+ CSSPropertyID property = properties->propertyAt(j).id();
+ specifiedProperties.add(property);
+ if (property == CSSPropertyWebkitAnimationTimingFunction || property == CSSPropertyAnimationTimingFunction)
+ timingFunction = KeyframeValue::timingFunction(*keyframeStyle);
+ else if (CSSAnimations::isAnimatableProperty(property))
+ keyframe->setPropertyValue(property, CSSAnimatableValueFactory::create(property, *keyframeStyle).get());
+ }
+ keyframes.append(keyframe);
+ // The last keyframe specified at a given offset is used.
+ perKeyframeTimingFunctions.set(offsets[0], timingFunction);
+ for (size_t j = 1; j < offsets.size(); ++j) {
+ keyframes.append(keyframe->cloneWithOffset(offsets[j]));
+ perKeyframeTimingFunctions.set(offsets[j], timingFunction);
+ }
+ }
+ ASSERT(!keyframes.isEmpty());
+
+ if (!perKeyframeTimingFunctions.contains(0))
+ perKeyframeTimingFunctions.set(0, defaultTimingFunction);
+
+ for (PropertySet::const_iterator iter = specifiedProperties.begin(); iter != specifiedProperties.end(); ++iter) {
+ const CSSPropertyID property = *iter;
+ ASSERT(property != CSSPropertyInvalid);
+ blink::Platform::current()->histogramSparse("WebCore.Animation.CSSProperties", UseCounter::mapCSSPropertyIdToCSSSampleIdForHistogram(property));
+ }
+
+ // Remove duplicate keyframes. In CSS the last keyframe at a given offset takes priority.
+ std::stable_sort(keyframes.begin(), keyframes.end(), Keyframe::compareOffsets);
+ size_t targetIndex = 0;
+ for (size_t i = 1; i < keyframes.size(); i++) {
+ if (keyframes[i]->offset() != keyframes[targetIndex]->offset())
+ targetIndex++;
+ if (targetIndex != i)
+ keyframes[targetIndex] = keyframes[i];
+ }
+ keyframes.shrink(targetIndex + 1);
+
+ // Add 0% and 100% keyframes if absent.
+ RefPtr<Keyframe> startKeyframe = keyframes[0];
+ if (startKeyframe->offset()) {
+ startKeyframe = Keyframe::create();
+ startKeyframe->setOffset(0);
+ keyframes.prepend(startKeyframe);
+ }
+ RefPtr<Keyframe> endKeyframe = keyframes[keyframes.size() - 1];
+ if (endKeyframe->offset() != 1) {
+ endKeyframe = Keyframe::create();
+ endKeyframe->setOffset(1);
+ keyframes.append(endKeyframe);
+ }
+ ASSERT(keyframes.size() >= 2);
+ ASSERT(!keyframes.first()->offset());
+ ASSERT(keyframes.last()->offset() == 1);
+
+ // Snapshot current property values for 0% and 100% if missing.
+ PropertySet allProperties;
+ size_t numKeyframes = keyframes.size();
+ for (size_t i = 0; i < numKeyframes; i++) {
+ const PropertySet& keyframeProperties = keyframes[i]->properties();
+ for (PropertySet::const_iterator iter = keyframeProperties.begin(); iter != keyframeProperties.end(); ++iter)
+ allProperties.add(*iter);
+ }
+ const PropertySet& startKeyframeProperties = startKeyframe->properties();
+ const PropertySet& endKeyframeProperties = endKeyframe->properties();
+ bool missingStartValues = startKeyframeProperties.size() < allProperties.size();
+ bool missingEndValues = endKeyframeProperties.size() < allProperties.size();
+ if (missingStartValues || missingEndValues) {
+ for (PropertySet::const_iterator iter = allProperties.begin(); iter != allProperties.end(); ++iter) {
+ const CSSPropertyID property = *iter;
+ bool startNeedsValue = missingStartValues && !startKeyframeProperties.contains(property);
+ bool endNeedsValue = missingEndValues && !endKeyframeProperties.contains(property);
+ if (!startNeedsValue && !endNeedsValue)
+ continue;
+ RefPtr<AnimatableValue> snapshotValue = CSSAnimatableValueFactory::create(property, style);
+ if (startNeedsValue)
+ startKeyframe->setPropertyValue(property, snapshotValue.get());
+ if (endNeedsValue)
+ endKeyframe->setPropertyValue(property, snapshotValue.get());
+ }
+ }
+ ASSERT(startKeyframe->properties().size() == allProperties.size());
+ ASSERT(endKeyframe->properties().size() == allProperties.size());
+
+ // Determine how many keyframes specify each property. Note that this must
+ // be done after we've filled in end keyframes.
+ typedef HashCountedSet<CSSPropertyID> PropertyCountedSet;
+ PropertyCountedSet propertyCounts;
+ for (size_t i = 0; i < numKeyframes; ++i) {
+ const PropertySet& properties = keyframes[i]->properties();
+ for (PropertySet::const_iterator iter = properties.begin(); iter != properties.end(); ++iter)
+ propertyCounts.add(*iter);
+ }
+
+ // Split keyframes into groups, where each group contains only keyframes
+ // which specify all properties used in that group. Each group is animated
+ // in a separate animation, to allow per-keyframe timing functions to be
+ // applied correctly.
+ for (PropertyCountedSet::const_iterator iter = propertyCounts.begin(); iter != propertyCounts.end(); ++iter) {
+ const CSSPropertyID property = iter->key;
+ const size_t count = iter->value;
+ ASSERT(count <= numKeyframes);
+ if (count == numKeyframes)
+ continue;
+ KeyframeAnimationEffect::KeyframeVector splitOutKeyframes;
+ for (size_t i = 0; i < numKeyframes; i++) {
+ Keyframe* keyframe = keyframes[i].get();
+ if (!keyframe->properties().contains(property)) {
+ ASSERT(i && i != numKeyframes - 1);
+ continue;
+ }
+ RefPtr<Keyframe> clonedKeyframe = Keyframe::create();
+ clonedKeyframe->setOffset(keyframe->offset());
+ clonedKeyframe->setComposite(keyframe->composite());
+ clonedKeyframe->setPropertyValue(property, keyframe->propertyValue(property));
+ splitOutKeyframes.append(clonedKeyframe);
+ // Note that it's OK if this keyframe ends up having no
+ // properties. This can only happen when none of the properties
+ // are specified in all keyframes, in which case we won't animate
+ // anything with these keyframes.
+ keyframe->clearPropertyValue(property);
+ }
+ ASSERT(!splitOutKeyframes.first()->offset());
+ ASSERT(splitOutKeyframes.last()->offset() == 1);
+#ifndef NDEBUG
+ for (size_t j = 0; j < splitOutKeyframes.size(); ++j)
+ ASSERT(splitOutKeyframes[j]->properties().size() == 1);
+#endif
+ keyframesAndTimingFunctions.append(std::make_pair(splitOutKeyframes, generateTimingFunction(splitOutKeyframes, perKeyframeTimingFunctions)));
+ }
+
+ unsigned numPropertiesSpecifiedInAllKeyframes = keyframes.first()->properties().size();
+#ifndef NDEBUG
+ for (size_t i = 1; i < numKeyframes; ++i)
+ ASSERT(keyframes[i]->properties().size() == numPropertiesSpecifiedInAllKeyframes);
+#endif
+
+ // If the animation specifies any keyframes, we always provide at least one
+ // vector of resolved keyframes, even if no properties are animated.
+ if (numPropertiesSpecifiedInAllKeyframes || keyframesAndTimingFunctions.isEmpty())
+ keyframesAndTimingFunctions.append(std::make_pair(keyframes, generateTimingFunction(keyframes, perKeyframeTimingFunctions)));
+}
// Returns the default timing function.
-const PassRefPtr<TimingFunction> timingFromAnimationData(const CSSAnimationData* animationData, Timing& timing)
+const PassRefPtr<TimingFunction> timingFromAnimationData(const CSSAnimationData* animationData, Timing& timing, bool& isPaused)
{
if (animationData->isDelaySet())
timing.startDelay = animationData->delay();
@@ -97,6 +295,8 @@ const PassRefPtr<TimingFunction> timingFromAnimationData(const CSSAnimationData*
default:
ASSERT_NOT_REACHED();
}
+ } else {
+ timing.fillMode = Timing::FillModeNone;
}
if (animationData->isDirectionSet()) {
switch (animationData->direction()) {
@@ -116,52 +316,60 @@ const PassRefPtr<TimingFunction> timingFromAnimationData(const CSSAnimationData*
ASSERT_NOT_REACHED();
}
}
+
+ // For CSS, the constraints on the timing properties are tighter than in
+ // the general case of the Web Animations model.
+ timing.assertValid();
+ ASSERT(!timing.iterationStart);
+ ASSERT(timing.playbackRate == 1);
+ ASSERT(timing.iterationDuration >= 0 && std::isfinite(timing.iterationDuration));
+
+ isPaused = animationData->isPlayStateSet() && animationData->playState() == AnimPlayStatePaused;
return animationData->isTimingFunctionSet() ? animationData->timingFunction() : CSSAnimationData::initialAnimationTimingFunction();
}
-CSSAnimationUpdateScope::CSSAnimationUpdateScope(Element* target)
- : m_target(target)
-{
- if (!m_target)
- return;
- ActiveAnimations* activeAnimations = m_target->activeAnimations();
- CSSAnimations* cssAnimations = activeAnimations ? activeAnimations->cssAnimations() : 0;
- // It's possible than an update was created outside an update scope. That's harmless
- // but we must clear it now to avoid applying it if an updated replacement is not
- // created in this scope.
- if (cssAnimations)
- cssAnimations->setPendingUpdate(nullptr);
-}
+} // namespace
-CSSAnimationUpdateScope::~CSSAnimationUpdateScope()
+const StyleRuleKeyframes* CSSAnimations::matchScopedKeyframesRule(StyleResolver* resolver, const Element* element, const StringImpl* animationName)
{
- if (!m_target)
- return;
- ActiveAnimations* activeAnimations = m_target->activeAnimations();
- CSSAnimations* cssAnimations = activeAnimations ? activeAnimations->cssAnimations() : 0;
- if (cssAnimations)
- cssAnimations->maybeApplyPendingUpdate(m_target);
+ if (resolver->styleTreeHasOnlyScopedResolverForDocument())
+ return resolver->styleTreeScopedStyleResolverForDocument()->keyframeStylesForAnimation(animationName);
+
+ Vector<ScopedStyleResolver*, 8> stack;
+ resolver->styleTreeResolveScopedKeyframesRules(element, stack);
+ if (stack.isEmpty())
+ return 0;
+
+ for (size_t i = 0; i < stack.size(); ++i) {
+ if (const StyleRuleKeyframes* keyframesRule = stack.at(i)->keyframeStylesForAnimation(animationName))
+ return keyframesRule;
+ }
+ return 0;
}
-bool CSSAnimations::needsUpdate(const Element* element, const RenderStyle* style)
+PassOwnPtr<CSSAnimationUpdate> CSSAnimations::calculateUpdate(Element* element, const Element& parentElement, const RenderStyle& style, RenderStyle* parentStyle, StyleResolver* resolver)
{
- ActiveAnimations* activeAnimations = element->activeAnimations();
- const CSSAnimationDataList* animations = style->animations();
- const CSSAnimations* cssAnimations = activeAnimations ? activeAnimations->cssAnimations() : 0;
- EDisplay display = style->display();
- return (display != NONE && animations && animations->size()) || (cssAnimations && !cssAnimations->isEmpty());
+ ASSERT(RuntimeEnabledFeatures::webAnimationsCSSEnabled());
+ OwnPtr<CSSAnimationUpdate> update = adoptPtr(new CSSAnimationUpdate());
+ calculateAnimationUpdate(update.get(), element, parentElement, style, parentStyle, resolver);
+ calculateAnimationCompositableValues(update.get(), element);
+ calculateTransitionUpdate(update.get(), element, style);
+ calculateTransitionCompositableValues(update.get(), element);
+ return update->isEmpty() ? nullptr : update.release();
}
-PassOwnPtr<CSSAnimationUpdate> CSSAnimations::calculateUpdate(const Element* element, const RenderStyle* style, const CSSAnimations* cssAnimations, const CSSAnimationDataList* animationDataList, StyleResolver* resolver)
+void CSSAnimations::calculateAnimationUpdate(CSSAnimationUpdate* update, Element* element, const Element& parentElement, const RenderStyle& style, RenderStyle* parentStyle, StyleResolver* resolver)
{
- OwnPtr<CSSAnimationUpdate> update;
+ const ActiveAnimations* activeAnimations = element ? element->activeAnimations() : 0;
+ const CSSAnimationDataList* animationDataList = style.animations();
+ const CSSAnimations* cssAnimations = activeAnimations ? &activeAnimations->cssAnimations() : 0;
+
HashSet<AtomicString> inactive;
if (cssAnimations)
for (AnimationMap::const_iterator iter = cssAnimations->m_animations.begin(); iter != cssAnimations->m_animations.end(); ++iter)
inactive.add(iter->key);
- RefPtr<MutableStylePropertySet> newStyles;
- if (style->display() != NONE) {
+ if (style.display() != NONE) {
for (size_t i = 0; animationDataList && i < animationDataList->size(); ++i) {
const CSSAnimationData* animationData = animationDataList->animation(i);
if (animationData->isNoneAnimation())
@@ -169,75 +377,352 @@ PassOwnPtr<CSSAnimationUpdate> CSSAnimations::calculateUpdate(const Element* ele
ASSERT(animationData->isValidAnimation());
AtomicString animationName(animationData->name());
+ // Keyframes and animation properties are snapshotted when the
+ // animation starts, so we don't need to track changes to these,
+ // with the exception of play-state.
if (cssAnimations) {
AnimationMap::const_iterator existing(cssAnimations->m_animations.find(animationName));
if (existing != cssAnimations->m_animations.end()) {
- // FIXME: The play-state of this animation might have changed, record the change in the update.
inactive.remove(animationName);
+ const HashSet<RefPtr<Player> >& players = existing->value;
+ ASSERT(!players.isEmpty());
+ bool isFirstPlayerPaused = (*players.begin())->paused();
+#ifndef NDEBUG
+ for (HashSet<RefPtr<Player> >::const_iterator iter = players.begin(); iter != players.end(); ++iter)
+ ASSERT((*iter)->paused() == isFirstPlayerPaused);
+#endif
+ if ((animationData->playState() == AnimPlayStatePaused) != isFirstPlayerPaused)
+ update->toggleAnimationPaused(animationName);
continue;
}
}
Timing timing;
- RefPtr<TimingFunction> defaultTimingFunction = timingFromAnimationData(animationData, timing);
- KeyframeAnimationEffect::KeyframeVector keyframes;
- resolver->resolveKeyframes(element, style, animationName, defaultTimingFunction.get(), keyframes, timing.timingFunction);
- if (!keyframes.isEmpty()) {
- if (!update)
- update = adoptPtr(new CSSAnimationUpdate());
- // FIXME: crbug.com/268791 - Keyframes are already normalized, perhaps there should be a flag on KeyframeAnimationEffect to skip normalization.
- update->startAnimation(animationName, InertAnimation::create(KeyframeAnimationEffect::create(keyframes), timing).get());
+ bool isPaused;
+ RefPtr<TimingFunction> defaultTimingFunction = timingFromAnimationData(animationData, timing, isPaused);
+ Vector<std::pair<KeyframeAnimationEffect::KeyframeVector, RefPtr<TimingFunction> > > keyframesAndTimingFunctions;
+ resolveKeyframes(resolver, element, parentElement, style, parentStyle, animationName, defaultTimingFunction.get(), keyframesAndTimingFunctions);
+ if (!keyframesAndTimingFunctions.isEmpty()) {
+ HashSet<RefPtr<InertAnimation> > animations;
+ for (size_t j = 0; j < keyframesAndTimingFunctions.size(); ++j) {
+ ASSERT(!keyframesAndTimingFunctions[j].first.isEmpty());
+ timing.timingFunction = keyframesAndTimingFunctions[j].second;
+ // FIXME: crbug.com/268791 - Keyframes are already normalized, perhaps there should be a flag on KeyframeAnimationEffect to skip normalization.
+ animations.add(InertAnimation::create(KeyframeAnimationEffect::create(keyframesAndTimingFunctions[j].first), timing, isPaused));
+ }
+ update->startAnimation(animationName, animations);
}
}
}
- if (!inactive.isEmpty() && !update)
- update = adoptPtr(new CSSAnimationUpdate());
+ ASSERT(inactive.isEmpty() || cssAnimations);
for (HashSet<AtomicString>::const_iterator iter = inactive.begin(); iter != inactive.end(); ++iter)
update->cancelAnimation(*iter, cssAnimations->m_animations.get(*iter));
-
- return update.release();
}
void CSSAnimations::maybeApplyPendingUpdate(Element* element)
{
- if (!element->renderer())
- m_pendingUpdate = nullptr;
-
- if (!m_pendingUpdate)
+ if (!m_pendingUpdate) {
+ m_previousCompositableValuesForAnimations.clear();
return;
+ }
OwnPtr<CSSAnimationUpdate> update = m_pendingUpdate.release();
- for (Vector<AtomicString>::const_iterator iter = update->cancelledAnimationNames().begin(); iter != update->cancelledAnimationNames().end(); ++iter)
- m_animations.take(*iter)->cancel();
+ m_previousCompositableValuesForAnimations.swap(update->compositableValuesForAnimations());
- // FIXME: Apply updates to play-state.
+ for (Vector<AtomicString>::const_iterator iter = update->cancelledAnimationNames().begin(); iter != update->cancelledAnimationNames().end(); ++iter) {
+ const HashSet<RefPtr<Player> >& players = m_animations.take(*iter);
+ for (HashSet<RefPtr<Player> >::const_iterator iter = players.begin(); iter != players.end(); ++iter)
+ (*iter)->cancel();
+ }
+
+ for (Vector<AtomicString>::const_iterator iter = update->animationsWithPauseToggled().begin(); iter != update->animationsWithPauseToggled().end(); ++iter) {
+ const HashSet<RefPtr<Player> >& players = m_animations.get(*iter);
+ ASSERT(!players.isEmpty());
+ bool isFirstPlayerPaused = (*players.begin())->paused();
+ for (HashSet<RefPtr<Player> >::const_iterator iter = players.begin(); iter != players.end(); ++iter) {
+ Player* player = iter->get();
+ ASSERT(player->paused() == isFirstPlayerPaused);
+ player->setPaused(!isFirstPlayerPaused);
+ }
+ }
for (Vector<CSSAnimationUpdate::NewAnimation>::const_iterator iter = update->newAnimations().begin(); iter != update->newAnimations().end(); ++iter) {
- OwnPtr<CSSAnimations::EventDelegate> eventDelegate = adoptPtr(new EventDelegate(element, iter->name));
- RefPtr<Animation> animation = Animation::create(element, iter->animation->effect(), iter->animation->specified(), eventDelegate.release());
- RefPtr<Player> player = element->document().timeline()->play(animation.get());
- m_animations.set(iter->name, player.get());
+ OwnPtr<AnimationEventDelegate> eventDelegate = adoptPtr(new AnimationEventDelegate(element, iter->name));
+ HashSet<RefPtr<Player> > players;
+ for (HashSet<RefPtr<InertAnimation> >::const_iterator animationsIter = iter->animations.begin(); animationsIter != iter->animations.end(); ++animationsIter) {
+ const InertAnimation* inertAnimation = animationsIter->get();
+ // The event delegate is set on the the first animation only. We
+ // rely on the behavior of OwnPtr::release() to achieve this.
+ RefPtr<Animation> animation = Animation::create(element, inertAnimation->effect(), inertAnimation->specified(), Animation::DefaultPriority, eventDelegate.release());
+ Player* player = element->document().timeline()->createPlayer(animation.get());
+ player->setPaused(inertAnimation->paused());
+ element->document().cssPendingAnimations().add(player);
+ player->update();
+ players.add(player);
+ }
+ m_animations.set(iter->name, players);
+ }
+
+ // Transitions that are run on the compositor only update main-thread state
+ // lazily. However, we need the new state to know what the from state shoud
+ // be when transitions are retargeted. Instead of triggering complete style
+ // recalculation, we find these cases by searching for new transitions that
+ // have matching cancelled animation property IDs on the compositor.
+ HashMap<CSSPropertyID, std::pair<RefPtr<Animation>, double> > retargetedCompositorTransitions;
+ const ActiveAnimations* activeAnimations = element->activeAnimations();
+ for (HashSet<CSSPropertyID>::iterator iter = update->cancelledTransitions().begin(); iter != update->cancelledTransitions().end(); ++iter) {
+ CSSPropertyID id = *iter;
+ ASSERT(m_transitions.contains(id));
+ Player* player = m_transitions.take(id).transition->player();
+ if (activeAnimations && activeAnimations->hasActiveAnimationsOnCompositor(id) && update->newTransitions().find(id) != update->newTransitions().end())
+ retargetedCompositorTransitions.add(id, std::pair<RefPtr<Animation>, double>(toAnimation(player->source()), player->startTime()));
+ player->cancel();
+ }
+
+ for (CSSAnimationUpdate::NewTransitionMap::const_iterator iter = update->newTransitions().begin(); iter != update->newTransitions().end(); ++iter) {
+ const CSSAnimationUpdate::NewTransition& newTransition = iter->value;
+
+ RunningTransition runningTransition;
+ runningTransition.from = newTransition.from;
+ runningTransition.to = newTransition.to;
+
+ CSSPropertyID id = newTransition.id;
+ InertAnimation* inertAnimation = newTransition.animation.get();
+ OwnPtr<TransitionEventDelegate> eventDelegate = adoptPtr(new TransitionEventDelegate(element, id));
+
+ RefPtr<AnimationEffect> effect = inertAnimation->effect();
+
+ if (retargetedCompositorTransitions.contains(id)) {
+ const std::pair<RefPtr<Animation>, double>& oldTransition = retargetedCompositorTransitions.get(id);
+ RefPtr<Animation> oldAnimation = oldTransition.first;
+ double oldStartTime = oldTransition.second;
+ double inheritedTime = isNull(oldStartTime) ? 0 : element->document().transitionTimeline()->currentTime() - oldStartTime;
+ oldAnimation->updateInheritedTime(inheritedTime);
+ KeyframeAnimationEffect* oldEffect = toKeyframeAnimationEffect(inertAnimation->effect());
+ const KeyframeAnimationEffect::KeyframeVector& frames = oldEffect->getFrames();
+ KeyframeAnimationEffect::KeyframeVector newFrames;
+ newFrames.append(frames[0]->clone());
+ newFrames[0]->clearPropertyValue(id);
+ ASSERT(oldAnimation->compositableValues()->size() == 1);
+ const AnimationEffect::CompositableValue* compositableValue = oldAnimation->compositableValues()->at(0).second.get();
+ ASSERT(!compositableValue->dependsOnUnderlyingValue());
+ newFrames[0]->setPropertyValue(id, compositableValue->compositeOnto(0).get());
+ newFrames.append(frames[1]->clone());
+ effect = KeyframeAnimationEffect::create(newFrames);
+ }
+ RefPtr<Animation> transition = Animation::create(element, effect, inertAnimation->specified(), Animation::TransitionPriority, eventDelegate.release());
+ RefPtr<Player> player = element->document().transitionTimeline()->createPlayer(transition.get());
+ player->update();
+ element->document().cssPendingAnimations().add(player.get());
+ runningTransition.transition = transition.get();
+ m_transitions.set(id, runningTransition);
+ ASSERT(id != CSSPropertyInvalid);
+ blink::Platform::current()->histogramSparse("WebCore.Animation.CSSProperties", UseCounter::mapCSSPropertyIdToCSSSampleIdForHistogram(id));
+ }
+}
+
+void CSSAnimations::calculateTransitionUpdateForProperty(CSSPropertyID id, const CSSAnimationData* anim, const RenderStyle& oldStyle, const RenderStyle& style, const TransitionMap* activeTransitions, CSSAnimationUpdate* update, const Element* element)
+{
+ RefPtr<AnimatableValue> to;
+ if (activeTransitions) {
+ TransitionMap::const_iterator activeTransitionIter = activeTransitions->find(id);
+ if (activeTransitionIter != activeTransitions->end()) {
+ to = CSSAnimatableValueFactory::create(id, style);
+ const AnimatableValue* activeTo = activeTransitionIter->value.to;
+ if (to->equals(activeTo))
+ return;
+ update->cancelTransition(id);
+ ASSERT(!element->activeAnimations() || !element->activeAnimations()->isAnimationStyleChange());
+ }
+ }
+
+ if (anim->duration() + anim->delay() <= 0)
+ return;
+
+ if (CSSPropertyAnimation::propertiesEqual(id, &oldStyle, &style))
+ return;
+
+ if (!to)
+ to = CSSAnimatableValueFactory::create(id, style);
+
+ RefPtr<AnimatableValue> from = CSSAnimatableValueFactory::create(id, oldStyle);
+ // If we have multiple transitions on the same property, we will use the
+ // last one since we iterate over them in order.
+ if (!from->usesNonDefaultInterpolationWith(to.get()))
+ return;
+
+ KeyframeAnimationEffect::KeyframeVector keyframes;
+
+ RefPtr<Keyframe> startKeyframe = Keyframe::create();
+ startKeyframe->setPropertyValue(id, from.get());
+ startKeyframe->setOffset(0);
+ keyframes.append(startKeyframe);
+
+ RefPtr<Keyframe> endKeyframe = Keyframe::create();
+ endKeyframe->setPropertyValue(id, to.get());
+ endKeyframe->setOffset(1);
+ keyframes.append(endKeyframe);
+
+ RefPtr<KeyframeAnimationEffect> effect = KeyframeAnimationEffect::create(keyframes);
+
+ Timing timing;
+ bool isPaused;
+ RefPtr<TimingFunction> timingFunction = timingFromAnimationData(anim, timing, isPaused);
+ ASSERT(!isPaused);
+ timing.timingFunction = timingFunction;
+ // Note that the backwards part is required for delay to work.
+ timing.fillMode = Timing::FillModeBoth;
+
+ update->startTransition(id, from.get(), to.get(), InertAnimation::create(effect, timing, isPaused));
+ ASSERT(!element->activeAnimations() || !element->activeAnimations()->isAnimationStyleChange());
+}
+
+void CSSAnimations::calculateTransitionUpdate(CSSAnimationUpdate* update, const Element* element, const RenderStyle& style)
+{
+ if (!element)
+ return;
+
+ ActiveAnimations* activeAnimations = element->activeAnimations();
+ const TransitionMap* activeTransitions = activeAnimations ? &activeAnimations->cssAnimations().m_transitions : 0;
+
+#if ASSERT_DISABLED
+ // In release builds we avoid the cost of checking for new and interrupted transitions if the style recalc is due to animation.
+ const bool animationStyleRecalc = activeAnimations && activeAnimations->isAnimationStyleChange();
+#else
+ // In debug builds we verify that it would have been safe to avoid populating and testing listedProperties if the style recalc is due to animation.
+ const bool animationStyleRecalc = false;
+#endif
+
+ BitArray<numCSSProperties> listedProperties;
+ bool anyTransitionHadAnimateAll = false;
+ const RenderObject* renderer = element->renderer();
+ if (!animationStyleRecalc && style.display() != NONE && renderer && renderer->style() && style.transitions()) {
+ const RenderStyle& oldStyle = *renderer->style();
+
+ for (size_t i = 0; i < style.transitions()->size(); ++i) {
+ const CSSAnimationData* anim = style.transitions()->animation(i);
+ CSSAnimationData::AnimationMode mode = anim->animationMode();
+ if (mode == CSSAnimationData::AnimateNone)
+ continue;
+
+ bool animateAll = mode == CSSAnimationData::AnimateAll;
+ ASSERT(animateAll || mode == CSSAnimationData::AnimateSingleProperty);
+ if (animateAll)
+ anyTransitionHadAnimateAll = true;
+ const StylePropertyShorthand& propertyList = animateAll ? CSSAnimations::animatableProperties() : shorthandForProperty(anim->property());
+ // If not a shorthand we only execute one iteration of this loop, and refer to the property directly.
+ for (unsigned j = 0; !j || j < propertyList.length(); ++j) {
+ CSSPropertyID id = propertyList.length() ? propertyList.properties()[j] : anim->property();
+
+ if (!animateAll) {
+ if (CSSAnimations::isAnimatableProperty(id))
+ listedProperties.set(id);
+ else
+ continue;
+ }
+
+ // FIXME: We should transition if an !important property changes even when an animation is running,
+ // but this is a bit hard to do with the current applyMatchedProperties system.
+ if (!update->compositableValuesForAnimations().contains(id)
+ && (!activeAnimations || !activeAnimations->cssAnimations().m_previousCompositableValuesForAnimations.contains(id))) {
+ calculateTransitionUpdateForProperty(id, anim, oldStyle, style, activeTransitions, update, element);
+ }
+ }
+ }
+ }
+
+ if (activeTransitions) {
+ for (TransitionMap::const_iterator iter = activeTransitions->begin(); iter != activeTransitions->end(); ++iter) {
+ const TimedItem* timedItem = iter->value.transition;
+ CSSPropertyID id = iter->key;
+ if (timedItem->phase() == TimedItem::PhaseAfter || (!anyTransitionHadAnimateAll && !animationStyleRecalc && !listedProperties.get(id))) {
+ ASSERT(timedItem->phase() == TimedItem::PhaseAfter || !(activeAnimations && activeAnimations->isAnimationStyleChange()));
+ update->cancelTransition(id);
+ }
+ }
}
}
void CSSAnimations::cancel()
{
- for (AnimationMap::iterator iter = m_animations.begin(); iter != m_animations.end(); ++iter)
- iter->value->cancel();
+ for (AnimationMap::iterator iter = m_animations.begin(); iter != m_animations.end(); ++iter) {
+ const HashSet<RefPtr<Player> >& players = iter->value;
+ for (HashSet<RefPtr<Player> >::const_iterator animationsIter = players.begin(); animationsIter != players.end(); ++animationsIter)
+ (*animationsIter)->cancel();
+ }
+
+ for (TransitionMap::iterator iter = m_transitions.begin(); iter != m_transitions.end(); ++iter)
+ iter->value.transition->player()->cancel();
m_animations.clear();
+ m_transitions.clear();
m_pendingUpdate = nullptr;
}
-void CSSAnimations::EventDelegate::maybeDispatch(Document::ListenerType listenerType, AtomicString& eventName, double elapsedTime)
+void CSSAnimations::calculateAnimationCompositableValues(CSSAnimationUpdate* update, const Element* element)
+{
+ ActiveAnimations* activeAnimations = element ? element->activeAnimations() : 0;
+ AnimationStack* animationStack = activeAnimations ? &activeAnimations->defaultStack() : 0;
+
+ if (update->newAnimations().isEmpty() && update->cancelledAnimationPlayers().isEmpty()) {
+ AnimationEffect::CompositableValueMap compositableValuesForAnimations(AnimationStack::compositableValues(animationStack, 0, 0, Animation::DefaultPriority));
+ update->adoptCompositableValuesForAnimations(compositableValuesForAnimations);
+ return;
+ }
+
+ Vector<InertAnimation*> newAnimations;
+ for (size_t i = 0; i < update->newAnimations().size(); ++i) {
+ HashSet<RefPtr<InertAnimation> > animations = update->newAnimations()[i].animations;
+ for (HashSet<RefPtr<InertAnimation> >::const_iterator animationsIter = animations.begin(); animationsIter != animations.end(); ++animationsIter)
+ newAnimations.append(animationsIter->get());
+ }
+ AnimationEffect::CompositableValueMap compositableValuesForAnimations(AnimationStack::compositableValues(animationStack, &newAnimations, &update->cancelledAnimationPlayers(), Animation::DefaultPriority));
+ update->adoptCompositableValuesForAnimations(compositableValuesForAnimations);
+}
+
+void CSSAnimations::calculateTransitionCompositableValues(CSSAnimationUpdate* update, const Element* element)
+{
+ ActiveAnimations* activeAnimations = element ? element->activeAnimations() : 0;
+ AnimationStack* animationStack = activeAnimations ? &activeAnimations->defaultStack() : 0;
+
+ AnimationEffect::CompositableValueMap compositableValuesForTransitions;
+ if (update->newTransitions().isEmpty() && update->cancelledTransitions().isEmpty()) {
+ compositableValuesForTransitions = AnimationStack::compositableValues(animationStack, 0, 0, Animation::TransitionPriority);
+ } else {
+ Vector<InertAnimation*> newTransitions;
+ for (CSSAnimationUpdate::NewTransitionMap::const_iterator iter = update->newTransitions().begin(); iter != update->newTransitions().end(); ++iter)
+ newTransitions.append(iter->value.animation.get());
+
+ HashSet<const Player*> cancelledPlayers;
+ if (!update->cancelledTransitions().isEmpty()) {
+ ASSERT(activeAnimations);
+ const TransitionMap& transitionMap = activeAnimations->cssAnimations().m_transitions;
+ for (HashSet<CSSPropertyID>::iterator iter = update->cancelledTransitions().begin(); iter != update->cancelledTransitions().end(); ++iter) {
+ ASSERT(transitionMap.contains(*iter));
+ cancelledPlayers.add(transitionMap.get(*iter).transition->player());
+ }
+ }
+
+ compositableValuesForTransitions = AnimationStack::compositableValues(animationStack, &newTransitions, &cancelledPlayers, Animation::TransitionPriority);
+ }
+
+ // Properties being animated by animations don't get values from transitions applied.
+ if (!update->compositableValuesForAnimations().isEmpty() && !compositableValuesForTransitions.isEmpty()) {
+ for (AnimationEffect::CompositableValueMap::const_iterator iter = update->compositableValuesForAnimations().begin(); iter != update->compositableValuesForAnimations().end(); ++iter)
+ compositableValuesForTransitions.remove(iter->key);
+ }
+ update->adoptCompositableValuesForTransitions(compositableValuesForTransitions);
+}
+
+void CSSAnimations::AnimationEventDelegate::maybeDispatch(Document::ListenerType listenerType, const AtomicString& eventName, double elapsedTime)
{
if (m_target->document().hasListenerType(listenerType))
m_target->document().timeline()->addEventToDispatch(m_target, WebKitAnimationEvent::create(eventName, m_name, elapsedTime));
}
-void CSSAnimations::EventDelegate::onEventCondition(const TimedItem* timedItem, bool isFirstSample, TimedItem::Phase previousPhase, double previousIteration)
+void CSSAnimations::AnimationEventDelegate::onEventCondition(const TimedItem* timedItem, bool isFirstSample, TimedItem::Phase previousPhase, double previousIteration)
{
// Events for a single document are queued and dispatched as a group at
// the end of DocumentTimeline::serviceAnimations.
@@ -256,7 +741,7 @@ void CSSAnimations::EventDelegate::onEventCondition(const TimedItem* timedItem,
// the elapsedTime for the first iteration in question.
ASSERT(timedItem->specified().hasIterationDuration);
const double elapsedTime = timedItem->specified().iterationDuration * (previousIteration + 1);
- maybeDispatch(Document::ANIMATIONITERATION_LISTENER, eventNames().animationiterationEvent, elapsedTime);
+ maybeDispatch(Document::ANIMATIONITERATION_LISTENER, EventTypeNames::animationiteration, elapsedTime);
return;
}
if ((isFirstSample || previousPhase == TimedItem::PhaseBefore) && isLaterPhase(currentPhase, TimedItem::PhaseBefore)) {
@@ -264,12 +749,30 @@ void CSSAnimations::EventDelegate::onEventCondition(const TimedItem* timedItem,
// The spec states that the elapsed time should be
// 'delay < 0 ? -delay : 0', but we always use 0 to match the existing
// implementation. See crbug.com/279611
- maybeDispatch(Document::ANIMATIONSTART_LISTENER, eventNames().animationstartEvent, 0);
+ maybeDispatch(Document::ANIMATIONSTART_LISTENER, EventTypeNames::animationstart, 0);
}
if ((isFirstSample || isEarlierPhase(previousPhase, TimedItem::PhaseAfter)) && currentPhase == TimedItem::PhaseAfter)
- maybeDispatch(Document::ANIMATIONEND_LISTENER, eventNames().animationendEvent, timedItem->activeDuration());
+ maybeDispatch(Document::ANIMATIONEND_LISTENER, EventTypeNames::animationend, timedItem->activeDuration());
+}
+
+void CSSAnimations::TransitionEventDelegate::onEventCondition(const TimedItem* timedItem, bool isFirstSample, TimedItem::Phase previousPhase, double previousIteration)
+{
+ // Events for a single document are queued and dispatched as a group at
+ // the end of DocumentTimeline::serviceAnimations.
+ // FIXME: Events which are queued outside of serviceAnimations should
+ // trigger a timer to dispatch when control is released.
+ const TimedItem::Phase currentPhase = timedItem->phase();
+ if (currentPhase == TimedItem::PhaseAfter && (isFirstSample || previousPhase != currentPhase) && m_target->document().hasListenerType(Document::TRANSITIONEND_LISTENER)) {
+ String propertyName = getPropertyNameString(m_property);
+ const Timing& timing = timedItem->specified();
+ double elapsedTime = timing.iterationDuration;
+ const AtomicString& eventType = EventTypeNames::transitionend;
+ String pseudoElement = PseudoElement::pseudoElementNameForEvents(m_target->pseudoId());
+ m_target->document().transitionTimeline()->addEventToDispatch(m_target, TransitionEvent::create(eventType, propertyName, elapsedTime, pseudoElement));
+ }
}
+
bool CSSAnimations::isAnimatableProperty(CSSPropertyID property)
{
switch (property) {
@@ -301,7 +804,9 @@ bool CSSAnimations::isAnimatableProperty(CSSPropertyID property)
case CSSPropertyColor:
case CSSPropertyFill:
case CSSPropertyFillOpacity:
- case CSSPropertyFlex:
+ case CSSPropertyFlexBasis:
+ case CSSPropertyFlexGrow:
+ case CSSPropertyFlexShrink:
case CSSPropertyFloodColor:
case CSSPropertyFloodOpacity:
case CSSPropertyFontSize:
@@ -339,6 +844,7 @@ bool CSSAnimations::isAnimatableProperty(CSSPropertyID property)
case CSSPropertyStrokeMiterlimit:
case CSSPropertyStrokeOpacity:
case CSSPropertyStrokeWidth:
+ case CSSPropertyTextDecorationColor:
case CSSPropertyTextIndent:
case CSSPropertyTextShadow:
case CSSPropertyTop:
@@ -354,8 +860,10 @@ bool CSSAnimations::isAnimatableProperty(CSSPropertyID property)
case CSSPropertyWebkitColumnRuleWidth:
case CSSPropertyWebkitColumnWidth:
case CSSPropertyWebkitFilter:
- case CSSPropertyWebkitMaskBoxImage:
+ case CSSPropertyWebkitMaskBoxImageOutset:
+ case CSSPropertyWebkitMaskBoxImageSlice:
case CSSPropertyWebkitMaskBoxImageSource:
+ case CSSPropertyWebkitMaskBoxImageWidth:
case CSSPropertyWebkitMaskImage:
case CSSPropertyWebkitMaskPositionX:
case CSSPropertyWebkitMaskPositionY:
@@ -363,8 +871,10 @@ bool CSSAnimations::isAnimatableProperty(CSSPropertyID property)
case CSSPropertyWebkitPerspective:
case CSSPropertyWebkitPerspectiveOriginX:
case CSSPropertyWebkitPerspectiveOriginY:
- case CSSPropertyWebkitShapeInside:
- case CSSPropertyWebkitTextFillColor:
+ case CSSPropertyShapeInside:
+ case CSSPropertyShapeOutside:
+ case CSSPropertyShapeMargin:
+ case CSSPropertyShapeImageThreshold:
case CSSPropertyWebkitTextStrokeColor:
case CSSPropertyWebkitTransform:
case CSSPropertyWebkitTransformOriginX:
@@ -376,9 +886,29 @@ bool CSSAnimations::isAnimatableProperty(CSSPropertyID property)
case CSSPropertyZIndex:
case CSSPropertyZoom:
return true;
+ // FIXME: Shorthands should not be present in this list, but
+ // CSSPropertyAnimation implements animation of these shorthands
+ // directly and makes use of this method.
+ case CSSPropertyFlex:
+ return !RuntimeEnabledFeatures::webAnimationsCSSEnabled();
default:
return false;
}
}
+const StylePropertyShorthand& CSSAnimations::animatableProperties()
+{
+ DEFINE_STATIC_LOCAL(Vector<CSSPropertyID>, properties, ());
+ DEFINE_STATIC_LOCAL(StylePropertyShorthand, propertyShorthand, ());
+ if (properties.isEmpty()) {
+ for (int i = firstCSSProperty; i < lastCSSProperty; ++i) {
+ CSSPropertyID id = convertToCSSPropertyID(i);
+ if (isAnimatableProperty(id))
+ properties.append(id);
+ }
+ propertyShorthand = StylePropertyShorthand(CSSPropertyInvalid, properties.begin(), properties.size());
+ }
+ return propertyShorthand;
+}
+
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/animation/css/CSSAnimations.h b/chromium/third_party/WebKit/Source/core/animation/css/CSSAnimations.h
index f59b8f6c8cb..fb553d96232 100644
--- a/chromium/third_party/WebKit/Source/core/animation/css/CSSAnimations.h
+++ b/chromium/third_party/WebKit/Source/core/animation/css/CSSAnimations.h
@@ -44,75 +44,169 @@
namespace WebCore {
-class CSSAnimationDataList;
class Element;
-class RenderObject;
+class StylePropertyShorthand;
class StyleResolver;
+class StyleRuleKeyframes;
-// Applied to scopes where an animation update will be added as pending and should then be applied (eg. Element style recalc).
-class CSSAnimationUpdateScope FINAL {
-public:
- CSSAnimationUpdateScope(Element*);
- ~CSSAnimationUpdateScope();
-private:
- Element* m_target;
-};
-
+// This class stores the CSS Animations/Transitions information we use during a style recalc.
+// This includes updates to animations/transitions as well as the CompositableValueMaps to be applied.
class CSSAnimationUpdate FINAL {
public:
- void startAnimation(AtomicString& animationName, PassRefPtr<InertAnimation> animation)
+ void startAnimation(AtomicString& animationName, const HashSet<RefPtr<InertAnimation> >& animations)
{
NewAnimation newAnimation;
newAnimation.name = animationName;
- newAnimation.animation = animation;
+ newAnimation.animations = animations;
m_newAnimations.append(newAnimation);
}
// Returns whether player has been cancelled and should be filtered during style application.
- bool isCancelled(const Player* player) const { return m_cancelledAnimationPlayers.contains(player); }
- void cancelAnimation(const AtomicString& name, const Player* player)
+ bool isCancelledAnimation(const Player* player) const { return m_cancelledAnimationPlayers.contains(player); }
+ void cancelAnimation(const AtomicString& name, const HashSet<RefPtr<Player> >& players)
{
m_cancelledAnimationNames.append(name);
- m_cancelledAnimationPlayers.add(player);
+ for (HashSet<RefPtr<Player> >::const_iterator iter = players.begin(); iter != players.end(); ++iter)
+ m_cancelledAnimationPlayers.add(iter->get());
+ }
+ void toggleAnimationPaused(const AtomicString& name)
+ {
+ m_animationsWithPauseToggled.append(name);
}
+
+ void startTransition(CSSPropertyID id, const AnimatableValue* from, const AnimatableValue* to, PassRefPtr<InertAnimation> animation)
+ {
+ NewTransition newTransition;
+ newTransition.id = id;
+ newTransition.from = from;
+ newTransition.to = to;
+ newTransition.animation = animation;
+ m_newTransitions.set(id, newTransition);
+ }
+ bool isCancelledTransition(CSSPropertyID id) const { return m_cancelledTransitions.contains(id); }
+ void cancelTransition(CSSPropertyID id) { m_cancelledTransitions.add(id); }
+
struct NewAnimation {
AtomicString name;
- RefPtr<InertAnimation> animation;
+ HashSet<RefPtr<InertAnimation> > animations;
};
const Vector<NewAnimation>& newAnimations() const { return m_newAnimations; }
const Vector<AtomicString>& cancelledAnimationNames() const { return m_cancelledAnimationNames; }
+ const HashSet<const Player*>& cancelledAnimationPlayers() const { return m_cancelledAnimationPlayers; }
+ const Vector<AtomicString>& animationsWithPauseToggled() const { return m_animationsWithPauseToggled; }
+
+ struct NewTransition {
+ CSSPropertyID id;
+ const AnimatableValue* from;
+ const AnimatableValue* to;
+ RefPtr<InertAnimation> animation;
+ };
+ typedef HashMap<CSSPropertyID, NewTransition> NewTransitionMap;
+ const NewTransitionMap& newTransitions() const { return m_newTransitions; }
+ const HashSet<CSSPropertyID>& cancelledTransitions() const { return m_cancelledTransitions; }
+
+ void adoptCompositableValuesForAnimations(AnimationEffect::CompositableValueMap& newMap) { newMap.swap(m_compositableValuesForAnimations); }
+ void adoptCompositableValuesForTransitions(AnimationEffect::CompositableValueMap& newMap) { newMap.swap(m_compositableValuesForTransitions); }
+ const AnimationEffect::CompositableValueMap& compositableValuesForAnimations() const { return m_compositableValuesForAnimations; }
+ const AnimationEffect::CompositableValueMap& compositableValuesForTransitions() const { return m_compositableValuesForTransitions; }
+ AnimationEffect::CompositableValueMap& compositableValuesForAnimations() { return m_compositableValuesForAnimations; }
+
+ bool isEmpty() const
+ {
+ return m_newAnimations.isEmpty()
+ && m_cancelledAnimationNames.isEmpty()
+ && m_cancelledAnimationPlayers.isEmpty()
+ && m_animationsWithPauseToggled.isEmpty()
+ && m_newTransitions.isEmpty()
+ && m_cancelledTransitions.isEmpty()
+ && m_compositableValuesForAnimations.isEmpty()
+ && m_compositableValuesForTransitions.isEmpty();
+ }
private:
- // Order is significant since it defines the order in which new animations will be started.
+ // Order is significant since it defines the order in which new animations
+ // will be started. Note that there may be multiple animations present
+ // with the same name, due to the way in which we split up animations with
+ // incomplete keyframes.
Vector<NewAnimation> m_newAnimations;
Vector<AtomicString> m_cancelledAnimationNames;
HashSet<const Player*> m_cancelledAnimationPlayers;
+ Vector<AtomicString> m_animationsWithPauseToggled;
+
+ NewTransitionMap m_newTransitions;
+ HashSet<CSSPropertyID> m_cancelledTransitions;
+
+ AnimationEffect::CompositableValueMap m_compositableValuesForAnimations;
+ AnimationEffect::CompositableValueMap m_compositableValuesForTransitions;
};
class CSSAnimations FINAL {
public:
+ // FIXME: This method is only used here and in the legacy animations
+ // implementation. It should be made private or file-scope when the legacy
+ // engine is removed.
+ static const StyleRuleKeyframes* matchScopedKeyframesRule(StyleResolver*, const Element*, const StringImpl*);
+
static bool isAnimatableProperty(CSSPropertyID);
- static bool needsUpdate(const Element*, const RenderStyle*);
- static PassOwnPtr<CSSAnimationUpdate> calculateUpdate(const Element*, const RenderStyle*, const CSSAnimations*, const CSSAnimationDataList*, StyleResolver*);
+ static const StylePropertyShorthand& animatableProperties();
+ // FIXME: This should take a const ScopedStyleTree instead of a StyleResolver.
+ // We should also change the Element* to a const Element*
+ static PassOwnPtr<CSSAnimationUpdate> calculateUpdate(Element*, const Element& parentElement, const RenderStyle&, RenderStyle* parentStyle, StyleResolver*);
+
void setPendingUpdate(PassOwnPtr<CSSAnimationUpdate> update) { m_pendingUpdate = update; }
void maybeApplyPendingUpdate(Element*);
- bool isEmpty() const { return m_animations.isEmpty() && !m_pendingUpdate; }
+ bool isEmpty() const { return m_animations.isEmpty() && m_transitions.isEmpty() && !m_pendingUpdate; }
void cancel();
+
private:
- typedef HashMap<AtomicString, RefPtr<Player> > AnimationMap;
+ // Note that a single animation name may map to multiple players due to
+ // the way in which we split up animations with incomplete keyframes.
+ // FIXME: Once the Web Animations model supports groups, we could use a
+ // ParGroup to drive multiple animations from a single Player.
+ typedef HashMap<AtomicString, HashSet<RefPtr<Player> > > AnimationMap;
+ struct RunningTransition {
+ Animation* transition; // The TransitionTimeline keeps the Players alive
+ const AnimatableValue* from;
+ const AnimatableValue* to;
+ };
+ typedef HashMap<CSSPropertyID, RunningTransition > TransitionMap;
AnimationMap m_animations;
+ TransitionMap m_transitions;
OwnPtr<CSSAnimationUpdate> m_pendingUpdate;
- class EventDelegate FINAL : public TimedItem::EventDelegate {
+
+ AnimationEffect::CompositableValueMap m_previousCompositableValuesForAnimations;
+
+ static void calculateAnimationUpdate(CSSAnimationUpdate*, Element*, const Element& parentElement, const RenderStyle&, RenderStyle* parentStyle, StyleResolver*);
+ static void calculateTransitionUpdate(CSSAnimationUpdate*, const Element*, const RenderStyle&);
+ static void calculateTransitionUpdateForProperty(CSSPropertyID, const CSSAnimationData*, const RenderStyle& oldStyle, const RenderStyle&, const TransitionMap* activeTransitions, CSSAnimationUpdate*, const Element*);
+
+ static void calculateAnimationCompositableValues(CSSAnimationUpdate*, const Element*);
+ static void calculateTransitionCompositableValues(CSSAnimationUpdate*, const Element*);
+
+ class AnimationEventDelegate FINAL : public TimedItem::EventDelegate {
public:
- EventDelegate(Element* target, const AtomicString& name)
+ AnimationEventDelegate(Element* target, const AtomicString& name)
: m_target(target)
, m_name(name)
{
}
virtual void onEventCondition(const TimedItem*, bool isFirstSample, TimedItem::Phase previousPhase, double previousIteration) OVERRIDE;
private:
- void maybeDispatch(Document::ListenerType, AtomicString& eventName, double elapsedTime);
+ void maybeDispatch(Document::ListenerType, const AtomicString& eventName, double elapsedTime);
Element* m_target;
const AtomicString m_name;
};
+
+ class TransitionEventDelegate FINAL : public TimedItem::EventDelegate {
+ public:
+ TransitionEventDelegate(Element* target, CSSPropertyID property)
+ : m_target(target)
+ , m_property(property)
+ {
+ }
+ virtual void onEventCondition(const TimedItem*, bool isFirstSample, TimedItem::Phase previousPhase, double previousIteration) OVERRIDE;
+ private:
+ Element* m_target;
+ const CSSPropertyID m_property;
+ };
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/animation/css/CSSPendingAnimations.cpp b/chromium/third_party/WebKit/Source/core/animation/css/CSSPendingAnimations.cpp
new file mode 100644
index 00000000000..3a4ec03d29e
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/animation/css/CSSPendingAnimations.cpp
@@ -0,0 +1,94 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/animation/css/CSSPendingAnimations.h"
+
+#include "core/animation/Animation.h"
+#include "core/animation/DocumentTimeline.h"
+#include "core/frame/FrameView.h"
+
+namespace WebCore {
+
+void CSSPendingAnimations::add(Player* player)
+{
+ ASSERT(player->source()->isAnimation());
+ // The actual start time is either this value, or the time that
+ // this animation, or an animation that it is synchronized with
+ // is started on the compositor.
+ const double defaultStartTime = player->timeline().currentTime();
+ m_pending.append(std::make_pair(player, defaultStartTime));
+}
+
+bool CSSPendingAnimations::startPendingAnimations()
+{
+ bool startedOnCompositor = false;
+ for (size_t i = 0; i < m_pending.size(); ++i) {
+ if (m_pending[i].first->maybeStartAnimationOnCompositor())
+ startedOnCompositor = true;
+ }
+
+ // If any animations were started on the compositor, all remaining
+ // need to wait for a synchronized start time. Otherwise they may
+ // start immediately.
+ if (startedOnCompositor) {
+ for (size_t i = 0; i < m_pending.size(); ++i)
+ m_waitingForCompositorAnimationStart.append(m_pending[i].first);
+ } else {
+ for (size_t i = 0; i < m_pending.size(); ++i)
+ m_pending[i].first->setStartTime(m_pending[i].second);
+ }
+ m_pending.clear();
+
+ if (startedOnCompositor || m_waitingForCompositorAnimationStart.isEmpty())
+ return !m_waitingForCompositorAnimationStart.isEmpty();
+
+ // Check if we're still waiting for any compositor animations to start.
+ for (size_t i = 0; i < m_waitingForCompositorAnimationStart.size(); ++i) {
+ if (m_waitingForCompositorAnimationStart[i].get()->hasActiveAnimationsOnCompositor())
+ return true;
+ }
+
+ // If not, go ahead and start any animations that were waiting.
+ notifyCompositorAnimationStarted(monotonicallyIncreasingTime());
+ return false;
+}
+
+void CSSPendingAnimations::notifyCompositorAnimationStarted(double monotonicAnimationStartTime)
+{
+ for (size_t i = 0; i < m_waitingForCompositorAnimationStart.size(); ++i) {
+ Player* player = m_waitingForCompositorAnimationStart[i].get();
+ player->setStartTime(monotonicAnimationStartTime - player->timeline().zeroTime());
+ }
+
+ m_waitingForCompositorAnimationStart.clear();
+}
+
+} // namespace
diff --git a/chromium/third_party/WebKit/Source/core/animation/css/CSSPendingAnimations.h b/chromium/third_party/WebKit/Source/core/animation/css/CSSPendingAnimations.h
new file mode 100644
index 00000000000..1bb3c28d4c0
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/animation/css/CSSPendingAnimations.h
@@ -0,0 +1,56 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef CSSPendingAnimations_h
+#define CSSPendingAnimations_h
+
+#include "core/animation/Player.h"
+#include "wtf/Vector.h"
+
+namespace WebCore {
+
+// Used to synchronize the start of main-thread animations with compositor
+// animations when both classes of CSS Animations are triggered by the same recalc
+class CSSPendingAnimations FINAL {
+public:
+ void add(Player*);
+ // Returns whether we are waiting for an animation to start and should
+ // service again on the next frame.
+ bool startPendingAnimations();
+ void notifyCompositorAnimationStarted(double monotonicAnimationStartTime);
+
+private:
+ Vector<std::pair<RefPtr<Player>, double> > m_pending;
+ Vector<RefPtr<Player> > m_waitingForCompositorAnimationStart;
+};
+
+} // namespace WebCore
+
+#endif
diff --git a/chromium/third_party/WebKit/Source/core/animation/css/TransitionTimeline.cpp b/chromium/third_party/WebKit/Source/core/animation/css/TransitionTimeline.cpp
new file mode 100644
index 00000000000..33ec27f2b0b
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/animation/css/TransitionTimeline.cpp
@@ -0,0 +1,52 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/animation/css/TransitionTimeline.h"
+
+#include "core/animation/ActiveAnimations.h"
+#include "core/animation/AnimationClock.h"
+#include "core/animation/AnimationStack.h"
+
+namespace WebCore {
+
+PassRefPtr<TransitionTimeline> TransitionTimeline::create(Document* document, PassOwnPtr<PlatformTiming> timing)
+{
+ return adoptRef(new TransitionTimeline(document, timing));
+}
+
+TransitionTimeline::TransitionTimeline(Document* document, PassOwnPtr<PlatformTiming> timing)
+ : DocumentTimeline(document, timing)
+{
+ setZeroTime(document->animationClock().currentTime());
+ document->animationClock().unfreeze();
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/animation/css/TransitionTimeline.h b/chromium/third_party/WebKit/Source/core/animation/css/TransitionTimeline.h
new file mode 100644
index 00000000000..6d55f48772e
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/animation/css/TransitionTimeline.h
@@ -0,0 +1,48 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef TransitionTimeline_h
+#define TransitionTimeline_h
+
+#include "core/animation/DocumentTimeline.h"
+
+namespace WebCore {
+
+class TransitionTimeline FINAL : public DocumentTimeline {
+public:
+ static PassRefPtr<TransitionTimeline> create(Document*, PassOwnPtr<PlatformTiming> = nullptr);
+
+private:
+ TransitionTimeline(Document*, PassOwnPtr<PlatformTiming>);
+};
+
+} // namespace WebCore
+
+#endif
diff --git a/chromium/third_party/WebKit/Source/core/core.gyp b/chromium/third_party/WebKit/Source/core/core.gyp
index 84d92d99c30..8b8a8b589c5 100644
--- a/chromium/third_party/WebKit/Source/core/core.gyp
+++ b/chromium/third_party/WebKit/Source/core/core.gyp
@@ -31,7 +31,8 @@
{
'includes': [
'../build/win/precompile.gypi',
- 'features.gypi',
+ '../build/features.gypi',
+ '../build/scripts/scripts.gypi',
'../modules/modules.gypi',
'../bindings/bindings.gypi',
'core.gypi',
@@ -172,7 +173,7 @@
'output_file_path': '<(SHARED_INTERMEDIATE_DIR)/blink/InspectorOverlayPage.h',
'character_array_name': 'InspectorOverlayPage_html',
},
- 'includes': [ 'ConvertFileToHeaderWithCharacterArray.gypi' ],
+ 'includes': [ '../build/ConvertFileToHeaderWithCharacterArray.gypi' ],
},
{
'target_name': 'injected_canvas_script_source',
@@ -182,7 +183,7 @@
'output_file_path': '<(SHARED_INTERMEDIATE_DIR)/blink/InjectedScriptCanvasModuleSource.h',
'character_array_name': 'InjectedScriptCanvasModuleSource_js',
},
- 'includes': [ 'ConvertFileToHeaderWithCharacterArray.gypi' ],
+ 'includes': [ '../build/ConvertFileToHeaderWithCharacterArray.gypi' ],
},
{
'target_name': 'injected_script_source',
@@ -192,7 +193,7 @@
'output_file_path': '<(SHARED_INTERMEDIATE_DIR)/blink/InjectedScriptSource.h',
'character_array_name': 'InjectedScriptSource_js',
},
- 'includes': [ 'ConvertFileToHeaderWithCharacterArray.gypi' ],
+ 'includes': [ '../build/ConvertFileToHeaderWithCharacterArray.gypi' ],
},
{
'target_name': 'debugger_script_source',
@@ -202,7 +203,7 @@
'output_file_path': '<(SHARED_INTERMEDIATE_DIR)/blink/DebuggerScriptSource.h',
'character_array_name': 'DebuggerScriptSource_js',
},
- 'includes': [ 'ConvertFileToHeaderWithCharacterArray.gypi' ],
+ 'includes': [ '../build/ConvertFileToHeaderWithCharacterArray.gypi' ],
},
{
'target_name': 'webcore_derived',
@@ -211,14 +212,16 @@
'dependencies': [
'webcore_prerequisites',
'../bindings/derived_sources.gyp:bindings_derived_sources',
- 'core_derived_sources.gyp:make_derived_sources',
+ 'core_derived_sources.gyp:make_core_derived_sources',
'inspector_overlay_page',
'inspector_protocol_sources',
'inspector_instrumentation_sources',
'injected_canvas_script_source',
'injected_script_source',
'debugger_script_source',
+ '../platform/platform_derived_sources.gyp:make_platform_derived_sources',
'../wtf/wtf.gyp:wtf',
+ '<(DEPTH)/gin/gin.gyp:gin',
'<(DEPTH)/skia/skia.gyp:skia',
'<(DEPTH)/third_party/iccjpeg/iccjpeg.gyp:iccjpeg',
'<(DEPTH)/third_party/libpng/libpng.gyp:libpng',
@@ -230,7 +233,6 @@
'<(DEPTH)/third_party/sqlite/sqlite.gyp:sqlite',
'<(DEPTH)/url/url.gyp:url_lib',
'<(DEPTH)/v8/tools/gyp/v8.gyp:v8',
- '<(libjpeg_gyp_path):libjpeg',
],
'include_dirs': [
'<(SHARED_INTERMEDIATE_DIR)/blink',
@@ -240,13 +242,9 @@
# FIXME: Remove these once the bindings script generates qualified
# includes for these correctly. (Sequences don't work yet.)
'<(bindings_dir)/v8/custom',
- '../modules/mediastream',
- '../modules/speech',
- 'dom',
'html',
'html/shadow',
'inspector',
- 'page',
'svg',
],
'sources': [
@@ -256,41 +254,49 @@
'<@(bindings_files)',
# Additional .cpp files for HashTools.h
- '<(SHARED_INTERMEDIATE_DIR)/blink/ColorData.cpp',
'<(SHARED_INTERMEDIATE_DIR)/blink/CSSPropertyNames.cpp',
'<(SHARED_INTERMEDIATE_DIR)/blink/CSSValueKeywords.cpp',
- # Additional .cpp files from make_derived_sources actions.
- '<(SHARED_INTERMEDIATE_DIR)/blink/HTMLElementFactory.cpp',
- '<(SHARED_INTERMEDIATE_DIR)/blink/HTMLNames.cpp',
- '<(SHARED_INTERMEDIATE_DIR)/blink/FetchInitiatorTypeNames.cpp',
- '<(SHARED_INTERMEDIATE_DIR)/blink/CalendarPicker.cpp',
- '<(SHARED_INTERMEDIATE_DIR)/blink/ColorSuggestionPicker.cpp',
+ # Additional .cpp files from make_core_derived_sources actions.
'<(SHARED_INTERMEDIATE_DIR)/blink/Event.cpp',
'<(SHARED_INTERMEDIATE_DIR)/blink/EventHeaders.h',
'<(SHARED_INTERMEDIATE_DIR)/blink/EventInterfaces.h',
+ '<(SHARED_INTERMEDIATE_DIR)/blink/EventNames.cpp',
+ '<(SHARED_INTERMEDIATE_DIR)/blink/EventNames.h',
'<(SHARED_INTERMEDIATE_DIR)/blink/EventTargetHeaders.h',
'<(SHARED_INTERMEDIATE_DIR)/blink/EventTargetInterfaces.h',
- '<(SHARED_INTERMEDIATE_DIR)/blink/PickerCommon.cpp',
+ '<(SHARED_INTERMEDIATE_DIR)/blink/EventTargetNames.cpp',
+ '<(SHARED_INTERMEDIATE_DIR)/blink/EventTargetNames.h',
+ '<(SHARED_INTERMEDIATE_DIR)/blink/EventTypeNames.cpp',
+ '<(SHARED_INTERMEDIATE_DIR)/blink/EventTypeNames.h',
+ '<(SHARED_INTERMEDIATE_DIR)/blink/FetchInitiatorTypeNames.cpp',
+ '<(SHARED_INTERMEDIATE_DIR)/blink/HTMLElementFactory.cpp',
+ '<(SHARED_INTERMEDIATE_DIR)/blink/HTMLElementFactory.h',
+ '<(SHARED_INTERMEDIATE_DIR)/blink/HTMLElementLookupTrie.cpp',
+ '<(SHARED_INTERMEDIATE_DIR)/blink/HTMLElementLookupTrie.h',
+ '<(SHARED_INTERMEDIATE_DIR)/blink/HTMLNames.cpp',
+ '<(SHARED_INTERMEDIATE_DIR)/blink/InputTypeNames.cpp',
+ '<(SHARED_INTERMEDIATE_DIR)/blink/MathMLNames.cpp',
+ '<(SHARED_INTERMEDIATE_DIR)/blink/SVGNames.cpp',
'<(SHARED_INTERMEDIATE_DIR)/blink/UserAgentStyleSheetsData.cpp',
'<(SHARED_INTERMEDIATE_DIR)/blink/V8HTMLElementWrapperFactory.cpp',
'<(SHARED_INTERMEDIATE_DIR)/blink/XLinkNames.cpp',
'<(SHARED_INTERMEDIATE_DIR)/blink/XMLNSNames.cpp',
'<(SHARED_INTERMEDIATE_DIR)/blink/XMLNames.cpp',
- '<(SHARED_INTERMEDIATE_DIR)/blink/SVGNames.cpp',
- '<(SHARED_INTERMEDIATE_DIR)/blink/MathMLNames.cpp',
- '<(SHARED_INTERMEDIATE_DIR)/blink/FontFamilyNames.cpp',
# Generated from HTMLEntityNames.in
'<(SHARED_INTERMEDIATE_DIR)/blink/HTMLEntityTable.cpp',
- # Generated from RuntimeEnabledFeatures.in
- '<(SHARED_INTERMEDIATE_DIR)/blink/RuntimeEnabledFeatures.cpp',
+ # Generated from CSSTokenizer-in.cpp
+ '<(SHARED_INTERMEDIATE_DIR)/blink/CSSTokenizer.cpp',
# Generated from CSSParser-in.cpp
'<(SHARED_INTERMEDIATE_DIR)/blink/CSSParser.cpp',
- # Additional .cpp files from the make_derived_sources rules.
+ # Generated from HTMLMetaElement-in.cpp
+ '<(SHARED_INTERMEDIATE_DIR)/blink/HTMLMetaElement.cpp',
+
+ # Additional .cpp files from the make_core_derived_sources rules.
'<(SHARED_INTERMEDIATE_DIR)/blink/CSSGrammar.cpp',
'<(SHARED_INTERMEDIATE_DIR)/blink/XPathGrammar.cpp',
@@ -326,9 +332,6 @@
],
}],
['OS=="win"', {
- 'defines': [
- '__PRETTY_FUNCTION__=__FUNCTION__',
- ],
# In generated bindings code: 'switch contains default but no case'.
# Disable c4267 warnings until we fix size_t to int truncations.
'msvs_disabled_warnings': [ 4065, 4267 ],
@@ -353,13 +356,14 @@
'inspector_protocol_sources',
'inspector_instrumentation_sources',
'../bindings/derived_sources.gyp:bindings_derived_sources',
- 'core_derived_sources.gyp:make_derived_sources',
+ 'core_derived_sources.gyp:make_core_derived_sources',
'../wtf/wtf.gyp:wtf',
'../config.gyp:config',
- '../weborigin/weborigin.gyp:weborigin',
- '<(DEPTH)/third_party/angle_dx11/src/build_angle.gyp:translator_glsl',
+ '../heap/blink_heap.gyp:blink_heap',
+ '../platform/blink_platform.gyp:blink_platform',
'<(DEPTH)/gpu/gpu.gyp:gles2_c_lib',
'<(DEPTH)/skia/skia.gyp:skia',
+ '<(angle_path)/src/build_angle.gyp:translator',
'<(DEPTH)/third_party/iccjpeg/iccjpeg.gyp:iccjpeg',
'<(DEPTH)/third_party/libpng/libpng.gyp:libpng',
'<(DEPTH)/third_party/libwebp/libwebp.gyp:libwebp',
@@ -372,14 +376,14 @@
'<(DEPTH)/third_party/zlib/zlib.gyp:zlib',
'<(DEPTH)/url/url.gyp:url_lib',
'<(DEPTH)/v8/tools/gyp/v8.gyp:v8',
- '<(libjpeg_gyp_path):libjpeg',
],
'export_dependent_settings': [
'../wtf/wtf.gyp:wtf',
'../config.gyp:config',
- '<(DEPTH)/third_party/angle_dx11/src/build_angle.gyp:translator_glsl',
+ '../heap/blink_heap.gyp:blink_heap',
'<(DEPTH)/gpu/gpu.gyp:gles2_c_lib',
'<(DEPTH)/skia/skia.gyp:skia',
+ '<(angle_path)/src/build_angle.gyp:translator',
'<(DEPTH)/third_party/iccjpeg/iccjpeg.gyp:iccjpeg',
'<(DEPTH)/third_party/libpng/libpng.gyp:libpng',
'<(DEPTH)/third_party/libwebp/libwebp.gyp:libwebp',
@@ -392,22 +396,17 @@
'<(DEPTH)/third_party/zlib/zlib.gyp:zlib',
'<(DEPTH)/url/url.gyp:url_lib',
'<(DEPTH)/v8/tools/gyp/v8.gyp:v8',
- '<(libjpeg_gyp_path):libjpeg',
],
'direct_dependent_settings': {
'defines': [
- 'WEBKIT_IMPLEMENTATION=1',
- 'INSIDE_WEBKIT',
+ 'BLINK_IMPLEMENTATION=1',
+ 'INSIDE_BLINK',
],
'include_dirs': [
'<@(webcore_include_dirs)',
'<(DEPTH)/gpu',
- '<(DEPTH)/third_party/angle_dx11/include/GLSLANG',
- ],
- 'msvs_disabled_warnings': [
- 4138, 4244, 4291, 4305, 4344, 4355, 4521, 4099,
+ '<(angle_path)/include',
],
- 'scons_line_length' : 1,
'xcode_settings': {
# Some Mac-specific parts of WebKit won't compile without having this
# prefix header injected.
@@ -473,17 +472,10 @@
# If this is unhandled, the console will receive log messages
# such as:
# com.google.Chrome[] objc[]: Class ScrollbarPrefsObserver is implemented in both .../Google Chrome.app/Contents/Versions/.../Google Chrome Helper.app/Contents/MacOS/../../../Google Chrome Framework.framework/Google Chrome Framework and /System/Library/Frameworks/WebKit.framework/Versions/A/Frameworks/WebCore.framework/Versions/A/WebCore. One of the two will be used. Which one is undefined.
- 'WebCascadeList=ChromiumWebCoreObjCWebCascadeList',
'WebCoreFlippedView=ChromiumWebCoreObjCWebCoreFlippedView',
'WebCoreTextFieldCell=ChromiumWebCoreObjCWebCoreTextFieldCell',
- 'WebScrollbarPrefsObserver=ChromiumWebCoreObjCWebScrollbarPrefsObserver',
'WebCoreRenderThemeNotificationObserver=ChromiumWebCoreObjCWebCoreRenderThemeNotificationObserver',
- 'WebFontCache=ChromiumWebCoreObjCWebFontCache',
- 'WebScrollAnimationHelperDelegate=ChromiumWebCoreObjCWebScrollAnimationHelperDelegate',
- 'WebScrollbarPainterControllerDelegate=ChromiumWebCoreObjCWebScrollbarPainterControllerDelegate',
- 'WebScrollbarPainterDelegate=ChromiumWebCoreObjCWebScrollbarPainterDelegate',
- 'WebScrollbarPartAnimation=ChromiumWebCoreObjCWebScrollbarPartAnimation',
- ],
+ ],
'postbuilds': [
{
# This step ensures that any Objective-C names that aren't
@@ -491,12 +483,12 @@
'postbuild_name': 'Check Objective-C Rename',
'variables': {
'class_whitelist_regex':
- 'ChromiumWebCoreObjC|TCMVisibleView|RTCMFlippedView',
+ 'ChromiumWebCoreObjC|TCMVisibleView|RTCMFlippedView|ScrollerStyleObserver',
'category_whitelist_regex':
'TCMInterposing|ScrollAnimatorChromiumMacExt|WebCoreTheme',
},
'action': [
- 'scripts/check_objc_rename.sh',
+ '../build/scripts/check_objc_rename.sh',
'<(class_whitelist_regex)',
'<(category_whitelist_regex)',
],
@@ -504,13 +496,6 @@
],
},
}],
- ['OS=="win"', {
- 'direct_dependent_settings': {
- 'defines': [
- '__PRETTY_FUNCTION__=__FUNCTION__',
- ],
- },
- }],
['OS in ("linux", "android") and "WTF_USE_WEBAUDIO_IPP=1" in feature_defines', {
'direct_dependent_settings': {
'cflags': [
@@ -556,10 +541,6 @@
'sources': [
'<@(webcore_dom_files)',
],
- 'sources!': [
- 'dom/default/PlatformMessagePortChannel.cpp',
- 'dom/default/PlatformMessagePortChannel.h',
- ],
# Disable c4267 warnings until we fix size_t to int truncations.
'msvs_disabled_warnings': [ 4267, ],
},
@@ -610,33 +591,8 @@
# Used only by mac.
['exclude', 'platform/Theme\\.cpp$'],
-
- # *NEON.cpp files need special compile options.
- # They are moved to the webcore_arm_neon target.
- ['exclude', 'platform/graphics/cpu/arm/filters/.*NEON\\.(cpp|h)'],
],
'conditions': [
- ['OS=="linux" or OS=="android"', {
- 'sources/': [
- # Cherry-pick files excluded by the broader regular expressions above.
- ['include', 'platform/graphics/harfbuzz/FontHarfBuzz\\.cpp$'],
- ['include', 'platform/graphics/harfbuzz/FontPlatformDataHarfBuzz\\.cpp$'],
- ['include', 'platform/graphics/harfbuzz/HarfBuzzFace\\.(cpp|h)$'],
- ['include', 'platform/graphics/harfbuzz/HarfBuzzFaceSkia\\.cpp$'],
- ['include', 'platform/graphics/harfbuzz/HarfBuzzShaper\\.(cpp|h)$'],
- ['include', 'platform/graphics/harfbuzz/HarfBuzzShaperBase\\.(cpp|h)$'],
- ['include', 'platform/graphics/opentype/OpenTypeTypes\\.h$'],
- ['include', 'platform/graphics/opentype/OpenTypeVerticalData\\.(cpp|h)$'],
- ['include', 'platform/graphics/skia/SimpleFontDataSkia\\.cpp$'],
- ],
- 'dependencies': [
- '<(DEPTH)/third_party/harfbuzz-ng/harfbuzz.gyp:harfbuzz-ng',
- ],
- }, { # OS!="linux" and OS!="android"
- 'sources/': [
- ['exclude', 'Harfbuzz[^/]+\\.(cpp|h)$'],
- ],
- }],
['OS!="linux"', {
'sources/': [
['exclude', 'Linux\\.cpp$'],
@@ -648,12 +604,14 @@
],
}],
['OS=="mac"', {
- 'dependencies': [
- '<(DEPTH)/third_party/harfbuzz-ng/harfbuzz.gyp:harfbuzz-ng',
- ],
'sources': [
'editing/SmartReplaceCF.cpp',
],
+ 'link_settings': {
+ 'libraries': [
+ '$(SDKROOT)/System/Library/Frameworks/Carbon.framework',
+ ],
+ },
'sources/': [
# Additional files from the WebCore Mac build that are presently
# used in the WebCore Chromium Mac build too.
@@ -661,30 +619,9 @@
# The Mac build is USE(CF).
['include', 'CF\\.cpp$'],
- # Use native Mac font code from core.
- ['include', 'platform/(graphics/)?mac/[^/]*Font[^/]*\\.(cpp|mm?)$'],
- ['include', 'platform/graphics/mac/ComplexText[^/]*\\.(cpp|h)$'],
-
- # We can use this for the fast Accelerate.framework FFT.
- ['include', 'platform/audio/mac/FFTFrameMac\\.cpp$'],
-
# Cherry-pick some files that can't be included by broader regexps.
# Some of these are used instead of Chromium platform files, see
# the specific exclusions in the "exclude" list below.
- ['include', 'platform/graphics/mac/ColorMac\\.mm$'],
- ['include', 'platform/graphics/mac/ComplexTextControllerCoreText\\.mm$'],
- ['include', 'platform/graphics/mac/FloatPointMac\\.mm$'],
- ['include', 'platform/graphics/mac/FloatRectMac\\.mm$'],
- ['include', 'platform/graphics/mac/FloatSizeMac\\.mm$'],
- ['include', 'platform/graphics/mac/GlyphPageTreeNodeMac\\.cpp$'],
- ['include', 'platform/graphics/mac/IntPointMac\\.mm$'],
- ['include', 'platform/graphics/mac/IntRectMac\\.mm$'],
- ['include', 'platform/mac/BlockExceptions\\.mm$'],
- ['include', 'platform/mac/KillRingMac\\.mm$'],
- ['include', 'platform/mac/LocalCurrentGraphicsContext\\.mm$'],
- ['include', 'platform/mac/NSScrollerImpDetails\\.mm$'],
- ['include', 'platform/mac/ScrollAnimatorMac\\.mm$'],
- ['include', 'platform/mac/ScrollElasticityController\\.mm$'],
['include', 'platform/mac/ThemeMac\\.h$'],
['include', 'platform/mac/ThemeMac\\.mm$'],
['include', 'platform/mac/WebCoreSystemInterface\\.h$'],
@@ -693,105 +630,15 @@
['include', 'platform/text/mac/String(Impl)?Mac\\.mm$'],
# Use USE_NEW_THEME on Mac.
['include', 'platform/Theme\\.cpp$'],
-
- # We use LocaleMac.mm instead of LocaleICU.cpp in order to
- # apply system locales.
- ['exclude', 'platform/text/LocaleICU\\.cpp$'],
- ['exclude', 'platform/text/LocaleICU\\.h$'],
- ['include', 'platform/text/mac/LocaleMac\\.mm$'],
-
- # The Mac uses platform/mac/KillRingMac.mm instead of the dummy
- # implementation.
- ['exclude', 'platform/KillRingNone\\.cpp$'],
-
- # The Mac currently uses FontCustomPlatformDataMac.cpp,
- # included by regex above, instead.
- ['exclude', 'platform/graphics/skia/FontCustomPlatformDataSkia\\.cpp$'],
-
- ['exclude', 'platform/ScrollbarThemeNonMacCommon\\.(cpp|h)$'],
-
- # Mac uses only ScrollAnimatorMac.
- ['exclude', 'platform/ScrollAnimatorNone\\.cpp$'],
- ['exclude', 'platform/ScrollAnimatorNone\\.h$'],
-
- ['include', 'platform/graphics/cg/FloatPointCG\\.cpp$'],
- ['include', 'platform/graphics/cg/FloatRectCG\\.cpp$'],
- ['include', 'platform/graphics/cg/FloatSizeCG\\.cpp$'],
- ['include', 'platform/graphics/cg/IntPointCG\\.cpp$'],
- ['include', 'platform/graphics/cg/IntRectCG\\.cpp$'],
- ['include', 'platform/graphics/cg/IntSizeCG\\.cpp$'],
- ['exclude', 'platform/graphics/skia/FontCacheSkia\\.cpp$'],
- ['exclude', 'platform/graphics/skia/GlyphPageTreeNodeSkia\\.cpp$'],
- ['exclude', 'platform/graphics/skia/SimpleFontDataSkia\\.cpp$'],
-
- # Mac uses Harfbuzz.
- ['include', 'platform/graphics/harfbuzz/HarfBuzzFaceCoreText\\.cpp$'],
- ['include', 'platform/graphics/harfbuzz/HarfBuzzFace\\.(cpp|h)$'],
- ['include', 'platform/graphics/harfbuzz/HarfBuzzShaper\\.(cpp|h)$'],
- ['include', 'platform/graphics/harfbuzz/HarfBuzzShaperBase\\.(cpp|h)$'],
- ],
- },{ # OS!="mac"
- 'sources/': [
- ['exclude', 'Mac\\.(cpp|mm?)$'],
- ['exclude', 'ScrollbarThemeMac'],
-
- # FIXME: We will eventually compile this too, but for now it's
- # only used on mac.
- ['exclude', 'platform/graphics/FontPlatformData\\.cpp$'],
- ],
- }],
- ['OS != "linux" and OS != "mac" and (OS != "win" or (OS == "win" and "ENABLE_GDI_FONTS_ON_WINDOWS=1" in feature_defines))', {
- 'sources/': [
- ['exclude', 'VDMX[^/]+\\.(cpp|h)$'],
],
}],
['OS=="win"', {
'sources/': [
['exclude', 'Posix\\.cpp$'],
-
- ['include', 'platform/ScrollbarThemeWin\\.(cpp|h)$'],
- ['include', 'platform/graphics/chromium/TransparencyWin\\.(cpp|h)$'],
- ['include', 'platform/graphics/opentype/'],
- ['include', 'platform/graphics/skia/SkiaFontWin\\.(cpp|h)$'],
-
- # Windows currently uses FontCustomPlatformDataWin.cpp instead.
- ['exclude', 'platform/graphics/skia/FontCustomPlatformDataSkia\\.cpp$'],
- ['include', 'platform/graphics/win/FontCustomPlatformDataWin\\.cpp$'],
-
- # SystemInfo.cpp is useful and we don't want to copy it.
- ['include', 'platform/win/SystemInfo\\.cpp$'],
-
- ['exclude', 'platform/text/LocaleICU\\.cpp$'],
- ['exclude', 'platform/text/LocaleICU\\.h$'],
- ['include', 'platform/text/win/LocaleWin\.cpp$'],
- ['include', 'platform/text/win/LocaleWin\.h$'],
- ],
- 'conditions': [
- ['"ENABLE_GDI_FONTS_ON_WINDOWS=1" in feature_defines', {
- 'sources/': [
- ['exclude', 'platform/graphics/skia/SimpleFontDataSkia\\.cpp$'],
- ['exclude', 'platform/graphics/skia/GlyphPageTreeNodeSkia\\.cpp$'],
- ['exclude', 'platform/graphics/skia/FontCacheSkia\\.cpp$'],
- ['exclude', 'platform/graphics/skia/FontCacheSkiaWin\\.cpp$'],
- ],
- },{ # ENABLE_GDI_FONTS_ON_WINDOWS!=1
- 'sources/': [
- ['include', 'platform/graphics/skia/SimpleFontDataSkia\\.cpp$'],
- ['include', 'platform/graphics/skia/GlyphPageTreeNodeSkia\\.cpp$'],
- ['include', 'platform/graphics/skia/FontCacheSkiaWin\\.cpp$'],
- ['include', 'platform/graphics/skia/FontCustomPlatformDataSkia\\.cpp$'],
- ['exclude', 'platform/graphics/chromium/SimpleFontDataChromiumWin\\.cpp$'],
- ['exclude', 'platform/graphics/chromium/GlyphPageTreeNodeChromiumWin\\.cpp$'],
- ['exclude', 'platform/graphics/chromium/FontCacheChromiumWin\\.cpp$'],
- ['exclude', 'platform/graphics/win/FontCustomPlatformDataWin\\.cpp$'],
- ],
- }],
],
},{ # OS!="win"
'sources/': [
['exclude', 'Win\\.cpp$'],
- ['exclude', '/(Windows|Uniscribe)[^/]*\\.cpp$'],
- ['include', 'platform/graphics/opentype/OpenTypeSanitizer\\.cpp$'],
],
}],
['OS=="win" and chromium_win_pch==1', {
@@ -803,8 +650,6 @@
'sources/': [
['include', 'platform/chromium/ClipboardChromiumLinux\\.cpp$'],
['include', 'platform/chromium/FileSystemChromiumLinux\\.cpp$'],
- ['include', 'platform/graphics/chromium/GlyphPageTreeNodeLinux\\.cpp$'],
- ['include', 'platform/graphics/chromium/VDMXParser\\.cpp$'],
],
}, { # OS!="android"
'sources/': [
@@ -813,58 +658,16 @@
}],
['use_default_render_theme==1', {
'sources/': [
- ['exclude', 'platform/ScrollbarThemeWin\\.(cpp|h)'],
['exclude', 'platform/chromium/PlatformThemeChromiumWin\\.(cpp|h)'],
],
}, { # use_default_render_theme==0
'sources/': [
- ['exclude', 'platform/ScrollbarThemeAuraOrGtk\\.(cpp|h)'],
['exclude', 'platform/chromium/PlatformThemeChromiumDefault\\.(cpp|h)'],
],
}],
],
},
{
- 'target_name': 'webcore_platform_geometry',
- 'type': 'static_library',
- 'dependencies': [
- 'webcore_prerequisites',
- ],
- 'sources': [
- '<@(webcore_platform_geometry_files)',
- ],
- },
- # The *NEON.cpp files fail to compile when -mthumb is passed. Force
- # them to build in ARM mode.
- # See https://bugs.webkit.org/show_bug.cgi?id=62916.
- {
- 'target_name': 'webcore_arm_neon',
- 'conditions': [
- ['target_arch=="arm"', {
- 'type': 'static_library',
- 'dependencies': [
- 'webcore_prerequisites',
- ],
- 'hard_dependency': 1,
- 'sources': [
- '<@(webcore_files)',
- ],
- 'sources/': [
- ['exclude', '.*'],
- ['include', 'platform/graphics/cpu/arm/filters/.*NEON\\.(cpp|h)'],
- ],
- 'cflags': ['-marm'],
- 'conditions': [
- ['OS=="android"', {
- 'cflags!': ['-mthumb'],
- }],
- ],
- },{ # target_arch!="arm"
- 'type': 'none',
- }],
- ],
- },
- {
'target_name': 'webcore_rendering',
'type': 'static_library',
'dependencies': [
@@ -1011,7 +814,6 @@
'webcore_dom',
'webcore_html',
'webcore_platform',
- 'webcore_platform_geometry',
'webcore_remaining',
'webcore_rendering',
'webcore_svg',
@@ -1019,6 +821,7 @@
'webcore_derived',
'../wtf/wtf.gyp:wtf',
'<(DEPTH)/skia/skia.gyp:skia',
+ '<(DEPTH)/third_party/khronos/khronos.gyp:khronos_headers',
'<(DEPTH)/third_party/npapi/npapi.gyp:npapi',
'<(DEPTH)/third_party/qcms/qcms.gyp:qcms',
'<(DEPTH)/url/url.gyp:url_lib',
@@ -1028,6 +831,7 @@
'../wtf/wtf.gyp:wtf',
'webcore_derived',
'<(DEPTH)/skia/skia.gyp:skia',
+ '<(DEPTH)/third_party/khronos/khronos.gyp:khronos_headers',
'<(DEPTH)/third_party/npapi/npapi.gyp:npapi',
'<(DEPTH)/third_party/qcms/qcms.gyp:qcms',
'<(DEPTH)/url/url.gyp:url_lib',
@@ -1039,18 +843,6 @@
],
},
'conditions': [
- ['target_arch=="arm"', {
- 'dependencies': [
- 'webcore_arm_neon',
- ],
- }],
- ['OS=="mac"', {
- 'direct_dependent_settings': {
- 'include_dirs': [
- '../WebKit/mac/WebCoreSupport',
- ],
- },
- }],
['OS=="linux" and "WTF_USE_WEBAUDIO_IPP=1" in feature_defines', {
'link_settings': {
'ldflags': [
@@ -1080,8 +872,8 @@
'webcore',
],
'defines': [
- 'WEBKIT_IMPLEMENTATION=1',
- 'INSIDE_WEBKIT',
+ 'BLINK_IMPLEMENTATION=1',
+ 'INSIDE_BLINK',
],
'include_dirs': [
'<(bindings_dir)/v8', # FIXME: Remove once http://crbug.com/236119 is fixed.
diff --git a/chromium/third_party/WebKit/Source/core/core.gypi b/chromium/third_party/WebKit/Source/core/core.gypi
index 3cd07aaf092..03c64b57f96 100644
--- a/chromium/third_party/WebKit/Source/core/core.gypi
+++ b/chromium/third_party/WebKit/Source/core/core.gypi
@@ -1,11 +1,11 @@
{
'variables': {
'core_idl_files': [
+ 'animation/ElementAnimation.idl',
'css/CSS.idl',
'css/CSSCharsetRule.idl',
'css/CSSFontFaceLoadEvent.idl',
'css/CSSFontFaceRule.idl',
- 'css/CSSHostRule.idl',
'css/CSSImportRule.idl',
'css/CSSKeyframeRule.idl',
'css/CSSKeyframesRule.idl',
@@ -23,11 +23,13 @@
# 'css/CSSUnknownRule.idl',
'css/CSSValue.idl',
'css/CSSValueList.idl',
- 'css/CSSViewportRule.idl',
'css/CSSVariablesMap.idl',
+ 'css/CSSVariablesMapForEachCallback.idl',
+ 'css/CSSViewportRule.idl',
'css/Counter.idl',
- 'css/FontFaceSet.idl',
+ 'css/DocumentFontFaceSet.idl',
'css/FontFace.idl',
+ 'css/FontFaceSet.idl',
'css/MediaList.idl',
'css/MediaQueryList.idl',
'css/RGBColor.idl',
@@ -42,9 +44,6 @@
'css/WebKitCSSRegionRule.idl',
'css/WebKitCSSTransformValue.idl',
'dom/Attr.idl',
- 'dom/AutocompleteErrorEvent.idl',
- 'dom/BeforeLoadEvent.idl',
- 'dom/BeforeUnloadEvent.idl',
'dom/CDATASection.idl',
'dom/CharacterData.idl',
'dom/ChildNode.idl',
@@ -52,8 +51,6 @@
'dom/ClientRectList.idl',
'dom/Clipboard.idl',
'dom/Comment.idl',
- 'dom/CompositionEvent.idl',
- 'dom/CustomEvent.idl',
'dom/DOMError.idl',
'dom/DOMException.idl',
'dom/DOMImplementation.idl',
@@ -69,17 +66,9 @@
'dom/DocumentType.idl',
'dom/Element.idl',
'dom/Entity.idl',
- 'dom/ErrorEvent.idl',
- 'dom/Event.idl',
- 'dom/EventTarget.idl',
- 'dom/FocusEvent.idl',
- 'dom/HashChangeEvent.idl',
- 'dom/KeyboardEvent.idl',
+ 'dom/GlobalEventHandlers.idl',
'dom/MessageChannel.idl',
- 'dom/MessageEvent.idl',
'dom/MessagePort.idl',
- 'dom/MouseEvent.idl',
- 'dom/MutationEvent.idl',
'dom/MutationObserver.idl',
'dom/MutationRecord.idl',
'dom/NamedNodeMap.idl',
@@ -88,31 +77,49 @@
'dom/NodeIterator.idl',
'dom/NodeList.idl',
'dom/Notation.idl',
- 'dom/OverflowEvent.idl',
- 'dom/PageTransitionEvent.idl',
'dom/ParentNode.idl',
- 'dom/PopStateEvent.idl',
'dom/ProcessingInstruction.idl',
- 'dom/ProgressEvent.idl',
'dom/Promise.idl',
'dom/Range.idl',
'dom/RequestAnimationFrameCallback.idl',
- 'dom/ResourceProgressEvent.idl',
- 'dom/SecurityPolicyViolationEvent.idl',
'dom/StringCallback.idl',
'dom/Text.idl',
- 'dom/TextEvent.idl',
'dom/Touch.idl',
- 'dom/TouchEvent.idl',
'dom/TouchList.idl',
- 'dom/TransitionEvent.idl',
'dom/TreeWalker.idl',
- 'dom/UIEvent.idl',
- 'dom/WebKitAnimationEvent.idl',
+ 'dom/URL.idl',
+ 'dom/URLUtils.idl',
+ 'dom/URLUtilsReadOnly.idl',
'dom/WebKitNamedFlow.idl',
'dom/WebKitNamedFlowCollection.idl',
- 'dom/WheelEvent.idl',
'dom/shadow/ShadowRoot.idl',
+ 'events/AutocompleteErrorEvent.idl',
+ 'events/BeforeLoadEvent.idl',
+ 'events/BeforeUnloadEvent.idl',
+ 'events/CompositionEvent.idl',
+ 'events/CustomEvent.idl',
+ 'events/ErrorEvent.idl',
+ 'events/Event.idl',
+ 'events/EventTarget.idl',
+ 'events/FocusEvent.idl',
+ 'events/HashChangeEvent.idl',
+ 'events/KeyboardEvent.idl',
+ 'events/MessageEvent.idl',
+ 'events/MouseEvent.idl',
+ 'events/MutationEvent.idl',
+ 'events/NavigatorEvents.idl',
+ 'events/OverflowEvent.idl',
+ 'events/PageTransitionEvent.idl',
+ 'events/PopStateEvent.idl',
+ 'events/ProgressEvent.idl',
+ 'events/ResourceProgressEvent.idl',
+ 'events/SecurityPolicyViolationEvent.idl',
+ 'events/TextEvent.idl',
+ 'events/TouchEvent.idl',
+ 'events/TransitionEvent.idl',
+ 'events/UIEvent.idl',
+ 'events/WebKitAnimationEvent.idl',
+ 'events/WheelEvent.idl',
'fileapi/Blob.idl',
'fileapi/File.idl',
'fileapi/FileError.idl',
@@ -120,6 +127,22 @@
'fileapi/FileReader.idl',
'fileapi/FileReaderSync.idl',
'fileapi/Stream.idl',
+ 'frame/BarProp.idl',
+ 'frame/Console.idl',
+ 'frame/ConsoleBase.idl',
+ 'frame/History.idl',
+ 'frame/ImageBitmap.idl',
+ 'frame/Location.idl',
+ 'frame/Navigator.idl',
+ 'frame/NavigatorID.idl',
+ 'frame/NavigatorOnLine.idl',
+ 'frame/Screen.idl',
+ 'frame/SecurityPolicy.idl',
+ 'frame/WebKitPoint.idl',
+ 'frame/Window.idl',
+ 'frame/WindowBase64.idl',
+ 'frame/WindowEventHandlers.idl',
+ 'frame/WindowTimers.idl',
'html/FormData.idl',
'html/HTMLAllCollection.idl',
'html/HTMLAnchorElement.idl',
@@ -188,8 +211,8 @@
'html/HTMLTableElement.idl',
'html/HTMLTableRowElement.idl',
'html/HTMLTableSectionElement.idl',
- 'html/HTMLTextAreaElement.idl',
'html/HTMLTemplateElement.idl',
+ 'html/HTMLTextAreaElement.idl',
'html/HTMLTitleElement.idl',
'html/HTMLTrackElement.idl',
'html/HTMLUListElement.idl',
@@ -203,15 +226,14 @@
'html/RadioNodeList.idl',
'html/TextMetrics.idl',
'html/TimeRanges.idl',
- 'html/URL.idl',
'html/ValidityState.idl',
'html/VoidCallback.idl',
'html/canvas/ANGLEInstancedArrays.idl',
+ 'html/canvas/Canvas2DContextAttributes.idl',
'html/canvas/CanvasGradient.idl',
'html/canvas/CanvasPattern.idl',
'html/canvas/CanvasRenderingContext.idl',
'html/canvas/CanvasRenderingContext2D.idl',
- 'html/canvas/Canvas2DContextAttributes.idl',
'html/canvas/EXTFragDepth.idl',
'html/canvas/EXTTextureFilterAnisotropic.idl',
'html/canvas/OESElementIndexUint.idl',
@@ -252,58 +274,44 @@
'html/track/TextTrackCueList.idl',
'html/track/TextTrackList.idl',
'html/track/TrackEvent.idl',
- 'html/track/TextTrackRegion.idl',
- 'html/track/TextTrackRegionList.idl',
+ 'html/track/vtt/VTTCue.idl',
+ 'html/track/vtt/VTTRegion.idl',
+ 'html/track/vtt/VTTRegionList.idl',
'inspector/InjectedScriptHost.idl',
'inspector/InspectorFrontendHost.idl',
'inspector/InspectorOverlayHost.idl',
'inspector/JavaScriptCallFrame.idl',
'loader/appcache/ApplicationCache.idl',
- 'page/PerformanceNavigation.idl',
- 'page/BarProp.idl',
- 'page/ConsoleBase.idl',
- 'page/Console.idl',
'page/EventSource.idl',
- 'page/History.idl',
- 'page/ImageBitmap.idl',
- 'page/Location.idl',
- 'page/MemoryInfo.idl',
- 'page/Navigator.idl',
- 'page/NavigatorID.idl',
- 'page/NavigatorOnLine.idl',
'page/PagePopupController.idl',
- 'page/Performance.idl',
- 'page/PerformanceEntry.idl',
- 'page/PerformanceMark.idl',
- 'page/PerformanceMeasure.idl',
- 'page/PerformanceResourceTiming.idl',
- 'page/PerformanceTiming.idl',
- 'page/Screen.idl',
- 'page/SecurityPolicy.idl',
'page/Selection.idl',
- 'page/SpeechInputEvent.idl',
- 'page/SpeechInputResult.idl',
- 'page/SpeechInputResultList.idl',
- 'page/WebKitPoint.idl',
- 'page/Window.idl',
- 'page/WindowBase64.idl',
'page/WindowPagePopup.idl',
- 'page/WindowTimers.idl',
- 'page/WorkerNavigator.idl',
'plugins/MimeType.idl',
'plugins/MimeTypeArray.idl',
'plugins/Plugin.idl',
'plugins/PluginArray.idl',
+ 'speech/SpeechInputEvent.idl',
+ 'speech/SpeechInputResult.idl',
+ 'speech/SpeechInputResultList.idl',
'storage/Storage.idl',
'storage/StorageEvent.idl',
+ 'timing/MemoryInfo.idl',
+ 'timing/Performance.idl',
+ 'timing/PerformanceEntry.idl',
+ 'timing/PerformanceMark.idl',
+ 'timing/PerformanceMeasure.idl',
+ 'timing/PerformanceNavigation.idl',
+ 'timing/PerformanceResourceTiming.idl',
+ 'timing/PerformanceTiming.idl',
'workers/AbstractWorker.idl',
'workers/DedicatedWorkerGlobalScope.idl',
'workers/SharedWorker.idl',
'workers/SharedWorkerGlobalScope.idl',
'workers/Worker.idl',
- 'workers/WorkerGlobalScope.idl',
'workers/WorkerConsole.idl',
+ 'workers/WorkerGlobalScope.idl',
'workers/WorkerLocation.idl',
+ 'workers/WorkerNavigator.idl',
'xml/DOMParser.idl',
'xml/DocumentXPathEvaluator.idl',
'xml/XMLHttpRequest.idl',
@@ -391,6 +399,7 @@
'svg/SVGGElement.idl',
'svg/SVGGlyphElement.idl',
'svg/SVGGlyphRefElement.idl',
+ 'svg/SVGGeometryElement.idl',
'svg/SVGGradientElement.idl',
'svg/SVGGraphicsElement.idl',
'svg/SVGHKernElement.idl',
@@ -470,67 +479,94 @@
'Init.cpp',
'Init.h',
'accessibility/AXObjectCache.cpp',
- 'accessibility/AccessibilityARIAGrid.cpp',
- 'accessibility/AccessibilityARIAGrid.h',
- 'accessibility/AccessibilityARIAGridCell.cpp',
- 'accessibility/AccessibilityARIAGridCell.h',
- 'accessibility/AccessibilityARIAGridRow.cpp',
- 'accessibility/AccessibilityARIAGridRow.h',
- 'accessibility/AccessibilityImageMapLink.cpp',
- 'accessibility/AccessibilityImageMapLink.h',
- 'accessibility/AccessibilityList.cpp',
- 'accessibility/AccessibilityList.h',
- 'accessibility/AccessibilityListBox.cpp',
- 'accessibility/AccessibilityListBox.h',
- 'accessibility/AccessibilityListBoxOption.cpp',
- 'accessibility/AccessibilityListBoxOption.h',
- 'accessibility/AccessibilityMediaControls.cpp',
- 'accessibility/AccessibilityMediaControls.h',
- 'accessibility/AccessibilityMenuList.cpp',
- 'accessibility/AccessibilityMenuList.h',
- 'accessibility/AccessibilityMenuListOption.cpp',
- 'accessibility/AccessibilityMenuListOption.h',
- 'accessibility/AccessibilityMenuListPopup.cpp',
- 'accessibility/AccessibilityMenuListPopup.h',
- 'accessibility/AccessibilityMockObject.cpp',
- 'accessibility/AccessibilityMockObject.h',
- 'accessibility/AccessibilityNodeObject.cpp',
- 'accessibility/AccessibilityNodeObject.h',
- 'accessibility/AccessibilityObject.cpp',
- 'accessibility/AccessibilityProgressIndicator.cpp',
- 'accessibility/AccessibilityProgressIndicator.h',
- 'accessibility/AccessibilityRenderObject.cpp',
- 'accessibility/AccessibilityRenderObject.h',
- 'accessibility/AccessibilityScrollView.cpp',
- 'accessibility/AccessibilityScrollView.h',
- 'accessibility/AccessibilityScrollbar.cpp',
- 'accessibility/AccessibilityScrollbar.h',
- 'accessibility/AccessibilitySlider.cpp',
- 'accessibility/AccessibilitySlider.h',
- 'accessibility/AccessibilitySpinButton.cpp',
- 'accessibility/AccessibilitySpinButton.h',
- 'accessibility/AccessibilitySVGRoot.cpp',
- 'accessibility/AccessibilitySVGRoot.h',
- 'accessibility/AccessibilityTable.cpp',
- 'accessibility/AccessibilityTable.h',
- 'accessibility/AccessibilityTableCell.cpp',
- 'accessibility/AccessibilityTableCell.h',
- 'accessibility/AccessibilityTableColumn.cpp',
- 'accessibility/AccessibilityTableColumn.h',
- 'accessibility/AccessibilityTableHeaderContainer.cpp',
- 'accessibility/AccessibilityTableHeaderContainer.h',
- 'accessibility/AccessibilityTableRow.cpp',
- 'accessibility/AccessibilityTableRow.h',
+ 'accessibility/AXARIAGrid.cpp',
+ 'accessibility/AXARIAGrid.h',
+ 'accessibility/AXARIAGridCell.cpp',
+ 'accessibility/AXARIAGridCell.h',
+ 'accessibility/AXARIAGridRow.cpp',
+ 'accessibility/AXARIAGridRow.h',
+ 'accessibility/AXImageMapLink.cpp',
+ 'accessibility/AXImageMapLink.h',
+ 'accessibility/AXInlineTextBox.cpp',
+ 'accessibility/AXInlineTextBox.h',
+ 'accessibility/AXList.cpp',
+ 'accessibility/AXList.h',
+ 'accessibility/AXListBox.cpp',
+ 'accessibility/AXListBox.h',
+ 'accessibility/AXListBoxOption.cpp',
+ 'accessibility/AXListBoxOption.h',
+ 'accessibility/AXMediaControls.cpp',
+ 'accessibility/AXMediaControls.h',
+ 'accessibility/AXMenuList.cpp',
+ 'accessibility/AXMenuList.h',
+ 'accessibility/AXMenuListOption.cpp',
+ 'accessibility/AXMenuListOption.h',
+ 'accessibility/AXMenuListPopup.cpp',
+ 'accessibility/AXMenuListPopup.h',
+ 'accessibility/AXMockObject.cpp',
+ 'accessibility/AXMockObject.h',
+ 'accessibility/AXNodeObject.cpp',
+ 'accessibility/AXNodeObject.h',
+ 'accessibility/AXObject.cpp',
+ 'accessibility/AXProgressIndicator.cpp',
+ 'accessibility/AXProgressIndicator.h',
+ 'accessibility/AXRenderObject.cpp',
+ 'accessibility/AXRenderObject.h',
+ 'accessibility/AXScrollView.cpp',
+ 'accessibility/AXScrollView.h',
+ 'accessibility/AXScrollbar.cpp',
+ 'accessibility/AXScrollbar.h',
+ 'accessibility/AXSlider.cpp',
+ 'accessibility/AXSlider.h',
+ 'accessibility/AXSpinButton.cpp',
+ 'accessibility/AXSpinButton.h',
+ 'accessibility/AXSVGRoot.cpp',
+ 'accessibility/AXSVGRoot.h',
+ 'accessibility/AXTable.cpp',
+ 'accessibility/AXTable.h',
+ 'accessibility/AXTableCell.cpp',
+ 'accessibility/AXTableCell.h',
+ 'accessibility/AXTableColumn.cpp',
+ 'accessibility/AXTableColumn.h',
+ 'accessibility/AXTableHeaderContainer.cpp',
+ 'accessibility/AXTableHeaderContainer.h',
+ 'accessibility/AXTableRow.cpp',
+ 'accessibility/AXTableRow.h',
+ 'animation/ActiveAnimations.cpp',
'animation/ActiveAnimations.h',
- 'animation/AnimatableColor.h',
+ 'animation/AnimatableClipPathOperation.cpp',
+ 'animation/AnimatableClipPathOperation.h',
'animation/AnimatableColor.cpp',
+ 'animation/AnimatableColor.h',
+ 'animation/AnimatableDouble.cpp',
+ 'animation/AnimatableDouble.h',
+ 'animation/AnimatableFilterOperations.cpp',
+ 'animation/AnimatableFilterOperations.h',
'animation/AnimatableImage.cpp',
'animation/AnimatableImage.h',
+ 'animation/AnimatableLength.cpp',
+ 'animation/AnimatableLength.h',
'animation/AnimatableLengthBox.cpp',
'animation/AnimatableLengthBox.h',
+ 'animation/AnimatableLengthBoxAndBool.cpp',
+ 'animation/AnimatableLengthBoxAndBool.h',
+ 'animation/AnimatableLengthPoint.cpp',
+ 'animation/AnimatableLengthPoint.h',
+ 'animation/AnimatableLengthSize.cpp',
+ 'animation/AnimatableLengthSize.h',
'animation/AnimatableNeutral.h',
- 'animation/AnimatableNumber.cpp',
- 'animation/AnimatableNumber.h',
+ 'animation/AnimatableRepeatable.cpp',
+ 'animation/AnimatableRepeatable.h',
+ 'animation/AnimatableSVGLength.cpp',
+ 'animation/AnimatableSVGLength.h',
+ 'animation/AnimatableSVGPaint.cpp',
+ 'animation/AnimatableSVGPaint.h',
+ 'animation/AnimatableShadow.cpp',
+ 'animation/AnimatableShadow.h',
+ 'animation/AnimatableShapeValue.cpp',
+ 'animation/AnimatableShapeValue.h',
+ 'animation/AnimatableStrokeDasharrayList.cpp',
+ 'animation/AnimatableStrokeDasharrayList.h',
'animation/AnimatableTransform.cpp',
'animation/AnimatableTransform.h',
'animation/AnimatableUnknown.h',
@@ -538,10 +574,19 @@
'animation/AnimatableValue.h',
'animation/AnimatableVisibility.cpp',
'animation/AnimatableVisibility.h',
+ 'animation/ElementAnimation.cpp',
+ 'animation/ElementAnimation.h',
'animation/Animation.cpp',
'animation/Animation.h',
+ 'animation/AnimationClock.h',
'animation/AnimationEffect.h',
+ 'animation/AnimationStack.cpp',
'animation/AnimationStack.h',
+ 'animation/CompositorAnimations.cpp',
+ 'animation/CompositorAnimations.h',
+ 'animation/CompositorAnimationsImpl.h',
+ 'animation/DocumentAnimations.cpp',
+ 'animation/DocumentAnimations.h',
'animation/DocumentTimeline.cpp',
'animation/DocumentTimeline.h',
'animation/InertAnimation.cpp',
@@ -558,6 +603,10 @@
'animation/css/CSSAnimatableValueFactory.h',
'animation/css/CSSAnimations.cpp',
'animation/css/CSSAnimations.h',
+ 'animation/css/CSSPendingAnimations.cpp',
+ 'animation/css/CSSPendingAnimations.h',
+ 'animation/css/TransitionTimeline.cpp',
+ 'animation/css/TransitionTimeline.h',
'css/BasicShapeFunctions.cpp',
'css/CSSArrayFunctionValue.cpp',
'css/CSSArrayFunctionValue.h',
@@ -577,6 +626,7 @@
'css/CSSComputedStyleDeclaration.cpp',
'css/CSSCrossfadeValue.cpp',
'css/CSSCrossfadeValue.h',
+ 'css/CSSCustomFontData.h',
'css/CSSCursorImageValue.cpp',
'css/CSSDefaultStyleSheets.cpp',
'css/CSSDefaultStyleSheets.h',
@@ -594,18 +644,22 @@
'css/CSSFontFaceSource.h',
'css/CSSFontFaceSrcValue.cpp',
'css/CSSFontFaceSrcValue.h',
+ 'css/CSSFontFeatureValue.cpp',
+ 'css/CSSFontFeatureValue.h',
'css/CSSFontSelector.cpp',
'css/CSSFontSelector.h',
+ 'css/CSSFontValue.cpp',
+ 'css/CSSFontValue.h',
'css/CSSFunctionValue.cpp',
'css/CSSFunctionValue.h',
'css/CSSGradientValue.cpp',
'css/CSSGradientValue.h',
+ 'css/CSSGridLineNamesValue.cpp',
+ 'css/CSSGridLineNamesValue.h',
'css/CSSGridTemplateValue.cpp',
'css/CSSGridTemplateValue.h',
'css/CSSGroupingRule.cpp',
'css/CSSGroupingRule.h',
- 'css/CSSHostRule.cpp',
- 'css/CSSHostRule.h',
'css/CSSImageGeneratorValue.cpp',
'css/CSSImageSetValue.cpp',
'css/CSSImageValue.cpp',
@@ -619,6 +673,8 @@
'css/CSSKeyframeRule.h',
'css/CSSKeyframesRule.cpp',
'css/CSSKeyframesRule.h',
+ 'css/CSSLengthFunctions.cpp',
+ 'css/CSSLengthFunctions.h',
'css/CSSLineBoxContainValue.cpp',
'css/CSSMatrix.cpp',
'css/CSSMatrix.h',
@@ -631,6 +687,7 @@
'css/CSSPageRule.cpp',
'css/CSSPageRule.h',
'css/CSSParser.h',
+ 'css/CSSParserMode.cpp',
'css/CSSParserMode.h',
'css/CSSParserValues.cpp',
'css/CSSPrimitiveValue.cpp',
@@ -646,11 +703,15 @@
'css/CSSRuleList.h',
'css/CSSSegmentedFontFace.cpp',
'css/CSSSegmentedFontFace.h',
+ 'css/CSSSegmentedFontFaceCache.cpp',
+ 'css/CSSSegmentedFontFaceCache.h',
'css/CSSSelector.cpp',
'css/CSSSelectorList.cpp',
'css/CSSSelectorList.h',
'css/CSSShaderValue.cpp',
'css/CSSShaderValue.h',
+ 'css/CSSShadowValue.cpp',
+ 'css/CSSShadowValue.h',
'css/CSSStyleDeclaration.cpp',
'css/CSSStyleDeclaration.h',
'css/CSSStyleRule.cpp',
@@ -663,8 +724,9 @@
'css/CSSSVGDocumentValue.h',
'css/CSSTimingFunctionValue.cpp',
'css/CSSTimingFunctionValue.h',
- 'css/CSSToStyleMap.cpp',
- 'css/CSSToStyleMap.h',
+ 'css/CSSTokenizer.h',
+ 'css/CSSToLengthConversionData.cpp',
+ 'css/CSSToLengthConversionData.h',
'css/CSSTransformValue.cpp',
'css/CSSUnicodeRangeValue.cpp',
'css/CSSUnicodeRangeValue.h',
@@ -673,31 +735,29 @@
'css/CSSValueList.cpp',
'css/CSSValuePool.cpp',
'css/CSSValuePool.h',
+ 'css/CSSVariablesIterator.h',
'css/CSSVariablesMap.cpp',
'css/CSSVariablesMap.h',
+ 'css/CSSVariablesMapForEachCallback.h',
'css/CSSVariableValue.h',
'css/CSSViewportRule.h',
'css/CSSViewportRule.cpp',
'css/Counter.h',
'css/DOMWindowCSS.cpp',
'css/DOMWindowCSS.h',
- 'css/DocumentRuleSets.cpp',
- 'css/DocumentRuleSets.h',
+ 'css/DocumentFontFaceSet.h',
+ 'css/DocumentFontFaceSet.cpp',
'css/ElementRuleCollector.cpp',
'css/ElementRuleCollector.h',
'css/FontFaceSet.h',
'css/FontFaceSet.cpp',
'css/FontFace.cpp',
'css/FontFace.h',
- 'css/FontFeatureValue.cpp',
- 'css/FontFeatureValue.h',
'css/FontSize.cpp',
'css/FontSize.h',
- 'css/FontValue.cpp',
- 'css/FontValue.h',
+ 'css/HashTools.h',
'css/InspectorCSSOMWrappers.cpp',
'css/InspectorCSSOMWrappers.h',
- 'css/LengthFunctions.cpp',
'css/MediaFeatureNames.cpp',
'css/MediaFeatureNames.h',
'css/MediaList.cpp',
@@ -734,8 +794,6 @@
'css/SelectorCheckerFastPath.h',
'css/SelectorFilter.cpp',
'css/SelectorFilter.h',
- 'css/ShadowValue.cpp',
- 'css/ShadowValue.h',
'css/SiblingTraversalStrategies.h',
'css/StyleColor.h',
'css/StyleInvalidationAnalysis.cpp',
@@ -757,8 +815,12 @@
'css/StyleSheetContents.h',
'css/StyleSheetList.cpp',
'css/StyleSheetList.h',
+ 'css/TreeBoundaryCrossingRules.cpp',
+ 'css/TreeBoundaryCrossingRules.h',
'css/resolver/AnimatedStyleBuilder.cpp',
'css/resolver/AnimatedStyleBuilder.h',
+ 'css/resolver/CSSToStyleMap.cpp',
+ 'css/resolver/CSSToStyleMap.h',
'css/resolver/ElementResolveContext.cpp',
'css/resolver/ElementResolveContext.h',
'css/resolver/ElementStyleResources.cpp',
@@ -775,16 +837,22 @@
'css/resolver/MediaQueryResult.h',
'css/resolver/ScopedStyleResolver.cpp',
'css/resolver/ScopedStyleResolver.h',
+ 'css/resolver/ScopedStyleTree.cpp',
+ 'css/resolver/ScopedStyleTree.h',
'css/resolver/SharedStyleFinder.cpp',
'css/resolver/SharedStyleFinder.h',
'css/resolver/StyleAdjuster.cpp',
'css/resolver/StyleAdjuster.h',
+ 'css/resolver/StyleBuilderConverter.cpp',
+ 'css/resolver/StyleBuilderConverter.h',
'css/resolver/StyleBuilderCustom.cpp',
- 'css/resolver/StyleBuilderCustom.h',
'css/resolver/StyleResolver.cpp',
'css/resolver/StyleResolver.h',
+ 'css/resolver/StyleResolverIncludes.h',
'css/resolver/StyleResolverState.cpp',
'css/resolver/StyleResolverState.h',
+ 'css/resolver/StyleResolverStats.cpp',
+ 'css/resolver/StyleResolverStats.h',
'css/resolver/StyleResourceLoader.cpp',
'css/resolver/StyleResourceLoader.h',
'css/resolver/TransformBuilder.cpp',
@@ -811,6 +879,7 @@
'editing/EditingStyle.cpp',
'editing/Editor.cpp',
'editing/EditorCommand.cpp',
+ 'editing/EditorKeyBindings.cpp',
'editing/FormatBlockCommand.cpp',
'editing/FormatBlockCommand.h',
'editing/FrameSelection.cpp',
@@ -838,6 +907,8 @@
'editing/ModifySelectionListLevel.cpp',
'editing/ModifySelectionListLevel.h',
'editing/MoveSelectionCommand.cpp',
+ 'editing/PlainTextRange.h',
+ 'editing/PlainTextRange.cpp',
'editing/RemoveCSSPropertyCommand.cpp',
'editing/RemoveCSSPropertyCommand.h',
'editing/RemoveFormatCommand.cpp',
@@ -851,6 +922,7 @@
'editing/ReplaceNodeWithSpanCommand.cpp',
'editing/ReplaceNodeWithSpanCommand.h',
'editing/ReplaceSelectionCommand.cpp',
+ 'editing/SelectionType.h',
'editing/SetNodeAttributeCommand.cpp',
'editing/SetNodeAttributeCommand.h',
'editing/SetSelectionCommand.cpp',
@@ -858,6 +930,8 @@
'editing/SimplifyMarkupCommand.cpp',
'editing/SmartReplaceCF.cpp',
'editing/SmartReplaceICU.cpp',
+ 'editing/SpellChecker.cpp',
+ 'editing/SpellChecker.h',
'editing/SpellCheckRequester.cpp',
'editing/SpellCheckRequester.h',
'editing/SpellingCorrectionCommand.cpp',
@@ -876,6 +950,8 @@
'editing/TextInsertionBaseCommand.h',
'editing/TextIterator.cpp',
'editing/TypingCommand.cpp',
+ 'editing/UndoStack.cpp',
+ 'editing/UndoStack.h',
'editing/UndoStep.h',
'editing/UnlinkCommand.cpp',
'editing/UnlinkCommand.h',
@@ -884,7 +960,6 @@
'editing/VisibleUnits.cpp',
'editing/WrapContentsInDummySpanCommand.cpp',
'editing/WrapContentsInDummySpanCommand.h',
- 'editing/chromium/EditorChromium.cpp',
'editing/htmlediting.cpp',
'editing/markup.cpp',
'fetch/CachedMetadata.cpp',
@@ -916,6 +991,8 @@
'fetch/ResourceLoaderOptions.h',
'fetch/ResourceLoaderSet.cpp',
'fetch/ResourceLoaderSet.h',
+ 'fetch/ResourceLoadPriorityOptimizer.cpp',
+ 'fetch/ResourceLoadPriorityOptimizer.h',
'fetch/ResourcePtr.cpp',
'fetch/ResourcePtr.h',
'fetch/FetchInitiatorInfo.h',
@@ -925,8 +1002,6 @@
'fetch/ShaderResource.h',
'fetch/TextResourceDecoder.cpp',
'fetch/TextResourceDecoder.h',
- 'fetch/TextTrackResource.cpp',
- 'fetch/TextTrackResource.h',
'fetch/XSLStyleSheetResource.cpp',
'fetch/XSLStyleSheetResource.h',
'fetch/MemoryCache.cpp',
@@ -935,10 +1010,6 @@
'fileapi/Blob.h',
'fileapi/BlobBuilder.cpp',
'fileapi/BlobBuilder.h',
- 'fileapi/BlobRegistry.cpp',
- 'fileapi/BlobRegistry.h',
- 'fileapi/BlobURL.cpp',
- 'fileapi/BlobURL.h',
'fileapi/File.cpp',
'fileapi/File.h',
'fileapi/FileError.cpp',
@@ -954,9 +1025,9 @@
'fileapi/FileReaderSync.h',
'fileapi/Stream.cpp',
'fileapi/Stream.h',
- 'history/BackForwardClient.h',
- 'history/BackForwardController.cpp',
'history/HistoryItem.cpp',
+ 'inspector/AsyncCallStackTracker.cpp',
+ 'inspector/AsyncCallStackTracker.h',
'inspector/BindingVisitors.h',
'inspector/ConsoleAPITypes.h',
'inspector/ConsoleMessage.cpp',
@@ -1076,8 +1147,8 @@
'inspector/ScriptProfile.h',
'inspector/TimelineRecordFactory.cpp',
'inspector/TimelineRecordFactory.h',
- 'inspector/TimelineTraceEventProcessor.cpp',
- 'inspector/TimelineTraceEventProcessor.h',
+ 'inspector/TraceEventDispatcher.cpp',
+ 'inspector/TraceEventDispatcher.h',
'inspector/WorkerConsoleAgent.cpp',
'inspector/WorkerConsoleAgent.h',
'inspector/WorkerDebuggerAgent.cpp',
@@ -1104,8 +1175,6 @@
'loader/FrameLoader.cpp',
'loader/FrameLoaderStateMachine.cpp',
'loader/HistoryController.cpp',
- 'loader/IconController.cpp',
- 'loader/IconController.h',
'loader/ImageLoader.cpp',
'loader/ImageLoader.h',
'loader/LinkLoader.cpp',
@@ -1120,8 +1189,8 @@
'loader/NavigationScheduler.cpp',
'loader/PingLoader.cpp',
'loader/PingLoader.h',
- 'loader/Prerenderer.cpp',
- 'loader/Prerenderer.h',
+ 'loader/PrerenderHandle.cpp',
+ 'loader/PrerenderHandle.h',
'loader/PrerendererClient.cpp',
'loader/PrerendererClient.h',
'loader/ProgressTracker.cpp',
@@ -1142,81 +1211,76 @@
'loader/appcache/ApplicationCache.cpp',
'loader/appcache/ApplicationCache.h',
'loader/appcache/ApplicationCacheHost.h',
- 'loader/archive/ArchiveResource.cpp',
- 'loader/archive/ArchiveResourceCollection.cpp',
- 'loader/archive/ArchiveResourceCollection.h',
- 'loader/archive/MHTMLArchive.cpp',
- 'loader/archive/MHTMLArchive.h',
- 'loader/archive/MHTMLParser.cpp',
- 'loader/archive/MHTMLParser.h',
'page/AutoscrollController.cpp',
'page/AutoscrollController.h',
- 'page/BarProp.cpp',
- 'page/BarProp.h',
+ 'frame/BarProp.cpp',
+ 'frame/BarProp.h',
+ 'page/BackForwardClient.h',
'page/Chrome.cpp',
- 'page/Console.cpp',
- 'page/Console.h',
- 'page/ConsoleBase.cpp',
- 'page/ConsoleBase.h',
- 'page/ContentSecurityPolicy.cpp',
- 'page/ContentSecurityPolicyResponseHeaders.cpp',
+ 'frame/Console.cpp',
+ 'frame/Console.h',
+ 'frame/ConsoleBase.cpp',
+ 'frame/ConsoleBase.h',
+ 'frame/ContentSecurityPolicy.cpp',
+ 'frame/ContentSecurityPolicyResponseHeaders.cpp',
'page/ContextMenuController.cpp',
'page/ContextMenuProvider.h',
'page/CreateWindow.cpp',
'page/CreateWindow.h',
- 'page/DeviceClient.h',
- 'page/DeviceController.cpp',
- 'page/DeviceController.h',
- 'page/DiagnosticLoggingKeys.cpp',
- 'page/DiagnosticLoggingKeys.h',
- 'page/DOMPoint.h',
- 'page/DOMSecurityPolicy.cpp',
+ 'frame/DOMPoint.h',
+ 'frame/DOMSecurityPolicy.cpp',
'page/DOMSelection.cpp',
'page/DOMSelection.h',
- 'page/DOMTimer.cpp',
- 'page/DOMTimer.h',
- 'page/DOMWindow.cpp',
- 'page/DOMWindow.h',
- 'page/DOMWindowBase64.cpp',
- 'page/DOMWindowBase64.h',
- 'page/DOMWindowLifecycleNotifier.cpp',
- 'page/DOMWindowLifecycleNotifier.h',
- 'page/DOMWindowLifecycleObserver.cpp',
- 'page/DOMWindowLifecycleObserver.h',
- 'page/DOMWindowTimers.cpp',
- 'page/DOMWindowTimers.h',
+ 'frame/DOMTimer.cpp',
+ 'frame/DOMTimer.h',
+ 'frame/DOMWindow.cpp',
+ 'frame/DOMWindow.h',
+ 'frame/DOMWindowBase64.cpp',
+ 'frame/DOMWindowBase64.h',
+ 'frame/DOMWindowEventHandlers.h',
+ 'frame/DOMWindowLifecycleNotifier.cpp',
+ 'frame/DOMWindowLifecycleNotifier.h',
+ 'frame/DOMWindowLifecycleObserver.cpp',
+ 'frame/DOMWindowLifecycleObserver.h',
+ 'frame/DOMWindowTimers.cpp',
+ 'frame/DOMWindowTimers.h',
'page/DOMWindowPagePopup.cpp',
'page/DOMWindowPagePopup.h',
- 'page/DOMWindowProperty.cpp',
- 'page/DOMWindowProperty.h',
+ 'frame/DOMWindowProperty.cpp',
+ 'frame/DOMWindowProperty.h',
'page/DragController.cpp',
+ 'page/DragData.cpp',
'page/EventHandler.cpp',
'page/EventSource.cpp',
'page/EventSource.h',
'page/FocusController.cpp',
- 'page/Frame.cpp',
- 'page/FrameActionScheduler.cpp',
- 'page/FrameActionScheduler.h',
- 'page/FrameDestructionObserver.cpp',
- 'page/FrameDestructionObserver.h',
+ 'frame/Frame.cpp',
+ 'frame/FrameDestructionObserver.cpp',
+ 'frame/FrameDestructionObserver.h',
'page/FrameTree.cpp',
- 'page/FrameView.cpp',
- 'page/History.cpp',
- 'page/History.h',
- 'page/ImageBitmap.cpp',
- 'page/ImageBitmap.h',
- 'page/LayoutMilestones.h',
- 'page/Location.cpp',
- 'page/Location.h',
- 'page/MemoryInfo.cpp',
+ 'frame/FrameView.cpp',
+ 'frame/GraphicsLayerDebugInfo.cpp',
+ 'frame/History.cpp',
+ 'frame/History.h',
+ 'frame/ImageBitmap.cpp',
+ 'frame/ImageBitmap.h',
+ 'frame/Location.cpp',
+ 'frame/Location.h',
+ 'timing/MemoryInfo.cpp',
'page/MouseEventWithHitTestResults.cpp',
'page/MouseEventWithHitTestResults.h',
- 'page/Navigator.cpp',
- 'page/Navigator.h',
- 'page/NavigatorBase.h',
- 'page/NavigatorID.cpp',
- 'page/NavigatorID.h',
- 'page/NavigatorOnLine.h',
+ 'frame/SmartClip.cpp',
+ 'frame/SmartClip.h',
+ 'frame/Navigator.cpp',
+ 'frame/Navigator.h',
+ 'frame/NavigatorBase.h',
+ 'frame/NavigatorID.cpp',
+ 'frame/NavigatorID.h',
+ 'frame/NavigatorOnLine.h',
+ 'frame/SettingsDelegate.cpp',
+ 'frame/SettingsDelegate.h',
+ 'page/NetworkStateNotifier.cpp',
+ 'page/NetworkStateNotifier.h',
'page/Page.cpp',
'page/PageConsole.cpp',
'page/PageGroup.cpp',
@@ -1232,70 +1296,56 @@
'page/PagePopupClient.h',
'page/PageScaleConstraints.cpp',
'page/PageScaleConstraints.h',
- 'page/PageScaleConstraintsSet.cpp',
- 'page/PageScaleConstraintsSet.h',
'page/PageSerializer.cpp',
'page/PageVisibilityState.cpp',
- 'page/Performance.cpp',
- 'page/Performance.h',
- 'page/PerformanceEntry.cpp',
- 'page/PerformanceEntry.h',
- 'page/PerformanceMark.h',
- 'page/PerformanceMeasure.h',
- 'page/PerformanceNavigation.cpp',
- 'page/PerformanceNavigation.h',
- 'page/PerformanceResourceTiming.cpp',
- 'page/PerformanceResourceTiming.h',
- 'page/PerformanceTiming.cpp',
- 'page/PerformanceTiming.h',
- 'page/PerformanceUserTiming.cpp',
- 'page/PerformanceUserTiming.h',
+ 'timing/Performance.cpp',
+ 'timing/Performance.h',
+ 'timing/PerformanceEntry.cpp',
+ 'timing/PerformanceEntry.h',
+ 'timing/PerformanceMark.h',
+ 'timing/PerformanceMeasure.h',
+ 'timing/PerformanceNavigation.cpp',
+ 'timing/PerformanceNavigation.h',
+ 'timing/PerformanceResourceTiming.cpp',
+ 'timing/PerformanceResourceTiming.h',
+ 'timing/PerformanceTiming.cpp',
+ 'timing/PerformanceTiming.h',
+ 'timing/PerformanceUserTiming.cpp',
+ 'timing/PerformanceUserTiming.h',
'page/PointerLockController.cpp',
'page/PointerLockController.h',
'page/PopupOpeningObserver.h',
'page/PrintContext.cpp',
- 'page/ResourceTimingInfo.h',
- 'page/RuntimeCSSEnabled.cpp',
- 'page/RuntimeCSSEnabled.h',
- 'page/RuntimeEnabledFeaturesCustom.cpp',
- 'page/Screen.cpp',
- 'page/Screen.h',
- 'page/Settings.cpp',
+ 'timing/ResourceTimingInfo.h',
+ 'css/RuntimeCSSEnabled.cpp',
+ 'css/RuntimeCSSEnabled.h',
+ 'frame/Screen.cpp',
+ 'frame/Screen.h',
+ 'frame/Settings.cpp',
'page/SpatialNavigation.cpp',
- 'page/SpeechInput.cpp',
- 'page/SpeechInput.h',
- 'page/SpeechInputClient.h',
- 'page/SpeechInputEvent.cpp',
- 'page/SpeechInputEvent.h',
- 'page/SpeechInputListener.h',
- 'page/SpeechInputResult.cpp',
- 'page/SpeechInputResult.h',
- 'page/SpeechInputResultList.cpp',
- 'page/SpeechInputResultList.h',
- 'page/SuspendableTimer.cpp',
- 'page/SuspendableTimer.h',
+ 'frame/SuspendableTimer.cpp',
+ 'frame/SuspendableTimer.h',
'page/TouchAdjustment.cpp',
'page/TouchAdjustment.h',
'page/TouchDisambiguation.cpp',
'page/TouchDisambiguation.h',
- 'page/UseCounter.cpp',
- 'page/UserContentURLPattern.cpp',
+ 'frame/UseCounter.cpp',
'page/WindowFeatures.cpp',
'page/WindowFocusAllowedIndicator.cpp',
- 'page/WorkerNavigator.cpp',
- 'page/WorkerNavigator.h',
- 'page/animation/AnimationBase.cpp',
- 'page/animation/AnimationBase.h',
- 'page/animation/AnimationController.cpp',
- 'page/animation/AnimationControllerPrivate.h',
- 'page/animation/CompositeAnimation.cpp',
- 'page/animation/CompositeAnimation.h',
- 'page/animation/CSSPropertyAnimation.cpp',
- 'page/animation/CSSPropertyAnimation.h',
- 'page/animation/ImplicitAnimation.cpp',
- 'page/animation/ImplicitAnimation.h',
- 'page/animation/KeyframeAnimation.cpp',
- 'page/animation/KeyframeAnimation.h',
+ 'workers/WorkerNavigator.cpp',
+ 'workers/WorkerNavigator.h',
+ 'frame/animation/AnimationBase.cpp',
+ 'frame/animation/AnimationBase.h',
+ 'frame/animation/AnimationController.cpp',
+ 'frame/animation/AnimationControllerPrivate.h',
+ 'frame/animation/CompositeAnimation.cpp',
+ 'frame/animation/CompositeAnimation.h',
+ 'frame/animation/CSSPropertyAnimation.cpp',
+ 'frame/animation/CSSPropertyAnimation.h',
+ 'frame/animation/ImplicitAnimation.cpp',
+ 'frame/animation/ImplicitAnimation.h',
+ 'frame/animation/KeyframeAnimation.cpp',
+ 'frame/animation/KeyframeAnimation.h',
'page/scrolling/ScrollingConstraints.cpp',
'page/scrolling/ScrollingConstraints.h',
'page/scrolling/ScrollingCoordinator.cpp',
@@ -1308,24 +1358,27 @@
'plugins/DOMPlugin.h',
'plugins/DOMPluginArray.cpp',
'plugins/DOMPluginArray.h',
- 'plugins/PluginData.cpp',
- 'plugins/PluginData.h',
- 'plugins/PluginListBuilder.cpp',
- 'plugins/PluginListBuilder.h',
'plugins/PluginOcclusionSupport.cpp',
'plugins/PluginOcclusionSupport.h',
'plugins/PluginView.h',
+ 'rendering/AbstractInlineTextBox.cpp',
+ 'rendering/AbstractInlineTextBox.h',
'rendering/AutoTableLayout.cpp',
'rendering/AutoTableLayout.h',
'rendering/BidiRun.cpp',
'rendering/BidiRun.h',
'rendering/ClipRect.cpp',
'rendering/ClipRect.h',
+ 'rendering/CompositedLayerMapping.cpp',
+ 'rendering/CompositedLayerMapping.h',
+ 'rendering/CompositedLayerMappingPtr.h',
'rendering/CompositingReasons.h',
'rendering/CounterNode.cpp',
'rendering/CounterNode.h',
'rendering/EllipsisBox.cpp',
'rendering/EllipsisBox.h',
+ 'rendering/FastTextAutosizer.cpp',
+ 'rendering/FastTextAutosizer.h',
'rendering/FilterEffectRenderer.cpp',
'rendering/FilterEffectRenderer.h',
'rendering/FixedTableLayout.cpp',
@@ -1334,6 +1387,8 @@
'rendering/FloatingObjects.h',
'rendering/FlowThreadController.cpp',
'rendering/FlowThreadController.h',
+ 'rendering/GraphicsContextAnnotator.cpp',
+ 'rendering/GraphicsContextAnnotator.h',
'rendering/TextAutosizer.cpp',
'rendering/TextAutosizer.h',
'rendering/HitTestingTransformState.cpp',
@@ -1352,6 +1407,7 @@
'rendering/OrderIterator.h',
'rendering/LayoutIndicator.cpp',
'rendering/LayoutIndicator.h',
+ 'rendering/LayoutRectRecorder.cpp',
'rendering/LayoutRepainter.cpp',
'rendering/LineWidth.cpp',
'rendering/LineWidth.h',
@@ -1409,12 +1465,16 @@
'rendering/RenderInputSpeech.cpp',
'rendering/RenderInputSpeech.h',
'rendering/RenderLayer.cpp',
- 'rendering/RenderLayerBacking.cpp',
+ 'rendering/RenderLayerClipper.cpp',
'rendering/RenderLayerCompositor.cpp',
'rendering/RenderLayerCompositor.h',
'rendering/RenderLayerFilterInfo.cpp',
'rendering/RenderLayerFilterInfo.h',
'rendering/RenderLayerScrollableArea.cpp',
+ 'rendering/RenderLayerStackingNode.cpp',
+ 'rendering/RenderLayerStackingNodeIterator.cpp',
+ 'rendering/RenderLayerReflectionInfo.cpp',
+ 'rendering/RenderLayerRepainter.cpp',
'rendering/RenderLayerModelObject.cpp',
'rendering/RenderLineBoxList.cpp',
'rendering/RenderListBox.cpp',
@@ -1430,8 +1490,6 @@
'rendering/RenderMediaControlElements.h',
'rendering/RenderMediaControls.cpp',
'rendering/RenderMediaControls.h',
- 'rendering/RenderMediaControlsChromium.cpp',
- 'rendering/RenderMediaControlsChromium.h',
'rendering/RenderMenuList.cpp',
'rendering/RenderMenuList.h',
'rendering/RenderMeter.cpp',
@@ -1442,6 +1500,8 @@
'rendering/RenderMultiColumnFlowThread.h',
'rendering/RenderMultiColumnSet.cpp',
'rendering/RenderMultiColumnSet.h',
+ 'rendering/RenderNamedFlowFragment.cpp',
+ 'rendering/RenderNamedFlowFragment.h',
'rendering/RenderNamedFlowThread.cpp',
'rendering/RenderNamedFlowThread.h',
'rendering/RenderObject.cpp',
@@ -1498,8 +1558,6 @@
'rendering/RenderTextControlSingleLine.h',
'rendering/RenderTextFragment.cpp',
'rendering/RenderTextFragment.h',
- 'rendering/RenderTextTrackCue.cpp',
- 'rendering/RenderTextTrackCue.h',
'rendering/RenderTheme.cpp',
'rendering/RenderTheme.h',
'rendering/RenderThemeChromiumAndroid.cpp',
@@ -1517,16 +1575,14 @@
'rendering/RenderThemeChromiumWin.cpp',
'rendering/RenderThemeChromiumWin.h',
'rendering/RenderTreeAsText.cpp',
+ 'rendering/RenderVTTCue.cpp',
+ 'rendering/RenderVTTCue.h',
'rendering/RenderVideo.cpp',
'rendering/RenderVideo.h',
'rendering/RenderView.cpp',
'rendering/RenderWidget.cpp',
'rendering/RenderWordBreak.cpp',
'rendering/RenderWordBreak.h',
- 'rendering/RenderingConfiguration.cpp',
- 'rendering/RenderingConfiguration.h',
- 'rendering/RenderingNodeProxy.cpp',
- 'rendering/RenderingNodeProxy.h',
'rendering/RootInlineBox.cpp',
'rendering/ScrollBehavior.cpp',
'rendering/SubtreeLayoutScope.cpp',
@@ -1536,6 +1592,10 @@
'rendering/VerticalPositionCache.h',
'rendering/break_lines.cpp',
'rendering/break_lines.h',
+ 'rendering/animation/WebAnimationProvider.cpp',
+ 'rendering/animation/WebAnimationProvider.h',
+ 'rendering/shapes/BoxShape.cpp',
+ 'rendering/shapes/BoxShape.h',
'rendering/shapes/PolygonShape.cpp',
'rendering/shapes/PolygonShape.h',
'rendering/shapes/RasterShape.cpp',
@@ -1552,6 +1612,8 @@
'rendering/shapes/ShapeOutsideInfo.cpp',
'rendering/shapes/ShapeOutsideInfo.h',
'rendering/style/BasicShapes.cpp',
+ 'rendering/style/BorderImageLength.h',
+ 'rendering/style/BorderImageLengthBox.h',
'rendering/style/CachedUAStyle.h',
'rendering/style/ContentData.cpp',
'rendering/style/CounterDirectives.cpp',
@@ -1565,6 +1627,9 @@
'rendering/style/RenderStyle.cpp',
'rendering/style/RenderStyle.h',
'rendering/style/ShadowData.cpp',
+ 'rendering/style/ShadowData.h',
+ 'rendering/style/ShadowList.cpp',
+ 'rendering/style/ShadowList.h',
'rendering/style/StyleBackgroundData.cpp',
'rendering/style/StyleBoxData.cpp',
'rendering/style/StyleFetchedImage.cpp',
@@ -1635,6 +1700,16 @@
'rendering/svg/SVGTextQuery.h',
'rendering/svg/SVGTextRunRenderingContext.cpp',
'rendering/svg/SVGTextRunRenderingContext.h',
+ 'speech/SpeechInput.cpp',
+ 'speech/SpeechInput.h',
+ 'speech/SpeechInputClient.h',
+ 'speech/SpeechInputEvent.cpp',
+ 'speech/SpeechInputEvent.h',
+ 'speech/SpeechInputListener.h',
+ 'speech/SpeechInputResult.cpp',
+ 'speech/SpeechInputResult.h',
+ 'speech/SpeechInputResultList.cpp',
+ 'speech/SpeechInputResultList.h',
'storage/Storage.cpp',
'storage/Storage.h',
'storage/StorageArea.h',
@@ -1651,7 +1726,7 @@
'workers/SharedWorker.h',
'workers/SharedWorkerGlobalScope.cpp',
'workers/SharedWorkerGlobalScope.h',
- 'workers/SharedWorkerRepository.h',
+ 'workers/SharedWorkerRepositoryClient.h',
'workers/SharedWorkerThread.cpp',
'workers/SharedWorkerThread.h',
'workers/Worker.cpp',
@@ -1661,15 +1736,16 @@
'workers/WorkerConsole.h',
'workers/WorkerEventQueue.cpp',
'workers/WorkerEventQueue.h',
- 'workers/WorkerGlobalScopeProxy.cpp',
'workers/WorkerGlobalScopeProxy.h',
+ 'workers/WorkerGlobalScopeProxyProvider.h',
+ 'workers/WorkerGlobalScopeProxyProvider.cpp',
'workers/WorkerGlobalScope.cpp',
'workers/WorkerGlobalScope.h',
'workers/WorkerLoaderProxy.h',
- 'workers/WorkerLocation.cpp',
'workers/WorkerLocation.h',
'workers/WorkerMessagingProxy.cpp',
'workers/WorkerMessagingProxy.h',
+ 'workers/WorkerObjectProxy.cpp',
'workers/WorkerObjectProxy.h',
'workers/WorkerReportingProxy.h',
'workers/WorkerRunLoop.cpp',
@@ -1747,15 +1823,12 @@
],
'webcore_dom_files': [
'dom/ActiveDOMObject.cpp',
+ 'dom/AddConsoleMessageTask.cpp',
+ 'dom/AddConsoleMessageTask.h',
'dom/Attr.cpp',
- 'dom/AutocompleteErrorEvent.h',
- 'dom/BeforeLoadEvent.h',
- 'dom/BeforeTextInsertedEvent.cpp',
- 'dom/BeforeTextInsertedEvent.h',
- 'dom/BeforeUnloadEvent.cpp',
- 'dom/BeforeUnloadEvent.h',
'dom/CDATASection.cpp',
'dom/CDATASection.h',
+ 'dom/CSSSelectorWatch.cpp',
'dom/CharacterData.cpp',
'dom/ChildListMutationScope.cpp',
'dom/ChildListMutationScope.h',
@@ -1768,83 +1841,41 @@
'dom/ClientRectList.cpp',
'dom/ClientRectList.h',
'dom/Clipboard.cpp',
- 'dom/ClipboardEvent.cpp',
- 'dom/ClipboardEvent.h',
'dom/Comment.cpp',
'dom/Comment.h',
- 'dom/CompositionEvent.cpp',
- 'dom/CompositionEvent.h',
'dom/ContainerNode.cpp',
- 'dom/ContainerNodeAlgorithms.h',
'dom/ContainerNodeAlgorithms.cpp',
- 'dom/ContextLifecycleObserver.h',
- 'dom/ContextLifecycleObserver.cpp',
+ 'dom/ContainerNodeAlgorithms.h',
'dom/ContextFeatures.cpp',
'dom/ContextFeatures.h',
'dom/ContextLifecycleNotifier.cpp',
'dom/ContextLifecycleNotifier.h',
+ 'dom/ContextLifecycleObserver.cpp',
+ 'dom/ContextLifecycleObserver.h',
'dom/CrossThreadTask.h',
- 'dom/CustomElement.cpp',
- 'dom/CustomElement.h',
- 'dom/CustomElementCallbackDispatcher.cpp',
- 'dom/CustomElementCallbackDispatcher.h',
- 'dom/CustomElementCallbackInvocation.cpp',
- 'dom/CustomElementCallbackInvocation.h',
- 'dom/CustomElementCallbackQueue.cpp',
- 'dom/CustomElementCallbackQueue.h',
- 'dom/CustomElementCallbackScheduler.cpp',
- 'dom/CustomElementCallbackScheduler.h',
- 'dom/CustomElementDefinition.cpp',
- 'dom/CustomElementDefinition.h',
- 'dom/CustomElementDescriptor.h',
- 'dom/CustomElementDescriptorHash.h',
- 'dom/CustomElementException.cpp',
- 'dom/CustomElementException.h',
- 'dom/CustomElementLifecycleCallbacks.h',
- 'dom/CustomElementObserver.cpp',
- 'dom/CustomElementObserver.h',
- 'dom/CustomElementRegistrationContext.cpp',
- 'dom/CustomElementRegistrationContext.h',
- 'dom/CustomElementRegistry.cpp',
- 'dom/CustomElementRegistry.h',
- 'dom/CustomElementUpgradeCandidateMap.cpp',
- 'dom/CustomElementUpgradeCandidateMap.h',
- 'dom/CustomEvent.cpp',
- 'dom/CustomEvent.h',
- 'dom/DOMError.cpp',
- 'dom/DOMError.h',
- 'dom/DOMException.cpp',
- 'dom/DOMException.h',
- 'dom/DOMImplementation.cpp',
- 'dom/DOMNamedFlowCollection.cpp',
- 'dom/DOMNamedFlowCollection.h',
- 'dom/DOMStringList.cpp',
- 'dom/DOMStringList.h',
- 'dom/DOMStringMap.cpp',
- 'dom/DOMStringMap.h',
- 'dom/DOMTokenList.cpp',
- 'dom/DOMTokenList.h',
+ 'dom/DatasetDOMStringMap.cpp',
+ 'dom/DatasetDOMStringMap.h',
'dom/DataTransferItem.cpp',
'dom/DataTransferItem.h',
+ 'dom/DataTransferItemList.cpp',
'dom/DataTransferItemList.h',
- 'dom/DatasetDOMStringMap.cpp',
- 'dom/DatasetDOMStringMap.h',
'dom/DecodedDataDocumentParser.cpp',
'dom/DecodedDataDocumentParser.h',
- 'dom/DeviceOrientationController.cpp',
- 'dom/DeviceOrientationController.h',
'dom/Document.cpp',
- 'dom/DocumentEventQueue.cpp',
- 'dom/DocumentEventQueue.h',
+ 'dom/DocumentEncodingData.h',
'dom/DocumentFragment.cpp',
'dom/DocumentFullscreen.cpp',
'dom/DocumentFullscreen.h',
'dom/DocumentInit.cpp',
'dom/DocumentInit.h',
+ 'dom/DocumentLifecycle.cpp',
+ 'dom/DocumentLifecycle.h',
+ 'dom/DocumentLifecycleNotifier.cpp',
+ 'dom/DocumentLifecycleNotifier.h',
'dom/DocumentLifecycleObserver.cpp',
'dom/DocumentLifecycleObserver.h',
- 'dom/DocumentMarkerController.cpp',
'dom/DocumentMarker.cpp',
+ 'dom/DocumentMarkerController.cpp',
'dom/DocumentOrderedList.cpp',
'dom/DocumentOrderedList.h',
'dom/DocumentOrderedMap.cpp',
@@ -1853,62 +1884,57 @@
'dom/DocumentStyleSheetCollection.cpp',
'dom/DocumentStyleSheetCollection.h',
'dom/DocumentType.cpp',
+ 'dom/DOMError.cpp',
+ 'dom/DOMError.h',
+ 'dom/DOMException.cpp',
+ 'dom/DOMException.h',
+ 'dom/DOMImplementation.cpp',
+ 'dom/DOMNamedFlowCollection.cpp',
+ 'dom/DOMNamedFlowCollection.h',
+ 'dom/DOMSettableTokenList.cpp',
+ 'dom/DOMSettableTokenList.h',
+ 'dom/DOMStringList.cpp',
+ 'dom/DOMStringList.h',
+ 'dom/DOMStringMap.cpp',
+ 'dom/DOMStringMap.h',
+ 'dom/DOMTokenList.cpp',
+ 'dom/DOMTokenList.h',
+ 'dom/DOMURL.cpp',
+ 'dom/DOMURL.h',
+ 'dom/DOMURLUtils.cpp',
+ 'dom/DOMURLUtils.h',
+ 'dom/DOMURLUtilsReadOnly.cpp',
+ 'dom/DOMURLUtilsReadOnly.h',
'dom/Element.cpp',
'dom/Element.h',
+ 'dom/ElementData.cpp',
+ 'dom/ElementData.h',
'dom/ElementRareData.cpp',
'dom/ElementRareData.h',
'dom/ElementTraversal.h',
'dom/Entity.h',
- 'dom/ErrorEvent.cpp',
- 'dom/ErrorEvent.h',
- 'dom/Event.cpp',
- 'dom/EventContext.cpp',
- 'dom/EventContext.h',
- 'dom/EventDispatchMediator.cpp',
- 'dom/EventDispatchMediator.h',
- 'dom/EventDispatcher.cpp',
- 'dom/EventDispatcher.h',
- 'dom/EventRetargeter.cpp',
- 'dom/EventRetargeter.h',
- 'dom/EventListenerMap.cpp',
- 'dom/EventNames.cpp',
- 'dom/EventPathWalker.cpp',
- 'dom/EventPathWalker.h',
- 'dom/EventQueue.h',
- 'dom/EventSender.h',
- 'dom/EventTarget.cpp',
- 'dom/FocusEvent.cpp',
- 'dom/FocusEvent.h',
+ 'dom/ExecutionContextTask.cpp',
+ 'dom/ExecutionContextTask.h',
+ 'dom/MainThreadTaskRunner.cpp',
+ 'dom/MainThreadTaskRunner.h',
'dom/FullscreenElementStack.cpp',
'dom/FullscreenElementStack.h',
- 'dom/GenericEventQueue.cpp',
- 'dom/GenericEventQueue.h',
- 'dom/GestureEvent.cpp',
- 'dom/GestureEvent.h',
- 'dom/HashChangeEvent.h',
- 'dom/IgnoreDestructiveWriteCountIncrementer.h',
+ 'dom/GlobalEventHandlers.h',
'dom/IconURL.cpp',
'dom/IconURL.h',
'dom/IdTargetObserver.cpp',
'dom/IdTargetObserver.h',
'dom/IdTargetObserverRegistry.cpp',
'dom/IdTargetObserverRegistry.h',
- 'dom/KeyboardEvent.cpp',
+ 'dom/IgnoreDestructiveWriteCountIncrementer.h',
'dom/LiveNodeList.cpp',
'dom/LiveNodeList.h',
'dom/MessageChannel.cpp',
'dom/MessageChannel.h',
- 'dom/MessageEvent.cpp',
- 'dom/MessageEvent.h',
'dom/MessagePort.cpp',
- 'dom/MessagePortChannel.cpp',
'dom/Microtask.cpp',
'dom/Microtask.h',
- 'dom/MouseEvent.cpp',
- 'dom/MouseRelatedEvent.cpp',
'dom/MutationCallback.h',
- 'dom/MutationEvent.cpp',
- 'dom/MutationEvent.h',
'dom/MutationObserver.cpp',
'dom/MutationObserver.h',
'dom/MutationObserverInterestGroup.cpp',
@@ -1921,11 +1947,11 @@
'dom/NamedFlow.h',
'dom/NamedFlowCollection.cpp',
'dom/NamedFlowCollection.h',
- 'dom/NameNodeList.cpp',
- 'dom/NameNodeList.h',
'dom/NamedNodeMap.cpp',
'dom/NamedNodesCollection.cpp',
'dom/NamedNodesCollection.h',
+ 'dom/NameNodeList.cpp',
+ 'dom/NameNodeList.h',
'dom/Node.cpp',
'dom/NodeChildRemovalTracker.h',
'dom/NodeChildRemovalTracker.cpp',
@@ -1947,48 +1973,77 @@
'dom/NodeTraversal.h',
'dom/NodeWithIndex.h',
'dom/Notation.h',
- 'dom/OverflowEvent.cpp',
- 'dom/OverflowEvent.h',
- 'dom/PageTransitionEvent.cpp',
- 'dom/PageTransitionEvent.h',
'dom/ParentNode.h',
'dom/PendingScript.cpp',
- 'dom/PopStateEvent.cpp',
- 'dom/PopStateEvent.h',
'dom/Position.cpp',
'dom/PositionIterator.cpp',
'dom/PositionIterator.h',
- 'dom/ProcessingInstruction.cpp',
- 'dom/ProcessingInstruction.h',
- 'dom/ProgressEvent.cpp',
- 'dom/ProgressEvent.h',
'dom/PostAttachCallbacks.cpp',
'dom/PostAttachCallbacks.h',
+ 'dom/PresentationAttributeStyle.cpp',
+ 'dom/PresentationAttributeStyle.h',
+ 'dom/ProcessingInstruction.cpp',
+ 'dom/ProcessingInstruction.h',
'dom/Promise.h',
'dom/PseudoElement.cpp',
'dom/QualifiedName.cpp',
'dom/Range.cpp',
'dom/RawDataDocumentParser.h',
'dom/RequestAnimationFrameCallback.h',
- 'dom/ResourceProgressEvent.cpp',
- 'dom/ResourceProgressEvent.h',
- 'dom/ScopedEventQueue.cpp',
- 'dom/ScopedEventQueue.h',
- 'dom/ScriptExecutionContext.cpp',
- 'dom/ScriptLoader.cpp',
- 'dom/ScriptLoader.h',
- 'dom/ScriptRunner.cpp',
+ 'dom/SandboxFlags.h',
+ 'dom/SandboxFlags.cpp',
'dom/ScriptableDocumentParser.cpp',
'dom/ScriptableDocumentParser.h',
'dom/ScriptedAnimationController.cpp',
'dom/ScriptedAnimationController.h',
+ 'dom/ExecutionContext.cpp',
+ 'dom/ScriptLoader.cpp',
+ 'dom/ScriptLoader.h',
+ 'dom/ScriptRunner.cpp',
'dom/SecurityContext.cpp',
'dom/SecurityContext.h',
- 'dom/SecurityPolicyViolationEvent.h',
'dom/SelectorQuery.cpp',
'dom/SelectorQuery.h',
- 'dom/DOMSettableTokenList.cpp',
- 'dom/DOMSettableTokenList.h',
+ 'dom/custom/CustomElement.cpp',
+ 'dom/custom/CustomElement.h',
+ 'dom/custom/CustomElementBaseElementQueue.cpp',
+ 'dom/custom/CustomElementBaseElementQueue.h',
+ 'dom/custom/CustomElementCallbackDispatcher.cpp',
+ 'dom/custom/CustomElementCallbackDispatcher.h',
+ 'dom/custom/CustomElementCallbackInvocation.cpp',
+ 'dom/custom/CustomElementCallbackInvocation.h',
+ 'dom/custom/CustomElementCallbackQueue.cpp',
+ 'dom/custom/CustomElementCallbackQueue.h',
+ 'dom/custom/CustomElementCallbackScheduler.cpp',
+ 'dom/custom/CustomElementCallbackScheduler.h',
+ 'dom/custom/CustomElementDefinition.cpp',
+ 'dom/custom/CustomElementDefinition.h',
+ 'dom/custom/CustomElementDescriptor.h',
+ 'dom/custom/CustomElementDescriptorHash.h',
+ 'dom/custom/CustomElementException.cpp',
+ 'dom/custom/CustomElementException.h',
+ 'dom/custom/CustomElementLifecycleCallbacks.h',
+ 'dom/custom/CustomElementObserver.cpp',
+ 'dom/custom/CustomElementObserver.h',
+ 'dom/custom/CustomElementRegistrationContext.cpp',
+ 'dom/custom/CustomElementRegistrationContext.h',
+ 'dom/custom/CustomElementRegistry.cpp',
+ 'dom/custom/CustomElementRegistry.h',
+ 'dom/custom/CustomElementUpgradeCandidateMap.cpp',
+ 'dom/custom/CustomElementUpgradeCandidateMap.h',
+ 'dom/shadow/ComposedTreeWalker.cpp',
+ 'dom/shadow/ComposedTreeWalker.h',
+ 'dom/shadow/ContentDistribution.cpp',
+ 'dom/shadow/ContentDistribution.h',
+ 'dom/shadow/ElementShadow.cpp',
+ 'dom/shadow/ElementShadow.h',
+ 'dom/shadow/InsertionPoint.cpp',
+ 'dom/shadow/InsertionPoint.h',
+ 'dom/shadow/SelectRuleFeatureSet.cpp',
+ 'dom/shadow/SelectRuleFeatureSet.h',
+ 'dom/shadow/ShadowRoot.cpp',
+ 'dom/shadow/ShadowRoot.h',
+ 'dom/shadow/ShadowRootRareData.h',
'dom/ShadowTreeStyleSheetCollection.cpp',
'dom/ShadowTreeStyleSheetCollection.h',
'dom/SimulatedClickOptions.h',
@@ -2008,72 +2063,112 @@
'dom/TagNodeList.cpp',
'dom/TagNodeList.h',
'dom/Text.cpp',
- 'dom/TextEvent.cpp',
- 'dom/TextEvent.h',
'dom/TextLinkColors.cpp',
'dom/TextLinkColors.h',
'dom/Touch.cpp',
'dom/Touch.h',
- 'dom/TouchEvent.cpp',
- 'dom/TouchEvent.h',
'dom/TouchList.cpp',
'dom/TouchList.h',
'dom/TransformSource.h',
'dom/TransformSourceLibxslt.cpp',
- 'dom/TransitionEvent.cpp',
- 'dom/TransitionEvent.h',
'dom/Traversal.cpp',
'dom/Traversal.h',
'dom/TreeScope.cpp',
'dom/TreeScope.h',
'dom/TreeScopeAdopter.cpp',
'dom/TreeScopeAdopter.h',
+ 'dom/TreeShared.h',
'dom/TreeWalker.cpp',
'dom/TreeWalker.h',
- 'dom/UIEvent.cpp',
- 'dom/UIEventWithKeyState.cpp',
- 'dom/UserActionElementSet.h',
'dom/UserActionElementSet.cpp',
- 'dom/UserGestureIndicator.cpp',
- 'dom/UserTypingGestureIndicator.cpp',
- 'dom/ViewportArguments.cpp',
- 'dom/ViewportArguments.h',
+ 'dom/UserActionElementSet.h',
+ 'dom/ViewportDescription.cpp',
+ 'dom/ViewportDescription.h',
'dom/VisitedLinkState.cpp',
'dom/VisitedLinkState.h',
- 'dom/WebKitAnimationEvent.cpp',
- 'dom/WebKitAnimationEvent.h',
'dom/WheelController.cpp',
'dom/WheelController.h',
- 'dom/WheelEvent.cpp',
- 'dom/WheelEvent.h',
- 'dom/WhitespaceChildList.h',
- 'dom/WindowEventContext.cpp',
- 'dom/WindowEventContext.h',
- 'dom/default/PlatformMessagePortChannel.cpp',
- 'dom/default/PlatformMessagePortChannel.h',
- 'dom/default/chromium/PlatformMessagePortChannelChromium.cpp',
- 'dom/default/chromium/PlatformMessagePortChannelChromium.h',
- 'dom/shadow/ComposedTreeWalker.cpp',
- 'dom/shadow/ComposedTreeWalker.h',
- 'dom/shadow/ContentDistribution.cpp',
- 'dom/shadow/ContentDistribution.h',
- 'dom/shadow/ShadowRootRareData.h',
- 'dom/shadow/ElementShadow.cpp',
- 'dom/shadow/ElementShadow.h',
- 'dom/shadow/InsertionPoint.cpp',
- 'dom/shadow/InsertionPoint.h',
- 'dom/shadow/SelectRuleFeatureSet.cpp',
- 'dom/shadow/SelectRuleFeatureSet.h',
- 'dom/shadow/ShadowRoot.cpp',
- 'dom/shadow/ShadowRoot.h',
+ 'events/AutocompleteErrorEvent.h',
+ 'events/BeforeLoadEvent.h',
+ 'events/BeforeTextInsertedEvent.cpp',
+ 'events/BeforeTextInsertedEvent.h',
+ 'events/BeforeUnloadEvent.cpp',
+ 'events/BeforeUnloadEvent.h',
+ 'events/ClipboardEvent.cpp',
+ 'events/ClipboardEvent.h',
+ 'events/CompositionEvent.cpp',
+ 'events/CompositionEvent.h',
+ 'events/CustomEvent.cpp',
+ 'events/CustomEvent.h',
+ 'events/DOMWindowEventQueue.cpp',
+ 'events/DOMWindowEventQueue.h',
+ 'events/ErrorEvent.cpp',
+ 'events/ErrorEvent.h',
+ 'events/Event.cpp',
+ 'events/EventContext.cpp',
+ 'events/EventContext.h',
+ 'events/EventDispatcher.cpp',
+ 'events/EventDispatcher.h',
+ 'events/EventDispatchMediator.cpp',
+ 'events/EventDispatchMediator.h',
+ 'events/EventListenerMap.cpp',
+ 'events/EventPath.cpp',
+ 'events/EventPath.h',
+ 'events/EventQueue.h',
+ 'events/EventRetargeter.cpp',
+ 'events/EventRetargeter.h',
+ 'events/EventSender.h',
+ 'events/EventTarget.cpp',
+ 'events/FocusEvent.cpp',
+ 'events/FocusEvent.h',
+ 'events/GenericEventQueue.cpp',
+ 'events/GenericEventQueue.h',
+ 'events/GestureEvent.cpp',
+ 'events/GestureEvent.h',
+ 'events/HashChangeEvent.h',
+ 'events/KeyboardEvent.cpp',
+ 'events/MessageEvent.cpp',
+ 'events/MessageEvent.h',
+ 'events/MouseEvent.cpp',
+ 'events/MouseRelatedEvent.cpp',
+ 'events/MutationEvent.cpp',
+ 'events/MutationEvent.h',
+ 'events/NavigatorEvents.cpp',
+ 'events/NavigatorEvents.h',
+ 'events/OverflowEvent.cpp',
+ 'events/OverflowEvent.h',
+ 'events/PageTransitionEvent.cpp',
+ 'events/PageTransitionEvent.h',
+ 'events/PopStateEvent.cpp',
+ 'events/PopStateEvent.h',
+ 'events/ProgressEvent.cpp',
+ 'events/ProgressEvent.h',
+ 'events/ResourceProgressEvent.cpp',
+ 'events/ResourceProgressEvent.h',
+ 'events/ScopedEventQueue.cpp',
+ 'events/ScopedEventQueue.h',
+ 'events/SecurityPolicyViolationEvent.h',
+ 'events/TextEvent.cpp',
+ 'events/TextEvent.h',
+ 'events/ThreadLocalEventNames.h',
+ 'events/TouchEvent.cpp',
+ 'events/TouchEvent.h',
+ 'events/TransitionEvent.cpp',
+ 'events/TransitionEvent.h',
+ 'events/UIEvent.cpp',
+ 'events/UIEventWithKeyState.cpp',
+ 'events/WebKitAnimationEvent.cpp',
+ 'events/WebKitAnimationEvent.h',
+ 'events/WheelEvent.cpp',
+ 'events/WheelEvent.h',
+ 'events/WindowEventContext.cpp',
+ 'events/WindowEventContext.h',
],
'webcore_html_files': [
'html/ClassList.cpp',
'html/ClassList.h',
'html/DOMFormData.cpp',
'html/DOMFormData.h',
- 'html/DOMURL.cpp',
- 'html/DOMURL.h',
'html/FormAssociatedElement.cpp',
'html/FormDataList.cpp',
'html/FormDataList.h',
@@ -2146,9 +2241,14 @@
'html/HTMLImport.h',
'html/HTMLImportsController.cpp',
'html/HTMLImportsController.h',
+ 'html/HTMLImportChild.cpp',
+ 'html/HTMLImportChild.h',
+ 'html/HTMLImportChildClient.h',
'html/HTMLImportLoader.cpp',
'html/HTMLImportLoader.h',
'html/HTMLImportLoaderClient.h',
+ 'html/HTMLImportResourceOwner.cpp',
+ 'html/HTMLImportResourceOwner.h',
'html/HTMLInputElement.cpp',
'html/HTMLKeygenElement.cpp',
'html/HTMLKeygenElement.h',
@@ -2167,7 +2267,6 @@
'html/HTMLMediaElement.cpp',
'html/HTMLMenuElement.cpp',
'html/HTMLMenuElement.h',
- 'html/HTMLMetaElement.cpp',
'html/HTMLMetaElement.h',
'html/HTMLMeterElement.cpp',
'html/HTMLMeterElement.h',
@@ -2192,7 +2291,7 @@
'html/HTMLParamElement.cpp',
'html/HTMLParamElement.h',
'html/HTMLPlugInElement.cpp',
- 'html/HTMLPlugInImageElement.cpp',
+ 'html/HTMLPlugInElement.h',
'html/HTMLPreElement.cpp',
'html/HTMLPreElement.h',
'html/HTMLProgressElement.cpp',
@@ -2298,7 +2397,6 @@
'html/canvas/CanvasRenderingContext2D.h',
'html/canvas/CanvasStyle.cpp',
'html/canvas/CanvasStyle.h',
- 'html/canvas/CheckedInt.h',
'html/canvas/DataView.cpp',
'html/canvas/DataView.h',
'html/canvas/DOMPath.h',
@@ -2413,8 +2511,6 @@
'html/forms/ImageInputType.h',
'html/forms/InputType.cpp',
'html/forms/InputType.h',
- 'html/forms/InputTypeNames.cpp',
- 'html/forms/InputTypeNames.h',
'html/forms/InputTypeView.cpp',
'html/forms/InputTypeView.h',
'html/forms/MonthInputType.cpp',
@@ -2473,8 +2569,6 @@
'html/parser/HTMLEntityTable.h',
'html/parser/HTMLFormattingElementList.cpp',
'html/parser/HTMLFormattingElementList.h',
- 'html/parser/HTMLIdentifier.cpp',
- 'html/parser/HTMLIdentifier.h',
'html/parser/HTMLInputStream.h',
'html/parser/HTMLMetaCharsetParser.cpp',
'html/parser/HTMLMetaCharsetParser.h',
@@ -2570,708 +2664,59 @@
'html/track/TextTrack.h',
'html/track/TextTrackCue.cpp',
'html/track/TextTrackCue.h',
- 'html/track/TextTrackCueGeneric.cpp',
- 'html/track/TextTrackCueGeneric.h',
'html/track/TextTrackCueList.cpp',
'html/track/TextTrackCueList.h',
'html/track/TextTrackList.cpp',
- 'html/track/TextTrackRegion.cpp',
- 'html/track/TextTrackRegion.h',
- 'html/track/TextTrackRegionList.cpp',
- 'html/track/TextTrackRegionList.h',
- 'html/track/TrackBase.cpp',
+ 'html/track/TrackBase.h',
'html/track/TrackEvent.cpp',
- 'html/track/WebVTTElement.cpp',
- 'html/track/WebVTTElement.h',
- 'html/track/WebVTTParser.cpp',
- 'html/track/WebVTTParser.h',
- 'html/track/WebVTTToken.h',
- 'html/track/WebVTTTokenizer.cpp',
- 'html/track/WebVTTTokenizer.h',
+ 'html/track/vtt/BufferedLineReader.cpp',
+ 'html/track/vtt/BufferedLineReader.h',
+ 'html/track/vtt/VTTCue.cpp',
+ 'html/track/vtt/VTTCue.h',
+ 'html/track/vtt/VTTElement.cpp',
+ 'html/track/vtt/VTTElement.h',
+ 'html/track/vtt/VTTParser.cpp',
+ 'html/track/vtt/VTTParser.h',
+ 'html/track/vtt/VTTRegion.cpp',
+ 'html/track/vtt/VTTRegion.h',
+ 'html/track/vtt/VTTRegionList.cpp',
+ 'html/track/vtt/VTTRegionList.h',
+ 'html/track/vtt/VTTToken.h',
+ 'html/track/vtt/VTTTokenizer.cpp',
+ 'html/track/vtt/VTTTokenizer.h',
],
'webcore_platform_files': [
- 'platform/AsyncFileSystemCallbacks.h',
- 'platform/CalculationValue.cpp',
- 'platform/CalculationValue.h',
- 'platform/Clock.cpp',
- 'platform/Clock.h',
- 'platform/ContentType.cpp',
- 'platform/ContentType.h',
- 'platform/ContextMenu.cpp',
- 'platform/ContextMenuItem.cpp',
- 'platform/CrossThreadCopier.cpp',
- 'platform/CrossThreadCopier.h',
- 'platform/Cursor.cpp',
- 'platform/DateComponents.cpp',
- 'platform/Decimal.cpp',
- 'platform/DragData.cpp',
'platform/DragImage.cpp',
- 'platform/EventTracer.cpp',
- 'platform/FileChooser.cpp',
- 'platform/FileMetadata.h',
- 'platform/FloatConversion.h',
- 'platform/HashTools.h',
- 'platform/JSONValues.cpp',
- 'platform/JSONValues.h',
- 'platform/KillRing.h',
- 'platform/KillRingNone.cpp',
- 'platform/Language.cpp',
- 'platform/LayoutTestSupport.cpp',
- 'platform/LayoutTestSupport.h',
- 'platform/Length.cpp',
- 'platform/LengthBox.cpp',
- 'platform/LifecycleContext.cpp',
- 'platform/LifecycleContext.h',
- 'platform/LifecycleNotifier.cpp',
- 'platform/LifecycleNotifier.h',
- 'platform/LifecycleObserver.cpp',
- 'platform/LifecycleObserver.h',
- 'platform/LinkHash.cpp',
- 'platform/LocalizedStrings.cpp',
- 'platform/LocalizedStrings.h',
- 'platform/Logging.cpp',
- 'platform/MIMETypeFromURL.cpp',
- 'platform/MIMETypeFromURL.h',
- 'platform/NotImplemented.cpp',
- 'platform/ParsingUtilities.h',
- 'platform/Partitions.cpp',
- 'platform/Partitions.h',
'platform/Pasteboard.cpp',
'platform/Pasteboard.h',
- 'platform/PlatformEvent.cpp',
- 'platform/PlatformEvent.h',
- 'platform/PlatformInstrumentation.cpp',
- 'platform/PlatformInstrumentation.h',
- 'platform/PlatformSpeechSynthesisUtterance.cpp',
- 'platform/PlatformSpeechSynthesisUtterance.h',
- 'platform/PlatformSpeechSynthesisVoice.cpp',
- 'platform/PlatformSpeechSynthesisVoice.h',
- 'platform/PlatformSpeechSynthesizer.cpp',
- 'platform/PlatformSpeechSynthesizer.h',
- 'platform/PlatformTouchEvent.h',
- 'platform/PlatformTouchPoint.h',
- 'platform/PrerenderHandle.h',
- 'platform/PrerenderClient.h',
- 'platform/PurgeableBuffer.cpp',
- 'platform/PurgeableBuffer.h',
- 'platform/SSLKeyGenerator.h',
- 'platform/ScrollAnimator.cpp',
- 'platform/ScrollAnimator.h',
- 'platform/ScrollAnimatorNone.cpp',
- 'platform/ScrollAnimatorNone.h',
- 'platform/ScrollView.cpp',
- 'platform/ScrollableArea.cpp',
- 'platform/Scrollbar.cpp',
- 'platform/Scrollbar.h',
- 'platform/ScrollbarTheme.cpp',
- 'platform/ScrollbarTheme.h',
- 'platform/ScrollbarThemeAndroid.cpp',
- 'platform/ScrollbarThemeAuraOrGtk.cpp',
- 'platform/ScrollbarThemeAuraOrGtk.h',
- 'platform/ScrollbarThemeClient.h',
- 'platform/ScrollbarThemeMacCommon.h',
- 'platform/ScrollbarThemeMacCommon.mm',
- 'platform/ScrollbarThemeMacNonOverlayAPI.h',
- 'platform/ScrollbarThemeMacNonOverlayAPI.mm',
- 'platform/ScrollbarThemeMacOverlayAPI.h',
- 'platform/ScrollbarThemeMacOverlayAPI.mm',
- 'platform/ScrollbarThemeNonMacCommon.cpp',
- 'platform/ScrollbarThemeNonMacCommon.h',
- 'platform/ScrollbarThemeOverlay.cpp',
- 'platform/ScrollbarThemeOverlay.h',
- 'platform/ScrollbarThemeWin.cpp',
- 'platform/ScrollbarThemeWin.h',
- 'platform/SecureTextInput.cpp',
- 'platform/SecureTextInput.h',
- 'platform/SerializedResource.h',
- 'platform/SharedBuffer.cpp',
- 'platform/SharedBufferChunkReader.cpp',
- 'platform/SharedTimer.h',
- 'platform/Sound.h',
- 'platform/SuddenTermination.h',
- 'platform/Task.h',
- 'platform/Theme.cpp',
- 'platform/ThreadGlobalData.cpp',
- 'platform/ThreadTimers.cpp',
- 'platform/ThreadTimers.h',
- 'platform/Timer.cpp',
- 'platform/UUID.cpp',
- 'platform/UUID.h',
- 'platform/Widget.cpp',
- 'platform/Widget.h',
+ 'platform/animation/AnimationTranslationUtil.cpp',
+ 'platform/animation/AnimationTranslationUtil.h',
'platform/animation/AnimationValue.h',
'platform/animation/CSSAnimationData.cpp',
'platform/animation/CSSAnimationDataList.cpp',
'platform/animation/KeyframeValueList.cpp',
'platform/animation/KeyframeValueList.h',
- 'platform/audio/AudioArray.h',
- 'platform/audio/AudioBus.cpp',
- 'platform/audio/AudioBus.h',
- 'platform/audio/AudioChannel.cpp',
- 'platform/audio/AudioChannel.h',
- 'platform/audio/AudioDSPKernel.h',
- 'platform/audio/AudioDSPKernelProcessor.cpp',
- 'platform/audio/AudioDSPKernelProcessor.h',
- 'platform/audio/AudioDestination.h',
- 'platform/audio/AudioFIFO.cpp',
- 'platform/audio/AudioFIFO.h',
- 'platform/audio/AudioFileReader.h',
- 'platform/audio/AudioIOCallback.h',
- 'platform/audio/AudioProcessor.h',
- 'platform/audio/AudioPullFIFO.cpp',
- 'platform/audio/AudioPullFIFO.h',
- 'platform/audio/AudioResampler.cpp',
- 'platform/audio/AudioResampler.h',
- 'platform/audio/AudioResamplerKernel.cpp',
- 'platform/audio/AudioResamplerKernel.h',
- 'platform/audio/AudioSourceProvider.h',
- 'platform/audio/AudioSourceProviderClient.h',
- 'platform/audio/AudioUtilities.cpp',
- 'platform/audio/AudioUtilities.h',
- 'platform/audio/Biquad.cpp',
- 'platform/audio/Biquad.h',
- 'platform/audio/Cone.cpp',
- 'platform/audio/Cone.h',
- 'platform/audio/DenormalDisabler.h',
- 'platform/audio/DirectConvolver.cpp',
- 'platform/audio/DirectConvolver.h',
- 'platform/audio/Distance.cpp',
- 'platform/audio/Distance.h',
- 'platform/audio/DownSampler.cpp',
- 'platform/audio/DownSampler.h',
- 'platform/audio/DynamicsCompressor.cpp',
- 'platform/audio/DynamicsCompressor.h',
- 'platform/audio/DynamicsCompressorKernel.cpp',
- 'platform/audio/DynamicsCompressorKernel.h',
- 'platform/audio/EqualPowerPanner.cpp',
- 'platform/audio/EqualPowerPanner.h',
- 'platform/audio/FFTConvolver.cpp',
- 'platform/audio/FFTConvolver.h',
- 'platform/audio/FFTFrame.cpp',
- 'platform/audio/FFTFrame.h',
- 'platform/audio/FFTFrameStub.cpp',
- 'platform/audio/HRTFDatabase.cpp',
- 'platform/audio/HRTFDatabase.h',
- 'platform/audio/HRTFDatabaseLoader.cpp',
- 'platform/audio/HRTFDatabaseLoader.h',
- 'platform/audio/HRTFElevation.cpp',
- 'platform/audio/HRTFElevation.h',
- 'platform/audio/HRTFKernel.cpp',
- 'platform/audio/HRTFKernel.h',
- 'platform/audio/HRTFPanner.cpp',
- 'platform/audio/HRTFPanner.h',
- 'platform/audio/MultiChannelResampler.cpp',
- 'platform/audio/MultiChannelResampler.h',
- 'platform/audio/Panner.cpp',
- 'platform/audio/Panner.h',
- 'platform/audio/Reverb.cpp',
- 'platform/audio/Reverb.h',
- 'platform/audio/ReverbAccumulationBuffer.cpp',
- 'platform/audio/ReverbAccumulationBuffer.h',
- 'platform/audio/ReverbConvolver.cpp',
- 'platform/audio/ReverbConvolver.h',
- 'platform/audio/ReverbConvolverStage.cpp',
- 'platform/audio/ReverbConvolverStage.h',
- 'platform/audio/ReverbInputBuffer.cpp',
- 'platform/audio/ReverbInputBuffer.h',
- 'platform/audio/SincResampler.cpp',
- 'platform/audio/SincResampler.h',
- 'platform/audio/UpSampler.cpp',
- 'platform/audio/UpSampler.h',
- 'platform/audio/VectorMath.cpp',
- 'platform/audio/VectorMath.h',
- 'platform/audio/ZeroPole.cpp',
- 'platform/audio/ZeroPole.h',
- 'platform/audio/chromium/AudioBusChromium.cpp',
- 'platform/audio/chromium/AudioDestinationChromium.cpp',
- 'platform/audio/chromium/AudioDestinationChromium.h',
- 'platform/audio/chromium/FFTFrameOpenMAXDLAndroid.cpp',
- 'platform/audio/ffmpeg/FFTFrameFFMPEG.cpp',
- 'platform/audio/mac/FFTFrameMac.cpp',
- 'platform/audio/ipp/FFTFrameIPP.cpp',
'platform/chromium/ChromiumDataObject.cpp',
'platform/chromium/ChromiumDataObject.h',
'platform/chromium/ChromiumDataObjectItem.cpp',
'platform/chromium/ChromiumDataObjectItem.h',
- 'platform/chromium/ClipboardChromium.cpp',
- 'platform/chromium/ClipboardChromium.h',
- 'platform/chromium/ClipboardChromiumPosix.cpp',
- 'platform/chromium/ClipboardChromiumWin.cpp',
- 'platform/chromium/ClipboardMimeTypes.cpp',
- 'platform/chromium/ClipboardMimeTypes.h',
- 'platform/chromium/ClipboardUtilitiesChromium.cpp',
- 'platform/chromium/ClipboardUtilitiesChromium.h',
- 'platform/chromium/FileSystemChromium.cpp',
- 'platform/chromium/FramelessScrollView.cpp',
- 'platform/chromium/FramelessScrollView.h',
- 'platform/chromium/FramelessScrollViewClient.h',
- 'platform/chromium/HistogramSupportChromium.cpp',
'platform/chromium/KeyCodeConversion.h',
'platform/chromium/KeyCodeConversionAndroid.cpp',
'platform/chromium/KeyCodeConversionGtk.cpp',
- 'platform/chromium/KeyboardCodes.h',
- 'platform/chromium/LanguageChromium.cpp',
- 'platform/chromium/MemoryUsageSupportChromium.cpp',
- 'platform/chromium/MIMETypeRegistryChromium.cpp',
- 'platform/chromium/PlatformKeyboardEventChromium.cpp',
- 'platform/chromium/PlatformScreenChromium.cpp',
- 'platform/chromium/PlatformThemeChromiumDefault.cpp',
- 'platform/chromium/PlatformThemeChromiumDefault.h',
- 'platform/chromium/PlatformSpeechSynthesizerChromium.cpp',
- 'platform/chromium/Prerender.cpp',
- 'platform/chromium/Prerender.h',
- 'platform/chromium/PrerenderHandle.cpp',
- 'platform/chromium/SSLKeyGeneratorChromium.cpp',
- 'platform/chromium/SharedTimerChromium.cpp',
- 'platform/chromium/SoundChromiumPosix.cpp',
- 'platform/chromium/SoundChromiumWin.cpp',
- 'platform/chromium/StatsCounterChromium.cpp',
- 'platform/chromium/SuddenTerminationChromium.cpp',
- 'platform/chromium/TraceEvent.h',
- 'platform/cocoa/KeyEventCocoa.h',
- 'platform/cocoa/KeyEventCocoa.mm',
- 'platform/graphics/ANGLEWebKitBridge.cpp',
- 'platform/graphics/ANGLEWebKitBridge.h',
- 'platform/graphics/BitmapImage.cpp',
- 'platform/graphics/ContentDecryptionModule.cpp',
- 'platform/graphics/ContentDecryptionModule.h',
- 'platform/graphics/ContentDecryptionModuleSession.cpp',
- 'platform/graphics/ContentDecryptionModuleSession.h',
- 'platform/graphics/Color.cpp',
- 'platform/graphics/CrossfadeGeneratedImage.cpp',
- 'platform/graphics/CrossfadeGeneratedImage.h',
- 'platform/graphics/DrawLooper.cpp',
- 'platform/graphics/DrawLooper.h',
- 'platform/graphics/Extensions3D.cpp',
- 'platform/graphics/Extensions3D.h',
- 'platform/graphics/Font.cpp',
- 'platform/graphics/FontCache.cpp',
- 'platform/graphics/FontData.cpp',
- 'platform/graphics/FontDescription.cpp',
- 'platform/graphics/FontFallbackList.cpp',
- 'platform/graphics/FontFamily.cpp',
- 'platform/graphics/FontFeatureSettings.cpp',
- 'platform/graphics/FontFastPath.cpp',
- 'platform/graphics/FontPlatformData.cpp',
- 'platform/graphics/FontPlatformData.h',
- 'platform/graphics/FrameData.cpp',
- 'platform/graphics/FrameData.h',
- 'platform/graphics/LayoutBoxExtent.cpp',
- 'platform/graphics/GeneratorGeneratedImage.cpp',
- 'platform/graphics/GeneratedImage.cpp',
- 'platform/graphics/GeneratedImage.h',
- 'platform/graphics/GlyphPageTreeNode.cpp',
- 'platform/graphics/Gradient.cpp',
- 'platform/graphics/GraphicsContext.cpp',
- 'platform/graphics/GraphicsContext3D.cpp',
- 'platform/graphics/GraphicsContext3DImagePacking.cpp',
- 'platform/graphics/GraphicsContextAnnotation.cpp',
- 'platform/graphics/GraphicsLayer.cpp',
- 'platform/graphics/GraphicsTypes.cpp',
- 'platform/graphics/Image.cpp',
- 'platform/graphics/ImageBuffer.cpp',
- 'platform/graphics/ImageOrientation.cpp',
- 'platform/graphics/ImageSource.cpp',
- 'platform/graphics/InbandTextTrackPrivate.h',
- 'platform/graphics/InbandTextTrackPrivateClient.h',
- 'platform/graphics/Latin1TextIterator.h',
- 'platform/graphics/MediaPlayer.cpp',
- 'platform/graphics/MediaPlayer.h',
- 'platform/graphics/Path.cpp',
- 'platform/graphics/PathTraversalState.cpp',
- 'platform/graphics/PathTraversalState.h',
- 'platform/graphics/Pattern.cpp',
- 'platform/graphics/RoundedRect.cpp',
- 'platform/graphics/SegmentedFontData.cpp',
- 'platform/graphics/SegmentedFontData.h',
- 'platform/graphics/ShadowBlur.cpp',
- 'platform/graphics/ShadowBlur.h',
- 'platform/graphics/SimpleFontData.cpp',
- 'platform/graphics/SVGGlyph.cpp',
- 'platform/graphics/StringTruncator.cpp',
- 'platform/graphics/StrokeData.cpp',
- 'platform/graphics/SurrogatePairAwareTextIterator.cpp',
- 'platform/graphics/SurrogatePairAwareTextIterator.h',
- 'platform/graphics/TextRun.cpp',
- 'platform/graphics/UnitBezier.h',
- 'platform/graphics/WidthIterator.cpp',
- 'platform/graphics/WidthIterator.h',
- 'platform/graphics/cg/FloatPointCG.cpp',
- 'platform/graphics/cg/FloatRectCG.cpp',
- 'platform/graphics/cg/FloatSizeCG.cpp',
- 'platform/graphics/cg/IntPointCG.cpp',
- 'platform/graphics/cg/IntRectCG.cpp',
- 'platform/graphics/cg/IntSizeCG.cpp',
- 'platform/graphics/chromium/AnimationTranslationUtil.cpp',
- 'platform/graphics/chromium/AnimationTranslationUtil.h',
- 'platform/graphics/chromium/Canvas2DLayerBridge.cpp',
- 'platform/graphics/chromium/Canvas2DLayerBridge.h',
- 'platform/graphics/chromium/Canvas2DLayerManager.cpp',
- 'platform/graphics/chromium/Canvas2DLayerManager.h',
- 'platform/graphics/chromium/CrossProcessFontLoading.h',
- 'platform/graphics/chromium/CrossProcessFontLoading.mm',
- 'platform/graphics/chromium/DeferredImageDecoder.cpp',
- 'platform/graphics/chromium/DeferredImageDecoder.h',
- 'platform/graphics/chromium/DiscardablePixelRef.cpp',
- 'platform/graphics/chromium/DiscardablePixelRef.h',
- 'platform/graphics/chromium/FontCacheAndroid.cpp',
- 'platform/graphics/chromium/FontCacheChromiumLinux.cpp',
- 'platform/graphics/chromium/FontCacheChromiumWin.cpp',
- 'platform/graphics/chromium/FontChromiumWin.cpp',
- 'platform/graphics/chromium/FontPlatformDataChromiumWin.cpp',
- 'platform/graphics/chromium/FontPlatformDataChromiumWin.h',
- 'platform/graphics/chromium/FontRenderStyle.h',
- 'platform/graphics/chromium/FontUtilsChromiumWin.cpp',
- 'platform/graphics/chromium/FontUtilsChromiumWin.h',
- 'platform/graphics/chromium/GlyphPageTreeNodeChromiumWin.cpp',
- 'platform/graphics/chromium/ImageDecodingStore.cpp',
- 'platform/graphics/chromium/ImageDecodingStore.h',
- 'platform/graphics/chromium/ImageFrameGenerator.cpp',
- 'platform/graphics/chromium/ImageFrameGenerator.h',
- 'platform/graphics/chromium/LazyDecodingPixelRef.cpp',
- 'platform/graphics/chromium/LazyDecodingPixelRef.h',
- 'platform/graphics/chromium/OpaqueRectTrackingContentLayerDelegate.cpp',
- 'platform/graphics/chromium/OpaqueRectTrackingContentLayerDelegate.h',
- 'platform/graphics/chromium/ScaledImageFragment.cpp',
- 'platform/graphics/chromium/ScaledImageFragment.h',
- 'platform/graphics/chromium/SimpleFontDataChromiumWin.cpp',
- 'platform/graphics/chromium/ThreadSafeDataTransport.cpp',
- 'platform/graphics/chromium/ThreadSafeDataTransport.h',
- 'platform/graphics/chromium/TransformSkMatrix44Conversions.cpp',
- 'platform/graphics/chromium/TransformSkMatrix44Conversions.h',
- 'platform/graphics/chromium/TransparencyWin.cpp',
- 'platform/graphics/chromium/TransparencyWin.h',
- 'platform/graphics/chromium/UniscribeHelper.cpp',
- 'platform/graphics/chromium/UniscribeHelper.h',
- 'platform/graphics/chromium/UniscribeHelperTextRun.cpp',
- 'platform/graphics/chromium/UniscribeHelperTextRun.h',
- 'platform/graphics/chromium/VDMXParser.cpp',
- 'platform/graphics/chromium/VDMXParser.h',
- 'platform/graphics/cocoa/FontPlatformDataCocoa.mm',
- 'platform/graphics/filters/custom/CustomFilterArrayParameter.h',
- 'platform/graphics/filters/custom/CustomFilterCompiledProgram.cpp',
- 'platform/graphics/filters/custom/CustomFilterCompiledProgram.h',
- 'platform/graphics/filters/custom/CustomFilterConstants.h',
- 'platform/graphics/filters/custom/CustomFilterGlobalContext.cpp',
- 'platform/graphics/filters/custom/CustomFilterGlobalContext.h',
- 'platform/graphics/filters/custom/CustomFilterMesh.cpp',
- 'platform/graphics/filters/custom/CustomFilterMesh.h',
- 'platform/graphics/filters/custom/CustomFilterMeshGenerator.cpp',
- 'platform/graphics/filters/custom/CustomFilterMeshGenerator.h',
- 'platform/graphics/filters/custom/CustomFilterNumberParameter.h',
- 'platform/graphics/filters/custom/CustomFilterOperation.cpp',
- 'platform/graphics/filters/custom/CustomFilterOperation.h',
- 'platform/graphics/filters/custom/CustomFilterParameter.h',
- 'platform/graphics/filters/custom/CustomFilterParameterList.cpp',
- 'platform/graphics/filters/custom/CustomFilterParameterList.h',
- 'platform/graphics/filters/custom/CustomFilterProgram.cpp',
- 'platform/graphics/filters/custom/CustomFilterProgram.h',
- 'platform/graphics/filters/custom/CustomFilterProgramClient.h',
- 'platform/graphics/filters/custom/CustomFilterProgramInfo.cpp',
- 'platform/graphics/filters/custom/CustomFilterProgramInfo.h',
- 'platform/graphics/filters/custom/CustomFilterRenderer.cpp',
- 'platform/graphics/filters/custom/CustomFilterRenderer.h',
- 'platform/graphics/filters/custom/CustomFilterTransformParameter.h',
- 'platform/graphics/filters/custom/CustomFilterValidatedProgram.cpp',
- 'platform/graphics/filters/custom/CustomFilterValidatedProgram.h',
- 'platform/graphics/filters/custom/FECustomFilter.cpp',
- 'platform/graphics/filters/custom/FECustomFilter.h',
- 'platform/graphics/filters/custom/ValidatedCustomFilterOperation.cpp',
- 'platform/graphics/filters/custom/ValidatedCustomFilterOperation.h',
- 'platform/graphics/filters/DistantLightSource.cpp',
- 'platform/graphics/filters/DistantLightSource.h',
- 'platform/graphics/filters/FEBlend.cpp',
- 'platform/graphics/filters/FEBlend.h',
- 'platform/graphics/filters/FEColorMatrix.cpp',
- 'platform/graphics/filters/FEColorMatrix.h',
- 'platform/graphics/filters/FEComponentTransfer.cpp',
- 'platform/graphics/filters/FEComponentTransfer.h',
- 'platform/graphics/filters/FEComposite.cpp',
- 'platform/graphics/filters/FEComposite.h',
- 'platform/graphics/filters/FEConvolveMatrix.cpp',
- 'platform/graphics/filters/FEConvolveMatrix.h',
- 'platform/graphics/filters/FEDiffuseLighting.cpp',
- 'platform/graphics/filters/FEDiffuseLighting.h',
- 'platform/graphics/filters/FEDisplacementMap.cpp',
- 'platform/graphics/filters/FEDisplacementMap.h',
- 'platform/graphics/filters/FEDropShadow.cpp',
- 'platform/graphics/filters/FEDropShadow.h',
- 'platform/graphics/filters/FEFlood.cpp',
- 'platform/graphics/filters/FEFlood.h',
- 'platform/graphics/filters/FEGaussianBlur.cpp',
- 'platform/graphics/filters/FEGaussianBlur.h',
- 'platform/graphics/filters/FELighting.cpp',
- 'platform/graphics/filters/FELighting.h',
- 'platform/graphics/filters/FEMerge.cpp',
- 'platform/graphics/filters/FEMerge.h',
- 'platform/graphics/filters/FEMorphology.cpp',
- 'platform/graphics/filters/FEMorphology.h',
- 'platform/graphics/filters/FEOffset.cpp',
- 'platform/graphics/filters/FEOffset.h',
- 'platform/graphics/filters/FESpecularLighting.cpp',
- 'platform/graphics/filters/FESpecularLighting.h',
- 'platform/graphics/filters/FETile.cpp',
- 'platform/graphics/filters/FETile.h',
- 'platform/graphics/filters/FETurbulence.cpp',
- 'platform/graphics/filters/FETurbulence.h',
- 'platform/graphics/filters/Filter.h',
- 'platform/graphics/filters/FilterEffect.cpp',
- 'platform/graphics/filters/FilterEffect.h',
- 'platform/graphics/filters/FilterOperation.cpp',
- 'platform/graphics/filters/FilterOperation.h',
- 'platform/graphics/filters/FilterOperations.cpp',
- 'platform/graphics/filters/FilterOperations.h',
- 'platform/graphics/filters/LightSource.h',
- 'platform/graphics/filters/PointLightSource.cpp',
- 'platform/graphics/filters/PointLightSource.h',
- 'platform/graphics/filters/ReferenceFilter.cpp',
- 'platform/graphics/filters/ReferenceFilter.h',
- 'platform/graphics/filters/SkiaImageFilterBuilder.cpp',
- 'platform/graphics/filters/SkiaImageFilterBuilder.h',
- 'platform/graphics/filters/SourceAlpha.cpp',
- 'platform/graphics/filters/SourceAlpha.h',
- 'platform/graphics/filters/SourceGraphic.cpp',
- 'platform/graphics/filters/SourceGraphic.h',
- 'platform/graphics/filters/SpotLightSource.cpp',
- 'platform/graphics/filters/SpotLightSource.h',
- 'platform/graphics/gpu/DrawingBuffer.cpp',
- 'platform/graphics/gpu/DrawingBuffer.h',
- 'platform/graphics/gpu/SharedGraphicsContext3D.cpp',
- 'platform/graphics/gpu/SharedGraphicsContext3D.h',
- 'platform/graphics/harfbuzz/FontHarfBuzz.cpp',
- 'platform/graphics/harfbuzz/FontPlatformDataHarfBuzz.cpp',
- 'platform/graphics/harfbuzz/FontPlatformDataHarfBuzz.h',
- 'platform/graphics/harfbuzz/HarfBuzzFaceCoreText.cpp',
- 'platform/graphics/harfbuzz/HarfBuzzFaceSkia.cpp',
- 'platform/graphics/harfbuzz/HarfBuzzFace.cpp',
- 'platform/graphics/harfbuzz/HarfBuzzFace.h',
- 'platform/graphics/harfbuzz/HarfBuzzShaper.cpp',
- 'platform/graphics/harfbuzz/HarfBuzzShaper.h',
- 'platform/graphics/mac/ColorMac.h',
- 'platform/graphics/mac/ColorMac.mm',
- 'platform/graphics/mac/ComplexTextController.cpp',
- 'platform/graphics/mac/ComplexTextController.h',
- 'platform/graphics/mac/ComplexTextControllerCoreText.mm',
- 'platform/graphics/mac/FloatPointMac.mm',
- 'platform/graphics/mac/FloatRectMac.mm',
- 'platform/graphics/mac/FloatSizeMac.mm',
- 'platform/graphics/mac/FontCacheMac.mm',
- 'platform/graphics/mac/FontComplexTextMac.cpp',
- 'platform/graphics/mac/FontCustomPlatformDataMac.cpp',
- 'platform/graphics/mac/FontMac.cpp',
- 'platform/graphics/mac/GlyphPageTreeNodeMac.cpp',
- 'platform/graphics/mac/IntPointMac.mm',
- 'platform/graphics/mac/IntRectMac.mm',
- 'platform/graphics/mac/IntSizeMac.mm',
- 'platform/graphics/mac/SimpleFontDataCoreText.cpp',
- 'platform/graphics/mac/SimpleFontDataMac.mm',
- 'platform/graphics/opentype/OpenTypeSanitizer.cpp',
- 'platform/graphics/opentype/OpenTypeSanitizer.h',
- 'platform/graphics/opentype/OpenTypeTypes.h',
- 'platform/graphics/opentype/OpenTypeUtilities.cpp',
- 'platform/graphics/opentype/OpenTypeUtilities.h',
- 'platform/graphics/opentype/OpenTypeVerticalData.cpp',
- 'platform/graphics/opentype/OpenTypeVerticalData.h',
- 'platform/graphics/skia/FontCacheSkia.cpp',
- 'platform/graphics/skia/FontCacheSkiaWin.cpp',
- 'platform/graphics/skia/FontCustomPlatformDataSkia.cpp',
- 'platform/graphics/skia/FontPlatformDataSkia.cpp',
- 'platform/graphics/skia/GlyphPageTreeNodeSkia.cpp',
- 'platform/graphics/skia/NativeImageSkia.cpp',
- 'platform/graphics/skia/NativeImageSkia.h',
- 'platform/graphics/skia/OpaqueRegionSkia.cpp',
- 'platform/graphics/skia/OpaqueRegionSkia.h',
- 'platform/graphics/skia/SimpleFontDataSkia.cpp',
- 'platform/graphics/skia/SkiaFontWin.cpp',
- 'platform/graphics/skia/SkiaFontWin.h',
- 'platform/graphics/skia/SkiaSharedBufferStream.cpp',
- 'platform/graphics/skia/SkiaSharedBufferStream.h',
- 'platform/graphics/skia/SkiaUtils.cpp',
- 'platform/graphics/skia/SkiaUtils.h',
- 'platform/graphics/transforms/IdentityTransformOperation.h',
- 'platform/graphics/transforms/InterpolatedTransformOperation.h',
- 'platform/graphics/transforms/InterpolatedTransformOperation.cpp',
- 'platform/graphics/transforms/Matrix3DTransformOperation.cpp',
- 'platform/graphics/transforms/Matrix3DTransformOperation.h',
- 'platform/graphics/transforms/MatrixTransformOperation.cpp',
- 'platform/graphics/transforms/MatrixTransformOperation.h',
- 'platform/graphics/transforms/PerspectiveTransformOperation.cpp',
- 'platform/graphics/transforms/PerspectiveTransformOperation.h',
- 'platform/graphics/transforms/RotateTransformOperation.cpp',
- 'platform/graphics/transforms/RotateTransformOperation.h',
- 'platform/graphics/transforms/ScaleTransformOperation.cpp',
- 'platform/graphics/transforms/ScaleTransformOperation.h',
- 'platform/graphics/transforms/SkewTransformOperation.cpp',
- 'platform/graphics/transforms/SkewTransformOperation.h',
- 'platform/graphics/transforms/TransformOperations.cpp',
- 'platform/graphics/transforms/TransformState.cpp',
- 'platform/graphics/transforms/TransformState.h',
- 'platform/graphics/transforms/TranslateTransformOperation.cpp',
- 'platform/graphics/transforms/TranslateTransformOperation.h',
- 'platform/graphics/win/FontCustomPlatformDataWin.cpp',
- 'platform/image-decoders/ImageDecoder.cpp',
- 'platform/image-decoders/ImageDecoder.h',
- 'platform/image-decoders/ImageFrame.cpp',
- 'platform/image-decoders/bmp/BMPImageDecoder.cpp',
- 'platform/image-decoders/bmp/BMPImageDecoder.h',
- 'platform/image-decoders/bmp/BMPImageReader.cpp',
- 'platform/image-decoders/bmp/BMPImageReader.h',
- 'platform/image-decoders/gif/GIFImageDecoder.cpp',
- 'platform/image-decoders/gif/GIFImageDecoder.h',
- 'platform/image-decoders/gif/GIFImageReader.cpp',
- 'platform/image-decoders/gif/GIFImageReader.h',
- 'platform/image-decoders/ico/ICOImageDecoder.cpp',
- 'platform/image-decoders/ico/ICOImageDecoder.h',
- 'platform/image-decoders/jpeg/JPEGImageDecoder.cpp',
- 'platform/image-decoders/jpeg/JPEGImageDecoder.h',
- 'platform/image-decoders/png/PNGImageDecoder.cpp',
- 'platform/image-decoders/png/PNGImageDecoder.h',
- 'platform/image-decoders/webp/WEBPImageDecoder.cpp',
- 'platform/image-decoders/webp/WEBPImageDecoder.h',
- 'platform/image-encoders/skia/JPEGImageEncoder.cpp',
- 'platform/image-encoders/skia/JPEGImageEncoder.h',
- 'platform/image-encoders/skia/PNGImageEncoder.cpp',
- 'platform/image-encoders/skia/PNGImageEncoder.h',
- 'platform/image-encoders/skia/WEBPImageEncoder.cpp',
- 'platform/image-encoders/skia/WEBPImageEncoder.h',
- 'platform/mac/BlockExceptions.mm',
- 'platform/mac/KillRingMac.mm',
- 'platform/mac/LocalCurrentGraphicsContext.h',
- 'platform/mac/LocalCurrentGraphicsContext.mm',
- 'platform/mac/NSScrollerImpDetails.h',
- 'platform/mac/NSScrollerImpDetails.mm',
- 'platform/mac/ScrollAnimatorMac.h',
- 'platform/mac/ScrollAnimatorMac.mm',
- 'platform/mac/ScrollElasticityController.h',
- 'platform/mac/ScrollElasticityController.mm',
'platform/mac/ThemeMac.h',
'platform/mac/ThemeMac.mm',
- 'platform/mac/WebFontCache.mm',
- 'platform/mediastream/MediaConstraints.h',
'platform/mediastream/MediaStreamCenter.cpp',
'platform/mediastream/MediaStreamCenter.h',
- 'platform/mediastream/MediaStreamComponent.cpp',
- 'platform/mediastream/MediaStreamComponent.h',
'platform/mediastream/MediaStreamDescriptor.cpp',
'platform/mediastream/MediaStreamDescriptor.h',
- 'platform/mediastream/MediaStreamSource.cpp',
- 'platform/mediastream/MediaStreamSource.h',
- 'platform/mediastream/RTCConfiguration.h',
- 'platform/mediastream/RTCDTMFSenderHandler.cpp',
- 'platform/mediastream/RTCDTMFSenderHandler.h',
- 'platform/mediastream/RTCDTMFSenderHandlerClient.h',
'platform/mediastream/RTCDataChannelHandler.cpp',
'platform/mediastream/RTCDataChannelHandler.h',
'platform/mediastream/RTCDataChannelHandlerClient.h',
'platform/mediastream/RTCPeerConnectionHandler.cpp',
'platform/mediastream/RTCPeerConnectionHandler.h',
'platform/mediastream/RTCPeerConnectionHandlerClient.h',
- 'platform/mediastream/RTCSessionDescriptionRequest.h',
'platform/mediastream/RTCStatsRequest.h',
- 'platform/mediastream/RTCVoidRequest.h',
- 'platform/midi/MIDIAccessor.h',
- 'platform/midi/MIDIAccessor.cpp',
- 'platform/midi/MIDIAccessorClient.h',
- 'platform/mock/DeviceOrientationClientMock.cpp',
'platform/mock/GeolocationClientMock.cpp',
- 'platform/mock/MIDIClientMock.cpp',
- 'platform/mock/MIDIClientMock.h',
- 'platform/mock/PlatformSpeechSynthesizerMock.cpp',
- 'platform/mock/PlatformSpeechSynthesizerMock.h',
- 'platform/mock/ScrollbarThemeMock.cpp',
- 'platform/mock/ScrollbarThemeMock.h',
- 'platform/mock/ScrollbarThemeOverlayMock.h',
- 'platform/network/BlobData.cpp',
- 'platform/network/BlobData.h',
- 'platform/network/DNS.cpp',
- 'platform/network/DNS.h',
- 'platform/network/FormData.cpp',
- 'platform/network/FormDataBuilder.cpp',
- 'platform/network/FormDataBuilder.h',
- 'platform/network/HTTPHeaderMap.cpp',
- 'platform/network/HTTPParsers.cpp',
- 'platform/network/HTTPParsers.h',
- 'platform/network/HTTPRequest.cpp',
- 'platform/network/HTTPRequest.h',
- 'platform/network/MIMEHeader.cpp',
- 'platform/network/NetworkStateNotifier.cpp',
- 'platform/network/NetworkStateNotifier.h',
- 'platform/network/ParsedContentType.cpp',
- 'platform/network/ParsedContentType.h',
- 'platform/network/ProxyServer.cpp',
- 'platform/network/ResourceError.cpp',
- 'platform/network/ResourceError.h',
- 'platform/network/ResourceRequest.cpp',
- 'platform/network/ResourceRequest.h',
- 'platform/network/ResourceResponse.cpp',
- 'platform/network/ResourceResponse.h',
- 'platform/network/SocketStreamError.cpp',
- 'platform/network/SocketStreamError.h',
- 'platform/network/SocketStreamHandle.cpp',
- 'platform/network/SocketStreamHandle.h',
- 'platform/network/SocketStreamHandleClient.h',
- 'platform/network/SocketStreamHandleInternal.h',
- 'platform/sql/SQLValue.cpp',
- 'platform/sql/SQLiteAuthorizer.cpp',
- 'platform/sql/SQLiteDatabase.cpp',
- 'platform/sql/SQLiteFileSystem.h',
- 'platform/sql/SQLiteStatement.cpp',
- 'platform/sql/SQLiteStatement.h',
- 'platform/sql/SQLiteTransaction.cpp',
- 'platform/sql/chromium/SQLiteFileSystemChromium.cpp',
- 'platform/sql/chromium/SQLiteFileSystemChromiumPosix.cpp',
- 'platform/sql/chromium/SQLiteFileSystemChromiumWin.cpp',
- 'platform/text/AtomicStringKeyedMRUCache.h',
- 'platform/text/BidiContext.cpp',
- 'platform/text/DateTimeFormat.cpp',
- 'platform/text/LineEnding.cpp',
- 'platform/text/LocaleICU.cpp',
- 'platform/text/LocaleICU.h',
- 'platform/text/LocaleToScriptMapping.h',
- 'platform/text/LocaleToScriptMappingDefault.cpp',
- 'platform/text/ParserUtilities.h',
- 'platform/text/PlatformLocale.cpp',
- 'platform/text/PlatformLocale.h',
- 'platform/text/QuotedPrintable.h',
- 'platform/text/QuotedPrintable.cpp',
- 'platform/text/RegularExpression.cpp',
- 'platform/text/SegmentedString.cpp',
- 'platform/text/SuffixTree.h',
- 'platform/text/TextBoundaries.cpp',
- 'platform/text/TextBreakIterator.cpp',
- 'platform/text/TextBreakIteratorICU.cpp',
- 'platform/text/TextBreakIteratorInternalICU.cpp',
- 'platform/text/TextEncodingDetector.h',
- 'platform/text/TextEncodingDetectorICU.cpp',
- 'platform/text/TextStream.cpp',
- 'platform/text/UnicodeRange.cpp',
- 'platform/text/cf/AtomicStringCF.cpp',
- 'platform/text/cf/StringCF.cpp',
- 'platform/text/cf/StringImplCF.cpp',
- 'platform/text/mac/LocaleMac.h',
- 'platform/text/mac/LocaleMac.mm',
- 'platform/text/mac/StringImplMac.mm',
- 'platform/text/mac/StringMac.mm',
- 'platform/text/transcoder/FontTranscoder.cpp',
- 'platform/text/transcoder/FontTranscoder.h',
- 'platform/text/win/LocaleWin.cpp',
- 'platform/text/win/LocaleWin.h',
- 'platform/win/SystemInfo.cpp',
- 'platform/win/SystemInfo.h',
- ],
- 'webcore_platform_geometry_files': [
- 'platform/graphics/FloatPoint.cpp',
- 'platform/graphics/FloatPolygon.cpp',
- 'platform/graphics/FloatPoint3D.cpp',
- 'platform/graphics/FloatQuad.cpp',
- 'platform/graphics/FloatRect.cpp',
- 'platform/graphics/FloatSize.cpp',
- 'platform/graphics/IntRect.cpp',
- 'platform/graphics/IntRectExtent.h',
- 'platform/graphics/LayoutRect.cpp',
- 'platform/graphics/Region.cpp',
- 'platform/graphics/transforms/TransformationMatrix.cpp',
- 'platform/graphics/transforms/AffineTransform.cpp',
],
'webcore_svg_files': [
'rendering/style/SVGRenderStyle.cpp',
@@ -3535,6 +2980,8 @@
'svg/SVGGlyphRefElement.cpp',
'svg/SVGGlyphRefElement.h',
'svg/SVGGlyphMap.h',
+ 'svg/SVGGeometryElement.cpp',
+ 'svg/SVGGeometryElement.h',
'svg/SVGGradientElement.cpp',
'svg/SVGGradientElement.h',
'svg/SVGGraphicsElement.cpp',
@@ -3545,8 +2992,6 @@
'svg/SVGImageElement.h',
'svg/SVGImageLoader.cpp',
'svg/SVGImageLoader.h',
- 'svg/SVGLangSpace.cpp',
- 'svg/SVGLangSpace.h',
'svg/SVGLength.cpp',
'svg/SVGLengthContext.cpp',
'svg/SVGLengthList.cpp',
@@ -3554,7 +2999,6 @@
'svg/SVGLineElement.h',
'svg/SVGLinearGradientElement.cpp',
'svg/SVGLinearGradientElement.h',
- 'svg/SVGLocatable.cpp',
'svg/SVGMPathElement.cpp',
'svg/SVGMPathElement.h',
'svg/SVGMarkerElement.cpp',
@@ -3680,8 +3124,6 @@
'svg/SVGTransformDistance.cpp',
'svg/SVGTransformDistance.h',
'svg/SVGTransformList.cpp',
- 'svg/SVGTransformable.cpp',
- 'svg/SVGTransformable.h',
'svg/SVGURIReference.cpp',
'svg/SVGURIReference.h',
'svg/SVGUnitTypes.h',
@@ -3722,7 +3164,7 @@
'svg/properties/SVGAnimatedPathSegListPropertyTearOff.h',
'svg/properties/SVGPathSegListPropertyTearOff.cpp',
],
- 'webcore_test_support_idl_files': [
+ 'webcore_testing_support_idl_files': [
'testing/GCObservation.idl',
'testing/Internals.idl',
'testing/InternalProfilers.idl',
@@ -3731,12 +3173,16 @@
'testing/LayerRectList.idl',
'testing/MallocStatistics.idl',
'testing/TypeConversions.idl',
+ ],
+ 'generated_webcore_testing_support_idl_files': [
'<(SHARED_INTERMEDIATE_DIR)/blink/InternalSettingsGenerated.idl',
'<(SHARED_INTERMEDIATE_DIR)/blink/InternalRuntimeFlags.idl',
],
'webcore_test_support_files': [
'testing/v8/WebCoreTestSupport.cpp',
'testing/v8/WebCoreTestSupport.h',
+ 'testing/DummyPageHolder.cpp',
+ 'testing/DummyPageHolder.h',
'testing/GCObservation.cpp',
'testing/GCObservation.h',
'testing/InspectorFrontendClientLocal.cpp',
@@ -3758,143 +3204,57 @@
'<(SHARED_INTERMEDIATE_DIR)/blink/InternalSettingsGenerated.h',
],
'webcore_platform_support_files': [
- 'platform/chromium/support/Platform.cpp',
- 'platform/chromium/support/WebActiveGestureAnimation.cpp',
- 'platform/chromium/support/WebActiveGestureAnimation.h',
'platform/chromium/support/WebArrayBuffer.cpp',
- 'platform/chromium/support/WebAudioBus.cpp',
'platform/chromium/support/WebCrypto.cpp',
- 'platform/chromium/support/WebCryptoAlgorithm.cpp',
- 'platform/chromium/support/WebCryptoKey.cpp',
- 'platform/chromium/support/WebCursorInfo.cpp',
- 'platform/chromium/support/WebData.cpp',
- 'platform/chromium/support/WebDeviceMotionData.cpp',
- 'platform/chromium/support/WebDeviceOrientationData.cpp',
- 'platform/chromium/support/WebFileSystemCallbacks.cpp',
- 'platform/chromium/support/WebFloatQuad.cpp',
- 'platform/chromium/support/WebHTTPBody.cpp',
- 'platform/chromium/support/WebHTTPLoadInfo.cpp',
- 'platform/chromium/support/WebMediaConstraints.cpp',
'platform/chromium/support/WebMediaStream.cpp',
- 'platform/chromium/support/WebMediaStreamSource.cpp',
'platform/chromium/support/WebMediaStreamTrack.cpp',
- 'platform/chromium/support/WebPrerender.cpp',
- 'platform/chromium/support/WebPrerenderingSupport.cpp',
- 'platform/chromium/support/WebRTCConfiguration.cpp',
- 'platform/chromium/support/WebRTCICECandidate.cpp',
'platform/chromium/support/WebRTCSessionDescription.cpp',
'platform/chromium/support/WebRTCSessionDescriptionRequest.cpp',
'platform/chromium/support/WebRTCStatsRequest.cpp',
- 'platform/chromium/support/WebRTCStatsResponse.cpp',
- 'platform/chromium/support/WebRTCVoidRequest.cpp',
- 'platform/chromium/support/WebScrollbarImpl.cpp',
- 'platform/chromium/support/WebScrollbarImpl.h',
- 'platform/chromium/support/WebScrollbarThemeClientImpl.cpp',
- 'platform/chromium/support/WebScrollbarThemeClientImpl.h',
- 'platform/chromium/support/WebScrollbarThemeGeometryNative.cpp',
- 'platform/chromium/support/WebScrollbarThemeGeometryNative.h',
- 'platform/chromium/support/WebSocketStreamError.cpp',
- 'platform/chromium/support/WebSourceInfo.cpp',
- 'platform/chromium/support/WebSpeechSynthesisUtterance.cpp',
- 'platform/chromium/support/WebSpeechSynthesisVoice.cpp',
- 'platform/chromium/support/WebSpeechSynthesizerClientImpl.cpp',
- 'platform/chromium/support/WebSpeechSynthesizerClientImpl.h',
- 'platform/chromium/support/WebThreadSafeData.cpp',
- 'platform/chromium/support/WebTransformKeyframe.cpp',
- 'platform/chromium/support/WebURL.cpp',
- 'platform/chromium/support/WebURLError.cpp',
- 'platform/chromium/support/WebURLRequest.cpp',
- 'platform/chromium/support/WebURLRequestPrivate.h',
- 'platform/chromium/support/WebURLResponse.cpp',
- 'platform/chromium/support/WebURLResponsePrivate.h',
- 'platform/chromium/support/WrappedResourceRequest.h',
- 'platform/chromium/support/WrappedResourceResponse.h',
],
'core_unittest_files': [
'animation/AnimatableColorTest.cpp',
+ 'animation/AnimatableDoubleTest.cpp',
+ 'animation/AnimatableLengthTest.cpp',
'animation/AnimatableNeutralTest.cpp',
- 'animation/AnimatableNumberTest.cpp',
+ 'animation/AnimatableStrokeDasharrayListTest.cpp',
'animation/AnimatableUnknownTest.cpp',
+ 'animation/AnimatableValueTestHelper.cpp',
+ 'animation/AnimatableValueTestHelper.h',
+ 'animation/AnimatableValueTestHelperTest.cpp',
+ 'animation/AnimationClockTest.cpp',
+ 'animation/CompositorAnimationsTest.cpp',
+ 'animation/CompositorAnimationsTestHelper.h',
+ 'animation/CompositorAnimationsTimingFunctionReverserTest.cpp',
'animation/DocumentTimelineTest.cpp',
+ 'animation/ElementAnimationTest.cpp',
'animation/KeyframeAnimationEffectTest.cpp',
'animation/PlayerTest.cpp',
'animation/TimedItemCalculationsTest.cpp',
'animation/TimedItemTest.cpp',
'css/CSSParserValuesTest.cpp',
'css/CSSCalculationValueTest.cpp',
+ 'css/CSSValueTestHelper.h',
+ 'dom/DocumentMarkerControllerTest.cpp',
+ 'editing/TextIteratorTest.cpp',
+ 'dom/MainThreadTaskRunnerTest.cpp',
'fetch/ImageResourceTest.cpp',
'fetch/MemoryCacheTest.cpp',
+ 'fetch/RawResourceTest.cpp',
'fetch/ResourceFetcherTest.cpp',
+ 'html/HTMLDimensionTest.cpp',
+ 'html/LinkRelAttributeTest.cpp',
'html/TimeRangesTest.cpp',
- 'page/ImageBitmapTest.cpp',
- 'platform/DecimalTest.cpp',
- 'platform/SharedBufferTest.cpp',
- 'platform/chromium/ClipboardChromiumTest.cpp',
- 'platform/graphics/BitmapImageTest.cpp',
- 'platform/graphics/FontTest.cpp',
- 'platform/graphics/GraphicsContextTest.cpp',
- 'platform/graphics/RoundedRectTest.cpp',
- 'platform/graphics/UnitBezierTest.cpp',
- 'platform/graphics/chromium/AnimationTranslationUtilTest.cpp',
- 'platform/graphics/chromium/Canvas2DLayerBridgeTest.cpp',
- 'platform/graphics/chromium/Canvas2DLayerManagerTest.cpp',
- 'platform/graphics/chromium/DeferredImageDecoderTest.cpp',
- 'platform/graphics/chromium/ImageDecodingStoreTest.cpp',
- 'platform/graphics/chromium/ImageFrameGeneratorTest.cpp',
- 'platform/graphics/chromium/ThreadSafeDataTransportTest.cpp',
- 'platform/graphics/chromium/test/MockDiscardablePixelRef.h',
- 'platform/graphics/chromium/test/MockImageDecoder.h',
- 'platform/graphics/gpu/DrawingBufferTest.cpp',
- 'platform/image-decoders/ImageDecoderTest.cpp',
- 'platform/image-decoders/gif/GIFImageDecoderTest.cpp',
- 'platform/image-decoders/jpeg/JPEGImageDecoderTest.cpp',
- 'platform/image-decoders/webp/WEBPImageDecoderTest.cpp',
- 'platform/text/DateTimeFormatTest.cpp',
+ 'html/track/vtt/BufferedLineReaderTest.cpp',
+ 'frame/ImageBitmapTest.cpp',
+ 'platform/animation/AnimationTranslationUtilTest.cpp',
+ 'platform/animation/TimingFunctionTestHelper.h',
+ 'platform/animation/TimingFunctionTestHelper.cpp',
+ 'platform/animation/TimingFunctionTestHelperTest.cpp',
'rendering/RenderOverflowTest.cpp',
- 'tests/ArenaTestHelpers.h',
- 'tests/FakeWebGraphicsContext3D.h',
- 'tests/HTMLDimension.cpp',
- 'tests/LayoutUnit.cpp',
- 'tests/LinkRelAttribute.cpp',
- 'tests/PODArenaTest.cpp',
- 'tests/PODFreeListArenaTest.cpp',
- 'tests/PODIntervalTreeTest.cpp',
- 'tests/PODRedBlackTreeTest.cpp',
- 'tests/TreeTestHelpers.cpp',
- 'tests/TreeTestHelpers.h',
- ],
- 'scripts_for_in_files': [
- # jinja2/__init__.py contains version string, so sufficient as
- # dependency for whole jinja2 package
- '<(DEPTH)/third_party/jinja2/__init__.py',
- '<(DEPTH)/third_party/markupsafe/__init__.py', # jinja2 dep
- 'scripts/in_file.py',
- 'scripts/in_generator.py',
- 'scripts/license.py',
- 'scripts/name_macros.py',
- 'scripts/template_expander.py',
- 'scripts/templates/macros.tmpl',
+ 'rendering/shapes/BoxShapeTest.cpp',
+ 'testing/UnitTestHelpers.h',
+ 'testing/UnitTestHelpers.cpp',
],
- 'conditions': [
- ['OS=="win"', {
- # Using native perl rather than cygwin perl cuts execution time
- # of idl preprocessing rules by a bit more than 50%.
- 'perl_exe': '<(DEPTH)/third_party/perl/perl/bin/perl.exe',
- 'gperf_exe': '<(DEPTH)/third_party/gperf/bin/gperf.exe',
- 'bison_exe': '<(DEPTH)/third_party/bison/bin/bison.exe',
- # Using cl instead of cygwin gcc cuts the processing time from
- # 1m58s to 0m52s.
- 'preprocessor': '--preprocessor "cl.exe -nologo -EP -TP"',
- },{
- 'perl_exe': 'perl',
- 'gperf_exe': 'gperf',
- 'bison_exe': 'bison',
- # We specify a preprocess so it happens locally and won't get
- # distributed to goma.
- # FIXME: /usr/bin/gcc won't exist on OSX forever. We want to
- # use /usr/bin/clang once we require Xcode 4.x.
- 'preprocessor': '--preprocessor "/usr/bin/gcc -E -P -x c++"'
- }],
- ],
}
}
diff --git a/chromium/third_party/WebKit/Source/core/core_derived_sources.gyp b/chromium/third_party/WebKit/Source/core/core_derived_sources.gyp
index 058f19e08cd..1cc7c34b412 100644
--- a/chromium/third_party/WebKit/Source/core/core_derived_sources.gyp
+++ b/chromium/third_party/WebKit/Source/core/core_derived_sources.gyp
@@ -32,7 +32,8 @@
'includes': [
'core.gypi',
'../bindings/bindings.gypi',
- 'features.gypi',
+ '../build/features.gypi',
+ '../build/scripts/scripts.gypi',
],
'targets': [
@@ -43,8 +44,13 @@
{
'action_name': 'Settings',
'inputs': [
- 'page/make_settings.pl',
- 'page/Settings.in',
+ '<@(scripts_for_in_files)',
+ '../build/scripts/make_settings.py',
+ '../build/scripts/templates/InternalSettingsGenerated.idl.tmpl',
+ '../build/scripts/templates/InternalSettingsGenerated.cpp.tmpl',
+ '../build/scripts/templates/InternalSettingsGenerated.h.tmpl',
+ '../build/scripts/templates/SettingsMacros.h.tmpl',
+ 'frame/Settings.in',
],
'outputs': [
'<(SHARED_INTERMEDIATE_DIR)/blink/SettingsMacros.h',
@@ -54,21 +60,20 @@
],
'action': [
'python',
- 'scripts/action_makenames.py',
- '<@(_outputs)',
- '--',
- '<@(_inputs)',
+ '../build/scripts/make_settings.py',
+ 'frame/Settings.in',
+ '--output_dir',
+ '<(SHARED_INTERMEDIATE_DIR)/blink',
],
- 'msvs_cygwin_shell': 1,
},
{
'action_name': 'InternalRuntimeFlags',
'inputs': [
'<@(scripts_for_in_files)',
- 'scripts/make_internal_runtime_flags.py',
- 'page/RuntimeEnabledFeatures.in',
- 'scripts/templates/InternalRuntimeFlags.h.tmpl',
- 'scripts/templates/InternalRuntimeFlags.idl.tmpl',
+ '../build/scripts/make_internal_runtime_flags.py',
+ '../platform/RuntimeEnabledFeatures.in',
+ '../build/scripts/templates/InternalRuntimeFlags.h.tmpl',
+ '../build/scripts/templates/InternalRuntimeFlags.idl.tmpl',
],
'outputs': [
'<(SHARED_INTERMEDIATE_DIR)/blink/InternalRuntimeFlags.idl',
@@ -76,8 +81,8 @@
],
'action': [
'python',
- 'scripts/make_internal_runtime_flags.py',
- 'page/RuntimeEnabledFeatures.in',
+ '../build/scripts/make_internal_runtime_flags.py',
+ '../platform/RuntimeEnabledFeatures.in',
'--output_dir',
'<(SHARED_INTERMEDIATE_DIR)/blink',
],
@@ -85,19 +90,17 @@
]
},
{
- 'target_name': 'make_derived_sources',
+ 'target_name': 'make_core_derived_sources',
'type': 'none',
'hard_dependency': 1,
'dependencies': [
'generate_test_support_idls',
+ '../config.gyp:config',
],
'sources': [
# bison rule
- '<(SHARED_INTERMEDIATE_DIR)/blink/CSSGrammar.y',
+ 'css/CSSGrammar.y',
'xml/XPathGrammar.y',
-
- # gperf rule
- 'platform/ColorData.gperf',
],
'actions': [
{
@@ -108,15 +111,15 @@
'outputs': [
'<(SHARED_INTERMEDIATE_DIR)/blink/V8ArrayBufferViewCustomScript.h',
],
- 'msvs_cygwin_shell': 0,
'action': [
- '<(perl_exe)',
- 'scripts/xxd.pl',
+ 'python',
+ '../build/scripts/xxd.py',
'V8ArrayBufferViewCustomScript_js',
'<@(_inputs)',
'<@(_outputs)'
],
'message': 'Generating V8ArrayBufferViewCustomScript.h from V8ArrayBufferViewCustomScript.js',
+ 'msvs_cygwin_shell': 0,
},
{
'action_name': 'generateXMLViewerCSS',
@@ -126,14 +129,14 @@
'outputs': [
'<(SHARED_INTERMEDIATE_DIR)/blink/XMLViewerCSS.h',
],
- 'msvs_cygwin_shell': 0,
'action': [
- '<(perl_exe)',
- 'scripts/xxd.pl',
+ 'python',
+ '../build/scripts/xxd.py',
'XMLViewer_css',
'<@(_inputs)',
'<@(_outputs)'
],
+ 'msvs_cygwin_shell': 0,
},
{
'action_name': 'generateXMLViewerJS',
@@ -143,14 +146,14 @@
'outputs': [
'<(SHARED_INTERMEDIATE_DIR)/blink/XMLViewerJS.h',
],
- 'msvs_cygwin_shell': 0,
'action': [
- '<(perl_exe)',
- 'scripts/xxd.pl',
+ 'python',
+ '../build/scripts/xxd.py',
'XMLViewer_js',
'<@(_inputs)',
'<@(_outputs)'
],
+ 'msvs_cygwin_shell': 0,
},
{
'action_name': 'HTMLEntityTable',
@@ -170,28 +173,6 @@
],
},
{
- 'action_name': 'RuntimeEnabledFeatures',
- 'inputs': [
- '<@(scripts_for_in_files)',
- 'scripts/make_runtime_features.py',
- 'scripts/name_utilities.py',
- 'page/RuntimeEnabledFeatures.in',
- 'scripts/templates/RuntimeEnabledFeatures.cpp.tmpl',
- 'scripts/templates/RuntimeEnabledFeatures.h.tmpl',
- ],
- 'outputs': [
- '<(SHARED_INTERMEDIATE_DIR)/blink/RuntimeEnabledFeatures.cpp',
- '<(SHARED_INTERMEDIATE_DIR)/blink/RuntimeEnabledFeatures.h',
- ],
- 'action': [
- 'python',
- 'scripts/make_runtime_features.py',
- 'page/RuntimeEnabledFeatures.in',
- '--output_dir',
- '<(SHARED_INTERMEDIATE_DIR)/blink',
- ],
- },
- {
'action_name': 'CSSPropertyNames',
'variables': {
'in_files': [
@@ -201,7 +182,7 @@
},
'inputs': [
'<@(scripts_for_in_files)',
- 'scripts/make_css_property_names.py',
+ '../build/scripts/make_css_property_names.py',
'<@(in_files)'
],
'outputs': [
@@ -210,7 +191,7 @@
],
'action': [
'python',
- 'scripts/make_css_property_names.py',
+ '../build/scripts/make_css_property_names.py',
'<@(in_files)',
'--output_dir',
'<(SHARED_INTERMEDIATE_DIR)/blink',
@@ -222,10 +203,10 @@
'action_name': 'StylePropertyShorthand',
'inputs': [
'<@(scripts_for_in_files)',
- 'scripts/make_style_shorthands.py',
+ '../build/scripts/make_style_shorthands.py',
'css/CSSShorthands.in',
- 'scripts/templates/StylePropertyShorthand.h.tmpl',
- 'scripts/templates/StylePropertyShorthand.cpp.tmpl',
+ '../build/scripts/templates/StylePropertyShorthand.h.tmpl',
+ '../build/scripts/templates/StylePropertyShorthand.cpp.tmpl',
],
'outputs': [
'<(SHARED_INTERMEDIATE_DIR)/blink/StylePropertyShorthand.cpp',
@@ -233,7 +214,7 @@
],
'action': [
'python',
- 'scripts/make_style_shorthands.py',
+ '../build/scripts/make_style_shorthands.py',
'css/CSSShorthands.in',
'--output_dir',
'<(SHARED_INTERMEDIATE_DIR)/blink',
@@ -243,11 +224,11 @@
'action_name': 'StyleBuilder',
'inputs': [
'<@(scripts_for_in_files)',
- 'scripts/make_style_builder.py',
+ '../build/scripts/make_style_builder.py',
'css/CSSProperties.in',
- 'scripts/templates/StyleBuilder.cpp.tmpl',
- 'scripts/templates/StyleBuilderFunctions.h.tmpl',
- 'scripts/templates/StyleBuilderFunctions.cpp.tmpl',
+ '../build/scripts/templates/StyleBuilder.cpp.tmpl',
+ '../build/scripts/templates/StyleBuilderFunctions.h.tmpl',
+ '../build/scripts/templates/StyleBuilderFunctions.cpp.tmpl',
],
'outputs': [
'<(SHARED_INTERMEDIATE_DIR)/blink/StyleBuilder.cpp',
@@ -256,7 +237,7 @@
],
'action': [
'python',
- 'scripts/make_style_builder.py',
+ '../build/scripts/make_style_builder.py',
'css/CSSProperties.in',
'--output_dir',
'<(SHARED_INTERMEDIATE_DIR)/blink',
@@ -272,7 +253,7 @@
},
'inputs': [
'<@(scripts_for_in_files)',
- 'scripts/make_css_value_keywords.py',
+ '../build/scripts/make_css_value_keywords.py',
'<@(in_files)'
],
'outputs': [
@@ -280,7 +261,7 @@
'<(SHARED_INTERMEDIATE_DIR)/blink/CSSValueKeywords.h',
],
'action': [
- 'scripts/make_css_value_keywords.py',
+ '../build/scripts/make_css_value_keywords.py',
'<@(in_files)',
'--output_dir',
'<(SHARED_INTERMEDIATE_DIR)/blink',
@@ -289,93 +270,59 @@
'msvs_cygwin_shell': 1,
},
{
- 'action_name': 'HTMLNames',
+ 'action_name': 'HTMLElementFactory',
'inputs': [
- 'scripts/Hasher.pm',
- 'scripts/StaticString.pm',
- 'scripts/make_names.pl',
+ '<@(make_element_factory_files)',
'html/HTMLTagNames.in',
'html/HTMLAttributeNames.in',
],
'outputs': [
+ '<(SHARED_INTERMEDIATE_DIR)/blink/HTMLElementFactory.cpp',
+ '<(SHARED_INTERMEDIATE_DIR)/blink/HTMLElementFactory.h',
'<(SHARED_INTERMEDIATE_DIR)/blink/HTMLNames.cpp',
'<(SHARED_INTERMEDIATE_DIR)/blink/HTMLNames.h',
- '<(SHARED_INTERMEDIATE_DIR)/blink/HTMLElementFactory.cpp',
'<(SHARED_INTERMEDIATE_DIR)/blink/V8HTMLElementWrapperFactory.cpp',
'<(SHARED_INTERMEDIATE_DIR)/blink/V8HTMLElementWrapperFactory.h',
],
'action': [
'python',
- 'scripts/action_makenames.py',
- '<@(_outputs)',
- '--',
- '<@(_inputs)',
- '--',
- '--factory',
- '--extraDefines', '<(feature_defines)'
- ],
- 'msvs_cygwin_shell': 1,
- },
- {
- 'action_name': 'FontFamilyNames',
- 'inputs': [
- 'scripts/Hasher.pm',
- 'scripts/StaticString.pm',
- 'scripts/make_names.pl',
- 'css/FontFamilyNames.in',
- ],
- 'outputs': [
- '<(SHARED_INTERMEDIATE_DIR)/blink/FontFamilyNames.cpp',
- '<(SHARED_INTERMEDIATE_DIR)/blink/FontFamilyNames.h',
- ],
- 'action': [
- 'python',
- 'scripts/action_makenames.py',
- '<@(_outputs)',
- '--',
- '<@(_inputs)',
- '--',
- '--fonts',
+ '../build/scripts/make_element_factory.py',
+ 'html/HTMLTagNames.in',
+ 'html/HTMLAttributeNames.in',
+ '--output_dir',
+ '<(SHARED_INTERMEDIATE_DIR)/blink',
],
- 'msvs_cygwin_shell': 1,
},
{
'action_name': 'SVGNames',
'inputs': [
- 'scripts/Hasher.pm',
- 'scripts/StaticString.pm',
- 'scripts/make_names.pl',
- 'svg/svgtags.in',
- 'svg/svgattrs.in',
+ '<@(make_element_factory_files)',
+ 'svg/SVGTagNames.in',
+ 'svg/SVGAttributeNames.in',
],
'outputs': [
- '<(SHARED_INTERMEDIATE_DIR)/blink/SVGNames.cpp',
- '<(SHARED_INTERMEDIATE_DIR)/blink/SVGNames.h',
'<(SHARED_INTERMEDIATE_DIR)/blink/SVGElementFactory.cpp',
'<(SHARED_INTERMEDIATE_DIR)/blink/SVGElementFactory.h',
+ '<(SHARED_INTERMEDIATE_DIR)/blink/SVGNames.cpp',
+ '<(SHARED_INTERMEDIATE_DIR)/blink/SVGNames.h',
'<(SHARED_INTERMEDIATE_DIR)/blink/V8SVGElementWrapperFactory.cpp',
'<(SHARED_INTERMEDIATE_DIR)/blink/V8SVGElementWrapperFactory.h',
],
'action': [
'python',
- 'scripts/action_makenames.py',
- '<@(_outputs)',
- '--',
- '<@(_inputs)',
- '--',
- '--factory',
- '--extraDefines', '<(feature_defines)'
+ '../build/scripts/make_element_factory.py',
+ 'svg/SVGTagNames.in',
+ 'svg/SVGAttributeNames.in',
+ '--output_dir',
+ '<(SHARED_INTERMEDIATE_DIR)/blink',
],
- 'msvs_cygwin_shell': 1,
},
{
'action_name': 'EventFactory',
'inputs': [
- '<@(scripts_for_in_files)',
- 'scripts/make_event_factory.py',
- 'scripts/name_utilities.py',
+ '<@(make_event_factory_files)',
'<(SHARED_INTERMEDIATE_DIR)/blink/EventInterfaces.in',
- 'dom/EventAliases.in',
+ 'events/EventAliases.in',
],
'outputs': [
'<(SHARED_INTERMEDIATE_DIR)/blink/Event.cpp',
@@ -384,9 +331,27 @@
],
'action': [
'python',
- 'scripts/make_event_factory.py',
+ '../build/scripts/make_event_factory.py',
+ '<(SHARED_INTERMEDIATE_DIR)/blink/EventInterfaces.in',
+ 'events/EventAliases.in',
+ '--output_dir',
+ '<(SHARED_INTERMEDIATE_DIR)/blink',
+ ],
+ },
+ {
+ 'action_name': 'EventNames',
+ 'inputs': [
+ '<@(make_names_files)',
+ '<(SHARED_INTERMEDIATE_DIR)/blink/EventInterfaces.in',
+ ],
+ 'outputs': [
+ '<(SHARED_INTERMEDIATE_DIR)/blink/EventNames.cpp',
+ '<(SHARED_INTERMEDIATE_DIR)/blink/EventNames.h',
+ ],
+ 'action': [
+ 'python',
+ '../build/scripts/make_names.py',
'<(SHARED_INTERMEDIATE_DIR)/blink/EventInterfaces.in',
- 'dom/EventAliases.in',
'--output_dir',
'<(SHARED_INTERMEDIATE_DIR)/blink',
],
@@ -394,10 +359,8 @@
{
'action_name': 'EventTargetFactory',
'inputs': [
- '<@(scripts_for_in_files)',
- 'scripts/make_event_factory.py',
- 'scripts/name_utilities.py',
- 'dom/EventTargetFactory.in',
+ '<@(make_event_factory_files)',
+ 'events/EventTargetFactory.in',
],
'outputs': [
'<(SHARED_INTERMEDIATE_DIR)/blink/EventTargetHeaders.h',
@@ -405,8 +368,26 @@
],
'action': [
'python',
- 'scripts/make_event_factory.py',
- 'dom/EventTargetFactory.in',
+ '../build/scripts/make_event_factory.py',
+ 'events/EventTargetFactory.in',
+ '--output_dir',
+ '<(SHARED_INTERMEDIATE_DIR)/blink',
+ ],
+ },
+ {
+ 'action_name': 'EventTargetNames',
+ 'inputs': [
+ '<@(make_names_files)',
+ 'events/EventTargetFactory.in',
+ ],
+ 'outputs': [
+ '<(SHARED_INTERMEDIATE_DIR)/blink/EventTargetNames.cpp',
+ '<(SHARED_INTERMEDIATE_DIR)/blink/EventTargetNames.h',
+ ],
+ 'action': [
+ 'python',
+ '../build/scripts/make_names.py',
+ 'events/EventTargetFactory.in',
'--output_dir',
'<(SHARED_INTERMEDIATE_DIR)/blink',
],
@@ -414,11 +395,9 @@
{
'action_name': 'MathMLNames',
'inputs': [
- 'scripts/Hasher.pm',
- 'scripts/StaticString.pm',
- 'scripts/make_names.pl',
- 'mathml/mathtags.in',
- 'mathml/mathattrs.in',
+ '<@(make_qualified_names_files)',
+ 'html/parser/MathMLTagNames.in',
+ 'html/parser/MathMLAttributeNames.in',
],
'outputs': [
'<(SHARED_INTERMEDIATE_DIR)/blink/MathMLNames.cpp',
@@ -426,21 +405,20 @@
],
'action': [
'python',
- 'scripts/action_makenames.py',
- '<@(_outputs)',
- '--',
- '<@(_inputs)',
- '--',
- '--extraDefines', '<(feature_defines)'
+ '../build/scripts/make_qualified_names.py',
+ 'html/parser/MathMLTagNames.in',
+ 'html/parser/MathMLAttributeNames.in',
+ '--output_dir',
+ '<(SHARED_INTERMEDIATE_DIR)/blink',
+ '--defines', '<(feature_defines)'
],
- 'msvs_cygwin_shell': 1,
},
{
'action_name': 'UserAgentStyleSheets',
'variables': {
'scripts': [
'css/make-css-file-arrays.pl',
- 'scripts/preprocessor.pm',
+ '../build/scripts/preprocessor.pm',
],
'stylesheets': [
'css/html.css',
@@ -457,6 +435,7 @@
'css/mediaControlsAndroid.css',
'css/fullscreen.css',
'css/xhtmlmp.css',
+ 'css/viewportAndroid.css',
],
},
'inputs': [
@@ -469,7 +448,7 @@
],
'action': [
'python',
- 'scripts/action_useragentstylesheets.py',
+ '../build/scripts/action_useragentstylesheets.py',
'<@(_outputs)',
'<@(stylesheets)',
'--',
@@ -482,9 +461,7 @@
{
'action_name': 'FetchInitiatorTypeNames',
'inputs': [
- 'scripts/Hasher.pm',
- 'scripts/StaticString.pm',
- 'scripts/make_names.pl',
+ '<@(make_names_files)',
'fetch/FetchInitiatorTypeNames.in',
],
'outputs': [
@@ -493,80 +470,52 @@
],
'action': [
'python',
- 'scripts/action_makenames.py',
- '<@(_outputs)',
- '--',
- '<@(_inputs)',
- '--',
- '--resourceTypes',
- ],
- 'msvs_cygwin_shell': 1,
- },
- {
- 'action_name': 'PickerCommon',
- 'inputs': [
- 'Resources/pagepopups/pickerCommon.css',
- 'Resources/pagepopups/pickerCommon.js',
- ],
- 'outputs': [
- '<(SHARED_INTERMEDIATE_DIR)/blink/PickerCommon.h',
- '<(SHARED_INTERMEDIATE_DIR)/blink/PickerCommon.cpp',
- ],
- 'action': [
- 'python',
- 'scripts/make-file-arrays.py',
- '--out-h=<(SHARED_INTERMEDIATE_DIR)/blink/PickerCommon.h',
- '--out-cpp=<(SHARED_INTERMEDIATE_DIR)/blink/PickerCommon.cpp',
- '<@(_inputs)',
+ '../build/scripts/make_names.py',
+ 'fetch/FetchInitiatorTypeNames.in',
+ '--output_dir',
+ '<(SHARED_INTERMEDIATE_DIR)/blink',
],
},
{
- 'action_name': 'CalendarPicker',
+ 'action_name': 'EventTypeNames',
'inputs': [
- 'Resources/pagepopups/calendarPicker.css',
- 'Resources/pagepopups/calendarPicker.js',
- 'Resources/pagepopups/chromium/calendarPickerChromium.css',
- 'Resources/pagepopups/chromium/pickerCommonChromium.css',
- 'Resources/pagepopups/suggestionPicker.css',
- 'Resources/pagepopups/suggestionPicker.js',
+ '<@(make_names_files)',
+ 'events/EventTypeNames.in',
],
'outputs': [
- '<(SHARED_INTERMEDIATE_DIR)/blink/CalendarPicker.h',
- '<(SHARED_INTERMEDIATE_DIR)/blink/CalendarPicker.cpp',
+ '<(SHARED_INTERMEDIATE_DIR)/blink/EventTypeNames.cpp',
+ '<(SHARED_INTERMEDIATE_DIR)/blink/EventTypeNames.h',
],
'action': [
'python',
- 'scripts/make-file-arrays.py',
- '--condition=ENABLE(CALENDAR_PICKER)',
- '--out-h=<(SHARED_INTERMEDIATE_DIR)/blink/CalendarPicker.h',
- '--out-cpp=<(SHARED_INTERMEDIATE_DIR)/blink/CalendarPicker.cpp',
- '<@(_inputs)',
+ '../build/scripts/make_names.py',
+ 'events/EventTypeNames.in',
+ '--output_dir',
+ '<(SHARED_INTERMEDIATE_DIR)/blink',
],
},
{
- 'action_name': 'ColorSuggestionPicker',
+ 'action_name': 'InputTypeNames',
'inputs': [
- 'Resources/pagepopups/colorSuggestionPicker.css',
- 'Resources/pagepopups/colorSuggestionPicker.js',
+ '<@(make_names_files)',
+ 'html/forms/InputTypeNames.in',
],
'outputs': [
- '<(SHARED_INTERMEDIATE_DIR)/blink/ColorSuggestionPicker.h',
- '<(SHARED_INTERMEDIATE_DIR)/blink/ColorSuggestionPicker.cpp',
+ '<(SHARED_INTERMEDIATE_DIR)/blink/InputTypeNames.cpp',
+ '<(SHARED_INTERMEDIATE_DIR)/blink/InputTypeNames.h',
],
'action': [
'python',
- 'scripts/make-file-arrays.py',
- '--out-h=<(SHARED_INTERMEDIATE_DIR)/blink/ColorSuggestionPicker.h',
- '--out-cpp=<(SHARED_INTERMEDIATE_DIR)/blink/ColorSuggestionPicker.cpp',
- '<@(_inputs)',
+ '../build/scripts/make_names.py',
+ 'html/forms/InputTypeNames.in',
+ '--output_dir',
+ '<(SHARED_INTERMEDIATE_DIR)/blink',
],
},
{
'action_name': 'XLinkNames',
'inputs': [
- 'scripts/Hasher.pm',
- 'scripts/StaticString.pm',
- 'scripts/make_names.pl',
+ '<@(make_qualified_names_files)',
'svg/xlinkattrs.in',
],
'outputs': [
@@ -575,21 +524,16 @@
],
'action': [
'python',
- 'scripts/action_makenames.py',
- '<@(_outputs)',
- '--',
- '<@(_inputs)',
- '--',
- '--extraDefines', '<(feature_defines)'
+ '../build/scripts/make_qualified_names.py',
+ 'svg/xlinkattrs.in',
+ '--output_dir',
+ '<(SHARED_INTERMEDIATE_DIR)/blink',
],
- 'msvs_cygwin_shell': 1,
},
{
'action_name': 'XMLNSNames',
'inputs': [
- 'scripts/Hasher.pm',
- 'scripts/StaticString.pm',
- 'scripts/make_names.pl',
+ '<@(make_qualified_names_files)',
'xml/xmlnsattrs.in',
],
'outputs': [
@@ -598,21 +542,16 @@
],
'action': [
'python',
- 'scripts/action_makenames.py',
- '<@(_outputs)',
- '--',
- '<@(_inputs)',
- '--',
- '--extraDefines', '<(feature_defines)'
+ '../build/scripts/make_qualified_names.py',
+ 'xml/xmlnsattrs.in',
+ '--output_dir',
+ '<(SHARED_INTERMEDIATE_DIR)/blink',
],
- 'msvs_cygwin_shell': 1,
},
{
'action_name': 'XMLNames',
'inputs': [
- 'scripts/Hasher.pm',
- 'scripts/StaticString.pm',
- 'scripts/make_names.pl',
+ '<@(make_qualified_names_files)',
'xml/xmlattrs.in',
],
'outputs': [
@@ -621,38 +560,34 @@
],
'action': [
'python',
- 'scripts/action_makenames.py',
- '<@(_outputs)',
- '--',
- '<@(_inputs)',
- '--',
- '--extraDefines', '<(feature_defines)'
+ '../build/scripts/make_qualified_names.py',
+ 'xml/xmlattrs.in',
+ '--output_dir',
+ '<(SHARED_INTERMEDIATE_DIR)/blink',
],
- 'msvs_cygwin_shell': 1,
},
{
- 'action_name': 'preprocess_grammar',
+ 'action_name': 'MakeTokenMatcher',
'inputs': [
- 'css/CSSGrammar.y.in',
- 'css/CSSGrammar.y.includes',
+ '<@(scripts_for_in_files)',
+ '../build/scripts/make_token_matcher.py',
+ '../core/css/CSSTokenizer-in.cpp',
],
'outputs': [
- '<(SHARED_INTERMEDIATE_DIR)/blink/CSSGrammar.y',
+ '<(SHARED_INTERMEDIATE_DIR)/blink/CSSTokenizer.cpp',
],
'action': [
- '<(perl_exe)',
- '-Iscripts',
- 'css/makegrammar.pl',
- '--outputDir',
- '<(SHARED_INTERMEDIATE_DIR)/blink',
- '<@(_inputs)',
+ 'python',
+ '../build/scripts/make_token_matcher.py',
+ '../core/css/CSSTokenizer-in.cpp',
+ '<(SHARED_INTERMEDIATE_DIR)/blink/CSSTokenizer.cpp',
],
},
{
- 'action_name': 'MakeTokenMatcher',
+ 'action_name': 'MakeParser',
'inputs': [
'<@(scripts_for_in_files)',
- '../core/scripts/make_token_matcher.py',
+ '../build/scripts/make_token_matcher.py',
'../core/css/CSSParser-in.cpp',
],
'outputs': [
@@ -660,11 +595,49 @@
],
'action': [
'python',
- '../core/scripts/make_token_matcher.py',
+ '../build/scripts/make_token_matcher.py',
'../core/css/CSSParser-in.cpp',
'<(SHARED_INTERMEDIATE_DIR)/blink/CSSParser.cpp',
],
},
+ {
+ 'action_name': 'MakeTokenMatcherForViewport',
+ 'inputs': [
+ '<@(scripts_for_in_files)',
+ '../build/scripts/make_token_matcher.py',
+ '../core/html/HTMLMetaElement-in.cpp',
+ ],
+ 'outputs': [
+ '<(SHARED_INTERMEDIATE_DIR)/blink/HTMLMetaElement.cpp',
+ ],
+ 'action': [
+ 'python',
+ '../build/scripts/make_token_matcher.py',
+ '../core/html/HTMLMetaElement-in.cpp',
+ '<(SHARED_INTERMEDIATE_DIR)/blink/HTMLMetaElement.cpp',
+ ],
+ },
+ {
+ 'action_name': 'HTMLElementLookupTrie',
+ 'inputs': [
+ '<@(scripts_for_in_files)',
+ '../build/scripts/make_element_lookup_trie.py',
+ '../build/scripts/templates/ElementLookupTrie.cpp.tmpl',
+ '../build/scripts/templates/ElementLookupTrie.h.tmpl',
+ 'html/HTMLTagNames.in',
+ ],
+ 'outputs': [
+ '<(SHARED_INTERMEDIATE_DIR)/blink/HTMLElementLookupTrie.cpp',
+ '<(SHARED_INTERMEDIATE_DIR)/blink/HTMLElementLookupTrie.h',
+ ],
+ 'action': [
+ 'python',
+ '../build/scripts/make_element_lookup_trie.py',
+ 'html/HTMLTagNames.in',
+ '--output_dir',
+ '<(SHARED_INTERMEDIATE_DIR)/blink',
+ ],
+ },
],
'rules': [
{
@@ -676,31 +649,13 @@
],
'action': [
'python',
- 'scripts/rule_bison.py',
+ '../build/scripts/rule_bison.py',
'<(RULE_INPUT_PATH)',
'<(SHARED_INTERMEDIATE_DIR)/blink',
'<(bison_exe)',
],
'msvs_cygwin_shell': 1,
},
- {
- 'rule_name': 'gperf',
- 'extension': 'gperf',
- 'outputs': [
- '<(SHARED_INTERMEDIATE_DIR)/blink/<(RULE_INPUT_ROOT).cpp',
- ],
- 'inputs': [
- 'scripts/make-hash-tools.pl',
- ],
- 'msvs_cygwin_shell': 0,
- 'action': [
- '<(perl_exe)',
- 'scripts/make-hash-tools.pl',
- '<(SHARED_INTERMEDIATE_DIR)/blink',
- '<(RULE_INPUT_PATH)',
- '<(gperf_exe)',
- ],
- },
],
},
],
diff --git a/chromium/third_party/WebKit/Source/core/css/BasicShapeFunctions.cpp b/chromium/third_party/WebKit/Source/core/css/BasicShapeFunctions.cpp
index e80d033b712..a49ea1495f1 100644
--- a/chromium/third_party/WebKit/Source/core/css/BasicShapeFunctions.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/BasicShapeFunctions.cpp
@@ -35,23 +35,26 @@
#include "core/css/CSSValuePool.h"
#include "core/css/resolver/StyleResolverState.h"
#include "core/rendering/style/BasicShapes.h"
+#include "core/rendering/style/RenderStyle.h"
namespace WebCore {
-PassRefPtr<CSSValue> valueForBasicShape(const BasicShape* basicShape)
+PassRefPtr<CSSValue> valueForBasicShape(const RenderStyle& style, const BasicShape* basicShape)
{
+ CSSValuePool& pool = cssValuePool();
+
RefPtr<CSSBasicShape> basicShapeValue;
switch (basicShape->type()) {
case BasicShape::BasicShapeRectangleType: {
const BasicShapeRectangle* rectangle = static_cast<const BasicShapeRectangle*>(basicShape);
RefPtr<CSSBasicShapeRectangle> rectangleValue = CSSBasicShapeRectangle::create();
- rectangleValue->setX(cssValuePool().createValue(rectangle->x()));
- rectangleValue->setY(cssValuePool().createValue(rectangle->y()));
- rectangleValue->setWidth(cssValuePool().createValue(rectangle->width()));
- rectangleValue->setHeight(cssValuePool().createValue(rectangle->height()));
- rectangleValue->setRadiusX(cssValuePool().createValue(rectangle->cornerRadiusX()));
- rectangleValue->setRadiusY(cssValuePool().createValue(rectangle->cornerRadiusY()));
+ rectangleValue->setX(pool.createValue(rectangle->x(), style));
+ rectangleValue->setY(pool.createValue(rectangle->y(), style));
+ rectangleValue->setWidth(pool.createValue(rectangle->width(), style));
+ rectangleValue->setHeight(pool.createValue(rectangle->height(), style));
+ rectangleValue->setRadiusX(pool.createValue(rectangle->cornerRadiusX(), style));
+ rectangleValue->setRadiusY(pool.createValue(rectangle->cornerRadiusY(), style));
basicShapeValue = rectangleValue.release();
break;
@@ -60,9 +63,9 @@ PassRefPtr<CSSValue> valueForBasicShape(const BasicShape* basicShape)
const BasicShapeCircle* circle = static_cast<const BasicShapeCircle*>(basicShape);
RefPtr<CSSBasicShapeCircle> circleValue = CSSBasicShapeCircle::create();
- circleValue->setCenterX(cssValuePool().createValue(circle->centerX()));
- circleValue->setCenterY(cssValuePool().createValue(circle->centerY()));
- circleValue->setRadius(cssValuePool().createValue(circle->radius()));
+ circleValue->setCenterX(pool.createValue(circle->centerX(), style));
+ circleValue->setCenterY(pool.createValue(circle->centerY(), style));
+ circleValue->setRadius(pool.createValue(circle->radius(), style));
basicShapeValue = circleValue.release();
break;
@@ -71,10 +74,10 @@ PassRefPtr<CSSValue> valueForBasicShape(const BasicShape* basicShape)
const BasicShapeEllipse* ellipse = static_cast<const BasicShapeEllipse*>(basicShape);
RefPtr<CSSBasicShapeEllipse> ellipseValue = CSSBasicShapeEllipse::create();
- ellipseValue->setCenterX(cssValuePool().createValue(ellipse->centerX()));
- ellipseValue->setCenterY(cssValuePool().createValue(ellipse->centerY()));
- ellipseValue->setRadiusX(cssValuePool().createValue(ellipse->radiusX()));
- ellipseValue->setRadiusY(cssValuePool().createValue(ellipse->radiusY()));
+ ellipseValue->setCenterX(pool.createValue(ellipse->centerX(), style));
+ ellipseValue->setCenterY(pool.createValue(ellipse->centerY(), style));
+ ellipseValue->setRadiusX(pool.createValue(ellipse->radiusX(), style));
+ ellipseValue->setRadiusY(pool.createValue(ellipse->radiusY(), style));
basicShapeValue = ellipseValue.release();
break;
@@ -86,7 +89,7 @@ PassRefPtr<CSSValue> valueForBasicShape(const BasicShape* basicShape)
polygonValue->setWindRule(polygon->windRule());
const Vector<Length>& values = polygon->values();
for (unsigned i = 0; i < values.size(); i += 2)
- polygonValue->appendPoint(cssValuePool().createValue(values.at(i)), cssValuePool().createValue(values.at(i + 1)));
+ polygonValue->appendPoint(pool.createValue(values.at(i), style), pool.createValue(values.at(i + 1), style));
basicShapeValue = polygonValue.release();
break;
@@ -108,12 +111,12 @@ PassRefPtr<CSSValue> valueForBasicShape(const BasicShape* basicShape)
default:
break;
}
- return cssValuePool().createValue<PassRefPtr<CSSBasicShape> >(basicShapeValue.release());
+ return pool.createValue(basicShapeValue.release());
}
static Length convertToLength(const StyleResolverState& state, CSSPrimitiveValue* value)
{
- return value->convertToLength<FixedIntegerConversion | FixedFloatConversion | PercentConversion>(state.style(), state.rootElementStyle(), state.style()->effectiveZoom());
+ return value->convertToLength<FixedConversion | PercentConversion>(state.cssToLengthConversionData());
}
PassRefPtr<BasicShape> basicShapeForValue(const StyleResolverState& state, const CSSBasicShape* basicShapeValue)
diff --git a/chromium/third_party/WebKit/Source/core/css/BasicShapeFunctions.h b/chromium/third_party/WebKit/Source/core/css/BasicShapeFunctions.h
index 4b3d39f07e4..7d07e311a2e 100644
--- a/chromium/third_party/WebKit/Source/core/css/BasicShapeFunctions.h
+++ b/chromium/third_party/WebKit/Source/core/css/BasicShapeFunctions.h
@@ -38,8 +38,9 @@ class BasicShape;
class CSSBasicShape;
class CSSValue;
class StyleResolverState;
+class RenderStyle;
-PassRefPtr<CSSValue> valueForBasicShape(const BasicShape*);
+PassRefPtr<CSSValue> valueForBasicShape(const RenderStyle&, const BasicShape*);
PassRefPtr<BasicShape> basicShapeForValue(const StyleResolverState&, const CSSBasicShape*);
}
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSArrayFunctionValue.cpp b/chromium/third_party/WebKit/Source/core/css/CSSArrayFunctionValue.cpp
index b2dddbd5727..3ead9d8137b 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSArrayFunctionValue.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/CSSArrayFunctionValue.cpp
@@ -42,9 +42,9 @@ CSSArrayFunctionValue::CSSArrayFunctionValue(const CSSArrayFunctionValue& cloneF
{
}
-String CSSArrayFunctionValue::customCssText() const
+String CSSArrayFunctionValue::customCSSText() const
{
- return "array(" + CSSValueList::customCssText() + ')';
+ return "array(" + CSSValueList::customCSSText() + ')';
}
PassRefPtr<CSSArrayFunctionValue> CSSArrayFunctionValue::cloneForCSSOM() const
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSArrayFunctionValue.h b/chromium/third_party/WebKit/Source/core/css/CSSArrayFunctionValue.h
index 9325207b6b0..fffc616c32d 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSArrayFunctionValue.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSArrayFunctionValue.h
@@ -42,7 +42,7 @@ public:
return adoptRef(new CSSArrayFunctionValue());
}
- String customCssText() const;
+ String customCSSText() const;
PassRefPtr<CSSArrayFunctionValue> cloneForCSSOM() const;
@@ -53,6 +53,8 @@ private:
explicit CSSArrayFunctionValue(const CSSArrayFunctionValue& cloneFrom);
};
+DEFINE_CSS_VALUE_TYPE_CASTS(CSSArrayFunctionValue, isArrayFunctionValue());
+
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSAspectRatioValue.cpp b/chromium/third_party/WebKit/Source/core/css/CSSAspectRatioValue.cpp
index 3a1fa318c41..8da5a2271cb 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSAspectRatioValue.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/CSSAspectRatioValue.cpp
@@ -31,7 +31,7 @@
namespace WebCore {
-String CSSAspectRatioValue::customCssText() const
+String CSSAspectRatioValue::customCSSText() const
{
return String::number(m_numeratorValue) + '/' + String::number(m_denominatorValue);
}
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSAspectRatioValue.h b/chromium/third_party/WebKit/Source/core/css/CSSAspectRatioValue.h
index 15bbce39f7c..a92ac34c2bb 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSAspectRatioValue.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSAspectRatioValue.h
@@ -40,7 +40,7 @@ public:
return adoptRef(new CSSAspectRatioValue(numeratorValue, denominatorValue));
}
- String customCssText() const;
+ String customCSSText() const;
float numeratorValue() const { return m_numeratorValue; }
float denominatorValue() const { return m_denominatorValue; }
@@ -59,6 +59,8 @@ private:
float m_denominatorValue;
};
+DEFINE_CSS_VALUE_TYPE_CASTS(CSSAspectRatioValue, isAspectRatioValue());
+
}
#endif
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSBasicShapes.h b/chromium/third_party/WebKit/Source/core/css/CSSBasicShapes.h
index e739ab058a3..ca8c661fc47 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSBasicShapes.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSBasicShapes.h
@@ -31,7 +31,7 @@
#define CSSBasicShapes_h
#include "core/css/CSSPrimitiveValue.h"
-#include "core/platform/graphics/WindRule.h"
+#include "platform/graphics/WindRule.h"
#include "wtf/RefPtr.h"
#include "wtf/Vector.h"
#include "wtf/text/WTFString.h"
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSBorderImageSliceValue.cpp b/chromium/third_party/WebKit/Source/core/css/CSSBorderImageSliceValue.cpp
index 792f9c2d234..7ffac3afb9b 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSBorderImageSliceValue.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/CSSBorderImageSliceValue.cpp
@@ -37,7 +37,7 @@ CSSBorderImageSliceValue::CSSBorderImageSliceValue(PassRefPtr<CSSPrimitiveValue>
{
}
-String CSSBorderImageSliceValue::customCssText() const
+String CSSBorderImageSliceValue::customCSSText() const
{
// Dump the slices first.
String text = m_slices->cssText();
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSBorderImageSliceValue.h b/chromium/third_party/WebKit/Source/core/css/CSSBorderImageSliceValue.h
index 37c13545089..7d297ea9be0 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSBorderImageSliceValue.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSBorderImageSliceValue.h
@@ -41,7 +41,7 @@ public:
return adoptRef(new CSSBorderImageSliceValue(slices, fill));
}
- String customCssText() const;
+ String customCSSText() const;
Quad* slices() { return m_slices ? m_slices->getQuadValue() : 0; }
@@ -56,6 +56,8 @@ private:
CSSBorderImageSliceValue(PassRefPtr<CSSPrimitiveValue> slices, bool fill);
};
+DEFINE_CSS_VALUE_TYPE_CASTS(CSSBorderImageSliceValue, isBorderImageSliceValue());
+
} // namespace WebCore
#endif // CSSBorderImageSliceValue_h
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSCalculationValue.cpp b/chromium/third_party/WebKit/Source/core/css/CSSCalculationValue.cpp
index f2eaae38cd7..e27cba3a66d 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSCalculationValue.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/CSSCalculationValue.cpp
@@ -35,7 +35,6 @@
#include "core/css/resolver/StyleResolver.h"
#include "wtf/MathExtras.h"
#include "wtf/OwnPtr.h"
-#include "wtf/PassOwnPtr.h"
#include "wtf/text/StringBuilder.h"
static const int maxExpressionDepth = 100;
@@ -136,7 +135,7 @@ static bool hasDoubleValue(CSSPrimitiveValue::UnitTypes type)
return false;
}
-static String buildCssText(const String& expression)
+static String buildCSSText(const String& expression)
{
StringBuilder result;
result.append("calc");
@@ -149,9 +148,9 @@ static String buildCssText(const String& expression)
return result.toString();
}
-String CSSCalcValue::customCssText() const
+String CSSCalcValue::customCSSText() const
{
- return buildCssText(m_expression->customCssText());
+ return buildCSSText(m_expression->customCSSText());
}
bool CSSCalcValue::equals(const CSSCalcValue& other) const
@@ -161,7 +160,7 @@ bool CSSCalcValue::equals(const CSSCalcValue& other) const
String CSSCalcValue::customSerializeResolvingVariables(const HashMap<AtomicString, String>& variables) const
{
- return buildCssText(m_expression->serializeResolvingVariables(variables));
+ return buildCSSText(m_expression->serializeResolvingVariables(variables));
}
bool CSSCalcValue::hasVariableReference() const
@@ -179,9 +178,9 @@ double CSSCalcValue::doubleValue() const
return clampToPermittedRange(m_expression->doubleValue());
}
-double CSSCalcValue::computeLengthPx(const RenderStyle* currentStyle, const RenderStyle* rootStyle, double multiplier, bool computingFontSize) const
+double CSSCalcValue::computeLengthPx(const CSSToLengthConversionData& conversionData) const
{
- return clampToPermittedRange(m_expression->computeLengthPx(currentStyle, rootStyle, multiplier, computingFontSize));
+ return clampToPermittedRange(m_expression->computeLengthPx(conversionData));
}
CSSCalcExpressionNode::~CSSCalcExpressionNode()
@@ -209,7 +208,7 @@ public:
return !m_value->getDoubleValue();
}
- virtual String customCssText() const
+ virtual String customCSSText() const
{
return m_value->cssText();
}
@@ -224,18 +223,18 @@ public:
return m_value->isVariableName();
}
- virtual PassOwnPtr<CalcExpressionNode> toCalcValue(const RenderStyle* style, const RenderStyle* rootStyle, double zoom) const
+ virtual PassOwnPtr<CalcExpressionNode> toCalcValue(const CSSToLengthConversionData& conversionData) const
{
switch (m_category) {
case CalcNumber:
return adoptPtr(new CalcExpressionNumber(m_value->getFloatValue()));
case CalcLength:
- return adoptPtr(new CalcExpressionNumber(m_value->computeLength<float>(style, rootStyle, zoom)));
+ return adoptPtr(new CalcExpressionLength(Length(m_value->computeLength<float>(conversionData), WebCore::Fixed)));
case CalcPercent:
case CalcPercentLength: {
CSSPrimitiveValue* primitiveValue = m_value.get();
return adoptPtr(new CalcExpressionLength(primitiveValue
- ? primitiveValue->convertToLength<FixedFloatConversion | PercentConversion | FractionConversion>(style, rootStyle, zoom)
+ ? primitiveValue->convertToLength<FixedConversion | PercentConversion>(conversionData)
: Length(Undefined)));
}
// Only types that could be part of a Length expression can be converted
@@ -256,11 +255,11 @@ public:
return 0;
}
- virtual double computeLengthPx(const RenderStyle* currentStyle, const RenderStyle* rootStyle, double multiplier, bool computingFontSize) const
+ virtual double computeLengthPx(const CSSToLengthConversionData& conversionData) const
{
switch (m_category) {
case CalcLength:
- return m_value->computeLength<double>(currentStyle, rootStyle, multiplier, computingFontSize);
+ return m_value->computeLength<double>(conversionData);
case CalcPercent:
case CalcNumber:
return m_value->getDoubleValue();
@@ -421,12 +420,12 @@ public:
return !doubleValue();
}
- virtual PassOwnPtr<CalcExpressionNode> toCalcValue(const RenderStyle* style, const RenderStyle* rootStyle, double zoom) const
+ virtual PassOwnPtr<CalcExpressionNode> toCalcValue(const CSSToLengthConversionData& conversionData) const
{
- OwnPtr<CalcExpressionNode> left(m_leftSide->toCalcValue(style, rootStyle, zoom));
+ OwnPtr<CalcExpressionNode> left(m_leftSide->toCalcValue(conversionData));
if (!left)
return nullptr;
- OwnPtr<CalcExpressionNode> right(m_rightSide->toCalcValue(style, rootStyle, zoom));
+ OwnPtr<CalcExpressionNode> right(m_rightSide->toCalcValue(conversionData));
if (!right)
return nullptr;
return adoptPtr(new CalcExpressionBinaryOperation(left.release(), right.release(), m_operator));
@@ -437,14 +436,14 @@ public:
return evaluate(m_leftSide->doubleValue(), m_rightSide->doubleValue());
}
- virtual double computeLengthPx(const RenderStyle* currentStyle, const RenderStyle* rootStyle, double multiplier, bool computingFontSize) const
+ virtual double computeLengthPx(const CSSToLengthConversionData& conversionData) const
{
- const double leftValue = m_leftSide->computeLengthPx(currentStyle, rootStyle, multiplier, computingFontSize);
- const double rightValue = m_rightSide->computeLengthPx(currentStyle, rootStyle, multiplier, computingFontSize);
+ const double leftValue = m_leftSide->computeLengthPx(conversionData);
+ const double rightValue = m_rightSide->computeLengthPx(conversionData);
return evaluate(leftValue, rightValue);
}
- static String buildCssText(const String& leftExpression, const String& rightExpression, CalcOperator op)
+ static String buildCSSText(const String& leftExpression, const String& rightExpression, CalcOperator op)
{
StringBuilder result;
result.append('(');
@@ -458,14 +457,14 @@ public:
return result.toString();
}
- virtual String customCssText() const
+ virtual String customCSSText() const
{
- return buildCssText(m_leftSide->customCssText(), m_rightSide->customCssText(), m_operator);
+ return buildCSSText(m_leftSide->customCSSText(), m_rightSide->customCSSText(), m_operator);
}
virtual String serializeResolvingVariables(const HashMap<AtomicString, String>& variables) const
{
- return buildCssText(m_leftSide->serializeResolvingVariables(variables), m_rightSide->serializeResolvingVariables(variables), m_operator);
+ return buildCSSText(m_leftSide->serializeResolvingVariables(variables), m_rightSide->serializeResolvingVariables(variables), m_operator);
}
virtual bool hasVariableReference() const
@@ -611,8 +610,7 @@ private:
if (!value || !value->isPrimitiveValue())
return false;
- CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value.get());
- result->value = CSSCalcPrimitiveValue::create(primitiveValue, parserValue->isInt);
+ result->value = CSSCalcPrimitiveValue::create(toCSSPrimitiveValue(value.get()), parserValue->isInt);
++*index;
return true;
@@ -707,7 +705,7 @@ PassRefPtr<CSSCalcExpressionNode> CSSCalcValue::createExpressionNode(PassRefPtr<
return CSSCalcBinaryOperation::create(leftSide, rightSide, op);
}
-PassRefPtr<CSSCalcExpressionNode> CSSCalcValue::createExpressionNode(const CalcExpressionNode* node, const RenderStyle* style)
+PassRefPtr<CSSCalcExpressionNode> CSSCalcValue::createExpressionNode(const CalcExpressionNode* node, float zoom)
{
switch (node->type()) {
case CalcExpressionNodeNumber: {
@@ -715,10 +713,10 @@ PassRefPtr<CSSCalcExpressionNode> CSSCalcValue::createExpressionNode(const CalcE
return createExpressionNode(CSSPrimitiveValue::create(value, CSSPrimitiveValue::CSS_NUMBER), value == trunc(value));
}
case CalcExpressionNodeLength:
- return createExpressionNode(toCalcExpressionLength(node)->length(), style);
+ return createExpressionNode(toCalcExpressionLength(node)->length(), zoom);
case CalcExpressionNodeBinaryOperation: {
const CalcExpressionBinaryOperation* binaryNode = toCalcExpressionBinaryOperation(node);
- return createExpressionNode(createExpressionNode(binaryNode->leftSide(), style), createExpressionNode(binaryNode->rightSide(), style), binaryNode->getOperator());
+ return createExpressionNode(createExpressionNode(binaryNode->leftSide(), zoom), createExpressionNode(binaryNode->rightSide(), zoom), binaryNode->getOperator());
}
case CalcExpressionNodeBlendLength: {
// FIXME(crbug.com/269320): Create a CSSCalcExpressionNode equivalent of CalcExpressionBlendLength.
@@ -727,11 +725,11 @@ PassRefPtr<CSSCalcExpressionNode> CSSCalcValue::createExpressionNode(const CalcE
const bool isInteger = !progress || (progress == 1);
return createExpressionNode(
createExpressionNode(
- createExpressionNode(blendNode->from(), style),
+ createExpressionNode(blendNode->from(), zoom),
createExpressionNode(CSSPrimitiveValue::create(1 - progress, CSSPrimitiveValue::CSS_NUMBER), isInteger),
CalcMultiply),
createExpressionNode(
- createExpressionNode(blendNode->to(), style),
+ createExpressionNode(blendNode->to(), zoom),
createExpressionNode(CSSPrimitiveValue::create(progress, CSSPrimitiveValue::CSS_NUMBER), isInteger),
CalcMultiply),
CalcAdd);
@@ -744,7 +742,7 @@ PassRefPtr<CSSCalcExpressionNode> CSSCalcValue::createExpressionNode(const CalcE
return 0;
}
-PassRefPtr<CSSCalcExpressionNode> CSSCalcValue::createExpressionNode(const Length& length, const RenderStyle* style)
+PassRefPtr<CSSCalcExpressionNode> CSSCalcValue::createExpressionNode(const Length& length, float zoom)
{
switch (length.type()) {
case Percent:
@@ -753,9 +751,9 @@ PassRefPtr<CSSCalcExpressionNode> CSSCalcValue::createExpressionNode(const Lengt
case ViewportPercentageMin:
case ViewportPercentageMax:
case Fixed:
- return createExpressionNode(CSSPrimitiveValue::create(length, style), length.value() == trunc(length.value()));
+ return createExpressionNode(CSSPrimitiveValue::create(length, zoom), length.value() == trunc(length.value()));
case Calculated:
- return createExpressionNode(length.calculationValue()->expression(), style);
+ return createExpressionNode(length.calculationValue()->expression(), zoom);
case Auto:
case Intrinsic:
case MinIntrinsic:
@@ -764,7 +762,6 @@ PassRefPtr<CSSCalcExpressionNode> CSSCalcValue::createExpressionNode(const Lengt
case FillAvailable:
case FitContent:
case ExtendToZoom:
- case Relative:
case Undefined:
ASSERT_NOT_REACHED();
return 0;
@@ -773,7 +770,7 @@ PassRefPtr<CSSCalcExpressionNode> CSSCalcValue::createExpressionNode(const Lengt
return 0;
}
-PassRefPtr<CSSCalcValue> CSSCalcValue::create(CSSParserString name, CSSParserValueList* parserValueList, CalculationPermittedValueRange range)
+PassRefPtr<CSSCalcValue> CSSCalcValue::create(CSSParserString name, CSSParserValueList* parserValueList, ValueRange range)
{
CSSCalcExpressionNodeParser parser;
RefPtr<CSSCalcExpressionNode> expression;
@@ -785,7 +782,7 @@ PassRefPtr<CSSCalcValue> CSSCalcValue::create(CSSParserString name, CSSParserVal
return expression ? adoptRef(new CSSCalcValue(expression, range)) : 0;
}
-PassRefPtr<CSSCalcValue> CSSCalcValue::create(PassRefPtr<CSSCalcExpressionNode> expression, CalculationPermittedValueRange range)
+PassRefPtr<CSSCalcValue> CSSCalcValue::create(PassRefPtr<CSSCalcExpressionNode> expression, ValueRange range)
{
return adoptRef(new CSSCalcValue(expression, range));
}
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSCalculationValue.h b/chromium/third_party/WebKit/Source/core/css/CSSCalculationValue.h
index 6bf1ac77149..6d58d608931 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSCalculationValue.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSCalculationValue.h
@@ -34,7 +34,7 @@
#include "core/css/CSSParserValues.h"
#include "core/css/CSSPrimitiveValue.h"
#include "core/css/CSSValue.h"
-#include "core/platform/CalculationValue.h"
+#include "platform/CalculationValue.h"
#include "wtf/PassOwnPtr.h"
#include "wtf/RefCounted.h"
#include "wtf/RefPtr.h"
@@ -45,8 +45,7 @@ class CSSParserValueList;
class CSSValueList;
class CalculationValue;
class CalcExpressionNode;
-class RenderStyle;
-struct Length;
+class Length;
enum CalculationCategory {
CalcNumber = 0,
@@ -67,10 +66,10 @@ public:
virtual ~CSSCalcExpressionNode() = 0;
virtual bool isZero() const = 0;
- virtual PassOwnPtr<CalcExpressionNode> toCalcValue(const RenderStyle*, const RenderStyle* rootStyle, double zoom = 1.0) const = 0;
+ virtual PassOwnPtr<CalcExpressionNode> toCalcValue(const CSSToLengthConversionData&) const = 0;
virtual double doubleValue() const = 0;
- virtual double computeLengthPx(const RenderStyle* currentStyle, const RenderStyle* rootStyle, double multiplier = 1.0, bool computingFontSize = false) const = 0;
- virtual String customCssText() const = 0;
+ virtual double computeLengthPx(const CSSToLengthConversionData&) const = 0;
+ virtual String customCSSText() const = 0;
virtual String serializeResolvingVariables(const HashMap<AtomicString, String>&) const = 0;
virtual bool hasVariableReference() const = 0;
virtual bool equals(const CSSCalcExpressionNode& other) const { return m_category == other.m_category && m_isInteger == other.m_isInteger; }
@@ -93,42 +92,42 @@ protected:
class CSSCalcValue : public CSSValue {
public:
- static PassRefPtr<CSSCalcValue> create(CSSParserString name, CSSParserValueList*, CalculationPermittedValueRange);
- static PassRefPtr<CSSCalcValue> create(PassRefPtr<CSSCalcExpressionNode>, CalculationPermittedValueRange = CalculationRangeAll);
- static PassRefPtr<CSSCalcValue> create(const CalculationValue* value, const RenderStyle* style) { return adoptRef(new CSSCalcValue(value, style)); }
+ static PassRefPtr<CSSCalcValue> create(CSSParserString name, CSSParserValueList*, ValueRange);
+ static PassRefPtr<CSSCalcValue> create(PassRefPtr<CSSCalcExpressionNode>, ValueRange = ValueRangeAll);
+ static PassRefPtr<CSSCalcValue> create(const CalculationValue* value, float zoom) { return adoptRef(new CSSCalcValue(value, zoom)); }
static PassRefPtr<CSSCalcExpressionNode> createExpressionNode(PassRefPtr<CSSPrimitiveValue>, bool isInteger = false);
static PassRefPtr<CSSCalcExpressionNode> createExpressionNode(PassRefPtr<CSSCalcExpressionNode>, PassRefPtr<CSSCalcExpressionNode>, CalcOperator);
- static PassRefPtr<CSSCalcExpressionNode> createExpressionNode(const CalcExpressionNode*, const RenderStyle*);
- static PassRefPtr<CSSCalcExpressionNode> createExpressionNode(const Length&, const RenderStyle*);
+ static PassRefPtr<CSSCalcExpressionNode> createExpressionNode(const CalcExpressionNode*, float zoom);
+ static PassRefPtr<CSSCalcExpressionNode> createExpressionNode(const Length&, float zoom);
- PassRefPtr<CalculationValue> toCalcValue(const RenderStyle* style, const RenderStyle* rootStyle, double zoom = 1.0) const
+ PassRefPtr<CalculationValue> toCalcValue(const CSSToLengthConversionData& conversionData) const
{
- return CalculationValue::create(m_expression->toCalcValue(style, rootStyle, zoom), m_nonNegative ? CalculationRangeNonNegative : CalculationRangeAll);
+ return CalculationValue::create(m_expression->toCalcValue(conversionData), m_nonNegative ? ValueRangeNonNegative : ValueRangeAll);
}
CalculationCategory category() const { return m_expression->category(); }
bool isInt() const { return m_expression->isInteger(); }
double doubleValue() const;
bool isNegative() const { return m_expression->doubleValue() < 0; }
- CalculationPermittedValueRange permittedValueRange() { return m_nonNegative ? CalculationRangeNonNegative : CalculationRangeAll; }
- double computeLengthPx(const RenderStyle* currentStyle, const RenderStyle* rootStyle, double multiplier = 1.0, bool computingFontSize = false) const;
+ ValueRange permittedValueRange() { return m_nonNegative ? ValueRangeNonNegative : ValueRangeAll; }
+ double computeLengthPx(const CSSToLengthConversionData&) const;
CSSCalcExpressionNode* expressionNode() const { return m_expression.get(); }
- String customCssText() const;
+ String customCSSText() const;
bool equals(const CSSCalcValue&) const;
String customSerializeResolvingVariables(const HashMap<AtomicString, String>&) const;
bool hasVariableReference() const;
private:
- CSSCalcValue(PassRefPtr<CSSCalcExpressionNode> expression, CalculationPermittedValueRange range)
+ CSSCalcValue(PassRefPtr<CSSCalcExpressionNode> expression, ValueRange range)
: CSSValue(CalculationClass)
, m_expression(expression)
- , m_nonNegative(range == CalculationRangeNonNegative)
+ , m_nonNegative(range == ValueRangeNonNegative)
{
}
- CSSCalcValue(const CalculationValue* value, const RenderStyle* style)
+ CSSCalcValue(const CalculationValue* value, float zoom)
: CSSValue(CalculationClass)
- , m_expression(createExpressionNode(value->expression(), style))
+ , m_expression(createExpressionNode(value->expression(), zoom))
, m_nonNegative(value->isNonNegative())
{
}
@@ -139,17 +138,7 @@ private:
const bool m_nonNegative;
};
-inline CSSCalcValue* toCSSCalcValue(CSSValue* value)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!value || value->isCalculationValue());
- return static_cast<CSSCalcValue*>(value);
-}
-
-inline const CSSCalcValue* toCSSCalcValue(const CSSValue* value)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!value || value->isCalculationValue());
- return static_cast<const CSSCalcValue*>(value);
-}
+DEFINE_CSS_VALUE_TYPE_CASTS(CSSCalcValue, isCalcValue());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSCalculationValueTest.cpp b/chromium/third_party/WebKit/Source/core/css/CSSCalculationValueTest.cpp
index bfd0be481e6..57875523784 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSCalculationValueTest.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/CSSCalculationValueTest.cpp
@@ -32,6 +32,7 @@
#include "core/css/CSSCalculationValue.h"
#include "core/css/CSSPrimitiveValue.h"
+#include "core/css/CSSToLengthConversionData.h"
#include "core/rendering/style/RenderStyle.h"
#include "core/rendering/style/StyleInheritedData.h"
@@ -41,6 +42,15 @@ using namespace WebCore;
namespace {
+void testExpression(PassRefPtr<CSSCalcExpressionNode> expression, const RenderStyle* style)
+{
+ EXPECT_TRUE(
+ expression->equals(
+ *CSSCalcValue::createExpressionNode(
+ expression->toCalcValue(CSSToLengthConversionData(style, style)).get(),
+ style->effectiveZoom()).get()));
+}
+
TEST(CSSCalculationValue, CreateExpressionNodeFromLength)
{
RefPtr<RenderStyle> style = RenderStyle::create();
@@ -48,7 +58,7 @@ TEST(CSSCalculationValue, CreateExpressionNodeFromLength)
RefPtr<CSSCalcExpressionNode> actual;
expected = CSSCalcValue::createExpressionNode(CSSPrimitiveValue::create(10, CSSPrimitiveValue::CSS_PX), true);
- actual = CSSCalcValue::createExpressionNode(Length(10, WebCore::Fixed), style.get());
+ actual = CSSCalcValue::createExpressionNode(Length(10, WebCore::Fixed), style->effectiveZoom());
EXPECT_TRUE(actual->equals(*expected.get()));
expected = CSSCalcValue::createExpressionNode(
@@ -61,8 +71,8 @@ TEST(CSSCalculationValue, CreateExpressionNodeFromLength)
adoptPtr(new CalcExpressionLength(Length(10, WebCore::Fixed))),
adoptPtr(new CalcExpressionLength(Length(20, WebCore::Fixed))),
CalcAdd)),
- CalculationRangeAll)),
- style.get());
+ ValueRangeAll)),
+ style->effectiveZoom());
EXPECT_TRUE(actual->equals(*expected.get()));
expected = CSSCalcValue::createExpressionNode(
@@ -75,8 +85,8 @@ TEST(CSSCalculationValue, CreateExpressionNodeFromLength)
adoptPtr(new CalcExpressionLength(Length(30, WebCore::Fixed))),
adoptPtr(new CalcExpressionNumber(40)),
CalcMultiply)),
- CalculationRangeAll)),
- style.get());
+ ValueRangeAll)),
+ style->effectiveZoom());
EXPECT_TRUE(actual->equals(*expected.get()));
expected = CSSCalcValue::createExpressionNode(
@@ -92,9 +102,47 @@ TEST(CSSCalculationValue, CreateExpressionNodeFromLength)
actual = CSSCalcValue::createExpressionNode(
Length(CalculationValue::create(
adoptPtr(new CalcExpressionBlendLength(Length(50, WebCore::Fixed), Length(60, WebCore::Fixed), 0.75)),
- CalculationRangeAll)),
- style.get());
+ ValueRangeAll)),
+ style->effectiveZoom());
EXPECT_TRUE(actual->equals(*expected.get()));
}
+TEST(CSSCalculationValue, CreateExpressionNodeFromLengthFromExpressionNode)
+{
+ RefPtr<CSSCalcExpressionNode> expression;
+ RefPtr<RenderStyle> style = RenderStyle::createDefaultStyle();
+ style->setEffectiveZoom(5);
+
+ testExpression(
+ CSSCalcValue::createExpressionNode(CSSPrimitiveValue::create(10, CSSPrimitiveValue::CSS_PX), true),
+ style.get());
+
+ testExpression(
+ CSSCalcValue::createExpressionNode(
+ CSSCalcValue::createExpressionNode(CSSPrimitiveValue::create(10, CSSPrimitiveValue::CSS_PX), true),
+ CSSCalcValue::createExpressionNode(CSSPrimitiveValue::create(20, CSSPrimitiveValue::CSS_PX), true),
+ CalcAdd),
+ style.get());
+
+ testExpression(
+ CSSCalcValue::createExpressionNode(
+ CSSCalcValue::createExpressionNode(CSSPrimitiveValue::create(30, CSSPrimitiveValue::CSS_PX), true),
+ CSSCalcValue::createExpressionNode(CSSPrimitiveValue::create(40, CSSPrimitiveValue::CSS_NUMBER), true),
+ CalcMultiply),
+ style.get());
+
+ testExpression(
+ CSSCalcValue::createExpressionNode(
+ CSSCalcValue::createExpressionNode(
+ CSSCalcValue::createExpressionNode(CSSPrimitiveValue::create(50, CSSPrimitiveValue::CSS_PX), true),
+ CSSCalcValue::createExpressionNode(CSSPrimitiveValue::create(0.25, CSSPrimitiveValue::CSS_NUMBER), false),
+ CalcMultiply),
+ CSSCalcValue::createExpressionNode(
+ CSSCalcValue::createExpressionNode(CSSPrimitiveValue::create(60, CSSPrimitiveValue::CSS_PX), true),
+ CSSCalcValue::createExpressionNode(CSSPrimitiveValue::create(0.75, CSSPrimitiveValue::CSS_NUMBER), false),
+ CalcMultiply),
+ CalcAdd),
+ style.get());
+}
+
}
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSCanvasValue.cpp b/chromium/third_party/WebKit/Source/core/css/CSSCanvasValue.cpp
index ca89a8771b7..ce46f047472 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSCanvasValue.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/CSSCanvasValue.cpp
@@ -37,7 +37,7 @@ CSSCanvasValue::~CSSCanvasValue()
m_element->removeObserver(&m_canvasObserver);
}
-String CSSCanvasValue::customCssText() const
+String CSSCanvasValue::customCSSText() const
{
StringBuilder result;
result.appendLiteral("-webkit-canvas(");
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSCanvasValue.h b/chromium/third_party/WebKit/Source/core/css/CSSCanvasValue.h
index 8283adb124e..bb2325f2b8b 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSCanvasValue.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSCanvasValue.h
@@ -38,7 +38,7 @@ public:
static PassRefPtr<CSSCanvasValue> create(const String& name) { return adoptRef(new CSSCanvasValue(name)); }
~CSSCanvasValue();
- String customCssText() const;
+ String customCSSText() const;
PassRefPtr<Image> image(RenderObject*, const IntSize&);
bool isFixedSize() const { return true; }
@@ -94,6 +94,8 @@ private:
HTMLCanvasElement* m_element;
};
+DEFINE_CSS_VALUE_TYPE_CASTS(CSSCanvasValue, isCanvasValue());
+
} // namespace WebCore
#endif // CSSCanvasValue_h
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSCharsetRule.h b/chromium/third_party/WebKit/Source/core/css/CSSCharsetRule.h
index ac95a4b6485..26ae5fd793f 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSCharsetRule.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSCharsetRule.h
@@ -42,7 +42,7 @@ public:
virtual void reattach(StyleRuleBase* rule) OVERRIDE { ASSERT_UNUSED(rule, !rule); }
const String& encoding() const { return m_encoding; }
- void setEncoding(const String& encoding, ExceptionState&) { m_encoding = encoding; }
+ void setEncoding(const String& encoding) { m_encoding = encoding; }
private:
CSSCharsetRule(CSSStyleSheet* parent, const String& encoding);
@@ -50,6 +50,8 @@ private:
String m_encoding;
};
+DEFINE_CSS_RULE_TYPE_CASTS(CSSCharsetRule, CHARSET_RULE);
+
} // namespace WebCore
#endif // CSSCharsetRule_h
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSCharsetRule.idl b/chromium/third_party/WebKit/Source/core/css/CSSCharsetRule.idl
index a6eab938159..18216075aba 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSCharsetRule.idl
+++ b/chromium/third_party/WebKit/Source/core/css/CSSCharsetRule.idl
@@ -19,6 +19,5 @@
*/
interface CSSCharsetRule : CSSRule {
- [TreatReturnedNullStringAs=Null, TreatNullAs=NullString, SetterRaisesException] attribute DOMString encoding;
+ attribute DOMString encoding;
};
-
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSComputedStyleDeclaration.cpp b/chromium/third_party/WebKit/Source/core/css/CSSComputedStyleDeclaration.cpp
index 37ef5411c12..d5888386226 100644..100755
--- a/chromium/third_party/WebKit/Source/core/css/CSSComputedStyleDeclaration.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/CSSComputedStyleDeclaration.cpp
@@ -29,12 +29,16 @@
#include "RuntimeEnabledFeatures.h"
#include "StylePropertyShorthand.h"
#include "bindings/v8/ExceptionState.h"
+#include "core/animation/DocumentAnimations.h"
#include "core/css/BasicShapeFunctions.h"
#include "core/css/CSSArrayFunctionValue.h"
#include "core/css/CSSAspectRatioValue.h"
#include "core/css/CSSBorderImage.h"
#include "core/css/CSSFilterValue.h"
+#include "core/css/CSSFontFeatureValue.h"
+#include "core/css/CSSFontValue.h"
#include "core/css/CSSFunctionValue.h"
+#include "core/css/CSSGridLineNamesValue.h"
#include "core/css/CSSGridTemplateValue.h"
#include "core/css/CSSLineBoxContainValue.h"
#include "core/css/CSSMixFunctionValue.h"
@@ -43,39 +47,37 @@
#include "core/css/CSSPrimitiveValueMappings.h"
#include "core/css/CSSReflectValue.h"
#include "core/css/CSSSelector.h"
+#include "core/css/CSSShadowValue.h"
#include "core/css/CSSTimingFunctionValue.h"
#include "core/css/CSSTransformValue.h"
#include "core/css/CSSValueList.h"
#include "core/css/CSSValuePool.h"
-#include "core/css/FontFeatureValue.h"
-#include "core/css/FontValue.h"
#include "core/css/Pair.h"
#include "core/css/Rect.h"
-#include "core/css/ShadowValue.h"
+#include "core/css/RuntimeCSSEnabled.h"
#include "core/css/StylePropertySet.h"
#include "core/css/resolver/StyleResolver.h"
#include "core/dom/Document.h"
#include "core/dom/ExceptionCode.h"
#include "core/dom/PseudoElement.h"
-#include "core/page/RuntimeCSSEnabled.h"
-#include "core/page/animation/AnimationController.h"
-#include "core/platform/graphics/FontFeatureSettings.h"
+#include "core/frame/animation/AnimationController.h"
#include "core/rendering/RenderBox.h"
+#include "core/rendering/RenderGrid.h"
#include "core/rendering/RenderView.h"
#include "core/rendering/style/ContentData.h"
#include "core/rendering/style/CounterContent.h"
#include "core/rendering/style/CursorList.h"
#include "core/rendering/style/RenderStyle.h"
+#include "core/rendering/style/ShadowList.h"
#include "core/rendering/style/ShapeValue.h"
-#include "wtf/text/StringBuilder.h"
-
-#include "core/platform/graphics/filters/custom/CustomFilterArrayParameter.h"
-#include "core/platform/graphics/filters/custom/CustomFilterNumberParameter.h"
-#include "core/platform/graphics/filters/custom/CustomFilterOperation.h"
-#include "core/platform/graphics/filters/custom/CustomFilterParameter.h"
-#include "core/platform/graphics/filters/custom/CustomFilterTransformParameter.h"
-
#include "core/rendering/style/StyleCustomFilterProgram.h"
+#include "platform/fonts/FontFeatureSettings.h"
+#include "platform/graphics/filters/custom/CustomFilterArrayParameter.h"
+#include "platform/graphics/filters/custom/CustomFilterNumberParameter.h"
+#include "platform/graphics/filters/custom/CustomFilterOperation.h"
+#include "platform/graphics/filters/custom/CustomFilterParameter.h"
+#include "platform/graphics/filters/custom/CustomFilterTransformParameter.h"
+#include "wtf/text/StringBuilder.h"
namespace WebCore {
@@ -135,6 +137,7 @@ static const CSSPropertyID staticComputableProperties[] = {
CSSPropertyEmptyCells,
CSSPropertyFloat,
CSSPropertyFontFamily,
+ CSSPropertyFontKerning,
CSSPropertyFontSize,
CSSPropertyFontStyle,
CSSPropertyFontVariant,
@@ -188,9 +191,8 @@ static const CSSPropertyID staticComputableProperties[] = {
CSSPropertyTextDecorationLine,
CSSPropertyTextDecorationStyle,
CSSPropertyTextDecorationColor,
-#if ENABLE(CSS3_TEXT)
- CSSPropertyWebkitTextUnderlinePosition,
-#endif // CSS3_TEXT
+ CSSPropertyTextJustify,
+ CSSPropertyTextUnderlinePosition,
CSSPropertyTextIndent,
CSSPropertyTextRendering,
CSSPropertyTextShadow,
@@ -198,6 +200,7 @@ static const CSSPropertyID staticComputableProperties[] = {
CSSPropertyTextTransform,
CSSPropertyTop,
CSSPropertyTouchAction,
+ CSSPropertyTouchActionDelay,
CSSPropertyTransitionDelay,
CSSPropertyTransitionDuration,
CSSPropertyTransitionProperty,
@@ -266,7 +269,6 @@ static const CSSPropertyID staticComputableProperties[] = {
CSSPropertyFlexDirection,
CSSPropertyFlexWrap,
CSSPropertyJustifyContent,
- CSSPropertyWebkitFontKerning,
CSSPropertyWebkitFontSmoothing,
CSSPropertyWebkitFontVariantLigatures,
CSSPropertyGridAutoColumns,
@@ -307,8 +309,11 @@ static const CSSPropertyID staticComputableProperties[] = {
CSSPropertyWebkitPerspectiveOrigin,
CSSPropertyWebkitPrintColorAdjust,
CSSPropertyWebkitRtlOrdering,
- CSSPropertyWebkitShapeInside,
- CSSPropertyWebkitShapeOutside,
+ CSSPropertyShapeInside,
+ CSSPropertyShapeOutside,
+ CSSPropertyShapePadding,
+ CSSPropertyShapeImageThreshold,
+ CSSPropertyShapeMargin,
CSSPropertyWebkitTapHighlightColor,
CSSPropertyWebkitTextCombine,
CSSPropertyWebkitTextDecorationsInEffect,
@@ -339,8 +344,6 @@ static const CSSPropertyID staticComputableProperties[] = {
CSSPropertyWebkitRegionFragment,
CSSPropertyWebkitAppRegion,
CSSPropertyWebkitWrapFlow,
- CSSPropertyWebkitShapeMargin,
- CSSPropertyWebkitShapePadding,
CSSPropertyWebkitWrapThrough,
CSSPropertyBufferedRendering,
CSSPropertyClipPath,
@@ -459,7 +462,7 @@ static PassRefPtr<CSSBorderImageSliceValue> valueForNinePieceImageSlice(const Ni
return CSSBorderImageSliceValue::create(cssValuePool().createValue(quad.release()), image.fill());
}
-static PassRefPtr<CSSPrimitiveValue> valueForNinePieceImageQuad(const LengthBox& box, const RenderStyle* style)
+static PassRefPtr<CSSPrimitiveValue> valueForNinePieceImageQuad(const BorderImageLengthBox& box, const RenderStyle& style)
{
// Create the slices.
RefPtr<CSSPrimitiveValue> top;
@@ -467,37 +470,37 @@ static PassRefPtr<CSSPrimitiveValue> valueForNinePieceImageQuad(const LengthBox&
RefPtr<CSSPrimitiveValue> bottom;
RefPtr<CSSPrimitiveValue> left;
- if (box.top().isRelative())
- top = cssValuePool().createValue(box.top().value(), CSSPrimitiveValue::CSS_NUMBER);
+ if (box.top().isNumber())
+ top = cssValuePool().createValue(box.top().number(), CSSPrimitiveValue::CSS_NUMBER);
else
- top = cssValuePool().createValue(box.top(), style);
+ top = cssValuePool().createValue(box.top().length(), style);
if (box.right() == box.top() && box.bottom() == box.top() && box.left() == box.top()) {
right = top;
bottom = top;
left = top;
} else {
- if (box.right().isRelative())
- right = cssValuePool().createValue(box.right().value(), CSSPrimitiveValue::CSS_NUMBER);
+ if (box.right().isNumber())
+ right = cssValuePool().createValue(box.right().number(), CSSPrimitiveValue::CSS_NUMBER);
else
- right = cssValuePool().createValue(box.right(), style);
+ right = cssValuePool().createValue(box.right().length(), style);
if (box.bottom() == box.top() && box.right() == box.left()) {
bottom = top;
left = right;
} else {
- if (box.bottom().isRelative())
- bottom = cssValuePool().createValue(box.bottom().value(), CSSPrimitiveValue::CSS_NUMBER);
+ if (box.bottom().isNumber())
+ bottom = cssValuePool().createValue(box.bottom().number(), CSSPrimitiveValue::CSS_NUMBER);
else
- bottom = cssValuePool().createValue(box.bottom(), style);
+ bottom = cssValuePool().createValue(box.bottom().length(), style);
if (box.left() == box.right())
left = right;
else {
- if (box.left().isRelative())
- left = cssValuePool().createValue(box.left().value(), CSSPrimitiveValue::CSS_NUMBER);
+ if (box.left().isNumber())
+ left = cssValuePool().createValue(box.left().number(), CSSPrimitiveValue::CSS_NUMBER);
else
- left = cssValuePool().createValue(box.left(), style);
+ left = cssValuePool().createValue(box.left().length(), style);
}
}
}
@@ -524,7 +527,7 @@ static PassRefPtr<CSSValue> valueForNinePieceImageRepeat(const NinePieceImage& i
return cssValuePool().createValue(Pair::create(horizontalRepeat.release(), verticalRepeat.release(), Pair::DropIdenticalValues));
}
-static PassRefPtr<CSSValue> valueForNinePieceImage(const NinePieceImage& image, const RenderStyle* style)
+static PassRefPtr<CSSValue> valueForNinePieceImage(const NinePieceImage& image, const RenderStyle& style)
{
if (!image.hasImage())
return cssValuePool().createIdentifierValue(CSSValueNone);
@@ -549,24 +552,24 @@ static PassRefPtr<CSSValue> valueForNinePieceImage(const NinePieceImage& image,
return createBorderImageValue(imageValue.release(), imageSlices.release(), borderSlices.release(), outset.release(), repeat.release());
}
-inline static PassRefPtr<CSSPrimitiveValue> zoomAdjustedPixelValue(double value, const RenderStyle* style)
+inline static PassRefPtr<CSSPrimitiveValue> zoomAdjustedPixelValue(double value, const RenderStyle& style)
{
return cssValuePool().createValue(adjustFloatForAbsoluteZoom(value, style), CSSPrimitiveValue::CSS_PX);
}
-inline static PassRefPtr<CSSPrimitiveValue> zoomAdjustedNumberValue(double value, const RenderStyle* style)
+inline static PassRefPtr<CSSPrimitiveValue> zoomAdjustedNumberValue(double value, const RenderStyle& style)
{
- return cssValuePool().createValue(value / style->effectiveZoom(), CSSPrimitiveValue::CSS_NUMBER);
+ return cssValuePool().createValue(value / style.effectiveZoom(), CSSPrimitiveValue::CSS_NUMBER);
}
-static PassRefPtr<CSSValue> zoomAdjustedPixelValueForLength(const Length& length, const RenderStyle* style)
+static PassRefPtr<CSSPrimitiveValue> zoomAdjustedPixelValueForLength(const Length& length, const RenderStyle& style)
{
if (length.isFixed())
return zoomAdjustedPixelValue(length.value(), style);
- return cssValuePool().createValue(length);
+ return cssValuePool().createValue(length, style);
}
-static PassRefPtr<CSSValue> valueForReflection(const StyleReflection* reflection, const RenderStyle* style)
+static PassRefPtr<CSSValue> valueForReflection(const StyleReflection* reflection, const RenderStyle& style)
{
if (!reflection)
return cssValuePool().createIdentifierValue(CSSValueNone);
@@ -596,15 +599,15 @@ static PassRefPtr<CSSValue> valueForReflection(const StyleReflection* reflection
return CSSReflectValue::create(direction.release(), offset.release(), valueForNinePieceImage(reflection->mask(), style));
}
-static PassRefPtr<CSSValueList> createPositionListForLayer(CSSPropertyID propertyID, const FillLayer* layer, const RenderStyle* style)
+static PassRefPtr<CSSValueList> createPositionListForLayer(CSSPropertyID propertyID, const FillLayer* layer, const RenderStyle& style)
{
RefPtr<CSSValueList> positionList = CSSValueList::createSpaceSeparated();
- if (layer->isBackgroundOriginSet()) {
+ if (layer->isBackgroundXOriginSet()) {
ASSERT_UNUSED(propertyID, propertyID == CSSPropertyBackgroundPosition || propertyID == CSSPropertyWebkitMaskPosition);
positionList->append(cssValuePool().createValue(layer->backgroundXOrigin()));
}
positionList->append(zoomAdjustedPixelValueForLength(layer->xPosition(), style));
- if (layer->isBackgroundOriginSet()) {
+ if (layer->isBackgroundYOriginSet()) {
ASSERT(propertyID == CSSPropertyBackgroundPosition || propertyID == CSSPropertyWebkitMaskPosition);
positionList->append(cssValuePool().createValue(layer->backgroundYOrigin()));
}
@@ -612,24 +615,21 @@ static PassRefPtr<CSSValueList> createPositionListForLayer(CSSPropertyID propert
return positionList.release();
}
-static PassRefPtr<CSSValue> valueForPositionOffset(RenderStyle* style, CSSPropertyID propertyID, const RenderObject* renderer, RenderView* renderView)
+static PassRefPtr<CSSValue> valueForPositionOffset(RenderStyle& style, CSSPropertyID propertyID, const RenderObject* renderer, RenderView* renderView)
{
- if (!style)
- return 0;
-
Length l;
switch (propertyID) {
case CSSPropertyLeft:
- l = style->left();
+ l = style.left();
break;
case CSSPropertyRight:
- l = style->right();
+ l = style.right();
break;
case CSSPropertyTop:
- l = style->top();
+ l = style.top();
break;
case CSSPropertyBottom:
- l = style->bottom();
+ l = style.bottom();
break;
default:
return 0;
@@ -653,59 +653,52 @@ static PassRefPtr<CSSValue> valueForPositionOffset(RenderStyle* style, CSSProper
return zoomAdjustedPixelValueForLength(l, style);
}
-PassRefPtr<CSSPrimitiveValue> CSSComputedStyleDeclaration::currentColorOrValidColor(RenderStyle* style, const Color& color) const
+PassRefPtr<CSSPrimitiveValue> CSSComputedStyleDeclaration::currentColorOrValidColor(const RenderStyle& style, const Color& color) const
{
// This function does NOT look at visited information, so that computed style doesn't expose that.
if (!color.isValid())
- return cssValuePool().createColorValue(style->color().rgb());
+ return cssValuePool().createColorValue(style.color().rgb());
return cssValuePool().createColorValue(color.rgb());
}
-static PassRefPtr<CSSValueList> valuesForBorderRadiusCorner(LengthSize radius, const RenderStyle* style, RenderObject* renderer, RenderView* renderView)
+static PassRefPtr<CSSValueList> valuesForBorderRadiusCorner(LengthSize radius, const RenderStyle& style)
{
RefPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
- LayoutUnit width = 0;
- LayoutUnit height = 0;
- if (radius.width().isCalculated() || radius.height().isCalculated()) {
- LayoutRect layoutRect = (renderer && renderer->isBox()) ? toRenderBox(renderer)->borderBoxRect() : LayoutRect();
- width = layoutRect.width();
- height = layoutRect.height();
- }
if (radius.width().type() == Percent)
list->append(cssValuePool().createValue(radius.width().percent(), CSSPrimitiveValue::CSS_PERCENTAGE));
else
- list->append(zoomAdjustedPixelValue(valueForLength(radius.width(), width, renderView), style));
+ list->append(zoomAdjustedPixelValueForLength(radius.width(), style));
if (radius.height().type() == Percent)
list->append(cssValuePool().createValue(radius.height().percent(), CSSPrimitiveValue::CSS_PERCENTAGE));
else
- list->append(zoomAdjustedPixelValue(valueForLength(radius.height(), height, renderView), style));
+ list->append(zoomAdjustedPixelValueForLength(radius.height(), style));
return list.release();
}
-static PassRefPtr<CSSValue> valueForBorderRadiusCorner(LengthSize radius, const RenderStyle* style, RenderObject* renderer, RenderView* renderView)
+static PassRefPtr<CSSValue> valueForBorderRadiusCorner(LengthSize radius, const RenderStyle& style)
{
- RefPtr<CSSValueList> list = valuesForBorderRadiusCorner(radius, style, renderer, renderView);
+ RefPtr<CSSValueList> list = valuesForBorderRadiusCorner(radius, style);
if (list->item(0)->equals(*list->item(1)))
return list->item(0);
return list.release();
}
-static PassRefPtr<CSSValueList> valueForBorderRadiusShorthand(const RenderStyle* style, RenderObject* renderer, RenderView* renderView)
+static PassRefPtr<CSSValueList> valueForBorderRadiusShorthand(const RenderStyle& style)
{
RefPtr<CSSValueList> list = CSSValueList::createSlashSeparated();
- bool showHorizontalBottomLeft = style->borderTopRightRadius().width() != style->borderBottomLeftRadius().width();
- bool showHorizontalBottomRight = style->borderBottomRightRadius().width() != style->borderTopLeftRadius().width();
- bool showHorizontalTopRight = style->borderTopRightRadius().width() != style->borderTopLeftRadius().width();
- bool showVerticalBottomLeft = style->borderTopRightRadius().height() != style->borderBottomLeftRadius().height();
- bool showVerticalBottomRight = (style->borderBottomRightRadius().height() != style->borderTopLeftRadius().height()) || showVerticalBottomLeft;
- bool showVerticalTopRight = (style->borderTopRightRadius().height() != style->borderTopLeftRadius().height()) || showVerticalBottomRight;
- bool showVerticalTopLeft = (style->borderTopLeftRadius().width() != style->borderTopLeftRadius().height());
+ bool showHorizontalBottomLeft = style.borderTopRightRadius().width() != style.borderBottomLeftRadius().width();
+ bool showHorizontalBottomRight = showHorizontalBottomLeft || (style.borderBottomRightRadius().width() != style.borderTopLeftRadius().width());
+ bool showHorizontalTopRight = showHorizontalBottomRight || (style.borderTopRightRadius().width() != style.borderTopLeftRadius().width());
- RefPtr<CSSValueList> topLeftRadius = valuesForBorderRadiusCorner(style->borderTopLeftRadius(), style, renderer, renderView);
- RefPtr<CSSValueList> topRightRadius = valuesForBorderRadiusCorner(style->borderTopRightRadius(), style, renderer, renderView);
- RefPtr<CSSValueList> bottomRightRadius = valuesForBorderRadiusCorner(style->borderBottomRightRadius(), style, renderer, renderView);
- RefPtr<CSSValueList> bottomLeftRadius = valuesForBorderRadiusCorner(style->borderBottomLeftRadius(), style, renderer, renderView);
+ bool showVerticalBottomLeft = style.borderTopRightRadius().height() != style.borderBottomLeftRadius().height();
+ bool showVerticalBottomRight = showVerticalBottomLeft || (style.borderBottomRightRadius().height() != style.borderTopLeftRadius().height());
+ bool showVerticalTopRight = showVerticalBottomRight || (style.borderTopRightRadius().height() != style.borderTopLeftRadius().height());
+
+ RefPtr<CSSValueList> topLeftRadius = valuesForBorderRadiusCorner(style.borderTopLeftRadius(), style);
+ RefPtr<CSSValueList> topRightRadius = valuesForBorderRadiusCorner(style.borderTopRightRadius(), style);
+ RefPtr<CSSValueList> bottomRightRadius = valuesForBorderRadiusCorner(style.borderBottomRightRadius(), style);
+ RefPtr<CSSValueList> bottomLeftRadius = valuesForBorderRadiusCorner(style.borderBottomLeftRadius(), style);
RefPtr<CSSValueList> horizontalRadii = CSSValueList::createSpaceSeparated();
horizontalRadii->append(topLeftRadius->item(0));
@@ -718,17 +711,18 @@ static PassRefPtr<CSSValueList> valueForBorderRadiusShorthand(const RenderStyle*
list->append(horizontalRadii.release());
- if (showVerticalTopLeft) {
- RefPtr<CSSValueList> verticalRadii = CSSValueList::createSpaceSeparated();
- verticalRadii->append(topLeftRadius->item(1));
- if (showVerticalTopRight)
- verticalRadii->append(topRightRadius->item(1));
- if (showVerticalBottomRight)
- verticalRadii->append(bottomRightRadius->item(1));
- if (showVerticalBottomLeft)
- verticalRadii->append(bottomLeftRadius->item(1));
+ RefPtr<CSSValueList> verticalRadii = CSSValueList::createSpaceSeparated();
+ verticalRadii->append(topLeftRadius->item(1));
+ if (showVerticalTopRight)
+ verticalRadii->append(topRightRadius->item(1));
+ if (showVerticalBottomRight)
+ verticalRadii->append(bottomRightRadius->item(1));
+ if (showVerticalBottomLeft)
+ verticalRadii->append(bottomLeftRadius->item(1));
+
+ if (!verticalRadii->equals(*toCSSValueList(list->item(0))))
list->append(verticalRadii.release());
- }
+
return list.release();
}
@@ -741,7 +735,7 @@ static LayoutRect sizingBox(RenderObject* renderer)
return box->style()->boxSizing() == BORDER_BOX ? box->borderBoxRect() : box->computedCSSContentBoxRect();
}
-static PassRefPtr<CSSTransformValue> valueForMatrixTransform(const TransformationMatrix& transform, const RenderStyle* style)
+static PassRefPtr<CSSTransformValue> valueForMatrixTransform(const TransformationMatrix& transform, const RenderStyle& style)
{
RefPtr<CSSTransformValue> transformValue;
if (transform.isAffine()) {
@@ -780,9 +774,9 @@ static PassRefPtr<CSSTransformValue> valueForMatrixTransform(const Transformatio
return transformValue.release();
}
-static PassRefPtr<CSSValue> computedTransform(RenderObject* renderer, const RenderStyle* style)
+static PassRefPtr<CSSValue> computedTransform(RenderObject* renderer, const RenderStyle& style)
{
- if (!renderer || !renderer->hasTransform() || !style->hasTransform())
+ if (!renderer || !renderer->hasTransform() || !style.hasTransform())
return cssValuePool().createIdentifierValue(CSSValueNone);
IntRect box;
@@ -790,7 +784,7 @@ static PassRefPtr<CSSValue> computedTransform(RenderObject* renderer, const Rend
box = pixelSnappedIntRect(toRenderBox(renderer)->borderBoxRect());
TransformationMatrix transform;
- style->applyTransform(transform, box.size(), RenderStyle::ExcludeTransformOrigin);
+ style.applyTransform(transform, box.size(), RenderStyle::ExcludeTransformOrigin);
// FIXME: Need to print out individual functions (https://bugs.webkit.org/show_bug.cgi?id=23924)
RefPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
@@ -815,7 +809,7 @@ static PassRefPtr<CSSValue> valueForCustomFilterNumberParameter(const CustomFilt
return numberParameterValue.release();
}
-static PassRefPtr<CSSValue> valueForCustomFilterTransformParameter(const RenderObject* renderer, const RenderStyle* style, const CustomFilterTransformParameter* transformParameter)
+static PassRefPtr<CSSValue> valueForCustomFilterTransformParameter(const RenderObject* renderer, const RenderStyle& style, const CustomFilterTransformParameter* transformParameter)
{
IntSize size;
if (renderer && renderer->isBox())
@@ -827,16 +821,16 @@ static PassRefPtr<CSSValue> valueForCustomFilterTransformParameter(const RenderO
return valueForMatrixTransform(transform, style);
}
-static PassRefPtr<CSSValue> valueForCustomFilterParameter(const RenderObject* renderer, const RenderStyle* style, const CustomFilterParameter* parameter)
+static PassRefPtr<CSSValue> valueForCustomFilterParameter(const RenderObject* renderer, const RenderStyle& style, const CustomFilterParameter* parameter)
{
// FIXME: Add here computed style for the other types: boolean, transform, matrix, texture.
ASSERT(parameter);
switch (parameter->parameterType()) {
- case CustomFilterParameter::ARRAY:
+ case CustomFilterParameter::Array:
return valueForCustomFilterArrayParameter(static_cast<const CustomFilterArrayParameter*>(parameter));
- case CustomFilterParameter::NUMBER:
+ case CustomFilterParameter::Number:
return valueForCustomFilterNumberParameter(static_cast<const CustomFilterNumberParameter*>(parameter));
- case CustomFilterParameter::TRANSFORM:
+ case CustomFilterParameter::Transform:
return valueForCustomFilterTransformParameter(renderer, style, static_cast<const CustomFilterTransformParameter*>(parameter));
}
@@ -844,85 +838,65 @@ static PassRefPtr<CSSValue> valueForCustomFilterParameter(const RenderObject* re
return 0;
}
-PassRefPtr<CSSValue> CSSComputedStyleDeclaration::valueForFilter(const RenderObject* renderer, const RenderStyle* style) const
+PassRefPtr<CSSValue> CSSComputedStyleDeclaration::valueForFilter(const RenderObject* renderer, const RenderStyle& style) const
{
- if (style->filter().operations().isEmpty())
+ if (style.filter().operations().isEmpty())
return cssValuePool().createIdentifierValue(CSSValueNone);
RefPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
RefPtr<CSSFilterValue> filterValue;
- Vector<RefPtr<FilterOperation> >::const_iterator end = style->filter().operations().end();
- for (Vector<RefPtr<FilterOperation> >::const_iterator it = style->filter().operations().begin(); it != end; ++it) {
+ Vector<RefPtr<FilterOperation> >::const_iterator end = style.filter().operations().end();
+ for (Vector<RefPtr<FilterOperation> >::const_iterator it = style.filter().operations().begin(); it != end; ++it) {
FilterOperation* filterOperation = (*it).get();
- switch (filterOperation->getOperationType()) {
- case FilterOperation::REFERENCE: {
- ReferenceFilterOperation* referenceOperation = static_cast<ReferenceFilterOperation*>(filterOperation);
+ switch (filterOperation->type()) {
+ case FilterOperation::REFERENCE:
filterValue = CSSFilterValue::create(CSSFilterValue::ReferenceFilterOperation);
- filterValue->append(cssValuePool().createValue(referenceOperation->url(), CSSPrimitiveValue::CSS_STRING));
+ filterValue->append(cssValuePool().createValue(toReferenceFilterOperation(filterOperation)->url(), CSSPrimitiveValue::CSS_STRING));
break;
- }
- case FilterOperation::GRAYSCALE: {
- BasicColorMatrixFilterOperation* colorMatrixOperation = static_cast<BasicColorMatrixFilterOperation*>(filterOperation);
+ case FilterOperation::GRAYSCALE:
filterValue = CSSFilterValue::create(CSSFilterValue::GrayscaleFilterOperation);
- filterValue->append(cssValuePool().createValue(colorMatrixOperation->amount(), CSSPrimitiveValue::CSS_NUMBER));
+ filterValue->append(cssValuePool().createValue(toBasicColorMatrixFilterOperation(filterOperation)->amount(), CSSPrimitiveValue::CSS_NUMBER));
break;
- }
- case FilterOperation::SEPIA: {
- BasicColorMatrixFilterOperation* colorMatrixOperation = static_cast<BasicColorMatrixFilterOperation*>(filterOperation);
+ case FilterOperation::SEPIA:
filterValue = CSSFilterValue::create(CSSFilterValue::SepiaFilterOperation);
- filterValue->append(cssValuePool().createValue(colorMatrixOperation->amount(), CSSPrimitiveValue::CSS_NUMBER));
+ filterValue->append(cssValuePool().createValue(toBasicColorMatrixFilterOperation(filterOperation)->amount(), CSSPrimitiveValue::CSS_NUMBER));
break;
- }
- case FilterOperation::SATURATE: {
- BasicColorMatrixFilterOperation* colorMatrixOperation = static_cast<BasicColorMatrixFilterOperation*>(filterOperation);
+ case FilterOperation::SATURATE:
filterValue = CSSFilterValue::create(CSSFilterValue::SaturateFilterOperation);
- filterValue->append(cssValuePool().createValue(colorMatrixOperation->amount(), CSSPrimitiveValue::CSS_NUMBER));
+ filterValue->append(cssValuePool().createValue(toBasicColorMatrixFilterOperation(filterOperation)->amount(), CSSPrimitiveValue::CSS_NUMBER));
break;
- }
- case FilterOperation::HUE_ROTATE: {
- BasicColorMatrixFilterOperation* colorMatrixOperation = static_cast<BasicColorMatrixFilterOperation*>(filterOperation);
+ case FilterOperation::HUE_ROTATE:
filterValue = CSSFilterValue::create(CSSFilterValue::HueRotateFilterOperation);
- filterValue->append(cssValuePool().createValue(colorMatrixOperation->amount(), CSSPrimitiveValue::CSS_DEG));
+ filterValue->append(cssValuePool().createValue(toBasicColorMatrixFilterOperation(filterOperation)->amount(), CSSPrimitiveValue::CSS_DEG));
break;
- }
- case FilterOperation::INVERT: {
- BasicComponentTransferFilterOperation* componentTransferOperation = static_cast<BasicComponentTransferFilterOperation*>(filterOperation);
+ case FilterOperation::INVERT:
filterValue = CSSFilterValue::create(CSSFilterValue::InvertFilterOperation);
- filterValue->append(cssValuePool().createValue(componentTransferOperation->amount(), CSSPrimitiveValue::CSS_NUMBER));
+ filterValue->append(cssValuePool().createValue(toBasicComponentTransferFilterOperation(filterOperation)->amount(), CSSPrimitiveValue::CSS_NUMBER));
break;
- }
- case FilterOperation::OPACITY: {
- BasicComponentTransferFilterOperation* componentTransferOperation = static_cast<BasicComponentTransferFilterOperation*>(filterOperation);
+ case FilterOperation::OPACITY:
filterValue = CSSFilterValue::create(CSSFilterValue::OpacityFilterOperation);
- filterValue->append(cssValuePool().createValue(componentTransferOperation->amount(), CSSPrimitiveValue::CSS_NUMBER));
+ filterValue->append(cssValuePool().createValue(toBasicComponentTransferFilterOperation(filterOperation)->amount(), CSSPrimitiveValue::CSS_NUMBER));
break;
- }
- case FilterOperation::BRIGHTNESS: {
- BasicComponentTransferFilterOperation* brightnessOperation = static_cast<BasicComponentTransferFilterOperation*>(filterOperation);
+ case FilterOperation::BRIGHTNESS:
filterValue = CSSFilterValue::create(CSSFilterValue::BrightnessFilterOperation);
- filterValue->append(cssValuePool().createValue(brightnessOperation->amount(), CSSPrimitiveValue::CSS_NUMBER));
+ filterValue->append(cssValuePool().createValue(toBasicComponentTransferFilterOperation(filterOperation)->amount(), CSSPrimitiveValue::CSS_NUMBER));
break;
- }
- case FilterOperation::CONTRAST: {
- BasicComponentTransferFilterOperation* contrastOperation = static_cast<BasicComponentTransferFilterOperation*>(filterOperation);
+ case FilterOperation::CONTRAST:
filterValue = CSSFilterValue::create(CSSFilterValue::ContrastFilterOperation);
- filterValue->append(cssValuePool().createValue(contrastOperation->amount(), CSSPrimitiveValue::CSS_NUMBER));
+ filterValue->append(cssValuePool().createValue(toBasicComponentTransferFilterOperation(filterOperation)->amount(), CSSPrimitiveValue::CSS_NUMBER));
break;
- }
- case FilterOperation::BLUR: {
- BlurFilterOperation* blurOperation = static_cast<BlurFilterOperation*>(filterOperation);
+ case FilterOperation::BLUR:
filterValue = CSSFilterValue::create(CSSFilterValue::BlurFilterOperation);
- filterValue->append(zoomAdjustedPixelValue(blurOperation->stdDeviation().value(), style));
+ filterValue->append(zoomAdjustedPixelValue(toBlurFilterOperation(filterOperation)->stdDeviation().value(), style));
break;
- }
case FilterOperation::DROP_SHADOW: {
- DropShadowFilterOperation* dropShadowOperation = static_cast<DropShadowFilterOperation*>(filterOperation);
+ DropShadowFilterOperation* dropShadowOperation = toDropShadowFilterOperation(filterOperation);
filterValue = CSSFilterValue::create(CSSFilterValue::DropShadowFilterOperation);
// We want our computed style to look like that of a text shadow (has neither spread nor inset style).
- OwnPtr<ShadowData> shadow = ShadowData::create(dropShadowOperation->location(), dropShadowOperation->stdDeviation(), 0, Normal, dropShadowOperation->color());
- filterValue->append(valueForShadow(shadow.get(), CSSPropertyTextShadow, style));
+ ShadowData shadow(dropShadowOperation->location(), dropShadowOperation->stdDeviation(), 0, Normal, dropShadowOperation->color());
+ filterValue->append(valueForShadowData(shadow, style, false));
break;
}
case FilterOperation::VALIDATED_CUSTOM:
@@ -930,7 +904,7 @@ PassRefPtr<CSSValue> CSSComputedStyleDeclaration::valueForFilter(const RenderObj
ASSERT_NOT_REACHED();
break;
case FilterOperation::CUSTOM: {
- CustomFilterOperation* customOperation = static_cast<CustomFilterOperation*>(filterOperation);
+ CustomFilterOperation* customOperation = toCustomFilterOperation(filterOperation);
filterValue = CSSFilterValue::create(CSSFilterValue::CustomFilterOperation);
// The output should be verbose, even if the values are the default ones.
@@ -946,7 +920,7 @@ PassRefPtr<CSSValue> CSSComputedStyleDeclaration::valueForFilter(const RenderObj
const CustomFilterProgramMixSettings mixSettings = program->mixSettings();
if (program->fragmentShader()) {
- if (program->programType() == PROGRAM_TYPE_BLENDS_ELEMENT_TEXTURE) {
+ if (program->programType() == ProgramTypeBlendsElementTexture) {
RefPtr<CSSMixFunctionValue> mixFunction = CSSMixFunctionValue::create();
mixFunction->append(program->fragmentShader()->cssValue());
mixFunction->append(cssValuePool().createValue(mixSettings.blendMode));
@@ -997,7 +971,7 @@ PassRefPtr<CSSValue> CSSComputedStyleDeclaration::valueForFilter(const RenderObj
return list.release();
}
-static PassRefPtr<CSSValue> valueForGridTrackBreadth(const GridLength& trackBreadth, const RenderStyle* style, RenderView* renderView)
+static PassRefPtr<CSSValue> specifiedValueForGridTrackBreadth(const GridLength& trackBreadth, const RenderStyle& style, RenderView* renderView)
{
if (!trackBreadth.isLength())
return cssValuePool().createValue(trackBreadth.flex(), CSSPrimitiveValue::CSS_FR);
@@ -1010,15 +984,15 @@ static PassRefPtr<CSSValue> valueForGridTrackBreadth(const GridLength& trackBrea
return zoomAdjustedPixelValueForLength(trackBreadthLength, style);
}
-static PassRefPtr<CSSValue> valueForGridTrackSize(const GridTrackSize& trackSize, const RenderStyle* style, RenderView* renderView)
+static PassRefPtr<CSSValue> specifiedValueForGridTrackSize(const GridTrackSize& trackSize, const RenderStyle& style, RenderView* renderView)
{
switch (trackSize.type()) {
case LengthTrackSizing:
- return valueForGridTrackBreadth(trackSize.length(), style, renderView);
+ return specifiedValueForGridTrackBreadth(trackSize.length(), style, renderView);
case MinMaxTrackSizing:
RefPtr<CSSValueList> minMaxTrackBreadths = CSSValueList::createCommaSeparated();
- minMaxTrackBreadths->append(valueForGridTrackBreadth(trackSize.minTrackBreadth(), style, renderView));
- minMaxTrackBreadths->append(valueForGridTrackBreadth(trackSize.maxTrackBreadth(), style, renderView));
+ minMaxTrackBreadths->append(specifiedValueForGridTrackBreadth(trackSize.minTrackBreadth(), style, renderView));
+ minMaxTrackBreadths->append(specifiedValueForGridTrackBreadth(trackSize.maxTrackBreadth(), style, renderView));
return CSSFunctionValue::create("minmax(", minMaxTrackBreadths);
}
ASSERT_NOT_REACHED();
@@ -1028,12 +1002,20 @@ static PassRefPtr<CSSValue> valueForGridTrackSize(const GridTrackSize& trackSize
static void addValuesForNamedGridLinesAtIndex(const OrderedNamedGridLines& orderedNamedGridLines, size_t i, CSSValueList& list)
{
const Vector<String>& namedGridLines = orderedNamedGridLines.get(i);
+ if (namedGridLines.isEmpty())
+ return;
+
+ RefPtr<CSSGridLineNamesValue> lineNames = CSSGridLineNamesValue::create();
for (size_t j = 0; j < namedGridLines.size(); ++j)
- list.append(cssValuePool().createValue(namedGridLines[j], CSSPrimitiveValue::CSS_STRING));
+ lineNames->append(cssValuePool().createValue(namedGridLines[j], CSSPrimitiveValue::CSS_STRING));
+ list.append(lineNames.release());
}
-static PassRefPtr<CSSValue> valueForGridTrackList(const Vector<GridTrackSize>& trackSizes, const OrderedNamedGridLines& orderedNamedGridLines, const RenderStyle* style, RenderView* renderView)
+static PassRefPtr<CSSValue> valueForGridTrackList(GridTrackSizingDirection direction, RenderObject* renderer, const RenderStyle& style, RenderView* renderView)
{
+ const Vector<GridTrackSize>& trackSizes = direction == ForColumns ? style.gridDefinitionColumns() : style.gridDefinitionRows();
+ const OrderedNamedGridLines& orderedNamedGridLines = direction == ForColumns ? style.orderedNamedGridColumnLines() : style.orderedNamedGridRowLines();
+
// Handle the 'none' case here.
if (!trackSizes.size()) {
ASSERT(orderedNamedGridLines.isEmpty());
@@ -1041,9 +1023,21 @@ static PassRefPtr<CSSValue> valueForGridTrackList(const Vector<GridTrackSize>& t
}
RefPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
- for (size_t i = 0; i < trackSizes.size(); ++i) {
- addValuesForNamedGridLinesAtIndex(orderedNamedGridLines, i, *list);
- list->append(valueForGridTrackSize(trackSizes[i], style, renderView));
+ if (renderer && renderer->isRenderGrid()) {
+ const Vector<LayoutUnit>& trackPositions = direction == ForColumns ? toRenderGrid(renderer)->columnPositions() : toRenderGrid(renderer)->rowPositions();
+ // There are at least #tracks + 1 grid lines (trackPositions). Apart from that, the grid container can generate implicit grid tracks,
+ // so we'll have more trackPositions than trackSizes as the latter only contain the explicit grid.
+ ASSERT(trackPositions.size() - 1 >= trackSizes.size());
+
+ for (size_t i = 0; i < trackSizes.size(); ++i) {
+ addValuesForNamedGridLinesAtIndex(orderedNamedGridLines, i, *list);
+ list->append(zoomAdjustedPixelValue(trackPositions[i + 1] - trackPositions[i], style));
+ }
+ } else {
+ for (size_t i = 0; i < trackSizes.size(); ++i) {
+ addValuesForNamedGridLinesAtIndex(orderedNamedGridLines, i, *list);
+ list->append(specifiedValueForGridTrackSize(trackSizes[i], style, renderView));
+ }
}
// Those are the trailing <string>* allowed in the syntax.
addValuesForNamedGridLinesAtIndex(orderedNamedGridLines, trackSizes.size(), *list);
@@ -1122,7 +1116,7 @@ static PassRefPtr<CSSValue> createTimingFunctionValue(const TimingFunction* timi
switch (timingFunction->type()) {
case TimingFunction::CubicBezierFunction:
{
- const CubicBezierTimingFunction* bezierTimingFunction = static_cast<const CubicBezierTimingFunction*>(timingFunction);
+ const CubicBezierTimingFunction* bezierTimingFunction = toCubicBezierTimingFunction(timingFunction);
if (bezierTimingFunction->subType() != CubicBezierTimingFunction::Custom) {
CSSValueID valueId = CSSValueInvalid;
switch (bezierTimingFunction->subType()) {
@@ -1149,7 +1143,7 @@ static PassRefPtr<CSSValue> createTimingFunctionValue(const TimingFunction* timi
case TimingFunction::StepsFunction:
{
- const StepsTimingFunction* stepsTimingFunction = static_cast<const StepsTimingFunction*>(timingFunction);
+ const StepsTimingFunction* stepsTimingFunction = toStepsTimingFunction(timingFunction);
if (stepsTimingFunction->subType() == StepsTimingFunction::Custom)
return CSSStepsTimingFunctionValue::create(stepsTimingFunction->numberOfSteps(), stepsTimingFunction->stepAtStart());
CSSValueID valueId;
@@ -1268,9 +1262,9 @@ String CSSComputedStyleDeclaration::cssText() const
return result.toString();
}
-void CSSComputedStyleDeclaration::setCssText(const String&, ExceptionState& es)
+void CSSComputedStyleDeclaration::setCSSText(const String&, ExceptionState& exceptionState)
{
- es.throwDOMException(NoModificationAllowedError, "Failed to set the 'cssText' property on a computed 'CSSStyleDeclaration': computed styles are read-only.");
+ exceptionState.throwDOMException(NoModificationAllowedError, "These styles are computed, and therefore read-only.");
}
static CSSValueID cssIdentifierForFontSizeKeyword(int keywordSize)
@@ -1295,7 +1289,7 @@ PassRefPtr<CSSValue> CSSComputedStyleDeclaration::getFontSizeCSSValuePreferringK
return cssValuePool().createIdentifierValue(cssIdentifierForFontSizeKeyword(keywordSize));
- return zoomAdjustedPixelValue(style->fontDescription().computedPixelSize(), style.get());
+ return zoomAdjustedPixelValue(style->fontDescription().computedPixelSize(), *style);
}
bool CSSComputedStyleDeclaration::useFixedFontDefaultSize() const
@@ -1310,21 +1304,26 @@ bool CSSComputedStyleDeclaration::useFixedFontDefaultSize() const
return style->fontDescription().useFixedDefaultSize();
}
-PassRefPtr<CSSValue> CSSComputedStyleDeclaration::valueForShadow(const ShadowData* shadow, CSSPropertyID propertyID, const RenderStyle* style) const
+PassRefPtr<CSSValue> CSSComputedStyleDeclaration::valueForShadowData(const ShadowData& shadow, const RenderStyle& style, bool useSpread) const
{
- if (!shadow)
+ RefPtr<CSSPrimitiveValue> x = zoomAdjustedPixelValue(shadow.x(), style);
+ RefPtr<CSSPrimitiveValue> y = zoomAdjustedPixelValue(shadow.y(), style);
+ RefPtr<CSSPrimitiveValue> blur = zoomAdjustedPixelValue(shadow.blur(), style);
+ RefPtr<CSSPrimitiveValue> spread = useSpread ? zoomAdjustedPixelValue(shadow.spread(), style) : PassRefPtr<CSSPrimitiveValue>();
+ RefPtr<CSSPrimitiveValue> shadowStyle = shadow.style() == Normal ? PassRefPtr<CSSPrimitiveValue>() : cssValuePool().createIdentifierValue(CSSValueInset);
+ RefPtr<CSSPrimitiveValue> color = currentColorOrValidColor(style, shadow.color());
+ return CSSShadowValue::create(x.release(), y.release(), blur.release(), spread.release(), shadowStyle.release(), color.release());
+}
+
+PassRefPtr<CSSValue> CSSComputedStyleDeclaration::valueForShadowList(const ShadowList* shadowList, const RenderStyle& style, bool useSpread) const
+{
+ if (!shadowList)
return cssValuePool().createIdentifierValue(CSSValueNone);
RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
- for (const ShadowData* s = shadow; s; s = s->next()) {
- RefPtr<CSSPrimitiveValue> x = zoomAdjustedPixelValue(s->x(), style);
- RefPtr<CSSPrimitiveValue> y = zoomAdjustedPixelValue(s->y(), style);
- RefPtr<CSSPrimitiveValue> blur = zoomAdjustedPixelValue(s->blur(), style);
- RefPtr<CSSPrimitiveValue> spread = propertyID == CSSPropertyTextShadow ? PassRefPtr<CSSPrimitiveValue>() : zoomAdjustedPixelValue(s->spread(), style);
- RefPtr<CSSPrimitiveValue> style = propertyID == CSSPropertyTextShadow || s->style() == Normal ? PassRefPtr<CSSPrimitiveValue>() : cssValuePool().createIdentifierValue(CSSValueInset);
- RefPtr<CSSPrimitiveValue> color = cssValuePool().createColorValue(s->color().rgb());
- list->prepend(ShadowValue::create(x.release(), y.release(), blur.release(), spread.release(), style.release(), color.release()));
- }
+ size_t shadowCount = shadowList->shadows().size();
+ for (size_t i = 0; i < shadowCount; ++i)
+ list->append(valueForShadowData(shadowList->shadows()[i], style, useSpread));
return list.release();
}
@@ -1335,17 +1334,17 @@ PassRefPtr<CSSValue> CSSComputedStyleDeclaration::getPropertyCSSValue(CSSPropert
static CSSValueID identifierForFamily(const AtomicString& family)
{
- if (family == cursiveFamily)
+ if (family == FontFamilyNames::webkit_cursive)
return CSSValueCursive;
- if (family == fantasyFamily)
+ if (family == FontFamilyNames::webkit_fantasy)
return CSSValueFantasy;
- if (family == monospaceFamily)
+ if (family == FontFamilyNames::webkit_monospace)
return CSSValueMonospace;
- if (family == pictographFamily)
+ if (family == FontFamilyNames::webkit_pictograph)
return CSSValueWebkitPictograph;
- if (family == sansSerifFamily)
+ if (family == FontFamilyNames::webkit_sans_serif)
return CSSValueSansSerif;
- if (family == serifFamily)
+ if (family == FontFamilyNames::webkit_serif)
return CSSValueSerif;
return CSSValueInvalid;
}
@@ -1423,7 +1422,7 @@ static PassRefPtr<CSSValue> valueForFillSourceType(EMaskSourceType type)
return 0;
}
-static PassRefPtr<CSSValue> valueForFillSize(const FillSize& fillSize, const RenderStyle* style)
+static PassRefPtr<CSSValue> valueForFillSize(const FillSize& fillSize, const RenderStyle& style)
{
if (fillSize.type == Contain)
return cssValuePool().createIdentifierValue(CSSValueContain);
@@ -1440,10 +1439,10 @@ static PassRefPtr<CSSValue> valueForFillSize(const FillSize& fillSize, const Ren
return list.release();
}
-static PassRefPtr<CSSValue> valueForContentData(const RenderStyle* style)
+static PassRefPtr<CSSValue> valueForContentData(const RenderStyle& style)
{
RefPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
- for (const ContentData* contentData = style->contentData(); contentData; contentData = contentData->next()) {
+ for (const ContentData* contentData = style.contentData(); contentData; contentData = contentData->next()) {
if (contentData->isCounter()) {
const CounterContent* counter = static_cast<const CounterContentData*>(contentData)->counter();
ASSERT(counter);
@@ -1455,14 +1454,14 @@ static PassRefPtr<CSSValue> valueForContentData(const RenderStyle* style)
} else if (contentData->isText())
list->append(cssValuePool().createValue(static_cast<const TextContentData*>(contentData)->text(), CSSPrimitiveValue::CSS_STRING));
}
- if (!style->regionThread().isNull())
- list->append(cssValuePool().createValue(style->regionThread(), CSSPrimitiveValue::CSS_STRING));
+ if (style.hasFlowFrom())
+ list->append(cssValuePool().createValue(style.regionThread(), CSSPrimitiveValue::CSS_STRING));
return list.release();
}
-static PassRefPtr<CSSValue> valueForCounterDirectives(const RenderStyle* style, CSSPropertyID propertyID)
+static PassRefPtr<CSSValue> valueForCounterDirectives(const RenderStyle& style, CSSPropertyID propertyID)
{
- const CounterDirectiveMap* map = style->counterDirectives();
+ const CounterDirectiveMap* map = style.counterDirectives();
if (!map)
return 0;
@@ -1481,54 +1480,49 @@ static void logUnimplementedPropertyID(CSSPropertyID propertyID)
if (!propertyIDSet.add(propertyID).isNewEntry)
return;
- LOG_ERROR("WebKit does not yet implement getComputedStyle for '%s'.", getPropertyName(propertyID));
+ WTF_LOG_ERROR("WebKit does not yet implement getComputedStyle for '%s'.", getPropertyName(propertyID));
}
-static PassRefPtr<CSSValueList> valueForFontFamily(RenderStyle* style)
+static PassRefPtr<CSSValueList> valueForFontFamily(RenderStyle& style)
{
- const FontFamily& firstFamily = style->fontDescription().family();
+ const FontFamily& firstFamily = style.fontDescription().family();
RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
for (const FontFamily* family = &firstFamily; family; family = family->next())
list->append(valueForFamily(family->family()));
return list.release();
}
-static PassRefPtr<CSSPrimitiveValue> valueForLineHeight(RenderStyle* style, RenderView* renderView)
+static PassRefPtr<CSSPrimitiveValue> valueForLineHeight(RenderStyle& style, RenderView* renderView)
{
- Length length = style->lineHeight();
+ Length length = style.lineHeight();
if (length.isNegative())
return cssValuePool().createIdentifierValue(CSSValueNormal);
- if (length.isPercent())
- // This is imperfect, because it doesn't include the zoom factor and the real computation
- // for how high to be in pixels does include things like minimum font size and the zoom factor.
- // On the other hand, since font-size doesn't include the zoom factor, we really can't do
- // that here either.
- return zoomAdjustedPixelValue(static_cast<int>(length.percent() * style->fontDescription().specifiedSize()) / 100, style);
- return zoomAdjustedPixelValue(valueForLength(length, 0, renderView), style);
+
+ return zoomAdjustedPixelValue(floatValueForLength(length, style.fontDescription().specifiedSize(), renderView), style);
}
-static PassRefPtr<CSSPrimitiveValue> valueForFontSize(RenderStyle* style)
+static PassRefPtr<CSSPrimitiveValue> valueForFontSize(RenderStyle& style)
{
- return zoomAdjustedPixelValue(style->fontDescription().computedPixelSize(), style);
+ return zoomAdjustedPixelValue(style.fontDescription().computedPixelSize(), style);
}
-static PassRefPtr<CSSPrimitiveValue> valueForFontStyle(RenderStyle* style)
+static PassRefPtr<CSSPrimitiveValue> valueForFontStyle(RenderStyle& style)
{
- if (style->fontDescription().italic())
+ if (style.fontDescription().italic())
return cssValuePool().createIdentifierValue(CSSValueItalic);
return cssValuePool().createIdentifierValue(CSSValueNormal);
}
-static PassRefPtr<CSSPrimitiveValue> valueForFontVariant(RenderStyle* style)
+static PassRefPtr<CSSPrimitiveValue> valueForFontVariant(RenderStyle& style)
{
- if (style->fontDescription().smallCaps())
+ if (style.fontDescription().smallCaps())
return cssValuePool().createIdentifierValue(CSSValueSmallCaps);
return cssValuePool().createIdentifierValue(CSSValueNormal);
}
-static PassRefPtr<CSSPrimitiveValue> valueForFontWeight(RenderStyle* style)
+static PassRefPtr<CSSPrimitiveValue> valueForFontWeight(RenderStyle& style)
{
- switch (style->fontDescription().weight()) {
+ switch (style.fontDescription().weight()) {
case FontWeight100:
return cssValuePool().createIdentifierValue(CSSValue100);
case FontWeight200:
@@ -1552,6 +1546,24 @@ static PassRefPtr<CSSPrimitiveValue> valueForFontWeight(RenderStyle* style)
return cssValuePool().createIdentifierValue(CSSValueNormal);
}
+static PassRefPtr<CSSValue> touchActionFlagsToCSSValue(TouchAction touchAction)
+{
+ RefPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+ if (touchAction == TouchActionAuto)
+ list->append(cssValuePool().createIdentifierValue(CSSValueAuto));
+ if (touchAction & TouchActionNone) {
+ ASSERT(touchAction == TouchActionNone);
+ list->append(cssValuePool().createIdentifierValue(CSSValueNone));
+ }
+ if (touchAction & TouchActionPanX)
+ list->append(cssValuePool().createIdentifierValue(CSSValuePanX));
+ if (touchAction & TouchActionPanY)
+ list->append(cssValuePool().createIdentifierValue(CSSValuePanY));
+
+ ASSERT(list->length());
+ return list.release();
+}
+
static bool isLayoutDependent(CSSPropertyID propertyID, PassRefPtr<RenderStyle> style, RenderObject* renderer)
{
// Some properties only depend on layout in certain conditions which
@@ -1561,6 +1573,8 @@ static bool isLayoutDependent(CSSPropertyID propertyID, PassRefPtr<RenderStyle>
// FIXME: Some of these cases could be narrowed down or optimized better.
switch (propertyID) {
case CSSPropertyBottom:
+ case CSSPropertyGridDefinitionColumns:
+ case CSSPropertyGridDefinitionRows:
case CSSPropertyHeight:
case CSSPropertyLeft:
case CSSPropertyRight:
@@ -1571,19 +1585,6 @@ static bool isLayoutDependent(CSSPropertyID propertyID, PassRefPtr<RenderStyle>
case CSSPropertyWidth:
case CSSPropertyWebkitFilter:
return true;
- case CSSPropertyBorderBottomLeftRadius:
- return renderer && (style->borderBottomLeftRadius().width().isCalculated() || style->borderBottomLeftRadius().height().isCalculated());
- case CSSPropertyBorderBottomRightRadius:
- return renderer && (style->borderBottomRightRadius().width().isCalculated() || style->borderBottomRightRadius().height().isCalculated());
- case CSSPropertyBorderRadius:
- return isLayoutDependent(CSSPropertyBorderBottomLeftRadius, style.get(), renderer)
- || isLayoutDependent(CSSPropertyBorderBottomRightRadius, style.get(), renderer)
- || isLayoutDependent(CSSPropertyBorderTopLeftRadius, style.get(), renderer)
- || isLayoutDependent(CSSPropertyBorderTopRightRadius, style, renderer);
- case CSSPropertyBorderTopLeftRadius:
- return renderer && (style->borderTopLeftRadius().width().isCalculated() || style->borderTopLeftRadius().height().isCalculated());
- case CSSPropertyBorderTopRightRadius:
- return renderer && (style->borderTopRightRadius().width().isCalculated() || style->borderTopRightRadius().height().isCalculated());
case CSSPropertyMargin:
return renderer && renderer->isBox() && (!style || !style->marginBottom().isFixed() || !style->marginTop().isFixed() || !style->marginLeft().isFixed() || !style->marginRight().isFixed());
case CSSPropertyMarginLeft:
@@ -1614,13 +1615,14 @@ PassRefPtr<RenderStyle> CSSComputedStyleDeclaration::computeRenderStyle(CSSPrope
Node* styledNode = this->styledNode();
ASSERT(styledNode);
RenderObject* renderer = styledNode->renderer();
- if (renderer && renderer->isComposited() && !RuntimeEnabledFeatures::webAnimationsCSSEnabled() && AnimationController::supportsAcceleratedAnimationOfProperty(propertyID)) {
+ if (renderer && renderer->compositingState() == PaintsIntoOwnBacking
+ && !RuntimeEnabledFeatures::webAnimationsCSSEnabled() && AnimationController::supportsAcceleratedAnimationOfProperty(propertyID)) {
AnimationUpdateBlock animationUpdateBlock(renderer->animation());
if (m_pseudoElementSpecifier && !styledNode->isPseudoElement()) {
// FIXME: This cached pseudo style will only exist if the animation has been run at least once.
- return renderer->animation()->getAnimatedStyleForRenderer(renderer)->getCachedPseudoStyle(m_pseudoElementSpecifier);
+ return renderer->animation().getAnimatedStyleForRenderer(renderer)->getCachedPseudoStyle(m_pseudoElementSpecifier);
}
- return renderer->animation()->getAnimatedStyleForRenderer(renderer);
+ return renderer->animation().getAnimatedStyleForRenderer(renderer);
}
return styledNode->computedStyle(styledNode->isPseudoElement() ? NOPSEUDO : m_pseudoElementSpecifier);
}
@@ -1630,7 +1632,7 @@ Node* CSSComputedStyleDeclaration::styledNode() const
if (!m_node)
return 0;
if (m_node->isElementNode()) {
- if (PseudoElement* element = toElement(m_node.get())->pseudoElement(m_pseudoElementSpecifier))
+ if (PseudoElement* element = toElement(m_node)->pseudoElement(m_pseudoElementSpecifier))
return element;
}
return m_node.get();
@@ -1647,6 +1649,10 @@ PassRefPtr<CSSValue> CSSComputedStyleDeclaration::getPropertyCSSValue(CSSPropert
if (updateLayout) {
Document& document = styledNode->document();
+ // If a compositor animation is running we may need to service animations
+ // in order to generate an up to date value.
+ DocumentAnimations::serviceBeforeGetComputedStyle(*styledNode, propertyID);
+
document.updateStyleForNodeIfNeeded(styledNode);
// The style recalc could have caused the styled node to be discarded or replaced
@@ -1658,7 +1664,7 @@ PassRefPtr<CSSValue> CSSComputedStyleDeclaration::getPropertyCSSValue(CSSPropert
bool forceFullLayout = isLayoutDependent(propertyID, style, renderer)
|| styledNode->isInShadowTree()
- || (document.styleResolverIfExists() && document.styleResolverIfExists()->hasViewportDependentMediaQueries() && document.ownerElement())
+ || (document.ownerElement() && document.ensureStyleResolver().hasViewportDependentMediaQueries())
|| document.seamlessParentIFrame();
if (forceFullLayout) {
@@ -1710,11 +1716,11 @@ PassRefPtr<CSSValue> CSSComputedStyleDeclaration::getPropertyCSSValue(CSSPropert
case CSSPropertyWebkitMaskSize: {
const FillLayer* layers = propertyID == CSSPropertyWebkitMaskSize ? style->maskLayers() : style->backgroundLayers();
if (!layers->next())
- return valueForFillSize(layers->size(), style.get());
+ return valueForFillSize(layers->size(), *style);
RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
for (const FillLayer* currLayer = layers; currLayer; currLayer = currLayer->next())
- list->append(valueForFillSize(currLayer->size(), style.get()));
+ list->append(valueForFillSize(currLayer->size(), *style));
return list.release();
}
@@ -1793,11 +1799,11 @@ PassRefPtr<CSSValue> CSSComputedStyleDeclaration::getPropertyCSSValue(CSSPropert
case CSSPropertyWebkitMaskPosition: {
const FillLayer* layers = propertyID == CSSPropertyWebkitMaskPosition ? style->maskLayers() : style->backgroundLayers();
if (!layers->next())
- return createPositionListForLayer(propertyID, layers, style.get());
+ return createPositionListForLayer(propertyID, layers, *style);
RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
for (const FillLayer* currLayer = layers; currLayer; currLayer = currLayer->next())
- list->append(createPositionListForLayer(propertyID, currLayer, style.get()));
+ list->append(createPositionListForLayer(propertyID, currLayer, *style));
return list.release();
}
case CSSPropertyBackgroundPositionX:
@@ -1830,26 +1836,26 @@ PassRefPtr<CSSValue> CSSComputedStyleDeclaration::getPropertyCSSValue(CSSPropert
return cssValuePool().createIdentifierValue(CSSValueSeparate);
case CSSPropertyBorderSpacing: {
RefPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
- list->append(zoomAdjustedPixelValue(style->horizontalBorderSpacing(), style.get()));
- list->append(zoomAdjustedPixelValue(style->verticalBorderSpacing(), style.get()));
+ list->append(zoomAdjustedPixelValue(style->horizontalBorderSpacing(), *style));
+ list->append(zoomAdjustedPixelValue(style->verticalBorderSpacing(), *style));
return list.release();
}
case CSSPropertyWebkitBorderHorizontalSpacing:
- return zoomAdjustedPixelValue(style->horizontalBorderSpacing(), style.get());
+ return zoomAdjustedPixelValue(style->horizontalBorderSpacing(), *style);
case CSSPropertyWebkitBorderVerticalSpacing:
- return zoomAdjustedPixelValue(style->verticalBorderSpacing(), style.get());
+ return zoomAdjustedPixelValue(style->verticalBorderSpacing(), *style);
case CSSPropertyBorderImageSource:
if (style->borderImageSource())
return style->borderImageSource()->cssValue();
return cssValuePool().createIdentifierValue(CSSValueNone);
case CSSPropertyBorderTopColor:
- return m_allowVisitedStyle ? cssValuePool().createColorValue(style->visitedDependentColor(CSSPropertyBorderTopColor).rgb()) : currentColorOrValidColor(style.get(), style->borderTopColor());
+ return m_allowVisitedStyle ? cssValuePool().createColorValue(style->visitedDependentColor(CSSPropertyBorderTopColor).rgb()) : currentColorOrValidColor(*style, style->borderTopColor());
case CSSPropertyBorderRightColor:
- return m_allowVisitedStyle ? cssValuePool().createColorValue(style->visitedDependentColor(CSSPropertyBorderRightColor).rgb()) : currentColorOrValidColor(style.get(), style->borderRightColor());
+ return m_allowVisitedStyle ? cssValuePool().createColorValue(style->visitedDependentColor(CSSPropertyBorderRightColor).rgb()) : currentColorOrValidColor(*style, style->borderRightColor());
case CSSPropertyBorderBottomColor:
- return m_allowVisitedStyle ? cssValuePool().createColorValue(style->visitedDependentColor(CSSPropertyBorderBottomColor).rgb()) : currentColorOrValidColor(style.get(), style->borderBottomColor());
+ return m_allowVisitedStyle ? cssValuePool().createColorValue(style->visitedDependentColor(CSSPropertyBorderBottomColor).rgb()) : currentColorOrValidColor(*style, style->borderBottomColor());
case CSSPropertyBorderLeftColor:
- return m_allowVisitedStyle ? cssValuePool().createColorValue(style->visitedDependentColor(CSSPropertyBorderLeftColor).rgb()) : currentColorOrValidColor(style.get(), style->borderLeftColor());
+ return m_allowVisitedStyle ? cssValuePool().createColorValue(style->visitedDependentColor(CSSPropertyBorderLeftColor).rgb()) : currentColorOrValidColor(*style, style->borderLeftColor());
case CSSPropertyBorderTopStyle:
return cssValuePool().createValue(style->borderTopStyle());
case CSSPropertyBorderRightStyle:
@@ -1859,15 +1865,15 @@ PassRefPtr<CSSValue> CSSComputedStyleDeclaration::getPropertyCSSValue(CSSPropert
case CSSPropertyBorderLeftStyle:
return cssValuePool().createValue(style->borderLeftStyle());
case CSSPropertyBorderTopWidth:
- return zoomAdjustedPixelValue(style->borderTopWidth(), style.get());
+ return zoomAdjustedPixelValue(style->borderTopWidth(), *style);
case CSSPropertyBorderRightWidth:
- return zoomAdjustedPixelValue(style->borderRightWidth(), style.get());
+ return zoomAdjustedPixelValue(style->borderRightWidth(), *style);
case CSSPropertyBorderBottomWidth:
- return zoomAdjustedPixelValue(style->borderBottomWidth(), style.get());
+ return zoomAdjustedPixelValue(style->borderBottomWidth(), *style);
case CSSPropertyBorderLeftWidth:
- return zoomAdjustedPixelValue(style->borderLeftWidth(), style.get());
+ return zoomAdjustedPixelValue(style->borderLeftWidth(), *style);
case CSSPropertyBottom:
- return valueForPositionOffset(style.get(), CSSPropertyBottom, renderer, m_node->document().renderView());
+ return valueForPositionOffset(*style, CSSPropertyBottom, renderer, m_node->document().renderView());
case CSSPropertyWebkitBoxAlign:
return cssValuePool().createValue(style->boxAlign());
case CSSPropertyWebkitBoxDecorationBreak:
@@ -1889,10 +1895,10 @@ PassRefPtr<CSSValue> CSSComputedStyleDeclaration::getPropertyCSSValue(CSSPropert
case CSSPropertyWebkitBoxPack:
return cssValuePool().createValue(style->boxPack());
case CSSPropertyWebkitBoxReflect:
- return valueForReflection(style->boxReflect(), style.get());
+ return valueForReflection(style->boxReflect(), *style);
case CSSPropertyBoxShadow:
case CSSPropertyWebkitBoxShadow:
- return valueForShadow(style->boxShadow(), propertyID, style.get());
+ return valueForShadowList(style->boxShadow(), *style, true);
case CSSPropertyCaptionSide:
return cssValuePool().createValue(style->captionSide());
case CSSPropertyClear:
@@ -1907,18 +1913,22 @@ PassRefPtr<CSSValue> CSSComputedStyleDeclaration::getPropertyCSSValue(CSSPropert
if (style->hasAutoColumnCount())
return cssValuePool().createIdentifierValue(CSSValueAuto);
return cssValuePool().createValue(style->columnCount(), CSSPrimitiveValue::CSS_NUMBER);
+ case CSSPropertyColumnFill:
+ if (RuntimeEnabledFeatures::regionBasedColumnsEnabled())
+ return cssValuePool().createValue(style->columnFill());
+ return 0;
case CSSPropertyWebkitColumnGap:
if (style->hasNormalColumnGap())
return cssValuePool().createIdentifierValue(CSSValueNormal);
- return zoomAdjustedPixelValue(style->columnGap(), style.get());
+ return zoomAdjustedPixelValue(style->columnGap(), *style);
case CSSPropertyWebkitColumnProgression:
return cssValuePool().createValue(style->columnProgression());
case CSSPropertyWebkitColumnRuleColor:
- return m_allowVisitedStyle ? cssValuePool().createColorValue(style->visitedDependentColor(CSSPropertyOutlineColor).rgb()) : currentColorOrValidColor(style.get(), style->columnRuleColor());
+ return m_allowVisitedStyle ? cssValuePool().createColorValue(style->visitedDependentColor(CSSPropertyOutlineColor).rgb()) : currentColorOrValidColor(*style, style->columnRuleColor());
case CSSPropertyWebkitColumnRuleStyle:
return cssValuePool().createValue(style->columnRuleStyle());
case CSSPropertyWebkitColumnRuleWidth:
- return zoomAdjustedPixelValue(style->columnRuleWidth(), style.get());
+ return zoomAdjustedPixelValue(style->columnRuleWidth(), *style);
case CSSPropertyWebkitColumnSpan:
return cssValuePool().createIdentifierValue(style->columnSpan() ? CSSValueAll : CSSValueNone);
case CSSPropertyWebkitColumnBreakAfter:
@@ -1930,7 +1940,7 @@ PassRefPtr<CSSValue> CSSComputedStyleDeclaration::getPropertyCSSValue(CSSPropert
case CSSPropertyWebkitColumnWidth:
if (style->hasAutoColumnWidth())
return cssValuePool().createIdentifierValue(CSSValueAuto);
- return zoomAdjustedPixelValue(style->columnWidth(), style.get());
+ return zoomAdjustedPixelValue(style->columnWidth(), *style);
case CSSPropertyTabSize:
return cssValuePool().createValue(style->tabSize(), CSSPrimitiveValue::CSS_NUMBER);
case CSSPropertyWebkitRegionBreakAfter:
@@ -1996,17 +2006,17 @@ PassRefPtr<CSSValue> CSSComputedStyleDeclaration::getPropertyCSSValue(CSSPropert
return cssValuePool().createIdentifierValue(CSSValueNone);
return cssValuePool().createValue(style->floating());
case CSSPropertyFont: {
- RefPtr<FontValue> computedFont = FontValue::create();
- computedFont->style = valueForFontStyle(style.get());
- computedFont->variant = valueForFontVariant(style.get());
- computedFont->weight = valueForFontWeight(style.get());
- computedFont->size = valueForFontSize(style.get());
- computedFont->lineHeight = valueForLineHeight(style.get(), m_node->document().renderView());
- computedFont->family = valueForFontFamily(style.get());
+ RefPtr<CSSFontValue> computedFont = CSSFontValue::create();
+ computedFont->style = valueForFontStyle(*style);
+ computedFont->variant = valueForFontVariant(*style);
+ computedFont->weight = valueForFontWeight(*style);
+ computedFont->size = valueForFontSize(*style);
+ computedFont->lineHeight = valueForLineHeight(*style, m_node->document().renderView());
+ computedFont->family = valueForFontFamily(*style);
return computedFont.release();
}
case CSSPropertyFontFamily: {
- RefPtr<CSSValueList> fontFamilyList = valueForFontFamily(style.get());
+ RefPtr<CSSValueList> fontFamilyList = valueForFontFamily(*style);
// If there's only a single family, return that as a CSSPrimitiveValue.
// NOTE: Gecko always returns this as a comma-separated CSSPrimitiveValue string.
if (fontFamilyList->length() == 1)
@@ -2014,13 +2024,13 @@ PassRefPtr<CSSValue> CSSComputedStyleDeclaration::getPropertyCSSValue(CSSPropert
return fontFamilyList.release();
}
case CSSPropertyFontSize:
- return valueForFontSize(style.get());
+ return valueForFontSize(*style);
case CSSPropertyFontStyle:
- return valueForFontStyle(style.get());
+ return valueForFontStyle(*style);
case CSSPropertyFontVariant:
- return valueForFontVariant(style.get());
+ return valueForFontVariant(*style);
case CSSPropertyFontWeight:
- return valueForFontWeight(style.get());
+ return valueForFontWeight(*style);
case CSSPropertyWebkitFontFeatureSettings: {
const FontFeatureSettings* featureSettings = style->fontDescription().featureSettings();
if (!featureSettings || !featureSettings->size())
@@ -2028,21 +2038,28 @@ PassRefPtr<CSSValue> CSSComputedStyleDeclaration::getPropertyCSSValue(CSSPropert
RefPtr<CSSValueList> list = CSSValueList::createCommaSeparated();
for (unsigned i = 0; i < featureSettings->size(); ++i) {
const FontFeature& feature = featureSettings->at(i);
- RefPtr<FontFeatureValue> featureValue = FontFeatureValue::create(feature.tag(), feature.value());
+ RefPtr<CSSFontFeatureValue> featureValue = CSSFontFeatureValue::create(feature.tag(), feature.value());
list->append(featureValue.release());
}
return list.release();
}
- case CSSPropertyGridAutoColumns:
- return valueForGridTrackSize(style->gridAutoColumns(), style.get(), m_node->document().renderView());
case CSSPropertyGridAutoFlow:
return cssValuePool().createValue(style->gridAutoFlow());
+
+ // Specs mention that getComputedStyle() should return the used value of the property instead of the computed
+ // one for grid-definition-{rows|columns} but not for the grid-auto-{rows|columns} as things like
+ // grid-auto-columns: 2fr; cannot be resolved to a value in pixels as the '2fr' means very different things
+ // depending on the size of the explicit grid or the number of implicit tracks added to the grid. See
+ // http://lists.w3.org/Archives/Public/www-style/2013Nov/0014.html
+ case CSSPropertyGridAutoColumns:
+ return specifiedValueForGridTrackSize(style->gridAutoColumns(), *style, m_node->document().renderView());
case CSSPropertyGridAutoRows:
- return valueForGridTrackSize(style->gridAutoRows(), style.get(), m_node->document().renderView());
+ return specifiedValueForGridTrackSize(style->gridAutoRows(), *style, m_node->document().renderView());
+
case CSSPropertyGridDefinitionColumns:
- return valueForGridTrackList(style->gridDefinitionColumns(), style->orderedNamedGridColumnLines(), style.get(), m_node->document().renderView());
+ return valueForGridTrackList(ForColumns, renderer, *style, m_node->document().renderView());
case CSSPropertyGridDefinitionRows:
- return valueForGridTrackList(style->gridDefinitionRows(), style->orderedNamedGridRowLines(), style.get(), m_node->document().renderView());
+ return valueForGridTrackList(ForRows, renderer, *style, m_node->document().renderView());
case CSSPropertyGridColumnStart:
return valueForGridPosition(style->gridColumnStart());
@@ -2073,9 +2090,9 @@ PassRefPtr<CSSValue> CSSComputedStyleDeclaration::getPropertyCSSValue(CSSPropert
// the "height" property does not apply for non-replaced inline elements.
if (!renderer->isReplaced() && renderer->isInline())
return cssValuePool().createIdentifierValue(CSSValueAuto);
- return zoomAdjustedPixelValue(sizingBox(renderer).height(), style.get());
+ return zoomAdjustedPixelValue(sizingBox(renderer).height(), *style);
}
- return zoomAdjustedPixelValueForLength(style->height(), style.get());
+ return zoomAdjustedPixelValueForLength(style->height(), *style);
case CSSPropertyWebkitHighlight:
if (style->highlight() == nullAtom)
return cssValuePool().createIdentifierValue(CSSValueNone);
@@ -2093,17 +2110,17 @@ PassRefPtr<CSSValue> CSSComputedStyleDeclaration::getPropertyCSSValue(CSSPropert
case CSSPropertyIsolation:
return cssValuePool().createValue(style->isolation());
case CSSPropertyLeft:
- return valueForPositionOffset(style.get(), CSSPropertyLeft, renderer, m_node->document().renderView());
+ return valueForPositionOffset(*style, CSSPropertyLeft, renderer, m_node->document().renderView());
case CSSPropertyLetterSpacing:
if (!style->letterSpacing())
return cssValuePool().createIdentifierValue(CSSValueNormal);
- return zoomAdjustedPixelValue(style->letterSpacing(), style.get());
+ return zoomAdjustedPixelValue(style->letterSpacing(), *style);
case CSSPropertyWebkitLineClamp:
if (style->lineClamp().isNone())
return cssValuePool().createIdentifierValue(CSSValueNone);
return cssValuePool().createValue(style->lineClamp().value(), style->lineClamp().isPercentage() ? CSSPrimitiveValue::CSS_PERCENTAGE : CSSPrimitiveValue::CSS_NUMBER);
case CSSPropertyLineHeight:
- return valueForLineHeight(style.get(), m_node->document().renderView());
+ return valueForLineHeight(*style, m_node->document().renderView());
case CSSPropertyListStyleImage:
if (style->listStyleImage())
return style->listStyleImage()->cssValue();
@@ -2119,13 +2136,13 @@ PassRefPtr<CSSValue> CSSComputedStyleDeclaration::getPropertyCSSValue(CSSPropert
case CSSPropertyMarginTop: {
Length marginTop = style->marginTop();
if (marginTop.isFixed() || !renderer || !renderer->isBox())
- return zoomAdjustedPixelValueForLength(marginTop, style.get());
- return zoomAdjustedPixelValue(toRenderBox(renderer)->marginTop(), style.get());
+ return zoomAdjustedPixelValueForLength(marginTop, *style);
+ return zoomAdjustedPixelValue(toRenderBox(renderer)->marginTop(), *style);
}
case CSSPropertyMarginRight: {
Length marginRight = style->marginRight();
if (marginRight.isFixed() || !renderer || !renderer->isBox())
- return zoomAdjustedPixelValueForLength(marginRight, style.get());
+ return zoomAdjustedPixelValueForLength(marginRight, *style);
float value;
if (marginRight.isPercent() || marginRight.isViewportPercentage()) {
// RenderBox gives a marginRight() that is the distance between the right-edge of the child box
@@ -2135,19 +2152,19 @@ PassRefPtr<CSSValue> CSSComputedStyleDeclaration::getPropertyCSSValue(CSSPropert
} else {
value = toRenderBox(renderer)->marginRight();
}
- return zoomAdjustedPixelValue(value, style.get());
+ return zoomAdjustedPixelValue(value, *style);
}
case CSSPropertyMarginBottom: {
Length marginBottom = style->marginBottom();
if (marginBottom.isFixed() || !renderer || !renderer->isBox())
- return zoomAdjustedPixelValueForLength(marginBottom, style.get());
- return zoomAdjustedPixelValue(toRenderBox(renderer)->marginBottom(), style.get());
+ return zoomAdjustedPixelValueForLength(marginBottom, *style);
+ return zoomAdjustedPixelValue(toRenderBox(renderer)->marginBottom(), *style);
}
case CSSPropertyMarginLeft: {
Length marginLeft = style->marginLeft();
if (marginLeft.isFixed() || !renderer || !renderer->isBox())
- return zoomAdjustedPixelValueForLength(marginLeft, style.get());
- return zoomAdjustedPixelValue(toRenderBox(renderer)->marginLeft(), style.get());
+ return zoomAdjustedPixelValueForLength(marginLeft, *style);
+ return zoomAdjustedPixelValue(toRenderBox(renderer)->marginLeft(), *style);
}
case CSSPropertyWebkitUserModify:
return cssValuePool().createValue(style->userModify());
@@ -2155,31 +2172,31 @@ PassRefPtr<CSSValue> CSSComputedStyleDeclaration::getPropertyCSSValue(CSSPropert
const Length& maxHeight = style->maxHeight();
if (maxHeight.isUndefined())
return cssValuePool().createIdentifierValue(CSSValueNone);
- return zoomAdjustedPixelValueForLength(maxHeight, style.get());
+ return zoomAdjustedPixelValueForLength(maxHeight, *style);
}
case CSSPropertyMaxWidth: {
const Length& maxWidth = style->maxWidth();
if (maxWidth.isUndefined())
return cssValuePool().createIdentifierValue(CSSValueNone);
- return zoomAdjustedPixelValueForLength(maxWidth, style.get());
+ return zoomAdjustedPixelValueForLength(maxWidth, *style);
}
case CSSPropertyMinHeight:
// FIXME: For flex-items, min-height:auto should compute to min-content.
if (style->minHeight().isAuto())
- return zoomAdjustedPixelValue(0, style.get());
- return zoomAdjustedPixelValueForLength(style->minHeight(), style.get());
+ return zoomAdjustedPixelValue(0, *style);
+ return zoomAdjustedPixelValueForLength(style->minHeight(), *style);
case CSSPropertyMinWidth:
// FIXME: For flex-items, min-width:auto should compute to min-content.
if (style->minWidth().isAuto())
- return zoomAdjustedPixelValue(0, style.get());
- return zoomAdjustedPixelValueForLength(style->minWidth(), style.get());
+ return zoomAdjustedPixelValue(0, *style);
+ return zoomAdjustedPixelValueForLength(style->minWidth(), *style);
case CSSPropertyObjectFit:
return cssValuePool().createValue(style->objectFit());
case CSSPropertyObjectPosition:
return cssValuePool().createValue(
Pair::create(
- cssValuePool().createValue(style->objectPosition().x()),
- cssValuePool().createValue(style->objectPosition().y()),
+ zoomAdjustedPixelValueForLength(style->objectPosition().x(), *style),
+ zoomAdjustedPixelValueForLength(style->objectPosition().y(), *style),
Pair::KeepIdenticalValues));
case CSSPropertyOpacity:
return cssValuePool().createValue(style->opacity(), CSSPrimitiveValue::CSS_NUMBER);
@@ -2188,15 +2205,15 @@ PassRefPtr<CSSValue> CSSComputedStyleDeclaration::getPropertyCSSValue(CSSPropert
return cssValuePool().createIdentifierValue(CSSValueAuto);
return cssValuePool().createValue(style->orphans(), CSSPrimitiveValue::CSS_NUMBER);
case CSSPropertyOutlineColor:
- return m_allowVisitedStyle ? cssValuePool().createColorValue(style->visitedDependentColor(CSSPropertyOutlineColor).rgb()) : currentColorOrValidColor(style.get(), style->outlineColor());
+ return m_allowVisitedStyle ? cssValuePool().createColorValue(style->visitedDependentColor(CSSPropertyOutlineColor).rgb()) : currentColorOrValidColor(*style, style->outlineColor());
case CSSPropertyOutlineOffset:
- return zoomAdjustedPixelValue(style->outlineOffset(), style.get());
+ return zoomAdjustedPixelValue(style->outlineOffset(), *style);
case CSSPropertyOutlineStyle:
if (style->outlineStyleIsAuto())
return cssValuePool().createIdentifierValue(CSSValueAuto);
return cssValuePool().createValue(style->outlineStyle());
case CSSPropertyOutlineWidth:
- return zoomAdjustedPixelValue(style->outlineWidth(), style.get());
+ return zoomAdjustedPixelValue(style->outlineWidth(), *style);
case CSSPropertyOverflow:
return cssValuePool().createValue(max(style->overflowX(), style->overflowY()));
case CSSPropertyOverflowWrap:
@@ -2208,26 +2225,26 @@ PassRefPtr<CSSValue> CSSComputedStyleDeclaration::getPropertyCSSValue(CSSPropert
case CSSPropertyPaddingTop: {
Length paddingTop = style->paddingTop();
if (paddingTop.isFixed() || !renderer || !renderer->isBox())
- return zoomAdjustedPixelValueForLength(paddingTop, style.get());
- return zoomAdjustedPixelValue(toRenderBox(renderer)->computedCSSPaddingTop(), style.get());
+ return zoomAdjustedPixelValueForLength(paddingTop, *style);
+ return zoomAdjustedPixelValue(toRenderBox(renderer)->computedCSSPaddingTop(), *style);
}
case CSSPropertyPaddingRight: {
Length paddingRight = style->paddingRight();
if (paddingRight.isFixed() || !renderer || !renderer->isBox())
- return zoomAdjustedPixelValueForLength(paddingRight, style.get());
- return zoomAdjustedPixelValue(toRenderBox(renderer)->computedCSSPaddingRight(), style.get());
+ return zoomAdjustedPixelValueForLength(paddingRight, *style);
+ return zoomAdjustedPixelValue(toRenderBox(renderer)->computedCSSPaddingRight(), *style);
}
case CSSPropertyPaddingBottom: {
Length paddingBottom = style->paddingBottom();
if (paddingBottom.isFixed() || !renderer || !renderer->isBox())
- return zoomAdjustedPixelValueForLength(paddingBottom, style.get());
- return zoomAdjustedPixelValue(toRenderBox(renderer)->computedCSSPaddingBottom(), style.get());
+ return zoomAdjustedPixelValueForLength(paddingBottom, *style);
+ return zoomAdjustedPixelValue(toRenderBox(renderer)->computedCSSPaddingBottom(), *style);
}
case CSSPropertyPaddingLeft: {
Length paddingLeft = style->paddingLeft();
if (paddingLeft.isFixed() || !renderer || !renderer->isBox())
- return zoomAdjustedPixelValueForLength(paddingLeft, style.get());
- return zoomAdjustedPixelValue(toRenderBox(renderer)->computedCSSPaddingLeft(), style.get());
+ return zoomAdjustedPixelValueForLength(paddingLeft, *style);
+ return zoomAdjustedPixelValue(toRenderBox(renderer)->computedCSSPaddingLeft(), *style);
}
case CSSPropertyPageBreakAfter:
return cssValuePool().createValue(style->pageBreakAfter());
@@ -2243,7 +2260,7 @@ PassRefPtr<CSSValue> CSSComputedStyleDeclaration::getPropertyCSSValue(CSSPropert
case CSSPropertyPosition:
return cssValuePool().createValue(style->position());
case CSSPropertyRight:
- return valueForPositionOffset(style.get(), CSSPropertyRight, renderer, m_node->document().renderView());
+ return valueForPositionOffset(*style, CSSPropertyRight, renderer, m_node->document().renderView());
case CSSPropertyWebkitRubyPosition:
return cssValuePool().createValue(style->rubyPosition());
case CSSPropertyTableLayout:
@@ -2259,17 +2276,17 @@ PassRefPtr<CSSValue> CSSComputedStyleDeclaration::getPropertyCSSValue(CSSPropert
case CSSPropertyTextDecorationStyle:
return valueForTextDecorationStyle(style->textDecorationStyle());
case CSSPropertyTextDecorationColor:
- return currentColorOrValidColor(style.get(), style->textDecorationColor());
-#if ENABLE(CSS3_TEXT)
- case CSSPropertyWebkitTextUnderlinePosition:
+ return currentColorOrValidColor(*style, style->textDecorationColor());
+ case CSSPropertyTextJustify:
+ return cssValuePool().createValue(style->textJustify());
+ case CSSPropertyTextUnderlinePosition:
return cssValuePool().createValue(style->textUnderlinePosition());
-#endif // CSS3_TEXT
case CSSPropertyWebkitTextDecorationsInEffect:
return renderTextDecorationFlagsToCSSValue(style->textDecorationsInEffect());
case CSSPropertyWebkitTextFillColor:
- return currentColorOrValidColor(style.get(), style->textFillColor());
+ return currentColorOrValidColor(*style, style->textFillColor());
case CSSPropertyWebkitTextEmphasisColor:
- return currentColorOrValidColor(style.get(), style->textEmphasisColor());
+ return currentColorOrValidColor(*style, style->textEmphasisColor());
case CSSPropertyWebkitTextEmphasisPosition:
return cssValuePool().createValue(style->textEmphasisPosition());
case CSSPropertyWebkitTextEmphasisStyle:
@@ -2293,7 +2310,7 @@ PassRefPtr<CSSValue> CSSComputedStyleDeclaration::getPropertyCSSValue(CSSPropert
}
}
case CSSPropertyTextIndent: {
- RefPtr<CSSValue> textIndent = zoomAdjustedPixelValueForLength(style->textIndent(), style.get());
+ RefPtr<CSSValue> textIndent = zoomAdjustedPixelValueForLength(style->textIndent(), *style);
if (RuntimeEnabledFeatures::css3TextEnabled() && style->textIndentLine() == TextIndentEachLine) {
RefPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
list->append(textIndent.release());
@@ -2303,7 +2320,7 @@ PassRefPtr<CSSValue> CSSComputedStyleDeclaration::getPropertyCSSValue(CSSPropert
return textIndent.release();
}
case CSSPropertyTextShadow:
- return valueForShadow(style->textShadow(), propertyID, style.get());
+ return valueForShadowList(style->textShadow(), *style, false);
case CSSPropertyTextRendering:
return cssValuePool().createValue(style->fontDescription().textRenderingMode());
case CSSPropertyTextOverflow:
@@ -2313,15 +2330,17 @@ PassRefPtr<CSSValue> CSSComputedStyleDeclaration::getPropertyCSSValue(CSSPropert
case CSSPropertyWebkitTextSecurity:
return cssValuePool().createValue(style->textSecurity());
case CSSPropertyWebkitTextStrokeColor:
- return currentColorOrValidColor(style.get(), style->textStrokeColor());
+ return currentColorOrValidColor(*style, style->textStrokeColor());
case CSSPropertyWebkitTextStrokeWidth:
- return zoomAdjustedPixelValue(style->textStrokeWidth(), style.get());
+ return zoomAdjustedPixelValue(style->textStrokeWidth(), *style);
case CSSPropertyTextTransform:
return cssValuePool().createValue(style->textTransform());
case CSSPropertyTop:
- return valueForPositionOffset(style.get(), CSSPropertyTop, renderer, m_node->document().renderView());
+ return valueForPositionOffset(*style, CSSPropertyTop, renderer, m_node->document().renderView());
case CSSPropertyTouchAction:
- return cssValuePool().createValue(style->touchAction());
+ return touchActionFlagsToCSSValue(style->touchAction());
+ case CSSPropertyTouchActionDelay:
+ return cssValuePool().createValue(style->touchActionDelay());
case CSSPropertyUnicodeBidi:
return cssValuePool().createValue(style->unicodeBidi());
case CSSPropertyVerticalAlign:
@@ -2363,20 +2382,20 @@ PassRefPtr<CSSValue> CSSComputedStyleDeclaration::getPropertyCSSValue(CSSPropert
// the "width" property does not apply for non-replaced inline elements.
if (!renderer->isReplaced() && renderer->isInline())
return cssValuePool().createIdentifierValue(CSSValueAuto);
- return zoomAdjustedPixelValue(sizingBox(renderer).width(), style.get());
+ return zoomAdjustedPixelValue(sizingBox(renderer).width(), *style);
}
- return zoomAdjustedPixelValueForLength(style->width(), style.get());
+ return zoomAdjustedPixelValueForLength(style->width(), *style);
case CSSPropertyWordBreak:
return cssValuePool().createValue(style->wordBreak());
case CSSPropertyWordSpacing:
- return zoomAdjustedPixelValue(style->wordSpacing(), style.get());
+ return zoomAdjustedPixelValue(style->wordSpacing(), *style);
case CSSPropertyWordWrap:
return cssValuePool().createValue(style->overflowWrap());
case CSSPropertyWebkitLineBreak:
return cssValuePool().createValue(style->lineBreak());
case CSSPropertyResize:
return cssValuePool().createValue(style->resize());
- case CSSPropertyWebkitFontKerning:
+ case CSSPropertyFontKerning:
return cssValuePool().createValue(style->fontDescription().kerning());
case CSSPropertyWebkitFontSmoothing:
return cssValuePool().createValue(style->fontDescription().fontSmoothing());
@@ -2540,25 +2559,25 @@ PassRefPtr<CSSValue> CSSComputedStyleDeclaration::getPropertyCSSValue(CSSPropert
case CSSPropertyWebkitBackfaceVisibility:
return cssValuePool().createIdentifierValue((style->backfaceVisibility() == BackfaceVisibilityHidden) ? CSSValueHidden : CSSValueVisible);
case CSSPropertyWebkitBorderImage:
- return valueForNinePieceImage(style->borderImage(), style.get());
+ return valueForNinePieceImage(style->borderImage(), *style);
case CSSPropertyBorderImageOutset:
- return valueForNinePieceImageQuad(style->borderImage().outset(), style.get());
+ return valueForNinePieceImageQuad(style->borderImage().outset(), *style);
case CSSPropertyBorderImageRepeat:
return valueForNinePieceImageRepeat(style->borderImage());
case CSSPropertyBorderImageSlice:
return valueForNinePieceImageSlice(style->borderImage());
case CSSPropertyBorderImageWidth:
- return valueForNinePieceImageQuad(style->borderImage().borderSlices(), style.get());
+ return valueForNinePieceImageQuad(style->borderImage().borderSlices(), *style);
case CSSPropertyWebkitMaskBoxImage:
- return valueForNinePieceImage(style->maskBoxImage(), style.get());
+ return valueForNinePieceImage(style->maskBoxImage(), *style);
case CSSPropertyWebkitMaskBoxImageOutset:
- return valueForNinePieceImageQuad(style->maskBoxImage().outset(), style.get());
+ return valueForNinePieceImageQuad(style->maskBoxImage().outset(), *style);
case CSSPropertyWebkitMaskBoxImageRepeat:
return valueForNinePieceImageRepeat(style->maskBoxImage());
case CSSPropertyWebkitMaskBoxImageSlice:
return valueForNinePieceImageSlice(style->maskBoxImage());
case CSSPropertyWebkitMaskBoxImageWidth:
- return valueForNinePieceImageQuad(style->maskBoxImage().borderSlices(), style.get());
+ return valueForNinePieceImageQuad(style->maskBoxImage().borderSlices(), *style);
case CSSPropertyWebkitMaskBoxImageSource:
if (style->maskBoxImageSource())
return style->maskBoxImageSource()->cssValue();
@@ -2575,7 +2594,7 @@ PassRefPtr<CSSValue> CSSComputedStyleDeclaration::getPropertyCSSValue(CSSPropert
case CSSPropertyWebkitPerspective:
if (!style->hasPerspective())
return cssValuePool().createIdentifierValue(CSSValueNone);
- return zoomAdjustedPixelValue(style->perspective(), style.get());
+ return zoomAdjustedPixelValue(style->perspective(), *style);
case CSSPropertyWebkitPerspectiveOrigin: {
RefPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
if (renderer) {
@@ -2584,12 +2603,12 @@ PassRefPtr<CSSValue> CSSComputedStyleDeclaration::getPropertyCSSValue(CSSPropert
box = toRenderBox(renderer)->borderBoxRect();
RenderView* renderView = m_node->document().renderView();
- list->append(zoomAdjustedPixelValue(minimumValueForLength(style->perspectiveOriginX(), box.width(), renderView), style.get()));
- list->append(zoomAdjustedPixelValue(minimumValueForLength(style->perspectiveOriginY(), box.height(), renderView), style.get()));
+ list->append(zoomAdjustedPixelValue(minimumValueForLength(style->perspectiveOriginX(), box.width(), renderView), *style));
+ list->append(zoomAdjustedPixelValue(minimumValueForLength(style->perspectiveOriginY(), box.height(), renderView), *style));
}
else {
- list->append(zoomAdjustedPixelValueForLength(style->perspectiveOriginX(), style.get()));
- list->append(zoomAdjustedPixelValueForLength(style->perspectiveOriginY(), style.get()));
+ list->append(zoomAdjustedPixelValueForLength(style->perspectiveOriginX(), *style));
+ list->append(zoomAdjustedPixelValueForLength(style->perspectiveOriginY(), *style));
}
return list.release();
@@ -2597,33 +2616,33 @@ PassRefPtr<CSSValue> CSSComputedStyleDeclaration::getPropertyCSSValue(CSSPropert
case CSSPropertyWebkitRtlOrdering:
return cssValuePool().createIdentifierValue(style->rtlOrdering() ? CSSValueVisual : CSSValueLogical);
case CSSPropertyWebkitTapHighlightColor:
- return currentColorOrValidColor(style.get(), style->tapHighlightColor());
+ return currentColorOrValidColor(*style, style->tapHighlightColor());
case CSSPropertyWebkitUserDrag:
return cssValuePool().createValue(style->userDrag());
case CSSPropertyWebkitUserSelect:
return cssValuePool().createValue(style->userSelect());
case CSSPropertyBorderBottomLeftRadius:
- return valueForBorderRadiusCorner(style->borderBottomLeftRadius(), style.get(), renderer, m_node->document().renderView());
+ return valueForBorderRadiusCorner(style->borderBottomLeftRadius(), *style);
case CSSPropertyBorderBottomRightRadius:
- return valueForBorderRadiusCorner(style->borderBottomRightRadius(), style.get(), renderer, m_node->document().renderView());
+ return valueForBorderRadiusCorner(style->borderBottomRightRadius(), *style);
case CSSPropertyBorderTopLeftRadius:
- return valueForBorderRadiusCorner(style->borderTopLeftRadius(), style.get(), renderer, m_node->document().renderView());
+ return valueForBorderRadiusCorner(style->borderTopLeftRadius(), *style);
case CSSPropertyBorderTopRightRadius:
- return valueForBorderRadiusCorner(style->borderTopRightRadius(), style.get(), renderer, m_node->document().renderView());
+ return valueForBorderRadiusCorner(style->borderTopRightRadius(), *style);
case CSSPropertyClip: {
if (!style->hasClip())
return cssValuePool().createIdentifierValue(CSSValueAuto);
RefPtr<Rect> rect = Rect::create();
- rect->setTop(zoomAdjustedPixelValue(style->clip().top().value(), style.get()));
- rect->setRight(zoomAdjustedPixelValue(style->clip().right().value(), style.get()));
- rect->setBottom(zoomAdjustedPixelValue(style->clip().bottom().value(), style.get()));
- rect->setLeft(zoomAdjustedPixelValue(style->clip().left().value(), style.get()));
+ rect->setTop(zoomAdjustedPixelValue(style->clip().top().value(), *style));
+ rect->setRight(zoomAdjustedPixelValue(style->clip().right().value(), *style));
+ rect->setBottom(zoomAdjustedPixelValue(style->clip().bottom().value(), *style));
+ rect->setLeft(zoomAdjustedPixelValue(style->clip().left().value(), *style));
return cssValuePool().createValue(rect.release());
}
case CSSPropertySpeak:
return cssValuePool().createValue(style->speak());
case CSSPropertyWebkitTransform:
- return computedTransform(renderer, style.get());
+ return computedTransform(renderer, *style);
case CSSPropertyWebkitTransformOrigin: {
RefPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
if (renderer) {
@@ -2632,15 +2651,15 @@ PassRefPtr<CSSValue> CSSComputedStyleDeclaration::getPropertyCSSValue(CSSPropert
box = toRenderBox(renderer)->borderBoxRect();
RenderView* renderView = m_node->document().renderView();
- list->append(zoomAdjustedPixelValue(minimumValueForLength(style->transformOriginX(), box.width(), renderView), style.get()));
- list->append(zoomAdjustedPixelValue(minimumValueForLength(style->transformOriginY(), box.height(), renderView), style.get()));
+ list->append(zoomAdjustedPixelValue(minimumValueForLength(style->transformOriginX(), box.width(), renderView), *style));
+ list->append(zoomAdjustedPixelValue(minimumValueForLength(style->transformOriginY(), box.height(), renderView), *style));
if (style->transformOriginZ() != 0)
- list->append(zoomAdjustedPixelValue(style->transformOriginZ(), style.get()));
+ list->append(zoomAdjustedPixelValue(style->transformOriginZ(), *style));
} else {
- list->append(zoomAdjustedPixelValueForLength(style->transformOriginX(), style.get()));
- list->append(zoomAdjustedPixelValueForLength(style->transformOriginY(), style.get()));
+ list->append(zoomAdjustedPixelValueForLength(style->transformOriginX(), *style));
+ list->append(zoomAdjustedPixelValueForLength(style->transformOriginY(), *style));
if (style->transformOriginZ() != 0)
- list->append(zoomAdjustedPixelValue(style->transformOriginZ(), style.get()));
+ list->append(zoomAdjustedPixelValue(style->transformOriginZ(), *style));
}
return list.release();
}
@@ -2702,19 +2721,17 @@ PassRefPtr<CSSValue> CSSComputedStyleDeclaration::getPropertyCSSValue(CSSPropert
case CSSPropertyWebkitLineBoxContain:
return createLineBoxContainValue(style->lineBoxContain());
case CSSPropertyContent:
- return valueForContentData(style.get());
+ return valueForContentData(*style);
case CSSPropertyCounterIncrement:
- return valueForCounterDirectives(style.get(), propertyID);
+ return valueForCounterDirectives(*style, propertyID);
case CSSPropertyCounterReset:
- return valueForCounterDirectives(style.get(), propertyID);
+ return valueForCounterDirectives(*style, propertyID);
case CSSPropertyWebkitClipPath:
if (ClipPathOperation* operation = style->clipPath()) {
- if (operation->getOperationType() == ClipPathOperation::SHAPE)
- return valueForBasicShape(static_cast<ShapeClipPathOperation*>(operation)->basicShape());
- if (operation->getOperationType() == ClipPathOperation::REFERENCE) {
- ReferenceClipPathOperation* referenceOperation = static_cast<ReferenceClipPathOperation*>(operation);
- return CSSPrimitiveValue::create(referenceOperation->url(), CSSPrimitiveValue::CSS_URI);
- }
+ if (operation->type() == ClipPathOperation::SHAPE)
+ return valueForBasicShape(*style, toShapeClipPathOperation(operation)->basicShape());
+ if (operation->type() == ClipPathOperation::REFERENCE)
+ return CSSPrimitiveValue::create(toReferenceClipPathOperation(operation)->url(), CSSPrimitiveValue::CSS_URI);
}
return cssValuePool().createIdentifierValue(CSSValueNone);
case CSSPropertyWebkitFlowInto:
@@ -2722,20 +2739,24 @@ PassRefPtr<CSSValue> CSSComputedStyleDeclaration::getPropertyCSSValue(CSSPropert
return cssValuePool().createIdentifierValue(CSSValueNone);
return cssValuePool().createValue(style->flowThread(), CSSPrimitiveValue::CSS_STRING);
case CSSPropertyWebkitFlowFrom:
- if (style->regionThread().isNull())
+ if (!style->hasFlowFrom())
return cssValuePool().createIdentifierValue(CSSValueNone);
return cssValuePool().createValue(style->regionThread(), CSSPrimitiveValue::CSS_STRING);
case CSSPropertyWebkitRegionFragment:
return cssValuePool().createValue(style->regionFragment());
case CSSPropertyWebkitWrapFlow:
return cssValuePool().createValue(style->wrapFlow());
- case CSSPropertyWebkitShapeMargin:
+ case CSSPropertyShapeMargin:
return cssValuePool().createValue(style->shapeMargin());
- case CSSPropertyWebkitShapePadding:
+ case CSSPropertyShapePadding:
return cssValuePool().createValue(style->shapePadding());
- case CSSPropertyWebkitShapeInside:
+ case CSSPropertyShapeImageThreshold:
+ return cssValuePool().createValue(style->shapeImageThreshold(), CSSPrimitiveValue::CSS_NUMBER);
+ case CSSPropertyShapeInside:
if (!style->shapeInside())
return cssValuePool().createIdentifierValue(CSSValueAuto);
+ if (style->shapeInside()->type() == ShapeValue::Box)
+ return cssValuePool().createValue(style->shapeInside()->layoutBox());
if (style->shapeInside()->type() == ShapeValue::Outside)
return cssValuePool().createIdentifierValue(CSSValueOutsideShape);
if (style->shapeInside()->type() == ShapeValue::Image) {
@@ -2744,21 +2765,23 @@ PassRefPtr<CSSValue> CSSComputedStyleDeclaration::getPropertyCSSValue(CSSPropert
return cssValuePool().createIdentifierValue(CSSValueNone);
}
ASSERT(style->shapeInside()->type() == ShapeValue::Shape);
- return valueForBasicShape(style->shapeInside()->shape());
- case CSSPropertyWebkitShapeOutside:
+ return valueForBasicShape(*style, style->shapeInside()->shape());
+ case CSSPropertyShapeOutside:
if (!style->shapeOutside())
return cssValuePool().createIdentifierValue(CSSValueAuto);
+ if (style->shapeOutside()->type() == ShapeValue::Box)
+ return cssValuePool().createValue(style->shapeOutside()->layoutBox());
if (style->shapeOutside()->type() == ShapeValue::Image) {
if (style->shapeOutside()->image())
return style->shapeOutside()->image()->cssValue();
return cssValuePool().createIdentifierValue(CSSValueNone);
}
ASSERT(style->shapeOutside()->type() == ShapeValue::Shape);
- return valueForBasicShape(style->shapeOutside()->shape());
+ return valueForBasicShape(*style, style->shapeOutside()->shape());
case CSSPropertyWebkitWrapThrough:
return cssValuePool().createValue(style->wrapThrough());
case CSSPropertyWebkitFilter:
- return valueForFilter(renderer, style.get());
+ return valueForFilter(renderer, *style);
case CSSPropertyMixBlendMode:
return cssValuePool().createValue(style->blendMode());
@@ -2792,9 +2815,9 @@ PassRefPtr<CSSValue> CSSComputedStyleDeclaration::getPropertyCSSValue(CSSPropert
case CSSPropertyBorderLeft:
return valuesForShorthandProperty(borderLeftShorthand());
case CSSPropertyBorderImage:
- return valueForNinePieceImage(style->borderImage(), style.get());
+ return valueForNinePieceImage(style->borderImage(), *style);
case CSSPropertyBorderRadius:
- return valueForBorderRadiusShorthand(style.get(), renderer, m_node->document().renderView());
+ return valueForBorderRadiusShorthand(*style);
case CSSPropertyBorderRight:
return valuesForShorthandProperty(borderRightShorthand());
case CSSPropertyBorderStyle:
@@ -2819,6 +2842,9 @@ PassRefPtr<CSSValue> CSSComputedStyleDeclaration::getPropertyCSSValue(CSSPropert
case CSSPropertyBackgroundRepeatX:
case CSSPropertyBackgroundRepeatY:
break;
+ case CSSPropertyInternalCallback:
+ // This property is hidden from the web.
+ return 0;
/* Unimplemented CSS 3 properties (including CSS3 shorthand properties) */
case CSSPropertyWebkitTextEmphasis:
@@ -3110,14 +3136,14 @@ bool CSSComputedStyleDeclaration::isPropertyImplicit(const String&)
return false;
}
-void CSSComputedStyleDeclaration::setProperty(const String& name, const String&, const String&, ExceptionState& es)
+void CSSComputedStyleDeclaration::setProperty(const String& name, const String&, const String&, ExceptionState& exceptionState)
{
- es.throwDOMException(NoModificationAllowedError, "Failed to set the '" + name + "' property on a computed 'CSSStyleDeclaration': computed styles are read-only.");
+ exceptionState.throwDOMException(NoModificationAllowedError, "These styles are computed, and therefore the '" + name + "' property is read-only.");
}
-String CSSComputedStyleDeclaration::removeProperty(const String& name, ExceptionState& es)
+String CSSComputedStyleDeclaration::removeProperty(const String& name, ExceptionState& exceptionState)
{
- es.throwDOMException(NoModificationAllowedError, "Failed to remove the '" + name + "' property from a computed 'CSSStyleDeclaration': computed styles are read-only.");
+ exceptionState.throwDOMException(NoModificationAllowedError, "These styles are computed, and therefore the '" + name + "' property is read-only.");
return String();
}
@@ -3131,9 +3157,9 @@ String CSSComputedStyleDeclaration::getPropertyValueInternal(CSSPropertyID prope
return getPropertyValue(propertyID);
}
-void CSSComputedStyleDeclaration::setPropertyInternal(CSSPropertyID id, const String&, bool, ExceptionState& es)
+void CSSComputedStyleDeclaration::setPropertyInternal(CSSPropertyID id, const String&, bool, ExceptionState& exceptionState)
{
- es.throwDOMException(NoModificationAllowedError, "Failed to set the '" + getPropertyNameString(id) + "' property on a computed 'CSSStyleDeclaration': computed styles are read-only.");
+ exceptionState.throwDOMException(NoModificationAllowedError, "These styles are computed, and therefore the '" + getPropertyNameString(id) + "' property is read-only.");
}
const HashMap<AtomicString, String>* CSSComputedStyleDeclaration::variableMap() const
@@ -3169,10 +3195,11 @@ String CSSComputedStyleDeclaration::variableValue(const AtomicString& name) cons
return it->value;
}
-void CSSComputedStyleDeclaration::setVariableValue(const AtomicString& name, const String&, ExceptionState& es)
+bool CSSComputedStyleDeclaration::setVariableValue(const AtomicString& name, const String&, ExceptionState& exceptionState)
{
ASSERT(RuntimeEnabledFeatures::cssVariablesEnabled());
- es.throwDOMException(NoModificationAllowedError, "Failed to set the '" + name + "' property on a computed 'CSSStyleDeclaration': computed styles are read-only.");
+ exceptionState.throwDOMException(NoModificationAllowedError, "These styles are computed, and therefore the '" + name + "' property is read-only.");
+ return false;
}
bool CSSComputedStyleDeclaration::removeVariable(const AtomicString&)
@@ -3181,10 +3208,40 @@ bool CSSComputedStyleDeclaration::removeVariable(const AtomicString&)
return false;
}
-void CSSComputedStyleDeclaration::clearVariables(ExceptionState& es)
+bool CSSComputedStyleDeclaration::clearVariables(ExceptionState& exceptionState)
+{
+ ASSERT(RuntimeEnabledFeatures::cssVariablesEnabled());
+ exceptionState.throwDOMException(NoModificationAllowedError, "These styles are computed, and therefore variables may not be cleared.");
+ return false;
+}
+
+CSSComputedStyleDeclaration::ComputedCSSVariablesIterator::ComputedCSSVariablesIterator(const HashMap<AtomicString, String>* variables)
+ : m_active(variables)
{
ASSERT(RuntimeEnabledFeatures::cssVariablesEnabled());
- es.throwDOMException(NoModificationAllowedError, "Failed to clear variables from a computed 'CSSStyleDeclaration': computed styles are read-only.");
+ if (m_active) {
+ m_it = variables->begin();
+ m_end = variables->end();
+ }
+}
+
+void CSSComputedStyleDeclaration::ComputedCSSVariablesIterator::advance()
+{
+ ASSERT(m_active);
+ ++m_it;
+ m_active = !atEnd();
+}
+
+AtomicString CSSComputedStyleDeclaration::ComputedCSSVariablesIterator::name() const
+{
+ ASSERT(m_active);
+ return m_it->key;
+}
+
+String CSSComputedStyleDeclaration::ComputedCSSVariablesIterator::value() const
+{
+ ASSERT(m_active);
+ return m_it->value;
}
PassRefPtr<CSSValueList> CSSComputedStyleDeclaration::valuesForBackgroundShorthand() const
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSComputedStyleDeclaration.h b/chromium/third_party/WebKit/Source/core/css/CSSComputedStyleDeclaration.h
index 6116b50d2b4..a3ff8770319 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSComputedStyleDeclaration.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSComputedStyleDeclaration.h
@@ -43,12 +43,30 @@ class RenderObject;
class RenderStyle;
class SVGPaint;
class ShadowData;
+class ShadowList;
class StylePropertySet;
class StylePropertyShorthand;
enum EUpdateLayout { DoNotUpdateLayout = false, UpdateLayout = true };
class CSSComputedStyleDeclaration : public CSSStyleDeclaration {
+private:
+ class ComputedCSSVariablesIterator : public CSSVariablesIterator {
+ public:
+ virtual ~ComputedCSSVariablesIterator() { }
+ static PassRefPtr<ComputedCSSVariablesIterator> create(const HashMap<AtomicString, String>* variableMap) { return adoptRef(new ComputedCSSVariablesIterator(variableMap)); }
+ private:
+ explicit ComputedCSSVariablesIterator(const HashMap<AtomicString, String>* variableMap);
+ virtual void advance() OVERRIDE;
+ virtual bool atEnd() const OVERRIDE { return m_it == m_end; }
+ virtual AtomicString name() const OVERRIDE;
+ virtual String value() const OVERRIDE;
+ bool m_active;
+ typedef HashMap<AtomicString, String>::const_iterator VariablesMapIterator;
+ VariablesMapIterator m_it;
+ VariablesMapIterator m_end;
+ };
+
public:
static PassRefPtr<CSSComputedStyleDeclaration> create(PassRefPtr<Node> node, bool allowVisitedStyle = false, const String& pseudoElementName = String())
{
@@ -95,7 +113,7 @@ private:
virtual void setProperty(const String& propertyName, const String& value, const String& priority, ExceptionState&);
virtual String removeProperty(const String& propertyName, ExceptionState&);
virtual String cssText() const;
- virtual void setCssText(const String&, ExceptionState&);
+ virtual void setCSSText(const String&, ExceptionState&);
virtual PassRefPtr<CSSValue> getPropertyCSSValueInternal(CSSPropertyID);
virtual String getPropertyValueInternal(CSSPropertyID);
virtual void setPropertyInternal(CSSPropertyID, const String& value, bool important, ExceptionState&);
@@ -103,17 +121,19 @@ private:
const HashMap<AtomicString, String>* variableMap() const;
virtual unsigned variableCount() const OVERRIDE;
virtual String variableValue(const AtomicString& name) const OVERRIDE;
- virtual void setVariableValue(const AtomicString& name, const String& value, ExceptionState&) OVERRIDE;
+ virtual bool setVariableValue(const AtomicString& name, const String& value, ExceptionState&) OVERRIDE;
virtual bool removeVariable(const AtomicString& name) OVERRIDE;
- virtual void clearVariables(ExceptionState&) OVERRIDE;
+ virtual bool clearVariables(ExceptionState&) OVERRIDE;
+ virtual PassRefPtr<CSSVariablesIterator> variablesIterator() const OVERRIDE { return ComputedCSSVariablesIterator::create(variableMap()); }
virtual bool cssPropertyMatches(CSSPropertyID, const CSSValue*) const OVERRIDE;
- PassRefPtr<CSSValue> valueForShadow(const ShadowData*, CSSPropertyID, const RenderStyle*) const;
- PassRefPtr<CSSPrimitiveValue> currentColorOrValidColor(RenderStyle*, const Color&) const;
- PassRefPtr<SVGPaint> adjustSVGPaintForCurrentColor(PassRefPtr<SVGPaint>, RenderStyle*) const;
+ PassRefPtr<CSSValue> valueForShadowData(const ShadowData&, const RenderStyle&, bool useSpread) const;
+ PassRefPtr<CSSValue> valueForShadowList(const ShadowList*, const RenderStyle&, bool useSpread) const;
+ PassRefPtr<CSSPrimitiveValue> currentColorOrValidColor(const RenderStyle&, const Color&) const;
+ PassRefPtr<SVGPaint> adjustSVGPaintForCurrentColor(PassRefPtr<SVGPaint>, RenderStyle&) const;
- PassRefPtr<CSSValue> valueForFilter(const RenderObject*, const RenderStyle*) const;
+ PassRefPtr<CSSValue> valueForFilter(const RenderObject*, const RenderStyle&) const;
PassRefPtr<CSSValueList> valuesForShorthandProperty(const StylePropertyShorthand&) const;
PassRefPtr<CSSValueList> valuesForSidesShorthand(const StylePropertyShorthand&) const;
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSCrossfadeValue.cpp b/chromium/third_party/WebKit/Source/core/css/CSSCrossfadeValue.cpp
index b45f6cc5d19..801cbb66f99 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSCrossfadeValue.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/CSSCrossfadeValue.cpp
@@ -27,10 +27,9 @@
#include "core/css/CSSCrossfadeValue.h"
#include "core/css/CSSImageValue.h"
-#include "core/fetch/ImageResource.h"
-#include "core/platform/graphics/CrossfadeGeneratedImage.h"
#include "core/rendering/RenderObject.h"
#include "core/rendering/style/StyleFetchedImage.h"
+#include "platform/graphics/CrossfadeGeneratedImage.h"
#include "wtf/text/StringBuilder.h"
namespace WebCore {
@@ -41,7 +40,7 @@ static bool subimageIsPending(CSSValue* value)
return toCSSImageValue(value)->cachedOrPendingImage()->isPendingImage();
if (value->isImageGeneratorValue())
- return static_cast<CSSImageGeneratorValue*>(value)->isPending();
+ return toCSSImageGeneratorValue(value)->isPending();
ASSERT_NOT_REACHED();
@@ -54,7 +53,7 @@ static bool subimageKnownToBeOpaque(CSSValue* value, const RenderObject* rendere
return toCSSImageValue(value)->knownToBeOpaque(renderer);
if (value->isImageGeneratorValue())
- return static_cast<CSSImageGeneratorValue*>(value)->knownToBeOpaque(renderer);
+ return toCSSImageGeneratorValue(value)->knownToBeOpaque(renderer);
ASSERT_NOT_REACHED();
@@ -75,7 +74,7 @@ static ImageResource* cachedImageForCSSValue(CSSValue* value, ResourceFetcher* f
}
if (value->isImageGeneratorValue()) {
- static_cast<CSSImageGeneratorValue*>(value)->loadSubimages(fetcher);
+ toCSSImageGeneratorValue(value)->loadSubimages(fetcher);
// FIXME: Handle CSSImageGeneratorValue (and thus cross-fades with gradients and canvas).
return 0;
}
@@ -93,7 +92,7 @@ CSSCrossfadeValue::~CSSCrossfadeValue()
m_cachedToImage->removeClient(&m_crossfadeSubimageObserver);
}
-String CSSCrossfadeValue::customCssText() const
+String CSSCrossfadeValue::customCSSText() const
{
StringBuilder result;
result.appendLiteral("-webkit-cross-fade(");
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSCrossfadeValue.h b/chromium/third_party/WebKit/Source/core/css/CSSCrossfadeValue.h
index 4df75201818..ffb46aed9f1 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSCrossfadeValue.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSCrossfadeValue.h
@@ -31,7 +31,7 @@
#include "core/fetch/ImageResource.h"
#include "core/fetch/ImageResourceClient.h"
#include "core/fetch/ResourcePtr.h"
-#include "core/platform/graphics/Image.h"
+#include "platform/graphics/Image.h"
namespace WebCore {
@@ -50,7 +50,7 @@ public:
~CSSCrossfadeValue();
- String customCssText() const;
+ String customCSSText() const;
PassRefPtr<Image> image(RenderObject*, const IntSize&);
bool isFixedSize() const { return true; }
@@ -104,6 +104,8 @@ private:
CrossfadeSubimageObserverProxy m_crossfadeSubimageObserver;
};
+DEFINE_CSS_VALUE_TYPE_CASTS(CSSCrossfadeValue, isCrossfadeValue());
+
} // namespace WebCore
#endif // CSSCrossfadeValue_h
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSCursorImageValue.cpp b/chromium/third_party/WebKit/Source/core/css/CSSCursorImageValue.cpp
index 24caef773da..878fd8910de 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSCursorImageValue.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/CSSCursorImageValue.cpp
@@ -24,7 +24,6 @@
#include "SVGNames.h"
#include "core/css/CSSImageSetValue.h"
-#include "core/css/CSSImageValue.h"
#include "core/fetch/ImageResource.h"
#include "core/fetch/ResourceFetcher.h"
#include "core/rendering/style/StyleFetchedImage.h"
@@ -74,7 +73,7 @@ CSSCursorImageValue::~CSSCursorImageValue()
}
}
-String CSSCursorImageValue::customCssText() const
+String CSSCursorImageValue::customCSSText() const
{
StringBuilder result;
result.append(m_imageValue->cssText());
@@ -122,7 +121,7 @@ bool CSSCursorImageValue::updateIfSVGCursorIsUsed(Element* element)
StyleImage* CSSCursorImageValue::cachedImage(ResourceFetcher* loader, float deviceScaleFactor)
{
if (m_imageValue->isImageSetValue())
- return static_cast<CSSImageSetValue*>(m_imageValue.get())->cachedImageSet(loader, deviceScaleFactor);
+ return toCSSImageSetValue(m_imageValue.get())->cachedImageSet(loader, deviceScaleFactor);
if (!m_accessedImage) {
m_accessedImage = true;
@@ -146,8 +145,7 @@ StyleImage* CSSCursorImageValue::cachedImage(ResourceFetcher* loader, float devi
}
if (m_image && m_image->isImageResource())
- return static_cast<StyleFetchedImage*>(m_image.get());
-
+ return toStyleFetchedImage(m_image);
return 0;
}
@@ -155,7 +153,7 @@ StyleImage* CSSCursorImageValue::cachedOrPendingImage(float deviceScaleFactor)
{
// Need to delegate completely so that changes in device scale factor can be handled appropriately.
if (m_imageValue->isImageSetValue())
- return static_cast<CSSImageSetValue*>(m_imageValue.get())->cachedOrPendingImageSet(deviceScaleFactor);
+ return toCSSImageSetValue(m_imageValue.get())->cachedOrPendingImageSet(deviceScaleFactor);
if (!m_image)
m_image = StylePendingImage::create(this);
@@ -177,7 +175,7 @@ String CSSCursorImageValue::cachedImageURL()
{
if (!m_image || !m_image->isImageResource())
return String();
- return static_cast<StyleFetchedImage*>(m_image.get())->cachedImage()->url().string();
+ return toStyleFetchedImage(m_image)->cachedImage()->url().string();
}
void CSSCursorImageValue::clearImageResource()
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSCursorImageValue.h b/chromium/third_party/WebKit/Source/core/css/CSSCursorImageValue.h
index c4a895cfe04..17bba3188a1 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSCursorImageValue.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSCursorImageValue.h
@@ -22,7 +22,7 @@
#define CSSCursorImageValue_h
#include "core/css/CSSImageValue.h"
-#include "core/platform/graphics/IntPoint.h"
+#include "platform/geometry/IntPoint.h"
#include "wtf/HashSet.h"
namespace WebCore {
@@ -48,7 +48,7 @@ public:
return IntPoint(-1, -1);
}
- String customCssText() const;
+ String customCSSText() const;
bool updateIfSVGCursorIsUsed(Element*);
StyleImage* cachedImage(ResourceFetcher*, float deviceScaleFactor);
@@ -75,6 +75,8 @@ private:
HashSet<SVGElement*> m_referencedElements;
};
+DEFINE_CSS_VALUE_TYPE_CASTS(CSSCursorImageValue, isCursorImageValue());
+
} // namespace WebCore
#endif // CSSCursorImageValue_h
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSCustomFontData.h b/chromium/third_party/WebKit/Source/core/css/CSSCustomFontData.h
new file mode 100644
index 00000000000..9436927cabb
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/css/CSSCustomFontData.h
@@ -0,0 +1,61 @@
+/*
+ * Copyright (C) 2013 Google, Inc.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ */
+
+#ifndef CSSCustomFontData_h
+#define CSSCustomFontData_h
+
+#include "core/css/CSSFontFaceSource.h"
+#include "platform/fonts/CustomFontData.h"
+
+namespace WebCore {
+
+class CSSCustomFontData FINAL : public CustomFontData {
+public:
+ static PassRefPtr<CSSCustomFontData> create(bool isLoadingFallback = false)
+ {
+ return adoptRef(new CSSCustomFontData(isLoadingFallback));
+ }
+
+ virtual ~CSSCustomFontData() { }
+
+ virtual void beginLoadIfNeeded() const OVERRIDE
+ {
+ if (!m_isUsed && m_isLoadingFallback && m_fontFaceSource) {
+ m_isUsed = true;
+ m_fontFaceSource->beginLoadIfNeeded();
+ }
+ }
+
+ virtual void setCSSFontFaceSource(CSSFontFaceSource* source) OVERRIDE { m_fontFaceSource = source; }
+ virtual void clearCSSFontFaceSource() OVERRIDE { m_fontFaceSource = 0; }
+
+private:
+ CSSCustomFontData(bool isLoadingFallback)
+ : CustomFontData(isLoadingFallback)
+ , m_fontFaceSource(0)
+ {
+ }
+
+ CSSFontFaceSource* m_fontFaceSource;
+};
+
+}
+
+#endif // CSSCustomFontData_h
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSDefaultStyleSheets.cpp b/chromium/third_party/WebKit/Source/core/css/CSSDefaultStyleSheets.cpp
index 3984e17c41e..cdd794828a7 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSDefaultStyleSheets.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/CSSDefaultStyleSheets.cpp
@@ -44,26 +44,19 @@ namespace WebCore {
using namespace HTMLNames;
RuleSet* CSSDefaultStyleSheets::defaultStyle;
+RuleSet* CSSDefaultStyleSheets::defaultViewportStyle;
RuleSet* CSSDefaultStyleSheets::defaultQuirksStyle;
RuleSet* CSSDefaultStyleSheets::defaultPrintStyle;
RuleSet* CSSDefaultStyleSheets::defaultViewSourceStyle;
RuleSet* CSSDefaultStyleSheets::defaultXHTMLMobileProfileStyle;
-StyleSheetContents* CSSDefaultStyleSheets::simpleDefaultStyleSheet;
StyleSheetContents* CSSDefaultStyleSheets::defaultStyleSheet;
+StyleSheetContents* CSSDefaultStyleSheets::viewportStyleSheet;
StyleSheetContents* CSSDefaultStyleSheets::quirksStyleSheet;
StyleSheetContents* CSSDefaultStyleSheets::svgStyleSheet;
StyleSheetContents* CSSDefaultStyleSheets::mediaControlsStyleSheet;
StyleSheetContents* CSSDefaultStyleSheets::fullscreenStyleSheet;
-// FIXME: It would be nice to use some mechanism that guarantees this is in sync with the real UA stylesheet.
-static const char* simpleUserAgentStyleSheet = "html,body,div{display:block}head{display:none}body{margin:8px}div:focus,span:focus{outline:auto 5px -webkit-focus-ring-color}a:-webkit-any-link{color:-webkit-link;text-decoration:underline}a:-webkit-any-link:active{color:-webkit-activelink}body:-webkit-seamless-document{margin:0}body:-webkit-full-page-media{background-color:black}@viewport{min-width:980px}";
-
-static inline bool elementCanUseSimpleDefaultStyle(Element* e)
-{
- return isHTMLHtmlElement(e) || e->hasTagName(headTag) || e->hasTagName(bodyTag) || e->hasTagName(divTag) || e->hasTagName(spanTag) || e->hasTagName(brTag) || isHTMLAnchorElement(e);
-}
-
static const MediaQueryEvaluator& screenEval()
{
DEFINE_STATIC_LOCAL(const MediaQueryEvaluator, staticScreenEval, ("screen"));
@@ -88,37 +81,31 @@ static StyleSheetContents* parseUASheet(const char* characters, unsigned size)
return parseUASheet(String(characters, size));
}
-void CSSDefaultStyleSheets::initDefaultStyle(Element* root)
+void CSSDefaultStyleSheets::loadDefaultStylesheetIfNecessary()
{
- if (!defaultStyle) {
- if (!root || elementCanUseSimpleDefaultStyle(root))
- loadSimpleDefaultStyle();
- else
- loadFullDefaultStyle();
- }
+ if (!defaultStyle)
+ loadDefaultStyle();
}
-void CSSDefaultStyleSheets::loadFullDefaultStyle()
+void CSSDefaultStyleSheets::loadDefaultStyle()
{
- if (simpleDefaultStyleSheet) {
- ASSERT(defaultStyle);
- ASSERT(defaultPrintStyle == defaultStyle);
- delete defaultStyle;
- simpleDefaultStyleSheet->deref();
- defaultStyle = RuleSet::create().leakPtr();
- defaultPrintStyle = RuleSet::create().leakPtr();
- simpleDefaultStyleSheet = 0;
- } else {
- ASSERT(!defaultStyle);
- defaultStyle = RuleSet::create().leakPtr();
- defaultPrintStyle = RuleSet::create().leakPtr();
- defaultQuirksStyle = RuleSet::create().leakPtr();
- }
+ ASSERT(!defaultStyle);
+ defaultStyle = RuleSet::create().leakPtr();
+ defaultViewportStyle = RuleSet::create().leakPtr();
+ defaultPrintStyle = RuleSet::create().leakPtr();
+ defaultQuirksStyle = RuleSet::create().leakPtr();
// Strict-mode rules.
String defaultRules = String(htmlUserAgentStyleSheet, sizeof(htmlUserAgentStyleSheet)) + RenderTheme::theme().extraDefaultStyleSheet();
defaultStyleSheet = parseUASheet(defaultRules);
defaultStyle->addRulesFromSheet(defaultStyleSheet, screenEval());
+#if OS(ANDROID)
+ String viewportRules(viewportAndroidUserAgentStyleSheet, sizeof(viewportAndroidUserAgentStyleSheet));
+#else
+ String viewportRules;
+#endif
+ viewportStyleSheet = parseUASheet(viewportRules);
+ defaultViewportStyle->addRulesFromSheet(viewportStyleSheet, screenEval());
defaultPrintStyle->addRulesFromSheet(defaultStyleSheet, printEval());
// Quirks-mode rules.
@@ -127,22 +114,6 @@ void CSSDefaultStyleSheets::loadFullDefaultStyle()
defaultQuirksStyle->addRulesFromSheet(quirksStyleSheet, screenEval());
}
-void CSSDefaultStyleSheets::loadSimpleDefaultStyle()
-{
- ASSERT(!defaultStyle);
- ASSERT(!simpleDefaultStyleSheet);
-
- defaultStyle = RuleSet::create().leakPtr();
- // There are no media-specific rules in the simple default style.
- defaultPrintStyle = defaultStyle;
- defaultQuirksStyle = RuleSet::create().leakPtr();
-
- simpleDefaultStyleSheet = parseUASheet(simpleUserAgentStyleSheet, strlen(simpleUserAgentStyleSheet));
- defaultStyle->addRulesFromSheet(simpleDefaultStyleSheet, screenEval());
-
- // No need to initialize quirks sheet yet as there are no quirk rules for elements allowed in simple default style.
-}
-
RuleSet* CSSDefaultStyleSheets::viewSourceStyle()
{
if (!defaultViewSourceStyle) {
@@ -163,11 +134,6 @@ RuleSet* CSSDefaultStyleSheets::xhtmlMobileProfileStyle()
void CSSDefaultStyleSheets::ensureDefaultStyleSheetsForElement(Element* element, bool& changedDefaultStyle)
{
- if (simpleDefaultStyleSheet && !elementCanUseSimpleDefaultStyle(element)) {
- loadFullDefaultStyle();
- changedDefaultStyle = true;
- }
-
// FIXME: We should assert that the sheet only styles SVG elements.
if (element->isSVGElement() && !svgStyleSheet) {
svgStyleSheet = parseUASheet(svgUserAgentStyleSheet, sizeof(svgUserAgentStyleSheet));
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSDefaultStyleSheets.h b/chromium/third_party/WebKit/Source/core/css/CSSDefaultStyleSheets.h
index 5cf0035835f..c85fd226340 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSDefaultStyleSheets.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSDefaultStyleSheets.h
@@ -32,24 +32,30 @@ class StyleSheetContents;
class CSSDefaultStyleSheets {
public:
static RuleSet* defaultStyle;
+ static RuleSet* defaultViewportStyle;
static RuleSet* defaultQuirksStyle;
static RuleSet* defaultPrintStyle;
static RuleSet* defaultViewSourceStyle;
static RuleSet* defaultXHTMLMobileProfileStyle;
- static StyleSheetContents* simpleDefaultStyleSheet;
static StyleSheetContents* defaultStyleSheet;
+ static StyleSheetContents* viewportStyleSheet;
static StyleSheetContents* quirksStyleSheet;
static StyleSheetContents* svgStyleSheet;
static StyleSheetContents* mediaControlsStyleSheet;
static StyleSheetContents* fullscreenStyleSheet;
static void ensureDefaultStyleSheetsForElement(Element*, bool& changedDefaultStyle);
- static void loadFullDefaultStyle();
- static void loadSimpleDefaultStyle();
- static void initDefaultStyle(Element*);
+ // FIXME: defaultStyleSheet should have an accessor which incorporates this branch:
+ static void loadDefaultStylesheetIfNecessary();
+
static RuleSet* viewSourceStyle();
+
+ // FIXME: Remove WAP support.
static RuleSet* xhtmlMobileProfileStyle();
+
+private:
+ static void loadDefaultStyle();
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSFilterRule.cpp b/chromium/third_party/WebKit/Source/core/css/CSSFilterRule.cpp
index c72a16e61e3..dc44874be19 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSFilterRule.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/CSSFilterRule.cpp
@@ -77,8 +77,7 @@ String CSSFilterRule::cssText() const
void CSSFilterRule::reattach(StyleRuleBase* rule)
{
ASSERT(rule);
- ASSERT_WITH_SECURITY_IMPLICATION(rule->isFilterRule());
- m_filterRule = static_cast<StyleRuleFilter*>(rule);
+ m_filterRule = toStyleRuleFilter(rule);
if (m_propertiesCSSOMWrapper)
m_propertiesCSSOMWrapper->reattach(m_filterRule->mutableProperties());
}
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSFilterRule.h b/chromium/third_party/WebKit/Source/core/css/CSSFilterRule.h
index 9e605873553..9bb1b192c2a 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSFilterRule.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSFilterRule.h
@@ -57,6 +57,8 @@ private:
mutable RefPtr<StyleRuleCSSStyleDeclaration> m_propertiesCSSOMWrapper;
};
+DEFINE_CSS_RULE_TYPE_CASTS(CSSFilterRule, WEBKIT_FILTER_RULE);
+
}
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSFilterValue.cpp b/chromium/third_party/WebKit/Source/core/css/CSSFilterValue.cpp
index 4e25d957628..75567a7eeb8 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSFilterValue.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/CSSFilterValue.cpp
@@ -26,8 +26,6 @@
#include "config.h"
#include "core/css/CSSFilterValue.h"
-#include "core/css/CSSValueList.h"
-#include "wtf/PassRefPtr.h"
#include "wtf/text/WTFString.h"
namespace WebCore {
@@ -43,7 +41,7 @@ bool CSSFilterValue::typeUsesSpaceSeparator(FilterOperationType operationType)
return operationType != CustomFilterOperation;
}
-String CSSFilterValue::customCssText() const
+String CSSFilterValue::customCSSText() const
{
String result;
switch (m_type) {
@@ -87,7 +85,7 @@ String CSSFilterValue::customCssText() const
break;
}
- return result + CSSValueList::customCssText() + ")";
+ return result + CSSValueList::customCSSText() + ")";
}
CSSFilterValue::CSSFilterValue(const CSSFilterValue& cloneFrom)
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSFilterValue.h b/chromium/third_party/WebKit/Source/core/css/CSSFilterValue.h
index 3398cfa788b..7a2f80c1a4c 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSFilterValue.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSFilterValue.h
@@ -57,7 +57,7 @@ public:
return adoptRef(new CSSFilterValue(type));
}
- String customCssText() const;
+ String customCSSText() const;
FilterOperationType operationType() const { return m_type; }
@@ -72,6 +72,8 @@ private:
FilterOperationType m_type;
};
+DEFINE_CSS_VALUE_TYPE_CASTS(CSSFilterValue, isFilterValue());
+
}
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSFontFace.cpp b/chromium/third_party/WebKit/Source/core/css/CSSFontFace.cpp
index c667aaa185e..c21c9125afb 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSFontFace.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/CSSFontFace.cpp
@@ -26,15 +26,39 @@
#include "config.h"
#include "core/css/CSSFontFace.h"
-#include "core/css/CSSFontFaceSource.h"
#include "core/css/CSSFontSelector.h"
#include "core/css/CSSSegmentedFontFace.h"
#include "core/css/FontFaceSet.h"
#include "core/dom/Document.h"
-#include "core/platform/graphics/SimpleFontData.h"
+#include "core/frame/UseCounter.h"
+#include "platform/fonts/SimpleFontData.h"
namespace WebCore {
+CSSFontFace::~CSSFontFace()
+{
+ m_fontFace->cssFontFaceDestroyed();
+}
+
+PassRefPtr<CSSFontFace> CSSFontFace::createFromStyleRule(Document* document, const StyleRuleFontFace* fontFaceRule)
+{
+ RefPtr<FontFace> fontFace = FontFace::create(fontFaceRule);
+ if (!fontFace || fontFace->family().isEmpty())
+ return 0;
+
+ unsigned traitsMask = fontFace->traitsMask();
+ if (!traitsMask)
+ return 0;
+
+ // FIXME: Plumbing back into createCSSFontFace seems odd.
+ // Maybe move FontFace::createCSSFontFace logic here?
+ RefPtr<CSSFontFace> cssFontFace = fontFace->createCSSFontFace(document);
+ if (!cssFontFace || !cssFontFace->isValid())
+ return 0;
+
+ return cssFontFace;
+}
+
bool CSSFontFace::isLoaded() const
{
size_t size = m_sources.size();
@@ -67,13 +91,15 @@ void CSSFontFace::setSegmentedFontFace(CSSSegmentedFontFace* segmentedFontFace)
m_segmentedFontFace = segmentedFontFace;
}
-void CSSFontFace::beginLoadingFontSoon(FontResource* resource)
+void CSSFontFace::beginLoadIfNeeded(CSSFontFaceSource* source)
{
if (!m_segmentedFontFace)
return;
- CSSFontSelector* fontSelector = m_segmentedFontFace->fontSelector();
- fontSelector->beginLoadingFontSoon(resource);
+ if (source->resource() && source->resource()->stillNeedsLoad()) {
+ CSSFontSelector* fontSelector = m_segmentedFontFace->fontSelector();
+ fontSelector->beginLoadingFontSoon(source->resource());
+ }
if (loadStatus() == FontFace::Unloaded)
setLoadStatus(FontFace::Loading);
@@ -83,6 +109,7 @@ void CSSFontFace::fontLoaded(CSSFontFaceSource* source)
{
if (source != m_activeSource)
return;
+ m_activeSource = 0;
// FIXME: Can we assert that m_segmentedFontFace is non-null? That may
// require stopping in-progress font loading when the last
@@ -94,8 +121,11 @@ void CSSFontFace::fontLoaded(CSSFontFaceSource* source)
fontSelector->fontLoaded();
if (fontSelector->document() && loadStatus() == FontFace::Loading) {
- if (source->ensureFontData())
+ if (source->ensureFontData()) {
setLoadStatus(FontFace::Loaded);
+ if (source->isSVGFontFaceSource())
+ UseCounter::count(*fontSelector->document(), UseCounter::SVGFontInCSS);
+ }
else if (!isValid())
setLoadStatus(FontFace::Error);
}
@@ -103,18 +133,15 @@ void CSSFontFace::fontLoaded(CSSFontFaceSource* source)
m_segmentedFontFace->fontLoaded(this);
}
-PassRefPtr<SimpleFontData> CSSFontFace::getFontData(const FontDescription& fontDescription, bool syntheticBold, bool syntheticItalic)
+PassRefPtr<SimpleFontData> CSSFontFace::getFontData(const FontDescription& fontDescription)
{
m_activeSource = 0;
if (!isValid())
return 0;
- ASSERT(m_segmentedFontFace);
- CSSFontSelector* fontSelector = m_segmentedFontFace->fontSelector();
-
size_t size = m_sources.size();
for (size_t i = 0; i < size; ++i) {
- if (RefPtr<SimpleFontData> result = m_sources[i]->getFontData(fontDescription, syntheticBold, syntheticItalic, fontSelector)) {
+ if (RefPtr<SimpleFontData> result = m_sources[i]->getFontData(fontDescription)) {
m_activeSource = m_sources[i].get();
if (loadStatus() == FontFace::Unloaded && (m_sources[i]->isLoading() || m_sources[i]->isLoaded()))
setLoadStatus(FontFace::Loading);
@@ -133,18 +160,28 @@ PassRefPtr<SimpleFontData> CSSFontFace::getFontData(const FontDescription& fontD
void CSSFontFace::willUseFontData(const FontDescription& fontDescription)
{
- if (loadStatus() != FontFace::Unloaded)
+ if (loadStatus() != FontFace::Unloaded || m_activeSource)
+ return;
+
+ // Kicks off font load here only if the @font-face has no unicode-range.
+ // @font-faces with unicode-range will be loaded when a GlyphPage for the
+ // font is created.
+ // FIXME: Pass around the text to render from RenderText, and kick download
+ // if m_ranges intersects with the text. Make sure this does not cause
+ // performance regression.
+ if (!m_ranges.isEntireRange())
return;
ASSERT(m_segmentedFontFace);
- CSSFontSelector* fontSelector = m_segmentedFontFace->fontSelector();
size_t size = m_sources.size();
for (size_t i = 0; i < size; ++i) {
if (!m_sources[i]->isValid() || (m_sources[i]->isLocal() && !m_sources[i]->isLocalFontAvailable(fontDescription)))
continue;
- if (!m_sources[i]->isLocal())
- m_sources[i]->willUseFontData();
+ if (!m_sources[i]->isLocal() && !m_sources[i]->isLoaded()) {
+ m_activeSource = m_sources[i].get();
+ beginLoadIfNeeded(m_activeSource);
+ }
break;
}
}
@@ -154,35 +191,46 @@ void CSSFontFace::setLoadStatus(FontFace::LoadStatus newStatus)
ASSERT(m_fontFace);
m_fontFace->setLoadStatus(newStatus);
+ if (!m_segmentedFontFace)
+ return;
Document* document = m_segmentedFontFace->fontSelector()->document();
if (!document)
return;
switch (newStatus) {
case FontFace::Loading:
- document->fonts()->beginFontLoading(m_fontFace.get());
+ FontFaceSet::from(document)->beginFontLoading(m_fontFace.get());
break;
case FontFace::Loaded:
- document->fonts()->fontLoaded(m_fontFace.get());
+ FontFaceSet::from(document)->fontLoaded(m_fontFace.get());
break;
case FontFace::Error:
- document->fonts()->loadError(m_fontFace.get());
+ FontFaceSet::from(document)->loadError(m_fontFace.get());
break;
default:
break;
}
}
-#if ENABLE(SVG_FONTS)
-bool CSSFontFace::hasSVGFontFaceSource() const
+bool CSSFontFace::UnicodeRangeSet::intersectsWith(const String& text) const
{
- size_t size = m_sources.size();
- for (size_t i = 0; i < size; i++) {
- if (m_sources[i]->isSVGFontFaceSource())
- return true;
+ if (text.isEmpty())
+ return false;
+ if (isEntireRange())
+ return true;
+
+ // FIXME: This takes O(text.length() * m_ranges.size()) time. It would be
+ // better to make m_ranges sorted and use binary search.
+ unsigned index = 0;
+ while (index < text.length()) {
+ UChar32 c = text.characterStartingAt(index);
+ index += U16_LENGTH(c);
+ for (unsigned i = 0; i < m_ranges.size(); i++) {
+ if (m_ranges[i].contains(c))
+ return true;
+ }
}
return false;
}
-#endif
}
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSFontFace.h b/chromium/third_party/WebKit/Source/core/css/CSSFontFace.h
index 7ada75e14f8..e4ad5f048a1 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSFontFace.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSFontFace.h
@@ -36,21 +36,24 @@
namespace WebCore {
class CSSSegmentedFontFace;
+class Document;
class FontDescription;
-class FontResource;
class SimpleFontData;
+class StyleRuleFontFace;
// FIXME: Can this be a subclass of FontFace?
class CSSFontFace : public RefCounted<CSSFontFace> {
public:
static PassRefPtr<CSSFontFace> create(PassRefPtr<FontFace> fontFace) { return adoptRef(new CSSFontFace(fontFace)); }
+ static PassRefPtr<CSSFontFace> createFromStyleRule(Document*, const StyleRuleFontFace*);
- struct UnicodeRange;
+ class UnicodeRangeSet;
+
+ ~CSSFontFace();
FontFace* fontFace() const { return m_fontFace.get(); }
- void addRange(UChar32 from, UChar32 to) { m_ranges.append(UnicodeRange(from, to)); }
- const Vector<UnicodeRange>& ranges() const { return m_ranges; }
+ UnicodeRangeSet& ranges() { return m_ranges; }
void setSegmentedFontFace(CSSSegmentedFontFace*);
void clearSegmentedFontFace() { m_segmentedFontFace = 0; }
@@ -60,10 +63,10 @@ public:
void addSource(PassOwnPtr<CSSFontFaceSource>);
- void beginLoadingFontSoon(FontResource*);
+ void beginLoadIfNeeded(CSSFontFaceSource*);
void fontLoaded(CSSFontFaceSource*);
- PassRefPtr<SimpleFontData> getFontData(const FontDescription&, bool syntheticBold, bool syntheticItalic);
+ PassRefPtr<SimpleFontData> getFontData(const FontDescription&);
struct UnicodeRange {
UnicodeRange(UChar32 from, UChar32 to)
@@ -74,17 +77,25 @@ public:
UChar32 from() const { return m_from; }
UChar32 to() const { return m_to; }
+ bool contains(UChar32 c) const { return m_from <= c && c <= m_to; }
private:
UChar32 m_from;
UChar32 m_to;
};
-#if ENABLE(SVG_FONTS)
- bool hasSVGFontFaceSource() const;
-#endif
+ class UnicodeRangeSet {
+ public:
+ void add(UChar32 from, UChar32 to) { m_ranges.append(UnicodeRange(from, to)); }
+ bool intersectsWith(const String&) const;
+ bool isEntireRange() const { return m_ranges.isEmpty(); }
+ size_t size() const { return m_ranges.size(); }
+ const UnicodeRange& rangeAt(size_t i) const { return m_ranges[i]; }
+ private:
+ Vector<UnicodeRange> m_ranges; // If empty, represents the whole code space.
+ };
- FontFace::LoadStatus loadStatus() const { return m_fontFace ? m_fontFace->loadStatus() : FontFace::Loaded; }
+ FontFace::LoadStatus loadStatus() const { return m_fontFace->loadStatus(); }
void willUseFontData(const FontDescription&);
private:
@@ -93,10 +104,11 @@ private:
, m_activeSource(0)
, m_fontFace(fontFace)
{
+ ASSERT(m_fontFace);
}
void setLoadStatus(FontFace::LoadStatus);
- Vector<UnicodeRange> m_ranges;
+ UnicodeRangeSet m_ranges;
CSSSegmentedFontFace* m_segmentedFontFace;
Vector<OwnPtr<CSSFontFaceSource> > m_sources;
CSSFontFaceSource* m_activeSource;
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSFontFaceLoadEvent.cpp b/chromium/third_party/WebKit/Source/core/css/CSSFontFaceLoadEvent.cpp
index 58a5e4f5372..95aa3b27328 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSFontFaceLoadEvent.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/CSSFontFaceLoadEvent.cpp
@@ -58,7 +58,7 @@ CSSFontFaceLoadEvent::~CSSFontFaceLoadEvent()
const AtomicString& CSSFontFaceLoadEvent::interfaceName() const
{
- return eventNames().interfaceForCSSFontFaceLoadEvent;
+ return EventNames::CSSFontFaceLoadEvent;
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSFontFaceLoadEvent.h b/chromium/third_party/WebKit/Source/core/css/CSSFontFaceLoadEvent.h
index 84b674c3db6..e77ca32e86b 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSFontFaceLoadEvent.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSFontFaceLoadEvent.h
@@ -33,8 +33,8 @@
#include "core/css/FontFace.h"
#include "core/dom/DOMError.h"
-#include "core/dom/Event.h"
-#include "core/dom/EventNames.h"
+#include "core/events/Event.h"
+#include "core/events/ThreadLocalEventNames.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefPtr.h"
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSFontFaceLoadEvent.idl b/chromium/third_party/WebKit/Source/core/css/CSSFontFaceLoadEvent.idl
index 7ab2522c8ad..b77706c4ec6 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSFontFaceLoadEvent.idl
+++ b/chromium/third_party/WebKit/Source/core/css/CSSFontFaceLoadEvent.idl
@@ -31,7 +31,7 @@
// FIXME: Make this constructable from Javascript
[
NoInterfaceObject,
- EnabledAtRuntime=FontLoadEvents,
+ RuntimeEnabled=FontLoadEvents,
] interface CSSFontFaceLoadEvent : Event {
readonly attribute FontFace[] fontfaces;
};
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSFontFaceRule.cpp b/chromium/third_party/WebKit/Source/core/css/CSSFontFaceRule.cpp
index f6cda03c95f..d6357bd3250 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSFontFaceRule.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/CSSFontFaceRule.cpp
@@ -63,8 +63,7 @@ String CSSFontFaceRule::cssText() const
void CSSFontFaceRule::reattach(StyleRuleBase* rule)
{
ASSERT(rule);
- ASSERT_WITH_SECURITY_IMPLICATION(rule->isFontFaceRule());
- m_fontFaceRule = static_cast<StyleRuleFontFace*>(rule);
+ m_fontFaceRule = toStyleRuleFontFace(rule);
if (m_propertiesCSSOMWrapper)
m_propertiesCSSOMWrapper->reattach(m_fontFaceRule->mutableProperties());
}
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSFontFaceRule.h b/chromium/third_party/WebKit/Source/core/css/CSSFontFaceRule.h
index 1be5c3a721c..0b88f9b2eee 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSFontFaceRule.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSFontFaceRule.h
@@ -51,11 +51,7 @@ private:
mutable RefPtr<StyleRuleCSSStyleDeclaration> m_propertiesCSSOMWrapper;
};
-inline CSSFontFaceRule* toCSSFontFaceRule(CSSRule* rule)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(rule->type() == CSSRule::FONT_FACE_RULE);
- return static_cast<CSSFontFaceRule*>(rule);
-}
+DEFINE_CSS_RULE_TYPE_CASTS(CSSFontFaceRule, FONT_FACE_RULE);
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSFontFaceSource.cpp b/chromium/third_party/WebKit/Source/core/css/CSSFontFaceSource.cpp
index 7fe19c9c864..d235aea7edf 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSFontFaceSource.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/CSSFontFaceSource.cpp
@@ -26,13 +26,13 @@
#include "config.h"
#include "core/css/CSSFontFaceSource.h"
+#include "RuntimeEnabledFeatures.h"
+#include "core/css/CSSCustomFontData.h"
#include "core/css/CSSFontFace.h"
-#include "core/css/CSSFontSelector.h"
-#include "core/fetch/FontResource.h"
-#include "core/platform/HistogramSupport.h"
-#include "core/platform/graphics/FontCache.h"
-#include "core/platform/graphics/FontDescription.h"
-#include "core/platform/graphics/SimpleFontData.h"
+#include "platform/fonts/FontCache.h"
+#include "platform/fonts/FontDescription.h"
+#include "platform/fonts/SimpleFontData.h"
+#include "public/platform/Platform.h"
#include "wtf/CurrentTime.h"
#if ENABLE(SVG_FONTS)
@@ -69,8 +69,9 @@ void CSSFontFaceSource::pruneTable()
return;
for (FontDataTable::iterator it = m_fontDataTable.begin(); it != m_fontDataTable.end(); ++it) {
- if (SimpleFontData* fontData = it->value.get())
- fontData->clearCSSFontFaceSource();
+ SimpleFontData* fontData = it->value.get();
+ if (fontData && fontData->customFontData())
+ fontData->customFontData()->clearCSSFontFaceSource();
}
m_fontDataTable.clear();
}
@@ -125,7 +126,7 @@ void CSSFontFaceSource::fontLoaded(FontResource*)
m_face->fontLoaded(this);
}
-PassRefPtr<SimpleFontData> CSSFontFaceSource::getFontData(const FontDescription& fontDescription, bool syntheticBold, bool syntheticItalic, CSSFontSelector* fontSelector)
+PassRefPtr<SimpleFontData> CSSFontFaceSource::getFontData(const FontDescription& fontDescription)
{
// If the font hasn't loaded or an error occurred, then we've got nothing.
if (!isValid())
@@ -134,16 +135,16 @@ PassRefPtr<SimpleFontData> CSSFontFaceSource::getFontData(const FontDescription&
if (isLocal()) {
// We're local. Just return a SimpleFontData from the normal cache.
// We don't want to check alternate font family names here, so pass true as the checkingAlternateName parameter.
- RefPtr<SimpleFontData> fontData = fontCache()->getFontResourceData(fontDescription, m_string, true);
+ RefPtr<SimpleFontData> fontData = FontCache::fontCache()->getFontData(fontDescription, m_string, true);
m_histograms.recordLocalFont(fontData);
return fontData;
}
// See if we have a mapping in our FontData cache.
- unsigned hashKey = (fontDescription.computedPixelSize() + 1) << 5 | fontDescription.widthVariant() << 3
- | (fontDescription.orientation() == Vertical ? 4 : 0) | (syntheticBold ? 2 : 0) | (syntheticItalic ? 1 : 0);
+ AtomicString emptyFontFamily = "";
+ FontCacheKey key = fontDescription.cacheKey(emptyFontFamily);
- RefPtr<SimpleFontData>& fontData = m_fontDataTable.add(hashKey, 0).iterator->value;
+ RefPtr<SimpleFontData>& fontData = m_fontDataTable.add(key.hash(), 0).iterator->value;
if (fontData)
return fontData; // No release, because fontData is a reference to a RefPtr that is held in the m_fontDataTable.
@@ -184,7 +185,11 @@ PassRefPtr<SimpleFontData> CSSFontFaceSource::getFontData(const FontDescription&
m_svgFontFaceElement = fontFaceElement;
}
- fontData = SimpleFontData::create(SVGFontData::create(fontFaceElement), fontDescription.computedPixelSize(), syntheticBold, syntheticItalic);
+ fontData = SimpleFontData::create(
+ SVGFontData::create(fontFaceElement),
+ fontDescription.effectiveFontSize(),
+ fontDescription.isSyntheticBold(),
+ fontDescription.isSyntheticItalic());
}
} else
#endif
@@ -193,22 +198,30 @@ PassRefPtr<SimpleFontData> CSSFontFaceSource::getFontData(const FontDescription&
if (!m_font->ensureCustomFontData())
return 0;
- fontData = SimpleFontData::create(m_font->platformDataFromCustomData(fontDescription.computedPixelSize(), syntheticBold, syntheticItalic,
- fontDescription.orientation(), fontDescription.widthVariant()), true, false);
+ fontData = SimpleFontData::create(
+ m_font->platformDataFromCustomData(fontDescription.effectiveFontSize(),
+ fontDescription.isSyntheticBold(), fontDescription.isSyntheticItalic(),
+ fontDescription.orientation(), fontDescription.widthVariant()), CustomFontData::create(false));
}
} else {
#if ENABLE(SVG_FONTS)
// In-Document SVG Fonts
- if (m_svgFontFaceElement)
- fontData = SimpleFontData::create(SVGFontData::create(m_svgFontFaceElement.get()), fontDescription.computedPixelSize(), syntheticBold, syntheticItalic);
+ if (m_svgFontFaceElement) {
+ fontData = SimpleFontData::create(
+ SVGFontData::create(m_svgFontFaceElement.get()),
+ fontDescription.effectiveFontSize(),
+ fontDescription.isSyntheticBold(),
+ fontDescription.isSyntheticItalic());
+ }
#endif
}
} else {
// This temporary font is not retained and should not be returned.
FontCachePurgePreventer fontCachePurgePreventer;
- SimpleFontData* temporaryFont = fontCache()->getNonRetainedLastResortFallbackFont(fontDescription);
- fontData = SimpleFontData::create(temporaryFont->platformData(), true, true);
- fontData->setCSSFontFaceSource(this);
+ SimpleFontData* temporaryFont = FontCache::fontCache()->getNonRetainedLastResortFallbackFont(fontDescription);
+ RefPtr<CSSCustomFontData> cssFontData = CSSCustomFontData::create(true);
+ cssFontData->setCSSFontFaceSource(this);
+ fontData = SimpleFontData::create(temporaryFont->platformData(), cssFontData);
}
return fontData; // No release, because fontData is a reference to a RefPtr that is held in the m_fontDataTable.
@@ -231,13 +244,6 @@ bool CSSFontFaceSource::isSVGFontFaceSource() const
}
#endif
-bool CSSFontFaceSource::isDecodeError() const
-{
- if (m_font)
- return m_font->status() == Resource::DecodeError;
- return false;
-}
-
bool CSSFontFaceSource::ensureFontData()
{
if (!m_font)
@@ -253,20 +259,13 @@ bool CSSFontFaceSource::isLocalFontAvailable(const FontDescription& fontDescript
{
if (!isLocal())
return false;
- return fontCache()->isPlatformFontAvailable(fontDescription, m_string, true);
+ return FontCache::fontCache()->isPlatformFontAvailable(fontDescription, m_string);
}
-void CSSFontFaceSource::willUseFontData()
+void CSSFontFaceSource::beginLoadIfNeeded()
{
- if (m_font)
- m_font->willUseFontData();
-}
-
-void CSSFontFaceSource::beginLoadingFontSoon()
-{
- ASSERT(m_face);
- ASSERT(m_font);
- m_face->beginLoadingFontSoon(m_font.get());
+ if (m_face && m_font)
+ m_face->beginLoadIfNeeded(this);
}
void CSSFontFaceSource::FontLoadHistograms::loadStarted()
@@ -278,7 +277,7 @@ void CSSFontFaceSource::FontLoadHistograms::loadStarted()
void CSSFontFaceSource::FontLoadHistograms::recordLocalFont(bool loadSuccess)
{
if (!m_loadStartTime) {
- HistogramSupport::histogramEnumeration("WebFont.LocalFontUsed", loadSuccess ? 1 : 0, 2);
+ blink::Platform::current()->histogramEnumeration("WebFont.LocalFontUsed", loadSuccess ? 1 : 0, 2);
m_loadStartTime = -1; // Do not count this font again.
}
}
@@ -287,8 +286,14 @@ void CSSFontFaceSource::FontLoadHistograms::recordRemoteFont(const FontResource*
{
if (m_loadStartTime > 0 && font && !font->isLoading()) {
int duration = static_cast<int>(currentTimeMS() - m_loadStartTime);
- HistogramSupport::histogramCustomCounts(histogramName(font), duration, 0, 10000, 50);
+ blink::Platform::current()->histogramCustomCounts(histogramName(font), duration, 0, 10000, 50);
m_loadStartTime = -1;
+
+ enum { Miss, Hit, DataUrl, CacheHitEnumMax };
+ int histogramValue = font->url().protocolIsData() ? DataUrl
+ : font->response().wasCached() ? Hit
+ : Miss;
+ blink::Platform::current()->histogramEnumeration("WebFont.CacheHit", histogramValue, CacheHitEnumMax);
}
}
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSFontFaceSource.h b/chromium/third_party/WebKit/Source/core/css/CSSFontFaceSource.h
index 6cdabfd488f..8ba3f027534 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSFontFaceSource.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSFontFaceSource.h
@@ -28,7 +28,7 @@
#include "core/fetch/FontResource.h"
#include "core/fetch/ResourcePtr.h"
-#include "core/platform/Timer.h"
+#include "platform/Timer.h"
#include "wtf/HashMap.h"
#include "wtf/text/AtomicString.h"
@@ -36,7 +36,6 @@ namespace WebCore {
class FontResource;
class CSSFontFace;
-class CSSFontSelector;
class FontDescription;
class SimpleFontData;
#if ENABLE(SVG_FONTS)
@@ -55,16 +54,13 @@ public:
bool isLoaded() const;
bool isValid() const;
- const AtomicString& string() const { return m_string; }
-
+ FontResource* resource() { return m_font.get(); }
void setFontFace(CSSFontFace* face) { m_face = face; }
virtual void didStartFontLoad(FontResource*) OVERRIDE;
virtual void fontLoaded(FontResource*);
- PassRefPtr<SimpleFontData> getFontData(const FontDescription&, bool syntheticBold, bool syntheticItalic, CSSFontSelector*);
-
- void pruneTable();
+ PassRefPtr<SimpleFontData> getFontData(const FontDescription&);
#if ENABLE(SVG_FONTS)
SVGFontFaceElement* svgFontFaceElement() const;
@@ -73,11 +69,9 @@ public:
void setHasExternalSVGFont(bool value) { m_hasExternalSVGFont = value; }
#endif
- bool isDecodeError() const;
bool ensureFontData();
bool isLocalFontAvailable(const FontDescription&);
- void willUseFontData();
- void beginLoadingFontSoon();
+ void beginLoadIfNeeded();
private:
typedef HashMap<unsigned, RefPtr<SimpleFontData> > FontDataTable; // The hash key is composed of size synthetic styles.
@@ -85,7 +79,6 @@ private:
class FontLoadHistograms {
public:
FontLoadHistograms() : m_loadStartTime(0) { }
- void willUseFontData();
void loadStarted();
void recordLocalFont(bool loadSuccess);
void recordRemoteFont(const FontResource*);
@@ -94,6 +87,7 @@ private:
double m_loadStartTime;
};
+ void pruneTable();
void startLoadingTimerFired(Timer<CSSFontFaceSource>*);
AtomicString m_string; // URI for remote, built-in font name for local.
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSFontFaceSrcValue.cpp b/chromium/third_party/WebKit/Source/core/css/CSSFontFaceSrcValue.cpp
index 5f6eb074600..9e7f212554a 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSFontFaceSrcValue.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/CSSFontFaceSrcValue.cpp
@@ -33,8 +33,8 @@
#include "core/fetch/FetchRequest.h"
#include "core/fetch/FontResource.h"
#include "core/fetch/ResourceFetcher.h"
-#include "core/platform/graphics/FontCustomPlatformData.h"
#include "core/svg/SVGFontFaceElement.h"
+#include "platform/fonts/FontCustomPlatformData.h"
#include "wtf/text/StringBuilder.h"
namespace WebCore {
@@ -64,7 +64,7 @@ bool CSSFontFaceSrcValue::isSupportedFormat() const
;
}
-String CSSFontFaceSrcValue::customCssText() const
+String CSSFontFaceSrcValue::customCSSText() const
{
StringBuilder result;
if (isLocal())
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSFontFaceSrcValue.h b/chromium/third_party/WebKit/Source/core/css/CSSFontFaceSrcValue.h
index 992448e9891..1be94d687ff 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSFontFaceSrcValue.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSFontFaceSrcValue.h
@@ -63,7 +63,7 @@ public:
void setSVGFontFaceElement(SVGFontFaceElement* element) { m_svgFontFaceElement = element; }
#endif
- String customCssText() const;
+ String customCSSText() const;
void addSubresourceStyleURLs(ListHashSet<KURL>&, const StyleSheetContents*) const;
@@ -95,11 +95,7 @@ private:
#endif
};
-inline CSSFontFaceSrcValue* toCSSFontFaceSrcValue(CSSValue* value)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!value || value->isFontFaceSrcValue());
- return static_cast<CSSFontFaceSrcValue*>(value);
-}
+DEFINE_CSS_VALUE_TYPE_CASTS(CSSFontFaceSrcValue, isFontFaceSrcValue());
}
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSFontFeatureValue.cpp b/chromium/third_party/WebKit/Source/core/css/CSSFontFeatureValue.cpp
new file mode 100644
index 00000000000..4b863b3a00b
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/css/CSSFontFeatureValue.cpp
@@ -0,0 +1,55 @@
+/*
+ * Copyright (C) 2011 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/css/CSSFontFeatureValue.h"
+
+#include "wtf/text/StringBuilder.h"
+
+namespace WebCore {
+
+CSSFontFeatureValue::CSSFontFeatureValue(const AtomicString& tag, int value)
+ : CSSValue(FontFeatureClass)
+ , m_tag(tag)
+ , m_value(value)
+{
+}
+
+String CSSFontFeatureValue::customCSSText() const
+{
+ StringBuilder builder;
+ builder.append('\'');
+ builder.append(m_tag);
+ builder.appendLiteral("' ");
+ builder.appendNumber(m_value);
+ return builder.toString();
+}
+
+bool CSSFontFeatureValue::equals(const CSSFontFeatureValue& other) const
+{
+ return m_tag == other.m_tag && m_value == other.m_value;
+}
+
+}
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSFontFeatureValue.h b/chromium/third_party/WebKit/Source/core/css/CSSFontFeatureValue.h
new file mode 100644
index 00000000000..8a0367fabe3
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/css/CSSFontFeatureValue.h
@@ -0,0 +1,58 @@
+/*
+ * Copyright (C) 2011 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef CSSFontFeatureValue_h
+#define CSSFontFeatureValue_h
+
+#include "core/css/CSSValue.h"
+#include "wtf/text/WTFString.h"
+
+namespace WebCore {
+
+class CSSFontFeatureValue : public CSSValue {
+public:
+ static PassRefPtr<CSSFontFeatureValue> create(const AtomicString& tag, int value)
+ {
+ return adoptRef(new CSSFontFeatureValue(tag, value));
+ }
+
+ const AtomicString& tag() const { return m_tag; }
+ int value() const { return m_value; }
+ String customCSSText() const;
+
+ bool equals(const CSSFontFeatureValue&) const;
+
+private:
+ CSSFontFeatureValue(const AtomicString& tag, int value);
+
+ AtomicString m_tag;
+ const int m_value;
+};
+
+DEFINE_CSS_VALUE_TYPE_CASTS(CSSFontFeatureValue, isFontFeatureValue());
+
+} // namespace
+
+#endif
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSFontSelector.cpp b/chromium/third_party/WebKit/Source/core/css/CSSFontSelector.cpp
index bfe6bfefa74..166e2c3e4ba 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSFontSelector.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/CSSFontSelector.cpp
@@ -27,7 +27,6 @@
#include "config.h"
#include "core/css/CSSFontSelector.h"
-#include "FontFamilyNames.h"
#include "RuntimeEnabledFeatures.h"
#include "core/css/CSSFontFace.h"
#include "core/css/CSSFontFaceRule.h"
@@ -39,86 +38,91 @@
#include "core/fetch/FontResource.h"
#include "core/fetch/ResourceFetcher.h"
#include "core/loader/FrameLoader.h"
-#include "core/page/Frame.h"
-#include "core/page/Settings.h"
-#include "core/platform/graphics/FontCache.h"
-#include "core/platform/graphics/SimpleFontData.h"
+#include "core/frame/Frame.h"
+#include "core/frame/Settings.h"
+#include "platform/fonts/FontCache.h"
+#include "platform/fonts/SimpleFontData.h"
#include "wtf/text/AtomicString.h"
using namespace std;
namespace WebCore {
-CSSFontSelector::CSSFontSelector(Document* document)
- : m_document(document)
- , m_beginLoadingTimer(this, &CSSFontSelector::beginLoadTimerFired)
- , m_version(0)
+FontLoader::FontLoader(ResourceFetcher* resourceFetcher)
+ : m_beginLoadingTimer(this, &FontLoader::beginLoadTimerFired)
+ , m_resourceFetcher(resourceFetcher)
{
- // FIXME: An old comment used to say there was no need to hold a reference to m_document
- // because "we are guaranteed to be destroyed before the document". But there does not
- // seem to be any such guarantee.
-
- ASSERT(m_document);
- fontCache()->addClient(this);
}
-CSSFontSelector::~CSSFontSelector()
+void FontLoader::addFontToBeginLoading(FontResource* fontResource)
{
- clearDocument();
- fontCache()->removeClient(this);
+ if (!m_resourceFetcher || !fontResource->stillNeedsLoad())
+ return;
+
+ m_fontsToBeginLoading.append(fontResource);
+ // FIXME: Use RequestCountTracker??!!
+ // Increment the request count now, in order to prevent didFinishLoad from being dispatched
+ // after this font has been requested but before it began loading. Balanced by
+ // decrementRequestCount() in beginLoadTimerFired() and in clearDocument().
+ m_resourceFetcher->incrementRequestCount(fontResource);
+ m_beginLoadingTimer.startOneShot(0);
}
-bool CSSFontSelector::isEmpty() const
+void FontLoader::beginLoadTimerFired(Timer<WebCore::FontLoader>*)
{
- return m_fonts.isEmpty();
+ loadPendingFonts();
}
-void CSSFontSelector::addFontFaceRule(const StyleRuleFontFace* fontFaceRule)
+void FontLoader::loadPendingFonts()
{
- RefPtr<FontFace> fontFace = FontFace::create(fontFaceRule);
- if (!fontFace || fontFace->family().isEmpty())
- return;
-
- unsigned traitsMask = fontFace->traitsMask();
- if (!traitsMask)
- return;
-
- RefPtr<CSSFontFace> cssFontFace = fontFace->createCSSFontFace(m_document);
- if (!cssFontFace || !cssFontFace->isValid())
- return;
+ ASSERT(m_resourceFetcher);
- OwnPtr<HashMap<unsigned, RefPtr<CSSSegmentedFontFace> > >& familyFontFaces = m_fontFaces.add(fontFace->family(), nullptr).iterator->value;
- if (!familyFontFaces) {
- familyFontFaces = adoptPtr(new HashMap<unsigned, RefPtr<CSSSegmentedFontFace> >);
-
- ASSERT(!m_locallyInstalledFontFaces.contains(fontFace->family()));
+ Vector<ResourcePtr<FontResource> > fontsToBeginLoading;
+ fontsToBeginLoading.swap(m_fontsToBeginLoading);
- Vector<unsigned> locallyInstalledFontsTraitsMasks;
- fontCache()->getTraitsInFamily(fontFace->family(), locallyInstalledFontsTraitsMasks);
- if (unsigned numLocallyInstalledFaces = locallyInstalledFontsTraitsMasks.size()) {
- OwnPtr<Vector<RefPtr<CSSSegmentedFontFace> > > familyLocallyInstalledFaces = adoptPtr(new Vector<RefPtr<CSSSegmentedFontFace> >);
+ for (size_t i = 0; i < fontsToBeginLoading.size(); ++i) {
+ fontsToBeginLoading[i]->beginLoadIfNeeded(m_resourceFetcher);
+ // Balances incrementRequestCount() in beginLoadingFontSoon().
+ m_resourceFetcher->decrementRequestCount(fontsToBeginLoading[i].get());
+ }
+}
- for (unsigned i = 0; i < numLocallyInstalledFaces; ++i) {
- RefPtr<CSSFontFace> locallyInstalledFontFace = CSSFontFace::create(0);
- locallyInstalledFontFace->addSource(adoptPtr(new CSSFontFaceSource(fontFace->family())));
- ASSERT(locallyInstalledFontFace->isValid());
+void FontLoader::clearResourceFetcher()
+{
+ if (!m_resourceFetcher) {
+ ASSERT(m_fontsToBeginLoading.isEmpty());
+ return;
+ }
- RefPtr<CSSSegmentedFontFace> segmentedFontFace = CSSSegmentedFontFace::create(this, static_cast<FontTraitsMask>(locallyInstalledFontsTraitsMasks[i]), true);
- segmentedFontFace->appendFontFace(locallyInstalledFontFace.release());
- familyLocallyInstalledFaces->append(segmentedFontFace);
- }
+ m_beginLoadingTimer.stop();
- m_locallyInstalledFontFaces.set(fontFace->family(), familyLocallyInstalledFaces.release());
- }
+ for (size_t i = 0; i < m_fontsToBeginLoading.size(); ++i) {
+ // Balances incrementRequestCount() in beginLoadingFontSoon().
+ m_resourceFetcher->decrementRequestCount(m_fontsToBeginLoading[i].get());
}
- RefPtr<CSSSegmentedFontFace>& segmentedFontFace = familyFontFaces->add(traitsMask, 0).iterator->value;
- if (!segmentedFontFace)
- segmentedFontFace = CSSSegmentedFontFace::create(this, static_cast<FontTraitsMask>(traitsMask), false);
+ m_fontsToBeginLoading.clear();
+ m_resourceFetcher = 0;
+}
- segmentedFontFace->appendFontFace(cssFontFace);
+CSSFontSelector::CSSFontSelector(Document* document)
+ : m_document(document)
+ , m_fontLoader(document->fetcher())
+ , m_genericFontFamilySettings(document->frame()->settings()->genericFontFamilySettings())
+{
+ // FIXME: An old comment used to say there was no need to hold a reference to m_document
+ // because "we are guaranteed to be destroyed before the document". But there does not
+ // seem to be any such guarantee.
+
+ ASSERT(m_document);
+ ASSERT(m_document->frame());
+ FontCache::fontCache()->addClient(this);
+}
- ++m_version;
+CSSFontSelector::~CSSFontSelector()
+{
+ clearDocument();
+ FontCache::fontCache()->removeClient(this);
}
void CSSFontSelector::registerForInvalidationCallbacks(FontSelectorClient* client)
@@ -137,15 +141,6 @@ void CSSFontSelector::dispatchInvalidationCallbacks()
copyToVector(m_clients, clients);
for (size_t i = 0; i < clients.size(); ++i)
clients[i]->fontsNeedUpdate(this);
-
- // FIXME: Make Document a FontSelectorClient so that it can simply register for invalidation callbacks.
- if (!m_document)
- return;
- if (StyleResolver* styleResolver = m_document->styleResolverIfExists())
- styleResolver->invalidateMatchedPropertiesCache();
- if (!m_document->renderer())
- return;
- m_document->setNeedsStyleRecalc();
}
void CSSFontSelector::fontLoaded()
@@ -158,189 +153,60 @@ void CSSFontSelector::fontCacheInvalidated()
dispatchInvalidationCallbacks();
}
-static PassRefPtr<FontData> fontDataForGenericFamily(Document* document, const FontDescription& fontDescription, const AtomicString& familyName)
+void CSSFontSelector::addFontFaceRule(const StyleRuleFontFace* fontFaceRule, PassRefPtr<CSSFontFace> cssFontFace)
{
- if (!document || !document->frame())
- return 0;
-
- const Settings* settings = document->frame()->settings();
- if (!settings)
- return 0;
-
- AtomicString genericFamily;
- UScriptCode script = fontDescription.script();
-
- if (familyName == serifFamily)
- genericFamily = settings->serifFontFamily(script);
- else if (familyName == sansSerifFamily)
- genericFamily = settings->sansSerifFontFamily(script);
- else if (familyName == cursiveFamily)
- genericFamily = settings->cursiveFontFamily(script);
- else if (familyName == fantasyFamily)
- genericFamily = settings->fantasyFontFamily(script);
- else if (familyName == monospaceFamily)
- genericFamily = settings->fixedFontFamily(script);
- else if (familyName == pictographFamily)
- genericFamily = settings->pictographFontFamily(script);
- else if (familyName == standardFamily)
- genericFamily = settings->standardFontFamily(script);
-
- if (!genericFamily.isEmpty())
- return fontCache()->getFontResourceData(fontDescription, genericFamily);
-
- return 0;
+ m_cssSegmentedFontFaceCache.add(this, fontFaceRule, cssFontFace);
}
-static inline bool compareFontFaces(CSSSegmentedFontFace* first, CSSSegmentedFontFace* second, FontTraitsMask desiredTraitsMask)
+void CSSFontSelector::removeFontFaceRule(const StyleRuleFontFace* fontFaceRule)
{
- FontTraitsMask firstTraitsMask = first->traitsMask();
- FontTraitsMask secondTraitsMask = second->traitsMask();
-
- bool firstHasDesiredVariant = firstTraitsMask & desiredTraitsMask & FontVariantMask;
- bool secondHasDesiredVariant = secondTraitsMask & desiredTraitsMask & FontVariantMask;
-
- if (firstHasDesiredVariant != secondHasDesiredVariant)
- return firstHasDesiredVariant;
-
- // We need to check font-variant css property for CSS2.1 compatibility.
- if ((desiredTraitsMask & FontVariantSmallCapsMask) && !first->isLocalFallback() && !second->isLocalFallback()) {
- // Prefer a font that has indicated that it can only support small-caps to a font that claims to support
- // all variants. The specialized font is more likely to be true small-caps and not require synthesis.
- bool firstRequiresSmallCaps = (firstTraitsMask & FontVariantSmallCapsMask) && !(firstTraitsMask & FontVariantNormalMask);
- bool secondRequiresSmallCaps = (secondTraitsMask & FontVariantSmallCapsMask) && !(secondTraitsMask & FontVariantNormalMask);
- if (firstRequiresSmallCaps != secondRequiresSmallCaps)
- return firstRequiresSmallCaps;
- }
-
- bool firstHasDesiredStyle = firstTraitsMask & desiredTraitsMask & FontStyleMask;
- bool secondHasDesiredStyle = secondTraitsMask & desiredTraitsMask & FontStyleMask;
-
- if (firstHasDesiredStyle != secondHasDesiredStyle)
- return firstHasDesiredStyle;
-
- if ((desiredTraitsMask & FontStyleItalicMask) && !first->isLocalFallback() && !second->isLocalFallback()) {
- // Prefer a font that has indicated that it can only support italics to a font that claims to support
- // all styles. The specialized font is more likely to be the one the author wants used.
- bool firstRequiresItalics = (firstTraitsMask & FontStyleItalicMask) && !(firstTraitsMask & FontStyleNormalMask);
- bool secondRequiresItalics = (secondTraitsMask & FontStyleItalicMask) && !(secondTraitsMask & FontStyleNormalMask);
- if (firstRequiresItalics != secondRequiresItalics)
- return firstRequiresItalics;
- }
-
- if (secondTraitsMask & desiredTraitsMask & FontWeightMask)
- return false;
- if (firstTraitsMask & desiredTraitsMask & FontWeightMask)
- return true;
-
- // http://www.w3.org/TR/2011/WD-css3-fonts-20111004/#font-matching-algorithm says :
- // - If the desired weight is less than 400, weights below the desired weight are checked in descending order followed by weights above the desired weight in ascending order until a match is found.
- // - If the desired weight is greater than 500, weights above the desired weight are checked in ascending order followed by weights below the desired weight in descending order until a match is found.
- // - If the desired weight is 400, 500 is checked first and then the rule for desired weights less than 400 is used.
- // - If the desired weight is 500, 400 is checked first and then the rule for desired weights less than 400 is used.
-
- static const unsigned fallbackRuleSets = 9;
- static const unsigned rulesPerSet = 8;
- static const FontTraitsMask weightFallbackRuleSets[fallbackRuleSets][rulesPerSet] = {
- { FontWeight200Mask, FontWeight300Mask, FontWeight400Mask, FontWeight500Mask, FontWeight600Mask, FontWeight700Mask, FontWeight800Mask, FontWeight900Mask },
- { FontWeight100Mask, FontWeight300Mask, FontWeight400Mask, FontWeight500Mask, FontWeight600Mask, FontWeight700Mask, FontWeight800Mask, FontWeight900Mask },
- { FontWeight200Mask, FontWeight100Mask, FontWeight400Mask, FontWeight500Mask, FontWeight600Mask, FontWeight700Mask, FontWeight800Mask, FontWeight900Mask },
- { FontWeight500Mask, FontWeight300Mask, FontWeight200Mask, FontWeight100Mask, FontWeight600Mask, FontWeight700Mask, FontWeight800Mask, FontWeight900Mask },
- { FontWeight400Mask, FontWeight300Mask, FontWeight200Mask, FontWeight100Mask, FontWeight600Mask, FontWeight700Mask, FontWeight800Mask, FontWeight900Mask },
- { FontWeight700Mask, FontWeight800Mask, FontWeight900Mask, FontWeight500Mask, FontWeight400Mask, FontWeight300Mask, FontWeight200Mask, FontWeight100Mask },
- { FontWeight800Mask, FontWeight900Mask, FontWeight600Mask, FontWeight500Mask, FontWeight400Mask, FontWeight300Mask, FontWeight200Mask, FontWeight100Mask },
- { FontWeight900Mask, FontWeight700Mask, FontWeight600Mask, FontWeight500Mask, FontWeight400Mask, FontWeight300Mask, FontWeight200Mask, FontWeight100Mask },
- { FontWeight800Mask, FontWeight700Mask, FontWeight600Mask, FontWeight500Mask, FontWeight400Mask, FontWeight300Mask, FontWeight200Mask, FontWeight100Mask }
- };
-
- unsigned ruleSetIndex = 0;
- unsigned w = FontWeight100Bit;
- while (!(desiredTraitsMask & (1 << w))) {
- w++;
- ruleSetIndex++;
- }
+ m_cssSegmentedFontFaceCache.remove(fontFaceRule);
+}
- ASSERT(ruleSetIndex < fallbackRuleSets);
- const FontTraitsMask* weightFallbackRule = weightFallbackRuleSets[ruleSetIndex];
- for (unsigned i = 0; i < rulesPerSet; ++i) {
- if (secondTraitsMask & weightFallbackRule[i])
- return false;
- if (firstTraitsMask & weightFallbackRule[i])
- return true;
- }
+static AtomicString familyNameFromSettings(const GenericFontFamilySettings& settings, const FontDescription& fontDescription, const AtomicString& genericFamilyName)
+{
+ UScriptCode script = fontDescription.script();
- return false;
+ if (fontDescription.genericFamily() == FontDescription::StandardFamily && !fontDescription.isSpecifiedFont())
+ return settings.standard(script);
+
+#if OS(ANDROID)
+ return FontCache::getGenericFamilyNameForScript(genericFamilyName, script);
+#else
+ if (genericFamilyName == FontFamilyNames::webkit_serif)
+ return settings.serif(script);
+ if (genericFamilyName == FontFamilyNames::webkit_sans_serif)
+ return settings.sansSerif(script);
+ if (genericFamilyName == FontFamilyNames::webkit_cursive)
+ return settings.cursive(script);
+ if (genericFamilyName == FontFamilyNames::webkit_fantasy)
+ return settings.fantasy(script);
+ if (genericFamilyName == FontFamilyNames::webkit_monospace)
+ return settings.fixed(script);
+ if (genericFamilyName == FontFamilyNames::webkit_pictograph)
+ return settings.pictograph(script);
+ if (genericFamilyName == FontFamilyNames::webkit_standard)
+ return settings.standard(script);
+#endif
+ return emptyAtom;
}
PassRefPtr<FontData> CSSFontSelector::getFontData(const FontDescription& fontDescription, const AtomicString& familyName)
{
- if (m_fontFaces.isEmpty()) {
- if (familyName.startsWith("-webkit-"))
- return fontDataForGenericFamily(m_document, fontDescription, familyName);
- if (fontDescription.genericFamily() == FontDescription::StandardFamily && !fontDescription.isSpecifiedFont())
- return fontDataForGenericFamily(m_document, fontDescription, "-webkit-standard");
- return 0;
- }
+ if (CSSSegmentedFontFace* face = m_cssSegmentedFontFaceCache.get(fontDescription, familyName))
+ return face->getFontData(fontDescription);
- CSSSegmentedFontFace* face = getFontFace(fontDescription, familyName);
- // If no face was found, then return 0 and let the OS come up with its best match for the name.
- if (!face) {
- // If we were handed a generic family, but there was no match, go ahead and return the correct font based off our
- // settings.
- if (fontDescription.genericFamily() == FontDescription::StandardFamily && !fontDescription.isSpecifiedFont())
- return fontDataForGenericFamily(m_document, fontDescription, "-webkit-standard");
- return fontDataForGenericFamily(m_document, fontDescription, familyName);
- }
+ // Try to return the correct font based off our settings, in case we were handed the generic font family name.
+ AtomicString settingsFamilyName = familyNameFromSettings(m_genericFontFamilySettings, fontDescription, familyName);
+ if (settingsFamilyName.isEmpty())
+ return 0;
- // We have a face. Ask it for a font data. If it cannot produce one, it will fail, and the OS will take over.
- return face->getFontData(fontDescription);
+ return FontCache::fontCache()->getFontData(fontDescription, settingsFamilyName);
}
-CSSSegmentedFontFace* CSSFontSelector::getFontFace(const FontDescription& fontDescription, const AtomicString& family)
+CSSSegmentedFontFace* CSSFontSelector::getFontFace(const FontDescription& fontDescription, const AtomicString& familyName)
{
- HashMap<unsigned, RefPtr<CSSSegmentedFontFace> >* familyFontFaces = m_fontFaces.get(family);
- if (!familyFontFaces || familyFontFaces->isEmpty())
- return 0;
-
- OwnPtr<HashMap<unsigned, RefPtr<CSSSegmentedFontFace> > >& segmentedFontFaceCache = m_fonts.add(family, nullptr).iterator->value;
- if (!segmentedFontFaceCache)
- segmentedFontFaceCache = adoptPtr(new HashMap<unsigned, RefPtr<CSSSegmentedFontFace> >);
-
- FontTraitsMask traitsMask = fontDescription.traitsMask();
-
- RefPtr<CSSSegmentedFontFace>& face = segmentedFontFaceCache->add(traitsMask, 0).iterator->value;
- if (!face) {
- for (HashMap<unsigned, RefPtr<CSSSegmentedFontFace> >::const_iterator i = familyFontFaces->begin(); i != familyFontFaces->end(); ++i) {
- CSSSegmentedFontFace* candidate = i->value.get();
- unsigned candidateTraitsMask = candidate->traitsMask();
- if ((traitsMask & FontStyleNormalMask) && !(candidateTraitsMask & FontStyleNormalMask))
- continue;
- if ((traitsMask & FontVariantNormalMask) && !(candidateTraitsMask & FontVariantNormalMask))
- continue;
-#if ENABLE(SVG_FONTS)
- // For SVG Fonts that specify that they only support the "normal" variant, we will assume they are incapable
- // of small-caps synthesis and just ignore the font face as a candidate.
- if (candidate->hasSVGFontFaceSource() && (traitsMask & FontVariantSmallCapsMask) && !(candidateTraitsMask & FontVariantSmallCapsMask))
- continue;
-#endif
- if (!face || compareFontFaces(candidate, face.get(), traitsMask))
- face = candidate;
- }
-
- if (Vector<RefPtr<CSSSegmentedFontFace> >* familyLocallyInstalledFontFaces = m_locallyInstalledFontFaces.get(family)) {
- unsigned numLocallyInstalledFontFaces = familyLocallyInstalledFontFaces->size();
- for (unsigned i = 0; i < numLocallyInstalledFontFaces; ++i) {
- CSSSegmentedFontFace* candidate = familyLocallyInstalledFontFaces->at(i).get();
- unsigned candidateTraitsMask = candidate->traitsMask();
- if ((traitsMask & FontStyleNormalMask) && !(candidateTraitsMask & FontStyleNormalMask))
- continue;
- if ((traitsMask & FontVariantNormalMask) && !(candidateTraitsMask & FontVariantNormalMask))
- continue;
- if (!face || compareFontFaces(candidate, face.get(), traitsMask))
- face = candidate;
- }
- }
- }
- return face.get();
+ return m_cssSegmentedFontFaceCache.get(fontDescription, familyName);
}
void CSSFontSelector::willUseFontData(const FontDescription& fontDescription, const AtomicString& family)
@@ -352,58 +218,18 @@ void CSSFontSelector::willUseFontData(const FontDescription& fontDescription, co
void CSSFontSelector::clearDocument()
{
- if (!m_document) {
- ASSERT(!m_beginLoadingTimer.isActive());
- ASSERT(m_fontsToBeginLoading.isEmpty());
- return;
- }
-
- m_beginLoadingTimer.stop();
-
- ResourceFetcher* fetcher = m_document->fetcher();
- for (size_t i = 0; i < m_fontsToBeginLoading.size(); ++i) {
- // Balances incrementRequestCount() in beginLoadingFontSoon().
- fetcher->decrementRequestCount(m_fontsToBeginLoading[i].get());
- }
-
- m_fontsToBeginLoading.clear();
-
+ m_fontLoader.clearResourceFetcher();
m_document = 0;
}
void CSSFontSelector::beginLoadingFontSoon(FontResource* font)
{
- if (!m_document)
- return;
-
- m_fontsToBeginLoading.append(font);
- // Increment the request count now, in order to prevent didFinishLoad from being dispatched
- // after this font has been requested but before it began loading. Balanced by
- // decrementRequestCount() in beginLoadTimerFired() and in clearDocument().
- m_document->fetcher()->incrementRequestCount(font);
- m_beginLoadingTimer.startOneShot(0);
+ m_fontLoader.addFontToBeginLoading(font);
}
-void CSSFontSelector::beginLoadTimerFired(Timer<WebCore::CSSFontSelector>*)
+void CSSFontSelector::loadPendingFonts()
{
- Vector<ResourcePtr<FontResource> > fontsToBeginLoading;
- fontsToBeginLoading.swap(m_fontsToBeginLoading);
-
- // CSSFontSelector could get deleted via beginLoadIfNeeded() or loadDone() unless protected.
- RefPtr<CSSFontSelector> protect(this);
-
- ResourceFetcher* fetcher = m_document->fetcher();
- for (size_t i = 0; i < fontsToBeginLoading.size(); ++i) {
- fontsToBeginLoading[i]->beginLoadIfNeeded(fetcher);
- // Balances incrementRequestCount() in beginLoadingFontSoon().
- fetcher->decrementRequestCount(fontsToBeginLoading[i].get());
- }
- // Ensure that if the request count reaches zero, the frame loader will know about it.
- fetcher->didLoadResource(0);
- // New font loads may be triggered by layout after the document load is complete but before we have dispatched
- // didFinishLoading for the frame. Make sure the delegate is always dispatched by checking explicitly.
- if (m_document && m_document->frame())
- m_document->frame()->loader()->checkLoadComplete();
+ m_fontLoader.loadPendingFonts();
}
}
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSFontSelector.h b/chromium/third_party/WebKit/Source/core/css/CSSFontSelector.h
index 559fa38fb1e..34d33a8809d 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSFontSelector.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSFontSelector.h
@@ -26,13 +26,14 @@
#ifndef CSSFontSelector_h
#define CSSFontSelector_h
+#include "core/css/CSSSegmentedFontFaceCache.h"
#include "core/fetch/ResourcePtr.h"
-#include "core/platform/Timer.h"
-#include "core/platform/graphics/FontSelector.h"
+#include "platform/Timer.h"
+#include "platform/fonts/FontSelector.h"
+#include "platform/fonts/GenericFontFamilySettings.h"
#include "wtf/Forward.h"
#include "wtf/HashMap.h"
#include "wtf/HashSet.h"
-#include "wtf/text/StringHash.h"
namespace WebCore {
@@ -44,6 +45,23 @@ class Document;
class FontDescription;
class StyleRuleFontFace;
+class FontLoader {
+public:
+ explicit FontLoader(ResourceFetcher*);
+
+ void addFontToBeginLoading(FontResource*);
+ void loadPendingFonts();
+
+ void clearResourceFetcher();
+
+private:
+ void beginLoadTimerFired(Timer<FontLoader>*);
+
+ Timer<FontLoader> m_beginLoadingTimer;
+ Vector<ResourcePtr<FontResource> > m_fontsToBeginLoading;
+ ResourceFetcher* m_resourceFetcher;
+};
+
class CSSFontSelector : public FontSelector {
public:
static PassRefPtr<CSSFontSelector> create(Document* document)
@@ -52,7 +70,7 @@ public:
}
virtual ~CSSFontSelector();
- virtual unsigned version() const OVERRIDE { return m_version; }
+ virtual unsigned version() const OVERRIDE { return m_cssSegmentedFontFaceCache.version(); }
virtual PassRefPtr<FontData> getFontData(const FontDescription&, const AtomicString&);
CSSSegmentedFontFace* getFontFace(const FontDescription&, const AtomicString& family);
@@ -60,37 +78,34 @@ public:
void clearDocument();
- void addFontFaceRule(const StyleRuleFontFace*);
+ void addFontFaceRule(const StyleRuleFontFace*, PassRefPtr<CSSFontFace>);
+ void removeFontFaceRule(const StyleRuleFontFace*);
void fontLoaded();
virtual void fontCacheInvalidated();
- bool isEmpty() const;
-
virtual void registerForInvalidationCallbacks(FontSelectorClient*);
virtual void unregisterForInvalidationCallbacks(FontSelectorClient*);
Document* document() const { return m_document; }
+ const GenericFontFamilySettings& genericFontFamilySettings() const { return m_genericFontFamilySettings; }
+
void beginLoadingFontSoon(FontResource*);
+ void loadPendingFonts();
private:
explicit CSSFontSelector(Document*);
void dispatchInvalidationCallbacks();
- void beginLoadTimerFired(Timer<CSSFontSelector>*);
-
Document* m_document;
- HashMap<String, OwnPtr<HashMap<unsigned, RefPtr<CSSSegmentedFontFace> > >, CaseFoldingHash> m_fontFaces;
- HashMap<String, OwnPtr<Vector<RefPtr<CSSSegmentedFontFace> > >, CaseFoldingHash> m_locallyInstalledFontFaces;
- HashMap<String, OwnPtr<HashMap<unsigned, RefPtr<CSSSegmentedFontFace> > >, CaseFoldingHash> m_fonts;
+ // FIXME: Move to Document or StyleEngine.
+ CSSSegmentedFontFaceCache m_cssSegmentedFontFaceCache;
HashSet<FontSelectorClient*> m_clients;
- Vector<ResourcePtr<FontResource> > m_fontsToBeginLoading;
- Timer<CSSFontSelector> m_beginLoadingTimer;
-
- unsigned m_version;
+ FontLoader m_fontLoader;
+ GenericFontFamilySettings m_genericFontFamilySettings;
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSFontValue.cpp b/chromium/third_party/WebKit/Source/core/css/CSSFontValue.cpp
new file mode 100644
index 00000000000..aee5a9726d6
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/css/CSSFontValue.cpp
@@ -0,0 +1,77 @@
+/**
+ * (C) 1999-2003 Lars Knoll (knoll@kde.org)
+ * Copyright (C) 2004, 2005, 2006 Apple Computer, Inc.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+#include "config.h"
+#include "core/css/CSSFontValue.h"
+
+#include "core/css/CSSPrimitiveValue.h"
+#include "core/css/CSSValueList.h"
+#include "wtf/text/StringBuilder.h"
+
+namespace WebCore {
+
+String CSSFontValue::customCSSText() const
+{
+ // font variant weight size / line-height family
+
+ StringBuilder result;
+
+ if (style)
+ result.append(style->cssText());
+ if (variant) {
+ if (!result.isEmpty())
+ result.append(' ');
+ result.append(variant->cssText());
+ }
+ if (weight) {
+ if (!result.isEmpty())
+ result.append(' ');
+ result.append(weight->cssText());
+ }
+ if (size) {
+ if (!result.isEmpty())
+ result.append(' ');
+ result.append(size->cssText());
+ }
+ if (lineHeight) {
+ if (!size)
+ result.append(' ');
+ result.append('/');
+ result.append(lineHeight->cssText());
+ }
+ if (family) {
+ if (!result.isEmpty())
+ result.append(' ');
+ result.append(family->cssText());
+ }
+
+ return result.toString();
+}
+
+bool CSSFontValue::equals(const CSSFontValue& other) const
+{
+ return compareCSSValuePtr(style, other.style)
+ && compareCSSValuePtr(variant, other.variant)
+ && compareCSSValuePtr(weight, other.weight)
+ && compareCSSValuePtr(size, other.size)
+ && compareCSSValuePtr(lineHeight, other.lineHeight)
+ && compareCSSValuePtr(family, other.family);
+}
+
+}
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSFontValue.h b/chromium/third_party/WebKit/Source/core/css/CSSFontValue.h
new file mode 100644
index 00000000000..f0c99d55326
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/css/CSSFontValue.h
@@ -0,0 +1,62 @@
+/*
+ * (C) 1999-2003 Lars Knoll (knoll@kde.org)
+ * Copyright (C) 2004, 2005, 2006, 2008 Apple Inc. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#ifndef CSSFontValue_h
+#define CSSFontValue_h
+
+#include "core/css/CSSValue.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefPtr.h"
+
+namespace WebCore {
+
+class CSSPrimitiveValue;
+class CSSValueList;
+
+class CSSFontValue : public CSSValue {
+public:
+ static PassRefPtr<CSSFontValue> create()
+ {
+ return adoptRef(new CSSFontValue);
+ }
+
+ String customCSSText() const;
+
+ bool equals(const CSSFontValue&) const;
+
+ RefPtr<CSSPrimitiveValue> style;
+ RefPtr<CSSPrimitiveValue> variant;
+ RefPtr<CSSPrimitiveValue> weight;
+ RefPtr<CSSPrimitiveValue> size;
+ RefPtr<CSSPrimitiveValue> lineHeight;
+ RefPtr<CSSValueList> family;
+
+private:
+ CSSFontValue()
+ : CSSValue(FontClass)
+ {
+ }
+};
+
+DEFINE_CSS_VALUE_TYPE_CASTS(CSSFontValue, isFontValue());
+
+} // namespace
+
+#endif
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSFunctionValue.cpp b/chromium/third_party/WebKit/Source/core/css/CSSFunctionValue.cpp
index aca627069c5..7cbbf86d06f 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSFunctionValue.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/CSSFunctionValue.cpp
@@ -47,7 +47,7 @@ CSSFunctionValue::CSSFunctionValue(String name, PassRefPtr<CSSValueList> args)
{
}
-String CSSFunctionValue::customCssText() const
+String CSSFunctionValue::customCSSText() const
{
StringBuilder result;
result.append(m_name); // Includes the '('
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSFunctionValue.h b/chromium/third_party/WebKit/Source/core/css/CSSFunctionValue.h
index d4e7e4d83dd..87fa8afacfb 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSFunctionValue.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSFunctionValue.h
@@ -45,7 +45,7 @@ public:
return adoptRef(new CSSFunctionValue(name, args));
}
- String customCssText() const;
+ String customCSSText() const;
bool equals(const CSSFunctionValue&) const;
@@ -59,20 +59,7 @@ private:
RefPtr<CSSValueList> m_args;
};
-inline CSSFunctionValue* toCSSFunctionValue(CSSValue* value)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(value->isFunctionValue());
- return static_cast<CSSFunctionValue*>(value);
-}
-
-inline const CSSFunctionValue* toCSSFunctionValue(const CSSValue* value)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(value->isFunctionValue());
- return static_cast<const CSSFunctionValue*>(value);
-}
-
-// Catch any unneeded cast.
-void toCSSFunctionValue(const CSSFunctionValue*);
+DEFINE_CSS_VALUE_TYPE_CASTS(CSSFunctionValue, isFunctionValue());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSGradientValue.cpp b/chromium/third_party/WebKit/Source/core/css/CSSGradientValue.cpp
index 0c6e578aac6..68269972045 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSGradientValue.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/CSSGradientValue.cpp
@@ -28,13 +28,14 @@
#include "CSSValueKeywords.h"
#include "core/css/CSSCalculationValue.h"
+#include "core/css/CSSToLengthConversionData.h"
#include "core/dom/NodeRenderStyle.h"
#include "core/dom/TextLinkColors.h"
-#include "core/platform/graphics/GeneratorGeneratedImage.h"
-#include "core/platform/graphics/Gradient.h"
-#include "core/platform/graphics/Image.h"
-#include "core/platform/graphics/IntSize.h"
#include "core/rendering/RenderObject.h"
+#include "platform/geometry/IntSize.h"
+#include "platform/graphics/Gradient.h"
+#include "platform/graphics/GradientGeneratedImage.h"
+#include "platform/graphics/Image.h"
#include "wtf/text/StringBuilder.h"
#include "wtf/text/WTFString.h"
@@ -61,14 +62,14 @@ PassRefPtr<Image> CSSGradientValue::image(RenderObject* renderer, const IntSize&
// We need to create an image.
RefPtr<Gradient> gradient;
- if (isLinearGradient())
- gradient = static_cast<CSSLinearGradientValue*>(this)->createGradient(renderer, size);
- else {
- ASSERT(isRadialGradient());
- gradient = static_cast<CSSRadialGradientValue*>(this)->createGradient(renderer, size);
- }
+ RenderStyle* rootStyle = renderer->document().documentElement()->renderStyle();
+ CSSToLengthConversionData conversionData(renderer->style(), rootStyle);
+ if (isLinearGradientValue())
+ gradient = toCSSLinearGradientValue(this)->createGradient(conversionData, size);
+ else
+ gradient = toCSSRadialGradientValue(this)->createGradient(conversionData, size);
- RefPtr<Image> newImage = GeneratorGeneratedImage::create(gradient, size);
+ RefPtr<Image> newImage = GradientGeneratedImage::create(gradient, size);
if (cacheable)
putImage(size, newImage);
@@ -118,10 +119,10 @@ PassRefPtr<CSSGradientValue> CSSGradientValue::gradientWithStylesResolved(const
RefPtr<CSSGradientValue> result;
if (!derived)
result = this;
- else if (isLinearGradient())
- result = static_cast<CSSLinearGradientValue*>(this)->clone();
- else if (isRadialGradient())
- result = static_cast<CSSRadialGradientValue*>(this)->clone();
+ else if (isLinearGradientValue())
+ result = toCSSLinearGradientValue(this)->clone();
+ else if (isRadialGradientValue())
+ result = toCSSRadialGradientValue(this)->clone();
else {
ASSERT_NOT_REACHED();
return 0;
@@ -133,10 +134,8 @@ PassRefPtr<CSSGradientValue> CSSGradientValue::gradientWithStylesResolved(const
return result.release();
}
-void CSSGradientValue::addStops(Gradient* gradient, RenderObject* renderer, RenderStyle* rootStyle, float maxLengthForRepeat)
+void CSSGradientValue::addStops(Gradient* gradient, const CSSToLengthConversionData& conversionData, float maxLengthForRepeat)
{
- RenderStyle* style = renderer->style();
-
if (m_gradientType == CSSDeprecatedLinearGradient || m_gradientType == CSSDeprecatedRadialGradient) {
sortStopsIfNeeded();
@@ -166,9 +165,9 @@ void CSSGradientValue::addStops(Gradient* gradient, RenderObject* renderer, Rend
FloatPoint gradientStart = gradient->p0();
FloatPoint gradientEnd;
- if (isLinearGradient())
+ if (isLinearGradientValue())
gradientEnd = gradient->p1();
- else if (isRadialGradient())
+ else if (isRadialGradientValue())
gradientEnd = gradientStart + FloatSize(gradient->endRadius(), 0);
for (size_t i = 0; i < numStops; ++i) {
@@ -186,9 +185,9 @@ void CSSGradientValue::addStops(Gradient* gradient, RenderObject* renderer, Rend
}
float length;
if (stop.m_position->isLength())
- length = stop.m_position->computeLength<float>(style, rootStyle, style->effectiveZoom());
+ length = stop.m_position->computeLength<float>(conversionData);
else
- length = stop.m_position->cssCalcValue()->toCalcValue(style, rootStyle, style->effectiveZoom())->evaluate(gradientLength);
+ length = stop.m_position->cssCalcValue()->toCalcValue(conversionData)->evaluate(gradientLength);
stops[i].offset = (gradientLength > 0) ? length / gradientLength : 0;
} else {
ASSERT_NOT_REACHED();
@@ -269,14 +268,14 @@ void CSSGradientValue::addStops(Gradient* gradient, RenderObject* renderer, Rend
// Radial gradients may need to extend further than the endpoints, because they have
// to repeat out to the corners of the box.
- if (isRadialGradient()) {
+ if (isRadialGradientValue()) {
if (!computedGradientLength) {
FloatSize gradientSize(gradientStart - gradientEnd);
gradientLength = gradientSize.diagonalLength();
}
if (maxLengthForRepeat > gradientLength)
- maxExtent = maxLengthForRepeat / gradientLength;
+ maxExtent = gradientLength > 0 ? maxLengthForRepeat / gradientLength : 0;
}
size_t originalNumStops = numStops;
@@ -327,7 +326,7 @@ void CSSGradientValue::addStops(Gradient* gradient, RenderObject* renderer, Rend
// If the gradient goes outside the 0-1 range, normalize it by moving the endpoints, and adjusting the stops.
if (numStops > 1 && (stops[0].offset < 0 || stops[numStops - 1].offset > 1)) {
- if (isLinearGradient()) {
+ if (isLinearGradientValue()) {
float firstOffset = stops[0].offset;
float lastOffset = stops[numStops - 1].offset;
float scale = lastOffset - firstOffset;
@@ -339,7 +338,7 @@ void CSSGradientValue::addStops(Gradient* gradient, RenderObject* renderer, Rend
FloatPoint p1 = gradient->p1();
gradient->setP0(FloatPoint(p0.x() + firstOffset * (p1.x() - p0.x()), p0.y() + firstOffset * (p1.y() - p0.y())));
gradient->setP1(FloatPoint(p1.x() + (lastOffset - 1) * (p1.x() - p0.x()), p1.y() + (lastOffset - 1) * (p1.y() - p0.y())));
- } else if (isRadialGradient()) {
+ } else if (isRadialGradientValue()) {
// Rather than scaling the points < 0, we truncate them, so only scale according to the largest point.
float firstOffset = 0;
float lastOffset = stops[numStops - 1].offset;
@@ -389,19 +388,17 @@ void CSSGradientValue::addStops(Gradient* gradient, RenderObject* renderer, Rend
gradient->setStopsSorted(true);
}
-static float positionFromValue(CSSPrimitiveValue* value, RenderStyle* style, RenderStyle* rootStyle, const IntSize& size, bool isHorizontal)
+static float positionFromValue(CSSPrimitiveValue* value, const CSSToLengthConversionData& conversionData, const IntSize& size, bool isHorizontal)
{
- float zoomFactor = style->effectiveZoom();
-
if (value->isNumber())
- return value->getFloatValue() * zoomFactor;
+ return value->getFloatValue() * conversionData.zoom();
int edgeDistance = isHorizontal ? size.width() : size.height();
if (value->isPercentage())
return value->getFloatValue() / 100.f * edgeDistance;
if (value->isCalculatedPercentageWithLength())
- return value->cssCalcValue()->toCalcValue(style, rootStyle, style->effectiveZoom())->evaluate(edgeDistance);
+ return value->cssCalcValue()->toCalcValue(conversionData)->evaluate(edgeDistance);
switch (value->getValueID()) {
case CSSValueTop:
@@ -420,18 +417,18 @@ static float positionFromValue(CSSPrimitiveValue* value, RenderStyle* style, Ren
break;
}
- return value->computeLength<float>(style, rootStyle, zoomFactor);
+ return value->computeLength<float>(conversionData);
}
-FloatPoint CSSGradientValue::computeEndPoint(CSSPrimitiveValue* horizontal, CSSPrimitiveValue* vertical, RenderStyle* style, RenderStyle* rootStyle, const IntSize& size)
+FloatPoint CSSGradientValue::computeEndPoint(CSSPrimitiveValue* horizontal, CSSPrimitiveValue* vertical, const CSSToLengthConversionData& conversionData, const IntSize& size)
{
FloatPoint result;
if (horizontal)
- result.setX(positionFromValue(horizontal, style, rootStyle, size, true));
+ result.setX(positionFromValue(horizontal, conversionData, size, true));
if (vertical)
- result.setY(positionFromValue(vertical, style, rootStyle, size, false));
+ result.setY(positionFromValue(vertical, conversionData, size, false));
return result;
}
@@ -463,7 +460,7 @@ bool CSSGradientValue::knownToBeOpaque(const RenderObject*) const
return true;
}
-String CSSLinearGradientValue::customCssText() const
+String CSSLinearGradientValue::customCSSText() const
{
StringBuilder result;
if (m_gradientType == CSSDeprecatedLinearGradient) {
@@ -638,12 +635,10 @@ static void endPointsFromAngle(float angleDeg, const IntSize& size, FloatPoint&
firstPoint.set(halfWidth - endX, halfHeight + endY);
}
-PassRefPtr<Gradient> CSSLinearGradientValue::createGradient(RenderObject* renderer, const IntSize& size)
+PassRefPtr<Gradient> CSSLinearGradientValue::createGradient(const CSSToLengthConversionData& conversionData, const IntSize& size)
{
ASSERT(!size.isEmpty());
- RenderStyle* rootStyle = renderer->document().documentElement()->renderStyle();
-
FloatPoint firstPoint;
FloatPoint secondPoint;
if (m_angle) {
@@ -652,9 +647,9 @@ PassRefPtr<Gradient> CSSLinearGradientValue::createGradient(RenderObject* render
} else {
switch (m_gradientType) {
case CSSDeprecatedLinearGradient:
- firstPoint = computeEndPoint(m_firstX.get(), m_firstY.get(), renderer->style(), rootStyle, size);
+ firstPoint = computeEndPoint(m_firstX.get(), m_firstY.get(), conversionData, size);
if (m_secondX || m_secondY)
- secondPoint = computeEndPoint(m_secondX.get(), m_secondY.get(), renderer->style(), rootStyle, size);
+ secondPoint = computeEndPoint(m_secondX.get(), m_secondY.get(), conversionData, size);
else {
if (m_firstX)
secondPoint.setX(size.width() - firstPoint.x());
@@ -663,7 +658,7 @@ PassRefPtr<Gradient> CSSLinearGradientValue::createGradient(RenderObject* render
}
break;
case CSSPrefixedLinearGradient:
- firstPoint = computeEndPoint(m_firstX.get(), m_firstY.get(), renderer->style(), rootStyle, size);
+ firstPoint = computeEndPoint(m_firstX.get(), m_firstY.get(), conversionData, size);
if (m_firstX)
secondPoint.setX(size.width() - firstPoint.x());
if (m_firstY)
@@ -682,7 +677,7 @@ PassRefPtr<Gradient> CSSLinearGradientValue::createGradient(RenderObject* render
float angle = 90 - rad2deg(atan2(rise, run));
endPointsFromAngle(angle, size, firstPoint, secondPoint, m_gradientType);
} else if (m_firstX || m_firstY) {
- secondPoint = computeEndPoint(m_firstX.get(), m_firstY.get(), renderer->style(), rootStyle, size);
+ secondPoint = computeEndPoint(m_firstX.get(), m_firstY.get(), conversionData, size);
if (m_firstX)
firstPoint.setX(size.width() - secondPoint.x());
if (m_firstY)
@@ -701,7 +696,7 @@ PassRefPtr<Gradient> CSSLinearGradientValue::createGradient(RenderObject* render
gradient->setDrawsInPMColorSpace(true);
// Now add the stops.
- addStops(gradient.get(), renderer, rootStyle, 1);
+ addStops(gradient.get(), conversionData, 1);
return gradient.release();
}
@@ -725,20 +720,20 @@ bool CSSLinearGradientValue::equals(const CSSLinearGradientValue& other) const
if (other.m_angle)
return false;
- bool equalXorY = false;
+ bool equalXandY = false;
if (m_firstX && m_firstY)
- equalXorY = compareCSSValuePtr(m_firstX, other.m_firstX) && compareCSSValuePtr(m_firstY, other.m_firstY);
+ equalXandY = compareCSSValuePtr(m_firstX, other.m_firstX) && compareCSSValuePtr(m_firstY, other.m_firstY);
else if (m_firstX)
- equalXorY =compareCSSValuePtr(m_firstX, other.m_firstX) && !other.m_firstY;
+ equalXandY = compareCSSValuePtr(m_firstX, other.m_firstX) && !other.m_firstY;
else if (m_firstY)
- equalXorY = compareCSSValuePtr(m_firstY, other.m_firstY) && !other.m_firstX;
+ equalXandY = compareCSSValuePtr(m_firstY, other.m_firstY) && !other.m_firstX;
else
- equalXorY = !other.m_firstX || !other.m_firstY;
+ equalXandY = !other.m_firstX && !other.m_firstY;
- return equalXorY && m_stops == other.m_stops;
+ return equalXandY && m_stops == other.m_stops;
}
-String CSSRadialGradientValue::customCssText() const
+String CSSRadialGradientValue::customCSSText() const
{
StringBuilder result;
@@ -888,17 +883,15 @@ String CSSRadialGradientValue::customCssText() const
return result.toString();
}
-float CSSRadialGradientValue::resolveRadius(CSSPrimitiveValue* radius, RenderStyle* style, RenderStyle* rootStyle, float* widthOrHeight)
+float CSSRadialGradientValue::resolveRadius(CSSPrimitiveValue* radius, const CSSToLengthConversionData& conversionData, float* widthOrHeight)
{
- float zoomFactor = style->effectiveZoom();
-
float result = 0;
if (radius->isNumber()) // Can the radius be a percentage?
- result = radius->getFloatValue() * zoomFactor;
+ result = radius->getFloatValue() * conversionData.zoom();
else if (widthOrHeight && radius->isPercentage())
result = *widthOrHeight * radius->getFloatValue() / 100;
else
- result = radius->computeLength<float>(style, rootStyle, zoomFactor);
+ result = radius->computeLength<float>(conversionData);
return result;
}
@@ -980,19 +973,17 @@ static inline float horizontalEllipseRadius(const FloatSize& p, float aspectRati
}
// FIXME: share code with the linear version
-PassRefPtr<Gradient> CSSRadialGradientValue::createGradient(RenderObject* renderer, const IntSize& size)
+PassRefPtr<Gradient> CSSRadialGradientValue::createGradient(const CSSToLengthConversionData& conversionData, const IntSize& size)
{
ASSERT(!size.isEmpty());
- RenderStyle* rootStyle = renderer->document().documentElement()->renderStyle();
-
- FloatPoint firstPoint = computeEndPoint(m_firstX.get(), m_firstY.get(), renderer->style(), rootStyle, size);
+ FloatPoint firstPoint = computeEndPoint(m_firstX.get(), m_firstY.get(), conversionData, size);
if (!m_firstX)
firstPoint.setX(size.width() / 2);
if (!m_firstY)
firstPoint.setY(size.height() / 2);
- FloatPoint secondPoint = computeEndPoint(m_secondX.get(), m_secondY.get(), renderer->style(), rootStyle, size);
+ FloatPoint secondPoint = computeEndPoint(m_secondX.get(), m_secondY.get(), conversionData, size);
if (!m_secondX)
secondPoint.setX(size.width() / 2);
if (!m_secondY)
@@ -1000,18 +991,18 @@ PassRefPtr<Gradient> CSSRadialGradientValue::createGradient(RenderObject* render
float firstRadius = 0;
if (m_firstRadius)
- firstRadius = resolveRadius(m_firstRadius.get(), renderer->style(), rootStyle);
+ firstRadius = resolveRadius(m_firstRadius.get(), conversionData);
float secondRadius = 0;
float aspectRatio = 1; // width / height.
if (m_secondRadius)
- secondRadius = resolveRadius(m_secondRadius.get(), renderer->style(), rootStyle);
+ secondRadius = resolveRadius(m_secondRadius.get(), conversionData);
else if (m_endHorizontalSize) {
float width = size.width();
float height = size.height();
- secondRadius = resolveRadius(m_endHorizontalSize.get(), renderer->style(), rootStyle, &width);
+ secondRadius = resolveRadius(m_endHorizontalSize.get(), conversionData, &width);
if (m_endVerticalSize)
- aspectRatio = secondRadius / resolveRadius(m_endVerticalSize.get(), renderer->style(), rootStyle, &height);
+ aspectRatio = secondRadius / resolveRadius(m_endVerticalSize.get(), conversionData, &height);
else
aspectRatio = 1;
} else {
@@ -1119,7 +1110,7 @@ PassRefPtr<Gradient> CSSRadialGradientValue::createGradient(RenderObject* render
}
// Now add the stops.
- addStops(gradient.get(), renderer, rootStyle, maxExtent);
+ addStops(gradient.get(), conversionData, maxExtent);
return gradient.release();
}
@@ -1139,17 +1130,17 @@ bool CSSRadialGradientValue::equals(const CSSRadialGradientValue& other) const
if (m_repeating != other.m_repeating)
return false;
- bool equalXorY = false;
+ bool equalXandY = false;
if (m_firstX && m_firstY)
- equalXorY = compareCSSValuePtr(m_firstX, other.m_firstX) && compareCSSValuePtr(m_firstY, other.m_firstY);
+ equalXandY = compareCSSValuePtr(m_firstX, other.m_firstX) && compareCSSValuePtr(m_firstY, other.m_firstY);
else if (m_firstX)
- equalXorY = compareCSSValuePtr(m_firstX, other.m_firstX) && !other.m_firstY;
+ equalXandY = compareCSSValuePtr(m_firstX, other.m_firstX) && !other.m_firstY;
else if (m_firstY)
- equalXorY = compareCSSValuePtr(m_firstY, other.m_firstY) && !other.m_firstX;
+ equalXandY = compareCSSValuePtr(m_firstY, other.m_firstY) && !other.m_firstX;
else
- equalXorY == !other.m_firstX || !other.m_firstY;
+ equalXandY = !other.m_firstX && !other.m_firstY;
- if (!equalXorY)
+ if (!equalXandY)
return false;
bool equalShape = true;
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSGradientValue.h b/chromium/third_party/WebKit/Source/core/css/CSSGradientValue.h
index 75e51520a94..7179b6fff80 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSGradientValue.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSGradientValue.h
@@ -75,9 +75,6 @@ public:
void sortStopsIfNeeded();
- bool isLinearGradient() const { return classType() == LinearGradientClass; }
- bool isRadialGradient() const { return classType() == RadialGradientClass; }
-
bool isRepeating() const { return m_repeating; }
CSSGradientType gradientType() const { return m_gradientType; }
@@ -113,10 +110,10 @@ protected:
{
}
- void addStops(Gradient*, RenderObject*, RenderStyle* rootStyle, float maxLengthForRepeat = 0);
+ void addStops(Gradient*, const CSSToLengthConversionData&, float maxLengthForRepeat = 0);
// Resolve points/radii to front end values.
- FloatPoint computeEndPoint(CSSPrimitiveValue*, CSSPrimitiveValue*, RenderStyle*, RenderStyle* rootStyle, const IntSize&);
+ FloatPoint computeEndPoint(CSSPrimitiveValue*, CSSPrimitiveValue*, const CSSToLengthConversionData&, const IntSize&);
bool isCacheable() const;
@@ -134,6 +131,7 @@ protected:
bool m_repeating;
};
+DEFINE_CSS_VALUE_TYPE_CASTS(CSSGradientValue, isGradientValue());
class CSSLinearGradientValue : public CSSGradientValue {
public:
@@ -145,10 +143,10 @@ public:
void setAngle(PassRefPtr<CSSPrimitiveValue> val) { m_angle = val; }
- String customCssText() const;
+ String customCSSText() const;
// Create the gradient for a given size.
- PassRefPtr<Gradient> createGradient(RenderObject*, const IntSize&);
+ PassRefPtr<Gradient> createGradient(const CSSToLengthConversionData&, const IntSize&);
PassRefPtr<CSSLinearGradientValue> clone() const
{
@@ -172,6 +170,8 @@ private:
RefPtr<CSSPrimitiveValue> m_angle; // may be null.
};
+DEFINE_CSS_VALUE_TYPE_CASTS(CSSLinearGradientValue, isLinearGradientValue());
+
class CSSRadialGradientValue : public CSSGradientValue {
public:
static PassRefPtr<CSSRadialGradientValue> create(CSSGradientRepeat repeat, CSSGradientType gradientType = CSSRadialGradient)
@@ -184,7 +184,7 @@ public:
return adoptRef(new CSSRadialGradientValue(*this));
}
- String customCssText() const;
+ String customCSSText() const;
void setFirstRadius(PassRefPtr<CSSPrimitiveValue> val) { m_firstRadius = val; }
void setSecondRadius(PassRefPtr<CSSPrimitiveValue> val) { m_secondRadius = val; }
@@ -196,7 +196,7 @@ public:
void setEndVerticalSize(PassRefPtr<CSSPrimitiveValue> val) { m_endVerticalSize = val; }
// Create the gradient for a given size.
- PassRefPtr<Gradient> createGradient(RenderObject*, const IntSize&);
+ PassRefPtr<Gradient> createGradient(const CSSToLengthConversionData&, const IntSize&);
bool equals(const CSSRadialGradientValue&) const;
@@ -219,7 +219,7 @@ private:
// Resolve points/radii to front end values.
- float resolveRadius(CSSPrimitiveValue*, RenderStyle*, RenderStyle* rootStyle, float* widthOrHeight = 0);
+ float resolveRadius(CSSPrimitiveValue*, const CSSToLengthConversionData&, float* widthOrHeight = 0);
// These may be null for non-deprecated gradients.
RefPtr<CSSPrimitiveValue> m_firstRadius;
@@ -233,6 +233,8 @@ private:
RefPtr<CSSPrimitiveValue> m_endVerticalSize;
};
+DEFINE_CSS_VALUE_TYPE_CASTS(CSSRadialGradientValue, isRadialGradientValue());
+
} // namespace WebCore
#endif // CSSGradientValue_h
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSGrammar.y b/chromium/third_party/WebKit/Source/core/css/CSSGrammar.y
new file mode 100644
index 00000000000..2c2c3753094
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/css/CSSGrammar.y
@@ -0,0 +1,1985 @@
+%{
+
+/*
+ * Copyright (C) 2002-2003 Lars Knoll (knoll@kde.org)
+ * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 Apple Inc. All rights reserved.
+ * Copyright (C) 2006 Alexey Proskuryakov (ap@nypop.com)
+ * Copyright (C) 2008 Eric Seidel <eric@webkit.org>
+ * Copyright (C) 2012 Intel Corporation. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ */
+
+#include "config.h"
+
+#include "CSSPropertyNames.h"
+#include "HTMLNames.h"
+#include "core/css/CSSKeyframeRule.h"
+#include "core/css/CSSKeyframesRule.h"
+#include "core/css/CSSParser.h"
+#include "core/css/CSSParserMode.h"
+#include "core/css/CSSPrimitiveValue.h"
+#include "core/css/CSSSelector.h"
+#include "core/css/CSSSelectorList.h"
+#include "core/css/MediaList.h"
+#include "core/css/MediaQueryExp.h"
+#include "core/css/StyleRule.h"
+#include "core/css/StyleSheetContents.h"
+#include "core/dom/Document.h"
+#include "wtf/FastMalloc.h"
+#include <stdlib.h>
+#include <string.h>
+
+using namespace WebCore;
+using namespace HTMLNames;
+
+#define YYMALLOC fastMalloc
+#define YYFREE fastFree
+
+#define YYENABLE_NLS 0
+#define YYLTYPE_IS_TRIVIAL 1
+#define YYMAXDEPTH 10000
+#define YYDEBUG 0
+
+#if YYDEBUG > 0
+#define YYPRINT(File,Type,Value) if (isCSSTokenAString(Type)) YYFPRINTF(File, "%s", String((Value).string).utf8().data())
+#endif
+
+%}
+
+%pure_parser
+
+%parse-param { CSSParser* parser }
+%lex-param { CSSParser* parser }
+
+%union {
+ bool boolean;
+ char character;
+ int integer;
+ double number;
+ CSSParserString string;
+
+ StyleRuleBase* rule;
+ Vector<RefPtr<StyleRuleBase> >* ruleList;
+ CSSParserSelector* selector;
+ Vector<OwnPtr<CSSParserSelector> >* selectorList;
+ CSSSelector::MarginBoxType marginBox;
+ CSSSelector::Relation relation;
+ MediaQuerySet* mediaList;
+ MediaQuery* mediaQuery;
+ MediaQuery::Restrictor mediaQueryRestrictor;
+ MediaQueryExp* mediaQueryExp;
+ CSSParserValue value;
+ CSSParserValueList* valueList;
+ Vector<OwnPtr<MediaQueryExp> >* mediaQueryExpList;
+ StyleKeyframe* keyframe;
+ Vector<RefPtr<StyleKeyframe> >* keyframeRuleList;
+ float val;
+ CSSPropertyID id;
+ CSSParserLocation location;
+}
+
+%{
+
+static inline int cssyyerror(void*, const char*)
+{
+ return 1;
+}
+
+#if YYDEBUG > 0
+static inline bool isCSSTokenAString(int yytype)
+{
+ switch (yytype) {
+ case IDENT:
+ case STRING:
+ case NTH:
+ case HEX:
+ case IDSEL:
+ case DIMEN:
+ case INVALIDDIMEN:
+ case URI:
+ case FUNCTION:
+ case ANYFUNCTION:
+ case HOSTFUNCTION:
+ case NOTFUNCTION:
+ case CALCFUNCTION:
+ case MINFUNCTION:
+ case MAXFUNCTION:
+ case VARFUNCTION:
+ case VAR_DEFINITION:
+ case UNICODERANGE:
+ return true;
+ default:
+ return false;
+ }
+}
+#endif
+
+inline static CSSParserValue makeOperatorValue(int value)
+{
+ CSSParserValue v;
+ v.id = CSSValueInvalid;
+ v.unit = CSSParserValue::Operator;
+ v.iValue = value;
+ return v;
+}
+
+inline static CSSParserValue makeIdentValue(CSSParserString string)
+{
+ CSSParserValue v;
+ v.id = cssValueKeywordID(string);
+ v.unit = CSSPrimitiveValue::CSS_IDENT;
+ v.string = string;
+ return v;
+}
+
+%}
+
+%expect 0
+
+%nonassoc LOWEST_PREC
+
+%left UNIMPORTANT_TOK
+
+%token WHITESPACE SGML_CD
+%token TOKEN_EOF 0
+
+%token INCLUDES
+%token DASHMATCH
+%token BEGINSWITH
+%token ENDSWITH
+%token CONTAINS
+
+%token <string> STRING
+%right <string> IDENT
+%token <string> NTH
+
+%nonassoc <string> HEX
+%nonassoc <string> IDSEL
+%nonassoc ':'
+%nonassoc '.'
+%nonassoc '['
+%nonassoc <string> '*'
+%nonassoc error
+%left '|'
+
+%token IMPORT_SYM
+%token PAGE_SYM
+%token MEDIA_SYM
+%token SUPPORTS_SYM
+%token FONT_FACE_SYM
+%token CHARSET_SYM
+%token NAMESPACE_SYM
+%token VIEWPORT_RULE_SYM
+%token INTERNAL_DECLS_SYM
+%token INTERNAL_MEDIALIST_SYM
+%token INTERNAL_RULE_SYM
+%token INTERNAL_SELECTOR_SYM
+%token INTERNAL_VALUE_SYM
+%token INTERNAL_KEYFRAME_RULE_SYM
+%token INTERNAL_KEYFRAME_KEY_LIST_SYM
+%token INTERNAL_SUPPORTS_CONDITION_SYM
+%token KEYFRAMES_SYM
+%token WEBKIT_KEYFRAMES_SYM
+%token WEBKIT_REGION_RULE_SYM
+%token WEBKIT_FILTER_RULE_SYM
+%token <marginBox> TOPLEFTCORNER_SYM
+%token <marginBox> TOPLEFT_SYM
+%token <marginBox> TOPCENTER_SYM
+%token <marginBox> TOPRIGHT_SYM
+%token <marginBox> TOPRIGHTCORNER_SYM
+%token <marginBox> BOTTOMLEFTCORNER_SYM
+%token <marginBox> BOTTOMLEFT_SYM
+%token <marginBox> BOTTOMCENTER_SYM
+%token <marginBox> BOTTOMRIGHT_SYM
+%token <marginBox> BOTTOMRIGHTCORNER_SYM
+%token <marginBox> LEFTTOP_SYM
+%token <marginBox> LEFTMIDDLE_SYM
+%token <marginBox> LEFTBOTTOM_SYM
+%token <marginBox> RIGHTTOP_SYM
+%token <marginBox> RIGHTMIDDLE_SYM
+%token <marginBox> RIGHTBOTTOM_SYM
+
+%token ATKEYWORD
+
+%token IMPORTANT_SYM
+%token MEDIA_ONLY
+%token MEDIA_NOT
+%token MEDIA_AND
+%token MEDIA_OR
+
+%token SUPPORTS_NOT
+%token SUPPORTS_AND
+%token SUPPORTS_OR
+
+%token <number> REMS
+%token <number> CHS
+%token <number> QEMS
+%token <number> EMS
+%token <number> EXS
+%token <number> PXS
+%token <number> CMS
+%token <number> MMS
+%token <number> INS
+%token <number> PTS
+%token <number> PCS
+%token <number> DEGS
+%token <number> RADS
+%token <number> GRADS
+%token <number> TURNS
+%token <number> MSECS
+%token <number> SECS
+%token <number> HERTZ
+%token <number> KHERTZ
+%token <string> DIMEN
+%token <string> INVALIDDIMEN
+%token <number> PERCENTAGE
+%token <number> FLOATTOKEN
+%token <number> INTEGER
+%token <number> VW
+%token <number> VH
+%token <number> VMIN
+%token <number> VMAX
+%token <number> DPPX
+%token <number> DPI
+%token <number> DPCM
+%token <number> FR
+
+%token <string> URI
+%token <string> FUNCTION
+%token <string> ANYFUNCTION
+%token <string> CUEFUNCTION
+%token <string> NOTFUNCTION
+%token <string> DISTRIBUTEDFUNCTION
+%token <string> CALCFUNCTION
+%token <string> MINFUNCTION
+%token <string> MAXFUNCTION
+%token <string> VARFUNCTION
+%token <string> VAR_DEFINITION
+%token <string> HOSTFUNCTION
+
+%token <string> UNICODERANGE
+
+%type <relation> combinator
+
+%type <rule> ruleset
+%type <rule> media
+%type <rule> import
+%type <rule> namespace
+%type <rule> page
+%type <rule> margin_box
+%type <rule> font_face
+%type <rule> keyframes
+%type <rule> rule
+%type <rule> valid_rule
+%type <ruleList> block_rule_body
+%type <ruleList> block_rule_list
+%type <ruleList> region_block_rule_body
+%type <ruleList> region_block_rule_list
+%type <rule> block_rule
+%type <rule> block_valid_rule
+%type <rule> region_block_rule
+%type <rule> region_block_valid_rule
+%type <rule> region
+%type <rule> supports
+%type <rule> viewport
+%type <rule> filter
+%type <boolean> keyframes_rule_start
+
+%type <string> maybe_ns_prefix
+
+%type <string> namespace_selector
+
+%type <string> string_or_uri
+%type <string> ident_or_string
+%type <string> medium
+%type <marginBox> margin_sym
+
+%type <mediaList> media_list
+%type <mediaList> maybe_media_list
+%type <mediaList> mq_list
+%type <mediaQuery> media_query
+%type <mediaQuery> valid_media_query
+%type <mediaQueryRestrictor> maybe_media_restrictor
+%type <valueList> maybe_media_value
+%type <mediaQueryExp> media_query_exp
+%type <mediaQueryExpList> media_query_exp_list
+%type <mediaQueryExpList> maybe_and_media_query_exp_list
+
+%type <boolean> supports_condition
+%type <boolean> supports_condition_in_parens
+%type <boolean> supports_negation
+%type <boolean> supports_conjunction
+%type <boolean> supports_disjunction
+%type <boolean> supports_declaration_condition
+
+%type <string> keyframe_name
+%type <keyframe> keyframe_rule
+%type <keyframeRuleList> keyframes_rule
+%type <keyframeRuleList> keyframe_rule_list
+%type <valueList> key_list
+%type <value> key
+
+%type <id> property
+
+%type <selector> specifier
+%type <selector> specifier_list
+%type <selector> simple_selector
+%type <selector> selector
+%type <selector> relative_selector
+%type <selectorList> selector_list
+%type <selectorList> simple_selector_list
+%type <selectorList> region_selector
+%type <selector> class
+%type <selector> attrib
+%type <selector> pseudo
+%type <selector> pseudo_page
+%type <selector> page_selector
+
+%type <boolean> declaration_list
+%type <boolean> decl_list
+%type <boolean> declaration
+%type <boolean> declarations_and_margins
+
+%type <boolean> prio
+
+%type <integer> match
+%type <integer> unary_operator
+%type <integer> maybe_unary_operator
+%type <character> operator
+
+%type <valueList> expr
+%type <value> term
+%type <value> unary_term
+%type <value> function
+%type <value> calc_func_term
+%type <character> calc_func_operator
+%type <valueList> calc_func_expr
+%type <valueList> calc_func_expr_list
+%type <valueList> calc_func_paren_expr
+%type <value> calc_function
+%type <string> min_or_max
+%type <value> min_or_max_function
+
+%type <string> element_name
+%type <string> attr_name
+
+%type <location> error_location
+
+%type <valueList> ident_list
+%type <value> track_names_list
+
+%%
+
+stylesheet:
+ maybe_charset maybe_sgml rule_list
+ | internal_decls
+ | internal_rule
+ | internal_selector
+ | internal_value
+ | internal_medialist
+ | internal_keyframe_rule
+ | internal_keyframe_key_list
+ | internal_supports_condition
+ ;
+
+internal_rule:
+ INTERNAL_RULE_SYM maybe_space valid_rule maybe_space TOKEN_EOF {
+ parser->m_rule = $3;
+ }
+;
+
+internal_keyframe_rule:
+ INTERNAL_KEYFRAME_RULE_SYM maybe_space keyframe_rule maybe_space TOKEN_EOF {
+ parser->m_keyframe = $3;
+ }
+;
+
+internal_keyframe_key_list:
+ INTERNAL_KEYFRAME_KEY_LIST_SYM maybe_space key_list TOKEN_EOF {
+ parser->m_valueList = parser->sinkFloatingValueList($3);
+ }
+;
+
+internal_decls:
+ INTERNAL_DECLS_SYM maybe_space_before_declaration declaration_list TOKEN_EOF {
+ /* can be empty */
+ }
+;
+
+internal_value:
+ INTERNAL_VALUE_SYM maybe_space expr TOKEN_EOF {
+ parser->m_valueList = parser->sinkFloatingValueList($3);
+ int oldParsedProperties = parser->m_parsedProperties.size();
+ if (!parser->parseValue(parser->m_id, parser->m_important))
+ parser->rollbackLastProperties(parser->m_parsedProperties.size() - oldParsedProperties);
+ parser->m_valueList = nullptr;
+ }
+;
+
+internal_medialist:
+ INTERNAL_MEDIALIST_SYM maybe_space location_label maybe_media_list TOKEN_EOF {
+ parser->m_mediaList = $4;
+ }
+;
+
+internal_selector:
+ INTERNAL_SELECTOR_SYM maybe_space selector_list TOKEN_EOF {
+ if (parser->m_selectorListForParseSelector)
+ parser->m_selectorListForParseSelector->adoptSelectorVector(*$3);
+ }
+;
+
+internal_supports_condition:
+ INTERNAL_SUPPORTS_CONDITION_SYM maybe_space supports_condition TOKEN_EOF {
+ parser->m_supportsCondition = $3;
+ }
+;
+
+space:
+ WHITESPACE
+ | space WHITESPACE
+ ;
+
+maybe_space:
+ /* empty */ %prec UNIMPORTANT_TOK
+ | space
+ ;
+
+maybe_sgml:
+ /* empty */
+ | maybe_sgml SGML_CD
+ | maybe_sgml WHITESPACE
+ ;
+
+closing_brace:
+ '}'
+ | %prec LOWEST_PREC TOKEN_EOF
+ ;
+
+closing_parenthesis:
+ ')'
+ | %prec LOWEST_PREC TOKEN_EOF
+ ;
+
+closing_square_bracket:
+ ']'
+ | %prec LOWEST_PREC TOKEN_EOF
+ ;
+
+semi_or_eof:
+ ';'
+ | TOKEN_EOF
+ ;
+
+maybe_charset:
+ /* empty */
+ | CHARSET_SYM maybe_space STRING maybe_space semi_or_eof {
+ if (parser->m_styleSheet)
+ parser->m_styleSheet->parserSetEncodingFromCharsetRule($3);
+ parser->startEndUnknownRule();
+ }
+ | CHARSET_SYM at_rule_recovery
+ ;
+
+rule_list:
+ /* empty */
+ | rule_list rule maybe_sgml {
+ if ($2 && parser->m_styleSheet)
+ parser->m_styleSheet->parserAppendRule($2);
+ }
+ ;
+
+valid_rule:
+ ruleset
+ | media
+ | page
+ | font_face
+ | keyframes
+ | namespace
+ | import
+ | region
+ | supports
+ | viewport
+ | filter
+ ;
+
+before_rule:
+ /* empty */ {
+ parser->startRule();
+ }
+ ;
+
+rule:
+ before_rule valid_rule {
+ $$ = $2;
+ parser->m_hadSyntacticallyValidCSSRule = true;
+ parser->endRule(!!$$);
+ }
+ | before_rule invalid_rule {
+ $$ = 0;
+ parser->endRule(false);
+ }
+ ;
+
+block_rule_body:
+ block_rule_list
+ | block_rule_list block_rule_recovery
+ ;
+
+block_rule_list:
+ /* empty */ { $$ = 0; }
+ | block_rule_list block_rule maybe_sgml {
+ $$ = parser->appendRule($1, $2);
+ }
+ ;
+
+region_block_rule_body:
+ region_block_rule_list
+ | region_block_rule_list block_rule_recovery
+ ;
+
+region_block_rule_list:
+ /* empty */ { $$ = 0; }
+ | region_block_rule_list region_block_rule maybe_sgml {
+ $$ = parser->appendRule($1, $2);
+ }
+ ;
+
+region_block_rule:
+ before_rule region_block_valid_rule {
+ $$ = $2;
+ parser->endRule(!!$$);
+ }
+ | before_rule invalid_rule {
+ $$ = 0;
+ parser->endRule(false);
+ }
+ ;
+
+block_rule_recovery:
+ before_rule invalid_rule_header {
+ parser->endRule(false);
+ }
+ ;
+
+region_block_valid_rule:
+ ruleset
+ | page
+ | font_face
+ | media
+ | keyframes
+ | supports
+ | viewport
+ | filter
+ ;
+
+block_valid_rule:
+ ruleset
+ | page
+ | font_face
+ | media
+ | keyframes
+ | supports
+ | viewport
+ | filter
+ | namespace
+ | region
+ ;
+
+block_rule:
+ before_rule block_valid_rule {
+ $$ = $2;
+ parser->endRule(!!$$);
+ }
+ | before_rule invalid_rule {
+ $$ = 0;
+ parser->endRule(false);
+ }
+ ;
+
+before_import_rule:
+ /* empty */ {
+ parser->startRuleHeader(CSSRuleSourceData::IMPORT_RULE);
+ }
+ ;
+
+import_rule_start:
+ before_import_rule IMPORT_SYM maybe_space {
+ parser->endRuleHeader();
+ parser->startRuleBody();
+ }
+ ;
+
+import:
+ import_rule_start string_or_uri maybe_space location_label maybe_media_list semi_or_eof {
+ $$ = parser->createImportRule($2, $5);
+ }
+ | import_rule_start string_or_uri maybe_space location_label maybe_media_list invalid_block {
+ $$ = 0;
+ }
+ ;
+
+namespace:
+ NAMESPACE_SYM maybe_space maybe_ns_prefix string_or_uri maybe_space semi_or_eof {
+ parser->addNamespace($3, $4);
+ $$ = 0;
+ }
+ ;
+
+maybe_ns_prefix:
+/* empty */ { $$.clear(); }
+| IDENT maybe_space
+;
+
+string_or_uri:
+STRING
+| URI
+;
+
+maybe_media_value:
+ /*empty*/ {
+ $$ = 0;
+ }
+ | ':' maybe_space expr {
+ $$ = $3;
+ }
+ ;
+
+media_query_exp:
+ '(' maybe_space IDENT maybe_space maybe_media_value closing_parenthesis {
+ parser->tokenToLowerCase($3);
+ $$ = parser->createFloatingMediaQueryExp($3, $5);
+ if (!$$)
+ YYERROR;
+ }
+ | '(' error error_recovery closing_parenthesis {
+ YYERROR;
+ }
+ ;
+
+media_query_exp_list:
+ media_query_exp {
+ $$ = parser->createFloatingMediaQueryExpList();
+ $$->append(parser->sinkFloatingMediaQueryExp($1));
+ }
+ | media_query_exp_list maybe_space MEDIA_AND maybe_space media_query_exp {
+ $$ = $1;
+ $$->append(parser->sinkFloatingMediaQueryExp($5));
+ }
+ ;
+
+maybe_and_media_query_exp_list:
+ maybe_space {
+ $$ = parser->createFloatingMediaQueryExpList();
+ }
+ | maybe_space MEDIA_AND maybe_space media_query_exp_list maybe_space {
+ $$ = $4;
+ }
+ ;
+
+maybe_media_restrictor:
+ /*empty*/ {
+ $$ = MediaQuery::None;
+ }
+ | MEDIA_ONLY maybe_space {
+ $$ = MediaQuery::Only;
+ }
+ | MEDIA_NOT maybe_space {
+ $$ = MediaQuery::Not;
+ }
+ ;
+
+valid_media_query:
+ media_query_exp_list maybe_space {
+ $$ = parser->createFloatingMediaQuery(parser->sinkFloatingMediaQueryExpList($1));
+ }
+ | maybe_media_restrictor medium maybe_and_media_query_exp_list {
+ parser->tokenToLowerCase($2);
+ $$ = parser->createFloatingMediaQuery($1, $2, parser->sinkFloatingMediaQueryExpList($3));
+ }
+ ;
+
+media_query:
+ valid_media_query
+ | valid_media_query error error_location rule_error_recovery {
+ parser->reportError(parser->lastLocationLabel(), CSSParser::InvalidMediaQueryError);
+ $$ = parser->createFloatingNotAllQuery();
+ }
+ | error error_location rule_error_recovery {
+ parser->reportError(parser->lastLocationLabel(), CSSParser::InvalidMediaQueryError);
+ $$ = parser->createFloatingNotAllQuery();
+ }
+ ;
+
+maybe_media_list:
+ /* empty */ {
+ $$ = parser->createMediaQuerySet();
+ }
+ | media_list
+ ;
+
+media_list:
+ media_query {
+ $$ = parser->createMediaQuerySet();
+ $$->addMediaQuery(parser->sinkFloatingMediaQuery($1));
+ }
+ | mq_list media_query {
+ $$ = $1;
+ $$->addMediaQuery(parser->sinkFloatingMediaQuery($2));
+ }
+ | mq_list {
+ $$ = $1;
+ $$->addMediaQuery(parser->sinkFloatingMediaQuery(parser->createFloatingNotAllQuery()));
+ }
+ ;
+
+mq_list:
+ media_query ',' maybe_space location_label {
+ $$ = parser->createMediaQuerySet();
+ $$->addMediaQuery(parser->sinkFloatingMediaQuery($1));
+ }
+ | mq_list media_query ',' maybe_space location_label {
+ $$ = $1;
+ $$->addMediaQuery(parser->sinkFloatingMediaQuery($2));
+ }
+ ;
+
+at_rule_body_start:
+ /* empty */ {
+ parser->startRuleBody();
+ }
+ ;
+
+before_media_rule:
+ /* empty */ {
+ parser->startRuleHeader(CSSRuleSourceData::MEDIA_RULE);
+ }
+ ;
+
+at_rule_header_end_maybe_space:
+ maybe_space {
+ parser->endRuleHeader();
+ }
+ ;
+
+media_rule_start:
+ before_media_rule MEDIA_SYM maybe_space;
+
+media:
+ media_rule_start maybe_media_list at_rule_header_end '{' at_rule_body_start maybe_space block_rule_body closing_brace {
+ $$ = parser->createMediaRule($2, $7);
+ }
+ ;
+
+medium:
+ IDENT
+ ;
+
+supports:
+ before_supports_rule SUPPORTS_SYM maybe_space supports_condition at_supports_rule_header_end '{' at_rule_body_start maybe_space block_rule_body closing_brace {
+ $$ = parser->createSupportsRule($4, $9);
+ }
+ ;
+
+before_supports_rule:
+ /* empty */ {
+ parser->startRuleHeader(CSSRuleSourceData::SUPPORTS_RULE);
+ parser->markSupportsRuleHeaderStart();
+ }
+ ;
+
+at_supports_rule_header_end:
+ /* empty */ {
+ parser->endRuleHeader();
+ parser->markSupportsRuleHeaderEnd();
+ }
+ ;
+
+supports_condition:
+ supports_condition_in_parens
+ | supports_negation
+ | supports_conjunction
+ | supports_disjunction
+ ;
+
+supports_negation:
+ SUPPORTS_NOT maybe_space supports_condition_in_parens {
+ $$ = !$3;
+ }
+ ;
+
+supports_conjunction:
+ supports_condition_in_parens SUPPORTS_AND maybe_space supports_condition_in_parens {
+ $$ = $1 && $4;
+ }
+ | supports_conjunction SUPPORTS_AND maybe_space supports_condition_in_parens {
+ $$ = $1 && $4;
+ }
+ ;
+
+supports_disjunction:
+ supports_condition_in_parens SUPPORTS_OR maybe_space supports_condition_in_parens {
+ $$ = $1 || $4;
+ }
+ | supports_disjunction SUPPORTS_OR maybe_space supports_condition_in_parens {
+ $$ = $1 || $4;
+ }
+ ;
+
+supports_condition_in_parens:
+ '(' maybe_space supports_condition closing_parenthesis maybe_space {
+ $$ = $3;
+ }
+ | supports_declaration_condition
+ | '(' error error_location error_recovery closing_parenthesis maybe_space {
+ parser->reportError($3, CSSParser::InvalidSupportsConditionError);
+ $$ = false;
+ }
+ ;
+
+supports_declaration_condition:
+ '(' maybe_space IDENT maybe_space ':' maybe_space expr prio closing_parenthesis maybe_space {
+ $$ = false;
+ CSSPropertyID id = cssPropertyID($3);
+ if (id != CSSPropertyInvalid) {
+ parser->m_valueList = parser->sinkFloatingValueList($7);
+ int oldParsedProperties = parser->m_parsedProperties.size();
+ $$ = parser->parseValue(id, $8);
+ // We just need to know if the declaration is supported as it is written. Rollback any additions.
+ if ($$)
+ parser->rollbackLastProperties(parser->m_parsedProperties.size() - oldParsedProperties);
+ }
+ parser->m_valueList = nullptr;
+ parser->endProperty($8, false);
+ }
+ | '(' maybe_space IDENT maybe_space ':' maybe_space error error_recovery closing_parenthesis maybe_space {
+ $$ = false;
+ parser->endProperty(false, false, CSSParser::GeneralError);
+ }
+ ;
+
+before_keyframes_rule:
+ /* empty */ {
+ parser->startRuleHeader(CSSRuleSourceData::KEYFRAMES_RULE);
+ }
+ ;
+
+keyframes_rule_start:
+ before_keyframes_rule KEYFRAMES_SYM maybe_space {
+ $$ = false;
+ }
+ | before_keyframes_rule WEBKIT_KEYFRAMES_SYM maybe_space {
+ $$ = true;
+ }
+ ;
+
+keyframes:
+ keyframes_rule_start keyframe_name at_rule_header_end_maybe_space '{' at_rule_body_start maybe_space location_label keyframes_rule closing_brace {
+ $$ = parser->createKeyframesRule($2, parser->sinkFloatingKeyframeVector($8), $1 /* isPrefixed */);
+ }
+ ;
+
+keyframe_name:
+ IDENT
+ | STRING
+ ;
+
+keyframes_rule:
+ keyframe_rule_list
+ | keyframe_rule_list keyframes_error_recovery {
+ parser->clearProperties();
+ };
+
+keyframe_rule_list:
+ /* empty */ {
+ $$ = parser->createFloatingKeyframeVector();
+ parser->resumeErrorLogging();
+ }
+ | keyframe_rule_list keyframe_rule maybe_space location_label {
+ $$ = $1;
+ $$->append($2);
+ }
+ | keyframe_rule_list keyframes_error_recovery invalid_block maybe_space location_label {
+ parser->clearProperties();
+ parser->resumeErrorLogging();
+ }
+ ;
+
+keyframe_rule:
+ key_list '{' maybe_space declaration_list closing_brace {
+ $$ = parser->createKeyframe($1);
+ }
+ ;
+
+key_list:
+ key maybe_space {
+ $$ = parser->createFloatingValueList();
+ $$->addValue(parser->sinkFloatingValue($1));
+ }
+ | key_list ',' maybe_space key maybe_space {
+ $$ = $1;
+ $$->addValue(parser->sinkFloatingValue($4));
+ }
+ ;
+
+key:
+ maybe_unary_operator PERCENTAGE {
+ $$.setFromNumber($1 * $2);
+ }
+ | IDENT {
+ if ($1.equalIgnoringCase("from"))
+ $$.setFromNumber(0);
+ else if ($1.equalIgnoringCase("to"))
+ $$.setFromNumber(100);
+ else {
+ YYERROR;
+ }
+ }
+ ;
+
+keyframes_error_recovery:
+ error rule_error_recovery {
+ parser->reportError(parser->lastLocationLabel(), CSSParser::InvalidKeyframeSelectorError);
+ }
+ ;
+
+before_page_rule:
+ /* empty */ {
+ parser->startRuleHeader(CSSRuleSourceData::PAGE_RULE);
+ }
+ ;
+
+page:
+ before_page_rule PAGE_SYM maybe_space page_selector at_rule_header_end
+ '{' at_rule_body_start maybe_space_before_declaration declarations_and_margins closing_brace {
+ if ($4)
+ $$ = parser->createPageRule(parser->sinkFloatingSelector($4));
+ else {
+ // Clear properties in the invalid @page rule.
+ parser->clearProperties();
+ // Also clear margin at-rules here once we fully implement margin at-rules parsing.
+ $$ = 0;
+ }
+ }
+ ;
+
+page_selector:
+ IDENT maybe_space {
+ $$ = parser->createFloatingSelectorWithTagName(QualifiedName(nullAtom, $1, parser->m_defaultNamespace));
+ $$->setForPage();
+ }
+ | IDENT pseudo_page maybe_space {
+ $$ = $2;
+ $$->prependTagSelector(QualifiedName(nullAtom, $1, parser->m_defaultNamespace));
+ $$->setForPage();
+ }
+ | pseudo_page maybe_space {
+ $$ = $1;
+ $$->setForPage();
+ }
+ | /* empty */ {
+ $$ = parser->createFloatingSelector();
+ $$->setForPage();
+ }
+ ;
+
+declarations_and_margins:
+ declaration_list
+ | declarations_and_margins margin_box maybe_space declaration_list
+ ;
+
+margin_box:
+ margin_sym {
+ parser->startDeclarationsForMarginBox();
+ } maybe_space '{' maybe_space declaration_list closing_brace {
+ $$ = parser->createMarginAtRule($1);
+ }
+ ;
+
+margin_sym :
+ TOPLEFTCORNER_SYM {
+ $$ = CSSSelector::TopLeftCornerMarginBox;
+ }
+ | TOPLEFT_SYM {
+ $$ = CSSSelector::TopLeftMarginBox;
+ }
+ | TOPCENTER_SYM {
+ $$ = CSSSelector::TopCenterMarginBox;
+ }
+ | TOPRIGHT_SYM {
+ $$ = CSSSelector::TopRightMarginBox;
+ }
+ | TOPRIGHTCORNER_SYM {
+ $$ = CSSSelector::TopRightCornerMarginBox;
+ }
+ | BOTTOMLEFTCORNER_SYM {
+ $$ = CSSSelector::BottomLeftCornerMarginBox;
+ }
+ | BOTTOMLEFT_SYM {
+ $$ = CSSSelector::BottomLeftMarginBox;
+ }
+ | BOTTOMCENTER_SYM {
+ $$ = CSSSelector::BottomCenterMarginBox;
+ }
+ | BOTTOMRIGHT_SYM {
+ $$ = CSSSelector::BottomRightMarginBox;
+ }
+ | BOTTOMRIGHTCORNER_SYM {
+ $$ = CSSSelector::BottomRightCornerMarginBox;
+ }
+ | LEFTTOP_SYM {
+ $$ = CSSSelector::LeftTopMarginBox;
+ }
+ | LEFTMIDDLE_SYM {
+ $$ = CSSSelector::LeftMiddleMarginBox;
+ }
+ | LEFTBOTTOM_SYM {
+ $$ = CSSSelector::LeftBottomMarginBox;
+ }
+ | RIGHTTOP_SYM {
+ $$ = CSSSelector::RightTopMarginBox;
+ }
+ | RIGHTMIDDLE_SYM {
+ $$ = CSSSelector::RightMiddleMarginBox;
+ }
+ | RIGHTBOTTOM_SYM {
+ $$ = CSSSelector::RightBottomMarginBox;
+ }
+ ;
+
+before_font_face_rule:
+ /* empty */ {
+ parser->startRuleHeader(CSSRuleSourceData::FONT_FACE_RULE);
+ }
+ ;
+
+font_face:
+ before_font_face_rule FONT_FACE_SYM at_rule_header_end_maybe_space
+ '{' at_rule_body_start maybe_space_before_declaration declaration_list closing_brace {
+ $$ = parser->createFontFaceRule();
+ }
+ ;
+
+before_viewport_rule:
+ /* empty */ {
+ parser->markViewportRuleBodyStart();
+ parser->startRuleHeader(CSSRuleSourceData::VIEWPORT_RULE);
+ }
+ ;
+
+viewport:
+ before_viewport_rule VIEWPORT_RULE_SYM at_rule_header_end_maybe_space
+ '{' at_rule_body_start maybe_space_before_declaration declaration_list closing_brace {
+ $$ = parser->createViewportRule();
+ parser->markViewportRuleBodyEnd();
+ }
+;
+
+region_selector:
+ selector_list {
+ parser->setReusableRegionSelectorVector($1);
+ $$ = parser->reusableRegionSelectorVector();
+ }
+;
+
+before_region_rule:
+ /* empty */ {
+ parser->startRuleHeader(CSSRuleSourceData::REGION_RULE);
+ }
+ ;
+
+region:
+ before_region_rule WEBKIT_REGION_RULE_SYM maybe_space region_selector at_rule_header_end '{' at_rule_body_start maybe_space region_block_rule_body closing_brace {
+ $$ = parser->createRegionRule($4, $9);
+ }
+;
+
+before_filter_rule:
+ /* empty */ {
+ parser->startRuleHeader(CSSRuleSourceData::FILTER_RULE);
+ parser->m_inFilterRule = true;
+ }
+ ;
+
+filter:
+ before_filter_rule WEBKIT_FILTER_RULE_SYM maybe_space IDENT at_rule_header_end_maybe_space
+ '{' at_rule_body_start maybe_space_before_declaration declaration_list closing_brace {
+ parser->m_inFilterRule = false;
+ $$ = parser->createFilterRule($4);
+ }
+ ;
+
+combinator:
+ '+' maybe_space { $$ = CSSSelector::DirectAdjacent; }
+ | '~' maybe_space { $$ = CSSSelector::IndirectAdjacent; }
+ | '>' maybe_space { $$ = CSSSelector::Child; }
+ | '^' maybe_space {
+ if (!RuntimeEnabledFeatures::shadowDOMEnabled())
+ YYERROR;
+ $$ = CSSSelector::ChildTree;
+ }
+ | '^' '^' maybe_space {
+ if (!RuntimeEnabledFeatures::shadowDOMEnabled())
+ YYERROR;
+ $$ = CSSSelector::DescendantTree;
+ }
+ ;
+
+maybe_unary_operator:
+ unary_operator
+ | /* empty */ { $$ = 1; }
+ ;
+
+unary_operator:
+ '-' { $$ = -1; }
+ | '+' { $$ = 1; }
+ ;
+
+maybe_space_before_declaration:
+ maybe_space {
+ parser->startProperty();
+ }
+ ;
+
+before_selector_list:
+ /* empty */ {
+ parser->startRuleHeader(CSSRuleSourceData::STYLE_RULE);
+ parser->startSelector();
+ }
+ ;
+
+at_rule_header_end:
+ /* empty */ {
+ parser->endRuleHeader();
+ }
+ ;
+
+at_selector_end:
+ /* empty */ {
+ parser->endSelector();
+ }
+ ;
+
+ruleset:
+ before_selector_list selector_list at_selector_end at_rule_header_end '{' at_rule_body_start maybe_space_before_declaration declaration_list closing_brace {
+ $$ = parser->createStyleRule($2);
+ }
+ ;
+
+before_selector_group_item:
+ /* empty */ {
+ parser->startSelector();
+ }
+
+selector_list:
+ selector %prec UNIMPORTANT_TOK {
+ $$ = parser->reusableSelectorVector();
+ $$->shrink(0);
+ $$->append(parser->sinkFloatingSelector($1));
+ }
+ | selector_list at_selector_end ',' maybe_space before_selector_group_item selector %prec UNIMPORTANT_TOK {
+ $$ = $1;
+ $$->append(parser->sinkFloatingSelector($6));
+ }
+ ;
+
+relative_selector:
+ combinator selector {
+ $$ = $2;
+ CSSParserSelector* end = $$;
+ while (end->tagHistory())
+ end = end->tagHistory();
+ end->setRelation($1);
+ }
+ | selector
+ ;
+
+selector:
+ simple_selector
+ | selector WHITESPACE
+ | selector WHITESPACE simple_selector
+ {
+ $$ = $3;
+ CSSParserSelector* end = $$;
+ while (end->tagHistory())
+ end = end->tagHistory();
+ end->setRelation(CSSSelector::Descendant);
+ if ($1->isContentPseudoElement())
+ end->setRelationIsAffectedByPseudoContent();
+ end->setTagHistory(parser->sinkFloatingSelector($1));
+ }
+ | selector combinator simple_selector {
+ $$ = $3;
+ CSSParserSelector* end = $$;
+ while (end->tagHistory())
+ end = end->tagHistory();
+ end->setRelation($2);
+ if ($1->isContentPseudoElement())
+ end->setRelationIsAffectedByPseudoContent();
+ end->setTagHistory(parser->sinkFloatingSelector($1));
+ }
+ ;
+
+namespace_selector:
+ /* empty */ '|' { $$.clear(); }
+ | '*' '|' { static const LChar star = '*'; $$.init(&star, 1); }
+ | IDENT '|'
+ ;
+
+simple_selector:
+ element_name {
+ $$ = parser->createFloatingSelectorWithTagName(QualifiedName(nullAtom, $1, parser->m_defaultNamespace));
+ }
+ | element_name specifier_list {
+ $$ = parser->rewriteSpecifiersWithElementName(nullAtom, $1, $2);
+ if (!$$)
+ YYERROR;
+ }
+ | specifier_list {
+ $$ = parser->rewriteSpecifiersWithNamespaceIfNeeded($1);
+ if (!$$)
+ YYERROR;
+ }
+ | namespace_selector element_name {
+ $$ = parser->createFloatingSelectorWithTagName(parser->determineNameInNamespace($1, $2));
+ if (!$$)
+ YYERROR;
+ }
+ | namespace_selector element_name specifier_list {
+ $$ = parser->rewriteSpecifiersWithElementName($1, $2, $3);
+ if (!$$)
+ YYERROR;
+ }
+ | namespace_selector specifier_list {
+ $$ = parser->rewriteSpecifiersWithElementName($1, starAtom, $2);
+ if (!$$)
+ YYERROR;
+ }
+ ;
+
+simple_selector_list:
+ simple_selector %prec UNIMPORTANT_TOK {
+ $$ = parser->createFloatingSelectorVector();
+ $$->append(parser->sinkFloatingSelector($1));
+ }
+ | simple_selector_list maybe_space ',' maybe_space simple_selector %prec UNIMPORTANT_TOK {
+ $$ = $1;
+ $$->append(parser->sinkFloatingSelector($5));
+ }
+ ;
+
+element_name:
+ IDENT {
+ if (parser->m_context.isHTMLDocument())
+ parser->tokenToLowerCase($1);
+ $$ = $1;
+ }
+ | '*' {
+ static const LChar star = '*';
+ $$.init(&star, 1);
+ }
+ ;
+
+specifier_list:
+ specifier
+ | specifier_list specifier {
+ $$ = parser->rewriteSpecifiers($1, $2);
+ }
+;
+
+specifier:
+ IDSEL {
+ $$ = parser->createFloatingSelector();
+ $$->setMatch(CSSSelector::Id);
+ if (isQuirksModeBehavior(parser->m_context.mode()))
+ parser->tokenToLowerCase($1);
+ $$->setValue($1);
+ }
+ | HEX {
+ if ($1[0] >= '0' && $1[0] <= '9') {
+ YYERROR;
+ } else {
+ $$ = parser->createFloatingSelector();
+ $$->setMatch(CSSSelector::Id);
+ if (isQuirksModeBehavior(parser->m_context.mode()))
+ parser->tokenToLowerCase($1);
+ $$->setValue($1);
+ }
+ }
+ | class
+ | attrib
+ | pseudo
+ ;
+
+class:
+ '.' IDENT {
+ $$ = parser->createFloatingSelector();
+ $$->setMatch(CSSSelector::Class);
+ if (isQuirksModeBehavior(parser->m_context.mode()))
+ parser->tokenToLowerCase($2);
+ $$->setValue($2);
+ }
+ ;
+
+attr_name:
+ IDENT maybe_space {
+ if (parser->m_context.isHTMLDocument())
+ parser->tokenToLowerCase($1);
+ $$ = $1;
+ }
+ ;
+
+attrib:
+ '[' maybe_space attr_name closing_square_bracket {
+ $$ = parser->createFloatingSelector();
+ $$->setAttribute(QualifiedName(nullAtom, $3, nullAtom));
+ $$->setMatch(CSSSelector::Set);
+ }
+ | '[' maybe_space attr_name match maybe_space ident_or_string maybe_space closing_square_bracket {
+ $$ = parser->createFloatingSelector();
+ $$->setAttribute(QualifiedName(nullAtom, $3, nullAtom));
+ $$->setMatch((CSSSelector::Match)$4);
+ $$->setValue($6);
+ }
+ | '[' maybe_space namespace_selector attr_name closing_square_bracket {
+ $$ = parser->createFloatingSelector();
+ $$->setAttribute(parser->determineNameInNamespace($3, $4));
+ $$->setMatch(CSSSelector::Set);
+ }
+ | '[' maybe_space namespace_selector attr_name match maybe_space ident_or_string maybe_space closing_square_bracket {
+ $$ = parser->createFloatingSelector();
+ $$->setAttribute(parser->determineNameInNamespace($3, $4));
+ $$->setMatch((CSSSelector::Match)$5);
+ $$->setValue($7);
+ }
+ | '[' selector_recovery closing_square_bracket {
+ YYERROR;
+ }
+ ;
+
+match:
+ '=' {
+ $$ = CSSSelector::Exact;
+ }
+ | INCLUDES {
+ $$ = CSSSelector::List;
+ }
+ | DASHMATCH {
+ $$ = CSSSelector::Hyphen;
+ }
+ | BEGINSWITH {
+ $$ = CSSSelector::Begin;
+ }
+ | ENDSWITH {
+ $$ = CSSSelector::End;
+ }
+ | CONTAINS {
+ $$ = CSSSelector::Contain;
+ }
+ ;
+
+ident_or_string:
+ IDENT
+ | STRING
+ ;
+
+pseudo_page:
+ ':' IDENT {
+ if ($2.isFunction())
+ YYERROR;
+ $$ = parser->createFloatingSelector();
+ $$->setMatch(CSSSelector::PagePseudoClass);
+ parser->tokenToLowerCase($2);
+ $$->setValue($2);
+ CSSSelector::PseudoType type = $$->pseudoType();
+ if (type == CSSSelector::PseudoUnknown)
+ YYERROR;
+ }
+
+pseudo:
+ ':' error_location IDENT {
+ if ($3.isFunction())
+ YYERROR;
+ $$ = parser->createFloatingSelector();
+ $$->setMatch(CSSSelector::PseudoClass);
+ parser->tokenToLowerCase($3);
+ $$->setValue($3);
+ CSSSelector::PseudoType type = $$->pseudoType();
+ if (type == CSSSelector::PseudoUnknown) {
+ parser->reportError($2, CSSParser::InvalidSelectorPseudoError);
+ YYERROR;
+ }
+ }
+ | ':' ':' error_location IDENT {
+ if ($4.isFunction())
+ YYERROR;
+ $$ = parser->createFloatingSelector();
+ $$->setMatch(CSSSelector::PseudoElement);
+ parser->tokenToLowerCase($4);
+ $$->setValue($4);
+ // FIXME: This call is needed to force selector to compute the pseudoType early enough.
+ CSSSelector::PseudoType type = $$->pseudoType();
+ if (type == CSSSelector::PseudoUnknown) {
+ parser->reportError($3, CSSParser::InvalidSelectorPseudoError);
+ YYERROR;
+ }
+ }
+ // used by ::cue(:past/:future)
+ | ':' ':' CUEFUNCTION maybe_space simple_selector_list maybe_space closing_parenthesis {
+ $$ = parser->createFloatingSelector();
+ $$->setMatch(CSSSelector::PseudoElement);
+ $$->adoptSelectorVector(*parser->sinkFloatingSelectorVector($5));
+ $$->setValue($3);
+ CSSSelector::PseudoType type = $$->pseudoType();
+ if (type != CSSSelector::PseudoCue)
+ YYERROR;
+ }
+ | ':' ':' CUEFUNCTION selector_recovery closing_parenthesis {
+ YYERROR;
+ }
+ | ':' ':' DISTRIBUTEDFUNCTION maybe_space relative_selector closing_parenthesis {
+ $$ = parser->createFloatingSelector();
+ $$->setMatch(CSSSelector::PseudoElement);
+ $$->setFunctionArgumentSelector($5);
+ parser->tokenToLowerCase($3);
+ $$->setValue($3);
+ }
+ | ':' ':' DISTRIBUTEDFUNCTION selector_recovery closing_parenthesis {
+ YYERROR;
+ }
+ // use by :-webkit-any.
+ // FIXME: should we support generic selectors here or just simple_selectors?
+ // Use simple_selector_list for now to match -moz-any.
+ // See http://lists.w3.org/Archives/Public/www-style/2010Sep/0566.html for some
+ // related discussion with respect to :not.
+ | ':' ANYFUNCTION maybe_space simple_selector_list maybe_space closing_parenthesis {
+ $$ = parser->createFloatingSelector();
+ $$->setMatch(CSSSelector::PseudoClass);
+ $$->adoptSelectorVector(*parser->sinkFloatingSelectorVector($4));
+ parser->tokenToLowerCase($2);
+ $$->setValue($2);
+ CSSSelector::PseudoType type = $$->pseudoType();
+ if (type != CSSSelector::PseudoAny)
+ YYERROR;
+ }
+ | ':' ANYFUNCTION selector_recovery closing_parenthesis {
+ YYERROR;
+ }
+ // used by :nth-*(ax+b)
+ | ':' FUNCTION maybe_space NTH maybe_space closing_parenthesis {
+ $$ = parser->createFloatingSelector();
+ $$->setMatch(CSSSelector::PseudoClass);
+ $$->setArgument($4);
+ $$->setValue($2);
+ CSSSelector::PseudoType type = $$->pseudoType();
+ if (type == CSSSelector::PseudoUnknown)
+ YYERROR;
+ }
+ // used by :nth-*
+ | ':' FUNCTION maybe_space maybe_unary_operator INTEGER maybe_space closing_parenthesis {
+ $$ = parser->createFloatingSelector();
+ $$->setMatch(CSSSelector::PseudoClass);
+ $$->setArgument(AtomicString::number($4 * $5));
+ $$->setValue($2);
+ CSSSelector::PseudoType type = $$->pseudoType();
+ if (type == CSSSelector::PseudoUnknown)
+ YYERROR;
+ }
+ // used by :nth-*(odd/even) and :lang
+ | ':' FUNCTION maybe_space IDENT maybe_space closing_parenthesis {
+ $$ = parser->createFloatingSelector();
+ $$->setMatch(CSSSelector::PseudoClass);
+ $$->setArgument($4);
+ parser->tokenToLowerCase($2);
+ $$->setValue($2);
+ CSSSelector::PseudoType type = $$->pseudoType();
+ if (type == CSSSelector::PseudoUnknown)
+ YYERROR;
+ else if (type == CSSSelector::PseudoNthChild ||
+ type == CSSSelector::PseudoNthOfType ||
+ type == CSSSelector::PseudoNthLastChild ||
+ type == CSSSelector::PseudoNthLastOfType) {
+ if (!isValidNthToken($4))
+ YYERROR;
+ }
+ }
+ | ':' FUNCTION selector_recovery closing_parenthesis {
+ YYERROR;
+ }
+ // used by :not
+ | ':' NOTFUNCTION maybe_space simple_selector maybe_space closing_parenthesis {
+ if (!$4->isSimple())
+ YYERROR;
+ else {
+ $$ = parser->createFloatingSelector();
+ $$->setMatch(CSSSelector::PseudoClass);
+
+ Vector<OwnPtr<CSSParserSelector> > selectorVector;
+ selectorVector.append(parser->sinkFloatingSelector($4));
+ $$->adoptSelectorVector(selectorVector);
+
+ parser->tokenToLowerCase($2);
+ $$->setValue($2);
+ }
+ }
+ | ':' NOTFUNCTION selector_recovery closing_parenthesis {
+ YYERROR;
+ }
+ | ':' HOSTFUNCTION maybe_space simple_selector_list maybe_space closing_parenthesis {
+ $$ = parser->createFloatingSelector();
+ $$->setMatch(CSSSelector::PseudoClass);
+ $$->adoptSelectorVector(*parser->sinkFloatingSelectorVector($4));
+ parser->tokenToLowerCase($2);
+ $$->setValue($2);
+ CSSSelector::PseudoType type = $$->pseudoType();
+ if (type != CSSSelector::PseudoHost)
+ YYERROR;
+ }
+ // used by :host()
+ | ':' HOSTFUNCTION maybe_space closing_parenthesis {
+ $$ = parser->createFloatingSelector();
+ $$->setMatch(CSSSelector::PseudoClass);
+ parser->tokenToLowerCase($2);
+ $$->setValue($2.atomicSubstring(0, $2.length() - 1));
+ CSSSelector::PseudoType type = $$->pseudoType();
+ if (type != CSSSelector::PseudoHost)
+ YYERROR;
+ }
+ | ':' HOSTFUNCTION selector_recovery closing_parenthesis {
+ YYERROR;
+ }
+ ;
+
+selector_recovery:
+ error error_location error_recovery;
+
+declaration_list:
+ /* empty */ { $$ = false; }
+ | declaration
+ | decl_list declaration {
+ $$ = $1 || $2;
+ }
+ | decl_list
+ ;
+
+decl_list:
+ declaration ';' maybe_space {
+ parser->startProperty();
+ $$ = $1;
+ }
+ | decl_list declaration ';' maybe_space {
+ parser->startProperty();
+ $$ = $1 || $2;
+ }
+ ;
+
+declaration:
+ VAR_DEFINITION maybe_space ':' maybe_space expr prio {
+ parser->storeVariableDeclaration($1, parser->sinkFloatingValueList($5), $6);
+ $$ = true;
+ parser->endProperty($6, true);
+ }
+ |
+ property ':' maybe_space error_location expr prio {
+ $$ = false;
+ bool isPropertyParsed = false;
+ if ($1 != CSSPropertyInvalid) {
+ parser->m_valueList = parser->sinkFloatingValueList($5);
+ int oldParsedProperties = parser->m_parsedProperties.size();
+ $$ = parser->parseValue($1, $6);
+ if (!$$) {
+ parser->rollbackLastProperties(parser->m_parsedProperties.size() - oldParsedProperties);
+ parser->reportError($4, CSSParser::InvalidPropertyValueError);
+ } else
+ isPropertyParsed = true;
+ parser->m_valueList = nullptr;
+ }
+ parser->endProperty($6, isPropertyParsed);
+ }
+ |
+ property ':' maybe_space error_location expr prio error error_recovery {
+ /* When we encounter something like p {color: red !important fail;} we should drop the declaration */
+ parser->reportError($4, CSSParser::InvalidPropertyValueError);
+ parser->endProperty(false, false);
+ $$ = false;
+ }
+ |
+ property ':' maybe_space error_location error error_recovery {
+ parser->reportError($4, CSSParser::InvalidPropertyValueError);
+ parser->endProperty(false, false);
+ $$ = false;
+ }
+ |
+ property error error_location error_recovery {
+ parser->reportError($3, CSSParser::PropertyDeclarationError);
+ parser->endProperty(false, false, CSSParser::GeneralError);
+ $$ = false;
+ }
+ |
+ error error_location error_recovery {
+ parser->reportError($2, CSSParser::PropertyDeclarationError);
+ $$ = false;
+ }
+ ;
+
+property:
+ error_location IDENT maybe_space {
+ $$ = cssPropertyID($2);
+ parser->setCurrentProperty($$);
+ if ($$ == CSSPropertyInvalid)
+ parser->reportError($1, CSSParser::InvalidPropertyError);
+ }
+ ;
+
+prio:
+ IMPORTANT_SYM maybe_space { $$ = true; }
+ | /* empty */ { $$ = false; }
+ ;
+
+ident_list:
+ IDENT maybe_space {
+ $$ = parser->createFloatingValueList();
+ $$->addValue(makeIdentValue($1));
+ }
+ | ident_list IDENT maybe_space {
+ $$ = $1;
+ $$->addValue(makeIdentValue($2));
+ }
+ ;
+
+track_names_list:
+ '(' maybe_space closing_parenthesis {
+ $$.setFromValueList(parser->sinkFloatingValueList(parser->createFloatingValueList()));
+ }
+ | '(' maybe_space ident_list closing_parenthesis {
+ $$.setFromValueList(parser->sinkFloatingValueList($3));
+ }
+ | '(' maybe_space expr_recovery closing_parenthesis {
+ YYERROR;
+ }
+ ;
+
+expr:
+ term {
+ $$ = parser->createFloatingValueList();
+ $$->addValue(parser->sinkFloatingValue($1));
+ }
+ | expr operator term {
+ $$ = $1;
+ $$->addValue(makeOperatorValue($2));
+ $$->addValue(parser->sinkFloatingValue($3));
+ }
+ | expr term {
+ $$ = $1;
+ $$->addValue(parser->sinkFloatingValue($2));
+ }
+ ;
+
+expr_recovery:
+ error error_location error_recovery {
+ parser->reportError($2, CSSParser::PropertyDeclarationError);
+ }
+ ;
+
+operator:
+ '/' maybe_space {
+ $$ = '/';
+ }
+ | ',' maybe_space {
+ $$ = ',';
+ }
+ ;
+
+term:
+ unary_term maybe_space
+ | unary_operator unary_term maybe_space { $$ = $2; $$.fValue *= $1; }
+ | STRING maybe_space { $$.id = CSSValueInvalid; $$.string = $1; $$.unit = CSSPrimitiveValue::CSS_STRING; }
+ | IDENT maybe_space { $$ = makeIdentValue($1); }
+ /* We might need to actually parse the number from a dimension, but we can't just put something that uses $$.string into unary_term. */
+ | DIMEN maybe_space { $$.id = CSSValueInvalid; $$.string = $1; $$.unit = CSSPrimitiveValue::CSS_DIMENSION; }
+ | unary_operator DIMEN maybe_space { $$.id = CSSValueInvalid; $$.string = $2; $$.unit = CSSPrimitiveValue::CSS_DIMENSION; }
+ | URI maybe_space { $$.id = CSSValueInvalid; $$.string = $1; $$.unit = CSSPrimitiveValue::CSS_URI; }
+ | UNICODERANGE maybe_space { $$.id = CSSValueInvalid; $$.string = $1; $$.unit = CSSPrimitiveValue::CSS_UNICODE_RANGE; }
+ | HEX maybe_space { $$.id = CSSValueInvalid; $$.string = $1; $$.unit = CSSPrimitiveValue::CSS_PARSER_HEXCOLOR; }
+ | '#' maybe_space { $$.id = CSSValueInvalid; $$.string = CSSParserString(); $$.unit = CSSPrimitiveValue::CSS_PARSER_HEXCOLOR; } /* Handle error case: "color: #;" */
+ | VARFUNCTION maybe_space IDENT closing_parenthesis maybe_space {
+ $$.id = CSSValueInvalid;
+ $$.string = $3;
+ $$.unit = CSSPrimitiveValue::CSS_VARIABLE_NAME;
+ }
+ | VARFUNCTION maybe_space expr_recovery closing_parenthesis {
+ YYERROR;
+ }
+ /* FIXME: according to the specs a function can have a unary_operator in front. I know no case where this makes sense */
+ | function maybe_space
+ | calc_function maybe_space
+ | min_or_max_function maybe_space
+ | '%' maybe_space { /* Handle width: %; */
+ $$.id = CSSValueInvalid; $$.unit = 0;
+ }
+ | track_names_list maybe_space
+ ;
+
+unary_term:
+ INTEGER { $$.setFromNumber($1); $$.isInt = true; }
+ | FLOATTOKEN { $$.setFromNumber($1); }
+ | PERCENTAGE { $$.setFromNumber($1, CSSPrimitiveValue::CSS_PERCENTAGE); }
+ | PXS { $$.setFromNumber($1, CSSPrimitiveValue::CSS_PX); }
+ | CMS { $$.setFromNumber($1, CSSPrimitiveValue::CSS_CM); }
+ | MMS { $$.setFromNumber($1, CSSPrimitiveValue::CSS_MM); }
+ | INS { $$.setFromNumber($1, CSSPrimitiveValue::CSS_IN); }
+ | PTS { $$.setFromNumber($1, CSSPrimitiveValue::CSS_PT); }
+ | PCS { $$.setFromNumber($1, CSSPrimitiveValue::CSS_PC); }
+ | DEGS { $$.setFromNumber($1, CSSPrimitiveValue::CSS_DEG); }
+ | RADS { $$.setFromNumber($1, CSSPrimitiveValue::CSS_RAD); }
+ | GRADS { $$.setFromNumber($1, CSSPrimitiveValue::CSS_GRAD); }
+ | TURNS { $$.setFromNumber($1, CSSPrimitiveValue::CSS_TURN); }
+ | MSECS { $$.setFromNumber($1, CSSPrimitiveValue::CSS_MS); }
+ | SECS { $$.setFromNumber($1, CSSPrimitiveValue::CSS_S); }
+ | HERTZ { $$.setFromNumber($1, CSSPrimitiveValue::CSS_HZ); }
+ | KHERTZ { $$.setFromNumber($1, CSSPrimitiveValue::CSS_KHZ); }
+ | EMS { $$.setFromNumber($1, CSSPrimitiveValue::CSS_EMS); }
+ | QEMS { $$.setFromNumber($1, CSSParserValue::Q_EMS); }
+ | EXS { $$.setFromNumber($1, CSSPrimitiveValue::CSS_EXS); }
+ | REMS {
+ $$.setFromNumber($1, CSSPrimitiveValue::CSS_REMS);
+ if (parser->m_styleSheet)
+ parser->m_styleSheet->parserSetUsesRemUnits(true);
+ }
+ | CHS { $$.setFromNumber($1, CSSPrimitiveValue::CSS_CHS); }
+ | VW { $$.setFromNumber($1, CSSPrimitiveValue::CSS_VW); }
+ | VH { $$.setFromNumber($1, CSSPrimitiveValue::CSS_VH); }
+ | VMIN { $$.setFromNumber($1, CSSPrimitiveValue::CSS_VMIN); }
+ | VMAX { $$.setFromNumber($1, CSSPrimitiveValue::CSS_VMAX); }
+ | DPPX { $$.setFromNumber($1, CSSPrimitiveValue::CSS_DPPX); }
+ | DPI { $$.setFromNumber($1, CSSPrimitiveValue::CSS_DPI); }
+ | DPCM { $$.setFromNumber($1, CSSPrimitiveValue::CSS_DPCM); }
+ | FR { $$.setFromNumber($1, CSSPrimitiveValue::CSS_FR); }
+ ;
+
+function:
+ FUNCTION maybe_space expr closing_parenthesis {
+ $$.setFromFunction(parser->createFloatingFunction($1, parser->sinkFloatingValueList($3)));
+ } |
+ FUNCTION maybe_space closing_parenthesis {
+ $$.setFromFunction(parser->createFloatingFunction($1, parser->sinkFloatingValueList(parser->createFloatingValueList())));
+ } |
+ FUNCTION maybe_space expr_recovery closing_parenthesis {
+ YYERROR;
+ }
+ ;
+
+calc_func_term:
+ unary_term
+ | VARFUNCTION maybe_space IDENT closing_parenthesis {
+ $$.id = CSSValueInvalid;
+ $$.string = $3;
+ $$.unit = CSSPrimitiveValue::CSS_VARIABLE_NAME;
+ }
+ | unary_operator unary_term { $$ = $2; $$.fValue *= $1; }
+ ;
+
+calc_func_operator:
+ space '+' space {
+ $$ = '+';
+ }
+ | space '-' space {
+ $$ = '-';
+ }
+ | calc_maybe_space '*' maybe_space {
+ $$ = '*';
+ }
+ | calc_maybe_space '/' maybe_space {
+ $$ = '/';
+ }
+ ;
+
+calc_maybe_space:
+ /* empty */
+ | WHITESPACE
+ ;
+
+calc_func_paren_expr:
+ '(' maybe_space calc_func_expr calc_maybe_space closing_parenthesis {
+ $$ = $3;
+ $$->insertValueAt(0, makeOperatorValue('('));
+ $$->addValue(makeOperatorValue(')'));
+ }
+ | '(' maybe_space expr_recovery closing_parenthesis {
+ YYERROR;
+ }
+ ;
+
+calc_func_expr:
+ calc_func_term {
+ $$ = parser->createFloatingValueList();
+ $$->addValue(parser->sinkFloatingValue($1));
+ }
+ | calc_func_expr calc_func_operator calc_func_term {
+ $$ = $1;
+ $$->addValue(makeOperatorValue($2));
+ $$->addValue(parser->sinkFloatingValue($3));
+ }
+ | calc_func_expr calc_func_operator calc_func_paren_expr {
+ $$ = $1;
+ $$->addValue(makeOperatorValue($2));
+ $$->extend(*($3));
+ }
+ | calc_func_paren_expr
+ ;
+
+calc_func_expr_list:
+ calc_func_expr calc_maybe_space
+ | calc_func_expr_list ',' maybe_space calc_func_expr calc_maybe_space {
+ $$ = $1;
+ $$->addValue(makeOperatorValue(','));
+ $$->extend(*($4));
+ }
+ ;
+
+calc_function:
+ CALCFUNCTION maybe_space calc_func_expr calc_maybe_space closing_parenthesis {
+ $$.setFromFunction(parser->createFloatingFunction($1, parser->sinkFloatingValueList($3)));
+ }
+ | CALCFUNCTION maybe_space expr_recovery closing_parenthesis {
+ YYERROR;
+ }
+ ;
+
+
+min_or_max:
+ MINFUNCTION
+ | MAXFUNCTION
+ ;
+
+min_or_max_function:
+ min_or_max maybe_space calc_func_expr_list closing_parenthesis {
+ $$.setFromFunction(parser->createFloatingFunction($1, parser->sinkFloatingValueList($3)));
+ }
+ | min_or_max maybe_space expr_recovery closing_parenthesis {
+ YYERROR;
+ }
+ ;
+
+invalid_at:
+ ATKEYWORD
+ | margin_sym
+ ;
+
+at_rule_recovery:
+ at_rule_header_recovery at_invalid_rule_header_end at_rule_end
+ ;
+
+at_rule_header_recovery:
+ error error_location rule_error_recovery {
+ parser->reportError($2, CSSParser::InvalidRuleError);
+ }
+ ;
+
+at_rule_end:
+ at_invalid_rule_header_end semi_or_eof
+ | at_invalid_rule_header_end invalid_block
+ ;
+
+regular_invalid_at_rule_header:
+ keyframes_rule_start at_rule_header_recovery
+ | before_page_rule PAGE_SYM at_rule_header_recovery
+ | before_font_face_rule FONT_FACE_SYM at_rule_header_recovery
+ | before_supports_rule SUPPORTS_SYM error error_location rule_error_recovery {
+ parser->reportError($4, CSSParser::InvalidSupportsConditionError);
+ parser->popSupportsRuleData();
+ }
+ | before_viewport_rule VIEWPORT_RULE_SYM at_rule_header_recovery {
+ parser->markViewportRuleBodyEnd();
+ }
+ | before_filter_rule WEBKIT_FILTER_RULE_SYM at_rule_header_recovery
+ | import_rule_start at_rule_header_recovery
+ | NAMESPACE_SYM at_rule_header_recovery
+ | before_region_rule WEBKIT_REGION_RULE_SYM at_rule_header_recovery
+ | error_location invalid_at at_rule_header_recovery {
+ parser->resumeErrorLogging();
+ parser->reportError($1, CSSParser::InvalidRuleError);
+ }
+ ;
+
+invalid_rule:
+ error error_location rule_error_recovery at_invalid_rule_header_end invalid_block {
+ parser->reportError($2, CSSParser::InvalidRuleError);
+ }
+ | regular_invalid_at_rule_header at_invalid_rule_header_end ';'
+ | regular_invalid_at_rule_header at_invalid_rule_header_end invalid_block
+ | media_rule_start maybe_media_list ';'
+ ;
+
+invalid_rule_header:
+ error error_location rule_error_recovery at_invalid_rule_header_end {
+ parser->reportError($2, CSSParser::InvalidRuleError);
+ }
+ | regular_invalid_at_rule_header at_invalid_rule_header_end
+ | media_rule_start maybe_media_list
+ ;
+
+at_invalid_rule_header_end:
+ /* empty */ {
+ parser->endInvalidRuleHeader();
+ }
+ ;
+
+invalid_block:
+ '{' error_recovery closing_brace {
+ parser->invalidBlockHit();
+ }
+ ;
+
+invalid_square_brackets_block:
+ '[' error_recovery closing_square_bracket
+ ;
+
+invalid_parentheses_block:
+ opening_parenthesis error_recovery closing_parenthesis;
+
+opening_parenthesis:
+ '(' | FUNCTION | CALCFUNCTION | VARFUNCTION | MINFUNCTION | MAXFUNCTION | ANYFUNCTION | NOTFUNCTION | CUEFUNCTION | DISTRIBUTEDFUNCTION | HOSTFUNCTION
+ ;
+
+error_location: {
+ $$ = parser->currentLocation();
+ }
+ ;
+
+location_label: {
+ parser->setLocationLabel(parser->currentLocation());
+ }
+ ;
+
+error_recovery:
+ /* empty */
+ | error_recovery error
+ | error_recovery invalid_block
+ | error_recovery invalid_square_brackets_block
+ | error_recovery invalid_parentheses_block
+ ;
+
+rule_error_recovery:
+ /* empty */
+ | rule_error_recovery error
+ | rule_error_recovery invalid_square_brackets_block
+ | rule_error_recovery invalid_parentheses_block
+ ;
+
+%%
+
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSGrammar.y.in b/chromium/third_party/WebKit/Source/core/css/CSSGrammar.y.in
deleted file mode 100644
index da016a2f6ee..00000000000
--- a/chromium/third_party/WebKit/Source/core/css/CSSGrammar.y.in
+++ /dev/null
@@ -1,1937 +0,0 @@
-/*
- * Copyright (C) 2002-2003 Lars Knoll (knoll@kde.org)
- * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 Apple Inc. All rights reserved.
- * Copyright (C) 2006 Alexey Proskuryakov (ap@nypop.com)
- * Copyright (C) 2008 Eric Seidel <eric@webkit.org>
- * Copyright (C) 2012 Intel Corporation. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- *
- */
-
-%pure_parser
-
-%parse-param { CSSParser* parser }
-%lex-param { CSSParser* parser }
-
-%union {
- bool boolean;
- char character;
- int integer;
- double number;
- CSSParserString string;
-
- StyleRuleBase* rule;
- Vector<RefPtr<StyleRuleBase> >* ruleList;
- CSSParserSelector* selector;
- Vector<OwnPtr<CSSParserSelector> >* selectorList;
- CSSSelector::MarginBoxType marginBox;
- CSSSelector::Relation relation;
- MediaQuerySet* mediaList;
- MediaQuery* mediaQuery;
- MediaQuery::Restrictor mediaQueryRestrictor;
- MediaQueryExp* mediaQueryExp;
- CSSParserValue value;
- CSSParserValueList* valueList;
- Vector<OwnPtr<MediaQueryExp> >* mediaQueryExpList;
- StyleKeyframe* keyframe;
- Vector<RefPtr<StyleKeyframe> >* keyframeRuleList;
- float val;
- CSSPropertyID id;
- CSSParserLocation location;
-}
-
-%{
-
-static inline int cssyyerror(void*, const char*)
-{
- return 1;
-}
-
-static inline bool isCSSTokenAString(int yytype)
-{
- switch (yytype) {
- case IDENT:
- case STRING:
- case NTH:
- case HEX:
- case IDSEL:
- case DIMEN:
- case INVALIDDIMEN:
- case URI:
- case FUNCTION:
- case ANYFUNCTION:
- case HOSTFUNCTION:
- case NOTFUNCTION:
- case CALCFUNCTION:
- case MINFUNCTION:
- case MAXFUNCTION:
- case VARFUNCTION:
- case VAR_DEFINITION:
- case UNICODERANGE:
- return true;
- default:
- return false;
- }
-}
-
-inline static CSSParserValue makeOperatorValue(int value)
-{
- CSSParserValue v;
- v.id = CSSValueInvalid;
- v.unit = CSSParserValue::Operator;
- v.iValue = value;
- return v;
-}
-
-%}
-
-%expect 0
-
-%nonassoc LOWEST_PREC
-
-%left UNIMPORTANT_TOK
-
-%token WHITESPACE SGML_CD
-%token TOKEN_EOF 0
-
-%token INCLUDES
-%token DASHMATCH
-%token BEGINSWITH
-%token ENDSWITH
-%token CONTAINS
-
-%token <string> STRING
-%right <string> IDENT
-%token <string> NTH
-
-%nonassoc <string> HEX
-%nonassoc <string> IDSEL
-%nonassoc ':'
-%nonassoc '.'
-%nonassoc '['
-%nonassoc <string> '*'
-%nonassoc error
-%left '|'
-
-%token IMPORT_SYM
-%token PAGE_SYM
-%token MEDIA_SYM
-%token SUPPORTS_SYM
-%token FONT_FACE_SYM
-%token HOST_SYM
-%token CHARSET_SYM
-%token NAMESPACE_SYM
-%token VIEWPORT_RULE_SYM
-%token INTERNAL_DECLS_SYM
-%token INTERNAL_MEDIALIST_SYM
-%token INTERNAL_RULE_SYM
-%token INTERNAL_SELECTOR_SYM
-%token INTERNAL_VALUE_SYM
-%token INTERNAL_KEYFRAME_RULE_SYM
-%token INTERNAL_KEYFRAME_KEY_LIST_SYM
-%token INTERNAL_SUPPORTS_CONDITION_SYM
-%token KEYFRAMES_SYM
-%token WEBKIT_KEYFRAMES_SYM
-%token WEBKIT_REGION_RULE_SYM
-%token WEBKIT_FILTER_RULE_SYM
-%token <marginBox> TOPLEFTCORNER_SYM
-%token <marginBox> TOPLEFT_SYM
-%token <marginBox> TOPCENTER_SYM
-%token <marginBox> TOPRIGHT_SYM
-%token <marginBox> TOPRIGHTCORNER_SYM
-%token <marginBox> BOTTOMLEFTCORNER_SYM
-%token <marginBox> BOTTOMLEFT_SYM
-%token <marginBox> BOTTOMCENTER_SYM
-%token <marginBox> BOTTOMRIGHT_SYM
-%token <marginBox> BOTTOMRIGHTCORNER_SYM
-%token <marginBox> LEFTTOP_SYM
-%token <marginBox> LEFTMIDDLE_SYM
-%token <marginBox> LEFTBOTTOM_SYM
-%token <marginBox> RIGHTTOP_SYM
-%token <marginBox> RIGHTMIDDLE_SYM
-%token <marginBox> RIGHTBOTTOM_SYM
-
-%token ATKEYWORD
-
-%token IMPORTANT_SYM
-%token MEDIA_ONLY
-%token MEDIA_NOT
-%token MEDIA_AND
-
-%token SUPPORTS_NOT
-%token SUPPORTS_AND
-%token SUPPORTS_OR
-
-%token <number> REMS
-%token <number> CHS
-%token <number> QEMS
-%token <number> EMS
-%token <number> EXS
-%token <number> PXS
-%token <number> CMS
-%token <number> MMS
-%token <number> INS
-%token <number> PTS
-%token <number> PCS
-%token <number> DEGS
-%token <number> RADS
-%token <number> GRADS
-%token <number> TURNS
-%token <number> MSECS
-%token <number> SECS
-%token <number> HERTZ
-%token <number> KHERTZ
-%token <string> DIMEN
-%token <string> INVALIDDIMEN
-%token <number> PERCENTAGE
-%token <number> FLOATTOKEN
-%token <number> INTEGER
-%token <number> VW
-%token <number> VH
-%token <number> VMIN
-%token <number> VMAX
-%token <number> DPPX
-%token <number> DPI
-%token <number> DPCM
-%token <number> FR
-
-%token <string> URI
-%token <string> FUNCTION
-%token <string> ANYFUNCTION
-%token <string> CUEFUNCTION
-%token <string> NOTFUNCTION
-%token <string> DISTRIBUTEDFUNCTION
-%token <string> CALCFUNCTION
-%token <string> MINFUNCTION
-%token <string> MAXFUNCTION
-%token <string> VARFUNCTION
-%token <string> VAR_DEFINITION
-%token <string> PARTFUNCTION
-%token <string> HOSTFUNCTION
-
-%token <string> UNICODERANGE
-
-%type <relation> combinator
-
-%type <rule> charset
-%type <rule> ruleset
-%type <rule> media
-%type <rule> import
-%type <rule> namespace
-%type <rule> page
-%type <rule> margin_box
-%type <rule> font_face
-%type <rule> host
-%type <rule> keyframes
-%type <rule> invalid_rule
-%type <rule> rule
-%type <rule> valid_rule
-%type <ruleList> block_rule_body
-%type <ruleList> block_rule_list
-%type <ruleList> region_block_rule_body
-%type <ruleList> region_block_rule_list
-%type <rule> block_rule
-%type <rule> block_valid_rule
-%type <rule> region
-%type <rule> supports
-%type <rule> viewport
-%type <rule> filter
-
-%type <string> maybe_ns_prefix
-
-%type <string> namespace_selector
-
-%type <string> string_or_uri
-%type <string> ident_or_string
-%type <string> medium
-%type <marginBox> margin_sym
-
-%type <mediaList> media_list
-%type <mediaList> maybe_media_list
-%type <mediaList> mq_list
-%type <mediaQuery> media_query
-%type <mediaQuery> valid_media_query
-%type <mediaQueryRestrictor> maybe_media_restrictor
-%type <valueList> maybe_media_value
-%type <mediaQueryExp> media_query_exp
-%type <mediaQueryExpList> media_query_exp_list
-%type <mediaQueryExpList> maybe_and_media_query_exp_list
-
-%type <boolean> supports_condition
-%type <boolean> supports_condition_in_parens
-%type <boolean> supports_negation
-%type <boolean> supports_conjunction
-%type <boolean> supports_disjunction
-%type <boolean> supports_declaration_condition
-
-%type <string> keyframe_name
-%type <keyframe> keyframe_rule
-%type <keyframeRuleList> keyframes_rule
-%type <keyframeRuleList> keyframe_rule_list
-%type <valueList> key_list
-%type <value> key
-
-%type <id> property
-
-%type <selector> specifier
-%type <selector> specifier_list
-%type <selector> simple_selector
-%type <selector> selector
-%type <selector> relative_selector
-%type <selectorList> selector_list
-%type <selectorList> simple_selector_list
-%type <selectorList> region_selector
-%type <selector> class
-%type <selector> attrib
-%type <selector> pseudo
-%type <selector> pseudo_page
-%type <selector> page_selector
-
-%type <boolean> declaration_list
-%type <boolean> decl_list
-%type <boolean> declaration
-%type <boolean> declarations_and_margins
-
-%type <boolean> prio
-
-%type <integer> match
-%type <integer> unary_operator
-%type <integer> maybe_unary_operator
-%type <character> operator
-
-%type <valueList> expr
-%type <value> term
-%type <value> unary_term
-%type <value> function
-%type <value> calc_func_term
-%type <character> calc_func_operator
-%type <valueList> calc_func_expr
-%type <valueList> calc_func_expr_list
-%type <valueList> calc_func_paren_expr
-%type <value> calc_function
-%type <string> min_or_max
-%type <value> min_or_max_function
-
-%type <string> element_name
-%type <string> attr_name
-
-%type <location> error_location
-
-%%
-
-stylesheet:
- maybe_charset maybe_sgml rule_list
- | internal_decls
- | internal_rule
- | internal_selector
- | internal_value
- | internal_medialist
- | internal_keyframe_rule
- | internal_keyframe_key_list
- | internal_supports_condition
- ;
-
-internal_rule:
- INTERNAL_RULE_SYM maybe_space valid_rule maybe_space TOKEN_EOF {
- parser->m_rule = $3;
- }
-;
-
-internal_keyframe_rule:
- INTERNAL_KEYFRAME_RULE_SYM maybe_space keyframe_rule maybe_space TOKEN_EOF {
- parser->m_keyframe = $3;
- }
-;
-
-internal_keyframe_key_list:
- INTERNAL_KEYFRAME_KEY_LIST_SYM maybe_space key_list TOKEN_EOF {
- parser->m_valueList = parser->sinkFloatingValueList($3);
- }
-;
-
-internal_decls:
- INTERNAL_DECLS_SYM maybe_space_before_declaration declaration_list TOKEN_EOF {
- /* can be empty */
- }
-;
-
-internal_value:
- INTERNAL_VALUE_SYM maybe_space expr TOKEN_EOF {
- parser->m_valueList = parser->sinkFloatingValueList($3);
- int oldParsedProperties = parser->m_parsedProperties.size();
- if (!parser->parseValue(parser->m_id, parser->m_important))
- parser->rollbackLastProperties(parser->m_parsedProperties.size() - oldParsedProperties);
- parser->m_valueList = nullptr;
- }
-;
-
-internal_medialist:
- INTERNAL_MEDIALIST_SYM maybe_space location_label maybe_media_list TOKEN_EOF {
- parser->m_mediaList = $4;
- }
-;
-
-internal_selector:
- INTERNAL_SELECTOR_SYM maybe_space selector_list TOKEN_EOF {
- if (parser->m_selectorListForParseSelector)
- parser->m_selectorListForParseSelector->adoptSelectorVector(*$3);
- }
-;
-
-internal_supports_condition:
- INTERNAL_SUPPORTS_CONDITION_SYM maybe_space supports_condition TOKEN_EOF {
- parser->m_supportsCondition = $3;
- }
-;
-
-maybe_space:
- /* empty */ %prec UNIMPORTANT_TOK
- | maybe_space WHITESPACE
- ;
-
-maybe_sgml:
- /* empty */
- | maybe_sgml SGML_CD
- | maybe_sgml WHITESPACE
- ;
-
-maybe_charset:
- /* empty */
- | charset
- ;
-
-closing_brace:
- '}'
- | %prec LOWEST_PREC TOKEN_EOF
- ;
-
-closing_parenthesis:
- ')'
- | %prec LOWEST_PREC TOKEN_EOF
- ;
-
-closing_square_bracket:
- ']'
- | %prec LOWEST_PREC TOKEN_EOF
- ;
-
-semi_or_eof:
- ';'
- | TOKEN_EOF
- ;
-
-charset:
- CHARSET_SYM maybe_space STRING maybe_space semi_or_eof {
- if (parser->m_styleSheet)
- parser->m_styleSheet->parserSetEncodingFromCharsetRule($3);
- parser->startEndUnknownRule();
- $$ = 0;
- }
- | CHARSET_SYM at_rule_recovery {
- $$ = 0;
- }
- ;
-
-rule_list:
- /* empty */
- | rule_list rule maybe_sgml {
- if ($2 && parser->m_styleSheet)
- parser->m_styleSheet->parserAppendRule($2);
- }
- ;
-
-valid_rule:
- ruleset
- | media
- | page
- | font_face
- | keyframes
- | namespace
- | import
- | region
- | supports
- | host
- | viewport
- | filter
- ;
-
-rule:
- valid_rule {
- parser->m_hadSyntacticallyValidCSSRule = true;
- }
- | invalid_rule
- ;
-
-block_rule_body:
- block_rule_list
- | block_rule_list error error_location rule_error_recovery {
- parser->reportError($3, CSSParser::InvalidRuleError);
- }
- ;
-
-block_rule_list:
- /* empty */ { $$ = 0; }
- | block_rule_list block_rule maybe_sgml {
- $$ = $1;
- if ($2) {
- if (!$$)
- $$ = parser->createRuleList();
- $$->append($2);
- }
- }
- ;
-
-region_block_rule_body:
- region_block_rule_list
- | region_block_rule_list error error_location rule_error_recovery {
- parser->reportError($3, CSSParser::InvalidRuleError);
- }
- ;
-
-region_block_rule_list:
- /* empty */ { $$ = 0; }
- | region_block_rule_list block_valid_rule maybe_sgml {
- $$ = $1;
- if ($2) {
- if (!$$)
- $$ = parser->createRuleList();
- $$->append($2);
- }
- }
- ;
-
-block_valid_rule:
- ruleset
- | page
- | font_face
- | media
- | keyframes
- | supports
- | viewport
- | filter
- ;
-
-block_rule:
- block_valid_rule
- | invalid_rule
- | namespace
- | import
- | region
- ;
-
-at_import_header_end_maybe_space:
- maybe_space {
- parser->endRuleHeader();
- parser->startRuleBody();
- }
- ;
-
-before_import_rule:
- /* empty */ {
- parser->startRuleHeader(CSSRuleSourceData::IMPORT_RULE);
- }
- ;
-
-import:
- before_import_rule IMPORT_SYM at_import_header_end_maybe_space string_or_uri maybe_space location_label maybe_media_list semi_or_eof {
- $$ = parser->createImportRule($4, $7);
- }
- | before_import_rule IMPORT_SYM at_import_header_end_maybe_space string_or_uri maybe_space location_label maybe_media_list invalid_block {
- $$ = 0;
- parser->endRuleBody(true);
- }
- | before_import_rule IMPORT_SYM at_rule_recovery {
- $$ = 0;
- parser->endRuleBody(true);
- }
- ;
-
-before_namespace_rule:
- /* empty */ {
- // FIXME: There should be parser->startRuleHeader.
- }
- ;
-
-namespace:
- before_namespace_rule NAMESPACE_SYM maybe_space maybe_ns_prefix string_or_uri maybe_space semi_or_eof {
- parser->addNamespace($4, $5);
- $$ = 0;
- }
- | before_namespace_rule NAMESPACE_SYM maybe_space maybe_ns_prefix string_or_uri maybe_space invalid_block {
- $$ = 0;
- }
- | before_namespace_rule NAMESPACE_SYM at_rule_recovery {
- $$ = 0;
- }
- ;
-
-maybe_ns_prefix:
-/* empty */ { $$.clear(); }
-| IDENT maybe_space
-;
-
-string_or_uri:
-STRING
-| URI
-;
-
-maybe_media_value:
- /*empty*/ {
- $$ = 0;
- }
- | ':' maybe_space expr {
- $$ = $3;
- }
- ;
-
-media_query_exp:
- '(' maybe_space IDENT maybe_space maybe_media_value closing_parenthesis maybe_space {
- parser->tokenToLowerCase($3);
- $$ = parser->createFloatingMediaQueryExp($3, $5);
- if (!$$)
- YYERROR;
- }
- | '(' error error_recovery closing_parenthesis {
- YYERROR;
- }
- ;
-
-media_query_exp_list:
- media_query_exp {
- $$ = parser->createFloatingMediaQueryExpList();
- $$->append(parser->sinkFloatingMediaQueryExp($1));
- }
- | media_query_exp_list MEDIA_AND maybe_space media_query_exp {
- $$ = $1;
- $$->append(parser->sinkFloatingMediaQueryExp($4));
- }
- ;
-
-maybe_and_media_query_exp_list:
- /*empty*/ {
- $$ = parser->createFloatingMediaQueryExpList();
- }
- | MEDIA_AND maybe_space media_query_exp_list {
- $$ = $3;
- }
- ;
-
-maybe_media_restrictor:
- /*empty*/ {
- $$ = MediaQuery::None;
- }
- | MEDIA_ONLY maybe_space {
- $$ = MediaQuery::Only;
- }
- | MEDIA_NOT maybe_space {
- $$ = MediaQuery::Not;
- }
- ;
-
-valid_media_query:
- media_query_exp_list {
- $$ = parser->createFloatingMediaQuery(parser->sinkFloatingMediaQueryExpList($1));
- }
- | maybe_media_restrictor medium maybe_and_media_query_exp_list {
- parser->tokenToLowerCase($2);
- $$ = parser->createFloatingMediaQuery($1, $2, parser->sinkFloatingMediaQueryExpList($3));
- }
- ;
-
-media_query:
- valid_media_query
- | valid_media_query error error_location rule_error_recovery {
- parser->reportError(parser->lastLocationLabel(), CSSParser::InvalidMediaQueryError);
- $$ = parser->createFloatingNotAllQuery();
- }
- | error error_location rule_error_recovery {
- parser->reportError(parser->lastLocationLabel(), CSSParser::InvalidMediaQueryError);
- $$ = parser->createFloatingNotAllQuery();
- }
- ;
-
-maybe_media_list:
- /* empty */ {
- $$ = parser->createMediaQuerySet();
- }
- | media_list
- ;
-
-media_list:
- media_query {
- $$ = parser->createMediaQuerySet();
- $$->addMediaQuery(parser->sinkFloatingMediaQuery($1));
- }
- | mq_list media_query {
- $$ = $1;
- $$->addMediaQuery(parser->sinkFloatingMediaQuery($2));
- }
- | mq_list {
- $$ = $1;
- $$->addMediaQuery(parser->sinkFloatingMediaQuery(parser->createFloatingNotAllQuery()));
- }
- ;
-
-mq_list:
- media_query ',' maybe_space location_label {
- $$ = parser->createMediaQuerySet();
- $$->addMediaQuery(parser->sinkFloatingMediaQuery($1));
- }
- | mq_list media_query ',' maybe_space location_label {
- $$ = $1;
- $$->addMediaQuery(parser->sinkFloatingMediaQuery($2));
- }
- ;
-
-at_rule_body_start:
- /* empty */ {
- parser->startRuleBody();
- }
- ;
-
-before_media_rule:
- /* empty */ {
- parser->startRuleHeader(CSSRuleSourceData::MEDIA_RULE);
- }
- ;
-
-at_rule_header_end_maybe_space:
- maybe_space {
- parser->endRuleHeader();
- }
- ;
-
-media:
- before_media_rule MEDIA_SYM maybe_space location_label media_list at_rule_header_end '{' at_rule_body_start maybe_space block_rule_body closing_brace {
- $$ = parser->createMediaRule($5, $10);
- }
- | before_media_rule MEDIA_SYM at_rule_header_end_maybe_space '{' at_rule_body_start maybe_space block_rule_body closing_brace {
- $$ = parser->createMediaRule(0, $7);
- }
- | before_media_rule MEDIA_SYM maybe_space location_label media_list semi_or_eof {
- $$ = 0;
- parser->endRuleBody(true);
- }
- | before_media_rule MEDIA_SYM at_rule_recovery {
- $$ = 0;
- parser->endRuleBody(true);
- }
- ;
-
-medium:
- IDENT maybe_space
- ;
-
-supports:
- before_supports_rule SUPPORTS_SYM maybe_space supports_condition at_supports_rule_header_end '{' at_rule_body_start maybe_space block_rule_body closing_brace {
- $$ = parser->createSupportsRule($4, $9);
- }
- | before_supports_rule SUPPORTS_SYM error error_location rule_error_recovery at_rule_end {
- $$ = 0;
- parser->reportError($4, CSSParser::InvalidSupportsConditionError);
- parser->endRuleBody(true);
- parser->popSupportsRuleData();
- }
- ;
-
-before_supports_rule:
- /* empty */ {
- parser->startRuleHeader(CSSRuleSourceData::SUPPORTS_RULE);
- parser->markSupportsRuleHeaderStart();
- }
- ;
-
-at_supports_rule_header_end:
- /* empty */ {
- parser->endRuleHeader();
- parser->markSupportsRuleHeaderEnd();
- }
- ;
-
-supports_condition:
- supports_condition_in_parens
- | supports_negation
- | supports_conjunction
- | supports_disjunction
- ;
-
-supports_negation:
- SUPPORTS_NOT maybe_space supports_condition_in_parens {
- $$ = !$3;
- }
- ;
-
-supports_conjunction:
- supports_condition_in_parens SUPPORTS_AND maybe_space supports_condition_in_parens {
- $$ = $1 && $4;
- }
- | supports_conjunction SUPPORTS_AND maybe_space supports_condition_in_parens {
- $$ = $1 && $4;
- }
- ;
-
-supports_disjunction:
- supports_condition_in_parens SUPPORTS_OR maybe_space supports_condition_in_parens {
- $$ = $1 || $4;
- }
- | supports_disjunction SUPPORTS_OR maybe_space supports_condition_in_parens {
- $$ = $1 || $4;
- }
- ;
-
-supports_condition_in_parens:
- '(' maybe_space supports_condition closing_parenthesis maybe_space {
- $$ = $3;
- }
- | supports_declaration_condition
- | '(' error error_location error_recovery closing_parenthesis maybe_space {
- parser->reportError($3, CSSParser::InvalidSupportsConditionError);
- $$ = false;
- }
- ;
-
-supports_declaration_condition:
- '(' maybe_space IDENT maybe_space ':' maybe_space expr prio closing_parenthesis maybe_space {
- $$ = false;
- CSSPropertyID id = cssPropertyID($3);
- if (id != CSSPropertyInvalid) {
- parser->m_valueList = parser->sinkFloatingValueList($7);
- int oldParsedProperties = parser->m_parsedProperties.size();
- $$ = parser->parseValue(id, $8);
- // We just need to know if the declaration is supported as it is written. Rollback any additions.
- if ($$)
- parser->rollbackLastProperties(parser->m_parsedProperties.size() - oldParsedProperties);
- }
- parser->m_valueList = nullptr;
- parser->endProperty($8, false);
- }
- | '(' maybe_space IDENT maybe_space ':' maybe_space error error_recovery closing_parenthesis maybe_space {
- $$ = false;
- parser->endProperty(false, false, CSSParser::GeneralError);
- }
- ;
-
-before_keyframes_rule:
- /* empty */ {
- parser->startRuleHeader(CSSRuleSourceData::KEYFRAMES_RULE);
- }
- ;
-
-keyframes:
- before_keyframes_rule KEYFRAMES_SYM maybe_space keyframe_name at_rule_header_end_maybe_space '{' at_rule_body_start maybe_space location_label keyframes_rule closing_brace {
- $$ = parser->createKeyframesRule($4, parser->sinkFloatingKeyframeVector($10), false /* isPrefixed */);
- }
- |
- before_keyframes_rule WEBKIT_KEYFRAMES_SYM maybe_space keyframe_name at_rule_header_end_maybe_space '{' at_rule_body_start maybe_space location_label keyframes_rule closing_brace {
- $$ = parser->createKeyframesRule($4, parser->sinkFloatingKeyframeVector($10), true /* isPrefixed */);
- }
- | before_keyframes_rule KEYFRAMES_SYM at_rule_recovery {
- $$ = 0;
- parser->endRuleBody(true);
- }
- | before_keyframes_rule WEBKIT_KEYFRAMES_SYM at_rule_recovery {
- $$ = 0;
- parser->endRuleBody(true);
- }
- ;
-
-keyframe_name:
- IDENT
- | STRING
- ;
-
-keyframes_rule:
- keyframe_rule_list
- | keyframe_rule_list keyframes_error_recovery {
- parser->clearProperties();
- };
-
-keyframe_rule_list:
- /* empty */ {
- $$ = parser->createFloatingKeyframeVector();
- parser->resumeErrorLogging();
- }
- | keyframe_rule_list keyframe_rule maybe_space location_label {
- $$ = $1;
- $$->append($2);
- }
- | keyframe_rule_list keyframes_error_recovery invalid_block maybe_space location_label {
- parser->clearProperties();
- parser->resumeErrorLogging();
- }
- ;
-
-keyframe_rule:
- key_list '{' maybe_space declaration_list closing_brace {
- $$ = parser->createKeyframe($1);
- }
- ;
-
-key_list:
- key maybe_space {
- $$ = parser->createFloatingValueList();
- $$->addValue(parser->sinkFloatingValue($1));
- }
- | key_list ',' maybe_space key maybe_space {
- $$ = $1;
- $$->addValue(parser->sinkFloatingValue($4));
- }
- ;
-
-key:
- maybe_unary_operator PERCENTAGE {
- $$.setFromNumber($1 * $2);
- }
- | IDENT {
- if ($1.equalIgnoringCase("from"))
- $$.setFromNumber(0);
- else if ($1.equalIgnoringCase("to"))
- $$.setFromNumber(100);
- else {
- YYERROR;
- }
- }
- ;
-
-keyframes_error_recovery:
- error rule_error_recovery {
- parser->reportError(parser->lastLocationLabel(), CSSParser::InvalidKeyframeSelectorError);
- }
- ;
-
-before_page_rule:
- /* empty */ {
- parser->startRuleHeader(CSSRuleSourceData::PAGE_RULE);
- }
- ;
-
-page:
- before_page_rule PAGE_SYM maybe_space page_selector at_rule_header_end
- '{' at_rule_body_start maybe_space_before_declaration declarations_and_margins closing_brace {
- if ($4)
- $$ = parser->createPageRule(parser->sinkFloatingSelector($4));
- else {
- // Clear properties in the invalid @page rule.
- parser->clearProperties();
- // Also clear margin at-rules here once we fully implement margin at-rules parsing.
- $$ = 0;
- parser->endRuleBody(true);
- }
- }
- | before_page_rule PAGE_SYM at_rule_recovery {
- parser->endRuleBody(true);
- $$ = 0;
- }
- ;
-
-page_selector:
- IDENT maybe_space {
- $$ = parser->createFloatingSelectorWithTagName(QualifiedName(nullAtom, $1, parser->m_defaultNamespace));
- $$->setForPage();
- }
- | IDENT pseudo_page maybe_space {
- $$ = $2;
- $$->prependTagSelector(QualifiedName(nullAtom, $1, parser->m_defaultNamespace));
- $$->setForPage();
- }
- | pseudo_page maybe_space {
- $$ = $1;
- $$->setForPage();
- }
- | /* empty */ {
- $$ = parser->createFloatingSelector();
- $$->setForPage();
- }
- ;
-
-declarations_and_margins:
- declaration_list
- | declarations_and_margins margin_box maybe_space declaration_list
- ;
-
-margin_box:
- margin_sym {
- parser->startDeclarationsForMarginBox();
- } maybe_space '{' maybe_space declaration_list closing_brace {
- $$ = parser->createMarginAtRule($1);
- }
- ;
-
-margin_sym :
- TOPLEFTCORNER_SYM {
- $$ = CSSSelector::TopLeftCornerMarginBox;
- }
- | TOPLEFT_SYM {
- $$ = CSSSelector::TopLeftMarginBox;
- }
- | TOPCENTER_SYM {
- $$ = CSSSelector::TopCenterMarginBox;
- }
- | TOPRIGHT_SYM {
- $$ = CSSSelector::TopRightMarginBox;
- }
- | TOPRIGHTCORNER_SYM {
- $$ = CSSSelector::TopRightCornerMarginBox;
- }
- | BOTTOMLEFTCORNER_SYM {
- $$ = CSSSelector::BottomLeftCornerMarginBox;
- }
- | BOTTOMLEFT_SYM {
- $$ = CSSSelector::BottomLeftMarginBox;
- }
- | BOTTOMCENTER_SYM {
- $$ = CSSSelector::BottomCenterMarginBox;
- }
- | BOTTOMRIGHT_SYM {
- $$ = CSSSelector::BottomRightMarginBox;
- }
- | BOTTOMRIGHTCORNER_SYM {
- $$ = CSSSelector::BottomRightCornerMarginBox;
- }
- | LEFTTOP_SYM {
- $$ = CSSSelector::LeftTopMarginBox;
- }
- | LEFTMIDDLE_SYM {
- $$ = CSSSelector::LeftMiddleMarginBox;
- }
- | LEFTBOTTOM_SYM {
- $$ = CSSSelector::LeftBottomMarginBox;
- }
- | RIGHTTOP_SYM {
- $$ = CSSSelector::RightTopMarginBox;
- }
- | RIGHTMIDDLE_SYM {
- $$ = CSSSelector::RightMiddleMarginBox;
- }
- | RIGHTBOTTOM_SYM {
- $$ = CSSSelector::RightBottomMarginBox;
- }
- ;
-
-before_font_face_rule:
- /* empty */ {
- parser->startRuleHeader(CSSRuleSourceData::FONT_FACE_RULE);
- }
- ;
-
-font_face:
- before_font_face_rule FONT_FACE_SYM at_rule_header_end_maybe_space
- '{' at_rule_body_start maybe_space_before_declaration declaration_list closing_brace {
- $$ = parser->createFontFaceRule();
- }
- | before_font_face_rule FONT_FACE_SYM at_rule_recovery {
- $$ = 0;
- parser->endRuleBody(true);
- }
-;
-
-before_host_rule:
- /* empty */ {
- parser->startRuleHeader(CSSRuleSourceData::HOST_RULE);
- }
- ;
-
-host:
- before_host_rule HOST_SYM at_rule_header_end_maybe_space
- '{' at_rule_body_start maybe_space block_rule_body closing_brace {
- $$ = parser->createHostRule($7);
- }
- | before_host_rule HOST_SYM at_rule_recovery {
- $$ = 0;
- parser->endRuleBody(true);
- }
- ;
-
-before_viewport_rule:
- /* empty */ {
- parser->markViewportRuleBodyStart();
- parser->startRuleHeader(CSSRuleSourceData::VIEWPORT_RULE);
- }
- ;
-
-viewport:
- before_viewport_rule VIEWPORT_RULE_SYM at_rule_header_end_maybe_space
- '{' at_rule_body_start maybe_space_before_declaration declaration_list closing_brace {
- $$ = parser->createViewportRule();
- parser->markViewportRuleBodyEnd();
- }
- | before_viewport_rule VIEWPORT_RULE_SYM at_rule_recovery {
- $$ = 0;
- parser->endRuleBody(true);
- parser->markViewportRuleBodyEnd();
- }
-;
-
-region_selector:
- selector_list {
- parser->setReusableRegionSelectorVector($1);
- $$ = parser->reusableRegionSelectorVector();
- }
-;
-
-before_region_rule:
- /* empty */ {
- parser->startRuleHeader(CSSRuleSourceData::REGION_RULE);
- }
- ;
-
-region:
- before_region_rule WEBKIT_REGION_RULE_SYM WHITESPACE region_selector at_rule_header_end '{' at_rule_body_start maybe_space region_block_rule_body closing_brace {
- $$ = parser->createRegionRule($4, $9);
- }
- | before_region_rule WEBKIT_REGION_RULE_SYM at_rule_recovery {
- $$ = 0;
- parser->endRuleBody(true);
- }
-;
-
-before_filter_rule:
- /* empty */ {
- parser->startRuleHeader(CSSRuleSourceData::FILTER_RULE);
- parser->m_inFilterRule = true;
- }
- ;
-
-filter:
- before_filter_rule WEBKIT_FILTER_RULE_SYM WHITESPACE IDENT at_rule_header_end_maybe_space
- '{' at_rule_body_start maybe_space_before_declaration declaration_list closing_brace {
- parser->m_inFilterRule = false;
- $$ = parser->createFilterRule($4);
- }
- | before_filter_rule WEBKIT_FILTER_RULE_SYM at_rule_recovery {
- $$ = 0;
- }
- ;
-
-combinator:
- '+' maybe_space { $$ = CSSSelector::DirectAdjacent; }
- | '~' maybe_space { $$ = CSSSelector::IndirectAdjacent; }
- | '>' maybe_space { $$ = CSSSelector::Child; }
- ;
-
-maybe_unary_operator:
- unary_operator
- | /* empty */ { $$ = 1; }
- ;
-
-unary_operator:
- '-' { $$ = -1; }
- | '+' { $$ = 1; }
- ;
-
-maybe_space_before_declaration:
- maybe_space {
- parser->startProperty();
- }
- ;
-
-before_selector_list:
- /* empty */ {
- parser->startRuleHeader(CSSRuleSourceData::STYLE_RULE);
- parser->startSelector();
- }
- ;
-
-at_rule_header_end:
- /* empty */ {
- parser->endRuleHeader();
- }
- ;
-
-at_selector_end:
- /* empty */ {
- parser->endSelector();
- }
- ;
-
-ruleset:
- before_selector_list selector_list at_selector_end at_rule_header_end '{' at_rule_body_start maybe_space_before_declaration declaration_list closing_brace {
- $$ = parser->createStyleRule($2);
- }
- ;
-
-before_selector_group_item:
- /* empty */ {
- parser->startSelector();
- }
-
-selector_list:
- selector %prec UNIMPORTANT_TOK {
- $$ = parser->reusableSelectorVector();
- $$->shrink(0);
- $$->append(parser->sinkFloatingSelector($1));
- }
- | selector_list at_selector_end ',' maybe_space before_selector_group_item selector %prec UNIMPORTANT_TOK {
- $$ = $1;
- $$->append(parser->sinkFloatingSelector($6));
- }
- ;
-
-relative_selector:
- combinator selector {
- $$ = $2;
- CSSParserSelector* end = $$;
- while (end->tagHistory())
- end = end->tagHistory();
- end->setRelation($1);
- }
- | selector
- ;
-
-selector:
- simple_selector
- | selector WHITESPACE
- | selector WHITESPACE simple_selector
- {
- $$ = $3;
- CSSParserSelector* end = $$;
- while (end->tagHistory())
- end = end->tagHistory();
- end->setRelation(CSSSelector::Descendant);
- if ($1->isContentPseudoElement())
- end->setRelationIsAffectedByPseudoContent();
- end->setTagHistory(parser->sinkFloatingSelector($1));
- }
- | selector combinator simple_selector {
- $$ = $3;
- CSSParserSelector* end = $$;
- while (end->tagHistory())
- end = end->tagHistory();
- end->setRelation($2);
- if ($1->isContentPseudoElement())
- end->setRelationIsAffectedByPseudoContent();
- end->setTagHistory(parser->sinkFloatingSelector($1));
- }
- ;
-
-namespace_selector:
- /* empty */ '|' { $$.clear(); }
- | '*' '|' { static LChar star = '*'; $$.init(&star, 1); }
- | IDENT '|'
- ;
-
-simple_selector:
- element_name {
- $$ = parser->createFloatingSelectorWithTagName(QualifiedName(nullAtom, $1, parser->m_defaultNamespace));
- }
- | element_name specifier_list {
- $$ = parser->rewriteSpecifiersWithElementName(nullAtom, $1, $2);
- if (!$$)
- YYERROR;
- }
- | specifier_list {
- $$ = parser->rewriteSpecifiersWithNamespaceIfNeeded($1);
- if (!$$)
- YYERROR;
- }
- | namespace_selector element_name {
- $$ = parser->createFloatingSelectorWithTagName(parser->determineNameInNamespace($1, $2));
- if (!$$)
- YYERROR;
- }
- | namespace_selector element_name specifier_list {
- $$ = parser->rewriteSpecifiersWithElementName($1, $2, $3);
- if (!$$)
- YYERROR;
- }
- | namespace_selector specifier_list {
- $$ = parser->rewriteSpecifiersWithElementName($1, starAtom, $2);
- if (!$$)
- YYERROR;
- }
- ;
-
-simple_selector_list:
- simple_selector %prec UNIMPORTANT_TOK {
- $$ = parser->createFloatingSelectorVector();
- $$->append(parser->sinkFloatingSelector($1));
- }
- | simple_selector_list maybe_space ',' maybe_space simple_selector %prec UNIMPORTANT_TOK {
- $$ = $1;
- $$->append(parser->sinkFloatingSelector($5));
- }
- ;
-
-element_name:
- IDENT {
- if (parser->m_context.isHTMLDocument)
- parser->tokenToLowerCase($1);
- $$ = $1;
- }
- | '*' {
- static LChar star = '*';
- $$.init(&star, 1);
- }
- ;
-
-specifier_list:
- specifier
- | specifier_list specifier {
- $$ = parser->rewriteSpecifiers($1, $2);
- }
-;
-
-specifier:
- IDSEL {
- $$ = parser->createFloatingSelector();
- $$->setMatch(CSSSelector::Id);
- if (parser->m_context.mode == CSSQuirksMode)
- parser->tokenToLowerCase($1);
- $$->setValue($1);
- }
- | HEX {
- if ($1[0] >= '0' && $1[0] <= '9') {
- YYERROR;
- } else {
- $$ = parser->createFloatingSelector();
- $$->setMatch(CSSSelector::Id);
- if (parser->m_context.mode == CSSQuirksMode)
- parser->tokenToLowerCase($1);
- $$->setValue($1);
- }
- }
- | class
- | attrib
- | pseudo
- ;
-
-class:
- '.' IDENT {
- $$ = parser->createFloatingSelector();
- $$->setMatch(CSSSelector::Class);
- if (parser->m_context.mode == CSSQuirksMode)
- parser->tokenToLowerCase($2);
- $$->setValue($2);
- }
- ;
-
-attr_name:
- IDENT maybe_space {
- if (parser->m_context.isHTMLDocument)
- parser->tokenToLowerCase($1);
- $$ = $1;
- }
- ;
-
-attrib:
- '[' maybe_space attr_name closing_square_bracket {
- $$ = parser->createFloatingSelector();
- $$->setAttribute(QualifiedName(nullAtom, $3, nullAtom));
- $$->setMatch(CSSSelector::Set);
- }
- | '[' maybe_space attr_name match maybe_space ident_or_string maybe_space closing_square_bracket {
- $$ = parser->createFloatingSelector();
- $$->setAttribute(QualifiedName(nullAtom, $3, nullAtom));
- $$->setMatch((CSSSelector::Match)$4);
- $$->setValue($6);
- }
- | '[' maybe_space namespace_selector attr_name closing_square_bracket {
- $$ = parser->createFloatingSelector();
- $$->setAttribute(parser->determineNameInNamespace($3, $4));
- $$->setMatch(CSSSelector::Set);
- }
- | '[' maybe_space namespace_selector attr_name match maybe_space ident_or_string maybe_space closing_square_bracket {
- $$ = parser->createFloatingSelector();
- $$->setAttribute(parser->determineNameInNamespace($3, $4));
- $$->setMatch((CSSSelector::Match)$5);
- $$->setValue($7);
- }
- | '[' selector_recovery closing_square_bracket {
- YYERROR;
- }
- ;
-
-match:
- '=' {
- $$ = CSSSelector::Exact;
- }
- | INCLUDES {
- $$ = CSSSelector::List;
- }
- | DASHMATCH {
- $$ = CSSSelector::Hyphen;
- }
- | BEGINSWITH {
- $$ = CSSSelector::Begin;
- }
- | ENDSWITH {
- $$ = CSSSelector::End;
- }
- | CONTAINS {
- $$ = CSSSelector::Contain;
- }
- ;
-
-ident_or_string:
- IDENT
- | STRING
- ;
-
-pseudo_page:
- ':' IDENT {
- if ($2.isFunction())
- YYERROR;
- $$ = parser->createFloatingSelector();
- $$->setMatch(CSSSelector::PagePseudoClass);
- parser->tokenToLowerCase($2);
- $$->setValue($2);
- CSSSelector::PseudoType type = $$->pseudoType();
- if (type == CSSSelector::PseudoUnknown)
- YYERROR;
- }
-
-pseudo:
- ':' error_location IDENT {
- if ($3.isFunction())
- YYERROR;
- $$ = parser->createFloatingSelector();
- $$->setMatch(CSSSelector::PseudoClass);
- parser->tokenToLowerCase($3);
- $$->setValue($3);
- CSSSelector::PseudoType type = $$->pseudoType();
- if (type == CSSSelector::PseudoUnknown) {
- parser->reportError($2, CSSParser::InvalidSelectorPseudoError);
- YYERROR;
- }
- }
- | ':' ':' error_location IDENT {
- if ($4.isFunction())
- YYERROR;
- $$ = parser->createFloatingSelector();
- $$->setMatch(CSSSelector::PseudoElement);
- parser->tokenToLowerCase($4);
- $$->setValue($4);
- // FIXME: This call is needed to force selector to compute the pseudoType early enough.
- CSSSelector::PseudoType type = $$->pseudoType();
- if (type == CSSSelector::PseudoUnknown) {
- parser->reportError($3, CSSParser::InvalidSelectorPseudoError);
- YYERROR;
- }
- }
- // used by ::cue(:past/:future)
- | ':' ':' CUEFUNCTION maybe_space simple_selector_list maybe_space closing_parenthesis {
- $$ = parser->createFloatingSelector();
- $$->setMatch(CSSSelector::PseudoElement);
- $$->adoptSelectorVector(*parser->sinkFloatingSelectorVector($5));
- $$->setValue($3);
- CSSSelector::PseudoType type = $$->pseudoType();
- if (type != CSSSelector::PseudoCue)
- YYERROR;
- }
- | ':' ':' CUEFUNCTION selector_recovery closing_parenthesis {
- YYERROR;
- }
- | ':' ':' DISTRIBUTEDFUNCTION maybe_space relative_selector closing_parenthesis {
- $$ = parser->createFloatingSelector();
- $$->setMatch(CSSSelector::PseudoElement);
- $$->setFunctionArgumentSelector($5);
- parser->tokenToLowerCase($3);
- $$->setValue($3);
- }
- | ':' ':' DISTRIBUTEDFUNCTION selector_recovery closing_parenthesis {
- YYERROR;
- }
- // use by :-webkit-any.
- // FIXME: should we support generic selectors here or just simple_selectors?
- // Use simple_selector_list for now to match -moz-any.
- // See http://lists.w3.org/Archives/Public/www-style/2010Sep/0566.html for some
- // related discussion with respect to :not.
- | ':' ANYFUNCTION maybe_space simple_selector_list maybe_space closing_parenthesis {
- $$ = parser->createFloatingSelector();
- $$->setMatch(CSSSelector::PseudoClass);
- $$->adoptSelectorVector(*parser->sinkFloatingSelectorVector($4));
- parser->tokenToLowerCase($2);
- $$->setValue($2);
- CSSSelector::PseudoType type = $$->pseudoType();
- if (type != CSSSelector::PseudoAny)
- YYERROR;
- }
- | ':' ANYFUNCTION selector_recovery closing_parenthesis {
- YYERROR;
- }
- // used by :nth-*(ax+b)
- | ':' FUNCTION maybe_space NTH maybe_space closing_parenthesis {
- $$ = parser->createFloatingSelector();
- $$->setMatch(CSSSelector::PseudoClass);
- $$->setArgument($4);
- $$->setValue($2);
- CSSSelector::PseudoType type = $$->pseudoType();
- if (type == CSSSelector::PseudoUnknown)
- YYERROR;
- }
- // used by :nth-*
- | ':' FUNCTION maybe_space maybe_unary_operator INTEGER maybe_space closing_parenthesis {
- $$ = parser->createFloatingSelector();
- $$->setMatch(CSSSelector::PseudoClass);
- $$->setArgument(String::number($4 * $5));
- $$->setValue($2);
- CSSSelector::PseudoType type = $$->pseudoType();
- if (type == CSSSelector::PseudoUnknown)
- YYERROR;
- }
- // used by :nth-*(odd/even) and :lang
- | ':' FUNCTION maybe_space IDENT maybe_space closing_parenthesis {
- $$ = parser->createFloatingSelector();
- $$->setMatch(CSSSelector::PseudoClass);
- $$->setArgument($4);
- parser->tokenToLowerCase($2);
- $$->setValue($2);
- CSSSelector::PseudoType type = $$->pseudoType();
- if (type == CSSSelector::PseudoUnknown)
- YYERROR;
- else if (type == CSSSelector::PseudoNthChild ||
- type == CSSSelector::PseudoNthOfType ||
- type == CSSSelector::PseudoNthLastChild ||
- type == CSSSelector::PseudoNthLastOfType) {
- if (!isValidNthToken($4))
- YYERROR;
- }
- }
- | ':' FUNCTION selector_recovery closing_parenthesis {
- YYERROR;
- }
- // used by :not
- | ':' NOTFUNCTION maybe_space simple_selector maybe_space closing_parenthesis {
- if (!$4->isSimple())
- YYERROR;
- else {
- $$ = parser->createFloatingSelector();
- $$->setMatch(CSSSelector::PseudoClass);
-
- Vector<OwnPtr<CSSParserSelector> > selectorVector;
- selectorVector.append(parser->sinkFloatingSelector($4));
- $$->adoptSelectorVector(selectorVector);
-
- parser->tokenToLowerCase($2);
- $$->setValue($2);
- }
- }
- | ':' NOTFUNCTION selector_recovery closing_parenthesis {
- YYERROR;
- }
- | ':' ':' PARTFUNCTION maybe_space IDENT maybe_space closing_parenthesis {
- $$ = parser->createFloatingSelector();
- $$->setMatch(CSSSelector::PseudoElement);
- $$->setArgument($5);
- if ($5.startsWithIgnoringCase("-webkit"))
- $$->setMatchUserAgentOnly();
- parser->tokenToLowerCase($3);
- $$->setValue($3);
- CSSSelector::PseudoType type = $$->pseudoType();
- if (type != CSSSelector::PseudoPart)
- YYERROR;
- }
- | ':' ':' PARTFUNCTION selector_recovery closing_parenthesis {
- YYERROR;
- }
- | ':' HOSTFUNCTION maybe_space simple_selector_list maybe_space closing_parenthesis {
- $$ = parser->createFloatingSelector();
- $$->setMatch(CSSSelector::PseudoClass);
- $$->adoptSelectorVector(*parser->sinkFloatingSelectorVector($4));
- parser->tokenToLowerCase($2);
- $$->setValue($2);
- CSSSelector::PseudoType type = $$->pseudoType();
- if (type != CSSSelector::PseudoHost)
- YYERROR;
- }
- // used by :host()
- | ':' HOSTFUNCTION maybe_space closing_parenthesis {
- $$ = parser->createFloatingSelector();
- $$->setMatch(CSSSelector::PseudoClass);
- parser->tokenToLowerCase($2);
- $$->setValue($2.atomicSubstring(0, $2.length() - 1));
- CSSSelector::PseudoType type = $$->pseudoType();
- if (type != CSSSelector::PseudoHost)
- YYERROR;
- }
- | ':' HOSTFUNCTION selector_recovery closing_parenthesis {
- YYERROR;
- }
- ;
-
-selector_recovery:
- error error_location error_recovery;
-
-declaration_list:
- /* empty */ { $$ = false; }
- | declaration
- | decl_list declaration {
- $$ = $1 || $2;
- }
- | decl_list
- ;
-
-decl_list:
- declaration ';' maybe_space {
- parser->startProperty();
- $$ = $1;
- }
- | decl_list declaration ';' maybe_space {
- parser->startProperty();
- $$ = $1 || $2;
- }
- ;
-
-declaration:
- VAR_DEFINITION maybe_space ':' maybe_space expr prio {
- parser->storeVariableDeclaration($1, parser->sinkFloatingValueList($5), $6);
- $$ = true;
- parser->endProperty($6, true);
- }
- |
- property ':' maybe_space error_location expr prio {
- $$ = false;
- bool isPropertyParsed = false;
- if ($1 != CSSPropertyInvalid) {
- parser->m_valueList = parser->sinkFloatingValueList($5);
- int oldParsedProperties = parser->m_parsedProperties.size();
- $$ = parser->parseValue($1, $6);
- if (!$$) {
- parser->rollbackLastProperties(parser->m_parsedProperties.size() - oldParsedProperties);
- parser->reportError($4, CSSParser::InvalidPropertyValueError);
- } else
- isPropertyParsed = true;
- parser->m_valueList = nullptr;
- }
- parser->endProperty($6, isPropertyParsed);
- }
- |
- property ':' maybe_space error_location expr prio error error_recovery {
- /* When we encounter something like p {color: red !important fail;} we should drop the declaration */
- parser->reportError($4, CSSParser::InvalidPropertyValueError);
- parser->endProperty(false, false);
- $$ = false;
- }
- |
- property ':' maybe_space error_location error error_recovery {
- parser->reportError($4, CSSParser::InvalidPropertyValueError);
- parser->endProperty(false, false);
- $$ = false;
- }
- |
- property error error_location error_recovery {
- parser->reportError($3, CSSParser::PropertyDeclarationError);
- parser->endProperty(false, false, CSSParser::GeneralError);
- $$ = false;
- }
- |
- error error_location error_recovery {
- parser->reportError($2, CSSParser::PropertyDeclarationError);
- $$ = false;
- }
- ;
-
-property:
- error_location IDENT maybe_space {
- $$ = cssPropertyID($2);
- parser->setCurrentProperty($$);
- if ($$ == CSSPropertyInvalid)
- parser->reportError($1, CSSParser::InvalidPropertyError);
- }
- ;
-
-prio:
- IMPORTANT_SYM maybe_space { $$ = true; }
- | /* empty */ { $$ = false; }
- ;
-
-expr:
- term {
- $$ = parser->createFloatingValueList();
- $$->addValue(parser->sinkFloatingValue($1));
- }
- | expr operator term {
- $$ = $1;
- $$->addValue(makeOperatorValue($2));
- $$->addValue(parser->sinkFloatingValue($3));
- }
- | expr term {
- $$ = $1;
- $$->addValue(parser->sinkFloatingValue($2));
- }
- ;
-
-expr_recovery:
- error error_location error_recovery {
- parser->reportError($2, CSSParser::PropertyDeclarationError);
- }
- ;
-
-operator:
- '/' maybe_space {
- $$ = '/';
- }
- | ',' maybe_space {
- $$ = ',';
- }
- ;
-
-term:
- unary_term maybe_space
- | unary_operator unary_term maybe_space { $$ = $2; $$.fValue *= $1; }
- | STRING maybe_space { $$.id = CSSValueInvalid; $$.string = $1; $$.unit = CSSPrimitiveValue::CSS_STRING; }
- | IDENT maybe_space {
- $$.id = cssValueKeywordID($1);
- $$.unit = CSSPrimitiveValue::CSS_IDENT;
- $$.string = $1;
- }
- /* We might need to actually parse the number from a dimension, but we can't just put something that uses $$.string into unary_term. */
- | DIMEN maybe_space { $$.id = CSSValueInvalid; $$.string = $1; $$.unit = CSSPrimitiveValue::CSS_DIMENSION; }
- | unary_operator DIMEN maybe_space { $$.id = CSSValueInvalid; $$.string = $2; $$.unit = CSSPrimitiveValue::CSS_DIMENSION; }
- | URI maybe_space { $$.id = CSSValueInvalid; $$.string = $1; $$.unit = CSSPrimitiveValue::CSS_URI; }
- | UNICODERANGE maybe_space { $$.id = CSSValueInvalid; $$.string = $1; $$.unit = CSSPrimitiveValue::CSS_UNICODE_RANGE; }
- | HEX maybe_space { $$.id = CSSValueInvalid; $$.string = $1; $$.unit = CSSPrimitiveValue::CSS_PARSER_HEXCOLOR; }
- | '#' maybe_space { $$.id = CSSValueInvalid; $$.string = CSSParserString(); $$.unit = CSSPrimitiveValue::CSS_PARSER_HEXCOLOR; } /* Handle error case: "color: #;" */
- | VARFUNCTION maybe_space IDENT closing_parenthesis maybe_space {
- $$.id = CSSValueInvalid;
- $$.string = $3;
- $$.unit = CSSPrimitiveValue::CSS_VARIABLE_NAME;
- }
- | VARFUNCTION maybe_space expr_recovery closing_parenthesis {
- YYERROR;
- }
- /* FIXME: according to the specs a function can have a unary_operator in front. I know no case where this makes sense */
- | function maybe_space
- | calc_function maybe_space
- | min_or_max_function maybe_space
- | '%' maybe_space { /* Handle width: %; */
- $$.id = CSSValueInvalid; $$.unit = 0;
- }
- ;
-
-unary_term:
- INTEGER { $$.setFromNumber($1); $$.isInt = true; }
- | FLOATTOKEN { $$.setFromNumber($1); }
- | PERCENTAGE { $$.setFromNumber($1, CSSPrimitiveValue::CSS_PERCENTAGE); }
- | PXS { $$.setFromNumber($1, CSSPrimitiveValue::CSS_PX); }
- | CMS { $$.setFromNumber($1, CSSPrimitiveValue::CSS_CM); }
- | MMS { $$.setFromNumber($1, CSSPrimitiveValue::CSS_MM); }
- | INS { $$.setFromNumber($1, CSSPrimitiveValue::CSS_IN); }
- | PTS { $$.setFromNumber($1, CSSPrimitiveValue::CSS_PT); }
- | PCS { $$.setFromNumber($1, CSSPrimitiveValue::CSS_PC); }
- | DEGS { $$.setFromNumber($1, CSSPrimitiveValue::CSS_DEG); }
- | RADS { $$.setFromNumber($1, CSSPrimitiveValue::CSS_RAD); }
- | GRADS { $$.setFromNumber($1, CSSPrimitiveValue::CSS_GRAD); }
- | TURNS { $$.setFromNumber($1, CSSPrimitiveValue::CSS_TURN); }
- | MSECS { $$.setFromNumber($1, CSSPrimitiveValue::CSS_MS); }
- | SECS { $$.setFromNumber($1, CSSPrimitiveValue::CSS_S); }
- | HERTZ { $$.setFromNumber($1, CSSPrimitiveValue::CSS_HZ); }
- | KHERTZ { $$.setFromNumber($1, CSSPrimitiveValue::CSS_KHZ); }
- | EMS { $$.setFromNumber($1, CSSPrimitiveValue::CSS_EMS); }
- | QEMS { $$.setFromNumber($1, CSSParserValue::Q_EMS); }
- | EXS { $$.setFromNumber($1, CSSPrimitiveValue::CSS_EXS); }
- | REMS {
- $$.setFromNumber($1, CSSPrimitiveValue::CSS_REMS);
- if (parser->m_styleSheet)
- parser->m_styleSheet->parserSetUsesRemUnits(true);
- }
- | CHS { $$.setFromNumber($1, CSSPrimitiveValue::CSS_CHS); }
- | VW { $$.setFromNumber($1, CSSPrimitiveValue::CSS_VW); }
- | VH { $$.setFromNumber($1, CSSPrimitiveValue::CSS_VH); }
- | VMIN { $$.setFromNumber($1, CSSPrimitiveValue::CSS_VMIN); }
- | VMAX { $$.setFromNumber($1, CSSPrimitiveValue::CSS_VMAX); }
- | DPPX { $$.setFromNumber($1, CSSPrimitiveValue::CSS_DPPX); }
- | DPI { $$.setFromNumber($1, CSSPrimitiveValue::CSS_DPI); }
- | DPCM { $$.setFromNumber($1, CSSPrimitiveValue::CSS_DPCM); }
- | FR { $$.setFromNumber($1, CSSPrimitiveValue::CSS_FR); }
- ;
-
-function:
- FUNCTION maybe_space expr closing_parenthesis {
- $$.setFromFunction(parser->createFloatingFunction($1, parser->sinkFloatingValueList($3)));
- } |
- FUNCTION maybe_space closing_parenthesis {
- $$.setFromFunction(parser->createFloatingFunction($1, parser->sinkFloatingValueList(parser->createFloatingValueList())));
- } |
- FUNCTION maybe_space expr_recovery closing_parenthesis {
- YYERROR;
- }
- ;
-
-calc_func_term:
- unary_term
- | VARFUNCTION maybe_space IDENT closing_parenthesis {
- $$.id = CSSValueInvalid;
- $$.string = $3;
- $$.unit = CSSPrimitiveValue::CSS_VARIABLE_NAME;
- }
- | unary_operator unary_term { $$ = $2; $$.fValue *= $1; }
- ;
-
-calc_func_operator:
- WHITESPACE '+' WHITESPACE {
- $$ = '+';
- }
- | WHITESPACE '-' WHITESPACE {
- $$ = '-';
- }
- | calc_maybe_space '*' maybe_space {
- $$ = '*';
- }
- | calc_maybe_space '/' maybe_space {
- $$ = '/';
- }
- ;
-
-calc_maybe_space:
- /* empty */
- | WHITESPACE
- ;
-
-calc_func_paren_expr:
- '(' maybe_space calc_func_expr calc_maybe_space closing_parenthesis {
- $$ = $3;
- $$->insertValueAt(0, makeOperatorValue('('));
- $$->addValue(makeOperatorValue(')'));
- }
- | '(' maybe_space expr_recovery closing_parenthesis {
- YYERROR;
- }
- ;
-
-calc_func_expr:
- calc_func_term {
- $$ = parser->createFloatingValueList();
- $$->addValue(parser->sinkFloatingValue($1));
- }
- | calc_func_expr calc_func_operator calc_func_term {
- $$ = $1;
- $$->addValue(makeOperatorValue($2));
- $$->addValue(parser->sinkFloatingValue($3));
- }
- | calc_func_expr calc_func_operator calc_func_paren_expr {
- $$ = $1;
- $$->addValue(makeOperatorValue($2));
- $$->extend(*($3));
- }
- | calc_func_paren_expr
- ;
-
-calc_func_expr_list:
- calc_func_expr calc_maybe_space
- | calc_func_expr_list ',' maybe_space calc_func_expr calc_maybe_space {
- $$ = $1;
- $$->addValue(makeOperatorValue(','));
- $$->extend(*($4));
- }
- ;
-
-calc_function:
- CALCFUNCTION maybe_space calc_func_expr calc_maybe_space closing_parenthesis {
- $$.setFromFunction(parser->createFloatingFunction($1, parser->sinkFloatingValueList($3)));
- }
- | CALCFUNCTION maybe_space expr_recovery closing_parenthesis {
- YYERROR;
- }
- ;
-
-
-min_or_max:
- MINFUNCTION
- | MAXFUNCTION
- ;
-
-min_or_max_function:
- min_or_max maybe_space calc_func_expr_list closing_parenthesis {
- $$.setFromFunction(parser->createFloatingFunction($1, parser->sinkFloatingValueList($3)));
- }
- | min_or_max maybe_space expr_recovery closing_parenthesis {
- YYERROR;
- }
- ;
-
-invalid_at:
- ATKEYWORD
- | margin_sym
- ;
-
-at_rule_recovery:
- at_rule_header_recovery at_invalid_rule_header_end at_rule_end
- ;
-
-at_rule_header_recovery:
- error error_location rule_error_recovery {
- parser->reportError($2, CSSParser::InvalidRuleError);
- }
- ;
-
-at_rule_end:
- at_invalid_rule_header_end semi_or_eof
- | at_invalid_rule_header_end invalid_block
- ;
-
-invalid_rule:
- error error_location rule_error_recovery at_invalid_rule_header_end invalid_block {
- parser->reportError($2, CSSParser::InvalidRuleError);
- $$ = 0;
- }
- | error_location invalid_at rule_error_recovery at_invalid_rule_header_end at_rule_end {
- parser->resumeErrorLogging();
- parser->reportError($1, CSSParser::InvalidRuleError);
- $$ = 0;
- }
- ;
-
-at_invalid_rule_header_end:
- /* empty */ {
- parser->endInvalidRuleHeader();
- }
- ;
-
-invalid_block:
- '{' error_recovery closing_brace {
- parser->invalidBlockHit();
- }
- ;
-
-invalid_square_brackets_block:
- '[' error_recovery closing_square_bracket
- ;
-
-invalid_parentheses_block:
- opening_parenthesis error_recovery closing_parenthesis;
-
-opening_parenthesis:
- '(' | FUNCTION | CALCFUNCTION | VARFUNCTION | MINFUNCTION | MAXFUNCTION | ANYFUNCTION | NOTFUNCTION | CUEFUNCTION | DISTRIBUTEDFUNCTION | HOSTFUNCTION
- ;
-
-error_location: {
- $$ = parser->currentLocation();
- }
- ;
-
-location_label: {
- parser->setLocationLabel(parser->currentLocation());
- }
- ;
-
-error_recovery:
- /* empty */
- | error_recovery error
- | error_recovery invalid_block
- | error_recovery invalid_square_brackets_block
- | error_recovery invalid_parentheses_block
- ;
-
-rule_error_recovery:
- /* empty */
- | rule_error_recovery error
- | rule_error_recovery invalid_square_brackets_block
- | rule_error_recovery invalid_parentheses_block
- ;
-
-%%
-
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSGrammar.y.includes b/chromium/third_party/WebKit/Source/core/css/CSSGrammar.y.includes
deleted file mode 100644
index 708e08b3c1d..00000000000
--- a/chromium/third_party/WebKit/Source/core/css/CSSGrammar.y.includes
+++ /dev/null
@@ -1,60 +0,0 @@
-%{
-
-/*
- * Copyright (C) 2002-2003 Lars Knoll (knoll@kde.org)
- * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010 Apple Inc. All rights reserved.
- * Copyright (C) 2006 Alexey Proskuryakov (ap@nypop.com)
- * Copyright (C) 2008 Eric Seidel <eric@webkit.org>
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- *
- */
-
-#include "config.h"
-
-#include "CSSPropertyNames.h"
-#include "HTMLNames.h"
-#include "core/css/CSSKeyframeRule.h"
-#include "core/css/CSSKeyframesRule.h"
-#include "core/css/CSSParser.h"
-#include "core/css/CSSParserMode.h"
-#include "core/css/CSSPrimitiveValue.h"
-#include "core/css/CSSSelector.h"
-#include "core/css/CSSSelectorList.h"
-#include "core/css/MediaList.h"
-#include "core/css/MediaQueryExp.h"
-#include "core/css/StyleRule.h"
-#include "core/css/StyleSheetContents.h"
-#include "core/dom/Document.h"
-#include "wtf/FastMalloc.h"
-#include <stdlib.h>
-#include <string.h>
-
-using namespace WebCore;
-using namespace HTMLNames;
-
-#define YYMALLOC fastMalloc
-#define YYFREE fastFree
-
-#define YYENABLE_NLS 0
-#define YYLTYPE_IS_TRIVIAL 1
-#define YYMAXDEPTH 10000
-#define YYDEBUG 0
-
-#if YYDEBUG > 0
-#define YYPRINT(File,Type,Value) if (isCSSTokenAString(Type)) YYFPRINTF(File, "%s", String((Value).string).utf8().data())
-#endif
-
-%}
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSGridLineNamesValue.cpp b/chromium/third_party/WebKit/Source/core/css/CSSGridLineNamesValue.cpp
new file mode 100644
index 00000000000..3a2877d9ae9
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/css/CSSGridLineNamesValue.cpp
@@ -0,0 +1,52 @@
+/*
+ * Copyright (C) 2013 Igalia, S.L. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/css/CSSGridLineNamesValue.h"
+
+namespace WebCore {
+
+String CSSGridLineNamesValue::customCSSText() const
+{
+ return "(" + CSSValueList::customCSSText() + ")";
+}
+
+CSSGridLineNamesValue::CSSGridLineNamesValue()
+ : CSSValueList(GridLineNamesClass, SpaceSeparator)
+{
+}
+
+PassRefPtr<CSSGridLineNamesValue> CSSGridLineNamesValue::cloneForCSSOM() const
+{
+ return adoptRef(new CSSGridLineNamesValue(*this));
+}
+
+}
+
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSGridLineNamesValue.h b/chromium/third_party/WebKit/Source/core/css/CSSGridLineNamesValue.h
new file mode 100644
index 00000000000..da97e059579
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/css/CSSGridLineNamesValue.h
@@ -0,0 +1,58 @@
+/*
+ * Copyright (C) 2013 Igalia, S.L. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef CSSGridLineNamesValue_h
+#define CSSGridLineNamesValue_h
+
+#include "core/css/CSSValueList.h"
+#include "wtf/PassRefPtr.h"
+
+namespace WebCore {
+
+class CSSGridLineNamesValue : public CSSValueList {
+public:
+ static PassRefPtr<CSSGridLineNamesValue> create()
+ {
+ return adoptRef(new CSSGridLineNamesValue());
+ }
+
+ String customCSSText() const;
+
+ PassRefPtr<CSSGridLineNamesValue> cloneForCSSOM() const;
+
+private:
+ CSSGridLineNamesValue();
+};
+
+DEFINE_CSS_VALUE_TYPE_CASTS(CSSGridLineNamesValue, isGridLineNamesValue());
+}
+
+
+#endif
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSGridTemplateValue.cpp b/chromium/third_party/WebKit/Source/core/css/CSSGridTemplateValue.cpp
index b54805c722e..d1ad1d8d056 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSGridTemplateValue.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/CSSGridTemplateValue.cpp
@@ -31,7 +31,6 @@
#include "config.h"
#include "core/css/CSSGridTemplateValue.h"
-#include "core/rendering/style/GridCoordinate.h"
#include "wtf/text/StringBuilder.h"
namespace WebCore {
@@ -67,7 +66,7 @@ static String stringForPosition(const NamedGridAreaMap& gridAreaMap, size_t row,
return ".";
}
-String CSSGridTemplateValue::customCssText() const
+String CSSGridTemplateValue::customCSSText() const
{
StringBuilder builder;
for (size_t row = 0; row < m_rowCount; ++row) {
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSGridTemplateValue.h b/chromium/third_party/WebKit/Source/core/css/CSSGridTemplateValue.h
index f2b796a283f..faa988053f6 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSGridTemplateValue.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSGridTemplateValue.h
@@ -42,7 +42,7 @@ public:
static PassRefPtr<CSSGridTemplateValue> create(const NamedGridAreaMap& gridAreaMap, size_t rowCount, size_t columnCount) { return adoptRef(new CSSGridTemplateValue(gridAreaMap, rowCount, columnCount)); }
~CSSGridTemplateValue() { }
- String customCssText() const;
+ String customCSSText() const;
const NamedGridAreaMap& gridAreaMap() const { return m_gridAreaMap; }
size_t rowCount() const { return m_rowCount; }
@@ -56,20 +56,7 @@ private:
size_t m_columnCount;
};
-inline CSSGridTemplateValue* toCSSGridTemplateValue(CSSValue* value)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(value->isGridTemplateValue());
- return static_cast<CSSGridTemplateValue*>(value);
-}
-
-inline const CSSGridTemplateValue* toCSSGridTemplateValue(const CSSValue* value)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(value->isGridTemplateValue());
- return static_cast<const CSSGridTemplateValue*>(value);
-}
-
-// Catch unneeded cast.
-void toCSSGridTemplateValue(const CSSGridTemplateValue*);
+DEFINE_CSS_VALUE_TYPE_CASTS(CSSGridTemplateValue, isGridTemplateValue());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSGroupingRule.cpp b/chromium/third_party/WebKit/Source/core/css/CSSGroupingRule.cpp
index b6728c04791..0c0bf2a9d20 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSGroupingRule.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/CSSGroupingRule.cpp
@@ -31,12 +31,10 @@
#include "config.h"
#include "core/css/CSSGroupingRule.h"
-#include "bindings/v8/ExceptionMessages.h"
#include "bindings/v8/ExceptionState.h"
#include "core/css/CSSParser.h"
#include "core/css/CSSRuleList.h"
#include "core/css/CSSStyleSheet.h"
-#include "core/css/StyleRule.h"
#include "core/dom/ExceptionCode.h"
#include "wtf/text/StringBuilder.h"
@@ -58,12 +56,12 @@ CSSGroupingRule::~CSSGroupingRule()
}
}
-unsigned CSSGroupingRule::insertRule(const String& ruleString, unsigned index, ExceptionState& es)
+unsigned CSSGroupingRule::insertRule(const String& ruleString, unsigned index, ExceptionState& exceptionState)
{
ASSERT(m_childRuleCSSOMWrappers.size() == m_groupRule->childRules().size());
if (index > m_groupRule->childRules().size()) {
- es.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("insertRule", "CSSGroupingRule", "the index " + String::number(index) + " must be less than or equal to the length of the rule list."));
+ exceptionState.throwDOMException(IndexSizeError, "the index " + String::number(index) + " must be less than or equal to the length of the rule list.");
return 0;
}
@@ -71,7 +69,7 @@ unsigned CSSGroupingRule::insertRule(const String& ruleString, unsigned index, E
CSSParser parser(parserContext(), UseCounter::getFrom(styleSheet));
RefPtr<StyleRuleBase> newRule = parser.parseRule(styleSheet ? styleSheet->contents() : 0, ruleString);
if (!newRule) {
- es.throwDOMException(SyntaxError, ExceptionMessages::failedToExecute("insertRule", "CSSGroupingRule", "the rule '" + ruleString + "' is invalid and cannot be parsed."));
+ exceptionState.throwDOMException(SyntaxError, "the rule '" + ruleString + "' is invalid and cannot be parsed.");
return 0;
}
@@ -79,7 +77,7 @@ unsigned CSSGroupingRule::insertRule(const String& ruleString, unsigned index, E
// FIXME: an HierarchyRequestError should also be thrown for a @charset or a nested
// @media rule. They are currently not getting parsed, resulting in a SyntaxError
// to get raised above.
- es.throwDOMException(HierarchyRequestError, ExceptionMessages::failedToExecute("insertRule", "CSSGroupingRule", "'@import' rules cannot be inserted inside a group rule."));
+ exceptionState.throwDOMException(HierarchyRequestError, "'@import' rules cannot be inserted inside a group rule.");
return 0;
}
CSSStyleSheet::RuleMutationScope mutationScope(this);
@@ -90,12 +88,12 @@ unsigned CSSGroupingRule::insertRule(const String& ruleString, unsigned index, E
return index;
}
-void CSSGroupingRule::deleteRule(unsigned index, ExceptionState& es)
+void CSSGroupingRule::deleteRule(unsigned index, ExceptionState& exceptionState)
{
ASSERT(m_childRuleCSSOMWrappers.size() == m_groupRule->childRules().size());
if (index >= m_groupRule->childRules().size()) {
- es.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("deleteRule", "CSSGroupingRule", "the index " + String::number(index) + " is greated than the length of the rule list."));
+ exceptionState.throwDOMException(IndexSizeError, "the index " + String::number(index) + " is greated than the length of the rule list.");
return;
}
@@ -108,7 +106,7 @@ void CSSGroupingRule::deleteRule(unsigned index, ExceptionState& es)
m_childRuleCSSOMWrappers.remove(index);
}
-void CSSGroupingRule::appendCssTextForItems(StringBuilder& result) const
+void CSSGroupingRule::appendCSSTextForItems(StringBuilder& result) const
{
unsigned size = length();
for (unsigned i = 0; i < size; ++i) {
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSGroupingRule.h b/chromium/third_party/WebKit/Source/core/css/CSSGroupingRule.h
index 1249f3db20b..9ba64484b95 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSGroupingRule.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSGroupingRule.h
@@ -50,7 +50,7 @@ public:
protected:
CSSGroupingRule(StyleRuleGroup* groupRule, CSSStyleSheet* parent);
- void appendCssTextForItems(StringBuilder&) const;
+ void appendCSSTextForItems(StringBuilder&) const;
RefPtr<StyleRuleGroup> m_groupRule;
mutable Vector<RefPtr<CSSRule> > m_childRuleCSSOMWrappers;
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSHelper.h b/chromium/third_party/WebKit/Source/core/css/CSSHelper.h
index ac2c792933a..6775631a6e9 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSHelper.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSHelper.h
@@ -29,7 +29,11 @@ namespace WebCore {
// We always assume 96 CSS pixels in a CSS inch. This is the cold hard truth of the Web.
// At high DPI, we may scale a CSS pixel, but the ratio of the CSS pixel to the so-called
// "absolute" CSS length units like inch and pt is always fixed and never changes.
-const float cssPixelsPerInch = 96;
+const double cssPixelsPerInch = 96;
+const double cssPixelsPerCentimeter = cssPixelsPerInch / 2.54; // 2.54 cm/in
+const double cssPixelsPerMillimeter = cssPixelsPerCentimeter / 10;
+const double cssPixelsPerPoint = cssPixelsPerInch / 72;
+const double cssPixelsPerPica = cssPixelsPerInch / 6;
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSHostRule.cpp b/chromium/third_party/WebKit/Source/core/css/CSSHostRule.cpp
deleted file mode 100644
index 983c37709ab..00000000000
--- a/chromium/third_party/WebKit/Source/core/css/CSSHostRule.cpp
+++ /dev/null
@@ -1,45 +0,0 @@
-/**
- * (C) 1999-2003 Lars Knoll (knoll@kde.org)
- * (C) 2002-2003 Dirk Mueller (mueller@kde.org)
- * Copyright (C) 2002, 2005, 2006, 2012 Apple Computer, Inc.
- * Copyright (C) 2006 Samuel Weinig (sam@webkit.org)
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-#include "core/css/CSSHostRule.h"
-
-#include "wtf/text/StringBuilder.h"
-
-namespace WebCore {
-
-CSSHostRule::CSSHostRule(StyleRuleHost* hostRule, CSSStyleSheet* parent)
- : CSSGroupingRule(hostRule, parent)
-{
-}
-
-String CSSHostRule::cssText() const
-{
- StringBuilder result;
- result.appendLiteral("@host { \n");
- appendCssTextForItems(result);
- result.append('}');
- return result.toString();
-}
-
-} // namespace WebCore
-
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSHostRule.h b/chromium/third_party/WebKit/Source/core/css/CSSHostRule.h
deleted file mode 100644
index 9dafa635609..00000000000
--- a/chromium/third_party/WebKit/Source/core/css/CSSHostRule.h
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * (C) 1999-2003 Lars Knoll (knoll@kde.org)
- * (C) 2002-2003 Dirk Mueller (mueller@kde.org)
- * Copyright (C) 2002, 2006, 2008, 2012 Apple Inc. All rights reserved.
- * Copyright (C) 2006 Samuel Weinig (sam@webkit.org)
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#ifndef CSSHostRule_h
-#define CSSHostRule_h
-
-#include "core/css/CSSGroupingRule.h"
-
-namespace WebCore {
-
-class CSSHostRule : public CSSGroupingRule {
-public:
- static PassRefPtr<CSSHostRule> create(StyleRuleHost* rule, CSSStyleSheet* sheet) { return adoptRef(new CSSHostRule(rule, sheet)); }
-
- virtual CSSRule::Type type() const OVERRIDE { return CSSRule::HOST_RULE; }
- virtual String cssText() const OVERRIDE;
-
-private:
- CSSHostRule(StyleRuleHost*, CSSStyleSheet*);
-};
-
-
-} // namespace WebCore
-
-#endif // CSSHostRule_h
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSHostRule.idl b/chromium/third_party/WebKit/Source/core/css/CSSHostRule.idl
deleted file mode 100644
index d86b7387241..00000000000
--- a/chromium/third_party/WebKit/Source/core/css/CSSHostRule.idl
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * Copyright (C) 2006, 2007 Apple Inc. All rights reserved.
- * Copyright (C) 2006 Samuel Weinig <sam.weinig@gmail.com>
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-// Introduced in Shadow DOM spec:
-interface CSSHostRule : CSSRule {
- readonly attribute CSSRuleList cssRules;
-
- [RaisesException] unsigned long insertRule(DOMString rule, unsigned long index);
- [RaisesException] void deleteRule(unsigned long index);
-};
-
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSImageGeneratorValue.cpp b/chromium/third_party/WebKit/Source/core/css/CSSImageGeneratorValue.cpp
index 472c6eecbf3..fa3f22a05e6 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSImageGeneratorValue.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/CSSImageGeneratorValue.cpp
@@ -29,7 +29,7 @@
#include "core/css/CSSCanvasValue.h"
#include "core/css/CSSCrossfadeValue.h"
#include "core/css/CSSGradientValue.h"
-#include "core/platform/graphics/Image.h"
+#include "platform/graphics/Image.h"
namespace WebCore {
@@ -63,7 +63,7 @@ void CSSImageGeneratorValue::removeClient(RenderObject* renderer)
{
ASSERT(renderer);
RenderObjectSizeCountMap::iterator it = m_clients.find(renderer);
- ASSERT(it != m_clients.end());
+ ASSERT_WITH_SECURITY_IMPLICATION(it != m_clients.end());
IntSize removedImageSize;
SizeAndCount& sizeCount = it->value;
@@ -110,13 +110,13 @@ PassRefPtr<Image> CSSImageGeneratorValue::image(RenderObject* renderer, const In
{
switch (classType()) {
case CanvasClass:
- return static_cast<CSSCanvasValue*>(this)->image(renderer, size);
+ return toCSSCanvasValue(this)->image(renderer, size);
case CrossfadeClass:
- return static_cast<CSSCrossfadeValue*>(this)->image(renderer, size);
+ return toCSSCrossfadeValue(this)->image(renderer, size);
case LinearGradientClass:
- return static_cast<CSSLinearGradientValue*>(this)->image(renderer, size);
+ return toCSSLinearGradientValue(this)->image(renderer, size);
case RadialGradientClass:
- return static_cast<CSSRadialGradientValue*>(this)->image(renderer, size);
+ return toCSSRadialGradientValue(this)->image(renderer, size);
default:
ASSERT_NOT_REACHED();
}
@@ -127,13 +127,13 @@ bool CSSImageGeneratorValue::isFixedSize() const
{
switch (classType()) {
case CanvasClass:
- return static_cast<const CSSCanvasValue*>(this)->isFixedSize();
+ return toCSSCanvasValue(this)->isFixedSize();
case CrossfadeClass:
- return static_cast<const CSSCrossfadeValue*>(this)->isFixedSize();
+ return toCSSCrossfadeValue(this)->isFixedSize();
case LinearGradientClass:
- return static_cast<const CSSLinearGradientValue*>(this)->isFixedSize();
+ return toCSSLinearGradientValue(this)->isFixedSize();
case RadialGradientClass:
- return static_cast<const CSSRadialGradientValue*>(this)->isFixedSize();
+ return toCSSRadialGradientValue(this)->isFixedSize();
default:
ASSERT_NOT_REACHED();
}
@@ -144,13 +144,13 @@ IntSize CSSImageGeneratorValue::fixedSize(const RenderObject* renderer)
{
switch (classType()) {
case CanvasClass:
- return static_cast<CSSCanvasValue*>(this)->fixedSize(renderer);
+ return toCSSCanvasValue(this)->fixedSize(renderer);
case CrossfadeClass:
- return static_cast<CSSCrossfadeValue*>(this)->fixedSize(renderer);
+ return toCSSCrossfadeValue(this)->fixedSize(renderer);
case LinearGradientClass:
- return static_cast<CSSLinearGradientValue*>(this)->fixedSize(renderer);
+ return toCSSLinearGradientValue(this)->fixedSize(renderer);
case RadialGradientClass:
- return static_cast<CSSRadialGradientValue*>(this)->fixedSize(renderer);
+ return toCSSRadialGradientValue(this)->fixedSize(renderer);
default:
ASSERT_NOT_REACHED();
}
@@ -161,13 +161,13 @@ bool CSSImageGeneratorValue::isPending() const
{
switch (classType()) {
case CrossfadeClass:
- return static_cast<const CSSCrossfadeValue*>(this)->isPending();
+ return toCSSCrossfadeValue(this)->isPending();
case CanvasClass:
- return static_cast<const CSSCanvasValue*>(this)->isPending();
+ return toCSSCanvasValue(this)->isPending();
case LinearGradientClass:
- return static_cast<const CSSLinearGradientValue*>(this)->isPending();
+ return toCSSLinearGradientValue(this)->isPending();
case RadialGradientClass:
- return static_cast<const CSSRadialGradientValue*>(this)->isPending();
+ return toCSSRadialGradientValue(this)->isPending();
default:
ASSERT_NOT_REACHED();
}
@@ -178,13 +178,13 @@ bool CSSImageGeneratorValue::knownToBeOpaque(const RenderObject* renderer) const
{
switch (classType()) {
case CrossfadeClass:
- return static_cast<const CSSCrossfadeValue*>(this)->knownToBeOpaque(renderer);
+ return toCSSCrossfadeValue(this)->knownToBeOpaque(renderer);
case CanvasClass:
return false;
case LinearGradientClass:
- return static_cast<const CSSLinearGradientValue*>(this)->knownToBeOpaque(renderer);
+ return toCSSLinearGradientValue(this)->knownToBeOpaque(renderer);
case RadialGradientClass:
- return static_cast<const CSSRadialGradientValue*>(this)->knownToBeOpaque(renderer);
+ return toCSSRadialGradientValue(this)->knownToBeOpaque(renderer);
default:
ASSERT_NOT_REACHED();
}
@@ -195,16 +195,16 @@ void CSSImageGeneratorValue::loadSubimages(ResourceFetcher* fetcher)
{
switch (classType()) {
case CrossfadeClass:
- static_cast<CSSCrossfadeValue*>(this)->loadSubimages(fetcher);
+ toCSSCrossfadeValue(this)->loadSubimages(fetcher);
break;
case CanvasClass:
- static_cast<CSSCanvasValue*>(this)->loadSubimages(fetcher);
+ toCSSCanvasValue(this)->loadSubimages(fetcher);
break;
case LinearGradientClass:
- static_cast<CSSLinearGradientValue*>(this)->loadSubimages(fetcher);
+ toCSSLinearGradientValue(this)->loadSubimages(fetcher);
break;
case RadialGradientClass:
- static_cast<CSSRadialGradientValue*>(this)->loadSubimages(fetcher);
+ toCSSRadialGradientValue(this)->loadSubimages(fetcher);
break;
default:
ASSERT_NOT_REACHED();
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSImageGeneratorValue.h b/chromium/third_party/WebKit/Source/core/css/CSSImageGeneratorValue.h
index 4d967684ed4..d5803d3d52f 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSImageGeneratorValue.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSImageGeneratorValue.h
@@ -27,7 +27,7 @@
#define CSSImageGeneratorValue_h
#include "core/css/CSSValue.h"
-#include "core/platform/graphics/IntSizeHash.h"
+#include "platform/geometry/IntSizeHash.h"
#include "wtf/HashCountedSet.h"
#include "wtf/RefPtr.h"
@@ -79,6 +79,8 @@ protected:
HashMap<IntSize, RefPtr<Image> > m_images; // A cache of Image objects by image size.
};
+DEFINE_CSS_VALUE_TYPE_CASTS(CSSImageGeneratorValue, isImageGeneratorValue());
+
} // namespace WebCore
#endif // CSSImageGeneratorValue_h
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSImageSetValue.cpp b/chromium/third_party/WebKit/Source/core/css/CSSImageSetValue.cpp
index f46027eceda..ef6321908a1 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSImageSetValue.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/CSSImageSetValue.cpp
@@ -49,7 +49,7 @@ CSSImageSetValue::CSSImageSetValue()
CSSImageSetValue::~CSSImageSetValue()
{
if (m_imageSet && m_imageSet->isImageResourceSet())
- static_cast<StyleFetchedImageSet*>(m_imageSet.get())->clearImageSetValue();
+ toStyleFetchedImageSet(m_imageSet)->clearImageSetValue();
}
void CSSImageSetValue::fillImageSet()
@@ -111,7 +111,7 @@ StyleFetchedImageSet* CSSImageSetValue::cachedImageSet(ResourceFetcher* loader,
}
}
- return (m_imageSet && m_imageSet->isImageResourceSet()) ? static_cast<StyleFetchedImageSet*>(m_imageSet.get()) : 0;
+ return (m_imageSet && m_imageSet->isImageResourceSet()) ? toStyleFetchedImageSet(m_imageSet) : 0;
}
StyleImage* CSSImageSetValue::cachedOrPendingImageSet(float deviceScaleFactor)
@@ -129,7 +129,7 @@ StyleImage* CSSImageSetValue::cachedOrPendingImageSet(float deviceScaleFactor)
return m_imageSet.get();
}
-String CSSImageSetValue::customCssText() const
+String CSSImageSetValue::customCSSText() const
{
StringBuilder result;
result.append("-webkit-image-set(");
@@ -163,10 +163,9 @@ bool CSSImageSetValue::hasFailedOrCanceledSubresources() const
{
if (!m_imageSet || !m_imageSet->isImageResourceSet())
return false;
- Resource* cachedResource = static_cast<StyleFetchedImageSet*>(m_imageSet.get())->cachedImage();
- if (!cachedResource)
- return true;
- return cachedResource->loadFailedOrCanceled();
+ if (Resource* cachedResource = toStyleFetchedImageSet(m_imageSet)->cachedImage())
+ return cachedResource->loadFailedOrCanceled();
+ return true;
}
CSSImageSetValue::CSSImageSetValue(const CSSImageSetValue& cloneFrom)
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSImageSetValue.h b/chromium/third_party/WebKit/Source/core/css/CSSImageSetValue.h
index 7f5a377441f..ee6e86b4313 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSImageSetValue.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSImageSetValue.h
@@ -48,7 +48,7 @@ public:
// Returns a StyleFetchedImageSet if the best fit image has been cached already, otherwise a StylePendingImage.
StyleImage* cachedOrPendingImageSet(float);
- String customCssText() const;
+ String customCSSText() const;
bool isPending() const { return !m_accessedBestFitImage; }
@@ -81,6 +81,8 @@ private:
Vector<ImageWithScale> m_imagesInSet;
};
+DEFINE_CSS_VALUE_TYPE_CASTS(CSSImageSetValue, isImageSetValue());
+
} // namespace WebCore
#endif // CSSImageSetValue_h
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSImageValue.cpp b/chromium/third_party/WebKit/Source/core/css/CSSImageValue.cpp
index 6f33b18af16..4dd0799e101 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSImageValue.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/CSSImageValue.cpp
@@ -24,9 +24,9 @@
#include "FetchInitiatorTypeNames.h"
#include "core/css/CSSParser.h"
#include "core/dom/Document.h"
+#include "core/fetch/CrossOriginAccessControl.h"
#include "core/fetch/FetchRequest.h"
#include "core/fetch/ImageResource.h"
-#include "core/fetch/ResourceFetcher.h"
#include "core/rendering/style/StyleFetchedImage.h"
#include "core/rendering/style/StylePendingImage.h"
@@ -59,29 +59,32 @@ StyleImage* CSSImageValue::cachedOrPendingImage()
return m_image.get();
}
-StyleFetchedImage* CSSImageValue::cachedImage(ResourceFetcher* loader, const ResourceLoaderOptions& options)
+StyleFetchedImage* CSSImageValue::cachedImage(ResourceFetcher* fetcher, const ResourceLoaderOptions& options, CORSEnabled corsEnabled)
{
- ASSERT(loader);
+ ASSERT(fetcher);
if (!m_accessedImage) {
m_accessedImage = true;
- FetchRequest request(ResourceRequest(loader->document()->completeURL(m_url)), m_initiatorName.isEmpty() ? FetchInitiatorTypeNames::css : m_initiatorName, options);
- if (ResourcePtr<ImageResource> cachedImage = loader->fetchImage(request))
+ FetchRequest request(ResourceRequest(fetcher->document()->completeURL(m_url)), m_initiatorName.isEmpty() ? FetchInitiatorTypeNames::css : m_initiatorName, options);
+
+ if (corsEnabled == PotentiallyCORSEnabled)
+ updateRequestForAccessControl(request.mutableResourceRequest(), fetcher->document()->securityOrigin(), options.allowCredentials);
+
+ if (ResourcePtr<ImageResource> cachedImage = fetcher->fetchImage(request))
m_image = StyleFetchedImage::create(cachedImage.get());
}
- return (m_image && m_image->isImageResource()) ? static_cast<StyleFetchedImage*>(m_image.get()) : 0;
+ return (m_image && m_image->isImageResource()) ? toStyleFetchedImage(m_image) : 0;
}
bool CSSImageValue::hasFailedOrCanceledSubresources() const
{
if (!m_image || !m_image->isImageResource())
return false;
- Resource* cachedResource = static_cast<StyleFetchedImage*>(m_image.get())->cachedImage();
- if (!cachedResource)
- return true;
- return cachedResource->loadFailedOrCanceled();
+ if (Resource* cachedResource = toStyleFetchedImage(m_image)->cachedImage())
+ return cachedResource->loadFailedOrCanceled();
+ return true;
}
bool CSSImageValue::equals(const CSSImageValue& other) const
@@ -89,7 +92,7 @@ bool CSSImageValue::equals(const CSSImageValue& other) const
return m_url == other.m_url;
}
-String CSSImageValue::customCssText() const
+String CSSImageValue::customCSSText() const
{
return "url(" + quoteCSSURLIfNeeded(m_url) + ")";
}
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSImageValue.h b/chromium/third_party/WebKit/Source/core/css/CSSImageValue.h
index 0e66982cb1a..a84afa5947a 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSImageValue.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSImageValue.h
@@ -38,14 +38,14 @@ public:
static PassRefPtr<CSSImageValue> create(const String& url, StyleImage* image) { return adoptRef(new CSSImageValue(url, image)); }
~CSSImageValue();
- StyleFetchedImage* cachedImage(ResourceFetcher*, const ResourceLoaderOptions&);
- StyleFetchedImage* cachedImage(ResourceFetcher* loader) { return cachedImage(loader, ResourceFetcher::defaultResourceOptions()); }
+ StyleFetchedImage* cachedImage(ResourceFetcher*, const ResourceLoaderOptions&, CORSEnabled);
+ StyleFetchedImage* cachedImage(ResourceFetcher* fetcher) { return cachedImage(fetcher, ResourceFetcher::defaultResourceOptions(), NotCORSEnabled); }
// Returns a StyleFetchedImage if the image is cached already, otherwise a StylePendingImage.
StyleImage* cachedOrPendingImage();
const String& url() { return m_url; }
- String customCssText() const;
+ String customCSSText() const;
PassRefPtr<CSSValue> cloneForCSSOM() const;
@@ -67,20 +67,7 @@ private:
AtomicString m_initiatorName;
};
-inline CSSImageValue* toCSSImageValue(CSSValue* value)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!value || value->isImageValue());
- return static_cast<CSSImageValue*>(value);
-}
-
-inline const CSSImageValue* toCSSImageValue(const CSSValue* value)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!value || value->isImageValue());
- return static_cast<const CSSImageValue*>(value);
-}
-
-// Catch unneeded cast.
-void toCSSImageValue(const CSSImageValue*);
+DEFINE_CSS_VALUE_TYPE_CASTS(CSSImageValue, isImageValue());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSImportRule.h b/chromium/third_party/WebKit/Source/core/css/CSSImportRule.h
index b16e943b585..0abfc9a3284 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSImportRule.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSImportRule.h
@@ -53,11 +53,7 @@ private:
mutable RefPtr<CSSStyleSheet> m_styleSheetCSSOMWrapper;
};
-inline CSSImportRule* toCSSImportRule(CSSRule* rule)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(rule->type() == CSSRule::IMPORT_RULE);
- return static_cast<CSSImportRule*>(rule);
-}
+DEFINE_CSS_RULE_TYPE_CASTS(CSSImportRule, IMPORT_RULE);
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSInheritedValue.cpp b/chromium/third_party/WebKit/Source/core/css/CSSInheritedValue.cpp
index a239629b8af..1fdb41893bd 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSInheritedValue.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/CSSInheritedValue.cpp
@@ -25,7 +25,7 @@
namespace WebCore {
-String CSSInheritedValue::customCssText() const
+String CSSInheritedValue::customCSSText() const
{
return "inherit";
}
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSInheritedValue.h b/chromium/third_party/WebKit/Source/core/css/CSSInheritedValue.h
index 3e346bfbb64..7367707daf6 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSInheritedValue.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSInheritedValue.h
@@ -33,7 +33,7 @@ public:
return adoptRef(new CSSInheritedValue);
}
- String customCssText() const;
+ String customCSSText() const;
bool equals(const CSSInheritedValue&) const { return true; }
@@ -44,6 +44,8 @@ private:
}
};
+DEFINE_CSS_VALUE_TYPE_CASTS(CSSInheritedValue, isInheritedValue());
+
} // namespace WebCore
#endif // CSSInheritedValue_h
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSInitialValue.cpp b/chromium/third_party/WebKit/Source/core/css/CSSInitialValue.cpp
index e9ec2c78a69..14dbdc9abb3 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSInitialValue.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/CSSInitialValue.cpp
@@ -25,7 +25,7 @@
namespace WebCore {
-String CSSInitialValue::customCssText() const
+String CSSInitialValue::customCSSText() const
{
return "initial";
}
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSInitialValue.h b/chromium/third_party/WebKit/Source/core/css/CSSInitialValue.h
index f2bc029904f..f8f9e512fce 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSInitialValue.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSInitialValue.h
@@ -37,7 +37,7 @@ public:
return adoptRef(new CSSInitialValue(/* implicit */ true));
}
- String customCssText() const;
+ String customCSSText() const;
bool isImplicit() const { return m_isImplicit; }
@@ -53,6 +53,8 @@ private:
bool m_isImplicit;
};
+DEFINE_CSS_VALUE_TYPE_CASTS(CSSInitialValue, isInitialValue());
+
} // namespace WebCore
#endif // CSSInitialValue_h
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSKeyframeRule.cpp b/chromium/third_party/WebKit/Source/core/css/CSSKeyframeRule.cpp
index 2b1a1fdae9f..65aa3077c93 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSKeyframeRule.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/CSSKeyframeRule.cpp
@@ -76,7 +76,7 @@ const Vector<double>& StyleKeyframe::keys() const
// Keys can only be cleared by setting the key text from JavaScript
// and this can never be null.
ASSERT(!m_keyText.isNull());
- m_keys = CSSParser(CSSStrictMode).parseKeyframeKeyList(m_keyText);
+ m_keys = CSSParser(HTMLStandardMode).parseKeyframeKeyList(m_keyText);
}
// If an invalid key string was set, m_keys may be empty.
ASSERT(m_keys);
@@ -95,7 +95,7 @@ MutableStylePropertySet* StyleKeyframe::mutableProperties()
{
if (!m_properties->isMutable())
m_properties = m_properties->mutableCopy();
- return static_cast<MutableStylePropertySet*>(m_properties.get());
+ return toMutableStylePropertySet(m_properties);
}
void StyleKeyframe::setProperties(PassRefPtr<StylePropertySet> properties)
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSKeyframeRule.h b/chromium/third_party/WebKit/Source/core/css/CSSKeyframeRule.h
index 44e2d753bbd..594314808f9 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSKeyframeRule.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSKeyframeRule.h
@@ -94,6 +94,8 @@ private:
friend class CSSKeyframesRule;
};
+DEFINE_CSS_RULE_TYPE_CASTS(CSSKeyframeRule, KEYFRAME_RULE);
+
} // namespace WebCore
#endif // CSSKeyframeRule_h
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSKeyframesRule.cpp b/chromium/third_party/WebKit/Source/core/css/CSSKeyframesRule.cpp
index b4fbb0e3d99..94d5dff8e6a 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSKeyframesRule.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/CSSKeyframesRule.cpp
@@ -198,8 +198,7 @@ CSSRuleList* CSSKeyframesRule::cssRules()
void CSSKeyframesRule::reattach(StyleRuleBase* rule)
{
ASSERT(rule);
- ASSERT_WITH_SECURITY_IMPLICATION(rule->isKeyframesRule());
- m_keyframesRule = static_cast<StyleRuleKeyframes*>(rule);
+ m_keyframesRule = toStyleRuleKeyframes(rule);
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSKeyframesRule.h b/chromium/third_party/WebKit/Source/core/css/CSSKeyframesRule.h
index e0518afe414..d74cf686e75 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSKeyframesRule.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSKeyframesRule.h
@@ -68,6 +68,8 @@ private:
bool m_isPrefixed;
};
+DEFINE_STYLE_RULE_TYPE_CASTS(Keyframes);
+
class CSSKeyframesRule FINAL : public CSSRule {
public:
static PassRefPtr<CSSKeyframesRule> create(StyleRuleKeyframes* rule, CSSStyleSheet* sheet) { return adoptRef(new CSSKeyframesRule(rule, sheet)); }
@@ -103,6 +105,8 @@ private:
bool m_isPrefixed;
};
+DEFINE_CSS_RULE_TYPE_CASTS(CSSKeyframesRule, KEYFRAMES_RULE);
+
} // namespace WebCore
#endif // CSSKeyframesRule_h
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSKeyframesRule.idl b/chromium/third_party/WebKit/Source/core/css/CSSKeyframesRule.idl
index c94dbc47e9b..d97dd4aae3b 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSKeyframesRule.idl
+++ b/chromium/third_party/WebKit/Source/core/css/CSSKeyframesRule.idl
@@ -28,8 +28,7 @@
// Introduced in DOM Level ?:
interface CSSKeyframesRule : CSSRule {
-
- [TreatReturnedNullStringAs=Null, TreatNullAs=NullString] attribute DOMString name;
+ attribute DOMString name;
readonly attribute CSSRuleList cssRules;
[ImplementedAs=item, NotEnumerable] getter CSSKeyframeRule(unsigned long index);
@@ -37,4 +36,3 @@ interface CSSKeyframesRule : CSSRule {
void deleteRule([Default=Undefined] optional DOMString key);
CSSKeyframeRule findRule([Default=Undefined] optional DOMString key);
};
-
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSLengthFunctions.cpp b/chromium/third_party/WebKit/Source/core/css/CSSLengthFunctions.cpp
new file mode 100644
index 00000000000..94acda3c866
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/css/CSSLengthFunctions.cpp
@@ -0,0 +1,149 @@
+/*
+ Copyright (C) 1999 Lars Knoll (knoll@kde.org)
+ Copyright (C) 2006, 2008 Apple Inc. All rights reserved.
+ Copyright (C) 2011 Rik Cabanier (cabanier@adobe.com)
+ Copyright (C) 2011 Adobe Systems Incorporated. All rights reserved.
+ Copyright (C) 2012 Motorola Mobility, Inc. All rights reserved.
+ Copyright (C) 2013 Google, Inc. All rights reserved.
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#include "config.h"
+#include "core/css/CSSLengthFunctions.h"
+
+#include "core/rendering/RenderView.h"
+#include "platform/LayoutUnit.h"
+#include "platform/Length.h"
+#include "platform/LengthFunctions.h"
+
+namespace WebCore {
+
+int minimumIntValueForLength(const Length& length, LayoutUnit maximumValue, RenderView* renderView, bool roundPercentages)
+{
+ return static_cast<int>(minimumValueForLength(length, maximumValue, renderView, roundPercentages));
+}
+
+int intValueForLength(const Length& length, LayoutUnit maximumValue, RenderView* renderView, bool roundPercentages)
+{
+ return static_cast<int>(valueForLength(length, maximumValue, renderView, roundPercentages));
+}
+
+LayoutUnit minimumValueForLength(const Length& length, LayoutUnit maximumValue, RenderView* renderView, bool roundPercentages)
+{
+ switch (length.type()) {
+ case Fixed:
+ return length.value();
+ case Percent:
+ if (roundPercentages)
+ return static_cast<LayoutUnit>(round(maximumValue * length.percent() / 100.0f));
+ // Don't remove the extra cast to float. It is needed for rounding on 32-bit Intel machines that use the FPU stack.
+ return static_cast<float>(maximumValue * length.percent() / 100.0f);
+ case Calculated:
+ return length.nonNanCalculatedValue(maximumValue);
+ case ViewportPercentageWidth:
+ return renderView ? renderView->viewportPercentageWidth(length.viewportPercentageLength()) : LayoutUnit(0);
+ case ViewportPercentageHeight:
+ return renderView ? renderView->viewportPercentageHeight(length.viewportPercentageLength()) : LayoutUnit(0);
+ case ViewportPercentageMin:
+ return renderView ? renderView->viewportPercentageMin(length.viewportPercentageLength()) : LayoutUnit(0);
+ case ViewportPercentageMax:
+ return renderView ? renderView->viewportPercentageMax(length.viewportPercentageLength()) : LayoutUnit(0);
+ case FillAvailable:
+ case Auto:
+ return 0;
+ case Intrinsic:
+ case MinIntrinsic:
+ case MinContent:
+ case MaxContent:
+ case FitContent:
+ case ExtendToZoom:
+ case Undefined:
+ ASSERT_NOT_REACHED();
+ return 0;
+ }
+ ASSERT_NOT_REACHED();
+ return 0;
+}
+
+LayoutUnit valueForLength(const Length& length, LayoutUnit maximumValue, RenderView* renderView, bool roundPercentages)
+{
+ switch (length.type()) {
+ case Fixed:
+ case Percent:
+ case Calculated:
+ case ViewportPercentageWidth:
+ case ViewportPercentageHeight:
+ case ViewportPercentageMin:
+ case ViewportPercentageMax:
+ return minimumValueForLength(length, maximumValue, renderView, roundPercentages);
+ case FillAvailable:
+ case Auto:
+ return maximumValue;
+ case Intrinsic:
+ case MinIntrinsic:
+ case MinContent:
+ case MaxContent:
+ case FitContent:
+ case ExtendToZoom:
+ case Undefined:
+ ASSERT_NOT_REACHED();
+ return 0;
+ }
+ ASSERT_NOT_REACHED();
+ return 0;
+}
+
+// This method has code duplicated in platform/LengthFunctions.cpp.
+// Any changes here most likely also need to be applied there.
+float floatValueForLength(const Length& length, float maximumValue, RenderView* renderView)
+{
+ if (!renderView)
+ return floatValueForLength(length, maximumValue);
+
+ switch (length.type()) {
+ case Fixed:
+ return length.getFloatValue();
+ case Percent:
+ return static_cast<float>(maximumValue * length.percent() / 100.0f);
+ case FillAvailable:
+ case Auto:
+ return static_cast<float>(maximumValue);
+ case Calculated:
+ return length.nonNanCalculatedValue(maximumValue);
+ case ViewportPercentageWidth:
+ return static_cast<int>(renderView->viewportPercentageWidth(length.viewportPercentageLength()));
+ case ViewportPercentageHeight:
+ return static_cast<int>(renderView->viewportPercentageHeight(length.viewportPercentageLength()));
+ case ViewportPercentageMin:
+ return static_cast<int>(renderView->viewportPercentageMin(length.viewportPercentageLength()));
+ case ViewportPercentageMax:
+ return static_cast<int>(renderView->viewportPercentageMax(length.viewportPercentageLength()));
+ case Intrinsic:
+ case MinIntrinsic:
+ case MinContent:
+ case MaxContent:
+ case FitContent:
+ case ExtendToZoom:
+ case Undefined:
+ ASSERT_NOT_REACHED();
+ return 0;
+ }
+ ASSERT_NOT_REACHED();
+ return 0;
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSLengthFunctions.h b/chromium/third_party/WebKit/Source/core/css/CSSLengthFunctions.h
new file mode 100644
index 00000000000..46e3540c180
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/css/CSSLengthFunctions.h
@@ -0,0 +1,42 @@
+/*
+ Copyright (C) 1999 Lars Knoll (knoll@kde.org)
+ Copyright (C) 2006, 2008 Apple Inc. All rights reserved.
+ Copyright (C) 2011 Rik Cabanier (cabanier@adobe.com)
+ Copyright (C) 2011 Adobe Systems Incorporated. All rights reserved.
+ Copyright (C) 2012 Motorola Mobility, Inc. All rights reserved.
+ Copyright (C) 2013 Google, Inc. All rights reserved.
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#ifndef CSSLengthFunctions_h
+#define CSSLengthFunctions_h
+
+namespace WebCore {
+
+class LayoutUnit;
+class Length;
+class RenderView;
+
+int minimumIntValueForLength(const Length&, LayoutUnit maximumValue, RenderView* = 0, bool roundPercentages = false);
+int intValueForLength(const Length&, LayoutUnit maximumValue, RenderView* = 0, bool roundPercentages = false);
+LayoutUnit minimumValueForLength(const Length&, LayoutUnit maximumValue, RenderView* = 0, bool roundPercentages = false);
+LayoutUnit valueForLength(const Length&, LayoutUnit maximumValue, RenderView* = 0, bool roundPercentages = false);
+float floatValueForLength(const Length&, float maximumValue, RenderView*);
+
+} // namespace WebCore
+
+#endif // CSSLengthFunctions_h
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSLineBoxContainValue.cpp b/chromium/third_party/WebKit/Source/core/css/CSSLineBoxContainValue.cpp
index c1ae2e5e635..7c3532b6c29 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSLineBoxContainValue.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/CSSLineBoxContainValue.cpp
@@ -37,7 +37,7 @@ CSSLineBoxContainValue::CSSLineBoxContainValue(unsigned value)
{
}
-String CSSLineBoxContainValue::customCssText() const
+String CSSLineBoxContainValue::customCSSText() const
{
StringBuilder text;
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSLineBoxContainValue.h b/chromium/third_party/WebKit/Source/core/css/CSSLineBoxContainValue.h
index 6e5a050e525..657578ab251 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSLineBoxContainValue.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSLineBoxContainValue.h
@@ -45,7 +45,7 @@ public:
return adoptRef(new CSSLineBoxContainValue(value));
}
- String customCssText() const;
+ String customCSSText() const;
bool equals(const CSSLineBoxContainValue& other) const { return m_value == other.m_value; }
LineBoxContain value() const { return m_value; }
@@ -56,6 +56,8 @@ private:
explicit CSSLineBoxContainValue(LineBoxContain);
};
+DEFINE_CSS_VALUE_TYPE_CASTS(CSSLineBoxContainValue, isLineBoxContainValue());
+
} // namespace
#endif
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSMatrix.cpp b/chromium/third_party/WebKit/Source/core/css/CSSMatrix.cpp
index 7866dd968f7..4926df97629 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSMatrix.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/CSSMatrix.cpp
@@ -30,9 +30,12 @@
#include "CSSValueKeywords.h"
#include "bindings/v8/ExceptionState.h"
#include "core/css/CSSParser.h"
+#include "core/css/CSSToLengthConversionData.h"
#include "core/css/StylePropertySet.h"
#include "core/css/resolver/TransformBuilder.h"
#include "core/dom/ExceptionCode.h"
+#include "core/rendering/style/RenderStyle.h"
+#include "core/rendering/style/StyleInheritedData.h"
#include "wtf/MathExtras.h"
namespace WebCore {
@@ -43,23 +46,19 @@ CSSMatrix::CSSMatrix(const TransformationMatrix& m)
ScriptWrappable::init(this);
}
-CSSMatrix::CSSMatrix(const String& s, ExceptionState& es)
+CSSMatrix::CSSMatrix(const String& s, ExceptionState& exceptionState)
{
ScriptWrappable::init(this);
- setMatrixValue(s, es);
+ setMatrixValue(s, exceptionState);
}
-CSSMatrix::~CSSMatrix()
-{
-}
-
-void CSSMatrix::setMatrixValue(const String& string, ExceptionState& es)
+void CSSMatrix::setMatrixValue(const String& string, ExceptionState& exceptionState)
{
if (string.isEmpty())
return;
RefPtr<MutableStylePropertySet> styleDeclaration = MutableStylePropertySet::create();
- if (CSSParser::parseValue(styleDeclaration.get(), CSSPropertyWebkitTransform, string, true, CSSStrictMode, 0)) {
+ if (CSSParser::parseValue(styleDeclaration.get(), CSSPropertyWebkitTransform, string, true, HTMLStandardMode, 0)) {
// Convert to TransformOperations. This can fail if a property
// requires style (i.e., param uses 'ems' or 'exs')
RefPtr<CSSValue> value = styleDeclaration->getPropertyCSSValue(CSSPropertyWebkitTransform);
@@ -68,26 +67,24 @@ void CSSMatrix::setMatrixValue(const String& string, ExceptionState& es)
if (!value || (value->isPrimitiveValue() && (toCSSPrimitiveValue(value.get()))->getValueID() == CSSValueNone))
return;
+ DEFINE_STATIC_REF(RenderStyle, defaultStyle, RenderStyle::createDefaultStyle());
TransformOperations operations;
- if (!TransformBuilder::createTransformOperations(value.get(), 0, 0, operations)) {
- es.throwDOMException(SyntaxError);
+ if (!TransformBuilder::createTransformOperations(value.get(), CSSToLengthConversionData(defaultStyle, defaultStyle), operations)) {
+ exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
return;
}
// Convert transform operations to a TransformationMatrix. This can fail
// if a param has a percentage ('%')
+ if (operations.dependsOnBoxSize())
+ exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
TransformationMatrix t;
- for (unsigned i = 0; i < operations.operations().size(); ++i) {
- if (operations.operations()[i].get()->apply(t, IntSize(0, 0))) {
- es.throwDOMException(SyntaxError);
- return;
- }
- }
+ operations.apply(FloatSize(0, 0), t);
// set the matrix
m_matrix = t;
} else { // There is something there but parsing failed.
- es.throwDOMException(SyntaxError);
+ exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
}
}
@@ -100,10 +97,10 @@ PassRefPtr<CSSMatrix> CSSMatrix::multiply(CSSMatrix* secondMatrix) const
return CSSMatrix::create(TransformationMatrix(m_matrix).multiply(secondMatrix->m_matrix));
}
-PassRefPtr<CSSMatrix> CSSMatrix::inverse(ExceptionState& es) const
+PassRefPtr<CSSMatrix> CSSMatrix::inverse(ExceptionState& exceptionState) const
{
if (!m_matrix.isInvertible()) {
- es.throwDOMException(NotSupportedError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
return 0;
}
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSMatrix.h b/chromium/third_party/WebKit/Source/core/css/CSSMatrix.h
index 1f3397d76b8..92c6cb1ab08 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSMatrix.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSMatrix.h
@@ -27,7 +27,7 @@
#define CSSMatrix_h
#include "bindings/v8/ScriptWrappable.h"
-#include "core/platform/graphics/transforms/TransformationMatrix.h"
+#include "platform/transforms/TransformationMatrix.h"
#include "wtf/RefCounted.h"
#include "wtf/text/WTFString.h"
@@ -35,19 +35,17 @@ namespace WebCore {
class ExceptionState;
-class CSSMatrix : public ScriptWrappable, public RefCounted<CSSMatrix> {
+class CSSMatrix FINAL : public ScriptWrappable, public RefCounted<CSSMatrix> {
public:
static PassRefPtr<CSSMatrix> create(const TransformationMatrix& m)
{
return adoptRef(new CSSMatrix(m));
}
- static PassRefPtr<CSSMatrix> create(const String& s, ExceptionState& es)
+ static PassRefPtr<CSSMatrix> create(const String& s, ExceptionState& exceptionState)
{
- return adoptRef(new CSSMatrix(s, es));
+ return adoptRef(new CSSMatrix(s, exceptionState));
}
- virtual ~CSSMatrix();
-
double a() const { return m_matrix.a(); }
double b() const { return m_matrix.b(); }
double c() const { return m_matrix.c(); }
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSMediaRule.cpp b/chromium/third_party/WebKit/Source/core/css/CSSMediaRule.cpp
index ad60dc7732c..7e8c34a5945 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSMediaRule.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/CSSMediaRule.cpp
@@ -53,7 +53,7 @@ String CSSMediaRule::cssText() const
result.append(' ');
}
result.appendLiteral("{ \n");
- appendCssTextForItems(result);
+ appendCSSTextForItems(result);
result.append('}');
return result.toString();
}
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSMediaRule.h b/chromium/third_party/WebKit/Source/core/css/CSSMediaRule.h
index 194f918a638..380c062c122 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSMediaRule.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSMediaRule.h
@@ -50,6 +50,8 @@ private:
mutable RefPtr<MediaList> m_mediaCSSOMWrapper;
};
+DEFINE_CSS_RULE_TYPE_CASTS(CSSMediaRule, MEDIA_RULE);
+
} // namespace WebCore
#endif // CSSMediaRule_h
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSMixFunctionValue.cpp b/chromium/third_party/WebKit/Source/core/css/CSSMixFunctionValue.cpp
index 288a7c34a57..0dd07a58fee 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSMixFunctionValue.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/CSSMixFunctionValue.cpp
@@ -42,9 +42,9 @@ CSSMixFunctionValue::CSSMixFunctionValue(const CSSMixFunctionValue& cloneFrom)
{
}
-String CSSMixFunctionValue::customCssText() const
+String CSSMixFunctionValue::customCSSText() const
{
- return "mix(" + CSSValueList::customCssText() + ")";
+ return "mix(" + CSSValueList::customCSSText() + ")";
}
PassRefPtr<CSSMixFunctionValue> CSSMixFunctionValue::cloneForCSSOM() const
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSMixFunctionValue.h b/chromium/third_party/WebKit/Source/core/css/CSSMixFunctionValue.h
index e91542d6b81..04a5e2d6020 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSMixFunctionValue.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSMixFunctionValue.h
@@ -42,7 +42,7 @@ public:
return adoptRef(new CSSMixFunctionValue());
}
- String customCssText() const;
+ String customCSSText() const;
PassRefPtr<CSSMixFunctionValue> cloneForCSSOM() const;
@@ -53,6 +53,8 @@ private:
CSSMixFunctionValue(const CSSMixFunctionValue& cloneFrom);
};
+DEFINE_CSS_VALUE_TYPE_CASTS(CSSMixFunctionValue, isMixFunctionValue());
+
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSPageRule.cpp b/chromium/third_party/WebKit/Source/core/css/CSSPageRule.cpp
index 5d08a3c2106..0513e92dd99 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSPageRule.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/CSSPageRule.cpp
@@ -95,8 +95,7 @@ String CSSPageRule::cssText() const
void CSSPageRule::reattach(StyleRuleBase* rule)
{
ASSERT(rule);
- ASSERT_WITH_SECURITY_IMPLICATION(rule->isPageRule());
- m_pageRule = static_cast<StyleRulePage*>(rule);
+ m_pageRule = toStyleRulePage(rule);
if (m_propertiesCSSOMWrapper)
m_propertiesCSSOMWrapper->reattach(m_pageRule->mutableProperties());
}
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSPageRule.h b/chromium/third_party/WebKit/Source/core/css/CSSPageRule.h
index 21079c1e7ca..4aa0f696e63 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSPageRule.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSPageRule.h
@@ -53,6 +53,8 @@ private:
mutable RefPtr<StyleRuleCSSStyleDeclaration> m_propertiesCSSOMWrapper;
};
+DEFINE_CSS_RULE_TYPE_CASTS(CSSPageRule, PAGE_RULE);
+
} // namespace WebCore
#endif // CSSPageRule_h
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSPageRule.idl b/chromium/third_party/WebKit/Source/core/css/CSSPageRule.idl
index e9e49d0969a..3c64d3b9c42 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSPageRule.idl
+++ b/chromium/third_party/WebKit/Source/core/css/CSSPageRule.idl
@@ -20,10 +20,6 @@
// Introduced in DOM Level 2:
interface CSSPageRule : CSSRule {
-
- [TreatReturnedNullStringAs=Null, TreatNullAs=NullString] attribute DOMString selectorText;
-
+ attribute DOMString selectorText;
readonly attribute CSSStyleDeclaration style;
-
};
-
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSParser-in.cpp b/chromium/third_party/WebKit/Source/core/css/CSSParser-in.cpp
index 5444ad82331..7b540fd7b14 100644..100755
--- a/chromium/third_party/WebKit/Source/core/css/CSSParser-in.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/CSSParser-in.cpp
@@ -38,8 +38,10 @@
#include "core/css/CSSCrossfadeValue.h"
#include "core/css/CSSCursorImageValue.h"
#include "core/css/CSSFontFaceSrcValue.h"
+#include "core/css/CSSFontFeatureValue.h"
#include "core/css/CSSFunctionValue.h"
#include "core/css/CSSGradientValue.h"
+#include "core/css/CSSGridLineNamesValue.h"
#include "core/css/CSSGridTemplateValue.h"
#include "core/css/CSSImageSetValue.h"
#include "core/css/CSSImageValue.h"
@@ -55,6 +57,7 @@
#include "core/css/CSSSVGDocumentValue.h"
#include "core/css/CSSSelector.h"
#include "core/css/CSSShaderValue.h"
+#include "core/css/CSSShadowValue.h"
#include "core/css/CSSStyleSheet.h"
#include "core/css/CSSTimingFunctionValue.h"
#include "core/css/CSSTransformValue.h"
@@ -63,12 +66,11 @@
#include "core/css/CSSValuePool.h"
#include "core/css/CSSVariableValue.h"
#include "core/css/Counter.h"
-#include "core/css/FontFeatureValue.h"
+#include "core/css/HashTools.h"
#include "core/css/MediaList.h"
#include "core/css/MediaQueryExp.h"
#include "core/css/Pair.h"
#include "core/css/Rect.h"
-#include "core/css/ShadowValue.h"
#include "core/css/StylePropertySet.h"
#include "core/css/StyleRule.h"
#include "core/css/StyleRuleImport.h"
@@ -76,13 +78,11 @@
#include "core/dom/Document.h"
#include "core/html/parser/HTMLParserIdioms.h"
#include "core/inspector/InspectorInstrumentation.h"
-#include "core/page/Page.h"
#include "core/page/PageConsole.h"
-#include "core/page/Settings.h"
-#include "core/platform/FloatConversion.h"
-#include "core/platform/HashTools.h"
+#include "core/frame/Settings.h"
#include "core/rendering/RenderTheme.h"
#include "core/svg/SVGParserUtilities.h"
+#include "platform/FloatConversion.h"
#include "wtf/BitArray.h"
#include "wtf/HexNumber.h"
#include "wtf/text/StringBuffer.h"
@@ -134,17 +134,6 @@ static bool equalIgnoringCase(CSSParserValue* value, const char (&b)[N])
return equalIgnoringCase(value->string, b);
}
-static bool hasPrefix(const char* string, unsigned length, const char* prefix)
-{
- for (unsigned i = 0; i < length; ++i) {
- if (!prefix[i])
- return true;
- if (string[i] != prefix[i])
- return false;
- }
- return false;
-}
-
static PassRefPtr<CSSPrimitiveValue> createPrimitiveValuePair(PassRefPtr<CSSPrimitiveValue> first, PassRefPtr<CSSPrimitiveValue> second, Pair::IdenticalValuesPolicy identicalValuesPolicy = Pair::DropIdenticalValues)
{
return cssValuePool().createValue(Pair::create(first, second, identicalValuesPolicy));
@@ -195,47 +184,6 @@ private:
bool m_hasSeenAnimationPropertyKeyword;
};
-const CSSParserContext& strictCSSParserContext()
-{
- DEFINE_STATIC_LOCAL(CSSParserContext, strictContext, (CSSStrictMode));
- return strictContext;
-}
-
-CSSParserContext::CSSParserContext(CSSParserMode mode, const KURL& baseURL)
- : baseURL(baseURL)
- , mode(mode)
- , isHTMLDocument(false)
- , isCSSCustomFilterEnabled(false)
- , isCSSStickyPositionEnabled(false)
- , needsSiteSpecificQuirks(false)
- , useLegacyBackgroundSizeShorthandBehavior(false)
-{
-}
-
-CSSParserContext::CSSParserContext(const Document& document, const KURL& baseURL, const String& charset)
- : baseURL(baseURL.isNull() ? document.baseURL() : baseURL)
- , charset(charset)
- , mode(document.inQuirksMode() ? CSSQuirksMode : CSSStrictMode)
- , isHTMLDocument(document.isHTMLDocument())
- , isCSSCustomFilterEnabled(document.settings() ? document.settings()->isCSSCustomFilterEnabled() : false)
- , isCSSStickyPositionEnabled(document.cssStickyPositionEnabled())
- , needsSiteSpecificQuirks(document.settings() ? document.settings()->needsSiteSpecificQuirks() : false)
- , useLegacyBackgroundSizeShorthandBehavior(document.settings() ? document.settings()->useLegacyBackgroundSizeShorthandBehavior() : false)
-{
-}
-
-bool operator==(const CSSParserContext& a, const CSSParserContext& b)
-{
- return a.baseURL == b.baseURL
- && a.charset == b.charset
- && a.mode == b.mode
- && a.isHTMLDocument == b.isHTMLDocument
- && a.isCSSCustomFilterEnabled == b.isCSSCustomFilterEnabled
- && a.isCSSStickyPositionEnabled == b.isCSSStickyPositionEnabled
- && a.needsSiteSpecificQuirks == b.needsSiteSpecificQuirks
- && a.useLegacyBackgroundSizeShorthandBehavior == b.useLegacyBackgroundSizeShorthandBehavior;
-}
-
CSSParser::CSSParser(const CSSParserContext& context, UseCounter* counter)
: m_context(context)
, m_important(false)
@@ -253,28 +201,18 @@ CSSParser::CSSParser(const CSSParserContext& context, UseCounter* counter)
, m_ignoreErrors(false)
, m_inFilterRule(false)
, m_defaultNamespace(starAtom)
- , m_parsedTextPrefixLength(0)
- , m_parsedTextSuffixLength(0)
, m_sourceDataHandler(0)
- , m_parsingMode(NormalMode)
- , m_is8BitSource(false)
- , m_currentCharacter8(0)
- , m_currentCharacter16(0)
, m_source(0)
- , m_length(0)
- , m_token(0)
- , m_lineNumber(0)
- , m_tokenStartLineNumber(0)
, m_ruleHeaderType(CSSRuleSourceData::UNKNOWN_RULE)
, m_allowImportRules(true)
, m_allowNamespaceDeclarations(true)
, m_inViewport(false)
, m_useCounter(counter)
+ , m_tokenizer(*this)
{
#if YYDEBUG > 0
cssyydebug = 1;
#endif
- m_tokenStart.ptr8 = 0;
CSSPropertySourceData::init();
}
@@ -288,76 +226,10 @@ CSSParser::~CSSParser()
deleteAllValues(m_floatingFunctions);
}
-AtomicString CSSParserString::atomicSubstring(unsigned position, unsigned length) const
-{
- ASSERT(m_length >= position + length);
-
- if (is8Bit())
- return AtomicString(characters8() + position, length);
- return AtomicString(characters16() + position, length);
-}
-
-void CSSParserString::trimTrailingWhitespace()
-{
- if (is8Bit()) {
- while (m_length > 0 && isHTMLSpace<LChar>(m_data.characters8[m_length - 1]))
- --m_length;
- } else {
- while (m_length > 0 && isHTMLSpace<UChar>(m_data.characters16[m_length - 1]))
- --m_length;
- }
-}
-
void CSSParser::setupParser(const char* prefix, unsigned prefixLength, const String& string, const char* suffix, unsigned suffixLength)
{
- m_parsedTextPrefixLength = prefixLength;
- m_parsedTextSuffixLength = suffixLength;
- unsigned stringLength = string.length();
- unsigned length = stringLength + m_parsedTextPrefixLength + m_parsedTextSuffixLength + 1;
- m_length = length;
-
- if (!stringLength || string.is8Bit()) {
- m_dataStart8 = adoptArrayPtr(new LChar[length]);
- for (unsigned i = 0; i < m_parsedTextPrefixLength; i++)
- m_dataStart8[i] = prefix[i];
-
- if (stringLength)
- memcpy(m_dataStart8.get() + m_parsedTextPrefixLength, string.characters8(), stringLength * sizeof(LChar));
-
- unsigned start = m_parsedTextPrefixLength + stringLength;
- unsigned end = start + suffixLength;
- for (unsigned i = start; i < end; i++)
- m_dataStart8[i] = suffix[i - start];
-
- m_dataStart8[length - 1] = 0;
-
- m_is8BitSource = true;
- m_currentCharacter8 = m_dataStart8.get();
- m_currentCharacter16 = 0;
- setTokenStart<LChar>(m_currentCharacter8);
- m_lexFunc = &CSSParser::realLex<LChar>;
- return;
- }
-
- m_dataStart16 = adoptArrayPtr(new UChar[length]);
- for (unsigned i = 0; i < m_parsedTextPrefixLength; i++)
- m_dataStart16[i] = prefix[i];
-
- ASSERT(stringLength);
- memcpy(m_dataStart16.get() + m_parsedTextPrefixLength, string.characters16(), stringLength * sizeof(UChar));
-
- unsigned start = m_parsedTextPrefixLength + stringLength;
- unsigned end = start + suffixLength;
- for (unsigned i = start; i < end; i++)
- m_dataStart16[i] = suffix[i - start];
-
- m_dataStart16[length - 1] = 0;
-
- m_is8BitSource = false;
- m_currentCharacter8 = 0;
- m_currentCharacter16 = m_dataStart16.get();
- setTokenStart<UChar>(m_currentCharacter16);
- m_lexFunc = &CSSParser::realLex<UChar>;
+ m_tokenizer.setupTokenizer(prefix, prefixLength, string, suffix, suffixLength);
+ m_ruleHasHeader = true;
}
void CSSParser::parseSheet(StyleSheetContents* sheet, const String& string, const TextPosition& startPosition, SourceDataHandler* sourceDataHandler, bool logErrors)
@@ -367,9 +239,10 @@ void CSSParser::parseSheet(StyleSheetContents* sheet, const String& string, cons
m_sourceDataHandler = sourceDataHandler;
m_logErrors = logErrors && sheet->singleOwnerDocument() && !sheet->baseURL().isEmpty() && sheet->singleOwnerDocument()->page();
m_ignoreErrors = false;
- m_lineNumber = 0;
+ m_tokenizer.m_lineNumber = 0;
m_startPosition = startPosition;
m_source = &string;
+ m_tokenizer.m_internal = false;
setupParser("", string, "");
cssyyparse(this);
sheet->shrinkToFit();
@@ -379,6 +252,7 @@ void CSSParser::parseSheet(StyleSheetContents* sheet, const String& string, cons
m_lineEndings.clear();
m_ignoreErrors = false;
m_logErrors = false;
+ m_tokenizer.m_internal = true;
}
PassRefPtr<StyleRuleBase> CSSParser::parseRule(StyleSheetContents* sheet, const String& string)
@@ -446,19 +320,19 @@ static inline bool isColorPropertyID(CSSPropertyID propertyId)
static bool parseColorValue(MutableStylePropertySet* declaration, CSSPropertyID propertyId, const String& string, bool important, CSSParserMode cssParserMode)
{
ASSERT(!string.isEmpty());
- bool strict = isStrictParserMode(cssParserMode);
+ bool quirksMode = isQuirksModeBehavior(cssParserMode);
if (!isColorPropertyID(propertyId))
return false;
CSSParserString cssString;
cssString.init(string);
CSSValueID valueID = cssValueKeywordID(cssString);
bool validPrimitive = false;
- if (valueID == CSSValueWebkitText)
+ if (valueID == CSSValueWebkitText) {
validPrimitive = true;
- else if (valueID == CSSValueCurrentcolor)
+ } else if (valueID == CSSValueCurrentcolor) {
validPrimitive = true;
- else if ((valueID >= CSSValueAqua && valueID <= CSSValueWindowtext) || valueID == CSSValueMenu
- || (valueID >= CSSValueWebkitFocusRingColor && valueID < CSSValueWebkitText && !strict)) {
+ } else if ((valueID >= CSSValueAqua && valueID <= CSSValueWindowtext) || valueID == CSSValueMenu
+ || (quirksMode && valueID >= CSSValueWebkitFocusRingColor && valueID < CSSValueWebkitText)) {
validPrimitive = true;
}
@@ -468,7 +342,7 @@ static bool parseColorValue(MutableStylePropertySet* declaration, CSSPropertyID
return true;
}
RGBA32 color;
- if (!CSSParser::fastParseColor(color, string, strict && string[0] != '#'))
+ if (!CSSParser::fastParseColor(color, string, !quirksMode && string[0] != '#'))
return false;
RefPtr<CSSValue> value = cssValuePool().createColorValue(color);
declaration->addParsedProperty(CSSProperty(propertyId, value.release(), important));
@@ -497,8 +371,8 @@ static inline bool isSimpleLengthPropertyID(CSSPropertyID propertyId, bool& acce
case CSSPropertyWebkitPaddingStart:
acceptsNegativeNumbers = false;
return true;
- case CSSPropertyWebkitShapeMargin:
- case CSSPropertyWebkitShapePadding:
+ case CSSPropertyShapeMargin:
+ case CSSPropertyShapePadding:
acceptsNegativeNumbers = false;
return RuntimeEnabledFeatures::cssShapesEnabled();
case CSSPropertyBottom:
@@ -543,8 +417,9 @@ static bool parseSimpleLengthValue(MutableStylePropertySet* declaration, CSSProp
{
ASSERT(!string.isEmpty());
bool acceptsNegativeNumbers;
- // In ViewportMode, width and height are shorthands, not simple length values.
- if (cssParserMode == ViewportMode || !isSimpleLengthPropertyID(propertyId, acceptsNegativeNumbers))
+
+ // In @viewport, width and height are shorthands, not simple length values.
+ if (isCSSViewportParsingEnabledForMode(cssParserMode) || !isSimpleLengthPropertyID(propertyId, acceptsNegativeNumbers))
return false;
unsigned length = string.length();
@@ -560,7 +435,8 @@ static bool parseSimpleLengthValue(MutableStylePropertySet* declaration, CSSProp
}
if (unit == CSSPrimitiveValue::CSS_NUMBER) {
- if (number && isStrictParserMode(cssParserMode))
+ bool quirksMode = isQuirksModeBehavior(cssParserMode);
+ if (number && !quirksMode)
return false;
unit = CSSPrimitiveValue::CSS_PX;
}
@@ -611,7 +487,7 @@ static inline bool isValidKeywordPropertyAndValue(CSSPropertyID propertyId, int
return true;
break;
case CSSPropertyDisplay:
- // inline | block | list-item | run-in | inline-block | table |
+ // inline | block | list-item | inline-block | table |
// inline-table | table-row-group | table-header-group | table-footer-group | table-row |
// table-column-group | table-column | table-cell | table-caption | -webkit-box | -webkit-inline-box | none | inherit
// flex | inline-flex | -webkit-flex | -webkit-inline-flex | grid | inline-grid | lazy-block
@@ -688,13 +564,13 @@ static inline bool isValidKeywordPropertyAndValue(CSSPropertyID propertyId, int
break;
case CSSPropertyPointerEvents:
// none | visiblePainted | visibleFill | visibleStroke | visible |
- // painted | fill | stroke | auto | all | inherit
- if (valueID == CSSValueVisible || valueID == CSSValueNone || valueID == CSSValueAll || valueID == CSSValueAuto || (valueID >= CSSValueVisiblepainted && valueID <= CSSValueStroke))
+ // painted | fill | stroke | auto | all | bounding-box | inherit
+ if (valueID == CSSValueVisible || valueID == CSSValueNone || valueID == CSSValueAll || valueID == CSSValueAuto || (valueID >= CSSValueVisiblepainted && valueID <= CSSValueBoundingBox))
return true;
break;
case CSSPropertyPosition: // static | relative | absolute | fixed | sticky | inherit
if (valueID == CSSValueStatic || valueID == CSSValueRelative || valueID == CSSValueAbsolute || valueID == CSSValueFixed
- || (parserContext.isCSSStickyPositionEnabled && valueID == CSSValueSticky))
+ || (RuntimeEnabledFeatures::cssStickyPositionEnabled() && valueID == CSSValueSticky))
return true;
break;
case CSSPropertyResize: // none | both | horizontal | vertical | auto
@@ -715,6 +591,12 @@ static inline bool isValidKeywordPropertyAndValue(CSSPropertyID propertyId, int
&& ((valueID >= CSSValueLeft && valueID <= CSSValueJustify) || valueID == CSSValueStart || valueID == CSSValueEnd || valueID == CSSValueAuto))
return true;
break;
+ case CSSPropertyTextJustify:
+ // auto | none | inter-word | distribute
+ if (RuntimeEnabledFeatures::css3TextEnabled()
+ && (valueID == CSSValueInterWord || valueID == CSSValueDistribute || valueID == CSSValueAuto || valueID == CSSValueNone))
+ return true;
+ break;
case CSSPropertyTextLineThroughMode:
case CSSPropertyTextOverlineMode:
case CSSPropertyTextUnderlineMode:
@@ -739,8 +621,8 @@ static inline bool isValidKeywordPropertyAndValue(CSSPropertyID propertyId, int
if ((valueID >= CSSValueCapitalize && valueID <= CSSValueLowercase) || valueID == CSSValueNone)
return true;
break;
- case CSSPropertyTouchAction: // auto | none
- if (RuntimeEnabledFeatures::cssTouchActionEnabled() && (valueID == CSSValueAuto || valueID == CSSValueNone))
+ case CSSPropertyTouchActionDelay: // none | script
+ if (RuntimeEnabledFeatures::cssTouchActionEnabled() && (valueID == CSSValueScript || valueID == CSSValueNone))
return true;
break;
case CSSPropertyVisibility: // visible | hidden | collapse | inherit
@@ -791,6 +673,15 @@ static inline bool isValidKeywordPropertyAndValue(CSSPropertyID propertyId, int
if (valueID == CSSValueStart || valueID == CSSValueEnd || valueID == CSSValueCenter || valueID == CSSValueJustify)
return true;
break;
+ case CSSPropertyInternalCallback:
+ // This property is only injected programmatically, not parsed from stylesheets.
+ return false;
+ case CSSPropertyColumnFill:
+ if (RuntimeEnabledFeatures::regionBasedColumnsEnabled()) {
+ if (valueID == CSSValueAuto || valueID == CSSValueBalance)
+ return true;
+ }
+ break;
case CSSPropertyAlignContent:
if (valueID == CSSValueFlexStart || valueID == CSSValueFlexEnd || valueID == CSSValueCenter || valueID == CSSValueSpaceBetween || valueID == CSSValueSpaceAround || valueID == CSSValueStretch)
return true;
@@ -815,7 +706,7 @@ static inline bool isValidKeywordPropertyAndValue(CSSPropertyID propertyId, int
if (valueID == CSSValueFlexStart || valueID == CSSValueFlexEnd || valueID == CSSValueCenter || valueID == CSSValueSpaceBetween || valueID == CSSValueSpaceAround)
return true;
break;
- case CSSPropertyWebkitFontKerning:
+ case CSSPropertyFontKerning:
if (valueID == CSSValueAuto || valueID == CSSValueNormal || valueID == CSSValueNone)
return true;
break;
@@ -947,9 +838,6 @@ static inline bool isKeywordPropertyID(CSSPropertyID propertyId)
switch (propertyId) {
case CSSPropertyMixBlendMode:
case CSSPropertyIsolation:
- return RuntimeEnabledFeatures::cssCompositingEnabled();
- case CSSPropertyTextAlignLast:
- return RuntimeEnabledFeatures::css3TextEnabled();
case CSSPropertyBorderBottomStyle:
case CSSPropertyBorderCollapse:
case CSSPropertyBorderLeftStyle:
@@ -979,6 +867,8 @@ static inline bool isKeywordPropertyID(CSSPropertyID propertyId)
case CSSPropertyResize:
case CSSPropertySpeak:
case CSSPropertyTableLayout:
+ case CSSPropertyTextAlignLast:
+ case CSSPropertyTextJustify:
case CSSPropertyTextLineThroughMode:
case CSSPropertyTextLineThroughStyle:
case CSSPropertyTextOverflow:
@@ -988,7 +878,7 @@ static inline bool isKeywordPropertyID(CSSPropertyID propertyId)
case CSSPropertyTextTransform:
case CSSPropertyTextUnderlineMode:
case CSSPropertyTextUnderlineStyle:
- case CSSPropertyTouchAction:
+ case CSSPropertyTouchActionDelay:
case CSSPropertyVisibility:
case CSSPropertyWebkitAppearance:
case CSSPropertyWebkitBackfaceVisibility:
@@ -1003,9 +893,11 @@ static inline bool isKeywordPropertyID(CSSPropertyID propertyId)
case CSSPropertyWebkitBoxLines:
case CSSPropertyWebkitBoxOrient:
case CSSPropertyWebkitBoxPack:
+ case CSSPropertyInternalCallback:
case CSSPropertyWebkitColumnBreakAfter:
case CSSPropertyWebkitColumnBreakBefore:
case CSSPropertyWebkitColumnBreakInside:
+ case CSSPropertyColumnFill:
case CSSPropertyWebkitColumnRuleStyle:
case CSSPropertyAlignContent:
case CSSPropertyAlignItems:
@@ -1013,7 +905,7 @@ static inline bool isKeywordPropertyID(CSSPropertyID propertyId)
case CSSPropertyFlexDirection:
case CSSPropertyFlexWrap:
case CSSPropertyJustifyContent:
- case CSSPropertyWebkitFontKerning:
+ case CSSPropertyFontKerning:
case CSSPropertyWebkitFontSmoothing:
case CSSPropertyGridAutoFlow:
case CSSPropertyWebkitLineAlign:
@@ -1088,7 +980,7 @@ static bool parseKeywordValue(MutableStylePropertySet* declaration, CSSPropertyI
}
template <typename CharacterType>
-static bool parseTransformArguments(CSSTransformValue* transformValue, CharacterType* characters, unsigned length, unsigned start, unsigned expectedCount)
+static bool parseTransformTranslateArguments(CSSTransformValue* transformValue, CharacterType* characters, unsigned length, unsigned start, unsigned expectedCount)
{
while (expectedCount) {
size_t end = WTF::find(characters, length, expectedCount == 1 ? ')' : ',', start);
@@ -1101,7 +993,7 @@ static bool parseTransformArguments(CSSTransformValue* transformValue, Character
return false;
if (unit != CSSPrimitiveValue::CSS_PX && (number || unit != CSSPrimitiveValue::CSS_NUMBER))
return false;
- transformValue->append(cssValuePool().createValue(number, unit));
+ transformValue->append(cssValuePool().createValue(number, CSSPrimitiveValue::CSS_PX));
start = end + 1;
--expectedCount;
}
@@ -1144,9 +1036,9 @@ static bool parseTranslateTransformValue(MutableStylePropertySet* properties, CS
RefPtr<CSSTransformValue> transformValue = CSSTransformValue::create(transformType);
bool success;
if (string.is8Bit())
- success = parseTransformArguments(transformValue.get(), string.characters8(), string.length(), argumentStart, expectedArgumentCount);
+ success = parseTransformTranslateArguments(transformValue.get(), string.characters8(), string.length(), argumentStart, expectedArgumentCount);
else
- success = parseTransformArguments(transformValue.get(), string.characters16(), string.length(), argumentStart, expectedArgumentCount);
+ success = parseTransformTranslateArguments(transformValue.get(), string.characters16(), string.length(), argumentStart, expectedArgumentCount);
if (!success)
return false;
RefPtr<CSSValueList> result = CSSValueList::createSpaceSeparated();
@@ -1160,7 +1052,7 @@ PassRefPtr<CSSValueList> CSSParser::parseFontFaceValue(const AtomicString& strin
if (string.isEmpty())
return 0;
RefPtr<MutableStylePropertySet> dummyStyle = MutableStylePropertySet::create();
- if (!parseValue(dummyStyle.get(), CSSPropertyFontFamily, string, false, CSSQuirksMode, 0))
+ if (!parseValue(dummyStyle.get(), CSSPropertyFontFamily, string, false, HTMLQuirksMode, 0))
return 0;
RefPtr<CSSValue> fontFamily = dummyStyle->getPropertyCSSValue(CSSPropertyFontFamily);
@@ -1176,9 +1068,9 @@ bool CSSParser::parseValue(MutableStylePropertySet* declaration, CSSPropertyID p
CSSParserContext context(document);
- if (parseSimpleLengthValue(declaration, propertyID, string, important, context.mode))
+ if (parseSimpleLengthValue(declaration, propertyID, string, important, context.mode()))
return true;
- if (parseColorValue(declaration, propertyID, string, important, context.mode))
+ if (parseColorValue(declaration, propertyID, string, important, context.mode()))
return true;
if (parseKeywordValue(declaration, propertyID, string, important, context))
return true;
@@ -1198,7 +1090,7 @@ bool CSSParser::parseValue(MutableStylePropertySet* declaration, CSSPropertyID p
CSSParserContext context(cssParserMode);
if (contextStyleSheet) {
context = contextStyleSheet->parserContext();
- context.mode = cssParserMode;
+ context.setMode(cssParserMode);
}
if (parseKeywordValue(declaration, propertyID, string, important, context))
@@ -1214,9 +1106,8 @@ bool CSSParser::parseValue(MutableStylePropertySet* declaration, CSSPropertyID p
{
// FIXME: Check RuntimeCSSEnabled::isPropertyEnabled or isValueEnabledForProperty.
- // We don't count the UA style sheet in our statistics.
- if (m_context.mode != UASheetMode && m_useCounter)
- m_useCounter->count(propertyID);
+ if (m_useCounter)
+ m_useCounter->count(m_context, propertyID);
setStyleSheet(contextStyleSheet);
@@ -1253,7 +1144,7 @@ bool CSSParser::parseColor(RGBA32& color, const String& string, bool strict)
if (fastParseColor(color, string, strict))
return true;
- CSSParser parser(CSSStrictMode);
+ CSSParser parser(HTMLStandardMode);
// In case the fast-path parser didn't understand the color, try the full parser.
if (!parser.parseColor(string))
@@ -1310,7 +1201,7 @@ PassRefPtr<ImmutableStylePropertySet> CSSParser::parseInlineStyleDeclaration(con
{
Document& document = element->document();
CSSParserContext context = document.elementSheet()->contents()->parserContext();
- context.mode = strictToCSSParserMode(element->isHTMLElement() && !document.inQuirksMode());
+ context.setMode((element->isHTMLElement() && !document.inQuirksMode()) ? HTMLStandardMode : HTMLQuirksMode);
return CSSParser(context, UseCounter::getFrom(&document)).parseDeclaration(string, document.elementSheet()->contents());
}
@@ -1415,7 +1306,7 @@ PassRefPtr<ImmutableStylePropertySet> CSSParser::createStylePropertySet()
if (unusedEntries)
results.remove(0, unusedEntries);
- CSSParserMode mode = inViewport() ? ViewportMode : m_context.mode;
+ CSSParserMode mode = inViewport() ? CSSViewportRuleMode : m_context.mode();
return ImmutableStylePropertySet::create(results.data(), results.size(), mode);
}
@@ -1448,7 +1339,8 @@ void CSSParser::addProperty(CSSPropertyID propId, PassRefPtr<CSSValue> value, bo
return;
}
- const Vector<StylePropertyShorthand> shorthands = matchingShorthandsForLonghand(propId);
+ Vector<StylePropertyShorthand, 4> shorthands;
+ getMatchingShorthandsForLonghand(propId, &shorthands);
// The longhand does not belong to multiple shorthands.
if (shorthands.size() == 1)
m_parsedProperties.append(CSSProperty(propId, value, important, true, CSSPropertyInvalid, m_implicitShorthand || implicit));
@@ -1470,13 +1362,14 @@ void CSSParser::clearProperties()
m_hasFontFaceOnlyValues = false;
}
+// FIXME: Move to CSSParserContext?
KURL CSSParser::completeURL(const CSSParserContext& context, const String& url)
{
if (url.isNull())
return KURL();
- if (context.charset.isEmpty())
- return KURL(context.baseURL, url);
- return KURL(context.baseURL, url, context.charset);
+ if (context.charset().isEmpty())
+ return KURL(context.baseURL(), url);
+ return KURL(context.baseURL(), url, context.charset());
}
KURL CSSParser::completeURL(const String& url) const
@@ -1488,7 +1381,7 @@ bool CSSParser::validCalculationUnit(CSSParserValue* value, Units unitflags, Rel
{
bool mustBeNonNegative = unitflags & FNonNeg;
- if (!parseCalculation(value, mustBeNonNegative ? CalculationRangeNonNegative : CalculationRangeAll))
+ if (!parseCalculation(value, mustBeNonNegative ? ValueRangeNonNegative : ValueRangeAll))
return false;
bool b = false;
@@ -1528,7 +1421,7 @@ bool CSSParser::validCalculationUnit(CSSParserValue* value, Units unitflags, Rel
inline bool CSSParser::shouldAcceptUnitLessValues(CSSParserValue* value, Units unitflags, CSSParserMode cssParserMode)
{
// Quirks mode and presentation attributes accept unit less values.
- return (unitflags & (FLength | FAngle | FTime)) && (!value->fValue || cssParserMode == CSSQuirksMode || cssParserMode == SVGAttributeMode || cssParserMode == CSSAttributeMode);
+ return (unitflags & (FLength | FAngle | FTime)) && (!value->fValue || isUnitLessLengthParsingEnabledForMode(cssParserMode));
}
bool CSSParser::validUnit(CSSParserValue* value, Units unitflags, CSSParserMode cssParserMode, ReleaseParsedCalcValueCondition releaseCalc)
@@ -1640,6 +1533,24 @@ static inline bool isForwardSlashOperator(CSSParserValue* value)
return value->unit == CSSParserValue::Operator && value->iValue == '/';
}
+static bool isGeneratedImageValue(CSSParserValue* val)
+{
+ if (val->unit != CSSParserValue::Function)
+ return false;
+
+ return equalIgnoringCase(val->function->name, "-webkit-gradient(")
+ || equalIgnoringCase(val->function->name, "-webkit-linear-gradient(")
+ || equalIgnoringCase(val->function->name, "linear-gradient(")
+ || equalIgnoringCase(val->function->name, "-webkit-repeating-linear-gradient(")
+ || equalIgnoringCase(val->function->name, "repeating-linear-gradient(")
+ || equalIgnoringCase(val->function->name, "-webkit-radial-gradient(")
+ || equalIgnoringCase(val->function->name, "radial-gradient(")
+ || equalIgnoringCase(val->function->name, "-webkit-repeating-radial-gradient(")
+ || equalIgnoringCase(val->function->name, "repeating-radial-gradient(")
+ || equalIgnoringCase(val->function->name, "-webkit-canvas(")
+ || equalIgnoringCase(val->function->name, "-webkit-cross-fade(");
+}
+
bool CSSParser::validWidthOrHeight(CSSParserValue* value)
{
int id = value->id;
@@ -1695,12 +1606,12 @@ void CSSParser::setCurrentProperty(CSSPropertyID propId)
bool CSSParser::parseValue(CSSPropertyID propId, bool important)
{
- if ((m_context.mode != UASheetMode && m_context.mode != CSSAttributeMode) && isInternalProperty(propId))
+ if (!isInternalPropertyAndValueParsingEnabledForMode(m_context.mode()) && isInternalProperty(propId))
return false;
// We don't count the UA style sheet in our statistics.
- if (m_context.mode != UASheetMode && m_useCounter)
- m_useCounter->count(propId);
+ if (m_useCounter)
+ m_useCounter->count(m_context, propId);
if (!m_valueList)
return false;
@@ -1712,7 +1623,7 @@ bool CSSParser::parseValue(CSSPropertyID propId, bool important)
if (inViewport()) {
// Allow @viewport rules from UA stylesheets even if the feature is disabled.
- if (!RuntimeEnabledFeatures::cssViewportEnabled() && m_context.mode != UASheetMode)
+ if (!RuntimeEnabledFeatures::cssViewportEnabled() && !isUASheetBehavior(m_context.mode()))
return false;
return parseViewportProperty(propId, important);
@@ -1847,7 +1758,7 @@ bool CSSParser::parseValue(CSSPropertyID propId, bool important)
break;
case CSSPropertyOutlineColor: // <color> | invert | inherit
// Outline color has "invert" as additional keyword.
- // Also, we want to allow the special focus color even in strict parsing mode.
+ // Also, we want to allow the special focus color even in HTML Standard parsing mode.
if (id == CSSValueInvert || id == CSSValueWebkitFocusRingColor) {
validPrimitive = true;
break;
@@ -1876,7 +1787,7 @@ bool CSSParser::parseValue(CSSPropertyID propId, bool important)
return false;
if ((id >= CSSValueAqua && id <= CSSValueWebkitText) || id == CSSValueMenu) {
- validPrimitive = isValueAllowedInMode(id, m_context.mode);
+ validPrimitive = isValueAllowedInMode(id, m_context.mode());
} else {
parsedValue = parseColor();
if (parsedValue)
@@ -2136,7 +2047,7 @@ bool CSSParser::parseValue(CSSPropertyID propId, bool important)
if (id == CSSValueAuto)
validPrimitive = true;
else
- validPrimitive = (!id && validUnit(value, FInteger, CSSQuirksMode));
+ validPrimitive = (!id && validUnit(value, FInteger, HTMLQuirksMode));
break;
case CSSPropertyLineHeight:
@@ -2177,17 +2088,17 @@ bool CSSParser::parseValue(CSSPropertyID propId, bool important)
validPrimitive = true;
break;
-#if ENABLE(CSS3_TEXT)
- case CSSPropertyWebkitTextUnderlinePosition:
- // auto | alphabetic | under
- return parseTextUnderlinePosition(important);
-#endif // CSS3_TEXT
+ case CSSPropertyTextUnderlinePosition:
+ // auto | under | inherit
+ if (RuntimeEnabledFeatures::css3TextDecorationsEnabled())
+ return parseTextUnderlinePosition(important);
+ return false;
case CSSPropertyZoom: // normal | reset | document | <number> | <percentage> | inherit
if (id == CSSValueNormal || id == CSSValueReset || id == CSSValueDocument)
validPrimitive = true;
else
- validPrimitive = (!id && validUnit(value, FNumber | FPercent | FNonNeg, CSSStrictMode));
+ validPrimitive = (!id && validUnit(value, FNumber | FPercent | FNonNeg, HTMLStandardMode));
break;
case CSSPropertySrc: // Only used within @font-face and @-webkit-filter, so cannot use inherit | initial or be !important. This is a list of urls or local references.
@@ -2200,19 +2111,17 @@ bool CSSParser::parseValue(CSSPropertyID propId, bool important)
/* CSS3 properties */
- case CSSPropertyBorderImage: {
- RefPtr<CSSValue> result;
- return parseBorderImage(propId, result, important);
- }
- case CSSPropertyWebkitBorderImage:
- case CSSPropertyWebkitMaskBoxImage: {
- RefPtr<CSSValue> result;
- if (parseBorderImage(propId, result)) {
+ case CSSPropertyBorderImage:
+ case CSSPropertyWebkitMaskBoxImage:
+ return parseBorderImageShorthand(propId, important);
+ case CSSPropertyWebkitBorderImage: {
+ if (RefPtr<CSSValue> result = parseBorderImage(propId)) {
addProperty(propId, result, important);
return true;
}
- break;
+ return false;
}
+
case CSSPropertyBorderImageOutset:
case CSSPropertyWebkitMaskBoxImageOutset: {
RefPtr<CSSPrimitiveValue> result;
@@ -2281,7 +2190,7 @@ bool CSSParser::parseValue(CSSPropertyID propId, bool important)
case CSSPropertyWebkitBorderRadius:
return parseBorderRadius(propId, important);
case CSSPropertyOutlineOffset:
- validPrimitive = validUnit(value, FLength | FPercent);
+ validPrimitive = validUnit(value, FLength);
break;
case CSSPropertyTextShadow: // CSS2 property, dropped in CSS2.1, back in CSS3, so treat as CSS3
case CSSPropertyBoxShadow:
@@ -2311,10 +2220,10 @@ bool CSSParser::parseValue(CSSPropertyID propId, bool important)
validPrimitive = validUnit(value, FNumber);
break;
case CSSPropertyWebkitBoxFlexGroup:
- validPrimitive = validUnit(value, FInteger | FNonNeg, CSSStrictMode);
+ validPrimitive = validUnit(value, FInteger | FNonNeg, HTMLStandardMode);
break;
case CSSPropertyWebkitBoxOrdinalGroup:
- validPrimitive = validUnit(value, FInteger | FNonNeg, CSSStrictMode) && value->fValue;
+ validPrimitive = validUnit(value, FInteger | FNonNeg, HTMLStandardMode) && value->fValue;
break;
case CSSPropertyWebkitFilter:
if (id == CSSValueNone)
@@ -2328,12 +2237,6 @@ bool CSSParser::parseValue(CSSPropertyID propId, bool important)
return false;
}
break;
- case CSSPropertyMixBlendMode:
- case CSSPropertyIsolation:
- if (!RuntimeEnabledFeatures::cssCompositingEnabled())
- return false;
- validPrimitive = true;
- break;
case CSSPropertyFlex: {
ShorthandScope scope(this, propId);
if (id == CSSValueNone) {
@@ -2356,7 +2259,7 @@ bool CSSParser::parseValue(CSSPropertyID propId, bool important)
validPrimitive = validUnit(value, FNumber | FNonNeg);
break;
case CSSPropertyOrder:
- if (validUnit(value, FInteger, CSSStrictMode)) {
+ if (validUnit(value, FInteger, HTMLStandardMode)) {
if (value->unit != CSSPrimitiveValue::CSS_VARIABLE_NAME) {
// We restrict the smallest value to int min + 2 because we use int min and int min + 1 as special values in a hash set.
parsedValue = cssValuePool().createValue(max(static_cast<double>(std::numeric_limits<int>::min() + 2), value->fValue),
@@ -2585,7 +2488,7 @@ bool CSSParser::parseValue(CSSPropertyID propId, bool important)
case CSSPropertyWebkitLineClamp:
// When specifying number of lines, don't allow 0 as a valid value
// When specifying either type of unit, require non-negative integers
- validPrimitive = (!id && (value->unit == CSSPrimitiveValue::CSS_PERCENTAGE || value->fValue) && validUnit(value, FInteger | FPercent | FNonNeg, CSSQuirksMode));
+ validPrimitive = (!id && (value->unit == CSSPrimitiveValue::CSS_PERCENTAGE || value->fValue) && validUnit(value, FInteger | FPercent | FNonNeg, HTMLQuirksMode));
break;
case CSSPropertyWebkitFontSizeDelta: // <length>
@@ -2774,13 +2677,15 @@ bool CSSParser::parseValue(CSSPropertyID propId, bool important)
return true;
}
break;
- case CSSPropertyWebkitShapeInside:
- case CSSPropertyWebkitShapeOutside:
+ case CSSPropertyShapeInside:
+ case CSSPropertyShapeOutside:
if (!RuntimeEnabledFeatures::cssShapesEnabled())
return false;
if (id == CSSValueAuto)
validPrimitive = true;
- else if (propId == CSSPropertyWebkitShapeInside && id == CSSValueOutsideShape)
+ else if (id == CSSValueContentBox || id == CSSValuePaddingBox || id == CSSValueBorderBox || id == CSSValueMarginBox)
+ validPrimitive = true;
+ else if (propId == CSSPropertyShapeInside && id == CSSValueOutsideShape)
validPrimitive = true;
else if (value->unit == CSSParserValue::Function)
return parseBasicShape(propId, important);
@@ -2789,10 +2694,18 @@ bool CSSParser::parseValue(CSSPropertyID propId, bool important)
m_valueList->next();
}
break;
- case CSSPropertyWebkitShapeMargin:
- case CSSPropertyWebkitShapePadding:
+ case CSSPropertyShapeMargin:
+ case CSSPropertyShapePadding:
validPrimitive = (RuntimeEnabledFeatures::cssShapesEnabled() && !id && validUnit(value, FLength | FNonNeg));
break;
+ case CSSPropertyShapeImageThreshold:
+ validPrimitive = (RuntimeEnabledFeatures::cssShapesEnabled() && !id && validUnit(value, FNumber));
+ break;
+
+ case CSSPropertyTouchAction:
+ // auto | none | [pan-x || pan-y]
+ return parseTouchAction(important);
+
case CSSPropertyBorderBottomStyle:
case CSSPropertyBorderCollapse:
case CSSPropertyBorderLeftStyle:
@@ -2823,6 +2736,7 @@ bool CSSParser::parseValue(CSSPropertyID propId, bool important)
case CSSPropertySpeak:
case CSSPropertyTableLayout:
case CSSPropertyTextAlignLast:
+ case CSSPropertyTextJustify:
case CSSPropertyTextLineThroughMode:
case CSSPropertyTextLineThroughStyle:
case CSSPropertyTextOverflow:
@@ -2832,7 +2746,7 @@ bool CSSParser::parseValue(CSSPropertyID propId, bool important)
case CSSPropertyTextTransform:
case CSSPropertyTextUnderlineMode:
case CSSPropertyTextUnderlineStyle:
- case CSSPropertyTouchAction:
+ case CSSPropertyTouchActionDelay:
case CSSPropertyVariable:
case CSSPropertyVisibility:
case CSSPropertyWebkitAppearance:
@@ -2848,9 +2762,11 @@ bool CSSParser::parseValue(CSSPropertyID propId, bool important)
case CSSPropertyWebkitBoxLines:
case CSSPropertyWebkitBoxOrient:
case CSSPropertyWebkitBoxPack:
+ case CSSPropertyInternalCallback:
case CSSPropertyWebkitColumnBreakAfter:
case CSSPropertyWebkitColumnBreakBefore:
case CSSPropertyWebkitColumnBreakInside:
+ case CSSPropertyColumnFill:
case CSSPropertyWebkitColumnRuleStyle:
case CSSPropertyAlignContent:
case CSSPropertyAlignItems:
@@ -2858,7 +2774,7 @@ bool CSSParser::parseValue(CSSPropertyID propId, bool important)
case CSSPropertyFlexDirection:
case CSSPropertyFlexWrap:
case CSSPropertyJustifyContent:
- case CSSPropertyWebkitFontKerning:
+ case CSSPropertyFontKerning:
case CSSPropertyWebkitFontSmoothing:
case CSSPropertyGridAutoFlow:
case CSSPropertyWebkitLineAlign:
@@ -2890,12 +2806,14 @@ bool CSSParser::parseValue(CSSPropertyID propId, bool important)
case CSSPropertyWhiteSpace:
case CSSPropertyWordBreak:
case CSSPropertyWordWrap:
+ case CSSPropertyMixBlendMode:
+ case CSSPropertyIsolation:
// These properties should be handled before in isValidKeywordPropertyAndValue().
ASSERT_NOT_REACHED();
return false;
- // Properties bellow are validated inside parseViewportProperty, because we
- // check for parser state inViewportScope. We need to invalidate if someone
- // adds them outside a @viewport rule.
+ // Properties below are validated inside parseViewportProperty, because we
+ // check for parser state. We need to invalidate if someone adds them outside
+ // a @viewport rule.
case CSSPropertyMaxZoom:
case CSSPropertyMinZoom:
case CSSPropertyOrientation:
@@ -2949,7 +2867,7 @@ static bool parseBackgroundClip(CSSParserValue* parserValue, RefPtr<CSSValue>& c
bool CSSParser::useLegacyBackgroundSizeShorthandBehavior() const
{
- return m_context.useLegacyBackgroundSizeShorthandBehavior;
+ return m_context.useLegacyBackgroundSizeShorthandBehavior();
}
const int cMaxFillProperties = 9;
@@ -3274,7 +3192,7 @@ PassRefPtr<CSSValue> CSSParser::parseColumnWidth()
// Always parse lengths in strict mode here, since it would be ambiguous otherwise when used in
// the 'columns' shorthand property.
if (value->id == CSSValueAuto
- || (validUnit(value, FLength | FNonNeg, CSSStrictMode) && value->fValue)) {
+ || (validUnit(value, FLength | FNonNeg, HTMLStandardMode) && value->fValue)) {
RefPtr<CSSValue> parsedValue = parseValidPrimitive(value->id, value);
m_valueList->next();
return parsedValue;
@@ -3286,7 +3204,7 @@ PassRefPtr<CSSValue> CSSParser::parseColumnCount()
{
CSSParserValue* value = m_valueList->current();
if (value->id == CSSValueAuto
- || (!value->id && validUnit(value, FPositiveInteger, CSSQuirksMode))) {
+ || (!value->id && validUnit(value, FPositiveInteger, HTMLQuirksMode))) {
RefPtr<CSSValue> parsedValue = parseValidPrimitive(value->id, value);
m_valueList->next();
return parsedValue;
@@ -3664,7 +3582,7 @@ PassRefPtr<CSSValue> CSSParser::parseAttr(CSSParserValueList* args)
if (attrName[0] == '-')
return 0;
- if (m_context.isHTMLDocument)
+ if (m_context.isHTMLDocument())
attrName = attrName.lower();
return cssValuePool().createValue(attrName, CSSPrimitiveValue::CSS_ATTR);
@@ -4754,7 +4672,7 @@ bool CSSParser::parseGridAreaShorthand(bool important)
ShorthandScope scope(this, CSSPropertyGridArea);
const StylePropertyShorthand& shorthand = gridAreaShorthand();
- ASSERT(shorthand.length() == 4);
+ ASSERT_UNUSED(shorthand, shorthand.length() == 4);
RefPtr<CSSValue> rowStartValue = parseGridPosition();
if (!rowStartValue)
@@ -4803,6 +4721,28 @@ bool CSSParser::parseSingleGridAreaLonghand(RefPtr<CSSValue>& property)
return true;
}
+void CSSParser::parseGridLineNames(CSSParserValueList* parserValueList, CSSValueList& valueList)
+{
+ ASSERT(parserValueList->current() && parserValueList->current()->unit == CSSParserValue::ValueList);
+
+ CSSParserValueList* identList = parserValueList->current()->valueList;
+ if (!identList->size()) {
+ parserValueList->next();
+ return;
+ }
+
+ RefPtr<CSSGridLineNamesValue> lineNames = CSSGridLineNamesValue::create();
+ while (CSSParserValue* identValue = identList->current()) {
+ ASSERT(identValue->unit == CSSPrimitiveValue::CSS_IDENT);
+ RefPtr<CSSPrimitiveValue> lineName = createPrimitiveStringValue(identValue);
+ lineNames->append(lineName.release());
+ identList->next();
+ }
+ valueList.append(lineNames.release());
+
+ parserValueList->next();
+}
+
bool CSSParser::parseGridTrackList(CSSPropertyID propId, bool important)
{
ASSERT(RuntimeEnabledFeatures::cssGridLayoutEnabled());
@@ -4817,12 +4757,10 @@ bool CSSParser::parseGridTrackList(CSSPropertyID propId, bool important)
}
RefPtr<CSSValueList> values = CSSValueList::createSpaceSeparated();
- // Handle leading <string>*.
- while (m_valueList->current() && m_valueList->current()->unit == CSSPrimitiveValue::CSS_STRING) {
- RefPtr<CSSPrimitiveValue> name = createPrimitiveStringValue(m_valueList->current());
- values->append(name);
- m_valueList->next();
- }
+ // Handle leading <ident>*.
+ value = m_valueList->current();
+ if (value && value->unit == CSSParserValue::ValueList)
+ parseGridLineNames(m_valueList.get(), *values);
bool seenTrackSizeOrRepeatFunction = false;
while (CSSParserValue* currentValue = m_valueList->current()) {
@@ -4837,13 +4775,10 @@ bool CSSParser::parseGridTrackList(CSSPropertyID propId, bool important)
values->append(value);
seenTrackSizeOrRepeatFunction = true;
}
-
- // This will handle the trailing <string>* in the grammar.
- while (m_valueList->current() && m_valueList->current()->unit == CSSPrimitiveValue::CSS_STRING) {
- RefPtr<CSSPrimitiveValue> name = createPrimitiveStringValue(m_valueList->current());
- values->append(name);
- m_valueList->next();
- }
+ // This will handle the trailing <ident>* in the grammar.
+ value = m_valueList->current();
+ if (value && value->unit == CSSParserValue::ValueList)
+ parseGridLineNames(m_valueList.get(), *values);
}
// We should have found a <track-size> or else it is not a valid <track-list>
@@ -4866,26 +4801,22 @@ bool CSSParser::parseGridTrackRepeatFunction(CSSValueList& list)
arguments->next(); // Skip the repetition count.
arguments->next(); // Skip the comma.
- // Handle leading <string>*.
- while (arguments->current() && arguments->current()->unit == CSSPrimitiveValue::CSS_STRING) {
- RefPtr<CSSPrimitiveValue> name = createPrimitiveStringValue(arguments->current());
- repeatedValues->append(name);
- arguments->next();
- }
+ // Handle leading <ident>*.
+ CSSParserValue* currentValue = arguments->current();
+ if (currentValue && currentValue->unit == CSSParserValue::ValueList)
+ parseGridLineNames(arguments, *repeatedValues);
- while (CSSParserValue* argumentValue = arguments->current()) {
+ while (arguments->current()) {
RefPtr<CSSValue> trackSize = parseGridTrackSize(*arguments);
if (!trackSize)
return false;
repeatedValues->append(trackSize);
- // This takes care of any trailing <string>* in the grammar.
- while (arguments->current() && arguments->current()->unit == CSSPrimitiveValue::CSS_STRING) {
- RefPtr<CSSPrimitiveValue> name = createPrimitiveStringValue(arguments->current());
- repeatedValues->append(name);
- arguments->next();
- }
+ // This takes care of any trailing <ident>* in the grammar.
+ currentValue = arguments->current();
+ if (currentValue && currentValue->unit == CSSParserValue::ValueList)
+ parseGridLineNames(arguments, *repeatedValues);
}
for (size_t i = 0; i < repetitions; ++i) {
@@ -5685,7 +5616,7 @@ bool CSSParser::parseFontWeight(bool important)
addProperty(CSSPropertyFontWeight, cssValuePool().createIdentifierValue(value->id), important);
return true;
}
- if (validUnit(value, FInteger | FNonNeg, CSSQuirksMode)) {
+ if (validUnit(value, FInteger | FNonNeg, HTMLQuirksMode)) {
int weight = static_cast<int>(value->fValue);
if (!(weight % 100) && weight >= 100 && weight <= 900) {
addProperty(CSSPropertyFontWeight, cssValuePool().createIdentifierValue(static_cast<CSSValueID>(CSSValue100 + weight / 100 - 1)), important);
@@ -6230,9 +6161,9 @@ bool CSSParser::parseColorParameters(CSSParserValue* value, int* colorArray, boo
CSSParserValue* v = args->current();
Units unitType = FUnknown;
// Get the first value and its type
- if (validUnit(v, FInteger, CSSStrictMode))
+ if (validUnit(v, FInteger, HTMLStandardMode))
unitType = FInteger;
- else if (validUnit(v, FPercent, CSSStrictMode))
+ else if (validUnit(v, FPercent, HTMLStandardMode))
unitType = FPercent;
else
return false;
@@ -6243,7 +6174,7 @@ bool CSSParser::parseColorParameters(CSSParserValue* value, int* colorArray, boo
if (v->unit != CSSParserValue::Operator && v->iValue != ',')
return false;
v = args->next();
- if (!validUnit(v, unitType, CSSStrictMode))
+ if (!validUnit(v, unitType, HTMLStandardMode))
return false;
colorArray[i] = colorIntFromValue(v);
}
@@ -6252,7 +6183,7 @@ bool CSSParser::parseColorParameters(CSSParserValue* value, int* colorArray, boo
if (v->unit != CSSParserValue::Operator && v->iValue != ',')
return false;
v = args->next();
- if (!validUnit(v, FNumber, CSSStrictMode))
+ if (!validUnit(v, FNumber, HTMLStandardMode))
return false;
const double value = parsedDouble(v, ReleaseParsedCalcValue);
// Convert the floating pointer number of alpha to an integer in the range [0, 256),
@@ -6272,7 +6203,7 @@ bool CSSParser::parseHSLParameters(CSSParserValue* value, double* colorArray, bo
CSSParserValueList* args = value->function->args.get();
CSSParserValue* v = args->current();
// Get the first value
- if (!validUnit(v, FNumber, CSSStrictMode))
+ if (!validUnit(v, FNumber, HTMLStandardMode))
return false;
// normalize the Hue value and change it to be between 0 and 1.0
colorArray[0] = (((static_cast<int>(parsedDouble(v, ReleaseParsedCalcValue)) % 360) + 360) % 360) / 360.0;
@@ -6281,7 +6212,7 @@ bool CSSParser::parseHSLParameters(CSSParserValue* value, double* colorArray, bo
if (v->unit != CSSParserValue::Operator && v->iValue != ',')
return false;
v = args->next();
- if (!validUnit(v, FPercent, CSSStrictMode))
+ if (!validUnit(v, FPercent, HTMLStandardMode))
return false;
colorArray[i] = max(0.0, min(100.0, parsedDouble(v, ReleaseParsedCalcValue))) / 100.0; // needs to be value between 0 and 1.0
}
@@ -6290,7 +6221,7 @@ bool CSSParser::parseHSLParameters(CSSParserValue* value, double* colorArray, bo
if (v->unit != CSSParserValue::Operator && v->iValue != ',')
return false;
v = args->next();
- if (!validUnit(v, FNumber, CSSStrictMode))
+ if (!validUnit(v, FNumber, HTMLStandardMode))
return false;
colorArray[3] = max(0.0, min(1.0, parsedDouble(v, ReleaseParsedCalcValue)));
}
@@ -6311,12 +6242,12 @@ bool CSSParser::parseColorFromValue(CSSParserValue* value, RGBA32& c)
&& value->fValue >= 0. && value->fValue < 1000000.) {
String str = String::format("%06d", static_cast<int>((value->fValue+.5)));
// FIXME: This should be strict parsing for SVG as well.
- if (!fastParseColor(c, str, inStrictMode()))
+ if (!fastParseColor(c, str, !inQuirksMode()))
return false;
} else if (value->unit == CSSPrimitiveValue::CSS_PARSER_HEXCOLOR ||
value->unit == CSSPrimitiveValue::CSS_IDENT ||
(inQuirksMode() && value->unit == CSSPrimitiveValue::CSS_DIMENSION)) {
- if (!fastParseColor(c, value->string, inStrictMode() && value->unit == CSSPrimitiveValue::CSS_IDENT))
+ if (!fastParseColor(c, value->string, !inQuirksMode() && value->unit == CSSPrimitiveValue::CSS_IDENT))
return false;
} else if (value->unit == CSSParserValue::Function &&
value->function->args != 0 &&
@@ -6384,7 +6315,7 @@ struct ShadowParseContext {
values = CSSValueList::createCommaSeparated();
// Construct the current shadow value and add it to the list.
- values->append(ShadowValue::create(x.release(), y.release(), blur.release(), spread.release(), style.release(), color.release()));
+ values->append(CSSShadowValue::create(x.release(), y.release(), blur.release(), spread.release(), style.release(), color.release()));
}
// Now reset for the next shadow value.
@@ -6492,13 +6423,13 @@ PassRefPtr<CSSValueList> CSSParser::parseShadow(CSSParserValueList* valueList, C
return 0;
// The value is good. Commit it.
context.commitValue();
- } else if (validUnit(val, FLength, CSSStrictMode)) {
+ } else if (validUnit(val, FLength, HTMLStandardMode)) {
// We required a length and didn't get one. Invalid.
if (!context.allowLength())
return 0;
// Blur radius must be non-negative.
- if (context.allowBlur && !validUnit(val, FLength | FNonNeg, CSSStrictMode))
+ if (context.allowBlur && !validUnit(val, FLength | FNonNeg, HTMLStandardMode))
return 0;
// A length is allowed here. Construct the value and add it.
@@ -6579,7 +6510,8 @@ bool CSSParser::parseReflect(CSSPropertyID propId, bool important)
RefPtr<CSSValue> mask;
val = m_valueList->next();
if (val) {
- if (!parseBorderImage(propId, mask))
+ mask = parseBorderImage(propId);
+ if (!mask)
return false;
}
@@ -6729,11 +6661,20 @@ struct BorderImageParseContext {
m_allowImage = !m_image;
}
- PassRefPtr<CSSValue> commitWebKitBorderImage()
+ PassRefPtr<CSSValue> commitCSSValue()
{
return createBorderImageValue(m_image, m_imageSlice, m_borderSlice, m_outset, m_repeat);
}
+ void commitMaskBoxImage(CSSParser* parser, bool important)
+ {
+ commitBorderImageProperty(CSSPropertyWebkitMaskBoxImageSource, parser, m_image, important);
+ commitBorderImageProperty(CSSPropertyWebkitMaskBoxImageSlice, parser, m_imageSlice, important);
+ commitBorderImageProperty(CSSPropertyWebkitMaskBoxImageWidth, parser, m_borderSlice, important);
+ commitBorderImageProperty(CSSPropertyWebkitMaskBoxImageOutset, parser, m_outset, important);
+ commitBorderImageProperty(CSSPropertyWebkitMaskBoxImageRepeat, parser, m_repeat, important);
+ }
+
void commitBorderImage(CSSParser* parser, bool important)
{
commitBorderImageProperty(CSSPropertyBorderImageSource, parser, m_image, important);
@@ -6770,27 +6711,26 @@ struct BorderImageParseContext {
RefPtr<CSSValue> m_repeat;
};
-bool CSSParser::parseBorderImage(CSSPropertyID propId, RefPtr<CSSValue>& result, bool important)
+static bool buildBorderImageParseContext(CSSParser& parser, CSSPropertyID propId, BorderImageParseContext& context)
{
- ShorthandScope scope(this, propId);
- BorderImageParseContext context;
- while (CSSParserValue* val = m_valueList->current()) {
+ ShorthandScope scope(&parser, propId);
+ while (CSSParserValue* val = parser.m_valueList->current()) {
context.setCanAdvance(false);
if (!context.canAdvance() && context.allowForwardSlashOperator() && isForwardSlashOperator(val))
context.commitForwardSlashOperator();
if (!context.canAdvance() && context.allowImage()) {
- if (val->unit == CSSPrimitiveValue::CSS_URI)
- context.commitImage(CSSImageValue::create(completeURL(val->string)));
- else if (isGeneratedImageValue(val)) {
+ if (val->unit == CSSPrimitiveValue::CSS_URI) {
+ context.commitImage(CSSImageValue::create(parser.completeURL(parser.m_context, val->string)));
+ } else if (isGeneratedImageValue(val)) {
RefPtr<CSSValue> value;
- if (parseGeneratedImage(m_valueList.get(), value))
+ if (parser.parseGeneratedImage(parser.m_valueList.get(), value))
context.commitImage(value.release());
else
return false;
} else if (val->unit == CSSParserValue::Function && equalIgnoringCase(val->function->name, "-webkit-image-set(")) {
- RefPtr<CSSValue> value = parseImageSet(m_valueList.get());
+ RefPtr<CSSValue> value = parser.parseImageSet(parser.m_valueList.get());
if (value)
context.commitImage(value.release());
else
@@ -6801,46 +6741,65 @@ bool CSSParser::parseBorderImage(CSSPropertyID propId, RefPtr<CSSValue>& result,
if (!context.canAdvance() && context.allowImageSlice()) {
RefPtr<CSSBorderImageSliceValue> imageSlice;
- if (parseBorderImageSlice(propId, imageSlice))
+ if (parser.parseBorderImageSlice(propId, imageSlice))
context.commitImageSlice(imageSlice.release());
}
if (!context.canAdvance() && context.allowRepeat()) {
RefPtr<CSSValue> repeat;
- if (parseBorderImageRepeat(repeat))
+ if (parser.parseBorderImageRepeat(repeat))
context.commitRepeat(repeat.release());
}
if (!context.canAdvance() && context.requireWidth()) {
RefPtr<CSSPrimitiveValue> borderSlice;
- if (parseBorderImageWidth(borderSlice))
+ if (parser.parseBorderImageWidth(borderSlice))
context.commitBorderWidth(borderSlice.release());
}
if (!context.canAdvance() && context.requireOutset()) {
RefPtr<CSSPrimitiveValue> borderOutset;
- if (parseBorderImageOutset(borderOutset))
+ if (parser.parseBorderImageOutset(borderOutset))
context.commitBorderOutset(borderOutset.release());
}
if (!context.canAdvance())
return false;
- m_valueList->next();
+ parser.m_valueList->next();
}
- if (context.allowCommit()) {
- if (propId == CSSPropertyBorderImage)
+ return context.allowCommit();
+}
+
+bool CSSParser::parseBorderImageShorthand(CSSPropertyID propId, bool important)
+{
+ BorderImageParseContext context;
+ if (buildBorderImageParseContext(*this, propId, context)) {
+ switch (propId) {
+ case CSSPropertyWebkitMaskBoxImage:
+ context.commitMaskBoxImage(this, important);
+ return true;
+ case CSSPropertyBorderImage:
context.commitBorderImage(this, important);
- else
- // Need to fully commit as a single value.
- result = context.commitWebKitBorderImage();
- return true;
+ return true;
+ default:
+ ASSERT_NOT_REACHED();
+ return false;
+ }
}
-
return false;
}
+PassRefPtr<CSSValue> CSSParser::parseBorderImage(CSSPropertyID propId)
+{
+ BorderImageParseContext context;
+ if (buildBorderImageParseContext(*this, propId, context)) {
+ return context.commitCSSValue();
+ }
+ return 0;
+}
+
static bool isBorderImageRepeatKeyword(int id)
{
return id == CSSValueStretch || id == CSSValueRepeat || id == CSSValueSpace || id == CSSValueRound;
@@ -6961,7 +6920,7 @@ bool CSSParser::parseBorderImageSlice(CSSPropertyID propId, RefPtr<CSSBorderImag
CSSParserValue* val;
while ((val = m_valueList->current())) {
// FIXME calc() http://webkit.org/b/16662 : calc is parsed but values are not created yet.
- if (context.allowNumber() && !isCalculation(val) && validUnit(val, FInteger | FNonNeg | FPercent, CSSStrictMode)) {
+ if (context.allowNumber() && !isCalculation(val) && validUnit(val, FInteger | FNonNeg | FPercent, HTMLStandardMode)) {
context.commitNumber(val);
} else if (context.allowFill() && val->id == CSSValueFill)
context.commitFill();
@@ -7074,7 +7033,7 @@ bool CSSParser::parseBorderImageQuad(Units validUnits, RefPtr<CSSPrimitiveValue>
BorderImageQuadParseContext context(this);
CSSParserValue* val;
while ((val = m_valueList->current())) {
- if (context.allowNumber() && (validUnit(val, validUnits, CSSStrictMode) || val->id == CSSValueAuto)) {
+ if (context.allowNumber() && (validUnit(val, validUnits, HTMLStandardMode) || val->id == CSSValueAuto)) {
context.commitNumber(val);
} else if (!inShorthand()) {
// If we're not parsing a shorthand then we are invalid.
@@ -7097,12 +7056,12 @@ bool CSSParser::parseBorderImageQuad(Units validUnits, RefPtr<CSSPrimitiveValue>
bool CSSParser::parseBorderImageWidth(RefPtr<CSSPrimitiveValue>& result)
{
- return parseBorderImageQuad(FLength | FInteger | FNonNeg | FPercent, result);
+ return parseBorderImageQuad(FLength | FNumber | FNonNeg | FPercent, result);
}
bool CSSParser::parseBorderImageOutset(RefPtr<CSSPrimitiveValue>& result)
{
- return parseBorderImageQuad(FLength | FInteger | FNonNeg, result);
+ return parseBorderImageQuad(FLength | FNumber | FNonNeg, result);
}
static void completeBorderRadii(RefPtr<CSSPrimitiveValue> radii[4])
@@ -7396,7 +7355,7 @@ bool CSSParser::parseDeprecatedGradient(CSSParserValueList* valueList, RefPtr<CS
a = args->next();
if (!a || a->unit != CSSPrimitiveValue::CSS_NUMBER)
return false;
- static_cast<CSSRadialGradientValue*>(result.get())->setFirstRadius(createPrimitiveNumericValue(a));
+ toCSSRadialGradientValue(result.get())->setFirstRadius(createPrimitiveNumericValue(a));
// Comma after the first radius.
a = args->next();
@@ -7433,7 +7392,7 @@ bool CSSParser::parseDeprecatedGradient(CSSParserValueList* valueList, RefPtr<CS
a = args->next();
if (!a || a->unit != CSSPrimitiveValue::CSS_NUMBER)
return false;
- static_cast<CSSRadialGradientValue*>(result.get())->setSecondRadius(createPrimitiveNumericValue(a));
+ toCSSRadialGradientValue(result.get())->setSecondRadius(createPrimitiveNumericValue(a));
}
// We now will accept any number of stops (0 or more).
@@ -7506,7 +7465,7 @@ bool CSSParser::parseDeprecatedLinearGradient(CSSParserValueList* valueList, Ref
bool expectComma = false;
// Look for angle.
- if (validUnit(a, FAngle, CSSStrictMode)) {
+ if (validUnit(a, FAngle, HTMLStandardMode)) {
result->setAngle(createPrimitiveNumericValue(a));
args->next();
@@ -7691,7 +7650,7 @@ bool CSSParser::parseLinearGradient(CSSParserValueList* valueList, RefPtr<CSSVal
bool expectComma = false;
// Look for angle.
- if (validUnit(a, FAngle, CSSStrictMode)) {
+ if (validUnit(a, FAngle, HTMLStandardMode)) {
result->setAngle(createPrimitiveNumericValue(a));
args->next();
@@ -7910,24 +7869,6 @@ bool CSSParser::parseGradientColorStops(CSSParserValueList* valueList, CSSGradie
return gradient->stopCount() >= 2;
}
-bool CSSParser::isGeneratedImageValue(CSSParserValue* val) const
-{
- if (val->unit != CSSParserValue::Function)
- return false;
-
- return equalIgnoringCase(val->function->name, "-webkit-gradient(")
- || equalIgnoringCase(val->function->name, "-webkit-linear-gradient(")
- || equalIgnoringCase(val->function->name, "linear-gradient(")
- || equalIgnoringCase(val->function->name, "-webkit-repeating-linear-gradient(")
- || equalIgnoringCase(val->function->name, "repeating-linear-gradient(")
- || equalIgnoringCase(val->function->name, "-webkit-radial-gradient(")
- || equalIgnoringCase(val->function->name, "radial-gradient(")
- || equalIgnoringCase(val->function->name, "-webkit-repeating-radial-gradient(")
- || equalIgnoringCase(val->function->name, "repeating-radial-gradient(")
- || equalIgnoringCase(val->function->name, "-webkit-canvas(")
- || equalIgnoringCase(val->function->name, "-webkit-cross-fade(");
-}
-
bool CSSParser::parseGeneratedImage(CSSParserValueList* valueList, RefPtr<CSSValue>& value)
{
CSSParserValue* val = valueList->current();
@@ -8280,21 +8221,21 @@ PassRefPtr<CSSValue> CSSParser::parseTransformValue(CSSParserValue *value)
if (info.type() == CSSTransformValue::Rotate3DTransformOperation && argNumber == 3) {
// 4th param of rotate3d() is an angle rather than a bare number, validate it as such
- if (!validUnit(a, FAngle, CSSStrictMode))
+ if (!validUnit(a, FAngle, HTMLStandardMode))
return 0;
} else if (info.type() == CSSTransformValue::Translate3DTransformOperation && argNumber == 2) {
// 3rd param of translate3d() cannot be a percentage
- if (!validUnit(a, FLength, CSSStrictMode))
+ if (!validUnit(a, FLength, HTMLStandardMode))
return 0;
} else if (info.type() == CSSTransformValue::TranslateZTransformOperation && !argNumber) {
// 1st param of translateZ() cannot be a percentage
- if (!validUnit(a, FLength, CSSStrictMode))
+ if (!validUnit(a, FLength, HTMLStandardMode))
return 0;
} else if (info.type() == CSSTransformValue::PerspectiveTransformOperation && !argNumber) {
// 1st param of perspective() must be a non-negative number (deprecated) or length.
- if (!validUnit(a, FNumber | FLength | FNonNeg, CSSStrictMode))
+ if (!validUnit(a, FNumber | FLength | FNonNeg, HTMLStandardMode))
return 0;
- } else if (!validUnit(a, unit, CSSStrictMode))
+ } else if (!validUnit(a, unit, HTMLStandardMode))
return 0;
// Add the value to the current transform operation.
@@ -8380,7 +8321,7 @@ PassRefPtr<CSSArrayFunctionValue> CSSParser::parseCustomFilterArrayFunction(CSSP
while (true) {
// We parse pairs <Value, Comma> at each step.
CSSParserValue* currentParserValue = arrayArgsParserValueList->current();
- if (!currentParserValue || !validUnit(currentParserValue, FNumber, CSSStrictMode))
+ if (!currentParserValue || !validUnit(currentParserValue, FNumber, HTMLStandardMode))
return 0;
RefPtr<CSSValue> arrayValue = cssValuePool().createValue(currentParserValue->fValue, CSSPrimitiveValue::CSS_NUMBER);
@@ -8499,7 +8440,7 @@ PassRefPtr<CSSValueList> CSSParser::parseCustomFilterParameters(CSSParserValueLi
// If we hit a comma, it means that we finished this parameter's values.
if (isComma(arg))
break;
- if (!validUnit(arg, FNumber, CSSStrictMode))
+ if (!validUnit(arg, FNumber, HTMLStandardMode))
return 0;
paramValueList->append(cssValuePool().createValue(arg->fValue, CSSPrimitiveValue::CSS_NUMBER));
arg = argsList->next();
@@ -8624,7 +8565,7 @@ PassRefPtr<CSSFilterValue> CSSParser::parseCustomFilterFunctionWithInlineSyntax(
RefPtr<CSSValueList> meshSizeList = CSSValueList::createSpaceSeparated();
for (arg = argsList->current(); arg; arg = argsList->next()) {
- if (!validUnit(arg, FInteger | FNonNeg, CSSStrictMode))
+ if (!validUnit(arg, FInteger | FNonNeg, HTMLStandardMode))
break;
int integerValue = clampToInteger(arg->fValue);
// According to the specification we can only accept positive non-zero values.
@@ -8762,7 +8703,6 @@ StyleRuleBase* CSSParser::createFilterRule(const CSSParserString& filterName)
clearProperties();
StyleRuleFilter* result = rule.get();
m_parsedRules.append(rule.release());
- endRuleBody();
return result;
}
@@ -8785,7 +8725,7 @@ PassRefPtr<CSSFilterValue> CSSParser::parseBuiltinFilterArguments(CSSParserValue
if (args->size()) {
CSSParserValue* value = args->current();
- if (!validUnit(value, FNumber | FPercent | FNonNeg, CSSStrictMode))
+ if (!validUnit(value, FNumber | FPercent | FNonNeg, HTMLStandardMode))
return 0;
double amount = value->fValue;
@@ -8809,7 +8749,7 @@ PassRefPtr<CSSFilterValue> CSSParser::parseBuiltinFilterArguments(CSSParserValue
if (args->size()) {
CSSParserValue* value = args->current();
- if (!validUnit(value, FNumber | FPercent, CSSStrictMode))
+ if (!validUnit(value, FNumber | FPercent, HTMLStandardMode))
return 0;
filterValue->append(cssValuePool().createValue(value->fValue, static_cast<CSSPrimitiveValue::UnitTypes>(value->unit)));
@@ -8823,7 +8763,7 @@ PassRefPtr<CSSFilterValue> CSSParser::parseBuiltinFilterArguments(CSSParserValue
if (args->size()) {
CSSParserValue* argument = args->current();
- if (!validUnit(argument, FAngle, CSSStrictMode))
+ if (!validUnit(argument, FAngle, HTMLStandardMode))
return 0;
filterValue->append(createPrimitiveNumericValue(argument));
@@ -8837,7 +8777,7 @@ PassRefPtr<CSSFilterValue> CSSParser::parseBuiltinFilterArguments(CSSParserValue
if (args->size()) {
CSSParserValue* argument = args->current();
- if (!validUnit(argument, FLength | FNonNeg, CSSStrictMode))
+ if (!validUnit(argument, FLength | FNonNeg, HTMLStandardMode))
return 0;
filterValue->append(createPrimitiveNumericValue(argument));
@@ -8888,7 +8828,7 @@ PassRefPtr<CSSValueList> CSSParser::parseFilter()
if (filterType == CSSFilterValue::CustomFilterOperation) {
// Make sure parsing fails if custom filters are disabled.
- if (!m_context.isCSSCustomFilterEnabled)
+ if (!RuntimeEnabledFeatures::cssCustomFilterEnabled())
return 0;
RefPtr<CSSFilterValue> filterValue = parseCustomFilterFunction(value);
@@ -9073,6 +9013,49 @@ bool CSSParser::parsePerspectiveOrigin(CSSPropertyID propId, CSSPropertyID& prop
return value;
}
+bool CSSParser::parseTouchAction(bool important)
+{
+ if (!RuntimeEnabledFeatures::cssTouchActionEnabled())
+ return false;
+
+ CSSParserValue* value = m_valueList->current();
+ RefPtr<CSSValueList> list = CSSValueList::createSpaceSeparated();
+ if (m_valueList->size() == 1 && value && (value->id == CSSValueAuto || value->id == CSSValueNone)) {
+ list->append(cssValuePool().createIdentifierValue(value->id));
+ addProperty(CSSPropertyTouchAction, list.release(), important);
+ m_valueList->next();
+ return true;
+ }
+
+ bool isValid = true;
+ while (isValid && value) {
+ switch (value->id) {
+ case CSSValuePanX:
+ case CSSValuePanY: {
+ RefPtr<CSSValue> panValue = cssValuePool().createIdentifierValue(value->id);
+ if (list->hasValue(panValue.get())) {
+ isValid = false;
+ break;
+ }
+ list->append(panValue.release());
+ break;
+ }
+ default:
+ isValid = false;
+ break;
+ }
+ if (isValid)
+ value = m_valueList->next();
+ }
+
+ if (list->length() && isValid) {
+ addProperty(CSSPropertyTouchAction, list.release(), important);
+ return true;
+ }
+
+ return false;
+}
+
void CSSParser::addTextDecorationProperty(CSSPropertyID propId, PassRefPtr<CSSValue> value, bool important)
{
// The text-decoration-line property takes priority over text-decoration, unless the latter has important priority set.
@@ -9125,26 +9108,23 @@ bool CSSParser::parseTextDecoration(CSSPropertyID propId, bool important)
return false;
}
-#if ENABLE(CSS3_TEXT)
bool CSSParser::parseTextUnderlinePosition(bool important)
{
- // The text-underline-position property has sintax "auto | alphabetic | [ under || [ left | right ] ]".
- // However, values 'left' and 'right' are not implemented yet, so we will parse sintax
- // "auto | alphabetic | under" for now.
+ // The text-underline-position property has syntax "auto | [ under || [ left | right ] ]".
+ // However, values 'left' and 'right' are not implemented yet, so we will parse syntax
+ // "auto | under" for now.
CSSParserValue* value = m_valueList->current();
switch (value->id) {
case CSSValueAuto:
- case CSSValueAlphabetic:
case CSSValueUnder:
if (m_valueList->next())
return false;
-
- addProperty(CSSPropertyWebkitTextUnderlinePosition, cssValuePool().createIdentifierValue(value->id), important);
+ addProperty(CSSPropertyTextUnderlinePosition, cssValuePool().createIdentifierValue(value->id), important);
return true;
+ default:
+ return false;
}
- return false;
}
-#endif // CSS3_TEXT
bool CSSParser::parseTextEmphasisStyle(bool important)
{
@@ -9306,7 +9286,7 @@ bool CSSParser::parseFontFeatureTag(CSSValueList* settings)
return false;
}
- String tag = value->string;
+ AtomicString tag = value->string;
int tagValue = 1;
// Feature tag values could follow: <integer> | on | off
value = m_valueList->next();
@@ -9321,7 +9301,7 @@ bool CSSParser::parseFontFeatureTag(CSSValueList* settings)
m_valueList->next();
}
}
- settings->append(FontFeatureValue::create(tag, tagValue));
+ settings->append(CSSFontFeatureValue::create(tag, tagValue));
return true;
}
@@ -9396,7 +9376,7 @@ bool CSSParser::parseFontVariantLigatures(bool important)
return true;
}
-bool CSSParser::parseCalculation(CSSParserValue* value, CalculationPermittedValueRange range)
+bool CSSParser::parseCalculation(CSSParserValue* value, ValueRange range)
{
ASSERT(isCalculation(value));
@@ -9415,1500 +9395,32 @@ bool CSSParser::parseCalculation(CSSParserValue* value, CalculationPermittedValu
#define END_TOKEN 0
-#include "CSSGrammar.h"
-
-enum CharacterType {
- // Types for the main switch.
-
- // The first 4 types must be grouped together, as they
- // represent the allowed chars in an identifier.
- CharacterCaselessU,
- CharacterIdentifierStart,
- CharacterNumber,
- CharacterDash,
-
- CharacterOther,
- CharacterNull,
- CharacterWhiteSpace,
- CharacterEndMediaQueryOrSupports,
- CharacterEndNthChild,
- CharacterQuote,
- CharacterExclamationMark,
- CharacterHashmark,
- CharacterDollar,
- CharacterAsterisk,
- CharacterPlus,
- CharacterDot,
- CharacterSlash,
- CharacterLess,
- CharacterAt,
- CharacterBackSlash,
- CharacterXor,
- CharacterVerticalBar,
- CharacterTilde,
-};
-
-// 128 ASCII codes
-static const CharacterType typesOfASCIICharacters[128] = {
-/* 0 - Null */ CharacterNull,
-/* 1 - Start of Heading */ CharacterOther,
-/* 2 - Start of Text */ CharacterOther,
-/* 3 - End of Text */ CharacterOther,
-/* 4 - End of Transm. */ CharacterOther,
-/* 5 - Enquiry */ CharacterOther,
-/* 6 - Acknowledgment */ CharacterOther,
-/* 7 - Bell */ CharacterOther,
-/* 8 - Back Space */ CharacterOther,
-/* 9 - Horizontal Tab */ CharacterWhiteSpace,
-/* 10 - Line Feed */ CharacterWhiteSpace,
-/* 11 - Vertical Tab */ CharacterOther,
-/* 12 - Form Feed */ CharacterWhiteSpace,
-/* 13 - Carriage Return */ CharacterWhiteSpace,
-/* 14 - Shift Out */ CharacterOther,
-/* 15 - Shift In */ CharacterOther,
-/* 16 - Data Line Escape */ CharacterOther,
-/* 17 - Device Control 1 */ CharacterOther,
-/* 18 - Device Control 2 */ CharacterOther,
-/* 19 - Device Control 3 */ CharacterOther,
-/* 20 - Device Control 4 */ CharacterOther,
-/* 21 - Negative Ack. */ CharacterOther,
-/* 22 - Synchronous Idle */ CharacterOther,
-/* 23 - End of Transmit */ CharacterOther,
-/* 24 - Cancel */ CharacterOther,
-/* 25 - End of Medium */ CharacterOther,
-/* 26 - Substitute */ CharacterOther,
-/* 27 - Escape */ CharacterOther,
-/* 28 - File Separator */ CharacterOther,
-/* 29 - Group Separator */ CharacterOther,
-/* 30 - Record Separator */ CharacterOther,
-/* 31 - Unit Separator */ CharacterOther,
-/* 32 - Space */ CharacterWhiteSpace,
-/* 33 - ! */ CharacterExclamationMark,
-/* 34 - " */ CharacterQuote,
-/* 35 - # */ CharacterHashmark,
-/* 36 - $ */ CharacterDollar,
-/* 37 - % */ CharacterOther,
-/* 38 - & */ CharacterOther,
-/* 39 - ' */ CharacterQuote,
-/* 40 - ( */ CharacterOther,
-/* 41 - ) */ CharacterEndNthChild,
-/* 42 - * */ CharacterAsterisk,
-/* 43 - + */ CharacterPlus,
-/* 44 - , */ CharacterOther,
-/* 45 - - */ CharacterDash,
-/* 46 - . */ CharacterDot,
-/* 47 - / */ CharacterSlash,
-/* 48 - 0 */ CharacterNumber,
-/* 49 - 1 */ CharacterNumber,
-/* 50 - 2 */ CharacterNumber,
-/* 51 - 3 */ CharacterNumber,
-/* 52 - 4 */ CharacterNumber,
-/* 53 - 5 */ CharacterNumber,
-/* 54 - 6 */ CharacterNumber,
-/* 55 - 7 */ CharacterNumber,
-/* 56 - 8 */ CharacterNumber,
-/* 57 - 9 */ CharacterNumber,
-/* 58 - : */ CharacterOther,
-/* 59 - ; */ CharacterEndMediaQueryOrSupports,
-/* 60 - < */ CharacterLess,
-/* 61 - = */ CharacterOther,
-/* 62 - > */ CharacterOther,
-/* 63 - ? */ CharacterOther,
-/* 64 - @ */ CharacterAt,
-/* 65 - A */ CharacterIdentifierStart,
-/* 66 - B */ CharacterIdentifierStart,
-/* 67 - C */ CharacterIdentifierStart,
-/* 68 - D */ CharacterIdentifierStart,
-/* 69 - E */ CharacterIdentifierStart,
-/* 70 - F */ CharacterIdentifierStart,
-/* 71 - G */ CharacterIdentifierStart,
-/* 72 - H */ CharacterIdentifierStart,
-/* 73 - I */ CharacterIdentifierStart,
-/* 74 - J */ CharacterIdentifierStart,
-/* 75 - K */ CharacterIdentifierStart,
-/* 76 - L */ CharacterIdentifierStart,
-/* 77 - M */ CharacterIdentifierStart,
-/* 78 - N */ CharacterIdentifierStart,
-/* 79 - O */ CharacterIdentifierStart,
-/* 80 - P */ CharacterIdentifierStart,
-/* 81 - Q */ CharacterIdentifierStart,
-/* 82 - R */ CharacterIdentifierStart,
-/* 83 - S */ CharacterIdentifierStart,
-/* 84 - T */ CharacterIdentifierStart,
-/* 85 - U */ CharacterCaselessU,
-/* 86 - V */ CharacterIdentifierStart,
-/* 87 - W */ CharacterIdentifierStart,
-/* 88 - X */ CharacterIdentifierStart,
-/* 89 - Y */ CharacterIdentifierStart,
-/* 90 - Z */ CharacterIdentifierStart,
-/* 91 - [ */ CharacterOther,
-/* 92 - \ */ CharacterBackSlash,
-/* 93 - ] */ CharacterOther,
-/* 94 - ^ */ CharacterXor,
-/* 95 - _ */ CharacterIdentifierStart,
-/* 96 - ` */ CharacterOther,
-/* 97 - a */ CharacterIdentifierStart,
-/* 98 - b */ CharacterIdentifierStart,
-/* 99 - c */ CharacterIdentifierStart,
-/* 100 - d */ CharacterIdentifierStart,
-/* 101 - e */ CharacterIdentifierStart,
-/* 102 - f */ CharacterIdentifierStart,
-/* 103 - g */ CharacterIdentifierStart,
-/* 104 - h */ CharacterIdentifierStart,
-/* 105 - i */ CharacterIdentifierStart,
-/* 106 - j */ CharacterIdentifierStart,
-/* 107 - k */ CharacterIdentifierStart,
-/* 108 - l */ CharacterIdentifierStart,
-/* 109 - m */ CharacterIdentifierStart,
-/* 110 - n */ CharacterIdentifierStart,
-/* 111 - o */ CharacterIdentifierStart,
-/* 112 - p */ CharacterIdentifierStart,
-/* 113 - q */ CharacterIdentifierStart,
-/* 114 - r */ CharacterIdentifierStart,
-/* 115 - s */ CharacterIdentifierStart,
-/* 116 - t */ CharacterIdentifierStart,
-/* 117 - u */ CharacterCaselessU,
-/* 118 - v */ CharacterIdentifierStart,
-/* 119 - w */ CharacterIdentifierStart,
-/* 120 - x */ CharacterIdentifierStart,
-/* 121 - y */ CharacterIdentifierStart,
-/* 122 - z */ CharacterIdentifierStart,
-/* 123 - { */ CharacterEndMediaQueryOrSupports,
-/* 124 - | */ CharacterVerticalBar,
-/* 125 - } */ CharacterOther,
-/* 126 - ~ */ CharacterTilde,
-/* 127 - Delete */ CharacterOther,
-};
-
-// Utility functions for the CSS tokenizer.
-
-template <typename CharacterType>
-static inline bool isCSSLetter(CharacterType character)
-{
- return character >= 128 || typesOfASCIICharacters[character] <= CharacterDash;
-}
-
-template <typename CharacterType>
-static inline bool isCSSEscape(CharacterType character)
-{
- return character >= ' ' && character != 127;
-}
-
-template <typename CharacterType>
-static inline bool isURILetter(CharacterType character)
-{
- return (character >= '*' && character != 127) || (character >= '#' && character <= '&') || character == '!';
-}
-
-template <typename CharacterType>
-static inline bool isIdentifierStartAfterDash(CharacterType* currentCharacter)
-{
- return isASCIIAlpha(currentCharacter[0]) || currentCharacter[0] == '_' || currentCharacter[0] >= 128
- || (currentCharacter[0] == '\\' && isCSSEscape(currentCharacter[1]));
-}
-
-template <typename CharacterType>
-static inline bool isEqualToCSSIdentifier(CharacterType* cssString, const char* constantString)
-{
- // Compare an character memory data with a zero terminated string.
- do {
- // The input must be part of an identifier if constantChar or constString
- // contains '-'. Otherwise toASCIILowerUnchecked('\r') would be equal to '-'.
- ASSERT((*constantString >= 'a' && *constantString <= 'z') || *constantString == '-');
- ASSERT(*constantString != '-' || isCSSLetter(*cssString));
- if (toASCIILowerUnchecked(*cssString++) != (*constantString++))
- return false;
- } while (*constantString);
- return true;
-}
-
-template <typename CharacterType>
-static inline bool isEqualToCSSCaseSensitiveIdentifier(CharacterType* string, const char* constantString)
-{
- ASSERT(*constantString);
-
- do {
- if (*string++ != *constantString++)
- return false;
- } while (*constantString);
- return true;
-}
-
-template <typename CharacterType>
-static CharacterType* checkAndSkipEscape(CharacterType* currentCharacter)
-{
- // Returns with 0, if escape check is failed. Otherwise
- // it returns with the following character.
- ASSERT(*currentCharacter == '\\');
-
- ++currentCharacter;
- if (!isCSSEscape(*currentCharacter))
- return 0;
-
- if (isASCIIHexDigit(*currentCharacter)) {
- int length = 6;
-
- do {
- ++currentCharacter;
- } while (isASCIIHexDigit(*currentCharacter) && --length);
-
- // Optional space after the escape sequence.
- if (isHTMLSpace<CharacterType>(*currentCharacter))
- ++currentCharacter;
- return currentCharacter;
- }
- return currentCharacter + 1;
-}
-
-template <typename CharacterType>
-static inline CharacterType* skipWhiteSpace(CharacterType* currentCharacter)
-{
- while (isHTMLSpace<CharacterType>(*currentCharacter))
- ++currentCharacter;
- return currentCharacter;
-}
-
-// Main CSS tokenizer functions.
-
-template <>
-const LChar* CSSParserString::characters<LChar>() const { return characters8(); }
-
-template <>
-const UChar* CSSParserString::characters<UChar>() const { return characters16(); }
-
-template <>
-inline LChar*& CSSParser::currentCharacter<LChar>()
-{
- return m_currentCharacter8;
-}
-
-template <>
-inline UChar*& CSSParser::currentCharacter<UChar>()
-{
- return m_currentCharacter16;
-}
-
-UChar*& CSSParser::currentCharacter16()
-{
- if (!m_currentCharacter16) {
- m_dataStart16 = adoptArrayPtr(new UChar[m_length]);
- m_currentCharacter16 = m_dataStart16.get();
- }
-
- return m_currentCharacter16;
-}
-
-template <>
-inline LChar* CSSParser::tokenStart<LChar>()
-{
- return m_tokenStart.ptr8;
-}
-
-template <>
-inline UChar* CSSParser::tokenStart<UChar>()
-{
- return m_tokenStart.ptr16;
-}
-
-template <>
-inline LChar* CSSParser::dataStart<LChar>()
-{
- return m_dataStart8.get();
-}
-
-template <>
-inline UChar* CSSParser::dataStart<UChar>()
-{
- return m_dataStart16.get();
-}
-
void CSSParser::ensureLineEndings()
{
if (!m_lineEndings)
m_lineEndings = lineEndings(*m_source);
}
-template <typename CharacterType>
-inline CSSParserLocation CSSParser::tokenLocation()
-{
- CSSParserLocation location;
- location.token.init(tokenStart<CharacterType>(), currentCharacter<CharacterType>() - tokenStart<CharacterType>());
- location.lineNumber = m_tokenStartLineNumber;
- location.offset = tokenStart<CharacterType>() - dataStart<CharacterType>();
- return location;
-}
-
-CSSParserLocation CSSParser::currentLocation()
-{
- if (is8BitSource())
- return tokenLocation<LChar>();
- else
- return tokenLocation<UChar>();
-}
-
-template <typename CharacterType>
-inline bool CSSParser::isIdentifierStart()
-{
- // Check whether an identifier is started.
- return isIdentifierStartAfterDash((*currentCharacter<CharacterType>() != '-') ? currentCharacter<CharacterType>() : currentCharacter<CharacterType>() + 1);
-}
-
-template <typename CharacterType>
-static inline CharacterType* checkAndSkipString(CharacterType* currentCharacter, int quote)
-{
- // Returns with 0, if string check is failed. Otherwise
- // it returns with the following character. This is necessary
- // since we cannot revert escape sequences, thus strings
- // must be validated before parsing.
- while (true) {
- if (UNLIKELY(*currentCharacter == quote)) {
- // String parsing is successful.
- return currentCharacter + 1;
- }
- if (UNLIKELY(!*currentCharacter)) {
- // String parsing is successful up to end of input.
- return currentCharacter;
- }
- if (UNLIKELY(*currentCharacter <= '\r' && (*currentCharacter == '\n' || (*currentCharacter | 0x1) == '\r'))) {
- // String parsing is failed for character '\n', '\f' or '\r'.
- return 0;
- }
-
- if (LIKELY(currentCharacter[0] != '\\'))
- ++currentCharacter;
- else if (currentCharacter[1] == '\n' || currentCharacter[1] == '\f')
- currentCharacter += 2;
- else if (currentCharacter[1] == '\r')
- currentCharacter += currentCharacter[2] == '\n' ? 3 : 2;
- else {
- currentCharacter = checkAndSkipEscape(currentCharacter);
- if (!currentCharacter)
- return 0;
- }
- }
-}
-
-template <typename CharacterType>
-unsigned CSSParser::parseEscape(CharacterType*& src)
-{
- ASSERT(*src == '\\' && isCSSEscape(src[1]));
-
- unsigned unicode = 0;
-
- ++src;
- if (isASCIIHexDigit(*src)) {
-
- int length = 6;
-
- do {
- unicode = (unicode << 4) + toASCIIHexValue(*src++);
- } while (--length && isASCIIHexDigit(*src));
-
- // Characters above 0x10ffff are not handled.
- if (unicode > 0x10ffff)
- unicode = 0xfffd;
-
- // Optional space after the escape sequence.
- if (isHTMLSpace<CharacterType>(*src))
- ++src;
-
- return unicode;
- }
-
- return *currentCharacter<CharacterType>()++;
-}
-
-template <>
-inline void CSSParser::UnicodeToChars<LChar>(LChar*& result, unsigned unicode)
-{
- ASSERT(unicode <= 0xff);
- *result = unicode;
-
- ++result;
-}
-
-template <>
-inline void CSSParser::UnicodeToChars<UChar>(UChar*& result, unsigned unicode)
-{
- // Replace unicode with a surrogate pairs when it is bigger than 0xffff
- if (U16_LENGTH(unicode) == 2) {
- *result++ = U16_LEAD(unicode);
- *result = U16_TRAIL(unicode);
- } else
- *result = unicode;
-
- ++result;
-}
-
-template <typename SrcCharacterType, typename DestCharacterType>
-inline bool CSSParser::parseIdentifierInternal(SrcCharacterType*& src, DestCharacterType*& result, bool& hasEscape)
-{
- hasEscape = false;
- do {
- if (LIKELY(*src != '\\'))
- *result++ = *src++;
- else {
- hasEscape = true;
- SrcCharacterType* savedEscapeStart = src;
- unsigned unicode = parseEscape<SrcCharacterType>(src);
- if (unicode > 0xff && sizeof(DestCharacterType) == 1) {
- src = savedEscapeStart;
- return false;
- }
- UnicodeToChars(result, unicode);
- }
- } while (isCSSLetter(src[0]) || (src[0] == '\\' && isCSSEscape(src[1])));
-
- return true;
-}
-
-template <typename CharacterType>
-inline void CSSParser::parseIdentifier(CharacterType*& result, CSSParserString& resultString, bool& hasEscape)
-{
- // If a valid identifier start is found, we can safely
- // parse the identifier until the next invalid character.
- ASSERT(isIdentifierStart<CharacterType>());
-
- CharacterType* start = currentCharacter<CharacterType>();
- if (UNLIKELY(!parseIdentifierInternal(currentCharacter<CharacterType>(), result, hasEscape))) {
- // Found an escape we couldn't handle with 8 bits, copy what has been recognized and continue
- ASSERT(is8BitSource());
- UChar*& result16 = currentCharacter16();
- UChar* start16 = result16;
- int i = 0;
- for (; i < result - start; i++)
- result16[i] = start[i];
-
- result16 += i;
-
- parseIdentifierInternal(currentCharacter<CharacterType>(), result16, hasEscape);
-
- resultString.init(start16, result16 - start16);
-
- return;
- }
-
- resultString.init(start, result - start);
-}
-
-template <typename SrcCharacterType, typename DestCharacterType>
-inline bool CSSParser::parseStringInternal(SrcCharacterType*& src, DestCharacterType*& result, UChar quote)
-{
- while (true) {
- if (UNLIKELY(*src == quote)) {
- // String parsing is done.
- ++src;
- return true;
- }
- if (UNLIKELY(!*src)) {
- // String parsing is done, but don't advance pointer if at the end of input.
- return true;
- }
- ASSERT(*src > '\r' || (*src < '\n' && *src) || *src == '\v');
-
- if (LIKELY(src[0] != '\\'))
- *result++ = *src++;
- else if (src[1] == '\n' || src[1] == '\f')
- src += 2;
- else if (src[1] == '\r')
- src += src[2] == '\n' ? 3 : 2;
- else {
- SrcCharacterType* savedEscapeStart = src;
- unsigned unicode = parseEscape<SrcCharacterType>(src);
- if (unicode > 0xff && sizeof(DestCharacterType) == 1) {
- src = savedEscapeStart;
- return false;
- }
- UnicodeToChars(result, unicode);
- }
- }
-
- return true;
-}
-
-template <typename CharacterType>
-inline void CSSParser::parseString(CharacterType*& result, CSSParserString& resultString, UChar quote)
-{
- CharacterType* start = currentCharacter<CharacterType>();
-
- if (UNLIKELY(!parseStringInternal(currentCharacter<CharacterType>(), result, quote))) {
- // Found an escape we couldn't handle with 8 bits, copy what has been recognized and continue
- ASSERT(is8BitSource());
- UChar*& result16 = currentCharacter16();
- UChar* start16 = result16;
- int i = 0;
- for (; i < result - start; i++)
- result16[i] = start[i];
-
- result16 += i;
-
- parseStringInternal(currentCharacter<CharacterType>(), result16, quote);
-
- resultString.init(start16, result16 - start16);
- return;
- }
-
- resultString.init(start, result - start);
-}
-
-template <typename CharacterType>
-inline bool CSSParser::findURI(CharacterType*& start, CharacterType*& end, UChar& quote)
-{
- start = skipWhiteSpace(currentCharacter<CharacterType>());
-
- if (*start == '"' || *start == '\'') {
- quote = *start++;
- end = checkAndSkipString(start, quote);
- if (!end)
- return false;
- } else {
- quote = 0;
- end = start;
- while (isURILetter(*end)) {
- if (LIKELY(*end != '\\'))
- ++end;
- else {
- end = checkAndSkipEscape(end);
- if (!end)
- return false;
- }
- }
- }
-
- end = skipWhiteSpace(end);
- if (*end != ')')
- return false;
-
- return true;
-}
-
-template <typename SrcCharacterType, typename DestCharacterType>
-inline bool CSSParser::parseURIInternal(SrcCharacterType*& src, DestCharacterType*& dest, UChar quote)
-{
- if (quote) {
- ASSERT(quote == '"' || quote == '\'');
- return parseStringInternal(src, dest, quote);
- }
-
- while (isURILetter(*src)) {
- if (LIKELY(*src != '\\'))
- *dest++ = *src++;
- else {
- unsigned unicode = parseEscape<SrcCharacterType>(src);
- if (unicode > 0xff && sizeof(SrcCharacterType) == 1)
- return false;
- UnicodeToChars(dest, unicode);
- }
- }
-
- return true;
-}
-
-template <typename CharacterType>
-inline void CSSParser::parseURI(CSSParserString& string)
-{
- CharacterType* uriStart;
- CharacterType* uriEnd;
- UChar quote;
- if (!findURI(uriStart, uriEnd, quote))
- return;
-
- CharacterType* dest = currentCharacter<CharacterType>() = uriStart;
- if (LIKELY(parseURIInternal(currentCharacter<CharacterType>(), dest, quote)))
- string.init(uriStart, dest - uriStart);
- else {
- // An escape sequence was encountered that can't be stored in 8 bits.
- // Reset the current character to the start of the URI and re-parse with
- // a 16-bit destination.
- ASSERT(is8BitSource());
- UChar* uriStart16 = currentCharacter16();
- currentCharacter<CharacterType>() = uriStart;
- bool result = parseURIInternal(currentCharacter<CharacterType>(), currentCharacter16(), quote);
- ASSERT_UNUSED(result, result);
- string.init(uriStart16, currentCharacter16() - uriStart16);
- }
-
- currentCharacter<CharacterType>() = uriEnd + 1;
- m_token = URI;
-}
-
-template <typename CharacterType>
-inline bool CSSParser::parseUnicodeRange()
-{
- CharacterType* character = currentCharacter<CharacterType>() + 1;
- int length = 6;
- ASSERT(*currentCharacter<CharacterType>() == '+');
-
- while (isASCIIHexDigit(*character) && length) {
- ++character;
- --length;
- }
-
- if (length && *character == '?') {
- // At most 5 hex digit followed by a question mark.
- do {
- ++character;
- --length;
- } while (*character == '?' && length);
- currentCharacter<CharacterType>() = character;
- return true;
- }
-
- if (length < 6) {
- // At least one hex digit.
- if (character[0] == '-' && isASCIIHexDigit(character[1])) {
- // Followed by a dash and a hex digit.
- ++character;
- length = 6;
- do {
- ++character;
- } while (--length && isASCIIHexDigit(*character));
- }
- currentCharacter<CharacterType>() = character;
- return true;
- }
- return false;
-}
-
-template <typename CharacterType>
-bool CSSParser::parseNthChild()
-{
- CharacterType* character = currentCharacter<CharacterType>();
-
- while (isASCIIDigit(*character))
- ++character;
- if (isASCIIAlphaCaselessEqual(*character, 'n')) {
- currentCharacter<CharacterType>() = character + 1;
- return true;
- }
- return false;
-}
-
-template <typename CharacterType>
-bool CSSParser::parseNthChildExtra()
-{
- CharacterType* character = skipWhiteSpace(currentCharacter<CharacterType>());
- if (*character != '+' && *character != '-')
- return false;
-
- character = skipWhiteSpace(character + 1);
- if (!isASCIIDigit(*character))
- return false;
-
- do {
- ++character;
- } while (isASCIIDigit(*character));
-
- currentCharacter<CharacterType>() = character;
- return true;
-}
-
-template <typename CharacterType>
-inline bool CSSParser::detectFunctionTypeToken(int length)
-{
- ASSERT(length > 0);
- CharacterType* name = tokenStart<CharacterType>();
- SWITCH(name, length) {
- CASE("not") {
- m_token = NOTFUNCTION;
- return true;
- }
- CASE("url") {
- m_token = URI;
- return true;
- }
- CASE("cue") {
- m_token = CUEFUNCTION;
- return true;
- }
- CASE("var") {
- if (!RuntimeEnabledFeatures::cssVariablesEnabled())
- return false;
- m_token = VARFUNCTION;
- return true;
- }
- CASE("calc") {
- m_token = CALCFUNCTION;
- return true;
- }
- CASE("host") {
- m_token = HOSTFUNCTION;
- return true;
- }
- CASE("nth-child") {
- m_parsingMode = NthChildMode;
- return true;
- }
- CASE("nth-of-type") {
- m_parsingMode = NthChildMode;
- return true;
- }
- CASE("nth-last-child") {
- m_parsingMode = NthChildMode;
- return true;
- }
- CASE("nth-last-of-type") {
- m_parsingMode = NthChildMode;
- return true;
- }
- CASE("part") {
- m_token = PARTFUNCTION;
- return true;
- }
- }
- return false;
-}
-
-template <typename CharacterType>
-inline void CSSParser::detectMediaQueryToken(int length)
-{
- ASSERT(m_parsingMode == MediaQueryMode);
- CharacterType* name = tokenStart<CharacterType>();
-
- SWITCH(name, length) {
- CASE("and") {
- m_token = MEDIA_AND;
- }
- CASE("not") {
- m_token = MEDIA_NOT;
- }
- CASE("only") {
- m_token = MEDIA_ONLY;
- }
- }
-}
-
-template <typename CharacterType>
-inline void CSSParser::detectNumberToken(CharacterType* type, int length)
-{
- ASSERT(length > 0);
-
- SWITCH(type, length) {
- CASE("cm") {
- m_token = CMS;
- }
- CASE("ch") {
- m_token = CHS;
- }
- CASE("deg") {
- m_token = DEGS;
- }
- CASE("dppx") {
- // There is a discussion about the name of this unit on www-style.
- // Keep this compile time guard in place until that is resolved.
- // http://lists.w3.org/Archives/Public/www-style/2012May/0915.html
- m_token = DPPX;
- }
- CASE("dpcm") {
- m_token = DPCM;
- }
- CASE("dpi") {
- m_token = DPI;
- }
- CASE("em") {
- m_token = EMS;
- }
- CASE("ex") {
- m_token = EXS;
- }
- CASE("fr") {
- m_token = FR;
- }
- CASE("grad") {
- m_token = GRADS;
- }
- CASE("hz") {
- m_token = HERTZ;
- }
- CASE("in") {
- m_token = INS;
- }
- CASE("khz") {
- m_token = KHERTZ;
- }
- CASE("mm") {
- m_token = MMS;
- }
- CASE("ms") {
- m_token = MSECS;
- }
- CASE("px") {
- m_token = PXS;
- }
- CASE("pt") {
- m_token = PTS;
- }
- CASE("pc") {
- m_token = PCS;
- }
- CASE("rad") {
- m_token = RADS;
- }
- CASE("rem") {
- m_token = REMS;
- }
- CASE("s") {
- m_token = SECS;
- }
- CASE("turn") {
- m_token = TURNS;
- }
- CASE("vw") {
- m_token = VW;
- }
- CASE("vh") {
- m_token = VH;
- }
- CASE("vmin") {
- m_token = VMIN;
- }
- CASE("vmax") {
- m_token = VMAX;
- }
- CASE("__qem") {
- m_token = QEMS;
- }
- }
-}
-
-template <typename CharacterType>
-inline void CSSParser::detectDashToken(int length)
-{
- CharacterType* name = tokenStart<CharacterType>();
-
- // Ignore leading dash.
- ++name;
- --length;
-
- SWITCH(name, length) {
- CASE("webkit-any") {
- m_token = ANYFUNCTION;
- }
- CASE("webkit-min") {
- m_token = MINFUNCTION;
- }
- CASE("webkit-max") {
- m_token = MAXFUNCTION;
- }
- CASE("webkit-calc") {
- m_token = CALCFUNCTION;
- }
- CASE("webkit-distributed") {
- m_token = DISTRIBUTEDFUNCTION;
- }
- }
-}
-
-template <typename CharacterType>
-inline void CSSParser::detectAtToken(int length, bool hasEscape)
-{
- CharacterType* name = tokenStart<CharacterType>();
- ASSERT(name[0] == '@' && length >= 2);
-
- // Ignore leading @.
- ++name;
- --length;
-
- // charset, font-face, import, media, namespace, page, supports,
- // -webkit-keyframes, keyframes, and -webkit-mediaquery are not affected by hasEscape.
- SWITCH(name, length) {
- CASE("bottom-left") {
- if (LIKELY(!hasEscape))
- m_token = BOTTOMLEFT_SYM;
- }
- CASE("bottom-right") {
- if (LIKELY(!hasEscape))
- m_token = BOTTOMRIGHT_SYM;
- }
- CASE("bottom-center") {
- if (LIKELY(!hasEscape))
- m_token = BOTTOMCENTER_SYM;
- }
- CASE("bottom-left-corner") {
- if (LIKELY(!hasEscape))
- m_token = BOTTOMLEFTCORNER_SYM;
- }
- CASE("bottom-right-corner") {
- if (LIKELY(!hasEscape))
- m_token = BOTTOMRIGHTCORNER_SYM;
- }
- CASE("charset") {
- if (name - 1 == dataStart<CharacterType>())
- m_token = CHARSET_SYM;
- }
- CASE("font-face") {
- m_token = FONT_FACE_SYM;
- }
- CASE("host") {
- m_token = HOST_SYM;
- }
- CASE("import") {
- m_parsingMode = MediaQueryMode;
- m_token = IMPORT_SYM;
- }
- CASE("keyframes") {
- if (RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled())
- m_token = KEYFRAMES_SYM;
- }
- CASE("left-top") {
- if (LIKELY(!hasEscape))
- m_token = LEFTTOP_SYM;
- }
- CASE("left-middle") {
- if (LIKELY(!hasEscape))
- m_token = LEFTMIDDLE_SYM;
- }
- CASE("left-bottom") {
- if (LIKELY(!hasEscape))
- m_token = LEFTBOTTOM_SYM;
- }
- CASE("media") {
- m_parsingMode = MediaQueryMode;
- m_token = MEDIA_SYM;
- }
- CASE("namespace") {
- m_token = NAMESPACE_SYM;
- }
- CASE("page") {
- m_token = PAGE_SYM;
- }
- CASE("right-top") {
- if (LIKELY(!hasEscape))
- m_token = RIGHTTOP_SYM;
- }
- CASE("right-middle") {
- if (LIKELY(!hasEscape))
- m_token = RIGHTMIDDLE_SYM;
- }
- CASE("right-bottom") {
- if (LIKELY(!hasEscape))
- m_token = RIGHTBOTTOM_SYM;
- }
- CASE("supports") {
- m_parsingMode = SupportsMode;
- m_token = SUPPORTS_SYM;
- }
- CASE("top-left") {
- if (LIKELY(!hasEscape))
- m_token = TOPLEFT_SYM;
- }
- CASE("top-right") {
- if (LIKELY(!hasEscape))
- m_token = TOPRIGHT_SYM;
- }
- CASE("top-center") {
- if (LIKELY(!hasEscape))
- m_token = TOPCENTER_SYM;
- }
- CASE("top-left-corner") {
- if (LIKELY(!hasEscape))
- m_token = TOPLEFTCORNER_SYM;
- }
- CASE("top-right-corner") {
- if (LIKELY(!hasEscape))
- m_token = TOPRIGHTCORNER_SYM;
- }
- CASE("viewport") {
- m_token = VIEWPORT_RULE_SYM;
- }
- CASE("-internal-rule") {
- if (LIKELY(!hasEscape))
- m_token = INTERNAL_RULE_SYM;
- }
- CASE("-webkit-region") {
- if (LIKELY(!hasEscape))
- m_token = WEBKIT_REGION_RULE_SYM;
- }
- CASE("-webkit-filter") {
- if (LIKELY(!hasEscape))
- m_token = WEBKIT_FILTER_RULE_SYM;
- }
- CASE("-internal-decls") {
- if (LIKELY(!hasEscape))
- m_token = INTERNAL_DECLS_SYM;
- }
- CASE("-internal-value") {
- if (LIKELY(!hasEscape))
- m_token = INTERNAL_VALUE_SYM;
- }
- CASE("-webkit-keyframes") {
- m_token = WEBKIT_KEYFRAMES_SYM;
- }
- CASE("-internal-selector") {
- if (LIKELY(!hasEscape))
- m_token = INTERNAL_SELECTOR_SYM;
- }
- CASE("-internal-medialist") {
- m_parsingMode = MediaQueryMode;
- m_token = INTERNAL_MEDIALIST_SYM;
- }
- CASE("-internal-keyframe-rule") {
- if (LIKELY(!hasEscape))
- m_token = INTERNAL_KEYFRAME_RULE_SYM;
- }
- CASE("-internal-keyframe-key-list") {
- m_token = INTERNAL_KEYFRAME_KEY_LIST_SYM;
- }
- CASE("-internal-supports-condition") {
- m_parsingMode = SupportsMode;
- m_token = INTERNAL_SUPPORTS_CONDITION_SYM;
- }
- }
-}
-
-template <typename CharacterType>
-inline void CSSParser::detectSupportsToken(int length)
-{
- ASSERT(m_parsingMode == SupportsMode);
- CharacterType* name = tokenStart<CharacterType>();
-
- SWITCH(name, length) {
- CASE("or") {
- m_token = SUPPORTS_OR;
- }
- CASE("and") {
- m_token = SUPPORTS_AND;
- }
- CASE("not") {
- m_token = SUPPORTS_NOT;
- }
- }
-}
-
-template <typename CharacterType>
-inline void CSSParser::detectCSSVariableDefinitionToken(int length)
-{
- static const unsigned prefixLength = sizeof("var-") - 1;
- if (length <= prefixLength)
- return;
- CharacterType* name = tokenStart<CharacterType>();
- COMPILE_ASSERT(prefixLength > 0, CSS_variable_prefix_must_be_nonempty);
- if (name[prefixLength - 1] == '-' && isIdentifierStartAfterDash(name + prefixLength) && isEqualToCSSCaseSensitiveIdentifier(name, "var"))
- m_token = VAR_DEFINITION;
-}
-
-template <typename SrcCharacterType>
-int CSSParser::realLex(void* yylvalWithoutType)
-{
- YYSTYPE* yylval = static_cast<YYSTYPE*>(yylvalWithoutType);
- // Write pointer for the next character.
- SrcCharacterType* result;
- CSSParserString resultString;
- bool hasEscape;
-
- // The input buffer is terminated by a \0 character, so
- // it is safe to read one character ahead of a known non-null.
-#ifndef NDEBUG
- // In debug we check with an ASSERT that the length is > 0 for string types.
- yylval->string.clear();
-#endif
-
-restartAfterComment:
- result = currentCharacter<SrcCharacterType>();
- setTokenStart(result);
- m_tokenStartLineNumber = m_lineNumber;
- m_token = *currentCharacter<SrcCharacterType>();
- ++currentCharacter<SrcCharacterType>();
-
- switch ((m_token <= 127) ? typesOfASCIICharacters[m_token] : CharacterIdentifierStart) {
- case CharacterCaselessU:
- if (UNLIKELY(*currentCharacter<SrcCharacterType>() == '+'))
- if (parseUnicodeRange<SrcCharacterType>()) {
- m_token = UNICODERANGE;
- yylval->string.init(tokenStart<SrcCharacterType>(), currentCharacter<SrcCharacterType>() - tokenStart<SrcCharacterType>());
- break;
- }
- // Fall through to CharacterIdentifierStart.
-
- case CharacterIdentifierStart:
- --currentCharacter<SrcCharacterType>();
- parseIdentifier(result, yylval->string, hasEscape);
- m_token = IDENT;
-
- if (UNLIKELY(*currentCharacter<SrcCharacterType>() == '(')) {
- if (m_parsingMode == SupportsMode && !hasEscape) {
- detectSupportsToken<SrcCharacterType>(result - tokenStart<SrcCharacterType>());
- if (m_token != IDENT)
- break;
- }
-
- m_token = FUNCTION;
- if (!hasEscape)
- detectFunctionTypeToken<SrcCharacterType>(result - tokenStart<SrcCharacterType>());
-
- // Skip parenthesis
- ++currentCharacter<SrcCharacterType>();
- ++result;
- ++yylval->string.m_length;
-
- if (token() == URI) {
- m_token = FUNCTION;
- // Check whether it is really an URI.
- if (yylval->string.is8Bit())
- parseURI<LChar>(yylval->string);
- else
- parseURI<UChar>(yylval->string);
- }
- } else if (UNLIKELY(m_parsingMode != NormalMode) && !hasEscape) {
- if (m_parsingMode == MediaQueryMode)
- detectMediaQueryToken<SrcCharacterType>(result - tokenStart<SrcCharacterType>());
- else if (m_parsingMode == SupportsMode)
- detectSupportsToken<SrcCharacterType>(result - tokenStart<SrcCharacterType>());
- else if (m_parsingMode == NthChildMode && isASCIIAlphaCaselessEqual(tokenStart<SrcCharacterType>()[0], 'n')) {
- if (result - tokenStart<SrcCharacterType>() == 1) {
- // String "n" is IDENT but "n+1" is NTH.
- if (parseNthChildExtra<SrcCharacterType>()) {
- m_token = NTH;
- yylval->string.m_length = currentCharacter<SrcCharacterType>() - tokenStart<SrcCharacterType>();
- }
- } else if (result - tokenStart<SrcCharacterType>() >= 2 && tokenStart<SrcCharacterType>()[1] == '-') {
- // String "n-" is IDENT but "n-1" is NTH.
- // Set currentCharacter to '-' to continue parsing.
- SrcCharacterType* nextCharacter = result;
- currentCharacter<SrcCharacterType>() = tokenStart<SrcCharacterType>() + 1;
- if (parseNthChildExtra<SrcCharacterType>()) {
- m_token = NTH;
- yylval->string.setLength(currentCharacter<SrcCharacterType>() - tokenStart<SrcCharacterType>());
- } else {
- // Revert the change to currentCharacter if unsuccessful.
- currentCharacter<SrcCharacterType>() = nextCharacter;
- }
- }
- }
- } else if (UNLIKELY(RuntimeEnabledFeatures::cssVariablesEnabled())) {
- detectCSSVariableDefinitionToken<SrcCharacterType>(result - tokenStart<SrcCharacterType>());
- }
- break;
-
- case CharacterDot:
- if (!isASCIIDigit(currentCharacter<SrcCharacterType>()[0]))
- break;
- // Fall through to CharacterNumber.
-
- case CharacterNumber: {
- bool dotSeen = (m_token == '.');
-
- while (true) {
- if (!isASCIIDigit(currentCharacter<SrcCharacterType>()[0])) {
- // Only one dot is allowed for a number,
- // and it must be followed by a digit.
- if (currentCharacter<SrcCharacterType>()[0] != '.' || dotSeen || !isASCIIDigit(currentCharacter<SrcCharacterType>()[1]))
- break;
- dotSeen = true;
- }
- ++currentCharacter<SrcCharacterType>();
- }
-
- if (UNLIKELY(m_parsingMode == NthChildMode) && !dotSeen && isASCIIAlphaCaselessEqual(*currentCharacter<SrcCharacterType>(), 'n')) {
- // "[0-9]+n" is always an NthChild.
- ++currentCharacter<SrcCharacterType>();
- parseNthChildExtra<SrcCharacterType>();
- m_token = NTH;
- yylval->string.init(tokenStart<SrcCharacterType>(), currentCharacter<SrcCharacterType>() - tokenStart<SrcCharacterType>());
- break;
- }
-
- // Use SVG parser for numbers on SVG presentation attributes.
- if (m_context.mode == SVGAttributeMode) {
- // We need to take care of units like 'em' or 'ex'.
- SrcCharacterType* character = currentCharacter<SrcCharacterType>();
- if (isASCIIAlphaCaselessEqual(*character, 'e')) {
- ASSERT(character - tokenStart<SrcCharacterType>() > 0);
- ++character;
- if (*character == '-' || *character == '+' || isASCIIDigit(*character)) {
- ++character;
- while (isASCIIDigit(*character))
- ++character;
- // Use FLOATTOKEN if the string contains exponents.
- dotSeen = true;
- currentCharacter<SrcCharacterType>() = character;
- }
- }
- if (!parseSVGNumber(tokenStart<SrcCharacterType>(), character - tokenStart<SrcCharacterType>(), yylval->number))
- break;
- } else {
- yylval->number = charactersToDouble(tokenStart<SrcCharacterType>(), currentCharacter<SrcCharacterType>() - tokenStart<SrcCharacterType>());
- }
-
- // Type of the function.
- if (isIdentifierStart<SrcCharacterType>()) {
- SrcCharacterType* type = currentCharacter<SrcCharacterType>();
- result = currentCharacter<SrcCharacterType>();
-
- parseIdentifier(result, resultString, hasEscape);
-
- m_token = DIMEN;
- if (!hasEscape)
- detectNumberToken(type, currentCharacter<SrcCharacterType>() - type);
-
- if (m_token == DIMEN) {
- // The decoded number is overwritten, but this is intentional.
- yylval->string.init(tokenStart<SrcCharacterType>(), currentCharacter<SrcCharacterType>() - tokenStart<SrcCharacterType>());
- }
- } else if (*currentCharacter<SrcCharacterType>() == '%') {
- // Although the CSS grammar says {num}% we follow
- // webkit at the moment which uses {num}%+.
- do {
- ++currentCharacter<SrcCharacterType>();
- } while (*currentCharacter<SrcCharacterType>() == '%');
- m_token = PERCENTAGE;
- } else
- m_token = dotSeen ? FLOATTOKEN : INTEGER;
- break;
- }
-
- case CharacterDash:
- if (isIdentifierStartAfterDash(currentCharacter<SrcCharacterType>())) {
- --currentCharacter<SrcCharacterType>();
- parseIdentifier(result, resultString, hasEscape);
- m_token = IDENT;
-
- if (*currentCharacter<SrcCharacterType>() == '(') {
- m_token = FUNCTION;
- if (!hasEscape)
- detectDashToken<SrcCharacterType>(result - tokenStart<SrcCharacterType>());
- ++currentCharacter<SrcCharacterType>();
- ++result;
- } else if (UNLIKELY(m_parsingMode == NthChildMode) && !hasEscape && isASCIIAlphaCaselessEqual(tokenStart<SrcCharacterType>()[1], 'n')) {
- if (result - tokenStart<SrcCharacterType>() == 2) {
- // String "-n" is IDENT but "-n+1" is NTH.
- if (parseNthChildExtra<SrcCharacterType>()) {
- m_token = NTH;
- result = currentCharacter<SrcCharacterType>();
- }
- } else if (result - tokenStart<SrcCharacterType>() >= 3 && tokenStart<SrcCharacterType>()[2] == '-') {
- // String "-n-" is IDENT but "-n-1" is NTH.
- // Set currentCharacter to second '-' of '-n-' to continue parsing.
- SrcCharacterType* nextCharacter = result;
- currentCharacter<SrcCharacterType>() = tokenStart<SrcCharacterType>() + 2;
- if (parseNthChildExtra<SrcCharacterType>()) {
- m_token = NTH;
- result = currentCharacter<SrcCharacterType>();
- } else {
- // Revert the change to currentCharacter if unsuccessful.
- currentCharacter<SrcCharacterType>() = nextCharacter;
- }
- }
- }
- resultString.setLength(result - tokenStart<SrcCharacterType>());
- yylval->string = resultString;
- } else if (currentCharacter<SrcCharacterType>()[0] == '-' && currentCharacter<SrcCharacterType>()[1] == '>') {
- currentCharacter<SrcCharacterType>() += 2;
- m_token = SGML_CD;
- } else if (UNLIKELY(m_parsingMode == NthChildMode)) {
- // "-[0-9]+n" is always an NthChild.
- if (parseNthChild<SrcCharacterType>()) {
- parseNthChildExtra<SrcCharacterType>();
- m_token = NTH;
- yylval->string.init(tokenStart<SrcCharacterType>(), currentCharacter<SrcCharacterType>() - tokenStart<SrcCharacterType>());
- }
- }
- break;
-
- case CharacterOther:
- // m_token is simply the current character.
- break;
-
- case CharacterNull:
- // Do not advance pointer at the end of input.
- --currentCharacter<SrcCharacterType>();
- break;
-
- case CharacterWhiteSpace:
- m_token = WHITESPACE;
- // Might start with a '\n'.
- --currentCharacter<SrcCharacterType>();
- do {
- if (*currentCharacter<SrcCharacterType>() == '\n')
- ++m_lineNumber;
- ++currentCharacter<SrcCharacterType>();
- } while (*currentCharacter<SrcCharacterType>() <= ' ' && (typesOfASCIICharacters[*currentCharacter<SrcCharacterType>()] == CharacterWhiteSpace));
- break;
-
- case CharacterEndMediaQueryOrSupports:
- if (m_parsingMode == MediaQueryMode || m_parsingMode == SupportsMode)
- m_parsingMode = NormalMode;
- break;
-
- case CharacterEndNthChild:
- if (m_parsingMode == NthChildMode)
- m_parsingMode = NormalMode;
- break;
-
- case CharacterQuote:
- if (checkAndSkipString(currentCharacter<SrcCharacterType>(), m_token)) {
- ++result;
- parseString<SrcCharacterType>(result, yylval->string, m_token);
- m_token = STRING;
- }
- break;
-
- case CharacterExclamationMark: {
- SrcCharacterType* start = skipWhiteSpace(currentCharacter<SrcCharacterType>());
- if (isEqualToCSSIdentifier(start, "important")) {
- m_token = IMPORTANT_SYM;
- currentCharacter<SrcCharacterType>() = start + 9;
- }
- break;
- }
-
- case CharacterHashmark: {
- SrcCharacterType* start = currentCharacter<SrcCharacterType>();
- result = currentCharacter<SrcCharacterType>();
-
- if (isASCIIDigit(*currentCharacter<SrcCharacterType>())) {
- // This must be a valid hex number token.
- do {
- ++currentCharacter<SrcCharacterType>();
- } while (isASCIIHexDigit(*currentCharacter<SrcCharacterType>()));
- m_token = HEX;
- yylval->string.init(start, currentCharacter<SrcCharacterType>() - start);
- } else if (isIdentifierStart<SrcCharacterType>()) {
- m_token = IDSEL;
- parseIdentifier(result, yylval->string, hasEscape);
- if (!hasEscape) {
- // Check whether the identifier is also a valid hex number.
- SrcCharacterType* current = start;
- m_token = HEX;
- do {
- if (!isASCIIHexDigit(*current)) {
- m_token = IDSEL;
- break;
- }
- ++current;
- } while (current < result);
- }
- }
- break;
- }
-
- case CharacterSlash:
- // Ignore comments. They are not even considered as white spaces.
- if (*currentCharacter<SrcCharacterType>() == '*') {
- const CSSParserLocation startLocation = currentLocation();
- if (m_sourceDataHandler) {
- unsigned startOffset = (is8BitSource() ? currentCharacter<LChar>() - m_dataStart8.get() : currentCharacter<UChar>() - m_dataStart16.get()) - 1; // Start with a slash.
- m_sourceDataHandler->startComment(startOffset - m_parsedTextPrefixLength);
- }
- ++currentCharacter<SrcCharacterType>();
- while (currentCharacter<SrcCharacterType>()[0] != '*' || currentCharacter<SrcCharacterType>()[1] != '/') {
- if (*currentCharacter<SrcCharacterType>() == '\n')
- ++m_lineNumber;
- if (*currentCharacter<SrcCharacterType>() == '\0') {
- // Unterminated comments are simply ignored.
- currentCharacter<SrcCharacterType>() -= 2;
- reportError(startLocation, UnterminatedCommentError);
- break;
- }
- ++currentCharacter<SrcCharacterType>();
- }
- currentCharacter<SrcCharacterType>() += 2;
- if (m_sourceDataHandler) {
- unsigned endOffset = is8BitSource() ? currentCharacter<LChar>() - m_dataStart8.get() : currentCharacter<UChar>() - m_dataStart16.get();
- unsigned userTextEndOffset = static_cast<unsigned>(m_length - 1 - m_parsedTextSuffixLength);
- m_sourceDataHandler->endComment(min(endOffset, userTextEndOffset) - m_parsedTextPrefixLength);
- }
- goto restartAfterComment;
- }
- break;
-
- case CharacterDollar:
- if (*currentCharacter<SrcCharacterType>() == '=') {
- ++currentCharacter<SrcCharacterType>();
- m_token = ENDSWITH;
- }
- break;
-
- case CharacterAsterisk:
- if (*currentCharacter<SrcCharacterType>() == '=') {
- ++currentCharacter<SrcCharacterType>();
- m_token = CONTAINS;
- }
- break;
-
- case CharacterPlus:
- if (UNLIKELY(m_parsingMode == NthChildMode)) {
- // Simplest case. "+[0-9]*n" is always NthChild.
- if (parseNthChild<SrcCharacterType>()) {
- parseNthChildExtra<SrcCharacterType>();
- m_token = NTH;
- yylval->string.init(tokenStart<SrcCharacterType>(), currentCharacter<SrcCharacterType>() - tokenStart<SrcCharacterType>());
- }
- }
- break;
-
- case CharacterLess:
- if (currentCharacter<SrcCharacterType>()[0] == '!' && currentCharacter<SrcCharacterType>()[1] == '-' && currentCharacter<SrcCharacterType>()[2] == '-') {
- currentCharacter<SrcCharacterType>() += 3;
- m_token = SGML_CD;
- }
- break;
-
- case CharacterAt:
- if (isIdentifierStart<SrcCharacterType>()) {
- m_token = ATKEYWORD;
- ++result;
- parseIdentifier(result, resultString, hasEscape);
- detectAtToken<SrcCharacterType>(result - tokenStart<SrcCharacterType>(), hasEscape);
- }
- break;
-
- case CharacterBackSlash:
- if (isCSSEscape(*currentCharacter<SrcCharacterType>())) {
- --currentCharacter<SrcCharacterType>();
- parseIdentifier(result, yylval->string, hasEscape);
- m_token = IDENT;
- }
- break;
-
- case CharacterXor:
- if (*currentCharacter<SrcCharacterType>() == '=') {
- ++currentCharacter<SrcCharacterType>();
- m_token = BEGINSWITH;
- }
- break;
-
- case CharacterVerticalBar:
- if (*currentCharacter<SrcCharacterType>() == '=') {
- ++currentCharacter<SrcCharacterType>();
- m_token = DASHMATCH;
- }
- break;
-
- case CharacterTilde:
- if (*currentCharacter<SrcCharacterType>() == '=') {
- ++currentCharacter<SrcCharacterType>();
- m_token = INCLUDES;
- }
- break;
-
- default:
- ASSERT_NOT_REACHED();
- break;
- }
-
- return token();
-}
-
CSSParserSelector* CSSParser::createFloatingSelectorWithTagName(const QualifiedName& tagQName)
{
CSSParserSelector* selector = new CSSParserSelector(tagQName);
- m_floatingSelectors.add(selector);
+ m_floatingSelectors.append(selector);
return selector;
}
CSSParserSelector* CSSParser::createFloatingSelector()
{
CSSParserSelector* selector = new CSSParserSelector;
- m_floatingSelectors.add(selector);
+ m_floatingSelectors.append(selector);
return selector;
}
PassOwnPtr<CSSParserSelector> CSSParser::sinkFloatingSelector(CSSParserSelector* selector)
{
if (selector) {
- ASSERT(m_floatingSelectors.contains(selector));
- m_floatingSelectors.remove(selector);
+ size_t index = m_floatingSelectors.reverseFind(selector);
+ ASSERT(index != kNotFound);
+ m_floatingSelectors.remove(index);
}
return adoptPtr(selector);
}
@@ -10916,15 +9428,16 @@ PassOwnPtr<CSSParserSelector> CSSParser::sinkFloatingSelector(CSSParserSelector*
Vector<OwnPtr<CSSParserSelector> >* CSSParser::createFloatingSelectorVector()
{
Vector<OwnPtr<CSSParserSelector> >* selectorVector = new Vector<OwnPtr<CSSParserSelector> >;
- m_floatingSelectorVectors.add(selectorVector);
+ m_floatingSelectorVectors.append(selectorVector);
return selectorVector;
}
PassOwnPtr<Vector<OwnPtr<CSSParserSelector> > > CSSParser::sinkFloatingSelectorVector(Vector<OwnPtr<CSSParserSelector> >* selectorVector)
{
if (selectorVector) {
- ASSERT(m_floatingSelectorVectors.contains(selectorVector));
- m_floatingSelectorVectors.remove(selectorVector);
+ size_t index = m_floatingSelectorVectors.reverseFind(selectorVector);
+ ASSERT(index != kNotFound);
+ m_floatingSelectorVectors.remove(index);
}
return adoptPtr(selectorVector);
}
@@ -10932,15 +9445,16 @@ PassOwnPtr<Vector<OwnPtr<CSSParserSelector> > > CSSParser::sinkFloatingSelectorV
CSSParserValueList* CSSParser::createFloatingValueList()
{
CSSParserValueList* list = new CSSParserValueList;
- m_floatingValueLists.add(list);
+ m_floatingValueLists.append(list);
return list;
}
PassOwnPtr<CSSParserValueList> CSSParser::sinkFloatingValueList(CSSParserValueList* list)
{
if (list) {
- ASSERT(m_floatingValueLists.contains(list));
- m_floatingValueLists.remove(list);
+ size_t index = m_floatingValueLists.reverseFind(list);
+ ASSERT(index != kNotFound);
+ m_floatingValueLists.remove(index);
}
return adoptPtr(list);
}
@@ -10948,7 +9462,7 @@ PassOwnPtr<CSSParserValueList> CSSParser::sinkFloatingValueList(CSSParserValueLi
CSSParserFunction* CSSParser::createFloatingFunction()
{
CSSParserFunction* function = new CSSParserFunction;
- m_floatingFunctions.add(function);
+ m_floatingFunctions.append(function);
return function;
}
@@ -10963,8 +9477,9 @@ CSSParserFunction* CSSParser::createFloatingFunction(const CSSParserString& name
PassOwnPtr<CSSParserFunction> CSSParser::sinkFloatingFunction(CSSParserFunction* function)
{
if (function) {
- ASSERT(m_floatingFunctions.contains(function));
- m_floatingFunctions.remove(function);
+ size_t index = m_floatingFunctions.reverseFind(function);
+ ASSERT(index != kNotFound);
+ m_floatingFunctions.remove(index);
}
return adoptPtr(function);
}
@@ -10972,8 +9487,9 @@ PassOwnPtr<CSSParserFunction> CSSParser::sinkFloatingFunction(CSSParserFunction*
CSSParserValue& CSSParser::sinkFloatingValue(CSSParserValue& value)
{
if (value.unit == CSSParserValue::Function) {
- ASSERT(m_floatingFunctions.contains(value.function));
- m_floatingFunctions.remove(value.function);
+ size_t index = m_floatingFunctions.reverseFind(value.function);
+ ASSERT(index != kNotFound);
+ m_floatingFunctions.remove(index);
}
return value;
}
@@ -11002,7 +9518,7 @@ PassOwnPtr<Vector<OwnPtr<MediaQueryExp> > > CSSParser::sinkFloatingMediaQueryExp
return m_floatingMediaQueryExpList.release();
}
-MediaQuery* CSSParser::createFloatingMediaQuery(MediaQuery::Restrictor restrictor, const String& mediaType, PassOwnPtr<Vector<OwnPtr<MediaQueryExp> > > expressions)
+MediaQuery* CSSParser::createFloatingMediaQuery(MediaQuery::Restrictor restrictor, const AtomicString& mediaType, PassOwnPtr<Vector<OwnPtr<MediaQueryExp> > > expressions)
{
m_floatingMediaQuery = adoptPtr(new MediaQuery(restrictor, mediaType, expressions));
return m_floatingMediaQuery.get();
@@ -11010,12 +9526,12 @@ MediaQuery* CSSParser::createFloatingMediaQuery(MediaQuery::Restrictor restricto
MediaQuery* CSSParser::createFloatingMediaQuery(PassOwnPtr<Vector<OwnPtr<MediaQueryExp> > > expressions)
{
- return createFloatingMediaQuery(MediaQuery::None, "all", expressions);
+ return createFloatingMediaQuery(MediaQuery::None, AtomicString("all", AtomicString::ConstructFromLiteral), expressions);
}
MediaQuery* CSSParser::createFloatingNotAllQuery()
{
- return createFloatingMediaQuery(MediaQuery::Not, "all", sinkFloatingMediaQueryExpList(createFloatingMediaQueryExpList()));
+ return createFloatingMediaQuery(MediaQuery::Not, AtomicString("all", AtomicString::ConstructFromLiteral), sinkFloatingMediaQueryExpList(createFloatingMediaQueryExpList()));
}
PassOwnPtr<MediaQuery> CSSParser::sinkFloatingMediaQuery(MediaQuery* query)
@@ -11046,14 +9562,11 @@ MediaQuerySet* CSSParser::createMediaQuerySet()
StyleRuleBase* CSSParser::createImportRule(const CSSParserString& url, MediaQuerySet* media)
{
- if (!media || !m_allowImportRules) {
- endRuleBody(true);
+ if (!media || !m_allowImportRules)
return 0;
- }
RefPtr<StyleRuleImport> rule = StyleRuleImport::create(url, media);
StyleRuleImport* result = rule.get();
m_parsedRules.append(rule.release());
- endRuleBody();
return result;
}
@@ -11061,15 +9574,14 @@ StyleRuleBase* CSSParser::createMediaRule(MediaQuerySet* media, RuleList* rules)
{
m_allowImportRules = m_allowNamespaceDeclarations = false;
RefPtr<StyleRuleMedia> rule;
- if (rules)
+ if (rules) {
rule = StyleRuleMedia::create(media ? media : MediaQuerySet::create(), *rules);
- else {
+ } else {
RuleList emptyRules;
rule = StyleRuleMedia::create(media ? media : MediaQuerySet::create(), emptyRules);
}
StyleRuleMedia* result = rule.get();
m_parsedRules.append(rule.release());
- endRuleBody();
return result;
}
@@ -11083,21 +9595,20 @@ StyleRuleBase* CSSParser::createSupportsRule(bool conditionIsSupported, RuleList
unsigned conditionOffset = data->ruleHeaderRange.start + 9;
unsigned conditionLength = data->ruleHeaderRange.length() - 9;
- if (is8BitSource())
- conditionText = String(m_dataStart8.get() + conditionOffset, conditionLength).stripWhiteSpace();
+ if (m_tokenizer.is8BitSource())
+ conditionText = String(m_tokenizer.m_dataStart8.get() + conditionOffset, conditionLength).stripWhiteSpace();
else
- conditionText = String(m_dataStart16.get() + conditionOffset, conditionLength).stripWhiteSpace();
+ conditionText = String(m_tokenizer.m_dataStart16.get() + conditionOffset, conditionLength).stripWhiteSpace();
- if (rules)
+ if (rules) {
rule = StyleRuleSupports::create(conditionText, conditionIsSupported, *rules);
- else {
+ } else {
RuleList emptyRules;
rule = StyleRuleSupports::create(conditionText, conditionIsSupported, emptyRules);
}
StyleRuleSupports* result = rule.get();
m_parsedRules.append(rule.release());
- endRuleBody();
return result;
}
@@ -11108,7 +9619,7 @@ void CSSParser::markSupportsRuleHeaderStart()
m_supportsRuleDataStack = adoptPtr(new RuleSourceDataList());
RefPtr<CSSRuleSourceData> data = CSSRuleSourceData::create(CSSRuleSourceData::SUPPORTS_RULE);
- data->ruleHeaderRange.start = tokenStartOffset();
+ data->ruleHeaderRange.start = m_tokenizer.tokenStartOffset();
m_supportsRuleDataStack->append(data);
}
@@ -11116,10 +9627,10 @@ void CSSParser::markSupportsRuleHeaderEnd()
{
ASSERT(m_supportsRuleDataStack && !m_supportsRuleDataStack->isEmpty());
- if (is8BitSource())
- m_supportsRuleDataStack->last()->ruleHeaderRange.end = tokenStart<LChar>() - m_dataStart8.get();
+ if (m_tokenizer.is8BitSource())
+ m_supportsRuleDataStack->last()->ruleHeaderRange.end = m_tokenizer.tokenStart<LChar>() - m_tokenizer.m_dataStart8.get();
else
- m_supportsRuleDataStack->last()->ruleHeaderRange.end = tokenStart<UChar>() - m_dataStart16.get();
+ m_supportsRuleDataStack->last()->ruleHeaderRange.end = m_tokenizer.tokenStart<UChar>() - m_tokenizer.m_dataStart16.get();
}
PassRefPtr<CSSRuleSourceData> CSSParser::popSupportsRuleData()
@@ -11139,6 +9650,15 @@ CSSParser::RuleList* CSSParser::createRuleList()
return listPtr;
}
+CSSParser::RuleList* CSSParser::appendRule(RuleList* ruleList, StyleRuleBase* rule)
+{
+ if (rule) {
+ if (!ruleList)
+ ruleList = createRuleList();
+ ruleList->append(rule);
+ }
+ return ruleList;
+}
template <typename CharacterType>
ALWAYS_INLINE static void makeLower(const CharacterType* input, CharacterType* output, unsigned length)
@@ -11161,12 +9681,12 @@ ALWAYS_INLINE static void makeLower(const CharacterType* input, CharacterType* o
void CSSParser::tokenToLowerCase(const CSSParserString& token)
{
size_t length = token.length();
- if (is8BitSource()) {
- size_t offset = token.characters8() - m_dataStart8.get();
- makeLower(token.characters8(), m_dataStart8.get() + offset, length);
+ if (m_tokenizer.is8BitSource()) {
+ size_t offset = token.characters8() - m_tokenizer.m_dataStart8.get();
+ makeLower(token.characters8(), m_tokenizer.m_dataStart8.get() + offset, length);
} else {
- size_t offset = token.characters16() - m_dataStart16.get();
- makeLower(token.characters16(), m_dataStart16.get() + offset, length);
+ size_t offset = token.characters16() - m_tokenizer.m_dataStart16.get();
+ makeLower(token.characters16(), m_tokenizer.m_dataStart16.get() + offset, length);
}
}
@@ -11176,88 +9696,21 @@ void CSSParser::endInvalidRuleHeader()
return;
CSSParserLocation location;
- location.lineNumber = m_lineNumber;
+ location.lineNumber = m_tokenizer.m_lineNumber;
location.offset = m_ruleHeaderStartOffset;
- if (is8BitSource())
- location.token.init(m_dataStart8.get() + m_ruleHeaderStartOffset, 0);
+ if (m_tokenizer.is8BitSource())
+ location.token.init(m_tokenizer.m_dataStart8.get() + m_ruleHeaderStartOffset, 0);
else
- location.token.init(m_dataStart16.get() + m_ruleHeaderStartOffset, 0);
+ location.token.init(m_tokenizer.m_dataStart16.get() + m_ruleHeaderStartOffset, 0);
reportError(location, m_ruleHeaderType == CSSRuleSourceData::STYLE_RULE ? InvalidSelectorError : InvalidRuleError);
endRuleHeader();
}
-void CSSParser::reportError(const CSSParserLocation& location, ErrorType error)
+void CSSParser::reportError(const CSSParserLocation&, ErrorType)
{
- if (!isLoggingErrors() || (m_ruleHeaderType == CSSRuleSourceData::SUPPORTS_RULE && error != InvalidSupportsConditionError))
- return;
-
- m_ignoreErrors = true;
- CSSParserString content = location.token;
- if (error == InvalidPropertyValueError || error == InvalidSelectorError || error == InvalidMediaQueryError || error == InvalidKeyframeSelectorError) {
- if (m_source) {
- if (is8BitSource())
- content.init(*m_source, location.token.characters8() - m_dataStart8.get(), tokenStart<LChar>() - location.token.characters8());
- else
- content.init(*m_source, location.token.characters16() - m_dataStart16.get(), tokenStart<UChar>() - location.token.characters16());
- content.trimTrailingWhitespace();
- }
- }
-
- if (!InspectorInstrumentation::cssErrorFilter(content, m_id, error))
- return;
-
- StringBuilder builder;
- switch (error) {
- case PropertyDeclarationError:
- builder.appendLiteral("Invalid CSS property declaration at: ");
- break;
-
- case InvalidPropertyValueError:
- builder.appendLiteral("Invalid CSS property value: ");
- break;
-
- case InvalidPropertyError:
- builder.appendLiteral("Invalid CSS property name: ");
- break;
-
- case InvalidSelectorError:
- builder.appendLiteral("Invalid CSS selector: ");
- break;
-
- case InvalidSupportsConditionError:
- builder.appendLiteral("Invalid CSS @supports condition: ");
- break;
-
- case InvalidRuleError:
- builder.appendLiteral("Invalid CSS rule at: ");
- break;
-
- case InvalidMediaQueryError:
- builder.appendLiteral("Invalid CSS media query: ");
- break;
-
- case InvalidSelectorPseudoError:
- builder.appendLiteral("Invalid CSS selector pseudoclass: ");
- break;
-
- case InvalidKeyframeSelectorError:
- builder.appendLiteral("Invalid CSS keyframe selector: ");
- break;
-
- case UnterminatedCommentError:
- content.setLength(0);
- builder.appendLiteral("Unterminated CSS comment");
- break;
-
- default:
- builder.appendLiteral("Unexpected CSS token: ");
- }
-
- builder.append(content);
-
- logError(builder.toString(), location);
+ // FIXME: error reporting temporatily disabled.
}
bool CSSParser::isLoggingErrors()
@@ -11292,7 +9745,6 @@ StyleRuleKeyframes* CSSParser::createKeyframesRule(const String& name, PassOwnPt
rule->setVendorPrefixed(isPrefixed);
StyleRuleKeyframes* rulePtr = rule.get();
m_parsedRules.append(rule.release());
- endRuleBody();
return rulePtr;
}
@@ -11308,9 +9760,7 @@ StyleRuleBase* CSSParser::createStyleRule(Vector<OwnPtr<CSSParserSelector> >* se
rule->setProperties(createStylePropertySet());
result = rule.get();
m_parsedRules.append(rule.release());
- endRuleBody();
- } else
- endRuleBody(true);
+ }
clearProperties();
return result;
}
@@ -11328,7 +9778,6 @@ StyleRuleBase* CSSParser::createFontFaceRule()
// have 'initial' value and cannot 'inherit' from parent.
// See http://dev.w3.org/csswg/css3-fonts/#font-family-desc
clearProperties();
- endRuleBody(true);
return 0;
}
}
@@ -11337,23 +9786,8 @@ StyleRuleBase* CSSParser::createFontFaceRule()
clearProperties();
StyleRuleFontFace* result = rule.get();
m_parsedRules.append(rule.release());
- endRuleBody();
- return result;
-}
-
-StyleRuleBase* CSSParser::createHostRule(RuleList* rules)
-{
- m_allowImportRules = m_allowNamespaceDeclarations = false;
- RefPtr<StyleRuleHost> rule;
- if (rules)
- rule = StyleRuleHost::create(*rules);
- else {
- RuleList emptyRules;
- rule = StyleRuleHost::create(emptyRules);
- }
- StyleRuleHost* result = rule.get();
- m_parsedRules.append(rule.release());
- endRuleBody();
+ if (m_styleSheet)
+ m_styleSheet->setHasFontFaceRule(true);
return result;
}
@@ -11524,9 +9958,7 @@ StyleRuleBase* CSSParser::createPageRule(PassOwnPtr<CSSParserSelector> pageSelec
rule->setProperties(createStylePropertySet());
pageRule = rule.get();
m_parsedRules.append(rule.release());
- endRuleBody();
- } else
- endRuleBody(true);
+ }
clearProperties();
return pageRule;
}
@@ -11539,10 +9971,11 @@ void CSSParser::setReusableRegionSelectorVector(Vector<OwnPtr<CSSParserSelector>
StyleRuleBase* CSSParser::createRegionRule(Vector<OwnPtr<CSSParserSelector> >* regionSelector, RuleList* rules)
{
- if (!RuntimeEnabledFeatures::cssRegionsEnabled() || !regionSelector || !rules) {
- endRuleBody(true);
+ if (m_useCounter)
+ m_useCounter->count(UseCounter::CSSWebkitRegionAtRule);
+
+ if (!RuntimeEnabledFeatures::cssRegionsEnabled() || !regionSelector || !rules)
return 0;
- }
m_allowImportRules = m_allowNamespaceDeclarations = false;
@@ -11614,59 +10047,78 @@ void CSSParser::invalidBlockHit()
m_styleSheet->setHasSyntacticallyValidCSSHeader(false);
}
+void CSSParser::startRule()
+{
+ if (!m_sourceDataHandler)
+ return;
+
+ ASSERT(m_ruleHasHeader);
+ m_ruleHasHeader = false;
+}
+
+void CSSParser::endRule(bool valid)
+{
+ if (!m_sourceDataHandler)
+ return;
+
+ if (m_ruleHasHeader)
+ m_sourceDataHandler->endRuleBody(m_tokenizer.safeUserStringTokenOffset(), !valid);
+ m_ruleHasHeader = true;
+}
+
void CSSParser::startRuleHeader(CSSRuleSourceData::Type ruleType)
{
resumeErrorLogging();
m_ruleHeaderType = ruleType;
- m_ruleHeaderStartOffset = safeUserStringTokenOffset();
- m_ruleHeaderStartLineNumber = m_tokenStartLineNumber;
- if (m_sourceDataHandler)
+ m_ruleHeaderStartOffset = m_tokenizer.safeUserStringTokenOffset();
+ m_ruleHeaderStartLineNumber = m_tokenizer.m_tokenStartLineNumber;
+ if (m_sourceDataHandler) {
+ ASSERT(!m_ruleHasHeader);
m_sourceDataHandler->startRuleHeader(ruleType, m_ruleHeaderStartOffset);
+ m_ruleHasHeader = true;
+ }
}
void CSSParser::endRuleHeader()
{
+ ASSERT(m_ruleHeaderType != CSSRuleSourceData::UNKNOWN_RULE);
m_ruleHeaderType = CSSRuleSourceData::UNKNOWN_RULE;
- if (m_sourceDataHandler)
- m_sourceDataHandler->endRuleHeader(safeUserStringTokenOffset());
+ if (m_sourceDataHandler) {
+ ASSERT(m_ruleHasHeader);
+ m_sourceDataHandler->endRuleHeader(m_tokenizer.safeUserStringTokenOffset());
+ }
}
void CSSParser::startSelector()
{
if (m_sourceDataHandler)
- m_sourceDataHandler->startSelector(safeUserStringTokenOffset());
+ m_sourceDataHandler->startSelector(m_tokenizer.safeUserStringTokenOffset());
}
void CSSParser::endSelector()
{
if (m_sourceDataHandler)
- m_sourceDataHandler->endSelector(safeUserStringTokenOffset());
+ m_sourceDataHandler->endSelector(m_tokenizer.safeUserStringTokenOffset());
}
void CSSParser::startRuleBody()
{
if (m_sourceDataHandler)
- m_sourceDataHandler->startRuleBody(safeUserStringTokenOffset());
-}
-
-void CSSParser::endRuleBody(bool discard)
-{
- if (m_sourceDataHandler)
- m_sourceDataHandler->endRuleBody(safeUserStringTokenOffset(), discard);
+ m_sourceDataHandler->startRuleBody(m_tokenizer.safeUserStringTokenOffset());
}
void CSSParser::startProperty()
{
resumeErrorLogging();
if (m_sourceDataHandler)
- m_sourceDataHandler->startProperty(safeUserStringTokenOffset());
+ m_sourceDataHandler->startProperty(m_tokenizer.safeUserStringTokenOffset());
}
void CSSParser::endProperty(bool isImportantFound, bool isPropertyParsed, ErrorType errorType)
{
m_id = CSSPropertyInvalid;
if (m_sourceDataHandler)
- m_sourceDataHandler->endProperty(isImportantFound, isPropertyParsed, safeUserStringTokenOffset(), errorType);
+ m_sourceDataHandler->endProperty(isImportantFound, isPropertyParsed, m_tokenizer.safeUserStringTokenOffset(), errorType);
}
void CSSParser::startEndUnknownRule()
@@ -11675,18 +10127,11 @@ void CSSParser::startEndUnknownRule()
m_sourceDataHandler->startEndUnknownRule();
}
-unsigned CSSParser::safeUserStringTokenOffset()
-{
- return min(tokenStartOffset(), static_cast<unsigned>(m_length - 1 - m_parsedTextSuffixLength)) - m_parsedTextPrefixLength;
-}
-
StyleRuleBase* CSSParser::createViewportRule()
{
// Allow @viewport rules from UA stylesheets even if the feature is disabled.
- if (!RuntimeEnabledFeatures::cssViewportEnabled() && m_context.mode != UASheetMode) {
- endRuleBody(true);
+ if (!RuntimeEnabledFeatures::cssViewportEnabled() && !isUASheetBehavior(m_context.mode()))
return 0;
- }
m_allowImportRules = m_allowNamespaceDeclarations = false;
@@ -11697,14 +10142,13 @@ StyleRuleBase* CSSParser::createViewportRule()
StyleRuleViewport* result = rule.get();
m_parsedRules.append(rule.release());
- endRuleBody();
return result;
}
bool CSSParser::parseViewportProperty(CSSPropertyID propId, bool important)
{
- ASSERT(RuntimeEnabledFeatures::cssViewportEnabled() || m_context.mode == UASheetMode);
+ ASSERT(RuntimeEnabledFeatures::cssViewportEnabled() || isUASheetBehavior(m_context.mode()));
CSSParserValue* value = m_valueList->current();
if (!value)
@@ -11764,7 +10208,7 @@ bool CSSParser::parseViewportProperty(CSSPropertyID propId, bool important)
bool CSSParser::parseViewportShorthand(CSSPropertyID propId, CSSPropertyID first, CSSPropertyID second, bool important)
{
- ASSERT(RuntimeEnabledFeatures::cssViewportEnabled() || m_context.mode == UASheetMode);
+ ASSERT(RuntimeEnabledFeatures::cssViewportEnabled() || isUASheetBehavior(m_context.mode()));
unsigned numValues = m_valueList->size();
if (numValues > 2)
@@ -11786,7 +10230,7 @@ bool CSSParser::parseViewportShorthand(CSSPropertyID propId, CSSPropertyID first
template <typename CharacterType>
static CSSPropertyID cssPropertyID(const CharacterType* propertyName, unsigned length)
{
- char buffer[maxCSSPropertyNameLength + 1 + 1]; // 1 to turn "apple"/"khtml" into "webkit", 1 for null character
+ char buffer[maxCSSPropertyNameLength + 1]; // 1 for null character
for (unsigned i = 0; i != length; ++i) {
CharacterType c = propertyName[i];
@@ -11828,7 +10272,7 @@ CSSPropertyID cssPropertyID(const CSSParserString& string)
template <typename CharacterType>
static CSSValueID cssValueKeywordID(const CharacterType* valueKeyword, unsigned length)
{
- char buffer[maxCSSValueKeywordLength + 1 + 1]; // 1 to turn "apple"/"khtml" into "webkit", 1 for null character
+ char buffer[maxCSSValueKeywordLength + 1]; // 1 for null character
for (unsigned i = 0; i != length; ++i) {
CharacterType c = valueKeyword[i];
@@ -11838,16 +10282,6 @@ static CSSValueID cssValueKeywordID(const CharacterType* valueKeyword, unsigned
}
buffer[length] = '\0';
- if (buffer[0] == '-') {
- // If the prefix is -apple- or -khtml-, change it to -webkit-.
- // This makes the string one character longer.
- if (hasPrefix(buffer, length, "-apple-") || hasPrefix(buffer, length, "-khtml-")) {
- memmove(buffer + 7, buffer + 6, length + 1 - 6);
- memcpy(buffer, "-webkit", 7);
- ++length;
- }
- }
-
const Value* hashTableEntry = findValue(buffer, length);
return hashTableEntry ? static_cast<CSSValueID>(hashTableEntry->id) : CSSValueInvalid;
}
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSParser.h b/chromium/third_party/WebKit/Source/core/css/CSSParser.h
index b4fa383d958..de263102892 100644..100755
--- a/chromium/third_party/WebKit/Source/core/css/CSSParser.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSParser.h
@@ -33,12 +33,13 @@
#include "core/css/CSSProperty.h"
#include "core/css/CSSPropertySourceData.h"
#include "core/css/CSSSelector.h"
+#include "core/css/CSSTokenizer.h"
#include "core/css/MediaQuery.h"
#include "core/css/StylePropertySet.h"
-#include "core/page/UseCounter.h"
-#include "core/platform/graphics/Color.h"
+#include "core/frame/UseCounter.h"
+#include "platform/graphics/Color.h"
#include "wtf/HashSet.h"
-#include "wtf/OwnArrayPtr.h"
+#include "wtf/OwnPtr.h"
#include "wtf/Vector.h"
#include "wtf/text/AtomicString.h"
#include "wtf/text/TextPosition.h"
@@ -68,6 +69,7 @@ class StyleRuleKeyframes;
class StyleKeyframe;
class StyleSheetContents;
+// FIXME: This class is shared with CSSTokenizer so should we rename it to CSSSourceLocation?
struct CSSParserLocation {
unsigned offset;
unsigned lineNumber;
@@ -185,6 +187,7 @@ public:
PassRefPtr<CSSValue> parseGridTrackSize(CSSParserValueList& inputList);
PassRefPtr<CSSPrimitiveValue> parseGridBreadth(CSSParserValue*);
PassRefPtr<CSSValue> parseGridTemplate();
+ void parseGridLineNames(CSSParserValueList* inputList, CSSValueList&);
bool parseClipShape(CSSPropertyID, bool important);
@@ -226,7 +229,8 @@ public:
// CSS3 Parsing Routines (for properties specific to CSS3)
PassRefPtr<CSSValueList> parseShadow(CSSParserValueList*, CSSPropertyID);
- bool parseBorderImage(CSSPropertyID, RefPtr<CSSValue>&, bool important = false);
+ bool parseBorderImageShorthand(CSSPropertyID, bool important);
+ PassRefPtr<CSSValue> parseBorderImage(CSSPropertyID);
bool parseBorderImageRepeat(RefPtr<CSSValue>&);
bool parseBorderImageSlice(CSSPropertyID, RefPtr<CSSBorderImageSliceValue>&);
bool parseBorderImageWidth(RefPtr<CSSPrimitiveValue>&);
@@ -277,16 +281,16 @@ public:
bool parseTextEmphasisStyle(bool important);
+ bool parseTouchAction(bool important);
+
void addTextDecorationProperty(CSSPropertyID, PassRefPtr<CSSValue>, bool important);
bool parseTextDecoration(CSSPropertyID propId, bool important);
-#if ENABLE(CSS3_TEXT)
bool parseTextUnderlinePosition(bool important);
-#endif // CSS3_TEXT
PassRefPtr<CSSValue> parseTextIndent();
bool parseLineBoxContain(bool important);
- bool parseCalculation(CSSParserValue*, CalculationPermittedValueRange);
+ bool parseCalculation(CSSParserValue*, ValueRange);
bool parseFontFeatureTag(CSSValueList*);
bool parseFontFeatureSettings(bool important);
@@ -297,6 +301,8 @@ public:
bool parseFontVariantLigatures(bool important);
+ bool parseGeneratedImage(CSSParserValueList*, RefPtr<CSSValue>&);
+
CSSParserSelector* createFloatingSelector();
CSSParserSelector* createFloatingSelectorWithTagName(const QualifiedName&);
PassOwnPtr<CSSParserSelector> sinkFloatingSelector(CSSParserSelector*);
@@ -321,6 +327,7 @@ public:
typedef Vector<RefPtr<StyleRuleBase> > RuleList;
StyleRuleBase* createMediaRule(MediaQuerySet*, RuleList*);
RuleList* createRuleList();
+ RuleList* appendRule(RuleList*, StyleRuleBase*);
StyleRuleBase* createStyleRule(Vector<OwnPtr<CSSParserSelector> >* selectors);
StyleRuleBase* createFontFaceRule();
StyleRuleBase* createPageRule(PassOwnPtr<CSSParserSelector> pageSelector);
@@ -340,7 +347,7 @@ public:
PassOwnPtr<MediaQueryExp> sinkFloatingMediaQueryExp(MediaQueryExp*);
Vector<OwnPtr<MediaQueryExp> >* createFloatingMediaQueryExpList();
PassOwnPtr<Vector<OwnPtr<MediaQueryExp> > > sinkFloatingMediaQueryExpList(Vector<OwnPtr<MediaQueryExp> >*);
- MediaQuery* createFloatingMediaQuery(MediaQuery::Restrictor, const String&, PassOwnPtr<Vector<OwnPtr<MediaQueryExp> > >);
+ MediaQuery* createFloatingMediaQuery(MediaQuery::Restrictor, const AtomicString&, PassOwnPtr<Vector<OwnPtr<MediaQueryExp> > >);
MediaQuery* createFloatingMediaQuery(PassOwnPtr<Vector<OwnPtr<MediaQueryExp> > >);
MediaQuery* createFloatingNotAllQuery();
PassOwnPtr<MediaQuery> sinkFloatingMediaQuery(MediaQuery*);
@@ -400,16 +407,15 @@ public:
AtomicString m_defaultNamespace;
// tokenizer methods and data
- size_t m_parsedTextPrefixLength;
- size_t m_parsedTextSuffixLength;
SourceDataHandler* m_sourceDataHandler;
+ void startRule();
+ void endRule(bool valid);
void startRuleHeader(CSSRuleSourceData::Type);
void endRuleHeader();
void startSelector();
void endSelector();
void startRuleBody();
- void endRuleBody(bool discard = false);
void startProperty();
void endProperty(bool isImportantFound, bool isPropertyParsed, ErrorType = NoError);
void startEndUnknownRule();
@@ -420,10 +426,6 @@ public:
void setLocationLabel(const CSSParserLocation& location) { m_locationLabel = location; }
const CSSParserLocation& lastLocationLabel() const { return m_locationLabel; }
- inline int lex(void* yylval) { return (this->*m_lexFunc)(yylval); }
-
- int token() { return m_token; }
-
void tokenToLowerCase(const CSSParserString& token);
void markViewportRuleBodyStart() { m_inViewport = true; }
@@ -436,7 +438,7 @@ public:
static KURL completeURL(const CSSParserContext&, const String& url);
- CSSParserLocation currentLocation();
+ CSSParserLocation currentLocation() { return m_tokenizer.currentLocation(); }
private:
enum PropertyType {
@@ -469,7 +471,7 @@ private:
: m_parser(parser)
, m_mode(declaration->cssParserMode())
{
- if (m_mode == ViewportMode) {
+ if (isCSSViewportParsingEnabledForMode(m_mode)) {
ASSERT(!m_parser->inViewport());
m_parser->markViewportRuleBodyStart();
}
@@ -477,7 +479,7 @@ private:
~StyleDeclarationScope()
{
- if (m_mode == ViewportMode)
+ if (isCSSViewportParsingEnabledForMode(m_mode))
m_parser->markViewportRuleBodyEnd();
}
@@ -486,85 +488,12 @@ private:
CSSParserMode m_mode;
};
- bool is8BitSource() const { return m_is8BitSource; }
-
- template <typename SourceCharacterType>
- int realLex(void* yylval);
-
- UChar*& currentCharacter16();
-
- template <typename CharacterType>
- inline CharacterType*& currentCharacter();
-
- template <typename CharacterType>
- inline CharacterType* tokenStart();
-
- template <typename CharacterType>
- inline CharacterType* dataStart();
-
- template <typename CharacterType>
- inline void setTokenStart(CharacterType*);
-
- inline unsigned tokenStartOffset();
- inline UChar tokenStartChar();
-
- template <typename CharacterType>
- inline bool isIdentifierStart();
-
inline void ensureLineEndings();
- template <typename CharacterType>
- inline CSSParserLocation tokenLocation();
-
- template <typename CharacterType>
- unsigned parseEscape(CharacterType*&);
- template <typename DestCharacterType>
- inline void UnicodeToChars(DestCharacterType*&, unsigned);
- template <typename SrcCharacterType, typename DestCharacterType>
- inline bool parseIdentifierInternal(SrcCharacterType*&, DestCharacterType*&, bool&);
-
- template <typename CharacterType>
- inline void parseIdentifier(CharacterType*&, CSSParserString&, bool&);
-
- template <typename SrcCharacterType, typename DestCharacterType>
- inline bool parseStringInternal(SrcCharacterType*&, DestCharacterType*&, UChar);
-
- template <typename CharacterType>
- inline void parseString(CharacterType*&, CSSParserString& resultString, UChar);
-
- template <typename CharacterType>
- inline bool findURI(CharacterType*& start, CharacterType*& end, UChar& quote);
-
- template <typename SrcCharacterType, typename DestCharacterType>
- inline bool parseURIInternal(SrcCharacterType*&, DestCharacterType*&, UChar quote);
-
- template <typename CharacterType>
- inline void parseURI(CSSParserString&);
- template <typename CharacterType>
- inline bool parseUnicodeRange();
- template <typename CharacterType>
- bool parseNthChild();
- template <typename CharacterType>
- bool parseNthChildExtra();
- template <typename CharacterType>
- inline bool detectFunctionTypeToken(int);
- template <typename CharacterType>
- inline void detectMediaQueryToken(int);
- template <typename CharacterType>
- inline void detectNumberToken(CharacterType*, int);
- template <typename CharacterType>
- inline void detectDashToken(int);
- template <typename CharacterType>
- inline void detectAtToken(int, bool);
- template <typename CharacterType>
- inline void detectSupportsToken(int);
- template <typename CharacterType>
- inline void detectCSSVariableDefinitionToken(int);
-
void setStyleSheet(StyleSheetContents* styleSheet) { m_styleSheet = styleSheet; }
- inline bool inStrictMode() const { return isStrictParserMode(m_context.mode); }
- inline bool inQuirksMode() const { return m_context.mode == CSSQuirksMode || m_context.mode == CSSAttributeMode; }
+ bool inQuirksMode() const { return isQuirksModeBehavior(m_context.mode()); }
+ bool inViewport() const { return m_inViewport; }
KURL completeURL(const String& url) const;
@@ -582,9 +511,6 @@ private:
void deleteFontFaceOnlyValues();
- bool isGeneratedImageValue(CSSParserValue*) const;
- bool parseGeneratedImage(CSSParserValueList*, RefPtr<CSSValue>&);
-
bool parseValue(MutableStylePropertySet*, CSSPropertyID, const String&, bool important, StyleSheetContents* contextStyleSheet);
PassRefPtr<ImmutableStylePropertySet> parseDeclaration(const String&, StyleSheetContents* contextStyleSheet);
@@ -605,57 +531,35 @@ private:
bool parseColor(const String&);
- enum ParsingMode {
- NormalMode,
- MediaQueryMode,
- SupportsMode,
- NthChildMode
- };
-
- ParsingMode m_parsingMode;
- bool m_is8BitSource;
- OwnArrayPtr<LChar> m_dataStart8;
- OwnArrayPtr<UChar> m_dataStart16;
- LChar* m_currentCharacter8;
- UChar* m_currentCharacter16;
const String* m_source;
- union {
- LChar* ptr8;
- UChar* ptr16;
- } m_tokenStart;
- unsigned m_length;
- int m_token;
TextPosition m_startPosition;
- int m_lineNumber;
- int m_tokenStartLineNumber;
CSSRuleSourceData::Type m_ruleHeaderType;
unsigned m_ruleHeaderStartOffset;
int m_ruleHeaderStartLineNumber;
OwnPtr<Vector<unsigned> > m_lineEndings;
+ bool m_ruleHasHeader;
+
bool m_allowImportRules;
bool m_allowNamespaceDeclarations;
bool parseViewportProperty(CSSPropertyID propId, bool important);
bool parseViewportShorthand(CSSPropertyID propId, CSSPropertyID first, CSSPropertyID second, bool important);
- bool inViewport() const { return m_inViewport; }
bool m_inViewport;
CSSParserLocation m_locationLabel;
bool useLegacyBackgroundSizeShorthandBehavior() const;
- int (CSSParser::*m_lexFunc)(void*);
-
Vector<RefPtr<StyleRuleBase> > m_parsedRules;
Vector<RefPtr<StyleKeyframe> > m_parsedKeyframes;
Vector<RefPtr<MediaQuerySet> > m_parsedMediaQuerySets;
Vector<OwnPtr<RuleList> > m_parsedRuleLists;
- HashSet<CSSParserSelector*> m_floatingSelectors;
- HashSet<Vector<OwnPtr<CSSParserSelector> >*> m_floatingSelectorVectors;
- HashSet<CSSParserValueList*> m_floatingValueLists;
- HashSet<CSSParserFunction*> m_floatingFunctions;
+ Vector<CSSParserSelector*> m_floatingSelectors;
+ Vector<Vector<OwnPtr<CSSParserSelector> >*> m_floatingSelectorVectors;
+ Vector<CSSParserValueList*> m_floatingValueLists;
+ Vector<CSSParserFunction*> m_floatingFunctions;
OwnPtr<MediaQuery> m_floatingMediaQuery;
OwnPtr<MediaQueryExp> m_floatingMediaQueryExp;
@@ -703,7 +607,7 @@ private:
bool shouldAcceptUnitLessValues(CSSParserValue*, Units, CSSParserMode);
- inline bool validUnit(CSSParserValue* value, Units unitflags, ReleaseParsedCalcValueCondition releaseCalc = DoNotReleaseParsedCalcValue) { return validUnit(value, unitflags, m_context.mode, releaseCalc); }
+ inline bool validUnit(CSSParserValue* value, Units unitflags, ReleaseParsedCalcValueCondition releaseCalc = DoNotReleaseParsedCalcValue) { return validUnit(value, unitflags, m_context.mode(), releaseCalc); }
bool validUnit(CSSParserValue*, Units, CSSParserMode, ReleaseParsedCalcValueCondition releaseCalc = DoNotReleaseParsedCalcValue);
bool parseBorderImageQuad(Units, RefPtr<CSSPrimitiveValue>&);
@@ -711,10 +615,10 @@ private:
double parsedDouble(CSSParserValue*, ReleaseParsedCalcValueCondition releaseCalc = DoNotReleaseParsedCalcValue);
bool isCalculation(CSSParserValue*);
- inline unsigned safeUserStringTokenOffset();
-
UseCounter* m_useCounter;
+ CSSTokenizer m_tokenizer;
+
friend class TransformOperationInfo;
friend class FilterOperationInfo;
};
@@ -762,35 +666,9 @@ String quoteCSSURLIfNeeded(const String&);
bool isValidNthToken(const CSSParserString&);
-template <>
-inline void CSSParser::setTokenStart<LChar>(LChar* tokenStart)
-{
- m_tokenStart.ptr8 = tokenStart;
-}
-
-template <>
-inline void CSSParser::setTokenStart<UChar>(UChar* tokenStart)
-{
- m_tokenStart.ptr16 = tokenStart;
-}
-
-inline unsigned CSSParser::tokenStartOffset()
-{
- if (is8BitSource())
- return m_tokenStart.ptr8 - m_dataStart8.get();
- return m_tokenStart.ptr16 - m_dataStart16.get();
-}
-
-inline UChar CSSParser::tokenStartChar()
-{
- if (is8BitSource())
- return *m_tokenStart.ptr8;
- return *m_tokenStart.ptr16;
-}
-
inline int cssyylex(void* yylval, CSSParser* parser)
{
- return parser->lex(yylval);
+ return parser->m_tokenizer.lex(yylval);
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSParserMode.cpp b/chromium/third_party/WebKit/Source/core/css/CSSParserMode.cpp
new file mode 100644
index 00000000000..b4d94f8a135
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/css/CSSParserMode.cpp
@@ -0,0 +1,66 @@
+/*
+ * Copyright (C) 2003 Lars Knoll (knoll@kde.org)
+ * Copyright (C) 2005 Allan Sandfeld Jensen (kde@carewolf.com)
+ * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 Apple Inc. All rights reserved.
+ * Copyright (C) 2007 Nicholas Shanks <webkit@nickshanks.com>
+ * Copyright (C) 2008 Eric Seidel <eric@webkit.org>
+ * Copyright (C) 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
+ * Copyright (C) 2012 Adobe Systems Incorporated. All rights reserved.
+ * Copyright (C) 2012 Intel Corporation. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#include "config.h"
+#include "core/css/CSSParserMode.h"
+
+#include "core/dom/Document.h"
+#include "core/frame/Settings.h"
+
+namespace WebCore {
+
+CSSParserContext::CSSParserContext(CSSParserMode mode)
+ : m_mode(mode)
+ , m_isHTMLDocument(false)
+ , m_useLegacyBackgroundSizeShorthandBehavior(false)
+{
+}
+
+CSSParserContext::CSSParserContext(const Document& document, const KURL& baseURL, const String& charset)
+ : m_baseURL(baseURL.isNull() ? document.baseURL() : baseURL)
+ , m_charset(charset)
+ , m_mode(document.inQuirksMode() ? HTMLQuirksMode : HTMLStandardMode)
+ , m_isHTMLDocument(document.isHTMLDocument())
+ , m_useLegacyBackgroundSizeShorthandBehavior(document.settings() ? document.settings()->useLegacyBackgroundSizeShorthandBehavior() : false)
+{
+}
+
+bool CSSParserContext::operator==(const CSSParserContext& other) const
+{
+ return m_baseURL == other.m_baseURL
+ && m_charset == other.m_charset
+ && m_mode == other.m_mode
+ && m_isHTMLDocument == other.m_isHTMLDocument
+ && m_useLegacyBackgroundSizeShorthandBehavior == other.m_useLegacyBackgroundSizeShorthandBehavior;
+}
+
+const CSSParserContext& strictCSSParserContext()
+{
+ DEFINE_STATIC_LOCAL(CSSParserContext, strictContext, (HTMLStandardMode));
+ return strictContext;
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSParserMode.h b/chromium/third_party/WebKit/Source/core/css/CSSParserMode.h
index cf981a75aec..efcac21a195 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSParserMode.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSParserMode.h
@@ -31,60 +31,95 @@
#ifndef CSSParserMode_h
#define CSSParserMode_h
-#include "weborigin/KURL.h"
+#include "platform/weborigin/KURL.h"
namespace WebCore {
class Document;
+// Must not grow beyond 3 bytes, due to packing in StylePropertySet.
enum CSSParserMode {
- CSSQuirksMode,
- CSSStrictMode,
- // SVG should always be in strict mode. For SVG attributes, the rules differ to strict sometimes.
+ HTMLStandardMode,
+ HTMLQuirksMode,
+ // HTML attributes are parsed in quirks mode but also allows internal properties and values.
+ HTMLAttributeMode,
+ // SVG attributes are parsed in quirks mode but rules differ slightly.
SVGAttributeMode,
- // CSS attribute are parsed in quirks mode. They also allow internal only properties and values.
- CSSAttributeMode,
- // User agent style sheet should always be in strict mode. Enables internal
- // only properties and values.
- UASheetMode,
- // Parsing @viewport descriptors. Always strict. Set as mode on StylePropertySet
- // to make sure CSSOM modifications use CSSParser::parseViewportProperty.
- ViewportMode
+ // @viewport rules are parsed in standards mode but CSSOM modifications (via StylePropertySet)
+ // must call parseViewportProperties so needs a special mode.
+ CSSViewportRuleMode,
+ // User agent stylesheets are parsed in standards mode but also allows internal properties and values.
+ UASheetMode
};
-inline CSSParserMode strictToCSSParserMode(bool inStrictMode)
+inline bool isQuirksModeBehavior(CSSParserMode mode)
{
- return inStrictMode ? CSSStrictMode : CSSQuirksMode;
+ return mode == HTMLQuirksMode; // || mode == HTMLAttributeMode;
}
-inline bool isStrictParserMode(CSSParserMode cssParserMode)
+inline bool isUASheetBehavior(CSSParserMode mode)
{
- return cssParserMode != CSSQuirksMode;
+ return mode == UASheetMode;
}
-struct CSSParserContext {
+inline bool isInternalPropertyAndValueParsingEnabledForMode(CSSParserMode mode)
+{
+ return mode == HTMLAttributeMode || mode == UASheetMode;
+}
+
+inline bool isUnitLessLengthParsingEnabledForMode(CSSParserMode mode)
+{
+ return mode == HTMLQuirksMode || mode == HTMLAttributeMode || mode == SVGAttributeMode;
+}
+
+inline bool isCSSViewportParsingEnabledForMode(CSSParserMode mode)
+{
+ return mode == CSSViewportRuleMode;
+}
+
+inline bool isSVGNumberParsingEnabledForMode(CSSParserMode mode)
+{
+ return mode == SVGAttributeMode;
+}
+
+inline bool isUseCounterEnabledForMode(CSSParserMode mode)
+{
+ // We don't count the UA style sheet in our statistics.
+ return mode != UASheetMode;
+}
+
+class CSSParserContext {
WTF_MAKE_FAST_ALLOCATED;
public:
- CSSParserContext(CSSParserMode, const KURL& baseURL = KURL());
+ CSSParserContext(CSSParserMode);
CSSParserContext(const Document&, const KURL& baseURL = KURL(), const String& charset = emptyString());
- KURL baseURL;
- String charset;
- CSSParserMode mode;
- bool isHTMLDocument;
- bool isCSSCustomFilterEnabled;
- bool isCSSStickyPositionEnabled;
- bool isCSSCompositingEnabled;
- bool isCSSTouchActionEnabled;
- bool needsSiteSpecificQuirks;
+ bool operator==(const CSSParserContext&) const;
+ bool operator!=(const CSSParserContext& other) const { return !(*this == other); }
+
+ CSSParserMode mode() const { return m_mode; }
+ const KURL& baseURL() const { return m_baseURL; }
+ const String& charset() const { return m_charset; }
+ bool isHTMLDocument() const { return m_isHTMLDocument; }
+
// This quirk is to maintain compatibility with Android apps built on
// the Android SDK prior to and including version 18. Presumably, this
// can be removed any time after 2015. See http://crbug.com/277157.
- bool useLegacyBackgroundSizeShorthandBehavior;
-};
+ bool useLegacyBackgroundSizeShorthandBehavior() const { return m_useLegacyBackgroundSizeShorthandBehavior; }
-bool operator==(const CSSParserContext&, const CSSParserContext&);
-inline bool operator!=(const CSSParserContext& a, const CSSParserContext& b) { return !(a == b); }
+ // FIXME: These setters shouldn't exist, however the current lifetime of CSSParserContext
+ // is not well understood and thus we sometimes need to override these fields.
+ void setMode(CSSParserMode mode) { m_mode = mode; }
+ void setBaseURL(const KURL& baseURL) { m_baseURL = baseURL; }
+ void setCharset(const String& charset) { m_charset = charset; }
+
+private:
+ KURL m_baseURL;
+ String m_charset;
+ CSSParserMode m_mode;
+ bool m_isHTMLDocument;
+ bool m_useLegacyBackgroundSizeShorthandBehavior;
+};
const CSSParserContext& strictCSSParserContext();
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSParserValues.cpp b/chromium/third_party/WebKit/Source/core/css/CSSParserValues.cpp
index 9863e9a5962..10a940a6588 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSParserValues.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/CSSParserValues.cpp
@@ -22,20 +22,41 @@
#include "core/css/CSSParserValues.h"
#include "core/css/CSSFunctionValue.h"
-#include "core/css/CSSPrimitiveValue.h"
-#include "core/css/CSSSelector.h"
#include "core/css/CSSSelectorList.h"
+#include "core/html/parser/HTMLParserIdioms.h"
namespace WebCore {
using namespace WTF;
+AtomicString CSSParserString::atomicSubstring(unsigned position, unsigned length) const
+{
+ ASSERT(m_length >= position + length);
+
+ if (is8Bit())
+ return AtomicString(characters8() + position, length);
+ return AtomicString(characters16() + position, length);
+}
+
+void CSSParserString::trimTrailingWhitespace()
+{
+ if (is8Bit()) {
+ while (m_length > 0 && isHTMLSpace<LChar>(m_data.characters8[m_length - 1]))
+ --m_length;
+ } else {
+ while (m_length > 0 && isHTMLSpace<UChar>(m_data.characters16[m_length - 1]))
+ --m_length;
+ }
+}
+
CSSParserValueList::~CSSParserValueList()
{
size_t numValues = m_values.size();
for (size_t i = 0; i < numValues; i++) {
if (m_values[i].unit == CSSParserValue::Function)
delete m_values[i].function;
+ else if (m_values[i].unit == CSSParserValue::ValueList)
+ delete m_values[i].valueList;
}
}
@@ -73,6 +94,8 @@ PassRefPtr<CSSValue> CSSParserValue::createCSSValue()
}
if (unit == CSSParserValue::Function)
return CSSFunctionValue::create(function);
+ if (unit == CSSParserValue::ValueList)
+ return CSSValueList::createFromParserValueList(valueList);
if (unit >= CSSParserValue::Q_EMS)
return CSSPrimitiveValue::createAllowingMarginQuirk(fValue, CSSPrimitiveValue::CSS_EMS);
@@ -234,5 +257,4 @@ CSSParserSelector* CSSParserSelector::findDistributedPseudoElementSelector() con
return 0;
}
-}
-
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSParserValues.h b/chromium/third_party/WebKit/Source/core/css/CSSParserValues.h
index 0aafa37c1bb..8efd3250dcf 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSParserValues.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSParserValues.h
@@ -131,6 +131,12 @@ struct CSSParserString {
bool m_is8Bit;
};
+template <>
+inline const LChar* CSSParserString::characters<LChar>() const { return characters8(); }
+
+template <>
+inline const UChar* CSSParserString::characters<UChar>() const { return characters16(); }
+
struct CSSParserFunction;
struct CSSParserValue {
@@ -141,16 +147,19 @@ struct CSSParserValue {
int iValue;
CSSParserString string;
CSSParserFunction* function;
+ CSSParserValueList* valueList;
};
enum {
- Operator = 0x100000,
- Function = 0x100001,
- Q_EMS = 0x100002
+ Operator = 0x100000,
+ Function = 0x100001,
+ ValueList = 0x100002,
+ Q_EMS = 0x100003,
};
int unit;
inline void setFromNumber(double value, int unit = CSSPrimitiveValue::CSS_NUMBER);
inline void setFromFunction(CSSParserFunction*);
+ inline void setFromValueList(PassOwnPtr<CSSParserValueList>);
PassRefPtr<CSSValue> createCSSValue();
};
@@ -215,7 +224,6 @@ public:
void setForPage() { m_selector->setForPage(); }
void setRelationIsAffectedByPseudoContent() { m_selector->setRelationIsAffectedByPseudoContent(); }
bool relationIsAffectedByPseudoContent() const { return m_selector->relationIsAffectedByPseudoContent(); }
- void setMatchUserAgentOnly() { m_selector->setMatchUserAgentOnly(); }
void adoptSelectorVector(Vector<OwnPtr<CSSParserSelector> >& selectorVector);
@@ -254,7 +262,10 @@ inline void CSSParserValue::setFromNumber(double value, int unit)
{
id = CSSValueInvalid;
isInt = false;
- fValue = value;
+ if (std::isfinite(value))
+ fValue = value;
+ else
+ fValue = 0;
this->unit = unit;
}
@@ -265,6 +276,13 @@ inline void CSSParserValue::setFromFunction(CSSParserFunction* function)
unit = Function;
}
+inline void CSSParserValue::setFromValueList(PassOwnPtr<CSSParserValueList> valueList)
+{
+ id = CSSValueInvalid;
+ this->valueList = valueList.leakPtr();
+ unit = ValueList;
+}
+
}
#endif
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSPrimitiveValue.cpp b/chromium/third_party/WebKit/Source/core/css/CSSPrimitiveValue.cpp
index 9a5741efa55..eb350e7a9c0 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSPrimitiveValue.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/CSSPrimitiveValue.cpp
@@ -21,13 +21,12 @@
#include "config.h"
#include "core/css/CSSPrimitiveValue.h"
-#include "CSSPropertyNames.h"
-#include "CSSValueKeywords.h"
#include "bindings/v8/ExceptionState.h"
#include "core/css/CSSBasicShapes.h"
#include "core/css/CSSCalculationValue.h"
#include "core/css/CSSHelper.h"
#include "core/css/CSSParser.h"
+#include "core/css/CSSToLengthConversionData.h"
#include "core/css/Counter.h"
#include "core/css/Pair.h"
#include "core/css/RGBColor.h"
@@ -35,9 +34,8 @@
#include "core/css/StyleSheetContents.h"
#include "core/dom/ExceptionCode.h"
#include "core/dom/Node.h"
-#include "core/platform/LayoutUnit.h"
-#include "core/platform/graphics/Color.h"
#include "core/rendering/style/RenderStyle.h"
+#include "platform/LayoutUnit.h"
#include "wtf/DecimalNumber.h"
#include "wtf/StdLibExtras.h"
#include "wtf/text/StringBuffer.h"
@@ -275,7 +273,7 @@ CSSPrimitiveValue::CSSPrimitiveValue(RGBA32 color)
m_value.rgbcolor = color;
}
-CSSPrimitiveValue::CSSPrimitiveValue(const Length& length, const RenderStyle* style)
+CSSPrimitiveValue::CSSPrimitiveValue(const Length& length, float zoom)
: CSSValue(PrimitiveClass)
{
switch (length.type()) {
@@ -296,12 +294,11 @@ CSSPrimitiveValue::CSSPrimitiveValue(const Length& length, const RenderStyle* st
return;
case Fixed:
m_primitiveUnitType = CSS_PX;
- m_value.num = adjustFloatForAbsoluteZoom(length.value(), style);
+ m_value.num = length.value() / zoom;
return;
case Calculated:
- init(CSSCalcValue::create(length.calculationValue().get(), style));
+ init(CSSCalcValue::create(length.calculationValue(), zoom));
return;
- case Relative:
case Undefined:
ASSERT_NOT_REACHED();
break;
@@ -369,7 +366,6 @@ void CSSPrimitiveValue::init(const Length& length)
m_value.num = length.viewportPercentageLength();
break;
case Calculated:
- case Relative:
case Undefined:
ASSERT_NOT_REACHED();
break;
@@ -521,89 +517,88 @@ double CSSPrimitiveValue::computeDegrees()
}
}
-template<> int CSSPrimitiveValue::computeLength(const RenderStyle* style, const RenderStyle* rootStyle, float multiplier, bool computingFontSize)
+template<> int CSSPrimitiveValue::computeLength(const CSSToLengthConversionData& conversionData)
{
- return roundForImpreciseConversion<int>(computeLengthDouble(style, rootStyle, multiplier, computingFontSize));
+ return roundForImpreciseConversion<int>(computeLengthDouble(conversionData));
}
-template<> unsigned CSSPrimitiveValue::computeLength(const RenderStyle* style, const RenderStyle* rootStyle, float multiplier, bool computingFontSize)
+template<> unsigned CSSPrimitiveValue::computeLength(const CSSToLengthConversionData& conversionData)
{
- return roundForImpreciseConversion<unsigned>(computeLengthDouble(style, rootStyle, multiplier, computingFontSize));
+ return roundForImpreciseConversion<unsigned>(computeLengthDouble(conversionData));
}
-template<> Length CSSPrimitiveValue::computeLength(const RenderStyle* style, const RenderStyle* rootStyle, float multiplier, bool computingFontSize)
+template<> Length CSSPrimitiveValue::computeLength(const CSSToLengthConversionData& conversionData)
{
- return Length(clampTo<float>(computeLengthDouble(style, rootStyle, multiplier, computingFontSize), minValueForCssLength, maxValueForCssLength), Fixed);
+ return Length(clampTo<float>(computeLengthDouble(conversionData), minValueForCssLength, maxValueForCssLength), Fixed);
}
-template<> short CSSPrimitiveValue::computeLength(const RenderStyle* style, const RenderStyle* rootStyle, float multiplier, bool computingFontSize)
+template<> short CSSPrimitiveValue::computeLength(const CSSToLengthConversionData& conversionData)
{
- return roundForImpreciseConversion<short>(computeLengthDouble(style, rootStyle, multiplier, computingFontSize));
+ return roundForImpreciseConversion<short>(computeLengthDouble(conversionData));
}
-template<> unsigned short CSSPrimitiveValue::computeLength(const RenderStyle* style, const RenderStyle* rootStyle, float multiplier, bool computingFontSize)
+template<> unsigned short CSSPrimitiveValue::computeLength(const CSSToLengthConversionData& conversionData)
{
- return roundForImpreciseConversion<unsigned short>(computeLengthDouble(style, rootStyle, multiplier, computingFontSize));
+ return roundForImpreciseConversion<unsigned short>(computeLengthDouble(conversionData));
}
-template<> float CSSPrimitiveValue::computeLength(const RenderStyle* style, const RenderStyle* rootStyle, float multiplier, bool computingFontSize)
+template<> float CSSPrimitiveValue::computeLength(const CSSToLengthConversionData& conversionData)
{
- return static_cast<float>(computeLengthDouble(style, rootStyle, multiplier, computingFontSize));
+ return static_cast<float>(computeLengthDouble(conversionData));
}
-template<> double CSSPrimitiveValue::computeLength(const RenderStyle* style, const RenderStyle* rootStyle, float multiplier, bool computingFontSize)
+template<> double CSSPrimitiveValue::computeLength(const CSSToLengthConversionData& conversionData)
{
- return computeLengthDouble(style, rootStyle, multiplier, computingFontSize);
+ return computeLengthDouble(conversionData);
}
-double CSSPrimitiveValue::computeLengthDouble(const RenderStyle* style, const RenderStyle* rootStyle, float multiplier, bool computingFontSize)
+double CSSPrimitiveValue::computeLengthDouble(const CSSToLengthConversionData& conversionData)
{
if (m_primitiveUnitType == CSS_CALC)
- // The multiplier and factor is applied to each value in the calc expression individually
- return m_value.calc->computeLengthPx(style, rootStyle, multiplier, computingFontSize);
+ return m_value.calc->computeLengthPx(conversionData);
+
+ const RenderStyle& style = conversionData.style();
+ const RenderStyle& rootStyle = conversionData.rootStyle();
+ bool computingFontSize = conversionData.computingFontSize();
double factor;
switch (primitiveType()) {
case CSS_EMS:
- factor = computingFontSize ? style->fontDescription().specifiedSize() : style->fontDescription().computedSize();
+ factor = computingFontSize ? style.fontDescription().specifiedSize() : style.fontDescription().computedSize();
break;
case CSS_EXS:
// FIXME: We have a bug right now where the zoom will be applied twice to EX units.
// We really need to compute EX using fontMetrics for the original specifiedSize and not use
// our actual constructed rendering font.
- if (style->fontMetrics().hasXHeight())
- factor = style->fontMetrics().xHeight();
+ if (style.fontMetrics().hasXHeight())
+ factor = style.fontMetrics().xHeight();
else
- factor = (computingFontSize ? style->fontDescription().specifiedSize() : style->fontDescription().computedSize()) / 2.0;
+ factor = (computingFontSize ? style.fontDescription().specifiedSize() : style.fontDescription().computedSize()) / 2.0;
break;
case CSS_REMS:
- if (rootStyle)
- factor = computingFontSize ? rootStyle->fontDescription().specifiedSize() : rootStyle->fontDescription().computedSize();
- else
- factor = 1.0;
+ factor = computingFontSize ? rootStyle.fontDescription().specifiedSize() : rootStyle.fontDescription().computedSize();
break;
case CSS_CHS:
- factor = style->fontMetrics().zeroWidth();
+ factor = style.fontMetrics().zeroWidth();
break;
case CSS_PX:
factor = 1.0;
break;
case CSS_CM:
- factor = cssPixelsPerInch / 2.54; // (2.54 cm/in)
+ factor = cssPixelsPerCentimeter;
break;
case CSS_MM:
- factor = cssPixelsPerInch / 25.4;
+ factor = cssPixelsPerMillimeter;
break;
case CSS_IN:
factor = cssPixelsPerInch;
break;
case CSS_PT:
- factor = cssPixelsPerInch / 72.0;
+ factor = cssPixelsPerPoint;
break;
case CSS_PC:
- // 1 pc == 12 pt
- factor = cssPixelsPerInch * 12.0 / 72.0;
+ factor = cssPixelsPerPica;
break;
case CSS_CALC_PERCENTAGE_WITH_LENGTH:
case CSS_CALC_PERCENTAGE_WITH_NUMBER:
@@ -621,15 +616,15 @@ double CSSPrimitiveValue::computeLengthDouble(const RenderStyle* style, const Re
if (computingFontSize || isFontRelativeLength())
return result;
- return result * multiplier;
+ return result * conversionData.zoom();
}
-void CSSPrimitiveValue::setFloatValue(unsigned short, double, ExceptionState& es)
+void CSSPrimitiveValue::setFloatValue(unsigned short, double, ExceptionState& exceptionState)
{
// Keeping values immutable makes optimizations easier and allows sharing of the primitive value objects.
// No other engine supports mutating style through this API. Computed style is always read-only anyway.
// Supporting setter would require making primitive value copy-on-write and taking care of style invalidation.
- es.throwDOMException(NoModificationAllowedError);
+ exceptionState.throwUninformativeAndGenericDOMException(NoModificationAllowedError);
}
double CSSPrimitiveValue::conversionToCanonicalUnitsScaleFactor(unsigned short unitType)
@@ -644,13 +639,13 @@ double CSSPrimitiveValue::conversionToCanonicalUnitsScaleFactor(unsigned short u
case CSS_HZ:
break;
case CSS_CM:
- factor = cssPixelsPerInch / 2.54; // (2.54 cm/in)
+ factor = cssPixelsPerCentimeter;
break;
case CSS_DPCM:
- factor = 2.54 / cssPixelsPerInch; // (2.54 cm/in)
+ factor = 1 / cssPixelsPerCentimeter;
break;
case CSS_MM:
- factor = cssPixelsPerInch / 25.4;
+ factor = cssPixelsPerMillimeter;
break;
case CSS_IN:
factor = cssPixelsPerInch;
@@ -659,10 +654,10 @@ double CSSPrimitiveValue::conversionToCanonicalUnitsScaleFactor(unsigned short u
factor = 1 / cssPixelsPerInch;
break;
case CSS_PT:
- factor = cssPixelsPerInch / 72.0;
+ factor = cssPixelsPerPoint;
break;
case CSS_PC:
- factor = cssPixelsPerInch * 12.0 / 72.0; // 1 pc == 12 pt
+ factor = cssPixelsPerPica;
break;
case CSS_RAD:
factor = 180 / piDouble;
@@ -684,12 +679,12 @@ double CSSPrimitiveValue::conversionToCanonicalUnitsScaleFactor(unsigned short u
return factor;
}
-double CSSPrimitiveValue::getDoubleValue(unsigned short unitType, ExceptionState& es) const
+double CSSPrimitiveValue::getDoubleValue(unsigned short unitType, ExceptionState& exceptionState) const
{
double result = 0;
bool success = getDoubleValueInternal(static_cast<UnitTypes>(unitType), &result);
if (!success) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return 0.0;
}
@@ -784,15 +779,15 @@ bool CSSPrimitiveValue::getDoubleValueInternal(UnitTypes requestedUnitType, doub
return true;
}
-void CSSPrimitiveValue::setStringValue(unsigned short, const String&, ExceptionState& es)
+void CSSPrimitiveValue::setStringValue(unsigned short, const String&, ExceptionState& exceptionState)
{
// Keeping values immutable makes optimizations easier and allows sharing of the primitive value objects.
// No other engine supports mutating style through this API. Computed style is always read-only anyway.
// Supporting setter would require making primitive value copy-on-write and taking care of style invalidation.
- es.throwDOMException(NoModificationAllowedError);
+ exceptionState.throwUninformativeAndGenericDOMException(NoModificationAllowedError);
}
-String CSSPrimitiveValue::getStringValue(ExceptionState& es) const
+String CSSPrimitiveValue::getStringValue(ExceptionState& exceptionState) const
{
switch (m_primitiveUnitType) {
case CSS_STRING:
@@ -805,7 +800,7 @@ String CSSPrimitiveValue::getStringValue(ExceptionState& es) const
case CSS_PROPERTY_ID:
return propertyName(m_value.propertyID);
default:
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
break;
}
@@ -831,40 +826,40 @@ String CSSPrimitiveValue::getStringValue() const
return String();
}
-Counter* CSSPrimitiveValue::getCounterValue(ExceptionState& es) const
+Counter* CSSPrimitiveValue::getCounterValue(ExceptionState& exceptionState) const
{
if (m_primitiveUnitType != CSS_COUNTER) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return 0;
}
return m_value.counter;
}
-Rect* CSSPrimitiveValue::getRectValue(ExceptionState& es) const
+Rect* CSSPrimitiveValue::getRectValue(ExceptionState& exceptionState) const
{
if (m_primitiveUnitType != CSS_RECT) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return 0;
}
return m_value.rect;
}
-Quad* CSSPrimitiveValue::getQuadValue(ExceptionState& es) const
+Quad* CSSPrimitiveValue::getQuadValue(ExceptionState& exceptionState) const
{
if (m_primitiveUnitType != CSS_QUAD) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return 0;
}
return m_value.quad;
}
-PassRefPtr<RGBColor> CSSPrimitiveValue::getRGBColorValue(ExceptionState& es) const
+PassRefPtr<RGBColor> CSSPrimitiveValue::getRGBColorValue(ExceptionState& exceptionState) const
{
if (m_primitiveUnitType != CSS_RGBCOLOR) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return 0;
}
@@ -872,10 +867,10 @@ PassRefPtr<RGBColor> CSSPrimitiveValue::getRGBColorValue(ExceptionState& es) con
return RGBColor::create(m_value.rgbcolor);
}
-Pair* CSSPrimitiveValue::getPairValue(ExceptionState& es) const
+Pair* CSSPrimitiveValue::getPairValue(ExceptionState& exceptionState) const
{
if (m_primitiveUnitType != CSS_PAIR) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return 0;
}
@@ -902,7 +897,7 @@ ALWAYS_INLINE static String formatNumber(double number, const char (&characters)
return formatNumber(number, characters, characterCount - 1);
}
-String CSSPrimitiveValue::customCssText(CssTextFormattingFlags formattingFlag) const
+String CSSPrimitiveValue::customCSSText(CSSTextFormattingFlags formattingFlag) const
{
// FIXME: return the original value instead of a generated one (e.g. color
// name if it was specified) - check what spec says about this
@@ -1124,8 +1119,11 @@ String CSSPrimitiveValue::customCssText(CssTextFormattingFlags formattingFlag) c
String CSSPrimitiveValue::customSerializeResolvingVariables(const HashMap<AtomicString, String>& variables) const
{
- if (isVariableName() && variables.contains(m_value.string))
- return variables.get(m_value.string);
+ if (isVariableName()) {
+ AtomicString variableName(m_value.string);
+ if (variables.contains(variableName))
+ return variables.get(variableName);
+ }
if (CSSCalcValue* calcValue = cssCalcValue())
return calcValue->customSerializeResolvingVariables(variables);
if (Pair* pairValue = getPairValue())
@@ -1136,7 +1134,7 @@ String CSSPrimitiveValue::customSerializeResolvingVariables(const HashMap<Atomic
return quadVal->serializeResolvingVariables(variables);
if (CSSBasicShape* shapeValue = getShapeValue())
return shapeValue->serializeResolvingVariables(variables);
- return customCssText();
+ return customCSSText();
}
bool CSSPrimitiveValue::hasVariableReference() const
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSPrimitiveValue.h b/chromium/third_party/WebKit/Source/core/css/CSSPrimitiveValue.h
index 4d2e614787a..65b1cfbf66f 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSPrimitiveValue.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSPrimitiveValue.h
@@ -25,7 +25,7 @@
#include "CSSPropertyNames.h"
#include "CSSValueKeywords.h"
#include "core/css/CSSValue.h"
-#include "core/platform/graphics/Color.h"
+#include "platform/graphics/Color.h"
#include "wtf/Forward.h"
#include "wtf/MathExtras.h"
#include "wtf/PassRefPtr.h"
@@ -34,16 +34,16 @@ namespace WebCore {
class CSSBasicShape;
class CSSCalcValue;
+class CSSToLengthConversionData;
class Counter;
class ExceptionState;
+class Length;
class Pair;
class Quad;
class RGBColor;
class Rect;
class RenderStyle;
-struct Length;
-
// Dimension calculations are imprecise, often resulting in values of e.g.
// 44.99998. We need to go ahead and round if we're really close to the next
// integer value.
@@ -204,7 +204,7 @@ public:
static PassRefPtr<CSSPrimitiveValue> createColor(unsigned rgbValue) { return adoptRef(new CSSPrimitiveValue(rgbValue)); }
static PassRefPtr<CSSPrimitiveValue> create(double value, UnitTypes type) { return adoptRef(new CSSPrimitiveValue(value, type)); }
static PassRefPtr<CSSPrimitiveValue> create(const String& value, UnitTypes type) { return adoptRef(new CSSPrimitiveValue(value, type)); }
- static PassRefPtr<CSSPrimitiveValue> create(const Length& value, const RenderStyle* style) { return adoptRef(new CSSPrimitiveValue(value, style)); }
+ static PassRefPtr<CSSPrimitiveValue> create(const Length& value, float zoom) { return adoptRef(new CSSPrimitiveValue(value, zoom)); }
template<typename T> static PassRefPtr<CSSPrimitiveValue> create(T value)
{
@@ -246,8 +246,7 @@ public:
}
/*
- * computes a length in pixels out of the given CSSValue. Need the RenderStyle to get
- * the fontinfo in case val is defined in em or ex.
+ * Computes a length in pixels out of the given CSSValue
*
* The metrics have to be a bit different for screen and printer output.
* For screen output we assume 1 inch == 72 px, for printer we assume 300 dpi
@@ -255,10 +254,10 @@ public:
* this is screen/printer dependent, so we probably need a config option for this,
* and some tool to calibrate.
*/
- template<typename T> T computeLength(const RenderStyle* currStyle, const RenderStyle* rootStyle, float multiplier = 1.0f, bool computingFontSize = false);
+ template<typename T> T computeLength(const CSSToLengthConversionData&);
// Converts to a Length, mapping various unit types appropriately.
- template<int> Length convertToLength(const RenderStyle* currStyle, const RenderStyle* rootStyle, double multiplier = 1.0, bool computingFontSize = false);
+ template<int> Length convertToLength(const CSSToLengthConversionData&);
// use with care!!!
void setPrimitiveType(unsigned short type) { m_primitiveUnitType = type; }
@@ -268,15 +267,15 @@ public:
double getDoubleValue() const;
void setFloatValue(unsigned short unitType, double floatValue, ExceptionState&);
- float getFloatValue(unsigned short unitType, ExceptionState& es) const { return getValue<float>(unitType, es); }
+ float getFloatValue(unsigned short unitType, ExceptionState& exceptionState) const { return getValue<float>(unitType, exceptionState); }
float getFloatValue(unsigned short unitType) const { return getValue<float>(unitType); }
float getFloatValue() const { return getValue<float>(); }
- int getIntValue(unsigned short unitType, ExceptionState& es) const { return getValue<int>(unitType, es); }
+ int getIntValue(unsigned short unitType, ExceptionState& exceptionState) const { return getValue<int>(unitType, exceptionState); }
int getIntValue(unsigned short unitType) const { return getValue<int>(unitType); }
int getIntValue() const { return getValue<int>(); }
- template<typename T> inline T getValue(unsigned short unitType, ExceptionState& es) const { return clampTo<T>(getDoubleValue(unitType, es)); }
+ template<typename T> inline T getValue(unsigned short unitType, ExceptionState& exceptionState) const { return clampTo<T>(getDoubleValue(unitType, exceptionState)); }
template<typename T> inline T getValue(unsigned short unitType) const { return clampTo<T>(getDoubleValue(unitType)); }
template<typename T> inline T getValue() const { return clampTo<T>(getDoubleValue()); }
@@ -308,7 +307,7 @@ public:
template<typename T> inline operator T() const; // Defined in CSSPrimitiveValueMappings.h
- String customCssText(CssTextFormattingFlags = QuoteCSSStringIfNeeded) const;
+ String customCSSText(CSSTextFormattingFlags = QuoteCSSStringIfNeeded) const;
String customSerializeResolvingVariables(const HashMap<AtomicString, String>&) const;
bool hasVariableReference() const;
@@ -337,7 +336,7 @@ private:
{
init(length);
}
- CSSPrimitiveValue(const Length&, const RenderStyle*);
+ CSSPrimitiveValue(const Length&, float zoom);
CSSPrimitiveValue(const String&, UnitTypes);
CSSPrimitiveValue(double, UnitTypes);
@@ -367,7 +366,7 @@ private:
void init(PassRefPtr<CSSCalcValue>);
bool getDoubleValueInternal(UnitTypes targetUnitType, double* result) const;
- double computeLengthDouble(const RenderStyle* currentStyle, const RenderStyle* rootStyle, float multiplier, bool computingFontSize);
+ double computeLengthDouble(const CSSToLengthConversionData&);
union {
CSSPropertyID propertyID;
@@ -385,20 +384,7 @@ private:
} m_value;
};
-inline CSSPrimitiveValue* toCSSPrimitiveValue(CSSValue* value)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!value || value->isPrimitiveValue());
- return static_cast<CSSPrimitiveValue*>(value);
-}
-
-inline const CSSPrimitiveValue* toCSSPrimitiveValue(const CSSValue* value)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!value || value->isPrimitiveValue());
- return static_cast<const CSSPrimitiveValue*>(value);
-}
-
-// Catch unneeded cast.
-void toCSSPrimitiveValue(const CSSPrimitiveValue*);
+DEFINE_CSS_VALUE_TYPE_CASTS(CSSPrimitiveValue, isPrimitiveValue());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSPrimitiveValueMappings.h b/chromium/third_party/WebKit/Source/core/css/CSSPrimitiveValueMappings.h
index 0de35fd03f4..3f386133793 100644..100755
--- a/chromium/third_party/WebKit/Source/core/css/CSSPrimitiveValueMappings.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSPrimitiveValueMappings.h
@@ -34,19 +34,20 @@
#include "core/css/CSSCalculationValue.h"
#include "core/css/CSSPrimitiveValue.h"
#include "core/css/CSSReflectionDirection.h"
-#include "core/platform/graphics/FontDescription.h"
-#include "core/platform/graphics/FontSmoothingMode.h"
-#include "core/platform/graphics/GraphicsTypes.h"
-#include "core/platform/Length.h"
-#include "core/platform/ThemeTypes.h"
-#include "core/platform/graphics/Path.h"
-#include "core/platform/graphics/TextRenderingMode.h"
-#include "core/platform/text/TextDirection.h"
-#include "core/platform/text/UnicodeBidi.h"
-#include "core/platform/text/WritingMode.h"
+#include "core/css/CSSToLengthConversionData.h"
#include "core/rendering/style/LineClampValue.h"
#include "core/rendering/style/RenderStyleConstants.h"
#include "core/rendering/style/SVGRenderStyleDefs.h"
+#include "platform/Length.h"
+#include "platform/ThemeTypes.h"
+#include "platform/fonts/FontDescription.h"
+#include "platform/fonts/FontSmoothingMode.h"
+#include "platform/fonts/TextRenderingMode.h"
+#include "platform/graphics/GraphicsTypes.h"
+#include "platform/graphics/Path.h"
+#include "platform/text/TextDirection.h"
+#include "platform/text/UnicodeBidi.h"
+#include "platform/text/WritingMode.h"
#include "wtf/MathExtras.h"
namespace WebCore {
@@ -176,6 +177,32 @@ template<> inline CSSPrimitiveValue::operator CSSReflectionDirection() const
return ReflectionBelow;
}
+template<> inline CSSPrimitiveValue::CSSPrimitiveValue(ColumnFill columnFill)
+ : CSSValue(PrimitiveClass)
+{
+ m_primitiveUnitType = CSS_VALUE_ID;
+ switch (columnFill) {
+ case ColumnFillAuto:
+ m_value.valueID = CSSValueAuto;
+ break;
+ case ColumnFillBalance:
+ m_value.valueID = CSSValueBalance;
+ break;
+ }
+}
+
+template<> inline CSSPrimitiveValue::operator ColumnFill() const
+{
+ if (m_primitiveUnitType == CSS_VALUE_ID) {
+ if (m_value.valueID == CSSValueBalance)
+ return ColumnFillBalance;
+ if (m_value.valueID == CSSValueAuto)
+ return ColumnFillAuto;
+ }
+ ASSERT_NOT_REACHED();
+ return ColumnFillBalance;
+}
+
template<> inline CSSPrimitiveValue::CSSPrimitiveValue(ColumnSpan columnSpan)
: CSSValue(PrimitiveClass)
{
@@ -1216,12 +1243,6 @@ template<> inline CSSPrimitiveValue::CSSPrimitiveValue(EDisplay e)
case LIST_ITEM:
m_value.valueID = CSSValueListItem;
break;
- case RUN_IN:
- m_value.valueID = CSSValueRunIn;
- break;
- case COMPACT:
- m_value.valueID = CSSValueCompact;
- break;
case INLINE_BLOCK:
m_value.valueID = CSSValueInlineBlock;
break;
@@ -2394,6 +2415,45 @@ template<> inline CSSPrimitiveValue::operator TextAlignLast() const
return TextAlignLastAuto;
}
+template<> inline CSSPrimitiveValue::CSSPrimitiveValue(TextJustify e)
+ : CSSValue(PrimitiveClass)
+{
+ m_primitiveUnitType = CSS_VALUE_ID;
+ switch (e) {
+ case TextJustifyAuto:
+ m_value.valueID = CSSValueAuto;
+ break;
+ case TextJustifyNone:
+ m_value.valueID = CSSValueNone;
+ break;
+ case TextJustifyInterWord:
+ m_value.valueID = CSSValueInterWord;
+ break;
+ case TextJustifyDistribute:
+ m_value.valueID = CSSValueDistribute;
+ break;
+ }
+}
+
+template<> inline CSSPrimitiveValue::operator TextJustify() const
+{
+ switch (m_value.valueID) {
+ case CSSValueAuto:
+ return TextJustifyAuto;
+ case CSSValueNone:
+ return TextJustifyNone;
+ case CSSValueInterWord:
+ return TextJustifyInterWord;
+ case CSSValueDistribute:
+ return TextJustifyDistribute;
+ default:
+ break;
+ }
+
+ ASSERT_NOT_REACHED();
+ return TextJustifyAuto;
+}
+
template<> inline CSSPrimitiveValue::operator TextDecoration() const
{
ASSERT(isValueID());
@@ -2438,7 +2498,6 @@ template<> inline CSSPrimitiveValue::operator TextDecorationStyle() const
return TextDecorationStyleSolid;
}
-#if ENABLE(CSS3_TEXT)
template<> inline CSSPrimitiveValue::CSSPrimitiveValue(TextUnderlinePosition e)
: CSSValue(PrimitiveClass)
{
@@ -2447,9 +2506,6 @@ template<> inline CSSPrimitiveValue::CSSPrimitiveValue(TextUnderlinePosition e)
case TextUnderlinePositionAuto:
m_value.valueID = CSSValueAuto;
break;
- case TextUnderlinePositionAlphabetic:
- m_value.valueID = CSSValueAlphabetic;
- break;
case TextUnderlinePositionUnder:
m_value.valueID = CSSValueUnder;
break;
@@ -2464,8 +2520,6 @@ template<> inline CSSPrimitiveValue::operator TextUnderlinePosition() const
switch (m_value.valueID) {
case CSSValueAuto:
return TextUnderlinePositionAuto;
- case CSSValueAlphabetic:
- return TextUnderlinePositionAlphabetic;
case CSSValueUnder:
return TextUnderlinePositionUnder;
default:
@@ -2477,7 +2531,6 @@ template<> inline CSSPrimitiveValue::operator TextUnderlinePosition() const
ASSERT_NOT_REACHED();
return TextUnderlinePositionAuto;
}
-#endif // CSS3_TEXT
template<> inline CSSPrimitiveValue::CSSPrimitiveValue(ETextSecurity e)
: CSSValue(PrimitiveClass)
@@ -3283,6 +3336,9 @@ template<> inline CSSPrimitiveValue::CSSPrimitiveValue(EPointerEvents e)
case PE_ALL:
m_value.valueID = CSSValueAll;
break;
+ case PE_BOUNDINGBOX:
+ m_value.valueID = CSSValueBoundingBox;
+ break;
}
}
@@ -3310,6 +3366,8 @@ template<> inline CSSPrimitiveValue::operator EPointerEvents() const
return PE_FILL;
case CSSValueStroke:
return PE_STROKE;
+ case CSSValueBoundingBox:
+ return PE_BOUNDINGBOX;
default:
break;
}
@@ -3398,6 +3456,26 @@ template<> inline CSSPrimitiveValue::operator ObjectFit() const
}
}
+template<> inline CSSPrimitiveValue::CSSPrimitiveValue(EFillSizeType fillSize)
+ : CSSValue(PrimitiveClass)
+{
+ m_primitiveUnitType = CSS_VALUE_ID;
+ switch (fillSize) {
+ case Contain:
+ m_value.valueID = CSSValueContain;
+ break;
+ case Cover:
+ m_value.valueID = CSSValueCover;
+ break;
+ case SizeNone:
+ m_value.valueID = CSSValueNone;
+ break;
+ case SizeLength:
+ default:
+ ASSERT_NOT_REACHED();
+ }
+}
+
template<> inline CSSPrimitiveValue::CSSPrimitiveValue(FontSmoothingMode smoothing)
: CSSValue(PrimitiveClass)
{
@@ -3764,104 +3842,104 @@ template<> inline CSSPrimitiveValue::operator ESpeak() const
return SpeakNormal;
}
-template<> inline CSSPrimitiveValue::CSSPrimitiveValue(BlendMode blendMode)
+template<> inline CSSPrimitiveValue::CSSPrimitiveValue(blink::WebBlendMode blendMode)
: CSSValue(PrimitiveClass)
{
m_primitiveUnitType = CSS_VALUE_ID;
switch (blendMode) {
- case BlendModeNormal:
+ case blink::WebBlendModeNormal:
m_value.valueID = CSSValueNormal;
break;
- case BlendModeMultiply:
+ case blink::WebBlendModeMultiply:
m_value.valueID = CSSValueMultiply;
break;
- case BlendModeScreen:
+ case blink::WebBlendModeScreen:
m_value.valueID = CSSValueScreen;
break;
- case BlendModeOverlay:
+ case blink::WebBlendModeOverlay:
m_value.valueID = CSSValueOverlay;
break;
- case BlendModeDarken:
+ case blink::WebBlendModeDarken:
m_value.valueID = CSSValueDarken;
break;
- case BlendModeLighten:
+ case blink::WebBlendModeLighten:
m_value.valueID = CSSValueLighten;
break;
- case BlendModeColorDodge:
+ case blink::WebBlendModeColorDodge:
m_value.valueID = CSSValueColorDodge;
break;
- case BlendModeColorBurn:
+ case blink::WebBlendModeColorBurn:
m_value.valueID = CSSValueColorBurn;
break;
- case BlendModeHardLight:
+ case blink::WebBlendModeHardLight:
m_value.valueID = CSSValueHardLight;
break;
- case BlendModeSoftLight:
+ case blink::WebBlendModeSoftLight:
m_value.valueID = CSSValueSoftLight;
break;
- case BlendModeDifference:
+ case blink::WebBlendModeDifference:
m_value.valueID = CSSValueDifference;
break;
- case BlendModeExclusion:
+ case blink::WebBlendModeExclusion:
m_value.valueID = CSSValueExclusion;
break;
- case BlendModeHue:
+ case blink::WebBlendModeHue:
m_value.valueID = CSSValueHue;
break;
- case BlendModeSaturation:
+ case blink::WebBlendModeSaturation:
m_value.valueID = CSSValueSaturation;
break;
- case BlendModeColor:
+ case blink::WebBlendModeColor:
m_value.valueID = CSSValueColor;
break;
- case BlendModeLuminosity:
+ case blink::WebBlendModeLuminosity:
m_value.valueID = CSSValueLuminosity;
break;
}
}
-template<> inline CSSPrimitiveValue::operator BlendMode() const
+template<> inline CSSPrimitiveValue::operator blink::WebBlendMode() const
{
ASSERT(isValueID());
switch (m_value.valueID) {
case CSSValueNormal:
- return BlendModeNormal;
+ return blink::WebBlendModeNormal;
case CSSValueMultiply:
- return BlendModeMultiply;
+ return blink::WebBlendModeMultiply;
case CSSValueScreen:
- return BlendModeScreen;
+ return blink::WebBlendModeScreen;
case CSSValueOverlay:
- return BlendModeOverlay;
+ return blink::WebBlendModeOverlay;
case CSSValueDarken:
- return BlendModeDarken;
+ return blink::WebBlendModeDarken;
case CSSValueLighten:
- return BlendModeLighten;
+ return blink::WebBlendModeLighten;
case CSSValueColorDodge:
- return BlendModeColorDodge;
+ return blink::WebBlendModeColorDodge;
case CSSValueColorBurn:
- return BlendModeColorBurn;
+ return blink::WebBlendModeColorBurn;
case CSSValueHardLight:
- return BlendModeHardLight;
+ return blink::WebBlendModeHardLight;
case CSSValueSoftLight:
- return BlendModeSoftLight;
+ return blink::WebBlendModeSoftLight;
case CSSValueDifference:
- return BlendModeDifference;
+ return blink::WebBlendModeDifference;
case CSSValueExclusion:
- return BlendModeExclusion;
+ return blink::WebBlendModeExclusion;
case CSSValueHue:
- return BlendModeHue;
+ return blink::WebBlendModeHue;
case CSSValueSaturation:
- return BlendModeSaturation;
+ return blink::WebBlendModeSaturation;
case CSSValueColor:
- return BlendModeColor;
+ return blink::WebBlendModeColor;
case CSSValueLuminosity:
- return BlendModeLuminosity;
+ return blink::WebBlendModeLuminosity;
default:
break;
}
ASSERT_NOT_REACHED();
- return BlendModeNormal;
+ return blink::WebBlendModeNormal;
}
template<> inline CSSPrimitiveValue::CSSPrimitiveValue(LineCap e)
@@ -4358,31 +4436,23 @@ template<> inline CSSPrimitiveValue::CSSPrimitiveValue(GridAutoFlow flow)
enum LengthConversion {
AnyConversion = ~0,
- FixedIntegerConversion = 1 << 0,
- FixedFloatConversion = 1 << 1,
- AutoConversion = 1 << 2,
- PercentConversion = 1 << 3,
- FractionConversion = 1 << 4,
+ FixedConversion = 1 << 0,
+ AutoConversion = 1 << 1,
+ PercentConversion = 1 << 2,
};
-template<int supported> Length CSSPrimitiveValue::convertToLength(const RenderStyle* style, const RenderStyle* rootStyle, double multiplier, bool computingFontSize)
+template<int supported> Length CSSPrimitiveValue::convertToLength(const CSSToLengthConversionData& conversionData)
{
ASSERT(!hasVariableReference());
- if ((supported & (FixedIntegerConversion | FixedFloatConversion)) && isFontRelativeLength() && (!style || !rootStyle))
- return Length(Undefined);
- if ((supported & FixedIntegerConversion) && isLength())
- return computeLength<Length>(style, rootStyle, multiplier, computingFontSize);
- if ((supported & FixedFloatConversion) && isLength())
- return Length(computeLength<double>(style, rootStyle, multiplier), Fixed);
+ if ((supported & FixedConversion) && isLength())
+ return computeLength<Length>(conversionData);
if ((supported & PercentConversion) && isPercentage())
return Length(getDoubleValue(), Percent);
- if ((supported & FractionConversion) && isNumber())
- return Length(getDoubleValue() * 100.0, Percent);
if ((supported & AutoConversion) && getValueID() == CSSValueAuto)
return Length(Auto);
- if ((supported & (FixedIntegerConversion | FixedFloatConversion)) && (supported & PercentConversion) && isCalculated())
- return Length(cssCalcValue()->toCalcValue(style, rootStyle, multiplier));
- if ((supported & (FixedIntegerConversion | FixedFloatConversion)) && isViewportPercentageLength())
+ if ((supported & FixedConversion) && (supported & PercentConversion) && isCalculated())
+ return Length(cssCalcValue()->toCalcValue(conversionData));
+ if ((supported & FixedConversion) && isViewportPercentageLength())
return viewportPercentageLength();
return Length(Undefined);
}
@@ -4796,20 +4866,6 @@ template<> inline CSSPrimitiveValue::operator EMaskType() const
return MT_LUMINANCE;
}
-template<> inline CSSPrimitiveValue::CSSPrimitiveValue(TouchAction t)
- : CSSValue(PrimitiveClass)
-{
- m_primitiveUnitType = CSS_VALUE_ID;
- switch (t) {
- case TouchActionNone:
- m_value.valueID = CSSValueNone;
- break;
- case TouchActionAuto:
- m_value.valueID = CSSValueAuto;
- break;
- }
-}
-
template<> inline CSSPrimitiveValue::operator TouchAction() const
{
ASSERT(isValueID());
@@ -4818,6 +4874,10 @@ template<> inline CSSPrimitiveValue::operator TouchAction() const
return TouchActionNone;
case CSSValueAuto:
return TouchActionAuto;
+ case CSSValuePanX:
+ return TouchActionPanX;
+ case CSSValuePanY:
+ return TouchActionPanY;
default:
break;
}
@@ -4856,6 +4916,73 @@ template<> inline CSSPrimitiveValue::operator EIsolation() const
return IsolationAuto;
}
+template<> inline CSSPrimitiveValue::CSSPrimitiveValue(TouchActionDelay t)
+ : CSSValue(PrimitiveClass)
+{
+ m_primitiveUnitType = CSS_VALUE_ID;
+ switch (t) {
+ case TouchActionDelayNone:
+ m_value.valueID = CSSValueNone;
+ break;
+ case TouchActionDelayScript:
+ m_value.valueID = CSSValueScript;
+ break;
+ }
+}
+
+template<> inline CSSPrimitiveValue::operator TouchActionDelay() const
+{
+ switch (m_value.valueID) {
+ case CSSValueNone:
+ return TouchActionDelayNone;
+ case CSSValueScript:
+ return TouchActionDelayScript;
+ default:
+ break;
+ }
+
+ ASSERT_NOT_REACHED();
+ return TouchActionDelayNone;
+}
+
+template<> inline CSSPrimitiveValue::CSSPrimitiveValue(LayoutBox layoutBox)
+ : CSSValue(PrimitiveClass)
+{
+ m_primitiveUnitType = CSS_VALUE_ID;
+ switch (layoutBox) {
+ case MarginBox:
+ m_value.valueID = CSSValueMarginBox;
+ break;
+ case BorderBox:
+ m_value.valueID = CSSValueBorderBox;
+ break;
+ case PaddingBox:
+ m_value.valueID = CSSValuePaddingBox;
+ break;
+ case ContentBox:
+ m_value.valueID = CSSValueContentBox;
+ break;
+ }
+}
+
+template<> inline CSSPrimitiveValue::operator LayoutBox() const
+{
+ switch (getValueID()) {
+ case CSSValueMarginBox:
+ return MarginBox;
+ case CSSValueBorderBox:
+ return BorderBox;
+ case CSSValuePaddingBox:
+ return PaddingBox;
+ case CSSValueContentBox:
+ return ContentBox;
+ default:
+ break;
+ }
+ ASSERT_NOT_REACHED();
+ return ContentBox;
+}
+
}
#endif
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSProperties.in b/chromium/third_party/WebKit/Source/core/css/CSSProperties.in
index 4bcc442423d..26318517545 100644..100755
--- a/chromium/third_party/WebKit/Source/core/css/CSSProperties.in
+++ b/chromium/third_party/WebKit/Source/core/css/CSSProperties.in
@@ -39,6 +39,7 @@ border-top-right-radius type_name=LengthSize, initial=initialBorderRadius, conve
border-top-style type_name=EBorderStyle, initial=initialBorderStyle
border-top-width type_name=unsigned, initial=initialBorderWidth, converter=convertLineWidth<unsigned>
bottom type_name=Length, initial=initialOffset, converter=convertLengthOrAuto
+box-shadow converter=convertShadow
box-sizing
caption-side
clear
@@ -57,6 +58,7 @@ flex-shrink type_name=float
flex-wrap
float type_name=EFloat, name_for_methods=Floating
font-family custom_all
+font-kerning custom_all
font-size custom_all
font-style custom_all
font-variant custom_all
@@ -81,7 +83,7 @@ max-height type_name=Length, initial=initialMaxSize, converter=convertLengthMaxS
max-width type_name=Length, initial=initialMaxSize, converter=convertLengthMaxSizing
min-height type_name=Length, initial=initialMinSize, converter=convertLengthSizing
min-width type_name=Length, initial=initialMinSize, converter=convertLengthSizing
-mix-blend-mode type_name=BlendMode, name_for_methods=BlendMode
+mix-blend-mode type_name=blink::WebBlendMode, name_for_methods=BlendMode
object-fit type_name=ObjectFit
object-position type_name=LengthPoint, initial=initialObjectPosition, converter=convertLengthPoint
opacity type_name=float
@@ -105,6 +107,11 @@ pointer-events
position
resize custom_value
right type_name=Length, initial=initialOffset, converter=convertLengthOrAuto
+shape-image-threshold type_name=float
+shape-inside type_name=ShapeValue*, custom_value
+shape-margin type_name=Length, converter=convertLength
+shape-outside type_name=ShapeValue*, custom_value
+shape-padding type_name=Length, converter=convertLength
size custom_all
speak
table-layout
@@ -116,11 +123,14 @@ text-decoration-line use_handlers_for=CSSPropertyTextDecoration
text-decoration-color custom_all
text-decoration-style type_name=TextDecorationStyle
text-indent custom_all
+text-justify type_name=TextJustify
text-overflow type_name=TextOverflow
text-rendering custom_all
+text-shadow converter=convertShadow
text-transform
top type_name=Length, initial=initialOffset, converter=convertLengthOrAuto
-touch-action type_name=TouchAction, initial=initialTouchAction
+touch-action type_name=TouchAction, custom_value
+touch-action-delay type_name=TouchActionDelay, initial=initialTouchActionDelay
unicode-bidi
vertical-align custom_value
visibility
@@ -162,12 +172,14 @@ z-index type_name=int, custom_all
-webkit-box-ordinal-group type_name=unsigned int
-webkit-box-orient
-webkit-box-pack
+-webkit-box-shadow use_handlers_for=CSSPropertyBoxShadow
-webkit-clip-path custom_value
-webkit-column-axis type_name=ColumnAxis
-webkit-column-break-after type_name=EPageBreak, initial=initialPageBreak
-webkit-column-break-before type_name=EPageBreak, initial=initialPageBreak
-webkit-column-break-inside type_name=EPageBreak, initial=initialPageBreak
-webkit-column-count type_name=unsigned short, custom_all
+column-fill type_name=ColumnFill
-webkit-column-gap type_name=float, custom_all
-webkit-column-progression type_name=ColumnProgression
-webkit-column-rule-color custom_all
@@ -177,7 +189,6 @@ z-index type_name=int, custom_all
-webkit-column-width type_name=float, custom_all
-webkit-flow-from type_name=AtomicString, name_for_methods=RegionThread, converter=convertString<CSSValueNone>
-webkit-flow-into type_name=AtomicString, name_for_methods=FlowThread, converter=convertString<CSSValueNone>
--webkit-font-kerning custom_all
-webkit-font-smoothing custom_all
-webkit-font-variant-ligatures custom_all
-webkit-highlight type_name=AtomicString, converter=convertString<CSSValueNone>
@@ -196,7 +207,6 @@ z-index type_name=int, custom_all
-internal-marquee-repetition type_name=int, name_for_methods=MarqueeLoopCount, custom_value
-internal-marquee-speed custom_value, name_for_methods=MarqueeSpeed
-internal-marquee-style name_for_methods=MarqueeBehavior
--webkit-mask-box-image initial=initialNinePieceImage, custom_value
-webkit-mask-box-image-outset custom_all
-webkit-mask-box-image-repeat custom_all
-webkit-mask-box-image-slice custom_all
@@ -221,10 +231,6 @@ z-index type_name=int, custom_all
-webkit-region-fragment type_name=RegionFragment
-webkit-rtl-ordering type_name=Order, getter=rtlOrdering, setter=setRTLOrdering, initial=initialRTLOrdering
-webkit-ruby-position type_name=RubyPosition
--webkit-shape-inside type_name=ShapeValue*, custom_value
--webkit-shape-margin type_name=Length, converter=convertLength
--webkit-shape-outside type_name=ShapeValue*, custom_value
--webkit-shape-padding type_name=Length, converter=convertLength
-webkit-text-combine type_name=TextCombine
-webkit-text-emphasis-color custom_all
-webkit-text-emphasis-position type_name=TextEmphasisPosition
@@ -232,7 +238,7 @@ z-index type_name=int, custom_all
-webkit-text-fill-color custom_all
-webkit-text-security
-webkit-text-stroke-color custom_all
--webkit-text-underline-position custom_value, condition=CSS3_TEXT
+text-underline-position custom_value
-webkit-transform-origin-x type_name=Length, converter=convertLength
-webkit-transform-origin-y type_name=Length, converter=convertLength
-webkit-transform-origin-z type_name=float, converter=convertComputedLength<float>
@@ -249,16 +255,30 @@ z-index type_name=int, custom_all
alignment-baseline svg
buffered-rendering svg
+clip-path svg, type_name=String, name_for_methods=ClipperResource, converter=convertFragmentIdentifier
clip-rule svg, type_name=WindRule
color-interpolation svg
color-interpolation-filters svg, type_name=EColorInterpolation
color-rendering svg
dominant-baseline svg
+fill-opacity svg, type_name=float, converter=convertNumberOrPercentage
fill-rule svg, type_name=WindRule
+filter svg, type_name=String, name_for_methods=FilterResource, converter=convertFragmentIdentifier
+flood-opacity svg, type_name=float, converter=convertNumberOrPercentage
+kerning svg, type_name=SVGLength, converter=convertSVGLength
+marker-start svg, type_name=String, name_for_methods=MarkerStartResource, converter=convertFragmentIdentifier
+marker-mid svg, type_name=String, name_for_methods=MarkerMidResource, converter=convertFragmentIdentifier
+marker-end svg, type_name=String, name_for_methods=MarkerEndResource, converter=convertFragmentIdentifier
+mask svg, type_name=String, name_for_methods=MaskerResource, converter=convertFragmentIdentifier
mask-type svg
shape-rendering svg
+stop-opacity svg, type_name=float, converter=convertNumberOrPercentage
+stroke-dashoffset svg, type_name=SVGLength, name_for_methods=StrokeDashOffset, converter=convertSVGLength
stroke-linecap svg, type_name=LineCap, name_for_methods=CapStyle
stroke-linejoin svg, type_name=LineJoin, name_for_methods=JoinStyle
+stroke-miterlimit svg, type_name=float, name_for_methods=StrokeMiterLimit
+stroke-opacity svg, type_name=float, converter=convertNumberOrPercentage
+stroke-width svg, type_name=SVGLength, converter=convertSVGLength
text-anchor svg
vector-effect svg
writing-mode svg, type_name=SVGWritingMode
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSProperty.cpp b/chromium/third_party/WebKit/Source/core/css/CSSProperty.cpp
index 56e95f1aba4..59e3d9e68af 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSProperty.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/CSSProperty.cpp
@@ -39,7 +39,8 @@ CSSPropertyID StylePropertyMetadata::shorthandID() const
if (!m_isSetFromShorthand)
return CSSPropertyInvalid;
- const Vector<StylePropertyShorthand> shorthands = matchingShorthandsForLonghand(static_cast<CSSPropertyID>(m_propertyID));
+ Vector<StylePropertyShorthand, 4> shorthands;
+ getMatchingShorthandsForLonghand(static_cast<CSSPropertyID>(m_propertyID), &shorthands);
ASSERT(shorthands.size() && m_indexInShorthandsVector >= 0 && m_indexInShorthandsVector < shorthands.size());
return shorthands.at(m_indexInShorthandsVector).id();
}
@@ -309,11 +310,13 @@ bool CSSProperty::isInheritedProperty(CSSPropertyID propertyID)
case CSSPropertyTabSize:
case CSSPropertyTextAlign:
case CSSPropertyTextAlignLast:
+ case CSSPropertyTextJustify:
case CSSPropertyTextAnchor:
case CSSPropertyTextIndent:
case CSSPropertyTextRendering:
case CSSPropertyTextShadow:
case CSSPropertyTextTransform:
+ case CSSPropertyTouchActionDelay:
case CSSPropertyVariable:
case CSSPropertyVisibility:
case CSSPropertyWebkitAspectRatio:
@@ -321,7 +324,7 @@ bool CSSProperty::isInheritedProperty(CSSPropertyID propertyID)
case CSSPropertyWebkitBorderVerticalSpacing:
case CSSPropertyWebkitBoxDirection:
case CSSPropertyWebkitFontFeatureSettings:
- case CSSPropertyWebkitFontKerning:
+ case CSSPropertyFontKerning:
case CSSPropertyWebkitFontSmoothing:
case CSSPropertyWebkitFontVariantLigatures:
case CSSPropertyWebkitLocale:
@@ -337,9 +340,7 @@ bool CSSProperty::isInheritedProperty(CSSPropertyID propertyID)
case CSSPropertyWebkitRubyPosition:
case CSSPropertyWebkitTapHighlightColor:
case CSSPropertyWebkitTextCombine:
-#if ENABLE(CSS3_TEXT)
- case CSSPropertyWebkitTextUnderlinePosition:
-#endif // CSS3_TEXT
+ case CSSPropertyTextUnderlinePosition:
case CSSPropertyWebkitTextDecorationsInEffect:
case CSSPropertyWebkitTextEmphasis:
case CSSPropertyWebkitTextEmphasisColor:
@@ -557,12 +558,14 @@ bool CSSProperty::isInheritedProperty(CSSPropertyID propertyID)
case CSSPropertyWebkitBoxPack:
case CSSPropertyWebkitBoxReflect:
case CSSPropertyWebkitBoxShadow:
+ case CSSPropertyInternalCallback:
case CSSPropertyWebkitClipPath:
case CSSPropertyWebkitColumnAxis:
case CSSPropertyWebkitColumnBreakAfter:
case CSSPropertyWebkitColumnBreakBefore:
case CSSPropertyWebkitColumnBreakInside:
case CSSPropertyWebkitColumnCount:
+ case CSSPropertyColumnFill:
case CSSPropertyWebkitColumnGap:
case CSSPropertyWebkitColumnProgression:
case CSSPropertyWebkitColumnRule:
@@ -662,10 +665,11 @@ bool CSSProperty::isInheritedProperty(CSSPropertyID propertyID)
case CSSPropertyWebkitRegionBreakInside:
case CSSPropertyWebkitRegionFragment:
case CSSPropertyWebkitWrapFlow:
- case CSSPropertyWebkitShapeMargin:
- case CSSPropertyWebkitShapePadding:
- case CSSPropertyWebkitShapeInside:
- case CSSPropertyWebkitShapeOutside:
+ case CSSPropertyShapeMargin:
+ case CSSPropertyShapeImageThreshold:
+ case CSSPropertyShapePadding:
+ case CSSPropertyShapeInside:
+ case CSSPropertyShapeOutside:
case CSSPropertyWebkitWrapThrough:
case CSSPropertyWebkitAppRegion:
case CSSPropertyWidth:
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSProperty.h b/chromium/third_party/WebKit/Source/core/css/CSSProperty.h
index fd802ecbe40..a0fb377ce3f 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSProperty.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSProperty.h
@@ -24,8 +24,8 @@
#include "CSSPropertyNames.h"
#include "RuntimeEnabledFeatures.h"
#include "core/css/CSSValue.h"
-#include "core/platform/text/TextDirection.h"
-#include "core/platform/text/WritingMode.h"
+#include "platform/text/TextDirection.h"
+#include "platform/text/WritingMode.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefPtr.h"
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSPropertyNames.in b/chromium/third_party/WebKit/Source/core/css/CSSPropertyNames.in
index 2f88d9396f0..880cb61d86b 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSPropertyNames.in
+++ b/chromium/third_party/WebKit/Source/core/css/CSSPropertyNames.in
@@ -45,13 +45,13 @@ color
direction
font
font-family
+font-kerning
font-size
font-style
font-variant
font-weight
text-rendering
-webkit-font-feature-settings
--webkit-font-kerning
-webkit-font-smoothing
-webkit-font-variant-ligatures
-webkit-locale
@@ -195,6 +195,7 @@ text-decoration-line
text-decoration-style
text-decoration-color
text-indent
+text-justify
text-line-through-color
text-line-through-mode
text-line-through-style
@@ -211,8 +212,10 @@ text-underline-color
text-underline-mode
text-underline-style
text-underline-width
+text-underline-position
top
touch-action
+touch-action-delay
unicode-bidi
unicode-range
@@ -270,11 +273,13 @@ z-index
-webkit-box-pack
-webkit-box-reflect
-webkit-box-shadow
+-internal-callback
-webkit-column-axis
-webkit-column-break-after
-webkit-column-break-before
-webkit-column-break-inside
-webkit-column-count
+column-fill
-webkit-column-gap
-webkit-column-progression
-webkit-column-rule
@@ -378,7 +383,6 @@ order
-webkit-ruby-position
-webkit-text-combine
-epub-text-combine alias_for=-webkit-text-combine
--webkit-text-underline-position condition=CSS3_TEXT
-webkit-text-decorations-in-effect
-webkit-text-emphasis
-epub-text-emphasis alias_for=-webkit-text-emphasis
@@ -407,10 +411,16 @@ order
-webkit-region-break-after
-webkit-region-break-before
-webkit-region-break-inside
--webkit-shape-inside
--webkit-shape-outside
--webkit-shape-margin
--webkit-shape-padding
+-webkit-shape-inside alias_for=shape-inside
+-webkit-shape-outside alias_for=shape-outside
+-webkit-shape-margin alias_for=shape-margin
+-webkit-shape-padding alias_for=shape-padding
+-webkit-shape-image-threshold alias_for=shape-image-threshold
+shape-inside
+shape-outside
+shape-margin
+shape-padding
+shape-image-threshold
-webkit-wrap-flow
-webkit-wrap-through
max-zoom
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSPropertySourceData.h b/chromium/third_party/WebKit/Source/core/css/CSSPropertySourceData.h
index f08deea8cbd..7b964d45f26 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSPropertySourceData.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSPropertySourceData.h
@@ -95,7 +95,6 @@ struct CSSRuleSourceData : public RefCounted<CSSRuleSourceData> {
PAGE_RULE,
KEYFRAMES_RULE,
REGION_RULE,
- HOST_RULE,
VIEWPORT_RULE,
SUPPORTS_RULE,
FILTER_RULE
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSReflectValue.cpp b/chromium/third_party/WebKit/Source/core/css/CSSReflectValue.cpp
index d73bae4615e..b13006ccc5e 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSReflectValue.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/CSSReflectValue.cpp
@@ -32,7 +32,7 @@ using namespace std;
namespace WebCore {
-String CSSReflectValue::customCssText() const
+String CSSReflectValue::customCSSText() const
{
if (m_mask)
return m_direction->cssText() + ' ' + m_offset->cssText() + ' ' + m_mask->cssText();
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSReflectValue.h b/chromium/third_party/WebKit/Source/core/css/CSSReflectValue.h
index 91ca5cdde3d..0fd92a07da2 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSReflectValue.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSReflectValue.h
@@ -46,7 +46,7 @@ public:
CSSPrimitiveValue* offset() const { return m_offset.get(); }
CSSValue* mask() const { return m_mask.get(); }
- String customCssText() const;
+ String customCSSText() const;
String customSerializeResolvingVariables(const HashMap<AtomicString, String>&) const;
void addSubresourceStyleURLs(ListHashSet<KURL>&, const StyleSheetContents*) const;
@@ -67,6 +67,8 @@ private:
RefPtr<CSSValue> m_mask;
};
+DEFINE_CSS_VALUE_TYPE_CASTS(CSSReflectValue, isReflectValue());
+
} // namespace WebCore
#endif // CSSReflectValue_h
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSRegionRule.cpp b/chromium/third_party/WebKit/Source/core/css/CSSRegionRule.cpp
index 27278dcc42e..94e9d0bae8c 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSRegionRule.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/CSSRegionRule.cpp
@@ -53,7 +53,7 @@ String CSSRegionRule::cssText() const
// Then add the rules.
result.appendLiteral(" { \n");
- appendCssTextForItems(result);
+ appendCSSTextForItems(result);
result.append('}');
return result.toString();
}
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSRegionRule.h b/chromium/third_party/WebKit/Source/core/css/CSSRegionRule.h
index f6f82e1a80b..e095da44af4 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSRegionRule.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSRegionRule.h
@@ -48,6 +48,8 @@ private:
CSSRegionRule(StyleRuleRegion*, CSSStyleSheet* parent);
};
+DEFINE_CSS_RULE_TYPE_CASTS(CSSRegionRule, WEBKIT_REGION_RULE);
+
}
#endif // CSSRegionRule_h
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSRule.cpp b/chromium/third_party/WebKit/Source/core/css/CSSRule.cpp
index d71bee10468..7673640a990 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSRule.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/CSSRule.cpp
@@ -25,7 +25,7 @@
#include "core/css/CSSStyleSheet.h"
#include "core/css/StyleRule.h"
#include "core/css/StyleSheetContents.h"
-#include "core/platform/NotImplemented.h"
+#include "platform/NotImplemented.h"
namespace WebCore {
@@ -41,7 +41,7 @@ COMPILE_ASSERT(StyleRuleBase::Region == static_cast<StyleRuleBase::Type>(CSSRule
COMPILE_ASSERT(StyleRuleBase::Viewport == static_cast<StyleRuleBase::Type>(CSSRule::VIEWPORT_RULE), enums_should_match);
-void CSSRule::setCssText(const String&)
+void CSSRule::setCSSText(const String&)
{
notImplemented();
}
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSRule.h b/chromium/third_party/WebKit/Source/core/css/CSSRule.h
index 705f7cf5f91..9cd66086e23 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSRule.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSRule.h
@@ -28,9 +28,9 @@
namespace WebCore {
+class CSSParserContext;
class CSSStyleSheet;
class StyleRuleBase;
-struct CSSParserContext;
class CSSRule : public RefCounted<CSSRule> {
public:
@@ -54,8 +54,7 @@ public:
SUPPORTS_RULE = 12,
VIEWPORT_RULE = 15,
WEBKIT_REGION_RULE = 16,
- WEBKIT_FILTER_RULE = 17,
- HOST_RULE = 1001,
+ WEBKIT_FILTER_RULE = 17
};
virtual Type type() const = 0;
@@ -84,7 +83,7 @@ public:
CSSRule* parentRule() const { return m_parentIsRule ? m_parentRule : 0; }
// NOTE: Just calls notImplemented().
- void setCssText(const String&);
+ void setCSSText(const String&);
protected:
CSSRule(CSSStyleSheet* parent)
@@ -109,6 +108,9 @@ private:
};
};
+#define DEFINE_CSS_RULE_TYPE_CASTS(ToType, TYPE_NAME) \
+ DEFINE_TYPE_CASTS(ToType, CSSRule, rule, rule->type() == CSSRule::TYPE_NAME, rule.type() == CSSRule::TYPE_NAME)
+
} // namespace WebCore
#endif // CSSRule_h
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSRule.idl b/chromium/third_party/WebKit/Source/core/css/CSSRule.idl
index 94ce538200a..9dadad92a10 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSRule.idl
+++ b/chromium/third_party/WebKit/Source/core/css/CSSRule.idl
@@ -20,8 +20,8 @@
// Introduced in DOM Level 2:
[
- CustomToV8,
- DependentLifetime
+ Custom=Wrap,
+ DependentLifetime,
] interface CSSRule {
// RuleType
@@ -37,14 +37,13 @@
const unsigned short KEYFRAME_RULE = 8;
const unsigned short WEBKIT_KEYFRAME_RULE = 8;
const unsigned short SUPPORTS_RULE = 12;
- [EnabledAtRuntime=CSSViewport] const unsigned short VIEWPORT_RULE = 15;
- [EnabledAtRuntime=CSSRegions] const unsigned short WEBKIT_REGION_RULE = 16;
+ [RuntimeEnabled=CSSViewport] const unsigned short VIEWPORT_RULE = 15;
+ [RuntimeEnabled=CSSRegions] const unsigned short WEBKIT_REGION_RULE = 16;
const unsigned short WEBKIT_FILTER_RULE = 17;
- const unsigned short HOST_RULE = 1001;
readonly attribute unsigned short type;
- [TreatReturnedNullStringAs=Null, TreatNullAs=NullString] attribute DOMString cssText;
+ attribute DOMString cssText;
readonly attribute CSSStyleSheet parentStyleSheet;
readonly attribute CSSRule parentRule;
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSSVGDocumentValue.cpp b/chromium/third_party/WebKit/Source/core/css/CSSSVGDocumentValue.cpp
index b8af3ce9aae..d0912d4263f 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSSVGDocumentValue.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/CSSSVGDocumentValue.cpp
@@ -29,7 +29,6 @@
#include "FetchInitiatorTypeNames.h"
#include "core/css/CSSParser.h"
#include "core/dom/Document.h"
-#include "core/fetch/DocumentResource.h"
#include "core/fetch/FetchRequest.h"
#include "core/fetch/ResourceFetcher.h"
@@ -60,7 +59,7 @@ DocumentResource* CSSSVGDocumentValue::load(ResourceFetcher* loader)
return m_document.get();
}
-String CSSSVGDocumentValue::customCssText() const
+String CSSSVGDocumentValue::customCSSText() const
{
return quoteCSSStringIfNeeded(m_url);
}
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSSVGDocumentValue.h b/chromium/third_party/WebKit/Source/core/css/CSSSVGDocumentValue.h
index 7e43406ffb5..d2decc42d88 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSSVGDocumentValue.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSSVGDocumentValue.h
@@ -41,7 +41,7 @@ public:
DocumentResource* cachedSVGDocument() const { return m_document.get(); }
DocumentResource* load(ResourceFetcher*);
- String customCssText() const;
+ String customCSSText() const;
const String& url() const { return m_url; }
bool loadRequested() const { return m_loadRequested; }
bool equals(const CSSSVGDocumentValue&) const;
@@ -54,6 +54,8 @@ private:
bool m_loadRequested;
};
+DEFINE_CSS_VALUE_TYPE_CASTS(CSSSVGDocumentValue, isSVGDocumentValue());
+
} // namespace WebCore
#endif // CSSSVGDocumentValue_h
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSSegmentedFontFace.cpp b/chromium/third_party/WebKit/Source/core/css/CSSSegmentedFontFace.cpp
index 60bc3c5a128..eaa1223b132 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSSegmentedFontFace.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/CSSSegmentedFontFace.cpp
@@ -26,18 +26,18 @@
#include "config.h"
#include "core/css/CSSSegmentedFontFace.h"
-#include "core/css/CSSFontFace.h"
#include "RuntimeEnabledFeatures.h"
-#include "core/platform/graphics/FontDescription.h"
-#include "core/platform/graphics/SegmentedFontData.h"
-#include "core/platform/graphics/SimpleFontData.h"
+#include "core/css/CSSFontFace.h"
+#include "platform/fonts/FontCache.h"
+#include "platform/fonts/FontDescription.h"
+#include "platform/fonts/SegmentedFontData.h"
+#include "platform/fonts/SimpleFontData.h"
namespace WebCore {
-CSSSegmentedFontFace::CSSSegmentedFontFace(CSSFontSelector* fontSelector, FontTraitsMask traitsMask, bool isLocalFallback)
+CSSSegmentedFontFace::CSSSegmentedFontFace(CSSFontSelector* fontSelector, FontTraitsMask traitsMask)
: m_fontSelector(fontSelector)
, m_traitsMask(traitsMask)
- , m_isLocalFallback(isLocalFallback)
{
}
@@ -77,7 +77,7 @@ void CSSSegmentedFontFace::fontLoaded(CSSFontFace*)
Vector<RefPtr<LoadFontCallback> > callbacks;
m_callbacks.swap(callbacks);
for (size_t index = 0; index < callbacks.size(); ++index) {
- if (checkFont())
+ if (isLoaded())
callbacks[index]->notifyLoaded(this);
else
callbacks[index]->notifyError(this);
@@ -92,7 +92,17 @@ void CSSSegmentedFontFace::appendFontFace(PassRefPtr<CSSFontFace> fontFace)
m_fontFaces.append(fontFace);
}
-static void appendFontData(SegmentedFontData* newFontData, PassRefPtr<SimpleFontData> prpFaceFontData, const Vector<CSSFontFace::UnicodeRange>& ranges)
+void CSSSegmentedFontFace::removeFontFace(PassRefPtr<CSSFontFace> fontFace)
+{
+ size_t index = m_fontFaces.find(fontFace);
+ if (index != kNotFound) {
+ pruneTable();
+ m_fontFaces.remove(index);
+ fontFace->clearSegmentedFontFace();
+ }
+}
+
+static void appendFontData(SegmentedFontData* newFontData, PassRefPtr<SimpleFontData> prpFaceFontData, const CSSFontFace::UnicodeRangeSet& ranges)
{
RefPtr<SimpleFontData> faceFontData = prpFaceFontData;
unsigned numRanges = ranges.size();
@@ -102,7 +112,7 @@ static void appendFontData(SegmentedFontData* newFontData, PassRefPtr<SimpleFont
}
for (unsigned j = 0; j < numRanges; ++j)
- newFontData->appendRange(FontDataRange(ranges[j].from(), ranges[j].to(), faceFontData));
+ newFontData->appendRange(FontDataRange(ranges.rangeAt(j).from(), ranges.rangeAt(j).to(), faceFontData));
}
PassRefPtr<FontData> CSSSegmentedFontFace::getFontData(const FontDescription& fontDescription)
@@ -111,26 +121,32 @@ PassRefPtr<FontData> CSSSegmentedFontFace::getFontData(const FontDescription& fo
return 0;
FontTraitsMask desiredTraitsMask = fontDescription.traitsMask();
- unsigned hashKey = ((fontDescription.computedPixelSize() + 1) << (FontTraitsMaskWidth + FontWidthVariantWidth + 1))
- | ((fontDescription.orientation() == Vertical ? 1 : 0) << (FontTraitsMaskWidth + FontWidthVariantWidth))
- | fontDescription.widthVariant() << FontTraitsMaskWidth
- | desiredTraitsMask;
+ AtomicString emptyFontFamily = "";
+ FontCacheKey key = fontDescription.cacheKey(emptyFontFamily, desiredTraitsMask);
- RefPtr<SegmentedFontData>& fontData = m_fontDataTable.add(hashKey, 0).iterator->value;
+ RefPtr<SegmentedFontData>& fontData = m_fontDataTable.add(key.hash(), 0).iterator->value;
if (fontData && fontData->numRanges())
return fontData; // No release, we have a reference to an object in the cache which should retain the ref count it has.
if (!fontData)
fontData = SegmentedFontData::create();
- bool syntheticBold = !(m_traitsMask & (FontWeight600Mask | FontWeight700Mask | FontWeight800Mask | FontWeight900Mask)) && (desiredTraitsMask & (FontWeight600Mask | FontWeight700Mask | FontWeight800Mask | FontWeight900Mask));
- bool syntheticItalic = !(m_traitsMask & FontStyleItalicMask) && (desiredTraitsMask & FontStyleItalicMask);
+ FontDescription requestedFontDescription(fontDescription);
+ requestedFontDescription.setTraitsMask(m_traitsMask);
+ requestedFontDescription.setSyntheticBold(!(m_traitsMask & (FontWeight600Mask | FontWeight700Mask | FontWeight800Mask | FontWeight900Mask)) && (desiredTraitsMask & (FontWeight600Mask | FontWeight700Mask | FontWeight800Mask | FontWeight900Mask)));
+ requestedFontDescription.setSyntheticItalic(!(m_traitsMask & FontStyleItalicMask) && (desiredTraitsMask & FontStyleItalicMask));
for (int i = m_fontFaces.size() - 1; i >= 0; --i) {
if (!m_fontFaces[i]->isValid())
continue;
- if (RefPtr<SimpleFontData> faceFontData = m_fontFaces[i]->getFontData(fontDescription, syntheticBold, syntheticItalic)) {
+ if (RefPtr<SimpleFontData> faceFontData = m_fontFaces[i]->getFontData(requestedFontDescription)) {
ASSERT(!faceFontData->isSegmented());
+#if ENABLE(SVG_FONTS)
+ // For SVG Fonts that specify that they only support the "normal" variant, we will assume they are incapable
+ // of small-caps synthesis and just ignore the font face.
+ if (faceFontData->isSVGFont() && (desiredTraitsMask & FontVariantSmallCapsMask) && !(m_traitsMask & FontVariantSmallCapsMask))
+ continue;
+#endif
appendFontData(fontData.get(), faceFontData.release(), m_fontFaces[i]->ranges());
}
}
@@ -140,24 +156,24 @@ PassRefPtr<FontData> CSSSegmentedFontFace::getFontData(const FontDescription& fo
return 0;
}
-bool CSSSegmentedFontFace::hasSVGFontFaceSource() const
+bool CSSSegmentedFontFace::isLoading() const
{
unsigned size = m_fontFaces.size();
for (unsigned i = 0; i < size; i++) {
- if (m_fontFaces[i]->hasSVGFontFaceSource())
+ if (m_fontFaces[i]->loadStatus() == FontFace::Loading)
return true;
}
return false;
}
-bool CSSSegmentedFontFace::isLoading() const
+bool CSSSegmentedFontFace::isLoaded() const
{
unsigned size = m_fontFaces.size();
for (unsigned i = 0; i < size; i++) {
- if (m_fontFaces[i]->loadStatus() == FontFace::Loading)
- return true;
+ if (m_fontFaces[i]->loadStatus() != FontFace::Loaded)
+ return false;
}
- return false;
+ return true;
}
void CSSSegmentedFontFace::willUseFontData(const FontDescription& fontDescription)
@@ -167,41 +183,44 @@ void CSSSegmentedFontFace::willUseFontData(const FontDescription& fontDescriptio
m_fontFaces[i]->willUseFontData(fontDescription);
}
-bool CSSSegmentedFontFace::checkFont() const
+bool CSSSegmentedFontFace::checkFont(const String& text) const
{
unsigned size = m_fontFaces.size();
for (unsigned i = 0; i < size; i++) {
- if (m_fontFaces[i]->loadStatus() != FontFace::Loaded)
+ if (m_fontFaces[i]->loadStatus() != FontFace::Loaded && m_fontFaces[i]->ranges().intersectsWith(text))
return false;
}
return true;
}
-void CSSSegmentedFontFace::loadFont(const FontDescription& fontDescription, PassRefPtr<LoadFontCallback> callback)
+void CSSSegmentedFontFace::loadFont(const FontDescription& fontDescription, const String& text, PassRefPtr<LoadFontCallback> callback)
{
- RefPtr<SegmentedFontData> fontData = toSegmentedFontData(getFontData(fontDescription).get());
- unsigned numRanges = fontData->numRanges();
- for (unsigned i = 0; i < numRanges; i++)
- fontData->rangeAt(i).fontData()->beginLoadIfNeeded();
+ unsigned size = m_fontFaces.size();
+ for (unsigned i = 0; i < size; i++) {
+ if (m_fontFaces[i]->loadStatus() == FontFace::Unloaded && m_fontFaces[i]->ranges().intersectsWith(text)) {
+ RefPtr<SimpleFontData> fontData = m_fontFaces[i]->getFontData(fontDescription);
+ if (fontData->customFontData())
+ fontData->customFontData()->beginLoadIfNeeded();
+ }
+ }
if (callback) {
if (isLoading())
m_callbacks.append(callback);
- else if (checkFont())
+ else if (isLoaded())
callback->notifyLoaded(this);
else
callback->notifyError(this);
}
}
-Vector<RefPtr<FontFace> > CSSSegmentedFontFace::fontFaces() const
+Vector<RefPtr<FontFace> > CSSSegmentedFontFace::fontFaces(const String& text) const
{
Vector<RefPtr<FontFace> > fontFaces;
unsigned size = m_fontFaces.size();
for (unsigned i = 0; i < size; i++) {
- RefPtr<FontFace> face = m_fontFaces[i]->fontFace();
- if (face)
- fontFaces.append(face);
+ if (m_fontFaces[i]->ranges().intersectsWith(text))
+ fontFaces.append(m_fontFaces[i]->fontFace());
}
return fontFaces;
}
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSSegmentedFontFace.h b/chromium/third_party/WebKit/Source/core/css/CSSSegmentedFontFace.h
index a9a624de911..26c5bb1e0b0 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSSegmentedFontFace.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSSegmentedFontFace.h
@@ -26,11 +26,12 @@
#ifndef CSSSegmentedFontFace_h
#define CSSSegmentedFontFace_h
-#include "core/platform/graphics/FontTraitsMask.h"
+#include "platform/fonts/FontTraitsMask.h"
#include "wtf/HashMap.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefCounted.h"
#include "wtf/Vector.h"
+#include "wtf/text/WTFString.h"
namespace WebCore {
@@ -43,23 +44,20 @@ class SegmentedFontData;
class CSSSegmentedFontFace : public RefCounted<CSSSegmentedFontFace> {
public:
- static PassRefPtr<CSSSegmentedFontFace> create(CSSFontSelector* selector, FontTraitsMask traitsMask, bool isLocalFallback) { return adoptRef(new CSSSegmentedFontFace(selector, traitsMask, isLocalFallback)); }
+ static PassRefPtr<CSSSegmentedFontFace> create(CSSFontSelector* selector, FontTraitsMask traitsMask) { return adoptRef(new CSSSegmentedFontFace(selector, traitsMask)); }
~CSSSegmentedFontFace();
CSSFontSelector* fontSelector() const { return m_fontSelector; }
FontTraitsMask traitsMask() const { return m_traitsMask; }
- bool isLocalFallback() const { return m_isLocalFallback; }
void fontLoaded(CSSFontFace*);
void appendFontFace(PassRefPtr<CSSFontFace>);
+ void removeFontFace(PassRefPtr<CSSFontFace>);
+ bool isEmpty() const { return m_fontFaces.isEmpty(); }
PassRefPtr<FontData> getFontData(const FontDescription&);
-#if ENABLE(SVG_FONTS)
- bool hasSVGFontFaceSource() const;
-#endif
-
class LoadFontCallback : public RefCounted<LoadFontCallback> {
public:
virtual ~LoadFontCallback() { }
@@ -67,21 +65,21 @@ public:
virtual void notifyError(CSSSegmentedFontFace*) = 0;
};
- bool checkFont() const;
- void loadFont(const FontDescription&, PassRefPtr<LoadFontCallback> loadCallback);
- Vector<RefPtr<FontFace> > fontFaces() const;
+ bool checkFont(const String&) const;
+ void loadFont(const FontDescription&, const String&, PassRefPtr<LoadFontCallback>);
+ Vector<RefPtr<FontFace> > fontFaces(const String& text) const;
void willUseFontData(const FontDescription&);
private:
- CSSSegmentedFontFace(CSSFontSelector*, FontTraitsMask, bool isLocalFallback);
+ CSSSegmentedFontFace(CSSFontSelector*, FontTraitsMask);
void pruneTable();
bool isValid() const;
bool isLoading() const;
+ bool isLoaded() const;
CSSFontSelector* m_fontSelector;
FontTraitsMask m_traitsMask;
- bool m_isLocalFallback;
HashMap<unsigned, RefPtr<SegmentedFontData> > m_fontDataTable;
Vector<RefPtr<CSSFontFace>, 1> m_fontFaces;
Vector<RefPtr<LoadFontCallback> > m_callbacks;
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSSegmentedFontFaceCache.cpp b/chromium/third_party/WebKit/Source/core/css/CSSSegmentedFontFaceCache.cpp
new file mode 100644
index 00000000000..17803d82821
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/css/CSSSegmentedFontFaceCache.cpp
@@ -0,0 +1,208 @@
+/*
+ * Copyright (C) 2007, 2008, 2011 Apple Inc. All rights reserved.
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+
+#include "config.h"
+#include "CSSSegmentedFontFaceCache.h"
+
+#include "FontFamilyNames.h"
+#include "core/css/CSSFontFace.h"
+#include "core/css/CSSFontFaceSource.h"
+#include "core/css/CSSFontSelector.h"
+#include "core/css/CSSSegmentedFontFace.h"
+#include "core/css/CSSValueList.h"
+#include "core/css/StyleRule.h"
+#include "core/fetch/FontResource.h"
+#include "core/fetch/ResourceFetcher.h"
+#include "platform/fonts/FontDescription.h"
+#include "wtf/text/AtomicString.h"
+
+namespace WebCore {
+
+CSSSegmentedFontFaceCache::CSSSegmentedFontFaceCache()
+ : m_version(0)
+{
+}
+
+void CSSSegmentedFontFaceCache::add(CSSFontSelector* cssFontSelector, const StyleRuleFontFace* fontFaceRule, PassRefPtr<CSSFontFace> prpCssFontFace)
+{
+ RefPtr<CSSFontFace> cssFontFace = prpCssFontFace;
+
+ if (!m_styleRuleToFontFace.add(fontFaceRule, cssFontFace).isNewEntry)
+ return;
+
+ FontFace* fontFace = cssFontFace->fontFace();
+
+ OwnPtr<TraitsMap>& familyFontFaces = m_fontFaces.add(fontFace->family(), nullptr).iterator->value;
+ if (!familyFontFaces)
+ familyFontFaces = adoptPtr(new TraitsMap);
+
+ RefPtr<CSSSegmentedFontFace>& segmentedFontFace = familyFontFaces->add(fontFace->traitsMask(), 0).iterator->value;
+ if (!segmentedFontFace)
+ segmentedFontFace = CSSSegmentedFontFace::create(cssFontSelector, static_cast<FontTraitsMask>(fontFace->traitsMask()));
+
+ segmentedFontFace->appendFontFace(cssFontFace);
+
+ ++m_version;
+}
+
+void CSSSegmentedFontFaceCache::remove(const StyleRuleFontFace* fontFaceRule)
+{
+ StyleRuleToFontFace::iterator styleRuleToFontFaceIter = m_styleRuleToFontFace.find(fontFaceRule);
+ if (styleRuleToFontFaceIter == m_styleRuleToFontFace.end())
+ return;
+ RefPtr<CSSFontFace> cssFontFace = styleRuleToFontFaceIter->value;
+
+ FamilyToTraitsMap::iterator fontFacesIter = m_fontFaces.find(cssFontFace->fontFace()->family());
+ if (fontFacesIter == m_fontFaces.end())
+ return;
+ TraitsMap* familyFontFaces = fontFacesIter->value.get();
+
+ TraitsMap::iterator familyFontFacesIter = familyFontFaces->find(cssFontFace->fontFace()->traitsMask());
+ if (familyFontFacesIter == familyFontFaces->end())
+ return;
+ RefPtr<CSSSegmentedFontFace> segmentedFontFace = familyFontFacesIter->value;
+
+ segmentedFontFace->removeFontFace(cssFontFace);
+ if (segmentedFontFace->isEmpty()) {
+ familyFontFaces->remove(familyFontFacesIter);
+ if (familyFontFaces->isEmpty())
+ m_fontFaces.remove(fontFacesIter);
+ }
+ m_styleRuleToFontFace.remove(styleRuleToFontFaceIter);
+ m_fonts.clear();
+ ++m_version;
+}
+
+static inline bool compareFontFaces(CSSSegmentedFontFace* first, CSSSegmentedFontFace* second, FontTraitsMask desiredTraitsMask)
+{
+ FontTraitsMask firstTraitsMask = first->traitsMask();
+ FontTraitsMask secondTraitsMask = second->traitsMask();
+
+ bool firstHasDesiredVariant = firstTraitsMask & desiredTraitsMask & FontVariantMask;
+ bool secondHasDesiredVariant = secondTraitsMask & desiredTraitsMask & FontVariantMask;
+
+ if (firstHasDesiredVariant != secondHasDesiredVariant)
+ return firstHasDesiredVariant;
+
+ // We need to check font-variant css property for CSS2.1 compatibility.
+ if (desiredTraitsMask & FontVariantSmallCapsMask) {
+ // Prefer a font that has indicated that it can only support small-caps to a font that claims to support
+ // all variants. The specialized font is more likely to be true small-caps and not require synthesis.
+ bool firstRequiresSmallCaps = (firstTraitsMask & FontVariantSmallCapsMask) && !(firstTraitsMask & FontVariantNormalMask);
+ bool secondRequiresSmallCaps = (secondTraitsMask & FontVariantSmallCapsMask) && !(secondTraitsMask & FontVariantNormalMask);
+ if (firstRequiresSmallCaps != secondRequiresSmallCaps)
+ return firstRequiresSmallCaps;
+ }
+
+ bool firstHasDesiredStyle = firstTraitsMask & desiredTraitsMask & FontStyleMask;
+ bool secondHasDesiredStyle = secondTraitsMask & desiredTraitsMask & FontStyleMask;
+
+ if (firstHasDesiredStyle != secondHasDesiredStyle)
+ return firstHasDesiredStyle;
+
+ if (desiredTraitsMask & FontStyleItalicMask) {
+ // Prefer a font that has indicated that it can only support italics to a font that claims to support
+ // all styles. The specialized font is more likely to be the one the author wants used.
+ bool firstRequiresItalics = (firstTraitsMask & FontStyleItalicMask) && !(firstTraitsMask & FontStyleNormalMask);
+ bool secondRequiresItalics = (secondTraitsMask & FontStyleItalicMask) && !(secondTraitsMask & FontStyleNormalMask);
+ if (firstRequiresItalics != secondRequiresItalics)
+ return firstRequiresItalics;
+ }
+
+ if (secondTraitsMask & desiredTraitsMask & FontWeightMask)
+ return false;
+ if (firstTraitsMask & desiredTraitsMask & FontWeightMask)
+ return true;
+
+ // http://www.w3.org/TR/2011/WD-css3-fonts-20111004/#font-matching-algorithm says :
+ // - If the desired weight is less than 400, weights below the desired weight are checked in descending order followed by weights above the desired weight in ascending order until a match is found.
+ // - If the desired weight is greater than 500, weights above the desired weight are checked in ascending order followed by weights below the desired weight in descending order until a match is found.
+ // - If the desired weight is 400, 500 is checked first and then the rule for desired weights less than 400 is used.
+ // - If the desired weight is 500, 400 is checked first and then the rule for desired weights less than 400 is used.
+
+ static const unsigned fallbackRuleSets = 9;
+ static const unsigned rulesPerSet = 8;
+ static const FontTraitsMask weightFallbackRuleSets[fallbackRuleSets][rulesPerSet] = {
+ { FontWeight200Mask, FontWeight300Mask, FontWeight400Mask, FontWeight500Mask, FontWeight600Mask, FontWeight700Mask, FontWeight800Mask, FontWeight900Mask },
+ { FontWeight100Mask, FontWeight300Mask, FontWeight400Mask, FontWeight500Mask, FontWeight600Mask, FontWeight700Mask, FontWeight800Mask, FontWeight900Mask },
+ { FontWeight200Mask, FontWeight100Mask, FontWeight400Mask, FontWeight500Mask, FontWeight600Mask, FontWeight700Mask, FontWeight800Mask, FontWeight900Mask },
+ { FontWeight500Mask, FontWeight300Mask, FontWeight200Mask, FontWeight100Mask, FontWeight600Mask, FontWeight700Mask, FontWeight800Mask, FontWeight900Mask },
+ { FontWeight400Mask, FontWeight300Mask, FontWeight200Mask, FontWeight100Mask, FontWeight600Mask, FontWeight700Mask, FontWeight800Mask, FontWeight900Mask },
+ { FontWeight700Mask, FontWeight800Mask, FontWeight900Mask, FontWeight500Mask, FontWeight400Mask, FontWeight300Mask, FontWeight200Mask, FontWeight100Mask },
+ { FontWeight800Mask, FontWeight900Mask, FontWeight600Mask, FontWeight500Mask, FontWeight400Mask, FontWeight300Mask, FontWeight200Mask, FontWeight100Mask },
+ { FontWeight900Mask, FontWeight700Mask, FontWeight600Mask, FontWeight500Mask, FontWeight400Mask, FontWeight300Mask, FontWeight200Mask, FontWeight100Mask },
+ { FontWeight800Mask, FontWeight700Mask, FontWeight600Mask, FontWeight500Mask, FontWeight400Mask, FontWeight300Mask, FontWeight200Mask, FontWeight100Mask }
+ };
+
+ unsigned ruleSetIndex = 0;
+ unsigned w = FontWeight100Bit;
+ while (!(desiredTraitsMask & (1 << w))) {
+ w++;
+ ruleSetIndex++;
+ }
+
+ ASSERT(ruleSetIndex < fallbackRuleSets);
+ const FontTraitsMask* weightFallbackRule = weightFallbackRuleSets[ruleSetIndex];
+ for (unsigned i = 0; i < rulesPerSet; ++i) {
+ if (secondTraitsMask & weightFallbackRule[i])
+ return false;
+ if (firstTraitsMask & weightFallbackRule[i])
+ return true;
+ }
+
+ return false;
+}
+
+CSSSegmentedFontFace* CSSSegmentedFontFaceCache::get(const FontDescription& fontDescription, const AtomicString& family)
+{
+ TraitsMap* familyFontFaces = m_fontFaces.get(family);
+ if (!familyFontFaces || familyFontFaces->isEmpty())
+ return 0;
+
+ OwnPtr<TraitsMap>& segmentedFontFaceCache = m_fonts.add(family, nullptr).iterator->value;
+ if (!segmentedFontFaceCache)
+ segmentedFontFaceCache = adoptPtr(new TraitsMap);
+
+ FontTraitsMask traitsMask = fontDescription.traitsMask();
+
+ RefPtr<CSSSegmentedFontFace>& face = segmentedFontFaceCache->add(traitsMask, 0).iterator->value;
+ if (!face) {
+ for (TraitsMap::const_iterator i = familyFontFaces->begin(); i != familyFontFaces->end(); ++i) {
+ CSSSegmentedFontFace* candidate = i->value.get();
+ unsigned candidateTraitsMask = candidate->traitsMask();
+ if ((traitsMask & FontStyleNormalMask) && !(candidateTraitsMask & FontStyleNormalMask))
+ continue;
+ if ((traitsMask & FontVariantNormalMask) && !(candidateTraitsMask & FontVariantNormalMask))
+ continue;
+ if (!face || compareFontFaces(candidate, face.get(), traitsMask))
+ face = candidate;
+ }
+ }
+ return face.get();
+}
+
+}
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSSegmentedFontFaceCache.h b/chromium/third_party/WebKit/Source/core/css/CSSSegmentedFontFaceCache.h
new file mode 100644
index 00000000000..c18220906eb
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/css/CSSSegmentedFontFaceCache.h
@@ -0,0 +1,71 @@
+/*
+ * Copyright (C) 2007, 2008, 2011 Apple Inc. All rights reserved.
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef CSSSegmentedFontFaceCache_h
+#define CSSSegmentedFontFaceCache_h
+
+#include "wtf/Forward.h"
+#include "wtf/HashMap.h"
+#include "wtf/text/StringHash.h"
+
+namespace WebCore {
+
+class CSSFontFace;
+class CSSFontSelector;
+class CSSSegmentedFontFace;
+class FontDescription;
+class StyleRuleFontFace;
+
+class CSSSegmentedFontFaceCache {
+public:
+ CSSSegmentedFontFaceCache();
+
+ // FIXME: Remove CSSFontSelector as argument. Passing CSSFontSelector here is
+ // a result of egregious spaghettification in CSSFontFace/FontFaceSet.
+ void add(CSSFontSelector*, const StyleRuleFontFace*, PassRefPtr<CSSFontFace>);
+ void remove(const StyleRuleFontFace*);
+ // FIXME: It's sort of weird that add/remove uses StyleRuleFontFace* as key,
+ // but this function uses FontDescription/family pair.
+ CSSSegmentedFontFace* get(const FontDescription&, const AtomicString& family);
+
+ unsigned version() const { return m_version; }
+
+private:
+ typedef HashMap<unsigned, RefPtr<CSSSegmentedFontFace> > TraitsMap;
+ typedef HashMap<String, OwnPtr<TraitsMap>, CaseFoldingHash> FamilyToTraitsMap;
+ typedef HashMap<const StyleRuleFontFace*, RefPtr<CSSFontFace> > StyleRuleToFontFace;
+ FamilyToTraitsMap m_fontFaces;
+ FamilyToTraitsMap m_fonts;
+ StyleRuleToFontFace m_styleRuleToFontFace;
+
+ // FIXME: See if this could be ditched
+ // Used to compare Font instances, and the usage seems suspect.
+ unsigned m_version;
+};
+
+}
+
+#endif
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSSelector.cpp b/chromium/third_party/WebKit/Source/core/css/CSSSelector.cpp
index e97024769da..b744726355b 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSSelector.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/CSSSelector.cpp
@@ -93,12 +93,15 @@ inline unsigned CSSSelector::specificityForOneSelector() const
switch (m_match) {
case Id:
return 0x10000;
+ case PseudoClass:
+ if (pseudoType() == PseudoHost)
+ return 0;
+ // fall through.
case Exact:
case Class:
case Set:
case List:
case Hyphen:
- case PseudoClass:
case PseudoElement:
case Contain:
case Begin:
@@ -249,7 +252,6 @@ PseudoId CSSSelector::pseudoId(PseudoType type)
case PseudoPastCue:
case PseudoSeamlessDocument:
case PseudoDistributed:
- case PseudoPart:
case PseudoUnresolved:
case PseudoContent:
case PseudoHost:
@@ -280,7 +282,6 @@ static HashMap<StringImpl*, CSSSelector::PseudoType>* nameToPseudoTypeMap()
DEFINE_STATIC_LOCAL(AtomicString, valid, ("valid", AtomicString::ConstructFromLiteral));
DEFINE_STATIC_LOCAL(AtomicString, invalid, ("invalid", AtomicString::ConstructFromLiteral));
DEFINE_STATIC_LOCAL(AtomicString, drag, ("-webkit-drag", AtomicString::ConstructFromLiteral));
- DEFINE_STATIC_LOCAL(AtomicString, dragAlias, ("-khtml-drag", AtomicString::ConstructFromLiteral)); // was documented with this name in Apple documentation, so keep an alia
DEFINE_STATIC_LOCAL(AtomicString, empty, ("empty", AtomicString::ConstructFromLiteral));
DEFINE_STATIC_LOCAL(AtomicString, enabled, ("enabled", AtomicString::ConstructFromLiteral));
DEFINE_STATIC_LOCAL(AtomicString, firstChild, ("first-child", AtomicString::ConstructFromLiteral));
@@ -342,7 +343,6 @@ static HashMap<StringImpl*, CSSSelector::PseudoType>* nameToPseudoTypeMap()
DEFINE_STATIC_LOCAL(AtomicString, inRange, ("in-range", AtomicString::ConstructFromLiteral));
DEFINE_STATIC_LOCAL(AtomicString, outOfRange, ("out-of-range", AtomicString::ConstructFromLiteral));
DEFINE_STATIC_LOCAL(AtomicString, scope, ("scope", AtomicString::ConstructFromLiteral));
- DEFINE_STATIC_LOCAL(AtomicString, part, ("part(", AtomicString::ConstructFromLiteral));
DEFINE_STATIC_LOCAL(AtomicString, unresolved, ("unresolved", AtomicString::ConstructFromLiteral));
DEFINE_STATIC_LOCAL(AtomicString, content, ("content", AtomicString::ConstructFromLiteral));
DEFINE_STATIC_LOCAL(AtomicString, host, ("host", AtomicString::ConstructFromLiteral));
@@ -366,7 +366,6 @@ static HashMap<StringImpl*, CSSSelector::PseudoType>* nameToPseudoTypeMap()
nameToPseudoType->set(valid.impl(), CSSSelector::PseudoValid);
nameToPseudoType->set(invalid.impl(), CSSSelector::PseudoInvalid);
nameToPseudoType->set(drag.impl(), CSSSelector::PseudoDrag);
- nameToPseudoType->set(dragAlias.impl(), CSSSelector::PseudoDrag);
nameToPseudoType->set(enabled.impl(), CSSSelector::PseudoEnabled);
nameToPseudoType->set(empty.impl(), CSSSelector::PseudoEmpty);
nameToPseudoType->set(firstChild.impl(), CSSSelector::PseudoFirstChild);
@@ -428,12 +427,11 @@ static HashMap<StringImpl*, CSSSelector::PseudoType>* nameToPseudoTypeMap()
nameToPseudoType->set(inRange.impl(), CSSSelector::PseudoInRange);
nameToPseudoType->set(outOfRange.impl(), CSSSelector::PseudoOutOfRange);
if (RuntimeEnabledFeatures::shadowDOMEnabled()) {
- nameToPseudoType->set(part.impl(), CSSSelector::PseudoPart);
nameToPseudoType->set(host.impl(), CSSSelector::PseudoHost);
nameToPseudoType->set(hostWithParams.impl(), CSSSelector::PseudoHost);
nameToPseudoType->set(content.impl(), CSSSelector::PseudoContent);
}
- if (RuntimeEnabledFeatures::customElementsEnabled() || RuntimeEnabledFeatures::embedderCustomElementsEnabled())
+ if (RuntimeEnabledFeatures::customElementsEnabled())
nameToPseudoType->set(unresolved.impl(), CSSSelector::PseudoUnresolved);
}
return nameToPseudoType;
@@ -487,7 +485,6 @@ void CSSSelector::extractPseudoType() const
case PseudoSelection:
case PseudoUserAgentCustomElement:
case PseudoWebKitCustomElement:
- case PseudoPart:
case PseudoContent:
element = true;
break;
@@ -670,17 +667,9 @@ String CSSSelector::selectorText(const String& rightSide) const
str.appendLiteral("::");
str.append(cs->value());
- switch (cs->pseudoType()) {
- case PseudoPart:
- str.append(cs->argument());
- str.append(')');
- break;
- case PseudoContent:
+ if (cs->pseudoType() == PseudoContent) {
if (cs->relation() == CSSSelector::SubSelector && cs->tagHistory())
return cs->tagHistory()->selectorText() + str.toString() + rightSide;
- break;
- default:
- break;
}
} else if (cs->isAttributeSelector()) {
str.append('[');
@@ -736,6 +725,10 @@ String CSSSelector::selectorText(const String& rightSide) const
if (cs->relationIsAffectedByPseudoContent() && tagHistory->pseudoType() != CSSSelector::PseudoContent)
return tagHistory->selectorText("::-webkit-distributed(> " + str.toString() + rightSide + ")");
return tagHistory->selectorText(" > " + str.toString() + rightSide);
+ case CSSSelector::ChildTree:
+ return tagHistory->selectorText(" ^ " + str.toString() + rightSide);
+ case CSSSelector::DescendantTree:
+ return tagHistory->selectorText(" ^^ " + str.toString() + rightSide);
case CSSSelector::DirectAdjacent:
return tagHistory->selectorText(" + " + str.toString() + rightSide);
case CSSSelector::IndirectAdjacent:
@@ -767,12 +760,6 @@ void CSSSelector::setSelectorList(PassOwnPtr<CSSSelectorList> selectorList)
m_data.m_rareData->m_selectorList = selectorList;
}
-void CSSSelector::setMatchUserAgentOnly()
-{
- createRareData();
- m_data.m_rareData->m_matchUserAgentOnly = true;
-}
-
static bool validateSubSelector(const CSSSelector* selector)
{
switch (selector->m_match) {
@@ -812,6 +799,7 @@ static bool validateSubSelector(const CSSSelector* selector)
case CSSSelector::PseudoFirstOfType:
case CSSSelector::PseudoLastOfType:
case CSSSelector::PseudoOnlyOfType:
+ case CSSSelector::PseudoHost:
return true;
default:
return false;
@@ -861,7 +849,6 @@ CSSSelector::RareData::RareData(PassRefPtr<StringImpl> value)
, m_b(0)
, m_attribute(anyQName())
, m_argument(nullAtom)
- , m_matchUserAgentOnly(0)
{
}
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSSelector.h b/chromium/third_party/WebKit/Source/core/css/CSSSelector.h
index 028e5124ba7..b0094687fb6 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSSelector.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSSelector.h
@@ -76,7 +76,10 @@ namespace WebCore {
DirectAdjacent,
IndirectAdjacent,
SubSelector,
- ShadowPseudo
+ ShadowPseudo,
+ // FIXME: rename ChildTree and DescendantTree when the spec for this is written down.
+ ChildTree,
+ DescendantTree
};
enum PseudoType {
@@ -160,7 +163,6 @@ namespace WebCore {
PseudoPastCue,
PseudoSeamlessDocument,
PseudoDistributed,
- PseudoPart,
PseudoUnresolved,
PseudoContent,
PseudoHost
@@ -201,10 +203,15 @@ namespace WebCore {
const QualifiedName& tagQName() const;
const AtomicString& value() const;
+
+ // WARNING: Use of QualifiedName by attribute() is a lie.
+ // attribute() will return a QualifiedName with prefix and namespaceURI
+ // set to starAtom to mean "matches any namespace". Be very careful
+ // how you use the returned QualifiedName.
+ // http://www.w3.org/TR/css3-selectors/#attrnmsp
const QualifiedName& attribute() const;
const AtomicString& argument() const { return m_hasRareData ? m_data.m_rareData->m_argument : nullAtom; }
const CSSSelectorList* selectorList() const { return m_hasRareData ? m_data.m_rareData->m_selectorList.get() : 0; }
- bool isMatchUserAgentOnly() const { return m_hasRareData ? m_data.m_rareData->m_matchUserAgentOnly : false; }
void setValue(const AtomicString&);
void setAttribute(const QualifiedName&);
@@ -218,10 +225,12 @@ namespace WebCore {
bool matchesPseudoElement() const;
bool isUnknownPseudoElement() const;
bool isCustomPseudoElement() const;
+ bool isDirectAdjacentSelector() const { return m_relation == DirectAdjacent; }
bool isSiblingSelector() const;
bool isAttributeSelector() const;
bool isDistributedPseudoElement() const;
bool isContentPseudoElement() const;
+ bool isHostPseudoClass() const;
Relation relation() const { return static_cast<Relation>(m_relation); }
@@ -270,9 +279,8 @@ namespace WebCore {
int m_a; // Used for :nth-*
int m_b; // Used for :nth-*
QualifiedName m_attribute; // used for attribute selector
- AtomicString m_argument; // Used for :contains, :lang, :nth-* and ::part
+ AtomicString m_argument; // Used for :contains, :lang, :nth-*
OwnPtr<CSSSelectorList> m_selectorList; // Used for :-webkit-any and :not
- unsigned m_matchUserAgentOnly : 1; // Used to make ::part with "-webkit"-prefixed part name match only elements in UA shadow roots.
private:
RareData(PassRefPtr<StringImpl> value);
@@ -308,7 +316,12 @@ inline bool CSSSelector::isUnknownPseudoElement() const
inline bool CSSSelector::isCustomPseudoElement() const
{
- return m_match == PseudoElement && (m_pseudoType == PseudoUserAgentCustomElement || m_pseudoType == PseudoWebKitCustomElement || m_pseudoType == PseudoPart);
+ return m_match == PseudoElement && (m_pseudoType == PseudoUserAgentCustomElement || m_pseudoType == PseudoWebKitCustomElement);
+}
+
+inline bool CSSSelector::isHostPseudoClass() const
+{
+ return m_match == PseudoClass && m_pseudoType == PseudoHost;
}
inline bool CSSSelector::isSiblingSelector() const
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSSelectorList.cpp b/chromium/third_party/WebKit/Source/core/css/CSSSelectorList.cpp
index 30ac8eb6d51..a3b8bdc7c12 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSSelectorList.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/CSSSelectorList.cpp
@@ -99,8 +99,12 @@ void CSSSelectorList::deleteSelectors()
if (!m_selectorArray)
return;
- for (CSSSelector* s = m_selectorArray; !s->isLastInSelectorList(); ++s)
+ bool finished = false;
+ for (CSSSelector* s = m_selectorArray; !finished; ++s) {
+ finished = s->isLastInSelectorList();
s->~CSSSelector();
+ }
+
fastFree(m_selectorArray);
}
@@ -179,4 +183,18 @@ bool CSSSelectorList::hasShadowDistributedAt(size_t index) const
return forEachTagSelector(functor, selectorAt(index));
}
+class SelectorHasCombinatorCrossingTreeBoundary {
+public:
+ bool operator()(const CSSSelector* selector)
+ {
+ return selector->relation() == CSSSelector::ChildTree || selector->relation() == CSSSelector::DescendantTree;
+ }
+};
+
+bool CSSSelectorList::hasCombinatorCrossingTreeBoundaryAt(size_t index) const
+{
+ SelectorHasCombinatorCrossingTreeBoundary functor;
+ return forEachTagSelector(functor, selectorAt(index));
+}
+
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSSelectorList.h b/chromium/third_party/WebKit/Source/core/css/CSSSelectorList.h
index 562e649db4d..320de3b4175 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSSelectorList.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSSelectorList.h
@@ -61,6 +61,7 @@ public:
bool selectorsNeedNamespaceResolution();
bool hasShadowDistributedAt(size_t index) const;
+ bool hasCombinatorCrossingTreeBoundaryAt(size_t index) const;
String selectorsText() const;
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSShaderValue.cpp b/chromium/third_party/WebKit/Source/core/css/CSSShaderValue.cpp
index a46e2e74aa0..1fafe3008f1 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSShaderValue.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/CSSShaderValue.cpp
@@ -81,7 +81,7 @@ StyleShader* CSSShaderValue::cachedOrPendingShader()
return m_shader.get();
}
-String CSSShaderValue::customCssText() const
+String CSSShaderValue::customCSSText() const
{
StringBuilder result;
result.appendLiteral("url(");
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSShaderValue.h b/chromium/third_party/WebKit/Source/core/css/CSSShaderValue.h
index 69daf55d1fb..9c736262402 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSShaderValue.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSShaderValue.h
@@ -51,7 +51,7 @@ public:
StyleFetchedShader* resource(ResourceFetcher*);
StyleShader* cachedOrPendingShader();
- String customCssText() const;
+ String customCSSText() const;
bool equals(const CSSShaderValue&) const;
@@ -64,13 +64,7 @@ private:
bool m_accessedShader;
};
-// This will catch anyone doing an unnecessary cast.
-CSSShaderValue* toCSSShaderValue(const CSSShaderValue*);
-
-inline CSSShaderValue* toCSSShaderValue(CSSValue* value)
-{
- return value->isCSSShaderValue() ? static_cast<CSSShaderValue*>(value) : 0;
-}
+DEFINE_CSS_VALUE_TYPE_CASTS(CSSShaderValue, isShaderValue());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSShadowValue.cpp b/chromium/third_party/WebKit/Source/core/css/CSSShadowValue.cpp
new file mode 100644
index 00000000000..35ecefb8cf9
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/css/CSSShadowValue.cpp
@@ -0,0 +1,91 @@
+/**
+ * (C) 1999-2003 Lars Knoll (knoll@kde.org)
+ * Copyright (C) 2004, 2005, 2006, 2009 Apple Computer, Inc.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+#include "config.h"
+#include "core/css/CSSShadowValue.h"
+
+#include "core/css/CSSPrimitiveValue.h"
+#include "wtf/text/StringBuilder.h"
+#include "wtf/text/WTFString.h"
+
+namespace WebCore {
+
+// Used for text-shadow and box-shadow
+CSSShadowValue::CSSShadowValue(PassRefPtr<CSSPrimitiveValue> x,
+ PassRefPtr<CSSPrimitiveValue> y,
+ PassRefPtr<CSSPrimitiveValue> blur,
+ PassRefPtr<CSSPrimitiveValue> spread,
+ PassRefPtr<CSSPrimitiveValue> style,
+ PassRefPtr<CSSPrimitiveValue> color)
+ : CSSValue(ShadowClass)
+ , x(x)
+ , y(y)
+ , blur(blur)
+ , spread(spread)
+ , style(style)
+ , color(color)
+{
+}
+
+String CSSShadowValue::customCSSText() const
+{
+ StringBuilder text;
+
+ if (color)
+ text.append(color->cssText());
+ if (x) {
+ if (!text.isEmpty())
+ text.append(' ');
+ text.append(x->cssText());
+ }
+ if (y) {
+ if (!text.isEmpty())
+ text.append(' ');
+ text.append(y->cssText());
+ }
+ if (blur) {
+ if (!text.isEmpty())
+ text.append(' ');
+ text.append(blur->cssText());
+ }
+ if (spread) {
+ if (!text.isEmpty())
+ text.append(' ');
+ text.append(spread->cssText());
+ }
+ if (style) {
+ if (!text.isEmpty())
+ text.append(' ');
+ text.append(style->cssText());
+ }
+
+ return text.toString();
+}
+
+bool CSSShadowValue::equals(const CSSShadowValue& other) const
+{
+ return compareCSSValuePtr(color, other.color)
+ && compareCSSValuePtr(x, other.x)
+ && compareCSSValuePtr(y, other.y)
+ && compareCSSValuePtr(blur, other.blur)
+ && compareCSSValuePtr(spread, other.spread)
+ && compareCSSValuePtr(style, other.style);
+}
+
+}
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSShadowValue.h b/chromium/third_party/WebKit/Source/core/css/CSSShadowValue.h
new file mode 100644
index 00000000000..79fe736c6f5
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/css/CSSShadowValue.h
@@ -0,0 +1,69 @@
+/*
+ * (C) 1999-2003 Lars Knoll (knoll@kde.org)
+ * Copyright (C) 2004, 2005, 2006, 2008, 2009 Apple Inc. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#ifndef CSSShadowValue_h
+#define CSSShadowValue_h
+
+#include "core/css/CSSValue.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefPtr.h"
+
+namespace WebCore {
+
+class CSSPrimitiveValue;
+
+// Used for text-shadow and box-shadow
+class CSSShadowValue : public CSSValue {
+public:
+ static PassRefPtr<CSSShadowValue> create(PassRefPtr<CSSPrimitiveValue> x,
+ PassRefPtr<CSSPrimitiveValue> y,
+ PassRefPtr<CSSPrimitiveValue> blur,
+ PassRefPtr<CSSPrimitiveValue> spread,
+ PassRefPtr<CSSPrimitiveValue> style,
+ PassRefPtr<CSSPrimitiveValue> color)
+ {
+ return adoptRef(new CSSShadowValue(x, y, blur, spread, style, color));
+ }
+
+ String customCSSText() const;
+
+ bool equals(const CSSShadowValue&) const;
+
+ RefPtr<CSSPrimitiveValue> x;
+ RefPtr<CSSPrimitiveValue> y;
+ RefPtr<CSSPrimitiveValue> blur;
+ RefPtr<CSSPrimitiveValue> spread;
+ RefPtr<CSSPrimitiveValue> style;
+ RefPtr<CSSPrimitiveValue> color;
+
+private:
+ CSSShadowValue(PassRefPtr<CSSPrimitiveValue> x,
+ PassRefPtr<CSSPrimitiveValue> y,
+ PassRefPtr<CSSPrimitiveValue> blur,
+ PassRefPtr<CSSPrimitiveValue> spread,
+ PassRefPtr<CSSPrimitiveValue> style,
+ PassRefPtr<CSSPrimitiveValue> color);
+};
+
+DEFINE_CSS_VALUE_TYPE_CASTS(CSSShadowValue, isShadowValue());
+
+} // namespace
+
+#endif
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSShorthands.in b/chromium/third_party/WebKit/Source/core/css/CSSShorthands.in
index ea55299ee00..f66d64994df 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSShorthands.in
+++ b/chromium/third_party/WebKit/Source/core/css/CSSShorthands.in
@@ -43,6 +43,7 @@ transition longhands=transition-property;transition-duration;transition-timing-f
-webkit-column-rule longhands=-webkit-column-rule-width;-webkit-column-rule-style;-webkit-column-rule-color
-webkit-margin-collapse longhands=-webkit-margin-before-collapse;-webkit-margin-after-collapse
-webkit-mask longhands=-webkit-mask-image;-webkit-mask-position-x;-webkit-mask-position-y;-webkit-mask-size;-webkit-mask-repeat-x;-webkit-mask-repeat-y;-webkit-mask-origin;-webkit-mask-clip
+-webkit-mask-box-image longhands=-webkit-mask-box-image-source;-webkit-mask-box-image-slice;-webkit-mask-box-image-width;-webkit-mask-box-image-outset;-webkit-mask-box-image-repeat
-webkit-mask-position longhands=-webkit-mask-position-x;-webkit-mask-position-y
-webkit-mask-repeat longhands=-webkit-mask-repeat-x;-webkit-mask-repeat-y
-webkit-text-emphasis longhands=-webkit-text-emphasis-style;-webkit-text-emphasis-color
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSStyleDeclaration.cpp b/chromium/third_party/WebKit/Source/core/css/CSSStyleDeclaration.cpp
index 1999c323d6d..1347f99c5c0 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSStyleDeclaration.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/CSSStyleDeclaration.cpp
@@ -29,7 +29,6 @@
#include "config.h"
#include "core/css/CSSStyleDeclaration.h"
-#include "core/css/CSSVariablesMap.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSStyleDeclaration.h b/chromium/third_party/WebKit/Source/core/css/CSSStyleDeclaration.h
index 5d30cae735b..5c2445af31a 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSStyleDeclaration.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSStyleDeclaration.h
@@ -23,6 +23,7 @@
#include "CSSPropertyNames.h"
#include "bindings/v8/ScriptWrappable.h"
+#include "core/css/CSSVariablesIterator.h"
#include "core/css/CSSVariablesMap.h"
#include "wtf/Forward.h"
#include "wtf/Noncopyable.h"
@@ -47,7 +48,7 @@ public:
virtual CSSRule* parentRule() const = 0;
virtual String cssText() const = 0;
- virtual void setCssText(const String&, ExceptionState&) = 0;
+ virtual void setCSSText(const String&, ExceptionState&) = 0;
virtual unsigned length() const = 0;
virtual String item(unsigned index) const = 0;
virtual PassRefPtr<CSSValue> getPropertyCSSValue(const String& propertyName) = 0;
@@ -61,9 +62,10 @@ public:
PassRefPtr<CSSVariablesMap> var();
virtual unsigned variableCount() const = 0;
virtual String variableValue(const AtomicString& name) const = 0;
- virtual void setVariableValue(const AtomicString& name, const String& value, ExceptionState&) = 0;
+ virtual bool setVariableValue(const AtomicString& name, const String& value, ExceptionState&) = 0; // Return value indicates whether variable was added.
virtual bool removeVariable(const AtomicString& name) = 0;
- virtual void clearVariables(ExceptionState&) = 0;
+ virtual bool clearVariables(ExceptionState&) = 0;
+ virtual PassRefPtr<CSSVariablesIterator> variablesIterator() const = 0;
// CSSPropertyID versions of the CSSOM functions to support bindings and editing.
// Use the non-virtual methods in the concrete subclasses when possible.
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSStyleDeclaration.idl b/chromium/third_party/WebKit/Source/core/css/CSSStyleDeclaration.idl
index 4f1bdf69650..f552573a8eb 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSStyleDeclaration.idl
+++ b/chromium/third_party/WebKit/Source/core/css/CSSStyleDeclaration.idl
@@ -22,7 +22,7 @@
[
DependentLifetime
] interface CSSStyleDeclaration {
- [TreatReturnedNullStringAs=Null, TreatNullAs=NullString, SetterRaisesException] attribute DOMString cssText;
+ [TreatReturnedNullStringAs=Null, TreatNullAs=NullString, RaisesException=Setter] attribute DOMString cssText;
[TreatReturnedNullStringAs=Null] DOMString getPropertyValue([Default=Undefined] optional DOMString propertyName);
CSSValue getPropertyCSSValue([Default=Undefined] optional DOMString propertyName);
@@ -37,6 +37,6 @@
[Custom, CustomEnumerateProperty] getter (DOMString or float) (DOMString name);
[Custom] setter void (DOMString propertyName, [TreatNullAs=NullString] DOMString propertyValue);
readonly attribute CSSRule parentRule;
- [EnabledAtRuntime=CSSVariables] readonly attribute CSSVariablesMap var;
+ [RuntimeEnabled=CSSVariables] readonly attribute CSSVariablesMap var;
};
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSStyleRule.cpp b/chromium/third_party/WebKit/Source/core/css/CSSStyleRule.cpp
index 35ea690c0a6..1ab4c5203a4 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSStyleRule.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/CSSStyleRule.cpp
@@ -123,8 +123,7 @@ String CSSStyleRule::cssText() const
void CSSStyleRule::reattach(StyleRuleBase* rule)
{
ASSERT(rule);
- ASSERT_WITH_SECURITY_IMPLICATION(rule->isStyleRule());
- m_styleRule = static_cast<StyleRule*>(rule);
+ m_styleRule = toStyleRule(rule);
if (m_propertiesCSSOMWrapper)
m_propertiesCSSOMWrapper->reattach(m_styleRule->mutableProperties());
}
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSStyleRule.h b/chromium/third_party/WebKit/Source/core/css/CSSStyleRule.h
index f608a2f4051..12b4562f039 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSStyleRule.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSStyleRule.h
@@ -57,11 +57,7 @@ private:
mutable RefPtr<StyleRuleCSSStyleDeclaration> m_propertiesCSSOMWrapper;
};
-inline CSSStyleRule* toCSSStyleRule(CSSRule* rule)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(rule->type() == CSSRule::STYLE_RULE);
- return static_cast<CSSStyleRule*>(rule);
-}
+DEFINE_CSS_RULE_TYPE_CASTS(CSSStyleRule, STYLE_RULE);
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSStyleRule.idl b/chromium/third_party/WebKit/Source/core/css/CSSStyleRule.idl
index 23cd73af4a3..b5c890f63bb 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSStyleRule.idl
+++ b/chromium/third_party/WebKit/Source/core/css/CSSStyleRule.idl
@@ -20,10 +20,6 @@
// Introduced in DOM Level 2:
interface CSSStyleRule : CSSRule {
-
- [TreatReturnedNullStringAs=Null, TreatNullAs=NullString] attribute DOMString selectorText;
-
+ attribute DOMString selectorText;
readonly attribute CSSStyleDeclaration style;
-
};
-
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSStyleSheet.cpp b/chromium/third_party/WebKit/Source/core/css/CSSStyleSheet.cpp
index 1f6e6e7e3c2..e7fe16ecd27 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSStyleSheet.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/CSSStyleSheet.cpp
@@ -28,13 +28,16 @@
#include "core/css/CSSImportRule.h"
#include "core/css/CSSParser.h"
#include "core/css/CSSRuleList.h"
+#include "core/css/CSSStyleRule.h"
#include "core/css/MediaList.h"
#include "core/css/StyleRule.h"
#include "core/css/StyleSheetContents.h"
#include "core/dom/Document.h"
#include "core/dom/ExceptionCode.h"
#include "core/dom/Node.h"
-#include "weborigin/SecurityOrigin.h"
+#include "core/frame/UseCounter.h"
+#include "core/inspector/InspectorInstrumentation.h"
+#include "platform/weborigin/SecurityOrigin.h"
#include "wtf/text/StringBuilder.h"
namespace WebCore {
@@ -117,22 +120,54 @@ CSSStyleSheet::~CSSStyleSheet()
if (m_childRuleCSSOMWrappers[i])
m_childRuleCSSOMWrappers[i]->setParentStyleSheet(0);
}
+
+ for (unsigned i = 0; i < m_extraChildRuleCSSOMWrappers.size(); ++i)
+ m_extraChildRuleCSSOMWrappers[i]->setParentStyleSheet(0);
+
if (m_mediaCSSOMWrapper)
m_mediaCSSOMWrapper->clearParentStyleSheet();
m_contents->unregisterClient(this);
}
+void CSSStyleSheet::extraCSSOMWrapperIndices(Vector<unsigned>& indices)
+{
+ indices.grow(m_extraChildRuleCSSOMWrappers.size());
+
+ for (unsigned i = 0; i < m_extraChildRuleCSSOMWrappers.size(); ++i) {
+ CSSRule* cssRule = m_extraChildRuleCSSOMWrappers[i].get();
+ ASSERT(cssRule->type() == CSSRule::STYLE_RULE);
+ StyleRule* styleRule = toCSSStyleRule(cssRule)->styleRule();
+
+ bool didFindIndex = false;
+ for (unsigned j = 0; j < m_contents->ruleCount(); ++j) {
+ if (m_contents->ruleAt(j) == styleRule) {
+ didFindIndex = true;
+ indices[i] = j;
+ break;
+ }
+ }
+ ASSERT(didFindIndex);
+ if (!didFindIndex)
+ indices[i] = 0;
+ }
+}
+
void CSSStyleSheet::willMutateRules()
{
+ InspectorInstrumentation::willMutateRules(this);
// If we are the only client it is safe to mutate.
if (m_contents->hasOneClient() && !m_contents->isInMemoryCache()) {
+ m_contents->clearRuleSet();
m_contents->setMutable();
return;
}
// Only cacheable stylesheets should have multiple clients.
ASSERT(m_contents->isCacheable());
+ Vector<unsigned> indices;
+ extraCSSOMWrapperIndices(indices);
+
// Copy-on-write.
m_contents->unregisterClient(this);
m_contents = m_contents->copy();
@@ -141,7 +176,7 @@ void CSSStyleSheet::willMutateRules()
m_contents->setMutable();
// Any existing CSSOM wrappers need to be connected to the copied child rules.
- reattachChildRuleCSSOMWrappers();
+ reattachChildRuleCSSOMWrappers(indices);
}
void CSSStyleSheet::didMutateRules()
@@ -149,19 +184,33 @@ void CSSStyleSheet::didMutateRules()
ASSERT(m_contents->isMutable());
ASSERT(m_contents->hasOneClient());
- didMutate();
+ InspectorInstrumentation::didMutateRules(this);
+ didMutate(PartialRuleUpdate);
}
-void CSSStyleSheet::didMutate()
+void CSSStyleSheet::didMutate(StyleSheetUpdateType updateType)
{
Document* owner = ownerDocument();
if (!owner)
return;
- owner->modifiedStyleSheet(this);
+
+ // Need FullStyleUpdate when insertRule or deleteRule,
+ // because StyleSheetCollection::analyzeStyleSheetChange cannot detect partial rule update.
+ StyleResolverUpdateMode updateMode = updateType != PartialRuleUpdate ? AnalyzedStyleUpdate : FullStyleUpdate;
+ owner->modifiedStyleSheet(this, RecalcStyleDeferred, updateMode);
+}
+
+void CSSStyleSheet::registerExtraChildRuleCSSOMWrapper(PassRefPtr<CSSRule> rule)
+{
+ m_extraChildRuleCSSOMWrappers.append(rule);
}
-void CSSStyleSheet::reattachChildRuleCSSOMWrappers()
+void CSSStyleSheet::reattachChildRuleCSSOMWrappers(const Vector<unsigned>& extraCSSOMWrapperIndices)
{
+ ASSERT(extraCSSOMWrapperIndices.size() == m_extraChildRuleCSSOMWrappers.size());
+ for (unsigned i = 0; i < extraCSSOMWrapperIndices.size(); ++i)
+ m_extraChildRuleCSSOMWrappers[i]->reattach(m_contents->ruleAt(extraCSSOMWrapperIndices[i]));
+
for (unsigned i = 0; i < m_childRuleCSSOMWrappers.size(); ++i) {
if (!m_childRuleCSSOMWrappers[i])
continue;
@@ -245,26 +294,26 @@ PassRefPtr<CSSRuleList> CSSStyleSheet::rules()
return nonCharsetRules.release();
}
-unsigned CSSStyleSheet::insertRule(const String& ruleString, unsigned index, ExceptionState& es)
+unsigned CSSStyleSheet::insertRule(const String& ruleString, unsigned index, ExceptionState& exceptionState)
{
ASSERT(m_childRuleCSSOMWrappers.isEmpty() || m_childRuleCSSOMWrappers.size() == m_contents->ruleCount());
if (index > length()) {
- es.throwDOMException(IndexSizeError);
+ exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
return 0;
}
CSSParser p(m_contents->parserContext(), UseCounter::getFrom(this));
RefPtr<StyleRuleBase> rule = p.parseRule(m_contents.get(), ruleString);
if (!rule) {
- es.throwDOMException(SyntaxError);
+ exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
return 0;
}
RuleMutationScope mutationScope(this);
bool success = m_contents->wrapperInsertRule(rule, index);
if (!success) {
- es.throwDOMException(HierarchyRequestError);
+ exceptionState.throwUninformativeAndGenericDOMException(HierarchyRequestError);
return 0;
}
if (!m_childRuleCSSOMWrappers.isEmpty())
@@ -273,12 +322,18 @@ unsigned CSSStyleSheet::insertRule(const String& ruleString, unsigned index, Exc
return index;
}
-void CSSStyleSheet::deleteRule(unsigned index, ExceptionState& es)
+unsigned CSSStyleSheet::insertRule(const String& rule, ExceptionState& exceptionState)
+{
+ UseCounter::countDeprecation(activeExecutionContext(), UseCounter::CSSStyleSheetInsertRuleOptionalArg);
+ return insertRule(rule, 0, exceptionState);
+}
+
+void CSSStyleSheet::deleteRule(unsigned index, ExceptionState& exceptionState)
{
ASSERT(m_childRuleCSSOMWrappers.isEmpty() || m_childRuleCSSOMWrappers.size() == m_contents->ruleCount());
if (index >= length()) {
- es.throwDOMException(IndexSizeError);
+ exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
return;
}
RuleMutationScope mutationScope(this);
@@ -292,7 +347,7 @@ void CSSStyleSheet::deleteRule(unsigned index, ExceptionState& es)
}
}
-int CSSStyleSheet::addRule(const String& selector, const String& style, int index, ExceptionState& es)
+int CSSStyleSheet::addRule(const String& selector, const String& style, int index, ExceptionState& exceptionState)
{
StringBuilder text;
text.append(selector);
@@ -301,15 +356,15 @@ int CSSStyleSheet::addRule(const String& selector, const String& style, int inde
if (!style.isEmpty())
text.append(' ');
text.append('}');
- insertRule(text.toString(), index, es);
+ insertRule(text.toString(), index, exceptionState);
// As per Microsoft documentation, always return -1.
return -1;
}
-int CSSStyleSheet::addRule(const String& selector, const String& style, ExceptionState& es)
+int CSSStyleSheet::addRule(const String& selector, const String& style, ExceptionState& exceptionState)
{
- return addRule(selector, style, length(), es);
+ return addRule(selector, style, length(), exceptionState);
}
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSStyleSheet.h b/chromium/third_party/WebKit/Source/core/css/CSSStyleSheet.h
index f81fdef1440..3c02c230c9f 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSStyleSheet.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSStyleSheet.h
@@ -41,6 +41,11 @@ class MediaQuerySet;
class SecurityOrigin;
class StyleSheetContents;
+enum StyleSheetUpdateType {
+ PartialRuleUpdate,
+ EntireStyleSheetUpdate
+};
+
class CSSStyleSheet : public StyleSheet {
public:
static PassRefPtr<CSSStyleSheet> create(PassRefPtr<StyleSheetContents>, CSSImportRule* ownerRule = 0);
@@ -59,19 +64,20 @@ public:
PassRefPtr<CSSRuleList> cssRules();
unsigned insertRule(const String& rule, unsigned index, ExceptionState&);
+ unsigned insertRule(const String& rule, ExceptionState&); // Deprecated.
void deleteRule(unsigned index, ExceptionState&);
// IE Extensions
PassRefPtr<CSSRuleList> rules();
int addRule(const String& selector, const String& style, int index, ExceptionState&);
int addRule(const String& selector, const String& style, ExceptionState&);
- void removeRule(unsigned index, ExceptionState& es) { deleteRule(index, es); }
+ void removeRule(unsigned index, ExceptionState& exceptionState) { deleteRule(index, exceptionState); }
// For CSSRuleList.
unsigned length() const;
CSSRule* item(unsigned index);
- virtual void clearOwnerNode() OVERRIDE { didMutate(); m_ownerNode = 0; }
+ virtual void clearOwnerNode() OVERRIDE { didMutate(EntireStyleSheetUpdate); m_ownerNode = 0; }
virtual CSSRule* ownerRule() const OVERRIDE { return m_ownerRule; }
virtual KURL baseURL() const OVERRIDE;
virtual bool isLoading() const OVERRIDE;
@@ -95,10 +101,11 @@ public:
void willMutateRules();
void didMutateRules();
- void didMutate();
+ void didMutate(StyleSheetUpdateType = PartialRuleUpdate);
void clearChildRuleCSSOMWrappers();
- void reattachChildRuleCSSOMWrappers();
+
+ void registerExtraChildRuleCSSOMWrapper(PassRefPtr<CSSRule>);
StyleSheetContents* contents() const { return m_contents.get(); }
@@ -112,6 +119,9 @@ private:
virtual bool isCSSStyleSheet() const { return true; }
virtual String type() const { return "text/css"; }
+ void extraCSSOMWrapperIndices(Vector<unsigned>& indices);
+ void reattachChildRuleCSSOMWrappers(const Vector<unsigned>& extraCSSOMWrapperIndices);
+
bool canAccessRules() const;
RefPtr<StyleSheetContents> m_contents;
@@ -127,6 +137,9 @@ private:
mutable RefPtr<MediaList> m_mediaCSSOMWrapper;
mutable Vector<RefPtr<CSSRule> > m_childRuleCSSOMWrappers;
+ // These are CSSOMWrappers that come from getMatchedCSSRules and thus don't map 1-1 to
+ // the StyleRules in the StyleSheetContents.
+ mutable Vector<RefPtr<CSSRule> > m_extraChildRuleCSSOMWrappers;
mutable OwnPtr<CSSRuleList> m_ruleListCSSOMWrapper;
};
@@ -150,6 +163,8 @@ inline CSSStyleSheet::RuleMutationScope::~RuleMutationScope()
m_styleSheet->didMutateRules();
}
+DEFINE_TYPE_CASTS(CSSStyleSheet, StyleSheet, sheet, sheet->isCSSStyleSheet(), sheet.isCSSStyleSheet());
+
} // namespace
#endif
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSStyleSheet.idl b/chromium/third_party/WebKit/Source/core/css/CSSStyleSheet.idl
index 986303a8d66..a9b09007967 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSStyleSheet.idl
+++ b/chromium/third_party/WebKit/Source/core/css/CSSStyleSheet.idl
@@ -20,20 +20,19 @@
// Introduced in DOM Level 2:
[
- GenerateIsReachable=ownerNode
+ GenerateVisitDOMWrapper=ownerNode,
] interface CSSStyleSheet : StyleSheet {
readonly attribute CSSRule ownerRule;
readonly attribute CSSRuleList cssRules;
- [RaisesException] unsigned long insertRule(DOMString rule, unsigned long index);
+ [RaisesException] unsigned long insertRule(DOMString rule, optional unsigned long index);
[RaisesException] void deleteRule(unsigned long index);
// IE Extensions
- readonly attribute CSSRuleList rules;
+ [MeasureAs=CSSStyleSheetRules] readonly attribute CSSRuleList rules;
- [RaisesException] long addRule([Default=Undefined] optional DOMString selector,
- [Default=Undefined] optional DOMString style,
- optional unsigned long index);
- [RaisesException] void removeRule([Default=Undefined] optional unsigned long index);
+ [RaisesException, MeasureAs=CSSStyleSheetAddRule] long addRule([Default=Undefined] optional DOMString selector,
+ [Default=Undefined] optional DOMString style,
+ optional unsigned long index);
+ [RaisesException, MeasureAs=CSSStyleSheetRemoveRule] void removeRule([Default=Undefined] optional unsigned long index);
};
-
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSSupportsRule.cpp b/chromium/third_party/WebKit/Source/core/css/CSSSupportsRule.cpp
index 08244c6cf64..705272cfdb0 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSSupportsRule.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/CSSSupportsRule.cpp
@@ -47,7 +47,7 @@ String CSSSupportsRule::cssText() const
result.append("@supports ");
result.append(conditionText());
result.append(" {\n");
- appendCssTextForItems(result);
+ appendCSSTextForItems(result);
result.append('}');
return result.toString();
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSSupportsRule.h b/chromium/third_party/WebKit/Source/core/css/CSSSupportsRule.h
index c797db14ab2..4d15dd2523f 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSSupportsRule.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSSupportsRule.h
@@ -54,6 +54,8 @@ private:
CSSSupportsRule(StyleRuleSupports*, CSSStyleSheet*);
};
+DEFINE_CSS_RULE_TYPE_CASTS(CSSSupportsRule, SUPPORTS_RULE);
+
} // namespace WebCore
#endif // CSSSupportsRule_h
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSTimingFunctionValue.cpp b/chromium/third_party/WebKit/Source/core/css/CSSTimingFunctionValue.cpp
index 8c131027a09..49420cbb26b 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSTimingFunctionValue.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/CSSTimingFunctionValue.cpp
@@ -30,7 +30,7 @@
namespace WebCore {
-String CSSCubicBezierTimingFunctionValue::customCssText() const
+String CSSCubicBezierTimingFunctionValue::customCSSText() const
{
return "cubic-bezier("
+ String::number(m_x1) + ", "
@@ -44,7 +44,7 @@ bool CSSCubicBezierTimingFunctionValue::equals(const CSSCubicBezierTimingFunctio
return m_x1 == other.m_x1 && m_x2 == other.m_x2 && m_y1 == other.m_y1 && m_y2 == other.m_y2;
}
-String CSSStepsTimingFunctionValue::customCssText() const
+String CSSStepsTimingFunctionValue::customCSSText() const
{
return "steps(" + String::number(m_steps) + ", " + (m_stepAtStart ? "start" : "end") + ')';
}
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSTimingFunctionValue.h b/chromium/third_party/WebKit/Source/core/css/CSSTimingFunctionValue.h
index 87f2b7ad943..54f566171c2 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSTimingFunctionValue.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSTimingFunctionValue.h
@@ -38,7 +38,7 @@ public:
return adoptRef(new CSSCubicBezierTimingFunctionValue(x1, y1, x2, y2));
}
- String customCssText() const;
+ String customCSSText() const;
double x1() const { return m_x1; }
double y1() const { return m_y1; }
@@ -63,6 +63,8 @@ private:
double m_y2;
};
+DEFINE_CSS_VALUE_TYPE_CASTS(CSSCubicBezierTimingFunctionValue, isCubicBezierTimingFunctionValue());
+
class CSSStepsTimingFunctionValue : public CSSValue {
public:
static PassRefPtr<CSSStepsTimingFunctionValue> create(int steps, bool stepAtStart)
@@ -73,7 +75,7 @@ public:
int numberOfSteps() const { return m_steps; }
bool stepAtStart() const { return m_stepAtStart; }
- String customCssText() const;
+ String customCSSText() const;
bool equals(const CSSStepsTimingFunctionValue&) const;
@@ -89,6 +91,8 @@ private:
bool m_stepAtStart;
};
+DEFINE_CSS_VALUE_TYPE_CASTS(CSSStepsTimingFunctionValue, isStepsTimingFunctionValue());
+
} // namespace
#endif
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSToLengthConversionData.cpp b/chromium/third_party/WebKit/Source/core/css/CSSToLengthConversionData.cpp
new file mode 100644
index 00000000000..6085a69892b
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/css/CSSToLengthConversionData.cpp
@@ -0,0 +1,45 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/css/CSSToLengthConversionData.h"
+
+#include "core/rendering/style/RenderStyle.h"
+
+namespace WebCore {
+
+float CSSToLengthConversionData::zoom() const
+{
+ if (m_useEffectiveZoom)
+ return m_style ? m_style->effectiveZoom() : 1;
+ return m_zoom;
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSToLengthConversionData.h b/chromium/third_party/WebKit/Source/core/css/CSSToLengthConversionData.h
new file mode 100644
index 00000000000..975be5f2122
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/css/CSSToLengthConversionData.h
@@ -0,0 +1,82 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef CSSToLengthConversionData_h
+#define CSSToLengthConversionData_h
+
+#include "wtf/Assertions.h"
+#include "wtf/Noncopyable.h"
+
+namespace WebCore {
+
+class RenderStyle;
+
+class CSSToLengthConversionData {
+public:
+ CSSToLengthConversionData(const RenderStyle* style, const RenderStyle* rootStyle, float zoom, bool computingFontSize = false)
+ : m_style(style)
+ , m_rootStyle(rootStyle)
+ , m_zoom(zoom)
+ , m_useEffectiveZoom(false)
+ , m_computingFontSize(computingFontSize)
+ {
+ ASSERT(zoom > 0);
+ }
+ CSSToLengthConversionData(const RenderStyle* style, const RenderStyle* rootStyle, bool computingFontSize = false)
+ : m_style(style)
+ , m_rootStyle(rootStyle)
+ , m_useEffectiveZoom(true)
+ , m_computingFontSize(computingFontSize)
+ {
+ }
+ const RenderStyle& style() const { return *m_style; }
+ const RenderStyle& rootStyle() const { return *m_rootStyle; }
+ float zoom() const;
+ bool computingFontSize() const { return m_computingFontSize; }
+
+ void setStyle(const RenderStyle* style) { m_style = style; }
+ void setRootStyle(const RenderStyle* rootStyle) { m_rootStyle = rootStyle; }
+
+ CSSToLengthConversionData copyWithAdjustedZoom(float newZoom) const
+ {
+ return CSSToLengthConversionData(m_style, m_rootStyle, newZoom, m_computingFontSize);
+ }
+
+private:
+ const RenderStyle* m_style;
+ const RenderStyle* m_rootStyle;
+ float m_zoom;
+ bool m_useEffectiveZoom;
+ bool m_computingFontSize;
+};
+
+} // namespace WebCore
+
+#endif
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSToStyleMap.cpp b/chromium/third_party/WebKit/Source/core/css/CSSToStyleMap.cpp
deleted file mode 100644
index 8a96e56372b..00000000000
--- a/chromium/third_party/WebKit/Source/core/css/CSSToStyleMap.cpp
+++ /dev/null
@@ -1,718 +0,0 @@
-/*
- * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
- * (C) 2004-2005 Allan Sandfeld Jensen (kde@carewolf.com)
- * Copyright (C) 2006, 2007 Nicholas Shanks (webkit@nickshanks.com)
- * Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 Apple Inc. All rights reserved.
- * Copyright (C) 2007 Alexey Proskuryakov <ap@webkit.org>
- * Copyright (C) 2007, 2008 Eric Seidel <eric@webkit.org>
- * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
- * Copyright (c) 2011, Code Aurora Forum. All rights reserved.
- * Copyright (C) Research In Motion Limited 2011. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-#include "core/css/CSSToStyleMap.h"
-
-#include "CSSValueKeywords.h"
-#include "core/css/CSSBorderImageSliceValue.h"
-#include "core/css/CSSPrimitiveValue.h"
-#include "core/css/CSSPrimitiveValueMappings.h"
-#include "core/css/CSSTimingFunctionValue.h"
-#include "core/css/Pair.h"
-#include "core/css/Rect.h"
-#include "core/css/resolver/StyleResolverState.h"
-#include "core/platform/animation/CSSAnimationData.h"
-#include "core/rendering/style/FillLayer.h"
-
-namespace WebCore {
-
-const RenderStyle* CSSToStyleMap::style() const
-{
- return m_state.style();
-}
-
-const RenderStyle* CSSToStyleMap::rootElementStyle() const
-{
- return m_state.rootElementStyle();
-}
-
-bool CSSToStyleMap::useSVGZoomRules() const
-{
- return m_state.useSVGZoomRules();
-}
-
-PassRefPtr<StyleImage> CSSToStyleMap::styleImage(CSSPropertyID propertyId, CSSValue* value)
-{
- return m_elementStyleResources.styleImage(m_state.document().textLinkColors(), m_state.style()->visitedDependentColor(CSSPropertyColor), propertyId, value);
-}
-
-void CSSToStyleMap::mapFillAttachment(CSSPropertyID, FillLayer* layer, CSSValue* value) const
-{
- if (value->isInitialValue()) {
- layer->setAttachment(FillLayer::initialFillAttachment(layer->type()));
- return;
- }
-
- if (!value->isPrimitiveValue())
- return;
-
- CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
- switch (primitiveValue->getValueID()) {
- case CSSValueFixed:
- layer->setAttachment(FixedBackgroundAttachment);
- break;
- case CSSValueScroll:
- layer->setAttachment(ScrollBackgroundAttachment);
- break;
- case CSSValueLocal:
- layer->setAttachment(LocalBackgroundAttachment);
- break;
- default:
- return;
- }
-}
-
-void CSSToStyleMap::mapFillClip(CSSPropertyID, FillLayer* layer, CSSValue* value) const
-{
- if (value->isInitialValue()) {
- layer->setClip(FillLayer::initialFillClip(layer->type()));
- return;
- }
-
- if (!value->isPrimitiveValue())
- return;
-
- CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
- layer->setClip(*primitiveValue);
-}
-
-void CSSToStyleMap::mapFillComposite(CSSPropertyID, FillLayer* layer, CSSValue* value) const
-{
- if (value->isInitialValue()) {
- layer->setComposite(FillLayer::initialFillComposite(layer->type()));
- return;
- }
-
- if (!value->isPrimitiveValue())
- return;
-
- CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
- layer->setComposite(*primitiveValue);
-}
-
-void CSSToStyleMap::mapFillBlendMode(CSSPropertyID, FillLayer* layer, CSSValue* value) const
-{
- if (value->isInitialValue()) {
- layer->setBlendMode(FillLayer::initialFillBlendMode(layer->type()));
- return;
- }
-
- if (!value->isPrimitiveValue())
- return;
-
- CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
- layer->setBlendMode(*primitiveValue);
-}
-
-void CSSToStyleMap::mapFillOrigin(CSSPropertyID, FillLayer* layer, CSSValue* value) const
-{
- if (value->isInitialValue()) {
- layer->setOrigin(FillLayer::initialFillOrigin(layer->type()));
- return;
- }
-
- if (!value->isPrimitiveValue())
- return;
-
- CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
- layer->setOrigin(*primitiveValue);
-}
-
-
-void CSSToStyleMap::mapFillImage(CSSPropertyID property, FillLayer* layer, CSSValue* value)
-{
- if (value->isInitialValue()) {
- layer->setImage(FillLayer::initialFillImage(layer->type()));
- return;
- }
-
- layer->setImage(styleImage(property, value));
-}
-
-void CSSToStyleMap::mapFillRepeatX(CSSPropertyID, FillLayer* layer, CSSValue* value) const
-{
- if (value->isInitialValue()) {
- layer->setRepeatX(FillLayer::initialFillRepeatX(layer->type()));
- return;
- }
-
- if (!value->isPrimitiveValue())
- return;
-
- CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
- layer->setRepeatX(*primitiveValue);
-}
-
-void CSSToStyleMap::mapFillRepeatY(CSSPropertyID, FillLayer* layer, CSSValue* value) const
-{
- if (value->isInitialValue()) {
- layer->setRepeatY(FillLayer::initialFillRepeatY(layer->type()));
- return;
- }
-
- if (!value->isPrimitiveValue())
- return;
-
- CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
- layer->setRepeatY(*primitiveValue);
-}
-
-void CSSToStyleMap::mapFillSize(CSSPropertyID, FillLayer* layer, CSSValue* value) const
-{
- if (!value->isPrimitiveValue()) {
- layer->setSizeType(SizeNone);
- return;
- }
-
- CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
- if (primitiveValue->getValueID() == CSSValueContain)
- layer->setSizeType(Contain);
- else if (primitiveValue->getValueID() == CSSValueCover)
- layer->setSizeType(Cover);
- else
- layer->setSizeType(SizeLength);
-
- LengthSize b = FillLayer::initialFillSizeLength(layer->type());
-
- if (value->isInitialValue() || primitiveValue->getValueID() == CSSValueContain || primitiveValue->getValueID() == CSSValueCover) {
- layer->setSizeLength(b);
- return;
- }
-
- float zoomFactor = style()->effectiveZoom();
-
- Length firstLength;
- Length secondLength;
-
- if (Pair* pair = primitiveValue->getPairValue()) {
- firstLength = pair->first()->convertToLength<AnyConversion>(style(), rootElementStyle(), zoomFactor);
- secondLength = pair->second()->convertToLength<AnyConversion>(style(), rootElementStyle(), zoomFactor);
- } else {
- firstLength = primitiveValue->convertToLength<AnyConversion>(style(), rootElementStyle(), zoomFactor);
- secondLength = Length();
- }
-
- if (firstLength.isUndefined() || secondLength.isUndefined())
- return;
-
- b.setWidth(firstLength);
- b.setHeight(secondLength);
- layer->setSizeLength(b);
-}
-
-void CSSToStyleMap::mapFillXPosition(CSSPropertyID propertyID, FillLayer* layer, CSSValue* value) const
-{
- if (value->isInitialValue()) {
- layer->setXPosition(FillLayer::initialFillXPosition(layer->type()));
- return;
- }
-
- if (!value->isPrimitiveValue())
- return;
-
- float zoomFactor = style()->effectiveZoom();
-
- CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
- Pair* pair = primitiveValue->getPairValue();
- if (pair) {
- ASSERT_UNUSED(propertyID, propertyID == CSSPropertyBackgroundPositionX || propertyID == CSSPropertyWebkitMaskPositionX);
- primitiveValue = pair->second();
- }
-
- Length length;
- if (primitiveValue->isLength())
- length = primitiveValue->computeLength<Length>(style(), rootElementStyle(), zoomFactor);
- else if (primitiveValue->isPercentage())
- length = Length(primitiveValue->getDoubleValue(), Percent);
- else if (primitiveValue->isCalculatedPercentageWithLength())
- length = Length(primitiveValue->cssCalcValue()->toCalcValue(style(), rootElementStyle(), zoomFactor));
- else if (primitiveValue->isViewportPercentageLength())
- length = primitiveValue->viewportPercentageLength();
- else
- return;
-
- layer->setXPosition(length);
- if (pair)
- layer->setBackgroundXOrigin(*(pair->first()));
-}
-
-void CSSToStyleMap::mapFillYPosition(CSSPropertyID propertyID, FillLayer* layer, CSSValue* value) const
-{
- if (value->isInitialValue()) {
- layer->setYPosition(FillLayer::initialFillYPosition(layer->type()));
- return;
- }
-
- if (!value->isPrimitiveValue())
- return;
-
- float zoomFactor = style()->effectiveZoom();
-
- CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
- Pair* pair = primitiveValue->getPairValue();
- if (pair) {
- ASSERT_UNUSED(propertyID, propertyID == CSSPropertyBackgroundPositionY || propertyID == CSSPropertyWebkitMaskPositionY);
- primitiveValue = pair->second();
- }
-
- Length length;
- if (primitiveValue->isLength())
- length = primitiveValue->computeLength<Length>(style(), rootElementStyle(), zoomFactor);
- else if (primitiveValue->isPercentage())
- length = Length(primitiveValue->getDoubleValue(), Percent);
- else if (primitiveValue->isCalculatedPercentageWithLength())
- length = Length(primitiveValue->cssCalcValue()->toCalcValue(style(), rootElementStyle(), zoomFactor));
- else if (primitiveValue->isViewportPercentageLength())
- length = primitiveValue->viewportPercentageLength();
- else
- return;
-
- layer->setYPosition(length);
- if (pair)
- layer->setBackgroundYOrigin(*(pair->first()));
-}
-
-void CSSToStyleMap::mapFillMaskSourceType(CSSPropertyID, FillLayer* layer, CSSValue* value)
-{
- EMaskSourceType type = FillLayer::initialFillMaskSourceType(layer->type());
- if (value->isInitialValue()) {
- layer->setMaskSourceType(type);
- return;
- }
-
- if (!value->isPrimitiveValue())
- return;
-
- CSSPrimitiveValue* primitiveValue = static_cast<CSSPrimitiveValue*>(value);
- switch (primitiveValue->getValueID()) {
- case CSSValueAlpha:
- type = MaskAlpha;
- break;
- case CSSValueLuminance:
- type = MaskLuminance;
- break;
- case CSSValueAuto:
- break;
- default:
- ASSERT_NOT_REACHED();
- }
-
- layer->setMaskSourceType(type);
-}
-
-void CSSToStyleMap::mapAnimationDelay(CSSAnimationData* animation, CSSValue* value) const
-{
- if (value->isInitialValue()) {
- animation->setDelay(CSSAnimationData::initialAnimationDelay());
- return;
- }
-
- if (!value->isPrimitiveValue())
- return;
-
- CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
- animation->setDelay(primitiveValue->computeTime<double, CSSPrimitiveValue::Seconds>());
-}
-
-void CSSToStyleMap::mapAnimationDirection(CSSAnimationData* layer, CSSValue* value) const
-{
- if (value->isInitialValue()) {
- layer->setDirection(CSSAnimationData::initialAnimationDirection());
- return;
- }
-
- if (!value->isPrimitiveValue())
- return;
-
- CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
- switch (primitiveValue->getValueID()) {
- case CSSValueNormal:
- layer->setDirection(CSSAnimationData::AnimationDirectionNormal);
- break;
- case CSSValueAlternate:
- layer->setDirection(CSSAnimationData::AnimationDirectionAlternate);
- break;
- case CSSValueReverse:
- layer->setDirection(CSSAnimationData::AnimationDirectionReverse);
- break;
- case CSSValueAlternateReverse:
- layer->setDirection(CSSAnimationData::AnimationDirectionAlternateReverse);
- break;
- default:
- break;
- }
-}
-
-void CSSToStyleMap::mapAnimationDuration(CSSAnimationData* animation, CSSValue* value) const
-{
- if (value->isInitialValue()) {
- animation->setDuration(CSSAnimationData::initialAnimationDuration());
- return;
- }
-
- if (!value->isPrimitiveValue())
- return;
-
- CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
- animation->setDuration(primitiveValue->computeTime<double, CSSPrimitiveValue::Seconds>());
-}
-
-void CSSToStyleMap::mapAnimationFillMode(CSSAnimationData* layer, CSSValue* value) const
-{
- if (value->isInitialValue()) {
- layer->setFillMode(CSSAnimationData::initialAnimationFillMode());
- return;
- }
-
- if (!value->isPrimitiveValue())
- return;
-
- CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
- switch (primitiveValue->getValueID()) {
- case CSSValueNone:
- layer->setFillMode(AnimationFillModeNone);
- break;
- case CSSValueForwards:
- layer->setFillMode(AnimationFillModeForwards);
- break;
- case CSSValueBackwards:
- layer->setFillMode(AnimationFillModeBackwards);
- break;
- case CSSValueBoth:
- layer->setFillMode(AnimationFillModeBoth);
- break;
- default:
- break;
- }
-}
-
-void CSSToStyleMap::mapAnimationIterationCount(CSSAnimationData* animation, CSSValue* value) const
-{
- if (value->isInitialValue()) {
- animation->setIterationCount(CSSAnimationData::initialAnimationIterationCount());
- return;
- }
-
- if (!value->isPrimitiveValue())
- return;
-
- CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
- if (primitiveValue->getValueID() == CSSValueInfinite)
- animation->setIterationCount(CSSAnimationData::IterationCountInfinite);
- else
- animation->setIterationCount(primitiveValue->getFloatValue());
-}
-
-void CSSToStyleMap::mapAnimationName(CSSAnimationData* layer, CSSValue* value) const
-{
- if (value->isInitialValue()) {
- layer->setName(CSSAnimationData::initialAnimationName());
- return;
- }
-
- if (!value->isPrimitiveValue())
- return;
-
- CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
- if (primitiveValue->getValueID() == CSSValueNone)
- layer->setIsNoneAnimation(true);
- else
- layer->setName(primitiveValue->getStringValue());
-}
-
-void CSSToStyleMap::mapAnimationPlayState(CSSAnimationData* layer, CSSValue* value) const
-{
- if (value->isInitialValue()) {
- layer->setPlayState(CSSAnimationData::initialAnimationPlayState());
- return;
- }
-
- if (!value->isPrimitiveValue())
- return;
-
- CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
- EAnimPlayState playState = (primitiveValue->getValueID() == CSSValuePaused) ? AnimPlayStatePaused : AnimPlayStatePlaying;
- layer->setPlayState(playState);
-}
-
-void CSSToStyleMap::mapAnimationProperty(CSSAnimationData* animation, CSSValue* value) const
-{
- if (value->isInitialValue()) {
- animation->setAnimationMode(CSSAnimationData::AnimateAll);
- animation->setProperty(CSSPropertyInvalid);
- return;
- }
-
- if (!value->isPrimitiveValue())
- return;
-
- CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
- if (primitiveValue->getValueID() == CSSValueAll) {
- animation->setAnimationMode(CSSAnimationData::AnimateAll);
- animation->setProperty(CSSPropertyInvalid);
- } else if (primitiveValue->getValueID() == CSSValueNone) {
- animation->setAnimationMode(CSSAnimationData::AnimateNone);
- animation->setProperty(CSSPropertyInvalid);
- } else {
- animation->setAnimationMode(CSSAnimationData::AnimateSingleProperty);
- animation->setProperty(primitiveValue->getPropertyID());
- }
-}
-
-void CSSToStyleMap::mapAnimationTimingFunction(CSSAnimationData* animation, CSSValue* value) const
-{
- if (value->isInitialValue()) {
- animation->setTimingFunction(CSSAnimationData::initialAnimationTimingFunction());
- return;
- }
-
- if (value->isPrimitiveValue()) {
- CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
- switch (primitiveValue->getValueID()) {
- case CSSValueLinear:
- animation->setTimingFunction(LinearTimingFunction::create());
- break;
- case CSSValueEase:
- animation->setTimingFunction(CubicBezierTimingFunction::preset(CubicBezierTimingFunction::Ease));
- break;
- case CSSValueEaseIn:
- animation->setTimingFunction(CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseIn));
- break;
- case CSSValueEaseOut:
- animation->setTimingFunction(CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseOut));
- break;
- case CSSValueEaseInOut:
- animation->setTimingFunction(CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseInOut));
- break;
- case CSSValueStepStart:
- animation->setTimingFunction(StepsTimingFunction::preset(StepsTimingFunction::Start));
- break;
- case CSSValueStepEnd:
- animation->setTimingFunction(StepsTimingFunction::preset(StepsTimingFunction::End));
- break;
- default:
- break;
- }
- return;
- }
-
- if (value->isCubicBezierTimingFunctionValue()) {
- CSSCubicBezierTimingFunctionValue* cubicTimingFunction = static_cast<CSSCubicBezierTimingFunctionValue*>(value);
- animation->setTimingFunction(CubicBezierTimingFunction::create(cubicTimingFunction->x1(), cubicTimingFunction->y1(), cubicTimingFunction->x2(), cubicTimingFunction->y2()));
- } else if (value->isStepsTimingFunctionValue()) {
- CSSStepsTimingFunctionValue* stepsTimingFunction = static_cast<CSSStepsTimingFunctionValue*>(value);
- animation->setTimingFunction(StepsTimingFunction::create(stepsTimingFunction->numberOfSteps(), stepsTimingFunction->stepAtStart()));
- }
-}
-
-void CSSToStyleMap::mapNinePieceImage(RenderStyle* mutableStyle, CSSPropertyID property, CSSValue* value, NinePieceImage& image)
-{
- // If we're not a value list, then we are "none" and don't need to alter the empty image at all.
- if (!value || !value->isValueList())
- return;
-
- // Retrieve the border image value.
- CSSValueList* borderImage = toCSSValueList(value);
-
- // Set the image (this kicks off the load).
- CSSPropertyID imageProperty;
- if (property == CSSPropertyWebkitBorderImage)
- imageProperty = CSSPropertyBorderImageSource;
- else if (property == CSSPropertyWebkitMaskBoxImage)
- imageProperty = CSSPropertyWebkitMaskBoxImageSource;
- else
- imageProperty = property;
-
- for (unsigned i = 0 ; i < borderImage->length() ; ++i) {
- CSSValue* current = borderImage->item(i);
-
- if (current->isImageValue() || current->isImageGeneratorValue() || current->isImageSetValue())
- image.setImage(styleImage(imageProperty, current));
- else if (current->isBorderImageSliceValue())
- mapNinePieceImageSlice(current, image);
- else if (current->isValueList()) {
- CSSValueList* slashList = toCSSValueList(current);
- // Map in the image slices.
- if (slashList->item(0) && slashList->item(0)->isBorderImageSliceValue())
- mapNinePieceImageSlice(slashList->item(0), image);
-
- // Map in the border slices.
- if (slashList->item(1))
- image.setBorderSlices(mapNinePieceImageQuad(slashList->item(1)));
-
- // Map in the outset.
- if (slashList->item(2))
- image.setOutset(mapNinePieceImageQuad(slashList->item(2)));
- } else if (current->isPrimitiveValue()) {
- // Set the appropriate rules for stretch/round/repeat of the slices.
- mapNinePieceImageRepeat(current, image);
- }
- }
-
- if (property == CSSPropertyWebkitBorderImage) {
- // We have to preserve the legacy behavior of -webkit-border-image and make the border slices
- // also set the border widths. We don't need to worry about percentages, since we don't even support
- // those on real borders yet.
- if (image.borderSlices().top().isFixed())
- mutableStyle->setBorderTopWidth(image.borderSlices().top().value());
- if (image.borderSlices().right().isFixed())
- mutableStyle->setBorderRightWidth(image.borderSlices().right().value());
- if (image.borderSlices().bottom().isFixed())
- mutableStyle->setBorderBottomWidth(image.borderSlices().bottom().value());
- if (image.borderSlices().left().isFixed())
- mutableStyle->setBorderLeftWidth(image.borderSlices().left().value());
- }
-}
-
-void CSSToStyleMap::mapNinePieceImageSlice(CSSValue* value, NinePieceImage& image) const
-{
- if (!value || !value->isBorderImageSliceValue())
- return;
-
- // Retrieve the border image value.
- CSSBorderImageSliceValue* borderImageSlice = static_cast<CSSBorderImageSliceValue*>(value);
-
- // Set up a length box to represent our image slices.
- LengthBox box;
- Quad* slices = borderImageSlice->slices();
- if (slices->top()->isPercentage())
- box.m_top = Length(slices->top()->getDoubleValue(), Percent);
- else
- box.m_top = Length(slices->top()->getIntValue(CSSPrimitiveValue::CSS_NUMBER), Fixed);
- if (slices->bottom()->isPercentage())
- box.m_bottom = Length(slices->bottom()->getDoubleValue(), Percent);
- else
- box.m_bottom = Length((int)slices->bottom()->getFloatValue(CSSPrimitiveValue::CSS_NUMBER), Fixed);
- if (slices->left()->isPercentage())
- box.m_left = Length(slices->left()->getDoubleValue(), Percent);
- else
- box.m_left = Length(slices->left()->getIntValue(CSSPrimitiveValue::CSS_NUMBER), Fixed);
- if (slices->right()->isPercentage())
- box.m_right = Length(slices->right()->getDoubleValue(), Percent);
- else
- box.m_right = Length(slices->right()->getIntValue(CSSPrimitiveValue::CSS_NUMBER), Fixed);
- image.setImageSlices(box);
-
- // Set our fill mode.
- image.setFill(borderImageSlice->m_fill);
-}
-
-LengthBox CSSToStyleMap::mapNinePieceImageQuad(CSSValue* value) const
-{
- if (!value || !value->isPrimitiveValue())
- return LengthBox();
-
- // Get our zoom value.
- float zoom = useSVGZoomRules() ? 1.0f : style()->effectiveZoom();
-
- // Retrieve the primitive value.
- CSSPrimitiveValue* borderWidths = toCSSPrimitiveValue(value);
-
- // Set up a length box to represent our image slices.
- LengthBox box; // Defaults to 'auto' so we don't have to handle that explicitly below.
- Quad* slices = borderWidths->getQuadValue();
- if (slices->top()->isNumber())
- box.m_top = Length(slices->top()->getIntValue(), Relative);
- else if (slices->top()->isPercentage())
- box.m_top = Length(slices->top()->getDoubleValue(CSSPrimitiveValue::CSS_PERCENTAGE), Percent);
- else if (slices->top()->getValueID() != CSSValueAuto)
- box.m_top = slices->top()->computeLength<Length>(style(), rootElementStyle(), zoom);
-
- if (slices->right()->isNumber())
- box.m_right = Length(slices->right()->getIntValue(), Relative);
- else if (slices->right()->isPercentage())
- box.m_right = Length(slices->right()->getDoubleValue(CSSPrimitiveValue::CSS_PERCENTAGE), Percent);
- else if (slices->right()->getValueID() != CSSValueAuto)
- box.m_right = slices->right()->computeLength<Length>(style(), rootElementStyle(), zoom);
-
- if (slices->bottom()->isNumber())
- box.m_bottom = Length(slices->bottom()->getIntValue(), Relative);
- else if (slices->bottom()->isPercentage())
- box.m_bottom = Length(slices->bottom()->getDoubleValue(CSSPrimitiveValue::CSS_PERCENTAGE), Percent);
- else if (slices->bottom()->getValueID() != CSSValueAuto)
- box.m_bottom = slices->bottom()->computeLength<Length>(style(), rootElementStyle(), zoom);
-
- if (slices->left()->isNumber())
- box.m_left = Length(slices->left()->getIntValue(), Relative);
- else if (slices->left()->isPercentage())
- box.m_left = Length(slices->left()->getDoubleValue(CSSPrimitiveValue::CSS_PERCENTAGE), Percent);
- else if (slices->left()->getValueID() != CSSValueAuto)
- box.m_left = slices->left()->computeLength<Length>(style(), rootElementStyle(), zoom);
-
- return box;
-}
-
-void CSSToStyleMap::mapNinePieceImageRepeat(CSSValue* value, NinePieceImage& image) const
-{
- if (!value || !value->isPrimitiveValue())
- return;
-
- CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
- Pair* pair = primitiveValue->getPairValue();
- if (!pair || !pair->first() || !pair->second())
- return;
-
- CSSValueID firstIdentifier = pair->first()->getValueID();
- CSSValueID secondIdentifier = pair->second()->getValueID();
-
- ENinePieceImageRule horizontalRule;
- switch (firstIdentifier) {
- case CSSValueStretch:
- horizontalRule = StretchImageRule;
- break;
- case CSSValueRound:
- horizontalRule = RoundImageRule;
- break;
- case CSSValueSpace:
- horizontalRule = SpaceImageRule;
- break;
- default: // CSSValueRepeat
- horizontalRule = RepeatImageRule;
- break;
- }
- image.setHorizontalRule(horizontalRule);
-
- ENinePieceImageRule verticalRule;
- switch (secondIdentifier) {
- case CSSValueStretch:
- verticalRule = StretchImageRule;
- break;
- case CSSValueRound:
- verticalRule = RoundImageRule;
- break;
- case CSSValueSpace:
- verticalRule = SpaceImageRule;
- break;
- default: // CSSValueRepeat
- verticalRule = RepeatImageRule;
- break;
- }
- image.setVerticalRule(verticalRule);
-}
-
-};
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSToStyleMap.h b/chromium/third_party/WebKit/Source/core/css/CSSToStyleMap.h
deleted file mode 100644
index 7ea347e32ec..00000000000
--- a/chromium/third_party/WebKit/Source/core/css/CSSToStyleMap.h
+++ /dev/null
@@ -1,92 +0,0 @@
-/*
- * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
- * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#ifndef CSSToStyleMap_h
-#define CSSToStyleMap_h
-
-#include "CSSPropertyNames.h"
-#include "core/css/resolver/ElementStyleResources.h"
-#include "core/platform/LengthBox.h"
-#include "wtf/Noncopyable.h"
-
-namespace WebCore {
-
-class FillLayer;
-class CSSValue;
-class CSSAnimationData;
-class RenderStyle;
-class StyleImage;
-class StyleResolverState;
-class NinePieceImage;
-
-// CSSToStyleMap is a short-lived helper object which
-// given the current StyleResolverState can map
-// CSSValue objects into their RenderStyle equivalents.
-
-class CSSToStyleMap {
- WTF_MAKE_NONCOPYABLE(CSSToStyleMap);
-public:
- CSSToStyleMap(const StyleResolverState& state, ElementStyleResources& elementStyleResources) : m_state(state), m_elementStyleResources(elementStyleResources) { }
-
- void mapFillAttachment(CSSPropertyID, FillLayer*, CSSValue*) const;
- void mapFillClip(CSSPropertyID, FillLayer*, CSSValue*) const;
- void mapFillComposite(CSSPropertyID, FillLayer*, CSSValue*) const;
- void mapFillBlendMode(CSSPropertyID, FillLayer*, CSSValue*) const;
- void mapFillOrigin(CSSPropertyID, FillLayer*, CSSValue*) const;
- void mapFillImage(CSSPropertyID, FillLayer*, CSSValue*);
- void mapFillRepeatX(CSSPropertyID, FillLayer*, CSSValue*) const;
- void mapFillRepeatY(CSSPropertyID, FillLayer*, CSSValue*) const;
- void mapFillSize(CSSPropertyID, FillLayer*, CSSValue*) const;
- void mapFillXPosition(CSSPropertyID, FillLayer*, CSSValue*) const;
- void mapFillYPosition(CSSPropertyID, FillLayer*, CSSValue*) const;
- void mapFillMaskSourceType(CSSPropertyID, FillLayer*, CSSValue*);
-
- void mapAnimationDelay(CSSAnimationData*, CSSValue*) const;
- void mapAnimationDirection(CSSAnimationData*, CSSValue*) const;
- void mapAnimationDuration(CSSAnimationData*, CSSValue*) const;
- void mapAnimationFillMode(CSSAnimationData*, CSSValue*) const;
- void mapAnimationIterationCount(CSSAnimationData*, CSSValue*) const;
- void mapAnimationName(CSSAnimationData*, CSSValue*) const;
- void mapAnimationPlayState(CSSAnimationData*, CSSValue*) const;
- void mapAnimationProperty(CSSAnimationData*, CSSValue*) const;
- void mapAnimationTimingFunction(CSSAnimationData*, CSSValue*) const;
-
- void mapNinePieceImage(RenderStyle* mutableStyle, CSSPropertyID, CSSValue*, NinePieceImage&);
- void mapNinePieceImageSlice(CSSValue*, NinePieceImage&) const;
- LengthBox mapNinePieceImageQuad(CSSValue*) const;
- void mapNinePieceImageRepeat(CSSValue*, NinePieceImage&) const;
-
-private:
- const RenderStyle* style() const;
- const RenderStyle* rootElementStyle() const;
- bool useSVGZoomRules() const;
-
- PassRefPtr<StyleImage> styleImage(CSSPropertyID, CSSValue*);
-
- // FIXME: Consider passing a StyleResolverState (or ElementResolveState)
- // as an argument instead of caching it on this object.
- const StyleResolverState& m_state;
- ElementStyleResources& m_elementStyleResources;
-};
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSTokenizer-in.cpp b/chromium/third_party/WebKit/Source/core/css/CSSTokenizer-in.cpp
new file mode 100644
index 00000000000..5ee194a188c
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/css/CSSTokenizer-in.cpp
@@ -0,0 +1,1559 @@
+/*
+ * Copyright (C) 2003 Lars Knoll (knoll@kde.org)
+ * Copyright (C) 2005 Allan Sandfeld Jensen (kde@carewolf.com)
+ * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 Apple Inc. All rights reserved.
+ * Copyright (C) 2007 Nicholas Shanks <webkit@nickshanks.com>
+ * Copyright (C) 2008 Eric Seidel <eric@webkit.org>
+ * Copyright (C) 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
+ * Copyright (C) 2012 Adobe Systems Incorporated. All rights reserved.
+ * Copyright (C) 2012 Intel Corporation. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#include "config.h"
+#include "core/css/CSSTokenizer.h"
+
+#include "core/css/CSSKeyframeRule.h"
+#include "core/css/CSSParser.h"
+#include "core/css/CSSParserValues.h"
+#include "core/css/MediaQuery.h"
+#include "core/css/StyleRule.h"
+#include "core/html/parser/HTMLParserIdioms.h"
+#include "core/svg/SVGParserUtilities.h"
+
+namespace WebCore {
+
+#include "CSSGrammar.h"
+
+enum CharacterType {
+ // Types for the main switch.
+
+ // The first 4 types must be grouped together, as they
+ // represent the allowed chars in an identifier.
+ CharacterCaselessU,
+ CharacterIdentifierStart,
+ CharacterNumber,
+ CharacterDash,
+
+ CharacterOther,
+ CharacterNull,
+ CharacterWhiteSpace,
+ CharacterEndMediaQueryOrSupports,
+ CharacterEndNthChild,
+ CharacterQuote,
+ CharacterExclamationMark,
+ CharacterHashmark,
+ CharacterDollar,
+ CharacterAsterisk,
+ CharacterPlus,
+ CharacterDot,
+ CharacterSlash,
+ CharacterLess,
+ CharacterAt,
+ CharacterBackSlash,
+ CharacterXor,
+ CharacterVerticalBar,
+ CharacterTilde,
+};
+
+// 128 ASCII codes
+static const CharacterType typesOfASCIICharacters[128] = {
+/* 0 - Null */ CharacterNull,
+/* 1 - Start of Heading */ CharacterOther,
+/* 2 - Start of Text */ CharacterOther,
+/* 3 - End of Text */ CharacterOther,
+/* 4 - End of Transm. */ CharacterOther,
+/* 5 - Enquiry */ CharacterOther,
+/* 6 - Acknowledgment */ CharacterOther,
+/* 7 - Bell */ CharacterOther,
+/* 8 - Back Space */ CharacterOther,
+/* 9 - Horizontal Tab */ CharacterWhiteSpace,
+/* 10 - Line Feed */ CharacterWhiteSpace,
+/* 11 - Vertical Tab */ CharacterOther,
+/* 12 - Form Feed */ CharacterWhiteSpace,
+/* 13 - Carriage Return */ CharacterWhiteSpace,
+/* 14 - Shift Out */ CharacterOther,
+/* 15 - Shift In */ CharacterOther,
+/* 16 - Data Line Escape */ CharacterOther,
+/* 17 - Device Control 1 */ CharacterOther,
+/* 18 - Device Control 2 */ CharacterOther,
+/* 19 - Device Control 3 */ CharacterOther,
+/* 20 - Device Control 4 */ CharacterOther,
+/* 21 - Negative Ack. */ CharacterOther,
+/* 22 - Synchronous Idle */ CharacterOther,
+/* 23 - End of Transmit */ CharacterOther,
+/* 24 - Cancel */ CharacterOther,
+/* 25 - End of Medium */ CharacterOther,
+/* 26 - Substitute */ CharacterOther,
+/* 27 - Escape */ CharacterOther,
+/* 28 - File Separator */ CharacterOther,
+/* 29 - Group Separator */ CharacterOther,
+/* 30 - Record Separator */ CharacterOther,
+/* 31 - Unit Separator */ CharacterOther,
+/* 32 - Space */ CharacterWhiteSpace,
+/* 33 - ! */ CharacterExclamationMark,
+/* 34 - " */ CharacterQuote,
+/* 35 - # */ CharacterHashmark,
+/* 36 - $ */ CharacterDollar,
+/* 37 - % */ CharacterOther,
+/* 38 - & */ CharacterOther,
+/* 39 - ' */ CharacterQuote,
+/* 40 - ( */ CharacterOther,
+/* 41 - ) */ CharacterEndNthChild,
+/* 42 - * */ CharacterAsterisk,
+/* 43 - + */ CharacterPlus,
+/* 44 - , */ CharacterOther,
+/* 45 - - */ CharacterDash,
+/* 46 - . */ CharacterDot,
+/* 47 - / */ CharacterSlash,
+/* 48 - 0 */ CharacterNumber,
+/* 49 - 1 */ CharacterNumber,
+/* 50 - 2 */ CharacterNumber,
+/* 51 - 3 */ CharacterNumber,
+/* 52 - 4 */ CharacterNumber,
+/* 53 - 5 */ CharacterNumber,
+/* 54 - 6 */ CharacterNumber,
+/* 55 - 7 */ CharacterNumber,
+/* 56 - 8 */ CharacterNumber,
+/* 57 - 9 */ CharacterNumber,
+/* 58 - : */ CharacterOther,
+/* 59 - ; */ CharacterEndMediaQueryOrSupports,
+/* 60 - < */ CharacterLess,
+/* 61 - = */ CharacterOther,
+/* 62 - > */ CharacterOther,
+/* 63 - ? */ CharacterOther,
+/* 64 - @ */ CharacterAt,
+/* 65 - A */ CharacterIdentifierStart,
+/* 66 - B */ CharacterIdentifierStart,
+/* 67 - C */ CharacterIdentifierStart,
+/* 68 - D */ CharacterIdentifierStart,
+/* 69 - E */ CharacterIdentifierStart,
+/* 70 - F */ CharacterIdentifierStart,
+/* 71 - G */ CharacterIdentifierStart,
+/* 72 - H */ CharacterIdentifierStart,
+/* 73 - I */ CharacterIdentifierStart,
+/* 74 - J */ CharacterIdentifierStart,
+/* 75 - K */ CharacterIdentifierStart,
+/* 76 - L */ CharacterIdentifierStart,
+/* 77 - M */ CharacterIdentifierStart,
+/* 78 - N */ CharacterIdentifierStart,
+/* 79 - O */ CharacterIdentifierStart,
+/* 80 - P */ CharacterIdentifierStart,
+/* 81 - Q */ CharacterIdentifierStart,
+/* 82 - R */ CharacterIdentifierStart,
+/* 83 - S */ CharacterIdentifierStart,
+/* 84 - T */ CharacterIdentifierStart,
+/* 85 - U */ CharacterCaselessU,
+/* 86 - V */ CharacterIdentifierStart,
+/* 87 - W */ CharacterIdentifierStart,
+/* 88 - X */ CharacterIdentifierStart,
+/* 89 - Y */ CharacterIdentifierStart,
+/* 90 - Z */ CharacterIdentifierStart,
+/* 91 - [ */ CharacterOther,
+/* 92 - \ */ CharacterBackSlash,
+/* 93 - ] */ CharacterOther,
+/* 94 - ^ */ CharacterXor,
+/* 95 - _ */ CharacterIdentifierStart,
+/* 96 - ` */ CharacterOther,
+/* 97 - a */ CharacterIdentifierStart,
+/* 98 - b */ CharacterIdentifierStart,
+/* 99 - c */ CharacterIdentifierStart,
+/* 100 - d */ CharacterIdentifierStart,
+/* 101 - e */ CharacterIdentifierStart,
+/* 102 - f */ CharacterIdentifierStart,
+/* 103 - g */ CharacterIdentifierStart,
+/* 104 - h */ CharacterIdentifierStart,
+/* 105 - i */ CharacterIdentifierStart,
+/* 106 - j */ CharacterIdentifierStart,
+/* 107 - k */ CharacterIdentifierStart,
+/* 108 - l */ CharacterIdentifierStart,
+/* 109 - m */ CharacterIdentifierStart,
+/* 110 - n */ CharacterIdentifierStart,
+/* 111 - o */ CharacterIdentifierStart,
+/* 112 - p */ CharacterIdentifierStart,
+/* 113 - q */ CharacterIdentifierStart,
+/* 114 - r */ CharacterIdentifierStart,
+/* 115 - s */ CharacterIdentifierStart,
+/* 116 - t */ CharacterIdentifierStart,
+/* 117 - u */ CharacterCaselessU,
+/* 118 - v */ CharacterIdentifierStart,
+/* 119 - w */ CharacterIdentifierStart,
+/* 120 - x */ CharacterIdentifierStart,
+/* 121 - y */ CharacterIdentifierStart,
+/* 122 - z */ CharacterIdentifierStart,
+/* 123 - { */ CharacterEndMediaQueryOrSupports,
+/* 124 - | */ CharacterVerticalBar,
+/* 125 - } */ CharacterOther,
+/* 126 - ~ */ CharacterTilde,
+/* 127 - Delete */ CharacterOther,
+};
+
+// Utility functions for the CSS tokenizer.
+
+template <typename CharacterType>
+static inline bool isCSSLetter(CharacterType character)
+{
+ return character >= 128 || typesOfASCIICharacters[character] <= CharacterDash;
+}
+
+template <typename CharacterType>
+static inline bool isCSSEscape(CharacterType character)
+{
+ return character >= ' ' && character != 127;
+}
+
+template <typename CharacterType>
+static inline bool isURILetter(CharacterType character)
+{
+ return (character >= '*' && character != 127) || (character >= '#' && character <= '&') || character == '!';
+}
+
+template <typename CharacterType>
+static inline bool isIdentifierStartAfterDash(CharacterType* currentCharacter)
+{
+ return isASCIIAlpha(currentCharacter[0]) || currentCharacter[0] == '_' || currentCharacter[0] >= 128
+ || (currentCharacter[0] == '\\' && isCSSEscape(currentCharacter[1]));
+}
+
+template <typename CharacterType>
+static inline bool isEqualToCSSIdentifier(CharacterType* cssString, const char* constantString)
+{
+ // Compare an character memory data with a zero terminated string.
+ do {
+ // The input must be part of an identifier if constantChar or constString
+ // contains '-'. Otherwise toASCIILowerUnchecked('\r') would be equal to '-'.
+ ASSERT((*constantString >= 'a' && *constantString <= 'z') || *constantString == '-');
+ ASSERT(*constantString != '-' || isCSSLetter(*cssString));
+ if (toASCIILowerUnchecked(*cssString++) != (*constantString++))
+ return false;
+ } while (*constantString);
+ return true;
+}
+
+template <typename CharacterType>
+static inline bool isEqualToCSSCaseSensitiveIdentifier(CharacterType* string, const char* constantString)
+{
+ ASSERT(*constantString);
+
+ do {
+ if (*string++ != *constantString++)
+ return false;
+ } while (*constantString);
+ return true;
+}
+
+template <typename CharacterType>
+static CharacterType* checkAndSkipEscape(CharacterType* currentCharacter)
+{
+ // Returns with 0, if escape check is failed. Otherwise
+ // it returns with the following character.
+ ASSERT(*currentCharacter == '\\');
+
+ ++currentCharacter;
+ if (!isCSSEscape(*currentCharacter))
+ return 0;
+
+ if (isASCIIHexDigit(*currentCharacter)) {
+ int length = 6;
+
+ do {
+ ++currentCharacter;
+ } while (isASCIIHexDigit(*currentCharacter) && --length);
+
+ // Optional space after the escape sequence.
+ if (isHTMLSpace<CharacterType>(*currentCharacter))
+ ++currentCharacter;
+ return currentCharacter;
+ }
+ return currentCharacter + 1;
+}
+
+template <typename CharacterType>
+static inline CharacterType* skipWhiteSpace(CharacterType* currentCharacter)
+{
+ while (isHTMLSpace<CharacterType>(*currentCharacter))
+ ++currentCharacter;
+ return currentCharacter;
+}
+
+// Main CSS tokenizer functions.
+
+template <>
+inline LChar*& CSSTokenizer::currentCharacter<LChar>()
+{
+ return m_currentCharacter8;
+}
+
+template <>
+inline UChar*& CSSTokenizer::currentCharacter<UChar>()
+{
+ return m_currentCharacter16;
+}
+
+UChar*& CSSTokenizer::currentCharacter16()
+{
+ if (!m_currentCharacter16) {
+ m_dataStart16 = adoptArrayPtr(new UChar[m_length]);
+ m_currentCharacter16 = m_dataStart16.get();
+ }
+
+ return m_currentCharacter16;
+}
+
+template <>
+inline LChar* CSSTokenizer::dataStart<LChar>()
+{
+ return m_dataStart8.get();
+}
+
+template <>
+inline UChar* CSSTokenizer::dataStart<UChar>()
+{
+ return m_dataStart16.get();
+}
+
+template <typename CharacterType>
+inline CSSParserLocation CSSTokenizer::tokenLocation()
+{
+ CSSParserLocation location;
+ location.token.init(tokenStart<CharacterType>(), currentCharacter<CharacterType>() - tokenStart<CharacterType>());
+ location.lineNumber = m_tokenStartLineNumber;
+ location.offset = tokenStart<CharacterType>() - dataStart<CharacterType>();
+ return location;
+}
+
+CSSParserLocation CSSTokenizer::currentLocation()
+{
+ if (is8BitSource())
+ return tokenLocation<LChar>();
+ return tokenLocation<UChar>();
+}
+
+template <typename CharacterType>
+inline bool CSSTokenizer::isIdentifierStart()
+{
+ // Check whether an identifier is started.
+ return isIdentifierStartAfterDash((*currentCharacter<CharacterType>() != '-') ? currentCharacter<CharacterType>() : currentCharacter<CharacterType>() + 1);
+}
+
+template <typename CharacterType>
+static inline CharacterType* checkAndSkipString(CharacterType* currentCharacter, int quote)
+{
+ // Returns with 0, if string check is failed. Otherwise
+ // it returns with the following character. This is necessary
+ // since we cannot revert escape sequences, thus strings
+ // must be validated before parsing.
+ while (true) {
+ if (UNLIKELY(*currentCharacter == quote)) {
+ // String parsing is successful.
+ return currentCharacter + 1;
+ }
+ if (UNLIKELY(!*currentCharacter)) {
+ // String parsing is successful up to end of input.
+ return currentCharacter;
+ }
+ if (UNLIKELY(*currentCharacter <= '\r' && (*currentCharacter == '\n' || (*currentCharacter | 0x1) == '\r'))) {
+ // String parsing is failed for character '\n', '\f' or '\r'.
+ return 0;
+ }
+
+ if (LIKELY(currentCharacter[0] != '\\')) {
+ ++currentCharacter;
+ } else if (currentCharacter[1] == '\n' || currentCharacter[1] == '\f') {
+ currentCharacter += 2;
+ } else if (currentCharacter[1] == '\r') {
+ currentCharacter += currentCharacter[2] == '\n' ? 3 : 2;
+ } else {
+ currentCharacter = checkAndSkipEscape(currentCharacter);
+ if (!currentCharacter)
+ return 0;
+ }
+ }
+}
+
+template <typename CharacterType>
+unsigned CSSTokenizer::parseEscape(CharacterType*& src)
+{
+ ASSERT(*src == '\\' && isCSSEscape(src[1]));
+
+ unsigned unicode = 0;
+
+ ++src;
+ if (isASCIIHexDigit(*src)) {
+
+ int length = 6;
+
+ do {
+ unicode = (unicode << 4) + toASCIIHexValue(*src++);
+ } while (--length && isASCIIHexDigit(*src));
+
+ // Characters above 0x10ffff are not handled.
+ if (unicode > 0x10ffff)
+ unicode = 0xfffd;
+
+ // Optional space after the escape sequence.
+ if (isHTMLSpace<CharacterType>(*src))
+ ++src;
+
+ return unicode;
+ }
+
+ return *currentCharacter<CharacterType>()++;
+}
+
+template <>
+inline void CSSTokenizer::UnicodeToChars<LChar>(LChar*& result, unsigned unicode)
+{
+ ASSERT(unicode <= 0xff);
+ *result = unicode;
+
+ ++result;
+}
+
+template <>
+inline void CSSTokenizer::UnicodeToChars<UChar>(UChar*& result, unsigned unicode)
+{
+ // Replace unicode with a surrogate pairs when it is bigger than 0xffff
+ if (U16_LENGTH(unicode) == 2) {
+ *result++ = U16_LEAD(unicode);
+ *result = U16_TRAIL(unicode);
+ } else {
+ *result = unicode;
+ }
+
+ ++result;
+}
+
+template <typename SrcCharacterType, typename DestCharacterType>
+inline bool CSSTokenizer::parseIdentifierInternal(SrcCharacterType*& src, DestCharacterType*& result, bool& hasEscape)
+{
+ hasEscape = false;
+ do {
+ if (LIKELY(*src != '\\')) {
+ *result++ = *src++;
+ } else {
+ hasEscape = true;
+ SrcCharacterType* savedEscapeStart = src;
+ unsigned unicode = parseEscape<SrcCharacterType>(src);
+ if (unicode > 0xff && sizeof(DestCharacterType) == 1) {
+ src = savedEscapeStart;
+ return false;
+ }
+ UnicodeToChars(result, unicode);
+ }
+ } while (isCSSLetter(src[0]) || (src[0] == '\\' && isCSSEscape(src[1])));
+
+ return true;
+}
+
+template <typename CharacterType>
+inline void CSSTokenizer::parseIdentifier(CharacterType*& result, CSSParserString& resultString, bool& hasEscape)
+{
+ // If a valid identifier start is found, we can safely
+ // parse the identifier until the next invalid character.
+ ASSERT(isIdentifierStart<CharacterType>());
+
+ CharacterType* start = currentCharacter<CharacterType>();
+ if (UNLIKELY(!parseIdentifierInternal(currentCharacter<CharacterType>(), result, hasEscape))) {
+ // Found an escape we couldn't handle with 8 bits, copy what has been recognized and continue
+ ASSERT(is8BitSource());
+ UChar*& result16 = currentCharacter16();
+ UChar* start16 = result16;
+ int i = 0;
+ for (; i < result - start; i++)
+ result16[i] = start[i];
+
+ result16 += i;
+
+ parseIdentifierInternal(currentCharacter<CharacterType>(), result16, hasEscape);
+
+ resultString.init(start16, result16 - start16);
+
+ return;
+ }
+
+ resultString.init(start, result - start);
+}
+
+template <typename SrcCharacterType, typename DestCharacterType>
+inline bool CSSTokenizer::parseStringInternal(SrcCharacterType*& src, DestCharacterType*& result, UChar quote)
+{
+ while (true) {
+ if (UNLIKELY(*src == quote)) {
+ // String parsing is done.
+ ++src;
+ return true;
+ }
+ if (UNLIKELY(!*src)) {
+ // String parsing is done, but don't advance pointer if at the end of input.
+ return true;
+ }
+ ASSERT(*src > '\r' || (*src < '\n' && *src) || *src == '\v');
+
+ if (LIKELY(src[0] != '\\')) {
+ *result++ = *src++;
+ } else if (src[1] == '\n' || src[1] == '\f') {
+ src += 2;
+ } else if (src[1] == '\r') {
+ src += src[2] == '\n' ? 3 : 2;
+ } else {
+ SrcCharacterType* savedEscapeStart = src;
+ unsigned unicode = parseEscape<SrcCharacterType>(src);
+ if (unicode > 0xff && sizeof(DestCharacterType) == 1) {
+ src = savedEscapeStart;
+ return false;
+ }
+ UnicodeToChars(result, unicode);
+ }
+ }
+
+ return true;
+}
+
+template <typename CharacterType>
+inline void CSSTokenizer::parseString(CharacterType*& result, CSSParserString& resultString, UChar quote)
+{
+ CharacterType* start = currentCharacter<CharacterType>();
+
+ if (UNLIKELY(!parseStringInternal(currentCharacter<CharacterType>(), result, quote))) {
+ // Found an escape we couldn't handle with 8 bits, copy what has been recognized and continue
+ ASSERT(is8BitSource());
+ UChar*& result16 = currentCharacter16();
+ UChar* start16 = result16;
+ int i = 0;
+ for (; i < result - start; i++)
+ result16[i] = start[i];
+
+ result16 += i;
+
+ parseStringInternal(currentCharacter<CharacterType>(), result16, quote);
+
+ resultString.init(start16, result16 - start16);
+ return;
+ }
+
+ resultString.init(start, result - start);
+}
+
+template <typename CharacterType>
+inline bool CSSTokenizer::findURI(CharacterType*& start, CharacterType*& end, UChar& quote)
+{
+ start = skipWhiteSpace(currentCharacter<CharacterType>());
+
+ if (*start == '"' || *start == '\'') {
+ quote = *start++;
+ end = checkAndSkipString(start, quote);
+ if (!end)
+ return false;
+ } else {
+ quote = 0;
+ end = start;
+ while (isURILetter(*end)) {
+ if (LIKELY(*end != '\\')) {
+ ++end;
+ } else {
+ end = checkAndSkipEscape(end);
+ if (!end)
+ return false;
+ }
+ }
+ }
+
+ end = skipWhiteSpace(end);
+ if (*end != ')')
+ return false;
+
+ return true;
+}
+
+template <typename SrcCharacterType, typename DestCharacterType>
+inline bool CSSTokenizer::parseURIInternal(SrcCharacterType*& src, DestCharacterType*& dest, UChar quote)
+{
+ if (quote) {
+ ASSERT(quote == '"' || quote == '\'');
+ return parseStringInternal(src, dest, quote);
+ }
+
+ while (isURILetter(*src)) {
+ if (LIKELY(*src != '\\')) {
+ *dest++ = *src++;
+ } else {
+ unsigned unicode = parseEscape<SrcCharacterType>(src);
+ if (unicode > 0xff && sizeof(SrcCharacterType) == 1)
+ return false;
+ UnicodeToChars(dest, unicode);
+ }
+ }
+
+ return true;
+}
+
+template <typename CharacterType>
+inline void CSSTokenizer::parseURI(CSSParserString& string)
+{
+ CharacterType* uriStart;
+ CharacterType* uriEnd;
+ UChar quote;
+ if (!findURI(uriStart, uriEnd, quote))
+ return;
+
+ CharacterType* dest = currentCharacter<CharacterType>() = uriStart;
+ if (LIKELY(parseURIInternal(currentCharacter<CharacterType>(), dest, quote))) {
+ string.init(uriStart, dest - uriStart);
+ } else {
+ // An escape sequence was encountered that can't be stored in 8 bits.
+ // Reset the current character to the start of the URI and re-parse with
+ // a 16-bit destination.
+ ASSERT(is8BitSource());
+ UChar* uriStart16 = currentCharacter16();
+ currentCharacter<CharacterType>() = uriStart;
+ bool result = parseURIInternal(currentCharacter<CharacterType>(), currentCharacter16(), quote);
+ ASSERT_UNUSED(result, result);
+ string.init(uriStart16, currentCharacter16() - uriStart16);
+ }
+
+ currentCharacter<CharacterType>() = uriEnd + 1;
+ m_token = URI;
+}
+
+template <typename CharacterType>
+inline bool CSSTokenizer::parseUnicodeRange()
+{
+ CharacterType* character = currentCharacter<CharacterType>() + 1;
+ int length = 6;
+ ASSERT(*currentCharacter<CharacterType>() == '+');
+
+ while (isASCIIHexDigit(*character) && length) {
+ ++character;
+ --length;
+ }
+
+ if (length && *character == '?') {
+ // At most 5 hex digit followed by a question mark.
+ do {
+ ++character;
+ --length;
+ } while (*character == '?' && length);
+ currentCharacter<CharacterType>() = character;
+ return true;
+ }
+
+ if (length < 6) {
+ // At least one hex digit.
+ if (character[0] == '-' && isASCIIHexDigit(character[1])) {
+ // Followed by a dash and a hex digit.
+ ++character;
+ length = 6;
+ do {
+ ++character;
+ } while (--length && isASCIIHexDigit(*character));
+ }
+ currentCharacter<CharacterType>() = character;
+ return true;
+ }
+ return false;
+}
+
+template <typename CharacterType>
+bool CSSTokenizer::parseNthChild()
+{
+ CharacterType* character = currentCharacter<CharacterType>();
+
+ while (isASCIIDigit(*character))
+ ++character;
+ if (isASCIIAlphaCaselessEqual(*character, 'n')) {
+ currentCharacter<CharacterType>() = character + 1;
+ return true;
+ }
+ return false;
+}
+
+template <typename CharacterType>
+bool CSSTokenizer::parseNthChildExtra()
+{
+ CharacterType* character = skipWhiteSpace(currentCharacter<CharacterType>());
+ if (*character != '+' && *character != '-')
+ return false;
+
+ character = skipWhiteSpace(character + 1);
+ if (!isASCIIDigit(*character))
+ return false;
+
+ do {
+ ++character;
+ } while (isASCIIDigit(*character));
+
+ currentCharacter<CharacterType>() = character;
+ return true;
+}
+
+template <typename CharacterType>
+inline bool CSSTokenizer::detectFunctionTypeToken(int length)
+{
+ ASSERT(length > 0);
+ CharacterType* name = tokenStart<CharacterType>();
+ SWITCH(name, length) {
+ CASE("not") {
+ m_token = NOTFUNCTION;
+ return true;
+ }
+ CASE("url") {
+ m_token = URI;
+ return true;
+ }
+ CASE("cue") {
+ m_token = CUEFUNCTION;
+ return true;
+ }
+ CASE("var") {
+ if (!RuntimeEnabledFeatures::cssVariablesEnabled())
+ return false;
+ m_token = VARFUNCTION;
+ return true;
+ }
+ CASE("calc") {
+ m_token = CALCFUNCTION;
+ return true;
+ }
+ CASE("host") {
+ m_token = HOSTFUNCTION;
+ return true;
+ }
+ CASE("nth-child") {
+ m_parsingMode = NthChildMode;
+ return true;
+ }
+ CASE("nth-of-type") {
+ m_parsingMode = NthChildMode;
+ return true;
+ }
+ CASE("nth-last-child") {
+ m_parsingMode = NthChildMode;
+ return true;
+ }
+ CASE("nth-last-of-type") {
+ m_parsingMode = NthChildMode;
+ return true;
+ }
+ }
+ return false;
+}
+
+template <typename CharacterType>
+inline void CSSTokenizer::detectMediaQueryToken(int length)
+{
+ ASSERT(m_parsingMode == MediaQueryMode);
+ CharacterType* name = tokenStart<CharacterType>();
+
+ SWITCH(name, length) {
+ CASE("and") {
+ m_token = MEDIA_AND;
+ }
+ CASE("not") {
+ m_token = MEDIA_NOT;
+ }
+ CASE("only") {
+ m_token = MEDIA_ONLY;
+ }
+ CASE("or") {
+ m_token = MEDIA_OR;
+ }
+ }
+}
+
+template <typename CharacterType>
+inline void CSSTokenizer::detectNumberToken(CharacterType* type, int length)
+{
+ ASSERT(length > 0);
+
+ SWITCH(type, length) {
+ CASE("cm") {
+ m_token = CMS;
+ }
+ CASE("ch") {
+ m_token = CHS;
+ }
+ CASE("deg") {
+ m_token = DEGS;
+ }
+ CASE("dppx") {
+ // There is a discussion about the name of this unit on www-style.
+ // Keep this compile time guard in place until that is resolved.
+ // http://lists.w3.org/Archives/Public/www-style/2012May/0915.html
+ m_token = DPPX;
+ }
+ CASE("dpcm") {
+ m_token = DPCM;
+ }
+ CASE("dpi") {
+ m_token = DPI;
+ }
+ CASE("em") {
+ m_token = EMS;
+ }
+ CASE("ex") {
+ m_token = EXS;
+ }
+ CASE("fr") {
+ m_token = FR;
+ }
+ CASE("grad") {
+ m_token = GRADS;
+ }
+ CASE("hz") {
+ m_token = HERTZ;
+ }
+ CASE("in") {
+ m_token = INS;
+ }
+ CASE("khz") {
+ m_token = KHERTZ;
+ }
+ CASE("mm") {
+ m_token = MMS;
+ }
+ CASE("ms") {
+ m_token = MSECS;
+ }
+ CASE("px") {
+ m_token = PXS;
+ }
+ CASE("pt") {
+ m_token = PTS;
+ }
+ CASE("pc") {
+ m_token = PCS;
+ }
+ CASE("rad") {
+ m_token = RADS;
+ }
+ CASE("rem") {
+ m_token = REMS;
+ }
+ CASE("s") {
+ m_token = SECS;
+ }
+ CASE("turn") {
+ m_token = TURNS;
+ }
+ CASE("vw") {
+ m_token = VW;
+ }
+ CASE("vh") {
+ m_token = VH;
+ }
+ CASE("vmin") {
+ m_token = VMIN;
+ }
+ CASE("vmax") {
+ m_token = VMAX;
+ }
+ CASE("__qem") {
+ m_token = QEMS;
+ }
+ }
+}
+
+template <typename CharacterType>
+inline void CSSTokenizer::detectDashToken(int length)
+{
+ CharacterType* name = tokenStart<CharacterType>();
+
+ // Ignore leading dash.
+ ++name;
+ --length;
+
+ SWITCH(name, length) {
+ CASE("webkit-any") {
+ m_token = ANYFUNCTION;
+ }
+ CASE("webkit-min") {
+ m_token = MINFUNCTION;
+ }
+ CASE("webkit-max") {
+ m_token = MAXFUNCTION;
+ }
+ CASE("webkit-calc") {
+ m_token = CALCFUNCTION;
+ }
+ CASE("webkit-distributed") {
+ m_token = DISTRIBUTEDFUNCTION;
+ }
+ }
+}
+
+template <typename CharacterType>
+inline void CSSTokenizer::detectAtToken(int length, bool hasEscape)
+{
+ CharacterType* name = tokenStart<CharacterType>();
+ ASSERT(name[0] == '@' && length >= 2);
+
+ // Ignore leading @.
+ ++name;
+ --length;
+
+ // charset, font-face, import, media, namespace, page, supports,
+ // -webkit-keyframes, keyframes, and -webkit-mediaquery are not affected by hasEscape.
+ SWITCH(name, length) {
+ CASE("bottom-left") {
+ if (LIKELY(!hasEscape))
+ m_token = BOTTOMLEFT_SYM;
+ }
+ CASE("bottom-right") {
+ if (LIKELY(!hasEscape))
+ m_token = BOTTOMRIGHT_SYM;
+ }
+ CASE("bottom-center") {
+ if (LIKELY(!hasEscape))
+ m_token = BOTTOMCENTER_SYM;
+ }
+ CASE("bottom-left-corner") {
+ if (LIKELY(!hasEscape))
+ m_token = BOTTOMLEFTCORNER_SYM;
+ }
+ CASE("bottom-right-corner") {
+ if (LIKELY(!hasEscape))
+ m_token = BOTTOMRIGHTCORNER_SYM;
+ }
+ CASE("charset") {
+ if (name - 1 == dataStart<CharacterType>())
+ m_token = CHARSET_SYM;
+ }
+ CASE("font-face") {
+ m_token = FONT_FACE_SYM;
+ }
+ CASE("import") {
+ m_parsingMode = MediaQueryMode;
+ m_token = IMPORT_SYM;
+ }
+ CASE("keyframes") {
+ if (RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled())
+ m_token = KEYFRAMES_SYM;
+ }
+ CASE("left-top") {
+ if (LIKELY(!hasEscape))
+ m_token = LEFTTOP_SYM;
+ }
+ CASE("left-middle") {
+ if (LIKELY(!hasEscape))
+ m_token = LEFTMIDDLE_SYM;
+ }
+ CASE("left-bottom") {
+ if (LIKELY(!hasEscape))
+ m_token = LEFTBOTTOM_SYM;
+ }
+ CASE("media") {
+ m_parsingMode = MediaQueryMode;
+ m_token = MEDIA_SYM;
+ }
+ CASE("namespace") {
+ m_token = NAMESPACE_SYM;
+ }
+ CASE("page") {
+ m_token = PAGE_SYM;
+ }
+ CASE("right-top") {
+ if (LIKELY(!hasEscape))
+ m_token = RIGHTTOP_SYM;
+ }
+ CASE("right-middle") {
+ if (LIKELY(!hasEscape))
+ m_token = RIGHTMIDDLE_SYM;
+ }
+ CASE("right-bottom") {
+ if (LIKELY(!hasEscape))
+ m_token = RIGHTBOTTOM_SYM;
+ }
+ CASE("supports") {
+ m_parsingMode = SupportsMode;
+ m_token = SUPPORTS_SYM;
+ }
+ CASE("top-left") {
+ if (LIKELY(!hasEscape))
+ m_token = TOPLEFT_SYM;
+ }
+ CASE("top-right") {
+ if (LIKELY(!hasEscape))
+ m_token = TOPRIGHT_SYM;
+ }
+ CASE("top-center") {
+ if (LIKELY(!hasEscape))
+ m_token = TOPCENTER_SYM;
+ }
+ CASE("top-left-corner") {
+ if (LIKELY(!hasEscape))
+ m_token = TOPLEFTCORNER_SYM;
+ }
+ CASE("top-right-corner") {
+ if (LIKELY(!hasEscape))
+ m_token = TOPRIGHTCORNER_SYM;
+ }
+ CASE("viewport") {
+ m_token = VIEWPORT_RULE_SYM;
+ }
+ CASE("-internal-rule") {
+ if (LIKELY(!hasEscape && m_internal))
+ m_token = INTERNAL_RULE_SYM;
+ }
+ CASE("-webkit-region") {
+ if (LIKELY(!hasEscape))
+ m_token = WEBKIT_REGION_RULE_SYM;
+ }
+ CASE("-webkit-filter") {
+ if (LIKELY(!hasEscape))
+ m_token = WEBKIT_FILTER_RULE_SYM;
+ }
+ CASE("-internal-decls") {
+ if (LIKELY(!hasEscape && m_internal))
+ m_token = INTERNAL_DECLS_SYM;
+ }
+ CASE("-internal-value") {
+ if (LIKELY(!hasEscape && m_internal))
+ m_token = INTERNAL_VALUE_SYM;
+ }
+ CASE("-webkit-keyframes") {
+ m_token = WEBKIT_KEYFRAMES_SYM;
+ }
+ CASE("-internal-selector") {
+ if (LIKELY(!hasEscape && m_internal))
+ m_token = INTERNAL_SELECTOR_SYM;
+ }
+ CASE("-internal-medialist") {
+ if (!m_internal)
+ return;
+ m_parsingMode = MediaQueryMode;
+ m_token = INTERNAL_MEDIALIST_SYM;
+ }
+ CASE("-internal-keyframe-rule") {
+ if (LIKELY(!hasEscape && m_internal))
+ m_token = INTERNAL_KEYFRAME_RULE_SYM;
+ }
+ CASE("-internal-keyframe-key-list") {
+ if (!m_internal)
+ return;
+ m_token = INTERNAL_KEYFRAME_KEY_LIST_SYM;
+ }
+ CASE("-internal-supports-condition") {
+ if (!m_internal)
+ return;
+ m_parsingMode = SupportsMode;
+ m_token = INTERNAL_SUPPORTS_CONDITION_SYM;
+ }
+ }
+}
+
+template <typename CharacterType>
+inline void CSSTokenizer::detectSupportsToken(int length)
+{
+ ASSERT(m_parsingMode == SupportsMode);
+ CharacterType* name = tokenStart<CharacterType>();
+
+ SWITCH(name, length) {
+ CASE("or") {
+ m_token = SUPPORTS_OR;
+ }
+ CASE("and") {
+ m_token = SUPPORTS_AND;
+ }
+ CASE("not") {
+ m_token = SUPPORTS_NOT;
+ }
+ }
+}
+
+template <typename CharacterType>
+inline void CSSTokenizer::detectCSSVariableDefinitionToken(int length)
+{
+ static const int prefixLength = static_cast<int>(sizeof("var-") - 1);
+ if (length <= prefixLength)
+ return;
+ CharacterType* name = tokenStart<CharacterType>();
+ COMPILE_ASSERT(prefixLength > 0, CSS_variable_prefix_must_be_nonempty);
+ if (name[prefixLength - 1] == '-' && isIdentifierStartAfterDash(name + prefixLength) && isEqualToCSSCaseSensitiveIdentifier(name, "var"))
+ m_token = VAR_DEFINITION;
+}
+
+template <typename SrcCharacterType>
+int CSSTokenizer::realLex(void* yylvalWithoutType)
+{
+ YYSTYPE* yylval = static_cast<YYSTYPE*>(yylvalWithoutType);
+ // Write pointer for the next character.
+ SrcCharacterType* result;
+ CSSParserString resultString;
+ bool hasEscape;
+
+ // The input buffer is terminated by a \0 character, so
+ // it is safe to read one character ahead of a known non-null.
+#ifndef NDEBUG
+ // In debug we check with an ASSERT that the length is > 0 for string types.
+ yylval->string.clear();
+#endif
+
+restartAfterComment:
+ result = currentCharacter<SrcCharacterType>();
+ setTokenStart(result);
+ m_tokenStartLineNumber = m_lineNumber;
+ m_token = *currentCharacter<SrcCharacterType>();
+ ++currentCharacter<SrcCharacterType>();
+
+ switch ((m_token <= 127) ? typesOfASCIICharacters[m_token] : CharacterIdentifierStart) {
+ case CharacterCaselessU:
+ if (UNLIKELY(*currentCharacter<SrcCharacterType>() == '+')) {
+ if (parseUnicodeRange<SrcCharacterType>()) {
+ m_token = UNICODERANGE;
+ yylval->string.init(tokenStart<SrcCharacterType>(), currentCharacter<SrcCharacterType>() - tokenStart<SrcCharacterType>());
+ break;
+ }
+ }
+ // Fall through to CharacterIdentifierStart.
+
+ case CharacterIdentifierStart:
+ --currentCharacter<SrcCharacterType>();
+ parseIdentifier(result, yylval->string, hasEscape);
+ m_token = IDENT;
+
+ if (UNLIKELY(*currentCharacter<SrcCharacterType>() == '(')) {
+ if (m_parsingMode == SupportsMode && !hasEscape) {
+ detectSupportsToken<SrcCharacterType>(result - tokenStart<SrcCharacterType>());
+ if (m_token != IDENT)
+ break;
+ }
+
+ m_token = FUNCTION;
+ if (!hasEscape)
+ detectFunctionTypeToken<SrcCharacterType>(result - tokenStart<SrcCharacterType>());
+
+ // Skip parenthesis
+ ++currentCharacter<SrcCharacterType>();
+ ++result;
+ ++yylval->string.m_length;
+
+ if (m_token == URI) {
+ m_token = FUNCTION;
+ // Check whether it is really an URI.
+ if (yylval->string.is8Bit())
+ parseURI<LChar>(yylval->string);
+ else
+ parseURI<UChar>(yylval->string);
+ }
+ } else if (UNLIKELY(m_parsingMode != NormalMode) && !hasEscape) {
+ if (m_parsingMode == MediaQueryMode) {
+ detectMediaQueryToken<SrcCharacterType>(result - tokenStart<SrcCharacterType>());
+ } else if (m_parsingMode == SupportsMode) {
+ detectSupportsToken<SrcCharacterType>(result - tokenStart<SrcCharacterType>());
+ } else if (m_parsingMode == NthChildMode && isASCIIAlphaCaselessEqual(tokenStart<SrcCharacterType>()[0], 'n')) {
+ if (result - tokenStart<SrcCharacterType>() == 1) {
+ // String "n" is IDENT but "n+1" is NTH.
+ if (parseNthChildExtra<SrcCharacterType>()) {
+ m_token = NTH;
+ yylval->string.m_length = currentCharacter<SrcCharacterType>() - tokenStart<SrcCharacterType>();
+ }
+ } else if (result - tokenStart<SrcCharacterType>() >= 2 && tokenStart<SrcCharacterType>()[1] == '-') {
+ // String "n-" is IDENT but "n-1" is NTH.
+ // Set currentCharacter to '-' to continue parsing.
+ SrcCharacterType* nextCharacter = result;
+ currentCharacter<SrcCharacterType>() = tokenStart<SrcCharacterType>() + 1;
+ if (parseNthChildExtra<SrcCharacterType>()) {
+ m_token = NTH;
+ yylval->string.setLength(currentCharacter<SrcCharacterType>() - tokenStart<SrcCharacterType>());
+ } else {
+ // Revert the change to currentCharacter if unsuccessful.
+ currentCharacter<SrcCharacterType>() = nextCharacter;
+ }
+ }
+ }
+ } else if (UNLIKELY(RuntimeEnabledFeatures::cssVariablesEnabled())) {
+ detectCSSVariableDefinitionToken<SrcCharacterType>(result - tokenStart<SrcCharacterType>());
+ }
+ break;
+
+ case CharacterDot:
+ if (!isASCIIDigit(currentCharacter<SrcCharacterType>()[0]))
+ break;
+ // Fall through to CharacterNumber.
+
+ case CharacterNumber: {
+ bool dotSeen = (m_token == '.');
+
+ while (true) {
+ if (!isASCIIDigit(currentCharacter<SrcCharacterType>()[0])) {
+ // Only one dot is allowed for a number,
+ // and it must be followed by a digit.
+ if (currentCharacter<SrcCharacterType>()[0] != '.' || dotSeen || !isASCIIDigit(currentCharacter<SrcCharacterType>()[1]))
+ break;
+ dotSeen = true;
+ }
+ ++currentCharacter<SrcCharacterType>();
+ }
+
+ if (UNLIKELY(m_parsingMode == NthChildMode) && !dotSeen && isASCIIAlphaCaselessEqual(*currentCharacter<SrcCharacterType>(), 'n')) {
+ // "[0-9]+n" is always an NthChild.
+ ++currentCharacter<SrcCharacterType>();
+ parseNthChildExtra<SrcCharacterType>();
+ m_token = NTH;
+ yylval->string.init(tokenStart<SrcCharacterType>(), currentCharacter<SrcCharacterType>() - tokenStart<SrcCharacterType>());
+ break;
+ }
+
+ // Use SVG parser for numbers on SVG presentation attributes.
+ if (isSVGNumberParsingEnabledForMode(m_parser.m_context.mode())) {
+ // We need to take care of units like 'em' or 'ex'.
+ SrcCharacterType* character = currentCharacter<SrcCharacterType>();
+ if (isASCIIAlphaCaselessEqual(*character, 'e')) {
+ ASSERT(character - tokenStart<SrcCharacterType>() > 0);
+ ++character;
+ if (*character == '-' || *character == '+' || isASCIIDigit(*character)) {
+ ++character;
+ while (isASCIIDigit(*character))
+ ++character;
+ // Use FLOATTOKEN if the string contains exponents.
+ dotSeen = true;
+ currentCharacter<SrcCharacterType>() = character;
+ }
+ }
+ if (!parseSVGNumber(tokenStart<SrcCharacterType>(), character - tokenStart<SrcCharacterType>(), yylval->number))
+ break;
+ } else {
+ yylval->number = charactersToDouble(tokenStart<SrcCharacterType>(), currentCharacter<SrcCharacterType>() - tokenStart<SrcCharacterType>());
+ }
+
+ // Type of the function.
+ if (isIdentifierStart<SrcCharacterType>()) {
+ SrcCharacterType* type = currentCharacter<SrcCharacterType>();
+ result = currentCharacter<SrcCharacterType>();
+
+ parseIdentifier(result, resultString, hasEscape);
+
+ m_token = DIMEN;
+ if (!hasEscape)
+ detectNumberToken(type, currentCharacter<SrcCharacterType>() - type);
+
+ if (m_token == DIMEN) {
+ // The decoded number is overwritten, but this is intentional.
+ yylval->string.init(tokenStart<SrcCharacterType>(), currentCharacter<SrcCharacterType>() - tokenStart<SrcCharacterType>());
+ }
+ } else if (*currentCharacter<SrcCharacterType>() == '%') {
+ // Although the CSS grammar says {num}% we follow
+ // webkit at the moment which uses {num}%+.
+ do {
+ ++currentCharacter<SrcCharacterType>();
+ } while (*currentCharacter<SrcCharacterType>() == '%');
+ m_token = PERCENTAGE;
+ } else {
+ m_token = dotSeen ? FLOATTOKEN : INTEGER;
+ }
+ break;
+ }
+
+ case CharacterDash:
+ if (isIdentifierStartAfterDash(currentCharacter<SrcCharacterType>())) {
+ --currentCharacter<SrcCharacterType>();
+ parseIdentifier(result, resultString, hasEscape);
+ m_token = IDENT;
+
+ if (*currentCharacter<SrcCharacterType>() == '(') {
+ m_token = FUNCTION;
+ if (!hasEscape)
+ detectDashToken<SrcCharacterType>(result - tokenStart<SrcCharacterType>());
+ ++currentCharacter<SrcCharacterType>();
+ ++result;
+ } else if (UNLIKELY(m_parsingMode == NthChildMode) && !hasEscape && isASCIIAlphaCaselessEqual(tokenStart<SrcCharacterType>()[1], 'n')) {
+ if (result - tokenStart<SrcCharacterType>() == 2) {
+ // String "-n" is IDENT but "-n+1" is NTH.
+ if (parseNthChildExtra<SrcCharacterType>()) {
+ m_token = NTH;
+ result = currentCharacter<SrcCharacterType>();
+ }
+ } else if (result - tokenStart<SrcCharacterType>() >= 3 && tokenStart<SrcCharacterType>()[2] == '-') {
+ // String "-n-" is IDENT but "-n-1" is NTH.
+ // Set currentCharacter to second '-' of '-n-' to continue parsing.
+ SrcCharacterType* nextCharacter = result;
+ currentCharacter<SrcCharacterType>() = tokenStart<SrcCharacterType>() + 2;
+ if (parseNthChildExtra<SrcCharacterType>()) {
+ m_token = NTH;
+ result = currentCharacter<SrcCharacterType>();
+ } else {
+ // Revert the change to currentCharacter if unsuccessful.
+ currentCharacter<SrcCharacterType>() = nextCharacter;
+ }
+ }
+ }
+ resultString.setLength(result - tokenStart<SrcCharacterType>());
+ yylval->string = resultString;
+ } else if (currentCharacter<SrcCharacterType>()[0] == '-' && currentCharacter<SrcCharacterType>()[1] == '>') {
+ currentCharacter<SrcCharacterType>() += 2;
+ m_token = SGML_CD;
+ } else if (UNLIKELY(m_parsingMode == NthChildMode)) {
+ // "-[0-9]+n" is always an NthChild.
+ if (parseNthChild<SrcCharacterType>()) {
+ parseNthChildExtra<SrcCharacterType>();
+ m_token = NTH;
+ yylval->string.init(tokenStart<SrcCharacterType>(), currentCharacter<SrcCharacterType>() - tokenStart<SrcCharacterType>());
+ }
+ }
+ break;
+
+ case CharacterOther:
+ // m_token is simply the current character.
+ break;
+
+ case CharacterNull:
+ // Do not advance pointer at the end of input.
+ --currentCharacter<SrcCharacterType>();
+ break;
+
+ case CharacterWhiteSpace:
+ m_token = WHITESPACE;
+ // Might start with a '\n'.
+ --currentCharacter<SrcCharacterType>();
+ do {
+ if (*currentCharacter<SrcCharacterType>() == '\n')
+ ++m_lineNumber;
+ ++currentCharacter<SrcCharacterType>();
+ } while (*currentCharacter<SrcCharacterType>() <= ' ' && (typesOfASCIICharacters[*currentCharacter<SrcCharacterType>()] == CharacterWhiteSpace));
+ break;
+
+ case CharacterEndMediaQueryOrSupports:
+ if (m_parsingMode == MediaQueryMode || m_parsingMode == SupportsMode)
+ m_parsingMode = NormalMode;
+ break;
+
+ case CharacterEndNthChild:
+ if (m_parsingMode == NthChildMode)
+ m_parsingMode = NormalMode;
+ break;
+
+ case CharacterQuote:
+ if (checkAndSkipString(currentCharacter<SrcCharacterType>(), m_token)) {
+ ++result;
+ parseString<SrcCharacterType>(result, yylval->string, m_token);
+ m_token = STRING;
+ }
+ break;
+
+ case CharacterExclamationMark: {
+ SrcCharacterType* start = skipWhiteSpace(currentCharacter<SrcCharacterType>());
+ if (isEqualToCSSIdentifier(start, "important")) {
+ m_token = IMPORTANT_SYM;
+ currentCharacter<SrcCharacterType>() = start + 9;
+ }
+ break;
+ }
+
+ case CharacterHashmark: {
+ SrcCharacterType* start = currentCharacter<SrcCharacterType>();
+ result = currentCharacter<SrcCharacterType>();
+
+ if (isASCIIDigit(*currentCharacter<SrcCharacterType>())) {
+ // This must be a valid hex number token.
+ do {
+ ++currentCharacter<SrcCharacterType>();
+ } while (isASCIIHexDigit(*currentCharacter<SrcCharacterType>()));
+ m_token = HEX;
+ yylval->string.init(start, currentCharacter<SrcCharacterType>() - start);
+ } else if (isIdentifierStart<SrcCharacterType>()) {
+ m_token = IDSEL;
+ parseIdentifier(result, yylval->string, hasEscape);
+ if (!hasEscape) {
+ // Check whether the identifier is also a valid hex number.
+ SrcCharacterType* current = start;
+ m_token = HEX;
+ do {
+ if (!isASCIIHexDigit(*current)) {
+ m_token = IDSEL;
+ break;
+ }
+ ++current;
+ } while (current < result);
+ }
+ }
+ break;
+ }
+
+ case CharacterSlash:
+ // Ignore comments. They are not even considered as white spaces.
+ if (*currentCharacter<SrcCharacterType>() == '*') {
+ const CSSParserLocation startLocation = currentLocation();
+ if (m_parser.m_sourceDataHandler) {
+ unsigned startOffset = currentCharacter<SrcCharacterType>() - dataStart<SrcCharacterType>() - 1; // Start with a slash.
+ m_parser.m_sourceDataHandler->startComment(startOffset - m_parsedTextPrefixLength);
+ }
+ ++currentCharacter<SrcCharacterType>();
+ while (currentCharacter<SrcCharacterType>()[0] != '*' || currentCharacter<SrcCharacterType>()[1] != '/') {
+ if (*currentCharacter<SrcCharacterType>() == '\n')
+ ++m_lineNumber;
+ if (*currentCharacter<SrcCharacterType>() == '\0') {
+ // Unterminated comments are simply ignored.
+ currentCharacter<SrcCharacterType>() -= 2;
+ m_parser.reportError(startLocation, CSSParser::UnterminatedCommentError);
+ break;
+ }
+ ++currentCharacter<SrcCharacterType>();
+ }
+ currentCharacter<SrcCharacterType>() += 2;
+ if (m_parser.m_sourceDataHandler) {
+ unsigned endOffset = currentCharacter<SrcCharacterType>() - dataStart<SrcCharacterType>();
+ unsigned userTextEndOffset = static_cast<unsigned>(m_length - 1 - m_parsedTextSuffixLength);
+ m_parser.m_sourceDataHandler->endComment(std::min(endOffset, userTextEndOffset) - m_parsedTextPrefixLength);
+ }
+ goto restartAfterComment;
+ }
+ break;
+
+ case CharacterDollar:
+ if (*currentCharacter<SrcCharacterType>() == '=') {
+ ++currentCharacter<SrcCharacterType>();
+ m_token = ENDSWITH;
+ }
+ break;
+
+ case CharacterAsterisk:
+ if (*currentCharacter<SrcCharacterType>() == '=') {
+ ++currentCharacter<SrcCharacterType>();
+ m_token = CONTAINS;
+ }
+ break;
+
+ case CharacterPlus:
+ if (UNLIKELY(m_parsingMode == NthChildMode)) {
+ // Simplest case. "+[0-9]*n" is always NthChild.
+ if (parseNthChild<SrcCharacterType>()) {
+ parseNthChildExtra<SrcCharacterType>();
+ m_token = NTH;
+ yylval->string.init(tokenStart<SrcCharacterType>(), currentCharacter<SrcCharacterType>() - tokenStart<SrcCharacterType>());
+ }
+ }
+ break;
+
+ case CharacterLess:
+ if (currentCharacter<SrcCharacterType>()[0] == '!' && currentCharacter<SrcCharacterType>()[1] == '-' && currentCharacter<SrcCharacterType>()[2] == '-') {
+ currentCharacter<SrcCharacterType>() += 3;
+ m_token = SGML_CD;
+ }
+ break;
+
+ case CharacterAt:
+ if (isIdentifierStart<SrcCharacterType>()) {
+ m_token = ATKEYWORD;
+ ++result;
+ parseIdentifier(result, resultString, hasEscape);
+ detectAtToken<SrcCharacterType>(result - tokenStart<SrcCharacterType>(), hasEscape);
+ }
+ break;
+
+ case CharacterBackSlash:
+ if (isCSSEscape(*currentCharacter<SrcCharacterType>())) {
+ --currentCharacter<SrcCharacterType>();
+ parseIdentifier(result, yylval->string, hasEscape);
+ m_token = IDENT;
+ }
+ break;
+
+ case CharacterXor:
+ if (*currentCharacter<SrcCharacterType>() == '=') {
+ ++currentCharacter<SrcCharacterType>();
+ m_token = BEGINSWITH;
+ }
+ break;
+
+ case CharacterVerticalBar:
+ if (*currentCharacter<SrcCharacterType>() == '=') {
+ ++currentCharacter<SrcCharacterType>();
+ m_token = DASHMATCH;
+ }
+ break;
+
+ case CharacterTilde:
+ if (*currentCharacter<SrcCharacterType>() == '=') {
+ ++currentCharacter<SrcCharacterType>();
+ m_token = INCLUDES;
+ }
+ break;
+
+ default:
+ ASSERT_NOT_REACHED();
+ break;
+ }
+
+ return m_token;
+}
+
+template <>
+inline void CSSTokenizer::setTokenStart<LChar>(LChar* tokenStart)
+{
+ m_tokenStart.ptr8 = tokenStart;
+}
+
+template <>
+inline void CSSTokenizer::setTokenStart<UChar>(UChar* tokenStart)
+{
+ m_tokenStart.ptr16 = tokenStart;
+}
+
+void CSSTokenizer::setupTokenizer(const char* prefix, unsigned prefixLength, const String& string, const char* suffix, unsigned suffixLength)
+{
+ m_parsedTextPrefixLength = prefixLength;
+ m_parsedTextSuffixLength = suffixLength;
+ unsigned stringLength = string.length();
+ unsigned length = stringLength + m_parsedTextPrefixLength + m_parsedTextSuffixLength + 1;
+ m_length = length;
+
+ if (!stringLength || string.is8Bit()) {
+ m_dataStart8 = adoptArrayPtr(new LChar[length]);
+ for (unsigned i = 0; i < m_parsedTextPrefixLength; i++)
+ m_dataStart8[i] = prefix[i];
+
+ if (stringLength)
+ memcpy(m_dataStart8.get() + m_parsedTextPrefixLength, string.characters8(), stringLength * sizeof(LChar));
+
+ unsigned start = m_parsedTextPrefixLength + stringLength;
+ unsigned end = start + suffixLength;
+ for (unsigned i = start; i < end; i++)
+ m_dataStart8[i] = suffix[i - start];
+
+ m_dataStart8[length - 1] = 0;
+
+ m_is8BitSource = true;
+ m_currentCharacter8 = m_dataStart8.get();
+ m_currentCharacter16 = 0;
+ setTokenStart<LChar>(m_currentCharacter8);
+ m_lexFunc = &CSSTokenizer::realLex<LChar>;
+ return;
+ }
+
+ m_dataStart16 = adoptArrayPtr(new UChar[length]);
+ for (unsigned i = 0; i < m_parsedTextPrefixLength; i++)
+ m_dataStart16[i] = prefix[i];
+
+ ASSERT(stringLength);
+ memcpy(m_dataStart16.get() + m_parsedTextPrefixLength, string.characters16(), stringLength * sizeof(UChar));
+
+ unsigned start = m_parsedTextPrefixLength + stringLength;
+ unsigned end = start + suffixLength;
+ for (unsigned i = start; i < end; i++)
+ m_dataStart16[i] = suffix[i - start];
+
+ m_dataStart16[length - 1] = 0;
+
+ m_is8BitSource = false;
+ m_currentCharacter8 = 0;
+ m_currentCharacter16 = m_dataStart16.get();
+ setTokenStart<UChar>(m_currentCharacter16);
+ m_lexFunc = &CSSTokenizer::realLex<UChar>;
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSTokenizer.h b/chromium/third_party/WebKit/Source/core/css/CSSTokenizer.h
new file mode 100644
index 00000000000..05b319c177a
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/css/CSSTokenizer.h
@@ -0,0 +1,197 @@
+/*
+ * Copyright (C) 2003 Lars Knoll (knoll@kde.org)
+ * Copyright (C) 2004, 2005, 2006, 2008, 2009, 2010 Apple Inc. All rights reserved.
+ * Copyright (C) 2008 Eric Seidel <eric@webkit.org>
+ * Copyright (C) 2009 - 2010 Torch Mobile (Beijing) Co. Ltd. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#ifndef CSSTokenizer_h
+#define CSSTokenizer_h
+
+#include "wtf/Noncopyable.h"
+#include "wtf/OwnPtr.h"
+#include "wtf/text/WTFString.h"
+
+namespace WebCore {
+
+class CSSParser;
+struct CSSParserLocation;
+struct CSSParserString;
+
+class CSSTokenizer {
+ WTF_MAKE_NONCOPYABLE(CSSTokenizer);
+public:
+ // FIXME: This should not be needed but there are still some ties between the 2 classes.
+ friend class CSSParser;
+
+ CSSTokenizer(CSSParser& parser)
+ : m_parser(parser)
+ , m_parsedTextPrefixLength(0)
+ , m_parsedTextSuffixLength(0)
+ , m_parsingMode(NormalMode)
+ , m_is8BitSource(false)
+ , m_length(0)
+ , m_token(0)
+ , m_lineNumber(0)
+ , m_tokenStartLineNumber(0)
+ , m_internal(true)
+ {
+ m_tokenStart.ptr8 = 0;
+ }
+
+ void setupTokenizer(const char* prefix, unsigned prefixLength, const String&, const char* suffix, unsigned suffixLength);
+
+ CSSParserLocation currentLocation();
+
+ inline int lex(void* yylval) { return (this->*m_lexFunc)(yylval); }
+
+ inline unsigned safeUserStringTokenOffset()
+ {
+ return std::min(tokenStartOffset(), static_cast<unsigned>(m_length - 1 - m_parsedTextSuffixLength)) - m_parsedTextPrefixLength;
+ }
+
+ bool is8BitSource() const { return m_is8BitSource; }
+
+ // FIXME: These 2 functions should be private so that we don't need the definitions below.
+ template <typename CharacterType>
+ inline CharacterType* tokenStart();
+
+ inline unsigned tokenStartOffset();
+
+private:
+ UChar*& currentCharacter16();
+
+ template <typename CharacterType>
+ inline CharacterType*& currentCharacter();
+
+ template <typename CharacterType>
+ inline CharacterType* dataStart();
+
+ template <typename CharacterType>
+ inline void setTokenStart(CharacterType*);
+
+ template <typename CharacterType>
+ inline bool isIdentifierStart();
+
+ template <typename CharacterType>
+ inline CSSParserLocation tokenLocation();
+
+ template <typename CharacterType>
+ unsigned parseEscape(CharacterType*&);
+ template <typename DestCharacterType>
+ inline void UnicodeToChars(DestCharacterType*&, unsigned);
+ template <typename SrcCharacterType, typename DestCharacterType>
+ inline bool parseIdentifierInternal(SrcCharacterType*&, DestCharacterType*&, bool&);
+
+ template <typename CharacterType>
+ inline void parseIdentifier(CharacterType*&, CSSParserString&, bool&);
+
+ template <typename SrcCharacterType, typename DestCharacterType>
+ inline bool parseStringInternal(SrcCharacterType*&, DestCharacterType*&, UChar);
+
+ template <typename CharacterType>
+ inline void parseString(CharacterType*&, CSSParserString& resultString, UChar);
+
+ template <typename CharacterType>
+ inline bool findURI(CharacterType*& start, CharacterType*& end, UChar& quote);
+
+ template <typename SrcCharacterType, typename DestCharacterType>
+ inline bool parseURIInternal(SrcCharacterType*&, DestCharacterType*&, UChar quote);
+
+ template <typename CharacterType>
+ inline void parseURI(CSSParserString&);
+ template <typename CharacterType>
+ inline bool parseUnicodeRange();
+ template <typename CharacterType>
+ bool parseNthChild();
+ template <typename CharacterType>
+ bool parseNthChildExtra();
+ template <typename CharacterType>
+ inline bool detectFunctionTypeToken(int);
+ template <typename CharacterType>
+ inline void detectMediaQueryToken(int);
+ template <typename CharacterType>
+ inline void detectNumberToken(CharacterType*, int);
+ template <typename CharacterType>
+ inline void detectDashToken(int);
+ template <typename CharacterType>
+ inline void detectAtToken(int, bool);
+ template <typename CharacterType>
+ inline void detectSupportsToken(int);
+ template <typename CharacterType>
+ inline void detectCSSVariableDefinitionToken(int);
+
+ template <typename SourceCharacterType>
+ int realLex(void* yylval);
+
+ CSSParser& m_parser;
+
+ size_t m_parsedTextPrefixLength;
+ size_t m_parsedTextSuffixLength;
+
+ enum ParsingMode {
+ NormalMode,
+ MediaQueryMode,
+ SupportsMode,
+ NthChildMode
+ };
+
+ ParsingMode m_parsingMode;
+ bool m_is8BitSource;
+ OwnPtr<LChar[]> m_dataStart8;
+ OwnPtr<UChar[]> m_dataStart16;
+ LChar* m_currentCharacter8;
+ UChar* m_currentCharacter16;
+ union {
+ LChar* ptr8;
+ UChar* ptr16;
+ } m_tokenStart;
+ unsigned m_length;
+ int m_token;
+ int m_lineNumber;
+ int m_tokenStartLineNumber;
+
+ // FIXME: This boolean is misnamed. Also it would be nice if we could consolidate it
+ // with the CSSParserMode logic to determine if internal properties are allowed.
+ bool m_internal;
+
+ int (CSSTokenizer::*m_lexFunc)(void*);
+};
+
+inline unsigned CSSTokenizer::tokenStartOffset()
+{
+ if (is8BitSource())
+ return m_tokenStart.ptr8 - m_dataStart8.get();
+ return m_tokenStart.ptr16 - m_dataStart16.get();
+}
+
+template <>
+inline LChar* CSSTokenizer::tokenStart<LChar>()
+{
+ return m_tokenStart.ptr8;
+}
+
+template <>
+inline UChar* CSSTokenizer::tokenStart<UChar>()
+{
+ return m_tokenStart.ptr16;
+}
+
+} // namespace WebCore
+
+#endif // CSSTokenizer_h
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSTransformValue.cpp b/chromium/third_party/WebKit/Source/core/css/CSSTransformValue.cpp
index 3be0ec6e95c..de981949bd3 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSTransformValue.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/CSSTransformValue.cpp
@@ -26,8 +26,6 @@
#include "config.h"
#include "core/css/CSSTransformValue.h"
-#include "core/css/CSSValueList.h"
-#include "wtf/PassRefPtr.h"
#include "wtf/text/WTFString.h"
namespace WebCore {
@@ -73,9 +71,9 @@ CSSTransformValue::CSSTransformValue(TransformOperationType op)
{
}
-String CSSTransformValue::customCssText() const
+String CSSTransformValue::customCSSText() const
{
- return transformValueToCssString(m_type, CSSValueList::customCssText());
+ return transformValueToCssString(m_type, CSSValueList::customCSSText());
}
String CSSTransformValue::customSerializeResolvingVariables(const HashMap<AtomicString, String>& variables) const
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSTransformValue.h b/chromium/third_party/WebKit/Source/core/css/CSSTransformValue.h
index 68c83cb402f..1ca3bbd45f1 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSTransformValue.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSTransformValue.h
@@ -64,7 +64,7 @@ public:
return adoptRef(new CSSTransformValue(type));
}
- String customCssText() const;
+ String customCSSText() const;
bool equals(const CSSTransformValue& other) const { return m_type == other.m_type && CSSValueList::equals(other); }
String customSerializeResolvingVariables(const HashMap<AtomicString, String>&) const;
@@ -79,6 +79,8 @@ private:
TransformOperationType m_type;
};
+DEFINE_CSS_VALUE_TYPE_CASTS(CSSTransformValue, isTransformValue());
+
}
#endif
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSUnicodeRangeValue.cpp b/chromium/third_party/WebKit/Source/core/css/CSSUnicodeRangeValue.cpp
index 967df4ec9a8..045f3081efc 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSUnicodeRangeValue.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/CSSUnicodeRangeValue.cpp
@@ -30,7 +30,7 @@
namespace WebCore {
-String CSSUnicodeRangeValue::customCssText() const
+String CSSUnicodeRangeValue::customCSSText() const
{
if (m_from == m_to)
return String::format("U+%X", m_from);
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSUnicodeRangeValue.h b/chromium/third_party/WebKit/Source/core/css/CSSUnicodeRangeValue.h
index 91af8ec1591..3ce02a98cc6 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSUnicodeRangeValue.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSUnicodeRangeValue.h
@@ -41,7 +41,7 @@ public:
UChar32 from() const { return m_from; }
UChar32 to() const { return m_to; }
- String customCssText() const;
+ String customCSSText() const;
bool equals(const CSSUnicodeRangeValue&) const;
@@ -57,6 +57,8 @@ private:
UChar32 m_to;
};
+DEFINE_CSS_VALUE_TYPE_CASTS(CSSUnicodeRangeValue, isUnicodeRangeValue());
+
} // namespace WebCore
#endif // CSSUnicodeRangeValue_h
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSValue.cpp b/chromium/third_party/WebKit/Source/core/css/CSSValue.cpp
index 1ffc0b146d8..6d74434cc11 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSValue.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/CSSValue.cpp
@@ -36,8 +36,11 @@
#include "core/css/CSSCursorImageValue.h"
#include "core/css/CSSFilterValue.h"
#include "core/css/CSSFontFaceSrcValue.h"
+#include "core/css/CSSFontFeatureValue.h"
+#include "core/css/CSSFontValue.h"
#include "core/css/CSSFunctionValue.h"
#include "core/css/CSSGradientValue.h"
+#include "core/css/CSSGridLineNamesValue.h"
#include "core/css/CSSGridTemplateValue.h"
#include "core/css/CSSImageSetValue.h"
#include "core/css/CSSImageValue.h"
@@ -49,14 +52,12 @@
#include "core/css/CSSReflectValue.h"
#include "core/css/CSSSVGDocumentValue.h"
#include "core/css/CSSShaderValue.h"
+#include "core/css/CSSShadowValue.h"
#include "core/css/CSSTimingFunctionValue.h"
#include "core/css/CSSTransformValue.h"
#include "core/css/CSSUnicodeRangeValue.h"
#include "core/css/CSSValueList.h"
#include "core/css/CSSVariableValue.h"
-#include "core/css/FontFeatureValue.h"
-#include "core/css/FontValue.h"
-#include "core/css/ShadowValue.h"
#include "core/svg/SVGColor.h"
#include "core/svg/SVGPaint.h"
@@ -66,7 +67,7 @@ struct SameSizeAsCSSValue : public RefCounted<SameSizeAsCSSValue> {
uint32_t bitfields;
};
-COMPILE_ASSERT(sizeof(CSSValue) == sizeof(SameSizeAsCSSValue), CSS_value_should_stay_small);
+COMPILE_ASSERT(sizeof(CSSValue) <= sizeof(SameSizeAsCSSValue), CSS_value_should_stay_small);
class TextCloneCSSValue : public CSSValue {
public:
@@ -85,9 +86,11 @@ private:
String m_cssText;
};
+DEFINE_CSS_VALUE_TYPE_CASTS(TextCloneCSSValue, isTextCloneCSSValue());
+
bool CSSValue::isImplicitInitialValue() const
{
- return m_classType == InitialClass && static_cast<const CSSInitialValue*>(this)->isImplicit();
+ return m_classType == InitialClass && toCSSInitialValue(this)->isImplicit();
}
CSSValue::Type CSSValue::cssValueType() const
@@ -113,9 +116,9 @@ void CSSValue::addSubresourceStyleURLs(ListHashSet<KURL>& urls, const StyleSheet
else if (isValueList())
toCSSValueList(this)->addSubresourceStyleURLs(urls, styleSheet);
else if (classType() == FontFaceSrcClass)
- static_cast<const CSSFontFaceSrcValue*>(this)->addSubresourceStyleURLs(urls, styleSheet);
+ toCSSFontFaceSrcValue(this)->addSubresourceStyleURLs(urls, styleSheet);
else if (classType() == ReflectClass)
- static_cast<const CSSReflectValue*>(this)->addSubresourceStyleURLs(urls, styleSheet);
+ toCSSReflectValue(this)->addSubresourceStyleURLs(urls, styleSheet);
}
bool CSSValue::hasFailedOrCanceledSubresources() const
@@ -126,13 +129,13 @@ bool CSSValue::hasFailedOrCanceledSubresources() const
if (isValueList())
return toCSSValueList(this)->hasFailedOrCanceledSubresources();
if (classType() == FontFaceSrcClass)
- return static_cast<const CSSFontFaceSrcValue*>(this)->hasFailedOrCanceledSubresources();
+ return toCSSFontFaceSrcValue(this)->hasFailedOrCanceledSubresources();
if (classType() == ImageClass)
return toCSSImageValue(this)->hasFailedOrCanceledSubresources();
if (classType() == CrossfadeClass)
- return static_cast<const CSSCrossfadeValue*>(this)->hasFailedOrCanceledSubresources();
+ return toCSSCrossfadeValue(this)->hasFailedOrCanceledSubresources();
if (classType() == ImageSetClass)
- return static_cast<const CSSImageSetValue*>(this)->hasFailedOrCanceledSubresources();
+ return toCSSImageSetValue(this)->hasFailedOrCanceledSubresources();
return false;
}
@@ -147,7 +150,7 @@ bool CSSValue::equals(const CSSValue& other) const
{
if (m_isTextClone) {
ASSERT(isCSSOMSafe());
- return static_cast<const TextCloneCSSValue*>(this)->cssText() == other.cssText();
+ return toTextCloneCSSValue(this)->cssText() == other.cssText();
}
if (m_classType == other.m_classType) {
@@ -161,11 +164,11 @@ bool CSSValue::equals(const CSSValue& other) const
case CursorImageClass:
return compareCSSValues<CSSCursorImageValue>(*this, other);
case FontClass:
- return compareCSSValues<FontValue>(*this, other);
+ return compareCSSValues<CSSFontValue>(*this, other);
case FontFaceSrcClass:
return compareCSSValues<CSSFontFaceSrcValue>(*this, other);
case FontFeatureClass:
- return compareCSSValues<FontFeatureValue>(*this, other);
+ return compareCSSValues<CSSFontFeatureValue>(*this, other);
case FunctionClass:
return compareCSSValues<CSSFunctionValue>(*this, other);
case LinearGradientClass:
@@ -180,6 +183,8 @@ bool CSSValue::equals(const CSSValue& other) const
return compareCSSValues<CSSInheritedValue>(*this, other);
case InitialClass:
return compareCSSValues<CSSInitialValue>(*this, other);
+ case GridLineNamesClass:
+ return compareCSSValues<CSSGridLineNamesValue>(*this, other);
case GridTemplateClass:
return compareCSSValues<CSSGridTemplateValue>(*this, other);
case PrimitiveClass:
@@ -187,7 +192,7 @@ bool CSSValue::equals(const CSSValue& other) const
case ReflectClass:
return compareCSSValues<CSSReflectValue>(*this, other);
case ShadowClass:
- return compareCSSValues<ShadowValue>(*this, other);
+ return compareCSSValues<CSSShadowValue>(*this, other);
case CubicBezierTimingFunctionClass:
return compareCSSValues<CSSCubicBezierTimingFunctionValue>(*this, other);
case StepsTimingFunctionClass:
@@ -235,79 +240,81 @@ String CSSValue::cssText() const
{
if (m_isTextClone) {
ASSERT(isCSSOMSafe());
- return static_cast<const TextCloneCSSValue*>(this)->cssText();
+ return toTextCloneCSSValue(this)->cssText();
}
ASSERT(!isCSSOMSafe() || isSubtypeExposedToCSSOM());
switch (classType()) {
case AspectRatioClass:
- return static_cast<const CSSAspectRatioValue*>(this)->customCssText();
+ return toCSSAspectRatioValue(this)->customCSSText();
case BorderImageSliceClass:
- return static_cast<const CSSBorderImageSliceValue*>(this)->customCssText();
+ return toCSSBorderImageSliceValue(this)->customCSSText();
case CanvasClass:
- return static_cast<const CSSCanvasValue*>(this)->customCssText();
+ return toCSSCanvasValue(this)->customCSSText();
case CursorImageClass:
- return static_cast<const CSSCursorImageValue*>(this)->customCssText();
+ return toCSSCursorImageValue(this)->customCSSText();
case FontClass:
- return static_cast<const FontValue*>(this)->customCssText();
+ return toCSSFontValue(this)->customCSSText();
case FontFaceSrcClass:
- return static_cast<const CSSFontFaceSrcValue*>(this)->customCssText();
+ return toCSSFontFaceSrcValue(this)->customCSSText();
case FontFeatureClass:
- return static_cast<const FontFeatureValue*>(this)->customCssText();
+ return toCSSFontFeatureValue(this)->customCSSText();
case FunctionClass:
- return static_cast<const CSSFunctionValue*>(this)->customCssText();
+ return toCSSFunctionValue(this)->customCSSText();
case LinearGradientClass:
- return static_cast<const CSSLinearGradientValue*>(this)->customCssText();
+ return toCSSLinearGradientValue(this)->customCSSText();
case RadialGradientClass:
- return static_cast<const CSSRadialGradientValue*>(this)->customCssText();
+ return toCSSRadialGradientValue(this)->customCSSText();
case CrossfadeClass:
- return static_cast<const CSSCrossfadeValue*>(this)->customCssText();
+ return toCSSCrossfadeValue(this)->customCSSText();
case ImageClass:
- return toCSSImageValue(this)->customCssText();
+ return toCSSImageValue(this)->customCSSText();
case InheritedClass:
- return static_cast<const CSSInheritedValue*>(this)->customCssText();
+ return toCSSInheritedValue(this)->customCSSText();
case InitialClass:
- return static_cast<const CSSInitialValue*>(this)->customCssText();
+ return toCSSInitialValue(this)->customCSSText();
+ case GridLineNamesClass:
+ return toCSSGridLineNamesValue(this)->customCSSText();
case GridTemplateClass:
- return static_cast<const CSSGridTemplateValue*>(this)->customCssText();
+ return toCSSGridTemplateValue(this)->customCSSText();
case PrimitiveClass:
- return toCSSPrimitiveValue(this)->customCssText();
+ return toCSSPrimitiveValue(this)->customCSSText();
case ReflectClass:
- return static_cast<const CSSReflectValue*>(this)->customCssText();
+ return toCSSReflectValue(this)->customCSSText();
case ShadowClass:
- return static_cast<const ShadowValue*>(this)->customCssText();
+ return toCSSShadowValue(this)->customCSSText();
case CubicBezierTimingFunctionClass:
- return static_cast<const CSSCubicBezierTimingFunctionValue*>(this)->customCssText();
+ return toCSSCubicBezierTimingFunctionValue(this)->customCSSText();
case StepsTimingFunctionClass:
- return static_cast<const CSSStepsTimingFunctionValue*>(this)->customCssText();
+ return toCSSStepsTimingFunctionValue(this)->customCSSText();
case UnicodeRangeClass:
- return static_cast<const CSSUnicodeRangeValue*>(this)->customCssText();
+ return toCSSUnicodeRangeValue(this)->customCSSText();
case ValueListClass:
- return toCSSValueList(this)->customCssText();
+ return toCSSValueList(this)->customCSSText();
case CSSTransformClass:
- return static_cast<const CSSTransformValue*>(this)->customCssText();
+ return toCSSTransformValue(this)->customCSSText();
case LineBoxContainClass:
- return static_cast<const CSSLineBoxContainValue*>(this)->customCssText();
+ return toCSSLineBoxContainValue(this)->customCSSText();
case CalculationClass:
- return static_cast<const CSSCalcValue*>(this)->customCssText();
+ return toCSSCalcValue(this)->customCSSText();
case ImageSetClass:
- return static_cast<const CSSImageSetValue*>(this)->customCssText();
+ return toCSSImageSetValue(this)->customCSSText();
case CSSFilterClass:
- return static_cast<const CSSFilterValue*>(this)->customCssText();
+ return toCSSFilterValue(this)->customCSSText();
case CSSArrayFunctionValueClass:
- return static_cast<const CSSArrayFunctionValue*>(this)->customCssText();
+ return toCSSArrayFunctionValue(this)->customCSSText();
case CSSMixFunctionValueClass:
- return static_cast<const CSSMixFunctionValue*>(this)->customCssText();
+ return toCSSMixFunctionValue(this)->customCSSText();
case CSSShaderClass:
- return static_cast<const CSSShaderValue*>(this)->customCssText();
+ return toCSSShaderValue(this)->customCSSText();
case VariableClass:
return toCSSVariableValue(this)->value();
case SVGColorClass:
- return static_cast<const SVGColor*>(this)->customCssText();
+ return toSVGColor(this)->customCSSText();
case SVGPaintClass:
- return static_cast<const SVGPaint*>(this)->customCssText();
+ return toSVGPaint(this)->customCSSText();
case CSSSVGDocumentClass:
- return static_cast<const CSSSVGDocumentValue*>(this)->customCssText();
+ return toCSSSVGDocumentValue(this)->customCSSText();
}
ASSERT_NOT_REACHED();
return String();
@@ -319,11 +326,11 @@ String CSSValue::serializeResolvingVariables(const HashMap<AtomicString, String>
case PrimitiveClass:
return toCSSPrimitiveValue(this)->customSerializeResolvingVariables(variables);
case ReflectClass:
- return static_cast<const CSSReflectValue*>(this)->customSerializeResolvingVariables(variables);
+ return toCSSReflectValue(this)->customSerializeResolvingVariables(variables);
case ValueListClass:
return toCSSValueList(this)->customSerializeResolvingVariables(variables);
case CSSTransformClass:
- return static_cast<const CSSTransformValue*>(this)->customSerializeResolvingVariables(variables);
+ return toCSSTransformValue(this)->customSerializeResolvingVariables(variables);
default:
return cssText();
}
@@ -333,113 +340,116 @@ void CSSValue::destroy()
{
if (m_isTextClone) {
ASSERT(isCSSOMSafe());
- delete static_cast<TextCloneCSSValue*>(this);
+ delete toTextCloneCSSValue(this);
return;
}
ASSERT(!isCSSOMSafe() || isSubtypeExposedToCSSOM());
switch (classType()) {
case AspectRatioClass:
- delete static_cast<CSSAspectRatioValue*>(this);
+ delete toCSSAspectRatioValue(this);
return;
case BorderImageSliceClass:
- delete static_cast<CSSBorderImageSliceValue*>(this);
+ delete toCSSBorderImageSliceValue(this);
return;
case CanvasClass:
- delete static_cast<CSSCanvasValue*>(this);
+ delete toCSSCanvasValue(this);
return;
case CursorImageClass:
- delete static_cast<CSSCursorImageValue*>(this);
+ delete toCSSCursorImageValue(this);
return;
case FontClass:
- delete static_cast<FontValue*>(this);
+ delete toCSSFontValue(this);
return;
case FontFaceSrcClass:
- delete static_cast<CSSFontFaceSrcValue*>(this);
+ delete toCSSFontFaceSrcValue(this);
return;
case FontFeatureClass:
- delete static_cast<FontFeatureValue*>(this);
+ delete toCSSFontFeatureValue(this);
return;
case FunctionClass:
- delete static_cast<CSSFunctionValue*>(this);
+ delete toCSSFunctionValue(this);
return;
case LinearGradientClass:
- delete static_cast<CSSLinearGradientValue*>(this);
+ delete toCSSLinearGradientValue(this);
return;
case RadialGradientClass:
- delete static_cast<CSSRadialGradientValue*>(this);
+ delete toCSSRadialGradientValue(this);
return;
case CrossfadeClass:
- delete static_cast<CSSCrossfadeValue*>(this);
+ delete toCSSCrossfadeValue(this);
return;
case ImageClass:
delete toCSSImageValue(this);
return;
case InheritedClass:
- delete static_cast<CSSInheritedValue*>(this);
+ delete toCSSInheritedValue(this);
return;
case InitialClass:
- delete static_cast<CSSInitialValue*>(this);
+ delete toCSSInitialValue(this);
+ return;
+ case GridLineNamesClass:
+ delete toCSSGridLineNamesValue(this);
return;
case GridTemplateClass:
- delete static_cast<CSSGridTemplateValue*>(this);
+ delete toCSSGridTemplateValue(this);
return;
case PrimitiveClass:
delete toCSSPrimitiveValue(this);
return;
case ReflectClass:
- delete static_cast<CSSReflectValue*>(this);
+ delete toCSSReflectValue(this);
return;
case ShadowClass:
- delete static_cast<ShadowValue*>(this);
+ delete toCSSShadowValue(this);
return;
case CubicBezierTimingFunctionClass:
- delete static_cast<CSSCubicBezierTimingFunctionValue*>(this);
+ delete toCSSCubicBezierTimingFunctionValue(this);
return;
case StepsTimingFunctionClass:
- delete static_cast<CSSStepsTimingFunctionValue*>(this);
+ delete toCSSStepsTimingFunctionValue(this);
return;
case UnicodeRangeClass:
- delete static_cast<CSSUnicodeRangeValue*>(this);
+ delete toCSSUnicodeRangeValue(this);
return;
case ValueListClass:
delete toCSSValueList(this);
return;
case CSSTransformClass:
- delete static_cast<CSSTransformValue*>(this);
+ delete toCSSTransformValue(this);
return;
case LineBoxContainClass:
- delete static_cast<CSSLineBoxContainValue*>(this);
+ delete toCSSLineBoxContainValue(this);
return;
case CalculationClass:
- delete static_cast<CSSCalcValue*>(this);
+ delete toCSSCalcValue(this);
return;
case ImageSetClass:
- delete static_cast<CSSImageSetValue*>(this);
+ delete toCSSImageSetValue(this);
return;
case CSSFilterClass:
- delete static_cast<CSSFilterValue*>(this);
+ delete toCSSFilterValue(this);
return;
case CSSArrayFunctionValueClass:
- delete static_cast<CSSArrayFunctionValue*>(this);
+ delete toCSSArrayFunctionValue(this);
return;
case CSSMixFunctionValueClass:
- delete static_cast<CSSMixFunctionValue*>(this);
+ delete toCSSMixFunctionValue(this);
return;
case CSSShaderClass:
- delete static_cast<CSSShaderValue*>(this);
+ delete toCSSShaderValue(this);
return;
case VariableClass:
delete toCSSVariableValue(this);
return;
case SVGColorClass:
- delete static_cast<SVGColor*>(this);
+ delete toSVGColor(this);
return;
case SVGPaintClass:
- delete static_cast<SVGPaint*>(this);
+ delete toSVGPaint(this);
return;
case CSSSVGDocumentClass:
- delete static_cast<CSSSVGDocumentValue*>(this);
+ delete toCSSSVGDocumentValue(this);
return;
}
ASSERT_NOT_REACHED();
@@ -456,19 +466,19 @@ PassRefPtr<CSSValue> CSSValue::cloneForCSSOM() const
case CursorImageClass:
return toCSSImageValue(this)->cloneForCSSOM();
case CSSFilterClass:
- return static_cast<const CSSFilterValue*>(this)->cloneForCSSOM();
+ return toCSSFilterValue(this)->cloneForCSSOM();
case CSSArrayFunctionValueClass:
- return static_cast<const CSSArrayFunctionValue*>(this)->cloneForCSSOM();
+ return toCSSArrayFunctionValue(this)->cloneForCSSOM();
case CSSMixFunctionValueClass:
- return static_cast<const CSSMixFunctionValue*>(this)->cloneForCSSOM();
+ return toCSSMixFunctionValue(this)->cloneForCSSOM();
case CSSTransformClass:
- return static_cast<const CSSTransformValue*>(this)->cloneForCSSOM();
+ return toCSSTransformValue(this)->cloneForCSSOM();
case ImageSetClass:
- return static_cast<const CSSImageSetValue*>(this)->cloneForCSSOM();
+ return toCSSImageSetValue(this)->cloneForCSSOM();
case SVGColorClass:
- return static_cast<const SVGColor*>(this)->cloneForCSSOM();
+ return toSVGColor(this)->cloneForCSSOM();
case SVGPaintClass:
- return static_cast<const SVGPaint*>(this)->cloneForCSSOM();
+ return toSVGPaint(this)->cloneForCSSOM();
default:
ASSERT(!isSubtypeExposedToCSSOM());
return TextCloneCSSValue::create(classType(), cssText());
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSValue.h b/chromium/third_party/WebKit/Source/core/css/CSSValue.h
index a92bc86a5b5..e6b21b8ce2b 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSValue.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSValue.h
@@ -22,7 +22,8 @@
#define CSSValue_h
#include "core/dom/ExceptionCode.h"
-#include "weborigin/KURL.h"
+#include "platform/weborigin/KURL.h"
+#include "wtf/HashMap.h"
#include "wtf/ListHashSet.h"
#include "wtf/RefCounted.h"
#include "wtf/RefPtr.h"
@@ -32,7 +33,7 @@ namespace WebCore {
class ExceptionState;
class StyleSheetContents;
-enum CssTextFormattingFlags { QuoteCSSStringIfNeeded, AlwaysQuoteCSSString };
+enum CSSTextFormattingFlags { QuoteCSSStringIfNeeded, AlwaysQuoteCSSString };
// FIXME: The current CSSValue and subclasses should be turned into internal types (StyleValue).
// The few subtypes that are actually exposed in CSSOM can be seen in the cloneForCSSOM() function.
@@ -61,7 +62,7 @@ public:
Type cssValueType() const;
String cssText() const;
- void setCssText(const String&, ExceptionState&) { } // FIXME: Not implemented.
+ void setCSSText(const String&, ExceptionState&) { } // FIXME: Not implemented.
String serializeResolvingVariables(const HashMap<AtomicString, String>&) const;
bool isPrimitiveValue() const { return m_classType == PrimitiveClass; }
@@ -71,7 +72,9 @@ public:
bool isAspectRatioValue() const { return m_classType == AspectRatioClass; }
bool isBorderImageSliceValue() const { return m_classType == BorderImageSliceClass; }
+ bool isCanvasValue() const { return m_classType == CanvasClass; }
bool isCursorImageValue() const { return m_classType == CursorImageClass; }
+ bool isCrossfadeValue() const { return m_classType == CrossfadeClass; }
bool isFontFeatureValue() const { return m_classType == FontFeatureClass; }
bool isFontValue() const { return m_classType == FontClass; }
bool isFontFaceSrcValue() const { return m_classType == FontFaceSrcClass; }
@@ -83,22 +86,27 @@ public:
bool isImplicitInitialValue() const;
bool isInheritedValue() const { return m_classType == InheritedClass; }
bool isInitialValue() const { return m_classType == InitialClass; }
+ bool isLinearGradientValue() const { return m_classType == LinearGradientClass; }
+ bool isRadialGradientValue() const { return m_classType == RadialGradientClass; }
bool isReflectValue() const { return m_classType == ReflectClass; }
bool isShadowValue() const { return m_classType == ShadowClass; }
+ bool isTextCloneCSSValue() const { return m_isTextClone; }
bool isCubicBezierTimingFunctionValue() const { return m_classType == CubicBezierTimingFunctionClass; }
bool isStepsTimingFunctionValue() const { return m_classType == StepsTimingFunctionClass; }
- bool isCSSTransformValue() const { return m_classType == CSSTransformClass; }
- bool isCSSLineBoxContainValue() const { return m_classType == LineBoxContainClass; }
- bool isCalculationValue() const {return m_classType == CalculationClass; }
- bool isCSSFilterValue() const { return m_classType == CSSFilterClass; }
- bool isCSSArrayFunctionValue() const { return m_classType == CSSArrayFunctionValueClass; }
- bool isCSSMixFunctionValue() const { return m_classType == CSSMixFunctionValueClass; }
- bool isCSSShaderValue() const { return m_classType == CSSShaderClass; }
+ bool isTransformValue() const { return m_classType == CSSTransformClass; }
+ bool isLineBoxContainValue() const { return m_classType == LineBoxContainClass; }
+ bool isCalcValue() const {return m_classType == CalculationClass; }
+ bool isFilterValue() const { return m_classType == CSSFilterClass; }
+ bool isArrayFunctionValue() const { return m_classType == CSSArrayFunctionValueClass; }
+ bool isMixFunctionValue() const { return m_classType == CSSMixFunctionValueClass; }
+ bool isShaderValue() const { return m_classType == CSSShaderClass; }
bool isVariableValue() const { return m_classType == VariableClass; }
bool isGridTemplateValue() const { return m_classType == GridTemplateClass; }
bool isSVGColor() const { return m_classType == SVGColorClass || m_classType == SVGPaintClass; }
bool isSVGPaint() const { return m_classType == SVGPaintClass; }
- bool isCSSSVGDocumentValue() const { return m_classType == CSSSVGDocumentClass; }
+ bool isSVGDocumentValue() const { return m_classType == CSSSVGDocumentClass; }
+ bool isUnicodeRangeValue() const { return m_classType == UnicodeRangeClass; }
+ bool isGridLineNamesValue() const { return m_classType == GridLineNamesClass; }
bool isCSSOMSafe() const { return m_isCSSOMSafe; }
bool isSubtypeExposedToCSSOM() const
@@ -166,6 +174,7 @@ protected:
CSSArrayFunctionValueClass,
CSSMixFunctionValueClass,
CSSTransformClass,
+ GridLineNamesClass,
// Do not append non-list class types here.
};
@@ -237,6 +246,9 @@ inline bool compareCSSValuePtr(const RefPtr<CSSValueType>& first, const RefPtr<C
return first ? second && first->equals(*second) : !second;
}
+#define DEFINE_CSS_VALUE_TYPE_CASTS(thisType, predicate) \
+ DEFINE_TYPE_CASTS(thisType, CSSValue, value, value->predicate, value.predicate)
+
} // namespace WebCore
#endif // CSSValue_h
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSValue.idl b/chromium/third_party/WebKit/Source/core/css/CSSValue.idl
index 9ac1fc83c19..dfdacd3a828 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSValue.idl
+++ b/chromium/third_party/WebKit/Source/core/css/CSSValue.idl
@@ -19,9 +19,8 @@
*/
[
- CustomToV8,
-
- DependentLifetime
+ Custom=Wrap,
+ DependentLifetime,
] interface CSSValue {
// UnitTypes
@@ -30,7 +29,7 @@
const unsigned short CSS_VALUE_LIST = 2;
const unsigned short CSS_CUSTOM = 3;
- [TreatReturnedNullStringAs=Null, TreatNullAs=NullString, SetterRaisesException] attribute DOMString cssText;
+ [TreatReturnedNullStringAs=Null, TreatNullAs=NullString, RaisesException=Setter] attribute DOMString cssText;
readonly attribute unsigned short cssValueType;
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSValueKeywords.in b/chromium/third_party/WebKit/Source/core/css/CSSValueKeywords.in
index 6cb1b6f8e8d..c2c3a1b4765 100644..100755
--- a/chromium/third_party/WebKit/Source/core/css/CSSValueKeywords.in
+++ b/chromium/third_party/WebKit/Source/core/css/CSSValueKeywords.in
@@ -3,8 +3,8 @@
//
// The mode argument is used to limit the keyword to be used only for certain
-// CSSParserModes. Values that have the prefix -internal- are automatically
-// only for UASheetMode or CSSAttributeMode.
+// CSSParserModes. Values that have the prefix -internal- are only allowed by
+// CSSParserModes listed in allowInternalPropertyAndValue()
inherit
initial
@@ -229,6 +229,13 @@ justify
-webkit-center
-webkit-match-parent
//
+// CSS_PROP_TEXT_JUSTIFY:
+//
+//auto
+//none
+inter-word
+distribute
+//
// CSS_PROP_LIST_STYLE_POSITION:
//
outside
@@ -325,8 +332,6 @@ katakana-iroha
inline
block
list-item
-run-in
-compact
inline-block
table
inline-table
@@ -454,6 +459,7 @@ portrait
pre
pre-line
pre-wrap
+-internal-presence
relative
scroll
separate
@@ -717,6 +723,9 @@ content-box
padding
padding-box
+// CSS_SHAPES
+margin-box
+
//
// background-size
//
@@ -799,6 +808,7 @@ visibleStroke
painted
fill
stroke
+bounding-box
//all
//none
@@ -901,8 +911,8 @@ off
optimizeQuality
-webkit-optimize-contrast
-// -webkit-shape-inside
-// -webkit-shape-outside
+// shape-inside
+// shape-outside
nonzero
evenodd
outside-shape
@@ -964,6 +974,9 @@ luminosity
// object-fit
scale-down
+// column-fill
+balance
+
// overflow
-webkit-paged-x
-webkit-paged-y
@@ -996,3 +1009,11 @@ markers
// isolation
// auto
isolate
+
+// touch-action-delay
+// none
+script
+
+// touch-action
+pan-x
+pan-y
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSValueList.cpp b/chromium/third_party/WebKit/Source/core/css/CSSValueList.cpp
index 1a18bc93c44..e1505c2e504 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSValueList.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/CSSValueList.cpp
@@ -94,7 +94,7 @@ PassRefPtr<CSSValueList> CSSValueList::copy()
return newList.release();
}
-String CSSValueList::customCssText(CssTextFormattingFlags formattingFlag) const
+String CSSValueList::customCSSText(CSSTextFormattingFlags formattingFlag) const
{
StringBuilder result;
String separator;
@@ -117,7 +117,7 @@ String CSSValueList::customCssText(CssTextFormattingFlags formattingFlag) const
if (!result.isEmpty())
result.append(separator);
if (formattingFlag == AlwaysQuoteCSSString && m_values[i]->isPrimitiveValue())
- result.append(toCSSPrimitiveValue(m_values[i].get())->customCssText(AlwaysQuoteCSSString));
+ result.append(toCSSPrimitiveValue(m_values[i].get())->customCSSText(AlwaysQuoteCSSString));
else
result.append(m_values[i]->cssText());
}
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSValueList.h b/chromium/third_party/WebKit/Source/core/css/CSSValueList.h
index eee33ca4205..2f08014f190 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSValueList.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSValueList.h
@@ -59,7 +59,7 @@ public:
bool hasValue(CSSValue*) const;
PassRefPtr<CSSValueList> copy();
- String customCssText(CssTextFormattingFlags = QuoteCSSStringIfNeeded) const;
+ String customCSSText(CSSTextFormattingFlags = QuoteCSSStringIfNeeded) const;
bool equals(const CSSValueList&) const;
bool equals(const CSSValue&) const;
String customSerializeResolvingVariables(const HashMap<AtomicString, String>&) const;
@@ -81,20 +81,7 @@ private:
Vector<RefPtr<CSSValue>, 4> m_values;
};
-inline CSSValueList* toCSSValueList(CSSValue* value)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!value || value->isValueList());
- return static_cast<CSSValueList*>(value);
-}
-
-inline const CSSValueList* toCSSValueList(const CSSValue* value)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!value || value->isValueList());
- return static_cast<const CSSValueList*>(value);
-}
-
-// Catch unneeded cast.
-void toCSSValueList(const CSSValueList*);
+DEFINE_CSS_VALUE_TYPE_CASTS(CSSValueList, isValueList());
// Objects of this class are intended to be stack-allocated and scoped to a single function.
// Please take care not to pass these around as they do hold onto a raw pointer.
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSValuePool.cpp b/chromium/third_party/WebKit/Source/core/css/CSSValuePool.cpp
index eaf855509dc..4550915eba4 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSValuePool.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/CSSValuePool.cpp
@@ -26,9 +26,9 @@
#include "config.h"
#include "core/css/CSSValuePool.h"
-#include "CSSValueKeywords.h"
#include "core/css/CSSParser.h"
#include "core/css/CSSValueList.h"
+#include "core/rendering/style/RenderStyle.h"
namespace WebCore {
@@ -75,7 +75,7 @@ PassRefPtr<CSSPrimitiveValue> CSSValuePool::createColorValue(unsigned rgbValue)
return m_colorBlack;
// Just wipe out the cache and start rebuilding if it gets too big.
- const int maximumColorCacheSize = 512;
+ const unsigned maximumColorCacheSize = 512;
if (m_colorValueCache.size() > maximumColorCacheSize)
m_colorValueCache.clear();
@@ -115,6 +115,11 @@ PassRefPtr<CSSPrimitiveValue> CSSValuePool::createValue(double value, CSSPrimiti
return cache[intValue];
}
+PassRefPtr<CSSPrimitiveValue> CSSValuePool::createValue(const Length& value, const RenderStyle& style)
+{
+ return CSSPrimitiveValue::create(value, style.effectiveZoom());
+}
+
PassRefPtr<CSSPrimitiveValue> CSSValuePool::createFontFamilyValue(const String& familyName)
{
RefPtr<CSSPrimitiveValue>& value = m_fontFamilyValueCache.add(familyName, 0).iterator->value;
@@ -126,7 +131,7 @@ PassRefPtr<CSSPrimitiveValue> CSSValuePool::createFontFamilyValue(const String&
PassRefPtr<CSSValueList> CSSValuePool::createFontFaceValue(const AtomicString& string)
{
// Just wipe out the cache and start rebuilding if it gets too big.
- const int maximumFontFaceCacheSize = 128;
+ const unsigned maximumFontFaceCacheSize = 128;
if (m_fontFaceValueCache.size() > maximumFontFaceCacheSize)
m_fontFaceValueCache.clear();
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSValuePool.h b/chromium/third_party/WebKit/Source/core/css/CSSValuePool.h
index ba63c181e8c..75b8984a1f7 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSValuePool.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSValuePool.h
@@ -52,7 +52,8 @@ public:
PassRefPtr<CSSPrimitiveValue> createColorValue(unsigned rgbValue);
PassRefPtr<CSSPrimitiveValue> createValue(double value, CSSPrimitiveValue::UnitTypes);
PassRefPtr<CSSPrimitiveValue> createValue(const String& value, CSSPrimitiveValue::UnitTypes type) { return CSSPrimitiveValue::create(value, type); }
- PassRefPtr<CSSPrimitiveValue> createValue(const Length& value, const RenderStyle* style) { return CSSPrimitiveValue::create(value, style); }
+ PassRefPtr<CSSPrimitiveValue> createValue(const Length& value, const RenderStyle&);
+ PassRefPtr<CSSPrimitiveValue> createValue(const Length& value, float zoom) { return CSSPrimitiveValue::create(value, zoom); }
template<typename T> static PassRefPtr<CSSPrimitiveValue> createValue(T value) { return CSSPrimitiveValue::create(value); }
private:
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSValueTestHelper.h b/chromium/third_party/WebKit/Source/core/css/CSSValueTestHelper.h
new file mode 100644
index 00000000000..765ea3098bc
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/css/CSSValueTestHelper.h
@@ -0,0 +1,76 @@
+/*
+ * Copyright (c) 2013, Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * Make testing with gtest and gmock nicer by adding pretty print and other
+ * helper functions.
+ */
+
+#ifndef CSSValueTestHelper_h
+#define CSSValueTestHelper_h
+
+#include "core/css/CSSPrimitiveValue.h"
+#include "core/css/CSSValue.h"
+
+#include <iostream>
+
+namespace testing {
+namespace internal {
+
+// gtest tests won't compile with clang when trying to EXPECT_EQ a class that
+// has the "template<typename T> operator T*()" private.
+// (See https://code.google.com/p/googletest/issues/detail?id=442)
+//
+// Work around is to define this custom IsNullLiteralHelper.
+char(&IsNullLiteralHelper(const WebCore::CSSValue&))[2];
+
+}
+}
+
+namespace WebCore {
+
+inline bool operator==(const CSSValue& a, const CSSValue& b)
+{
+ return a.equals(b);
+}
+
+inline void PrintTo(const CSSValue& cssValue, ::std::ostream* os, const char* typeName = "CSSValue")
+{
+ *os << typeName << "(" << cssValue.cssText().utf8().data() << ")";
+}
+
+inline void PrintTo(const CSSPrimitiveValue& cssValue, ::std::ostream* os, const char* typeName = "CSSPrimitiveValue")
+{
+ PrintTo(*static_cast<const CSSValue*>(&cssValue), os, typeName);
+}
+
+}
+
+#endif
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSVariableValue.h b/chromium/third_party/WebKit/Source/core/css/CSSVariableValue.h
index 5e691e1ec56..525581ae19c 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSVariableValue.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSVariableValue.h
@@ -59,17 +59,7 @@ private:
const String m_value;
};
-inline CSSVariableValue* toCSSVariableValue(CSSValue* value)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!value || value->isVariableValue());
- return static_cast<CSSVariableValue*>(value);
-}
-
-inline const CSSVariableValue* toCSSVariableValue(const CSSValue* value)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!value || value->isVariableValue());
- return static_cast<const CSSVariableValue*>(value);
-}
+DEFINE_CSS_VALUE_TYPE_CASTS(CSSVariableValue, isVariableValue());
}
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSVariablesIterator.h b/chromium/third_party/WebKit/Source/core/css/CSSVariablesIterator.h
new file mode 100644
index 00000000000..edfe3a7e9ed
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/css/CSSVariablesIterator.h
@@ -0,0 +1,49 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef CSSVariablesIterator_h
+#define CSSVariablesIterator_h
+
+#include "wtf/RefCounted.h"
+
+namespace WebCore {
+
+class CSSVariablesIterator : public RefCounted<CSSVariablesIterator> {
+public:
+ virtual ~CSSVariablesIterator() { }
+ virtual void advance() = 0;
+ virtual bool atEnd() const = 0;
+ virtual AtomicString name() const = 0;
+ virtual String value() const = 0;
+ virtual void addedVariable(const AtomicString& name) { }
+ virtual void removedVariable(const AtomicString& name) { }
+ virtual void clearedVariables() { }
+};
+
+}
+
+#endif // CSSVariablesIterator_h
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSVariablesMap.cpp b/chromium/third_party/WebKit/Source/core/css/CSSVariablesMap.cpp
index 599a9dca639..eb6232dd43a 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSVariablesMap.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/CSSVariablesMap.cpp
@@ -29,7 +29,6 @@
#include "config.h"
#include "core/css/CSSVariablesMap.h"
-#include "bindings/v8/ExceptionState.h"
#include "core/css/CSSStyleDeclaration.h"
namespace WebCore {
@@ -55,23 +54,68 @@ bool CSSVariablesMap::has(const AtomicString& name) const
return false;
}
-void CSSVariablesMap::set(const AtomicString& name, const String& value, ExceptionState& es) const
+void CSSVariablesMap::set(const AtomicString& name, const String& value, ExceptionState& exceptionState)
{
- if (m_styleDeclaration)
- m_styleDeclaration->setVariableValue(name, value, es);
+ if (!m_styleDeclaration)
+ return;
+ if (m_styleDeclaration->setVariableValue(name, value, exceptionState)) {
+ Iterators::iterator end = m_activeIterators.end();
+ for (Iterators::iterator it = m_activeIterators.begin(); it != end; ++it)
+ (*it)->addedVariable(name);
+ }
}
-bool CSSVariablesMap::remove(const AtomicString& name) const
+bool CSSVariablesMap::remove(const AtomicString& name)
{
- if (m_styleDeclaration)
- return m_styleDeclaration->removeVariable(name);
+ if (!m_styleDeclaration)
+ return false;
+ if (m_styleDeclaration->removeVariable(name)) {
+ Iterators::iterator end = m_activeIterators.end();
+ for (Iterators::iterator it = m_activeIterators.begin(); it != end; ++it)
+ (*it)->removedVariable(name);
+ return true;
+ }
return false;
}
-void CSSVariablesMap::clear(ExceptionState& es) const
+void CSSVariablesMap::clear(ExceptionState& exceptionState)
{
- if (m_styleDeclaration)
- return m_styleDeclaration->clearVariables(es);
+ if (!m_styleDeclaration)
+ return;
+ if (m_styleDeclaration->clearVariables(exceptionState)) {
+ Iterators::iterator end = m_activeIterators.end();
+ for (Iterators::iterator it = m_activeIterators.begin(); it != end; ++it)
+ (*it)->clearedVariables();
+ }
+}
+
+void CSSVariablesMap::forEach(PassOwnPtr<CSSVariablesMapForEachCallback> callback, ScriptValue& thisArg) const
+{
+ forEach(callback, &thisArg);
+}
+
+void CSSVariablesMap::forEach(PassOwnPtr<CSSVariablesMapForEachCallback> callback) const
+{
+ forEach(callback, 0);
+}
+
+void CSSVariablesMap::forEach(PassOwnPtr<CSSVariablesMapForEachCallback> callback, ScriptValue* thisArg) const
+{
+ if (!m_styleDeclaration)
+ return;
+ RefPtr<CSSVariablesIterator> iterator = m_styleDeclaration->variablesIterator();
+ m_activeIterators.append(iterator.get());
+ while (!iterator->atEnd()) {
+ String name = iterator->name();
+ String value = iterator->value();
+ if (thisArg)
+ callback->handleItem(*thisArg, value, name, const_cast<CSSVariablesMap*>(this));
+ else
+ callback->handleItem(value, name, const_cast<CSSVariablesMap*>(this));
+ iterator->advance();
+ }
+ ASSERT(m_activeIterators.last() == iterator.get());
+ m_activeIterators.removeLast();
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSVariablesMap.h b/chromium/third_party/WebKit/Source/core/css/CSSVariablesMap.h
index 5c236953923..12b1bee2845 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSVariablesMap.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSVariablesMap.h
@@ -29,18 +29,19 @@
#define CSSVariablesMap_h
#include "RuntimeEnabledFeatures.h"
+#include "core/css/CSSVariablesMapForEachCallback.h"
+#include "wtf/PassOwnPtr.h"
#include "wtf/RefCounted.h"
#include "wtf/text/WTFString.h"
namespace WebCore {
class CSSStyleDeclaration;
+class CSSVariablesIterator;
class ExceptionState;
-class CSSVariablesMap : public RefCounted<CSSVariablesMap> {
+class CSSVariablesMap FINAL : public RefCounted<CSSVariablesMap> {
public:
- virtual ~CSSVariablesMap() { }
-
static PassRefPtr<CSSVariablesMap> create(CSSStyleDeclaration* styleDeclaration)
{
return adoptRef(new CSSVariablesMap(styleDeclaration));
@@ -49,9 +50,11 @@ public:
unsigned size() const;
String get(const AtomicString& name) const;
bool has(const AtomicString& name) const;
- void set(const AtomicString& name, const String& value, ExceptionState&) const;
- bool remove(const AtomicString& name) const;
- void clear(ExceptionState&) const;
+ void set(const AtomicString& name, const String& value, ExceptionState&);
+ bool remove(const AtomicString& name);
+ void clear(ExceptionState&);
+ void forEach(PassOwnPtr<CSSVariablesMapForEachCallback>, ScriptValue& thisArg) const;
+ void forEach(PassOwnPtr<CSSVariablesMapForEachCallback>) const;
void clearStyleDeclaration() { m_styleDeclaration = 0; }
@@ -62,7 +65,11 @@ private:
ASSERT(RuntimeEnabledFeatures::cssVariablesEnabled());
}
+ void forEach(PassOwnPtr<CSSVariablesMapForEachCallback>, ScriptValue* thisArg) const;
+
CSSStyleDeclaration* m_styleDeclaration;
+ typedef Vector<CSSVariablesIterator*> Iterators;
+ mutable Iterators m_activeIterators;
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSVariablesMap.idl b/chromium/third_party/WebKit/Source/core/css/CSSVariablesMap.idl
index b6ab78a0cb1..3c88025beb9 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSVariablesMap.idl
+++ b/chromium/third_party/WebKit/Source/core/css/CSSVariablesMap.idl
@@ -32,4 +32,5 @@ interface CSSVariablesMap {
[RaisesException] void set(DOMString name, DOMString value);
[ImplementedAs=remove] boolean delete(DOMString name);
[RaisesException] void clear();
+ void forEach(CSSVariablesMapForEachCallback callback, optional any thisArg);
};
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSVariablesMapForEachCallback.h b/chromium/third_party/WebKit/Source/core/css/CSSVariablesMapForEachCallback.h
new file mode 100644
index 00000000000..001ccbdcf74
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/css/CSSVariablesMapForEachCallback.h
@@ -0,0 +1,48 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef CSSVariablesMapForEachCallback_h
+#define CSSVariablesMapForEachCallback_h
+
+#include "bindings/v8/ScriptValue.h"
+#include "wtf/RefCounted.h"
+#include "wtf/text/WTFString.h"
+
+namespace WebCore {
+
+class CSSVariablesMap;
+
+class CSSVariablesMapForEachCallback {
+public:
+ virtual ~CSSVariablesMapForEachCallback() { }
+ virtual void handleItem(ScriptValue thisValue, const String& value, const String& name, CSSVariablesMap*) = 0;
+ virtual void handleItem(const String& value, const String& name, CSSVariablesMap*) = 0;
+};
+
+} // namespace WebCore
+
+#endif // CSSVariablesMapForEachCallback_h
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSVariablesMapForEachCallback.idl b/chromium/third_party/WebKit/Source/core/css/CSSVariablesMapForEachCallback.idl
new file mode 100644
index 00000000000..11a6cfcb581
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/css/CSSVariablesMapForEachCallback.idl
@@ -0,0 +1,31 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+callback interface CSSVariablesMapForEachCallback {
+ [CallWith=ThisValue] void handleItem(DOMString value, DOMString name, CSSVariablesMap map);
+ void handleItem(DOMString value, DOMString name, CSSVariablesMap map);
+};
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSViewportRule.cpp b/chromium/third_party/WebKit/Source/core/css/CSSViewportRule.cpp
index 6f6733864b3..a5d1f0e9cf9 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSViewportRule.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/CSSViewportRule.cpp
@@ -76,9 +76,7 @@ String CSSViewportRule::cssText() const
void CSSViewportRule::reattach(StyleRuleBase* rule)
{
ASSERT(rule);
- ASSERT_WITH_SECURITY_IMPLICATION(rule->isViewportRule());
- m_viewportRule = static_cast<StyleRuleViewport*>(rule);
-
+ m_viewportRule = toStyleRuleViewport(rule);
if (m_propertiesCSSOMWrapper)
m_propertiesCSSOMWrapper->reattach(m_viewportRule->mutableProperties());
}
diff --git a/chromium/third_party/WebKit/Source/core/css/CSSViewportRule.h b/chromium/third_party/WebKit/Source/core/css/CSSViewportRule.h
index 3cdd4dcc169..2ef8c81511f 100644
--- a/chromium/third_party/WebKit/Source/core/css/CSSViewportRule.h
+++ b/chromium/third_party/WebKit/Source/core/css/CSSViewportRule.h
@@ -60,6 +60,8 @@ private:
mutable RefPtr<StyleRuleCSSStyleDeclaration> m_propertiesCSSOMWrapper;
};
+DEFINE_CSS_RULE_TYPE_CASTS(CSSViewportRule, VIEWPORT_RULE);
+
} // namespace WebCore
#endif // CSSViewportRule_h
diff --git a/chromium/third_party/WebKit/Source/core/css/DOMWindowCSS.cpp b/chromium/third_party/WebKit/Source/core/css/DOMWindowCSS.cpp
index b417c4ab993..248ddcc4648 100644
--- a/chromium/third_party/WebKit/Source/core/css/DOMWindowCSS.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/DOMWindowCSS.cpp
@@ -31,8 +31,8 @@
#include "core/css/DOMWindowCSS.h"
#include "core/css/CSSParser.h"
+#include "core/css/RuntimeCSSEnabled.h"
#include "core/css/StylePropertySet.h"
-#include "core/page/RuntimeCSSEnabled.h"
#include "wtf/text/WTFString.h"
namespace WebCore {
@@ -75,12 +75,12 @@ bool DOMWindowCSS::supports(const String& property, const String& value) const
return false;
RefPtr<MutableStylePropertySet> dummyStyle = MutableStylePropertySet::create();
- return CSSParser::parseValue(dummyStyle.get(), propertyID, normalizedValue, false, CSSStrictMode, 0);
+ return CSSParser::parseValue(dummyStyle.get(), propertyID, normalizedValue, false, HTMLStandardMode, 0);
}
bool DOMWindowCSS::supports(const String& conditionText) const
{
- CSSParserContext context(CSSStrictMode);
+ CSSParserContext context(HTMLStandardMode);
CSSParser parser(context);
return parser.parseSupportsCondition(conditionText);
}
diff --git a/chromium/third_party/WebKit/Source/core/css/DocumentFontFaceSet.cpp b/chromium/third_party/WebKit/Source/core/css/DocumentFontFaceSet.cpp
new file mode 100644
index 00000000000..408668f70fc
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/css/DocumentFontFaceSet.cpp
@@ -0,0 +1,38 @@
+/*
+ * Copyright (C) 2013, Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
+ * DAMAGE.
+ */
+
+#include "config.h"
+#include "core/css/DocumentFontFaceSet.h"
+
+#include "core/css/FontFaceSet.h"
+
+namespace WebCore {
+
+PassRefPtr<FontFaceSet> DocumentFontFaceSet::fonts(Document* document)
+{
+ return FontFaceSet::from(document);
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/css/DocumentFontFaceSet.h b/chromium/third_party/WebKit/Source/core/css/DocumentFontFaceSet.h
new file mode 100644
index 00000000000..910d878291e
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/css/DocumentFontFaceSet.h
@@ -0,0 +1,43 @@
+/*
+ * Copyright (C) 2013, Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
+ * DAMAGE.
+ */
+
+#ifndef DocumentFontFaceSet_h
+#define DocumentFontFaceSet_h
+
+#include "wtf/PassRefPtr.h"
+
+namespace WebCore {
+
+class Document;
+class FontFaceSet;
+
+class DocumentFontFaceSet {
+public:
+ static PassRefPtr<FontFaceSet> fonts(Document*);
+};
+
+} // namespace WebCore
+
+#endif // DocumentFontFaceSet_h
diff --git a/chromium/third_party/WebKit/Source/core/css/DocumentFontFaceSet.idl b/chromium/third_party/WebKit/Source/core/css/DocumentFontFaceSet.idl
new file mode 100644
index 00000000000..820fdc899e9
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/css/DocumentFontFaceSet.idl
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+partial interface Document {
+ [RuntimeEnabled=FontLoadEvents] readonly attribute FontFaceSet fonts;
+};
diff --git a/chromium/third_party/WebKit/Source/core/css/DocumentRuleSets.cpp b/chromium/third_party/WebKit/Source/core/css/DocumentRuleSets.cpp
deleted file mode 100644
index 298d23d7eb4..00000000000
--- a/chromium/third_party/WebKit/Source/core/css/DocumentRuleSets.cpp
+++ /dev/null
@@ -1,118 +0,0 @@
-/*
- * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
- * (C) 2004-2005 Allan Sandfeld Jensen (kde@carewolf.com)
- * Copyright (C) 2006, 2007 Nicholas Shanks (webkit@nickshanks.com)
- * Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 Apple Inc. All rights reserved.
- * Copyright (C) 2007 Alexey Proskuryakov <ap@webkit.org>
- * Copyright (C) 2007, 2008 Eric Seidel <eric@webkit.org>
- * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
- * Copyright (c) 2011, Code Aurora Forum. All rights reserved.
- * Copyright (C) Research In Motion Limited 2011. All rights reserved.
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-#include "core/css/DocumentRuleSets.h"
-
-#include "core/css/CSSDefaultStyleSheets.h"
-#include "core/css/CSSStyleSheet.h"
-#include "core/css/StyleSheetContents.h"
-#include "core/css/resolver/MatchRequest.h"
-#include "core/css/resolver/StyleResolver.h"
-#include "core/dom/StyleEngine.h"
-
-namespace WebCore {
-
-void ShadowDistributedRules::addRule(StyleRule* rule, size_t selectorIndex, ContainerNode* scopingNode, AddRuleFlags addRuleFlags)
-{
- if (m_shadowDistributedRuleSetMap.contains(scopingNode))
- m_shadowDistributedRuleSetMap.get(scopingNode)->addRule(rule, selectorIndex, addRuleFlags);
- else {
- OwnPtr<RuleSet> ruleSetForScope = RuleSet::create();
- ruleSetForScope->addRule(rule, selectorIndex, addRuleFlags);
- m_shadowDistributedRuleSetMap.add(scopingNode, ruleSetForScope.release());
- }
-}
-
-void ShadowDistributedRules::collectMatchRequests(bool includeEmptyRules, Vector<MatchRequest>& matchRequests)
-{
- for (ShadowDistributedRuleSetMap::iterator it = m_shadowDistributedRuleSetMap.begin(); it != m_shadowDistributedRuleSetMap.end(); ++it)
- matchRequests.append(MatchRequest(it->value.get(), includeEmptyRules, it->key));
-}
-
-void ShadowDistributedRules::reset(const ContainerNode* scopingNode)
-{
- m_shadowDistributedRuleSetMap.remove(scopingNode);
-}
-
-void ShadowDistributedRules::collectFeaturesTo(RuleFeatureSet& features)
-{
- for (ShadowDistributedRuleSetMap::iterator it = m_shadowDistributedRuleSetMap.begin(); it != m_shadowDistributedRuleSetMap.end(); ++it)
- features.add(it->value->features());
-}
-
-DocumentRuleSets::DocumentRuleSets()
-{
-}
-
-DocumentRuleSets::~DocumentRuleSets()
-{
-}
-
-void DocumentRuleSets::initUserStyle(StyleEngine* styleSheetCollection, const MediaQueryEvaluator& medium, StyleResolver& resolver)
-{
- OwnPtr<RuleSet> tempUserStyle = RuleSet::create();
- if (CSSStyleSheet* pageUserSheet = styleSheetCollection->pageUserSheet())
- tempUserStyle->addRulesFromSheet(pageUserSheet->contents(), medium, &resolver);
- collectRulesFromUserStyleSheets(styleSheetCollection->injectedUserStyleSheets(), *tempUserStyle, medium, resolver);
- collectRulesFromUserStyleSheets(styleSheetCollection->documentUserStyleSheets(), *tempUserStyle, medium, resolver);
- if (tempUserStyle->ruleCount() > 0 || tempUserStyle->pageRules().size() > 0)
- m_userStyle = tempUserStyle.release();
-}
-
-void DocumentRuleSets::collectRulesFromUserStyleSheets(const Vector<RefPtr<CSSStyleSheet> >& userSheets, RuleSet& userStyle, const MediaQueryEvaluator& medium, StyleResolver& resolver)
-{
- for (unsigned i = 0; i < userSheets.size(); ++i) {
- ASSERT(userSheets[i]->contents()->isUserStyleSheet());
- userStyle.addRulesFromSheet(userSheets[i]->contents(), medium, &resolver);
- }
-}
-
-void DocumentRuleSets::resetAuthorStyle()
-{
- m_shadowDistributedRules.clear();
-}
-
-void DocumentRuleSets::collectFeaturesTo(RuleFeatureSet& features, bool isViewSource)
-{
- // Collect all ids and rules using sibling selectors (:first-child and similar)
- // in the current set of stylesheets. Style sharing code uses this information to reject
- // sharing candidates.
- if (CSSDefaultStyleSheets::defaultStyle)
- features.add(CSSDefaultStyleSheets::defaultStyle->features());
-
- if (isViewSource)
- features.add(CSSDefaultStyleSheets::viewSourceStyle()->features());
-
- if (m_userStyle)
- features.add(m_userStyle->features());
-
- m_shadowDistributedRules.collectFeaturesTo(features);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/css/DocumentRuleSets.h b/chromium/third_party/WebKit/Source/core/css/DocumentRuleSets.h
deleted file mode 100644
index 4434ec56a70..00000000000
--- a/chromium/third_party/WebKit/Source/core/css/DocumentRuleSets.h
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
- * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#ifndef DocumentRuleSets_h
-#define DocumentRuleSets_h
-
-#include "core/css/RuleFeature.h"
-#include "core/css/RuleSet.h"
-
-#include "wtf/OwnPtr.h"
-#include "wtf/RefPtr.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-class CSSStyleRule;
-class CSSStyleSheet;
-class InspectorCSSOMWrappers;
-class MatchRequest;
-class MediaQueryEvaluator;
-class RuleSet;
-class StyleEngine;
-
-class ShadowDistributedRules {
-public:
- void addRule(StyleRule*, size_t selectorIndex, ContainerNode* scopingNode, AddRuleFlags);
- void collectMatchRequests(bool includeEmptyRules, Vector<MatchRequest>&);
- void clear() { m_shadowDistributedRuleSetMap.clear(); }
- void reset(const ContainerNode* scopingNode);
- bool isEmpty() const { return m_shadowDistributedRuleSetMap.isEmpty(); }
- void collectFeaturesTo(RuleFeatureSet&);
-
-private:
- typedef HashMap<const ContainerNode*, OwnPtr<RuleSet> > ShadowDistributedRuleSetMap;
- ShadowDistributedRuleSetMap m_shadowDistributedRuleSetMap;
-};
-
-class DocumentRuleSets {
-public:
- DocumentRuleSets();
- ~DocumentRuleSets();
- RuleSet* userStyle() const { return m_userStyle.get(); }
-
- void initUserStyle(StyleEngine*, const MediaQueryEvaluator&, StyleResolver&);
- void resetAuthorStyle();
- void collectFeaturesTo(RuleFeatureSet&, bool isViewSource);
-
- ShadowDistributedRules& shadowDistributedRules() { return m_shadowDistributedRules; }
-
-private:
- void collectRulesFromUserStyleSheets(const Vector<RefPtr<CSSStyleSheet> >&, RuleSet& userStyle, const MediaQueryEvaluator&, StyleResolver&);
- OwnPtr<RuleSet> m_userStyle;
- ShadowDistributedRules m_shadowDistributedRules;
-};
-
-} // namespace WebCore
-
-#endif // DocumentRuleSets_h
diff --git a/chromium/third_party/WebKit/Source/core/css/ElementRuleCollector.cpp b/chromium/third_party/WebKit/Source/core/css/ElementRuleCollector.cpp
index 5ccfc77f504..4fdd44c8eb4 100644
--- a/chromium/third_party/WebKit/Source/core/css/ElementRuleCollector.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/ElementRuleCollector.cpp
@@ -31,6 +31,8 @@
#include "core/css/CSSRuleList.h"
#include "core/css/CSSSelector.h"
+#include "core/css/CSSStyleRule.h"
+#include "core/css/CSSStyleSheet.h"
#include "core/css/SelectorCheckerFastPath.h"
#include "core/css/SiblingTraversalStrategies.h"
#include "core/css/StylePropertySet.h"
@@ -41,35 +43,45 @@
namespace WebCore {
ElementRuleCollector::ElementRuleCollector(const ElementResolveContext& context,
- const SelectorFilter& filter, RenderStyle* style)
+ const SelectorFilter& filter, RenderStyle* style, ShouldIncludeStyleSheetInCSSOMWrapper includeStyleSheet)
: m_context(context)
, m_selectorFilter(filter)
, m_style(style)
, m_regionForStyling(0)
, m_pseudoStyleRequest(NOPSEUDO)
, m_mode(SelectorChecker::ResolvingStyle)
- , m_behaviorAtBoundary(SelectorChecker::DoesNotCrossBoundary)
, m_canUseFastReject(m_selectorFilter.parentStackIsConsistent(context.parentNode()))
, m_sameOriginOnly(false)
, m_matchingUARules(false)
+ , m_includeStyleSheet(includeStyleSheet)
{ }
+ElementRuleCollector::~ElementRuleCollector()
+{
+}
+
MatchResult& ElementRuleCollector::matchedResult()
{
return m_result;
}
-PassRefPtr<CSSRuleList> ElementRuleCollector::matchedRuleList()
+PassRefPtr<StyleRuleList> ElementRuleCollector::matchedStyleRuleList()
{
- ASSERT(m_mode == SelectorChecker::CollectingRules);
- return m_ruleList.release();
+ ASSERT(m_mode == SelectorChecker::CollectingStyleRules);
+ return m_styleRuleList.release();
}
-inline void ElementRuleCollector::addMatchedRule(const RuleData* rule, CascadeScope cascadeScope, CascadeOrder cascadeOrder)
+PassRefPtr<CSSRuleList> ElementRuleCollector::matchedCSSRuleList()
+{
+ ASSERT(m_mode == SelectorChecker::CollectingCSSRules);
+ return m_cssRuleList.release();
+}
+
+inline void ElementRuleCollector::addMatchedRule(const RuleData* rule, unsigned specificity, CascadeScope cascadeScope, CascadeOrder cascadeOrder, unsigned styleSheetIndex)
{
if (!m_matchedRules)
m_matchedRules = adoptPtr(new Vector<MatchedRule, 32>);
- m_matchedRules->append(MatchedRule(rule, cascadeScope, cascadeOrder));
+ m_matchedRules->append(MatchedRule(rule, specificity, cascadeScope, cascadeOrder, styleSheetIndex));
}
void ElementRuleCollector::clearMatchedRules()
@@ -79,11 +91,18 @@ void ElementRuleCollector::clearMatchedRules()
m_matchedRules->clear();
}
+inline StyleRuleList* ElementRuleCollector::ensureStyleRuleList()
+{
+ if (!m_styleRuleList)
+ m_styleRuleList = StyleRuleList::create();
+ return m_styleRuleList.get();
+}
+
inline StaticCSSRuleList* ElementRuleCollector::ensureRuleList()
{
- if (!m_ruleList)
- m_ruleList = StaticCSSRuleList::create();
- return m_ruleList.get();
+ if (!m_cssRuleList)
+ m_cssRuleList = StaticCSSRuleList::create();
+ return m_cssRuleList.get();
}
void ElementRuleCollector::addElementStyleProperties(const StylePropertySet* propertySet, bool isCacheable)
@@ -107,7 +126,7 @@ static bool rulesApplicableInCurrentTreeScope(const Element* element, const Cont
if (elementApplyAuthorStyles)
return true;
// c) the rules comes from a scoped style sheet within the same tree scope
- if (!scopingNode || &treeScope == &scopingNode->treeScope())
+ if (!scopingNode || treeScope == scopingNode->treeScope())
return true;
// d) the rules comes from a scoped style sheet within an active shadow root whose host is the given element
if (element->isInShadowTree() && (behaviorAtBoundary & SelectorChecker::ScopeIsShadowHost) && scopingNode == element->containingShadowRoot()->host())
@@ -118,20 +137,20 @@ static bool rulesApplicableInCurrentTreeScope(const Element* element, const Cont
return false;
}
-void ElementRuleCollector::collectMatchingRules(const MatchRequest& matchRequest, RuleRange& ruleRange, CascadeScope cascadeScope, CascadeOrder cascadeOrder)
+void ElementRuleCollector::collectMatchingRules(const MatchRequest& matchRequest, RuleRange& ruleRange, SelectorChecker::BehaviorAtBoundary behaviorAtBoundary, CascadeScope cascadeScope, CascadeOrder cascadeOrder)
{
ASSERT(matchRequest.ruleSet);
ASSERT(m_context.element());
- Element* element = m_context.element();
- const AtomicString& pseudoId = element->shadowPseudoId();
+ Element& element = *m_context.element();
+ const AtomicString& pseudoId = element.shadowPseudoId();
if (!pseudoId.isEmpty()) {
- ASSERT(element->isStyledElement());
- collectMatchingRulesForList(matchRequest.ruleSet->shadowPseudoElementRules(pseudoId.impl()), ignoreCascadeScope, cascadeOrder, matchRequest, ruleRange);
+ ASSERT(element.isStyledElement());
+ collectMatchingRulesForList(matchRequest.ruleSet->shadowPseudoElementRules(pseudoId.impl()), behaviorAtBoundary, ignoreCascadeScope, cascadeOrder, matchRequest, ruleRange);
}
- if (element->isWebVTTElement())
- collectMatchingRulesForList(matchRequest.ruleSet->cuePseudoRules(), cascadeScope, cascadeOrder, matchRequest, ruleRange);
+ if (element.isVTTElement())
+ collectMatchingRulesForList(matchRequest.ruleSet->cuePseudoRules(), behaviorAtBoundary, cascadeScope, cascadeOrder, matchRequest, ruleRange);
// Check whether other types of rules are applicable in the current tree scope. Criteria for this:
// a) it's a UA rule
// b) the tree scope allows author rules
@@ -139,27 +158,27 @@ void ElementRuleCollector::collectMatchingRules(const MatchRequest& matchRequest
// d) the rules comes from a scoped style sheet within an active shadow root whose host is the given element
// e) the rules can cross boundaries
// b)-e) is checked in rulesApplicableInCurrentTreeScope.
- if (!m_matchingUARules && !rulesApplicableInCurrentTreeScope(element, matchRequest.scope, m_behaviorAtBoundary, matchRequest.elementApplyAuthorStyles))
+ if (!m_matchingUARules && !rulesApplicableInCurrentTreeScope(&element, matchRequest.scope, behaviorAtBoundary, matchRequest.elementApplyAuthorStyles))
return;
// We need to collect the rules for id, class, tag, and everything else into a buffer and
// then sort the buffer.
- if (element->hasID())
- collectMatchingRulesForList(matchRequest.ruleSet->idRules(element->idForStyleResolution().impl()), cascadeScope, cascadeOrder, matchRequest, ruleRange);
- if (element->isStyledElement() && element->hasClass()) {
- for (size_t i = 0; i < element->classNames().size(); ++i)
- collectMatchingRulesForList(matchRequest.ruleSet->classRules(element->classNames()[i].impl()), cascadeScope, cascadeOrder, matchRequest, ruleRange);
+ if (element.hasID())
+ collectMatchingRulesForList(matchRequest.ruleSet->idRules(element.idForStyleResolution().impl()), behaviorAtBoundary, cascadeScope, cascadeOrder, matchRequest, ruleRange);
+ if (element.isStyledElement() && element.hasClass()) {
+ for (size_t i = 0; i < element.classNames().size(); ++i)
+ collectMatchingRulesForList(matchRequest.ruleSet->classRules(element.classNames()[i].impl()), behaviorAtBoundary, cascadeScope, cascadeOrder, matchRequest, ruleRange);
}
- if (element->isLink())
- collectMatchingRulesForList(matchRequest.ruleSet->linkPseudoClassRules(), cascadeScope, cascadeOrder, matchRequest, ruleRange);
+ if (element.isLink())
+ collectMatchingRulesForList(matchRequest.ruleSet->linkPseudoClassRules(), behaviorAtBoundary, cascadeScope, cascadeOrder, matchRequest, ruleRange);
if (SelectorChecker::matchesFocusPseudoClass(element))
- collectMatchingRulesForList(matchRequest.ruleSet->focusPseudoClassRules(), cascadeScope, cascadeOrder, matchRequest, ruleRange);
- collectMatchingRulesForList(matchRequest.ruleSet->tagRules(element->localName().impl()), cascadeScope, cascadeOrder, matchRequest, ruleRange);
- collectMatchingRulesForList(matchRequest.ruleSet->universalRules(), cascadeScope, cascadeOrder, matchRequest, ruleRange);
+ collectMatchingRulesForList(matchRequest.ruleSet->focusPseudoClassRules(), behaviorAtBoundary, cascadeScope, cascadeOrder, matchRequest, ruleRange);
+ collectMatchingRulesForList(matchRequest.ruleSet->tagRules(element.localName().impl()), behaviorAtBoundary, cascadeScope, cascadeOrder, matchRequest, ruleRange);
+ collectMatchingRulesForList(matchRequest.ruleSet->universalRules(), behaviorAtBoundary, cascadeScope, cascadeOrder, matchRequest, ruleRange);
}
-void ElementRuleCollector::collectMatchingRulesForRegion(const MatchRequest& matchRequest, RuleRange& ruleRange, CascadeScope cascadeScope, CascadeOrder cascadeOrder)
+void ElementRuleCollector::collectMatchingRulesForRegion(const MatchRequest& matchRequest, RuleRange& ruleRange, SelectorChecker::BehaviorAtBoundary behaviorAtBoundary, CascadeScope cascadeScope, CascadeOrder cascadeOrder)
{
if (!m_regionForStyling)
return;
@@ -167,12 +186,44 @@ void ElementRuleCollector::collectMatchingRulesForRegion(const MatchRequest& mat
unsigned size = matchRequest.ruleSet->m_regionSelectorsAndRuleSets.size();
for (unsigned i = 0; i < size; ++i) {
const CSSSelector* regionSelector = matchRequest.ruleSet->m_regionSelectorsAndRuleSets.at(i).selector;
- if (checkRegionSelector(regionSelector, toElement(m_regionForStyling->node()))) {
+ if (checkRegionSelector(regionSelector, toElement(m_regionForStyling->nodeForRegion()))) {
RuleSet* regionRules = matchRequest.ruleSet->m_regionSelectorsAndRuleSets.at(i).ruleSet.get();
ASSERT(regionRules);
- collectMatchingRules(MatchRequest(regionRules, matchRequest.includeEmptyRules, matchRequest.scope), ruleRange, cascadeScope, cascadeOrder);
+ collectMatchingRules(MatchRequest(regionRules, matchRequest.includeEmptyRules, matchRequest.scope), ruleRange, behaviorAtBoundary, cascadeScope, cascadeOrder);
+ }
+ }
+}
+
+
+static CSSStyleSheet* findStyleSheet(StyleEngine* styleEngine, StyleRule* rule)
+{
+ // FIXME: StyleEngine has a bunch of different accessors for StyleSheet lists, is this the only one we need to care about?
+ const Vector<RefPtr<CSSStyleSheet> >& stylesheets = styleEngine->activeAuthorStyleSheets();
+ for (size_t i = 0; i < stylesheets.size(); ++i) {
+ CSSStyleSheet* sheet = stylesheets[i].get();
+ for (unsigned j = 0; j < sheet->length(); ++j) {
+ CSSRule* cssRule = sheet->item(j);
+ if (cssRule->type() != CSSRule::STYLE_RULE)
+ continue;
+ CSSStyleRule* cssStyleRule = toCSSStyleRule(cssRule);
+ if (cssStyleRule->styleRule() == rule)
+ return sheet;
}
}
+ return 0;
+}
+
+void ElementRuleCollector::appendCSSOMWrapperForRule(StyleRule* rule)
+{
+ // FIXME: There should be no codepath that creates a CSSOMWrapper without a parent stylesheet or rule because
+ // then that codepath can lead to the CSSStyleSheet contents not getting correctly copied when the rule is modified
+ // through the wrapper (e.g. rule.selectorText="div"). Right now, the inspector uses the pointers for identity though,
+ // so calling CSSStyleSheet->willMutateRules breaks the inspector.
+ CSSStyleSheet* sheet = m_includeStyleSheet == IncludeStyleSheetInCSSOMWrapper ? findStyleSheet(m_context.element()->document().styleEngine(), rule) : 0;
+ RefPtr<CSSRule> cssRule = rule->createCSSOMWrapper(sheet);
+ if (sheet)
+ sheet->registerExtraChildRuleCSSOMWrapper(cssRule);
+ ensureRuleList()->rules().append(cssRule);
}
void ElementRuleCollector::sortAndTransferMatchedRules()
@@ -183,9 +234,15 @@ void ElementRuleCollector::sortAndTransferMatchedRules()
sortMatchedRules();
Vector<MatchedRule, 32>& matchedRules = *m_matchedRules;
- if (m_mode == SelectorChecker::CollectingRules) {
+ if (m_mode == SelectorChecker::CollectingStyleRules) {
for (unsigned i = 0; i < matchedRules.size(); ++i)
- ensureRuleList()->rules().append(matchedRules[i].ruleData()->rule()->createCSSOMWrapper());
+ ensureStyleRuleList()->m_list.append(matchedRules[i].ruleData()->rule());
+ return;
+ }
+
+ if (m_mode == SelectorChecker::CollectingCSSRules) {
+ for (unsigned i = 0; i < matchedRules.size(); ++i)
+ appendCSSOMWrapperForRule(matchedRules[i].ruleData()->rule());
return;
}
@@ -199,21 +256,24 @@ void ElementRuleCollector::sortAndTransferMatchedRules()
}
}
-inline bool ElementRuleCollector::ruleMatches(const RuleData& ruleData, const ContainerNode* scope, PseudoId& dynamicPseudo)
+inline bool ElementRuleCollector::ruleMatches(const RuleData& ruleData, const ContainerNode* scope, SelectorChecker::BehaviorAtBoundary behaviorAtBoundary, SelectorChecker::MatchResult* result)
{
- if (ruleData.hasFastCheckableSelector()) {
+ // Scoped rules can't match because the fast path uses a pool of tag/class/ids, collected from
+ // elements in that tree and those will never match the host, since it's in a different pool.
+ if (ruleData.hasFastCheckableSelector() && !scope) {
// We know this selector does not include any pseudo elements.
if (m_pseudoStyleRequest.pseudoId != NOPSEUDO)
return false;
// We know a sufficiently simple single part selector matches simply because we found it from the rule hash.
// This is limited to HTML only so we don't need to check the namespace.
+ ASSERT(m_context.element());
if (ruleData.hasRightmostSelectorMatchingHTMLBasedOnRuleHash() && m_context.element()->isHTMLElement()) {
if (!ruleData.hasMultipartSelector())
return true;
}
- if (ruleData.selector()->m_match == CSSSelector::Tag && !SelectorChecker::tagMatches(m_context.element(), ruleData.selector()->tagQName()))
+ if (ruleData.selector()->m_match == CSSSelector::Tag && !SelectorChecker::tagMatches(*m_context.element(), ruleData.selector()->tagQName()))
return false;
- SelectorCheckerFastPath selectorCheckerFastPath(ruleData.selector(), m_context.element());
+ SelectorCheckerFastPath selectorCheckerFastPath(ruleData.selector(), *m_context.element());
if (!selectorCheckerFastPath.matchesRightmostAttributeSelector())
return false;
@@ -221,30 +281,30 @@ inline bool ElementRuleCollector::ruleMatches(const RuleData& ruleData, const Co
}
// Slow path.
- SelectorChecker selectorChecker(document(), m_mode);
+ SelectorChecker selectorChecker(m_context.element()->document(), m_mode);
SelectorChecker::SelectorCheckingContext context(ruleData.selector(), m_context.element(), SelectorChecker::VisitedMatchEnabled);
context.elementStyle = m_style.get();
context.scope = scope;
context.pseudoId = m_pseudoStyleRequest.pseudoId;
context.scrollbar = m_pseudoStyleRequest.scrollbar;
context.scrollbarPart = m_pseudoStyleRequest.scrollbarPart;
- context.behaviorAtBoundary = m_behaviorAtBoundary;
- SelectorChecker::Match match = selectorChecker.match(context, dynamicPseudo, DOMSiblingTraversalStrategy());
+ context.behaviorAtBoundary = behaviorAtBoundary;
+ SelectorChecker::Match match = selectorChecker.match(context, DOMSiblingTraversalStrategy(), result);
if (match != SelectorChecker::SelectorMatches)
return false;
- if (m_pseudoStyleRequest.pseudoId != NOPSEUDO && m_pseudoStyleRequest.pseudoId != dynamicPseudo)
+ if (m_pseudoStyleRequest.pseudoId != NOPSEUDO && m_pseudoStyleRequest.pseudoId != result->dynamicPseudo)
return false;
return true;
}
-void ElementRuleCollector::collectRuleIfMatches(const RuleData& ruleData, CascadeScope cascadeScope, CascadeOrder cascadeOrder, const MatchRequest& matchRequest, RuleRange& ruleRange)
+void ElementRuleCollector::collectRuleIfMatches(const RuleData& ruleData, SelectorChecker::BehaviorAtBoundary behaviorAtBoundary, CascadeScope cascadeScope, CascadeOrder cascadeOrder, const MatchRequest& matchRequest, RuleRange& ruleRange)
{
if (m_canUseFastReject && m_selectorFilter.fastRejectSelector<RuleData::maximumIdentifierCount>(ruleData.descendantSelectorIdentifierHashes()))
return;
StyleRule* rule = ruleData.rule();
- PseudoId dynamicPseudo = NOPSEUDO;
- if (ruleMatches(ruleData, matchRequest.scope, dynamicPseudo)) {
+ SelectorChecker::MatchResult result;
+ if (ruleMatches(ruleData, matchRequest.scope, behaviorAtBoundary, &result)) {
// If the rule has no properties to apply, then ignore it in the non-debug mode.
const StylePropertySet* properties = rule->properties();
if (!properties || (properties->isEmpty() && !matchRequest.includeEmptyRules))
@@ -252,13 +312,15 @@ void ElementRuleCollector::collectRuleIfMatches(const RuleData& ruleData, Cascad
// FIXME: Exposing the non-standard getMatchedCSSRules API to web is the only reason this is needed.
if (m_sameOriginOnly && !ruleData.hasDocumentSecurityOrigin())
return;
+
+ PseudoId dynamicPseudo = result.dynamicPseudo;
// If we're matching normal rules, set a pseudo bit if
// we really just matched a pseudo-element.
if (dynamicPseudo != NOPSEUDO && m_pseudoStyleRequest.pseudoId == NOPSEUDO) {
- if (m_mode == SelectorChecker::CollectingRules)
+ if (m_mode == SelectorChecker::CollectingCSSRules || m_mode == SelectorChecker::CollectingStyleRules)
return;
// FIXME: Matching should not modify the style directly.
- if (dynamicPseudo < FIRST_INTERNAL_PSEUDOID)
+ if (m_style && dynamicPseudo < FIRST_INTERNAL_PSEUDOID)
m_style->setHasPseudoStyle(dynamicPseudo);
} else {
// Update our first/last rule indices in the matched rules array.
@@ -267,37 +329,44 @@ void ElementRuleCollector::collectRuleIfMatches(const RuleData& ruleData, Cascad
ruleRange.firstRuleIndex = ruleRange.lastRuleIndex;
// Add this rule to our list of matched rules.
- addMatchedRule(&ruleData, cascadeScope, cascadeOrder);
+ addMatchedRule(&ruleData, result.specificity, cascadeScope, cascadeOrder, matchRequest.styleSheetIndex);
return;
}
}
}
-void ElementRuleCollector::collectMatchingRulesForList(const RuleData* rules, CascadeScope cascadeScope, CascadeOrder cascadeOrder, const MatchRequest& matchRequest, RuleRange& ruleRange)
+void ElementRuleCollector::collectMatchingRulesForList(const RuleData* rules, SelectorChecker::BehaviorAtBoundary behaviorAtBoundary, CascadeScope cascadeScope, CascadeOrder cascadeOrder, const MatchRequest& matchRequest, RuleRange& ruleRange)
{
if (!rules)
return;
while (!rules->isLastInArray())
- collectRuleIfMatches(*rules++, cascadeScope, cascadeOrder, matchRequest, ruleRange);
- collectRuleIfMatches(*rules, cascadeScope, cascadeOrder, matchRequest, ruleRange);
+ collectRuleIfMatches(*rules++, behaviorAtBoundary, cascadeScope, cascadeOrder, matchRequest, ruleRange);
+ collectRuleIfMatches(*rules, behaviorAtBoundary, cascadeScope, cascadeOrder, matchRequest, ruleRange);
}
-void ElementRuleCollector::collectMatchingRulesForList(const Vector<RuleData>* rules, CascadeScope cascadeScope, CascadeOrder cascadeOrder, const MatchRequest& matchRequest, RuleRange& ruleRange)
+void ElementRuleCollector::collectMatchingRulesForList(const Vector<RuleData>* rules, SelectorChecker::BehaviorAtBoundary behaviorAtBoundary, CascadeScope cascadeScope, CascadeOrder cascadeOrder, const MatchRequest& matchRequest, RuleRange& ruleRange)
{
if (!rules)
return;
unsigned size = rules->size();
for (unsigned i = 0; i < size; ++i)
- collectRuleIfMatches(rules->at(i), cascadeScope, cascadeOrder, matchRequest, ruleRange);
+ collectRuleIfMatches(rules->at(i), behaviorAtBoundary, cascadeScope, cascadeOrder, matchRequest, ruleRange);
}
static inline bool compareRules(const MatchedRule& matchedRule1, const MatchedRule& matchedRule2)
{
- unsigned specificity1 = matchedRule1.ruleData()->specificity();
- unsigned specificity2 = matchedRule2.ruleData()->specificity();
- return matchedRule1.cascadeScope() == matchedRule2.cascadeScope() ?
- ((specificity1 == specificity2) ? matchedRule1.position() < matchedRule2.position() : specificity1 < specificity2) :
- matchedRule1.cascadeScope() > matchedRule2.cascadeScope();
+ if (matchedRule1.cascadeScope() != matchedRule2.cascadeScope())
+ return matchedRule1.cascadeScope() > matchedRule2.cascadeScope();
+
+ unsigned specificity1 = matchedRule1.specificity();
+ unsigned specificity2 = matchedRule2.specificity();
+ if (specificity1 != specificity2)
+ return specificity1 < specificity2;
+
+ if (matchedRule1.styleSheetIndex() != matchedRule2.styleSheetIndex())
+ return matchedRule1.styleSheetIndex() < matchedRule2.styleSheetIndex();
+
+ return matchedRule1.position() < matchedRule2.position();
}
void ElementRuleCollector::sortMatchedRules()
@@ -314,11 +383,10 @@ bool ElementRuleCollector::hasAnyMatchingRules(RuleSet* ruleSet)
// To check whether a given RuleSet has any rule matching a given element,
// should not see the element's treescope. Because RuleSet has no
// information about "scope".
- m_behaviorAtBoundary = SelectorChecker::StaysWithinTreeScope;
int firstRuleIndex = -1, lastRuleIndex = -1;
RuleRange ruleRange(firstRuleIndex, lastRuleIndex);
// FIXME: Verify whether it's ok to ignore CascadeScope here.
- collectMatchingRules(MatchRequest(ruleSet), ruleRange);
+ collectMatchingRules(MatchRequest(ruleSet), ruleRange, SelectorChecker::StaysWithinTreeScope);
return m_matchedRules && !m_matchedRules->isEmpty();
}
diff --git a/chromium/third_party/WebKit/Source/core/css/ElementRuleCollector.h b/chromium/third_party/WebKit/Source/core/css/ElementRuleCollector.h
index 60f7abc7459..cf47567909a 100644
--- a/chromium/third_party/WebKit/Source/core/css/ElementRuleCollector.h
+++ b/chromium/third_party/WebKit/Source/core/css/ElementRuleCollector.h
@@ -27,13 +27,13 @@
#include "core/css/resolver/ElementResolveContext.h"
#include "core/css/resolver/MatchRequest.h"
#include "core/css/resolver/MatchResult.h"
+#include "core/css/resolver/StyleResolverIncludes.h"
#include "wtf/RefPtr.h"
#include "wtf/Vector.h"
namespace WebCore {
class CSSRuleList;
-class DocumentRuleSets;
class RenderRegion;
class RuleData;
class RuleSet;
@@ -50,9 +50,11 @@ const CascadeOrder ignoreCascadeOrder = 0;
class MatchedRule {
WTF_MAKE_FAST_ALLOCATED;
public:
- explicit MatchedRule(const RuleData* ruleData, CascadeScope cascadeScope, CascadeOrder cascadeOrder)
+ explicit MatchedRule(const RuleData* ruleData, unsigned specificity, CascadeScope cascadeScope, CascadeOrder cascadeOrder, unsigned styleSheetIndex)
: m_ruleData(ruleData)
+ , m_specificity(specificity)
, m_cascadeScope(cascadeScope)
+ , m_styleSheetIndex(styleSheetIndex)
{
ASSERT(m_ruleData);
static const unsigned BitsForPositionInRuleData = 18;
@@ -62,11 +64,21 @@ public:
const RuleData* ruleData() const { return m_ruleData; }
uint32_t cascadeScope() const { return m_cascadeScope; }
uint32_t position() const { return m_position; }
+ unsigned specificity() const { return ruleData()->specificity() + m_specificity; }
+ uint32_t styleSheetIndex() const { return m_styleSheetIndex; }
private:
const RuleData* m_ruleData;
+ unsigned m_specificity;
CascadeScope m_cascadeScope;
uint32_t m_position;
+ uint32_t m_styleSheetIndex;
+};
+
+class StyleRuleList : public RefCounted<StyleRuleList> {
+public:
+ static PassRefPtr<StyleRuleList> create() { return adoptRef(new StyleRuleList()); }
+ Vector<StyleRule*> m_list;
};
// ElementRuleCollector is designed to be used as a stack object.
@@ -76,12 +88,8 @@ private:
class ElementRuleCollector {
WTF_MAKE_NONCOPYABLE(ElementRuleCollector);
public:
- ElementRuleCollector(const ElementResolveContext&, const SelectorFilter&, RenderStyle*);
-
- void setBehaviorAtBoundary(SelectorChecker::BehaviorAtBoundary boundary) { m_behaviorAtBoundary = boundary; }
- SelectorChecker::BehaviorAtBoundary behaviorAtBoundary() const { return m_behaviorAtBoundary; }
- void setCanUseFastReject(bool canUseFastReject) { m_canUseFastReject = canUseFastReject; }
- bool canUseFastReject() const { return m_canUseFastReject; }
+ ElementRuleCollector(const ElementResolveContext&, const SelectorFilter&, RenderStyle* = 0, ShouldIncludeStyleSheetInCSSOMWrapper = IncludeStyleSheetInCSSOMWrapper);
+ ~ElementRuleCollector();
void setMode(SelectorChecker::Mode mode) { m_mode = mode; }
void setPseudoStyleRequest(const PseudoStyleRequest& request) { m_pseudoStyleRequest = request; }
@@ -92,10 +100,11 @@ public:
bool hasAnyMatchingRules(RuleSet*);
MatchResult& matchedResult();
- PassRefPtr<CSSRuleList> matchedRuleList();
+ PassRefPtr<StyleRuleList> matchedStyleRuleList();
+ PassRefPtr<CSSRuleList> matchedCSSRuleList();
- void collectMatchingRules(const MatchRequest&, RuleRange&, CascadeScope = ignoreCascadeScope, CascadeOrder = ignoreCascadeOrder);
- void collectMatchingRulesForRegion(const MatchRequest&, RuleRange&, CascadeScope = ignoreCascadeScope, CascadeOrder = ignoreCascadeOrder);
+ void collectMatchingRules(const MatchRequest&, RuleRange&, SelectorChecker::BehaviorAtBoundary = SelectorChecker::DoesNotCrossBoundary, CascadeScope = ignoreCascadeScope, CascadeOrder = ignoreCascadeOrder);
+ void collectMatchingRulesForRegion(const MatchRequest&, RuleRange&, SelectorChecker::BehaviorAtBoundary = SelectorChecker::DoesNotCrossBoundary, CascadeScope = ignoreCascadeScope, CascadeOrder = ignoreCascadeOrder);
void sortAndTransferMatchedRules();
void clearMatchedRules();
void addElementStyleProperties(const StylePropertySet*, bool isCacheable = true);
@@ -105,17 +114,19 @@ public:
void sortAndTransferMatchedRulesWithOnlySortBySpecificity();
private:
- Document& document() { return m_context.document(); }
+ void collectRuleIfMatches(const RuleData&, SelectorChecker::BehaviorAtBoundary, CascadeScope, CascadeOrder, const MatchRequest&, RuleRange&);
+ void collectMatchingRulesForList(const Vector<RuleData>*, SelectorChecker::BehaviorAtBoundary, CascadeScope, CascadeOrder, const MatchRequest&, RuleRange&);
+ void collectMatchingRulesForList(const RuleData*, SelectorChecker::BehaviorAtBoundary, CascadeScope, CascadeOrder, const MatchRequest&, RuleRange&);
+ bool ruleMatches(const RuleData&, const ContainerNode* scope, SelectorChecker::BehaviorAtBoundary, SelectorChecker::MatchResult*);
- void collectRuleIfMatches(const RuleData&, CascadeScope, CascadeOrder, const MatchRequest&, RuleRange&);
- void collectMatchingRulesForList(const Vector<RuleData>*, CascadeScope, CascadeOrder, const MatchRequest&, RuleRange&);
- void collectMatchingRulesForList(const RuleData*, CascadeScope, CascadeOrder, const MatchRequest&, RuleRange&);
- bool ruleMatches(const RuleData&, const ContainerNode* scope, PseudoId&);
+ void appendCSSOMWrapperForRule(StyleRule*);
void sortMatchedRules();
- void addMatchedRule(const RuleData*, CascadeScope, CascadeOrder);
+ void addMatchedRule(const RuleData*, unsigned specificity, CascadeScope, CascadeOrder);
+ void addMatchedRule(const RuleData*, unsigned specificity, CascadeScope, CascadeOrder, unsigned styleSheetIndex);
StaticCSSRuleList* ensureRuleList();
+ StyleRuleList* ensureStyleRuleList();
private:
const ElementResolveContext& m_context;
@@ -125,15 +136,16 @@ private:
const RenderRegion* m_regionForStyling;
PseudoStyleRequest m_pseudoStyleRequest;
SelectorChecker::Mode m_mode;
- SelectorChecker::BehaviorAtBoundary m_behaviorAtBoundary;
bool m_canUseFastReject;
bool m_sameOriginOnly;
bool m_matchingUARules;
+ bool m_includeStyleSheet;
OwnPtr<Vector<MatchedRule, 32> > m_matchedRules;
// Output.
- RefPtr<StaticCSSRuleList> m_ruleList;
+ RefPtr<StaticCSSRuleList> m_cssRuleList;
+ RefPtr<StyleRuleList> m_styleRuleList;
MatchResult m_result;
};
diff --git a/chromium/third_party/WebKit/Source/core/css/FontFace.cpp b/chromium/third_party/WebKit/Source/core/css/FontFace.cpp
index d1d38962785..3b35cbca0fb 100644
--- a/chromium/third_party/WebKit/Source/core/css/FontFace.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/FontFace.cpp
@@ -31,11 +31,13 @@
#include "config.h"
#include "core/css/FontFace.h"
-#include "CSSPropertyNames.h"
#include "CSSValueKeywords.h"
#include "FontFamilyNames.h"
#include "bindings/v8/Dictionary.h"
#include "bindings/v8/ExceptionState.h"
+#include "bindings/v8/ScriptPromiseResolver.h"
+#include "bindings/v8/ScriptScope.h"
+#include "bindings/v8/ScriptState.h"
#include "core/css/CSSFontFace.h"
#include "core/css/CSSFontFaceSrcValue.h"
#include "core/css/CSSParser.h"
@@ -44,65 +46,100 @@
#include "core/css/CSSValueList.h"
#include "core/css/StylePropertySet.h"
#include "core/css/StyleRule.h"
+#include "core/dom/DOMError.h"
#include "core/dom/Document.h"
-#include "core/page/Frame.h"
-#include "core/page/Settings.h"
-#include "core/platform/graphics/FontTraitsMask.h"
+#include "core/dom/ExceptionCode.h"
+#include "core/frame/Frame.h"
+#include "core/frame/Settings.h"
#include "core/svg/SVGFontFaceElement.h"
+#include "platform/fonts/FontDescription.h"
+#include "platform/fonts/FontTraitsMask.h"
+#include "platform/fonts/SimpleFontData.h"
namespace WebCore {
+class FontFaceReadyPromiseResolver {
+public:
+ static PassOwnPtr<FontFaceReadyPromiseResolver> create(ScriptPromise promise, ExecutionContext* context)
+ {
+ return adoptPtr(new FontFaceReadyPromiseResolver(promise, context));
+ }
+
+ void resolve(PassRefPtr<FontFace> fontFace)
+ {
+ ScriptScope scope(m_scriptState);
+ switch (fontFace->loadStatus()) {
+ case FontFace::Loaded:
+ m_resolver->resolve(fontFace);
+ break;
+ case FontFace::Error:
+ m_resolver->reject(DOMError::create(NetworkError));
+ break;
+ default:
+ ASSERT_NOT_REACHED();
+ }
+ }
+
+private:
+ FontFaceReadyPromiseResolver(ScriptPromise promise, ExecutionContext* context)
+ : m_scriptState(ScriptState::current())
+ , m_resolver(ScriptPromiseResolver::create(promise, context))
+ { }
+ ScriptState* m_scriptState;
+ RefPtr<ScriptPromiseResolver> m_resolver;
+};
+
static PassRefPtr<CSSValue> parseCSSValue(const String& s, CSSPropertyID propertyID)
{
if (s.isEmpty())
return 0;
RefPtr<MutableStylePropertySet> parsedStyle = MutableStylePropertySet::create();
- CSSParser::parseValue(parsedStyle.get(), propertyID, s, true, CSSStrictMode, 0);
+ CSSParser::parseValue(parsedStyle.get(), propertyID, s, true, HTMLStandardMode, 0);
return parsedStyle->getPropertyCSSValue(propertyID);
}
-PassRefPtr<FontFace> FontFace::create(const String& family, const String& source, const Dictionary& descriptors, ExceptionState& es)
+PassRefPtr<FontFace> FontFace::create(const AtomicString& family, const String& source, const Dictionary& descriptors, ExceptionState& exceptionState)
{
RefPtr<CSSValue> src = parseCSSValue(source, CSSPropertySrc);
if (!src || !src->isValueList()) {
- es.throwDOMException(SyntaxError);
+ exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
return 0;
}
RefPtr<FontFace> fontFace = adoptRef<FontFace>(new FontFace(src));
- fontFace->setFamily(family, es);
- if (es.hadException())
+ fontFace->setFamily(family, exceptionState);
+ if (exceptionState.hadException())
return 0;
String value;
if (descriptors.get("style", value)) {
- fontFace->setStyle(value, es);
- if (es.hadException())
+ fontFace->setStyle(value, exceptionState);
+ if (exceptionState.hadException())
return 0;
}
if (descriptors.get("weight", value)) {
- fontFace->setWeight(value, es);
- if (es.hadException())
+ fontFace->setWeight(value, exceptionState);
+ if (exceptionState.hadException())
return 0;
}
if (descriptors.get("stretch", value)) {
- fontFace->setStretch(value, es);
- if (es.hadException())
+ fontFace->setStretch(value, exceptionState);
+ if (exceptionState.hadException())
return 0;
}
if (descriptors.get("unicodeRange", value)) {
- fontFace->setUnicodeRange(value, es);
- if (es.hadException())
+ fontFace->setUnicodeRange(value, exceptionState);
+ if (exceptionState.hadException())
return 0;
}
if (descriptors.get("variant", value)) {
- fontFace->setVariant(value, es);
- if (es.hadException())
+ fontFace->setVariant(value, exceptionState);
+ if (exceptionState.hadException())
return 0;
}
if (descriptors.get("featureSettings", value)) {
- fontFace->setFeatureSettings(value, es);
- if (es.hadException())
+ fontFace->setFeatureSettings(value, exceptionState);
+ if (exceptionState.hadException())
return 0;
}
@@ -137,6 +174,7 @@ PassRefPtr<FontFace> FontFace::create(const StyleRuleFontFace* fontFaceRule)
FontFace::FontFace(PassRefPtr<CSSValue> src)
: m_src(src)
, m_status(Unloaded)
+ , m_cssFontFace(0)
{
}
@@ -174,41 +212,41 @@ String FontFace::featureSettings() const
return m_featureSettings ? m_featureSettings->cssText() : "normal";
}
-void FontFace::setStyle(const String& s, ExceptionState& es)
+void FontFace::setStyle(const String& s, ExceptionState& exceptionState)
{
- setPropertyFromString(s, CSSPropertyFontStyle, es);
+ setPropertyFromString(s, CSSPropertyFontStyle, exceptionState);
}
-void FontFace::setWeight(const String& s, ExceptionState& es)
+void FontFace::setWeight(const String& s, ExceptionState& exceptionState)
{
- setPropertyFromString(s, CSSPropertyFontWeight, es);
+ setPropertyFromString(s, CSSPropertyFontWeight, exceptionState);
}
-void FontFace::setStretch(const String& s, ExceptionState& es)
+void FontFace::setStretch(const String& s, ExceptionState& exceptionState)
{
- setPropertyFromString(s, CSSPropertyFontStretch, es);
+ setPropertyFromString(s, CSSPropertyFontStretch, exceptionState);
}
-void FontFace::setUnicodeRange(const String& s, ExceptionState& es)
+void FontFace::setUnicodeRange(const String& s, ExceptionState& exceptionState)
{
- setPropertyFromString(s, CSSPropertyUnicodeRange, es);
+ setPropertyFromString(s, CSSPropertyUnicodeRange, exceptionState);
}
-void FontFace::setVariant(const String& s, ExceptionState& es)
+void FontFace::setVariant(const String& s, ExceptionState& exceptionState)
{
- setPropertyFromString(s, CSSPropertyFontVariant, es);
+ setPropertyFromString(s, CSSPropertyFontVariant, exceptionState);
}
-void FontFace::setFeatureSettings(const String& s, ExceptionState& es)
+void FontFace::setFeatureSettings(const String& s, ExceptionState& exceptionState)
{
- setPropertyFromString(s, CSSPropertyWebkitFontFeatureSettings, es);
+ setPropertyFromString(s, CSSPropertyWebkitFontFeatureSettings, exceptionState);
}
-void FontFace::setPropertyFromString(const String& s, CSSPropertyID propertyID, ExceptionState& es)
+void FontFace::setPropertyFromString(const String& s, CSSPropertyID propertyID, ExceptionState& exceptionState)
{
RefPtr<CSSValue> value = parseCSSValue(s, propertyID);
if (!value || !setPropertyValue(value, propertyID))
- es.throwDOMException(SyntaxError);
+ exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
}
bool FontFace::setPropertyFromStyle(const StylePropertySet* properties, CSSPropertyID propertyID)
@@ -253,30 +291,30 @@ bool FontFace::setFamilyValue(CSSValueList* familyList)
return false;
CSSPrimitiveValue* familyValue = toCSSPrimitiveValue(familyList->itemWithoutBoundsCheck(0));
- String family;
+ AtomicString family;
if (familyValue->isString()) {
- family = familyValue->getStringValue();
+ family = AtomicString(familyValue->getStringValue());
} else if (familyValue->isValueID()) {
// We need to use the raw text for all the generic family types, since @font-face is a way of actually
// defining what font to use for those types.
switch (familyValue->getValueID()) {
case CSSValueSerif:
- family = FontFamilyNames::serifFamily;
+ family = FontFamilyNames::webkit_serif;
break;
case CSSValueSansSerif:
- family = FontFamilyNames::sansSerifFamily;
+ family = FontFamilyNames::webkit_sans_serif;
break;
case CSSValueCursive:
- family = FontFamilyNames::cursiveFamily;
+ family = FontFamilyNames::webkit_cursive;
break;
case CSSValueFantasy:
- family = FontFamilyNames::fantasyFamily;
+ family = FontFamilyNames::webkit_fantasy;
break;
case CSSValueMonospace:
- family = FontFamilyNames::monospaceFamily;
+ family = FontFamilyNames::webkit_monospace;
break;
case CSSValueWebkitPictograph:
- family = FontFamilyNames::pictographFamily;
+ family = FontFamilyNames::webkit_pictograph;
break;
default:
return false;
@@ -303,6 +341,48 @@ String FontFace::status() const
return emptyString();
}
+void FontFace::setLoadStatus(LoadStatus status)
+{
+ m_status = status;
+ if (m_status == Loaded || m_status == Error)
+ resolveReadyPromises();
+}
+
+void FontFace::load()
+{
+ // FIXME: This does not load FontFace created by JavaScript, since m_cssFontFace is null.
+ if (m_status != Unloaded || !m_cssFontFace)
+ return;
+
+ FontDescription fontDescription;
+ FontFamily fontFamily;
+ fontFamily.setFamily(m_family);
+ fontDescription.setFamily(fontFamily);
+ fontDescription.setTraitsMask(static_cast<FontTraitsMask>(traitsMask()));
+
+ RefPtr<SimpleFontData> fontData = m_cssFontFace->getFontData(fontDescription);
+ if (fontData && fontData->customFontData())
+ fontData->customFontData()->beginLoadIfNeeded();
+}
+
+ScriptPromise FontFace::ready(ExecutionContext* context)
+{
+ ScriptPromise promise = ScriptPromise::createPending(context);
+ OwnPtr<FontFaceReadyPromiseResolver> resolver = FontFaceReadyPromiseResolver::create(promise, context);
+ if (m_status == Loaded || m_status == Error)
+ resolver->resolve(this);
+ else
+ m_readyResolvers.append(resolver.release());
+ return promise;
+}
+
+void FontFace::resolveReadyPromises()
+{
+ for (size_t i = 0; i < m_readyResolvers.size(); i++)
+ m_readyResolvers[i]->resolve(this);
+ m_readyResolvers.clear();
+}
+
unsigned FontFace::traitsMask() const
{
unsigned traitsMask = 0;
@@ -402,7 +482,11 @@ unsigned FontFace::traitsMask() const
PassRefPtr<CSSFontFace> FontFace::createCSSFontFace(Document* document)
{
+ if (m_cssFontFace)
+ return m_cssFontFace;
+
RefPtr<CSSFontFace> cssFontFace = CSSFontFace::create(this);
+ m_cssFontFace = cssFontFace.get();
// Each item in the src property's list is a single CSSFontFaceSource. Put them all into a CSSFontFace.
CSSValueList* srcList = toCSSValueList(m_src.get());
@@ -412,7 +496,7 @@ PassRefPtr<CSSFontFace> FontFace::createCSSFontFace(Document* document)
for (int i = 0; i < srcLength; i++) {
// An item in the list either specifies a string (local font name) or a URL (remote font to download).
- CSSFontFaceSrcValue* item = static_cast<CSSFontFaceSrcValue*>(srcList->itemWithoutBoundsCheck(i));
+ CSSFontFaceSrcValue* item = toCSSFontFaceSrcValue(srcList->itemWithoutBoundsCheck(i));
OwnPtr<CSSFontFaceSource> source;
#if ENABLE(SVG_FONTS)
@@ -446,8 +530,8 @@ PassRefPtr<CSSFontFace> FontFace::createCSSFontFace(Document* document)
if (CSSValueList* rangeList = toCSSValueList(m_unicodeRange.get())) {
unsigned numRanges = rangeList->length();
for (unsigned i = 0; i < numRanges; i++) {
- CSSUnicodeRangeValue* range = static_cast<CSSUnicodeRangeValue*>(rangeList->itemWithoutBoundsCheck(i));
- cssFontFace->addRange(range->from(), range->to());
+ CSSUnicodeRangeValue* range = toCSSUnicodeRangeValue(rangeList->itemWithoutBoundsCheck(i));
+ cssFontFace->ranges().add(range->from(), range->to());
}
}
return cssFontFace;
diff --git a/chromium/third_party/WebKit/Source/core/css/FontFace.h b/chromium/third_party/WebKit/Source/core/css/FontFace.h
index 69c50940629..900d3a7c962 100644
--- a/chromium/third_party/WebKit/Source/core/css/FontFace.h
+++ b/chromium/third_party/WebKit/Source/core/css/FontFace.h
@@ -32,6 +32,7 @@
#define FontFace_h
#include "CSSPropertyNames.h"
+#include "bindings/v8/ScriptPromise.h"
#include "core/css/CSSValue.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefCounted.h"
@@ -44,6 +45,7 @@ class CSSValueList;
class Dictionary;
class Document;
class ExceptionState;
+class FontFaceReadyPromiseResolver;
class StylePropertySet;
class StyleRuleFontFace;
@@ -51,12 +53,12 @@ class FontFace : public RefCounted<FontFace> {
public:
enum LoadStatus { Unloaded, Loading, Loaded, Error };
- static PassRefPtr<FontFace> create(const String& family, const String& source, const Dictionary&, ExceptionState&);
+ static PassRefPtr<FontFace> create(const AtomicString& family, const String& source, const Dictionary&, ExceptionState&);
static PassRefPtr<FontFace> create(const StyleRuleFontFace*);
~FontFace();
- String family() const { return m_family; }
+ const AtomicString& family() const { return m_family; }
String style() const;
String weight() const;
String stretch() const;
@@ -65,7 +67,7 @@ public:
String featureSettings() const;
// FIXME: Changing these attributes should affect font matching.
- void setFamily(const String& s, ExceptionState&) { m_family = s; }
+ void setFamily(const AtomicString& s, ExceptionState&) { m_family = s; }
void setStyle(const String&, ExceptionState&);
void setWeight(const String&, ExceptionState&);
void setStretch(const String&, ExceptionState&);
@@ -75,10 +77,14 @@ public:
String status() const;
+ void load();
+ ScriptPromise ready(ExecutionContext*);
+
LoadStatus loadStatus() const { return m_status; }
- void setLoadStatus(LoadStatus status) { m_status = status; }
+ void setLoadStatus(LoadStatus);
unsigned traitsMask() const;
PassRefPtr<CSSFontFace> createCSSFontFace(Document*);
+ void cssFontFaceDestroyed() { m_cssFontFace = 0; }
private:
FontFace(PassRefPtr<CSSValue> source);
@@ -87,8 +93,9 @@ private:
bool setPropertyFromStyle(const StylePropertySet*, CSSPropertyID);
bool setPropertyValue(PassRefPtr<CSSValue>, CSSPropertyID);
bool setFamilyValue(CSSValueList*);
+ void resolveReadyPromises();
- String m_family;
+ AtomicString m_family;
RefPtr<CSSValue> m_src;
RefPtr<CSSValue> m_style;
RefPtr<CSSValue> m_weight;
@@ -97,6 +104,9 @@ private:
RefPtr<CSSValue> m_variant;
RefPtr<CSSValue> m_featureSettings;
LoadStatus m_status;
+
+ Vector<OwnPtr<FontFaceReadyPromiseResolver> > m_readyResolvers;
+ CSSFontFace* m_cssFontFace;
};
typedef Vector<RefPtr<FontFace> > FontFaceArray;
diff --git a/chromium/third_party/WebKit/Source/core/css/FontFace.idl b/chromium/third_party/WebKit/Source/core/css/FontFace.idl
index a66872bb63b..fcfef2d143b 100644
--- a/chromium/third_party/WebKit/Source/core/css/FontFace.idl
+++ b/chromium/third_party/WebKit/Source/core/css/FontFace.idl
@@ -36,22 +36,21 @@ enum FontFaceLoadStatus {
};
[
- EnabledAtRuntime=FontLoadEvents,
+ RuntimeEnabled=FontLoadEvents,
Constructor(DOMString family, DOMString source, Dictionary descriptors),
- ConstructorRaisesException
+ RaisesException=Constructor
] interface FontFace {
- [SetterRaisesException] attribute DOMString family;
- [SetterRaisesException] attribute DOMString style;
- [SetterRaisesException] attribute DOMString weight;
- [SetterRaisesException] attribute DOMString stretch;
- [SetterRaisesException] attribute DOMString unicodeRange;
- [SetterRaisesException] attribute DOMString variant;
- [SetterRaisesException] attribute DOMString featureSettings;
+ [RaisesException=Setter] attribute DOMString family;
+ [RaisesException=Setter] attribute DOMString style;
+ [RaisesException=Setter] attribute DOMString weight;
+ [RaisesException=Setter] attribute DOMString stretch;
+ [RaisesException=Setter] attribute DOMString unicodeRange;
+ [RaisesException=Setter] attribute DOMString variant;
+ [RaisesException=Setter] attribute DOMString featureSettings;
readonly attribute FontFaceLoadStatus status;
- // FIXME: Implement them
- // void load();
- // Promise ready();
+ void load();
+ [CallWith=ExecutionContext] Promise ready();
};
diff --git a/chromium/third_party/WebKit/Source/core/css/FontFaceSet.cpp b/chromium/third_party/WebKit/Source/core/css/FontFaceSet.cpp
index c9838d2df51..38165b8a9aa 100644
--- a/chromium/third_party/WebKit/Source/core/css/FontFaceSet.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/FontFaceSet.cpp
@@ -27,7 +27,6 @@
#include "core/css/FontFaceSet.h"
#include "RuntimeEnabledFeatures.h"
-#include "V8FontFaceSet.h"
#include "bindings/v8/Dictionary.h"
#include "bindings/v8/ScriptPromiseResolver.h"
#include "bindings/v8/ScriptScope.h"
@@ -40,43 +39,36 @@
#include "core/css/StylePropertySet.h"
#include "core/css/resolver/StyleResolver.h"
#include "core/dom/Document.h"
-#include "core/page/FrameView.h"
-#include "core/platform/HistogramSupport.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
+#include "public/platform/Platform.h"
namespace WebCore {
static const int defaultFontSize = 10;
-static const char* const defaultFontFamily = "sans-serif";
+static const char defaultFontFamily[] = "sans-serif";
class LoadFontPromiseResolver : public CSSSegmentedFontFace::LoadFontCallback {
public:
- static PassRefPtr<LoadFontPromiseResolver> create(const FontFamily& family, ScriptExecutionContext* context)
+ static PassRefPtr<LoadFontPromiseResolver> create(const FontFamily& family, ScriptPromise promise, ExecutionContext* context)
{
int numFamilies = 0;
for (const FontFamily* f = &family; f; f = f->next())
numFamilies++;
- return adoptRef<LoadFontPromiseResolver>(new LoadFontPromiseResolver(numFamilies, context));
+ return adoptRef<LoadFontPromiseResolver>(new LoadFontPromiseResolver(numFamilies, promise, context));
}
virtual void notifyLoaded(CSSSegmentedFontFace*) OVERRIDE;
virtual void notifyError(CSSSegmentedFontFace*) OVERRIDE;
void loaded(Document*);
void error(Document*);
- void resolve();
-
- ScriptPromise promise()
- {
- ScriptPromise promise = m_resolver->promise();
- m_resolver->detachPromise();
- return promise;
- }
private:
- LoadFontPromiseResolver(int numLoading, ScriptExecutionContext* context)
+ LoadFontPromiseResolver(int numLoading, ScriptPromise promise, ExecutionContext* context)
: m_numLoading(numLoading)
, m_errorOccured(false)
, m_scriptState(ScriptState::current())
- , m_resolver(ScriptPromiseResolver::create(context))
+ , m_resolver(ScriptPromiseResolver::create(promise, context))
{ }
int m_numLoading;
@@ -91,7 +83,11 @@ void LoadFontPromiseResolver::loaded(Document* document)
if (m_numLoading || !document)
return;
- document->fonts()->scheduleResolve(this);
+ ScriptScope scope(m_scriptState);
+ if (m_errorOccured)
+ m_resolver->reject(ScriptValue::createNull());
+ else
+ m_resolver->resolve(ScriptValue::createNull());
}
void LoadFontPromiseResolver::error(Document* document)
@@ -110,39 +106,23 @@ void LoadFontPromiseResolver::notifyError(CSSSegmentedFontFace* face)
error(face->fontSelector()->document());
}
-void LoadFontPromiseResolver::resolve()
-{
- ScriptScope scope(m_scriptState);
- if (m_errorOccured)
- m_resolver->reject(ScriptValue::createNull());
- else
- m_resolver->fulfill(ScriptValue::createNull());
-}
-
class FontsReadyPromiseResolver {
public:
- static PassOwnPtr<FontsReadyPromiseResolver> create(ScriptExecutionContext* context)
+ static PassOwnPtr<FontsReadyPromiseResolver> create(ScriptPromise promise, ExecutionContext* context)
{
- return adoptPtr(new FontsReadyPromiseResolver(context));
+ return adoptPtr(new FontsReadyPromiseResolver(promise, context));
}
- void call(PassRefPtr<FontFaceSet> fontFaceSet)
+ void resolve(PassRefPtr<FontFaceSet> fontFaceSet)
{
ScriptScope scope(m_scriptState);
- m_resolver->fulfill(fontFaceSet);
- }
-
- ScriptPromise promise()
- {
- ScriptPromise promise = m_resolver->promise();
- m_resolver->detachPromise();
- return promise;
+ m_resolver->resolve(fontFaceSet);
}
private:
- FontsReadyPromiseResolver(ScriptExecutionContext* context)
+ FontsReadyPromiseResolver(ScriptPromise promise, ExecutionContext* context)
: m_scriptState(ScriptState::current())
- , m_resolver(ScriptPromiseResolver::create(context))
+ , m_resolver(ScriptPromiseResolver::create(promise, context))
{ }
ScriptState* m_scriptState;
RefPtr<ScriptPromiseResolver> m_resolver;
@@ -151,8 +131,8 @@ private:
FontFaceSet::FontFaceSet(Document* document)
: ActiveDOMObject(document)
, m_loadingCount(0)
- , m_shouldFireDoneEvent(false)
- , m_timer(this, &FontFaceSet::timerFired)
+ , m_shouldFireLoadingEvent(false)
+ , m_asyncRunner(this, &FontFaceSet::handlePendingEventsAndPromises)
{
suspendIfNeeded();
}
@@ -163,90 +143,71 @@ FontFaceSet::~FontFaceSet()
Document* FontFaceSet::document() const
{
- return toDocument(scriptExecutionContext());
-}
-
-EventTargetData* FontFaceSet::eventTargetData()
-{
- return &m_eventTargetData;
-}
-
-EventTargetData* FontFaceSet::ensureEventTargetData()
-{
- return &m_eventTargetData;
+ return toDocument(executionContext());
}
const AtomicString& FontFaceSet::interfaceName() const
{
- return eventNames().interfaceForFontFaceSet;
+ return EventTargetNames::FontFaceSet;
}
-ScriptExecutionContext* FontFaceSet::scriptExecutionContext() const
+ExecutionContext* FontFaceSet::executionContext() const
{
- return ActiveDOMObject::scriptExecutionContext();
+ return ActiveDOMObject::executionContext();
}
AtomicString FontFaceSet::status() const
{
DEFINE_STATIC_LOCAL(AtomicString, loading, ("loading", AtomicString::ConstructFromLiteral));
DEFINE_STATIC_LOCAL(AtomicString, loaded, ("loaded", AtomicString::ConstructFromLiteral));
- return (m_loadingCount > 0 || m_shouldFireDoneEvent) ? loading : loaded;
+ return (m_loadingCount > 0 || hasLoadedFonts()) ? loading : loaded;
+}
+
+void FontFaceSet::handlePendingEventsAndPromisesSoon()
+{
+ // setPendingActivity() is unnecessary because m_asyncRunner will be
+ // automatically stopped on destruction.
+ m_asyncRunner.runAsync();
}
void FontFaceSet::didLayout()
{
- Document* d = document();
- if (d->page() && d->page()->mainFrame() == d->frame())
+ if (document()->frame()->isMainFrame())
m_histogram.record();
if (!RuntimeEnabledFeatures::fontLoadEventsEnabled())
return;
- if (m_loadingCount || (!m_shouldFireDoneEvent && m_readyResolvers.isEmpty()))
+ if (m_loadingCount || (!hasLoadedFonts() && m_readyResolvers.isEmpty()))
return;
- if (!m_timer.isActive())
- m_timer.startOneShot(0);
+ handlePendingEventsAndPromisesSoon();
}
-void FontFaceSet::timerFired(Timer<FontFaceSet>*)
+void FontFaceSet::handlePendingEventsAndPromises()
{
- firePendingEvents();
- resolvePendingLoadPromises();
+ fireLoadingEvent();
fireDoneEventIfPossible();
}
-void FontFaceSet::scheduleEvent(PassRefPtr<Event> event)
+void FontFaceSet::fireLoadingEvent()
{
- m_pendingEvents.append(event);
- if (!m_timer.isActive())
- m_timer.startOneShot(0);
+ if (m_shouldFireLoadingEvent) {
+ m_shouldFireLoadingEvent = false;
+ dispatchEvent(CSSFontFaceLoadEvent::createForFontFaces(EventTypeNames::loading));
+ }
}
-void FontFaceSet::firePendingEvents()
+void FontFaceSet::suspend()
{
- if (m_pendingEvents.isEmpty())
- return;
-
- Vector<RefPtr<Event> > pendingEvents;
- m_pendingEvents.swap(pendingEvents);
- for (size_t index = 0; index < pendingEvents.size(); ++index)
- dispatchEvent(pendingEvents[index].release());
+ m_asyncRunner.suspend();
}
-void FontFaceSet::scheduleResolve(LoadFontPromiseResolver* resolver)
+void FontFaceSet::resume()
{
- m_pendingLoadResolvers.append(resolver);
- if (!m_timer.isActive())
- m_timer.startOneShot(0);
+ m_asyncRunner.resume();
}
-void FontFaceSet::resolvePendingLoadPromises()
+void FontFaceSet::stop()
{
- if (m_pendingLoadResolvers.isEmpty())
- return;
-
- Vector<RefPtr<LoadFontPromiseResolver> > resolvers;
- m_pendingLoadResolvers.swap(resolvers);
- for (size_t index = 0; index < resolvers.size(); ++index)
- resolvers[index]->resolve();
+ m_asyncRunner.stop();
}
void FontFaceSet::beginFontLoading(FontFace* fontFace)
@@ -255,10 +216,12 @@ void FontFaceSet::beginFontLoading(FontFace* fontFace)
if (!RuntimeEnabledFeatures::fontLoadEventsEnabled())
return;
+ if (!m_loadingCount && !hasLoadedFonts()) {
+ ASSERT(!m_shouldFireLoadingEvent);
+ m_shouldFireLoadingEvent = true;
+ handlePendingEventsAndPromisesSoon();
+ }
++m_loadingCount;
- if (m_loadingCount == 1 && !m_shouldFireDoneEvent)
- scheduleEvent(CSSFontFaceLoadEvent::createForFontFaces(eventNames().loadingEvent));
- m_shouldFireDoneEvent = false;
}
void FontFaceSet::fontLoaded(FontFace* fontFace)
@@ -281,29 +244,24 @@ void FontFaceSet::queueDoneEvent(FontFace* fontFace)
{
ASSERT(m_loadingCount > 0);
--m_loadingCount;
- if (!m_loadingCount) {
- ASSERT(!m_shouldFireDoneEvent);
- m_shouldFireDoneEvent = true;
- if (!m_timer.isActive())
- m_timer.startOneShot(0);
- }
+ if (!m_loadingCount)
+ handlePendingEventsAndPromisesSoon();
}
ScriptPromise FontFaceSet::ready()
{
- OwnPtr<FontsReadyPromiseResolver> resolver = FontsReadyPromiseResolver::create(scriptExecutionContext());
- ScriptPromise promise = resolver->promise();
+ ScriptPromise promise = ScriptPromise::createPending(executionContext());
+ OwnPtr<FontsReadyPromiseResolver> resolver = FontsReadyPromiseResolver::create(promise, executionContext());
m_readyResolvers.append(resolver.release());
- if (!m_timer.isActive())
- m_timer.startOneShot(0);
+ handlePendingEventsAndPromisesSoon();
return promise;
}
void FontFaceSet::fireDoneEventIfPossible()
{
- if (!m_pendingEvents.isEmpty() || !m_pendingLoadResolvers.isEmpty())
+ if (m_shouldFireLoadingEvent)
return;
- if (m_loadingCount || (!m_shouldFireDoneEvent && m_readyResolvers.isEmpty()))
+ if (m_loadingCount || (!hasLoadedFonts() && m_readyResolvers.isEmpty()))
return;
// If the layout was invalidated in between when we thought layout
@@ -313,14 +271,13 @@ void FontFaceSet::fireDoneEventIfPossible()
if (!d->view() || d->view()->needsLayout())
return;
- if (m_shouldFireDoneEvent) {
- m_shouldFireDoneEvent = false;
+ if (hasLoadedFonts()) {
RefPtr<CSSFontFaceLoadEvent> doneEvent;
RefPtr<CSSFontFaceLoadEvent> errorEvent;
- doneEvent = CSSFontFaceLoadEvent::createForFontFaces(eventNames().loadingdoneEvent, m_loadedFonts);
+ doneEvent = CSSFontFaceLoadEvent::createForFontFaces(EventTypeNames::loadingdone, m_loadedFonts);
m_loadedFonts.clear();
if (!m_failedFonts.isEmpty()) {
- errorEvent = CSSFontFaceLoadEvent::createForFontFaces(eventNames().loadingerrorEvent, m_failedFonts);
+ errorEvent = CSSFontFaceLoadEvent::createForFontFaces(EventTypeNames::loadingerror, m_failedFonts);
m_failedFonts.clear();
}
dispatchEvent(doneEvent);
@@ -332,63 +289,67 @@ void FontFaceSet::fireDoneEventIfPossible()
Vector<OwnPtr<FontsReadyPromiseResolver> > resolvers;
m_readyResolvers.swap(resolvers);
for (size_t index = 0; index < resolvers.size(); ++index)
- resolvers[index]->call(this);
+ resolvers[index]->resolve(this);
}
}
-Vector<RefPtr<FontFace> > FontFaceSet::match(const String& fontString, const String&, ExceptionState& es)
+static const String& nullToSpace(const String& s)
+{
+ DEFINE_STATIC_LOCAL(String, space, (" "));
+ return s.isNull() ? space : s;
+}
+
+Vector<RefPtr<FontFace> > FontFaceSet::match(const String& fontString, const String& text, ExceptionState& exceptionState)
{
- // FIXME: The second parameter (text) is ignored.
Vector<RefPtr<FontFace> > matchedFonts;
Font font;
if (!resolveFontStyle(fontString, font)) {
- es.throwDOMException(SyntaxError);
+ exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
return matchedFonts;
}
for (const FontFamily* f = &font.family(); f; f = f->next()) {
- CSSSegmentedFontFace* face = document()->styleResolver()->fontSelector()->getFontFace(font.fontDescription(), f->family());
+ CSSSegmentedFontFace* face = document()->styleEngine()->fontSelector()->getFontFace(font.fontDescription(), f->family());
if (face)
- matchedFonts.append(face->fontFaces());
+ matchedFonts.append(face->fontFaces(nullToSpace(text)));
}
return matchedFonts;
}
-ScriptPromise FontFaceSet::load(const String& fontString, const String&, ExceptionState& es)
+ScriptPromise FontFaceSet::load(const String& fontString, const String& text, ExceptionState& exceptionState)
{
- // FIXME: The second parameter (text) is ignored.
Font font;
if (!resolveFontStyle(fontString, font)) {
- es.throwDOMException(SyntaxError);
+ exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
return ScriptPromise();
}
Document* d = document();
- RefPtr<LoadFontPromiseResolver> resolver = LoadFontPromiseResolver::create(font.family(), scriptExecutionContext());
+ ScriptPromise promise = ScriptPromise::createPending(executionContext());
+ RefPtr<LoadFontPromiseResolver> resolver = LoadFontPromiseResolver::create(font.family(), promise, executionContext());
for (const FontFamily* f = &font.family(); f; f = f->next()) {
- CSSSegmentedFontFace* face = d->styleResolver()->fontSelector()->getFontFace(font.fontDescription(), f->family());
+ CSSSegmentedFontFace* face = d->styleEngine()->fontSelector()->getFontFace(font.fontDescription(), f->family());
if (!face) {
resolver->error(d);
continue;
}
- face->loadFont(font.fontDescription(), resolver);
+ face->loadFont(font.fontDescription(), nullToSpace(text), resolver);
}
- return resolver->promise();
+ return promise;
}
-bool FontFaceSet::check(const String& fontString, const String&, ExceptionState& es)
+bool FontFaceSet::check(const String& fontString, const String& text, ExceptionState& exceptionState)
{
- // FIXME: The second parameter (text) is ignored.
Font font;
if (!resolveFontStyle(fontString, font)) {
- es.throwDOMException(SyntaxError);
+ exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
return false;
}
for (const FontFamily* f = &font.family(); f; f = f->next()) {
- CSSSegmentedFontFace* face = document()->styleResolver()->fontSelector()->getFontFace(font.fontDescription(), f->family());
- if (!face || !face->checkFont())
+ CSSSegmentedFontFace* face = document()->styleEngine()->fontSelector()->getFontFace(font.fontDescription(), f->family());
+ if (!face || !face->checkFont(nullToSpace(text)))
return false;
}
return true;
@@ -401,7 +362,7 @@ bool FontFaceSet::resolveFontStyle(const String& fontString, Font& font)
// Interpret fontString in the same way as the 'font' attribute of CanvasRenderingContext2D.
RefPtr<MutableStylePropertySet> parsedStyle = MutableStylePropertySet::create();
- CSSParser::parseValue(parsedStyle.get(), CSSPropertyFont, fontString, true, CSSStrictMode, 0);
+ CSSParser::parseValue(parsedStyle.get(), CSSPropertyFont, fontString, true, HTMLStandardMode, 0);
if (parsedStyle->isEmpty())
return false;
@@ -432,11 +393,11 @@ bool FontFaceSet::resolveFontStyle(const String& fontString, Font& font)
CSSPropertyValue(CSSPropertyFontSize, *parsedStyle),
CSSPropertyValue(CSSPropertyLineHeight, *parsedStyle),
};
- StyleResolver* styleResolver = document()->styleResolver();
- styleResolver->applyPropertiesToStyle(properties, WTF_ARRAY_LENGTH(properties), style.get());
+ StyleResolver& styleResolver = document()->ensureStyleResolver();
+ styleResolver.applyPropertiesToStyle(properties, WTF_ARRAY_LENGTH(properties), style.get());
font = style->font();
- font.update(styleResolver->fontSelector());
+ font.update(document()->styleEngine()->fontSelector());
return true;
}
@@ -445,7 +406,30 @@ void FontFaceSet::FontLoadHistogram::record()
if (m_recorded)
return;
m_recorded = true;
- HistogramSupport::histogramCustomCounts("WebFont.WebFontsInPage", m_count, 1, 100, 50);
+ blink::Platform::current()->histogramCustomCounts("WebFont.WebFontsInPage", m_count, 1, 100, 50);
}
+static const char* supplementName()
+{
+ return "FontFaceSet";
+}
+
+PassRefPtr<FontFaceSet> FontFaceSet::from(Document* document)
+{
+ RefPtr<FontFaceSet> fonts = static_cast<FontFaceSet*>(SupplementType::from(document, supplementName()));
+ if (!fonts) {
+ fonts = FontFaceSet::create(document);
+ SupplementType::provideTo(document, supplementName(), fonts);
+ }
+
+ return fonts.release();
+}
+
+void FontFaceSet::didLayout(Document* document)
+{
+ if (FontFaceSet* fonts = static_cast<FontFaceSet*>(SupplementType::from(document, supplementName())))
+ fonts->didLayout();
+}
+
+
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/css/FontFaceSet.h b/chromium/third_party/WebKit/Source/core/css/FontFaceSet.h
index fdc2b3abc55..ebad1329e07 100644
--- a/chromium/third_party/WebKit/Source/core/css/FontFaceSet.h
+++ b/chromium/third_party/WebKit/Source/core/css/FontFaceSet.h
@@ -29,10 +29,11 @@
#include "bindings/v8/ScriptPromise.h"
#include "core/css/FontFace.h"
#include "core/dom/ActiveDOMObject.h"
-#include "core/dom/EventListener.h"
-#include "core/dom/EventNames.h"
-#include "core/dom/EventTarget.h"
-#include "core/platform/Timer.h"
+#include "core/events/EventListener.h"
+#include "core/events/EventTarget.h"
+#include "core/events/ThreadLocalEventNames.h"
+#include "platform/AsyncMethodRunner.h"
+#include "platform/RefCountedSupplement.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefCounted.h"
#include "wtf/Vector.h"
@@ -47,20 +48,15 @@ namespace WebCore {
class CSSFontFaceSource;
class Dictionary;
class Document;
-class Event;
class ExceptionState;
class Font;
class FontResource;
class FontsReadyPromiseResolver;
-class LoadFontPromiseResolver;
-class ScriptExecutionContext;
+class ExecutionContext;
-class FontFaceSet : public RefCounted<FontFaceSet>, public ActiveDOMObject, public EventTarget {
+class FontFaceSet : public RefCountedSupplement<Document, FontFaceSet>, public ActiveDOMObject, public EventTargetWithInlineData {
+ REFCOUNTED_EVENT_TARGET(FontFaceSet);
public:
- static PassRefPtr<FontFaceSet> create(Document* document)
- {
- return adoptRef<FontFaceSet>(new FontFaceSet(document));
- }
virtual ~FontFaceSet();
DEFINE_ATTRIBUTE_EVENT_LISTENER(loading);
@@ -74,11 +70,8 @@ public:
AtomicString status() const;
- virtual ScriptExecutionContext* scriptExecutionContext() const;
- virtual const AtomicString& interfaceName() const;
-
- using RefCounted<FontFaceSet>::ref;
- using RefCounted<FontFaceSet>::deref;
+ virtual ExecutionContext* executionContext() const OVERRIDE;
+ virtual const AtomicString& interfaceName() const OVERRIDE;
Document* document() const;
@@ -86,9 +79,23 @@ public:
void beginFontLoading(FontFace*);
void fontLoaded(FontFace*);
void loadError(FontFace*);
- void scheduleResolve(LoadFontPromiseResolver*);
+
+ // ActiveDOMObject
+ virtual void suspend() OVERRIDE;
+ virtual void resume() OVERRIDE;
+ virtual void stop() OVERRIDE;
+
+ static PassRefPtr<FontFaceSet> from(Document*);
+ static void didLayout(Document*);
private:
+ typedef RefCountedSupplement<Document, FontFaceSet> SupplementType;
+
+ static PassRefPtr<FontFaceSet> create(Document* document)
+ {
+ return adoptRef<FontFaceSet>(new FontFaceSet(document));
+ }
+
class FontLoadHistogram {
public:
FontLoadHistogram() : m_count(0), m_recorded(false) { }
@@ -102,28 +109,23 @@ private:
FontFaceSet(Document*);
- virtual void refEventTarget() { ref(); }
- virtual void derefEventTarget() { deref(); }
- virtual EventTargetData* eventTargetData();
- virtual EventTargetData* ensureEventTargetData();
+ bool hasLoadedFonts() const { return !m_loadedFonts.isEmpty() || !m_failedFonts.isEmpty(); }
- void scheduleEvent(PassRefPtr<Event>);
void queueDoneEvent(FontFace*);
- void firePendingEvents();
- void resolvePendingLoadPromises();
+ void fireLoadingEvent();
void fireDoneEventIfPossible();
bool resolveFontStyle(const String&, Font&);
- void timerFired(Timer<FontFaceSet>*);
+ void handlePendingEventsAndPromisesSoon();
+ void handlePendingEventsAndPromises();
- EventTargetData m_eventTargetData;
unsigned m_loadingCount;
- Vector<RefPtr<Event> > m_pendingEvents;
- Vector<RefPtr<LoadFontPromiseResolver> > m_pendingLoadResolvers;
+ bool m_shouldFireLoadingEvent;
Vector<OwnPtr<FontsReadyPromiseResolver> > m_readyResolvers;
FontFaceArray m_loadedFonts;
FontFaceArray m_failedFonts;
- bool m_shouldFireDoneEvent;
- Timer<FontFaceSet> m_timer;
+
+ AsyncMethodRunner<FontFaceSet> m_asyncRunner;
+
FontLoadHistogram m_histogram;
};
diff --git a/chromium/third_party/WebKit/Source/core/css/FontFaceSet.idl b/chromium/third_party/WebKit/Source/core/css/FontFaceSet.idl
index 9fe5d56031e..643c335b562 100644
--- a/chromium/third_party/WebKit/Source/core/css/FontFaceSet.idl
+++ b/chromium/third_party/WebKit/Source/core/css/FontFaceSet.idl
@@ -31,10 +31,10 @@
enum FontFaceSetLoadStatus { "loading", "loaded" };
[
- NoInterfaceObject,
- EnabledAtRuntime=FontLoadEvents,
ActiveDOMObject,
- GenerateIsReachable=document
+ GenerateVisitDOMWrapper=document,
+ NoInterfaceObject,
+ RuntimeEnabled=FontLoadEvents,
] interface FontFaceSet : EventTarget {
attribute EventHandler onloading;
@@ -43,8 +43,8 @@ enum FontFaceSetLoadStatus { "loading", "loaded" };
[RaisesException] sequence<FontFace> match(DOMString font, [Default=NullString] optional DOMString text);
[RaisesException] boolean check(DOMString font, [Default=NullString] optional DOMString text);
- [EnabledAtRuntime=Promise, RaisesException] Promise load(DOMString font, [Default=NullString] optional DOMString text);
- [EnabledAtRuntime=Promise] Promise ready();
+ [RaisesException] Promise load(DOMString font, [Default=NullString] optional DOMString text);
+ Promise ready();
readonly attribute FontFaceSetLoadStatus status;
};
diff --git a/chromium/third_party/WebKit/Source/core/css/FontFamilyNames.in b/chromium/third_party/WebKit/Source/core/css/FontFamilyNames.in
deleted file mode 100644
index f1b878e27b5..00000000000
--- a/chromium/third_party/WebKit/Source/core/css/FontFamilyNames.in
+++ /dev/null
@@ -1,7 +0,0 @@
-cursiveFamily="-webkit-cursive"
-fantasyFamily="-webkit-fantasy"
-monospaceFamily="-webkit-monospace"
-sansSerifFamily="-webkit-sans-serif"
-serifFamily="-webkit-serif"
-pictographFamily="-webkit-pictograph"
-standardFamily="-webkit-standard"
diff --git a/chromium/third_party/WebKit/Source/core/css/FontFeatureValue.cpp b/chromium/third_party/WebKit/Source/core/css/FontFeatureValue.cpp
deleted file mode 100644
index 37c93daf297..00000000000
--- a/chromium/third_party/WebKit/Source/core/css/FontFeatureValue.cpp
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/css/FontFeatureValue.h"
-
-#include "wtf/text/StringBuilder.h"
-
-namespace WebCore {
-
-FontFeatureValue::FontFeatureValue(const String& tag, int value)
- : CSSValue(FontFeatureClass)
- , m_tag(tag)
- , m_value(value)
-{
-}
-
-String FontFeatureValue::customCssText() const
-{
- StringBuilder builder;
- builder.append('\'');
- builder.append(m_tag);
- builder.appendLiteral("' ");
- builder.appendNumber(m_value);
- return builder.toString();
-}
-
-bool FontFeatureValue::equals(const FontFeatureValue& other) const
-{
- return m_tag == other.m_tag && m_value == other.m_value;
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/css/FontFeatureValue.h b/chromium/third_party/WebKit/Source/core/css/FontFeatureValue.h
deleted file mode 100644
index 4aa3345b3aa..00000000000
--- a/chromium/third_party/WebKit/Source/core/css/FontFeatureValue.h
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef FontFeatureValue_h
-#define FontFeatureValue_h
-
-#include "core/css/CSSValue.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class FontFeatureValue : public CSSValue {
-public:
- static PassRefPtr<FontFeatureValue> create(const String& tag, int value)
- {
- return adoptRef(new FontFeatureValue(tag, value));
- }
-
- const String& tag() const { return m_tag; }
- int value() const { return m_value; }
- String customCssText() const;
-
- bool equals(const FontFeatureValue&) const;
-
-private:
- FontFeatureValue(const String&, int);
-
- String m_tag;
- const int m_value;
-};
-
-} // namespace
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/css/FontSize.cpp b/chromium/third_party/WebKit/Source/core/css/FontSize.cpp
index d24fd145fcd..4b545c458a8 100644
--- a/chromium/third_party/WebKit/Source/core/css/FontSize.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/FontSize.cpp
@@ -31,7 +31,7 @@
#include "CSSValueKeywords.h"
#include "core/dom/Document.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/css/FontValue.cpp b/chromium/third_party/WebKit/Source/core/css/FontValue.cpp
deleted file mode 100644
index 5537183a15f..00000000000
--- a/chromium/third_party/WebKit/Source/core/css/FontValue.cpp
+++ /dev/null
@@ -1,77 +0,0 @@
-/**
- * (C) 1999-2003 Lars Knoll (knoll@kde.org)
- * Copyright (C) 2004, 2005, 2006 Apple Computer, Inc.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-#include "config.h"
-#include "core/css/FontValue.h"
-
-#include "core/css/CSSPrimitiveValue.h"
-#include "core/css/CSSValueList.h"
-#include "wtf/text/StringBuilder.h"
-
-namespace WebCore {
-
-String FontValue::customCssText() const
-{
- // font variant weight size / line-height family
-
- StringBuilder result;
-
- if (style)
- result.append(style->cssText());
- if (variant) {
- if (!result.isEmpty())
- result.append(' ');
- result.append(variant->cssText());
- }
- if (weight) {
- if (!result.isEmpty())
- result.append(' ');
- result.append(weight->cssText());
- }
- if (size) {
- if (!result.isEmpty())
- result.append(' ');
- result.append(size->cssText());
- }
- if (lineHeight) {
- if (!size)
- result.append(' ');
- result.append('/');
- result.append(lineHeight->cssText());
- }
- if (family) {
- if (!result.isEmpty())
- result.append(' ');
- result.append(family->cssText());
- }
-
- return result.toString();
-}
-
-bool FontValue::equals(const FontValue& other) const
-{
- return compareCSSValuePtr(style, other.style)
- && compareCSSValuePtr(variant, other.variant)
- && compareCSSValuePtr(weight, other.weight)
- && compareCSSValuePtr(size, other.size)
- && compareCSSValuePtr(lineHeight, other.lineHeight)
- && compareCSSValuePtr(family, other.family);
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/css/FontValue.h b/chromium/third_party/WebKit/Source/core/css/FontValue.h
deleted file mode 100644
index df8f9a739ed..00000000000
--- a/chromium/third_party/WebKit/Source/core/css/FontValue.h
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * (C) 1999-2003 Lars Knoll (knoll@kde.org)
- * Copyright (C) 2004, 2005, 2006, 2008 Apple Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#ifndef FontValue_h
-#define FontValue_h
-
-#include "core/css/CSSValue.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefPtr.h"
-
-namespace WebCore {
-
-class CSSPrimitiveValue;
-class CSSValueList;
-
-class FontValue : public CSSValue {
-public:
- static PassRefPtr<FontValue> create()
- {
- return adoptRef(new FontValue);
- }
-
- String customCssText() const;
-
- bool equals(const FontValue&) const;
-
- RefPtr<CSSPrimitiveValue> style;
- RefPtr<CSSPrimitiveValue> variant;
- RefPtr<CSSPrimitiveValue> weight;
- RefPtr<CSSPrimitiveValue> size;
- RefPtr<CSSPrimitiveValue> lineHeight;
- RefPtr<CSSValueList> family;
-
-private:
- FontValue()
- : CSSValue(FontClass)
- {
- }
-};
-
-} // namespace
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/css/HashTools.h b/chromium/third_party/WebKit/Source/core/css/HashTools.h
new file mode 100644
index 00000000000..c86f62d3343
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/css/HashTools.h
@@ -0,0 +1,40 @@
+/*
+ * Copyright (C) 2010 Andras Becsi <abecsi@inf.u-szeged.hu>, University of Szeged
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#ifndef HashTools_h
+#define HashTools_h
+
+namespace WebCore {
+
+struct Property {
+ int nameOffset;
+ int id;
+};
+
+struct Value {
+ int nameOffset;
+ int id;
+};
+
+const Property* findProperty(register const char* str, register unsigned int len);
+const Value* findValue(register const char* str, register unsigned int len);
+
+} // namespace WebCore
+
+#endif // HashTools_h
diff --git a/chromium/third_party/WebKit/Source/core/css/InspectorCSSOMWrappers.cpp b/chromium/third_party/WebKit/Source/core/css/InspectorCSSOMWrappers.cpp
index 595d22ccae4..5a99c072010 100644
--- a/chromium/third_party/WebKit/Source/core/css/InspectorCSSOMWrappers.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/InspectorCSSOMWrappers.cpp
@@ -30,7 +30,6 @@
#include "core/css/InspectorCSSOMWrappers.h"
#include "core/css/CSSDefaultStyleSheets.h"
-#include "core/css/CSSHostRule.h"
#include "core/css/CSSImportRule.h"
#include "core/css/CSSMediaRule.h"
#include "core/css/CSSRegionRule.h"
@@ -65,22 +64,19 @@ void InspectorCSSOMWrappers::collect(ListType* listType)
CSSRule* cssRule = listType->item(i);
switch (cssRule->type()) {
case CSSRule::IMPORT_RULE:
- collect(static_cast<CSSImportRule*>(cssRule)->styleSheet());
+ collect(toCSSImportRule(cssRule)->styleSheet());
break;
case CSSRule::MEDIA_RULE:
- collect(static_cast<CSSMediaRule*>(cssRule));
+ collect(toCSSMediaRule(cssRule));
break;
case CSSRule::SUPPORTS_RULE:
- collect(static_cast<CSSSupportsRule*>(cssRule));
+ collect(toCSSSupportsRule(cssRule));
break;
case CSSRule::WEBKIT_REGION_RULE:
- collect(static_cast<CSSRegionRule*>(cssRule));
- break;
- case CSSRule::HOST_RULE:
- collect(static_cast<CSSHostRule*>(cssRule));
+ collect(toCSSRegionRule(cssRule));
break;
case CSSRule::STYLE_RULE:
- m_styleRuleToCSSOMWrapperMap.add(static_cast<CSSStyleRule*>(cssRule)->styleRule(), static_cast<CSSStyleRule*>(cssRule));
+ m_styleRuleToCSSOMWrapperMap.add(toCSSStyleRule(cssRule)->styleRule(), toCSSStyleRule(cssRule));
break;
default:
break;
@@ -105,17 +101,17 @@ void InspectorCSSOMWrappers::collectFromStyleSheets(const Vector<RefPtr<CSSStyle
void InspectorCSSOMWrappers::collectFromStyleEngine(StyleEngine* styleSheetCollection)
{
- collectFromStyleSheets(styleSheetCollection->activeAuthorStyleSheets());
- collect(styleSheetCollection->pageUserSheet());
- collectFromStyleSheets(styleSheetCollection->injectedUserStyleSheets());
- collectFromStyleSheets(styleSheetCollection->documentUserStyleSheets());
+ Vector<const Vector<RefPtr<CSSStyleSheet> >*> activeAuthorStyleSheets;
+ styleSheetCollection->getActiveAuthorStyleSheets(activeAuthorStyleSheets);
+ for (size_t i = 0; i < activeAuthorStyleSheets.size(); ++i)
+ collectFromStyleSheets(*activeAuthorStyleSheets[i]);
}
CSSStyleRule* InspectorCSSOMWrappers::getWrapperForRuleInSheets(StyleRule* rule, StyleEngine* styleSheetCollection)
{
if (m_styleRuleToCSSOMWrapperMap.isEmpty()) {
- collectFromStyleSheetContents(m_styleSheetCSSOMWrapperSet, CSSDefaultStyleSheets::simpleDefaultStyleSheet);
collectFromStyleSheetContents(m_styleSheetCSSOMWrapperSet, CSSDefaultStyleSheets::defaultStyleSheet);
+ collectFromStyleSheetContents(m_styleSheetCSSOMWrapperSet, CSSDefaultStyleSheets::viewportStyleSheet);
collectFromStyleSheetContents(m_styleSheetCSSOMWrapperSet, CSSDefaultStyleSheets::quirksStyleSheet);
collectFromStyleSheetContents(m_styleSheetCSSOMWrapperSet, CSSDefaultStyleSheets::svgStyleSheet);
collectFromStyleSheetContents(m_styleSheetCSSOMWrapperSet, CSSDefaultStyleSheets::mediaControlsStyleSheet);
diff --git a/chromium/third_party/WebKit/Source/core/css/LengthFunctions.cpp b/chromium/third_party/WebKit/Source/core/css/LengthFunctions.cpp
deleted file mode 100644
index 3a91ce20444..00000000000
--- a/chromium/third_party/WebKit/Source/core/css/LengthFunctions.cpp
+++ /dev/null
@@ -1,145 +0,0 @@
-/*
- Copyright (C) 1999 Lars Knoll (knoll@kde.org)
- Copyright (C) 2006, 2008 Apple Inc. All rights reserved.
- Copyright (C) 2011 Rik Cabanier (cabanier@adobe.com)
- Copyright (C) 2011 Adobe Systems Incorporated. All rights reserved.
- Copyright (C) 2012 Motorola Mobility, Inc. All rights reserved.
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include "config.h"
-#include "core/css/LengthFunctions.h"
-
-#include "core/platform/LayoutUnit.h"
-#include "core/platform/Length.h"
-#include "core/rendering/RenderView.h"
-
-namespace WebCore {
-
-int minimumIntValueForLength(const Length& length, LayoutUnit maximumValue, RenderView* renderView, bool roundPercentages)
-{
- return static_cast<int>(minimumValueForLength(length, maximumValue, renderView, roundPercentages));
-}
-
-int intValueForLength(const Length& length, LayoutUnit maximumValue, RenderView* renderView, bool roundPercentages)
-{
- return static_cast<int>(valueForLength(length, maximumValue, renderView, roundPercentages));
-}
-
-LayoutUnit minimumValueForLength(const Length& length, LayoutUnit maximumValue, RenderView* renderView, bool roundPercentages)
-{
- switch (length.type()) {
- case Fixed:
- return length.value();
- case Percent:
- if (roundPercentages)
- return static_cast<LayoutUnit>(round(maximumValue * length.percent() / 100.0f));
- // Don't remove the extra cast to float. It is needed for rounding on 32-bit Intel machines that use the FPU stack.
- return static_cast<float>(maximumValue * length.percent() / 100.0f);
- case Calculated:
- return length.nonNanCalculatedValue(maximumValue);
- case ViewportPercentageWidth:
- return renderView ? renderView->viewportPercentageWidth(length.viewportPercentageLength()) : LayoutUnit(0);
- case ViewportPercentageHeight:
- return renderView ? renderView->viewportPercentageHeight(length.viewportPercentageLength()) : LayoutUnit(0);
- case ViewportPercentageMin:
- return renderView ? renderView->viewportPercentageMin(length.viewportPercentageLength()) : LayoutUnit(0);
- case ViewportPercentageMax:
- return renderView ? renderView->viewportPercentageMax(length.viewportPercentageLength()) : LayoutUnit(0);
- case FillAvailable:
- case Auto:
- return 0;
- case Relative:
- case Intrinsic:
- case MinIntrinsic:
- case MinContent:
- case MaxContent:
- case FitContent:
- case ExtendToZoom:
- case Undefined:
- ASSERT_NOT_REACHED();
- return 0;
- }
- ASSERT_NOT_REACHED();
- return 0;
-}
-
-LayoutUnit valueForLength(const Length& length, LayoutUnit maximumValue, RenderView* renderView, bool roundPercentages)
-{
- switch (length.type()) {
- case Fixed:
- case Percent:
- case Calculated:
- case ViewportPercentageWidth:
- case ViewportPercentageHeight:
- case ViewportPercentageMin:
- case ViewportPercentageMax:
- return minimumValueForLength(length, maximumValue, renderView, roundPercentages);
- case FillAvailable:
- case Auto:
- return maximumValue;
- case Relative:
- case Intrinsic:
- case MinIntrinsic:
- case MinContent:
- case MaxContent:
- case FitContent:
- case ExtendToZoom:
- case Undefined:
- ASSERT_NOT_REACHED();
- return 0;
- }
- ASSERT_NOT_REACHED();
- return 0;
-}
-
-float floatValueForLength(const Length& length, float maximumValue, RenderView* renderView)
-{
- switch (length.type()) {
- case Fixed:
- return length.getFloatValue();
- case Percent:
- return static_cast<float>(maximumValue * length.percent() / 100.0f);
- case FillAvailable:
- case Auto:
- return static_cast<float>(maximumValue);
- case Calculated:
- return length.nonNanCalculatedValue(maximumValue);
- case ViewportPercentageWidth:
- return renderView ? static_cast<int>(renderView->viewportPercentageWidth(length.viewportPercentageLength())) : 0;
- case ViewportPercentageHeight:
- return renderView ? static_cast<int>(renderView->viewportPercentageHeight(length.viewportPercentageLength())) : 0;
- case ViewportPercentageMin:
- return renderView ? static_cast<int>(renderView->viewportPercentageMin(length.viewportPercentageLength())) : 0;
- case ViewportPercentageMax:
- return renderView ? static_cast<int>(renderView->viewportPercentageMax(length.viewportPercentageLength())) : 0;
- case Relative:
- case Intrinsic:
- case MinIntrinsic:
- case MinContent:
- case MaxContent:
- case FitContent:
- case ExtendToZoom:
- case Undefined:
- ASSERT_NOT_REACHED();
- return 0;
- }
- ASSERT_NOT_REACHED();
- return 0;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/css/LengthFunctions.h b/chromium/third_party/WebKit/Source/core/css/LengthFunctions.h
deleted file mode 100644
index 89adc48f6d6..00000000000
--- a/chromium/third_party/WebKit/Source/core/css/LengthFunctions.h
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- Copyright (C) 1999 Lars Knoll (knoll@kde.org)
- Copyright (C) 2006, 2008 Apple Inc. All rights reserved.
- Copyright (C) 2011 Rik Cabanier (cabanier@adobe.com)
- Copyright (C) 2011 Adobe Systems Incorporated. All rights reserved.
- Copyright (C) 2012 Motorola Mobility, Inc. All rights reserved.
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#ifndef LengthFunctions_h
-#define LengthFunctions_h
-
-namespace WebCore {
-
-class LayoutUnit;
-class RenderView;
-struct Length;
-
-int minimumIntValueForLength(const Length&, LayoutUnit maximumValue, RenderView* = 0, bool roundPercentages = false);
-int intValueForLength(const Length&, LayoutUnit maximumValue, RenderView* = 0, bool roundPercentages = false);
-LayoutUnit minimumValueForLength(const Length&, LayoutUnit maximumValue, RenderView* = 0, bool roundPercentages = false);
-LayoutUnit valueForLength(const Length&, LayoutUnit maximumValue, RenderView* = 0, bool roundPercentages = false);
-float floatValueForLength(const Length&, float maximumValue, RenderView* = 0);
-
-} // namespace WebCore
-
-#endif // LengthFunctions_h
diff --git a/chromium/third_party/WebKit/Source/core/css/MediaList.cpp b/chromium/third_party/WebKit/Source/core/css/MediaList.cpp
index 607ca4af3e7..4a4442fb83d 100644
--- a/chromium/third_party/WebKit/Source/core/css/MediaList.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/MediaList.cpp
@@ -27,8 +27,7 @@
#include "core/css/MediaQuery.h"
#include "core/css/MediaQueryExp.h"
#include "core/dom/Document.h"
-#include "core/dom/ExceptionCode.h"
-#include "core/page/DOMWindow.h"
+#include "core/frame/DOMWindow.h"
#include "wtf/text/StringBuilder.h"
namespace WebCore {
@@ -74,7 +73,7 @@ PassRefPtr<MediaQuerySet> MediaQuerySet::create(const String& mediaString)
if (mediaString.isEmpty())
return MediaQuerySet::create();
- CSSParser parser(CSSStrictMode);
+ CSSParser parser(HTMLStandardMode);
return parser.parseMediaQueryList(mediaString);
}
@@ -196,26 +195,26 @@ String MediaList::item(unsigned index) const
return String();
}
-void MediaList::deleteMedium(const String& medium, ExceptionState& es)
+void MediaList::deleteMedium(const String& medium, ExceptionState& exceptionState)
{
CSSStyleSheet::RuleMutationScope mutationScope(m_parentRule);
bool success = m_mediaQueries->remove(medium);
if (!success) {
- es.throwDOMException(NotFoundError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
return;
}
if (m_parentStyleSheet)
m_parentStyleSheet->didMutate();
}
-void MediaList::appendMedium(const String& medium, ExceptionState& es)
+void MediaList::appendMedium(const String& medium, ExceptionState& exceptionState)
{
CSSStyleSheet::RuleMutationScope mutationScope(m_parentRule);
bool success = m_mediaQueries->add(medium);
if (!success) {
- es.throwDOMException(InvalidCharacterError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidCharacterError);
return;
}
diff --git a/chromium/third_party/WebKit/Source/core/css/MediaQuery.cpp b/chromium/third_party/WebKit/Source/core/css/MediaQuery.cpp
index 16f08b1d4c9..681ac137fa2 100644
--- a/chromium/third_party/WebKit/Source/core/css/MediaQuery.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/MediaQuery.cpp
@@ -73,7 +73,7 @@ static bool expressionCompare(const OwnPtr<MediaQueryExp>& a, const OwnPtr<Media
return codePointCompare(a->serialize(), b->serialize()) < 0;
}
-MediaQuery::MediaQuery(Restrictor r, const String& mediaType, PassOwnPtr<ExpressionVector> expressions)
+MediaQuery::MediaQuery(Restrictor r, const AtomicString& mediaType, PassOwnPtr<ExpressionVector> expressions)
: m_restrictor(r)
, m_mediaType(mediaType.lower())
, m_expressions(expressions)
diff --git a/chromium/third_party/WebKit/Source/core/css/MediaQuery.h b/chromium/third_party/WebKit/Source/core/css/MediaQuery.h
index 96a7b7c2488..fa5463ee7df 100644
--- a/chromium/third_party/WebKit/Source/core/css/MediaQuery.h
+++ b/chromium/third_party/WebKit/Source/core/css/MediaQuery.h
@@ -46,12 +46,12 @@ public:
Only, Not, None
};
- MediaQuery(Restrictor, const String& mediaType, PassOwnPtr<ExpressionVector> exprs);
+ MediaQuery(Restrictor, const AtomicString& mediaType, PassOwnPtr<ExpressionVector> exprs);
~MediaQuery();
Restrictor restrictor() const { return m_restrictor; }
const ExpressionVector& expressions() const { return *m_expressions; }
- String mediaType() const { return m_mediaType; }
+ const AtomicString& mediaType() const { return m_mediaType; }
bool operator==(const MediaQuery& other) const;
String cssText() const;
@@ -61,7 +61,7 @@ private:
MediaQuery(const MediaQuery&);
Restrictor m_restrictor;
- String m_mediaType;
+ AtomicString m_mediaType;
OwnPtr<ExpressionVector> m_expressions;
String m_serializationCache;
diff --git a/chromium/third_party/WebKit/Source/core/css/MediaQueryEvaluator.cpp b/chromium/third_party/WebKit/Source/core/css/MediaQueryEvaluator.cpp
index bf07d2d0f86..5673e6e98fc 100644
--- a/chromium/third_party/WebKit/Source/core/css/MediaQueryEvaluator.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/MediaQueryEvaluator.cpp
@@ -34,21 +34,22 @@
#include "core/css/CSSAspectRatioValue.h"
#include "core/css/CSSHelper.h"
#include "core/css/CSSPrimitiveValue.h"
+#include "core/css/CSSToLengthConversionData.h"
#include "core/css/MediaFeatureNames.h"
#include "core/css/MediaList.h"
#include "core/css/MediaQuery.h"
-#include "core/css/MediaQueryExp.h"
-#include "core/css/resolver/StyleResolver.h"
+#include "core/css/resolver/MediaQueryResult.h"
#include "core/dom/NodeRenderStyle.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameView.h"
+#include "core/inspector/InspectorInstrumentation.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
#include "core/page/Page.h"
-#include "core/page/Settings.h"
-#include "core/platform/PlatformScreen.h"
-#include "core/platform/graphics/FloatRect.h"
+#include "core/frame/Settings.h"
#include "core/rendering/RenderLayerCompositor.h"
#include "core/rendering/RenderView.h"
#include "core/rendering/style/RenderStyle.h"
+#include "platform/PlatformScreen.h"
+#include "platform/geometry/FloatRect.h"
#include "wtf/HashMap.h"
namespace WebCore {
@@ -88,7 +89,7 @@ MediaQueryEvaluator::MediaQueryEvaluator(const AtomicString& acceptedMediaType,
: m_mediaType(acceptedMediaType)
, m_frame(frame)
, m_style(style)
- , m_expResult(false) // doesn't matter when we have m_frame and m_style
+ , m_expResult(false) // Doesn't matter when we have m_frame and m_style.
{
}
@@ -117,14 +118,14 @@ static bool applyRestrictor(MediaQuery::Restrictor r, bool value)
return r == MediaQuery::Not ? !value : value;
}
-bool MediaQueryEvaluator::eval(const MediaQuerySet* querySet, StyleResolver* styleResolver) const
+bool MediaQueryEvaluator::eval(const MediaQuerySet* querySet, MediaQueryResultList* viewportDependentMediaQueryResults) const
{
if (!querySet)
return true;
const Vector<OwnPtr<MediaQuery> >& queries = querySet->queryVector();
if (!queries.size())
- return true; // empty query list evaluates to true
+ return true; // Empty query list evaluates to true.
// Iterate over queries, stop if any of them eval to true (OR semantics).
bool result = false;
@@ -137,11 +138,8 @@ bool MediaQueryEvaluator::eval(const MediaQuerySet* querySet, StyleResolver* sty
size_t j = 0;
for (; j < expressions.size(); ++j) {
bool exprResult = eval(expressions.at(j).get());
- // FIXME: Instead of storing these on StyleResolver, we should store them locally
- // and then any client of this method can grab at them afterwords.
- // Alternatively we could use an explicit out-parameter of this method.
- if (styleResolver && expressions.at(j)->isViewportDependent())
- styleResolver->addViewportDependentMediaQueryResult(expressions.at(j).get(), exprResult);
+ if (viewportDependentMediaQueryResults && expressions.at(j)->isViewportDependent())
+ viewportDependentMediaQueryResults->append(adoptRef(new MediaQueryResult(*expressions.at(j), exprResult)));
if (!exprResult)
break;
}
@@ -172,7 +170,7 @@ bool compareValue(T a, T b, MediaFeaturePrefix op)
static bool compareAspectRatioValue(CSSValue* value, int width, int height, MediaFeaturePrefix op)
{
if (value->isAspectRatioValue()) {
- CSSAspectRatioValue* aspectRatio = static_cast<CSSAspectRatioValue*>(value);
+ CSSAspectRatioValue* aspectRatio = toCSSAspectRatioValue(value);
return compareValue(width * static_cast<int>(aspectRatio->denominatorValue()), height * static_cast<int>(aspectRatio->numeratorValue()), op);
}
@@ -191,7 +189,7 @@ static bool numberValue(CSSValue* value, float& result)
static bool colorMediaFeatureEval(CSSValue* value, RenderStyle*, Frame* frame, MediaFeaturePrefix op)
{
- int bitsPerComponent = screenDepthPerComponent(frame->page()->mainFrame()->view());
+ int bitsPerComponent = screenDepthPerComponent(frame->view());
float number;
if (value)
return numberValue(value, number) && compareValue(bitsPerComponent, static_cast<int>(number), op);
@@ -206,13 +204,14 @@ static bool colorIndexMediaFeatureEval(CSSValue* value, RenderStyle*, Frame*, Me
if (!value)
return false;
+ // Acording to spec, if the device does not use a color lookup table, the value is zero.
float number;
return numberValue(value, number) && compareValue(0, static_cast<int>(number), op);
}
static bool monochromeMediaFeatureEval(CSSValue* value, RenderStyle* style, Frame* frame, MediaFeaturePrefix op)
{
- if (!screenIsMonochrome(frame->page()->mainFrame()->view())) {
+ if (!screenIsMonochrome(frame->view())) {
if (value) {
float number;
return numberValue(value, number) && compareValue(0, static_cast<int>(number), op);
@@ -252,25 +251,26 @@ static bool aspectRatioMediaFeatureEval(CSSValue* value, RenderStyle*, Frame* fr
}
// ({,min-,max-}aspect-ratio)
- // assume if we have a device, its aspect ratio is non-zero
+ // assume if we have a device, its aspect ratio is non-zero.
return true;
}
static bool deviceAspectRatioMediaFeatureEval(CSSValue* value, RenderStyle*, Frame* frame, MediaFeaturePrefix op)
{
if (value) {
- FloatRect sg = screenRect(frame->page()->mainFrame()->view());
+ FloatRect sg = screenRect(frame->view());
return compareAspectRatioValue(value, static_cast<int>(sg.width()), static_cast<int>(sg.height()), op);
}
// ({,min-,max-}device-aspect-ratio)
- // assume if we have a device, its aspect ratio is non-zero
+ // assume if we have a device, its aspect ratio is non-zero.
return true;
}
static bool evalResolution(CSSValue* value, Frame* frame, MediaFeaturePrefix op)
{
- // FIXME: Possibly handle other media types than 'screen' and 'print'.
+ // According to MQ4, only 'screen', 'print' and 'speech' may match.
+ // FIXME: What should speech match? https://www.w3.org/Style/CSS/Tracker/issues/348
float actualResolution = 0;
// This checks the actual media type applied to the document, and we know
@@ -348,9 +348,9 @@ static bool computeLength(CSSValue* value, bool strict, RenderStyle* initialStyl
}
if (primitiveValue->isLength()) {
- // Relative (like EM) and root relative (like REM) units are always resolved against the initial values
- // for media queries, hence the two initialStyle parameters.
- result = primitiveValue->computeLength<int>(initialStyle, initialStyle, 1.0 /* multiplier */, true /* computingFontSize */);
+ // Relative (like EM) and root relative (like REM) units are always resolved against
+ // the initial values for media queries, hence the two initialStyle parameters.
+ result = primitiveValue->computeLength<int>(CSSToLengthConversionData(initialStyle, initialStyle, 1.0 /* zoom */, true /* computingFontSize */));
return true;
}
@@ -360,11 +360,13 @@ static bool computeLength(CSSValue* value, bool strict, RenderStyle* initialStyl
static bool deviceHeightMediaFeatureEval(CSSValue* value, RenderStyle* style, Frame* frame, MediaFeaturePrefix op)
{
if (value) {
- FloatRect sg = screenRect(frame->page()->mainFrame()->view());
int length;
- long height = sg.height();
- InspectorInstrumentation::applyScreenHeightOverride(frame, &height);
- return computeLength(value, !frame->document()->inQuirksMode(), style, length) && compareValue(static_cast<int>(height), length, op);
+ if (!computeLength(value, !frame->document()->inQuirksMode(), style, length))
+ return false;
+ int height = static_cast<int>(screenRect(frame->view()).height());
+ if (frame->settings()->reportScreenSizeInPhysicalPixelsQuirk())
+ height = lroundf(height * frame->page()->deviceScaleFactor());
+ return compareValue(height, length, op);
}
// ({,min-,max-}device-height)
// assume if we have a device, assume non-zero
@@ -374,11 +376,13 @@ static bool deviceHeightMediaFeatureEval(CSSValue* value, RenderStyle* style, Fr
static bool deviceWidthMediaFeatureEval(CSSValue* value, RenderStyle* style, Frame* frame, MediaFeaturePrefix op)
{
if (value) {
- FloatRect sg = screenRect(frame->page()->mainFrame()->view());
int length;
- long width = sg.width();
- InspectorInstrumentation::applyScreenWidthOverride(frame, &width);
- return computeLength(value, !frame->document()->inQuirksMode(), style, length) && compareValue(static_cast<int>(width), length, op);
+ if (!computeLength(value, !frame->document()->inQuirksMode(), style, length))
+ return false;
+ int width = static_cast<int>(screenRect(frame->view()).width());
+ if (frame->settings()->reportScreenSizeInPhysicalPixelsQuirk())
+ width = lroundf(width * frame->page()->deviceScaleFactor());
+ return compareValue(width, length, op);
}
// ({,min-,max-}device-width)
// assume if we have a device, assume non-zero
@@ -415,7 +419,7 @@ static bool widthMediaFeatureEval(CSSValue* value, RenderStyle* style, Frame* fr
return width;
}
-// rest of the functions are trampolines which set the prefix according to the media feature expression used
+// Rest of the functions are trampolines which set the prefix according to the media feature expression used.
static bool minColorMediaFeatureEval(CSSValue* value, RenderStyle* style, Frame* frame, MediaFeaturePrefix)
{
@@ -575,9 +579,8 @@ static bool transform3dMediaFeatureEval(CSSValue* value, RenderStyle*, Frame* fr
return returnValueIfNoParameter;
}
-static bool viewModeMediaFeatureEval(CSSValue* value, RenderStyle*, Frame* frame, MediaFeaturePrefix op)
+static bool viewModeMediaFeatureEval(CSSValue* value, RenderStyle*, Frame* frame, MediaFeaturePrefix)
{
- UNUSED_PARAM(op);
if (!value)
return true;
@@ -646,7 +649,7 @@ static bool pointerMediaFeatureEval(CSSValue* value, RenderStyle*, Frame* frame,
static bool scanMediaFeatureEval(CSSValue* value, RenderStyle*, Frame* frame, MediaFeaturePrefix)
{
- // Scan only applies to tv media.
+ // Scan only applies to 'tv' media.
if (!equalIgnoringCase(frame->view()->mediaType(), "tv"))
return false;
@@ -680,9 +683,8 @@ bool MediaQueryEvaluator::eval(const MediaQueryExp* expr) const
if (!gFunctionMap)
createFunctionMap();
- // call the media feature evaluation function. Assume no prefix
- // and let trampoline functions override the prefix if prefix is
- // used
+ // Call the media feature evaluation function. Assume no prefix and let
+ // trampoline functions override the prefix if prefix is used.
EvalFunc func = gFunctionMap->get(expr->mediaFeature().impl());
if (func)
return func(expr->value(), m_style.get(), m_frame, NoPrefix);
diff --git a/chromium/third_party/WebKit/Source/core/css/MediaQueryEvaluator.h b/chromium/third_party/WebKit/Source/core/css/MediaQueryEvaluator.h
index eb67ac718d9..60bd9cd78f2 100644
--- a/chromium/third_party/WebKit/Source/core/css/MediaQueryEvaluator.h
+++ b/chromium/third_party/WebKit/Source/core/css/MediaQueryEvaluator.h
@@ -33,9 +33,11 @@
namespace WebCore {
class Frame;
class MediaQueryExp;
+class MediaQueryResult;
class MediaQuerySet;
class RenderStyle;
-class StyleResolver;
+
+typedef Vector<RefPtr<MediaQueryResult> > MediaQueryResultList;
/**
* Class that evaluates css media queries as defined in
@@ -74,7 +76,7 @@ public:
bool mediaTypeMatchSpecific(const char* mediaTypeToMatch) const;
/** Evaluates a list of media queries */
- bool eval(const MediaQuerySet*, StyleResolver* = 0) const;
+ bool eval(const MediaQuerySet*, MediaQueryResultList* = 0) const;
/** Evaluates media query subexpression, ie "and (media-feature: value)" part */
bool eval(const MediaQueryExp*) const;
diff --git a/chromium/third_party/WebKit/Source/core/css/MediaQueryExp.cpp b/chromium/third_party/WebKit/Source/core/css/MediaQueryExp.cpp
index d2ccd174840..05c0e5cffd7 100644
--- a/chromium/third_party/WebKit/Source/core/css/MediaQueryExp.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/MediaQueryExp.cpp
@@ -192,6 +192,8 @@ bool MediaQueryExp::isViewportDependent() const
|| m_mediaFeature == MediaFeatureNames::orientationMediaFeature
|| m_mediaFeature == MediaFeatureNames::aspectRatioMediaFeature
|| m_mediaFeature == MediaFeatureNames::minAspectRatioMediaFeature
+ || m_mediaFeature == MediaFeatureNames::devicePixelRatioMediaFeature
+ || m_mediaFeature == MediaFeatureNames::resolutionMediaFeature
|| m_mediaFeature == MediaFeatureNames::maxAspectRatioMediaFeature;
}
diff --git a/chromium/third_party/WebKit/Source/core/css/MediaQueryListListener.idl b/chromium/third_party/WebKit/Source/core/css/MediaQueryListListener.idl
deleted file mode 100644
index 755c4163546..00000000000
--- a/chromium/third_party/WebKit/Source/core/css/MediaQueryListListener.idl
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-[
-
- CPPPureInterface
-] interface MediaQueryListListener {
- void queryChanged([Default=Undefined] optional MediaQueryList list);
-};
diff --git a/chromium/third_party/WebKit/Source/core/css/MediaQueryMatcher.cpp b/chromium/third_party/WebKit/Source/core/css/MediaQueryMatcher.cpp
index bd2dd5c77a2..9051099e17c 100644
--- a/chromium/third_party/WebKit/Source/core/css/MediaQueryMatcher.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/MediaQueryMatcher.cpp
@@ -26,8 +26,8 @@
#include "core/css/MediaQueryListListener.h"
#include "core/css/resolver/StyleResolver.h"
#include "core/dom/Document.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameView.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
namespace WebCore {
@@ -83,11 +83,8 @@ PassOwnPtr<MediaQueryEvaluator> MediaQueryMatcher::prepareEvaluator() const
if (!documentElement)
return nullptr;
- StyleResolver* styleResolver = m_document->styleResolver();
- if (!styleResolver)
- return nullptr;
-
- RefPtr<RenderStyle> rootStyle = styleResolver->styleForElement(documentElement, 0 /*defaultParent*/, DisallowStyleSharing, MatchOnlyUserAgentRules);
+ StyleResolver& styleResolver = m_document->ensureStyleResolver();
+ RefPtr<RenderStyle> rootStyle = styleResolver.styleForElement(documentElement, 0 /*defaultParent*/, DisallowStyleSharing, MatchOnlyUserAgentRules);
return adoptPtr(new MediaQueryEvaluator(mediaType(), m_document->frame(), rootStyle.get()));
}
diff --git a/chromium/third_party/WebKit/Source/core/css/PageRuleCollector.cpp b/chromium/third_party/WebKit/Source/core/css/PageRuleCollector.cpp
index 65c409eaa1f..e4494526d30 100644
--- a/chromium/third_party/WebKit/Source/core/css/PageRuleCollector.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/PageRuleCollector.cpp
@@ -40,10 +40,11 @@ static inline bool comparePageRules(const StyleRulePage* r1, const StyleRulePage
return r1->selector()->specificity() < r2->selector()->specificity();
}
-bool PageRuleCollector::isLeftPage(int pageIndex) const
+bool PageRuleCollector::isLeftPage(const RenderStyle* rootElementStyle, int pageIndex) const
{
bool isFirstPageLeft = false;
- if (!m_context.rootElementStyle() || !m_context.rootElementStyle()->isLeftToRightDirection())
+ ASSERT(rootElementStyle);
+ if (!rootElementStyle->isLeftToRightDirection())
isFirstPageLeft = true;
return (pageIndex + (isFirstPageLeft ? 1 : 0)) % 2;
@@ -61,9 +62,8 @@ String PageRuleCollector::pageName(int /* pageIndex */) const
return "";
}
-PageRuleCollector::PageRuleCollector(const ElementResolveContext& context, int pageIndex)
- : m_context(context)
- , m_isLeftPage(isLeftPage(pageIndex))
+PageRuleCollector::PageRuleCollector(const RenderStyle* rootElementStyle, int pageIndex)
+ : m_isLeftPage(isLeftPage(rootElementStyle, pageIndex))
, m_isFirstPage(isFirstPage(pageIndex))
, m_pageName(pageName(pageIndex)) { }
diff --git a/chromium/third_party/WebKit/Source/core/css/PageRuleCollector.h b/chromium/third_party/WebKit/Source/core/css/PageRuleCollector.h
index 296ee6fd1ea..83251612aaf 100644
--- a/chromium/third_party/WebKit/Source/core/css/PageRuleCollector.h
+++ b/chromium/third_party/WebKit/Source/core/css/PageRuleCollector.h
@@ -32,20 +32,19 @@ class StyleRulePage;
class PageRuleCollector {
public:
- PageRuleCollector(const ElementResolveContext&, int pageIndex);
+ PageRuleCollector(const RenderStyle* rootElementStyle, int pageIndex);
void matchPageRules(RuleSet* rules);
MatchResult& matchedResult() { return m_result; }
private:
- bool isLeftPage(int pageIndex) const;
- bool isRightPage(int pageIndex) const { return !isLeftPage(pageIndex); }
+ bool isLeftPage(const RenderStyle* rootElementStyle, int pageIndex) const;
+ bool isRightPage(const RenderStyle* rootElementStyle, int pageIndex) const { return !isLeftPage(rootElementStyle, pageIndex); }
bool isFirstPage(int pageIndex) const;
String pageName(int pageIndex) const;
void matchPageRulesForList(Vector<StyleRulePage*>& matchedRules, const Vector<StyleRulePage*>& rules, bool isLeftPage, bool isFirstPage, const String& pageName);
- const ElementResolveContext& m_context;
const bool m_isLeftPage;
const bool m_isFirstPage;
const String m_pageName;
diff --git a/chromium/third_party/WebKit/Source/core/css/Pair.h b/chromium/third_party/WebKit/Source/core/css/Pair.h
index 2c1940f0b52..fc2edaa828b 100644
--- a/chromium/third_party/WebKit/Source/core/css/Pair.h
+++ b/chromium/third_party/WebKit/Source/core/css/Pair.h
@@ -32,7 +32,7 @@ namespace WebCore {
// and border-spacing (all of which are space-separated sets of two values). At the moment we are only using it for
// border-radius and background-size, but (FIXME) border-spacing and background-position could be converted over to use
// it (eliminating some extra -webkit- internal properties).
-class Pair : public RefCounted<Pair> {
+class Pair FINAL : public RefCounted<Pair> {
public:
enum IdenticalValuesPolicy { DropIdenticalValues, KeepIdenticalValues };
@@ -44,7 +44,6 @@ public:
{
return adoptRef(new Pair(first, second, identicalValuesPolicy));
}
- virtual ~Pair() { }
CSSPrimitiveValue* first() const { return m_first.get(); }
CSSPrimitiveValue* second() const { return m_second.get(); }
diff --git a/chromium/third_party/WebKit/Source/core/css/PropertySetCSSStyleDeclaration.cpp b/chromium/third_party/WebKit/Source/core/css/PropertySetCSSStyleDeclaration.cpp
index 900dc36f1e0..e30610ab3a2 100644
--- a/chromium/third_party/WebKit/Source/core/css/PropertySetCSSStyleDeclaration.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/PropertySetCSSStyleDeclaration.cpp
@@ -44,6 +44,7 @@ class StyleAttributeMutationScope {
public:
StyleAttributeMutationScope(PropertySetCSSStyleDeclaration* decl)
{
+ InspectorInstrumentation::willMutateStyle(decl);
++s_scopeCount;
if (s_scopeCount != 1) {
@@ -59,7 +60,7 @@ public:
bool shouldReadOldValue = false;
- m_mutationRecipients = MutationObserverInterestGroup::createForAttributesMutation(s_currentDecl->parentElement(), HTMLNames::styleAttr);
+ m_mutationRecipients = MutationObserverInterestGroup::createForAttributesMutation(*s_currentDecl->parentElement(), HTMLNames::styleAttr);
if (m_mutationRecipients && m_mutationRecipients->isOldValueRequested())
shouldReadOldValue = true;
@@ -83,16 +84,18 @@ public:
m_mutationRecipients->enqueueMutationRecord(m_mutation);
s_shouldDeliver = false;
- if (!s_shouldNotifyInspector) {
- s_currentDecl = 0;
- return;
- }
+
// We have to clear internal state before calling Inspector's code.
PropertySetCSSStyleDeclaration* localCopyStyleDecl = s_currentDecl;
s_currentDecl = 0;
+ InspectorInstrumentation::didMutateStyle(localCopyStyleDecl, localCopyStyleDecl->parentElement());
+
+ if (!s_shouldNotifyInspector)
+ return;
+
s_shouldNotifyInspector = false;
if (localCopyStyleDecl->parentElement())
- InspectorInstrumentation::didInvalidateStyleAttr(&localCopyStyleDecl->parentElement()->document(), localCopyStyleDecl->parentElement());
+ InspectorInstrumentation::didInvalidateStyleAttr(localCopyStyleDecl->parentElement());
}
void enqueueMutationRecord()
@@ -149,12 +152,12 @@ String PropertySetCSSStyleDeclaration::cssText() const
return m_propertySet->asText();
}
-void PropertySetCSSStyleDeclaration::setCssText(const String& text, ExceptionState& es)
+void PropertySetCSSStyleDeclaration::setCSSText(const String& text, ExceptionState& exceptionState)
{
StyleAttributeMutationScope mutationScope(this);
willMutate();
- // FIXME: Detect syntax errors and set es.
+ // FIXME: Detect syntax errors and set exceptionState.
m_propertySet->parseDeclaration(text, contextStyleSheet());
didMutate(PropertyChanged);
@@ -205,7 +208,7 @@ bool PropertySetCSSStyleDeclaration::isPropertyImplicit(const String& propertyNa
return m_propertySet->isPropertyImplicit(propertyID);
}
-void PropertySetCSSStyleDeclaration::setProperty(const String& propertyName, const String& value, const String& priority, ExceptionState& es)
+void PropertySetCSSStyleDeclaration::setProperty(const String& propertyName, const String& value, const String& priority, ExceptionState& exceptionState)
{
StyleAttributeMutationScope mutationScope(this);
CSSPropertyID propertyID = cssPropertyID(propertyName);
@@ -227,7 +230,7 @@ void PropertySetCSSStyleDeclaration::setProperty(const String& propertyName, con
}
}
-String PropertySetCSSStyleDeclaration::removeProperty(const String& propertyName, ExceptionState& es)
+String PropertySetCSSStyleDeclaration::removeProperty(const String& propertyName, ExceptionState& exceptionState)
{
StyleAttributeMutationScope mutationScope(this);
CSSPropertyID propertyID = cssPropertyID(propertyName);
@@ -256,7 +259,7 @@ String PropertySetCSSStyleDeclaration::getPropertyValueInternal(CSSPropertyID pr
return m_propertySet->getPropertyValue(propertyID);
}
-void PropertySetCSSStyleDeclaration::setPropertyInternal(CSSPropertyID propertyID, const String& value, bool important, ExceptionState& es)
+void PropertySetCSSStyleDeclaration::setPropertyInternal(CSSPropertyID propertyID, const String& value, bool important, ExceptionState&)
{
StyleAttributeMutationScope mutationScope(this);
willMutate();
@@ -281,7 +284,7 @@ String PropertySetCSSStyleDeclaration::variableValue(const AtomicString& name) c
return m_propertySet->variableValue(name);
}
-void PropertySetCSSStyleDeclaration::setVariableValue(const AtomicString& name, const String& value, ExceptionState&)
+bool PropertySetCSSStyleDeclaration::setVariableValue(const AtomicString& name, const String& value, ExceptionState&)
{
ASSERT(RuntimeEnabledFeatures::cssVariablesEnabled());
StyleAttributeMutationScope mutationScope(this);
@@ -290,6 +293,7 @@ void PropertySetCSSStyleDeclaration::setVariableValue(const AtomicString& name,
didMutate(changed ? PropertyChanged : NoChanges);
if (changed)
mutationScope.enqueueMutationRecord();
+ return changed;
}
bool PropertySetCSSStyleDeclaration::removeVariable(const AtomicString& name)
@@ -304,7 +308,7 @@ bool PropertySetCSSStyleDeclaration::removeVariable(const AtomicString& name)
return changed;
}
-void PropertySetCSSStyleDeclaration::clearVariables(ExceptionState&)
+bool PropertySetCSSStyleDeclaration::clearVariables(ExceptionState&)
{
ASSERT(RuntimeEnabledFeatures::cssVariablesEnabled());
StyleAttributeMutationScope mutationScope(this);
@@ -313,6 +317,12 @@ void PropertySetCSSStyleDeclaration::clearVariables(ExceptionState&)
didMutate(changed ? PropertyChanged : NoChanges);
if (changed)
mutationScope.enqueueMutationRecord();
+ return changed;
+}
+
+PassRefPtr<CSSVariablesIterator> PropertySetCSSStyleDeclaration::variablesIterator() const
+{
+ return m_propertySet->variablesIterator();
}
CSSValue* PropertySetCSSStyleDeclaration::cloneAndCacheForCSSOM(CSSValue* internalValue)
diff --git a/chromium/third_party/WebKit/Source/core/css/PropertySetCSSStyleDeclaration.h b/chromium/third_party/WebKit/Source/core/css/PropertySetCSSStyleDeclaration.h
index 4bb4c7fa8ae..20b36855afe 100644
--- a/chromium/third_party/WebKit/Source/core/css/PropertySetCSSStyleDeclaration.h
+++ b/chromium/third_party/WebKit/Source/core/css/PropertySetCSSStyleDeclaration.h
@@ -63,16 +63,17 @@ private:
virtual void setProperty(const String& propertyName, const String& value, const String& priority, ExceptionState&) OVERRIDE;
virtual String removeProperty(const String& propertyName, ExceptionState&) OVERRIDE;
virtual String cssText() const OVERRIDE;
- virtual void setCssText(const String&, ExceptionState&) OVERRIDE;
+ virtual void setCSSText(const String&, ExceptionState&) OVERRIDE;
virtual PassRefPtr<CSSValue> getPropertyCSSValueInternal(CSSPropertyID) OVERRIDE;
virtual String getPropertyValueInternal(CSSPropertyID) OVERRIDE;
virtual void setPropertyInternal(CSSPropertyID, const String& value, bool important, ExceptionState&) OVERRIDE;
virtual unsigned variableCount() const OVERRIDE;
virtual String variableValue(const AtomicString& name) const OVERRIDE;
- virtual void setVariableValue(const AtomicString& name, const String& value, ExceptionState&) OVERRIDE;
+ virtual bool setVariableValue(const AtomicString& name, const String& value, ExceptionState&) OVERRIDE;
virtual bool removeVariable(const AtomicString& name) OVERRIDE;
- virtual void clearVariables(ExceptionState&) OVERRIDE;
+ virtual bool clearVariables(ExceptionState&) OVERRIDE;
+ virtual PassRefPtr<CSSVariablesIterator> variablesIterator() const OVERRIDE;
virtual bool cssPropertyMatches(CSSPropertyID, const CSSValue*) const OVERRIDE;
virtual PassRefPtr<MutableStylePropertySet> copyProperties() const OVERRIDE;
diff --git a/chromium/third_party/WebKit/Source/core/css/PseudoStyleRequest.h b/chromium/third_party/WebKit/Source/core/css/PseudoStyleRequest.h
index c07cb2fe46a..11b93fc7eb7 100644
--- a/chromium/third_party/WebKit/Source/core/css/PseudoStyleRequest.h
+++ b/chromium/third_party/WebKit/Source/core/css/PseudoStyleRequest.h
@@ -22,8 +22,8 @@
#ifndef PseudoStyleRequest_h
#define PseudoStyleRequest_h
-#include "core/platform/ScrollTypes.h"
#include "core/rendering/style/RenderStyleConstants.h"
+#include "platform/scroll/ScrollTypes.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/css/RGBColor.h b/chromium/third_party/WebKit/Source/core/css/RGBColor.h
index 5cc591cbb30..5cd4697d4fb 100644
--- a/chromium/third_party/WebKit/Source/core/css/RGBColor.h
+++ b/chromium/third_party/WebKit/Source/core/css/RGBColor.h
@@ -27,7 +27,7 @@
#ifndef RGBColor_h
#define RGBColor_h
-#include "core/platform/graphics/Color.h"
+#include "platform/graphics/Color.h"
#include "wtf/RefCounted.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/css/RuleFeature.cpp b/chromium/third_party/WebKit/Source/core/css/RuleFeature.cpp
index 7d7879fb5ec..7c8f160ae43 100644
--- a/chromium/third_party/WebKit/Source/core/css/RuleFeature.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/RuleFeature.cpp
@@ -38,19 +38,16 @@ namespace WebCore {
void RuleFeatureSet::collectFeaturesFromSelector(const CSSSelector* selector)
{
if (selector->m_match == CSSSelector::Id)
- idsInRules.add(selector->value().impl());
+ idsInRules.add(selector->value());
else if (selector->m_match == CSSSelector::Class)
- classesInRules.add(selector->value().impl());
+ classesInRules.add(selector->value());
else if (selector->isAttributeSelector())
- attrsInRules.add(selector->attribute().localName().impl());
+ attrsInRules.add(selector->attribute().localName());
switch (selector->pseudoType()) {
case CSSSelector::PseudoFirstLine:
m_usesFirstLineRules = true;
break;
break;
- case CSSSelector::PseudoPart:
- attrsInRules.add(HTMLNames::partAttr.localName().impl());
- break;
case CSSSelector::PseudoHost:
collectFeaturesFromSelectorList(selector->selectorList());
break;
@@ -84,6 +81,7 @@ void RuleFeatureSet::add(const RuleFeatureSet& other)
siblingRules.append(other.siblingRules);
uncommonAttributeRules.append(other.uncommonAttributeRules);
m_usesFirstLineRules = m_usesFirstLineRules || other.m_usesFirstLineRules;
+ m_maxDirectAdjacentSelectors = std::max(m_maxDirectAdjacentSelectors, other.maxDirectAdjacentSelectors());
}
void RuleFeatureSet::clear()
@@ -94,6 +92,7 @@ void RuleFeatureSet::clear()
siblingRules.clear();
uncommonAttributeRules.clear();
m_usesFirstLineRules = false;
+ m_maxDirectAdjacentSelectors = 0;
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/css/RuleFeature.h b/chromium/third_party/WebKit/Source/core/css/RuleFeature.h
index c8d35fc9fa7..b51863c4289 100644
--- a/chromium/third_party/WebKit/Source/core/css/RuleFeature.h
+++ b/chromium/third_party/WebKit/Source/core/css/RuleFeature.h
@@ -48,6 +48,7 @@ class RuleFeatureSet {
public:
RuleFeatureSet()
: m_usesFirstLineRules(false)
+ , m_maxDirectAdjacentSelectors(0)
{ }
void add(const RuleFeatureSet&);
@@ -58,6 +59,9 @@ public:
bool usesSiblingRules() const { return !siblingRules.isEmpty(); }
bool usesFirstLineRules() const { return m_usesFirstLineRules; }
+ unsigned maxDirectAdjacentSelectors() const { return m_maxDirectAdjacentSelectors; }
+ void setMaxDirectAdjacentSelectors(unsigned value) { m_maxDirectAdjacentSelectors = std::max(value, m_maxDirectAdjacentSelectors); }
+
inline bool hasSelectorForAttribute(const AtomicString& attributeName) const
{
ASSERT(!attributeName.isEmpty());
@@ -85,6 +89,7 @@ private:
void collectFeaturesFromSelectorList(const CSSSelectorList*);
bool m_usesFirstLineRules;
+ unsigned m_maxDirectAdjacentSelectors;
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/css/RuleSet.cpp b/chromium/third_party/WebKit/Source/core/css/RuleSet.cpp
index 87fd2dc3ea7..f7a0325f543 100644
--- a/chromium/third_party/WebKit/Source/core/css/RuleSet.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/RuleSet.cpp
@@ -32,19 +32,15 @@
#include "HTMLNames.h"
#include "RuntimeEnabledFeatures.h"
#include "core/css/CSSFontSelector.h"
-#include "core/css/CSSKeyframesRule.h"
#include "core/css/CSSSelector.h"
#include "core/css/CSSSelectorList.h"
-#include "core/css/MediaQueryEvaluator.h"
#include "core/css/SelectorChecker.h"
#include "core/css/SelectorCheckerFastPath.h"
#include "core/css/SelectorFilter.h"
-#include "core/css/StyleRule.h"
#include "core/css/StyleRuleImport.h"
#include "core/css/StyleSheetContents.h"
-#include "core/css/resolver/StyleResolver.h"
#include "core/html/track/TextTrackCue.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/weborigin/SecurityOrigin.h"
namespace WebCore {
@@ -52,16 +48,6 @@ using namespace HTMLNames;
// -----------------------------------------------------------------
-static inline bool isDocumentScope(const ContainerNode* scope)
-{
- return !scope || scope->isDocumentNode();
-}
-
-static inline bool isScopingNodeInShadowTree(const ContainerNode* scopingNode)
-{
- return scopingNode && scopingNode->isInShadowTree();
-}
-
static inline bool isSelectorMatchingHTMLBasedOnRuleHash(const CSSSelector* selector)
{
ASSERT(selector);
@@ -224,18 +210,27 @@ RuleData::RuleData(StyleRule* rule, unsigned selectorIndex, unsigned position, A
static void collectFeaturesFromRuleData(RuleFeatureSet& features, const RuleData& ruleData)
{
bool foundSiblingSelector = false;
+ unsigned maxDirectAdjacentSelectors = 0;
for (const CSSSelector* selector = ruleData.selector(); selector; selector = selector->tagHistory()) {
features.collectFeaturesFromSelector(selector);
if (const CSSSelectorList* selectorList = selector->selectorList()) {
for (const CSSSelector* subSelector = selectorList->first(); subSelector; subSelector = CSSSelectorList::next(subSelector)) {
+ // FIXME: Shouldn't this be checking subSelector->isSiblingSelector()?
if (!foundSiblingSelector && selector->isSiblingSelector())
foundSiblingSelector = true;
+ if (subSelector->isDirectAdjacentSelector())
+ maxDirectAdjacentSelectors++;
features.collectFeaturesFromSelector(subSelector);
}
- } else if (!foundSiblingSelector && selector->isSiblingSelector())
- foundSiblingSelector = true;
+ } else {
+ if (!foundSiblingSelector && selector->isSiblingSelector())
+ foundSiblingSelector = true;
+ if (selector->isDirectAdjacentSelector())
+ maxDirectAdjacentSelectors++;
+ }
}
+ features.setMaxDirectAdjacentSelectors(maxDirectAdjacentSelectors);
if (foundSiblingSelector)
features.siblingRules.append(RuleFeature(ruleData.rule(), ruleData.selectorIndex(), ruleData.hasDocumentSecurityOrigin()));
if (ruleData.containsUncommonAttributeSelector())
@@ -263,8 +258,7 @@ bool RuleSet::findBestRuleSetAndAdd(const CSSSelector* component, RuleData& rule
return true;
}
if (component->isCustomPseudoElement()) {
- StringImpl* pseudoValue = component->pseudoType() == CSSSelector::PseudoPart ? component->argument().impl() : component->value().impl();
- addToRuleSet(pseudoValue, ensurePendingRules()->shadowPseudoElementRules, ruleData);
+ addToRuleSet(component->value().impl(), ensurePendingRules()->shadowPseudoElementRules, ruleData);
return true;
}
if (component->pseudoType() == CSSSelector::PseudoCue) {
@@ -325,6 +319,18 @@ void RuleSet::addViewportRule(StyleRuleViewport* rule)
m_viewportRules.append(rule);
}
+void RuleSet::addFontFaceRule(StyleRuleFontFace* rule)
+{
+ ensurePendingRules(); // So that m_fontFaceRules.shrinkToFit() gets called.
+ m_fontFaceRules.append(rule);
+}
+
+void RuleSet::addKeyframesRule(StyleRuleKeyframes* rule)
+{
+ ensurePendingRules(); // So that m_keyframesRules.shrinkToFit() gets called.
+ m_keyframesRules.append(rule);
+}
+
void RuleSet::addRegionRule(StyleRuleRegion* regionRule, bool hasDocumentSecurityOrigin)
{
ensurePendingRules(); // So that m_regionSelectorsAndRuleSets.shrinkToFit() gets called.
@@ -338,11 +344,11 @@ void RuleSet::addRegionRule(StyleRuleRegion* regionRule, bool hasDocumentSecurit
// FIXME: Should this add other types of rules? (i.e. use addChildRules() directly?)
const Vector<RefPtr<StyleRuleBase> >& childRules = regionRule->childRules();
AddRuleFlags addRuleFlags = hasDocumentSecurityOrigin ? RuleHasDocumentSecurityOrigin : RuleHasNoSpecialState;
- addRuleFlags = static_cast<AddRuleFlags>(addRuleFlags | RuleCanUseFastCheckSelector | RuleIsInRegionRule);
+ addRuleFlags = static_cast<AddRuleFlags>(addRuleFlags | RuleIsInRegionRule | RuleCanUseFastCheckSelector);
for (unsigned i = 0; i < childRules.size(); ++i) {
StyleRuleBase* regionStylingRule = childRules[i].get();
if (regionStylingRule->isStyleRule())
- regionRuleSet->addStyleRule(static_cast<StyleRule*>(regionStylingRule), addRuleFlags);
+ regionRuleSet->addStyleRule(toStyleRule(regionStylingRule), addRuleFlags);
}
// Update the "global" rule count so that proper order is maintained
m_ruleCount = regionRuleSet->m_ruleCount;
@@ -350,75 +356,57 @@ void RuleSet::addRegionRule(StyleRuleRegion* regionRule, bool hasDocumentSecurit
m_regionSelectorsAndRuleSets.append(RuleSetSelectorPair(regionRule->selectorList().first(), regionRuleSet.release()));
}
-void RuleSet::addChildRules(const Vector<RefPtr<StyleRuleBase> >& rules, const MediaQueryEvaluator& medium, StyleResolver* resolver, const ContainerNode* scope, bool hasDocumentSecurityOrigin, AddRuleFlags addRuleFlags)
+void RuleSet::addChildRules(const Vector<RefPtr<StyleRuleBase> >& rules, const MediaQueryEvaluator& medium, AddRuleFlags addRuleFlags)
{
for (unsigned i = 0; i < rules.size(); ++i) {
StyleRuleBase* rule = rules[i].get();
if (rule->isStyleRule()) {
- StyleRule* styleRule = static_cast<StyleRule*>(rule);
+ StyleRule* styleRule = toStyleRule(rule);
const CSSSelectorList& selectorList = styleRule->selectorList();
for (size_t selectorIndex = 0; selectorIndex != kNotFound; selectorIndex = selectorList.indexOfNextSelectorAfter(selectorIndex)) {
- if (selectorList.hasShadowDistributedAt(selectorIndex)) {
- if (isDocumentScope(scope))
- continue;
- resolver->ruleSets().shadowDistributedRules().addRule(styleRule, selectorIndex, const_cast<ContainerNode*>(scope), addRuleFlags);
- } else
+ if (selectorList.hasCombinatorCrossingTreeBoundaryAt(selectorIndex)) {
+ m_treeBoundaryCrossingRules.append(MinimalRuleData(styleRule, selectorIndex, addRuleFlags));
+ } else if (selectorList.hasShadowDistributedAt(selectorIndex)) {
+ m_shadowDistributedRules.append(MinimalRuleData(styleRule, selectorIndex, addRuleFlags));
+ } else {
addRule(styleRule, selectorIndex, addRuleFlags);
+ }
}
- } else if (rule->isPageRule())
- addPageRule(static_cast<StyleRulePage*>(rule));
- else if (rule->isMediaRule()) {
- StyleRuleMedia* mediaRule = static_cast<StyleRuleMedia*>(rule);
- if ((!mediaRule->mediaQueries() || medium.eval(mediaRule->mediaQueries(), resolver)))
- addChildRules(mediaRule->childRules(), medium, resolver, scope, hasDocumentSecurityOrigin, addRuleFlags);
- } else if (rule->isFontFaceRule() && resolver) {
- // Add this font face to our set.
- // FIXME(BUG 72461): We don't add @font-face rules of scoped style sheets for the moment.
- if (!isDocumentScope(scope))
- continue;
- const StyleRuleFontFace* fontFaceRule = static_cast<StyleRuleFontFace*>(rule);
- resolver->fontSelector()->addFontFaceRule(fontFaceRule);
- resolver->invalidateMatchedPropertiesCache();
- } else if (rule->isKeyframesRule() && resolver) {
- resolver->ensureScopedStyleResolver(scope)->addKeyframeStyle(static_cast<StyleRuleKeyframes*>(rule));
- } else if (rule->isRegionRule() && resolver) {
- // FIXME (BUG 72472): We don't add @-webkit-region rules of scoped style sheets for the moment.
- addRegionRule(static_cast<StyleRuleRegion*>(rule), hasDocumentSecurityOrigin);
- } else if (rule->isHostRule() && resolver) {
- if (!isScopingNodeInShadowTree(scope))
- continue;
- bool enabled = resolver->buildScopedStyleTreeInDocumentOrder();
- resolver->setBuildScopedStyleTreeInDocumentOrder(false);
- resolver->ensureScopedStyleResolver(scope->shadowHost())->addHostRule(static_cast<StyleRuleHost*>(rule), hasDocumentSecurityOrigin, scope);
- resolver->setBuildScopedStyleTreeInDocumentOrder(enabled);
+ } else if (rule->isPageRule()) {
+ addPageRule(toStyleRulePage(rule));
+ } else if (rule->isMediaRule()) {
+ StyleRuleMedia* mediaRule = toStyleRuleMedia(rule);
+ if ((!mediaRule->mediaQueries() || medium.eval(mediaRule->mediaQueries(), &m_viewportDependentMediaQueryResults)))
+ addChildRules(mediaRule->childRules(), medium, addRuleFlags);
+ } else if (rule->isFontFaceRule()) {
+ addFontFaceRule(toStyleRuleFontFace(rule));
+ } else if (rule->isKeyframesRule()) {
+ addKeyframesRule(toStyleRuleKeyframes(rule));
+ } else if (rule->isRegionRule()) {
+ addRegionRule(toStyleRuleRegion(rule), addRuleFlags & RuleHasDocumentSecurityOrigin);
} else if (rule->isViewportRule()) {
- // @viewport should not be scoped.
- if (!isDocumentScope(scope))
- continue;
- addViewportRule(static_cast<StyleRuleViewport*>(rule));
+ addViewportRule(toStyleRuleViewport(rule));
+ } else if (rule->isSupportsRule() && toStyleRuleSupports(rule)->conditionIsSupported()) {
+ addChildRules(toStyleRuleSupports(rule)->childRules(), medium, addRuleFlags);
}
- else if (rule->isSupportsRule() && static_cast<StyleRuleSupports*>(rule)->conditionIsSupported())
- addChildRules(static_cast<StyleRuleSupports*>(rule)->childRules(), medium, resolver, scope, hasDocumentSecurityOrigin, addRuleFlags);
}
}
-void RuleSet::addRulesFromSheet(StyleSheetContents* sheet, const MediaQueryEvaluator& medium, StyleResolver* resolver, const ContainerNode* scope)
+void RuleSet::addRulesFromSheet(StyleSheetContents* sheet, const MediaQueryEvaluator& medium, AddRuleFlags addRuleFlags)
{
ASSERT(sheet);
+ addRuleFlags = static_cast<AddRuleFlags>(addRuleFlags | RuleCanUseFastCheckSelector);
const Vector<RefPtr<StyleRuleImport> >& importRules = sheet->importRules();
for (unsigned i = 0; i < importRules.size(); ++i) {
StyleRuleImport* importRule = importRules[i].get();
- if (importRule->styleSheet() && (!importRule->mediaQueries() || medium.eval(importRule->mediaQueries(), resolver)))
- addRulesFromSheet(importRule->styleSheet(), medium, resolver, scope);
+ if (importRule->styleSheet() && (!importRule->mediaQueries() || medium.eval(importRule->mediaQueries(), &m_viewportDependentMediaQueryResults)))
+ addRulesFromSheet(importRule->styleSheet(), medium, addRuleFlags);
}
- bool hasDocumentSecurityOrigin = resolver && resolver->document().securityOrigin()->canRequest(sheet->baseURL());
- AddRuleFlags addRuleFlags = static_cast<AddRuleFlags>((hasDocumentSecurityOrigin ? RuleHasDocumentSecurityOrigin : 0) | (!scope ? RuleCanUseFastCheckSelector : 0));
-
- addChildRules(sheet->childRules(), medium, resolver, scope, hasDocumentSecurityOrigin, addRuleFlags);
+ addChildRules(sheet->childRules(), medium, addRuleFlags);
}
void RuleSet::addStyleRule(StyleRule* rule, AddRuleFlags addRuleFlags)
@@ -459,6 +447,10 @@ void RuleSet::compactRules()
m_universalRules.shrinkToFit();
m_pageRules.shrinkToFit();
m_viewportRules.shrinkToFit();
+ m_fontFaceRules.shrinkToFit();
+ m_keyframesRules.shrinkToFit();
+ m_treeBoundaryCrossingRules.shrinkToFit();
+ m_shadowDistributedRules.shrinkToFit();
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/css/RuleSet.h b/chromium/third_party/WebKit/Source/core/css/RuleSet.h
index f8867f8b550..d8249a3edb9 100644
--- a/chromium/third_party/WebKit/Source/core/css/RuleSet.h
+++ b/chromium/third_party/WebKit/Source/core/css/RuleSet.h
@@ -22,8 +22,11 @@
#ifndef RuleSet_h
#define RuleSet_h
+#include "core/css/CSSKeyframesRule.h"
+#include "core/css/MediaQueryEvaluator.h"
#include "core/css/RuleFeature.h"
#include "core/css/StyleRule.h"
+#include "core/css/resolver/MediaQueryResult.h"
#include "wtf/Forward.h"
#include "wtf/HashMap.h"
#include "wtf/LinkedStack.h"
@@ -44,12 +47,23 @@ enum PropertyWhitelistType {
};
class CSSSelector;
-class ContainerNode;
class MediaQueryEvaluator;
-class StyleResolver;
class StyleRuleRegion;
class StyleSheetContents;
+struct MinimalRuleData {
+ MinimalRuleData(StyleRule* rule, unsigned selectorIndex, AddRuleFlags flags)
+ : m_rule(rule)
+ , m_selectorIndex(selectorIndex)
+ , m_flags(flags)
+ {
+ }
+
+ StyleRule* m_rule;
+ unsigned m_selectorIndex;
+ AddRuleFlags m_flags;
+};
+
class RuleData {
WTF_MAKE_FAST_ALLOCATED;
public:
@@ -108,7 +122,7 @@ class RuleSet {
public:
static PassOwnPtr<RuleSet> create() { return adoptPtr(new RuleSet); }
- void addRulesFromSheet(StyleSheetContents*, const MediaQueryEvaluator&, StyleResolver* = 0, const ContainerNode* = 0);
+ void addRulesFromSheet(StyleSheetContents*, const MediaQueryEvaluator&, AddRuleFlags = RuleHasNoSpecialState);
void addStyleRule(StyleRule*, AddRuleFlags);
void addRule(StyleRule*, unsigned selectorIndex, AddRuleFlags);
@@ -124,6 +138,11 @@ public:
const Vector<RuleData>* universalRules() const { ASSERT(!m_pendingRules); return &m_universalRules; }
const Vector<StyleRulePage*>& pageRules() const { ASSERT(!m_pendingRules); return m_pageRules; }
const Vector<StyleRuleViewport*>& viewportRules() const { ASSERT(!m_pendingRules); return m_viewportRules; }
+ const Vector<StyleRuleFontFace*>& fontFaceRules() const { return m_fontFaceRules; }
+ const Vector<StyleRuleKeyframes*>& keyframesRules() const { return m_keyframesRules; }
+ const Vector<MinimalRuleData>& treeBoundaryCrossingRules() const { return m_treeBoundaryCrossingRules; }
+ const Vector<MinimalRuleData>& shadowDistributedRules() const { return m_shadowDistributedRules; }
+ const MediaQueryResultList& viewportDependentMediaQueryResults() const { return m_viewportDependentMediaQueryResults; }
unsigned ruleCount() const { return m_ruleCount; }
@@ -156,9 +175,11 @@ private:
void addToRuleSet(StringImpl* key, PendingRuleMap&, const RuleData&);
void addPageRule(StyleRulePage*);
void addViewportRule(StyleRuleViewport*);
+ void addFontFaceRule(StyleRuleFontFace*);
+ void addKeyframesRule(StyleRuleKeyframes*);
void addRegionRule(StyleRuleRegion*, bool hasDocumentSecurityOrigin);
- void addChildRules(const Vector<RefPtr<StyleRuleBase> >&, const MediaQueryEvaluator& medium, StyleResolver*, const ContainerNode* scope, bool hasDocumentSecurityOrigin, AddRuleFlags);
+ void addChildRules(const Vector<RefPtr<StyleRuleBase> >&, const MediaQueryEvaluator& medium, AddRuleFlags);
bool findBestRuleSetAndAdd(const CSSSelector*, RuleData&);
void compactRules();
@@ -189,6 +210,12 @@ private:
RuleFeatureSet m_features;
Vector<StyleRulePage*> m_pageRules;
Vector<StyleRuleViewport*> m_viewportRules;
+ Vector<StyleRuleFontFace*> m_fontFaceRules;
+ Vector<StyleRuleKeyframes*> m_keyframesRules;
+ Vector<MinimalRuleData> m_treeBoundaryCrossingRules;
+ Vector<MinimalRuleData> m_shadowDistributedRules;
+
+ MediaQueryResultList m_viewportDependentMediaQueryResults;
unsigned m_ruleCount;
OwnPtr<PendingRuleMaps> m_pendingRules;
diff --git a/chromium/third_party/WebKit/Source/core/css/RuntimeCSSEnabled.cpp b/chromium/third_party/WebKit/Source/core/css/RuntimeCSSEnabled.cpp
new file mode 100644
index 00000000000..7e0d728e2b8
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/css/RuntimeCSSEnabled.cpp
@@ -0,0 +1,173 @@
+/*
+ * Copyright (C) 2013 Adobe Systems Incorporated. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer.
+ * 2. Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer in the documentation and/or other materials
+ * provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/css/RuntimeCSSEnabled.h"
+
+#include "RuntimeEnabledFeatures.h"
+
+namespace WebCore {
+
+// FIXME: We should use a real BitVector class instead!
+typedef Vector<bool> BoolVector;
+
+static void setCSSPropertiesEnabled(CSSPropertyID* properties, size_t length, bool featureFlag)
+{
+ for (size_t i = 0; i < length; i++)
+ RuntimeCSSEnabled::setCSSPropertyEnabled(properties[i], featureFlag);
+}
+
+static void setPropertySwitchesFromRuntimeFeatures()
+{
+ CSSPropertyID regionProperites[] = {
+ CSSPropertyWebkitFlowInto,
+ CSSPropertyWebkitFlowFrom,
+ CSSPropertyWebkitRegionFragment,
+ CSSPropertyWebkitRegionBreakAfter,
+ CSSPropertyWebkitRegionBreakBefore,
+ CSSPropertyWebkitRegionBreakInside
+ };
+ setCSSPropertiesEnabled(regionProperites, WTF_ARRAY_LENGTH(regionProperites), RuntimeEnabledFeatures::cssRegionsEnabled());
+ CSSPropertyID exclusionProperties[] = {
+ CSSPropertyWebkitWrapFlow,
+ CSSPropertyWebkitWrapThrough,
+ };
+ setCSSPropertiesEnabled(exclusionProperties, WTF_ARRAY_LENGTH(exclusionProperties), RuntimeEnabledFeatures::cssExclusionsEnabled());
+ CSSPropertyID shapeProperties[] = {
+ CSSPropertyShapeMargin,
+ CSSPropertyShapePadding,
+ CSSPropertyShapeImageThreshold,
+ CSSPropertyShapeInside,
+ CSSPropertyShapeOutside,
+ };
+ setCSSPropertiesEnabled(shapeProperties, WTF_ARRAY_LENGTH(shapeProperties), RuntimeEnabledFeatures::cssShapesEnabled());
+ CSSPropertyID css3TextDecorationProperties[] = {
+ CSSPropertyTextDecorationColor,
+ CSSPropertyTextDecorationLine,
+ CSSPropertyTextDecorationStyle,
+ CSSPropertyTextUnderlinePosition,
+ };
+ setCSSPropertiesEnabled(css3TextDecorationProperties, WTF_ARRAY_LENGTH(css3TextDecorationProperties), RuntimeEnabledFeatures::css3TextDecorationsEnabled());
+ CSSPropertyID css3TextProperties[] = {
+ CSSPropertyTextAlignLast,
+ CSSPropertyTextJustify,
+ };
+ setCSSPropertiesEnabled(css3TextProperties, WTF_ARRAY_LENGTH(css3TextProperties), RuntimeEnabledFeatures::css3TextEnabled());
+ CSSPropertyID cssGridLayoutProperties[] = {
+ CSSPropertyGridAutoColumns,
+ CSSPropertyGridAutoRows,
+ CSSPropertyGridDefinitionColumns,
+ CSSPropertyGridDefinitionRows,
+ CSSPropertyGridColumnStart,
+ CSSPropertyGridColumnEnd,
+ CSSPropertyGridRowStart,
+ CSSPropertyGridRowEnd,
+ CSSPropertyGridColumn,
+ CSSPropertyGridRow,
+ CSSPropertyGridArea,
+ CSSPropertyGridAutoFlow,
+ CSSPropertyGridTemplate
+ };
+ setCSSPropertiesEnabled(cssGridLayoutProperties, WTF_ARRAY_LENGTH(cssGridLayoutProperties), RuntimeEnabledFeatures::cssGridLayoutEnabled());
+ CSSPropertyID cssObjectFitPositionProperties[] = {
+ CSSPropertyObjectFit,
+ CSSPropertyObjectPosition
+ };
+ setCSSPropertiesEnabled(cssObjectFitPositionProperties, WTF_ARRAY_LENGTH(cssObjectFitPositionProperties), RuntimeEnabledFeatures::objectFitPositionEnabled());
+
+ CSSPropertyID animationProperties[] = {
+ CSSPropertyAnimation,
+ CSSPropertyAnimationName,
+ CSSPropertyAnimationDuration,
+ CSSPropertyAnimationTimingFunction,
+ CSSPropertyAnimationDelay,
+ CSSPropertyAnimationIterationCount,
+ CSSPropertyAnimationDirection,
+ CSSPropertyAnimationFillMode,
+ CSSPropertyAnimationPlayState
+ };
+ setCSSPropertiesEnabled(animationProperties, WTF_ARRAY_LENGTH(animationProperties), RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled());
+
+ RuntimeCSSEnabled::setCSSPropertyEnabled(CSSPropertyBackgroundBlendMode, RuntimeEnabledFeatures::cssCompositingEnabled());
+ RuntimeCSSEnabled::setCSSPropertyEnabled(CSSPropertyMixBlendMode, RuntimeEnabledFeatures::cssCompositingEnabled());
+ RuntimeCSSEnabled::setCSSPropertyEnabled(CSSPropertyIsolation, RuntimeEnabledFeatures::cssCompositingEnabled());
+ RuntimeCSSEnabled::setCSSPropertyEnabled(CSSPropertyTouchAction, RuntimeEnabledFeatures::cssTouchActionEnabled());
+ RuntimeCSSEnabled::setCSSPropertyEnabled(CSSPropertyPaintOrder, RuntimeEnabledFeatures::svgPaintOrderEnabled());
+ RuntimeCSSEnabled::setCSSPropertyEnabled(CSSPropertyVariable, RuntimeEnabledFeatures::cssVariablesEnabled());
+ RuntimeCSSEnabled::setCSSPropertyEnabled(CSSPropertyMaskSourceType, RuntimeEnabledFeatures::cssMaskSourceTypeEnabled());
+ RuntimeCSSEnabled::setCSSPropertyEnabled(CSSPropertyColumnFill, RuntimeEnabledFeatures::regionBasedColumnsEnabled());
+
+ // InternalCallback is an implementation detail, rather than an experimental feature, and should never be exposed to the web.
+ RuntimeCSSEnabled::setCSSPropertyEnabled(CSSPropertyInternalCallback, false);
+}
+
+static BoolVector& propertySwitches()
+{
+ static BoolVector* switches = 0;
+ if (!switches) {
+ switches = new BoolVector;
+ // Accomodate CSSPropertyIDs that fall outside the firstCSSProperty, lastCSSProperty range (eg. CSSPropertyVariable).
+ switches->fill(true, lastCSSProperty + 1);
+ setPropertySwitchesFromRuntimeFeatures();
+ }
+ return *switches;
+}
+
+size_t indexForProperty(CSSPropertyID propertyId)
+{
+ RELEASE_ASSERT(propertyId >= 0 && propertyId <= lastCSSProperty);
+ ASSERT(propertyId != CSSPropertyInvalid);
+ return static_cast<size_t>(propertyId);
+}
+
+bool RuntimeCSSEnabled::isCSSPropertyEnabled(CSSPropertyID propertyId)
+{
+ // Internal properties shouldn't be exposed to the web
+ // so they are considered to be always disabled.
+ if (isInternalProperty(propertyId))
+ return false;
+
+ return propertySwitches()[indexForProperty(propertyId)];
+}
+
+void RuntimeCSSEnabled::setCSSPropertyEnabled(CSSPropertyID propertyId, bool enable)
+{
+ propertySwitches()[indexForProperty(propertyId)] = enable;
+}
+
+void RuntimeCSSEnabled::filterEnabledCSSPropertiesIntoVector(const CSSPropertyID* properties, size_t propertyCount, Vector<CSSPropertyID>& outVector)
+{
+ for (unsigned i = 0; i < propertyCount; i++) {
+ CSSPropertyID property = properties[i];
+ if (RuntimeCSSEnabled::isCSSPropertyEnabled(property))
+ outVector.append(property);
+ }
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/page/RuntimeCSSEnabled.h b/chromium/third_party/WebKit/Source/core/css/RuntimeCSSEnabled.h
index 493d3a52356..493d3a52356 100644
--- a/chromium/third_party/WebKit/Source/core/page/RuntimeCSSEnabled.h
+++ b/chromium/third_party/WebKit/Source/core/css/RuntimeCSSEnabled.h
diff --git a/chromium/third_party/WebKit/Source/core/css/SVGCSSComputedStyleDeclaration.cpp b/chromium/third_party/WebKit/Source/core/css/SVGCSSComputedStyleDeclaration.cpp
index 5858b481315..c972f873786 100644
--- a/chromium/third_party/WebKit/Source/core/css/SVGCSSComputedStyleDeclaration.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/SVGCSSComputedStyleDeclaration.cpp
@@ -80,11 +80,11 @@ static PassRefPtr<CSSValue> paintOrderToCSSValueList(EPaintOrder paintorder)
return list.release();
}
-PassRefPtr<SVGPaint> CSSComputedStyleDeclaration::adjustSVGPaintForCurrentColor(PassRefPtr<SVGPaint> newPaint, RenderStyle* style) const
+PassRefPtr<SVGPaint> CSSComputedStyleDeclaration::adjustSVGPaintForCurrentColor(PassRefPtr<SVGPaint> newPaint, RenderStyle& style) const
{
RefPtr<SVGPaint> paint = newPaint;
if (paint->paintType() == SVGPaint::SVG_PAINTTYPE_CURRENTCOLOR || paint->paintType() == SVGPaint::SVG_PAINTTYPE_URI_CURRENTCOLOR)
- paint->setColor(style->color());
+ paint->setColor(style.color());
return paint.release();
}
@@ -154,13 +154,13 @@ PassRefPtr<CSSValue> CSSComputedStyleDeclaration::getSVGPropertyCSSValue(CSSProp
return CSSPrimitiveValue::create(svgStyle->filterResource(), CSSPrimitiveValue::CSS_URI);
return CSSPrimitiveValue::createIdentifier(CSSValueNone);
case CSSPropertyFloodColor:
- return currentColorOrValidColor(style, svgStyle->floodColor());
+ return currentColorOrValidColor(*style, svgStyle->floodColor());
case CSSPropertyLightingColor:
- return currentColorOrValidColor(style, svgStyle->lightingColor());
+ return currentColorOrValidColor(*style, svgStyle->lightingColor());
case CSSPropertyStopColor:
- return currentColorOrValidColor(style, svgStyle->stopColor());
+ return currentColorOrValidColor(*style, svgStyle->stopColor());
case CSSPropertyFill:
- return adjustSVGPaintForCurrentColor(SVGPaint::create(svgStyle->fillPaintType(), svgStyle->fillPaintUri(), svgStyle->fillPaintColor()), style);
+ return adjustSVGPaintForCurrentColor(SVGPaint::create(svgStyle->fillPaintType(), svgStyle->fillPaintUri(), svgStyle->fillPaintColor()), *style);
case CSSPropertyKerning:
return SVGLength::toCSSPrimitiveValue(svgStyle->kerning());
case CSSPropertyMarkerEnd:
@@ -176,7 +176,7 @@ PassRefPtr<CSSValue> CSSComputedStyleDeclaration::getSVGPropertyCSSValue(CSSProp
return CSSPrimitiveValue::create(svgStyle->markerStartResource(), CSSPrimitiveValue::CSS_URI);
return CSSPrimitiveValue::createIdentifier(CSSValueNone);
case CSSPropertyStroke:
- return adjustSVGPaintForCurrentColor(SVGPaint::create(svgStyle->strokePaintType(), svgStyle->strokePaintUri(), svgStyle->strokePaintColor()), style);
+ return adjustSVGPaintForCurrentColor(SVGPaint::create(svgStyle->strokePaintType(), svgStyle->strokePaintUri(), svgStyle->strokePaintColor()), *style);
case CSSPropertyStrokeDasharray:
return strokeDashArrayToCSSValueList(svgStyle->strokeDashArray());
case CSSPropertyStrokeDashoffset:
@@ -226,7 +226,7 @@ PassRefPtr<CSSValue> CSSComputedStyleDeclaration::getSVGPropertyCSSValue(CSSProp
// in either this switch statement or the one in CSSComputedStyleDelcaration::getPropertyCSSValue
ASSERT_WITH_MESSAGE(0, "unimplemented propertyID: %d", propertyID);
}
- LOG_ERROR("unimplemented propertyID: %d", propertyID);
+ WTF_LOG_ERROR("unimplemented propertyID: %d", propertyID);
return 0;
}
diff --git a/chromium/third_party/WebKit/Source/core/css/SelectorChecker.cpp b/chromium/third_party/WebKit/Source/core/css/SelectorChecker.cpp
index 80222e12dd6..15474cedd1d 100644
--- a/chromium/third_party/WebKit/Source/core/css/SelectorChecker.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/SelectorChecker.cpp
@@ -29,11 +29,9 @@
#include "core/css/SelectorChecker.h"
#include "HTMLNames.h"
-#include "core/css/CSSSelector.h"
#include "core/css/CSSSelectorList.h"
#include "core/css/SiblingTraversalStrategies.h"
#include "core/dom/Document.h"
-#include "core/dom/Element.h"
#include "core/dom/FullscreenElementStack.h"
#include "core/dom/NodeRenderStyle.h"
#include "core/dom/Text.h"
@@ -47,17 +45,15 @@
#include "core/html/HTMLOptGroupElement.h"
#include "core/html/HTMLOptionElement.h"
#include "core/html/parser/HTMLParserIdioms.h"
+#include "core/html/track/vtt/VTTElement.h"
#include "core/inspector/InspectorInstrumentation.h"
#include "core/page/FocusController.h"
-#include "core/page/Frame.h"
-#include "core/page/Page.h"
-#include "core/platform/ScrollableArea.h"
-#include "core/platform/ScrollbarTheme.h"
+#include "core/frame/Frame.h"
#include "core/rendering/RenderObject.h"
#include "core/rendering/RenderScrollbar.h"
#include "core/rendering/style/RenderStyle.h"
-
-#include "core/html/track/WebVTTElement.h"
+#include "platform/scroll/ScrollableArea.h"
+#include "platform/scroll/ScrollbarTheme.h"
namespace WebCore {
@@ -76,18 +72,10 @@ static bool matchesCustomPseudoElement(const Element* element, const CSSSelector
if (!root)
return false;
- if (selector->pseudoType() != CSSSelector::PseudoPart) {
- const AtomicString& pseudoId = selector->pseudoType() == CSSSelector::PseudoWebKitCustomElement ? element->shadowPseudoId() : element->pseudo();
- if (pseudoId != selector->value())
- return false;
- if (selector->pseudoType() == CSSSelector::PseudoWebKitCustomElement && root->type() != ShadowRoot::UserAgentShadowRoot)
- return false;
- return true;
- }
-
- if (element->part() != selector->argument())
+ const AtomicString& pseudoId = selector->pseudoType() == CSSSelector::PseudoWebKitCustomElement ? element->shadowPseudoId() : element->pseudo();
+ if (pseudoId != selector->value())
return false;
- if (selector->isMatchUserAgentOnly() && root->type() != ShadowRoot::UserAgentShadowRoot)
+ if (selector->pseudoType() == CSSSelector::PseudoWebKitCustomElement && root->type() != ShadowRoot::UserAgentShadowRoot)
return false;
return true;
}
@@ -128,6 +116,11 @@ bool SelectorChecker::scopeContainsLastMatchedElement(const SelectorCheckingCont
return root->host() == context.scope;
}
+static inline bool nextSelectorExceedsScope(const SelectorChecker::SelectorCheckingContext& context)
+{
+ return context.element == context.scope && (context.behaviorAtBoundary & SelectorChecker::BoundaryBehaviorMask) != SelectorChecker::StaysWithinTreeScope;
+}
+
// Recursive check of selectors and combinators
// It can return 4 different values:
// * SelectorMatches - the selector matches the element e
@@ -135,10 +128,11 @@ bool SelectorChecker::scopeContainsLastMatchedElement(const SelectorCheckingCont
// * SelectorFailsAllSiblings - the selector fails for e and any sibling of e
// * SelectorFailsCompletely - the selector fails for e and any sibling or ancestor of e
template<typename SiblingTraversalStrategy>
-SelectorChecker::Match SelectorChecker::match(const SelectorCheckingContext& context, PseudoId& dynamicPseudo, const SiblingTraversalStrategy& siblingTraversalStrategy) const
+SelectorChecker::Match SelectorChecker::match(const SelectorCheckingContext& context, const SiblingTraversalStrategy& siblingTraversalStrategy, MatchResult* result) const
{
// first selector has to match
- if (!checkOne(context, siblingTraversalStrategy))
+ unsigned specificity = 0;
+ if (!checkOne(context, siblingTraversalStrategy, &specificity))
return SelectorFailsLocally;
if (context.selector->m_match == CSSSelector::PseudoElement) {
@@ -155,44 +149,94 @@ SelectorChecker::Match SelectorChecker::match(const SelectorCheckingContext& con
PseudoId pseudoId = CSSSelector::pseudoId(context.selector->pseudoType());
if (pseudoId == FIRST_LETTER)
context.element->document().styleEngine()->setUsesFirstLetterRules(true);
- if (pseudoId != NOPSEUDO && m_mode != SharingRules)
- dynamicPseudo = pseudoId;
+ if (pseudoId != NOPSEUDO && m_mode != SharingRules && result)
+ result->dynamicPseudo = pseudoId;
}
}
- // The rest of the selectors has to match
- CSSSelector::Relation relation = context.selector->relation();
-
// Prepare next selector
const CSSSelector* historySelector = context.selector->tagHistory();
- if (!historySelector)
- return scopeContainsLastMatchedElement(context) ? SelectorMatches : SelectorFailsLocally;
-
- SelectorCheckingContext nextContext(context);
- nextContext.selector = historySelector;
+ if (!historySelector) {
+ if (scopeContainsLastMatchedElement(context)) {
+ if (result)
+ result->specificity += specificity;
+ return SelectorMatches;
+ }
+ return SelectorFailsLocally;
+ }
- PseudoId ignoreDynamicPseudo = NOPSEUDO;
- if (relation != CSSSelector::SubSelector) {
+ Match match;
+ if (context.selector->relation() != CSSSelector::SubSelector) {
// Abort if the next selector would exceed the scope.
- if (context.element == context.scope && (context.behaviorAtBoundary & BoundaryBehaviorMask) != StaysWithinTreeScope)
+ if (nextSelectorExceedsScope(context))
return SelectorFailsCompletely;
// Bail-out if this selector is irrelevant for the pseudoId
- if (context.pseudoId != NOPSEUDO && context.pseudoId != dynamicPseudo)
+ if (context.pseudoId != NOPSEUDO && (!result || context.pseudoId != result->dynamicPseudo))
return SelectorFailsCompletely;
- // Disable :visited matching when we see the first link or try to match anything else than an ancestors.
- if (!context.isSubSelector && (context.element->isLink() || (relation != CSSSelector::Descendant && relation != CSSSelector::Child)))
- nextContext.visitedMatchType = VisitedMatchDisabled;
-
- nextContext.pseudoId = NOPSEUDO;
+ if (result) {
+ TemporaryChange<PseudoId> dynamicPseudoScope(result->dynamicPseudo, NOPSEUDO);
+ match = matchForRelation(context, siblingTraversalStrategy, result);
+ } else {
+ return matchForRelation(context, siblingTraversalStrategy, 0);
+ }
+ } else {
+ match = matchForSubSelector(context, siblingTraversalStrategy, result);
}
+ if (match != SelectorMatches || !result)
+ return match;
+
+ result->specificity += specificity;
+ return SelectorMatches;
+}
+
+static inline SelectorChecker::SelectorCheckingContext prepareNextContextForRelation(const SelectorChecker::SelectorCheckingContext& context)
+{
+ SelectorChecker::SelectorCheckingContext nextContext(context);
+ ASSERT(context.selector->tagHistory());
+ nextContext.selector = context.selector->tagHistory();
+ return nextContext;
+}
+
+template<typename SiblingTraversalStrategy>
+SelectorChecker::Match SelectorChecker::matchForSubSelector(const SelectorCheckingContext& context, const SiblingTraversalStrategy& siblingTraversalStrategy, MatchResult* result) const
+{
+ SelectorCheckingContext nextContext = prepareNextContextForRelation(context);
+
+ PseudoId dynamicPseudo = result ? result->dynamicPseudo : NOPSEUDO;
+ // a selector is invalid if something follows a pseudo-element
+ // We make an exception for scrollbar pseudo elements and allow a set of pseudo classes (but nothing else)
+ // to follow the pseudo elements.
+ nextContext.hasScrollbarPseudo = dynamicPseudo != NOPSEUDO && (context.scrollbar || dynamicPseudo == SCROLLBAR_CORNER || dynamicPseudo == RESIZER);
+ nextContext.hasSelectionPseudo = dynamicPseudo == SELECTION;
+ if ((context.elementStyle || m_mode == CollectingCSSRules || m_mode == CollectingStyleRules || m_mode == QueryingRules) && dynamicPseudo != NOPSEUDO
+ && !nextContext.hasSelectionPseudo
+ && !(nextContext.hasScrollbarPseudo && nextContext.selector->m_match == CSSSelector::PseudoClass))
+ return SelectorFailsCompletely;
+
+ nextContext.isSubSelector = true;
+ return match(nextContext, siblingTraversalStrategy, result);
+}
+
+template<typename SiblingTraversalStrategy>
+SelectorChecker::Match SelectorChecker::matchForRelation(const SelectorCheckingContext& context, const SiblingTraversalStrategy& siblingTraversalStrategy, MatchResult* result) const
+{
+ SelectorCheckingContext nextContext = prepareNextContextForRelation(context);
+
+ CSSSelector::Relation relation = context.selector->relation();
+
+ // Disable :visited matching when we see the first link or try to match anything else than an ancestors.
+ if (!context.isSubSelector && (context.element->isLink() || (relation != CSSSelector::Descendant && relation != CSSSelector::Child)))
+ nextContext.visitedMatchType = VisitedMatchDisabled;
+
+ nextContext.pseudoId = NOPSEUDO;
switch (relation) {
case CSSSelector::Descendant:
if (context.selector->relationIsAffectedByPseudoContent()) {
for (Element* element = context.element; element; element = element->parentElement()) {
- if (matchForShadowDistributed(element, siblingTraversalStrategy, ignoreDynamicPseudo, nextContext) == SelectorMatches)
+ if (matchForShadowDistributed(element, siblingTraversalStrategy, nextContext, result) == SelectorMatches)
return SelectorMatches;
}
return SelectorFailsCompletely;
@@ -200,17 +244,17 @@ SelectorChecker::Match SelectorChecker::match(const SelectorCheckingContext& con
nextContext.isSubSelector = false;
nextContext.elementStyle = 0;
for (nextContext.element = parentElement(context); nextContext.element; nextContext.element = parentElement(nextContext)) {
- Match match = this->match(nextContext, ignoreDynamicPseudo, siblingTraversalStrategy);
+ Match match = this->match(nextContext, siblingTraversalStrategy, result);
if (match == SelectorMatches || match == SelectorFailsCompletely)
return match;
- if (nextContext.element == nextContext.scope && (nextContext.behaviorAtBoundary & BoundaryBehaviorMask) != StaysWithinTreeScope)
+ if (nextSelectorExceedsScope(nextContext))
return SelectorFailsCompletely;
}
return SelectorFailsCompletely;
case CSSSelector::Child:
{
if (context.selector->relationIsAffectedByPseudoContent())
- return matchForShadowDistributed(context.element, siblingTraversalStrategy, ignoreDynamicPseudo, nextContext);
+ return matchForShadowDistributed(context.element, siblingTraversalStrategy, nextContext, result);
nextContext.element = parentElement(context);
if (!nextContext.element)
@@ -218,7 +262,7 @@ SelectorChecker::Match SelectorChecker::match(const SelectorCheckingContext& con
nextContext.isSubSelector = false;
nextContext.elementStyle = 0;
- return match(nextContext, ignoreDynamicPseudo, siblingTraversalStrategy);
+ return match(nextContext, siblingTraversalStrategy, result);
}
case CSSSelector::DirectAdjacent:
if (m_mode == ResolvingStyle) {
@@ -230,7 +274,7 @@ SelectorChecker::Match SelectorChecker::match(const SelectorCheckingContext& con
return SelectorFailsAllSiblings;
nextContext.isSubSelector = false;
nextContext.elementStyle = 0;
- return match(nextContext, ignoreDynamicPseudo, siblingTraversalStrategy);
+ return match(nextContext, siblingTraversalStrategy, result);
case CSSSelector::IndirectAdjacent:
if (m_mode == ResolvingStyle) {
@@ -241,38 +285,44 @@ SelectorChecker::Match SelectorChecker::match(const SelectorCheckingContext& con
nextContext.isSubSelector = false;
nextContext.elementStyle = 0;
for (; nextContext.element; nextContext.element = nextContext.element->previousElementSibling()) {
- Match match = this->match(nextContext, ignoreDynamicPseudo, siblingTraversalStrategy);
+ Match match = this->match(nextContext, siblingTraversalStrategy, result);
if (match == SelectorMatches || match == SelectorFailsAllSiblings || match == SelectorFailsCompletely)
return match;
};
return SelectorFailsAllSiblings;
- case CSSSelector::SubSelector:
- // a selector is invalid if something follows a pseudo-element
- // We make an exception for scrollbar pseudo elements and allow a set of pseudo classes (but nothing else)
- // to follow the pseudo elements.
- nextContext.hasScrollbarPseudo = dynamicPseudo != NOPSEUDO && (context.scrollbar || dynamicPseudo == SCROLLBAR_CORNER || dynamicPseudo == RESIZER);
- nextContext.hasSelectionPseudo = dynamicPseudo == SELECTION;
- if ((context.elementStyle || m_mode == CollectingRules || m_mode == QueryingRules) && dynamicPseudo != NOPSEUDO
- && !nextContext.hasSelectionPseudo
- && !(nextContext.hasScrollbarPseudo && nextContext.selector->m_match == CSSSelector::PseudoClass))
- return SelectorFailsCompletely;
- nextContext.isSubSelector = true;
- return match(nextContext, dynamicPseudo, siblingTraversalStrategy);
-
case CSSSelector::ShadowPseudo:
+ case CSSSelector::ChildTree:
{
// If we're in the same tree-scope as the scoping element, then following a shadow descendant combinator would escape that and thus the scope.
- if (context.scope && &context.scope->treeScope() == &context.element->treeScope() && (context.behaviorAtBoundary & BoundaryBehaviorMask) != StaysWithinTreeScope)
+ if (context.scope && context.scope->treeScope() == context.element->treeScope() && (context.behaviorAtBoundary & BoundaryBehaviorMask) != StaysWithinTreeScope)
return SelectorFailsCompletely;
- Element* shadowHostNode = context.element->shadowHost();
- if (!shadowHostNode)
+
+ Element* shadowHost = context.element->shadowHost();
+ if (!shadowHost)
return SelectorFailsCompletely;
- nextContext.element = shadowHostNode;
+ nextContext.element = shadowHost;
nextContext.isSubSelector = false;
nextContext.elementStyle = 0;
- return match(nextContext, ignoreDynamicPseudo, siblingTraversalStrategy);
+ return this->match(nextContext, siblingTraversalStrategy, result);
}
+
+ case CSSSelector::DescendantTree:
+ {
+ nextContext.isSubSelector = false;
+ nextContext.elementStyle = 0;
+ for (nextContext.element = parentElement(context); nextContext.element; nextContext.element = parentElement(nextContext)) {
+ Match match = this->match(nextContext, siblingTraversalStrategy, result);
+ if (match == SelectorMatches || match == SelectorFailsCompletely)
+ return match;
+ if (nextSelectorExceedsScope(nextContext))
+ return SelectorFailsCompletely;
+ }
+ return SelectorFailsCompletely;
+ }
+
+ case CSSSelector::SubSelector:
+ ASSERT_NOT_REACHED();
}
ASSERT_NOT_REACHED();
@@ -280,15 +330,28 @@ SelectorChecker::Match SelectorChecker::match(const SelectorCheckingContext& con
}
template<typename SiblingTraversalStrategy>
-SelectorChecker::Match SelectorChecker::matchForShadowDistributed(const Element* element, const SiblingTraversalStrategy& siblingTraversalStrategy, PseudoId& dynamicPseudo, SelectorCheckingContext& nextContext) const
+SelectorChecker::Match SelectorChecker::matchForShadowDistributed(const Element* element, const SiblingTraversalStrategy& siblingTraversalStrategy, SelectorCheckingContext& nextContext, MatchResult* result) const
{
+ ASSERT(element);
Vector<InsertionPoint*, 8> insertionPoints;
- collectInsertionPointsWhereNodeIsDistributed(element, insertionPoints);
+
+ const ContainerNode* scope = nextContext.scope;
+ BehaviorAtBoundary behaviorAtBoundary = nextContext.behaviorAtBoundary;
+
+ collectDestinationInsertionPoints(*element, insertionPoints);
for (size_t i = 0; i < insertionPoints.size(); ++i) {
nextContext.element = insertionPoints[i];
+
+ // If a given scope is a shadow host of an insertion point but behaviorAtBoundary doesn't have ScopeIsShadowHost,
+ // we need to update behaviorAtBoundary to make selectors like ":host > ::content" work correctly.
+ if (scope == insertionPoints[i]->containingShadowRoot()->shadowHost() && !(behaviorAtBoundary & ScopeIsShadowHost))
+ nextContext.behaviorAtBoundary = static_cast<BehaviorAtBoundary>(behaviorAtBoundary | ScopeIsShadowHost);
+ else
+ nextContext.behaviorAtBoundary = behaviorAtBoundary;
+
nextContext.isSubSelector = false;
nextContext.elementStyle = 0;
- if (match(nextContext, dynamicPseudo, siblingTraversalStrategy) == SelectorMatches)
+ if (match(nextContext, siblingTraversalStrategy, result) == SelectorMatches)
return SelectorMatches;
}
return SelectorFailsCompletely;
@@ -365,11 +428,25 @@ static bool attributeValueMatches(const Attribute* attributeItem, CSSSelector::M
return true;
}
-static bool anyAttributeMatches(Element* element, CSSSelector::Match match, const QualifiedName& selectorAttr, const AtomicString& selectorValue, bool caseSensitive)
+static bool anyAttributeMatches(Element& element, CSSSelector::Match match, const CSSSelector& selector)
{
- ASSERT(element->hasAttributesWithoutUpdate());
- for (size_t i = 0; i < element->attributeCount(); ++i) {
- const Attribute* attributeItem = element->attributeItem(i);
+ const QualifiedName& selectorAttr = selector.attribute();
+ ASSERT(selectorAttr.localName() != starAtom); // Should not be possible from the CSS grammar.
+
+ // Synchronize the attribute in case it is lazy-computed.
+ // Currently all lazy properties have a null namespace, so only pass localName().
+ element.synchronizeAttribute(selectorAttr.localName());
+
+ if (!element.hasAttributesWithoutUpdate())
+ return false;
+
+ const AtomicString& selectorValue = selector.value();
+ // Case sensitivity for attribute matching is looser than hasAttribute or
+ // Element::shouldIgnoreAttributeCase() for now. Unclear if that's correct.
+ bool caseSensitive = !element.document().isHTMLDocument() || HTMLDocument::isCaseSensitiveAttribute(selectorAttr);
+
+ for (size_t i = 0; i < element.attributeCount(); ++i) {
+ const Attribute* attributeItem = element.attributeItem(i);
if (!attributeItem->matches(selectorAttr))
continue;
@@ -382,31 +459,27 @@ static bool anyAttributeMatches(Element* element, CSSSelector::Match match, cons
}
template<typename SiblingTraversalStrategy>
-bool SelectorChecker::checkOne(const SelectorCheckingContext& context, const SiblingTraversalStrategy& siblingTraversalStrategy) const
+bool SelectorChecker::checkOne(const SelectorCheckingContext& context, const SiblingTraversalStrategy& siblingTraversalStrategy, unsigned* specificity) const
{
- Element* const & element = context.element;
+ ASSERT(context.element);
+ Element& element = *context.element;
const CSSSelector* const & selector = context.selector;
- ASSERT(element);
ASSERT(selector);
+ bool elementIsHostInItsShadowTree = isHostInItsShadowTree(element, context.behaviorAtBoundary, context.scope);
if (selector->m_match == CSSSelector::Tag)
- return SelectorChecker::tagMatches(element, selector->tagQName());
+ return SelectorChecker::tagMatches(element, selector->tagQName(), elementIsHostInItsShadowTree ? MatchingHostInItsShadowTree : MatchingElement);
if (selector->m_match == CSSSelector::Class)
- return element->hasClass() && element->classNames().contains(selector->value());
+ return element.hasClass() && element.classNames().contains(selector->value()) && !elementIsHostInItsShadowTree;
if (selector->m_match == CSSSelector::Id)
- return element->hasID() && element->idForStyleResolution() == selector->value();
+ return element.hasID() && element.idForStyleResolution() == selector->value() && !elementIsHostInItsShadowTree;
if (selector->isAttributeSelector()) {
- const QualifiedName& attr = selector->attribute();
-
- if (!element->hasAttributes())
+ if (elementIsHostInItsShadowTree)
return false;
-
- bool caseSensitive = !m_documentIsHTML || HTMLDocument::isCaseSensitiveAttribute(attr);
-
- if (!anyAttributeMatches(element, static_cast<CSSSelector::Match>(selector->m_match), attr, selector->value(), caseSensitive))
+ if (!anyAttributeMatches(element, static_cast<CSSSelector::Match>(selector->m_match), *selector))
return false;
}
@@ -430,10 +503,10 @@ bool SelectorChecker::checkOne(const SelectorCheckingContext& context, const Sib
} else if (context.hasScrollbarPseudo) {
// CSS scrollbars match a specific subset of pseudo classes, and they have specialized rules for each
// (since there are no elements involved).
- return checkScrollbarPseudoClass(context, &element->document(), selector);
+ return checkScrollbarPseudoClass(context, &element.document(), selector);
} else if (context.hasSelectionPseudo) {
if (selector->pseudoType() == CSSSelector::PseudoWindowInactive)
- return !element->document().page()->focusController().isActive();
+ return !element.document().page()->focusController().isActive();
}
// Normal element pseudo class checking.
@@ -444,7 +517,7 @@ bool SelectorChecker::checkOne(const SelectorCheckingContext& context, const Sib
case CSSSelector::PseudoEmpty:
{
bool result = true;
- for (Node* n = element->firstChild(); n; n = n->nextSibling()) {
+ for (Node* n = element.firstChild(); n; n = n->nextSibling()) {
if (n->isElementNode()) {
result = false;
break;
@@ -458,20 +531,20 @@ bool SelectorChecker::checkOne(const SelectorCheckingContext& context, const Sib
}
}
if (m_mode == ResolvingStyle) {
- element->setStyleAffectedByEmpty();
+ element.setStyleAffectedByEmpty();
if (context.elementStyle)
context.elementStyle->setEmptyState(result);
- else if (element->renderStyle() && (element->document().styleEngine()->usesSiblingRules() || element->renderStyle()->unique()))
- element->renderStyle()->setEmptyState(result);
+ else if (element.renderStyle() && (element.document().styleEngine()->usesSiblingRules() || element.renderStyle()->unique()))
+ element.renderStyle()->setEmptyState(result);
}
return result;
}
case CSSSelector::PseudoFirstChild:
// first-child matches the first child that is an element
- if (Element* parent = element->parentElement()) {
- bool result = siblingTraversalStrategy.isFirstChild(element);
+ if (Element* parent = element.parentElement()) {
+ bool result = siblingTraversalStrategy.isFirstChild(&element);
if (m_mode == ResolvingStyle) {
- RenderStyle* childStyle = context.elementStyle ? context.elementStyle : element->renderStyle();
+ RenderStyle* childStyle = context.elementStyle ? context.elementStyle : element.renderStyle();
parent->setChildrenAffectedByFirstChildRules();
if (result && childStyle)
childStyle->setFirstChildState();
@@ -481,8 +554,8 @@ bool SelectorChecker::checkOne(const SelectorCheckingContext& context, const Sib
break;
case CSSSelector::PseudoFirstOfType:
// first-of-type matches the first element of its type
- if (Element* parent = element->parentElement()) {
- bool result = siblingTraversalStrategy.isFirstOfType(element, element->tagQName());
+ if (Element* parent = element.parentElement()) {
+ bool result = siblingTraversalStrategy.isFirstOfType(&element, element.tagQName());
if (m_mode == ResolvingStyle)
parent->setChildrenAffectedByForwardPositionalRules();
return result;
@@ -490,10 +563,10 @@ bool SelectorChecker::checkOne(const SelectorCheckingContext& context, const Sib
break;
case CSSSelector::PseudoLastChild:
// last-child matches the last child that is an element
- if (Element* parent = element->parentElement()) {
- bool result = parent->isFinishedParsingChildren() && siblingTraversalStrategy.isLastChild(element);
+ if (Element* parent = element.parentElement()) {
+ bool result = parent->isFinishedParsingChildren() && siblingTraversalStrategy.isLastChild(&element);
if (m_mode == ResolvingStyle) {
- RenderStyle* childStyle = context.elementStyle ? context.elementStyle : element->renderStyle();
+ RenderStyle* childStyle = context.elementStyle ? context.elementStyle : element.renderStyle();
parent->setChildrenAffectedByLastChildRules();
if (result && childStyle)
childStyle->setLastChildState();
@@ -503,20 +576,20 @@ bool SelectorChecker::checkOne(const SelectorCheckingContext& context, const Sib
break;
case CSSSelector::PseudoLastOfType:
// last-of-type matches the last element of its type
- if (Element* parent = element->parentElement()) {
+ if (Element* parent = element.parentElement()) {
if (m_mode == ResolvingStyle)
parent->setChildrenAffectedByBackwardPositionalRules();
if (!parent->isFinishedParsingChildren())
return false;
- return siblingTraversalStrategy.isLastOfType(element, element->tagQName());
+ return siblingTraversalStrategy.isLastOfType(&element, element.tagQName());
}
break;
case CSSSelector::PseudoOnlyChild:
- if (Element* parent = element->parentElement()) {
- bool firstChild = siblingTraversalStrategy.isFirstChild(element);
- bool onlyChild = firstChild && parent->isFinishedParsingChildren() && siblingTraversalStrategy.isLastChild(element);
+ if (Element* parent = element.parentElement()) {
+ bool firstChild = siblingTraversalStrategy.isFirstChild(&element);
+ bool onlyChild = firstChild && parent->isFinishedParsingChildren() && siblingTraversalStrategy.isLastChild(&element);
if (m_mode == ResolvingStyle) {
- RenderStyle* childStyle = context.elementStyle ? context.elementStyle : element->renderStyle();
+ RenderStyle* childStyle = context.elementStyle ? context.elementStyle : element.renderStyle();
parent->setChildrenAffectedByFirstChildRules();
parent->setChildrenAffectedByLastChildRules();
if (firstChild && childStyle)
@@ -529,24 +602,24 @@ bool SelectorChecker::checkOne(const SelectorCheckingContext& context, const Sib
break;
case CSSSelector::PseudoOnlyOfType:
// FIXME: This selector is very slow.
- if (Element* parent = element->parentElement()) {
+ if (Element* parent = element.parentElement()) {
if (m_mode == ResolvingStyle) {
parent->setChildrenAffectedByForwardPositionalRules();
parent->setChildrenAffectedByBackwardPositionalRules();
}
if (!parent->isFinishedParsingChildren())
return false;
- return siblingTraversalStrategy.isFirstOfType(element, element->tagQName()) && siblingTraversalStrategy.isLastOfType(element, element->tagQName());
+ return siblingTraversalStrategy.isFirstOfType(&element, element.tagQName()) && siblingTraversalStrategy.isLastOfType(&element, element.tagQName());
}
break;
case CSSSelector::PseudoNthChild:
if (!selector->parseNth())
break;
- if (Element* parent = element->parentElement()) {
- int count = 1 + siblingTraversalStrategy.countElementsBefore(element);
+ if (Element* parent = element.parentElement()) {
+ int count = 1 + siblingTraversalStrategy.countElementsBefore(&element);
if (m_mode == ResolvingStyle) {
- RenderStyle* childStyle = context.elementStyle ? context.elementStyle : element->renderStyle();
- element->setChildIndex(count);
+ RenderStyle* childStyle = context.elementStyle ? context.elementStyle : element.renderStyle();
+ element.setChildIndex(count);
if (childStyle)
childStyle->setUnique();
parent->setChildrenAffectedByForwardPositionalRules();
@@ -559,8 +632,8 @@ bool SelectorChecker::checkOne(const SelectorCheckingContext& context, const Sib
case CSSSelector::PseudoNthOfType:
if (!selector->parseNth())
break;
- if (Element* parent = element->parentElement()) {
- int count = 1 + siblingTraversalStrategy.countElementsOfTypeBefore(element, element->tagQName());
+ if (Element* parent = element.parentElement()) {
+ int count = 1 + siblingTraversalStrategy.countElementsOfTypeBefore(&element, element.tagQName());
if (m_mode == ResolvingStyle)
parent->setChildrenAffectedByForwardPositionalRules();
@@ -571,12 +644,12 @@ bool SelectorChecker::checkOne(const SelectorCheckingContext& context, const Sib
case CSSSelector::PseudoNthLastChild:
if (!selector->parseNth())
break;
- if (Element* parent = element->parentElement()) {
+ if (Element* parent = element.parentElement()) {
if (m_mode == ResolvingStyle)
parent->setChildrenAffectedByBackwardPositionalRules();
if (!parent->isFinishedParsingChildren())
return false;
- int count = 1 + siblingTraversalStrategy.countElementsAfter(element);
+ int count = 1 + siblingTraversalStrategy.countElementsAfter(&element);
if (selector->matchNth(count))
return true;
}
@@ -584,147 +657,144 @@ bool SelectorChecker::checkOne(const SelectorCheckingContext& context, const Sib
case CSSSelector::PseudoNthLastOfType:
if (!selector->parseNth())
break;
- if (Element* parent = element->parentElement()) {
+ if (Element* parent = element.parentElement()) {
if (m_mode == ResolvingStyle)
parent->setChildrenAffectedByBackwardPositionalRules();
if (!parent->isFinishedParsingChildren())
return false;
- int count = 1 + siblingTraversalStrategy.countElementsOfTypeAfter(element, element->tagQName());
+ int count = 1 + siblingTraversalStrategy.countElementsOfTypeAfter(&element, element.tagQName());
if (selector->matchNth(count))
return true;
}
break;
case CSSSelector::PseudoTarget:
- if (element == element->document().cssTarget())
+ if (element == element.document().cssTarget())
return true;
break;
case CSSSelector::PseudoAny:
{
SelectorCheckingContext subContext(context);
subContext.isSubSelector = true;
- PseudoId ignoreDynamicPseudo = NOPSEUDO;
ASSERT(selector->selectorList());
for (subContext.selector = selector->selectorList()->first(); subContext.selector; subContext.selector = CSSSelectorList::next(subContext.selector)) {
- if (match(subContext, ignoreDynamicPseudo, siblingTraversalStrategy) == SelectorMatches)
+ if (match(subContext, siblingTraversalStrategy) == SelectorMatches)
return true;
}
}
break;
case CSSSelector::PseudoAutofill:
- if (!element || !element->isFormControlElement())
+ if (!element.isFormControlElement())
break;
- if (element->hasTagName(inputTag))
- return toHTMLInputElement(element)->isAutofilled();
- break;
+ return toHTMLFormControlElement(element).isAutofilled();
case CSSSelector::PseudoAnyLink:
case CSSSelector::PseudoLink:
// :visited and :link matches are separated later when applying the style. Here both classes match all links...
- return element->isLink();
+ return element.isLink();
case CSSSelector::PseudoVisited:
// ...except if :visited matching is disabled for ancestor/sibling matching.
- return element->isLink() && context.visitedMatchType == VisitedMatchEnabled;
+ return element.isLink() && context.visitedMatchType == VisitedMatchEnabled;
case CSSSelector::PseudoDrag:
if (m_mode == ResolvingStyle) {
if (context.elementStyle)
context.elementStyle->setAffectedByDrag();
else
- element->setChildrenAffectedByDrag(true);
+ element.setChildrenAffectedByDrag();
}
- if (element->renderer() && element->renderer()->isDragging())
+ if (element.renderer() && element.renderer()->isDragging())
return true;
break;
case CSSSelector::PseudoFocus:
+ if (m_mode == ResolvingStyle) {
+ if (context.elementStyle)
+ context.elementStyle->setAffectedByFocus();
+ else
+ element.setChildrenAffectedByFocus();
+ }
return matchesFocusPseudoClass(element);
case CSSSelector::PseudoHover:
// If we're in quirks mode, then hover should never match anchors with no
// href and *:hover should not match anything. This is important for sites like wsj.com.
- if (m_strictParsing || context.isSubSelector || (selector->m_match == CSSSelector::Tag && selector->tagQName() != anyQName() && !isHTMLAnchorElement(element)) || element->isLink()) {
+ if (m_strictParsing || context.isSubSelector || (selector->m_match == CSSSelector::Tag && selector->tagQName() != anyQName() && !isHTMLAnchorElement(element)) || element.isLink()) {
if (m_mode == ResolvingStyle) {
if (context.elementStyle)
context.elementStyle->setAffectedByHover();
else
- element->setChildrenAffectedByHover(true);
+ element.setChildrenAffectedByHover();
}
- if (element->hovered() || InspectorInstrumentation::forcePseudoState(element, CSSSelector::PseudoHover))
+ if (element.hovered() || InspectorInstrumentation::forcePseudoState(&element, CSSSelector::PseudoHover))
return true;
}
break;
case CSSSelector::PseudoActive:
// If we're in quirks mode, then :active should never match anchors with no
// href and *:active should not match anything.
- if (m_strictParsing || context.isSubSelector || (selector->m_match == CSSSelector::Tag && selector->tagQName() != anyQName() && !isHTMLAnchorElement(element)) || element->isLink()) {
+ if (m_strictParsing || context.isSubSelector || (selector->m_match == CSSSelector::Tag && selector->tagQName() != anyQName() && !isHTMLAnchorElement(element)) || element.isLink()) {
if (m_mode == ResolvingStyle) {
if (context.elementStyle)
context.elementStyle->setAffectedByActive();
else
- element->setChildrenAffectedByActive(true);
+ element.setChildrenAffectedByActive();
}
- if (element->active() || InspectorInstrumentation::forcePseudoState(element, CSSSelector::PseudoActive))
+ if (element.active() || InspectorInstrumentation::forcePseudoState(&element, CSSSelector::PseudoActive))
return true;
}
break;
case CSSSelector::PseudoEnabled:
- if (element && (element->isFormControlElement() || element->hasTagName(optionTag) || isHTMLOptGroupElement(element)))
- return !element->isDisabledFormControl();
+ if (element.isFormControlElement() || element.hasTagName(optionTag) || isHTMLOptGroupElement(element))
+ return !element.isDisabledFormControl();
break;
case CSSSelector::PseudoFullPageMedia:
- return element && element->document().isMediaDocument();
+ return element.document().isMediaDocument();
break;
case CSSSelector::PseudoDefault:
- return element && element->isDefaultButtonForForm();
+ return element.isDefaultButtonForForm();
case CSSSelector::PseudoDisabled:
- if (element && (element->isFormControlElement() || element->hasTagName(optionTag) || isHTMLOptGroupElement(element)))
- return element->isDisabledFormControl();
+ if (element.isFormControlElement() || element.hasTagName(optionTag) || isHTMLOptGroupElement(element))
+ return element.isDisabledFormControl();
break;
case CSSSelector::PseudoReadOnly:
- return element && element->matchesReadOnlyPseudoClass();
+ return element.matchesReadOnlyPseudoClass();
case CSSSelector::PseudoReadWrite:
- return element && element->matchesReadWritePseudoClass();
+ return element.matchesReadWritePseudoClass();
case CSSSelector::PseudoOptional:
- return element && element->isOptionalFormControl();
+ return element.isOptionalFormControl();
case CSSSelector::PseudoRequired:
- return element && element->isRequiredFormControl();
+ return element.isRequiredFormControl();
case CSSSelector::PseudoValid:
- if (!element)
- return false;
- element->document().setContainsValidityStyleRules();
- return element->willValidate() && element->isValidFormControlElement();
+ element.document().setContainsValidityStyleRules();
+ return element.willValidate() && element.isValidFormControlElement();
case CSSSelector::PseudoInvalid:
- if (!element)
- return false;
- element->document().setContainsValidityStyleRules();
- return element->willValidate() && !element->isValidFormControlElement();
+ element.document().setContainsValidityStyleRules();
+ return element.willValidate() && !element.isValidFormControlElement();
case CSSSelector::PseudoChecked:
{
- if (!element)
- break;
- if (element->hasTagName(inputTag)) {
- HTMLInputElement* inputElement = toHTMLInputElement(element);
+ if (element.hasTagName(inputTag)) {
+ HTMLInputElement& inputElement = toHTMLInputElement(element);
// Even though WinIE allows checked and indeterminate to
// co-exist, the CSS selector spec says that you can't be
// both checked and indeterminate. We will behave like WinIE
// behind the scenes and just obey the CSS spec here in the
// test for matching the pseudo.
- if (inputElement->shouldAppearChecked() && !inputElement->shouldAppearIndeterminate())
+ if (inputElement.shouldAppearChecked() && !inputElement.shouldAppearIndeterminate())
return true;
- } else if (element->hasTagName(optionTag) && toHTMLOptionElement(element)->selected())
+ } else if (element.hasTagName(optionTag) && toHTMLOptionElement(element).selected())
return true;
break;
}
case CSSSelector::PseudoIndeterminate:
- return element && element->shouldAppearIndeterminate();
+ return element.shouldAppearIndeterminate();
case CSSSelector::PseudoRoot:
- if (element == element->document().documentElement())
+ if (element == element.document().documentElement())
return true;
break;
case CSSSelector::PseudoLang:
{
AtomicString value;
- if (element->isWebVTTElement())
- value = toWebVTTElement(element)->language();
+ if (element.isVTTElement())
+ value = toVTTElement(element).language();
else
- value = element->computeInheritedLanguage();
+ value = element.computeInheritedLanguage();
const AtomicString& argument = selector->argument();
if (value.isEmpty() || !value.startsWith(argument, false))
break;
@@ -737,51 +807,47 @@ bool SelectorChecker::checkOne(const SelectorCheckingContext& context, const Sib
// element is an element in the document, the 'full-screen' pseudoclass applies to
// that element. Also, an <iframe>, <object> or <embed> element whose child browsing
// context's Document is in the fullscreen state has the 'full-screen' pseudoclass applied.
- if (element->isFrameElementBase() && element->containsFullScreenElement())
+ if (element.isFrameElementBase() && element.containsFullScreenElement())
return true;
- if (FullscreenElementStack* fullscreen = FullscreenElementStack::fromIfExists(&element->document())) {
+ if (FullscreenElementStack* fullscreen = FullscreenElementStack::fromIfExists(&element.document())) {
if (!fullscreen->webkitIsFullScreen())
return false;
return element == fullscreen->webkitCurrentFullScreenElement();
}
return false;
case CSSSelector::PseudoFullScreenAncestor:
- return element->containsFullScreenElement();
+ return element.containsFullScreenElement();
case CSSSelector::PseudoFullScreenDocument:
// While a Document is in the fullscreen state, the 'full-screen-document' pseudoclass applies
// to all elements of that Document.
- if (!FullscreenElementStack::isFullScreen(&element->document()))
+ if (!FullscreenElementStack::isFullScreen(&element.document()))
return false;
return true;
case CSSSelector::PseudoSeamlessDocument:
// While a document is rendered in a seamless iframe, the 'seamless-document' pseudoclass applies
// to all elements of that Document.
- return element->document().shouldDisplaySeamlesslyWithParent();
+ return element.document().shouldDisplaySeamlesslyWithParent();
case CSSSelector::PseudoInRange:
- if (!element)
- return false;
- element->document().setContainsValidityStyleRules();
- return element->isInRange();
+ element.document().setContainsValidityStyleRules();
+ return element.isInRange();
case CSSSelector::PseudoOutOfRange:
- if (!element)
- return false;
- element->document().setContainsValidityStyleRules();
- return element->isOutOfRange();
+ element.document().setContainsValidityStyleRules();
+ return element.isOutOfRange();
case CSSSelector::PseudoFutureCue:
- return (element->isWebVTTElement() && !toWebVTTElement(element)->isPastNode());
+ return (element.isVTTElement() && !toVTTElement(element).isPastNode());
case CSSSelector::PseudoPastCue:
- return (element->isWebVTTElement() && toWebVTTElement(element)->isPastNode());
+ return (element.isVTTElement() && toVTTElement(element).isPastNode());
case CSSSelector::PseudoScope:
{
- const Node* contextualReferenceNode = !context.scope || (context.behaviorAtBoundary & BoundaryBehaviorMask) == CrossesBoundary ? element->document().documentElement() : context.scope;
+ const Node* contextualReferenceNode = !context.scope || (context.behaviorAtBoundary & BoundaryBehaviorMask) == CrossesBoundary ? element.document().documentElement() : context.scope;
if (element == contextualReferenceNode)
return true;
break;
}
case CSSSelector::PseudoUnresolved:
- if (element->isUnresolvedCustomElement())
+ if (element.isUnresolvedCustomElement())
return true;
break;
@@ -790,26 +856,41 @@ bool SelectorChecker::checkOne(const SelectorCheckingContext& context, const Sib
// :host only matches a shadow host when :host is in a shadow tree of the shadow host.
if (!context.scope || !(context.behaviorAtBoundary & ScopeIsShadowHost) || context.scope != element)
return false;
- ASSERT(element->shadow());
+ ASSERT(element.shadow());
// For empty parameter case, i.e. just :host or :host().
- if (!selector->selectorList())
+ if (!selector->selectorList()) // Use *'s specificity. So just 0.
return true;
SelectorCheckingContext subContext(context);
subContext.isSubSelector = true;
- subContext.behaviorAtBoundary = CrossesBoundary;
- subContext.scope = 0;
- // Use NodeRenderingTraversal to traverse a composed ancestor list of a given element.
- for (Element* nextElement = NodeRenderingTraversal::parentElement(element); nextElement; nextElement = NodeRenderingTraversal::parentElement(nextElement)) {
- // If one of simple selectors matches an element, returns SelectorMatches. Just "OR".
- for (subContext.selector = selector->selectorList()->first(); subContext.selector; subContext.selector = CSSSelectorList::next(subContext.selector)) {
- PseudoId ignoreDynamicPseudo = NOPSEUDO;
+
+ bool matched = false;
+ unsigned maxSpecificity = 0;
+
+ // If one of simple selectors matches an element, returns SelectorMatches. Just "OR".
+ for (subContext.selector = selector->selectorList()->first(); subContext.selector; subContext.selector = CSSSelectorList::next(subContext.selector)) {
+ subContext.behaviorAtBoundary = ScopeIsShadowHostInPseudoHostParameter;
+ subContext.scope = context.scope;
+ // Use NodeRenderingTraversal to traverse a composed ancestor list of a given element.
+ for (Element* nextElement = &element; nextElement; nextElement = NodeRenderingTraversal::parentElement(nextElement)) {
+ MatchResult subResult;
subContext.element = nextElement;
- if (match(subContext, ignoreDynamicPseudo, siblingTraversalStrategy) == SelectorMatches)
- return true;
+ if (match(subContext, siblingTraversalStrategy, &subResult) == SelectorMatches) {
+ matched = true;
+ // Consider div:host(div:host(div:host(div:host...))).
+ maxSpecificity = std::max(maxSpecificity, subContext.selector->specificity() + subResult.specificity);
+ break;
+ }
+ subContext.behaviorAtBoundary = CrossesBoundary;
+ subContext.scope = 0;
}
}
+ if (matched) {
+ if (specificity)
+ *specificity = maxSpecificity;
+ return true;
+ }
}
break;
@@ -838,10 +919,9 @@ bool SelectorChecker::checkOne(const SelectorCheckingContext& context, const Sib
subContext.isSubSelector = true;
subContext.behaviorAtBoundary = StaysWithinTreeScope;
- PseudoId ignoreDynamicPseudo = NOPSEUDO;
const CSSSelector* const & selector = context.selector;
for (subContext.selector = selector->selectorList()->first(); subContext.selector; subContext.selector = CSSSelectorList::next(subContext.selector)) {
- if (match(subContext, ignoreDynamicPseudo, siblingTraversalStrategy) == SelectorMatches)
+ if (match(subContext, siblingTraversalStrategy) == SelectorMatches)
return true;
}
return false;
@@ -973,22 +1053,22 @@ unsigned SelectorChecker::determineLinkMatchType(const CSSSelector* selector)
return linkMatchType;
}
-bool SelectorChecker::isFrameFocused(const Element* element)
+bool SelectorChecker::isFrameFocused(const Element& element)
{
- return element->document().frame() && element->document().frame()->selection().isFocusedAndActive();
+ return element.document().frame() && element.document().frame()->selection().isFocusedAndActive();
}
-bool SelectorChecker::matchesFocusPseudoClass(const Element* element)
+bool SelectorChecker::matchesFocusPseudoClass(const Element& element)
{
- if (InspectorInstrumentation::forcePseudoState(const_cast<Element*>(element), CSSSelector::PseudoFocus))
+ if (InspectorInstrumentation::forcePseudoState(const_cast<Element*>(&element), CSSSelector::PseudoFocus))
return true;
- return element->focused() && isFrameFocused(element);
+ return element.focused() && isFrameFocused(element);
}
template
-SelectorChecker::Match SelectorChecker::match(const SelectorCheckingContext&, PseudoId&, const DOMSiblingTraversalStrategy&) const;
+SelectorChecker::Match SelectorChecker::match(const SelectorCheckingContext&, const DOMSiblingTraversalStrategy&, MatchResult*) const;
template
-SelectorChecker::Match SelectorChecker::match(const SelectorCheckingContext&, PseudoId&, const ShadowDOMSiblingTraversalStrategy&) const;
+SelectorChecker::Match SelectorChecker::match(const SelectorCheckingContext&, const ShadowDOMSiblingTraversalStrategy&, MatchResult*) const;
}
diff --git a/chromium/third_party/WebKit/Source/core/css/SelectorChecker.h b/chromium/third_party/WebKit/Source/core/css/SelectorChecker.h
index aba4e034d66..13d7d7dc1fc 100644
--- a/chromium/third_party/WebKit/Source/core/css/SelectorChecker.h
+++ b/chromium/third_party/WebKit/Source/core/css/SelectorChecker.h
@@ -29,11 +29,13 @@
#define SelectorChecker_h
#include "core/css/CSSSelector.h"
-#include "core/inspector/InspectorInstrumentation.h"
+#include "core/dom/Element.h"
+#include "platform/scroll/ScrollTypes.h"
namespace WebCore {
class CSSSelector;
+class ContainerNode;
class Element;
class RenderScrollbar;
class RenderStyle;
@@ -43,7 +45,7 @@ class SelectorChecker {
public:
enum Match { SelectorMatches, SelectorFailsLocally, SelectorFailsAllSiblings, SelectorFailsCompletely };
enum VisitedMatchType { VisitedMatchDisabled, VisitedMatchEnabled };
- enum Mode { ResolvingStyle = 0, CollectingRules, QueryingRules, SharingRules };
+ enum Mode { ResolvingStyle = 0, CollectingStyleRules, CollectingCSSRules, QueryingRules, SharingRules };
explicit SelectorChecker(Document&, Mode);
enum BehaviorAtBoundary {
DoesNotCrossBoundary = 0,
@@ -51,7 +53,15 @@ public:
StaysWithinTreeScope = 2,
BoundaryBehaviorMask = 3, // 2bit for boundary behavior
ScopeContainsLastMatchedElement = 4,
- ScopeIsShadowHost = 8
+ ScopeIsShadowHost = 8,
+ TreatShadowHostAsNormalScope = 16,
+
+ ScopeIsShadowHostInPseudoHostParameter = CrossesBoundary | ScopeIsShadowHost | TreatShadowHostAsNormalScope
+ };
+
+ enum MatchingTagType {
+ MatchingElement = 0,
+ MatchingHostInItsShadowTree
};
struct SelectorCheckingContext {
@@ -85,33 +95,48 @@ public:
BehaviorAtBoundary behaviorAtBoundary;
};
- template<typename SiblingTraversalStrategy>
- Match match(const SelectorCheckingContext&, PseudoId&, const SiblingTraversalStrategy&) const;
+ struct MatchResult {
+ MatchResult()
+ : dynamicPseudo(NOPSEUDO)
+ , specificity(0) { }
+
+ PseudoId dynamicPseudo;
+ unsigned specificity;
+ };
template<typename SiblingTraversalStrategy>
- Match matchForShadowDistributed(const Element*, const SiblingTraversalStrategy&, PseudoId&, SelectorCheckingContext& nextContext) const;
+ Match match(const SelectorCheckingContext&, const SiblingTraversalStrategy&, MatchResult* = 0) const;
template<typename SiblingTraversalStrategy>
- bool checkOne(const SelectorCheckingContext&, const SiblingTraversalStrategy&) const;
+ bool checkOne(const SelectorCheckingContext&, const SiblingTraversalStrategy&, unsigned* specificity = 0) const;
bool strictParsing() const { return m_strictParsing; }
Mode mode() const { return m_mode; }
- static bool tagMatches(const Element*, const QualifiedName&);
+ static bool tagMatches(const Element&, const QualifiedName&, MatchingTagType = MatchingElement);
static bool isCommonPseudoClassSelector(const CSSSelector*);
- static bool matchesFocusPseudoClass(const Element*);
- static bool checkExactAttribute(const Element*, const QualifiedName& selectorAttributeName, const StringImpl* value);
+ static bool matchesFocusPseudoClass(const Element&);
+ static bool checkExactAttribute(const Element&, const QualifiedName& selectorAttributeName, const StringImpl* value);
enum LinkMatchMask { MatchLink = 1, MatchVisited = 2, MatchAll = MatchLink | MatchVisited };
static unsigned determineLinkMatchType(const CSSSelector*);
+ static bool isHostInItsShadowTree(const Element&, BehaviorAtBoundary, const ContainerNode* scope);
+
private:
+ template<typename SiblingTraversalStrategy>
+ Match matchForSubSelector(const SelectorCheckingContext&, const SiblingTraversalStrategy&, MatchResult*) const;
+ template<typename SiblingTraversalStrategy>
+ Match matchForRelation(const SelectorCheckingContext&, const SiblingTraversalStrategy&, MatchResult*) const;
+ template<typename SiblingTraversalStrategy>
+ Match matchForShadowDistributed(const Element*, const SiblingTraversalStrategy&, SelectorCheckingContext& nextContext, MatchResult* = 0) const;
+
bool checkScrollbarPseudoClass(const SelectorCheckingContext&, Document*, const CSSSelector*) const;
Element* parentElement(const SelectorCheckingContext&) const;
bool scopeContainsLastMatchedElement(const SelectorCheckingContext&) const;
- static bool isFrameFocused(const Element*);
+ static bool isFrameFocused(const Element&);
bool m_strictParsing;
bool m_documentIsHTML;
@@ -129,30 +154,35 @@ inline bool SelectorChecker::isCommonPseudoClassSelector(const CSSSelector* sele
|| pseudoType == CSSSelector::PseudoFocus;
}
-inline bool SelectorChecker::tagMatches(const Element* element, const QualifiedName& tagQName)
+inline bool SelectorChecker::tagMatches(const Element& element, const QualifiedName& tagQName, MatchingTagType matchingTagType)
{
if (tagQName == anyQName())
return true;
const AtomicString& localName = tagQName.localName();
- if (localName != starAtom && localName != element->localName())
+ if (localName != starAtom && (localName != element.localName() || matchingTagType == MatchingHostInItsShadowTree))
return false;
const AtomicString& namespaceURI = tagQName.namespaceURI();
- return namespaceURI == starAtom || namespaceURI == element->namespaceURI();
+ return namespaceURI == starAtom || namespaceURI == element.namespaceURI();
}
-inline bool SelectorChecker::checkExactAttribute(const Element* element, const QualifiedName& selectorAttributeName, const StringImpl* value)
+inline bool SelectorChecker::checkExactAttribute(const Element& element, const QualifiedName& selectorAttributeName, const StringImpl* value)
{
- if (!element->hasAttributesWithoutUpdate())
+ if (!element.hasAttributesWithoutUpdate())
return false;
- unsigned size = element->attributeCount();
+ unsigned size = element.attributeCount();
for (unsigned i = 0; i < size; ++i) {
- const Attribute* attribute = element->attributeItem(i);
+ const Attribute* attribute = element.attributeItem(i);
if (attribute->matches(selectorAttributeName) && (!value || attribute->value().impl() == value))
return true;
}
return false;
}
+inline bool SelectorChecker::isHostInItsShadowTree(const Element& element, BehaviorAtBoundary behaviorAtBoundary, const ContainerNode* scope)
+{
+ return (behaviorAtBoundary & (ScopeIsShadowHost | TreatShadowHostAsNormalScope)) == ScopeIsShadowHost && scope == element;
+}
+
}
#endif
diff --git a/chromium/third_party/WebKit/Source/core/css/SelectorCheckerFastPath.cpp b/chromium/third_party/WebKit/Source/core/css/SelectorCheckerFastPath.cpp
index 7c8fecb8691..557f0438a56 100644
--- a/chromium/third_party/WebKit/Source/core/css/SelectorCheckerFastPath.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/SelectorCheckerFastPath.cpp
@@ -39,11 +39,11 @@ using namespace HTMLNames;
namespace {
-template <bool checkValue(const Element*, const CSSSelector*)>
+template <bool checkValue(const Element&, const CSSSelector*)>
inline bool fastCheckSingleSelector(const CSSSelector*& selector, const Element*& element, const CSSSelector*& topChildOrSubselector, const Element*& topChildOrSubselectorMatchElement)
{
for (; element; element = element->parentElement()) {
- if (checkValue(element, selector)) {
+ if (checkValue(*element, selector)) {
if (selector->relation() == CSSSelector::Descendant)
topChildOrSubselector = 0;
else if (!topChildOrSubselector) {
@@ -73,29 +73,29 @@ inline bool fastCheckSingleSelector(const CSSSelector*& selector, const Element*
return false;
}
-inline bool checkClassValue(const Element* element, const CSSSelector* selector)
+inline bool checkClassValue(const Element& element, const CSSSelector* selector)
{
- return element->hasClass() && element->classNames().contains(selector->value().impl());
+ return element.hasClass() && element.classNames().contains(selector->value());
}
-inline bool checkIDValue(const Element* element, const CSSSelector* selector)
+inline bool checkIDValue(const Element& element, const CSSSelector* selector)
{
- return element->hasID() && element->idForStyleResolution().impl() == selector->value().impl();
+ return element.hasID() && element.idForStyleResolution() == selector->value();
}
-inline bool checkExactAttributeValue(const Element* element, const CSSSelector* selector)
+inline bool checkExactAttributeValue(const Element& element, const CSSSelector* selector)
{
return SelectorChecker::checkExactAttribute(element, selector->attribute(), selector->value().impl());
}
-inline bool checkTagValue(const Element* element, const CSSSelector* selector)
+inline bool checkTagValue(const Element& element, const CSSSelector* selector)
{
return SelectorChecker::tagMatches(element, selector->tagQName());
}
}
-SelectorCheckerFastPath::SelectorCheckerFastPath(const CSSSelector* selector, const Element* element)
+SelectorCheckerFastPath::SelectorCheckerFastPath(const CSSSelector* selector, const Element& element)
: m_selector(selector)
, m_element(element)
{
@@ -127,7 +127,7 @@ bool SelectorCheckerFastPath::matches() const
{
ASSERT(matchesRightmostSelector(SelectorChecker::VisitedMatchEnabled));
const CSSSelector* selector = m_selector;
- const Element* element = m_element;
+ const Element* element = &m_element;
const CSSSelector* topChildOrSubselector = 0;
const Element* topChildOrSubselectorMatchElement = 0;
@@ -209,9 +209,9 @@ bool SelectorCheckerFastPath::commonPseudoClassSelectorMatches(SelectorChecker::
switch (m_selector->pseudoType()) {
case CSSSelector::PseudoLink:
case CSSSelector::PseudoAnyLink:
- return m_element->isLink();
+ return m_element.isLink();
case CSSSelector::PseudoVisited:
- return m_element->isLink() && visitedMatchType == SelectorChecker::VisitedMatchEnabled;
+ return m_element.isLink() && visitedMatchType == SelectorChecker::VisitedMatchEnabled;
case CSSSelector::PseudoFocus:
return SelectorChecker::matchesFocusPseudoClass(m_element);
default:
diff --git a/chromium/third_party/WebKit/Source/core/css/SelectorCheckerFastPath.h b/chromium/third_party/WebKit/Source/core/css/SelectorCheckerFastPath.h
index 819ecbc332a..1a37b9ac35a 100644
--- a/chromium/third_party/WebKit/Source/core/css/SelectorCheckerFastPath.h
+++ b/chromium/third_party/WebKit/Source/core/css/SelectorCheckerFastPath.h
@@ -36,7 +36,7 @@ namespace WebCore {
class SelectorCheckerFastPath {
public:
- SelectorCheckerFastPath(const CSSSelector*, const Element*);
+ SelectorCheckerFastPath(const CSSSelector*, const Element&);
bool matches() const;
bool matchesRightmostSelector(SelectorChecker::VisitedMatchType) const;
@@ -48,7 +48,7 @@ private:
bool commonPseudoClassSelectorMatches(SelectorChecker::VisitedMatchType) const;
const CSSSelector* m_selector;
- const Element* m_element;
+ const Element& m_element;
};
inline bool SelectorCheckerFastPath::matchesRightmostAttributeSelector() const
diff --git a/chromium/third_party/WebKit/Source/core/css/SelectorFilter.cpp b/chromium/third_party/WebKit/Source/core/css/SelectorFilter.cpp
index d24cdd38cd8..50d13de6b48 100644
--- a/chromium/third_party/WebKit/Source/core/css/SelectorFilter.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/SelectorFilter.cpp
@@ -30,31 +30,30 @@
#include "core/css/SelectorFilter.h"
#include "core/css/CSSSelector.h"
-#include "core/dom/Element.h"
namespace WebCore {
// Salt to separate otherwise identical string hashes so a class-selector like .article won't match <article> elements.
enum { TagNameSalt = 13, IdAttributeSalt = 17, ClassAttributeSalt = 19 };
-static inline void collectElementIdentifierHashes(const Element* element, Vector<unsigned, 4>& identifierHashes)
+static inline void collectElementIdentifierHashes(const Element& element, Vector<unsigned, 4>& identifierHashes)
{
- identifierHashes.append(element->localName().impl()->existingHash() * TagNameSalt);
- if (element->hasID())
- identifierHashes.append(element->idForStyleResolution().impl()->existingHash() * IdAttributeSalt);
- if (element->isStyledElement() && element->hasClass()) {
- const SpaceSplitString& classNames = element->classNames();
+ identifierHashes.append(element.localName().impl()->existingHash() * TagNameSalt);
+ if (element.hasID())
+ identifierHashes.append(element.idForStyleResolution().impl()->existingHash() * IdAttributeSalt);
+ if (element.isStyledElement() && element.hasClass()) {
+ const SpaceSplitString& classNames = element.classNames();
size_t count = classNames.size();
for (size_t i = 0; i < count; ++i)
identifierHashes.append(classNames[i].impl()->existingHash() * ClassAttributeSalt);
}
}
-void SelectorFilter::pushParentStackFrame(Element* parent)
+void SelectorFilter::pushParentStackFrame(Element& parent)
{
ASSERT(m_ancestorIdentifierFilter);
- ASSERT(m_parentStack.isEmpty() || m_parentStack.last().element == parent->parentOrShadowHostElement());
- ASSERT(!m_parentStack.isEmpty() || !parent->parentOrShadowHostElement());
+ ASSERT(m_parentStack.isEmpty() || m_parentStack.last().element == parent.parentOrShadowHostElement());
+ ASSERT(!m_parentStack.isEmpty() || !parent.parentOrShadowHostElement());
m_parentStack.append(ParentStackFrame(parent));
ParentStackFrame& parentFrame = m_parentStack.last();
// Mix tags, class names and ids into some sort of weird bouillabaisse.
@@ -80,31 +79,31 @@ void SelectorFilter::popParentStackFrame()
}
}
-void SelectorFilter::setupParentStack(Element* parent)
+void SelectorFilter::setupParentStack(Element& parent)
{
ASSERT(m_parentStack.isEmpty() == !m_ancestorIdentifierFilter);
// Kill whatever we stored before.
m_parentStack.shrink(0);
m_ancestorIdentifierFilter = adoptPtr(new BloomFilter<bloomFilterKeyBits>);
// Fast version if parent is a root element:
- if (!parent->parentOrShadowHostNode()) {
+ if (!parent.parentOrShadowHostNode()) {
pushParentStackFrame(parent);
return;
}
// Otherwise climb up the tree.
Vector<Element*, 30> ancestors;
- for (Element* ancestor = parent; ancestor; ancestor = ancestor->parentOrShadowHostElement())
+ for (Element* ancestor = &parent; ancestor; ancestor = ancestor->parentOrShadowHostElement())
ancestors.append(ancestor);
for (size_t n = ancestors.size(); n; --n)
- pushParentStackFrame(ancestors[n - 1]);
+ pushParentStackFrame(*ancestors[n - 1]);
}
-void SelectorFilter::pushParent(Element* parent)
+void SelectorFilter::pushParent(Element& parent)
{
ASSERT(m_ancestorIdentifierFilter);
// We may get invoked for some random elements in some wacky cases during style resolve.
// Pause maintaining the stack in this case.
- if (m_parentStack.last().element != parent->parentOrShadowHostElement())
+ if (m_parentStack.last().element != parent.parentOrShadowHostElement())
return;
pushParentStackFrame(parent);
}
@@ -153,9 +152,13 @@ void SelectorFilter::collectIdentifierHashes(const CSSSelector* selector, unsign
case CSSSelector::Descendant:
case CSSSelector::Child:
if (relationIsAffectedByPseudoContent) {
- skipOverSubselectors = true;
- break;
+ // Disable fastRejectSelector.
+ *identifierHashes = 0;
+ return;
}
+ // Fall through.
+ case CSSSelector::ChildTree:
+ case CSSSelector::DescendantTree:
skipOverSubselectors = false;
collectDescendantSelectorIdentifierHashes(selector, hash);
break;
diff --git a/chromium/third_party/WebKit/Source/core/css/SelectorFilter.h b/chromium/third_party/WebKit/Source/core/css/SelectorFilter.h
index 4ffde10719e..905edb6dd30 100644
--- a/chromium/third_party/WebKit/Source/core/css/SelectorFilter.h
+++ b/chromium/third_party/WebKit/Source/core/css/SelectorFilter.h
@@ -39,11 +39,11 @@ class CSSSelector;
class SelectorFilter {
public:
- void pushParentStackFrame(Element* parent);
+ void pushParentStackFrame(Element& parent);
void popParentStackFrame();
- void setupParentStack(Element* parent);
- void pushParent(Element* parent);
+ void setupParentStack(Element& parent);
+ void pushParent(Element& parent);
void popParent() { popParentStackFrame(); }
bool parentStackIsEmpty() const { return m_parentStack.isEmpty(); }
bool parentStackIsConsistent(const ContainerNode* parentNode) const { return !m_parentStack.isEmpty() && m_parentStack.last().element == parentNode; }
@@ -55,7 +55,7 @@ public:
private:
struct ParentStackFrame {
ParentStackFrame() : element(0) { }
- ParentStackFrame(Element* element) : element(element) { }
+ ParentStackFrame(Element& element) : element(&element) { }
Element* element;
Vector<unsigned, 4> identifierHashes;
};
diff --git a/chromium/third_party/WebKit/Source/core/css/ShadowValue.cpp b/chromium/third_party/WebKit/Source/core/css/ShadowValue.cpp
deleted file mode 100644
index 1ee8b1d5e63..00000000000
--- a/chromium/third_party/WebKit/Source/core/css/ShadowValue.cpp
+++ /dev/null
@@ -1,91 +0,0 @@
-/**
- * (C) 1999-2003 Lars Knoll (knoll@kde.org)
- * Copyright (C) 2004, 2005, 2006, 2009 Apple Computer, Inc.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-#include "config.h"
-#include "core/css/ShadowValue.h"
-
-#include "core/css/CSSPrimitiveValue.h"
-#include "wtf/text/StringBuilder.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-// Used for text-shadow and box-shadow
-ShadowValue::ShadowValue(PassRefPtr<CSSPrimitiveValue> _x,
- PassRefPtr<CSSPrimitiveValue> _y,
- PassRefPtr<CSSPrimitiveValue> _blur,
- PassRefPtr<CSSPrimitiveValue> _spread,
- PassRefPtr<CSSPrimitiveValue> _style,
- PassRefPtr<CSSPrimitiveValue> _color)
- : CSSValue(ShadowClass)
- , x(_x)
- , y(_y)
- , blur(_blur)
- , spread(_spread)
- , style(_style)
- , color(_color)
-{
-}
-
-String ShadowValue::customCssText() const
-{
- StringBuilder text;
-
- if (color)
- text.append(color->cssText());
- if (x) {
- if (!text.isEmpty())
- text.append(' ');
- text.append(x->cssText());
- }
- if (y) {
- if (!text.isEmpty())
- text.append(' ');
- text.append(y->cssText());
- }
- if (blur) {
- if (!text.isEmpty())
- text.append(' ');
- text.append(blur->cssText());
- }
- if (spread) {
- if (!text.isEmpty())
- text.append(' ');
- text.append(spread->cssText());
- }
- if (style) {
- if (!text.isEmpty())
- text.append(' ');
- text.append(style->cssText());
- }
-
- return text.toString();
-}
-
-bool ShadowValue::equals(const ShadowValue& other) const
-{
- return compareCSSValuePtr(color, other.color)
- && compareCSSValuePtr(x, other.x)
- && compareCSSValuePtr(y, other.y)
- && compareCSSValuePtr(blur, other.blur)
- && compareCSSValuePtr(spread, other.spread)
- && compareCSSValuePtr(style, other.style);
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/css/ShadowValue.h b/chromium/third_party/WebKit/Source/core/css/ShadowValue.h
deleted file mode 100644
index 6e0192e4638..00000000000
--- a/chromium/third_party/WebKit/Source/core/css/ShadowValue.h
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * (C) 1999-2003 Lars Knoll (knoll@kde.org)
- * Copyright (C) 2004, 2005, 2006, 2008, 2009 Apple Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#ifndef ShadowValue_h
-#define ShadowValue_h
-
-#include "core/css/CSSValue.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefPtr.h"
-
-namespace WebCore {
-
-class CSSPrimitiveValue;
-
-// Used for text-shadow and box-shadow
-class ShadowValue : public CSSValue {
-public:
- static PassRefPtr<ShadowValue> create(PassRefPtr<CSSPrimitiveValue> x,
- PassRefPtr<CSSPrimitiveValue> y,
- PassRefPtr<CSSPrimitiveValue> blur,
- PassRefPtr<CSSPrimitiveValue> spread,
- PassRefPtr<CSSPrimitiveValue> style,
- PassRefPtr<CSSPrimitiveValue> color)
- {
- return adoptRef(new ShadowValue(x, y, blur, spread, style, color));
- }
-
- String customCssText() const;
-
- bool equals(const ShadowValue&) const;
-
- RefPtr<CSSPrimitiveValue> x;
- RefPtr<CSSPrimitiveValue> y;
- RefPtr<CSSPrimitiveValue> blur;
- RefPtr<CSSPrimitiveValue> spread;
- RefPtr<CSSPrimitiveValue> style;
- RefPtr<CSSPrimitiveValue> color;
-
-private:
- ShadowValue(PassRefPtr<CSSPrimitiveValue> x,
- PassRefPtr<CSSPrimitiveValue> y,
- PassRefPtr<CSSPrimitiveValue> blur,
- PassRefPtr<CSSPrimitiveValue> spread,
- PassRefPtr<CSSPrimitiveValue> style,
- PassRefPtr<CSSPrimitiveValue> color);
-};
-
-} // namespace
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/css/SiblingTraversalStrategies.h b/chromium/third_party/WebKit/Source/core/css/SiblingTraversalStrategies.h
index 65885c93549..b082fa6df0e 100644
--- a/chromium/third_party/WebKit/Source/core/css/SiblingTraversalStrategies.h
+++ b/chromium/third_party/WebKit/Source/core/css/SiblingTraversalStrategies.h
@@ -31,7 +31,6 @@
#include "core/dom/Element.h"
#include "core/rendering/style/RenderStyle.h"
-#include "wtf/UnusedParam.h"
namespace WebCore {
@@ -98,14 +97,8 @@ inline int DOMSiblingTraversalStrategy::countElementsOfTypeBefore(Element* eleme
inline int DOMSiblingTraversalStrategy::countElementsAfter(Element* element) const
{
int count = 0;
- for (const Element* sibling = element->nextElementSibling(); sibling; sibling = sibling->nextElementSibling()) {
- unsigned index = sibling->childIndex();
- if (index) {
- count += index;
- break;
- }
+ for (const Element* sibling = element->nextElementSibling(); sibling; sibling = sibling->nextElementSibling())
++count;
- }
return count;
}
@@ -122,7 +115,7 @@ inline int DOMSiblingTraversalStrategy::countElementsOfTypeAfter(Element* elemen
}
struct ShadowDOMSiblingTraversalStrategy {
- ShadowDOMSiblingTraversalStrategy(const Vector<Node*>& siblings, int nth)
+ ShadowDOMSiblingTraversalStrategy(const Vector<Node*, 32>& siblings, int nth)
: m_siblings(siblings)
, m_nth(nth)
{
@@ -139,14 +132,12 @@ struct ShadowDOMSiblingTraversalStrategy {
int countElementsOfTypeAfter(Element*, const QualifiedName&) const;
private:
- Vector<Node*> m_siblings;
+ const Vector<Node*, 32>& m_siblings;
int m_nth;
};
inline bool ShadowDOMSiblingTraversalStrategy::isFirstChild(Element* element) const
{
- UNUSED_PARAM(element);
-
ASSERT(element == toElement(m_siblings[m_nth]));
for (int i = m_nth - 1; i >= 0; --i) {
@@ -159,8 +150,6 @@ inline bool ShadowDOMSiblingTraversalStrategy::isFirstChild(Element* element) co
inline bool ShadowDOMSiblingTraversalStrategy::isLastChild(Element* element) const
{
- UNUSED_PARAM(element);
-
ASSERT(element == toElement(m_siblings[m_nth]));
for (size_t i = m_nth + 1; i < m_siblings.size(); ++i) {
@@ -173,8 +162,6 @@ inline bool ShadowDOMSiblingTraversalStrategy::isLastChild(Element* element) con
inline bool ShadowDOMSiblingTraversalStrategy::isFirstOfType(Element* element, const QualifiedName& type) const
{
- UNUSED_PARAM(element);
-
ASSERT(element == toElement(m_siblings[m_nth]));
for (int i = m_nth - 1; i >= 0; --i) {
@@ -187,8 +174,6 @@ inline bool ShadowDOMSiblingTraversalStrategy::isFirstOfType(Element* element, c
inline bool ShadowDOMSiblingTraversalStrategy::isLastOfType(Element* element, const QualifiedName& type) const
{
- UNUSED_PARAM(element);
-
ASSERT(element == toElement(m_siblings[m_nth]));
for (size_t i = m_nth + 1; i < m_siblings.size(); ++i) {
@@ -201,8 +186,6 @@ inline bool ShadowDOMSiblingTraversalStrategy::isLastOfType(Element* element, co
inline int ShadowDOMSiblingTraversalStrategy::countElementsBefore(Element* element) const
{
- UNUSED_PARAM(element);
-
ASSERT(element == toElement(m_siblings[m_nth]));
int count = 0;
@@ -216,8 +199,6 @@ inline int ShadowDOMSiblingTraversalStrategy::countElementsBefore(Element* eleme
inline int ShadowDOMSiblingTraversalStrategy::countElementsAfter(Element* element) const
{
- UNUSED_PARAM(element);
-
ASSERT(element == toElement(m_siblings[m_nth]));
int count = 0;
@@ -231,8 +212,6 @@ inline int ShadowDOMSiblingTraversalStrategy::countElementsAfter(Element* elemen
inline int ShadowDOMSiblingTraversalStrategy::countElementsOfTypeBefore(Element* element, const QualifiedName& type) const
{
- UNUSED_PARAM(element);
-
ASSERT(element == toElement(m_siblings[m_nth]));
int count = 0;
@@ -246,8 +225,6 @@ inline int ShadowDOMSiblingTraversalStrategy::countElementsOfTypeBefore(Element*
inline int ShadowDOMSiblingTraversalStrategy::countElementsOfTypeAfter(Element* element, const QualifiedName& type) const
{
- UNUSED_PARAM(element);
-
ASSERT(element == toElement(m_siblings[m_nth]));
int count = 0;
diff --git a/chromium/third_party/WebKit/Source/core/css/StyleColor.h b/chromium/third_party/WebKit/Source/core/css/StyleColor.h
index eb893e4601a..1f58584f9a9 100644
--- a/chromium/third_party/WebKit/Source/core/css/StyleColor.h
+++ b/chromium/third_party/WebKit/Source/core/css/StyleColor.h
@@ -31,7 +31,7 @@
#ifndef StyleColor_h
#define StyleColor_h
-#include "core/platform/graphics/Color.h"
+#include "platform/graphics/Color.h"
#include "wtf/FastAllocBase.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/css/StyleInvalidationAnalysis.cpp b/chromium/third_party/WebKit/Source/core/css/StyleInvalidationAnalysis.cpp
index 6fa9e012a57..440e17fe346 100644
--- a/chromium/third_party/WebKit/Source/core/css/StyleInvalidationAnalysis.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/StyleInvalidationAnalysis.cpp
@@ -88,17 +88,6 @@ static bool hasDistributedRule(StyleSheetContents* styleSheetContents)
return false;
}
-static bool hasAtHostRule(StyleSheetContents* styleSheetContents)
-{
- const Vector<RefPtr<StyleRuleBase> >& rules = styleSheetContents->childRules();
- for (unsigned i = 0; i < rules.size(); i++) {
- const StyleRuleBase* rule = rules[i].get();
- if (rule->isHostRule())
- return true;
- }
- return false;
-}
-
static Node* determineScopingNodeForStyleScoped(HTMLStyleElement* ownerElement, StyleSheetContents* styleSheetContents)
{
ASSERT(ownerElement && ownerElement->isRegisteredAsScoped());
@@ -112,13 +101,43 @@ static Node* determineScopingNodeForStyleScoped(HTMLStyleElement* ownerElement,
return scope;
}
- if (ownerElement->isRegisteredAsScoped() && hasAtHostRule(styleSheetContents))
+ if (ownerElement->isRegisteredAsScoped())
return ownerElement->containingShadowRoot()->shadowHost();
}
return ownerElement->isRegisteredInShadowRoot() ? ownerElement->containingShadowRoot()->shadowHost() : ownerElement->parentNode();
}
+static bool ruleAdditionMightRequireDocumentStyleRecalc(StyleRuleBase* rule)
+{
+ // This funciton is conservative. We only return false when we know that
+ // the added @rule can't require style recalcs.
+ switch (rule->type()) {
+ case StyleRule::Import: // Whatever we import should do its own analysis, we don't need to invalidate the document here!
+ case StyleRule::Keyframes: // Keyframes never cause style invalidations and are handled during sheet insertion.
+ case StyleRule::Page: // Page rules apply only during printing, we force a full-recalc before printing.
+ return false;
+
+ case StyleRule::Media: // If the media rule doesn't apply, we could avoid recalc.
+ case StyleRule::FontFace: // If the fonts aren't in use, we could avoid recalc.
+ case StyleRule::Supports: // If we evaluated the supports-clause we could avoid recalc.
+ case StyleRule::Viewport: // If the viewport doesn't match, we could avoid recalcing.
+ // FIXME: Unclear if any of the rest need to cause style recalc:
+ case StyleRule::Region:
+ case StyleRule::Filter:
+ return true;
+
+ // These should all be impossible to reach:
+ case StyleRule::Unknown:
+ case StyleRule::Charset:
+ case StyleRule::Keyframe:
+ case StyleRule::Style:
+ break;
+ }
+ ASSERT_NOT_REACHED();
+ return true;
+}
+
void StyleInvalidationAnalysis::analyzeStyleSheet(StyleSheetContents* styleSheetContents)
{
ASSERT(!styleSheetContents->isLoading());
@@ -145,9 +164,11 @@ void StyleInvalidationAnalysis::analyzeStyleSheet(StyleSheetContents* styleSheet
for (unsigned i = 0; i < rules.size(); i++) {
StyleRuleBase* rule = rules[i].get();
if (!rule->isStyleRule()) {
- // FIXME: Media rules and maybe some others could be allowed.
- m_dirtiesAllStyle = true;
- return;
+ if (ruleAdditionMightRequireDocumentStyleRecalc(rule)) {
+ m_dirtiesAllStyle = true;
+ return;
+ }
+ continue;
}
StyleRule* styleRule = toStyleRule(rule);
if (!determineSelectorScopes(styleRule->selectorList(), m_idScopes, m_classScopes)) {
@@ -171,7 +192,7 @@ static bool elementMatchesSelectorScopes(const Element* element, const HashSet<S
return false;
}
-void StyleInvalidationAnalysis::invalidateStyle(Document* document)
+void StyleInvalidationAnalysis::invalidateStyle(Document& document)
{
ASSERT(!m_dirtiesAllStyle);
@@ -187,10 +208,10 @@ void StyleInvalidationAnalysis::invalidateStyle(Document* document)
if (elementMatchesSelectorScopes(element, m_idScopes, m_classScopes)) {
element->setNeedsStyleRecalc();
// The whole subtree is now invalidated, we can skip to the next sibling.
- element = ElementTraversal::nextSkippingChildren(element);
+ element = ElementTraversal::nextSkippingChildren(*element);
continue;
}
- element = ElementTraversal::next(element);
+ element = ElementTraversal::next(*element);
}
}
diff --git a/chromium/third_party/WebKit/Source/core/css/StyleInvalidationAnalysis.h b/chromium/third_party/WebKit/Source/core/css/StyleInvalidationAnalysis.h
index e58f37a672b..79cf3d87bda 100644
--- a/chromium/third_party/WebKit/Source/core/css/StyleInvalidationAnalysis.h
+++ b/chromium/third_party/WebKit/Source/core/css/StyleInvalidationAnalysis.h
@@ -41,7 +41,7 @@ public:
StyleInvalidationAnalysis(const Vector<StyleSheetContents*>&);
bool dirtiesAllStyle() const { return m_dirtiesAllStyle; }
- void invalidateStyle(Document*);
+ void invalidateStyle(Document&);
private:
diff --git a/chromium/third_party/WebKit/Source/core/css/StyleMedia.cpp b/chromium/third_party/WebKit/Source/core/css/StyleMedia.cpp
index 6f003f7574b..791ef27328f 100644
--- a/chromium/third_party/WebKit/Source/core/css/StyleMedia.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/StyleMedia.cpp
@@ -30,8 +30,8 @@
#include "core/css/MediaQueryEvaluator.h"
#include "core/css/resolver/StyleResolver.h"
#include "core/dom/Document.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameView.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
namespace WebCore {
@@ -40,13 +40,13 @@ StyleMedia::StyleMedia(Frame* frame)
{
}
-String StyleMedia::type() const
+AtomicString StyleMedia::type() const
{
FrameView* view = m_frame ? m_frame->view() : 0;
if (view)
return view->mediaType();
- return String();
+ return nullAtom;
}
bool StyleMedia::matchMedium(const String& query) const
@@ -60,11 +60,8 @@ bool StyleMedia::matchMedium(const String& query) const
if (!documentElement)
return false;
- StyleResolver* styleResolver = document->styleResolver();
- if (!styleResolver)
- return false;
-
- RefPtr<RenderStyle> rootStyle = styleResolver->styleForElement(documentElement, 0 /*defaultParent*/, DisallowStyleSharing, MatchOnlyUserAgentRules);
+ StyleResolver& styleResolver = document->ensureStyleResolver();
+ RefPtr<RenderStyle> rootStyle = styleResolver.styleForElement(documentElement, 0 /*defaultParent*/, DisallowStyleSharing, MatchOnlyUserAgentRules);
RefPtr<MediaQuerySet> media = MediaQuerySet::create();
if (!media->set(query))
diff --git a/chromium/third_party/WebKit/Source/core/css/StyleMedia.h b/chromium/third_party/WebKit/Source/core/css/StyleMedia.h
index fdf620d8eca..e2cd69be117 100644
--- a/chromium/third_party/WebKit/Source/core/css/StyleMedia.h
+++ b/chromium/third_party/WebKit/Source/core/css/StyleMedia.h
@@ -27,7 +27,7 @@
#ifndef StyleMedia_h
#define StyleMedia_h
-#include "core/page/DOMWindowProperty.h"
+#include "core/frame/DOMWindowProperty.h"
#include "wtf/RefCounted.h"
#include "wtf/text/WTFString.h"
@@ -39,7 +39,7 @@ class StyleMedia : public RefCounted<StyleMedia>, public DOMWindowProperty {
public:
static PassRefPtr<StyleMedia> create(Frame* frame) { return adoptRef(new StyleMedia(frame));}
- String type() const;
+ AtomicString type() const;
bool matchMedium(const String&) const;
private:
diff --git a/chromium/third_party/WebKit/Source/core/css/StylePropertySerializer.cpp b/chromium/third_party/WebKit/Source/core/css/StylePropertySerializer.cpp
index dbe5d9f9d9e..825781430ab 100644
--- a/chromium/third_party/WebKit/Source/core/css/StylePropertySerializer.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/StylePropertySerializer.cpp
@@ -25,7 +25,7 @@
#include "CSSValueKeywords.h"
#include "StylePropertyShorthand.h"
-#include "core/page/RuntimeCSSEnabled.h"
+#include "core/css/RuntimeCSSEnabled.h"
#include "wtf/BitArray.h"
#include "wtf/text/StringBuilder.h"
@@ -88,7 +88,7 @@ String StylePropertySerializer::asText() const
continue;
case CSSPropertyContent:
if (property.value()->isValueList())
- value = toCSSValueList(property.value())->customCssText(AlwaysQuoteCSSString);
+ value = toCSSValueList(property.value())->customCSSText(AlwaysQuoteCSSString);
break;
case CSSPropertyBorderTopWidth:
case CSSPropertyBorderRightWidth:
diff --git a/chromium/third_party/WebKit/Source/core/css/StylePropertySet.cpp b/chromium/third_party/WebKit/Source/core/css/StylePropertySet.cpp
index 79107e29516..c7e0ae63811 100644
--- a/chromium/third_party/WebKit/Source/core/css/StylePropertySet.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/StylePropertySet.cpp
@@ -28,10 +28,9 @@
#include "core/css/CSSParser.h"
#include "core/css/CSSValuePool.h"
#include "core/css/CSSVariableValue.h"
-#include "core/css/PropertySetCSSStyleDeclaration.h"
+#include "core/css/RuntimeCSSEnabled.h"
#include "core/css/StylePropertySerializer.h"
#include "core/css/StyleSheetContents.h"
-#include "core/page/RuntimeCSSEnabled.h"
#include "wtf/text/StringBuilder.h"
#ifndef NDEBUG
@@ -58,8 +57,8 @@ PassRefPtr<ImmutableStylePropertySet> ImmutableStylePropertySet::create(const CS
PassRefPtr<ImmutableStylePropertySet> StylePropertySet::immutableCopyIfNeeded() const
{
if (!isMutable())
- return static_cast<ImmutableStylePropertySet*>(const_cast<StylePropertySet*>(this));
- const MutableStylePropertySet* mutableThis = static_cast<const MutableStylePropertySet*>(this);
+ return toImmutableStylePropertySet(const_cast<StylePropertySet*>(this));
+ const MutableStylePropertySet* mutableThis = toMutableStylePropertySet(this);
return ImmutableStylePropertySet::create(mutableThis->m_propertyVector.data(), mutableThis->m_propertyVector.size(), cssParserMode());
}
@@ -69,7 +68,7 @@ MutableStylePropertySet::MutableStylePropertySet(CSSParserMode cssParserMode)
}
MutableStylePropertySet::MutableStylePropertySet(const CSSProperty* properties, unsigned length)
- : StylePropertySet(CSSStrictMode)
+ : StylePropertySet(HTMLStandardMode)
{
m_propertyVector.reserveInitialCapacity(length);
for (unsigned i = 0; i < length; ++i)
@@ -98,9 +97,9 @@ ImmutableStylePropertySet::~ImmutableStylePropertySet()
MutableStylePropertySet::MutableStylePropertySet(const StylePropertySet& other)
: StylePropertySet(other.cssParserMode())
{
- if (other.isMutable())
- m_propertyVector = static_cast<const MutableStylePropertySet&>(other).m_propertyVector;
- else {
+ if (other.isMutable()) {
+ m_propertyVector = toMutableStylePropertySet(other).m_propertyVector;
+ } else {
m_propertyVector.reserveInitialCapacity(other.propertyCount());
for (unsigned i = 0; i < other.propertyCount(); ++i)
m_propertyVector.uncheckedAppend(other.propertyAt(i).toCSSProperty());
@@ -275,7 +274,9 @@ unsigned getIndexInShorthandVectorForPrefixingVariant(const CSSProperty& propert
return 0;
CSSPropertyID prefixedShorthand = prefixingVariantForPropertyId(property.shorthandID());
- return indexOfShorthandForLonghand(prefixedShorthand, matchingShorthandsForLonghand(prefixingVariant));
+ Vector<StylePropertyShorthand, 4> shorthands;
+ getMatchingShorthandsForLonghand(prefixingVariant, &shorthands);
+ return indexOfShorthandForLonghand(prefixedShorthand, shorthands);
}
bool MutableStylePropertySet::setVariableValue(const AtomicString& name, const String& value, bool important)
@@ -286,17 +287,18 @@ bool MutableStylePropertySet::setVariableValue(const AtomicString& name, const S
size_t index = findVariableIndex(name);
if (index != kNotFound) {
- CSSValue* cssValue = m_propertyVector.at(index).value();
+ const CSSValue* cssValue = m_propertyVector.at(index).value();
if (toCSSVariableValue(cssValue)->value() == value)
return false;
}
CSSProperty property(CSSPropertyVariable, CSSVariableValue::create(name, value), important);
- if (index == kNotFound)
+ if (index == kNotFound) {
m_propertyVector.append(property);
- else
- m_propertyVector.at(index) = property;
- return true;
+ return true;
+ }
+ m_propertyVector.at(index) = property;
+ return false;
}
void MutableStylePropertySet::appendPrefixingVariantProperty(const CSSProperty& property)
@@ -336,7 +338,7 @@ void MutableStylePropertySet::parseDeclaration(const String& styleDeclaration, S
CSSParserContext context(cssParserMode());
if (contextStyleSheet) {
context = contextStyleSheet->parserContext();
- context.mode = cssParserMode();
+ context.setMode(cssParserMode());
}
CSSParser parser(context, UseCounter::getFrom(contextStyleSheet));
@@ -364,7 +366,7 @@ String StylePropertySet::asText() const
bool StylePropertySet::hasCSSOMWrapper() const
{
- return m_isMutable && static_cast<const MutableStylePropertySet*>(this)->m_cssomWrapper;
+ return m_isMutable && toMutableStylePropertySet(this)->m_cssomWrapper;
}
void MutableStylePropertySet::mergeAndOverrideOnConflict(const StylePropertySet* other)
@@ -421,6 +423,7 @@ static const CSSPropertyID staticBlockProperties[] = {
CSSPropertyTextAlign,
CSSPropertyTextAlignLast,
CSSPropertyTextIndent,
+ CSSPropertyTextJustify,
CSSPropertyWidows
};
@@ -563,6 +566,58 @@ bool MutableStylePropertySet::clearVariables()
return removePropertiesInSet(&variablesId, 1);
}
+PassRefPtr<MutableStylePropertySet::VariablesIterator> MutableStylePropertySet::VariablesIterator::create(MutableStylePropertySet* propertySet)
+{
+ ASSERT(RuntimeEnabledFeatures::cssVariablesEnabled());
+ const size_t propertyCount = propertySet->propertyCount();
+ size_t variableCount = 0;
+ Vector<AtomicString> remainingNames(propertyCount);
+ for (int i = propertyCount; i--; ) {
+ const PropertyReference& property = propertySet->propertyAt(i);
+ if (property.id() == CSSPropertyVariable)
+ remainingNames[variableCount++] = toCSSVariableValue(property.value())->name();
+ }
+ remainingNames.shrink(variableCount);
+
+ RefPtr<VariablesIterator> iterator = adoptRef(new VariablesIterator(propertySet));
+ // FIXME: Make use of the Vector move constructor when rvalues are supported on all platforms.
+ iterator->takeRemainingNames(remainingNames);
+ return iterator.release();
+}
+
+void MutableStylePropertySet::VariablesIterator::addedVariable(const AtomicString& name)
+{
+ ASSERT(!m_remainingNames.contains(name));
+ ASSERT(!m_newNames.contains(name));
+ m_newNames.append(name);
+}
+
+void MutableStylePropertySet::VariablesIterator::removedVariable(const AtomicString& name)
+{
+ size_t index = m_remainingNames.find(name);
+ if (index != kNotFound)
+ m_remainingNames.remove(index);
+ index = m_newNames.find(name);
+ if (index != kNotFound)
+ m_newNames.remove(index);
+}
+
+void MutableStylePropertySet::VariablesIterator::clearedVariables()
+{
+ m_remainingNames.clear();
+ m_newNames.clear();
+}
+
+void MutableStylePropertySet::VariablesIterator::advance()
+{
+ if (!atEnd())
+ m_remainingNames.removeLast();
+ if (!m_newNames.isEmpty()) {
+ m_remainingNames.appendVector(m_newNames);
+ m_newNames.clear();
+ }
+}
+
PassRefPtr<MutableStylePropertySet> StylePropertySet::mutableCopy() const
{
return adoptRef(new MutableStylePropertySet(*this));
diff --git a/chromium/third_party/WebKit/Source/core/css/StylePropertySet.h b/chromium/third_party/WebKit/Source/core/css/StylePropertySet.h
index 8e9c913568e..1003f3b93e5 100644
--- a/chromium/third_party/WebKit/Source/core/css/StylePropertySet.h
+++ b/chromium/third_party/WebKit/Source/core/css/StylePropertySet.h
@@ -25,6 +25,7 @@
#include "core/css/CSSParserMode.h"
#include "core/css/CSSPrimitiveValue.h"
#include "core/css/CSSProperty.h"
+#include "core/css/CSSVariablesIterator.h"
#include "core/css/PropertySetCSSStyleDeclaration.h"
#include "wtf/ListHashSet.h"
#include "wtf/Vector.h"
@@ -172,9 +173,17 @@ inline const StylePropertyMetadata* ImmutableStylePropertySet::metadataArray() c
return reinterpret_cast<const StylePropertyMetadata*>(&reinterpret_cast<const char*>(&(this->m_storage))[m_arraySize * sizeof(CSSValue*)]);
}
+DEFINE_TYPE_CASTS(ImmutableStylePropertySet, StylePropertySet, set, !set->isMutable(), !set.isMutable());
+
+inline ImmutableStylePropertySet* toImmutableStylePropertySet(const RefPtr<StylePropertySet>& set)
+{
+ return toImmutableStylePropertySet(set.get());
+}
+
class MutableStylePropertySet : public StylePropertySet {
public:
- static PassRefPtr<MutableStylePropertySet> create(CSSParserMode = CSSQuirksMode);
+ ~MutableStylePropertySet() { }
+ static PassRefPtr<MutableStylePropertySet> create(CSSParserMode = HTMLQuirksMode);
static PassRefPtr<MutableStylePropertySet> create(const CSSProperty* properties, unsigned count);
unsigned propertyCount() const { return m_propertyVector.size(); }
@@ -204,6 +213,8 @@ public:
bool removeVariable(const AtomicString& name);
bool clearVariables();
+ PassRefPtr<CSSVariablesIterator> variablesIterator() { return VariablesIterator::create(this); }
+
void mergeAndOverrideOnConflict(const StylePropertySet*);
void clear();
@@ -215,6 +226,26 @@ public:
Vector<CSSProperty, 4> m_propertyVector;
private:
+ class VariablesIterator : public CSSVariablesIterator {
+ public:
+ virtual ~VariablesIterator() { }
+ static PassRefPtr<VariablesIterator> create(MutableStylePropertySet*);
+ private:
+ explicit VariablesIterator(MutableStylePropertySet* propertySet) : m_propertySet(propertySet) { }
+ void takeRemainingNames(Vector<AtomicString>& remainingNames) { m_remainingNames.swap(remainingNames); }
+ virtual void advance() OVERRIDE;
+ virtual bool atEnd() const OVERRIDE { return m_remainingNames.isEmpty(); }
+ virtual AtomicString name() const OVERRIDE { return m_remainingNames.last(); }
+ virtual String value() const OVERRIDE { return m_propertySet->variableValue(name()); }
+ virtual void addedVariable(const AtomicString& name) OVERRIDE;
+ virtual void removedVariable(const AtomicString& name) OVERRIDE;
+ virtual void clearedVariables() OVERRIDE;
+
+ RefPtr<MutableStylePropertySet> m_propertySet;
+ Vector<AtomicString> m_remainingNames;
+ Vector<AtomicString> m_newNames;
+ };
+
explicit MutableStylePropertySet(CSSParserMode);
explicit MutableStylePropertySet(const StylePropertySet&);
MutableStylePropertySet(const CSSProperty* properties, unsigned count);
@@ -226,24 +257,31 @@ private:
friend class StylePropertySet;
};
+DEFINE_TYPE_CASTS(MutableStylePropertySet, StylePropertySet, set, set->isMutable(), set.isMutable());
+
+inline MutableStylePropertySet* toMutableStylePropertySet(const RefPtr<StylePropertySet>& set)
+{
+ return toMutableStylePropertySet(set.get());
+}
+
inline const StylePropertyMetadata& StylePropertySet::PropertyReference::propertyMetadata() const
{
if (m_propertySet.isMutable())
- return static_cast<const MutableStylePropertySet&>(m_propertySet).m_propertyVector.at(m_index).metadata();
- return static_cast<const ImmutableStylePropertySet&>(m_propertySet).metadataArray()[m_index];
+ return toMutableStylePropertySet(m_propertySet).m_propertyVector.at(m_index).metadata();
+ return toImmutableStylePropertySet(m_propertySet).metadataArray()[m_index];
}
inline const CSSValue* StylePropertySet::PropertyReference::propertyValue() const
{
if (m_propertySet.isMutable())
- return static_cast<const MutableStylePropertySet&>(m_propertySet).m_propertyVector.at(m_index).value();
- return static_cast<const ImmutableStylePropertySet&>(m_propertySet).valueArray()[m_index];
+ return toMutableStylePropertySet(m_propertySet).m_propertyVector.at(m_index).value();
+ return toImmutableStylePropertySet(m_propertySet).valueArray()[m_index];
}
inline unsigned StylePropertySet::propertyCount() const
{
if (m_isMutable)
- return static_cast<const MutableStylePropertySet*>(this)->m_propertyVector.size();
+ return toMutableStylePropertySet(this)->m_propertyVector.size();
return m_arraySize;
}
@@ -258,9 +296,9 @@ inline void StylePropertySet::deref()
return;
if (m_isMutable)
- delete static_cast<MutableStylePropertySet*>(this);
+ delete toMutableStylePropertySet(this);
else
- delete static_cast<ImmutableStylePropertySet*>(this);
+ delete toImmutableStylePropertySet(this);
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/css/StylePropertyShorthandCustom.cpp b/chromium/third_party/WebKit/Source/core/css/StylePropertyShorthandCustom.cpp
index c3d44ac9fa0..b157746c8b9 100644
--- a/chromium/third_party/WebKit/Source/core/css/StylePropertyShorthandCustom.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/StylePropertyShorthandCustom.cpp
@@ -113,7 +113,7 @@ bool isExpandedShorthand(CSSPropertyID id)
return shorthandForProperty(id).length();
}
-unsigned indexOfShorthandForLonghand(CSSPropertyID shorthandID, const Vector<StylePropertyShorthand>& shorthands)
+unsigned indexOfShorthandForLonghand(CSSPropertyID shorthandID, const Vector<StylePropertyShorthand, 4>& shorthands)
{
for (unsigned i = 0; i < shorthands.size(); ++i) {
if (shorthands.at(i).id() == shorthandID)
diff --git a/chromium/third_party/WebKit/Source/core/css/StyleRule.cpp b/chromium/third_party/WebKit/Source/core/css/StyleRule.cpp
index 3008e849c37..299f7a2300d 100644
--- a/chromium/third_party/WebKit/Source/core/css/StyleRule.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/StyleRule.cpp
@@ -25,7 +25,6 @@
#include "RuntimeEnabledFeatures.h"
#include "core/css/CSSFilterRule.h"
#include "core/css/CSSFontFaceRule.h"
-#include "core/css/CSSHostRule.h"
#include "core/css/CSSImportRule.h"
#include "core/css/CSSKeyframesRule.h"
#include "core/css/CSSMediaRule.h"
@@ -43,7 +42,7 @@ struct SameSizeAsStyleRuleBase : public WTF::RefCountedBase {
unsigned bitfields;
};
-COMPILE_ASSERT(sizeof(StyleRuleBase) == sizeof(SameSizeAsStyleRuleBase), StyleRuleBase_should_stay_small);
+COMPILE_ASSERT(sizeof(StyleRuleBase) <= sizeof(SameSizeAsStyleRuleBase), StyleRuleBase_should_stay_small);
PassRefPtr<CSSRule> StyleRuleBase::createCSSOMWrapper(CSSStyleSheet* parentSheet) const
{
@@ -62,34 +61,31 @@ void StyleRuleBase::destroy()
delete toStyleRule(this);
return;
case Page:
- delete static_cast<StyleRulePage*>(this);
+ delete toStyleRulePage(this);
return;
case FontFace:
- delete static_cast<StyleRuleFontFace*>(this);
+ delete toStyleRuleFontFace(this);
return;
case Media:
- delete static_cast<StyleRuleMedia*>(this);
+ delete toStyleRuleMedia(this);
return;
case Supports:
- delete static_cast<StyleRuleSupports*>(this);
+ delete toStyleRuleSupports(this);
return;
case Region:
- delete static_cast<StyleRuleRegion*>(this);
+ delete toStyleRuleRegion(this);
return;
case Import:
- delete static_cast<StyleRuleImport*>(this);
+ delete toStyleRuleImport(this);
return;
case Keyframes:
- delete static_cast<StyleRuleKeyframes*>(this);
- return;
- case HostInternal:
- delete static_cast<StyleRuleHost*>(this);
+ delete toStyleRuleKeyframes(this);
return;
case Viewport:
- delete static_cast<StyleRuleViewport*>(this);
+ delete toStyleRuleViewport(this);
return;
case Filter:
- delete static_cast<StyleRuleFilter*>(this);
+ delete toStyleRuleFilter(this);
return;
case Unknown:
case Charset:
@@ -104,29 +100,27 @@ PassRefPtr<StyleRuleBase> StyleRuleBase::copy() const
{
switch (type()) {
case Style:
- return static_cast<const StyleRule*>(this)->copy();
+ return toStyleRule(this)->copy();
case Page:
- return static_cast<const StyleRulePage*>(this)->copy();
+ return toStyleRulePage(this)->copy();
case FontFace:
- return static_cast<const StyleRuleFontFace*>(this)->copy();
+ return toStyleRuleFontFace(this)->copy();
case Media:
- return static_cast<const StyleRuleMedia*>(this)->copy();
+ return toStyleRuleMedia(this)->copy();
case Supports:
- return static_cast<const StyleRuleSupports*>(this)->copy();
+ return toStyleRuleSupports(this)->copy();
case Region:
- return static_cast<const StyleRuleRegion*>(this)->copy();
+ return toStyleRuleRegion(this)->copy();
case Import:
// FIXME: Copy import rules.
ASSERT_NOT_REACHED();
return 0;
case Keyframes:
- return static_cast<const StyleRuleKeyframes*>(this)->copy();
- case HostInternal:
- return static_cast<const StyleRuleHost*>(this)->copy();
+ return toStyleRuleKeyframes(this)->copy();
case Viewport:
- return static_cast<const StyleRuleViewport*>(this)->copy();
+ return toStyleRuleViewport(this)->copy();
case Filter:
- return static_cast<const StyleRuleFilter*>(this)->copy();
+ return toStyleRuleFilter(this)->copy();
case Unknown:
case Charset:
case Keyframe:
@@ -146,34 +140,31 @@ PassRefPtr<CSSRule> StyleRuleBase::createCSSOMWrapper(CSSStyleSheet* parentSheet
rule = CSSStyleRule::create(toStyleRule(self), parentSheet);
break;
case Page:
- rule = CSSPageRule::create(static_cast<StyleRulePage*>(self), parentSheet);
+ rule = CSSPageRule::create(toStyleRulePage(self), parentSheet);
break;
case FontFace:
- rule = CSSFontFaceRule::create(static_cast<StyleRuleFontFace*>(self), parentSheet);
+ rule = CSSFontFaceRule::create(toStyleRuleFontFace(self), parentSheet);
break;
case Media:
- rule = CSSMediaRule::create(static_cast<StyleRuleMedia*>(self), parentSheet);
+ rule = CSSMediaRule::create(toStyleRuleMedia(self), parentSheet);
break;
case Supports:
- rule = CSSSupportsRule::create(static_cast<StyleRuleSupports*>(self), parentSheet);
+ rule = CSSSupportsRule::create(toStyleRuleSupports(self), parentSheet);
break;
case Region:
- rule = CSSRegionRule::create(static_cast<StyleRuleRegion*>(self), parentSheet);
+ rule = CSSRegionRule::create(toStyleRuleRegion(self), parentSheet);
break;
case Import:
- rule = CSSImportRule::create(static_cast<StyleRuleImport*>(self), parentSheet);
+ rule = CSSImportRule::create(toStyleRuleImport(self), parentSheet);
break;
case Keyframes:
- rule = CSSKeyframesRule::create(static_cast<StyleRuleKeyframes*>(self), parentSheet);
+ rule = CSSKeyframesRule::create(toStyleRuleKeyframes(self), parentSheet);
break;
case Viewport:
- rule = CSSViewportRule::create(static_cast<StyleRuleViewport*>(self), parentSheet);
- break;
- case HostInternal:
- rule = CSSHostRule::create(static_cast<StyleRuleHost*>(self), parentSheet);
+ rule = CSSViewportRule::create(toStyleRuleViewport(self), parentSheet);
break;
case Filter:
- rule = CSSFilterRule::create(static_cast<StyleRuleFilter*>(self), parentSheet);
+ rule = CSSFilterRule::create(toStyleRuleFilter(self), parentSheet);
break;
case Unknown:
case Charset:
@@ -211,7 +202,7 @@ MutableStylePropertySet* StyleRule::mutableProperties()
{
if (!m_properties->isMutable())
m_properties = m_properties->mutableCopy();
- return static_cast<MutableStylePropertySet*>(m_properties.get());
+ return toMutableStylePropertySet(m_properties);
}
void StyleRule::setProperties(PassRefPtr<StylePropertySet> properties)
@@ -239,7 +230,7 @@ MutableStylePropertySet* StyleRulePage::mutableProperties()
{
if (!m_properties->isMutable())
m_properties = m_properties->mutableCopy();
- return static_cast<MutableStylePropertySet*>(m_properties.get());
+ return toMutableStylePropertySet(m_properties);
}
void StyleRulePage::setProperties(PassRefPtr<StylePropertySet> properties)
@@ -266,7 +257,7 @@ MutableStylePropertySet* StyleRuleFontFace::mutableProperties()
{
if (!m_properties->isMutable())
m_properties = m_properties->mutableCopy();
- return static_cast<MutableStylePropertySet*>(m_properties.get());
+ return toMutableStylePropertySet(m_properties);
}
void StyleRuleFontFace::setProperties(PassRefPtr<StylePropertySet> properties)
@@ -358,7 +349,7 @@ MutableStylePropertySet* StyleRuleViewport::mutableProperties()
{
if (!m_properties->isMutable())
m_properties = m_properties->mutableCopy();
- return static_cast<MutableStylePropertySet*>(m_properties.get());
+ return toMutableStylePropertySet(m_properties);
}
void StyleRuleViewport::setProperties(PassRefPtr<StylePropertySet> properties)
@@ -387,7 +378,7 @@ MutableStylePropertySet* StyleRuleFilter::mutableProperties()
{
if (!m_properties->isMutable())
m_properties = m_properties->mutableCopy();
- return static_cast<MutableStylePropertySet*>(m_properties.get());
+ return toMutableStylePropertySet(m_properties);
}
void StyleRuleFilter::setProperties(PassRefPtr<StylePropertySet> properties)
diff --git a/chromium/third_party/WebKit/Source/core/css/StyleRule.h b/chromium/third_party/WebKit/Source/core/css/StyleRule.h
index aa319ed7344..e1216ebeedd 100644
--- a/chromium/third_party/WebKit/Source/core/css/StyleRule.h
+++ b/chromium/third_party/WebKit/Source/core/css/StyleRule.h
@@ -50,8 +50,7 @@ public:
Supports = 12,
Viewport = 15,
Region = 16,
- Filter = 17,
- HostInternal = 18, // Spec says Host = 1001, but we can use only 5 bit for type().
+ Filter = 17
};
Type type() const { return static_cast<Type>(m_type); }
@@ -66,7 +65,6 @@ public:
bool isSupportsRule() const { return type() == Supports; }
bool isViewportRule() const { return type() == Viewport; }
bool isImportRule() const { return type() == Import; }
- bool isHostRule() const { return type() == HostInternal; }
bool isFilterRule() const { return type() == Filter; }
PassRefPtr<StyleRuleBase> copy() const;
@@ -122,20 +120,6 @@ private:
CSSSelectorList m_selectorList;
};
-inline const StyleRule* toStyleRule(const StyleRuleBase* rule)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!rule || rule->isStyleRule());
- return static_cast<const StyleRule*>(rule);
-}
-
-inline StyleRule* toStyleRule(StyleRuleBase* rule)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!rule || rule->isStyleRule());
- return static_cast<StyleRule*>(rule);
-}
-
-void toStyleRule(const StyleRule*);
-
class StyleRuleFontFace : public StyleRuleBase {
public:
static PassRefPtr<StyleRuleFontFace> create() { return adoptRef(new StyleRuleFontFace); }
@@ -250,20 +234,6 @@ private:
CSSSelectorList m_selectorList;
};
-class StyleRuleHost : public StyleRuleGroup {
-public:
- static PassRefPtr<StyleRuleHost> create(Vector<RefPtr<StyleRuleBase> >& adoptRules)
- {
- return adoptRef(new StyleRuleHost(adoptRules));
- }
-
- PassRefPtr<StyleRuleHost> copy() const { return adoptRef(new StyleRuleHost(*this)); }
-
-private:
- StyleRuleHost(Vector<RefPtr<StyleRuleBase> >& adoptRules) : StyleRuleGroup(HostInternal, adoptRules) { }
- StyleRuleHost(const StyleRuleHost& o) : StyleRuleGroup(o) { }
-};
-
class StyleRuleViewport : public StyleRuleBase {
public:
static PassRefPtr<StyleRuleViewport> create() { return adoptRef(new StyleRuleViewport); }
@@ -284,24 +254,6 @@ private:
RefPtr<StylePropertySet> m_properties;
};
-inline const StyleRuleMedia* toStyleRuleMedia(const StyleRuleGroup* rule)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!rule || rule->isMediaRule());
- return static_cast<const StyleRuleMedia*>(rule);
-}
-
-inline const StyleRuleSupports* toStyleRuleSupports(const StyleRuleGroup* rule)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!rule || rule->isSupportsRule());
- return static_cast<const StyleRuleSupports*>(rule);
-}
-
-inline const StyleRuleRegion* toStyleRuleRegion(const StyleRuleGroup* rule)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!rule || rule->isRegionRule());
- return static_cast<const StyleRuleRegion*>(rule);
-}
-
class StyleRuleFilter : public StyleRuleBase {
public:
static PassRefPtr<StyleRuleFilter> create(const String& filterName) { return adoptRef(new StyleRuleFilter(filterName)); }
@@ -325,6 +277,18 @@ private:
RefPtr<StylePropertySet> m_properties;
};
+#define DEFINE_STYLE_RULE_TYPE_CASTS(Type) \
+ DEFINE_TYPE_CASTS(StyleRule##Type, StyleRuleBase, rule, rule->is##Type##Rule(), rule.is##Type##Rule())
+
+DEFINE_TYPE_CASTS(StyleRule, StyleRuleBase, rule, rule->isStyleRule(), rule.isStyleRule());
+DEFINE_STYLE_RULE_TYPE_CASTS(FontFace);
+DEFINE_STYLE_RULE_TYPE_CASTS(Page);
+DEFINE_STYLE_RULE_TYPE_CASTS(Media);
+DEFINE_STYLE_RULE_TYPE_CASTS(Supports);
+DEFINE_STYLE_RULE_TYPE_CASTS(Region);
+DEFINE_STYLE_RULE_TYPE_CASTS(Viewport);
+DEFINE_STYLE_RULE_TYPE_CASTS(Filter);
+
} // namespace WebCore
#endif // StyleRule_h
diff --git a/chromium/third_party/WebKit/Source/core/css/StyleRuleImport.cpp b/chromium/third_party/WebKit/Source/core/css/StyleRuleImport.cpp
index 331cdf7fc2b..aff60cb9ecd 100644
--- a/chromium/third_party/WebKit/Source/core/css/StyleRuleImport.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/StyleRuleImport.cpp
@@ -62,10 +62,10 @@ void StyleRuleImport::setCSSStyleSheet(const String& href, const KURL& baseURL,
if (m_styleSheet)
m_styleSheet->clearOwnerRule();
- CSSParserContext context = m_parentStyleSheet ? m_parentStyleSheet->parserContext() : CSSStrictMode;
- context.charset = charset;
+ CSSParserContext context = m_parentStyleSheet ? m_parentStyleSheet->parserContext() : HTMLStandardMode;
+ context.setCharset(charset);
if (!baseURL.isNull())
- context.baseURL = baseURL;
+ context.setBaseURL(baseURL);
m_styleSheet = StyleSheetContents::create(this, href, context);
@@ -115,10 +115,7 @@ void StyleRuleImport::requestStyleSheet()
}
FetchRequest request(ResourceRequest(absURL), FetchInitiatorTypeNames::css, m_parentStyleSheet->charset());
- if (m_parentStyleSheet->isUserStyleSheet())
- m_resource = fetcher->fetchUserCSSStyleSheet(request);
- else
- m_resource = fetcher->fetchCSSStyleSheet(request);
+ m_resource = fetcher->fetchCSSStyleSheet(request);
if (m_resource) {
// if the import rule is issued dynamically, the sheet may be
// removed from the pending sheet count, so let the doc know
diff --git a/chromium/third_party/WebKit/Source/core/css/StyleRuleImport.h b/chromium/third_party/WebKit/Source/core/css/StyleRuleImport.h
index c44253f53c9..8af664e2438 100644
--- a/chromium/third_party/WebKit/Source/core/css/StyleRuleImport.h
+++ b/chromium/third_party/WebKit/Source/core/css/StyleRuleImport.h
@@ -81,6 +81,8 @@ private:
bool m_loading;
};
+DEFINE_STYLE_RULE_TYPE_CASTS(Import);
+
} // namespace WebCore
#endif
diff --git a/chromium/third_party/WebKit/Source/core/css/StyleSheet.h b/chromium/third_party/WebKit/Source/core/css/StyleSheet.h
index 6ca572eff46..2207b5a006c 100644
--- a/chromium/third_party/WebKit/Source/core/css/StyleSheet.h
+++ b/chromium/third_party/WebKit/Source/core/css/StyleSheet.h
@@ -51,7 +51,6 @@ public:
virtual KURL baseURL() const = 0;
virtual bool isLoading() const = 0;
virtual bool isCSSStyleSheet() const { return false; }
- virtual bool isXSLStyleSheet() const { return false; }
};
} // namespace
diff --git a/chromium/third_party/WebKit/Source/core/css/StyleSheet.idl b/chromium/third_party/WebKit/Source/core/css/StyleSheet.idl
index 2c179ac0a53..e3e13b37b1d 100644
--- a/chromium/third_party/WebKit/Source/core/css/StyleSheet.idl
+++ b/chromium/third_party/WebKit/Source/core/css/StyleSheet.idl
@@ -20,8 +20,8 @@
// Introduced in DOM Level 2:
[
- CustomToV8,
- GenerateIsReachable=ownerNode
+ Custom=Wrap,
+ GenerateVisitDOMWrapper=ownerNode,
] interface StyleSheet {
[TreatReturnedNullStringAs=Null] readonly attribute DOMString type;
attribute boolean disabled;
diff --git a/chromium/third_party/WebKit/Source/core/css/StyleSheetContents.cpp b/chromium/third_party/WebKit/Source/core/css/StyleSheetContents.cpp
index 9eeb6f1d3b1..fa7b022da58 100644
--- a/chromium/third_party/WebKit/Source/core/css/StyleSheetContents.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/StyleSheetContents.cpp
@@ -27,9 +27,12 @@
#include "core/css/StylePropertySet.h"
#include "core/css/StyleRule.h"
#include "core/css/StyleRuleImport.h"
+#include "core/css/resolver/StyleResolver.h"
#include "core/dom/Node.h"
+#include "core/dom/StyleEngine.h"
#include "core/fetch/CSSStyleSheetResource.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/TraceEvent.h"
+#include "platform/weborigin/SecurityOrigin.h"
#include "wtf/Deque.h"
namespace WebCore {
@@ -56,12 +59,12 @@ StyleSheetContents::StyleSheetContents(StyleRuleImport* ownerRule, const String&
: m_ownerRule(ownerRule)
, m_originalURL(originalURL)
, m_loadCompleted(false)
- , m_isUserStyleSheet(ownerRule && ownerRule->parentStyleSheet() && ownerRule->parentStyleSheet()->isUserStyleSheet())
, m_hasSyntacticallyValidCSSHeader(true)
, m_didLoadErrorOccur(false)
, m_usesRemUnits(false)
, m_isMutable(false)
, m_isInMemoryCache(false)
+ , m_hasFontFaceRule(false)
, m_parserContext(context)
{
}
@@ -75,12 +78,12 @@ StyleSheetContents::StyleSheetContents(const StyleSheetContents& o)
, m_childRules(o.m_childRules.size())
, m_namespaces(o.m_namespaces)
, m_loadCompleted(true)
- , m_isUserStyleSheet(o.m_isUserStyleSheet)
, m_hasSyntacticallyValidCSSHeader(o.m_hasSyntacticallyValidCSSHeader)
, m_didLoadErrorOccur(false)
, m_usesRemUnits(o.m_usesRemUnits)
, m_isMutable(false)
, m_isInMemoryCache(false)
+ , m_hasFontFaceRule(o.m_hasFontFaceRule)
, m_parserContext(o.m_parserContext)
{
ASSERT(o.isCacheable());
@@ -99,6 +102,13 @@ StyleSheetContents::~StyleSheetContents()
bool StyleSheetContents::isCacheable() const
{
+ // FIXME: StyleSheets with media queries can't be cached because their RuleSet
+ // is processed differently based off the media queries, which might resolve
+ // differently depending on the context of the parent CSSStyleSheet (e.g.
+ // if they are in differently sized iframes). Once RuleSets are media query
+ // agnostic, we can restore sharing of StyleSheetContents with medea queries.
+ if (m_hasMediaQueries)
+ return false;
// FIXME: Support copying import rules.
if (!m_importRules.isEmpty())
return false;
@@ -126,19 +136,31 @@ void StyleSheetContents::parserAppendRule(PassRefPtr<StyleRuleBase> rule)
if (rule->isImportRule()) {
// Parser enforces that @import rules come before anything else except @charset.
ASSERT(m_childRules.isEmpty());
- m_importRules.append(static_cast<StyleRuleImport*>(rule.get()));
+ StyleRuleImport* importRule = toStyleRuleImport(rule.get());
+ if (importRule->mediaQueries())
+ setHasMediaQueries();
+ m_importRules.append(importRule);
m_importRules.last()->setParentStyleSheet(this);
m_importRules.last()->requestStyleSheet();
return;
}
// Add warning message to inspector if dpi/dpcm values are used for screen media.
- if (rule->isMediaRule())
- reportMediaQueryWarningIfNeeded(singleOwnerDocument(), static_cast<StyleRuleMedia*>(rule.get())->mediaQueries());
+ if (rule->isMediaRule()) {
+ setHasMediaQueries();
+ reportMediaQueryWarningIfNeeded(singleOwnerDocument(), toStyleRuleMedia(rule.get())->mediaQueries());
+ }
m_childRules.append(rule);
}
+void StyleSheetContents::setHasMediaQueries()
+{
+ m_hasMediaQueries = true;
+ if (parentStyleSheet())
+ parentStyleSheet()->setHasMediaQueries();
+}
+
StyleRuleBase* StyleSheetContents::ruleAt(unsigned index) const
{
ASSERT_WITH_SECURITY_IMPLICATION(index < ruleCount());
@@ -209,7 +231,12 @@ bool StyleSheetContents::wrapperInsertRule(PassRefPtr<StyleRuleBase> rule, unsig
// Inserting non-import rule before @import is not allowed.
if (!rule->isImportRule())
return false;
- m_importRules.insert(childVectorIndex, static_cast<StyleRuleImport*>(rule.get()));
+
+ StyleRuleImport* importRule = toStyleRuleImport(rule.get());
+ if (importRule->mediaQueries())
+ setHasMediaQueries();
+
+ m_importRules.insert(childVectorIndex, importRule);
m_importRules[childVectorIndex]->setParentStyleSheet(this);
m_importRules[childVectorIndex]->requestStyleSheet();
// FIXME: Stylesheet doesn't actually change meaningfully before the imported sheets are loaded.
@@ -218,6 +245,10 @@ bool StyleSheetContents::wrapperInsertRule(PassRefPtr<StyleRuleBase> rule, unsig
// Inserting @import rule after a non-import rule is not allowed.
if (rule->isImportRule())
return false;
+
+ if (rule->isMediaRule())
+ setHasMediaQueries();
+
childVectorIndex -= m_importRules.size();
m_childRules.insert(childVectorIndex, rule);
@@ -263,15 +294,16 @@ const AtomicString& StyleSheetContents::determineNamespace(const AtomicString& p
return nullAtom; // No namespace. If an element/attribute has a namespace, we won't match it.
if (prefix == starAtom)
return starAtom; // We'll match any namespace.
- PrefixNamespaceURIMap::const_iterator it = m_namespaces.find(prefix);
- if (it == m_namespaces.end())
- return nullAtom;
- return it->value;
+ return m_namespaces.get(prefix);
}
void StyleSheetContents::parseAuthorStyleSheet(const CSSStyleSheetResource* cachedStyleSheet, const SecurityOrigin* securityOrigin)
{
- bool enforceMIMEType = isStrictParserMode(m_parserContext.mode);
+ TRACE_EVENT0("webkit", "StyleSheetContents::parseAuthorStyleSheet");
+
+ bool quirksMode = isQuirksModeBehavior(m_parserContext.mode());
+
+ bool enforceMIMEType = !quirksMode;
bool hasValidMIMEType = false;
String sheetText = cachedStyleSheet->sheetText(enforceMIMEType, &hasValidMIMEType);
@@ -288,15 +320,6 @@ void StyleSheetContents::parseAuthorStyleSheet(const CSSStyleSheetResource* cach
return;
}
}
- if (m_parserContext.needsSiteSpecificQuirks && isStrictParserMode(m_parserContext.mode)) {
- // Work around <https://bugs.webkit.org/show_bug.cgi?id=28350>.
- DEFINE_STATIC_LOCAL(const String, mediaWikiKHTMLFixesStyleSheet, ("/* KHTML fix stylesheet */\n/* work around the horizontal scrollbars */\n#column-content { margin-left: 0; }\n\n"));
- // There are two variants of KHTMLFixes.css. One is equal to mediaWikiKHTMLFixesStyleSheet,
- // while the other lacks the second trailing newline.
- if (baseURL().string().endsWith("/KHTMLFixes.css") && !sheetText.isNull() && mediaWikiKHTMLFixesStyleSheet.startsWith(sheetText)
- && sheetText.length() >= mediaWikiKHTMLFixesStyleSheet.length() - 1)
- clearRules();
- }
}
bool StyleSheetContents::parseString(const String& sheetText)
@@ -351,6 +374,10 @@ void StyleSheetContents::notifyLoadedSheet(const CSSStyleSheetResource* sheet)
{
ASSERT(sheet);
m_didLoadErrorOccur |= sheet->errorOccurred();
+ // updateLayoutIgnorePendingStyleSheets can cause us to create the RuleSet on this
+ // sheet before its imports have loaded. So clear the RuleSet when the imports
+ // load since the import's subrules are flattened into its parent sheet's RuleSet.
+ clearRuleSet();
}
void StyleSheetContents::startLoadingDynamicSheet()
@@ -415,7 +442,7 @@ void StyleSheetContents::addSubresourceStyleURLs(ListHashSet<KURL>& urls)
if (rule->isStyleRule())
toStyleRule(rule)->properties()->addSubresourceStyleURLs(urls, this);
else if (rule->isFontFaceRule())
- static_cast<StyleRuleFontFace*>(rule)->properties()->addSubresourceStyleURLs(urls, this);
+ toStyleRuleFontFace(rule)->properties()->addSubresourceStyleURLs(urls, this);
}
}
}
@@ -426,23 +453,19 @@ static bool childRulesHaveFailedOrCanceledSubresources(const Vector<RefPtr<Style
const StyleRuleBase* rule = rules[i].get();
switch (rule->type()) {
case StyleRuleBase::Style:
- if (static_cast<const StyleRule*>(rule)->properties()->hasFailedOrCanceledSubresources())
+ if (toStyleRule(rule)->properties()->hasFailedOrCanceledSubresources())
return true;
break;
case StyleRuleBase::FontFace:
- if (static_cast<const StyleRuleFontFace*>(rule)->properties()->hasFailedOrCanceledSubresources())
+ if (toStyleRuleFontFace(rule)->properties()->hasFailedOrCanceledSubresources())
return true;
break;
case StyleRuleBase::Media:
- if (childRulesHaveFailedOrCanceledSubresources(static_cast<const StyleRuleMedia*>(rule)->childRules()))
+ if (childRulesHaveFailedOrCanceledSubresources(toStyleRuleMedia(rule)->childRules()))
return true;
break;
case StyleRuleBase::Region:
- if (childRulesHaveFailedOrCanceledSubresources(static_cast<const StyleRuleRegion*>(rule)->childRules()))
- return true;
- break;
- case StyleRuleBase::HostInternal:
- if (childRulesHaveFailedOrCanceledSubresources(static_cast<const StyleRuleHost*>(rule)->childRules()))
+ if (childRulesHaveFailedOrCanceledSubresources(toStyleRuleRegion(rule)->childRules()))
return true;
break;
case StyleRuleBase::Import:
@@ -505,4 +528,34 @@ void StyleSheetContents::shrinkToFit()
m_childRules.shrinkToFit();
}
+RuleSet& StyleSheetContents::ensureRuleSet(const MediaQueryEvaluator& medium, AddRuleFlags addRuleFlags)
+{
+ if (!m_ruleSet) {
+ m_ruleSet = RuleSet::create();
+ m_ruleSet->addRulesFromSheet(this, medium, addRuleFlags);
+ }
+ return *m_ruleSet.get();
+}
+
+void StyleSheetContents::clearRuleSet()
+{
+ if (StyleSheetContents* parentSheet = parentStyleSheet())
+ parentSheet->clearRuleSet();
+
+ // Don't want to clear the StyleResolver if the RuleSet hasn't been created
+ // since we only clear the StyleResolver so that it's members are properly
+ // updated in ScopedStyleResolver::addRulesFromSheet.
+ if (!m_ruleSet)
+ return;
+
+ // Clearing the ruleSet means we need to recreate the styleResolver data structures.
+ // See the StyleResolver calls in ScopedStyleResolver::addRulesFromSheet.
+ for (size_t i = 0; i < m_clients.size(); ++i) {
+ if (Document* document = m_clients[i]->ownerDocument())
+ document->styleEngine()->clearResolver();
+ }
+ m_ruleSet.clear();
+}
+
+
}
diff --git a/chromium/third_party/WebKit/Source/core/css/StyleSheetContents.h b/chromium/third_party/WebKit/Source/core/css/StyleSheetContents.h
index 02bf850ba74..7d59d80ef93 100644
--- a/chromium/third_party/WebKit/Source/core/css/StyleSheetContents.h
+++ b/chromium/third_party/WebKit/Source/core/css/StyleSheetContents.h
@@ -22,12 +22,14 @@
#define StyleSheetContents_h
#include "core/css/CSSParserMode.h"
-#include "weborigin/KURL.h"
+#include "core/css/RuleSet.h"
+#include "platform/weborigin/KURL.h"
#include "wtf/HashMap.h"
#include "wtf/ListHashSet.h"
#include "wtf/RefCounted.h"
#include "wtf/Vector.h"
#include "wtf/text/AtomicStringHash.h"
+#include "wtf/text/StringHash.h"
#include "wtf/text/TextPosition.h"
@@ -43,7 +45,7 @@ class StyleRuleImport;
class StyleSheetContents : public RefCounted<StyleSheetContents> {
public:
- static PassRefPtr<StyleSheetContents> create(const CSSParserContext& context = CSSParserContext(CSSStrictMode))
+ static PassRefPtr<StyleSheetContents> create(const CSSParserContext& context = CSSParserContext(HTMLStandardMode))
{
return adoptRef(new StyleSheetContents(0, String(), context));
}
@@ -78,7 +80,7 @@ public:
Node* singleOwnerNode() const;
Document* singleOwnerDocument() const;
- const String& charset() const { return m_parserContext.charset; }
+ const String& charset() const { return m_parserContext.charset(); }
bool loadCompleted() const { return m_loadCompleted; }
bool hasFailedOrCanceledSubresources() const;
@@ -86,11 +88,12 @@ public:
KURL completeURL(const String& url) const;
void addSubresourceStyleURLs(ListHashSet<KURL>&);
- void setIsUserStyleSheet(bool b) { m_isUserStyleSheet = b; }
- bool isUserStyleSheet() const { return m_isUserStyleSheet; }
void setHasSyntacticallyValidCSSHeader(bool b) { m_hasSyntacticallyValidCSSHeader = b; }
bool hasSyntacticallyValidCSSHeader() const { return m_hasSyntacticallyValidCSSHeader; }
+ void setHasFontFaceRule(bool b) { m_hasFontFaceRule = b; }
+ bool hasFontFaceRule() const { return m_hasFontFaceRule; }
+
void parserAddNamespace(const AtomicString& prefix, const AtomicString& uri);
void parserAppendRule(PassRefPtr<StyleRuleBase>);
void parserSetEncodingFromCharsetRule(const String& encoding);
@@ -114,7 +117,7 @@ public:
// this style sheet. This property probably isn't useful for much except
// the JavaScript binding (which needs to use this value for security).
String originalURL() const { return m_originalURL; }
- const KURL& baseURL() const { return m_parserContext.baseURL; }
+ const KURL& baseURL() const { return m_parserContext.baseURL(); }
unsigned ruleCount() const;
StyleRuleBase* ruleAt(unsigned index) const;
@@ -139,7 +142,13 @@ public:
void addedToMemoryCache();
void removedFromMemoryCache();
+ void setHasMediaQueries();
+ bool hasMediaQueries() { return m_hasMediaQueries; }
+
void shrinkToFit();
+ RuleSet& ruleSet() { ASSERT(m_ruleSet); return *m_ruleSet.get(); }
+ RuleSet& ensureRuleSet(const MediaQueryEvaluator&, AddRuleFlags);
+ void clearRuleSet();
private:
StyleSheetContents(StyleRuleImport* ownerRule, const String& originalURL, const CSSParserContext&);
@@ -158,16 +167,18 @@ private:
PrefixNamespaceURIMap m_namespaces;
bool m_loadCompleted : 1;
- bool m_isUserStyleSheet : 1;
bool m_hasSyntacticallyValidCSSHeader : 1;
bool m_didLoadErrorOccur : 1;
bool m_usesRemUnits : 1;
bool m_isMutable : 1;
bool m_isInMemoryCache : 1;
+ bool m_hasFontFaceRule : 1;
+ bool m_hasMediaQueries : 1;
CSSParserContext m_parserContext;
Vector<CSSStyleSheet*> m_clients;
+ OwnPtr<RuleSet> m_ruleSet;
};
} // namespace
diff --git a/chromium/third_party/WebKit/Source/core/css/StyleSheetList.cpp b/chromium/third_party/WebKit/Source/core/css/StyleSheetList.cpp
index b773deb826e..10f5905ba4e 100644
--- a/chromium/third_party/WebKit/Source/core/css/StyleSheetList.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/StyleSheetList.cpp
@@ -31,8 +31,8 @@ namespace WebCore {
using namespace HTMLNames;
-StyleSheetList::StyleSheetList(Document* document)
- : m_document(document)
+StyleSheetList::StyleSheetList(TreeScope* treeScope)
+ : m_treeScope(treeScope)
{
}
@@ -40,20 +40,20 @@ StyleSheetList::~StyleSheetList()
{
}
-inline const Vector<RefPtr<StyleSheet> >& StyleSheetList::styleSheets() const
+inline const Vector<RefPtr<StyleSheet> >& StyleSheetList::styleSheets()
{
- if (!m_document)
+ if (!m_treeScope)
return m_detachedStyleSheets;
- return m_document->styleEngine()->styleSheetsForStyleSheetList();
+ return document()->styleEngine()->styleSheetsForStyleSheetList(*m_treeScope);
}
void StyleSheetList::detachFromDocument()
{
- m_detachedStyleSheets = m_document->styleEngine()->styleSheetsForStyleSheetList();
- m_document = 0;
+ m_detachedStyleSheets = document()->styleEngine()->styleSheetsForStyleSheetList(*m_treeScope);
+ m_treeScope = 0;
}
-unsigned StyleSheetList::length() const
+unsigned StyleSheetList::length()
{
return styleSheets().size();
}
@@ -64,9 +64,9 @@ StyleSheet* StyleSheetList::item(unsigned index)
return index < sheets.size() ? sheets[index].get() : 0;
}
-HTMLStyleElement* StyleSheetList::getNamedItem(const String& name) const
+HTMLStyleElement* StyleSheetList::getNamedItem(const AtomicString& name) const
{
- if (!m_document)
+ if (!m_treeScope)
return 0;
// IE also supports retrieving a stylesheet by name, using the name/id of the <style> tag
@@ -75,7 +75,7 @@ HTMLStyleElement* StyleSheetList::getNamedItem(const String& name) const
// and doesn't look for name attribute.
// But unicity of stylesheet ids is good practice anyway ;)
// FIXME: We should figure out if we should change this or fix the spec.
- Element* element = m_document->getElementById(name);
+ Element* element = m_treeScope->getElementById(name);
if (element && element->hasTagName(styleTag))
return toHTMLStyleElement(element);
return 0;
diff --git a/chromium/third_party/WebKit/Source/core/css/StyleSheetList.h b/chromium/third_party/WebKit/Source/core/css/StyleSheetList.h
index e340f04e518..c9c15404729 100644
--- a/chromium/third_party/WebKit/Source/core/css/StyleSheetList.h
+++ b/chromium/third_party/WebKit/Source/core/css/StyleSheetList.h
@@ -22,6 +22,7 @@
#define StyleSheetList_h
#include "core/css/CSSStyleSheet.h"
+#include "core/dom/TreeScope.h"
#include "wtf/Forward.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefCounted.h"
@@ -29,30 +30,29 @@
namespace WebCore {
-class Document;
class HTMLStyleElement;
class StyleSheet;
class StyleSheetList : public RefCounted<StyleSheetList> {
public:
- static PassRefPtr<StyleSheetList> create(Document* document) { return adoptRef(new StyleSheetList(document)); }
+ static PassRefPtr<StyleSheetList> create(TreeScope* treeScope) { return adoptRef(new StyleSheetList(treeScope)); }
~StyleSheetList();
- unsigned length() const;
+ unsigned length();
StyleSheet* item(unsigned index);
- HTMLStyleElement* getNamedItem(const String&) const;
+ HTMLStyleElement* getNamedItem(const AtomicString&) const;
- Document* document() { return m_document; }
+ Document* document() { return m_treeScope->documentScope(); }
void detachFromDocument();
CSSStyleSheet* anonymousNamedGetter(const AtomicString&);
private:
- StyleSheetList(Document*);
- const Vector<RefPtr<StyleSheet> >& styleSheets() const;
+ StyleSheetList(TreeScope*);
+ const Vector<RefPtr<StyleSheet> >& styleSheets();
- Document* m_document;
+ TreeScope* m_treeScope;
Vector<RefPtr<StyleSheet> > m_detachedStyleSheets;
};
diff --git a/chromium/third_party/WebKit/Source/core/css/StyleSheetList.idl b/chromium/third_party/WebKit/Source/core/css/StyleSheetList.idl
index dcf92c2e020..7341728216d 100644
--- a/chromium/third_party/WebKit/Source/core/css/StyleSheetList.idl
+++ b/chromium/third_party/WebKit/Source/core/css/StyleSheetList.idl
@@ -20,7 +20,7 @@
// Introduced in DOM Level 2:
[
- GenerateIsReachable=document,
+ GenerateVisitDOMWrapper=document,
] interface StyleSheetList {
readonly attribute unsigned long length;
getter StyleSheet item(unsigned long index);
diff --git a/chromium/third_party/WebKit/Source/core/css/TreeBoundaryCrossingRules.cpp b/chromium/third_party/WebKit/Source/core/css/TreeBoundaryCrossingRules.cpp
new file mode 100644
index 00000000000..30a5604c412
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/css/TreeBoundaryCrossingRules.cpp
@@ -0,0 +1,63 @@
+/*
+ * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
+ * (C) 2004-2005 Allan Sandfeld Jensen (kde@carewolf.com)
+ * Copyright (C) 2006, 2007 Nicholas Shanks (webkit@nickshanks.com)
+ * Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 Apple Inc. All rights reserved.
+ * Copyright (C) 2007 Alexey Proskuryakov <ap@webkit.org>
+ * Copyright (C) 2007, 2008 Eric Seidel <eric@webkit.org>
+ * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
+ * Copyright (c) 2011, Code Aurora Forum. All rights reserved.
+ * Copyright (C) Research In Motion Limited 2011. All rights reserved.
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#include "config.h"
+#include "core/css/TreeBoundaryCrossingRules.h"
+
+#include "core/css/RuleFeature.h"
+#include "core/dom/StyleEngine.h"
+
+namespace WebCore {
+
+void TreeBoundaryCrossingRules::addRule(StyleRule* rule, size_t selectorIndex, ContainerNode* scopingNode, AddRuleFlags addRuleFlags)
+{
+ if (m_treeBoundaryCrossingRuleSetMap.contains(scopingNode)) {
+ m_treeBoundaryCrossingRuleSetMap.get(scopingNode)->addRule(rule, selectorIndex, addRuleFlags);
+ } else {
+ OwnPtr<RuleSet> ruleSetForScope = RuleSet::create();
+ ruleSetForScope->addRule(rule, selectorIndex, addRuleFlags);
+ m_treeBoundaryCrossingRuleSetMap.add(scopingNode, ruleSetForScope.release());
+ m_scopingNodes.add(scopingNode);
+ }
+}
+
+void TreeBoundaryCrossingRules::reset(const ContainerNode* scopingNode)
+{
+ m_treeBoundaryCrossingRuleSetMap.remove(scopingNode);
+ m_scopingNodes.remove(scopingNode);
+}
+
+void TreeBoundaryCrossingRules::collectFeaturesTo(RuleFeatureSet& features)
+{
+ for (TreeBoundaryCrossingRuleSetMap::iterator::Values it = m_treeBoundaryCrossingRuleSetMap.values().begin(); it != m_treeBoundaryCrossingRuleSetMap.values().end(); ++it) {
+ RuleSet* ruleSet = it->get();
+ features.add(ruleSet->features());
+ }
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/css/TreeBoundaryCrossingRules.h b/chromium/third_party/WebKit/Source/core/css/TreeBoundaryCrossingRules.h
new file mode 100644
index 00000000000..bba30ed9dcf
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/css/TreeBoundaryCrossingRules.h
@@ -0,0 +1,58 @@
+/*
+ * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
+ * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ */
+
+#ifndef TreeBoundaryCrossingRules_h
+#define TreeBoundaryCrossingRules_h
+
+#include "core/css/RuleSet.h"
+#include "core/dom/DocumentOrderedList.h"
+
+#include "wtf/OwnPtr.h"
+#include "wtf/RefPtr.h"
+#include "wtf/Vector.h"
+
+namespace WebCore {
+
+class ContainerNode;
+class RuleFeatureSet;
+
+class TreeBoundaryCrossingRules {
+public:
+ void addRule(StyleRule*, size_t selectorIndex, ContainerNode* scopingNode, AddRuleFlags);
+ void clear() { m_treeBoundaryCrossingRuleSetMap.clear(); }
+ void reset(const ContainerNode* scopingNode);
+ bool isEmpty() const { return m_treeBoundaryCrossingRuleSetMap.isEmpty(); }
+ void collectFeaturesTo(RuleFeatureSet&);
+
+ DocumentOrderedList::iterator begin() { return m_scopingNodes.begin(); }
+ DocumentOrderedList::iterator end() { return m_scopingNodes.end(); }
+ RuleSet* ruleSetScopedBy(const ContainerNode* scopingNode) { return m_treeBoundaryCrossingRuleSetMap.get(scopingNode); }
+
+private:
+ DocumentOrderedList m_scopingNodes;
+ typedef HashMap<const ContainerNode*, OwnPtr<RuleSet> > TreeBoundaryCrossingRuleSetMap;
+ TreeBoundaryCrossingRuleSetMap m_treeBoundaryCrossingRuleSetMap;
+};
+
+} // namespace WebCore
+
+#endif // TreeBoundaryCrossingRules_h
diff --git a/chromium/third_party/WebKit/Source/core/css/WebKitCSSMatrix.idl b/chromium/third_party/WebKit/Source/core/css/WebKitCSSMatrix.idl
index b3232daf141..0016fcfdc80 100644
--- a/chromium/third_party/WebKit/Source/core/css/WebKitCSSMatrix.idl
+++ b/chromium/third_party/WebKit/Source/core/css/WebKitCSSMatrix.idl
@@ -27,7 +27,7 @@
[
Constructor([Default=NullString] optional DOMString cssValue),
ImplementedAs=CSSMatrix,
- ConstructorRaisesException
+ RaisesException=Constructor
] interface WebKitCSSMatrix {
// These attributes are simple aliases for certain elements of the 4x4 matrix
diff --git a/chromium/third_party/WebKit/Source/core/css/WebKitCSSRegionRule.idl b/chromium/third_party/WebKit/Source/core/css/WebKitCSSRegionRule.idl
index ad91ce0f027..68113448048 100644
--- a/chromium/third_party/WebKit/Source/core/css/WebKitCSSRegionRule.idl
+++ b/chromium/third_party/WebKit/Source/core/css/WebKitCSSRegionRule.idl
@@ -28,7 +28,7 @@
*/
[
- EnabledAtRuntime=CSSRegions,
+ RuntimeEnabled=CSSRegions,
ImplementedAs=CSSRegionRule
] interface WebKitCSSRegionRule : CSSRule {
readonly attribute CSSRuleList cssRules;
diff --git a/chromium/third_party/WebKit/Source/core/css/fullscreen.css b/chromium/third_party/WebKit/Source/core/css/fullscreen.css
index 5ea5f06c2f0..7ecffc6ffa2 100644
--- a/chromium/third_party/WebKit/Source/core/css/fullscreen.css
+++ b/chromium/third_party/WebKit/Source/core/css/fullscreen.css
@@ -24,6 +24,8 @@
video:-webkit-full-screen, audio:-webkit-full-screen {
background-color: transparent !important;
position: relative !important;
+ left: 0 !important;
+ top: 0 ! important;
margin: 0 !important;
height: 100% !important;
width: 100% !important;
diff --git a/chromium/third_party/WebKit/Source/core/css/html.css b/chromium/third_party/WebKit/Source/core/css/html.css
index b41ccf09630..fdacec72bdf 100644
--- a/chromium/third_party/WebKit/Source/core/css/html.css
+++ b/chromium/third_party/WebKit/Source/core/css/html.css
@@ -448,6 +448,13 @@ input::-webkit-clear-button {
flex: none;
-webkit-user-modify: read-only !important;
-webkit-margin-start: 2px;
+ opacity: 0;
+ pionter-events: none;
+}
+
+input:enabled:read-write:-webkit-any(:focus,:hover)::-webkit-clear-button {
+ opacity: 1;
+ pointer-events: auto;
}
input[type="search"]::-webkit-search-cancel-button {
@@ -456,6 +463,13 @@ input[type="search"]::-webkit-search-cancel-button {
flex: none;
-webkit-user-modify: read-only !important;
-webkit-margin-start: 1px;
+ opacity: 0;
+ pointer-events: none;
+}
+
+input[type="search"]:enabled:read-write:-webkit-any(:focus,:hover)::-webkit-search-cancel-button {
+ opacity: 1;
+ pointer-events: auto;
}
input[type="search"]::-webkit-search-decoration {
@@ -600,6 +614,13 @@ input::-webkit-inner-spin-button {
flex: none;
-webkit-user-select: none;
-webkit-user-modify: read-only !important;
+ opacity: 0;
+ pointer-events: none;
+}
+
+input:enabled:read-write:-webkit-any(:focus,:hover)::-webkit-inner-spin-button {
+ opacity: 1;
+ pointer-events: auto;
}
#if defined(ENABLE_INPUT_SPEECH) && ENABLE_INPUT_SPEECH
@@ -667,7 +688,7 @@ input[type="file"] {
text-align: start !important;
}
-input:-webkit-autofill {
+input:-webkit-autofill, textarea:-webkit-autofill {
background-color: #FAFFBD !important;
background-image:none !important;
color: #000000 !important;
@@ -682,6 +703,7 @@ input[type="radio"], input[type="checkbox"] {
input[type="button"], input[type="submit"], input[type="reset"] {
-webkit-appearance: push-button;
+ -webkit-user-select: none;
white-space: pre
}
@@ -787,19 +809,25 @@ input[type="color"]::-webkit-color-swatch {
-webkit-user-modify: read-only !important;
}
-#if defined(ENABLE_CALENDAR_PICKER) && ENABLE_CALENDAR_PICKER
input::-webkit-calendar-picker-indicator {
display: inline-block;
width: 0.66em;
height: 0.66em;
padding: 0.17em 0.34em;
-webkit-user-modify: read-only !important;
+ opacity: 0;
+ pointer-events: none;
}
input::-webkit-calendar-picker-indicator:hover {
background-color: #eee;
}
+input:enabled:read-write:-webkit-any(:focus,:hover)::-webkit-calendar-picker-indicator {
+ opacity: 1;
+ pointer-events: auto;
+}
+
input[type="date"]:disabled::-webkit-clear-button,
input[type="date"]:disabled::-webkit-inner-spin-button,
input[type="datetime-local"]:disabled::-webkit-clear-button,
@@ -820,7 +848,6 @@ input[type="week"][readonly]::-webkit-inner-spin-button,
input[readonly]::-webkit-calendar-picker-indicator {
visibility: hidden;
}
-#endif // ENABLE_CALENDAR_PICKER
select {
-webkit-appearance: menulist;
@@ -1130,11 +1157,5 @@ textarea[dir=auto] {
border-width: 0px;
}
-/* viewport */
-
-@viewport {
- min-width: 980px;
-}
-
/* noscript is handled internally, as it depends on settings. */
diff --git a/chromium/third_party/WebKit/Source/core/css/makegrammar.pl b/chromium/third_party/WebKit/Source/core/css/makegrammar.pl
deleted file mode 100644
index eb47022af17..00000000000
--- a/chromium/third_party/WebKit/Source/core/css/makegrammar.pl
+++ /dev/null
@@ -1,58 +0,0 @@
-#! /usr/bin/perl
-#
-# This file is part of the WebKit project
-#
-# Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Library General Public
-# License as published by the Free Software Foundation; either
-# version 2 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Library General Public License for more details.
-#
-# You should have received a copy of the GNU Library General Public License
-# along with this library; see the file COPYING.LIB. If not, write to
-# the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
-# Boston, MA 02110-1301, USA.
-use strict;
-use warnings;
-
-use File::Basename;
-use File::Spec;
-use Getopt::Long;
-
-my $outputDir = ".";
-
-GetOptions(
- 'outputDir=s' => \$outputDir,
-);
-
-my $grammarFilePath = $ARGV[0];
-my $grammarIncludesFilePath = @ARGV > 0 ? $ARGV[1] : "";
-
-my ($filename, $basePath, $suffix) = fileparse($grammarFilePath, (".y", ".y.in"));
-
-my $grammarFileOutPath = File::Spec->join($outputDir, "$filename.y");
-if (!$grammarIncludesFilePath) {
- $grammarIncludesFilePath = "${basePath}${filename}.y.includes";
-}
-
-open GRAMMAR, ">$grammarFileOutPath" or die;
-open INCLUDES, "<$grammarIncludesFilePath" or die;
-
-while (<INCLUDES>) {
- print GRAMMAR;
-}
-
-open GRAMMARFILE, "<$grammarFilePath" or die;
-while (<GRAMMARFILE>) {
- print GRAMMAR;
-}
-
-close GRAMMAR;
-
-$grammarFilePath = $grammarFileOutPath;
diff --git a/chromium/third_party/WebKit/Source/core/css/mediaControls.css b/chromium/third_party/WebKit/Source/core/css/mediaControls.css
index 2c8e073dd30..a2efc1d2bc1 100644
--- a/chromium/third_party/WebKit/Source/core/css/mediaControls.css
+++ b/chromium/third_party/WebKit/Source/core/css/mediaControls.css
@@ -281,7 +281,11 @@ audio::-webkit-media-controls-return-to-realtime-button, video::-webkit-media-co
color: inherit;
}
-audio::-webkit-media-controls-toggle-closed-captions-button, video::-webkit-media-controls-toggle-closed-captions-button {
+audio::-webkit-media-controls-toggle-closed-captions-button {
+ display: none;
+}
+
+video::-webkit-media-controls-toggle-closed-captions-button {
-webkit-appearance: media-toggle-closed-captions-button;
display: flex;
flex: none;
diff --git a/chromium/third_party/WebKit/Source/core/css/mediaControlsAndroid.css b/chromium/third_party/WebKit/Source/core/css/mediaControlsAndroid.css
index 69bdd8d66a0..35a0bb4435e 100644
--- a/chromium/third_party/WebKit/Source/core/css/mediaControlsAndroid.css
+++ b/chromium/third_party/WebKit/Source/core/css/mediaControlsAndroid.css
@@ -30,10 +30,14 @@ audio {
height: 35px;
}
-audio::-webkit-media-controls-enclosure, video::-webkit-media-controls-enclosure {
+audio::-webkit-media-controls-enclosure {
height: 35px;
}
+video::-webkit-media-controls-enclosure {
+ height: 40px;
+}
+
audio::-webkit-media-controls-overlay-enclosure {
display: none;
}
@@ -54,7 +58,6 @@ video::-webkit-media-controls-overlay-enclosure {
audio::-webkit-media-controls-panel, video::-webkit-media-controls-panel {
height: 35px;
- border-radius: 0;
}
audio::-webkit-media-controls-mute-button, video::-webkit-media-controls-mute-button {
@@ -104,7 +107,7 @@ audio::-webkit-media-controls-fullscreen-button {
display: none;
}
-audio::-webkit-media-controls-toggle-closed-captions-button, video::-webkit-media-controls-toggle-closed-captions-button {
+video::-webkit-media-controls-toggle-closed-captions-button {
width: 35px;
height: 35px;
line-height: 35px;
diff --git a/chromium/third_party/WebKit/Source/core/css/resolver/AnimatedStyleBuilder.cpp b/chromium/third_party/WebKit/Source/core/css/resolver/AnimatedStyleBuilder.cpp
index bc86494a5ea..dbfd63b8bb6 100644
--- a/chromium/third_party/WebKit/Source/core/css/resolver/AnimatedStyleBuilder.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/resolver/AnimatedStyleBuilder.cpp
@@ -31,10 +31,22 @@
#include "config.h"
#include "core/css/resolver/AnimatedStyleBuilder.h"
+#include "core/animation/AnimatableClipPathOperation.h"
#include "core/animation/AnimatableColor.h"
+#include "core/animation/AnimatableDouble.h"
+#include "core/animation/AnimatableFilterOperations.h"
#include "core/animation/AnimatableImage.h"
+#include "core/animation/AnimatableLength.h"
#include "core/animation/AnimatableLengthBox.h"
-#include "core/animation/AnimatableNumber.h"
+#include "core/animation/AnimatableLengthBoxAndBool.h"
+#include "core/animation/AnimatableLengthPoint.h"
+#include "core/animation/AnimatableLengthSize.h"
+#include "core/animation/AnimatableRepeatable.h"
+#include "core/animation/AnimatableSVGLength.h"
+#include "core/animation/AnimatableSVGPaint.h"
+#include "core/animation/AnimatableShadow.h"
+#include "core/animation/AnimatableShapeValue.h"
+#include "core/animation/AnimatableStrokeDasharrayList.h"
#include "core/animation/AnimatableTransform.h"
#include "core/animation/AnimatableUnknown.h"
#include "core/animation/AnimatableValue.h"
@@ -51,30 +63,166 @@ namespace WebCore {
namespace {
-Length animatableValueToLength(const AnimatableValue* value, const StyleResolverState& state)
+Length animatableValueToLength(const AnimatableValue* value, const StyleResolverState& state, NumberRange range = AllValues)
{
- const RenderStyle* style = state.style();
- if (value->isNumber())
- return toAnimatableNumber(value)->toLength(style, state.rootElementStyle(), style->effectiveZoom());
+ if (value->isLength())
+ return toAnimatableLength(value)->toLength(state.cssToLengthConversionData(), range);
RefPtr<CSSValue> cssValue = toAnimatableUnknown(value)->toCSSValue();
CSSPrimitiveValue* cssPrimitiveValue = toCSSPrimitiveValue(cssValue.get());
- return cssPrimitiveValue->convertToLength<AnyConversion>(style, state.rootElementStyle(), style->effectiveZoom());
+ return cssPrimitiveValue->convertToLength<AnyConversion>(state.cssToLengthConversionData());
}
-template<typename T> T animatableValueRoundClampTo(const AnimatableValue* value)
+BorderImageLength animatableValueToBorderImageLength(const AnimatableValue* value, const StyleResolverState& state)
+{
+ if (value->isLength())
+ return BorderImageLength(toAnimatableLength(value)->toLength(state.cssToLengthConversionData(), NonNegativeValues));
+ if (value->isDouble())
+ return BorderImageLength(clampTo<double>(toAnimatableDouble(value)->toDouble(), 0));
+ RefPtr<CSSValue> cssValue = toAnimatableUnknown(value)->toCSSValue();
+ CSSPrimitiveValue* cssPrimitiveValue = toCSSPrimitiveValue(cssValue.get());
+ return BorderImageLength(cssPrimitiveValue->convertToLength<AnyConversion>(state.cssToLengthConversionData()));
+}
+
+template<typename T> T animatableValueRoundClampTo(const AnimatableValue* value, T min = defaultMinimumForClamp<T>(), T max = defaultMaximumForClamp<T>())
{
COMPILE_ASSERT(WTF::IsInteger<T>::value, ShouldUseIntegralTypeTWhenRoundingValues);
- return clampTo<T>(round(toAnimatableNumber(value)->toDouble()));
+ return clampTo<T>(round(toAnimatableDouble(value)->toDouble()), min, max);
}
-LengthBox animatableValueToLengthBox(const AnimatableValue* value, const StyleResolverState& state)
+LengthBox animatableValueToLengthBox(const AnimatableValue* value, const StyleResolverState& state, NumberRange range = AllValues)
{
const AnimatableLengthBox* animatableLengthBox = toAnimatableLengthBox(value);
return LengthBox(
- animatableValueToLength(animatableLengthBox->top(), state),
- animatableValueToLength(animatableLengthBox->right(), state),
- animatableValueToLength(animatableLengthBox->bottom(), state),
- animatableValueToLength(animatableLengthBox->left(), state));
+ animatableValueToLength(animatableLengthBox->top(), state, range),
+ animatableValueToLength(animatableLengthBox->right(), state, range),
+ animatableValueToLength(animatableLengthBox->bottom(), state, range),
+ animatableValueToLength(animatableLengthBox->left(), state, range));
+}
+
+BorderImageLengthBox animatableValueToBorderImageLengthBox(const AnimatableValue* value, const StyleResolverState& state)
+{
+ const AnimatableLengthBox* animatableLengthBox = toAnimatableLengthBox(value);
+ return BorderImageLengthBox(
+ animatableValueToBorderImageLength(animatableLengthBox->top(), state),
+ animatableValueToBorderImageLength(animatableLengthBox->right(), state),
+ animatableValueToBorderImageLength(animatableLengthBox->bottom(), state),
+ animatableValueToBorderImageLength(animatableLengthBox->left(), state));
+}
+
+LengthPoint animatableValueToLengthPoint(const AnimatableValue* value, const StyleResolverState& state, NumberRange range = AllValues)
+{
+ const AnimatableLengthPoint* animatableLengthPoint = toAnimatableLengthPoint(value);
+ return LengthPoint(
+ animatableValueToLength(animatableLengthPoint->x(), state, range),
+ animatableValueToLength(animatableLengthPoint->y(), state, range));
+}
+
+LengthSize animatableValueToLengthSize(const AnimatableValue* value, const StyleResolverState& state, NumberRange range)
+{
+ const AnimatableLengthSize* animatableLengthSize = toAnimatableLengthSize(value);
+ return LengthSize(
+ animatableValueToLength(animatableLengthSize->width(), state, range),
+ animatableValueToLength(animatableLengthSize->height(), state, range));
+}
+
+template <CSSPropertyID property>
+void setFillSize(FillLayer* fillLayer, const AnimatableValue* value, const StyleResolverState& state)
+{
+ if (value->isLengthSize())
+ fillLayer->setSize(FillSize(SizeLength, animatableValueToLengthSize(value, state, NonNegativeValues)));
+ else
+ state.styleMap().mapFillSize(property, fillLayer, toAnimatableUnknown(value)->toCSSValue().get());
+}
+
+SVGLength animatableValueToNonNegativeSVGLength(const AnimatableValue* value)
+{
+ SVGLength length = toAnimatableSVGLength(value)->toSVGLength();
+ if (length.valueInSpecifiedUnits() < 0)
+ length.setValueInSpecifiedUnits(0);
+ return length;
+}
+
+template <CSSPropertyID property>
+void setOnFillLayers(FillLayer* fillLayer, const AnimatableValue* value, StyleResolverState& state)
+{
+ const Vector<RefPtr<AnimatableValue> >& values = toAnimatableRepeatable(value)->values();
+ ASSERT(!values.isEmpty());
+ FillLayer* prev = 0;
+ for (size_t i = 0; i < values.size(); ++i) {
+ if (!fillLayer) {
+ switch (property) {
+ case CSSPropertyBackgroundImage:
+ case CSSPropertyBackgroundPositionX:
+ case CSSPropertyBackgroundPositionY:
+ case CSSPropertyBackgroundSize:
+ case CSSPropertyWebkitBackgroundSize:
+ fillLayer = new FillLayer(BackgroundFillLayer);
+ break;
+ case CSSPropertyWebkitMaskImage:
+ case CSSPropertyWebkitMaskPositionX:
+ case CSSPropertyWebkitMaskPositionY:
+ case CSSPropertyWebkitMaskSize:
+ fillLayer = new FillLayer(MaskFillLayer);
+ break;
+ default:
+ ASSERT_NOT_REACHED();
+ }
+ prev->setNext(fillLayer);
+ }
+ const AnimatableValue* layerValue = values[i].get();
+ switch (property) {
+ case CSSPropertyBackgroundImage:
+ case CSSPropertyWebkitMaskImage:
+ if (layerValue->isImage()) {
+ fillLayer->setImage(toAnimatableImage(layerValue)->toStyleImage());
+ } else {
+ ASSERT(toAnimatableUnknown(layerValue)->toCSSValueID() == CSSValueNone);
+ fillLayer->setImage(0);
+ }
+ break;
+ case CSSPropertyBackgroundPositionX:
+ case CSSPropertyWebkitMaskPositionX:
+ fillLayer->setXPosition(animatableValueToLength(layerValue, state));
+ break;
+ case CSSPropertyBackgroundPositionY:
+ case CSSPropertyWebkitMaskPositionY:
+ fillLayer->setYPosition(animatableValueToLength(layerValue, state));
+ break;
+ case CSSPropertyBackgroundSize:
+ case CSSPropertyWebkitBackgroundSize:
+ case CSSPropertyWebkitMaskSize:
+ setFillSize<property>(fillLayer, layerValue, state);
+ break;
+ default:
+ ASSERT_NOT_REACHED();
+ }
+ prev = fillLayer;
+ fillLayer = fillLayer->next();
+ }
+ while (fillLayer) {
+ switch (property) {
+ case CSSPropertyBackgroundImage:
+ case CSSPropertyWebkitMaskImage:
+ fillLayer->clearImage();
+ break;
+ case CSSPropertyBackgroundPositionX:
+ case CSSPropertyWebkitMaskPositionX:
+ fillLayer->clearXPosition();
+ break;
+ case CSSPropertyBackgroundPositionY:
+ case CSSPropertyWebkitMaskPositionY:
+ fillLayer->clearYPosition();
+ break;
+ case CSSPropertyBackgroundSize:
+ case CSSPropertyWebkitBackgroundSize:
+ case CSSPropertyWebkitMaskSize:
+ fillLayer->clearSize();
+ break;
+ default:
+ ASSERT_NOT_REACHED();
+ }
+ fillLayer = fillLayer->next();
+ }
}
} // namespace
@@ -92,24 +240,45 @@ void AnimatedStyleBuilder::applyProperty(CSSPropertyID property, StyleResolverSt
style->setBackgroundColor(toAnimatableColor(value)->color());
style->setVisitedLinkBackgroundColor(toAnimatableColor(value)->visitedLinkColor());
return;
+ case CSSPropertyBackgroundImage:
+ setOnFillLayers<CSSPropertyBackgroundImage>(style->accessBackgroundLayers(), value, state);
+ return;
+ case CSSPropertyBackgroundPositionX:
+ setOnFillLayers<CSSPropertyBackgroundPositionX>(style->accessBackgroundLayers(), value, state);
+ return;
+ case CSSPropertyBackgroundPositionY:
+ setOnFillLayers<CSSPropertyBackgroundPositionY>(style->accessBackgroundLayers(), value, state);
+ return;
+ case CSSPropertyBackgroundSize:
+ setOnFillLayers<CSSPropertyBackgroundSize>(style->accessBackgroundLayers(), value, state);
+ return;
+ case CSSPropertyBaselineShift:
+ style->setBaselineShiftValue(toAnimatableSVGLength(value)->toSVGLength());
+ return;
case CSSPropertyBorderBottomColor:
style->setBorderBottomColor(toAnimatableColor(value)->color());
style->setVisitedLinkBorderBottomColor(toAnimatableColor(value)->visitedLinkColor());
return;
+ case CSSPropertyBorderBottomLeftRadius:
+ style->setBorderBottomLeftRadius(animatableValueToLengthSize(value, state, NonNegativeValues));
+ return;
+ case CSSPropertyBorderBottomRightRadius:
+ style->setBorderBottomRightRadius(animatableValueToLengthSize(value, state, NonNegativeValues));
+ return;
case CSSPropertyBorderBottomWidth:
style->setBorderBottomWidth(animatableValueRoundClampTo<unsigned>(value));
return;
case CSSPropertyBorderImageOutset:
- style->setBorderImageOutset(animatableValueToLengthBox(value, state));
+ style->setBorderImageOutset(animatableValueToBorderImageLengthBox(value, state));
return;
case CSSPropertyBorderImageSlice:
- style->setBorderImageSlices(animatableValueToLengthBox(value, state));
+ style->setBorderImageSlices(animatableValueToLengthBox(value, state, NonNegativeValues));
return;
case CSSPropertyBorderImageSource:
style->setBorderImageSource(toAnimatableImage(value)->toStyleImage());
return;
case CSSPropertyBorderImageWidth:
- style->setBorderImageWidth(animatableValueToLengthBox(value, state));
+ style->setBorderImageWidth(animatableValueToBorderImageLengthBox(value, state));
return;
case CSSPropertyBorderLeftColor:
style->setBorderLeftColor(toAnimatableColor(value)->color());
@@ -129,28 +298,82 @@ void AnimatedStyleBuilder::applyProperty(CSSPropertyID property, StyleResolverSt
style->setBorderTopColor(toAnimatableColor(value)->color());
style->setVisitedLinkBorderTopColor(toAnimatableColor(value)->visitedLinkColor());
return;
+ case CSSPropertyBorderTopLeftRadius:
+ style->setBorderTopLeftRadius(animatableValueToLengthSize(value, state, NonNegativeValues));
+ return;
+ case CSSPropertyBorderTopRightRadius:
+ style->setBorderTopRightRadius(animatableValueToLengthSize(value, state, NonNegativeValues));
+ return;
case CSSPropertyBorderTopWidth:
style->setBorderTopWidth(animatableValueRoundClampTo<unsigned>(value));
return;
case CSSPropertyBottom:
style->setBottom(animatableValueToLength(value, state));
return;
+ case CSSPropertyBoxShadow:
+ case CSSPropertyWebkitBoxShadow:
+ style->setBoxShadow(toAnimatableShadow(value)->shadowList());
+ return;
case CSSPropertyClip:
style->setClip(animatableValueToLengthBox(value, state));
+ style->setHasClip(true);
return;
case CSSPropertyColor:
style->setColor(toAnimatableColor(value)->color());
style->setVisitedLinkColor(toAnimatableColor(value)->visitedLinkColor());
return;
+ case CSSPropertyFillOpacity:
+ // Avoiding a value of 1 forces a layer to be created.
+ style->setFillOpacity(clampTo<float>(toAnimatableDouble(value)->toDouble(), 0, nextafterf(1, 0)));
+ return;
+ case CSSPropertyFill:
+ {
+ const AnimatableSVGPaint* svgPaint = toAnimatableSVGPaint(value);
+ style->accessSVGStyle()->setFillPaint(svgPaint->paintType(), svgPaint->color(), svgPaint->uri());
+ }
+ return;
+ case CSSPropertyFlexGrow:
+ style->setFlexGrow(clampTo<float>(toAnimatableDouble(value)->toDouble(), 0));
+ return;
+ case CSSPropertyFlexShrink:
+ style->setFlexShrink(clampTo<float>(toAnimatableDouble(value)->toDouble(), 0));
+ return;
+ case CSSPropertyFlexBasis:
+ style->setFlexBasis(animatableValueToLength(value, state, NonNegativeValues));
+ return;
+ case CSSPropertyFloodColor:
+ style->setFloodColor(toAnimatableColor(value)->color());
+ return;
+ case CSSPropertyFloodOpacity:
+ style->setFloodOpacity(clampTo<float>(toAnimatableDouble(value)->toDouble(), 0, 1));
+ return;
+ case CSSPropertyFontSize:
+ style->setFontSize(clampTo<float>(toAnimatableDouble(value)->toDouble(), 0));
+ return;
case CSSPropertyHeight:
- style->setHeight(animatableValueToLength(value, state));
+ style->setHeight(animatableValueToLength(value, state, NonNegativeValues));
+ return;
+ case CSSPropertyKerning:
+ style->setKerning(toAnimatableSVGLength(value)->toSVGLength());
return;
case CSSPropertyLeft:
style->setLeft(animatableValueToLength(value, state));
return;
+ case CSSPropertyLightingColor:
+ style->setLightingColor(toAnimatableColor(value)->color());
+ return;
+ case CSSPropertyLineHeight:
+ if (value->isLength())
+ style->setLineHeight(animatableValueToLength(value, state, NonNegativeValues));
+ else
+ style->setLineHeight(Length(clampTo<float>(toAnimatableDouble(value)->toDouble(), 0), Percent));
+ return;
case CSSPropertyListStyleImage:
style->setListStyleImage(toAnimatableImage(value)->toStyleImage());
return;
+ case CSSPropertyLetterSpacing:
+ style->setLetterSpacing(clampTo<float>(toAnimatableDouble(value)->toDouble()));
+ return;
case CSSPropertyMarginBottom:
style->setMarginBottom(animatableValueToLength(value, state));
return;
@@ -164,19 +387,26 @@ void AnimatedStyleBuilder::applyProperty(CSSPropertyID property, StyleResolverSt
style->setMarginTop(animatableValueToLength(value, state));
return;
case CSSPropertyMaxHeight:
- style->setMaxHeight(animatableValueToLength(value, state));
+ style->setMaxHeight(animatableValueToLength(value, state, NonNegativeValues));
return;
case CSSPropertyMaxWidth:
- style->setMaxWidth(animatableValueToLength(value, state));
+ style->setMaxWidth(animatableValueToLength(value, state, NonNegativeValues));
return;
case CSSPropertyMinHeight:
- style->setMinHeight(animatableValueToLength(value, state));
+ style->setMinHeight(animatableValueToLength(value, state, NonNegativeValues));
return;
case CSSPropertyMinWidth:
- style->setMinWidth(animatableValueToLength(value, state));
+ style->setMinWidth(animatableValueToLength(value, state, NonNegativeValues));
+ return;
+ case CSSPropertyObjectPosition:
+ style->setObjectPosition(animatableValueToLengthPoint(value, state));
return;
case CSSPropertyOpacity:
- style->setOpacity(toAnimatableNumber(value)->toDouble());
+ // Avoiding a value of 1 forces a layer to be created.
+ style->setOpacity(clampTo<float>(toAnimatableDouble(value)->toDouble(), 0, nextafterf(1, 0)));
+ return;
+ case CSSPropertyOrphans:
+ style->setOrphans(animatableValueRoundClampTo<unsigned short>(value, 1));
return;
case CSSPropertyOutlineColor:
style->setOutlineColor(toAnimatableColor(value)->color());
@@ -189,36 +419,118 @@ void AnimatedStyleBuilder::applyProperty(CSSPropertyID property, StyleResolverSt
style->setOutlineWidth(animatableValueRoundClampTo<unsigned short>(value));
return;
case CSSPropertyPaddingBottom:
- style->setPaddingBottom(animatableValueToLength(value, state));
+ style->setPaddingBottom(animatableValueToLength(value, state, NonNegativeValues));
return;
case CSSPropertyPaddingLeft:
- style->setPaddingLeft(animatableValueToLength(value, state));
+ style->setPaddingLeft(animatableValueToLength(value, state, NonNegativeValues));
return;
case CSSPropertyPaddingRight:
- style->setPaddingRight(animatableValueToLength(value, state));
+ style->setPaddingRight(animatableValueToLength(value, state, NonNegativeValues));
return;
case CSSPropertyPaddingTop:
- style->setPaddingTop(animatableValueToLength(value, state));
+ style->setPaddingTop(animatableValueToLength(value, state, NonNegativeValues));
return;
case CSSPropertyRight:
style->setRight(animatableValueToLength(value, state));
return;
+ case CSSPropertyStrokeWidth:
+ style->setStrokeWidth(animatableValueToNonNegativeSVGLength(value));
+ return;
+ case CSSPropertyStopColor:
+ style->setStopColor(toAnimatableColor(value)->color());
+ return;
+ case CSSPropertyStopOpacity:
+ style->setStopOpacity(clampTo<float>(toAnimatableDouble(value)->toDouble(), 0, 1));
+ return;
+ case CSSPropertyStrokeDasharray:
+ style->setStrokeDashArray(toAnimatableStrokeDasharrayList(value)->toSVGLengthVector());
+ return;
+ case CSSPropertyStrokeDashoffset:
+ style->setStrokeDashOffset(toAnimatableSVGLength(value)->toSVGLength());
+ return;
+ case CSSPropertyStrokeMiterlimit:
+ style->setStrokeMiterLimit(clampTo<float>(toAnimatableDouble(value)->toDouble(), 1));
+ return;
+ case CSSPropertyStrokeOpacity:
+ style->setStrokeOpacity(clampTo<float>(toAnimatableDouble(value)->toDouble(), 0, 1));
+ return;
+ case CSSPropertyStroke:
+ {
+ const AnimatableSVGPaint* svgPaint = toAnimatableSVGPaint(value);
+ style->accessSVGStyle()->setStrokePaint(svgPaint->paintType(), svgPaint->color(), svgPaint->uri());
+ }
+ return;
case CSSPropertyTextDecorationColor:
style->setTextDecorationColor(toAnimatableColor(value)->color());
style->setVisitedLinkTextDecorationColor(toAnimatableColor(value)->visitedLinkColor());
return;
+ case CSSPropertyTextIndent:
+ style->setTextIndent(animatableValueToLength(value, state));
+ return;
+ case CSSPropertyTextShadow:
+ style->setTextShadow(toAnimatableShadow(value)->shadowList());
+ return;
case CSSPropertyTop:
style->setTop(animatableValueToLength(value, state));
return;
+ case CSSPropertyWebkitBackgroundSize:
+ setOnFillLayers<CSSPropertyWebkitBackgroundSize>(style->accessBackgroundLayers(), value, state);
+ return;
+ case CSSPropertyWebkitBorderHorizontalSpacing:
+ style->setHorizontalBorderSpacing(animatableValueRoundClampTo<unsigned short>(value));
+ return;
+ case CSSPropertyWebkitBorderVerticalSpacing:
+ style->setVerticalBorderSpacing(animatableValueRoundClampTo<unsigned short>(value));
+ return;
+ case CSSPropertyWebkitClipPath:
+ style->setClipPath(toAnimatableClipPathOperation(value)->clipPathOperation());
+ return;
+ case CSSPropertyWebkitColumnCount:
+ style->setColumnCount(animatableValueRoundClampTo<unsigned short>(value, 1));
+ return;
+ case CSSPropertyWebkitColumnGap:
+ style->setColumnGap(clampTo(toAnimatableDouble(value)->toDouble(), 0));
+ return;
case CSSPropertyWebkitColumnRuleColor:
style->setColumnRuleColor(toAnimatableColor(value)->color());
style->setVisitedLinkColumnRuleColor(toAnimatableColor(value)->visitedLinkColor());
return;
+ case CSSPropertyWebkitColumnWidth:
+ style->setColumnWidth(clampTo(toAnimatableDouble(value)->toDouble(), std::numeric_limits<float>::epsilon()));
+ return;
+ case CSSPropertyWebkitColumnRuleWidth:
+ style->setColumnRuleWidth(animatableValueRoundClampTo<unsigned short>(value));
+ return;
+ case CSSPropertyWebkitFilter:
+ style->setFilter(toAnimatableFilterOperations(value)->operations());
+ return;
+ case CSSPropertyWebkitMaskBoxImageOutset:
+ style->setMaskBoxImageOutset(animatableValueToBorderImageLengthBox(value, state));
+ return;
+ case CSSPropertyWebkitMaskBoxImageSlice:
+ style->setMaskBoxImageSlices(animatableValueToLengthBox(toAnimatableLengthBoxAndBool(value)->box(), state, NonNegativeValues));
+ style->setMaskBoxImageSlicesFill(toAnimatableLengthBoxAndBool(value)->flag());
+ return;
case CSSPropertyWebkitMaskBoxImageSource:
style->setMaskBoxImageSource(toAnimatableImage(value)->toStyleImage());
return;
+ case CSSPropertyWebkitMaskBoxImageWidth:
+ style->setMaskBoxImageWidth(animatableValueToBorderImageLengthBox(value, state));
+ return;
case CSSPropertyWebkitMaskImage:
- style->setMaskImage(toAnimatableImage(value)->toStyleImage());
+ setOnFillLayers<CSSPropertyWebkitMaskImage>(style->accessMaskLayers(), value, state);
+ return;
+ case CSSPropertyWebkitMaskPositionX:
+ setOnFillLayers<CSSPropertyWebkitMaskPositionX>(style->accessMaskLayers(), value, state);
+ return;
+ case CSSPropertyWebkitMaskPositionY:
+ setOnFillLayers<CSSPropertyWebkitMaskPositionY>(style->accessMaskLayers(), value, state);
+ return;
+ case CSSPropertyWebkitMaskSize:
+ setOnFillLayers<CSSPropertyWebkitMaskSize>(style->accessMaskLayers(), value, state);
+ return;
+ case CSSPropertyWebkitPerspective:
+ style->setPerspective(clampTo<float>(toAnimatableDouble(value)->toDouble()));
return;
case CSSPropertyWebkitPerspectiveOriginX:
style->setPerspectiveOriginX(animatableValueToLength(value, state));
@@ -226,29 +538,46 @@ void AnimatedStyleBuilder::applyProperty(CSSPropertyID property, StyleResolverSt
case CSSPropertyWebkitPerspectiveOriginY:
style->setPerspectiveOriginY(animatableValueToLength(value, state));
return;
- case CSSPropertyWebkitTextEmphasisColor:
- style->setTextEmphasisColor(toAnimatableColor(value)->color());
- style->setVisitedLinkTextEmphasisColor(toAnimatableColor(value)->visitedLinkColor());
+ case CSSPropertyShapeInside:
+ style->setShapeInside(toAnimatableShapeValue(value)->shapeValue());
+ return;
+ case CSSPropertyShapeOutside:
+ style->setShapeOutside(toAnimatableShapeValue(value)->shapeValue());
+ return;
+ case CSSPropertyShapeMargin:
+ style->setShapeMargin(animatableValueToLength(value, state, NonNegativeValues));
return;
- case CSSPropertyWebkitTextFillColor:
- style->setTextFillColor(toAnimatableColor(value)->color());
- style->setVisitedLinkTextFillColor(toAnimatableColor(value)->visitedLinkColor());
+ case CSSPropertyShapeImageThreshold:
+ style->setShapeImageThreshold(clampTo<float>(toAnimatableDouble(value)->toDouble(), 0, 1));
return;
case CSSPropertyWebkitTextStrokeColor:
style->setTextStrokeColor(toAnimatableColor(value)->color());
style->setVisitedLinkTextStrokeColor(toAnimatableColor(value)->visitedLinkColor());
return;
- case CSSPropertyWebkitTransform:
- style->setTransform(toAnimatableTransform(value)->transformOperations());
+ case CSSPropertyWebkitTransform: {
+ const TransformOperations& operations = toAnimatableTransform(value)->transformOperations();
+ // FIXME: Using identity matrix here when the transform list is empty
+ // forces a layer to be created in the presence of a transform animation.
+ style->setTransform(operations.size() ? operations : TransformOperations(true));
return;
+ }
case CSSPropertyWebkitTransformOriginX:
style->setTransformOriginX(animatableValueToLength(value, state));
return;
case CSSPropertyWebkitTransformOriginY:
style->setTransformOriginY(animatableValueToLength(value, state));
return;
+ case CSSPropertyWebkitTransformOriginZ:
+ style->setTransformOriginZ(toAnimatableDouble(value)->toDouble());
+ return;
+ case CSSPropertyWidows:
+ style->setWidows(animatableValueRoundClampTo<unsigned short>(value, 1));
+ return;
case CSSPropertyWidth:
- style->setWidth(animatableValueToLength(value, state));
+ style->setWidth(animatableValueToLength(value, state, NonNegativeValues));
+ return;
+ case CSSPropertyWordSpacing:
+ style->setWordSpacing(clampTo<float>(toAnimatableDouble(value)->toDouble()));
return;
case CSSPropertyVisibility:
style->setVisibility(toAnimatableVisibility(value)->visibility());
@@ -256,8 +585,11 @@ void AnimatedStyleBuilder::applyProperty(CSSPropertyID property, StyleResolverSt
case CSSPropertyZIndex:
style->setZIndex(animatableValueRoundClampTo<int>(value));
return;
+ case CSSPropertyZoom:
+ style->setZoom(clampTo<float>(toAnimatableDouble(value)->toDouble(), std::numeric_limits<float>::denorm_min()));
+ return;
default:
- RELEASE_ASSERT_WITH_MESSAGE(!CSSAnimations::isAnimatableProperty(property), "Web Animations not yet implemented: Unable to apply AnimatableValue to RenderStyle: %s", getPropertyNameString(property).utf8().data());
+ ASSERT_WITH_MESSAGE(!CSSAnimations::isAnimatableProperty(property), "Web Animations not yet implemented: Unable to apply AnimatableValue to RenderStyle: %s", getPropertyNameString(property).utf8().data());
ASSERT_NOT_REACHED();
}
}
diff --git a/chromium/third_party/WebKit/Source/core/css/resolver/CSSToStyleMap.cpp b/chromium/third_party/WebKit/Source/core/css/resolver/CSSToStyleMap.cpp
new file mode 100644
index 00000000000..31303805178
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/css/resolver/CSSToStyleMap.cpp
@@ -0,0 +1,670 @@
+/*
+ * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
+ * (C) 2004-2005 Allan Sandfeld Jensen (kde@carewolf.com)
+ * Copyright (C) 2006, 2007 Nicholas Shanks (webkit@nickshanks.com)
+ * Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 Apple Inc. All rights reserved.
+ * Copyright (C) 2007 Alexey Proskuryakov <ap@webkit.org>
+ * Copyright (C) 2007, 2008 Eric Seidel <eric@webkit.org>
+ * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
+ * Copyright (c) 2011, Code Aurora Forum. All rights reserved.
+ * Copyright (C) Research In Motion Limited 2011. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#include "config.h"
+#include "core/css/resolver/CSSToStyleMap.h"
+
+#include "CSSValueKeywords.h"
+#include "core/css/CSSBorderImageSliceValue.h"
+#include "core/css/CSSPrimitiveValue.h"
+#include "core/css/CSSPrimitiveValueMappings.h"
+#include "core/css/CSSTimingFunctionValue.h"
+#include "core/css/Pair.h"
+#include "core/css/Rect.h"
+#include "core/css/resolver/StyleResolverState.h"
+#include "core/platform/animation/CSSAnimationData.h"
+#include "core/rendering/style/BorderImageLengthBox.h"
+#include "core/rendering/style/FillLayer.h"
+
+namespace WebCore {
+
+const CSSToLengthConversionData& CSSToStyleMap::cssToLengthConversionData() const
+{
+ return m_state.cssToLengthConversionData();
+}
+
+bool CSSToStyleMap::useSVGZoomRules() const
+{
+ return m_state.useSVGZoomRules();
+}
+
+PassRefPtr<StyleImage> CSSToStyleMap::styleImage(CSSPropertyID propertyId, CSSValue* value)
+{
+ return m_elementStyleResources.styleImage(m_state.document().textLinkColors(), m_state.style()->color(), propertyId, value);
+}
+
+void CSSToStyleMap::mapFillAttachment(CSSPropertyID, FillLayer* layer, CSSValue* value) const
+{
+ if (value->isInitialValue()) {
+ layer->setAttachment(FillLayer::initialFillAttachment(layer->type()));
+ return;
+ }
+
+ if (!value->isPrimitiveValue())
+ return;
+
+ CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
+ switch (primitiveValue->getValueID()) {
+ case CSSValueFixed:
+ layer->setAttachment(FixedBackgroundAttachment);
+ break;
+ case CSSValueScroll:
+ layer->setAttachment(ScrollBackgroundAttachment);
+ break;
+ case CSSValueLocal:
+ layer->setAttachment(LocalBackgroundAttachment);
+ break;
+ default:
+ return;
+ }
+}
+
+void CSSToStyleMap::mapFillClip(CSSPropertyID, FillLayer* layer, CSSValue* value) const
+{
+ if (value->isInitialValue()) {
+ layer->setClip(FillLayer::initialFillClip(layer->type()));
+ return;
+ }
+
+ if (!value->isPrimitiveValue())
+ return;
+
+ CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
+ layer->setClip(*primitiveValue);
+}
+
+void CSSToStyleMap::mapFillComposite(CSSPropertyID, FillLayer* layer, CSSValue* value) const
+{
+ if (value->isInitialValue()) {
+ layer->setComposite(FillLayer::initialFillComposite(layer->type()));
+ return;
+ }
+
+ if (!value->isPrimitiveValue())
+ return;
+
+ CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
+ layer->setComposite(*primitiveValue);
+}
+
+void CSSToStyleMap::mapFillBlendMode(CSSPropertyID, FillLayer* layer, CSSValue* value) const
+{
+ if (value->isInitialValue()) {
+ layer->setBlendMode(FillLayer::initialFillBlendMode(layer->type()));
+ return;
+ }
+
+ if (!value->isPrimitiveValue())
+ return;
+
+ CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
+ layer->setBlendMode(*primitiveValue);
+}
+
+void CSSToStyleMap::mapFillOrigin(CSSPropertyID, FillLayer* layer, CSSValue* value) const
+{
+ if (value->isInitialValue()) {
+ layer->setOrigin(FillLayer::initialFillOrigin(layer->type()));
+ return;
+ }
+
+ if (!value->isPrimitiveValue())
+ return;
+
+ CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
+ layer->setOrigin(*primitiveValue);
+}
+
+
+void CSSToStyleMap::mapFillImage(CSSPropertyID property, FillLayer* layer, CSSValue* value)
+{
+ if (value->isInitialValue()) {
+ layer->setImage(FillLayer::initialFillImage(layer->type()));
+ return;
+ }
+
+ layer->setImage(styleImage(property, value));
+}
+
+void CSSToStyleMap::mapFillRepeatX(CSSPropertyID, FillLayer* layer, CSSValue* value) const
+{
+ if (value->isInitialValue()) {
+ layer->setRepeatX(FillLayer::initialFillRepeatX(layer->type()));
+ return;
+ }
+
+ if (!value->isPrimitiveValue())
+ return;
+
+ CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
+ layer->setRepeatX(*primitiveValue);
+}
+
+void CSSToStyleMap::mapFillRepeatY(CSSPropertyID, FillLayer* layer, CSSValue* value) const
+{
+ if (value->isInitialValue()) {
+ layer->setRepeatY(FillLayer::initialFillRepeatY(layer->type()));
+ return;
+ }
+
+ if (!value->isPrimitiveValue())
+ return;
+
+ CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
+ layer->setRepeatY(*primitiveValue);
+}
+
+void CSSToStyleMap::mapFillSize(CSSPropertyID, FillLayer* layer, CSSValue* value) const
+{
+ if (!value->isPrimitiveValue()) {
+ layer->setSizeType(SizeNone);
+ return;
+ }
+
+ CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
+ if (primitiveValue->getValueID() == CSSValueContain)
+ layer->setSizeType(Contain);
+ else if (primitiveValue->getValueID() == CSSValueCover)
+ layer->setSizeType(Cover);
+ else
+ layer->setSizeType(SizeLength);
+
+ LengthSize b = FillLayer::initialFillSizeLength(layer->type());
+
+ if (value->isInitialValue() || primitiveValue->getValueID() == CSSValueContain || primitiveValue->getValueID() == CSSValueCover) {
+ layer->setSizeLength(b);
+ return;
+ }
+
+ Length firstLength;
+ Length secondLength;
+
+ if (Pair* pair = primitiveValue->getPairValue()) {
+ firstLength = pair->first()->convertToLength<AnyConversion>(cssToLengthConversionData());
+ secondLength = pair->second()->convertToLength<AnyConversion>(cssToLengthConversionData());
+ } else {
+ firstLength = primitiveValue->convertToLength<AnyConversion>(cssToLengthConversionData());
+ secondLength = Length();
+ }
+
+ if (firstLength.isUndefined() || secondLength.isUndefined())
+ return;
+
+ b.setWidth(firstLength);
+ b.setHeight(secondLength);
+ layer->setSizeLength(b);
+}
+
+void CSSToStyleMap::mapFillXPosition(CSSPropertyID propertyID, FillLayer* layer, CSSValue* value) const
+{
+ if (value->isInitialValue()) {
+ layer->setXPosition(FillLayer::initialFillXPosition(layer->type()));
+ return;
+ }
+
+ if (!value->isPrimitiveValue())
+ return;
+
+ CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
+ Pair* pair = primitiveValue->getPairValue();
+ if (pair) {
+ ASSERT_UNUSED(propertyID, propertyID == CSSPropertyBackgroundPositionX || propertyID == CSSPropertyWebkitMaskPositionX);
+ primitiveValue = pair->second();
+ }
+
+ Length length = primitiveValue->convertToLength<FixedConversion | PercentConversion>(cssToLengthConversionData());
+ ASSERT(!length.isUndefined());
+
+ layer->setXPosition(length);
+ if (pair)
+ layer->setBackgroundXOrigin(*(pair->first()));
+}
+
+void CSSToStyleMap::mapFillYPosition(CSSPropertyID propertyID, FillLayer* layer, CSSValue* value) const
+{
+ if (value->isInitialValue()) {
+ layer->setYPosition(FillLayer::initialFillYPosition(layer->type()));
+ return;
+ }
+
+ if (!value->isPrimitiveValue())
+ return;
+
+ CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
+ Pair* pair = primitiveValue->getPairValue();
+ if (pair) {
+ ASSERT_UNUSED(propertyID, propertyID == CSSPropertyBackgroundPositionY || propertyID == CSSPropertyWebkitMaskPositionY);
+ primitiveValue = pair->second();
+ }
+
+ Length length = primitiveValue->convertToLength<FixedConversion | PercentConversion>(cssToLengthConversionData());
+ ASSERT(!length.isUndefined());
+
+ layer->setYPosition(length);
+ if (pair)
+ layer->setBackgroundYOrigin(*(pair->first()));
+}
+
+void CSSToStyleMap::mapFillMaskSourceType(CSSPropertyID, FillLayer* layer, CSSValue* value)
+{
+ EMaskSourceType type = FillLayer::initialFillMaskSourceType(layer->type());
+ if (value->isInitialValue()) {
+ layer->setMaskSourceType(type);
+ return;
+ }
+
+ if (!value->isPrimitiveValue())
+ return;
+
+ switch (toCSSPrimitiveValue(value)->getValueID()) {
+ case CSSValueAlpha:
+ type = MaskAlpha;
+ break;
+ case CSSValueLuminance:
+ type = MaskLuminance;
+ break;
+ case CSSValueAuto:
+ break;
+ default:
+ ASSERT_NOT_REACHED();
+ }
+
+ layer->setMaskSourceType(type);
+}
+
+void CSSToStyleMap::mapAnimationDelay(CSSAnimationData* animation, CSSValue* value) const
+{
+ if (value->isInitialValue()) {
+ animation->setDelay(CSSAnimationData::initialAnimationDelay());
+ return;
+ }
+
+ if (!value->isPrimitiveValue())
+ return;
+
+ animation->setDelay(toCSSPrimitiveValue(value)->computeTime<double, CSSPrimitiveValue::Seconds>());
+}
+
+void CSSToStyleMap::mapAnimationDirection(CSSAnimationData* layer, CSSValue* value) const
+{
+ if (value->isInitialValue()) {
+ layer->setDirection(CSSAnimationData::initialAnimationDirection());
+ return;
+ }
+
+ if (!value->isPrimitiveValue())
+ return;
+
+ switch (toCSSPrimitiveValue(value)->getValueID()) {
+ case CSSValueNormal:
+ layer->setDirection(CSSAnimationData::AnimationDirectionNormal);
+ break;
+ case CSSValueAlternate:
+ layer->setDirection(CSSAnimationData::AnimationDirectionAlternate);
+ break;
+ case CSSValueReverse:
+ layer->setDirection(CSSAnimationData::AnimationDirectionReverse);
+ break;
+ case CSSValueAlternateReverse:
+ layer->setDirection(CSSAnimationData::AnimationDirectionAlternateReverse);
+ break;
+ default:
+ break;
+ }
+}
+
+void CSSToStyleMap::mapAnimationDuration(CSSAnimationData* animation, CSSValue* value) const
+{
+ if (value->isInitialValue()) {
+ animation->setDuration(CSSAnimationData::initialAnimationDuration());
+ return;
+ }
+
+ if (!value->isPrimitiveValue())
+ return;
+
+ CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
+ animation->setDuration(primitiveValue->computeTime<double, CSSPrimitiveValue::Seconds>());
+}
+
+void CSSToStyleMap::mapAnimationFillMode(CSSAnimationData* layer, CSSValue* value) const
+{
+ if (value->isInitialValue()) {
+ layer->setFillMode(CSSAnimationData::initialAnimationFillMode());
+ return;
+ }
+
+ if (!value->isPrimitiveValue())
+ return;
+
+ CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
+ switch (primitiveValue->getValueID()) {
+ case CSSValueNone:
+ layer->setFillMode(AnimationFillModeNone);
+ break;
+ case CSSValueForwards:
+ layer->setFillMode(AnimationFillModeForwards);
+ break;
+ case CSSValueBackwards:
+ layer->setFillMode(AnimationFillModeBackwards);
+ break;
+ case CSSValueBoth:
+ layer->setFillMode(AnimationFillModeBoth);
+ break;
+ default:
+ break;
+ }
+}
+
+void CSSToStyleMap::mapAnimationIterationCount(CSSAnimationData* animation, CSSValue* value) const
+{
+ if (value->isInitialValue()) {
+ animation->setIterationCount(CSSAnimationData::initialAnimationIterationCount());
+ return;
+ }
+
+ if (!value->isPrimitiveValue())
+ return;
+
+ CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
+ if (primitiveValue->getValueID() == CSSValueInfinite)
+ animation->setIterationCount(CSSAnimationData::IterationCountInfinite);
+ else
+ animation->setIterationCount(primitiveValue->getFloatValue());
+}
+
+void CSSToStyleMap::mapAnimationName(CSSAnimationData* layer, CSSValue* value) const
+{
+ if (value->isInitialValue()) {
+ layer->setName(CSSAnimationData::initialAnimationName());
+ return;
+ }
+
+ if (!value->isPrimitiveValue())
+ return;
+
+ CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
+ if (primitiveValue->getValueID() == CSSValueNone)
+ layer->setIsNoneAnimation(true);
+ else
+ layer->setName(AtomicString(primitiveValue->getStringValue()));
+}
+
+void CSSToStyleMap::mapAnimationPlayState(CSSAnimationData* layer, CSSValue* value) const
+{
+ if (value->isInitialValue()) {
+ layer->setPlayState(CSSAnimationData::initialAnimationPlayState());
+ return;
+ }
+
+ if (!value->isPrimitiveValue())
+ return;
+
+ CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
+ EAnimPlayState playState = (primitiveValue->getValueID() == CSSValuePaused) ? AnimPlayStatePaused : AnimPlayStatePlaying;
+ layer->setPlayState(playState);
+}
+
+void CSSToStyleMap::mapAnimationProperty(CSSAnimationData* animation, CSSValue* value) const
+{
+ if (value->isInitialValue()) {
+ animation->setAnimationMode(CSSAnimationData::AnimateAll);
+ animation->setProperty(CSSPropertyInvalid);
+ return;
+ }
+
+ if (!value->isPrimitiveValue())
+ return;
+
+ CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
+ if (primitiveValue->getValueID() == CSSValueAll) {
+ animation->setAnimationMode(CSSAnimationData::AnimateAll);
+ animation->setProperty(CSSPropertyInvalid);
+ } else if (primitiveValue->getValueID() == CSSValueNone) {
+ animation->setAnimationMode(CSSAnimationData::AnimateNone);
+ animation->setProperty(CSSPropertyInvalid);
+ } else {
+ animation->setAnimationMode(CSSAnimationData::AnimateSingleProperty);
+ animation->setProperty(primitiveValue->getPropertyID());
+ }
+}
+
+void CSSToStyleMap::mapAnimationTimingFunction(CSSAnimationData* animation, CSSValue* value) const
+{
+ if (value->isInitialValue()) {
+ animation->setTimingFunction(CSSAnimationData::initialAnimationTimingFunction());
+ return;
+ }
+
+ if (value->isPrimitiveValue()) {
+ CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
+ switch (primitiveValue->getValueID()) {
+ case CSSValueLinear:
+ animation->setTimingFunction(LinearTimingFunction::create());
+ break;
+ case CSSValueEase:
+ animation->setTimingFunction(CubicBezierTimingFunction::preset(CubicBezierTimingFunction::Ease));
+ break;
+ case CSSValueEaseIn:
+ animation->setTimingFunction(CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseIn));
+ break;
+ case CSSValueEaseOut:
+ animation->setTimingFunction(CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseOut));
+ break;
+ case CSSValueEaseInOut:
+ animation->setTimingFunction(CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseInOut));
+ break;
+ case CSSValueStepStart:
+ animation->setTimingFunction(StepsTimingFunction::preset(StepsTimingFunction::Start));
+ break;
+ case CSSValueStepEnd:
+ animation->setTimingFunction(StepsTimingFunction::preset(StepsTimingFunction::End));
+ break;
+ default:
+ break;
+ }
+ return;
+ }
+
+ if (value->isCubicBezierTimingFunctionValue()) {
+ CSSCubicBezierTimingFunctionValue* cubicTimingFunction = toCSSCubicBezierTimingFunctionValue(value);
+ animation->setTimingFunction(CubicBezierTimingFunction::create(cubicTimingFunction->x1(), cubicTimingFunction->y1(), cubicTimingFunction->x2(), cubicTimingFunction->y2()));
+ } else if (value->isStepsTimingFunctionValue()) {
+ CSSStepsTimingFunctionValue* stepsTimingFunction = toCSSStepsTimingFunctionValue(value);
+ animation->setTimingFunction(StepsTimingFunction::create(stepsTimingFunction->numberOfSteps(), stepsTimingFunction->stepAtStart()));
+ }
+}
+
+void CSSToStyleMap::mapNinePieceImage(RenderStyle* mutableStyle, CSSPropertyID property, CSSValue* value, NinePieceImage& image)
+{
+ // If we're not a value list, then we are "none" and don't need to alter the empty image at all.
+ if (!value || !value->isValueList())
+ return;
+
+ // Retrieve the border image value.
+ CSSValueList* borderImage = toCSSValueList(value);
+
+ // Set the image (this kicks off the load).
+ CSSPropertyID imageProperty;
+ if (property == CSSPropertyWebkitBorderImage)
+ imageProperty = CSSPropertyBorderImageSource;
+ else if (property == CSSPropertyWebkitMaskBoxImage)
+ imageProperty = CSSPropertyWebkitMaskBoxImageSource;
+ else
+ imageProperty = property;
+
+ for (unsigned i = 0 ; i < borderImage->length() ; ++i) {
+ CSSValue* current = borderImage->item(i);
+
+ if (current->isImageValue() || current->isImageGeneratorValue() || current->isImageSetValue())
+ image.setImage(styleImage(imageProperty, current));
+ else if (current->isBorderImageSliceValue())
+ mapNinePieceImageSlice(current, image);
+ else if (current->isValueList()) {
+ CSSValueList* slashList = toCSSValueList(current);
+ // Map in the image slices.
+ if (slashList->item(0) && slashList->item(0)->isBorderImageSliceValue())
+ mapNinePieceImageSlice(slashList->item(0), image);
+
+ // Map in the border slices.
+ if (slashList->item(1))
+ image.setBorderSlices(mapNinePieceImageQuad(slashList->item(1)));
+
+ // Map in the outset.
+ if (slashList->item(2))
+ image.setOutset(mapNinePieceImageQuad(slashList->item(2)));
+ } else if (current->isPrimitiveValue()) {
+ // Set the appropriate rules for stretch/round/repeat of the slices.
+ mapNinePieceImageRepeat(current, image);
+ }
+ }
+
+ if (property == CSSPropertyWebkitBorderImage) {
+ // We have to preserve the legacy behavior of -webkit-border-image and make the border slices
+ // also set the border widths. We don't need to worry about percentages, since we don't even support
+ // those on real borders yet.
+ if (image.borderSlices().top().isLength() && image.borderSlices().top().length().isFixed())
+ mutableStyle->setBorderTopWidth(image.borderSlices().top().length().value());
+ if (image.borderSlices().right().isLength() && image.borderSlices().right().length().isFixed())
+ mutableStyle->setBorderRightWidth(image.borderSlices().right().length().value());
+ if (image.borderSlices().bottom().isLength() && image.borderSlices().bottom().length().isFixed())
+ mutableStyle->setBorderBottomWidth(image.borderSlices().bottom().length().value());
+ if (image.borderSlices().left().isLength() && image.borderSlices().left().length().isFixed())
+ mutableStyle->setBorderLeftWidth(image.borderSlices().left().length().value());
+ }
+}
+
+void CSSToStyleMap::mapNinePieceImageSlice(CSSValue* value, NinePieceImage& image) const
+{
+ if (!value || !value->isBorderImageSliceValue())
+ return;
+
+ // Retrieve the border image value.
+ CSSBorderImageSliceValue* borderImageSlice = toCSSBorderImageSliceValue(value);
+
+ // Set up a length box to represent our image slices.
+ LengthBox box;
+ Quad* slices = borderImageSlice->slices();
+ if (slices->top()->isPercentage())
+ box.m_top = Length(slices->top()->getDoubleValue(), Percent);
+ else
+ box.m_top = Length(slices->top()->getIntValue(CSSPrimitiveValue::CSS_NUMBER), Fixed);
+ if (slices->bottom()->isPercentage())
+ box.m_bottom = Length(slices->bottom()->getDoubleValue(), Percent);
+ else
+ box.m_bottom = Length((int)slices->bottom()->getFloatValue(CSSPrimitiveValue::CSS_NUMBER), Fixed);
+ if (slices->left()->isPercentage())
+ box.m_left = Length(slices->left()->getDoubleValue(), Percent);
+ else
+ box.m_left = Length(slices->left()->getIntValue(CSSPrimitiveValue::CSS_NUMBER), Fixed);
+ if (slices->right()->isPercentage())
+ box.m_right = Length(slices->right()->getDoubleValue(), Percent);
+ else
+ box.m_right = Length(slices->right()->getIntValue(CSSPrimitiveValue::CSS_NUMBER), Fixed);
+ image.setImageSlices(box);
+
+ // Set our fill mode.
+ image.setFill(borderImageSlice->m_fill);
+}
+
+static BorderImageLength toBorderImageLength(CSSPrimitiveValue& value, const CSSToLengthConversionData& conversionData)
+{
+ if (value.isNumber())
+ return value.getDoubleValue();
+ if (value.isPercentage())
+ return Length(value.getDoubleValue(CSSPrimitiveValue::CSS_PERCENTAGE), Percent);
+ if (value.getValueID() != CSSValueAuto)
+ return value.computeLength<Length>(conversionData);
+ return Length(Auto);
+}
+
+BorderImageLengthBox CSSToStyleMap::mapNinePieceImageQuad(CSSValue* value) const
+{
+ if (!value || !value->isPrimitiveValue())
+ return BorderImageLengthBox(Length(Auto));
+
+ float zoom = useSVGZoomRules() ? 1.0f : cssToLengthConversionData().zoom();
+ Quad* slices = toCSSPrimitiveValue(value)->getQuadValue();
+
+ // Set up a border image length box to represent our image slices.
+ const CSSToLengthConversionData& conversionData = cssToLengthConversionData().copyWithAdjustedZoom(zoom);
+ return BorderImageLengthBox(
+ toBorderImageLength(*slices->top(), conversionData),
+ toBorderImageLength(*slices->right(), conversionData),
+ toBorderImageLength(*slices->bottom(), conversionData),
+ toBorderImageLength(*slices->left(), conversionData));
+}
+
+void CSSToStyleMap::mapNinePieceImageRepeat(CSSValue* value, NinePieceImage& image) const
+{
+ if (!value || !value->isPrimitiveValue())
+ return;
+
+ CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
+ Pair* pair = primitiveValue->getPairValue();
+ if (!pair || !pair->first() || !pair->second())
+ return;
+
+ CSSValueID firstIdentifier = pair->first()->getValueID();
+ CSSValueID secondIdentifier = pair->second()->getValueID();
+
+ ENinePieceImageRule horizontalRule;
+ switch (firstIdentifier) {
+ case CSSValueStretch:
+ horizontalRule = StretchImageRule;
+ break;
+ case CSSValueRound:
+ horizontalRule = RoundImageRule;
+ break;
+ case CSSValueSpace:
+ horizontalRule = SpaceImageRule;
+ break;
+ default: // CSSValueRepeat
+ horizontalRule = RepeatImageRule;
+ break;
+ }
+ image.setHorizontalRule(horizontalRule);
+
+ ENinePieceImageRule verticalRule;
+ switch (secondIdentifier) {
+ case CSSValueStretch:
+ verticalRule = StretchImageRule;
+ break;
+ case CSSValueRound:
+ verticalRule = RoundImageRule;
+ break;
+ case CSSValueSpace:
+ verticalRule = SpaceImageRule;
+ break;
+ default: // CSSValueRepeat
+ verticalRule = RepeatImageRule;
+ break;
+ }
+ image.setVerticalRule(verticalRule);
+}
+
+};
diff --git a/chromium/third_party/WebKit/Source/core/css/resolver/CSSToStyleMap.h b/chromium/third_party/WebKit/Source/core/css/resolver/CSSToStyleMap.h
new file mode 100644
index 00000000000..b994b6f0a78
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/css/resolver/CSSToStyleMap.h
@@ -0,0 +1,92 @@
+/*
+ * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
+ * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
+ * Copyright (C) 2012 Google Inc. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#ifndef CSSToStyleMap_h
+#define CSSToStyleMap_h
+
+#include "CSSPropertyNames.h"
+#include "core/css/resolver/ElementStyleResources.h"
+#include "wtf/Noncopyable.h"
+
+namespace WebCore {
+
+class FillLayer;
+class CSSAnimationData;
+class CSSToLengthConversionData;
+class CSSValue;
+class RenderStyle;
+class StyleImage;
+class StyleResolverState;
+class NinePieceImage;
+class BorderImageLengthBox;
+
+// CSSToStyleMap is a short-lived helper object which
+// given the current StyleResolverState can map
+// CSSValue objects into their RenderStyle equivalents.
+
+class CSSToStyleMap {
+ WTF_MAKE_NONCOPYABLE(CSSToStyleMap);
+public:
+ CSSToStyleMap(const StyleResolverState& state, ElementStyleResources& elementStyleResources) : m_state(state), m_elementStyleResources(elementStyleResources) { }
+
+ void mapFillAttachment(CSSPropertyID, FillLayer*, CSSValue*) const;
+ void mapFillClip(CSSPropertyID, FillLayer*, CSSValue*) const;
+ void mapFillComposite(CSSPropertyID, FillLayer*, CSSValue*) const;
+ void mapFillBlendMode(CSSPropertyID, FillLayer*, CSSValue*) const;
+ void mapFillOrigin(CSSPropertyID, FillLayer*, CSSValue*) const;
+ void mapFillImage(CSSPropertyID, FillLayer*, CSSValue*);
+ void mapFillRepeatX(CSSPropertyID, FillLayer*, CSSValue*) const;
+ void mapFillRepeatY(CSSPropertyID, FillLayer*, CSSValue*) const;
+ void mapFillSize(CSSPropertyID, FillLayer*, CSSValue*) const;
+ void mapFillXPosition(CSSPropertyID, FillLayer*, CSSValue*) const;
+ void mapFillYPosition(CSSPropertyID, FillLayer*, CSSValue*) const;
+ void mapFillMaskSourceType(CSSPropertyID, FillLayer*, CSSValue*);
+
+ void mapAnimationDelay(CSSAnimationData*, CSSValue*) const;
+ void mapAnimationDirection(CSSAnimationData*, CSSValue*) const;
+ void mapAnimationDuration(CSSAnimationData*, CSSValue*) const;
+ void mapAnimationFillMode(CSSAnimationData*, CSSValue*) const;
+ void mapAnimationIterationCount(CSSAnimationData*, CSSValue*) const;
+ void mapAnimationName(CSSAnimationData*, CSSValue*) const;
+ void mapAnimationPlayState(CSSAnimationData*, CSSValue*) const;
+ void mapAnimationProperty(CSSAnimationData*, CSSValue*) const;
+ void mapAnimationTimingFunction(CSSAnimationData*, CSSValue*) const;
+
+ void mapNinePieceImage(RenderStyle* mutableStyle, CSSPropertyID, CSSValue*, NinePieceImage&);
+ void mapNinePieceImageSlice(CSSValue*, NinePieceImage&) const;
+ BorderImageLengthBox mapNinePieceImageQuad(CSSValue*) const;
+ void mapNinePieceImageRepeat(CSSValue*, NinePieceImage&) const;
+
+private:
+ const CSSToLengthConversionData& cssToLengthConversionData() const;
+ bool useSVGZoomRules() const;
+
+ PassRefPtr<StyleImage> styleImage(CSSPropertyID, CSSValue*);
+
+ // FIXME: Consider passing a StyleResolverState (or ElementResolveState)
+ // as an argument instead of caching it on this object.
+ const StyleResolverState& m_state;
+ ElementStyleResources& m_elementStyleResources;
+};
+
+}
+
+#endif
diff --git a/chromium/third_party/WebKit/Source/core/css/resolver/ElementResolveContext.cpp b/chromium/third_party/WebKit/Source/core/css/resolver/ElementResolveContext.cpp
index 00f93157bcb..75a1ab10f17 100644
--- a/chromium/third_party/WebKit/Source/core/css/resolver/ElementResolveContext.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/resolver/ElementResolveContext.cpp
@@ -29,19 +29,20 @@
namespace WebCore {
-ElementResolveContext::ElementResolveContext(Element* element)
- : m_element(element)
- , m_elementLinkState(element ? element->document().visitedLinkState()->determineLinkState(element) : NotInsideLink)
+ElementResolveContext::ElementResolveContext(Element& element)
+ : m_element(&element)
+ , m_elementLinkState(element.document().visitedLinkState().determineLinkState(element))
, m_distributedToInsertionPoint(false)
, m_resetStyleInheritance(false)
{
NodeRenderingTraversal::ParentDetails parentDetails;
- m_parentNode = NodeRenderingTraversal::parent(element, &parentDetails);
+ m_parentNode = NodeRenderingTraversal::parent(&element, &parentDetails);
m_distributedToInsertionPoint = parentDetails.insertionPoint();
m_resetStyleInheritance = parentDetails.resetStyleInheritance();
- Node* documentElement = document().documentElement();
- RenderStyle* documentStyle = document().renderStyle();
+ const Document& document = element.document();
+ Node* documentElement = document.documentElement();
+ RenderStyle* documentStyle = document.renderStyle();
m_rootElementStyle = documentElement && element != documentElement ? documentElement->renderStyle() : documentStyle;
if (!m_rootElementStyle)
m_rootElementStyle = documentStyle;
diff --git a/chromium/third_party/WebKit/Source/core/css/resolver/ElementResolveContext.h b/chromium/third_party/WebKit/Source/core/css/resolver/ElementResolveContext.h
index ebbe1cfe50f..f255e897425 100644
--- a/chromium/third_party/WebKit/Source/core/css/resolver/ElementResolveContext.h
+++ b/chromium/third_party/WebKit/Source/core/css/resolver/ElementResolveContext.h
@@ -45,14 +45,11 @@ public:
{
}
- explicit ElementResolveContext(Element*);
-
- Document& document() const { return m_element->document(); }
- bool isDocumentElement() const { return m_element && m_element == m_element->document().documentElement(); }
+ explicit ElementResolveContext(Element&);
Element* element() const { return m_element; }
const ContainerNode* parentNode() const { return m_parentNode; }
- RenderStyle* rootElementStyle() const { return m_rootElementStyle; }
+ const RenderStyle* rootElementStyle() const { return m_rootElementStyle; }
EInsideLink elementLinkState() const { return m_elementLinkState; }
bool distributedToInsertionPoint() const { return m_distributedToInsertionPoint; }
bool resetStyleInheritance() const { return m_resetStyleInheritance; }
diff --git a/chromium/third_party/WebKit/Source/core/css/resolver/ElementStyleResources.cpp b/chromium/third_party/WebKit/Source/core/css/resolver/ElementStyleResources.cpp
index f99919aeb27..d8b081743c9 100644
--- a/chromium/third_party/WebKit/Source/core/css/resolver/ElementStyleResources.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/resolver/ElementStyleResources.cpp
@@ -25,15 +25,15 @@
#include "core/css/CSSGradientValue.h"
#include "core/css/CSSSVGDocumentValue.h"
-#include "core/platform/graphics/filters/FilterOperation.h"
#include "core/rendering/style/StyleGeneratedImage.h"
#include "core/rendering/style/StyleImage.h"
#include "core/rendering/style/StylePendingImage.h"
+#include "platform/graphics/filters/FilterOperation.h"
namespace WebCore {
ElementStyleResources::ElementStyleResources()
- : m_hasPendingShaders(false)
+ : m_hasNewCustomFilterProgram(false)
, m_deviceScaleFactor(1)
{
}
@@ -45,15 +45,15 @@ PassRefPtr<StyleImage> ElementStyleResources::styleImage(const TextLinkColors& t
if (value->isImageGeneratorValue()) {
if (value->isGradientValue())
- return generatedOrPendingFromValue(property, static_cast<CSSGradientValue*>(value)->gradientWithStylesResolved(textLinkColors, currentColor).get());
- return generatedOrPendingFromValue(property, static_cast<CSSImageGeneratorValue*>(value));
+ return generatedOrPendingFromValue(property, toCSSGradientValue(value)->gradientWithStylesResolved(textLinkColors, currentColor).get());
+ return generatedOrPendingFromValue(property, toCSSImageGeneratorValue(value));
}
if (value->isImageSetValue())
- return setOrPendingFromValue(property, static_cast<CSSImageSetValue*>(value));
+ return setOrPendingFromValue(property, toCSSImageSetValue(value));
if (value->isCursorImageValue())
- return cursorOrPendingFromValue(property, static_cast<CSSCursorImageValue*>(value));
+ return cursorOrPendingFromValue(property, toCSSCursorImageValue(value));
return 0;
}
@@ -96,12 +96,4 @@ void ElementStyleResources::addPendingSVGDocument(FilterOperation* filterOperati
m_pendingSVGDocuments.set(filterOperation, cssSVGDocumentValue);
}
-void ElementStyleResources::clear()
-{
- m_pendingImageProperties.clear();
- m_pendingSVGDocuments.clear();
- m_hasPendingShaders = false;
- m_deviceScaleFactor = 1;
-}
-
}
diff --git a/chromium/third_party/WebKit/Source/core/css/resolver/ElementStyleResources.h b/chromium/third_party/WebKit/Source/core/css/resolver/ElementStyleResources.h
index 08aaede6042..354b022fe28 100644
--- a/chromium/third_party/WebKit/Source/core/css/resolver/ElementStyleResources.h
+++ b/chromium/third_party/WebKit/Source/core/css/resolver/ElementStyleResources.h
@@ -24,7 +24,7 @@
#define ElementStyleResources_h
#include "CSSPropertyNames.h"
-#include "core/platform/graphics/Color.h"
+#include "platform/graphics/Color.h"
#include "wtf/HashMap.h"
#include "wtf/Noncopyable.h"
@@ -45,9 +45,6 @@ typedef HashMap<CSSPropertyID, RefPtr<CSSValue> > PendingImagePropertyMap;
// Holds information about resources, requested by stylesheets.
// Lifetime: per-element style resolve.
-// FIXME: At least for the moment, the lifetime actually matches that of StyleResolverState,
-// but all data is cleared for each element resolve. We must investigate performance
-// implications of matching effective and intended lifetime.
class ElementStyleResources {
WTF_MAKE_NONCOPYABLE(ElementStyleResources);
public:
@@ -63,20 +60,18 @@ public:
const PendingImagePropertyMap& pendingImageProperties() const { return m_pendingImageProperties; }
const PendingSVGDocumentMap& pendingSVGDocuments() const { return m_pendingSVGDocuments; }
- void setHasPendingShaders(bool hasPendingShaders) { m_hasPendingShaders = hasPendingShaders; }
- bool hasPendingShaders() const { return m_hasPendingShaders; }
+ void setHasNewCustomFilterProgram(bool hasNewCustomFilterProgram) { m_hasNewCustomFilterProgram = hasNewCustomFilterProgram; }
+ bool hasNewCustomFilterProgram() const { return m_hasNewCustomFilterProgram; }
float deviceScaleFactor() const { return m_deviceScaleFactor; }
void setDeviceScaleFactor(float deviceScaleFactor) { m_deviceScaleFactor = deviceScaleFactor; }
void addPendingSVGDocument(FilterOperation*, CSSSVGDocumentValue*);
- void clear();
-
private:
PendingImagePropertyMap m_pendingImageProperties;
PendingSVGDocumentMap m_pendingSVGDocuments;
- bool m_hasPendingShaders;
+ bool m_hasNewCustomFilterProgram;
float m_deviceScaleFactor;
};
diff --git a/chromium/third_party/WebKit/Source/core/css/resolver/FilterOperationResolver.cpp b/chromium/third_party/WebKit/Source/core/css/resolver/FilterOperationResolver.cpp
index 39d0f95001b..37706e6818d 100644
--- a/chromium/third_party/WebKit/Source/core/css/resolver/FilterOperationResolver.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/resolver/FilterOperationResolver.cpp
@@ -34,26 +34,22 @@
#include "core/css/CSSParser.h"
#include "core/css/CSSPrimitiveValueMappings.h"
#include "core/css/CSSShaderValue.h"
-#include "core/css/ShadowValue.h"
+#include "core/css/CSSShadowValue.h"
#include "core/css/resolver/TransformBuilder.h"
-#include "core/platform/graphics/filters/custom/CustomFilterArrayParameter.h"
-#include "core/platform/graphics/filters/custom/CustomFilterConstants.h"
-#include "core/platform/graphics/filters/custom/CustomFilterNumberParameter.h"
-#include "core/platform/graphics/filters/custom/CustomFilterOperation.h"
-#include "core/platform/graphics/filters/custom/CustomFilterParameter.h"
-#include "core/platform/graphics/filters/custom/CustomFilterProgramInfo.h"
-#include "core/platform/graphics/filters/custom/CustomFilterTransformParameter.h"
#include "core/rendering/style/StyleCustomFilterProgram.h"
#include "core/rendering/style/StyleShader.h"
+#include "core/rendering/svg/ReferenceFilterBuilder.h"
#include "core/svg/SVGURIReference.h"
+#include "platform/graphics/filters/custom/CustomFilterArrayParameter.h"
+#include "platform/graphics/filters/custom/CustomFilterConstants.h"
+#include "platform/graphics/filters/custom/CustomFilterNumberParameter.h"
+#include "platform/graphics/filters/custom/CustomFilterOperation.h"
+#include "platform/graphics/filters/custom/CustomFilterParameter.h"
+#include "platform/graphics/filters/custom/CustomFilterProgramInfo.h"
+#include "platform/graphics/filters/custom/CustomFilterTransformParameter.h"
namespace WebCore {
-static Length convertToFloatLength(CSSPrimitiveValue* primitiveValue, const RenderStyle* style, const RenderStyle* rootStyle, double multiplier)
-{
- return primitiveValue ? primitiveValue->convertToLength<FixedFloatConversion | PercentConversion | FractionConversion>(style, rootStyle, multiplier) : Length(Undefined);
-}
-
static FilterOperation::OperationType filterOperationForType(CSSFilterValue::FilterOperationType type)
{
switch (type) {
@@ -87,23 +83,10 @@ static FilterOperation::OperationType filterOperationForType(CSSFilterValue::Fil
return FilterOperation::NONE;
}
-static bool sortParametersByNameComparator(const RefPtr<CustomFilterParameter>& a, const RefPtr<CustomFilterParameter>& b)
-{
- return codePointCompareLessThan(a->name(), b->name());
-}
-
-static StyleShader* cachedOrPendingStyleShaderFromValue(CSSShaderValue* value, StyleResolverState& state)
+static StyleShader* styleShader(CSSValue* value)
{
- StyleShader* shader = value->cachedOrPendingShader();
- if (shader && shader->isPendingShader())
- state.elementStyleResources().setHasPendingShaders(true);
- return shader;
-}
-
-static StyleShader* styleShader(CSSValue* value, StyleResolverState& state)
-{
- if (value->isCSSShaderValue())
- return cachedOrPendingStyleShaderFromValue(static_cast<CSSShaderValue*>(value), state);
+ if (value->isShaderValue())
+ return toCSSShaderValue(value)->cachedOrPendingShader();
return 0;
}
@@ -141,7 +124,7 @@ static PassRefPtr<CustomFilterParameter> parseCustomFilterTransformParameter(con
{
RefPtr<CustomFilterTransformParameter> transformParameter = CustomFilterTransformParameter::create(name);
TransformOperations operations;
- TransformBuilder::createTransformOperations(values, state.style(), state.rootElementStyle(), operations);
+ TransformBuilder::createTransformOperations(values, state.cssToLengthConversionData(), operations);
transformParameter->setOperations(operations);
return transformParameter.release();
}
@@ -161,14 +144,14 @@ static PassRefPtr<CustomFilterParameter> parseCustomFilterParameter(const String
if (!values->length())
return 0;
- if (parameterValue->isCSSArrayFunctionValue())
+ if (parameterValue->isArrayFunctionValue())
return parseCustomFilterArrayParameter(name, values);
// If the first value of the list is a transform function,
// then we could safely assume that all the remaining items
// are transforms. parseCustomFilterTransformParameter will
// return 0 if that assumption is incorrect.
- if (values->itemWithoutBoundsCheck(0)->isCSSTransformValue())
+ if (values->itemWithoutBoundsCheck(0)->isTransformValue())
return parseCustomFilterTransformParameter(name, values, state);
// We can have only arrays of booleans or numbers, so use the first value to choose between those two.
@@ -217,15 +200,14 @@ static bool parseCustomFilterParameterList(CSSValue* parametersValue, CustomFilt
}
// Make sure we sort the parameters before passing them down to the CustomFilterOperation.
- std::sort(parameterList.begin(), parameterList.end(), sortParametersByNameComparator);
+ parameterList.sortParametersByName();
return true;
}
-static PassRefPtr<CustomFilterOperation> createCustomFilterOperationWithAtRuleReferenceSyntax(CSSFilterValue* filterValue)
+static PassRefPtr<CustomFilterOperation> createCustomFilterOperationWithAtRuleReferenceSyntax(CSSFilterValue*)
{
// FIXME: Implement style resolution for the custom filter at-rule reference syntax.
- UNUSED_PARAM(filterValue);
return 0;
}
@@ -236,10 +218,13 @@ static PassRefPtr<CustomFilterProgram> createCustomFilterProgram(CSSShaderValue*
ResourceFetcher* fetcher = state.document().fetcher();
KURL vertexShaderURL = vertexShader ? vertexShader->completeURL(fetcher) : KURL();
KURL fragmentShaderURL = fragmentShader ? fragmentShader->completeURL(fetcher) : KURL();
- RefPtr<StyleCustomFilterProgram> program = StyleCustomFilterProgram::create(vertexShaderURL, vertexShader ? styleShader(vertexShader, state) : 0,
- fragmentShaderURL, fragmentShader ? styleShader(fragmentShader, state) : 0, programType, mixSettings, meshType);
- // FIXME
- // FIXME: Find out what the fixme above means.
+ // We re-resolve the custom filter style after the shaders are loaded.
+ // We always create a StyleCustomFilterProgram here, and later replace it with a program from the StyleCustomFilterProgramCache, if available.
+ StyleShader* styleVertexShader = vertexShader ? styleShader(vertexShader) : 0;
+ StyleShader* styleFragmentShader = fragmentShader ? styleShader(fragmentShader) : 0;
+ RefPtr<StyleCustomFilterProgram> program = StyleCustomFilterProgram::create(vertexShaderURL, styleVertexShader,
+ fragmentShaderURL, styleFragmentShader, programType, mixSettings, meshType);
+ state.elementStyleResources().setHasNewCustomFilterProgram(true);
return program.release();
}
@@ -252,19 +237,25 @@ static PassRefPtr<CustomFilterOperation> createCustomFilterOperationWithInlineSy
unsigned shadersListLength = shadersList->length();
ASSERT(shadersListLength);
- CSSShaderValue* vertexShader = toCSSShaderValue(shadersList->itemWithoutBoundsCheck(0));
+ CSSShaderValue* vertexShader = 0;
CSSShaderValue* fragmentShader = 0;
- CustomFilterProgramType programType = PROGRAM_TYPE_BLENDS_ELEMENT_TEXTURE;
+
+ if (shadersList->itemWithoutBoundsCheck(0)->isShaderValue())
+ vertexShader = toCSSShaderValue(shadersList->itemWithoutBoundsCheck(0));
+
+ CustomFilterProgramType programType = ProgramTypeBlendsElementTexture;
CustomFilterProgramMixSettings mixSettings;
if (shadersListLength > 1) {
CSSValue* fragmentShaderOrMixFunction = shadersList->itemWithoutBoundsCheck(1);
- if (fragmentShaderOrMixFunction->isCSSMixFunctionValue()) {
- CSSMixFunctionValue* mixFunction = static_cast<CSSMixFunctionValue*>(fragmentShaderOrMixFunction);
+ if (fragmentShaderOrMixFunction->isMixFunctionValue()) {
+ CSSMixFunctionValue* mixFunction = toCSSMixFunctionValue(fragmentShaderOrMixFunction);
CSSValueListIterator iterator(mixFunction);
ASSERT(mixFunction->length());
- fragmentShader = toCSSShaderValue(iterator.value());
+ if (iterator.value()->isShaderValue())
+ fragmentShader = toCSSShaderValue(iterator.value());
+
iterator.advance();
ASSERT(mixFunction->length() <= 3);
@@ -279,8 +270,9 @@ static PassRefPtr<CustomFilterOperation> createCustomFilterOperationWithInlineSy
iterator.advance();
}
} else {
- programType = PROGRAM_TYPE_NO_ELEMENT_TEXTURE;
- fragmentShader = toCSSShaderValue(fragmentShaderOrMixFunction);
+ programType = ProgramTypeNoElementTexture;
+ if (fragmentShaderOrMixFunction->isShaderValue())
+ fragmentShader = toCSSShaderValue(fragmentShaderOrMixFunction);
}
}
@@ -354,7 +346,7 @@ static PassRefPtr<CustomFilterOperation> createCustomFilterOperation(CSSFilterVa
}
-bool FilterOperationResolver::createFilterOperations(CSSValue* inValue, const RenderStyle* style, const RenderStyle* rootStyle, FilterOperations& outOperations, StyleResolverState& state)
+bool FilterOperationResolver::createFilterOperations(CSSValue* inValue, const CSSToLengthConversionData& unadjustedConversionData, FilterOperations& outOperations, StyleResolverState& state)
{
ASSERT(outOperations.isEmpty());
@@ -370,14 +362,15 @@ bool FilterOperationResolver::createFilterOperations(CSSValue* inValue, const Re
if (!inValue->isValueList())
return false;
- float zoomFactor = (style ? style->effectiveZoom() : 1) * state.elementStyleResources().deviceScaleFactor();
+ float zoomFactor = unadjustedConversionData.zoom() * state.elementStyleResources().deviceScaleFactor();
+ const CSSToLengthConversionData& conversionData = unadjustedConversionData.copyWithAdjustedZoom(zoomFactor);
FilterOperations operations;
for (CSSValueListIterator i = inValue; i.hasMore(); i.advance()) {
CSSValue* currValue = i.value();
- if (!currValue->isCSSFilterValue())
+ if (!currValue->isFilterValue())
continue;
- CSSFilterValue* filterValue = static_cast<CSSFilterValue*>(i.value());
+ CSSFilterValue* filterValue = toCSSFilterValue(i.value());
FilterOperation::OperationType operationType = filterOperationForType(filterValue->operationType());
if (operationType == FilterOperation::VALIDATED_CUSTOM) {
@@ -398,25 +391,25 @@ bool FilterOperationResolver::createFilterOperations(CSSValue* inValue, const Re
continue;
CSSValue* argument = filterValue->itemWithoutBoundsCheck(0);
- if (!argument->isCSSSVGDocumentValue())
+ if (!argument->isSVGDocumentValue())
continue;
- CSSSVGDocumentValue* svgDocumentValue = static_cast<CSSSVGDocumentValue*>(argument);
+ CSSSVGDocumentValue* svgDocumentValue = toCSSSVGDocumentValue(argument);
KURL url = state.document().completeURL(svgDocumentValue->url());
- RefPtr<ReferenceFilterOperation> operation = ReferenceFilterOperation::create(svgDocumentValue->url(), url.fragmentIdentifier(), operationType);
+ RefPtr<ReferenceFilterOperation> operation = ReferenceFilterOperation::create(svgDocumentValue->url(), url.fragmentIdentifier());
if (SVGURIReference::isExternalURIReference(svgDocumentValue->url(), state.document())) {
if (!svgDocumentValue->loadRequested())
state.elementStyleResources().addPendingSVGDocument(operation.get(), svgDocumentValue);
else if (svgDocumentValue->cachedSVGDocument())
- operation->setDocumentResourceReference(adoptPtr(new DocumentResourceReference(svgDocumentValue->cachedSVGDocument())));
+ ReferenceFilterBuilder::setDocumentResourceReference(operation.get(), adoptPtr(new DocumentResourceReference(svgDocumentValue->cachedSVGDocument())));
}
operations.operations().append(operation);
continue;
}
// Check that all parameters are primitive values, with the
- // exception of drop shadow which has a ShadowValue parameter.
+ // exception of drop shadow which has a CSSShadowValue parameter.
if (operationType != FilterOperation::DROP_SHADOW) {
bool haveNonPrimitiveValue = false;
for (unsigned j = 0; j < filterValue->length(); ++j) {
@@ -469,11 +462,11 @@ bool FilterOperationResolver::createFilterOperations(CSSValue* inValue, const Re
case CSSFilterValue::BlurFilterOperation: {
Length stdDeviation = Length(0, Fixed);
if (filterValue->length() >= 1)
- stdDeviation = convertToFloatLength(firstValue, style, rootStyle, zoomFactor);
+ stdDeviation = firstValue->convertToLength<FixedConversion | PercentConversion>(conversionData);
if (stdDeviation.isUndefined())
return false;
- operations.operations().append(BlurFilterOperation::create(stdDeviation, operationType));
+ operations.operations().append(BlurFilterOperation::create(stdDeviation));
break;
}
case CSSFilterValue::DropShadowFilterOperation: {
@@ -484,14 +477,14 @@ bool FilterOperationResolver::createFilterOperations(CSSValue* inValue, const Re
if (!cssValue->isShadowValue())
continue;
- ShadowValue* item = static_cast<ShadowValue*>(cssValue);
- IntPoint location(item->x->computeLength<int>(style, rootStyle, zoomFactor), item->y->computeLength<int>(style, rootStyle, zoomFactor));
- int blur = item->blur ? item->blur->computeLength<int>(style, rootStyle, zoomFactor) : 0;
+ CSSShadowValue* item = toCSSShadowValue(cssValue);
+ IntPoint location(item->x->computeLength<int>(conversionData), item->y->computeLength<int>(conversionData));
+ int blur = item->blur ? item->blur->computeLength<int>(conversionData) : 0;
Color shadowColor;
if (item->color)
- shadowColor = state.document().textLinkColors().colorFromPrimitiveValue(item->color.get(), state.style()->visitedDependentColor(CSSPropertyColor));
+ shadowColor = state.document().textLinkColors().colorFromPrimitiveValue(item->color.get(), state.style()->color());
- operations.operations().append(DropShadowFilterOperation::create(location, blur, shadowColor.isValid() ? shadowColor : Color::transparent, operationType));
+ operations.operations().append(DropShadowFilterOperation::create(location, blur, shadowColor.isValid() ? shadowColor : Color::transparent));
break;
}
case CSSFilterValue::UnknownFilterOperation:
diff --git a/chromium/third_party/WebKit/Source/core/css/resolver/FilterOperationResolver.h b/chromium/third_party/WebKit/Source/core/css/resolver/FilterOperationResolver.h
index b2096f7f894..4475ce31d63 100644
--- a/chromium/third_party/WebKit/Source/core/css/resolver/FilterOperationResolver.h
+++ b/chromium/third_party/WebKit/Source/core/css/resolver/FilterOperationResolver.h
@@ -23,18 +23,18 @@
#define FilterOperationResolver_h
#include "core/css/resolver/StyleResolverState.h"
-#include "core/platform/graphics/filters/FilterOperations.h"
+#include "platform/graphics/filters/FilterOperations.h"
namespace WebCore {
+class CSSToLengthConversionData;
class CSSValue;
-class RenderStyle;
class FilterOperationResolver {
private:
FilterOperationResolver();
public:
- static bool createFilterOperations(CSSValue* inValue, const RenderStyle* inStyle, const RenderStyle* rootStyle, FilterOperations& outOperations, StyleResolverState&);
+ static bool createFilterOperations(CSSValue* inValue, const CSSToLengthConversionData&, FilterOperations& outOperations, StyleResolverState&);
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/css/resolver/FontBuilder.cpp b/chromium/third_party/WebKit/Source/core/css/resolver/FontBuilder.cpp
index 684f36d47c9..57eba497510 100644
--- a/chromium/third_party/WebKit/Source/core/css/resolver/FontBuilder.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/resolver/FontBuilder.cpp
@@ -24,13 +24,14 @@
#include "core/css/resolver/FontBuilder.h"
#include "core/css/CSSCalculationValue.h"
-#include "core/css/FontFeatureValue.h"
+#include "core/css/CSSFontFeatureValue.h"
+#include "core/css/CSSToLengthConversionData.h"
#include "core/css/FontSize.h"
-#include "core/page/Frame.h"
-#include "core/page/Settings.h"
-#include "core/platform/text/LocaleToScriptMapping.h"
+#include "core/frame/Frame.h"
+#include "core/frame/Settings.h"
#include "core/rendering/RenderTheme.h"
#include "core/rendering/RenderView.h"
+#include "platform/text/LocaleToScriptMapping.h"
namespace WebCore {
@@ -77,13 +78,6 @@ void FontBuilder::initForStyleResolve(const Document& document, RenderStyle* sty
m_fontDirty = false;
}
-void FontBuilder::clear()
-{
- m_document = 0;
- m_style = 0;
- m_fontDirty = false;
-}
-
void FontBuilder::setInitial(float effectiveZoom)
{
ASSERT(m_document && m_document->settings());
@@ -95,7 +89,7 @@ void FontBuilder::setInitial(float effectiveZoom)
scope.reset();
scope.fontDescription().setGenericFamily(FontDescription::StandardFamily);
scope.fontDescription().setUsePrinterFont(m_document->printing());
- const AtomicString& standardFontFamily = m_document->settings()->standardFontFamily();
+ const AtomicString& standardFontFamily = m_document->settings()->genericFontFamilySettings().standard();
if (!standardFontFamily.isEmpty()) {
scope.fontDescription().firstFamily().setFamily(standardFontFamily);
scope.fontDescription().firstFamily().appendFamily(0);
@@ -185,34 +179,34 @@ void FontBuilder::setFontFamilyValue(CSSValue* value, float effectiveZoom)
AtomicString face;
Settings* settings = m_document->settings();
if (contentValue->isString()) {
- face = contentValue->getStringValue();
+ face = AtomicString(contentValue->getStringValue());
} else if (settings) {
switch (contentValue->getValueID()) {
case CSSValueWebkitBody:
- face = settings->standardFontFamily();
+ face = settings->genericFontFamilySettings().standard();
break;
case CSSValueSerif:
- face = serifFamily;
+ face = FontFamilyNames::webkit_serif;
scope.fontDescription().setGenericFamily(FontDescription::SerifFamily);
break;
case CSSValueSansSerif:
- face = sansSerifFamily;
+ face = FontFamilyNames::webkit_sans_serif;
scope.fontDescription().setGenericFamily(FontDescription::SansSerifFamily);
break;
case CSSValueCursive:
- face = cursiveFamily;
+ face = FontFamilyNames::webkit_cursive;
scope.fontDescription().setGenericFamily(FontDescription::CursiveFamily);
break;
case CSSValueFantasy:
- face = fantasyFamily;
+ face = FontFamilyNames::webkit_fantasy;
scope.fontDescription().setGenericFamily(FontDescription::FantasyFamily);
break;
case CSSValueMonospace:
- face = monospaceFamily;
+ face = FontFamilyNames::webkit_monospace;
scope.fontDescription().setGenericFamily(FontDescription::MonospaceFamily);
break;
case CSSValueWebkitPictograph:
- face = pictographFamily;
+ face = FontFamilyNames::webkit_pictograph;
scope.fontDescription().setGenericFamily(FontDescription::PictographFamily);
break;
default:
@@ -331,11 +325,11 @@ void FontBuilder::setFontSizeValue(CSSValue* value, RenderStyle* parentStyle, co
} else {
scope.fontDescription().setIsAbsoluteSize(parentIsAbsoluteSize || !(primitiveValue->isPercentage() || primitiveValue->isFontRelativeLength()));
if (primitiveValue->isLength())
- size = primitiveValue->computeLength<float>(parentStyle, rootElementStyle, 1.0, true);
+ size = primitiveValue->computeLength<float>(CSSToLengthConversionData(parentStyle, rootElementStyle, 1.0, true));
else if (primitiveValue->isPercentage())
size = (primitiveValue->getFloatValue() * parentSize) / 100.0f;
else if (primitiveValue->isCalculatedPercentageWithLength())
- size = primitiveValue->cssCalcValue()->toCalcValue(parentStyle, rootElementStyle)->evaluate(parentSize);
+ size = primitiveValue->cssCalcValue()->toCalcValue(CSSToLengthConversionData(parentStyle, rootElementStyle, 1.0f))->evaluate(parentSize);
else if (primitiveValue->isViewportPercentageLength())
size = valueForLength(primitiveValue->viewportPercentageLength(), 0, m_document->renderView());
else
@@ -505,7 +499,7 @@ void FontBuilder::setFeatureSettingsValue(CSSValue* value)
CSSValue* item = list->itemWithoutBoundsCheck(i);
if (!item->isFontFeatureValue())
continue;
- FontFeatureValue* feature = static_cast<FontFeatureValue*>(item);
+ CSSFontFeatureValue* feature = toCSSFontFeatureValue(item);
settings->append(FontFeature(feature->tag(), feature->value()));
}
scope.fontDescription().setFeatureSettings(settings.release());
@@ -649,7 +643,7 @@ void FontBuilder::createFontForDocument(PassRefPtr<FontSelector> fontSelector, R
fontDescription.setScript(localeToScriptCodeForFontSelection(documentStyle->locale()));
if (Settings* settings = m_document->settings()) {
fontDescription.setUsePrinterFont(m_document->printing());
- const AtomicString& standardFont = settings->standardFontFamily(fontDescription.script());
+ const AtomicString& standardFont = settings->genericFontFamilySettings().standard(fontDescription.script());
if (!standardFont.isEmpty()) {
fontDescription.setGenericFamily(FontDescription::StandardFamily);
fontDescription.firstFamily().setFamily(standardFont);
diff --git a/chromium/third_party/WebKit/Source/core/css/resolver/FontBuilder.h b/chromium/third_party/WebKit/Source/core/css/resolver/FontBuilder.h
index 8aa5d3852c0..b573b5159fd 100644
--- a/chromium/third_party/WebKit/Source/core/css/resolver/FontBuilder.h
+++ b/chromium/third_party/WebKit/Source/core/css/resolver/FontBuilder.h
@@ -25,7 +25,7 @@
#include "CSSValueKeywords.h"
-#include "core/platform/graphics/FontDescription.h"
+#include "platform/fonts/FontDescription.h"
#include "wtf/PassRefPtr.h"
namespace WebCore {
@@ -43,7 +43,6 @@ public:
// FIXME: The name is probably wrong, but matches StyleResolverState callsite for consistency.
void initForStyleResolve(const Document&, RenderStyle*, bool useSVGZoomRules);
- void clear();
void setInitial(float effectiveZoom);
diff --git a/chromium/third_party/WebKit/Source/core/css/resolver/MatchRequest.h b/chromium/third_party/WebKit/Source/core/css/resolver/MatchRequest.h
index 8b120d45b5d..df0207f4038 100644
--- a/chromium/third_party/WebKit/Source/core/css/resolver/MatchRequest.h
+++ b/chromium/third_party/WebKit/Source/core/css/resolver/MatchRequest.h
@@ -31,11 +31,12 @@ class ContainerNode;
class MatchRequest {
public:
- MatchRequest(RuleSet* ruleSet, bool includeEmptyRules = false, const ContainerNode* scope = 0, bool elementApplyAuthorStyles = true)
+ MatchRequest(RuleSet* ruleSet, bool includeEmptyRules = false, const ContainerNode* scope = 0, bool elementApplyAuthorStyles = true, unsigned styleSheetIndex = 0)
: ruleSet(ruleSet)
, includeEmptyRules(includeEmptyRules)
, scope(scope)
, elementApplyAuthorStyles(elementApplyAuthorStyles)
+ , styleSheetIndex(styleSheetIndex)
{
// Now that we're about to read from the RuleSet, we're done adding more
// rules to the set and we should make sure it's compacted.
@@ -46,6 +47,7 @@ public:
const bool includeEmptyRules;
const ContainerNode* scope;
const bool elementApplyAuthorStyles;
+ const unsigned styleSheetIndex;
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/css/resolver/MatchedPropertiesCache.cpp b/chromium/third_party/WebKit/Source/core/css/resolver/MatchedPropertiesCache.cpp
index 17367953be4..d3c222a1f1e 100644
--- a/chromium/third_party/WebKit/Source/core/css/resolver/MatchedPropertiesCache.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/resolver/MatchedPropertiesCache.cpp
@@ -148,6 +148,9 @@ bool MatchedPropertiesCache::isCacheable(const Element* element, const RenderSty
return false;
if (style->hasCurrentColor())
return false;
+ // CSSPropertyInternalCallback sets the rule's selector name into the RenderStyle, and that's not recalculated if the RenderStyle is loaded from the cache, so don't cache it.
+ if (!style->callbackSelectors().isEmpty())
+ return false;
// The cache assumes static knowledge about which properties are inherited.
if (parentStyle->hasExplicitlyInheritedProperties())
return false;
diff --git a/chromium/third_party/WebKit/Source/core/css/resolver/MatchedPropertiesCache.h b/chromium/third_party/WebKit/Source/core/css/resolver/MatchedPropertiesCache.h
index f1ccc3d1e96..2e5297d5acd 100644
--- a/chromium/third_party/WebKit/Source/core/css/resolver/MatchedPropertiesCache.h
+++ b/chromium/third_party/WebKit/Source/core/css/resolver/MatchedPropertiesCache.h
@@ -25,7 +25,7 @@
#include "core/css/resolver/MatchResult.h"
-#include "core/platform/Timer.h"
+#include "platform/Timer.h"
#include "wtf/Forward.h"
#include "wtf/HashMap.h"
#include "wtf/Noncopyable.h"
diff --git a/chromium/third_party/WebKit/Source/core/css/resolver/MediaQueryResult.h b/chromium/third_party/WebKit/Source/core/css/resolver/MediaQueryResult.h
index e18cbcff12a..1dc00f42dc3 100644
--- a/chromium/third_party/WebKit/Source/core/css/resolver/MediaQueryResult.h
+++ b/chromium/third_party/WebKit/Source/core/css/resolver/MediaQueryResult.h
@@ -25,10 +25,11 @@
#include "core/css/MediaQueryExp.h"
#include "wtf/Noncopyable.h"
+#include "wtf/RefCounted.h"
namespace WebCore {
-class MediaQueryResult {
+class MediaQueryResult : public RefCounted<MediaQueryResult> {
WTF_MAKE_NONCOPYABLE(MediaQueryResult); WTF_MAKE_FAST_ALLOCATED;
public:
MediaQueryResult(const MediaQueryExp& expr, bool result)
diff --git a/chromium/third_party/WebKit/Source/core/css/resolver/ScopedStyleResolver.cpp b/chromium/third_party/WebKit/Source/core/css/resolver/ScopedStyleResolver.cpp
index cb60fdc2797..706f5d827ab 100644
--- a/chromium/third_party/WebKit/Source/core/css/resolver/ScopedStyleResolver.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/resolver/ScopedStyleResolver.cpp
@@ -31,9 +31,10 @@
#include "core/css/CSSStyleSheet.h"
#include "core/css/PageRuleCollector.h"
#include "core/css/RuleFeature.h"
-#include "core/css/RuleSet.h"
#include "core/css/StyleRule.h"
+#include "core/css/StyleSheetContents.h"
#include "core/css/resolver/StyleResolver.h" // For MatchRequest.
+#include "core/css/resolver/ViewportStyleResolver.h"
#include "core/dom/Document.h"
#include "core/dom/shadow/ElementShadow.h"
#include "core/dom/shadow/ShadowRoot.h"
@@ -41,202 +42,23 @@
namespace WebCore {
-ScopedStyleResolver* ScopedStyleTree::ensureScopedStyleResolver(const ContainerNode& scopingNode)
-{
- bool isNewEntry;
- ScopedStyleResolver* scopedStyleResolver = addScopedStyleResolver(scopingNode, isNewEntry);
- if (isNewEntry)
- setupScopedStylesTree(scopedStyleResolver);
- return scopedStyleResolver;
-}
-
-ScopedStyleResolver* ScopedStyleTree::scopedStyleResolverFor(const ContainerNode& scopingNode)
-{
- if (!scopingNode.hasScopedHTMLStyleChild()
- && !(scopingNode.isElementNode() && toElement(scopingNode).shadow())
- && !scopingNode.isDocumentNode()
- && !scopingNode.isShadowRoot())
- return 0;
- HashMap<const ContainerNode*, OwnPtr<ScopedStyleResolver> >::iterator it = m_authorStyles.find(&scopingNode);
- return it != m_authorStyles.end() ? it->value.get() : 0;
-}
-
-ScopedStyleResolver* ScopedStyleTree::addScopedStyleResolver(const ContainerNode& scopingNode, bool& isNewEntry)
-{
- HashMap<const ContainerNode*, OwnPtr<ScopedStyleResolver> >::AddResult addResult = m_authorStyles.add(&scopingNode, nullptr);
-
- if (addResult.isNewEntry) {
- addResult.iterator->value = ScopedStyleResolver::create(scopingNode);
- if (scopingNode.isDocumentNode())
- m_scopedResolverForDocument = addResult.iterator->value.get();
- }
- isNewEntry = addResult.isNewEntry;
- return addResult.iterator->value.get();
-}
-
-void ScopedStyleTree::setupScopedStylesTree(ScopedStyleResolver* target)
-{
- ASSERT(target);
-
- const ContainerNode& scopingNode = target->scopingNode();
-
- // Since StyleResolver creates RuleSets according to styles' document
- // order, a parent of the given ScopedRuleData has been already
- // prepared.
- for (const ContainerNode* node = scopingNode.parentOrShadowHostNode(); node; node = node->parentOrShadowHostNode()) {
- if (ScopedStyleResolver* scopedResolver = scopedStyleResolverFor(*node)) {
- target->setParent(scopedResolver);
- break;
- }
- if (node->isDocumentNode()) {
- bool dummy;
- ScopedStyleResolver* scopedResolver = addScopedStyleResolver(*node, dummy);
- target->setParent(scopedResolver);
- setupScopedStylesTree(scopedResolver);
- break;
- }
- }
-
- if (m_buildInDocumentOrder)
- return;
-
- // Reparent all nodes whose scoping node is contained by target's one.
- for (HashMap<const ContainerNode*, OwnPtr<ScopedStyleResolver> >::iterator it = m_authorStyles.begin(); it != m_authorStyles.end(); ++it) {
- if (it->value == target)
- continue;
- if (it->value->parent() == target->parent() && scopingNode.containsIncludingShadowDOM(it->key))
- it->value->setParent(target);
- }
-}
-
-void ScopedStyleTree::clear()
-{
- m_authorStyles.clear();
- m_scopedResolverForDocument = 0;
- m_cache.clear();
-}
-
-void ScopedStyleTree::resolveScopedStyles(const Element* element, Vector<ScopedStyleResolver*, 8>& resolvers)
-{
- for (ScopedStyleResolver* scopedResolver = scopedResolverFor(element); scopedResolver; scopedResolver = scopedResolver->parent())
- resolvers.append(scopedResolver);
-}
-
-void ScopedStyleTree::collectScopedResolversForHostedShadowTrees(const Element* element, Vector<ScopedStyleResolver*, 8>& resolvers)
-{
- ElementShadow* shadow = element->shadow();
- if (!shadow)
- return;
-
- // Adding scoped resolver for active shadow roots for shadow host styling.
- for (ShadowRoot* shadowRoot = shadow->youngestShadowRoot(); shadowRoot; shadowRoot = shadowRoot->olderShadowRoot()) {
- if (shadowRoot->hasScopedHTMLStyleChild()) {
- if (ScopedStyleResolver* resolver = scopedStyleResolverFor(*shadowRoot))
- resolvers.append(resolver);
- }
- if (!shadowRoot->containsShadowElements())
- break;
- }
-}
-
-void ScopedStyleTree::resolveScopedKeyframesRules(const Element* element, Vector<ScopedStyleResolver*, 8>& resolvers)
-{
- Document& document = element->document();
- TreeScope& treeScope = element->treeScope();
- bool applyAuthorStyles = treeScope.applyAuthorStyles();
-
- for (ScopedStyleResolver* scopedResolver = scopedResolverFor(element); scopedResolver; scopedResolver = scopedResolver->parent()) {
- if (&scopedResolver->treeScope() == &treeScope || (applyAuthorStyles && &scopedResolver->treeScope() == &document))
- resolvers.append(scopedResolver);
- }
-}
-
-inline ScopedStyleResolver* ScopedStyleTree::enclosingScopedStyleResolverFor(const ContainerNode* scopingNode)
-{
- for (; scopingNode; scopingNode = scopingNode->parentOrShadowHostNode()) {
- if (ScopedStyleResolver* scopedStyleResolver = scopedStyleResolverFor(*scopingNode))
- return scopedStyleResolver;
- }
- return 0;
-}
-
-void ScopedStyleTree::resolveStyleCache(const ContainerNode* scopingNode)
-{
- m_cache.scopedResolver = enclosingScopedStyleResolverFor(scopingNode);
- m_cache.nodeForScopedStyles = scopingNode;
-}
-
-void ScopedStyleTree::pushStyleCache(const ContainerNode& scopingNode, const ContainerNode* parent)
-{
- if (m_authorStyles.isEmpty())
- return;
-
- if (!cacheIsValid(parent)) {
- resolveStyleCache(&scopingNode);
- return;
- }
-
- ScopedStyleResolver* scopedResolver = scopedStyleResolverFor(scopingNode);
- if (scopedResolver)
- m_cache.scopedResolver = scopedResolver;
- m_cache.nodeForScopedStyles = &scopingNode;
-}
-
-void ScopedStyleTree::popStyleCache(const ContainerNode& scopingNode)
-{
- if (!cacheIsValid(&scopingNode))
- return;
-
- if (m_cache.scopedResolver && &m_cache.scopedResolver->scopingNode() == &scopingNode)
- m_cache.scopedResolver = m_cache.scopedResolver->parent();
- m_cache.nodeForScopedStyles = scopingNode.parentOrShadowHostNode();
-}
-
-void ScopedStyleTree::collectFeaturesTo(RuleFeatureSet& features)
-{
- for (HashMap<const ContainerNode*, OwnPtr<ScopedStyleResolver> >::iterator it = m_authorStyles.begin(); it != m_authorStyles.end(); ++it)
- it->value->collectFeaturesTo(features);
-}
-
-inline void ScopedStyleTree::reparentNodes(const ScopedStyleResolver* oldParent, ScopedStyleResolver* newParent)
-{
- // FIXME: this takes O(N) (N = number of all scoping nodes).
- for (HashMap<const ContainerNode*, OwnPtr<ScopedStyleResolver> >::iterator it = m_authorStyles.begin(); it != m_authorStyles.end(); ++it) {
- if (it->value->parent() == oldParent)
- it->value->setParent(newParent);
- }
-}
-
-void ScopedStyleTree::remove(const ContainerNode* scopingNode)
-{
- if (!scopingNode || scopingNode->isDocumentNode())
- return;
-
- ScopedStyleResolver* resolverRemoved = scopedStyleResolverFor(*scopingNode);
- if (!resolverRemoved)
- return;
-
- reparentNodes(resolverRemoved, resolverRemoved->parent());
- if (m_cache.scopedResolver == resolverRemoved)
- m_cache.clear();
-
- m_authorStyles.remove(scopingNode);
-}
-
-const ContainerNode* ScopedStyleResolver::scopingNodeFor(const CSSStyleSheet* sheet)
+ContainerNode* ScopedStyleResolver::scopingNodeFor(Document& document, const CSSStyleSheet* sheet)
{
ASSERT(sheet);
- Document* document = sheet->ownerDocument();
- if (!document)
+ Document* sheetDocument = sheet->ownerDocument();
+ if (!sheetDocument)
return 0;
Node* ownerNode = sheet->ownerNode();
- if (!ownerNode || !ownerNode->hasTagName(HTMLNames::styleTag))
- return 0;
+ if (!ownerNode || !isHTMLStyleElement(ownerNode))
+ return &document;
HTMLStyleElement* styleElement = toHTMLStyleElement(ownerNode);
- if (!styleElement->scoped())
- return styleElement->isInShadowTree() ? styleElement->containingShadowRoot() : 0;
+ if (!styleElement->scoped()) {
+ if (styleElement->isInShadowTree())
+ return styleElement->containingShadowRoot();
+ return &document;
+ }
ContainerNode* parent = styleElement->parentNode();
if (!parent)
@@ -247,73 +69,35 @@ const ContainerNode* ScopedStyleResolver::scopingNodeFor(const CSSStyleSheet* sh
void ScopedStyleResolver::addRulesFromSheet(StyleSheetContents* sheet, const MediaQueryEvaluator& medium, StyleResolver* resolver)
{
- if (!m_authorStyle)
- m_authorStyle = RuleSet::create();
- m_authorStyle->addRulesFromSheet(sheet, medium, resolver, &m_scopingNode);
-}
+ m_authorStyleSheets.append(sheet);
-inline RuleSet* ScopedStyleResolver::ensureAtHostRuleSetFor(const ShadowRoot* shadowRoot)
-{
- HashMap<const ShadowRoot*, OwnPtr<RuleSet> >::AddResult addResult = m_atHostRules.add(shadowRoot, nullptr);
- if (addResult.isNewEntry)
- addResult.iterator->value = RuleSet::create();
- return addResult.iterator->value.get();
-}
-
-void ScopedStyleResolver::addHostRule(StyleRuleHost* hostRule, bool hasDocumentSecurityOrigin, const ContainerNode* scopingNode)
-{
- if (!scopingNode)
- return;
-
- ShadowRoot* shadowRoot = scopingNode->containingShadowRoot();
- if (!shadowRoot || !shadowRoot->host())
- return;
-
- RuleSet* rule = ensureAtHostRuleSetFor(shadowRoot);
-
- const Vector<RefPtr<StyleRuleBase> >& childRules = hostRule->childRules();
- AddRuleFlags addRuleFlags = hasDocumentSecurityOrigin ? RuleHasDocumentSecurityOrigin : RuleHasNoSpecialState;
- addRuleFlags = static_cast<AddRuleFlags>(addRuleFlags | RuleCanUseFastCheckSelector);
- for (unsigned i = 0; i < childRules.size(); ++i) {
- StyleRuleBase* hostStylingRule = childRules[i].get();
- if (hostStylingRule->isStyleRule())
- rule->addStyleRule(static_cast<StyleRule*>(hostStylingRule), addRuleFlags);
- }
+ AddRuleFlags addRuleFlags = resolver->document().securityOrigin()->canRequest(sheet->baseURL()) ? RuleHasDocumentSecurityOrigin : RuleHasNoSpecialState;
+ const RuleSet& ruleSet = sheet->ensureRuleSet(medium, addRuleFlags);
+ resolver->addMediaQueryResults(ruleSet.viewportDependentMediaQueryResults());
+ resolver->processScopedRules(ruleSet, sheet->baseURL(), &m_scopingNode);
}
void ScopedStyleResolver::collectFeaturesTo(RuleFeatureSet& features)
{
- if (m_authorStyle)
- features.add(m_authorStyle->features());
-
- if (m_atHostRules.isEmpty())
- return;
-
- for (HashMap<const ShadowRoot*, OwnPtr<RuleSet> >::iterator it = m_atHostRules.begin(); it != m_atHostRules.end(); ++it)
- features.add(it->value->features());
+ for (size_t i = 0; i < m_authorStyleSheets.size(); ++i)
+ features.add(m_authorStyleSheets[i]->ruleSet().features());
}
void ScopedStyleResolver::resetAuthorStyle()
{
- m_authorStyle = RuleSet::create();
+ m_authorStyleSheets.clear();
m_keyframesRuleMap.clear();
}
-void ScopedStyleResolver::resetAtHostRules(const ShadowRoot* shadowRoot)
-{
- m_atHostRules.remove(shadowRoot);
-}
-
bool ScopedStyleResolver::checkRegionStyle(Element* regionElement)
{
- if (!m_authorStyle)
- return false;
-
- unsigned rulesSize = m_authorStyle->m_regionSelectorsAndRuleSets.size();
- for (unsigned i = 0; i < rulesSize; ++i) {
- ASSERT(m_authorStyle->m_regionSelectorsAndRuleSets.at(i).ruleSet.get());
- if (checkRegionSelector(m_authorStyle->m_regionSelectorsAndRuleSets.at(i).selector, regionElement))
- return true;
+ for (size_t i = 0; i < m_authorStyleSheets.size(); ++i) {
+ const RuleSet& ruleSet = m_authorStyleSheets[i]->ruleSet();
+ for (unsigned i = 0; i < ruleSet.m_regionSelectorsAndRuleSets.size(); ++i) {
+ ASSERT(ruleSet.m_regionSelectorsAndRuleSets.at(i).ruleSet.get());
+ if (checkRegionSelector(ruleSet.m_regionSelectorsAndRuleSets.at(i).selector, regionElement))
+ return true;
+ }
}
return false;
}
@@ -344,62 +128,8 @@ void ScopedStyleResolver::addKeyframeStyle(PassRefPtr<StyleRuleKeyframes> rule)
}
}
-inline RuleSet* ScopedStyleResolver::atHostRuleSetFor(const ShadowRoot* shadowRoot) const
-{
- HashMap<const ShadowRoot*, OwnPtr<RuleSet> >::const_iterator it = m_atHostRules.find(shadowRoot);
- return it != m_atHostRules.end() ? it->value.get() : 0;
-}
-
-void ScopedStyleResolver::matchHostRules(ElementRuleCollector& collector, bool includeEmptyRules)
-{
- // FIXME: Determine tree position.
- CascadeScope cascadeScope = ignoreCascadeScope;
-
- if (m_atHostRules.isEmpty() || !m_scopingNode.isElementNode())
- return;
-
- ElementShadow* shadow = toElement(m_scopingNode).shadow();
- if (!shadow)
- return;
-
- collector.clearMatchedRules();
- collector.matchedResult().ranges.lastAuthorRule = collector.matchedResult().matchedProperties.size() - 1;
-
- // FIXME(99827): https://bugs.webkit.org/show_bug.cgi?id=99827
- // add a new flag to ElementShadow and cache whether any @host @-rules are
- // applied to the element or not. So we can quickly exit this method
- // by using the flag.
- ShadowRoot* shadowRoot = shadow->youngestShadowRoot();
- for (; shadowRoot; shadowRoot = shadowRoot->olderShadowRoot())
- if (!shadowRoot->containsShadowElements())
- break;
- // All shadow roots have <shadow>.
- if (!shadowRoot)
- shadowRoot = shadow->oldestShadowRoot();
-
- RuleRange ruleRange = collector.matchedResult().ranges.authorRuleRange();
- collector.setBehaviorAtBoundary(static_cast<SelectorChecker::BehaviorAtBoundary>(SelectorChecker::DoesNotCrossBoundary | SelectorChecker::ScopeContainsLastMatchedElement));
- for (; shadowRoot; shadowRoot = shadowRoot->youngerShadowRoot()) {
- if (RuleSet* ruleSet = atHostRuleSetFor(shadowRoot))
- collector.collectMatchingRules(MatchRequest(ruleSet, includeEmptyRules, &m_scopingNode), ruleRange, cascadeScope);
- }
-
- collector.sortAndTransferMatchedRules();
-}
-
-void ScopedStyleResolver::matchAuthorRules(ElementRuleCollector& collector, bool includeEmptyRules, bool applyAuthorStyles)
-{
- collector.clearMatchedRules();
- collector.matchedResult().ranges.lastAuthorRule = collector.matchedResult().matchedProperties.size() - 1;
- collectMatchingAuthorRules(collector, includeEmptyRules, applyAuthorStyles, ignoreCascadeScope);
- collector.sortAndTransferMatchedRules();
-}
-
void ScopedStyleResolver::collectMatchingAuthorRules(ElementRuleCollector& collector, bool includeEmptyRules, bool applyAuthorStyles, CascadeScope cascadeScope, CascadeOrder cascadeOrder)
{
- if (!m_authorStyle)
- return;
-
const ContainerNode* scopingNode = &m_scopingNode;
unsigned behaviorAtBoundary = SelectorChecker::DoesNotCrossBoundary;
@@ -411,24 +141,28 @@ void ScopedStyleResolver::collectMatchingAuthorRules(ElementRuleCollector& colle
behaviorAtBoundary |= SelectorChecker::ScopeIsShadowHost;
}
- MatchRequest matchRequest(m_authorStyle.get(), includeEmptyRules, scopingNode, applyAuthorStyles);
RuleRange ruleRange = collector.matchedResult().ranges.authorRuleRange();
- collector.setBehaviorAtBoundary(static_cast<SelectorChecker::BehaviorAtBoundary>(behaviorAtBoundary));
- collector.collectMatchingRules(matchRequest, ruleRange, cascadeScope, cascadeOrder);
- collector.collectMatchingRulesForRegion(matchRequest, ruleRange, cascadeScope, cascadeOrder);
+ for (size_t i = 0; i < m_authorStyleSheets.size(); ++i) {
+ MatchRequest matchRequest(&m_authorStyleSheets[i]->ruleSet(), includeEmptyRules, scopingNode, applyAuthorStyles, i);
+ collector.collectMatchingRules(matchRequest, ruleRange, static_cast<SelectorChecker::BehaviorAtBoundary>(behaviorAtBoundary), cascadeScope, cascadeOrder);
+ collector.collectMatchingRulesForRegion(matchRequest, ruleRange, static_cast<SelectorChecker::BehaviorAtBoundary>(behaviorAtBoundary), cascadeScope, cascadeOrder);
+ }
}
void ScopedStyleResolver::matchPageRules(PageRuleCollector& collector)
{
// Only consider the global author RuleSet for @page rules, as per the HTML5 spec.
ASSERT(m_scopingNode.isDocumentNode());
- collector.matchPageRules(m_authorStyle.get());
+ for (size_t i = 0; i < m_authorStyleSheets.size(); ++i)
+ collector.matchPageRules(&m_authorStyleSheets[i]->ruleSet());
}
void ScopedStyleResolver::collectViewportRulesTo(StyleResolver* resolver) const
{
- if (m_authorStyle)
- resolver->collectViewportRules(m_authorStyle.get(), StyleResolver::AuthorOrigin);
+ if (!m_scopingNode.isDocumentNode())
+ return;
+ for (size_t i = 0; i < m_authorStyleSheets.size(); ++i)
+ resolver->viewportStyleResolver()->collectViewportRules(&m_authorStyleSheets[i]->ruleSet(), ViewportStyleResolver::AuthorOrigin);
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/css/resolver/ScopedStyleResolver.h b/chromium/third_party/WebKit/Source/core/css/resolver/ScopedStyleResolver.h
index 5372eddf402..7aa1a1a18dd 100644
--- a/chromium/third_party/WebKit/Source/core/css/resolver/ScopedStyleResolver.h
+++ b/chromium/third_party/WebKit/Source/core/css/resolver/ScopedStyleResolver.h
@@ -27,20 +27,15 @@
#ifndef ScopedStyleResolver_h
#define ScopedStyleResolver_h
-#include "core/css/CSSKeyframesRule.h"
#include "core/css/ElementRuleCollector.h"
#include "core/css/RuleSet.h"
#include "core/dom/ContainerNode.h"
-#include "core/dom/Element.h"
-#include "wtf/Forward.h"
#include "wtf/HashMap.h"
#include "wtf/OwnPtr.h"
#include "wtf/PassOwnPtr.h"
-#include "wtf/Vector.h"
namespace WebCore {
-class ElementRuleCollector;
class MediaQueryEvaluator;
class PageRuleCollector;
class ShadowRoot;
@@ -50,113 +45,41 @@ class StyleSheetContents;
class ScopedStyleResolver {
WTF_MAKE_NONCOPYABLE(ScopedStyleResolver); WTF_MAKE_FAST_ALLOCATED;
public:
- static PassOwnPtr<ScopedStyleResolver> create(const ContainerNode& scopingNode) { return adoptPtr(new ScopedStyleResolver(scopingNode)); }
+ static PassOwnPtr<ScopedStyleResolver> create(ContainerNode& scopingNode) { return adoptPtr(new ScopedStyleResolver(scopingNode)); }
- static const ContainerNode* scopingNodeFor(const CSSStyleSheet*);
+ static ContainerNode* scopingNodeFor(Document&, const CSSStyleSheet*);
const ContainerNode& scopingNode() const { return m_scopingNode; }
const TreeScope& treeScope() const { return m_scopingNode.treeScope(); }
- void prepareEmptyRuleSet() { m_authorStyle = RuleSet::create(); }
void setParent(ScopedStyleResolver* newParent) { m_parent = newParent; }
ScopedStyleResolver* parent() { return m_parent; }
- bool hasOnlyEmptyRuleSets() const { return !m_authorStyle->ruleCount() && m_atHostRules.isEmpty(); }
-
public:
bool checkRegionStyle(Element*);
const StyleRuleKeyframes* keyframeStylesForAnimation(const StringImpl* animationName);
void addKeyframeStyle(PassRefPtr<StyleRuleKeyframes>);
- void matchHostRules(ElementRuleCollector&, bool includeEmptyRules);
- void matchAuthorRules(ElementRuleCollector&, bool includeEmptyRules, bool applyAuthorStyles);
void collectMatchingAuthorRules(ElementRuleCollector&, bool includeEmptyRules, bool applyAuthorStyles, CascadeScope, CascadeOrder = ignoreCascadeOrder);
void matchPageRules(PageRuleCollector&);
void addRulesFromSheet(StyleSheetContents*, const MediaQueryEvaluator&, StyleResolver*);
- void addHostRule(StyleRuleHost*, bool hasDocumentSecurityOrigin, const ContainerNode* scopingNode);
void collectFeaturesTo(RuleFeatureSet&);
void resetAuthorStyle();
- void resetAtHostRules(const ShadowRoot*);
void collectViewportRulesTo(StyleResolver*) const;
private:
- explicit ScopedStyleResolver(const ContainerNode& scopingNode) : m_scopingNode(scopingNode), m_parent(0) { }
+ explicit ScopedStyleResolver(ContainerNode& scopingNode) : m_scopingNode(scopingNode), m_parent(0) { }
- RuleSet* ensureAtHostRuleSetFor(const ShadowRoot*);
- RuleSet* atHostRuleSetFor(const ShadowRoot*) const;
+ RuleSet* ensureAuthorStyle();
- const ContainerNode& m_scopingNode;
+ ContainerNode& m_scopingNode;
ScopedStyleResolver* m_parent;
- OwnPtr<RuleSet> m_authorStyle;
- HashMap<const ShadowRoot*, OwnPtr<RuleSet> > m_atHostRules;
+ Vector<StyleSheetContents*> m_authorStyleSheets;
typedef HashMap<const StringImpl*, RefPtr<StyleRuleKeyframes> > KeyframesRuleMap;
KeyframesRuleMap m_keyframesRuleMap;
};
-class ScopedStyleTree {
- WTF_MAKE_NONCOPYABLE(ScopedStyleTree); WTF_MAKE_FAST_ALLOCATED;
-public:
- ScopedStyleTree() : m_scopedResolverForDocument(0), m_buildInDocumentOrder(true) { }
-
- ScopedStyleResolver* ensureScopedStyleResolver(const ContainerNode& scopingNode);
- ScopedStyleResolver* scopedStyleResolverFor(const ContainerNode& scopingNode);
- ScopedStyleResolver* addScopedStyleResolver(const ContainerNode& scopingNode, bool& isNewEntry);
- void clear();
-
- // for fast-path.
- bool hasOnlyScopedResolverForDocument() const { return m_scopedResolverForDocument && m_authorStyles.size() == 1; }
- ScopedStyleResolver* scopedStyleResolverForDocument() { return m_scopedResolverForDocument; }
-
- void resolveScopedStyles(const Element*, Vector<ScopedStyleResolver*, 8>&);
- void collectScopedResolversForHostedShadowTrees(const Element*, Vector<ScopedStyleResolver*, 8>&);
- void resolveScopedKeyframesRules(const Element*, Vector<ScopedStyleResolver*, 8>&);
- ScopedStyleResolver* scopedResolverFor(const Element*);
-
- void remove(const ContainerNode* scopingNode);
-
- void pushStyleCache(const ContainerNode& scopingNode, const ContainerNode* parent);
- void popStyleCache(const ContainerNode& scopingNode);
-
- void collectFeaturesTo(RuleFeatureSet& features);
- void setBuildInDocumentOrder(bool enabled) { m_buildInDocumentOrder = enabled; }
- bool buildInDocumentOrder() const { return m_buildInDocumentOrder; }
-
-private:
- void setupScopedStylesTree(ScopedStyleResolver* target);
-
- bool cacheIsValid(const ContainerNode* parent) const { return parent && parent == m_cache.nodeForScopedStyles; }
- void resolveStyleCache(const ContainerNode* scopingNode);
- ScopedStyleResolver* enclosingScopedStyleResolverFor(const ContainerNode* scopingNode);
-
- void reparentNodes(const ScopedStyleResolver* oldParent, ScopedStyleResolver* newParent);
-
-private:
- HashMap<const ContainerNode*, OwnPtr<ScopedStyleResolver> > m_authorStyles;
- ScopedStyleResolver* m_scopedResolverForDocument;
- bool m_buildInDocumentOrder;
-
- struct ScopedStyleCache {
- ScopedStyleResolver* scopedResolver;
- const ContainerNode* nodeForScopedStyles;
-
- void clear()
- {
- scopedResolver = 0;
- nodeForScopedStyles = 0;
- }
- };
- ScopedStyleCache m_cache;
-};
-
-inline ScopedStyleResolver* ScopedStyleTree::scopedResolverFor(const Element* element)
-{
- if (!cacheIsValid(element))
- resolveStyleCache(element);
-
- return m_cache.scopedResolver;
-}
-
} // namespace WebCore
#endif // ScopedStyleResolver_h
diff --git a/chromium/third_party/WebKit/Source/core/css/resolver/ScopedStyleTree.cpp b/chromium/third_party/WebKit/Source/core/css/resolver/ScopedStyleTree.cpp
new file mode 100644
index 00000000000..729faf15e8f
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/css/resolver/ScopedStyleTree.cpp
@@ -0,0 +1,219 @@
+/*
+ * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
+ * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
+ * Copyright (C) 2012 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/css/resolver/ScopedStyleTree.h"
+
+#include "core/css/RuleFeature.h"
+#include "core/dom/Document.h"
+#include "core/dom/shadow/ElementShadow.h"
+#include "core/dom/shadow/ShadowRoot.h"
+
+namespace WebCore {
+
+ScopedStyleResolver* ScopedStyleTree::ensureScopedStyleResolver(ContainerNode& scopingNode)
+{
+ bool isNewEntry;
+ ScopedStyleResolver* scopedStyleResolver = addScopedStyleResolver(scopingNode, isNewEntry);
+ if (isNewEntry)
+ setupScopedStylesTree(scopedStyleResolver);
+ return scopedStyleResolver;
+}
+
+ScopedStyleResolver* ScopedStyleTree::scopedStyleResolverFor(const ContainerNode& scopingNode)
+{
+ if (!scopingNode.hasScopedHTMLStyleChild()
+ && !isShadowHost(&scopingNode)
+ && !scopingNode.isDocumentNode()
+ && !scopingNode.isShadowRoot())
+ return 0;
+ return lookupScopedStyleResolverFor(&scopingNode);
+}
+
+ScopedStyleResolver* ScopedStyleTree::addScopedStyleResolver(ContainerNode& scopingNode, bool& isNewEntry)
+{
+ HashMap<const ContainerNode*, OwnPtr<ScopedStyleResolver> >::AddResult addResult = m_authorStyles.add(&scopingNode, nullptr);
+
+ if (addResult.isNewEntry) {
+ addResult.iterator->value = ScopedStyleResolver::create(scopingNode);
+ if (scopingNode.isDocumentNode())
+ m_scopedResolverForDocument = addResult.iterator->value.get();
+ }
+ isNewEntry = addResult.isNewEntry;
+ return addResult.iterator->value.get();
+}
+
+void ScopedStyleTree::setupScopedStylesTree(ScopedStyleResolver* target)
+{
+ ASSERT(target);
+
+ const ContainerNode& scopingNode = target->scopingNode();
+
+ // Since StyleResolver creates RuleSets according to styles' document
+ // order, a parent of the given ScopedRuleData has been already
+ // prepared.
+ for (ContainerNode* node = scopingNode.parentOrShadowHostNode(); node; node = node->parentOrShadowHostNode()) {
+ if (ScopedStyleResolver* scopedResolver = scopedStyleResolverFor(*node)) {
+ target->setParent(scopedResolver);
+ break;
+ }
+ if (node->isDocumentNode()) {
+ bool dummy;
+ ScopedStyleResolver* scopedResolver = addScopedStyleResolver(*node, dummy);
+ target->setParent(scopedResolver);
+ setupScopedStylesTree(scopedResolver);
+ break;
+ }
+ }
+
+ if (m_buildInDocumentOrder)
+ return;
+
+ // Reparent all nodes whose scoping node is contained by target's one.
+ for (HashMap<const ContainerNode*, OwnPtr<ScopedStyleResolver> >::iterator it = m_authorStyles.begin(); it != m_authorStyles.end(); ++it) {
+ if (it->value == target)
+ continue;
+ ASSERT(it->key->inDocument());
+ if (it->value->parent() == target->parent() && scopingNode.containsIncludingShadowDOM(it->key))
+ it->value->setParent(target);
+ }
+}
+
+void ScopedStyleTree::clear()
+{
+ m_authorStyles.clear();
+ m_scopedResolverForDocument = 0;
+ m_cache.clear();
+}
+
+void ScopedStyleTree::resolveScopedStyles(const Element* element, Vector<ScopedStyleResolver*, 8>& resolvers)
+{
+ for (ScopedStyleResolver* scopedResolver = scopedResolverFor(element); scopedResolver; scopedResolver = scopedResolver->parent())
+ resolvers.append(scopedResolver);
+}
+
+void ScopedStyleTree::collectScopedResolversForHostedShadowTrees(const Element* element, Vector<ScopedStyleResolver*, 8>& resolvers)
+{
+ ElementShadow* shadow = element->shadow();
+ if (!shadow)
+ return;
+
+ // Adding scoped resolver for active shadow roots for shadow host styling.
+ for (ShadowRoot* shadowRoot = shadow->youngestShadowRoot(); shadowRoot; shadowRoot = shadowRoot->olderShadowRoot()) {
+ if (shadowRoot->hasScopedHTMLStyleChild()) {
+ if (ScopedStyleResolver* resolver = scopedStyleResolverFor(*shadowRoot))
+ resolvers.append(resolver);
+ }
+ if (!shadowRoot->containsShadowElements())
+ break;
+ }
+}
+
+void ScopedStyleTree::resolveScopedKeyframesRules(const Element* element, Vector<ScopedStyleResolver*, 8>& resolvers)
+{
+ Document& document = element->document();
+ TreeScope& treeScope = element->treeScope();
+ bool applyAuthorStyles = treeScope.applyAuthorStyles();
+
+ for (ScopedStyleResolver* scopedResolver = scopedResolverFor(element); scopedResolver; scopedResolver = scopedResolver->parent()) {
+ if (scopedResolver->treeScope() == treeScope || (applyAuthorStyles && scopedResolver->treeScope() == document))
+ resolvers.append(scopedResolver);
+ }
+}
+
+inline ScopedStyleResolver* ScopedStyleTree::enclosingScopedStyleResolverFor(const ContainerNode* scopingNode)
+{
+ for (; scopingNode; scopingNode = scopingNode->parentOrShadowHostNode()) {
+ if (ScopedStyleResolver* scopedStyleResolver = scopedStyleResolverFor(*scopingNode))
+ return scopedStyleResolver;
+ }
+ return 0;
+}
+
+void ScopedStyleTree::resolveStyleCache(const ContainerNode* scopingNode)
+{
+ m_cache.scopedResolver = enclosingScopedStyleResolverFor(scopingNode);
+ m_cache.nodeForScopedStyles = scopingNode;
+}
+
+void ScopedStyleTree::pushStyleCache(const ContainerNode& scopingNode, const ContainerNode* parent)
+{
+ if (m_authorStyles.isEmpty())
+ return;
+
+ if (!cacheIsValid(parent)) {
+ resolveStyleCache(&scopingNode);
+ return;
+ }
+
+ ScopedStyleResolver* scopedResolver = scopedStyleResolverFor(scopingNode);
+ if (scopedResolver)
+ m_cache.scopedResolver = scopedResolver;
+ m_cache.nodeForScopedStyles = &scopingNode;
+}
+
+void ScopedStyleTree::popStyleCache(const ContainerNode& scopingNode)
+{
+ if (!cacheIsValid(&scopingNode))
+ return;
+
+ if (m_cache.scopedResolver && m_cache.scopedResolver->scopingNode() == scopingNode)
+ m_cache.scopedResolver = m_cache.scopedResolver->parent();
+ m_cache.nodeForScopedStyles = scopingNode.parentOrShadowHostNode();
+}
+
+void ScopedStyleTree::collectFeaturesTo(RuleFeatureSet& features)
+{
+ for (HashMap<const ContainerNode*, OwnPtr<ScopedStyleResolver> >::iterator it = m_authorStyles.begin(); it != m_authorStyles.end(); ++it)
+ it->value->collectFeaturesTo(features);
+}
+
+inline void ScopedStyleTree::reparentNodes(const ScopedStyleResolver* oldParent, ScopedStyleResolver* newParent)
+{
+ // FIXME: this takes O(N) (N = number of all scoping nodes).
+ for (HashMap<const ContainerNode*, OwnPtr<ScopedStyleResolver> >::iterator it = m_authorStyles.begin(); it != m_authorStyles.end(); ++it) {
+ if (it->value->parent() == oldParent)
+ it->value->setParent(newParent);
+ }
+}
+
+void ScopedStyleTree::remove(const ContainerNode* scopingNode)
+{
+ if (!scopingNode || scopingNode->isDocumentNode())
+ return;
+
+ ScopedStyleResolver* resolverRemoved = lookupScopedStyleResolverFor(scopingNode);
+ if (!resolverRemoved)
+ return;
+
+ reparentNodes(resolverRemoved, resolverRemoved->parent());
+ if (m_cache.scopedResolver == resolverRemoved)
+ m_cache.clear();
+
+ m_authorStyles.remove(scopingNode);
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/css/resolver/ScopedStyleTree.h b/chromium/third_party/WebKit/Source/core/css/resolver/ScopedStyleTree.h
new file mode 100644
index 00000000000..51f68fe70d7
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/css/resolver/ScopedStyleTree.h
@@ -0,0 +1,108 @@
+/*
+ * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
+ * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
+ * Copyright (C) 2012 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef ScopedStyleTree_h
+#define ScopedStyleTree_h
+
+#include "core/css/resolver/ScopedStyleResolver.h"
+#include "wtf/HashMap.h"
+#include "wtf/OwnPtr.h"
+#include "wtf/Vector.h"
+
+namespace WebCore {
+
+class ScopedStyleTree {
+ WTF_MAKE_NONCOPYABLE(ScopedStyleTree); WTF_MAKE_FAST_ALLOCATED;
+public:
+ ScopedStyleTree() : m_scopedResolverForDocument(0), m_buildInDocumentOrder(true) { }
+
+ ScopedStyleResolver* ensureScopedStyleResolver(ContainerNode& scopingNode);
+ ScopedStyleResolver* lookupScopedStyleResolverFor(const ContainerNode* scopingNode)
+ {
+ HashMap<const ContainerNode*, OwnPtr<ScopedStyleResolver> >::iterator it = m_authorStyles.find(scopingNode);
+ return it != m_authorStyles.end() ? it->value.get() : 0;
+ }
+
+ ScopedStyleResolver* scopedStyleResolverFor(const ContainerNode& scopingNode);
+ ScopedStyleResolver* addScopedStyleResolver(ContainerNode& scopingNode, bool& isNewEntry);
+ void clear();
+
+ // for fast-path.
+ bool hasOnlyScopedResolverForDocument() const { return m_scopedResolverForDocument && m_authorStyles.size() == 1; }
+ ScopedStyleResolver* scopedStyleResolverForDocument() const { return m_scopedResolverForDocument; }
+
+ void resolveScopedStyles(const Element*, Vector<ScopedStyleResolver*, 8>&);
+ void collectScopedResolversForHostedShadowTrees(const Element*, Vector<ScopedStyleResolver*, 8>&);
+ void resolveScopedKeyframesRules(const Element*, Vector<ScopedStyleResolver*, 8>&);
+ ScopedStyleResolver* scopedResolverFor(const Element*);
+
+ void remove(const ContainerNode* scopingNode);
+
+ void pushStyleCache(const ContainerNode& scopingNode, const ContainerNode* parent);
+ void popStyleCache(const ContainerNode& scopingNode);
+
+ void collectFeaturesTo(RuleFeatureSet& features);
+ void setBuildInDocumentOrder(bool enabled) { m_buildInDocumentOrder = enabled; }
+ bool buildInDocumentOrder() const { return m_buildInDocumentOrder; }
+
+private:
+ void setupScopedStylesTree(ScopedStyleResolver* target);
+
+ bool cacheIsValid(const ContainerNode* parent) const { return parent && parent == m_cache.nodeForScopedStyles; }
+ void resolveStyleCache(const ContainerNode* scopingNode);
+ ScopedStyleResolver* enclosingScopedStyleResolverFor(const ContainerNode* scopingNode);
+
+ void reparentNodes(const ScopedStyleResolver* oldParent, ScopedStyleResolver* newParent);
+
+private:
+ HashMap<const ContainerNode*, OwnPtr<ScopedStyleResolver> > m_authorStyles;
+ ScopedStyleResolver* m_scopedResolverForDocument;
+ bool m_buildInDocumentOrder;
+
+ struct ScopedStyleCache {
+ ScopedStyleResolver* scopedResolver;
+ const ContainerNode* nodeForScopedStyles;
+
+ void clear()
+ {
+ scopedResolver = 0;
+ nodeForScopedStyles = 0;
+ }
+ };
+ ScopedStyleCache m_cache;
+};
+
+inline ScopedStyleResolver* ScopedStyleTree::scopedResolverFor(const Element* element)
+{
+ if (!cacheIsValid(element))
+ resolveStyleCache(element);
+
+ return m_cache.scopedResolver;
+}
+
+} // namespace WebCore
+
+#endif // ScopedStyleTree_h
diff --git a/chromium/third_party/WebKit/Source/core/css/resolver/SharedStyleFinder.cpp b/chromium/third_party/WebKit/Source/core/css/resolver/SharedStyleFinder.cpp
index aad32e73e01..92890d6c3af 100644
--- a/chromium/third_party/WebKit/Source/core/css/resolver/SharedStyleFinder.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/resolver/SharedStyleFinder.cpp
@@ -32,10 +32,9 @@
#include "HTMLNames.h"
#include "XMLNames.h"
#include "core/css/resolver/StyleResolver.h"
-#include "core/css/resolver/StyleResolverState.h"
+#include "core/css/resolver/StyleResolverStats.h"
#include "core/dom/ContainerNode.h"
#include "core/dom/Document.h"
-#include "core/dom/Element.h"
#include "core/dom/ElementTraversal.h"
#include "core/dom/FullscreenElementStack.h"
#include "core/dom/Node.h"
@@ -46,7 +45,6 @@
#include "core/html/HTMLElement.h"
#include "core/html/HTMLInputElement.h"
#include "core/html/HTMLOptGroupElement.h"
-#include "core/html/track/WebVTTElement.h"
#include "core/rendering/style/RenderStyle.h"
#include "core/svg/SVGElement.h"
#include "wtf/HashSet.h"
@@ -56,53 +54,42 @@ namespace WebCore {
using namespace HTMLNames;
-static inline bool parentElementPreventsSharing(const Element* parentElement)
+bool SharedStyleFinder::canShareStyleWithControl(Element& candidate) const
{
- return parentElement->hasFlagsSetDuringStylingOfChildren();
-}
-
-bool SharedStyleFinder::canShareStyleWithControl(const ElementResolveContext& context, Element* element) const
-{
- if (!element->hasTagName(inputTag) || !context.element()->hasTagName(inputTag))
+ if (!candidate.hasTagName(inputTag) || !element().hasTagName(inputTag))
return false;
- HTMLInputElement* thisInputElement = toHTMLInputElement(element);
- HTMLInputElement* otherInputElement = toHTMLInputElement(context.element());
- if (thisInputElement->elementData() != otherInputElement->elementData()) {
- if (thisInputElement->fastGetAttribute(typeAttr) != otherInputElement->fastGetAttribute(typeAttr))
- return false;
- if (thisInputElement->fastGetAttribute(readonlyAttr) != otherInputElement->fastGetAttribute(readonlyAttr))
- return false;
- }
+ HTMLInputElement& candidateInput = toHTMLInputElement(candidate);
+ HTMLInputElement& thisInput = toHTMLInputElement(element());
- if (thisInputElement->isAutofilled() != otherInputElement->isAutofilled())
+ if (candidateInput.isAutofilled() != thisInput.isAutofilled())
return false;
- if (thisInputElement->shouldAppearChecked() != otherInputElement->shouldAppearChecked())
+ if (candidateInput.shouldAppearChecked() != thisInput.shouldAppearChecked())
return false;
- if (thisInputElement->shouldAppearIndeterminate() != otherInputElement->shouldAppearIndeterminate())
+ if (candidateInput.shouldAppearIndeterminate() != thisInput.shouldAppearIndeterminate())
return false;
- if (thisInputElement->isRequired() != otherInputElement->isRequired())
+ if (candidateInput.isRequired() != thisInput.isRequired())
return false;
- if (element->isDisabledFormControl() != context.element()->isDisabledFormControl())
+ if (candidate.isDisabledFormControl() != element().isDisabledFormControl())
return false;
- if (element->isDefaultButtonForForm() != context.element()->isDefaultButtonForForm())
+ if (candidate.isDefaultButtonForForm() != element().isDefaultButtonForForm())
return false;
- if (context.document().containsValidityStyleRules()) {
- bool willValidate = element->willValidate();
+ if (document().containsValidityStyleRules()) {
+ bool willValidate = candidate.willValidate();
- if (willValidate != context.element()->willValidate())
+ if (willValidate != element().willValidate())
return false;
- if (willValidate && (element->isValidFormControlElement() != context.element()->isValidFormControlElement()))
+ if (willValidate && (candidate.isValidFormControlElement() != element().isValidFormControlElement()))
return false;
- if (element->isInRange() != context.element()->isInRange())
+ if (candidate.isInRange() != element().isInRange())
return false;
- if (element->isOutOfRange() != context.element()->isOutOfRange())
+ if (candidate.isOutOfRange() != element().isOutOfRange())
return false;
}
@@ -111,146 +98,129 @@ bool SharedStyleFinder::canShareStyleWithControl(const ElementResolveContext& co
bool SharedStyleFinder::classNamesAffectedByRules(const SpaceSplitString& classNames) const
{
- for (unsigned i = 0; i < classNames.size(); ++i) {
- if (m_features.classesInRules.contains(classNames[i].impl()))
+ unsigned count = classNames.size();
+ for (unsigned i = 0; i < count; ++i) {
+ if (m_features.classesInRules.contains(classNames[i]))
return true;
}
return false;
}
-static inline bool elementHasDirectionAuto(Element* element)
+static inline const AtomicString& typeAttributeValue(const Element& element)
{
- // FIXME: This line is surprisingly hot, we may wish to inline hasDirectionAuto into StyleResolver.
- return element->isHTMLElement() && toHTMLElement(element)->hasDirectionAuto();
+ // type is animatable in SVG so we need to go down the slow path here.
+ return element.isSVGElement() ? element.getAttribute(typeAttr) : element.fastGetAttribute(typeAttr);
}
-bool SharedStyleFinder::sharingCandidateHasIdenticalStyleAffectingAttributes(const ElementResolveContext& context, Element* sharingCandidate) const
+bool SharedStyleFinder::sharingCandidateHasIdenticalStyleAffectingAttributes(Element& candidate) const
{
- if (context.element()->elementData() == sharingCandidate->elementData())
+ if (element().elementData() == candidate.elementData())
return true;
- if (context.element()->fastGetAttribute(XMLNames::langAttr) != sharingCandidate->fastGetAttribute(XMLNames::langAttr))
+ if (element().fastGetAttribute(XMLNames::langAttr) != candidate.fastGetAttribute(XMLNames::langAttr))
+ return false;
+ if (element().fastGetAttribute(langAttr) != candidate.fastGetAttribute(langAttr))
+ return false;
+
+ // These two checks must be here since RuleSet has a specail case to allow style sharing between elements
+ // with type and readonly attributes whereas other attribute selectors prevent sharing.
+ if (typeAttributeValue(element()) != typeAttributeValue(candidate))
return false;
- if (context.element()->fastGetAttribute(langAttr) != sharingCandidate->fastGetAttribute(langAttr))
+ if (element().fastGetAttribute(readonlyAttr) != candidate.fastGetAttribute(readonlyAttr))
return false;
if (!m_elementAffectedByClassRules) {
- if (sharingCandidate->hasClass() && classNamesAffectedByRules(sharingCandidate->classNames()))
+ if (candidate.hasClass() && classNamesAffectedByRules(candidate.classNames()))
return false;
- } else if (sharingCandidate->hasClass()) {
+ } else if (candidate.hasClass()) {
// SVG elements require a (slow!) getAttribute comparision because "class" is an animatable attribute for SVG.
- if (context.element()->isSVGElement()) {
- if (context.element()->getAttribute(classAttr) != sharingCandidate->getAttribute(classAttr))
+ if (element().isSVGElement()) {
+ if (element().getAttribute(classAttr) != candidate.getAttribute(classAttr))
return false;
- } else if (context.element()->classNames() != sharingCandidate->classNames()) {
+ } else if (element().classNames() != candidate.classNames()) {
return false;
}
} else {
return false;
}
- if (context.element()->presentationAttributeStyle() != sharingCandidate->presentationAttributeStyle())
+ if (element().presentationAttributeStyle() != candidate.presentationAttributeStyle())
return false;
- if (context.element()->hasTagName(progressTag)) {
- if (context.element()->shouldAppearIndeterminate() != sharingCandidate->shouldAppearIndeterminate())
+ // FIXME: Consider removing this, it's unlikely we'll have so many progress elements
+ // that sharing the style makes sense. Instead we should just not support style sharing
+ // for them.
+ if (element().hasTagName(progressTag)) {
+ if (element().shouldAppearIndeterminate() != candidate.shouldAppearIndeterminate())
return false;
}
return true;
}
-bool SharedStyleFinder::canShareStyleWithElement(const ElementResolveContext& context, Element* element) const
+bool SharedStyleFinder::canShareStyleWithElement(Element& candidate) const
{
- if (context.element() == element)
+ if (element() == candidate)
return false;
- Element* parent = element->parentElement();
- RenderStyle* style = element->renderStyle();
+ Element* parent = candidate.parentElement();
+ RenderStyle* style = candidate.renderStyle();
if (!style)
return false;
- if (!parent)
- return false;
- if (context.element()->parentElement()->renderStyle() != parent->renderStyle())
+ if (!style->isSharable())
return false;
- if (style->unique())
+ if (!parent)
return false;
- if (style->hasUniquePseudoStyle())
+ if (element().parentElement()->renderStyle() != parent->renderStyle())
return false;
- if (element->tagQName() != context.element()->tagQName())
+ if (candidate.tagQName() != element().tagQName())
return false;
- if (element->inlineStyle())
+ if (candidate.inlineStyle())
return false;
- if (element->needsStyleRecalc())
+ if (candidate.needsStyleRecalc())
return false;
- if (element->isSVGElement() && toSVGElement(element)->animatedSMILStyleProperties())
+ if (candidate.isSVGElement() && toSVGElement(candidate).animatedSMILStyleProperties())
return false;
- if (element->isLink() != context.element()->isLink())
+ if (candidate.isLink() != element().isLink())
return false;
- if (element->hovered() != context.element()->hovered())
+ if (candidate.hovered() != element().hovered())
return false;
- if (element->active() != context.element()->active())
+ if (candidate.active() != element().active())
return false;
- if (element->focused() != context.element()->focused())
+ if (candidate.focused() != element().focused())
return false;
- if (element->shadowPseudoId() != context.element()->shadowPseudoId())
+ if (candidate.shadowPseudoId() != element().shadowPseudoId())
return false;
- if (element == element->document().cssTarget())
+ if (candidate == document().cssTarget())
return false;
- if (!sharingCandidateHasIdenticalStyleAffectingAttributes(context, element))
+ if (!sharingCandidateHasIdenticalStyleAffectingAttributes(candidate))
return false;
- if (element->additionalPresentationAttributeStyle() != context.element()->additionalPresentationAttributeStyle())
+ if (candidate.additionalPresentationAttributeStyle() != element().additionalPresentationAttributeStyle())
return false;
-
- if (element->hasID() && m_features.idsInRules.contains(element->idForStyleResolution().impl()))
+ if (candidate.hasID() && m_features.idsInRules.contains(candidate.idForStyleResolution()))
return false;
- if (element->hasScopedHTMLStyleChild())
+ if (candidate.hasScopedHTMLStyleChild())
return false;
- if (isShadowHost(element) && element->shadow()->containsActiveStyles())
+ if (candidate.shadow() && candidate.shadow()->containsActiveStyles())
return 0;
- // FIXME: We should share style for option and optgroup whenever possible.
- // Before doing so, we need to resolve issues in HTMLSelectElement::recalcListItems
- // and RenderMenuList::setText. See also https://bugs.webkit.org/show_bug.cgi?id=88405
- if (element->hasTagName(optionTag) || isHTMLOptGroupElement(element))
- return false;
-
- bool isControl = element->isFormControlElement();
-
- if (isControl != context.element()->isFormControlElement())
- return false;
+ bool isControl = candidate.isFormControlElement();
- if (isControl && !canShareStyleWithControl(context, element))
+ if (isControl != element().isFormControlElement())
return false;
- if (style->transitions() || style->animations())
+ if (isControl && !canShareStyleWithControl(candidate))
return false;
- // Turn off style sharing for elements that can gain layers for reasons outside of the style system.
- // See comments in RenderObject::setStyle().
- if (element->hasTagName(iframeTag) || element->hasTagName(frameTag) || element->hasTagName(embedTag) || element->hasTagName(objectTag) || element->hasTagName(appletTag) || element->hasTagName(canvasTag))
- return false;
-
- if (elementHasDirectionAuto(element))
- return false;
-
- if (element->isLink() && context.elementLinkState() != style->insideLink())
- return false;
-
- if (element->isUnresolvedCustomElement() != context.element()->isUnresolvedCustomElement())
+ // FIXME: This line is surprisingly hot, we may wish to inline hasDirectionAuto into StyleResolver.
+ if (candidate.isHTMLElement() && toHTMLElement(candidate).hasDirectionAuto())
return false;
- // Deny sharing styles between WebVTT and non-WebVTT nodes.
- if (element->isWebVTTElement() != context.element()->isWebVTTElement())
+ if (candidate.isLink() && m_context.elementLinkState() != style->insideLink())
return false;
- if (element->isWebVTTElement() && context.element()->isWebVTTElement() && toWebVTTElement(element)->isPastNode() != toWebVTTElement(context.element())->isPastNode())
+ if (candidate.isUnresolvedCustomElement() != element().isUnresolvedCustomElement())
return false;
- if (FullscreenElementStack* fullscreen = FullscreenElementStack::fromIfExists(&context.document())) {
- if (element == fullscreen->webkitCurrentFullScreenElement() || context.element() == fullscreen->webkitCurrentFullScreenElement())
- return false;
- }
-
- if (context.element()->parentElement() != parent) {
+ if (element().parentElement() != parent) {
if (!parent->isStyledElement())
return false;
if (parent->hasScopedHTMLStyleChild())
@@ -259,86 +229,86 @@ bool SharedStyleFinder::canShareStyleWithElement(const ElementResolveContext& co
return false;
if (parent->isSVGElement() && toSVGElement(parent)->animatedSMILStyleProperties())
return false;
- if (parent->hasID() && m_features.idsInRules.contains(parent->idForStyleResolution().impl()))
+ if (parent->hasID() && m_features.idsInRules.contains(parent->idForStyleResolution()))
return false;
- if (parentElementPreventsSharing(parent))
+ if (!parent->childrenSupportStyleSharing())
return false;
}
return true;
}
-#ifdef STYLE_STATS
-Element* SharedStyleFinder::searchDocumentForSharedStyle(const ElementResolveContext& context) const
+bool SharedStyleFinder::documentContainsValidCandidate() const
{
- for (Element* element = context.element()->document().documentElement(); element; element = ElementTraversal::next(element)) {
- if (canShareStyleWithElement(context, element))
- return element;
+ for (Element* element = document().documentElement(); element; element = ElementTraversal::next(*element)) {
+ if (element->supportsStyleSharing() && canShareStyleWithElement(*element))
+ return true;
}
- return 0;
+ return false;
}
-#endif
-inline Element* SharedStyleFinder::findElementForStyleSharing(const ElementResolveContext& context) const
+inline Element* SharedStyleFinder::findElementForStyleSharing() const
{
- StyleSharingList& styleSharingList = m_styleResolver->styleSharingList();
+ StyleSharingList& styleSharingList = m_styleResolver.styleSharingList();
for (StyleSharingList::iterator it = styleSharingList.begin(); it != styleSharingList.end(); ++it) {
- if (!canShareStyleWithElement(context, it->get()))
+ Element& candidate = **it;
+ if (!canShareStyleWithElement(candidate))
continue;
- Element* element = it->get();
if (it != styleSharingList.begin()) {
// Move the element to the front of the LRU
styleSharingList.remove(it);
- styleSharingList.prepend(element);
+ styleSharingList.prepend(&candidate);
}
- return element;
+ return &candidate;
}
- m_styleResolver->addToStyleSharingList(context.element());
+ m_styleResolver.addToStyleSharingList(element());
return 0;
}
-RenderStyle* SharedStyleFinder::locateSharedStyle(const ElementResolveContext& context, RenderStyle* newStyle)
+bool SharedStyleFinder::matchesRuleSet(RuleSet* ruleSet)
{
- STYLE_STATS_ADD_SEARCH();
+ if (!ruleSet)
+ return false;
+ ElementRuleCollector collector(m_context, m_styleResolver.selectorFilter());
+ return collector.hasAnyMatchingRules(ruleSet);
+}
- if (!m_styleResolver->supportsStyleSharing(context.element()))
- return 0;
+RenderStyle* SharedStyleFinder::findSharedStyle()
+{
+ INCREMENT_STYLE_STATS_COUNTER(m_styleResolver, sharedStyleLookups);
- STYLE_STATS_ADD_ELEMENT_ELIGIBLE_FOR_SHARING();
+ if (!element().supportsStyleSharing())
+ return 0;
// Cache whether context.element() is affected by any known class selectors.
- // FIXME: This should be an explicit out parameter, instead of a member variable.
- m_elementAffectedByClassRules = context.element() && context.element()->hasClass() && classNamesAffectedByRules(context.element()->classNames());
+ m_elementAffectedByClassRules = element().hasClass() && classNamesAffectedByRules(element().classNames());
- Element* shareElement = findElementForStyleSharing(context);
+ Element* shareElement = findElementForStyleSharing();
-#ifdef STYLE_STATS
- // FIXME: these stats don't to into account whether or not sibling/attribute
- // rules prevent these nodes from actually sharing
- if (shareElement) {
- STYLE_STATS_ADD_SEARCH_FOUND_SIBLING_FOR_SHARING();
- } else {
- shareElement = searchDocumentForSharedStyle(context);
- if (shareElement)
- STYLE_STATS_ADD_SEARCH_MISSED_SHARING();
- shareElement = 0;
+ if (!shareElement) {
+ if (m_styleResolver.stats() && m_styleResolver.stats()->printMissedCandidateCount && documentContainsValidCandidate())
+ INCREMENT_STYLE_STATS_COUNTER(m_styleResolver, sharedStyleMissed);
+ return 0;
}
-#endif
- // If we have exhausted all our budget or our cousins.
- if (!shareElement)
- return 0;
+ INCREMENT_STYLE_STATS_COUNTER(m_styleResolver, sharedStyleFound);
- // Can't share if sibling rules apply. This is checked at the end as it should rarely fail.
- if (m_styleResolver->styleSharingCandidateMatchesRuleSet(context, newStyle, m_siblingRuleSet))
+ if (matchesRuleSet(m_siblingRuleSet)) {
+ INCREMENT_STYLE_STATS_COUNTER(m_styleResolver, sharedStyleRejectedBySiblingRules);
return 0;
- // Can't share if attribute rules apply.
- if (m_styleResolver->styleSharingCandidateMatchesRuleSet(context, newStyle, m_uncommonAttributeRuleSet))
+ }
+
+ if (matchesRuleSet(m_uncommonAttributeRuleSet)) {
+ INCREMENT_STYLE_STATS_COUNTER(m_styleResolver, sharedStyleRejectedByUncommonAttributeRules);
return 0;
+ }
+
// Tracking child index requires unique style for each node. This may get set by the sibling rule match above.
- if (parentElementPreventsSharing(context.element()->parentElement()))
+ if (!element().parentElement()->childrenSupportStyleSharing()) {
+ INCREMENT_STYLE_STATS_COUNTER(m_styleResolver, sharedStyleRejectedByParent);
return 0;
- STYLE_STATS_ADD_STYLE_SHARED();
+ }
+
return shareElement->renderStyle();
}
diff --git a/chromium/third_party/WebKit/Source/core/css/resolver/SharedStyleFinder.h b/chromium/third_party/WebKit/Source/core/css/resolver/SharedStyleFinder.h
index d407279a588..e65c5c07cd0 100644
--- a/chromium/third_party/WebKit/Source/core/css/resolver/SharedStyleFinder.h
+++ b/chromium/third_party/WebKit/Source/core/css/resolver/SharedStyleFinder.h
@@ -22,10 +22,12 @@
#ifndef SharedStyleFinder_h
#define SharedStyleFinder_h
+#include "core/css/resolver/ElementResolveContext.h"
+#include "core/dom/Element.h"
+
namespace WebCore {
class Element;
-class ElementResolveContext;
class Node;
class RenderStyle;
class RuleFeatureSet;
@@ -35,38 +37,43 @@ class StyleResolver;
class SharedStyleFinder {
public:
- // FIXME: StyleResolver* only used for calling styleSharingCandidateMatchesRuleSet.
// RuleSets are passed non-const as the act of matching against them can cause them
// to be compacted. :(
- SharedStyleFinder(const RuleFeatureSet& features, RuleSet* siblingRuleSet,
- RuleSet* uncommonAttributeRuleSet, StyleResolver* styleResolver)
+ SharedStyleFinder(const ElementResolveContext& context,
+ const RuleFeatureSet& features, RuleSet* siblingRuleSet,
+ RuleSet* uncommonAttributeRuleSet, StyleResolver& styleResolver)
: m_elementAffectedByClassRules(false)
, m_features(features)
, m_siblingRuleSet(siblingRuleSet)
, m_uncommonAttributeRuleSet(uncommonAttributeRuleSet)
, m_styleResolver(styleResolver)
+ , m_context(context)
{ }
- // FIXME: It is not necessarily safe to call this method more than once.
- RenderStyle* locateSharedStyle(const ElementResolveContext&, RenderStyle* newStyle);
+ RenderStyle* findSharedStyle();
private:
- Element* findElementForStyleSharing(const ElementResolveContext&) const;
+ Element* findElementForStyleSharing() const;
- // Only used when we're collecting stats on styles
- Element* searchDocumentForSharedStyle(const ElementResolveContext&) const;
+ // Only used when we're collecting stats on styles.
+ bool documentContainsValidCandidate() const;
bool classNamesAffectedByRules(const SpaceSplitString&) const;
- bool canShareStyleWithElement(const ElementResolveContext&, Element*) const;
- bool canShareStyleWithControl(const ElementResolveContext&, Element*) const;
- bool sharingCandidateHasIdenticalStyleAffectingAttributes(const ElementResolveContext&, Element*) const;
+ bool canShareStyleWithElement(Element& candidate) const;
+ bool canShareStyleWithControl(Element& candidate) const;
+ bool sharingCandidateHasIdenticalStyleAffectingAttributes(Element& candidate) const;
+ bool matchesRuleSet(RuleSet*);
+
+ Element& element() const { return *m_context.element(); }
+ Document& document() const { return element().document(); }
bool m_elementAffectedByClassRules;
const RuleFeatureSet& m_features;
RuleSet* m_siblingRuleSet;
RuleSet* m_uncommonAttributeRuleSet;
- StyleResolver* m_styleResolver;
+ StyleResolver& m_styleResolver;
+ const ElementResolveContext& m_context;
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/css/resolver/StyleAdjuster.cpp b/chromium/third_party/WebKit/Source/core/css/resolver/StyleAdjuster.cpp
index 10f572ff437..4b1fe76c082 100644
--- a/chromium/third_party/WebKit/Source/core/css/resolver/StyleAdjuster.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/resolver/StyleAdjuster.cpp
@@ -39,15 +39,14 @@
#include "core/html/HTMLInputElement.h"
#include "core/html/HTMLTableElement.h"
#include "core/html/HTMLTextAreaElement.h"
-#include "core/page/FrameView.h"
-#include "core/page/Page.h"
-#include "core/page/Settings.h"
-#include "core/platform/Length.h"
+#include "core/frame/FrameView.h"
+#include "core/frame/Settings.h"
#include "core/rendering/Pagination.h"
#include "core/rendering/RenderTheme.h"
#include "core/rendering/style/GridPosition.h"
#include "core/rendering/style/RenderStyle.h"
#include "core/rendering/style/RenderStyleConstants.h"
+#include "platform/Length.h"
#include "wtf/Assertions.h"
namespace WebCore {
@@ -112,8 +111,6 @@ static EDisplay equivalentBlockDisplay(EDisplay display, bool isFloating, bool s
return GRID;
case INLINE:
- case RUN_IN:
- case COMPACT:
case INLINE_BLOCK:
case TABLE_ROW_GROUP:
case TABLE_HEADER_GROUP:
@@ -133,11 +130,11 @@ static EDisplay equivalentBlockDisplay(EDisplay display, bool isFloating, bool s
}
// CSS requires text-decoration to be reset at each DOM element for tables,
-// inline blocks, inline tables, run-ins, shadow DOM crossings, floating elements,
+// inline blocks, inline tables, shadow DOM crossings, floating elements,
// and absolute or relatively positioned elements.
static bool doesNotInheritTextDecoration(const RenderStyle* style, const Element* e)
{
- return style->display() == TABLE || style->display() == INLINE_TABLE || style->display() == RUN_IN
+ return style->display() == TABLE || style->display() == INLINE_TABLE
|| style->display() == INLINE_BLOCK || style->display() == INLINE_BOX || isAtShadowBoundary(e)
|| style->isFloating() || style->hasOutOfFlowPosition();
}
@@ -277,9 +274,11 @@ void StyleAdjuster::adjustRenderStyle(RenderStyle* style, RenderStyle* parentSty
|| style->boxReflect()
|| style->hasFilter()
|| style->hasBlendMode()
+ || style->hasIsolation()
|| style->position() == StickyPosition
- || (style->position() == FixedPosition && e && e->document().page() && e->document().page()->settings().fixedPositionCreatesStackingContext())
+ || (style->position() == FixedPosition && e && e->document().settings() && e->document().settings()->fixedPositionCreatesStackingContext())
|| isInTopLayer(e, style)
+ || style->hasFlowFrom()
))
style->setZIndex(0);
@@ -336,10 +335,6 @@ void StyleAdjuster::adjustRenderStyle(RenderStyle* style, RenderStyle* parentSty
style->adjustBackgroundLayers();
style->adjustMaskLayers();
- // Do the same for animations and transitions.
- style->adjustAnimations();
- style->adjustTransitions();
-
// Important: Intrinsic margins get added to controls before the theme has adjusted the style, since the theme will
// alter fonts and heights/widths.
if (e && e->isFormControlElement() && style->fontSize() >= 11) {
@@ -389,6 +384,10 @@ void StyleAdjuster::adjustRenderStyle(RenderStyle* style, RenderStyle* parentSty
// not be scaled again.
if (e->hasTagName(SVGNames::foreignObjectTag))
style->setEffectiveZoom(RenderStyle::initialZoom());
+
+ // SVG text layout code expects us to be a block-level style element.
+ if ((e->hasTagName(SVGNames::foreignObjectTag) || e->hasTagName(SVGNames::textTag)) && style->isDisplayInlineType())
+ style->setDisplay(BLOCK);
}
}
diff --git a/chromium/third_party/WebKit/Source/core/css/resolver/StyleBuilderConverter.cpp b/chromium/third_party/WebKit/Source/core/css/resolver/StyleBuilderConverter.cpp
new file mode 100644
index 00000000000..d3ffb158dce
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/css/resolver/StyleBuilderConverter.cpp
@@ -0,0 +1,174 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/css/resolver/StyleBuilderConverter.h"
+
+#include "core/css/CSSPrimitiveValueMappings.h"
+#include "core/css/CSSShadowValue.h"
+#include "core/css/Pair.h"
+#include "core/svg/SVGURIReference.h"
+
+namespace WebCore {
+
+String StyleBuilderConverter::convertFragmentIdentifier(StyleResolverState& state, CSSValue* value)
+{
+ CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
+ if (primitiveValue->isURI())
+ return SVGURIReference::fragmentIdentifierFromIRIString(primitiveValue->getStringValue(), state.document());
+ return String();
+}
+
+Length StyleBuilderConverter::convertLength(StyleResolverState& state, CSSValue* value)
+{
+ CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
+ Length result = primitiveValue->convertToLength<FixedConversion | PercentConversion>(state.cssToLengthConversionData());
+ ASSERT(!result.isUndefined());
+ result.setQuirk(primitiveValue->isQuirkValue());
+ return result;
+}
+
+Length StyleBuilderConverter::convertLengthOrAuto(StyleResolverState& state, CSSValue* value)
+{
+ CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
+ Length result = primitiveValue->convertToLength<FixedConversion | PercentConversion | AutoConversion>(state.cssToLengthConversionData());
+ ASSERT(!result.isUndefined());
+ result.setQuirk(primitiveValue->isQuirkValue());
+ return result;
+}
+
+Length StyleBuilderConverter::convertLengthSizing(StyleResolverState& state, CSSValue* value)
+{
+ CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
+ switch (primitiveValue->getValueID()) {
+ case CSSValueInvalid:
+ return convertLength(state, value);
+ case CSSValueIntrinsic:
+ return Length(Intrinsic);
+ case CSSValueMinIntrinsic:
+ return Length(MinIntrinsic);
+ case CSSValueWebkitMinContent:
+ return Length(MinContent);
+ case CSSValueWebkitMaxContent:
+ return Length(MaxContent);
+ case CSSValueWebkitFillAvailable:
+ return Length(FillAvailable);
+ case CSSValueWebkitFitContent:
+ return Length(FitContent);
+ case CSSValueAuto:
+ return Length(Auto);
+ default:
+ ASSERT_NOT_REACHED();
+ return Length();
+ }
+}
+
+Length StyleBuilderConverter::convertLengthMaxSizing(StyleResolverState& state, CSSValue* value)
+{
+ CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
+ if (primitiveValue->getValueID() == CSSValueNone)
+ return Length(Undefined);
+ return convertLengthSizing(state, value);
+}
+
+LengthPoint StyleBuilderConverter::convertLengthPoint(StyleResolverState& state, CSSValue* value)
+{
+ CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
+ Pair* pair = primitiveValue->getPairValue();
+ Length x = pair->first()->convertToLength<FixedConversion | PercentConversion>(state.cssToLengthConversionData());
+ Length y = pair->second()->convertToLength<FixedConversion | PercentConversion>(state.cssToLengthConversionData());
+ return LengthPoint(x, y);
+}
+
+float StyleBuilderConverter::convertNumberOrPercentage(StyleResolverState& state, CSSValue* value)
+{
+ CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
+ ASSERT(primitiveValue->isNumber() || primitiveValue->isPercentage());
+ if (primitiveValue->isNumber())
+ return primitiveValue->getFloatValue();
+ return primitiveValue->getFloatValue() / 100.0f;
+}
+
+LengthSize StyleBuilderConverter::convertRadius(StyleResolverState& state, CSSValue* value)
+{
+ CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
+ Pair* pair = primitiveValue->getPairValue();
+ Length radiusWidth = pair->first()->convertToLength<FixedConversion | PercentConversion>(state.cssToLengthConversionData());
+ Length radiusHeight = pair->second()->convertToLength<FixedConversion | PercentConversion>(state.cssToLengthConversionData());
+ float width = radiusWidth.value();
+ float height = radiusHeight.value();
+ ASSERT(width >= 0 && height >= 0);
+ if (width <= 0 || height <= 0)
+ return LengthSize(Length(0, Fixed), Length(0, Fixed));
+ return LengthSize(radiusWidth, radiusHeight);
+}
+
+PassRefPtr<ShadowList> StyleBuilderConverter::convertShadow(StyleResolverState& state, CSSValue* value)
+{
+ if (value->isPrimitiveValue()) {
+ ASSERT(toCSSPrimitiveValue(value)->getValueID() == CSSValueNone);
+ return PassRefPtr<ShadowList>();
+ }
+
+ const CSSValueList* valueList = toCSSValueList(value);
+ size_t shadowCount = valueList->length();
+ ShadowDataVector shadows;
+ for (size_t i = 0; i < shadowCount; ++i) {
+ const CSSShadowValue* item = toCSSShadowValue(valueList->item(i));
+ int x = item->x->computeLength<int>(state.cssToLengthConversionData());
+ int y = item->y->computeLength<int>(state.cssToLengthConversionData());
+ int blur = item->blur ? item->blur->computeLength<int>(state.cssToLengthConversionData()) : 0;
+ int spread = item->spread ? item->spread->computeLength<int>(state.cssToLengthConversionData()) : 0;
+ ShadowStyle shadowStyle = item->style && item->style->getValueID() == CSSValueInset ? Inset : Normal;
+ Color color;
+ if (item->color)
+ color = state.document().textLinkColors().colorFromPrimitiveValue(item->color.get(), state.style()->color());
+ else
+ color = state.style()->color();
+
+ if (!color.isValid())
+ color = Color::transparent;
+ shadows.append(ShadowData(IntPoint(x, y), blur, spread, shadowStyle, color));
+ }
+ return ShadowList::adopt(shadows);
+}
+
+float StyleBuilderConverter::convertSpacing(StyleResolverState& state, CSSValue* value)
+{
+ CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
+ if (primitiveValue->getValueID() == CSSValueNormal)
+ return 0;
+ if (state.useSVGZoomRules())
+ return primitiveValue->computeLength<float>(state.cssToLengthConversionData().copyWithAdjustedZoom(1));
+ return primitiveValue->computeLength<float>(state.cssToLengthConversionData());
+}
+
+SVGLength StyleBuilderConverter::convertSVGLength(StyleResolverState&, CSSValue* value)
+{
+ return SVGLength::fromCSSPrimitiveValue(toCSSPrimitiveValue(value));
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/css/resolver/StyleBuilderConverter.h b/chromium/third_party/WebKit/Source/core/css/resolver/StyleBuilderConverter.h
new file mode 100644
index 00000000000..12f03ecfdcc
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/css/resolver/StyleBuilderConverter.h
@@ -0,0 +1,104 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef StyleBuilderConverter_h
+#define StyleBuilderConverter_h
+
+#include "core/css/CSSValue.h"
+#include "core/css/resolver/StyleResolverState.h"
+#include "core/rendering/RenderView.h"
+#include "core/rendering/style/ShadowList.h"
+#include "core/svg/SVGLength.h"
+#include "platform/LengthSize.h"
+
+namespace WebCore {
+
+// Note that we assume the parser only allows valid CSSValue types.
+
+class StyleBuilderConverter {
+public:
+ static String convertFragmentIdentifier(StyleResolverState&, CSSValue*);
+ template <typename T> static T convertComputedLength(StyleResolverState&, CSSValue*);
+ template <typename T> static T convertLineWidth(StyleResolverState&, CSSValue*);
+ static Length convertLength(StyleResolverState&, CSSValue*);
+ static Length convertLengthOrAuto(StyleResolverState&, CSSValue*);
+ static Length convertLengthSizing(StyleResolverState&, CSSValue*);
+ static Length convertLengthMaxSizing(StyleResolverState&, CSSValue*);
+ static LengthPoint convertLengthPoint(StyleResolverState&, CSSValue*);
+ static float convertNumberOrPercentage(StyleResolverState&, CSSValue*);
+ static LengthSize convertRadius(StyleResolverState&, CSSValue*);
+ static PassRefPtr<ShadowList> convertShadow(StyleResolverState&, CSSValue*);
+ static float convertSpacing(StyleResolverState&, CSSValue*);
+ template <CSSValueID IdForNone> static AtomicString convertString(StyleResolverState&, CSSValue*);
+ static SVGLength convertSVGLength(StyleResolverState&, CSSValue*);
+};
+
+template <typename T>
+T StyleBuilderConverter::convertComputedLength(StyleResolverState& state, CSSValue* value)
+{
+ return toCSSPrimitiveValue(value)->computeLength<T>(state.cssToLengthConversionData());
+}
+
+template <typename T>
+T StyleBuilderConverter::convertLineWidth(StyleResolverState& state, CSSValue* value)
+{
+ CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
+ CSSValueID valueID = primitiveValue->getValueID();
+ if (valueID == CSSValueThin)
+ return 1;
+ if (valueID == CSSValueMedium)
+ return 3;
+ if (valueID == CSSValueThick)
+ return 5;
+ if (primitiveValue->isViewportPercentageLength())
+ return intValueForLength(primitiveValue->viewportPercentageLength(), 0, state.document().renderView());
+ if (valueID == CSSValueInvalid) {
+ // Any original result that was >= 1 should not be allowed to fall below 1.
+ // This keeps border lines from vanishing.
+ T result = primitiveValue->computeLength<T>(state.cssToLengthConversionData());
+ if (state.style()->effectiveZoom() < 1.0f && result < 1.0) {
+ T originalLength = primitiveValue->computeLength<T>(state.cssToLengthConversionData().copyWithAdjustedZoom(1.0));
+ if (originalLength >= 1.0)
+ return 1.0;
+ }
+ return result;
+ }
+ ASSERT_NOT_REACHED();
+ return 0;
+}
+
+template <CSSValueID IdForNone>
+AtomicString StyleBuilderConverter::convertString(StyleResolverState&, CSSValue* value)
+{
+ CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
+ if (primitiveValue->getValueID() == IdForNone)
+ return nullAtom;
+ return primitiveValue->getStringValue();
+}
+
+} // namespace WebCore
+
+#endif
diff --git a/chromium/third_party/WebKit/Source/core/css/resolver/StyleBuilderCustom.cpp b/chromium/third_party/WebKit/Source/core/css/resolver/StyleBuilderCustom.cpp
index 5f05ecab845..8f239d8cb64 100644..100755
--- a/chromium/third_party/WebKit/Source/core/css/resolver/StyleBuilderCustom.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/resolver/StyleBuilderCustom.cpp
@@ -37,18 +37,20 @@
*/
#include "config.h"
-#include "core/css/resolver/StyleBuilderCustom.h"
+#include "StyleBuilderFunctions.h"
#include "CSSPropertyNames.h"
#include "CSSValueKeywords.h"
-#include "StyleBuilderFunctions.h"
#include "StylePropertyShorthand.h"
#include "core/css/BasicShapeFunctions.h"
#include "core/css/CSSAspectRatioValue.h"
#include "core/css/CSSCursorImageValue.h"
+#include "core/css/CSSFontValue.h"
#include "core/css/CSSFunctionValue.h"
#include "core/css/CSSGradientValue.h"
+#include "core/css/CSSGridLineNamesValue.h"
#include "core/css/CSSGridTemplateValue.h"
+#include "core/css/CSSHelper.h"
#include "core/css/CSSImageSetValue.h"
#include "core/css/CSSLineBoxContainValue.h"
#include "core/css/CSSParser.h"
@@ -57,20 +59,16 @@
#include "core/css/CSSReflectValue.h"
#include "core/css/CSSVariableValue.h"
#include "core/css/Counter.h"
-#include "core/css/FontValue.h"
-#include "core/css/Pair.h"
#include "core/css/Rect.h"
-#include "core/css/ShadowValue.h"
#include "core/css/StylePropertySet.h"
+#include "core/css/StyleRule.h"
#include "core/css/resolver/ElementStyleResources.h"
#include "core/css/resolver/FilterOperationResolver.h"
#include "core/css/resolver/FontBuilder.h"
#include "core/css/resolver/StyleBuilder.h"
-#include "core/css/resolver/StyleResolverState.h"
#include "core/css/resolver/TransformBuilder.h"
-#include "core/page/Frame.h"
-#include "core/page/Settings.h"
-#include "core/platform/graphics/FontDescription.h"
+#include "core/frame/Frame.h"
+#include "core/frame/Settings.h"
#include "core/rendering/style/CounterContent.h"
#include "core/rendering/style/CursorList.h"
#include "core/rendering/style/QuotesData.h"
@@ -78,11 +76,10 @@
#include "core/rendering/style/RenderStyleConstants.h"
#include "core/rendering/style/SVGRenderStyle.h"
#include "core/rendering/style/SVGRenderStyleDefs.h"
-#include "core/rendering/style/ShadowData.h"
#include "core/rendering/style/StyleGeneratedImage.h"
#include "core/svg/SVGColor.h"
#include "core/svg/SVGPaint.h"
-#include "core/svg/SVGURIReference.h"
+#include "platform/fonts/FontDescription.h"
#include "wtf/MathExtras.h"
#include "wtf/StdLibExtras.h"
#include "wtf/Vector.h"
@@ -91,7 +88,7 @@ namespace WebCore {
static Length clipConvertToLength(StyleResolverState& state, CSSPrimitiveValue* value)
{
- return value->convertToLength<FixedIntegerConversion | PercentConversion | FractionConversion | AutoConversion>(state.style(), state.rootElementStyle(), state.style()->effectiveZoom());
+ return value->convertToLength<FixedConversion | PercentConversion | AutoConversion>(state.cssToLengthConversionData());
}
void StyleBuilderFunctions::applyInitialCSSPropertyClip(StyleResolverState& state)
@@ -151,7 +148,7 @@ void StyleBuilderFunctions::applyValueCSSPropertyCursor(StyleResolverState& stat
for (int i = 0; i < len; i++) {
CSSValue* item = list->itemWithoutBoundsCheck(i);
if (item->isCursorImageValue()) {
- CSSCursorImageValue* image = static_cast<CSSCursorImageValue*>(item);
+ CSSCursorImageValue* image = toCSSCursorImageValue(item);
if (image->updateIfSVGCursorIsUsed(state.element())) // Elements with SVG cursors are not allowed to share style.
state.style()->setUnique();
state.style()->addCursor(state.styleImage(CSSPropertyCursor, image), image->hotSpot());
@@ -275,18 +272,22 @@ void StyleBuilderFunctions::applyValueCSSPropertyLineHeight(StyleResolverState&
if (primitiveValue->getValueID() == CSSValueNormal) {
lineHeight = RenderStyle::initialLineHeight();
} else if (primitiveValue->isLength()) {
- double multiplier = state.style()->effectiveZoom();
+ float multiplier = state.style()->effectiveZoom();
if (Frame* frame = state.document().frame())
multiplier *= frame->textZoomFactor();
- lineHeight = primitiveValue->computeLength<Length>(state.style(), state.rootElementStyle(), multiplier);
+ lineHeight = primitiveValue->computeLength<Length>(state.cssToLengthConversionData().copyWithAdjustedZoom(multiplier));
} else if (primitiveValue->isPercentage()) {
- // FIXME: percentage should not be restricted to an integer here.
- lineHeight = Length((state.style()->fontSize() * primitiveValue->getIntValue()) / 100, Fixed);
+ lineHeight = Length((state.style()->computedFontSize() * primitiveValue->getIntValue()) / 100.0, Fixed);
} else if (primitiveValue->isNumber()) {
- // FIXME: number and percentage values should produce the same type of Length (ie. Fixed or Percent).
lineHeight = Length(primitiveValue->getDoubleValue() * 100.0, Percent);
} else if (primitiveValue->isViewportPercentageLength()) {
lineHeight = primitiveValue->viewportPercentageLength();
+ } else if (primitiveValue->isCalculated()) {
+ double multiplier = state.style()->effectiveZoom();
+ if (Frame* frame = state.document().frame())
+ multiplier *= frame->textZoomFactor();
+ Length zoomedLength = Length(primitiveValue->cssCalcValue()->toCalcValue(state.cssToLengthConversionData().copyWithAdjustedZoom(multiplier)));
+ lineHeight = Length(valueForLength(zoomedLength, state.style()->fontSize()), Fixed);
} else {
return;
}
@@ -338,8 +339,8 @@ void StyleBuilderFunctions::applyValueCSSPropertyResize(StyleResolverState& stat
state.style()->setResize(r);
}
-static Length mmLength(double mm) { return CSSPrimitiveValue::create(mm, CSSPrimitiveValue::CSS_MM)->computeLength<Length>(0, 0); }
-static Length inchLength(double inch) { return CSSPrimitiveValue::create(inch, CSSPrimitiveValue::CSS_IN)->computeLength<Length>(0, 0); }
+static Length mmLength(double mm) { return Length(mm * cssPixelsPerMillimeter, Fixed); }
+static Length inchLength(double inch) { return Length(inch * cssPixelsPerInch, Fixed); }
static bool getPageSizeFromName(CSSPrimitiveValue* pageSizeName, CSSPrimitiveValue* pageOrientation, Length& width, Length& height)
{
DEFINE_STATIC_LOCAL(Length, a5Width, (mmLength(148)));
@@ -434,8 +435,8 @@ void StyleBuilderFunctions::applyValueCSSPropertySize(StyleResolverState& state,
// <length>{2}
if (!second->isLength())
return;
- width = first->computeLength<Length>(state.style(), state.rootElementStyle());
- height = second->computeLength<Length>(state.style(), state.rootElementStyle());
+ width = first->computeLength<Length>(state.cssToLengthConversionData().copyWithAdjustedZoom(1.0));
+ height = second->computeLength<Length>(state.cssToLengthConversionData().copyWithAdjustedZoom(1.0));
} else {
// <page-size> <orientation>
// The value order is guaranteed. See CSSParser::parseSizeParameter.
@@ -453,7 +454,7 @@ void StyleBuilderFunctions::applyValueCSSPropertySize(StyleResolverState& state,
if (primitiveValue->isLength()) {
// <length>
pageSizeType = PAGE_SIZE_RESOLVED;
- width = height = primitiveValue->computeLength<Length>(state.style(), state.rootElementStyle());
+ width = height = primitiveValue->computeLength<Length>(state.cssToLengthConversionData().copyWithAdjustedZoom(1.0));
} else {
switch (primitiveValue->getValueID()) {
case 0:
@@ -537,7 +538,7 @@ void StyleBuilderFunctions::applyValueCSSPropertyTextIndent(StyleResolverState&
CSSValueList* valueList = toCSSValueList(value);
CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(valueList->itemWithoutBoundsCheck(0));
- Length lengthOrPercentageValue = primitiveValue->convertToLength<FixedIntegerConversion | PercentConversion>(state.style(), state.rootElementStyle(), state.style()->effectiveZoom());
+ Length lengthOrPercentageValue = primitiveValue->convertToLength<FixedConversion | PercentConversion>(state.cssToLengthConversionData());
ASSERT(!lengthOrPercentageValue.isUndefined());
state.style()->setTextIndent(lengthOrPercentageValue);
@@ -560,7 +561,16 @@ void StyleBuilderFunctions::applyValueCSSPropertyVerticalAlign(StyleResolverStat
if (primitiveValue->getValueID())
return state.style()->setVerticalAlign(*primitiveValue);
- state.style()->setVerticalAlignLength(primitiveValue->convertToLength<FixedIntegerConversion | PercentConversion>(state.style(), state.rootElementStyle(), state.style()->effectiveZoom()));
+ state.style()->setVerticalAlignLength(primitiveValue->convertToLength<FixedConversion | PercentConversion>(state.cssToLengthConversionData()));
+}
+
+void StyleBuilderFunctions::applyValueCSSPropertyTouchAction(StyleResolverState& state, CSSValue* value)
+{
+ TouchAction action = RenderStyle::initialTouchAction();
+ for (CSSValueListIterator i(value); i.hasMore(); i.advance())
+ action |= *toCSSPrimitiveValue(i.value());
+
+ state.style()->setTouchAction(action);
}
static void resetEffectiveZoom(StyleResolverState& state)
@@ -629,12 +639,19 @@ void StyleBuilderFunctions::applyValueCSSPropertyWebkitAspectRatio(StyleResolver
state.style()->setHasAspectRatio(false);
return;
}
- CSSAspectRatioValue* aspectRatioValue = static_cast<CSSAspectRatioValue*>(value);
+ CSSAspectRatioValue* aspectRatioValue = toCSSAspectRatioValue(value);
state.style()->setHasAspectRatio(true);
state.style()->setAspectRatioDenominator(aspectRatioValue->denominatorValue());
state.style()->setAspectRatioNumerator(aspectRatioValue->numeratorValue());
}
+void StyleBuilderFunctions::applyValueCSSPropertyWebkitBorderImage(StyleResolverState& state, CSSValue* value)
+{
+ NinePieceImage image;
+ state.styleMap().mapNinePieceImage(state.style(), CSSPropertyWebkitBorderImage, value, image);
+ state.style()->setBorderImage(image);
+}
+
void StyleBuilderFunctions::applyValueCSSPropertyWebkitClipPath(StyleResolverState& state, CSSValue* value)
{
if (value->isPrimitiveValue()) {
@@ -688,7 +705,7 @@ void StyleBuilderFunctions::applyValueCSSPropertyInternalMarqueeIncrement(StyleR
break;
}
} else {
- Length marqueeLength = primitiveValue ? primitiveValue->convertToLength<FixedIntegerConversion | PercentConversion | FractionConversion>(state.style(), state.rootElementStyle()) : Length(Undefined);
+ Length marqueeLength = primitiveValue ? primitiveValue->convertToLength<FixedConversion | PercentConversion>(state.cssToLengthConversionData()) : Length(Undefined);
if (!marqueeLength.isUndefined())
state.style()->setMarqueeIncrement(marqueeLength);
}
@@ -783,7 +800,7 @@ void StyleBuilderFunctions::applyValueCSSPropertyWebkitTextEmphasisStyle(StyleRe
if (primitiveValue->isString()) {
state.style()->setTextEmphasisFill(TextEmphasisFillFilled);
state.style()->setTextEmphasisMark(TextEmphasisMarkCustom);
- state.style()->setTextEmphasisCustomMark(primitiveValue->getStringValue());
+ state.style()->setTextEmphasisCustomMark(AtomicString(primitiveValue->getStringValue()));
return;
}
@@ -798,8 +815,7 @@ void StyleBuilderFunctions::applyValueCSSPropertyWebkitTextEmphasisStyle(StyleRe
}
}
-#if ENABLE(CSS3_TEXT)
-void StyleBuilderFunctions::applyValueCSSPropetyWebkitTextUnderlinePosition(StyleResolverState& state, CSSValue* value)
+void StyleBuilderFunctions::applyValueCSSPropertyTextUnderlinePosition(StyleResolverState& state, CSSValue* value)
{
// This is true if value is 'auto' or 'alphabetic'.
if (value->isPrimitiveValue()) {
@@ -816,92 +832,6 @@ void StyleBuilderFunctions::applyValueCSSPropetyWebkitTextUnderlinePosition(Styl
}
state.style()->setTextUnderlinePosition(static_cast<TextUnderlinePosition>(t));
}
-#endif // CSS3_TEXT
-
-Length StyleBuilderConverter::convertLength(StyleResolverState& state, CSSValue* value)
-{
- CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
- Length result = primitiveValue->convertToLength<FixedIntegerConversion | PercentConversion>(state.style(), state.rootElementStyle(), state.style()->effectiveZoom());
- ASSERT(!result.isUndefined());
- result.setQuirk(primitiveValue->isQuirkValue());
- return result;
-}
-
-Length StyleBuilderConverter::convertLengthOrAuto(StyleResolverState& state, CSSValue* value)
-{
- CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
- Length result = primitiveValue->convertToLength<FixedIntegerConversion | PercentConversion | AutoConversion>(state.style(), state.rootElementStyle(), state.style()->effectiveZoom());
- ASSERT(!result.isUndefined());
- result.setQuirk(primitiveValue->isQuirkValue());
- return result;
-}
-
-Length StyleBuilderConverter::convertLengthSizing(StyleResolverState& state, CSSValue* value)
-{
- CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
- switch (primitiveValue->getValueID()) {
- case CSSValueInvalid:
- return convertLength(state, value);
- case CSSValueIntrinsic:
- return Length(Intrinsic);
- case CSSValueMinIntrinsic:
- return Length(MinIntrinsic);
- case CSSValueWebkitMinContent:
- return Length(MinContent);
- case CSSValueWebkitMaxContent:
- return Length(MaxContent);
- case CSSValueWebkitFillAvailable:
- return Length(FillAvailable);
- case CSSValueWebkitFitContent:
- return Length(FitContent);
- case CSSValueAuto:
- return Length(Auto);
- default:
- ASSERT_NOT_REACHED();
- return Length();
- }
-}
-
-Length StyleBuilderConverter::convertLengthMaxSizing(StyleResolverState& state, CSSValue* value)
-{
- CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
- if (primitiveValue->getValueID() == CSSValueNone)
- return Length(Undefined);
- return convertLengthSizing(state, value);
-}
-
-LengthPoint StyleBuilderConverter::convertLengthPoint(StyleResolverState& state, CSSValue* value)
-{
- CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
- Pair* pair = primitiveValue->getPairValue();
- Length x = pair->first()->convertToLength<FixedIntegerConversion | PercentConversion>(state.style(), state.rootElementStyle(), state.style()->effectiveZoom());
- Length y = pair->second()->convertToLength<FixedIntegerConversion | PercentConversion>(state.style(), state.rootElementStyle(), state.style()->effectiveZoom());
- return LengthPoint(x, y);
-}
-
-LengthSize StyleBuilderConverter::convertRadius(StyleResolverState& state, CSSValue* value)
-{
- CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
- Pair* pair = primitiveValue->getPairValue();
- Length radiusWidth = pair->first()->convertToLength<FixedIntegerConversion | PercentConversion>(state.style(), state.rootElementStyle(), state.style()->effectiveZoom());
- Length radiusHeight = pair->second()->convertToLength<FixedIntegerConversion | PercentConversion>(state.style(), state.rootElementStyle(), state.style()->effectiveZoom());
- float width = radiusWidth.value();
- float height = radiusHeight.value();
- ASSERT(width >= 0 && height >= 0);
- if (width <= 0 || height <= 0)
- return LengthSize(Length(0, Fixed), Length(0, Fixed));
- return LengthSize(radiusWidth, radiusHeight);
-}
-
-float StyleBuilderConverter::convertSpacing(StyleResolverState& state, CSSValue* value)
-{
- CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
- if (primitiveValue->getValueID() == CSSValueNormal)
- return 0;
- float zoom = state.useSVGZoomRules() ? 1.0f : state.style()->effectiveZoom();
- return primitiveValue->computeLength<float>(state.style(), state.rootElementStyle(), zoom);
-}
-
// Everything below this line is from the old StyleResolver::applyProperty
// and eventually needs to move into new StyleBuilderFunctions calls intead.
@@ -950,7 +880,7 @@ static bool createGridTrackBreadth(CSSPrimitiveValue* primitiveValue, const Styl
return true;
}
- workingLength = primitiveValue->convertToLength<FixedIntegerConversion | PercentConversion | AutoConversion>(state.style(), state.rootElementStyle(), state.style()->effectiveZoom());
+ workingLength = primitiveValue->convertToLength<FixedConversion | PercentConversion | AutoConversion>(state.cssToLengthConversionData());
if (workingLength.length().isUndefined())
return false;
@@ -998,16 +928,16 @@ static bool createGridTrackList(CSSValue* value, Vector<GridTrackSize>& trackSiz
size_t currentNamedGridLine = 0;
for (CSSValueListIterator i = value; i.hasMore(); i.advance()) {
CSSValue* currValue = i.value();
- if (currValue->isPrimitiveValue()) {
- CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(currValue);
- if (primitiveValue->isString()) {
- String namedGridLine = primitiveValue->getStringValue();
+ if (currValue->isGridLineNamesValue()) {
+ CSSGridLineNamesValue* lineNamesValue = toCSSGridLineNamesValue(currValue);
+ for (CSSValueListIterator j = lineNamesValue; j.hasMore(); j.advance()) {
+ String namedGridLine = toCSSPrimitiveValue(j.value())->getStringValue();
NamedGridLinesMap::AddResult result = namedGridLines.add(namedGridLine, Vector<size_t>());
result.iterator->value.append(currentNamedGridLine);
OrderedNamedGridLines::AddResult orderedInsertionResult = orderedNamedGridLines.add(currentNamedGridLine, Vector<String>());
orderedInsertionResult.iterator->value.append(namedGridLine);
- continue;
}
+ continue;
}
++currentNamedGridLine;
@@ -1146,35 +1076,6 @@ static EPaintOrder paintOrderFlattened(CSSValue* cssPaintOrder)
return PO_NORMAL;
}
-static bool numberToFloat(const CSSPrimitiveValue* primitiveValue, float& out)
-{
- if (!primitiveValue)
- return false;
- if (primitiveValue->primitiveType() != CSSPrimitiveValue::CSS_NUMBER)
- return false;
- out = primitiveValue->getFloatValue();
- return true;
-}
-
-static bool percentageOrNumberToFloat(const CSSPrimitiveValue* primitiveValue, float& out)
-{
- if (!primitiveValue)
- return false;
- int type = primitiveValue->primitiveType();
- if (type == CSSPrimitiveValue::CSS_PERCENTAGE) {
- out = primitiveValue->getFloatValue() / 100.0f;
- return true;
- }
- return numberToFloat(primitiveValue, out);
-}
-
-static String fragmentIdentifier(const CSSPrimitiveValue* primitiveValue, Document& document)
-{
- if (primitiveValue->primitiveType() != CSSPrimitiveValue::CSS_URI)
- return String();
- return SVGURIReference::fragmentIdentifierFromIRIString(primitiveValue->getStringValue(), document);
-}
-
static inline bool isValidVisitedLinkProperty(CSSPropertyID id)
{
switch (id) {
@@ -1207,11 +1108,11 @@ static bool hasVariableReference(CSSValue* value)
return primitiveValue->hasVariableReference();
}
- if (value->isCalculationValue())
- return static_cast<CSSCalcValue*>(value)->hasVariableReference();
+ if (value->isCalcValue())
+ return toCSSCalcValue(value)->hasVariableReference();
if (value->isReflectValue()) {
- CSSReflectValue* reflectValue = static_cast<CSSReflectValue*>(value);
+ CSSReflectValue* reflectValue = toCSSReflectValue(value);
CSSPrimitiveValue* direction = reflectValue->direction();
CSSPrimitiveValue* offset = reflectValue->offset();
CSSValue* mask = reflectValue->mask();
@@ -1303,8 +1204,6 @@ void StyleBuilder::oldApplyProperty(CSSPropertyID id, StyleResolverState& state,
{
CSSPrimitiveValue* primitiveValue = value->isPrimitiveValue() ? toCSSPrimitiveValue(value) : 0;
- float zoomFactor = state.style()->effectiveZoom();
-
// What follows is a list that maps the CSS properties into their corresponding front-end
// RenderStyle values.
switch (id) {
@@ -1327,12 +1226,12 @@ void StyleBuilder::oldApplyProperty(CSSPropertyID id, StyleResolverState& state,
CSSValue* item = i.value();
if (item->isImageGeneratorValue()) {
if (item->isGradientValue())
- state.style()->setContent(StyleGeneratedImage::create(static_cast<CSSGradientValue*>(item)->gradientWithStylesResolved(state.document().textLinkColors(), state.style()->color()).get()), didSet);
+ state.style()->setContent(StyleGeneratedImage::create(toCSSGradientValue(item)->gradientWithStylesResolved(state.document().textLinkColors(), state.style()->color()).get()), didSet);
else
- state.style()->setContent(StyleGeneratedImage::create(static_cast<CSSImageGeneratorValue*>(item)), didSet);
+ state.style()->setContent(StyleGeneratedImage::create(toCSSImageGeneratorValue(item)), didSet);
didSet = true;
} else if (item->isImageSetValue()) {
- state.style()->setContent(state.elementStyleResources().setOrPendingFromValue(CSSPropertyContent, static_cast<CSSImageSetValue*>(item)), didSet);
+ state.style()->setContent(state.elementStyleResources().setOrPendingFromValue(CSSPropertyContent, toCSSImageSetValue(item)), didSet);
didSet = true;
}
@@ -1356,9 +1255,9 @@ void StyleBuilder::oldApplyProperty(CSSPropertyID id, StyleResolverState& state,
state.style()->setUnique();
else
state.parentStyle()->setUnique();
- QualifiedName attr(nullAtom, contentValue->getStringValue().impl(), nullAtom);
+ QualifiedName attr(nullAtom, AtomicString(contentValue->getStringValue()), nullAtom);
const AtomicString& value = state.element()->getAttribute(attr);
- state.style()->setContent(value.isNull() ? emptyAtom : value.impl(), didSet);
+ state.style()->setContent(value.isNull() ? emptyString() : value.string(), didSet);
didSet = true;
// register the fact that the attribute value affects the style
state.contentAttrValues().append(attr.localName());
@@ -1368,7 +1267,7 @@ void StyleBuilder::oldApplyProperty(CSSPropertyID id, StyleResolverState& state,
CSSValueID listStyleIdent = counterValue->listStyleIdent();
if (listStyleIdent != CSSValueNone)
listStyleType = static_cast<EListStyleType>(listStyleIdent - CSSValueDisc);
- OwnPtr<CounterContent> counter = adoptPtr(new CounterContent(counterValue->identifier(), listStyleType, counterValue->separator()));
+ OwnPtr<CounterContent> counter = adoptPtr(new CounterContent(AtomicString(counterValue->identifier()), listStyleType, AtomicString(counterValue->separator())));
state.style()->setContent(counter.release(), didSet);
didSet = true;
} else {
@@ -1484,46 +1383,6 @@ void StyleBuilder::oldApplyProperty(CSSPropertyID id, StyleResolverState& state,
break;
// CSS3 Properties
- case CSSPropertyTextShadow:
- case CSSPropertyBoxShadow:
- case CSSPropertyWebkitBoxShadow: {
- if (isInherit) {
- if (id == CSSPropertyTextShadow)
- return state.style()->setTextShadow(cloneShadow(state.parentStyle()->textShadow()));
- return state.style()->setBoxShadow(cloneShadow(state.parentStyle()->boxShadow()));
- }
- if (isInitial || primitiveValue) // initial | none
- return id == CSSPropertyTextShadow ? state.style()->setTextShadow(nullptr) : state.style()->setBoxShadow(nullptr);
-
- if (!value->isValueList())
- return;
-
- for (CSSValueListIterator i = value; i.hasMore(); i.advance()) {
- CSSValue* currValue = i.value();
- if (!currValue->isShadowValue())
- continue;
- ShadowValue* item = static_cast<ShadowValue*>(currValue);
- int x = item->x->computeLength<int>(state.style(), state.rootElementStyle(), zoomFactor);
- int y = item->y->computeLength<int>(state.style(), state.rootElementStyle(), zoomFactor);
- int blur = item->blur ? item->blur->computeLength<int>(state.style(), state.rootElementStyle(), zoomFactor) : 0;
- int spread = item->spread ? item->spread->computeLength<int>(state.style(), state.rootElementStyle(), zoomFactor) : 0;
- ShadowStyle shadowStyle = item->style && item->style->getValueID() == CSSValueInset ? Inset : Normal;
- Color color;
- if (item->color)
- color = state.document().textLinkColors().colorFromPrimitiveValue(item->color.get(), state.style()->visitedDependentColor(CSSPropertyColor));
- else if (state.style())
- color = state.style()->color();
-
- if (!color.isValid())
- color = Color::transparent;
- OwnPtr<ShadowData> shadow = ShadowData::create(IntPoint(x, y), blur, spread, shadowStyle, color);
- if (id == CSSPropertyTextShadow)
- state.style()->setTextShadow(shadow.release(), i.index()); // add to the list if this is not the first entry
- else
- state.style()->setBoxShadow(shadow.release(), i.index()); // add to the list if this is not the first entry
- }
- return;
- }
case CSSPropertyWebkitBoxReflect: {
HANDLE_INHERIT_AND_INITIAL(boxReflect, BoxReflect)
if (primitiveValue) {
@@ -1534,11 +1393,11 @@ void StyleBuilder::oldApplyProperty(CSSPropertyID id, StyleResolverState& state,
if (!value->isReflectValue())
return;
- CSSReflectValue* reflectValue = static_cast<CSSReflectValue*>(value);
+ CSSReflectValue* reflectValue = toCSSReflectValue(value);
RefPtr<StyleReflection> reflection = StyleReflection::create();
reflection->setDirection(*reflectValue->direction());
if (reflectValue->offset())
- reflection->setOffset(reflectValue->offset()->convertToLength<FixedIntegerConversion | PercentConversion>(state.style(), state.rootElementStyle(), zoomFactor));
+ reflection->setOffset(reflectValue->offset()->convertToLength<FixedConversion | PercentConversion>(state.cssToLengthConversionData()));
NinePieceImage mask;
mask.setMaskDefaults();
state.styleMap().mapNinePieceImage(state.style(), id, reflectValue->mask(), mask);
@@ -1558,7 +1417,7 @@ void StyleBuilder::oldApplyProperty(CSSPropertyID id, StyleResolverState& state,
if (primitiveValue->getValueID() == CSSValueAuto)
state.style()->setLocale(nullAtom);
else
- state.style()->setLocale(primitiveValue->getStringValue());
+ state.style()->setLocale(AtomicString(primitiveValue->getStringValue()));
state.fontBuilder().setScript(state.style()->locale());
return;
}
@@ -1581,11 +1440,11 @@ void StyleBuilder::oldApplyProperty(CSSPropertyID id, StyleResolverState& state,
result *= 3;
else if (primitiveValue->getValueID() == CSSValueThick)
result *= 5;
- width = CSSPrimitiveValue::create(result, CSSPrimitiveValue::CSS_EMS)->computeLength<float>(state.style(), state.rootElementStyle(), zoomFactor);
+ width = CSSPrimitiveValue::create(result, CSSPrimitiveValue::CSS_EMS)->computeLength<float>(state.cssToLengthConversionData());
break;
}
default:
- width = primitiveValue->computeLength<float>(state.style(), state.rootElementStyle(), zoomFactor);
+ width = primitiveValue->computeLength<float>(state.cssToLengthConversionData());
break;
}
state.style()->setTextStrokeWidth(width);
@@ -1594,7 +1453,7 @@ void StyleBuilder::oldApplyProperty(CSSPropertyID id, StyleResolverState& state,
case CSSPropertyWebkitTransform: {
HANDLE_INHERIT_AND_INITIAL(transform, Transform);
TransformOperations operations;
- TransformBuilder::createTransformOperations(value, state.style(), state.rootElementStyle(), operations);
+ TransformBuilder::createTransformOperations(value, state.cssToLengthConversionData(), operations);
state.style()->setTransform(operations);
return;
}
@@ -1611,10 +1470,10 @@ void StyleBuilder::oldApplyProperty(CSSPropertyID id, StyleResolverState& state,
float perspectiveValue;
if (primitiveValue->isLength()) {
- perspectiveValue = primitiveValue->computeLength<float>(state.style(), state.rootElementStyle(), zoomFactor);
+ perspectiveValue = primitiveValue->computeLength<float>(state.cssToLengthConversionData());
} else if (primitiveValue->isNumber()) {
// For backward compatibility, treat valueless numbers as px.
- perspectiveValue = CSSPrimitiveValue::create(primitiveValue->getDoubleValue(), CSSPrimitiveValue::CSS_PX)->computeLength<float>(state.style(), state.rootElementStyle(), zoomFactor);
+ perspectiveValue = CSSPrimitiveValue::create(primitiveValue->getDoubleValue(), CSSPrimitiveValue::CSS_PX)->computeLength<float>(state.cssToLengthConversionData());
} else {
return;
}
@@ -1628,10 +1487,19 @@ void StyleBuilder::oldApplyProperty(CSSPropertyID id, StyleResolverState& state,
if (!primitiveValue)
break;
- Color col = state.document().textLinkColors().colorFromPrimitiveValue(primitiveValue, state.style()->visitedDependentColor(CSSPropertyColor));
+ Color col = state.document().textLinkColors().colorFromPrimitiveValue(primitiveValue, state.style()->color());
state.style()->setTapHighlightColor(col);
return;
}
+ case CSSPropertyInternalCallback: {
+ if (isInherit || isInitial)
+ return;
+ if (primitiveValue && primitiveValue->getValueID() == CSSValueInternalPresence) {
+ state.style()->addCallbackSelector(state.currentRule()->selectorList().selectorsText());
+ return;
+ }
+ break;
+ }
case CSSPropertyInvalid:
return;
// Directional properties are resolved by resolveDirectionAwareProperty() before the switch.
@@ -1717,11 +1585,10 @@ void StyleBuilder::oldApplyProperty(CSSPropertyID id, StyleResolverState& state,
return;
}
- if (!value->isCSSLineBoxContainValue())
+ if (!value->isLineBoxContainValue())
return;
- CSSLineBoxContainValue* lineBoxContainValue = static_cast<CSSLineBoxContainValue*>(value);
- state.style()->setLineBoxContain(lineBoxContainValue->value());
+ state.style()->setLineBoxContain(toCSSLineBoxContainValue(value)->value());
return;
}
@@ -1742,7 +1609,7 @@ void StyleBuilder::oldApplyProperty(CSSPropertyID id, StyleResolverState& state,
case CSSPropertyWebkitFilter: {
HANDLE_INHERIT_AND_INITIAL(filter, Filter);
FilterOperations operations;
- if (FilterOperationResolver::createFilterOperations(value, state.style(), state.rootElementStyle(), operations, state))
+ if (FilterOperationResolver::createFilterOperations(value, state.cssToLengthConversionData(), operations, state))
state.style()->setFilter(operations);
return;
}
@@ -1920,6 +1787,7 @@ void StyleBuilder::oldApplyProperty(CSSPropertyID id, StyleResolverState& state,
case CSSPropertyBorderTopStyle:
case CSSPropertyBorderTopWidth:
case CSSPropertyBottom:
+ case CSSPropertyBoxShadow:
case CSSPropertyBoxSizing:
case CSSPropertyCaptionSide:
case CSSPropertyClear:
@@ -1932,6 +1800,7 @@ void StyleBuilder::oldApplyProperty(CSSPropertyID id, StyleResolverState& state,
case CSSPropertyDisplay:
case CSSPropertyEmptyCells:
case CSSPropertyFloat:
+ case CSSPropertyFontKerning:
case CSSPropertyFontSize:
case CSSPropertyFontStyle:
case CSSPropertyFontVariant:
@@ -1986,11 +1855,14 @@ void StyleBuilder::oldApplyProperty(CSSPropertyID id, StyleResolverState& state,
case CSSPropertyTextDecorationStyle:
case CSSPropertyTextDecorationColor:
case CSSPropertyTextIndent:
+ case CSSPropertyTextJustify:
case CSSPropertyTextOverflow:
case CSSPropertyTextRendering:
+ case CSSPropertyTextShadow:
case CSSPropertyTextTransform:
case CSSPropertyTop:
case CSSPropertyTouchAction:
+ case CSSPropertyTouchActionDelay:
case CSSPropertyUnicodeBidi:
case CSSPropertyVariable:
case CSSPropertyVerticalAlign:
@@ -2023,11 +1895,13 @@ void StyleBuilder::oldApplyProperty(CSSPropertyID id, StyleResolverState& state,
case CSSPropertyWebkitBoxOrdinalGroup:
case CSSPropertyWebkitBoxOrient:
case CSSPropertyWebkitBoxPack:
+ case CSSPropertyWebkitBoxShadow:
case CSSPropertyWebkitColumnAxis:
case CSSPropertyWebkitColumnBreakAfter:
case CSSPropertyWebkitColumnBreakBefore:
case CSSPropertyWebkitColumnBreakInside:
case CSSPropertyWebkitColumnCount:
+ case CSSPropertyColumnFill:
case CSSPropertyWebkitColumnGap:
case CSSPropertyWebkitColumnProgression:
case CSSPropertyWebkitColumnRuleColor:
@@ -2047,7 +1921,6 @@ void StyleBuilder::oldApplyProperty(CSSPropertyID id, StyleResolverState& state,
case CSSPropertyOrder:
case CSSPropertyWebkitFlowFrom:
case CSSPropertyWebkitFlowInto:
- case CSSPropertyWebkitFontKerning:
case CSSPropertyWebkitFontSmoothing:
case CSSPropertyWebkitFontVariantLigatures:
case CSSPropertyWebkitHighlight:
@@ -2088,9 +1961,7 @@ void StyleBuilder::oldApplyProperty(CSSPropertyID id, StyleResolverState& state,
case CSSPropertyWebkitRtlOrdering:
case CSSPropertyWebkitRubyPosition:
case CSSPropertyWebkitTextCombine:
-#if ENABLE(CSS3_TEXT)
- case CSSPropertyWebkitTextUnderlinePosition:
-#endif // CSS3_TEXT
+ case CSSPropertyTextUnderlinePosition:
case CSSPropertyWebkitTextEmphasisColor:
case CSSPropertyWebkitTextEmphasisPosition:
case CSSPropertyWebkitTextEmphasisStyle:
@@ -2110,11 +1981,12 @@ void StyleBuilder::oldApplyProperty(CSSPropertyID id, StyleResolverState& state,
case CSSPropertyWebkitUserSelect:
case CSSPropertyWebkitClipPath:
case CSSPropertyWebkitWrapFlow:
- case CSSPropertyWebkitShapeMargin:
- case CSSPropertyWebkitShapePadding:
+ case CSSPropertyShapeMargin:
+ case CSSPropertyShapePadding:
+ case CSSPropertyShapeImageThreshold:
case CSSPropertyWebkitWrapThrough:
- case CSSPropertyWebkitShapeInside:
- case CSSPropertyWebkitShapeOutside:
+ case CSSPropertyShapeInside:
+ case CSSPropertyShapeOutside:
case CSSPropertyWhiteSpace:
case CSSPropertyWidows:
case CSSPropertyWidth:
@@ -2142,6 +2014,20 @@ void StyleBuilder::oldApplyProperty(CSSPropertyID id, StyleResolverState& state,
case CSSPropertyTextAnchor:
case CSSPropertyVectorEffect:
case CSSPropertyWritingMode:
+ case CSSPropertyClipPath:
+ case CSSPropertyFillOpacity:
+ case CSSPropertyFilter:
+ case CSSPropertyFloodOpacity:
+ case CSSPropertyKerning:
+ case CSSPropertyMarkerEnd:
+ case CSSPropertyMarkerMid:
+ case CSSPropertyMarkerStart:
+ case CSSPropertyMask:
+ case CSSPropertyStopOpacity:
+ case CSSPropertyStrokeDashoffset:
+ case CSSPropertyStrokeMiterlimit:
+ case CSSPropertyStrokeOpacity:
+ case CSSPropertyStrokeWidth:
ASSERT_NOT_REACHED();
return;
// Only used in @viewport rules
@@ -2179,13 +2065,6 @@ void StyleBuilder::oldApplyProperty(CSSPropertyID id, StyleResolverState& state,
break;
}
- case CSSPropertyKerning:
- {
- HANDLE_SVG_INHERIT_AND_INITIAL(kerning, Kerning);
- if (primitiveValue)
- state.style()->accessSVGStyle()->setKerning(SVGLength::fromCSSPrimitiveValue(primitiveValue));
- break;
- }
case CSSPropertyColorProfile:
{
// Not implemented.
@@ -2205,7 +2084,7 @@ void StyleBuilder::oldApplyProperty(CSSPropertyID id, StyleResolverState& state,
return;
}
if (value->isSVGPaint()) {
- SVGPaint* svgPaint = static_cast<SVGPaint*>(value);
+ SVGPaint* svgPaint = toSVGPaint(value);
svgStyle->setFillPaint(svgPaint->paintType(), colorFromSVGColorCSSValue(svgPaint, state.style()->color()), svgPaint->uri(), state.applyPropertyToRegularStyle(), state.applyPropertyToVisitedLinkStyle());
}
break;
@@ -2223,18 +2102,11 @@ void StyleBuilder::oldApplyProperty(CSSPropertyID id, StyleResolverState& state,
return;
}
if (value->isSVGPaint()) {
- SVGPaint* svgPaint = static_cast<SVGPaint*>(value);
+ SVGPaint* svgPaint = toSVGPaint(value);
svgStyle->setStrokePaint(svgPaint->paintType(), colorFromSVGColorCSSValue(svgPaint, state.style()->color()), svgPaint->uri(), state.applyPropertyToRegularStyle(), state.applyPropertyToVisitedLinkStyle());
}
break;
}
- case CSSPropertyStrokeWidth:
- {
- HANDLE_SVG_INHERIT_AND_INITIAL(strokeWidth, StrokeWidth)
- if (primitiveValue)
- state.style()->accessSVGStyle()->setStrokeWidth(SVGLength::fromCSSPrimitiveValue(primitiveValue));
- break;
- }
case CSSPropertyStrokeDasharray:
{
HANDLE_SVG_INHERIT_AND_INITIAL(strokeDashArray, StrokeDashArray)
@@ -2259,114 +2131,25 @@ void StyleBuilder::oldApplyProperty(CSSPropertyID id, StyleResolverState& state,
state.style()->accessSVGStyle()->setStrokeDashArray(array);
break;
}
- case CSSPropertyStrokeDashoffset:
- {
- HANDLE_SVG_INHERIT_AND_INITIAL(strokeDashOffset, StrokeDashOffset)
- if (primitiveValue)
- state.style()->accessSVGStyle()->setStrokeDashOffset(SVGLength::fromCSSPrimitiveValue(primitiveValue));
- break;
- }
- case CSSPropertyFillOpacity:
- {
- HANDLE_SVG_INHERIT_AND_INITIAL(fillOpacity, FillOpacity)
- float f = 0.0f;
- if (percentageOrNumberToFloat(primitiveValue, f))
- state.style()->accessSVGStyle()->setFillOpacity(f);
- break;
- }
- case CSSPropertyStrokeOpacity:
- {
- HANDLE_SVG_INHERIT_AND_INITIAL(strokeOpacity, StrokeOpacity)
- float f = 0.0f;
- if (percentageOrNumberToFloat(primitiveValue, f))
- state.style()->accessSVGStyle()->setStrokeOpacity(f);
- break;
- }
- case CSSPropertyStopOpacity:
- {
- HANDLE_SVG_INHERIT_AND_INITIAL(stopOpacity, StopOpacity)
- float f = 0.0f;
- if (percentageOrNumberToFloat(primitiveValue, f))
- state.style()->accessSVGStyle()->setStopOpacity(f);
- break;
- }
- case CSSPropertyMarkerStart:
- {
- HANDLE_SVG_INHERIT_AND_INITIAL(markerStartResource, MarkerStartResource)
- if (primitiveValue)
- state.style()->accessSVGStyle()->setMarkerStartResource(fragmentIdentifier(primitiveValue, state.document()));
- break;
- }
- case CSSPropertyMarkerMid:
- {
- HANDLE_SVG_INHERIT_AND_INITIAL(markerMidResource, MarkerMidResource)
- if (primitiveValue)
- state.style()->accessSVGStyle()->setMarkerMidResource(fragmentIdentifier(primitiveValue, state.document()));
- break;
- }
- case CSSPropertyMarkerEnd:
- {
- HANDLE_SVG_INHERIT_AND_INITIAL(markerEndResource, MarkerEndResource)
- if (primitiveValue)
- state.style()->accessSVGStyle()->setMarkerEndResource(fragmentIdentifier(primitiveValue, state.document()));
- break;
- }
- case CSSPropertyStrokeMiterlimit:
- {
- HANDLE_SVG_INHERIT_AND_INITIAL(strokeMiterLimit, StrokeMiterLimit)
- float f = 0.0f;
- if (numberToFloat(primitiveValue, f))
- state.style()->accessSVGStyle()->setStrokeMiterLimit(f);
- break;
- }
- case CSSPropertyFilter:
- {
- HANDLE_SVG_INHERIT_AND_INITIAL(filterResource, FilterResource)
- if (primitiveValue)
- state.style()->accessSVGStyle()->setFilterResource(fragmentIdentifier(primitiveValue, state.document()));
- break;
- }
- case CSSPropertyMask:
- {
- HANDLE_SVG_INHERIT_AND_INITIAL(maskerResource, MaskerResource)
- if (primitiveValue)
- state.style()->accessSVGStyle()->setMaskerResource(fragmentIdentifier(primitiveValue, state.document()));
- break;
- }
- case CSSPropertyClipPath:
- {
- HANDLE_SVG_INHERIT_AND_INITIAL(clipperResource, ClipperResource)
- if (primitiveValue)
- state.style()->accessSVGStyle()->setClipperResource(fragmentIdentifier(primitiveValue, state.document()));
- break;
- }
case CSSPropertyStopColor:
{
HANDLE_SVG_INHERIT_AND_INITIAL(stopColor, StopColor);
if (value->isSVGColor())
- state.style()->accessSVGStyle()->setStopColor(colorFromSVGColorCSSValue(static_cast<SVGColor*>(value), state.style()->color()));
+ state.style()->accessSVGStyle()->setStopColor(colorFromSVGColorCSSValue(toSVGColor(value), state.style()->color()));
break;
}
case CSSPropertyLightingColor:
{
HANDLE_SVG_INHERIT_AND_INITIAL(lightingColor, LightingColor);
if (value->isSVGColor())
- state.style()->accessSVGStyle()->setLightingColor(colorFromSVGColorCSSValue(static_cast<SVGColor*>(value), state.style()->color()));
- break;
- }
- case CSSPropertyFloodOpacity:
- {
- HANDLE_SVG_INHERIT_AND_INITIAL(floodOpacity, FloodOpacity)
- float f = 0.0f;
- if (percentageOrNumberToFloat(primitiveValue, f))
- state.style()->accessSVGStyle()->setFloodOpacity(f);
+ state.style()->accessSVGStyle()->setLightingColor(colorFromSVGColorCSSValue(toSVGColor(value), state.style()->color()));
break;
}
case CSSPropertyFloodColor:
{
HANDLE_SVG_INHERIT_AND_INITIAL(floodColor, FloodColor);
if (value->isSVGColor())
- state.style()->accessSVGStyle()->setFloodColor(colorFromSVGColorCSSValue(static_cast<SVGColor*>(value), state.style()->color()));
+ state.style()->accessSVGStyle()->setFloodColor(colorFromSVGColorCSSValue(toSVGColor(value), state.style()->color()));
break;
}
case CSSPropertyGlyphOrientationHorizontal:
diff --git a/chromium/third_party/WebKit/Source/core/css/resolver/StyleBuilderCustom.h b/chromium/third_party/WebKit/Source/core/css/resolver/StyleBuilderCustom.h
deleted file mode 100644
index 597c5019b25..00000000000
--- a/chromium/third_party/WebKit/Source/core/css/resolver/StyleBuilderCustom.h
+++ /dev/null
@@ -1,99 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef StyleBuilderCustom_h
-#define StyleBuilderCustom_h
-
-#include "core/css/CSSValue.h"
-#include "core/css/resolver/StyleResolverState.h"
-#include "core/platform/LengthSize.h"
-#include "core/svg/SVGLength.h"
-
-namespace WebCore {
-
-// Note that we assume the parser only allows valid CSSValue types.
-
-class StyleBuilderConverter {
-public:
- template <typename T> static T convertComputedLength(StyleResolverState&, CSSValue*);
- template <typename T> static T convertLineWidth(StyleResolverState&, CSSValue*);
- static Length convertLength(StyleResolverState&, CSSValue*);
- static Length convertLengthOrAuto(StyleResolverState&, CSSValue*);
- static Length convertLengthSizing(StyleResolverState&, CSSValue*);
- static Length convertLengthMaxSizing(StyleResolverState&, CSSValue*);
- static LengthPoint convertLengthPoint(StyleResolverState&, CSSValue*);
- static LengthSize convertRadius(StyleResolverState&, CSSValue*);
- static float convertSpacing(StyleResolverState&, CSSValue*);
- template <CSSValueID IdForNone> static AtomicString convertString(StyleResolverState&, CSSValue*);
-};
-
-template <typename T>
-T StyleBuilderConverter::convertComputedLength(StyleResolverState& state, CSSValue* value)
-{
- CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
- float zoom = state.style()->effectiveZoom();
- return primitiveValue->computeLength<T>(state.style(), state.rootElementStyle(), zoom);
-}
-
-template <typename T>
-T StyleBuilderConverter::convertLineWidth(StyleResolverState& state, CSSValue* value)
-{
- CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
- CSSValueID valueID = primitiveValue->getValueID();
- if (valueID == CSSValueThin)
- return 1;
- if (valueID == CSSValueMedium)
- return 3;
- if (valueID == CSSValueThick)
- return 5;
- if (valueID == CSSValueInvalid) {
- float zoom = state.style()->effectiveZoom();
- // Any original result that was >= 1 should not be allowed to fall below 1.
- // This keeps border lines from vanishing.
- T result = primitiveValue->computeLength<T>(state.style(), state.rootElementStyle(), zoom);
- if (zoom < 1.0f && result < 1.0) {
- T originalLength = primitiveValue->computeLength<T>(state.style(), state.rootElementStyle(), 1.0);
- if (originalLength >= 1.0)
- return 1.0;
- }
- return result;
- }
- ASSERT_NOT_REACHED();
- return 0;
-}
-
-template <CSSValueID IdForNone>
-AtomicString StyleBuilderConverter::convertString(StyleResolverState&, CSSValue* value)
-{
- CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
- if (primitiveValue->getValueID() == IdForNone)
- return nullAtom;
- return primitiveValue->getStringValue();
-}
-
-} // namespace WebCore
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/css/resolver/StyleResolver.cpp b/chromium/third_party/WebKit/Source/core/css/resolver/StyleResolver.cpp
index 63748e5edd5..bc5cbdab5db 100644
--- a/chromium/third_party/WebKit/Source/core/css/resolver/StyleResolver.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/resolver/StyleResolver.cpp
@@ -33,7 +33,8 @@
#include "HTMLNames.h"
#include "RuntimeEnabledFeatures.h"
#include "StylePropertyShorthand.h"
-#include "core/animation/AnimatableNumber.h"
+#include "core/animation/ActiveAnimations.h"
+#include "core/animation/AnimatableLength.h"
#include "core/animation/AnimatableValue.h"
#include "core/animation/Animation.h"
#include "core/animation/DocumentTimeline.h"
@@ -41,6 +42,7 @@
#include "core/animation/css/CSSAnimations.h"
#include "core/css/CSSCalculationValue.h"
#include "core/css/CSSDefaultStyleSheets.h"
+#include "core/css/CSSFontFace.h"
#include "core/css/CSSFontSelector.h"
#include "core/css/CSSKeyframeRule.h"
#include "core/css/CSSKeyframesRule.h"
@@ -54,15 +56,17 @@
#include "core/css/ElementRuleCollector.h"
#include "core/css/MediaQueryEvaluator.h"
#include "core/css/PageRuleCollector.h"
-#include "core/css/RuleSet.h"
#include "core/css/StylePropertySet.h"
+#include "core/css/StyleRuleImport.h"
+#include "core/css/StyleSheetContents.h"
#include "core/css/resolver/AnimatedStyleBuilder.h"
#include "core/css/resolver/MatchResult.h"
#include "core/css/resolver/MediaQueryResult.h"
#include "core/css/resolver/SharedStyleFinder.h"
#include "core/css/resolver/StyleAdjuster.h"
-#include "core/css/resolver/StyleBuilder.h"
+#include "core/css/resolver/StyleResolverStats.h"
#include "core/css/resolver/ViewportStyleResolver.h"
+#include "core/dom/CSSSelectorWatch.h"
#include "core/dom/NodeRenderStyle.h"
#include "core/dom/StyleEngine.h"
#include "core/dom/Text.h"
@@ -70,8 +74,8 @@
#include "core/dom/shadow/ShadowRoot.h"
#include "core/html/HTMLIFrameElement.h"
#include "core/inspector/InspectorInstrumentation.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameView.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
#include "core/rendering/RenderView.h"
#include "core/rendering/style/KeyframeList.h"
#include "core/rendering/style/StyleCustomFilterProgramCache.h"
@@ -79,10 +83,23 @@
#include "core/svg/SVGElement.h"
#include "core/svg/SVGFontFaceElement.h"
#include "wtf/StdLibExtras.h"
-#include "wtf/Vector.h"
using namespace std;
+namespace {
+
+using namespace WebCore;
+
+void setAnimationUpdateIfNeeded(StyleResolverState& state, Element& element)
+{
+ // If any changes to CSS Animations were detected, stash the update away for application after the
+ // render object is updated if we're in the appropriate scope.
+ if (RuntimeEnabledFeatures::webAnimationsCSSEnabled() && state.animationUpdate())
+ element.ensureActiveAnimations()->cssAnimations().setPendingUpdate(state.takeAnimationUpdate());
+}
+
+} // namespace
+
namespace WebCore {
using namespace HTMLNames;
@@ -91,43 +108,51 @@ RenderStyle* StyleResolver::s_styleNotYetAvailable;
static StylePropertySet* leftToRightDeclaration()
{
- DEFINE_STATIC_LOCAL(RefPtr<MutableStylePropertySet>, leftToRightDecl, (MutableStylePropertySet::create()));
+ DEFINE_STATIC_REF(MutableStylePropertySet, leftToRightDecl, (MutableStylePropertySet::create()));
if (leftToRightDecl->isEmpty())
leftToRightDecl->setProperty(CSSPropertyDirection, CSSValueLtr);
- return leftToRightDecl.get();
+ return leftToRightDecl;
}
static StylePropertySet* rightToLeftDeclaration()
{
- DEFINE_STATIC_LOCAL(RefPtr<MutableStylePropertySet>, rightToLeftDecl, (MutableStylePropertySet::create()));
+ DEFINE_STATIC_REF(MutableStylePropertySet, rightToLeftDecl, (MutableStylePropertySet::create()));
if (rightToLeftDecl->isEmpty())
rightToLeftDecl->setProperty(CSSPropertyDirection, CSSValueRtl);
- return rightToLeftDecl.get();
+ return rightToLeftDecl;
}
-StyleResolver::StyleResolver(Document& document, bool matchAuthorAndUserStyles)
+static void addFontFaceRule(Document* document, CSSFontSelector* cssFontSelector, const StyleRuleFontFace* fontFaceRule)
+{
+ RefPtr<CSSFontFace> cssFontFace = CSSFontFace::createFromStyleRule(document, fontFaceRule);
+ if (cssFontFace)
+ cssFontSelector->addFontFaceRule(fontFaceRule, cssFontFace);
+}
+
+StyleResolver::StyleResolver(Document& document)
: m_document(document)
- , m_matchAuthorAndUserStyles(matchAuthorAndUserStyles)
- , m_fontSelector(CSSFontSelector::create(&document))
, m_viewportStyleResolver(ViewportStyleResolver::create(&document))
+ , m_needCollectFeatures(false)
, m_styleResourceLoader(document.fetcher())
+ , m_styleResolverStatsSequence(0)
+ , m_accessCount(0)
{
- Element* root = document.documentElement();
-
- CSSDefaultStyleSheets::initDefaultStyle(root);
+ // FIXME: Why do this here instead of as part of resolving style on the root?
+ CSSDefaultStyleSheets::loadDefaultStylesheetIfNecessary();
- // construct document root element default style. this is needed
+ // Construct document root element default style. This is needed
// to evaluate media queries that contain relative constraints, like "screen and (max-width: 10em)"
- // This is here instead of constructor, because when constructor is run,
- // document doesn't have documentElement
- // NOTE: this assumes that element that gets passed to styleForElement -call
- // is always from the document that owns the style selector
+ // This is here instead of constructor because when constructor is run,
+ // Document doesn't have documentElement.
+ // NOTE: This assumes that element that gets passed to the styleForElement call
+ // is always from the document that owns the StyleResolver.
FrameView* view = document.view();
if (view)
m_medium = adoptPtr(new MediaQueryEvaluator(view->mediaType()));
else
m_medium = adoptPtr(new MediaQueryEvaluator("all"));
+ Element* root = document.documentElement();
if (root)
m_rootDefaultStyle = styleForElement(root, 0, DisallowStyleSharing, MatchOnlyUserAgentRules);
@@ -136,19 +161,66 @@ StyleResolver::StyleResolver(Document& document, bool matchAuthorAndUserStyles)
m_styleTree.clear();
- StyleEngine* styleSheetCollection = document.styleEngine();
- m_ruleSets.initUserStyle(styleSheetCollection, *m_medium, *this);
+ initWatchedSelectorRules(CSSSelectorWatch::from(document).watchedCallbackSelectors());
#if ENABLE(SVG_FONTS)
if (document.svgExtensions()) {
const HashSet<SVGFontFaceElement*>& svgFontFaceElements = document.svgExtensions()->svgFontFaceElements();
HashSet<SVGFontFaceElement*>::const_iterator end = svgFontFaceElements.end();
for (HashSet<SVGFontFaceElement*>::const_iterator it = svgFontFaceElements.begin(); it != end; ++it)
- fontSelector()->addFontFaceRule((*it)->fontFaceRule());
+ addFontFaceRule(&document, document.styleEngine()->fontSelector(), (*it)->fontFaceRule());
}
#endif
+}
+
+void StyleResolver::initWatchedSelectorRules(const Vector<RefPtr<StyleRule> >& watchedSelectors)
+{
+ if (!watchedSelectors.size())
+ return;
+ m_watchedSelectorsRules = RuleSet::create();
+ for (unsigned i = 0; i < watchedSelectors.size(); ++i)
+ m_watchedSelectorsRules->addStyleRule(watchedSelectors[i].get(), RuleHasNoSpecialState);
+}
+
+void StyleResolver::lazyAppendAuthorStyleSheets(unsigned firstNew, const Vector<RefPtr<CSSStyleSheet> >& styleSheets)
+{
+ unsigned size = styleSheets.size();
+ for (unsigned i = firstNew; i < size; ++i)
+ m_pendingStyleSheets.add(styleSheets[i].get());
+}
+
+void StyleResolver::removePendingAuthorStyleSheets(const Vector<RefPtr<CSSStyleSheet> >& styleSheets)
+{
+ for (unsigned i = 0; i < styleSheets.size(); ++i)
+ m_pendingStyleSheets.remove(styleSheets[i].get());
+}
- styleSheetCollection->appendActiveAuthorStyleSheets(this);
+void StyleResolver::appendCSSStyleSheet(CSSStyleSheet* cssSheet)
+{
+ ASSERT(cssSheet);
+ ASSERT(!cssSheet->disabled());
+ if (cssSheet->mediaQueries() && !m_medium->eval(cssSheet->mediaQueries(), &m_viewportDependentMediaQueryResults))
+ return;
+
+ StyleSheetContents* sheet = cssSheet->contents();
+ ContainerNode* scopingNode = ScopedStyleResolver::scopingNodeFor(document(), cssSheet);
+ if (!scopingNode)
+ return;
+
+ ScopedStyleResolver* resolver = ensureScopedStyleResolver(scopingNode);
+ ASSERT(resolver);
+ resolver->addRulesFromSheet(sheet, *m_medium, this);
+ m_inspectorCSSOMWrappers.collectFromStyleSheetIfNeeded(cssSheet);
+}
+
+void StyleResolver::appendPendingAuthorStyleSheets()
+{
+ setBuildScopedStyleTreeInDocumentOrder(false);
+ for (ListHashSet<CSSStyleSheet*, 16>::iterator it = m_pendingStyleSheets.begin(); it != m_pendingStyleSheets.end(); ++it)
+ appendCSSStyleSheet(*it);
+
+ m_pendingStyleSheets.clear();
+ finishAppendAuthorStyleSheets();
}
void StyleResolver::appendAuthorStyleSheets(unsigned firstNew, const Vector<RefPtr<CSSStyleSheet> >& styleSheets)
@@ -156,18 +228,8 @@ void StyleResolver::appendAuthorStyleSheets(unsigned firstNew, const Vector<RefP
// This handles sheets added to the end of the stylesheet list only. In other cases the style resolver
// needs to be reconstructed. To handle insertions too the rule order numbers would need to be updated.
unsigned size = styleSheets.size();
- for (unsigned i = firstNew; i < size; ++i) {
- CSSStyleSheet* cssSheet = styleSheets[i].get();
- ASSERT(!cssSheet->disabled());
- if (cssSheet->mediaQueries() && !m_medium->eval(cssSheet->mediaQueries(), this))
- continue;
-
- StyleSheetContents* sheet = cssSheet->contents();
- ScopedStyleResolver* resolver = ensureScopedStyleResolver(ScopedStyleResolver::scopingNodeFor(cssSheet));
- ASSERT(resolver);
- resolver->addRulesFromSheet(sheet, *m_medium, this);
- m_inspectorCSSOMWrappers.collectFromStyleSheetIfNeeded(cssSheet);
- }
+ for (unsigned i = firstNew; i < size; ++i)
+ appendCSSStyleSheet(styleSheets[i].get());
}
void StyleResolver::finishAppendAuthorStyleSheets()
@@ -175,49 +237,66 @@ void StyleResolver::finishAppendAuthorStyleSheets()
collectFeatures();
if (document().renderer() && document().renderer()->style())
- document().renderer()->style()->font().update(fontSelector());
+ document().renderer()->style()->font().update(document().styleEngine()->fontSelector());
collectViewportRules();
+
+ document().styleEngine()->resetCSSFeatureFlags(m_features);
}
-void StyleResolver::resetAuthorStyle(const ContainerNode* scopingNode)
+void StyleResolver::resetRuleFeatures()
{
- ScopedStyleResolver* resolver = scopingNode ? m_styleTree.scopedStyleResolverFor(*scopingNode) : m_styleTree.scopedStyleResolverForDocument();
- if (!resolver)
- return;
-
- m_ruleSets.shadowDistributedRules().reset(scopingNode);
-
- resolver->resetAuthorStyle();
- if (!scopingNode)
- return;
-
- if (scopingNode->isShadowRoot())
- resetAtHostRules(scopingNode);
-
- if (!resolver->hasOnlyEmptyRuleSets())
- return;
+ // Need to recreate RuleFeatureSet.
+ m_features.clear();
+ m_siblingRuleSet.clear();
+ m_uncommonAttributeRuleSet.clear();
+ m_needCollectFeatures = true;
+}
- m_styleTree.remove(scopingNode);
+void StyleResolver::addTreeBoundaryCrossingRules(const Vector<MinimalRuleData>& rules, ContainerNode* scope)
+{
+ for (unsigned i = 0; i < rules.size(); ++i) {
+ const MinimalRuleData& info = rules[i];
+ m_treeBoundaryCrossingRules.addRule(info.m_rule, info.m_selectorIndex, scope, info.m_flags);
+ }
}
-void StyleResolver::resetAtHostRules(const ContainerNode* scopingNode)
+void StyleResolver::processScopedRules(const RuleSet& authorRules, const KURL& sheetBaseURL, ContainerNode* scope)
{
- ASSERT(scopingNode);
- ASSERT(scopingNode->isShadowRoot());
+ const Vector<StyleRuleKeyframes*> keyframesRules = authorRules.keyframesRules();
+ for (unsigned i = 0; i < keyframesRules.size(); ++i)
+ ensureScopedStyleResolver(scope)->addKeyframeStyle(keyframesRules[i]);
+
+ addTreeBoundaryCrossingRules(authorRules.treeBoundaryCrossingRules(), scope);
+
+ // FIXME(BUG 72461): We don't add @font-face rules of scoped style sheets for the moment.
+ if (!scope || scope->isDocumentNode()) {
+ const Vector<StyleRuleFontFace*> fontFaceRules = authorRules.fontFaceRules();
+ for (unsigned i = 0; i < fontFaceRules.size(); ++i)
+ addFontFaceRule(&m_document, document().styleEngine()->fontSelector(), fontFaceRules[i]);
+ if (fontFaceRules.size())
+ invalidateMatchedPropertiesCache();
+ } else {
+ addTreeBoundaryCrossingRules(authorRules.shadowDistributedRules(), scope);
+ }
+}
- const ShadowRoot* shadowRoot = toShadowRoot(scopingNode);
- const ContainerNode* shadowHost = shadowRoot->shadowHost();
- ASSERT(shadowHost);
- ScopedStyleResolver* resolver = m_styleTree.scopedStyleResolverFor(*shadowHost);
+void StyleResolver::resetAuthorStyle(const ContainerNode* scopingNode)
+{
+ // FIXME: When chanking scoped attribute, scopingNode's hasScopedHTMLStyleChild has been already modified.
+ // So we cannot use hasScopedHTMLStyleChild flag here.
+ ScopedStyleResolver* resolver = scopingNode ? m_styleTree.lookupScopedStyleResolverFor(scopingNode) : m_styleTree.scopedStyleResolverForDocument();
if (!resolver)
return;
- resolver->resetAtHostRules(shadowRoot);
- if (!resolver->hasOnlyEmptyRuleSets())
+ treeBoundaryCrossingRules().reset(scopingNode);
+
+ resolver->resetAuthorStyle();
+ resetRuleFeatures();
+ if (!scopingNode)
return;
- m_styleTree.remove(shadowHost);
+ m_styleTree.remove(scopingNode);
}
static PassOwnPtr<RuleSet> makeRuleSet(const Vector<RuleFeature>& rules)
@@ -234,60 +313,42 @@ static PassOwnPtr<RuleSet> makeRuleSet(const Vector<RuleFeature>& rules)
void StyleResolver::collectFeatures()
{
m_features.clear();
- m_ruleSets.collectFeaturesTo(m_features, document().isViewSource());
+ // Collect all ids and rules using sibling selectors (:first-child and similar)
+ // in the current set of stylesheets. Style sharing code uses this information to reject
+ // sharing candidates.
+ if (CSSDefaultStyleSheets::defaultStyle)
+ m_features.add(CSSDefaultStyleSheets::defaultStyle->features());
+
+ if (document().isViewSource())
+ m_features.add(CSSDefaultStyleSheets::viewSourceStyle()->features());
+
+ if (m_watchedSelectorsRules)
+ m_features.add(m_watchedSelectorsRules->features());
+
+ m_treeBoundaryCrossingRules.collectFeaturesTo(m_features);
+
m_styleTree.collectFeaturesTo(m_features);
m_siblingRuleSet = makeRuleSet(m_features.siblingRules);
m_uncommonAttributeRuleSet = makeRuleSet(m_features.uncommonAttributeRules);
+ m_needCollectFeatures = false;
}
-bool StyleResolver::supportsStyleSharing(Element* element)
+bool StyleResolver::hasRulesForId(const AtomicString& id) const
{
- if (!element || !element->isStyledElement() || !element->parentElement())
- return false;
-
- // If the element has inline style it is probably unique.
- if (element->inlineStyle())
- return false;
- if (element->isSVGElement() && toSVGElement(element)->animatedSMILStyleProperties())
- return false;
- // Ids stop style sharing if they show up in the stylesheets.
- if (element->hasID() && m_features.idsInRules.contains(element->idForStyleResolution().impl()))
- return false;
- // Active and hovered elements always make a chain towards the document node
- // and no siblings or cousins will have the same state.
- if (element->hovered())
- return false;
- if (element->active())
- return false;
- // There is always only one focused element.
- if (element->focused())
- return false;
- if (element->parentElement()->hasFlagsSetDuringStylingOfChildren())
- return false;
- if (element->hasScopedHTMLStyleChild())
- return false;
- if (element == m_document.cssTarget())
- return false;
- if (element->isHTMLElement() && toHTMLElement(element)->hasDirectionAuto())
- return false;
- if (element->hasActiveAnimations())
- return false;
- // When a dialog is first shown, its style is mutated to center it in the
- // viewport. So the styles can't be shared since the viewport position and
- // size may be different each time a dialog is opened.
- if (element->hasTagName(dialogTag))
- return false;
- if (isShadowHost(element) && element->shadow()->containsActiveStyles())
- return false;
- return true;
+ return m_features.idsInRules.contains(id);
}
-void StyleResolver::addToStyleSharingList(Element* element)
+void StyleResolver::addToStyleSharingList(Element& element)
{
+ // Never add elements to the style sharing list if we're not in a recalcStyle,
+ // otherwise we could leave stale pointers in there.
+ if (!document().inStyleRecalc())
+ return;
+ INCREMENT_STYLE_STATS_COUNTER(*this, sharedStyleCandidates);
if (m_styleSharingList.size() >= styleSharingListSize)
m_styleSharingList.remove(--m_styleSharingList.end());
- m_styleSharingList.prepend(element);
+ m_styleSharingList.prepend(&element);
}
void StyleResolver::clearStyleSharingList()
@@ -295,10 +356,15 @@ void StyleResolver::clearStyleSharingList()
m_styleSharingList.clear();
}
-void StyleResolver::pushParentElement(Element* parent)
+void StyleResolver::fontsNeedUpdate(FontSelector* fontSelector)
+{
+ invalidateMatchedPropertiesCache();
+ m_document.setNeedsStyleRecalc();
+}
+
+void StyleResolver::pushParentElement(Element& parent)
{
- ASSERT(parent);
- const ContainerNode* parentsParent = parent->parentOrShadowHostElement();
+ const ContainerNode* parentsParent = parent.parentOrShadowHostElement();
// We are not always invoked consistently. For example, script execution can cause us to enter
// style recalc in the middle of tree building. We may also be invoked from somewhere within the tree.
@@ -310,18 +376,17 @@ void StyleResolver::pushParentElement(Element* parent)
m_selectorFilter.pushParent(parent);
// Note: We mustn't skip ShadowRoot nodes for the scope stack.
- m_styleTree.pushStyleCache(*parent, parent->parentOrShadowHostNode());
+ m_styleTree.pushStyleCache(parent, parent.parentOrShadowHostNode());
}
-void StyleResolver::popParentElement(Element* parent)
+void StyleResolver::popParentElement(Element& parent)
{
- ASSERT(parent);
// Note that we may get invoked for some random elements in some wacky cases during style resolve.
// Pause maintaining the stack in this case.
- if (m_selectorFilter.parentStackIsConsistent(parent))
+ if (m_selectorFilter.parentStackIsConsistent(&parent))
m_selectorFilter.popParent();
- m_styleTree.popStyleCache(*parent);
+ m_styleTree.popStyleCache(parent);
}
void StyleResolver::pushParentShadowRoot(const ShadowRoot& shadowRoot)
@@ -338,42 +403,34 @@ void StyleResolver::popParentShadowRoot(const ShadowRoot& shadowRoot)
StyleResolver::~StyleResolver()
{
- m_fontSelector->clearDocument();
m_viewportStyleResolver->clearDocument();
}
-inline void StyleResolver::matchShadowDistributedRules(ElementRuleCollector& collector, bool includeEmptyRules)
+inline void StyleResolver::collectTreeBoundaryCrossingRules(Element* element, ElementRuleCollector& collector, bool includeEmptyRules)
{
- // FIXME: Determine tree position.
- CascadeScope cascadeScope = ignoreCascadeScope;
-
- if (m_ruleSets.shadowDistributedRules().isEmpty())
+ if (m_treeBoundaryCrossingRules.isEmpty())
return;
- bool previousCanUseFastReject = collector.canUseFastReject();
- SelectorChecker::BehaviorAtBoundary previousBoundary = collector.behaviorAtBoundary();
- collector.setBehaviorAtBoundary(static_cast<SelectorChecker::BehaviorAtBoundary>(SelectorChecker::CrossesBoundary | SelectorChecker::ScopeContainsLastMatchedElement));
- collector.setCanUseFastReject(false);
-
- collector.clearMatchedRules();
- collector.matchedResult().ranges.lastAuthorRule = collector.matchedResult().matchedProperties.size() - 1;
RuleRange ruleRange = collector.matchedResult().ranges.authorRuleRange();
- Vector<MatchRequest> matchRequests;
- m_ruleSets.shadowDistributedRules().collectMatchRequests(includeEmptyRules, matchRequests);
- for (size_t i = 0; i < matchRequests.size(); ++i)
- collector.collectMatchingRules(matchRequests[i], ruleRange, cascadeScope);
- collector.sortAndTransferMatchedRules();
-
- collector.setBehaviorAtBoundary(previousBoundary);
- collector.setCanUseFastReject(previousCanUseFastReject);
-}
+ CascadeOrder cascadeOrder = 0;
-void StyleResolver::matchHostRules(Element* element, ScopedStyleResolver* resolver, ElementRuleCollector& collector, bool includeEmptyRules)
-{
- if (element != &resolver->scopingNode())
- return;
- resolver->matchHostRules(collector, includeEmptyRules);
+ DocumentOrderedList::iterator it = m_treeBoundaryCrossingRules.end();
+ while (it != m_treeBoundaryCrossingRules.begin()) {
+ --it;
+ const ContainerNode* scopingNode = toContainerNode(*it);
+ RuleSet* ruleSet = m_treeBoundaryCrossingRules.ruleSetScopedBy(scopingNode);
+ unsigned boundaryBehavior = SelectorChecker::CrossesBoundary | SelectorChecker::ScopeContainsLastMatchedElement;
+
+ // If a given scoping node is a shadow root and a given element is in a descendant tree of tree hosted by
+ // the scoping node's shadow host, we should use ScopeIsShadowHost.
+ if (scopingNode && scopingNode->isShadowRoot()) {
+ if (element->isInDescendantTreeOf(toShadowRoot(scopingNode)->host()))
+ boundaryBehavior |= SelectorChecker::ScopeIsShadowHost;
+ scopingNode = toShadowRoot(scopingNode)->host();
+ }
+ collector.collectMatchingRules(MatchRequest(ruleSet, includeEmptyRules, scopingNode), ruleRange, static_cast<SelectorChecker::BehaviorAtBoundary>(boundaryBehavior), ignoreCascadeScope, cascadeOrder++);
+ }
}
static inline bool applyAuthorStylesOf(const Element* element)
@@ -381,7 +438,7 @@ static inline bool applyAuthorStylesOf(const Element* element)
return element->treeScope().applyAuthorStyles() || (element->shadow() && element->shadow()->applyAuthorStyles());
}
-void StyleResolver::matchScopedAuthorRulesForShadowHost(Element* element, ElementRuleCollector& collector, bool includeEmptyRules, Vector<ScopedStyleResolver*, 8>& resolvers, Vector<ScopedStyleResolver*, 8>& resolversInShadowTree)
+void StyleResolver::matchAuthorRulesForShadowHost(Element* element, ElementRuleCollector& collector, bool includeEmptyRules, Vector<ScopedStyleResolver*, 8>& resolvers, Vector<ScopedStyleResolver*, 8>& resolversInShadowTree)
{
collector.clearMatchedRules();
collector.matchedResult().ranges.lastAuthorRule = collector.matchedResult().matchedProperties.size() - 1;
@@ -393,22 +450,26 @@ void StyleResolver::matchScopedAuthorRulesForShadowHost(Element* element, Elemen
for (int j = resolversInShadowTree.size() - 1; j >= 0; --j)
resolversInShadowTree.at(j)->collectMatchingAuthorRules(collector, includeEmptyRules, applyAuthorStyles, cascadeScope, cascadeOrder++);
- if (resolvers.isEmpty() || &resolvers.first()->treeScope() != &element->treeScope())
+ if (resolvers.isEmpty() || resolvers.first()->treeScope() != element->treeScope())
++cascadeScope;
cascadeOrder += resolvers.size();
for (unsigned i = 0; i < resolvers.size(); ++i)
resolvers.at(i)->collectMatchingAuthorRules(collector, includeEmptyRules, applyAuthorStyles, cascadeScope++, --cascadeOrder);
+ collectTreeBoundaryCrossingRules(element, collector, includeEmptyRules);
collector.sortAndTransferMatchedRules();
-
- if (!resolvers.isEmpty())
- matchHostRules(element, resolvers.first(), collector, includeEmptyRules);
}
-void StyleResolver::matchScopedAuthorRules(Element* element, ElementRuleCollector& collector, bool includeEmptyRules)
+void StyleResolver::matchAuthorRules(Element* element, ElementRuleCollector& collector, bool includeEmptyRules)
{
+ collector.clearMatchedRules();
+ collector.matchedResult().ranges.lastAuthorRule = collector.matchedResult().matchedProperties.size() - 1;
+
+ bool applyAuthorStyles = applyAuthorStylesOf(element);
if (m_styleTree.hasOnlyScopedResolverForDocument()) {
- m_styleTree.scopedStyleResolverForDocument()->matchAuthorRules(collector, includeEmptyRules, applyAuthorStylesOf(element));
+ m_styleTree.scopedStyleResolverForDocument()->collectMatchingAuthorRules(collector, includeEmptyRules, applyAuthorStyles, ignoreCascadeScope);
+ collectTreeBoundaryCrossingRules(element, collector, includeEmptyRules);
+ collector.sortAndTransferMatchedRules();
return;
}
@@ -418,45 +479,34 @@ void StyleResolver::matchScopedAuthorRules(Element* element, ElementRuleCollecto
Vector<ScopedStyleResolver*, 8> resolversInShadowTree;
m_styleTree.collectScopedResolversForHostedShadowTrees(element, resolversInShadowTree);
if (!resolversInShadowTree.isEmpty()) {
- matchScopedAuthorRulesForShadowHost(element, collector, includeEmptyRules, resolvers, resolversInShadowTree);
+ matchAuthorRulesForShadowHost(element, collector, includeEmptyRules, resolvers, resolversInShadowTree);
return;
}
if (resolvers.isEmpty())
return;
- bool applyAuthorStyles = applyAuthorStylesOf(element);
CascadeScope cascadeScope = 0;
CascadeOrder cascadeOrder = resolvers.size();
- collector.clearMatchedRules();
- collector.matchedResult().ranges.lastAuthorRule = collector.matchedResult().matchedProperties.size() - 1;
-
for (unsigned i = 0; i < resolvers.size(); ++i, --cascadeOrder) {
ScopedStyleResolver* resolver = resolvers.at(i);
// FIXME: Need to clarify how to treat style scoped.
- resolver->collectMatchingAuthorRules(collector, includeEmptyRules, applyAuthorStyles, cascadeScope++, &resolver->treeScope() == &element->treeScope() && resolver->scopingNode().isShadowRoot() ? 0 : cascadeOrder);
+ resolver->collectMatchingAuthorRules(collector, includeEmptyRules, applyAuthorStyles, cascadeScope++, resolver->treeScope() == element->treeScope() && resolver->scopingNode().isShadowRoot() ? 0 : cascadeOrder);
}
+ collectTreeBoundaryCrossingRules(element, collector, includeEmptyRules);
collector.sortAndTransferMatchedRules();
-
- matchHostRules(element, resolvers.first(), collector, includeEmptyRules);
-}
-
-void StyleResolver::matchAuthorRules(Element* element, ElementRuleCollector& collector, bool includeEmptyRules)
-{
- matchScopedAuthorRules(element, collector, includeEmptyRules);
- matchShadowDistributedRules(collector, includeEmptyRules);
}
-void StyleResolver::matchUserRules(ElementRuleCollector& collector, bool includeEmptyRules)
+void StyleResolver::matchWatchSelectorRules(ElementRuleCollector& collector)
{
- if (!m_ruleSets.userStyle())
+ if (!m_watchedSelectorsRules)
return;
collector.clearMatchedRules();
collector.matchedResult().ranges.lastUserRule = collector.matchedResult().matchedProperties.size() - 1;
- MatchRequest matchRequest(m_ruleSets.userStyle(), includeEmptyRules);
+ MatchRequest matchRequest(m_watchedSelectorsRules.get());
RuleRange ruleRange = collector.matchedResult().ranges.userRuleRange();
collector.collectMatchingRules(matchRequest, ruleRange);
collector.collectMatchingRulesForRegion(matchRequest, ruleRange);
@@ -468,10 +518,6 @@ void StyleResolver::matchUARules(ElementRuleCollector& collector)
{
collector.setMatchingUARules(true);
- // First we match rules from the user agent sheet.
- if (CSSDefaultStyleSheets::simpleDefaultStyleSheet)
- collector.matchedResult().isCacheable = false;
-
RuleSet* userAgentStyleSheet = m_medium->mediaTypeMatchSpecific("print")
? CSSDefaultStyleSheets::defaultPrintStyle : CSSDefaultStyleSheets::defaultStyle;
matchUARules(collector, userAgentStyleSheet);
@@ -485,6 +531,8 @@ void StyleResolver::matchUARules(ElementRuleCollector& collector)
matchUARules(collector, CSSDefaultStyleSheets::viewSourceStyle());
collector.setMatchingUARules(false);
+
+ matchWatchSelectorRules(collector);
}
void StyleResolver::matchUARules(ElementRuleCollector& collector, RuleSet* rules)
@@ -498,14 +546,10 @@ void StyleResolver::matchUARules(ElementRuleCollector& collector, RuleSet* rules
collector.sortAndTransferMatchedRules();
}
-void StyleResolver::matchAllRules(StyleResolverState& state, ElementRuleCollector& collector, bool matchAuthorAndUserStyles, bool includeSMILProperties)
+void StyleResolver::matchAllRules(StyleResolverState& state, ElementRuleCollector& collector, bool includeSMILProperties)
{
matchUARules(collector);
- // Now we check user sheet rules.
- if (matchAuthorAndUserStyles)
- matchUserRules(collector, false);
-
// Now check author rules, beginning first with presentational attributes mapped from HTML.
if (state.element()->isStyledElement()) {
collector.addElementStyleProperties(state.element()->presentationAttributeStyle());
@@ -523,38 +567,21 @@ void StyleResolver::matchAllRules(StyleResolverState& state, ElementRuleCollecto
}
}
- // Check the rules in author sheets next.
- if (matchAuthorAndUserStyles)
- matchAuthorRules(state.element(), collector, false);
+ matchAuthorRules(state.element(), collector, false);
if (state.element()->isStyledElement()) {
- // Now check our inline style attribute.
- if (matchAuthorAndUserStyles && state.element()->inlineStyle()) {
+ if (state.element()->inlineStyle()) {
// Inline style is immutable as long as there is no CSSOM wrapper.
- // FIXME: Media control shadow trees seem to have problems with caching.
- bool isInlineStyleCacheable = !state.element()->inlineStyle()->isMutable() && !state.element()->isInShadowTree();
- // FIXME: Constify.
+ bool isInlineStyleCacheable = !state.element()->inlineStyle()->isMutable();
collector.addElementStyleProperties(state.element()->inlineStyle(), isInlineStyleCacheable);
}
// Now check SMIL animation override style.
- if (includeSMILProperties && matchAuthorAndUserStyles && state.element()->isSVGElement())
+ if (includeSMILProperties && state.element()->isSVGElement())
collector.addElementStyleProperties(toSVGElement(state.element())->animatedSMILStyleProperties(), false /* isCacheable */);
-
- if (state.element()->hasActiveAnimations())
- collector.matchedResult().isCacheable = false;
}
}
-bool StyleResolver::styleSharingCandidateMatchesRuleSet(const ElementResolveContext& context, RenderStyle* style, RuleSet* ruleSet)
-{
- if (!ruleSet)
- return false;
-
- ElementRuleCollector collector(context, m_selectorFilter, style);
- return collector.hasAnyMatchingRules(ruleSet);
-}
-
PassRefPtr<RenderStyle> StyleResolver::styleForDocument(Document& document, CSSFontSelector* fontSelector)
{
const Frame* frame = document.frame();
@@ -604,7 +631,7 @@ static inline void resetDirectionAndWritingModeOnDocument(Document& document)
static void addContentAttrValuesToFeatures(const Vector<AtomicString>& contentAttrValues, RuleFeatureSet& features)
{
for (size_t i = 0; i < contentAttrValues.size(); ++i)
- features.attrsInRules.add(contentAttrValues[i].impl());
+ features.attrsInRules.add(contentAttrValues[i]);
}
PassRefPtr<RenderStyle> StyleResolver::styleForElement(Element* element, RenderStyle* defaultParent, StyleSharingBehavior sharingBehavior,
@@ -612,6 +639,8 @@ PassRefPtr<RenderStyle> StyleResolver::styleForElement(Element* element, RenderS
{
ASSERT(document().frame());
ASSERT(documentSettings());
+ ASSERT(!hasPendingAuthorStyleSheets());
+ ASSERT(!m_needCollectFeatures);
// Once an element has a renderer, we don't try to destroy it, since otherwise the renderer
// will vanish if a style recalc happens during loading.
@@ -619,20 +648,21 @@ PassRefPtr<RenderStyle> StyleResolver::styleForElement(Element* element, RenderS
if (!s_styleNotYetAvailable) {
s_styleNotYetAvailable = RenderStyle::create().leakRef();
s_styleNotYetAvailable->setDisplay(NONE);
- s_styleNotYetAvailable->font().update(m_fontSelector);
+ s_styleNotYetAvailable->font().update(document().styleEngine()->fontSelector());
}
element->document().setHasNodesWithPlaceholderStyle();
return s_styleNotYetAvailable;
}
+ didAccess();
+
if (element == document().documentElement())
resetDirectionAndWritingModeOnDocument(document());
StyleResolverState state(document(), element, defaultParent, regionForStyling);
if (sharingBehavior == AllowStyleSharing && !state.distributedToInsertionPoint() && state.parentStyle()) {
- SharedStyleFinder styleFinder(m_features, m_siblingRuleSet.get(), m_uncommonAttributeRuleSet.get(), this);
- RefPtr<RenderStyle> sharedStyle = styleFinder.locateSharedStyle(state.elementContext(), state.style());
- if (sharedStyle)
+ SharedStyleFinder styleFinder(state.elementContext(), m_features, m_siblingRuleSet.get(), m_uncommonAttributeRuleSet.get(), *this);
+ if (RefPtr<RenderStyle> sharedStyle = styleFinder.findSharedStyle())
return sharedStyle.release();
}
@@ -679,7 +709,7 @@ PassRefPtr<RenderStyle> StyleResolver::styleForElement(Element* element, RenderS
if (matchingBehavior == MatchOnlyUserAgentRules)
matchUARules(collector);
else
- matchAllRules(state, collector, m_matchAuthorAndUserStyles, matchingBehavior != MatchAllRulesExcludingSMIL);
+ matchAllRules(state, collector, matchingBehavior != MatchAllRulesExcludingSMIL);
applyMatchedProperties(state, collector.matchedResult());
@@ -689,29 +719,31 @@ PassRefPtr<RenderStyle> StyleResolver::styleForElement(Element* element, RenderS
StyleAdjuster adjuster(state.cachedUAStyle(), m_document.inQuirksMode());
adjuster.adjustRenderStyle(state.style(), state.parentStyle(), element);
}
- document().didAccessStyleResolver();
+
+ // FIXME: The CSSWG wants to specify that the effects of animations are applied before
+ // important rules, but this currently happens here as we require adjustment to have happened
+ // before deciding which properties to transition.
+ applyAnimatedProperties(state, element);
// FIXME: Shouldn't this be on RenderBody::styleDidChange?
if (element->hasTagName(bodyTag))
- document().textLinkColors().setTextColor(state.style()->visitedDependentColor(CSSPropertyColor));
+ document().textLinkColors().setTextColor(state.style()->color());
- // If any changes to CSS Animations were detected, stash the update away for application after the
- // render object is updated if we're in the appropriate scope.
- if (RuntimeEnabledFeatures::webAnimationsCSSEnabled() && state.animationUpdate())
- element->ensureActiveAnimations()->cssAnimations()->setPendingUpdate(state.takeAnimationUpdate());
+ setAnimationUpdateIfNeeded(state, *element);
// Now return the style.
return state.takeStyle();
}
-PassRefPtr<RenderStyle> StyleResolver::styleForKeyframe(Element* e, const RenderStyle* elementStyle, const StyleKeyframe* keyframe)
+PassRefPtr<RenderStyle> StyleResolver::styleForKeyframe(Element* element, const RenderStyle& elementStyle, RenderStyle* parentStyle, const StyleKeyframe* keyframe, const AtomicString& animationName)
{
ASSERT(document().frame());
ASSERT(documentSettings());
+ ASSERT(!hasPendingAuthorStyleSheets());
- if (e == document().documentElement())
+ if (element == document().documentElement())
resetDirectionAndWritingModeOnDocument(document());
- StyleResolverState state(document(), e);
+ StyleResolverState state(document(), element, parentStyle);
MatchResult result;
if (keyframe->properties())
@@ -720,9 +752,21 @@ PassRefPtr<RenderStyle> StyleResolver::styleForKeyframe(Element* e, const Render
ASSERT(!state.style());
// Create the style
- state.setStyle(RenderStyle::clone(elementStyle));
+ state.setStyle(RenderStyle::clone(&elementStyle));
state.setLineHeightValue(0);
+ // Make sure that the CSSAnimationData for the animation to which this
+ // keyframe belongs is first in the list. This makes sure that if the
+ // animation-timing-function property is set for this keyframe, it will be
+ // applied to the correct CSSAnimationData object. Note that objects other
+ // than the first in the list are ignored when reading the timing function
+ // value. See KeyframeValue::timingFunction().
+ CSSAnimationDataList* animations = state.style()->accessAnimations();
+ ASSERT(animations && !animations->isEmpty());
+ while (animations->animation(0)->name() != animationName)
+ animations->remove(0);
+ ASSERT(!animations->isEmpty() && animations->animation(0)->name() == animationName);
+
state.fontBuilder().initForStyleResolve(state.document(), state.style(), state.useSVGZoomRules());
// We don't need to bother with !important. Since there is only ever one
@@ -751,30 +795,14 @@ PassRefPtr<RenderStyle> StyleResolver::styleForKeyframe(Element* e, const Render
// Start loading resources referenced by this style.
m_styleResourceLoader.loadPendingResources(state.style(), state.elementStyleResources());
+ document().styleEngine()->fontSelector()->loadPendingFonts();
- document().didAccessStyleResolver();
+ didAccess();
return state.takeStyle();
}
-const StyleRuleKeyframes* StyleResolver::matchScopedKeyframesRule(const Element* e, const StringImpl* animationName)
-{
- if (m_styleTree.hasOnlyScopedResolverForDocument())
- return m_styleTree.scopedStyleResolverForDocument()->keyframeStylesForAnimation(animationName);
-
- Vector<ScopedStyleResolver*, 8> stack;
- m_styleTree.resolveScopedKeyframesRules(e, stack);
- if (stack.isEmpty())
- return 0;
-
- for (size_t i = 0; i < stack.size(); ++i) {
- if (const StyleRuleKeyframes* keyframesRule = stack.at(i)->keyframeStylesForAnimation(animationName))
- return keyframesRule;
- }
- return 0;
-}
-
-void StyleResolver::keyframeStylesForAnimation(Element* e, const RenderStyle* elementStyle, KeyframeList& list)
+void StyleResolver::keyframeStylesForAnimation(Element* e, const RenderStyle& elementStyle, KeyframeList& list)
{
ASSERT(!RuntimeEnabledFeatures::webAnimationsCSSEnabled());
list.clear();
@@ -783,18 +811,20 @@ void StyleResolver::keyframeStylesForAnimation(Element* e, const RenderStyle* el
if (!e || list.animationName().isEmpty())
return;
- const StyleRuleKeyframes* keyframesRule = matchScopedKeyframesRule(e, list.animationName().impl());
+ ASSERT(!hasPendingAuthorStyleSheets());
+ const StyleRuleKeyframes* keyframesRule = CSSAnimations::matchScopedKeyframesRule(this, e, list.animationName().impl());
if (!keyframesRule)
return;
// Construct and populate the style for each keyframe
+ const AtomicString& name = list.animationName();
const Vector<RefPtr<StyleKeyframe> >& keyframes = keyframesRule->keyframes();
for (unsigned i = 0; i < keyframes.size(); ++i) {
// Apply the declaration to the style. This is a simplified version of the logic in styleForElement
const StyleKeyframe* keyframe = keyframes[i].get();
KeyframeValue keyframeValue(0, 0);
- keyframeValue.setStyle(styleForKeyframe(e, elementStyle, keyframe));
+ keyframeValue.setStyle(styleForKeyframe(e, elementStyle, 0, keyframe, name));
keyframeValue.addProperties(keyframe->properties());
// Add this keyframe style to all the indicated key times
@@ -814,7 +844,7 @@ void StyleResolver::keyframeStylesForAnimation(Element* e, const RenderStyle* el
zeroPercentKeyframe->setKeyText("0%");
}
KeyframeValue keyframeValue(0, 0);
- keyframeValue.setStyle(styleForKeyframe(e, elementStyle, zeroPercentKeyframe));
+ keyframeValue.setStyle(styleForKeyframe(e, elementStyle, 0, zeroPercentKeyframe, name));
keyframeValue.addProperties(zeroPercentKeyframe->properties());
list.insert(keyframeValue);
}
@@ -827,145 +857,65 @@ void StyleResolver::keyframeStylesForAnimation(Element* e, const RenderStyle* el
hundredPercentKeyframe->setKeyText("100%");
}
KeyframeValue keyframeValue(1, 0);
- keyframeValue.setStyle(styleForKeyframe(e, elementStyle, hundredPercentKeyframe));
+ keyframeValue.setStyle(styleForKeyframe(e, elementStyle, 0, hundredPercentKeyframe, name));
keyframeValue.addProperties(hundredPercentKeyframe->properties());
list.insert(keyframeValue);
}
}
-void StyleResolver::resolveKeyframes(const Element* element, const RenderStyle* style, const AtomicString& name, TimingFunction* defaultTimingFunction, KeyframeAnimationEffect::KeyframeVector& keyframes, RefPtr<TimingFunction>& timingFunction)
+// This function is used by the WebAnimations JavaScript API method animate().
+// FIXME: Remove this when animate() switches away from resolution-dependent parsing.
+PassRefPtr<KeyframeAnimationEffect> StyleResolver::createKeyframeAnimationEffect(Element& element, const Vector<RefPtr<MutableStylePropertySet> >& propertySetVector, KeyframeAnimationEffect::KeyframeVector& keyframes)
{
- ASSERT(RuntimeEnabledFeatures::webAnimationsCSSEnabled());
- const StyleRuleKeyframes* keyframesRule = matchScopedKeyframesRule(element, name.impl());
- if (!keyframesRule)
- return;
+ ASSERT(RuntimeEnabledFeatures::webAnimationsAPIEnabled());
+ ASSERT(propertySetVector.size() == keyframes.size());
- // Construct and populate the style for each keyframe
- HashMap<double, RefPtr<TimingFunction> > timingFunctions;
- const Vector<RefPtr<StyleKeyframe> >& styleKeyframes = keyframesRule->keyframes();
- for (size_t i = 0; i < styleKeyframes.size(); ++i) {
- const StyleKeyframe* styleKeyframe = styleKeyframes[i].get();
- RefPtr<RenderStyle> keyframeStyle = styleForKeyframe(0, style, styleKeyframe);
- RefPtr<Keyframe> keyframe = Keyframe::create();
- const Vector<double>& offsets = styleKeyframe->keys();
- ASSERT(!offsets.isEmpty());
- keyframe->setOffset(offsets[0]);
- TimingFunction* timingFunction = defaultTimingFunction;
- const StylePropertySet* properties = styleKeyframe->properties();
- for (unsigned j = 0; j < properties->propertyCount(); j++) {
- CSSPropertyID property = properties->propertyAt(j).id();
- if (property == CSSPropertyWebkitAnimationTimingFunction || property == CSSPropertyAnimationTimingFunction) {
- // FIXME: This sometimes gets the wrong timing function. See crbug.com/288540.
-
- timingFunction = KeyframeValue::timingFunction(keyframeStyle.get(), name);
- } else if (CSSAnimations::isAnimatableProperty(property)) {
- keyframe->setPropertyValue(property, CSSAnimatableValueFactory::create(property, keyframeStyle.get()).get());
- }
- }
- keyframes.append(keyframe);
- // The last keyframe specified at a given offset is used.
- timingFunctions.set(offsets[0], timingFunction);
- for (size_t j = 1; j < offsets.size(); ++j) {
- keyframes.append(keyframe->cloneWithOffset(offsets[j]));
- timingFunctions.set(offsets[j], timingFunction);
+ StyleResolverState state(element.document(), &element);
+ state.setStyle(RenderStyle::create());
+
+ for (unsigned i = 0; i < propertySetVector.size(); ++i) {
+ for (unsigned j = 0; j < propertySetVector[i]->propertyCount(); ++j) {
+ CSSPropertyID id = propertySetVector[i]->propertyAt(j).id();
+ StyleBuilder::applyProperty(id, state, propertySetVector[i]->getPropertyCSSValue(id).get());
+ keyframes[i]->setPropertyValue(id, CSSAnimatableValueFactory::create(id, *state.style()).get());
}
}
+ return KeyframeAnimationEffect::create(keyframes);
+}
- if (keyframes.isEmpty())
- return;
+PassRefPtr<PseudoElement> StyleResolver::createPseudoElementIfNeeded(Element& element, PseudoId pseudoId)
+{
+ RenderObject* renderer = element.renderer();
+ if (!renderer)
+ return 0;
- // Remove duplicate keyframes. In CSS the last keyframe at a given offset takes priority.
- std::stable_sort(keyframes.begin(), keyframes.end(), Keyframe::compareOffsets);
- size_t targetIndex = 0;
- for (size_t i = 1; i < keyframes.size(); i++) {
- if (keyframes[i]->offset() != keyframes[targetIndex]->offset())
- targetIndex++;
- if (targetIndex != i)
- keyframes[targetIndex] = keyframes[i];
- }
- keyframes.shrink(targetIndex + 1);
-
- // Add 0% and 100% keyframes if absent.
- RefPtr<Keyframe> startKeyframe = keyframes[0];
- if (startKeyframe->offset()) {
- startKeyframe = Keyframe::create();
- startKeyframe->setOffset(0);
- keyframes.prepend(startKeyframe);
- }
- RefPtr<Keyframe> endKeyframe = keyframes[keyframes.size() - 1];
- if (endKeyframe->offset() != 1) {
- endKeyframe = Keyframe::create();
- endKeyframe->setOffset(1);
- keyframes.append(endKeyframe);
- }
- ASSERT(keyframes.size() >= 2);
- ASSERT(!keyframes.first()->offset());
- ASSERT(keyframes.last()->offset() == 1);
-
- // Generate the chained timing function. Note that timing functions apply
- // from the keyframe in which they're specified to the next keyframe.
- // FIXME: Handle keyframe sets where some keyframes don't specify all
- // properties. In this case, timing functions apply between the keyframes
- // which specify a particular property, so we'll need a separate chained
- // timing function (and therefore animation) for each property. See
- // LayoutTests/animations/missing-keyframe-properties-timing-function.html
- if (!timingFunctions.contains(0))
- timingFunctions.set(0, defaultTimingFunction);
- bool isTimingFunctionLinearThroughout = true;
- RefPtr<ChainedTimingFunction> chainedTimingFunction = ChainedTimingFunction::create();
- for (size_t i = 0; i < keyframes.size() - 1; ++i) {
- double lowerBound = keyframes[i]->offset();
- ASSERT(lowerBound >=0 && lowerBound < 1);
- double upperBound = keyframes[i + 1]->offset();
- ASSERT(upperBound > 0 && upperBound <= 1);
- TimingFunction* timingFunction = timingFunctions.get(lowerBound);
- ASSERT(timingFunction);
- isTimingFunctionLinearThroughout &= timingFunction->type() == TimingFunction::LinearFunction;
- chainedTimingFunction->appendSegment(upperBound, timingFunction);
- }
- if (isTimingFunctionLinearThroughout)
- timingFunction = LinearTimingFunction::create();
- else
- timingFunction = chainedTimingFunction;
-
- // Snapshot current property values for 0% and 100% if missing.
- HashSet<CSSPropertyID> allProperties;
- for (size_t i = 0; i < keyframes.size(); i++) {
- const HashSet<CSSPropertyID>& keyframeProperties = keyframes[i]->properties();
- for (HashSet<CSSPropertyID>::const_iterator iter = keyframeProperties.begin(); iter != keyframeProperties.end(); ++iter)
- allProperties.add(*iter);
- }
- const HashSet<CSSPropertyID>& startKeyframeProperties = startKeyframe->properties();
- const HashSet<CSSPropertyID>& endKeyframeProperties = endKeyframe->properties();
- bool missingStartValues = startKeyframeProperties.size() < allProperties.size();
- bool missingEndValues = endKeyframeProperties.size() < allProperties.size();
- if (!missingStartValues && !missingEndValues)
- return;
- for (HashSet<CSSPropertyID>::const_iterator iter = allProperties.begin(); iter != allProperties.end(); ++iter) {
- const CSSPropertyID property = *iter;
- bool startNeedsValue = missingStartValues && !startKeyframeProperties.contains(property);
- bool endNeedsValue = missingEndValues && !endKeyframeProperties.contains(property);
- if (!startNeedsValue && !endNeedsValue)
- continue;
- RefPtr<AnimatableValue> snapshotValue = CSSAnimatableValueFactory::create(property, style);
- if (startNeedsValue)
- startKeyframe->setPropertyValue(property, snapshotValue.get());
- if (endNeedsValue)
- endKeyframe->setPropertyValue(property, snapshotValue.get());
- }
- ASSERT(startKeyframe->properties().size() == allProperties.size());
- ASSERT(endKeyframe->properties().size() == allProperties.size());
+ if (pseudoId < FIRST_INTERNAL_PSEUDOID && !renderer->style()->hasPseudoStyle(pseudoId))
+ return 0;
+
+ RenderStyle* parentStyle = renderer->style();
+ StyleResolverState state(document(), &element, parentStyle);
+ if (!pseudoStyleForElementInternal(element, pseudoId, parentStyle, state))
+ return 0;
+ RefPtr<RenderStyle> style = state.takeStyle();
+ ASSERT(style);
+
+ if (!element.needsPseudoElement(pseudoId, *style))
+ return 0;
+
+ renderer->style()->addCachedPseudoStyle(style.release());
+ RefPtr<PseudoElement> pseudo = PseudoElement::create(&element, pseudoId);
+
+ setAnimationUpdateIfNeeded(state, *pseudo);
+ if (ActiveAnimations* activeAnimations = pseudo->activeAnimations())
+ activeAnimations->cssAnimations().maybeApplyPendingUpdate(pseudo.get());
+ return pseudo.release();
}
-PassRefPtr<RenderStyle> StyleResolver::pseudoStyleForElement(Element* e, const PseudoStyleRequest& pseudoStyleRequest, RenderStyle* parentStyle)
+bool StyleResolver::pseudoStyleForElementInternal(Element& element, const PseudoStyleRequest& pseudoStyleRequest, RenderStyle* parentStyle, StyleResolverState& state)
{
ASSERT(document().frame());
ASSERT(documentSettings());
- ASSERT(parentStyle);
- if (!e)
- return 0;
-
- StyleResolverState state(document(), e, parentStyle);
+ ASSERT(pseudoStyleRequest.pseudoId != FIRST_LINE_INHERITED);
if (pseudoStyleRequest.allowsInheritance(state.parentStyle())) {
state.setStyle(RenderStyle::create());
@@ -982,17 +932,14 @@ PassRefPtr<RenderStyle> StyleResolver::pseudoStyleForElement(Element* e, const P
{
// Check UA, user and author rules.
- ElementRuleCollector collector(state.elementContext(), m_selectorFilter, state.style());
+ ElementRuleCollector collector(state.elementContext(), m_selectorFilter, state.style());
collector.setPseudoStyleRequest(pseudoStyleRequest);
matchUARules(collector);
- if (m_matchAuthorAndUserStyles) {
- matchUserRules(collector, false);
- matchAuthorRules(state.element(), collector, false);
- }
+ matchAuthorRules(state.element(), collector, false);
if (collector.matchedResult().matchedProperties.isEmpty())
- return 0;
+ return false;
state.style()->setStyleType(pseudoStyleRequest.pseudoId);
@@ -1007,10 +954,28 @@ PassRefPtr<RenderStyle> StyleResolver::pseudoStyleForElement(Element* e, const P
adjuster.adjustRenderStyle(state.style(), state.parentStyle(), 0);
}
- // Start loading resources referenced by this style.
- m_styleResourceLoader.loadPendingResources(state.style(), state.elementStyleResources());
+ // FIXME: The CSSWG wants to specify that the effects of animations are applied before
+ // important rules, but this currently happens here as we require adjustment to have happened
+ // before deciding which properties to transition.
+ applyAnimatedProperties(state, element.pseudoElement(pseudoStyleRequest.pseudoId));
+
+ didAccess();
+
+ return true;
+}
+
+PassRefPtr<RenderStyle> StyleResolver::pseudoStyleForElement(Element* element, const PseudoStyleRequest& pseudoStyleRequest, RenderStyle* parentStyle)
+{
+ ASSERT(parentStyle);
+ if (!element)
+ return 0;
+
+ StyleResolverState state(document(), element, parentStyle);
+ if (!pseudoStyleForElementInternal(*element, pseudoStyleRequest, parentStyle, state))
+ return 0;
- document().didAccessStyleResolver();
+ if (PseudoElement* pseudoElement = element->pseudoElement(pseudoStyleRequest.pseudoId))
+ setAnimationUpdateIfNeeded(state, *pseudoElement);
// Now return the style.
return state.takeStyle();
@@ -1018,19 +983,20 @@ PassRefPtr<RenderStyle> StyleResolver::pseudoStyleForElement(Element* e, const P
PassRefPtr<RenderStyle> StyleResolver::styleForPage(int pageIndex)
{
+ ASSERT(!hasPendingAuthorStyleSheets());
resetDirectionAndWritingModeOnDocument(document());
StyleResolverState state(document(), document().documentElement()); // m_rootElementStyle will be set to the document style.
state.setStyle(RenderStyle::create());
- if (state.rootElementStyle())
- state.style()->inheritFrom(state.rootElementStyle());
+ const RenderStyle* rootElementStyle = state.rootElementStyle() ? state.rootElementStyle() : document().renderStyle();
+ ASSERT(rootElementStyle);
+ state.style()->inheritFrom(rootElementStyle);
state.fontBuilder().initForStyleResolve(state.document(), state.style(), state.useSVGZoomRules());
- PageRuleCollector collector(state.elementContext(), pageIndex);
+ PageRuleCollector collector(rootElementStyle, pageIndex);
collector.matchPageRules(CSSDefaultStyleSheets::defaultPrintStyle);
- collector.matchPageRules(m_ruleSets.userStyle());
if (ScopedStyleResolver* scopedResolver = m_styleTree.scopedStyleResolverForDocument())
scopedResolver->matchPageRules(collector);
@@ -1055,8 +1021,9 @@ PassRefPtr<RenderStyle> StyleResolver::styleForPage(int pageIndex)
// Start loading resources referenced by this style.
m_styleResourceLoader.loadPendingResources(state.style(), state.elementStyleResources());
+ document().styleEngine()->fontSelector()->loadPendingFonts();
- document().didAccessStyleResolver();
+ didAccess();
// Now return the style.
return state.takeStyle();
@@ -1064,13 +1031,13 @@ PassRefPtr<RenderStyle> StyleResolver::styleForPage(int pageIndex)
void StyleResolver::collectViewportRules()
{
- collectViewportRules(CSSDefaultStyleSheets::defaultStyle, UserAgentOrigin);
+ viewportStyleResolver()->collectViewportRules(CSSDefaultStyleSheets::defaultStyle, ViewportStyleResolver::UserAgentOrigin);
- if (document().isMobileDocument())
- collectViewportRules(CSSDefaultStyleSheets::xhtmlMobileProfileStyle(), UserAgentOrigin);
+ if (!InspectorInstrumentation::applyViewportStyleOverride(&document(), this))
+ viewportStyleResolver()->collectViewportRules(CSSDefaultStyleSheets::defaultViewportStyle, ViewportStyleResolver::UserAgentOrigin);
- if (m_ruleSets.userStyle())
- collectViewportRules(m_ruleSets.userStyle(), UserAgentOrigin);
+ if (document().isMobileDocument())
+ viewportStyleResolver()->collectViewportRules(CSSDefaultStyleSheets::xhtmlMobileProfileStyle(), ViewportStyleResolver::UserAgentOrigin);
if (ScopedStyleResolver* scopedResolver = m_styleTree.scopedStyleResolverForDocument())
scopedResolver->collectViewportRulesTo(this);
@@ -1078,17 +1045,6 @@ void StyleResolver::collectViewportRules()
viewportStyleResolver()->resolve();
}
-void StyleResolver::collectViewportRules(RuleSet* rules, ViewportOrigin origin)
-{
- rules->compactRulesIfNeeded();
-
- const Vector<StyleRuleViewport*>& viewportRules = rules->viewportRules();
- if (origin == AuthorOrigin && viewportRules.size())
- viewportStyleResolver()->setHasAuthorStyle();
- for (size_t i = 0; i < viewportRules.size(); ++i)
- viewportStyleResolver()->addViewportRule(viewportRules[i]);
-}
-
PassRefPtr<RenderStyle> StyleResolver::defaultStyleForElement()
{
StyleResolverState state(document(), 0);
@@ -1097,7 +1053,7 @@ PassRefPtr<RenderStyle> StyleResolver::defaultStyleForElement()
state.style()->setLineHeight(RenderStyle::initialLineHeight());
state.setLineHeightValue(0);
state.fontBuilder().setInitial(state.style()->effectiveZoom());
- state.style()->font().update(fontSelector());
+ state.style()->font().update(document().styleEngine()->fontSelector());
return state.takeStyle();
}
@@ -1116,127 +1072,111 @@ bool StyleResolver::checkRegionStyle(Element* regionElement)
{
// FIXME (BUG 72472): We don't add @-webkit-region rules of scoped style sheets for the moment,
// so all region rules are global by default. Verify whether that can stand or needs changing.
-
- if (ScopedStyleResolver* scopedResolver = m_styleTree.scopedStyleResolverForDocument())
+ if (ScopedStyleResolver* scopedResolver = m_styleTree.scopedStyleResolverForDocument()) {
if (scopedResolver->checkRegionStyle(regionElement))
return true;
-
- if (m_ruleSets.userStyle()) {
- unsigned rulesSize = m_ruleSets.userStyle()->m_regionSelectorsAndRuleSets.size();
- for (unsigned i = 0; i < rulesSize; ++i) {
- ASSERT(m_ruleSets.userStyle()->m_regionSelectorsAndRuleSets.at(i).ruleSet.get());
- if (checkRegionSelector(m_ruleSets.userStyle()->m_regionSelectorsAndRuleSets.at(i).selector, regionElement))
- return true;
- }
}
-
return false;
}
void StyleResolver::updateFont(StyleResolverState& state)
{
- state.fontBuilder().createFont(m_fontSelector, state.parentStyle(), state.style());
+ state.fontBuilder().createFont(document().styleEngine()->fontSelector(), state.parentStyle(), state.style());
}
-PassRefPtr<CSSRuleList> StyleResolver::styleRulesForElement(Element* e, unsigned rulesToInclude)
+PassRefPtr<StyleRuleList> StyleResolver::styleRulesForElement(Element* element, unsigned rulesToInclude)
{
- return pseudoStyleRulesForElement(e, NOPSEUDO, rulesToInclude);
+ ASSERT(element);
+ StyleResolverState state(document(), element);
+ ElementRuleCollector collector(state.elementContext(), m_selectorFilter, state.style());
+ collector.setMode(SelectorChecker::CollectingStyleRules);
+ collectPseudoRulesForElement(element, collector, NOPSEUDO, rulesToInclude);
+ return collector.matchedStyleRuleList();
}
-PassRefPtr<CSSRuleList> StyleResolver::pseudoStyleRulesForElement(Element* e, PseudoId pseudoId, unsigned rulesToInclude)
+PassRefPtr<CSSRuleList> StyleResolver::pseudoCSSRulesForElement(Element* element, PseudoId pseudoId, unsigned rulesToInclude, ShouldIncludeStyleSheetInCSSOMWrapper includeDocument)
{
- if (!e || !e->document().haveStylesheetsLoaded())
- return 0;
+ ASSERT(element);
+ StyleResolverState state(document(), element);
+ ElementRuleCollector collector(state.elementContext(), m_selectorFilter, state.style(), includeDocument);
+ collector.setMode(SelectorChecker::CollectingCSSRules);
+ collectPseudoRulesForElement(element, collector, pseudoId, rulesToInclude);
+ return collector.matchedCSSRuleList();
+}
- if (e == document().documentElement())
- resetDirectionAndWritingModeOnDocument(document());
- StyleResolverState state(document(), e);
+PassRefPtr<CSSRuleList> StyleResolver::cssRulesForElement(Element* element, unsigned rulesToInclude, ShouldIncludeStyleSheetInCSSOMWrapper includeDocument)
+{
+ return pseudoCSSRulesForElement(element, NOPSEUDO, rulesToInclude, includeDocument);
+}
- ElementRuleCollector collector(state.elementContext(), m_selectorFilter, state.style());
- collector.setMode(SelectorChecker::CollectingRules);
+void StyleResolver::collectPseudoRulesForElement(Element* element, ElementRuleCollector& collector, PseudoId pseudoId, unsigned rulesToInclude)
+{
collector.setPseudoStyleRequest(PseudoStyleRequest(pseudoId));
- if (rulesToInclude & UAAndUserCSSRules) {
- // First we match rules from the user agent sheet.
+ if (rulesToInclude & UAAndUserCSSRules)
matchUARules(collector);
- // Now we check user sheet rules.
- if (m_matchAuthorAndUserStyles)
- matchUserRules(collector, rulesToInclude & EmptyCSSRules);
- }
-
- if (m_matchAuthorAndUserStyles && (rulesToInclude & AuthorCSSRules)) {
+ if (rulesToInclude & AuthorCSSRules) {
collector.setSameOriginOnly(!(rulesToInclude & CrossOriginCSSRules));
-
- // Check the rules in author sheets.
- matchAuthorRules(state.element(), collector, rulesToInclude & EmptyCSSRules);
+ matchAuthorRules(element, collector, rulesToInclude & EmptyCSSRules);
}
-
- return collector.matchedRuleList();
}
// -------------------------------------------------------------------------------------
// this is mostly boring stuff on how to apply a certain rule to the renderstyle...
+void StyleResolver::applyAnimatedProperties(StyleResolverState& state, Element* animatingElement)
+{
+ if (!RuntimeEnabledFeatures::webAnimationsCSSEnabled())
+ return;
+
+ const Element* element = state.element();
+ ASSERT(element);
+
+ // The animating element may be this element, or its pseudo element. It is
+ // null when calculating the style for a potential pseudo element that has
+ // yet to be created.
+ ASSERT(animatingElement == element || !animatingElement || animatingElement->parentOrShadowHostElement() == element);
+
+ if (!(animatingElement && animatingElement->hasActiveAnimations())
+ && !(state.style()->transitions() && !state.style()->transitions()->isEmpty())
+ && !(state.style()->animations() && !state.style()->animations()->isEmpty()))
+ return;
+
+ state.setAnimationUpdate(CSSAnimations::calculateUpdate(animatingElement, *element, *state.style(), state.parentStyle(), this));
+ if (!state.animationUpdate())
+ return;
+
+ const AnimationEffect::CompositableValueMap& compositableValuesForAnimations = state.animationUpdate()->compositableValuesForAnimations();
+ const AnimationEffect::CompositableValueMap& compositableValuesForTransitions = state.animationUpdate()->compositableValuesForTransitions();
+ applyAnimatedProperties<HighPriorityProperties>(state, compositableValuesForAnimations);
+ applyAnimatedProperties<HighPriorityProperties>(state, compositableValuesForTransitions);
+ applyAnimatedProperties<LowPriorityProperties>(state, compositableValuesForAnimations);
+ applyAnimatedProperties<LowPriorityProperties>(state, compositableValuesForTransitions);
+
+ // If the animations/transitions change opacity or transform, we need to update
+ // the style to impose the stacking rules. Note that this is also
+ // done in StyleResolver::adjustRenderStyle().
+ RenderStyle* style = state.style();
+ if (style->hasAutoZIndex() && (style->opacity() < 1.0f || style->hasTransform()))
+ style->setZIndex(0);
+}
+
template <StyleResolver::StyleApplicationPass pass>
-bool StyleResolver::applyAnimatedProperties(StyleResolverState& state, const DocumentTimeline* timeline)
+void StyleResolver::applyAnimatedProperties(StyleResolverState& state, const AnimationEffect::CompositableValueMap& compositableValues)
{
ASSERT(RuntimeEnabledFeatures::webAnimationsCSSEnabled());
ASSERT(pass != VariableDefinitions);
ASSERT(pass != AnimationProperties);
- const Element* element = state.element();
- const CSSAnimationUpdate* update = state.animationUpdate();
- AnimationStack* animationStack = timeline->animationStack(element);
- if (!animationStack)
- return false;
- bool didApply = false;
- const Vector<Animation*>& animations = animationStack->activeAnimations(element);
- for (size_t i = 0; i < animations.size(); ++i) {
- RefPtr<Animation> animation = animations.at(i);
- if (update && update->isCancelled(animation->player()))
+ for (AnimationEffect::CompositableValueMap::const_iterator iter = compositableValues.begin(); iter != compositableValues.end(); ++iter) {
+ CSSPropertyID property = iter->key;
+ if (!isPropertyForPass<pass>(property))
continue;
- const AnimationEffect::CompositableValueMap* compositableValues = animation->compositableValues();
- for (AnimationEffect::CompositableValueMap::const_iterator iter = compositableValues->begin(); iter != compositableValues->end(); ++iter) {
- CSSPropertyID property = iter->key;
- if (!isPropertyForPass<pass>(property))
- continue;
- RELEASE_ASSERT_WITH_MESSAGE(!iter->value->dependsOnUnderlyingValue(), "Not yet implemented: An interface for compositing onto the underlying value.");
- RefPtr<AnimatableValue> animatableValue = iter->value->compositeOnto(0);
- if (pass == HighPriorityProperties && property == CSSPropertyLineHeight)
- state.setLineHeightValue(toAnimatableNumber(animatableValue.get())->toCSSValue().get());
- else
- AnimatedStyleBuilder::applyProperty(property, state, animatableValue.get());
- didApply = true;
- }
+ ASSERT_WITH_MESSAGE(!iter->value->dependsOnUnderlyingValue(), "Web Animations not yet implemented: An interface for compositing onto the underlying value.");
+ RefPtr<AnimatableValue> animatableValue = iter->value->compositeOnto(0);
+ AnimatedStyleBuilder::applyProperty(property, state, animatableValue.get());
}
-
- if (!update)
- return didApply;
-
- // FIXME: Remove this repetition by incorporating a merge of newAnimations with AnimationStack.
- // Then resolve the stack before calling applyAnimatedProperties, eg.
- // CompositableValueMap* resolved = timeline->animationStack()->resolveWith(newAnimations);
- // applyAnimatedProperties(state, resolved);
- const Vector<CSSAnimationUpdate::NewAnimation>& newAnimations = update->newAnimations();
- for (size_t i = 0; i < newAnimations.size(); ++i) {
- RefPtr<InertAnimation> animation = newAnimations.at(i).animation;
- OwnPtr<AnimationEffect::CompositableValueMap> compositableValues = animation->sample();
- if (!compositableValues)
- continue;
- for (AnimationEffect::CompositableValueMap::const_iterator iter = compositableValues->begin(); iter != compositableValues->end(); ++iter) {
- CSSPropertyID property = iter->key;
- if (!isPropertyForPass<pass>(property))
- continue;
- RefPtr<AnimatableValue> animatableValue = iter->value->compositeOnto(AnimatableValue::neutralValue());
- if (pass == HighPriorityProperties && property == CSSPropertyLineHeight)
- state.setLineHeightValue(toAnimatableNumber(animatableValue.get())->toCSSValue().get());
- else
- AnimatedStyleBuilder::applyProperty(property, state, animatableValue.get());
- didApply = true;
- }
- }
- return didApply;
}
// http://dev.w3.org/csswg/css3-regions/#the-at-region-style-rule
@@ -1332,6 +1272,7 @@ template <StyleResolver::StyleApplicationPass pass>
void StyleResolver::applyProperties(StyleResolverState& state, const StylePropertySet* properties, StyleRule* rule, bool isImportant, bool inheritedOnly, PropertyWhitelistType propertyWhitelistType)
{
ASSERT((propertyWhitelistType != PropertyWhitelistRegion) || state.regionForStyling());
+ state.setCurrentRule(rule);
unsigned propertyCount = properties->propertyCount();
for (unsigned i = 0; i < propertyCount; ++i) {
@@ -1396,28 +1337,12 @@ void StyleResolver::invalidateMatchedPropertiesCache()
m_matchedPropertiesCache.clear();
}
-void StyleResolver::calculateCSSAnimationUpdate(StyleResolverState& state)
-{
- if (!RuntimeEnabledFeatures::webAnimationsCSSEnabled())
- return;
-
- const Element* element = state.element();
- ASSERT(element);
-
- if (!CSSAnimations::needsUpdate(element, state.style()))
- return;
-
- ActiveAnimations* activeAnimations = element->activeAnimations();
- const CSSAnimationDataList* animations = state.style()->animations();
- const CSSAnimations* cssAnimations = activeAnimations ? activeAnimations->cssAnimations() : 0;
- state.setAnimationUpdate(CSSAnimations::calculateUpdate(element, state.style(), cssAnimations, animations, this));
-}
-
void StyleResolver::applyMatchedProperties(StyleResolverState& state, const MatchResult& matchResult)
{
const Element* element = state.element();
ASSERT(element);
- STYLE_STATS_ADD_MATCHED_PROPERTIES_SEARCH();
+
+ INCREMENT_STYLE_STATS_COUNTER(*this, matchedPropertyApply);
unsigned cacheHash = matchResult.isCacheable ? computeMatchedPropertiesHash(matchResult.matchedProperties.data(), matchResult.matchedProperties.size()) : 0;
bool applyInheritedOnly = false;
@@ -1425,13 +1350,13 @@ void StyleResolver::applyMatchedProperties(StyleResolverState& state, const Matc
if (cacheHash && (cachedMatchedProperties = m_matchedPropertiesCache.find(cacheHash, state, matchResult))
&& MatchedPropertiesCache::isCacheable(element, state.style(), state.parentStyle())) {
- STYLE_STATS_ADD_MATCHED_PROPERTIES_HIT();
+ INCREMENT_STYLE_STATS_COUNTER(*this, matchedPropertyCacheHit);
// We can build up the style by copying non-inherited properties from an earlier style object built using the same exact
// style declarations. We then only need to apply the inherited properties, if any, as their values can depend on the
// element context. This is fast and saves memory by reusing the style data structures.
state.style()->copyNonInheritedFrom(cachedMatchedProperties->renderStyle.get());
if (state.parentStyle()->inheritedDataShared(cachedMatchedProperties->parentRenderStyle.get()) && !isAtShadowBoundary(element)) {
- STYLE_STATS_ADD_MATCHED_PROPERTIES_HIT_SHARED_INHERITED();
+ INCREMENT_STYLE_STATS_COUNTER(*this, matchedPropertyCacheInheritedHit);
EInsideLink linkStatus = state.style()->insideLink();
// If the cache item parent style has identical inherited properties to the current parent style then the
@@ -1457,6 +1382,12 @@ void StyleResolver::applyMatchedProperties(StyleResolverState& state, const Matc
applyMatchedProperties<AnimationProperties>(state, matchResult, true, matchResult.ranges.firstUserRule, matchResult.ranges.lastUserRule, applyInheritedOnly);
applyMatchedProperties<AnimationProperties>(state, matchResult, true, matchResult.ranges.firstUARule, matchResult.ranges.lastUARule, applyInheritedOnly);
+ // Match transition-property / animation-name length by trimming and
+ // lengthening other transition / animation property lists
+ // FIXME: This is wrong because we shouldn't affect the computed values
+ state.style()->adjustAnimations();
+ state.style()->adjustTransitions();
+
// Now we have all of the matched rules in the appropriate order. Walk the rules and apply
// high-priority properties first, i.e., those properties that other properties depend on.
// The order is (1) high-priority not important, (2) high-priority important, (3) normal not important
@@ -1495,48 +1426,54 @@ void StyleResolver::applyMatchedProperties(StyleResolverState& state, const Matc
applyMatchedProperties<LowPriorityProperties>(state, matchResult, true, matchResult.ranges.firstUserRule, matchResult.ranges.lastUserRule, applyInheritedOnly);
applyMatchedProperties<LowPriorityProperties>(state, matchResult, true, matchResult.ranges.firstUARule, matchResult.ranges.lastUARule, applyInheritedOnly);
- if (RuntimeEnabledFeatures::webAnimationsEnabled() && !applyInheritedOnly) {
- calculateCSSAnimationUpdate(state);
- // Apply animated properties, then reapply any rules marked important.
- if (applyAnimatedProperties<HighPriorityProperties>(state, element->document().timeline())) {
- bool important = true;
- applyMatchedProperties<HighPriorityProperties>(state, matchResult, important, matchResult.ranges.firstAuthorRule, matchResult.ranges.lastAuthorRule, applyInheritedOnly);
- applyMatchedProperties<HighPriorityProperties>(state, matchResult, important, matchResult.ranges.firstUserRule, matchResult.ranges.lastUserRule, applyInheritedOnly);
- applyMatchedProperties<HighPriorityProperties>(state, matchResult, important, matchResult.ranges.firstUARule, matchResult.ranges.lastUARule, applyInheritedOnly);
- }
- if (applyAnimatedProperties<LowPriorityProperties>(state, element->document().timeline())) {
- bool important = true;
- applyMatchedProperties<LowPriorityProperties>(state, matchResult, important, matchResult.ranges.firstAuthorRule, matchResult.ranges.lastAuthorRule, applyInheritedOnly);
- applyMatchedProperties<LowPriorityProperties>(state, matchResult, important, matchResult.ranges.firstUserRule, matchResult.ranges.lastUserRule, applyInheritedOnly);
- applyMatchedProperties<LowPriorityProperties>(state, matchResult, important, matchResult.ranges.firstUARule, matchResult.ranges.lastUARule, applyInheritedOnly);
- }
- }
-
// Start loading resources referenced by this style.
m_styleResourceLoader.loadPendingResources(state.style(), state.elementStyleResources());
+ document().styleEngine()->fontSelector()->loadPendingFonts();
- ASSERT(!state.fontBuilder().fontDirty());
-
-#ifdef STYLE_STATS
- if (!cachedMatchedProperties)
- STYLE_STATS_ADD_MATCHED_PROPERTIES_TO_CACHE();
-#endif
+ if (!cachedMatchedProperties && cacheHash && MatchedPropertiesCache::isCacheable(element, state.style(), state.parentStyle())) {
+ INCREMENT_STYLE_STATS_COUNTER(*this, matchedPropertyCacheAdded);
+ m_matchedPropertiesCache.add(state.style(), state.parentStyle(), cacheHash, matchResult);
+ }
- if (cachedMatchedProperties || !cacheHash)
- return;
- if (!MatchedPropertiesCache::isCacheable(element, state.style(), state.parentStyle()))
- return;
- STYLE_STATS_ADD_MATCHED_PROPERTIES_ENTERED_INTO_CACHE();
- m_matchedPropertiesCache.add(state.style(), state.parentStyle(), cacheHash, matchResult);
+ ASSERT(!state.fontBuilder().fontDirty());
}
CSSPropertyValue::CSSPropertyValue(CSSPropertyID id, const StylePropertySet& propertySet)
: property(id), value(propertySet.getPropertyCSSValue(id).get())
{ }
+void StyleResolver::enableStats(StatsReportType reportType)
+{
+ if (m_styleResolverStats)
+ return;
+ m_styleResolverStats = StyleResolverStats::create();
+ m_styleResolverStatsTotals = StyleResolverStats::create();
+ if (reportType == ReportSlowStats) {
+ m_styleResolverStats->printMissedCandidateCount = true;
+ m_styleResolverStatsTotals->printMissedCandidateCount = true;
+ }
+}
+
+void StyleResolver::disableStats()
+{
+ m_styleResolverStatsSequence = 0;
+ m_styleResolverStats.clear();
+ m_styleResolverStatsTotals.clear();
+}
+
+void StyleResolver::printStats()
+{
+ if (!m_styleResolverStats)
+ return;
+ fprintf(stderr, "=== Style Resolver Stats (resolve #%u) (%s) ===\n", ++m_styleResolverStatsSequence, m_document.url().string().utf8().data());
+ fprintf(stderr, "%s\n", m_styleResolverStats->report().utf8().data());
+ fprintf(stderr, "== Totals ==\n");
+ fprintf(stderr, "%s\n", m_styleResolverStatsTotals->report().utf8().data());
+}
+
void StyleResolver::applyPropertiesToStyle(const CSSPropertyValue* properties, size_t count, RenderStyle* style)
{
- StyleResolverState state(document(), 0, style);
+ StyleResolverState state(document(), document().documentElement(), style);
state.setStyle(style);
state.fontBuilder().initForStyleResolve(document(), style, state.useSVGZoomRules());
@@ -1559,54 +1496,19 @@ void StyleResolver::applyPropertiesToStyle(const CSSPropertyValue* properties, s
}
}
-void StyleResolver::addViewportDependentMediaQueryResult(const MediaQueryExp* expr, bool result)
+void StyleResolver::addMediaQueryResults(const MediaQueryResultList& list)
{
- m_viewportDependentMediaQueryResults.append(adoptPtr(new MediaQueryResult(*expr, result)));
+ for (size_t i = 0; i < list.size(); ++i)
+ m_viewportDependentMediaQueryResults.append(list[i]);
}
bool StyleResolver::affectedByViewportChange() const
{
- unsigned s = m_viewportDependentMediaQueryResults.size();
- for (unsigned i = 0; i < s; i++) {
+ for (unsigned i = 0; i < m_viewportDependentMediaQueryResults.size(); ++i) {
if (m_medium->eval(&m_viewportDependentMediaQueryResults[i]->m_expression) != m_viewportDependentMediaQueryResults[i]->m_result)
return true;
}
return false;
}
-#ifdef STYLE_STATS
-StyleSharingStats StyleResolver::m_styleSharingStats;
-
-static void printStyleStats(unsigned searches, unsigned elementsEligibleForSharing, unsigned stylesShared, unsigned searchFoundSiblingForSharing, unsigned searchesMissedSharing,
- unsigned matchedPropertiesSearches, unsigned matchedPropertiesHit, unsigned matchedPropertiesSharedInheritedHit, unsigned matchedPropertiesToCache, unsigned matchedPropertiesEnteredIntoCache)
-{
- double percentOfElementsSharingStyle = (stylesShared * 100.0) / searches;
- double percentOfNodesEligibleForSharing = (elementsEligibleForSharing * 100.0) / searches;
- double percentOfEligibleSharingRelativesFound = (searchFoundSiblingForSharing * 100.0) / searches;
- double percentOfMatchedPropertiesHit = (matchedPropertiesHit * 100.0) / matchedPropertiesSearches;
- double percentOfMatchedPropertiesSharedInheritedHit = (matchedPropertiesSharedInheritedHit * 100.0) / matchedPropertiesSearches;
- double percentOfMatchedPropertiesEnteredIntoCache = (matchedPropertiesEnteredIntoCache * 100.0) / matchedPropertiesToCache;
-
- fprintf(stderr, "%u elements checked, %u were eligible for style sharing (%.2f%%).\n", searches, elementsEligibleForSharing, percentOfNodesEligibleForSharing);
- fprintf(stderr, "%u elements were found to share with, %u were possible (%.2f%%).\n", searchFoundSiblingForSharing, searchesMissedSharing + searchFoundSiblingForSharing, percentOfEligibleSharingRelativesFound);
- fprintf(stderr, "%u styles were actually shared once sibling and attribute rules were considered (%.2f%%).\n", stylesShared, percentOfElementsSharingStyle);
- fprintf(stderr, "%u/%u (%.2f%%) matched property lookups hit the cache.\n", matchedPropertiesHit, matchedPropertiesSearches, percentOfMatchedPropertiesHit);
- fprintf(stderr, "%u/%u (%.2f%%) matched property lookups hit the cache and shared inherited data.\n", matchedPropertiesSharedInheritedHit, matchedPropertiesSearches, percentOfMatchedPropertiesSharedInheritedHit);
- fprintf(stderr, "%u/%u (%.2f%%) matched properties were cacheable\n", matchedPropertiesEnteredIntoCache, matchedPropertiesToCache, percentOfMatchedPropertiesEnteredIntoCache);
-}
-
-void StyleSharingStats::printStats() const
-{
- fprintf(stderr, "--------------------------------------------------------------------------------\n");
- fprintf(stderr, "This recalc style:\n");
- printStyleStats(m_searches, m_elementsEligibleForSharing, m_stylesShared, m_searchFoundSiblingForSharing, m_searchesMissedSharing,
- m_matchedPropertiesSearches, m_matchedPropertiesHit, m_matchedPropertiesSharedInheritedHit, m_matchedPropertiesToCache, m_matchedPropertiesEnteredIntoCache);
-
- fprintf(stderr, "Total:\n");
- printStyleStats(m_totalSearches, m_totalElementsEligibleForSharing, m_totalStylesShared, m_totalSearchFoundSiblingForSharing, m_totalSearchesMissedSharing,
- m_totalMatchedPropertiesSearches, m_totalMatchedPropertiesHit, m_totalMatchedPropertiesSharedInheritedHit, m_totalMatchedPropertiesToCache, m_totalMatchedPropertiesEnteredIntoCache);
- fprintf(stderr, "--------------------------------------------------------------------------------\n");
-}
-#endif
-
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/css/resolver/StyleResolver.h b/chromium/third_party/WebKit/Source/core/css/resolver/StyleResolver.h
index 16cf4013a9a..f1dae0b2381 100644
--- a/chromium/third_party/WebKit/Source/core/css/resolver/StyleResolver.h
+++ b/chromium/third_party/WebKit/Source/core/css/resolver/StyleResolver.h
@@ -23,7 +23,6 @@
#define StyleResolver_h
#include "core/animation/KeyframeAnimationEffect.h"
-#include "core/css/DocumentRuleSets.h"
#include "core/css/InspectorCSSOMWrappers.h"
#include "core/css/PseudoStyleRequest.h"
#include "core/css/RuleFeature.h"
@@ -31,14 +30,18 @@
#include "core/css/SelectorChecker.h"
#include "core/css/SelectorFilter.h"
#include "core/css/SiblingTraversalStrategies.h"
+#include "core/css/TreeBoundaryCrossingRules.h"
#include "core/css/resolver/MatchedPropertiesCache.h"
#include "core/css/resolver/ScopedStyleResolver.h"
+#include "core/css/resolver/ScopedStyleTree.h"
#include "core/css/resolver/StyleBuilder.h"
+#include "core/css/resolver/StyleResolverIncludes.h"
#include "core/css/resolver/StyleResolverState.h"
#include "core/css/resolver/StyleResourceLoader.h"
#include "wtf/Deque.h"
#include "wtf/HashMap.h"
#include "wtf/HashSet.h"
+#include "wtf/ListHashSet.h"
#include "wtf/RefPtr.h"
#include "wtf/Vector.h"
@@ -58,13 +61,13 @@ class ElementRuleCollector;
class KeyframeList;
class KeyframeValue;
class MediaQueryEvaluator;
-class MediaQueryExp;
class MediaQueryResult;
class RenderRegion;
class RuleData;
class Settings;
class StyleKeyframe;
class StylePropertySet;
+class StyleResolverStats;
class StyleRule;
class StyleRuleKeyframes;
class StyleRulePage;
@@ -87,81 +90,7 @@ enum RuleMatchingBehavior {
};
const unsigned styleSharingListSize = 40;
-typedef WTF::Deque<RefPtr<Element>, styleSharingListSize> StyleSharingList;
-
-#undef STYLE_STATS
-
-#ifdef STYLE_STATS
-struct StyleSharingStats {
- void addSearch() { ++m_searches; ++m_totalSearches; }
- void addElementEligibleForSharing() { ++m_elementsEligibleForSharing; ++m_totalElementsEligibleForSharing; }
- void addStyleShared() { ++m_stylesShared; ++m_totalStylesShared; }
- void addSearchFoundSiblingForSharing() { ++m_searchFoundSiblingForSharing; ++m_totalSearchFoundSiblingForSharing; }
- void addSearchMissedSharing() { ++m_searchesMissedSharing; ++m_totalSearchesMissedSharing; }
- void addMatchedPropertiesSearch() { ++m_matchedPropertiesSearches; ++m_totalMatchedPropertiesSearches; }
- void addMatchedPropertiesHit() { ++m_matchedPropertiesHit; ++m_totalMatchedPropertiesHit; }
- void addMatchedPropertiesHitSharedInherited() { ++m_matchedPropertiesSharedInheritedHit; ++m_totalMatchedPropertiesSharedInheritedHit; }
- void addMatchedPropertiesToCache() { ++m_matchedPropertiesToCache; ++m_totalMatchedPropertiesToCache; }
- void addMatchedPropertiesEnteredIntoCache() { ++m_matchedPropertiesEnteredIntoCache; ++m_totalMatchedPropertiesEnteredIntoCache; }
-
- void clear()
- {
- m_searches = m_elementsEligibleForSharing = m_stylesShared = m_searchesMissedSharing = m_searchFoundSiblingForSharing =
- m_matchedPropertiesSearches = m_matchedPropertiesHit = m_matchedPropertiesSharedInheritedHit = m_matchedPropertiesToCache =
- m_matchedPropertiesEnteredIntoCache = 0;
- }
-
- void printStats() const;
-
- unsigned m_searches;
- unsigned m_elementsEligibleForSharing;
- unsigned m_stylesShared;
- unsigned m_searchFoundSiblingForSharing;
- unsigned m_searchesMissedSharing;
- unsigned m_matchedPropertiesSearches;
- unsigned m_matchedPropertiesHit;
- unsigned m_matchedPropertiesSharedInheritedHit;
- unsigned m_matchedPropertiesToCache;
- unsigned m_matchedPropertiesEnteredIntoCache;
-
- unsigned m_totalSearches;
- unsigned m_totalElementsEligibleForSharing;
- unsigned m_totalStylesShared;
- unsigned m_totalSearchFoundSiblingForSharing;
- unsigned m_totalSearchesMissedSharing;
- unsigned m_totalMatchedPropertiesSearches;
- unsigned m_totalMatchedPropertiesHit;
- unsigned m_totalMatchedPropertiesSharedInheritedHit;
- unsigned m_totalMatchedPropertiesToCache;
- unsigned m_totalMatchedPropertiesEnteredIntoCache;
-};
-
-#define STYLE_STATS_ADD_SEARCH() StyleResolver::styleSharingStats().addSearch();
-#define STYLE_STATS_ADD_ELEMENT_ELIGIBLE_FOR_SHARING() StyleResolver::styleSharingStats().addElementEligibleForSharing();
-#define STYLE_STATS_ADD_STYLE_SHARED() StyleResolver::styleSharingStats().addStyleShared();
-#define STYLE_STATS_ADD_SEARCH_FOUND_SIBLING_FOR_SHARING() StyleResolver::styleSharingStats().addSearchFoundSiblingForSharing();
-#define STYLE_STATS_ADD_SEARCH_MISSED_SHARING() StyleResolver::styleSharingStats().addSearchMissedSharing();
-#define STYLE_STATS_PRINT() StyleResolver::styleSharingStats().printStats();
-#define STYLE_STATS_CLEAR() StyleResolver::styleSharingStats().clear();
-#define STYLE_STATS_ADD_MATCHED_PROPERTIES_SEARCH() StyleResolver::styleSharingStats().addMatchedPropertiesSearch();
-#define STYLE_STATS_ADD_MATCHED_PROPERTIES_HIT() StyleResolver::styleSharingStats().addMatchedPropertiesHit();
-#define STYLE_STATS_ADD_MATCHED_PROPERTIES_HIT_SHARED_INHERITED() StyleResolver::styleSharingStats().addMatchedPropertiesHitSharedInherited();
-#define STYLE_STATS_ADD_MATCHED_PROPERTIES_TO_CACHE() StyleResolver::styleSharingStats().addMatchedPropertiesToCache();
-#define STYLE_STATS_ADD_MATCHED_PROPERTIES_ENTERED_INTO_CACHE() StyleResolver::styleSharingStats().addMatchedPropertiesEnteredIntoCache();
-#else
-#define STYLE_STATS_ADD_SEARCH() (void(0));
-#define STYLE_STATS_ADD_ELEMENT_ELIGIBLE_FOR_SHARING() (void(0));
-#define STYLE_STATS_ADD_STYLE_SHARED() (void(0));
-#define STYLE_STATS_ADD_SEARCH_FOUND_SIBLING_FOR_SHARING() (void(0));
-#define STYLE_STATS_ADD_SEARCH_MISSED_SHARING() (void(0));
-#define STYLE_STATS_PRINT() (void(0));
-#define STYLE_STATS_CLEAR() (void(0));
-#define STYLE_STATS_ADD_MATCHED_PROPERTIES_SEARCH() (void(0));
-#define STYLE_STATS_ADD_MATCHED_PROPERTIES_HIT() (void(0));
-#define STYLE_STATS_ADD_MATCHED_PROPERTIES_HIT_SHARED_INHERITED() (void(0));
-#define STYLE_STATS_ADD_MATCHED_PROPERTIES_TO_CACHE() (void(0));
-#define STYLE_STATS_ADD_MATCHED_PROPERTIES_ENTERED_INTO_CACHE() (void(0));
-#endif
+typedef WTF::Deque<Element*, styleSharingListSize> StyleSharingList;
struct CSSPropertyValue {
CSSPropertyValue(CSSPropertyID property, CSSValue* value)
@@ -173,32 +102,29 @@ struct CSSPropertyValue {
};
// This class selects a RenderStyle for a given element based on a collection of stylesheets.
-class StyleResolver {
+class StyleResolver : public FontSelectorClient {
WTF_MAKE_NONCOPYABLE(StyleResolver); WTF_MAKE_FAST_ALLOCATED;
public:
- StyleResolver(Document&, bool matchAuthorAndUserStyles);
+ explicit StyleResolver(Document&);
~StyleResolver();
// FIXME: StyleResolver should not be keeping tree-walk state.
// These should move to some global tree-walk state, or should be contained in a
// TreeWalkContext or similar which is passed in to StyleResolver methods when available.
// Using these during tree walk will allow style selector to optimize child and descendant selector lookups.
- void pushParentElement(Element*);
- void popParentElement(Element*);
+ void pushParentElement(Element&);
+ void popParentElement(Element&);
void pushParentShadowRoot(const ShadowRoot&);
void popParentShadowRoot(const ShadowRoot&);
PassRefPtr<RenderStyle> styleForElement(Element*, RenderStyle* parentStyle = 0, StyleSharingBehavior = AllowStyleSharing,
RuleMatchingBehavior = MatchAllRules, RenderRegion* regionForStyling = 0);
- // FIXME: The following logic related to animations and keyframes should be factored out of StyleResolver
- // The body of calculateCSSAnimationUpdate can move to CSSAnimations.cpp and take just const element, const style,
- // and const ScopedStyleTree
- void calculateCSSAnimationUpdate(StyleResolverState&);
- void resolveKeyframes(const Element*, const RenderStyle*, const AtomicString& animationName, TimingFunction* defaultTimingFunction, KeyframeAnimationEffect::KeyframeVector&, RefPtr<TimingFunction>&);
- void keyframeStylesForAnimation(Element*, const RenderStyle*, KeyframeList&);
- const StyleRuleKeyframes* matchScopedKeyframesRule(const Element*, const StringImpl* animationName);
- PassRefPtr<RenderStyle> styleForKeyframe(Element*, const RenderStyle*, const StyleKeyframe*);
+ // FIXME: keyframeStylesForAnimation is only used in the legacy animations implementation
+ // and should be removed when that is replaced by Web Animations.
+ void keyframeStylesForAnimation(Element*, const RenderStyle&, KeyframeList&);
+ PassRefPtr<RenderStyle> styleForKeyframe(Element*, const RenderStyle&, RenderStyle* parentStyle, const StyleKeyframe*, const AtomicString& animationName);
+ static PassRefPtr<KeyframeAnimationEffect> createKeyframeAnimationEffect(Element&, const Vector<RefPtr<MutableStylePropertySet> >&, KeyframeAnimationEffect::KeyframeVector&);
PassRefPtr<RenderStyle> pseudoStyleForElement(Element*, const PseudoStyleRequest&, RenderStyle* parentStyle);
@@ -212,27 +138,37 @@ public:
// their dependency on Document* instead of grabbing one through StyleResolver.
Document& document() { return m_document; }
- // FIXME: It could be better to call m_ruleSets.appendAuthorStyleSheets() directly after we factor StyleRsolver further.
+ // FIXME: It could be better to call appendAuthorStyleSheets() directly after we factor StyleResolver further.
// https://bugs.webkit.org/show_bug.cgi?id=108890
void appendAuthorStyleSheets(unsigned firstNew, const Vector<RefPtr<CSSStyleSheet> >&);
void resetAuthorStyle(const ContainerNode*);
- void resetAtHostRules(const ContainerNode*);
void finishAppendAuthorStyleSheets();
- DocumentRuleSets& ruleSets() { return m_ruleSets; }
- const DocumentRuleSets& ruleSets() const { return m_ruleSets; }
+ TreeBoundaryCrossingRules& treeBoundaryCrossingRules() { return m_treeBoundaryCrossingRules; }
+ void processScopedRules(const RuleSet& authorRules, const KURL&, ContainerNode* scope = 0);
+
+ void lazyAppendAuthorStyleSheets(unsigned firstNew, const Vector<RefPtr<CSSStyleSheet> >&);
+ void removePendingAuthorStyleSheets(const Vector<RefPtr<CSSStyleSheet> >&);
+ void appendPendingAuthorStyleSheets();
+ bool hasPendingAuthorStyleSheets() const { return m_pendingStyleSheets.size() > 0 || m_needCollectFeatures; }
+
SelectorFilter& selectorFilter() { return m_selectorFilter; }
void setBuildScopedStyleTreeInDocumentOrder(bool enabled) { m_styleTree.setBuildInDocumentOrder(enabled); }
bool buildScopedStyleTreeInDocumentOrder() const { return m_styleTree.buildInDocumentOrder(); }
+ bool styleTreeHasOnlyScopedResolverForDocument() const { return m_styleTree.hasOnlyScopedResolverForDocument(); }
+ ScopedStyleResolver* styleTreeScopedStyleResolverForDocument() const { return m_styleTree.scopedStyleResolverForDocument(); }
- ScopedStyleResolver* ensureScopedStyleResolver(const ContainerNode* scope)
+ ScopedStyleResolver* ensureScopedStyleResolver(ContainerNode* scope)
{
- return m_styleTree.ensureScopedStyleResolver(scope ? *scope : document());
+ ASSERT(scope);
+ return m_styleTree.ensureScopedStyleResolver(*scope);
}
- // FIXME: Used by SharingStyleFinder, but should be removed.
- bool styleSharingCandidateMatchesRuleSet(const ElementResolveContext&, RenderStyle*, RuleSet*);
+ void styleTreeResolveScopedKeyframesRules(const Element* element, Vector<ScopedStyleResolver*, 8>& resolvers)
+ {
+ m_styleTree.resolveScopedKeyframesRules(element, resolvers);
+ }
// These methods will give back the set of rules that matched for a given element (or a pseudo-element).
enum CSSRuleFilter {
@@ -243,17 +179,17 @@ public:
AllButEmptyCSSRules = UAAndUserCSSRules | AuthorCSSRules | CrossOriginCSSRules,
AllCSSRules = AllButEmptyCSSRules | EmptyCSSRules,
};
- PassRefPtr<CSSRuleList> styleRulesForElement(Element*, unsigned rulesToInclude = AllButEmptyCSSRules);
- PassRefPtr<CSSRuleList> pseudoStyleRulesForElement(Element*, PseudoId, unsigned rulesToInclude = AllButEmptyCSSRules);
+ PassRefPtr<CSSRuleList> cssRulesForElement(Element*, unsigned rulesToInclude = AllButEmptyCSSRules, ShouldIncludeStyleSheetInCSSOMWrapper = IncludeStyleSheetInCSSOMWrapper);
+ PassRefPtr<CSSRuleList> pseudoCSSRulesForElement(Element*, PseudoId, unsigned rulesToInclude = AllButEmptyCSSRules, ShouldIncludeStyleSheetInCSSOMWrapper = IncludeStyleSheetInCSSOMWrapper);
+ PassRefPtr<StyleRuleList> styleRulesForElement(Element*, unsigned rulesToInclude);
// |properties| is an array with |count| elements.
void applyPropertiesToStyle(const CSSPropertyValue* properties, size_t count, RenderStyle*);
- CSSFontSelector* fontSelector() const { return m_fontSelector.get(); }
ViewportStyleResolver* viewportStyleResolver() { return m_viewportStyleResolver.get(); }
- // FIXME: This logic belongs in MediaQueryEvaluator.
- void addViewportDependentMediaQueryResult(const MediaQueryExp*, bool result);
+ void addMediaQueryResults(const MediaQueryResultList&);
+ MediaQueryResultList* viewportDependentMediaQueryResults() { return &m_viewportDependentMediaQueryResults; }
bool hasViewportDependentMediaQueries() const { return !m_viewportDependentMediaQueryResults.isEmpty(); }
bool affectedByViewportChange() const;
@@ -269,42 +205,62 @@ public:
// FIXME: StyleResolver should not have this member or method.
InspectorCSSOMWrappers& inspectorCSSOMWrappers() { return m_inspectorCSSOMWrappers; }
- enum ViewportOrigin { UserAgentOrigin, AuthorOrigin };
-
- // Exposed for ScopedStyleResolver.
- // FIXME: Likely belongs on viewportStyleResolver.
- void collectViewportRules(RuleSet*, ViewportOrigin);
-
- const RuleFeatureSet& ruleFeatureSet() const { return m_features; }
+ const RuleFeatureSet& ensureRuleFeatureSet()
+ {
+ if (hasPendingAuthorStyleSheets())
+ appendPendingAuthorStyleSheets();
+ return m_features;
+ }
StyleSharingList& styleSharingList() { return m_styleSharingList; }
- bool supportsStyleSharing(Element*);
+ bool hasRulesForId(const AtomicString&) const;
- void addToStyleSharingList(Element*);
+ void addToStyleSharingList(Element&);
void clearStyleSharingList();
-#ifdef STYLE_STATS
- ALWAYS_INLINE static StyleSharingStats& styleSharingStats() { return m_styleSharingStats; }
-#endif
+ StyleResolverStats* stats() { return m_styleResolverStats.get(); }
+ StyleResolverStats* statsTotals() { return m_styleResolverStatsTotals.get(); }
+ enum StatsReportType { ReportDefaultStats, ReportSlowStats };
+ void enableStats(StatsReportType = ReportDefaultStats);
+ void disableStats();
+ void printStats();
+
+ unsigned accessCount() const { return m_accessCount; }
+ void didAccess() { ++m_accessCount; }
+
+ PassRefPtr<PseudoElement> createPseudoElementIfNeeded(Element&, PseudoId);
+
+private:
+ // FontSelectorClient implementation.
+ virtual void fontsNeedUpdate(FontSelector*);
+
private:
+ void initWatchedSelectorRules(const Vector<RefPtr<StyleRule> >& watchedSelectors);
+
+ void addTreeBoundaryCrossingRules(const Vector<MinimalRuleData>&, ContainerNode* scope);
+
// FIXME: This should probably go away, folded into FontBuilder.
void updateFont(StyleResolverState&);
+ void appendCSSStyleSheet(CSSStyleSheet*);
+
+ void collectPseudoRulesForElement(Element*, ElementRuleCollector&, PseudoId, unsigned rulesToInclude);
void matchUARules(ElementRuleCollector&, RuleSet*);
void matchAuthorRules(Element*, ElementRuleCollector&, bool includeEmptyRules);
- void matchShadowDistributedRules(ElementRuleCollector&, bool includeEmptyRules);
- void matchScopedAuthorRulesForShadowHost(Element*, ElementRuleCollector&, bool includeEmptyRules, Vector<ScopedStyleResolver*, 8>& resolvers, Vector<ScopedStyleResolver*, 8>& resolversInShadowTree);
- void matchHostRules(Element*, ScopedStyleResolver*, ElementRuleCollector&, bool includeEmptyRules);
- void matchScopedAuthorRules(Element*, ElementRuleCollector&, bool includeEmptyRules);
- void matchAllRules(StyleResolverState&, ElementRuleCollector&, bool matchAuthorAndUserStyles, bool includeSMILProperties);
+ void matchAuthorRulesForShadowHost(Element*, ElementRuleCollector&, bool includeEmptyRules, Vector<ScopedStyleResolver*, 8>& resolvers, Vector<ScopedStyleResolver*, 8>& resolversInShadowTree);
+ void matchAllRules(StyleResolverState&, ElementRuleCollector&, bool includeSMILProperties);
void matchUARules(ElementRuleCollector&);
- void matchUserRules(ElementRuleCollector&, bool includeEmptyRules);
+ // FIXME: watched selectors should be implemented using injected author stylesheets: http://crbug.com/316960
+ void matchWatchSelectorRules(ElementRuleCollector&);
void collectFeatures();
+ void collectTreeBoundaryCrossingRules(Element*, ElementRuleCollector&, bool includeEmptyRules);
+ void resetRuleFeatures();
bool fastRejectSelector(const RuleData&) const;
void applyMatchedProperties(StyleResolverState&, const MatchResult&);
+ void applyAnimatedProperties(StyleResolverState&, Element* animatingElement);
enum StyleApplicationPass {
VariableDefinitions,
@@ -319,7 +275,7 @@ private:
template <StyleApplicationPass pass>
void applyProperties(StyleResolverState&, const StylePropertySet* properties, StyleRule*, bool isImportant, bool inheritedOnly, PropertyWhitelistType = PropertyWhitelistNone);
template <StyleApplicationPass pass>
- bool applyAnimatedProperties(StyleResolverState&, const DocumentTimeline*);
+ void applyAnimatedProperties(StyleResolverState&, const AnimationEffect::CompositableValueMap&);
void matchPageRules(MatchResult&, RuleSet*, bool isLeftPage, bool isFirstPage, const String& pageName);
void matchPageRulesForList(Vector<StyleRulePage*>& matchedRules, const Vector<StyleRulePage*>&, bool isLeftPage, bool isFirstPage, const String& pageName);
void collectViewportRules();
@@ -330,7 +286,7 @@ private:
bool isFirstPage(int pageIndex) const;
String pageName(int pageIndex) const;
- DocumentRuleSets m_ruleSets;
+ bool pseudoStyleForElementInternal(Element&, const PseudoStyleRequest&, RenderStyle* parentStyle, StyleResolverState&);
// FIXME: This likely belongs on RuleSet.
typedef HashMap<StringImpl*, RefPtr<StyleRuleKeyframes> > KeyframesRuleMap;
@@ -343,18 +299,17 @@ private:
MatchedPropertiesCache m_matchedPropertiesCache;
OwnPtr<MediaQueryEvaluator> m_medium;
+ MediaQueryResultList m_viewportDependentMediaQueryResults;
+
RefPtr<RenderStyle> m_rootDefaultStyle;
Document& m_document;
SelectorFilter m_selectorFilter;
- bool m_matchAuthorAndUserStyles;
-
- RefPtr<CSSFontSelector> m_fontSelector;
- Vector<OwnPtr<MediaQueryResult> > m_viewportDependentMediaQueryResults;
-
RefPtr<ViewportStyleResolver> m_viewportStyleResolver;
+ ListHashSet<CSSStyleSheet*, 16> m_pendingStyleSheets;
+
ScopedStyleTree m_styleTree;
// FIXME: The entire logic of collecting features on StyleResolver, as well astransferring them
@@ -363,15 +318,23 @@ private:
OwnPtr<RuleSet> m_siblingRuleSet;
OwnPtr<RuleSet> m_uncommonAttributeRuleSet;
+ // FIXME: watched selectors should be implemented using injected author stylesheets: http://crbug.com/316960
+ OwnPtr<RuleSet> m_watchedSelectorsRules;
+ TreeBoundaryCrossingRules m_treeBoundaryCrossingRules;
+
+ bool m_needCollectFeatures;
+
InspectorCSSOMWrappers m_inspectorCSSOMWrappers;
StyleResourceLoader m_styleResourceLoader;
StyleSharingList m_styleSharingList;
-#ifdef STYLE_STATS
- static StyleSharingStats m_styleSharingStats;
-#endif
+ OwnPtr<StyleResolverStats> m_styleResolverStats;
+ OwnPtr<StyleResolverStats> m_styleResolverStatsTotals;
+ unsigned m_styleResolverStatsSequence;
+
+ unsigned m_accessCount;
};
inline bool checkRegionSelector(const CSSSelector* regionSelector, Element* regionElement)
@@ -382,8 +345,7 @@ inline bool checkRegionSelector(const CSSSelector* regionSelector, Element* regi
SelectorChecker selectorChecker(regionElement->document(), SelectorChecker::QueryingRules);
for (const CSSSelector* s = regionSelector; s; s = CSSSelectorList::next(s)) {
SelectorChecker::SelectorCheckingContext selectorCheckingContext(s, regionElement, SelectorChecker::VisitedMatchDisabled);
- PseudoId ignoreDynamicPseudo = NOPSEUDO;
- if (selectorChecker.match(selectorCheckingContext, ignoreDynamicPseudo, DOMSiblingTraversalStrategy()) == SelectorChecker::SelectorMatches)
+ if (selectorChecker.match(selectorCheckingContext, DOMSiblingTraversalStrategy()) == SelectorChecker::SelectorMatches)
return true;
}
return false;
diff --git a/chromium/third_party/WebKit/Source/core/css/resolver/StyleResolverIncludes.h b/chromium/third_party/WebKit/Source/core/css/resolver/StyleResolverIncludes.h
new file mode 100644
index 00000000000..380c1eb1d57
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/css/resolver/StyleResolverIncludes.h
@@ -0,0 +1,13 @@
+#ifndef StyleResolverIncludes_h
+#define StyleResolverIncludes_h
+
+namespace WebCore {
+
+enum ShouldIncludeStyleSheetInCSSOMWrapper {
+ IncludeStyleSheetInCSSOMWrapper,
+ DoNotIncludeStyleSheetInCSSOMWrapper,
+};
+
+}
+
+#endif // StyleResolverIncludes_h
diff --git a/chromium/third_party/WebKit/Source/core/css/resolver/StyleResolverState.cpp b/chromium/third_party/WebKit/Source/core/css/resolver/StyleResolverState.cpp
index b98a30c462b..6df80021ba5 100644
--- a/chromium/third_party/WebKit/Source/core/css/resolver/StyleResolverState.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/resolver/StyleResolverState.cpp
@@ -22,7 +22,6 @@
#include "config.h"
#include "core/css/resolver/StyleResolverState.h"
-#include "core/dom/Element.h"
#include "core/dom/Node.h"
#include "core/dom/NodeRenderStyle.h"
#include "core/page/Page.h"
@@ -30,44 +29,26 @@
namespace WebCore {
StyleResolverState::StyleResolverState(Document& document, Element* element, RenderStyle* parentStyle, RenderRegion* regionForStyling)
- : m_elementContext(element ? ElementResolveContext(element) : ElementResolveContext())
- , m_document(element ? m_elementContext.document() : document)
- , m_regionForStyling(0)
+ : m_elementContext(element ? ElementResolveContext(*element) : ElementResolveContext())
+ , m_document(document)
+ , m_style(0)
+ , m_cssToLengthConversionData(0, rootElementStyle())
+ , m_parentStyle(parentStyle)
+ , m_regionForStyling(regionForStyling)
, m_applyPropertyToRegularStyle(true)
, m_applyPropertyToVisitedLinkStyle(false)
, m_lineHeightValue(0)
, m_styleMap(*this, m_elementStyleResources)
+ , m_currentRule(0)
{
- m_regionForStyling = regionForStyling;
-
if (m_elementContext.resetStyleInheritance())
m_parentStyle = 0;
- else if (parentStyle)
- m_parentStyle = parentStyle;
- else if (m_elementContext.parentNode())
+ else if (!parentStyle && m_elementContext.parentNode())
m_parentStyle = m_elementContext.parentNode()->renderStyle();
- else
- m_parentStyle = 0;
-
- m_style = 0;
- m_elementStyleResources.clear();
- m_fontBuilder.clear();
- // FIXME: StyleResolverState is never passed between documents
- // so we should be able to do this initialization at StyleResolverState
- // createion time instead of now, correct?
+ // FIXME: How can we not have a page here?
if (Page* page = document.page())
m_elementStyleResources.setDeviceScaleFactor(page->deviceScaleFactor());
}
-StyleResolverState::~StyleResolverState()
-{
- m_elementContext = ElementResolveContext();
- m_style = 0;
- m_parentStyle = 0;
- m_regionForStyling = 0;
- m_elementStyleResources.clear();
- m_fontBuilder.clear();
-}
-
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/css/resolver/StyleResolverState.h b/chromium/third_party/WebKit/Source/core/css/resolver/StyleResolverState.h
index 6bf00dc9da6..18095bd28dd 100644
--- a/chromium/third_party/WebKit/Source/core/css/resolver/StyleResolverState.h
+++ b/chromium/third_party/WebKit/Source/core/css/resolver/StyleResolverState.h
@@ -26,7 +26,8 @@
#include "core/animation/css/CSSAnimations.h"
#include "core/css/CSSSVGDocumentValue.h"
-#include "core/css/CSSToStyleMap.h"
+#include "core/css/CSSToLengthConversionData.h"
+#include "core/css/resolver/CSSToStyleMap.h"
#include "core/css/resolver/ElementResolveContext.h"
#include "core/css/resolver/ElementStyleResources.h"
#include "core/css/resolver/FontBuilder.h"
@@ -39,12 +40,12 @@ namespace WebCore {
class FontDescription;
class RenderRegion;
+class StyleRule;
class StyleResolverState {
WTF_MAKE_NONCOPYABLE(StyleResolverState);
public:
StyleResolverState(Document&, Element*, RenderStyle* parentStyle = 0, RenderRegion* regionForStyling = 0);
- ~StyleResolverState();
// In FontFaceSet and CanvasRenderingContext2D, we don't have an element to grab the document from.
// This is why we have to store the document separately.
@@ -58,11 +59,13 @@ public:
const ElementResolveContext& elementContext() const { return m_elementContext; }
- void setStyle(PassRefPtr<RenderStyle> style) { m_style = style; }
+ void setStyle(PassRefPtr<RenderStyle> style) { m_style = style; m_cssToLengthConversionData.setStyle(m_style.get()); }
const RenderStyle* style() const { return m_style.get(); }
RenderStyle* style() { return m_style.get(); }
PassRefPtr<RenderStyle> takeStyle() { return m_style.release(); }
+ const CSSToLengthConversionData& cssToLengthConversionData() const { return m_cssToLengthConversionData; }
+
void setAnimationUpdate(PassOwnPtr<CSSAnimationUpdate> update) { m_animationUpdate = update; }
const CSSAnimationUpdate* animationUpdate() { return m_animationUpdate.get(); }
PassOwnPtr<CSSAnimationUpdate> takeAnimationUpdate() { return m_animationUpdate.release(); }
@@ -73,6 +76,9 @@ public:
const RenderRegion* regionForStyling() const { return m_regionForStyling; }
+ void setCurrentRule(StyleRule* currentRule) { m_currentRule = currentRule; }
+ const StyleRule* currentRule() const { return m_currentRule; }
+
// FIXME: These are effectively side-channel "out parameters" for the various
// map functions. When we map from CSS to style objects we use this state object
// to track various meta-data about that mapping (e.g. if it's cache-able).
@@ -101,7 +107,7 @@ public:
// sites are extremely verbose.
PassRefPtr<StyleImage> styleImage(CSSPropertyID propertyId, CSSValue* value)
{
- return m_elementStyleResources.styleImage(document().textLinkColors(), style()->visitedDependentColor(CSSPropertyColor), propertyId, value);
+ return m_elementStyleResources.styleImage(document().textLinkColors(), style()->color(), propertyId, value);
}
FontBuilder& fontBuilder() { return m_fontBuilder; }
@@ -129,14 +135,14 @@ public:
private:
friend class StyleResolveScope;
- void initElement(Element*);
-
ElementResolveContext m_elementContext;
Document& m_document;
// m_style is the primary output for each element's style resolve.
RefPtr<RenderStyle> m_style;
+ CSSToLengthConversionData m_cssToLengthConversionData;
+
// m_parentStyle is not always just element->parentNode()->style()
// so we keep it separate from m_elementContext.
RefPtr<RenderStyle> m_parentStyle;
@@ -162,6 +168,8 @@ private:
// a back-pointer to this object.
CSSToStyleMap m_styleMap;
Vector<AtomicString> m_contentAttrValues;
+
+ StyleRule* m_currentRule;
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/css/resolver/StyleResolverStats.cpp b/chromium/third_party/WebKit/Source/core/css/resolver/StyleResolverStats.cpp
new file mode 100644
index 00000000000..bb795bfa34c
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/css/resolver/StyleResolverStats.cpp
@@ -0,0 +1,87 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/css/resolver/StyleResolverStats.h"
+
+#include "wtf/text/CString.h"
+#include "wtf/text/StringBuilder.h"
+
+#define PERCENT(x, y) ((!y) ? 0 : (((x) * 100.0) / (y)))
+
+namespace WebCore {
+
+void StyleResolverStats::reset()
+{
+ sharedStyleLookups = 0;
+ sharedStyleCandidates = 0;
+ sharedStyleFound = 0;
+ sharedStyleMissed = 0;
+ sharedStyleRejectedByUncommonAttributeRules = 0;
+ sharedStyleRejectedBySiblingRules = 0;
+ sharedStyleRejectedByParent = 0;
+ matchedPropertyApply = 0;
+ matchedPropertyCacheHit = 0;
+ matchedPropertyCacheInheritedHit = 0;
+ matchedPropertyCacheAdded = 0;
+}
+
+String StyleResolverStats::report() const
+{
+ StringBuilder output;
+
+ unsigned sharedStylesRejected = sharedStyleRejectedByUncommonAttributeRules + sharedStyleRejectedBySiblingRules + sharedStyleRejectedByParent;
+ unsigned sharedStylesUsed = sharedStyleFound - sharedStylesRejected;
+
+ output.append("Style sharing:\n");
+ output.append(String::format(" %u elements were added to the sharing candidate list.\n", sharedStyleCandidates));
+ output.append(String::format(" %u calls were made to findSharedStyle, %u found a candidate to share with (%.2f%%).\n", sharedStyleLookups, sharedStyleFound, PERCENT(sharedStyleFound, sharedStyleLookups)));
+ if (printMissedCandidateCount)
+ output.append(String::format(" %u candidates could have matched but were not in the list when searching (%.2f%%).\n", sharedStyleMissed, PERCENT(sharedStyleMissed, sharedStyleLookups)));
+ output.append(String::format(" %u of found styles were rejected (%.2f%%), %.2f%% by uncommon attribute rules, %.2f%% by sibling rules and %.2f%% by parents disabling sharing.\n",
+ sharedStylesRejected,
+ PERCENT(sharedStylesRejected, sharedStyleFound),
+ PERCENT(sharedStyleRejectedByUncommonAttributeRules, sharedStylesRejected),
+ PERCENT(sharedStyleRejectedBySiblingRules, sharedStylesRejected),
+ PERCENT(sharedStyleRejectedByParent, sharedStylesRejected)));
+ output.append(String::format(" %u of found styles were used for sharing (%.2f%%).\n", sharedStylesUsed, PERCENT(sharedStylesUsed, sharedStyleFound)));
+ output.append(String::format(" %.2f%% of calls to findSharedStyle returned a shared style.\n", PERCENT(sharedStylesUsed, sharedStyleLookups)));
+
+ output.append("\n");
+
+ output.append("Matched property cache:\n");
+ output.append(String::format(" %u calls to applyMatchedProperties, %u hit the cache (%.2f%%).\n", matchedPropertyApply, matchedPropertyCacheHit, PERCENT(matchedPropertyCacheHit, matchedPropertyApply)));
+ output.append(String::format(" %u cache hits also shared the inherited style (%.2f%%).\n", matchedPropertyCacheInheritedHit, PERCENT(matchedPropertyCacheInheritedHit, matchedPropertyCacheHit)));
+ output.append(String::format(" %u styles created in applyMatchedProperties were added to the cache (%.2f%%).\n", matchedPropertyCacheAdded, PERCENT(matchedPropertyCacheAdded, matchedPropertyApply)));
+
+ return output.toString();
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/css/resolver/StyleResolverStats.h b/chromium/third_party/WebKit/Source/core/css/resolver/StyleResolverStats.h
new file mode 100644
index 00000000000..084c02d588b
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/css/resolver/StyleResolverStats.h
@@ -0,0 +1,77 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef StyleResolverStats_h
+#define StyleResolverStats_h
+
+#include "wtf/PassOwnPtr.h"
+#include "wtf/text/WTFString.h"
+
+namespace WebCore {
+
+class StyleResolverStats {
+public:
+ static PassOwnPtr<StyleResolverStats> create()
+ {
+ return adoptPtr(new StyleResolverStats);
+ }
+
+ void reset();
+ String report() const;
+
+ unsigned sharedStyleLookups;
+ unsigned sharedStyleCandidates;
+ unsigned sharedStyleFound;
+ unsigned sharedStyleMissed;
+ unsigned sharedStyleRejectedByUncommonAttributeRules;
+ unsigned sharedStyleRejectedBySiblingRules;
+ unsigned sharedStyleRejectedByParent;
+ unsigned matchedPropertyApply;
+ unsigned matchedPropertyCacheHit;
+ unsigned matchedPropertyCacheInheritedHit;
+ unsigned matchedPropertyCacheAdded;
+
+ // We keep a separate flag for this since crawling the entire document to print
+ // the number of missed candidates is very slow.
+ bool printMissedCandidateCount;
+
+private:
+ StyleResolverStats()
+ : printMissedCandidateCount(false)
+ {
+ reset();
+ }
+};
+
+#define INCREMENT_STYLE_STATS_COUNTER(resolver, counter) ((resolver).stats() && ++(resolver).stats()-> counter && (resolver).statsTotals()-> counter ++);
+
+} // namespace WebCore
+
+#endif // StyleResolverStats_h
diff --git a/chromium/third_party/WebKit/Source/core/css/resolver/StyleResourceLoader.cpp b/chromium/third_party/WebKit/Source/core/css/resolver/StyleResourceLoader.cpp
index 3158763d320..04405c340a7 100644
--- a/chromium/third_party/WebKit/Source/core/css/resolver/StyleResourceLoader.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/resolver/StyleResourceLoader.cpp
@@ -30,7 +30,6 @@
#include "core/css/CSSShaderValue.h"
#include "core/css/resolver/ElementStyleResources.h"
#include "core/fetch/ResourceFetcher.h"
-#include "core/platform/graphics/filters/custom/CustomFilterOperation.h"
#include "core/rendering/style/ContentData.h"
#include "core/rendering/style/CursorList.h"
#include "core/rendering/style/FillLayer.h"
@@ -43,12 +42,14 @@
#include "core/rendering/style/StyleGeneratedImage.h"
#include "core/rendering/style/StylePendingImage.h"
#include "core/rendering/style/StylePendingShader.h"
+#include "core/rendering/svg/ReferenceFilterBuilder.h"
+#include "platform/graphics/filters/custom/CustomFilterOperation.h"
namespace WebCore {
StyleResourceLoader::StyleResourceLoader(ResourceFetcher* fetcher)
- : m_fetcher(fetcher)
- , m_customFilterProgramCache(StyleCustomFilterProgramCache::create())
+ : m_customFilterProgramCache(StyleCustomFilterProgramCache::create())
+ , m_fetcher(fetcher)
{
}
@@ -60,8 +61,8 @@ void StyleResourceLoader::loadPendingSVGDocuments(RenderStyle* renderStyle, cons
Vector<RefPtr<FilterOperation> >& filterOperations = renderStyle->mutableFilter().operations();
for (unsigned i = 0; i < filterOperations.size(); ++i) {
RefPtr<FilterOperation> filterOperation = filterOperations.at(i);
- if (filterOperation->getOperationType() == FilterOperation::REFERENCE) {
- ReferenceFilterOperation* referenceFilter = static_cast<ReferenceFilterOperation*>(filterOperation.get());
+ if (filterOperation->type() == FilterOperation::REFERENCE) {
+ ReferenceFilterOperation* referenceFilter = toReferenceFilterOperation(filterOperation.get());
CSSSVGDocumentValue* value = elementStyleResources.pendingSVGDocuments().get(referenceFilter);
if (!value)
@@ -71,7 +72,7 @@ void StyleResourceLoader::loadPendingSVGDocuments(RenderStyle* renderStyle, cons
continue;
// Stash the DocumentResource on the reference filter.
- referenceFilter->setDocumentResourceReference(adoptPtr(new DocumentResourceReference(resource)));
+ ReferenceFilterBuilder::setDocumentResourceReference(referenceFilter, adoptPtr(new DocumentResourceReference(resource)));
}
}
}
@@ -111,13 +112,13 @@ void StyleResourceLoader::loadPendingShapeImage(RenderStyle* renderStyle, ShapeV
if (!image || !image->isPendingImage())
return;
- StylePendingImage* pendingImage = static_cast<StylePendingImage*>(image);
+ StylePendingImage* pendingImage = toStylePendingImage(image);
CSSImageValue* cssImageValue = pendingImage->cssImageValue();
ResourceLoaderOptions options = ResourceFetcher::defaultResourceOptions();
- options.requestOriginPolicy = RestrictToSameOrigin;
+ options.allowCredentials = DoNotAllowStoredCredentials;
- shapeValue->setImage(cssImageValue->cachedImage(m_fetcher, options));
+ shapeValue->setImage(cssImageValue->cachedImage(m_fetcher, options, PotentiallyCORSEnabled));
}
void StyleResourceLoader::loadPendingImages(RenderStyle* style, const ElementStyleResources& elementStyleResources)
@@ -133,7 +134,7 @@ void StyleResourceLoader::loadPendingImages(RenderStyle* style, const ElementSty
case CSSPropertyBackgroundImage: {
for (FillLayer* backgroundLayer = style->accessBackgroundLayers(); backgroundLayer; backgroundLayer = backgroundLayer->next()) {
if (backgroundLayer->image() && backgroundLayer->image()->isPendingImage())
- backgroundLayer->setImage(loadPendingImage(static_cast<StylePendingImage*>(backgroundLayer->image()), elementStyleResources.deviceScaleFactor()));
+ backgroundLayer->setImage(loadPendingImage(toStylePendingImage(backgroundLayer->image()), elementStyleResources.deviceScaleFactor()));
}
break;
}
@@ -142,7 +143,7 @@ void StyleResourceLoader::loadPendingImages(RenderStyle* style, const ElementSty
if (contentData->isImage()) {
StyleImage* image = static_cast<ImageContentData*>(contentData)->image();
if (image->isPendingImage()) {
- RefPtr<StyleImage> loadedImage = loadPendingImage(static_cast<StylePendingImage*>(image), elementStyleResources.deviceScaleFactor());
+ RefPtr<StyleImage> loadedImage = loadPendingImage(toStylePendingImage(image), elementStyleResources.deviceScaleFactor());
if (loadedImage)
static_cast<ImageContentData*>(contentData)->setImage(loadedImage.release());
}
@@ -156,7 +157,7 @@ void StyleResourceLoader::loadPendingImages(RenderStyle* style, const ElementSty
CursorData& currentCursor = cursorList->at(i);
if (StyleImage* image = currentCursor.image()) {
if (image->isPendingImage())
- currentCursor.setImage(loadPendingImage(static_cast<StylePendingImage*>(image), elementStyleResources.deviceScaleFactor()));
+ currentCursor.setImage(loadPendingImage(toStylePendingImage(image), elementStyleResources.deviceScaleFactor()));
}
}
}
@@ -164,19 +165,19 @@ void StyleResourceLoader::loadPendingImages(RenderStyle* style, const ElementSty
}
case CSSPropertyListStyleImage: {
if (style->listStyleImage() && style->listStyleImage()->isPendingImage())
- style->setListStyleImage(loadPendingImage(static_cast<StylePendingImage*>(style->listStyleImage()), elementStyleResources.deviceScaleFactor()));
+ style->setListStyleImage(loadPendingImage(toStylePendingImage(style->listStyleImage()), elementStyleResources.deviceScaleFactor()));
break;
}
case CSSPropertyBorderImageSource: {
if (style->borderImageSource() && style->borderImageSource()->isPendingImage())
- style->setBorderImageSource(loadPendingImage(static_cast<StylePendingImage*>(style->borderImageSource()), elementStyleResources.deviceScaleFactor()));
+ style->setBorderImageSource(loadPendingImage(toStylePendingImage(style->borderImageSource()), elementStyleResources.deviceScaleFactor()));
break;
}
case CSSPropertyWebkitBoxReflect: {
if (StyleReflection* reflection = style->boxReflect()) {
const NinePieceImage& maskImage = reflection->mask();
if (maskImage.image() && maskImage.image()->isPendingImage()) {
- RefPtr<StyleImage> loadedImage = loadPendingImage(static_cast<StylePendingImage*>(maskImage.image()), elementStyleResources.deviceScaleFactor());
+ RefPtr<StyleImage> loadedImage = loadPendingImage(toStylePendingImage(maskImage.image()), elementStyleResources.deviceScaleFactor());
reflection->setMask(NinePieceImage(loadedImage.release(), maskImage.imageSlices(), maskImage.fill(), maskImage.borderSlices(), maskImage.outset(), maskImage.horizontalRule(), maskImage.verticalRule()));
}
}
@@ -184,20 +185,20 @@ void StyleResourceLoader::loadPendingImages(RenderStyle* style, const ElementSty
}
case CSSPropertyWebkitMaskBoxImageSource: {
if (style->maskBoxImageSource() && style->maskBoxImageSource()->isPendingImage())
- style->setMaskBoxImageSource(loadPendingImage(static_cast<StylePendingImage*>(style->maskBoxImageSource()), elementStyleResources.deviceScaleFactor()));
+ style->setMaskBoxImageSource(loadPendingImage(toStylePendingImage(style->maskBoxImageSource()), elementStyleResources.deviceScaleFactor()));
break;
}
case CSSPropertyWebkitMaskImage: {
for (FillLayer* maskLayer = style->accessMaskLayers(); maskLayer; maskLayer = maskLayer->next()) {
if (maskLayer->image() && maskLayer->image()->isPendingImage())
- maskLayer->setImage(loadPendingImage(static_cast<StylePendingImage*>(maskLayer->image()), elementStyleResources.deviceScaleFactor()));
+ maskLayer->setImage(loadPendingImage(toStylePendingImage(maskLayer->image()), elementStyleResources.deviceScaleFactor()));
}
break;
}
- case CSSPropertyWebkitShapeInside:
+ case CSSPropertyShapeInside:
loadPendingShapeImage(style, style->shapeInside());
break;
- case CSSPropertyWebkitShapeOutside:
+ case CSSPropertyShapeOutside:
loadPendingShapeImage(style, style->shapeOutside());
break;
default:
@@ -208,14 +209,14 @@ void StyleResourceLoader::loadPendingImages(RenderStyle* style, const ElementSty
void StyleResourceLoader::loadPendingShaders(RenderStyle* style, const ElementStyleResources& elementStyleResources)
{
- if (!style->hasFilter() || !elementStyleResources.hasPendingShaders())
+ if (!style->hasFilter() || !elementStyleResources.hasNewCustomFilterProgram())
return;
Vector<RefPtr<FilterOperation> >& filterOperations = style->mutableFilter().operations();
for (unsigned i = 0; i < filterOperations.size(); ++i) {
RefPtr<FilterOperation> filterOperation = filterOperations.at(i);
- if (filterOperation->getOperationType() == FilterOperation::CUSTOM) {
- CustomFilterOperation* customFilter = static_cast<CustomFilterOperation*>(filterOperation.get());
+ if (filterOperation->type() == FilterOperation::CUSTOM) {
+ CustomFilterOperation* customFilter = toCustomFilterOperation(filterOperation.get());
ASSERT(customFilter->program());
StyleCustomFilterProgram* program = static_cast<StyleCustomFilterProgram*>(customFilter->program());
// Note that the StylePendingShaders could be already resolved to StyleFetchedShaders. That's because the rule was matched before.
@@ -251,9 +252,6 @@ void StyleResourceLoader::loadPendingResources(RenderStyle* renderStyle, Element
// Start loading the SVG Documents referenced by this style.
loadPendingSVGDocuments(renderStyle, elementStyleResources);
-
- // FIXME: Investigate if this clearing is necessary.
- elementStyleResources.clear();
}
}
diff --git a/chromium/third_party/WebKit/Source/core/css/resolver/TransformBuilder.cpp b/chromium/third_party/WebKit/Source/core/css/resolver/TransformBuilder.cpp
index f13e02dceaf..3779a01f6a5 100644
--- a/chromium/third_party/WebKit/Source/core/css/resolver/TransformBuilder.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/resolver/TransformBuilder.cpp
@@ -31,15 +31,15 @@
#include "core/css/CSSPrimitiveValueMappings.h"
#include "core/css/CSSTransformValue.h"
-#include "core/platform/graphics/transforms/Matrix3DTransformOperation.h"
-#include "core/platform/graphics/transforms/MatrixTransformOperation.h"
-#include "core/platform/graphics/transforms/PerspectiveTransformOperation.h"
-#include "core/platform/graphics/transforms/RotateTransformOperation.h"
-#include "core/platform/graphics/transforms/ScaleTransformOperation.h"
-#include "core/platform/graphics/transforms/SkewTransformOperation.h"
-#include "core/platform/graphics/transforms/TransformationMatrix.h"
-#include "core/platform/graphics/transforms/TranslateTransformOperation.h"
#include "core/rendering/style/RenderStyle.h"
+#include "platform/transforms/Matrix3DTransformOperation.h"
+#include "platform/transforms/MatrixTransformOperation.h"
+#include "platform/transforms/PerspectiveTransformOperation.h"
+#include "platform/transforms/RotateTransformOperation.h"
+#include "platform/transforms/ScaleTransformOperation.h"
+#include "platform/transforms/SkewTransformOperation.h"
+#include "platform/transforms/TransformationMatrix.h"
+#include "platform/transforms/TranslateTransformOperation.h"
namespace WebCore {
@@ -51,9 +51,9 @@ TransformBuilder::~TransformBuilder()
{
}
-static Length convertToFloatLength(CSSPrimitiveValue* primitiveValue, const RenderStyle* style, const RenderStyle* rootStyle, double multiplier)
+static Length convertToFloatLength(CSSPrimitiveValue* primitiveValue, const CSSToLengthConversionData& conversionData)
{
- return primitiveValue ? primitiveValue->convertToLength<FixedFloatConversion | PercentConversion | FractionConversion>(style, rootStyle, multiplier) : Length(Undefined);
+ return primitiveValue ? primitiveValue->convertToLength<FixedConversion | PercentConversion>(conversionData) : Length(Undefined);
}
static TransformOperation::OperationType getTransformOperationType(CSSTransformValue::TransformOperationType type)
@@ -85,22 +85,22 @@ static TransformOperation::OperationType getTransformOperationType(CSSTransformV
return TransformOperation::None;
}
-bool TransformBuilder::createTransformOperations(CSSValue* inValue, const RenderStyle* style, const RenderStyle* rootStyle, TransformOperations& outOperations)
+bool TransformBuilder::createTransformOperations(CSSValue* inValue, const CSSToLengthConversionData& conversionData, TransformOperations& outOperations)
{
if (!inValue || !inValue->isValueList()) {
outOperations.clear();
return false;
}
- float zoomFactor = style ? style->effectiveZoom() : 1;
+ float zoomFactor = conversionData.zoom();
TransformOperations operations;
for (CSSValueListIterator i = inValue; i.hasMore(); i.advance()) {
CSSValue* currValue = i.value();
- if (!currValue->isCSSTransformValue())
+ if (!currValue->isTransformValue())
continue;
- CSSTransformValue* transformValue = static_cast<CSSTransformValue*>(i.value());
+ CSSTransformValue* transformValue = toCSSTransformValue(i.value());
if (!transformValue->length())
continue;
@@ -169,13 +169,13 @@ bool TransformBuilder::createTransformOperations(CSSValue* inValue, const Render
Length tx = Length(0, Fixed);
Length ty = Length(0, Fixed);
if (transformValue->operationType() == CSSTransformValue::TranslateYTransformOperation)
- ty = convertToFloatLength(firstValue, style, rootStyle, zoomFactor);
+ ty = convertToFloatLength(firstValue, conversionData);
else {
- tx = convertToFloatLength(firstValue, style, rootStyle, zoomFactor);
+ tx = convertToFloatLength(firstValue, conversionData);
if (transformValue->operationType() != CSSTransformValue::TranslateXTransformOperation) {
if (transformValue->length() > 1) {
CSSPrimitiveValue* secondValue = toCSSPrimitiveValue(transformValue->itemWithoutBoundsCheck(1));
- ty = convertToFloatLength(secondValue, style, rootStyle, zoomFactor);
+ ty = convertToFloatLength(secondValue, conversionData);
}
}
}
@@ -192,19 +192,19 @@ bool TransformBuilder::createTransformOperations(CSSValue* inValue, const Render
Length ty = Length(0, Fixed);
Length tz = Length(0, Fixed);
if (transformValue->operationType() == CSSTransformValue::TranslateZTransformOperation)
- tz = convertToFloatLength(firstValue, style, rootStyle, zoomFactor);
+ tz = convertToFloatLength(firstValue, conversionData);
else if (transformValue->operationType() == CSSTransformValue::TranslateYTransformOperation)
- ty = convertToFloatLength(firstValue, style, rootStyle, zoomFactor);
+ ty = convertToFloatLength(firstValue, conversionData);
else {
- tx = convertToFloatLength(firstValue, style, rootStyle, zoomFactor);
+ tx = convertToFloatLength(firstValue, conversionData);
if (transformValue->operationType() != CSSTransformValue::TranslateXTransformOperation) {
if (transformValue->length() > 2) {
CSSPrimitiveValue* thirdValue = toCSSPrimitiveValue(transformValue->itemWithoutBoundsCheck(2));
- tz = convertToFloatLength(thirdValue, style, rootStyle, zoomFactor);
+ tz = convertToFloatLength(thirdValue, conversionData);
}
if (transformValue->length() > 1) {
CSSPrimitiveValue* secondValue = toCSSPrimitiveValue(transformValue->itemWithoutBoundsCheck(1));
- ty = convertToFloatLength(secondValue, style, rootStyle, zoomFactor);
+ ty = convertToFloatLength(secondValue, conversionData);
}
}
}
@@ -307,7 +307,7 @@ bool TransformBuilder::createTransformOperations(CSSValue* inValue, const Render
case CSSTransformValue::PerspectiveTransformOperation: {
Length p = Length(0, Fixed);
if (firstValue->isLength())
- p = convertToFloatLength(firstValue, style, rootStyle, zoomFactor);
+ p = convertToFloatLength(firstValue, conversionData);
else {
// This is a quirk that should go away when 3d transforms are finalized.
double val = firstValue->getDoubleValue();
diff --git a/chromium/third_party/WebKit/Source/core/css/resolver/TransformBuilder.h b/chromium/third_party/WebKit/Source/core/css/resolver/TransformBuilder.h
index d582465ce3e..a3ac2e0b0f5 100644
--- a/chromium/third_party/WebKit/Source/core/css/resolver/TransformBuilder.h
+++ b/chromium/third_party/WebKit/Source/core/css/resolver/TransformBuilder.h
@@ -31,13 +31,13 @@
#ifndef TransformBuilder_h
#define TransformBuilder_h
-#include "core/platform/graphics/transforms/TransformOperations.h"
+#include "platform/transforms/TransformOperations.h"
#include "wtf/Noncopyable.h"
namespace WebCore {
+class CSSToLengthConversionData;
class CSSValue;
-class RenderStyle;
class TransformBuilder {
WTF_MAKE_NONCOPYABLE(TransformBuilder); WTF_MAKE_FAST_ALLOCATED;
@@ -45,7 +45,7 @@ public:
TransformBuilder();
~TransformBuilder();
- static bool createTransformOperations(CSSValue* inValue, const RenderStyle* inStyle, const RenderStyle* rootStyle, TransformOperations& outOperations);
+ static bool createTransformOperations(CSSValue* inValue, const CSSToLengthConversionData&, TransformOperations& outOperations);
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/css/resolver/ViewportStyleResolver.cpp b/chromium/third_party/WebKit/Source/core/css/resolver/ViewportStyleResolver.cpp
index f38f7d78060..61894a2458a 100644
--- a/chromium/third_party/WebKit/Source/core/css/resolver/ViewportStyleResolver.cpp
+++ b/chromium/third_party/WebKit/Source/core/css/resolver/ViewportStyleResolver.cpp
@@ -31,11 +31,12 @@
#include "core/css/resolver/ViewportStyleResolver.h"
#include "CSSValueKeywords.h"
+#include "core/css/CSSToLengthConversionData.h"
#include "core/css/StylePropertySet.h"
#include "core/css/StyleRule.h"
#include "core/dom/Document.h"
#include "core/dom/NodeRenderStyle.h"
-#include "core/dom/ViewportArguments.h"
+#include "core/dom/ViewportDescription.h"
namespace WebCore {
@@ -50,7 +51,16 @@ ViewportStyleResolver::~ViewportStyleResolver()
{
}
-void ViewportStyleResolver::addViewportRule(StyleRuleViewport* viewportRule)
+void ViewportStyleResolver::collectViewportRules(RuleSet* rules, Origin origin)
+{
+ rules->compactRulesIfNeeded();
+
+ const Vector<StyleRuleViewport*>& viewportRules = rules->viewportRules();
+ for (size_t i = 0; i < viewportRules.size(); ++i)
+ addViewportRule(viewportRules[i], origin);
+}
+
+void ViewportStyleResolver::addViewportRule(StyleRuleViewport* viewportRule, Origin origin)
{
StylePropertySet* propertySet = viewportRule->mutableProperties();
@@ -58,6 +68,9 @@ void ViewportStyleResolver::addViewportRule(StyleRuleViewport* viewportRule)
if (!propertyCount)
return;
+ if (origin == AuthorOrigin)
+ m_hasAuthorStyle = true;
+
if (!m_propertySet) {
m_propertySet = propertySet->mutableCopy();
return;
@@ -82,23 +95,23 @@ void ViewportStyleResolver::resolve()
if (!m_propertySet || (!m_hasAuthorStyle && m_document->hasLegacyViewportTag())) {
ASSERT(!m_hasAuthorStyle);
m_propertySet = 0;
- m_document->setViewportArguments(ViewportArguments());
+ m_document->setViewportDescription(ViewportDescription());
return;
}
- ViewportArguments arguments(m_hasAuthorStyle ? ViewportArguments::AuthorStyleSheet : ViewportArguments::UserAgentStyleSheet);
+ ViewportDescription description(m_hasAuthorStyle ? ViewportDescription::AuthorStyleSheet : ViewportDescription::UserAgentStyleSheet);
- arguments.userZoom = viewportArgumentValue(CSSPropertyUserZoom);
- arguments.zoom = viewportArgumentValue(CSSPropertyZoom);
- arguments.minZoom = viewportArgumentValue(CSSPropertyMinZoom);
- arguments.maxZoom = viewportArgumentValue(CSSPropertyMaxZoom);
- arguments.minWidth = viewportLengthValue(CSSPropertyMinWidth);
- arguments.maxWidth = viewportLengthValue(CSSPropertyMaxWidth);
- arguments.minHeight = viewportLengthValue(CSSPropertyMinHeight);
- arguments.maxHeight = viewportLengthValue(CSSPropertyMaxHeight);
- arguments.orientation = viewportArgumentValue(CSSPropertyOrientation);
+ description.userZoom = viewportArgumentValue(CSSPropertyUserZoom);
+ description.zoom = viewportArgumentValue(CSSPropertyZoom);
+ description.minZoom = viewportArgumentValue(CSSPropertyMinZoom);
+ description.maxZoom = viewportArgumentValue(CSSPropertyMaxZoom);
+ description.minWidth = viewportLengthValue(CSSPropertyMinWidth);
+ description.maxWidth = viewportLengthValue(CSSPropertyMaxWidth);
+ description.minHeight = viewportLengthValue(CSSPropertyMinHeight);
+ description.maxHeight = viewportLengthValue(CSSPropertyMaxHeight);
+ description.orientation = viewportArgumentValue(CSSPropertyOrientation);
- m_document->setViewportArguments(arguments);
+ m_document->setViewportDescription(description);
m_propertySet = 0;
m_hasAuthorStyle = false;
@@ -106,7 +119,7 @@ void ViewportStyleResolver::resolve()
float ViewportStyleResolver::viewportArgumentValue(CSSPropertyID id) const
{
- float defaultValue = ViewportArguments::ValueAuto;
+ float defaultValue = ViewportDescription::ValueAuto;
// UserZoom default value is CSSValueZoom, which maps to true, meaning that
// yes, it is user scalable. When the value is set to CSSValueFixed, we
@@ -143,13 +156,13 @@ float ViewportStyleResolver::viewportArgumentValue(CSSPropertyID id) const
case CSSValueAuto:
return defaultValue;
case CSSValueLandscape:
- return ViewportArguments::ValueLandscape;
+ return ViewportDescription::ValueLandscape;
case CSSValuePortrait:
- return ViewportArguments::ValuePortrait;
+ return ViewportDescription::ValuePortrait;
case CSSValueZoom:
return defaultValue;
case CSSValueInternalExtendToZoom:
- return ViewportArguments::ValueExtendToZoom;
+ return ViewportDescription::ValueExtendToZoom;
case CSSValueFixed:
return 0;
default:
@@ -171,7 +184,7 @@ Length ViewportStyleResolver::viewportLengthValue(CSSPropertyID id) const
CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value.get());
if (primitiveValue->isLength())
- return primitiveValue->computeLength<Length>(m_document->renderStyle(), m_document->renderStyle());
+ return primitiveValue->computeLength<Length>(CSSToLengthConversionData(m_document->renderStyle(), m_document->renderStyle(), 1.0f));
if (primitiveValue->isViewportPercentageLength())
return primitiveValue->viewportPercentageLength();
diff --git a/chromium/third_party/WebKit/Source/core/css/resolver/ViewportStyleResolver.h b/chromium/third_party/WebKit/Source/core/css/resolver/ViewportStyleResolver.h
index b71128e9f0b..30b663f2b18 100644
--- a/chromium/third_party/WebKit/Source/core/css/resolver/ViewportStyleResolver.h
+++ b/chromium/third_party/WebKit/Source/core/css/resolver/ViewportStyleResolver.h
@@ -31,7 +31,8 @@
#define ViewportStyleResolver_h
#include "CSSPropertyNames.h"
-#include "core/platform/Length.h"
+#include "core/css/RuleSet.h"
+#include "platform/Length.h"
#include "wtf/RefCounted.h"
#include "wtf/RefPtr.h"
@@ -50,8 +51,9 @@ public:
~ViewportStyleResolver();
- void setHasAuthorStyle() { m_hasAuthorStyle = true; }
- void addViewportRule(StyleRuleViewport*);
+ enum Origin { UserAgentOrigin, AuthorOrigin };
+
+ void collectViewportRules(RuleSet*, Origin);
void clearDocument();
void resolve();
@@ -59,6 +61,8 @@ public:
private:
explicit ViewportStyleResolver(Document*);
+ void addViewportRule(StyleRuleViewport*, Origin);
+
float viewportArgumentValue(CSSPropertyID) const;
Length viewportLengthValue(CSSPropertyID) const;
diff --git a/chromium/third_party/WebKit/Source/core/css/themeChromiumLinux.css b/chromium/third_party/WebKit/Source/core/css/themeChromiumLinux.css
index f41a4761b23..7d15d64ede3 100644
--- a/chromium/third_party/WebKit/Source/core/css/themeChromiumLinux.css
+++ b/chromium/third_party/WebKit/Source/core/css/themeChromiumLinux.css
@@ -37,10 +37,6 @@ select[size="1"] {
background-color: ButtonFace;
}
-select:disabled option:checked, option:disabled:checked {
- color: GrayText;
-}
-
input[type=range] {
color: #9d968E;
}
diff --git a/chromium/third_party/WebKit/Source/core/css/themeWin.css b/chromium/third_party/WebKit/Source/core/css/themeWin.css
index b7a6f0b37ba..3c727d33b66 100644
--- a/chromium/third_party/WebKit/Source/core/css/themeWin.css
+++ b/chromium/third_party/WebKit/Source/core/css/themeWin.css
@@ -111,6 +111,15 @@ select,
select[size="0"],
select[size="1"] {
border-radius: 0;
+ /* Same as native_theme_base. */
+ border-color: #a9a9a9;
+}
+
+select[size],
+select[multiple],
+select[size][multiple] {
+ /* Same as native_theme_base. */
+ border: 1px solid #a9a9a9;
}
/* Option font must be inherited because we depend on computing the size of the
@@ -120,10 +129,8 @@ option {
font: inherit !important;
}
-select:disabled option:checked, option:disabled:checked {
- color: #d2d2d2
-}
-
textarea {
- font-family: monospace;
+ font-family: monospace;
+ /* Same as native_theme_base. */
+ border-color: #a9a9a9;
}
diff --git a/chromium/third_party/WebKit/Source/core/css/view-source.css b/chromium/third_party/WebKit/Source/core/css/view-source.css
index 5e0e6eaea3d..daebdbf4f67 100644
--- a/chromium/third_party/WebKit/Source/core/css/view-source.css
+++ b/chromium/third_party/WebKit/Source/core/css/view-source.css
@@ -98,30 +98,36 @@ tbody:last-child .webkit-line-content:empty:before {
}
.webkit-html-external-link, .webkit-html-resource-link {
- /* Keep this in sync with inspector.css (.webkit-html-external-link, .webkit-html-resource-link) */
+ /* Keep this in sync with inspectorSyntaxHighlight.css (.webkit-html-external-link, .webkit-html-resource-link) */
color: #00e;
}
.webkit-html-external-link {
- /* Keep this in sync with inspector.css (.webkit-html-external-link) */
+ /* Keep this in sync with inspectorSyntaxHighlight.css (.webkit-html-external-link) */
text-decoration: none;
}
.webkit-html-external-link:hover {
- /* Keep this in sync with inspector.css (.webkit-html-external-link:hover) */
+ /* Keep this in sync with inspectorSyntaxHighlight.css (.webkit-html-external-link:hover) */
text-decoration: underline;
}
.webkit-html-comment {
- /* Keep this in sync with inspector.css (.webkit-html-comment) */
+ /* Keep this in sync with inspectorSyntaxHighlight.css (.webkit-html-comment) */
color: rgb(35, 110, 37);
}
.webkit-html-doctype {
- /* Keep this in sync with inspector.css (.webkit-html-doctype) */
+ /* Keep this in sync with inspectorSyntaxHighlight.css (.webkit-html-doctype) */
color: rgb(192, 192, 192);
}
+.webkit-html-end-of-file {
+ /* Keep this in sync with inspectorSyntaxHighlight.css (.webkit-html-end-of-file) */
+ color: rgb(255, 0, 0);
+ font-weight: bold;
+}
+
.webkit-html-message-bubble {
box-shadow: black 0px 2px 5px;
border-radius: 9px;
diff --git a/chromium/third_party/WebKit/Source/core/css/viewportAndroid.css b/chromium/third_party/WebKit/Source/core/css/viewportAndroid.css
new file mode 100644
index 00000000000..f40650501ef
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/css/viewportAndroid.css
@@ -0,0 +1,35 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/* These styles override other user-agent styles for Chromium on Android. */
+
+@viewport {
+ min-width: 980px;
+}
diff --git a/chromium/third_party/WebKit/Source/core/dom/ActiveDOMObject.cpp b/chromium/third_party/WebKit/Source/core/dom/ActiveDOMObject.cpp
index 161428839aa..be52d0f70fd 100644
--- a/chromium/third_party/WebKit/Source/core/dom/ActiveDOMObject.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/ActiveDOMObject.cpp
@@ -27,33 +27,33 @@
#include "config.h"
#include "core/dom/ActiveDOMObject.h"
-#include "core/dom/ScriptExecutionContext.h"
+#include "core/dom/ExecutionContext.h"
namespace WebCore {
-ActiveDOMObject::ActiveDOMObject(ScriptExecutionContext* scriptExecutionContext)
- : ContextLifecycleObserver(scriptExecutionContext, ActiveDOMObjectType)
+ActiveDOMObject::ActiveDOMObject(ExecutionContext* executionContext)
+ : ContextLifecycleObserver(executionContext, ActiveDOMObjectType)
, m_pendingActivityCount(0)
#if !ASSERT_DISABLED
, m_suspendIfNeededCalled(false)
#endif
{
- ASSERT(!scriptExecutionContext || scriptExecutionContext->isContextThread());
+ ASSERT(!executionContext || executionContext->isContextThread());
}
ActiveDOMObject::~ActiveDOMObject()
{
// ActiveDOMObject may be inherited by a sub-class whose life-cycle
- // exceeds that of the associated ScriptExecutionContext. In those cases,
- // m_scriptExecutionContext would/should have been nullified by
+ // exceeds that of the associated ExecutionContext. In those cases,
+ // m_executionContext would/should have been nullified by
// ContextLifecycleObserver::contextDestroyed() (which we implement /
// inherit). Hence, we should ensure that this is not 0 before use it
// here.
- if (!scriptExecutionContext())
+ if (!executionContext())
return;
ASSERT(m_suspendIfNeededCalled);
- ASSERT(scriptExecutionContext()->isContextThread());
+ ASSERT(executionContext()->isContextThread());
}
void ActiveDOMObject::suspendIfNeeded()
@@ -62,8 +62,8 @@ void ActiveDOMObject::suspendIfNeeded()
ASSERT(!m_suspendIfNeededCalled);
m_suspendIfNeededCalled = true;
#endif
- if (ScriptExecutionContext* context = scriptExecutionContext())
- scriptExecutionContext()->suspendActiveDOMObjectIfNeeded(this);
+ if (ExecutionContext* context = executionContext())
+ context->suspendActiveDOMObjectIfNeeded(this);
}
bool ActiveDOMObject::hasPendingActivity() const
@@ -71,12 +71,7 @@ bool ActiveDOMObject::hasPendingActivity() const
return m_pendingActivityCount;
}
-bool ActiveDOMObject::canSuspend() const
-{
- return false;
-}
-
-void ActiveDOMObject::suspend(ReasonForSuspension)
+void ActiveDOMObject::suspend()
{
}
diff --git a/chromium/third_party/WebKit/Source/core/dom/ActiveDOMObject.h b/chromium/third_party/WebKit/Source/core/dom/ActiveDOMObject.h
index 0e123c71ac7..1157363cb3b 100644
--- a/chromium/third_party/WebKit/Source/core/dom/ActiveDOMObject.h
+++ b/chromium/third_party/WebKit/Source/core/dom/ActiveDOMObject.h
@@ -35,33 +35,31 @@ namespace WebCore {
class ActiveDOMObject : public ContextLifecycleObserver {
public:
- ActiveDOMObject(ScriptExecutionContext*);
+ ActiveDOMObject(ExecutionContext*);
// suspendIfNeeded() should be called exactly once after object construction to synchronize
- // the suspend state with that in ScriptExecutionContext.
+ // the suspend state with that in ExecutionContext.
void suspendIfNeeded();
#if !ASSERT_DISABLED
bool suspendIfNeededCalled() const { return m_suspendIfNeededCalled; }
#endif
+ // Should return true if there's any pending asynchronous activity, and so
+ // this object must not be garbage collected.
+ //
+ // Default implementation is that it returns true iff
+ // m_pendingActivityCount is non-zero.
virtual bool hasPendingActivity() const;
- // canSuspend() is used by the caller if there is a choice between suspending and stopping.
- // For example, a page won't be suspended and placed in the back/forward cache if it has
- // the objects that can not be suspended.
- // However, 'suspend' can be called even if canSuspend() would return 'false'. That
- // happens in step-by-step JS debugging for example - in this case it would be incorrect
- // to stop the object. Exact semantics of suspend is up to the object then.
- enum ReasonForSuspension {
- JavaScriptDebuggerPaused,
- WillDeferLoading,
- DocumentWillBecomeInactive
- };
- virtual bool canSuspend() const;
- virtual void suspend(ReasonForSuspension);
+ // These methods have an empty default implementation so that subclasses
+ // which don't need special treatment can skip implementation.
+ virtual void suspend();
virtual void resume();
virtual void stop();
+protected:
+ virtual ~ActiveDOMObject();
+
template<class T> void setPendingActivity(T* thisObject)
{
ASSERT(thisObject == this);
@@ -76,9 +74,6 @@ public:
thisObject->deref();
}
-protected:
- virtual ~ActiveDOMObject();
-
private:
unsigned m_pendingActivityCount;
#if !ASSERT_DISABLED
diff --git a/chromium/third_party/WebKit/Source/core/dom/AddConsoleMessageTask.cpp b/chromium/third_party/WebKit/Source/core/dom/AddConsoleMessageTask.cpp
new file mode 100644
index 00000000000..58f0304fed9
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/AddConsoleMessageTask.cpp
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/dom/AddConsoleMessageTask.h"
+
+#include "core/dom/ExecutionContext.h"
+
+namespace WebCore {
+
+void AddConsoleMessageTask::performTask(ExecutionContext* context)
+{
+ context->addConsoleMessage(m_source, m_level, m_message);
+}
+
+} // namespace
diff --git a/chromium/third_party/WebKit/Source/core/dom/AddConsoleMessageTask.h b/chromium/third_party/WebKit/Source/core/dom/AddConsoleMessageTask.h
new file mode 100644
index 00000000000..deb1e06206b
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/AddConsoleMessageTask.h
@@ -0,0 +1,59 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef AddConsoleMessageTask_h
+#define AddConsoleMessageTask_h
+
+#include "core/dom/ExecutionContextTask.h"
+#include "core/frame/ConsoleTypes.h"
+#include "wtf/OwnPtr.h"
+#include "wtf/PassOwnPtr.h"
+#include "wtf/text/WTFString.h"
+
+namespace WebCore {
+
+class AddConsoleMessageTask : public ExecutionContextTask {
+public:
+ static PassOwnPtr<AddConsoleMessageTask> create(MessageSource source, MessageLevel level, const String& message)
+ {
+ return adoptPtr(new AddConsoleMessageTask(source, level, message));
+ }
+ virtual void performTask(ExecutionContext*);
+private:
+ AddConsoleMessageTask(MessageSource source, MessageLevel level, const String& message)
+ : m_source(source)
+ , m_level(level)
+ , m_message(message.isolatedCopy())
+ {
+ }
+ MessageSource m_source;
+ MessageLevel m_level;
+ String m_message;
+};
+
+} // namespace
+
+#endif
diff --git a/chromium/third_party/WebKit/Source/core/dom/Attr.cpp b/chromium/third_party/WebKit/Source/core/dom/Attr.cpp
index 26fc0d78fb6..b67b2818f65 100644
--- a/chromium/third_party/WebKit/Source/core/dom/Attr.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/Attr.cpp
@@ -24,13 +24,13 @@
#include "core/dom/Attr.h"
#include "XMLNSNames.h"
-#include "bindings/v8/ExceptionMessages.h"
#include "bindings/v8/ExceptionState.h"
#include "bindings/v8/ExceptionStatePlaceholder.h"
#include "core/dom/Element.h"
#include "core/dom/ExceptionCode.h"
-#include "core/dom/ScopedEventQueue.h"
#include "core/dom/Text.h"
+#include "core/events/ScopedEventQueue.h"
+#include "core/frame/UseCounter.h"
#include "wtf/text/AtomicString.h"
#include "wtf/text/StringBuilder.h"
@@ -43,7 +43,6 @@ Attr::Attr(Element& element, const QualifiedName& name)
, m_element(&element)
, m_name(name)
, m_ignoreChildrenChanged(0)
- , m_specified(true)
{
ScriptWrappable::init(this);
}
@@ -54,7 +53,6 @@ Attr::Attr(Document& document, const QualifiedName& name, const AtomicString& st
, m_name(name)
, m_standaloneValue(standaloneValue)
, m_ignoreChildrenChanged(0)
- , m_specified(true)
{
ScriptWrappable::init(this);
}
@@ -86,25 +84,27 @@ void Attr::createTextChild()
// This does everything appendChild() would do in this situation (assuming m_ignoreChildrenChanged was set),
// but much more efficiently.
textNode->setParentOrShadowHostNode(this);
- treeScope().adoptIfNeeded(textNode.get());
+ treeScope().adoptIfNeeded(*textNode);
setFirstChild(textNode.get());
setLastChild(textNode.get());
}
}
-void Attr::setPrefix(const AtomicString& prefix, ExceptionState& es)
+void Attr::setPrefix(const AtomicString& prefix, ExceptionState& exceptionState)
{
- checkSetPrefix(prefix, es);
- if (es.hadException())
+ UseCounter::count(document(), UseCounter::AttributeSetPrefix);
+
+ checkSetPrefix(prefix, exceptionState);
+ if (exceptionState.hadException())
return;
if (prefix == xmlnsAtom && namespaceURI() != XMLNSNames::xmlnsNamespaceURI) {
- es.throwDOMException(NamespaceError, ExceptionMessages::failedToSet("prefix", "Attr", "The prefix '" + xmlnsAtom + "' may not be used on the namespace '" + namespaceURI() + "'."));
+ exceptionState.throwDOMException(NamespaceError, "The prefix '" + xmlnsAtom + "' may not be used on the namespace '" + namespaceURI() + "'.");
return;
}
if (this->qualifiedName() == xmlnsAtom) {
- es.throwDOMException(NamespaceError, ExceptionMessages::failedToSet("prefix", "Attr", "The prefix '" + prefix + "' may not be used as a namespace prefix for attributes whose qualified name is '" + xmlnsAtom + "'."));
+ exceptionState.throwDOMException(NamespaceError, "The prefix '" + prefix + "' may not be used as a namespace prefix for attributes whose qualified name is '" + xmlnsAtom + "'.");
return;
}
diff --git a/chromium/third_party/WebKit/Source/core/dom/Attr.h b/chromium/third_party/WebKit/Source/core/dom/Attr.h
index bd9e7eb5e2e..40d812b3997 100644
--- a/chromium/third_party/WebKit/Source/core/dom/Attr.h
+++ b/chromium/third_party/WebKit/Source/core/dom/Attr.h
@@ -47,7 +47,7 @@ public:
virtual ~Attr();
String name() const { return qualifiedName().toString(); }
- bool specified() const { return m_specified; }
+ bool specified() const { return true; }
Element* ownerElement() const { return m_element; }
const AtomicString& value() const;
@@ -58,8 +58,6 @@ public:
bool isId() const;
- void setSpecified(bool specified) { m_specified = specified; }
-
void attachToElement(Element*);
void detachFromElementWithValue(const AtomicString&);
@@ -94,22 +92,10 @@ private:
Element* m_element;
QualifiedName m_name;
AtomicString m_standaloneValue;
-
- unsigned m_ignoreChildrenChanged : 31;
- bool m_specified : 1;
+ unsigned m_ignoreChildrenChanged;
};
-inline Attr* toAttr(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->isAttributeNode());
- return static_cast<Attr*>(node);
-}
-
-inline const Attr* toAttr(const Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->isAttributeNode());
- return static_cast<const Attr*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(Attr, isAttributeNode());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/Attr.idl b/chromium/third_party/WebKit/Source/core/dom/Attr.idl
index 0dcdb021712..00d9205a929 100644
--- a/chromium/third_party/WebKit/Source/core/dom/Attr.idl
+++ b/chromium/third_party/WebKit/Source/core/dom/Attr.idl
@@ -24,21 +24,21 @@ interface Attr : Node {
[TreatReturnedNullStringAs=Null] readonly attribute DOMString name;
- readonly attribute boolean specified;
+ [MeasureAs=AttributeSpecified] readonly attribute boolean specified;
- [TreatReturnedNullStringAs=Null, TreatNullAs=NullString, SetterRaisesException, CustomElementCallbacks=Enable] attribute DOMString value;
+ [TreatReturnedNullStringAs=Null, TreatNullAs=NullString, RaisesException=Setter, CustomElementCallbacks] attribute DOMString value;
// DOM Level 2
- readonly attribute Element ownerElement;
+ [MeasureAs=AttributeOwnerElement] readonly attribute Element ownerElement;
// DOM Level 3
- readonly attribute boolean isId;
+ [MeasureAs=AttributeIsId] readonly attribute boolean isId;
// DOM 4
- [TreatReturnedNullStringAs=Null, TreatNullAs=NullString, PerWorldBindings, SetterRaisesException] attribute DOMString prefix;
+ [TreatReturnedNullStringAs=Null, TreatNullAs=NullString, PerWorldBindings, RaisesException=Setter] attribute DOMString prefix;
[TreatReturnedNullStringAs=Null, PerWorldBindings] readonly attribute DOMString namespaceURI;
[TreatReturnedNullStringAs=Null, PerWorldBindings] readonly attribute DOMString localName;
};
diff --git a/chromium/third_party/WebKit/Source/core/dom/AutocompleteErrorEvent.h b/chromium/third_party/WebKit/Source/core/dom/AutocompleteErrorEvent.h
deleted file mode 100644
index 2f36cc7caa9..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/AutocompleteErrorEvent.h
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef AutocompleteErrorEvent_h
-#define AutocompleteErrorEvent_h
-
-#include "core/dom/Event.h"
-#include "core/dom/EventNames.h"
-
-namespace WebCore {
-
-struct AutocompleteErrorEventInit : public EventInit {
- String reason;
-};
-
-class AutocompleteErrorEvent : public Event {
-public:
- static PassRefPtr<AutocompleteErrorEvent> create()
- {
- return adoptRef(new AutocompleteErrorEvent);
- }
-
- static PassRefPtr<AutocompleteErrorEvent> create(const String& reason)
- {
- return adoptRef(new AutocompleteErrorEvent(reason));
- }
-
- static PassRefPtr<AutocompleteErrorEvent> create(const AtomicString& eventType, const AutocompleteErrorEventInit& initializer)
- {
- return adoptRef(new AutocompleteErrorEvent(eventType, initializer));
- }
-
- const String& reason() const { return m_reason; }
-
- virtual const AtomicString& interfaceName() const { return eventNames().interfaceForAutocompleteErrorEvent; }
-
-private:
- AutocompleteErrorEvent()
- {
- ScriptWrappable::init(this);
- }
-
- AutocompleteErrorEvent(const String& reason)
- : Event(eventNames().autocompleteerrorEvent, false, false)
- , m_reason(reason)
- {
- ScriptWrappable::init(this);
- }
-
- AutocompleteErrorEvent(const AtomicString& eventType, const AutocompleteErrorEventInit& initializer)
- : Event(eventType, initializer)
- , m_reason(initializer.reason)
- {
- ScriptWrappable::init(this);
- }
-
- String m_reason;
-};
-
-} // namespace WebCore
-
-#endif // AutocompleteErrorEvent_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/AutocompleteErrorEvent.idl b/chromium/third_party/WebKit/Source/core/dom/AutocompleteErrorEvent.idl
deleted file mode 100644
index 5f9b7008e4f..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/AutocompleteErrorEvent.idl
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-[
- ConstructorTemplate=Event
-] interface AutocompleteErrorEvent : Event {
- [InitializedByEventConstructor] readonly attribute DOMString reason;
-};
-
diff --git a/chromium/third_party/WebKit/Source/core/dom/BeforeLoadEvent.h b/chromium/third_party/WebKit/Source/core/dom/BeforeLoadEvent.h
deleted file mode 100644
index 1e6d5fcbfd8..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/BeforeLoadEvent.h
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * Copyright (C) 2009 Apple Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-#ifndef BeforeLoadEvent_h
-#define BeforeLoadEvent_h
-
-#include "core/dom/Event.h"
-#include "core/dom/EventNames.h"
-
-namespace WebCore {
-
-struct BeforeLoadEventInit : public EventInit {
- BeforeLoadEventInit()
- {
- };
-
- String url;
-};
-
-class BeforeLoadEvent : public Event {
-public:
- static PassRefPtr<BeforeLoadEvent> create()
- {
- return adoptRef(new BeforeLoadEvent);
- }
-
- static PassRefPtr<BeforeLoadEvent> create(const String& url)
- {
- return adoptRef(new BeforeLoadEvent(url));
- }
-
- static PassRefPtr<BeforeLoadEvent> create(const AtomicString& type, const BeforeLoadEventInit& initializer)
- {
- return adoptRef(new BeforeLoadEvent(type, initializer));
- }
-
- const String& url() const { return m_url; }
-
- virtual const AtomicString& interfaceName() const { return eventNames().interfaceForBeforeLoadEvent; }
-
-private:
- BeforeLoadEvent()
- {
- ScriptWrappable::init(this);
- }
-
- explicit BeforeLoadEvent(const String& url)
- : Event(eventNames().beforeloadEvent, false, true)
- , m_url(url)
- {
- ScriptWrappable::init(this);
- }
-
- BeforeLoadEvent(const AtomicString& type, const BeforeLoadEventInit& initializer)
- : Event(type, initializer)
- , m_url(initializer.url)
- {
- ScriptWrappable::init(this);
- }
-
- String m_url;
-};
-
-} // namespace WebCore
-
-#endif // BeforeLoadEvent_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/BeforeLoadEvent.idl b/chromium/third_party/WebKit/Source/core/dom/BeforeLoadEvent.idl
deleted file mode 100644
index 428a513123d..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/BeforeLoadEvent.idl
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright (C) 2009 Apple Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-[
- ConstructorTemplate=Event
-] interface BeforeLoadEvent : Event {
- [InitializedByEventConstructor] readonly attribute DOMString url;
-};
-
diff --git a/chromium/third_party/WebKit/Source/core/dom/BeforeTextInsertedEvent.cpp b/chromium/third_party/WebKit/Source/core/dom/BeforeTextInsertedEvent.cpp
deleted file mode 100644
index 72e478038d7..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/BeforeTextInsertedEvent.cpp
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Copyright (C) 2005 Apple Computer, Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/dom/BeforeTextInsertedEvent.h"
-
-#include "core/dom/EventNames.h"
-
-namespace WebCore {
-
-BeforeTextInsertedEvent::BeforeTextInsertedEvent(const String& text)
- : Event(eventNames().webkitBeforeTextInsertedEvent, false, true), m_text(text)
-{
-}
-
-BeforeTextInsertedEvent::~BeforeTextInsertedEvent()
-{
-}
-
-const AtomicString& BeforeTextInsertedEvent::interfaceName() const
-{
- // Notice that there is no BeforeTextInsertedEvent.idl.
- return eventNames().interfaceForEvent;
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/dom/BeforeTextInsertedEvent.h b/chromium/third_party/WebKit/Source/core/dom/BeforeTextInsertedEvent.h
deleted file mode 100644
index a08e2de10af..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/BeforeTextInsertedEvent.h
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright (C) 2006 Apple Computer, Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef BeforeTextInsertedEvent_h
-#define BeforeTextInsertedEvent_h
-
-#include "core/dom/Event.h"
-
-namespace WebCore {
-
-class BeforeTextInsertedEvent : public Event {
-public:
- virtual ~BeforeTextInsertedEvent();
-
- static PassRefPtr<BeforeTextInsertedEvent> create(const String& text)
- {
- return adoptRef(new BeforeTextInsertedEvent(text));
- }
-
- virtual const AtomicString& interfaceName() const;
- virtual bool isBeforeTextInsertedEvent() const { return true; }
-
- const String& text() const { return m_text; }
- void setText(const String& s) { m_text = s; }
-
-private:
- explicit BeforeTextInsertedEvent(const String&);
-
- String m_text;
-};
-
-} // namespace
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/dom/BeforeUnloadEvent.cpp b/chromium/third_party/WebKit/Source/core/dom/BeforeUnloadEvent.cpp
deleted file mode 100644
index a22374c0619..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/BeforeUnloadEvent.cpp
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Copyright (C) 2001 Peter Kelly (pmk@post.com)
- * Copyright (C) 2001 Tobias Anton (anton@stud.fbi.fh-darmstadt.de)
- * Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
- * Copyright (C) 2003, 2005, 2006 Apple Computer, Inc.
- * Copyright (C) 2013 Samsung Electronics.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-#include "core/dom/BeforeUnloadEvent.h"
-
-#include "core/dom/EventNames.h"
-
-namespace WebCore {
-
-BeforeUnloadEvent::BeforeUnloadEvent()
- : Event(eventNames().beforeunloadEvent, false, true)
-{
- ScriptWrappable::init(this);
-}
-
-BeforeUnloadEvent::~BeforeUnloadEvent()
-{
-}
-
-bool BeforeUnloadEvent::isBeforeUnloadEvent() const
-{
- return true;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/BeforeUnloadEvent.h b/chromium/third_party/WebKit/Source/core/dom/BeforeUnloadEvent.h
deleted file mode 100644
index a76ad521bca..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/BeforeUnloadEvent.h
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Copyright (C) 2001 Peter Kelly (pmk@post.com)
- * Copyright (C) 2001 Tobias Anton (anton@stud.fbi.fh-darmstadt.de)
- * Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
- * Copyright (C) 2003, 2004, 2005, 2006 Apple Computer, Inc.
- * Copyright (C) 2013 Samsung Electronics.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#ifndef BeforeUnloadEvent_h
-#define BeforeUnloadEvent_h
-
-#include "core/dom/Event.h"
-#include "core/dom/EventNames.h"
-
-namespace WebCore {
-
-class BeforeUnloadEvent : public Event {
-public:
- virtual ~BeforeUnloadEvent();
-
- static PassRefPtr<BeforeUnloadEvent> create()
- {
- return adoptRef(new BeforeUnloadEvent);
- }
-
- virtual bool isBeforeUnloadEvent() const OVERRIDE;
-
- void setReturnValue(const String& returnValue) { m_returnValue = returnValue; }
- String returnValue() const { return m_returnValue; }
-
- virtual const AtomicString& interfaceName() const OVERRIDE { return eventNames().interfaceForBeforeUnloadEvent; }
-
-private:
- BeforeUnloadEvent();
-
- String m_returnValue;
-};
-
-inline BeforeUnloadEvent* toBeforeUnloadEvent(Event* event)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!event || event->isBeforeUnloadEvent());
- return static_cast<BeforeUnloadEvent*>(event);
-}
-
-} // namespace WebCore
-
-#endif // BeforeUnloadEvent_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/CDATASection.h b/chromium/third_party/WebKit/Source/core/dom/CDATASection.h
index ed9075f17d2..338866f02ec 100644
--- a/chromium/third_party/WebKit/Source/core/dom/CDATASection.h
+++ b/chromium/third_party/WebKit/Source/core/dom/CDATASection.h
@@ -40,17 +40,7 @@ private:
virtual PassRefPtr<Text> cloneWithData(const String&) OVERRIDE;
};
-inline CDATASection* toCDATASection(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->nodeType() == Node::CDATA_SECTION_NODE);
- return static_cast<CDATASection*>(node);
-}
-
-inline const CDATASection* toCDATASection(const Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->nodeType() == Node::CDATA_SECTION_NODE);
- return static_cast<const CDATASection*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(CDATASection, nodeType() == Node::CDATA_SECTION_NODE);
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/CSSSelectorWatch.cpp b/chromium/third_party/WebKit/Source/core/dom/CSSSelectorWatch.cpp
new file mode 100644
index 00000000000..074d6b2ee81
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/CSSSelectorWatch.cpp
@@ -0,0 +1,168 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/dom/CSSSelectorWatch.h"
+
+#include "core/css/CSSParser.h"
+#include "core/css/CSSSelectorList.h"
+#include "core/css/StylePropertySet.h"
+#include "core/dom/Document.h"
+#include "core/dom/ExecutionContext.h"
+#include "core/loader/FrameLoaderClient.h"
+#include "core/frame/Frame.h"
+#include "core/rendering/style/StyleRareNonInheritedData.h"
+
+namespace WebCore {
+
+// The address of this string is important; its value is just documentation.
+static const char kSupplementName[] = "CSSSelectorWatch";
+
+CSSSelectorWatch::CSSSelectorWatch(Document& document)
+ : m_document(document)
+ , m_callbackSelectorChangeTimer(this, &CSSSelectorWatch::callbackSelectorChangeTimerFired)
+ , m_timerExpirations(0)
+{
+}
+
+CSSSelectorWatch& CSSSelectorWatch::from(Document& document)
+{
+ CSSSelectorWatch* watch = static_cast<CSSSelectorWatch*>(DocumentSupplement::from(&document, kSupplementName));
+ if (!watch) {
+ watch = new CSSSelectorWatch(document);
+ DocumentSupplement::provideTo(&document, kSupplementName, adoptPtr(watch));
+ }
+ return *watch;
+}
+
+void CSSSelectorWatch::callbackSelectorChangeTimerFired(Timer<CSSSelectorWatch>*)
+{
+ // Should be ensured by updateSelectorMatches():
+ ASSERT(!m_addedSelectors.isEmpty() || !m_removedSelectors.isEmpty());
+
+ if (m_timerExpirations < 1) {
+ m_timerExpirations++;
+ m_callbackSelectorChangeTimer.startOneShot(0);
+ return;
+ }
+ if (m_document.frame()) {
+ Vector<String> addedSelectors;
+ Vector<String> removedSelectors;
+ copyToVector(m_addedSelectors, addedSelectors);
+ copyToVector(m_removedSelectors, removedSelectors);
+ m_document.frame()->loader().client()->selectorMatchChanged(addedSelectors, removedSelectors);
+ }
+ m_addedSelectors.clear();
+ m_removedSelectors.clear();
+ m_timerExpirations = 0;
+}
+
+void CSSSelectorWatch::updateSelectorMatches(const Vector<String>& removedSelectors, const Vector<String>& addedSelectors)
+{
+ bool shouldUpdateTimer = false;
+
+ for (unsigned i = 0; i < removedSelectors.size(); ++i) {
+ const String& selector = removedSelectors[i];
+ if (!m_matchingCallbackSelectors.remove(selector))
+ continue;
+
+ // Count reached 0.
+ shouldUpdateTimer = true;
+ if (m_addedSelectors.contains(selector))
+ m_addedSelectors.remove(selector);
+ else
+ m_removedSelectors.add(selector);
+ }
+
+ for (unsigned i = 0; i < addedSelectors.size(); ++i) {
+ const String& selector = addedSelectors[i];
+ HashCountedSet<String>::AddResult result = m_matchingCallbackSelectors.add(selector);
+ if (!result.isNewEntry)
+ continue;
+
+ shouldUpdateTimer = true;
+ if (m_removedSelectors.contains(selector))
+ m_removedSelectors.remove(selector);
+ else
+ m_addedSelectors.add(selector);
+ }
+
+ if (!shouldUpdateTimer)
+ return;
+
+ if (m_removedSelectors.isEmpty() && m_addedSelectors.isEmpty()) {
+ if (m_callbackSelectorChangeTimer.isActive()) {
+ m_timerExpirations = 0;
+ m_callbackSelectorChangeTimer.stop();
+ }
+ } else {
+ m_timerExpirations = 0;
+ if (!m_callbackSelectorChangeTimer.isActive())
+ m_callbackSelectorChangeTimer.startOneShot(0);
+ }
+}
+
+static bool allCompound(const CSSSelectorList& selectorList)
+{
+ for (const CSSSelector* selector = selectorList.first(); selector; selector = selectorList.next(selector)) {
+ if (!selector->isCompound())
+ return false;
+ }
+ return true;
+}
+
+void CSSSelectorWatch::watchCSSSelectors(const Vector<String>& selectors)
+{
+ m_watchedCallbackSelectors.clear();
+ CSSParserContext context(UASheetMode);
+ CSSParser parser(context);
+
+ const CSSProperty callbackProperty(CSSPropertyInternalCallback, CSSPrimitiveValue::createIdentifier(CSSValueInternalPresence));
+ const RefPtr<StylePropertySet> callbackPropertySet = ImmutableStylePropertySet::create(&callbackProperty, 1, UASheetMode);
+
+ CSSSelectorList selectorList;
+ for (unsigned i = 0; i < selectors.size(); ++i) {
+ parser.parseSelector(selectors[i], selectorList);
+ if (!selectorList.isValid())
+ continue;
+
+ // Only accept Compound Selectors, since they're cheaper to match.
+ if (!allCompound(selectorList))
+ continue;
+
+ RefPtr<StyleRule> rule = StyleRule::create();
+ rule->wrapperAdoptSelectorList(selectorList);
+ rule->setProperties(callbackPropertySet);
+ m_watchedCallbackSelectors.append(rule.release());
+ }
+ m_document.changedSelectorWatch();
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/CSSSelectorWatch.h b/chromium/third_party/WebKit/Source/core/dom/CSSSelectorWatch.h
new file mode 100644
index 00000000000..e1cbbed5608
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/CSSSelectorWatch.h
@@ -0,0 +1,82 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef CSSSelectorWatch_h
+#define CSSSelectorWatch_h
+
+#include "core/css/StyleRule.h"
+#include "core/dom/DocumentSupplementable.h"
+#include "platform/Timer.h"
+#include "wtf/HashCountedSet.h"
+#include "wtf/HashSet.h"
+#include "wtf/RefPtr.h"
+#include "wtf/Vector.h"
+#include "wtf/WeakPtr.h"
+#include "wtf/text/WTFString.h"
+
+namespace WebCore {
+
+class CSSSelectorWatch : public DocumentSupplement {
+public:
+ virtual ~CSSSelectorWatch() { }
+
+ static CSSSelectorWatch& from(Document&);
+
+ void watchCSSSelectors(const Vector<String>& selectors);
+ const Vector<RefPtr<StyleRule> >& watchedCallbackSelectors() const { return m_watchedCallbackSelectors; }
+
+ void updateSelectorMatches(const Vector<String>& removedSelectors, const Vector<String>& addedSelectors);
+
+private:
+ CSSSelectorWatch(Document&);
+ void callbackSelectorChangeTimerFired(Timer<CSSSelectorWatch>*);
+
+ Document& m_document;
+
+ Vector<RefPtr<StyleRule> > m_watchedCallbackSelectors;
+
+ // Maps a CSS selector string with a -webkit-callback property to the number
+ // of matching RenderStyle objects in this document.
+ HashCountedSet<String> m_matchingCallbackSelectors;
+ // Selectors are relative to m_matchingCallbackSelectors's contents at
+ // the previous call to selectorMatchChanged.
+ HashSet<String> m_addedSelectors;
+ HashSet<String> m_removedSelectors;
+
+ Timer<CSSSelectorWatch> m_callbackSelectorChangeTimer;
+
+ // When an element is reparented, the new location's style is evaluated after the expriation of the relayout timer.
+ // We don't want to send redundant callbacks to the embedder, so this counter lets us wait another time around the event loop.
+ int m_timerExpirations;
+};
+
+} // namespace WebCore
+
+#endif // CSSSelectorWatch_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/CharacterData.cpp b/chromium/third_party/WebKit/Source/core/dom/CharacterData.cpp
index 9d6f9c7e3a9..d0344f255cd 100644
--- a/chromium/third_party/WebKit/Source/core/dom/CharacterData.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/CharacterData.cpp
@@ -22,19 +22,17 @@
#include "config.h"
#include "core/dom/CharacterData.h"
-#include "bindings/v8/ExceptionMessages.h"
#include "bindings/v8/ExceptionState.h"
#include "core/dom/Document.h"
-#include "core/dom/EventNames.h"
#include "core/dom/ExceptionCode.h"
-#include "core/dom/MutationEvent.h"
#include "core/dom/MutationObserverInterestGroup.h"
#include "core/dom/MutationRecord.h"
#include "core/dom/ProcessingInstruction.h"
#include "core/dom/Text.h"
#include "core/editing/FrameSelection.h"
+#include "core/events/MutationEvent.h"
+#include "core/events/ThreadLocalEventNames.h"
#include "core/inspector/InspectorInstrumentation.h"
-#include "core/platform/text/TextBreakIterator.h"
using namespace std;
@@ -59,43 +57,20 @@ void CharacterData::setData(const String& data)
document().didRemoveText(this, 0, oldLength);
}
-String CharacterData::substringData(unsigned offset, unsigned count, ExceptionState& es)
+String CharacterData::substringData(unsigned offset, unsigned count, ExceptionState& exceptionState)
{
if (offset > length()) {
- es.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("substringData", "CharacterData", "The offset " + String::number(offset) + " is greater than the node's length (" + String::number(length()) + ")."));
+ exceptionState.throwDOMException(IndexSizeError, "The offset " + String::number(offset) + " is greater than the node's length (" + String::number(length()) + ").");
return String();
}
return m_data.substring(offset, count);
}
-unsigned CharacterData::parserAppendData(const String& string, unsigned offset, unsigned lengthLimit)
+void CharacterData::parserAppendData(const String& string)
{
unsigned oldLength = m_data.length();
-
- ASSERT(lengthLimit >= oldLength);
-
- unsigned characterLength = string.length() - offset;
- unsigned characterLengthLimit = min(characterLength, lengthLimit - oldLength);
-
- // Check that we are not on an unbreakable boundary.
- // Some text break iterator implementations work best if the passed buffer is as small as possible,
- // see <https://bugs.webkit.org/show_bug.cgi?id=29092>.
- // We need at least two characters look-ahead to account for UTF-16 surrogates.
- ASSERT(!string.is8Bit() || string.containsOnlyLatin1()); // Latin-1 doesn't have unbreakable boundaries.
- if (characterLengthLimit < characterLength && !string.is8Bit()) {
- NonSharedCharacterBreakIterator it(string.characters16() + offset, (characterLengthLimit + 2 > characterLength) ? characterLength : characterLengthLimit + 2);
- if (!it.isBreak(characterLengthLimit))
- characterLengthLimit = it.preceding(characterLengthLimit);
- }
-
- if (!characterLengthLimit)
- return 0;
-
- if (string.is8Bit())
- m_data.append(string.characters8() + offset, characterLengthLimit);
- else
- m_data.append(string.characters16() + offset, characterLengthLimit);
+ m_data.append(string);
ASSERT(!renderer() || isTextNode());
if (isTextNode())
@@ -105,8 +80,6 @@ unsigned CharacterData::parserAppendData(const String& string, unsigned offset,
if (parentNode())
parentNode()->childrenChanged();
-
- return characterLengthLimit;
}
void CharacterData::appendData(const String& data)
@@ -118,10 +91,10 @@ void CharacterData::appendData(const String& data)
// FIXME: Should we call textInserted here?
}
-void CharacterData::insertData(unsigned offset, const String& data, ExceptionState& es, RecalcStyleBehavior recalcStyleBehavior)
+void CharacterData::insertData(unsigned offset, const String& data, ExceptionState& exceptionState, RecalcStyleBehavior recalcStyleBehavior)
{
if (offset > length()) {
- es.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("insertData", "CharacterData", "The offset " + String::number(offset) + " is greater than the node's length (" + String::number(length()) + ")."));
+ exceptionState.throwDOMException(IndexSizeError, "The offset " + String::number(offset) + " is greater than the node's length (" + String::number(length()) + ").");
return;
}
@@ -133,10 +106,10 @@ void CharacterData::insertData(unsigned offset, const String& data, ExceptionSta
document().didInsertText(this, offset, data.length());
}
-void CharacterData::deleteData(unsigned offset, unsigned count, ExceptionState& es, RecalcStyleBehavior recalcStyleBehavior)
+void CharacterData::deleteData(unsigned offset, unsigned count, ExceptionState& exceptionState, RecalcStyleBehavior recalcStyleBehavior)
{
if (offset > length()) {
- es.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("deleteData", "CharacterData", "The offset " + String::number(offset) + " is greater than the node's length (" + String::number(length()) + ")."));
+ exceptionState.throwDOMException(IndexSizeError, "The offset " + String::number(offset) + " is greater than the node's length (" + String::number(length()) + ").");
return;
}
@@ -154,10 +127,10 @@ void CharacterData::deleteData(unsigned offset, unsigned count, ExceptionState&
document().didRemoveText(this, offset, realCount);
}
-void CharacterData::replaceData(unsigned offset, unsigned count, const String& data, ExceptionState& es)
+void CharacterData::replaceData(unsigned offset, unsigned count, const String& data, ExceptionState& exceptionState)
{
if (offset > length()) {
- es.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("replaceData", "CharacterData", "The offset " + String::number(offset) + " is greater than the node's length (" + String::number(length()) + ")."));
+ exceptionState.throwDOMException(IndexSizeError, "The offset " + String::number(offset) + " is greater than the node's length (" + String::number(length()) + ").");
return;
}
@@ -214,7 +187,7 @@ void CharacterData::setDataAndUpdate(const String& newData, unsigned offsetOfRep
void CharacterData::didModifyData(const String& oldData)
{
- if (OwnPtr<MutationObserverInterestGroup> mutationRecipients = MutationObserverInterestGroup::createForCharacterDataMutation(this))
+ if (OwnPtr<MutationObserverInterestGroup> mutationRecipients = MutationObserverInterestGroup::createForCharacterDataMutation(*this))
mutationRecipients->enqueueMutationRecord(MutationRecord::createCharacterData(this, oldData));
if (parentNode())
@@ -222,10 +195,10 @@ void CharacterData::didModifyData(const String& oldData)
if (!isInShadowTree()) {
if (document().hasListenerType(Document::DOMCHARACTERDATAMODIFIED_LISTENER))
- dispatchScopedEvent(MutationEvent::create(eventNames().DOMCharacterDataModifiedEvent, true, 0, oldData, m_data));
+ dispatchScopedEvent(MutationEvent::create(EventTypeNames::DOMCharacterDataModified, true, 0, oldData, m_data));
dispatchSubtreeModifiedEvent();
}
- InspectorInstrumentation::characterDataModified(&document(), this);
+ InspectorInstrumentation::characterDataModified(this);
}
int CharacterData::maxCharacterOffset() const
diff --git a/chromium/third_party/WebKit/Source/core/dom/CharacterData.h b/chromium/third_party/WebKit/Source/core/dom/CharacterData.h
index 8c50a3f5383..11636228cc7 100644
--- a/chromium/third_party/WebKit/Source/core/dom/CharacterData.h
+++ b/chromium/third_party/WebKit/Source/core/dom/CharacterData.h
@@ -48,9 +48,7 @@ public:
StringImpl* dataImpl() { return m_data.impl(); }
- // Like appendData, but optimized for the parser (e.g., no mutation events).
- // Returns how much could be added before length limit was met.
- unsigned parserAppendData(const String& string, unsigned offset, unsigned lengthLimit);
+ void parserAppendData(const String&);
protected:
CharacterData(TreeScope& treeScope, const String& text, ConstructionType type)
@@ -79,17 +77,7 @@ private:
void setDataAndUpdate(const String&, unsigned offsetOfReplacedData, unsigned oldLength, unsigned newLength, RecalcStyleBehavior = DoNotRecalcStyle);
};
-inline CharacterData* toCharacterData(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->isCharacterDataNode());
- return static_cast<CharacterData*>(node);
-}
-
-inline const CharacterData* toCharacterData(const Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->isCharacterDataNode());
- return static_cast<const CharacterData*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(CharacterData, isCharacterDataNode());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/ChildListMutationScope.cpp b/chromium/third_party/WebKit/Source/core/dom/ChildListMutationScope.cpp
index 6acb5b1ba68..1d00364cac5 100644
--- a/chromium/third_party/WebKit/Source/core/dom/ChildListMutationScope.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/ChildListMutationScope.cpp
@@ -33,10 +33,8 @@
#include "core/dom/MutationObserverInterestGroup.h"
#include "core/dom/MutationRecord.h"
-#include "core/dom/Node.h"
#include "core/dom/StaticNodeList.h"
#include "wtf/HashMap.h"
-#include "wtf/OwnPtr.h"
#include "wtf/StdLibExtras.h"
namespace WebCore {
@@ -62,14 +60,14 @@ ChildListMutationAccumulator::~ChildListMutationAccumulator()
accumulatorMap().remove(m_target.get());
}
-PassRefPtr<ChildListMutationAccumulator> ChildListMutationAccumulator::getOrCreate(Node* target)
+PassRefPtr<ChildListMutationAccumulator> ChildListMutationAccumulator::getOrCreate(Node& target)
{
- AccumulatorMap::AddResult result = accumulatorMap().add(target, 0);
+ AccumulatorMap::AddResult result = accumulatorMap().add(&target, 0);
RefPtr<ChildListMutationAccumulator> accumulator;
if (!result.isNewEntry)
accumulator = result.iterator->value;
else {
- accumulator = adoptRef(new ChildListMutationAccumulator(target, MutationObserverInterestGroup::createForChildListMutation(target)));
+ accumulator = adoptRef(new ChildListMutationAccumulator(PassRefPtr<Node>(target), MutationObserverInterestGroup::createForChildListMutation(target)));
result.iterator->value = accumulator.get();
}
return accumulator.release();
diff --git a/chromium/third_party/WebKit/Source/core/dom/ChildListMutationScope.h b/chromium/third_party/WebKit/Source/core/dom/ChildListMutationScope.h
index 442df97e19b..d847d826a6d 100644
--- a/chromium/third_party/WebKit/Source/core/dom/ChildListMutationScope.h
+++ b/chromium/third_party/WebKit/Source/core/dom/ChildListMutationScope.h
@@ -45,7 +45,7 @@ class MutationObserverInterestGroup;
// ChildListMutationAccumulator is not meant to be used directly; ChildListMutationScope is the public interface.
class ChildListMutationAccumulator : public RefCounted<ChildListMutationAccumulator> {
public:
- static PassRefPtr<ChildListMutationAccumulator> getOrCreate(Node*);
+ static PassRefPtr<ChildListMutationAccumulator> getOrCreate(Node&);
~ChildListMutationAccumulator();
void childAdded(PassRefPtr<Node>);
@@ -75,22 +75,22 @@ private:
class ChildListMutationScope {
WTF_MAKE_NONCOPYABLE(ChildListMutationScope);
public:
- explicit ChildListMutationScope(Node* target)
+ explicit ChildListMutationScope(Node& target)
{
- if (target->document().hasMutationObserversOfType(MutationObserver::ChildList))
+ if (target.document().hasMutationObserversOfType(MutationObserver::ChildList))
m_accumulator = ChildListMutationAccumulator::getOrCreate(target);
}
- void childAdded(Node* child)
+ void childAdded(Node& child)
{
if (m_accumulator && m_accumulator->hasObservers())
- m_accumulator->childAdded(child);
+ m_accumulator->childAdded(PassRefPtr<Node>(child));
}
- void willRemoveChild(Node* child)
+ void willRemoveChild(Node& child)
{
if (m_accumulator && m_accumulator->hasObservers())
- m_accumulator->willRemoveChild(child);
+ m_accumulator->willRemoveChild(PassRefPtr<Node>(child));
}
private:
diff --git a/chromium/third_party/WebKit/Source/core/dom/ChildNode.idl b/chromium/third_party/WebKit/Source/core/dom/ChildNode.idl
index 8a0be4dcd11..21441f63506 100644
--- a/chromium/third_party/WebKit/Source/core/dom/ChildNode.idl
+++ b/chromium/third_party/WebKit/Source/core/dom/ChildNode.idl
@@ -26,6 +26,6 @@
] interface ChildNode {
[PerWorldBindings] readonly attribute Element previousElementSibling;
[PerWorldBindings] readonly attribute Element nextElementSibling;
- [RaisesException, CustomElementCallbacks=Enable] void remove();
+ [RaisesException, CustomElementCallbacks] void remove();
};
diff --git a/chromium/third_party/WebKit/Source/core/dom/ChildNodeList.h b/chromium/third_party/WebKit/Source/core/dom/ChildNodeList.h
index af70df3c596..46f5beab4b1 100644
--- a/chromium/third_party/WebKit/Source/core/dom/ChildNodeList.h
+++ b/chromium/third_party/WebKit/Source/core/dom/ChildNodeList.h
@@ -29,20 +29,20 @@
namespace WebCore {
- class ChildNodeList : public LiveNodeList {
- public:
- static PassRefPtr<ChildNodeList> create(PassRefPtr<Node> rootNode)
- {
- return adoptRef(new ChildNodeList(rootNode));
- }
+class ChildNodeList FINAL : public LiveNodeList {
+public:
+ static PassRefPtr<ChildNodeList> create(PassRefPtr<Node> rootNode)
+ {
+ return adoptRef(new ChildNodeList(rootNode));
+ }
- virtual ~ChildNodeList();
+ virtual ~ChildNodeList();
- protected:
- explicit ChildNodeList(PassRefPtr<Node> rootNode);
+protected:
+ explicit ChildNodeList(PassRefPtr<Node> rootNode);
- virtual bool nodeMatches(Element*) const;
- };
+ virtual bool nodeMatches(Element*) const OVERRIDE;
+};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/ClassNodeList.h b/chromium/third_party/WebKit/Source/core/dom/ClassNodeList.h
index 0d90b3d892c..2e08ea81928 100644
--- a/chromium/third_party/WebKit/Source/core/dom/ClassNodeList.h
+++ b/chromium/third_party/WebKit/Source/core/dom/ClassNodeList.h
@@ -37,7 +37,7 @@
namespace WebCore {
-class ClassNodeList : public LiveNodeList {
+class ClassNodeList FINAL : public LiveNodeList {
public:
static PassRefPtr<ClassNodeList> create(PassRefPtr<Node> rootNode, const String& classNames)
{
@@ -51,7 +51,7 @@ public:
private:
ClassNodeList(PassRefPtr<Node> rootNode, const String& classNames);
- virtual bool nodeMatches(Element*) const;
+ virtual bool nodeMatches(Element*) const OVERRIDE;
SpaceSplitString m_classNames;
String m_originalClassNames;
diff --git a/chromium/third_party/WebKit/Source/core/dom/ClientRect.h b/chromium/third_party/WebKit/Source/core/dom/ClientRect.h
index 6476e0f493e..3ef3b24f3b4 100644
--- a/chromium/third_party/WebKit/Source/core/dom/ClientRect.h
+++ b/chromium/third_party/WebKit/Source/core/dom/ClientRect.h
@@ -28,7 +28,7 @@
#define ClientRect_h
#include "bindings/v8/ScriptWrappable.h"
-#include "core/platform/graphics/FloatRect.h"
+#include "platform/geometry/FloatRect.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefCounted.h"
diff --git a/chromium/third_party/WebKit/Source/core/dom/ClientRectList.h b/chromium/third_party/WebKit/Source/core/dom/ClientRectList.h
index bf36ef91afd..0639714f74e 100644
--- a/chromium/third_party/WebKit/Source/core/dom/ClientRectList.h
+++ b/chromium/third_party/WebKit/Source/core/dom/ClientRectList.h
@@ -28,7 +28,7 @@
#define ClientRectList_h
#include "bindings/v8/ScriptWrappable.h"
-#include "core/platform/graphics/FloatQuad.h"
+#include "platform/geometry/FloatQuad.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefCounted.h"
#include "wtf/Vector.h"
diff --git a/chromium/third_party/WebKit/Source/core/dom/Clipboard.cpp b/chromium/third_party/WebKit/Source/core/dom/Clipboard.cpp
index ee98d9f9586..4a16d84f8ef 100644
--- a/chromium/third_party/WebKit/Source/core/dom/Clipboard.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/Clipboard.cpp
@@ -26,52 +26,26 @@
#include "config.h"
#include "core/dom/Clipboard.h"
+#include "HTMLNames.h"
+#include "core/dom/DataTransferItem.h"
+#include "core/dom/DataTransferItemList.h"
+#include "core/editing/markup.h"
#include "core/fetch/ImageResource.h"
#include "core/fileapi/FileList.h"
+#include "core/html/HTMLImageElement.h"
+#include "core/frame/Frame.h"
+#include "core/platform/DragImage.h"
+#include "core/platform/chromium/ChromiumDataObject.h"
+#include "core/rendering/RenderImage.h"
+#include "core/rendering/RenderObject.h"
+#include "platform/MIMETypeRegistry.h"
+#include "platform/clipboard/ClipboardMimeTypes.h"
+#include "platform/clipboard/ClipboardUtilities.h"
namespace WebCore {
-Clipboard::Clipboard(ClipboardAccessPolicy policy, ClipboardType clipboardType)
- : m_policy(policy)
- , m_dropEffect("uninitialized")
- , m_effectAllowed("uninitialized")
- , m_dragStarted(false)
- , m_clipboardType(clipboardType)
- , m_dragImage(0)
-{
- ScriptWrappable::init(this);
-}
-
-void Clipboard::setAccessPolicy(ClipboardAccessPolicy policy)
-{
- // once you go numb, can never go back
- ASSERT(m_policy != ClipboardNumb || policy == ClipboardNumb);
- m_policy = policy;
-}
-
-bool Clipboard::canReadTypes() const
-{
- return m_policy == ClipboardReadable || m_policy == ClipboardTypesReadable || m_policy == ClipboardWritable;
-}
-
-bool Clipboard::canReadData() const
-{
- return m_policy == ClipboardReadable || m_policy == ClipboardWritable;
-}
-
-bool Clipboard::canWriteData() const
-{
- return m_policy == ClipboardWritable;
-}
-
-bool Clipboard::canSetDragImage() const
-{
- return m_policy == ClipboardImageWritable || m_policy == ClipboardWritable;
-}
-
// These "conversion" methods are called by both WebCore and WebKit, and never make sense to JS, so we don't
// worry about security for these. They don't allow access to the pasteboard anyway.
-
static DragOperation dragOpFromIEOp(const String& op)
{
// yep, it's really just this fixed set
@@ -118,6 +92,317 @@ static String IEOpFromDragOp(DragOperation op)
return "none";
}
+// We provide the IE clipboard types (URL and Text), and the clipboard types specified in the WHATWG Web Applications 1.0 draft
+// see http://www.whatwg.org/specs/web-apps/current-work/ Section 6.3.5.3
+static String normalizeType(const String& type, bool* convertToURL = 0)
+{
+ String cleanType = type.stripWhiteSpace().lower();
+ if (cleanType == mimeTypeText || cleanType.startsWith(mimeTypeTextPlainEtc))
+ return mimeTypeTextPlain;
+ if (cleanType == mimeTypeURL) {
+ if (convertToURL)
+ *convertToURL = true;
+ return mimeTypeTextURIList;
+ }
+ return cleanType;
+}
+
+PassRefPtr<Clipboard> Clipboard::create(ClipboardType type, ClipboardAccessPolicy policy, PassRefPtr<ChromiumDataObject> dataObject)
+{
+ return adoptRef(new Clipboard(type, policy , dataObject));
+}
+
+Clipboard::~Clipboard()
+{
+}
+
+void Clipboard::setDropEffect(const String &effect)
+{
+ if (!isForDragAndDrop())
+ return;
+
+ // The attribute must ignore any attempts to set it to a value other than none, copy, link, and move.
+ if (effect != "none" && effect != "copy" && effect != "link" && effect != "move")
+ return;
+
+ // FIXME: The spec actually allows this in all circumstances, even though there's no point in
+ // setting the drop effect when this condition is not true.
+ if (canReadTypes())
+ m_dropEffect = effect;
+}
+
+void Clipboard::setEffectAllowed(const String &effect)
+{
+ if (!isForDragAndDrop())
+ return;
+
+ if (dragOpFromIEOp(effect) == DragOperationPrivate) {
+ // This means that there was no conversion, and the effectAllowed that
+ // we are passed isn't a valid effectAllowed, so we should ignore it,
+ // and not set m_effectAllowed.
+
+ // The attribute must ignore any attempts to set it to a value other than
+ // none, copy, copyLink, copyMove, link, linkMove, move, all, and uninitialized.
+ return;
+ }
+
+
+ if (canWriteData())
+ m_effectAllowed = effect;
+}
+
+void Clipboard::clearData(const String& type)
+{
+ if (!canWriteData())
+ return;
+
+ if (type.isNull())
+ m_dataObject->clearAll();
+ else
+ m_dataObject->clearData(normalizeType(type));
+}
+
+String Clipboard::getData(const String& type) const
+{
+ if (!canReadData())
+ return String();
+
+ bool convertToURL = false;
+ String data = m_dataObject->getData(normalizeType(type, &convertToURL));
+ if (!convertToURL)
+ return data;
+ return convertURIListToURL(data);
+}
+
+bool Clipboard::setData(const String& type, const String& data)
+{
+ if (!canWriteData())
+ return false;
+
+ return m_dataObject->setData(normalizeType(type), data);
+}
+
+// extensions beyond IE's API
+Vector<String> Clipboard::types() const
+{
+ Vector<String> types;
+ if (!canReadTypes())
+ return types;
+
+ ListHashSet<String> typesSet = m_dataObject->types();
+ types.appendRange(typesSet.begin(), typesSet.end());
+ return types;
+}
+
+PassRefPtr<FileList> Clipboard::files() const
+{
+ RefPtr<FileList> files = FileList::create();
+ if (!canReadData())
+ return files.release();
+
+ for (size_t i = 0; i < m_dataObject->length(); ++i) {
+ if (m_dataObject->item(i)->kind() == ChromiumDataObjectItem::FileKind) {
+ RefPtr<Blob> blob = m_dataObject->item(i)->getAsFile();
+ if (blob && blob->isFile())
+ files->append(toFile(blob.get()));
+ }
+ }
+
+ return files.release();
+}
+
+void Clipboard::setDragImage(Element* image, int x, int y, ExceptionState& exceptionState)
+{
+ if (!isForDragAndDrop())
+ return;
+
+ if (!image) {
+ exceptionState.throwTypeError("setDragImage: Invalid first argument");
+ return;
+ }
+ IntPoint location(x, y);
+ if (image->hasTagName(HTMLNames::imgTag) && !image->inDocument())
+ setDragImageResource(toHTMLImageElement(image)->cachedImage(), location);
+ else
+ setDragImageElement(image, location);
+}
+
+void Clipboard::setDragImageResource(ImageResource* img, const IntPoint& loc)
+{
+ setDragImage(img, 0, loc);
+}
+
+void Clipboard::setDragImageElement(Node* node, const IntPoint& loc)
+{
+ setDragImage(0, node, loc);
+}
+
+PassOwnPtr<DragImage> Clipboard::createDragImage(IntPoint& loc, Frame* frame) const
+{
+ if (m_dragImageElement) {
+ loc = m_dragLoc;
+ return frame->nodeImage(m_dragImageElement.get());
+ }
+ if (m_dragImage) {
+ loc = m_dragLoc;
+ return DragImage::create(m_dragImage->image());
+ }
+ return nullptr;
+}
+
+static ImageResource* getImageResource(Element* element)
+{
+ // Attempt to pull ImageResource from element
+ ASSERT(element);
+ RenderObject* renderer = element->renderer();
+ if (!renderer || !renderer->isImage())
+ return 0;
+
+ RenderImage* image = toRenderImage(renderer);
+ if (image->cachedImage() && !image->cachedImage()->errorOccurred())
+ return image->cachedImage();
+
+ return 0;
+}
+
+static void writeImageToDataObject(ChromiumDataObject* dataObject, Element* element, const KURL& url)
+{
+ // Shove image data into a DataObject for use as a file
+ ImageResource* cachedImage = getImageResource(element);
+ if (!cachedImage || !cachedImage->imageForRenderer(element->renderer()) || !cachedImage->isLoaded())
+ return;
+
+ SharedBuffer* imageBuffer = cachedImage->imageForRenderer(element->renderer())->data();
+ if (!imageBuffer || !imageBuffer->size())
+ return;
+
+ String imageExtension = cachedImage->image()->filenameExtension();
+ ASSERT(!imageExtension.isEmpty());
+
+ // Determine the filename for the file contents of the image.
+ String filename = cachedImage->response().suggestedFilename();
+ if (filename.isEmpty())
+ filename = url.lastPathComponent();
+
+ String fileExtension;
+ if (filename.isEmpty()) {
+ filename = element->getAttribute(HTMLNames::altAttr);
+ } else {
+ // Strip any existing extension. Assume that alt text is usually not a filename.
+ int extensionIndex = filename.reverseFind('.');
+ if (extensionIndex != -1) {
+ fileExtension = filename.substring(extensionIndex + 1);
+ filename.truncate(extensionIndex);
+ }
+ }
+
+ if (!fileExtension.isEmpty() && fileExtension != imageExtension) {
+ String imageMimeType = MIMETypeRegistry::getMIMETypeForExtension(imageExtension);
+ ASSERT(imageMimeType.startsWith("image/"));
+ // Use the file extension only if it has imageMimeType: it's untrustworthy otherwise.
+ if (imageMimeType == MIMETypeRegistry::getMIMETypeForExtension(fileExtension))
+ imageExtension = fileExtension;
+ }
+
+ imageExtension = "." + imageExtension;
+ validateFilename(filename, imageExtension);
+
+ dataObject->addSharedBuffer(filename + imageExtension, imageBuffer);
+}
+
+void Clipboard::declareAndWriteDragImage(Element* element, const KURL& url, const String& title)
+{
+ if (!m_dataObject)
+ return;
+
+ m_dataObject->setURLAndTitle(url, title);
+
+ // Write the bytes in the image to the file format.
+ writeImageToDataObject(m_dataObject.get(), element, url);
+
+ // Put img tag on the clipboard referencing the image
+ m_dataObject->setData(mimeTypeTextHTML, createMarkup(element, IncludeNode, 0, ResolveAllURLs));
+}
+
+void Clipboard::writeURL(const KURL& url, const String& title)
+{
+ if (!m_dataObject)
+ return;
+ ASSERT(!url.isEmpty());
+
+ m_dataObject->setURLAndTitle(url, title);
+
+ // The URL can also be used as plain text.
+ m_dataObject->setData(mimeTypeTextPlain, url.string());
+
+ // The URL can also be used as an HTML fragment.
+ m_dataObject->setHTMLAndBaseURL(urlToMarkup(url, title), url);
+}
+
+void Clipboard::writeRange(Range* selectedRange, Frame* frame)
+{
+ ASSERT(selectedRange);
+ if (!m_dataObject)
+ return;
+
+ m_dataObject->setHTMLAndBaseURL(createMarkup(selectedRange, 0, AnnotateForInterchange, false, ResolveNonLocalURLs), frame->document()->url());
+
+ String str = frame->selectedTextForClipboard();
+#if OS(WIN)
+ replaceNewlinesWithWindowsStyleNewlines(str);
+#endif
+ replaceNBSPWithSpace(str);
+ m_dataObject->setData(mimeTypeTextPlain, str);
+}
+
+void Clipboard::writePlainText(const String& text)
+{
+ if (!m_dataObject)
+ return;
+
+ String str = text;
+#if OS(WIN)
+ replaceNewlinesWithWindowsStyleNewlines(str);
+#endif
+ replaceNBSPWithSpace(str);
+
+ m_dataObject->setData(mimeTypeTextPlain, str);
+}
+
+bool Clipboard::hasData()
+{
+ ASSERT(isForDragAndDrop());
+
+ return m_dataObject->length() > 0;
+}
+
+void Clipboard::setAccessPolicy(ClipboardAccessPolicy policy)
+{
+ // once you go numb, can never go back
+ ASSERT(m_policy != ClipboardNumb || policy == ClipboardNumb);
+ m_policy = policy;
+}
+
+bool Clipboard::canReadTypes() const
+{
+ return m_policy == ClipboardReadable || m_policy == ClipboardTypesReadable || m_policy == ClipboardWritable;
+}
+
+bool Clipboard::canReadData() const
+{
+ return m_policy == ClipboardReadable || m_policy == ClipboardWritable;
+}
+
+bool Clipboard::canWriteData() const
+{
+ return m_policy == ClipboardWritable;
+}
+
+bool Clipboard::canSetDragImage() const
+{
+ return m_policy == ClipboardImageWritable || m_policy == ClipboardWritable;
+}
+
DragOperation Clipboard::sourceOperation() const
{
DragOperation op = dragOpFromIEOp(m_effectAllowed);
@@ -144,63 +429,72 @@ void Clipboard::setDestinationOperation(DragOperation op)
m_dropEffect = IEOpFromDragOp(op);
}
-bool Clipboard::hasFileOfType(const String& type) const
+bool Clipboard::hasDropZoneType(const String& keyword)
{
- if (!canReadTypes())
- return false;
+ if (keyword.startsWith("file:"))
+ return hasFileOfType(keyword.substring(5));
- RefPtr<FileList> fileList = files();
- if (fileList->isEmpty())
- return false;
+ if (keyword.startsWith("string:"))
+ return hasStringOfType(keyword.substring(7));
- for (unsigned int f = 0; f < fileList->length(); f++) {
- if (equalIgnoringCase(fileList->item(f)->type(), type))
- return true;
- }
return false;
}
-bool Clipboard::hasStringOfType(const String& type) const
+PassRefPtr<DataTransferItemList> Clipboard::items()
{
- if (!canReadTypes())
- return false;
+ // FIXME: According to the spec, we are supposed to return the same collection of items each
+ // time. We now return a wrapper that always wraps the *same* set of items, so JS shouldn't be
+ // able to tell, but we probably still want to fix this.
+ return DataTransferItemList::create(this, m_dataObject);
+}
- return types().contains(type);
+PassRefPtr<ChromiumDataObject> Clipboard::dataObject() const
+{
+ return m_dataObject;
}
-void Clipboard::setDropEffect(const String &effect)
+Clipboard::Clipboard(ClipboardType type, ClipboardAccessPolicy policy, PassRefPtr<ChromiumDataObject> dataObject)
+ : m_policy(policy)
+ , m_dropEffect("uninitialized")
+ , m_effectAllowed("uninitialized")
+ , m_clipboardType(type)
+ , m_dataObject(dataObject)
{
- if (!isForDragAndDrop())
- return;
+ ScriptWrappable::init(this);
+}
- // The attribute must ignore any attempts to set it to a value other than none, copy, link, and move.
- if (effect != "none" && effect != "copy" && effect != "link" && effect != "move")
+void Clipboard::setDragImage(ImageResource* image, Node* node, const IntPoint& loc)
+{
+ if (!canSetDragImage())
return;
- // FIXME: The spec actually allows this in all circumstances, even though there's no point in
- // setting the drop effect when this condition is not true.
- if (canReadTypes())
- m_dropEffect = effect;
+ m_dragImage = image;
+ m_dragLoc = loc;
+ m_dragImageElement = node;
}
-void Clipboard::setEffectAllowed(const String &effect)
+bool Clipboard::hasFileOfType(const String& type) const
{
- if (!isForDragAndDrop())
- return;
+ if (!canReadTypes())
+ return false;
- if (dragOpFromIEOp(effect) == DragOperationPrivate) {
- // This means that there was no conversion, and the effectAllowed that
- // we are passed isn't a valid effectAllowed, so we should ignore it,
- // and not set m_effectAllowed.
+ RefPtr<FileList> fileList = files();
+ if (fileList->isEmpty())
+ return false;
- // The attribute must ignore any attempts to set it to a value other than
- // none, copy, copyLink, copyMove, link, linkMove, move, all, and uninitialized.
- return;
+ for (unsigned f = 0; f < fileList->length(); f++) {
+ if (equalIgnoringCase(fileList->item(f)->type(), type))
+ return true;
}
+ return false;
+}
+bool Clipboard::hasStringOfType(const String& type) const
+{
+ if (!canReadTypes())
+ return false;
- if (canWriteData())
- m_effectAllowed = effect;
+ return types().contains(type);
}
DragOperation convertDropZoneOperationToDragOperation(const String& dragOperation)
@@ -228,15 +522,4 @@ String convertDragOperationToDropZoneOperation(DragOperation operation)
}
}
-bool Clipboard::hasDropZoneType(const String& keyword)
-{
- if (keyword.startsWith("file:"))
- return hasFileOfType(keyword.substring(5));
-
- if (keyword.startsWith("string:"))
- return hasStringOfType(keyword.substring(7));
-
- return false;
-}
-
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/Clipboard.h b/chromium/third_party/WebKit/Source/core/dom/Clipboard.h
index bc861ded2e0..dfe22710e76 100644
--- a/chromium/third_party/WebKit/Source/core/dom/Clipboard.h
+++ b/chromium/third_party/WebKit/Source/core/dom/Clipboard.h
@@ -26,21 +26,25 @@
#include "bindings/v8/ScriptWrappable.h"
#include "core/dom/ClipboardAccessPolicy.h"
-#include "core/dom/Node.h"
#include "core/fetch/ResourcePtr.h"
#include "core/page/DragActions.h"
-#include "core/platform/DragImage.h"
-#include "core/platform/graphics/IntPoint.h"
+#include "platform/geometry/IntPoint.h"
#include "wtf/Forward.h"
+#include "wtf/RefCounted.h"
+#include "wtf/RefPtr.h"
+#include "wtf/Vector.h"
namespace WebCore {
-class ImageResource;
+class ChromiumDataObject;
class DataTransferItemList;
-class DragData;
class DragImage;
+class Element;
+class ExceptionState;
class FileList;
class Frame;
+class ImageResource;
+class Node;
class Range;
// State available during IE's events for drag and drop and copy/paste
@@ -52,9 +56,8 @@ public:
DragAndDrop,
};
- static PassRefPtr<Clipboard> create(ClipboardAccessPolicy, DragData*, Frame*);
-
- virtual ~Clipboard() { }
+ static PassRefPtr<Clipboard> create(ClipboardType, ClipboardAccessPolicy, PassRefPtr<ChromiumDataObject>);
+ ~Clipboard();
bool isForCopyAndPaste() const { return m_clipboardType == CopyAndPaste; }
bool isForDragAndDrop() const { return m_clipboardType == DragAndDrop; }
@@ -65,28 +68,28 @@ public:
String effectAllowed() const { return m_effectAllowed; }
void setEffectAllowed(const String&);
- virtual void clearData(const String& type) = 0;
- virtual void clearAllData() = 0;
- virtual String getData(const String& type) const = 0;
- virtual bool setData(const String& type, const String& data) = 0;
+ void clearData(const String& type = String());
+ String getData(const String& type) const;
+ bool setData(const String& type, const String& data);
// extensions beyond IE's API
- virtual ListHashSet<String> types() const = 0;
- virtual PassRefPtr<FileList> files() const = 0;
+ Vector<String> types() const;
+ PassRefPtr<FileList> files() const;
IntPoint dragLocation() const { return m_dragLoc; }
- ImageResource* dragImage() const { return m_dragImage.get(); }
- virtual void setDragImage(ImageResource*, const IntPoint&) = 0;
+ void setDragImage(Element*, int x, int y, ExceptionState&);
+ ImageResource* dragImageResource() const { return m_dragImage.get(); }
+ void setDragImageResource(ImageResource*, const IntPoint&);
Node* dragImageElement() const { return m_dragImageElement.get(); }
- virtual void setDragImageElement(Node*, const IntPoint&) = 0;
+ void setDragImageElement(Node*, const IntPoint&);
- virtual PassOwnPtr<DragImage> createDragImage(IntPoint& dragLocation) const = 0;
- virtual void declareAndWriteDragImage(Element*, const KURL&, const String& title, Frame*) = 0;
- virtual void writeURL(const KURL&, const String&, Frame*) = 0;
- virtual void writeRange(Range*, Frame*) = 0;
- virtual void writePlainText(const String&) = 0;
+ PassOwnPtr<DragImage> createDragImage(IntPoint& dragLocation, Frame*) const;
+ void declareAndWriteDragImage(Element*, const KURL&, const String& title);
+ void writeURL(const KURL&, const String&);
+ void writeRange(Range*, Frame*);
+ void writePlainText(const String&);
- virtual bool hasData() = 0;
+ bool hasData();
void setAccessPolicy(ClipboardAccessPolicy);
bool canReadTypes() const;
@@ -105,16 +108,15 @@ public:
bool hasDropZoneType(const String&);
- void setDragHasStarted() { m_dragStarted = true; }
+ PassRefPtr<DataTransferItemList> items();
- virtual PassRefPtr<DataTransferItemList> items() = 0;
+ PassRefPtr<ChromiumDataObject> dataObject() const;
-protected:
- Clipboard(ClipboardAccessPolicy, ClipboardType);
+private:
+ Clipboard(ClipboardType, ClipboardAccessPolicy, PassRefPtr<ChromiumDataObject>);
- bool dragStarted() const { return m_dragStarted; }
+ void setDragImage(ImageResource*, Node*, const IntPoint&);
-private:
bool hasFileOfType(const String&) const;
bool hasStringOfType(const String&) const;
@@ -122,10 +124,9 @@ private:
ClipboardAccessPolicy m_policy;
String m_dropEffect;
String m_effectAllowed;
- bool m_dragStarted;
ClipboardType m_clipboardType;
+ RefPtr<ChromiumDataObject> m_dataObject;
-protected:
IntPoint m_dragLoc;
ResourcePtr<ImageResource> m_dragImage;
RefPtr<Node> m_dragImageElement;
diff --git a/chromium/third_party/WebKit/Source/core/dom/Clipboard.idl b/chromium/third_party/WebKit/Source/core/dom/Clipboard.idl
index 82453c70fd7..695f70d4866 100644
--- a/chromium/third_party/WebKit/Source/core/dom/Clipboard.idl
+++ b/chromium/third_party/WebKit/Source/core/dom/Clipboard.idl
@@ -30,13 +30,13 @@
] interface Clipboard {
[TreatReturnedNullStringAs=Undefined] attribute DOMString dropEffect;
[TreatReturnedNullStringAs=Undefined] attribute DOMString effectAllowed;
- [CustomGetter] readonly attribute Array types;
+ readonly attribute DOMString[] types;
readonly attribute FileList files;
- [Custom, RaisesException] void clearData(optional DOMString type);
+ void clearData(optional DOMString type);
DOMString getData(DOMString type);
boolean setData(DOMString type, DOMString data);
- [Custom, RaisesException] void setDragImage(HTMLImageElement image, long x, long y);
+ [RaisesException] void setDragImage(Element image, long x, long y);
readonly attribute DataTransferItemList items;
};
diff --git a/chromium/third_party/WebKit/Source/core/dom/ClipboardEvent.cpp b/chromium/third_party/WebKit/Source/core/dom/ClipboardEvent.cpp
deleted file mode 100644
index bda69f20101..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/ClipboardEvent.cpp
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Copyright (C) 2001 Peter Kelly (pmk@post.com)
- * Copyright (C) 2001 Tobias Anton (anton@stud.fbi.fh-darmstadt.de)
- * Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
- * Copyright (C) 2003, 2005, 2006, 2008 Apple Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-#include "core/dom/ClipboardEvent.h"
-
-#include "core/dom/Clipboard.h"
-#include "core/dom/EventNames.h"
-
-namespace WebCore {
-
-ClipboardEvent::ClipboardEvent()
-{
-}
-
-ClipboardEvent::ClipboardEvent(const AtomicString& eventType, bool canBubble, bool cancelable, PassRefPtr<Clipboard> clipboard)
- : Event(eventType, canBubble, cancelable), m_clipboard(clipboard)
-{
-}
-
-ClipboardEvent::~ClipboardEvent()
-{
-}
-
-const AtomicString& ClipboardEvent::interfaceName() const
-{
- // Notice that there is no ClipboardEvent.idl.
- return eventNames().interfaceForEvent;
-}
-
-bool ClipboardEvent::isClipboardEvent() const
-{
- return true;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/ClipboardEvent.h b/chromium/third_party/WebKit/Source/core/dom/ClipboardEvent.h
deleted file mode 100644
index 87bd13d2db1..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/ClipboardEvent.h
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * Copyright (C) 2001 Peter Kelly (pmk@post.com)
- * Copyright (C) 2001 Tobias Anton (anton@stud.fbi.fh-darmstadt.de)
- * Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
- * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#ifndef ClipboardEvent_h
-#define ClipboardEvent_h
-
-#include "core/dom/Event.h"
-
-namespace WebCore {
-
- class Clipboard;
-
- class ClipboardEvent : public Event {
- public:
- virtual ~ClipboardEvent();
-
- static PassRefPtr<ClipboardEvent> create()
- {
- return adoptRef(new ClipboardEvent);
- }
- static PassRefPtr<ClipboardEvent> create(const AtomicString& type, bool canBubbleArg, bool cancelableArg, PassRefPtr<Clipboard> clipboardArg)
- {
- return adoptRef(new ClipboardEvent(type, canBubbleArg, cancelableArg, clipboardArg));
- }
-
- Clipboard* clipboard() const { return m_clipboard.get(); }
-
- private:
- ClipboardEvent();
- ClipboardEvent(const AtomicString& type, bool canBubbleArg, bool cancelableArg, PassRefPtr<Clipboard>);
-
- virtual const AtomicString& interfaceName() const OVERRIDE;
- virtual bool isClipboardEvent() const OVERRIDE;
-
- RefPtr<Clipboard> m_clipboard;
- };
-
-} // namespace WebCore
-
-#endif // ClipboardEvent_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/Comment.cpp b/chromium/third_party/WebKit/Source/core/dom/Comment.cpp
index 186008aeceb..90fb91b2ab8 100644
--- a/chromium/third_party/WebKit/Source/core/dom/Comment.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/Comment.cpp
@@ -39,7 +39,7 @@ PassRefPtr<Comment> Comment::create(Document& document, const String& text)
String Comment::nodeName() const
{
- return commentAtom.string();
+ return "#comment";
}
Node::NodeType Comment::nodeType() const
diff --git a/chromium/third_party/WebKit/Source/core/dom/Comment.h b/chromium/third_party/WebKit/Source/core/dom/Comment.h
index 6b4a449cca4..b0625f4be12 100644
--- a/chromium/third_party/WebKit/Source/core/dom/Comment.h
+++ b/chromium/third_party/WebKit/Source/core/dom/Comment.h
@@ -27,7 +27,7 @@
namespace WebCore {
-class ScriptExecutionContext;
+class ExecutionContext;
class Comment FINAL : public CharacterData {
public:
@@ -42,17 +42,7 @@ private:
virtual bool childTypeAllowed(NodeType) const;
};
-inline Comment* toComment(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->nodeType() == Node::COMMENT_NODE);
- return static_cast<Comment*>(node);
-}
-
-inline const Comment* toComment(const Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->nodeType() == Node::COMMENT_NODE);
- return static_cast<const Comment*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(Comment, nodeType() == Node::COMMENT_NODE);
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/Comment.idl b/chromium/third_party/WebKit/Source/core/dom/Comment.idl
index 0503d63153b..0297e953064 100644
--- a/chromium/third_party/WebKit/Source/core/dom/Comment.idl
+++ b/chromium/third_party/WebKit/Source/core/dom/Comment.idl
@@ -19,7 +19,7 @@
[
Constructor([Default=NullString] optional DOMString data),
- ConstructorCallWith=Document
+ ConstructorCallWith=Document,
] interface Comment : CharacterData {
};
diff --git a/chromium/third_party/WebKit/Source/core/dom/CompositionEvent.cpp b/chromium/third_party/WebKit/Source/core/dom/CompositionEvent.cpp
deleted file mode 100644
index 45c61c070b9..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/CompositionEvent.cpp
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * Copyright (C) 2009 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-#include "config.h"
-#include "core/dom/CompositionEvent.h"
-
-#include "core/dom/EventNames.h"
-
-namespace WebCore {
-
-CompositionEventInit::CompositionEventInit()
-{
-}
-
-CompositionEvent::CompositionEvent()
-{
- ScriptWrappable::init(this);
-}
-
-CompositionEvent::CompositionEvent(const AtomicString& type, PassRefPtr<AbstractView> view, const String& data)
- : UIEvent(type, true, true, view, 0)
- , m_data(data)
-{
- ScriptWrappable::init(this);
-}
-
-CompositionEvent::CompositionEvent(const AtomicString& type, const CompositionEventInit& initializer)
- : UIEvent(type, initializer)
- , m_data(initializer.data)
-{
- ScriptWrappable::init(this);
-}
-
-CompositionEvent::~CompositionEvent()
-{
-}
-
-void CompositionEvent::initCompositionEvent(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<AbstractView> view, const String& data)
-{
- if (dispatched())
- return;
-
- initUIEvent(type, canBubble, cancelable, view, 0);
-
- m_data = data;
-}
-
-const AtomicString& CompositionEvent::interfaceName() const
-{
- return eventNames().interfaceForCompositionEvent;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/CompositionEvent.h b/chromium/third_party/WebKit/Source/core/dom/CompositionEvent.h
deleted file mode 100644
index cf39f9b188c..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/CompositionEvent.h
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * Copyright (C) 2009 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-#ifndef CompositionEvent_h
-#define CompositionEvent_h
-
-#include "core/dom/UIEvent.h"
-
-namespace WebCore {
-
-struct CompositionEventInit : UIEventInit {
- CompositionEventInit();
-
- String data;
-};
-
-class CompositionEvent : public UIEvent {
-public:
- static PassRefPtr<CompositionEvent> create()
- {
- return adoptRef(new CompositionEvent);
- }
-
- static PassRefPtr<CompositionEvent> create(const AtomicString& type, PassRefPtr<AbstractView> view, const String& data)
- {
- return adoptRef(new CompositionEvent(type, view, data));
- }
-
- static PassRefPtr<CompositionEvent> create(const AtomicString& type, const CompositionEventInit& initializer)
- {
- return adoptRef(new CompositionEvent(type, initializer));
- }
-
- virtual ~CompositionEvent();
-
- void initCompositionEvent(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<AbstractView>, const String& data);
-
- String data() const { return m_data; }
-
- virtual const AtomicString& interfaceName() const;
-
-private:
- CompositionEvent();
- CompositionEvent(const AtomicString& type, PassRefPtr<AbstractView>, const String&);
- CompositionEvent(const AtomicString& type, const CompositionEventInit&);
-
- String m_data;
-};
-
-} // namespace WebCore
-
-#endif // CompositionEvent_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/CompositionEvent.idl b/chromium/third_party/WebKit/Source/core/dom/CompositionEvent.idl
deleted file mode 100644
index c54d50f48bc..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/CompositionEvent.idl
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright (C) 2009 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-[
- ConstructorTemplate=Event
-] interface CompositionEvent : UIEvent {
-
- [InitializedByEventConstructor] readonly attribute DOMString data;
-
- void initCompositionEvent([Default=Undefined] optional DOMString typeArg,
- [Default=Undefined] optional boolean canBubbleArg,
- [Default=Undefined] optional boolean cancelableArg,
- [Default=Undefined] optional Window viewArg,
- [Default=Undefined] optional DOMString dataArg);
-
-};
-
diff --git a/chromium/third_party/WebKit/Source/core/dom/ContainerNode.cpp b/chromium/third_party/WebKit/Source/core/dom/ContainerNode.cpp
index d65d85dcfe2..ba1ac83c663 100644
--- a/chromium/third_party/WebKit/Source/core/dom/ContainerNode.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/ContainerNode.cpp
@@ -24,33 +24,30 @@
#include "core/dom/ContainerNode.h"
#include "bindings/v8/ExceptionState.h"
-#include "bindings/v8/ExceptionStatePlaceholder.h"
#include "core/dom/ChildListMutationScope.h"
#include "core/dom/ContainerNodeAlgorithms.h"
#include "core/dom/ElementTraversal.h"
-#include "core/dom/EventNames.h"
#include "core/dom/ExceptionCode.h"
#include "core/dom/FullscreenElementStack.h"
-#include "core/dom/MutationEvent.h"
#include "core/dom/NodeChildRemovalTracker.h"
#include "core/dom/NodeRareData.h"
#include "core/dom/NodeRenderStyle.h"
#include "core/dom/NodeTraversal.h"
+#include "core/events/MutationEvent.h"
+#include "core/events/ThreadLocalEventNames.h"
#include "core/html/HTMLCollection.h"
#include "core/rendering/InlineTextBox.h"
#include "core/rendering/RenderText.h"
#include "core/rendering/RenderTheme.h"
#include "core/rendering/RenderView.h"
#include "core/rendering/RenderWidget.h"
-#include "wtf/Vector.h"
using namespace std;
namespace WebCore {
-static void dispatchChildInsertionEvents(Node*);
-static void dispatchChildRemovalEvents(Node*);
-static void updateTreeAfterInsertion(ContainerNode*, Node*);
+static void dispatchChildInsertionEvents(Node&);
+static void dispatchChildRemovalEvents(Node&);
ChildNodesLazySnapshot* ChildNodesLazySnapshot::latestSnapshot = 0;
@@ -58,16 +55,16 @@ ChildNodesLazySnapshot* ChildNodesLazySnapshot::latestSnapshot = 0;
unsigned NoEventDispatchAssertion::s_count = 0;
#endif
-static void collectChildrenAndRemoveFromOldParent(Node* node, NodeVector& nodes, ExceptionState& es)
+static void collectChildrenAndRemoveFromOldParent(Node& node, NodeVector& nodes, ExceptionState& exceptionState)
{
- if (node->nodeType() != Node::DOCUMENT_FRAGMENT_NODE) {
- nodes.append(node);
- if (ContainerNode* oldParent = node->parentNode())
- oldParent->removeChild(node, es);
+ if (!node.isDocumentFragment()) {
+ nodes.append(&node);
+ if (ContainerNode* oldParent = node.parentNode())
+ oldParent->removeChild(&node, exceptionState);
return;
}
getChildNodes(node, nodes);
- toContainerNode(node)->removeChildren();
+ toContainerNode(node).removeChildren();
}
void ContainerNode::removeDetachedChildren()
@@ -76,85 +73,57 @@ void ContainerNode::removeDetachedChildren()
for (Node* child = firstChild(); child; child = child->nextSibling())
child->updateAncestorConnectedSubframeCountForRemoval();
}
- // FIXME: We should be able to ASSERT(!attached()) here: https://bugs.webkit.org/show_bug.cgi?id=107801
- removeDetachedChildrenInContainer<Node, ContainerNode>(this);
+ ASSERT(needsAttach());
+ removeDetachedChildrenInContainer<Node, ContainerNode>(*this);
}
-void ContainerNode::takeAllChildrenFrom(ContainerNode* oldParent)
+void ContainerNode::parserTakeAllChildrenFrom(ContainerNode& oldParent)
{
- NodeVector children;
- getChildNodes(oldParent, children);
-
- if (oldParent->document().hasMutationObserversOfType(MutationObserver::ChildList)) {
- ChildListMutationScope mutation(oldParent);
- for (unsigned i = 0; i < children.size(); ++i)
- mutation.willRemoveChild(children[i].get());
- }
-
- // FIXME: We need to do notifyMutationObserversNodeWillDetach() for each child,
- // probably inside removeDetachedChildrenInContainer.
-
- oldParent->removeDetachedChildren();
-
- for (unsigned i = 0; i < children.size(); ++i) {
- if (children[i]->attached())
- children[i]->detach();
- // FIXME: We need a no mutation event version of adoptNode.
- RefPtr<Node> child = document().adoptNode(children[i].release(), ASSERT_NO_EXCEPTION);
- // FIXME: Together with adoptNode above, the tree scope might get updated recursively twice
- // (if the document changed or oldParent was in a shadow tree, AND *this is in a shadow tree).
- // Can we do better?
- treeScope().adoptIfNeeded(child.get());
+ while (RefPtr<Node> child = oldParent.firstChild()) {
+ oldParent.parserRemoveChild(*child);
+ treeScope().adoptIfNeeded(*child);
parserAppendChild(child.get());
}
}
ContainerNode::~ContainerNode()
{
- if (Document* document = documentInternal())
- willBeDeletedFrom(document);
+ willBeDeletedFromDocument();
removeDetachedChildren();
}
-static inline bool isChildTypeAllowed(ContainerNode* newParent, Node* child)
+bool ContainerNode::isChildTypeAllowed(const Node& child) const
{
- if (!child->isDocumentFragment())
- return newParent->childTypeAllowed(child->nodeType());
+ if (!child.isDocumentFragment())
+ return childTypeAllowed(child.nodeType());
- for (Node* node = child->firstChild(); node; node = node->nextSibling()) {
- if (!newParent->childTypeAllowed(node->nodeType()))
+ for (Node* node = child.firstChild(); node; node = node->nextSibling()) {
+ if (!childTypeAllowed(node->nodeType()))
return false;
}
return true;
}
-static inline bool isInTemplateContent(const Node* node)
+bool ContainerNode::containsConsideringHostElements(const Node& newChild) const
{
- Document& document = node->document();
- return &document == document.templateDocument();
+ if (isInShadowTree() || document() == document().templateDocument())
+ return newChild.containsIncludingHostElements(*this);
+ return newChild.contains(this);
}
-static inline bool containsConsideringHostElements(const Node* newChild, const Node* newParent)
-{
- return (newParent->isInShadowTree() || isInTemplateContent(newParent))
- ? newChild->containsIncludingHostElements(newParent)
- : newChild->contains(newParent);
-}
-
-static inline bool checkAcceptChild(ContainerNode* newParent, Node* newChild, Node* oldChild, ExceptionState& es)
+bool ContainerNode::checkAcceptChild(const Node* newChild, const Node* oldChild, ExceptionState& exceptionState) const
{
// Not mentioned in spec: throw NotFoundError if newChild is null
if (!newChild) {
- es.throwDOMException(NotFoundError);
+ exceptionState.throwDOMException(NotFoundError, "The new child element is null.");
return false;
}
// Use common case fast path if possible.
- if ((newChild->isElementNode() || newChild->isTextNode()) && newParent->isElementNode()) {
- ASSERT(!newParent->isDocumentTypeNode());
- ASSERT(isChildTypeAllowed(newParent, newChild));
- if (containsConsideringHostElements(newChild, newParent)) {
- es.throwDOMException(HierarchyRequestError);
+ if ((newChild->isElementNode() || newChild->isTextNode()) && isElementNode()) {
+ ASSERT(isChildTypeAllowed(*newChild));
+ if (containsConsideringHostElements(*newChild)) {
+ exceptionState.throwDOMException(HierarchyRequestError, "The new child element contains the parent.");
return false;
}
return true;
@@ -163,51 +132,40 @@ static inline bool checkAcceptChild(ContainerNode* newParent, Node* newChild, No
// This should never happen, but also protect release builds from tree corruption.
ASSERT(!newChild->isPseudoElement());
if (newChild->isPseudoElement()) {
- es.throwDOMException(HierarchyRequestError);
+ exceptionState.throwDOMException(HierarchyRequestError, "The new child element is a pseudo-element.");
return false;
}
- if (containsConsideringHostElements(newChild, newParent)) {
- es.throwDOMException(HierarchyRequestError);
+ if (containsConsideringHostElements(*newChild)) {
+ exceptionState.throwDOMException(HierarchyRequestError, "The new child element contains the parent.");
return false;
}
- if (oldChild && newParent->isDocumentNode()) {
- if (!toDocument(newParent)->canReplaceChild(newChild, oldChild)) {
- es.throwDOMException(HierarchyRequestError);
+ if (oldChild && isDocumentNode()) {
+ if (!toDocument(this)->canReplaceChild(*newChild, *oldChild)) {
+ // FIXME: Adjust 'Document::canReplaceChild' to return some additional detail (or an error message).
+ exceptionState.throwDOMException(HierarchyRequestError, "Failed to replace child.");
return false;
}
- } else if (!isChildTypeAllowed(newParent, newChild)) {
- es.throwDOMException(HierarchyRequestError);
+ } else if (!isChildTypeAllowed(*newChild)) {
+ exceptionState.throwDOMException(HierarchyRequestError, "Nodes of type '" + newChild->nodeName() + "' may not be inserted inside nodes of type '" + nodeName() + "'.");
return false;
}
return true;
}
-static inline bool checkAcceptChildGuaranteedNodeTypes(ContainerNode* newParent, Node* newChild, ExceptionState& es)
+bool ContainerNode::checkAcceptChildGuaranteedNodeTypes(const Node& newChild, ExceptionState& exceptionState) const
{
- ASSERT(!newParent->isDocumentTypeNode());
- ASSERT(isChildTypeAllowed(newParent, newChild));
- if (newChild->contains(newParent)) {
- es.throwDOMException(HierarchyRequestError);
+ ASSERT(isChildTypeAllowed(newChild));
+ if (newChild.contains(this)) {
+ exceptionState.throwDOMException(HierarchyRequestError, "The new child element contains the parent.");
return false;
}
-
return true;
}
-static inline bool checkAddChild(ContainerNode* newParent, Node* newChild, ExceptionState& es)
-{
- return checkAcceptChild(newParent, newChild, 0, es);
-}
-
-static inline bool checkReplaceChild(ContainerNode* newParent, Node* newChild, Node* oldChild, ExceptionState& es)
-{
- return checkAcceptChild(newParent, newChild, oldChild, es);
-}
-
-void ContainerNode::insertBefore(PassRefPtr<Node> newChild, Node* refChild, ExceptionState& es)
+void ContainerNode::insertBefore(PassRefPtr<Node> newChild, Node* refChild, ExceptionState& exceptionState)
{
// Check that this node is not "floating".
// If it is, it can be deleted as a side effect of sending mutation events.
@@ -217,17 +175,18 @@ void ContainerNode::insertBefore(PassRefPtr<Node> newChild, Node* refChild, Exce
// insertBefore(node, 0) is equivalent to appendChild(node)
if (!refChild) {
- appendChild(newChild, es);
+ appendChild(newChild, exceptionState);
return;
}
// Make sure adding the new child is OK.
- if (!checkAddChild(this, newChild.get(), es))
+ if (!checkAcceptChild(newChild.get(), 0, exceptionState))
return;
+ ASSERT(newChild);
// NotFoundError: Raised if refChild is not a child of this node
if (refChild->parentNode() != this) {
- es.throwDOMException(NotFoundError);
+ exceptionState.throwDOMException(NotFoundError, "The node before which the new node is to be inserted is not a child of this node.");
return;
}
@@ -237,21 +196,22 @@ void ContainerNode::insertBefore(PassRefPtr<Node> newChild, Node* refChild, Exce
RefPtr<Node> next = refChild;
NodeVector targets;
- collectChildrenAndRemoveFromOldParent(newChild.get(), targets, es);
- if (es.hadException())
+ collectChildrenAndRemoveFromOldParent(*newChild, targets, exceptionState);
+ if (exceptionState.hadException())
return;
if (targets.isEmpty())
return;
// We need this extra check because collectChildrenAndRemoveFromOldParent() can fire mutation events.
- if (!checkAcceptChildGuaranteedNodeTypes(this, newChild.get(), es))
+ if (!checkAcceptChildGuaranteedNodeTypes(*newChild, exceptionState))
return;
- InspectorInstrumentation::willInsertDOMNode(&document(), this);
+ InspectorInstrumentation::willInsertDOMNode(this);
- ChildListMutationScope mutation(this);
+ ChildListMutationScope mutation(*this);
for (NodeVector::const_iterator it = targets.begin(); it != targets.end(); ++it) {
- Node* child = it->get();
+ ASSERT(*it);
+ Node& child = **it;
// Due to arbitrary code running in response to a DOM mutation event it's
// possible that "next" is no longer a child of "this".
@@ -259,71 +219,69 @@ void ContainerNode::insertBefore(PassRefPtr<Node> newChild, Node* refChild, Exce
// In either of those cases, we'll just stop.
if (next->parentNode() != this)
break;
- if (child->parentNode())
+ if (child.parentNode())
break;
treeScope().adoptIfNeeded(child);
- insertBeforeCommon(next.get(), child);
+ insertBeforeCommon(*next, child);
- updateTreeAfterInsertion(this, child);
+ updateTreeAfterInsertion(child);
}
dispatchSubtreeModifiedEvent();
}
-void ContainerNode::insertBeforeCommon(Node* nextChild, Node* newChild)
+void ContainerNode::insertBeforeCommon(Node& nextChild, Node& newChild)
{
NoEventDispatchAssertion assertNoEventDispatch;
- ASSERT(newChild);
- ASSERT(!newChild->parentNode()); // Use insertBefore if you need to handle reparenting (and want DOM mutation events).
- ASSERT(!newChild->nextSibling());
- ASSERT(!newChild->previousSibling());
- ASSERT(!newChild->isShadowRoot());
+ ASSERT(!newChild.parentNode()); // Use insertBefore if you need to handle reparenting (and want DOM mutation events).
+ ASSERT(!newChild.nextSibling());
+ ASSERT(!newChild.previousSibling());
+ ASSERT(!newChild.isShadowRoot());
- Node* prev = nextChild->previousSibling();
+ Node* prev = nextChild.previousSibling();
ASSERT(m_lastChild != prev);
- nextChild->setPreviousSibling(newChild);
+ nextChild.setPreviousSibling(&newChild);
if (prev) {
ASSERT(m_firstChild != nextChild);
ASSERT(prev->nextSibling() == nextChild);
- prev->setNextSibling(newChild);
+ prev->setNextSibling(&newChild);
} else {
ASSERT(m_firstChild == nextChild);
- m_firstChild = newChild;
+ m_firstChild = &newChild;
}
- newChild->setParentOrShadowHostNode(this);
- newChild->setPreviousSibling(prev);
- newChild->setNextSibling(nextChild);
+ newChild.setParentOrShadowHostNode(this);
+ newChild.setPreviousSibling(prev);
+ newChild.setNextSibling(&nextChild);
}
-void ContainerNode::parserInsertBefore(PassRefPtr<Node> newChild, Node* nextChild)
+void ContainerNode::parserInsertBefore(PassRefPtr<Node> newChild, Node& nextChild)
{
ASSERT(newChild);
- ASSERT(nextChild);
- ASSERT(nextChild->parentNode() == this);
+ ASSERT(nextChild.parentNode() == this);
ASSERT(!newChild->isDocumentFragment());
ASSERT(!hasTagName(HTMLNames::templateTag));
- if (nextChild->previousSibling() == newChild || nextChild == newChild) // nothing to do
+ if (nextChild.previousSibling() == newChild || nextChild == newChild) // nothing to do
return;
- if (&document() != &newChild->document())
+ if (document() != newChild->document())
document().adoptNode(newChild.get(), ASSERT_NO_EXCEPTION);
- insertBeforeCommon(nextChild, newChild.get());
+ insertBeforeCommon(nextChild, *newChild);
newChild->updateAncestorConnectedSubframeCountForInsertion();
- ChildListMutationScope(this).childAdded(newChild.get());
+ ChildListMutationScope(*this).childAdded(*newChild);
- childrenChanged(true, newChild->previousSibling(), nextChild, 1);
+ childrenChanged(true, newChild->previousSibling(), &nextChild, 1);
- ChildNodeInsertionNotifier(this).notify(newChild.get());
+ ChildNodeInsertionNotifier(*this).notify(*newChild);
}
-void ContainerNode::replaceChild(PassRefPtr<Node> newChild, Node* oldChild, ExceptionState& es)
+void ContainerNode::replaceChild(PassRefPtr<Node> newChild, Node* oldChild, ExceptionState& exceptionState)
{
// Check that this node is not "floating".
// If it is, it can be deleted as a side effect of sending mutation events.
@@ -335,51 +293,52 @@ void ContainerNode::replaceChild(PassRefPtr<Node> newChild, Node* oldChild, Exce
return;
if (!oldChild) {
- es.throwDOMException(NotFoundError);
+ exceptionState.throwDOMException(NotFoundError, "The node to be replaced is null.");
return;
}
// Make sure replacing the old child with the new is ok
- if (!checkReplaceChild(this, newChild.get(), oldChild, es))
+ if (!checkAcceptChild(newChild.get(), oldChild, exceptionState))
return;
// NotFoundError: Raised if oldChild is not a child of this node.
if (oldChild->parentNode() != this) {
- es.throwDOMException(NotFoundError);
+ exceptionState.throwDOMException(NotFoundError, "The node to be replaced is not a child of this node.");
return;
}
- ChildListMutationScope mutation(this);
+ ChildListMutationScope mutation(*this);
RefPtr<Node> next = oldChild->nextSibling();
// Remove the node we're replacing
RefPtr<Node> removedChild = oldChild;
- removeChild(oldChild, es);
- if (es.hadException())
+ removeChild(oldChild, exceptionState);
+ if (exceptionState.hadException())
return;
if (next && (next->previousSibling() == newChild || next == newChild)) // nothing to do
return;
// Does this one more time because removeChild() fires a MutationEvent.
- if (!checkReplaceChild(this, newChild.get(), oldChild, es))
+ if (!checkAcceptChild(newChild.get(), oldChild, exceptionState))
return;
NodeVector targets;
- collectChildrenAndRemoveFromOldParent(newChild.get(), targets, es);
- if (es.hadException())
+ collectChildrenAndRemoveFromOldParent(*newChild, targets, exceptionState);
+ if (exceptionState.hadException())
return;
// Does this yet another check because collectChildrenAndRemoveFromOldParent() fires a MutationEvent.
- if (!checkReplaceChild(this, newChild.get(), oldChild, es))
+ if (!checkAcceptChild(newChild.get(), oldChild, exceptionState))
return;
- InspectorInstrumentation::willInsertDOMNode(&document(), this);
+ InspectorInstrumentation::willInsertDOMNode(this);
// Add the new child(ren)
for (NodeVector::const_iterator it = targets.begin(); it != targets.end(); ++it) {
- Node* child = it->get();
+ ASSERT(*it);
+ Node& child = **it;
// Due to arbitrary code running in response to a DOM mutation event it's
// possible that "next" is no longer a child of "this".
@@ -387,7 +346,7 @@ void ContainerNode::replaceChild(PassRefPtr<Node> newChild, Node* oldChild, Exce
// In either of those cases, we'll just stop.
if (next && next->parentNode() != this)
break;
- if (child->parentNode())
+ if (child.parentNode())
break;
treeScope().adoptIfNeeded(child);
@@ -396,51 +355,50 @@ void ContainerNode::replaceChild(PassRefPtr<Node> newChild, Node* oldChild, Exce
{
NoEventDispatchAssertion assertNoEventDispatch;
if (next)
- insertBeforeCommon(next.get(), child);
+ insertBeforeCommon(*next, child);
else
- appendChildToContainer(child, this);
+ appendChildToContainer(child, *this);
}
- updateTreeAfterInsertion(this, child);
+ updateTreeAfterInsertion(child);
}
dispatchSubtreeModifiedEvent();
}
-static void willRemoveChild(Node* child)
+void ContainerNode::willRemoveChild(Node& child)
{
- ASSERT(child->parentNode());
- ChildListMutationScope(child->parentNode()).willRemoveChild(child);
- child->notifyMutationObserversNodeWillDetach();
+ ASSERT(child.parentNode() == this);
+ ChildListMutationScope(*this).willRemoveChild(child);
+ child.notifyMutationObserversNodeWillDetach();
dispatchChildRemovalEvents(child);
- child->document().nodeWillBeRemoved(child); // e.g. mutation event listener can create a new range.
+ document().nodeWillBeRemoved(child); // e.g. mutation event listener can create a new range.
ChildFrameDisconnector(child).disconnect();
}
-static void willRemoveChildren(ContainerNode* container)
+void ContainerNode::willRemoveChildren()
{
NodeVector children;
- getChildNodes(container, children);
+ getChildNodes(*this, children);
- ChildListMutationScope mutation(container);
+ ChildListMutationScope mutation(*this);
for (NodeVector::const_iterator it = children.begin(); it != children.end(); it++) {
- Node* child = it->get();
+ ASSERT(*it);
+ Node& child = **it;
mutation.willRemoveChild(child);
- child->notifyMutationObserversNodeWillDetach();
-
- // fire removed from document mutation events.
+ child.notifyMutationObserversNodeWillDetach();
dispatchChildRemovalEvents(child);
}
- ChildFrameDisconnector(container).disconnect(ChildFrameDisconnector::DescendantsOnly);
+ ChildFrameDisconnector(*this).disconnect(ChildFrameDisconnector::DescendantsOnly);
}
void ContainerNode::disconnectDescendantFrames()
{
- ChildFrameDisconnector(this).disconnect();
+ ChildFrameDisconnector(*this).disconnect();
}
-void ContainerNode::removeChild(Node* oldChild, ExceptionState& es)
+void ContainerNode::removeChild(Node* oldChild, ExceptionState& exceptionState)
{
// Check that this node is not "floating".
// If it is, it can be deleted as a side effect of sending mutation events.
@@ -450,7 +408,7 @@ void ContainerNode::removeChild(Node* oldChild, ExceptionState& es)
// NotFoundError: Raised if oldChild is not a child of this node.
if (!oldChild || oldChild->parentNode() != this) {
- es.throwDOMException(NotFoundError);
+ exceptionState.throwDOMException(NotFoundError, "The node to be removed is not a child of this node.");
return;
}
@@ -464,40 +422,38 @@ void ContainerNode::removeChild(Node* oldChild, ExceptionState& es)
// Events fired when blurring currently focused node might have moved this
// child into a different parent.
if (child->parentNode() != this) {
- es.throwDOMException(NotFoundError);
+ exceptionState.throwDOMException(NotFoundError, "The node to be removed is no longer a child of this node. Perhaps it was moved in a 'blur' event handler?");
return;
}
- willRemoveChild(child.get());
+ willRemoveChild(*child);
// Mutation events might have moved this child into a different parent.
if (child->parentNode() != this) {
- es.throwDOMException(NotFoundError);
+ exceptionState.throwDOMException(NotFoundError, "The node to be removed is no longer a child of this node. Perhaps it was moved in response to a mutation?");
return;
}
{
- WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;
+ RenderWidget::UpdateSuspendScope suspendWidgetHierarchyUpdates;
Node* prev = child->previousSibling();
Node* next = child->nextSibling();
- removeBetween(prev, next, child.get());
+ removeBetween(prev, next, *child);
childrenChanged(false, prev, next, -1);
- ChildNodeRemovalNotifier(this).notify(child.get());
+ ChildNodeRemovalNotifier(*this).notify(*child);
}
dispatchSubtreeModifiedEvent();
}
-void ContainerNode::removeBetween(Node* previousChild, Node* nextChild, Node* oldChild)
+void ContainerNode::removeBetween(Node* previousChild, Node* nextChild, Node& oldChild)
{
NoEventDispatchAssertion assertNoEventDispatch;
- ASSERT(oldChild);
- ASSERT(oldChild->parentNode() == this);
+ ASSERT(oldChild.parentNode() == this);
- // Remove from rendering tree
- if (oldChild->attached())
- oldChild->detach();
+ if (!oldChild.needsAttach())
+ oldChild.detach();
if (nextChild)
nextChild->setPreviousSibling(previousChild);
@@ -508,31 +464,30 @@ void ContainerNode::removeBetween(Node* previousChild, Node* nextChild, Node* ol
if (m_lastChild == oldChild)
m_lastChild = previousChild;
- oldChild->setPreviousSibling(0);
- oldChild->setNextSibling(0);
- oldChild->setParentOrShadowHostNode(0);
+ oldChild.setPreviousSibling(0);
+ oldChild.setNextSibling(0);
+ oldChild.setParentOrShadowHostNode(0);
document().adoptIfNeeded(oldChild);
}
-void ContainerNode::parserRemoveChild(Node* oldChild)
+void ContainerNode::parserRemoveChild(Node& oldChild)
{
- ASSERT(oldChild);
- ASSERT(oldChild->parentNode() == this);
- ASSERT(!oldChild->isDocumentFragment());
+ ASSERT(oldChild.parentNode() == this);
+ ASSERT(!oldChild.isDocumentFragment());
- Node* prev = oldChild->previousSibling();
- Node* next = oldChild->nextSibling();
+ Node* prev = oldChild.previousSibling();
+ Node* next = oldChild.nextSibling();
- oldChild->updateAncestorConnectedSubframeCountForRemoval();
+ oldChild.updateAncestorConnectedSubframeCountForRemoval();
- ChildListMutationScope(this).willRemoveChild(oldChild);
- oldChild->notifyMutationObserversNodeWillDetach();
+ ChildListMutationScope(*this).willRemoveChild(oldChild);
+ oldChild.notifyMutationObserversNodeWillDetach();
removeBetween(prev, next, oldChild);
childrenChanged(true, prev, next, -1);
- ChildNodeRemovalNotifier(this).notify(oldChild);
+ ChildNodeRemovalNotifier(*this).notify(oldChild);
}
// this differs from other remove functions because it forcibly removes all the children,
@@ -550,12 +505,12 @@ void ContainerNode::removeChildren()
// Do any prep work needed before actually starting to detach
// and remove... e.g. stop loading frames, fire unload events.
- willRemoveChildren(protect.get());
+ willRemoveChildren();
{
// Removing focus can cause frames to load, either via events (focusout, blur)
// or widget updates (e.g., for <embed>).
- SubframeLoadingDisabler disabler(this);
+ SubframeLoadingDisabler disabler(*this);
// Exclude this node when looking for removed focusedElement since only
// children will be removed.
@@ -570,26 +525,26 @@ void ContainerNode::removeChildren()
NodeVector removedChildren;
{
- WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;
+ RenderWidget::UpdateSuspendScope suspendWidgetHierarchyUpdates;
{
NoEventDispatchAssertion assertNoEventDispatch;
removedChildren.reserveInitialCapacity(childNodeCount());
while (m_firstChild) {
removedChildren.append(m_firstChild);
- removeBetween(0, m_firstChild->nextSibling(), m_firstChild);
+ removeBetween(0, m_firstChild->nextSibling(), *m_firstChild);
}
}
childrenChanged(false, 0, 0, -static_cast<int>(removedChildren.size()));
for (size_t i = 0; i < removedChildren.size(); ++i)
- ChildNodeRemovalNotifier(this).notify(removedChildren[i].get());
+ ChildNodeRemovalNotifier(*this).notify(*removedChildren[i]);
}
dispatchSubtreeModifiedEvent();
}
-void ContainerNode::appendChild(PassRefPtr<Node> newChild, ExceptionState& es)
+void ContainerNode::appendChild(PassRefPtr<Node> newChild, ExceptionState& exceptionState)
{
RefPtr<ContainerNode> protect(this);
@@ -598,35 +553,37 @@ void ContainerNode::appendChild(PassRefPtr<Node> newChild, ExceptionState& es)
ASSERT(refCount() || parentOrShadowHostNode());
// Make sure adding the new child is ok
- if (!checkAddChild(this, newChild.get(), es))
+ if (!checkAcceptChild(newChild.get(), 0, exceptionState))
return;
+ ASSERT(newChild);
if (newChild == m_lastChild) // nothing to do
return;
NodeVector targets;
- collectChildrenAndRemoveFromOldParent(newChild.get(), targets, es);
- if (es.hadException())
+ collectChildrenAndRemoveFromOldParent(*newChild, targets, exceptionState);
+ if (exceptionState.hadException())
return;
if (targets.isEmpty())
return;
// We need this extra check because collectChildrenAndRemoveFromOldParent() can fire mutation events.
- if (!checkAcceptChildGuaranteedNodeTypes(this, newChild.get(), es))
+ if (!checkAcceptChildGuaranteedNodeTypes(*newChild, exceptionState))
return;
- InspectorInstrumentation::willInsertDOMNode(&document(), this);
+ InspectorInstrumentation::willInsertDOMNode(this);
// Now actually add the child(ren)
- ChildListMutationScope mutation(this);
+ ChildListMutationScope mutation(*this);
for (NodeVector::const_iterator it = targets.begin(); it != targets.end(); ++it) {
- Node* child = it->get();
+ ASSERT(*it);
+ Node& child = **it;
// If the child has a parent again, just stop what we're doing, because
// that means someone is doing something with DOM mutation -- can't re-parent
// a child that already has a parent.
- if (child->parentNode())
+ if (child.parentNode())
break;
treeScope().adoptIfNeeded(child);
@@ -634,10 +591,10 @@ void ContainerNode::appendChild(PassRefPtr<Node> newChild, ExceptionState& es)
// Append child to the end of the list
{
NoEventDispatchAssertion assertNoEventDispatch;
- appendChildToContainer(child, this);
+ appendChildToContainer(child, *this);
}
- updateTreeAfterInsertion(this, child);
+ updateTreeAfterInsertion(child);
}
dispatchSubtreeModifiedEvent();
@@ -650,23 +607,23 @@ void ContainerNode::parserAppendChild(PassRefPtr<Node> newChild)
ASSERT(!newChild->isDocumentFragment());
ASSERT(!hasTagName(HTMLNames::templateTag));
- if (&document() != &newChild->document())
+ if (document() != newChild->document())
document().adoptNode(newChild.get(), ASSERT_NO_EXCEPTION);
Node* last = m_lastChild;
{
NoEventDispatchAssertion assertNoEventDispatch;
// FIXME: This method should take a PassRefPtr.
- appendChildToContainer(newChild.get(), this);
- treeScope().adoptIfNeeded(newChild.get());
+ appendChildToContainer(*newChild, *this);
+ treeScope().adoptIfNeeded(*newChild);
}
newChild->updateAncestorConnectedSubframeCountForInsertion();
- ChildListMutationScope(this).childAdded(newChild.get());
+ ChildListMutationScope(*this).childAdded(*newChild);
childrenChanged(true, last, 0, 1);
- ChildNodeInsertionNotifier(this).notify(newChild.get());
+ ChildNodeInsertionNotifier(*this).notify(*newChild);
}
void ContainerNode::attach(const AttachContext& context)
@@ -689,13 +646,17 @@ void ContainerNode::childrenChanged(bool changedByParser, Node*, Node*, int chil
if (!changedByParser && childCountDelta)
document().updateRangesAfterChildrenChanged(this);
invalidateNodeListCachesInAncestors();
+ if (childCountDelta > 0 && inActiveDocument()) {
+ setChildNeedsStyleRecalc();
+ markAncestorsWithChildNeedsStyleRecalc();
+ }
}
void ContainerNode::cloneChildNodes(ContainerNode *clone)
{
- TrackExceptionState es;
- for (Node* n = firstChild(); n && !es.hadException(); n = n->nextSibling())
- clone->appendChild(n->cloneNode(true), es);
+ TrackExceptionState exceptionState;
+ for (Node* n = firstChild(); n && !exceptionState.hadException(); n = n->nextSibling())
+ clone->appendChild(n->cloneNode(true), exceptionState);
}
@@ -831,6 +792,22 @@ LayoutRect ContainerNode::boundingBox() const
return enclosingLayoutRect(FloatRect(upperLeft, lowerRight.expandedTo(upperLeft) - upperLeft));
}
+// This is used by FrameSelection to denote when the active-state of the page has changed
+// independent of the focused element changing.
+void ContainerNode::focusStateChanged()
+{
+ // If we're just changing the window's active state and the focused node has no
+ // renderer we can just ignore the state change.
+ if (!renderer())
+ return;
+ // FIXME: This could probably setNeedsStyleRecalc(LocalStyleChange) in the affectedByFocus case
+ // and only setNeedsStyleRecalc(SubtreeStyleChange) in the childrenAffectedByFocus case.
+ if (renderStyle()->affectedByFocus() || (isElementNode() && toElement(this)->childrenAffectedByFocus()))
+ setNeedsStyleRecalc();
+ if (renderer() && renderer()->style()->hasAppearance())
+ RenderTheme::theme().stateChanged(renderer(), FocusState);
+}
+
void ContainerNode::setFocus(bool received)
{
if (focused() == received)
@@ -838,18 +815,20 @@ void ContainerNode::setFocus(bool received)
Node::setFocus(received);
- // note that we need to recalc the style
- setNeedsStyleRecalc();
+ focusStateChanged();
+ // If :focus sets display: none, we lose focus but still need to recalc our style.
+ if (!renderer() && !received)
+ setNeedsStyleRecalc();
}
-void ContainerNode::setActive(bool down, bool pause)
+void ContainerNode::setActive(bool down)
{
- if (down == active()) return;
+ if (down == active())
+ return;
Node::setActive(down);
- // note that we need to recalc the style
- // FIXME: Move to Element
+ // FIXME: Why does this not need to handle the display: none transition like :hover does?
if (renderer()) {
if (renderStyle()->affectedByActive() || (isElementNode() && toElement(this)->childrenAffectedByActive()))
setNeedsStyleRecalc();
@@ -860,24 +839,18 @@ void ContainerNode::setActive(bool down, bool pause)
void ContainerNode::setHovered(bool over)
{
- if (over == hovered()) return;
+ if (over == hovered())
+ return;
Node::setHovered(over);
+ // If :hover sets display: none we lose our hover but still need to recalc our style.
if (!renderer()) {
- // When setting hover to false, the style needs to be recalc'd even when
- // there's no renderer (imagine setting display:none in the :hover class,
- // if a nil renderer would prevent this element from recalculating its
- // style, it would never go back to its normal style and remain
- // stuck in its hovered style).
if (!over)
setNeedsStyleRecalc();
-
return;
}
- // note that we need to recalc the style
- // FIXME: Move to Element
if (renderer()) {
if (renderStyle()->affectedByHover() || (isElementNode() && toElement(this)->childrenAffectedByHover()))
setNeedsStyleRecalc();
@@ -888,12 +861,12 @@ void ContainerNode::setHovered(bool over)
PassRefPtr<HTMLCollection> ContainerNode::children()
{
- return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLCollection>(this, NodeChildren);
+ return ensureRareData().ensureNodeLists().addCacheWithAtomicName<HTMLCollection>(this, NodeChildren);
}
Element* ContainerNode::firstElementChild() const
{
- return ElementTraversal::firstWithin(this);
+ return ElementTraversal::firstWithin(*this);
}
Element* ContainerNode::lastElementChild() const
@@ -933,64 +906,64 @@ Node *ContainerNode::childNode(unsigned index) const
return n;
}
-static void dispatchChildInsertionEvents(Node* child)
+static void dispatchChildInsertionEvents(Node& child)
{
- if (child->isInShadowTree())
+ if (child.isInShadowTree())
return;
ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
- RefPtr<Node> c = child;
- RefPtr<Document> document = &child->document();
+ RefPtr<Node> c(child);
+ RefPtr<Document> document(child.document());
if (c->parentNode() && document->hasListenerType(Document::DOMNODEINSERTED_LISTENER))
- c->dispatchScopedEvent(MutationEvent::create(eventNames().DOMNodeInsertedEvent, true, c->parentNode()));
+ c->dispatchScopedEvent(MutationEvent::create(EventTypeNames::DOMNodeInserted, true, c->parentNode()));
// dispatch the DOMNodeInsertedIntoDocument event to all descendants
if (c->inDocument() && document->hasListenerType(Document::DOMNODEINSERTEDINTODOCUMENT_LISTENER)) {
- for (; c; c = NodeTraversal::next(c.get(), child))
- c->dispatchScopedEvent(MutationEvent::create(eventNames().DOMNodeInsertedIntoDocumentEvent, false));
+ for (; c; c = NodeTraversal::next(*c, &child))
+ c->dispatchScopedEvent(MutationEvent::create(EventTypeNames::DOMNodeInsertedIntoDocument, false));
}
}
-static void dispatchChildRemovalEvents(Node* child)
+static void dispatchChildRemovalEvents(Node& child)
{
- if (child->isInShadowTree()) {
- InspectorInstrumentation::willRemoveDOMNode(&child->document(), child);
+ if (child.isInShadowTree()) {
+ InspectorInstrumentation::willRemoveDOMNode(&child);
return;
}
ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
- InspectorInstrumentation::willRemoveDOMNode(&child->document(), child);
+ InspectorInstrumentation::willRemoveDOMNode(&child);
- RefPtr<Node> c = child;
- RefPtr<Document> document = &child->document();
+ RefPtr<Node> c(child);
+ RefPtr<Document> document(child.document());
// dispatch pre-removal mutation events
if (c->parentNode() && document->hasListenerType(Document::DOMNODEREMOVED_LISTENER)) {
NodeChildRemovalTracker scope(child);
- c->dispatchScopedEvent(MutationEvent::create(eventNames().DOMNodeRemovedEvent, true, c->parentNode()));
+ c->dispatchScopedEvent(MutationEvent::create(EventTypeNames::DOMNodeRemoved, true, c->parentNode()));
}
// dispatch the DOMNodeRemovedFromDocument event to all descendants
if (c->inDocument() && document->hasListenerType(Document::DOMNODEREMOVEDFROMDOCUMENT_LISTENER)) {
NodeChildRemovalTracker scope(child);
- for (; c; c = NodeTraversal::next(c.get(), child))
- c->dispatchScopedEvent(MutationEvent::create(eventNames().DOMNodeRemovedFromDocumentEvent, false));
+ for (; c; c = NodeTraversal::next(*c, &child))
+ c->dispatchScopedEvent(MutationEvent::create(EventTypeNames::DOMNodeRemovedFromDocument, false));
}
}
-static void updateTreeAfterInsertion(ContainerNode* parent, Node* child)
+void ContainerNode::updateTreeAfterInsertion(Node& child)
{
- ASSERT(parent->refCount());
- ASSERT(child->refCount());
+ ASSERT(refCount());
+ ASSERT(child.refCount());
- ChildListMutationScope(parent).childAdded(child);
+ ChildListMutationScope(*this).childAdded(child);
- parent->childrenChanged(false, child->previousSibling(), child->nextSibling(), 1);
+ childrenChanged(false, child.previousSibling(), child.nextSibling(), 1);
- ChildNodeInsertionNotifier(parent).notify(child);
+ ChildNodeInsertionNotifier(*this).notify(child);
dispatchChildInsertionEvents(child);
}
diff --git a/chromium/third_party/WebKit/Source/core/dom/ContainerNode.h b/chromium/third_party/WebKit/Source/core/dom/ContainerNode.h
index 80b9c88c0ab..d64d78275f9 100644
--- a/chromium/third_party/WebKit/Source/core/dom/ContainerNode.h
+++ b/chromium/third_party/WebKit/Source/core/dom/ContainerNode.h
@@ -37,8 +37,8 @@ class HTMLCollection;
namespace Private {
template<class GenericNode, class GenericNodeContainer>
- void addChildNodesToDeletionQueue(GenericNode*& head, GenericNode*& tail, GenericNodeContainer*);
-};
+ void addChildNodesToDeletionQueue(GenericNode*& head, GenericNode*& tail, GenericNodeContainer&);
+}
class NoEventDispatchAssertion {
public:
@@ -105,11 +105,11 @@ public:
// They don't send DOM mutation events or handle reparenting.
// However, arbitrary code may be run by beforeload handlers.
void parserAppendChild(PassRefPtr<Node>);
- void parserRemoveChild(Node*);
- void parserInsertBefore(PassRefPtr<Node> newChild, Node* refChild);
+ void parserRemoveChild(Node&);
+ void parserInsertBefore(PassRefPtr<Node> newChild, Node& refChild);
+ void parserTakeAllChildrenFrom(ContainerNode&);
void removeChildren();
- void takeAllChildrenFrom(ContainerNode*);
void cloneChildNodes(ContainerNode* clone);
@@ -117,7 +117,8 @@ public:
virtual void detach(const AttachContext& = AttachContext()) OVERRIDE;
virtual LayoutRect boundingBox() const OVERRIDE;
virtual void setFocus(bool) OVERRIDE;
- virtual void setActive(bool active = true, bool pause = false) OVERRIDE;
+ void focusStateChanged();
+ virtual void setActive(bool = true) OVERRIDE;
virtual void setHovered(bool = true) OVERRIDE;
// -----------------------------------------------------------------------------
@@ -135,18 +136,26 @@ protected:
ContainerNode(TreeScope*, ConstructionType = CreateContainer);
template<class GenericNode, class GenericNodeContainer>
- friend void appendChildToContainer(GenericNode* child, GenericNodeContainer*);
+ friend void appendChildToContainer(GenericNode& child, GenericNodeContainer&);
template<class GenericNode, class GenericNodeContainer>
- friend void Private::addChildNodesToDeletionQueue(GenericNode*& head, GenericNode*& tail, GenericNodeContainer*);
+ friend void Private::addChildNodesToDeletionQueue(GenericNode*& head, GenericNode*& tail, GenericNodeContainer&);
void removeDetachedChildren();
void setFirstChild(Node* child) { m_firstChild = child; }
void setLastChild(Node* child) { m_lastChild = child; }
private:
- void removeBetween(Node* previousChild, Node* nextChild, Node* oldChild);
- void insertBeforeCommon(Node* nextChild, Node* oldChild);
+ void removeBetween(Node* previousChild, Node* nextChild, Node& oldChild);
+ void insertBeforeCommon(Node& nextChild, Node& oldChild);
+ void updateTreeAfterInsertion(Node& child);
+ void willRemoveChildren();
+ void willRemoveChild(Node& child);
+
+ inline bool checkAcceptChildGuaranteedNodeTypes(const Node& newChild, ExceptionState&) const;
+ inline bool checkAcceptChild(const Node* newChild, const Node* oldChild, ExceptionState&) const;
+ inline bool containsConsideringHostElements(const Node&) const;
+ inline bool isChildTypeAllowed(const Node& child) const;
void attachChildren(const AttachContext& = AttachContext());
void detachChildren(const AttachContext& = AttachContext());
@@ -162,20 +171,7 @@ private:
bool childAttachedAllowedWhenAttachingChildren(ContainerNode*);
#endif
-inline ContainerNode* toContainerNode(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->isContainerNode());
- return static_cast<ContainerNode*>(node);
-}
-
-inline const ContainerNode* toContainerNode(const Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->isContainerNode());
- return static_cast<const ContainerNode*>(node);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toContainerNode(const ContainerNode*);
+DEFINE_NODE_TYPE_CASTS(ContainerNode, isContainerNode());
inline ContainerNode::ContainerNode(TreeScope* treeScope, ConstructionType type)
: Node(treeScope, type)
@@ -190,8 +186,8 @@ inline void ContainerNode::attachChildren(const AttachContext& context)
childrenContext.resolvedStyle = 0;
for (Node* child = firstChild(); child; child = child->nextSibling()) {
- ASSERT(!child->attached() || childAttachedAllowedWhenAttachingChildren(this));
- if (!child->attached())
+ ASSERT(child->needsAttach() || childAttachedAllowedWhenAttachingChildren(this));
+ if (child->needsAttach())
child->attach(childrenContext);
}
}
@@ -248,10 +244,10 @@ inline Node* Node::highestAncestor() const
const int initialNodeVectorSize = 11;
typedef Vector<RefPtr<Node>, initialNodeVectorSize> NodeVector;
-inline void getChildNodes(Node* node, NodeVector& nodes)
+inline void getChildNodes(Node& node, NodeVector& nodes)
{
ASSERT(!nodes.size());
- for (Node* child = node->firstChild(); child; child = child->nextSibling())
+ for (Node* child = node.firstChild(); child; child = child->nextSibling())
nodes.append(child);
}
@@ -259,8 +255,8 @@ class ChildNodesLazySnapshot {
WTF_MAKE_NONCOPYABLE(ChildNodesLazySnapshot);
WTF_MAKE_FAST_ALLOCATED;
public:
- explicit ChildNodesLazySnapshot(Node* parentNode)
- : m_currentNode(parentNode->firstChild())
+ explicit ChildNodesLazySnapshot(Node& parentNode)
+ : m_currentNode(parentNode.firstChild())
, m_currentIndex(0)
{
m_nextSnapshot = latestSnapshot;
diff --git a/chromium/third_party/WebKit/Source/core/dom/ContainerNodeAlgorithms.cpp b/chromium/third_party/WebKit/Source/core/dom/ContainerNodeAlgorithms.cpp
index ab67eefcd5e..4c55b46355d 100644
--- a/chromium/third_party/WebKit/Source/core/dom/ContainerNodeAlgorithms.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/ContainerNodeAlgorithms.cpp
@@ -29,7 +29,6 @@
#include "core/dom/Element.h"
#include "core/dom/shadow/ElementShadow.h"
#include "core/dom/shadow/ShadowRoot.h"
-#include "core/html/HTMLFrameOwnerElement.h"
namespace WebCore {
@@ -42,115 +41,115 @@ public:
}
};
-void ChildNodeInsertionNotifier::notifyDescendantInsertedIntoDocument(ContainerNode* node)
+void ChildNodeInsertionNotifier::notifyDescendantInsertedIntoDocument(ContainerNode& node)
{
ChildNodesLazySnapshot snapshot(node);
while (RefPtr<Node> child = snapshot.nextNode()) {
// If we have been removed from the document during this loop, then
// we don't want to tell the rest of our children that they've been
// inserted into the document because they haven't.
- if (node->inDocument() && child->parentNode() == node)
- notifyNodeInsertedIntoDocument(child.get());
+ if (node.inDocument() && child->parentNode() == node)
+ notifyNodeInsertedIntoDocument(*child);
}
- if (!node->isElementNode())
+ if (!node.isElementNode())
return;
- if (ElementShadow* shadow = toElement(node)->shadow()) {
+ if (ElementShadow* shadow = toElement(node).shadow()) {
ShadowRootVector roots(shadow);
for (size_t i = 0; i < roots.size(); ++i) {
- if (node->inDocument() && roots[i]->host() == node)
- notifyNodeInsertedIntoDocument(roots[i].get());
+ if (node.inDocument() && roots[i]->host() == node)
+ notifyNodeInsertedIntoDocument(*roots[i]);
}
}
}
-void ChildNodeInsertionNotifier::notifyDescendantInsertedIntoTree(ContainerNode* node)
+void ChildNodeInsertionNotifier::notifyDescendantInsertedIntoTree(ContainerNode& node)
{
- for (Node* child = node->firstChild(); child; child = child->nextSibling()) {
+ for (Node* child = node.firstChild(); child; child = child->nextSibling()) {
if (child->isContainerNode())
- notifyNodeInsertedIntoTree(toContainerNode(child));
+ notifyNodeInsertedIntoTree(toContainerNode(*child));
}
- for (ShadowRoot* root = node->youngestShadowRoot(); root; root = root->olderShadowRoot())
- notifyNodeInsertedIntoTree(root);
+ for (ShadowRoot* root = node.youngestShadowRoot(); root; root = root->olderShadowRoot())
+ notifyNodeInsertedIntoTree(*root);
}
-void ChildNodeRemovalNotifier::notifyDescendantRemovedFromDocument(ContainerNode* node)
+void ChildNodeRemovalNotifier::notifyDescendantRemovedFromDocument(ContainerNode& node)
{
ChildNodesLazySnapshot snapshot(node);
while (RefPtr<Node> child = snapshot.nextNode()) {
// If we have been added to the document during this loop, then we
// don't want to tell the rest of our children that they've been
// removed from the document because they haven't.
- if (!node->inDocument() && child->parentNode() == node)
- notifyNodeRemovedFromDocument(child.get());
+ if (!node.inDocument() && child->parentNode() == node)
+ notifyNodeRemovedFromDocument(*child);
}
- if (!node->isElementNode())
+ if (!node.isElementNode())
return;
- if (node->document().cssTarget() == node)
- node->document().setCSSTarget(0);
+ if (node.document().cssTarget() == node)
+ node.document().setCSSTarget(0);
- if (ElementShadow* shadow = toElement(node)->shadow()) {
+ if (ElementShadow* shadow = toElement(node).shadow()) {
ShadowRootVector roots(shadow);
for (size_t i = 0; i < roots.size(); ++i) {
- if (!node->inDocument() && roots[i]->host() == node)
- notifyNodeRemovedFromDocument(roots[i].get());
+ if (!node.inDocument() && roots[i]->host() == node)
+ notifyNodeRemovedFromDocument(*roots[i]);
}
}
}
-void ChildNodeRemovalNotifier::notifyDescendantRemovedFromTree(ContainerNode* node)
+void ChildNodeRemovalNotifier::notifyDescendantRemovedFromTree(ContainerNode& node)
{
- for (Node* child = node->firstChild(); child; child = child->nextSibling()) {
+ for (Node* child = node.firstChild(); child; child = child->nextSibling()) {
if (child->isContainerNode())
- notifyNodeRemovedFromTree(toContainerNode(child));
+ notifyNodeRemovedFromTree(toContainerNode(*child));
}
- if (!node->isElementNode())
+ if (!node.isElementNode())
return;
- if (ElementShadow* shadow = toElement(node)->shadow()) {
+ if (ElementShadow* shadow = toElement(node).shadow()) {
ShadowRootVector roots(shadow);
for (size_t i = 0; i < roots.size(); ++i)
- notifyNodeRemovedFromTree(roots[i].get());
+ notifyNodeRemovedFromTree(*roots[i]);
}
}
-void ChildFrameDisconnector::collectFrameOwners(ElementShadow* shadow)
+void ChildFrameDisconnector::collectFrameOwners(ElementShadow& shadow)
{
- for (ShadowRoot* root = shadow->youngestShadowRoot(); root; root = root->olderShadowRoot())
- collectFrameOwners(root);
+ for (ShadowRoot* root = shadow.youngestShadowRoot(); root; root = root->olderShadowRoot())
+ collectFrameOwners(*root);
}
#ifndef NDEBUG
-unsigned assertConnectedSubrameCountIsConsistent(Node* node)
+unsigned assertConnectedSubrameCountIsConsistent(Node& node)
{
unsigned count = 0;
- if (node->isElementNode()) {
- if (node->isFrameOwnerElement() && toHTMLFrameOwnerElement(node)->contentFrame())
+ if (node.isElementNode()) {
+ if (node.isFrameOwnerElement() && toHTMLFrameOwnerElement(node).contentFrame())
count++;
- if (ElementShadow* shadow = toElement(node)->shadow()) {
+ if (ElementShadow* shadow = toElement(node).shadow()) {
for (ShadowRoot* root = shadow->youngestShadowRoot(); root; root = root->olderShadowRoot())
- count += assertConnectedSubrameCountIsConsistent(root);
+ count += assertConnectedSubrameCountIsConsistent(*root);
}
}
- for (Node* child = node->firstChild(); child; child = child->nextSibling())
- count += assertConnectedSubrameCountIsConsistent(child);
+ for (Node* child = node.firstChild(); child; child = child->nextSibling())
+ count += assertConnectedSubrameCountIsConsistent(*child);
// If we undercount there's possibly a security bug since we'd leave frames
// in subtrees outside the document.
- ASSERT(node->connectedSubframeCount() >= count);
+ ASSERT(node.connectedSubframeCount() >= count);
// If we overcount it's safe, but not optimal because it means we'll traverse
// through the document in ChildFrameDisconnector looking for frames that have
// already been disconnected.
- ASSERT(node->connectedSubframeCount() == count);
+ ASSERT(node.connectedSubframeCount() == count);
return count;
}
diff --git a/chromium/third_party/WebKit/Source/core/dom/ContainerNodeAlgorithms.h b/chromium/third_party/WebKit/Source/core/dom/ContainerNodeAlgorithms.h
index d8910cfb7da..b863c252f2f 100644
--- a/chromium/third_party/WebKit/Source/core/dom/ContainerNodeAlgorithms.h
+++ b/chromium/third_party/WebKit/Source/core/dom/ContainerNodeAlgorithms.h
@@ -31,52 +31,52 @@ namespace WebCore {
class ChildNodeInsertionNotifier {
public:
- explicit ChildNodeInsertionNotifier(ContainerNode* insertionPoint)
+ explicit ChildNodeInsertionNotifier(ContainerNode& insertionPoint)
: m_insertionPoint(insertionPoint)
{
}
- void notify(Node*);
+ void notify(Node&);
private:
- void notifyDescendantInsertedIntoDocument(ContainerNode*);
- void notifyDescendantInsertedIntoTree(ContainerNode*);
- void notifyNodeInsertedIntoDocument(Node*);
- void notifyNodeInsertedIntoTree(ContainerNode*);
+ void notifyDescendantInsertedIntoDocument(ContainerNode&);
+ void notifyDescendantInsertedIntoTree(ContainerNode&);
+ void notifyNodeInsertedIntoDocument(Node&);
+ void notifyNodeInsertedIntoTree(ContainerNode&);
- ContainerNode* m_insertionPoint;
+ ContainerNode& m_insertionPoint;
Vector< RefPtr<Node> > m_postInsertionNotificationTargets;
};
class ChildNodeRemovalNotifier {
public:
- explicit ChildNodeRemovalNotifier(ContainerNode* insertionPoint)
+ explicit ChildNodeRemovalNotifier(ContainerNode& insertionPoint)
: m_insertionPoint(insertionPoint)
{
}
- void notify(Node*);
+ void notify(Node&);
private:
- void notifyDescendantRemovedFromDocument(ContainerNode*);
- void notifyDescendantRemovedFromTree(ContainerNode*);
- void notifyNodeRemovedFromDocument(Node*);
- void notifyNodeRemovedFromTree(ContainerNode*);
+ void notifyDescendantRemovedFromDocument(ContainerNode&);
+ void notifyDescendantRemovedFromTree(ContainerNode&);
+ void notifyNodeRemovedFromDocument(Node&);
+ void notifyNodeRemovedFromTree(ContainerNode&);
- ContainerNode* m_insertionPoint;
+ ContainerNode& m_insertionPoint;
};
namespace Private {
template<class GenericNode, class GenericNodeContainer>
- void addChildNodesToDeletionQueue(GenericNode*& head, GenericNode*& tail, GenericNodeContainer*);
+ void addChildNodesToDeletionQueue(GenericNode*& head, GenericNode*& tail, GenericNodeContainer&);
}
// Helper functions for TreeShared-derived classes, which have a 'Node' style interface
// This applies to 'ContainerNode' and 'SVGElementInstance'
template<class GenericNode, class GenericNodeContainer>
-inline void removeDetachedChildrenInContainer(GenericNodeContainer* container)
+inline void removeDetachedChildrenInContainer(GenericNodeContainer& container)
{
// List of nodes to be deleted.
GenericNode* head = 0;
@@ -87,7 +87,7 @@ inline void removeDetachedChildrenInContainer(GenericNodeContainer* container)
GenericNode* n;
GenericNode* next;
while ((n = head) != 0) {
- ASSERT(n->m_deletionHasBegun);
+ ASSERT_WITH_SECURITY_IMPLICATION(n->m_deletionHasBegun);
next = n->nextSibling();
n->setNextSibling(0);
@@ -97,25 +97,26 @@ inline void removeDetachedChildrenInContainer(GenericNodeContainer* container)
tail = 0;
if (n->hasChildNodes())
- Private::addChildNodesToDeletionQueue<GenericNode, GenericNodeContainer>(head, tail, static_cast<GenericNodeContainer*>(n));
+ Private::addChildNodesToDeletionQueue<GenericNode, GenericNodeContainer>(head, tail, static_cast<GenericNodeContainer&>(*n));
delete n;
}
}
template<class GenericNode, class GenericNodeContainer>
-inline void appendChildToContainer(GenericNode* child, GenericNodeContainer* container)
+inline void appendChildToContainer(GenericNode& child, GenericNodeContainer& container)
{
- child->setParentOrShadowHostNode(container);
+ child.setParentOrShadowHostNode(&container);
- GenericNode* lastChild = container->lastChild();
+ GenericNode* lastChild = container.lastChild();
if (lastChild) {
- child->setPreviousSibling(lastChild);
- lastChild->setNextSibling(child);
- } else
- container->setFirstChild(child);
+ child.setPreviousSibling(lastChild);
+ lastChild->setNextSibling(&child);
+ } else {
+ container.setFirstChild(&child);
+ }
- container->setLastChild(child);
+ container.setLastChild(&child);
}
// Helper methods for removeDetachedChildrenInContainer, hidden from WebCore namespace
@@ -123,7 +124,7 @@ namespace Private {
template<class GenericNode, class GenericNodeContainer, bool dispatchRemovalNotification>
struct NodeRemovalDispatcher {
- static void dispatch(GenericNode*, GenericNodeContainer*)
+ static void dispatch(GenericNode&, GenericNodeContainer&)
{
// no-op, by default
}
@@ -131,12 +132,12 @@ namespace Private {
template<class GenericNode, class GenericNodeContainer>
struct NodeRemovalDispatcher<GenericNode, GenericNodeContainer, true> {
- static void dispatch(GenericNode* node, GenericNodeContainer* container)
+ static void dispatch(GenericNode& node, GenericNodeContainer& container)
{
// Clean up any TreeScope to a removed tree.
- if (Document* containerDocument = container->ownerDocument())
+ if (Document* containerDocument = container.ownerDocument())
containerDocument->adoptIfNeeded(node);
- if (node->inDocument())
+ if (node.inDocument())
ChildNodeRemovalNotifier(container).notify(node);
}
};
@@ -152,22 +153,22 @@ namespace Private {
};
template<class GenericNode, class GenericNodeContainer>
- void addChildNodesToDeletionQueue(GenericNode*& head, GenericNode*& tail, GenericNodeContainer* container)
+ void addChildNodesToDeletionQueue(GenericNode*& head, GenericNode*& tail, GenericNodeContainer& container)
{
// We have to tell all children that their parent has died.
GenericNode* next = 0;
- for (GenericNode* n = container->firstChild(); n != 0; n = next) {
- ASSERT(!n->m_deletionHasBegun);
+ for (GenericNode* n = container.firstChild(); n; n = next) {
+ ASSERT_WITH_SECURITY_IMPLICATION(!n->m_deletionHasBegun);
next = n->nextSibling();
n->setNextSibling(0);
n->setParentOrShadowHostNode(0);
- container->setFirstChild(next);
+ container.setFirstChild(next);
if (next)
next->setPreviousSibling(0);
if (!n->refCount()) {
-#ifndef NDEBUG
+#if SECURITY_ASSERT_ENABLED
n->m_deletionHasBegun = true;
#endif
// Add the node to the list of nodes to be deleted.
@@ -180,88 +181,80 @@ namespace Private {
tail = n;
} else {
RefPtr<GenericNode> protect(n); // removedFromDocument may remove remove all references to this node.
- NodeRemovalDispatcher<GenericNode, GenericNodeContainer, ShouldDispatchRemovalNotification<GenericNode>::value>::dispatch(n, container);
+ NodeRemovalDispatcher<GenericNode, GenericNodeContainer, ShouldDispatchRemovalNotification<GenericNode>::value>::dispatch(*n, container);
}
}
- container->setLastChild(0);
+ container.setLastChild(0);
}
} // namespace Private
-inline void ChildNodeInsertionNotifier::notifyNodeInsertedIntoDocument(Node* node)
+inline void ChildNodeInsertionNotifier::notifyNodeInsertedIntoDocument(Node& node)
{
- ASSERT(m_insertionPoint->inDocument());
+ ASSERT(m_insertionPoint.inDocument());
RefPtr<Node> protect(node);
- if (Node::InsertionShouldCallDidNotifySubtreeInsertions == node->insertedInto(m_insertionPoint))
- m_postInsertionNotificationTargets.append(node);
- if (node->isContainerNode())
+ if (Node::InsertionShouldCallDidNotifySubtreeInsertions == node.insertedInto(&m_insertionPoint))
+ m_postInsertionNotificationTargets.append(&node);
+ if (node.isContainerNode())
notifyDescendantInsertedIntoDocument(toContainerNode(node));
}
-inline void ChildNodeInsertionNotifier::notifyNodeInsertedIntoTree(ContainerNode* node)
+inline void ChildNodeInsertionNotifier::notifyNodeInsertedIntoTree(ContainerNode& node)
{
NoEventDispatchAssertion assertNoEventDispatch;
- ASSERT(!m_insertionPoint->inDocument());
+ ASSERT(!m_insertionPoint.inDocument());
- if (Node::InsertionShouldCallDidNotifySubtreeInsertions == node->insertedInto(m_insertionPoint))
- m_postInsertionNotificationTargets.append(node);
+ if (Node::InsertionShouldCallDidNotifySubtreeInsertions == node.insertedInto(&m_insertionPoint))
+ m_postInsertionNotificationTargets.append(&node);
notifyDescendantInsertedIntoTree(node);
}
-inline void ChildNodeInsertionNotifier::notify(Node* node)
+inline void ChildNodeInsertionNotifier::notify(Node& node)
{
ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
- InspectorInstrumentation::didInsertDOMNode(&node->document(), node);
+ InspectorInstrumentation::didInsertDOMNode(&node);
- RefPtr<Document> protectDocument(&node->document());
+ RefPtr<Document> protectDocument(node.document());
RefPtr<Node> protectNode(node);
- if (m_insertionPoint->inDocument())
+ if (m_insertionPoint.inDocument())
notifyNodeInsertedIntoDocument(node);
- else if (node->isContainerNode())
+ else if (node.isContainerNode())
notifyNodeInsertedIntoTree(toContainerNode(node));
- // Script runs in didNotifySubtreeInsertions so we should lazy attach before
- // to ensure that triggering a style recalc in script attaches all nodes that
- // were inserted.
- // FIXME: We should merge the lazy attach logic into the tree traversal in
- // notifyNodeInsertedIntoDocument.
- if (!node->attached() && node->parentNode() && node->parentNode()->attached())
- node->lazyAttach();
-
for (size_t i = 0; i < m_postInsertionNotificationTargets.size(); ++i) {
- Node* node = m_postInsertionNotificationTargets[i].get();
- if (node->inDocument())
- node->didNotifySubtreeInsertionsToDocument();
+ Node* targetNode = m_postInsertionNotificationTargets[i].get();
+ if (targetNode->inDocument())
+ targetNode->didNotifySubtreeInsertionsToDocument();
}
}
-inline void ChildNodeRemovalNotifier::notifyNodeRemovedFromDocument(Node* node)
+inline void ChildNodeRemovalNotifier::notifyNodeRemovedFromDocument(Node& node)
{
- ASSERT(m_insertionPoint->inDocument());
- node->removedFrom(m_insertionPoint);
+ ASSERT(m_insertionPoint.inDocument());
+ node.removedFrom(&m_insertionPoint);
- if (node->isContainerNode())
+ if (node.isContainerNode())
notifyDescendantRemovedFromDocument(toContainerNode(node));
}
-inline void ChildNodeRemovalNotifier::notifyNodeRemovedFromTree(ContainerNode* node)
+inline void ChildNodeRemovalNotifier::notifyNodeRemovedFromTree(ContainerNode& node)
{
NoEventDispatchAssertion assertNoEventDispatch;
- ASSERT(!m_insertionPoint->inDocument());
+ ASSERT(!m_insertionPoint.inDocument());
- node->removedFrom(m_insertionPoint);
+ node.removedFrom(&m_insertionPoint);
notifyDescendantRemovedFromTree(node);
}
-inline void ChildNodeRemovalNotifier::notify(Node* node)
+inline void ChildNodeRemovalNotifier::notify(Node& node)
{
- if (node->inDocument()) {
+ if (node.inDocument()) {
notifyNodeRemovedFromDocument(node);
- node->document().notifyRemovePendingSheetIfNeeded();
- } else if (node->isContainerNode())
+ node.document().notifyRemovePendingSheetIfNeeded();
+ } else if (node.isContainerNode())
notifyNodeRemovedFromTree(toContainerNode(node));
}
@@ -272,7 +265,7 @@ public:
DescendantsOnly
};
- explicit ChildFrameDisconnector(Node* root)
+ explicit ChildFrameDisconnector(Node& root)
: m_root(root)
{
}
@@ -280,32 +273,32 @@ public:
void disconnect(DisconnectPolicy = RootAndDescendants);
private:
- void collectFrameOwners(Node* root);
- void collectFrameOwners(ElementShadow*);
+ void collectFrameOwners(Node& root);
+ void collectFrameOwners(ElementShadow&);
void disconnectCollectedFrameOwners();
Vector<RefPtr<HTMLFrameOwnerElement>, 10> m_frameOwners;
- Node* m_root;
+ Node& m_root;
};
#ifndef NDEBUG
-unsigned assertConnectedSubrameCountIsConsistent(Node*);
+unsigned assertConnectedSubrameCountIsConsistent(Node&);
#endif
-inline void ChildFrameDisconnector::collectFrameOwners(Node* root)
+inline void ChildFrameDisconnector::collectFrameOwners(Node& root)
{
- if (!root->connectedSubframeCount())
+ if (!root.connectedSubframeCount())
return;
- if (root->isHTMLElement() && root->isFrameOwnerElement())
- m_frameOwners.append(toHTMLFrameOwnerElement(root));
+ if (root.isHTMLElement() && root.isFrameOwnerElement())
+ m_frameOwners.append(&toHTMLFrameOwnerElement(root));
- for (Node* child = root->firstChild(); child; child = child->nextSibling())
- collectFrameOwners(child);
+ for (Node* child = root.firstChild(); child; child = child->nextSibling())
+ collectFrameOwners(*child);
- ElementShadow* shadow = root->isElementNode() ? toElement(root)->shadow() : 0;
+ ElementShadow* shadow = root.isElementNode() ? toElement(root).shadow() : 0;
if (shadow)
- collectFrameOwners(shadow);
+ collectFrameOwners(*shadow);
}
inline void ChildFrameDisconnector::disconnectCollectedFrameOwners()
@@ -318,7 +311,7 @@ inline void ChildFrameDisconnector::disconnectCollectedFrameOwners()
HTMLFrameOwnerElement* owner = m_frameOwners[i].get();
// Don't need to traverse up the tree for the first owner since no
// script could have moved it.
- if (!i || m_root->containsIncludingShadowDOM(owner))
+ if (!i || m_root.containsIncludingShadowDOM(owner))
owner->disconnectContentFrame();
}
}
@@ -329,14 +322,14 @@ inline void ChildFrameDisconnector::disconnect(DisconnectPolicy policy)
assertConnectedSubrameCountIsConsistent(m_root);
#endif
- if (!m_root->connectedSubframeCount())
+ if (!m_root.connectedSubframeCount())
return;
if (policy == RootAndDescendants)
collectFrameOwners(m_root);
else {
- for (Node* child = m_root->firstChild(); child; child = child->nextSibling())
- collectFrameOwners(child);
+ for (Node* child = m_root.firstChild(); child; child = child->nextSibling())
+ collectFrameOwners(*child);
}
disconnectCollectedFrameOwners();
diff --git a/chromium/third_party/WebKit/Source/core/dom/ContextFeatures.cpp b/chromium/third_party/WebKit/Source/core/dom/ContextFeatures.cpp
index 47af9c0ba3d..980dde13bfb 100644
--- a/chromium/third_party/WebKit/Source/core/dom/ContextFeatures.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/ContextFeatures.cpp
@@ -27,9 +27,9 @@
#include "config.h"
#include "core/dom/ContextFeatures.h"
+#include "RuntimeEnabledFeatures.h"
#include "core/dom/Document.h"
#include "core/page/Page.h"
-#include "RuntimeEnabledFeatures.h"
namespace WebCore {
@@ -46,8 +46,8 @@ const char* ContextFeatures::supplementName()
ContextFeatures* ContextFeatures::defaultSwitch()
{
- DEFINE_STATIC_LOCAL(RefPtr<ContextFeatures>, instance, (ContextFeatures::create(ContextFeaturesClient::empty())));
- return instance.get();
+ DEFINE_STATIC_REF(ContextFeatures, instance, (ContextFeatures::create(ContextFeaturesClient::empty())));
+ return instance;
}
bool ContextFeatures::dialogElementEnabled(Document* document)
diff --git a/chromium/third_party/WebKit/Source/core/dom/ContextFeatures.h b/chromium/third_party/WebKit/Source/core/dom/ContextFeatures.h
index 231ee040b50..109b781ff09 100644
--- a/chromium/third_party/WebKit/Source/core/dom/ContextFeatures.h
+++ b/chromium/third_party/WebKit/Source/core/dom/ContextFeatures.h
@@ -27,7 +27,7 @@
#ifndef ContextFeatures_h
#define ContextFeatures_h
-#include "core/platform/RefCountedSupplement.h"
+#include "platform/RefCountedSupplement.h"
namespace WebCore {
@@ -102,9 +102,14 @@ inline bool ContextFeatures::isEnabled(Document* document, FeatureType type, boo
inline void ContextFeatures::urlDidChange(Document* document)
{
- if (m_client)
- return;
- m_client->urlDidChange(document);
+ // FIXME: The original code, commented out below, is obviously
+ // wrong, but the seemingly correct fix of negating the test to
+ // the more logical 'if (!m_client)' crashes the renderer.
+ // See issue 294180
+ //
+ // if (m_client)
+ // return;
+ // m_client->urlDidChange(document);
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/ContextLifecycleNotifier.cpp b/chromium/third_party/WebKit/Source/core/dom/ContextLifecycleNotifier.cpp
index 205380d717f..048978c7354 100644
--- a/chromium/third_party/WebKit/Source/core/dom/ContextLifecycleNotifier.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/ContextLifecycleNotifier.cpp
@@ -28,13 +28,13 @@
#include "config.h"
#include "core/dom/ContextLifecycleNotifier.h"
-#include "core/dom/ScriptExecutionContext.h"
+#include "core/dom/ExecutionContext.h"
#include "wtf/TemporaryChange.h"
namespace WebCore {
-ContextLifecycleNotifier::ContextLifecycleNotifier(ScriptExecutionContext* context)
- : LifecycleNotifier(context)
+ContextLifecycleNotifier::ContextLifecycleNotifier(ExecutionContext* context)
+ : LifecycleNotifier<ExecutionContext>(context)
{
}
@@ -42,23 +42,23 @@ ContextLifecycleNotifier::~ContextLifecycleNotifier()
{
}
-void ContextLifecycleNotifier::addObserver(LifecycleObserver* observer)
+void ContextLifecycleNotifier::addObserver(ContextLifecycleNotifier::Observer* observer)
{
- LifecycleNotifier::addObserver(observer);
+ LifecycleNotifier<ExecutionContext>::addObserver(observer);
RELEASE_ASSERT(m_iterating != IteratingOverContextObservers);
- if (observer->observerType() == LifecycleObserver::ActiveDOMObjectType) {
+ if (observer->observerType() == Observer::ActiveDOMObjectType) {
RELEASE_ASSERT(m_iterating != IteratingOverActiveDOMObjects);
m_activeDOMObjects.add(static_cast<ActiveDOMObject*>(observer));
}
}
-void ContextLifecycleNotifier::removeObserver(LifecycleObserver* observer)
+void ContextLifecycleNotifier::removeObserver(ContextLifecycleNotifier::Observer* observer)
{
- LifecycleNotifier::removeObserver(observer);
+ LifecycleNotifier<ExecutionContext>::removeObserver(observer);
RELEASE_ASSERT(m_iterating != IteratingOverContextObservers);
- if (observer->observerType() == LifecycleObserver::ActiveDOMObjectType) {
+ if (observer->observerType() == Observer::ActiveDOMObjectType) {
RELEASE_ASSERT(m_iterating != IteratingOverActiveDOMObjects);
m_activeDOMObjects.remove(static_cast<ActiveDOMObject*>(observer));
}
@@ -69,20 +69,20 @@ void ContextLifecycleNotifier::notifyResumingActiveDOMObjects()
TemporaryChange<IterationType> scope(this->m_iterating, IteratingOverActiveDOMObjects);
ActiveDOMObjectSet::iterator activeObjectsEnd = m_activeDOMObjects.end();
for (ActiveDOMObjectSet::iterator iter = m_activeDOMObjects.begin(); iter != activeObjectsEnd; ++iter) {
- ASSERT((*iter)->scriptExecutionContext() == context());
+ ASSERT((*iter)->executionContext() == context());
ASSERT((*iter)->suspendIfNeededCalled());
(*iter)->resume();
}
}
-void ContextLifecycleNotifier::notifySuspendingActiveDOMObjects(ActiveDOMObject::ReasonForSuspension why)
+void ContextLifecycleNotifier::notifySuspendingActiveDOMObjects()
{
TemporaryChange<IterationType> scope(this->m_iterating, IteratingOverActiveDOMObjects);
ActiveDOMObjectSet::iterator activeObjectsEnd = m_activeDOMObjects.end();
for (ActiveDOMObjectSet::iterator iter = m_activeDOMObjects.begin(); iter != activeObjectsEnd; ++iter) {
- ASSERT((*iter)->scriptExecutionContext() == context());
+ ASSERT((*iter)->executionContext() == context());
ASSERT((*iter)->suspendIfNeededCalled());
- (*iter)->suspend(why);
+ (*iter)->suspend();
}
}
@@ -91,26 +91,12 @@ void ContextLifecycleNotifier::notifyStoppingActiveDOMObjects()
TemporaryChange<IterationType> scope(this->m_iterating, IteratingOverActiveDOMObjects);
ActiveDOMObjectSet::iterator activeObjectsEnd = m_activeDOMObjects.end();
for (ActiveDOMObjectSet::iterator iter = m_activeDOMObjects.begin(); iter != activeObjectsEnd; ++iter) {
- ASSERT((*iter)->scriptExecutionContext() == context());
+ ASSERT((*iter)->executionContext() == context());
ASSERT((*iter)->suspendIfNeededCalled());
(*iter)->stop();
}
}
-bool ContextLifecycleNotifier::canSuspendActiveDOMObjects()
-{
- TemporaryChange<IterationType> scope(this->m_iterating, IteratingOverActiveDOMObjects);
- ActiveDOMObjectSet::iterator activeObjectsEnd = m_activeDOMObjects.end();
- for (ActiveDOMObjectSet::const_iterator iter = m_activeDOMObjects.begin(); iter != activeObjectsEnd; ++iter) {
- ASSERT((*iter)->scriptExecutionContext() == context());
- ASSERT((*iter)->suspendIfNeededCalled());
- if (!(*iter)->canSuspend())
- return false;
- }
-
- return true;
-}
-
bool ContextLifecycleNotifier::hasPendingActivity() const
{
ActiveDOMObjectSet::const_iterator activeObjectsEnd = activeDOMObjects().end();
@@ -123,4 +109,3 @@ bool ContextLifecycleNotifier::hasPendingActivity() const
}
} // namespace WebCore
-
diff --git a/chromium/third_party/WebKit/Source/core/dom/ContextLifecycleNotifier.h b/chromium/third_party/WebKit/Source/core/dom/ContextLifecycleNotifier.h
index 42a61f3e069..93d85407c1e 100644
--- a/chromium/third_party/WebKit/Source/core/dom/ContextLifecycleNotifier.h
+++ b/chromium/third_party/WebKit/Source/core/dom/ContextLifecycleNotifier.h
@@ -28,7 +28,7 @@
#define ContextLifecycleNotifier_h
#include "core/dom/ActiveDOMObject.h"
-#include "core/platform/LifecycleNotifier.h"
+#include "platform/LifecycleNotifier.h"
#include "wtf/HashSet.h"
#include "wtf/PassOwnPtr.h"
@@ -36,11 +36,11 @@ namespace WebCore {
class ActiveDOMObject;
class ContextLifecycleObserver;
-class ScriptExecutionContext;
+class ExecutionContext;
-class ContextLifecycleNotifier : public LifecycleNotifier {
+class ContextLifecycleNotifier : public LifecycleNotifier<ExecutionContext> {
public:
- static PassOwnPtr<ContextLifecycleNotifier> create(ScriptExecutionContext*);
+ static PassOwnPtr<ContextLifecycleNotifier> create(ExecutionContext*);
virtual ~ContextLifecycleNotifier();
@@ -48,25 +48,24 @@ public:
const ActiveDOMObjectSet& activeDOMObjects() const { return m_activeDOMObjects; }
- virtual void addObserver(LifecycleObserver*) OVERRIDE;
- virtual void removeObserver(LifecycleObserver*) OVERRIDE;
+ virtual void addObserver(Observer*) OVERRIDE;
+ virtual void removeObserver(Observer*) OVERRIDE;
void notifyResumingActiveDOMObjects();
- void notifySuspendingActiveDOMObjects(ActiveDOMObject::ReasonForSuspension);
+ void notifySuspendingActiveDOMObjects();
void notifyStoppingActiveDOMObjects();
bool contains(ActiveDOMObject* object) const { return m_activeDOMObjects.contains(object); }
- bool canSuspendActiveDOMObjects();
bool hasPendingActivity() const;
protected:
- explicit ContextLifecycleNotifier(ScriptExecutionContext*);
+ explicit ContextLifecycleNotifier(ExecutionContext*);
private:
ActiveDOMObjectSet m_activeDOMObjects;
};
-inline PassOwnPtr<ContextLifecycleNotifier> ContextLifecycleNotifier::create(ScriptExecutionContext* context)
+inline PassOwnPtr<ContextLifecycleNotifier> ContextLifecycleNotifier::create(ExecutionContext* context)
{
return adoptPtr(new ContextLifecycleNotifier(context));
}
diff --git a/chromium/third_party/WebKit/Source/core/dom/ContextLifecycleObserver.cpp b/chromium/third_party/WebKit/Source/core/dom/ContextLifecycleObserver.cpp
index be2d6c4ff96..b534648f4d8 100644
--- a/chromium/third_party/WebKit/Source/core/dom/ContextLifecycleObserver.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/ContextLifecycleObserver.cpp
@@ -27,22 +27,27 @@
#include "config.h"
#include "core/dom/ContextLifecycleObserver.h"
-#include "core/dom/ScriptExecutionContext.h"
+#include "core/dom/ExecutionContext.h"
namespace WebCore {
-ContextLifecycleObserver::ContextLifecycleObserver(ScriptExecutionContext* scriptExecutionContext, Type type)
- : LifecycleObserver(scriptExecutionContext, type)
+template<> void observerContext(ExecutionContext* context, LifecycleObserver<ExecutionContext>* observer)
{
+ context->wasObservedBy(observer);
}
-ContextLifecycleObserver::~ContextLifecycleObserver()
+template<> void unobserverContext(ExecutionContext* context, LifecycleObserver<ExecutionContext>* observer)
{
+ context->wasUnobservedBy(observer);
}
-ScriptExecutionContext* ContextLifecycleObserver::scriptExecutionContext() const
+ContextLifecycleObserver::ContextLifecycleObserver(ExecutionContext* executionContext, Type type)
+ : LifecycleObserver<ExecutionContext>(executionContext, type)
+{
+}
+
+ContextLifecycleObserver::~ContextLifecycleObserver()
{
- return static_cast<ScriptExecutionContext*>(m_lifecycleContext);
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/ContextLifecycleObserver.h b/chromium/third_party/WebKit/Source/core/dom/ContextLifecycleObserver.h
index c48a1ed7b97..adde88c5574 100644
--- a/chromium/third_party/WebKit/Source/core/dom/ContextLifecycleObserver.h
+++ b/chromium/third_party/WebKit/Source/core/dom/ContextLifecycleObserver.h
@@ -27,17 +27,19 @@
#ifndef ContextLifecycleObserver_h
#define ContextLifecycleObserver_h
-#include "core/platform/LifecycleObserver.h"
+#include "platform/LifecycleContext.h"
namespace WebCore {
-class ScriptExecutionContext;
+class ExecutionContext;
-class ContextLifecycleObserver : public LifecycleObserver {
-public:
- explicit ContextLifecycleObserver(ScriptExecutionContext*, Type = GenericType);
- ScriptExecutionContext* scriptExecutionContext() const;
+template<> void observerContext(ExecutionContext*, LifecycleObserver<ExecutionContext>*);
+template<> void unobserverContext(ExecutionContext*, LifecycleObserver<ExecutionContext>*);
+class ContextLifecycleObserver : public LifecycleObserver<ExecutionContext> {
+public:
+ explicit ContextLifecycleObserver(ExecutionContext*, Type = GenericType);
+ ExecutionContext* executionContext() const { return lifecycleContext(); }
protected:
virtual ~ContextLifecycleObserver();
};
diff --git a/chromium/third_party/WebKit/Source/core/dom/CrossThreadTask.h b/chromium/third_party/WebKit/Source/core/dom/CrossThreadTask.h
index 22864b8a4ca..9902ebdcefd 100644
--- a/chromium/third_party/WebKit/Source/core/dom/CrossThreadTask.h
+++ b/chromium/third_party/WebKit/Source/core/dom/CrossThreadTask.h
@@ -31,8 +31,9 @@
#ifndef CrossThreadTask_h
#define CrossThreadTask_h
-#include "core/dom/ScriptExecutionContext.h"
-#include "core/platform/CrossThreadCopier.h"
+#include "core/dom/ExecutionContext.h"
+#include "core/dom/ExecutionContextTask.h"
+#include "platform/CrossThreadCopier.h"
#include "wtf/PassOwnPtr.h"
#include "wtf/PassRefPtr.h"
#include "wtf/TypeTraits.h"
@@ -57,9 +58,9 @@ template<typename T> struct CrossThreadTaskTraits<PassOwnPtr<T> > {
};
template<typename P1, typename MP1>
-class CrossThreadTask1 : public ScriptExecutionContext::Task {
+class CrossThreadTask1 : public ExecutionContextTask {
public:
- typedef void (*Method)(ScriptExecutionContext*, MP1);
+ typedef void (*Method)(ExecutionContext*, MP1);
typedef CrossThreadTask1<P1, MP1> CrossThreadTask;
typedef typename CrossThreadTaskTraits<P1>::ParamType Param1;
@@ -75,7 +76,7 @@ private:
{
}
- virtual void performTask(ScriptExecutionContext* context)
+ virtual void performTask(ExecutionContext* context)
{
(*m_method)(context, m_parameter1);
}
@@ -86,9 +87,9 @@ private:
};
template<typename P1, typename MP1, typename P2, typename MP2>
-class CrossThreadTask2 : public ScriptExecutionContext::Task {
+class CrossThreadTask2 : public ExecutionContextTask {
public:
- typedef void (*Method)(ScriptExecutionContext*, MP1, MP2);
+ typedef void (*Method)(ExecutionContext*, MP1, MP2);
typedef CrossThreadTask2<P1, MP1, P2, MP2> CrossThreadTask;
typedef typename CrossThreadTaskTraits<P1>::ParamType Param1;
typedef typename CrossThreadTaskTraits<P2>::ParamType Param2;
@@ -106,7 +107,7 @@ private:
{
}
- virtual void performTask(ScriptExecutionContext* context)
+ virtual void performTask(ExecutionContext* context)
{
(*m_method)(context, m_parameter1, m_parameter2);
}
@@ -118,9 +119,9 @@ private:
};
template<typename P1, typename MP1, typename P2, typename MP2, typename P3, typename MP3>
-class CrossThreadTask3 : public ScriptExecutionContext::Task {
+class CrossThreadTask3 : public ExecutionContextTask {
public:
- typedef void (*Method)(ScriptExecutionContext*, MP1, MP2, MP3);
+ typedef void (*Method)(ExecutionContext*, MP1, MP2, MP3);
typedef CrossThreadTask3<P1, MP1, P2, MP2, P3, MP3> CrossThreadTask;
typedef typename CrossThreadTaskTraits<P1>::ParamType Param1;
typedef typename CrossThreadTaskTraits<P2>::ParamType Param2;
@@ -140,7 +141,7 @@ private:
{
}
- virtual void performTask(ScriptExecutionContext* context)
+ virtual void performTask(ExecutionContext* context)
{
(*m_method)(context, m_parameter1, m_parameter2, m_parameter3);
}
@@ -153,9 +154,9 @@ private:
};
template<typename P1, typename MP1, typename P2, typename MP2, typename P3, typename MP3, typename P4, typename MP4>
-class CrossThreadTask4 : public ScriptExecutionContext::Task {
+class CrossThreadTask4 : public ExecutionContextTask {
public:
- typedef void (*Method)(ScriptExecutionContext*, MP1, MP2, MP3, MP4);
+ typedef void (*Method)(ExecutionContext*, MP1, MP2, MP3, MP4);
typedef CrossThreadTask4<P1, MP1, P2, MP2, P3, MP3, P4, MP4> CrossThreadTask;
typedef typename CrossThreadTaskTraits<P1>::ParamType Param1;
typedef typename CrossThreadTaskTraits<P2>::ParamType Param2;
@@ -177,7 +178,7 @@ private:
{
}
- virtual void performTask(ScriptExecutionContext* context)
+ virtual void performTask(ExecutionContext* context)
{
(*m_method)(context, m_parameter1, m_parameter2, m_parameter3, m_parameter4);
}
@@ -191,9 +192,9 @@ private:
};
template<typename P1, typename MP1, typename P2, typename MP2, typename P3, typename MP3, typename P4, typename MP4, typename P5, typename MP5>
-class CrossThreadTask5 : public ScriptExecutionContext::Task {
+class CrossThreadTask5 : public ExecutionContextTask {
public:
- typedef void (*Method)(ScriptExecutionContext*, MP1, MP2, MP3, MP4, MP5);
+ typedef void (*Method)(ExecutionContext*, MP1, MP2, MP3, MP4, MP5);
typedef CrossThreadTask5<P1, MP1, P2, MP2, P3, MP3, P4, MP4, P5, MP5> CrossThreadTask;
typedef typename CrossThreadTaskTraits<P1>::ParamType Param1;
typedef typename CrossThreadTaskTraits<P2>::ParamType Param2;
@@ -217,7 +218,7 @@ private:
{
}
- virtual void performTask(ScriptExecutionContext* context)
+ virtual void performTask(ExecutionContext* context)
{
(*m_method)(context, m_parameter1, m_parameter2, m_parameter3, m_parameter4, m_parameter5);
}
@@ -232,9 +233,9 @@ private:
};
template<typename P1, typename MP1, typename P2, typename MP2, typename P3, typename MP3, typename P4, typename MP4, typename P5, typename MP5, typename P6, typename MP6>
-class CrossThreadTask6 : public ScriptExecutionContext::Task {
+class CrossThreadTask6 : public ExecutionContextTask {
public:
- typedef void (*Method)(ScriptExecutionContext*, MP1, MP2, MP3, MP4, MP5, MP6);
+ typedef void (*Method)(ExecutionContext*, MP1, MP2, MP3, MP4, MP5, MP6);
typedef CrossThreadTask6<P1, MP1, P2, MP2, P3, MP3, P4, MP4, P5, MP5, P6, MP6> CrossThreadTask;
typedef typename CrossThreadTaskTraits<P1>::ParamType Param1;
typedef typename CrossThreadTaskTraits<P2>::ParamType Param2;
@@ -260,7 +261,7 @@ private:
{
}
- virtual void performTask(ScriptExecutionContext* context)
+ virtual void performTask(ExecutionContext* context)
{
(*m_method)(context, m_parameter1, m_parameter2, m_parameter3, m_parameter4, m_parameter5, m_parameter6);
}
@@ -276,9 +277,9 @@ private:
};
template<typename P1, typename MP1, typename P2, typename MP2, typename P3, typename MP3, typename P4, typename MP4, typename P5, typename MP5, typename P6, typename MP6, typename P7, typename MP7>
-class CrossThreadTask7 : public ScriptExecutionContext::Task {
+class CrossThreadTask7 : public ExecutionContextTask {
public:
- typedef void (*Method)(ScriptExecutionContext*, MP1, MP2, MP3, MP4, MP5, MP6, MP7);
+ typedef void (*Method)(ExecutionContext*, MP1, MP2, MP3, MP4, MP5, MP6, MP7);
typedef CrossThreadTask7<P1, MP1, P2, MP2, P3, MP3, P4, MP4, P5, MP5, P6, MP6, P7, MP7> CrossThreadTask;
typedef typename CrossThreadTaskTraits<P1>::ParamType Param1;
typedef typename CrossThreadTaskTraits<P2>::ParamType Param2;
@@ -306,7 +307,7 @@ private:
{
}
- virtual void performTask(ScriptExecutionContext* context)
+ virtual void performTask(ExecutionContext* context)
{
(*m_method)(context, m_parameter1, m_parameter2, m_parameter3, m_parameter4, m_parameter5, m_parameter6, m_parameter7);
}
@@ -323,9 +324,9 @@ private:
};
template<typename P1, typename MP1, typename P2, typename MP2, typename P3, typename MP3, typename P4, typename MP4, typename P5, typename MP5, typename P6, typename MP6, typename P7, typename MP7, typename P8, typename MP8>
-class CrossThreadTask8 : public ScriptExecutionContext::Task {
+class CrossThreadTask8 : public ExecutionContextTask {
public:
- typedef void (*Method)(ScriptExecutionContext*, MP1, MP2, MP3, MP4, MP5, MP6, MP7, MP8);
+ typedef void (*Method)(ExecutionContext*, MP1, MP2, MP3, MP4, MP5, MP6, MP7, MP8);
typedef CrossThreadTask8<P1, MP1, P2, MP2, P3, MP3, P4, MP4, P5, MP5, P6, MP6, P7, MP7, P8, MP8> CrossThreadTask;
typedef typename CrossThreadTaskTraits<P1>::ParamType Param1;
typedef typename CrossThreadTaskTraits<P2>::ParamType Param2;
@@ -355,7 +356,7 @@ private:
{
}
- virtual void performTask(ScriptExecutionContext* context)
+ virtual void performTask(ExecutionContext* context)
{
(*m_method)(context, m_parameter1, m_parameter2, m_parameter3, m_parameter4, m_parameter5, m_parameter6, m_parameter7, m_parameter8);
}
@@ -373,8 +374,8 @@ private:
};
template<typename P1, typename MP1>
-PassOwnPtr<ScriptExecutionContext::Task> createCallbackTask(
- void (*method)(ScriptExecutionContext*, MP1),
+PassOwnPtr<ExecutionContextTask> createCallbackTask(
+ void (*method)(ExecutionContext*, MP1),
const P1& parameter1)
{
return CrossThreadTask1<typename CrossThreadCopier<P1>::Type, MP1>::create(
@@ -383,8 +384,8 @@ PassOwnPtr<ScriptExecutionContext::Task> createCallbackTask(
}
template<typename P1, typename MP1, typename P2, typename MP2>
-PassOwnPtr<ScriptExecutionContext::Task> createCallbackTask(
- void (*method)(ScriptExecutionContext*, MP1, MP2),
+PassOwnPtr<ExecutionContextTask> createCallbackTask(
+ void (*method)(ExecutionContext*, MP1, MP2),
const P1& parameter1, const P2& parameter2)
{
return CrossThreadTask2<typename CrossThreadCopier<P1>::Type, MP1, typename CrossThreadCopier<P2>::Type, MP2>::create(
@@ -393,8 +394,8 @@ PassOwnPtr<ScriptExecutionContext::Task> createCallbackTask(
}
template<typename P1, typename MP1, typename P2, typename MP2, typename P3, typename MP3>
-PassOwnPtr<ScriptExecutionContext::Task> createCallbackTask(
- void (*method)(ScriptExecutionContext*, MP1, MP2, MP3),
+PassOwnPtr<ExecutionContextTask> createCallbackTask(
+ void (*method)(ExecutionContext*, MP1, MP2, MP3),
const P1& parameter1, const P2& parameter2, const P3& parameter3)
{
return CrossThreadTask3<typename CrossThreadCopier<P1>::Type, MP1, typename CrossThreadCopier<P2>::Type, MP2, typename CrossThreadCopier<P3>::Type, MP3>::create(
@@ -404,8 +405,8 @@ PassOwnPtr<ScriptExecutionContext::Task> createCallbackTask(
}
template<typename P1, typename MP1, typename P2, typename MP2, typename P3, typename MP3, typename P4, typename MP4>
-PassOwnPtr<ScriptExecutionContext::Task> createCallbackTask(
- void (*method)(ScriptExecutionContext*, MP1, MP2, MP3, MP4),
+PassOwnPtr<ExecutionContextTask> createCallbackTask(
+ void (*method)(ExecutionContext*, MP1, MP2, MP3, MP4),
const P1& parameter1, const P2& parameter2, const P3& parameter3, const P4& parameter4)
{
return CrossThreadTask4<typename CrossThreadCopier<P1>::Type, MP1, typename CrossThreadCopier<P2>::Type, MP2, typename CrossThreadCopier<P3>::Type, MP3,
@@ -416,8 +417,8 @@ PassOwnPtr<ScriptExecutionContext::Task> createCallbackTask(
}
template<typename P1, typename MP1, typename P2, typename MP2, typename P3, typename MP3, typename P4, typename MP4, typename P5, typename MP5>
-PassOwnPtr<ScriptExecutionContext::Task> createCallbackTask(
- void (*method)(ScriptExecutionContext*, MP1, MP2, MP3, MP4, MP5),
+PassOwnPtr<ExecutionContextTask> createCallbackTask(
+ void (*method)(ExecutionContext*, MP1, MP2, MP3, MP4, MP5),
const P1& parameter1, const P2& parameter2, const P3& parameter3, const P4& parameter4, const P5& parameter5)
{
return CrossThreadTask5<typename CrossThreadCopier<P1>::Type, MP1, typename CrossThreadCopier<P2>::Type, MP2, typename CrossThreadCopier<P3>::Type, MP3,
@@ -429,8 +430,8 @@ PassOwnPtr<ScriptExecutionContext::Task> createCallbackTask(
}
template<typename P1, typename MP1, typename P2, typename MP2, typename P3, typename MP3, typename P4, typename MP4, typename P5, typename MP5, typename P6, typename MP6>
-PassOwnPtr<ScriptExecutionContext::Task> createCallbackTask(
- void (*method)(ScriptExecutionContext*, MP1, MP2, MP3, MP4, MP5, MP6),
+PassOwnPtr<ExecutionContextTask> createCallbackTask(
+ void (*method)(ExecutionContext*, MP1, MP2, MP3, MP4, MP5, MP6),
const P1& parameter1, const P2& parameter2, const P3& parameter3, const P4& parameter4, const P5& parameter5, const P6& parameter6)
{
return CrossThreadTask6<typename CrossThreadCopier<P1>::Type, MP1, typename CrossThreadCopier<P2>::Type, MP2, typename CrossThreadCopier<P3>::Type, MP3,
@@ -442,8 +443,8 @@ PassOwnPtr<ScriptExecutionContext::Task> createCallbackTask(
}
template<typename P1, typename MP1, typename P2, typename MP2, typename P3, typename MP3, typename P4, typename MP4, typename P5, typename MP5, typename P6, typename MP6, typename P7, typename MP7>
-PassOwnPtr<ScriptExecutionContext::Task> createCallbackTask(
- void (*method)(ScriptExecutionContext*, MP1, MP2, MP3, MP4, MP5, MP6, MP7),
+PassOwnPtr<ExecutionContextTask> createCallbackTask(
+ void (*method)(ExecutionContext*, MP1, MP2, MP3, MP4, MP5, MP6, MP7),
const P1& parameter1, const P2& parameter2, const P3& parameter3, const P4& parameter4, const P5& parameter5, const P6& parameter6, const P7& parameter7)
{
return CrossThreadTask7<typename CrossThreadCopier<P1>::Type, MP1, typename CrossThreadCopier<P2>::Type, MP2, typename CrossThreadCopier<P3>::Type, MP3,
@@ -457,9 +458,9 @@ PassOwnPtr<ScriptExecutionContext::Task> createCallbackTask(
}
template<typename P1, typename MP1, typename P2, typename MP2, typename P3, typename MP3, typename P4, typename MP4, typename P5, typename MP5, typename P6, typename MP6, typename P7, typename MP7, typename P8, typename MP8>
-PassOwnPtr<ScriptExecutionContext::Task> createCallbackTask(
- void (*method)(ScriptExecutionContext*, MP1, MP2, MP3, MP4, MP5, MP6, MP7, MP8),
- const P1& parameter1, const P2& parameter2, const P3& parameter3, const P4& parameter4, const P5& parameter5, const P6& parameter6, const P7& parameter7, const P8& parameter8)
+PassOwnPtr<ExecutionContextTask> createCallbackTask(
+ void (*method)(ExecutionContext*, MP1, MP2, MP3, MP4, MP5, MP6, MP7, MP8),
+ const P1& parameter1, const P2& parameter2, const P3& parameter3, const P4& parameter4, const P5& parameter5, const P6& parameter6, const P7& parameter7, const P8& parameter8)
{
return CrossThreadTask8<typename CrossThreadCopier<P1>::Type, MP1, typename CrossThreadCopier<P2>::Type, MP2, typename CrossThreadCopier<P3>::Type, MP3,
typename CrossThreadCopier<P4>::Type, MP4, typename CrossThreadCopier<P5>::Type, MP5, typename CrossThreadCopier<P6>::Type, MP6,
diff --git a/chromium/third_party/WebKit/Source/core/dom/CustomElement.cpp b/chromium/third_party/WebKit/Source/core/dom/CustomElement.cpp
deleted file mode 100644
index d09bafcbea6..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/CustomElement.cpp
+++ /dev/null
@@ -1,180 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * 3. Neither the name of Google Inc. nor the names of its contributors
- * may be used to endorse or promote products derived from this
- * software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/dom/CustomElement.h"
-
-#include "HTMLNames.h"
-#include "MathMLNames.h"
-#include "RuntimeEnabledFeatures.h"
-#include "SVGNames.h"
-#include "core/dom/CustomElementCallbackScheduler.h"
-#include "core/dom/CustomElementObserver.h"
-#include "core/dom/Element.h"
-
-namespace WebCore {
-
-Vector<AtomicString>& CustomElement::embedderCustomElementNames()
-{
- DEFINE_STATIC_LOCAL(Vector<AtomicString>, names, ());
- return names;
-}
-
-void CustomElement::addEmbedderCustomElementName(const AtomicString& name)
-{
- AtomicString lower = name.lower();
- if (isValidName(lower, EmbedderNames))
- return;
- embedderCustomElementNames().append(lower);
-}
-
-static CustomElement::NameSet enabledNameSet()
-{
- return CustomElement::NameSet((RuntimeEnabledFeatures::customElementsEnabled() ? CustomElement::StandardNames : 0) | (RuntimeEnabledFeatures::embedderCustomElementsEnabled() ? CustomElement::EmbedderNames : 0));
-}
-
-bool CustomElement::isValidName(const AtomicString& name, NameSet validNames)
-{
- validNames = NameSet(validNames & enabledNameSet());
-
- if ((validNames & EmbedderNames) && kNotFound != embedderCustomElementNames().find(name))
- return Document::isValidName(name);
-
- if ((validNames & StandardNames) && kNotFound != name.find('-')) {
- DEFINE_STATIC_LOCAL(Vector<AtomicString>, reservedNames, ());
- if (reservedNames.isEmpty()) {
- reservedNames.append(MathMLNames::annotation_xmlTag.localName());
- reservedNames.append(SVGNames::color_profileTag.localName());
- reservedNames.append(SVGNames::font_faceTag.localName());
- reservedNames.append(SVGNames::font_face_srcTag.localName());
- reservedNames.append(SVGNames::font_face_uriTag.localName());
- reservedNames.append(SVGNames::font_face_formatTag.localName());
- reservedNames.append(SVGNames::font_face_nameTag.localName());
- reservedNames.append(SVGNames::missing_glyphTag.localName());
- }
-
- if (kNotFound == reservedNames.find(name))
- return Document::isValidName(name.string());
- }
-
- return false;
-}
-
-void CustomElement::define(Element* element, PassRefPtr<CustomElementDefinition> passDefinition)
-{
- RefPtr<CustomElementDefinition> definition(passDefinition);
-
- switch (element->customElementState()) {
- case Element::NotCustomElement:
- case Element::Upgraded:
- ASSERT_NOT_REACHED();
- break;
-
- case Element::WaitingForParser:
- definitions().add(element, definition);
- break;
-
- case Element::WaitingForUpgrade:
- definitions().add(element, definition);
- CustomElementCallbackScheduler::scheduleCreatedCallback(definition->callbacks(), element);
- break;
- }
-}
-
-CustomElementDefinition* CustomElement::definitionFor(Element* element)
-{
- CustomElementDefinition* definition = definitions().get(element);
- ASSERT(definition);
- return definition;
-}
-
-void CustomElement::didFinishParsingChildren(Element* element)
-{
- ASSERT(element->customElementState() == Element::WaitingForParser);
- element->setCustomElementState(Element::WaitingForUpgrade);
-
- CustomElementObserver::notifyElementDidFinishParsingChildren(element);
-
- if (CustomElementDefinition* definition = definitions().get(element))
- CustomElementCallbackScheduler::scheduleCreatedCallback(definition->callbacks(), element);
-}
-
-void CustomElement::attributeDidChange(Element* element, const AtomicString& name, const AtomicString& oldValue, const AtomicString& newValue)
-{
- ASSERT(element->customElementState() == Element::Upgraded);
- CustomElementCallbackScheduler::scheduleAttributeChangedCallback(definitionFor(element)->callbacks(), element, name, oldValue, newValue);
-}
-
-void CustomElement::didEnterDocument(Element* element, const Document& document)
-{
- ASSERT(element->customElementState() == Element::Upgraded);
- if (!document.defaultView())
- return;
- CustomElementCallbackScheduler::scheduleEnteredViewCallback(definitionFor(element)->callbacks(), element);
-}
-
-void CustomElement::didLeaveDocument(Element* element, const Document& document)
-{
- ASSERT(element->customElementState() == Element::Upgraded);
- if (!document.defaultView())
- return;
- CustomElementCallbackScheduler::scheduleLeftViewCallback(definitionFor(element)->callbacks(), element);
-}
-
-void CustomElement::wasDestroyed(Element* element)
-{
- switch (element->customElementState()) {
- case Element::NotCustomElement:
- ASSERT_NOT_REACHED();
- break;
-
- case Element::WaitingForParser:
- case Element::WaitingForUpgrade:
- case Element::Upgraded:
- definitions().remove(element);
- CustomElementObserver::notifyElementWasDestroyed(element);
- break;
- }
-}
-
-void CustomElement::DefinitionMap::add(Element* element, PassRefPtr<CustomElementDefinition> definition)
-{
- ASSERT(definition.get());
- DefinitionMap::ElementDefinitionHashMap::AddResult result = m_definitions.add(element, definition);
- ASSERT(result.isNewEntry);
-}
-
-CustomElement::DefinitionMap& CustomElement::definitions()
-{
- DEFINE_STATIC_LOCAL(DefinitionMap, map, ());
- return map;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/CustomElement.h b/chromium/third_party/WebKit/Source/core/dom/CustomElement.h
deleted file mode 100644
index 3e66512558e..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/CustomElement.h
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * 3. Neither the name of Google Inc. nor the names of its contributors
- * may be used to endorse or promote products derived from this
- * software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef CustomElement_h
-#define CustomElement_h
-
-#include "core/dom/CustomElementDefinition.h"
-#include "wtf/HashMap.h"
-#include "wtf/Noncopyable.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefPtr.h"
-#include "wtf/Vector.h"
-#include "wtf/text/AtomicString.h"
-
-namespace WebCore {
-
-class Document;
-class Element;
-
-class CustomElement {
-public:
- enum NameSet {
- EmbedderNames = 1 << 0,
- StandardNames = 1 << 1,
- AllNames = EmbedderNames | StandardNames
- };
- static bool isValidName(const AtomicString& name, NameSet validNames = AllNames);
- static void addEmbedderCustomElementName(const AtomicString& name);
-
- // API for registration contexts
- static void define(Element*, PassRefPtr<CustomElementDefinition>);
-
- // API for wrapper creation, which uses a definition as a key
- static CustomElementDefinition* definitionFor(Element*);
-
- // API for Element to kick off changes
-
- static void didFinishParsingChildren(Element*);
- static void attributeDidChange(Element*, const AtomicString& name, const AtomicString& oldValue, const AtomicString& newValue);
- static void didEnterDocument(Element*, const Document&);
- static void didLeaveDocument(Element*, const Document&);
- static void wasDestroyed(Element*);
-
-private:
- CustomElement();
-
- static Vector<AtomicString>& embedderCustomElementNames();
-
- // Maps resolved elements to their definitions
-
- class DefinitionMap {
- WTF_MAKE_NONCOPYABLE(DefinitionMap);
- public:
- DefinitionMap() { }
- ~DefinitionMap() { }
-
- void add(Element*, PassRefPtr<CustomElementDefinition>);
- void remove(Element* element) { m_definitions.remove(element); }
- CustomElementDefinition* get(Element* element) const { return m_definitions.get(element); }
-
- private:
- typedef HashMap<Element*, RefPtr<CustomElementDefinition> > ElementDefinitionHashMap;
- ElementDefinitionHashMap m_definitions;
- };
- static DefinitionMap& definitions();
-};
-
-}
-
-#endif // CustomElement_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/CustomElementCallbackDispatcher.cpp b/chromium/third_party/WebKit/Source/core/dom/CustomElementCallbackDispatcher.cpp
deleted file mode 100644
index 9ae56c4d290..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/CustomElementCallbackDispatcher.cpp
+++ /dev/null
@@ -1,124 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * 3. Neither the name of Google Inc. nor the names of its contributors
- * may be used to endorse or promote products derived from this
- * software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/dom/CustomElementCallbackDispatcher.h"
-
-#include "core/dom/CustomElementCallbackQueue.h"
-#include "core/dom/CustomElementCallbackScheduler.h"
-#include "wtf/MainThread.h"
-
-namespace WebCore {
-
-size_t CustomElementCallbackDispatcher::s_elementQueueStart = 0;
-
-// The base of the stack has a null sentinel value.
-size_t CustomElementCallbackDispatcher::s_elementQueueEnd = kNumSentinels;
-
-CustomElementCallbackDispatcher& CustomElementCallbackDispatcher::instance()
-{
- DEFINE_STATIC_LOCAL(CustomElementCallbackDispatcher, instance, ());
- return instance;
-}
-
-// Dispatches callbacks at microtask checkpoint.
-bool CustomElementCallbackDispatcher::dispatch()
-{
- ASSERT(isMainThread());
- if (inCallbackDeliveryScope())
- return false;
-
- size_t start = kNumSentinels; // skip null sentinel
- size_t end = s_elementQueueEnd;
- ElementQueue thisQueue = currentElementQueue();
-
- for (size_t i = start; i < end; i++) {
- {
- // The created callback may schedule entered document
- // callbacks.
- CallbackDeliveryScope deliveryScope;
- m_flattenedProcessingStack[i]->processInElementQueue(thisQueue);
- }
-
- ASSERT(!s_elementQueueStart);
- ASSERT(s_elementQueueEnd == end);
- }
-
- s_elementQueueEnd = kNumSentinels;
- m_flattenedProcessingStack.resize(s_elementQueueEnd);
-
- CustomElementCallbackScheduler::clearElementCallbackQueueMap();
-
- bool didWork = start < end;
- return didWork;
-}
-
-// Dispatches callbacks when popping the processing stack.
-void CustomElementCallbackDispatcher::processElementQueueAndPop()
-{
- instance().processElementQueueAndPop(s_elementQueueStart, s_elementQueueEnd);
-}
-
-void CustomElementCallbackDispatcher::processElementQueueAndPop(size_t start, size_t end)
-{
- ASSERT(isMainThread());
- ElementQueue thisQueue = currentElementQueue();
-
- for (size_t i = start; i < end; i++) {
- {
- // The created callback may schedule entered document
- // callbacks.
- CallbackDeliveryScope deliveryScope;
- m_flattenedProcessingStack[i]->processInElementQueue(thisQueue);
- }
-
- ASSERT(start == s_elementQueueStart);
- ASSERT(end == s_elementQueueEnd);
- }
-
- // Pop the element queue from the processing stack
- m_flattenedProcessingStack.resize(start);
- s_elementQueueEnd = start;
-
- if (start == kNumSentinels)
- CustomElementCallbackScheduler::clearElementCallbackQueueMap();
-}
-
-void CustomElementCallbackDispatcher::enqueue(CustomElementCallbackQueue* callbackQueue)
-{
- if (callbackQueue->owner() == currentElementQueue())
- return;
-
- callbackQueue->setOwner(currentElementQueue());
- m_flattenedProcessingStack.append(callbackQueue);
- ++s_elementQueueEnd;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/CustomElementCallbackDispatcher.h b/chromium/third_party/WebKit/Source/core/dom/CustomElementCallbackDispatcher.h
deleted file mode 100644
index 12301797dfb..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/CustomElementCallbackDispatcher.h
+++ /dev/null
@@ -1,114 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * 3. Neither the name of Google Inc. nor the names of its contributors
- * may be used to endorse or promote products derived from this
- * software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef CustomElementCallbackDispatcher_h
-#define CustomElementCallbackDispatcher_h
-
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-class CustomElementCallbackQueue;
-class CustomElementCallbackScheduler;
-
-class CustomElementCallbackDispatcher {
- WTF_MAKE_NONCOPYABLE(CustomElementCallbackDispatcher);
-public:
- static CustomElementCallbackDispatcher& instance();
-
- // This is stack allocated in many DOM callbacks. Make it cheap.
- class CallbackDeliveryScope {
- public:
- CallbackDeliveryScope()
- : m_savedElementQueueStart(s_elementQueueStart)
- {
- s_elementQueueStart = s_elementQueueEnd;
- }
-
- ~CallbackDeliveryScope()
- {
- if (s_elementQueueStart != s_elementQueueEnd)
- processElementQueueAndPop();
- s_elementQueueStart = m_savedElementQueueStart;
- }
-
- private:
- size_t m_savedElementQueueStart;
- };
-
- // Returns true if more work may have to be performed at the
- // checkpoint by this or other workers (for example, this work
- // invoked author scripts)
- bool dispatch();
-
-protected:
- friend class CustomElementCallbackScheduler;
- void enqueue(CustomElementCallbackQueue*);
-
-private:
- CustomElementCallbackDispatcher()
- {
- // Add a null element as a sentinel. This makes it possible to
- // identify elements queued when there is no
- // CallbackDeliveryScope active. Also, if the processing stack
- // is popped when empty, this sentinel will cause a null deref
- // crash.
- CustomElementCallbackQueue* sentinel = 0;
- for (size_t i = 0; i < kNumSentinels; i++)
- m_flattenedProcessingStack.append(sentinel);
- ASSERT(s_elementQueueEnd == m_flattenedProcessingStack.size());
- }
-
- // The start of the element queue on the top of the processing
- // stack. An offset into instance().m_flattenedProcessingStack.
- static size_t s_elementQueueStart;
-
- // The end of the element queue on the top of the processing
- // stack. A cache of instance().m_flattenedProcessingStack.size().
- static size_t s_elementQueueEnd;
-
- static bool inCallbackDeliveryScope() { return s_elementQueueStart; }
-
- typedef int ElementQueue;
- static ElementQueue currentElementQueue() { return ElementQueue(s_elementQueueStart); }
-
- static void processElementQueueAndPop();
- void processElementQueueAndPop(size_t start, size_t end);
-
- // The processing stack, flattened. Element queues lower in the
- // stack appear toward the head of the vector. The first element
- // is a null sentinel value.
- static const size_t kNumSentinels = 1;
- Vector<CustomElementCallbackQueue*> m_flattenedProcessingStack;
-};
-
-}
-
-#endif // CustomElementCallbackDispatcher_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/CustomElementCallbackInvocation.cpp b/chromium/third_party/WebKit/Source/core/dom/CustomElementCallbackInvocation.cpp
deleted file mode 100644
index 57298335aec..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/CustomElementCallbackInvocation.cpp
+++ /dev/null
@@ -1,135 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * 3. Neither the name of Google Inc. nor the names of its contributors
- * may be used to endorse or promote products derived from this
- * software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/dom/CustomElementCallbackInvocation.h"
-
-#include "core/dom/CustomElementCallbackScheduler.h"
-#include "core/dom/Element.h"
-
-namespace WebCore {
-
-class CreatedInvocation : public CustomElementCallbackInvocation {
-public:
- CreatedInvocation(PassRefPtr<CustomElementLifecycleCallbacks> callbacks)
- : CustomElementCallbackInvocation(callbacks)
- {
- }
-
-private:
- virtual void dispatch(Element*) OVERRIDE;
- virtual bool isCreated() const OVERRIDE { return true; }
-};
-
-void CreatedInvocation::dispatch(Element* element)
-{
- if (element->inDocument() && element->document().defaultView())
- CustomElementCallbackScheduler::scheduleEnteredViewCallback(callbacks(), element);
- callbacks()->created(element);
-}
-
-class EnteredLeftViewInvocation : public CustomElementCallbackInvocation {
-public:
- EnteredLeftViewInvocation(PassRefPtr<CustomElementLifecycleCallbacks>, CustomElementLifecycleCallbacks::CallbackType which);
-
-private:
- virtual void dispatch(Element*) OVERRIDE;
-
- CustomElementLifecycleCallbacks::CallbackType m_which;
-};
-
-EnteredLeftViewInvocation::EnteredLeftViewInvocation(PassRefPtr<CustomElementLifecycleCallbacks> callbacks, CustomElementLifecycleCallbacks::CallbackType which)
- : CustomElementCallbackInvocation(callbacks)
- , m_which(which)
-{
- ASSERT(m_which == CustomElementLifecycleCallbacks::EnteredView || m_which == CustomElementLifecycleCallbacks::LeftView);
-}
-
-void EnteredLeftViewInvocation::dispatch(Element* element)
-{
- switch (m_which) {
- case CustomElementLifecycleCallbacks::EnteredView:
- callbacks()->enteredView(element);
- break;
- case CustomElementLifecycleCallbacks::LeftView:
- callbacks()->leftView(element);
- break;
- default:
- ASSERT_NOT_REACHED();
- }
-}
-
-class AttributeChangedInvocation : public CustomElementCallbackInvocation {
-public:
- AttributeChangedInvocation(PassRefPtr<CustomElementLifecycleCallbacks>, const AtomicString& name, const AtomicString& oldValue, const AtomicString& newValue);
-
-private:
- virtual void dispatch(Element*) OVERRIDE;
-
- AtomicString m_name;
- AtomicString m_oldValue;
- AtomicString m_newValue;
-};
-
-AttributeChangedInvocation::AttributeChangedInvocation(PassRefPtr<CustomElementLifecycleCallbacks> callbacks, const AtomicString& name, const AtomicString& oldValue, const AtomicString& newValue)
- : CustomElementCallbackInvocation(callbacks)
- , m_name(name)
- , m_oldValue(oldValue)
- , m_newValue(newValue)
-{
-}
-
-void AttributeChangedInvocation::dispatch(Element* element)
-{
- callbacks()->attributeChanged(element, m_name, m_oldValue, m_newValue);
-}
-
-PassOwnPtr<CustomElementCallbackInvocation> CustomElementCallbackInvocation::createInvocation(PassRefPtr<CustomElementLifecycleCallbacks> callbacks, CustomElementLifecycleCallbacks::CallbackType which)
-{
- switch (which) {
- case CustomElementLifecycleCallbacks::Created:
- return adoptPtr(new CreatedInvocation(callbacks));
-
- case CustomElementLifecycleCallbacks::EnteredView:
- case CustomElementLifecycleCallbacks::LeftView:
- return adoptPtr(new EnteredLeftViewInvocation(callbacks, which));
-
- default:
- ASSERT_NOT_REACHED();
- return PassOwnPtr<CustomElementCallbackInvocation>();
- }
-}
-
-PassOwnPtr<CustomElementCallbackInvocation> CustomElementCallbackInvocation::createAttributeChangedInvocation(PassRefPtr<CustomElementLifecycleCallbacks> callbacks, const AtomicString& name, const AtomicString& oldValue, const AtomicString& newValue)
-{
- return adoptPtr(new AttributeChangedInvocation(callbacks, name, oldValue, newValue));
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/CustomElementCallbackInvocation.h b/chromium/third_party/WebKit/Source/core/dom/CustomElementCallbackInvocation.h
deleted file mode 100644
index d2f81356010..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/CustomElementCallbackInvocation.h
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * 3. Neither the name of Google Inc. nor the names of its contributors
- * may be used to endorse or promote products derived from this
- * software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef CustomElementCallbackInvocation_h
-#define CustomElementCallbackInvocation_h
-
-#include "core/dom/CustomElementLifecycleCallbacks.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefPtr.h"
-#include "wtf/text/AtomicString.h"
-
-namespace WebCore {
-
-class Element;
-
-class CustomElementCallbackInvocation {
- WTF_MAKE_NONCOPYABLE(CustomElementCallbackInvocation);
-public:
- static PassOwnPtr<CustomElementCallbackInvocation> createInvocation(PassRefPtr<CustomElementLifecycleCallbacks>, CustomElementLifecycleCallbacks::CallbackType);
- static PassOwnPtr<CustomElementCallbackInvocation> createAttributeChangedInvocation(PassRefPtr<CustomElementLifecycleCallbacks>, const AtomicString& name, const AtomicString& oldValue, const AtomicString& newValue);
-
- virtual ~CustomElementCallbackInvocation() { }
- virtual void dispatch(Element*) = 0;
- virtual bool isCreated() const { return false; }
-
-protected:
- CustomElementCallbackInvocation(PassRefPtr<CustomElementLifecycleCallbacks> callbacks)
- : m_callbacks(callbacks)
- {
- }
-
- CustomElementLifecycleCallbacks* callbacks() { return m_callbacks.get(); }
-
-private:
- RefPtr<CustomElementLifecycleCallbacks> m_callbacks;
-};
-
-}
-
-#endif // CustomElementCallbackInvocation_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/CustomElementCallbackQueue.cpp b/chromium/third_party/WebKit/Source/core/dom/CustomElementCallbackQueue.cpp
deleted file mode 100644
index 114b21fe37f..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/CustomElementCallbackQueue.cpp
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * 3. Neither the name of Google Inc. nor the names of its contributors
- * may be used to endorse or promote products derived from this
- * software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/dom/CustomElementCallbackQueue.h"
-
-namespace WebCore {
-
-PassOwnPtr<CustomElementCallbackQueue> CustomElementCallbackQueue::create(PassRefPtr<Element> element)
-{
- return adoptPtr(new CustomElementCallbackQueue(element));
-}
-
-CustomElementCallbackQueue::CustomElementCallbackQueue(PassRefPtr<Element> element)
- : m_element(element)
- , m_owner(-1)
- , m_index(0)
- , m_inCreatedCallback(false)
-{
-}
-
-void CustomElementCallbackQueue::processInElementQueue(ElementQueue caller)
-{
- ASSERT(!m_inCreatedCallback);
-
- while (m_index < m_queue.size() && owner() == caller) {
- m_inCreatedCallback = m_queue[m_index]->isCreated();
-
- // dispatch() may cause recursion which steals this callback
- // queue and reenters processInQueue. owner() == caller
- // detects this recursion and cedes processing.
- m_queue[m_index++]->dispatch(m_element.get());
- m_inCreatedCallback = false;
- }
-
- if (owner() == caller && m_index == m_queue.size()) {
- // This processInQueue exhausted the queue; shrink it.
- m_index = 0;
- m_queue.resize(0);
- m_owner = -1;
- }
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/CustomElementCallbackQueue.h b/chromium/third_party/WebKit/Source/core/dom/CustomElementCallbackQueue.h
deleted file mode 100644
index 9afdeedf111..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/CustomElementCallbackQueue.h
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * 3. Neither the name of Google Inc. nor the names of its contributors
- * may be used to endorse or promote products derived from this
- * software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef CustomElementCallbackQueue_h
-#define CustomElementCallbackQueue_h
-
-#include "core/dom/CustomElementCallbackInvocation.h"
-#include "core/dom/Element.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefPtr.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-class CustomElementCallbackQueue {
- WTF_MAKE_NONCOPYABLE(CustomElementCallbackQueue);
-public:
- static PassOwnPtr<CustomElementCallbackQueue> create(PassRefPtr<Element>);
-
- typedef int ElementQueue;
- ElementQueue owner() { return m_owner; }
- void setOwner(ElementQueue newOwner)
- {
- // ElementCallbackQueues only migrate towards the top of the
- // processing stack.
- ASSERT(newOwner >= m_owner);
- m_owner = newOwner;
- }
-
- void append(PassOwnPtr<CustomElementCallbackInvocation> invocation) { m_queue.append(invocation); }
- void processInElementQueue(ElementQueue);
- bool inCreatedCallback() const { return m_inCreatedCallback; }
-
-private:
- CustomElementCallbackQueue(PassRefPtr<Element>);
-
- RefPtr<Element> m_element;
- Vector<OwnPtr<CustomElementCallbackInvocation> > m_queue;
- ElementQueue m_owner;
- size_t m_index;
- bool m_inCreatedCallback;
-};
-
-}
-
-#endif // CustomElementCallbackQueue_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/CustomElementCallbackScheduler.cpp b/chromium/third_party/WebKit/Source/core/dom/CustomElementCallbackScheduler.cpp
deleted file mode 100644
index d6086cd6cac..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/CustomElementCallbackScheduler.cpp
+++ /dev/null
@@ -1,122 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * 3. Neither the name of Google Inc. nor the names of its contributors
- * may be used to endorse or promote products derived from this
- * software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/dom/CustomElementCallbackScheduler.h"
-
-#include "core/dom/CustomElementCallbackDispatcher.h"
-#include "core/dom/CustomElementCallbackQueue.h"
-#include "core/dom/CustomElementLifecycleCallbacks.h"
-#include "core/dom/Element.h"
-
-namespace WebCore {
-
-void CustomElementCallbackScheduler::scheduleAttributeChangedCallback(PassRefPtr<CustomElementLifecycleCallbacks> callbacks, PassRefPtr<Element> element, const AtomicString& name, const AtomicString& oldValue, const AtomicString& newValue)
-{
- if (!callbacks->hasAttributeChangedCallback())
- return;
-
- CustomElementCallbackQueue* queue = instance().schedule(element);
- queue->append(CustomElementCallbackInvocation::createAttributeChangedInvocation(callbacks, name, oldValue, newValue));
-}
-
-void CustomElementCallbackScheduler::scheduleCreatedCallback(PassRefPtr<CustomElementLifecycleCallbacks> callbacks, PassRefPtr<Element> element)
-{
- if (!callbacks->hasCreatedCallback())
- return;
-
- CustomElementCallbackQueue* queue = instance().scheduleInCurrentElementQueue(element);
- queue->append(CustomElementCallbackInvocation::createInvocation(callbacks, CustomElementLifecycleCallbacks::Created));
-}
-
-void CustomElementCallbackScheduler::scheduleEnteredViewCallback(PassRefPtr<CustomElementLifecycleCallbacks> callbacks, PassRefPtr<Element> element)
-{
- if (!callbacks->hasEnteredViewCallback())
- return;
-
- CustomElementCallbackQueue* queue = instance().schedule(element);
- queue->append(CustomElementCallbackInvocation::createInvocation(callbacks, CustomElementLifecycleCallbacks::EnteredView));
-}
-
-void CustomElementCallbackScheduler::scheduleLeftViewCallback(PassRefPtr<CustomElementLifecycleCallbacks> callbacks, PassRefPtr<Element> element)
-{
- if (!callbacks->hasLeftViewCallback())
- return;
-
- CustomElementCallbackQueue* queue = instance().schedule(element);
- queue->append(CustomElementCallbackInvocation::createInvocation(callbacks, CustomElementLifecycleCallbacks::LeftView));
-}
-
-CustomElementCallbackScheduler& CustomElementCallbackScheduler::instance()
-{
- DEFINE_STATIC_LOCAL(CustomElementCallbackScheduler, instance, ());
- return instance;
-}
-
-CustomElementCallbackQueue* CustomElementCallbackScheduler::ensureCallbackQueue(PassRefPtr<Element> element)
-{
- Element* key = element.get();
- ElementCallbackQueueMap::iterator it = m_elementCallbackQueueMap.find(key);
- if (it == m_elementCallbackQueueMap.end())
- it = m_elementCallbackQueueMap.add(key, CustomElementCallbackQueue::create(element)).iterator;
- return it->value.get();
-}
-
-void CustomElementCallbackScheduler::clearElementCallbackQueueMap()
-{
- ElementCallbackQueueMap emptyMap;
- instance().m_elementCallbackQueueMap.swap(emptyMap);
-}
-
-// Finds or creates the callback queue for element. If the
-// createdCallback has not finished running, the callback queue is not
-// moved to the top-of-stack. Otherwise like
-// scheduleInCurrentElementQueue.
-CustomElementCallbackQueue* CustomElementCallbackScheduler::schedule(PassRefPtr<Element> element)
-{
- CustomElementCallbackQueue* callbackQueue = ensureCallbackQueue(element);
- if (!callbackQueue->inCreatedCallback())
- CustomElementCallbackDispatcher::instance().enqueue(callbackQueue);
- return callbackQueue;
-}
-
-// Finds or creates the callback queue for element. If the element's
-// callback queue is scheduled in an earlier processing stack frame,
-// its owner is set to the element queue on the top of the processing
-// stack. Because callback queues are processed exhaustively, this
-// effectively moves the callback queue to the top of the stack.
-CustomElementCallbackQueue* CustomElementCallbackScheduler::scheduleInCurrentElementQueue(PassRefPtr<Element> element)
-{
- CustomElementCallbackQueue* callbackQueue = ensureCallbackQueue(element);
- CustomElementCallbackDispatcher::instance().enqueue(callbackQueue);
- return callbackQueue;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/CustomElementCallbackScheduler.h b/chromium/third_party/WebKit/Source/core/dom/CustomElementCallbackScheduler.h
deleted file mode 100644
index b0e757fedeb..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/CustomElementCallbackScheduler.h
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * 3. Neither the name of Google Inc. nor the names of its contributors
- * may be used to endorse or promote products derived from this
- * software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef CustomElementCallbackScheduler_h
-#define CustomElementCallbackScheduler_h
-
-#include "core/dom/CustomElementCallbackQueue.h"
-#include "wtf/HashMap.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/text/AtomicString.h"
-
-namespace WebCore {
-
-class CustomElementLifecycleCallbacks;
-class Element;
-
-class CustomElementCallbackScheduler {
-public:
- static void scheduleAttributeChangedCallback(PassRefPtr<CustomElementLifecycleCallbacks>, PassRefPtr<Element>, const AtomicString& name, const AtomicString& oldValue, const AtomicString& newValue);
- static void scheduleCreatedCallback(PassRefPtr<CustomElementLifecycleCallbacks>, PassRefPtr<Element>);
- static void scheduleEnteredViewCallback(PassRefPtr<CustomElementLifecycleCallbacks>, PassRefPtr<Element>);
- static void scheduleLeftViewCallback(PassRefPtr<CustomElementLifecycleCallbacks>, PassRefPtr<Element>);
-
-protected:
- friend class CustomElementCallbackDispatcher;
- static void clearElementCallbackQueueMap();
-
-private:
- CustomElementCallbackScheduler() { }
-
- static CustomElementCallbackScheduler& instance();
-
- CustomElementCallbackQueue* ensureCallbackQueue(PassRefPtr<Element>);
- CustomElementCallbackQueue* schedule(PassRefPtr<Element>);
- CustomElementCallbackQueue* scheduleInCurrentElementQueue(PassRefPtr<Element>);
-
- typedef HashMap<Element*, OwnPtr<CustomElementCallbackQueue> > ElementCallbackQueueMap;
- ElementCallbackQueueMap m_elementCallbackQueueMap;
-};
-
-}
-
-#endif // CustomElementCallbackScheduler_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/CustomElementDefinition.cpp b/chromium/third_party/WebKit/Source/core/dom/CustomElementDefinition.cpp
deleted file mode 100644
index 5f2991029df..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/CustomElementDefinition.cpp
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/dom/CustomElementDefinition.h"
-
-namespace WebCore {
-
-PassRefPtr<CustomElementDefinition> CustomElementDefinition::create(const CustomElementDescriptor& descriptor, PassRefPtr<CustomElementLifecycleCallbacks> callbacks)
-{
- return adoptRef(new CustomElementDefinition(descriptor, callbacks));
-}
-
-CustomElementDefinition::CustomElementDefinition(const CustomElementDescriptor& descriptor, PassRefPtr<CustomElementLifecycleCallbacks> callbacks)
- : m_descriptor(descriptor)
- , m_callbacks(callbacks)
-{
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/dom/CustomElementDefinition.h b/chromium/third_party/WebKit/Source/core/dom/CustomElementDefinition.h
deleted file mode 100644
index 96aa3dcbde7..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/CustomElementDefinition.h
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef CustomElementDefinition_h
-#define CustomElementDefinition_h
-
-#include "core/dom/CustomElementDescriptor.h"
-#include "core/dom/CustomElementLifecycleCallbacks.h"
-#include "wtf/Forward.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-
-namespace WebCore {
-
-class CustomElementDefinition : public RefCounted<CustomElementDefinition> {
-public:
- static PassRefPtr<CustomElementDefinition> create(const CustomElementDescriptor&, PassRefPtr<CustomElementLifecycleCallbacks>);
-
- virtual ~CustomElementDefinition() {}
-
- const CustomElementDescriptor& descriptor() const { return m_descriptor; }
- CustomElementLifecycleCallbacks* callbacks() const { return m_callbacks.get(); }
-
-private:
- CustomElementDefinition(const CustomElementDescriptor&, PassRefPtr<CustomElementLifecycleCallbacks>);
-
- CustomElementDescriptor m_descriptor;
- RefPtr<CustomElementLifecycleCallbacks> m_callbacks;
-};
-
-}
-
-#endif // CustomElementDefinition_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/CustomElementDescriptorHash.h b/chromium/third_party/WebKit/Source/core/dom/CustomElementDescriptorHash.h
deleted file mode 100644
index 81c51de8459..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/CustomElementDescriptorHash.h
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef CustomElementDescriptorHash_h
-#define CustomElementDescriptorHash_h
-
-#include "core/dom/CustomElementDescriptor.h"
-#include "wtf/HashFunctions.h"
-#include "wtf/HashTraits.h"
-#include "wtf/text/AtomicStringHash.h"
-
-namespace WebCore {
-
-struct CustomElementDescriptorHash {
- static unsigned hash(const CustomElementDescriptor& descriptor)
- {
- return WTF::pairIntHash(AtomicStringHash::hash(descriptor.type()), WTF::pairIntHash(AtomicStringHash::hash(descriptor.namespaceURI()), AtomicStringHash::hash(descriptor.localName())));
- }
-
- static bool equal(const CustomElementDescriptor& a, const CustomElementDescriptor& b)
- {
- return a == b;
- }
-
- static const bool safeToCompareToEmptyOrDeleted = true;
-};
-
-} // namespace WebCore
-
-namespace WTF {
-
-template<>
-struct HashTraits<WebCore::CustomElementDescriptor> : SimpleClassHashTraits<WebCore::CustomElementDescriptor> {
- static const bool emptyValueIsZero = HashTraits<AtomicString>::emptyValueIsZero;
-};
-
-} // namespace WTF
-
-#endif // CustomElementDescriptorHash
diff --git a/chromium/third_party/WebKit/Source/core/dom/CustomElementException.cpp b/chromium/third_party/WebKit/Source/core/dom/CustomElementException.cpp
deleted file mode 100644
index 73b1717819a..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/CustomElementException.cpp
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * 3. Neither the name of Google Inc. nor the names of its contributors
- * may be used to endorse or promote products derived from this
- * software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/dom/CustomElementException.h"
-
-#include "bindings/v8/ExceptionState.h"
-#include "core/dom/ExceptionCode.h"
-
-namespace WebCore {
-
-String CustomElementException::preamble(const AtomicString& type)
-{
- return "Failed to call 'register' on 'Document' for type '" + type + "': ";
-}
-
-void CustomElementException::throwException(Reason reason, const AtomicString& type, ExceptionState& es)
-{
- switch (reason) {
- case CannotRegisterFromExtension:
- es.throwDOMException(NotSupportedError, preamble(type) + "elements cannot be registered from extensions.");
- return;
-
- case ConstructorPropertyNotConfigurable:
- es.throwDOMException(NotSupportedError, preamble(type) + "prototype constructor property is not configurable.");
- return;
-
- case ContextDestroyedCheckingPrototype:
- es.throwDOMException(InvalidStateError, preamble(type) + "the context is no longer valid.");
- return;
-
- case ContextDestroyedCreatingCallbacks:
- es.throwDOMException(InvalidStateError);
- return;
-
- case ContextDestroyedRegisteringDefinition:
- es.throwDOMException(NotSupportedError);
- return;
-
- case ExtendsIsInvalidName:
- es.throwDOMException(InvalidCharacterError, preamble(type) + ": the tag name specified in 'extends' is not a valid tag name.");
- return;
-
- case ExtendsIsCustomElementName:
- es.throwDOMException(InvalidCharacterError, preamble(type) + ": the tag name specified in 'extends' is a custom element name. Use inheritance instead.");
- return;
-
- case InvalidName:
- es.throwDOMException(InvalidCharacterError, preamble(type) + ": '" + type + "' is not a valid name.");
- return;
-
- case PrototypeInUse:
- es.throwDOMException(NotSupportedError, preamble(type) + "prototype is already in-use as an interface prototype object.");
- return;
-
- case PrototypeNotAnObject:
- es.throwDOMException(InvalidStateError, preamble(type) + "the prototype option is not an object.");
- return;
-
- case TypeAlreadyRegistered:
- es.throwDOMException(InvalidStateError, preamble(type) + "a type with that name is already registered.");
- return;
- }
-
- ASSERT_NOT_REACHED();
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/CustomElementLifecycleCallbacks.h b/chromium/third_party/WebKit/Source/core/dom/CustomElementLifecycleCallbacks.h
deleted file mode 100644
index eb2f32fc00c..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/CustomElementLifecycleCallbacks.h
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef CustomElementLifecycleCallbacks_h
-#define CustomElementLifecycleCallbacks_h
-
-#include "wtf/RefCounted.h"
-#include "wtf/text/AtomicString.h"
-
-namespace WebCore {
-
-class Element;
-
-class CustomElementLifecycleCallbacks : public RefCounted<CustomElementLifecycleCallbacks> {
-public:
- virtual ~CustomElementLifecycleCallbacks() { }
-
- bool hasCreatedCallback() const { return m_which & Created; }
- virtual void created(Element*) = 0;
-
- bool hasEnteredViewCallback() const { return m_which & EnteredView; }
- virtual void enteredView(Element*) = 0;
-
- bool hasLeftViewCallback() const { return m_which & LeftView; }
- virtual void leftView(Element*) = 0;
-
- bool hasAttributeChangedCallback() const { return m_which & AttributeChanged; }
- virtual void attributeChanged(Element*, const AtomicString& name, const AtomicString& oldValue, const AtomicString& newValue) = 0;
-
- enum CallbackType {
- None = 0,
- Created = 1 << 0,
- EnteredView = 1 << 1,
- LeftView = 1 << 2,
- AttributeChanged = 1 << 3
- };
-
-protected:
- CustomElementLifecycleCallbacks(CallbackType which) : m_which(which) { }
-
-private:
- CallbackType m_which;
-};
-
-}
-
-#endif // CustomElementLifecycleCallbacks_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/CustomElementObserver.cpp b/chromium/third_party/WebKit/Source/core/dom/CustomElementObserver.cpp
deleted file mode 100644
index 45f1350d963..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/CustomElementObserver.cpp
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * 3. Neither the name of Google Inc. nor the names of its contributors
- * may be used to endorse or promote products derived from this
- * software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/dom/CustomElementObserver.h"
-
-namespace WebCore {
-
-CustomElementObserver::ElementObserverMap& CustomElementObserver::elementObservers()
-{
- DEFINE_STATIC_LOCAL(ElementObserverMap, map, ());
- return map;
-}
-
-void CustomElementObserver::notifyElementDidFinishParsingChildren(Element* element)
-{
- ElementObserverMap::iterator it = elementObservers().find(element);
- if (it == elementObservers().end())
- return;
- it->value->elementDidFinishParsingChildren(element);
-}
-
-void CustomElementObserver::notifyElementWasDestroyed(Element* element)
-{
- ElementObserverMap::iterator it = elementObservers().find(element);
- if (it == elementObservers().end())
- return;
- it->value->elementWasDestroyed(element);
-}
-
-void CustomElementObserver::observe(Element* element)
-{
- ElementObserverMap::AddResult result = elementObservers().add(element, this);
- ASSERT(result.isNewEntry);
-}
-
-void CustomElementObserver::unobserve(Element* element)
-{
- CustomElementObserver* observer = elementObservers().take(element);
- ASSERT(observer == this);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/CustomElementRegistrationContext.cpp b/chromium/third_party/WebKit/Source/core/dom/CustomElementRegistrationContext.cpp
deleted file mode 100644
index 6c4133f9702..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/CustomElementRegistrationContext.cpp
+++ /dev/null
@@ -1,150 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * 3. Neither the name of Google Inc. nor the names of its contributors
- * may be used to endorse or promote products derived from this
- * software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/dom/CustomElementRegistrationContext.h"
-
-#include "HTMLNames.h"
-#include "SVGNames.h"
-#include "bindings/v8/ExceptionState.h"
-#include "core/dom/CustomElement.h"
-#include "core/dom/CustomElementCallbackScheduler.h"
-#include "core/dom/CustomElementDefinition.h"
-#include "core/dom/Element.h"
-#include "core/html/HTMLElement.h"
-#include "core/html/HTMLUnknownElement.h"
-#include "core/svg/SVGUnknownElement.h"
-#include "wtf/RefPtr.h"
-
-namespace WebCore {
-
-void CustomElementRegistrationContext::registerElement(Document* document, CustomElementConstructorBuilder* constructorBuilder, const AtomicString& type, CustomElement::NameSet validNames, ExceptionState& es)
-{
- CustomElementDefinition* definition = m_registry.registerElement(document, constructorBuilder, type, validNames, es);
-
- if (!definition)
- return;
-
- // Upgrade elements that were waiting for this definition.
- const CustomElementUpgradeCandidateMap::ElementSet& upgradeCandidates = m_candidates.takeUpgradeCandidatesFor(definition->descriptor());
- for (CustomElementUpgradeCandidateMap::ElementSet::const_iterator it = upgradeCandidates.begin(); it != upgradeCandidates.end(); ++it)
- didResolveElement(definition, *it);
-}
-
-PassRefPtr<Element> CustomElementRegistrationContext::createCustomTagElement(Document& document, const QualifiedName& tagName, CreationMode mode)
-{
- ASSERT(CustomElement::isValidName(tagName.localName()));
-
- RefPtr<Element> element;
-
- if (HTMLNames::xhtmlNamespaceURI == tagName.namespaceURI()) {
- element = HTMLElement::create(tagName, document);
- } else if (SVGNames::svgNamespaceURI == tagName.namespaceURI()) {
- element = SVGUnknownElement::create(tagName, document);
- } else {
- // XML elements are not custom elements, so return early.
- return Element::create(tagName, &document);
- }
-
- element->setCustomElementState(mode == CreatedByParser ? Element::WaitingForParser : Element::WaitingForUpgrade);
- resolve(element.get(), nullAtom);
- return element.release();
-}
-
-void CustomElementRegistrationContext::didGiveTypeExtension(Element* element, const AtomicString& type)
-{
- resolve(element, type);
-}
-
-void CustomElementRegistrationContext::resolve(Element* element, const AtomicString& typeExtension)
-{
- // If an element has a custom tag name it takes precedence over
- // the "is" attribute (if any).
- const AtomicString& type = CustomElement::isValidName(element->localName())
- ? element->localName()
- : typeExtension;
- ASSERT(!type.isNull());
-
- CustomElementDescriptor descriptor(type, element->namespaceURI(), element->localName());
- CustomElementDefinition* definition = m_registry.find(descriptor);
- if (definition)
- didResolveElement(definition, element);
- else
- didCreateUnresolvedElement(descriptor, element);
-}
-
-void CustomElementRegistrationContext::didResolveElement(CustomElementDefinition* definition, Element* element)
-{
- CustomElement::define(element, definition);
-}
-
-void CustomElementRegistrationContext::didCreateUnresolvedElement(const CustomElementDescriptor& descriptor, Element* element)
-{
- ASSERT(element->customElementState() == Element::WaitingForParser || element->customElementState() == Element::WaitingForUpgrade);
- m_candidates.add(descriptor, element);
-}
-
-PassRefPtr<CustomElementRegistrationContext> CustomElementRegistrationContext::create()
-{
- return adoptRef(new CustomElementRegistrationContext());
-}
-
-void CustomElementRegistrationContext::setIsAttributeAndTypeExtension(Element* element, const AtomicString& type)
-{
- ASSERT(element);
- ASSERT(!type.isEmpty());
- element->setAttribute(HTMLNames::isAttr, type);
- setTypeExtension(element, type);
-}
-
-void CustomElementRegistrationContext::setTypeExtension(Element* element, const AtomicString& type, CreationMode mode)
-{
- if (!element->isHTMLElement() && !element->isSVGElement())
- return;
-
- if (element->isCustomElement()) {
- // This can happen if:
- // 1. The element has a custom tag, which takes precedence over
- // type extensions.
- // 2. Undoing a command (eg ReplaceNodeWithSpan) recycles an
- // element but tries to overwrite its attribute list.
- return;
- }
-
- // Custom tags take precedence over type extensions
- ASSERT(!CustomElement::isValidName(element->localName()));
-
- element->setCustomElementState(mode == CreatedByParser ? Element::WaitingForParser : Element::WaitingForUpgrade);
-
- if (CustomElementRegistrationContext* context = element->document().registrationContext())
- context->didGiveTypeExtension(element, type);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/CustomElementRegistrationContext.h b/chromium/third_party/WebKit/Source/core/dom/CustomElementRegistrationContext.h
deleted file mode 100644
index 7d23d725b99..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/CustomElementRegistrationContext.h
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * 3. Neither the name of Google Inc. nor the names of its contributors
- * may be used to endorse or promote products derived from this
- * software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef CustomElementRegistrationContext_h
-#define CustomElementRegistrationContext_h
-
-#include "core/dom/CustomElementDescriptor.h"
-#include "core/dom/CustomElementRegistry.h"
-#include "core/dom/CustomElementUpgradeCandidateMap.h"
-#include "core/dom/QualifiedName.h"
-#include "wtf/HashMap.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/text/AtomicString.h"
-
-namespace WebCore {
-
-class CustomElementConstructorBuilder;
-class CustomElementDefinition;
-class Document;
-class Element;
-class ExceptionState;
-
-class CustomElementRegistrationContext : public RefCounted<CustomElementRegistrationContext> {
-public:
- static PassRefPtr<CustomElementRegistrationContext> create();
-
- ~CustomElementRegistrationContext() { }
-
- // Definitions
- void registerElement(Document*, CustomElementConstructorBuilder*, const AtomicString& type, CustomElement::NameSet validNames, ExceptionState&);
-
- // Instance creation
- enum CreationMode {
- CreatedByParser,
- NotCreatedByParser
- };
-
- PassRefPtr<Element> createCustomTagElement(Document&, const QualifiedName&, CreationMode = NotCreatedByParser);
- static void setIsAttributeAndTypeExtension(Element*, const AtomicString& type);
- static void setTypeExtension(Element*, const AtomicString& type, CreationMode = NotCreatedByParser);
-
-protected:
- CustomElementRegistrationContext() { }
-
- // Instance creation
- void didGiveTypeExtension(Element*, const AtomicString& type);
-
-private:
- void resolve(Element*, const AtomicString& typeExtension);
- void didResolveElement(CustomElementDefinition*, Element*);
- void didCreateUnresolvedElement(const CustomElementDescriptor&, Element*);
-
- CustomElementRegistry m_registry;
-
- // Element creation
- CustomElementUpgradeCandidateMap m_candidates;
-};
-
-}
-
-#endif // CustomElementRegistrationContext_h
-
diff --git a/chromium/third_party/WebKit/Source/core/dom/CustomElementRegistry.cpp b/chromium/third_party/WebKit/Source/core/dom/CustomElementRegistry.cpp
deleted file mode 100644
index 00d6d71b81a..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/CustomElementRegistry.cpp
+++ /dev/null
@@ -1,126 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * 3. Neither the name of Google Inc. nor the names of its contributors
- * may be used to endorse or promote products derived from this
- * software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/dom/CustomElementRegistry.h"
-
-#include "HTMLNames.h"
-#include "SVGNames.h"
-#include "bindings/v8/CustomElementConstructorBuilder.h"
-#include "core/dom/CustomElement.h"
-#include "core/dom/CustomElementDefinition.h"
-#include "core/dom/CustomElementException.h"
-#include "core/dom/CustomElementRegistrationContext.h"
-#include "core/dom/DocumentLifecycleObserver.h"
-
-namespace WebCore {
-
-class RegistrationContextObserver : public DocumentLifecycleObserver {
-public:
- explicit RegistrationContextObserver(Document* document)
- : DocumentLifecycleObserver(document)
- , m_wentAway(!document)
- {
- }
-
- bool registrationContextWentAway() { return m_wentAway; }
-
-private:
- virtual void documentWasDisposed() OVERRIDE { m_wentAway = true; }
-
- bool m_wentAway;
-};
-
-CustomElementDefinition* CustomElementRegistry::registerElement(Document* document, CustomElementConstructorBuilder* constructorBuilder, const AtomicString& userSuppliedName, CustomElement::NameSet validNames, ExceptionState& es)
-{
- // FIXME: In every instance except one it is the
- // CustomElementConstructorBuilder that observes document
- // destruction during registration. This responsibility should be
- // consolidated in one place.
- RegistrationContextObserver observer(document);
-
- AtomicString type = userSuppliedName.lower();
-
- if (!constructorBuilder->isFeatureAllowed()) {
- CustomElementException::throwException(CustomElementException::CannotRegisterFromExtension, type, es);
- return 0;
- }
-
- if (!CustomElement::isValidName(type, validNames)) {
- CustomElementException::throwException(CustomElementException::InvalidName, type, es);
- return 0;
- }
-
- QualifiedName tagName = nullQName();
- if (!constructorBuilder->validateOptions(type, tagName, es))
- return 0;
-
- ASSERT(tagName.namespaceURI() == HTMLNames::xhtmlNamespaceURI || tagName.namespaceURI() == SVGNames::svgNamespaceURI);
-
- // FIXME: This should be done earlier in validateOptions.
- if (m_registeredTypeNames.contains(type)) {
- CustomElementException::throwException(CustomElementException::TypeAlreadyRegistered, type, es);
- return 0;
- }
-
- ASSERT(!observer.registrationContextWentAway());
-
- RefPtr<CustomElementLifecycleCallbacks> lifecycleCallbacks = constructorBuilder->createCallbacks();
-
- // Consulting the constructor builder could execute script and
- // kill the document.
- if (observer.registrationContextWentAway()) {
- CustomElementException::throwException(CustomElementException::ContextDestroyedCreatingCallbacks, type, es);
- return 0;
- }
-
- const CustomElementDescriptor descriptor(type, tagName.namespaceURI(), tagName.localName());
- RefPtr<CustomElementDefinition> definition = CustomElementDefinition::create(descriptor, lifecycleCallbacks);
-
- if (!constructorBuilder->createConstructor(document, definition.get(), es))
- return 0;
-
- m_definitions.add(descriptor, definition);
- m_registeredTypeNames.add(descriptor.type());
-
- if (!constructorBuilder->didRegisterDefinition(definition.get())) {
- CustomElementException::throwException(CustomElementException::ContextDestroyedRegisteringDefinition, type, es);
- return 0;
- }
-
- return definition.get();
-}
-
-CustomElementDefinition* CustomElementRegistry::find(const CustomElementDescriptor& descriptor) const
-{
- return m_definitions.get(descriptor);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/CustomElementRegistry.h b/chromium/third_party/WebKit/Source/core/dom/CustomElementRegistry.h
deleted file mode 100644
index d1a79bd990b..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/CustomElementRegistry.h
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * 3. Neither the name of Google Inc. nor the names of its contributors
- * may be used to endorse or promote products derived from this
- * software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef CustomElementRegistry_h
-#define CustomElementRegistry_h
-
-#include "core/dom/CustomElement.h"
-#include "core/dom/CustomElementDefinition.h"
-#include "core/dom/CustomElementDescriptor.h"
-#include "core/dom/CustomElementDescriptorHash.h"
-#include "wtf/HashMap.h"
-#include "wtf/HashSet.h"
-#include "wtf/RefPtr.h"
-#include "wtf/text/AtomicString.h"
-#include "wtf/text/AtomicStringHash.h"
-
-namespace WebCore {
-
-class CustomElementConstructorBuilder;
-class Document;
-class ExceptionState;
-
-class CustomElementRegistry {
- WTF_MAKE_NONCOPYABLE(CustomElementRegistry);
-protected:
- friend class CustomElementRegistrationContext;
-
- CustomElementRegistry() { }
- virtual ~CustomElementRegistry() { }
-
- CustomElementDefinition* registerElement(Document*, CustomElementConstructorBuilder*, const AtomicString& name, CustomElement::NameSet validNames, ExceptionState&);
- CustomElementDefinition* find(const CustomElementDescriptor&) const;
-
-private:
- typedef HashMap<CustomElementDescriptor, RefPtr<CustomElementDefinition> > DefinitionMap;
- DefinitionMap m_definitions;
- HashSet<AtomicString> m_registeredTypeNames;
-};
-
-} // namespace WebCore
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/dom/CustomElementUpgradeCandidateMap.cpp b/chromium/third_party/WebKit/Source/core/dom/CustomElementUpgradeCandidateMap.cpp
deleted file mode 100644
index 8583eb20465..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/CustomElementUpgradeCandidateMap.cpp
+++ /dev/null
@@ -1,110 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/dom/CustomElementUpgradeCandidateMap.h"
-
-#include "core/dom/Element.h"
-
-namespace WebCore {
-
-CustomElementUpgradeCandidateMap::~CustomElementUpgradeCandidateMap()
-{
- UpgradeCandidateMap::const_iterator::Keys end = m_upgradeCandidates.end().keys();
- for (UpgradeCandidateMap::const_iterator::Keys it = m_upgradeCandidates.begin().keys(); it != end; ++it)
- unobserve(*it);
-}
-
-void CustomElementUpgradeCandidateMap::add(const CustomElementDescriptor& descriptor, Element* element)
-{
- observe(element);
-
- UpgradeCandidateMap::AddResult result = m_upgradeCandidates.add(element, descriptor);
- ASSERT(result.isNewEntry);
-
- UnresolvedDefinitionMap::iterator it = m_unresolvedDefinitions.find(descriptor);
- if (it == m_unresolvedDefinitions.end())
- it = m_unresolvedDefinitions.add(descriptor, ElementSet()).iterator;
- it->value.add(element);
-}
-
-void CustomElementUpgradeCandidateMap::remove(Element* element)
-{
- unobserve(element);
- removeCommon(element);
-}
-
-void CustomElementUpgradeCandidateMap::elementWasDestroyed(Element* element)
-{
- CustomElementObserver::elementWasDestroyed(element);
- removeCommon(element);
-}
-
-void CustomElementUpgradeCandidateMap::removeCommon(Element* element)
-{
- UpgradeCandidateMap::iterator candidate = m_upgradeCandidates.find(element);
- ASSERT(candidate != m_upgradeCandidates.end());
-
- UnresolvedDefinitionMap::iterator elements = m_unresolvedDefinitions.find(candidate->value);
- ASSERT(elements != m_unresolvedDefinitions.end());
- elements->value.remove(element);
- m_upgradeCandidates.remove(candidate);
-}
-
-void CustomElementUpgradeCandidateMap::elementDidFinishParsingChildren(Element* element)
-{
- // An upgrade candidate finished parsing; reorder so that eventual
- // upgrade order matches finished-parsing order.
- moveToEnd(element);
-}
-
-void CustomElementUpgradeCandidateMap::moveToEnd(Element* element)
-{
- UpgradeCandidateMap::iterator candidate = m_upgradeCandidates.find(element);
- ASSERT(candidate != m_upgradeCandidates.end());
-
- UnresolvedDefinitionMap::iterator elements = m_unresolvedDefinitions.find(candidate->value);
- ASSERT(elements != m_unresolvedDefinitions.end());
- elements->value.appendOrMoveToLast(element);
-}
-
-ListHashSet<Element*> CustomElementUpgradeCandidateMap::takeUpgradeCandidatesFor(const CustomElementDescriptor& descriptor)
-{
- const ListHashSet<Element*>& candidates = m_unresolvedDefinitions.take(descriptor);
-
- for (ElementSet::const_iterator candidate = candidates.begin(); candidate != candidates.end(); ++candidate) {
- unobserve(*candidate);
- m_upgradeCandidates.remove(*candidate);
- }
-
- return candidates;
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/dom/CustomElementUpgradeCandidateMap.h b/chromium/third_party/WebKit/Source/core/dom/CustomElementUpgradeCandidateMap.h
deleted file mode 100644
index f9f23114f3c..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/CustomElementUpgradeCandidateMap.h
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef CustomElementUpgradeCandidateMap_h
-#define CustomElementUpgradeCandidateMap_h
-
-#include "core/dom/CustomElementDescriptor.h"
-#include "core/dom/CustomElementDescriptorHash.h"
-#include "core/dom/CustomElementObserver.h"
-#include "wtf/HashMap.h"
-#include "wtf/ListHashSet.h"
-#include "wtf/Noncopyable.h"
-
-namespace WebCore {
-
-class Element;
-
-class CustomElementUpgradeCandidateMap : CustomElementObserver {
- WTF_MAKE_NONCOPYABLE(CustomElementUpgradeCandidateMap);
-public:
- CustomElementUpgradeCandidateMap() { }
- ~CustomElementUpgradeCandidateMap();
-
- // API for CustomElementRegistrationContext to save and take candidates
-
- typedef ListHashSet<Element*> ElementSet;
-
- void add(const CustomElementDescriptor&, Element*);
- void remove(Element*);
- ElementSet takeUpgradeCandidatesFor(const CustomElementDescriptor&);
-
-private:
- virtual void elementWasDestroyed(Element*) OVERRIDE;
- void removeCommon(Element*);
-
- virtual void elementDidFinishParsingChildren(Element*) OVERRIDE;
- void moveToEnd(Element*);
-
- typedef HashMap<Element*, CustomElementDescriptor> UpgradeCandidateMap;
- UpgradeCandidateMap m_upgradeCandidates;
-
- typedef HashMap<CustomElementDescriptor, ElementSet> UnresolvedDefinitionMap;
- UnresolvedDefinitionMap m_unresolvedDefinitions;
-};
-
-}
-
-#endif // CustomElementUpgradeCandidateMap_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/CustomEvent.cpp b/chromium/third_party/WebKit/Source/core/dom/CustomEvent.cpp
deleted file mode 100644
index c46919d2e74..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/CustomEvent.cpp
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/dom/CustomEvent.h"
-
-#include "bindings/v8/SerializedScriptValue.h"
-#include "core/dom/EventNames.h"
-
-namespace WebCore {
-
-CustomEvent::CustomEvent()
-{
- ScriptWrappable::init(this);
-}
-
-CustomEvent::CustomEvent(const AtomicString& type, const CustomEventInit& initializer)
- : Event(type, initializer)
-{
- ScriptWrappable::init(this);
-}
-
-CustomEvent::~CustomEvent()
-{
-}
-
-void CustomEvent::initCustomEvent(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<SerializedScriptValue> serializedDetail)
-{
- if (dispatched())
- return;
-
- initEvent(type, canBubble, cancelable);
-
- m_serializedDetail = serializedDetail;
-}
-
-const AtomicString& CustomEvent::interfaceName() const
-{
- return eventNames().interfaceForCustomEvent;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/CustomEvent.h b/chromium/third_party/WebKit/Source/core/dom/CustomEvent.h
deleted file mode 100644
index d67c8c786ab..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/CustomEvent.h
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef CustomEvent_h
-#define CustomEvent_h
-
-#include "core/dom/Event.h"
-
-namespace WebCore {
-
-class SerializedScriptValue;
-
-typedef EventInit CustomEventInit;
-
-class CustomEvent : public Event {
-public:
- virtual ~CustomEvent();
-
- static PassRefPtr<CustomEvent> create()
- {
- return adoptRef(new CustomEvent);
- }
-
- static PassRefPtr<CustomEvent> create(const AtomicString& type, const CustomEventInit& initializer)
- {
- return adoptRef(new CustomEvent(type, initializer));
- }
-
- void initCustomEvent(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<SerializedScriptValue>);
-
- virtual const AtomicString& interfaceName() const;
-
- SerializedScriptValue* serializedDetail() { return m_serializedDetail.get(); }
-
- void setSerializedDetail(PassRefPtr<SerializedScriptValue> detail)
- {
- ASSERT(!m_serializedDetail);
- m_serializedDetail = detail;
- }
-
-private:
- CustomEvent();
- CustomEvent(const AtomicString& type, const CustomEventInit& initializer);
-
- RefPtr<SerializedScriptValue> m_serializedDetail;
-};
-
-} // namespace WebCore
-
-#endif // CustomEvent_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/CustomEvent.idl b/chromium/third_party/WebKit/Source/core/dom/CustomEvent.idl
deleted file mode 100644
index 12edaa53265..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/CustomEvent.idl
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-[
- ConstructorTemplate=Event
-] interface CustomEvent : Event {
- [InitializedByEventConstructor, Custom] readonly attribute any detail;
-
- [Custom] void initCustomEvent([Default=Undefined] optional DOMString typeArg,
- [Default=Undefined] optional boolean canBubbleArg,
- [Default=Undefined] optional boolean cancelableArg,
- [Default=Undefined] optional any detailArg);
-};
diff --git a/chromium/third_party/WebKit/Source/core/dom/DOMError.cpp b/chromium/third_party/WebKit/Source/core/dom/DOMError.cpp
index e77d271e9a6..3d41a04960a 100644
--- a/chromium/third_party/WebKit/Source/core/dom/DOMError.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/DOMError.cpp
@@ -26,7 +26,6 @@
#include "config.h"
#include "core/dom/DOMError.h"
-#include "wtf/text/WTFString.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/dom/DOMError.idl b/chromium/third_party/WebKit/Source/core/dom/DOMError.idl
index 83522fa0053..b2ea60f4821 100644
--- a/chromium/third_party/WebKit/Source/core/dom/DOMError.idl
+++ b/chromium/third_party/WebKit/Source/core/dom/DOMError.idl
@@ -27,7 +27,7 @@
*/
[
NoInterfaceObject
-] interface DOMError {
+] interface DOMError {
readonly attribute DOMString name;
readonly attribute DOMString message;
};
diff --git a/chromium/third_party/WebKit/Source/core/dom/DOMException.cpp b/chromium/third_party/WebKit/Source/core/dom/DOMException.cpp
index 348a94e98d3..ebb5b209f6c 100644
--- a/chromium/third_party/WebKit/Source/core/dom/DOMException.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/DOMException.cpp
@@ -33,7 +33,7 @@
namespace WebCore {
-static struct CoreException {
+static const struct CoreException {
const char* const name;
const char* const message;
const int code;
diff --git a/chromium/third_party/WebKit/Source/core/dom/DOMImplementation.cpp b/chromium/third_party/WebKit/Source/core/dom/DOMImplementation.cpp
index 3215a6a5b2a..ff898a52dea 100644
--- a/chromium/third_party/WebKit/Source/core/dom/DOMImplementation.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/DOMImplementation.cpp
@@ -32,11 +32,11 @@
#include "core/css/MediaList.h"
#include "core/css/StyleSheetContents.h"
#include "core/dom/ContextFeatures.h"
-#include "core/dom/CustomElementRegistrationContext.h"
#include "core/dom/DocumentInit.h"
#include "core/dom/DocumentType.h"
#include "core/dom/Element.h"
#include "core/dom/ExceptionCode.h"
+#include "core/dom/custom/CustomElementRegistrationContext.h"
#include "core/html/HTMLDocument.h"
#include "core/html/HTMLMediaElement.h"
#include "core/html/HTMLViewSourceDocument.h"
@@ -45,15 +45,15 @@
#include "core/html/PluginDocument.h"
#include "core/html/TextDocument.h"
#include "core/loader/FrameLoader.h"
-#include "core/page/Frame.h"
+#include "core/frame/Frame.h"
#include "core/page/Page.h"
-#include "core/platform/ContentType.h"
-#include "core/platform/MIMETypeRegistry.h"
-#include "core/platform/graphics/Image.h"
-#include "core/platform/graphics/MediaPlayer.h"
-#include "core/plugins/PluginData.h"
#include "core/svg/SVGDocument.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/ContentType.h"
+#include "platform/MIMETypeRegistry.h"
+#include "platform/graphics/Image.h"
+#include "platform/graphics/media/MediaPlayer.h"
+#include "platform/plugins/PluginData.h"
+#include "platform/weborigin/SecurityOrigin.h"
#include "wtf/StdLibExtras.h"
namespace WebCore {
@@ -161,7 +161,7 @@ static bool isSupportedSVG11Feature(const String& feature, const String& version
&& svgFeatures.contains(feature.right(feature.length() - 35));
}
-DOMImplementation::DOMImplementation(Document* document)
+DOMImplementation::DOMImplementation(Document& document)
: m_document(document)
{
ScriptWrappable::init(this);
@@ -178,14 +178,14 @@ bool DOMImplementation::hasFeature(const String& feature, const String& version)
return true;
}
-PassRefPtr<DocumentType> DOMImplementation::createDocumentType(const String& qualifiedName,
- const String& publicId, const String& systemId, ExceptionState& es)
+PassRefPtr<DocumentType> DOMImplementation::createDocumentType(const AtomicString& qualifiedName,
+ const String& publicId, const String& systemId, ExceptionState& exceptionState)
{
- String prefix, localName;
- if (!Document::parseQualifiedName(qualifiedName, prefix, localName, es))
+ AtomicString prefix, localName;
+ if (!Document::parseQualifiedName(qualifiedName, prefix, localName, exceptionState))
return 0;
- return DocumentType::create(m_document, qualifiedName, publicId, systemId);
+ return DocumentType::create(&m_document, qualifiedName, publicId, systemId);
}
DOMImplementation* DOMImplementation::getInterface(const String& /*feature*/)
@@ -193,26 +193,26 @@ DOMImplementation* DOMImplementation::getInterface(const String& /*feature*/)
return 0;
}
-PassRefPtr<Document> DOMImplementation::createDocument(const String& namespaceURI,
- const String& qualifiedName, DocumentType* doctype, ExceptionState& es)
+PassRefPtr<Document> DOMImplementation::createDocument(const AtomicString& namespaceURI,
+ const AtomicString& qualifiedName, DocumentType* doctype, ExceptionState& exceptionState)
{
RefPtr<Document> doc;
- DocumentInit init = DocumentInit::fromContext(m_document->contextDocument());
+ DocumentInit init = DocumentInit::fromContext(m_document.contextDocument());
if (namespaceURI == SVGNames::svgNamespaceURI) {
doc = SVGDocument::create(init);
} else if (namespaceURI == HTMLNames::xhtmlNamespaceURI) {
- doc = Document::createXHTML(init.withRegistrationContext(m_document->registrationContext()));
+ doc = Document::createXHTML(init.withRegistrationContext(m_document.registrationContext()));
} else {
doc = Document::create(init);
}
- doc->setSecurityOrigin(m_document->securityOrigin());
- doc->setContextFeatures(m_document->contextFeatures());
+ doc->setSecurityOrigin(m_document.securityOrigin()->isolatedCopy());
+ doc->setContextFeatures(m_document.contextFeatures());
RefPtr<Node> documentElement;
if (!qualifiedName.isEmpty()) {
- documentElement = doc->createElementNS(namespaceURI, qualifiedName, es);
- if (es.hadException())
+ documentElement = doc->createElementNS(namespaceURI, qualifiedName, exceptionState);
+ if (exceptionState.hadException())
return 0;
}
@@ -307,57 +307,62 @@ bool DOMImplementation::isTextMIMEType(const String& mimeType)
PassRefPtr<HTMLDocument> DOMImplementation::createHTMLDocument(const String& title)
{
- DocumentInit init = DocumentInit::fromContext(m_document->contextDocument())
- .withRegistrationContext(m_document->registrationContext());
+ DocumentInit init = DocumentInit::fromContext(m_document.contextDocument())
+ .withRegistrationContext(m_document.registrationContext());
RefPtr<HTMLDocument> d = HTMLDocument::create(init);
d->open();
d->write("<!doctype html><html><body></body></html>");
if (!title.isNull())
d->setTitle(title);
- d->setSecurityOrigin(m_document->securityOrigin());
- d->setContextFeatures(m_document->contextFeatures());
+ d->setSecurityOrigin(m_document.securityOrigin()->isolatedCopy());
+ d->setContextFeatures(m_document.contextFeatures());
return d.release();
}
PassRefPtr<Document> DOMImplementation::createDocument(const String& type, Frame* frame, const KURL& url, bool inViewSourceMode)
{
+ return createDocument(type, DocumentInit(url, frame), inViewSourceMode);
+}
+
+PassRefPtr<Document> DOMImplementation::createDocument(const String& type, const DocumentInit& init, bool inViewSourceMode)
+{
if (inViewSourceMode)
- return HTMLViewSourceDocument::create(DocumentInit(url, frame), type);
+ return HTMLViewSourceDocument::create(init, type);
// Plugins cannot take HTML and XHTML from us, and we don't even need to initialize the plugin database for those.
if (type == "text/html")
- return HTMLDocument::create(DocumentInit(url, frame));
+ return HTMLDocument::create(init);
if (type == "application/xhtml+xml")
- return Document::createXHTML(DocumentInit(url, frame));
+ return Document::createXHTML(init);
PluginData* pluginData = 0;
- if (frame && frame->page() && frame->loader()->allowPlugins(NotAboutToInstantiatePlugin))
- pluginData = frame->page()->pluginData();
+ if (init.frame() && init.frame()->page() && init.frame()->loader().allowPlugins(NotAboutToInstantiatePlugin))
+ pluginData = init.frame()->page()->pluginData();
// PDF is one image type for which a plugin can override built-in support.
// We do not want QuickTime to take over all image types, obviously.
if ((type == "application/pdf" || type == "text/pdf") && pluginData && pluginData->supportsMimeType(type))
- return PluginDocument::create(DocumentInit(url, frame));
+ return PluginDocument::create(init);
if (Image::supportsType(type))
- return ImageDocument::create(DocumentInit(url, frame));
+ return ImageDocument::create(init);
// Check to see if the type can be played by our MediaPlayer, if so create a MediaDocument
if (HTMLMediaElement::supportsType(ContentType(type)))
- return MediaDocument::create(DocumentInit(url, frame));
+ return MediaDocument::create(init);
// Everything else except text/plain can be overridden by plugins. In particular, Adobe SVG Viewer should be used for SVG, if installed.
// Disallowing plug-ins to use text/plain prevents plug-ins from hijacking a fundamental type that the browser is expected to handle,
// and also serves as an optimization to prevent loading the plug-in database in the common case.
if (type != "text/plain" && pluginData && pluginData->supportsMimeType(type))
- return PluginDocument::create(DocumentInit(url, frame));
+ return PluginDocument::create(init);
if (isTextMIMEType(type))
- return TextDocument::create(DocumentInit(url, frame));
+ return TextDocument::create(init);
if (type == "image/svg+xml")
- return SVGDocument::create(DocumentInit(url, frame));
+ return SVGDocument::create(init);
if (isXMLMIMEType(type))
- return Document::create(DocumentInit(url, frame));
+ return Document::create(init);
- return HTMLDocument::create(DocumentInit(url, frame));
+ return HTMLDocument::create(init);
}
}
diff --git a/chromium/third_party/WebKit/Source/core/dom/DOMImplementation.h b/chromium/third_party/WebKit/Source/core/dom/DOMImplementation.h
index 153f4c4491f..b710d2ad22c 100644
--- a/chromium/third_party/WebKit/Source/core/dom/DOMImplementation.h
+++ b/chromium/third_party/WebKit/Source/core/dom/DOMImplementation.h
@@ -32,6 +32,7 @@ namespace WebCore {
class CSSStyleSheet;
class Document;
+class DocumentInit;
class DocumentType;
class ExceptionState;
class Frame;
@@ -41,16 +42,16 @@ class KURL;
class DOMImplementation : public ScriptWrappable {
WTF_MAKE_FAST_ALLOCATED;
public:
- static PassOwnPtr<DOMImplementation> create(Document* document) { return adoptPtr(new DOMImplementation(document)); }
+ static PassOwnPtr<DOMImplementation> create(Document& document) { return adoptPtr(new DOMImplementation(document)); }
- void ref() { m_document->ref(); }
- void deref() { m_document->deref(); }
- Document* document() { return m_document; }
+ void ref() { m_document.ref(); }
+ void deref() { m_document.deref(); }
+ Document* document() { return &m_document; }
// DOM methods & attributes for DOMImplementation
static bool hasFeature(const String& feature, const String& version);
- PassRefPtr<DocumentType> createDocumentType(const String& qualifiedName, const String& publicId, const String& systemId, ExceptionState&);
- PassRefPtr<Document> createDocument(const String& namespaceURI, const String& qualifiedName, DocumentType*, ExceptionState&);
+ PassRefPtr<DocumentType> createDocumentType(const AtomicString& qualifiedName, const String& publicId, const String& systemId, ExceptionState&);
+ PassRefPtr<Document> createDocument(const AtomicString& namespaceURI, const AtomicString& qualifiedName, DocumentType*, ExceptionState&);
DOMImplementation* getInterface(const String& feature);
@@ -62,14 +63,15 @@ public:
// Other methods (not part of DOM)
static PassRefPtr<Document> createDocument(const String& MIMEType, Frame*, const KURL&, bool inViewSourceMode);
+ static PassRefPtr<Document> createDocument(const String& type, const DocumentInit&, bool inViewSourceMode);
static bool isXMLMIMEType(const String& MIMEType);
static bool isTextMIMEType(const String& MIMEType);
private:
- explicit DOMImplementation(Document*);
+ explicit DOMImplementation(Document&);
- Document* m_document;
+ Document& m_document;
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/DOMImplementation.idl b/chromium/third_party/WebKit/Source/core/dom/DOMImplementation.idl
index c110cb4d32e..7630c5e5fbd 100644
--- a/chromium/third_party/WebKit/Source/core/dom/DOMImplementation.idl
+++ b/chromium/third_party/WebKit/Source/core/dom/DOMImplementation.idl
@@ -19,30 +19,29 @@
*/
[
- GenerateIsReachable=document
+ GenerateVisitDOMWrapper=document,
] interface DOMImplementation {
// DOM Level 1
- boolean hasFeature([Default=Undefined] optional DOMString feature,
- [TreatNullAs=NullString,Default=Undefined] optional DOMString version);
+ boolean hasFeature(DOMString feature, [TreatNullAs=NullString] DOMString version);
// DOM Level 2
- [RaisesException] DocumentType createDocumentType([TreatNullAs=NullString] DOMString qualifiedName,
- [TreatNullAs=NullString] DOMString publicId,
- [TreatNullAs=NullString] DOMString systemId);
- [RaisesException] Document createDocument([TreatNullAs=NullString] DOMString namespaceURI,
- [TreatNullAs=NullString] DOMString qualifiedName,
- [Default=Undefined] optional DocumentType doctype);
+ [RaisesException] DocumentType createDocumentType(DOMString qualifiedName,
+ DOMString publicId,
+ DOMString systemId);
+ [RaisesException] Document createDocument([TreatNullAs=NullString] DOMString namespaceURI,
+ [TreatNullAs=NullString] DOMString qualifiedName,
+ [Default=Undefined] optional DocumentType doctype);
// DOMImplementationCSS interface from DOM Level 2 CSS
- CSSStyleSheet createCSSStyleSheet([Default=Undefined] optional DOMString title,
- [Default=Undefined] optional DOMString media);
+ [MeasureAs=DOMImplementationCreateCSSStyleSheet]
+ CSSStyleSheet createCSSStyleSheet([Default=Undefined] optional DOMString title,
+ [Default=Undefined] optional DOMString media);
// HTMLDOMImplementation interface from DOM Level 2 HTML
HTMLDocument createHTMLDocument([Default=NullString] optional DOMString title);
};
-
diff --git a/chromium/third_party/WebKit/Source/core/dom/DOMNamedFlowCollection.cpp b/chromium/third_party/WebKit/Source/core/dom/DOMNamedFlowCollection.cpp
index 47107a19a22..9fbf981ff46 100644
--- a/chromium/third_party/WebKit/Source/core/dom/DOMNamedFlowCollection.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/DOMNamedFlowCollection.cpp
@@ -31,7 +31,7 @@
#include "RuntimeEnabledFeatures.h"
#include "core/dom/NamedFlow.h"
-#include "core/dom/NamedFlowCollection.h"
+#include "wtf/text/StringHash.h"
namespace WebCore {
@@ -60,7 +60,7 @@ PassRefPtr<NamedFlow> DOMNamedFlowCollection::item(unsigned long index) const
PassRefPtr<NamedFlow> DOMNamedFlowCollection::namedItem(const AtomicString& name) const
{
- DOMNamedFlowSet::const_iterator it = m_namedFlows.find<String, DOMNamedFlowHashTranslator>(name);
+ DOMNamedFlowSet::const_iterator it = m_namedFlows.find<DOMNamedFlowHashTranslator, String>(name);
if (it != m_namedFlows.end())
return *it;
return 0;
diff --git a/chromium/third_party/WebKit/Source/core/dom/DOMSettableTokenList.cpp b/chromium/third_party/WebKit/Source/core/dom/DOMSettableTokenList.cpp
index 10692ca2d15..2d69533d6b3 100644
--- a/chromium/third_party/WebKit/Source/core/dom/DOMSettableTokenList.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/DOMSettableTokenList.cpp
@@ -52,9 +52,9 @@ bool DOMSettableTokenList::containsInternal(const AtomicString& token) const
return m_tokens.contains(token);
}
-void DOMSettableTokenList::add(const Vector<String>& tokens, ExceptionState& es)
+void DOMSettableTokenList::add(const Vector<String>& tokens, ExceptionState& exceptionState)
{
- DOMTokenList::add(tokens, es);
+ DOMTokenList::add(tokens, exceptionState);
for (size_t i = 0; i < tokens.size(); ++i) {
if (m_tokens.isNull())
@@ -73,9 +73,9 @@ void DOMSettableTokenList::addInternal(const AtomicString& token)
m_tokens.add(token);
}
-void DOMSettableTokenList::remove(const Vector<String>& tokens, ExceptionState& es)
+void DOMSettableTokenList::remove(const Vector<String>& tokens, ExceptionState& exceptionState)
{
- DOMTokenList::remove(tokens, es);
+ DOMTokenList::remove(tokens, exceptionState);
for (size_t i = 0; i < tokens.size(); ++i)
m_tokens.remove(tokens[i]);
}
diff --git a/chromium/third_party/WebKit/Source/core/dom/DOMStringMap.h b/chromium/third_party/WebKit/Source/core/dom/DOMStringMap.h
index cbcc402722d..22ce97497f1 100644
--- a/chromium/third_party/WebKit/Source/core/dom/DOMStringMap.h
+++ b/chromium/third_party/WebKit/Source/core/dom/DOMStringMap.h
@@ -49,18 +49,18 @@ public:
virtual bool contains(const String& name) = 0;
virtual void setItem(const String& name, const String& value, ExceptionState&) = 0;
virtual void deleteItem(const String& name, ExceptionState&) = 0;
- bool anonymousNamedSetter(const String& name, const String& value, ExceptionState& es)
+ bool anonymousNamedSetter(const String& name, const String& value, ExceptionState& exceptionState)
{
- setItem(name, value, es);
+ setItem(name, value, exceptionState);
return true;
}
bool anonymousNamedDeleter(const AtomicString& name, ExceptionState&)
{
// FIXME: Remove ExceptionState parameter.
- TrackExceptionState es;
- deleteItem(name, es);
- bool result = !es.hadException();
+ TrackExceptionState exceptionState;
+ deleteItem(name, exceptionState);
+ bool result = !exceptionState.hadException();
// DOMStringMap deleter should ignore exception.
// Behavior of Firefox and Opera are same.
// delete document.body.dataset["-foo"] // false instead of DOM Exception 12
@@ -73,6 +73,19 @@ public:
}
bool namedPropertyQuery(const AtomicString&, ExceptionState&);
+ String anonymousIndexedGetter(uint32_t index)
+ {
+ return item(String::number(index));
+ }
+ bool anonymousIndexedSetter(uint32_t index, const String& value, ExceptionState& exceptionState)
+ {
+ return anonymousNamedSetter(String::number(index), value, exceptionState);
+ }
+ bool anonymousIndexedDeleter(uint32_t index, ExceptionState& exceptionState)
+ {
+ return anonymousNamedDeleter(AtomicString::number(index), exceptionState);
+ }
+
virtual Element* element() = 0;
protected:
diff --git a/chromium/third_party/WebKit/Source/core/dom/DOMStringMap.idl b/chromium/third_party/WebKit/Source/core/dom/DOMStringMap.idl
index 5b09c3380e5..fcbbf899d42 100644
--- a/chromium/third_party/WebKit/Source/core/dom/DOMStringMap.idl
+++ b/chromium/third_party/WebKit/Source/core/dom/DOMStringMap.idl
@@ -24,10 +24,13 @@
*/
[
- GenerateIsReachable=element
+ GenerateVisitDOMWrapper=element,
] interface DOMStringMap {
+ [ImplementedAs=anonymousIndexedGetter, NotEnumerable] getter DOMString (unsigned long index);
+ [ImplementedAs=anonymousIndexedSetter, RaisesException, NotEnumerable] setter DOMString (unsigned long index, DOMString value);
+ [ImplementedAs=anonymousIndexedDeleter, RaisesException, NotEnumerable] deleter boolean (unsigned long index);
[ImplementedAs=item, OverrideBuiltins] getter DOMString (DOMString name);
- [ImplementedAs=anonymousNamedDeleter, RaisesException] deleter boolean (DOMString name);
[ImplementedAs=anonymousNamedSetter, RaisesException, OverrideBuiltins] setter DOMString (DOMString name, DOMString value);
+ [ImplementedAs=anonymousNamedDeleter, RaisesException] deleter boolean (DOMString name);
};
diff --git a/chromium/third_party/WebKit/Source/core/dom/DOMTokenList.cpp b/chromium/third_party/WebKit/Source/core/dom/DOMTokenList.cpp
index a907c784491..41255b2b170 100644
--- a/chromium/third_party/WebKit/Source/core/dom/DOMTokenList.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/DOMTokenList.cpp
@@ -32,17 +32,17 @@
namespace WebCore {
-bool DOMTokenList::validateToken(const AtomicString& token, ExceptionState& es)
+bool DOMTokenList::validateToken(const AtomicString& token, ExceptionState& exceptionState)
{
if (token.isEmpty()) {
- es.throwDOMException(SyntaxError);
+ exceptionState.throwDOMException(SyntaxError, "The token provided must not be empty.");
return false;
}
unsigned length = token.length();
for (unsigned i = 0; i < length; ++i) {
if (isHTMLSpace<UChar>(token[i])) {
- es.throwDOMException(InvalidCharacterError);
+ exceptionState.throwDOMException(InvalidCharacterError, "The token provided ('" + token + "') contains HTML space characters, which are not valid in tokens.");
return false;
}
}
@@ -50,38 +50,42 @@ bool DOMTokenList::validateToken(const AtomicString& token, ExceptionState& es)
return true;
}
-bool DOMTokenList::validateTokens(const Vector<String>& tokens, ExceptionState& es)
+bool DOMTokenList::validateTokens(const Vector<String>& tokens, ExceptionState& exceptionState)
{
for (size_t i = 0; i < tokens.size(); ++i) {
- if (!validateToken(tokens[i], es))
+ if (!validateToken(tokens[i], exceptionState))
return false;
}
return true;
}
-bool DOMTokenList::contains(const AtomicString& token, ExceptionState& es) const
+bool DOMTokenList::contains(const AtomicString& token, ExceptionState& exceptionState) const
{
- if (!validateToken(token, es))
+ if (!validateToken(token, exceptionState))
return false;
return containsInternal(token);
}
-void DOMTokenList::add(const AtomicString& token, ExceptionState& es)
+void DOMTokenList::add(const AtomicString& token, ExceptionState& exceptionState)
{
Vector<String> tokens;
tokens.append(token.string());
- add(tokens, es);
+ add(tokens, exceptionState);
}
-void DOMTokenList::add(const Vector<String>& tokens, ExceptionState& es)
+void DOMTokenList::add(const Vector<String>& tokens, ExceptionState& exceptionState)
{
Vector<String> filteredTokens;
+ filteredTokens.reserveCapacity(tokens.size());
for (size_t i = 0; i < tokens.size(); ++i) {
- if (!validateToken(tokens[i], es))
+ if (!validateToken(tokens[i], exceptionState))
return;
- if (!containsInternal(tokens[i]))
- filteredTokens.append(tokens[i]);
+ if (containsInternal(tokens[i]))
+ continue;
+ if (filteredTokens.contains(tokens[i]))
+ continue;
+ filteredTokens.append(tokens[i]);
}
if (filteredTokens.isEmpty())
@@ -90,16 +94,16 @@ void DOMTokenList::add(const Vector<String>& tokens, ExceptionState& es)
setValue(addTokens(value(), filteredTokens));
}
-void DOMTokenList::remove(const AtomicString& token, ExceptionState& es)
+void DOMTokenList::remove(const AtomicString& token, ExceptionState& exceptionState)
{
Vector<String> tokens;
tokens.append(token.string());
- remove(tokens, es);
+ remove(tokens, exceptionState);
}
-void DOMTokenList::remove(const Vector<String>& tokens, ExceptionState& es)
+void DOMTokenList::remove(const Vector<String>& tokens, ExceptionState& exceptionState)
{
- if (!validateTokens(tokens, es))
+ if (!validateTokens(tokens, exceptionState))
return;
// Check using containsInternal first since it is a lot faster than going
@@ -116,9 +120,9 @@ void DOMTokenList::remove(const Vector<String>& tokens, ExceptionState& es)
setValue(removeTokens(value(), tokens));
}
-bool DOMTokenList::toggle(const AtomicString& token, ExceptionState& es)
+bool DOMTokenList::toggle(const AtomicString& token, ExceptionState& exceptionState)
{
- if (!validateToken(token, es))
+ if (!validateToken(token, exceptionState))
return false;
if (containsInternal(token)) {
@@ -129,9 +133,9 @@ bool DOMTokenList::toggle(const AtomicString& token, ExceptionState& es)
return true;
}
-bool DOMTokenList::toggle(const AtomicString& token, bool force, ExceptionState& es)
+bool DOMTokenList::toggle(const AtomicString& token, bool force, ExceptionState& exceptionState)
{
- if (!validateToken(token, es))
+ if (!validateToken(token, exceptionState))
return false;
if (force)
diff --git a/chromium/third_party/WebKit/Source/core/dom/DOMTokenList.idl b/chromium/third_party/WebKit/Source/core/dom/DOMTokenList.idl
index 3f166772624..9830b7ec93d 100644
--- a/chromium/third_party/WebKit/Source/core/dom/DOMTokenList.idl
+++ b/chromium/third_party/WebKit/Source/core/dom/DOMTokenList.idl
@@ -23,14 +23,14 @@
*/
[
- GenerateIsReachable=element
+ GenerateVisitDOMWrapper=element,
] interface DOMTokenList {
readonly attribute unsigned long length;
[TreatReturnedNullStringAs=Null] getter DOMString item(unsigned long index);
[RaisesException] boolean contains(DOMString token);
- [RaisesException, CustomElementCallbacks=Enable] void add(DOMString... tokens);
- [RaisesException, CustomElementCallbacks=Enable] void remove(DOMString... tokens);
- [RaisesException, CustomElementCallbacks=Enable] boolean toggle(DOMString token, optional boolean force);
+ [RaisesException, CustomElementCallbacks] void add(DOMString... tokens);
+ [RaisesException, CustomElementCallbacks] void remove(DOMString... tokens);
+ [RaisesException, CustomElementCallbacks] boolean toggle(DOMString token, optional boolean force);
[NotEnumerable] DOMString toString();
};
diff --git a/chromium/third_party/WebKit/Source/core/dom/DOMURL.cpp b/chromium/third_party/WebKit/Source/core/dom/DOMURL.cpp
new file mode 100644
index 00000000000..8881223f724
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/DOMURL.cpp
@@ -0,0 +1,94 @@
+/*
+ * Copyright (C) 2011 Google Inc. All rights reserved.
+ * Copyright (C) 2012 Motorola Mobility Inc.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/dom/DOMURL.h"
+
+#include "bindings/v8/ExceptionMessages.h"
+#include "bindings/v8/ExceptionState.h"
+#include "core/dom/ExceptionCode.h"
+#include "core/dom/ExecutionContext.h"
+#include "core/fetch/MemoryCache.h"
+#include "core/fileapi/Blob.h"
+#include "core/html/PublicURLManager.h"
+#include "platform/blob/BlobURL.h"
+#include "platform/weborigin/SecurityOrigin.h"
+#include "wtf/MainThread.h"
+
+namespace WebCore {
+
+DOMURL::DOMURL(const String& url, const KURL& base, ExceptionState& exceptionState)
+{
+ ScriptWrappable::init(this);
+ if (!base.isValid())
+ exceptionState.throwDOMException(SyntaxError, "Invalid base URL");
+
+ m_url = KURL(base, url);
+ if (!m_url.isValid())
+ exceptionState.throwDOMException(SyntaxError, "Invalid URL");
+}
+
+void DOMURL::setInput(const String& value)
+{
+ KURL url(blankURL(), value);
+ if (url.isValid()) {
+ m_url = url;
+ m_input = String();
+ } else {
+ m_url = KURL();
+ m_input = value;
+ }
+}
+
+String DOMURL::createObjectURL(ExecutionContext* executionContext, Blob* blob)
+{
+ if (!executionContext || !blob)
+ return String();
+ return createPublicURL(executionContext, blob);
+}
+
+String DOMURL::createPublicURL(ExecutionContext* executionContext, URLRegistrable* registrable)
+{
+ KURL publicURL = BlobURL::createPublicURL(executionContext->securityOrigin());
+ if (publicURL.isEmpty())
+ return String();
+
+ executionContext->publicURLManager().registerURL(executionContext->securityOrigin(), publicURL, registrable);
+
+ return publicURL.string();
+}
+
+void DOMURL::revokeObjectURL(ExecutionContext* executionContext, const String& urlString)
+{
+ if (!executionContext)
+ return;
+
+ KURL url(KURL(), urlString);
+ MemoryCache::removeURLFromCache(executionContext, url);
+ executionContext->publicURLManager().revoke(url);
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/DOMURL.h b/chromium/third_party/WebKit/Source/core/dom/DOMURL.h
new file mode 100644
index 00000000000..2b112f7d966
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/DOMURL.h
@@ -0,0 +1,82 @@
+/*
+ * Copyright (C) 2011 Google Inc. All rights reserved.
+ * Copyright (C) 2012 Motorola Mobility Inc.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef DOMURL_h
+#define DOMURL_h
+
+#include "bindings/v8/ScriptWrappable.h"
+#include "core/dom/DOMURLUtils.h"
+#include "platform/weborigin/KURL.h"
+#include "wtf/Forward.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefCounted.h"
+#include "wtf/text/WTFString.h"
+
+namespace WebCore {
+
+class Blob;
+class ExceptionState;
+class ExecutionContext;
+class URLRegistrable;
+
+class DOMURL FINAL : public ScriptWrappable, public DOMURLUtils, public RefCounted<DOMURL> {
+
+public:
+ static PassRefPtr<DOMURL> create(const String& url, ExceptionState& exceptionState)
+ {
+ return adoptRef(new DOMURL(url, blankURL(), exceptionState));
+ }
+ static PassRefPtr<DOMURL> create(const String& url, const String& base, ExceptionState& exceptionState)
+ {
+ return adoptRef(new DOMURL(url, KURL(KURL(), base), exceptionState));
+ }
+ static PassRefPtr<DOMURL> create(const String& url, PassRefPtr<DOMURL> base, ExceptionState& exceptionState)
+ {
+ ASSERT(base);
+ return adoptRef(new DOMURL(url, base->m_url, exceptionState));
+ }
+
+ static String createObjectURL(ExecutionContext*, Blob*);
+ static void revokeObjectURL(ExecutionContext*, const String&);
+
+ static String createPublicURL(ExecutionContext*, URLRegistrable*);
+
+ virtual KURL url() const OVERRIDE { return m_url; }
+ virtual void setURL(const KURL& url) OVERRIDE { m_url = url; }
+
+ virtual String input() const OVERRIDE { return m_input; }
+ virtual void setInput(const String&) OVERRIDE;
+
+private:
+ DOMURL(const String& url, const KURL& base, ExceptionState&);
+
+ KURL m_url;
+ String m_input;
+};
+
+} // namespace WebCore
+
+#endif // DOMURL_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/DOMURLUtils.cpp b/chromium/third_party/WebKit/Source/core/dom/DOMURLUtils.cpp
new file mode 100644
index 00000000000..7e1fa195c5a
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/DOMURLUtils.cpp
@@ -0,0 +1,142 @@
+/*
+ * Copyright (C) 2011 Google Inc. All rights reserved.
+ * Copyright (C) 2012 Motorola Mobility Inc.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/dom/DOMURLUtils.h"
+
+#include "platform/weborigin/KnownPorts.h"
+
+namespace WebCore {
+
+void DOMURLUtils::setHref(DOMURLUtils* impl, const String& value)
+{
+ impl->setInput(value);
+}
+
+void DOMURLUtils::setProtocol(DOMURLUtils* impl, const String& value)
+{
+ KURL url = impl->url();
+ if (url.isNull())
+ return;
+ url.setProtocol(value);
+ impl->setURL(url);
+}
+
+void DOMURLUtils::setUsername(DOMURLUtils* impl, const String& value)
+{
+ KURL url = impl->url();
+ if (url.isNull())
+ return;
+ url.setUser(value);
+ impl->setURL(url);
+}
+
+void DOMURLUtils::setPassword(DOMURLUtils* impl, const String& value)
+{
+ KURL url = impl->url();
+ if (url.isNull())
+ return;
+ url.setPass(value);
+ impl->setURL(url);
+}
+
+void DOMURLUtils::setHost(DOMURLUtils* impl, const String& value)
+{
+ if (value.isEmpty())
+ return;
+
+ KURL url = impl->url();
+ if (!url.canSetHostOrPort())
+ return;
+
+ url.setHostAndPort(value);
+ impl->setURL(url);
+}
+
+void DOMURLUtils::setHostname(DOMURLUtils* impl, const String& value)
+{
+ KURL url = impl->url();
+ if (!url.canSetHostOrPort())
+ return;
+
+ // Before setting new value:
+ // Remove all leading U+002F SOLIDUS ("/") characters.
+ unsigned i = 0;
+ unsigned hostLength = value.length();
+ while (value[i] == '/')
+ i++;
+
+ if (i == hostLength)
+ return;
+
+ url.setHost(value.substring(i));
+
+ impl->setURL(url);
+}
+
+void DOMURLUtils::setPort(DOMURLUtils* impl, const String& value)
+{
+ KURL url = impl->url();
+ if (!url.canSetHostOrPort())
+ return;
+
+ url.setPort(value);
+ impl->setURL(url);
+}
+
+void DOMURLUtils::setPathname(DOMURLUtils* impl, const String& value)
+{
+ KURL url = impl->url();
+ if (!url.canSetPathname())
+ return;
+ url.setPath(value);
+ impl->setURL(url);
+}
+
+void DOMURLUtils::setSearch(DOMURLUtils* impl, const String& value)
+{
+ KURL url = impl->url();
+ if (!url.isValid())
+ return;
+ url.setQuery(value);
+ impl->setURL(url);
+}
+
+void DOMURLUtils::setHash(DOMURLUtils* impl, const String& value)
+{
+ KURL url = impl->url();
+ if (url.isNull())
+ return;
+
+ if (value[0] == '#')
+ url.setFragmentIdentifier(value.substring(1));
+ else
+ url.setFragmentIdentifier(value);
+
+ impl->setURL(url);
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/DOMURLUtils.h b/chromium/third_party/WebKit/Source/core/dom/DOMURLUtils.h
new file mode 100644
index 00000000000..1987ecd7205
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/DOMURLUtils.h
@@ -0,0 +1,59 @@
+/*
+ * Copyright (C) 2011 Google Inc. All rights reserved.
+ * Copyright (C) 2012 Motorola Mobility Inc.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef DOMURLUtils_h
+#define DOMURLUtils_h
+
+#include "core/dom/DOMURLUtilsReadOnly.h"
+#include "wtf/Forward.h"
+#include "wtf/text/WTFString.h"
+
+namespace WebCore {
+
+class KURL;
+
+class DOMURLUtils : public DOMURLUtilsReadOnly {
+public:
+ virtual void setURL(const KURL&) = 0;
+ virtual void setInput(const String&) = 0;
+ virtual ~DOMURLUtils() { };
+
+ static void setHref(DOMURLUtils*, const String&);
+
+ static void setProtocol(DOMURLUtils*, const String&);
+ static void setUsername(DOMURLUtils*, const String&);
+ static void setPassword(DOMURLUtils*, const String&);
+ static void setHost(DOMURLUtils*, const String&);
+ static void setHostname(DOMURLUtils*, const String&);
+ static void setPort(DOMURLUtils*, const String&);
+ static void setPathname(DOMURLUtils*, const String&);
+ static void setSearch(DOMURLUtils*, const String&);
+ static void setHash(DOMURLUtils*, const String&);
+};
+
+} // namespace WebCore
+
+#endif // DOMURLUtils_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/DOMURLUtilsReadOnly.cpp b/chromium/third_party/WebKit/Source/core/dom/DOMURLUtilsReadOnly.cpp
new file mode 100644
index 00000000000..15b1268115a
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/DOMURLUtilsReadOnly.cpp
@@ -0,0 +1,81 @@
+/*
+ * Copyright (C) 2011 Google Inc. All rights reserved.
+ * Copyright (C) 2012 Motorola Mobility Inc.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/dom/DOMURLUtilsReadOnly.h"
+
+#include "platform/weborigin/KnownPorts.h"
+#include "platform/weborigin/SecurityOrigin.h"
+
+namespace WebCore {
+
+String DOMURLUtilsReadOnly::href(DOMURLUtilsReadOnly* impl)
+{
+ const KURL& url = impl->url();
+ if (url.isNull())
+ return impl->input();
+ return url.string();
+}
+
+String DOMURLUtilsReadOnly::origin(const KURL& url)
+{
+ if (url.isNull())
+ return "";
+ return SecurityOrigin::create(url)->toString();
+}
+
+String DOMURLUtilsReadOnly::host(const KURL& url)
+{
+ if (url.hostEnd() == url.pathStart())
+ return url.host();
+ if (isDefaultPortForProtocol(url.port(), url.protocol()))
+ return url.host();
+ return url.host() + ":" + String::number(url.port());
+}
+
+String DOMURLUtilsReadOnly::port(const KURL& url)
+{
+ if (url.hasPort())
+ return String::number(url.port());
+
+ return emptyString();
+}
+
+String DOMURLUtilsReadOnly::search(const KURL& url)
+{
+ String query = url.query();
+ return query.isEmpty() ? emptyString() : "?" + query;
+}
+
+String DOMURLUtilsReadOnly::hash(const KURL& url)
+{
+ String fragmentIdentifier = url.fragmentIdentifier();
+ if (fragmentIdentifier.isEmpty())
+ return emptyString();
+ return AtomicString(String("#" + fragmentIdentifier));
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/DOMURLUtilsReadOnly.h b/chromium/third_party/WebKit/Source/core/dom/DOMURLUtilsReadOnly.h
new file mode 100644
index 00000000000..36d60851e3e
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/DOMURLUtilsReadOnly.h
@@ -0,0 +1,77 @@
+/*
+ * Copyright (C) 2011 Google Inc. All rights reserved.
+ * Copyright (C) 2012 Motorola Mobility Inc.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef DOMURLUtilsReadOnly_h
+#define DOMURLUtilsReadOnly_h
+
+#include "platform/weborigin/KURL.h"
+#include "wtf/Forward.h"
+#include "wtf/text/WTFString.h"
+
+namespace WebCore {
+
+class DOMURLUtilsReadOnly {
+public:
+ virtual KURL url() const = 0;
+ virtual String input() const = 0;
+ virtual ~DOMURLUtilsReadOnly() { };
+
+ static String href(DOMURLUtilsReadOnly*);
+
+ static String origin(const KURL&);
+ static String origin(DOMURLUtilsReadOnly* impl) { return origin(impl->url()); }
+
+ static String protocol(const KURL& url) { return url.protocol() + ":"; }
+ static String protocol(DOMURLUtilsReadOnly* impl) { return protocol(impl->url()); }
+
+ static String username(const KURL& url) { return url.user(); }
+ static String username(DOMURLUtilsReadOnly* impl) { return username(impl->url()); }
+
+ static String password(const KURL& url) { return url.pass(); }
+ static String password(DOMURLUtilsReadOnly* impl) { return password(impl->url()); }
+
+ static String host(const KURL&);
+ static String host(DOMURLUtilsReadOnly* impl) { return host(impl->url()); }
+
+ static String hostname(const KURL& url) { return url.host(); }
+ static String hostname(DOMURLUtilsReadOnly* impl) { return hostname(impl->url()); }
+
+ static String port(const KURL&);
+ static String port(DOMURLUtilsReadOnly* impl) { return port(impl->url()); }
+
+ static String pathname(const KURL& url) { return url.path(); }
+ static String pathname(DOMURLUtilsReadOnly* impl) { return pathname(impl->url()); }
+
+ static String search(const KURL&);
+ static String search(DOMURLUtilsReadOnly* impl) { return search(impl->url()); }
+
+ static String hash(const KURL&);
+ static String hash(DOMURLUtilsReadOnly* impl) { return hash(impl->url()); }
+};
+
+} // namespace WebCore
+
+#endif // DOMURLUtilsReadOnly_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/DataTransferItem.cpp b/chromium/third_party/WebKit/Source/core/dom/DataTransferItem.cpp
index 7d79f11f4f0..aef76486648 100644
--- a/chromium/third_party/WebKit/Source/core/dom/DataTransferItem.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/DataTransferItem.cpp
@@ -31,10 +31,69 @@
#include "config.h"
#include "core/dom/DataTransferItem.h"
+#include "bindings/v8/V8Binding.h"
+#include "core/dom/Clipboard.h"
+#include "core/dom/StringCallback.h"
+#include "core/platform/chromium/ChromiumDataObjectItem.h"
+#include "wtf/StdLibExtras.h"
+
namespace WebCore {
-const char DataTransferItem::kindString[] = "string";
-const char DataTransferItem::kindFile[] = "file";
+PassRefPtr<DataTransferItem> DataTransferItem::create(PassRefPtr<Clipboard> clipboard, PassRefPtr<ChromiumDataObjectItem> item)
+{
+ return adoptRef(new DataTransferItem(clipboard, item));
+}
+
+DataTransferItem::~DataTransferItem()
+{
+}
+
+String DataTransferItem::kind() const
+{
+ DEFINE_STATIC_LOCAL(const String, kindString, ("string"));
+ DEFINE_STATIC_LOCAL(const String, kindFile, ("file"));
+ if (!m_clipboard->canReadTypes())
+ return String();
+ switch (m_item->kind()) {
+ case ChromiumDataObjectItem::StringKind:
+ return kindString;
+ case ChromiumDataObjectItem::FileKind:
+ return kindFile;
+ }
+ ASSERT_NOT_REACHED();
+ return String();
+}
+
+String DataTransferItem::type() const
+{
+ if (!m_clipboard->canReadTypes())
+ return String();
+ return m_item->type();
+}
+
+void DataTransferItem::getAsString(ExecutionContext* context, PassOwnPtr<StringCallback> callback) const
+{
+ if (!m_clipboard->canReadData())
+ return;
+
+ m_item->getAsString(callback, context);
+}
+
+PassRefPtr<Blob> DataTransferItem::getAsFile() const
+{
+ if (!m_clipboard->canReadData())
+ return 0;
+
+ return m_item->getAsFile();
+}
+
+DataTransferItem::DataTransferItem(PassRefPtr<Clipboard> clipboard, PassRefPtr<ChromiumDataObjectItem> item)
+ : m_clipboard(clipboard)
+ , m_item(item)
+{
+ ScriptWrappable::init(this);
+}
+
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/DataTransferItem.h b/chromium/third_party/WebKit/Source/core/dom/DataTransferItem.h
index 31fb28c4a19..b7e200cec9f 100644
--- a/chromium/third_party/WebKit/Source/core/dom/DataTransferItem.h
+++ b/chromium/third_party/WebKit/Source/core/dom/DataTransferItem.h
@@ -34,31 +34,36 @@
#include "bindings/v8/ScriptWrappable.h"
#include "wtf/Forward.h"
#include "wtf/RefCounted.h"
+#include "wtf/RefPtr.h"
namespace WebCore {
class Blob;
+class ChromiumDataObjectItem;
+class Clipboard;
class File;
class StringCallback;
-class ScriptExecutionContext;
+class ExecutionContext;
class DataTransferItem : public RefCounted<DataTransferItem>, public ScriptWrappable {
public:
- DataTransferItem()
- {
- ScriptWrappable::init(this);
- }
+ static PassRefPtr<DataTransferItem> create(PassRefPtr<Clipboard>, PassRefPtr<ChromiumDataObjectItem>);
+ ~DataTransferItem();
- virtual ~DataTransferItem() { }
+ String kind() const;
+ String type() const;
- static const char kindString[];
- static const char kindFile[];
+ void getAsString(ExecutionContext*, PassOwnPtr<StringCallback>) const;
+ PassRefPtr<Blob> getAsFile() const;
- virtual String kind() const = 0;
- virtual String type() const = 0;
+ Clipboard* clipboard() { return m_clipboard.get(); }
+ ChromiumDataObjectItem* dataObjectItem() { return m_item.get(); }
- virtual void getAsString(PassRefPtr<StringCallback>) const = 0;
- virtual PassRefPtr<Blob> getAsFile() const = 0;
+private:
+ DataTransferItem(PassRefPtr<Clipboard>, PassRefPtr<ChromiumDataObjectItem>);
+
+ RefPtr<Clipboard> m_clipboard;
+ RefPtr<ChromiumDataObjectItem> m_item;
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/DataTransferItem.idl b/chromium/third_party/WebKit/Source/core/dom/DataTransferItem.idl
index 7a3327fa53a..849965218fc 100644
--- a/chromium/third_party/WebKit/Source/core/dom/DataTransferItem.idl
+++ b/chromium/third_party/WebKit/Source/core/dom/DataTransferItem.idl
@@ -34,7 +34,7 @@
readonly attribute DOMString kind;
readonly attribute DOMString type;
- void getAsString(StringCallback? callback);
+ [CallWith=ExecutionContext] void getAsString(StringCallback? callback);
Blob getAsFile();
};
diff --git a/chromium/third_party/WebKit/Source/core/dom/DataTransferItemList.cpp b/chromium/third_party/WebKit/Source/core/dom/DataTransferItemList.cpp
new file mode 100644
index 00000000000..8facacb9096
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/DataTransferItemList.cpp
@@ -0,0 +1,110 @@
+/*
+ * Copyright (C) 2006, 2007 Apple Inc. All rights reserved.
+ * Copyright (C) 2008, 2009 Google Inc.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/dom/DataTransferItemList.h"
+
+#include "bindings/v8/ExceptionState.h"
+#include "core/dom/Clipboard.h"
+#include "core/dom/DataTransferItem.h"
+#include "core/dom/ExceptionCode.h"
+#include "core/platform/chromium/ChromiumDataObject.h"
+
+namespace WebCore {
+
+PassRefPtr<DataTransferItemList> DataTransferItemList::create(PassRefPtr<Clipboard> clipboard, PassRefPtr<ChromiumDataObject> list)
+{
+ return adoptRef(new DataTransferItemList(clipboard, list));
+}
+
+DataTransferItemList::~DataTransferItemList()
+{
+}
+
+size_t DataTransferItemList::length() const
+{
+ if (!m_clipboard->canReadTypes())
+ return 0;
+ return m_dataObject->length();
+}
+
+PassRefPtr<DataTransferItem> DataTransferItemList::item(unsigned long index)
+{
+ if (!m_clipboard->canReadTypes())
+ return 0;
+ RefPtr<ChromiumDataObjectItem> item = m_dataObject->item(index);
+ if (!item)
+ return 0;
+
+ return DataTransferItem::create(m_clipboard, item);
+}
+
+void DataTransferItemList::deleteItem(unsigned long index, ExceptionState& exceptionState)
+{
+ if (!m_clipboard->canWriteData()) {
+ exceptionState.throwDOMException(InvalidStateError, "The list is not writable.");
+ return;
+ }
+ m_dataObject->deleteItem(index);
+}
+
+void DataTransferItemList::clear()
+{
+ if (!m_clipboard->canWriteData())
+ return;
+ m_dataObject->clearAll();
+}
+
+PassRefPtr<DataTransferItem> DataTransferItemList::add(const String& data, const String& type, ExceptionState& exceptionState)
+{
+ if (!m_clipboard->canWriteData())
+ return 0;
+ RefPtr<ChromiumDataObjectItem> item = m_dataObject->add(data, type);
+ if (!item) {
+ exceptionState.throwDOMException(NotSupportedError, "An item already exists for type '" + type + "'.");
+ return 0;
+ }
+ return DataTransferItem::create(m_clipboard, item);
+}
+
+PassRefPtr<DataTransferItem> DataTransferItemList::add(PassRefPtr<File> file)
+{
+ if (!m_clipboard->canWriteData())
+ return 0;
+ RefPtr<ChromiumDataObjectItem> item = m_dataObject->add(file);
+ if (!item)
+ return 0;
+ return DataTransferItem::create(m_clipboard, item);
+}
+
+DataTransferItemList::DataTransferItemList(PassRefPtr<Clipboard> clipboard, PassRefPtr<ChromiumDataObject> dataObject)
+ : m_clipboard(clipboard)
+ , m_dataObject(dataObject)
+{
+ ScriptWrappable::init(this);
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/DataTransferItemList.h b/chromium/third_party/WebKit/Source/core/dom/DataTransferItemList.h
index 90d847f886a..f296c7b001a 100644
--- a/chromium/third_party/WebKit/Source/core/dom/DataTransferItemList.h
+++ b/chromium/third_party/WebKit/Source/core/dom/DataTransferItemList.h
@@ -32,32 +32,36 @@
#define DataTransferItemList_h
#include "bindings/v8/ScriptWrappable.h"
-#include "core/dom/DataTransferItem.h"
#include "wtf/Forward.h"
#include "wtf/RefCounted.h"
+#include "wtf/RefPtr.h"
namespace WebCore {
+class ChromiumDataObject;
class Clipboard;
+class DataTransferItem;
class File;
class ExceptionState;
class DataTransferItemList : public RefCounted<DataTransferItemList>, public ScriptWrappable {
public:
- DataTransferItemList()
- {
- ScriptWrappable::init(this);
- }
+ static PassRefPtr<DataTransferItemList> create(PassRefPtr<Clipboard>, PassRefPtr<ChromiumDataObject>);
+ ~DataTransferItemList();
- virtual ~DataTransferItemList() { }
+ size_t length() const;
+ PassRefPtr<DataTransferItem> item(unsigned long index);
+ void deleteItem(unsigned long index, ExceptionState&);
+ void clear();
+ PassRefPtr<DataTransferItem> add(const String& data, const String& type, ExceptionState&);
+ PassRefPtr<DataTransferItem> add(PassRefPtr<File>);
- virtual size_t length() const = 0;
- virtual PassRefPtr<DataTransferItem> item(unsigned long index) = 0;
- virtual void deleteItem(unsigned long index, ExceptionState&) = 0;
- virtual void clear() = 0;
- virtual PassRefPtr<DataTransferItem> add(const String& data, const String& type, ExceptionState&) = 0;
- virtual PassRefPtr<DataTransferItem> add(PassRefPtr<File>) = 0;
+private:
+ DataTransferItemList(PassRefPtr<Clipboard>, PassRefPtr<ChromiumDataObject>);
+
+ RefPtr<Clipboard> m_clipboard;
+ RefPtr<ChromiumDataObject> m_dataObject;
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/DatasetDOMStringMap.cpp b/chromium/third_party/WebKit/Source/core/dom/DatasetDOMStringMap.cpp
index fbeaa54b6dd..921531948ca 100644
--- a/chromium/third_party/WebKit/Source/core/dom/DatasetDOMStringMap.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/DatasetDOMStringMap.cpp
@@ -26,6 +26,7 @@
#include "config.h"
#include "core/dom/DatasetDOMStringMap.h"
+#include "bindings/v8/ExceptionMessages.h"
#include "bindings/v8/ExceptionState.h"
#include "core/dom/Attribute.h"
#include "core/dom/Element.h"
@@ -82,7 +83,7 @@ static bool propertyNameMatchesAttributeName(const String& propertyName, const S
unsigned p = 0;
bool wordBoundary = false;
while (a < attributeLength && p < propertyLength) {
- if (attributeName[a] == '-' && a + 1 < attributeLength && attributeName[a + 1] != '-')
+ if (attributeName[a] == '-' && a + 1 < attributeLength && isASCIILower(attributeName[a + 1]))
wordBoundary = true;
else {
if ((wordBoundary ? toASCIIUpper(attributeName[a]) : attributeName[a]) != propertyName[p])
@@ -177,20 +178,20 @@ bool DatasetDOMStringMap::contains(const String& name)
return false;
}
-void DatasetDOMStringMap::setItem(const String& name, const String& value, ExceptionState& es)
+void DatasetDOMStringMap::setItem(const String& name, const String& value, ExceptionState& exceptionState)
{
if (!isValidPropertyName(name)) {
- es.throwDOMException(SyntaxError);
+ exceptionState.throwDOMException(SyntaxError, ExceptionMessages::failedToSet(name, "DOMStringMap", "'" + name + "' is not a valid property name."));
return;
}
- m_element->setAttribute(convertPropertyNameToAttributeName(name), value, es);
+ m_element->setAttribute(convertPropertyNameToAttributeName(name), value, exceptionState);
}
-void DatasetDOMStringMap::deleteItem(const String& name, ExceptionState& es)
+void DatasetDOMStringMap::deleteItem(const String& name, ExceptionState& exceptionState)
{
if (!isValidPropertyName(name)) {
- es.throwDOMException(SyntaxError);
+ exceptionState.throwDOMException(SyntaxError, ExceptionMessages::failedToDelete(name, "DOMStringMap", "'" + name + "' is not a valid property name."));
return;
}
diff --git a/chromium/third_party/WebKit/Source/core/dom/DecodedDataDocumentParser.cpp b/chromium/third_party/WebKit/Source/core/dom/DecodedDataDocumentParser.cpp
index c7345802679..7f3c01f23d8 100644
--- a/chromium/third_party/WebKit/Source/core/dom/DecodedDataDocumentParser.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/DecodedDataDocumentParser.cpp
@@ -27,60 +27,86 @@
#include "core/dom/DecodedDataDocumentParser.h"
#include "core/dom/Document.h"
+#include "core/dom/DocumentEncodingData.h"
#include "core/fetch/TextResourceDecoder.h"
namespace WebCore {
DecodedDataDocumentParser::DecodedDataDocumentParser(Document* document)
: DocumentParser(document)
+ , m_hasAppendedData(false)
{
}
-size_t DecodedDataDocumentParser::appendBytes(const char* data, size_t length)
+DecodedDataDocumentParser::~DecodedDataDocumentParser()
+{
+}
+
+void DecodedDataDocumentParser::setDecoder(PassOwnPtr<TextResourceDecoder> decoder)
+{
+ m_decoder = decoder;
+}
+
+TextResourceDecoder* DecodedDataDocumentParser::decoder()
+{
+ return m_decoder.get();
+}
+
+void DecodedDataDocumentParser::setHasAppendedData()
+{
+ m_hasAppendedData = true;
+}
+
+void DecodedDataDocumentParser::appendBytes(const char* data, size_t length)
{
if (!length)
- return 0;
+ return;
// This should be checking isStopped(), but XMLDocumentParser prematurely
// stops parsing when handling an XSLT processing instruction and still
// needs to receive decoded bytes.
if (isDetached())
- return 0;
-
- String decoded = document()->decoder()->decode(data, length);
- document()->setEncoding(document()->decoder()->encoding());
-
- if (decoded.isEmpty())
- return 0;
+ return;
- size_t consumedChars = decoded.length();
- append(decoded.releaseImpl());
-
- return consumedChars;
+ String decoded = m_decoder->decode(data, length);
+ updateDocument(decoded);
}
-size_t DecodedDataDocumentParser::flush()
+void DecodedDataDocumentParser::flush()
{
// This should be checking isStopped(), but XMLDocumentParser prematurely
// stops parsing when handling an XSLT processing instruction and still
// needs to receive decoded bytes.
if (isDetached())
- return 0;
+ return;
// null decoder indicates there is no data received.
// We have nothing to do in that case.
- TextResourceDecoder* decoder = document()->decoder();
- if (!decoder)
- return 0;
- String remainingData = decoder->flush();
- document()->setEncoding(document()->decoder()->encoding());
- if (remainingData.isEmpty())
- return 0;
-
- size_t consumedChars = remainingData.length();
- append(remainingData.releaseImpl());
-
- return consumedChars;
+ if (!m_decoder)
+ return;
+
+ String remainingData = m_decoder->flush();
+ updateDocument(remainingData);
+}
+
+void DecodedDataDocumentParser::updateDocument(String& decodedData)
+{
+ DocumentEncodingData encodingData;
+ encodingData.encoding = m_decoder->encoding();
+ encodingData.wasDetectedHeuristically = m_decoder->encodingWasDetectedHeuristically();
+ encodingData.sawDecodingError = m_decoder->sawError();
+ document()->setEncodingData(encodingData);
+
+ if (decodedData.isEmpty())
+ return;
+
+ append(decodedData.releaseImpl());
+ // FIXME: Should be removed as part of https://code.google.com/p/chromium/issues/detail?id=319643
+ if (!m_hasAppendedData) {
+ m_hasAppendedData = true;
+ if (m_decoder->encoding().usesVisualOrdering())
+ document()->setVisuallyOrdered();
+ }
}
};
diff --git a/chromium/third_party/WebKit/Source/core/dom/DecodedDataDocumentParser.h b/chromium/third_party/WebKit/Source/core/dom/DecodedDataDocumentParser.h
index c931c0c7402..453147d0ecd 100644
--- a/chromium/third_party/WebKit/Source/core/dom/DecodedDataDocumentParser.h
+++ b/chromium/third_party/WebKit/Source/core/dom/DecodedDataDocumentParser.h
@@ -27,8 +27,11 @@
#define DecodedDataDocumentParser_h
#include "core/dom/DocumentParser.h"
+#include "wtf/OwnPtr.h"
+#include "wtf/RefPtr.h"
namespace WebCore {
+class TextResourceDecoder;
class DecodedDataDocumentParser : public DocumentParser {
public:
@@ -36,17 +39,26 @@ public:
// XMLHttpRequest if the responseXML was well formed.
virtual bool wellFormed() const { return true; }
+ // The below functions are used by DocumentWriter (the loader).
+ virtual void appendBytes(const char* bytes, size_t length) OVERRIDE;
+ virtual void flush() OVERRIDE;
+ virtual bool needsDecoder() const OVERRIDE { return !m_decoder; }
+ virtual void setDecoder(PassOwnPtr<TextResourceDecoder>) OVERRIDE;
+ virtual TextResourceDecoder* decoder() OVERRIDE;
+ virtual void setHasAppendedData() OVERRIDE;
+
protected:
explicit DecodedDataDocumentParser(Document*);
+ virtual ~DecodedDataDocumentParser();
private:
// append is used by DocumentWriter::replaceDocument.
virtual void append(PassRefPtr<StringImpl>) = 0;
- // appendBytes and flush are used by DocumentWriter (the loader).
- virtual size_t appendBytes(const char* bytes, size_t length) OVERRIDE;
- virtual size_t flush() OVERRIDE;
- virtual bool needsDecoder() const OVERRIDE { return true; }
+ void updateDocument(String& decodedData);
+
+ bool m_hasAppendedData;
+ OwnPtr<TextResourceDecoder> m_decoder;
};
}
diff --git a/chromium/third_party/WebKit/Source/core/dom/DeviceOrientationClient.h b/chromium/third_party/WebKit/Source/core/dom/DeviceOrientationClient.h
deleted file mode 100644
index 14de5264d2c..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/DeviceOrientationClient.h
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright 2010, The Android Open Source Project
- * Copyright (C) 2012 Samsung Electronics. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef DeviceOrientationClient_h
-#define DeviceOrientationClient_h
-
-#include "core/page/DeviceClient.h"
-
-namespace WebCore {
-
-class DeviceOrientationController;
-class DeviceOrientationData;
-class Page;
-
-class DeviceOrientationClient : public DeviceClient {
-public:
- virtual ~DeviceOrientationClient() {}
- virtual void setController(DeviceOrientationController*) = 0;
- virtual DeviceOrientationData* lastOrientation() const = 0;
- virtual void deviceOrientationControllerDestroyed() = 0;
-};
-
-void provideDeviceOrientationTo(Page*, DeviceOrientationClient*);
-
-} // namespace WebCore
-
-#endif // DeviceOrientationClient_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/DeviceOrientationController.cpp b/chromium/third_party/WebKit/Source/core/dom/DeviceOrientationController.cpp
deleted file mode 100644
index 90710985971..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/DeviceOrientationController.cpp
+++ /dev/null
@@ -1,92 +0,0 @@
-/*
- * Copyright 2010, The Android Open Source Project
- * Copyright (C) 2012 Samsung Electronics. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/dom/DeviceOrientationController.h"
-
-#include "core/dom/DeviceOrientationClient.h"
-#include "core/inspector/InspectorInstrumentation.h"
-#include "modules/device_orientation/DeviceOrientationEvent.h"
-
-namespace WebCore {
-
-DeviceOrientationController::DeviceOrientationController(Page* page, DeviceOrientationClient* client)
- : DeviceController(client)
- , m_page(page)
-{
- ASSERT(m_client);
- deviceOrientationClient()->setController(this);
-}
-
-PassOwnPtr<DeviceOrientationController> DeviceOrientationController::create(Page* page, DeviceOrientationClient* client)
-{
- return adoptPtr(new DeviceOrientationController(page, client));
-}
-
-void DeviceOrientationController::didChangeDeviceOrientation(DeviceOrientationData* orientation)
-{
- orientation = InspectorInstrumentation::overrideDeviceOrientation(m_page, orientation);
- dispatchDeviceEvent(DeviceOrientationEvent::create(eventNames().deviceorientationEvent, orientation));
-}
-
-DeviceOrientationClient* DeviceOrientationController::deviceOrientationClient()
-{
- return static_cast<DeviceOrientationClient*>(m_client);
-}
-
-bool DeviceOrientationController::hasLastData()
-{
- return deviceOrientationClient()->lastOrientation();
-}
-
-PassRefPtr<Event> DeviceOrientationController::getLastEvent()
-{
- return DeviceOrientationEvent::create(eventNames().deviceorientationEvent, deviceOrientationClient()->lastOrientation());
-}
-
-const char* DeviceOrientationController::supplementName()
-{
- return "DeviceOrientationController";
-}
-
-DeviceOrientationController* DeviceOrientationController::from(Page* page)
-{
- return static_cast<DeviceOrientationController*>(Supplement<Page>::from(page, supplementName()));
-}
-
-bool DeviceOrientationController::isActiveAt(Page* page)
-{
- if (DeviceOrientationController* self = DeviceOrientationController::from(page))
- return self->isActive();
- return false;
-}
-
-void provideDeviceOrientationTo(Page* page, DeviceOrientationClient* client)
-{
- DeviceOrientationController::provideTo(page, DeviceOrientationController::supplementName(), DeviceOrientationController::create(page, client));
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/DeviceOrientationController.h b/chromium/third_party/WebKit/Source/core/dom/DeviceOrientationController.h
deleted file mode 100644
index 3173d397a65..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/DeviceOrientationController.h
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Copyright 2010, The Android Open Source Project
- * Copyright (C) 2012 Samsung Electronics. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef DeviceOrientationController_h
-#define DeviceOrientationController_h
-
-#include "core/page/DeviceController.h"
-
-namespace WebCore {
-
-class DeviceOrientationClient;
-class DeviceOrientationData;
-
-class DeviceOrientationController : public DeviceController {
-public:
- ~DeviceOrientationController() { };
-
- static PassOwnPtr<DeviceOrientationController> create(Page*, DeviceOrientationClient*);
-
- void didChangeDeviceOrientation(DeviceOrientationData*);
- DeviceOrientationClient* deviceOrientationClient();
-
- virtual bool hasLastData() OVERRIDE;
- virtual PassRefPtr<Event> getLastEvent() OVERRIDE;
-
- static const char* supplementName();
- static DeviceOrientationController* from(Page*);
- static bool isActiveAt(Page*);
-
-private:
- DeviceOrientationController(Page*, DeviceOrientationClient*);
-
- Page* m_page;
-};
-
-} // namespace WebCore
-
-#endif // DeviceOrientationController_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/Document.cpp b/chromium/third_party/WebKit/Source/core/dom/Document.cpp
index 9a791f8db45..d1b53da3212 100644
--- a/chromium/third_party/WebKit/Source/core/dom/Document.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/Document.cpp
@@ -42,40 +42,39 @@
#include "bindings/v8/ExceptionStatePlaceholder.h"
#include "bindings/v8/ScriptController.h"
#include "core/accessibility/AXObjectCache.h"
+#include "core/animation/AnimationClock.h"
+#include "core/animation/DocumentAnimations.h"
#include "core/animation/DocumentTimeline.h"
+#include "core/animation/css/TransitionTimeline.h"
#include "core/css/CSSDefaultStyleSheets.h"
#include "core/css/CSSFontSelector.h"
#include "core/css/CSSStyleDeclaration.h"
#include "core/css/CSSStyleSheet.h"
-#include "core/css/FontFaceSet.h"
#include "core/css/MediaQueryMatcher.h"
#include "core/css/StylePropertySet.h"
#include "core/css/StyleSheetContents.h"
#include "core/css/StyleSheetList.h"
#include "core/css/resolver/FontBuilder.h"
#include "core/css/resolver/StyleResolver.h"
+#include "core/css/resolver/StyleResolverStats.h"
+#include "core/dom/AddConsoleMessageTask.h"
#include "core/dom/Attr.h"
-#include "core/dom/BeforeUnloadEvent.h"
#include "core/dom/CDATASection.h"
#include "core/dom/Comment.h"
#include "core/dom/ContextFeatures.h"
-#include "core/dom/CustomElementRegistrationContext.h"
#include "core/dom/DOMImplementation.h"
#include "core/dom/DOMNamedFlowCollection.h"
-#include "core/dom/DocumentEventQueue.h"
#include "core/dom/DocumentFragment.h"
+#include "core/dom/DocumentLifecycleNotifier.h"
#include "core/dom/DocumentLifecycleObserver.h"
#include "core/dom/DocumentMarkerController.h"
#include "core/dom/DocumentSharedObjectPool.h"
#include "core/dom/DocumentType.h"
#include "core/dom/Element.h"
#include "core/dom/ElementTraversal.h"
-#include "core/dom/Event.h"
-#include "core/dom/EventFactory.h"
-#include "core/dom/EventListener.h"
-#include "core/dom/EventNames.h"
#include "core/dom/ExceptionCode.h"
-#include "core/dom/HashChangeEvent.h"
+#include "core/dom/ExecutionContextTask.h"
+#include "core/dom/MainThreadTaskRunner.h"
#include "core/dom/NamedFlowCollection.h"
#include "core/dom/NodeChildRemovalTracker.h"
#include "core/dom/NodeFilter.h"
@@ -85,13 +84,9 @@
#include "core/dom/NodeRenderingTraversal.h"
#include "core/dom/NodeTraversal.h"
#include "core/dom/NodeWithIndex.h"
-#include "core/dom/PageTransitionEvent.h"
-#include "core/dom/PopStateEvent.h"
#include "core/dom/PostAttachCallbacks.h"
#include "core/dom/ProcessingInstruction.h"
-#include "core/dom/QualifiedName.h"
#include "core/dom/RequestAnimationFrameCallback.h"
-#include "core/dom/ScopedEventQueue.h"
#include "core/dom/ScriptRunner.h"
#include "core/dom/ScriptedAnimationController.h"
#include "core/dom/SelectorQuery.h"
@@ -99,14 +94,30 @@
#include "core/dom/TouchList.h"
#include "core/dom/TransformSource.h"
#include "core/dom/TreeWalker.h"
-#include "core/dom/UserActionElementSet.h"
#include "core/dom/VisitedLinkState.h"
+#include "core/dom/custom/CustomElementRegistrationContext.h"
#include "core/dom/shadow/ElementShadow.h"
#include "core/dom/shadow/ShadowRoot.h"
#include "core/editing/Editor.h"
#include "core/editing/FrameSelection.h"
+#include "core/editing/SpellChecker.h"
+#include "core/events/BeforeUnloadEvent.h"
+#include "core/events/Event.h"
+#include "core/events/EventFactory.h"
+#include "core/events/EventListener.h"
+#include "core/events/HashChangeEvent.h"
+#include "core/events/PageTransitionEvent.h"
+#include "core/events/ScopedEventQueue.h"
+#include "core/events/ThreadLocalEventNames.h"
#include "core/fetch/ResourceFetcher.h"
#include "core/fetch/TextResourceDecoder.h"
+#include "core/frame/ContentSecurityPolicy.h"
+#include "core/frame/DOMSecurityPolicy.h"
+#include "core/frame/DOMWindow.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
+#include "core/frame/History.h"
+#include "core/frame/animation/AnimationController.h"
#include "core/html/HTMLAllCollection.h"
#include "core/html/HTMLAnchorElement.h"
#include "core/html/HTMLCanvasElement.h"
@@ -137,51 +148,42 @@
#include "core/loader/FrameLoader.h"
#include "core/loader/FrameLoaderClient.h"
#include "core/loader/ImageLoader.h"
-#include "core/loader/Prerenderer.h"
#include "core/loader/appcache/ApplicationCacheHost.h"
#include "core/page/Chrome.h"
#include "core/page/ChromeClient.h"
-#include "core/page/ContentSecurityPolicy.h"
-#include "core/page/DOMSecurityPolicy.h"
-#include "core/page/DOMWindow.h"
#include "core/page/EventHandler.h"
-#include "core/page/Frame.h"
#include "core/page/FrameTree.h"
-#include "core/page/FrameView.h"
-#include "core/page/History.h"
#include "core/page/MouseEventWithHitTestResults.h"
#include "core/page/Page.h"
#include "core/page/PageConsole.h"
#include "core/page/PointerLockController.h"
-#include "core/page/Settings.h"
-#include "core/page/animation/AnimationController.h"
+#include "core/frame/Settings.h"
#include "core/page/scrolling/ScrollingCoordinator.h"
-#include "core/platform/DateComponents.h"
-#include "core/platform/Language.h"
-#include "core/platform/ScrollbarTheme.h"
-#include "core/platform/Timer.h"
-#include "core/platform/chromium/TraceEvent.h"
-#include "core/platform/network/HTTPParsers.h"
-#include "core/platform/text/PlatformLocale.h"
-#include "core/platform/text/SegmentedString.h"
-#include "core/rendering/HitTestRequest.h"
+#include "core/rendering/FastTextAutosizer.h"
#include "core/rendering/HitTestResult.h"
#include "core/rendering/RenderView.h"
#include "core/rendering/RenderWidget.h"
#include "core/rendering/TextAutosizer.h"
#include "core/svg/SVGDocumentExtensions.h"
+#include "core/svg/SVGFontFaceElement.h"
#include "core/svg/SVGStyleElement.h"
-#include "core/workers/SharedWorkerRepository.h"
#include "core/xml/XSLTProcessor.h"
#include "core/xml/parser/XMLDocumentParser.h"
-#include "weborigin/SchemeRegistry.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/DateComponents.h"
+#include "platform/Language.h"
+#include "platform/TraceEvent.h"
+#include "platform/network/HTTPParsers.h"
+#include "platform/scroll/ScrollbarTheme.h"
+#include "platform/text/PlatformLocale.h"
+#include "platform/text/SegmentedString.h"
+#include "platform/weborigin/OriginAccessEntry.h"
+#include "platform/weborigin/SchemeRegistry.h"
+#include "platform/weborigin/SecurityOrigin.h"
#include "wtf/CurrentTime.h"
#include "wtf/HashFunctions.h"
#include "wtf/MainThread.h"
-#include "wtf/PassRefPtr.h"
#include "wtf/StdLibExtras.h"
-#include "wtf/UnusedParam.h"
+#include "wtf/TemporaryChange.h"
#include "wtf/text/StringBuffer.h"
#include "wtf/text/TextEncodingRegistry.h"
@@ -193,8 +195,6 @@ namespace WebCore {
using namespace HTMLNames;
-static const double cDefaultIncrementalRenderingSuppressionTimeoutInSeconds = 5;
-
static const unsigned cMaxWriteRecursionDepth = 21;
// This amount of time must have elapsed before we will even consider scheduling a layout without a delay.
@@ -288,45 +288,37 @@ static bool shouldInheritSecurityOriginFromOwner(const KURL& url)
return url.isEmpty() || url.isBlankURL();
}
-static Widget* widgetForElement(Element* focusedElement)
+static Widget* widgetForElement(const Element& focusedElement)
{
- if (!focusedElement)
- return 0;
- RenderObject* renderer = focusedElement->renderer();
+ RenderObject* renderer = focusedElement.renderer();
if (!renderer || !renderer->isWidget())
return 0;
return toRenderWidget(renderer)->widget();
}
-static bool acceptsEditingFocus(Element* element)
+static bool acceptsEditingFocus(const Element& element)
{
- ASSERT(element);
- ASSERT(element->rendererIsEditable());
-
- Element* root = element->rootEditableElement();
- Frame* frame = element->document().frame();
- if (!frame || !root)
- return false;
+ ASSERT(element.rendererIsEditable());
- return frame->editor().shouldBeginEditing(rangeOfContents(root).get());
+ return element.document().frame() && element.rootEditableElement();
}
-static bool canAccessAncestor(const SecurityOrigin* activeSecurityOrigin, Frame* targetFrame)
+static bool canAccessAncestor(const SecurityOrigin& activeSecurityOrigin, Frame* targetFrame)
{
// targetFrame can be 0 when we're trying to navigate a top-level frame
// that has a 0 opener.
if (!targetFrame)
return false;
- const bool isLocalActiveOrigin = activeSecurityOrigin->isLocal();
- for (Frame* ancestorFrame = targetFrame; ancestorFrame; ancestorFrame = ancestorFrame->tree()->parent()) {
+ const bool isLocalActiveOrigin = activeSecurityOrigin.isLocal();
+ for (Frame* ancestorFrame = targetFrame; ancestorFrame; ancestorFrame = ancestorFrame->tree().parent()) {
Document* ancestorDocument = ancestorFrame->document();
// FIXME: Should be an ASSERT? Frames should alway have documents.
if (!ancestorDocument)
return true;
const SecurityOrigin* ancestorSecurityOrigin = ancestorDocument->securityOrigin();
- if (activeSecurityOrigin->canAccess(ancestorSecurityOrigin))
+ if (activeSecurityOrigin.canAccess(ancestorSecurityOrigin))
return true;
// Allow file URL descendant navigation even when allowFileAccessFromFileURLs is false.
@@ -339,18 +331,18 @@ static bool canAccessAncestor(const SecurityOrigin* activeSecurityOrigin, Frame*
return false;
}
-static void printNavigationErrorMessage(Frame* frame, const KURL& activeURL, const char* reason)
+static void printNavigationErrorMessage(const Frame& frame, const KURL& activeURL, const char* reason)
{
- String message = "Unsafe JavaScript attempt to initiate navigation for frame with URL '" + frame->document()->url().string() + "' from frame with URL '" + activeURL.string() + "'. " + reason + "\n";
+ String message = "Unsafe JavaScript attempt to initiate navigation for frame with URL '" + frame.document()->url().string() + "' from frame with URL '" + activeURL.string() + "'. " + reason + "\n";
// FIXME: should we print to the console of the document performing the navigation instead?
- frame->domWindow()->printErrorMessage(message);
+ frame.domWindow()->printErrorMessage(message);
}
uint64_t Document::s_globalTreeVersion = 0;
// This class should be passed only to Document::postTask.
-class CheckFocusedElementTask FINAL : public ScriptExecutionContext::Task {
+class CheckFocusedElementTask FINAL : public ExecutionContextTask {
public:
static PassOwnPtr<CheckFocusedElementTask> create()
{
@@ -360,7 +352,7 @@ public:
private:
CheckFocusedElementTask() { }
- virtual void performTask(ScriptExecutionContext* context) OVERRIDE
+ virtual void performTask(ExecutionContext* context) OVERRIDE
{
ASSERT(context->isDocument());
Document* document = toDocument(context);
@@ -382,31 +374,25 @@ private:
Document::Document(const DocumentInit& initializer, DocumentClassFlags documentClasses)
: ContainerNode(0, CreateDocument)
, TreeScope(this)
- , m_styleResolverThrowawayTimer(this, &Document::styleResolverThrowawayTimerFired)
- , m_lastStyleResolverAccessTime(0)
- , m_didCalculateStyleResolver(false)
- , m_ignorePendingStylesheets(false)
- , m_evaluateMediaQueriesOnStyleRecalc(false)
- , m_needsNotifyRemoveAllPendingStylesheet(false)
, m_hasNodesWithPlaceholderStyle(false)
+ , m_needsNotifyRemoveAllPendingStylesheet(false)
+ , m_evaluateMediaQueriesOnStyleRecalc(false)
, m_pendingSheetLayout(NoLayoutWithPendingSheets)
, m_frame(initializer.frame())
- , m_domWindow(0)
+ , m_domWindow(m_frame ? m_frame->domWindow() : 0)
, m_import(initializer.import())
, m_activeParserCount(0)
, m_contextFeatures(ContextFeatures::defaultSwitch())
, m_wellFormed(false)
, m_printing(false)
, m_paginatedForScreen(false)
- , m_ignoreAutofocus(false)
, m_compatibilityMode(NoQuirksMode)
, m_compatibilityModeLocked(false)
, m_didPostCheckFocusedElementTask(false)
, m_domTreeVersion(++s_globalTreeVersion)
, m_listenerTypes(0)
, m_mutationObserverTypes(0)
- , m_styleEngine(StyleEngine::create(*this))
- , m_visitedLinkState(VisitedLinkState::create(this))
+ , m_visitedLinkState(VisitedLinkState::create(*this))
, m_visuallyOrdered(false)
, m_readyState(Complete)
, m_bParsing(false)
@@ -415,6 +401,7 @@ Document::Document(const DocumentInit& initializer, DocumentClassFlags documentC
, m_gotoAnchorNeededAfterStylesheetsLoad(false)
, m_containsValidityStyleRules(false)
, m_updateFocusAppearanceRestoresSelection(false)
+ , m_containsPlugins(false)
, m_ignoreDestructiveWriteCount(0)
, m_titleSetExplicitly(false)
, m_markers(adoptPtr(new DocumentMarkerController))
@@ -436,8 +423,8 @@ Document::Document(const DocumentInit& initializer, DocumentClassFlags documentC
, m_sawElementsInKnownNamespaces(false)
, m_isSrcdocDocument(false)
, m_isMobileDocument(false)
- , m_renderer(0)
- , m_eventQueue(DocumentEventQueue::create(this))
+ , m_mayDisplaySeamlesslyWithParent(false)
+ , m_renderView(0)
, m_weakFactory(this)
, m_contextDocument(initializer.contextDocument())
, m_idAttributeName(idAttr)
@@ -450,26 +437,25 @@ Document::Document(const DocumentInit& initializer, DocumentClassFlags documentC
, m_writeRecursionIsTooDeep(false)
, m_writeRecursionDepth(0)
, m_lastHandledUserGestureTimestamp(0)
- , m_prerenderer(Prerenderer::create(this))
- , m_textAutosizer(TextAutosizer::create(this))
+ , m_taskRunner(MainThreadTaskRunner::create(this))
, m_registrationContext(initializer.registrationContext(this))
- , m_pendingTasksTimer(this, &Document::pendingTasksTimerFired)
- , m_scheduledTasksAreSuspended(false)
, m_sharedObjectPoolClearTimer(this, &Document::sharedObjectPoolClearTimerFired)
#ifndef NDEBUG
, m_didDispatchViewportPropertiesChanged(false)
#endif
+ , m_animationClock(AnimationClock::create())
, m_timeline(DocumentTimeline::create(this))
+ , m_transitionTimeline(TransitionTimeline::create(this))
, m_templateDocumentHost(0)
- , m_fonts(0)
, m_didAssociateFormControlsTimer(this, &Document::didAssociateFormControlsTimerFired)
{
+ setClient(this);
ScriptWrappable::init(this);
if (m_frame) {
provideContextFeaturesToDocumentFrom(this, m_frame->page());
- m_fetcher = m_frame->loader()->activeDocumentLoader()->fetcher();
+ m_fetcher = m_frame->loader().activeDocumentLoader()->fetcher();
}
if (!m_fetcher)
@@ -491,22 +477,18 @@ Document::Document(const DocumentInit& initializer, DocumentClassFlags documentC
m_nodeListCounts[i] = 0;
InspectorCounters::incrementCounter(InspectorCounters::DocumentCounter);
-}
-static bool isAttributeOnAllOwners(const WebCore::QualifiedName& attribute, const WebCore::QualifiedName& prefixedAttribute, const HTMLFrameOwnerElement* owner)
-{
- if (!owner)
- return true;
- do {
- if (!(owner->hasAttribute(attribute) || owner->hasAttribute(prefixedAttribute)))
- return false;
- } while ((owner = owner->document().ownerElement()));
- return true;
+ m_lifecyle.advanceTo(DocumentLifecycle::Inactive);
+
+ // Since CSSFontSelector requires Document::m_fetcher and StyleEngine owns
+ // CSSFontSelector, need to initialize m_styleEngine after initializing
+ // m_fetcher.
+ m_styleEngine = StyleEngine::create(*this);
}
Document::~Document()
{
- ASSERT(!renderer());
+ ASSERT(!renderView());
ASSERT(m_ranges.isEmpty());
ASSERT(!m_parentTreeScope);
ASSERT(!hasGuardRefCount());
@@ -533,8 +515,6 @@ Document::~Document()
if (this == topDocument())
clearAXObjectCache();
- setDecoder(PassRefPtr<TextResourceDecoder>());
-
if (m_styleSheetList)
m_styleSheetList->detachFromDocument();
@@ -543,13 +523,11 @@ Document::~Document()
m_import = 0;
}
- m_styleEngine.clear();
+ m_styleEngine.clear(); // We need to destory CSSFontSelector before destroying m_fetcher.
if (m_elemSheet)
m_elemSheet->clearOwnerNode();
- clearStyleResolver(); // We need to destory CSSFontSelector before destroying m_fetcher.
-
// It's possible for multiple Documents to end up referencing the same ResourceFetcher (e.g., SVGImages
// load the initial empty document and the SVGDocument with the same DocumentLoader).
if (m_fetcher->document() == this)
@@ -567,13 +545,14 @@ Document::~Document()
ASSERT(!m_nodeListCounts[i]);
clearDocumentScope();
+ setClient(0);
InspectorCounters::decrementCounter(InspectorCounters::DocumentCounter);
}
void Document::dispose()
{
- ASSERT(!m_deletionHasBegun);
+ ASSERT_WITH_SECURITY_IMPLICATION(!m_deletionHasBegun);
// We must make sure not to be retaining any of our children through
// these extra pointers or we will create a reference cycle.
m_docType = 0;
@@ -602,7 +581,7 @@ void Document::dispose()
// removeDetachedChildren() can access FormController.
m_formController.clear();
- m_markers->detach();
+ m_markers->clear();
m_cssCanvasElements.clear();
@@ -614,21 +593,27 @@ void Document::dispose()
if (svgExtensions())
accessSVGExtensions()->pauseAnimations();
- lifecycleNotifier()->notifyDocumentWasDisposed();
+ m_lifecyle.advanceTo(DocumentLifecycle::Disposed);
+ lifecycleNotifier().notifyDocumentWasDisposed();
}
-SelectorQueryCache* Document::selectorQueryCache()
+SelectorQueryCache& Document::selectorQueryCache()
{
if (!m_selectorQueryCache)
m_selectorQueryCache = adoptPtr(new SelectorQueryCache());
- return m_selectorQueryCache.get();
+ return *m_selectorQueryCache;
}
-MediaQueryMatcher* Document::mediaQueryMatcher()
+MediaQueryMatcher& Document::mediaQueryMatcher()
{
if (!m_mediaQueryMatcher)
m_mediaQueryMatcher = MediaQueryMatcher::create(this);
- return m_mediaQueryMatcher.get();
+ return *m_mediaQueryMatcher;
+}
+
+void Document::mediaQueryAffectingValueChanged()
+{
+ styleEngine()->clearMediaQueryRuleSetStyleSheets();
}
void Document::setCompatibilityMode(CompatibilityMode mode)
@@ -637,10 +622,9 @@ void Document::setCompatibilityMode(CompatibilityMode mode)
return;
bool wasInQuirksMode = inQuirksMode();
m_compatibilityMode = mode;
- selectorQueryCache()->invalidate();
+ selectorQueryCache().invalidate();
if (inQuirksMode() != wasInQuirksMode) {
- // All user stylesheets have to reparse using the different mode.
- m_styleEngine->clearPageUserSheet();
+ // All injected stylesheets have to reparse using the different mode.
m_styleEngine->invalidateInjectedStyleSheetCache();
}
}
@@ -656,7 +640,7 @@ void Document::setDoctype(PassRefPtr<DocumentType> docType)
ASSERT(!m_docType || !docType);
m_docType = docType;
if (m_docType) {
- this->adoptIfNeeded(m_docType.get());
+ this->adoptIfNeeded(*m_docType);
if (m_docType->publicId().startsWith("-//wapforum//dtd xhtml mobile 1.", /* caseSensitive */ false))
m_isMobileDocument = true;
}
@@ -667,7 +651,7 @@ void Document::setDoctype(PassRefPtr<DocumentType> docType)
DOMImplementation* Document::implementation()
{
if (!m_implementation)
- m_implementation = DOMImplementation::create(this);
+ m_implementation = DOMImplementation::create(*this);
return m_implementation.get();
}
@@ -676,11 +660,19 @@ bool Document::hasManifest() const
return documentElement() && isHTMLHtmlElement(documentElement()) && documentElement()->hasAttribute(manifestAttr);
}
+Location* Document::location() const
+{
+ if (!frame())
+ return 0;
+
+ return domWindow()->location();
+}
+
void Document::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
{
ContainerNode::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
- Element* newDocumentElement = ElementTraversal::firstWithin(this);
+ Element* newDocumentElement = ElementTraversal::firstWithin(*this);
if (newDocumentElement == m_documentElement)
return;
m_documentElement = newDocumentElement;
@@ -688,48 +680,48 @@ void Document::childrenChanged(bool changedByParser, Node* beforeChange, Node* a
clearStyleResolver();
}
-PassRefPtr<Element> Document::createElement(const AtomicString& name, ExceptionState& es)
+PassRefPtr<Element> Document::createElement(const AtomicString& name, ExceptionState& exceptionState)
{
if (!isValidName(name)) {
- es.throwDOMException(InvalidCharacterError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidCharacterError);
return 0;
}
if (isXHTMLDocument() || isHTMLDocument())
- return HTMLElementFactory::createHTMLElement(QualifiedName(nullAtom, isHTMLDocument() ? name.lower() : name, xhtmlNamespaceURI), this, 0, false);
+ return HTMLElementFactory::createHTMLElement(isHTMLDocument() ? name.lower() : name, document(), 0, false);
return createElement(QualifiedName(nullAtom, name, nullAtom), false);
}
-PassRefPtr<Element> Document::createElement(const AtomicString& localName, const AtomicString& typeExtension, ExceptionState& es)
+PassRefPtr<Element> Document::createElement(const AtomicString& localName, const AtomicString& typeExtension, ExceptionState& exceptionState)
{
if (!isValidName(localName)) {
- es.throwDOMException(InvalidCharacterError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidCharacterError);
return 0;
}
RefPtr<Element> element;
- if (CustomElement::isValidName(localName) && registrationContext())
+ if (RuntimeEnabledFeatures::customElementsEnabled() && CustomElement::isValidName(localName) && registrationContext())
element = registrationContext()->createCustomTagElement(*this, QualifiedName(nullAtom, localName, xhtmlNamespaceURI));
else
- element = createElement(localName, es);
+ element = createElement(localName, exceptionState);
- if (!typeExtension.isNull() && !typeExtension.isEmpty())
+ if (RuntimeEnabledFeatures::customElementsEnabled() && !typeExtension.isNull() && !typeExtension.isEmpty())
CustomElementRegistrationContext::setIsAttributeAndTypeExtension(element.get(), typeExtension);
return element;
}
-PassRefPtr<Element> Document::createElementNS(const AtomicString& namespaceURI, const String& qualifiedName, const AtomicString& typeExtension, ExceptionState& es)
+PassRefPtr<Element> Document::createElementNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, const AtomicString& typeExtension, ExceptionState& exceptionState)
{
- String prefix, localName;
- if (!parseQualifiedName(qualifiedName, prefix, localName, es))
+ AtomicString prefix, localName;
+ if (!parseQualifiedName(qualifiedName, prefix, localName, exceptionState))
return 0;
QualifiedName qName(prefix, localName, namespaceURI);
if (!hasValidNamespaceForElements(qName)) {
- es.throwDOMException(NamespaceError);
+ exceptionState.throwUninformativeAndGenericDOMException(NamespaceError);
return 0;
}
@@ -737,7 +729,7 @@ PassRefPtr<Element> Document::createElementNS(const AtomicString& namespaceURI,
if (CustomElement::isValidName(qName.localName()) && registrationContext())
element = registrationContext()->createCustomTagElement(*this, qName);
else
- element = createElementNS(namespaceURI, qualifiedName, es);
+ element = createElementNS(namespaceURI, qualifiedName, exceptionState);
if (!typeExtension.isNull() && !typeExtension.isEmpty())
CustomElementRegistrationContext::setIsAttributeAndTypeExtension(element.get(), typeExtension);
@@ -745,20 +737,20 @@ PassRefPtr<Element> Document::createElementNS(const AtomicString& namespaceURI,
return element;
}
-ScriptValue Document::registerElement(WebCore::ScriptState* state, const AtomicString& name, ExceptionState& es)
+ScriptValue Document::registerElement(WebCore::ScriptState* state, const AtomicString& name, ExceptionState& exceptionState)
{
- return registerElement(state, name, Dictionary(), es);
+ return registerElement(state, name, Dictionary(), exceptionState);
}
-ScriptValue Document::registerElement(WebCore::ScriptState* state, const AtomicString& name, const Dictionary& options, ExceptionState& es, CustomElement::NameSet validNames)
+ScriptValue Document::registerElement(WebCore::ScriptState* state, const AtomicString& name, const Dictionary& options, ExceptionState& exceptionState, CustomElement::NameSet validNames)
{
if (!registrationContext()) {
- es.throwDOMException(NotSupportedError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
return ScriptValue();
}
CustomElementConstructorBuilder constructorBuilder(state, &options);
- registrationContext()->registerElement(this, &constructorBuilder, name, validNames, es);
+ registrationContext()->registerElement(this, &constructorBuilder, name, validNames, exceptionState);
return constructorBuilder.bindingsReturnValue();
}
@@ -793,27 +785,27 @@ PassRefPtr<Comment> Document::createComment(const String& data)
return Comment::create(*this, data);
}
-PassRefPtr<CDATASection> Document::createCDATASection(const String& data, ExceptionState& es)
+PassRefPtr<CDATASection> Document::createCDATASection(const String& data, ExceptionState& exceptionState)
{
if (isHTMLDocument()) {
- es.throwDOMException(NotSupportedError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
return 0;
}
- if (data.find("]]>") != WTF::kNotFound) {
- es.throwDOMException(InvalidCharacterError, "String cannot contain ']]>' since that is the end delimiter of a CData section.");
+ if (data.contains("]]>")) {
+ exceptionState.throwDOMException(InvalidCharacterError, "String cannot contain ']]>' since that is the end delimiter of a CData section.");
return 0;
}
return CDATASection::create(*this, data);
}
-PassRefPtr<ProcessingInstruction> Document::createProcessingInstruction(const String& target, const String& data, ExceptionState& es)
+PassRefPtr<ProcessingInstruction> Document::createProcessingInstruction(const String& target, const String& data, ExceptionState& exceptionState)
{
if (!isValidName(target)) {
- es.throwDOMException(InvalidCharacterError);
+ exceptionState.throwDOMException(InvalidCharacterError, "The target provided ('" + target + "') is not a valid name.");
return 0;
}
- if (isHTMLDocument()) {
- es.throwDOMException(NotSupportedError);
+ if (data.contains("?>")) {
+ exceptionState.throwDOMException(InvalidCharacterError, "The data provided ('" + data + "') contains '?>'.");
return 0;
}
return ProcessingInstruction::create(*this, target, data);
@@ -829,10 +821,10 @@ PassRefPtr<CSSStyleDeclaration> Document::createCSSStyleDeclaration()
return MutableStylePropertySet::create()->ensureCSSStyleDeclaration();
}
-PassRefPtr<Node> Document::importNode(Node* importedNode, bool deep, ExceptionState& es)
+PassRefPtr<Node> Document::importNode(Node* importedNode, bool deep, ExceptionState& exceptionState)
{
if (!importedNode) {
- es.throwDOMException(NotSupportedError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
return 0;
}
@@ -840,9 +832,9 @@ PassRefPtr<Node> Document::importNode(Node* importedNode, bool deep, ExceptionSt
case TEXT_NODE:
return createTextNode(importedNode->nodeValue());
case CDATA_SECTION_NODE:
- return createCDATASection(importedNode->nodeValue(), es);
+ return createCDATASection(importedNode->nodeValue(), exceptionState);
case PROCESSING_INSTRUCTION_NODE:
- return createProcessingInstruction(importedNode->nodeName(), importedNode->nodeValue(), es);
+ return createProcessingInstruction(importedNode->nodeName(), importedNode->nodeValue(), exceptionState);
case COMMENT_NODE:
return createComment(importedNode->nodeValue());
case ELEMENT_NODE: {
@@ -850,7 +842,7 @@ PassRefPtr<Node> Document::importNode(Node* importedNode, bool deep, ExceptionSt
// FIXME: The following check might be unnecessary. Is it possible that
// oldElement has mismatched prefix/namespace?
if (!hasValidNamespaceForElements(oldElement->tagQName())) {
- es.throwDOMException(NamespaceError);
+ exceptionState.throwUninformativeAndGenericDOMException(NamespaceError);
return 0;
}
RefPtr<Element> newElement = createElement(oldElement->tagQName(), false);
@@ -859,11 +851,11 @@ PassRefPtr<Node> Document::importNode(Node* importedNode, bool deep, ExceptionSt
if (deep) {
for (Node* oldChild = oldElement->firstChild(); oldChild; oldChild = oldChild->nextSibling()) {
- RefPtr<Node> newChild = importNode(oldChild, true, es);
- if (es.hadException())
+ RefPtr<Node> newChild = importNode(oldChild, true, exceptionState);
+ if (exceptionState.hadException())
return 0;
- newElement->appendChild(newChild.release(), es);
- if (es.hadException())
+ newElement->appendChild(newChild.release(), exceptionState);
+ if (exceptionState.hadException())
return 0;
}
}
@@ -882,11 +874,11 @@ PassRefPtr<Node> Document::importNode(Node* importedNode, bool deep, ExceptionSt
RefPtr<DocumentFragment> newFragment = createDocumentFragment();
if (deep) {
for (Node* oldChild = oldFragment->firstChild(); oldChild; oldChild = oldChild->nextSibling()) {
- RefPtr<Node> newChild = importNode(oldChild, true, es);
- if (es.hadException())
+ RefPtr<Node> newChild = importNode(oldChild, true, exceptionState);
+ if (exceptionState.hadException())
return 0;
- newFragment->appendChild(newChild.release(), es);
- if (es.hadException())
+ newFragment->appendChild(newChild.release(), exceptionState);
+ if (exceptionState.hadException())
return 0;
}
}
@@ -902,14 +894,14 @@ PassRefPtr<Node> Document::importNode(Node* importedNode, bool deep, ExceptionSt
case XPATH_NAMESPACE_NODE:
break;
}
- es.throwDOMException(NotSupportedError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
return 0;
}
-PassRefPtr<Node> Document::adoptNode(PassRefPtr<Node> source, ExceptionState& es)
+PassRefPtr<Node> Document::adoptNode(PassRefPtr<Node> source, ExceptionState& exceptionState)
{
if (!source) {
- es.throwDOMException(NotSupportedError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
return 0;
}
@@ -921,37 +913,36 @@ PassRefPtr<Node> Document::adoptNode(PassRefPtr<Node> source, ExceptionState& es
case DOCUMENT_NODE:
case DOCUMENT_TYPE_NODE:
case XPATH_NAMESPACE_NODE:
- es.throwDOMException(NotSupportedError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
return 0;
case ATTRIBUTE_NODE: {
Attr* attr = toAttr(source.get());
if (attr->ownerElement())
- attr->ownerElement()->removeAttributeNode(attr, es);
- attr->setSpecified(true);
+ attr->ownerElement()->removeAttributeNode(attr, exceptionState);
break;
}
default:
if (source->isShadowRoot()) {
// ShadowRoot cannot disconnect itself from the host node.
- es.throwDOMException(HierarchyRequestError);
+ exceptionState.throwUninformativeAndGenericDOMException(HierarchyRequestError);
return 0;
}
if (source->isFrameOwnerElement()) {
HTMLFrameOwnerElement* frameOwnerElement = toHTMLFrameOwnerElement(source.get());
- if (frame() && frame()->tree()->isDescendantOf(frameOwnerElement->contentFrame())) {
- es.throwDOMException(HierarchyRequestError);
+ if (frame() && frame()->tree().isDescendantOf(frameOwnerElement->contentFrame())) {
+ exceptionState.throwUninformativeAndGenericDOMException(HierarchyRequestError);
return 0;
}
}
if (source->parentNode()) {
- source->parentNode()->removeChild(source.get(), es);
- if (es.hadException())
+ source->parentNode()->removeChild(source.get(), exceptionState);
+ if (exceptionState.hadException())
return 0;
}
}
- this->adoptIfNeeded(source.get());
+ this->adoptIfNeeded(*source);
return source;
}
@@ -992,17 +983,19 @@ PassRefPtr<Element> Document::createElement(const QualifiedName& qName, bool cre
// FIXME: Use registered namespaces and look up in a hash to find the right factory.
if (qName.namespaceURI() == xhtmlNamespaceURI)
- e = HTMLElementFactory::createHTMLElement(qName, this, 0, createdByParser);
+ e = HTMLElementFactory::createHTMLElement(qName.localName(), document(), 0, createdByParser);
else if (qName.namespaceURI() == SVGNames::svgNamespaceURI)
- e = SVGElementFactory::createSVGElement(qName, this, createdByParser);
+ e = SVGElementFactory::createSVGElement(qName.localName(), document(), createdByParser);
if (e)
m_sawElementsInKnownNamespaces = true;
else
e = Element::create(qName, &document());
- // <image> uses imgTag so we need a special rule.
- ASSERT((qName.matches(imageTag) && e->tagQName().matches(imgTag) && e->tagQName().prefix() == qName.prefix()) || qName == e->tagQName());
+ if (e->prefix() != qName.prefix())
+ e->setTagNameForCreateElementNS(qName);
+
+ ASSERT(qName == e->tagQName());
return e.release();
}
@@ -1012,19 +1005,9 @@ bool Document::regionBasedColumnsEnabled() const
return settings() && settings()->regionBasedColumnsEnabled();
}
-bool Document::cssStickyPositionEnabled() const
-{
- return settings() && settings()->cssStickyPositionEnabled();
-}
-
-bool Document::cssCompositingEnabled() const
-{
- return RuntimeEnabledFeatures::cssCompositingEnabled();
-}
-
PassRefPtr<DOMNamedFlowCollection> Document::webkitGetNamedFlows()
{
- if (!RuntimeEnabledFeatures::cssRegionsEnabled() || !renderer())
+ if (!RuntimeEnabledFeatures::cssRegionsEnabled() || !renderView())
return 0;
updateStyleIfNeeded();
@@ -1040,15 +1023,15 @@ NamedFlowCollection* Document::namedFlows()
return m_namedFlows.get();
}
-PassRefPtr<Element> Document::createElementNS(const String& namespaceURI, const String& qualifiedName, ExceptionState& es)
+PassRefPtr<Element> Document::createElementNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionState& exceptionState)
{
- String prefix, localName;
- if (!parseQualifiedName(qualifiedName, prefix, localName, es))
+ AtomicString prefix, localName;
+ if (!parseQualifiedName(qualifiedName, prefix, localName, exceptionState))
return 0;
QualifiedName qName(prefix, localName, namespaceURI);
if (!hasValidNamespaceForElements(qName)) {
- es.throwDOMException(NamespaceError);
+ exceptionState.throwUninformativeAndGenericDOMException(NamespaceError);
return 0;
}
@@ -1083,8 +1066,8 @@ void Document::setReadyState(ReadyState readyState)
case Loading:
if (!m_documentTiming.domLoading) {
m_documentTiming.domLoading = monotonicallyIncreasingTime();
- if (RuntimeEnabledFeatures::webAnimationsEnabled())
- m_timeline->setZeroTimeAsPerfTime(m_documentTiming.domLoading);
+ if (RuntimeEnabledFeatures::webAnimationsCSSEnabled())
+ m_timeline->setZeroTime(m_documentTiming.domLoading);
}
break;
case Interactive:
@@ -1098,15 +1081,20 @@ void Document::setReadyState(ReadyState readyState)
}
m_readyState = readyState;
- dispatchEvent(Event::create(eventNames().readystatechangeEvent));
+ dispatchEvent(Event::create(EventTypeNames::readystatechange));
+}
+
+bool Document::isLoadCompleted()
+{
+ return m_readyState == Complete;
}
-String Document::encodingName() const
+AtomicString Document::encodingName() const
{
- // TextEncoding::domName() returns a char*, no need to allocate a new
+ // TextEncoding::name() returns a char*, no need to allocate a new
// String for it each time.
// FIXME: We should fix TextEncoding to speak AtomicString anyway.
- return AtomicString(m_encoding.domName());
+ return AtomicString(encoding().name());
}
String Document::defaultCharset() const
@@ -1118,13 +1106,18 @@ String Document::defaultCharset() const
void Document::setCharset(const String& charset)
{
- if (!decoder())
+ if (DocumentLoader* documentLoader = loader())
+ documentLoader->setUserChosenEncoding(charset);
+ WTF::TextEncoding encoding(charset);
+ // In case the encoding didn't exist, we keep the old one (helps some sites specifying invalid encodings).
+ if (!encoding.isValid())
return;
- decoder()->setEncoding(charset, TextResourceDecoder::UserChosenEncoding);
- setEncoding(m_decoder->encoding());
+ DocumentEncodingData newEncodingData = m_encodingData;
+ newEncodingData.encoding = encoding;
+ setEncodingData(newEncodingData);
}
-void Document::setContentLanguage(const String& language)
+void Document::setContentLanguage(const AtomicString& language)
{
if (m_contentLanguage == language)
return;
@@ -1134,25 +1127,25 @@ void Document::setContentLanguage(const String& language)
setNeedsStyleRecalc();
}
-void Document::setXMLVersion(const String& version, ExceptionState& es)
+void Document::setXMLVersion(const String& version, ExceptionState& exceptionState)
{
if (!implementation()->hasFeature("XML", String())) {
- es.throwDOMException(NotSupportedError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
return;
}
if (!XMLDocumentParser::supportsXMLVersion(version)) {
- es.throwDOMException(NotSupportedError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
return;
}
m_xmlVersion = version;
}
-void Document::setXMLStandalone(bool standalone, ExceptionState& es)
+void Document::setXMLStandalone(bool standalone, ExceptionState& exceptionState)
{
if (!implementation()->hasFeature("XML", String())) {
- es.throwDOMException(NotSupportedError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
return;
}
@@ -1194,7 +1187,7 @@ String Document::suggestedMIMEType() const
Element* Document::elementFromPoint(int x, int y) const
{
- if (!renderer())
+ if (!renderView())
return 0;
return TreeScope::elementFromPoint(x, y);
@@ -1202,13 +1195,14 @@ Element* Document::elementFromPoint(int x, int y) const
PassRefPtr<Range> Document::caretRangeFromPoint(int x, int y)
{
- if (!renderer())
+ if (!renderView())
return 0;
LayoutPoint localPoint;
- Node* node = nodeFromPoint(this, x, y, &localPoint);
- if (!node)
+ RenderObject* renderer = rendererFromPoint(this, x, y, &localPoint);
+ if (!renderer)
return 0;
+ Node* node = renderer->node();
Node* shadowAncestorNode = ancestorInThisScope(node);
if (shadowAncestorNode != node) {
unsigned offset = shadowAncestorNode->nodeIndex();
@@ -1216,9 +1210,6 @@ PassRefPtr<Range> Document::caretRangeFromPoint(int x, int y)
return Range::create(*this, container, offset, container, offset);
}
- RenderObject* renderer = node->renderer();
- if (!renderer)
- return 0;
PositionWithAffinity positionWithAffinity = renderer->positionForPoint(localPoint);
if (positionWithAffinity.position().isNull())
return 0;
@@ -1280,9 +1271,6 @@ static inline String canonicalizedTitle(Document* document, const String& title)
buffer.shrink(builderIndex + 1);
- // Replace the backslashes with currency symbols if the encoding requires it.
- document->displayBufferModifiedByEncoding(buffer.characters(), buffer.length());
-
return String::adopt(buffer);
}
@@ -1303,8 +1291,7 @@ void Document::updateTitle(const String& title)
if (!m_frame || oldTitle == m_title)
return;
- m_frame->loader()->history()->setCurrentItemTitle(m_title);
- m_frame->loader()->client()->dispatchDidReceiveTitle(m_title);
+ m_frame->loader().client()->dispatchDidReceiveTitle(m_title);
}
void Document::setTitle(const String& title)
@@ -1322,11 +1309,8 @@ void Document::setTitle(const String& title)
updateTitle(title);
- if (m_titleElement) {
- ASSERT(isHTMLTitleElement(m_titleElement.get()));
- if (isHTMLTitleElement(m_titleElement.get()))
- toHTMLTitleElement(m_titleElement.get())->setText(title);
- }
+ if (m_titleElement && isHTMLTitleElement(m_titleElement.get()))
+ toHTMLTitleElement(m_titleElement)->setText(title);
}
void Document::setTitleElement(const String& title, Element* titleElement)
@@ -1365,7 +1349,7 @@ void Document::removeTitle(Element* titleElement)
updateTitle(String());
}
-PageVisibilityState Document::visibilityState() const
+PageVisibilityState Document::pageVisibilityState() const
{
// The visibility of the document is inherited from the visibility of the
// page. If there is no page associated with the document, we will assume
@@ -1376,19 +1360,21 @@ PageVisibilityState Document::visibilityState() const
return m_frame->page()->visibilityState();
}
-String Document::webkitVisibilityState() const
+String Document::visibilityState() const
{
- return pageVisibilityStateString(visibilityState());
+ return pageVisibilityStateString(pageVisibilityState());
}
-bool Document::webkitHidden() const
+bool Document::hidden() const
{
- return visibilityState() != PageVisibilityStateVisible;
+ return pageVisibilityState() != PageVisibilityStateVisible;
}
void Document::dispatchVisibilityStateChangeEvent()
{
- dispatchEvent(Event::create(eventNames().webkitvisibilitychangeEvent));
+ dispatchEvent(Event::create(EventTypeNames::visibilitychange));
+ // Also send out the deprecated version until it can be removed.
+ dispatchEvent(Event::create(EventTypeNames::webkitvisibilitychange));
}
DOMSecurityPolicy* Document::securityPolicy()
@@ -1449,20 +1435,20 @@ PassRefPtr<Range> Document::createRange()
return Range::create(*this);
}
-PassRefPtr<NodeIterator> Document::createNodeIterator(Node* root, ExceptionState& es)
+PassRefPtr<NodeIterator> Document::createNodeIterator(Node* root, ExceptionState& exceptionState)
{
// FIXME: Probably this should be handled within the bindings layer and TypeError should be thrown.
if (!root) {
- es.throwDOMException(NotSupportedError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
return 0;
}
return NodeIterator::create(root, NodeFilter::SHOW_ALL, PassRefPtr<NodeFilter>());
}
-PassRefPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned whatToShow, ExceptionState& es)
+PassRefPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned whatToShow, ExceptionState& exceptionState)
{
if (!root) {
- es.throwDOMException(NotSupportedError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
return 0;
}
// FIXME: It might be a good idea to emit a warning if |whatToShow| contains a bit that is not defined in
@@ -1470,59 +1456,38 @@ PassRefPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned whatT
return NodeIterator::create(root, whatToShow, PassRefPtr<NodeFilter>());
}
-PassRefPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned whatToShow, PassRefPtr<NodeFilter> filter, ExceptionState& es)
+PassRefPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned whatToShow, PassRefPtr<NodeFilter> filter, ExceptionState& exceptionState)
{
if (!root) {
- es.throwDOMException(NotSupportedError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
return 0;
}
// FIXME: Ditto.
return NodeIterator::create(root, whatToShow, filter);
}
-PassRefPtr<NodeIterator> Document::createNodeIterator(Node* root, unsigned whatToShow, PassRefPtr<NodeFilter> filter, bool expandEntityReferences, ExceptionState& es)
+PassRefPtr<TreeWalker> Document::createTreeWalker(Node* root, ExceptionState& exceptionState)
{
if (!root) {
- es.throwDOMException(NotSupportedError);
- return 0;
- }
- // FIXME: Warn if |expandEntityReferences| is specified. This optional argument is deprecated in DOM4.
- UNUSED_PARAM(expandEntityReferences);
- return NodeIterator::create(root, whatToShow, filter);
-}
-
-PassRefPtr<TreeWalker> Document::createTreeWalker(Node* root, ExceptionState& es)
-{
- if (!root) {
- es.throwDOMException(NotSupportedError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
return 0;
}
return TreeWalker::create(root, NodeFilter::SHOW_ALL, PassRefPtr<NodeFilter>());
}
-PassRefPtr<TreeWalker> Document::createTreeWalker(Node* root, unsigned whatToShow, ExceptionState& es)
+PassRefPtr<TreeWalker> Document::createTreeWalker(Node* root, unsigned whatToShow, ExceptionState& exceptionState)
{
if (!root) {
- es.throwDOMException(NotSupportedError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
return 0;
}
return TreeWalker::create(root, whatToShow, PassRefPtr<NodeFilter>());
}
-PassRefPtr<TreeWalker> Document::createTreeWalker(Node* root, unsigned whatToShow, PassRefPtr<NodeFilter> filter, ExceptionState& es)
+PassRefPtr<TreeWalker> Document::createTreeWalker(Node* root, unsigned whatToShow, PassRefPtr<NodeFilter> filter, ExceptionState& exceptionState)
{
if (!root) {
- es.throwDOMException(NotSupportedError);
- return 0;
- }
- return TreeWalker::create(root, whatToShow, filter);
-}
-
-PassRefPtr<TreeWalker> Document::createTreeWalker(Node* root, unsigned whatToShow, PassRefPtr<NodeFilter> filter, bool expandEntityReferences, ExceptionState& es)
-{
- UNUSED_PARAM(expandEntityReferences);
- if (!root) {
- es.throwDOMException(NotSupportedError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
return 0;
}
return TreeWalker::create(root, whatToShow, filter);
@@ -1549,7 +1514,7 @@ void Document::scheduleStyleRecalc()
void Document::unscheduleStyleRecalc()
{
- ASSERT(!attached() || (!needsStyleRecalc() && !childNeedsStyleRecalc()));
+ ASSERT(!isActive() || (!needsStyleRecalc() && !childNeedsStyleRecalc()));
m_styleRecalcTimer.stop();
}
@@ -1607,53 +1572,46 @@ void Document::setStyleDependentState(RenderStyle* documentStyle)
FontBuilder fontBuilder;
fontBuilder.initForStyleResolve(*this, documentStyle, isSVGDocument());
- RefPtr<CSSFontSelector> selector = m_styleResolver ? m_styleResolver->fontSelector() : 0;
+ RefPtr<CSSFontSelector> selector = m_styleEngine->fontSelector();
fontBuilder.createFontForDocument(selector, documentStyle);
}
void Document::inheritHtmlAndBodyElementStyles(StyleRecalcChange change)
{
- RenderView* renderView = this->renderView();
-
- if (!documentElement() || !frame() || !view())
- return;
+ ASSERT(inStyleRecalc());
+ ASSERT(documentElement());
RefPtr<RenderStyle> documentElementStyle = documentElement()->renderStyle();
if (!documentElementStyle || documentElement()->needsStyleRecalc() || change == Force)
- documentElementStyle = styleResolver()->styleForElement(documentElement());
-
- RefPtr<RenderStyle> bodyStyle = 0;
- if (body()) {
- bodyStyle = body()->renderStyle();
- if (!bodyStyle || body()->needsStyleRecalc() || documentElement()->needsStyleRecalc() || change == Force)
- bodyStyle = styleResolver()->styleForElement(body(), documentElementStyle.get());
- }
+ documentElementStyle = ensureStyleResolver().styleForElement(documentElement());
WritingMode rootWritingMode = documentElementStyle->writingMode();
- bool isHorizontalWritingMode = documentElementStyle->isHorizontalWritingMode();
TextDirection rootDirection = documentElementStyle->direction();
+ HTMLElement* body = this->body();
- if (!writingModeSetOnDocumentElement() && body()) {
- rootWritingMode = bodyStyle->writingMode();
- isHorizontalWritingMode = bodyStyle->isHorizontalWritingMode();
+ if (body) {
+ RefPtr<RenderStyle> bodyStyle = body->renderStyle();
+ if (!bodyStyle || body->needsStyleRecalc() || documentElement()->needsStyleRecalc() || change == Force)
+ bodyStyle = ensureStyleResolver().styleForElement(body, documentElementStyle.get());
+ if (!writingModeSetOnDocumentElement())
+ rootWritingMode = bodyStyle->writingMode();
+ if (!directionSetOnDocumentElement())
+ rootDirection = bodyStyle->direction();
}
- if (!directionSetOnDocumentElement() && body())
- rootDirection = bodyStyle->direction();
-
- RefPtr<RenderStyle> documentStyle = renderView->style();
+ RefPtr<RenderStyle> documentStyle = renderView()->style();
if (documentStyle->writingMode() != rootWritingMode || documentStyle->direction() != rootDirection) {
RefPtr<RenderStyle> newStyle = RenderStyle::clone(documentStyle.get());
newStyle->setWritingMode(rootWritingMode);
newStyle->setDirection(rootDirection);
- renderView->setStyle(newStyle);
+ renderView()->setStyle(newStyle);
setStyleDependentState(newStyle.get());
}
- if (body()) {
- if (RenderStyle* style = body()->renderStyle()) {
+ if (body) {
+ if (RenderStyle* style = body->renderStyle()) {
if (style->direction() != rootDirection || style->writingMode() != rootWritingMode)
- body()->setNeedsStyleRecalc();
+ body->setNeedsStyleRecalc();
}
}
@@ -1666,23 +1624,27 @@ void Document::inheritHtmlAndBodyElementStyles(StyleRecalcChange change)
void Document::recalcStyle(StyleRecalcChange change)
{
// we should not enter style recalc while painting
- ASSERT(!view() || !view()->isPainting());
- if (view() && view()->isPainting())
+ RELEASE_ASSERT(!view() || !view()->isPainting());
+
+ // FIXME: We should never enter here without a FrameView or with an inactive document.
+ if (!isActive() || !view())
return;
if (m_inStyleRecalc)
- return; // Guard against re-entrancy. -dwh
+ return;
TRACE_EVENT0("webkit", "Document::recalcStyle");
TRACE_EVENT_SCOPED_SAMPLING_STATE("Blink", "RecalcStyle");
+ updateDistributionIfNeeded();
+
+ InspectorInstrumentationCookie cookie = InspectorInstrumentation::willRecalculateStyle(this);
+
if (m_evaluateMediaQueriesOnStyleRecalc) {
m_evaluateMediaQueriesOnStyleRecalc = false;
evaluateMediaQueryList();
}
- updateDistributionIfNeeded();
-
// FIXME: We should update style on our ancestor chain before proceeding (especially for seamless),
// however doing so currently causes several tests to crash, as Frame::setDocument calls Document::attach
// before setting the DOMWindow on the Frame, or the SecurityOrigin on the document. The attach, in turn
@@ -1693,51 +1655,52 @@ void Document::recalcStyle(StyleRecalcChange change)
if (m_styleEngine->needsUpdateActiveStylesheetsOnStyleRecalc())
m_styleEngine->updateActiveStyleSheets(FullStyleUpdate);
- InspectorInstrumentationCookie cookie = InspectorInstrumentation::willRecalculateStyle(this);
-
if (m_elemSheet && m_elemSheet->contents()->usesRemUnits())
m_styleEngine->setUsesRemUnit(true);
- m_inStyleRecalc = true;
{
PostAttachCallbacks::SuspendScope suspendPostAttachCallbacks;
- WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;
-
- RefPtr<FrameView> frameView = view();
- if (frameView) {
- frameView->pauseScheduledEvents();
- frameView->beginDeferredRepaints();
- }
-
- if (!renderer())
- goto bailOut;
+ RenderWidget::UpdateSuspendScope suspendWidgetHierarchyUpdates;
+ FrameView::DeferredRepaintScope deferRepaints(*view());
+ TemporaryChange<bool> changeInStyleRecalc(m_inStyleRecalc, true);
if (styleChangeType() >= SubtreeStyleChange)
change = Force;
- if ((change == Force) || (shouldDisplaySeamlesslyWithParent() && (change >= Inherit))) {
+ // FIXME: Cannot access the ensureStyleResolver() before calling styleForDocument below because
+ // apparently the StyleResolver's constructor has side effects. We should fix it.
+ // See printing/setPrinting.html, printing/width-overflow.html though they only fail on
+ // mac when accessing the resolver by what appears to be a viewport size difference.
+
+ if (change == Force || (change >= Inherit && shouldDisplaySeamlesslyWithParent())) {
m_hasNodesWithPlaceholderStyle = false;
- RefPtr<RenderStyle> documentStyle = StyleResolver::styleForDocument(*this, m_styleResolver ? m_styleResolver->fontSelector() : 0);
- StyleRecalcChange localChange = RenderStyle::compare(documentStyle.get(), renderer()->style());
+ RefPtr<RenderStyle> documentStyle = StyleResolver::styleForDocument(*this, m_styleEngine->fontSelector());
+ StyleRecalcChange localChange = RenderStyle::compare(documentStyle.get(), renderView()->style());
if (localChange != NoChange)
- renderer()->setStyle(documentStyle.release());
+ renderView()->setStyle(documentStyle.release());
}
- inheritHtmlAndBodyElementStyles(change);
+ clearNeedsStyleRecalc();
- for (Node* n = firstChild(); n; n = n->nextSibling()) {
- if (!n->isElementNode())
- continue;
- Element* element = toElement(n);
- if (shouldRecalcStyle(change, element))
- element->recalcStyle(change);
+ // Uncomment to enable printing of statistics about style sharing and the matched property cache.
+ // Optionally pass StyleResolver::ReportSlowStats to print numbers that require crawling the
+ // entire DOM (where collecting them is very slow).
+ // FIXME: Expose this as a runtime flag.
+ // ensureStyleResolver().enableStats(/*StyleResolver::ReportSlowStats*/);
+
+ if (StyleResolverStats* stats = ensureStyleResolver().stats())
+ stats->reset();
+
+ if (Element* documentElement = this->documentElement()) {
+ inheritHtmlAndBodyElementStyles(change);
+ if (shouldRecalcStyle(change, documentElement))
+ documentElement->recalcStyle(change);
}
- if (view())
- view()->updateCompositingLayersAfterStyleChange();
+ ensureStyleResolver().printStats();
+
+ view()->updateCompositingLayersAfterStyleChange();
- bailOut:
- clearNeedsStyleRecalc();
clearChildNeedsStyleRecalc();
unscheduleStyleRecalc();
@@ -1746,30 +1709,21 @@ void Document::recalcStyle(StyleRecalcChange change)
if (m_styleEngine->needsUpdateActiveStylesheetsOnStyleRecalc())
setNeedsStyleRecalc();
- m_inStyleRecalc = false;
-
- // Pseudo element removal and similar may only work with these flags still set. Reset them after the style recalc.
- if (m_styleResolver) {
- m_styleEngine->resetCSSFeatureFlags(m_styleResolver->ruleFeatureSet());
- m_styleResolver->clearStyleSharingList();
- }
-
- if (frameView) {
- frameView->resumeScheduledEvents();
- frameView->endDeferredRepaints();
+ if (m_styleEngine->hasResolver()) {
+ // Pseudo element removal and similar may only work with these flags still set. Reset them after the style recalc.
+ StyleResolver& resolver = m_styleEngine->ensureResolver();
+ m_styleEngine->resetCSSFeatureFlags(resolver.ensureRuleFeatureSet());
+ resolver.clearStyleSharingList();
}
}
- STYLE_STATS_PRINT();
- STYLE_STATS_CLEAR();
-
InspectorInstrumentation::didRecalculateStyle(cookie);
// As a result of the style recalculation, the currently hovered element might have been
// detached (for example, by setting display:none in the :hover style), schedule another mouseMove event
// to check if any other elements ended up under the mouse pointer due to re-layout.
if (hoverNode() && !hoverNode()->renderer() && frame())
- frame()->eventHandler()->dispatchFakeMouseMoveEventSoon();
+ frame()->eventHandler().dispatchFakeMouseMoveEventSoon();
}
void Document::updateStyleIfNeeded()
@@ -1780,8 +1734,10 @@ void Document::updateStyleIfNeeded()
if (!needsStyleRecalc() && !childNeedsStyleRecalc() && !childNeedsDistributionRecalc())
return;
- AnimationUpdateBlock animationUpdateBlock(m_frame ? m_frame->animation() : 0);
+ RefPtr<Frame> holder(m_frame);
+ AnimationUpdateBlock animationUpdateBlock(m_frame ? &m_frame->animation() : 0);
recalcStyle(NoChange);
+ DocumentAnimations::serviceAfterStyleRecalc(*this);
}
void Document::updateStyleForNodeIfNeeded(Node* node)
@@ -1800,7 +1756,7 @@ void Document::updateLayout()
{
ASSERT(isMainThread());
- FrameView* frameView = view();
+ RefPtr<FrameView> frameView = view();
if (frameView && frameView->isInLayout()) {
// View layout should not be re-entrant.
ASSERT_NOT_REACHED();
@@ -1813,10 +1769,10 @@ void Document::updateLayout()
updateStyleIfNeeded();
// Only do a layout if changes have occurred that make it necessary.
- if (frameView && renderer() && (frameView->layoutPending() || renderer()->needsLayout()))
+ if (isActive() && frameView && renderView() && (frameView->layoutPending() || renderView()->needsLayout()))
frameView->layout();
- if (frameView)
+ if (isActive() && frameView)
frameView->partialLayout().reset();
setNeedsFocusedElementCheck();
@@ -1827,32 +1783,33 @@ void Document::setNeedsFocusedElementCheck()
// FIXME: Using a Task doesn't look a good idea.
if (!m_focusedElement || m_didPostCheckFocusedElementTask)
return;
- postTask(CheckFocusedElementTask::create());
+ m_taskRunner->postTask(CheckFocusedElementTask::create());
m_didPostCheckFocusedElementTask = true;
}
void Document::recalcStyleForLayoutIgnoringPendingStylesheets()
{
- TemporaryChange<bool> ignorePendingStylesheets(m_ignorePendingStylesheets, m_ignorePendingStylesheets);
- if (!haveStylesheetsLoaded()) {
- m_ignorePendingStylesheets = true;
- // FIXME: We are willing to attempt to suppress painting with outdated style info only once.
- // Our assumption is that it would be dangerous to try to stop it a second time, after page
- // content has already been loaded and displayed with accurate style information. (Our
- // suppression involves blanking the whole page at the moment. If it were more refined, we
- // might be able to do something better.) It's worth noting though that this entire method
- // is a hack, since what we really want to do is suspend JS instead of doing a layout with
- // inaccurate information.
- HTMLElement* bodyElement = body();
- if (bodyElement && !bodyElement->renderer() && m_pendingSheetLayout == NoLayoutWithPendingSheets) {
- m_pendingSheetLayout = DidLayoutWithPendingSheets;
- styleResolverChanged(RecalcStyleImmediately);
- } else if (m_hasNodesWithPlaceholderStyle) {
- // If new nodes have been added or style recalc has been done with style sheets still
- // pending, some nodes may not have had their real style calculated yet. Normally this
- // gets cleaned when style sheets arrive but here we need up-to-date style immediately.
- recalcStyle(Force);
- }
+ ASSERT(m_styleEngine->ignoringPendingStylesheets());
+
+ if (!m_styleEngine->hasPendingSheets())
+ return;
+
+ // FIXME: We are willing to attempt to suppress painting with outdated style info only once.
+ // Our assumption is that it would be dangerous to try to stop it a second time, after page
+ // content has already been loaded and displayed with accurate style information. (Our
+ // suppression involves blanking the whole page at the moment. If it were more refined, we
+ // might be able to do something better.) It's worth noting though that this entire method
+ // is a hack, since what we really want to do is suspend JS instead of doing a layout with
+ // inaccurate information.
+ HTMLElement* bodyElement = body();
+ if (bodyElement && !bodyElement->renderer() && m_pendingSheetLayout == NoLayoutWithPendingSheets) {
+ m_pendingSheetLayout = DidLayoutWithPendingSheets;
+ styleResolverChanged(RecalcStyleImmediately);
+ } else if (m_hasNodesWithPlaceholderStyle) {
+ // If new nodes have been added or style recalc has been done with style sheets still
+ // pending, some nodes may not have had their real style calculated yet. Normally this
+ // gets cleaned when style sheets arrive but here we need up-to-date style immediately.
+ recalcStyle(Force);
}
}
@@ -1862,10 +1819,13 @@ void Document::recalcStyleForLayoutIgnoringPendingStylesheets()
// stylesheets are loaded. Doing a layout ignoring the pending stylesheets
// lets us get reasonable answers. The long term solution to this problem is
// to instead suspend JavaScript execution.
-void Document::updateLayoutIgnorePendingStylesheets()
+void Document::updateLayoutIgnorePendingStylesheets(Document::RunPostLayoutTasks runPostLayoutTasks)
{
+ StyleEngine::IgnoringPendingStylesheet ignoring(m_styleEngine.get());
recalcStyleForLayoutIgnoringPendingStylesheets();
updateLayout();
+ if (runPostLayoutTasks == RunPostLayoutTasksSynchronously && view())
+ view()->flushAnyPendingPostLayoutTasks();
}
void Document::partialUpdateLayoutIgnorePendingStylesheets(Node* stopLayoutAtNode)
@@ -1877,7 +1837,7 @@ void Document::partialUpdateLayoutIgnorePendingStylesheets(Node* stopLayoutAtNod
return;
}
- TemporaryChange<bool> ignorePendingStylesheets(m_ignorePendingStylesheets, m_ignorePendingStylesheets);
+ StyleEngine::IgnoringPendingStylesheet ignoring(m_styleEngine.get());
recalcStyleForLayoutIgnoringPendingStylesheets();
if (stopLayoutAtNode) {
@@ -1902,14 +1862,14 @@ void Document::partialUpdateLayoutIgnorePendingStylesheets(Node* stopLayoutAtNod
PassRefPtr<RenderStyle> Document::styleForElementIgnoringPendingStylesheets(Element* element)
{
- ASSERT_ARG(element, &element->document() == this);
- TemporaryChange<bool> ignoreStyleSheets(m_ignorePendingStylesheets, true);
- return styleResolver()->styleForElement(element, element->parentNode() ? element->parentNode()->computedStyle() : 0);
+ ASSERT_ARG(element, element->document() == this);
+ StyleEngine::IgnoringPendingStylesheet ignoring(m_styleEngine.get());
+ return ensureStyleResolver().styleForElement(element, element->parentNode() ? element->parentNode()->computedStyle() : 0);
}
PassRefPtr<RenderStyle> Document::styleForPage(int pageIndex)
{
- return styleResolver()->styleForPage(pageIndex);
+ return ensureStyleResolver().styleForPage(pageIndex);
}
bool Document::isPageBoxVisible(int pageIndex)
@@ -1966,37 +1926,44 @@ void Document::setIsViewSource(bool isViewSource)
didUpdateSecurityOrigin();
}
-void Document::createStyleResolver()
+StyleResolver* Document::styleResolver() const
{
- bool matchAuthorAndUserStyles = true;
- if (Settings* docSettings = settings())
- matchAuthorAndUserStyles = docSettings->authorAndUserStylesEnabled();
- m_styleResolver = adoptPtr(new StyleResolver(*this, matchAuthorAndUserStyles));
- m_styleEngine->combineCSSFeatureFlags(m_styleResolver->ruleFeatureSet());
+ return m_styleEngine->resolver();
+}
+
+StyleResolver& Document::ensureStyleResolver() const
+{
+ return m_styleEngine->ensureResolver();
}
void Document::clearStyleResolver()
{
- m_styleResolver.clear();
+ m_styleEngine->clearResolver();
}
void Document::attach(const AttachContext& context)
{
- ASSERT(!attached());
+ ASSERT(m_lifecyle.state() == DocumentLifecycle::Inactive);
ASSERT(!m_axObjectCache || this != topDocument());
- // Create the rendering tree
- setRenderer(new RenderView(this));
- renderView()->setIsInWindow(true);
+ m_renderView = new RenderView(this);
+ setRenderer(m_renderView);
+
+ m_renderView->setIsInWindow(true);
+ m_renderView->setStyle(StyleResolver::styleForDocument(*this));
+ view()->updateCompositingLayersAfterStyleChange();
- recalcStyle(Force);
+ m_styleEngine->didAttach();
ContainerNode::attach(context);
+
+ m_lifecyle.advanceTo(DocumentLifecycle::Active);
}
void Document::detach(const AttachContext& context)
{
- ASSERT(attached());
+ ASSERT(isActive());
+ m_lifecyle.advanceTo(DocumentLifecycle::Stopping);
if (page())
page()->documentDetached(this);
@@ -2005,7 +1972,6 @@ void Document::detach(const AttachContext& context)
clearAXObjectCache();
stopActiveDOMObjects();
- m_eventQueue->close();
// FIXME: consider using ActiveDOMObject.
if (m_scriptedAnimationController)
@@ -2015,11 +1981,14 @@ void Document::detach(const AttachContext& context)
if (svgExtensions())
accessSVGExtensions()->pauseAnimations();
- RenderObject* render = renderer();
+ // FIXME: This shouldn't be needed once DOMWindow becomes ExecutionContext.
+ if (m_domWindow)
+ m_domWindow->clearEventQueue();
- documentWillBecomeInactive();
+ RenderView* renderView = m_renderView;
- SharedWorkerRepository::documentDetached(this);
+ if (renderView)
+ renderView->setIsInWindow(false);
if (m_frame) {
FrameView* view = m_frame->view();
@@ -2027,8 +1996,10 @@ void Document::detach(const AttachContext& context)
view->detachCustomScrollbars();
}
- // indicate destruction mode, i.e. attached() but renderer == 0
+ // Indicate destruction mode by setting the renderer to null.
+ // FIXME: Don't do this and use m_lifecycle.state() == Stopping instead.
setRenderer(0);
+ m_renderView = 0;
m_hoverNode = 0;
m_focusedElement = 0;
@@ -2038,10 +2009,10 @@ void Document::detach(const AttachContext& context)
unscheduleStyleRecalc();
- clearStyleResolver();
+ m_styleEngine->didDetach();
- if (render)
- render->destroy();
+ if (renderView)
+ renderView->destroy();
if (m_touchEventTargets && m_touchEventTargets->size() && parentDocument())
parentDocument()->didRemoveEventTargetNode(this);
@@ -2056,16 +2027,17 @@ void Document::detach(const AttachContext& context)
if (m_mediaQueryMatcher)
m_mediaQueryMatcher->documentDestroyed();
- lifecycleNotifier()->notifyDocumentWasDetached();
+ lifecycleNotifier().notifyDocumentWasDetached();
+ m_lifecyle.advanceTo(DocumentLifecycle::Stopped);
}
void Document::prepareForDestruction()
{
+ m_markers->prepareForDestruction();
disconnectDescendantFrames();
- // The process of disconnecting descendant frames could have already
- // detached us.
- if (!attached())
+ // The process of disconnecting descendant frames could have already detached us.
+ if (!isActive())
return;
if (DOMWindow* window = this->domWindow())
@@ -2079,20 +2051,10 @@ void Document::removeAllEventListeners()
if (DOMWindow* domWindow = this->domWindow())
domWindow->removeAllEventListeners();
- for (Node* node = firstChild(); node; node = NodeTraversal::next(node))
+ for (Node* node = firstChild(); node; node = NodeTraversal::next(*node))
node->removeAllEventListeners();
}
-void Document::suspendActiveDOMObjects(ActiveDOMObject::ReasonForSuspension why)
-{
- ScriptExecutionContext::suspendActiveDOMObjects(why);
-}
-
-void Document::resumeActiveDOMObjects()
-{
- ScriptExecutionContext::resumeActiveDOMObjects();
-}
-
void Document::clearAXObjectCache()
{
ASSERT(topDocument() == this);
@@ -2108,7 +2070,7 @@ AXObjectCache* Document::existingAXObjectCache() const
// If the renderer is gone then we are in the process of destruction.
// This method will be called before m_frame = 0.
- if (!topDocument()->renderer())
+ if (!topDocument()->renderView())
return 0;
return topDocument()->m_axObjectCache.get();
@@ -2126,7 +2088,7 @@ AXObjectCache* Document::axObjectCache() const
Document* topDocument = this->topDocument();
// If the document has already been detached, do not make a new axObjectCache.
- if (!topDocument->renderer())
+ if (!topDocument->renderView())
return 0;
ASSERT(topDocument == this || !m_axObjectCache);
@@ -2139,8 +2101,8 @@ void Document::setVisuallyOrdered()
{
m_visuallyOrdered = true;
// FIXME: How is possible to not have a renderer here?
- if (renderer())
- renderer()->style()->setRTLOrdering(VisualOrder);
+ if (renderView())
+ renderView()->style()->setRTLOrdering(VisualOrder);
setNeedsStyleRecalc();
}
@@ -2173,7 +2135,6 @@ void Document::open(Document* ownerDocument)
setURL(ownerDocument->url());
m_cookieURL = ownerDocument->cookieURL();
setSecurityOrigin(ownerDocument->securityOrigin());
- InspectorInstrumentation::childDocumentOpened(this);
}
if (m_frame) {
@@ -2188,8 +2149,8 @@ void Document::open(Document* ownerDocument)
}
}
- if (m_frame->loader()->state() == FrameStateProvisional)
- m_frame->loader()->stopAllLoaders();
+ if (m_frame->loader().state() == FrameStateProvisional)
+ m_frame->loader().stopAllLoaders();
}
removeAllEventListeners();
@@ -2198,7 +2159,7 @@ void Document::open(Document* ownerDocument)
parser->setWasCreatedByScript(true);
if (m_frame)
- m_frame->loader()->didExplicitOpen();
+ m_frame->loader().didExplicitOpen();
if (m_loadEventProgress != LoadEventInProgress && m_loadEventProgress != UnloadEventInProgress)
m_loadEventProgress = LoadEventNotRun;
}
@@ -2219,7 +2180,7 @@ void Document::cancelParsing()
// We have to clear the parser to avoid possibly triggering
// the onload handler when closing as a side effect of a cancel-style
// change, such as opening a new document or closing the window while
- // still parsing
+ // still parsing.
detachParser();
explicitClose();
}
@@ -2259,17 +2220,17 @@ HTMLElement* Document::body() const
return 0;
}
-void Document::setBody(PassRefPtr<HTMLElement> prpNewBody, ExceptionState& es)
+void Document::setBody(PassRefPtr<HTMLElement> prpNewBody, ExceptionState& exceptionState)
{
RefPtr<HTMLElement> newBody = prpNewBody;
if (!newBody || !documentElement()) {
- es.throwDOMException(HierarchyRequestError);
+ exceptionState.throwUninformativeAndGenericDOMException(HierarchyRequestError);
return;
}
if (!newBody->hasTagName(bodyTag) && !newBody->hasTagName(framesetTag)) {
- es.throwDOMException(HierarchyRequestError);
+ exceptionState.throwUninformativeAndGenericDOMException(HierarchyRequestError);
return;
}
@@ -2278,9 +2239,9 @@ void Document::setBody(PassRefPtr<HTMLElement> prpNewBody, ExceptionState& es)
return;
if (oldBody)
- documentElement()->replaceChild(newBody.release(), oldBody, es);
+ documentElement()->replaceChild(newBody.release(), oldBody, exceptionState);
else
- documentElement()->appendChild(newBody.release(), es);
+ documentElement()->appendChild(newBody.release(), exceptionState);
}
HTMLHeadElement* Document::head()
@@ -2320,14 +2281,14 @@ void Document::explicitClose()
return;
}
- m_frame->loader()->checkCompleted();
+ m_frame->loader().checkCompleted();
}
void Document::implicitClose()
{
ASSERT(!inStyleRecalc());
- bool wasLocationChangePending = frame() && frame()->navigationScheduler()->locationChangePending();
+ bool wasLocationChangePending = frame() && frame()->navigationScheduler().locationChangePending();
bool doload = !parsing() && m_parser && !processingLoadEvent() && !wasLocationChangePending;
// If the load was blocked because of a pending location change and the location change triggers a same document
@@ -2339,7 +2300,7 @@ void Document::implicitClose()
// The call to dispatchWindowLoadEvent can detach the DOMWindow and cause it (and its
// attached Document) to be destroyed.
- RefPtr<DOMWindow> protect(this->domWindow());
+ RefPtr<DOMWindow> protectedWindow(this->domWindow());
m_loadEventProgress = LoadEventInProgress;
@@ -2350,11 +2311,7 @@ void Document::implicitClose()
// onLoad event handler, as in Radar 3206524.
detachParser();
- Frame* f = frame();
- if (f && !RuntimeEnabledFeatures::webAnimationsCSSEnabled())
- f->animation()->resumeAnimationsForDocument(this);
-
- if (f && f->script()->canExecuteScripts(NotAboutToExecuteScript)) {
+ if (frame() && frame()->script().canExecuteScripts(NotAboutToExecuteScript)) {
ImageLoader::dispatchPendingBeforeLoadEvents();
ImageLoader::dispatchPendingLoadEvents();
ImageLoader::dispatchPendingErrorEvents();
@@ -2363,22 +2320,23 @@ void Document::implicitClose()
HTMLStyleElement::dispatchPendingLoadEvents();
}
+ // JS running below could remove the frame or destroy the RenderView so we call
+ // those two functions repeatedly and don't save them on the stack.
+
// To align the HTML load event and the SVGLoad event for the outermost <svg> element, fire it from
// here, instead of doing it from SVGElement::finishedParsingChildren (if externalResourcesRequired="false",
// which is the default, for ='true' its fired at a later time, once all external resources finished loading).
if (svgExtensions())
accessSVGExtensions()->dispatchSVGLoadEventToOutermostSVGElements();
- dispatchWindowLoadEvent();
- enqueuePageshowEvent(PageshowEventNotPersisted);
- enqueuePopstateEvent(m_pendingStateObject ? m_pendingStateObject.release() : SerializedScriptValue::nullValue());
+ if (protectedWindow)
+ protectedWindow->documentWasClosed();
if (frame()) {
- frame()->loader()->client()->dispatchDidHandleOnloadEvents();
+ frame()->loader().client()->dispatchDidHandleOnloadEvents();
loader()->applicationCacheHost()->stopDeferringEvents();
}
- // An event handler may have removed the frame
if (!frame()) {
m_loadEventProgress = LoadEventCompleted;
return;
@@ -2388,7 +2346,7 @@ void Document::implicitClose()
// fires. This will improve onload scores, and other browsers do it.
// If they wanna cheat, we can too. -dwh
- if (frame()->navigationScheduler()->locationChangePending() && elapsedTime() < cLayoutScheduleThreshold) {
+ if (frame()->navigationScheduler().locationChangePending() && elapsedTime() < cLayoutScheduleThreshold) {
// Just bail out. Before or during the onload we were shifted to another page.
// The old i-Bench suite does this. When this happens don't bother painting or laying out.
m_loadEventProgress = LoadEventCompleted;
@@ -2396,8 +2354,6 @@ void Document::implicitClose()
return;
}
- RenderObject* renderObject = renderer();
-
// We used to force a synchronous display and flush here. This really isn't
// necessary and can in fact be actively harmful if pages are loading at a rate of > 60fps
// (if your platform is syncing flushes and limiting them to 60fps).
@@ -2406,25 +2362,25 @@ void Document::implicitClose()
updateStyleIfNeeded();
// Always do a layout after loading if needed.
- if (view() && renderObject && (!renderObject->firstChild() || renderObject->needsLayout()))
+ if (view() && renderView() && (!renderView()->firstChild() || renderView()->needsLayout()))
view()->layout();
}
m_loadEventProgress = LoadEventCompleted;
- if (f && renderObject && AXObjectCache::accessibilityEnabled()) {
+ if (frame() && renderView() && AXObjectCache::accessibilityEnabled()) {
// The AX cache may have been cleared at this point, but we need to make sure it contains an
// AX object to send the notification to. getOrCreate will make sure that an valid AX object
// exists in the cache (we ignore the return value because we don't need it here). This is
// only safe to call when a layout is not in progress, so it can not be used in postNotification.
if (AXObjectCache* cache = axObjectCache()) {
- cache->getOrCreate(renderObject);
+ cache->getOrCreate(renderView());
if (this == topDocument()) {
- cache->postNotification(renderObject, AXObjectCache::AXLoadComplete, true);
+ cache->postNotification(renderView(), AXObjectCache::AXLoadComplete, true);
} else {
// AXLoadComplete can only be posted on the top document, so if it's a document
// in an iframe that just finished loading, post AXLayoutComplete instead.
- cache->postNotification(renderObject, AXObjectCache::AXLayoutComplete, true);
+ cache->postNotification(renderView(), AXObjectCache::AXLayoutComplete, true);
}
}
}
@@ -2445,7 +2401,7 @@ bool Document::dispatchBeforeUnloadEvent(Chrome& chrome, bool& didAllowNavigatio
RefPtr<BeforeUnloadEvent> beforeUnloadEvent = BeforeUnloadEvent::create();
m_loadEventProgress = BeforeUnloadEventInProgress;
- dispatchWindowEvent(beforeUnloadEvent.get(), this);
+ m_domWindow->dispatchEvent(beforeUnloadEvent.get(), this);
m_loadEventProgress = BeforeUnloadEventCompleted;
if (!beforeUnloadEvent->defaultPrevented())
defaultEventHandler(beforeUnloadEvent.get());
@@ -2457,7 +2413,7 @@ bool Document::dispatchBeforeUnloadEvent(Chrome& chrome, bool& didAllowNavigatio
return true;
}
- String text = displayStringModifiedByEncoding(beforeUnloadEvent->returnValue());
+ String text = beforeUnloadEvent->returnValue();
if (chrome.runBeforeUnloadConfirmPanel(text, m_frame)) {
didAllowNavigation = true;
return true;
@@ -2477,27 +2433,27 @@ void Document::dispatchUnloadEvents()
toHTMLInputElement(currentFocusedElement)->endEditing();
if (m_loadEventProgress < PageHideInProgress) {
m_loadEventProgress = PageHideInProgress;
- dispatchWindowEvent(PageTransitionEvent::create(eventNames().pagehideEvent, false), this);
+ if (DOMWindow* window = domWindow())
+ window->dispatchEvent(PageTransitionEvent::create(EventTypeNames::pagehide, false), this);
if (!m_frame)
return;
// The DocumentLoader (and thus its DocumentLoadTiming) might get destroyed
// while dispatching the event, so protect it to prevent writing the end
// time into freed memory.
- RefPtr<DocumentLoader> documentLoader = m_frame->loader()->provisionalDocumentLoader();
+ RefPtr<DocumentLoader> documentLoader = m_frame->loader().provisionalDocumentLoader();
m_loadEventProgress = UnloadEventInProgress;
- RefPtr<Event> unloadEvent(Event::create(eventNames().unloadEvent));
+ RefPtr<Event> unloadEvent(Event::create(EventTypeNames::unload));
if (documentLoader && !documentLoader->timing()->unloadEventStart() && !documentLoader->timing()->unloadEventEnd()) {
DocumentLoadTiming* timing = documentLoader->timing();
ASSERT(timing->navigationStart());
timing->markUnloadEventStart();
- dispatchWindowEvent(unloadEvent, this);
+ m_frame->domWindow()->dispatchEvent(unloadEvent, this);
timing->markUnloadEventEnd();
} else {
m_frame->domWindow()->dispatchEvent(unloadEvent, m_frame->document());
}
}
- updateStyleIfNeeded();
m_loadEventProgress = UnloadEventHandled;
}
@@ -2505,8 +2461,8 @@ void Document::dispatchUnloadEvents()
return;
// Don't remove event listeners from a transitional empty document (see https://bugs.webkit.org/show_bug.cgi?id=28716 for more information).
- bool keepEventListeners = m_frame->loader()->stateMachine()->isDisplayingInitialEmptyDocument() && m_frame->loader()->provisionalDocumentLoader()
- && isSecureTransitionTo(m_frame->loader()->provisionalDocumentLoader()->url());
+ bool keepEventListeners = m_frame->loader().stateMachine()->isDisplayingInitialEmptyDocument() && m_frame->loader().provisionalDocumentLoader()
+ && isSecureTransitionTo(m_frame->loader().provisionalDocumentLoader()->url());
if (!keepEventListeners)
removeAllEventListeners();
}
@@ -2613,7 +2569,7 @@ double Document::timerAlignmentInterval() const
{
Page* p = page();
if (!p)
- return ScriptExecutionContext::timerAlignmentInterval();
+ return DOMTimer::visiblePageAlignmentInterval();
return p->timerAlignmentInterval();
}
@@ -2656,7 +2612,7 @@ void Document::updateBaseURL()
// FIXME: Now that we don't support Objective-C this can probably be removed.
m_baseURL = KURL(ParsedURLString, documentURI());
}
- selectorQueryCache()->invalidate();
+ selectorQueryCache().invalidate();
if (!m_baseURL.isValid())
m_baseURL = KURL();
@@ -2673,7 +2629,7 @@ void Document::updateBaseURL()
if (!equalIgnoringFragmentIdentifier(oldBaseURL, m_baseURL)) {
// Base URL change changes any relative visited links.
// FIXME: There are other URLs in the tree that would need to be re-evaluated on dynamic base URL change. Style should be invalidated too.
- for (Element* element = ElementTraversal::firstWithin(this); element; element = ElementTraversal::next(element)) {
+ for (Element* element = ElementTraversal::firstWithin(*this); element; element = ElementTraversal::next(*element)) {
if (isHTMLAnchorElement(element))
toHTMLAnchorElement(element)->invalidateCachedVisitedLinkHash();
}
@@ -2691,7 +2647,7 @@ void Document::processBaseElement()
// Find the first href attribute in a base element and the first target attribute in a base element.
const AtomicString* href = 0;
const AtomicString* target = 0;
- for (Element* element = ElementTraversal::firstWithin(this); element && (!href || !target); element = ElementTraversal::next(element)) {
+ for (Element* element = ElementTraversal::firstWithin(*this); element && (!href || !target); element = ElementTraversal::next(*element)) {
if (element->hasTagName(baseTag)) {
if (!href) {
const AtomicString& value = element->fastGetAttribute(hrefAttr);
@@ -2704,7 +2660,7 @@ void Document::processBaseElement()
target = &value;
}
if (contentSecurityPolicy()->isActive())
- UseCounter::count(this, UseCounter::ContentSecurityPolicyWithBaseElement);
+ UseCounter::count(*this, UseCounter::ContentSecurityPolicyWithBaseElement);
}
}
@@ -2725,7 +2681,7 @@ void Document::processBaseElement()
String Document::userAgent(const KURL& url) const
{
- return frame() ? frame()->loader()->userAgent(url) : String();
+ return frame() ? frame()->loader().userAgent(url) : String();
}
void Document::disableEval(const String& errorMessage)
@@ -2733,7 +2689,7 @@ void Document::disableEval(const String& errorMessage)
if (!frame())
return;
- frame()->script()->disableEval(errorMessage);
+ frame()->script().disableEval(errorMessage);
}
bool Document::canNavigate(Frame* targetFrame)
@@ -2748,21 +2704,24 @@ bool Document::canNavigate(Frame* targetFrame)
return true;
// Frame-busting is generally allowed, but blocked for sandboxed frames lacking the 'allow-top-navigation' flag.
- if (!isSandboxed(SandboxTopNavigation) && targetFrame == m_frame->tree()->top())
+ if (!isSandboxed(SandboxTopNavigation) && targetFrame == m_frame->tree().top())
return true;
if (isSandboxed(SandboxNavigation)) {
- if (targetFrame->tree()->isDescendantOf(m_frame))
+ if (targetFrame->tree().isDescendantOf(m_frame))
return true;
const char* reason = "The frame attempting navigation is sandboxed, and is therefore disallowed from navigating its ancestors.";
- if (isSandboxed(SandboxTopNavigation) && targetFrame == m_frame->tree()->top())
+ if (isSandboxed(SandboxTopNavigation) && targetFrame == m_frame->tree().top())
reason = "The frame attempting navigation of the top-level window is sandboxed, but the 'allow-top-navigation' flag is not set.";
- printNavigationErrorMessage(targetFrame, url(), reason);
+ printNavigationErrorMessage(*targetFrame, url(), reason);
return false;
}
+ ASSERT(securityOrigin());
+ SecurityOrigin& origin = *securityOrigin();
+
// This is the normal case. A document can navigate its decendant frames,
// or, more generally, a document can navigate a frame if the document is
// in the same origin as any of that frame's ancestors (in the frame
@@ -2770,7 +2729,7 @@ bool Document::canNavigate(Frame* targetFrame)
//
// See http://www.adambarth.com/papers/2008/barth-jackson-mitchell.pdf for
// historical information about this security check.
- if (canAccessAncestor(securityOrigin(), targetFrame))
+ if (canAccessAncestor(origin, targetFrame))
return true;
// Top-level frames are easier to navigate than other frames because they
@@ -2784,28 +2743,28 @@ bool Document::canNavigate(Frame* targetFrame)
// some way related to the frame being navigate (e.g., by the "opener"
// and/or "parent" relation). Requiring some sort of relation prevents a
// document from navigating arbitrary, unrelated top-level frames.
- if (!targetFrame->tree()->parent()) {
- if (targetFrame == m_frame->loader()->opener())
+ if (!targetFrame->tree().parent()) {
+ if (targetFrame == m_frame->loader().opener())
return true;
- if (canAccessAncestor(securityOrigin(), targetFrame->loader()->opener()))
+ if (canAccessAncestor(origin, targetFrame->loader().opener()))
return true;
}
- printNavigationErrorMessage(targetFrame, url(), "The frame attempting navigation is neither same-origin with the target, nor is it the target's parent or opener.");
+ printNavigationErrorMessage(*targetFrame, url(), "The frame attempting navigation is neither same-origin with the target, nor is it the target's parent or opener.");
return false;
}
Frame* Document::findUnsafeParentScrollPropagationBoundary()
{
Frame* currentFrame = m_frame;
- Frame* ancestorFrame = currentFrame->tree()->parent();
+ Frame* ancestorFrame = currentFrame->tree().parent();
while (ancestorFrame) {
if (!ancestorFrame->document()->securityOrigin()->canAccess(securityOrigin()))
return currentFrame;
currentFrame = ancestorFrame;
- ancestorFrame = ancestorFrame->tree()->parent();
+ ancestorFrame = ancestorFrame->tree().parent();
}
return 0;
}
@@ -2844,7 +2803,7 @@ CSSStyleSheet* Document::elementSheet()
return m_elemSheet.get();
}
-void Document::processHttpEquiv(const String& equiv, const String& content)
+void Document::processHttpEquiv(const AtomicString& equiv, const AtomicString& content)
{
ASSERT(!equiv.isNull() && !content.isNull());
@@ -2867,21 +2826,22 @@ void Document::processHttpEquiv(const String& equiv, const String& content)
processHttpEquivContentSecurityPolicy(equiv, content);
}
-void Document::processHttpEquivContentSecurityPolicy(const String& equiv, const String& content)
+void Document::processHttpEquivContentSecurityPolicy(const AtomicString& equiv, const AtomicString& content)
{
if (equalIgnoringCase(equiv, "content-security-policy"))
contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::Enforce);
else if (equalIgnoringCase(equiv, "content-security-policy-report-only"))
contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::Report);
+ // FIXME: Remove deprecation messages after the next release branch.
else if (equalIgnoringCase(equiv, "x-webkit-csp"))
- contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::PrefixedEnforce);
+ UseCounter::countDeprecation(this, UseCounter::PrefixedContentSecurityPolicy);
else if (equalIgnoringCase(equiv, "x-webkit-csp-report-only"))
- contentSecurityPolicy()->didReceiveHeader(content, ContentSecurityPolicy::PrefixedReport);
+ UseCounter::countDeprecation(this, UseCounter::PrefixedContentSecurityPolicyReportOnly);
else
ASSERT_NOT_REACHED();
}
-void Document::processHttpEquivDefaultStyle(const String& content)
+void Document::processHttpEquivDefaultStyle(const AtomicString& content)
{
// The preferred style set has been overridden as per section
// 14.3.2 of the HTML4.0 specification. We need to update the
@@ -2894,7 +2854,7 @@ void Document::processHttpEquivDefaultStyle(const String& content)
styleResolverChanged(RecalcStyleDeferred);
}
-void Document::processHttpEquivRefresh(const String& content)
+void Document::processHttpEquivRefresh(const AtomicString& content)
{
maybeHandleHttpRefresh(content, HttpRefreshFromMetaTag);
}
@@ -2924,10 +2884,10 @@ void Document::maybeHandleHttpRefresh(const String& content, HttpRefreshType htt
addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, message);
return;
}
- m_frame->navigationScheduler()->scheduleRedirect(delay, refreshURL);
+ m_frame->navigationScheduler().scheduleRedirect(delay, refreshURL);
}
-void Document::processHttpEquivSetCookie(const String& content)
+void Document::processHttpEquivSetCookie(const AtomicString& content)
{
// FIXME: make setCookie work on XML documents too; e.g. in case of <html:meta .....>
if (!isHTMLDocument())
@@ -2937,167 +2897,62 @@ void Document::processHttpEquivSetCookie(const String& content)
toHTMLDocument(this)->setCookie(content, IGNORE_EXCEPTION);
}
-void Document::processHttpEquivXFrameOptions(const String& content)
+void Document::processHttpEquivXFrameOptions(const AtomicString& content)
{
Frame* frame = this->frame();
if (!frame)
return;
- FrameLoader* frameLoader = frame->loader();
+ FrameLoader& frameLoader = frame->loader();
unsigned long requestIdentifier = loader()->mainResourceIdentifier();
- if (frameLoader->shouldInterruptLoadForXFrameOptions(content, url(), requestIdentifier)) {
+ if (frameLoader.shouldInterruptLoadForXFrameOptions(content, url(), requestIdentifier)) {
String message = "Refused to display '" + url().elidedString() + "' in a frame because it set 'X-Frame-Options' to '" + content + "'.";
- frameLoader->stopAllLoaders();
+ frameLoader.stopAllLoaders();
// Stopping the loader isn't enough, as we're already parsing the document; to honor the header's
// intent, we must navigate away from the possibly partially-rendered document to a location that
// doesn't inherit the parent's SecurityOrigin.
- frame->navigationScheduler()->scheduleLocationChange(securityOrigin(), SecurityOrigin::urlWithUniqueSecurityOrigin(), String());
+ frame->navigationScheduler().scheduleLocationChange(this, SecurityOrigin::urlWithUniqueSecurityOrigin(), String());
addConsoleMessageWithRequestIdentifier(SecurityMessageSource, ErrorMessageLevel, message, requestIdentifier);
}
}
-static bool isInvalidSeparator(UChar c)
+bool Document::shouldMergeWithLegacyDescription(ViewportDescription::Type origin)
{
- return c == ';';
+ return settings() && settings()->viewportMetaMergeContentQuirk() && m_legacyViewportDescription.isMetaViewportType() && m_legacyViewportDescription.type == origin;
}
-// Though isspace() considers \t and \v to be whitespace, Win IE doesn't.
-static bool isSeparator(UChar c)
+void Document::setViewportDescription(const ViewportDescription& viewportDescription)
{
- return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '=' || c == ',' || c == '\0';
-}
-
-void Document::processArguments(const String& features, void* data, ArgumentsCallback callback)
-{
- bool error = false;
-
- // Tread lightly in this code -- it was specifically designed to mimic Win IE's parsing behavior.
- int keyBegin, keyEnd;
- int valueBegin, valueEnd;
-
- int i = 0;
- int length = features.length();
- String buffer = features.lower();
- while (i < length) {
- // skip to first non-separator, but don't skip past the end of the string
- while (isSeparator(buffer[i])) {
- if (i >= length)
- break;
- i++;
- }
- keyBegin = i;
-
- // skip to first separator
- while (!isSeparator(buffer[i])) {
- error |= isInvalidSeparator(buffer[i]);
- i++;
- }
- keyEnd = i;
-
- // skip to first '=', but don't skip past a ',' or the end of the string
- while (buffer[i] != '=') {
- error |= isInvalidSeparator(buffer[i]);
- if (buffer[i] == ',' || i >= length)
- break;
- i++;
- }
-
- // skip to first non-separator, but don't skip past a ',' or the end of the string
- while (isSeparator(buffer[i])) {
- if (buffer[i] == ',' || i >= length)
- break;
- i++;
- }
- valueBegin = i;
-
- // skip to first separator
- while (!isSeparator(buffer[i])) {
- error |= isInvalidSeparator(buffer[i]);
- i++;
- }
- valueEnd = i;
-
- ASSERT_WITH_SECURITY_IMPLICATION(i <= length);
-
- String keyString = buffer.substring(keyBegin, keyEnd - keyBegin);
- String valueString = buffer.substring(valueBegin, valueEnd - valueBegin);
- callback(keyString, valueString, this, data);
- }
- if (error) {
- String message = "Error parsing a meta element's content: ';' is not a valid key-value pair separator. Please use ',' instead.";
- addConsoleMessage(RenderingMessageSource, WarningMessageLevel, message);
- }
-}
-
-void Document::processViewport(const String& features, ViewportArguments::Type origin)
-{
- ASSERT(!features.isNull());
-
- if (!page() || !shouldOverrideLegacyViewport(origin))
- return;
-
- ViewportArguments newArgumentsFromLegacyTag(origin);
- processArguments(features, (void*)&newArgumentsFromLegacyTag, &setViewportFeature);
-
- if (newArgumentsFromLegacyTag.minZoom == ViewportArguments::ValueAuto)
- newArgumentsFromLegacyTag.minZoom = 0.25;
-
- if (newArgumentsFromLegacyTag.maxZoom == ViewportArguments::ValueAuto) {
- newArgumentsFromLegacyTag.maxZoom = 5;
- newArgumentsFromLegacyTag.minZoom = std::min(newArgumentsFromLegacyTag.minZoom, float(5));
- }
-
- const Settings& settings = document().page()->settings();
-
- if (newArgumentsFromLegacyTag.maxWidth.isAuto()) {
- if (newArgumentsFromLegacyTag.zoom == ViewportArguments::ValueAuto) {
- newArgumentsFromLegacyTag.minWidth = Length(ExtendToZoom);
- newArgumentsFromLegacyTag.maxWidth = Length(settings.layoutFallbackWidth(), Fixed);
- } else if (newArgumentsFromLegacyTag.maxHeight.isAuto()) {
- newArgumentsFromLegacyTag.minWidth = Length(ExtendToZoom);
- newArgumentsFromLegacyTag.maxWidth = Length(ExtendToZoom);
- }
- }
-
- if (settings.viewportMetaZeroValuesQuirk()
- && newArgumentsFromLegacyTag.type == ViewportArguments::ViewportMeta
- && newArgumentsFromLegacyTag.maxWidth.type() == ViewportPercentageWidth
- && !static_cast<int>(newArgumentsFromLegacyTag.zoom)) {
- newArgumentsFromLegacyTag.zoom = 1.0;
- }
-
- setViewportArguments(newArgumentsFromLegacyTag);
-}
+ if (viewportDescription.isLegacyViewportType()) {
+ if (settings() && !settings()->viewportMetaEnabled())
+ return;
-void Document::setViewportArguments(const ViewportArguments& viewportArguments)
-{
- if (viewportArguments.isLegacyViewportType()) {
- m_legacyViewportArguments = viewportArguments;
+ m_legacyViewportDescription = viewportDescription;
// When no author style for @viewport is present, and a meta tag for defining
// the viewport is, apply the meta tag viewport instead of the UA styles.
- if (m_viewportArguments.type == ViewportArguments::AuthorStyleSheet)
+ if (m_viewportDescription.type == ViewportDescription::AuthorStyleSheet)
return;
- m_viewportArguments = viewportArguments;
+ m_viewportDescription = viewportDescription;
} else {
// If the legacy viewport tag has higher priority than the cascaded @viewport
// descriptors, use the values from the legacy tag.
- if (!shouldOverrideLegacyViewport(viewportArguments.type))
- m_viewportArguments = m_legacyViewportArguments;
+ if (!shouldOverrideLegacyDescription(viewportDescription.type))
+ m_viewportDescription = m_legacyViewportDescription;
else
- m_viewportArguments = viewportArguments;
+ m_viewportDescription = viewportDescription;
}
- updateViewportArguments();
+ updateViewportDescription();
}
-void Document::updateViewportArguments()
+void Document::updateViewportDescription()
{
- if (page() && page()->mainFrame() == frame()) {
+ if (frame() && frame()->isMainFrame()) {
#ifndef NDEBUG
m_didDispatchViewportPropertiesChanged = true;
#endif
- page()->chrome().dispatchViewportPropertiesDidChange(m_viewportArguments);
+ page()->chrome().dispatchViewportPropertiesDidChange(m_viewportDescription);
}
}
@@ -3115,9 +2970,31 @@ void Document::processReferrerPolicy(const String& policy)
m_referrerPolicy = ReferrerPolicyOrigin;
}
+String Document::outgoingReferrer()
+{
+ // See http://www.whatwg.org/specs/web-apps/current-work/#fetching-resources
+ // for why we walk the parent chain for srcdoc documents.
+ Document* referrerDocument = this;
+ if (Frame* frame = m_frame) {
+ while (frame->document()->isSrcdocDocument()) {
+ frame = frame->tree().parent();
+ // Srcdoc documents cannot be top-level documents, by definition,
+ // because they need to be contained in iframes with the srcdoc.
+ ASSERT(frame);
+ }
+ referrerDocument = frame->document();
+ }
+ return referrerDocument->m_url.strippedForUseAsReferrer();
+}
+
+String Document::outgoingOrigin() const
+{
+ return securityOrigin()->toString();
+}
+
MouseEventWithHitTestResults Document::prepareMouseEvent(const HitTestRequest& request, const LayoutPoint& documentPoint, const PlatformMouseEvent& event)
{
- ASSERT(!renderer() || renderer()->isRenderView());
+ ASSERT(!renderView() || renderView()->isRenderView());
// RenderView::hitTest causes a layout, and we don't want to hit that until the first
// layout because until then, there is nothing shown on the screen - the user can't
@@ -3125,7 +3002,7 @@ MouseEventWithHitTestResults Document::prepareMouseEvent(const HitTestRequest& r
// mousemove events before the first layout should not lead to a premature layout()
// happening, which could show a flash of white.
// See also the similar code in EventHandler::hitTestResultAtPoint.
- if (!renderer() || !view() || !view()->didFirstLayout())
+ if (!renderView() || !view() || !view()->didFirstLayout())
return MouseEventWithHitTestResults(event, HitTestResult(LayoutPoint()));
HitTestResult result(documentPoint);
@@ -3165,13 +3042,9 @@ bool Document::childTypeAllowed(NodeType type) const
return false;
}
-bool Document::canReplaceChild(Node* newChild, Node* oldChild)
+bool Document::canReplaceChild(const Node& newChild, const Node& oldChild) const
{
- if (!oldChild)
- // ContainerNode::replaceChild will raise a NotFoundError.
- return true;
-
- if (oldChild->nodeType() == newChild->nodeType())
+ if (oldChild.nodeType() == newChild.nodeType())
return true;
int numDoctypes = 0;
@@ -3196,8 +3069,8 @@ bool Document::canReplaceChild(Node* newChild, Node* oldChild)
}
// Then, see how many doctypes and elements might be added by the new child.
- if (newChild->nodeType() == DOCUMENT_FRAGMENT_NODE) {
- for (Node* c = newChild->firstChild(); c; c = c->nextSibling()) {
+ if (newChild.nodeType() == DOCUMENT_FRAGMENT_NODE) {
+ for (Node* c = newChild.firstChild(); c; c = c->nextSibling()) {
switch (c->nodeType()) {
case ATTRIBUTE_NODE:
case CDATA_SECTION_NODE:
@@ -3220,7 +3093,7 @@ bool Document::canReplaceChild(Node* newChild, Node* oldChild)
}
}
} else {
- switch (newChild->nodeType()) {
+ switch (newChild.nodeType()) {
case ATTRIBUTE_NODE:
case CDATA_SECTION_NODE:
case DOCUMENT_FRAGMENT_NODE:
@@ -3248,11 +3121,29 @@ bool Document::canReplaceChild(Node* newChild, Node* oldChild)
return true;
}
-PassRefPtr<Node> Document::cloneNode(bool /*deep*/)
+PassRefPtr<Node> Document::cloneNode(bool deep)
{
- // Spec says cloning Document nodes is "implementation dependent"
- // so we do not support it...
- return 0;
+ RefPtr<Document> clone = cloneDocumentWithoutChildren();
+ clone->cloneDataFromDocument(*this);
+ if (deep)
+ cloneChildNodes(clone.get());
+ return clone.release();
+}
+
+PassRefPtr<Document> Document::cloneDocumentWithoutChildren()
+{
+ DocumentInit init(url());
+ if (isXHTMLDocument())
+ return createXHTML(init.withRegistrationContext(registrationContext()));
+ return create(init);
+}
+
+void Document::cloneDataFromDocument(const Document& other)
+{
+ setCompatibilityMode(other.compatibilityMode());
+ setEncodingData(other.m_encodingData);
+ setContextFeatures(other.contextFeatures());
+ setSecurityOrigin(other.securityOrigin()->isolatedCopy());
}
StyleSheetList* Document::styleSheets()
@@ -3284,32 +3175,28 @@ void Document::evaluateMediaQueryList()
m_mediaQueryMatcher->styleResolverChanged();
}
-void Document::styleResolverChanged(StyleResolverUpdateType updateType, StyleResolverUpdateMode updateMode)
+void Document::styleResolverChanged(RecalcStyleTime updateTime, StyleResolverUpdateMode updateMode)
{
- // Don't bother updating, since we haven't loaded all our style info yet
- // and haven't calculated the style selector for the first time.
- if (!attached() || (!m_didCalculateStyleResolver && !haveStylesheetsLoaded())) {
- m_styleResolver.clear();
+ // styleResolverChanged() can be invoked during Document destruction.
+ // We just skip that case.
+ if (!m_styleEngine)
return;
- }
- m_didCalculateStyleResolver = true;
- bool needsRecalc = m_styleEngine->updateActiveStyleSheets(updateMode);
-
- if (didLayoutWithPendingStylesheets() && !m_styleEngine->hasPendingSheets()) {
+ StyleResolverChange change = m_styleEngine->resolverChanged(updateTime, updateMode);
+ if (change.needsRepaint()) {
// We need to manually repaint because we avoid doing all repaints in layout or style
// recalc while sheets are still loading to avoid FOUC.
m_pendingSheetLayout = IgnoreLayoutWithPendingSheets;
renderView()->repaintViewAndCompositedLayers();
}
- if (!needsRecalc)
+ if (!change.needsStyleRecalc())
return;
m_evaluateMediaQueriesOnStyleRecalc = true;
setNeedsStyleRecalc();
- if (updateType == RecalcStyleImmediately)
+ if (updateTime == RecalcStyleImmediately)
updateStyleIfNeeded();
}
@@ -3320,10 +3207,10 @@ void Document::notifySeamlessChildDocumentsOfStylesheetUpdate() const
return;
// Seamless child frames are expected to notify their seamless children recursively, so we only do direct children.
- for (Frame* child = frame()->tree()->firstChild(); child; child = child->tree()->nextSibling()) {
+ for (Frame* child = frame()->tree().firstChild(); child; child = child->tree().nextSibling()) {
Document* childDocument = child->document();
if (childDocument->shouldDisplaySeamlesslyWithParent()) {
- ASSERT(&childDocument->seamlessParentIFrame()->document() == this);
+ ASSERT(childDocument->seamlessParentIFrame()->document() == this);
childDocument->seamlessParentUpdatedStylesheets();
}
}
@@ -3349,17 +3236,11 @@ void Document::removeFocusedElementOfSubtree(Node* node, bool amongChildrenOnly)
if (!m_focusedElement)
return;
- Element* focusedElement = node->treeScope().adjustedFocusedElement();
- if (!focusedElement)
+ // We can't be focused if we're not in the document.
+ if (!node->inDocument())
return;
-
- bool nodeInSubtree = false;
- if (amongChildrenOnly)
- nodeInSubtree = focusedElement->isDescendantOf(node);
- else
- nodeInSubtree = (focusedElement == node) || focusedElement->isDescendantOf(node);
-
- if (nodeInSubtree)
+ bool contains = node->containsIncludingShadowDOM(m_focusedElement.get());
+ if (contains && (m_focusedElement != node || !amongChildrenOnly))
setFocusedElement(0);
}
@@ -3382,7 +3263,7 @@ void Document::hoveredNodeDetached(Node* node)
return;
if (frame())
- frame()->eventHandler()->scheduleHoverStateUpdate();
+ frame()->eventHandler().scheduleHoverStateUpdate();
}
void Document::activeChainNodeDetached(Node* node)
@@ -3416,7 +3297,7 @@ bool Document::setFocusedElement(PassRefPtr<Element> prpNewFocusedElement, Focus
RefPtr<Element> newFocusedElement = prpNewFocusedElement;
// Make sure newFocusedNode is actually in this document
- if (newFocusedElement && (&newFocusedElement->document() != this))
+ if (newFocusedElement && (newFocusedElement->document() != this))
return true;
if (NodeChildRemovalTracker::isBeingRemoved(newFocusedElement.get()))
@@ -3451,10 +3332,10 @@ bool Document::setFocusedElement(PassRefPtr<Element> prpNewFocusedElement, Focus
newFocusedElement = 0;
}
- oldFocusedElement->dispatchFocusOutEvent(eventNames().focusoutEvent, newFocusedElement.get()); // DOM level 3 name for the bubbling blur event.
+ oldFocusedElement->dispatchFocusOutEvent(EventTypeNames::focusout, newFocusedElement.get()); // DOM level 3 name for the bubbling blur event.
// FIXME: We should remove firing DOMFocusOutEvent event when we are sure no content depends
// on it, probably when <rdar://problem/8503958> is resolved.
- oldFocusedElement->dispatchFocusOutEvent(eventNames().DOMFocusOutEvent, newFocusedElement.get()); // DOM level 2 name for compatibility.
+ oldFocusedElement->dispatchFocusOutEvent(EventTypeNames::DOMFocusOut, newFocusedElement.get()); // DOM level 2 name for compatibility.
if (m_focusedElement) {
// handler shifted focus
@@ -3462,11 +3343,8 @@ bool Document::setFocusedElement(PassRefPtr<Element> prpNewFocusedElement, Focus
newFocusedElement = 0;
}
- if (oldFocusedElement->isRootEditableElement())
- frame()->editor().didEndEditing();
-
if (view()) {
- Widget* oldWidget = widgetForElement(oldFocusedElement.get());
+ Widget* oldWidget = widgetForElement(*oldFocusedElement);
if (oldWidget)
oldWidget->setFocus(false);
else
@@ -3475,7 +3353,7 @@ bool Document::setFocusedElement(PassRefPtr<Element> prpNewFocusedElement, Focus
}
if (newFocusedElement && newFocusedElement->isFocusable()) {
- if (newFocusedElement->isRootEditableElement() && !acceptsEditingFocus(newFocusedElement.get())) {
+ if (newFocusedElement->isRootEditableElement() && !acceptsEditingFocus(*newFocusedElement)) {
// delegate blocks focus change
focusChangeBlocked = true;
goto SetFocusedElementDone;
@@ -3492,7 +3370,7 @@ bool Document::setFocusedElement(PassRefPtr<Element> prpNewFocusedElement, Focus
goto SetFocusedElementDone;
}
- m_focusedElement->dispatchFocusInEvent(eventNames().focusinEvent, oldFocusedElement.get()); // DOM level 3 bubbling focus event.
+ m_focusedElement->dispatchFocusInEvent(EventTypeNames::focusin, oldFocusedElement.get()); // DOM level 3 bubbling focus event.
if (m_focusedElement != newFocusedElement) {
// handler shifted focus
@@ -3502,7 +3380,7 @@ bool Document::setFocusedElement(PassRefPtr<Element> prpNewFocusedElement, Focus
// FIXME: We should remove firing DOMFocusInEvent event when we are sure no content depends
// on it, probably when <rdar://problem/8503958> is m.
- m_focusedElement->dispatchFocusInEvent(eventNames().DOMFocusInEvent, oldFocusedElement.get()); // DOM level 2 for compatibility.
+ m_focusedElement->dispatchFocusInEvent(EventTypeNames::DOMFocusIn, oldFocusedElement.get()); // DOM level 2 for compatibility.
if (m_focusedElement != newFocusedElement) {
// handler shifted focus
@@ -3512,19 +3390,19 @@ bool Document::setFocusedElement(PassRefPtr<Element> prpNewFocusedElement, Focus
m_focusedElement->setFocus(true);
if (m_focusedElement->isRootEditableElement())
- frame()->editor().didBeginEditing(m_focusedElement.get());
+ frame()->spellChecker().didBeginEditing(m_focusedElement.get());
// eww, I suck. set the qt focus correctly
// ### find a better place in the code for this
if (view()) {
- Widget* focusWidget = widgetForElement(m_focusedElement.get());
+ Widget* focusWidget = widgetForElement(*m_focusedElement);
if (focusWidget) {
// Make sure a widget has the right size before giving it focus.
// Otherwise, we are testing edge cases of the Widget code.
// Specifically, in WebCore this does not work well for text fields.
updateLayout();
// Re-get the widget in case updating the layout changed things.
- focusWidget = widgetForElement(m_focusedElement.get());
+ focusWidget = widgetForElement(*m_focusedElement);
}
if (focusWidget)
focusWidget->setFocus(true);
@@ -3623,19 +3501,19 @@ void Document::nodeChildrenWillBeRemoved(ContainerNode* container)
HashSet<NodeIterator*>::const_iterator nodeIteratorsEnd = m_nodeIterators.end();
for (HashSet<NodeIterator*>::const_iterator it = m_nodeIterators.begin(); it != nodeIteratorsEnd; ++it) {
for (Node* n = container->firstChild(); n; n = n->nextSibling())
- (*it)->nodeWillBeRemoved(n);
+ (*it)->nodeWillBeRemoved(*n);
}
if (Frame* frame = this->frame()) {
for (Node* n = container->firstChild(); n; n = n->nextSibling()) {
- frame->eventHandler()->nodeWillBeRemoved(n);
- frame->selection().nodeWillBeRemoved(n);
- frame->page()->dragCaretController().nodeWillBeRemoved(n);
+ frame->eventHandler().nodeWillBeRemoved(*n);
+ frame->selection().nodeWillBeRemoved(*n);
+ frame->page()->dragCaretController().nodeWillBeRemoved(*n);
}
}
}
-void Document::nodeWillBeRemoved(Node* n)
+void Document::nodeWillBeRemoved(Node& n)
{
HashSet<NodeIterator*>::const_iterator nodeIteratorsEnd = m_nodeIterators.end();
for (HashSet<NodeIterator*>::const_iterator it = m_nodeIterators.begin(); it != nodeIteratorsEnd; ++it)
@@ -3648,7 +3526,7 @@ void Document::nodeWillBeRemoved(Node* n)
}
if (Frame* frame = this->frame()) {
- frame->eventHandler()->nodeWillBeRemoved(n);
+ frame->eventHandler().nodeWillBeRemoved(n);
frame->selection().nodeWillBeRemoved(n);
frame->page()->dragCaretController().nodeWillBeRemoved(n);
}
@@ -3724,46 +3602,43 @@ EventListener* Document::getWindowAttributeEventListener(const AtomicString& eve
return domWindow->getAttributeEventListener(eventType, isolatedWorld);
}
-void Document::dispatchWindowEvent(PassRefPtr<Event> event, PassRefPtr<EventTarget> target)
+EventQueue* Document::eventQueue() const
{
- ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
- DOMWindow* domWindow = this->domWindow();
- if (!domWindow)
- return;
- domWindow->dispatchEvent(event, target);
+ if (!m_domWindow)
+ return 0;
+ return m_domWindow->eventQueue();
}
-void Document::enqueueWindowEvent(PassRefPtr<Event> event)
+void Document::enqueueAnimationFrameEvent(PassRefPtr<Event> event)
{
- event->setTarget(domWindow());
- m_eventQueue->enqueueEvent(event);
+ ensureScriptedAnimationController().enqueueEvent(event);
}
-void Document::enqueueDocumentEvent(PassRefPtr<Event> event)
+void Document::enqueueScrollEventForNode(Node* target)
{
- event->setTarget(this);
- m_eventQueue->enqueueEvent(event);
+ // Per the W3C CSSOM View Module only scroll events fired at the document should bubble.
+ RefPtr<Event> scrollEvent = target->isDocumentNode() ? Event::createBubble(EventTypeNames::scroll) : Event::create(EventTypeNames::scroll);
+ scrollEvent->setTarget(target);
+ ensureScriptedAnimationController().enqueuePerFrameEvent(scrollEvent.release());
}
-PassRefPtr<Event> Document::createEvent(const String& eventType, ExceptionState& es)
+void Document::enqueueResizeEvent()
+{
+ RefPtr<Event> event = Event::create(EventTypeNames::resize);
+ event->setTarget(domWindow());
+ ensureScriptedAnimationController().enqueuePerFrameEvent(event.release());
+}
+
+PassRefPtr<Event> Document::createEvent(const String& eventType, ExceptionState& exceptionState)
{
RefPtr<Event> event = EventFactory::create(eventType);
if (event)
return event.release();
- es.throwDOMException(NotSupportedError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
return 0;
}
-void Document::dispatchWindowLoadEvent()
-{
- ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
- DOMWindow* domWindow = this->domWindow();
- if (!domWindow)
- return;
- domWindow->dispatchLoadEvent();
-}
-
void Document::addMutationEventListenerTypeIfEnabled(ListenerType listenerType)
{
if (ContextFeatures::mutationEventsEnabled(this))
@@ -3772,38 +3647,46 @@ void Document::addMutationEventListenerTypeIfEnabled(ListenerType listenerType)
void Document::addListenerTypeIfNeeded(const AtomicString& eventType)
{
- if (eventType == eventNames().DOMSubtreeModifiedEvent) {
- UseCounter::count(this, UseCounter::DOMSubtreeModifiedEvent);
+ if (eventType == EventTypeNames::DOMSubtreeModified) {
+ UseCounter::count(*this, UseCounter::DOMSubtreeModifiedEvent);
addMutationEventListenerTypeIfEnabled(DOMSUBTREEMODIFIED_LISTENER);
- } else if (eventType == eventNames().DOMNodeInsertedEvent) {
- UseCounter::count(this, UseCounter::DOMNodeInsertedEvent);
+ } else if (eventType == EventTypeNames::DOMNodeInserted) {
+ UseCounter::count(*this, UseCounter::DOMNodeInsertedEvent);
addMutationEventListenerTypeIfEnabled(DOMNODEINSERTED_LISTENER);
- } else if (eventType == eventNames().DOMNodeRemovedEvent) {
- UseCounter::count(this, UseCounter::DOMNodeRemovedEvent);
+ } else if (eventType == EventTypeNames::DOMNodeRemoved) {
+ UseCounter::count(*this, UseCounter::DOMNodeRemovedEvent);
addMutationEventListenerTypeIfEnabled(DOMNODEREMOVED_LISTENER);
- } else if (eventType == eventNames().DOMNodeRemovedFromDocumentEvent) {
- UseCounter::count(this, UseCounter::DOMNodeRemovedFromDocumentEvent);
+ } else if (eventType == EventTypeNames::DOMNodeRemovedFromDocument) {
+ UseCounter::count(*this, UseCounter::DOMNodeRemovedFromDocumentEvent);
addMutationEventListenerTypeIfEnabled(DOMNODEREMOVEDFROMDOCUMENT_LISTENER);
- } else if (eventType == eventNames().DOMNodeInsertedIntoDocumentEvent) {
- UseCounter::count(this, UseCounter::DOMNodeInsertedIntoDocumentEvent);
+ } else if (eventType == EventTypeNames::DOMNodeInsertedIntoDocument) {
+ UseCounter::count(*this, UseCounter::DOMNodeInsertedIntoDocumentEvent);
addMutationEventListenerTypeIfEnabled(DOMNODEINSERTEDINTODOCUMENT_LISTENER);
- } else if (eventType == eventNames().DOMCharacterDataModifiedEvent) {
- UseCounter::count(this, UseCounter::DOMCharacterDataModifiedEvent);
+ } else if (eventType == EventTypeNames::DOMCharacterDataModified) {
+ UseCounter::count(*this, UseCounter::DOMCharacterDataModifiedEvent);
addMutationEventListenerTypeIfEnabled(DOMCHARACTERDATAMODIFIED_LISTENER);
- } else if (eventType == eventNames().overflowchangedEvent) {
+ } else if (eventType == EventTypeNames::overflowchanged) {
+ UseCounter::count(*this, UseCounter::OverflowChangedEvent);
addListenerType(OVERFLOWCHANGED_LISTENER);
- } else if (eventType == eventNames().webkitAnimationStartEvent || (RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled() && eventType == eventNames().animationstartEvent)) {
+ } else if (eventType == EventTypeNames::webkitAnimationStart || (RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled() && eventType == EventTypeNames::animationstart)) {
addListenerType(ANIMATIONSTART_LISTENER);
- } else if (eventType == eventNames().webkitAnimationEndEvent || (RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled() && eventType == eventNames().animationendEvent)) {
+ } else if (eventType == EventTypeNames::webkitAnimationEnd || (RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled() && eventType == EventTypeNames::animationend)) {
addListenerType(ANIMATIONEND_LISTENER);
- } else if (eventType == eventNames().webkitAnimationIterationEvent || (RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled() && eventType == eventNames().animationiterationEvent)) {
+ } else if (eventType == EventTypeNames::webkitAnimationIteration || (RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled() && eventType == EventTypeNames::animationiteration)) {
addListenerType(ANIMATIONITERATION_LISTENER);
- } else if (eventType == eventNames().webkitTransitionEndEvent || eventType == eventNames().transitionendEvent) {
+ } else if (eventType == EventTypeNames::webkitTransitionEnd || eventType == EventTypeNames::transitionend) {
addListenerType(TRANSITIONEND_LISTENER);
- } else if (eventType == eventNames().beforeloadEvent) {
+ } else if (eventType == EventTypeNames::beforeload) {
+ if (m_frame && m_frame->script().shouldBypassMainWorldContentSecurityPolicy()) {
+ UseCounter::count(*this, UseCounter::BeforeLoadEventInIsolatedWorld);
+ } else {
+ UseCounter::count(*this, UseCounter::BeforeLoadEvent);
+ }
addListenerType(BEFORELOAD_LISTENER);
- } else if (eventType == eventNames().scrollEvent) {
+ } else if (eventType == EventTypeNames::scroll) {
addListenerType(SCROLL_LISTENER);
+ } else if (eventType == EventTypeNames::DOMFocusIn || eventType == EventTypeNames::DOMFocusOut) {
+ UseCounter::count(*this, UseCounter::DOMFocusInOutEvent);
}
}
@@ -3819,9 +3702,9 @@ HTMLFrameOwnerElement* Document::ownerElement() const
return frame()->ownerElement();
}
-String Document::cookie(ExceptionState& es) const
+String Document::cookie(ExceptionState& exceptionState) const
{
- if (page() && !page()->settings().cookieEnabled())
+ if (settings() && !settings()->cookieEnabled())
return String();
// FIXME: The HTML5 DOM spec states that this attribute can raise an
@@ -3829,13 +3712,12 @@ String Document::cookie(ExceptionState& es) const
// browsing context.
if (!securityOrigin()->canAccessCookies()) {
- String accessDeniedMessage = "Access to 'cookie' is denied for this document.";
if (isSandboxed(SandboxOrigin))
- es.throwSecurityError(accessDeniedMessage + " The document is sandboxed and lacks the 'allow-same-origin' flag.");
+ exceptionState.throwSecurityError("The document is sandboxed and lacks the 'allow-same-origin' flag.");
else if (url().protocolIs("data"))
- es.throwSecurityError(accessDeniedMessage + " Cookies are disabled inside 'data:' URLs.");
+ exceptionState.throwSecurityError("Cookies are disabled inside 'data:' URLs.");
else
- es.throwSecurityError(accessDeniedMessage);
+ exceptionState.throwSecurityError("Access is denied for this document.");
return String();
}
@@ -3846,9 +3728,9 @@ String Document::cookie(ExceptionState& es) const
return cookies(this, cookieURL);
}
-void Document::setCookie(const String& value, ExceptionState& es)
+void Document::setCookie(const String& value, ExceptionState& exceptionState)
{
- if (page() && !page()->settings().cookieEnabled())
+ if (settings() && !settings()->cookieEnabled())
return;
// FIXME: The HTML5 DOM spec states that this attribute can raise an
@@ -3856,13 +3738,12 @@ void Document::setCookie(const String& value, ExceptionState& es)
// browsing context.
if (!securityOrigin()->canAccessCookies()) {
- String accessDeniedMessage = "Access to 'cookie' is denied for this document.";
if (isSandboxed(SandboxOrigin))
- es.throwSecurityError(accessDeniedMessage + " The document is sandboxed and lacks the 'allow-same-origin' flag.");
+ exceptionState.throwSecurityError("The document is sandboxed and lacks the 'allow-same-origin' flag.");
else if (url().protocolIs("data"))
- es.throwSecurityError(accessDeniedMessage + " Cookies are disabled inside 'data:' URLs.");
+ exceptionState.throwSecurityError("Cookies are disabled inside 'data:' URLs.");
else
- es.throwSecurityError(accessDeniedMessage);
+ exceptionState.throwSecurityError("Access is denied for this document.");
return;
}
@@ -3873,11 +3754,11 @@ void Document::setCookie(const String& value, ExceptionState& es)
setCookies(this, cookieURL, value);
}
-String Document::referrer() const
+const AtomicString& Document::referrer() const
{
if (loader())
return loader()->request().httpReferrer();
- return String();
+ return nullAtom;
}
String Document::domain() const
@@ -3885,56 +3766,39 @@ String Document::domain() const
return securityOrigin()->domain();
}
-void Document::setDomain(const String& newDomain, ExceptionState& es)
+void Document::setDomain(const String& newDomain, ExceptionState& exceptionState)
{
- if (SchemeRegistry::isDomainRelaxationForbiddenForURLScheme(securityOrigin()->protocol())) {
- es.throwSecurityError(ExceptionMessages::failedToSet("domain", "Document", "assignment is forbidden for the '" + securityOrigin()->protocol() + "' scheme."));
+ if (isSandboxed(SandboxDocumentDomain)) {
+ exceptionState.throwSecurityError("Assignment is forbidden for sandboxed iframes.");
return;
}
- // Both NS and IE specify that changing the domain is only allowed when
- // the new domain is a suffix of the old domain.
-
- // If the new domain is the same as the old domain, still call
- // securityOrigin()->setDomainForDOM. This will change the
- // security check behavior. For example, if a page loaded on port 8000
- // assigns its current domain using document.domain, the page will
- // allow other pages loaded on different ports in the same domain that
- // have also assigned to access this page.
- if (equalIgnoringCase(domain(), newDomain)) {
- securityOrigin()->setDomainFromDOM(newDomain);
- if (m_frame)
- m_frame->script()->updateSecurityOrigin();
+ if (SchemeRegistry::isDomainRelaxationForbiddenForURLScheme(securityOrigin()->protocol())) {
+ exceptionState.throwSecurityError("Assignment is forbidden for the '" + securityOrigin()->protocol() + "' scheme.");
return;
}
- int oldLength = domain().length();
- int newLength = newDomain.length();
- String exceptionMessage = ExceptionMessages::failedToSet("domain", "Document", "'" + newDomain + "' is not a suffix of '" + domain() + "'.");
- // e.g. newDomain = subdomain.www.example.com (25) and domain() = www.example.com (15)
- if (newLength >= oldLength) {
- es.throwSecurityError(exceptionMessage);
+ if (newDomain.isEmpty()) {
+ exceptionState.throwSecurityError("'" + newDomain + "' is an empty domain.");
return;
}
- String test = domain();
- // Check that it's a complete suffix, not e.g. "ample.com"
- if (test[oldLength - newLength - 1] != '.') {
- es.throwSecurityError(exceptionMessage);
+ OriginAccessEntry::IPAddressSetting ipAddressSetting = settings() && settings()->treatIPAddressAsDomain() ? OriginAccessEntry::TreatIPAddressAsDomain : OriginAccessEntry::TreatIPAddressAsIPAddress;
+ OriginAccessEntry accessEntry(securityOrigin()->protocol(), newDomain, OriginAccessEntry::AllowSubdomains, ipAddressSetting);
+ OriginAccessEntry::MatchResult result = accessEntry.matchesOrigin(*securityOrigin());
+ if (result == OriginAccessEntry::DoesNotMatchOrigin) {
+ exceptionState.throwSecurityError("'" + newDomain + "' is not a suffix of '" + domain() + "'.");
return;
}
- // Now test is "example.com" from domain()
- // and we check that it's the same thing as newDomain
- test.remove(0, oldLength - newLength);
- if (test != newDomain) {
- es.throwSecurityError(exceptionMessage);
+ if (result == OriginAccessEntry::MatchesOriginButIsPublicSuffix) {
+ exceptionState.throwSecurityError("'" + newDomain + "' is a top-level domain.");
return;
}
securityOrigin()->setDomainFromDOM(newDomain);
if (m_frame)
- m_frame->script()->updateSecurityOrigin();
+ m_frame->script().updateSecurityOrigin();
}
// http://www.whatwg.org/specs/web-apps/current-work/#dom-document-lastmodified
@@ -3943,12 +3807,12 @@ String Document::lastModified() const
DateComponents date;
bool foundDate = false;
if (m_frame) {
- String httpLastModified;
- if (DocumentLoader* documentLoader = loader())
- httpLastModified = documentLoader->response().httpHeaderField("Last-Modified");
- if (!httpLastModified.isEmpty()) {
- date.setMillisecondsSinceEpochForDateTime(parseDate(httpLastModified));
- foundDate = true;
+ if (DocumentLoader* documentLoader = loader()) {
+ const AtomicString& httpLastModified = documentLoader->response().httpHeaderField("Last-Modified");
+ if (!httpLastModified.isEmpty()) {
+ date.setMillisecondsSinceEpochForDateTime(parseDate(httpLastModified));
+ foundDate = true;
+ }
}
}
// FIXME: If this document came from the file system, the HTML5
@@ -4035,7 +3899,7 @@ bool Document::isValidName(const String& name)
}
template<typename CharType>
-static bool parseQualifiedNameInternal(const String& qualifiedName, const CharType* characters, unsigned length, String& prefix, String& localName, ExceptionState& es)
+static bool parseQualifiedNameInternal(const AtomicString& qualifiedName, const CharType* characters, unsigned length, AtomicString& prefix, AtomicString& localName, ExceptionState& exceptionState)
{
bool nameStart = true;
bool sawColon = false;
@@ -4046,7 +3910,7 @@ static bool parseQualifiedNameInternal(const String& qualifiedName, const CharTy
U16_NEXT(characters, i, length, c)
if (c == ':') {
if (sawColon) {
- es.throwDOMException(NamespaceError);
+ exceptionState.throwUninformativeAndGenericDOMException(NamespaceError);
return false; // multiple colons: not allowed
}
nameStart = true;
@@ -4054,63 +3918,55 @@ static bool parseQualifiedNameInternal(const String& qualifiedName, const CharTy
colonPos = i - 1;
} else if (nameStart) {
if (!isValidNameStart(c)) {
- es.throwDOMException(InvalidCharacterError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidCharacterError);
return false;
}
nameStart = false;
} else {
if (!isValidNamePart(c)) {
- es.throwDOMException(InvalidCharacterError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidCharacterError);
return false;
}
}
}
if (!sawColon) {
- prefix = String();
+ prefix = nullAtom;
localName = qualifiedName;
} else {
- prefix = qualifiedName.substring(0, colonPos);
+ prefix = AtomicString(characters, colonPos);
if (prefix.isEmpty()) {
- es.throwDOMException(NamespaceError);
+ exceptionState.throwUninformativeAndGenericDOMException(NamespaceError);
return false;
}
- localName = qualifiedName.substring(colonPos + 1);
+ int prefixStart = colonPos + 1;
+ localName = AtomicString(characters + prefixStart, length - prefixStart);
}
if (localName.isEmpty()) {
- es.throwDOMException(NamespaceError);
+ exceptionState.throwUninformativeAndGenericDOMException(NamespaceError);
return false;
}
return true;
}
-bool Document::parseQualifiedName(const String& qualifiedName, String& prefix, String& localName, ExceptionState& es)
+bool Document::parseQualifiedName(const AtomicString& qualifiedName, AtomicString& prefix, AtomicString& localName, ExceptionState& exceptionState)
{
unsigned length = qualifiedName.length();
if (!length) {
- es.throwDOMException(InvalidCharacterError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidCharacterError);
return false;
}
if (qualifiedName.is8Bit())
- return parseQualifiedNameInternal(qualifiedName, qualifiedName.characters8(), length, prefix, localName, es);
- return parseQualifiedNameInternal(qualifiedName, qualifiedName.characters16(), length, prefix, localName, es);
-}
-
-void Document::setDecoder(PassRefPtr<TextResourceDecoder> decoder)
-{
- m_decoder = decoder;
- setEncoding(m_decoder ? m_decoder->encoding() : WTF::TextEncoding());
+ return parseQualifiedNameInternal(qualifiedName, qualifiedName.characters8(), length, prefix, localName, exceptionState);
+ return parseQualifiedNameInternal(qualifiedName, qualifiedName.characters16(), length, prefix, localName, exceptionState);
}
-void Document::setEncoding(const WTF::TextEncoding& encoding)
+void Document::setEncodingData(const DocumentEncodingData& newData)
{
- if (m_encoding == encoding)
- return;
-
// It's possible for the encoding of the document to change while we're decoding
// data. That can only occur while we're processing the <head> portion of the
// document. There isn't much user-visible content in the <head>, but there is
@@ -4118,17 +3974,18 @@ void Document::setEncoding(const WTF::TextEncoding& encoding)
// document's title so that the user doesn't see an incorrectly decoded title
// in the title bar.
if (m_titleElement
+ && encoding() != newData.encoding
&& !m_titleElement->firstElementChild()
- && m_encoding == Latin1Encoding()
+ && encoding() == Latin1Encoding()
&& m_titleElement->textContent().containsOnlyLatin1()) {
CString originalBytes = m_titleElement->textContent().latin1();
- OwnPtr<TextCodec> codec = newTextCodec(encoding);
+ OwnPtr<TextCodec> codec = newTextCodec(newData.encoding);
String correctlyDecodedTitle = codec->decode(originalBytes.data(), originalBytes.length(), true);
- m_titleElement->setTextContent(correctlyDecodedTitle, IGNORE_EXCEPTION);
+ m_titleElement->setTextContent(correctlyDecodedTitle);
}
- m_encoding = encoding;
+ m_encodingData = newData;
}
KURL Document::completeURL(const String& url, const KURL& baseURLOverride) const
@@ -4138,10 +3995,15 @@ KURL Document::completeURL(const String& url, const KURL& baseURLOverride) const
// See also [CSS]StyleSheet::completeURL(const String&)
if (url.isNull())
return KURL();
- const KURL& baseURL = ((baseURLOverride.isEmpty() || baseURLOverride == blankURL()) && parentDocument()) ? parentDocument()->baseURL() : baseURLOverride;
- if (!m_decoder)
+ const KURL* baseURLFromParent = 0;
+ if (baseURLOverride.isEmpty() || baseURLOverride == blankURL()) {
+ if (Document* parent = parentDocument())
+ baseURLFromParent = &parent->baseURL();
+ }
+ const KURL& baseURL = baseURLFromParent ? *baseURLFromParent : baseURLOverride;
+ if (!encoding().isValid())
return KURL(baseURL, url);
- return KURL(baseURL, url, m_decoder->encoding());
+ return KURL(baseURL, url, encoding());
}
KURL Document::completeURL(const String& url) const
@@ -4149,12 +4011,6 @@ KURL Document::completeURL(const String& url) const
return completeURL(url, m_baseURL);
}
-void Document::documentWillBecomeInactive()
-{
- if (renderer())
- renderView()->setIsInWindow(false);
-}
-
// Support for Javascript execCommand, and related methods
static Editor::Command command(Document* document, const String& commandName, bool userInterface = false)
@@ -4199,15 +4055,15 @@ String Document::queryCommandValue(const String& commandName)
KURL Document::openSearchDescriptionURL()
{
- static const char* const openSearchMIMEType = "application/opensearchdescription+xml";
- static const char* const openSearchRelation = "search";
+ static const char openSearchMIMEType[] = "application/opensearchdescription+xml";
+ static const char openSearchRelation[] = "search";
// FIXME: Why do only top-level frames have openSearchDescriptionURLs?
- if (!frame() || frame()->tree()->parent())
+ if (!frame() || frame()->tree().parent())
return KURL();
// FIXME: Why do we need to wait for FrameStateComplete?
- if (frame()->loader()->state() != FrameStateComplete)
+ if (frame()->loader().state() != FrameStateComplete)
return KURL();
if (!head())
@@ -4243,9 +4099,9 @@ void Document::popCurrentScript()
void Document::applyXSLTransform(ProcessingInstruction* pi)
{
ASSERT(!pi->isLoading());
- UseCounter::count(this, UseCounter::XSLProcessingInstruction);
+ UseCounter::count(*this, UseCounter::XSLProcessingInstruction);
RefPtr<XSLTProcessor> processor = XSLTProcessor::create();
- processor->setXSLStyleSheet(static_cast<XSLStyleSheet*>(pi->sheet()));
+ processor->setXSLStyleSheet(toXSLStyleSheet(pi->sheet()));
String resultMIMEType;
String newSource;
String resultEncoding;
@@ -4265,7 +4121,7 @@ void Document::setTransformSource(PassOwnPtr<TransformSource> source)
void Document::setDesignMode(InheritedBool value)
{
m_designMode = value;
- for (Frame* frame = m_frame; frame && frame->document(); frame = frame->tree()->traverseNext(m_frame))
+ for (Frame* frame = m_frame; frame && frame->document(); frame = frame->tree().traverseNext(m_frame))
frame->document()->setNeedsStyleRecalc();
}
@@ -4287,7 +4143,7 @@ Document* Document::parentDocument() const
{
if (!m_frame)
return 0;
- Frame* parent = m_frame->tree()->parent();
+ Frame* parent = m_frame->tree().parent();
if (!parent)
return 0;
return parent->document();
@@ -4312,21 +4168,21 @@ WeakPtr<Document> Document::contextDocument()
return WeakPtr<Document>(0);
}
-PassRefPtr<Attr> Document::createAttribute(const String& name, ExceptionState& es)
+PassRefPtr<Attr> Document::createAttribute(const AtomicString& name, ExceptionState& exceptionState)
{
- return createAttributeNS(String(), name, es, true);
+ return createAttributeNS(nullAtom, name, exceptionState, true);
}
-PassRefPtr<Attr> Document::createAttributeNS(const String& namespaceURI, const String& qualifiedName, ExceptionState& es, bool shouldIgnoreNamespaceChecks)
+PassRefPtr<Attr> Document::createAttributeNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionState& exceptionState, bool shouldIgnoreNamespaceChecks)
{
- String prefix, localName;
- if (!parseQualifiedName(qualifiedName, prefix, localName, es))
+ AtomicString prefix, localName;
+ if (!parseQualifiedName(qualifiedName, prefix, localName, exceptionState))
return 0;
QualifiedName qName(prefix, localName, namespaceURI);
if (!shouldIgnoreNamespaceChecks && !hasValidNamespaceForAttributes(qName)) {
- es.throwDOMException(NamespaceError);
+ exceptionState.throwUninformativeAndGenericDOMException(NamespaceError);
return 0;
}
@@ -4352,7 +4208,7 @@ bool Document::hasSVGRootNode() const
PassRefPtr<HTMLCollection> Document::ensureCachedCollection(CollectionType type)
{
- return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLCollection>(this, type);
+ return ensureRareData().ensureNodeLists().addCacheWithAtomicName<HTMLCollection>(this, type);
}
PassRefPtr<HTMLCollection> Document::images()
@@ -4370,12 +4226,6 @@ PassRefPtr<HTMLCollection> Document::embeds()
return ensureCachedCollection(DocEmbeds);
}
-PassRefPtr<HTMLCollection> Document::plugins()
-{
- // This is an alias for embeds() required for the JS DOM bindings.
- return ensureCachedCollection(DocEmbeds);
-}
-
PassRefPtr<HTMLCollection> Document::scripts()
{
return ensureCachedCollection(DocScripts);
@@ -4398,23 +4248,23 @@ PassRefPtr<HTMLCollection> Document::anchors()
PassRefPtr<HTMLCollection> Document::allForBinding()
{
- UseCounter::count(this, UseCounter::DocumentAll);
+ UseCounter::count(*this, UseCounter::DocumentAll);
return all();
}
PassRefPtr<HTMLCollection> Document::all()
{
- return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLAllCollection>(this, DocAll);
+ return ensureRareData().ensureNodeLists().addCacheWithAtomicName<HTMLAllCollection>(this, DocAll);
}
PassRefPtr<HTMLCollection> Document::windowNamedItems(const AtomicString& name)
{
- return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLNameCollection>(this, WindowNamedItems, name);
+ return ensureRareData().ensureNodeLists().addCacheWithAtomicName<HTMLNameCollection>(this, WindowNamedItems, name);
}
PassRefPtr<HTMLCollection> Document::documentNamedItems(const AtomicString& name)
{
- return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLNameCollection>(this, DocumentNamedItems, name);
+ return ensureRareData().ensureNodeLists().addCacheWithAtomicName<HTMLNameCollection>(this, DocumentNamedItems, name);
}
void Document::finishedParsing()
@@ -4424,7 +4274,7 @@ void Document::finishedParsing()
setParsing(false);
if (!m_documentTiming.domContentLoadedEventStart)
m_documentTiming.domContentLoadedEventStart = monotonicallyIncreasingTime();
- dispatchEvent(Event::createBubble(eventNames().DOMContentLoadedEvent));
+ dispatchEvent(Event::createBubble(EventTypeNames::DOMContentLoaded));
if (!m_documentTiming.domContentLoadedEventEnd)
m_documentTiming.domContentLoadedEventEnd = monotonicallyIncreasingTime();
@@ -4443,7 +4293,7 @@ void Document::finishedParsing()
// See https://bugs.webkit.org/show_bug.cgi?id=36864 starting around comment 35.
updateStyleIfNeeded();
- f->loader()->finishedParsing();
+ f->loader().finishedParsing();
InspectorInstrumentation::domContentLoadedEventFired(f.get());
}
@@ -4467,41 +4317,17 @@ void Document::sharedObjectPoolClearTimerFired(Timer<Document>*)
m_sharedObjectPool.clear();
}
-void Document::didAccessStyleResolver()
-{
- static const int timeBeforeThrowingAwayStyleResolverAfterLastUseInSeconds = 60;
- static const int holdOffTimeBeforeReschedulingTimerInSeconds = 5;
-
- double currentTime = WTF::currentTime();
-
- if (currentTime > m_lastStyleResolverAccessTime + holdOffTimeBeforeReschedulingTimerInSeconds) {
- m_styleResolverThrowawayTimer.startOneShot(timeBeforeThrowingAwayStyleResolverAfterLastUseInSeconds);
- m_lastStyleResolverAccessTime = currentTime;
- }
-}
-
-void Document::styleResolverThrowawayTimerFired(Timer<Document>*)
-{
- ASSERT(!m_inStyleRecalc);
- clearStyleResolver();
-}
-
-const Vector<IconURL>& Document::shortcutIconURLs()
-{
- // Include any icons where type = link, rel = "shortcut icon".
- return iconURLs(Favicon);
-}
-
-const Vector<IconURL>& Document::iconURLs(int iconTypesMask)
+Vector<IconURL> Document::iconURLs(int iconTypesMask)
{
- m_iconURLs.clear();
+ IconURL firstFavicon;
+ IconURL firstTouchIcon;
+ IconURL firstTouchPrecomposedIcon;
+ Vector<IconURL> secondaryIcons;
- if (!head() || !(head()->children()))
- return m_iconURLs;
-
- RefPtr<HTMLCollection> children = head()->children();
- unsigned int length = children->length();
- for (unsigned int i = 0; i < length; ++i) {
+ // Start from the last child node so that icons seen later take precedence as required by the spec.
+ RefPtr<HTMLCollection> children = head() ? head()->children() : 0;
+ unsigned length = children ? children->length() : 0;
+ for (unsigned i = 0; i < length; i++) {
Node* child = children->item(i);
if (!child->hasTagName(linkTag))
continue;
@@ -4510,13 +4336,42 @@ const Vector<IconURL>& Document::iconURLs(int iconTypesMask)
continue;
if (linkElement->href().isEmpty())
continue;
+#if !ENABLE(TOUCH_ICON_LOADING)
+ if (linkElement->iconType() != Favicon)
+ continue;
+#endif
- // Put it at the front to ensure that icons seen later take precedence as required by the spec.
IconURL newURL(linkElement->href(), linkElement->iconSizes(), linkElement->type(), linkElement->iconType());
- m_iconURLs.prepend(newURL);
+ if (linkElement->iconType() == Favicon) {
+ if (firstFavicon.m_iconType != InvalidIcon)
+ secondaryIcons.append(firstFavicon);
+ firstFavicon = newURL;
+ } else if (linkElement->iconType() == TouchIcon) {
+ if (firstTouchIcon.m_iconType != InvalidIcon)
+ secondaryIcons.append(firstTouchIcon);
+ firstTouchIcon = newURL;
+ } else if (linkElement->iconType() == TouchPrecomposedIcon) {
+ if (firstTouchPrecomposedIcon.m_iconType != InvalidIcon)
+ secondaryIcons.append(firstTouchPrecomposedIcon);
+ firstTouchPrecomposedIcon = newURL;
+ } else {
+ ASSERT_NOT_REACHED();
+ }
}
- return m_iconURLs;
+ Vector<IconURL> iconURLs;
+ if (firstFavicon.m_iconType != InvalidIcon)
+ iconURLs.append(firstFavicon);
+ else if (m_url.protocolIsInHTTPFamily() && iconTypesMask & Favicon)
+ iconURLs.append(IconURL::defaultFavicon(m_url));
+
+ if (firstTouchIcon.m_iconType != InvalidIcon)
+ iconURLs.append(firstTouchIcon);
+ if (firstTouchPrecomposedIcon.m_iconType != InvalidIcon)
+ iconURLs.append(firstTouchPrecomposedIcon);
+ for (int i = secondaryIcons.size() - 1; i >= 0; --i)
+ iconURLs.append(secondaryIcons[i]);
+ return iconURLs;
}
void Document::setUseSecureKeyboardEntryWhenActive(bool usesSecureKeyboard)
@@ -4533,20 +4388,6 @@ bool Document::useSecureKeyboardEntryWhenActive() const
return m_useSecureKeyboardEntryWhenActive;
}
-static bool isEligibleForSeamless(Document* parent, Document* child)
-{
- // It should not matter what we return for the top-most document.
- if (!parent)
- return false;
- if (parent->isSandboxed(SandboxSeamlessIframes))
- return false;
- if (child->isSrcdocDocument())
- return true;
- if (parent->securityOrigin()->canAccess(child->securityOrigin()))
- return true;
- return parent->securityOrigin()->canRequest(child->url());
-}
-
void Document::initSecurityContext()
{
initSecurityContext(DocumentInit(m_url, m_frame, contextDocument(), m_import));
@@ -4593,15 +4434,14 @@ void Document::initSecurityContext(const DocumentInit& initializer)
}
}
- Document* parentDocument = ownerElement() ? &ownerElement()->document() : 0;
- if (parentDocument && initializer.shouldTreatURLAsSrcdocDocument()) {
+ if (initializer.shouldTreatURLAsSrcdocDocument()) {
m_isSrcdocDocument = true;
- setBaseURLOverride(parentDocument->baseURL());
+ setBaseURLOverride(initializer.parentBaseURL());
}
// FIXME: What happens if we inherit the security origin? This check may need to be later.
// <iframe seamless src="about:blank"> likely won't work as-is.
- m_mayDisplaySeamlesslyWithParent = isEligibleForSeamless(parentDocument, this);
+ m_mayDisplaySeamlesslyWithParent = initializer.isSeamlessAllowedFor(this);
if (!shouldInheritSecurityOriginFromOwner(m_url))
return;
@@ -4609,8 +4449,7 @@ void Document::initSecurityContext(const DocumentInit& initializer)
// If we do not obtain a meaningful origin from the URL, then we try to
// find one via the frame hierarchy.
- Frame* ownerFrame = initializer.ownerFrame();
- if (!ownerFrame) {
+ if (!initializer.owner()) {
didFailToInitializeSecurityOrigin();
return;
}
@@ -4620,21 +4459,21 @@ void Document::initSecurityContext(const DocumentInit& initializer)
// but we're also sandboxed, the only thing we inherit is the ability
// to load local resources. This lets about:blank iframes in file://
// URL documents load images and other resources from the file system.
- if (ownerFrame->document()->securityOrigin()->canLoadLocalResources())
+ if (initializer.owner()->securityOrigin()->canLoadLocalResources())
securityOrigin()->grantLoadLocalResources();
return;
}
- m_cookieURL = ownerFrame->document()->cookieURL();
+ m_cookieURL = initializer.owner()->cookieURL();
// We alias the SecurityOrigins to match Firefox, see Bug 15313
// https://bugs.webkit.org/show_bug.cgi?id=15313
- setSecurityOrigin(ownerFrame->document()->securityOrigin());
+ setSecurityOrigin(initializer.owner()->securityOrigin());
}
void Document::initContentSecurityPolicy(const ContentSecurityPolicyResponseHeaders& headers)
{
- if (m_frame && m_frame->tree()->parent() && (shouldInheritSecurityOriginFromOwner(m_url) || isPluginDocument()))
- contentSecurityPolicy()->copyStateFrom(m_frame->tree()->parent()->document()->contentSecurityPolicy());
+ if (m_frame && m_frame->tree().parent() && (shouldInheritSecurityOriginFromOwner(m_url) || isPluginDocument()))
+ contentSecurityPolicy()->copyStateFrom(m_frame->tree().parent()->document()->contentSecurityPolicy());
contentSecurityPolicy()->didReceiveHeaders(headers);
}
@@ -4649,9 +4488,9 @@ bool Document::allowInlineEventHandlers(Node* node, EventListener* listener, con
// we also need to ask the owner document of the node.
if (!m_frame)
return false;
- if (!m_frame->script()->canExecuteScripts(NotAboutToExecuteScript))
+ if (!m_frame->script().canExecuteScripts(NotAboutToExecuteScript))
return false;
- if (node && &node->document() != this && !node->document().allowInlineEventHandlers(node, listener, contextURL, contextLine))
+ if (node && node->document() != this && !node->document().allowInlineEventHandlers(node, listener, contextURL, contextLine))
return false;
return true;
@@ -4666,16 +4505,22 @@ bool Document::allowExecutingScripts(Node* node)
return false;
if (!node->document().frame() && !node->document().import())
return false;
- if (!contextDocument().get()->frame()->script()->canExecuteScripts(AboutToExecuteScript))
+ if (!contextDocument().get()->frame()->script().canExecuteScripts(AboutToExecuteScript))
return false;
return true;
}
+void Document::updateSecurityOrigin(PassRefPtr<SecurityOrigin> origin)
+{
+ setSecurityOrigin(origin);
+ didUpdateSecurityOrigin();
+}
+
void Document::didUpdateSecurityOrigin()
{
if (!m_frame)
return;
- m_frame->script()->updateSecurityOrigin();
+ m_frame->script().updateSecurityOrigin();
}
bool Document::isContextThread() const
@@ -4683,19 +4528,6 @@ bool Document::isContextThread() const
return isMainThread();
}
-void Document::statePopped(PassRefPtr<SerializedScriptValue> stateObject)
-{
- if (!frame())
- return;
-
- // Per step 11 of section 6.5.9 (history traversal) of the HTML5 spec, we
- // defer firing of popstate until we're in the complete state.
- if (m_readyState == Complete)
- enqueuePopstateEvent(stateObject);
- else
- m_pendingStateObject = stateObject;
-}
-
void Document::updateFocusAppearanceSoon(bool restorePreviousSelection)
{
m_updateFocusAppearanceRestoresSelection = restorePreviousSelection;
@@ -4775,6 +4607,11 @@ void Document::parseDNSPrefetchControlHeader(const String& dnsPrefetchControl)
m_haveExplicitlyDisabledDNSPrefetch = true;
}
+void Document::reportBlockedScriptExecutionToInspector(const String& directiveText)
+{
+ InspectorInstrumentation::scriptExecutionBlockedByCSP(this, directiveText);
+}
+
void Document::addMessage(MessageSource source, MessageLevel level, const String& message, const String& sourceURL, unsigned lineNumber, ScriptState* state)
{
internalAddMessage(source, level, message, sourceURL, lineNumber, 0, state);
@@ -4783,7 +4620,7 @@ void Document::addMessage(MessageSource source, MessageLevel level, const String
void Document::internalAddMessage(MessageSource source, MessageLevel level, const String& message, const String& sourceURL, unsigned lineNumber, PassRefPtr<ScriptCallStack> callStack, ScriptState* state)
{
if (!isContextThread()) {
- postTask(AddConsoleMessageTask::create(source, level, message));
+ m_taskRunner->postTask(AddConsoleMessageTask::create(source, level, message));
return;
}
Page* page = this->page();
@@ -4805,7 +4642,7 @@ void Document::internalAddMessage(MessageSource source, MessageLevel level, cons
void Document::addConsoleMessageWithRequestIdentifier(MessageSource source, MessageLevel level, const String& message, unsigned long requestIdentifier)
{
if (!isContextThread()) {
- postTask(AddConsoleMessageTask::create(source, level, message));
+ m_taskRunner->postTask(AddConsoleMessageTask::create(source, level, message));
return;
}
@@ -4813,137 +4650,50 @@ void Document::addConsoleMessageWithRequestIdentifier(MessageSource source, Mess
page->console().addMessage(source, level, message, String(), 0, 0, 0, 0, requestIdentifier);
}
-struct PerformTaskContext {
- WTF_MAKE_NONCOPYABLE(PerformTaskContext); WTF_MAKE_FAST_ALLOCATED;
-public:
- PerformTaskContext(WeakPtr<Document> document, PassOwnPtr<ScriptExecutionContext::Task> task)
- : documentReference(document)
- , task(task)
- {
- }
-
- WeakPtr<Document> documentReference;
- OwnPtr<ScriptExecutionContext::Task> task;
-};
-
-void Document::didReceiveTask(void* untypedContext)
+// FIXME(crbug.com/305497): This should be removed after ExecutionContext-DOMWindow migration.
+void Document::postTask(PassOwnPtr<ExecutionContextTask> task)
{
- ASSERT(isMainThread());
-
- OwnPtr<PerformTaskContext> context = adoptPtr(static_cast<PerformTaskContext*>(untypedContext));
- ASSERT(context);
-
- Document* document = context->documentReference.get();
- if (!document)
- return;
-
- Page* page = document->page();
- if ((page && page->defersLoading()) || !document->m_pendingTasks.isEmpty()) {
- document->m_pendingTasks.append(context->task.release());
- return;
- }
-
- context->task->performTask(document);
-}
-
-void Document::postTask(PassOwnPtr<Task> task)
-{
- callOnMainThread(didReceiveTask, new PerformTaskContext(m_weakFactory.createWeakPtr(), task));
+ m_taskRunner->postTask(task);
}
-void Document::pendingTasksTimerFired(Timer<Document>*)
+void Document::tasksWereSuspended()
{
- while (!m_pendingTasks.isEmpty()) {
- OwnPtr<Task> task = m_pendingTasks[0].release();
- m_pendingTasks.remove(0);
- task->performTask(this);
- }
-}
-
-void Document::suspendScheduledTasks(ActiveDOMObject::ReasonForSuspension reason)
-{
- ASSERT(!m_scheduledTasksAreSuspended);
-
- suspendScriptedAnimationControllerCallbacks();
- suspendActiveDOMObjects(reason);
scriptRunner()->suspend();
- m_pendingTasksTimer.stop();
+
if (m_parser)
m_parser->suspendScheduledTasks();
-
- m_scheduledTasksAreSuspended = true;
+ if (m_scriptedAnimationController)
+ m_scriptedAnimationController->suspend();
}
-void Document::resumeScheduledTasks()
+void Document::tasksWereResumed()
{
- ASSERT(m_scheduledTasksAreSuspended);
+ scriptRunner()->resume();
if (m_parser)
m_parser->resumeScheduledTasks();
- if (!m_pendingTasks.isEmpty())
- m_pendingTasksTimer.startOneShot(0);
- scriptRunner()->resume();
- resumeActiveDOMObjects();
- resumeScriptedAnimationControllerCallbacks();
-
- m_scheduledTasksAreSuspended = false;
-}
-
-void Document::suspendScriptedAnimationControllerCallbacks()
-{
- if (m_scriptedAnimationController)
- m_scriptedAnimationController->suspend();
-}
-
-void Document::resumeScriptedAnimationControllerCallbacks()
-{
if (m_scriptedAnimationController)
m_scriptedAnimationController->resume();
}
-String Document::displayStringModifiedByEncoding(const String& str) const
-{
- if (m_decoder)
- return m_decoder->encoding().displayString(str.impl());
- return str;
-}
-
-PassRefPtr<StringImpl> Document::displayStringModifiedByEncoding(PassRefPtr<StringImpl> str) const
-{
- if (m_decoder)
- return m_decoder->encoding().displayString(str);
- return str;
-}
-
-template <typename CharacterType>
-void Document::displayBufferModifiedByEncodingInternal(CharacterType* buffer, unsigned len) const
-{
- if (m_decoder)
- m_decoder->encoding().displayBuffer(buffer, len);
-}
-
-// Generate definitions for both character types
-template void Document::displayBufferModifiedByEncodingInternal<LChar>(LChar*, unsigned) const;
-template void Document::displayBufferModifiedByEncodingInternal<UChar>(UChar*, unsigned) const;
-
-void Document::enqueuePageshowEvent(PageshowEventPersistence persisted)
+// FIXME: suspendScheduledTasks(), resumeScheduledTasks(), tasksNeedSuspension()
+// should be moved to DOMWindow once it inherits ExecutionContext
+void Document::suspendScheduledTasks()
{
- // FIXME: https://bugs.webkit.org/show_bug.cgi?id=36334 Pageshow event needs to fire asynchronously.
- dispatchWindowEvent(PageTransitionEvent::create(eventNames().pageshowEvent, persisted), this);
+ ExecutionContext::suspendScheduledTasks();
+ m_taskRunner->suspend();
}
-void Document::enqueueHashchangeEvent(const String& oldURL, const String& newURL)
+void Document::resumeScheduledTasks()
{
- enqueueWindowEvent(HashChangeEvent::create(oldURL, newURL));
+ ExecutionContext::resumeScheduledTasks();
+ m_taskRunner->resume();
}
-void Document::enqueuePopstateEvent(PassRefPtr<SerializedScriptValue> stateObject)
+bool Document::tasksNeedSuspension()
{
- if (!ContextFeatures::pushStateEnabled(this))
- return;
-
- // FIXME: https://bugs.webkit.org/show_bug.cgi?id=36202 Popstate event needs to fire asynchronously
- dispatchWindowEvent(PopStateEvent::create(stateObject, domWindow() ? domWindow()->history() : 0));
+ Page* page = this->page();
+ return page && page->defersLoading();
}
void Document::addToTopLayer(Element* element, const Element* before)
@@ -4984,7 +4734,7 @@ void Document::webkitExitPointerLock()
if (!page())
return;
if (Element* target = page()->pointerLockController().element()) {
- if (&target->document() != this)
+ if (target->document() != this)
return;
}
page()->pointerLockController().requestPointerUnlock();
@@ -4995,7 +4745,7 @@ Element* Document::webkitPointerLockElement() const
if (!page() || page()->pointerLockController().lockPending())
return 0;
if (Element* element = page()->pointerLockController().element()) {
- if (&element->document() == this)
+ if (element->document() == this)
return element;
}
return 0;
@@ -5013,10 +4763,10 @@ void Document::decrementLoadEventDelayCount()
void Document::loadEventDelayTimerFired(Timer<Document>*)
{
if (frame())
- frame()->loader()->checkCompleted();
+ frame()->loader().checkCompleted();
}
-int Document::requestAnimationFrame(PassRefPtr<RequestAnimationFrameCallback> callback)
+ScriptedAnimationController& Document::ensureScriptedAnimationController()
{
if (!m_scriptedAnimationController) {
m_scriptedAnimationController = ScriptedAnimationController::create(this);
@@ -5024,8 +4774,12 @@ int Document::requestAnimationFrame(PassRefPtr<RequestAnimationFrameCallback> ca
if (!page())
m_scriptedAnimationController->suspend();
}
+ return *m_scriptedAnimationController;
+}
- return m_scriptedAnimationController->registerCallback(callback);
+int Document::requestAnimationFrame(PassOwnPtr<RequestAnimationFrameCallback> callback)
+{
+ return ensureScriptedAnimationController().registerCallback(callback);
}
void Document::cancelAnimationFrame(int id)
@@ -5092,7 +4846,7 @@ void Document::didRemoveTouchEventHandler(Node* handler)
scrollingCoordinator->touchEventTargetRectsDidChange(this);
if (m_touchEventTargets->size())
return;
- for (const Frame* frame = page->mainFrame(); frame; frame = frame->tree()->traverseNext()) {
+ for (const Frame* frame = page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
if (frame->document() && frame->document()->hasTouchEventHandlers())
return;
}
@@ -5139,7 +4893,7 @@ DocumentLoader* Document::loader() const
if (!m_frame)
return 0;
- DocumentLoader* loader = m_frame->loader()->documentLoader();
+ DocumentLoader* loader = m_frame->loader().documentLoader();
if (!loader)
return 0;
@@ -5172,7 +4926,7 @@ Node* eventTargetNodeForDocument(Document* doc)
return node;
}
-void Document::adjustFloatQuadsForScrollAndAbsoluteZoom(Vector<FloatQuad>& quads, RenderObject* renderer)
+void Document::adjustFloatQuadsForScrollAndAbsoluteZoom(Vector<FloatQuad>& quads, RenderObject& renderer)
{
if (!view())
return;
@@ -5184,7 +4938,7 @@ void Document::adjustFloatQuadsForScrollAndAbsoluteZoom(Vector<FloatQuad>& quads
}
}
-void Document::adjustFloatRectForScrollAndAbsoluteZoom(FloatRect& rect, RenderObject* renderer)
+void Document::adjustFloatRectForScrollAndAbsoluteZoom(FloatRect& rect, RenderObject& renderer)
{
if (!view())
return;
@@ -5208,7 +4962,7 @@ void Document::decrementActiveParserCount()
// http/tests/security/feed-urls-from-remote.html to timeout on Mac WK1
// see http://webkit.org/b/110554 and http://webkit.org/b/110401
loader()->checkLoadComplete();
- frame()->loader()->checkLoadComplete();
+ frame()->loader().checkLoadComplete();
}
void Document::setContextFeatures(PassRefPtr<ContextFeatures> features)
@@ -5235,8 +4989,11 @@ void Document::updateHoverActiveState(const HitTestRequest& request, Element* in
{
ASSERT(!request.readOnly());
+ if (request.active() && m_frame)
+ m_frame->eventHandler().notifyElementActivated();
+
Element* innerElementInDocument = innerElement;
- while (innerElementInDocument && &innerElementInDocument->document() != this) {
+ while (innerElementInDocument && innerElementInDocument->document() != this) {
innerElementInDocument->document().updateHoverActiveState(request, innerElementInDocument, event);
innerElementInDocument = innerElementInDocument->document().ownerElement();
}
@@ -5276,11 +5033,6 @@ void Document::updateHoverActiveState(const HitTestRequest& request, Element* in
RefPtr<Node> oldHoverNode = hoverNode();
- // A touch release does not set a new hover target; setting the element we're working with to 0
- // will clear the chain of hovered elements all the way to the top of the tree.
- if (request.touchRelease())
- innerElementInDocument = 0;
-
// Check to see if the hovered node has changed.
// If it hasn't, we do not need to do anything.
Node* newHoverNode = innerElementInDocument;
@@ -5335,7 +5087,7 @@ void Document::updateHoverActiveState(const HitTestRequest& request, Element* in
bool ancestorHasCapturingMouseleaveListener = false;
if (event && newHoverNode != oldHoverNode.get()) {
for (Node* node = oldHoverNode.get(); node; node = node->parentOrShadowHostNode()) {
- if (node->hasCapturingEventListeners(eventNames().mouseleaveEvent)) {
+ if (node->hasCapturingEventListeners(EventTypeNames::mouseleave)) {
ancestorHasCapturingMouseleaveListener = true;
break;
}
@@ -5345,14 +5097,14 @@ void Document::updateHoverActiveState(const HitTestRequest& request, Element* in
size_t removeCount = nodesToRemoveFromChain.size();
for (size_t i = 0; i < removeCount; ++i) {
nodesToRemoveFromChain[i]->setHovered(false);
- if (event && (ancestorHasCapturingMouseleaveListener || nodesToRemoveFromChain[i]->hasEventListeners(eventNames().mouseleaveEvent)))
- nodesToRemoveFromChain[i]->dispatchMouseEvent(*event, eventNames().mouseleaveEvent, 0, newHoverNode);
+ if (event && (ancestorHasCapturingMouseleaveListener || nodesToRemoveFromChain[i]->hasEventListeners(EventTypeNames::mouseleave)))
+ nodesToRemoveFromChain[i]->dispatchMouseEvent(*event, EventTypeNames::mouseleave, 0, newHoverNode);
}
bool ancestorHasCapturingMouseenterListener = false;
if (event && newHoverNode != oldHoverNode.get()) {
for (Node* node = newHoverNode; node; node = node->parentOrShadowHostNode()) {
- if (node->hasCapturingEventListeners(eventNames().mouseenterEvent)) {
+ if (node->hasCapturingEventListeners(EventTypeNames::mouseenter)) {
ancestorHasCapturingMouseenterListener = true;
break;
}
@@ -5369,8 +5121,8 @@ void Document::updateHoverActiveState(const HitTestRequest& request, Element* in
nodesToAddToChain[i]->setActive(true);
if (!sawCommonAncestor) {
nodesToAddToChain[i]->setHovered(true);
- if (event && (ancestorHasCapturingMouseenterListener || nodesToAddToChain[i]->hasEventListeners(eventNames().mouseenterEvent)))
- nodesToAddToChain[i]->dispatchMouseEvent(*event, eventNames().mouseenterEvent, 0, oldHoverNode.get());
+ if (event && (ancestorHasCapturingMouseenterListener || nodesToAddToChain[i]->hasEventListeners(EventTypeNames::mouseenter)))
+ nodesToAddToChain[i]->dispatchMouseEvent(*event, EventTypeNames::mouseenter, 0, oldHoverNode.get());
}
}
@@ -5379,14 +5131,14 @@ void Document::updateHoverActiveState(const HitTestRequest& request, Element* in
bool Document::haveStylesheetsLoaded() const
{
- return !m_styleEngine->hasPendingSheets() || m_ignorePendingStylesheets;
+ return m_styleEngine->haveStylesheetsLoaded();
}
Locale& Document::getCachedLocale(const AtomicString& locale)
{
AtomicString localeKey = locale;
if (locale.isEmpty() || !RuntimeEnabledFeatures::langAttributeAwareFormControlUIEnabled())
- localeKey = defaultLanguage();
+ return Locale::defaultLocale();
LocaleIdentifierToLocaleMap::AddResult result = m_localeCache.add(localeKey, nullptr);
if (result.isNewEntry)
result.iterator->value = Locale::create(localeKey);
@@ -5399,8 +5151,7 @@ Document& Document::ensureTemplateDocument()
return *const_cast<Document*>(document);
if (isHTMLDocument()) {
- DocumentInit init = DocumentInit::fromContext(contextDocument(), blankURL())
- .withRegistrationContext(registrationContext());
+ DocumentInit init = DocumentInit::fromContext(contextDocument(), blankURL());
m_templateDocument = HTMLDocument::create(init);
} else {
m_templateDocument = Document::create(DocumentInit(blankURL()));
@@ -5411,13 +5162,6 @@ Document& Document::ensureTemplateDocument()
return *m_templateDocument.get();
}
-PassRefPtr<FontFaceSet> Document::fonts()
-{
- if (!m_fonts)
- m_fonts = FontFaceSet::create(this);
- return m_fonts;
-}
-
void Document::didAssociateFormControl(Element* element)
{
if (!frame() || !frame()->page())
@@ -5445,14 +5189,48 @@ float Document::devicePixelRatio() const
return m_frame ? m_frame->devicePixelRatio() : 1.0;
}
-PassOwnPtr<LifecycleNotifier> Document::createLifecycleNotifier()
+PassOwnPtr<LifecycleNotifier<Document> > Document::createLifecycleNotifier()
{
return DocumentLifecycleNotifier::create(this);
}
-DocumentLifecycleNotifier* Document::lifecycleNotifier()
+DocumentLifecycleNotifier& Document::lifecycleNotifier()
+{
+ return static_cast<DocumentLifecycleNotifier&>(LifecycleContext<Document>::lifecycleNotifier());
+}
+
+void Document::removedStyleSheet(StyleSheet* sheet, RecalcStyleTime when, StyleResolverUpdateMode updateMode)
+{
+ // If we're in document teardown, then we don't need this notification of our sheet's removal.
+ // styleResolverChanged() is needed even when the document is inactive so that
+ // imported docuements (which is inactive) notifies the change to the master document.
+ if (isActive())
+ styleEngine()->modifiedStyleSheet(sheet);
+ styleResolverChanged(when, updateMode);
+}
+
+void Document::modifiedStyleSheet(StyleSheet* sheet, RecalcStyleTime when, StyleResolverUpdateMode updateMode)
+{
+ // If we're in document teardown, then we don't need this notification of our sheet's removal.
+ // styleResolverChanged() is needed even when the document is inactive so that
+ // imported docuements (which is inactive) notifies the change to the master document.
+ if (isActive())
+ styleEngine()->modifiedStyleSheet(sheet);
+ styleResolverChanged(when, updateMode);
+}
+
+TextAutosizer* Document::textAutosizer()
+{
+ if (!m_textAutosizer && !RuntimeEnabledFeatures::fastTextAutosizingEnabled())
+ m_textAutosizer = TextAutosizer::create(this);
+ return m_textAutosizer.get();
+}
+
+FastTextAutosizer* Document::fastTextAutosizer()
{
- return static_cast<DocumentLifecycleNotifier*>(ScriptExecutionContext::lifecycleNotifier());
+ if (!m_fastTextAutosizer && RuntimeEnabledFeatures::fastTextAutosizingEnabled())
+ m_fastTextAutosizer = FastTextAutosizer::create(this);
+ return m_fastTextAutosizer.get();
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/Document.h b/chromium/third_party/WebKit/Source/core/dom/Document.h
index 2a616d0e7a5..cc23012b679 100644
--- a/chromium/third_party/WebKit/Source/core/dom/Document.h
+++ b/chromium/third_party/WebKit/Source/core/dom/Document.h
@@ -29,26 +29,29 @@
#define Document_h
#include "bindings/v8/ScriptValue.h"
+#include "core/animation/css/CSSPendingAnimations.h"
#include "core/dom/ContainerNode.h"
-#include "core/dom/CustomElement.h"
#include "core/dom/DOMTimeStamp.h"
-#include "core/dom/DocumentEventQueue.h"
+#include "core/dom/DocumentEncodingData.h"
#include "core/dom/DocumentInit.h"
+#include "core/dom/DocumentLifecycle.h"
+#include "core/dom/DocumentSupplementable.h"
#include "core/dom/DocumentTiming.h"
+#include "core/dom/ExecutionContext.h"
#include "core/dom/IconURL.h"
#include "core/dom/MutationObserver.h"
#include "core/dom/QualifiedName.h"
-#include "core/dom/ScriptExecutionContext.h"
#include "core/dom/TextLinkColors.h"
#include "core/dom/TreeScope.h"
#include "core/dom/UserActionElementSet.h"
-#include "core/dom/ViewportArguments.h"
+#include "core/dom/ViewportDescription.h"
+#include "core/dom/custom/CustomElement.h"
#include "core/html/CollectionType.h"
#include "core/page/FocusDirection.h"
#include "core/page/PageVisibilityState.h"
-#include "weborigin/ReferrerPolicy.h"
-#include "core/platform/Timer.h"
#include "core/rendering/HitTestRequest.h"
+#include "platform/Timer.h"
+#include "platform/weborigin/ReferrerPolicy.h"
#include "wtf/HashSet.h"
#include "wtf/OwnPtr.h"
#include "wtf/PassOwnPtr.h"
@@ -58,12 +61,13 @@
namespace WebCore {
class AXObjectCache;
+class AnimationClock;
class Attr;
class CDATASection;
+class CSSFontSelector;
class CSSStyleDeclaration;
class CSSStyleSheet;
class CSSStyleSheetResource;
-class ScriptResource;
class CanvasRenderingContext;
class CharacterData;
class Chrome;
@@ -92,6 +96,8 @@ class Element;
class Event;
class EventListener;
class ExceptionState;
+class MainThreadTaskRunner;
+class FastTextAutosizer;
class FloatQuad;
class FloatRect;
class FormController;
@@ -118,6 +124,7 @@ class LayoutPoint;
class LayoutRect;
class LiveNodeListBase;
class Locale;
+class Location;
class MediaQueryList;
class MediaQueryMatcher;
class MouseEventWithHitTestResults;
@@ -126,7 +133,6 @@ class NodeFilter;
class NodeIterator;
class Page;
class PlatformMouseEvent;
-class Prerenderer;
class ProcessingInstruction;
class Range;
class RegisteredEventListener;
@@ -135,6 +141,7 @@ class RequestAnimationFrameCallback;
class ResourceFetcher;
class SVGDocumentExtensions;
class ScriptElementData;
+class ScriptResource;
class ScriptRunner;
class ScriptableDocumentParser;
class ScriptedAnimationController;
@@ -143,14 +150,13 @@ class SegmentedString;
class SelectorQueryCache;
class SerializedScriptValue;
class Settings;
+class StyleEngine;
class StyleResolver;
class StyleSheet;
-class StyleEngine;
class StyleSheetContents;
class StyleSheetList;
class Text;
class TextAutosizer;
-class TextResourceDecoder;
class Touch;
class TouchList;
class TransformSource;
@@ -164,13 +170,11 @@ class FontFaceSet;
typedef int ExceptionCode;
-enum PageshowEventPersistence {
- PageshowEventNotPersisted = 0,
- PageshowEventPersisted = 1
+enum RecalcStyleTime {
+ RecalcStyleImmediately, // synchronous
+ RecalcStyleDeferred // asynchronous
};
-enum StyleResolverUpdateType { RecalcStyleImmediately, RecalcStyleDeferred };
-
enum StyleResolverUpdateMode {
// Discards the StyleResolver and rebuilds it.
FullStyleUpdate,
@@ -205,7 +209,8 @@ enum DocumentClass {
typedef unsigned char DocumentClassFlags;
-class Document : public ContainerNode, public TreeScope, public ScriptExecutionContext {
+class Document : public ContainerNode, public TreeScope, public SecurityContext, public ExecutionContext, public ExecutionContextClient
+ , public DocumentSupplementable, public LifecycleContext<Document> {
public:
static PassRefPtr<Document> create(const DocumentInit& initializer = DocumentInit())
{
@@ -217,86 +222,58 @@ public:
}
virtual ~Document();
- MediaQueryMatcher* mediaQueryMatcher();
+ MediaQueryMatcher& mediaQueryMatcher();
+
+ void mediaQueryAffectingValueChanged();
using ContainerNode::ref;
using ContainerNode::deref;
+ using SecurityContext::securityOrigin;
+ using SecurityContext::contentSecurityPolicy;
+ using ExecutionContextClient::addConsoleMessage;
virtual bool canContainRangeEndPoint() const { return true; }
- SelectorQueryCache* selectorQueryCache();
+ SelectorQueryCache& selectorQueryCache();
// DOM methods & attributes for Document
- DEFINE_ATTRIBUTE_EVENT_LISTENER(abort);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(change);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(click);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(contextmenu);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(dblclick);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(dragenter);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(dragover);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(dragleave);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(drop);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(dragstart);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(drag);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(dragend);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(input);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(invalid);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(keydown);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(keypress);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(keyup);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(mousedown);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(mouseenter);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(mouseleave);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(mousemove);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(mouseout);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(mouseover);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(mouseup);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(mousewheel);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(scroll);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(select);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(submit);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(wheel);
-
- DEFINE_ATTRIBUTE_EVENT_LISTENER(blur);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(error);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(focus);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(load);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(readystatechange);
-
- // WebKit extensions
- DEFINE_ATTRIBUTE_EVENT_LISTENER(beforecut);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(cut);
DEFINE_ATTRIBUTE_EVENT_LISTENER(beforecopy);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(copy);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(beforecut);
DEFINE_ATTRIBUTE_EVENT_LISTENER(beforepaste);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(copy);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(cut);
DEFINE_ATTRIBUTE_EVENT_LISTENER(paste);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(reset);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(readystatechange);
DEFINE_ATTRIBUTE_EVENT_LISTENER(search);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(selectstart);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(securitypolicyviolation);
DEFINE_ATTRIBUTE_EVENT_LISTENER(selectionchange);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(touchstart);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(touchmove);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(touchend);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(selectstart);
DEFINE_ATTRIBUTE_EVENT_LISTENER(touchcancel);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(touchend);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(touchmove);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(touchstart);
DEFINE_ATTRIBUTE_EVENT_LISTENER(webkitfullscreenchange);
DEFINE_ATTRIBUTE_EVENT_LISTENER(webkitfullscreenerror);
DEFINE_ATTRIBUTE_EVENT_LISTENER(webkitpointerlockchange);
DEFINE_ATTRIBUTE_EVENT_LISTENER(webkitpointerlockerror);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(webkitvisibilitychange);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(securitypolicyviolation);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(wheel);
- bool shouldOverrideLegacyViewport(ViewportArguments::Type);
- void setViewportArguments(const ViewportArguments&);
- const ViewportArguments& viewportArguments() const { return m_viewportArguments; }
+ bool shouldMergeWithLegacyDescription(ViewportDescription::Type);
+ bool shouldOverrideLegacyDescription(ViewportDescription::Type);
+ void setViewportDescription(const ViewportDescription&);
+ const ViewportDescription& viewportDescription() const { return m_viewportDescription; }
#ifndef NDEBUG
bool didDispatchViewportPropertiesChanged() const { return m_didDispatchViewportPropertiesChanged; }
#endif
- bool hasLegacyViewportTag() const { return m_legacyViewportArguments.isLegacyViewportType(); }
+ bool hasLegacyViewportTag() const { return m_legacyViewportDescription.isLegacyViewportType(); }
void setReferrerPolicy(ReferrerPolicy referrerPolicy) { m_referrerPolicy = referrerPolicy; }
ReferrerPolicy referrerPolicy() const { return m_referrerPolicy; }
+ String outgoingReferrer();
+ String outgoingOrigin() const;
+
void setDoctype(PassRefPtr<DocumentType>);
DocumentType* doctype() const { return m_docType.get(); }
@@ -309,21 +286,21 @@ public:
bool hasManifest() const;
+ Location* location() const;
+
PassRefPtr<Element> createElement(const AtomicString& name, ExceptionState&);
PassRefPtr<DocumentFragment> createDocumentFragment();
PassRefPtr<Text> createTextNode(const String& data);
PassRefPtr<Comment> createComment(const String& data);
PassRefPtr<CDATASection> createCDATASection(const String& data, ExceptionState&);
PassRefPtr<ProcessingInstruction> createProcessingInstruction(const String& target, const String& data, ExceptionState&);
- PassRefPtr<Attr> createAttribute(const String& name, ExceptionState&);
- PassRefPtr<Attr> createAttributeNS(const String& namespaceURI, const String& qualifiedName, ExceptionState&, bool shouldIgnoreNamespaceChecks = false);
+ PassRefPtr<Attr> createAttribute(const AtomicString& name, ExceptionState&);
+ PassRefPtr<Attr> createAttributeNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionState&, bool shouldIgnoreNamespaceChecks = false);
PassRefPtr<Node> importNode(Node* importedNode, ExceptionState& ec) { return importNode(importedNode, true, ec); }
PassRefPtr<Node> importNode(Node* importedNode, bool deep, ExceptionState&);
- PassRefPtr<Element> createElementNS(const String& namespaceURI, const String& qualifiedName, ExceptionState&);
+ PassRefPtr<Element> createElementNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionState&);
PassRefPtr<Element> createElement(const QualifiedName&, bool createdByParser);
- bool cssStickyPositionEnabled() const;
- bool cssCompositingEnabled() const;
PassRefPtr<DOMNamedFlowCollection> webkitGetNamedFlows();
NamedFlowCollection* namedFlows();
@@ -343,7 +320,7 @@ public:
*/
PassRefPtr<NodeList> nodesFromRect(int centerX, int centerY,
unsigned topPadding, unsigned rightPadding, unsigned bottomPadding, unsigned leftPadding,
- HitTestRequest::HitTestRequestType hitType = HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::DisallowShadowContent) const;
+ HitTestRequest::HitTestRequestType hitType = HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent) const;
Element* elementFromPoint(int x, int y) const;
PassRefPtr<Range> caretRangeFromPoint(int x, int y);
@@ -351,11 +328,11 @@ public:
String defaultCharset() const;
- String inputEncoding() const { return Document::encodingName(); }
- String charset() const { return Document::encodingName(); }
- String characterSet() const { return Document::encodingName(); }
+ AtomicString inputEncoding() const { return Document::encodingName(); }
+ AtomicString charset() const { return Document::encodingName(); }
+ AtomicString characterSet() const { return Document::encodingName(); }
- String encodingName() const;
+ AtomicString encodingName() const;
void setCharset(const String&);
@@ -363,8 +340,8 @@ public:
String suggestedMIMEType() const;
- String contentLanguage() const { return m_contentLanguage; }
- void setContentLanguage(const String&);
+ const AtomicString& contentLanguage() const { return m_contentLanguage; }
+ void setContentLanguage(const AtomicString&);
String xmlEncoding() const { return m_xmlEncoding; }
String xmlVersion() const { return m_xmlVersion; }
@@ -382,8 +359,8 @@ public:
virtual KURL baseURI() const;
- String webkitVisibilityState() const;
- bool webkitHidden() const;
+ String visibilityState() const;
+ bool hidden() const;
void dispatchVisibilityStateChangeEvent();
DOMSecurityPolicy* securityPolicy();
@@ -392,7 +369,6 @@ public:
PassRefPtr<HTMLCollection> images();
PassRefPtr<HTMLCollection> embeds();
- PassRefPtr<HTMLCollection> plugins(); // an alias for embeds() required for the JS DOM bindings.
PassRefPtr<HTMLCollection> applets();
PassRefPtr<HTMLCollection> links();
PassRefPtr<HTMLCollection> forms();
@@ -418,20 +394,14 @@ public:
bool isSrcdocDocument() const { return m_isSrcdocDocument; }
bool isMobileDocument() const { return m_isMobileDocument; }
- StyleResolver* styleResolverIfExists() const { return m_styleResolver.get(); }
+ StyleResolver* styleResolver() const;
+ StyleResolver& ensureStyleResolver() const;
bool isViewSource() const { return m_isViewSource; }
void setIsViewSource(bool);
bool sawElementsInKnownNamespaces() const { return m_sawElementsInKnownNamespaces; }
- StyleResolver* styleResolver()
- {
- if (!m_styleResolver)
- createStyleResolver();
- return m_styleResolver.get();
- }
-
void notifyRemovePendingSheetIfNeeded();
bool haveStylesheetsLoaded() const;
@@ -446,15 +416,14 @@ public:
void setGotoAnchorNeededAfterStylesheetsLoad(bool b) { m_gotoAnchorNeededAfterStylesheetsLoad = b; }
// Called when one or more stylesheets in the document may have been added, removed, or changed.
- void styleResolverChanged(StyleResolverUpdateType, StyleResolverUpdateMode = FullStyleUpdate);
+ void styleResolverChanged(RecalcStyleTime, StyleResolverUpdateMode = FullStyleUpdate);
// FIXME: Switch all callers of styleResolverChanged to these or better ones and then make them
// do something smarter.
- void removedStyleSheet(StyleSheet*, StyleResolverUpdateType type = RecalcStyleDeferred) { styleResolverChanged(type); }
- void addedStyleSheet(StyleSheet*, StyleResolverUpdateType type = RecalcStyleDeferred) { styleResolverChanged(type); }
- void modifiedStyleSheet(StyleSheet*, StyleResolverUpdateType type = RecalcStyleDeferred) { styleResolverChanged(type); }
-
- void didAccessStyleResolver();
+ void removedStyleSheet(StyleSheet*, RecalcStyleTime when = RecalcStyleDeferred, StyleResolverUpdateMode = FullStyleUpdate);
+ void addedStyleSheet(StyleSheet*, RecalcStyleTime when = RecalcStyleDeferred) { styleResolverChanged(when); }
+ void modifiedStyleSheet(StyleSheet*, RecalcStyleTime when = RecalcStyleDeferred, StyleResolverUpdateMode = FullStyleUpdate);
+ void changedSelectorWatch() { styleResolverChanged(RecalcStyleDeferred); }
void evaluateMediaQueryList();
@@ -475,12 +444,10 @@ public:
PassRefPtr<NodeIterator> createNodeIterator(Node* root, ExceptionState&);
PassRefPtr<NodeIterator> createNodeIterator(Node* root, unsigned whatToShow, ExceptionState&);
PassRefPtr<NodeIterator> createNodeIterator(Node* root, unsigned whatToShow, PassRefPtr<NodeFilter>, ExceptionState&);
- PassRefPtr<NodeIterator> createNodeIterator(Node* root, unsigned whatToShow, PassRefPtr<NodeFilter>, bool expandEntityReferences, ExceptionState&);
PassRefPtr<TreeWalker> createTreeWalker(Node* root, ExceptionState&);
PassRefPtr<TreeWalker> createTreeWalker(Node* root, unsigned whatToShow, ExceptionState&);
PassRefPtr<TreeWalker> createTreeWalker(Node* root, unsigned whatToShow, PassRefPtr<NodeFilter>, ExceptionState&);
- PassRefPtr<TreeWalker> createTreeWalker(Node* root, unsigned whatToShow, PassRefPtr<NodeFilter>, bool expandEntityReferences, ExceptionState&);
// Special support for editing
PassRefPtr<CSSStyleDeclaration> createCSSStyleDeclaration();
@@ -492,7 +459,11 @@ public:
void updateStyleIfNeeded();
void updateStyleForNodeIfNeeded(Node*);
void updateLayout();
- void updateLayoutIgnorePendingStylesheets();
+ enum RunPostLayoutTasks {
+ RunPostLayoutTasksAsyhnchronously,
+ RunPostLayoutTasksSynchronously,
+ };
+ void updateLayoutIgnorePendingStylesheets(RunPostLayoutTasks = RunPostLayoutTasksAsyhnchronously);
void partialUpdateLayoutIgnorePendingStylesheets(Node*);
PassRefPtr<RenderStyle> styleForElementIgnoringPendingStylesheets(Element*);
PassRefPtr<RenderStyle> styleForPage(int pageIndex);
@@ -514,21 +485,7 @@ public:
virtual void detach(const AttachContext& = AttachContext()) OVERRIDE;
void prepareForDestruction();
- // Override ScriptExecutionContext methods to do additional work
- virtual void suspendActiveDOMObjects(ActiveDOMObject::ReasonForSuspension) OVERRIDE;
- virtual void resumeActiveDOMObjects() OVERRIDE;
-
- // Implemented in RenderView.h to avoid a cyclic header dependency this just
- // returns renderer so callers can avoid verbose casts.
- RenderView* renderView() const;
-
- // Shadow the implementations on Node to provide faster access for documents.
- RenderObject* renderer() const { return m_renderer; }
- void setRenderer(RenderObject* renderer)
- {
- m_renderer = renderer;
- Node::setRenderer(renderer);
- }
+ RenderView* renderView() const { return m_renderView; }
AXObjectCache* existingAXObjectCache() const;
AXObjectCache* axObjectCache() const;
@@ -587,7 +544,6 @@ public:
KURL completeURL(const String&, const KURL& baseURLOverride) const;
virtual String userAgent(const KURL&) const;
-
virtual void disableEval(const String& errorMessage);
bool canNavigate(Frame* targetFrame);
@@ -625,6 +581,8 @@ public:
Complete
};
void setReadyState(ReadyState);
+ bool isLoadCompleted();
+
void setParsing(bool);
bool parsing() const { return m_bParsing; }
int minimumLayoutDelay();
@@ -634,7 +592,7 @@ public:
int elapsedTime() const;
TextLinkColors& textLinkColors() { return m_textLinkColors; }
- VisitedLinkState* visitedLinkState() const { return m_visitedLinkState.get(); }
+ VisitedLinkState& visitedLinkState() const { return *m_visitedLinkState; }
MouseEventWithHitTestResults prepareMouseEvent(const HitTestRequest&, const LayoutPoint&, const PlatformMouseEvent&);
@@ -653,11 +611,6 @@ public:
void setNeedsFocusedElementCheck();
void didRunCheckFocusedElementTask() { m_didPostCheckFocusedElementTask = false; }
- // The m_ignoreAutofocus flag specifies whether or not the document has been changed by the user enough
- // for WebCore to ignore the autofocus attribute on any form controls
- bool ignoreAutofocus() const { return m_ignoreAutofocus; };
- void setIgnoreAutofocus(bool shouldIgnore = true) { m_ignoreAutofocus = shouldIgnore; };
-
void setHoverNode(PassRefPtr<Node>);
Node* hoverNode() const { return m_hoverNode.get(); }
@@ -696,23 +649,20 @@ public:
// nodeChildrenWillBeRemoved is used when removing all node children at once.
void nodeChildrenWillBeRemoved(ContainerNode*);
// nodeWillBeRemoved is only safe when removing one node at a time.
- void nodeWillBeRemoved(Node*);
- bool canReplaceChild(Node* newChild, Node* oldChild);
+ void nodeWillBeRemoved(Node&);
+ bool canReplaceChild(const Node& newChild, const Node& oldChild) const;
void didInsertText(Node*, unsigned offset, unsigned length);
void didRemoveText(Node*, unsigned offset, unsigned length);
void didMergeTextNodes(Text* oldNode, unsigned offset);
void didSplitTextNode(Text* oldNode);
- void setDOMWindow(DOMWindow* domWindow) { m_domWindow = domWindow; }
+ void clearDOMWindow() { m_domWindow = 0; }
DOMWindow* domWindow() const { return m_domWindow; }
- // In DOM Level 2, the Document's DOMWindow is called the defaultView.
- DOMWindow* defaultView() const { return domWindow(); }
// Helper functions for forwarding DOMWindow event related tasks to the DOMWindow if it exists.
void setWindowAttributeEventListener(const AtomicString& eventType, PassRefPtr<EventListener>, DOMWrapperWorld* isolatedWorld = 0);
EventListener* getWindowAttributeEventListener(const AtomicString& eventType, DOMWrapperWorld* isolatedWorld);
- void dispatchWindowEvent(PassRefPtr<Event>, PassRefPtr<EventTarget> = 0);
PassRefPtr<Event> createEvent(const String& eventType, ExceptionState&);
@@ -756,9 +706,9 @@ public:
* @param equiv The http header name (value of the meta tag's "equiv" attribute)
* @param content The header value (value of the meta tag's "content" attribute)
*/
- void processHttpEquiv(const String& equiv, const String& content);
- void processViewport(const String& features, ViewportArguments::Type origin);
- void updateViewportArguments();
+ void processHttpEquiv(const AtomicString& equiv, const AtomicString& content);
+ void processViewport(const String& features, ViewportDescription::Type origin);
+ void updateViewportDescription();
void processReferrerPolicy(const String& policy);
// Returns the owning element in the parent document.
@@ -778,7 +728,7 @@ public:
String cookie(ExceptionState&) const;
void setCookie(const String&, ExceptionState&);
- String referrer() const;
+ const AtomicString& referrer() const;
String domain() const;
void setDomain(const String& newDomain, ExceptionState&);
@@ -808,7 +758,7 @@ public:
// The following breaks a qualified name into a prefix and a local name.
// It also does a validity check, and returns false if the qualified name
// is invalid. It also sets ExceptionCode when name is invalid.
- static bool parseQualifiedName(const String& qualifiedName, String& prefix, String& localName, ExceptionState&);
+ static bool parseQualifiedName(const AtomicString& qualifiedName, AtomicString& prefix, AtomicString& localName, ExceptionState&);
// Checks to make sure prefix and namespace do not conflict (per DOM Core 3)
static bool hasValidNamespaceForElements(const QualifiedName&);
@@ -868,8 +818,7 @@ public:
bool hasNodesWithPlaceholderStyle() const { return m_hasNodesWithPlaceholderStyle; }
void setHasNodesWithPlaceholderStyle() { m_hasNodesWithPlaceholderStyle = true; }
- const Vector<IconURL>& shortcutIconURLs();
- const Vector<IconURL>& iconURLs(int iconTypesMask);
+ Vector<IconURL> iconURLs(int iconTypesMask);
void setUseSecureKeyboardEntryWhenActive(bool);
bool useSecureKeyboardEntryWhenActive() const;
@@ -884,31 +833,22 @@ public:
bool isDNSPrefetchEnabled() const { return m_isDNSPrefetchEnabled; }
void parseDNSPrefetchControlHeader(const String&);
- virtual void postTask(PassOwnPtr<Task>); // Executes the task on context's thread asynchronously.
+ // FIXME(crbug.com/305497): This should be removed once DOMWindow is an ExecutionContext.
+ virtual void postTask(PassOwnPtr<ExecutionContextTask>) OVERRIDE; // Executes the task on context's thread asynchronously.
- void suspendScriptedAnimationControllerCallbacks();
- void resumeScriptedAnimationControllerCallbacks();
+ virtual void tasksWereSuspended() OVERRIDE;
+ virtual void tasksWereResumed() OVERRIDE;
+ virtual void suspendScheduledTasks() OVERRIDE;
+ virtual void resumeScheduledTasks() OVERRIDE;
+ virtual bool tasksNeedSuspension() OVERRIDE;
void finishedParsing();
- void documentWillBecomeInactive();
-
- void setDecoder(PassRefPtr<TextResourceDecoder>);
- TextResourceDecoder* decoder() const { return m_decoder.get(); }
-
- void setEncoding(const WTF::TextEncoding&);
- const WTF::TextEncoding& encoding() const { return m_encoding; }
+ void setEncodingData(const DocumentEncodingData& newData);
+ const WTF::TextEncoding& encoding() const { return m_encodingData.encoding; }
- String displayStringModifiedByEncoding(const String&) const;
- PassRefPtr<StringImpl> displayStringModifiedByEncoding(PassRefPtr<StringImpl>) const;
- void displayBufferModifiedByEncoding(LChar* buffer, unsigned len) const
- {
- displayBufferModifiedByEncodingInternal(buffer, len);
- }
- void displayBufferModifiedByEncoding(UChar* buffer, unsigned len) const
- {
- displayBufferModifiedByEncodingInternal(buffer, len);
- }
+ bool encodingWasDetectedHeuristically() const { return m_encodingData.wasDetectedHeuristically; }
+ bool sawDecodingError() const { return m_encodingData.sawDecodingError; }
void setAnnotatedRegionsDirty(bool f) { m_annotatedRegionsDirty = f; }
bool annotatedRegionsDirty() const { return m_annotatedRegionsDirty; }
@@ -946,18 +886,18 @@ public:
bool processingLoadEvent() const { return m_loadEventProgress == LoadEventInProgress; }
bool loadEventFinished() const { return m_loadEventProgress >= LoadEventCompleted; }
+ void setContainsPlugins() { m_containsPlugins = true; }
+ bool containsPlugins() const { return m_containsPlugins; }
+
virtual bool isContextThread() const;
virtual bool isJSExecutionForbidden() const { return false; }
bool containsValidityStyleRules() const { return m_containsValidityStyleRules; }
void setContainsValidityStyleRules() { m_containsValidityStyleRules = true; }
- void enqueueWindowEvent(PassRefPtr<Event>);
- void enqueueDocumentEvent(PassRefPtr<Event>);
- void enqueuePageshowEvent(PageshowEventPersistence);
- void enqueueHashchangeEvent(const String& oldURL, const String& newURL);
- void enqueuePopstateEvent(PassRefPtr<SerializedScriptValue> stateObject);
- virtual DocumentEventQueue* eventQueue() const { return m_eventQueue.get(); }
+ void enqueueResizeEvent();
+ void enqueueScrollEventForNode(Node*);
+ void enqueueAnimationFrameEvent(PassRefPtr<Event>);
const QualifiedName& idAttributeName() const { return m_idAttributeName; }
@@ -977,7 +917,7 @@ public:
const DocumentTiming* timing() const { return &m_documentTiming; }
- int requestAnimationFrame(PassRefPtr<RequestAnimationFrameCallback>);
+ int requestAnimationFrame(PassOwnPtr<RequestAnimationFrameCallback>);
void cancelAnimationFrame(int id);
void serviceScriptedAnimations(double monotonicAnimationStartTime);
@@ -1000,17 +940,15 @@ public:
bool isInDocumentWrite() { return m_writeRecursionDepth > 0; }
- void suspendScheduledTasks(ActiveDOMObject::ReasonForSuspension);
- void resumeScheduledTasks();
-
IntSize initialViewportSize() const;
- Prerenderer* prerenderer() { return m_prerenderer.get(); }
-
- TextAutosizer* textAutosizer() { return m_textAutosizer.get(); }
+ // There are currently two parallel autosizing implementations: TextAutosizer and FastTextAutosizer.
+ // See http://tinyurl.com/chromium-fast-autosizer for more details.
+ TextAutosizer* textAutosizer();
+ FastTextAutosizer* fastTextAutosizer();
PassRefPtr<Element> createElement(const AtomicString& localName, const AtomicString& typeExtension, ExceptionState&);
- PassRefPtr<Element> createElementNS(const AtomicString& namespaceURI, const String& qualifiedName, const AtomicString& typeExtension, ExceptionState&);
+ PassRefPtr<Element> createElementNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, const AtomicString& typeExtension, ExceptionState&);
ScriptValue registerElement(WebCore::ScriptState*, const AtomicString& name, ExceptionState&);
ScriptValue registerElement(WebCore::ScriptState*, const AtomicString& name, const Dictionary& options, ExceptionState&, CustomElement::NameSet validNames = CustomElement::StandardNames);
CustomElementRegistrationContext* registrationContext() { return m_registrationContext.get(); }
@@ -1020,8 +958,8 @@ public:
bool haveImportsLoaded() const;
void didLoadAllImports();
- void adjustFloatQuadsForScrollAndAbsoluteZoom(Vector<FloatQuad>&, RenderObject*);
- void adjustFloatRectForScrollAndAbsoluteZoom(FloatRect&, RenderObject*);
+ void adjustFloatQuadsForScrollAndAbsoluteZoom(Vector<FloatQuad>&, RenderObject&);
+ void adjustFloatRectForScrollAndAbsoluteZoom(FloatRect&, RenderObject&);
bool hasActiveParser();
unsigned activeParserCount() { return m_activeParserCount; }
@@ -1029,7 +967,7 @@ public:
void decrementActiveParserCount();
void setContextFeatures(PassRefPtr<ContextFeatures>);
- ContextFeatures* contextFeatures() { return m_contextFeatures.get(); }
+ ContextFeatures* contextFeatures() const { return m_contextFeatures.get(); }
DocumentSharedObjectPool* sharedObjectPool() { return m_sharedObjectPool.get(); }
@@ -1043,7 +981,10 @@ public:
// Return a Locale for the default locale if the argument is null or empty.
Locale& getCachedLocale(const AtomicString& locale = nullAtom);
+ AnimationClock& animationClock() { return *m_animationClock; }
DocumentTimeline* timeline() const { return m_timeline.get(); }
+ DocumentTimeline* transitionTimeline() const { return m_transitionTimeline.get(); }
+ CSSPendingAnimations& cssPendingAnimations() { return m_cssPendingAnimations; }
void addToTopLayer(Element*, const Element* before = 0);
void removeFromTopLayer(Element*);
@@ -1062,8 +1003,9 @@ public:
virtual DOMWindow* executingWindow() OVERRIDE { return domWindow(); }
virtual void userEventWasHandled() OVERRIDE { resetLastHandledUserGestureTimestamp(); }
- PassRefPtr<FontFaceSet> fonts();
- DocumentLifecycleNotifier* lifecycleNotifier();
+ DocumentLifecycleNotifier& lifecycleNotifier();
+ bool isActive() const { return m_lifecyle.state() == DocumentLifecycle::Active; }
+ bool isStopped() const { return m_lifecyle.state() == DocumentLifecycle::Stopped; }
enum HttpRefreshType {
HttpRefreshFromHeader,
@@ -1071,6 +1013,9 @@ public:
};
void maybeHandleHttpRefresh(const String&, HttpRefreshType);
+ void updateSecurityOrigin(PassRefPtr<SecurityOrigin>);
+ PassOwnPtr<LifecycleNotifier<Document> > createLifecycleNotifier();
+
protected:
Document(const DocumentInit&, DocumentClassFlags = DefaultDocumentClass);
@@ -1080,17 +1025,20 @@ protected:
virtual void dispose() OVERRIDE;
+ virtual PassRefPtr<Document> cloneDocumentWithoutChildren();
+
private:
friend class Node;
friend class IgnoreDestructiveWriteCountIncrementer;
+ ScriptedAnimationController& ensureScriptedAnimationController();
+ virtual SecurityContext& securityContext() OVERRIDE { return *this; }
+ virtual EventQueue* eventQueue() const FINAL;
+
void updateDistributionIfNeeded();
void detachParser();
- typedef void (*ArgumentsCallback)(const String& keyString, const String& valueString, Document*, void* data);
- void processArguments(const String& features, void* data, ArgumentsCallback);
-
virtual bool isDocument() const OVERRIDE { return true; }
virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0);
@@ -1099,14 +1047,15 @@ private:
virtual NodeType nodeType() const;
virtual bool childTypeAllowed(NodeType) const;
virtual PassRefPtr<Node> cloneNode(bool deep = true);
+ void cloneDataFromDocument(const Document&);
- virtual void refScriptExecutionContext() { ref(); }
- virtual void derefScriptExecutionContext() { deref(); }
- virtual PassOwnPtr<LifecycleNotifier> createLifecycleNotifier() OVERRIDE;
+ virtual void refExecutionContext() { ref(); }
+ virtual void derefExecutionContext() { deref(); }
- virtual const KURL& virtualURL() const; // Same as url(), but needed for ScriptExecutionContext to implement it without a performance loss for direct calls.
+ virtual const KURL& virtualURL() const; // Same as url(), but needed for ExecutionContext to implement it without a performance loss for direct calls.
virtual KURL virtualCompleteURL(const String&) const; // Same as completeURL() for the same reason as above.
+ virtual void reportBlockedScriptExecutionToInspector(const String& directiveText) OVERRIDE;
virtual void addMessage(MessageSource, MessageLevel, const String& message, const String& sourceURL, unsigned lineNumber, ScriptState*);
void internalAddMessage(MessageSource, MessageLevel, const String& message, const String& sourceURL, unsigned lineNumber, PassRefPtr<ScriptCallStack>, ScriptState*);
@@ -1116,8 +1065,6 @@ private:
void updateFocusAppearanceTimerFired(Timer<Document>*);
void updateBaseURL();
- void createStyleResolver();
-
void executeScriptsWaitingForResourcesIfNeeded();
void seamlessParentUpdatedStylesheets();
@@ -1128,14 +1075,7 @@ private:
void loadEventDelayTimerFired(Timer<Document>*);
- void pendingTasksTimerFired(Timer<Document>*);
-
- static void didReceiveTask(void*);
-
- template <typename CharacterType>
- void displayBufferModifiedByEncodingInternal(CharacterType*, unsigned) const;
-
- PageVisibilityState visibilityState() const;
+ PageVisibilityState pageVisibilityState() const;
PassRefPtr<HTMLCollection> ensureCachedCollection(CollectionType);
@@ -1150,22 +1090,16 @@ private:
void didAssociateFormControlsTimerFired(Timer<Document>*);
void styleResolverThrowawayTimerFired(Timer<Document>*);
- void processHttpEquivDefaultStyle(const String& content);
- void processHttpEquivRefresh(const String& content);
- void processHttpEquivSetCookie(const String& content);
- void processHttpEquivXFrameOptions(const String& content);
- void processHttpEquivContentSecurityPolicy(const String& equiv, const String& content);
+ void processHttpEquivDefaultStyle(const AtomicString& content);
+ void processHttpEquivRefresh(const AtomicString& content);
+ void processHttpEquivSetCookie(const AtomicString& content);
+ void processHttpEquivXFrameOptions(const AtomicString& content);
+ void processHttpEquivContentSecurityPolicy(const AtomicString& equiv, const AtomicString& content);
- Timer<Document> m_styleResolverThrowawayTimer;
- double m_lastStyleResolverAccessTime;
+ DocumentLifecycle m_lifecyle;
- OwnPtr<StyleResolver> m_styleResolver;
- bool m_didCalculateStyleResolver;
bool m_hasNodesWithPlaceholderStyle;
bool m_needsNotifyRemoveAllPendingStylesheet;
- // But sometimes you need to ignore pending stylesheet count to
- // force an immediate layout when requested by JS.
- bool m_ignorePendingStylesheets;
bool m_evaluateMediaQueriesOnStyleRecalc;
// If we do ignore the pending stylesheet count, then we need to add a boolean
@@ -1208,8 +1142,6 @@ private:
bool m_printing;
bool m_paginatedForScreen;
- bool m_ignoreAutofocus;
-
CompatibilityMode m_compatibilityMode;
bool m_compatibilityModeLocked; // This is cheaper than making setCompatibilityMode virtual.
@@ -1236,7 +1168,7 @@ private:
OwnPtr<FormController> m_formController;
TextLinkColors m_textLinkColors;
- OwnPtr<VisitedLinkState> m_visitedLinkState;
+ const OwnPtr<VisitedLinkState> m_visitedLinkState;
bool m_loadingSheet;
bool m_visuallyOrdered;
@@ -1251,6 +1183,7 @@ private:
bool m_haveExplicitlyDisabledDNSPrefetch;
bool m_containsValidityStyleRules;
bool m_updateFocusAppearanceRestoresSelection;
+ bool m_containsPlugins;
// http://www.whatwg.org/specs/web-apps/current-work/#ignore-destructive-writes-counter
unsigned m_ignoreDestructiveWriteCount;
@@ -1269,7 +1202,6 @@ private:
LoadEventProgress m_loadEventProgress;
- RefPtr<SerializedScriptValue> m_pendingStateObject;
double m_startTime;
bool m_overMinimumLayoutThreshold;
@@ -1285,10 +1217,9 @@ private:
unsigned m_xmlStandalone : 2;
unsigned m_hasXMLDeclaration : 1;
- String m_contentLanguage;
+ AtomicString m_contentLanguage;
- RefPtr<TextResourceDecoder> m_decoder;
- WTF::TextEncoding m_encoding;
+ DocumentEncodingData m_encodingData;
InheritedBool m_designMode;
@@ -1303,8 +1234,6 @@ private:
HashMap<String, RefPtr<HTMLCanvasElement> > m_cssCanvasElements;
- Vector<IconURL> m_iconURLs;
-
OwnPtr<SelectorQueryCache> m_selectorQueryCache;
bool m_useSecureKeyboardEntryWhenActive;
@@ -1315,9 +1244,11 @@ private:
bool m_sawElementsInKnownNamespaces;
bool m_isSrcdocDocument;
bool m_isMobileDocument;
+ // Set in Document::initSecurityContext() at Document creation, per:
+ // http://www.whatwg.org/specs/web-apps/current-work/#attr-iframe-seamless
+ bool m_mayDisplaySeamlesslyWithParent;
- RenderObject* m_renderer;
- RefPtr<DocumentEventQueue> m_eventQueue;
+ RenderView* m_renderView;
WeakPtrFactory<Document> m_weakFactory;
WeakPtr<Document> m_contextDocument;
@@ -1331,8 +1262,8 @@ private:
int m_loadEventDelayCount;
Timer<Document> m_loadEventDelayTimer;
- ViewportArguments m_viewportArguments;
- ViewportArguments m_legacyViewportArguments;
+ ViewportDescription m_viewportDescription;
+ ViewportDescription m_legacyViewportDescription;
ReferrerPolicy m_referrerPolicy;
@@ -1348,18 +1279,12 @@ private:
double m_lastHandledUserGestureTimestamp;
RefPtr<ScriptedAnimationController> m_scriptedAnimationController;
-
- Timer<Document> m_pendingTasksTimer;
- Vector<OwnPtr<Task> > m_pendingTasks;
-
- OwnPtr<Prerenderer> m_prerenderer;
-
+ OwnPtr<MainThreadTaskRunner> m_taskRunner;
OwnPtr<TextAutosizer> m_textAutosizer;
+ OwnPtr<FastTextAutosizer> m_fastTextAutosizer;
RefPtr<CustomElementRegistrationContext> m_registrationContext;
- bool m_scheduledTasksAreSuspended;
-
RefPtr<NamedFlowCollection> m_namedFlows;
RefPtr<DOMSecurityPolicy> m_domSecurityPolicy;
@@ -1376,13 +1301,14 @@ private:
typedef HashMap<AtomicString, OwnPtr<Locale> > LocaleIdentifierToLocaleMap;
LocaleIdentifierToLocaleMap m_localeCache;
+ OwnPtr<AnimationClock> m_animationClock;
RefPtr<DocumentTimeline> m_timeline;
+ RefPtr<DocumentTimeline> m_transitionTimeline;
+ CSSPendingAnimations m_cssPendingAnimations;
RefPtr<Document> m_templateDocument;
Document* m_templateDocumentHost; // Manually managed weakref (backpointer from m_templateDocument).
- RefPtr<FontFaceSet> m_fonts;
-
Timer<Document> m_didAssociateFormControlsTimer;
HashSet<RefPtr<Element> > m_associatedFormControls;
};
@@ -1402,40 +1328,38 @@ inline const Document* Document::templateDocument() const
return m_templateDocument.get();
}
-inline bool Document::shouldOverrideLegacyViewport(ViewportArguments::Type origin)
+inline bool Document::shouldOverrideLegacyDescription(ViewportDescription::Type origin)
{
// The different (legacy) meta tags have different priorities based on the type
// regardless of which order they appear in the DOM. The priority is given by the
- // ViewportArguments::Type enum.
- return origin >= m_legacyViewportArguments.type;
+ // ViewportDescription::Type enum.
+ return origin >= m_legacyViewportDescription.type;
}
-inline Document* toDocument(ScriptExecutionContext* scriptExecutionContext)
+inline Document* toDocument(ExecutionContext* executionContext)
{
- ASSERT_WITH_SECURITY_IMPLICATION(!scriptExecutionContext || scriptExecutionContext->isDocument());
- return static_cast<Document*>(scriptExecutionContext);
+ ASSERT_WITH_SECURITY_IMPLICATION(!executionContext || executionContext->isDocument());
+ return static_cast<Document*>(executionContext);
}
-inline const Document* toDocument(const ScriptExecutionContext* scriptExecutionContext)
+inline const Document* toDocument(const ExecutionContext* executionContext)
{
- ASSERT_WITH_SECURITY_IMPLICATION(!scriptExecutionContext || scriptExecutionContext->isDocument());
- return static_cast<const Document*>(scriptExecutionContext);
+ ASSERT_WITH_SECURITY_IMPLICATION(!executionContext || executionContext->isDocument());
+ return static_cast<const Document*>(executionContext);
}
-inline Document* toDocument(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->isDocumentNode());
- return static_cast<Document*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(Document, isDocumentNode());
-inline const Document* toDocument(const Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->isDocumentNode());
- return static_cast<const Document*>(node);
-}
+#define DEFINE_DOCUMENT_TYPE_CASTS(thisType) \
+ DEFINE_TYPE_CASTS(thisType, Document, document, document->is##thisType(), document.is##thisType())
-// This will catch anyone doing an unnecessary cast.
-void toDocument(const Document*);
+// All these varations are needed to avoid ambiguous overloads with the Node and TreeScope versions.
+inline bool operator==(const Document& a, const Document& b) { return &a == &b; }
+inline bool operator==(const Document& a, const Document* b) { return &a == b; }
+inline bool operator==(const Document* a, const Document& b) { return a == &b; }
+inline bool operator!=(const Document& a, const Document& b) { return !(a == b); }
+inline bool operator!=(const Document& a, const Document* b) { return !(a == b); }
+inline bool operator!=(const Document* a, const Document& b) { return !(a == b); }
// Put these methods here, because they require the Document definition, but we really want to inline them.
diff --git a/chromium/third_party/WebKit/Source/core/dom/Document.idl b/chromium/third_party/WebKit/Source/core/dom/Document.idl
index a18606dcb1c..366966261f7 100644
--- a/chromium/third_party/WebKit/Source/core/dom/Document.idl
+++ b/chromium/third_party/WebKit/Source/core/dom/Document.idl
@@ -21,7 +21,7 @@
callback CustomElementConstructor = Element ();
[
- CustomToV8
+ SpecialWrapFor=HTMLDocument|SVGDocument
] interface Document : Node {
// DOM Level 1 Core
@@ -29,64 +29,56 @@ callback CustomElementConstructor = Element ();
readonly attribute DOMImplementation implementation;
readonly attribute Element documentElement;
- [CustomElementCallbacks=Enable, PerWorldBindings, ActivityLog=AccessForIsolatedWorlds, RaisesException] Element createElement([TreatNullAs=NullString,Default=Undefined] optional DOMString tagName);
- DocumentFragment createDocumentFragment();
- [PerWorldBindings] Text createTextNode([Default=Undefined] optional DOMString data);
- Comment createComment([Default=Undefined] optional DOMString data);
+ [CustomElementCallbacks, PerWorldBindings, ActivityLogging=ForIsolatedWorlds, RaisesException] Element createElement(DOMString tagName);
+ DocumentFragment createDocumentFragment();
+ [PerWorldBindings] Text createTextNode(DOMString data);
+ Comment createComment(DOMString data);
[RaisesException, MeasureAs=DocumentCreateCDATASection] CDATASection createCDATASection([Default=Undefined] optional DOMString data); // Removed from DOM4.
- [RaisesException] ProcessingInstruction createProcessingInstruction([Default=Undefined] optional DOMString target,
- [Default=Undefined] optional DOMString data);
+ [RaisesException] ProcessingInstruction createProcessingInstruction(DOMString target, DOMString data);
[RaisesException, MeasureAs=DocumentCreateAttribute] Attr createAttribute([Default=Undefined] optional DOMString name); // Removed from DOM4.
- [PerWorldBindings] NodeList getElementsByTagName([Default=Undefined] optional DOMString tagname);
+ [PerWorldBindings] NodeList getElementsByTagName(DOMString localName);
// Introduced in DOM Level 2:
- [CustomElementCallbacks=Enable, PerWorldBindings, ActivityLog=AccessForIsolatedWorlds, RaisesException] Node importNode([Default=Undefined] optional Node importedNode,
- optional boolean deep);
- [CustomElementCallbacks=Enable, PerWorldBindings, ActivityLog=AccessForIsolatedWorlds, RaisesException] Element createElementNS([TreatNullAs=NullString,Default=Undefined] optional DOMString namespaceURI,
- [TreatNullAs=NullString,Default=Undefined] optional DOMString qualifiedName);
+ [CustomElementCallbacks, PerWorldBindings, ActivityLogging=ForIsolatedWorlds, RaisesException] Node importNode(Node node, optional boolean deep);
+ [CustomElementCallbacks, PerWorldBindings, ActivityLogging=ForIsolatedWorlds, RaisesException] Element createElementNS([TreatNullAs=NullString] DOMString namespaceURI, DOMString qualifiedName);
[RaisesException, MeasureAs=DocumentCreateAttributeNS] Attr createAttributeNS([TreatNullAs=NullString,Default=Undefined] optional DOMString namespaceURI,
[TreatNullAs=NullString,Default=Undefined] optional DOMString qualifiedName); // Removed from DOM4.
- NodeList getElementsByTagNameNS([TreatNullAs=NullString,Default=Undefined] optional DOMString namespaceURI,
- [Default=Undefined] optional DOMString localName);
- [PerWorldBindings] Element getElementById([Default=Undefined] optional DOMString elementId);
+ NodeList getElementsByTagNameNS([TreatNullAs=NullString] DOMString namespaceURI, DOMString localName);
+ [PerWorldBindings] Element getElementById(DOMString elementId);
// DOM Level 3 Core
[TreatReturnedNullStringAs=Null, MeasureAs=DocumentInputEncoding] readonly attribute DOMString inputEncoding; // Removed from DOM4.
[TreatReturnedNullStringAs=Null, MeasureAs=DocumentXMLEncoding] readonly attribute DOMString xmlEncoding; // Removed from DOM4.
- [TreatReturnedNullStringAs=Null, TreatNullAs=NullString, SetterRaisesException, MeasureAs=DocumentXMLVersion] attribute DOMString xmlVersion; // Removed from DOM4.
- [SetterRaisesException, MeasureAs=DocumentXMLStandalone] attribute boolean xmlStandalone; // Removed from DOM4.
+ [TreatReturnedNullStringAs=Null, TreatNullAs=NullString, RaisesException=Setter, MeasureAs=DocumentXMLVersion] attribute DOMString xmlVersion; // Removed from DOM4.
+ [RaisesException=Setter, MeasureAs=DocumentXMLStandalone] attribute boolean xmlStandalone; // Removed from DOM4.
- [RaisesException, CustomElementCallbacks=Enable] Node adoptNode([Default=Undefined] optional Node source);
+ [RaisesException, CustomElementCallbacks] Node adoptNode(Node node);
[TreatReturnedNullStringAs=Null] readonly attribute DOMString documentURI;
// DOM Level 2 Events (DocumentEvents interface)
- [RaisesException] Event createEvent([Default=Undefined] optional DOMString eventType);
+ [RaisesException] Event createEvent(DOMString eventType);
// DOM Level 2 Traversal and Range (DocumentRange interface)
- Range createRange();
+ Range createRange();
// DOM Level 2 Traversal and Range (DocumentTraversal interface)
- // In DOM4, the fourth argument |expandEntityReferences| is removed.
- // Historically, this argument was never implemented and has been ignored.
- // We still receive the argument to keep compatibility, but don't do anything if it's specified.
+
[RaisesException] NodeIterator createNodeIterator(Node root,
optional unsigned long whatToShow,
- optional NodeFilter filter,
- optional boolean expandEntityReferences);
+ optional NodeFilter filter);
[RaisesException] TreeWalker createTreeWalker(Node root,
optional unsigned long whatToShow,
- optional NodeFilter filter,
- optional boolean expandEntityReferences);
+ optional NodeFilter filter);
// DOM Level 2 Abstract Views (DocumentView interface)
- readonly attribute Window defaultView;
+ [ImplementedAs=domWindow] readonly attribute Window defaultView;
// DOM Level 2 Style (DocumentStyle interface)
@@ -98,7 +90,7 @@ callback CustomElementConstructor = Element ();
[Default=Undefined] optional DOMString pseudoElement);
// Common extensions
- [CustomElementCallbacks=Enable]
+ [CustomElementCallbacks]
boolean execCommand([Default=Undefined] optional DOMString command,
[Default=Undefined] optional boolean userInterface,
[TreatNullAs=NullString, TreatUndefinedAs=NullString,Default=Undefined] optional DOMString value);
@@ -111,14 +103,14 @@ callback CustomElementConstructor = Element ();
// Moved down from HTMLDocument
- [TreatNullAs=NullString, CustomElementCallbacks=Enable] attribute DOMString title;
+ [TreatNullAs=NullString, CustomElementCallbacks] attribute DOMString title;
readonly attribute DOMString referrer;
- [TreatNullAs=NullString, SetterRaisesException] attribute DOMString domain;
+ [TreatNullAs=NullString, RaisesException=Setter] attribute DOMString domain;
readonly attribute DOMString URL;
- [TreatNullAs=NullString, GetterRaisesException, SetterRaisesException] attribute DOMString cookie;
+ [TreatNullAs=NullString, RaisesException] attribute DOMString cookie;
- [SetterRaisesException, CustomElementCallbacks=Enable] attribute HTMLElement body;
+ [RaisesException=Setter, CustomElementCallbacks] attribute HTMLElement body;
readonly attribute HTMLHeadElement head;
readonly attribute HTMLCollection images;
@@ -130,7 +122,7 @@ callback CustomElementConstructor = Element ();
[PerWorldBindings] NodeList getElementsByName([Default=Undefined] optional DOMString elementName);
- [Custom, Replaceable, PerWorldBindings, ActivityLog=AccessForIsolatedWorlds] readonly attribute Location location;
+ [PerWorldBindings, ActivityLogging=ForIsolatedWorlds, PutForwards=href] readonly attribute Location location;
// IE extensions
[MeasureAs=DocumentCharset, TreatReturnedNullStringAs=Undefined, TreatNullAs=NullString] attribute DOMString charset;
@@ -154,7 +146,7 @@ callback CustomElementConstructor = Element ();
CanvasRenderingContext getCSSCanvasContext(DOMString contextId, DOMString name, long width, long height);
// HTML 5
- NodeList getElementsByClassName([Default=Undefined] optional DOMString tagname);
+ NodeList getElementsByClassName(DOMString classNames);
readonly attribute DOMString compatMode;
@@ -165,90 +157,31 @@ callback CustomElementConstructor = Element ();
void webkitExitPointerLock();
readonly attribute Element webkitPointerLockElement;
- [EnabledAtRuntime=CSSRegions] WebKitNamedFlowCollection webkitGetNamedFlows();
-
- [EnabledAtRuntime=FontLoadEvents] readonly attribute FontFaceSet fonts;
-
- // Event handler DOM attributes
- [NotEnumerable] attribute EventHandler onabort;
- [NotEnumerable] attribute EventHandler onblur;
- [NotEnumerable] attribute EventHandler onchange;
- [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onclick;
- [NotEnumerable] attribute EventHandler oncontextmenu;
- [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler ondblclick;
- [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler ondrag;
- [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler ondragend;
- [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler ondragenter;
- [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler ondragleave;
- [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler ondragover;
- [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler ondragstart;
- [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler ondrop;
- [NotEnumerable] attribute EventHandler onerror;
- [NotEnumerable] attribute EventHandler onfocus;
- [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler oninput;
- [NotEnumerable] attribute EventHandler oninvalid;
- [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onkeydown;
- [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onkeypress;
- [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onkeyup;
- [NotEnumerable] attribute EventHandler onload;
- [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onmousedown;
- [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onmouseenter;
- [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onmouseleave;
- [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onmousemove;
- [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onmouseout;
- [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onmouseover;
- [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onmouseup;
- [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onmousewheel; // Deprecated in favor of onwheel.
- [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onwheel;
- [NotEnumerable] attribute EventHandler onreadystatechange;
- [NotEnumerable] attribute EventHandler onscroll;
- [NotEnumerable] attribute EventHandler onselect;
- [NotEnumerable] attribute EventHandler onsubmit;
-
- // attribute [NotEnumerable] EventHandler oncanplay;
- // attribute [NotEnumerable] EventHandler oncanplaythrough;
- // attribute [NotEnumerable] EventHandler ondurationchange;
- // attribute [NotEnumerable] EventHandler onemptied;
- // attribute [NotEnumerable] EventHandler onended;
- // attribute [NotEnumerable] EventHandler onloadeddata;
- // attribute [NotEnumerable] EventHandler onloadedmetadata;
- // attribute [NotEnumerable] EventHandler onloadstart;
- // attribute [NotEnumerable] EventHandler onpause;
- // attribute [NotEnumerable] EventHandler onplay;
- // attribute [NotEnumerable] EventHandler onplaying;
- // attribute [NotEnumerable] EventHandler onprogress;
- // attribute [NotEnumerable] EventHandler onratechange;
- // attribute [NotEnumerable] EventHandler onseeked;
- // attribute [NotEnumerable] EventHandler onseeking;
- // attribute [NotEnumerable] EventHandler onshow;
- // attribute [NotEnumerable] EventHandler onstalled;
- // attribute [NotEnumerable] EventHandler onsuspend;
- // attribute [NotEnumerable] EventHandler ontimeupdate;
- // attribute [NotEnumerable] EventHandler onvolumechange;
- // attribute [NotEnumerable] EventHandler onwaiting;
-
- // WebKit extensions
- [NotEnumerable] attribute EventHandler onbeforecut;
- [NotEnumerable] attribute EventHandler oncut;
- [NotEnumerable] attribute EventHandler onbeforecopy;
- [NotEnumerable] attribute EventHandler oncopy;
- [NotEnumerable] attribute EventHandler onbeforepaste;
- [NotEnumerable] attribute EventHandler onpaste;
- [NotEnumerable] attribute EventHandler onreset;
- [NotEnumerable] attribute EventHandler onsearch;
- [NotEnumerable] attribute EventHandler onselectstart;
- [NotEnumerable] attribute EventHandler onselectionchange;
- [NotEnumerable, EnabledAtRuntime=Touch] attribute EventHandler ontouchstart;
- [NotEnumerable, EnabledAtRuntime=Touch] attribute EventHandler ontouchmove;
- [NotEnumerable, EnabledAtRuntime=Touch] attribute EventHandler ontouchend;
- [NotEnumerable, EnabledAtRuntime=Touch] attribute EventHandler ontouchcancel;
- [NotEnumerable] attribute EventHandler onwebkitfullscreenchange;
- [NotEnumerable] attribute EventHandler onwebkitfullscreenerror;
- [NotEnumerable] attribute EventHandler onwebkitpointerlockchange;
- [NotEnumerable] attribute EventHandler onwebkitpointerlockerror;
- [NotEnumerable, EnabledAtRuntime=ExperimentalContentSecurityPolicyFeatures] attribute EventHandler onsecuritypolicyviolation;
-
- [EnabledAtRuntime=Touch] Touch createTouch([Default=Undefined] optional Window window,
+ [RuntimeEnabled=CSSRegions] WebKitNamedFlowCollection webkitGetNamedFlows();
+
+ // Event handler attributes
+ attribute EventHandler onbeforecopy;
+ attribute EventHandler onbeforecut;
+ attribute EventHandler onbeforepaste;
+ attribute EventHandler oncopy;
+ attribute EventHandler oncut;
+ attribute EventHandler onpaste;
+ attribute EventHandler onreadystatechange;
+ attribute EventHandler onsearch;
+ [RuntimeEnabled=ExperimentalContentSecurityPolicyFeatures] attribute EventHandler onsecuritypolicyviolation;
+ attribute EventHandler onselectionchange;
+ attribute EventHandler onselectstart;
+ [RuntimeEnabled=Touch] attribute EventHandler ontouchcancel;
+ [RuntimeEnabled=Touch] attribute EventHandler ontouchend;
+ [RuntimeEnabled=Touch] attribute EventHandler ontouchmove;
+ [RuntimeEnabled=Touch] attribute EventHandler ontouchstart;
+ attribute EventHandler onwebkitfullscreenchange;
+ attribute EventHandler onwebkitfullscreenerror;
+ attribute EventHandler onwebkitpointerlockchange;
+ attribute EventHandler onwebkitpointerlockerror;
+ [PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute EventHandler onwheel;
+
+ [RuntimeEnabled=Touch] Touch createTouch([Default=Undefined] optional Window window,
[Default=Undefined] optional EventTarget target,
[Default=Undefined] optional long identifier,
[Default=Undefined] optional long pageX,
@@ -259,23 +192,28 @@ callback CustomElementConstructor = Element ();
[Default=Undefined] optional long webkitRadiusY,
[Default=Undefined] optional float webkitRotationAngle,
[Default=Undefined] optional float webkitForce);
- [EnabledAtRuntime=Touch] TouchList createTouchList(Touch... touches);
+ [RuntimeEnabled=Touch] TouchList createTouchList(Touch... touches);
- [DeprecateAs=PrefixedDocumentRegister, EnabledAtRuntime=CustomElements, ImplementedAs=registerElement, CallWith=ScriptState, CustomElementCallbacks=Enable, RaisesException] CustomElementConstructor webkitRegister(DOMString name, optional Dictionary options);
- [EnabledAtRuntime=CustomElements, ImplementedAs=registerElement, CallWith=ScriptState, CustomElementCallbacks=Enable, RaisesException] CustomElementConstructor register(DOMString name, optional Dictionary options);
- [CustomElementCallbacks=Enable, PerWorldBindings, ActivityLog=AccessForIsolatedWorlds, RaisesException] Element createElement(DOMString localName, [TreatNullAs=NullString] DOMString typeExtension);
- [CustomElementCallbacks=Enable, PerWorldBindings, ActivityLog=AccessForIsolatedWorlds, RaisesException] Element createElementNS([TreatNullAs=NullString] DOMString namespaceURI, DOMString qualifiedName,
+ [RuntimeEnabled=CustomElements, CallWith=ScriptState, CustomElementCallbacks, RaisesException] CustomElementConstructor registerElement(DOMString name, optional Dictionary options);
+ [CustomElementCallbacks, PerWorldBindings, ActivityLogging=ForIsolatedWorlds, RaisesException] Element createElement(DOMString localName, [TreatNullAs=NullString] DOMString typeExtension);
+ [CustomElementCallbacks, PerWorldBindings, ActivityLogging=ForIsolatedWorlds, RaisesException] Element createElementNS([TreatNullAs=NullString] DOMString namespaceURI, DOMString qualifiedName,
[TreatNullAs=NullString] DOMString typeExtension);
// Page visibility API.
- readonly attribute DOMString webkitVisibilityState;
- readonly attribute boolean webkitHidden;
+ readonly attribute DOMString visibilityState;
+ readonly attribute boolean hidden;
+
+ // Deprecated prefixed page visibility API.
+ // TODO(davidben): This is a property so attaching a deprecation warning results in false positives when outputting
+ // document in the console. It's possible http://crbug.com/43394 will resolve this.
+ [MeasureAs=PrefixedPageVisibility, ImplementedAs=visibilityState] readonly attribute DOMString webkitVisibilityState;
+ [MeasureAs=PrefixedPageVisibility, ImplementedAs=hidden] readonly attribute boolean webkitHidden;
// Security Policy API: http://dvcs.w3.org/hg/content-security-policy/raw-file/tip/csp-specification.dev.html#script-interfaces
- [EnabledAtRuntime=ExperimentalContentSecurityPolicyFeatures] readonly attribute SecurityPolicy securityPolicy;
+ [RuntimeEnabled=ExperimentalContentSecurityPolicyFeatures] readonly attribute SecurityPolicy securityPolicy;
readonly attribute HTMLScriptElement currentScript;
};
+Document implements GlobalEventHandlers;
Document implements ParentNode;
-
diff --git a/chromium/third_party/WebKit/Source/core/dom/DocumentEncodingData.h b/chromium/third_party/WebKit/Source/core/dom/DocumentEncodingData.h
new file mode 100644
index 00000000000..5a696afdd17
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/DocumentEncodingData.h
@@ -0,0 +1,52 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef DocumentEncodingData_h
+#define DocumentEncodingData_h
+
+#include "wtf/text/TextEncoding.h"
+
+namespace WebCore {
+
+struct DocumentEncodingData {
+ DocumentEncodingData()
+ : wasDetectedHeuristically(false)
+ , sawDecodingError(false)
+ {
+ }
+
+ WTF::TextEncoding encoding;
+ bool wasDetectedHeuristically;
+ bool sawDecodingError;
+};
+
+} // namespace WebCore
+
+#endif // DocumentEncodingData_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/DocumentEventQueue.cpp b/chromium/third_party/WebKit/Source/core/dom/DocumentEventQueue.cpp
deleted file mode 100644
index eba99c1fabc..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/DocumentEventQueue.cpp
+++ /dev/null
@@ -1,147 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-#include "config.h"
-#include "core/dom/DocumentEventQueue.h"
-
-#include "core/dom/Document.h"
-#include "core/dom/Event.h"
-#include "core/dom/EventNames.h"
-#include "core/page/DOMWindow.h"
-#include "core/page/SuspendableTimer.h"
-
-namespace WebCore {
-
-class DocumentEventQueueTimer : public SuspendableTimer {
- WTF_MAKE_NONCOPYABLE(DocumentEventQueueTimer);
-public:
- DocumentEventQueueTimer(DocumentEventQueue* eventQueue, ScriptExecutionContext* context)
- : SuspendableTimer(context)
- , m_eventQueue(eventQueue) { }
-
-private:
- virtual void fired() { m_eventQueue->pendingEventTimerFired(); }
- DocumentEventQueue* m_eventQueue;
-};
-
-PassRefPtr<DocumentEventQueue> DocumentEventQueue::create(ScriptExecutionContext* context)
-{
- return adoptRef(new DocumentEventQueue(context));
-}
-
-DocumentEventQueue::DocumentEventQueue(ScriptExecutionContext* context)
- : m_pendingEventTimer(adoptPtr(new DocumentEventQueueTimer(this, context)))
- , m_isClosed(false)
-{
- m_pendingEventTimer->suspendIfNeeded();
-}
-
-DocumentEventQueue::~DocumentEventQueue()
-{
-}
-
-bool DocumentEventQueue::enqueueEvent(PassRefPtr<Event> event)
-{
- if (m_isClosed)
- return false;
-
- ASSERT(event->target());
- bool wasAdded = m_queuedEvents.add(event).isNewEntry;
- ASSERT_UNUSED(wasAdded, wasAdded); // It should not have already been in the list.
-
- if (!m_pendingEventTimer->isActive())
- m_pendingEventTimer->startOneShot(0);
-
- return true;
-}
-
-void DocumentEventQueue::enqueueOrDispatchScrollEvent(PassRefPtr<Node> target, ScrollEventTargetType targetType)
-{
- if (!target->document().hasListenerType(Document::SCROLL_LISTENER))
- return;
-
- // Per the W3C CSSOM View Module, scroll events fired at the document should bubble, others should not.
- RefPtr<Event> scrollEvent = targetType == ScrollEventDocumentTarget ? Event::createBubble(eventNames().scrollEvent) : Event::create(eventNames().scrollEvent);
-
- if (!m_nodesWithQueuedScrollEvents.add(target.get()).isNewEntry)
- return;
-
- scrollEvent->setTarget(target);
- enqueueEvent(scrollEvent.release());
-}
-
-bool DocumentEventQueue::cancelEvent(Event* event)
-{
- ListHashSet<RefPtr<Event>, 16>::iterator it = m_queuedEvents.find(event);
- bool found = it != m_queuedEvents.end();
- if (found)
- m_queuedEvents.remove(it);
- if (m_queuedEvents.isEmpty())
- m_pendingEventTimer->stop();
- return found;
-}
-
-void DocumentEventQueue::close()
-{
- m_isClosed = true;
- m_pendingEventTimer->stop();
- m_queuedEvents.clear();
-}
-
-void DocumentEventQueue::pendingEventTimerFired()
-{
- ASSERT(!m_pendingEventTimer->isActive());
- ASSERT(!m_queuedEvents.isEmpty());
-
- m_nodesWithQueuedScrollEvents.clear();
-
- // Insert a marker for where we should stop.
- ASSERT(!m_queuedEvents.contains(0));
- bool wasAdded = m_queuedEvents.add(0).isNewEntry;
- ASSERT_UNUSED(wasAdded, wasAdded); // It should not have already been in the list.
-
- RefPtr<DocumentEventQueue> protector(this);
-
- while (!m_queuedEvents.isEmpty()) {
- ListHashSet<RefPtr<Event>, 16>::iterator iter = m_queuedEvents.begin();
- RefPtr<Event> event = *iter;
- m_queuedEvents.remove(iter);
- if (!event)
- break;
- dispatchEvent(event.get());
- }
-}
-
-void DocumentEventQueue::dispatchEvent(PassRefPtr<Event> event)
-{
- EventTarget* eventTarget = event->target();
- if (eventTarget->toDOMWindow())
- eventTarget->toDOMWindow()->dispatchEvent(event, 0);
- else
- eventTarget->dispatchEvent(event);
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/dom/DocumentEventQueue.h b/chromium/third_party/WebKit/Source/core/dom/DocumentEventQueue.h
deleted file mode 100644
index bd8fb76c65a..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/DocumentEventQueue.h
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-#ifndef DocumentEventQueue_h
-#define DocumentEventQueue_h
-
-#include "core/dom/EventQueue.h"
-#include "wtf/Forward.h"
-#include "wtf/HashSet.h"
-#include "wtf/ListHashSet.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/RefCounted.h"
-
-namespace WebCore {
-
-class Event;
-class DocumentEventQueueTimer;
-class Node;
-class ScriptExecutionContext;
-
-class DocumentEventQueue : public RefCounted<DocumentEventQueue>, public EventQueue {
-public:
- enum ScrollEventTargetType {
- ScrollEventDocumentTarget,
- ScrollEventElementTarget
- };
-
- static PassRefPtr<DocumentEventQueue> create(ScriptExecutionContext*);
- virtual ~DocumentEventQueue();
-
- // EventQueue
- virtual bool enqueueEvent(PassRefPtr<Event>) OVERRIDE;
- virtual bool cancelEvent(Event*) OVERRIDE;
- virtual void close() OVERRIDE;
-
- void enqueueOrDispatchScrollEvent(PassRefPtr<Node>, ScrollEventTargetType);
-
-private:
- explicit DocumentEventQueue(ScriptExecutionContext*);
-
- void pendingEventTimerFired();
- void dispatchEvent(PassRefPtr<Event>);
-
- OwnPtr<DocumentEventQueueTimer> m_pendingEventTimer;
- ListHashSet<RefPtr<Event>, 16> m_queuedEvents;
- HashSet<Node*> m_nodesWithQueuedScrollEvents;
- bool m_isClosed;
-
- friend class DocumentEventQueueTimer;
-};
-
-}
-
-#endif // DocumentEventQueue_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/DocumentFragment.h b/chromium/third_party/WebKit/Source/core/dom/DocumentFragment.h
index ed8a76a0b12..4730abcd065 100644
--- a/chromium/third_party/WebKit/Source/core/dom/DocumentFragment.h
+++ b/chromium/third_party/WebKit/Source/core/dom/DocumentFragment.h
@@ -29,7 +29,7 @@
namespace WebCore {
-class ScriptExecutionContext;
+class ExecutionContext;
class DocumentFragment : public ContainerNode {
public:
@@ -51,17 +51,7 @@ private:
virtual bool childTypeAllowed(NodeType) const;
};
-inline DocumentFragment* toDocumentFragment(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->nodeType() == Node::DOCUMENT_FRAGMENT_NODE);
- return static_cast<DocumentFragment*>(node);
-}
-
-inline const DocumentFragment* toDocumentFragment(const Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->nodeType() == Node::DOCUMENT_FRAGMENT_NODE);
- return static_cast<const DocumentFragment*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(DocumentFragment, nodeType() == Node::DOCUMENT_FRAGMENT_NODE);
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/DocumentFragment.idl b/chromium/third_party/WebKit/Source/core/dom/DocumentFragment.idl
index 942f021f7c8..4f1ecf98231 100644
--- a/chromium/third_party/WebKit/Source/core/dom/DocumentFragment.idl
+++ b/chromium/third_party/WebKit/Source/core/dom/DocumentFragment.idl
@@ -19,7 +19,7 @@
[
Constructor,
- ConstructorCallWith=Document
+ ConstructorCallWith=Document,
] interface DocumentFragment : Node {
// NodeSelector - Selector API
[RaisesException] Element querySelector(DOMString selectors);
@@ -27,4 +27,3 @@
};
DocumentFragment implements ParentNode;
-
diff --git a/chromium/third_party/WebKit/Source/core/dom/DocumentFullscreen.idl b/chromium/third_party/WebKit/Source/core/dom/DocumentFullscreen.idl
index 3081eacb3ab..561ad8018b4 100644
--- a/chromium/third_party/WebKit/Source/core/dom/DocumentFullscreen.idl
+++ b/chromium/third_party/WebKit/Source/core/dom/DocumentFullscreen.idl
@@ -20,13 +20,13 @@
*/
partial interface Document {
// Mozilla version
- [EnabledAtRuntime=Fullscreen] readonly attribute boolean webkitIsFullScreen;
- [EnabledAtRuntime=Fullscreen] readonly attribute boolean webkitFullScreenKeyboardInputAllowed;
- [EnabledAtRuntime=Fullscreen] readonly attribute Element webkitCurrentFullScreenElement;
- [EnabledAtRuntime=Fullscreen] void webkitCancelFullScreen();
+ [RuntimeEnabled=Fullscreen] readonly attribute boolean webkitIsFullScreen;
+ [RuntimeEnabled=Fullscreen] readonly attribute boolean webkitFullScreenKeyboardInputAllowed;
+ [RuntimeEnabled=Fullscreen] readonly attribute Element webkitCurrentFullScreenElement;
+ [RuntimeEnabled=Fullscreen] void webkitCancelFullScreen();
// W3C version
- [EnabledAtRuntime=Fullscreen] readonly attribute boolean webkitFullscreenEnabled;
- [EnabledAtRuntime=Fullscreen] readonly attribute Element webkitFullscreenElement;
- [EnabledAtRuntime=Fullscreen] void webkitExitFullscreen();
+ [RuntimeEnabled=Fullscreen] readonly attribute boolean webkitFullscreenEnabled;
+ [RuntimeEnabled=Fullscreen] readonly attribute Element webkitFullscreenElement;
+ [RuntimeEnabled=Fullscreen] void webkitExitFullscreen();
};
diff --git a/chromium/third_party/WebKit/Source/core/dom/DocumentInit.cpp b/chromium/third_party/WebKit/Source/core/dom/DocumentInit.cpp
index ba30041b2fd..90b4dd996f1 100644
--- a/chromium/third_party/WebKit/Source/core/dom/DocumentInit.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/DocumentInit.cpp
@@ -29,16 +29,43 @@
#include "core/dom/DocumentInit.h"
#include "RuntimeEnabledFeatures.h"
-#include "core/dom/CustomElementRegistrationContext.h"
#include "core/dom/Document.h"
+#include "core/dom/custom/CustomElementRegistrationContext.h"
+#include "core/html/HTMLFrameOwnerElement.h"
#include "core/html/HTMLImportsController.h"
-#include "core/page/Frame.h"
+#include "core/frame/Frame.h"
namespace WebCore {
+static Document* parentDocument(Frame* frame)
+{
+ if (!frame)
+ return 0;
+ Element* ownerElement = frame->ownerElement();
+ if (!ownerElement)
+ return 0;
+ return &ownerElement->document();
+}
+
+
+static Document* ownerDocument(Frame* frame)
+{
+ if (!frame)
+ return 0;
+
+ Frame* ownerFrame = frame->tree().parent();
+ if (!ownerFrame)
+ ownerFrame = frame->loader().opener();
+ if (!ownerFrame)
+ return 0;
+ return ownerFrame->document();
+}
+
DocumentInit::DocumentInit(const KURL& url, Frame* frame, WeakPtr<Document> contextDocument, HTMLImport* import)
: m_url(url)
, m_frame(frame)
+ , m_parent(parentDocument(frame))
+ , m_owner(ownerDocument(frame))
, m_contextDocument(contextDocument)
, m_import(import)
{
@@ -47,6 +74,8 @@ DocumentInit::DocumentInit(const KURL& url, Frame* frame, WeakPtr<Document> cont
DocumentInit::DocumentInit(const DocumentInit& other)
: m_url(other.m_url)
, m_frame(other.m_frame)
+ , m_parent(other.m_parent)
+ , m_owner(other.m_owner)
, m_contextDocument(other.m_contextDocument)
, m_import(other.m_import)
, m_registrationContext(other.m_registrationContext)
@@ -65,8 +94,20 @@ bool DocumentInit::shouldSetURL() const
bool DocumentInit::shouldTreatURLAsSrcdocDocument() const
{
- ASSERT(m_frame);
- return m_frame->loader()->shouldTreatURLAsSrcdocDocument(m_url);
+ return m_parent && m_frame->loader().shouldTreatURLAsSrcdocDocument(m_url);
+}
+
+bool DocumentInit::isSeamlessAllowedFor(Document* child) const
+{
+ if (!m_parent)
+ return false;
+ if (m_parent->isSandboxed(SandboxSeamlessIframes))
+ return false;
+ if (child->isSrcdocDocument())
+ return true;
+ if (m_parent->securityOrigin()->canAccess(child->securityOrigin()))
+ return true;
+ return m_parent->securityOrigin()->canRequest(child->url());
}
Frame* DocumentInit::frameForSecurityContext() const
@@ -81,7 +122,7 @@ Frame* DocumentInit::frameForSecurityContext() const
SandboxFlags DocumentInit::sandboxFlags() const
{
ASSERT(frameForSecurityContext());
- return frameForSecurityContext()->loader()->effectiveSandboxFlags();
+ return frameForSecurityContext()->loader().effectiveSandboxFlags();
}
Settings* DocumentInit::settings() const
@@ -90,15 +131,9 @@ Settings* DocumentInit::settings() const
return frameForSecurityContext()->settings();
}
-Frame* DocumentInit::ownerFrame() const
+KURL DocumentInit::parentBaseURL() const
{
- if (!m_frame)
- return 0;
-
- Frame* ownerFrame = m_frame->tree()->parent();
- if (!ownerFrame)
- ownerFrame = m_frame->loader()->opener();
- return ownerFrame;
+ return m_parent->baseURL();
}
DocumentInit& DocumentInit::withRegistrationContext(CustomElementRegistrationContext* registrationContext)
diff --git a/chromium/third_party/WebKit/Source/core/dom/DocumentInit.h b/chromium/third_party/WebKit/Source/core/dom/DocumentInit.h
index b647e4e73b4..911d14f4620 100644
--- a/chromium/third_party/WebKit/Source/core/dom/DocumentInit.h
+++ b/chromium/third_party/WebKit/Source/core/dom/DocumentInit.h
@@ -28,8 +28,9 @@
#ifndef DocumentInit_h
#define DocumentInit_h
+#include "core/dom/SandboxFlags.h"
#include "core/dom/SecurityContext.h"
-#include "weborigin/KURL.h"
+#include "platform/weborigin/KURL.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefPtr.h"
#include "wtf/WeakPtr.h"
@@ -55,12 +56,17 @@ public:
bool hasSecurityContext() const { return frameForSecurityContext(); }
bool shouldTreatURLAsSrcdocDocument() const;
bool shouldSetURL() const;
+ bool isSeamlessAllowedFor(Document* child) const;
SandboxFlags sandboxFlags() const;
+ Document* parent() const { return m_parent.get(); }
+ Document* owner() const { return m_owner.get(); }
+ KURL parentBaseURL() const;
Frame* ownerFrame() const;
Settings* settings() const;
DocumentInit& withRegistrationContext(CustomElementRegistrationContext*);
+
PassRefPtr<CustomElementRegistrationContext> registrationContext(Document*) const;
WeakPtr<Document> contextDocument() const;
@@ -71,6 +77,8 @@ private:
KURL m_url;
Frame* m_frame;
+ RefPtr<Document> m_parent;
+ RefPtr<Document> m_owner;
WeakPtr<Document> m_contextDocument;
HTMLImport* m_import;
RefPtr<CustomElementRegistrationContext> m_registrationContext;
diff --git a/chromium/third_party/WebKit/Source/core/dom/DocumentLifecycle.cpp b/chromium/third_party/WebKit/Source/core/dom/DocumentLifecycle.cpp
new file mode 100644
index 00000000000..157548f32b0
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/DocumentLifecycle.cpp
@@ -0,0 +1,55 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/dom/DocumentLifecycle.h"
+
+#include "wtf/Assertions.h"
+
+namespace WebCore {
+
+DocumentLifecycle::DocumentLifecycle()
+ : m_state(Uninitialized)
+{
+}
+
+DocumentLifecycle::~DocumentLifecycle()
+{
+}
+
+void DocumentLifecycle::advanceTo(State state)
+{
+ // FIXME: We can dispose a document multiple times. This seems wrong.
+ // See https://code.google.com/p/chromium/issues/detail?id=301668.
+ ASSERT(state > m_state || (state == Disposed && m_state == Disposed));
+ m_state = state;
+}
+
+}
diff --git a/chromium/third_party/WebKit/Source/core/dom/DocumentLifecycle.h b/chromium/third_party/WebKit/Source/core/dom/DocumentLifecycle.h
new file mode 100644
index 00000000000..c3f919635e8
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/DocumentLifecycle.h
@@ -0,0 +1,63 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef DocumentLifecycle_h
+#define DocumentLifecycle_h
+
+#include "wtf/Noncopyable.h"
+
+namespace WebCore {
+
+class DocumentLifecycle {
+ WTF_MAKE_NONCOPYABLE(DocumentLifecycle);
+public:
+ enum State {
+ Uninitialized,
+ Inactive,
+ Active,
+ Stopping,
+ Stopped,
+ Disposed,
+ };
+
+ DocumentLifecycle();
+ ~DocumentLifecycle();
+
+ State state() const { return m_state; }
+
+ void advanceTo(State);
+
+private:
+ State m_state;
+};
+
+}
+
+#endif
diff --git a/chromium/third_party/WebKit/Source/core/dom/DocumentLifecycleNotifier.cpp b/chromium/third_party/WebKit/Source/core/dom/DocumentLifecycleNotifier.cpp
new file mode 100644
index 00000000000..36c7997a979
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/DocumentLifecycleNotifier.cpp
@@ -0,0 +1,60 @@
+/*
+ * Copyright (C) 2013 Google Inc. All Rights Reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+
+#include "config.h"
+#include "core/dom/DocumentLifecycleNotifier.h"
+
+#include "core/dom/Document.h"
+#include "wtf/Assertions.h"
+
+namespace WebCore {
+
+DocumentLifecycleNotifier::DocumentLifecycleNotifier(Document* document)
+ : LifecycleNotifier<Document>(document)
+{
+}
+
+void DocumentLifecycleNotifier::addObserver(DocumentLifecycleNotifier::Observer* observer)
+{
+ if (observer->observerType() == Observer::DocumentLifecycleObserverType) {
+ RELEASE_ASSERT(m_iterating != IteratingOverDocumentObservers);
+ m_documentObservers.add(static_cast<DocumentLifecycleObserver*>(observer));
+ }
+
+ LifecycleNotifier<Document>::addObserver(observer);
+}
+
+void DocumentLifecycleNotifier::removeObserver(DocumentLifecycleNotifier::Observer* observer)
+{
+ if (observer->observerType() == Observer::DocumentLifecycleObserverType) {
+ RELEASE_ASSERT(m_iterating != IteratingOverDocumentObservers);
+ m_documentObservers.remove(static_cast<DocumentLifecycleObserver*>(observer));
+ }
+
+ LifecycleNotifier<Document>::removeObserver(observer);
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/DocumentLifecycleNotifier.h b/chromium/third_party/WebKit/Source/core/dom/DocumentLifecycleNotifier.h
new file mode 100644
index 00000000000..07888bd1b74
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/DocumentLifecycleNotifier.h
@@ -0,0 +1,75 @@
+/*
+ * Copyright (C) 2013 Google Inc. All Rights Reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef DocumentLifecycleNotifier_h
+#define DocumentLifecycleNotifier_h
+
+#include "core/dom/DocumentLifecycleObserver.h"
+#include "wtf/PassOwnPtr.h"
+#include "wtf/TemporaryChange.h"
+
+namespace WebCore {
+
+class Document;
+
+class DocumentLifecycleNotifier : public LifecycleNotifier<Document> {
+public:
+ static PassOwnPtr<DocumentLifecycleNotifier> create(Document*);
+
+ void notifyDocumentWasDetached();
+ void notifyDocumentWasDisposed();
+
+ virtual void addObserver(Observer*) OVERRIDE;
+ virtual void removeObserver(Observer*) OVERRIDE;
+
+private:
+ explicit DocumentLifecycleNotifier(Document*);
+
+ typedef HashSet<DocumentLifecycleObserver*> DocumentObserverSet;
+ DocumentObserverSet m_documentObservers;
+};
+
+inline PassOwnPtr<DocumentLifecycleNotifier> DocumentLifecycleNotifier::create(Document* document)
+{
+ return adoptPtr(new DocumentLifecycleNotifier(document));
+}
+
+inline void DocumentLifecycleNotifier::notifyDocumentWasDetached()
+{
+ TemporaryChange<IterationType> scope(this->m_iterating, IteratingOverDocumentObservers);
+ for (DocumentObserverSet::iterator i = m_documentObservers.begin(); i != m_documentObservers.end(); ++i)
+ (*i)->documentWasDetached();
+}
+
+inline void DocumentLifecycleNotifier::notifyDocumentWasDisposed()
+{
+ TemporaryChange<IterationType> scope(this->m_iterating, IteratingOverDocumentObservers);
+ for (DocumentObserverSet::iterator i = m_documentObservers.begin(); i != m_documentObservers.end(); ++i)
+ (*i)->documentWasDisposed();
+}
+
+} // namespace WebCore
+
+#endif // DocumentLifecycleNotifier_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/DocumentLifecycleObserver.cpp b/chromium/third_party/WebKit/Source/core/dom/DocumentLifecycleObserver.cpp
index 497d2ea65cf..b0abbfd1394 100644
--- a/chromium/third_party/WebKit/Source/core/dom/DocumentLifecycleObserver.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/DocumentLifecycleObserver.cpp
@@ -31,38 +31,23 @@
namespace WebCore {
-DocumentLifecycleObserver::DocumentLifecycleObserver(Document* document)
- : ContextLifecycleObserver(document, DocumentLifecycleObserverType)
-{
-}
-
-DocumentLifecycleObserver::~DocumentLifecycleObserver()
+template<> void observerContext(Document* context, LifecycleObserver<Document>* observer)
{
+ static_cast<LifecycleContext<Document>*>(context)->wasObservedBy(observer);
}
-DocumentLifecycleNotifier::DocumentLifecycleNotifier(ScriptExecutionContext* context)
- : ContextLifecycleNotifier(context)
+template<> void unobserverContext(Document* context, LifecycleObserver<Document>* observer)
{
+ static_cast<LifecycleContext<Document>*>(context)->wasUnobservedBy(observer);
}
-void DocumentLifecycleNotifier::addObserver(LifecycleObserver* observer)
+DocumentLifecycleObserver::DocumentLifecycleObserver(Document* document)
+ : LifecycleObserver<Document>(document, DocumentLifecycleObserverType)
{
- if (observer->observerType() == LifecycleObserver::DocumentLifecycleObserverType) {
- RELEASE_ASSERT(m_iterating != IteratingOverDocumentObservers);
- m_documentObservers.add(static_cast<DocumentLifecycleObserver*>(observer));
- }
-
- ContextLifecycleNotifier::addObserver(observer);
}
-void DocumentLifecycleNotifier::removeObserver(LifecycleObserver* observer)
+DocumentLifecycleObserver::~DocumentLifecycleObserver()
{
- if (observer->observerType() == LifecycleObserver::DocumentLifecycleObserverType) {
- RELEASE_ASSERT(m_iterating != IteratingOverDocumentObservers);
- m_documentObservers.remove(static_cast<DocumentLifecycleObserver*>(observer));
- }
-
- ContextLifecycleNotifier::removeObserver(observer);
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/DocumentLifecycleObserver.h b/chromium/third_party/WebKit/Source/core/dom/DocumentLifecycleObserver.h
index 27f1a68f9d8..47233c51a72 100644
--- a/chromium/third_party/WebKit/Source/core/dom/DocumentLifecycleObserver.h
+++ b/chromium/third_party/WebKit/Source/core/dom/DocumentLifecycleObserver.h
@@ -26,17 +26,16 @@
#ifndef DocumentLifecycleObserver_h
#define DocumentLifecycleObserver_h
-#include "core/dom/ContextLifecycleNotifier.h"
-#include "core/dom/ContextLifecycleObserver.h"
-#include "wtf/Assertions.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/TemporaryChange.h"
+#include "platform/LifecycleContext.h"
namespace WebCore {
class Document;
-class DocumentLifecycleObserver : public ContextLifecycleObserver {
+template<> void observerContext(Document*, LifecycleObserver<Document>*);
+template<> void unobserverContext(Document*, LifecycleObserver<Document>*);
+
+class DocumentLifecycleObserver : public LifecycleObserver<Document> {
public:
explicit DocumentLifecycleObserver(Document*);
virtual ~DocumentLifecycleObserver();
@@ -44,42 +43,6 @@ public:
virtual void documentWasDisposed() { }
};
-class DocumentLifecycleNotifier : public ContextLifecycleNotifier {
-public:
- static PassOwnPtr<DocumentLifecycleNotifier> create(ScriptExecutionContext*);
-
- void notifyDocumentWasDetached();
- void notifyDocumentWasDisposed();
-
- virtual void addObserver(LifecycleObserver*) OVERRIDE;
- virtual void removeObserver(LifecycleObserver*) OVERRIDE;
-
-private:
- explicit DocumentLifecycleNotifier(ScriptExecutionContext*);
-
- typedef HashSet<DocumentLifecycleObserver*> DocumentObserverSet;
- DocumentObserverSet m_documentObservers;
-};
-
-inline PassOwnPtr<DocumentLifecycleNotifier> DocumentLifecycleNotifier::create(ScriptExecutionContext* context)
-{
- return adoptPtr(new DocumentLifecycleNotifier(context));
-}
-
-inline void DocumentLifecycleNotifier::notifyDocumentWasDetached()
-{
- TemporaryChange<IterationType> scope(this->m_iterating, IteratingOverDocumentObservers);
- for (DocumentObserverSet::iterator i = m_documentObservers.begin(); i != m_documentObservers.end(); ++i)
- (*i)->documentWasDetached();
-}
-
-inline void DocumentLifecycleNotifier::notifyDocumentWasDisposed()
-{
- TemporaryChange<IterationType> scope(this->m_iterating, IteratingOverDocumentObservers);
- for (DocumentObserverSet::iterator i = m_documentObservers.begin(); i != m_documentObservers.end(); ++i)
- (*i)->documentWasDisposed();
-}
-
} // namespace WebCore
#endif // DocumentLifecycleObserver_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/DocumentMarker.cpp b/chromium/third_party/WebKit/Source/core/dom/DocumentMarker.cpp
index 5f3db283d6e..12b903937f6 100644
--- a/chromium/third_party/WebKit/Source/core/dom/DocumentMarker.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/DocumentMarker.cpp
@@ -84,8 +84,8 @@ private:
PassRefPtr<DocumentMarkerTextMatch> DocumentMarkerTextMatch::instanceFor(bool match)
{
- DEFINE_STATIC_LOCAL(RefPtr<DocumentMarkerTextMatch>, trueInstance, (adoptRef(new DocumentMarkerTextMatch(true))));
- DEFINE_STATIC_LOCAL(RefPtr<DocumentMarkerTextMatch>, falseInstance, (adoptRef(new DocumentMarkerTextMatch(false))));
+ DEFINE_STATIC_REF(DocumentMarkerTextMatch, trueInstance, (adoptRef(new DocumentMarkerTextMatch(true))));
+ DEFINE_STATIC_REF(DocumentMarkerTextMatch, falseInstance, (adoptRef(new DocumentMarkerTextMatch(false))));
return match ? trueInstance : falseInstance;
}
diff --git a/chromium/third_party/WebKit/Source/core/dom/DocumentMarker.h b/chromium/third_party/WebKit/Source/core/dom/DocumentMarker.h
index f4410fbdc3f..ded6b9d1c79 100644
--- a/chromium/third_party/WebKit/Source/core/dom/DocumentMarker.h
+++ b/chromium/third_party/WebKit/Source/core/dom/DocumentMarker.h
@@ -38,10 +38,19 @@ class DocumentMarkerDetails;
// for all types other than type TextMatch.
class DocumentMarker {
public:
+ enum MarkerTypeIndex {
+ SpellingMarkerIndex = 0,
+ GramarMarkerIndex,
+ TextMatchMarkerIndex,
+ InvisibleSpellcheckMarkerIndex,
+ MarkerTypeIndexesCount
+ };
+
enum MarkerType {
- Spelling = 1 << 0,
- Grammar = 1 << 1,
- TextMatch = 1 << 2
+ Spelling = 1 << SpellingMarkerIndex,
+ Grammar = 1 << GramarMarkerIndex,
+ TextMatch = 1 << TextMatchMarkerIndex,
+ InvisibleSpellcheck = 1 << InvisibleSpellcheckMarkerIndex
};
class MarkerTypes {
@@ -63,7 +72,7 @@ public:
class AllMarkers : public MarkerTypes {
public:
AllMarkers()
- : MarkerTypes(Spelling | Grammar | TextMatch)
+ : MarkerTypes(Spelling | Grammar | TextMatch | InvisibleSpellcheck)
{
}
};
@@ -76,6 +85,14 @@ public:
}
};
+ class SpellCheckClientMarkers : public MarkerTypes {
+ public:
+ SpellCheckClientMarkers()
+ : MarkerTypes(Spelling | Grammar | InvisibleSpellcheck)
+ {
+ }
+ };
+
DocumentMarker();
DocumentMarker(MarkerType, unsigned startOffset, unsigned endOffset);
DocumentMarker(MarkerType, unsigned startOffset, unsigned endOffset, const String& description);
diff --git a/chromium/third_party/WebKit/Source/core/dom/DocumentMarkerController.cpp b/chromium/third_party/WebKit/Source/core/dom/DocumentMarkerController.cpp
index 48af00e18ef..ef4fa8220e6 100644
--- a/chromium/third_party/WebKit/Source/core/dom/DocumentMarkerController.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/DocumentMarkerController.cpp
@@ -40,6 +40,27 @@
namespace WebCore {
+namespace {
+
+DocumentMarker::MarkerTypeIndex MarkerTypeToMarkerIndex(DocumentMarker::MarkerType type)
+{
+ switch (type) {
+ case DocumentMarker::Spelling:
+ return DocumentMarker::SpellingMarkerIndex;
+ case DocumentMarker::Grammar:
+ return DocumentMarker::GramarMarkerIndex;
+ case DocumentMarker::TextMatch:
+ return DocumentMarker::TextMatchMarkerIndex;
+ case DocumentMarker::InvisibleSpellcheck:
+ return DocumentMarker::InvisibleSpellcheckMarkerIndex;
+ }
+
+ ASSERT_NOT_REACHED();
+ return DocumentMarker::SpellingMarkerIndex;
+}
+
+} // namespace
+
inline bool DocumentMarkerController::possiblyHasMarkers(DocumentMarker::MarkerTypes types)
{
return m_possiblyExistingMarkerTypes.intersects(types);
@@ -54,7 +75,7 @@ DocumentMarkerController::~DocumentMarkerController()
{
}
-void DocumentMarkerController::detach()
+void DocumentMarkerController::clear()
{
m_markers.clear();
m_possiblyExistingMarkerTypes = 0;
@@ -119,6 +140,11 @@ void DocumentMarkerController::addTextMatchMarker(const Range* range, bool activ
}
}
+void DocumentMarkerController::prepareForDestruction()
+{
+ clear();
+}
+
void DocumentMarkerController::removeMarkers(Range* range, DocumentMarker::MarkerTypes markerTypes, RemovePartiallyOverlappingMarkerOrNot shouldRemovePartiallyOverlappingMarker)
{
for (TextIterator markedText(range); !markedText.atEnd(); markedText.advance()) {
@@ -133,6 +159,36 @@ void DocumentMarkerController::removeMarkers(Range* range, DocumentMarker::Marke
}
}
+static bool startsFurther(const DocumentMarker& lhv, const DocumentMarker& rhv)
+{
+ return lhv.startOffset() < rhv.startOffset();
+}
+
+static bool startsAfter(const DocumentMarker& marker, size_t startOffset)
+{
+ return marker.startOffset() < startOffset;
+}
+
+static bool endsBefore(size_t startOffset, const DocumentMarker& rhv)
+{
+ return startOffset < rhv.endOffset();
+}
+
+static bool compareByStart(const DocumentMarker* lhv, const DocumentMarker* rhv)
+{
+ return startsFurther(*lhv, *rhv);
+}
+
+static bool doesNotOverlap(const DocumentMarker& lhv, const DocumentMarker& rhv)
+{
+ return lhv.endOffset() < rhv.startOffset();
+}
+
+static bool doesNotInclude(const DocumentMarker& marker, size_t startOffset)
+{
+ return marker.endOffset() < startOffset;
+}
+
// Markers are stored in order sorted by their start offset.
// Markers of the same type do not overlap each other.
@@ -144,49 +200,28 @@ void DocumentMarkerController::addMarker(Node* node, const DocumentMarker& newMa
m_possiblyExistingMarkerTypes.add(newMarker.type());
- OwnPtr<MarkerList>& list = m_markers.add(node, nullptr).iterator->value;
+ OwnPtr<MarkerLists>& markers = m_markers.add(node, nullptr).iterator->value;
+ if (!markers) {
+ markers = adoptPtr(new MarkerLists);
+ markers->grow(DocumentMarker::MarkerTypeIndexesCount);
+ }
+
+ DocumentMarker::MarkerTypeIndex markerListIndex = MarkerTypeToMarkerIndex(newMarker.type());
+ if (!markers->at(markerListIndex)) {
+ markers->insert(markerListIndex, adoptPtr(new MarkerList));
+ }
- if (!list) {
- list = adoptPtr(new MarkerList);
+ OwnPtr<MarkerList>& list = markers->at(markerListIndex);
+ if (list->isEmpty() || list->last().endOffset() < newMarker.startOffset()) {
list->append(RenderedDocumentMarker(newMarker));
} else {
RenderedDocumentMarker toInsert(newMarker);
- size_t numMarkers = list->size();
- size_t i;
- // Iterate over all markers whose start offset is less than or equal to the new marker's.
- // If one of them is of the same type as the new marker and touches it or intersects with it
- // (there is at most one), remove it and adjust the new marker's start offset to encompass it.
- for (i = 0; i < numMarkers; ++i) {
- DocumentMarker marker = list->at(i);
- if (marker.startOffset() > toInsert.startOffset())
- break;
- if (marker.type() == toInsert.type() && marker.type() != DocumentMarker::TextMatch && marker.endOffset() >= toInsert.startOffset()) {
- toInsert.setStartOffset(marker.startOffset());
- list->remove(i);
- numMarkers--;
- break;
- }
+ if (toInsert.type() != DocumentMarker::TextMatch) {
+ mergeOverlapping(list.get(), toInsert);
+ } else {
+ MarkerList::iterator pos = std::lower_bound(list->begin(), list->end(), toInsert, startsFurther);
+ list->insert(pos - list->begin(), RenderedDocumentMarker(toInsert));
}
- size_t j = i;
- // Iterate over all markers whose end offset is less than or equal to the new marker's,
- // removing markers of the same type as the new marker which touch it or intersect with it,
- // adjusting the new marker's end offset to cover them if necessary.
- while (j < numMarkers) {
- DocumentMarker marker = list->at(j);
- if (marker.startOffset() > toInsert.endOffset())
- break;
- if (marker.type() == toInsert.type() && marker.type() != DocumentMarker::TextMatch) {
- list->remove(j);
- if (toInsert.endOffset() <= marker.endOffset()) {
- toInsert.setEndOffset(marker.endOffset());
- break;
- }
- numMarkers--;
- } else
- j++;
- }
- // At this point i points to the node before which we want to insert.
- list->insert(i, RenderedDocumentMarker(toInsert));
}
// repaint the affected node
@@ -194,6 +229,20 @@ void DocumentMarkerController::addMarker(Node* node, const DocumentMarker& newMa
node->renderer()->repaint();
}
+void DocumentMarkerController::mergeOverlapping(MarkerList* list, DocumentMarker& toInsert)
+{
+ MarkerList::iterator firstOverlapping = std::lower_bound(list->begin(), list->end(), toInsert, doesNotOverlap);
+ size_t index = firstOverlapping - list->begin();
+ list->insert(index, RenderedDocumentMarker(toInsert));
+ MarkerList::iterator inserted = list->begin() + index;
+ firstOverlapping = inserted + 1;
+ for (MarkerList::iterator i = firstOverlapping; i != list->end() && i->startOffset() <= inserted->endOffset(); ) {
+ inserted->setStartOffset(std::min(inserted->startOffset(), i->startOffset()));
+ inserted->setEndOffset(std::max(inserted->endOffset(), i->endOffset()));
+ list->remove(i - list->begin());
+ }
+}
+
// copies markers from srcNode to dstNode, applying the specified shift delta to the copies. The shift is
// useful if, e.g., the caller has created the dstNode from a non-prefix substring of the srcNode.
void DocumentMarkerController::copyMarkers(Node* srcNode, unsigned startOffset, int length, Node* dstNode, int delta)
@@ -205,32 +254,35 @@ void DocumentMarkerController::copyMarkers(Node* srcNode, unsigned startOffset,
return;
ASSERT(!m_markers.isEmpty());
- MarkerList* list = m_markers.get(srcNode);
- if (!list)
+ MarkerLists* markers = m_markers.get(srcNode);
+ if (!markers)
return;
bool docDirty = false;
- unsigned endOffset = startOffset + length - 1;
- for (size_t i = 0; i != list->size(); ++i) {
- DocumentMarker marker = list->at(i);
+ for (size_t markerListIndex = 0; markerListIndex < DocumentMarker::MarkerTypeIndexesCount; ++markerListIndex) {
+ OwnPtr<MarkerList>& list = (*markers)[markerListIndex];
+ if (!list)
+ continue;
- // stop if we are now past the specified range
- if (marker.startOffset() > endOffset)
- break;
+ unsigned endOffset = startOffset + length - 1;
+ MarkerList::iterator startPos = std::lower_bound(list->begin(), list->end(), startOffset, doesNotInclude);
+ for (MarkerList::iterator i = startPos; i != list->end(); ++i) {
+ DocumentMarker marker = *i;
- // skip marker that is before the specified range or is the wrong type
- if (marker.endOffset() < startOffset)
- continue;
+ // stop if we are now past the specified range
+ if (marker.startOffset() > endOffset)
+ break;
- // pin the marker to the specified range and apply the shift delta
- docDirty = true;
- if (marker.startOffset() < startOffset)
- marker.setStartOffset(startOffset);
- if (marker.endOffset() > endOffset)
- marker.setEndOffset(endOffset);
- marker.shiftOffsets(delta);
+ // pin the marker to the specified range and apply the shift delta
+ docDirty = true;
+ if (marker.startOffset() < startOffset)
+ marker.setStartOffset(startOffset);
+ if (marker.endOffset() > endOffset)
+ marker.setEndOffset(endOffset);
+ marker.shiftOffsets(delta);
- addMarker(dstNode, marker);
+ addMarker(dstNode, marker);
+ }
}
// repaint the affected node
@@ -247,53 +299,68 @@ void DocumentMarkerController::removeMarkers(Node* node, unsigned startOffset, i
return;
ASSERT(!(m_markers.isEmpty()));
- MarkerList* list = m_markers.get(node);
- if (!list)
+ MarkerLists* markers = m_markers.get(node);
+ if (!markers)
return;
bool docDirty = false;
- unsigned endOffset = startOffset + length;
- for (size_t i = 0; i < list->size();) {
- DocumentMarker marker = list->at(i);
-
- // markers are returned in order, so stop if we are now past the specified range
- if (marker.startOffset() >= endOffset)
- break;
-
- // skip marker that is wrong type or before target
- if (marker.endOffset() <= startOffset || !markerTypes.contains(marker.type())) {
- i++;
+ size_t emptyListsCount = 0;
+ for (size_t markerListIndex = 0; markerListIndex < DocumentMarker::MarkerTypeIndexesCount; ++markerListIndex) {
+ OwnPtr<MarkerList>& list = (*markers)[markerListIndex];
+ if (!list || list->isEmpty()) {
+ if (list.get() && list->isEmpty())
+ list.clear();
+ ++emptyListsCount;
continue;
}
+ if (!markerTypes.contains(list->begin()->type()))
+ continue;
+ unsigned endOffset = startOffset + length;
+ MarkerList::iterator startPos = std::upper_bound(list->begin(), list->end(), startOffset, endsBefore);
+ for (MarkerList::iterator i = startPos; i != list->end(); ) {
+ DocumentMarker marker = *i;
- // at this point we know that marker and target intersect in some way
- docDirty = true;
+ // markers are returned in order, so stop if we are now past the specified range
+ if (marker.startOffset() >= endOffset)
+ break;
- // pitch the old marker
- list->remove(i);
+ // at this point we know that marker and target intersect in some way
+ docDirty = true;
- if (shouldRemovePartiallyOverlappingMarker)
- // Stop here. Don't add resulting slices back.
- continue;
+ // pitch the old marker
+ list->remove(i - list->begin());
+
+ if (shouldRemovePartiallyOverlappingMarker) {
+ // Stop here. Don't add resulting slices back.
+ continue;
+ }
- // add either of the resulting slices that are left after removing target
- if (startOffset > marker.startOffset()) {
- DocumentMarker newLeft = marker;
- newLeft.setEndOffset(startOffset);
- list->insert(i, RenderedDocumentMarker(newLeft));
- // i now points to the newly-inserted node, but we want to skip that one
- i++;
+ // add either of the resulting slices that are left after removing target
+ if (startOffset > marker.startOffset()) {
+ DocumentMarker newLeft = marker;
+ newLeft.setEndOffset(startOffset);
+ size_t insertIndex = i - list->begin();
+ list->insert(insertIndex , RenderedDocumentMarker(newLeft));
+ // Move to the marker after the inserted one.
+ i = list->begin() + insertIndex + 1;
+ }
+ if (marker.endOffset() > endOffset) {
+ DocumentMarker newRight = marker;
+ newRight.setStartOffset(endOffset);
+ size_t insertIndex = i - list->begin();
+ list->insert(insertIndex, RenderedDocumentMarker(newRight));
+ // Move to the marker after the inserted one.
+ i = list->begin() + insertIndex + 1;
+ }
}
- if (marker.endOffset() > endOffset) {
- DocumentMarker newRight = marker;
- newRight.setStartOffset(endOffset);
- list->insert(i, RenderedDocumentMarker(newRight));
- // i now points to the newly-inserted node, but we want to skip that one
- i++;
+
+ if (list->isEmpty()) {
+ list.clear();
+ ++emptyListsCount;
}
}
- if (list->isEmpty()) {
+ if (emptyListsCount == DocumentMarker::MarkerTypeIndexesCount) {
m_markers.remove(node);
if (m_markers.isEmpty())
m_possiblyExistingMarkerTypes = 0;
@@ -314,15 +381,12 @@ DocumentMarker* DocumentMarkerController::markerContainingPoint(const LayoutPoin
MarkerMap::iterator end = m_markers.end();
for (MarkerMap::iterator nodeIterator = m_markers.begin(); nodeIterator != end; ++nodeIterator) {
// inner loop; process each marker in this node
- MarkerList* list = nodeIterator->value.get();
- unsigned markerCount = list->size();
+ MarkerLists* markers = nodeIterator->value.get();
+ OwnPtr<MarkerList>& list = (*markers)[MarkerTypeToMarkerIndex(markerType)];
+ unsigned markerCount = list.get() ? list->size() : 0;
for (unsigned markerIndex = 0; markerIndex < markerCount; ++markerIndex) {
RenderedDocumentMarker& marker = list->at(markerIndex);
- // skip marker that is wrong type
- if (marker.type() != markerType)
- continue;
-
if (marker.contains(point))
return &marker;
}
@@ -334,15 +398,21 @@ DocumentMarker* DocumentMarkerController::markerContainingPoint(const LayoutPoin
Vector<DocumentMarker*> DocumentMarkerController::markersFor(Node* node, DocumentMarker::MarkerTypes markerTypes)
{
Vector<DocumentMarker*> result;
- MarkerList* list = m_markers.get(node);
- if (!list)
+
+ MarkerLists* markers = m_markers.get(node);
+ if (!markers)
return result;
- for (size_t i = 0; i < list->size(); ++i) {
- if (markerTypes.contains(list->at(i).type()))
+ for (size_t markerListIndex = 0; markerListIndex < DocumentMarker::MarkerTypeIndexesCount; ++markerListIndex) {
+ OwnPtr<MarkerList>& list = (*markers)[markerListIndex];
+ if (!list || list->isEmpty() || !markerTypes.contains(list->begin()->type()))
+ continue;
+
+ for (size_t i = 0; i < list->size(); ++i)
result.append(&(list->at(i)));
}
+ std::sort(result.begin(), result.end(), compareByStart);
return result;
}
@@ -350,9 +420,14 @@ Vector<DocumentMarker*> DocumentMarkerController::markers()
{
Vector<DocumentMarker*> result;
for (MarkerMap::iterator i = m_markers.begin(); i != m_markers.end(); ++i) {
- for (size_t j = 0; j < i->value->size(); ++j)
- result.append(&(i->value->at(j)));
+ MarkerLists* markers = i->value.get();
+ for (size_t markerListIndex = 0; markerListIndex < DocumentMarker::MarkerTypeIndexesCount; ++markerListIndex) {
+ OwnPtr<MarkerList>& list = (*markers)[markerListIndex];
+ for (size_t j = 0; list.get() && j < list->size(); ++j)
+ result.append(&(list->at(j)));
+ }
}
+ std::sort(result.begin(), result.end(), compareByStart);
return result;
}
@@ -369,7 +444,7 @@ Vector<DocumentMarker*> DocumentMarkerController::markersInRange(Range* range, D
ASSERT(endContainer);
Node* pastLastNode = range->pastLastNode();
- for (Node* node = range->firstNode(); node != pastLastNode; node = NodeTraversal::next(node)) {
+ for (Node* node = range->firstNode(); node != pastLastNode; node = NodeTraversal::next(*node)) {
Vector<DocumentMarker*> markers = markersFor(node);
Vector<DocumentMarker*>::const_iterator end = markers.end();
for (Vector<DocumentMarker*>::const_iterator it = markers.begin(); it != end; ++it) {
@@ -398,19 +473,19 @@ Vector<IntRect> DocumentMarkerController::renderedRectsForMarkers(DocumentMarker
MarkerMap::iterator end = m_markers.end();
for (MarkerMap::iterator nodeIterator = m_markers.begin(); nodeIterator != end; ++nodeIterator) {
// inner loop; process each marker in this node
- MarkerList* list = nodeIterator->value.get();
- unsigned markerCount = list->size();
- for (unsigned markerIndex = 0; markerIndex < markerCount; ++markerIndex) {
- const RenderedDocumentMarker& marker = list->at(markerIndex);
-
- // skip marker that is wrong type
- if (marker.type() != markerType)
+ MarkerLists* markers = nodeIterator->value.get();
+ for (size_t markerListIndex = 0; markerListIndex < DocumentMarker::MarkerTypeIndexesCount; ++markerListIndex) {
+ OwnPtr<MarkerList>& list = (*markers)[markerListIndex];
+ if (!list || list->isEmpty() || list->begin()->type() != markerType)
continue;
+ for (unsigned markerIndex = 0; markerIndex < list->size(); ++markerIndex) {
+ const RenderedDocumentMarker& marker = list->at(markerIndex);
- if (!marker.isRendered())
- continue;
+ if (!marker.isRendered())
+ continue;
- result.append(marker.renderedRect());
+ result.append(marker.renderedRect());
+ }
}
}
@@ -434,7 +509,7 @@ void DocumentMarkerController::removeMarkers(DocumentMarker::MarkerTypes markerT
return;
ASSERT(!m_markers.isEmpty());
- Vector<RefPtr<Node> > nodesWithMarkers;
+ Vector<const Node*> nodesWithMarkers;
copyKeysToVector(m_markers, nodesWithMarkers);
unsigned size = nodesWithMarkers.size();
for (unsigned i = 0; i < size; ++i) {
@@ -449,30 +524,32 @@ void DocumentMarkerController::removeMarkers(DocumentMarker::MarkerTypes markerT
void DocumentMarkerController::removeMarkersFromList(MarkerMap::iterator iterator, DocumentMarker::MarkerTypes markerTypes)
{
bool needsRepainting = false;
- bool listCanBeRemoved;
+ bool nodeCanBeRemoved;
+ size_t emptyListsCount = 0;
if (markerTypes == DocumentMarker::AllMarkers()) {
needsRepainting = true;
- listCanBeRemoved = true;
+ nodeCanBeRemoved = true;
} else {
- MarkerList* list = iterator->value.get();
-
- for (size_t i = 0; i != list->size(); ) {
- DocumentMarker marker = list->at(i);
-
- // skip nodes that are not of the specified type
- if (!markerTypes.contains(marker.type())) {
- ++i;
+ MarkerLists* markers = iterator->value.get();
+
+ for (size_t markerListIndex = 0; markerListIndex < DocumentMarker::MarkerTypeIndexesCount; ++markerListIndex) {
+ OwnPtr<MarkerList>& list = (*markers)[markerListIndex];
+ if (!list || list->isEmpty()) {
+ if (list.get() && list->isEmpty())
+ list.clear();
+ ++emptyListsCount;
continue;
}
-
- // pitch the old marker
- list->remove(i);
- needsRepainting = true;
- // i now is the index of the next marker
+ if (markerTypes.contains(list->begin()->type())) {
+ list->clear();
+ list.clear();
+ ++emptyListsCount;
+ needsRepainting = true;
+ }
}
- listCanBeRemoved = list->isEmpty();
+ nodeCanBeRemoved = emptyListsCount == DocumentMarker::MarkerTypeIndexesCount;
}
if (needsRepainting) {
@@ -480,7 +557,7 @@ void DocumentMarkerController::removeMarkersFromList(MarkerMap::iterator iterato
renderer->repaint();
}
- if (listCanBeRemoved) {
+ if (nodeCanBeRemoved) {
m_markers.remove(iterator);
if (m_markers.isEmpty())
m_possiblyExistingMarkerTypes = 0;
@@ -496,27 +573,21 @@ void DocumentMarkerController::repaintMarkers(DocumentMarker::MarkerTypes marker
// outer loop: process each markered node in the document
MarkerMap::iterator end = m_markers.end();
for (MarkerMap::iterator i = m_markers.begin(); i != end; ++i) {
- Node* node = i->key.get();
+ const Node* node = i->key;
// inner loop: process each marker in the current node
- MarkerList* list = i->value.get();
- bool nodeNeedsRepaint = false;
- for (size_t i = 0; i != list->size(); ++i) {
- DocumentMarker marker = list->at(i);
-
- // skip nodes that are not of the specified type
- if (markerTypes.contains(marker.type())) {
- nodeNeedsRepaint = true;
+ MarkerLists* markers = i->value.get();
+ for (size_t markerListIndex = 0; markerListIndex < DocumentMarker::MarkerTypeIndexesCount; ++markerListIndex) {
+ OwnPtr<MarkerList>& list = (*markers)[markerListIndex];
+ if (!list || list->isEmpty() || !markerTypes.contains(list->begin()->type()))
+ continue;
+
+ // cause the node to be redrawn
+ if (RenderObject* renderer = node->renderer()) {
+ renderer->repaint();
break;
}
}
-
- if (!nodeNeedsRepaint)
- continue;
-
- // cause the node to be redrawn
- if (RenderObject* renderer = node->renderer())
- renderer->repaint();
}
}
@@ -527,9 +598,12 @@ void DocumentMarkerController::invalidateRenderedRectsForMarkersInRect(const Lay
for (MarkerMap::iterator i = m_markers.begin(); i != end; ++i) {
// inner loop: process each rect in the current node
- MarkerList* list = i->value.get();
- for (size_t listIndex = 0; listIndex < list->size(); ++listIndex)
- list->at(listIndex).invalidate(r);
+ MarkerLists* markers = i->value.get();
+ for (size_t markerListIndex = 0; markerListIndex < DocumentMarker::MarkerTypeIndexesCount; ++markerListIndex) {
+ OwnPtr<MarkerList>& list = (*markers)[markerListIndex];
+ for (size_t markerIndex = 0; list.get() && markerIndex < list->size(); ++markerIndex)
+ list->at(markerIndex).invalidate(r);
+ }
}
}
@@ -539,20 +613,23 @@ void DocumentMarkerController::shiftMarkers(Node* node, unsigned startOffset, in
return;
ASSERT(!m_markers.isEmpty());
- MarkerList* list = m_markers.get(node);
- if (!list)
+ MarkerLists* markers = m_markers.get(node);
+ if (!markers)
return;
bool docDirty = false;
- for (size_t i = 0; i != list->size(); ++i) {
- RenderedDocumentMarker& marker = list->at(i);
- if (marker.startOffset() >= startOffset) {
- ASSERT((int)marker.startOffset() + delta >= 0);
- marker.shiftOffsets(delta);
+ for (size_t markerListIndex = 0; markerListIndex < DocumentMarker::MarkerTypeIndexesCount; ++markerListIndex) {
+ OwnPtr<MarkerList>& list = (*markers)[markerListIndex];
+ if (!list)
+ continue;
+ MarkerList::iterator startPos = std::lower_bound(list->begin(), list->end(), startOffset, startsAfter);
+ for (MarkerList::iterator marker = startPos; marker != list->end(); ++marker) {
+ ASSERT((int)marker->startOffset() + delta >= 0);
+ marker->shiftOffsets(delta);
docDirty = true;
// Marker moved, so previously-computed rendered rectangle is now invalid
- marker.invalidate();
+ marker->invalidate();
}
}
@@ -572,7 +649,7 @@ void DocumentMarkerController::setMarkersActive(Range* range, bool active)
Node* pastLastNode = range->pastLastNode();
- for (Node* node = range->firstNode(); node != pastLastNode; node = NodeTraversal::next(node)) {
+ for (Node* node = range->firstNode(); node != pastLastNode; node = NodeTraversal::next(*node)) {
int startOffset = node == startContainer ? range->startOffset() : 0;
int endOffset = node == endContainer ? range->endOffset() : INT_MAX;
setMarkersActive(node, startOffset, endOffset, active);
@@ -581,23 +658,22 @@ void DocumentMarkerController::setMarkersActive(Range* range, bool active)
void DocumentMarkerController::setMarkersActive(Node* node, unsigned startOffset, unsigned endOffset, bool active)
{
- MarkerList* list = m_markers.get(node);
- if (!list)
+ MarkerLists* markers = m_markers.get(node);
+ if (!markers)
return;
bool docDirty = false;
- for (size_t i = 0; i != list->size(); ++i) {
- DocumentMarker& marker = list->at(i);
+ OwnPtr<MarkerList>& list = (*markers)[MarkerTypeToMarkerIndex(DocumentMarker::TextMatch)];
+ if (!list)
+ return;
+ MarkerList::iterator startPos = std::upper_bound(list->begin(), list->end(), startOffset, endsBefore);
+ for (MarkerList::iterator marker = startPos; marker != list->end(); ++marker) {
// Markers are returned in order, so stop if we are now past the specified range.
- if (marker.startOffset() >= endOffset)
+ if (marker->startOffset() >= endOffset)
break;
- // Skip marker that is wrong type or before target.
- if (marker.endOffset() <= startOffset || marker.type() != DocumentMarker::TextMatch)
- continue;
-
- marker.setActiveMatch(active);
+ marker->setActiveMatch(active);
docDirty = true;
}
@@ -618,7 +694,7 @@ bool DocumentMarkerController::hasMarkers(Range* range, DocumentMarker::MarkerTy
ASSERT(endContainer);
Node* pastLastNode = range->pastLastNode();
- for (Node* node = range->firstNode(); node != pastLastNode; node = NodeTraversal::next(node)) {
+ for (Node* node = range->firstNode(); node != pastLastNode; node = NodeTraversal::next(*node)) {
Vector<DocumentMarker*> markers = markersFor(node);
Vector<DocumentMarker*>::const_iterator end = markers.end();
for (Vector<DocumentMarker*>::const_iterator it = markers.begin(); it != end; ++it) {
@@ -641,12 +717,15 @@ void DocumentMarkerController::showMarkers() const
fprintf(stderr, "%d nodes have markers:\n", m_markers.size());
MarkerMap::const_iterator end = m_markers.end();
for (MarkerMap::const_iterator nodeIterator = m_markers.begin(); nodeIterator != end; ++nodeIterator) {
- Node* node = nodeIterator->key.get();
+ const Node* node = nodeIterator->key;
fprintf(stderr, "%p", node);
- MarkerList* list = nodeIterator->value.get();
- for (unsigned markerIndex = 0; markerIndex < list->size(); ++markerIndex) {
- const DocumentMarker& marker = list->at(markerIndex);
- fprintf(stderr, " %d:[%d:%d](%d)", marker.type(), marker.startOffset(), marker.endOffset(), marker.activeMatch());
+ MarkerLists* markers = m_markers.get(node);
+ for (size_t markerListIndex = 0; markerListIndex < DocumentMarker::MarkerTypeIndexesCount; ++markerListIndex) {
+ OwnPtr<MarkerList>& list = (*markers)[markerListIndex];
+ for (unsigned markerIndex = 0; list.get() && markerIndex < list->size(); ++markerIndex) {
+ const DocumentMarker& marker = list->at(markerIndex);
+ fprintf(stderr, " %d:[%d:%d](%d)", marker.type(), marker.startOffset(), marker.endOffset(), marker.activeMatch());
+ }
}
fprintf(stderr, "\n");
diff --git a/chromium/third_party/WebKit/Source/core/dom/DocumentMarkerController.h b/chromium/third_party/WebKit/Source/core/dom/DocumentMarkerController.h
index 0b14aaa579c..a3b023f7d4c 100644
--- a/chromium/third_party/WebKit/Source/core/dom/DocumentMarkerController.h
+++ b/chromium/third_party/WebKit/Source/core/dom/DocumentMarkerController.h
@@ -28,12 +28,13 @@
#define DocumentMarkerController_h
#include "core/dom/DocumentMarker.h"
-#include "core/platform/graphics/IntRect.h"
+#include "platform/geometry/IntRect.h"
#include "wtf/HashMap.h"
#include "wtf/Vector.h"
namespace WebCore {
+class ContainerNode;
class LayoutPoint;
class LayoutRect;
class Node;
@@ -47,7 +48,7 @@ public:
DocumentMarkerController();
~DocumentMarkerController();
- void detach();
+ void clear();
void addMarker(Range*, DocumentMarker::MarkerType);
void addMarker(Range*, DocumentMarker::MarkerType, const String& description);
void addMarker(Range*, DocumentMarker::MarkerType, const String& description, uint32_t hash);
@@ -58,6 +59,7 @@ public:
void copyMarkers(Node* srcNode, unsigned startOffset, int length, Node* dstNode, int delta);
bool hasMarkers(Range*, DocumentMarker::MarkerTypes = DocumentMarker::AllMarkers());
+ void prepareForDestruction();
// When a marker partially overlaps with range, if removePartiallyOverlappingMarkers is true, we completely
// remove the marker. If the argument is false, we will adjust the span of the marker so that it retains
// the portion that is outside of the range.
@@ -87,7 +89,9 @@ private:
void addMarker(Node*, const DocumentMarker&);
typedef Vector<RenderedDocumentMarker> MarkerList;
- typedef HashMap<RefPtr<Node>, OwnPtr<MarkerList> > MarkerMap;
+ typedef Vector<OwnPtr<MarkerList>, DocumentMarker::MarkerTypeIndexesCount> MarkerLists;
+ typedef HashMap<const Node*, OwnPtr<MarkerLists> > MarkerMap;
+ void mergeOverlapping(MarkerList*, DocumentMarker&);
bool possiblyHasMarkers(DocumentMarker::MarkerTypes);
void removeMarkersFromList(MarkerMap::iterator, DocumentMarker::MarkerTypes);
diff --git a/chromium/third_party/WebKit/Source/core/dom/DocumentMarkerControllerTest.cpp b/chromium/third_party/WebKit/Source/core/dom/DocumentMarkerControllerTest.cpp
new file mode 100644
index 00000000000..f7132ed5527
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/DocumentMarkerControllerTest.cpp
@@ -0,0 +1,181 @@
+/*
+ * Copyright (c) 2013, Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/dom/DocumentMarkerController.h"
+
+#include "bindings/v8/ExceptionStatePlaceholder.h"
+#include "core/dom/Document.h"
+#include "core/dom/Range.h"
+#include "core/dom/Text.h"
+#include "core/html/HTMLElement.h"
+#include "core/testing/DummyPageHolder.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefPtr.h"
+#include "wtf/testing/WTFTestHelpers.h"
+#include <gtest/gtest.h>
+
+using namespace WebCore;
+
+namespace {
+
+class DocumentMarkerControllerTest : public ::testing::Test {
+protected:
+ virtual void SetUp() OVERRIDE;
+
+ Document& document() const { return *m_document; }
+ DocumentMarkerController& markerController() const { return *m_document->markers(); }
+
+ PassRefPtr<Text> createTextNode(const char*);
+ void markNodeContents(PassRefPtr<Node>);
+ void setBodyInnerHTML(const char*);
+
+private:
+ OwnPtr<DummyPageHolder> m_dummyPageHolder;
+ Document* m_document;
+};
+
+void DocumentMarkerControllerTest::SetUp()
+{
+ m_dummyPageHolder = DummyPageHolder::create(IntSize(800, 600));
+ m_document = &m_dummyPageHolder->document();
+ ASSERT(m_document);
+}
+
+PassRefPtr<Text> DocumentMarkerControllerTest::createTextNode(const char* textContents)
+{
+ return document().createTextNode(String::fromUTF8(textContents));
+}
+
+void DocumentMarkerControllerTest::markNodeContents(PassRefPtr<Node> node)
+{
+ // Force renderers to be created; TextIterator, which is used in
+ // DocumentMarkerControllerTest::addMarker(), needs them.
+ document().updateLayout();
+ RefPtr<Range> range = rangeOfContents(node.get());
+ markerController().addMarker(range.get(), DocumentMarker::Spelling);
+}
+
+void DocumentMarkerControllerTest::setBodyInnerHTML(const char* bodyContent)
+{
+ document().body()->setInnerHTML(String::fromUTF8(bodyContent), ASSERT_NO_EXCEPTION);
+}
+
+TEST_F(DocumentMarkerControllerTest, NodeWillBeRemovedMarkedByNormalize)
+{
+ setBodyInnerHTML("<b><i>foo</i></b>");
+ {
+ RefPtr<Element> parent = toElement(document().body()->firstChild()->firstChild());
+ parent->appendChild(createTextNode("bar").get());
+ markNodeContents(parent.get());
+ EXPECT_EQ(2u, markerController().markers().size());
+ parent->normalize();
+ }
+ // No more reference to marked node.
+ EXPECT_EQ(1u, markerController().markers().size());
+}
+
+TEST_F(DocumentMarkerControllerTest, NodeWillBeRemovedMarkedByRemoveChildren)
+{
+ setBodyInnerHTML("<b><i>foo</i></b>");
+ RefPtr<Element> parent = toElement(document().body()->firstChild()->firstChild());
+ markNodeContents(parent.get());
+ EXPECT_EQ(1u, markerController().markers().size());
+ parent->removeChildren();
+ // No more reference to marked node.
+ EXPECT_EQ(0u, markerController().markers().size());
+}
+
+TEST_F(DocumentMarkerControllerTest, NodeWillBeRemovedByRemoveMarked)
+{
+ setBodyInnerHTML("<b><i>foo</i></b>");
+ {
+ RefPtr<Element> parent = toElement(document().body()->firstChild()->firstChild());
+ markNodeContents(parent);
+ EXPECT_EQ(1u, markerController().markers().size());
+ parent->removeChild(parent->firstChild());
+ }
+ // No more reference to marked node.
+ EXPECT_EQ(0u, markerController().markers().size());
+}
+
+TEST_F(DocumentMarkerControllerTest, NodeWillBeRemovedMarkedByRemoveAncestor)
+{
+ setBodyInnerHTML("<b><i>foo</i></b>");
+ {
+ RefPtr<Element> parent = toElement(document().body()->firstChild()->firstChild());
+ markNodeContents(parent);
+ EXPECT_EQ(1u, markerController().markers().size());
+ parent->parentNode()->parentNode()->removeChild(parent->parentNode());
+ }
+ // No more reference to marked node.
+ EXPECT_EQ(0u, markerController().markers().size());
+}
+
+TEST_F(DocumentMarkerControllerTest, NodeWillBeRemovedMarkedByRemoveParent)
+{
+ setBodyInnerHTML("<b><i>foo</i></b>");
+ {
+ RefPtr<Element> parent = toElement(document().body()->firstChild()->firstChild());
+ markNodeContents(parent);
+ EXPECT_EQ(1u, markerController().markers().size());
+ parent->parentNode()->removeChild(parent.get());
+ }
+ // No more reference to marked node.
+ EXPECT_EQ(0u, markerController().markers().size());
+}
+
+TEST_F(DocumentMarkerControllerTest, NodeWillBeRemovedMarkedByReplaceChild)
+{
+ setBodyInnerHTML("<b><i>foo</i></b>");
+ {
+ RefPtr<Element> parent = toElement(document().body()->firstChild()->firstChild());
+ markNodeContents(parent.get());
+ EXPECT_EQ(1u, markerController().markers().size());
+ parent->replaceChild(createTextNode("bar").get(), parent->firstChild());
+ }
+ // No more reference to marked node.
+ EXPECT_EQ(0u, markerController().markers().size());
+}
+
+TEST_F(DocumentMarkerControllerTest, NodeWillBeRemovedBySetInnerHTML)
+{
+ setBodyInnerHTML("<b><i>foo</i></b>");
+ {
+ RefPtr<Element> parent = toElement(document().body()->firstChild()->firstChild());
+ markNodeContents(parent);
+ EXPECT_EQ(1u, markerController().markers().size());
+ setBodyInnerHTML("");
+ }
+ // No more reference to marked node.
+ EXPECT_EQ(0u, markerController().markers().size());
+}
+
+}
diff --git a/chromium/third_party/WebKit/Source/core/dom/DocumentOrderedList.cpp b/chromium/third_party/WebKit/Source/core/dom/DocumentOrderedList.cpp
index 62802ccbfaf..49520e692d1 100644
--- a/chromium/third_party/WebKit/Source/core/dom/DocumentOrderedList.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/DocumentOrderedList.cpp
@@ -64,9 +64,9 @@ void DocumentOrderedList::parserAdd(Node* node)
m_nodes.add(node);
}
-void DocumentOrderedList::remove(Node* node)
+void DocumentOrderedList::remove(const Node* node)
{
- m_nodes.remove(node);
+ m_nodes.remove(const_cast<Node*>(node));
}
}
diff --git a/chromium/third_party/WebKit/Source/core/dom/DocumentOrderedList.h b/chromium/third_party/WebKit/Source/core/dom/DocumentOrderedList.h
index 8dde172864e..133a34df77f 100644
--- a/chromium/third_party/WebKit/Source/core/dom/DocumentOrderedList.h
+++ b/chromium/third_party/WebKit/Source/core/dom/DocumentOrderedList.h
@@ -42,7 +42,7 @@ public:
void add(Node*);
void parserAdd(Node*);
- void remove(Node*);
+ void remove(const Node*);
bool isEmpty() const { return m_nodes.isEmpty(); }
void clear() { m_nodes.clear(); }
diff --git a/chromium/third_party/WebKit/Source/core/dom/DocumentOrderedMap.cpp b/chromium/third_party/WebKit/Source/core/dom/DocumentOrderedMap.cpp
index bd58170866d..494d266768f 100644
--- a/chromium/third_party/WebKit/Source/core/dom/DocumentOrderedMap.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/DocumentOrderedMap.cpp
@@ -122,7 +122,8 @@ inline Element* DocumentOrderedMap::get(StringImpl* key, const TreeScope* scope)
if (m_duplicateCounts.contains(key)) {
// We know there's at least one node that matches; iterate to find the first one.
- for (element = ElementTraversal::firstWithin(scope->rootNode()); element; element = ElementTraversal::next(element)) {
+ ASSERT(scope->rootNode());
+ for (element = ElementTraversal::firstWithin(*scope->rootNode()); element; element = ElementTraversal::next(*element)) {
if (!keyMatches(key, element))
continue;
m_duplicateCounts.remove(key);
diff --git a/chromium/third_party/WebKit/Source/core/dom/DocumentParser.cpp b/chromium/third_party/WebKit/Source/core/dom/DocumentParser.cpp
index dcafb092c93..ac2ffa99a21 100644
--- a/chromium/third_party/WebKit/Source/core/dom/DocumentParser.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/DocumentParser.cpp
@@ -25,6 +25,7 @@
#include "config.h"
#include "core/dom/DocumentParser.h"
+#include "core/fetch/TextResourceDecoder.h"
#include "wtf/Assertions.h"
@@ -46,6 +47,16 @@ DocumentParser::~DocumentParser()
ASSERT(!m_document);
}
+void DocumentParser::setDecoder(PassOwnPtr<TextResourceDecoder>)
+{
+ ASSERT_NOT_REACHED();
+}
+
+TextResourceDecoder* DocumentParser::decoder()
+{
+ return 0;
+}
+
void DocumentParser::startParsing()
{
m_state = ParsingState;
diff --git a/chromium/third_party/WebKit/Source/core/dom/DocumentParser.h b/chromium/third_party/WebKit/Source/core/dom/DocumentParser.h
index 3b3969b21c1..c0b502ae36b 100644
--- a/chromium/third_party/WebKit/Source/core/dom/DocumentParser.h
+++ b/chromium/third_party/WebKit/Source/core/dom/DocumentParser.h
@@ -26,6 +26,7 @@
#include "wtf/Forward.h"
#include "wtf/RefCounted.h"
+#include "wtf/RefPtr.h"
namespace WebCore {
@@ -33,6 +34,7 @@ class Document;
class DocumentWriter;
class SegmentedString;
class ScriptableDocumentParser;
+class TextResourceDecoder;
class DocumentParser : public RefCounted<DocumentParser> {
public:
@@ -46,10 +48,13 @@ public:
// insert is used by document.write.
virtual void insert(const SegmentedString&) = 0;
- // appendBytes and flush are used by DocumentWriter (the loader).
- virtual size_t appendBytes(const char* bytes, size_t length) = 0;
- virtual size_t flush() = 0;
+ // The below functions are used by DocumentWriter (the loader).
+ virtual void appendBytes(const char* bytes, size_t length) = 0;
+ virtual void flush() = 0;
virtual bool needsDecoder() const { return false; }
+ virtual void setDecoder(PassOwnPtr<TextResourceDecoder>);
+ virtual TextResourceDecoder* decoder();
+ virtual void setHasAppendedData() { }
// pinToMainThread also makes append() not yield before completion of that chunk.
virtual void pinToMainThread() { }
diff --git a/chromium/third_party/WebKit/Source/core/dom/DocumentStyleSheetCollection.cpp b/chromium/third_party/WebKit/Source/core/dom/DocumentStyleSheetCollection.cpp
index c4e18a94a38..94421382571 100644
--- a/chromium/third_party/WebKit/Source/core/dom/DocumentStyleSheetCollection.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/DocumentStyleSheetCollection.cpp
@@ -28,6 +28,7 @@
#include "core/dom/DocumentStyleSheetCollection.h"
#include "HTMLNames.h"
+#include "RuntimeEnabledFeatures.h"
#include "SVGNames.h"
#include "core/css/CSSStyleSheet.h"
#include "core/css/resolver/StyleResolver.h"
@@ -38,7 +39,7 @@
#include "core/html/HTMLIFrameElement.h"
#include "core/html/HTMLLinkElement.h"
#include "core/html/HTMLStyleElement.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
#include "core/svg/SVGStyleElement.h"
namespace WebCore {
@@ -48,14 +49,11 @@ using namespace HTMLNames;
DocumentStyleSheetCollection::DocumentStyleSheetCollection(TreeScope& treeScope)
: StyleSheetCollection(treeScope)
{
- ASSERT(treeScope.rootNode() == &treeScope.rootNode()->document());
+ ASSERT(treeScope.rootNode() == treeScope.rootNode()->document());
}
-void DocumentStyleSheetCollection::collectStyleSheets(StyleEngine* collections, Vector<RefPtr<StyleSheet> >& styleSheets, Vector<RefPtr<CSSStyleSheet> >& activeSheets)
+void DocumentStyleSheetCollection::collectStyleSheetsFromCandidates(StyleEngine* engine, StyleSheetCollectionBase& collection, DocumentStyleSheetCollection::CollectFor collectFor)
{
- if (document()->settings() && !document()->settings()->authorAndUserStylesEnabled())
- return;
-
DocumentOrderedList::iterator begin = m_styleSheetCandidateNodes.begin();
DocumentOrderedList::iterator end = m_styleSheetCandidateNodes.end();
for (DocumentOrderedList::iterator it = begin; it != end; ++it) {
@@ -67,7 +65,7 @@ void DocumentStyleSheetCollection::collectStyleSheets(StyleEngine* collections,
// We don't support linking to embedded CSS stylesheets, see <https://bugs.webkit.org/show_bug.cgi?id=49281> for discussion.
ProcessingInstruction* pi = toProcessingInstruction(n);
// Don't apply XSL transforms to already transformed documents -- <rdar://problem/4132806>
- if (pi->isXSL() && !document()->transformSourceDocument()) {
+ if (RuntimeEnabledFeatures::xsltEnabled() && pi->isXSL() && !document()->transformSourceDocument()) {
// Don't apply XSL transforms until loading is finished.
if (!document()->parsing() && !pi->isLoading())
document()->applyXSLTransform(pi);
@@ -75,7 +73,7 @@ void DocumentStyleSheetCollection::collectStyleSheets(StyleEngine* collections,
}
sheet = pi->sheet();
if (sheet && !sheet->disabled() && sheet->isCSSStyleSheet())
- activeSheet = static_cast<CSSStyleSheet*>(sheet);
+ activeSheet = toCSSStyleSheet(sheet);
} else if ((n->isHTMLElement() && (n->hasTagName(linkTag) || n->hasTagName(styleTag))) || (n->isSVGElement() && n->hasTagName(SVGNames::styleTag))) {
Element* e = toElement(n);
AtomicString title = e->getAttribute(titleAttr);
@@ -86,11 +84,11 @@ void DocumentStyleSheetCollection::collectStyleSheets(StyleEngine* collections,
enabledViaScript = linkElement->isEnabledViaScript();
if (!linkElement->isDisabled() && linkElement->styleSheetIsLoading()) {
// it is loading but we should still decide which style sheet set to use
- if (!enabledViaScript && !title.isEmpty() && collections->preferredStylesheetSetName().isEmpty()) {
+ if (!enabledViaScript && !title.isEmpty() && engine->preferredStylesheetSetName().isEmpty()) {
const AtomicString& rel = e->getAttribute(relAttr);
if (!rel.contains("alternate")) {
- collections->setPreferredStylesheetSetName(title);
- collections->setSelectedStylesheetSetName(title);
+ engine->setPreferredStylesheetSetName(title);
+ engine->setSelectedStylesheetSetName(title);
}
}
@@ -106,7 +104,7 @@ void DocumentStyleSheetCollection::collectStyleSheets(StyleEngine* collections,
}
if (sheet && !sheet->disabled() && sheet->isCSSStyleSheet())
- activeSheet = static_cast<CSSStyleSheet*>(sheet);
+ activeSheet = toCSSStyleSheet(sheet);
// Check to see if this sheet belongs to a styleset
// (thus making it PREFERRED or ALTERNATE rather than
@@ -114,73 +112,81 @@ void DocumentStyleSheetCollection::collectStyleSheets(StyleEngine* collections,
AtomicString rel = e->getAttribute(relAttr);
if (!enabledViaScript && sheet && !title.isEmpty()) {
// Yes, we have a title.
- if (collections->preferredStylesheetSetName().isEmpty()) {
+ if (engine->preferredStylesheetSetName().isEmpty()) {
// No preferred set has been established. If
// we are NOT an alternate sheet, then establish
// us as the preferred set. Otherwise, just ignore
// this sheet.
if (e->hasLocalName(styleTag) || !rel.contains("alternate")) {
- collections->setPreferredStylesheetSetName(title);
- collections->setSelectedStylesheetSetName(title);
+ engine->setPreferredStylesheetSetName(title);
+ engine->setSelectedStylesheetSetName(title);
}
}
- if (title != collections->preferredStylesheetSetName())
+ if (title != engine->preferredStylesheetSetName())
activeSheet = 0;
}
if (rel.contains("alternate") && title.isEmpty())
activeSheet = 0;
}
- if (sheet)
- styleSheets.append(sheet);
+
+ if (sheet && collectFor == CollectForList)
+ collection.appendSheetForList(sheet);
if (activeSheet)
- activeSheets.append(activeSheet);
+ collection.appendActiveStyleSheet(activeSheet);
}
}
-static void collectActiveCSSStyleSheetsFromSeamlessParents(Vector<RefPtr<CSSStyleSheet> >& sheets, Document* document)
+static void collectActiveCSSStyleSheetsFromSeamlessParents(StyleSheetCollectionBase& collection, Document* document)
{
HTMLIFrameElement* seamlessParentIFrame = document->seamlessParentIFrame();
if (!seamlessParentIFrame)
return;
- sheets.append(seamlessParentIFrame->document().styleEngine()->activeAuthorStyleSheets());
+ collection.appendActiveStyleSheets(seamlessParentIFrame->document().styleEngine()->activeAuthorStyleSheets());
+}
+
+void DocumentStyleSheetCollection::collectStyleSheets(StyleEngine* engine, StyleSheetCollectionBase& collection, DocumentStyleSheetCollection::CollectFor colletFor)
+{
+ ASSERT(document()->styleEngine() == engine);
+ collection.appendActiveStyleSheets(engine->injectedAuthorStyleSheets());
+ collection.appendActiveStyleSheets(engine->documentAuthorStyleSheets());
+ collectActiveCSSStyleSheetsFromSeamlessParents(collection, document());
+ collectStyleSheetsFromCandidates(engine, collection, colletFor);
}
-bool DocumentStyleSheetCollection::updateActiveStyleSheets(StyleEngine* collections, StyleResolverUpdateMode updateMode)
+bool DocumentStyleSheetCollection::updateActiveStyleSheets(StyleEngine* engine, StyleResolverUpdateMode updateMode)
{
- Vector<RefPtr<StyleSheet> > styleSheets;
- Vector<RefPtr<CSSStyleSheet> > activeCSSStyleSheets;
- activeCSSStyleSheets.append(collections->injectedAuthorStyleSheets());
- activeCSSStyleSheets.append(collections->documentAuthorStyleSheets());
- collectActiveCSSStyleSheetsFromSeamlessParents(activeCSSStyleSheets, document());
- collectStyleSheets(collections, styleSheets, activeCSSStyleSheets);
-
- StyleResolverUpdateType styleResolverUpdateType;
- bool requiresFullStyleRecalc;
- analyzeStyleSheetChange(updateMode, activeAuthorStyleSheets(), activeCSSStyleSheets, styleResolverUpdateType, requiresFullStyleRecalc);
-
- if (styleResolverUpdateType == Reconstruct) {
- document()->clearStyleResolver();
- } else {
- StyleResolver* styleResolver = document()->styleResolverIfExists();
- ASSERT(styleResolver);
+ StyleSheetCollectionBase collection;
+ engine->collectDocumentActiveStyleSheets(collection);
+
+ StyleSheetChange change;
+ analyzeStyleSheetChange(updateMode, collection, change);
+
+ if (change.styleResolverUpdateType == Reconstruct) {
+ engine->clearMasterResolver();
+ engine->resetFontSelector();
+ } else if (StyleResolver* styleResolver = engine->resolver()) {
// FIXME: We might have already had styles in child treescope. In this case, we cannot use buildScopedStyleTreeInDocumentOrder.
// Need to change "false" to some valid condition.
styleResolver->setBuildScopedStyleTreeInDocumentOrder(false);
- if (styleResolverUpdateType == Reset) {
+ if (change.styleResolverUpdateType != Additive) {
+ ASSERT(change.styleResolverUpdateType == Reset || change.styleResolverUpdateType == ResetStyleResolverAndFontSelector);
resetAllRuleSetsInTreeScope(styleResolver);
- styleResolver->appendAuthorStyleSheets(0, activeCSSStyleSheets);
+ if (change.styleResolverUpdateType == ResetStyleResolverAndFontSelector)
+ engine->resetFontSelector();
+ styleResolver->removePendingAuthorStyleSheets(m_activeAuthorStyleSheets);
+ styleResolver->lazyAppendAuthorStyleSheets(0, collection.activeAuthorStyleSheets());
} else {
- ASSERT(styleResolverUpdateType == Additive);
- styleResolver->appendAuthorStyleSheets(m_activeAuthorStyleSheets.size(), activeCSSStyleSheets);
+ styleResolver->lazyAppendAuthorStyleSheets(m_activeAuthorStyleSheets.size(), collection.activeAuthorStyleSheets());
}
+ } else if (change.styleResolverUpdateType == ResetStyleResolverAndFontSelector) {
+ engine->resetFontSelector();
}
m_scopingNodesForStyleScoped.didRemoveScopingNodes();
- m_activeAuthorStyleSheets.swap(activeCSSStyleSheets);
- m_styleSheetsForStyleSheetList.swap(styleSheets);
+ collection.swap(*this);
updateUsesRemUnits();
- return requiresFullStyleRecalc;
+ return change.requiresFullStyleRecalc;
}
}
diff --git a/chromium/third_party/WebKit/Source/core/dom/DocumentStyleSheetCollection.h b/chromium/third_party/WebKit/Source/core/dom/DocumentStyleSheetCollection.h
index 1a039fbdb92..9920ad8a848 100644
--- a/chromium/third_party/WebKit/Source/core/dom/DocumentStyleSheetCollection.h
+++ b/chromium/third_party/WebKit/Source/core/dom/DocumentStyleSheetCollection.h
@@ -43,10 +43,16 @@ class DocumentStyleSheetCollection FINAL : public StyleSheetCollection {
public:
explicit DocumentStyleSheetCollection(TreeScope&);
+ enum CollectFor {
+ CollectForList,
+ DontCollectForList
+ };
+
bool updateActiveStyleSheets(StyleEngine*, StyleResolverUpdateMode);
+ void collectStyleSheets(StyleEngine*, StyleSheetCollectionBase&, CollectFor);
private:
- void collectStyleSheets(StyleEngine*, Vector<RefPtr<StyleSheet> >& styleSheets, Vector<RefPtr<CSSStyleSheet> >& activeSheets);
+ void collectStyleSheetsFromCandidates(StyleEngine*, StyleSheetCollectionBase&, CollectFor);
};
}
diff --git a/chromium/third_party/WebKit/Source/core/dom/DocumentSupplementable.h b/chromium/third_party/WebKit/Source/core/dom/DocumentSupplementable.h
new file mode 100644
index 00000000000..9b5e7790af0
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/DocumentSupplementable.h
@@ -0,0 +1,42 @@
+/*
+ * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
+ * (C) 1999 Antti Koivisto (koivisto@kde.org)
+ * (C) 2001 Dirk Mueller (mueller@kde.org)
+ * (C) 2006 Alexey Proskuryakov (ap@webkit.org)
+ * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2012 Apple Inc. All rights reserved.
+ * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
+ * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ */
+
+#ifndef DocumentSupplementable_h
+#define DocumentSupplementable_h
+
+#include "platform/Supplementable.h"
+
+namespace WebCore {
+
+class Document;
+
+typedef Supplementable<Document> DocumentSupplementable;
+typedef Supplement<Document> DocumentSupplement;
+
+} // namespace WebCore
+
+#endif // DocumentSupplementable_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/DocumentType.h b/chromium/third_party/WebKit/Source/core/dom/DocumentType.h
index 7da8ac879b5..6aa51fe4194 100644
--- a/chromium/third_party/WebKit/Source/core/dom/DocumentType.h
+++ b/chromium/third_party/WebKit/Source/core/dom/DocumentType.h
@@ -64,17 +64,7 @@ private:
String m_subset;
};
-inline DocumentType* toDocumentType(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->nodeType() == Node::DOCUMENT_TYPE_NODE);
- return static_cast<DocumentType*>(node);
-}
-
-inline const DocumentType* toDocumentType(const Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->nodeType() == Node::DOCUMENT_TYPE_NODE);
- return static_cast<const DocumentType*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(DocumentType, nodeType() == Node::DOCUMENT_TYPE_NODE);
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/Element.cpp b/chromium/third_party/WebKit/Source/core/dom/Element.cpp
index 7699ff200bb..8be9f406e93 100644
--- a/chromium/third_party/WebKit/Source/core/dom/Element.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/Element.cpp
@@ -26,9 +26,7 @@
#include "config.h"
#include "core/dom/Element.h"
-#include "CSSPropertyNames.h"
#include "CSSValueKeywords.h"
-#include "HTMLNames.h"
#include "RuntimeEnabledFeatures.h"
#include "SVGNames.h"
#include "XMLNames.h"
@@ -43,18 +41,13 @@
#include "core/css/StylePropertySet.h"
#include "core/css/resolver/StyleResolver.h"
#include "core/dom/Attr.h"
-#include "core/dom/Attribute.h"
+#include "core/dom/CSSSelectorWatch.h"
#include "core/dom/ClientRect.h"
#include "core/dom/ClientRectList.h"
-#include "core/dom/CustomElement.h"
-#include "core/dom/CustomElementRegistrationContext.h"
#include "core/dom/DatasetDOMStringMap.h"
-#include "core/dom/Document.h"
#include "core/dom/DocumentSharedObjectPool.h"
#include "core/dom/ElementRareData.h"
-#include "core/dom/EventDispatcher.h"
#include "core/dom/ExceptionCode.h"
-#include "core/dom/FocusEvent.h"
#include "core/dom/FullscreenElementStack.h"
#include "core/dom/MutationObserverInterestGroup.h"
#include "core/dom/MutationRecord.h"
@@ -62,16 +55,24 @@
#include "core/dom/NodeRenderStyle.h"
#include "core/dom/NodeRenderingContext.h"
#include "core/dom/PostAttachCallbacks.h"
+#include "core/dom/PresentationAttributeStyle.h"
#include "core/dom/PseudoElement.h"
#include "core/dom/ScriptableDocumentParser.h"
#include "core/dom/SelectorQuery.h"
#include "core/dom/Text.h"
-#include "core/dom/WhitespaceChildList.h"
+#include "core/dom/custom/CustomElement.h"
+#include "core/dom/custom/CustomElementRegistrationContext.h"
#include "core/dom/shadow/InsertionPoint.h"
#include "core/dom/shadow/ShadowRoot.h"
#include "core/editing/FrameSelection.h"
#include "core/editing/TextIterator.h"
#include "core/editing/htmlediting.h"
+#include "core/editing/markup.h"
+#include "core/events/EventDispatcher.h"
+#include "core/events/FocusEvent.h"
+#include "core/frame/ContentSecurityPolicy.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
#include "core/html/ClassList.h"
#include "core/html/HTMLCollection.h"
#include "core/html/HTMLDocument.h"
@@ -81,15 +82,14 @@
#include "core/html/HTMLLabelElement.h"
#include "core/html/HTMLOptionsCollection.h"
#include "core/html/HTMLTableRowsCollection.h"
+#include "core/html/HTMLTemplateElement.h"
#include "core/html/parser/HTMLParserIdioms.h"
-#include "core/page/ContentSecurityPolicy.h"
+#include "core/inspector/InspectorInstrumentation.h"
#include "core/page/FocusController.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameView.h"
#include "core/page/Page.h"
#include "core/page/PointerLockController.h"
#include "core/rendering/FlowThreadController.h"
-#include "core/rendering/RenderRegion.h"
+#include "core/rendering/RenderNamedFlowFragment.h"
#include "core/rendering/RenderView.h"
#include "core/rendering/RenderWidget.h"
#include "core/svg/SVGDocumentExtensions.h"
@@ -104,14 +104,9 @@ namespace WebCore {
using namespace HTMLNames;
using namespace XMLNames;
-static inline bool shouldIgnoreAttributeCase(const Element* e)
-{
- return e && e->document().isHTMLDocument() && e->isHTMLElement();
-}
-
class StyleResolverParentPusher {
public:
- StyleResolverParentPusher(Element* parent)
+ explicit StyleResolverParentPusher(Element& parent)
: m_parent(parent)
, m_pushedStyleResolver(0)
{
@@ -120,7 +115,7 @@ public:
{
if (m_pushedStyleResolver)
return;
- m_pushedStyleResolver = m_parent->document().styleResolver();
+ m_pushedStyleResolver = &m_parent.document().ensureStyleResolver();
m_pushedStyleResolver->pushParentElement(m_parent);
}
~StyleResolverParentPusher()
@@ -131,15 +126,15 @@ public:
// This tells us that our pushed style selector is in a bad state,
// so we should just bail out in that scenario.
- ASSERT(m_pushedStyleResolver == m_parent->document().styleResolver());
- if (m_pushedStyleResolver != m_parent->document().styleResolver())
+ ASSERT(m_pushedStyleResolver == m_parent.document().styleResolver());
+ if (m_pushedStyleResolver != m_parent.document().styleResolver())
return;
m_pushedStyleResolver->popParentElement(m_parent);
}
private:
- Element* m_parent;
+ Element& m_parent;
StyleResolver* m_pushedStyleResolver;
};
@@ -160,16 +155,16 @@ static AttrNodeList* attrNodeListForElement(Element* element)
return attrNodeListMap().get(element);
}
-static AttrNodeList* ensureAttrNodeListForElement(Element* element)
+static AttrNodeList& ensureAttrNodeListForElement(Element* element)
{
if (element->hasSyntheticAttrChildNodes()) {
ASSERT(attrNodeListMap().contains(element));
- return attrNodeListMap().get(element);
+ return *attrNodeListMap().get(element);
}
ASSERT(!attrNodeListMap().contains(element));
element->setHasSyntheticAttrChildNodes(true);
AttrNodeListMap::AddResult result = attrNodeListMap().add(element, adoptPtr(new AttrNodeList));
- return result.iterator->value.get();
+ return *result.iterator->value;
}
static void removeAttrNodeListForElement(Element* element)
@@ -180,11 +175,12 @@ static void removeAttrNodeListForElement(Element* element)
element->setHasSyntheticAttrChildNodes(false);
}
-static Attr* findAttrNodeInList(AttrNodeList* attrNodeList, const QualifiedName& name)
+static Attr* findAttrNodeInList(const AttrNodeList& attrNodeList, const QualifiedName& name)
{
- for (unsigned i = 0; i < attrNodeList->size(); ++i) {
- if (attrNodeList->at(i)->qualifiedName() == name)
- return attrNodeList->at(i).get();
+ AttrNodeList::const_iterator end = attrNodeList.end();
+ for (AttrNodeList::const_iterator it = attrNodeList.begin(); it != end; ++it) {
+ if ((*it)->qualifiedName() == name)
+ return it->get();
}
return 0;
}
@@ -196,14 +192,10 @@ PassRefPtr<Element> Element::create(const QualifiedName& tagName, Document* docu
Element::~Element()
{
-#ifndef NDEBUG
- if (document().renderer()) {
- // When the document is not destroyed, an element that was part of a named flow
- // content nodes should have been removed from the content nodes collection
- // and the inNamedFlow flag reset.
- ASSERT(!inNamedFlow());
- }
-#endif
+ // When the document is not destroyed, an element that was part of a named flow
+ // content nodes should have been removed from the content nodes collection
+ // and the inNamedFlow flag reset.
+ ASSERT(!document().renderView() || !inNamedFlow());
if (PropertySetCSSStyleDeclaration* cssomWrapper = inlineStyleCSSOMWrapper())
cssomWrapper->clearParentElement();
@@ -217,7 +209,7 @@ Element::~Element()
if (RuntimeEnabledFeatures::webAnimationsCSSEnabled()) {
if (ActiveAnimations* activeAnimations = data->activeAnimations())
- activeAnimations->cssAnimations()->cancel();
+ activeAnimations->cssAnimations().cancel();
}
}
@@ -239,9 +231,9 @@ inline ElementRareData* Element::elementRareData() const
return static_cast<ElementRareData*>(rareData());
}
-inline ElementRareData* Element::ensureElementRareData()
+inline ElementRareData& Element::ensureElementRareData()
{
- return static_cast<ElementRareData*>(ensureRareData());
+ return static_cast<ElementRareData&>(ensureRareData());
}
void Element::clearTabIndexExplicitlyIfNeeded()
@@ -252,7 +244,7 @@ void Element::clearTabIndexExplicitlyIfNeeded()
void Element::setTabIndexExplicitly(short tabIndex)
{
- ensureElementRareData()->setTabIndexExplicitly(tabIndex);
+ ensureElementRareData().setTabIndexExplicitly(tabIndex);
}
bool Element::supportsFocus() const
@@ -297,11 +289,6 @@ bool Element::rendererIsFocusable() const
return true;
}
-DEFINE_VIRTUAL_ATTRIBUTE_EVENT_LISTENER(Element, blur);
-DEFINE_VIRTUAL_ATTRIBUTE_EVENT_LISTENER(Element, error);
-DEFINE_VIRTUAL_ATTRIBUTE_EVENT_LISTENER(Element, focus);
-DEFINE_VIRTUAL_ATTRIBUTE_EVENT_LISTENER(Element, load);
-
PassRefPtr<Node> Element::cloneNode(bool deep)
{
return deep ? cloneElementWithChildren() : cloneElementWithoutChildren();
@@ -378,32 +365,32 @@ void Element::setBooleanAttribute(const QualifiedName& name, bool value)
NamedNodeMap* Element::attributes() const
{
- ElementRareData* rareData = const_cast<Element*>(this)->ensureElementRareData();
- if (NamedNodeMap* attributeMap = rareData->attributeMap())
+ ElementRareData& rareData = const_cast<Element*>(this)->ensureElementRareData();
+ if (NamedNodeMap* attributeMap = rareData.attributeMap())
return attributeMap;
- rareData->setAttributeMap(NamedNodeMap::create(const_cast<Element*>(this)));
- return rareData->attributeMap();
+ rareData.setAttributeMap(NamedNodeMap::create(const_cast<Element*>(this)));
+ return rareData.attributeMap();
}
ActiveAnimations* Element::activeAnimations() const
{
- if (hasActiveAnimations())
+ if (hasRareData())
return elementRareData()->activeAnimations();
return 0;
}
ActiveAnimations* Element::ensureActiveAnimations()
{
- ElementRareData* rareData = ensureElementRareData();
- if (!elementRareData()->activeAnimations())
- rareData->setActiveAnimations(adoptPtr(new ActiveAnimations()));
- return rareData->activeAnimations();
+ ElementRareData& rareData = ensureElementRareData();
+ if (!rareData.activeAnimations())
+ rareData.setActiveAnimations(adoptPtr(new ActiveAnimations()));
+ return rareData.activeAnimations();
}
bool Element::hasActiveAnimations() const
{
- if (!RuntimeEnabledFeatures::webAnimationsEnabled())
+ if (!RuntimeEnabledFeatures::webAnimationsCSSEnabled())
return false;
if (!hasRareData())
@@ -452,21 +439,20 @@ inline void Element::synchronizeAttribute(const QualifiedName& name) const
}
}
-inline void Element::synchronizeAttribute(const AtomicString& localName) const
+void Element::synchronizeAttribute(const AtomicString& localName) const
{
// This version of synchronizeAttribute() is streamlined for the case where you don't have a full QualifiedName,
// e.g when called from DOM API.
if (!elementData())
return;
- if (elementData()->m_styleAttributeIsDirty && equalPossiblyIgnoringCase(localName, styleAttr.localName(), shouldIgnoreAttributeCase(this))) {
+ if (elementData()->m_styleAttributeIsDirty && equalPossiblyIgnoringCase(localName, styleAttr.localName(), shouldIgnoreAttributeCase())) {
ASSERT(isStyledElement());
synchronizeStyleAttributeInternal();
return;
}
if (elementData()->m_animatedSVGAttributesAreDirty) {
// We're not passing a namespace argument on purpose. SVGNames::*Attr are defined w/o namespaces as well.
- ASSERT(isSVGElement());
- static_cast<const SVGElement*>(this)->synchronizeAnimatedSVGAttribute(QualifiedName(nullAtom, localName, nullAtom));
+ toSVGElement(this)->synchronizeAnimatedSVGAttribute(QualifiedName(nullAtom, localName, nullAtom));
}
}
@@ -524,8 +510,7 @@ void Element::scrollByUnits(int units, ScrollGranularity granularity)
direction = ScrollUp;
units = -units;
}
- Node* stopNode = this;
- toRenderBox(renderer())->scroll(direction, granularity, units, &stopNode);
+ toRenderBox(renderer())->scroll(direction, granularity, units);
}
void Element::scrollByLines(int lines)
@@ -538,16 +523,16 @@ void Element::scrollByPages(int pages)
scrollByUnits(pages, ScrollByPage);
}
-static float localZoomForRenderer(RenderObject* renderer)
+static float localZoomForRenderer(RenderObject& renderer)
{
// FIXME: This does the wrong thing if two opposing zooms are in effect and canceled each
// other out, but the alternative is that we'd have to crawl up the whole render tree every
// time (or store an additional bit in the RenderStyle to indicate that a zoom was specified).
float zoomFactor = 1;
- if (renderer->style()->effectiveZoom() != 1) {
+ if (renderer.style()->effectiveZoom() != 1) {
// Need to find the nearest enclosing RenderObject that set up
// a differing zoom, and then we divide our result by it to eliminate the zoom.
- RenderObject* prev = renderer;
+ RenderObject* prev = &renderer;
for (RenderObject* curr = prev->parent(); curr; curr = curr->parent()) {
if (curr->style()->effectiveZoom() != prev->style()->effectiveZoom()) {
zoomFactor = prev->style()->zoom();
@@ -561,7 +546,7 @@ static float localZoomForRenderer(RenderObject* renderer)
return zoomFactor;
}
-static int adjustForLocalZoom(LayoutUnit value, RenderObject* renderer)
+static int adjustForLocalZoom(LayoutUnit value, RenderObject& renderer)
{
float zoomFactor = localZoomForRenderer(renderer);
if (zoomFactor == 1)
@@ -573,7 +558,7 @@ int Element::offsetLeft()
{
document().partialUpdateLayoutIgnorePendingStylesheets(this);
if (RenderBoxModelObject* renderer = renderBoxModelObject())
- return adjustForLocalZoom(renderer->pixelSnappedOffsetLeft(), renderer);
+ return adjustForLocalZoom(renderer->pixelSnappedOffsetLeft(), *renderer);
return 0;
}
@@ -581,7 +566,7 @@ int Element::offsetTop()
{
document().partialUpdateLayoutIgnorePendingStylesheets(this);
if (RenderBoxModelObject* renderer = renderBoxModelObject())
- return adjustForLocalZoom(renderer->pixelSnappedOffsetTop(), renderer);
+ return adjustForLocalZoom(renderer->pixelSnappedOffsetTop(), *renderer);
return 0;
}
@@ -590,13 +575,13 @@ int Element::offsetWidth()
document().updateStyleForNodeIfNeeded(this);
if (RenderBox* renderer = renderBox()) {
- if (!renderer->requiresLayoutToDetermineWidth())
- return adjustLayoutUnitForAbsoluteZoom(renderer->fixedOffsetWidth(), renderer).round();
+ if (renderer->canDetermineWidthWithoutLayout())
+ return adjustLayoutUnitForAbsoluteZoom(renderer->fixedOffsetWidth(), *renderer).round();
}
document().partialUpdateLayoutIgnorePendingStylesheets(this);
if (RenderBoxModelObject* renderer = renderBoxModelObject())
- return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedOffsetWidth(), renderer).round();
+ return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedOffsetWidth(), *renderer).round();
return 0;
}
@@ -604,7 +589,7 @@ int Element::offsetHeight()
{
document().partialUpdateLayoutIgnorePendingStylesheets(this);
if (RenderBoxModelObject* renderer = renderBoxModelObject())
- return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedOffsetHeight(), renderer).round();
+ return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedOffsetHeight(), *renderer).round();
return 0;
}
@@ -653,12 +638,12 @@ int Element::clientWidth()
|| (inQuirksMode && isHTMLElement() && document().body() == this)) {
if (FrameView* view = document().view()) {
if (RenderView* renderView = document().renderView())
- return adjustForAbsoluteZoom(view->layoutWidth(), renderView);
+ return adjustForAbsoluteZoom(view->layoutSize().width(), renderView);
}
}
if (RenderBox* renderer = renderBox())
- return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedClientWidth(), renderer).round();
+ return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedClientWidth(), *renderer).round();
return 0;
}
@@ -674,43 +659,109 @@ int Element::clientHeight()
|| (inQuirksMode && isHTMLElement() && document().body() == this)) {
if (FrameView* view = document().view()) {
if (RenderView* renderView = document().renderView())
- return adjustForAbsoluteZoom(view->layoutHeight(), renderView);
+ return adjustForAbsoluteZoom(view->layoutSize().height(), renderView);
}
}
if (RenderBox* renderer = renderBox())
- return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedClientHeight(), renderer).round();
+ return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedClientHeight(), *renderer).round();
return 0;
}
int Element::scrollLeft()
{
document().updateLayoutIgnorePendingStylesheets();
- if (RenderBox* rend = renderBox())
- return adjustForAbsoluteZoom(rend->scrollLeft(), rend);
+
+ if (document().documentElement() != this) {
+ if (RenderBox* rend = renderBox())
+ return adjustForAbsoluteZoom(rend->scrollLeft(), rend);
+ return 0;
+ }
+
+ if (RuntimeEnabledFeatures::scrollTopLeftInteropEnabled()) {
+ if (document().inQuirksMode())
+ return 0;
+
+ if (FrameView* view = document().view()) {
+ if (RenderView* renderView = document().renderView())
+ return adjustForAbsoluteZoom(view->scrollX(), renderView);
+ }
+ }
+
return 0;
}
int Element::scrollTop()
{
document().updateLayoutIgnorePendingStylesheets();
- if (RenderBox* rend = renderBox())
- return adjustForAbsoluteZoom(rend->scrollTop(), rend);
+
+ if (document().documentElement() != this) {
+ if (RenderBox* rend = renderBox())
+ return adjustForAbsoluteZoom(rend->scrollTop(), rend);
+ return 0;
+ }
+
+ if (RuntimeEnabledFeatures::scrollTopLeftInteropEnabled()) {
+ if (document().inQuirksMode())
+ return 0;
+
+ if (FrameView* view = document().view()) {
+ if (RenderView* renderView = document().renderView())
+ return adjustForAbsoluteZoom(view->scrollY(), renderView);
+ }
+ }
+
return 0;
}
void Element::setScrollLeft(int newLeft)
{
document().updateLayoutIgnorePendingStylesheets();
- if (RenderBox* rend = renderBox())
- rend->setScrollLeft(static_cast<int>(newLeft * rend->style()->effectiveZoom()));
+
+ if (document().documentElement() != this) {
+ if (RenderBox* rend = renderBox())
+ rend->setScrollLeft(static_cast<int>(newLeft * rend->style()->effectiveZoom()));
+ return;
+ }
+
+ if (RuntimeEnabledFeatures::scrollTopLeftInteropEnabled()) {
+ if (document().inQuirksMode())
+ return;
+
+ Frame* frame = document().frame();
+ if (!frame)
+ return;
+ FrameView* view = frame->view();
+ if (!view)
+ return;
+
+ view->setScrollPosition(IntPoint(static_cast<int>(newLeft * frame->pageZoomFactor()), view->scrollY()));
+ }
}
void Element::setScrollTop(int newTop)
{
document().updateLayoutIgnorePendingStylesheets();
- if (RenderBox* rend = renderBox())
- rend->setScrollTop(static_cast<int>(newTop * rend->style()->effectiveZoom()));
+
+ if (document().documentElement() != this) {
+ if (RenderBox* rend = renderBox())
+ rend->setScrollTop(static_cast<int>(newTop * rend->style()->effectiveZoom()));
+ return;
+ }
+
+ if (RuntimeEnabledFeatures::scrollTopLeftInteropEnabled()) {
+ if (document().inQuirksMode())
+ return;
+
+ Frame* frame = document().frame();
+ if (!frame)
+ return;
+ FrameView* view = frame->view();
+ if (!view)
+ return;
+
+ view->setScrollPosition(IntPoint(view->scrollX(), static_cast<int>(newTop * frame->pageZoomFactor())));
+ }
}
int Element::scrollWidth()
@@ -774,7 +825,7 @@ PassRefPtr<ClientRectList> Element::getClientRects()
Vector<FloatQuad> quads;
renderBoxModelObject->absoluteQuads(quads);
- document().adjustFloatQuadsForScrollAndAbsoluteZoom(quads, renderBoxModelObject);
+ document().adjustFloatQuadsForScrollAndAbsoluteZoom(quads, *renderBoxModelObject);
return ClientRectList::create(quads);
}
@@ -802,7 +853,8 @@ PassRefPtr<ClientRect> Element::getBoundingClientRect()
for (size_t i = 1; i < quads.size(); ++i)
result.unite(quads[i].boundingBox());
- document().adjustFloatRectForScrollAndAbsoluteZoom(result, renderer());
+ ASSERT(renderer());
+ document().adjustFloatRectForScrollAndAbsoluteZoom(result, *renderer());
return ClientRect::create(result);
}
@@ -819,7 +871,7 @@ const AtomicString& Element::getAttribute(const AtomicString& localName) const
if (!elementData())
return nullAtom;
synchronizeAttribute(localName);
- if (const Attribute* attribute = elementData()->getAttributeItem(localName, shouldIgnoreAttributeCase(this)))
+ if (const Attribute* attribute = elementData()->getAttributeItem(localName, shouldIgnoreAttributeCase()))
return attribute->value();
return nullAtom;
}
@@ -829,15 +881,15 @@ const AtomicString& Element::getAttributeNS(const AtomicString& namespaceURI, co
return getAttribute(QualifiedName(nullAtom, localName, namespaceURI));
}
-void Element::setAttribute(const AtomicString& localName, const AtomicString& value, ExceptionState& es)
+void Element::setAttribute(const AtomicString& localName, const AtomicString& value, ExceptionState& exceptionState)
{
if (!Document::isValidName(localName)) {
- es.throwDOMException(InvalidCharacterError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidCharacterError);
return;
}
synchronizeAttribute(localName);
- const AtomicString& caseAdjustedLocalName = shouldIgnoreAttributeCase(this) ? localName.lower() : localName;
+ const AtomicString& caseAdjustedLocalName = shouldIgnoreAttributeCase() ? localName.lower() : localName;
size_t index = elementData() ? elementData()->getAttributeItemIndex(caseAdjustedLocalName, false) : kNotFound;
const QualifiedName& qName = index != kNotFound ? attributeItem(index)->name() : QualifiedName(nullAtom, caseAdjustedLocalName, nullAtom);
@@ -857,7 +909,7 @@ void Element::setSynchronizedLazyAttribute(const QualifiedName& name, const Atom
setAttributeInternal(index, name, value, InSynchronizationOfLazyAttribute);
}
-inline void Element::setAttributeInternal(size_t index, const QualifiedName& name, const AtomicString& newValue, SynchronizationOfLazyAttribute inSynchronizationOfLazyAttribute)
+ALWAYS_INLINE void Element::setAttributeInternal(size_t index, const QualifiedName& name, const AtomicString& newValue, SynchronizationOfLazyAttribute inSynchronizationOfLazyAttribute)
{
if (newValue.isNull()) {
if (index != kNotFound)
@@ -870,12 +922,13 @@ inline void Element::setAttributeInternal(size_t index, const QualifiedName& nam
return;
}
- QualifiedName existingAttributeName = attributeItem(index)->name();
+ const Attribute* existingAttribute = attributeItem(index);
+ QualifiedName existingAttributeName = existingAttribute->name();
if (!inSynchronizationOfLazyAttribute)
- willModifyAttribute(existingAttributeName, attributeItem(index)->value(), newValue);
+ willModifyAttribute(existingAttributeName, existingAttribute->value(), newValue);
- if (newValue != attributeItem(index)->value()) {
+ if (newValue != existingAttribute->value()) {
// If there is an Attr node hooked to this attribute, the Attr::setValue() call below
// will write into the ElementData.
// FIXME: Refactor this so it makes some sense.
@@ -908,7 +961,7 @@ static bool checkNeedsStyleInvalidationForIdChange(const AtomicString& oldId, co
void Element::attributeChanged(const QualifiedName& name, const AtomicString& newValue, AttributeModificationReason reason)
{
- if (ElementShadow* parentElementShadow = shadowOfParentForDistribution(this)) {
+ if (ElementShadow* parentElementShadow = shadowWhereNodeCanBeDistributed(*this)) {
if (shouldInvalidateDistributionWhenAttributeChanged(parentElementShadow, name, newValue))
parentElementShadow->setNeedsDistributionRecalc();
}
@@ -917,8 +970,8 @@ void Element::attributeChanged(const QualifiedName& name, const AtomicString& ne
document().incDOMTreeVersion();
- StyleResolver* styleResolver = document().styleResolverIfExists();
- bool testShouldInvalidateStyle = attached() && styleResolver && styleChangeType() < SubtreeStyleChange;
+ StyleResolver* styleResolver = document().styleResolver();
+ bool testShouldInvalidateStyle = inActiveDocument() && styleResolver && styleChangeType() < SubtreeStyleChange;
bool shouldInvalidateStyle = false;
if (isStyledElement() && name == styleAttr) {
@@ -933,7 +986,7 @@ void Element::attributeChanged(const QualifiedName& name, const AtomicString& ne
AtomicString newId = makeIdForStyleResolution(newValue, document().inQuirksMode());
if (newId != oldId) {
elementData()->setIdForStyleResolution(newId);
- shouldInvalidateStyle = testShouldInvalidateStyle && checkNeedsStyleInvalidationForIdChange(oldId, newId, styleResolver->ruleFeatureSet());
+ shouldInvalidateStyle = testShouldInvalidateStyle && checkNeedsStyleInvalidationForIdChange(oldId, newId, styleResolver->ensureRuleFeatureSet());
}
} else if (name == classAttr) {
classAttributeChanged(newValue);
@@ -958,7 +1011,7 @@ void Element::attributeChanged(const QualifiedName& name, const AtomicString& ne
inline void Element::attributeChangedFromParserOrByCloning(const QualifiedName& name, const AtomicString& newValue, AttributeModificationReason reason)
{
if (name == isAttr)
- CustomElementRegistrationContext::setTypeExtension(this, newValue, reason == ModifiedDirectly ? CustomElementRegistrationContext::CreatedByParser : CustomElementRegistrationContext::NotCreatedByParser);
+ CustomElementRegistrationContext::setTypeExtension(this, newValue);
attributeChanged(name, newValue, reason);
}
@@ -1003,37 +1056,44 @@ static bool checkSelectorForClassChange(const SpaceSplitString& changedClasses,
template<typename Checker>
static bool checkSelectorForClassChange(const SpaceSplitString& oldClasses, const SpaceSplitString& newClasses, const Checker& checker)
{
- unsigned oldSize = oldClasses.size();
- if (!oldSize)
+ if (!oldClasses.size())
return checkSelectorForClassChange(newClasses, checker);
- BitVector remainingClassBits;
- remainingClassBits.ensureSize(oldSize);
+
// Class vectors tend to be very short. This is faster than using a hash table.
- unsigned newSize = newClasses.size();
- for (unsigned i = 0; i < newSize; ++i) {
- for (unsigned j = 0; j < oldSize; ++j) {
+ BitVector remainingClassBits;
+ remainingClassBits.ensureSize(oldClasses.size());
+
+ for (unsigned i = 0; i < newClasses.size(); ++i) {
+ bool found = false;
+ for (unsigned j = 0; j < oldClasses.size(); ++j) {
if (newClasses[i] == oldClasses[j]) {
+ // Mark each class that is still in the newClasses so we can skip doing
+ // an n^2 search below when looking for removals. We can't break from
+ // this loop early since a class can appear more than once.
remainingClassBits.quickSet(j);
- continue;
+ found = true;
}
}
- if (checker.hasSelectorForClass(newClasses[i]))
+ // Class was added.
+ if (!found && checker.hasSelectorForClass(newClasses[i]))
return true;
}
- for (unsigned i = 0; i < oldSize; ++i) {
- // If the bit is not set the the corresponding class has been removed.
+
+ for (unsigned i = 0; i < oldClasses.size(); ++i) {
if (remainingClassBits.quickGet(i))
continue;
+ // Class was removed.
if (checker.hasSelectorForClass(oldClasses[i]))
return true;
}
+
return false;
}
void Element::classAttributeChanged(const AtomicString& newClassString)
{
- StyleResolver* styleResolver = document().styleResolverIfExists();
- bool testShouldInvalidateStyle = attached() && styleResolver && styleChangeType() < SubtreeStyleChange;
+ StyleResolver* styleResolver = document().styleResolver();
+ bool testShouldInvalidateStyle = inActiveDocument() && styleResolver && styleChangeType() < SubtreeStyleChange;
bool shouldInvalidateStyle = false;
if (classStringHasClassName(newClassString)) {
@@ -1041,10 +1101,10 @@ void Element::classAttributeChanged(const AtomicString& newClassString)
const SpaceSplitString oldClasses = elementData()->classNames();
elementData()->setClass(newClassString, shouldFoldCase);
const SpaceSplitString& newClasses = elementData()->classNames();
- shouldInvalidateStyle = testShouldInvalidateStyle && checkSelectorForClassChange(oldClasses, newClasses, styleResolver->ruleFeatureSet());
+ shouldInvalidateStyle = testShouldInvalidateStyle && checkSelectorForClassChange(oldClasses, newClasses, styleResolver->ensureRuleFeatureSet());
} else {
const SpaceSplitString& oldClasses = elementData()->classNames();
- shouldInvalidateStyle = testShouldInvalidateStyle && checkSelectorForClassChange(oldClasses, styleResolver->ruleFeatureSet());
+ shouldInvalidateStyle = testShouldInvalidateStyle && checkSelectorForClassChange(oldClasses, styleResolver->ensureRuleFeatureSet());
elementData()->clearClass();
}
@@ -1169,10 +1229,10 @@ String Element::nodeNamePreservingCase() const
return m_tagName.toString();
}
-void Element::setPrefix(const AtomicString& prefix, ExceptionState& es)
+void Element::setPrefix(const AtomicString& prefix, ExceptionState& exceptionState)
{
- checkSetPrefix(prefix, es);
- if (es.hadException())
+ checkSetPrefix(prefix, exceptionState);
+ if (exceptionState.hadException())
return;
m_tagName.setPrefix(prefix.isEmpty() ? AtomicString() : prefix);
@@ -1220,14 +1280,7 @@ Node::InsertionNotificationRequest Element::insertedInto(ContainerNode* insertio
if (containsFullScreenElement() && parentElement() && !parentElement()->containsFullScreenElement())
setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(true);
- if (Element* before = pseudoElement(BEFORE))
- before->insertedInto(insertionPoint);
-
- if (Element* after = pseudoElement(AFTER))
- after->insertedInto(insertionPoint);
-
- if (Element* backdrop = pseudoElement(BACKDROP))
- backdrop->insertedInto(insertionPoint);
+ ASSERT(!hasRareData() || !elementRareData()->hasPseudoElements());
if (!insertionPoint->isInTreeScope())
return InsertionDone;
@@ -1239,7 +1292,7 @@ Node::InsertionNotificationRequest Element::insertedInto(ContainerNode* insertio
CustomElement::didEnterDocument(this, document());
TreeScope& scope = insertionPoint->treeScope();
- if (&scope != &treeScope())
+ if (scope != treeScope())
return InsertionDone;
const AtomicString& idValue = getIdAttribute();
@@ -1265,15 +1318,7 @@ void Element::removedFrom(ContainerNode* insertionPoint)
{
bool wasInDocument = insertionPoint->inDocument();
- if (Element* before = pseudoElement(BEFORE))
- before->removedFrom(insertionPoint);
-
- if (Element* after = pseudoElement(AFTER))
- after->removedFrom(insertionPoint);
-
- if (Element* backdrop = pseudoElement(BACKDROP))
- backdrop->removedFrom(insertionPoint);
- document().removeFromTopLayer(this);
+ ASSERT(!hasRareData() || !elementRareData()->hasPseudoElements());
if (containsFullScreenElement())
setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(false);
@@ -1283,7 +1328,7 @@ void Element::removedFrom(ContainerNode* insertionPoint)
setSavedLayerScrollOffset(IntSize());
- if (insertionPoint->isInTreeScope() && &treeScope() == &document()) {
+ if (insertionPoint->isInTreeScope() && treeScope() == document()) {
const AtomicString& idValue = getIdAttribute();
if (!idValue.isNull())
updateId(insertionPoint->treeScope(), idValue, nullAtom);
@@ -1308,6 +1353,8 @@ void Element::removedFrom(ContainerNode* insertionPoint)
CustomElement::didLeaveDocument(this, insertionPoint->document());
}
+ document().removeFromTopLayer(this);
+
if (hasRareData())
elementRareData()->setIsInCanvasSubtree(false);
}
@@ -1316,28 +1363,32 @@ void Element::attach(const AttachContext& context)
{
ASSERT(document().inStyleRecalc());
- StyleResolverParentPusher parentPusher(this);
+ StyleResolverParentPusher parentPusher(*this);
- // We've already been through detach when doing a lazyAttach, but we might
+ // We've already been through detach when doing an attach, but we might
// need to clear any state that's been added since then.
- if (hasRareData() && styleChangeType() == LazyAttachStyleChange) {
+ if (hasRareData() && styleChangeType() == NeedsReattachStyleChange) {
ElementRareData* data = elementRareData();
data->clearComputedStyle();
data->resetDynamicRestyleObservations();
+ // Only clear the style state if we're not going to reuse the style from recalcStyle.
if (!context.resolvedStyle)
data->resetStyleState();
}
NodeRenderingContext(this, context.resolvedStyle).createRendererForElementIfNeeded();
+ addCallbackSelectors();
+
createPseudoElementIfNeeded(BEFORE);
// When a shadow root exists, it does the work of attaching the children.
if (ElementShadow* shadow = this->shadow()) {
parentPusher.push();
shadow->attach(context);
- } else if (firstChild())
+ } else if (firstChild()) {
parentPusher.push();
+ }
ContainerNode::attach(context);
@@ -1351,6 +1402,10 @@ void Element::attach(const AttachContext& context)
document().updateFocusAppearanceSoon(false /* don't restore selection */);
data->setNeedsFocusAppearanceUpdateSoonAfterAttach(false);
}
+ if (RuntimeEnabledFeatures::webAnimationsCSSEnabled() && !renderer()) {
+ if (ActiveAnimations* activeAnimations = data->activeAnimations())
+ activeAnimations->cssAnimations().cancel();
+ }
}
InspectorInstrumentation::didRecalculateStyleForElement(this);
@@ -1364,25 +1419,33 @@ void Element::unregisterNamedFlowContentNode()
void Element::detach(const AttachContext& context)
{
- WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;
+ RenderWidget::UpdateSuspendScope suspendWidgetHierarchyUpdates;
unregisterNamedFlowContentNode();
cancelFocusAppearanceUpdate();
+ removeCallbackSelectors();
if (hasRareData()) {
ElementRareData* data = elementRareData();
data->setPseudoElement(BEFORE, 0);
data->setPseudoElement(AFTER, 0);
data->setPseudoElement(BACKDROP, 0);
- data->clearComputedStyle();
- data->resetDynamicRestyleObservations();
data->setIsInsideRegion(false);
- // Only clear the style state if we're not going to reuse the style from recalcStyle.
- if (!context.resolvedStyle)
+ // attach() will perform the below steps for us when inside recalcStyle.
+ if (!document().inStyleRecalc()) {
data->resetStyleState();
+ data->clearComputedStyle();
+ data->resetDynamicRestyleObservations();
+ }
- if (RuntimeEnabledFeatures::webAnimationsCSSEnabled() && !context.performingReattach) {
- if (ActiveAnimations* activeAnimations = data->activeAnimations())
- activeAnimations->cssAnimations()->cancel();
+ if (RuntimeEnabledFeatures::webAnimationsCSSEnabled()) {
+ if (ActiveAnimations* activeAnimations = data->activeAnimations()) {
+ if (context.performingReattach) {
+ // FIXME: restart compositor animations rather than pull back to the main thread
+ activeAnimations->cancelAnimationOnCompositor();
+ } else {
+ activeAnimations->cssAnimations().cancel();
+ }
+ }
}
}
if (ElementShadow* shadow = this->shadow())
@@ -1418,7 +1481,7 @@ bool Element::pseudoStyleCacheIsInvalid(const RenderStyle* currentStyle, RenderS
newStyle->addCachedPseudoStyle(newPseudoStyle);
if (pseudoId == FIRST_LINE || pseudoId == FIRST_LINE_INHERITED) {
// FIXME: We should do an actual diff to determine whether a repaint vs. layout
- // is needed, but for now just assume a layout will be required. The diff code
+ // is needed, but for now just assume a layout will be required. The diff code
// in RenderObject::setStyle would need to be factored out so that it could be reused.
renderer()->setNeedsLayoutAndPrefWidthsRecalc();
}
@@ -1430,58 +1493,83 @@ bool Element::pseudoStyleCacheIsInvalid(const RenderStyle* currentStyle, RenderS
PassRefPtr<RenderStyle> Element::styleForRenderer()
{
- if (hasCustomStyleCallbacks()) {
- if (RefPtr<RenderStyle> style = customStyleForRenderer())
- return style.release();
- }
+ ASSERT(document().inStyleRecalc());
+
+ RefPtr<RenderStyle> style;
+
+ // FIXME: Instead of clearing updates that may have been added from calls to styleForElement
+ // outside recalcStyle, we should just never set them if we're not inside recalcStyle.
+ if (ActiveAnimations* activeAnimations = this->activeAnimations())
+ activeAnimations->cssAnimations().setPendingUpdate(nullptr);
+
+ if (hasCustomStyleCallbacks())
+ style = customStyleForRenderer();
+ if (!style)
+ style = originalStyleForRenderer();
- return originalStyleForRenderer();
+ // styleForElement() might add active animations so we need to get it again.
+ if (ActiveAnimations* activeAnimations = this->activeAnimations())
+ activeAnimations->cssAnimations().maybeApplyPendingUpdate(this);
+
+ ASSERT(style);
+ return style.release();
}
PassRefPtr<RenderStyle> Element::originalStyleForRenderer()
{
- return document().styleResolver()->styleForElement(this);
+ ASSERT(document().inStyleRecalc());
+ return document().ensureStyleResolver().styleForElement(this);
}
-bool Element::recalcStyle(StyleRecalcChange change)
+void Element::recalcStyle(StyleRecalcChange change, Text* nextTextSibling)
{
ASSERT(document().inStyleRecalc());
+ ASSERT(!parentOrShadowHostNode()->needsStyleRecalc());
if (hasCustomStyleCallbacks())
willRecalcStyle(change);
- if (hasRareData() && (change > NoChange || needsStyleRecalc())) {
- ElementRareData* data = elementRareData();
- data->resetStyleState();
- data->clearComputedStyle();
- }
+ if (change >= Inherit || needsStyleRecalc()) {
+ if (hasRareData()) {
+ ElementRareData* data = elementRareData();
+ data->resetStyleState();
+ data->clearComputedStyle();
- // Active InsertionPoints have no renderers so they never need to go through a recalc.
- if ((change >= Inherit || needsStyleRecalc()) && parentRenderStyle() && !isActiveInsertionPoint(this))
- change = recalcOwnStyle(change);
+ if (change >= Inherit) {
+ if (ActiveAnimations* activeAnimations = data->activeAnimations())
+ activeAnimations->setAnimationStyleChange(false);
+ }
+ }
+ if (parentRenderStyle())
+ change = recalcOwnStyle(change);
+ clearNeedsStyleRecalc();
+ }
// If we reattached we don't need to recalc the style of our descendants anymore.
- if (change < Reattach)
+ if ((change >= Inherit && change < Reattach) || childNeedsStyleRecalc())
recalcChildStyle(change);
-
- clearNeedsStyleRecalc();
clearChildNeedsStyleRecalc();
if (hasCustomStyleCallbacks())
didRecalcStyle(change);
- return change == Reattach;
+ if (change == Reattach)
+ reattachWhitespaceSiblings(nextTextSibling);
}
StyleRecalcChange Element::recalcOwnStyle(StyleRecalcChange change)
{
ASSERT(document().inStyleRecalc());
+ ASSERT(!parentOrShadowHostNode()->needsStyleRecalc());
+ ASSERT(change >= Inherit || needsStyleRecalc());
+ ASSERT(parentRenderStyle());
- CSSAnimationUpdateScope cssAnimationUpdateScope(this);
RefPtr<RenderStyle> oldStyle = renderStyle();
RefPtr<RenderStyle> newStyle = styleForRenderer();
StyleRecalcChange localChange = RenderStyle::compare(oldStyle.get(), newStyle.get());
+ ASSERT(newStyle);
+
if (localChange == Reattach) {
AttachContext reattachContext;
reattachContext.resolvedStyle = newStyle.get();
@@ -1489,10 +1577,15 @@ StyleRecalcChange Element::recalcOwnStyle(StyleRecalcChange change)
return Reattach;
}
+ ASSERT(oldStyle);
+
InspectorInstrumentation::didRecalculateStyleForElement(this);
+ if (localChange != NoChange)
+ updateCallbackSelectors(oldStyle.get(), newStyle.get());
+
if (RenderObject* renderer = this->renderer()) {
- if (localChange != NoChange || pseudoStyleCacheIsInvalid(oldStyle.get(), newStyle.get()) || (change == Force && renderer->requiresForcedStyleRecalcPropagation()) || shouldNotifyRendererWithIdenticalStyles()) {
+ if (localChange != NoChange || pseudoStyleCacheIsInvalid(oldStyle.get(), newStyle.get()) || shouldNotifyRendererWithIdenticalStyles()) {
renderer->setAnimatableStyle(newStyle.get());
} else {
// Although no change occurred, we use the new style so that the cousin style sharing code won't get
@@ -1505,9 +1598,9 @@ StyleRecalcChange Element::recalcOwnStyle(StyleRecalcChange change)
// If "rem" units are used anywhere in the document, and if the document element's font size changes, then go ahead and force font updating
// all the way down the tree. This is simpler than having to maintain a cache of objects (and such font size changes should be rare anyway).
- if (document().styleEngine()->usesRemUnits() && document().documentElement() == this && oldStyle && newStyle && oldStyle->fontSize() != newStyle->fontSize()) {
+ if (document().styleEngine()->usesRemUnits() && document().documentElement() == this && oldStyle->fontSize() != newStyle->fontSize()) {
// Cached RenderStyles may depend on the re units.
- document().styleResolver()->invalidateMatchedPropertiesCache();
+ document().ensureStyleResolver().invalidateMatchedPropertiesCache();
return Force;
}
@@ -1520,8 +1613,10 @@ StyleRecalcChange Element::recalcOwnStyle(StyleRecalcChange change)
void Element::recalcChildStyle(StyleRecalcChange change)
{
ASSERT(document().inStyleRecalc());
+ ASSERT(change >= Inherit || childNeedsStyleRecalc());
+ ASSERT(!needsStyleRecalc());
- StyleResolverParentPusher parentPusher(this);
+ StyleResolverParentPusher parentPusher(*this);
for (ShadowRoot* root = youngestShadowRoot(); root; root = root->olderShadowRoot()) {
if (shouldRecalcStyle(change, root)) {
@@ -1533,93 +1628,137 @@ void Element::recalcChildStyle(StyleRecalcChange change)
if (shouldRecalcStyle(change, this))
updatePseudoElement(BEFORE, change);
- // FIXME: This check is good enough for :hover + foo, but it is not good enough for :hover + foo + bar.
- // For now we will just worry about the common case, since it's a lot trickier to get the second case right
- // without doing way too much re-resolution.
- bool hasDirectAdjacentRules = childrenAffectedByDirectAdjacentRules();
- bool hasIndirectAdjacentRules = childrenAffectedByForwardPositionalRules();
- bool forceCheckOfNextElementSibling = false;
- bool forceCheckOfAnyElementSibling = false;
- if (hasDirectAdjacentRules || hasIndirectAdjacentRules) {
- for (Node* child = firstChild(); child; child = child->nextSibling()) {
- if (!child->isElementNode())
- continue;
- Element* element = toElement(child);
- bool childRulesChanged = element->needsStyleRecalc() && element->styleChangeType() >= SubtreeStyleChange;
- if (forceCheckOfNextElementSibling || forceCheckOfAnyElementSibling)
- element->setNeedsStyleRecalc();
- forceCheckOfNextElementSibling = childRulesChanged && hasDirectAdjacentRules;
- forceCheckOfAnyElementSibling = forceCheckOfAnyElementSibling || (childRulesChanged && hasIndirectAdjacentRules);
- }
- }
+ if (change < Force && hasRareData() && childNeedsStyleRecalc())
+ checkForChildrenAdjacentRuleChanges();
+
// This loop is deliberately backwards because we use insertBefore in the rendering tree, and want to avoid
// a potentially n^2 loop to find the insertion point while resolving style. Having us start from the last
// child and work our way back means in the common case, we'll find the insertion point in O(1) time.
- // Reversing this loop can lead to non-deterministic results in our code to optimize out empty whitespace
- // RenderTexts. We try to put off recalcing their style until the end to avoid this issue.
// See crbug.com/288225
- WhitespaceChildList whitespaceChildList(change);
+ StyleResolver& styleResolver = document().ensureStyleResolver();
+ Text* lastTextNode = 0;
for (Node* child = lastChild(); child; child = child->previousSibling()) {
if (child->isTextNode()) {
- Text* textChild = toText(child);
- // FIXME: This check is expensive and may negate the performance gained by the optimization of
- // avoiding whitespace renderers.
- if (textChild->containsOnlyWhitespace())
- whitespaceChildList.append(textChild);
- else
- textChild->recalcTextStyle(change);
+ toText(child)->recalcTextStyle(change, lastTextNode);
+ lastTextNode = toText(child);
} else if (child->isElementNode()) {
Element* element = toElement(child);
if (shouldRecalcStyle(change, element)) {
parentPusher.push();
- element->recalcStyle(change);
- } else if (document().styleResolver()->supportsStyleSharing(element)) {
- document().styleResolver()->addToStyleSharingList(element);
+ element->recalcStyle(change, lastTextNode);
+ } else if (element->supportsStyleSharing()) {
+ styleResolver.addToStyleSharingList(*element);
}
+ if (element->renderer())
+ lastTextNode = 0;
}
}
- whitespaceChildList.recalcStyle();
-
if (shouldRecalcStyle(change, this)) {
updatePseudoElement(AFTER, change);
updatePseudoElement(BACKDROP, change);
}
}
+void Element::checkForChildrenAdjacentRuleChanges()
+{
+ bool hasDirectAdjacentRules = childrenAffectedByDirectAdjacentRules();
+ bool hasIndirectAdjacentRules = childrenAffectedByForwardPositionalRules();
+
+ if (!hasDirectAdjacentRules && !hasIndirectAdjacentRules)
+ return;
+
+ unsigned forceCheckOfNextElementCount = 0;
+ bool forceCheckOfAnyElementSibling = false;
+
+ for (Node* child = firstChild(); child; child = child->nextSibling()) {
+ if (!child->isElementNode())
+ continue;
+ Element* element = toElement(child);
+ bool childRulesChanged = element->needsStyleRecalc() && element->styleChangeType() >= SubtreeStyleChange;
+
+ if (forceCheckOfNextElementCount || forceCheckOfAnyElementSibling)
+ element->setNeedsStyleRecalc();
+
+ if (forceCheckOfNextElementCount)
+ forceCheckOfNextElementCount--;
+
+ if (childRulesChanged && hasDirectAdjacentRules)
+ forceCheckOfNextElementCount = document().styleEngine()->maxDirectAdjacentSelectors();
+
+ forceCheckOfAnyElementSibling = forceCheckOfAnyElementSibling || (childRulesChanged && hasIndirectAdjacentRules);
+ }
+}
+
+void Element::updateCallbackSelectors(RenderStyle* oldStyle, RenderStyle* newStyle)
+{
+ Vector<String> emptyVector;
+ const Vector<String>& oldCallbackSelectors = oldStyle ? oldStyle->callbackSelectors() : emptyVector;
+ const Vector<String>& newCallbackSelectors = newStyle ? newStyle->callbackSelectors() : emptyVector;
+ if (oldCallbackSelectors.isEmpty() && newCallbackSelectors.isEmpty())
+ return;
+ if (oldCallbackSelectors != newCallbackSelectors)
+ CSSSelectorWatch::from(document()).updateSelectorMatches(oldCallbackSelectors, newCallbackSelectors);
+}
+
+void Element::addCallbackSelectors()
+{
+ updateCallbackSelectors(0, renderStyle());
+}
+
+void Element::removeCallbackSelectors()
+{
+ updateCallbackSelectors(renderStyle(), 0);
+}
+
ElementShadow* Element::shadow() const
{
return hasRareData() ? elementRareData()->shadow() : 0;
}
-ElementShadow* Element::ensureShadow()
+ElementShadow& Element::ensureShadow()
{
- return ensureElementRareData()->ensureShadow();
+ return ensureElementRareData().ensureShadow();
}
void Element::didAffectSelector(AffectedSelectorMask mask)
{
setNeedsStyleRecalc();
- if (ElementShadow* elementShadow = shadowOfParentForDistribution(this))
+ if (ElementShadow* elementShadow = shadowWhereNodeCanBeDistributed(*this))
elementShadow->didAffectSelector(mask);
}
-PassRefPtr<ShadowRoot> Element::createShadowRoot(ExceptionState& es)
+void Element::setAnimationStyleChange(bool animationStyleChange)
+{
+ if (ActiveAnimations* activeAnimations = elementRareData()->activeAnimations())
+ activeAnimations->setAnimationStyleChange(animationStyleChange);
+}
+
+void Element::setNeedsAnimationStyleRecalc()
+{
+ bool recalcPending = styleChangeType() != NoStyleChange;
+ setNeedsStyleRecalc(LocalStyleChange, StyleChangeFromRenderer);
+
+ if (!recalcPending)
+ setAnimationStyleChange(true);
+}
+
+PassRefPtr<ShadowRoot> Element::createShadowRoot(ExceptionState& exceptionState)
{
if (alwaysCreateUserAgentShadowRoot())
ensureUserAgentShadowRoot();
if (RuntimeEnabledFeatures::authorShadowDOMForAnyElementEnabled())
- return ensureShadow()->addShadowRoot(this, ShadowRoot::AuthorShadowRoot);
+ return PassRefPtr<ShadowRoot>(ensureShadow().addShadowRoot(*this, ShadowRoot::AuthorShadowRoot));
// Since some elements recreates shadow root dynamically, multiple shadow
// subtrees won't work well in that element. Until they are fixed, we disable
// adding author shadow root for them.
if (!areAuthorShadowsAllowed()) {
- es.throwDOMException(HierarchyRequestError);
+ exceptionState.throwUninformativeAndGenericDOMException(HierarchyRequestError);
return 0;
}
- return ensureShadow()->addShadowRoot(this, ShadowRoot::AuthorShadowRoot);
+ return PassRefPtr<ShadowRoot>(ensureShadow().addShadowRoot(*this, ShadowRoot::AuthorShadowRoot));
}
ShadowRoot* Element::shadowRoot() const
@@ -1649,11 +1788,11 @@ ShadowRoot* Element::userAgentShadowRoot() const
return 0;
}
-ShadowRoot* Element::ensureUserAgentShadowRoot()
+ShadowRoot& Element::ensureUserAgentShadowRoot()
{
if (ShadowRoot* shadowRoot = userAgentShadowRoot())
- return shadowRoot;
- ShadowRoot* shadowRoot = ensureShadow()->addShadowRoot(this, ShadowRoot::UserAgentShadowRoot);
+ return *shadowRoot;
+ ShadowRoot& shadowRoot = ensureShadow().addShadowRoot(*this, ShadowRoot::UserAgentShadowRoot);
didAddUserAgentShadowRoot(shadowRoot);
return shadowRoot;
}
@@ -1673,25 +1812,26 @@ bool Element::childTypeAllowed(NodeType type) const
return false;
}
-static void inline checkForEmptyStyleChange(Element* element, RenderStyle* style)
+void Element::checkForEmptyStyleChange(RenderStyle* style)
{
- if (!style && !element->styleAffectedByEmpty())
+ if (!style && !styleAffectedByEmpty())
return;
- if (!style || (element->styleAffectedByEmpty() && (!style->emptyState() || element->hasChildNodes())))
- element->setNeedsStyleRecalc();
+ if (!style || (styleAffectedByEmpty() && (!style->emptyState() || hasChildNodes())))
+ setNeedsStyleRecalc();
}
-static void checkForSiblingStyleChanges(Element* e, RenderStyle* style, bool finishedParsingCallback,
- Node* beforeChange, Node* afterChange, int childCountDelta)
+void Element::checkForSiblingStyleChanges(bool finishedParsingCallback, Node* beforeChange, Node* afterChange, int childCountDelta)
{
- if (!e->attached() || e->document().hasPendingForcedStyleRecalc() || e->styleChangeType() >= SubtreeStyleChange)
+ if (!inActiveDocument() || document().hasPendingForcedStyleRecalc() || styleChangeType() >= SubtreeStyleChange)
return;
+ RenderStyle* style = renderStyle();
+
// :empty selector.
- checkForEmptyStyleChange(e, style);
+ checkForEmptyStyleChange(style);
- if (!style || (e->needsStyleRecalc() && e->childrenAffectedByPositionalRules()))
+ if (!style || (needsStyleRecalc() && childrenAffectedByPositionalRules()))
return;
// Forward positional selectors include the ~ selector, nth-child, nth-of-type, first-of-type and only-of-type.
@@ -1701,17 +1841,17 @@ static void checkForSiblingStyleChanges(Element* e, RenderStyle* style, bool fin
// |afterChange| is 0 in the parser callback case, so we won't do any work for the forward case if we don't have to.
// For performance reasons we just mark the parent node as changed, since we don't want to make childrenChanged O(n^2) by crawling all our kids
// here. recalcStyle will then force a walk of the children when it sees that this has happened.
- if ((e->childrenAffectedByForwardPositionalRules() && afterChange) || (e->childrenAffectedByBackwardPositionalRules() && beforeChange)) {
- e->setNeedsStyleRecalc();
+ if ((childrenAffectedByForwardPositionalRules() && afterChange) || (childrenAffectedByBackwardPositionalRules() && beforeChange)) {
+ setNeedsStyleRecalc();
return;
}
// :first-child. In the parser callback case, we don't have to check anything, since we were right the first time.
// In the DOM case, we only need to do something if |afterChange| is not 0.
// |afterChange| is 0 in the parser case, so it works out that we'll skip this block.
- if (e->childrenAffectedByFirstChildRules() && afterChange) {
+ if (childrenAffectedByFirstChildRules() && afterChange) {
// Find our new first child.
- Node* newFirstChild = e->firstElementChild();
+ Node* newFirstChild = firstElementChild();
RenderStyle* newFirstChildStyle = newFirstChild ? newFirstChild->renderStyle() : 0;
// Find the first element node following |afterChange|
@@ -1729,9 +1869,9 @@ static void checkForSiblingStyleChanges(Element* e, RenderStyle* style, bool fin
// :last-child. In the parser callback case, we don't have to check anything, since we were right the first time.
// In the DOM case, we only need to do something if |afterChange| is not 0.
- if (e->childrenAffectedByLastChildRules() && beforeChange) {
+ if (childrenAffectedByLastChildRules() && beforeChange) {
// Find our new last child.
- Node* newLastChild = e->lastElementChild();
+ Node* newLastChild = lastElementChild();
RenderStyle* newLastChildStyle = newLastChild ? newLastChild->renderStyle() : 0;
// Find the last element node going backwards from |beforeChange|
@@ -1749,7 +1889,7 @@ static void checkForSiblingStyleChanges(Element* e, RenderStyle* style, bool fin
// The + selector. We need to invalidate the first element following the insertion point. It is the only possible element
// that could be affected by this DOM change.
- if (e->childrenAffectedByDirectAdjacentRules() && afterChange) {
+ if (childrenAffectedByDirectAdjacentRules() && afterChange) {
if (Node* firstElementAfterInsertion = afterChange->isElementNode() ? afterChange : afterChange->nextElementSibling())
firstElementAfterInsertion->setNeedsStyleRecalc();
}
@@ -1759,9 +1899,9 @@ void Element::childrenChanged(bool changedByParser, Node* beforeChange, Node* af
{
ContainerNode::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
if (changedByParser)
- checkForEmptyStyleChange(this, renderStyle());
+ checkForEmptyStyleChange(renderStyle());
else
- checkForSiblingStyleChanges(this, renderStyle(), false, beforeChange, afterChange, childCountDelta);
+ checkForSiblingStyleChanges(false, beforeChange, afterChange, childCountDelta);
if (ElementShadow* shadow = this->shadow())
shadow->setNeedsDistributionRecalc();
@@ -1782,9 +1922,7 @@ void Element::beginParsingChildren()
void Element::finishParsingChildren()
{
setIsParsingChildrenFinished();
- checkForSiblingStyleChanges(this, renderStyle(), true, lastChild(), 0, 0);
- if (isCustomElement())
- CustomElement::didFinishParsingChildren(this);
+ checkForSiblingStyleChanges(this, lastChild(), 0, 0);
}
#ifndef NDEBUG
@@ -1821,10 +1959,10 @@ const Vector<RefPtr<Attr> >& Element::attrNodeList()
return *attrNodeListForElement(this);
}
-PassRefPtr<Attr> Element::setAttributeNode(Attr* attrNode, ExceptionState& es)
+PassRefPtr<Attr> Element::setAttributeNode(Attr* attrNode, ExceptionState& exceptionState)
{
if (!attrNode) {
- es.throwDOMException(TypeMismatchError);
+ exceptionState.throwUninformativeAndGenericDOMException(TypeMismatchError);
return 0;
}
@@ -1835,14 +1973,14 @@ PassRefPtr<Attr> Element::setAttributeNode(Attr* attrNode, ExceptionState& es)
// InUseAttributeError: Raised if node is an Attr that is already an attribute of another Element object.
// The DOM user must explicitly clone Attr nodes to re-use them in other elements.
if (attrNode->ownerElement()) {
- es.throwDOMException(InUseAttributeError);
+ exceptionState.throwUninformativeAndGenericDOMException(InUseAttributeError);
return 0;
}
synchronizeAllAttributes();
UniqueElementData* elementData = ensureUniqueElementData();
- size_t index = elementData->getAttributeItemIndex(attrNode->qualifiedName(), shouldIgnoreAttributeCase(this));
+ size_t index = elementData->getAttributeItemIndex(attrNode->qualifiedName(), shouldIgnoreAttributeCase());
if (index != kNotFound) {
if (oldAttrNode)
detachAttrNodeFromElementWithValue(oldAttrNode.get(), elementData->attributeItem(index)->value());
@@ -1853,35 +1991,35 @@ PassRefPtr<Attr> Element::setAttributeNode(Attr* attrNode, ExceptionState& es)
setAttributeInternal(index, attrNode->qualifiedName(), attrNode->value(), NotInSynchronizationOfLazyAttribute);
attrNode->attachToElement(this);
- treeScope().adoptIfNeeded(attrNode);
- ensureAttrNodeListForElement(this)->append(attrNode);
+ treeScope().adoptIfNeeded(*attrNode);
+ ensureAttrNodeListForElement(this).append(attrNode);
return oldAttrNode.release();
}
-PassRefPtr<Attr> Element::setAttributeNodeNS(Attr* attr, ExceptionState& es)
+PassRefPtr<Attr> Element::setAttributeNodeNS(Attr* attr, ExceptionState& exceptionState)
{
- return setAttributeNode(attr, es);
+ return setAttributeNode(attr, exceptionState);
}
-PassRefPtr<Attr> Element::removeAttributeNode(Attr* attr, ExceptionState& es)
+PassRefPtr<Attr> Element::removeAttributeNode(Attr* attr, ExceptionState& exceptionState)
{
if (!attr) {
- es.throwDOMException(TypeMismatchError);
+ exceptionState.throwUninformativeAndGenericDOMException(TypeMismatchError);
return 0;
}
if (attr->ownerElement() != this) {
- es.throwDOMException(NotFoundError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
return 0;
}
- ASSERT(&document() == &attr->document());
+ ASSERT(document() == attr->document());
synchronizeAttribute(attr->qualifiedName());
size_t index = elementData()->getAttrIndex(attr);
if (index == kNotFound) {
- es.throwDOMException(NotFoundError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
return 0;
}
@@ -1890,17 +2028,17 @@ PassRefPtr<Attr> Element::removeAttributeNode(Attr* attr, ExceptionState& es)
return guard.release();
}
-bool Element::parseAttributeName(QualifiedName& out, const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionState& es)
+bool Element::parseAttributeName(QualifiedName& out, const AtomicString& namespaceURI, const AtomicString& qualifiedName, ExceptionState& exceptionState)
{
- String prefix, localName;
- if (!Document::parseQualifiedName(qualifiedName, prefix, localName, es))
+ AtomicString prefix, localName;
+ if (!Document::parseQualifiedName(qualifiedName, prefix, localName, exceptionState))
return false;
- ASSERT(!es.hadException());
+ ASSERT(!exceptionState.hadException());
QualifiedName qName(prefix, localName, namespaceURI);
if (!Document::hasValidNamespaceForAttributes(qName)) {
- es.throwDOMException(NamespaceError);
+ exceptionState.throwUninformativeAndGenericDOMException(NamespaceError);
return false;
}
@@ -1908,10 +2046,10 @@ bool Element::parseAttributeName(QualifiedName& out, const AtomicString& namespa
return true;
}
-void Element::setAttributeNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, const AtomicString& value, ExceptionState& es)
+void Element::setAttributeNS(const AtomicString& namespaceURI, const AtomicString& qualifiedName, const AtomicString& value, ExceptionState& exceptionState)
{
QualifiedName parsedName = anyName;
- if (!parseAttributeName(parsedName, namespaceURI, qualifiedName, es))
+ if (!parseAttributeName(parsedName, namespaceURI, qualifiedName, exceptionState))
return;
setAttribute(parsedName, value);
}
@@ -1953,7 +2091,7 @@ void Element::removeAttribute(const AtomicString& name)
if (!elementData())
return;
- AtomicString localName = shouldIgnoreAttributeCase(this) ? name.lower() : name;
+ AtomicString localName = shouldIgnoreAttributeCase() ? name.lower() : name;
size_t index = elementData()->getAttributeItemIndex(localName, false);
if (index == kNotFound) {
if (UNLIKELY(localName == styleAttr) && elementData()->m_styleAttributeIsDirty && isStyledElement())
@@ -1974,7 +2112,7 @@ PassRefPtr<Attr> Element::getAttributeNode(const AtomicString& localName)
if (!elementData())
return 0;
synchronizeAttribute(localName);
- const Attribute* attribute = elementData()->getAttributeItem(localName, shouldIgnoreAttributeCase(this));
+ const Attribute* attribute = elementData()->getAttributeItem(localName, shouldIgnoreAttributeCase());
if (!attribute)
return 0;
return ensureAttr(attribute->name());
@@ -1997,7 +2135,7 @@ bool Element::hasAttribute(const AtomicString& localName) const
if (!elementData())
return false;
synchronizeAttribute(localName);
- return elementData()->getAttributeItem(shouldIgnoreAttributeCase(this) ? localName.lower() : localName, false);
+ return elementData()->getAttributeItem(shouldIgnoreAttributeCase() ? localName.lower() : localName, false);
}
bool Element::hasAttributeNS(const AtomicString& namespaceURI, const AtomicString& localName) const
@@ -2044,7 +2182,7 @@ void Element::focus(bool restorePreviousSelection, FocusDirection direction)
doc.updateLayoutIgnorePendingStylesheets();
if (!isFocusable()) {
- ensureElementRareData()->setNeedsFocusAppearanceUpdateSoonAfterAttach(true);
+ ensureElementRareData().setNeedsFocusAppearanceUpdateSoonAfterAttach(true);
return;
}
@@ -2065,11 +2203,8 @@ void Element::updateFocusAppearance(bool /*restorePreviousSelection*/)
// FIXME: We should restore the previous selection if there is one.
VisibleSelection newSelection = VisibleSelection(firstPositionInOrBeforeNode(this), DOWNSTREAM);
-
- if (frame->selection().shouldChangeSelection(newSelection)) {
- frame->selection().setSelection(newSelection);
- frame->selection().revealSelection();
- }
+ frame->selection().setSelection(newSelection);
+ frame->selection().revealSelection();
} else if (renderer() && !renderer()->isWidget())
renderer()->scrollRectToVisible(boundingBox());
}
@@ -2103,28 +2238,135 @@ bool Element::isMouseFocusable() const
void Element::dispatchFocusEvent(Element* oldFocusedElement, FocusDirection)
{
- RefPtr<FocusEvent> event = FocusEvent::create(eventNames().focusEvent, false, false, document().defaultView(), 0, oldFocusedElement);
+ RefPtr<FocusEvent> event = FocusEvent::create(EventTypeNames::focus, false, false, document().domWindow(), 0, oldFocusedElement);
EventDispatcher::dispatchEvent(this, FocusEventDispatchMediator::create(event.release()));
}
void Element::dispatchBlurEvent(Element* newFocusedElement)
{
- RefPtr<FocusEvent> event = FocusEvent::create(eventNames().blurEvent, false, false, document().defaultView(), 0, newFocusedElement);
+ RefPtr<FocusEvent> event = FocusEvent::create(EventTypeNames::blur, false, false, document().domWindow(), 0, newFocusedElement);
EventDispatcher::dispatchEvent(this, BlurEventDispatchMediator::create(event.release()));
}
void Element::dispatchFocusInEvent(const AtomicString& eventType, Element* oldFocusedElement)
{
ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
- ASSERT(eventType == eventNames().focusinEvent || eventType == eventNames().DOMFocusInEvent);
- dispatchScopedEventDispatchMediator(FocusInEventDispatchMediator::create(FocusEvent::create(eventType, true, false, document().defaultView(), 0, oldFocusedElement)));
+ ASSERT(eventType == EventTypeNames::focusin || eventType == EventTypeNames::DOMFocusIn);
+ dispatchScopedEventDispatchMediator(FocusInEventDispatchMediator::create(FocusEvent::create(eventType, true, false, document().domWindow(), 0, oldFocusedElement)));
}
void Element::dispatchFocusOutEvent(const AtomicString& eventType, Element* newFocusedElement)
{
ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
- ASSERT(eventType == eventNames().focusoutEvent || eventType == eventNames().DOMFocusOutEvent);
- dispatchScopedEventDispatchMediator(FocusOutEventDispatchMediator::create(FocusEvent::create(eventType, true, false, document().defaultView(), 0, newFocusedElement)));
+ ASSERT(eventType == EventTypeNames::focusout || eventType == EventTypeNames::DOMFocusOut);
+ dispatchScopedEventDispatchMediator(FocusOutEventDispatchMediator::create(FocusEvent::create(eventType, true, false, document().domWindow(), 0, newFocusedElement)));
+}
+
+String Element::innerHTML() const
+{
+ return createMarkup(this, ChildrenOnly);
+}
+
+String Element::outerHTML() const
+{
+ return createMarkup(this);
+}
+
+void Element::setInnerHTML(const String& html, ExceptionState& exceptionState)
+{
+ if (RefPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(html, this, AllowScriptingContent, "innerHTML", exceptionState)) {
+ ContainerNode* container = this;
+ if (hasTagName(templateTag))
+ container = toHTMLTemplateElement(this)->content();
+ replaceChildrenWithFragment(container, fragment.release(), exceptionState);
+ }
+}
+
+void Element::setOuterHTML(const String& html, ExceptionState& exceptionState)
+{
+ Node* p = parentNode();
+ if (!p || !p->isElementNode()) {
+ exceptionState.throwUninformativeAndGenericDOMException(NoModificationAllowedError);
+ return;
+ }
+ RefPtr<Element> parent = toElement(p);
+ RefPtr<Node> prev = previousSibling();
+ RefPtr<Node> next = nextSibling();
+
+ RefPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(html, parent.get(), AllowScriptingContent, "outerHTML", exceptionState);
+ if (exceptionState.hadException())
+ return;
+
+ parent->replaceChild(fragment.release(), this, exceptionState);
+ RefPtr<Node> node = next ? next->previousSibling() : 0;
+ if (!exceptionState.hadException() && node && node->isTextNode())
+ mergeWithNextTextNode(node.release(), exceptionState);
+
+ if (!exceptionState.hadException() && prev && prev->isTextNode())
+ mergeWithNextTextNode(prev.release(), exceptionState);
+}
+
+Node* Element::insertAdjacent(const String& where, Node* newChild, ExceptionState& exceptionState)
+{
+ if (equalIgnoringCase(where, "beforeBegin")) {
+ if (ContainerNode* parent = this->parentNode()) {
+ parent->insertBefore(newChild, this, exceptionState);
+ if (!exceptionState.hadException())
+ return newChild;
+ }
+ return 0;
+ }
+
+ if (equalIgnoringCase(where, "afterBegin")) {
+ insertBefore(newChild, firstChild(), exceptionState);
+ return exceptionState.hadException() ? 0 : newChild;
+ }
+
+ if (equalIgnoringCase(where, "beforeEnd")) {
+ appendChild(newChild, exceptionState);
+ return exceptionState.hadException() ? 0 : newChild;
+ }
+
+ if (equalIgnoringCase(where, "afterEnd")) {
+ if (ContainerNode* parent = this->parentNode()) {
+ parent->insertBefore(newChild, nextSibling(), exceptionState);
+ if (!exceptionState.hadException())
+ return newChild;
+ }
+ return 0;
+ }
+
+ exceptionState.throwDOMException(SyntaxError, "The value provided ('" + where + "') is not one of 'beforeBegin', 'afterBegin', 'beforeEnd', or 'afterEnd'.");
+ return 0;
+}
+
+// Step 1 of http://domparsing.spec.whatwg.org/#insertadjacenthtml()
+static Element* contextElementForInsertion(const String& where, Element* element, ExceptionState& exceptionState)
+{
+ if (equalIgnoringCase(where, "beforeBegin") || equalIgnoringCase(where, "afterEnd")) {
+ ContainerNode* parent = element->parentNode();
+ if (!parent || !parent->isElementNode()) {
+ exceptionState.throwDOMException(NoModificationAllowedError, "The element has no parent.");
+ return 0;
+ }
+ return toElement(parent);
+ }
+ if (equalIgnoringCase(where, "afterBegin") || equalIgnoringCase(where, "beforeEnd"))
+ return element;
+ exceptionState.throwDOMException(SyntaxError, "The value provided ('" + where + "') is not one of 'beforeBegin', 'afterBegin', 'beforeEnd', or 'afterEnd'.");
+ return 0;
+}
+
+void Element::insertAdjacentHTML(const String& where, const String& markup, ExceptionState& exceptionState)
+{
+ RefPtr<Element> contextElement = contextElementForInsertion(where, this, exceptionState);
+ if (!contextElement)
+ return;
+
+ RefPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(markup, contextElement.get(), AllowScriptingContent, "insertAdjacentHTML", exceptionState);
+ if (!fragment)
+ return;
+ insertAdjacent(where, fragment.get(), exceptionState);
}
String Element::innerText()
@@ -2194,14 +2436,24 @@ const AtomicString& Element::pseudo() const
return getAttribute(pseudoAttr);
}
-const AtomicString& Element::part() const
+void Element::setPseudo(const AtomicString& value)
{
- return getAttribute(partAttr);
+ setAttribute(pseudoAttr, value);
}
-void Element::setPart(const AtomicString& value)
+bool Element::isInDescendantTreeOf(const Element* shadowHost) const
{
- setAttribute(partAttr, value);
+ ASSERT(shadowHost);
+ ASSERT(isShadowHost(shadowHost));
+
+ const ShadowRoot* shadowRoot = containingShadowRoot();
+ while (shadowRoot) {
+ const Element* ancestorShadowHost = shadowRoot->shadowHost();
+ if (ancestorShadowHost == shadowHost)
+ return true;
+ shadowRoot = ancestorShadowHost->containingShadowRoot();
+ }
+ return false;
}
LayoutSize Element::minimumSizeForResizing() const
@@ -2213,7 +2465,7 @@ void Element::setMinimumSizeForResizing(const LayoutSize& size)
{
if (!hasRareData() && size == defaultMinimumSizeForResizing())
return;
- ensureElementRareData()->setMinimumSizeForResizing(size);
+ ensureElementRareData().setMinimumSizeForResizing(size);
}
RenderStyle* Element::computedStyle(PseudoId pseudoElementSpecifier)
@@ -2232,85 +2484,88 @@ RenderStyle* Element::computedStyle(PseudoId pseudoElementSpecifier)
return usedStyle;
}
- if (!attached())
+ if (!inActiveDocument())
// FIXME: Try to do better than this. Ensure that styleForElement() works for elements that are not in the
// document tree and figure out when to destroy the computed style for such elements.
return 0;
- ElementRareData* data = ensureElementRareData();
- if (!data->computedStyle())
- data->setComputedStyle(document().styleForElementIgnoringPendingStylesheets(this));
- return pseudoElementSpecifier ? data->computedStyle()->getCachedPseudoStyle(pseudoElementSpecifier) : data->computedStyle();
+ ElementRareData& rareData = ensureElementRareData();
+ if (!rareData.computedStyle())
+ rareData.setComputedStyle(document().styleForElementIgnoringPendingStylesheets(this));
+ return pseudoElementSpecifier ? rareData.computedStyle()->getCachedPseudoStyle(pseudoElementSpecifier) : rareData.computedStyle();
}
void Element::setStyleAffectedByEmpty()
{
- ensureElementRareData()->setStyleAffectedByEmpty(true);
+ ensureElementRareData().setStyleAffectedByEmpty(true);
+}
+
+void Element::setChildrenAffectedByFocus()
+{
+ ensureElementRareData().setChildrenAffectedByFocus(true);
}
-void Element::setChildrenAffectedByHover(bool value)
+void Element::setChildrenAffectedByHover()
{
- if (value || hasRareData())
- ensureElementRareData()->setChildrenAffectedByHover(value);
+ ensureElementRareData().setChildrenAffectedByHover(true);
}
-void Element::setChildrenAffectedByActive(bool value)
+void Element::setChildrenAffectedByActive()
{
- if (value || hasRareData())
- ensureElementRareData()->setChildrenAffectedByActive(value);
+ ensureElementRareData().setChildrenAffectedByActive(true);
}
-void Element::setChildrenAffectedByDrag(bool value)
+void Element::setChildrenAffectedByDrag()
{
- if (value || hasRareData())
- ensureElementRareData()->setChildrenAffectedByDrag(value);
+ ensureElementRareData().setChildrenAffectedByDrag(true);
}
void Element::setChildrenAffectedByFirstChildRules()
{
- ensureElementRareData()->setChildrenAffectedByFirstChildRules(true);
+ ensureElementRareData().setChildrenAffectedByFirstChildRules(true);
}
void Element::setChildrenAffectedByLastChildRules()
{
- ensureElementRareData()->setChildrenAffectedByLastChildRules(true);
+ ensureElementRareData().setChildrenAffectedByLastChildRules(true);
}
void Element::setChildrenAffectedByDirectAdjacentRules()
{
- ensureElementRareData()->setChildrenAffectedByDirectAdjacentRules(true);
+ ensureElementRareData().setChildrenAffectedByDirectAdjacentRules(true);
}
void Element::setChildrenAffectedByForwardPositionalRules()
{
- ensureElementRareData()->setChildrenAffectedByForwardPositionalRules(true);
+ ensureElementRareData().setChildrenAffectedByForwardPositionalRules(true);
}
void Element::setChildrenAffectedByBackwardPositionalRules()
{
- ensureElementRareData()->setChildrenAffectedByBackwardPositionalRules(true);
+ ensureElementRareData().setChildrenAffectedByBackwardPositionalRules(true);
}
void Element::setChildIndex(unsigned index)
{
- ElementRareData* rareData = ensureElementRareData();
+ ElementRareData& rareData = ensureElementRareData();
if (RenderStyle* style = renderStyle())
style->setUnique();
- rareData->setChildIndex(index);
+ rareData.setChildIndex(index);
}
-bool Element::hasFlagsSetDuringStylingOfChildren() const
+bool Element::childrenSupportStyleSharing() const
{
if (!hasRareData())
- return false;
- return rareDataChildrenAffectedByHover()
- || rareDataChildrenAffectedByActive()
- || rareDataChildrenAffectedByDrag()
- || rareDataChildrenAffectedByFirstChildRules()
- || rareDataChildrenAffectedByLastChildRules()
- || rareDataChildrenAffectedByDirectAdjacentRules()
- || rareDataChildrenAffectedByForwardPositionalRules()
- || rareDataChildrenAffectedByBackwardPositionalRules();
+ return true;
+ return !rareDataChildrenAffectedByFocus()
+ && !rareDataChildrenAffectedByHover()
+ && !rareDataChildrenAffectedByActive()
+ && !rareDataChildrenAffectedByDrag()
+ && !rareDataChildrenAffectedByFirstChildRules()
+ && !rareDataChildrenAffectedByLastChildRules()
+ && !rareDataChildrenAffectedByDirectAdjacentRules()
+ && !rareDataChildrenAffectedByForwardPositionalRules()
+ && !rareDataChildrenAffectedByBackwardPositionalRules();
}
bool Element::rareDataStyleAffectedByEmpty() const
@@ -2319,6 +2574,12 @@ bool Element::rareDataStyleAffectedByEmpty() const
return elementRareData()->styleAffectedByEmpty();
}
+bool Element::rareDataChildrenAffectedByFocus() const
+{
+ ASSERT(hasRareData());
+ return elementRareData()->childrenAffectedByFocus();
+}
+
bool Element::rareDataChildrenAffectedByHover() const
{
ASSERT(hasRareData());
@@ -2375,7 +2636,7 @@ unsigned Element::rareDataChildIndex() const
void Element::setIsInCanvasSubtree(bool isInCanvasSubtree)
{
- ensureElementRareData()->setIsInCanvasSubtree(isInCanvasSubtree);
+ ensureElementRareData().setIsInCanvasSubtree(isInCanvasSubtree);
}
bool Element::isInCanvasSubtree() const
@@ -2388,7 +2649,7 @@ void Element::setIsInsideRegion(bool value)
if (value == isInsideRegion())
return;
- ensureElementRareData()->setIsInsideRegion(value);
+ ensureElementRareData().setIsInsideRegion(value);
}
bool Element::isInsideRegion() const
@@ -2398,7 +2659,7 @@ bool Element::isInsideRegion() const
void Element::setRegionOversetState(RegionOversetState state)
{
- ensureElementRareData()->setRegionOversetState(state);
+ ensureElementRareData().setRegionOversetState(state);
}
RegionOversetState Element::regionOversetState() const
@@ -2458,8 +2719,14 @@ void Element::updatePseudoElement(PseudoId pseudoId, StyleRecalcChange change)
{
PseudoElement* element = pseudoElement(pseudoId);
if (element && (needsStyleRecalc() || shouldRecalcStyle(change, element))) {
+ // Need to clear the cached style if the PseudoElement wants a recalc so it
+ // computes a new style.
+ if (element->needsStyleRecalc())
+ renderer()->style()->removeCachedPseudoStyle(pseudoId);
+
// PseudoElement styles hang off their parent element's style so if we needed
// a style recalc we should Force one on the pseudo.
+ // FIXME: We should figure out the right text sibling to pass.
element->recalcStyle(needsStyleRecalc() ? Force : change);
// Wait until our parent is not displayed or pseudoElementRendererIsNeeded
@@ -2472,33 +2739,34 @@ void Element::updatePseudoElement(PseudoId pseudoId, StyleRecalcChange change)
createPseudoElementIfNeeded(pseudoId);
}
-void Element::createPseudoElementIfNeeded(PseudoId pseudoId)
-{
- if (needsPseudoElement(pseudoId))
- createPseudoElement(pseudoId);
-}
-
-bool Element::needsPseudoElement(PseudoId pseudoId) const
+bool Element::needsPseudoElement(PseudoId pseudoId, const RenderStyle& style) const
{
if (pseudoId == BACKDROP && !isInTopLayer())
return false;
- if (!renderer() || !pseudoElementRendererIsNeeded(renderer()->getCachedPseudoStyle(pseudoId)))
+ if (!renderer() || !pseudoElementRendererIsNeeded(&style))
return false;
if (!renderer()->canHaveGeneratedChildren())
return false;
return true;
}
-void Element::createPseudoElement(PseudoId pseudoId)
+void Element::createPseudoElementIfNeeded(PseudoId pseudoId)
{
- ASSERT(needsPseudoElement(pseudoId));
- ASSERT(!isPseudoElement());
- RefPtr<PseudoElement> element = PseudoElement::create(this, pseudoId);
+ if (isPseudoElement())
+ return;
+
+ RefPtr<PseudoElement> element = document().ensureStyleResolver().createPseudoElementIfNeeded(*this, pseudoId);
+ if (!element)
+ return;
+
if (pseudoId == BACKDROP)
document().addToTopLayer(element.get(), this);
+ element->insertedInto(this);
element->attach();
- ensureElementRareData()->setPseudoElement(pseudoId, element.release());
+ InspectorInstrumentation::pseudoElementCreated(element.get());
+
+ ensureElementRareData().setPseudoElement(pseudoId, element.release());
}
PseudoElement* Element::pseudoElement(PseudoId pseudoId) const
@@ -2513,33 +2781,33 @@ RenderObject* Element::pseudoElementRenderer(PseudoId pseudoId) const
return 0;
}
-bool Element::webkitMatchesSelector(const String& selector, ExceptionState& es)
+bool Element::webkitMatchesSelector(const String& selector, ExceptionState& exceptionState)
{
if (selector.isEmpty()) {
- es.throwDOMException(SyntaxError);
+ exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
return false;
}
- SelectorQuery* selectorQuery = document().selectorQueryCache()->add(selector, document(), es);
+ SelectorQuery* selectorQuery = document().selectorQueryCache().add(selector, document(), exceptionState);
if (!selectorQuery)
return false;
- return selectorQuery->matches(this);
+ return selectorQuery->matches(*this);
}
DOMTokenList* Element::classList()
{
- ElementRareData* data = ensureElementRareData();
- if (!data->classList())
- data->setClassList(ClassList::create(this));
- return data->classList();
+ ElementRareData& rareData = ensureElementRareData();
+ if (!rareData.classList())
+ rareData.setClassList(ClassList::create(this));
+ return rareData.classList();
}
DOMStringMap* Element::dataset()
{
- ElementRareData* data = ensureElementRareData();
- if (!data->dataset())
- data->setDataset(DatasetDOMStringMap::create(this));
- return data->dataset();
+ ElementRareData& rareData = ensureElementRareData();
+ if (!rareData.dataset())
+ rareData.setDataset(DatasetDOMStringMap::create(this));
+ return rareData.dataset();
}
KURL Element::getURLAttribute(const QualifiedName& name) const
@@ -2574,8 +2842,7 @@ int Element::getIntegralAttribute(const QualifiedName& attributeName) const
void Element::setIntegralAttribute(const QualifiedName& attributeName, int value)
{
- // FIXME: Need an AtomicString version of String::number.
- setAttribute(attributeName, String::number(value));
+ setAttribute(attributeName, AtomicString::number(value));
}
unsigned Element::getUnsignedIntegralAttribute(const QualifiedName& attributeName) const
@@ -2585,8 +2852,22 @@ unsigned Element::getUnsignedIntegralAttribute(const QualifiedName& attributeNam
void Element::setUnsignedIntegralAttribute(const QualifiedName& attributeName, unsigned value)
{
- // FIXME: Need an AtomicString version of String::number.
- setAttribute(attributeName, String::number(value));
+ // Range restrictions are enforced for unsigned IDL attributes that
+ // reflect content attributes,
+ // http://www.whatwg.org/specs/web-apps/current-work/multipage/common-dom-interfaces.html#reflecting-content-attributes-in-idl-attributes
+ if (value > 0x7fffffffu)
+ value = 0;
+ setAttribute(attributeName, AtomicString::number(value));
+}
+
+double Element::getFloatingPointAttribute(const QualifiedName& attributeName, double fallbackValue) const
+{
+ return parseToDoubleForNumberType(getAttribute(attributeName), fallbackValue);
+}
+
+void Element::setFloatingPointAttribute(const QualifiedName& attributeName, double value)
+{
+ setAttribute(attributeName, AtomicString::number(value));
}
bool Element::childShouldCreateRenderer(const Node& child) const
@@ -2615,7 +2896,7 @@ bool Element::containsFullScreenElement() const
void Element::setContainsFullScreenElement(bool flag)
{
- ensureElementRareData()->setContainsFullScreenElement(flag);
+ ensureElementRareData().setContainsFullScreenElement(flag);
setNeedsStyleRecalc(SubtreeStyleChange);
}
@@ -2641,7 +2922,7 @@ void Element::setIsInTopLayer(bool inTopLayer)
{
if (isInTopLayer() == inTopLayer)
return;
- ensureElementRareData()->setIsInTopLayer(inTopLayer);
+ ensureElementRareData().setIsInTopLayer(inTopLayer);
// We must ensure a reattach occurs so the renderer is inserted in the correct sibling order under RenderView according to its
// top layer position, or in its usual place if not in the top layer.
@@ -2685,8 +2966,8 @@ bool Element::isSpellCheckingEnabled() const
RenderRegion* Element::renderRegion() const
{
- if (renderer() && renderer()->isRenderRegion())
- return toRenderRegion(renderer());
+ if (renderer() && renderer()->isRenderNamedFlowFragmentContainer())
+ return toRenderBlockFlow(renderer())->renderNamedFlowFragment();
return 0;
}
@@ -2709,10 +2990,13 @@ bool Element::shouldMoveToFlowThread(RenderStyle* styleToUse) const
const AtomicString& Element::webkitRegionOverset() const
{
+ DEFINE_STATIC_LOCAL(AtomicString, undefinedState, ("undefined", AtomicString::ConstructFromLiteral));
+ if (!RuntimeEnabledFeatures::cssRegionsEnabled())
+ return undefinedState;
+
document().updateLayoutIgnorePendingStylesheets();
- DEFINE_STATIC_LOCAL(AtomicString, undefinedState, ("undefined", AtomicString::ConstructFromLiteral));
- if (!RuntimeEnabledFeatures::cssRegionsEnabled() || !renderRegion())
+ if (!renderRegion())
return undefinedState;
switch (renderRegion()->regionOversetState()) {
@@ -2738,11 +3022,14 @@ const AtomicString& Element::webkitRegionOverset() const
Vector<RefPtr<Range> > Element::webkitGetRegionFlowRanges() const
{
+ Vector<RefPtr<Range> > rangeObjects;
+ if (!RuntimeEnabledFeatures::cssRegionsEnabled())
+ return rangeObjects;
+
document().updateLayoutIgnorePendingStylesheets();
- Vector<RefPtr<Range> > rangeObjects;
- if (RuntimeEnabledFeatures::cssRegionsEnabled() && renderer() && renderer()->isRenderRegion()) {
- RenderRegion* region = toRenderRegion(renderer());
+ if (renderer() && renderer()->isRenderNamedFlowFragmentContainer()) {
+ RenderNamedFlowFragment* region = toRenderBlockFlow(renderer())->renderNamedFlowFragment();
if (region->isValid())
region->getRanges(rangeObjects);
}
@@ -2757,7 +3044,7 @@ bool Element::fastAttributeLookupAllowed(const QualifiedName& name) const
return false;
if (isSVGElement())
- return !static_cast<const SVGElement*>(this)->isAnimatableAttribute(name);
+ return !toSVGElement(this)->isAnimatableAttribute(name);
return true;
}
@@ -2825,7 +3112,7 @@ void Element::updateLabel(TreeScope& scope, const AtomicString& oldForAttributeV
static bool hasSelectorForAttribute(Document* document, const AtomicString& localName)
{
- return document->styleResolver() && document->styleResolver()->ruleFeatureSet().hasSelectorForAttribute(localName);
+ return document->ensureStyleResolver().ensureRuleFeatureSet().hasSelectorForAttribute(localName);
}
void Element::willModifyAttribute(const QualifiedName& name, const AtomicString& oldValue, const AtomicString& newValue)
@@ -2841,48 +3128,48 @@ void Element::willModifyAttribute(const QualifiedName& name, const AtomicString&
}
if (oldValue != newValue) {
- if (attached() && hasSelectorForAttribute(&document(), name.localName()))
+ if (inActiveDocument() && hasSelectorForAttribute(&document(), name.localName()))
setNeedsStyleRecalc();
if (isUpgradedCustomElement())
CustomElement::attributeDidChange(this, name.localName(), oldValue, newValue);
}
- if (OwnPtr<MutationObserverInterestGroup> recipients = MutationObserverInterestGroup::createForAttributesMutation(this, name))
+ if (OwnPtr<MutationObserverInterestGroup> recipients = MutationObserverInterestGroup::createForAttributesMutation(*this, name))
recipients->enqueueMutationRecord(MutationRecord::createAttributes(this, name, oldValue));
- InspectorInstrumentation::willModifyDOMAttr(&document(), this, oldValue, newValue);
+ InspectorInstrumentation::willModifyDOMAttr(this, oldValue, newValue);
}
void Element::didAddAttribute(const QualifiedName& name, const AtomicString& value)
{
attributeChanged(name, value);
- InspectorInstrumentation::didModifyDOMAttr(&document(), this, name.localName(), value);
+ InspectorInstrumentation::didModifyDOMAttr(this, name.localName(), value);
dispatchSubtreeModifiedEvent();
}
void Element::didModifyAttribute(const QualifiedName& name, const AtomicString& value)
{
attributeChanged(name, value);
- InspectorInstrumentation::didModifyDOMAttr(&document(), this, name.localName(), value);
+ InspectorInstrumentation::didModifyDOMAttr(this, name.localName(), value);
// Do not dispatch a DOMSubtreeModified event here; see bug 81141.
}
void Element::didRemoveAttribute(const QualifiedName& name)
{
attributeChanged(name, nullAtom);
- InspectorInstrumentation::didRemoveDOMAttr(&document(), this, name.localName());
+ InspectorInstrumentation::didRemoveDOMAttr(this, name.localName());
dispatchSubtreeModifiedEvent();
}
-void Element::didMoveToNewDocument(Document* oldDocument)
+void Element::didMoveToNewDocument(Document& oldDocument)
{
Node::didMoveToNewDocument(oldDocument);
// If the documents differ by quirks mode then they differ by case sensitivity
// for class and id names so we need to go through the attribute change logic
// to pick up the new casing in the ElementData.
- if (oldDocument->inQuirksMode() != document().inQuirksMode()) {
+ if (oldDocument.inQuirksMode() != document().inQuirksMode()) {
if (hasID())
setIdAttribute(getIdAttribute());
if (hasClass())
@@ -2922,15 +3209,15 @@ PassRefPtr<HTMLCollection> Element::ensureCachedHTMLCollection(CollectionType ty
RefPtr<HTMLCollection> collection;
if (type == TableRows) {
ASSERT(hasTagName(tableTag));
- return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLTableRowsCollection>(this, type);
+ return ensureRareData().ensureNodeLists().addCacheWithAtomicName<HTMLTableRowsCollection>(this, type);
} else if (type == SelectOptions) {
ASSERT(hasTagName(selectTag));
- return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLOptionsCollection>(this, type);
+ return ensureRareData().ensureNodeLists().addCacheWithAtomicName<HTMLOptionsCollection>(this, type);
} else if (type == FormControls) {
ASSERT(hasTagName(formTag) || hasTagName(fieldsetTag));
- return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLFormControlsCollection>(this, type);
+ return ensureRareData().ensureNodeLists().addCacheWithAtomicName<HTMLFormControlsCollection>(this, type);
}
- return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLCollection>(this, type);
+ return ensureRareData().ensureNodeLists().addCacheWithAtomicName<HTMLCollection>(this, type);
}
static void scheduleLayerUpdateCallback(Node* node)
@@ -2962,24 +3249,24 @@ void Element::setSavedLayerScrollOffset(const IntSize& size)
{
if (size.isZero() && !hasRareData())
return;
- ensureElementRareData()->setSavedLayerScrollOffset(size);
+ ensureElementRareData().setSavedLayerScrollOffset(size);
}
PassRefPtr<Attr> Element::attrIfExists(const QualifiedName& name)
{
if (AttrNodeList* attrNodeList = attrNodeListForElement(this))
- return findAttrNodeInList(attrNodeList, name);
+ return findAttrNodeInList(*attrNodeList, name);
return 0;
}
PassRefPtr<Attr> Element::ensureAttr(const QualifiedName& name)
{
- AttrNodeList* attrNodeList = ensureAttrNodeListForElement(this);
+ AttrNodeList& attrNodeList = ensureAttrNodeListForElement(this);
RefPtr<Attr> attrNode = findAttrNodeInList(attrNodeList, name);
if (!attrNode) {
attrNode = Attr::create(*this, name);
- treeScope().adoptIfNeeded(attrNode.get());
- attrNodeList->append(attrNode);
+ treeScope().adoptIfNeeded(*attrNode);
+ attrNodeList.append(attrNode);
}
return attrNode.release();
}
@@ -3008,7 +3295,7 @@ void Element::detachAllAttrNodesFromElement()
for (unsigned i = 0; i < attributeCount(); ++i) {
const Attribute* attribute = attributeItem(i);
- if (RefPtr<Attr> attrNode = findAttrNodeInList(attrNodeList, attribute->name()))
+ if (RefPtr<Attr> attrNode = findAttrNodeInList(*attrNodeList, attribute->name()))
attrNode->detachFromElementWithValue(attribute->value());
}
@@ -3099,7 +3386,12 @@ void Element::createUniqueElementData()
InputMethodContext* Element::inputMethodContext()
{
- return ensureElementRareData()->ensureInputMethodContext(toHTMLElement(this));
+ return ensureElementRareData().ensureInputMethodContext(toHTMLElement(this));
+}
+
+bool Element::hasInputMethodContext() const
+{
+ return hasRareData() && elementRareData()->hasInputMethodContext();
}
bool Element::hasPendingResources() const
@@ -3109,86 +3401,12 @@ bool Element::hasPendingResources() const
void Element::setHasPendingResources()
{
- ensureElementRareData()->setHasPendingResources(true);
+ ensureElementRareData().setHasPendingResources(true);
}
void Element::clearHasPendingResources()
{
- ensureElementRareData()->setHasPendingResources(false);
-}
-
-struct PresentationAttributeCacheKey {
- PresentationAttributeCacheKey() : tagName(0) { }
- StringImpl* tagName;
- // Only the values need refcounting.
- Vector<pair<StringImpl*, AtomicString>, 3> attributesAndValues;
-};
-
-struct PresentationAttributeCacheEntry {
- WTF_MAKE_FAST_ALLOCATED;
-public:
- PresentationAttributeCacheKey key;
- RefPtr<StylePropertySet> value;
-};
-
-typedef HashMap<unsigned, OwnPtr<PresentationAttributeCacheEntry>, AlreadyHashed> PresentationAttributeCache;
-
-static bool operator!=(const PresentationAttributeCacheKey& a, const PresentationAttributeCacheKey& b)
-{
- if (a.tagName != b.tagName)
- return true;
- return a.attributesAndValues != b.attributesAndValues;
-}
-
-static PresentationAttributeCache& presentationAttributeCache()
-{
- DEFINE_STATIC_LOCAL(PresentationAttributeCache, cache, ());
- return cache;
-}
-
-class PresentationAttributeCacheCleaner {
- WTF_MAKE_NONCOPYABLE(PresentationAttributeCacheCleaner); WTF_MAKE_FAST_ALLOCATED;
-public:
- PresentationAttributeCacheCleaner()
- : m_hitCount(0)
- , m_cleanTimer(this, &PresentationAttributeCacheCleaner::cleanCache)
- {
- }
-
- void didHitPresentationAttributeCache()
- {
- if (presentationAttributeCache().size() < minimumPresentationAttributeCacheSizeForCleaning)
- return;
-
- m_hitCount++;
-
- if (!m_cleanTimer.isActive())
- m_cleanTimer.startOneShot(presentationAttributeCacheCleanTimeInSeconds);
- }
-
-private:
- static const unsigned presentationAttributeCacheCleanTimeInSeconds = 60;
- static const int minimumPresentationAttributeCacheSizeForCleaning = 100;
- static const unsigned minimumPresentationAttributeCacheHitCountPerMinute = (100 * presentationAttributeCacheCleanTimeInSeconds) / 60;
-
- void cleanCache(Timer<PresentationAttributeCacheCleaner>* timer)
- {
- ASSERT_UNUSED(timer, timer == &m_cleanTimer);
- unsigned hitCount = m_hitCount;
- m_hitCount = 0;
- if (hitCount > minimumPresentationAttributeCacheHitCountPerMinute)
- return;
- presentationAttributeCache().clear();
- }
-
- unsigned m_hitCount;
- Timer<PresentationAttributeCacheCleaner> m_cleanTimer;
-};
-
-static PresentationAttributeCacheCleaner& presentationAttributeCacheCleaner()
-{
- DEFINE_STATIC_LOCAL(PresentationAttributeCacheCleaner, cleaner, ());
- return cleaner;
+ ensureElementRareData().setHasPendingResources(false);
}
void Element::synchronizeStyleAttributeInternal() const
@@ -3212,12 +3430,13 @@ MutableStylePropertySet* Element::ensureMutableInlineStyle()
{
ASSERT(isStyledElement());
RefPtr<StylePropertySet>& inlineStyle = ensureUniqueElementData()->m_inlineStyle;
- if (!inlineStyle)
- inlineStyle = MutableStylePropertySet::create(strictToCSSParserMode(isHTMLElement() && !document().inQuirksMode()));
- else if (!inlineStyle->isMutable())
+ if (!inlineStyle) {
+ CSSParserMode mode = (!isHTMLElement() || document().inQuirksMode()) ? HTMLQuirksMode : HTMLStandardMode;
+ inlineStyle = MutableStylePropertySet::create(mode);
+ } else if (!inlineStyle->isMutable()) {
inlineStyle = inlineStyle->mutableCopy();
- ASSERT(inlineStyle->isMutable());
- return static_cast<MutableStylePropertySet*>(inlineStyle.get());
+ }
+ return toMutableStylePropertySet(inlineStyle);
}
PropertySetCSSStyleDeclaration* Element::inlineStyleCSSOMWrapper()
@@ -3269,7 +3488,7 @@ void Element::styleAttributeChanged(const AtomicString& newStyleString, Attribut
elementData()->m_styleAttributeIsDirty = false;
setNeedsStyleRecalc(LocalStyleChange);
- InspectorInstrumentation::didInvalidateStyleAttr(&document(), this);
+ InspectorInstrumentation::didInvalidateStyleAttr(this);
}
void Element::inlineStyleChanged()
@@ -3278,7 +3497,7 @@ void Element::inlineStyleChanged()
setNeedsStyleRecalc(LocalStyleChange);
ASSERT(elementData());
elementData()->m_styleAttributeIsDirty = true;
- InspectorInstrumentation::didInvalidateStyleAttr(&document(), this);
+ InspectorInstrumentation::didInvalidateStyleAttr(this);
}
bool Element::setInlineStyleProperty(CSSPropertyID propertyID, CSSValueID identifier, bool important)
@@ -3341,101 +3560,12 @@ void Element::addSubresourceAttributeURLs(ListHashSet<KURL>& urls) const
inlineStyle->addSubresourceStyleURLs(urls, document().elementSheet()->contents());
}
-static inline bool attributeNameSort(const pair<StringImpl*, AtomicString>& p1, const pair<StringImpl*, AtomicString>& p2)
-{
- // Sort based on the attribute name pointers. It doesn't matter what the order is as long as it is always the same.
- return p1.first < p2.first;
-}
-
-void Element::makePresentationAttributeCacheKey(PresentationAttributeCacheKey& result) const
-{
- ASSERT(isStyledElement());
- // FIXME: Enable for SVG.
- if (namespaceURI() != xhtmlNamespaceURI)
- return;
- // Interpretation of the size attributes on <input> depends on the type attribute.
- if (hasTagName(inputTag))
- return;
- unsigned size = attributeCount();
- for (unsigned i = 0; i < size; ++i) {
- const Attribute* attribute = attributeItem(i);
- if (!isPresentationAttribute(attribute->name()))
- continue;
- if (!attribute->namespaceURI().isNull())
- return;
- // FIXME: Background URL may depend on the base URL and can't be shared. Disallow caching.
- if (attribute->name() == backgroundAttr)
- return;
- result.attributesAndValues.append(std::make_pair(attribute->localName().impl(), attribute->value()));
- }
- if (result.attributesAndValues.isEmpty())
- return;
- // Attribute order doesn't matter. Sort for easy equality comparison.
- std::sort(result.attributesAndValues.begin(), result.attributesAndValues.end(), attributeNameSort);
- // The cache key is non-null when the tagName is set.
- result.tagName = localName().impl();
-}
-
-static unsigned computePresentationAttributeCacheHash(const PresentationAttributeCacheKey& key)
+void Element::updatePresentationAttributeStyle()
{
- if (!key.tagName)
- return 0;
- ASSERT(key.attributesAndValues.size());
- unsigned attributeHash = StringHasher::hashMemory(key.attributesAndValues.data(), key.attributesAndValues.size() * sizeof(key.attributesAndValues[0]));
- return WTF::pairIntHash(key.tagName->existingHash(), attributeHash);
-}
-
-void Element::rebuildPresentationAttributeStyle()
-{
- ASSERT(isStyledElement());
- PresentationAttributeCacheKey cacheKey;
- makePresentationAttributeCacheKey(cacheKey);
-
- unsigned cacheHash = computePresentationAttributeCacheHash(cacheKey);
-
- PresentationAttributeCache::iterator cacheIterator;
- if (cacheHash) {
- cacheIterator = presentationAttributeCache().add(cacheHash, nullptr).iterator;
- if (cacheIterator->value && cacheIterator->value->key != cacheKey)
- cacheHash = 0;
- } else {
- cacheIterator = presentationAttributeCache().end();
- }
-
- RefPtr<StylePropertySet> style;
- if (cacheHash && cacheIterator->value) {
- style = cacheIterator->value->value;
- presentationAttributeCacheCleaner().didHitPresentationAttributeCache();
- } else {
- style = MutableStylePropertySet::create(isSVGElement() ? SVGAttributeMode : CSSAttributeMode);
- unsigned size = attributeCount();
- for (unsigned i = 0; i < size; ++i) {
- const Attribute* attribute = attributeItem(i);
- collectStyleForPresentationAttribute(attribute->name(), attribute->value(), static_cast<MutableStylePropertySet*>(style.get()));
- }
- }
-
// ShareableElementData doesn't store presentation attribute style, so make sure we have a UniqueElementData.
UniqueElementData* elementData = ensureUniqueElementData();
-
elementData->m_presentationAttributeStyleIsDirty = false;
- elementData->m_presentationAttributeStyle = style->isEmpty() ? 0 : style;
-
- if (!cacheHash || cacheIterator->value)
- return;
-
- OwnPtr<PresentationAttributeCacheEntry> newEntry = adoptPtr(new PresentationAttributeCacheEntry);
- newEntry->key = cacheKey;
- newEntry->value = style.release();
-
- static const int presentationAttributeCacheMaximumSize = 4096;
- if (presentationAttributeCache().size() > presentationAttributeCacheMaximumSize) {
- // Start building from scratch if the cache ever gets big.
- presentationAttributeCache().clear();
- presentationAttributeCache().set(cacheHash, newEntry.release());
- } else {
- cacheIterator->value = newEntry.release();
- }
+ elementData->m_presentationAttributeStyle = computePresentationAttributeStyle(*this);
}
void Element::addPropertyToPresentationAttributeStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, CSSValueID identifier)
@@ -3456,206 +3586,56 @@ void Element::addPropertyToPresentationAttributeStyle(MutableStylePropertySet* s
style->setProperty(propertyID, value, false);
}
-void ElementData::deref()
-{
- if (!derefBase())
- return;
-
- if (m_isUnique)
- delete static_cast<UniqueElementData*>(this);
- else
- delete static_cast<ShareableElementData*>(this);
-}
-
-ElementData::ElementData()
- : m_isUnique(true)
- , m_arraySize(0)
- , m_presentationAttributeStyleIsDirty(false)
- , m_styleAttributeIsDirty(false)
- , m_animatedSVGAttributesAreDirty(false)
-{
-}
-
-ElementData::ElementData(unsigned arraySize)
- : m_isUnique(false)
- , m_arraySize(arraySize)
- , m_presentationAttributeStyleIsDirty(false)
- , m_styleAttributeIsDirty(false)
- , m_animatedSVGAttributesAreDirty(false)
-{
-}
-
-struct SameSizeAsElementData : public RefCounted<SameSizeAsElementData> {
- unsigned bitfield;
- void* refPtrs[3];
-};
-
-COMPILE_ASSERT(sizeof(ElementData) == sizeof(SameSizeAsElementData), element_attribute_data_should_stay_small);
-
-static size_t sizeForShareableElementDataWithAttributeCount(unsigned count)
-{
- return sizeof(ShareableElementData) + sizeof(Attribute) * count;
-}
-
-PassRefPtr<ShareableElementData> ShareableElementData::createWithAttributes(const Vector<Attribute>& attributes)
-{
- void* slot = WTF::fastMalloc(sizeForShareableElementDataWithAttributeCount(attributes.size()));
- return adoptRef(new (slot) ShareableElementData(attributes));
-}
-
-PassRefPtr<UniqueElementData> UniqueElementData::create()
-{
- return adoptRef(new UniqueElementData);
-}
-
-ShareableElementData::ShareableElementData(const Vector<Attribute>& attributes)
- : ElementData(attributes.size())
-{
- for (unsigned i = 0; i < m_arraySize; ++i)
- new (&m_attributeArray[i]) Attribute(attributes[i]);
-}
-
-ShareableElementData::~ShareableElementData()
-{
- for (unsigned i = 0; i < m_arraySize; ++i)
- m_attributeArray[i].~Attribute();
-}
-
-ShareableElementData::ShareableElementData(const UniqueElementData& other)
- : ElementData(other, false)
-{
- ASSERT(!other.m_presentationAttributeStyle);
-
- if (other.m_inlineStyle) {
- ASSERT(!other.m_inlineStyle->hasCSSOMWrapper());
- m_inlineStyle = other.m_inlineStyle->immutableCopyIfNeeded();
- }
-
- for (unsigned i = 0; i < m_arraySize; ++i)
- new (&m_attributeArray[i]) Attribute(other.m_attributeVector.at(i));
-}
-
-ElementData::ElementData(const ElementData& other, bool isUnique)
- : m_isUnique(isUnique)
- , m_arraySize(isUnique ? 0 : other.length())
- , m_presentationAttributeStyleIsDirty(other.m_presentationAttributeStyleIsDirty)
- , m_styleAttributeIsDirty(other.m_styleAttributeIsDirty)
- , m_animatedSVGAttributesAreDirty(other.m_animatedSVGAttributesAreDirty)
- , m_classNames(other.m_classNames)
- , m_idForStyleResolution(other.m_idForStyleResolution)
-{
- // NOTE: The inline style is copied by the subclass copy constructor since we don't know what to do with it here.
-}
-
-UniqueElementData::UniqueElementData()
-{
-}
-
-UniqueElementData::UniqueElementData(const UniqueElementData& other)
- : ElementData(other, true)
- , m_presentationAttributeStyle(other.m_presentationAttributeStyle)
- , m_attributeVector(other.m_attributeVector)
-{
- m_inlineStyle = other.m_inlineStyle ? other.m_inlineStyle->mutableCopy() : 0;
-}
-
-UniqueElementData::UniqueElementData(const ShareableElementData& other)
- : ElementData(other, true)
-{
- // An ShareableElementData should never have a mutable inline StylePropertySet attached.
- ASSERT(!other.m_inlineStyle || !other.m_inlineStyle->isMutable());
- m_inlineStyle = other.m_inlineStyle;
-
- m_attributeVector.reserveCapacity(other.length());
- for (unsigned i = 0; i < other.length(); ++i)
- m_attributeVector.uncheckedAppend(other.m_attributeArray[i]);
-}
-
-PassRefPtr<UniqueElementData> ElementData::makeUniqueCopy() const
-{
- if (isUnique())
- return adoptRef(new UniqueElementData(static_cast<const UniqueElementData&>(*this)));
- return adoptRef(new UniqueElementData(static_cast<const ShareableElementData&>(*this)));
-}
-
-PassRefPtr<ShareableElementData> UniqueElementData::makeShareableCopy() const
-{
- void* slot = WTF::fastMalloc(sizeForShareableElementDataWithAttributeCount(m_attributeVector.size()));
- return adoptRef(new (slot) ShareableElementData(*this));
-}
-
-void UniqueElementData::addAttribute(const QualifiedName& attributeName, const AtomicString& value)
-{
- m_attributeVector.append(Attribute(attributeName, value));
-}
-
-void UniqueElementData::removeAttribute(size_t index)
+bool Element::supportsStyleSharing() const
{
- ASSERT_WITH_SECURITY_IMPLICATION(index < length());
- m_attributeVector.remove(index);
-}
-
-bool ElementData::isEquivalent(const ElementData* other) const
-{
- if (!other)
- return isEmpty();
-
- unsigned len = length();
- if (len != other->length())
+ if (!isStyledElement() || !parentElement())
+ return false;
+ // If the element has inline style it is probably unique.
+ if (inlineStyle())
+ return false;
+ if (isSVGElement() && toSVGElement(this)->animatedSMILStyleProperties())
+ return false;
+ // Ids stop style sharing if they show up in the stylesheets.
+ if (hasID() && document().ensureStyleResolver().hasRulesForId(idForStyleResolution()))
+ return false;
+ // Active and hovered elements always make a chain towards the document node
+ // and no siblings or cousins will have the same state.
+ if (hovered())
+ return false;
+ if (active())
+ return false;
+ if (focused())
+ return false;
+ if (!parentElement()->childrenSupportStyleSharing())
+ return false;
+ if (hasScopedHTMLStyleChild())
+ return false;
+ if (this == document().cssTarget())
+ return false;
+ if (isHTMLElement() && toHTMLElement(this)->hasDirectionAuto())
+ return false;
+ if (hasActiveAnimations())
+ return false;
+ if (shadow() && shadow()->containsActiveStyles())
+ return false;
+ // Turn off style sharing for elements that can gain layers for reasons outside of the style system.
+ // See comments in RenderObject::setStyle().
+ // FIXME: Why does gaining a layer from outside the style system require disabling sharing?
+ if (hasTagName(iframeTag)
+ || hasTagName(frameTag)
+ || hasTagName(embedTag)
+ || hasTagName(objectTag)
+ || hasTagName(appletTag)
+ || hasTagName(canvasTag))
+ return false;
+ // FIXME: We should share style for option and optgroup whenever possible.
+ // Before doing so, we need to resolve issues in HTMLSelectElement::recalcListItems
+ // and RenderMenuList::setText. See also https://bugs.webkit.org/show_bug.cgi?id=88405
+ if (hasTagName(optionTag) || hasTagName(optgroupTag))
+ return false;
+ if (FullscreenElementStack::isActiveFullScreenElement(this))
return false;
-
- for (unsigned i = 0; i < len; i++) {
- const Attribute* attribute = attributeItem(i);
- const Attribute* otherAttr = other->getAttributeItem(attribute->name());
- if (!otherAttr || attribute->value() != otherAttr->value())
- return false;
- }
-
return true;
}
-size_t ElementData::getAttrIndex(Attr* attr) const
-{
- // This relies on the fact that Attr's QualifiedName == the Attribute's name.
- for (unsigned i = 0; i < length(); ++i) {
- if (attributeItem(i)->name() == attr->qualifiedName())
- return i;
- }
- return kNotFound;
-}
-
-size_t ElementData::getAttributeItemIndexSlowCase(const AtomicString& name, bool shouldIgnoreAttributeCase) const
-{
- // Continue to checking case-insensitively and/or full namespaced names if necessary:
- for (unsigned i = 0; i < length(); ++i) {
- const Attribute* attribute = attributeItem(i);
- if (!attribute->name().hasPrefix()) {
- if (shouldIgnoreAttributeCase && equalIgnoringCase(name, attribute->localName()))
- return i;
- } else {
- // FIXME: Would be faster to do this comparison without calling toString, which
- // generates a temporary string by concatenation. But this branch is only reached
- // if the attribute name has a prefix, which is rare in HTML.
- if (equalPossiblyIgnoringCase(name, attribute->name().toString(), shouldIgnoreAttributeCase))
- return i;
- }
- }
- return kNotFound;
-}
-
-Attribute* UniqueElementData::getAttributeItem(const QualifiedName& name)
-{
- for (unsigned i = 0; i < length(); ++i) {
- if (m_attributeVector.at(i).name().matches(name))
- return &m_attributeVector.at(i);
- }
- return 0;
-}
-
-Attribute* UniqueElementData::attributeItem(unsigned index)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(index < length());
- return &m_attributeVector.at(index);
-}
-
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/Element.h b/chromium/third_party/WebKit/Source/core/dom/Element.h
index 9d1ad834329..370d7d6a5ed 100644
--- a/chromium/third_party/WebKit/Source/core/dom/Element.h
+++ b/chromium/third_party/WebKit/Source/core/dom/Element.h
@@ -30,11 +30,12 @@
#include "core/css/CSSPrimitiveValue.h"
#include "core/dom/Attribute.h"
#include "core/dom/Document.h"
+#include "core/dom/ElementData.h"
#include "core/dom/SpaceSplitString.h"
#include "core/html/CollectionType.h"
#include "core/page/FocusDirection.h"
-#include "core/platform/ScrollTypes.h"
#include "core/rendering/RegionOversetState.h"
+#include "platform/scroll/ScrollTypes.h"
namespace WebCore {
@@ -45,7 +46,6 @@ class ClientRect;
class ClientRectList;
class DOMStringMap;
class DOMTokenList;
-class Element;
class ElementRareData;
class ElementShadow;
class ExceptionState;
@@ -58,113 +58,7 @@ class PropertySetCSSStyleDeclaration;
class PseudoElement;
class RenderRegion;
class ShadowRoot;
-class ShareableElementData;
class StylePropertySet;
-class UniqueElementData;
-
-struct PresentationAttributeCacheKey;
-
-class ElementData : public RefCounted<ElementData> {
- WTF_MAKE_FAST_ALLOCATED;
-public:
- // Override RefCounted's deref() to ensure operator delete is called on
- // the appropriate subclass type.
- void deref();
-
- void clearClass() const { m_classNames.clear(); }
- void setClass(const AtomicString& className, bool shouldFoldCase) const { m_classNames.set(className, shouldFoldCase); }
- const SpaceSplitString& classNames() const { return m_classNames; }
-
- const AtomicString& idForStyleResolution() const { return m_idForStyleResolution; }
- void setIdForStyleResolution(const AtomicString& newId) const { m_idForStyleResolution = newId; }
-
- const StylePropertySet* inlineStyle() const { return m_inlineStyle.get(); }
-
- const StylePropertySet* presentationAttributeStyle() const;
-
- size_t length() const;
- bool isEmpty() const { return !length(); }
-
- const Attribute* attributeItem(unsigned index) const;
- const Attribute* getAttributeItem(const QualifiedName&) const;
- size_t getAttributeItemIndex(const QualifiedName&, bool shouldIgnoreCase = false) const;
- size_t getAttributeItemIndex(const AtomicString& name, bool shouldIgnoreAttributeCase) const;
- size_t getAttrIndex(Attr*) const;
-
- bool hasID() const { return !m_idForStyleResolution.isNull(); }
- bool hasClass() const { return !m_classNames.isNull(); }
-
- bool isEquivalent(const ElementData* other) const;
-
- bool isUnique() const { return m_isUnique; }
-
-protected:
- ElementData();
- ElementData(unsigned arraySize);
- ElementData(const ElementData&, bool isUnique);
-
- unsigned m_isUnique : 1;
- unsigned m_arraySize : 28;
- mutable unsigned m_presentationAttributeStyleIsDirty : 1;
- mutable unsigned m_styleAttributeIsDirty : 1;
- mutable unsigned m_animatedSVGAttributesAreDirty : 1;
-
- mutable RefPtr<StylePropertySet> m_inlineStyle;
- mutable SpaceSplitString m_classNames;
- mutable AtomicString m_idForStyleResolution;
-
-private:
- friend class Element;
- friend class ShareableElementData;
- friend class UniqueElementData;
- friend class SVGElement;
-
- const Attribute* attributeBase() const;
- const Attribute* getAttributeItem(const AtomicString& name, bool shouldIgnoreAttributeCase) const;
- size_t getAttributeItemIndexSlowCase(const AtomicString& name, bool shouldIgnoreAttributeCase) const;
-
- PassRefPtr<UniqueElementData> makeUniqueCopy() const;
-};
-
-#if COMPILER(MSVC)
-#pragma warning(push)
-#pragma warning(disable: 4200) // Disable "zero-sized array in struct/union" warning
-#endif
-
-class ShareableElementData : public ElementData {
-public:
- static PassRefPtr<ShareableElementData> createWithAttributes(const Vector<Attribute>&);
-
- explicit ShareableElementData(const Vector<Attribute>&);
- explicit ShareableElementData(const UniqueElementData&);
- ~ShareableElementData();
-
- Attribute m_attributeArray[0];
-};
-
-#if COMPILER(MSVC)
-#pragma warning(pop)
-#endif
-
-class UniqueElementData : public ElementData {
-public:
- static PassRefPtr<UniqueElementData> create();
- PassRefPtr<ShareableElementData> makeShareableCopy() const;
-
- // These functions do no error/duplicate checking.
- void addAttribute(const QualifiedName&, const AtomicString&);
- void removeAttribute(size_t index);
-
- Attribute* attributeItem(unsigned index);
- Attribute* getAttributeItem(const QualifiedName&);
-
- UniqueElementData();
- explicit UniqueElementData(const ShareableElementData&);
- explicit UniqueElementData(const UniqueElementData&);
-
- mutable RefPtr<StylePropertySet> m_presentationAttributeStyle;
- Vector<Attribute, 4> m_attributeVector;
-};
enum AffectedSelectorType {
AffectedSelectorChecked = 1,
@@ -188,59 +82,21 @@ public:
static PassRefPtr<Element> create(const QualifiedName&, Document*);
virtual ~Element();
- DEFINE_ATTRIBUTE_EVENT_LISTENER(abort);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(change);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(click);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(contextmenu);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(dblclick);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(dragenter);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(dragover);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(dragleave);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(drop);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(dragstart);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(drag);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(dragend);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(input);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(invalid);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(keydown);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(keypress);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(keyup);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(mousedown);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(mouseenter);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(mouseleave);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(mousemove);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(mouseout);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(mouseover);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(mouseup);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(mousewheel);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(scroll);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(select);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(submit);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(wheel);
-
- // These four attribute event handler attributes are overridden by HTMLBodyElement
- // and HTMLFrameSetElement to forward to the DOMWindow.
- DECLARE_VIRTUAL_ATTRIBUTE_EVENT_LISTENER(blur);
- DECLARE_VIRTUAL_ATTRIBUTE_EVENT_LISTENER(error);
- DECLARE_VIRTUAL_ATTRIBUTE_EVENT_LISTENER(focus);
- DECLARE_VIRTUAL_ATTRIBUTE_EVENT_LISTENER(load);
-
- // WebKit extensions
- DEFINE_ATTRIBUTE_EVENT_LISTENER(beforecut);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(cut);
DEFINE_ATTRIBUTE_EVENT_LISTENER(beforecopy);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(copy);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(beforecut);
DEFINE_ATTRIBUTE_EVENT_LISTENER(beforepaste);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(copy);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(cut);
DEFINE_ATTRIBUTE_EVENT_LISTENER(paste);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(reset);
DEFINE_ATTRIBUTE_EVENT_LISTENER(search);
DEFINE_ATTRIBUTE_EVENT_LISTENER(selectstart);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(touchstart);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(touchmove);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(touchend);
DEFINE_ATTRIBUTE_EVENT_LISTENER(touchcancel);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(touchend);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(touchmove);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(touchstart);
DEFINE_ATTRIBUTE_EVENT_LISTENER(webkitfullscreenchange);
DEFINE_ATTRIBUTE_EVENT_LISTENER(webkitfullscreenerror);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(wheel);
bool hasAttribute(const QualifiedName&) const;
const AtomicString& getAttribute(const QualifiedName&) const;
@@ -253,6 +109,8 @@ public:
void setIntegralAttribute(const QualifiedName& attributeName, int value);
unsigned getUnsignedIntegralAttribute(const QualifiedName& attributeName) const;
void setUnsignedIntegralAttribute(const QualifiedName& attributeName, unsigned value);
+ double getFloatingPointAttribute(const QualifiedName& attributeName, double fallbackValue = std::numeric_limits<double>::quiet_NaN()) const;
+ void setFloatingPointAttribute(const QualifiedName& attributeName, double value);
// Call this to get the value of an attribute that is known not to be the style
// attribute or one of the SVG animatable attributes.
@@ -287,6 +145,8 @@ public:
const AtomicString& getNameAttribute() const;
const AtomicString& getClassAttribute() const;
+ bool shouldIgnoreAttributeCase() const;
+
// Call this to get the value of the id attribute for style resolution purposes.
// The value will already be lowercased if the document is in compatibility mode,
// so this function is not suitable for non-style uses.
@@ -335,7 +195,7 @@ public:
// Returns the absolute bounding box translated into screen coordinates:
IntRect screenRect() const;
- virtual void didMoveToNewDocument(Document*) OVERRIDE;
+ virtual void didMoveToNewDocument(Document&) OVERRIDE;
void removeAttribute(const AtomicString& name);
void removeAttributeNS(const AtomicString& namespaceURI, const AtomicString& localName);
@@ -359,6 +219,9 @@ public:
String tagName() const { return nodeName(); }
bool hasTagName(const QualifiedName& tagName) const { return m_tagName.matches(tagName); }
+ // Should be called only by Document::createElementNS to fix up m_tagName immediately after construction.
+ void setTagNameForCreateElementNS(const QualifiedName&);
+
// A fast function for checking the local name against another atomic string.
bool hasLocalName(const AtomicString& other) const { return m_tagName.localName() == other; }
bool hasLocalName(const QualifiedName& other) const { return m_tagName.localName() == other.localName(); }
@@ -396,6 +259,7 @@ public:
void synchronizeStyleAttributeInternal() const;
const StylePropertySet* presentationAttributeStyle();
+ virtual bool isPresentationAttribute(const QualifiedName&) const { return false; }
virtual void collectStyleForPresentationAttribute(const QualifiedName&, const AtomicString&, MutableStylePropertySet*) { }
// For exposing to DOM only.
@@ -435,24 +299,31 @@ public:
virtual void detach(const AttachContext& = AttachContext()) OVERRIDE;
virtual RenderObject* createRenderer(RenderStyle*);
virtual bool rendererIsNeeded(const RenderStyle&);
- bool recalcStyle(StyleRecalcChange);
+ void recalcStyle(StyleRecalcChange, Text* nextTextSibling = 0);
void didAffectSelector(AffectedSelectorMask);
+ void setAnimationStyleChange(bool);
+ void setNeedsAnimationStyleRecalc();
+
+ bool supportsStyleSharing() const;
ElementShadow* shadow() const;
- ElementShadow* ensureShadow();
+ ElementShadow& ensureShadow();
PassRefPtr<ShadowRoot> createShadowRoot(ExceptionState&);
ShadowRoot* shadowRoot() const;
+ ShadowRoot* youngestShadowRoot() const;
bool hasAuthorShadowRoot() const { return shadowRoot(); }
virtual void didAddShadowRoot(ShadowRoot&);
ShadowRoot* userAgentShadowRoot() const;
- ShadowRoot* ensureUserAgentShadowRoot();
- virtual const AtomicString& shadowPseudoId() const { return !part().isEmpty() ? part() : pseudo(); }
+ ShadowRoot& ensureUserAgentShadowRoot();
+ const AtomicString& shadowPseudoId() const;
+ bool isInDescendantTreeOf(const Element* shadowHost) const;
RenderStyle* computedStyle(PseudoId = NOPSEUDO);
// Methods for indicating the style is affected by dynamic updates (e.g., children changing, our position changing in our sibling list, etc.)
bool styleAffectedByEmpty() const { return hasRareData() && rareDataStyleAffectedByEmpty(); }
+ bool childrenAffectedByFocus() const { return hasRareData() && rareDataChildrenAffectedByFocus(); }
bool childrenAffectedByHover() const { return hasRareData() && rareDataChildrenAffectedByHover(); }
bool childrenAffectedByActive() const { return hasRareData() && rareDataChildrenAffectedByActive(); }
bool childrenAffectedByDrag() const { return hasRareData() && rareDataChildrenAffectedByDrag(); }
@@ -464,12 +335,13 @@ public:
bool childrenAffectedByBackwardPositionalRules() const { return hasRareData() && rareDataChildrenAffectedByBackwardPositionalRules(); }
unsigned childIndex() const { return hasRareData() ? rareDataChildIndex() : 0; }
- bool hasFlagsSetDuringStylingOfChildren() const;
+ bool childrenSupportStyleSharing() const;
void setStyleAffectedByEmpty();
- void setChildrenAffectedByHover(bool);
- void setChildrenAffectedByActive(bool);
- void setChildrenAffectedByDrag(bool);
+ void setChildrenAffectedByFocus();
+ void setChildrenAffectedByHover();
+ void setChildrenAffectedByActive();
+ void setChildrenAffectedByDrag();
void setChildrenAffectedByFirstChildRules();
void setChildrenAffectedByLastChildRules();
void setChildrenAffectedByDirectAdjacentRules();
@@ -481,7 +353,7 @@ public:
bool isInCanvasSubtree() const;
bool isUpgradedCustomElement() { return customElementState() == Upgraded; }
- bool isUnresolvedCustomElement() { return isCustomElement() && !isUpgradedCustomElement(); }
+ bool isUnresolvedCustomElement() { return customElementState() == WaitingForUpgrade; }
void setIsInsideRegion(bool);
bool isInsideRegion() const;
@@ -523,14 +395,18 @@ public:
String innerText();
String outerText();
+ String innerHTML() const;
+ String outerHTML() const;
+ void setInnerHTML(const String&, ExceptionState&);
+ void setOuterHTML(const String&, ExceptionState&);
+ void insertAdjacentHTML(const String& where, const String& html, ExceptionState&);
String textFromChildren();
virtual String title() const { return String(); }
- const AtomicString& pseudo() const;
- virtual const AtomicString& part() const;
- void setPart(const AtomicString&);
+ virtual const AtomicString& pseudo() const;
+ void setPseudo(const AtomicString&);
LayoutSize minimumSizeForResizing() const;
void setMinimumSizeForResizing(const LayoutSize&);
@@ -620,8 +496,8 @@ public:
bool isSpellCheckingEnabled() const;
+ // FIXME: public for NodeRenderingContext, we shouldn't expose this though.
PassRefPtr<RenderStyle> styleForRenderer();
- PassRefPtr<RenderStyle> originalStyleForRenderer();
RenderRegion* renderRegion() const;
virtual bool shouldMoveToFlowThread(RenderStyle*) const;
@@ -640,9 +516,14 @@ public:
bool hasActiveAnimations() const;
InputMethodContext* inputMethodContext();
+ bool hasInputMethodContext() const;
virtual void setPrefix(const AtomicString&, ExceptionState&) OVERRIDE FINAL;
+ void synchronizeAttribute(const AtomicString& localName) const;
+
+ bool needsPseudoElement(PseudoId, const RenderStyle&) const;
+
protected:
Element(const QualifiedName& tagName, Document* document, ConstructionType type)
: ContainerNode(document, type)
@@ -651,8 +532,6 @@ protected:
ScriptWrappable::init(this);
}
- virtual bool isPresentationAttribute(const QualifiedName&) const { return false; }
-
void addPropertyToPresentationAttributeStyle(MutableStylePropertySet*, CSSPropertyID, CSSValueID identifier);
void addPropertyToPresentationAttributeStyle(MutableStylePropertySet*, CSSPropertyID, double value, CSSPrimitiveValue::UnitTypes);
void addPropertyToPresentationAttributeStyle(MutableStylePropertySet*, CSSPropertyID, const String& value);
@@ -688,9 +567,15 @@ protected:
// svgAttributeChanged (called when element.className.baseValue is set)
void classAttributeChanged(const AtomicString& newClassString);
+ PassRefPtr<RenderStyle> originalStyleForRenderer();
+
+ Node* insertAdjacent(const String& where, Node* newChild, ExceptionState&);
+
private:
void styleAttributeChanged(const AtomicString& newStyleString, AttributeModificationReason);
+ void updatePresentationAttributeStyle();
+
void inlineStyleChanged();
PropertySetCSSStyleDeclaration* inlineStyleCSSOMWrapper();
void setInlineStyleFromString(const AtomicString&);
@@ -699,18 +584,19 @@ private:
StyleRecalcChange recalcOwnStyle(StyleRecalcChange);
void recalcChildStyle(StyleRecalcChange);
- void makePresentationAttributeCacheKey(PresentationAttributeCacheKey&) const;
- void rebuildPresentationAttributeStyle();
+ // FIXME: These methods should all be renamed to something better than "check",
+ // since it's not clear that they alter the style bits of siblings and children.
+ void checkForChildrenAdjacentRuleChanges();
+ void checkForSiblingStyleChanges(bool finishedParsingCallback, Node* beforeChange, Node* afterChange, int childCountDelta);
+ inline void checkForEmptyStyleChange(RenderStyle*);
void updatePseudoElement(PseudoId, StyleRecalcChange);
inline void createPseudoElementIfNeeded(PseudoId);
- inline bool needsPseudoElement(PseudoId) const;
- void createPseudoElement(PseudoId);
// FIXME: Everyone should allow author shadows.
virtual bool areAuthorShadowsAllowed() const { return true; }
- virtual void didAddUserAgentShadowRoot(ShadowRoot*) { }
+ virtual void didAddUserAgentShadowRoot(ShadowRoot&) { }
virtual bool alwaysCreateUserAgentShadowRoot() const { return false; }
// FIXME: Remove the need for Attr to call willModifyAttribute/didModifyAttribute.
@@ -724,7 +610,6 @@ private:
void didRemoveAttribute(const QualifiedName&);
void synchronizeAttribute(const QualifiedName&) const;
- void synchronizeAttribute(const AtomicString& localName) const;
void updateId(const AtomicString& oldId, const AtomicString& newId);
void updateId(TreeScope&, const AtomicString& oldId, const AtomicString& newId);
@@ -751,6 +636,10 @@ private:
virtual RenderStyle* virtualComputedStyle(PseudoId pseudoElementSpecifier = NOPSEUDO) { return computedStyle(pseudoElementSpecifier); }
+ inline void updateCallbackSelectors(RenderStyle* oldStyle, RenderStyle* newStyle);
+ inline void removeCallbackSelectors();
+ inline void addCallbackSelectors();
+
// cloneNode is private so that non-virtual cloneElementWithChildren and cloneElementWithoutChildren
// are used instead.
virtual PassRefPtr<Node> cloneNode(bool deep) OVERRIDE;
@@ -758,6 +647,7 @@ private:
QualifiedName m_tagName;
bool rareDataStyleAffectedByEmpty() const;
+ bool rareDataChildrenAffectedByFocus() const;
bool rareDataChildrenAffectedByHover() const;
bool rareDataChildrenAffectedByActive() const;
bool rareDataChildrenAffectedByDrag() const;
@@ -780,7 +670,7 @@ private:
bool shouldInvalidateDistributionWhenAttributeChanged(ElementShadow*, const QualifiedName&, const AtomicString&);
ElementRareData* elementRareData() const;
- ElementRareData* ensureElementRareData();
+ ElementRareData& ensureElementRareData();
void detachAllAttrNodesFromElement();
void detachAttrNodeFromElementWithValue(Attr*, const AtomicString& value);
@@ -791,26 +681,7 @@ private:
RefPtr<ElementData> m_elementData;
};
-inline Element* toElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->isElementNode());
- return static_cast<Element*>(node);
-}
-
-inline const Element* toElement(const Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->isElementNode());
- return static_cast<const Element*>(node);
-}
-
-inline const Element& toElement(const Node& node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(node.isElementNode());
- return static_cast<const Element&>(node);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toElement(const Element*);
+DEFINE_NODE_TYPE_CASTS(Element, isElementNode());
inline bool isDisabledFormControl(const Node* node)
{
@@ -822,21 +693,6 @@ inline bool Node::hasTagName(const QualifiedName& name) const
return isElementNode() && toElement(this)->hasTagName(name);
}
-inline bool Node::hasLocalName(const AtomicString& name) const
-{
- return isElementNode() && toElement(this)->hasLocalName(name);
-}
-
-inline bool Node::hasAttributes() const
-{
- return isElementNode() && toElement(this)->hasAttributes();
-}
-
-inline NamedNodeMap* Node::attributes() const
-{
- return isElementNode() ? toElement(this)->attributes() : 0;
-}
-
inline Element* Node::parentElement() const
{
ContainerNode* parent = parentNode();
@@ -886,6 +742,11 @@ inline const AtomicString& Element::idForStyleResolution() const
return elementData()->idForStyleResolution();
}
+inline const AtomicString& Element::shadowPseudoId() const
+{
+ return pseudo();
+}
+
inline bool Element::isIdAttributeName(const QualifiedName& attributeName) const
{
// FIXME: This check is probably not correct for the case where the document has an id attribute
@@ -914,6 +775,11 @@ inline const AtomicString& Element::getClassAttribute() const
return fastGetAttribute(HTMLNames::classAttr);
}
+inline bool Element::shouldIgnoreAttributeCase() const
+{
+ return isHTMLElement() && document().isHTMLDocument();
+}
+
inline void Element::setIdAttribute(const AtomicString& value)
{
setAttribute(document().idAttributeName(), value);
@@ -1004,10 +870,20 @@ inline const StylePropertySet* Element::presentationAttributeStyle()
if (!elementData())
return 0;
if (elementData()->m_presentationAttributeStyleIsDirty)
- rebuildPresentationAttributeStyle();
+ updatePresentationAttributeStyle();
+ // Need to call elementData() again since updatePresentationAttributeStyle()
+ // might swap it with a UniqueElementData.
return elementData()->presentationAttributeStyle();
}
+inline void Element::setTagNameForCreateElementNS(const QualifiedName& tagName)
+{
+ // We expect this method to be called only to reset the prefix.
+ ASSERT(tagName.localName() == m_tagName.localName());
+ ASSERT(tagName.namespaceURI() == m_tagName.namespaceURI());
+ m_tagName = tagName;
+}
+
inline bool isShadowHost(const Node* node)
{
return node && node->isElementNode() && toElement(node)->shadow();
@@ -1018,86 +894,6 @@ inline bool isShadowHost(const Element* element)
return element && element->shadow();
}
-inline size_t ElementData::length() const
-{
- if (isUnique())
- return static_cast<const UniqueElementData*>(this)->m_attributeVector.size();
- return m_arraySize;
-}
-
-inline const StylePropertySet* ElementData::presentationAttributeStyle() const
-{
- if (!m_isUnique)
- return 0;
- return static_cast<const UniqueElementData*>(this)->m_presentationAttributeStyle.get();
-}
-
-inline const Attribute* ElementData::getAttributeItem(const AtomicString& name, bool shouldIgnoreAttributeCase) const
-{
- size_t index = getAttributeItemIndex(name, shouldIgnoreAttributeCase);
- if (index != kNotFound)
- return attributeItem(index);
- return 0;
-}
-
-inline const Attribute* ElementData::attributeBase() const
-{
- if (m_isUnique)
- return static_cast<const UniqueElementData*>(this)->m_attributeVector.begin();
- return static_cast<const ShareableElementData*>(this)->m_attributeArray;
-}
-
-inline size_t ElementData::getAttributeItemIndex(const QualifiedName& name, bool shouldIgnoreCase) const
-{
- const Attribute* begin = attributeBase();
- for (unsigned i = 0; i < length(); ++i) {
- const Attribute& attribute = begin[i];
- if (attribute.name().matchesPossiblyIgnoringCase(name, shouldIgnoreCase))
- return i;
- }
- return kNotFound;
-}
-
-// We use a boolean parameter instead of calling shouldIgnoreAttributeCase so that the caller
-// can tune the behavior (hasAttribute is case sensitive whereas getAttribute is not).
-inline size_t ElementData::getAttributeItemIndex(const AtomicString& name, bool shouldIgnoreAttributeCase) const
-{
- unsigned len = length();
- bool doSlowCheck = shouldIgnoreAttributeCase;
-
- // Optimize for the case where the attribute exists and its name exactly matches.
- const Attribute* begin = attributeBase();
- for (unsigned i = 0; i < len; ++i) {
- const Attribute& attribute = begin[i];
- if (!attribute.name().hasPrefix()) {
- if (name == attribute.localName())
- return i;
- } else
- doSlowCheck = true;
- }
-
- if (doSlowCheck)
- return getAttributeItemIndexSlowCase(name, shouldIgnoreAttributeCase);
- return kNotFound;
-}
-
-inline const Attribute* ElementData::getAttributeItem(const QualifiedName& name) const
-{
- const Attribute* begin = attributeBase();
- for (unsigned i = 0; i < length(); ++i) {
- const Attribute& attribute = begin[i];
- if (attribute.name().matches(name))
- return &attribute;
- }
- return 0;
-}
-
-inline const Attribute* ElementData::attributeItem(unsigned index) const
-{
- RELEASE_ASSERT(index < length());
- return attributeBase() + index;
-}
-
} // namespace
#endif
diff --git a/chromium/third_party/WebKit/Source/core/dom/Element.idl b/chromium/third_party/WebKit/Source/core/dom/Element.idl
index 55df8341afd..ac5003883ee 100644
--- a/chromium/third_party/WebKit/Source/core/dom/Element.idl
+++ b/chromium/third_party/WebKit/Source/core/dom/Element.idl
@@ -19,51 +19,42 @@
*/
[
- CustomToV8
+ SpecialWrapFor=HTMLElement|SVGElement
] interface Element : Node {
// DOM Level 1 Core
[TreatReturnedNullStringAs=Null, PerWorldBindings] readonly attribute DOMString tagName;
- [TreatReturnedNullStringAs=Null] DOMString getAttribute([Default=Undefined] optional DOMString name);
- [RaisesException, CustomElementCallbacks=Enable] void setAttribute([Default=Undefined] optional DOMString name,
- [Default=Undefined] optional DOMString value);
- [CustomElementCallbacks=Enable] void removeAttribute([Default=Undefined] optional DOMString name);
+ [TreatReturnedNullStringAs=Null] DOMString getAttribute(DOMString name);
+ [RaisesException, CustomElementCallbacks] void setAttribute(DOMString name, DOMString value);
+ [CustomElementCallbacks] void removeAttribute(DOMString name);
[MeasureAs=ElementGetAttributeNode] Attr getAttributeNode([Default=Undefined] optional DOMString name); // Removed from DOM4.
- [RaisesException, CustomElementCallbacks=Enable, MeasureAs=ElementSetAttributeNode] Attr setAttributeNode([Default=Undefined, StrictTypeChecking] optional Attr newAttr); // Removed from DOM4.
- [RaisesException, CustomElementCallbacks=Enable, MeasureAs=ElementRemoveAttributeNode] Attr removeAttributeNode([Default=Undefined, StrictTypeChecking] optional Attr oldAttr); // Removed from DOM4.
- [PerWorldBindings] NodeList getElementsByTagName([Default=Undefined] optional DOMString name);
+ [RaisesException, CustomElementCallbacks, MeasureAs=ElementSetAttributeNode] Attr setAttributeNode([Default=Undefined, StrictTypeChecking] optional Attr newAttr); // Removed from DOM4.
+ [RaisesException, CustomElementCallbacks, MeasureAs=ElementRemoveAttributeNode] Attr removeAttributeNode([Default=Undefined, StrictTypeChecking] optional Attr oldAttr); // Removed from DOM4.
+ [PerWorldBindings] NodeList getElementsByTagName(DOMString name);
[PerWorldBindings] readonly attribute NamedNodeMap attributes;
[MeasureAs=HasAttributes] boolean hasAttributes();
// DOM Level 2 Core
- DOMString getAttributeNS([TreatNullAs=NullString,Default=Undefined] optional DOMString namespaceURI,
- [Default=Undefined] optional DOMString localName);
- [RaisesException, CustomElementCallbacks=Enable] void setAttributeNS([TreatNullAs=NullString,Default=Undefined] optional DOMString namespaceURI,
- [Default=Undefined] optional DOMString qualifiedName,
- [Default=Undefined] optional DOMString value);
- [CustomElementCallbacks=Enable] void removeAttributeNS([TreatNullAs=NullString] DOMString namespaceURI,
- DOMString localName);
- NodeList getElementsByTagNameNS([TreatNullAs=NullString,Default=Undefined] optional DOMString namespaceURI,
- [Default=Undefined] optional DOMString localName);
- [MeasureAs=ElementGetAttributeNodeNS] Attr getAttributeNodeNS([TreatNullAs=NullString,Default=Undefined] optional DOMString namespaceURI,
- [Default=Undefined] optional DOMString localName); // Removed from DOM4.
- [RaisesException, CustomElementCallbacks=Enable] Attr setAttributeNodeNS([Default=Undefined, StrictTypeChecking] optional Attr newAttr);
+ DOMString getAttributeNS([TreatNullAs=NullString] DOMString namespaceURI, DOMString localName);
+ [RaisesException, CustomElementCallbacks] void setAttributeNS([TreatNullAs=NullString] DOMString namespaceURI, DOMString qualifiedName, DOMString value);
+ [CustomElementCallbacks] void removeAttributeNS([TreatNullAs=NullString] DOMString namespaceURI, DOMString localName);
+ NodeList getElementsByTagNameNS([TreatNullAs=NullString] DOMString namespaceURI, DOMString localName);
+ [MeasureAs=ElementGetAttributeNodeNS] Attr getAttributeNodeNS([TreatNullAs=NullString,Default=Undefined] optional DOMString namespaceURI,
+ [Default=Undefined] optional DOMString localName); // Removed from DOM4.
+ [RaisesException, CustomElementCallbacks, MeasureAs=ElementSetAttributeNodeNS] Attr setAttributeNodeNS([Default=Undefined, StrictTypeChecking] optional Attr newAttr); // Removed from DOM4.
boolean hasAttribute(DOMString name);
- boolean hasAttributeNS([TreatNullAs=NullString,Default=Undefined] optional DOMString namespaceURI,
- [Default=Undefined] optional DOMString localName);
+ boolean hasAttributeNS([TreatNullAs=NullString] DOMString namespaceURI, DOMString localName);
[PerWorldBindings] readonly attribute CSSStyleDeclaration style;
// DOM4
- // iht.com relies on id returning the empty string when no id is present.
- // Other browsers do this as well. So we don't convert null to JS null.
[Reflect] attribute DOMString id;
[TreatReturnedNullStringAs=Null, PerWorldBindings] readonly attribute DOMString namespaceURI;
- [TreatReturnedNullStringAs=Null, TreatNullAs=NullString, PerWorldBindings, SetterRaisesException] attribute DOMString prefix;
+ [TreatReturnedNullStringAs=Null, TreatNullAs=NullString, PerWorldBindings, RaisesException=Setter] attribute DOMString prefix;
[TreatReturnedNullStringAs=Null, PerWorldBindings] readonly attribute DOMString localName;
// Common extensions
@@ -77,8 +68,8 @@
[PerWorldBindings] readonly attribute long clientTop;
[PerWorldBindings] readonly attribute long clientWidth;
[PerWorldBindings] readonly attribute long clientHeight;
- [PerWorldBindings] attribute long scrollLeft;
- [PerWorldBindings] attribute long scrollTop;
+ [PerWorldBindings] attribute long scrollLeft;
+ [PerWorldBindings] attribute long scrollTop;
[PerWorldBindings] readonly attribute long scrollWidth;
[PerWorldBindings] readonly attribute long scrollHeight;
@@ -93,7 +84,10 @@
void scrollByPages([Default=Undefined] optional long pages);
// HTML 5
- NodeList getElementsByClassName([Default=Undefined] optional DOMString name);
+ NodeList getElementsByClassName(DOMString classNames);
+ [TreatNullAs=NullString, CustomElementCallbacks, PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds, RaisesException=Setter] attribute DOMString innerHTML;
+ [TreatNullAs=NullString, CustomElementCallbacks, RaisesException=Setter] attribute DOMString outerHTML;
+ [CustomElementCallbacks, RaisesException] void insertAdjacentHTML(DOMString where, DOMString html);
[Reflect=class, PerWorldBindings] attribute DOMString className;
[PerWorldBindings] readonly attribute DOMTokenList classList;
@@ -104,17 +98,17 @@
[RaisesException] Element querySelector(DOMString selectors);
[RaisesException] NodeList querySelectorAll(DOMString selectors);
- // WebKit extension, pending specification.
- [RaisesException] boolean webkitMatchesSelector([Default=Undefined] optional DOMString selectors);
+ // WebKit extension
+ [RaisesException, MeasureAs=ElementPrefixedMatchesSelector] boolean webkitMatchesSelector([Default=Undefined] optional DOMString selectors);
// Shadow DOM API
- [EnabledAtRuntime=ShadowDOM, Reflect, PerWorldBindings] attribute DOMString pseudo;
- [EnabledAtRuntime=ShadowDOM, RaisesException] ShadowRoot createShadowRoot();
- [EnabledAtRuntime=ShadowDOM, PerWorldBindings] readonly attribute ShadowRoot shadowRoot;
- [EnabledAtRuntime=ShadowDOM, PerWorldBindings] NodeList getDestinationInsertionPoints();
+ [RuntimeEnabled=ShadowDOM, Reflect, TreatNullAs=NullString, PerWorldBindings] attribute DOMString pseudo;
+ [RuntimeEnabled=ShadowDOM, RaisesException] ShadowRoot createShadowRoot();
+ [RuntimeEnabled=ShadowDOM, PerWorldBindings] readonly attribute ShadowRoot shadowRoot;
+ [RuntimeEnabled=ShadowDOM, PerWorldBindings] NodeList getDestinationInsertionPoints();
// To-be-deprecated prefixed Shadow DOM API
- [Reflect=pseudo, ImplementedAs=pseudo, PerWorldBindings, MeasureAs=ShadowDOMPrefixedPseudo] attribute DOMString webkitPseudo;
+ [Reflect=pseudo, TreatNullAs=NullString, ImplementedAs=pseudo, PerWorldBindings, MeasureAs=ShadowDOMPrefixedPseudo] attribute DOMString webkitPseudo;
[ImplementedAs=createShadowRoot, RaisesException, MeasureAs=ShadowDOMPrefixedCreateShadowRoot] ShadowRoot webkitCreateShadowRoot();
[ImplementedAs=shadowRoot, PerWorldBindings, MeasureAs=ShadowDOMPrefixedShadowRoot] readonly attribute ShadowRoot webkitShadowRoot;
@@ -124,91 +118,33 @@
// Mozilla version
const unsigned short ALLOW_KEYBOARD_INPUT = 1;
- [EnabledAtRuntime=Fullscreen, PerWorldBindings, ActivityLog=Access] void webkitRequestFullScreen([Default=Undefined] optional unsigned short flags);
+ [RuntimeEnabled=Fullscreen, PerWorldBindings, ActivityLogging=ForAllWorlds, MeasureAs=PrefixedElementRequestFullScreen] void webkitRequestFullScreen([Default=Undefined] optional unsigned short flags);
// W3C version
- [EnabledAtRuntime=Fullscreen, PerWorldBindings, ActivityLog=Access] void webkitRequestFullscreen();
+ [RuntimeEnabled=Fullscreen, PerWorldBindings, ActivityLogging=ForAllWorlds, MeasureAs=PrefixedElementRequestFullscreen] void webkitRequestFullscreen();
void webkitRequestPointerLock();
// CSS Regions API
- [EnabledAtRuntime=CSSRegions, PerWorldBindings] readonly attribute DOMString webkitRegionOverset;
- [EnabledAtRuntime=CSSRegions] sequence<Range> webkitGetRegionFlowRanges();
-
- // Event handler DOM attributes
- [NotEnumerable, PerWorldBindings] attribute EventHandler onabort;
- [NotEnumerable, PerWorldBindings] attribute EventHandler onblur;
- [NotEnumerable, PerWorldBindings] attribute EventHandler onchange;
- [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onclick;
- [NotEnumerable, PerWorldBindings] attribute EventHandler oncontextmenu;
- [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler ondblclick;
- [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler ondrag;
- [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler ondragend;
- [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler ondragenter;
- [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler ondragleave;
- [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler ondragover;
- [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler ondragstart;
- [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler ondrop;
- [NotEnumerable, PerWorldBindings] attribute EventHandler onerror;
- [NotEnumerable, PerWorldBindings] attribute EventHandler onfocus;
- [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler oninput;
- [NotEnumerable, PerWorldBindings] attribute EventHandler oninvalid;
- [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onkeydown;
- [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onkeypress;
- [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onkeyup;
- [NotEnumerable, PerWorldBindings] attribute EventHandler onload;
- [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onmousedown;
- [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onmouseenter;
- [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onmouseleave;
- [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onmousemove;
- [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onmouseout;
- [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onmouseover;
- [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onmouseup;
- [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onmousewheel; // Deprecated in favor of onwheel.
- [NotEnumerable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onwheel;
- [NotEnumerable, PerWorldBindings] attribute EventHandler onscroll;
- [NotEnumerable, PerWorldBindings] attribute EventHandler onselect;
- [NotEnumerable, PerWorldBindings] attribute EventHandler onsubmit;
-
- // attribute [NotEnumerable] EventHandler oncanplay;
- // attribute [NotEnumerable] EventHandler oncanplaythrough;
- // attribute [NotEnumerable] EventHandler ondurationchange;
- // attribute [NotEnumerable] EventHandler onemptied;
- // attribute [NotEnumerable] EventHandler onended;
- // attribute [NotEnumerable] EventHandler onloadeddata;
- // attribute [NotEnumerable] EventHandler onloadedmetadata;
- // attribute [NotEnumerable] EventHandler onloadstart;
- // attribute [NotEnumerable] EventHandler onpause;
- // attribute [NotEnumerable] EventHandler onplay;
- // attribute [NotEnumerable] EventHandler onplaying;
- // attribute [NotEnumerable] EventHandler onprogress;
- // attribute [NotEnumerable] EventHandler onratechange;
- // attribute [NotEnumerable] EventHandler onreadystatechange;
- // attribute [NotEnumerable] EventHandler onseeked;
- // attribute [NotEnumerable] EventHandler onseeking;
- // attribute [NotEnumerable] EventHandler onshow;
- // attribute [NotEnumerable] EventHandler onstalled;
- // attribute [NotEnumerable] EventHandler onsuspend;
- // attribute [NotEnumerable] EventHandler ontimeupdate;
- // attribute [NotEnumerable] EventHandler onvolumechange;
- // attribute [NotEnumerable] EventHandler onwaiting;
-
- // WebKit extensions
- [NotEnumerable, PerWorldBindings] attribute EventHandler onbeforecut;
- [NotEnumerable, PerWorldBindings] attribute EventHandler oncut;
- [NotEnumerable, PerWorldBindings] attribute EventHandler onbeforecopy;
- [NotEnumerable, PerWorldBindings] attribute EventHandler oncopy;
- [NotEnumerable, PerWorldBindings] attribute EventHandler onbeforepaste;
- [NotEnumerable, PerWorldBindings] attribute EventHandler onpaste;
- [NotEnumerable, PerWorldBindings] attribute EventHandler onreset;
- [NotEnumerable, PerWorldBindings] attribute EventHandler onsearch;
- [NotEnumerable, PerWorldBindings] attribute EventHandler onselectstart;
- [NotEnumerable, EnabledAtRuntime=Touch, PerWorldBindings] attribute EventHandler ontouchstart;
- [NotEnumerable, EnabledAtRuntime=Touch, PerWorldBindings] attribute EventHandler ontouchmove;
- [NotEnumerable, EnabledAtRuntime=Touch, PerWorldBindings] attribute EventHandler ontouchend;
- [NotEnumerable, EnabledAtRuntime=Touch, PerWorldBindings] attribute EventHandler ontouchcancel;
- [NotEnumerable, PerWorldBindings] attribute EventHandler onwebkitfullscreenchange;
- [NotEnumerable, PerWorldBindings] attribute EventHandler onwebkitfullscreenerror;
+ [RuntimeEnabled=CSSRegions, PerWorldBindings] readonly attribute DOMString webkitRegionOverset;
+ [RuntimeEnabled=CSSRegions] sequence<Range> webkitGetRegionFlowRanges();
+
+ // Event handler attributes
+ attribute EventHandler onbeforecopy;
+ attribute EventHandler onbeforecut;
+ attribute EventHandler onbeforepaste;
+ attribute EventHandler oncopy;
+ attribute EventHandler oncut;
+ attribute EventHandler onpaste;
+ attribute EventHandler onsearch;
+ attribute EventHandler onselectstart;
+ [RuntimeEnabled=Touch] attribute EventHandler ontouchcancel;
+ [RuntimeEnabled=Touch] attribute EventHandler ontouchend;
+ [RuntimeEnabled=Touch] attribute EventHandler ontouchmove;
+ [RuntimeEnabled=Touch] attribute EventHandler ontouchstart;
+ attribute EventHandler onwebkitfullscreenchange;
+ attribute EventHandler onwebkitfullscreenerror;
+ [PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute EventHandler onwheel;
};
Element implements ParentNode;
diff --git a/chromium/third_party/WebKit/Source/core/dom/ElementData.cpp b/chromium/third_party/WebKit/Source/core/dom/ElementData.cpp
new file mode 100644
index 00000000000..2ce4aa0413a
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/ElementData.cpp
@@ -0,0 +1,225 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/dom/ElementData.h"
+
+#include "core/css/StylePropertySet.h"
+#include "core/dom/Attr.h"
+#include "core/dom/QualifiedName.h"
+#include "wtf/Vector.h"
+
+namespace WebCore {
+
+struct SameSizeAsElementData : public RefCounted<SameSizeAsElementData> {
+ unsigned bitfield;
+ void* refPtrs[3];
+};
+
+COMPILE_ASSERT(sizeof(ElementData) == sizeof(SameSizeAsElementData), element_attribute_data_should_stay_small);
+
+static size_t sizeForShareableElementDataWithAttributeCount(unsigned count)
+{
+ return sizeof(ShareableElementData) + sizeof(Attribute) * count;
+}
+
+ElementData::ElementData()
+ : m_isUnique(true)
+ , m_arraySize(0)
+ , m_presentationAttributeStyleIsDirty(false)
+ , m_styleAttributeIsDirty(false)
+ , m_animatedSVGAttributesAreDirty(false)
+{
+}
+
+ElementData::ElementData(unsigned arraySize)
+ : m_isUnique(false)
+ , m_arraySize(arraySize)
+ , m_presentationAttributeStyleIsDirty(false)
+ , m_styleAttributeIsDirty(false)
+ , m_animatedSVGAttributesAreDirty(false)
+{
+}
+
+ElementData::ElementData(const ElementData& other, bool isUnique)
+ : m_isUnique(isUnique)
+ , m_arraySize(isUnique ? 0 : other.length())
+ , m_presentationAttributeStyleIsDirty(other.m_presentationAttributeStyleIsDirty)
+ , m_styleAttributeIsDirty(other.m_styleAttributeIsDirty)
+ , m_animatedSVGAttributesAreDirty(other.m_animatedSVGAttributesAreDirty)
+ , m_classNames(other.m_classNames)
+ , m_idForStyleResolution(other.m_idForStyleResolution)
+{
+ // NOTE: The inline style is copied by the subclass copy constructor since we don't know what to do with it here.
+}
+
+void ElementData::destroy()
+{
+ if (m_isUnique)
+ delete static_cast<UniqueElementData*>(this);
+ else
+ delete static_cast<ShareableElementData*>(this);
+}
+
+PassRefPtr<UniqueElementData> ElementData::makeUniqueCopy() const
+{
+ if (isUnique())
+ return adoptRef(new UniqueElementData(static_cast<const UniqueElementData&>(*this)));
+ return adoptRef(new UniqueElementData(static_cast<const ShareableElementData&>(*this)));
+}
+
+bool ElementData::isEquivalent(const ElementData* other) const
+{
+ if (!other)
+ return isEmpty();
+
+ unsigned len = length();
+ if (len != other->length())
+ return false;
+
+ for (unsigned i = 0; i < len; i++) {
+ const Attribute* attribute = attributeItem(i);
+ const Attribute* otherAttr = other->getAttributeItem(attribute->name());
+ if (!otherAttr || attribute->value() != otherAttr->value())
+ return false;
+ }
+
+ return true;
+}
+
+size_t ElementData::getAttrIndex(Attr* attr) const
+{
+ // This relies on the fact that Attr's QualifiedName == the Attribute's name.
+ for (unsigned i = 0; i < length(); ++i) {
+ if (attributeItem(i)->name() == attr->qualifiedName())
+ return i;
+ }
+ return kNotFound;
+}
+
+size_t ElementData::getAttributeItemIndexSlowCase(const AtomicString& name, bool shouldIgnoreAttributeCase) const
+{
+ // Continue to checking case-insensitively and/or full namespaced names if necessary:
+ for (unsigned i = 0; i < length(); ++i) {
+ const Attribute* attribute = attributeItem(i);
+ // FIXME: Why check the prefix? Namespace is all that should matter
+ // and all HTML/SVG attributes have a null namespace!
+ if (!attribute->name().hasPrefix()) {
+ if (shouldIgnoreAttributeCase && equalIgnoringCase(name, attribute->localName()))
+ return i;
+ } else {
+ // FIXME: Would be faster to do this comparison without calling toString, which
+ // generates a temporary string by concatenation. But this branch is only reached
+ // if the attribute name has a prefix, which is rare in HTML.
+ if (equalPossiblyIgnoringCase(name, attribute->name().toString(), shouldIgnoreAttributeCase))
+ return i;
+ }
+ }
+ return kNotFound;
+}
+
+ShareableElementData::ShareableElementData(const Vector<Attribute>& attributes)
+ : ElementData(attributes.size())
+{
+ for (unsigned i = 0; i < m_arraySize; ++i)
+ new (&m_attributeArray[i]) Attribute(attributes[i]);
+}
+
+ShareableElementData::~ShareableElementData()
+{
+ for (unsigned i = 0; i < m_arraySize; ++i)
+ m_attributeArray[i].~Attribute();
+}
+
+ShareableElementData::ShareableElementData(const UniqueElementData& other)
+ : ElementData(other, false)
+{
+ ASSERT(!other.m_presentationAttributeStyle);
+
+ if (other.m_inlineStyle) {
+ ASSERT(!other.m_inlineStyle->hasCSSOMWrapper());
+ m_inlineStyle = other.m_inlineStyle->immutableCopyIfNeeded();
+ }
+
+ for (unsigned i = 0; i < m_arraySize; ++i)
+ new (&m_attributeArray[i]) Attribute(other.m_attributeVector.at(i));
+}
+
+PassRefPtr<ShareableElementData> ShareableElementData::createWithAttributes(const Vector<Attribute>& attributes)
+{
+ void* slot = WTF::fastMalloc(sizeForShareableElementDataWithAttributeCount(attributes.size()));
+ return adoptRef(new (slot) ShareableElementData(attributes));
+}
+
+UniqueElementData::UniqueElementData()
+{
+}
+
+UniqueElementData::UniqueElementData(const UniqueElementData& other)
+ : ElementData(other, true)
+ , m_presentationAttributeStyle(other.m_presentationAttributeStyle)
+ , m_attributeVector(other.m_attributeVector)
+{
+ m_inlineStyle = other.m_inlineStyle ? other.m_inlineStyle->mutableCopy() : 0;
+}
+
+UniqueElementData::UniqueElementData(const ShareableElementData& other)
+ : ElementData(other, true)
+{
+ // An ShareableElementData should never have a mutable inline StylePropertySet attached.
+ ASSERT(!other.m_inlineStyle || !other.m_inlineStyle->isMutable());
+ m_inlineStyle = other.m_inlineStyle;
+
+ m_attributeVector.reserveCapacity(other.length());
+ for (unsigned i = 0; i < other.length(); ++i)
+ m_attributeVector.uncheckedAppend(other.m_attributeArray[i]);
+}
+
+PassRefPtr<UniqueElementData> UniqueElementData::create()
+{
+ return adoptRef(new UniqueElementData);
+}
+
+PassRefPtr<ShareableElementData> UniqueElementData::makeShareableCopy() const
+{
+ void* slot = WTF::fastMalloc(sizeForShareableElementDataWithAttributeCount(m_attributeVector.size()));
+ return adoptRef(new (slot) ShareableElementData(*this));
+}
+
+Attribute* UniqueElementData::getAttributeItem(const QualifiedName& name)
+{
+ for (unsigned i = 0; i < length(); ++i) {
+ if (m_attributeVector.at(i).name().matches(name))
+ return &m_attributeVector.at(i);
+ }
+ return 0;
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/ElementData.h b/chromium/third_party/WebKit/Source/core/dom/ElementData.h
new file mode 100644
index 00000000000..2426667d6c2
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/ElementData.h
@@ -0,0 +1,259 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef ElementData_h
+#define ElementData_h
+
+#include "core/dom/Attribute.h"
+#include "core/dom/SpaceSplitString.h"
+#include "wtf/text/AtomicString.h"
+
+namespace WebCore {
+
+class Attr;
+class ShareableElementData;
+class StylePropertySet;
+class UniqueElementData;
+
+class ElementData : public RefCounted<ElementData> {
+ WTF_MAKE_FAST_ALLOCATED;
+public:
+ // Override RefCounted's deref() to ensure operator delete is called on
+ // the appropriate subclass type.
+ void deref();
+
+ void clearClass() const { m_classNames.clear(); }
+ void setClass(const AtomicString& className, bool shouldFoldCase) const { m_classNames.set(className, shouldFoldCase); }
+ const SpaceSplitString& classNames() const { return m_classNames; }
+
+ const AtomicString& idForStyleResolution() const { return m_idForStyleResolution; }
+ void setIdForStyleResolution(const AtomicString& newId) const { m_idForStyleResolution = newId; }
+
+ const StylePropertySet* inlineStyle() const { return m_inlineStyle.get(); }
+
+ const StylePropertySet* presentationAttributeStyle() const;
+
+ size_t length() const;
+ bool isEmpty() const { return !length(); }
+
+ const Attribute* attributeItem(unsigned index) const;
+ const Attribute* getAttributeItem(const QualifiedName&) const;
+ size_t getAttributeItemIndex(const QualifiedName&, bool shouldIgnoreCase = false) const;
+ size_t getAttributeItemIndex(const AtomicString& name, bool shouldIgnoreAttributeCase) const;
+ size_t getAttrIndex(Attr*) const;
+
+ bool hasID() const { return !m_idForStyleResolution.isNull(); }
+ bool hasClass() const { return !m_classNames.isNull(); }
+
+ bool isEquivalent(const ElementData* other) const;
+
+ bool isUnique() const { return m_isUnique; }
+
+protected:
+ ElementData();
+ explicit ElementData(unsigned arraySize);
+ ElementData(const ElementData&, bool isUnique);
+
+ unsigned m_isUnique : 1;
+ unsigned m_arraySize : 28;
+ mutable unsigned m_presentationAttributeStyleIsDirty : 1;
+ mutable unsigned m_styleAttributeIsDirty : 1;
+ mutable unsigned m_animatedSVGAttributesAreDirty : 1;
+
+ mutable RefPtr<StylePropertySet> m_inlineStyle;
+ mutable SpaceSplitString m_classNames;
+ mutable AtomicString m_idForStyleResolution;
+
+private:
+ friend class Element;
+ friend class ShareableElementData;
+ friend class UniqueElementData;
+ friend class SVGElement;
+
+ void destroy();
+
+ const Attribute* attributeBase() const;
+ const Attribute* getAttributeItem(const AtomicString& name, bool shouldIgnoreAttributeCase) const;
+ size_t getAttributeItemIndexSlowCase(const AtomicString& name, bool shouldIgnoreAttributeCase) const;
+
+ PassRefPtr<UniqueElementData> makeUniqueCopy() const;
+};
+
+#if COMPILER(MSVC)
+#pragma warning(push)
+#pragma warning(disable: 4200) // Disable "zero-sized array in struct/union" warning
+#endif
+
+class ShareableElementData : public ElementData {
+public:
+ static PassRefPtr<ShareableElementData> createWithAttributes(const Vector<Attribute>&);
+
+ explicit ShareableElementData(const Vector<Attribute>&);
+ explicit ShareableElementData(const UniqueElementData&);
+ ~ShareableElementData();
+
+ Attribute m_attributeArray[0];
+};
+
+#if COMPILER(MSVC)
+#pragma warning(pop)
+#endif
+
+class UniqueElementData : public ElementData {
+public:
+ static PassRefPtr<UniqueElementData> create();
+ PassRefPtr<ShareableElementData> makeShareableCopy() const;
+
+ // These functions do no error/duplicate checking.
+ void addAttribute(const QualifiedName&, const AtomicString&);
+ void removeAttribute(size_t index);
+
+ Attribute* attributeItem(unsigned index);
+ Attribute* getAttributeItem(const QualifiedName&);
+
+ UniqueElementData();
+ explicit UniqueElementData(const ShareableElementData&);
+ explicit UniqueElementData(const UniqueElementData&);
+
+ mutable RefPtr<StylePropertySet> m_presentationAttributeStyle;
+ Vector<Attribute, 4> m_attributeVector;
+};
+
+inline void ElementData::deref()
+{
+ if (!derefBase())
+ return;
+ destroy();
+}
+
+inline size_t ElementData::length() const
+{
+ if (isUnique())
+ return static_cast<const UniqueElementData*>(this)->m_attributeVector.size();
+ return m_arraySize;
+}
+
+inline const StylePropertySet* ElementData::presentationAttributeStyle() const
+{
+ if (!m_isUnique)
+ return 0;
+ return static_cast<const UniqueElementData*>(this)->m_presentationAttributeStyle.get();
+}
+
+inline const Attribute* ElementData::getAttributeItem(const AtomicString& name, bool shouldIgnoreAttributeCase) const
+{
+ size_t index = getAttributeItemIndex(name, shouldIgnoreAttributeCase);
+ if (index != kNotFound)
+ return attributeItem(index);
+ return 0;
+}
+
+inline const Attribute* ElementData::attributeBase() const
+{
+ if (m_isUnique)
+ return static_cast<const UniqueElementData*>(this)->m_attributeVector.begin();
+ return static_cast<const ShareableElementData*>(this)->m_attributeArray;
+}
+
+inline size_t ElementData::getAttributeItemIndex(const QualifiedName& name, bool shouldIgnoreCase) const
+{
+ const Attribute* begin = attributeBase();
+ // Cache length for performance as ElementData::length() contains a conditional branch.
+ unsigned len = length();
+ for (unsigned i = 0; i < len; ++i) {
+ const Attribute& attribute = begin[i];
+ if (attribute.name().matchesPossiblyIgnoringCase(name, shouldIgnoreCase))
+ return i;
+ }
+ return kNotFound;
+}
+
+// We use a boolean parameter instead of calling shouldIgnoreAttributeCase so that the caller
+// can tune the behavior (hasAttribute is case sensitive whereas getAttribute is not).
+inline size_t ElementData::getAttributeItemIndex(const AtomicString& name, bool shouldIgnoreAttributeCase) const
+{
+ // Cache length for performance as ElementData::length() contains a conditional branch.
+ unsigned len = length();
+ bool doSlowCheck = shouldIgnoreAttributeCase;
+
+ // Optimize for the case where the attribute exists and its name exactly matches.
+ const Attribute* begin = attributeBase();
+ for (unsigned i = 0; i < len; ++i) {
+ const Attribute& attribute = begin[i];
+ // FIXME: Why check the prefix? Namespaces should be all that matter.
+ // Most attributes (all of HTML and CSS) have no namespace.
+ if (!attribute.name().hasPrefix()) {
+ if (name == attribute.localName())
+ return i;
+ } else {
+ doSlowCheck = true;
+ }
+ }
+
+ if (doSlowCheck)
+ return getAttributeItemIndexSlowCase(name, shouldIgnoreAttributeCase);
+ return kNotFound;
+}
+
+inline const Attribute* ElementData::getAttributeItem(const QualifiedName& name) const
+{
+ const Attribute* begin = attributeBase();
+ for (unsigned i = 0; i < length(); ++i) {
+ const Attribute& attribute = begin[i];
+ if (attribute.name().matches(name))
+ return &attribute;
+ }
+ return 0;
+}
+
+inline const Attribute* ElementData::attributeItem(unsigned index) const
+{
+ RELEASE_ASSERT(index < length());
+ return attributeBase() + index;
+}
+
+inline void UniqueElementData::addAttribute(const QualifiedName& attributeName, const AtomicString& value)
+{
+ m_attributeVector.append(Attribute(attributeName, value));
+}
+
+inline void UniqueElementData::removeAttribute(size_t index)
+{
+ m_attributeVector.remove(index);
+}
+
+inline Attribute* UniqueElementData::attributeItem(unsigned index)
+{
+ return &m_attributeVector.at(index);
+}
+
+} // namespace WebCore
+
+#endif // ElementData_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/ElementRareData.h b/chromium/third_party/WebKit/Source/core/dom/ElementRareData.h
index f48368145f4..a1879973aa5 100644
--- a/chromium/third_party/WebKit/Source/core/dom/ElementRareData.h
+++ b/chromium/third_party/WebKit/Source/core/dom/ElementRareData.h
@@ -30,7 +30,6 @@
#include "core/dom/shadow/ElementShadow.h"
#include "core/html/ClassList.h"
#include "core/html/ime/InputMethodContext.h"
-#include "core/inspector/InspectorInstrumentation.h"
#include "core/rendering/style/StyleInheritedData.h"
#include "wtf/OwnPtr.h"
@@ -76,6 +75,8 @@ public:
bool isInTopLayer() const { return m_isInTopLayer; }
void setIsInTopLayer(bool value) { m_isInTopLayer = value; }
+ bool childrenAffectedByFocus() const { return m_childrenAffectedByFocus; }
+ void setChildrenAffectedByFocus(bool value) { m_childrenAffectedByFocus = value; }
bool childrenAffectedByHover() const { return m_childrenAffectedByHover; }
void setChildrenAffectedByHover(bool value) { m_childrenAffectedByHover = value; }
bool childrenAffectedByActive() const { return m_childrenAffectedByActive; }
@@ -98,11 +99,11 @@ public:
void clearShadow() { m_shadow = nullptr; }
ElementShadow* shadow() const { return m_shadow.get(); }
- ElementShadow* ensureShadow()
+ ElementShadow& ensureShadow()
{
if (!m_shadow)
m_shadow = ElementShadow::create();
- return m_shadow.get();
+ return *m_shadow;
}
NamedNodeMap* attributeMap() const { return m_attributeMap.get(); }
@@ -139,6 +140,7 @@ public:
bool hasPendingResources() const { return m_hasPendingResources; }
void setHasPendingResources(bool has) { m_hasPendingResources = has; }
+ bool hasInputMethodContext() const { return m_inputMethodContext; }
InputMethodContext* ensureInputMethodContext(HTMLElement* element)
{
if (!m_inputMethodContext)
@@ -146,6 +148,8 @@ public:
return m_inputMethodContext.get();
}
+ bool hasPseudoElements() const;
+
private:
short m_tabIndex;
unsigned short m_childIndex;
@@ -156,6 +160,7 @@ private:
unsigned m_containsFullScreenElement : 1;
unsigned m_isInTopLayer : 1;
unsigned m_hasPendingResources : 1;
+ unsigned m_childrenAffectedByFocus : 1;
unsigned m_childrenAffectedByHover : 1;
unsigned m_childrenAffectedByActive : 1;
unsigned m_childrenAffectedByDrag : 1;
@@ -187,7 +192,6 @@ private:
RefPtr<PseudoElement> m_backdrop;
ElementRareData(RenderObject*);
- void releasePseudoElement(PseudoElement*);
};
inline IntSize defaultMinimumSizeForResizing()
@@ -206,6 +210,7 @@ inline ElementRareData::ElementRareData(RenderObject* renderer)
, m_containsFullScreenElement(false)
, m_isInTopLayer(false)
, m_hasPendingResources(false)
+ , m_childrenAffectedByFocus(false)
, m_childrenAffectedByHover(false)
, m_childrenAffectedByActive(false)
, m_childrenAffectedByDrag(false)
@@ -228,26 +233,32 @@ inline ElementRareData::~ElementRareData()
ASSERT(!m_backdrop);
}
-inline void ElementRareData::setPseudoElement(PseudoId pseudoId, PassRefPtr<PseudoElement> prpElement)
+inline bool ElementRareData::hasPseudoElements() const
+{
+ return m_generatedBefore || m_generatedAfter || m_backdrop;
+}
+
+inline void ElementRareData::setPseudoElement(PseudoId pseudoId, PassRefPtr<PseudoElement> element)
{
- RefPtr<PseudoElement> element = prpElement;
switch (pseudoId) {
case BEFORE:
- releasePseudoElement(m_generatedBefore.get());
+ if (m_generatedBefore)
+ m_generatedBefore->dispose();
m_generatedBefore = element;
break;
case AFTER:
- releasePseudoElement(m_generatedAfter.get());
+ if (m_generatedAfter)
+ m_generatedAfter->dispose();
m_generatedAfter = element;
break;
case BACKDROP:
- releasePseudoElement(m_backdrop.get());
+ if (m_backdrop)
+ m_backdrop->dispose();
m_backdrop = element;
break;
default:
ASSERT_NOT_REACHED();
}
- InspectorInstrumentation::pseudoElementCreated(element.get());
}
inline PseudoElement* ElementRareData::pseudoElement(PseudoId pseudoId) const
@@ -264,32 +275,15 @@ inline PseudoElement* ElementRareData::pseudoElement(PseudoId pseudoId) const
}
}
-inline void ElementRareData::releasePseudoElement(PseudoElement* element)
-{
- if (!element)
- return;
-
- InspectorInstrumentation::pseudoElementDestroyed(element);
-
- if (element->attached())
- element->detach();
-
- ASSERT(!element->nextSibling());
- ASSERT(!element->previousSibling());
-
- element->document().removeFromTopLayer(element);
- element->setParentOrShadowHostNode(0);
-}
-
inline void ElementRareData::resetStyleState()
{
- setComputedStyle(0);
setStyleAffectedByEmpty(false);
setChildIndex(0);
}
inline void ElementRareData::resetDynamicRestyleObservations()
{
+ setChildrenAffectedByFocus(false);
setChildrenAffectedByHover(false);
setChildrenAffectedByActive(false);
setChildrenAffectedByDrag(false);
diff --git a/chromium/third_party/WebKit/Source/core/dom/ElementTraversal.h b/chromium/third_party/WebKit/Source/core/dom/ElementTraversal.h
index 027873290da..274725d57ee 100644
--- a/chromium/third_party/WebKit/Source/core/dom/ElementTraversal.h
+++ b/chromium/third_party/WebKit/Source/core/dom/ElementTraversal.h
@@ -33,112 +33,112 @@ namespace WebCore {
namespace ElementTraversal {
// First element child of the node.
-Element* firstWithin(const Node*);
-Element* firstWithin(const ContainerNode*);
+Element* firstWithin(const Node&);
+Element* firstWithin(const ContainerNode&);
// Pre-order traversal skipping non-element nodes.
-Element* next(const Node*);
-Element* next(const Node*, const Node* stayWithin);
-Element* next(const ContainerNode*);
-Element* next(const ContainerNode*, const Node* stayWithin);
+Element* next(const Node&);
+Element* next(const Node&, const Node* stayWithin);
+Element* next(const ContainerNode&);
+Element* next(const ContainerNode&, const Node* stayWithin);
// Like next, but skips children.
-Element* nextSkippingChildren(const Node*);
-Element* nextSkippingChildren(const Node*, const Node* stayWithin);
-Element* nextSkippingChildren(const ContainerNode*);
-Element* nextSkippingChildren(const ContainerNode*, const Node* stayWithin);
+Element* nextSkippingChildren(const Node&);
+Element* nextSkippingChildren(const Node&, const Node* stayWithin);
+Element* nextSkippingChildren(const ContainerNode&);
+Element* nextSkippingChildren(const ContainerNode&, const Node* stayWithin);
// Pre-order traversal including the pseudo-elements.
-Element* previousIncludingPseudo(const Node*, const Node* stayWithin = 0);
-Element* nextIncludingPseudo(const Node*, const Node* stayWithin = 0);
-Element* nextIncludingPseudoSkippingChildren(const Node*, const Node* stayWithin = 0);
+Element* previousIncludingPseudo(const Node&, const Node* stayWithin = 0);
+Element* nextIncludingPseudo(const Node&, const Node* stayWithin = 0);
+Element* nextIncludingPseudoSkippingChildren(const Node&, const Node* stayWithin = 0);
// Utility function to traverse only the element and pseudo-element siblings of a node.
-Element* pseudoAwarePreviousSibling(const Node*);
+Element* pseudoAwarePreviousSibling(const Node&);
template <class NodeType>
-inline Element* firstElementWithinTemplate(NodeType* current)
+inline Element* firstElementWithinTemplate(NodeType& current)
{
// Except for the root containers, only elements can have element children.
- Node* node = current->firstChild();
+ Node* node = current.firstChild();
while (node && !node->isElementNode())
node = node->nextSibling();
return toElement(node);
}
-inline Element* firstWithin(const ContainerNode* current) { return firstElementWithinTemplate(current); }
-inline Element* firstWithin(const Node* current) { return firstElementWithinTemplate(current); }
+inline Element* firstWithin(const ContainerNode& current) { return firstElementWithinTemplate(current); }
+inline Element* firstWithin(const Node& current) { return firstElementWithinTemplate(current); }
template <class NodeType>
-inline Element* traverseNextElementTemplate(NodeType* current)
+inline Element* traverseNextElementTemplate(NodeType& current)
{
Node* node = NodeTraversal::next(current);
while (node && !node->isElementNode())
- node = NodeTraversal::nextSkippingChildren(node);
+ node = NodeTraversal::nextSkippingChildren(*node);
return toElement(node);
}
-inline Element* next(const ContainerNode* current) { return traverseNextElementTemplate(current); }
-inline Element* next(const Node* current) { return traverseNextElementTemplate(current); }
+inline Element* next(const ContainerNode& current) { return traverseNextElementTemplate(current); }
+inline Element* next(const Node& current) { return traverseNextElementTemplate(current); }
template <class NodeType>
-inline Element* traverseNextElementTemplate(NodeType* current, const Node* stayWithin)
+inline Element* traverseNextElementTemplate(NodeType& current, const Node* stayWithin)
{
Node* node = NodeTraversal::next(current, stayWithin);
while (node && !node->isElementNode())
- node = NodeTraversal::nextSkippingChildren(node, stayWithin);
+ node = NodeTraversal::nextSkippingChildren(*node, stayWithin);
return toElement(node);
}
-inline Element* next(const ContainerNode* current, const Node* stayWithin) { return traverseNextElementTemplate(current, stayWithin); }
-inline Element* next(const Node* current, const Node* stayWithin) { return traverseNextElementTemplate(current, stayWithin); }
+inline Element* next(const ContainerNode& current, const Node* stayWithin) { return traverseNextElementTemplate(current, stayWithin); }
+inline Element* next(const Node& current, const Node* stayWithin) { return traverseNextElementTemplate(current, stayWithin); }
template <class NodeType>
-inline Element* traverseNextElementSkippingChildrenTemplate(NodeType* current)
+inline Element* traverseNextElementSkippingChildrenTemplate(NodeType& current)
{
Node* node = NodeTraversal::nextSkippingChildren(current);
while (node && !node->isElementNode())
- node = NodeTraversal::nextSkippingChildren(node);
+ node = NodeTraversal::nextSkippingChildren(*node);
return toElement(node);
}
-inline Element* nextSkippingChildren(const ContainerNode* current) { return traverseNextElementSkippingChildrenTemplate(current); }
-inline Element* nextSkippingChildren(const Node* current) { return traverseNextElementSkippingChildrenTemplate(current); }
+inline Element* nextSkippingChildren(const ContainerNode& current) { return traverseNextElementSkippingChildrenTemplate(current); }
+inline Element* nextSkippingChildren(const Node& current) { return traverseNextElementSkippingChildrenTemplate(current); }
template <class NodeType>
-inline Element* traverseNextElementSkippingChildrenTemplate(NodeType* current, const Node* stayWithin)
+inline Element* traverseNextElementSkippingChildrenTemplate(NodeType& current, const Node* stayWithin)
{
Node* node = NodeTraversal::nextSkippingChildren(current, stayWithin);
while (node && !node->isElementNode())
- node = NodeTraversal::nextSkippingChildren(node, stayWithin);
+ node = NodeTraversal::nextSkippingChildren(*node, stayWithin);
return toElement(node);
}
-inline Element* nextSkippingChildren(const ContainerNode* current, const Node* stayWithin) { return traverseNextElementSkippingChildrenTemplate(current, stayWithin); }
-inline Element* nextSkippingChildren(const Node* current, const Node* stayWithin) { return traverseNextElementSkippingChildrenTemplate(current, stayWithin); }
+inline Element* nextSkippingChildren(const ContainerNode& current, const Node* stayWithin) { return traverseNextElementSkippingChildrenTemplate(current, stayWithin); }
+inline Element* nextSkippingChildren(const Node& current, const Node* stayWithin) { return traverseNextElementSkippingChildrenTemplate(current, stayWithin); }
-inline Element* previousIncludingPseudo(const Node* current, const Node* stayWithin)
+inline Element* previousIncludingPseudo(const Node& current, const Node* stayWithin)
{
Node* node = NodeTraversal::previousIncludingPseudo(current, stayWithin);
while (node && !node->isElementNode())
- node = NodeTraversal::previousIncludingPseudo(node, stayWithin);
+ node = NodeTraversal::previousIncludingPseudo(*node, stayWithin);
return toElement(node);
}
-inline Element* nextIncludingPseudo(const Node* current, const Node* stayWithin)
+inline Element* nextIncludingPseudo(const Node& current, const Node* stayWithin)
{
Node* node = NodeTraversal::nextIncludingPseudo(current, stayWithin);
while (node && !node->isElementNode())
- node = NodeTraversal::nextIncludingPseudo(node, stayWithin);
+ node = NodeTraversal::nextIncludingPseudo(*node, stayWithin);
return toElement(node);
}
-inline Element* nextIncludingPseudoSkippingChildren(const Node* current, const Node* stayWithin)
+inline Element* nextIncludingPseudoSkippingChildren(const Node& current, const Node* stayWithin)
{
Node* node = NodeTraversal::nextIncludingPseudoSkippingChildren(current, stayWithin);
while (node && !node->isElementNode())
- node = NodeTraversal::nextIncludingPseudoSkippingChildren(node, stayWithin);
+ node = NodeTraversal::nextIncludingPseudoSkippingChildren(*node, stayWithin);
return toElement(node);
}
-inline Element* pseudoAwarePreviousSibling(const Node* current)
+inline Element* pseudoAwarePreviousSibling(const Node& current)
{
- Node* node = current->pseudoAwarePreviousSibling();
+ Node* node = current.pseudoAwarePreviousSibling();
while (node && !node->isElementNode())
node = node->pseudoAwarePreviousSibling();
return toElement(node);
diff --git a/chromium/third_party/WebKit/Source/core/dom/Entity.h b/chromium/third_party/WebKit/Source/core/dom/Entity.h
index ee46c2c7bdf..e1a7a002513 100644
--- a/chromium/third_party/WebKit/Source/core/dom/Entity.h
+++ b/chromium/third_party/WebKit/Source/core/dom/Entity.h
@@ -28,11 +28,7 @@ namespace WebCore {
class Entity : public ContainerNode {
private:
- Entity() : ContainerNode(0)
- {
- ASSERT_NOT_REACHED();
- ScriptWrappable::init(this);
- }
+ Entity(); // Left unimplemented on purpose.
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/ErrorEvent.cpp b/chromium/third_party/WebKit/Source/core/dom/ErrorEvent.cpp
deleted file mode 100644
index dc15aecb3a8..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/ErrorEvent.cpp
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
- * Copyright (C) 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/dom/ErrorEvent.h"
-
-#include "core/dom/EventNames.h"
-
-namespace WebCore {
-
-ErrorEventInit::ErrorEventInit()
- : message()
- , filename()
- , lineno(0)
- , colno(0)
-{
-}
-
-ErrorEvent::ErrorEvent()
-{
- ScriptWrappable::init(this);
-}
-
-ErrorEvent::ErrorEvent(const AtomicString& type, const ErrorEventInit& initializer)
- : Event(type, initializer)
- , m_sanitizedMessage(initializer.message)
- , m_fileName(initializer.filename)
- , m_lineNumber(initializer.lineno)
- , m_columnNumber(initializer.colno)
- , m_world(DOMWrapperWorld::current())
-{
- ScriptWrappable::init(this);
-}
-
-ErrorEvent::ErrorEvent(const String& message, const String& fileName, unsigned lineNumber, unsigned columnNumber, PassRefPtr<DOMWrapperWorld> world)
- : Event(eventNames().errorEvent, false, true)
- , m_sanitizedMessage(message)
- , m_fileName(fileName)
- , m_lineNumber(lineNumber)
- , m_columnNumber(columnNumber)
- , m_world(world)
-{
- ScriptWrappable::init(this);
-}
-
-void ErrorEvent::setUnsanitizedMessage(const String& message)
-{
- ASSERT(m_unsanitizedMessage.isEmpty());
- m_unsanitizedMessage = message;
-}
-
-ErrorEvent::~ErrorEvent()
-{
-}
-
-const AtomicString& ErrorEvent::interfaceName() const
-{
- return eventNames().interfaceForErrorEvent;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/ErrorEvent.h b/chromium/third_party/WebKit/Source/core/dom/ErrorEvent.h
deleted file mode 100644
index 34b8a42497e..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/ErrorEvent.h
+++ /dev/null
@@ -1,101 +0,0 @@
-/*
- * Copyright (C) 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ErrorEvent_h
-#define ErrorEvent_h
-
-#include "bindings/v8/DOMWrapperWorld.h"
-#include "core/dom/Event.h"
-#include "wtf/RefPtr.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-struct ErrorEventInit : public EventInit {
- ErrorEventInit();
-
- String message;
- String filename;
- unsigned lineno;
- unsigned colno;
-};
-
-class ErrorEvent : public Event {
-public:
- static PassRefPtr<ErrorEvent> create()
- {
- return adoptRef(new ErrorEvent);
- }
- static PassRefPtr<ErrorEvent> create(const String& message, const String& fileName, unsigned lineNumber, unsigned columnNumber, PassRefPtr<DOMWrapperWorld> world)
- {
- return adoptRef(new ErrorEvent(message, fileName, lineNumber, columnNumber, world));
- }
- static PassRefPtr<ErrorEvent> create(const AtomicString& type, const ErrorEventInit& initializer)
- {
- return adoptRef(new ErrorEvent(type, initializer));
- }
- static PassRefPtr<ErrorEvent> createSanitizedError(PassRefPtr<DOMWrapperWorld> world)
- {
- return adoptRef(new ErrorEvent("Script error.", String(), 0, 0, world));
- }
- virtual ~ErrorEvent();
-
- // As 'message' is exposed to JavaScript, never return unsanitizedMessage.
- const String& message() const { return m_sanitizedMessage; }
- const String& filename() const { return m_fileName; }
- unsigned lineno() const { return m_lineNumber; }
- unsigned colno() const { return m_columnNumber; }
-
- // 'messageForConsole' is not exposed to JavaScript, and prefers 'm_unsanitizedMessage'.
- const String& messageForConsole() const { return !m_unsanitizedMessage.isEmpty() ? m_unsanitizedMessage : m_sanitizedMessage; }
-
- virtual const AtomicString& interfaceName() const;
-
- PassRefPtr<DOMWrapperWorld> world() const { return m_world; }
-
- void setUnsanitizedMessage(const String&);
-
-private:
- ErrorEvent();
- ErrorEvent(const String& message, const String& fileName, unsigned lineNumber, unsigned columnNumber, PassRefPtr<DOMWrapperWorld>);
- ErrorEvent(const AtomicString&, const ErrorEventInit&);
-
- String m_unsanitizedMessage;
- String m_sanitizedMessage;
- String m_fileName;
- unsigned m_lineNumber;
- unsigned m_columnNumber;
-
- RefPtr<DOMWrapperWorld> m_world;
-};
-
-} // namespace WebCore
-
-#endif // ErrorEvent_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/ErrorEvent.idl b/chromium/third_party/WebKit/Source/core/dom/ErrorEvent.idl
deleted file mode 100644
index 33f02390d8d..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/ErrorEvent.idl
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright (C) 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-[
- ConstructorTemplate=Event
-] interface ErrorEvent : Event {
- [InitializedByEventConstructor] readonly attribute DOMString message;
- [InitializedByEventConstructor] readonly attribute DOMString filename;
- [InitializedByEventConstructor] readonly attribute unsigned long lineno;
- [InitializedByEventConstructor] readonly attribute unsigned long colno;
- [InitializedByEventConstructor, Custom, Unserializable] readonly attribute any error;
-};
-
diff --git a/chromium/third_party/WebKit/Source/core/dom/Event.cpp b/chromium/third_party/WebKit/Source/core/dom/Event.cpp
deleted file mode 100644
index b41e6ba41b3..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/Event.cpp
+++ /dev/null
@@ -1,204 +0,0 @@
-/*
- * Copyright (C) 2001 Peter Kelly (pmk@post.com)
- * Copyright (C) 2001 Tobias Anton (anton@stud.fbi.fh-darmstadt.de)
- * Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
- * Copyright (C) 2003, 2005, 2006, 2008 Apple Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-#include "core/dom/Event.h"
-
-#include "core/dom/EventNames.h"
-#include "core/dom/EventTarget.h"
-#include "core/dom/StaticNodeList.h"
-#include "wtf/CurrentTime.h"
-#include "wtf/text/AtomicString.h"
-
-namespace WebCore {
-
-EventInit::EventInit()
- : bubbles(false)
- , cancelable(false)
-{
-}
-
-
-Event::Event()
- : m_canBubble(false)
- , m_cancelable(false)
- , m_propagationStopped(false)
- , m_immediatePropagationStopped(false)
- , m_defaultPrevented(false)
- , m_defaultHandled(false)
- , m_cancelBubble(false)
- , m_eventPhase(0)
- , m_currentTarget(0)
- , m_createTime(convertSecondsToDOMTimeStamp(currentTime()))
-{
- ScriptWrappable::init(this);
-}
-
-Event::Event(const AtomicString& eventType, bool canBubbleArg, bool cancelableArg)
- : m_type(eventType)
- , m_canBubble(canBubbleArg)
- , m_cancelable(cancelableArg)
- , m_propagationStopped(false)
- , m_immediatePropagationStopped(false)
- , m_defaultPrevented(false)
- , m_defaultHandled(false)
- , m_cancelBubble(false)
- , m_eventPhase(0)
- , m_currentTarget(0)
- , m_createTime(convertSecondsToDOMTimeStamp(currentTime()))
-{
- ScriptWrappable::init(this);
-}
-
-Event::Event(const AtomicString& eventType, const EventInit& initializer)
- : m_type(eventType)
- , m_canBubble(initializer.bubbles)
- , m_cancelable(initializer.cancelable)
- , m_propagationStopped(false)
- , m_immediatePropagationStopped(false)
- , m_defaultPrevented(false)
- , m_defaultHandled(false)
- , m_cancelBubble(false)
- , m_eventPhase(0)
- , m_currentTarget(0)
- , m_createTime(convertSecondsToDOMTimeStamp(currentTime()))
-{
- ScriptWrappable::init(this);
-}
-
-Event::~Event()
-{
-}
-
-void Event::initEvent(const AtomicString& eventTypeArg, bool canBubbleArg, bool cancelableArg)
-{
- if (dispatched())
- return;
-
- m_propagationStopped = false;
- m_immediatePropagationStopped = false;
- m_defaultPrevented = false;
-
- m_type = eventTypeArg;
- m_canBubble = canBubbleArg;
- m_cancelable = cancelableArg;
-}
-
-const AtomicString& Event::interfaceName() const
-{
- return eventNames().interfaceForEvent;
-}
-
-bool Event::hasInterface(const AtomicString& name) const
-{
- return interfaceName() == name;
-}
-
-bool Event::isUIEvent() const
-{
- return false;
-}
-
-bool Event::isMouseEvent() const
-{
- return false;
-}
-
-bool Event::isFocusEvent() const
-{
- return false;
-}
-
-bool Event::isKeyboardEvent() const
-{
- return false;
-}
-
-bool Event::isTouchEvent() const
-{
- return false;
-}
-
-bool Event::isGestureEvent() const
-{
- return false;
-}
-
-bool Event::isDragEvent() const
-{
- return false;
-}
-
-bool Event::isClipboardEvent() const
-{
- return false;
-}
-
-bool Event::isBeforeTextInsertedEvent() const
-{
- return false;
-}
-
-bool Event::isBeforeUnloadEvent() const
-{
- return false;
-}
-
-void Event::setTarget(PassRefPtr<EventTarget> target)
-{
- if (m_target == target)
- return;
-
- m_target = target;
- if (m_target)
- receivedTarget();
-}
-
-void Event::receivedTarget()
-{
-}
-
-void Event::setUnderlyingEvent(PassRefPtr<Event> ue)
-{
- // Prohibit creation of a cycle -- just do nothing in that case.
- for (Event* e = ue.get(); e; e = e->underlyingEvent())
- if (e == this)
- return;
- m_underlyingEvent = ue;
-}
-
-PassRefPtr<NodeList> Event::path() const
-{
- if (!m_currentTarget || !m_currentTarget->toNode())
- return StaticNodeList::createEmpty();
- Node* node = m_currentTarget->toNode();
- size_t eventPathSize = m_eventPath.size();
- for (size_t i = 0; i < eventPathSize; ++i) {
- if (node == m_eventPath[i]->node()) {
- ASSERT(m_eventPath[i]->eventPath());
- return m_eventPath[i]->eventPath();
- }
- }
- return StaticNodeList::createEmpty();
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/Event.h b/chromium/third_party/WebKit/Source/core/dom/Event.h
deleted file mode 100644
index 1ede2694007..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/Event.h
+++ /dev/null
@@ -1,212 +0,0 @@
-/*
- * Copyright (C) 2001 Peter Kelly (pmk@post.com)
- * Copyright (C) 2001 Tobias Anton (anton@stud.fbi.fh-darmstadt.de)
- * Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
- * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#ifndef Event_h
-#define Event_h
-
-#include "bindings/v8/ScriptWrappable.h"
-#include "core/dom/DOMTimeStamp.h"
-#include "core/dom/EventContext.h"
-#include "wtf/RefCounted.h"
-#include "wtf/text/AtomicString.h"
-
-namespace WebCore {
-
-class Clipboard;
-class EventTarget;
-class EventDispatcher;
-class HTMLIFrameElement;
-
-struct EventInit {
- EventInit();
-
- bool bubbles;
- bool cancelable;
-};
-
-class Event : public ScriptWrappable, public RefCounted<Event> {
-public:
- enum PhaseType {
- NONE = 0,
- CAPTURING_PHASE = 1,
- AT_TARGET = 2,
- BUBBLING_PHASE = 3
- };
-
- enum EventType {
- MOUSEDOWN = 1,
- MOUSEUP = 2,
- MOUSEOVER = 4,
- MOUSEOUT = 8,
- MOUSEMOVE = 16,
- MOUSEDRAG = 32,
- CLICK = 64,
- DBLCLICK = 128,
- KEYDOWN = 256,
- KEYUP = 512,
- KEYPRESS = 1024,
- DRAGDROP = 2048,
- FOCUS = 4096,
- BLUR = 8192,
- SELECT = 16384,
- CHANGE = 32768
- };
-
- static PassRefPtr<Event> create()
- {
- return adoptRef(new Event);
- }
-
- // A factory for a simple event. The event doesn't bubble, and isn't
- // cancelable.
- // http://www.whatwg.org/specs/web-apps/current-work/multipage/webappapis.html#fire-a-simple-event
- static PassRefPtr<Event> create(const AtomicString& type)
- {
- return adoptRef(new Event(type, false, false));
- }
- static PassRefPtr<Event> createCancelable(const AtomicString& type)
- {
- return adoptRef(new Event(type, false, true));
- }
- static PassRefPtr<Event> createBubble(const AtomicString& type)
- {
- return adoptRef(new Event(type, true, false));
- }
- static PassRefPtr<Event> createCancelableBubble(const AtomicString& type)
- {
- return adoptRef(new Event(type, true, true));
- }
-
- static PassRefPtr<Event> create(const AtomicString& type, const EventInit& initializer)
- {
- return adoptRef(new Event(type, initializer));
- }
-
- virtual ~Event();
-
- void initEvent(const AtomicString& type, bool canBubble, bool cancelable);
-
- const AtomicString& type() const { return m_type; }
- void setType(const AtomicString& type) { m_type = type; }
-
- EventTarget* target() const { return m_target.get(); }
- void setTarget(PassRefPtr<EventTarget>);
-
- EventTarget* currentTarget() const { return m_currentTarget; }
- void setCurrentTarget(EventTarget* currentTarget) { m_currentTarget = currentTarget; }
-
- unsigned short eventPhase() const { return m_eventPhase; }
- void setEventPhase(unsigned short eventPhase) { m_eventPhase = eventPhase; }
-
- bool bubbles() const { return m_canBubble; }
- bool cancelable() const { return m_cancelable; }
- DOMTimeStamp timeStamp() const { return m_createTime; }
-
- void stopPropagation() { m_propagationStopped = true; }
- void stopImmediatePropagation() { m_immediatePropagationStopped = true; }
-
- // IE Extensions
- EventTarget* srcElement() const { return target(); } // MSIE extension - "the object that fired the event"
-
- bool legacyReturnValue() const { return !defaultPrevented(); }
- void setLegacyReturnValue(bool returnValue) { setDefaultPrevented(!returnValue); }
-
- Clipboard* clipboardData() const { return isClipboardEvent() ? clipboard() : 0; }
-
- virtual const AtomicString& interfaceName() const;
- bool hasInterface(const AtomicString&) const;
-
- // These events are general classes of events.
- virtual bool isUIEvent() const;
- virtual bool isMouseEvent() const;
- virtual bool isFocusEvent() const;
- virtual bool isKeyboardEvent() const;
- virtual bool isTouchEvent() const;
- virtual bool isGestureEvent() const;
-
- // Drag events are a subset of mouse events.
- virtual bool isDragEvent() const;
-
- // These events lack a DOM interface.
- virtual bool isClipboardEvent() const;
- virtual bool isBeforeTextInsertedEvent() const;
-
- virtual bool isBeforeUnloadEvent() const;
-
- bool propagationStopped() const { return m_propagationStopped || m_immediatePropagationStopped; }
- bool immediatePropagationStopped() const { return m_immediatePropagationStopped; }
-
- bool defaultPrevented() const { return m_defaultPrevented; }
- void preventDefault()
- {
- if (m_cancelable)
- m_defaultPrevented = true;
- }
- void setDefaultPrevented(bool defaultPrevented) { m_defaultPrevented = defaultPrevented; }
-
- bool defaultHandled() const { return m_defaultHandled; }
- void setDefaultHandled() { m_defaultHandled = true; }
-
- bool cancelBubble() const { return m_cancelBubble; }
- void setCancelBubble(bool cancel) { m_cancelBubble = cancel; }
-
- Event* underlyingEvent() const { return m_underlyingEvent.get(); }
- void setUnderlyingEvent(PassRefPtr<Event>);
-
- EventPath& eventPath() { return m_eventPath; }
- PassRefPtr<NodeList> path() const;
-
- virtual Clipboard* clipboard() const { return 0; }
-
- bool isBeingDispatched() const { return eventPhase(); }
-
-protected:
- Event();
- Event(const AtomicString& type, bool canBubble, bool cancelable);
- Event(const AtomicString& type, const EventInit&);
-
- virtual void receivedTarget();
- bool dispatched() const { return m_target; }
-
-private:
- AtomicString m_type;
- bool m_canBubble;
- bool m_cancelable;
-
- bool m_propagationStopped;
- bool m_immediatePropagationStopped;
- bool m_defaultPrevented;
- bool m_defaultHandled;
- bool m_cancelBubble;
-
- unsigned short m_eventPhase;
- EventTarget* m_currentTarget;
- RefPtr<EventTarget> m_target;
- DOMTimeStamp m_createTime;
- RefPtr<Event> m_underlyingEvent;
- EventPath m_eventPath;
-};
-
-} // namespace WebCore
-
-#endif // Event_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/Event.idl b/chromium/third_party/WebKit/Source/core/dom/Event.idl
deleted file mode 100644
index 88d704fa31a..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/Event.idl
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * Copyright (C) 2006, 2007, 2009, 2011 Apple Inc. All rights reserved.
- * Copyright (C) 2006 Samuel Weinig <sam.weinig@gmail.com>
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-// Introduced in DOM Level 2:
-[
- CustomToV8,
- ConstructorTemplate=Event
-
-] interface Event {
-
- // DOM PhaseType
- const unsigned short NONE = 0;
- const unsigned short CAPTURING_PHASE = 1;
- const unsigned short AT_TARGET = 2;
- const unsigned short BUBBLING_PHASE = 3;
-
- // Reverse-engineered from Netscape
- const unsigned short MOUSEDOWN = 1;
- const unsigned short MOUSEUP = 2;
- const unsigned short MOUSEOVER = 4;
- const unsigned short MOUSEOUT = 8;
- const unsigned short MOUSEMOVE = 16;
- const unsigned short MOUSEDRAG = 32;
- const unsigned short CLICK = 64;
- const unsigned short DBLCLICK = 128;
- const unsigned short KEYDOWN = 256;
- const unsigned short KEYUP = 512;
- const unsigned short KEYPRESS = 1024;
- const unsigned short DRAGDROP = 2048;
- const unsigned short FOCUS = 4096;
- const unsigned short BLUR = 8192;
- const unsigned short SELECT = 16384;
- const unsigned short CHANGE = 32768;
-
- readonly attribute DOMString type;
- readonly attribute EventTarget target;
- readonly attribute EventTarget currentTarget;
- readonly attribute unsigned short eventPhase;
- [InitializedByEventConstructor] readonly attribute boolean bubbles;
- [InitializedByEventConstructor] readonly attribute boolean cancelable;
- readonly attribute DOMTimeStamp timeStamp;
-
- void stopPropagation();
- void preventDefault();
- void initEvent([Default=Undefined] optional DOMString eventTypeArg,
- [Default=Undefined] optional boolean canBubbleArg,
- [Default=Undefined] optional boolean cancelableArg);
-
- // DOM Level 3 Additions.
- readonly attribute boolean defaultPrevented;
- void stopImmediatePropagation();
-
- // IE Extensions
- readonly attribute EventTarget srcElement;
- [ImplementedAs=legacyReturnValue, DeprecateAs=EventReturnValue] attribute boolean returnValue;
- attribute boolean cancelBubble;
-
- [EnabledAtRuntime=ShadowDOM] readonly attribute NodeList path;
-
- [Custom] readonly attribute Clipboard clipboardData;
-};
-
diff --git a/chromium/third_party/WebKit/Source/core/dom/EventAliases.in b/chromium/third_party/WebKit/Source/core/dom/EventAliases.in
deleted file mode 100644
index a4b61c27132..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/EventAliases.in
+++ /dev/null
@@ -1,14 +0,0 @@
-# Aliases
-AnimationEvent ImplementedAs=WebKitAnimationEvent, EnabledAtRuntime=cssAnimationUnprefixedEnabled
-Events ImplementedAs=Event
-HTMLEvents ImplementedAs=Event
-KeyboardEvents ImplementedAs=KeyboardEvent
-MouseEvents ImplementedAs=MouseEvent
-MutationEvents ImplementedAs=MutationEvent
-OrientationEvent ImplementedAs=Event, Conditional=ORIENTATION_EVENTS
-SVGEvents ImplementedAs=Event
-SVGZoomEvents ImplementedAs=SVGZoomEvent
-UIEvents ImplementedAs=UIEvent
-WebKitTransitionEvent ImplementedAs=TransitionEvent
-
-core/dom/TouchEvent EnabledAtRuntime=touchEnabled
diff --git a/chromium/third_party/WebKit/Source/core/dom/EventContext.cpp b/chromium/third_party/WebKit/Source/core/dom/EventContext.cpp
deleted file mode 100644
index b1d2fe8ed49..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/EventContext.cpp
+++ /dev/null
@@ -1,140 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-#include "config.h"
-#include "core/dom/EventContext.h"
-
-#include "core/dom/Event.h"
-#include "core/dom/FocusEvent.h"
-#include "core/dom/MouseEvent.h"
-#include "core/dom/Node.h"
-#include "core/dom/StaticNodeList.h"
-#include "core/dom/TouchEvent.h"
-#include "core/dom/TouchList.h"
-
-namespace WebCore {
-
-EventContext::EventContext(PassRefPtr<Node> node, PassRefPtr<EventTarget> currentTarget, PassRefPtr<EventTarget> target)
- : m_node(node)
- , m_currentTarget(currentTarget)
- , m_target(target)
-{
- ASSERT(m_node);
- ASSERT(!isUnreachableNode(m_target.get()));
-}
-
-EventContext::~EventContext()
-{
-}
-
-void EventContext::adoptEventPath(Vector<RefPtr<Node> >& nodes)
-{
- m_eventPath = StaticNodeList::adopt(nodes);
-}
-
-void EventContext::handleLocalEvents(Event* event) const
-{
- event->setTarget(m_target.get());
- event->setCurrentTarget(m_currentTarget.get());
- m_node->handleLocalEvents(event);
-}
-
-bool EventContext::isMouseOrFocusEventContext() const
-{
- return false;
-}
-
-bool EventContext::isTouchEventContext() const
-{
- return false;
-}
-
-MouseOrFocusEventContext::MouseOrFocusEventContext(PassRefPtr<Node> node, PassRefPtr<EventTarget> currentTarget, PassRefPtr<EventTarget> target)
- : EventContext(node, currentTarget, target)
- , m_relatedTarget(0)
-{
-}
-
-MouseOrFocusEventContext::~MouseOrFocusEventContext()
-{
-}
-
-void MouseOrFocusEventContext::handleLocalEvents(Event* event) const
-{
- ASSERT(event->isMouseEvent() || event->isFocusEvent());
- if (m_relatedTarget.get() && event->isMouseEvent())
- toMouseEvent(event)->setRelatedTarget(m_relatedTarget.get());
- else if (m_relatedTarget.get() && event->isFocusEvent())
- toFocusEvent(event)->setRelatedTarget(m_relatedTarget.get());
- EventContext::handleLocalEvents(event);
-}
-
-bool MouseOrFocusEventContext::isMouseOrFocusEventContext() const
-{
- return true;
-}
-
-TouchEventContext::TouchEventContext(PassRefPtr<Node> node, PassRefPtr<EventTarget> currentTarget, PassRefPtr<EventTarget> target)
- : EventContext(node, currentTarget, target)
- , m_touches(TouchList::create())
- , m_targetTouches(TouchList::create())
- , m_changedTouches(TouchList::create())
-{
-}
-
-TouchEventContext::~TouchEventContext()
-{
-}
-
-void TouchEventContext::handleLocalEvents(Event* event) const
-{
-#ifndef NDEBUG
- checkReachability(m_touches.get());
- checkReachability(m_targetTouches.get());
- checkReachability(m_changedTouches.get());
-#endif
- ASSERT(event->isTouchEvent());
- TouchEvent* touchEvent = toTouchEvent(event);
- touchEvent->setTouches(m_touches);
- touchEvent->setTargetTouches(m_targetTouches);
- touchEvent->setChangedTouches(m_changedTouches);
- EventContext::handleLocalEvents(event);
-}
-
-bool TouchEventContext::isTouchEventContext() const
-{
- return true;
-}
-
-#ifndef NDEBUG
-void TouchEventContext::checkReachability(TouchList* touchList) const
-{
- for (size_t i = 0; i < touchList->length(); ++i)
- ASSERT(touchList->item(i)->target()->toNode()->treeScope().isInclusiveAncestorOf(m_node->treeScope()));
-}
-#endif
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/dom/EventContext.h b/chromium/third_party/WebKit/Source/core/dom/EventContext.h
deleted file mode 100644
index 748fff0eeb8..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/EventContext.h
+++ /dev/null
@@ -1,127 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-#ifndef EventContext_h
-#define EventContext_h
-
-#include "core/dom/EventTarget.h"
-#include "core/dom/Node.h"
-#include "core/dom/StaticNodeList.h"
-#include "core/dom/TreeScope.h"
-#include "wtf/RefPtr.h"
-
-namespace WebCore {
-
-class Event;
-class TouchList;
-
-class EventContext {
-public:
- // FIXME: Use ContainerNode instead of Node.
- EventContext(PassRefPtr<Node>, PassRefPtr<EventTarget> currentTarget, PassRefPtr<EventTarget> target);
- virtual ~EventContext();
-
- Node* node() const { return m_node.get(); }
- EventTarget* target() const { return m_target.get(); }
- PassRefPtr<NodeList> eventPath() { return m_eventPath; }
- void adoptEventPath(Vector<RefPtr<Node> >&);
- void setEventPath(PassRefPtr<NodeList> nodeList) { m_eventPath = nodeList; }
-
- bool currentTargetSameAsTarget() const { return m_currentTarget.get() == m_target.get(); }
- virtual void handleLocalEvents(Event*) const;
- virtual bool isMouseOrFocusEventContext() const;
- virtual bool isTouchEventContext() const;
-
-protected:
-#ifndef NDEBUG
- bool isUnreachableNode(EventTarget*);
-#endif
- RefPtr<Node> m_node;
- RefPtr<EventTarget> m_currentTarget;
- RefPtr<EventTarget> m_target;
- RefPtr<NodeList> m_eventPath;
-};
-
-typedef Vector<OwnPtr<EventContext>, 32> EventPath;
-
-class MouseOrFocusEventContext : public EventContext {
-public:
- MouseOrFocusEventContext(PassRefPtr<Node>, PassRefPtr<EventTarget> currentTarget, PassRefPtr<EventTarget> target);
- virtual ~MouseOrFocusEventContext();
- EventTarget* relatedTarget() const { return m_relatedTarget.get(); }
- void setRelatedTarget(PassRefPtr<EventTarget>);
- virtual void handleLocalEvents(Event*) const OVERRIDE;
- virtual bool isMouseOrFocusEventContext() const OVERRIDE;
-
-private:
- RefPtr<EventTarget> m_relatedTarget;
-};
-
-
-class TouchEventContext : public EventContext {
-public:
- TouchEventContext(PassRefPtr<Node>, PassRefPtr<EventTarget> currentTarget, PassRefPtr<EventTarget> target);
- virtual ~TouchEventContext();
-
- virtual void handleLocalEvents(Event*) const OVERRIDE;
- virtual bool isTouchEventContext() const OVERRIDE;
-
- TouchList* touches() { return m_touches.get(); }
- TouchList* targetTouches() { return m_targetTouches.get(); }
- TouchList* changedTouches() { return m_changedTouches.get(); }
-
-private:
- RefPtr<TouchList> m_touches;
- RefPtr<TouchList> m_targetTouches;
- RefPtr<TouchList> m_changedTouches;
-#ifndef NDEBUG
- void checkReachability(TouchList*) const;
-#endif
-};
-
-inline TouchEventContext* toTouchEventContext(EventContext* eventContext)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!eventContext || eventContext->isTouchEventContext());
- return static_cast<TouchEventContext*>(eventContext);
-}
-
-#ifndef NDEBUG
-inline bool EventContext::isUnreachableNode(EventTarget* target)
-{
- // FIXME: Checks also for SVG elements.
- return target && target->toNode() && !target->toNode()->isSVGElement() && !target->toNode()->treeScope().isInclusiveAncestorOf(m_node->treeScope());
-}
-#endif
-
-inline void MouseOrFocusEventContext::setRelatedTarget(PassRefPtr<EventTarget> relatedTarget)
-{
- ASSERT(!isUnreachableNode(relatedTarget.get()));
- m_relatedTarget = relatedTarget;
-}
-
-}
-
-#endif // EventContext_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/EventDispatchMediator.cpp b/chromium/third_party/WebKit/Source/core/dom/EventDispatchMediator.cpp
deleted file mode 100644
index 45c92061a98..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/EventDispatchMediator.cpp
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/dom/EventDispatchMediator.h"
-
-#include "core/dom/Event.h"
-#include "core/dom/EventDispatcher.h"
-
-namespace WebCore {
-
-PassRefPtr<EventDispatchMediator> EventDispatchMediator::create(PassRefPtr<Event> event)
-{
- return adoptRef(new EventDispatchMediator(event));
-}
-
-EventDispatchMediator::EventDispatchMediator(PassRefPtr<Event> event)
- : m_event(event)
-{
-}
-
-bool EventDispatchMediator::dispatchEvent(EventDispatcher* dispatcher) const
-{
- ASSERT(m_event.get() == dispatcher->event());
- return dispatcher->dispatch();
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/EventDispatcher.cpp b/chromium/third_party/WebKit/Source/core/dom/EventDispatcher.cpp
deleted file mode 100644
index 9bcfb1134e7..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/EventDispatcher.cpp
+++ /dev/null
@@ -1,227 +0,0 @@
-/*
- * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
- * (C) 1999 Antti Koivisto (koivisto@kde.org)
- * (C) 2001 Dirk Mueller (mueller@kde.org)
- * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
- * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
- * Copyright (C) 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-#include "core/dom/EventDispatcher.h"
-
-#include "core/dom/ContainerNode.h"
-#include "core/dom/EventContext.h"
-#include "core/dom/EventDispatchMediator.h"
-#include "core/dom/EventRetargeter.h"
-#include "core/dom/MouseEvent.h"
-#include "core/dom/ScopedEventQueue.h"
-#include "core/dom/WindowEventContext.h"
-#include "core/inspector/InspectorInstrumentation.h"
-#include "core/page/FrameView.h"
-#include "wtf/RefPtr.h"
-
-namespace WebCore {
-
-static HashSet<Node*>* gNodesDispatchingSimulatedClicks = 0;
-
-bool EventDispatcher::dispatchEvent(Node* node, PassRefPtr<EventDispatchMediator> mediator)
-{
- ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
- if (!mediator->event())
- return true;
- EventDispatcher dispatcher(node, mediator->event());
- return mediator->dispatchEvent(&dispatcher);
-}
-
-EventDispatcher::EventDispatcher(Node* node, PassRefPtr<Event> event)
- : m_node(node)
- , m_event(event)
-#ifndef NDEBUG
- , m_eventDispatched(false)
-#endif
-{
- ASSERT(node);
- ASSERT(m_event.get());
- ASSERT(!m_event->type().isNull()); // JavaScript code can create an event with an empty name, but not null.
- m_view = node->document().view();
- EventRetargeter::ensureEventPath(m_node.get(), m_event.get());
-}
-
-void EventDispatcher::dispatchScopedEvent(Node* node, PassRefPtr<EventDispatchMediator> mediator)
-{
- // We need to set the target here because it can go away by the time we actually fire the event.
- mediator->event()->setTarget(EventRetargeter::eventTargetRespectingTargetRules(node));
- ScopedEventQueue::instance()->enqueueEventDispatchMediator(mediator);
-}
-
-void EventDispatcher::dispatchSimulatedClick(Node* node, Event* underlyingEvent, SimulatedClickMouseEventOptions mouseEventOptions, SimulatedClickVisualOptions visualOptions)
-{
- if (isDisabledFormControl(node))
- return;
-
- if (!gNodesDispatchingSimulatedClicks)
- gNodesDispatchingSimulatedClicks = new HashSet<Node*>;
- else if (gNodesDispatchingSimulatedClicks->contains(node))
- return;
-
- gNodesDispatchingSimulatedClicks->add(node);
-
- if (mouseEventOptions == SendMouseOverUpDownEvents)
- EventDispatcher(node, SimulatedMouseEvent::create(eventNames().mouseoverEvent, node->document().defaultView(), underlyingEvent)).dispatch();
-
- if (mouseEventOptions != SendNoEvents)
- EventDispatcher(node, SimulatedMouseEvent::create(eventNames().mousedownEvent, node->document().defaultView(), underlyingEvent)).dispatch();
- node->setActive(true, visualOptions == ShowPressedLook);
- if (mouseEventOptions != SendNoEvents)
- EventDispatcher(node, SimulatedMouseEvent::create(eventNames().mouseupEvent, node->document().defaultView(), underlyingEvent)).dispatch();
- node->setActive(false);
-
- // always send click
- EventDispatcher(node, SimulatedMouseEvent::create(eventNames().clickEvent, node->document().defaultView(), underlyingEvent)).dispatch();
-
- gNodesDispatchingSimulatedClicks->remove(node);
-}
-
-bool EventDispatcher::dispatch()
-{
-#ifndef NDEBUG
- ASSERT(!m_eventDispatched);
- m_eventDispatched = true;
-#endif
- ChildNodesLazySnapshot::takeChildNodesLazySnapshot();
-
- m_event->setTarget(EventRetargeter::eventTargetRespectingTargetRules(m_node.get()));
- ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
- ASSERT(m_event->target());
- WindowEventContext windowEventContext(m_event.get(), m_node.get(), topEventContext());
- InspectorInstrumentationCookie cookie = InspectorInstrumentation::willDispatchEvent(&m_node->document(), *m_event, windowEventContext.window(), m_node.get(), m_event->eventPath());
-
- void* preDispatchEventHandlerResult;
- if (dispatchEventPreProcess(preDispatchEventHandlerResult) == ContinueDispatching)
- if (dispatchEventAtCapturing(windowEventContext) == ContinueDispatching)
- if (dispatchEventAtTarget() == ContinueDispatching)
- dispatchEventAtBubbling(windowEventContext);
- dispatchEventPostProcess(preDispatchEventHandlerResult);
-
- // Ensure that after event dispatch, the event's target object is the
- // outermost shadow DOM boundary.
- m_event->setTarget(windowEventContext.target());
- m_event->setCurrentTarget(0);
- InspectorInstrumentation::didDispatchEvent(cookie);
-
- return !m_event->defaultPrevented();
-}
-
-inline EventDispatchContinuation EventDispatcher::dispatchEventPreProcess(void*& preDispatchEventHandlerResult)
-{
- // Give the target node a chance to do some work before DOM event handlers get a crack.
- preDispatchEventHandlerResult = m_node->preDispatchEventHandler(m_event.get());
- return (m_event->eventPath().isEmpty() || m_event->propagationStopped()) ? DoneDispatching : ContinueDispatching;
-}
-
-inline EventDispatchContinuation EventDispatcher::dispatchEventAtCapturing(WindowEventContext& windowEventContext)
-{
- // Trigger capturing event handlers, starting at the top and working our way down.
- m_event->setEventPhase(Event::CAPTURING_PHASE);
-
- if (windowEventContext.handleLocalEvents(m_event.get()) && m_event->propagationStopped())
- return DoneDispatching;
-
- for (size_t i = m_event->eventPath().size() - 1; i > 0; --i) {
- const EventContext& eventContext = *m_event->eventPath()[i];
- if (eventContext.currentTargetSameAsTarget())
- continue;
- eventContext.handleLocalEvents(m_event.get());
- if (m_event->propagationStopped())
- return DoneDispatching;
- }
-
- return ContinueDispatching;
-}
-
-inline EventDispatchContinuation EventDispatcher::dispatchEventAtTarget()
-{
- m_event->setEventPhase(Event::AT_TARGET);
- m_event->eventPath()[0]->handleLocalEvents(m_event.get());
- return m_event->propagationStopped() ? DoneDispatching : ContinueDispatching;
-}
-
-inline void EventDispatcher::dispatchEventAtBubbling(WindowEventContext& windowContext)
-{
- // Trigger bubbling event handlers, starting at the bottom and working our way up.
- size_t size = m_event->eventPath().size();
- for (size_t i = 1; i < size; ++i) {
- const EventContext& eventContext = *m_event->eventPath()[i];
- if (eventContext.currentTargetSameAsTarget())
- m_event->setEventPhase(Event::AT_TARGET);
- else if (m_event->bubbles() && !m_event->cancelBubble())
- m_event->setEventPhase(Event::BUBBLING_PHASE);
- else
- continue;
- eventContext.handleLocalEvents(m_event.get());
- if (m_event->propagationStopped())
- return;
- }
- if (m_event->bubbles() && !m_event->cancelBubble()) {
- m_event->setEventPhase(Event::BUBBLING_PHASE);
- windowContext.handleLocalEvents(m_event.get());
- }
-}
-
-inline void EventDispatcher::dispatchEventPostProcess(void* preDispatchEventHandlerResult)
-{
- m_event->setTarget(EventRetargeter::eventTargetRespectingTargetRules(m_node.get()));
- m_event->setCurrentTarget(0);
- m_event->setEventPhase(0);
-
- // Pass the data from the preDispatchEventHandler to the postDispatchEventHandler.
- m_node->postDispatchEventHandler(m_event.get(), preDispatchEventHandlerResult);
-
- // Call default event handlers. While the DOM does have a concept of preventing
- // default handling, the detail of which handlers are called is an internal
- // implementation detail and not part of the DOM.
- if (!m_event->defaultPrevented() && !m_event->defaultHandled()) {
- // Non-bubbling events call only one default event handler, the one for the target.
- m_node->willCallDefaultEventHandler(*m_event);
- m_node->defaultEventHandler(m_event.get());
- ASSERT(!m_event->defaultPrevented());
- if (m_event->defaultHandled())
- return;
- // For bubbling events, call default event handlers on the same targets in the
- // same order as the bubbling phase.
- if (m_event->bubbles()) {
- size_t size = m_event->eventPath().size();
- for (size_t i = 1; i < size; ++i) {
- m_event->eventPath()[i]->node()->willCallDefaultEventHandler(*m_event);
- m_event->eventPath()[i]->node()->defaultEventHandler(m_event.get());
- ASSERT(!m_event->defaultPrevented());
- if (m_event->defaultHandled())
- return;
- }
- }
- }
-}
-
-const EventContext* EventDispatcher::topEventContext()
-{
- return m_event->eventPath().isEmpty() ? 0 : m_event->eventPath().last().get();
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/dom/EventDispatcher.h b/chromium/third_party/WebKit/Source/core/dom/EventDispatcher.h
deleted file mode 100644
index 55871324622..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/EventDispatcher.h
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
- * (C) 1999 Antti Koivisto (koivisto@kde.org)
- * (C) 2001 Dirk Mueller (mueller@kde.org)
- * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010 Apple Inc. All rights reserved.
- * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
- * Copyright (C) 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#ifndef EventDispatcher_h
-#define EventDispatcher_h
-
-#include "core/dom/EventContext.h"
-#include "core/dom/SimulatedClickOptions.h"
-#include "wtf/Forward.h"
-#include "wtf/PassRefPtr.h"
-
-namespace WebCore {
-
-class Event;
-class EventDispatchMediator;
-class EventTarget;
-class FrameView;
-class Node;
-class PlatformKeyboardEvent;
-class PlatformMouseEvent;
-class ShadowRoot;
-class TreeScope;
-class WindowEventContext;
-
-enum EventDispatchContinuation {
- ContinueDispatching,
- DoneDispatching
-};
-
-class EventDispatcher {
-public:
- static bool dispatchEvent(Node*, PassRefPtr<EventDispatchMediator>);
- static void dispatchScopedEvent(Node*, PassRefPtr<EventDispatchMediator>);
-
- static void dispatchSimulatedClick(Node*, Event* underlyingEvent, SimulatedClickMouseEventOptions, SimulatedClickVisualOptions);
-
- bool dispatch();
- Node* node() const { return m_node.get(); }
- Event* event() const { return m_event.get(); }
-
-private:
- EventDispatcher(Node*, PassRefPtr<Event>);
- const EventContext* topEventContext();
-
- EventDispatchContinuation dispatchEventPreProcess(void*& preDispatchEventHandlerResult);
- EventDispatchContinuation dispatchEventAtCapturing(WindowEventContext&);
- EventDispatchContinuation dispatchEventAtTarget();
- void dispatchEventAtBubbling(WindowEventContext&);
- void dispatchEventPostProcess(void* preDispatchEventHandlerResult);
-
- RefPtr<Node> m_node;
- RefPtr<Event> m_event;
- RefPtr<FrameView> m_view;
-#ifndef NDEBUG
- bool m_eventDispatched;
-#endif
-};
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/dom/EventListener.h b/chromium/third_party/WebKit/Source/core/dom/EventListener.h
deleted file mode 100644
index cb4eaa08c1c..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/EventListener.h
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Copyright (C) 2006, 2008, 2009 Apple Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#ifndef EventListener_h
-#define EventListener_h
-
-#include "wtf/RefCounted.h"
-
-namespace WebCore {
-
- class DOMWrapperWorld;
- class Event;
- class ScriptExecutionContext;
-
- class EventListener : public RefCounted<EventListener> {
- public:
- enum Type {
- JSEventListenerType,
- ImageEventListenerType,
- ObjCEventListenerType,
- CPPEventListenerType,
- ConditionEventListenerType,
- GObjectEventListenerType,
- NativeEventListenerType,
- };
-
- virtual ~EventListener() { }
- virtual bool operator==(const EventListener&) = 0;
- virtual void handleEvent(ScriptExecutionContext*, Event*) = 0;
- virtual bool wasCreatedFromMarkup() const { return false; }
- virtual DOMWrapperWorld* world() const { return 0; }
-
- bool isAttribute() const { return virtualisAttribute(); }
- Type type() const { return m_type; }
-
- protected:
- explicit EventListener(Type type)
- : m_type(type)
- {
- }
-
- private:
- virtual bool virtualisAttribute() const { return false; }
-
- Type m_type;
- };
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/dom/EventListenerMap.cpp b/chromium/third_party/WebKit/Source/core/dom/EventListenerMap.cpp
deleted file mode 100644
index 3d34f5925d2..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/EventListenerMap.cpp
+++ /dev/null
@@ -1,272 +0,0 @@
-/*
- * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
- * (C) 1999 Antti Koivisto (koivisto@kde.org)
- * (C) 2001 Dirk Mueller (mueller@kde.org)
- * Copyright (C) 2004, 2005, 2006, 2007 Apple Inc. All rights reserved.
- * Copyright (C) 2006 Alexey Proskuryakov (ap@webkit.org)
- * (C) 2007, 2008 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2011 Andreas Kling (kling@webkit.org)
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-#include "config.h"
-#include "core/dom/EventListenerMap.h"
-
-#include "core/dom/EventTarget.h"
-#include "wtf/StdLibExtras.h"
-#include "wtf/Vector.h"
-
-#ifndef NDEBUG
-#include "wtf/ThreadingPrimitives.h"
-#endif
-
-using namespace WTF;
-
-namespace WebCore {
-
-#ifndef NDEBUG
-static Mutex& activeIteratorCountMutex()
-{
- DEFINE_STATIC_LOCAL(Mutex, mutex, ());
- return mutex;
-}
-
-void EventListenerMap::assertNoActiveIterators()
-{
- MutexLocker locker(activeIteratorCountMutex());
- ASSERT(!m_activeIteratorCount);
-}
-#endif
-
-EventListenerMap::EventListenerMap()
-#ifndef NDEBUG
- : m_activeIteratorCount(0)
-#endif
-{
-}
-
-bool EventListenerMap::contains(const AtomicString& eventType) const
-{
- for (unsigned i = 0; i < m_entries.size(); ++i) {
- if (m_entries[i].first == eventType)
- return true;
- }
- return false;
-}
-
-bool EventListenerMap::containsCapturing(const AtomicString& eventType) const
-{
- for (unsigned i = 0; i < m_entries.size(); ++i) {
- if (m_entries[i].first == eventType) {
- const EventListenerVector* vector = m_entries[i].second.get();
- for (unsigned j = 0; j < vector->size(); ++j) {
- if (vector->at(j).useCapture)
- return true;
- }
- }
- }
- return false;
-}
-
-void EventListenerMap::clear()
-{
- assertNoActiveIterators();
-
- m_entries.clear();
-}
-
-Vector<AtomicString> EventListenerMap::eventTypes() const
-{
- Vector<AtomicString> types;
- types.reserveInitialCapacity(m_entries.size());
-
- for (unsigned i = 0; i < m_entries.size(); ++i)
- types.uncheckedAppend(m_entries[i].first);
-
- return types;
-}
-
-static bool addListenerToVector(EventListenerVector* vector, PassRefPtr<EventListener> listener, bool useCapture)
-{
- RegisteredEventListener registeredListener(listener, useCapture);
-
- if (vector->find(registeredListener) != kNotFound)
- return false; // Duplicate listener.
-
- vector->append(registeredListener);
- return true;
-}
-
-bool EventListenerMap::add(const AtomicString& eventType, PassRefPtr<EventListener> listener, bool useCapture)
-{
- assertNoActiveIterators();
-
- for (unsigned i = 0; i < m_entries.size(); ++i) {
- if (m_entries[i].first == eventType)
- return addListenerToVector(m_entries[i].second.get(), listener, useCapture);
- }
-
- m_entries.append(std::make_pair(eventType, adoptPtr(new EventListenerVector)));
- return addListenerToVector(m_entries.last().second.get(), listener, useCapture);
-}
-
-static bool removeListenerFromVector(EventListenerVector* listenerVector, EventListener* listener, bool useCapture, size_t& indexOfRemovedListener)
-{
- RegisteredEventListener registeredListener(listener, useCapture);
- indexOfRemovedListener = listenerVector->find(registeredListener);
- if (indexOfRemovedListener == kNotFound)
- return false;
- listenerVector->remove(indexOfRemovedListener);
- return true;
-}
-
-bool EventListenerMap::remove(const AtomicString& eventType, EventListener* listener, bool useCapture, size_t& indexOfRemovedListener)
-{
- assertNoActiveIterators();
-
- for (unsigned i = 0; i < m_entries.size(); ++i) {
- if (m_entries[i].first == eventType) {
- bool wasRemoved = removeListenerFromVector(m_entries[i].second.get(), listener, useCapture, indexOfRemovedListener);
- if (m_entries[i].second->isEmpty())
- m_entries.remove(i);
- return wasRemoved;
- }
- }
-
- return false;
-}
-
-EventListenerVector* EventListenerMap::find(const AtomicString& eventType)
-{
- assertNoActiveIterators();
-
- for (unsigned i = 0; i < m_entries.size(); ++i) {
- if (m_entries[i].first == eventType)
- return m_entries[i].second.get();
- }
-
- return 0;
-}
-
-static void removeFirstListenerCreatedFromMarkup(EventListenerVector* listenerVector)
-{
- bool foundListener = false;
-
- for (size_t i = 0; i < listenerVector->size(); ++i) {
- if (!listenerVector->at(i).listener->wasCreatedFromMarkup())
- continue;
- foundListener = true;
- listenerVector->remove(i);
- break;
- }
-
- ASSERT_UNUSED(foundListener, foundListener);
-}
-
-void EventListenerMap::removeFirstEventListenerCreatedFromMarkup(const AtomicString& eventType)
-{
- assertNoActiveIterators();
-
- for (unsigned i = 0; i < m_entries.size(); ++i) {
- if (m_entries[i].first == eventType) {
- removeFirstListenerCreatedFromMarkup(m_entries[i].second.get());
- if (m_entries[i].second->isEmpty())
- m_entries.remove(i);
- return;
- }
- }
-}
-
-static void copyListenersNotCreatedFromMarkupToTarget(const AtomicString& eventType, EventListenerVector* listenerVector, EventTarget* target)
-{
- for (size_t i = 0; i < listenerVector->size(); ++i) {
- // Event listeners created from markup have already been transfered to the shadow tree during cloning.
- if ((*listenerVector)[i].listener->wasCreatedFromMarkup())
- continue;
- target->addEventListener(eventType, (*listenerVector)[i].listener, (*listenerVector)[i].useCapture);
- }
-}
-
-void EventListenerMap::copyEventListenersNotCreatedFromMarkupToTarget(EventTarget* target)
-{
- assertNoActiveIterators();
-
- for (unsigned i = 0; i < m_entries.size(); ++i)
- copyListenersNotCreatedFromMarkupToTarget(m_entries[i].first, m_entries[i].second.get(), target);
-}
-
-EventListenerIterator::EventListenerIterator()
- : m_map(0)
- , m_entryIndex(0)
- , m_index(0)
-{
-}
-
-EventListenerIterator::EventListenerIterator(EventTarget* target)
- : m_map(0)
- , m_entryIndex(0)
- , m_index(0)
-{
- ASSERT(target);
- EventTargetData* data = target->eventTargetData();
-
- if (!data)
- return;
-
- m_map = &data->eventListenerMap;
-
-#ifndef NDEBUG
- {
- MutexLocker locker(activeIteratorCountMutex());
- m_map->m_activeIteratorCount++;
- }
-#endif
-}
-
-#ifndef NDEBUG
-EventListenerIterator::~EventListenerIterator()
-{
- if (m_map) {
- MutexLocker locker(activeIteratorCountMutex());
- m_map->m_activeIteratorCount--;
- }
-}
-#endif
-
-EventListener* EventListenerIterator::nextListener()
-{
- if (!m_map)
- return 0;
-
- for (; m_entryIndex < m_map->m_entries.size(); ++m_entryIndex) {
- EventListenerVector& listeners = *m_map->m_entries[m_entryIndex].second;
- if (m_index < listeners.size())
- return listeners[m_index++].listener.get();
- m_index = 0;
- }
-
- return 0;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/EventListenerMap.h b/chromium/third_party/WebKit/Source/core/dom/EventListenerMap.h
deleted file mode 100644
index 4889d94a1d9..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/EventListenerMap.h
+++ /dev/null
@@ -1,99 +0,0 @@
-/*
- * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
- * (C) 1999 Antti Koivisto (koivisto@kde.org)
- * (C) 2001 Dirk Mueller (mueller@kde.org)
- * Copyright (C) 2004, 2005, 2006, 2007, 2012 Apple Inc. All rights reserved.
- * Copyright (C) 2006 Alexey Proskuryakov (ap@webkit.org)
- * (C) 2007, 2008 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2011 Andreas Kling (kling@webkit.org)
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-#ifndef EventListenerMap_h
-#define EventListenerMap_h
-
-#include "core/dom/RegisteredEventListener.h"
-#include "wtf/Forward.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/text/AtomicStringHash.h"
-
-namespace WebCore {
-
-class EventTarget;
-
-typedef Vector<RegisteredEventListener, 1> EventListenerVector;
-
-class EventListenerMap {
-public:
- EventListenerMap();
-
- bool isEmpty() const { return m_entries.isEmpty(); }
- bool contains(const AtomicString& eventType) const;
- bool containsCapturing(const AtomicString& eventType) const;
-
- void clear();
- bool add(const AtomicString& eventType, PassRefPtr<EventListener>, bool useCapture);
- bool remove(const AtomicString& eventType, EventListener*, bool useCapture, size_t& indexOfRemovedListener);
- EventListenerVector* find(const AtomicString& eventType);
- Vector<AtomicString> eventTypes() const;
-
- void removeFirstEventListenerCreatedFromMarkup(const AtomicString& eventType);
- void copyEventListenersNotCreatedFromMarkupToTarget(EventTarget*);
-
-private:
- friend class EventListenerIterator;
-
- void assertNoActiveIterators();
-
- Vector<std::pair<AtomicString, OwnPtr<EventListenerVector> >, 2> m_entries;
-
-#ifndef NDEBUG
- int m_activeIteratorCount;
-#endif
-};
-
-class EventListenerIterator {
- WTF_MAKE_NONCOPYABLE(EventListenerIterator);
-public:
- EventListenerIterator();
- EventListenerIterator(EventTarget*);
-#ifndef NDEBUG
- ~EventListenerIterator();
-#endif
-
- EventListener* nextListener();
-
-private:
- EventListenerMap* m_map;
- unsigned m_entryIndex;
- unsigned m_index;
-};
-
-#ifdef NDEBUG
-inline void EventListenerMap::assertNoActiveIterators() { }
-#endif
-
-} // namespace WebCore
-
-#endif // EventListenerMap_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/EventNames.cpp b/chromium/third_party/WebKit/Source/core/dom/EventNames.cpp
deleted file mode 100644
index 9821d03e512..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/EventNames.cpp
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright (C) 2005 Apple Computer, Inc.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#include "config.h"
-#include "core/dom/EventNames.h"
-
-namespace WebCore {
-
-#define INITIALIZE_EVENT_NAME(name) \
- , name##Event(#name, AtomicString::ConstructFromLiteral)
-
-#define INITIALIZE_EVENT_INTERFACE(name) \
- , interfaceFor##name(#name, AtomicString::ConstructFromLiteral)
-
-EventNames::EventNames()
- : dummy(0)
-EVENT_NAMES_FOR_EACH(INITIALIZE_EVENT_NAME)
-EVENT_INTERFACES_FOR_EACH(INITIALIZE_EVENT_INTERFACE)
-EVENT_TARGET_INTERFACES_FOR_EACH(INITIALIZE_EVENT_INTERFACE)
-{
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/dom/EventNames.h b/chromium/third_party/WebKit/Source/core/dom/EventNames.h
deleted file mode 100644
index 225727d4443..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/EventNames.h
+++ /dev/null
@@ -1,338 +0,0 @@
-/*
- * Copyright (C) 2005, 2007 Apple Inc. All rights reserved.
- * Copyright (C) 2006 Jon Shier (jshier@iastate.edu)
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#ifndef EventNames_h
-#define EventNames_h
-
-#include "EventInterfaces.h"
-#include "EventTargetInterfaces.h"
-#include "core/platform/ThreadGlobalData.h"
-#include "wtf/text/AtomicString.h"
-
-namespace WebCore {
-
-#define EVENT_NAMES_FOR_EACH(macro) \
- \
- macro(abort) \
- macro(beforecopy) \
- macro(beforecut) \
- macro(beforeload) \
- macro(beforepaste) \
- macro(beforeunload) \
- macro(blocked) \
- macro(blur) \
- macro(cached) \
- macro(cancel) \
- macro(change) \
- macro(chargingchange) \
- macro(chargingtimechange) \
- macro(checking) \
- macro(click) \
- macro(close) \
- macro(complete) \
- macro(compositionend) \
- macro(compositionstart) \
- macro(compositionupdate) \
- macro(connect) \
- macro(contextmenu) \
- macro(copy) \
- macro(cut) \
- macro(dblclick) \
- macro(devicemotion) \
- macro(deviceorientation) \
- macro(dischargingtimechange) \
- macro(disconnect) \
- macro(display) \
- macro(downloading) \
- macro(drag) \
- macro(dragend) \
- macro(dragenter) \
- macro(dragleave) \
- macro(dragover) \
- macro(dragstart) \
- macro(drop) \
- macro(error) \
- macro(focus) \
- macro(focusin) \
- macro(focusout) \
- macro(gesturetap) \
- macro(gesturetapunconfirmed) \
- macro(gesturetapdown) \
- macro(gesturescrollstart) \
- macro(gesturescrollend) \
- macro(gesturescrollupdate) \
- macro(hashchange) \
- macro(input) \
- macro(invalid) \
- macro(keydown) \
- macro(keypress) \
- macro(keyup) \
- macro(levelchange) \
- macro(load) \
- macro(loading) \
- macro(loadingdone) \
- macro(loadingerror) \
- macro(loadstart) \
- macro(message) \
- macro(midimessage) \
- macro(mousedown) \
- macro(mouseenter) \
- macro(mouseleave) \
- macro(mousemove) \
- macro(mouseout) \
- macro(mouseover) \
- macro(mouseup) \
- macro(mousewheel) \
- macro(noupdate) \
- macro(obsolete) \
- macro(offline) \
- macro(online) \
- macro(open) \
- macro(overflowchanged) \
- macro(pagehide) \
- macro(pageshow) \
- macro(paste) \
- macro(popstate) \
- macro(readystatechange) \
- macro(reset) \
- macro(resize) \
- macro(scroll) \
- macro(search) \
- macro(select) \
- macro(selectstart) \
- macro(selectionchange) \
- macro(storage) \
- macro(submit) \
- macro(textInput) \
- macro(unload) \
- macro(updateready) \
- macro(upgradeneeded) \
- macro(versionchange) \
- macro(webkitvisibilitychange) \
- macro(wheel) \
- macro(write) \
- macro(writeend) \
- macro(writestart) \
- macro(zoom) \
- \
- macro(DOMActivate) \
- macro(DOMFocusIn) \
- macro(DOMFocusOut) \
- macro(DOMCharacterDataModified) \
- macro(DOMNodeInserted) \
- macro(DOMNodeInsertedIntoDocument) \
- macro(DOMNodeRemoved) \
- macro(DOMNodeRemovedFromDocument) \
- macro(DOMSubtreeModified) \
- macro(DOMContentLoaded) \
- \
- macro(webkitBeforeTextInserted) \
- macro(webkitEditableContentChanged) \
- \
- macro(canplay) \
- macro(canplaythrough) \
- macro(durationchange) \
- macro(emptied) \
- macro(ended) \
- macro(loadeddata) \
- macro(loadedmetadata) \
- macro(pause) \
- macro(play) \
- macro(playing) \
- macro(ratechange) \
- macro(seeked) \
- macro(seeking) \
- macro(timeupdate) \
- macro(volumechange) \
- macro(waiting) \
- \
- macro(addtrack) \
- macro(cuechange) \
- macro(enter) \
- macro(exit) \
- \
- macro(addsourcebuffer) \
- macro(removesourcebuffer) \
- macro(sourceopen) \
- macro(sourceended) \
- macro(sourceclose) \
- macro(update) \
- macro(updateend) \
- macro(updatestart) \
- macro(webkitaddsourcebuffer) \
- macro(webkitremovesourcebuffer) \
- macro(webkitsourceopen) \
- macro(webkitsourceended) \
- macro(webkitsourceclose) \
- \
- macro(webkitkeyadded) \
- macro(webkitkeyerror) \
- macro(webkitkeymessage) \
- macro(webkitneedkey) \
- \
- macro(progress) \
- macro(stalled) \
- macro(suspend) \
- \
- macro(animationend) \
- macro(webkitAnimationEnd) \
- macro(animationstart) \
- macro(webkitAnimationStart) \
- macro(animationiteration) \
- macro(webkitAnimationIteration) \
- \
- macro(webkitTransitionEnd) \
- macro(transitionend) \
- \
- macro(orientationchange) \
- \
- macro(timeout) \
- \
- macro(touchstart) \
- macro(touchmove) \
- macro(touchend) \
- macro(touchcancel) \
- \
- macro(success) \
- \
- macro(loadend) \
- \
- macro(webkitfullscreenchange) \
- macro(webkitfullscreenerror) \
- \
- macro(webkitspeechchange) \
- \
- macro(audiostart) \
- macro(soundstart) \
- macro(speechstart) \
- macro(speechend) \
- macro(soundend) \
- macro(audioend) \
- macro(result) \
- macro(nomatch) \
- macro(start) \
- macro(end) \
- macro(mark) \
- macro(boundary) \
- macro(resume) \
- \
- macro(webglcontextlost) \
- macro(webglcontextrestored) \
- macro(webglcontextcreationerror) \
- \
- macro(audioprocess) \
- \
- macro(connecting) \
- macro(addstream) \
- macro(removestream) \
- macro(signalingstatechange) \
- macro(removetrack) \
- macro(mute) \
- macro(unmute) \
- macro(iceconnectionstatechange) \
- macro(icecandidate) \
- macro(negotiationneeded) \
- macro(datachannel) \
- macro(tonechange) \
- \
- macro(show) \
- \
- macro(webkitpointerlockchange) \
- macro(webkitpointerlockerror) \
- \
- macro(webkitregionlayoutupdate) \
- \
- macro(webkitregionoversetchange) \
- \
- macro(webkitnetworkinfochange) \
- \
- macro(webkitresourcetimingbufferfull) \
- \
- macro(webkitdeviceproximity) \
- \
- macro(autocomplete) \
- macro(autocompleteerror) \
- \
- macro(webkitprerenderstart) \
- macro(webkitprerenderstop) \
- macro(webkitprerenderload) \
- macro(webkitprerenderdomcontentloaded) \
- \
- macro(securitypolicyviolation) \
- \
-
-// end of EVENT_NAMES_FOR_EACH
-
- class EventNames {
- WTF_MAKE_NONCOPYABLE(EventNames); WTF_MAKE_FAST_ALLOCATED;
- int dummy; // Needed to make initialization macro work.
- // Private to prevent accidental call to EventNames() instead of eventNames()
- EventNames();
- friend class ThreadGlobalData;
-
- public:
- #define EVENT_NAMES_DECLARE(name) AtomicString name##Event;
- EVENT_NAMES_FOR_EACH(EVENT_NAMES_DECLARE)
- #undef EVENT_NAMES_DECLARE
-
- #define EVENT_INTERFACE_DECLARE(name) AtomicString interfaceFor##name;
- EVENT_INTERFACES_FOR_EACH(EVENT_INTERFACE_DECLARE)
- EVENT_TARGET_INTERFACES_FOR_EACH(EVENT_INTERFACE_DECLARE)
- #undef EVENT_INTERFACE_DECLARE
-
- inline bool isTouchEventType(const AtomicString& eventType) const
- {
- return eventType == touchstartEvent
- || eventType == touchmoveEvent
- || eventType == touchendEvent
- || eventType == touchcancelEvent;
- }
-
- inline bool isGestureEventType(const AtomicString& eventType) const
- {
- return eventType == gesturetapEvent
- || eventType == gesturetapunconfirmedEvent
- || eventType == gesturetapdownEvent
- || eventType == gesturescrollstartEvent
- || eventType == gesturescrollendEvent
- || eventType == gesturescrollupdateEvent;
- }
-
- Vector<AtomicString> touchEventNames() const
- {
- Vector<AtomicString> names;
- names.reserveCapacity(4);
- names.append(touchstartEvent);
- names.append(touchmoveEvent);
- names.append(touchendEvent);
- names.append(touchcancelEvent);
- return names;
- }
- };
-
- inline EventNames& eventNames()
- {
- return threadGlobalData().eventNames();
- }
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/dom/EventPathWalker.cpp b/chromium/third_party/WebKit/Source/core/dom/EventPathWalker.cpp
deleted file mode 100644
index aea6933cfc3..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/EventPathWalker.cpp
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/dom/EventPathWalker.h"
-
-#include "core/dom/shadow/ElementShadow.h"
-#include "core/dom/shadow/InsertionPoint.h"
-#include "core/dom/shadow/ShadowRoot.h"
-
-namespace WebCore {
-
-EventPathWalker::EventPathWalker(const Node* node)
- : m_node(node)
- , m_distributedNode(node)
- , m_isVisitingInsertionPointInReprojection(false)
-{
- ASSERT(node);
- node->document().updateDistributionForNodeIfNeeded(const_cast<Node*>(node));
-}
-
-Node* EventPathWalker::parent(const Node* node)
-{
- EventPathWalker walker(node);
- walker.moveToParent();
- return walker.node();
-}
-
-void EventPathWalker::moveToParent()
-{
- ASSERT(m_node);
- ASSERT(m_distributedNode);
- if (ElementShadow* shadow = shadowOfParent(m_node)) {
- if (InsertionPoint* insertionPoint = shadow->findInsertionPointFor(m_distributedNode)) {
- m_node = insertionPoint;
- m_isVisitingInsertionPointInReprojection = true;
- return;
- }
- }
- if (!m_node->isShadowRoot()) {
- m_node = m_node->parentNode();
- if (!(m_node && m_node->isShadowRoot() && toShadowRoot(m_node)->insertionPoint()))
- m_distributedNode = m_node;
- m_isVisitingInsertionPointInReprojection = false;
- return;
- }
-
- const ShadowRoot* shadowRoot = toShadowRoot(m_node);
- if (InsertionPoint* insertionPoint = shadowRoot->insertionPoint()) {
- m_node = insertionPoint;
- m_isVisitingInsertionPointInReprojection = true;
- return;
- }
- m_node = shadowRoot->host();
- m_distributedNode = m_node;
- m_isVisitingInsertionPointInReprojection = false;
-}
-
-} // namespace
diff --git a/chromium/third_party/WebKit/Source/core/dom/EventPathWalker.h b/chromium/third_party/WebKit/Source/core/dom/EventPathWalker.h
deleted file mode 100644
index 9006e9bfe98..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/EventPathWalker.h
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef EventPathWalker_h
-#define EventPathWalker_h
-
-namespace WebCore {
-
-class Node;
-
-class EventPathWalker {
-public:
- explicit EventPathWalker(const Node*);
- static Node* parent(const Node*);
- void moveToParent();
- Node* node() const { return const_cast<Node*>(m_node); }
- bool isVisitingInsertionPointInReprojection() { return m_isVisitingInsertionPointInReprojection; }
-
-private:
- const Node* m_node;
- const Node* m_distributedNode;
- bool m_isVisitingInsertionPointInReprojection;
-};
-
-} // namespace
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/dom/EventRetargeter.cpp b/chromium/third_party/WebKit/Source/core/dom/EventRetargeter.cpp
deleted file mode 100644
index da3e8297b40..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/EventRetargeter.cpp
+++ /dev/null
@@ -1,283 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-#include "core/dom/EventRetargeter.h"
-
-#include "RuntimeEnabledFeatures.h"
-#include "core/dom/ContainerNode.h"
-#include "core/dom/EventContext.h"
-#include "core/dom/EventPathWalker.h"
-#include "core/dom/FocusEvent.h"
-#include "core/dom/FullscreenElementStack.h"
-#include "core/dom/MouseEvent.h"
-#include "core/dom/Touch.h"
-#include "core/dom/TouchEvent.h"
-#include "core/dom/TouchList.h"
-#include "core/dom/TreeScope.h"
-#include "core/dom/shadow/ShadowRoot.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefPtr.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-static inline bool inTheSameScope(ShadowRoot* shadowRoot, EventTarget* target)
-{
- return target->toNode() && target->toNode()->treeScope().rootNode() == shadowRoot;
-}
-
-static inline EventDispatchBehavior determineDispatchBehavior(Event* event, ShadowRoot* shadowRoot, EventTarget* target)
-{
- // Video-only full screen is a mode where we use the shadow DOM as an implementation
- // detail that should not be detectable by the web content.
- if (Element* element = FullscreenElementStack::currentFullScreenElementFrom(&target->toNode()->document())) {
- // FIXME: We assume that if the full screen element is a media element that it's
- // the video-only full screen. Both here and elsewhere. But that is probably wrong.
- if (element->isMediaElement() && shadowRoot && shadowRoot->host() == element)
- return StayInsideShadowDOM;
- }
-
- // WebKit never allowed selectstart event to cross the the shadow DOM boundary.
- // Changing this breaks existing sites.
- // See https://bugs.webkit.org/show_bug.cgi?id=52195 for details.
- const AtomicString eventType = event->type();
- if (inTheSameScope(shadowRoot, target)
- && (eventType == eventNames().abortEvent
- || eventType == eventNames().changeEvent
- || eventType == eventNames().errorEvent
- || eventType == eventNames().loadEvent
- || eventType == eventNames().resetEvent
- || eventType == eventNames().resizeEvent
- || eventType == eventNames().scrollEvent
- || eventType == eventNames().selectEvent
- || eventType == eventNames().selectstartEvent))
- return StayInsideShadowDOM;
-
- return RetargetEvent;
-}
-
-void EventRetargeter::ensureEventPath(Node* node, Event* event)
-{
- calculateEventPath(node, event);
- calculateAdjustedEventPathForEachNode(event->eventPath());
-}
-
-void EventRetargeter::calculateEventPath(Node* node, Event* event)
-{
- EventPath& eventPath = event->eventPath();
- eventPath.clear();
- bool inDocument = node->inDocument();
- bool isSVGElement = node->isSVGElement();
- bool isMouseOrFocusEvent = event->isMouseEvent() || event->isFocusEvent();
- bool isTouchEvent = event->isTouchEvent();
- Vector<EventTarget*, 32> targetStack;
- for (EventPathWalker walker(node); walker.node(); walker.moveToParent()) {
- Node* node = walker.node();
- if (targetStack.isEmpty())
- targetStack.append(eventTargetRespectingTargetRules(node));
- else if (walker.isVisitingInsertionPointInReprojection())
- targetStack.append(targetStack.last());
- if (isMouseOrFocusEvent)
- eventPath.append(adoptPtr(new MouseOrFocusEventContext(node, eventTargetRespectingTargetRules(node), targetStack.last())));
- else if (isTouchEvent)
- eventPath.append(adoptPtr(new TouchEventContext(node, eventTargetRespectingTargetRules(node), targetStack.last())));
- else
- eventPath.append(adoptPtr(new EventContext(node, eventTargetRespectingTargetRules(node), targetStack.last())));
- if (!inDocument)
- break;
- if (!node->isShadowRoot())
- continue;
- if (determineDispatchBehavior(event, toShadowRoot(node), targetStack.last()) == StayInsideShadowDOM)
- break;
- if (!isSVGElement) {
- ASSERT(!targetStack.isEmpty());
- targetStack.removeLast();
- }
- }
-}
-
-void EventRetargeter::calculateAdjustedEventPathForEachNode(EventPath& eventPath)
-{
- if (!RuntimeEnabledFeatures::shadowDOMEnabled())
- return;
- TreeScope* lastScope = 0;
- size_t eventPathSize = eventPath.size();
- for (size_t i = 0; i < eventPathSize; ++i) {
- TreeScope* currentScope = &eventPath[i]->node()->treeScope();
- if (currentScope == lastScope) {
- // Fast path.
- eventPath[i]->setEventPath(eventPath[i - 1]->eventPath());
- continue;
- }
- lastScope = currentScope;
- Vector<RefPtr<Node> > nodes;
- for (size_t j = 0; j < eventPathSize; ++j) {
- Node* node = eventPath[j]->node();
- if (node->treeScope().isInclusiveAncestorOf(*currentScope))
- nodes.append(node);
- }
- eventPath[i]->adoptEventPath(nodes);
- }
-}
-
-void EventRetargeter::adjustForMouseEvent(Node* node, MouseEvent& mouseEvent)
-{
- adjustForRelatedTarget(node, mouseEvent.relatedTarget(), mouseEvent.eventPath());
-}
-
-void EventRetargeter::adjustForFocusEvent(Node* node, FocusEvent& focusEvent)
-{
- adjustForRelatedTarget(node, focusEvent.relatedTarget(), focusEvent.eventPath());
-}
-
-void EventRetargeter::adjustForTouchEvent(Node* node, TouchEvent& touchEvent)
-{
- EventPath& eventPath = touchEvent.eventPath();
- size_t eventPathSize = eventPath.size();
-
- EventPathTouchLists eventPathTouches(eventPathSize);
- EventPathTouchLists eventPathTargetTouches(eventPathSize);
- EventPathTouchLists eventPathChangedTouches(eventPathSize);
-
- for (size_t i = 0; i < eventPathSize; ++i) {
- ASSERT(eventPath[i]->isTouchEventContext());
- TouchEventContext* touchEventContext = toTouchEventContext(eventPath[i].get());
- eventPathTouches[i] = touchEventContext->touches();
- eventPathTargetTouches[i] = touchEventContext->targetTouches();
- eventPathChangedTouches[i] = touchEventContext->changedTouches();
- }
-
- adjustTouchList(node, touchEvent.touches(), eventPath, eventPathTouches);
- adjustTouchList(node, touchEvent.targetTouches(), eventPath, eventPathTargetTouches);
- adjustTouchList(node, touchEvent.changedTouches(), eventPath, eventPathChangedTouches);
-}
-
-void EventRetargeter::adjustTouchList(const Node* node, const TouchList* touchList, const EventPath& eventPath, EventPathTouchLists& eventPathTouchLists)
-{
- if (!touchList)
- return;
- size_t eventPathSize = eventPath.size();
- ASSERT(eventPathTouchLists.size() == eventPathSize);
- for (size_t i = 0; i < touchList->length(); ++i) {
- const Touch& touch = *touchList->item(i);
- AdjustedNodes adjustedNodes;
- calculateAdjustedNodes(node, touch.target()->toNode(), DoesNotStopAtBoundary, const_cast<EventPath&>(eventPath), adjustedNodes);
- ASSERT(adjustedNodes.size() == eventPathSize);
- for (size_t j = 0; j < eventPathSize; ++j)
- eventPathTouchLists[j]->append(touch.cloneWithNewTarget(adjustedNodes[j].get()));
- }
-}
-
-void EventRetargeter::adjustForRelatedTarget(const Node* node, EventTarget* relatedTarget, EventPath& eventPath)
-{
- if (!node)
- return;
- if (!relatedTarget)
- return;
- Node* relatedNode = relatedTarget->toNode();
- if (!relatedNode)
- return;
- AdjustedNodes adjustedNodes;
- calculateAdjustedNodes(node, relatedNode, StopAtBoundaryIfNeeded, eventPath, adjustedNodes);
- ASSERT(adjustedNodes.size() <= eventPath.size());
- for (size_t i = 0; i < adjustedNodes.size(); ++i) {
- ASSERT(eventPath[i]->isMouseOrFocusEventContext());
- MouseOrFocusEventContext* mouseOrFocusEventContext = static_cast<MouseOrFocusEventContext*>(eventPath[i].get());
- mouseOrFocusEventContext->setRelatedTarget(adjustedNodes[i]);
- }
-}
-
-void EventRetargeter::calculateAdjustedNodes(const Node* node, const Node* relatedNode, EventWithRelatedTargetDispatchBehavior eventWithRelatedTargetDispatchBehavior, EventPath& eventPath, AdjustedNodes& adjustedNodes)
-{
- RelatedNodeMap relatedNodeMap;
- buildRelatedNodeMap(relatedNode, relatedNodeMap);
-
- // Synthetic mouse events can have a relatedTarget which is identical to the target.
- bool targetIsIdenticalToToRelatedTarget = (node == relatedNode);
-
- TreeScope* lastTreeScope = 0;
- Node* adjustedNode = 0;
- for (EventPath::const_iterator iter = eventPath.begin(); iter < eventPath.end(); ++iter) {
- TreeScope* scope = &(*iter)->node()->treeScope();
- if (scope == lastTreeScope) {
- // Re-use the previous adjustedRelatedTarget if treeScope does not change. Just for the performance optimization.
- adjustedNodes.append(adjustedNode);
- } else {
- adjustedNode = findRelatedNode(scope, relatedNodeMap);
- adjustedNodes.append(adjustedNode);
- }
- lastTreeScope = scope;
- if (eventWithRelatedTargetDispatchBehavior == DoesNotStopAtBoundary)
- continue;
- if (targetIsIdenticalToToRelatedTarget) {
- if (node->treeScope().rootNode() == (*iter)->node()) {
- eventPath.shrink(iter + 1 - eventPath.begin());
- break;
- }
- } else if ((*iter)->target() == adjustedNode) {
- // Event dispatching should be stopped here.
- eventPath.shrink(iter - eventPath.begin());
- adjustedNodes.shrink(adjustedNodes.size() - 1);
- break;
- }
- }
-}
-
-void EventRetargeter::buildRelatedNodeMap(const Node* relatedNode, RelatedNodeMap& relatedNodeMap)
-{
- Vector<Node*, 32> relatedNodeStack;
- TreeScope* lastTreeScope = 0;
- for (EventPathWalker walker(relatedNode); walker.node(); walker.moveToParent()) {
- Node* node = walker.node();
- if (relatedNodeStack.isEmpty())
- relatedNodeStack.append(node);
- else if (walker.isVisitingInsertionPointInReprojection())
- relatedNodeStack.append(relatedNodeStack.last());
- TreeScope* scope = &node->treeScope();
- // Skips adding a node to the map if treeScope does not change. Just for the performance optimization.
- if (scope != lastTreeScope)
- relatedNodeMap.add(scope, relatedNodeStack.last());
- lastTreeScope = scope;
- if (node->isShadowRoot()) {
- ASSERT(!relatedNodeStack.isEmpty());
- relatedNodeStack.removeLast();
- }
- }
-}
-
-Node* EventRetargeter::findRelatedNode(TreeScope* scope, RelatedNodeMap& relatedNodeMap)
-{
- Vector<TreeScope*, 32> parentTreeScopes;
- Node* relatedNode = 0;
- while (scope) {
- parentTreeScopes.append(scope);
- RelatedNodeMap::const_iterator found = relatedNodeMap.find(scope);
- if (found != relatedNodeMap.end()) {
- relatedNode = found->value;
- break;
- }
- scope = scope->parentTreeScope();
- }
- for (Vector<TreeScope*, 32>::iterator iter = parentTreeScopes.begin(); iter < parentTreeScopes.end(); ++iter)
- relatedNodeMap.add(*iter, relatedNode);
- return relatedNode;
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/dom/EventRetargeter.h b/chromium/third_party/WebKit/Source/core/dom/EventRetargeter.h
deleted file mode 100644
index ea5b36e8c81..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/EventRetargeter.h
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#ifndef EventRetargeter_h
-#define EventRetargeter_h
-
-#include "SVGNames.h"
-#include "core/dom/ContainerNode.h"
-#include "core/dom/EventContext.h"
-#include "core/dom/shadow/ShadowRoot.h"
-#include "core/svg/SVGElementInstance.h"
-#include "core/svg/SVGUseElement.h"
-#include "wtf/HashMap.h"
-#include "wtf/RefPtr.h"
-
-namespace WebCore {
-
-class EventTarget;
-class FocusEvent;
-class MouseEvent;
-class Node;
-class TouchEvent;
-class TreeScope;
-
-enum EventDispatchBehavior {
- RetargetEvent,
- StayInsideShadowDOM
-};
-
-class EventRetargeter {
-public:
- static void ensureEventPath(Node*, Event*);
- static void adjustForMouseEvent(Node*, MouseEvent&);
- static void adjustForFocusEvent(Node*, FocusEvent&);
- typedef Vector<RefPtr<TouchList> > EventPathTouchLists;
- static void adjustForTouchEvent(Node*, TouchEvent&);
- static EventTarget* eventTargetRespectingTargetRules(Node* referenceNode);
-
-private:
- typedef Vector<RefPtr<Node> > AdjustedNodes;
- typedef HashMap<TreeScope*, Node*> RelatedNodeMap;
- enum EventWithRelatedTargetDispatchBehavior {
- StopAtBoundaryIfNeeded,
- DoesNotStopAtBoundary
- };
- static void calculateEventPath(Node*, Event*);
- static void calculateAdjustedEventPathForEachNode(EventPath&);
-
- static void adjustForRelatedTarget(const Node*, EventTarget* relatedTarget, EventPath&);
- static void calculateAdjustedNodes(const Node*, const Node* relatedNode, EventWithRelatedTargetDispatchBehavior, EventPath&, AdjustedNodes&);
- static void buildRelatedNodeMap(const Node*, RelatedNodeMap&);
- static Node* findRelatedNode(TreeScope*, RelatedNodeMap&);
- static void adjustTouchList(const Node*, const TouchList*, const EventPath&, EventPathTouchLists&);
-};
-
-inline EventTarget* EventRetargeter::eventTargetRespectingTargetRules(Node* referenceNode)
-{
- ASSERT(referenceNode);
-
- if (referenceNode->isPseudoElement())
- return referenceNode->parentNode();
-
- if (!referenceNode->isSVGElement() || !referenceNode->isInShadowTree())
- return referenceNode;
-
- // Spec: The event handling for the non-exposed tree works as if the referenced element had been textually included
- // as a deeply cloned child of the 'use' element, except that events are dispatched to the SVGElementInstance objects.
- Node* rootNode = referenceNode->treeScope().rootNode();
- Element* shadowHostElement = rootNode->isShadowRoot() ? toShadowRoot(rootNode)->host() : 0;
- // At this time, SVG nodes are not supported in non-<use> shadow trees.
- if (!shadowHostElement || !shadowHostElement->hasTagName(SVGNames::useTag))
- return referenceNode;
- SVGUseElement* useElement = toSVGUseElement(shadowHostElement);
- if (SVGElementInstance* instance = useElement->instanceForShadowTreeElement(referenceNode))
- return instance;
-
- return referenceNode;
-}
-
-}
-
-#endif // EventRetargeter_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/EventSender.h b/chromium/third_party/WebKit/Source/core/dom/EventSender.h
deleted file mode 100644
index 51d4c78f646..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/EventSender.h
+++ /dev/null
@@ -1,113 +0,0 @@
-/*
- * Copyright (C) 2012 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef EventSender_h
-#define EventSender_h
-
-#include "core/platform/Timer.h"
-#include "wtf/Vector.h"
-#include "wtf/text/AtomicString.h"
-
-namespace WebCore {
-
-template<typename T> class EventSender {
- WTF_MAKE_NONCOPYABLE(EventSender); WTF_MAKE_FAST_ALLOCATED;
-public:
- explicit EventSender(const AtomicString& eventType);
-
- const AtomicString& eventType() const { return m_eventType; }
- void dispatchEventSoon(T*);
- void cancelEvent(T*);
- void dispatchPendingEvents();
-
-#ifndef NDEBUG
- bool hasPendingEvents(T* sender) const
- {
- return m_dispatchSoonList.find(sender) != kNotFound || m_dispatchingList.find(sender) != kNotFound;
- }
-#endif
-
-private:
- void timerFired(Timer<EventSender<T> >*) { dispatchPendingEvents(); }
-
- AtomicString m_eventType;
- Timer<EventSender<T> > m_timer;
- Vector<T*> m_dispatchSoonList;
- Vector<T*> m_dispatchingList;
-};
-
-template<typename T> EventSender<T>::EventSender(const AtomicString& eventType)
- : m_eventType(eventType)
- , m_timer(this, &EventSender::timerFired)
-{
-}
-
-template<typename T> void EventSender<T>::dispatchEventSoon(T* sender)
-{
- m_dispatchSoonList.append(sender);
- if (!m_timer.isActive())
- m_timer.startOneShot(0);
-}
-
-template<typename T> void EventSender<T>::cancelEvent(T* sender)
-{
- // Remove instances of this sender from both lists.
- // Use loops because we allow multiple instances to get into the lists.
- size_t size = m_dispatchSoonList.size();
- for (size_t i = 0; i < size; ++i) {
- if (m_dispatchSoonList[i] == sender)
- m_dispatchSoonList[i] = 0;
- }
- size = m_dispatchingList.size();
- for (size_t i = 0; i < size; ++i) {
- if (m_dispatchingList[i] == sender)
- m_dispatchingList[i] = 0;
- }
-}
-
-template<typename T> void EventSender<T>::dispatchPendingEvents()
-{
- // Need to avoid re-entering this function; if new dispatches are
- // scheduled before the parent finishes processing the list, they
- // will set a timer and eventually be processed.
- if (!m_dispatchingList.isEmpty())
- return;
-
- m_timer.stop();
-
- m_dispatchingList.swap(m_dispatchSoonList);
- size_t size = m_dispatchingList.size();
- for (size_t i = 0; i < size; ++i) {
- if (T* sender = m_dispatchingList[i]) {
- m_dispatchingList[i] = 0;
- sender->dispatchPendingEvent(this);
- }
- }
- m_dispatchingList.clear();
-}
-
-} // namespace WebCore
-
-#endif // EventSender_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/EventTarget.cpp b/chromium/third_party/WebKit/Source/core/dom/EventTarget.cpp
deleted file mode 100644
index 5745d7f8d95..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/EventTarget.cpp
+++ /dev/null
@@ -1,366 +0,0 @@
-/*
- * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
- * (C) 1999 Antti Koivisto (koivisto@kde.org)
- * (C) 2001 Dirk Mueller (mueller@kde.org)
- * Copyright (C) 2004, 2005, 2006, 2007 Apple Inc. All rights reserved.
- * Copyright (C) 2006 Alexey Proskuryakov (ap@webkit.org)
- * (C) 2007, 2008 Nikolas Zimmermann <zimmermann@kde.org>
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-#include "config.h"
-#include "core/dom/EventTarget.h"
-
-#include "RuntimeEnabledFeatures.h"
-#include "bindings/v8/DOMWrapperWorld.h"
-#include "bindings/v8/ExceptionState.h"
-#include "bindings/v8/ScriptController.h"
-#include "core/dom/Event.h"
-#include "core/dom/ExceptionCode.h"
-#include "core/inspector/InspectorInstrumentation.h"
-#include "core/page/DOMWindow.h"
-#include "wtf/StdLibExtras.h"
-#include "wtf/Vector.h"
-
-using namespace WTF;
-
-namespace WebCore {
-
-EventTargetData::EventTargetData()
-{
-}
-
-EventTargetData::~EventTargetData()
-{
-}
-
-EventTarget::~EventTarget()
-{
-}
-
-Node* EventTarget::toNode()
-{
- return 0;
-}
-
-DOMWindow* EventTarget::toDOMWindow()
-{
- return 0;
-}
-
-MessagePort* EventTarget::toMessagePort()
-{
- return 0;
-}
-
-inline DOMWindow* EventTarget::executingWindow()
-{
- if (ScriptExecutionContext* context = scriptExecutionContext())
- return context->executingWindow();
- return 0;
-}
-
-bool EventTarget::addEventListener(const AtomicString& eventType, PassRefPtr<EventListener> listener, bool useCapture)
-{
- EventTargetData* d = ensureEventTargetData();
- return d->eventListenerMap.add(eventType, listener, useCapture);
-}
-
-bool EventTarget::removeEventListener(const AtomicString& eventType, EventListener* listener, bool useCapture)
-{
- EventTargetData* d = eventTargetData();
- if (!d)
- return false;
-
- size_t indexOfRemovedListener;
-
- if (!d->eventListenerMap.remove(eventType, listener, useCapture, indexOfRemovedListener))
- return false;
-
- // Notify firing events planning to invoke the listener at 'index' that
- // they have one less listener to invoke.
- if (!d->firingEventIterators)
- return true;
- for (size_t i = 0; i < d->firingEventIterators->size(); ++i) {
- FiringEventIterator& firingIterator = d->firingEventIterators->at(i);
- if (eventType != firingIterator.eventType)
- continue;
-
- if (indexOfRemovedListener >= firingIterator.end)
- continue;
-
- --firingIterator.end;
- if (indexOfRemovedListener <= firingIterator.iterator)
- --firingIterator.iterator;
- }
-
- return true;
-}
-
-bool EventTarget::setAttributeEventListener(const AtomicString& eventType, PassRefPtr<EventListener> listener, DOMWrapperWorld* isolatedWorld)
-{
- clearAttributeEventListener(eventType, isolatedWorld);
- if (!listener)
- return false;
- return addEventListener(eventType, listener, false);
-}
-
-EventListener* EventTarget::getAttributeEventListener(const AtomicString& eventType, DOMWrapperWorld* isolatedWorld)
-{
- const EventListenerVector& entry = getEventListeners(eventType);
- for (size_t i = 0; i < entry.size(); ++i) {
- EventListener* listener = entry[i].listener.get();
- if (listener->isAttribute()) {
- DOMWrapperWorld* listenerWorld = listener->world();
- // Worker listener
- if (!listenerWorld) {
- ASSERT(!isolatedWorld);
- return listener;
- }
- if (listenerWorld->isMainWorld() && !isolatedWorld)
- return listener;
- if (listenerWorld == isolatedWorld)
- return listener;
- }
- }
- return 0;
-}
-
-bool EventTarget::clearAttributeEventListener(const AtomicString& eventType, DOMWrapperWorld* isolatedWorld)
-{
- EventListener* listener = getAttributeEventListener(eventType, isolatedWorld);
- if (!listener)
- return false;
- return removeEventListener(eventType, listener, false);
-}
-
-bool EventTarget::dispatchEvent(PassRefPtr<Event> event, ExceptionState& es)
-{
- if (!event || event->type().isEmpty() || event->isBeingDispatched()) {
- es.throwDOMException(InvalidStateError);
- return false;
- }
-
- if (!scriptExecutionContext())
- return false;
-
- return dispatchEvent(event);
-}
-
-bool EventTarget::dispatchEvent(PassRefPtr<Event> event)
-{
- event->setTarget(this);
- event->setCurrentTarget(this);
- event->setEventPhase(Event::AT_TARGET);
- bool defaultPrevented = fireEventListeners(event.get());
- event->setEventPhase(0);
- return defaultPrevented;
-}
-
-void EventTarget::uncaughtExceptionInEventHandler()
-{
-}
-
-static AtomicString legacyType(const Event* event)
-{
- if (event->type() == eventNames().transitionendEvent)
- return eventNames().webkitTransitionEndEvent;
-
- if (event->type() == eventNames().animationstartEvent)
- return eventNames().webkitAnimationStartEvent;
-
- if (event->type() == eventNames().animationendEvent)
- return eventNames().webkitAnimationEndEvent;
-
- if (event->type() == eventNames().animationiterationEvent)
- return eventNames().webkitAnimationIterationEvent;
-
- if (event->type() == eventNames().wheelEvent)
- return eventNames().mousewheelEvent;
-
- return emptyString();
-}
-
-void EventTarget::countLegacyEvents(const AtomicString& legacyTypeName, EventListenerVector* listenersVector, EventListenerVector* legacyListenersVector)
-{
- UseCounter::Feature unprefixedFeature;
- UseCounter::Feature prefixedFeature;
- UseCounter::Feature prefixedAndUnprefixedFeature;
- bool shouldCount = false;
-
- if (legacyTypeName == eventNames().webkitTransitionEndEvent) {
- prefixedFeature = UseCounter::PrefixedTransitionEndEvent;
- unprefixedFeature = UseCounter::UnprefixedTransitionEndEvent;
- prefixedAndUnprefixedFeature = UseCounter::PrefixedAndUnprefixedTransitionEndEvent;
- shouldCount = true;
- } else if (legacyTypeName == eventNames().webkitAnimationEndEvent) {
- prefixedFeature = UseCounter::PrefixedAnimationEndEvent;
- unprefixedFeature = UseCounter::UnprefixedAnimationEndEvent;
- prefixedAndUnprefixedFeature = UseCounter::PrefixedAndUnprefixedAnimationEndEvent;
- shouldCount = true;
- } else if (legacyTypeName == eventNames().webkitAnimationStartEvent) {
- prefixedFeature = UseCounter::PrefixedAnimationStartEvent;
- unprefixedFeature = UseCounter::UnprefixedAnimationStartEvent;
- prefixedAndUnprefixedFeature = UseCounter::PrefixedAndUnprefixedAnimationStartEvent;
- shouldCount = true;
- } else if (legacyTypeName == eventNames().webkitAnimationIterationEvent) {
- prefixedFeature = UseCounter::PrefixedAnimationIterationEvent;
- unprefixedFeature = UseCounter::UnprefixedAnimationIterationEvent;
- prefixedAndUnprefixedFeature = UseCounter::PrefixedAndUnprefixedAnimationIterationEvent;
- shouldCount = true;
- }
-
- if (shouldCount) {
- if (DOMWindow* executingWindow = this->executingWindow()) {
- if (legacyListenersVector) {
- if (listenersVector)
- UseCounter::count(executingWindow, prefixedAndUnprefixedFeature);
- else
- UseCounter::count(executingWindow, prefixedFeature);
- } else if (listenersVector) {
- UseCounter::count(executingWindow, unprefixedFeature);
- }
- }
- }
-}
-
-bool EventTarget::fireEventListeners(Event* event)
-{
- ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
- ASSERT(event && !event->type().isEmpty());
-
- EventTargetData* d = eventTargetData();
- if (!d)
- return true;
-
- EventListenerVector* legacyListenersVector = 0;
- AtomicString legacyTypeName = legacyType(event);
- if (!legacyTypeName.isEmpty())
- legacyListenersVector = d->eventListenerMap.find(legacyTypeName);
-
- EventListenerVector* listenersVector = d->eventListenerMap.find(event->type());
- if (!RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled() && (event->type() == eventNames().animationiterationEvent || event->type() == eventNames().animationendEvent
- || event->type() == eventNames().animationstartEvent))
- listenersVector = 0;
-
- if (listenersVector) {
- fireEventListeners(event, d, *listenersVector);
- } else if (legacyListenersVector) {
- AtomicString unprefixedTypeName = event->type();
- event->setType(legacyTypeName);
- fireEventListeners(event, d, *legacyListenersVector);
- event->setType(unprefixedTypeName);
- }
-
- countLegacyEvents(legacyTypeName, listenersVector, legacyListenersVector);
- return !event->defaultPrevented();
-}
-
-void EventTarget::fireEventListeners(Event* event, EventTargetData* d, EventListenerVector& entry)
-{
- RefPtr<EventTarget> protect = this;
-
- // Fire all listeners registered for this event. Don't fire listeners removed
- // during event dispatch. Also, don't fire event listeners added during event
- // dispatch. Conveniently, all new event listeners will be added after or at
- // index |size|, so iterating up to (but not including) |size| naturally excludes
- // new event listeners.
-
- if (event->type() == eventNames().beforeunloadEvent) {
- if (DOMWindow* executingWindow = this->executingWindow()) {
- if (executingWindow->top())
- UseCounter::count(executingWindow, UseCounter::SubFrameBeforeUnloadFired);
- }
- }
-
- bool userEventWasHandled = false;
- size_t i = 0;
- size_t size = entry.size();
- if (!d->firingEventIterators)
- d->firingEventIterators = adoptPtr(new FiringEventIteratorVector);
- d->firingEventIterators->append(FiringEventIterator(event->type(), i, size));
- for ( ; i < size; ++i) {
- RegisteredEventListener& registeredListener = entry[i];
- if (event->eventPhase() == Event::CAPTURING_PHASE && !registeredListener.useCapture)
- continue;
- if (event->eventPhase() == Event::BUBBLING_PHASE && registeredListener.useCapture)
- continue;
-
- // If stopImmediatePropagation has been called, we just break out immediately, without
- // handling any more events on this target.
- if (event->immediatePropagationStopped())
- break;
-
- ScriptExecutionContext* context = scriptExecutionContext();
- if (!context)
- break;
-
- InspectorInstrumentationCookie cookie = InspectorInstrumentation::willHandleEvent(context, event);
- // To match Mozilla, the AT_TARGET phase fires both capturing and bubbling
- // event listeners, even though that violates some versions of the DOM spec.
- registeredListener.listener->handleEvent(context, event);
- if (!userEventWasHandled && ScriptController::processingUserGesture())
- userEventWasHandled = true;
- InspectorInstrumentation::didHandleEvent(cookie);
- }
- d->firingEventIterators->removeLast();
- if (userEventWasHandled) {
- if (ScriptExecutionContext* context = scriptExecutionContext())
- context->userEventWasHandled();
- }
-}
-
-const EventListenerVector& EventTarget::getEventListeners(const AtomicString& eventType)
-{
- DEFINE_STATIC_LOCAL(EventListenerVector, emptyVector, ());
-
- EventTargetData* d = eventTargetData();
- if (!d)
- return emptyVector;
-
- EventListenerVector* listenerVector = d->eventListenerMap.find(eventType);
- if (!listenerVector)
- return emptyVector;
-
- return *listenerVector;
-}
-
-void EventTarget::removeAllEventListeners()
-{
- EventTargetData* d = eventTargetData();
- if (!d)
- return;
- d->eventListenerMap.clear();
-
- // Notify firing events planning to invoke the listener at 'index' that
- // they have one less listener to invoke.
- if (d->firingEventIterators) {
- for (size_t i = 0; i < d->firingEventIterators->size(); ++i) {
- d->firingEventIterators->at(i).iterator = 0;
- d->firingEventIterators->at(i).end = 0;
- }
- }
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/EventTarget.h b/chromium/third_party/WebKit/Source/core/dom/EventTarget.h
deleted file mode 100644
index 3a5dc0ab9cb..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/EventTarget.h
+++ /dev/null
@@ -1,213 +0,0 @@
-/*
- * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
- * (C) 1999 Antti Koivisto (koivisto@kde.org)
- * (C) 2001 Dirk Mueller (mueller@kde.org)
- * Copyright (C) 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
- * Copyright (C) 2006 Alexey Proskuryakov (ap@webkit.org)
- * (C) 2007, 2008 Nikolas Zimmermann <zimmermann@kde.org>
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-#ifndef EventTarget_h
-#define EventTarget_h
-
-#include "core/dom/EventListenerMap.h"
-#include "core/dom/EventNames.h"
-#include "wtf/Forward.h"
-
-namespace WebCore {
-
- class ApplicationCache;
- class AudioContext;
- class DOMWindow;
- class DedicatedWorkerGlobalScope;
- class Event;
- class EventListener;
- class EventSource;
- class ExceptionState;
- class FileReader;
- class FileWriter;
- class IDBDatabase;
- class IDBRequest;
- class IDBTransaction;
- class MIDIAccess;
- class MIDIInput;
- class MIDIPort;
- class MediaController;
- class MediaStream;
- class MessagePort;
- class NamedFlow;
- class Node;
- class Notification;
- class SVGElementInstance;
- class ScriptExecutionContext;
- class ScriptProcessorNode;
- class SharedWorker;
- class SharedWorkerGlobalScope;
- class TextTrack;
- class TextTrackCue;
- class WebSocket;
- class Worker;
- class XMLHttpRequest;
- class XMLHttpRequestUpload;
-
- struct FiringEventIterator {
- FiringEventIterator(const AtomicString& eventType, size_t& iterator, size_t& end)
- : eventType(eventType)
- , iterator(iterator)
- , end(end)
- {
- }
-
- const AtomicString& eventType;
- size_t& iterator;
- size_t& end;
- };
- typedef Vector<FiringEventIterator, 1> FiringEventIteratorVector;
-
- struct EventTargetData {
- WTF_MAKE_NONCOPYABLE(EventTargetData); WTF_MAKE_FAST_ALLOCATED;
- public:
- EventTargetData();
- ~EventTargetData();
-
- EventListenerMap eventListenerMap;
- OwnPtr<FiringEventIteratorVector> firingEventIterators;
- };
-
- class EventTarget {
- public:
- void ref() { refEventTarget(); }
- void deref() { derefEventTarget(); }
-
- virtual const AtomicString& interfaceName() const = 0;
- virtual ScriptExecutionContext* scriptExecutionContext() const = 0;
-
- virtual Node* toNode();
- virtual DOMWindow* toDOMWindow();
- virtual MessagePort* toMessagePort();
-
- virtual bool addEventListener(const AtomicString& eventType, PassRefPtr<EventListener>, bool useCapture);
- virtual bool removeEventListener(const AtomicString& eventType, EventListener*, bool useCapture);
- virtual void removeAllEventListeners();
- virtual bool dispatchEvent(PassRefPtr<Event>);
- bool dispatchEvent(PassRefPtr<Event>, ExceptionState&); // DOM API
- virtual void uncaughtExceptionInEventHandler();
-
- // Used for legacy "onEvent" attribute APIs.
- bool setAttributeEventListener(const AtomicString& eventType, PassRefPtr<EventListener>, DOMWrapperWorld* isolatedWorld = 0);
- EventListener* getAttributeEventListener(const AtomicString& eventType, DOMWrapperWorld* isolatedWorld = 0);
-
- bool hasEventListeners();
- bool hasEventListeners(const AtomicString& eventType);
- bool hasCapturingEventListeners(const AtomicString& eventType);
- const EventListenerVector& getEventListeners(const AtomicString& eventType);
-
- bool fireEventListeners(Event*);
- bool isFiringEventListeners();
-
- protected:
- virtual ~EventTarget();
-
- virtual EventTargetData* eventTargetData() = 0;
- virtual EventTargetData* ensureEventTargetData() = 0;
-
- private:
- virtual void refEventTarget() = 0;
- virtual void derefEventTarget() = 0;
-
- DOMWindow* executingWindow();
- void fireEventListeners(Event*, EventTargetData*, EventListenerVector&);
- void countLegacyEvents(const AtomicString& legacyTypeName, EventListenerVector*, EventListenerVector*);
-
- bool clearAttributeEventListener(const AtomicString& eventType, DOMWrapperWorld* isolatedWorld);
-
- friend class EventListenerIterator;
- };
-
- // FIXME: These macros should be split into separate DEFINE and DECLARE
- // macros to avoid causing so many header includes.
- #define DEFINE_ATTRIBUTE_EVENT_LISTENER(attribute) \
- EventListener* on##attribute(DOMWrapperWorld* isolatedWorld) { return getAttributeEventListener(eventNames().attribute##Event, isolatedWorld); } \
- void setOn##attribute(PassRefPtr<EventListener> listener, DOMWrapperWorld* isolatedWorld = 0) { setAttributeEventListener(eventNames().attribute##Event, listener, isolatedWorld); } \
-
- #define DECLARE_VIRTUAL_ATTRIBUTE_EVENT_LISTENER(attribute) \
- virtual EventListener* on##attribute(DOMWrapperWorld* isolatedWorld); \
- virtual void setOn##attribute(PassRefPtr<EventListener>, DOMWrapperWorld* isolatedWorld); \
-
- #define DEFINE_VIRTUAL_ATTRIBUTE_EVENT_LISTENER(type, attribute) \
- EventListener* type::on##attribute(DOMWrapperWorld* isolatedWorld) { return getAttributeEventListener(eventNames().attribute##Event, isolatedWorld); } \
- void type::setOn##attribute(PassRefPtr<EventListener> listener, DOMWrapperWorld* isolatedWorld) { setAttributeEventListener(eventNames().attribute##Event, listener, isolatedWorld); } \
-
- #define DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(attribute) \
- EventListener* on##attribute(DOMWrapperWorld* isolatedWorld) { return document().getWindowAttributeEventListener(eventNames().attribute##Event, isolatedWorld); } \
- void setOn##attribute(PassRefPtr<EventListener> listener, DOMWrapperWorld* isolatedWorld) { document().setWindowAttributeEventListener(eventNames().attribute##Event, listener, isolatedWorld); } \
-
- #define DEFINE_MAPPED_ATTRIBUTE_EVENT_LISTENER(attribute, eventName) \
- EventListener* on##attribute(DOMWrapperWorld* isolatedWorld) { return getAttributeEventListener(eventNames().eventName##Event, isolatedWorld); } \
- void setOn##attribute(PassRefPtr<EventListener> listener, DOMWrapperWorld* isolatedWorld) { setAttributeEventListener(eventNames().eventName##Event, listener, isolatedWorld); } \
-
- #define DECLARE_FORWARDING_ATTRIBUTE_EVENT_LISTENER(recipient, attribute) \
- EventListener* on##attribute(DOMWrapperWorld* isolatedWorld); \
- void setOn##attribute(PassRefPtr<EventListener> listener, DOMWrapperWorld* isolatedWorld);
-
- #define DEFINE_FORWARDING_ATTRIBUTE_EVENT_LISTENER(type, recipient, attribute) \
- EventListener* type::on##attribute(DOMWrapperWorld* isolatedWorld) { return recipient ? recipient->getAttributeEventListener(eventNames().attribute##Event, isolatedWorld) : 0; } \
- void type::setOn##attribute(PassRefPtr<EventListener> listener, DOMWrapperWorld* isolatedWorld) { if (recipient) recipient->setAttributeEventListener(eventNames().attribute##Event, listener, isolatedWorld); }
-
- inline bool EventTarget::isFiringEventListeners()
- {
- EventTargetData* d = eventTargetData();
- if (!d)
- return false;
- return d->firingEventIterators && !d->firingEventIterators->isEmpty();
- }
-
- inline bool EventTarget::hasEventListeners()
- {
- EventTargetData* d = eventTargetData();
- if (!d)
- return false;
- return !d->eventListenerMap.isEmpty();
- }
-
- inline bool EventTarget::hasEventListeners(const AtomicString& eventType)
- {
- EventTargetData* d = eventTargetData();
- if (!d)
- return false;
- return d->eventListenerMap.contains(eventType);
- }
-
- inline bool EventTarget::hasCapturingEventListeners(const AtomicString& eventType)
- {
- EventTargetData* d = eventTargetData();
- if (!d)
- return false;
- return d->eventListenerMap.containsCapturing(eventType);
- }
-
-} // namespace WebCore
-
-#endif // EventTarget_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/EventTarget.idl b/chromium/third_party/WebKit/Source/core/dom/EventTarget.idl
deleted file mode 100644
index 7c870369a03..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/EventTarget.idl
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright (C) 2006, 2007 Apple Inc. All rights reserved.
- * Copyright (C) 2006 Samuel Weinig <sam.weinig@gmail.com>
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-[
- CustomToV8,
- DoNotGenerateWrap
-] interface EventTarget {
- void addEventListener(DOMString type,
- EventListener listener,
- optional boolean useCapture);
- void removeEventListener(DOMString type,
- EventListener listener,
- optional boolean useCapture);
- [RaisesException] boolean dispatchEvent(Event event);
-};
diff --git a/chromium/third_party/WebKit/Source/core/dom/EventTargetFactory.in b/chromium/third_party/WebKit/Source/core/dom/EventTargetFactory.in
deleted file mode 100644
index 9ead7d2707a..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/EventTargetFactory.in
+++ /dev/null
@@ -1,47 +0,0 @@
-namespace="EventTarget"
-
-core/css/FontFaceSet
-core/dom/MessagePort
-core/dom/Node
-core/dom/WebKitNamedFlow ImplementedAs=NamedFlow
-core/fileapi/FileReader
-core/html/MediaController
-core/html/track/TextTrack
-core/html/track/TextTrackCue
-core/html/track/TextTrackList
-core/loader/appcache/ApplicationCache
-core/page/EventSource
-core/page/Performance
-core/page/Window ImplementedAs=DOMWindow
-core/svg/SVGElementInstance
-core/workers/DedicatedWorkerGlobalScope
-core/workers/SharedWorker
-core/workers/SharedWorkerGlobalScope
-core/workers/Worker
-core/xml/XMLHttpRequest
-core/xml/XMLHttpRequestUpload
-modules/encryptedmedia/MediaKeySession Conditional=ENCRYPTED_MEDIA_V2
-modules/filesystem/FileWriter
-modules/indexeddb/IDBDatabase
-modules/indexeddb/IDBOpenDBRequest
-modules/indexeddb/IDBRequest
-modules/indexeddb/IDBTransaction
-modules/mediasource/MediaSource
-modules/mediasource/SourceBuffer
-modules/mediasource/SourceBufferList
-modules/mediasource/WebKitMediaSource
-modules/mediasource/WebKitSourceBufferList
-modules/mediastream/MediaStream
-modules/mediastream/MediaStreamTrack
-modules/mediastream/RTCDTMFSender
-modules/mediastream/RTCDataChannel
-modules/mediastream/RTCPeerConnection
-modules/notifications/Notification
-modules/speech/SpeechRecognition
-modules/speech/SpeechSynthesisUtterance
-modules/webaudio/AudioContext Conditional=WEB_AUDIO
-modules/webaudio/AudioNode Conditional=WEB_AUDIO
-modules/webmidi/MIDIAccess
-modules/webmidi/MIDIInput
-modules/webmidi/MIDIPort
-modules/websockets/WebSocket
diff --git a/chromium/third_party/WebKit/Source/core/dom/ExecutionContext.cpp b/chromium/third_party/WebKit/Source/core/dom/ExecutionContext.cpp
new file mode 100644
index 00000000000..1f62b74cfef
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/ExecutionContext.cpp
@@ -0,0 +1,337 @@
+/*
+ * Copyright (C) 2008 Apple Inc. All Rights Reserved.
+ * Copyright (C) 2012 Google Inc. All Rights Reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "config.h"
+#include "core/dom/ExecutionContext.h"
+
+#include "core/dom/AddConsoleMessageTask.h"
+#include "core/dom/ContextLifecycleNotifier.h"
+#include "core/dom/ExecutionContextTask.h"
+#include "core/events/EventTarget.h"
+#include "core/html/PublicURLManager.h"
+#include "core/inspector/InspectorInstrumentation.h"
+#include "core/inspector/ScriptCallStack.h"
+#include "core/workers/WorkerGlobalScope.h"
+#include "core/workers/WorkerThread.h"
+#include "wtf/MainThread.h"
+
+namespace WebCore {
+
+class ExecutionContext::PendingException {
+ WTF_MAKE_NONCOPYABLE(PendingException);
+public:
+ PendingException(const String& errorMessage, int lineNumber, int columnNumber, const String& sourceURL, PassRefPtr<ScriptCallStack> callStack)
+ : m_errorMessage(errorMessage)
+ , m_lineNumber(lineNumber)
+ , m_columnNumber(columnNumber)
+ , m_sourceURL(sourceURL)
+ , m_callStack(callStack)
+ {
+ }
+ String m_errorMessage;
+ int m_lineNumber;
+ int m_columnNumber;
+ String m_sourceURL;
+ RefPtr<ScriptCallStack> m_callStack;
+};
+
+ExecutionContext::ExecutionContext()
+ : m_client(0)
+ , m_sandboxFlags(SandboxNone)
+ , m_circularSequentialID(0)
+ , m_inDispatchErrorEvent(false)
+ , m_activeDOMObjectsAreSuspended(false)
+ , m_activeDOMObjectsAreStopped(false)
+{
+}
+
+ExecutionContext::~ExecutionContext()
+{
+}
+
+bool ExecutionContext::hasPendingActivity()
+{
+ return lifecycleNotifier().hasPendingActivity();
+}
+
+void ExecutionContext::suspendActiveDOMObjects()
+{
+ lifecycleNotifier().notifySuspendingActiveDOMObjects();
+ m_activeDOMObjectsAreSuspended = true;
+}
+
+void ExecutionContext::resumeActiveDOMObjects()
+{
+ m_activeDOMObjectsAreSuspended = false;
+ lifecycleNotifier().notifyResumingActiveDOMObjects();
+}
+
+void ExecutionContext::stopActiveDOMObjects()
+{
+ m_activeDOMObjectsAreStopped = true;
+ lifecycleNotifier().notifyStoppingActiveDOMObjects();
+}
+
+void ExecutionContext::suspendScheduledTasks()
+{
+ suspendActiveDOMObjects();
+ if (m_client)
+ m_client->tasksWereSuspended();
+}
+
+void ExecutionContext::resumeScheduledTasks()
+{
+ resumeActiveDOMObjects();
+ if (m_client)
+ m_client->tasksWereResumed();
+}
+
+void ExecutionContext::suspendActiveDOMObjectIfNeeded(ActiveDOMObject* object)
+{
+ ASSERT(lifecycleNotifier().contains(object));
+ // Ensure all ActiveDOMObjects are suspended also newly created ones.
+ if (m_activeDOMObjectsAreSuspended)
+ object->suspend();
+}
+
+bool ExecutionContext::shouldSanitizeScriptError(const String& sourceURL, AccessControlStatus corsStatus)
+{
+ return !(securityOrigin()->canRequest(completeURL(sourceURL)) || corsStatus == SharableCrossOrigin);
+}
+
+void ExecutionContext::reportException(PassRefPtr<ErrorEvent> event, PassRefPtr<ScriptCallStack> callStack, AccessControlStatus corsStatus)
+{
+ RefPtr<ErrorEvent> errorEvent = event;
+ if (m_inDispatchErrorEvent) {
+ if (!m_pendingExceptions)
+ m_pendingExceptions = adoptPtr(new Vector<OwnPtr<PendingException> >());
+ m_pendingExceptions->append(adoptPtr(new PendingException(errorEvent->messageForConsole(), errorEvent->lineno(), errorEvent->colno(), errorEvent->filename(), callStack)));
+ return;
+ }
+
+ // First report the original exception and only then all the nested ones.
+ if (!dispatchErrorEvent(errorEvent, corsStatus) && m_client)
+ m_client->logExceptionToConsole(errorEvent->messageForConsole(), errorEvent->filename(), errorEvent->lineno(), errorEvent->colno(), callStack);
+
+ if (!m_pendingExceptions)
+ return;
+
+ for (size_t i = 0; i < m_pendingExceptions->size(); i++) {
+ PendingException* e = m_pendingExceptions->at(i).get();
+ if (m_client)
+ m_client->logExceptionToConsole(e->m_errorMessage, e->m_sourceURL, e->m_lineNumber, e->m_columnNumber, e->m_callStack);
+ }
+ m_pendingExceptions.clear();
+}
+
+void ExecutionContext::addConsoleMessage(MessageSource source, MessageLevel level, const String& message, const String& sourceURL, unsigned lineNumber)
+{
+ if (!m_client)
+ return;
+ m_client->addMessage(source, level, message, sourceURL, lineNumber, 0);
+}
+
+void ExecutionContext::addConsoleMessage(MessageSource source, MessageLevel level, const String& message, ScriptState* state)
+{
+ if (!m_client)
+ return;
+ m_client->addMessage(source, level, message, String(), 0, state);
+}
+
+bool ExecutionContext::dispatchErrorEvent(PassRefPtr<ErrorEvent> event, AccessControlStatus corsStatus)
+{
+ if (!m_client)
+ return false;
+ EventTarget* target = m_client->errorEventTarget();
+ if (!target)
+ return false;
+
+ RefPtr<ErrorEvent> errorEvent = event;
+ if (shouldSanitizeScriptError(errorEvent->filename(), corsStatus))
+ errorEvent = ErrorEvent::createSanitizedError(errorEvent->world());
+
+ ASSERT(!m_inDispatchErrorEvent);
+ m_inDispatchErrorEvent = true;
+ target->dispatchEvent(errorEvent);
+ m_inDispatchErrorEvent = false;
+ return errorEvent->defaultPrevented();
+}
+
+int ExecutionContext::circularSequentialID()
+{
+ ++m_circularSequentialID;
+ if (m_circularSequentialID <= 0)
+ m_circularSequentialID = 1;
+ return m_circularSequentialID;
+}
+
+int ExecutionContext::installNewTimeout(PassOwnPtr<ScheduledAction> action, int timeout, bool singleShot)
+{
+ int timeoutID;
+ while (true) {
+ timeoutID = circularSequentialID();
+ if (!m_timeouts.contains(timeoutID))
+ break;
+ }
+ TimeoutMap::AddResult result = m_timeouts.add(timeoutID, DOMTimer::create(this, action, timeout, singleShot, timeoutID));
+ ASSERT(result.isNewEntry);
+ DOMTimer* timer = result.iterator->value.get();
+
+ timer->suspendIfNeeded();
+
+ return timer->timeoutID();
+}
+
+void ExecutionContext::removeTimeoutByID(int timeoutID)
+{
+ if (timeoutID <= 0)
+ return;
+ m_timeouts.remove(timeoutID);
+}
+
+PublicURLManager& ExecutionContext::publicURLManager()
+{
+ if (!m_publicURLManager)
+ m_publicURLManager = PublicURLManager::create(this);
+ return *m_publicURLManager;
+}
+
+void ExecutionContext::didChangeTimerAlignmentInterval()
+{
+ for (TimeoutMap::iterator iter = m_timeouts.begin(); iter != m_timeouts.end(); ++iter)
+ iter->value->didChangeAlignmentInterval();
+}
+
+SecurityOrigin* ExecutionContext::securityOrigin() const
+{
+ RELEASE_ASSERT(m_client);
+ return m_client->securityContext().securityOrigin();
+}
+
+ContentSecurityPolicy* ExecutionContext::contentSecurityPolicy() const
+{
+ RELEASE_ASSERT(m_client);
+ return m_client->securityContext().contentSecurityPolicy();
+}
+
+const KURL& ExecutionContext::url() const
+{
+ if (!m_client) {
+ DEFINE_STATIC_LOCAL(KURL, emptyURL, ());
+ return emptyURL;
+ }
+
+ return m_client->virtualURL();
+}
+
+KURL ExecutionContext::completeURL(const String& url) const
+{
+
+ if (!m_client) {
+ DEFINE_STATIC_LOCAL(KURL, emptyURL, ());
+ return emptyURL;
+ }
+
+ return m_client->virtualCompleteURL(url);
+}
+
+void ExecutionContext::userEventWasHandled()
+{
+ if (!m_client)
+ return;
+ m_client->userEventWasHandled();
+}
+
+void ExecutionContext::disableEval(const String& errorMessage)
+{
+ if (!m_client)
+ return;
+ return m_client->disableEval(errorMessage);
+}
+
+DOMWindow* ExecutionContext::executingWindow() const
+{
+ RELEASE_ASSERT(m_client);
+ return m_client->executingWindow();
+}
+
+String ExecutionContext::userAgent(const KURL& url) const
+{
+ if (!m_client)
+ return String();
+ return m_client->userAgent(url);
+}
+
+double ExecutionContext::timerAlignmentInterval() const
+{
+ if (!m_client)
+ return DOMTimer::visiblePageAlignmentInterval();
+ return m_client->timerAlignmentInterval();
+}
+
+void ExecutionContext::postTask(PassOwnPtr<ExecutionContextTask> task)
+{
+ if (!m_client)
+ return;
+ m_client->postTask(task);
+}
+
+void ExecutionContext::postTask(const Closure& closure)
+{
+ if (!m_client)
+ return;
+ m_client->postTask(CallClosureTask::create(closure));
+}
+
+PassOwnPtr<LifecycleNotifier<ExecutionContext> > ExecutionContext::createLifecycleNotifier()
+{
+ return ContextLifecycleNotifier::create(this);
+}
+
+ContextLifecycleNotifier& ExecutionContext::lifecycleNotifier()
+{
+ return static_cast<ContextLifecycleNotifier&>(LifecycleContext<ExecutionContext>::lifecycleNotifier());
+}
+
+bool ExecutionContext::isIteratingOverObservers() const
+{
+ return m_lifecycleNotifier && m_lifecycleNotifier->isIteratingOverObservers();
+}
+
+void ExecutionContext::enforceSandboxFlags(SandboxFlags mask)
+{
+ m_sandboxFlags |= mask;
+
+ RELEASE_ASSERT(m_client);
+ // The SandboxOrigin is stored redundantly in the security origin.
+ if (isSandboxed(SandboxOrigin) && m_client->securityContext().securityOrigin() && !m_client->securityContext().securityOrigin()->isUnique()) {
+ m_client->securityContext().setSecurityOrigin(SecurityOrigin::createUnique());
+ m_client->didUpdateSecurityOrigin();
+ }
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/ExecutionContext.h b/chromium/third_party/WebKit/Source/core/dom/ExecutionContext.h
new file mode 100644
index 00000000000..3fb01bb79f8
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/ExecutionContext.h
@@ -0,0 +1,167 @@
+/*
+ * Copyright (C) 2008 Apple Inc. All Rights Reserved.
+ * Copyright (C) 2012 Google Inc. All Rights Reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#ifndef ExecutionContext_h
+#define ExecutionContext_h
+
+#include "core/dom/ActiveDOMObject.h"
+#include "core/dom/ExecutionContextClient.h"
+#include "core/dom/SandboxFlags.h"
+#include "core/dom/SecurityContext.h"
+#include "core/events/ErrorEvent.h"
+#include "core/fetch/CrossOriginAccessControl.h"
+#include "core/frame/ConsoleTypes.h"
+#include "core/frame/DOMTimer.h"
+#include "platform/LifecycleContext.h"
+#include "platform/weborigin/KURL.h"
+#include "wtf/Functional.h"
+#include "wtf/OwnPtr.h"
+#include "wtf/PassOwnPtr.h"
+
+namespace WTF {
+class OrdinalNumber;
+}
+
+namespace WebCore {
+
+class ContextLifecycleNotifier;
+class DOMWindow;
+class EventListener;
+class EventQueue;
+class EventTarget;
+class ExecutionContextTask;
+class PublicURLManager;
+class SecurityOrigin;
+class ScriptCallStack;
+class ScriptState;
+
+class ExecutionContext : public LifecycleContext<ExecutionContext> {
+public:
+ ExecutionContext();
+ virtual ~ExecutionContext();
+
+ // Delegating to ExecutionContextClient
+ void setClient(ExecutionContextClient* client) { m_client = client; }
+ bool isDocument() const { return m_client && m_client->isDocument(); }
+ bool isWorkerGlobalScope() const { return m_client && m_client->isWorkerGlobalScope(); }
+ bool isJSExecutionForbidden() { return m_client && m_client->isJSExecutionForbidden(); }
+ SecurityOrigin* securityOrigin() const;
+ ContentSecurityPolicy* contentSecurityPolicy() const;
+ const KURL& url() const;
+ KURL completeURL(const String& url) const;
+ void userEventWasHandled();
+ void disableEval(const String& errorMessage);
+ DOMWindow* executingWindow() const;
+ String userAgent(const KURL&) const;
+ void postTask(PassOwnPtr<ExecutionContextTask>);
+ void postTask(const Closure&);
+ double timerAlignmentInterval() const;
+
+ bool shouldSanitizeScriptError(const String& sourceURL, AccessControlStatus);
+ void reportException(PassRefPtr<ErrorEvent>, PassRefPtr<ScriptCallStack>, AccessControlStatus);
+
+ void addConsoleMessage(MessageSource, MessageLevel, const String& message, const String& sourceURL, unsigned lineNumber);
+ void addConsoleMessage(MessageSource, MessageLevel, const String& message, ScriptState* = 0);
+
+ PublicURLManager& publicURLManager();
+
+ // Active objects are not garbage collected even if inaccessible, e.g. because their activity may result in callbacks being invoked.
+ bool hasPendingActivity();
+
+ void suspendActiveDOMObjects();
+ void resumeActiveDOMObjects();
+ void stopActiveDOMObjects();
+
+ virtual void suspendScheduledTasks();
+ virtual void resumeScheduledTasks();
+ virtual bool tasksNeedSuspension() { return false; }
+
+ bool activeDOMObjectsAreSuspended() const { return m_activeDOMObjectsAreSuspended; }
+ bool activeDOMObjectsAreStopped() const { return m_activeDOMObjectsAreStopped; }
+ bool isIteratingOverObservers() const;
+
+ // Called after the construction of an ActiveDOMObject to synchronize suspend state.
+ void suspendActiveDOMObjectIfNeeded(ActiveDOMObject*);
+
+ void ref() { refExecutionContext(); }
+ void deref() { derefExecutionContext(); }
+
+ // Gets the next id in a circular sequence from 1 to 2^31-1.
+ int circularSequentialID();
+
+ void didChangeTimerAlignmentInterval();
+
+ SandboxFlags sandboxFlags() const { return m_sandboxFlags; }
+ bool isSandboxed(SandboxFlags mask) const { return m_sandboxFlags & mask; }
+ void enforceSandboxFlags(SandboxFlags mask);
+
+ PassOwnPtr<LifecycleNotifier<ExecutionContext> > createLifecycleNotifier();
+
+ virtual EventQueue* eventQueue() const = 0;
+
+protected:
+
+ ContextLifecycleNotifier& lifecycleNotifier();
+
+private:
+ friend class DOMTimer; // For installNewTimeout() and removeTimeoutByID() below.
+
+ bool dispatchErrorEvent(PassRefPtr<ErrorEvent>, AccessControlStatus);
+
+ virtual void refExecutionContext() = 0;
+ virtual void derefExecutionContext() = 0;
+ // LifecycleContext implementation.
+
+ // Implementation details for DOMTimer. No other classes should call these functions.
+ int installNewTimeout(PassOwnPtr<ScheduledAction>, int timeout, bool singleShot);
+ void removeTimeoutByID(int timeoutID); // This makes underlying DOMTimer instance destructed.
+
+ ExecutionContextClient* m_client;
+ SandboxFlags m_sandboxFlags;
+
+ int m_circularSequentialID;
+ typedef HashMap<int, OwnPtr<DOMTimer> > TimeoutMap;
+ TimeoutMap m_timeouts;
+
+ bool m_inDispatchErrorEvent;
+ class PendingException;
+ OwnPtr<Vector<OwnPtr<PendingException> > > m_pendingExceptions;
+
+ bool m_activeDOMObjectsAreSuspended;
+ bool m_activeDOMObjectsAreStopped;
+
+ OwnPtr<PublicURLManager> m_publicURLManager;
+
+ // The location of this member is important; to make sure contextDestroyed() notification on
+ // ExecutionContext's members (notably m_timeouts) is called before they are destructed,
+ // m_lifecycleNotifer should be placed *after* such members.
+ OwnPtr<ContextLifecycleNotifier> m_lifecycleNotifier;
+};
+
+} // namespace WebCore
+
+#endif // ExecutionContext_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/ExecutionContextClient.h b/chromium/third_party/WebKit/Source/core/dom/ExecutionContextClient.h
new file mode 100644
index 00000000000..4293c744c09
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/ExecutionContextClient.h
@@ -0,0 +1,86 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef ExecutionContextClient_h
+#define ExecutionContextClient_h
+
+#include "core/frame/ConsoleTypes.h"
+#include "platform/LifecycleNotifier.h"
+#include "platform/weborigin/KURL.h"
+#include "wtf/Forward.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/text/WTFString.h"
+
+namespace WebCore {
+
+class DOMWindow;
+class EventQueue;
+class EventTarget;
+class ExecutionContextTask;
+class KURL;
+template<class T> class LifecycleNotifier;
+class ScriptCallStack;
+class ScriptState;
+class SecurityContext;
+
+class ExecutionContextClient {
+public:
+ virtual void postTask(PassOwnPtr<ExecutionContextTask>) = 0; // Executes the task on context's thread asynchronously.
+
+ virtual bool isDocument() const { return false; }
+ virtual bool isWorkerGlobalScope() const { return false; }
+ virtual bool isJSExecutionForbidden() const = 0;
+ virtual DOMWindow* executingWindow() { return 0; }
+ virtual void userEventWasHandled() { }
+ virtual String userAgent(const KURL&) const = 0;
+ virtual void disableEval(const String& errorMessage) = 0;
+ virtual SecurityContext& securityContext() = 0;
+ virtual const KURL& virtualURL() const = 0;
+ virtual KURL virtualCompleteURL(const String&) const = 0;
+ virtual void addMessage(MessageSource, MessageLevel, const String& message, const String& sourceURL, unsigned lineNumber, ScriptState*) = 0;
+ virtual void reportBlockedScriptExecutionToInspector(const String& directiveText) = 0;
+ virtual EventTarget* errorEventTarget() = 0;
+ virtual void logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, int columnNumber, PassRefPtr<ScriptCallStack>) = 0;
+ virtual double timerAlignmentInterval() const = 0;
+ virtual void didUpdateSecurityOrigin() = 0;
+
+ virtual void tasksWereSuspended() { }
+ virtual void tasksWereResumed() { }
+
+ void addConsoleMessage(MessageSource source, MessageLevel level, const String& message, const String& sourceURL, unsigned lineNumber) { addMessage(source, level, message, sourceURL, lineNumber, 0); }
+ void addConsoleMessage(MessageSource source, MessageLevel level, const String& message, ScriptState* state = 0) { addMessage(source, level, message, String(), 0, state); }
+ KURL contextURL() const { return virtualURL(); }
+ KURL contextCompleteURL(const String& url) const { return virtualCompleteURL(url); }
+
+protected:
+ virtual ~ExecutionContextClient() { }
+
+};
+
+
+} // namespace
+
+#endif
diff --git a/chromium/third_party/WebKit/Source/core/dom/ExecutionContextTask.cpp b/chromium/third_party/WebKit/Source/core/dom/ExecutionContextTask.cpp
new file mode 100644
index 00000000000..124a5ac4aac
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/ExecutionContextTask.cpp
@@ -0,0 +1,38 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef ExecutionContextTask_h
+#define ExecutionContextTask_h
+
+#include "config.h"
+#include "core/dom/ExecutionContextTask.h"
+
+namespace WebCore {
+
+
+} // namespace
+
+#endif
diff --git a/chromium/third_party/WebKit/Source/core/dom/ExecutionContextTask.h b/chromium/third_party/WebKit/Source/core/dom/ExecutionContextTask.h
new file mode 100644
index 00000000000..9d07d75d6a9
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/ExecutionContextTask.h
@@ -0,0 +1,65 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef ExecutionContextTask_h
+#define ExecutionContextTask_h
+
+#include "wtf/FastAllocBase.h"
+#include "wtf/Functional.h"
+#include "wtf/Noncopyable.h"
+#include "wtf/PassOwnPtr.h"
+
+namespace WebCore {
+
+class ExecutionContext;
+
+class ExecutionContextTask {
+ WTF_MAKE_NONCOPYABLE(ExecutionContextTask);
+ WTF_MAKE_FAST_ALLOCATED;
+public:
+ ExecutionContextTask() { }
+ virtual ~ExecutionContextTask() { }
+ virtual void performTask(ExecutionContext*) = 0;
+ // Certain tasks get marked specially so that they aren't discarded, and are executed, when the context is shutting down its message queue.
+ virtual bool isCleanupTask() const { return false; }
+};
+
+class CallClosureTask : public ExecutionContextTask {
+public:
+ static PassOwnPtr<CallClosureTask> create(const Closure& closure)
+ {
+ return adoptPtr(new CallClosureTask(closure));
+ }
+ virtual void performTask(ExecutionContext*) OVERRIDE { m_closure(); }
+
+private:
+ explicit CallClosureTask(const Closure& closure) : m_closure(closure) { }
+ Closure m_closure;
+};
+
+} // namespace
+
+#endif
diff --git a/chromium/third_party/WebKit/Source/core/dom/FocusEvent.cpp b/chromium/third_party/WebKit/Source/core/dom/FocusEvent.cpp
deleted file mode 100644
index 6d9569d4d9a..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/FocusEvent.cpp
+++ /dev/null
@@ -1,134 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/dom/FocusEvent.h"
-
-#include "core/dom/Event.h"
-#include "core/dom/EventDispatcher.h"
-#include "core/dom/EventNames.h"
-#include "core/dom/EventRetargeter.h"
-
-namespace WebCore {
-
-FocusEventInit::FocusEventInit()
- : relatedTarget(0)
-{
-}
-
-const AtomicString& FocusEvent::interfaceName() const
-{
- return eventNames().interfaceForFocusEvent;
-}
-
-bool FocusEvent::isFocusEvent() const
-{
- return true;
-}
-
-FocusEvent::FocusEvent()
-{
- ScriptWrappable::init(this);
-}
-
-FocusEvent::FocusEvent(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<AbstractView> view, int detail, EventTarget* relatedTarget)
- : UIEvent(type, canBubble, cancelable, view, detail)
- , m_relatedTarget(relatedTarget)
-{
- ScriptWrappable::init(this);
-}
-
-FocusEvent::FocusEvent(const AtomicString& type, const FocusEventInit& initializer)
- : UIEvent(type, initializer)
- , m_relatedTarget(initializer.relatedTarget)
-{
- ScriptWrappable::init(this);
-}
-
-PassRefPtr<FocusEventDispatchMediator> FocusEventDispatchMediator::create(PassRefPtr<FocusEvent> focusEvent)
-{
- return adoptRef(new FocusEventDispatchMediator(focusEvent));
-}
-
-FocusEventDispatchMediator::FocusEventDispatchMediator(PassRefPtr<FocusEvent> focusEvent)
- : EventDispatchMediator(focusEvent)
-{
-}
-
-bool FocusEventDispatchMediator::dispatchEvent(EventDispatcher* dispatcher) const
-{
- EventRetargeter::adjustForFocusEvent(dispatcher->node(), *event());
- return EventDispatchMediator::dispatchEvent(dispatcher);
-}
-
-PassRefPtr<BlurEventDispatchMediator> BlurEventDispatchMediator::create(PassRefPtr<FocusEvent> focusEvent)
-{
- return adoptRef(new BlurEventDispatchMediator(focusEvent));
-}
-
-BlurEventDispatchMediator::BlurEventDispatchMediator(PassRefPtr<FocusEvent> focusEvent)
- : EventDispatchMediator(focusEvent)
-{
-}
-
-bool BlurEventDispatchMediator::dispatchEvent(EventDispatcher* dispatcher) const
-{
- EventRetargeter::adjustForFocusEvent(dispatcher->node(), *event());
- return EventDispatchMediator::dispatchEvent(dispatcher);
-}
-
-PassRefPtr<FocusInEventDispatchMediator> FocusInEventDispatchMediator::create(PassRefPtr<FocusEvent> focusEvent)
-{
- return adoptRef(new FocusInEventDispatchMediator(focusEvent));
-}
-
-FocusInEventDispatchMediator::FocusInEventDispatchMediator(PassRefPtr<FocusEvent> focusEvent)
- : EventDispatchMediator(focusEvent)
-{
-}
-
-bool FocusInEventDispatchMediator::dispatchEvent(EventDispatcher* dispatcher) const
-{
- EventRetargeter::adjustForFocusEvent(dispatcher->node(), *event());
- return EventDispatchMediator::dispatchEvent(dispatcher);
-}
-
-PassRefPtr<FocusOutEventDispatchMediator> FocusOutEventDispatchMediator::create(PassRefPtr<FocusEvent> focusEvent)
-{
- return adoptRef(new FocusOutEventDispatchMediator(focusEvent));
-}
-
-FocusOutEventDispatchMediator::FocusOutEventDispatchMediator(PassRefPtr<FocusEvent> focusEvent)
- : EventDispatchMediator(focusEvent)
-{
-}
-
-bool FocusOutEventDispatchMediator::dispatchEvent(EventDispatcher* dispatcher) const
-{
- EventRetargeter::adjustForFocusEvent(dispatcher->node(), *event());
- return EventDispatchMediator::dispatchEvent(dispatcher);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/FocusEvent.h b/chromium/third_party/WebKit/Source/core/dom/FocusEvent.h
deleted file mode 100644
index f96c0764eca..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/FocusEvent.h
+++ /dev/null
@@ -1,117 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef FocusEvent_h
-#define FocusEvent_h
-
-#include "core/dom/EventTarget.h"
-#include "core/dom/UIEvent.h"
-
-namespace WebCore {
-
-class Node;
-
-struct FocusEventInit : public UIEventInit {
- FocusEventInit();
-
- RefPtr<EventTarget> relatedTarget;
-};
-
-class FocusEvent : public UIEvent {
-public:
- static PassRefPtr<FocusEvent> create()
- {
- return adoptRef(new FocusEvent);
- }
-
- static PassRefPtr<FocusEvent> create(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<AbstractView> view, int detail, EventTarget* relatedTarget)
- {
- return adoptRef(new FocusEvent(type, canBubble, cancelable, view, detail, relatedTarget));
- }
-
- static PassRefPtr<FocusEvent> create(const AtomicString& type, const FocusEventInit& initializer)
- {
- return adoptRef(new FocusEvent(type, initializer));
- }
-
- EventTarget* relatedTarget() const { return m_relatedTarget.get(); }
- void setRelatedTarget(EventTarget* relatedTarget) { m_relatedTarget = relatedTarget; }
-
- virtual const AtomicString& interfaceName() const;
- virtual bool isFocusEvent() const;
-
-private:
- FocusEvent();
- FocusEvent(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<AbstractView>, int, EventTarget*);
- FocusEvent(const AtomicString& type, const FocusEventInit&);
-
- RefPtr<EventTarget> m_relatedTarget;
-};
-
-inline FocusEvent* toFocusEvent(Event* event)
-{
- ASSERT(event && event->isFocusEvent());
- return static_cast<FocusEvent*>(event);
-}
-
-class FocusEventDispatchMediator : public EventDispatchMediator {
-public:
- static PassRefPtr<FocusEventDispatchMediator> create(PassRefPtr<FocusEvent>);
-private:
- explicit FocusEventDispatchMediator(PassRefPtr<FocusEvent>);
- FocusEvent* event() const { return static_cast<FocusEvent*>(EventDispatchMediator::event()); }
- virtual bool dispatchEvent(EventDispatcher*) const OVERRIDE;
-};
-
-class BlurEventDispatchMediator : public EventDispatchMediator {
-public:
- static PassRefPtr<BlurEventDispatchMediator> create(PassRefPtr<FocusEvent>);
-private:
- explicit BlurEventDispatchMediator(PassRefPtr<FocusEvent>);
- FocusEvent* event() const { return static_cast<FocusEvent*>(EventDispatchMediator::event()); }
- virtual bool dispatchEvent(EventDispatcher*) const OVERRIDE;
-};
-
-class FocusInEventDispatchMediator : public EventDispatchMediator {
-public:
- static PassRefPtr<FocusInEventDispatchMediator> create(PassRefPtr<FocusEvent>);
-private:
- explicit FocusInEventDispatchMediator(PassRefPtr<FocusEvent>);
- FocusEvent* event() const { return static_cast<FocusEvent*>(EventDispatchMediator::event()); }
- virtual bool dispatchEvent(EventDispatcher*) const OVERRIDE;
-};
-
-class FocusOutEventDispatchMediator : public EventDispatchMediator {
-public:
- static PassRefPtr<FocusOutEventDispatchMediator> create(PassRefPtr<FocusEvent>);
-private:
- explicit FocusOutEventDispatchMediator(PassRefPtr<FocusEvent>);
- FocusEvent* event() const { return static_cast<FocusEvent*>(EventDispatchMediator::event()); }
- virtual bool dispatchEvent(EventDispatcher*) const OVERRIDE;
-};
-
-} // namespace WebCore
-
-#endif // FocusEvent_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/FocusEvent.idl b/chromium/third_party/WebKit/Source/core/dom/FocusEvent.idl
deleted file mode 100644
index 659e5769f59..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/FocusEvent.idl
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-[
- ConstructorTemplate=Event
-] interface FocusEvent : UIEvent {
- [InitializedByEventConstructor] readonly attribute EventTarget relatedTarget;
-};
diff --git a/chromium/third_party/WebKit/Source/core/dom/FullscreenElementStack.cpp b/chromium/third_party/WebKit/Source/core/dom/FullscreenElementStack.cpp
index 4d5d692ccee..f6daf0e6631 100644
--- a/chromium/third_party/WebKit/Source/core/dom/FullscreenElementStack.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/FullscreenElementStack.cpp
@@ -29,17 +29,16 @@
#include "core/dom/FullscreenElementStack.h"
#include "HTMLNames.h"
-#include "bindings/v8/ScriptController.h"
#include "core/dom/Document.h"
-#include "core/dom/Element.h"
-#include "core/dom/Event.h"
+#include "core/events/Event.h"
#include "core/html/HTMLFrameOwnerElement.h"
#include "core/page/Chrome.h"
#include "core/page/ChromeClient.h"
-#include "core/page/Frame.h"
+#include "core/frame/Frame.h"
#include "core/page/Page.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
#include "core/rendering/RenderFullScreen.h"
+#include "platform/UserGestureIndicator.h"
namespace WebCore {
@@ -66,7 +65,7 @@ FullscreenElementStack* FullscreenElementStack::from(Document* document)
FullscreenElementStack* fullscreen = fromIfExists(document);
if (!fullscreen) {
fullscreen = new FullscreenElementStack(document);
- Supplement<ScriptExecutionContext>::provideTo(document, supplementName(), adoptPtr(fullscreen));
+ DocumentSupplement::provideTo(document, supplementName(), adoptPtr(fullscreen));
}
return fullscreen;
@@ -74,7 +73,7 @@ FullscreenElementStack* FullscreenElementStack::from(Document* document)
FullscreenElementStack* FullscreenElementStack::fromIfExistsSlow(Document* document)
{
- return static_cast<FullscreenElementStack*>(Supplement<ScriptExecutionContext>::from(document, supplementName()));
+ return static_cast<FullscreenElementStack*>(DocumentSupplement::from(document, supplementName()));
}
Element* FullscreenElementStack::fullscreenElementFrom(Document* document)
@@ -113,7 +112,7 @@ FullscreenElementStack::~FullscreenElementStack()
inline Document* FullscreenElementStack::document()
{
- return toDocument(scriptExecutionContext());
+ return lifecycleContext();
}
void FullscreenElementStack::documentWasDetached()
@@ -171,7 +170,7 @@ void FullscreenElementStack::requestFullScreenForElement(Element* element, unsig
// A descendant browsing context's document has a non-empty fullscreen element stack.
bool descendentHasNonEmptyStack = false;
- for (Frame* descendant = document()->frame() ? document()->frame()->tree()->traverseNext() : 0; descendant; descendant = descendant->tree()->traverseNext()) {
+ for (Frame* descendant = document()->frame() ? document()->frame()->tree().traverseNext() : 0; descendant; descendant = descendant->tree().traverseNext()) {
if (fullscreenElementFrom(descendant->document())) {
descendentHasNonEmptyStack = true;
break;
@@ -184,12 +183,12 @@ void FullscreenElementStack::requestFullScreenForElement(Element* element, unsig
// An algorithm is allowed to show a pop-up if, in the task in which the algorithm is running, either:
// - an activation behavior is currently being processed whose click event was trusted, or
// - the event listener for a trusted click event is being handled.
- if (!ScriptController::processingUserGesture())
+ // FIXME: Does this need to null-check settings()?
+ if (!UserGestureIndicator::processingUserGesture() && (!element->isMediaElement() || document()->settings()->mediaFullscreenRequiresUserGesture()))
break;
- UserGestureIndicator::consumeUserGesture();
// There is a previously-established user preference, security risk, or platform limitation.
- if (!document()->page() || !document()->page()->settings().fullScreenEnabled())
+ if (!document()->settings() || !document()->settings()->fullScreenEnabled())
break;
// 2. Let doc be element's node document. (i.e. "this")
@@ -284,7 +283,7 @@ void FullscreenElementStack::webkitExitFullscreen()
// element stack (if any), ordered so that the child of the doc is last and the document furthest
// away from the doc is first.
Deque<RefPtr<Document> > descendants;
- for (Frame* descendant = document()->frame() ? document()->frame()->tree()->traverseNext() : 0; descendant; descendant = descendant->tree()->traverseNext()) {
+ for (Frame* descendant = document()->frame() ? document()->frame()->tree().traverseNext() : 0; descendant; descendant = descendant->tree().traverseNext()) {
if (fullscreenElementFrom(descendant->document()))
descendants.prepend(descendant->document());
}
@@ -305,7 +304,7 @@ void FullscreenElementStack::webkitExitFullscreen()
// If doc's fullscreen element stack is non-empty and the element now at the top is either
// not in a document or its node document is not doc, repeat this substep.
newTop = fullscreenElementFrom(currentDoc);
- if (newTop && (!newTop->inDocument() || &newTop->document() != currentDoc))
+ if (newTop && (!newTop->inDocument() || newTop->document() != currentDoc))
continue;
// 2. Queue a task to fire an event named fullscreenchange with its bubbles attribute set to true
@@ -352,16 +351,16 @@ bool FullscreenElementStack::webkitFullscreenEnabled(Document* document)
void FullscreenElementStack::webkitWillEnterFullScreenForElement(Element* element)
{
- if (!document()->attached())
+ if (!document()->isActive())
return;
ASSERT(element);
// Protect against being called after the document has been removed from the page.
- if (!document()->page())
+ if (!document()->settings())
return;
- ASSERT(document()->page()->settings().fullScreenEnabled());
+ ASSERT(document()->settings()->fullScreenEnabled());
if (m_fullScreenRenderer)
m_fullScreenRenderer->unwrapRenderer();
@@ -392,7 +391,7 @@ void FullscreenElementStack::webkitDidEnterFullScreenForElement(Element*)
if (!m_fullScreenElement)
return;
- if (!document()->attached())
+ if (!document()->isActive())
return;
m_fullScreenElement->didBecomeFullscreenElement();
@@ -405,7 +404,7 @@ void FullscreenElementStack::webkitWillExitFullScreenForElement(Element*)
if (!m_fullScreenElement)
return;
- if (!document()->attached())
+ if (!document()->isActive())
return;
m_fullScreenElement->willStopBeingFullscreenElement();
@@ -416,7 +415,7 @@ void FullscreenElementStack::webkitDidExitFullScreenForElement(Element*)
if (!m_fullScreenElement)
return;
- if (!document()->attached())
+ if (!document()->isActive())
return;
m_fullScreenElement->setContainsFullScreenElementOnAncestorsCrossingFrameBoundaries(false);
@@ -486,7 +485,7 @@ void FullscreenElementStack::fullScreenChangeDelayTimerFired(Timer<FullscreenEle
if (!document()->contains(node.get()) && !node->inDocument())
changeQueue.append(document()->documentElement());
- node->dispatchEvent(Event::createBubble(eventNames().webkitfullscreenchangeEvent));
+ node->dispatchEvent(Event::createBubble(EventTypeNames::webkitfullscreenchange));
}
while (!errorQueue.isEmpty()) {
@@ -502,7 +501,7 @@ void FullscreenElementStack::fullScreenChangeDelayTimerFired(Timer<FullscreenEle
if (!document()->contains(node.get()) && !node->inDocument())
errorQueue.append(document()->documentElement());
- node->dispatchEvent(Event::createBubble(eventNames().webkitfullscreenerrorEvent));
+ node->dispatchEvent(Event::createBubble(EventTypeNames::webkitfullscreenerror));
}
}
@@ -517,6 +516,10 @@ void FullscreenElementStack::removeFullScreenElementOfSubtree(Node* node, bool a
if (!m_fullScreenElement)
return;
+ // If the node isn't in a document it can't have a fullscreen'd child.
+ if (!node->inDocument())
+ return;
+
bool elementInSubtree = false;
if (amongChildrenOnly)
elementInSubtree = m_fullScreenElement->isDescendantOf(node);
diff --git a/chromium/third_party/WebKit/Source/core/dom/FullscreenElementStack.h b/chromium/third_party/WebKit/Source/core/dom/FullscreenElementStack.h
index 8e5e986231e..4211a8387da 100644
--- a/chromium/third_party/WebKit/Source/core/dom/FullscreenElementStack.h
+++ b/chromium/third_party/WebKit/Source/core/dom/FullscreenElementStack.h
@@ -30,9 +30,9 @@
#include "core/dom/DocumentLifecycleObserver.h"
#include "core/dom/Element.h"
-#include "core/platform/Supplementable.h"
-#include "core/platform/Timer.h"
-#include "core/platform/graphics/LayoutRect.h"
+#include "platform/Supplementable.h"
+#include "platform/Timer.h"
+#include "platform/geometry/LayoutRect.h"
#include "wtf/Deque.h"
#include "wtf/RefPtr.h"
#include "wtf/Vector.h"
@@ -44,10 +44,10 @@ class Element;
class Node;
class RenderFullScreen;
class RenderStyle;
-class ScriptExecutionContext;
+class ExecutionContext;
class FullscreenElementStack
- : public Supplement<ScriptExecutionContext>
+ : public DocumentSupplement
, public DocumentLifecycleObserver {
public:
virtual ~FullscreenElementStack();
diff --git a/chromium/third_party/WebKit/Source/core/dom/GenericEventQueue.cpp b/chromium/third_party/WebKit/Source/core/dom/GenericEventQueue.cpp
deleted file mode 100644
index b002fd63174..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/GenericEventQueue.cpp
+++ /dev/null
@@ -1,113 +0,0 @@
-/*
- * Copyright (C) 2012 Victor Carbune (victor@rosedu.org)
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/dom/GenericEventQueue.h"
-
-#include "core/dom/Event.h"
-
-namespace WebCore {
-
-PassOwnPtr<GenericEventQueue> GenericEventQueue::create(EventTarget* owner)
-{
- return adoptPtr(new GenericEventQueue(owner));
-}
-
-GenericEventQueue::GenericEventQueue(EventTarget* owner)
- : m_owner(owner)
- , m_timer(this, &GenericEventQueue::timerFired)
- , m_isClosed(false)
-{
-}
-
-GenericEventQueue::~GenericEventQueue()
-{
-}
-
-bool GenericEventQueue::enqueueEvent(PassRefPtr<Event> event)
-{
- if (m_isClosed)
- return false;
-
- if (event->target() == m_owner)
- event->setTarget(0);
-
- m_pendingEvents.append(event);
-
- if (!m_timer.isActive())
- m_timer.startOneShot(0);
-
- return true;
-}
-
-bool GenericEventQueue::cancelEvent(Event* event)
-{
- bool found = m_pendingEvents.contains(event);
-
- if (found)
- m_pendingEvents.remove(m_pendingEvents.find(event));
-
- if (m_pendingEvents.isEmpty())
- m_timer.stop();
-
- return found;
-}
-
-void GenericEventQueue::timerFired(Timer<GenericEventQueue>*)
-{
- ASSERT(!m_timer.isActive());
- ASSERT(!m_pendingEvents.isEmpty());
-
- Vector<RefPtr<Event> > pendingEvents;
- m_pendingEvents.swap(pendingEvents);
-
- RefPtr<EventTarget> protect(m_owner);
- for (unsigned i = 0; i < pendingEvents.size(); ++i) {
- EventTarget* target = pendingEvents[i]->target() ? pendingEvents[i]->target() : m_owner;
- target->dispatchEvent(pendingEvents[i].release());
- }
-}
-
-void GenericEventQueue::close()
-{
- m_isClosed = true;
-
- m_timer.stop();
- m_pendingEvents.clear();
-}
-
-void GenericEventQueue::cancelAllEvents()
-{
- m_timer.stop();
- m_pendingEvents.clear();
-}
-
-bool GenericEventQueue::hasPendingEvents() const
-{
- return m_pendingEvents.size();
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/dom/GenericEventQueue.h b/chromium/third_party/WebKit/Source/core/dom/GenericEventQueue.h
deleted file mode 100644
index a4d1c20b933..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/GenericEventQueue.h
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * Copyright (C) 2012 Victor Carbune (victor@rosedu.org)
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef GenericEventQueue_h
-#define GenericEventQueue_h
-
-#include "core/dom/EventQueue.h"
-#include "core/dom/EventTarget.h"
-#include "core/platform/Timer.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/RefPtr.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-class GenericEventQueue : public EventQueue {
- WTF_MAKE_FAST_ALLOCATED;
-public:
- explicit GenericEventQueue(EventTarget*);
- static PassOwnPtr<GenericEventQueue> create(EventTarget*);
- virtual ~GenericEventQueue();
-
- // EventQueue
- virtual bool enqueueEvent(PassRefPtr<Event>) OVERRIDE;
- virtual bool cancelEvent(Event*) OVERRIDE;
- virtual void close() OVERRIDE;
-
- void cancelAllEvents();
- bool hasPendingEvents() const;
-
-private:
- void timerFired(Timer<GenericEventQueue>*);
-
- EventTarget* m_owner;
- Vector<RefPtr<Event> > m_pendingEvents;
- Timer<GenericEventQueue> m_timer;
-
- bool m_isClosed;
-};
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/dom/GestureEvent.cpp b/chromium/third_party/WebKit/Source/core/dom/GestureEvent.cpp
deleted file mode 100644
index 47b60831f6f..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/GestureEvent.cpp
+++ /dev/null
@@ -1,128 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/dom/Element.h"
-#include "core/dom/GestureEvent.h"
-#include "wtf/text/AtomicString.h"
-
-namespace WebCore {
-
-PassRefPtr<GestureEvent> GestureEvent::create()
-{
- return adoptRef(new GestureEvent);
-}
-
-PassRefPtr<GestureEvent> GestureEvent::create(PassRefPtr<AbstractView> view, const PlatformGestureEvent& event)
-{
- AtomicString eventType;
- switch (event.type()) {
- case PlatformEvent::GestureScrollBegin:
- eventType = eventNames().gesturescrollstartEvent; break;
- case PlatformEvent::GestureScrollEnd:
- eventType = eventNames().gesturescrollendEvent; break;
- case PlatformEvent::GestureScrollUpdate:
- case PlatformEvent::GestureScrollUpdateWithoutPropagation:
- eventType = eventNames().gesturescrollupdateEvent; break;
- case PlatformEvent::GestureTap:
- eventType = eventNames().gesturetapEvent; break;
- case PlatformEvent::GestureTapUnconfirmed:
- eventType = eventNames().gesturetapunconfirmedEvent; break;
- case PlatformEvent::GestureTapDown:
- eventType = eventNames().gesturetapdownEvent; break;
- case PlatformEvent::GestureTwoFingerTap:
- case PlatformEvent::GestureLongPress:
- case PlatformEvent::GesturePinchBegin:
- case PlatformEvent::GesturePinchEnd:
- case PlatformEvent::GesturePinchUpdate:
- case PlatformEvent::GestureTapDownCancel:
- default:
- return 0;
- }
- return adoptRef(new GestureEvent(eventType, view, event.globalPosition().x(), event.globalPosition().y(), event.position().x(), event.position().y(), event.ctrlKey(), event.altKey(), event.shiftKey(), event.metaKey(), event.deltaX(), event.deltaY()));
-}
-
-void GestureEvent::initGestureEvent(const AtomicString& type, PassRefPtr<AbstractView> view, int screenX, int screenY, int clientX, int clientY, bool ctrlKey, bool altKey, bool shiftKey, bool metaKey, float deltaX, float deltaY)
-{
- if (dispatched())
- return;
-
- initUIEvent(type, true, true, view, 0);
- m_screenLocation = IntPoint(screenX, screenY);
- m_ctrlKey = ctrlKey;
- m_altKey = altKey;
- m_shiftKey = shiftKey;
- m_metaKey = metaKey;
-
- m_deltaX = deltaX;
- m_deltaY = deltaY;
-
- initCoordinates(IntPoint(clientX, clientY));
-}
-
-const AtomicString& GestureEvent::interfaceName() const
-{
- // FIXME: when a GestureEvent.idl interface is defined, return the string "GestureEvent".
- // Until that happens, do not advertise an interface that does not exist, since it will
- // trip up the bindings integrity checks.
- return UIEvent::interfaceName();
-}
-
-bool GestureEvent::isGestureEvent() const
-{
- return true;
-}
-
-GestureEvent::GestureEvent()
- : m_deltaX(0)
- , m_deltaY(0)
-{
-}
-
-GestureEvent::GestureEvent(const AtomicString& type, PassRefPtr<AbstractView> view, int screenX, int screenY, int clientX, int clientY, bool ctrlKey, bool altKey, bool shiftKey, bool metaKey, float deltaX, float deltaY)
- : MouseRelatedEvent(type, true, true, view, 0, IntPoint(screenX, screenY), IntPoint(clientX, clientY), IntPoint(0, 0), ctrlKey, altKey, shiftKey, metaKey)
- , m_deltaX(deltaX)
- , m_deltaY(deltaY)
-{
-}
-
-GestureEventDispatchMediator::GestureEventDispatchMediator(PassRefPtr<GestureEvent> gestureEvent)
- : EventDispatchMediator(gestureEvent)
-{
-}
-
-GestureEvent* GestureEventDispatchMediator::event() const
-{
- return toGestureEvent(EventDispatchMediator::event());
-}
-
-bool GestureEventDispatchMediator::dispatchEvent(EventDispatcher* dispatcher) const
-{
- dispatcher->dispatch();
- ASSERT(!event()->defaultPrevented());
- return event()->defaultHandled() || event()->defaultPrevented();
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/GestureEvent.h b/chromium/third_party/WebKit/Source/core/dom/GestureEvent.h
deleted file mode 100644
index b630ae9342c..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/GestureEvent.h
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef GestureEvent_h
-#define GestureEvent_h
-
-#include "core/dom/EventDispatcher.h"
-#include "core/dom/MouseRelatedEvent.h"
-#include "core/platform/PlatformGestureEvent.h"
-
-namespace WebCore {
-
-class GestureEvent : public MouseRelatedEvent {
-public:
- virtual ~GestureEvent() { }
-
- static PassRefPtr<GestureEvent> create();
- static PassRefPtr<GestureEvent> create(PassRefPtr<AbstractView>, const PlatformGestureEvent&);
-
- void initGestureEvent(const AtomicString& type, PassRefPtr<AbstractView>, int screenX, int screenY, int clientX, int clientY, bool ctrlKey, bool altKey, bool shiftKey, bool metaKey, float deltaX, float deltaY);
-
- virtual bool isGestureEvent() const OVERRIDE;
-
- virtual const AtomicString& interfaceName() const;
-
- float deltaX() const { return m_deltaX; }
- float deltaY() const { return m_deltaY; }
-
-private:
- GestureEvent();
- GestureEvent(const AtomicString& type, PassRefPtr<AbstractView>, int screenX, int screenY, int clientX, int clientY, bool ctrlKey, bool altKey, bool shiftKey, bool metaKey, float deltaX, float deltaY);
-
- float m_deltaX;
- float m_deltaY;
-};
-
-class GestureEventDispatchMediator : public EventDispatchMediator {
-public:
- static PassRefPtr<GestureEventDispatchMediator> create(PassRefPtr<GestureEvent> gestureEvent)
- {
- return adoptRef(new GestureEventDispatchMediator(gestureEvent));
- }
-
-private:
- explicit GestureEventDispatchMediator(PassRefPtr<GestureEvent>);
-
- GestureEvent* event() const;
-
- virtual bool dispatchEvent(EventDispatcher*) const OVERRIDE;
-};
-
-inline GestureEvent* toGestureEvent(Event* event)
-{
- ASSERT(event && event->isGestureEvent());
- return static_cast<GestureEvent*>(event);
-}
-
-} // namespace WebCore
-
-#endif // GestureEvent_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/GlobalEventHandlers.h b/chromium/third_party/WebKit/Source/core/dom/GlobalEventHandlers.h
new file mode 100644
index 00000000000..8da83b9add9
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/GlobalEventHandlers.h
@@ -0,0 +1,99 @@
+/*
+ * Copyright (c) 2013, Opera Software ASA. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Opera Software ASA nor the names of its
+ * contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef GlobalEventHandlers_h
+#define GlobalEventHandlers_h
+
+#include "core/events/EventTarget.h"
+
+namespace WebCore {
+
+namespace GlobalEventHandlers {
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(abort);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(blur);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(cancel);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(canplay);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(canplaythrough);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(change);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(click);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(close);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(contextmenu);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(cuechange);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(dblclick);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(drag);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(dragend);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(dragenter);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(dragleave);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(dragover);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(dragstart);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(drop);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(durationchange);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(emptied);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(ended);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(error);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(focus);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(input);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(invalid);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(keydown);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(keypress);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(keyup);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(load);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(loadeddata);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(loadedmetadata);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(loadstart);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(mousedown);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(mouseenter);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(mouseleave);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(mousemove);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(mouseout);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(mouseover);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(mouseup);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(mousewheel);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(pause);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(play);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(playing);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(progress);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(ratechange);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(reset);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(scroll);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(seeked);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(seeking);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(select);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(show);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(stalled);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(submit);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(suspend);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(timeupdate);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(volumechange);
+DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(waiting);
+}
+
+} // namespace
+
+#endif
diff --git a/chromium/third_party/WebKit/Source/core/dom/GlobalEventHandlers.idl b/chromium/third_party/WebKit/Source/core/dom/GlobalEventHandlers.idl
new file mode 100644
index 00000000000..880038222f2
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/GlobalEventHandlers.idl
@@ -0,0 +1,92 @@
+/*
+ * Copyright (c) 2013, Opera Software ASA. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Opera Software ASA nor the names of its
+ * contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+[
+ NoInterfaceObject
+] interface GlobalEventHandlers {
+ attribute EventHandler onabort;
+ attribute EventHandler onblur;
+ attribute EventHandler oncancel;
+ attribute EventHandler oncanplay;
+ attribute EventHandler oncanplaythrough;
+ attribute EventHandler onchange;
+ [PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute EventHandler onclick;
+ attribute EventHandler onclose;
+ attribute EventHandler oncontextmenu;
+ attribute EventHandler oncuechange;
+ [PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute EventHandler ondblclick;
+ [PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute EventHandler ondrag;
+ [PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute EventHandler ondragend;
+ [PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute EventHandler ondragenter;
+ //[PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute EventHandler ondragexit;
+ [PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute EventHandler ondragleave;
+ [PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute EventHandler ondragover;
+ [PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute EventHandler ondragstart;
+ [PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute EventHandler ondrop;
+ attribute EventHandler ondurationchange;
+ attribute EventHandler onemptied;
+ attribute EventHandler onended;
+ attribute EventHandler onerror;
+ attribute EventHandler onfocus;
+ [PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute EventHandler oninput;
+ attribute EventHandler oninvalid;
+ [PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute EventHandler onkeydown;
+ [PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute EventHandler onkeypress;
+ [PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute EventHandler onkeyup;
+ attribute EventHandler onload;
+ attribute EventHandler onloadeddata;
+ attribute EventHandler onloadedmetadata;
+ attribute EventHandler onloadstart;
+ [PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute EventHandler onmousedown;
+ [PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute EventHandler onmouseenter;
+ [PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute EventHandler onmouseleave;
+ [PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute EventHandler onmousemove;
+ [PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute EventHandler onmouseout;
+ [PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute EventHandler onmouseover;
+ [PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute EventHandler onmouseup;
+ [PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute EventHandler onmousewheel;
+ attribute EventHandler onpause;
+ attribute EventHandler onplay;
+ attribute EventHandler onplaying;
+ attribute EventHandler onprogress;
+ attribute EventHandler onratechange;
+ attribute EventHandler onreset;
+ attribute EventHandler onscroll;
+ attribute EventHandler onseeked;
+ attribute EventHandler onseeking;
+ attribute EventHandler onselect;
+ attribute EventHandler onshow;
+ //attribute EventHandler onsort;
+ attribute EventHandler onstalled;
+ attribute EventHandler onsubmit;
+ attribute EventHandler onsuspend;
+ attribute EventHandler ontimeupdate;
+ attribute EventHandler onvolumechange;
+ attribute EventHandler onwaiting;
+};
diff --git a/chromium/third_party/WebKit/Source/core/dom/HashChangeEvent.h b/chromium/third_party/WebKit/Source/core/dom/HashChangeEvent.h
deleted file mode 100644
index dee8c10fcce..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/HashChangeEvent.h
+++ /dev/null
@@ -1,99 +0,0 @@
-/*
- * Copyright (C) 2010 Apple Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#ifndef HashChangeEvent_h
-#define HashChangeEvent_h
-
-#include "core/dom/Event.h"
-#include "core/dom/EventNames.h"
-
-namespace WebCore {
-
-struct HashChangeEventInit : public EventInit {
- HashChangeEventInit()
- {
- };
-
- String oldURL;
- String newURL;
-};
-
-class HashChangeEvent : public Event {
-public:
- static PassRefPtr<HashChangeEvent> create()
- {
- return adoptRef(new HashChangeEvent);
- }
-
- static PassRefPtr<HashChangeEvent> create(const String& oldURL, const String& newURL)
- {
- return adoptRef(new HashChangeEvent(oldURL, newURL));
- }
-
- static PassRefPtr<HashChangeEvent> create(const AtomicString& type, const HashChangeEventInit& initializer)
- {
- return adoptRef(new HashChangeEvent(type, initializer));
- }
-
- void initHashChangeEvent(const AtomicString& eventType, bool canBubble, bool cancelable, const String& oldURL, const String& newURL)
- {
- if (dispatched())
- return;
-
- initEvent(eventType, canBubble, cancelable);
-
- m_oldURL = oldURL;
- m_newURL = newURL;
- }
-
- const String& oldURL() const { return m_oldURL; }
- const String& newURL() const { return m_newURL; }
-
- virtual const AtomicString& interfaceName() const { return eventNames().interfaceForHashChangeEvent; }
-
-private:
- HashChangeEvent()
- {
- ScriptWrappable::init(this);
- }
-
- HashChangeEvent(const String& oldURL, const String& newURL)
- : Event(eventNames().hashchangeEvent, false, false)
- , m_oldURL(oldURL)
- , m_newURL(newURL)
- {
- ScriptWrappable::init(this);
- }
-
- HashChangeEvent(const AtomicString& type, const HashChangeEventInit& initializer)
- : Event(type, initializer)
- , m_oldURL(initializer.oldURL)
- , m_newURL(initializer.newURL)
- {
- ScriptWrappable::init(this);
- }
-
- String m_oldURL;
- String m_newURL;
-};
-
-} // namespace WebCore
-
-#endif // HashChangeEvent_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/HashChangeEvent.idl b/chromium/third_party/WebKit/Source/core/dom/HashChangeEvent.idl
deleted file mode 100644
index 470a2083c72..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/HashChangeEvent.idl
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright (C) 2010 Apple Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-// Introduced in http://www.whatwg.org/specs/web-apps/current-work/multipage/history.html#event-hashchange
-[
- ConstructorTemplate=Event
-] interface HashChangeEvent : Event {
- void initHashChangeEvent([Default=Undefined] optional DOMString type,
- [Default=Undefined] optional boolean canBubble,
- [Default=Undefined] optional boolean cancelable,
- [Default=Undefined] optional DOMString oldURL,
- [Default=Undefined] optional DOMString newURL);
- [InitializedByEventConstructor] readonly attribute DOMString oldURL;
- [InitializedByEventConstructor] readonly attribute DOMString newURL;
-};
-
diff --git a/chromium/third_party/WebKit/Source/core/dom/IconURL.cpp b/chromium/third_party/WebKit/Source/core/dom/IconURL.cpp
index 97575a261c5..248835b507e 100644
--- a/chromium/third_party/WebKit/Source/core/dom/IconURL.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/IconURL.cpp
@@ -33,9 +33,18 @@
namespace WebCore {
-IconURL IconURL::defaultIconURL(const KURL& url, IconType type)
+IconURL IconURL::defaultFavicon(const KURL& documentURL)
{
- IconURL result(url, emptyString(), emptyString(), type);
+ ASSERT(documentURL.protocolIsInHTTPFamily());
+ KURL url;
+ bool couldSetProtocol = url.setProtocol(documentURL.protocol());
+ ASSERT_UNUSED(couldSetProtocol, couldSetProtocol);
+ url.setHost(documentURL.host());
+ if (documentURL.hasPort())
+ url.setPort(documentURL.port());
+ url.setPath("/favicon.ico");
+
+ IconURL result(url, emptyString(), emptyString(), Favicon);
result.m_isDefaultIcon = true;
return result;
}
diff --git a/chromium/third_party/WebKit/Source/core/dom/IconURL.h b/chromium/third_party/WebKit/Source/core/dom/IconURL.h
index e352b7fcc12..adec2a7a8fd 100644
--- a/chromium/third_party/WebKit/Source/core/dom/IconURL.h
+++ b/chromium/third_party/WebKit/Source/core/dom/IconURL.h
@@ -31,7 +31,7 @@
#ifndef IconURL_h
#define IconURL_h
-#include "weborigin/KURL.h"
+#include "platform/weborigin/KURL.h"
namespace WebCore {
@@ -70,7 +70,7 @@ struct IconURL {
{
}
- static IconURL defaultIconURL(const KURL&, IconType);
+ static IconURL defaultFavicon(const KURL&);
};
bool operator==(const IconURL&, const IconURL&);
diff --git a/chromium/third_party/WebKit/Source/core/dom/KeyboardEvent.cpp b/chromium/third_party/WebKit/Source/core/dom/KeyboardEvent.cpp
deleted file mode 100644
index b20d77ab037..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/KeyboardEvent.cpp
+++ /dev/null
@@ -1,240 +0,0 @@
-/**
- * Copyright (C) 2001 Peter Kelly (pmk@post.com)
- * Copyright (C) 2001 Tobias Anton (anton@stud.fbi.fh-darmstadt.de)
- * Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
- * Copyright (C) 2003, 2005, 2006, 2007 Apple Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-#include "core/dom/KeyboardEvent.h"
-
-#include "core/dom/EventNames.h"
-#include "core/platform/PlatformKeyboardEvent.h"
-#include "core/platform/WindowsKeyboardCodes.h"
-
-namespace WebCore {
-
-static inline const AtomicString& eventTypeForKeyboardEventType(PlatformEvent::Type type)
-{
- switch (type) {
- case PlatformEvent::KeyUp:
- return eventNames().keyupEvent;
- case PlatformEvent::RawKeyDown:
- return eventNames().keydownEvent;
- case PlatformEvent::Char:
- return eventNames().keypressEvent;
- case PlatformEvent::KeyDown:
- // The caller should disambiguate the combined event into RawKeyDown or Char events.
- break;
- default:
- break;
- }
- ASSERT_NOT_REACHED();
- return eventNames().keydownEvent;
-}
-
-static inline int windowsVirtualKeyCodeWithoutLocation(int keycode)
-{
- switch (keycode) {
- case VK_LCONTROL:
- case VK_RCONTROL:
- return VK_CONTROL;
- case VK_LSHIFT:
- case VK_RSHIFT:
- return VK_SHIFT;
- case VK_LMENU:
- case VK_RMENU:
- return VK_MENU;
- default:
- return keycode;
- }
-}
-
-static inline KeyboardEvent::KeyLocationCode keyLocationCode(const PlatformKeyboardEvent& key)
-{
- if (key.isKeypad())
- return KeyboardEvent::DOM_KEY_LOCATION_NUMPAD;
-
- switch (key.windowsVirtualKeyCode()) {
- case VK_LCONTROL:
- case VK_LSHIFT:
- case VK_LMENU:
- case VK_LWIN:
- return KeyboardEvent::DOM_KEY_LOCATION_LEFT;
- case VK_RCONTROL:
- case VK_RSHIFT:
- case VK_RMENU:
- case VK_RWIN:
- return KeyboardEvent::DOM_KEY_LOCATION_RIGHT;
- default:
- return KeyboardEvent::DOM_KEY_LOCATION_STANDARD;
- }
-}
-
-KeyboardEventInit::KeyboardEventInit()
- : location(0)
- , ctrlKey(false)
- , altKey(false)
- , shiftKey(false)
- , metaKey(false)
-{
-}
-
-KeyboardEvent::KeyboardEvent()
- : m_location(DOM_KEY_LOCATION_STANDARD)
- , m_altGraphKey(false)
-{
- ScriptWrappable::init(this);
-}
-
-KeyboardEvent::KeyboardEvent(const PlatformKeyboardEvent& key, AbstractView* view)
- : UIEventWithKeyState(eventTypeForKeyboardEventType(key.type()),
- true, true, view, 0, key.ctrlKey(), key.altKey(), key.shiftKey(), key.metaKey())
- , m_keyEvent(adoptPtr(new PlatformKeyboardEvent(key)))
- , m_keyIdentifier(key.keyIdentifier())
- , m_location(keyLocationCode(key))
- , m_altGraphKey(false)
-{
- ScriptWrappable::init(this);
-}
-
-KeyboardEvent::KeyboardEvent(const AtomicString& eventType, const KeyboardEventInit& initializer)
- : UIEventWithKeyState(eventType, initializer.bubbles, initializer.cancelable, initializer.view, initializer.detail, initializer.ctrlKey, initializer.altKey, initializer.shiftKey, initializer.metaKey)
- , m_keyIdentifier(initializer.keyIdentifier)
- , m_location(initializer.location)
- , m_altGraphKey(false)
-{
- ScriptWrappable::init(this);
-}
-
-KeyboardEvent::KeyboardEvent(const AtomicString& eventType, bool canBubble, bool cancelable, AbstractView *view,
- const String &keyIdentifier, unsigned location,
- bool ctrlKey, bool altKey, bool shiftKey, bool metaKey, bool altGraphKey)
- : UIEventWithKeyState(eventType, canBubble, cancelable, view, 0, ctrlKey, altKey, shiftKey, metaKey)
- , m_keyIdentifier(keyIdentifier)
- , m_location(location)
- , m_altGraphKey(altGraphKey)
-{
- ScriptWrappable::init(this);
-}
-
-KeyboardEvent::~KeyboardEvent()
-{
-}
-
-void KeyboardEvent::initKeyboardEvent(const AtomicString& type, bool canBubble, bool cancelable, AbstractView* view,
- const String &keyIdentifier, unsigned location,
- bool ctrlKey, bool altKey, bool shiftKey, bool metaKey, bool altGraphKey)
-{
- if (dispatched())
- return;
-
- initUIEvent(type, canBubble, cancelable, view, 0);
-
- m_keyIdentifier = keyIdentifier;
- m_location = location;
- m_ctrlKey = ctrlKey;
- m_shiftKey = shiftKey;
- m_altKey = altKey;
- m_metaKey = metaKey;
- m_altGraphKey = altGraphKey;
-}
-
-bool KeyboardEvent::getModifierState(const String& keyIdentifier) const
-{
- // FIXME: The following keyIdentifiers are not supported yet (crbug.com/265458):
- // "AltGraph", "CapsLock", "Fn", "NumLock", "ScrollLock", "SymbolLock", "OS".
- if (keyIdentifier == "Control")
- return ctrlKey();
- if (keyIdentifier == "Shift")
- return shiftKey();
- if (keyIdentifier == "Alt")
- return altKey();
- if (keyIdentifier == "Meta")
- return metaKey();
- return false;
-}
-
-int KeyboardEvent::keyCode() const
-{
- // IE: virtual key code for keyup/keydown, character code for keypress
- // Firefox: virtual key code for keyup/keydown, zero for keypress
- // We match IE.
- if (!m_keyEvent)
- return 0;
- if (type() == eventNames().keydownEvent || type() == eventNames().keyupEvent)
- return windowsVirtualKeyCodeWithoutLocation(m_keyEvent->windowsVirtualKeyCode());
-
- return charCode();
-}
-
-int KeyboardEvent::charCode() const
-{
- // IE: not supported
- // Firefox: 0 for keydown/keyup events, character code for keypress
- // We match Firefox
-
- if (!m_keyEvent || (type() != eventNames().keypressEvent))
- return 0;
- String text = m_keyEvent->text();
- return static_cast<int>(text.characterStartingAt(0));
-}
-
-const AtomicString& KeyboardEvent::interfaceName() const
-{
- return eventNames().interfaceForKeyboardEvent;
-}
-
-bool KeyboardEvent::isKeyboardEvent() const
-{
- return true;
-}
-
-int KeyboardEvent::which() const
-{
- // Netscape's "which" returns a virtual key code for keydown and keyup, and a character code for keypress.
- // That's exactly what IE's "keyCode" returns. So they are the same for keyboard events.
- return keyCode();
-}
-
-KeyboardEvent* findKeyboardEvent(Event* event)
-{
- for (Event* e = event; e; e = e->underlyingEvent()) {
- if (e->isKeyboardEvent())
- return toKeyboardEvent(e);
- }
- return 0;
-}
-
-PassRefPtr<KeyboardEventDispatchMediator> KeyboardEventDispatchMediator::create(PassRefPtr<KeyboardEvent> event)
-{
- return adoptRef(new KeyboardEventDispatchMediator(event));
-}
-
-KeyboardEventDispatchMediator::KeyboardEventDispatchMediator(PassRefPtr<KeyboardEvent> event)
- : EventDispatchMediator(event)
-{
-}
-
-bool KeyboardEventDispatchMediator::dispatchEvent(EventDispatcher* dispatcher) const
-{
- // Make sure not to return true if we already took default action while handling the event.
- return EventDispatchMediator::dispatchEvent(dispatcher) && !event()->defaultHandled();
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/KeyboardEvent.h b/chromium/third_party/WebKit/Source/core/dom/KeyboardEvent.h
deleted file mode 100644
index 3cbeb06d346..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/KeyboardEvent.h
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
- * Copyright (C) 2001 Peter Kelly (pmk@post.com)
- * Copyright (C) 2001 Tobias Anton (anton@stud.fbi.fh-darmstadt.de)
- * Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
- * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#ifndef KeyboardEvent_h
-#define KeyboardEvent_h
-
-#include "core/dom/EventDispatchMediator.h"
-#include "core/dom/UIEventWithKeyState.h"
-
-namespace WebCore {
-
-class EventDispatcher;
-class Node;
-class PlatformKeyboardEvent;
-
-struct KeyboardEventInit : public UIEventInit {
- KeyboardEventInit();
-
- String keyIdentifier;
- unsigned location;
- bool ctrlKey;
- bool altKey;
- bool shiftKey;
- bool metaKey;
-};
-
-class KeyboardEvent : public UIEventWithKeyState {
-public:
- enum KeyLocationCode {
- DOM_KEY_LOCATION_STANDARD = 0x00,
- DOM_KEY_LOCATION_LEFT = 0x01,
- DOM_KEY_LOCATION_RIGHT = 0x02,
- DOM_KEY_LOCATION_NUMPAD = 0x03
- };
-
- static PassRefPtr<KeyboardEvent> create()
- {
- return adoptRef(new KeyboardEvent);
- }
-
- static PassRefPtr<KeyboardEvent> create(const PlatformKeyboardEvent& platformEvent, AbstractView* view)
- {
- return adoptRef(new KeyboardEvent(platformEvent, view));
- }
-
- static PassRefPtr<KeyboardEvent> create(const AtomicString& type, const KeyboardEventInit& initializer)
- {
- return adoptRef(new KeyboardEvent(type, initializer));
- }
-
- static PassRefPtr<KeyboardEvent> create(const AtomicString& type, bool canBubble, bool cancelable, AbstractView* view,
- const String& keyIdentifier, unsigned location,
- bool ctrlKey, bool altKey, bool shiftKey, bool metaKey, bool altGraphKey)
- {
- return adoptRef(new KeyboardEvent(type, canBubble, cancelable, view, keyIdentifier, location,
- ctrlKey, altKey, shiftKey, metaKey, altGraphKey));
- }
-
- virtual ~KeyboardEvent();
-
- void initKeyboardEvent(const AtomicString& type, bool canBubble, bool cancelable, AbstractView*,
- const String& keyIdentifier, unsigned location,
- bool ctrlKey, bool altKey, bool shiftKey, bool metaKey, bool altGraphKey = false);
-
- const String& keyIdentifier() const { return m_keyIdentifier; }
- unsigned location() const { return m_location; }
-
- bool getModifierState(const String& keyIdentifier) const;
-
- bool altGraphKey() const { return m_altGraphKey; }
-
- const PlatformKeyboardEvent* keyEvent() const { return m_keyEvent.get(); }
-
- int keyCode() const; // key code for keydown and keyup, character for keypress
- int charCode() const; // character code for keypress, 0 for keydown and keyup
-
- virtual const AtomicString& interfaceName() const;
- virtual bool isKeyboardEvent() const;
- virtual int which() const;
-
-private:
- KeyboardEvent();
- KeyboardEvent(const PlatformKeyboardEvent&, AbstractView*);
- KeyboardEvent(const AtomicString&, const KeyboardEventInit&);
- KeyboardEvent(const AtomicString& type, bool canBubble, bool cancelable, AbstractView*,
- const String& keyIdentifier, unsigned location,
- bool ctrlKey, bool altKey, bool shiftKey, bool metaKey, bool altGraphKey);
-
- OwnPtr<PlatformKeyboardEvent> m_keyEvent;
- String m_keyIdentifier;
- unsigned m_location;
- bool m_altGraphKey : 1;
-};
-
-KeyboardEvent* findKeyboardEvent(Event*);
-
-class KeyboardEventDispatchMediator : public EventDispatchMediator {
-public:
- static PassRefPtr<KeyboardEventDispatchMediator> create(PassRefPtr<KeyboardEvent>);
-private:
- explicit KeyboardEventDispatchMediator(PassRefPtr<KeyboardEvent>);
- virtual bool dispatchEvent(EventDispatcher*) const OVERRIDE;
-};
-
-inline KeyboardEvent* toKeyboardEvent(Event* event)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!event || event->isKeyboardEvent());
- return static_cast<KeyboardEvent*>(event);
-}
-
-} // namespace WebCore
-
-#endif // KeyboardEvent_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/KeyboardEvent.idl b/chromium/third_party/WebKit/Source/core/dom/KeyboardEvent.idl
deleted file mode 100644
index 62dd799a8b7..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/KeyboardEvent.idl
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright (C) 2006 Apple Computer, Inc.
- * Copyright (C) 2006 Samuel Weinig <sam.weinig@gmail.com>
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-[
- ConstructorTemplate=Event
-] interface KeyboardEvent : UIEvent {
- const unsigned long DOM_KEY_LOCATION_STANDARD = 0x00;
- const unsigned long DOM_KEY_LOCATION_LEFT = 0x01;
- const unsigned long DOM_KEY_LOCATION_RIGHT = 0x02;
- const unsigned long DOM_KEY_LOCATION_NUMPAD = 0x03;
-
- [InitializedByEventConstructor] readonly attribute DOMString keyIdentifier;
- [InitializedByEventConstructor] readonly attribute unsigned long location;
- [ImplementedAs=location, DeprecateAs=KeyboardEventKeyLocation, InitializedByEventConstructor] readonly attribute unsigned long keyLocation; // Deprecated.
- [InitializedByEventConstructor] readonly attribute boolean ctrlKey;
- [InitializedByEventConstructor] readonly attribute boolean shiftKey;
- [InitializedByEventConstructor] readonly attribute boolean altKey;
- [InitializedByEventConstructor] readonly attribute boolean metaKey;
- readonly attribute boolean altGraphKey;
-
- boolean getModifierState(DOMString keyArgument);
-
- // FIXME: this does not match the version in the DOM spec.
- void initKeyboardEvent([Default=Undefined] optional DOMString type,
- [Default=Undefined] optional boolean canBubble,
- [Default=Undefined] optional boolean cancelable,
- [Default=Undefined] optional Window view,
- [Default=Undefined] optional DOMString keyIdentifier,
- [Default=Undefined] optional unsigned long location,
- [Default=Undefined] optional boolean ctrlKey,
- [Default=Undefined] optional boolean altKey,
- [Default=Undefined] optional boolean shiftKey,
- [Default=Undefined] optional boolean metaKey,
- [Default=Undefined] optional boolean altGraphKey);
-};
-
diff --git a/chromium/third_party/WebKit/Source/core/dom/LiveNodeList.cpp b/chromium/third_party/WebKit/Source/core/dom/LiveNodeList.cpp
index abb485eb2ff..5343cb9520f 100644
--- a/chromium/third_party/WebKit/Source/core/dom/LiveNodeList.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/LiveNodeList.cpp
@@ -23,25 +23,24 @@
#include "config.h"
#include "core/dom/LiveNodeList.h"
-#include "core/dom/Document.h"
#include "core/dom/Element.h"
#include "core/html/HTMLCollection.h"
namespace WebCore {
-Node* LiveNodeListBase::rootNode() const
+Node& LiveNodeListBase::rootNode() const
{
if (isRootedAtDocument() && m_ownerNode->inDocument())
- return &m_ownerNode->document();
- return m_ownerNode.get();
+ return m_ownerNode->document();
+ return *m_ownerNode;
}
ContainerNode* LiveNodeListBase::rootContainerNode() const
{
- Node* rootNode = this->rootNode();
- if (!rootNode->isContainerNode())
+ Node& rootNode = this->rootNode();
+ if (!rootNode.isContainerNode())
return 0;
- return toContainerNode(rootNode);
+ return toContainerNode(&rootNode);
}
void LiveNodeListBase::invalidateCache() const
@@ -70,11 +69,11 @@ void LiveNodeListBase::invalidateIdNameCacheMaps() const
Node* LiveNodeList::namedItem(const AtomicString& elementId) const
{
- Node* rootNode = this->rootNode();
+ Node& rootNode = this->rootNode();
- if (rootNode->inDocument()) {
- Element* element = rootNode->treeScope().getElementById(elementId);
- if (element && nodeMatches(element) && element->isDescendantOf(rootNode))
+ if (rootNode.inDocument()) {
+ Element* element = rootNode.treeScope().getElementById(elementId);
+ if (element && nodeMatches(element) && element->isDescendantOf(&rootNode))
return element;
if (!element)
return 0;
diff --git a/chromium/third_party/WebKit/Source/core/dom/LiveNodeList.h b/chromium/third_party/WebKit/Source/core/dom/LiveNodeList.h
index 97dd515544a..2145b245f9e 100644
--- a/chromium/third_party/WebKit/Source/core/dom/LiveNodeList.h
+++ b/chromium/third_party/WebKit/Source/core/dom/LiveNodeList.h
@@ -100,7 +100,7 @@ public:
protected:
Document& document() const { return m_ownerNode->document(); }
- Node* rootNode() const;
+ Node& rootNode() const;
ContainerNode* rootContainerNode() const;
bool overridesItemAfter() const { return m_overridesItemAfter; }
@@ -137,8 +137,8 @@ protected:
private:
Node* itemBeforeOrAfterCachedItem(unsigned offset, ContainerNode* root) const;
Node* traverseChildNodeListForwardToOffset(unsigned offset, Node* currentNode, unsigned& currentOffset) const;
- Element* traverseLiveNodeListFirstElement(ContainerNode* root) const;
- Element* traverseLiveNodeListForwardToOffset(unsigned offset, Element* currentElement, unsigned& currentOffset, ContainerNode* root) const;
+ Element* traverseLiveNodeListFirstElement(ContainerNode& root) const;
+ Element* traverseLiveNodeListForwardToOffset(unsigned offset, Element& currentElement, unsigned& currentOffset, ContainerNode* root) const;
bool isLastItemCloserThanLastOrCachedItem(unsigned offset) const;
bool isFirstItemCloserThanCachedItem(unsigned offset) const;
Node* iterateForPreviousNode(Node* current) const;
diff --git a/chromium/third_party/WebKit/Source/core/dom/MainThreadTaskRunner.cpp b/chromium/third_party/WebKit/Source/core/dom/MainThreadTaskRunner.cpp
new file mode 100644
index 00000000000..976d971ce66
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/MainThreadTaskRunner.cpp
@@ -0,0 +1,116 @@
+/*
+ * Copyright (C) 2013 Google Inc. All Rights Reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "config.h"
+#include "core/dom/MainThreadTaskRunner.h"
+
+#include "core/dom/Document.h"
+#include "core/dom/ExecutionContextTask.h"
+#include "wtf/Assertions.h"
+
+namespace WebCore {
+
+struct PerformTaskContext {
+ WTF_MAKE_NONCOPYABLE(PerformTaskContext); WTF_MAKE_FAST_ALLOCATED;
+public:
+ PerformTaskContext(WeakPtr<MainThreadTaskRunner> runner, PassOwnPtr<ExecutionContextTask> task)
+ : m_runner(runner)
+ , m_task(task)
+ {
+ }
+
+ WeakPtr<MainThreadTaskRunner> m_runner;
+ OwnPtr<ExecutionContextTask> m_task;
+
+ static void didReceiveTask(void* untypedContext);
+};
+
+void PerformTaskContext::didReceiveTask(void* untypedContext)
+{
+ ASSERT(isMainThread());
+
+ OwnPtr<PerformTaskContext> self = adoptPtr(static_cast<PerformTaskContext*>(untypedContext));
+ ASSERT(self);
+
+ MainThreadTaskRunner* runner = self->m_runner.get();
+ if (!runner)
+ return;
+ runner->perform(self->m_task.release());
+}
+
+MainThreadTaskRunner::MainThreadTaskRunner(ExecutionContext* context)
+ : m_context(context)
+ , m_weakFactory(this)
+ , m_pendingTasksTimer(this, &MainThreadTaskRunner::pendingTasksTimerFired)
+ , m_suspended(false)
+{
+}
+
+MainThreadTaskRunner::~MainThreadTaskRunner()
+{
+}
+
+void MainThreadTaskRunner::postTask(PassOwnPtr<ExecutionContextTask> task)
+{
+ callOnMainThread(PerformTaskContext::didReceiveTask, new PerformTaskContext(m_weakFactory.createWeakPtr(), task));
+}
+
+void MainThreadTaskRunner::perform(PassOwnPtr<ExecutionContextTask> task)
+{
+ if (m_context->tasksNeedSuspension() || !m_pendingTasks.isEmpty()) {
+ m_pendingTasks.append(task);
+ return;
+ }
+
+ task->performTask(m_context);
+}
+
+void MainThreadTaskRunner::suspend()
+{
+ ASSERT(!m_suspended);
+ m_pendingTasksTimer.stop();
+ m_suspended = true;
+}
+
+void MainThreadTaskRunner::resume()
+{
+ ASSERT(m_suspended);
+ if (!m_pendingTasks.isEmpty())
+ m_pendingTasksTimer.startOneShot(0);
+
+ m_suspended = false;
+}
+
+void MainThreadTaskRunner::pendingTasksTimerFired(Timer<MainThreadTaskRunner>*)
+{
+ while (!m_pendingTasks.isEmpty()) {
+ OwnPtr<ExecutionContextTask> task = m_pendingTasks[0].release();
+ m_pendingTasks.remove(0);
+ task->performTask(m_context);
+ }
+}
+
+} // namespace
diff --git a/chromium/third_party/WebKit/Source/core/dom/MainThreadTaskRunner.h b/chromium/third_party/WebKit/Source/core/dom/MainThreadTaskRunner.h
new file mode 100644
index 00000000000..a61a2267261
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/MainThreadTaskRunner.h
@@ -0,0 +1,77 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef MainThreadTaskRunner_h
+#define MainThreadTaskRunner_h
+
+#include "platform/Timer.h"
+
+#include "wtf/FastAllocBase.h"
+#include "wtf/Noncopyable.h"
+#include "wtf/OwnPtr.h"
+#include "wtf/PassOwnPtr.h"
+#include "wtf/Vector.h"
+#include "wtf/WeakPtr.h"
+
+namespace WebCore {
+
+class ExecutionContext;
+class ExecutionContextTask;
+
+class MainThreadTaskRunner {
+ WTF_MAKE_NONCOPYABLE(MainThreadTaskRunner);
+ WTF_MAKE_FAST_ALLOCATED;
+
+public:
+ static PassOwnPtr<MainThreadTaskRunner> create(ExecutionContext*);
+
+ ~MainThreadTaskRunner();
+
+ void postTask(PassOwnPtr<ExecutionContextTask>); // Executes the task on context's thread asynchronously.
+ void perform(PassOwnPtr<ExecutionContextTask>);
+ void suspend();
+ void resume();
+
+private:
+ explicit MainThreadTaskRunner(ExecutionContext*);
+
+ void pendingTasksTimerFired(Timer<MainThreadTaskRunner>*);
+
+ ExecutionContext* m_context;
+ WeakPtrFactory<MainThreadTaskRunner> m_weakFactory;
+ Timer<MainThreadTaskRunner> m_pendingTasksTimer;
+ Vector<OwnPtr<ExecutionContextTask> > m_pendingTasks;
+ bool m_suspended;
+};
+
+inline PassOwnPtr<MainThreadTaskRunner> MainThreadTaskRunner::create(ExecutionContext* context)
+{
+ return adoptPtr(new MainThreadTaskRunner(context));
+}
+
+} // namespace
+
+#endif
diff --git a/chromium/third_party/WebKit/Source/core/dom/MainThreadTaskRunnerTest.cpp b/chromium/third_party/WebKit/Source/core/dom/MainThreadTaskRunnerTest.cpp
new file mode 100644
index 00000000000..ca1779947a4
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/MainThreadTaskRunnerTest.cpp
@@ -0,0 +1,139 @@
+/*
+ * Copyright (C) 2008 Apple Inc. All Rights Reserved.
+ * Copyright (C) 2013 Google Inc. All Rights Reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "config.h"
+#include "core/dom/MainThreadTaskRunner.h"
+
+#include "core/dom/ExecutionContext.h"
+#include "core/dom/ExecutionContextTask.h"
+#include "core/events/EventQueue.h"
+#include "core/testing/UnitTestHelpers.h"
+#include <gtest/gtest.h>
+
+using namespace WebCore;
+
+namespace {
+
+class NullEventQueue : public EventQueue {
+public:
+ NullEventQueue() { }
+ virtual ~NullEventQueue() { }
+ virtual bool enqueueEvent(PassRefPtr<Event>) OVERRIDE { return true; }
+ virtual bool cancelEvent(Event*) OVERRIDE { return true; }
+ virtual void close() OVERRIDE { }
+};
+
+class NullExecutionContext : public ExecutionContext, public RefCounted<NullExecutionContext> {
+public:
+ using RefCounted<NullExecutionContext>::ref;
+ using RefCounted<NullExecutionContext>::deref;
+
+ virtual void refExecutionContext() OVERRIDE { ref(); }
+ virtual void derefExecutionContext() OVERRIDE { deref(); }
+ virtual EventQueue* eventQueue() const OVERRIDE { return m_queue.get(); }
+ virtual bool tasksNeedSuspension() { return m_tasksNeedSuspension; }
+
+ void setTasksNeedSuspention(bool flag) { m_tasksNeedSuspension = flag; }
+
+ NullExecutionContext();
+
+private:
+ bool m_tasksNeedSuspension;
+ OwnPtr<EventQueue> m_queue;
+};
+
+NullExecutionContext::NullExecutionContext()
+ : m_tasksNeedSuspension(false)
+ , m_queue(adoptPtr(new NullEventQueue()))
+{
+}
+
+class MarkingBooleanTask FINAL : public ExecutionContextTask {
+public:
+ static PassOwnPtr<MarkingBooleanTask> create(bool* toBeMarked)
+ {
+ return adoptPtr(new MarkingBooleanTask(toBeMarked));
+ }
+
+
+ virtual ~MarkingBooleanTask() { }
+
+private:
+ MarkingBooleanTask(bool* toBeMarked) : m_toBeMarked(toBeMarked) { }
+
+ virtual void performTask(ExecutionContext* context) OVERRIDE
+ {
+ *m_toBeMarked = true;
+ }
+
+ bool* m_toBeMarked;
+};
+
+TEST(MainThreadTaskRunnerTest, PostTask)
+{
+ RefPtr<NullExecutionContext> context = adoptRef(new NullExecutionContext());
+ OwnPtr<MainThreadTaskRunner> runner = MainThreadTaskRunner::create(context.get());
+ bool isMarked = false;
+
+ runner->postTask(MarkingBooleanTask::create(&isMarked));
+ EXPECT_FALSE(isMarked);
+ WebCore::testing::runPendingTasks();
+ EXPECT_TRUE(isMarked);
+}
+
+TEST(MainThreadTaskRunnerTest, SuspendTask)
+{
+ RefPtr<NullExecutionContext> context = adoptRef(new NullExecutionContext());
+ OwnPtr<MainThreadTaskRunner> runner = MainThreadTaskRunner::create(context.get());
+ bool isMarked = false;
+
+ context->setTasksNeedSuspention(true);
+ runner->postTask(MarkingBooleanTask::create(&isMarked));
+ runner->suspend();
+ WebCore::testing::runPendingTasks();
+ EXPECT_FALSE(isMarked);
+
+ context->setTasksNeedSuspention(false);
+ runner->resume();
+ WebCore::testing::runPendingTasks();
+ EXPECT_TRUE(isMarked);
+}
+
+TEST(MainThreadTaskRunnerTest, RemoveRunner)
+{
+ RefPtr<NullExecutionContext> context = adoptRef(new NullExecutionContext());
+ OwnPtr<MainThreadTaskRunner> runner = MainThreadTaskRunner::create(context.get());
+ bool isMarked = false;
+
+ context->setTasksNeedSuspention(true);
+ runner->postTask(MarkingBooleanTask::create(&isMarked));
+ runner.clear();
+ WebCore::testing::runPendingTasks();
+ EXPECT_FALSE(isMarked);
+}
+
+}
diff --git a/chromium/third_party/WebKit/Source/core/dom/MessageChannel.cpp b/chromium/third_party/WebKit/Source/core/dom/MessageChannel.cpp
index 4c65face9c5..20a493d97c8 100644
--- a/chromium/third_party/WebKit/Source/core/dom/MessageChannel.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/MessageChannel.cpp
@@ -28,16 +28,32 @@
#include "core/dom/MessageChannel.h"
#include "core/dom/MessagePort.h"
-#include "core/dom/MessagePortChannel.h"
+#include "public/platform/Platform.h"
+#include "public/platform/WebMessagePortChannel.h"
namespace WebCore {
-MessageChannel::MessageChannel(ScriptExecutionContext* context)
+static void createChannel(MessagePort* port1, MessagePort* port2)
+{
+ // Create proxies for each endpoint.
+ OwnPtr<blink::WebMessagePortChannel> channel1 = adoptPtr(blink::Platform::current()->createMessagePortChannel());
+ OwnPtr<blink::WebMessagePortChannel> channel2 = adoptPtr(blink::Platform::current()->createMessagePortChannel());
+
+ // Entangle the two endpoints.
+ channel1->entangle(channel2.get());
+ channel2->entangle(channel1.get());
+
+ // Now entangle the proxies with the appropriate local ports.
+ port1->entangle(channel2.release());
+ port2->entangle(channel1.release());
+}
+
+MessageChannel::MessageChannel(ExecutionContext* context)
: m_port1(MessagePort::create(*context))
, m_port2(MessagePort::create(*context))
{
ScriptWrappable::init(this);
- MessagePortChannel::createChannel(m_port1.get(), m_port2.get());
+ createChannel(m_port1.get(), m_port2.get());
}
MessageChannel::~MessageChannel()
diff --git a/chromium/third_party/WebKit/Source/core/dom/MessageChannel.h b/chromium/third_party/WebKit/Source/core/dom/MessageChannel.h
index 507825b29cd..5b1dc49a04f 100644
--- a/chromium/third_party/WebKit/Source/core/dom/MessageChannel.h
+++ b/chromium/third_party/WebKit/Source/core/dom/MessageChannel.h
@@ -35,18 +35,18 @@
namespace WebCore {
class MessagePort;
-class ScriptExecutionContext;
+class ExecutionContext;
class MessageChannel : public RefCounted<MessageChannel>, public ScriptWrappable {
public:
- static PassRefPtr<MessageChannel> create(ScriptExecutionContext* context) { return adoptRef(new MessageChannel(context)); }
+ static PassRefPtr<MessageChannel> create(ExecutionContext* context) { return adoptRef(new MessageChannel(context)); }
~MessageChannel();
MessagePort* port1() const { return m_port1.get(); }
MessagePort* port2() const { return m_port2.get(); }
private:
- explicit MessageChannel(ScriptExecutionContext*);
+ explicit MessageChannel(ExecutionContext*);
RefPtr<MessagePort> m_port1;
RefPtr<MessagePort> m_port2;
diff --git a/chromium/third_party/WebKit/Source/core/dom/MessageChannel.idl b/chromium/third_party/WebKit/Source/core/dom/MessageChannel.idl
index f5b516524ff..fbd8babde20 100644
--- a/chromium/third_party/WebKit/Source/core/dom/MessageChannel.idl
+++ b/chromium/third_party/WebKit/Source/core/dom/MessageChannel.idl
@@ -25,8 +25,8 @@
*/
[
+ CustomConstructor,
GlobalContext=Window&WorkerGlobalScope,
- CustomConstructor
] interface MessageChannel {
readonly attribute MessagePort port1;
readonly attribute MessagePort port2;
diff --git a/chromium/third_party/WebKit/Source/core/dom/MessageEvent.cpp b/chromium/third_party/WebKit/Source/core/dom/MessageEvent.cpp
deleted file mode 100644
index 2bfbf006187..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/MessageEvent.cpp
+++ /dev/null
@@ -1,158 +0,0 @@
-/*
- * Copyright (C) 2007 Henry Mason (hmason@mac.com)
- * Copyright (C) 2003, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-#include "config.h"
-#include "core/dom/MessageEvent.h"
-
-#include "core/dom/EventNames.h"
-#include "core/page/DOMWindow.h"
-
-namespace WebCore {
-
-static inline bool isValidSource(EventTarget* source)
-{
- return !source || source->toDOMWindow() || source->toMessagePort();
-}
-
-MessageEventInit::MessageEventInit()
-{
-}
-
-MessageEvent::MessageEvent()
- : m_dataType(DataTypeScriptValue)
-{
- ScriptWrappable::init(this);
-}
-
-MessageEvent::MessageEvent(const AtomicString& type, const MessageEventInit& initializer)
- : Event(type, initializer)
- , m_dataType(DataTypeScriptValue)
- , m_origin(initializer.origin)
- , m_lastEventId(initializer.lastEventId)
- , m_source(isValidSource(initializer.source.get()) ? initializer.source : 0)
- , m_ports(adoptPtr(new MessagePortArray(initializer.ports)))
-{
- ScriptWrappable::init(this);
- ASSERT(isValidSource(m_source.get()));
-}
-
-MessageEvent::MessageEvent(const String& origin, const String& lastEventId, PassRefPtr<EventTarget> source, PassOwnPtr<MessagePortArray> ports)
- : Event(eventNames().messageEvent, false, false)
- , m_dataType(DataTypeScriptValue)
- , m_origin(origin)
- , m_lastEventId(lastEventId)
- , m_source(source)
- , m_ports(ports)
-{
- ScriptWrappable::init(this);
- ASSERT(isValidSource(m_source.get()));
-}
-
-MessageEvent::MessageEvent(PassRefPtr<SerializedScriptValue> data, const String& origin, const String& lastEventId, PassRefPtr<EventTarget> source, PassOwnPtr<MessagePortArray> ports)
- : Event(eventNames().messageEvent, false, false)
- , m_dataType(DataTypeSerializedScriptValue)
- , m_dataAsSerializedScriptValue(data)
- , m_origin(origin)
- , m_lastEventId(lastEventId)
- , m_source(source)
- , m_ports(ports)
-{
- ScriptWrappable::init(this);
- if (m_dataAsSerializedScriptValue)
- m_dataAsSerializedScriptValue->registerMemoryAllocatedWithCurrentScriptContext();
- ASSERT(isValidSource(m_source.get()));
-}
-
-MessageEvent::MessageEvent(const String& data, const String& origin)
- : Event(eventNames().messageEvent, false, false)
- , m_dataType(DataTypeString)
- , m_dataAsString(data)
- , m_origin(origin)
-{
- ScriptWrappable::init(this);
-}
-
-MessageEvent::MessageEvent(PassRefPtr<Blob> data, const String& origin)
- : Event(eventNames().messageEvent, false, false)
- , m_dataType(DataTypeBlob)
- , m_dataAsBlob(data)
- , m_origin(origin)
-{
- ScriptWrappable::init(this);
-}
-
-MessageEvent::MessageEvent(PassRefPtr<ArrayBuffer> data, const String& origin)
- : Event(eventNames().messageEvent, false, false)
- , m_dataType(DataTypeArrayBuffer)
- , m_dataAsArrayBuffer(data)
- , m_origin(origin)
-{
- ScriptWrappable::init(this);
-}
-
-MessageEvent::~MessageEvent()
-{
-}
-
-void MessageEvent::initMessageEvent(const AtomicString& type, bool canBubble, bool cancelable, const String& origin, const String& lastEventId, DOMWindow* source, PassOwnPtr<MessagePortArray> ports)
-{
- if (dispatched())
- return;
-
- initEvent(type, canBubble, cancelable);
-
- m_dataType = DataTypeScriptValue;
- m_origin = origin;
- m_lastEventId = lastEventId;
- m_source = source;
- m_ports = ports;
-}
-
-void MessageEvent::initMessageEvent(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<SerializedScriptValue> data, const String& origin, const String& lastEventId, DOMWindow* source, PassOwnPtr<MessagePortArray> ports)
-{
- if (dispatched())
- return;
-
- initEvent(type, canBubble, cancelable);
-
- m_dataType = DataTypeSerializedScriptValue;
- m_dataAsSerializedScriptValue = data;
- m_origin = origin;
- m_lastEventId = lastEventId;
- m_source = source;
- m_ports = ports;
-
- if (m_dataAsSerializedScriptValue)
- m_dataAsSerializedScriptValue->registerMemoryAllocatedWithCurrentScriptContext();
-}
-
-const AtomicString& MessageEvent::interfaceName() const
-{
- return eventNames().interfaceForMessageEvent;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/MessageEvent.h b/chromium/third_party/WebKit/Source/core/dom/MessageEvent.h
deleted file mode 100644
index 71dc3884f70..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/MessageEvent.h
+++ /dev/null
@@ -1,134 +0,0 @@
-/*
- * Copyright (C) 2007 Henry Mason (hmason@mac.com)
- * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-#ifndef MessageEvent_h
-#define MessageEvent_h
-
-#include "bindings/v8/SerializedScriptValue.h"
-#include "core/dom/Event.h"
-#include "core/dom/EventTarget.h"
-#include "core/dom/MessagePort.h"
-#include "core/fileapi/Blob.h"
-#include "core/page/DOMWindow.h"
-#include "wtf/ArrayBuffer.h"
-
-namespace WebCore {
-
-struct MessageEventInit : public EventInit {
- MessageEventInit();
-
- String origin;
- String lastEventId;
- RefPtr<EventTarget> source;
- MessagePortArray ports;
-};
-
-class MessageEvent : public Event {
-public:
- static PassRefPtr<MessageEvent> create()
- {
- return adoptRef(new MessageEvent);
- }
- static PassRefPtr<MessageEvent> create(PassOwnPtr<MessagePortArray> ports, const String& origin = String(), const String& lastEventId = String(), PassRefPtr<EventTarget> source = 0)
- {
- return adoptRef(new MessageEvent(origin, lastEventId, source, ports));
- }
- static PassRefPtr<MessageEvent> create(PassOwnPtr<MessagePortArray> ports, PassRefPtr<SerializedScriptValue> data, const String& origin = String(), const String& lastEventId = String(), PassRefPtr<EventTarget> source = 0)
- {
- return adoptRef(new MessageEvent(data, origin, lastEventId, source, ports));
- }
- static PassRefPtr<MessageEvent> create(const String& data, const String& origin = String())
- {
- return adoptRef(new MessageEvent(data, origin));
- }
- static PassRefPtr<MessageEvent> create(PassRefPtr<Blob> data, const String& origin = String())
- {
- return adoptRef(new MessageEvent(data, origin));
- }
- static PassRefPtr<MessageEvent> create(PassRefPtr<ArrayBuffer> data, const String& origin = String())
- {
- return adoptRef(new MessageEvent(data, origin));
- }
- static PassRefPtr<MessageEvent> create(const AtomicString& type, const MessageEventInit& initializer)
- {
- return adoptRef(new MessageEvent(type, initializer));
- }
- virtual ~MessageEvent();
-
- void initMessageEvent(const AtomicString& type, bool canBubble, bool cancelable, const String& origin, const String& lastEventId, DOMWindow* source, PassOwnPtr<MessagePortArray>);
- void initMessageEvent(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<SerializedScriptValue> data, const String& origin, const String& lastEventId, DOMWindow* source, PassOwnPtr<MessagePortArray>);
-
- const String& origin() const { return m_origin; }
- const String& lastEventId() const { return m_lastEventId; }
- EventTarget* source() const { return m_source.get(); }
- MessagePortArray ports() const { return m_ports ? *m_ports : MessagePortArray(); }
-
- virtual const AtomicString& interfaceName() const;
-
- enum DataType {
- DataTypeScriptValue,
- DataTypeSerializedScriptValue,
- DataTypeString,
- DataTypeBlob,
- DataTypeArrayBuffer
- };
- DataType dataType() const { return m_dataType; }
- SerializedScriptValue* dataAsSerializedScriptValue() const { ASSERT(m_dataType == DataTypeScriptValue || m_dataType == DataTypeSerializedScriptValue); return m_dataAsSerializedScriptValue.get(); }
- String dataAsString() const { ASSERT(m_dataType == DataTypeString); return m_dataAsString; }
- Blob* dataAsBlob() const { ASSERT(m_dataType == DataTypeBlob); return m_dataAsBlob.get(); }
- ArrayBuffer* dataAsArrayBuffer() const { ASSERT(m_dataType == DataTypeArrayBuffer); return m_dataAsArrayBuffer.get(); }
-
- void setSerializedData(PassRefPtr<SerializedScriptValue> data)
- {
- ASSERT(!m_dataAsSerializedScriptValue);
- m_dataAsSerializedScriptValue = data;
- }
-
-private:
- MessageEvent();
- MessageEvent(const AtomicString&, const MessageEventInit&);
- MessageEvent(const String& origin, const String& lastEventId, PassRefPtr<EventTarget> source, PassOwnPtr<MessagePortArray>);
- MessageEvent(PassRefPtr<SerializedScriptValue> data, const String& origin, const String& lastEventId, PassRefPtr<EventTarget> source, PassOwnPtr<MessagePortArray>);
-
- explicit MessageEvent(const String& data, const String& origin);
- explicit MessageEvent(PassRefPtr<Blob> data, const String& origin);
- explicit MessageEvent(PassRefPtr<ArrayBuffer> data, const String& origin);
-
- DataType m_dataType;
- RefPtr<SerializedScriptValue> m_dataAsSerializedScriptValue;
- String m_dataAsString;
- RefPtr<Blob> m_dataAsBlob;
- RefPtr<ArrayBuffer> m_dataAsArrayBuffer;
- String m_origin;
- String m_lastEventId;
- RefPtr<EventTarget> m_source;
- OwnPtr<MessagePortArray> m_ports;
-};
-
-} // namespace WebCore
-
-#endif // MessageEvent_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/MessageEvent.idl b/chromium/third_party/WebKit/Source/core/dom/MessageEvent.idl
deleted file mode 100644
index 33d1c33f462..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/MessageEvent.idl
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright (C) 2007 Henry Mason <hmason@mac.com>
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-[
- GlobalContext=Window&WorkerGlobalScope,
- ConstructorTemplate=Event
-] interface MessageEvent : Event {
- [InitializedByEventConstructor] readonly attribute DOMString origin;
- [InitializedByEventConstructor] readonly attribute DOMString lastEventId;
- [InitializedByEventConstructor] readonly attribute EventTarget source; // May be a Window or a MessagePort
- [InitializedByEventConstructor, CustomGetter] readonly attribute any data;
- [InitializedByEventConstructor] readonly attribute MessagePort[] ports;
-
- [Custom] void initMessageEvent([Default=Undefined] optional DOMString typeArg,
- [Default=Undefined] optional boolean canBubbleArg,
- [Default=Undefined] optional boolean cancelableArg,
- [Default=Undefined] optional any dataArg,
- [Default=Undefined] optional DOMString originArg,
- [Default=Undefined] optional DOMString lastEventIdArg,
- [Default=Undefined] optional Window sourceArg,
- [Default=Undefined] optional Array messagePorts);
-
- [Custom] void webkitInitMessageEvent([Default=Undefined] optional DOMString typeArg,
- [Default=Undefined] optional boolean canBubbleArg,
- [Default=Undefined] optional boolean cancelableArg,
- [Default=Undefined] optional any dataArg,
- [Default=Undefined] optional DOMString originArg,
- [Default=Undefined] optional DOMString lastEventIdArg,
- [Default=Undefined] optional Window sourceArg,
- [Default=Undefined] optional Array transferables);
-};
-
diff --git a/chromium/third_party/WebKit/Source/core/dom/MessagePort.cpp b/chromium/third_party/WebKit/Source/core/dom/MessagePort.cpp
index 9b3f1cd5f28..887bfc9bad7 100644
--- a/chromium/third_party/WebKit/Source/core/dom/MessagePort.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/MessagePort.cpp
@@ -29,68 +29,77 @@
#include "bindings/v8/ExceptionState.h"
#include "bindings/v8/ExceptionStatePlaceholder.h"
+#include "bindings/v8/SerializedScriptValue.h"
#include "core/dom/Document.h"
-#include "core/dom/EventNames.h"
#include "core/dom/ExceptionCode.h"
-#include "core/dom/MessageEvent.h"
-#include "core/page/DOMWindow.h"
+#include "core/dom/ExecutionContext.h"
+#include "core/events/MessageEvent.h"
+#include "core/events/ThreadLocalEventNames.h"
+#include "core/frame/DOMWindow.h"
#include "core/workers/WorkerGlobalScope.h"
+#include "public/platform/WebString.h"
+#include "wtf/Functional.h"
#include "wtf/text/AtomicString.h"
namespace WebCore {
-MessagePort::MessagePort(ScriptExecutionContext& scriptExecutionContext)
- : m_started(false)
+PassRefPtr<MessagePort> MessagePort::create(ExecutionContext& executionContext)
+{
+ RefPtr<MessagePort> port = adoptRef(new MessagePort(executionContext));
+ port->suspendIfNeeded();
+ return port.release();
+}
+
+MessagePort::MessagePort(ExecutionContext& executionContext)
+ : ActiveDOMObject(&executionContext)
+ , m_started(false)
, m_closed(false)
- , m_scriptExecutionContext(&scriptExecutionContext)
+ , m_weakFactory(this)
{
ScriptWrappable::init(this);
- m_scriptExecutionContext->createdMessagePort(this);
-
- // Don't need to call processMessagePortMessagesSoon() here, because the port will not be opened until start() is invoked.
}
MessagePort::~MessagePort()
{
close();
- if (m_scriptExecutionContext)
- m_scriptExecutionContext->destroyedMessagePort(this);
}
-void MessagePort::postMessage(PassRefPtr<SerializedScriptValue> message, const MessagePortArray* ports, ExceptionState& es)
+void MessagePort::postMessage(PassRefPtr<SerializedScriptValue> message, const MessagePortArray* ports, ExceptionState& exceptionState)
{
if (!isEntangled())
return;
- ASSERT(m_scriptExecutionContext);
+ ASSERT(executionContext());
+ ASSERT(m_entangledChannel);
OwnPtr<MessagePortChannelArray> channels;
// Make sure we aren't connected to any of the passed-in ports.
if (ports) {
for (unsigned int i = 0; i < ports->size(); ++i) {
MessagePort* dataPort = (*ports)[i].get();
- if (dataPort == this || m_entangledChannel->isConnectedTo(dataPort)) {
- es.throwDOMException(DataCloneError);
+ if (dataPort == this) {
+ exceptionState.throwDOMException(DataCloneError, "Item #" + String::number(i) + " in the array of ports contains the source port.");
return;
}
}
- channels = MessagePort::disentanglePorts(ports, es);
- if (es.hadException())
+ channels = MessagePort::disentanglePorts(ports, exceptionState);
+ if (exceptionState.hadException())
return;
}
- m_entangledChannel->postMessageToRemote(message, channels.release());
+
+ blink::WebString messageString = message->toWireString();
+ blink::WebMessagePortChannelArray* webChannels = 0;
+ if (channels && channels->size()) {
+ webChannels = new blink::WebMessagePortChannelArray(channels->size());
+ for (size_t i = 0; i < channels->size(); ++i)
+ (*webChannels)[i] = (*channels)[i].leakPtr();
+ }
+ m_entangledChannel->postMessage(messageString, webChannels);
}
-PassOwnPtr<MessagePortChannel> MessagePort::disentangle()
+PassOwnPtr<blink::WebMessagePortChannel> MessagePort::disentangle()
{
ASSERT(m_entangledChannel);
-
- m_entangledChannel->disentangle();
-
- // We can't receive any messages or generate any events, so remove ourselves from the list of active ports.
- ASSERT(m_scriptExecutionContext);
- m_scriptExecutionContext->destroyedMessagePort(this);
- m_scriptExecutionContext = 0;
-
+ m_entangledChannel->setClient(0);
return m_entangledChannel.release();
}
@@ -98,8 +107,8 @@ PassOwnPtr<MessagePortChannel> MessagePort::disentangle()
// This code may be called from another thread, and so should not call any non-threadsafe APIs (i.e. should not call into the entangled channel or access mutable variables).
void MessagePort::messageAvailable()
{
- ASSERT(m_scriptExecutionContext);
- m_scriptExecutionContext->processMessagePortMessagesSoon();
+ ASSERT(executionContext());
+ executionContext()->postTask(bind(&MessagePort::dispatchMessages, m_weakFactory.createWeakPtr()));
}
void MessagePort::start()
@@ -108,89 +117,81 @@ void MessagePort::start()
if (!isEntangled())
return;
- ASSERT(m_scriptExecutionContext);
+ ASSERT(executionContext());
if (m_started)
return;
m_started = true;
- m_scriptExecutionContext->processMessagePortMessagesSoon();
+ messageAvailable();
}
void MessagePort::close()
{
if (isEntangled())
- m_entangledChannel->close();
+ m_entangledChannel->setClient(0);
m_closed = true;
}
-void MessagePort::entangle(PassOwnPtr<MessagePortChannel> remote)
+void MessagePort::entangle(PassOwnPtr<blink::WebMessagePortChannel> remote)
{
// Only invoked to set our initial entanglement.
ASSERT(!m_entangledChannel);
- ASSERT(m_scriptExecutionContext);
+ ASSERT(executionContext());
- // Don't entangle the ports if the channel is closed.
- if (remote->entangleIfOpen(this))
- m_entangledChannel = remote;
-}
-
-void MessagePort::contextDestroyed()
-{
- ASSERT(m_scriptExecutionContext);
- // Must be closed before blowing away the cached context, to ensure that we get no more calls to messageAvailable().
- // ScriptExecutionContext::closeMessagePorts() takes care of that.
- ASSERT(m_closed);
- m_scriptExecutionContext = 0;
+ m_entangledChannel = remote;
+ m_entangledChannel->setClient(this);
}
const AtomicString& MessagePort::interfaceName() const
{
- return eventNames().interfaceForMessagePort;
+ return EventTargetNames::MessagePort;
}
-ScriptExecutionContext* MessagePort::scriptExecutionContext() const
+static bool tryGetMessageFrom(blink::WebMessagePortChannel& webChannel, RefPtr<SerializedScriptValue>& message, OwnPtr<MessagePortChannelArray>& channels)
{
- return m_scriptExecutionContext;
+ blink::WebString messageString;
+ blink::WebMessagePortChannelArray webChannels;
+ if (!webChannel.tryGetMessage(&messageString, webChannels))
+ return false;
+
+ if (webChannels.size()) {
+ channels = adoptPtr(new MessagePortChannelArray(webChannels.size()));
+ for (size_t i = 0; i < webChannels.size(); ++i)
+ (*channels)[i] = adoptPtr(webChannels[i]);
+ }
+ message = SerializedScriptValue::createFromWire(messageString);
+ return true;
}
void MessagePort::dispatchMessages()
{
// Messages for contexts that are not fully active get dispatched too, but JSAbstractEventListener::handleEvent() doesn't call handlers for these.
// The HTML5 spec specifies that any messages sent to a document that is not fully active should be dropped, so this behavior is OK.
- ASSERT(started());
+ if (!started())
+ return;
RefPtr<SerializedScriptValue> message;
OwnPtr<MessagePortChannelArray> channels;
- while (m_entangledChannel && m_entangledChannel->tryGetMessageFromRemote(message, channels)) {
-
+ while (m_entangledChannel && tryGetMessageFrom(*m_entangledChannel, message, channels)) {
// close() in Worker onmessage handler should prevent next message from dispatching.
- if (m_scriptExecutionContext->isWorkerGlobalScope() && toWorkerGlobalScope(m_scriptExecutionContext)->isClosing())
+ if (executionContext()->isWorkerGlobalScope() && toWorkerGlobalScope(executionContext())->isClosing())
return;
- OwnPtr<MessagePortArray> ports = MessagePort::entanglePorts(*m_scriptExecutionContext, channels.release());
+ OwnPtr<MessagePortArray> ports = MessagePort::entanglePorts(*executionContext(), channels.release());
RefPtr<Event> evt = MessageEvent::create(ports.release(), message.release());
dispatchEvent(evt.release(), ASSERT_NO_EXCEPTION);
}
}
-bool MessagePort::hasPendingActivity()
+bool MessagePort::hasPendingActivity() const
{
// The spec says that entangled message ports should always be treated as if they have a strong reference.
// We'll also stipulate that the queue needs to be open (if the app drops its reference to the port before start()-ing it, then it's not really entangled as it's unreachable).
- if (m_started && m_entangledChannel && m_entangledChannel->hasPendingActivity())
- return true;
- if (isEntangled() && !locallyEntangledPort())
- return true;
- return false;
+ return m_started && isEntangled();
}
-MessagePort* MessagePort::locallyEntangledPort()
-{
- return m_entangledChannel ? m_entangledChannel->locallyEntangledPort(m_scriptExecutionContext) : 0;
-}
-
-PassOwnPtr<MessagePortChannelArray> MessagePort::disentanglePorts(const MessagePortArray* ports, ExceptionState& es)
+PassOwnPtr<MessagePortChannelArray> MessagePort::disentanglePorts(const MessagePortArray* ports, ExceptionState& exceptionState)
{
if (!ports || !ports->size())
return nullptr;
@@ -199,10 +200,17 @@ PassOwnPtr<MessagePortChannelArray> MessagePort::disentanglePorts(const MessageP
HashSet<MessagePort*> portSet;
// Walk the incoming array - if there are any duplicate ports, or null ports or cloned ports, throw an error (per section 8.3.3 of the HTML5 spec).
- for (unsigned int i = 0; i < ports->size(); ++i) {
+ for (unsigned i = 0; i < ports->size(); ++i) {
MessagePort* port = (*ports)[i].get();
if (!port || port->isNeutered() || portSet.contains(port)) {
- es.throwDOMException(DataCloneError);
+ String type;
+ if (!port)
+ type = "null";
+ else if (port->isNeutered())
+ type = "already neutered";
+ else
+ type = "a duplicate";
+ exceptionState.throwDOMException(DataCloneError, "Item #" + String::number(i) + " in the array of ports is " + type + ".");
return nullptr;
}
portSet.add(port);
@@ -210,14 +218,12 @@ PassOwnPtr<MessagePortChannelArray> MessagePort::disentanglePorts(const MessageP
// Passed-in ports passed validity checks, so we can disentangle them.
OwnPtr<MessagePortChannelArray> portArray = adoptPtr(new MessagePortChannelArray(ports->size()));
- for (unsigned int i = 0 ; i < ports->size() ; ++i) {
- OwnPtr<MessagePortChannel> channel = (*ports)[i]->disentangle();
- (*portArray)[i] = channel.release();
- }
+ for (unsigned i = 0; i < ports->size(); ++i)
+ (*portArray)[i] = (*ports)[i]->disentangle();
return portArray.release();
}
-PassOwnPtr<MessagePortArray> MessagePort::entanglePorts(ScriptExecutionContext& context, PassOwnPtr<MessagePortChannelArray> channels)
+PassOwnPtr<MessagePortArray> MessagePort::entanglePorts(ExecutionContext& context, PassOwnPtr<MessagePortChannelArray> channels)
{
if (!channels || !channels->size())
return nullptr;
@@ -231,14 +237,4 @@ PassOwnPtr<MessagePortArray> MessagePort::entanglePorts(ScriptExecutionContext&
return portArray.release();
}
-EventTargetData* MessagePort::eventTargetData()
-{
- return &m_eventTargetData;
-}
-
-EventTargetData* MessagePort::ensureEventTargetData()
-{
- return &m_eventTargetData;
-}
-
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/MessagePort.h b/chromium/third_party/WebKit/Source/core/dom/MessagePort.h
index 34773c9bc35..c5f78eac9ee 100644
--- a/chromium/third_party/WebKit/Source/core/dom/MessagePort.h
+++ b/chromium/third_party/WebKit/Source/core/dom/MessagePort.h
@@ -28,15 +28,18 @@
#define MessagePort_h
#include "bindings/v8/ScriptWrappable.h"
-#include "core/dom/EventListener.h"
-#include "core/dom/EventTarget.h"
-#include "core/dom/MessagePortChannel.h"
-#include "wtf/Forward.h"
+#include "core/dom/ActiveDOMObject.h"
+#include "core/events/EventListener.h"
+#include "core/events/EventTarget.h"
+#include "public/platform/WebMessagePortChannel.h"
+#include "public/platform/WebMessagePortChannelClient.h"
#include "wtf/OwnPtr.h"
#include "wtf/PassOwnPtr.h"
#include "wtf/PassRefPtr.h"
+#include "wtf/RefCounted.h"
#include "wtf/RefPtr.h"
#include "wtf/Vector.h"
+#include "wtf/WeakPtr.h"
namespace WebCore {
@@ -44,14 +47,23 @@ class Event;
class ExceptionState;
class Frame;
class MessagePort;
-class ScriptExecutionContext;
+class ExecutionContext;
+class SerializedScriptValue;
// The overwhelmingly common case is sending a single port, so handle that efficiently with an inline buffer of size 1.
typedef Vector<RefPtr<MessagePort>, 1> MessagePortArray;
-class MessagePort : public RefCounted<MessagePort>, public ScriptWrappable, public EventTarget {
+// Not to be confused with blink::WebMessagePortChannelArray; this one uses Vector and OwnPtr instead of WebVector and raw pointers.
+typedef Vector<OwnPtr<blink::WebMessagePortChannel>, 1> MessagePortChannelArray;
+
+class MessagePort : public RefCounted<MessagePort>
+ , public ActiveDOMObject
+ , public EventTargetWithInlineData
+ , public ScriptWrappable
+ , public blink::WebMessagePortChannelClient {
+ REFCOUNTED_EVENT_TARGET(MessagePort);
public:
- static PassRefPtr<MessagePort> create(ScriptExecutionContext& scriptExecutionContext) { return adoptRef(new MessagePort(scriptExecutionContext)); }
+ static PassRefPtr<MessagePort> create(ExecutionContext&);
virtual ~MessagePort();
void postMessage(PassRefPtr<SerializedScriptValue> message, const MessagePortArray*, ExceptionState&);
@@ -59,64 +71,51 @@ public:
void start();
void close();
- void entangle(PassOwnPtr<MessagePortChannel>);
- PassOwnPtr<MessagePortChannel> disentangle();
+ void entangle(PassOwnPtr<blink::WebMessagePortChannel>);
+ PassOwnPtr<blink::WebMessagePortChannel> disentangle();
// Returns 0 if there is an exception, or if the passed-in array is 0/empty.
static PassOwnPtr<MessagePortChannelArray> disentanglePorts(const MessagePortArray*, ExceptionState&);
// Returns 0 if the passed array is 0/empty.
- static PassOwnPtr<MessagePortArray> entanglePorts(ScriptExecutionContext&, PassOwnPtr<MessagePortChannelArray>);
+ static PassOwnPtr<MessagePortArray> entanglePorts(ExecutionContext&, PassOwnPtr<MessagePortChannelArray>);
- void messageAvailable();
bool started() const { return m_started; }
- void contextDestroyed();
-
virtual const AtomicString& interfaceName() const OVERRIDE;
- virtual ScriptExecutionContext* scriptExecutionContext() const OVERRIDE;
+ virtual ExecutionContext* executionContext() const OVERRIDE { return ActiveDOMObject::executionContext(); }
MessagePort* toMessagePort() OVERRIDE { return this; }
- void dispatchMessages();
-
- using RefCounted<MessagePort>::ref;
- using RefCounted<MessagePort>::deref;
-
- bool hasPendingActivity();
+ // ActiveDOMObject implementation.
+ virtual bool hasPendingActivity() const OVERRIDE;
+ virtual void stop() OVERRIDE { close(); }
void setOnmessage(PassRefPtr<EventListener> listener, DOMWrapperWorld* world)
{
- setAttributeEventListener(eventNames().messageEvent, listener, world);
+ setAttributeEventListener(EventTypeNames::message, listener, world);
start();
}
- EventListener* onmessage(DOMWrapperWorld* world) { return getAttributeEventListener(eventNames().messageEvent, world); }
-
- // Returns null if there is no entangled port, or if the entangled port is run by a different thread.
- // This is used solely to enable a GC optimization. Some platforms may not be able to determine ownership
- // of the remote port (since it may live cross-process) - those platforms may always return null.
- MessagePort* locallyEntangledPort();
+ EventListener* onmessage(DOMWrapperWorld* world) { return getAttributeEventListener(EventTypeNames::message, world); }
// A port starts out its life entangled, and remains entangled until it is closed or is cloned.
- bool isEntangled() { return !m_closed && !isNeutered(); }
+ bool isEntangled() const { return !m_closed && !isNeutered(); }
// A port gets neutered when it is transferred to a new owner via postMessage().
- bool isNeutered() { return !m_entangledChannel; }
+ bool isNeutered() const { return !m_entangledChannel; }
private:
- explicit MessagePort(ScriptExecutionContext&);
+ explicit MessagePort(ExecutionContext&);
- virtual void refEventTarget() OVERRIDE { ref(); }
- virtual void derefEventTarget() OVERRIDE { deref(); }
- virtual EventTargetData* eventTargetData() OVERRIDE;
- virtual EventTargetData* ensureEventTargetData() OVERRIDE;
+ // WebMessagePortChannelClient implementation.
+ virtual void messageAvailable() OVERRIDE;
+ void dispatchMessages();
- OwnPtr<MessagePortChannel> m_entangledChannel;
+ OwnPtr<blink::WebMessagePortChannel> m_entangledChannel;
bool m_started;
bool m_closed;
- ScriptExecutionContext* m_scriptExecutionContext;
- EventTargetData m_eventTargetData;
+ WeakPtrFactory<MessagePort> m_weakFactory;
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/MessagePortChannel.cpp b/chromium/third_party/WebKit/Source/core/dom/MessagePortChannel.cpp
deleted file mode 100644
index be0712023d1..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/MessagePortChannel.cpp
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright (C) 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-#include "config.h"
-#include "core/dom/MessagePortChannel.h"
-
-namespace WebCore {
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/MessagePortChannel.h b/chromium/third_party/WebKit/Source/core/dom/MessagePortChannel.h
deleted file mode 100644
index 5c78a3138b3..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/MessagePortChannel.h
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- * Copyright (C) 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef MessagePortChannel_h
-#define MessagePortChannel_h
-
-#include "bindings/v8/SerializedScriptValue.h"
-#include "wtf/Forward.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/RefPtr.h"
-
-namespace WebCore {
-
- class MessagePort;
- class MessagePortChannel;
- class PlatformMessagePortChannel;
- class ScriptExecutionContext;
- class SerializedScriptValue;
-
- // The overwhelmingly common case is sending a single port, so handle that efficiently with an inline buffer of size 1.
- typedef Vector<OwnPtr<MessagePortChannel>, 1> MessagePortChannelArray;
-
- // MessagePortChannel is a platform-independent interface to the remote side of a message channel.
- // It acts as a wrapper around the platform-dependent PlatformMessagePortChannel implementation which ensures that the platform-dependent close() method is invoked before destruction.
- class MessagePortChannel {
- WTF_MAKE_NONCOPYABLE(MessagePortChannel); WTF_MAKE_FAST_ALLOCATED;
- public:
- static void createChannel(PassRefPtr<MessagePort>, PassRefPtr<MessagePort>);
-
- // Entangles the channel with a port (called when a port has been cloned, after the clone has been marshaled to its new owning thread and is ready to receive messages).
- // Returns false if the entanglement failed because the port was closed.
- bool entangleIfOpen(MessagePort*);
-
- // Disentangles the channel from a given port so it no longer forwards messages to the port. Called when the port is being cloned and no new owning thread has yet been established.
- void disentangle();
-
- // Closes the port (ensures that no further messages can be added to either queue).
- void close();
-
- // Used by MessagePort.postMessage() to prevent callers from passing a port's own entangled port.
- bool isConnectedTo(MessagePort*);
-
- // Returns true if the proxy currently contains messages for this port.
- bool hasPendingActivity();
-
- // Sends a message and optional cloned port to the remote port.
- void postMessageToRemote(PassRefPtr<SerializedScriptValue>, PassOwnPtr<MessagePortChannelArray>);
-
- // Extracts a message from the message queue for this port.
- bool tryGetMessageFromRemote(RefPtr<SerializedScriptValue>&, OwnPtr<MessagePortChannelArray>&);
-
- // Returns the entangled port if run by the same thread (see MessagePort::locallyEntangledPort() for more details).
- MessagePort* locallyEntangledPort(const ScriptExecutionContext*);
-
- ~MessagePortChannel();
-
- // Creates a new wrapper for the passed channel.
- static PassOwnPtr<MessagePortChannel> create(PassRefPtr<PlatformMessagePortChannel>);
-
- // FIXME: PlatformMessagePortChannel is an implementation detail, and should not be exposed via a public function.
- PlatformMessagePortChannel* channel() const { return m_channel.get(); }
-
- private:
- explicit MessagePortChannel(PassRefPtr<PlatformMessagePortChannel>);
- RefPtr<PlatformMessagePortChannel> m_channel;
- };
-
-} // namespace WebCore
-
-#endif // MessagePortChannel_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/Microtask.cpp b/chromium/third_party/WebKit/Source/core/dom/Microtask.cpp
index cb0b12b618b..27cd2178f46 100644
--- a/chromium/third_party/WebKit/Source/core/dom/Microtask.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/Microtask.cpp
@@ -31,8 +31,8 @@
#include "config.h"
#include "core/dom/Microtask.h"
-#include "core/dom/CustomElementCallbackDispatcher.h"
#include "core/dom/MutationObserver.h"
+#include "core/dom/custom/CustomElementCallbackDispatcher.h"
#include "wtf/Vector.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/dom/MouseEvent.cpp b/chromium/third_party/WebKit/Source/core/dom/MouseEvent.cpp
deleted file mode 100644
index 6ae78a2b59b..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/MouseEvent.cpp
+++ /dev/null
@@ -1,290 +0,0 @@
-/*
- * Copyright (C) 2001 Peter Kelly (pmk@post.com)
- * Copyright (C) 2001 Tobias Anton (anton@stud.fbi.fh-darmstadt.de)
- * Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
- * Copyright (C) 2003, 2005, 2006, 2008 Apple Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-#include "core/dom/MouseEvent.h"
-
-#include "core/dom/Clipboard.h"
-#include "core/dom/EventDispatcher.h"
-#include "core/dom/EventNames.h"
-#include "core/dom/EventRetargeter.h"
-#include "core/platform/PlatformMouseEvent.h"
-
-namespace WebCore {
-
-MouseEventInit::MouseEventInit()
- : screenX(0)
- , screenY(0)
- , clientX(0)
- , clientY(0)
- , ctrlKey(false)
- , altKey(false)
- , shiftKey(false)
- , metaKey(false)
- , button(0)
- , relatedTarget(0)
-{
-}
-
-PassRefPtr<MouseEvent> MouseEvent::create(const AtomicString& type, const MouseEventInit& initializer)
-{
- return adoptRef(new MouseEvent(type, initializer));
-}
-
-PassRefPtr<MouseEvent> MouseEvent::create(const AtomicString& eventType, PassRefPtr<AbstractView> view, const PlatformMouseEvent& event, int detail, PassRefPtr<Node> relatedTarget)
-{
- ASSERT(event.type() == PlatformEvent::MouseMoved || event.button() != NoButton);
-
- bool isMouseEnterOrLeave = eventType == eventNames().mouseenterEvent || eventType == eventNames().mouseleaveEvent;
- bool isCancelable = !isMouseEnterOrLeave;
- bool isBubbling = !isMouseEnterOrLeave;
-
- return MouseEvent::create(eventType, isBubbling, isCancelable, view,
- detail, event.globalPosition().x(), event.globalPosition().y(), event.position().x(), event.position().y(),
- event.movementDelta().x(), event.movementDelta().y(),
- event.ctrlKey(), event.altKey(), event.shiftKey(), event.metaKey(), event.button(),
- relatedTarget, 0, false);
-}
-
-PassRefPtr<MouseEvent> MouseEvent::create(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<AbstractView> view,
- int detail, int screenX, int screenY, int pageX, int pageY,
- int movementX, int movementY,
- bool ctrlKey, bool altKey, bool shiftKey, bool metaKey, unsigned short button,
- PassRefPtr<EventTarget> relatedTarget)
-
-{
- return MouseEvent::create(type, canBubble, cancelable, view,
- detail, screenX, screenY, pageX, pageY,
- movementX, movementY,
- ctrlKey, altKey, shiftKey, metaKey, button, relatedTarget, 0, false);
-}
-
-PassRefPtr<MouseEvent> MouseEvent::create(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<AbstractView> view,
- int detail, int screenX, int screenY, int pageX, int pageY,
- int movementX, int movementY,
- bool ctrlKey, bool altKey, bool shiftKey, bool metaKey, unsigned short button,
- PassRefPtr<EventTarget> relatedTarget, PassRefPtr<Clipboard> clipboard, bool isSimulated)
-{
- return adoptRef(new MouseEvent(type, canBubble, cancelable, view,
- detail, screenX, screenY, pageX, pageY,
- movementX, movementY,
- ctrlKey, altKey, shiftKey, metaKey, button, relatedTarget, clipboard, isSimulated));
-}
-
-MouseEvent::MouseEvent()
- : m_button(0)
- , m_buttonDown(false)
-{
- ScriptWrappable::init(this);
-}
-
-MouseEvent::MouseEvent(const AtomicString& eventType, bool canBubble, bool cancelable, PassRefPtr<AbstractView> view,
- int detail, int screenX, int screenY, int pageX, int pageY,
- int movementX, int movementY,
- bool ctrlKey, bool altKey, bool shiftKey, bool metaKey,
- unsigned short button, PassRefPtr<EventTarget> relatedTarget,
- PassRefPtr<Clipboard> clipboard, bool isSimulated)
- : MouseRelatedEvent(eventType, canBubble, cancelable, view, detail, IntPoint(screenX, screenY),
- IntPoint(pageX, pageY),
- IntPoint(movementX, movementY),
- ctrlKey, altKey, shiftKey, metaKey, isSimulated)
- , m_button(button == (unsigned short)-1 ? 0 : button)
- , m_buttonDown(button != (unsigned short)-1)
- , m_relatedTarget(relatedTarget)
- , m_clipboard(clipboard)
-{
- ScriptWrappable::init(this);
-}
-
-MouseEvent::MouseEvent(const AtomicString& eventType, const MouseEventInit& initializer)
- : MouseRelatedEvent(eventType, initializer.bubbles, initializer.cancelable, initializer.view, initializer.detail, IntPoint(initializer.screenX, initializer.screenY),
- IntPoint(0 /* pageX */, 0 /* pageY */),
- IntPoint(0 /* movementX */, 0 /* movementY */),
- initializer.ctrlKey, initializer.altKey, initializer.shiftKey, initializer.metaKey, false /* isSimulated */)
- , m_button(initializer.button == (unsigned short)-1 ? 0 : initializer.button)
- , m_buttonDown(initializer.button != (unsigned short)-1)
- , m_relatedTarget(initializer.relatedTarget)
- , m_clipboard(0 /* clipboard */)
-{
- ScriptWrappable::init(this);
- initCoordinates(IntPoint(initializer.clientX, initializer.clientY));
-}
-
-MouseEvent::~MouseEvent()
-{
-}
-
-void MouseEvent::initMouseEvent(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<AbstractView> view,
- int detail, int screenX, int screenY, int clientX, int clientY,
- bool ctrlKey, bool altKey, bool shiftKey, bool metaKey,
- unsigned short button, PassRefPtr<EventTarget> relatedTarget)
-{
- if (dispatched())
- return;
-
- initUIEvent(type, canBubble, cancelable, view, detail);
-
- m_screenLocation = IntPoint(screenX, screenY);
- m_ctrlKey = ctrlKey;
- m_altKey = altKey;
- m_shiftKey = shiftKey;
- m_metaKey = metaKey;
- m_button = button == (unsigned short)-1 ? 0 : button;
- m_buttonDown = button != (unsigned short)-1;
- m_relatedTarget = relatedTarget;
-
- initCoordinates(IntPoint(clientX, clientY));
-
- // FIXME: m_isSimulated is not set to false here.
- // FIXME: m_clipboard is not set to 0 here.
-}
-
-const AtomicString& MouseEvent::interfaceName() const
-{
- return eventNames().interfaceForMouseEvent;
-}
-
-bool MouseEvent::isMouseEvent() const
-{
- return true;
-}
-
-bool MouseEvent::isDragEvent() const
-{
- const AtomicString& t = type();
- return t == eventNames().dragenterEvent || t == eventNames().dragoverEvent || t == eventNames().dragleaveEvent || t == eventNames().dropEvent
- || t == eventNames().dragstartEvent|| t == eventNames().dragEvent || t == eventNames().dragendEvent;
-}
-
-int MouseEvent::which() const
-{
- // For the DOM, the return values for left, middle and right mouse buttons are 0, 1, 2, respectively.
- // For the Netscape "which" property, the return values for left, middle and right mouse buttons are 1, 2, 3, respectively.
- // So we must add 1.
- if (!m_buttonDown)
- return 0;
- return m_button + 1;
-}
-
-Node* MouseEvent::toElement() const
-{
- // MSIE extension - "the object toward which the user is moving the mouse pointer"
- if (type() == eventNames().mouseoutEvent || type() == eventNames().mouseleaveEvent)
- return relatedTarget() ? relatedTarget()->toNode() : 0;
-
- return target() ? target()->toNode() : 0;
-}
-
-Node* MouseEvent::fromElement() const
-{
- // MSIE extension - "object from which activation or the mouse pointer is exiting during the event" (huh?)
- if (type() != eventNames().mouseoutEvent && type() != eventNames().mouseleaveEvent)
- return relatedTarget() ? relatedTarget()->toNode() : 0;
-
- return target() ? target()->toNode() : 0;
-}
-
-PassRefPtr<SimulatedMouseEvent> SimulatedMouseEvent::create(const AtomicString& eventType, PassRefPtr<AbstractView> view, PassRefPtr<Event> underlyingEvent)
-{
- return adoptRef(new SimulatedMouseEvent(eventType, view, underlyingEvent));
-}
-
-SimulatedMouseEvent::~SimulatedMouseEvent()
-{
-}
-
-SimulatedMouseEvent::SimulatedMouseEvent(const AtomicString& eventType, PassRefPtr<AbstractView> view, PassRefPtr<Event> underlyingEvent)
- : MouseEvent(eventType, true, true, view, 0, 0, 0, 0, 0,
- 0, 0,
- false, false, false, false, 0, 0, 0, true)
-{
- if (UIEventWithKeyState* keyStateEvent = findEventWithKeyState(underlyingEvent.get())) {
- m_ctrlKey = keyStateEvent->ctrlKey();
- m_altKey = keyStateEvent->altKey();
- m_shiftKey = keyStateEvent->shiftKey();
- m_metaKey = keyStateEvent->metaKey();
- }
- setUnderlyingEvent(underlyingEvent);
-
- if (this->underlyingEvent() && this->underlyingEvent()->isMouseEvent()) {
- MouseEvent* mouseEvent = toMouseEvent(this->underlyingEvent());
- m_screenLocation = mouseEvent->screenLocation();
- initCoordinates(mouseEvent->clientLocation());
- }
-}
-
-PassRefPtr<MouseEventDispatchMediator> MouseEventDispatchMediator::create(PassRefPtr<MouseEvent> mouseEvent, MouseEventType mouseEventType)
-{
- return adoptRef(new MouseEventDispatchMediator(mouseEvent, mouseEventType));
-}
-
-MouseEventDispatchMediator::MouseEventDispatchMediator(PassRefPtr<MouseEvent> mouseEvent, MouseEventType mouseEventType)
- : EventDispatchMediator(mouseEvent), m_mouseEventType(mouseEventType)
-{
-}
-
-MouseEvent* MouseEventDispatchMediator::event() const
-{
- return toMouseEvent(EventDispatchMediator::event());
-}
-
-bool MouseEventDispatchMediator::dispatchEvent(EventDispatcher* dispatcher) const
-{
- if (isSyntheticMouseEvent()) {
- EventRetargeter::adjustForMouseEvent(dispatcher->node(), *event());
- return dispatcher->dispatch();
- }
-
- if (isDisabledFormControl(dispatcher->node()))
- return false;
-
- if (event()->type().isEmpty())
- return true; // Shouldn't happen.
-
- ASSERT(!event()->target() || event()->target() != event()->relatedTarget());
-
- EventTarget* relatedTarget = event()->relatedTarget();
- EventRetargeter::adjustForMouseEvent(dispatcher->node(), *event());
-
- dispatcher->dispatch();
- bool swallowEvent = event()->defaultHandled() || event()->defaultPrevented();
-
- if (event()->type() != eventNames().clickEvent || event()->detail() != 2)
- return !swallowEvent;
-
- // Special case: If it's a double click event, we also send the dblclick event. This is not part
- // of the DOM specs, but is used for compatibility with the ondblclick="" attribute. This is treated
- // as a separate event in other DOM-compliant browsers like Firefox, and so we do the same.
- RefPtr<MouseEvent> doubleClickEvent = MouseEvent::create();
- doubleClickEvent->initMouseEvent(eventNames().dblclickEvent, event()->bubbles(), event()->cancelable(), event()->view(),
- event()->detail(), event()->screenX(), event()->screenY(), event()->clientX(), event()->clientY(),
- event()->ctrlKey(), event()->altKey(), event()->shiftKey(), event()->metaKey(),
- event()->button(), relatedTarget);
- if (event()->defaultHandled())
- doubleClickEvent->setDefaultHandled();
- EventDispatcher::dispatchEvent(dispatcher->node(), MouseEventDispatchMediator::create(doubleClickEvent));
- if (doubleClickEvent->defaultHandled() || doubleClickEvent->defaultPrevented())
- return false;
- return !swallowEvent;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/MouseEvent.h b/chromium/third_party/WebKit/Source/core/dom/MouseEvent.h
deleted file mode 100644
index 5ef39b06c17..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/MouseEvent.h
+++ /dev/null
@@ -1,150 +0,0 @@
-/*
- * Copyright (C) 2001 Peter Kelly (pmk@post.com)
- * Copyright (C) 2001 Tobias Anton (anton@stud.fbi.fh-darmstadt.de)
- * Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
- * Copyright (C) 2003, 2004, 2005, 2006, 2008 Apple Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#ifndef MouseEvent_h
-#define MouseEvent_h
-
-#include "core/dom/EventDispatchMediator.h"
-#include "core/dom/MouseRelatedEvent.h"
-
-namespace WebCore {
-
-class Clipboard;
-class EventDispatcher;
-class PlatformMouseEvent;
-
-struct MouseEventInit : public UIEventInit {
- MouseEventInit();
-
- int screenX;
- int screenY;
- int clientX;
- int clientY;
- bool ctrlKey;
- bool altKey;
- bool shiftKey;
- bool metaKey;
- unsigned short button;
- RefPtr<EventTarget> relatedTarget;
-};
-
-class MouseEvent : public MouseRelatedEvent {
-public:
- static PassRefPtr<MouseEvent> create()
- {
- return adoptRef(new MouseEvent);
- }
-
- static PassRefPtr<MouseEvent> create(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<AbstractView>,
- int detail, int screenX, int screenY, int pageX, int pageY,
- int movementX, int movementY,
- bool ctrlKey, bool altKey, bool shiftKey, bool metaKey, unsigned short button,
- PassRefPtr<EventTarget> relatedTarget);
-
- static PassRefPtr<MouseEvent> create(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<AbstractView>,
- int detail, int screenX, int screenY, int pageX, int pageY,
- int movementX, int movementY,
- bool ctrlKey, bool altKey, bool shiftKey, bool metaKey, unsigned short button,
- PassRefPtr<EventTarget> relatedTarget, PassRefPtr<Clipboard>, bool isSimulated = false);
-
- static PassRefPtr<MouseEvent> create(const AtomicString& eventType, PassRefPtr<AbstractView>, const PlatformMouseEvent&, int detail, PassRefPtr<Node> relatedTarget);
-
- static PassRefPtr<MouseEvent> create(const AtomicString& eventType, const MouseEventInit&);
-
- virtual ~MouseEvent();
-
- void initMouseEvent(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<AbstractView>,
- int detail, int screenX, int screenY, int clientX, int clientY,
- bool ctrlKey, bool altKey, bool shiftKey, bool metaKey,
- unsigned short button, PassRefPtr<EventTarget> relatedTarget);
-
- // WinIE uses 1,4,2 for left/middle/right but not for click (just for mousedown/up, maybe others),
- // but we will match the standard DOM.
- unsigned short button() const { return m_button; }
- bool buttonDown() const { return m_buttonDown; }
- EventTarget* relatedTarget() const { return m_relatedTarget.get(); }
- void setRelatedTarget(PassRefPtr<EventTarget> relatedTarget) { m_relatedTarget = relatedTarget; }
-
- Clipboard* clipboard() const { return m_clipboard.get(); }
-
- Node* toElement() const;
- Node* fromElement() const;
-
- Clipboard* dataTransfer() const { return isDragEvent() ? m_clipboard.get() : 0; }
-
- virtual const AtomicString& interfaceName() const;
-
- virtual bool isMouseEvent() const;
- virtual bool isDragEvent() const;
- virtual int which() const;
-
-protected:
- MouseEvent(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<AbstractView>,
- int detail, int screenX, int screenY, int pageX, int pageY,
- int movementX, int movementY,
- bool ctrlKey, bool altKey, bool shiftKey, bool metaKey, unsigned short button,
- PassRefPtr<EventTarget> relatedTarget, PassRefPtr<Clipboard>, bool isSimulated);
-
- MouseEvent(const AtomicString& type, const MouseEventInit&);
-
- MouseEvent();
-
-private:
- unsigned short m_button;
- bool m_buttonDown;
- RefPtr<EventTarget> m_relatedTarget;
- RefPtr<Clipboard> m_clipboard;
-};
-
-class SimulatedMouseEvent : public MouseEvent {
-public:
- static PassRefPtr<SimulatedMouseEvent> create(const AtomicString& eventType, PassRefPtr<AbstractView>, PassRefPtr<Event> underlyingEvent);
- virtual ~SimulatedMouseEvent();
-
-private:
- SimulatedMouseEvent(const AtomicString& eventType, PassRefPtr<AbstractView>, PassRefPtr<Event> underlyingEvent);
-};
-
-class MouseEventDispatchMediator : public EventDispatchMediator {
-public:
- enum MouseEventType { SyntheticMouseEvent, NonSyntheticMouseEvent};
- static PassRefPtr<MouseEventDispatchMediator> create(PassRefPtr<MouseEvent>, MouseEventType = NonSyntheticMouseEvent);
-
-private:
- explicit MouseEventDispatchMediator(PassRefPtr<MouseEvent>, MouseEventType);
- MouseEvent* event() const;
-
- virtual bool dispatchEvent(EventDispatcher*) const OVERRIDE;
- bool isSyntheticMouseEvent() const { return m_mouseEventType == SyntheticMouseEvent; }
- MouseEventType m_mouseEventType;
-};
-
-inline MouseEvent* toMouseEvent(Event* event)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!event || event->isMouseEvent());
- return static_cast<MouseEvent*>(event);
-}
-
-} // namespace WebCore
-
-#endif // MouseEvent_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/MouseEvent.idl b/chromium/third_party/WebKit/Source/core/dom/MouseEvent.idl
deleted file mode 100644
index 92c3bfb518a..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/MouseEvent.idl
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * Copyright (C) 2006, 2007 Apple Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-[
- ConstructorTemplate=Event
-] interface MouseEvent : UIEvent {
- [InitializedByEventConstructor] readonly attribute long screenX;
- [InitializedByEventConstructor] readonly attribute long screenY;
- [InitializedByEventConstructor] readonly attribute long clientX;
- [InitializedByEventConstructor] readonly attribute long clientY;
- [InitializedByEventConstructor] readonly attribute boolean ctrlKey;
- [InitializedByEventConstructor] readonly attribute boolean shiftKey;
- [InitializedByEventConstructor] readonly attribute boolean altKey;
- [InitializedByEventConstructor] readonly attribute boolean metaKey;
- [InitializedByEventConstructor] readonly attribute unsigned short button;
- [InitializedByEventConstructor] readonly attribute EventTarget relatedTarget;
- readonly attribute long webkitMovementX;
- readonly attribute long webkitMovementY;
-
- void initMouseEvent([Default=Undefined] optional DOMString type,
- [Default=Undefined] optional boolean canBubble,
- [Default=Undefined] optional boolean cancelable,
- [Default=Undefined] optional Window view,
- [Default=Undefined] optional long detail,
- [Default=Undefined] optional long screenX,
- [Default=Undefined] optional long screenY,
- [Default=Undefined] optional long clientX,
- [Default=Undefined] optional long clientY,
- [Default=Undefined] optional boolean ctrlKey,
- [Default=Undefined] optional boolean altKey,
- [Default=Undefined] optional boolean shiftKey,
- [Default=Undefined] optional boolean metaKey,
- [Default=Undefined] optional unsigned short button,
- [Default=Undefined] optional EventTarget relatedTarget);
-
- // extensions
- readonly attribute long offsetX;
- readonly attribute long offsetY;
- readonly attribute long x;
- readonly attribute long y;
- readonly attribute Node fromElement;
- readonly attribute Node toElement;
-
- readonly attribute Clipboard dataTransfer;
-};
-
diff --git a/chromium/third_party/WebKit/Source/core/dom/MouseRelatedEvent.cpp b/chromium/third_party/WebKit/Source/core/dom/MouseRelatedEvent.cpp
deleted file mode 100644
index 147ba2dc73f..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/MouseRelatedEvent.cpp
+++ /dev/null
@@ -1,230 +0,0 @@
-/*
- * Copyright (C) 2001 Peter Kelly (pmk@post.com)
- * Copyright (C) 2001 Tobias Anton (anton@stud.fbi.fh-darmstadt.de)
- * Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
- * Copyright (C) 2003, 2005, 2006, 2008 Apple Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-#include "core/dom/MouseRelatedEvent.h"
-
-#include "core/dom/Document.h"
-#include "core/page/DOMWindow.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameView.h"
-#include "core/rendering/RenderLayer.h"
-#include "core/rendering/RenderObject.h"
-
-namespace WebCore {
-
-MouseRelatedEvent::MouseRelatedEvent()
- : m_isSimulated(false)
- , m_hasCachedRelativePosition(false)
-{
-}
-
-static LayoutSize contentsScrollOffset(AbstractView* abstractView)
-{
- if (!abstractView)
- return LayoutSize();
- Frame* frame = abstractView->frame();
- if (!frame)
- return LayoutSize();
- FrameView* frameView = frame->view();
- if (!frameView)
- return LayoutSize();
- float scaleFactor = frame->pageZoomFactor();
- return LayoutSize(frameView->scrollX() / scaleFactor, frameView->scrollY() / scaleFactor);
-}
-
-MouseRelatedEvent::MouseRelatedEvent(const AtomicString& eventType, bool canBubble, bool cancelable, PassRefPtr<AbstractView> abstractView,
- int detail, const IntPoint& screenLocation, const IntPoint& windowLocation,
- const IntPoint& movementDelta,
- bool ctrlKey, bool altKey, bool shiftKey, bool metaKey, bool isSimulated)
- : UIEventWithKeyState(eventType, canBubble, cancelable, abstractView, detail, ctrlKey, altKey, shiftKey, metaKey)
- , m_screenLocation(screenLocation)
- , m_movementDelta(movementDelta)
- , m_isSimulated(isSimulated)
-{
- LayoutPoint adjustedPageLocation;
- LayoutPoint scrollPosition;
-
- Frame* frame = view() ? view()->frame() : 0;
- if (frame && !isSimulated) {
- if (FrameView* frameView = frame->view()) {
- scrollPosition = frameView->scrollPosition();
- adjustedPageLocation = frameView->windowToContents(windowLocation);
- float scaleFactor = 1 / frame->pageZoomFactor();
- if (scaleFactor != 1.0f) {
- adjustedPageLocation.scale(scaleFactor, scaleFactor);
- scrollPosition.scale(scaleFactor, scaleFactor);
- }
- }
- }
-
- m_clientLocation = adjustedPageLocation - toLayoutSize(scrollPosition);
- m_pageLocation = adjustedPageLocation;
-
- initCoordinates();
-}
-
-void MouseRelatedEvent::initCoordinates()
-{
- // Set up initial values for coordinates.
- // Correct values are computed lazily, see computeRelativePosition.
- m_layerLocation = m_pageLocation;
- m_offsetLocation = m_pageLocation;
-
- computePageLocation();
- m_hasCachedRelativePosition = false;
-}
-
-void MouseRelatedEvent::initCoordinates(const LayoutPoint& clientLocation)
-{
- // Set up initial values for coordinates.
- // Correct values are computed lazily, see computeRelativePosition.
- m_clientLocation = clientLocation;
- m_pageLocation = clientLocation + contentsScrollOffset(view());
-
- m_layerLocation = m_pageLocation;
- m_offsetLocation = m_pageLocation;
-
- computePageLocation();
- m_hasCachedRelativePosition = false;
-}
-
-static float pageZoomFactor(const UIEvent* event)
-{
- DOMWindow* window = event->view();
- if (!window)
- return 1;
- Frame* frame = window->frame();
- if (!frame)
- return 1;
- return frame->pageZoomFactor();
-}
-
-void MouseRelatedEvent::computePageLocation()
-{
- float scaleFactor = pageZoomFactor(this);
- setAbsoluteLocation(roundedLayoutPoint(FloatPoint(pageX() * scaleFactor, pageY() * scaleFactor)));
-}
-
-void MouseRelatedEvent::receivedTarget()
-{
- m_hasCachedRelativePosition = false;
-}
-
-void MouseRelatedEvent::computeRelativePosition()
-{
- Node* targetNode = target() ? target()->toNode() : 0;
- if (!targetNode)
- return;
-
- // Compute coordinates that are based on the target.
- m_layerLocation = m_pageLocation;
- m_offsetLocation = m_pageLocation;
-
- // Must have an updated render tree for this math to work correctly.
- targetNode->document().updateLayoutIgnorePendingStylesheets();
-
- // Adjust offsetLocation to be relative to the target's position.
- if (RenderObject* r = targetNode->renderer()) {
- FloatPoint localPos = r->absoluteToLocal(absoluteLocation(), UseTransforms);
- m_offsetLocation = roundedLayoutPoint(localPos);
- float scaleFactor = 1 / pageZoomFactor(this);
- if (scaleFactor != 1.0f)
- m_offsetLocation.scale(scaleFactor, scaleFactor);
- }
-
- // Adjust layerLocation to be relative to the layer.
- // FIXME: event.layerX and event.layerY are poorly defined,
- // and probably don't always correspond to RenderLayer offsets.
- // https://bugs.webkit.org/show_bug.cgi?id=21868
- Node* n = targetNode;
- while (n && !n->renderer())
- n = n->parentNode();
-
- RenderLayer* layer;
- if (n && (layer = n->renderer()->enclosingLayer())) {
- for (; layer; layer = layer->parent()) {
- m_layerLocation -= toLayoutSize(layer->location());
- }
- }
-
- m_hasCachedRelativePosition = true;
-}
-
-int MouseRelatedEvent::layerX()
-{
- if (!m_hasCachedRelativePosition)
- computeRelativePosition();
- return m_layerLocation.x();
-}
-
-int MouseRelatedEvent::layerY()
-{
- if (!m_hasCachedRelativePosition)
- computeRelativePosition();
- return m_layerLocation.y();
-}
-
-int MouseRelatedEvent::offsetX()
-{
- if (!m_hasCachedRelativePosition)
- computeRelativePosition();
- return roundToInt(m_offsetLocation.x());
-}
-
-int MouseRelatedEvent::offsetY()
-{
- if (!m_hasCachedRelativePosition)
- computeRelativePosition();
- return roundToInt(m_offsetLocation.y());
-}
-
-int MouseRelatedEvent::pageX() const
-{
- return m_pageLocation.x();
-}
-
-int MouseRelatedEvent::pageY() const
-{
- return m_pageLocation.y();
-}
-
-const LayoutPoint& MouseRelatedEvent::pageLocation() const
-{
- return m_pageLocation;
-}
-
-int MouseRelatedEvent::x() const
-{
- // FIXME: This is not correct.
- // See Microsoft documentation and <http://www.quirksmode.org/dom/w3c_events.html>.
- return m_clientLocation.x();
-}
-
-int MouseRelatedEvent::y() const
-{
- // FIXME: This is not correct.
- // See Microsoft documentation and <http://www.quirksmode.org/dom/w3c_events.html>.
- return m_clientLocation.y();
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/MouseRelatedEvent.h b/chromium/third_party/WebKit/Source/core/dom/MouseRelatedEvent.h
deleted file mode 100644
index a33ddf8d38b..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/MouseRelatedEvent.h
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
- * Copyright (C) 2001 Peter Kelly (pmk@post.com)
- * Copyright (C) 2001 Tobias Anton (anton@stud.fbi.fh-darmstadt.de)
- * Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
- * Copyright (C) 2003, 2004, 2005, 2006 Apple Computer, Inc.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#ifndef MouseRelatedEvent_h
-#define MouseRelatedEvent_h
-
-#include "core/dom/UIEventWithKeyState.h"
-#include "core/platform/graphics/LayoutPoint.h"
-
-namespace WebCore {
-
- // Internal only: Helper class for what's common between mouse and wheel events.
- class MouseRelatedEvent : public UIEventWithKeyState {
- public:
- // Note that these values are adjusted to counter the effects of zoom, so that values
- // exposed via DOM APIs are invariant under zooming.
- int screenX() const { return m_screenLocation.x(); }
- int screenY() const { return m_screenLocation.y(); }
- const IntPoint& screenLocation() const { return m_screenLocation; }
- int clientX() const { return m_clientLocation.x(); }
- int clientY() const { return m_clientLocation.y(); }
- int webkitMovementX() const { return m_movementDelta.x(); }
- int webkitMovementY() const { return m_movementDelta.y(); }
- const LayoutPoint& clientLocation() const { return m_clientLocation; }
- int layerX();
- int layerY();
- int offsetX();
- int offsetY();
- bool isSimulated() const { return m_isSimulated; }
- virtual int pageX() const;
- virtual int pageY() const;
- virtual const LayoutPoint& pageLocation() const;
- int x() const;
- int y() const;
-
- // Page point in "absolute" coordinates (i.e. post-zoomed, page-relative coords,
- // usable with RenderObject::absoluteToLocal).
- const LayoutPoint& absoluteLocation() const { return m_absoluteLocation; }
- void setAbsoluteLocation(const LayoutPoint& p) { m_absoluteLocation = p; }
-
- protected:
- MouseRelatedEvent();
- MouseRelatedEvent(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<AbstractView>,
- int detail, const IntPoint& screenLocation, const IntPoint& windowLocation,
- const IntPoint& movementDelta,
- bool ctrlKey, bool altKey, bool shiftKey, bool metaKey, bool isSimulated = false);
-
- void initCoordinates();
- void initCoordinates(const LayoutPoint& clientLocation);
- virtual void receivedTarget();
-
- void computePageLocation();
- void computeRelativePosition();
-
- // Expose these so MouseEvent::initMouseEvent can set them.
- IntPoint m_screenLocation;
- LayoutPoint m_clientLocation;
- LayoutPoint m_movementDelta;
-
- private:
- LayoutPoint m_pageLocation;
- LayoutPoint m_layerLocation;
- LayoutPoint m_offsetLocation;
- LayoutPoint m_absoluteLocation;
- bool m_isSimulated;
- bool m_hasCachedRelativePosition;
- };
-
-} // namespace WebCore
-
-#endif // MouseRelatedEvent_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/MutationCallback.h b/chromium/third_party/WebKit/Source/core/dom/MutationCallback.h
index af904e2c62f..88f230bb35d 100644
--- a/chromium/third_party/WebKit/Source/core/dom/MutationCallback.h
+++ b/chromium/third_party/WebKit/Source/core/dom/MutationCallback.h
@@ -31,7 +31,6 @@
#ifndef MutationCallback_h
#define MutationCallback_h
-#include "wtf/RefCounted.h"
#include "wtf/RefPtr.h"
#include "wtf/Vector.h"
@@ -40,12 +39,12 @@ namespace WebCore {
class MutationRecord;
class MutationObserver;
-class MutationCallback : public RefCounted<MutationCallback> {
+class MutationCallback {
public:
virtual ~MutationCallback() { }
virtual void call(const Vector<RefPtr<MutationRecord> >&, MutationObserver*) = 0;
- virtual ScriptExecutionContext* scriptExecutionContext() const = 0;
+ virtual ExecutionContext* executionContext() const = 0;
};
}
diff --git a/chromium/third_party/WebKit/Source/core/dom/MutationEvent.cpp b/chromium/third_party/WebKit/Source/core/dom/MutationEvent.cpp
deleted file mode 100644
index fcb19b9e690..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/MutationEvent.cpp
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * Copyright (C) 2001 Peter Kelly (pmk@post.com)
- * Copyright (C) 2001 Tobias Anton (anton@stud.fbi.fh-darmstadt.de)
- * Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
- * Copyright (C) 2003, 2005, 2006, 2008 Apple Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-#include "core/dom/MutationEvent.h"
-
-#include "core/dom/EventNames.h"
-
-namespace WebCore {
-
-MutationEvent::MutationEvent()
- : m_attrChange(0)
-{
- ScriptWrappable::init(this);
-}
-
-MutationEvent::MutationEvent(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<Node> relatedNode,
- const String& prevValue, const String& newValue,
- const String& attrName, unsigned short attrChange)
- : Event(type, canBubble, cancelable)
- , m_relatedNode(relatedNode)
- , m_prevValue(prevValue)
- , m_newValue(newValue)
- , m_attrName(attrName)
- , m_attrChange(attrChange)
-{
- ScriptWrappable::init(this);
-}
-
-MutationEvent::~MutationEvent()
-{
-}
-
-void MutationEvent::initMutationEvent(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<Node> relatedNode,
- const String& prevValue, const String& newValue,
- const String& attrName, unsigned short attrChange)
-{
- if (dispatched())
- return;
-
- initEvent(type, canBubble, cancelable);
-
- m_relatedNode = relatedNode;
- m_prevValue = prevValue;
- m_newValue = newValue;
- m_attrName = attrName;
- m_attrChange = attrChange;
-}
-
-const AtomicString& MutationEvent::interfaceName() const
-{
- return eventNames().interfaceForMutationEvent;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/MutationEvent.h b/chromium/third_party/WebKit/Source/core/dom/MutationEvent.h
deleted file mode 100644
index 15e3da1dd1b..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/MutationEvent.h
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * Copyright (C) 2001 Peter Kelly (pmk@post.com)
- * Copyright (C) 2001 Tobias Anton (anton@stud.fbi.fh-darmstadt.de)
- * Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
- * Copyright (C) 2003, 2004, 2005, 2006, 2008 Apple Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#ifndef MutationEvent_h
-#define MutationEvent_h
-
-#include "core/dom/Event.h"
-#include "core/dom/Node.h"
-
-namespace WebCore {
-
- class MutationEvent : public Event {
- public:
- virtual ~MutationEvent();
-
- enum attrChangeType {
- MODIFICATION = 1,
- ADDITION = 2,
- REMOVAL = 3
- };
-
- static PassRefPtr<MutationEvent> create()
- {
- return adoptRef(new MutationEvent);
- }
-
- static PassRefPtr<MutationEvent> create(const AtomicString& type, bool canBubble, PassRefPtr<Node> relatedNode = 0,
- const String& prevValue = String(), const String& newValue = String(), const String& attrName = String(), unsigned short attrChange = 0)
- {
- return adoptRef(new MutationEvent(type, canBubble, false, relatedNode, prevValue, newValue, attrName, attrChange));
- }
-
- void initMutationEvent(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<Node> relatedNode,
- const String& prevValue, const String& newValue,
- const String& attrName, unsigned short attrChange);
-
- Node* relatedNode() const { return m_relatedNode.get(); }
- String prevValue() const { return m_prevValue; }
- String newValue() const { return m_newValue; }
- String attrName() const { return m_attrName; }
- unsigned short attrChange() const { return m_attrChange; }
-
- virtual const AtomicString& interfaceName() const;
-
- private:
- MutationEvent();
- MutationEvent(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<Node> relatedNode,
- const String& prevValue, const String& newValue,
- const String& attrName, unsigned short attrChange);
-
- RefPtr<Node> m_relatedNode;
- String m_prevValue;
- String m_newValue;
- String m_attrName;
- unsigned short m_attrChange;
- };
-
-} // namespace WebCore
-
-#endif // MutationEvent_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/MutationObserver.cpp b/chromium/third_party/WebKit/Source/core/dom/MutationObserver.cpp
index e2d5fec85cb..06e610a33f4 100644
--- a/chromium/third_party/WebKit/Source/core/dom/MutationObserver.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/MutationObserver.cpp
@@ -40,9 +40,7 @@
#include "core/dom/MutationObserverRegistration.h"
#include "core/dom/MutationRecord.h"
#include "core/dom/Node.h"
-#include "wtf/HashSet.h"
#include "wtf/MainThread.h"
-#include "wtf/Vector.h"
namespace WebCore {
@@ -55,13 +53,13 @@ struct MutationObserver::ObserverLessThan {
}
};
-PassRefPtr<MutationObserver> MutationObserver::create(PassRefPtr<MutationCallback> callback)
+PassRefPtr<MutationObserver> MutationObserver::create(PassOwnPtr<MutationCallback> callback)
{
ASSERT(isMainThread());
return adoptRef(new MutationObserver(callback));
}
-MutationObserver::MutationObserver(PassRefPtr<MutationCallback> callback)
+MutationObserver::MutationObserver(PassOwnPtr<MutationCallback> callback)
: m_callback(callback)
, m_priority(s_observerPriority++)
{
@@ -73,45 +71,65 @@ MutationObserver::~MutationObserver()
ASSERT(m_registrations.isEmpty());
}
-bool MutationObserver::validateOptions(MutationObserverOptions options)
-{
- return (options & (Attributes | CharacterData | ChildList))
- && ((options & Attributes) || !(options & AttributeOldValue))
- && ((options & Attributes) || !(options & AttributeFilter))
- && ((options & CharacterData) || !(options & CharacterDataOldValue));
-}
-
-void MutationObserver::observe(Node* node, const Dictionary& optionsDictionary, ExceptionState& es)
+void MutationObserver::observe(Node* node, const Dictionary& optionsDictionary, ExceptionState& exceptionState)
{
if (!node) {
- es.throwDOMException(NotFoundError);
+ exceptionState.throwDOMException(NotFoundError, "The provided node was null.");
return;
}
- static const struct {
- const char* name;
- MutationObserverOptions value;
- } booleanOptions[] = {
- { "childList", ChildList },
- { "attributes", Attributes },
- { "characterData", CharacterData },
- { "subtree", Subtree },
- { "attributeOldValue", AttributeOldValue },
- { "characterDataOldValue", CharacterDataOldValue }
- };
MutationObserverOptions options = 0;
- for (unsigned i = 0; i < sizeof(booleanOptions) / sizeof(booleanOptions[0]); ++i) {
- bool value = false;
- if (optionsDictionary.get(booleanOptions[i].name, value) && value)
- options |= booleanOptions[i].value;
- }
+
+ bool attributeOldValue = false;
+ bool attributeOldValuePresent = optionsDictionary.get("attributeOldValue", attributeOldValue);
+ if (attributeOldValue)
+ options |= AttributeOldValue;
HashSet<AtomicString> attributeFilter;
- if (optionsDictionary.get("attributeFilter", attributeFilter))
+ bool attributeFilterPresent = optionsDictionary.get("attributeFilter", attributeFilter);
+ if (attributeFilterPresent)
options |= AttributeFilter;
- if (!validateOptions(options)) {
- es.throwDOMException(SyntaxError);
+ bool attributes = false;
+ bool attributesPresent = optionsDictionary.get("attributes", attributes);
+ if (attributes || (!attributesPresent && (attributeOldValuePresent || attributeFilterPresent)))
+ options |= Attributes;
+
+ bool characterDataOldValue = false;
+ bool characterDataOldValuePresent = optionsDictionary.get("characterDataOldValue", characterDataOldValue);
+ if (characterDataOldValue)
+ options |= CharacterDataOldValue;
+
+ bool characterData = false;
+ bool characterDataPresent = optionsDictionary.get("characterData", characterData);
+ if (characterData || (!characterDataPresent && characterDataOldValuePresent))
+ options |= CharacterData;
+
+ bool childListValue = false;
+ if (optionsDictionary.get("childList", childListValue) && childListValue)
+ options |= ChildList;
+
+ bool subtreeValue = false;
+ if (optionsDictionary.get("subtree", subtreeValue) && subtreeValue)
+ options |= Subtree;
+
+ if (!(options & Attributes)) {
+ if (options & AttributeOldValue) {
+ exceptionState.throwDOMException(TypeError, "The options object may only set 'attributeOldValue' to true when 'attributes' is true or not present.");
+ return;
+ }
+ if (options & AttributeFilter) {
+ exceptionState.throwDOMException(TypeError, "The options object may only set 'attributeFilter' when 'attributes' is true or not present.");
+ return;
+ }
+ }
+ if (!((options & CharacterData) || !(options & CharacterDataOldValue))) {
+ exceptionState.throwDOMException(TypeError, "The options object may only set 'characterDataOldValue' to true when 'characterData' is true or not present.");
+ return;
+ }
+
+ if (!(options & (Attributes | CharacterData | ChildList))) {
+ exceptionState.throwDOMException(TypeError, "The options object must set at least one of 'attributes', 'characterData', or 'childList' to true.");
return;
}
@@ -182,7 +200,7 @@ HashSet<Node*> MutationObserver::getObservedNodes() const
bool MutationObserver::canDeliver()
{
- return !m_callback->scriptExecutionContext()->activeDOMObjectsAreSuspended();
+ return !m_callback->executionContext()->activeDOMObjectsAreSuspended();
}
void MutationObserver::deliver()
diff --git a/chromium/third_party/WebKit/Source/core/dom/MutationObserver.h b/chromium/third_party/WebKit/Source/core/dom/MutationObserver.h
index 3f2941d4295..062d01edfe1 100644
--- a/chromium/third_party/WebKit/Source/core/dom/MutationObserver.h
+++ b/chromium/third_party/WebKit/Source/core/dom/MutationObserver.h
@@ -70,7 +70,7 @@ public:
CharacterDataOldValue = 1 << 6,
};
- static PassRefPtr<MutationObserver> create(PassRefPtr<MutationCallback>);
+ static PassRefPtr<MutationObserver> create(PassOwnPtr<MutationCallback>);
static void deliverAllMutations();
~MutationObserver();
@@ -89,12 +89,10 @@ public:
private:
struct ObserverLessThan;
- explicit MutationObserver(PassRefPtr<MutationCallback>);
+ explicit MutationObserver(PassOwnPtr<MutationCallback>);
void deliver();
- static bool validateOptions(MutationObserverOptions);
-
- RefPtr<MutationCallback> m_callback;
+ OwnPtr<MutationCallback> m_callback;
Vector<RefPtr<MutationRecord> > m_records;
HashSet<MutationObserverRegistration*> m_registrations;
unsigned m_priority;
diff --git a/chromium/third_party/WebKit/Source/core/dom/MutationObserver.idl b/chromium/third_party/WebKit/Source/core/dom/MutationObserver.idl
index e87fa44b094..d16bb4fd3e2 100644
--- a/chromium/third_party/WebKit/Source/core/dom/MutationObserver.idl
+++ b/chromium/third_party/WebKit/Source/core/dom/MutationObserver.idl
@@ -29,7 +29,7 @@
*/
[
- CustomConstructor(MutationCallback callback)
+ CustomConstructor(MutationCallback callback),
] interface MutationObserver {
[RaisesException] void observe(Node target, Dictionary options);
sequence<MutationRecord> takeRecords();
diff --git a/chromium/third_party/WebKit/Source/core/dom/MutationObserverInterestGroup.cpp b/chromium/third_party/WebKit/Source/core/dom/MutationObserverInterestGroup.cpp
index 7169bb25bab..e9e839ba0be 100644
--- a/chromium/third_party/WebKit/Source/core/dom/MutationObserverInterestGroup.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/MutationObserverInterestGroup.cpp
@@ -33,16 +33,14 @@
#include "core/dom/MutationObserverInterestGroup.h"
#include "core/dom/MutationRecord.h"
-#include "core/dom/Node.h"
-#include "core/dom/QualifiedName.h"
namespace WebCore {
-PassOwnPtr<MutationObserverInterestGroup> MutationObserverInterestGroup::createIfNeeded(Node* target, MutationObserver::MutationType type, MutationRecordDeliveryOptions oldValueFlag, const QualifiedName* attributeName)
+PassOwnPtr<MutationObserverInterestGroup> MutationObserverInterestGroup::createIfNeeded(Node& target, MutationObserver::MutationType type, MutationRecordDeliveryOptions oldValueFlag, const QualifiedName* attributeName)
{
ASSERT((type == MutationObserver::Attributes && attributeName) || !attributeName);
HashMap<MutationObserver*, MutationRecordDeliveryOptions> observers;
- target->getRegisteredMutationObserversOfType(observers, type, attributeName);
+ target.getRegisteredMutationObserversOfType(observers, type, attributeName);
if (observers.isEmpty())
return nullptr;
diff --git a/chromium/third_party/WebKit/Source/core/dom/MutationObserverInterestGroup.h b/chromium/third_party/WebKit/Source/core/dom/MutationObserverInterestGroup.h
index 4950f311729..b149afcf935 100644
--- a/chromium/third_party/WebKit/Source/core/dom/MutationObserverInterestGroup.h
+++ b/chromium/third_party/WebKit/Source/core/dom/MutationObserverInterestGroup.h
@@ -42,26 +42,26 @@ namespace WebCore {
class MutationObserverInterestGroup {
public:
- static PassOwnPtr<MutationObserverInterestGroup> createForChildListMutation(Node* target)
+ static PassOwnPtr<MutationObserverInterestGroup> createForChildListMutation(Node& target)
{
- if (!target->document().hasMutationObserversOfType(MutationObserver::ChildList))
+ if (!target.document().hasMutationObserversOfType(MutationObserver::ChildList))
return nullptr;
MutationRecordDeliveryOptions oldValueFlag = 0;
return createIfNeeded(target, MutationObserver::ChildList, oldValueFlag);
}
- static PassOwnPtr<MutationObserverInterestGroup> createForCharacterDataMutation(Node* target)
+ static PassOwnPtr<MutationObserverInterestGroup> createForCharacterDataMutation(Node& target)
{
- if (!target->document().hasMutationObserversOfType(MutationObserver::CharacterData))
+ if (!target.document().hasMutationObserversOfType(MutationObserver::CharacterData))
return nullptr;
return createIfNeeded(target, MutationObserver::CharacterData, MutationObserver::CharacterDataOldValue);
}
- static PassOwnPtr<MutationObserverInterestGroup> createForAttributesMutation(Node* target, const QualifiedName& attributeName)
+ static PassOwnPtr<MutationObserverInterestGroup> createForAttributesMutation(Node& target, const QualifiedName& attributeName)
{
- if (!target->document().hasMutationObserversOfType(MutationObserver::Attributes))
+ if (!target.document().hasMutationObserversOfType(MutationObserver::Attributes))
return nullptr;
return createIfNeeded(target, MutationObserver::Attributes, MutationObserver::AttributeOldValue, &attributeName);
@@ -71,7 +71,7 @@ public:
void enqueueMutationRecord(PassRefPtr<MutationRecord>);
private:
- static PassOwnPtr<MutationObserverInterestGroup> createIfNeeded(Node* target, MutationObserver::MutationType, MutationRecordDeliveryOptions oldValueFlag, const QualifiedName* attributeName = 0);
+ static PassOwnPtr<MutationObserverInterestGroup> createIfNeeded(Node& target, MutationObserver::MutationType, MutationRecordDeliveryOptions oldValueFlag, const QualifiedName* attributeName = 0);
MutationObserverInterestGroup(HashMap<MutationObserver*, MutationRecordDeliveryOptions>& observers, MutationRecordDeliveryOptions oldValueFlag);
bool hasOldValue(MutationRecordDeliveryOptions options) { return options & m_oldValueFlag; }
diff --git a/chromium/third_party/WebKit/Source/core/dom/MutationRecord.cpp b/chromium/third_party/WebKit/Source/core/dom/MutationRecord.cpp
index 5d86f3e9c0d..77c6f393073 100644
--- a/chromium/third_party/WebKit/Source/core/dom/MutationRecord.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/MutationRecord.cpp
@@ -168,22 +168,22 @@ const AtomicString& CharacterDataRecord::type()
PassRefPtr<MutationRecord> MutationRecord::createChildList(PassRefPtr<Node> target, PassRefPtr<NodeList> added, PassRefPtr<NodeList> removed, PassRefPtr<Node> previousSibling, PassRefPtr<Node> nextSibling)
{
- return adoptRef(static_cast<MutationRecord*>(new ChildListRecord(target, added, removed, previousSibling, nextSibling)));
+ return adoptRef(new ChildListRecord(target, added, removed, previousSibling, nextSibling));
}
PassRefPtr<MutationRecord> MutationRecord::createAttributes(PassRefPtr<Node> target, const QualifiedName& name, const AtomicString& oldValue)
{
- return adoptRef(static_cast<MutationRecord*>(new AttributesRecord(target, name, oldValue)));
+ return adoptRef(new AttributesRecord(target, name, oldValue));
}
PassRefPtr<MutationRecord> MutationRecord::createCharacterData(PassRefPtr<Node> target, const String& oldValue)
{
- return adoptRef(static_cast<MutationRecord*>(new CharacterDataRecord(target, oldValue)));
+ return adoptRef(new CharacterDataRecord(target, oldValue));
}
PassRefPtr<MutationRecord> MutationRecord::createWithNullOldValue(PassRefPtr<MutationRecord> record)
{
- return adoptRef(static_cast<MutationRecord*>(new MutationRecordWithNullOldValue(record)));
+ return adoptRef(new MutationRecordWithNullOldValue(record));
}
MutationRecord::~MutationRecord()
diff --git a/chromium/third_party/WebKit/Source/core/dom/NameNodeList.h b/chromium/third_party/WebKit/Source/core/dom/NameNodeList.h
index 96bcac439d6..5a595d8d9a3 100644
--- a/chromium/third_party/WebKit/Source/core/dom/NameNodeList.h
+++ b/chromium/third_party/WebKit/Source/core/dom/NameNodeList.h
@@ -31,7 +31,7 @@
namespace WebCore {
// NodeList which lists all Nodes in a Element with a given "name" attribute
-class NameNodeList : public LiveNodeList {
+class NameNodeList FINAL : public LiveNodeList {
public:
static PassRefPtr<NameNodeList> create(PassRefPtr<Node> rootNode, CollectionType type, const AtomicString& name)
{
@@ -44,7 +44,7 @@ public:
private:
NameNodeList(PassRefPtr<Node> rootNode, const AtomicString& name);
- virtual bool nodeMatches(Element*) const;
+ virtual bool nodeMatches(Element*) const OVERRIDE;
AtomicString m_name;
};
diff --git a/chromium/third_party/WebKit/Source/core/dom/NamedFlow.cpp b/chromium/third_party/WebKit/Source/core/dom/NamedFlow.cpp
index 013b0eb1f42..04f1c08d1f7 100644
--- a/chromium/third_party/WebKit/Source/core/dom/NamedFlow.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/NamedFlow.cpp
@@ -31,12 +31,12 @@
#include "core/dom/NamedFlow.h"
#include "RuntimeEnabledFeatures.h"
-#include "core/dom/EventNames.h"
#include "core/dom/NamedFlowCollection.h"
#include "core/dom/StaticNodeList.h"
-#include "core/dom/UIEvent.h"
+#include "core/events/ThreadLocalEventNames.h"
+#include "core/events/UIEvent.h"
+#include "core/rendering/RenderNamedFlowFragment.h"
#include "core/rendering/RenderNamedFlowThread.h"
-#include "core/rendering/RenderRegion.h"
namespace WebCore {
@@ -104,11 +104,11 @@ int NamedFlow::firstEmptyRegionIndex() const
int countNonPseudoRegions = -1;
RenderRegionList::const_iterator iter = regionList.begin();
for (int index = 0; iter != regionList.end(); ++index, ++iter) {
- const RenderRegion* renderRegion = *iter;
+ const RenderNamedFlowFragment* renderRegion = toRenderNamedFlowFragment(*iter);
// FIXME: Pseudo-elements are not included in the list.
// They will be included when we will properly support the Region interface
// http://dev.w3.org/csswg/css-regions/#the-region-interface
- if (renderRegion->isPseudoElement())
+ if (!renderRegion->isElementBasedRegion())
continue;
countNonPseudoRegions++;
if (renderRegion->regionOversetState() == RegionEmpty)
@@ -135,13 +135,13 @@ PassRefPtr<NodeList> NamedFlow::getRegionsByContent(Node* contentNode)
if (inFlowThread(contentNode->renderer(), m_parentFlowThread)) {
const RenderRegionList& regionList = m_parentFlowThread->renderRegionList();
for (RenderRegionList::const_iterator iter = regionList.begin(); iter != regionList.end(); ++iter) {
- const RenderRegion* renderRegion = *iter;
+ const RenderNamedFlowFragment* renderRegion = toRenderNamedFlowFragment(*iter);
// They will be included when we will properly support the Region interface
// http://dev.w3.org/csswg/css-regions/#the-region-interface
- if (renderRegion->isPseudoElement())
+ if (!renderRegion->isElementBasedRegion())
continue;
if (m_parentFlowThread->objectInFlowRegion(contentNode->renderer(), renderRegion))
- regionNodes.append(renderRegion->node());
+ regionNodes.append(renderRegion->nodeForRegion());
}
}
@@ -162,12 +162,12 @@ PassRefPtr<NodeList> NamedFlow::getRegions()
const RenderRegionList& regionList = m_parentFlowThread->renderRegionList();
for (RenderRegionList::const_iterator iter = regionList.begin(); iter != regionList.end(); ++iter) {
- const RenderRegion* renderRegion = *iter;
+ const RenderNamedFlowFragment* renderRegion = toRenderNamedFlowFragment(*iter);
// They will be included when we will properly support the Region interface
// http://dev.w3.org/csswg/css-regions/#the-region-interface
- if (renderRegion->isPseudoElement())
+ if (!renderRegion->isElementBasedRegion())
continue;
- regionNodes.append(renderRegion->node());
+ regionNodes.append(renderRegion->nodeForRegion());
}
return StaticNodeList::adopt(regionNodes);
@@ -204,16 +204,6 @@ void NamedFlow::setRenderer(RenderNamedFlowThread* parentFlowThread)
m_parentFlowThread = parentFlowThread;
}
-EventTargetData* NamedFlow::eventTargetData()
-{
- return &m_eventTargetData;
-}
-
-EventTargetData* NamedFlow::ensureEventTargetData()
-{
- return &m_eventTargetData;
-}
-
void NamedFlow::dispatchRegionLayoutUpdateEvent()
{
ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
@@ -222,7 +212,7 @@ void NamedFlow::dispatchRegionLayoutUpdateEvent()
if (flowState() == FlowStateNull)
return;
- RefPtr<Event> event = UIEvent::create(eventNames().webkitregionlayoutupdateEvent, false, false, m_flowManager->document()->defaultView(), 0);
+ RefPtr<Event> event = UIEvent::create(EventTypeNames::webkitregionlayoutupdate, false, false, m_flowManager->document()->domWindow(), 0);
dispatchEvent(event);
}
@@ -235,17 +225,17 @@ void NamedFlow::dispatchRegionOversetChangeEvent()
if (flowState() == FlowStateNull)
return;
- RefPtr<Event> event = UIEvent::create(eventNames().webkitregionoversetchangeEvent, false, false, m_flowManager->document()->defaultView(), 0);
+ RefPtr<Event> event = UIEvent::create(EventTypeNames::webkitregionoversetchange, false, false, m_flowManager->document()->domWindow(), 0);
dispatchEvent(event);
}
const AtomicString& NamedFlow::interfaceName() const
{
- return eventNames().interfaceForNamedFlow;
+ return EventTargetNames::NamedFlow;
}
-ScriptExecutionContext* NamedFlow::scriptExecutionContext() const
+ExecutionContext* NamedFlow::executionContext() const
{
return m_flowManager->document();
}
diff --git a/chromium/third_party/WebKit/Source/core/dom/NamedFlow.h b/chromium/third_party/WebKit/Source/core/dom/NamedFlow.h
index 13306ccdca4..75f2bd5765a 100644
--- a/chromium/third_party/WebKit/Source/core/dom/NamedFlow.h
+++ b/chromium/third_party/WebKit/Source/core/dom/NamedFlow.h
@@ -31,7 +31,7 @@
#define NamedFlow_h
#include "bindings/v8/ScriptWrappable.h"
-#include "core/dom/EventTarget.h"
+#include "core/events/EventTarget.h"
#include "wtf/RefCounted.h"
#include "wtf/RefPtr.h"
#include "wtf/text/AtomicString.h"
@@ -43,9 +43,10 @@ class NamedFlowCollection;
class Node;
class NodeList;
class RenderNamedFlowThread;
-class ScriptExecutionContext;
+class ExecutionContext;
-class NamedFlow : public RefCounted<NamedFlow>, public ScriptWrappable, public EventTarget {
+class NamedFlow : public RefCounted<NamedFlow>, public ScriptWrappable, public EventTargetWithInlineData {
+ REFCOUNTED_EVENT_TARGET(NamedFlow);
public:
static PassRefPtr<NamedFlow> create(PassRefPtr<NamedFlowCollection> manager, const AtomicString& flowThreadName);
@@ -58,11 +59,8 @@ public:
PassRefPtr<NodeList> getRegions();
PassRefPtr<NodeList> getContent();
- using RefCounted<NamedFlow>::ref;
- using RefCounted<NamedFlow>::deref;
-
- virtual const AtomicString& interfaceName() const;
- virtual ScriptExecutionContext* scriptExecutionContext() const;
+ virtual const AtomicString& interfaceName() const OVERRIDE;
+ virtual ExecutionContext* executionContext() const OVERRIDE;
// This function is called from the JS binding code to determine if the NamedFlow object is reachable or not.
// If the object has listeners, the object should only be discarded if the parent Document is not reachable.
@@ -83,20 +81,11 @@ public:
private:
NamedFlow(PassRefPtr<NamedFlowCollection>, const AtomicString&);
- // EventTarget implementation.
- virtual void refEventTarget() { ref(); }
- virtual void derefEventTarget() { deref(); }
-
- virtual EventTargetData* eventTargetData() OVERRIDE;
- virtual EventTargetData* ensureEventTargetData() OVERRIDE;
-
// The name of the flow thread as specified in CSS.
AtomicString m_flowThreadName;
RefPtr<NamedFlowCollection> m_flowManager;
RenderNamedFlowThread* m_parentFlowThread;
-
- EventTargetData m_eventTargetData;
};
}
diff --git a/chromium/third_party/WebKit/Source/core/dom/NamedFlowCollection.cpp b/chromium/third_party/WebKit/Source/core/dom/NamedFlowCollection.cpp
index ef35fa9c383..2b48c7be3d1 100644
--- a/chromium/third_party/WebKit/Source/core/dom/NamedFlowCollection.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/NamedFlowCollection.cpp
@@ -33,7 +33,6 @@
#include "RuntimeEnabledFeatures.h"
#include "core/dom/DOMNamedFlowCollection.h"
#include "core/dom/Document.h"
-#include "core/dom/NamedFlow.h"
#include "core/inspector/InspectorInstrumentation.h"
#include "wtf/text/StringHash.h"
#include "wtf/text/WTFString.h"
@@ -41,7 +40,7 @@
namespace WebCore {
NamedFlowCollection::NamedFlowCollection(Document* document)
- : ContextLifecycleObserver(document)
+ : DocumentLifecycleObserver(document)
{
ASSERT(RuntimeEnabledFeatures::cssRegionsEnabled());
}
@@ -62,7 +61,7 @@ Vector<RefPtr<NamedFlow> > NamedFlowCollection::namedFlows()
NamedFlow* NamedFlowCollection::flowByName(const String& flowName)
{
- NamedFlowSet::iterator it = m_namedFlows.find<String, NamedFlowHashTranslator>(flowName);
+ NamedFlowSet::iterator it = m_namedFlows.find<NamedFlowHashTranslator>(flowName);
if (it == m_namedFlows.end() || (*it)->flowState() == NamedFlow::FlowStateNull)
return 0;
@@ -71,7 +70,7 @@ NamedFlow* NamedFlowCollection::flowByName(const String& flowName)
PassRefPtr<NamedFlow> NamedFlowCollection::ensureFlowWithName(const String& flowName)
{
- NamedFlowSet::iterator it = m_namedFlows.find<String, NamedFlowHashTranslator>(flowName);
+ NamedFlowSet::iterator it = m_namedFlows.find<NamedFlowHashTranslator>(flowName);
if (it != m_namedFlows.end()) {
NamedFlow* namedFlow = *it;
ASSERT(namedFlow->flowState() == NamedFlow::FlowStateNull);
@@ -103,8 +102,7 @@ void NamedFlowCollection::discardNamedFlow(NamedFlow* namedFlow)
Document* NamedFlowCollection::document() const
{
- ScriptExecutionContext* context = ContextLifecycleObserver::scriptExecutionContext();
- return toDocument(context);
+ return lifecycleContext();
}
PassRefPtr<DOMNamedFlowCollection> NamedFlowCollection::createCSSOMSnapshot()
diff --git a/chromium/third_party/WebKit/Source/core/dom/NamedFlowCollection.h b/chromium/third_party/WebKit/Source/core/dom/NamedFlowCollection.h
index 8d8d32cb9e9..f9c4b9cb446 100644
--- a/chromium/third_party/WebKit/Source/core/dom/NamedFlowCollection.h
+++ b/chromium/third_party/WebKit/Source/core/dom/NamedFlowCollection.h
@@ -30,7 +30,7 @@
#ifndef NamedFlowCollection_h
#define NamedFlowCollection_h
-#include "core/dom/ContextLifecycleObserver.h"
+#include "core/dom/DocumentLifecycleObserver.h"
#include "core/dom/NamedFlow.h"
#include "wtf/Forward.h"
#include "wtf/ListHashSet.h"
@@ -43,7 +43,7 @@ namespace WebCore {
class Document;
class DOMNamedFlowCollection;
-class NamedFlowCollection : public RefCounted<NamedFlowCollection>, public ContextLifecycleObserver {
+class NamedFlowCollection : public RefCounted<NamedFlowCollection>, public DocumentLifecycleObserver {
public:
static PassRefPtr<NamedFlowCollection> create(Document* doc) { return adoptRef(new NamedFlowCollection(doc)); }
diff --git a/chromium/third_party/WebKit/Source/core/dom/NamedNodeMap.cpp b/chromium/third_party/WebKit/Source/core/dom/NamedNodeMap.cpp
index 24e787b7246..2265972d656 100644
--- a/chromium/third_party/WebKit/Source/core/dom/NamedNodeMap.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/NamedNodeMap.cpp
@@ -35,11 +35,6 @@ namespace WebCore {
using namespace HTMLNames;
-static inline bool shouldIgnoreAttributeCase(const Element* e)
-{
- return e && e->document().isHTMLDocument() && e->isHTMLElement();
-}
-
void NamedNodeMap::ref()
{
m_element->ref();
@@ -60,45 +55,45 @@ PassRefPtr<Node> NamedNodeMap::getNamedItemNS(const AtomicString& namespaceURI,
return m_element->getAttributeNodeNS(namespaceURI, localName);
}
-PassRefPtr<Node> NamedNodeMap::removeNamedItem(const AtomicString& name, ExceptionState& es)
+PassRefPtr<Node> NamedNodeMap::removeNamedItem(const AtomicString& name, ExceptionState& exceptionState)
{
- size_t index = m_element->hasAttributes() ? m_element->getAttributeItemIndex(name, shouldIgnoreAttributeCase(m_element)) : kNotFound;
+ size_t index = m_element->hasAttributes() ? m_element->getAttributeItemIndex(name, m_element->shouldIgnoreAttributeCase()) : kNotFound;
if (index == kNotFound) {
- es.throwDOMException(NotFoundError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
return 0;
}
return m_element->detachAttribute(index);
}
-PassRefPtr<Node> NamedNodeMap::removeNamedItemNS(const AtomicString& namespaceURI, const AtomicString& localName, ExceptionState& es)
+PassRefPtr<Node> NamedNodeMap::removeNamedItemNS(const AtomicString& namespaceURI, const AtomicString& localName, ExceptionState& exceptionState)
{
size_t index = m_element->hasAttributes() ? m_element->getAttributeItemIndex(QualifiedName(nullAtom, localName, namespaceURI)) : kNotFound;
if (index == kNotFound) {
- es.throwDOMException(NotFoundError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
return 0;
}
return m_element->detachAttribute(index);
}
-PassRefPtr<Node> NamedNodeMap::setNamedItem(Node* node, ExceptionState& es)
+PassRefPtr<Node> NamedNodeMap::setNamedItem(Node* node, ExceptionState& exceptionState)
{
if (!node) {
- es.throwDOMException(NotFoundError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
return 0;
}
// Not mentioned in spec: throw a HIERARCHY_REQUEST_ERROR if the user passes in a non-attribute node
if (!node->isAttributeNode()) {
- es.throwDOMException(HierarchyRequestError);
+ exceptionState.throwUninformativeAndGenericDOMException(HierarchyRequestError);
return 0;
}
- return m_element->setAttributeNode(toAttr(node), es);
+ return m_element->setAttributeNode(toAttr(node), exceptionState);
}
-PassRefPtr<Node> NamedNodeMap::setNamedItemNS(Node* node, ExceptionState& es)
+PassRefPtr<Node> NamedNodeMap::setNamedItemNS(Node* node, ExceptionState& exceptionState)
{
- return setNamedItem(node, es);
+ return setNamedItem(node, exceptionState);
}
PassRefPtr<Node> NamedNodeMap::item(unsigned index) const
diff --git a/chromium/third_party/WebKit/Source/core/dom/NamedNodeMap.idl b/chromium/third_party/WebKit/Source/core/dom/NamedNodeMap.idl
index 6169b7afee2..0f51574fdd1 100644
--- a/chromium/third_party/WebKit/Source/core/dom/NamedNodeMap.idl
+++ b/chromium/third_party/WebKit/Source/core/dom/NamedNodeMap.idl
@@ -19,15 +19,15 @@
*/
[
- GenerateIsReachable=element
+ GenerateVisitDOMWrapper=element,
] interface NamedNodeMap {
Node getNamedItem([Default=Undefined] optional DOMString name);
[NotEnumerable, ImplementedAs=getNamedItem] getter Node ([Default=Undefined] optional DOMString name);
- [RaisesException, CustomElementCallbacks=Enable] Node setNamedItem([Default=Undefined] optional Node node);
+ [RaisesException, CustomElementCallbacks] Node setNamedItem([Default=Undefined] optional Node node);
- [RaisesException, CustomElementCallbacks=Enable] Node removeNamedItem([Default=Undefined] optional DOMString name);
+ [RaisesException, CustomElementCallbacks] Node removeNamedItem([Default=Undefined] optional DOMString name);
getter Node item([Default=Undefined] optional unsigned long index);
@@ -40,9 +40,9 @@
/*[RaisesException]*/ Node getNamedItemNS([TreatNullAs=NullString,Default=Undefined] optional DOMString namespaceURI,
[Default=Undefined] optional DOMString localName);
- [RaisesException, CustomElementCallbacks=Enable] Node setNamedItemNS([Default=Undefined] optional Node node);
+ [RaisesException, CustomElementCallbacks] Node setNamedItemNS([Default=Undefined] optional Node node);
- [RaisesException, CustomElementCallbacks=Enable] Node removeNamedItemNS([TreatNullAs=NullString,Default=Undefined] optional DOMString namespaceURI,
+ [RaisesException, CustomElementCallbacks] Node removeNamedItemNS([TreatNullAs=NullString,Default=Undefined] optional DOMString namespaceURI,
[Default=Undefined] optional DOMString localName);
};
diff --git a/chromium/third_party/WebKit/Source/core/dom/NamedNodesCollection.h b/chromium/third_party/WebKit/Source/core/dom/NamedNodesCollection.h
index 0b4199b143f..b202bcf238f 100644
--- a/chromium/third_party/WebKit/Source/core/dom/NamedNodesCollection.h
+++ b/chromium/third_party/WebKit/Source/core/dom/NamedNodesCollection.h
@@ -39,7 +39,7 @@
namespace WebCore {
-class NamedNodesCollection : public NodeList {
+class NamedNodesCollection FINAL : public NodeList {
public:
static PassRefPtr<NodeList> create(const Vector<RefPtr<Node> >& nodes)
{
diff --git a/chromium/third_party/WebKit/Source/core/dom/Node.cpp b/chromium/third_party/WebKit/Source/core/dom/Node.cpp
index c9cba1e2512..abea9efac4e 100644
--- a/chromium/third_party/WebKit/Source/core/dom/Node.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/Node.cpp
@@ -27,71 +27,70 @@
#include "HTMLNames.h"
#include "XMLNames.h"
-#include "bindings/v8/ExceptionMessages.h"
#include "bindings/v8/ExceptionState.h"
-#include "bindings/v8/ExceptionStatePlaceholder.h"
+#include "bindings/v8/ScriptCallStackFactory.h"
#include "core/accessibility/AXObjectCache.h"
#include "core/dom/Attr.h"
#include "core/dom/Attribute.h"
-#include "core/dom/BeforeLoadEvent.h"
#include "core/dom/ChildListMutationScope.h"
#include "core/dom/ChildNodeList.h"
#include "core/dom/ClassNodeList.h"
#include "core/dom/DOMImplementation.h"
#include "core/dom/Document.h"
#include "core/dom/DocumentFragment.h"
+#include "core/dom/DocumentMarkerController.h"
#include "core/dom/DocumentType.h"
#include "core/dom/Element.h"
#include "core/dom/ElementRareData.h"
-#include "core/dom/Event.h"
-#include "core/dom/EventDispatchMediator.h"
-#include "core/dom/EventDispatcher.h"
-#include "core/dom/EventListener.h"
-#include "core/dom/EventNames.h"
#include "core/dom/ExceptionCode.h"
-#include "core/dom/GestureEvent.h"
-#include "core/dom/KeyboardEvent.h"
#include "core/dom/LiveNodeList.h"
-#include "core/dom/MouseEvent.h"
-#include "core/dom/MutationEvent.h"
#include "core/dom/NameNodeList.h"
#include "core/dom/NodeRareData.h"
#include "core/dom/NodeTraversal.h"
#include "core/dom/ProcessingInstruction.h"
+#include "core/dom/Range.h"
#include "core/dom/SelectorQuery.h"
#include "core/dom/TagNodeList.h"
#include "core/dom/TemplateContentDocumentFragment.h"
#include "core/dom/Text.h"
-#include "core/dom/TextEvent.h"
-#include "core/dom/TouchEvent.h"
#include "core/dom/TreeScopeAdopter.h"
-#include "core/dom/UIEvent.h"
#include "core/dom/UserActionElementSet.h"
#include "core/dom/WheelController.h"
-#include "core/dom/WheelEvent.h"
#include "core/dom/shadow/ElementShadow.h"
#include "core/dom/shadow/InsertionPoint.h"
#include "core/dom/shadow/ShadowRoot.h"
#include "core/editing/htmlediting.h"
+#include "core/events/BeforeLoadEvent.h"
+#include "core/events/Event.h"
+#include "core/events/EventDispatchMediator.h"
+#include "core/events/EventDispatcher.h"
+#include "core/events/EventListener.h"
+#include "core/events/GestureEvent.h"
+#include "core/events/KeyboardEvent.h"
+#include "core/events/MouseEvent.h"
+#include "core/events/MutationEvent.h"
+#include "core/events/TextEvent.h"
+#include "core/events/ThreadLocalEventNames.h"
+#include "core/events/TouchEvent.h"
+#include "core/events/UIEvent.h"
+#include "core/events/WheelEvent.h"
#include "core/html/HTMLAnchorElement.h"
#include "core/html/HTMLDialogElement.h"
#include "core/html/HTMLFrameOwnerElement.h"
#include "core/html/HTMLStyleElement.h"
#include "core/html/RadioNodeList.h"
-#include "core/inspector/InspectorCounters.h"
#include "core/page/ContextMenuController.h"
#include "core/page/EventHandler.h"
-#include "core/page/Frame.h"
+#include "core/frame/Frame.h"
#include "core/page/Page.h"
-#include "core/page/Settings.h"
-#include "core/platform/Partitions.h"
+#include "core/frame/Settings.h"
#include "core/rendering/FlowThreadController.h"
#include "core/rendering/RenderBox.h"
#include "core/svg/graphics/SVGImage.h"
+#include "platform/Partitions.h"
#include "wtf/HashSet.h"
#include "wtf/PassOwnPtr.h"
#include "wtf/RefCountedLeakCounter.h"
-#include "wtf/UnusedParam.h"
#include "wtf/Vector.h"
#include "wtf/text/CString.h"
#include "wtf/text/StringBuilder.h"
@@ -292,33 +291,36 @@ Node::~Node()
RELEASE_ASSERT(!renderer());
- if (!isContainerNode()) {
- if (Document* document = documentInternal())
- willBeDeletedFrom(document);
- }
+ if (!isContainerNode())
+ willBeDeletedFromDocument();
if (m_previous)
m_previous->setNextSibling(0);
if (m_next)
m_next->setPreviousSibling(0);
- m_treeScope->guardDeref();
+ if (m_treeScope)
+ m_treeScope->guardDeref();
InspectorCounters::decrementCounter(InspectorCounters::NodeCounter);
}
-void Node::willBeDeletedFrom(Document* document)
+void Node::willBeDeletedFromDocument()
{
+ if (!isTreeScopeInitialized())
+ return;
+
+ Document& document = this->document();
+
if (hasEventTargetData()) {
- if (document)
- document->didRemoveEventTargetNode(this);
+ document.didRemoveEventTargetNode(this);
clearEventTargetData();
}
- if (document) {
- if (AXObjectCache* cache = document->existingAXObjectCache())
- cache->remove(this);
- }
+ if (AXObjectCache* cache = document.existingAXObjectCache())
+ cache->remove(this);
+
+ document.markers()->removeMarkers(this);
}
NodeRareData* Node::rareData() const
@@ -327,10 +329,10 @@ NodeRareData* Node::rareData() const
return static_cast<NodeRareData*>(m_data.m_rareData);
}
-NodeRareData* Node::ensureRareData()
+NodeRareData& Node::ensureRareData()
{
if (hasRareData())
- return rareData();
+ return *rareData();
NodeRareData* data;
if (isElementNode())
@@ -341,7 +343,7 @@ NodeRareData* Node::ensureRareData()
m_data.m_rareData = data;
setFlag(HasRareDataFlag);
- return data;
+ return *data;
}
void Node::clearRareData()
@@ -380,23 +382,16 @@ void Node::setNodeValue(const String&)
PassRefPtr<NodeList> Node::childNodes()
{
- return ensureRareData()->ensureNodeLists()->ensureChildNodeList(this);
+ return ensureRareData().ensureNodeLists().ensureChildNodeList(this);
}
-Node *Node::lastDescendant() const
+Node& Node::lastDescendant() const
{
- Node *n = const_cast<Node *>(this);
+ Node* n = const_cast<Node*>(this);
while (n && n->lastChild())
n = n->lastChild();
- return n;
-}
-
-Node* Node::firstDescendant() const
-{
- Node *n = const_cast<Node *>(this);
- while (n && n->firstChild())
- n = n->firstChild();
- return n;
+ ASSERT(n);
+ return *n;
}
Node* Node::pseudoAwarePreviousSibling() const
@@ -455,42 +450,42 @@ Node* Node::pseudoAwareLastChild() const
return lastChild();
}
-void Node::insertBefore(PassRefPtr<Node> newChild, Node* refChild, ExceptionState& es)
+void Node::insertBefore(PassRefPtr<Node> newChild, Node* refChild, ExceptionState& exceptionState)
{
if (isContainerNode())
- toContainerNode(this)->insertBefore(newChild, refChild, es);
+ toContainerNode(this)->insertBefore(newChild, refChild, exceptionState);
else
- es.throwDOMException(HierarchyRequestError);
+ exceptionState.throwDOMException(HierarchyRequestError, "This node type does not support this method.");
}
-void Node::replaceChild(PassRefPtr<Node> newChild, Node* oldChild, ExceptionState& es)
+void Node::replaceChild(PassRefPtr<Node> newChild, Node* oldChild, ExceptionState& exceptionState)
{
if (isContainerNode())
- toContainerNode(this)->replaceChild(newChild, oldChild, es);
+ toContainerNode(this)->replaceChild(newChild, oldChild, exceptionState);
else
- es.throwDOMException(HierarchyRequestError);
+ exceptionState.throwDOMException(HierarchyRequestError, "This node type does not support this method.");
}
-void Node::removeChild(Node* oldChild, ExceptionState& es)
+void Node::removeChild(Node* oldChild, ExceptionState& exceptionState)
{
if (isContainerNode())
- toContainerNode(this)->removeChild(oldChild, es);
+ toContainerNode(this)->removeChild(oldChild, exceptionState);
else
- es.throwDOMException(NotFoundError);
+ exceptionState.throwDOMException(NotFoundError, "This node type does not support this method.");
}
-void Node::appendChild(PassRefPtr<Node> newChild, ExceptionState& es)
+void Node::appendChild(PassRefPtr<Node> newChild, ExceptionState& exceptionState)
{
if (isContainerNode())
- toContainerNode(this)->appendChild(newChild, es);
+ toContainerNode(this)->appendChild(newChild, exceptionState);
else
- es.throwDOMException(HierarchyRequestError);
+ exceptionState.throwDOMException(HierarchyRequestError, "This node type does not support this method.");
}
-void Node::remove(ExceptionState& es)
+void Node::remove(ExceptionState& exceptionState)
{
if (ContainerNode* parent = parentNode())
- parent->removeChild(this, es);
+ parent->removeChild(this, exceptionState);
}
void Node::normalize()
@@ -504,15 +499,15 @@ void Node::normalize()
while (node) {
NodeType type = node->nodeType();
if (type == ELEMENT_NODE)
- toElement(node.get())->normalizeAttributes();
+ toElement(node)->normalizeAttributes();
if (node == this)
break;
if (type == TEXT_NODE)
- node = toText(node.get())->mergeNextSiblingNodesIfPossible();
+ node = toText(node)->mergeNextSiblingNodesIfPossible();
else
- node = NodeTraversal::nextPostOrder(node.get());
+ node = NodeTraversal::nextPostOrder(*node);
}
}
@@ -522,12 +517,12 @@ const AtomicString& Node::prefix() const
return nullAtom;
}
-void Node::setPrefix(const AtomicString& /*prefix*/, ExceptionState& es)
+void Node::setPrefix(const AtomicString& /*prefix*/, ExceptionState& exceptionState)
{
// The spec says that for nodes other than elements and attributes, prefix is always null.
// It does not say what to do when the user tries to set the prefix on another type of
// node, however Mozilla throws a NamespaceError exception.
- es.throwDOMException(NamespaceError);
+ exceptionState.throwDOMException(NamespaceError, "Prefixes are only supported on element and attribute nodes.");
}
const AtomicString& Node::localName() const
@@ -625,21 +620,6 @@ LayoutRect Node::boundingBox() const
return LayoutRect();
}
-LayoutRect Node::renderRect(bool* isReplaced)
-{
- RenderObject* hitRenderer = this->renderer();
- ASSERT(hitRenderer);
- RenderObject* renderer = hitRenderer;
- while (renderer && !renderer->isBody() && !renderer->isRoot()) {
- if (renderer->isRenderBlock() || renderer->isInlineBlockOrInlineTable() || renderer->isReplaced()) {
- *isReplaced = renderer->isReplaced();
- return renderer->absoluteBoundingBoxRect();
- }
- renderer = renderer->parent();
- }
- return LayoutRect();
-}
-
bool Node::hasNonEmptyBoundingBox() const
{
// Before calling absoluteRects, check for the common case where the renderer
@@ -661,6 +641,7 @@ bool Node::hasNonEmptyBoundingBox() const
return false;
}
+#ifndef NDEBUG
inline static ShadowRoot* oldestShadowRootFor(const Node* node)
{
if (!node->isElementNode())
@@ -669,6 +650,7 @@ inline static ShadowRoot* oldestShadowRootFor(const Node* node)
return shadow->oldestShadowRoot();
return 0;
}
+#endif
void Node::recalcDistribution()
{
@@ -703,58 +685,128 @@ void Node::markAncestorsWithChildNeedsDistributionRecalc()
document().scheduleStyleRecalc();
}
-inline void Node::setStyleChange(StyleChangeType changeType)
+namespace {
+
+unsigned styledSubtreeSize(const Node*);
+
+unsigned styledSubtreeSizeIgnoringSelfAndShadowRoots(const Node* rootNode)
{
- m_nodeFlags = (m_nodeFlags & ~StyleChangeMask) | changeType;
+ unsigned nodeCount = 0;
+ for (Node* child = rootNode->firstChild(); child; child = child->nextSibling())
+ nodeCount += styledSubtreeSize(child);
+ return nodeCount;
}
-inline void Node::markAncestorsWithChildNeedsStyleRecalc()
+unsigned styledSubtreeSize(const Node* rootNode)
{
- for (ContainerNode* p = parentOrShadowHostNode(); p && !p->childNeedsStyleRecalc(); p = p->parentOrShadowHostNode())
- p->setChildNeedsStyleRecalc();
+ if (rootNode->isTextNode())
+ return 1;
+ if (!rootNode->isElementNode())
+ return 0;
- if (document().needsStyleRecalc() || document().childNeedsStyleRecalc())
- document().scheduleStyleRecalc();
+ // FIXME: We should use a shadow-tree aware node-iterator when such exists.
+ unsigned nodeCount = 1 + styledSubtreeSizeIgnoringSelfAndShadowRoots(rootNode);
+
+ // ShadowRoots don't have style (so don't count them), but their children might.
+ for (ShadowRoot* shadowRoot = rootNode->youngestShadowRoot(); shadowRoot; shadowRoot = shadowRoot->olderShadowRoot())
+ nodeCount += styledSubtreeSizeIgnoringSelfAndShadowRoots(shadowRoot);
+
+ return nodeCount;
}
-void Node::refEventTarget()
+PassRefPtr<JSONArray> jsStackAsJSONArray()
{
- ref();
+ RefPtr<JSONArray> jsonArray = JSONArray::create();
+ RefPtr<ScriptCallStack> stack = createScriptCallStack(10);
+ if (!stack)
+ return jsonArray.release();
+ for (size_t i = 0; i < stack->size(); i++)
+ jsonArray->pushString(stack->at(i).functionName());
+ return jsonArray.release();
}
-void Node::derefEventTarget()
+PassRefPtr<JSONObject> jsonObjectForStyleInvalidation(unsigned nodeCount, const Node* rootNode)
{
- deref();
+ RefPtr<JSONObject> jsonObject = JSONObject::create();
+ jsonObject->setNumber("node_count", nodeCount);
+ jsonObject->setString("root_node", rootNode->debugName());
+ jsonObject->setArray("js_stack", jsStackAsJSONArray());
+ return jsonObject.release();
+}
+
+} // anonymous namespace'd functions supporting traceStyleChange
+
+void Node::traceStyleChange(StyleChangeType changeType)
+{
+ static const unsigned kMinLoggedSize = 100;
+ unsigned nodeCount = styledSubtreeSize(this);
+ if (nodeCount < kMinLoggedSize)
+ return;
+
+ TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("style.debug"),
+ "Node::setNeedsStyleRecalc",
+ "data", jsonObjectForStyleInvalidation(nodeCount, this)->toJSONString().ascii()
+ );
+}
+
+void Node::traceStyleChangeIfNeeded(StyleChangeType changeType)
+{
+ // TRACE_EVENT_CATEGORY_GROUP_ENABLED macro loads a global static bool into our local bool.
+ bool styleTracingEnabled;
+ TRACE_EVENT_CATEGORY_GROUP_ENABLED(TRACE_DISABLED_BY_DEFAULT("style.debug"), &styleTracingEnabled);
+ if (UNLIKELY(styleTracingEnabled))
+ traceStyleChange(changeType);
+}
+
+inline void Node::setStyleChange(StyleChangeType changeType)
+{
+ m_nodeFlags = (m_nodeFlags & ~StyleChangeMask) | changeType;
+}
+
+void Node::markAncestorsWithChildNeedsStyleRecalc()
+{
+ for (ContainerNode* p = parentOrShadowHostNode(); p && !p->childNeedsStyleRecalc(); p = p->parentOrShadowHostNode())
+ p->setChildNeedsStyleRecalc();
+
+ if (document().needsStyleRecalc() || document().childNeedsStyleRecalc())
+ document().scheduleStyleRecalc();
}
void Node::setNeedsStyleRecalc(StyleChangeType changeType, StyleChangeSource source)
{
ASSERT(changeType != NoStyleChange);
- if (!attached()) // changed compared to what?
+ if (!inActiveDocument())
return;
if (source == StyleChangeFromRenderer)
setFlag(NotifyRendererWithIdenticalStyles);
StyleChangeType existingChangeType = styleChangeType();
- if (changeType > existingChangeType)
+ if (changeType > existingChangeType) {
setStyleChange(changeType);
+ if (changeType >= SubtreeStyleChange)
+ traceStyleChangeIfNeeded(changeType);
+ }
if (existingChangeType == NoStyleChange)
markAncestorsWithChildNeedsStyleRecalc();
+
+ if (isElementNode() && hasRareData())
+ toElement(*this).setAnimationStyleChange(false);
}
-void Node::lazyAttach()
+void Node::clearNeedsStyleRecalc()
{
- markAncestorsWithChildNeedsStyleRecalc();
- for (Node* node = this; node; node = NodeTraversal::next(node, this)) {
- node->setAttached();
- node->setStyleChange(LazyAttachStyleChange);
- if (node->isContainerNode())
- node->setChildNeedsStyleRecalc();
- for (ShadowRoot* root = node->youngestShadowRoot(); root; root = root->olderShadowRoot())
- root->lazyAttach();
- }
+ m_nodeFlags &= ~StyleChangeMask;
+ clearFlag(NotifyRendererWithIdenticalStyles);
+
+ if (isElementNode() && hasRareData())
+ toElement(*this).setAnimationStyleChange(false);
+}
+
+bool Node::inActiveDocument() const
+{
+ return inDocument() && document().isActive();
}
Node* Node::focusDelegate()
@@ -854,13 +906,13 @@ void Node::clearNodeLists()
rareData()->clearNodeLists();
}
-void Node::checkSetPrefix(const AtomicString& prefix, ExceptionState& es)
+void Node::checkSetPrefix(const AtomicString& prefix, ExceptionState& exceptionState)
{
// Perform error checking as required by spec for setting Node.prefix. Used by
// Element::setPrefix() and Attr::setPrefix()
if (!prefix.isEmpty() && !Document::isValidName(prefix)) {
- es.throwDOMException(InvalidCharacterError);
+ exceptionState.throwDOMException(InvalidCharacterError, "The prefix '" + prefix + "' is not a valid name.");
return;
}
@@ -868,12 +920,12 @@ void Node::checkSetPrefix(const AtomicString& prefix, ExceptionState& es)
const AtomicString& nodeNamespaceURI = namespaceURI();
if (nodeNamespaceURI.isEmpty() && !prefix.isEmpty()) {
- es.throwDOMException(NamespaceError, ExceptionMessages::failedToSet("prefix", "Node", "No namespace is set, so a namespace prefix may not be set."));
+ exceptionState.throwDOMException(NamespaceError, "No namespace is set, so a namespace prefix may not be set.");
return;
}
if (prefix == xmlAtom && nodeNamespaceURI != XMLNames::xmlNamespaceURI) {
- es.throwDOMException(NamespaceError, ExceptionMessages::failedToSet("prefix", "Node", "The prefix '" + xmlAtom + "' may not be set on namespace '" + nodeNamespaceURI + "'."));
+ exceptionState.throwDOMException(NamespaceError, "The prefix '" + xmlAtom + "' may not be set on namespace '" + nodeNamespaceURI + "'.");
return;
}
// Attribute-specific checks are in Attr::setPrefix().
@@ -884,7 +936,7 @@ bool Node::isDescendantOf(const Node *other) const
// Return true if other is an ancestor of this, otherwise false
if (!other || !other->hasChildNodes() || inDocument() != other->inDocument())
return false;
- if (&other->treeScope() != &treeScope())
+ if (other->treeScope() != treeScope())
return false;
if (other->isTreeScope())
return !isTreeScope();
@@ -910,7 +962,7 @@ bool Node::containsIncludingShadowDOM(const Node* node) const
if (this == node)
return true;
- if (&document() != &node->document())
+ if (document() != node->document())
return false;
if (inDocument() != node->inDocument())
@@ -922,48 +974,62 @@ bool Node::containsIncludingShadowDOM(const Node* node) const
return false;
for (; node; node = node->shadowHost()) {
- if (&treeScope() == &node->treeScope())
+ if (treeScope() == node->treeScope())
return contains(node);
}
return false;
}
-bool Node::containsIncludingHostElements(const Node* node) const
+bool Node::containsIncludingHostElements(const Node& node) const
{
- while (node) {
- if (node == this)
+ const Node* current = &node;
+ do {
+ if (current == this)
return true;
- if (node->isDocumentFragment() && toDocumentFragment(node)->isTemplateContent())
- node = static_cast<const TemplateContentDocumentFragment*>(node)->host();
+ if (current->isDocumentFragment() && toDocumentFragment(current)->isTemplateContent())
+ current = static_cast<const TemplateContentDocumentFragment*>(current)->host();
else
- node = node->parentOrShadowHostNode();
- }
+ current = current->parentOrShadowHostNode();
+ } while (current);
return false;
}
-inline void Node::detachNode(Node* root, const AttachContext& context)
+Node* Node::commonAncestor(const Node& other, Node* (*parent)(const Node&))
{
- Node* node = root;
- while (node) {
- if (node->styleChangeType() == LazyAttachStyleChange) {
- // FIXME: This is needed because Node::lazyAttach marks nodes as being attached even
- // though they've never been through attach(). This allows us to avoid doing all the
- // virtual calls to detach() and other associated work.
- node->clearAttached();
- node->clearChildNeedsStyleRecalc();
-
- for (ShadowRoot* shadowRoot = node->youngestShadowRoot(); shadowRoot; shadowRoot = shadowRoot->olderShadowRoot())
- detachNode(shadowRoot, context);
-
- node = NodeTraversal::next(node, root);
- continue;
- }
- // Handle normal reattaches from style recalc (ex. display type changes)
- if (node->attached())
- node->detach(context);
- node = NodeTraversal::nextSkippingChildren(node, root);
+ if (this == other)
+ return this;
+ if (document() != other.document())
+ return 0;
+ int thisDepth = 0;
+ for (Node* node = this; node; node = parent(*node)) {
+ if (node == &other)
+ return node;
+ thisDepth++;
}
+ int otherDepth = 0;
+ for (const Node* node = &other; node; node = parent(*node)) {
+ if (node == this)
+ return this;
+ otherDepth++;
+ }
+ Node* thisIterator = this;
+ const Node* otherIterator = &other;
+ if (thisDepth > otherDepth) {
+ for (int i = thisDepth; i > otherDepth; --i)
+ thisIterator = parent(*thisIterator);
+ } else if (otherDepth > thisDepth) {
+ for (int i = otherDepth; i > thisDepth; --i)
+ otherIterator = parent(*otherIterator);
+ }
+ while (thisIterator) {
+ if (thisIterator == otherIterator)
+ return thisIterator;
+ thisIterator = parent(*thisIterator);
+ otherIterator = parent(*otherIterator);
+ }
+ ASSERT(!otherIterator);
+ return 0;
}
void Node::reattach(const AttachContext& context)
@@ -971,17 +1037,18 @@ void Node::reattach(const AttachContext& context)
AttachContext reattachContext(context);
reattachContext.performingReattach = true;
- detachNode(this, reattachContext);
+ // We only need to detach if the node has already been through attach().
+ if (styleChangeType() < NeedsReattachStyleChange)
+ detach(reattachContext);
attach(reattachContext);
}
void Node::attach(const AttachContext&)
{
ASSERT(document().inStyleRecalc() || isDocumentNode());
- ASSERT(!attached());
+ ASSERT(needsAttach());
ASSERT(!renderer() || (renderer()->style() && (renderer()->parent() || renderer()->isRenderView())));
- setAttached();
clearNeedsStyleRecalc();
if (Document* doc = documentInternal()) {
@@ -1023,13 +1090,31 @@ void Node::detach(const AttachContext& context)
}
}
- clearAttached();
+ setStyleChange(NeedsReattachStyleChange);
+ setChildNeedsStyleRecalc();
#ifndef NDEBUG
detachingNode = 0;
#endif
}
+void Node::reattachWhitespaceSiblings(Text* start)
+{
+ for (Node* sibling = start; sibling; sibling = sibling->nextSibling()) {
+ if (sibling->isTextNode() && toText(sibling)->containsOnlyWhitespace()) {
+ bool hadRenderer = sibling->hasRenderer();
+ sibling->reattach();
+ // If the reattach didn't toggle the visibility of the whitespace we don't
+ // need to continue reattaching siblings since they won't toggle visibility
+ // either.
+ if (hadRenderer == sibling->hasRenderer())
+ return;
+ } else if (sibling->renderer()) {
+ return;
+ }
+ }
+}
+
// FIXME: This code is used by editing. Seems like it could move over there and not pollute Node.
Node *Node::previousNodeConsideringAtomicNodes() const
{
@@ -1144,7 +1229,7 @@ Node* Node::nonBoundaryShadowTreeRootNode()
while (root) {
if (root->isShadowRoot())
return root;
- Node* parent = root->parentNodeGuaranteedHostFree();
+ Node* parent = root->parentOrShadowHostNode();
if (parent && parent->isShadowRoot())
return root;
root = parent;
@@ -1173,6 +1258,13 @@ Element* Node::parentOrShadowHostElement() const
return toElement(parent);
}
+ContainerNode* Node::parentOrShadowHostOrTemplateHostNode() const
+{
+ if (isDocumentFragment() && toDocumentFragment(this)->isTemplateContent())
+ return static_cast<const TemplateContentDocumentFragment*>(this)->host();
+ return parentOrShadowHostNode();
+}
+
bool Node::isBlockFlowElement() const
{
return isElementNode() && renderer() && renderer()->isRenderBlockFlow();
@@ -1235,8 +1327,8 @@ PassRefPtr<NodeList> Node::getElementsByTagName(const AtomicString& localName)
return 0;
if (document().isHTMLDocument())
- return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLTagNodeList>(this, HTMLTagNodeListType, localName);
- return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<TagNodeList>(this, TagNodeListType, localName);
+ return ensureRareData().ensureNodeLists().addCacheWithAtomicName<HTMLTagNodeList>(this, HTMLTagNodeListType, localName);
+ return ensureRareData().ensureNodeLists().addCacheWithAtomicName<TagNodeList>(this, TagNodeListType, localName);
}
PassRefPtr<NodeList> Node::getElementsByTagNameNS(const AtomicString& namespaceURI, const AtomicString& localName)
@@ -1247,49 +1339,49 @@ PassRefPtr<NodeList> Node::getElementsByTagNameNS(const AtomicString& namespaceU
if (namespaceURI == starAtom)
return getElementsByTagName(localName);
- return ensureRareData()->ensureNodeLists()->addCacheWithQualifiedName(this, namespaceURI.isEmpty() ? nullAtom : namespaceURI, localName);
+ return ensureRareData().ensureNodeLists().addCacheWithQualifiedName(this, namespaceURI.isEmpty() ? nullAtom : namespaceURI, localName);
}
PassRefPtr<NodeList> Node::getElementsByName(const String& elementName)
{
- return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<NameNodeList>(this, NameNodeListType, elementName);
+ return ensureRareData().ensureNodeLists().addCacheWithAtomicName<NameNodeList>(this, NameNodeListType, elementName);
}
PassRefPtr<NodeList> Node::getElementsByClassName(const String& classNames)
{
- return ensureRareData()->ensureNodeLists()->addCacheWithName<ClassNodeList>(this, ClassNodeListType, classNames);
+ return ensureRareData().ensureNodeLists().addCacheWithName<ClassNodeList>(this, ClassNodeListType, classNames);
}
PassRefPtr<RadioNodeList> Node::radioNodeList(const AtomicString& name)
{
ASSERT(hasTagName(formTag) || hasTagName(fieldsetTag));
- return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<RadioNodeList>(this, RadioNodeListType, name);
+ return ensureRareData().ensureNodeLists().addCacheWithAtomicName<RadioNodeList>(this, RadioNodeListType, name);
}
-PassRefPtr<Element> Node::querySelector(const AtomicString& selectors, ExceptionState& es)
+PassRefPtr<Element> Node::querySelector(const AtomicString& selectors, ExceptionState& exceptionState)
{
if (selectors.isEmpty()) {
- es.throwDOMException(SyntaxError);
+ exceptionState.throwDOMException(SyntaxError, "The provided selector is empty.");
return 0;
}
- SelectorQuery* selectorQuery = document().selectorQueryCache()->add(selectors, document(), es);
+ SelectorQuery* selectorQuery = document().selectorQueryCache().add(selectors, document(), exceptionState);
if (!selectorQuery)
return 0;
- return selectorQuery->queryFirst(this);
+ return selectorQuery->queryFirst(*this);
}
-PassRefPtr<NodeList> Node::querySelectorAll(const AtomicString& selectors, ExceptionState& es)
+PassRefPtr<NodeList> Node::querySelectorAll(const AtomicString& selectors, ExceptionState& exceptionState)
{
if (selectors.isEmpty()) {
- es.throwDOMException(SyntaxError);
+ exceptionState.throwDOMException(SyntaxError, "The provided selector is empty.");
return 0;
}
- SelectorQuery* selectorQuery = document().selectorQueryCache()->add(selectors, document(), es);
+ SelectorQuery* selectorQuery = document().selectorQueryCache().add(selectors, document(), exceptionState);
if (!selectorQuery)
return 0;
- return selectorQuery->queryAll(this);
+ return selectorQuery->queryAll(*this);
}
Document* Node::ownerDocument() const
@@ -1410,13 +1502,13 @@ bool Node::isDefaultNamespace(const AtomicString& namespaceURIMaybeEmpty) const
}
}
-String Node::lookupPrefix(const AtomicString &namespaceURI) const
+const AtomicString& Node::lookupPrefix(const AtomicString& namespaceURI) const
{
// Implemented according to
// http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/namespaces-algorithms.html#lookupNamespacePrefixAlgo
if (namespaceURI.isEmpty())
- return String();
+ return nullAtom;
switch (nodeType()) {
case ELEMENT_NODE:
@@ -1424,32 +1516,32 @@ String Node::lookupPrefix(const AtomicString &namespaceURI) const
case DOCUMENT_NODE:
if (Element* de = toDocument(this)->documentElement())
return de->lookupPrefix(namespaceURI);
- return String();
+ return nullAtom;
case ENTITY_NODE:
case NOTATION_NODE:
case DOCUMENT_FRAGMENT_NODE:
case DOCUMENT_TYPE_NODE:
- return String();
+ return nullAtom;
case ATTRIBUTE_NODE: {
- const Attr *attr = static_cast<const Attr *>(this);
+ const Attr *attr = toAttr(this);
if (attr->ownerElement())
return attr->ownerElement()->lookupPrefix(namespaceURI);
- return String();
+ return nullAtom;
}
default:
if (Element* ancestor = ancestorElement())
return ancestor->lookupPrefix(namespaceURI);
- return String();
+ return nullAtom;
}
}
-String Node::lookupNamespaceURI(const String &prefix) const
+const AtomicString& Node::lookupNamespaceURI(const String& prefix) const
{
// Implemented according to
// http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/namespaces-algorithms.html#lookupNamespaceURIAlgo
if (!prefix.isNull() && prefix.isEmpty())
- return String();
+ return nullAtom;
switch (nodeType()) {
case ELEMENT_NODE: {
@@ -1466,47 +1558,46 @@ String Node::lookupNamespaceURI(const String &prefix) const
if (!attr->value().isEmpty())
return attr->value();
- return String();
+ return nullAtom;
} else if (attr->localName() == xmlnsAtom && prefix.isNull()) {
if (!attr->value().isEmpty())
return attr->value();
- return String();
+ return nullAtom;
}
}
}
if (Element* ancestor = ancestorElement())
return ancestor->lookupNamespaceURI(prefix);
- return String();
+ return nullAtom;
}
case DOCUMENT_NODE:
if (Element* de = toDocument(this)->documentElement())
return de->lookupNamespaceURI(prefix);
- return String();
+ return nullAtom;
case ENTITY_NODE:
case NOTATION_NODE:
case DOCUMENT_TYPE_NODE:
case DOCUMENT_FRAGMENT_NODE:
- return String();
+ return nullAtom;
case ATTRIBUTE_NODE: {
- const Attr *attr = static_cast<const Attr *>(this);
-
+ const Attr *attr = toAttr(this);
if (attr->ownerElement())
return attr->ownerElement()->lookupNamespaceURI(prefix);
else
- return String();
+ return nullAtom;
}
default:
if (Element* ancestor = ancestorElement())
return ancestor->lookupNamespaceURI(prefix);
- return String();
+ return nullAtom;
}
}
-String Node::lookupNamespacePrefix(const AtomicString &_namespaceURI, const Element *originalElement) const
+const AtomicString& Node::lookupNamespacePrefix(const AtomicString& _namespaceURI, const Element* originalElement) const
{
if (_namespaceURI.isNull())
- return String();
+ return nullAtom;
if (originalElement->lookupNamespaceURI(prefix()) == _namespaceURI)
return prefix();
@@ -1525,7 +1616,7 @@ String Node::lookupNamespacePrefix(const AtomicString &_namespaceURI, const Elem
if (Element* ancestor = ancestorElement())
return ancestor->lookupNamespacePrefix(_namespaceURI, originalElement);
- return String();
+ return nullAtom;
}
static void appendTextContent(const Node* node, bool convertBRsToNewlines, bool& isNullString, StringBuilder& content)
@@ -1577,7 +1668,7 @@ String Node::textContent(bool convertBRsToNewlines) const
return isNullString ? String() : content.toString();
}
-void Node::setTextContent(const String& text, ExceptionState& es)
+void Node::setTextContent(const String& text)
{
switch (nodeType()) {
case TEXT_NODE:
@@ -1591,10 +1682,10 @@ void Node::setTextContent(const String& text, ExceptionState& es)
case ENTITY_NODE:
case DOCUMENT_FRAGMENT_NODE: {
RefPtr<ContainerNode> container = toContainerNode(this);
- ChildListMutationScope mutation(this);
+ ChildListMutationScope mutation(*this);
container->removeChildren();
if (!text.isEmpty())
- container->appendChild(document().createTextNode(text), es);
+ container->appendChild(document().createTextNode(text), ASSERT_NO_EXCEPTION);
return;
}
case DOCUMENT_NODE:
@@ -1681,7 +1772,7 @@ unsigned short Node::compareDocumentPositionInternal(const Node* otherNode, Shad
// If one node is in the document and the other is not, we must be disconnected.
// If the nodes have different owning documents, they must be disconnected. Note that we avoid
// comparing Attr nodes here, since they return false from inDocument() all the time (which seems like a bug).
- if (start1->inDocument() != start2->inDocument() || (treatment == TreatShadowTreesAsDisconnected && &start1->treeScope() != &start2->treeScope())) {
+ if (start1->inDocument() != start2->inDocument() || (treatment == TreatShadowTreesAsDisconnected && start1->treeScope() != start2->treeScope())) {
unsigned short direction = (this > otherNode) ? DOCUMENT_POSITION_PRECEDING : DOCUMENT_POSITION_FOLLOWING;
return DOCUMENT_POSITION_DISCONNECTED | DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC | direction;
}
@@ -1702,7 +1793,7 @@ unsigned short Node::compareDocumentPositionInternal(const Node* otherNode, Shad
return DOCUMENT_POSITION_DISCONNECTED | DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC | direction;
}
- unsigned connection = &start1->treeScope() != &start2->treeScope() ? DOCUMENT_POSITION_DISCONNECTED | DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC : 0;
+ unsigned connection = start1->treeScope() != start2->treeScope() ? DOCUMENT_POSITION_DISCONNECTED | DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC : 0;
// Walk the two chains backwards and look for the first difference.
for (unsigned i = min(index1, index2); i; --i) {
@@ -1894,7 +1985,7 @@ void Node::showNodePathForThis() const
static void traverseTreeAndMark(const String& baseIndent, const Node* rootNode, const Node* markedNode1, const char* markedLabel1, const Node* markedNode2, const char* markedLabel2)
{
- for (const Node* node = rootNode; node; node = NodeTraversal::next(node)) {
+ for (const Node* node = rootNode; node; node = NodeTraversal::next(*node)) {
if (node == markedNode1)
fprintf(stderr, "%s", markedLabel1);
if (node == markedNode2)
@@ -2013,15 +2104,15 @@ Node* Node::enclosingLinkEventParentOrSelf()
const AtomicString& Node::interfaceName() const
{
- return eventNames().interfaceForNode;
+ return EventTargetNames::Node;
}
-ScriptExecutionContext* Node::scriptExecutionContext() const
+ExecutionContext* Node::executionContext() const
{
return document().contextDocument().get();
}
-void Node::didMoveToNewDocument(Document* oldDocument)
+void Node::didMoveToNewDocument(Document& oldDocument)
{
TreeScopeAdopter::ensureDidMoveToNewDocumentWasCalled(oldDocument);
@@ -2034,27 +2125,28 @@ void Node::didMoveToNewDocument(Document* oldDocument)
}
}
- if (AXObjectCache::accessibilityEnabled() && oldDocument)
- if (AXObjectCache* cache = oldDocument->existingAXObjectCache())
+ if (AXObjectCache::accessibilityEnabled()) {
+ if (AXObjectCache* cache = oldDocument.existingAXObjectCache())
cache->remove(this);
+ }
- const EventListenerVector& mousewheelListeners = getEventListeners(eventNames().mousewheelEvent);
- WheelController* oldController = WheelController::from(oldDocument);
+ const EventListenerVector& mousewheelListeners = getEventListeners(EventTypeNames::mousewheel);
+ WheelController* oldController = WheelController::from(&oldDocument);
WheelController* newController = WheelController::from(&document());
for (size_t i = 0; i < mousewheelListeners.size(); ++i) {
- oldController->didRemoveWheelEventHandler(oldDocument);
+ oldController->didRemoveWheelEventHandler(&oldDocument);
newController->didAddWheelEventHandler(&document());
}
- const EventListenerVector& wheelListeners = getEventListeners(eventNames().wheelEvent);
+ const EventListenerVector& wheelListeners = getEventListeners(EventTypeNames::wheel);
for (size_t i = 0; i < wheelListeners.size(); ++i) {
- oldController->didRemoveWheelEventHandler(oldDocument);
+ oldController->didRemoveWheelEventHandler(&oldDocument);
newController->didAddWheelEventHandler(&document());
}
- if (const TouchEventTargetSet* touchHandlers = oldDocument ? oldDocument->touchEventTargets() : 0) {
+ if (const TouchEventTargetSet* touchHandlers = oldDocument.touchEventTargets()) {
while (touchHandlers->contains(this)) {
- oldDocument->didRemoveTouchEventHandler(this);
+ oldDocument.didRemoveTouchEventHandler(this);
document().didAddTouchEventHandler(this);
}
}
@@ -2079,9 +2171,9 @@ static inline bool tryAddEventListener(Node* targetNode, const AtomicString& eve
Document& document = targetNode->document();
document.addListenerTypeIfNeeded(eventType);
- if (eventType == eventNames().wheelEvent || eventType == eventNames().mousewheelEvent)
+ if (eventType == EventTypeNames::wheel || eventType == EventTypeNames::mousewheel)
WheelController::from(&document)->didAddWheelEventHandler(&document);
- else if (eventNames().isTouchEventType(eventType))
+ else if (isTouchEventType(eventType))
document.didAddTouchEventHandler(targetNode);
return true;
@@ -2100,9 +2192,9 @@ static inline bool tryRemoveEventListener(Node* targetNode, const AtomicString&
// FIXME: Notify Document that the listener has vanished. We need to keep track of a number of
// listeners for each type, not just a bool - see https://bugs.webkit.org/show_bug.cgi?id=33861
Document& document = targetNode->document();
- if (eventType == eventNames().wheelEvent || eventType == eventNames().mousewheelEvent)
+ if (eventType == EventTypeNames::wheel || eventType == EventTypeNames::mousewheel)
WheelController::from(&document)->didAddWheelEventHandler(&document);
- else if (eventNames().isTouchEventType(eventType))
+ else if (isTouchEventType(eventType))
document.didRemoveTouchEventHandler(targetNode);
return true;
@@ -2126,14 +2218,14 @@ EventTargetData* Node::eventTargetData()
return hasEventTargetData() ? eventTargetDataMap().get(this) : 0;
}
-EventTargetData* Node::ensureEventTargetData()
+EventTargetData& Node::ensureEventTargetData()
{
if (hasEventTargetData())
- return eventTargetDataMap().get(this);
+ return *eventTargetDataMap().get(this);
setHasEventTargetData(true);
EventTargetData* data = new EventTargetData;
eventTargetDataMap().set(this, adoptPtr(data));
- return data;
+ return *data;
}
void Node::clearEventTargetData()
@@ -2191,7 +2283,7 @@ void Node::getRegisteredMutationObserversOfType(HashMap<MutationObserver*, Mutat
void Node::registerMutationObserver(MutationObserver* observer, MutationObserverOptions options, const HashSet<AtomicString>& attributeFilter)
{
MutationObserverRegistration* registration = 0;
- Vector<OwnPtr<MutationObserverRegistration> >& registry = ensureRareData()->ensureMutationObserverData()->registry;
+ Vector<OwnPtr<MutationObserverRegistration> >& registry = ensureRareData().ensureMutationObserverData().registry;
for (size_t i = 0; i < registry.size(); ++i) {
if (registry[i]->observer() == observer) {
registration = registry[i].get();
@@ -2228,7 +2320,7 @@ void Node::unregisterMutationObserver(MutationObserverRegistration* registration
void Node::registerTransientMutationObserver(MutationObserverRegistration* registration)
{
- ensureRareData()->ensureMutationObserverData()->transientRegistry.add(registration);
+ ensureRareData().ensureMutationObserverData().transientRegistry.add(registration);
}
void Node::unregisterTransientMutationObserver(MutationObserverRegistration* registration)
@@ -2285,9 +2377,9 @@ void Node::dispatchScopedEventDispatchMediator(PassRefPtr<EventDispatchMediator>
bool Node::dispatchEvent(PassRefPtr<Event> event)
{
if (event->isMouseEvent())
- return EventDispatcher::dispatchEvent(this, MouseEventDispatchMediator::create(adoptRef(toMouseEvent(event.leakRef())), MouseEventDispatchMediator::SyntheticMouseEvent));
+ return EventDispatcher::dispatchEvent(this, MouseEventDispatchMediator::create(static_pointer_cast<MouseEvent>(event), MouseEventDispatchMediator::SyntheticMouseEvent));
if (event->isTouchEvent())
- return dispatchTouchEvent(adoptRef(toTouchEvent(event.leakRef())));
+ return dispatchTouchEvent(static_pointer_cast<TouchEvent>(event));
return EventDispatcher::dispatchEvent(this, EventDispatchMediator::create(event));
}
@@ -2301,13 +2393,13 @@ void Node::dispatchSubtreeModifiedEvent()
if (!document().hasListenerType(Document::DOMSUBTREEMODIFIED_LISTENER))
return;
- dispatchScopedEvent(MutationEvent::create(eventNames().DOMSubtreeModifiedEvent, true));
+ dispatchScopedEvent(MutationEvent::create(EventTypeNames::DOMSubtreeModified, true));
}
bool Node::dispatchDOMActivateEvent(int detail, PassRefPtr<Event> underlyingEvent)
{
ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
- RefPtr<UIEvent> event = UIEvent::create(eventNames().DOMActivateEvent, true, true, document().defaultView(), detail);
+ RefPtr<UIEvent> event = UIEvent::create(EventTypeNames::DOMActivate, true, true, document().domWindow(), detail);
event->setUnderlyingEvent(underlyingEvent);
dispatchScopedEvent(event);
return event->defaultHandled();
@@ -2315,18 +2407,18 @@ bool Node::dispatchDOMActivateEvent(int detail, PassRefPtr<Event> underlyingEven
bool Node::dispatchKeyEvent(const PlatformKeyboardEvent& event)
{
- return EventDispatcher::dispatchEvent(this, KeyboardEventDispatchMediator::create(KeyboardEvent::create(event, document().defaultView())));
+ return EventDispatcher::dispatchEvent(this, KeyboardEventDispatchMediator::create(KeyboardEvent::create(event, document().domWindow())));
}
bool Node::dispatchMouseEvent(const PlatformMouseEvent& event, const AtomicString& eventType,
int detail, Node* relatedTarget)
{
- return EventDispatcher::dispatchEvent(this, MouseEventDispatchMediator::create(MouseEvent::create(eventType, document().defaultView(), event, detail, relatedTarget)));
+ return EventDispatcher::dispatchEvent(this, MouseEventDispatchMediator::create(MouseEvent::create(eventType, document().domWindow(), event, detail, relatedTarget)));
}
bool Node::dispatchGestureEvent(const PlatformGestureEvent& event)
{
- RefPtr<GestureEvent> gestureEvent = GestureEvent::create(document().defaultView(), event);
+ RefPtr<GestureEvent> gestureEvent = GestureEvent::create(document().domWindow(), event);
if (!gestureEvent.get())
return false;
return EventDispatcher::dispatchEvent(this, GestureEventDispatchMediator::create(gestureEvent));
@@ -2337,9 +2429,9 @@ bool Node::dispatchTouchEvent(PassRefPtr<TouchEvent> event)
return EventDispatcher::dispatchEvent(this, TouchEventDispatchMediator::create(event));
}
-void Node::dispatchSimulatedClick(Event* underlyingEvent, SimulatedClickMouseEventOptions eventOptions, SimulatedClickVisualOptions visualOptions)
+void Node::dispatchSimulatedClick(Event* underlyingEvent, SimulatedClickMouseEventOptions eventOptions)
{
- EventDispatcher::dispatchSimulatedClick(this, underlyingEvent, eventOptions, visualOptions);
+ EventDispatcher::dispatchSimulatedClick(this, underlyingEvent, eventOptions);
}
bool Node::dispatchBeforeLoadEvent(const String& sourceURL)
@@ -2355,17 +2447,17 @@ bool Node::dispatchBeforeLoadEvent(const String& sourceURL)
bool Node::dispatchWheelEvent(const PlatformWheelEvent& event)
{
- return EventDispatcher::dispatchEvent(this, WheelEventDispatchMediator::create(event, document().defaultView()));
+ return EventDispatcher::dispatchEvent(this, WheelEventDispatchMediator::create(event, document().domWindow()));
}
void Node::dispatchChangeEvent()
{
- dispatchScopedEvent(Event::createBubble(eventNames().changeEvent));
+ dispatchScopedEvent(Event::createBubble(EventTypeNames::change));
}
void Node::dispatchInputEvent()
{
- dispatchScopedEvent(Event::createBubble(eventNames().inputEvent));
+ dispatchScopedEvent(Event::createBubble(EventTypeNames::input));
}
void Node::defaultEventHandler(Event* event)
@@ -2373,24 +2465,25 @@ void Node::defaultEventHandler(Event* event)
if (event->target() != this)
return;
const AtomicString& eventType = event->type();
- if (eventType == eventNames().keydownEvent || eventType == eventNames().keypressEvent) {
+ if (eventType == EventTypeNames::keydown || eventType == EventTypeNames::keypress) {
if (event->isKeyboardEvent()) {
if (Frame* frame = document().frame())
- frame->eventHandler()->defaultKeyboardEventHandler(toKeyboardEvent(event));
+ frame->eventHandler().defaultKeyboardEventHandler(toKeyboardEvent(event));
}
- } else if (eventType == eventNames().clickEvent) {
+ } else if (eventType == EventTypeNames::click) {
int detail = event->isUIEvent() ? static_cast<UIEvent*>(event)->detail() : 0;
if (dispatchDOMActivateEvent(detail, event))
event->setDefaultHandled();
- } else if (eventType == eventNames().contextmenuEvent) {
+ } else if (eventType == EventTypeNames::contextmenu) {
if (Page* page = document().page())
page->contextMenuController().handleContextMenuEvent(event);
- } else if (eventType == eventNames().textInputEvent) {
- if (event->hasInterface(eventNames().interfaceForTextEvent))
+ } else if (eventType == EventTypeNames::textInput) {
+ if (event->hasInterface(EventNames::TextEvent)) {
if (Frame* frame = document().frame())
- frame->eventHandler()->defaultTextInputEventHandler(static_cast<TextEvent*>(event));
+ frame->eventHandler().defaultTextInputEventHandler(toTextEvent(event));
+ }
#if OS(WIN)
- } else if (eventType == eventNames().mousedownEvent && event->isMouseEvent()) {
+ } else if (eventType == EventTypeNames::mousedown && event->isMouseEvent()) {
MouseEvent* mouseEvent = toMouseEvent(event);
if (mouseEvent->button() == MiddleButton) {
if (enclosingLinkEventParentOrSelf())
@@ -2402,12 +2495,12 @@ void Node::defaultEventHandler(Event* event)
if (renderer) {
if (Frame* frame = document().frame())
- frame->eventHandler()->startPanScrolling(renderer);
+ frame->eventHandler().startPanScrolling(renderer);
}
}
#endif
- } else if ((eventType == eventNames().wheelEvent || eventType == eventNames().mousewheelEvent) && event->hasInterface(eventNames().interfaceForWheelEvent)) {
- WheelEvent* wheelEvent = static_cast<WheelEvent*>(event);
+ } else if ((eventType == EventTypeNames::wheel || eventType == EventTypeNames::mousewheel) && event->hasInterface(EventNames::WheelEvent)) {
+ WheelEvent* wheelEvent = toWheelEvent(event);
// If we don't have a renderer, send the wheel event to the first node we find with a renderer.
// This is needed for <option> and <optgroup> elements so that <select>s get a wheel scroll.
@@ -2415,10 +2508,11 @@ void Node::defaultEventHandler(Event* event)
while (startNode && !startNode->renderer())
startNode = startNode->parentOrShadowHostNode();
- if (startNode && startNode->renderer())
+ if (startNode && startNode->renderer()) {
if (Frame* frame = document().frame())
- frame->eventHandler()->defaultWheelEventHandler(startNode, wheelEvent);
- } else if (event->type() == eventNames().webkitEditableContentChangedEvent) {
+ frame->eventHandler().defaultWheelEventHandler(startNode, wheelEvent);
+ }
+ } else if (event->type() == EventTypeNames::webkitEditableContentChanged) {
dispatchInputEvent();
}
}
@@ -2431,27 +2525,27 @@ bool Node::willRespondToMouseMoveEvents()
{
if (isDisabledFormControl(this))
return false;
- return hasEventListeners(eventNames().mousemoveEvent) || hasEventListeners(eventNames().mouseoverEvent) || hasEventListeners(eventNames().mouseoutEvent);
+ return hasEventListeners(EventTypeNames::mousemove) || hasEventListeners(EventTypeNames::mouseover) || hasEventListeners(EventTypeNames::mouseout);
}
bool Node::willRespondToMouseClickEvents()
{
if (isDisabledFormControl(this))
return false;
- return isContentEditable(UserSelectAllIsAlwaysNonEditable) || hasEventListeners(eventNames().mouseupEvent) || hasEventListeners(eventNames().mousedownEvent) || hasEventListeners(eventNames().clickEvent) || hasEventListeners(eventNames().DOMActivateEvent);
+ return isContentEditable(UserSelectAllIsAlwaysNonEditable) || hasEventListeners(EventTypeNames::mouseup) || hasEventListeners(EventTypeNames::mousedown) || hasEventListeners(EventTypeNames::click) || hasEventListeners(EventTypeNames::DOMActivate);
}
bool Node::willRespondToTouchEvents()
{
if (isDisabledFormControl(this))
return false;
- return hasEventListeners(eventNames().touchstartEvent) || hasEventListeners(eventNames().touchmoveEvent) || hasEventListeners(eventNames().touchcancelEvent) || hasEventListeners(eventNames().touchendEvent);
+ return hasEventListeners(EventTypeNames::touchstart) || hasEventListeners(EventTypeNames::touchmove) || hasEventListeners(EventTypeNames::touchcancel) || hasEventListeners(EventTypeNames::touchend);
}
// This is here for inlining
inline void TreeScope::removedLastRefToScope()
{
- ASSERT(!deletionHasBegun());
+ ASSERT_WITH_SECURITY_IMPLICATION(!deletionHasBegun());
if (m_guardRefCount) {
// If removing a child removes the last self-only ref, we don't
// want the scope to be destructed until after
@@ -2459,14 +2553,16 @@ inline void TreeScope::removedLastRefToScope()
// extra self-only ref.
guardRef();
dispose();
-#ifndef NDEBUG
+#if !ASSERT_DISABLED
// We need to do this right now since guardDeref() can delete this.
rootNode()->m_inRemovedLastRefFunction = false;
#endif
guardDeref();
} else {
-#ifndef NDEBUG
+#if !ASSERT_DISABLED
rootNode()->m_inRemovedLastRefFunction = false;
+#endif
+#if SECURITY_ASSERT_ENABLED
beginDeletion();
#endif
delete this;
@@ -2485,19 +2581,12 @@ void Node::removedLastRef()
return;
}
-#ifndef NDEBUG
+#if SECURITY_ASSERT_ENABLED
m_deletionHasBegun = true;
#endif
delete this;
}
-void Node::textRects(Vector<IntRect>& rects) const
-{
- RefPtr<Range> range = Range::create(document());
- range->selectNodeContents(const_cast<Node*>(this), IGNORE_EXCEPTION);
- range->textRects(rects);
-}
-
unsigned Node::connectedSubframeCount() const
{
return hasRareData() ? rareData()->connectedSubframeCount() : 0;
@@ -2506,7 +2595,7 @@ unsigned Node::connectedSubframeCount() const
void Node::incrementConnectedSubframeCount(unsigned amount)
{
ASSERT(isContainerNode());
- ensureRareData()->incrementConnectedSubframeCount(amount);
+ ensureRareData().incrementConnectedSubframeCount(amount);
}
void Node::decrementConnectedSubframeCount(unsigned amount)
@@ -2540,7 +2629,7 @@ PassRefPtr<NodeList> Node::getDestinationInsertionPoints()
{
document().updateDistributionForNodeIfNeeded(this);
Vector<InsertionPoint*, 8> insertionPoints;
- collectInsertionPointsWhereNodeIsDistributed(this, insertionPoints);
+ collectDestinationInsertionPoints(*this, insertionPoints);
Vector<RefPtr<Node> > filteredInsertionPoints;
for (size_t i = 0; i < insertionPoints.size(); ++i) {
InsertionPoint* insertionPoint = insertionPoints[i];
@@ -2578,7 +2667,7 @@ void Node::setFocus(bool flag)
document().userActionElements().setFocused(this, flag);
}
-void Node::setActive(bool flag, bool)
+void Node::setActive(bool flag)
{
document().userActionElements().setActive(this, flag);
}
@@ -2621,22 +2710,18 @@ void Node::setCustomElementState(CustomElementState newState)
ASSERT_NOT_REACHED(); // Everything starts in this state
return;
- case WaitingForParser:
- ASSERT(NotCustomElement == oldState);
- break;
-
case WaitingForUpgrade:
- ASSERT(NotCustomElement == oldState || WaitingForParser == oldState);
+ ASSERT(NotCustomElement == oldState);
break;
case Upgraded:
- ASSERT(WaitingForParser == oldState || WaitingForUpgrade == oldState);
+ ASSERT(WaitingForUpgrade == oldState);
break;
}
ASSERT(isHTMLElement() || isSVGElement());
- setFlag(newState & 1, CustomElementWaitingForParserOrIsUpgraded);
- setFlag(newState & 2, CustomElementWaitingForUpgradeOrIsUpgraded);
+ setFlag(CustomElement);
+ setFlag(newState == Upgraded, CustomElementUpgraded);
if (oldState == NotCustomElement || newState == Upgraded)
setNeedsStyleRecalc(); // :unresolved has changed
diff --git a/chromium/third_party/WebKit/Source/core/dom/Node.h b/chromium/third_party/WebKit/Source/core/dom/Node.h
index 58738dcc8f2..36235187f71 100644
--- a/chromium/third_party/WebKit/Source/core/dom/Node.h
+++ b/chromium/third_party/WebKit/Source/core/dom/Node.h
@@ -27,16 +27,16 @@
#include "bindings/v8/ExceptionStatePlaceholder.h"
#include "bindings/v8/ScriptWrappable.h"
-#include "core/dom/EventTarget.h"
#include "core/dom/MutationObserver.h"
#include "core/dom/SimulatedClickOptions.h"
#include "core/dom/TreeScope.h"
+#include "core/dom/TreeShared.h"
#include "core/editing/EditingBoundary.h"
+#include "core/events/EventTarget.h"
#include "core/inspector/InspectorCounters.h"
-#include "core/platform/TreeShared.h"
-#include "core/platform/graphics/LayoutRect.h"
#include "core/rendering/style/RenderStyleConstants.h"
-#include "weborigin/KURLHash.h"
+#include "platform/geometry/LayoutRect.h"
+#include "platform/weborigin/KURLHash.h"
#include "wtf/Forward.h"
#include "wtf/ListHashSet.h"
#include "wtf/text/AtomicString.h"
@@ -63,8 +63,8 @@ class HTMLInputElement;
class IntRect;
class KeyboardEvent;
class NSResolver;
-class NamedNodeMap;
class NameNodeList;
+class NamedNodeMap;
class NodeList;
class NodeListsNodeData;
class NodeRareData;
@@ -82,6 +82,7 @@ class RenderObject;
class RenderStyle;
class ShadowRoot;
class TagNodeList;
+class Text;
class TouchEvent;
const int nodeStyleChangeShift = 14;
@@ -90,7 +91,7 @@ enum StyleChangeType {
NoStyleChange = 0,
LocalStyleChange = 1 << nodeStyleChangeShift,
SubtreeStyleChange = 2 << nodeStyleChangeShift,
- LazyAttachStyleChange = 3 << nodeStyleChangeShift,
+ NeedsReattachStyleChange = 3 << nodeStyleChangeShift,
};
// If the style change is from the renderer then we'll call setStyle on the
@@ -119,6 +120,7 @@ class Node : public EventTarget, public ScriptWrappable, public TreeShared<Node>
friend class TreeScope;
friend class TreeScopeAdopter;
+ DEFINE_EVENT_TARGET_REFCOUNTING(TreeShared<Node>);
public:
enum NodeType {
ELEMENT_NODE = 1,
@@ -162,12 +164,10 @@ public:
static void dumpStatistics();
virtual ~Node();
- void willBeDeletedFrom(Document*);
// DOM methods & attributes for Node
bool hasTagName(const QualifiedName&) const;
- bool hasLocalName(const AtomicString&) const;
virtual String nodeName() const = 0;
virtual String nodeValue() const;
virtual void setNodeValue(const String&);
@@ -179,8 +179,6 @@ public:
PassRefPtr<NodeList> childNodes();
Node* firstChild() const;
Node* lastChild() const;
- bool hasAttributes() const;
- NamedNodeMap* attributes() const;
// ChildNode interface API
Element* previousElementSibling() const;
@@ -195,15 +193,14 @@ public:
virtual KURL baseURI() const;
// These should all actually return a node, but this is only important for language bindings,
- // which will already know and hold a ref on the right node to return. Returning bool allows
- // these methods to be more efficient since they don't need to return a ref
+ // which will already know and hold a ref on the right node to return.
void insertBefore(PassRefPtr<Node> newChild, Node* refChild, ExceptionState& = ASSERT_NO_EXCEPTION);
void replaceChild(PassRefPtr<Node> newChild, Node* oldChild, ExceptionState& = ASSERT_NO_EXCEPTION);
void removeChild(Node* child, ExceptionState&);
void appendChild(PassRefPtr<Node> newChild, ExceptionState& = ASSERT_NO_EXCEPTION);
bool hasChildNodes() const { return firstChild(); }
- virtual PassRefPtr<Node> cloneNode(bool deep = true) = 0;
+ virtual PassRefPtr<Node> cloneNode(bool deep = false) = 0;
virtual const AtomicString& localName() const;
virtual const AtomicString& namespaceURI() const;
virtual const AtomicString& prefix() const;
@@ -213,15 +210,14 @@ public:
bool isSameNode(Node* other) const { return this == other; }
bool isEqualNode(Node*) const;
bool isDefaultNamespace(const AtomicString& namespaceURI) const;
- String lookupPrefix(const AtomicString& namespaceURI) const;
- String lookupNamespaceURI(const String& prefix) const;
- String lookupNamespacePrefix(const AtomicString& namespaceURI, const Element* originalElement) const;
+ const AtomicString& lookupPrefix(const AtomicString& namespaceURI) const;
+ const AtomicString& lookupNamespaceURI(const String& prefix) const;
+ const AtomicString& lookupNamespacePrefix(const AtomicString& namespaceURI, const Element* originalElement) const;
String textContent(bool convertBRsToNewlines = false) const;
- void setTextContent(const String&, ExceptionState&);
+ void setTextContent(const String&);
- Node* lastDescendant() const;
- Node* firstDescendant() const;
+ Node& lastDescendant() const;
// Other methods (not part of DOM)
@@ -236,19 +232,23 @@ public:
bool isAfterPseudoElement() const { return pseudoId() == AFTER; }
PseudoId pseudoId() const { return (isElementNode() && hasCustomStyleCallbacks()) ? customPseudoId() : NOPSEUDO; }
+ bool isCustomElement() const { return getFlag(CustomElement); }
enum CustomElementState {
- NotCustomElement,
- WaitingForParser,
- WaitingForUpgrade,
- Upgraded
+ NotCustomElement = 0,
+ WaitingForUpgrade = 1 << 0,
+ Upgraded = 1 << 1
};
- bool isCustomElement() const { return customElementState() != NotCustomElement; }
- CustomElementState customElementState() const { return CustomElementState((getFlag(CustomElementWaitingForParserOrIsUpgraded) ? 1 : 0) | (getFlag(CustomElementWaitingForUpgradeOrIsUpgraded) ? 2 : 0)); }
+ CustomElementState customElementState() const
+ {
+ return isCustomElement()
+ ? (getFlag(CustomElementUpgraded) ? Upgraded : WaitingForUpgrade)
+ : NotCustomElement;
+ }
void setCustomElementState(CustomElementState newState);
virtual bool isMediaControlElement() const { return false; }
virtual bool isMediaControls() const { return false; }
- virtual bool isWebVTTElement() const { return false; }
+ virtual bool isVTTElement() const { return false; }
virtual bool isAttributeNode() const { return false; }
virtual bool isCharacterDataNode() const { return false; }
virtual bool isFrameOwnerElement() const { return false; }
@@ -259,7 +259,7 @@ public:
// if this element can participate in style sharing.
//
// FIXME: The only things that ever go through StyleResolver that aren't StyledElements are
- // PseudoElements and WebVTTElements. It's possible we can just eliminate all the checks
+ // PseudoElements and VTTElements. It's possible we can just eliminate all the checks
// since those elements will never have class names, inline style, or other things that
// this apparently guards against.
bool isStyledElement() const { return isHTMLElement() || isSVGElement(); }
@@ -295,8 +295,9 @@ public:
void setParentOrShadowHostNode(ContainerNode*);
Node* highestAncestor() const;
- // Use when it's guaranteed to that shadowHost is 0.
- ContainerNode* parentNodeGuaranteedHostFree() const;
+ // Knows about all kinds of hosts.
+ ContainerNode* parentOrShadowHostOrTemplateHostNode() const;
+
// Returns the parent node, but 0 if the parent node is a ShadowRoot.
ContainerNode* nonShadowBoundaryParentNode() const;
@@ -365,8 +366,7 @@ public:
bool hovered() const { return isUserActionElement() && isUserActionElementHovered(); }
bool focused() const { return isUserActionElement() && isUserActionElementFocused(); }
- bool attached() const { return getFlag(IsAttachedFlag); }
- void setAttached() { setFlag(IsAttachedFlag); }
+ bool needsAttach() const { return styleChangeType() == NeedsReattachStyleChange; }
bool needsStyleRecalc() const { return styleChangeType() != NoStyleChange; }
StyleChangeType styleChangeType() const { return static_cast<StyleChangeType>(m_nodeFlags & StyleChangeMask); }
bool childNeedsStyleRecalc() const { return getFlag(ChildNeedsStyleRecalcFlag); }
@@ -378,11 +378,7 @@ public:
void clearChildNeedsStyleRecalc() { clearFlag(ChildNeedsStyleRecalcFlag); }
void setNeedsStyleRecalc(StyleChangeType = SubtreeStyleChange, StyleChangeSource = StyleChangeFromCSS);
- void clearNeedsStyleRecalc()
- {
- m_nodeFlags &= ~StyleChangeMask;
- clearFlag(NotifyRendererWithIdenticalStyles);
- }
+ void clearNeedsStyleRecalc();
bool childNeedsDistributionRecalc() const { return getFlag(ChildNeedsDistributionRecalc); }
void setChildNeedsDistributionRecalc() { setFlag(ChildNeedsDistributionRecalc); }
@@ -407,11 +403,8 @@ public:
bool isV8CollectableDuringMinorGC() const { return getFlag(V8CollectableDuringMinorGCFlag); }
void setV8CollectableDuringMinorGC(bool flag) { setFlag(flag, V8CollectableDuringMinorGCFlag); }
- void lazyAttach();
- void lazyReattach();
-
virtual void setFocus(bool flag);
- virtual void setActive(bool flag = true, bool pause = false);
+ virtual void setActive(bool flag = true);
virtual void setHovered(bool flag = true);
virtual short tabIndex() const;
@@ -458,8 +451,6 @@ public:
virtual bool shouldUseInputMethod();
virtual LayoutRect boundingBox() const;
IntRect pixelSnappedBoundingBox() const { return pixelSnappedIntRect(boundingBox()); }
- LayoutRect renderRect(bool* isReplaced);
- IntRect pixelSnappedRenderRect(bool* isReplaced) { return pixelSnappedIntRect(renderRect(isReplaced)); }
// Returns true if the node has a non-empty bounding box in layout.
// This does not 100% guarantee the user can see it, but is pretty close.
@@ -480,7 +471,13 @@ public:
return *documentInternal();
}
- TreeScope& treeScope() const { return *m_treeScope; }
+ TreeScope& treeScope() const
+ {
+ ASSERT(m_treeScope);
+ return *m_treeScope;
+ }
+
+ bool inActiveDocument() const;
// Returns true if this node is associated with a document and is in its associated document's
// node tree, false otherwise.
@@ -501,7 +498,8 @@ public:
bool isDescendantOf(const Node*) const;
bool contains(const Node*) const;
bool containsIncludingShadowDOM(const Node*) const;
- bool containsIncludingHostElements(const Node*) const;
+ bool containsIncludingHostElements(const Node&) const;
+ Node* commonAncestor(const Node&, Node* (*parent)(const Node&));
// FIXME: Remove this when crbug.com/265716 cleans up contains semantics.
bool bindingsContains(const Node* node) const { return containsIncludingShadowDOM(node); }
@@ -523,6 +521,7 @@ public:
// Integration with rendering tree
// As renderer() includes a branch you should avoid calling it repeatedly in hot code paths.
+ // Note that if a Node has a renderer, it's parentNode is guaranteed to have one as well.
RenderObject* renderer() const { return hasRareData() ? m_data.m_rareData->renderer() : m_data.m_renderer; };
void setRenderer(RenderObject* renderer)
{
@@ -531,6 +530,7 @@ public:
else
m_data.m_renderer = renderer;
}
+ bool hasRenderer() const { return renderer(); }
// Use these two methods with caution.
RenderBox* renderBox() const;
@@ -636,8 +636,8 @@ public:
virtual Node* toNode();
- virtual const AtomicString& interfaceName() const;
- virtual ScriptExecutionContext* scriptExecutionContext() const;
+ virtual const AtomicString& interfaceName() const OVERRIDE;
+ virtual ExecutionContext* executionContext() const OVERRIDE;
virtual bool addEventListener(const AtomicString& eventType, PassRefPtr<EventListener>, bool useCapture);
virtual bool removeEventListener(const AtomicString& eventType, EventListener*, bool useCapture);
@@ -664,7 +664,7 @@ public:
bool dispatchGestureEvent(const PlatformGestureEvent&);
bool dispatchTouchEvent(PassRefPtr<TouchEvent>);
- void dispatchSimulatedClick(Event* underlyingEvent, SimulatedClickMouseEventOptions = SendNoEvents, SimulatedClickVisualOptions = ShowPressedLook);
+ void dispatchSimulatedClick(Event* underlyingEvent, SimulatedClickMouseEventOptions = SendNoEvents);
virtual bool dispatchBeforeLoadEvent(const String& sourceURL);
virtual void dispatchChangeEvent();
@@ -674,11 +674,8 @@ public:
virtual void defaultEventHandler(Event*);
virtual void willCallDefaultEventHandler(const Event&);
- using TreeShared<Node>::ref;
- using TreeShared<Node>::deref;
-
- virtual EventTargetData* eventTargetData();
- virtual EventTargetData* ensureEventTargetData();
+ virtual EventTargetData* eventTargetData() OVERRIDE;
+ virtual EventTargetData& ensureEventTargetData() OVERRIDE;
void getRegisteredMutationObserversOfType(HashMap<MutationObserver*, MutationRecordDeliveryOptions>&, MutationObserver::MutationType, const QualifiedName* attributeName);
void registerMutationObserver(MutationObserver*, MutationObserverOptions, const HashSet<AtomicString>& attributeFilter);
@@ -691,8 +688,6 @@ public:
virtual void unregisterScopedHTMLStyleChild();
size_t numberOfScopedHTMLStyleChildren() const;
- void textRects(Vector<IntRect>&) const;
-
unsigned connectedSubframeCount() const;
void incrementConnectedSubframeCount(unsigned amount = 1);
void decrementConnectedSubframeCount(unsigned amount = 1);
@@ -711,7 +706,8 @@ private:
IsElementFlag = 1 << 2,
IsHTMLFlag = 1 << 3,
IsSVGFlag = 1 << 4,
- IsAttachedFlag = 1 << 5,
+
+ ChildNeedsDistributionRecalc = 1 << 5,
ChildNeedsStyleRecalcFlag = 1 << 6,
InDocumentFlag = 1 << 7,
IsLinkFlag = 1 << 8,
@@ -741,16 +737,15 @@ private:
NotifyRendererWithIdenticalStyles = 1 << 26,
- CustomElementWaitingForParserOrIsUpgraded = 1 << 27,
- CustomElementWaitingForUpgradeOrIsUpgraded = 1 << 28,
+ CustomElement = 1 << 27,
+ CustomElementUpgraded = 1 << 28,
- ChildNeedsDistributionRecalc = 1 << 29,
- AlreadySpellCheckedFlag = 1 << 30,
+ AlreadySpellCheckedFlag = 1 << 29,
- DefaultNodeFlags = IsParsingChildrenFinishedFlag
+ DefaultNodeFlags = IsParsingChildrenFinishedFlag | ChildNeedsStyleRecalcFlag | NeedsReattachStyleChange
};
- // 2 bits remaining
+ // 3 bits remaining.
bool getFlag(NodeFlags mask) const { return m_nodeFlags & mask; }
void setFlag(bool f, NodeFlags mask) const { m_nodeFlags = (m_nodeFlags & ~mask) | (-(int32_t)f & mask); }
@@ -763,7 +758,6 @@ protected:
CreateText = DefaultNodeFlags | IsTextFlag,
CreateContainer = DefaultNodeFlags | IsContainerFlag,
CreateElement = CreateContainer | IsElementFlag,
- CreatePseudoElement = CreateElement | InDocumentFlag,
CreateShadowRoot = CreateContainer | IsDocumentFragmentFlag | IsInShadowTreeFlag,
CreateDocumentFragment = CreateContainer | IsDocumentFragmentFlag,
CreateHTMLElement = CreateElement | IsHTMLFlag,
@@ -780,10 +774,10 @@ protected:
, m_previous(0)
, m_next(0)
{
+ ASSERT(m_treeScope || type == CreateDocument || type == CreateShadowRoot);
ScriptWrappable::init(this);
- if (!m_treeScope)
- m_treeScope = TreeScope::noDocumentInstance();
- m_treeScope->guardRef();
+ if (m_treeScope)
+ m_treeScope->guardRef();
#if !defined(NDEBUG) || (defined(DUMP_NODE_STATISTICS) && DUMP_NODE_STATISTICS)
trackForDebugging();
@@ -791,14 +785,18 @@ protected:
InspectorCounters::incrementCounter(InspectorCounters::NodeCounter);
}
- virtual void didMoveToNewDocument(Document* oldDocument);
+ virtual void didMoveToNewDocument(Document& oldDocument);
virtual void addSubresourceAttributeURLs(ListHashSet<KURL>&) const { }
+ static void reattachWhitespaceSiblings(Text* start);
+
+ void willBeDeletedFromDocument();
+
bool hasRareData() const { return getFlag(HasRareDataFlag); }
NodeRareData* rareData() const;
- NodeRareData* ensureRareData();
+ NodeRareData& ensureRareData();
void clearRareData();
void clearEventTargetData();
@@ -808,6 +806,13 @@ protected:
Document* documentInternal() const { return treeScope().documentScope(); }
void setTreeScope(TreeScope* scope) { m_treeScope = scope; }
+ // isTreeScopeInitialized() can be false
+ // - in the destruction of Document or ShadowRoot where m_treeScope is set to null or
+ // - in the Node constructor called by these two classes where m_treeScope is set by TreeScope ctor.
+ bool isTreeScopeInitialized() const { return m_treeScope; }
+
+ void markAncestorsWithChildNeedsStyleRecalc();
+
private:
friend class TreeShared<Node>;
@@ -829,17 +834,10 @@ private:
bool isUserActionElementHovered() const;
bool isUserActionElementFocused() const;
+ void traceStyleChange(StyleChangeType);
+ void traceStyleChangeIfNeeded(StyleChangeType);
void setStyleChange(StyleChangeType);
- void detachNode(Node*, const AttachContext&);
- void clearAttached() { clearFlag(IsAttachedFlag); }
-
- // Used to share code between lazyAttach and setNeedsStyleRecalc.
- void markAncestorsWithChildNeedsStyleRecalc();
-
- virtual void refEventTarget();
- virtual void derefEventTarget();
-
virtual RenderStyle* nonRendererStyle() const { return 0; }
virtual RenderStyle* virtualComputedStyle(PseudoId = NOPSEUDO);
@@ -897,29 +895,18 @@ inline ContainerNode* Node::parentNode() const
return isShadowRoot() ? 0 : parentOrShadowHostNode();
}
-inline ContainerNode* Node::parentNodeGuaranteedHostFree() const
-{
- ASSERT(!isShadowRoot());
- return parentOrShadowHostNode();
-}
-
inline void Node::lazyReattachIfAttached()
{
- if (attached())
- lazyReattach();
-}
-
-inline void Node::lazyReattach()
-{
- if (styleChangeType() == LazyAttachStyleChange)
+ if (styleChangeType() == NeedsReattachStyleChange)
+ return;
+ if (!inActiveDocument())
return;
AttachContext context;
context.performingReattach = true;
- if (attached())
- detach(context);
- lazyAttach();
+ detach(context);
+ markAncestorsWithChildNeedsStyleRecalc();
}
inline bool shouldRecalcStyle(StyleRecalcChange change, const Node* node)
@@ -927,7 +914,39 @@ inline bool shouldRecalcStyle(StyleRecalcChange change, const Node* node)
return change >= Inherit || node->childNeedsStyleRecalc() || node->needsStyleRecalc();
}
-} //namespace
+inline bool isTreeScopeRoot(const Node* node)
+{
+ return !node || node->isDocumentNode() || node->isShadowRoot();
+}
+
+inline bool isTreeScopeRoot(const Node& node)
+{
+ return node.isDocumentNode() || node.isShadowRoot();
+}
+
+// Allow equality comparisons of Nodes by reference or pointer, interchangeably.
+inline bool operator==(const Node& a, const Node& b) { return &a == &b; }
+inline bool operator==(const Node& a, const Node* b) { return &a == b; }
+inline bool operator==(const Node* a, const Node& b) { return a == &b; }
+inline bool operator!=(const Node& a, const Node& b) { return !(a == b); }
+inline bool operator!=(const Node& a, const Node* b) { return !(a == b); }
+inline bool operator!=(const Node* a, const Node& b) { return !(a == b); }
+inline bool operator==(const PassRefPtr<Node>& a, const Node& b) { return a.get() == &b; }
+inline bool operator==(const Node& a, const PassRefPtr<Node>& b) { return &a == b.get(); }
+inline bool operator!=(const PassRefPtr<Node>& a, const Node& b) { return !(a == b); }
+inline bool operator!=(const Node& a, const PassRefPtr<Node>& b) { return !(a == b); }
+
+
+#define DEFINE_NODE_TYPE_CASTS(thisType, predicate) \
+ template<typename T> inline thisType* to##thisType(const RefPtr<T>& node) { return to##thisType(node.get()); } \
+ DEFINE_TYPE_CASTS(thisType, Node, node, node->predicate, node.predicate)
+
+// This requires isClassName(const Node&).
+#define DEFINE_NODE_TYPE_CASTS_WITH_FUNCTION(thisType) \
+ template<typename T> inline thisType* to##thisType(const RefPtr<T>& node) { return to##thisType(node.get()); } \
+ DEFINE_TYPE_CASTS(thisType, Node, node, is##thisType(*node), is##thisType(node))
+
+} // namespace WebCore
#ifndef NDEBUG
// Outside the WebCore namespace for ease of invocation from gdb.
diff --git a/chromium/third_party/WebKit/Source/core/dom/Node.idl b/chromium/third_party/WebKit/Source/core/dom/Node.idl
index 3d774a2bade..c67bbebddf5 100644
--- a/chromium/third_party/WebKit/Source/core/dom/Node.idl
+++ b/chromium/third_party/WebKit/Source/core/dom/Node.idl
@@ -19,8 +19,8 @@
*/
[
- CustomToV8,
- DependentLifetime
+ Custom=Wrap,
+ DependentLifetime,
] interface Node : EventTarget {
// NodeType
const unsigned short ELEMENT_NODE = 1;
@@ -36,10 +36,9 @@
const unsigned short DOCUMENT_FRAGMENT_NODE = 11;
const unsigned short NOTATION_NODE = 12;
- [TreatReturnedNullStringAs=Null, PerWorldBindings] readonly attribute DOMString nodeName;
+ [PerWorldBindings] readonly attribute DOMString nodeName;
- // FIXME: the spec says this can also raise on retrieval.
- [TreatReturnedNullStringAs=Null, TreatNullAs=NullString, PerWorldBindings, CustomElementCallbacks=Enable] attribute DOMString nodeValue;
+ [TreatReturnedNullStringAs=Null, TreatNullAs=NullString, PerWorldBindings, CustomElementCallbacks] attribute DOMString nodeValue;
[PerWorldBindings] readonly attribute unsigned short nodeType;
[PerWorldBindings] readonly attribute Node parentNode;
@@ -50,35 +49,34 @@
[PerWorldBindings] readonly attribute Node nextSibling;
[PerWorldBindings] readonly attribute Document ownerDocument;
- [Custom, PerWorldBindings, ActivityLog=AccessForIsolatedWorlds, RaisesException] Node insertBefore(Node newChild, Node refChild);
- [Custom, PerWorldBindings, ActivityLog=AccessForIsolatedWorlds, RaisesException] Node replaceChild(Node newChild, Node oldChild);
- [Custom, PerWorldBindings, RaisesException] Node removeChild(Node oldChild);
- [Custom, PerWorldBindings, ActivityLog=AccessForIsolatedWorlds, RaisesException] Node appendChild(Node newChild);
+ [Custom, CustomElementCallbacks, PerWorldBindings, ActivityLogging=ForIsolatedWorlds, RaisesException] Node insertBefore(Node newChild, Node refChild);
+ [Custom, CustomElementCallbacks, PerWorldBindings, ActivityLogging=ForIsolatedWorlds, RaisesException] Node replaceChild(Node newChild, Node oldChild);
+ [Custom, CustomElementCallbacks, PerWorldBindings, RaisesException] Node removeChild(Node oldChild);
+ [Custom, CustomElementCallbacks, PerWorldBindings, ActivityLogging=ForIsolatedWorlds, RaisesException] Node appendChild(Node newChild);
boolean hasChildNodes();
- [CustomElementCallbacks=Enable, PerWorldBindings]
+ [CustomElementCallbacks, PerWorldBindings]
Node cloneNode(optional boolean deep);
- [CustomElementCallbacks=Enable] void normalize();
+ [CustomElementCallbacks] void normalize();
// Introduced in DOM Level 2:
[MeasureAs=NodeIsSupported] boolean isSupported([Default=Undefined] optional DOMString feature,
[TreatNullAs=NullString,Default=Undefined] optional DOMString version); // Removed in DOM4.
[TreatReturnedNullStringAs=Null, PerWorldBindings, MeasureAs=NodeNamespaceURI] readonly attribute DOMString namespaceURI; // Moved to Element and Attr in DOM4.
- [TreatReturnedNullStringAs=Null, TreatNullAs=NullString, PerWorldBindings, SetterRaisesException, MeasureAs=NodePrefix] attribute DOMString prefix; // Moved to Element and Attr in DOM4.
+ [TreatReturnedNullStringAs=Null, TreatNullAs=NullString, PerWorldBindings, RaisesException=Setter, MeasureAs=NodePrefix] attribute DOMString prefix; // Moved to Element and Attr in DOM4.
[TreatReturnedNullStringAs=Null, PerWorldBindings, MeasureAs=NodeLocalName] readonly attribute DOMString localName; // Moved to Element and Attr in DOM4.
// Introduced in DOM Level 3:
- [TreatReturnedNullStringAs=Null, PerWorldBindings] readonly attribute DOMString baseURI;
+ [TreatReturnedNullStringAs=Null, PerWorldBindings] readonly attribute DOMString baseURI;
- // FIXME: the spec says this can also raise on retrieval.
- [TreatReturnedNullStringAs=Null, TreatNullAs=NullString, PerWorldBindings, SetterRaisesException, CustomElementCallbacks=Enable] attribute DOMString textContent;
+ [TreatReturnedNullStringAs=Null, TreatNullAs=NullString, PerWorldBindings, CustomElementCallbacks] attribute DOMString textContent;
[MeasureAs=NodeIsSameNode] boolean isSameNode([Default=Undefined] optional Node other); // Removed in DOM4.
- boolean isEqualNode([Default=Undefined] optional Node other);
- [TreatReturnedNullStringAs=Null] DOMString lookupPrefix([TreatNullAs=NullString,Default=Undefined] optional DOMString namespaceURI);
- boolean isDefaultNamespace([TreatNullAs=NullString,Default=Undefined] optional DOMString namespaceURI);
- [TreatReturnedNullStringAs=Null] DOMString lookupNamespaceURI([TreatNullAs=NullString,Default=Undefined] optional DOMString prefix);
+ boolean isEqualNode(Node other);
+ [TreatReturnedNullStringAs=Null] DOMString lookupPrefix([TreatNullAs=NullString] DOMString namespaceURI);
+ boolean isDefaultNamespace([TreatNullAs=NullString] DOMString namespaceURI);
+ [TreatReturnedNullStringAs=Null] DOMString lookupNamespaceURI([TreatNullAs=NullString] DOMString prefix);
// DocumentPosition
const unsigned short DOCUMENT_POSITION_DISCONNECTED = 0x01;
@@ -88,11 +86,11 @@
const unsigned short DOCUMENT_POSITION_CONTAINED_BY = 0x10;
const unsigned short DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC = 0x20;
- unsigned short compareDocumentPosition([Default=Undefined] optional Node other);
+ unsigned short compareDocumentPosition(Node other);
// Introduced in DOM4
- [ImplementedAs=bindingsContains] boolean contains([Default=Undefined] optional Node other);
+ [ImplementedAs=bindingsContains] boolean contains(Node other);
// IE extensions
- [PerWorldBindings] readonly attribute Element parentElement;
+ [PerWorldBindings] readonly attribute Element parentElement;
};
diff --git a/chromium/third_party/WebKit/Source/core/dom/NodeChildRemovalTracker.h b/chromium/third_party/WebKit/Source/core/dom/NodeChildRemovalTracker.h
index b4faa116e4a..09fa82933ee 100644
--- a/chromium/third_party/WebKit/Source/core/dom/NodeChildRemovalTracker.h
+++ b/chromium/third_party/WebKit/Source/core/dom/NodeChildRemovalTracker.h
@@ -33,21 +33,21 @@ namespace WebCore {
class NodeChildRemovalTracker {
public:
- explicit NodeChildRemovalTracker(Node*);
+ explicit NodeChildRemovalTracker(Node&);
~NodeChildRemovalTracker();
static bool isBeingRemoved(Node*);
private:
- Node* node() const { return m_node; }
+ Node& node() const { return m_node; }
NodeChildRemovalTracker* previous() { return m_previous; }
- Node* m_node;
+ Node& m_node;
NodeChildRemovalTracker* m_previous;
static NodeChildRemovalTracker* s_last;
};
-inline NodeChildRemovalTracker::NodeChildRemovalTracker(Node* node)
+inline NodeChildRemovalTracker::NodeChildRemovalTracker(Node& node)
: m_node(node)
, m_previous(s_last)
{
@@ -62,7 +62,7 @@ inline NodeChildRemovalTracker::~NodeChildRemovalTracker()
inline bool NodeChildRemovalTracker::isBeingRemoved(Node* node)
{
for (NodeChildRemovalTracker* removal = s_last; removal; removal = removal->previous()) {
- if (removal->node()->containsIncludingShadowDOM(node))
+ if (removal->node().containsIncludingShadowDOM(node))
return true;
}
diff --git a/chromium/third_party/WebKit/Source/core/dom/NodeFilter.idl b/chromium/third_party/WebKit/Source/core/dom/NodeFilter.idl
index 989099fc9aa..58ac22e9407 100644
--- a/chromium/third_party/WebKit/Source/core/dom/NodeFilter.idl
+++ b/chromium/third_party/WebKit/Source/core/dom/NodeFilter.idl
@@ -19,6 +19,7 @@
*/
[
+ DependentLifetime
] interface NodeFilter {
// Constants returned by acceptNode
const short FILTER_ACCEPT = 1;
diff --git a/chromium/third_party/WebKit/Source/core/dom/NodeIterator.cpp b/chromium/third_party/WebKit/Source/core/dom/NodeIterator.cpp
index f2cb1e7738a..35c912fe65a 100644
--- a/chromium/third_party/WebKit/Source/core/dom/NodeIterator.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/NodeIterator.cpp
@@ -25,12 +25,10 @@
#include "config.h"
#include "core/dom/NodeIterator.h"
-#include "bindings/v8/ExceptionMessages.h"
#include "bindings/v8/ExceptionState.h"
#include "bindings/v8/ScriptState.h"
#include "core/dom/Document.h"
#include "core/dom/ExceptionCode.h"
-#include "core/dom/NodeFilter.h"
#include "core/dom/NodeTraversal.h"
namespace WebCore {
@@ -58,7 +56,7 @@ bool NodeIterator::NodePointer::moveToNext(Node* root)
isPointerBeforeNode = false;
return true;
}
- node = NodeTraversal::next(node.get(), root);
+ node = NodeTraversal::next(*node, root);
return node;
}
@@ -70,7 +68,7 @@ bool NodeIterator::NodePointer::moveToPrevious(Node* root)
isPointerBeforeNode = true;
return true;
}
- node = NodeTraversal::previous(node.get(), root);
+ node = NodeTraversal::previous(*node, root);
return node;
}
@@ -88,10 +86,10 @@ NodeIterator::~NodeIterator()
root()->document().detachNodeIterator(this);
}
-PassRefPtr<Node> NodeIterator::nextNode(ScriptState* state, ExceptionState& es)
+PassRefPtr<Node> NodeIterator::nextNode(ScriptState* state, ExceptionState& exceptionState)
{
if (m_detached) {
- es.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("nextNode", "NodeIterator", "The iterator is detached."));
+ exceptionState.throwDOMException(InvalidStateError, "The iterator is detached.");
return 0;
}
@@ -117,10 +115,10 @@ PassRefPtr<Node> NodeIterator::nextNode(ScriptState* state, ExceptionState& es)
return result.release();
}
-PassRefPtr<Node> NodeIterator::previousNode(ScriptState* state, ExceptionState& es)
+PassRefPtr<Node> NodeIterator::previousNode(ScriptState* state, ExceptionState& exceptionState)
{
if (m_detached) {
- es.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("previousNode", "NodeIterator", "The iterator is detached."));
+ exceptionState.throwDOMException(InvalidStateError, "The iterator is detached.");
return 0;
}
@@ -153,24 +151,23 @@ void NodeIterator::detach()
m_referenceNode.node.clear();
}
-void NodeIterator::nodeWillBeRemoved(Node* removedNode)
+void NodeIterator::nodeWillBeRemoved(Node& removedNode)
{
updateForNodeRemoval(removedNode, m_candidateNode);
updateForNodeRemoval(removedNode, m_referenceNode);
}
-void NodeIterator::updateForNodeRemoval(Node* removedNode, NodePointer& referenceNode) const
+void NodeIterator::updateForNodeRemoval(Node& removedNode, NodePointer& referenceNode) const
{
ASSERT(!m_detached);
- ASSERT(removedNode);
- ASSERT(&root()->document() == &removedNode->document());
+ ASSERT(root()->document() == removedNode.document());
// Iterator is not affected if the removed node is the reference node and is the root.
// or if removed node is not the reference node, or the ancestor of the reference node.
- if (!removedNode->isDescendantOf(root()))
+ if (!removedNode.isDescendantOf(root()))
return;
bool willRemoveReferenceNode = removedNode == referenceNode.node;
- bool willRemoveReferenceNodeAncestor = referenceNode.node && referenceNode.node->isDescendantOf(removedNode);
+ bool willRemoveReferenceNodeAncestor = referenceNode.node && referenceNode.node->isDescendantOf(&removedNode);
if (!willRemoveReferenceNode && !willRemoveReferenceNodeAncestor)
return;
@@ -179,8 +176,8 @@ void NodeIterator::updateForNodeRemoval(Node* removedNode, NodePointer& referenc
if (node) {
// Move out from under the node being removed if the new reference
// node is a descendant of the node being removed.
- while (node && node->isDescendantOf(removedNode))
- node = NodeTraversal::next(node, root());
+ while (node && node->isDescendantOf(&removedNode))
+ node = NodeTraversal::next(*node, root());
if (node)
referenceNode.node = node;
} else {
@@ -189,8 +186,8 @@ void NodeIterator::updateForNodeRemoval(Node* removedNode, NodePointer& referenc
// Move out from under the node being removed if the reference node is
// a descendant of the node being removed.
if (willRemoveReferenceNodeAncestor) {
- while (node && node->isDescendantOf(removedNode))
- node = NodeTraversal::previous(node, root());
+ while (node && node->isDescendantOf(&removedNode))
+ node = NodeTraversal::previous(*node, root());
}
if (node) {
// Removing last node.
@@ -207,8 +204,8 @@ void NodeIterator::updateForNodeRemoval(Node* removedNode, NodePointer& referenc
// Move out from under the node being removed if the reference node is
// a descendant of the node being removed.
if (willRemoveReferenceNodeAncestor) {
- while (node && node->isDescendantOf(removedNode))
- node = NodeTraversal::previous(node, root());
+ while (node && node->isDescendantOf(&removedNode))
+ node = NodeTraversal::previous(*node, root());
}
if (node)
referenceNode.node = node;
@@ -218,8 +215,8 @@ void NodeIterator::updateForNodeRemoval(Node* removedNode, NodePointer& referenc
// Move out from under the node being removed if the reference node is
// a descendant of the node being removed.
if (willRemoveReferenceNodeAncestor) {
- while (node && node->isDescendantOf(removedNode))
- node = NodeTraversal::previous(node, root());
+ while (node && node->isDescendantOf(&removedNode))
+ node = NodeTraversal::previous(*node, root());
}
if (node)
referenceNode.node = node;
diff --git a/chromium/third_party/WebKit/Source/core/dom/NodeIterator.h b/chromium/third_party/WebKit/Source/core/dom/NodeIterator.h
index 4c504bf75c2..1f06a57c3e4 100644
--- a/chromium/third_party/WebKit/Source/core/dom/NodeIterator.h
+++ b/chromium/third_party/WebKit/Source/core/dom/NodeIterator.h
@@ -51,7 +51,7 @@ public:
bool pointerBeforeReferenceNode() const { return m_referenceNode.isPointerBeforeNode; }
// This function is called before any node is removed from the document tree.
- void nodeWillBeRemoved(Node*);
+ void nodeWillBeRemoved(Node&);
private:
NodeIterator(PassRefPtr<Node>, unsigned whatToShow, PassRefPtr<NodeFilter>);
@@ -66,7 +66,7 @@ private:
bool moveToPrevious(Node* root);
};
- void updateForNodeRemoval(Node* nodeToBeRemoved, NodePointer&) const;
+ void updateForNodeRemoval(Node& nodeToBeRemoved, NodePointer&) const;
NodePointer m_referenceNode;
NodePointer m_candidateNode;
diff --git a/chromium/third_party/WebKit/Source/core/dom/NodeIterator.idl b/chromium/third_party/WebKit/Source/core/dom/NodeIterator.idl
index 5e52661f8d3..9c636c4bdd6 100644
--- a/chromium/third_party/WebKit/Source/core/dom/NodeIterator.idl
+++ b/chromium/third_party/WebKit/Source/core/dom/NodeIterator.idl
@@ -20,7 +20,7 @@
// Introduced in DOM Level 2:
[
- CustomToV8
+ SetReference(NodeFilter filter)
] interface NodeIterator {
readonly attribute Node root;
readonly attribute unsigned long whatToShow;
diff --git a/chromium/third_party/WebKit/Source/core/dom/NodeList.h b/chromium/third_party/WebKit/Source/core/dom/NodeList.h
index d6ddf179ec4..1d77043f3f8 100644
--- a/chromium/third_party/WebKit/Source/core/dom/NodeList.h
+++ b/chromium/third_party/WebKit/Source/core/dom/NodeList.h
@@ -30,27 +30,27 @@
namespace WebCore {
- class Node;
-
- class NodeList : public ScriptWrappable, public RefCounted<NodeList> {
- public:
- virtual ~NodeList() { }
-
- // DOM methods & attributes for NodeList
- virtual unsigned length() const = 0;
- virtual Node* item(unsigned index) const = 0;
- virtual Node* namedItem(const AtomicString&) const = 0;
-
- // Other methods (not part of DOM)
- virtual bool isLiveNodeList() const { return false; }
- void anonymousNamedGetter(const AtomicString&, bool&, RefPtr<Node>&, bool&, unsigned&);
-
- protected:
- NodeList()
- {
- ScriptWrappable::init(this);
- }
- };
+class Node;
+
+class NodeList : public ScriptWrappable, public RefCounted<NodeList> {
+public:
+ virtual ~NodeList() { }
+
+ // DOM methods & attributes for NodeList
+ virtual unsigned length() const = 0;
+ virtual Node* item(unsigned index) const = 0;
+ virtual Node* namedItem(const AtomicString&) const = 0;
+
+ // Other methods (not part of DOM)
+ virtual bool isLiveNodeList() const { return false; }
+ void anonymousNamedGetter(const AtomicString&, bool&, RefPtr<Node>&, bool&, unsigned&);
+
+protected:
+ NodeList()
+ {
+ ScriptWrappable::init(this);
+ }
+};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/NodeList.idl b/chromium/third_party/WebKit/Source/core/dom/NodeList.idl
index 794ba11888f..19ccec64c87 100644
--- a/chromium/third_party/WebKit/Source/core/dom/NodeList.idl
+++ b/chromium/third_party/WebKit/Source/core/dom/NodeList.idl
@@ -19,8 +19,8 @@
*/
[
- CustomIsReachable,
- DependentLifetime
+ Custom=VisitDOMWrapper,
+ DependentLifetime,
] interface NodeList {
getter Node item(unsigned long index);
diff --git a/chromium/third_party/WebKit/Source/core/dom/NodeRareData.h b/chromium/third_party/WebKit/Source/core/dom/NodeRareData.h
index 120a15b6a02..38dd440c6cb 100644
--- a/chromium/third_party/WebKit/Source/core/dom/NodeRareData.h
+++ b/chromium/third_party/WebKit/Source/core/dom/NodeRareData.h
@@ -60,7 +60,7 @@ public:
void removeChildNodeList(ChildNodeList* list)
{
- ASSERT(m_childNodeList = list);
+ ASSERT(m_childNodeList == list);
if (deleteThisAndUpdateNodeRareDataIfAboutToRemoveLastList(list->ownerNode()))
return;
m_childNodeList = 0;
@@ -249,19 +249,19 @@ public:
void clearNodeLists() { m_nodeLists.clear(); }
NodeListsNodeData* nodeLists() const { return m_nodeLists.get(); }
- NodeListsNodeData* ensureNodeLists()
+ NodeListsNodeData& ensureNodeLists()
{
if (!m_nodeLists)
m_nodeLists = NodeListsNodeData::create();
- return m_nodeLists.get();
+ return *m_nodeLists;
}
NodeMutationObserverData* mutationObserverData() { return m_mutationObserverData.get(); }
- NodeMutationObserverData* ensureMutationObserverData()
+ NodeMutationObserverData& ensureMutationObserverData()
{
if (!m_mutationObserverData)
m_mutationObserverData = NodeMutationObserverData::create();
- return m_mutationObserverData.get();
+ return *m_mutationObserverData;
}
unsigned connectedSubframeCount() const { return m_connectedFrameCount; }
diff --git a/chromium/third_party/WebKit/Source/core/dom/NodeRenderingContext.cpp b/chromium/third_party/WebKit/Source/core/dom/NodeRenderingContext.cpp
index 60d7d949244..2d2b4a4e08d 100644
--- a/chromium/third_party/WebKit/Source/core/dom/NodeRenderingContext.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/NodeRenderingContext.cpp
@@ -27,7 +27,6 @@
#include "core/dom/NodeRenderingContext.h"
#include "RuntimeEnabledFeatures.h"
-#include "core/animation/css/CSSAnimations.h"
#include "core/css/resolver/StyleResolver.h"
#include "core/dom/ContainerNode.h"
#include "core/dom/FullscreenElementStack.h"
@@ -83,9 +82,8 @@ RenderObject* NodeRenderingContext::nextRenderer() const
if (m_parentFlowRenderer)
return m_parentFlowRenderer->nextRendererForNode(m_node);
- // Avoid an O(N^2) problem with this function by not checking for
- // nextRenderer() when the parent element hasn't attached yet.
- if (m_renderingParent && !m_renderingParent->attached())
+ // Avoid an O(N^2) walk over the children when reattaching all children of a node.
+ if (m_renderingParent && m_renderingParent->needsAttach())
return 0;
for (Node* sibling = NodeRenderingTraversal::nextSibling(m_node); sibling; sibling = NodeRenderingTraversal::nextSibling(sibling)) {
@@ -164,7 +162,7 @@ bool NodeRenderingContext::elementInsideRegionNeedsRenderer()
Element* element = toElement(m_node);
bool elementInsideRegionNeedsRenderer = false;
RenderObject* parentRenderer = this->parentRenderer();
- if ((parentRenderer && !parentRenderer->canHaveChildren() && parentRenderer->isRenderRegion())
+ if ((parentRenderer && !parentRenderer->canHaveChildren() && parentRenderer->isRenderNamedFlowFragmentContainer())
|| (!parentRenderer && element->parentElement() && element->parentElement()->isInsideRegion())) {
if (!m_style)
@@ -207,11 +205,8 @@ void NodeRenderingContext::createRendererForElementIfNeeded()
if (!shouldCreateRenderer() && !elementInsideRegionNeedsRenderer())
return;
- // If m_style is already available, this scope shouldn't attempt to trigger animation updates.
- CSSAnimationUpdateScope cssAnimationUpdateScope(m_style ? 0 : element);
if (!m_style)
m_style = element->styleForRenderer();
- ASSERT(m_style);
moveToFlowThreadIfNeeded();
@@ -259,7 +254,7 @@ void NodeRenderingContext::createRendererForTextIfNeeded()
RenderObject* parentRenderer = this->parentRenderer();
if (m_parentDetails.resetStyleInheritance())
- m_style = textNode->document().styleResolver()->defaultStyleForElement();
+ m_style = textNode->document().ensureStyleResolver().defaultStyleForElement();
else
m_style = parentRenderer->style();
diff --git a/chromium/third_party/WebKit/Source/core/dom/NodeRenderingTraversal.cpp b/chromium/third_party/WebKit/Source/core/dom/NodeRenderingTraversal.cpp
index 7353a13d10a..b30c66aba53 100644
--- a/chromium/third_party/WebKit/Source/core/dom/NodeRenderingTraversal.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/NodeRenderingTraversal.cpp
@@ -34,7 +34,7 @@ namespace WebCore {
namespace NodeRenderingTraversal {
-void ParentDetails::didTraverseInsertionPoint(InsertionPoint* insertionPoint)
+void ParentDetails::didTraverseInsertionPoint(const InsertionPoint* insertionPoint)
{
if (!m_insertionPoint) {
m_insertionPoint = insertionPoint;
@@ -49,10 +49,14 @@ void ParentDetails::didTraverseShadowRoot(const ShadowRoot* root)
ContainerNode* parent(const Node* node, ParentDetails* details)
{
- // FIXME: Once everything lazy attaches we should assert that we don't need a distribution recalc here.
+ // FIXME: We should probably ASSERT(!node->document().childNeedsDistributionRecalc()) here, but
+ // a bunch of things use NodeRenderingTraversal::parent in places where that looks like it could
+ // be false.
+ ASSERT(node);
+ if (isActiveInsertionPoint(*node))
+ return 0;
ComposedTreeWalker walker(node, ComposedTreeWalker::CanStartFromShadowBoundary);
- ContainerNode* found = toContainerNode(walker.traverseParent(walker.get(), details));
- return details->outOfComposition() ? 0 : found;
+ return toContainerNode(walker.traverseParent(walker.get(), details));
}
Node* nextSibling(const Node* node)
diff --git a/chromium/third_party/WebKit/Source/core/dom/NodeRenderingTraversal.h b/chromium/third_party/WebKit/Source/core/dom/NodeRenderingTraversal.h
index 135d8661067..8935ae60a45 100644
--- a/chromium/third_party/WebKit/Source/core/dom/NodeRenderingTraversal.h
+++ b/chromium/third_party/WebKit/Source/core/dom/NodeRenderingTraversal.h
@@ -40,28 +40,23 @@ public:
ParentDetails()
: m_insertionPoint(0)
, m_resetStyleInheritance(false)
- , m_outOfComposition(false)
{ }
- InsertionPoint* insertionPoint() const { return m_insertionPoint; }
+ const InsertionPoint* insertionPoint() const { return m_insertionPoint; }
bool resetStyleInheritance() const { return m_resetStyleInheritance; }
- bool outOfComposition() const { return m_outOfComposition; }
- void didTraverseInsertionPoint(InsertionPoint*);
+ void didTraverseInsertionPoint(const InsertionPoint*);
void didTraverseShadowRoot(const ShadowRoot*);
- void childWasOutOfComposition() { m_outOfComposition = true; }
bool operator==(const ParentDetails& other)
{
return m_insertionPoint == other.m_insertionPoint
- && m_resetStyleInheritance == other.m_resetStyleInheritance
- && m_outOfComposition == other.m_outOfComposition;
+ && m_resetStyleInheritance == other.m_resetStyleInheritance;
}
private:
- InsertionPoint* m_insertionPoint;
+ const InsertionPoint* m_insertionPoint;
bool m_resetStyleInheritance;
- bool m_outOfComposition;
};
ContainerNode* parent(const Node*);
diff --git a/chromium/third_party/WebKit/Source/core/dom/NodeTraversal.cpp b/chromium/third_party/WebKit/Source/core/dom/NodeTraversal.cpp
index 11a9661374c..631a8b9c741 100644
--- a/chromium/third_party/WebKit/Source/core/dom/NodeTraversal.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/NodeTraversal.cpp
@@ -30,142 +30,142 @@
namespace WebCore {
namespace NodeTraversal {
-Node* previousIncludingPseudo(const Node* current, const Node* stayWithin)
+Node* previousIncludingPseudo(const Node& current, const Node* stayWithin)
{
if (current == stayWithin)
return 0;
- if (Node* previous = current->pseudoAwarePreviousSibling()) {
+ if (Node* previous = current.pseudoAwarePreviousSibling()) {
while (previous->pseudoAwareLastChild())
previous = previous->pseudoAwareLastChild();
return previous;
}
- return current->parentNode();
+ return current.parentNode();
}
-Node* nextIncludingPseudo(const Node* current, const Node* stayWithin)
+Node* nextIncludingPseudo(const Node& current, const Node* stayWithin)
{
- if (Node* next = current->pseudoAwareFirstChild())
+ if (Node* next = current.pseudoAwareFirstChild())
return next;
if (current == stayWithin)
return 0;
- if (Node* next = current->pseudoAwareNextSibling())
+ if (Node* next = current.pseudoAwareNextSibling())
return next;
- for (current = current->parentNode(); current; current = current->parentNode()) {
- if (current == stayWithin)
+ for (Node* parent = current.parentNode(); parent; parent = parent->parentNode()) {
+ if (parent == stayWithin)
return 0;
- if (Node* next = current->pseudoAwareNextSibling())
+ if (Node* next = parent->pseudoAwareNextSibling())
return next;
}
return 0;
}
-Node* nextIncludingPseudoSkippingChildren(const Node* current, const Node* stayWithin)
+Node* nextIncludingPseudoSkippingChildren(const Node& current, const Node* stayWithin)
{
if (current == stayWithin)
return 0;
- if (Node* next = current->pseudoAwareNextSibling())
+ if (Node* next = current.pseudoAwareNextSibling())
return next;
- for (current = current->parentNode(); current; current = current->parentNode()) {
- if (current == stayWithin)
+ for (Node* parent = current.parentNode(); parent; parent = parent->parentNode()) {
+ if (parent == stayWithin)
return 0;
- if (Node* next = current->pseudoAwareNextSibling())
+ if (Node* next = parent->pseudoAwareNextSibling())
return next;
}
return 0;
}
-Node* nextAncestorSibling(const Node* current)
+Node* nextAncestorSibling(const Node& current)
{
- ASSERT(!current->nextSibling());
- for (current = current->parentNode(); current; current = current->parentNode()) {
- if (current->nextSibling())
- return current->nextSibling();
+ ASSERT(!current.nextSibling());
+ for (Node* parent = current.parentNode(); parent; parent = parent->parentNode()) {
+ if (parent->nextSibling())
+ return parent->nextSibling();
}
return 0;
}
-Node* nextAncestorSibling(const Node* current, const Node* stayWithin)
+Node* nextAncestorSibling(const Node& current, const Node* stayWithin)
{
- ASSERT(!current->nextSibling());
+ ASSERT(!current.nextSibling());
ASSERT(current != stayWithin);
- for (current = current->parentNode(); current; current = current->parentNode()) {
- if (current == stayWithin)
+ for (Node* parent = current.parentNode(); parent; parent = parent->parentNode()) {
+ if (parent == stayWithin)
return 0;
- if (current->nextSibling())
- return current->nextSibling();
+ if (parent->nextSibling())
+ return parent->nextSibling();
}
return 0;
}
-Node* previous(const Node* current, const Node* stayWithin)
+Node* previous(const Node& current, const Node* stayWithin)
{
if (current == stayWithin)
return 0;
- if (current->previousSibling()) {
- Node* previous = current->previousSibling();
+ if (current.previousSibling()) {
+ Node* previous = current.previousSibling();
while (previous->lastChild())
previous = previous->lastChild();
return previous;
}
- return current->parentNode();
+ return current.parentNode();
}
-Node* previousSkippingChildren(const Node* current, const Node* stayWithin)
+Node* previousSkippingChildren(const Node& current, const Node* stayWithin)
{
if (current == stayWithin)
return 0;
- if (current->previousSibling())
- return current->previousSibling();
- for (current = current->parentNode(); current; current = current->parentNode()) {
- if (current == stayWithin)
+ if (current.previousSibling())
+ return current.previousSibling();
+ for (Node* parent = current.parentNode(); parent; parent = parent->parentNode()) {
+ if (parent == stayWithin)
return 0;
- if (current->previousSibling())
- return current->previousSibling();
+ if (parent->previousSibling())
+ return parent->previousSibling();
}
return 0;
}
-Node* nextPostOrder(const Node* current, const Node* stayWithin)
+Node* nextPostOrder(const Node& current, const Node* stayWithin)
{
if (current == stayWithin)
return 0;
- if (!current->nextSibling())
- return current->parentNode();
- Node* next = current->nextSibling();
+ if (!current.nextSibling())
+ return current.parentNode();
+ Node* next = current.nextSibling();
while (next->firstChild())
next = next->firstChild();
return next;
}
-static Node* previousAncestorSiblingPostOrder(const Node* current, const Node* stayWithin)
+static Node* previousAncestorSiblingPostOrder(const Node& current, const Node* stayWithin)
{
- ASSERT(!current->previousSibling());
- for (current = current->parentNode(); current; current = current->parentNode()) {
- if (current == stayWithin)
+ ASSERT(!current.previousSibling());
+ for (Node* parent = current.parentNode(); parent; parent = parent->parentNode()) {
+ if (parent == stayWithin)
return 0;
- if (current->previousSibling())
- return current->previousSibling();
+ if (parent->previousSibling())
+ return parent->previousSibling();
}
return 0;
}
-Node* previousPostOrder(const Node* current, const Node* stayWithin)
+Node* previousPostOrder(const Node& current, const Node* stayWithin)
{
- if (current->lastChild())
- return current->lastChild();
+ if (current.lastChild())
+ return current.lastChild();
if (current == stayWithin)
return 0;
- if (current->previousSibling())
- return current->previousSibling();
+ if (current.previousSibling())
+ return current.previousSibling();
return previousAncestorSiblingPostOrder(current, stayWithin);
}
-Node* previousSkippingChildrenPostOrder(const Node* current, const Node* stayWithin)
+Node* previousSkippingChildrenPostOrder(const Node& current, const Node* stayWithin)
{
if (current == stayWithin)
return 0;
- if (current->previousSibling())
- return current->previousSibling();
+ if (current.previousSibling())
+ return current.previousSibling();
return previousAncestorSiblingPostOrder(current, stayWithin);
}
diff --git a/chromium/third_party/WebKit/Source/core/dom/NodeTraversal.h b/chromium/third_party/WebKit/Source/core/dom/NodeTraversal.h
index c6966a61b9b..438b0c09a29 100644
--- a/chromium/third_party/WebKit/Source/core/dom/NodeTraversal.h
+++ b/chromium/third_party/WebKit/Source/core/dom/NodeTraversal.h
@@ -35,85 +35,85 @@ namespace NodeTraversal {
// This uses the same order that tags appear in the source file. If the stayWithin
// argument is non-null, the traversal will stop once the specified node is reached.
// This can be used to restrict traversal to a particular sub-tree.
-Node* next(const Node*);
-Node* next(const Node*, const Node* stayWithin);
-Node* next(const ContainerNode*);
-Node* next(const ContainerNode*, const Node* stayWithin);
+Node* next(const Node&);
+Node* next(const Node&, const Node* stayWithin);
+Node* next(const ContainerNode&);
+Node* next(const ContainerNode&, const Node* stayWithin);
// Like next, but skips children and starts with the next sibling.
-Node* nextSkippingChildren(const Node*);
-Node* nextSkippingChildren(const Node*, const Node* stayWithin);
-Node* nextSkippingChildren(const ContainerNode*);
-Node* nextSkippingChildren(const ContainerNode*, const Node* stayWithin);
+Node* nextSkippingChildren(const Node&);
+Node* nextSkippingChildren(const Node&, const Node* stayWithin);
+Node* nextSkippingChildren(const ContainerNode&);
+Node* nextSkippingChildren(const ContainerNode&, const Node* stayWithin);
// Does a reverse pre-order traversal to find the node that comes before the current one in document order
-Node* previous(const Node*, const Node* stayWithin = 0);
+Node* previous(const Node&, const Node* stayWithin = 0);
// Like previous, but skips children and starts with the next sibling.
-Node* previousSkippingChildren(const Node*, const Node* stayWithin = 0);
+Node* previousSkippingChildren(const Node&, const Node* stayWithin = 0);
// Like next, but visits parents after their children.
-Node* nextPostOrder(const Node*, const Node* stayWithin = 0);
+Node* nextPostOrder(const Node&, const Node* stayWithin = 0);
// Like previous/previousSkippingChildren, but visits parents before their children.
-Node* previousPostOrder(const Node*, const Node* stayWithin = 0);
-Node* previousSkippingChildrenPostOrder(const Node*, const Node* stayWithin = 0);
+Node* previousPostOrder(const Node&, const Node* stayWithin = 0);
+Node* previousSkippingChildrenPostOrder(const Node&, const Node* stayWithin = 0);
// Pre-order traversal including the pseudo-elements.
-Node* previousIncludingPseudo(const Node*, const Node* stayWithin = 0);
-Node* nextIncludingPseudo(const Node*, const Node* stayWithin = 0);
-Node* nextIncludingPseudoSkippingChildren(const Node*, const Node* stayWithin = 0);
+Node* previousIncludingPseudo(const Node&, const Node* stayWithin = 0);
+Node* nextIncludingPseudo(const Node&, const Node* stayWithin = 0);
+Node* nextIncludingPseudoSkippingChildren(const Node&, const Node* stayWithin = 0);
-Node* nextAncestorSibling(const Node*);
-Node* nextAncestorSibling(const Node*, const Node* stayWithin);
+Node* nextAncestorSibling(const Node&);
+Node* nextAncestorSibling(const Node&, const Node* stayWithin);
template <class NodeType>
-inline Node* traverseNextTemplate(NodeType* current)
+inline Node* traverseNextTemplate(NodeType& current)
{
- if (current->firstChild())
- return current->firstChild();
- if (current->nextSibling())
- return current->nextSibling();
+ if (current.firstChild())
+ return current.firstChild();
+ if (current.nextSibling())
+ return current.nextSibling();
return nextAncestorSibling(current);
}
-inline Node* next(const Node* current) { return traverseNextTemplate(current); }
-inline Node* next(const ContainerNode* current) { return traverseNextTemplate(current); }
+inline Node* next(const Node& current) { return traverseNextTemplate(current); }
+inline Node* next(const ContainerNode& current) { return traverseNextTemplate(current); }
template <class NodeType>
-inline Node* traverseNextTemplate(NodeType* current, const Node* stayWithin)
+inline Node* traverseNextTemplate(NodeType& current, const Node* stayWithin)
{
- if (current->firstChild())
- return current->firstChild();
+ if (current.firstChild())
+ return current.firstChild();
if (current == stayWithin)
return 0;
- if (current->nextSibling())
- return current->nextSibling();
+ if (current.nextSibling())
+ return current.nextSibling();
return nextAncestorSibling(current, stayWithin);
}
-inline Node* next(const Node* current, const Node* stayWithin) { return traverseNextTemplate(current, stayWithin); }
-inline Node* next(const ContainerNode* current, const Node* stayWithin) { return traverseNextTemplate(current, stayWithin); }
+inline Node* next(const Node& current, const Node* stayWithin) { return traverseNextTemplate(current, stayWithin); }
+inline Node* next(const ContainerNode& current, const Node* stayWithin) { return traverseNextTemplate(current, stayWithin); }
template <class NodeType>
-inline Node* traverseNextSkippingChildrenTemplate(NodeType* current)
+inline Node* traverseNextSkippingChildrenTemplate(NodeType& current)
{
- if (current->nextSibling())
- return current->nextSibling();
+ if (current.nextSibling())
+ return current.nextSibling();
return nextAncestorSibling(current);
}
-inline Node* nextSkippingChildren(const Node* current) { return traverseNextSkippingChildrenTemplate(current); }
-inline Node* nextSkippingChildren(const ContainerNode* current) { return traverseNextSkippingChildrenTemplate(current); }
+inline Node* nextSkippingChildren(const Node& current) { return traverseNextSkippingChildrenTemplate(current); }
+inline Node* nextSkippingChildren(const ContainerNode& current) { return traverseNextSkippingChildrenTemplate(current); }
template <class NodeType>
-inline Node* traverseNextSkippingChildrenTemplate(NodeType* current, const Node* stayWithin)
+inline Node* traverseNextSkippingChildrenTemplate(NodeType& current, const Node* stayWithin)
{
if (current == stayWithin)
return 0;
- if (current->nextSibling())
- return current->nextSibling();
+ if (current.nextSibling())
+ return current.nextSibling();
return nextAncestorSibling(current, stayWithin);
}
-inline Node* nextSkippingChildren(const Node* current, const Node* stayWithin) { return traverseNextSkippingChildrenTemplate(current, stayWithin); }
-inline Node* nextSkippingChildren(const ContainerNode* current, const Node* stayWithin) { return traverseNextSkippingChildrenTemplate(current, stayWithin); }
+inline Node* nextSkippingChildren(const Node& current, const Node* stayWithin) { return traverseNextSkippingChildrenTemplate(current, stayWithin); }
+inline Node* nextSkippingChildren(const ContainerNode& current, const Node* stayWithin) { return traverseNextSkippingChildrenTemplate(current, stayWithin); }
}
diff --git a/chromium/third_party/WebKit/Source/core/dom/OverflowEvent.cpp b/chromium/third_party/WebKit/Source/core/dom/OverflowEvent.cpp
deleted file mode 100644
index 63ee454e7af..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/OverflowEvent.cpp
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * Copyright (C) 2006, 2007 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/dom/OverflowEvent.h"
-
-#include "core/dom/EventNames.h"
-
-namespace WebCore {
-
-OverflowEventInit::OverflowEventInit()
- : orient(0)
- , horizontalOverflow(false)
- , verticalOverflow(false)
-{
-}
-
-OverflowEvent::OverflowEvent()
- : Event(eventNames().overflowchangedEvent, false, false)
- , m_orient(VERTICAL)
- , m_horizontalOverflow(false)
- , m_verticalOverflow(false)
-{
- ScriptWrappable::init(this);
-}
-
-OverflowEvent::OverflowEvent(bool horizontalOverflowChanged, bool horizontalOverflow, bool verticalOverflowChanged, bool verticalOverflow)
- : Event(eventNames().overflowchangedEvent, false, false)
- , m_horizontalOverflow(horizontalOverflow)
- , m_verticalOverflow(verticalOverflow)
-{
- ASSERT(horizontalOverflowChanged || verticalOverflowChanged);
- ScriptWrappable::init(this);
-
- if (horizontalOverflowChanged && verticalOverflowChanged)
- m_orient = BOTH;
- else if (horizontalOverflowChanged)
- m_orient = HORIZONTAL;
- else
- m_orient = VERTICAL;
-}
-
-OverflowEvent::OverflowEvent(const AtomicString& type, const OverflowEventInit& initializer)
- : Event(type, initializer)
- , m_orient(initializer.orient)
- , m_horizontalOverflow(initializer.horizontalOverflow)
- , m_verticalOverflow(initializer.verticalOverflow)
-{
- ScriptWrappable::init(this);
-}
-
-const AtomicString& OverflowEvent::interfaceName() const
-{
- return eventNames().interfaceForOverflowEvent;
-}
-
-void OverflowEvent::initOverflowEvent(unsigned short orient, bool horizontalOverflow, bool verticalOverflow)
-{
- if (dispatched())
- return;
-
- m_orient = orient;
- m_horizontalOverflow = horizontalOverflow;
- m_verticalOverflow = verticalOverflow;
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/dom/OverflowEvent.h b/chromium/third_party/WebKit/Source/core/dom/OverflowEvent.h
deleted file mode 100644
index 7509469e458..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/OverflowEvent.h
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * Copyright (C) 2006, 2007, 2008 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef OverflowEvent_h
-#define OverflowEvent_h
-
-#include "core/dom/Event.h"
-
-namespace WebCore {
-
-struct OverflowEventInit : public EventInit {
- OverflowEventInit();
-
- unsigned short orient;
- bool horizontalOverflow;
- bool verticalOverflow;
-};
-
-class OverflowEvent : public Event {
-public:
- enum orientType {
- HORIZONTAL = 0,
- VERTICAL = 1,
- BOTH = 2
- };
-
- static PassRefPtr<OverflowEvent> create()
- {
- return adoptRef(new OverflowEvent);
- }
- static PassRefPtr<OverflowEvent> create(bool horizontalOverflowChanged, bool horizontalOverflow, bool verticalOverflowChanged, bool verticalOverflow)
- {
- return adoptRef(new OverflowEvent(horizontalOverflowChanged, horizontalOverflow, verticalOverflowChanged, verticalOverflow));
- }
- static PassRefPtr<OverflowEvent> create(const AtomicString& type, const OverflowEventInit& initializer)
- {
- return adoptRef(new OverflowEvent(type, initializer));
- }
-
- void initOverflowEvent(unsigned short orient, bool horizontalOverflow, bool verticalOverflow);
-
- unsigned short orient() const { return m_orient; }
- bool horizontalOverflow() const { return m_horizontalOverflow; }
- bool verticalOverflow() const { return m_verticalOverflow; }
-
- virtual const AtomicString& interfaceName() const;
-
-private:
- OverflowEvent();
- OverflowEvent(bool horizontalOverflowChanged, bool horizontalOverflow, bool verticalOverflowChanged, bool verticalOverflow);
- OverflowEvent(const AtomicString&, const OverflowEventInit&);
-
- unsigned short m_orient;
- bool m_horizontalOverflow;
- bool m_verticalOverflow;
-};
-
-}
-
-#endif // OverflowEvent_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/OverflowEvent.idl b/chromium/third_party/WebKit/Source/core/dom/OverflowEvent.idl
deleted file mode 100644
index 69adee9a578..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/OverflowEvent.idl
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Copyright (C) 2006, 2007 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-[
- ConstructorTemplate=Event
-] interface OverflowEvent : Event {
- const unsigned short HORIZONTAL = 0;
- const unsigned short VERTICAL = 1;
- const unsigned short BOTH = 2;
-
- [InitializedByEventConstructor] readonly attribute unsigned short orient;
- [InitializedByEventConstructor] readonly attribute boolean horizontalOverflow;
- [InitializedByEventConstructor] readonly attribute boolean verticalOverflow;
-};
-
diff --git a/chromium/third_party/WebKit/Source/core/dom/PageTransitionEvent.cpp b/chromium/third_party/WebKit/Source/core/dom/PageTransitionEvent.cpp
deleted file mode 100644
index b351ef4532a..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/PageTransitionEvent.cpp
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Copyright (C) 2009 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/dom/PageTransitionEvent.h"
-
-#include "core/dom/EventNames.h"
-
-namespace WebCore {
-
-PageTransitionEventInit::PageTransitionEventInit()
- : persisted(false)
-{
-}
-
-PageTransitionEvent::PageTransitionEvent()
- : m_persisted(false)
-{
- ScriptWrappable::init(this);
-}
-
-PageTransitionEvent::PageTransitionEvent(const AtomicString& type, bool persisted)
- : Event(type, true, true)
- , m_persisted(persisted)
-{
- ScriptWrappable::init(this);
-}
-
-PageTransitionEvent::PageTransitionEvent(const AtomicString& type, const PageTransitionEventInit& initializer)
- : Event(type, initializer)
- , m_persisted(initializer.persisted)
-{
- ScriptWrappable::init(this);
-}
-
-PageTransitionEvent::~PageTransitionEvent()
-{
-}
-
-const AtomicString& PageTransitionEvent::interfaceName() const
-{
- return eventNames().interfaceForPageTransitionEvent;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/PageTransitionEvent.h b/chromium/third_party/WebKit/Source/core/dom/PageTransitionEvent.h
deleted file mode 100644
index 723dfffffd0..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/PageTransitionEvent.h
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * Copyright (C) 2009 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef PageTransitionEvent_h
-#define PageTransitionEvent_h
-
-#include "core/dom/Event.h"
-
-namespace WebCore {
-
-struct PageTransitionEventInit : public EventInit {
- PageTransitionEventInit();
-
- bool persisted;
-};
-
-class PageTransitionEvent : public Event {
-public:
- static PassRefPtr<PageTransitionEvent> create()
- {
- return adoptRef(new PageTransitionEvent);
- }
- static PassRefPtr<PageTransitionEvent> create(const AtomicString& type, bool persisted)
- {
- return adoptRef(new PageTransitionEvent(type, persisted));
- }
- static PassRefPtr<PageTransitionEvent> create(const AtomicString& type, const PageTransitionEventInit& initializer)
- {
- return adoptRef(new PageTransitionEvent(type, initializer));
- }
-
- virtual ~PageTransitionEvent();
-
- virtual const AtomicString& interfaceName() const;
-
- bool persisted() const { return m_persisted; }
-
-private:
- PageTransitionEvent();
- PageTransitionEvent(const AtomicString& type, bool persisted);
- PageTransitionEvent(const AtomicString&, const PageTransitionEventInit&);
-
- bool m_persisted;
-};
-
-} // namespace WebCore
-
-#endif // PageTransitionEvent_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/PageTransitionEvent.idl b/chromium/third_party/WebKit/Source/core/dom/PageTransitionEvent.idl
deleted file mode 100644
index 47749be6a05..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/PageTransitionEvent.idl
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright (C) 2009 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-[
- ConstructorTemplate=Event
-] interface PageTransitionEvent : Event {
- [InitializedByEventConstructor] readonly attribute boolean persisted;
-};
-
diff --git a/chromium/third_party/WebKit/Source/core/dom/PendingScript.cpp b/chromium/third_party/WebKit/Source/core/dom/PendingScript.cpp
index 6ad05cfed0e..b448c8bd9bf 100644
--- a/chromium/third_party/WebKit/Source/core/dom/PendingScript.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/PendingScript.cpp
@@ -33,8 +33,6 @@ namespace WebCore {
PendingScript::~PendingScript()
{
- if (m_resource)
- m_resource->removeClient(this);
}
PassRefPtr<Element> PendingScript::releaseElementAndClear()
@@ -47,18 +45,7 @@ PassRefPtr<Element> PendingScript::releaseElementAndClear()
void PendingScript::setScriptResource(ScriptResource* resource)
{
- if (m_resource == resource)
- return;
- if (m_resource)
- m_resource->removeClient(this);
- m_resource = resource;
- if (m_resource)
- m_resource->addClient(this);
-}
-
-ScriptResource* PendingScript::resource() const
-{
- return m_resource.get();
+ setResource(resource);
}
void PendingScript::notifyFinished(Resource*)
diff --git a/chromium/third_party/WebKit/Source/core/dom/PendingScript.h b/chromium/third_party/WebKit/Source/core/dom/PendingScript.h
index 0f169a9cabe..a5c5855819c 100644
--- a/chromium/third_party/WebKit/Source/core/dom/PendingScript.h
+++ b/chromium/third_party/WebKit/Source/core/dom/PendingScript.h
@@ -27,22 +27,23 @@
#define PendingScript_h
#include "core/fetch/ResourceClient.h"
-#include "core/fetch/ResourcePtr.h"
+#include "core/fetch/ResourceOwner.h"
+#include "core/fetch/ScriptResource.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefPtr.h"
#include "wtf/text/TextPosition.h"
namespace WebCore {
-class ScriptResource;
class Element;
+class ScriptResource;
// A container for an external script which may be loaded and executed.
//
// A ResourcePtr alone does not prevent the underlying Resource
// from purging its data buffer. This class holds a dummy client open for its
// lifetime in order to guarantee that the data buffer will not be purged.
-class PendingScript : public ResourceClient {
+class PendingScript : public ResourceOwner<ScriptResource> {
public:
PendingScript()
: m_watchingForLoad(false)
@@ -58,7 +59,7 @@ public:
}
PendingScript(const PendingScript& other)
- : ResourceClient(other)
+ : ResourceOwner(other)
, m_watchingForLoad(other.m_watchingForLoad)
, m_element(other.m_element)
, m_startingPosition(other.m_startingPosition)
@@ -76,7 +77,7 @@ public:
m_watchingForLoad = other.m_watchingForLoad;
m_element = other.m_element;
m_startingPosition = other.m_startingPosition;
- setScriptResource(other.resource());
+ this->ResourceOwner<ScriptResource, ResourceClient>::operator=(other);
return *this;
}
@@ -91,7 +92,6 @@ public:
void setElement(Element* element) { m_element = element; }
PassRefPtr<Element> releaseElementAndClear();
- ScriptResource* resource() const;
void setScriptResource(ScriptResource*);
virtual void notifyFinished(Resource*);
@@ -100,7 +100,6 @@ private:
bool m_watchingForLoad;
RefPtr<Element> m_element;
TextPosition m_startingPosition; // Only used for inline script tags.
- ResourcePtr<ScriptResource> m_resource;
};
}
diff --git a/chromium/third_party/WebKit/Source/core/dom/PopStateEvent.cpp b/chromium/third_party/WebKit/Source/core/dom/PopStateEvent.cpp
deleted file mode 100644
index 652d9a20bb1..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/PopStateEvent.cpp
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * Copyright (C) 2009 Apple Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-#include "config.h"
-#include "core/dom/PopStateEvent.h"
-
-#include "bindings/v8/SerializedScriptValue.h"
-#include "core/dom/EventNames.h"
-#include "core/page/History.h"
-
-namespace WebCore {
-
-PopStateEvent::PopStateEvent()
- : Event(eventNames().popstateEvent, false, true)
- , m_serializedState(0)
- , m_history(0)
-{
- ScriptWrappable::init(this);
-}
-
-PopStateEvent::PopStateEvent(const AtomicString& type, const PopStateEventInit& initializer)
- : Event(type, initializer)
- , m_history(0)
-{
- ScriptWrappable::init(this);
-}
-
-PopStateEvent::PopStateEvent(PassRefPtr<SerializedScriptValue> serializedState, PassRefPtr<History> history)
- : Event(eventNames().popstateEvent, false, true)
- , m_serializedState(serializedState)
- , m_history(history)
-{
- ScriptWrappable::init(this);
-}
-
-PopStateEvent::~PopStateEvent()
-{
-}
-
-PassRefPtr<PopStateEvent> PopStateEvent::create()
-{
- return adoptRef(new PopStateEvent);
-}
-
-PassRefPtr<PopStateEvent> PopStateEvent::create(PassRefPtr<SerializedScriptValue> serializedState, PassRefPtr<History> history)
-{
- return adoptRef(new PopStateEvent(serializedState, history));
-}
-
-PassRefPtr<PopStateEvent> PopStateEvent::create(const AtomicString& type, const PopStateEventInit& initializer)
-{
- return adoptRef(new PopStateEvent(type, initializer));
-}
-
-const AtomicString& PopStateEvent::interfaceName() const
-{
- return eventNames().interfaceForPopStateEvent;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/PopStateEvent.h b/chromium/third_party/WebKit/Source/core/dom/PopStateEvent.h
deleted file mode 100644
index 19abdd13bbb..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/PopStateEvent.h
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Copyright (C) 2009 Apple Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-#ifndef PopStateEvent_h
-#define PopStateEvent_h
-
-#include "core/dom/Event.h"
-
-namespace WebCore {
-
-class History;
-class SerializedScriptValue;
-
-typedef EventInit PopStateEventInit;
-
-class PopStateEvent : public Event {
-public:
- virtual ~PopStateEvent();
- static PassRefPtr<PopStateEvent> create();
- static PassRefPtr<PopStateEvent> create(PassRefPtr<SerializedScriptValue>, PassRefPtr<History>);
- static PassRefPtr<PopStateEvent> create(const AtomicString&, const PopStateEventInit&);
-
- SerializedScriptValue* serializedState() const { return m_serializedState.get(); }
- void setSerializedState(PassRefPtr<SerializedScriptValue> state)
- {
- ASSERT(!m_serializedState);
- m_serializedState = state;
- }
- History* history() const { return m_history.get(); }
-
- virtual const AtomicString& interfaceName() const;
-
-private:
- PopStateEvent();
- PopStateEvent(const AtomicString&, const PopStateEventInit&);
- explicit PopStateEvent(PassRefPtr<SerializedScriptValue>, PassRefPtr<History>);
-
- RefPtr<SerializedScriptValue> m_serializedState;
- RefPtr<History> m_history;
-};
-
-} // namespace WebCore
-
-#endif // PopStateEvent_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/PopStateEvent.idl b/chromium/third_party/WebKit/Source/core/dom/PopStateEvent.idl
deleted file mode 100644
index 20ddbaa78f0..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/PopStateEvent.idl
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright (C) 2009 Apple Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-[
- ConstructorTemplate=Event
-] interface PopStateEvent : Event {
- [InitializedByEventConstructor, CustomGetter] readonly attribute any state;
-};
diff --git a/chromium/third_party/WebKit/Source/core/dom/Position.cpp b/chromium/third_party/WebKit/Source/core/dom/Position.cpp
index 8d52a1e59c1..f6d9fa115b8 100644
--- a/chromium/third_party/WebKit/Source/core/dom/Position.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/Position.cpp
@@ -37,9 +37,9 @@
#include "core/editing/htmlediting.h"
#include "core/html/HTMLHtmlElement.h"
#include "core/html/HTMLTableElement.h"
-#include "core/page/Frame.h"
-#include "core/page/Settings.h"
-#include "core/platform/Logging.h"
+#include "core/frame/Frame.h"
+#include "core/frame/Settings.h"
+#include "platform/Logging.h"
#include "core/rendering/InlineIterator.h"
#include "core/rendering/InlineTextBox.h"
#include "core/rendering/RenderBlock.h"
@@ -55,11 +55,11 @@ using namespace HTMLNames;
static Node* nextRenderedEditable(Node* node)
{
while ((node = node->nextLeafNode())) {
- if (!node->rendererIsEditable())
- continue;
RenderObject* renderer = node->renderer();
if (!renderer)
continue;
+ if (!node->rendererIsEditable())
+ continue;
if ((renderer->isBox() && toRenderBox(renderer)->inlineBoxWrapper()) || (renderer->isText() && toRenderText(renderer)->firstTextBox()))
return node;
}
@@ -69,11 +69,11 @@ static Node* nextRenderedEditable(Node* node)
static Node* previousRenderedEditable(Node* node)
{
while ((node = node->previousLeafNode())) {
- if (!node->rendererIsEditable())
- continue;
RenderObject* renderer = node->renderer();
if (!renderer)
continue;
+ if (!node->rendererIsEditable())
+ continue;
if ((renderer->isBox() && toRenderBox(renderer)->inlineBoxWrapper()) || (renderer->isText() && toRenderText(renderer)->firstTextBox()))
return node;
}
@@ -161,7 +161,7 @@ Text* Position::containerText() const
{
switch (anchorType()) {
case PositionIsOffsetInAnchor:
- return m_anchorNode && m_anchorNode->isTextNode() ? toText(m_anchorNode.get()) : 0;
+ return m_anchorNode && m_anchorNode->isTextNode() ? toText(m_anchorNode) : 0;
case PositionIsBeforeAnchor:
case PositionIsAfterAnchor:
return 0;
@@ -1016,13 +1016,13 @@ bool Position::rendersInDifferentPosition(const Position &pos) const
InlineBox* b2;
pos.getInlineBoxAndOffset(DOWNSTREAM, b2, ignoredCaretOffset);
- LOG(Editing, "renderer: %p [%p]\n", renderer, b1);
- LOG(Editing, "thisRenderedOffset: %d\n", thisRenderedOffset);
- LOG(Editing, "posRenderer: %p [%p]\n", posRenderer, b2);
- LOG(Editing, "posRenderedOffset: %d\n", posRenderedOffset);
- LOG(Editing, "node min/max: %d:%d\n", caretMinOffset(deprecatedNode()), caretMaxOffset(deprecatedNode()));
- LOG(Editing, "pos node min/max: %d:%d\n", caretMinOffset(pos.deprecatedNode()), caretMaxOffset(pos.deprecatedNode()));
- LOG(Editing, "----------------------------------------------------------------------\n");
+ WTF_LOG(Editing, "renderer: %p [%p]\n", renderer, b1);
+ WTF_LOG(Editing, "thisRenderedOffset: %d\n", thisRenderedOffset);
+ WTF_LOG(Editing, "posRenderer: %p [%p]\n", posRenderer, b2);
+ WTF_LOG(Editing, "posRenderedOffset: %d\n", posRenderedOffset);
+ WTF_LOG(Editing, "node min/max: %d:%d\n", caretMinOffset(deprecatedNode()), caretMaxOffset(deprecatedNode()));
+ WTF_LOG(Editing, "pos node min/max: %d:%d\n", caretMinOffset(pos.deprecatedNode()), caretMaxOffset(pos.deprecatedNode()));
+ WTF_LOG(Editing, "----------------------------------------------------------------------\n");
if (!b1 || !b2) {
return false;
diff --git a/chromium/third_party/WebKit/Source/core/dom/Position.h b/chromium/third_party/WebKit/Source/core/dom/Position.h
index d2b1d1e552f..eea78f644ce 100644
--- a/chromium/third_party/WebKit/Source/core/dom/Position.h
+++ b/chromium/third_party/WebKit/Source/core/dom/Position.h
@@ -29,7 +29,7 @@
#include "core/dom/ContainerNode.h"
#include "core/editing/EditingBoundary.h"
#include "core/editing/TextAffinity.h"
-#include "core/platform/text/TextDirection.h"
+#include "platform/text/TextDirection.h"
#include "wtf/Assertions.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefPtr.h"
diff --git a/chromium/third_party/WebKit/Source/core/dom/PositionIterator.cpp b/chromium/third_party/WebKit/Source/core/dom/PositionIterator.cpp
index 5cc76b10806..f94c0aee90c 100644
--- a/chromium/third_party/WebKit/Source/core/dom/PositionIterator.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/PositionIterator.cpp
@@ -27,7 +27,6 @@
#include "core/dom/PositionIterator.h"
#include "HTMLNames.h"
-#include "core/dom/Node.h"
#include "core/editing/htmlediting.h"
#include "core/html/HTMLHtmlElement.h"
#include "core/rendering/RenderBlock.h"
diff --git a/chromium/third_party/WebKit/Source/core/dom/PresentationAttributeStyle.cpp b/chromium/third_party/WebKit/Source/core/dom/PresentationAttributeStyle.cpp
new file mode 100644
index 00000000000..e9ced659b29
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/PresentationAttributeStyle.cpp
@@ -0,0 +1,208 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/dom/PresentationAttributeStyle.h"
+
+#include "HTMLNames.h"
+#include "core/css/StylePropertySet.h"
+#include "core/dom/Attribute.h"
+#include "core/dom/Element.h"
+#include "wtf/HashFunctions.h"
+#include "wtf/HashMap.h"
+#include "wtf/text/CString.h"
+
+namespace WebCore {
+
+using namespace HTMLNames;
+
+struct PresentationAttributeCacheKey {
+ PresentationAttributeCacheKey() : tagName(0) { }
+ StringImpl* tagName;
+ Vector<std::pair<StringImpl*, AtomicString>, 3> attributesAndValues;
+};
+
+static bool operator!=(const PresentationAttributeCacheKey& a, const PresentationAttributeCacheKey& b)
+{
+ if (a.tagName != b.tagName)
+ return true;
+ return a.attributesAndValues != b.attributesAndValues;
+}
+
+struct PresentationAttributeCacheEntry {
+ WTF_MAKE_FAST_ALLOCATED;
+public:
+ PresentationAttributeCacheKey key;
+ RefPtr<StylePropertySet> value;
+};
+
+typedef HashMap<unsigned, OwnPtr<PresentationAttributeCacheEntry>, AlreadyHashed> PresentationAttributeCache;
+static PresentationAttributeCache& presentationAttributeCache()
+{
+ DEFINE_STATIC_LOCAL(PresentationAttributeCache, cache, ());
+ return cache;
+}
+
+class PresentationAttributeCacheCleaner {
+ WTF_MAKE_NONCOPYABLE(PresentationAttributeCacheCleaner); WTF_MAKE_FAST_ALLOCATED;
+public:
+ PresentationAttributeCacheCleaner()
+ : m_hitCount(0)
+ , m_cleanTimer(this, &PresentationAttributeCacheCleaner::cleanCache)
+ {
+ }
+
+ void didHitPresentationAttributeCache()
+ {
+ if (presentationAttributeCache().size() < minimumPresentationAttributeCacheSizeForCleaning)
+ return;
+
+ m_hitCount++;
+
+ if (!m_cleanTimer.isActive())
+ m_cleanTimer.startOneShot(presentationAttributeCacheCleanTimeInSeconds);
+ }
+
+private:
+ static const unsigned presentationAttributeCacheCleanTimeInSeconds = 60;
+ static const unsigned minimumPresentationAttributeCacheSizeForCleaning = 100;
+ static const unsigned minimumPresentationAttributeCacheHitCountPerMinute = (100 * presentationAttributeCacheCleanTimeInSeconds) / 60;
+
+ void cleanCache(Timer<PresentationAttributeCacheCleaner>* timer)
+ {
+ ASSERT_UNUSED(timer, timer == &m_cleanTimer);
+ unsigned hitCount = m_hitCount;
+ m_hitCount = 0;
+ if (hitCount > minimumPresentationAttributeCacheHitCountPerMinute)
+ return;
+ presentationAttributeCache().clear();
+ }
+
+ unsigned m_hitCount;
+ Timer<PresentationAttributeCacheCleaner> m_cleanTimer;
+};
+
+static bool attributeNameSort(const pair<StringImpl*, AtomicString>& p1, const pair<StringImpl*, AtomicString>& p2)
+{
+ // Sort based on the attribute name pointers. It doesn't matter what the order is as long as it is always the same.
+ return p1.first < p2.first;
+}
+
+static void makePresentationAttributeCacheKey(Element& element, PresentationAttributeCacheKey& result)
+{
+ // FIXME: Enable for SVG.
+ if (!element.isHTMLElement())
+ return;
+ // Interpretation of the size attributes on <input> depends on the type attribute.
+ if (element.hasTagName(inputTag))
+ return;
+ unsigned size = element.attributeCount();
+ for (unsigned i = 0; i < size; ++i) {
+ const Attribute* attribute = element.attributeItem(i);
+ if (!element.isPresentationAttribute(attribute->name()))
+ continue;
+ if (!attribute->namespaceURI().isNull())
+ return;
+ // FIXME: Background URL may depend on the base URL and can't be shared. Disallow caching.
+ if (attribute->name() == backgroundAttr)
+ return;
+ result.attributesAndValues.append(std::make_pair(attribute->localName().impl(), attribute->value()));
+ }
+ if (result.attributesAndValues.isEmpty())
+ return;
+ // Attribute order doesn't matter. Sort for easy equality comparison.
+ std::sort(result.attributesAndValues.begin(), result.attributesAndValues.end(), attributeNameSort);
+ // The cache key is non-null when the tagName is set.
+ result.tagName = element.localName().impl();
+}
+
+static unsigned computePresentationAttributeCacheHash(const PresentationAttributeCacheKey& key)
+{
+ if (!key.tagName)
+ return 0;
+ ASSERT(key.attributesAndValues.size());
+ unsigned attributeHash = StringHasher::hashMemory(key.attributesAndValues.data(), key.attributesAndValues.size() * sizeof(key.attributesAndValues[0]));
+ return WTF::pairIntHash(key.tagName->existingHash(), attributeHash);
+}
+
+PassRefPtr<StylePropertySet> computePresentationAttributeStyle(Element& element)
+{
+ DEFINE_STATIC_LOCAL(PresentationAttributeCacheCleaner, cacheCleaner, ());
+
+ ASSERT(element.isStyledElement());
+
+ PresentationAttributeCacheKey cacheKey;
+ makePresentationAttributeCacheKey(element, cacheKey);
+
+ unsigned cacheHash = computePresentationAttributeCacheHash(cacheKey);
+
+ PresentationAttributeCache::iterator cacheIterator;
+ if (cacheHash) {
+ cacheIterator = presentationAttributeCache().add(cacheHash, nullptr).iterator;
+ if (cacheIterator->value && cacheIterator->value->key != cacheKey)
+ cacheHash = 0;
+ } else {
+ cacheIterator = presentationAttributeCache().end();
+ }
+
+ RefPtr<StylePropertySet> style;
+ if (cacheHash && cacheIterator->value) {
+ style = cacheIterator->value->value;
+ cacheCleaner.didHitPresentationAttributeCache();
+ } else {
+ style = MutableStylePropertySet::create(element.isSVGElement() ? SVGAttributeMode : HTMLAttributeMode);
+ unsigned size = element.attributeCount();
+ for (unsigned i = 0; i < size; ++i) {
+ const Attribute* attribute = element.attributeItem(i);
+ element.collectStyleForPresentationAttribute(attribute->name(), attribute->value(), toMutableStylePropertySet(style));
+ }
+ }
+
+ if (!cacheHash || cacheIterator->value)
+ return style.release();
+
+ OwnPtr<PresentationAttributeCacheEntry> newEntry = adoptPtr(new PresentationAttributeCacheEntry);
+ newEntry->key = cacheKey;
+ newEntry->value = style;
+
+ static const unsigned presentationAttributeCacheMaximumSize = 4096;
+ if (presentationAttributeCache().size() > presentationAttributeCacheMaximumSize) {
+ // FIXME: Discarding the entire cache when it gets too big is probably bad
+ // since it creates a perf "cliff". Perhaps we should use an LRU?
+ presentationAttributeCache().clear();
+ presentationAttributeCache().set(cacheHash, newEntry.release());
+ } else {
+ cacheIterator->value = newEntry.release();
+ }
+
+ return style.release();
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/PresentationAttributeStyle.h b/chromium/third_party/WebKit/Source/core/dom/PresentationAttributeStyle.h
new file mode 100644
index 00000000000..017561f744f
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/PresentationAttributeStyle.h
@@ -0,0 +1,45 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef PresentationAttributeStyle_h
+#define PresentationAttributeStyle_h
+
+#include "wtf/RefPtr.h"
+
+namespace WebCore {
+
+class Element;
+class StylePropertySet;
+
+PassRefPtr<StylePropertySet> computePresentationAttributeStyle(Element&);
+
+} // namespace WebCore
+
+#endif // PresentationAttributeStyle_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/ProcessingInstruction.cpp b/chromium/third_party/WebKit/Source/core/dom/ProcessingInstruction.cpp
index be736e8e48c..bd1bd7b02c6 100644
--- a/chromium/third_party/WebKit/Source/core/dom/ProcessingInstruction.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/ProcessingInstruction.cpp
@@ -39,7 +39,6 @@ namespace WebCore {
inline ProcessingInstruction::ProcessingInstruction(Document& document, const String& target, const String& data)
: CharacterData(document, data, CreateOther)
, m_target(target)
- , m_resource(0)
, m_loading(false)
, m_alternate(false)
, m_createdByParser(false)
@@ -59,9 +58,6 @@ ProcessingInstruction::~ProcessingInstruction()
if (m_sheet)
m_sheet->clearOwnerNode();
- if (m_resource)
- m_resource->removeClient(this);
-
if (inDocument())
document().styleEngine()->removeStyleSheetCandidateNode(this);
}
@@ -85,7 +81,7 @@ PassRefPtr<Node> ProcessingInstruction::cloneNode(bool /*deep*/)
void ProcessingInstruction::checkStyleSheet()
{
- if (m_target == "xml-stylesheet" && document().frame() && parentNode() == &document()) {
+ if (m_target == "xml-stylesheet" && document().frame() && parentNode() == document()) {
// see http://www.w3.org/TR/xml-stylesheet/
// ### support stylesheet included in a fragment of this (or another) document
// ### make sure this gets called when adding from javascript
@@ -123,35 +119,28 @@ void ProcessingInstruction::checkStyleSheet()
m_loading = false;
}
} else {
- if (m_resource) {
- m_resource->removeClient(this);
- m_resource = 0;
- }
+ clearResource();
String url = document().completeURL(href).string();
if (!dispatchBeforeLoadEvent(url))
return;
- m_loading = true;
- document().styleEngine()->addPendingSheet();
+ ResourcePtr<StyleSheetResource> resource;
FetchRequest request(ResourceRequest(document().completeURL(href)), FetchInitiatorTypeNames::processinginstruction);
- if (m_isXSL)
- m_resource = document().fetcher()->fetchXSLStyleSheet(request);
- else
- {
+ if (m_isXSL) {
+ resource = document().fetcher()->fetchXSLStyleSheet(request);
+ } else {
String charset = attrs.get("charset");
if (charset.isEmpty())
charset = document().charset();
request.setCharset(charset);
-
- m_resource = document().fetcher()->fetchCSSStyleSheet(request);
+ resource = document().fetcher()->fetchCSSStyleSheet(request);
}
- if (m_resource)
- m_resource->addClient(this);
- else {
- // The request may have been denied if (for example) the stylesheet is local and the document is remote.
- m_loading = false;
- document().styleEngine()->removePendingSheet(this);
+
+ if (resource) {
+ m_loading = true;
+ document().styleEngine()->addPendingSheet();
+ setResource(resource);
}
}
}
@@ -210,25 +199,22 @@ void ProcessingInstruction::setXSLStyleSheet(const String& href, const KURL& bas
void ProcessingInstruction::parseStyleSheet(const String& sheet)
{
if (m_isCSS)
- static_cast<CSSStyleSheet*>(m_sheet.get())->contents()->parseString(sheet);
+ toCSSStyleSheet(m_sheet.get())->contents()->parseString(sheet);
else if (m_isXSL)
- static_cast<XSLStyleSheet*>(m_sheet.get())->parseString(sheet);
-
- if (m_resource)
- m_resource->removeClient(this);
- m_resource = 0;
+ toXSLStyleSheet(m_sheet.get())->parseString(sheet);
+ clearResource();
m_loading = false;
if (m_isCSS)
- static_cast<CSSStyleSheet*>(m_sheet.get())->contents()->checkLoaded();
+ toCSSStyleSheet(m_sheet.get())->contents()->checkLoaded();
else if (m_isXSL)
- static_cast<XSLStyleSheet*>(m_sheet.get())->checkLoaded();
+ toXSLStyleSheet(m_sheet.get())->checkLoaded();
}
void ProcessingInstruction::setCSSStyleSheet(PassRefPtr<CSSStyleSheet> sheet)
{
- ASSERT(!m_resource);
+ ASSERT(!resource());
ASSERT(!m_loading);
m_sheet = sheet;
sheet->setTitle(m_title);
@@ -270,7 +256,7 @@ void ProcessingInstruction::removedFrom(ContainerNode* insertionPoint)
}
// If we're in document teardown, then we don't need to do any notification of our sheet's removal.
- if (document().renderer())
+ if (document().isActive())
document().removedStyleSheet(removedSheet.get());
}
diff --git a/chromium/third_party/WebKit/Source/core/dom/ProcessingInstruction.h b/chromium/third_party/WebKit/Source/core/dom/ProcessingInstruction.h
index 7c8ace9080d..2dec480183e 100644
--- a/chromium/third_party/WebKit/Source/core/dom/ProcessingInstruction.h
+++ b/chromium/third_party/WebKit/Source/core/dom/ProcessingInstruction.h
@@ -23,7 +23,8 @@
#define ProcessingInstruction_h
#include "core/dom/CharacterData.h"
-#include "core/fetch/ResourcePtr.h"
+#include "core/fetch/ResourceOwner.h"
+#include "core/fetch/StyleSheetResource.h"
#include "core/fetch/StyleSheetResourceClient.h"
namespace WebCore {
@@ -31,7 +32,7 @@ namespace WebCore {
class StyleSheet;
class CSSStyleSheet;
-class ProcessingInstruction FINAL : public CharacterData, private StyleSheetResourceClient {
+class ProcessingInstruction FINAL : public CharacterData, private ResourceOwner<StyleSheetResource> {
public:
static PassRefPtr<ProcessingInstruction> create(Document&, const String& target, const String& data);
virtual ~ProcessingInstruction();
@@ -76,7 +77,6 @@ private:
String m_localHref;
String m_title;
String m_media;
- ResourcePtr<Resource> m_resource;
RefPtr<StyleSheet> m_sheet;
bool m_loading;
bool m_alternate;
@@ -85,17 +85,7 @@ private:
bool m_isXSL;
};
-inline ProcessingInstruction* toProcessingInstruction(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->nodeType() == Node::PROCESSING_INSTRUCTION_NODE);
- return static_cast<ProcessingInstruction*>(node);
-}
-
-inline const ProcessingInstruction* toProcessingInstruction(const Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->nodeType() == Node::PROCESSING_INSTRUCTION_NODE);
- return static_cast<const ProcessingInstruction*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(ProcessingInstruction, nodeType() == Node::PROCESSING_INSTRUCTION_NODE);
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/ProgressEvent.cpp b/chromium/third_party/WebKit/Source/core/dom/ProgressEvent.cpp
deleted file mode 100644
index da8a3c1f369..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/ProgressEvent.cpp
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Copyright (C) 2007, 2008 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/dom/ProgressEvent.h"
-
-#include "core/dom/EventNames.h"
-
-namespace WebCore {
-
-ProgressEventInit::ProgressEventInit()
- : lengthComputable(false)
- , loaded(0)
- , total(0)
-{
-}
-
-ProgressEvent::ProgressEvent()
- : m_lengthComputable(false)
- , m_loaded(0)
- , m_total(0)
-{
- ScriptWrappable::init(this);
-}
-
-ProgressEvent::ProgressEvent(const AtomicString& type, const ProgressEventInit& initializer)
- : Event(type, initializer)
- , m_lengthComputable(initializer.lengthComputable)
- , m_loaded(initializer.loaded)
- , m_total(initializer.total)
-{
- ScriptWrappable::init(this);
-}
-
-ProgressEvent::ProgressEvent(const AtomicString& type, bool lengthComputable, unsigned long long loaded, unsigned long long total)
- : Event(type, false, true)
- , m_lengthComputable(lengthComputable)
- , m_loaded(loaded)
- , m_total(total)
-{
- ScriptWrappable::init(this);
-}
-
-const AtomicString& ProgressEvent::interfaceName() const
-{
- return eventNames().interfaceForProgressEvent;
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/dom/ProgressEvent.h b/chromium/third_party/WebKit/Source/core/dom/ProgressEvent.h
deleted file mode 100644
index 035e23e60fa..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/ProgressEvent.h
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * Copyright (C) 2007, 2008 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ProgressEvent_h
-#define ProgressEvent_h
-
-#include "core/dom/Event.h"
-
-namespace WebCore {
-
-struct ProgressEventInit : public EventInit {
- ProgressEventInit();
-
- bool lengthComputable;
- unsigned long long loaded;
- unsigned long long total;
-};
-
-class ProgressEvent : public Event {
-public:
- static PassRefPtr<ProgressEvent> create()
- {
- return adoptRef(new ProgressEvent);
- }
- static PassRefPtr<ProgressEvent> create(const AtomicString& type, bool lengthComputable, unsigned long long loaded, unsigned long long total)
- {
- return adoptRef(new ProgressEvent(type, lengthComputable, loaded, total));
- }
- static PassRefPtr<ProgressEvent> create(const AtomicString& type, const ProgressEventInit& initializer)
- {
- return adoptRef(new ProgressEvent(type, initializer));
- }
-
- bool lengthComputable() const { return m_lengthComputable; }
- unsigned long long loaded() const { return m_loaded; }
- unsigned long long total() const { return m_total; }
-
- virtual const AtomicString& interfaceName() const;
-
-protected:
- ProgressEvent();
- ProgressEvent(const AtomicString& type, bool lengthComputable, unsigned long long loaded, unsigned long long total);
- ProgressEvent(const AtomicString&, const ProgressEventInit&);
-
-private:
- bool m_lengthComputable;
- unsigned long long m_loaded;
- unsigned long long m_total;
-};
-}
-
-#endif // ProgressEvent_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/ProgressEvent.idl b/chromium/third_party/WebKit/Source/core/dom/ProgressEvent.idl
deleted file mode 100644
index d775b88799e..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/ProgressEvent.idl
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Copyright (C) 2007 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-[
- ConstructorTemplate=Event
-] interface ProgressEvent : Event {
- [InitializedByEventConstructor] readonly attribute boolean lengthComputable;
- [InitializedByEventConstructor] readonly attribute unsigned long long loaded;
- [InitializedByEventConstructor] readonly attribute unsigned long long total;
-};
-
diff --git a/chromium/third_party/WebKit/Source/core/dom/Promise.idl b/chromium/third_party/WebKit/Source/core/dom/Promise.idl
index f7fb7ba61cf..45989d44d82 100644
--- a/chromium/third_party/WebKit/Source/core/dom/Promise.idl
+++ b/chromium/third_party/WebKit/Source/core/dom/Promise.idl
@@ -31,9 +31,8 @@
callback PromiseInit = void (any resolve, any reject);
callback AnyCallback = any (optional any value);
[
- GlobalContext=Window&WorkerGlobalScope,
CustomConstructor(PromiseInit init),
- EnabledAtRuntime=Promise
+ GlobalContext=Window&WorkerGlobalScope,
] interface Promise {
[Custom] Promise then(optional AnyCallback fulfillCallback, optional AnyCallback rejectCallback);
[Custom] Promise catch(optional AnyCallback rejectCallback);
@@ -41,6 +40,7 @@ callback AnyCallback = any (optional any value);
[Custom] static Promise resolve(any value);
[Custom] static Promise reject(any value);
- [Custom] static Promise _any(any... values);
- [Custom] static Promise every(any... values);
+ [Custom] static Promise cast(any value);
+ [Custom] static Promise race(any iterable);
+ [Custom] static Promise all(any iterable);
};
diff --git a/chromium/third_party/WebKit/Source/core/dom/PseudoElement.cpp b/chromium/third_party/WebKit/Source/core/dom/PseudoElement.cpp
index 9c10bd0e0b0..9512d82defe 100644
--- a/chromium/third_party/WebKit/Source/core/dom/PseudoElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/PseudoElement.cpp
@@ -27,6 +27,7 @@
#include "config.h"
#include "core/dom/PseudoElement.h"
+#include "core/inspector/InspectorInstrumentation.h"
#include "core/rendering/RenderObject.h"
#include "core/rendering/RenderQuote.h"
#include "core/rendering/style/ContentData.h"
@@ -54,7 +55,7 @@ String PseudoElement::pseudoElementNameForEvents(PseudoId pseudoId)
}
PseudoElement::PseudoElement(Element* parent, PseudoId pseudoId)
- : Element(pseudoElementTagName(), &parent->document(), CreatePseudoElement)
+ : Element(pseudoElementTagName(), &parent->document(), CreateElement)
, m_pseudoId(pseudoId)
{
ASSERT(pseudoId != NOPSEUDO);
@@ -67,6 +68,19 @@ PassRefPtr<RenderStyle> PseudoElement::customStyleForRenderer()
return parentOrShadowHostElement()->renderer()->getCachedPseudoStyle(m_pseudoId);
}
+void PseudoElement::dispose()
+{
+ InspectorInstrumentation::pseudoElementDestroyed(this);
+
+ ASSERT(!nextSibling());
+ ASSERT(!previousSibling());
+
+ detach();
+ RefPtr<Element> parent = parentOrShadowHostElement();
+ setParentOrShadowHostNode(0);
+ removedFrom(parent.get());
+}
+
void PseudoElement::attach(const AttachContext& context)
{
ASSERT(!renderer());
@@ -77,7 +91,7 @@ void PseudoElement::attach(const AttachContext& context)
if (!renderer)
return;
RenderStyle* style = renderer->style();
- if (!style->regionThread().isEmpty())
+ if (style->hasFlowFrom())
return;
if (style->styleType() != BEFORE && style->styleType() != AFTER)
return;
diff --git a/chromium/third_party/WebKit/Source/core/dom/PseudoElement.h b/chromium/third_party/WebKit/Source/core/dom/PseudoElement.h
index a0ddf69da94..6f109333e08 100644
--- a/chromium/third_party/WebKit/Source/core/dom/PseudoElement.h
+++ b/chromium/third_party/WebKit/Source/core/dom/PseudoElement.h
@@ -53,6 +53,8 @@ public:
static String pseudoElementNameForEvents(PseudoId);
+ void dispose();
+
private:
PseudoElement(Element*, PseudoId);
@@ -66,23 +68,10 @@ const QualifiedName& pseudoElementTagName();
inline bool pseudoElementRendererIsNeeded(const RenderStyle* style)
{
- return style && style->display() != NONE && (style->styleType() == BACKDROP || style->contentData() || !style->regionThread().isEmpty());
-}
-
-inline PseudoElement* toPseudoElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->isPseudoElement());
- return static_cast<PseudoElement*>(node);
-}
-
-inline const PseudoElement* toPseudoElement(const Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->isPseudoElement());
- return static_cast<const PseudoElement*>(node);
+ return style && style->display() != NONE && (style->styleType() == BACKDROP || style->contentData() || style->hasFlowFrom());
}
-// This will catch anyone doing an unnecessary cast.
-void toPseudoElement(const PseudoElement*);
+DEFINE_NODE_TYPE_CASTS(PseudoElement, isPseudoElement());
} // namespace
diff --git a/chromium/third_party/WebKit/Source/core/dom/QualifiedName.cpp b/chromium/third_party/WebKit/Source/core/dom/QualifiedName.cpp
index 1495d92e5df..1912986ead2 100644
--- a/chromium/third_party/WebKit/Source/core/dom/QualifiedName.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/QualifiedName.cpp
@@ -33,6 +33,7 @@
#include "core/dom/QualifiedName.h"
#include "wtf/Assertions.h"
#include "wtf/HashSet.h"
+#include "wtf/MainThread.h"
#include "wtf/StaticConstructors.h"
namespace WebCore {
@@ -44,10 +45,18 @@ static const int staticQualifiedNamesCount = HTMLNames::HTMLTagsCount + HTMLName
+ XMLNames::XMLAttrsCount;
struct QualifiedNameHashTraits : public HashTraits<QualifiedName::QualifiedNameImpl*> {
- static const int minimumTableSize = WTF::HashTableCapacityForSize<staticQualifiedNamesCount>::value;
+ static const unsigned minimumTableSize = WTF::HashTableCapacityForSize<staticQualifiedNamesCount>::value;
};
-typedef HashSet<QualifiedName::QualifiedNameImpl*, QualifiedNameHash, QualifiedNameHashTraits> QNameSet;
+typedef HashSet<QualifiedName::QualifiedNameImpl*, QualifiedNameHash, QualifiedNameHashTraits> QualifiedNameCache;
+
+static QualifiedNameCache& qualifiedNameCache()
+{
+ // This code is lockless and thus assumes it all runs on one thread!
+ ASSERT(isMainThread());
+ static QualifiedNameCache* gNameCache = new QualifiedNameCache;
+ return *gNameCache;
+}
struct QNameComponentsTranslator {
static unsigned hash(const QualifiedNameComponents& components)
@@ -60,18 +69,14 @@ struct QNameComponentsTranslator {
}
static void translate(QualifiedName::QualifiedNameImpl*& location, const QualifiedNameComponents& components, unsigned)
{
- location = QualifiedName::QualifiedNameImpl::create(components.m_prefix, components.m_localName, components.m_namespace).leakRef();
+ location = QualifiedName::QualifiedNameImpl::create(AtomicString(components.m_prefix), AtomicString(components.m_localName), AtomicString(components.m_namespace)).leakRef();
}
};
-static QNameSet* gNameCache;
-
QualifiedName::QualifiedName(const AtomicString& p, const AtomicString& l, const AtomicString& n)
{
- if (!gNameCache)
- gNameCache = new QNameSet;
QualifiedNameComponents components = { p.impl(), l.impl(), n.isEmpty() ? nullAtom.impl() : n.impl() };
- QNameSet::AddResult addResult = gNameCache->add<QNameComponentsTranslator>(components);
+ QualifiedNameCache::AddResult addResult = qualifiedNameCache().add<QNameComponentsTranslator>(components);
m_impl = *addResult.iterator;
if (!addResult.isNewEntry)
m_impl->ref();
@@ -94,7 +99,7 @@ void QualifiedName::deref()
QualifiedName::QualifiedNameImpl::~QualifiedNameImpl()
{
- gNameCache->remove(this);
+ qualifiedNameCache().remove(this);
}
String QualifiedName::toString() const
diff --git a/chromium/third_party/WebKit/Source/core/dom/Range.cpp b/chromium/third_party/WebKit/Source/core/dom/Range.cpp
index e1df7031cab..5b75ea2bab4 100644
--- a/chromium/third_party/WebKit/Source/core/dom/Range.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/Range.cpp
@@ -27,7 +27,6 @@
#include "bindings/v8/ExceptionMessages.h"
#include "bindings/v8/ExceptionState.h"
-#include "bindings/v8/ExceptionStatePlaceholder.h"
#include "core/dom/ClientRect.h"
#include "core/dom/ClientRectList.h"
#include "core/dom/DocumentFragment.h"
@@ -36,18 +35,17 @@
#include "core/dom/NodeTraversal.h"
#include "core/dom/NodeWithIndex.h"
#include "core/dom/ProcessingInstruction.h"
-#include "core/dom/ScopedEventQueue.h"
+#include "core/events/ScopedEventQueue.h"
#include "core/dom/Text.h"
#include "core/editing/TextIterator.h"
#include "core/editing/VisiblePosition.h"
#include "core/editing/VisibleUnits.h"
#include "core/editing/markup.h"
#include "core/html/HTMLElement.h"
-#include "core/platform/graphics/FloatQuad.h"
#include "core/rendering/RenderBoxModelObject.h"
#include "core/rendering/RenderText.h"
+#include "platform/geometry/FloatQuad.h"
#include "wtf/RefCountedLeakCounter.h"
-#include "wtf/Vector.h"
#include "wtf/text/CString.h"
#include "wtf/text/StringBuilder.h"
#ifndef NDEBUG
@@ -119,7 +117,7 @@ Range::~Range()
void Range::setDocument(Document& document)
{
- ASSERT(m_ownerDocument != &document);
+ ASSERT(m_ownerDocument != document);
ASSERT(m_ownerDocument);
m_ownerDocument->detachRange(this);
m_ownerDocument = &document;
@@ -128,50 +126,50 @@ void Range::setDocument(Document& document)
m_ownerDocument->attachRange(this);
}
-Node* Range::startContainer(ExceptionState& es) const
+Node* Range::startContainer(ExceptionState& exceptionState) const
{
if (!m_start.container()) {
- es.throwDOMException(InvalidStateError);
+ exceptionState.throwDOMException(InvalidStateError, "The range has no container. Perhaps 'detatch()' has been invoked on this object?");
return 0;
}
return m_start.container();
}
-int Range::startOffset(ExceptionState& es) const
+int Range::startOffset(ExceptionState& exceptionState) const
{
if (!m_start.container()) {
- es.throwDOMException(InvalidStateError);
+ exceptionState.throwDOMException(InvalidStateError, "The range has no container. Perhaps 'detatch()' has been invoked on this object?");
return 0;
}
return m_start.offset();
}
-Node* Range::endContainer(ExceptionState& es) const
+Node* Range::endContainer(ExceptionState& exceptionState) const
{
if (!m_start.container()) {
- es.throwDOMException(InvalidStateError);
+ exceptionState.throwDOMException(InvalidStateError, "The range has no container. Perhaps 'detatch()' has been invoked on this object?");
return 0;
}
return m_end.container();
}
-int Range::endOffset(ExceptionState& es) const
+int Range::endOffset(ExceptionState& exceptionState) const
{
if (!m_start.container()) {
- es.throwDOMException(InvalidStateError);
+ exceptionState.throwDOMException(InvalidStateError, "The range has no container. Perhaps 'detatch()' has been invoked on this object?");
return 0;
}
return m_end.offset();
}
-Node* Range::commonAncestorContainer(ExceptionState& es) const
+Node* Range::commonAncestorContainer(ExceptionState& exceptionState) const
{
if (!m_start.container()) {
- es.throwDOMException(InvalidStateError);
+ exceptionState.throwDOMException(InvalidStateError, "The range has no container. Perhaps 'detatch()' has been invoked on this object?");
return 0;
}
@@ -189,10 +187,10 @@ Node* Range::commonAncestorContainer(Node* containerA, Node* containerB)
return 0;
}
-bool Range::collapsed(ExceptionState& es) const
+bool Range::collapsed(ExceptionState& exceptionState) const
{
if (!m_start.container()) {
- es.throwDOMException(InvalidStateError);
+ exceptionState.throwDOMException(InvalidStateError, "The range has no container. Perhaps 'detatch()' has been invoked on this object?");
return 0;
}
@@ -211,78 +209,78 @@ static inline bool checkForDifferentRootContainer(const RangeBoundaryPoint& star
return startRootContainer != endRootContainer || (Range::compareBoundaryPoints(start, end, ASSERT_NO_EXCEPTION) > 0);
}
-void Range::setStart(PassRefPtr<Node> refNode, int offset, ExceptionState& es)
+void Range::setStart(PassRefPtr<Node> refNode, int offset, ExceptionState& exceptionState)
{
if (!m_start.container()) {
- es.throwDOMException(InvalidStateError);
+ exceptionState.throwDOMException(InvalidStateError, "The range has no container. Perhaps 'detatch()' has been invoked on this object?");
return;
}
if (!refNode) {
- es.throwDOMException(NotFoundError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
return;
}
bool didMoveDocument = false;
- if (&refNode->document() != m_ownerDocument) {
+ if (refNode->document() != m_ownerDocument) {
setDocument(refNode->document());
didMoveDocument = true;
}
- Node* childNode = checkNodeWOffset(refNode.get(), offset, es);
- if (es.hadException())
+ Node* childNode = checkNodeWOffset(refNode.get(), offset, exceptionState);
+ if (exceptionState.hadException())
return;
m_start.set(refNode, offset, childNode);
if (didMoveDocument || checkForDifferentRootContainer(m_start, m_end))
- collapse(true, es);
+ collapse(true, exceptionState);
}
-void Range::setEnd(PassRefPtr<Node> refNode, int offset, ExceptionState& es)
+void Range::setEnd(PassRefPtr<Node> refNode, int offset, ExceptionState& exceptionState)
{
if (!m_start.container()) {
- es.throwDOMException(InvalidStateError);
+ exceptionState.throwDOMException(InvalidStateError, "The range has no container. Perhaps 'detatch()' has been invoked on this object?");
return;
}
if (!refNode) {
- es.throwDOMException(NotFoundError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
return;
}
bool didMoveDocument = false;
- if (&refNode->document() != m_ownerDocument) {
+ if (refNode->document() != m_ownerDocument) {
setDocument(refNode->document());
didMoveDocument = true;
}
- Node* childNode = checkNodeWOffset(refNode.get(), offset, es);
- if (es.hadException())
+ Node* childNode = checkNodeWOffset(refNode.get(), offset, exceptionState);
+ if (exceptionState.hadException())
return;
m_end.set(refNode, offset, childNode);
if (didMoveDocument || checkForDifferentRootContainer(m_start, m_end))
- collapse(false, es);
+ collapse(false, exceptionState);
}
-void Range::setStart(const Position& start, ExceptionState& es)
+void Range::setStart(const Position& start, ExceptionState& exceptionState)
{
Position parentAnchored = start.parentAnchoredEquivalent();
- setStart(parentAnchored.containerNode(), parentAnchored.offsetInContainerNode(), es);
+ setStart(parentAnchored.containerNode(), parentAnchored.offsetInContainerNode(), exceptionState);
}
-void Range::setEnd(const Position& end, ExceptionState& es)
+void Range::setEnd(const Position& end, ExceptionState& exceptionState)
{
Position parentAnchored = end.parentAnchoredEquivalent();
- setEnd(parentAnchored.containerNode(), parentAnchored.offsetInContainerNode(), es);
+ setEnd(parentAnchored.containerNode(), parentAnchored.offsetInContainerNode(), exceptionState);
}
-void Range::collapse(bool toStart, ExceptionState& es)
+void Range::collapse(bool toStart, ExceptionState& exceptionState)
{
if (!m_start.container()) {
- es.throwDOMException(InvalidStateError);
+ exceptionState.throwDOMException(InvalidStateError, "The range has no container. Perhaps 'detatch()' has been invoked on this object?");
return;
}
@@ -292,92 +290,92 @@ void Range::collapse(bool toStart, ExceptionState& es)
m_start = m_end;
}
-bool Range::isPointInRange(Node* refNode, int offset, ExceptionState& es)
+bool Range::isPointInRange(Node* refNode, int offset, ExceptionState& exceptionState)
{
if (!m_start.container()) {
- es.throwDOMException(InvalidStateError);
+ exceptionState.throwDOMException(InvalidStateError, "The range has no container. Perhaps 'detatch()' has been invoked on this object?");
return false;
}
if (!refNode) {
- es.throwDOMException(HierarchyRequestError);
+ exceptionState.throwUninformativeAndGenericDOMException(HierarchyRequestError);
return false;
}
- if (!refNode->attached() || &refNode->document() != m_ownerDocument) {
+ if (!refNode->inActiveDocument() || refNode->document() != m_ownerDocument) {
return false;
}
- checkNodeWOffset(refNode, offset, es);
- if (es.hadException())
+ checkNodeWOffset(refNode, offset, exceptionState);
+ if (exceptionState.hadException())
return false;
- return compareBoundaryPoints(refNode, offset, m_start.container(), m_start.offset(), es) >= 0 && !es.hadException()
- && compareBoundaryPoints(refNode, offset, m_end.container(), m_end.offset(), es) <= 0 && !es.hadException();
+ return compareBoundaryPoints(refNode, offset, m_start.container(), m_start.offset(), exceptionState) >= 0 && !exceptionState.hadException()
+ && compareBoundaryPoints(refNode, offset, m_end.container(), m_end.offset(), exceptionState) <= 0 && !exceptionState.hadException();
}
-short Range::comparePoint(Node* refNode, int offset, ExceptionState& es) const
+short Range::comparePoint(Node* refNode, int offset, ExceptionState& exceptionState) const
{
// http://developer.mozilla.org/en/docs/DOM:range.comparePoint
// This method returns -1, 0 or 1 depending on if the point described by the
// refNode node and an offset within the node is before, same as, or after the range respectively.
if (!m_start.container()) {
- es.throwDOMException(InvalidStateError);
+ exceptionState.throwDOMException(InvalidStateError, "The range has no container. Perhaps 'detatch()' has been invoked on this object?");
return 0;
}
if (!refNode) {
- es.throwDOMException(HierarchyRequestError);
+ exceptionState.throwUninformativeAndGenericDOMException(HierarchyRequestError);
return 0;
}
- if (!refNode->attached() || &refNode->document() != m_ownerDocument) {
- es.throwDOMException(WrongDocumentError);
+ if (!refNode->inActiveDocument() || refNode->document() != m_ownerDocument) {
+ exceptionState.throwUninformativeAndGenericDOMException(WrongDocumentError);
return 0;
}
- checkNodeWOffset(refNode, offset, es);
- if (es.hadException())
+ checkNodeWOffset(refNode, offset, exceptionState);
+ if (exceptionState.hadException())
return 0;
// compare to start, and point comes before
- if (compareBoundaryPoints(refNode, offset, m_start.container(), m_start.offset(), es) < 0)
+ if (compareBoundaryPoints(refNode, offset, m_start.container(), m_start.offset(), exceptionState) < 0)
return -1;
- if (es.hadException())
+ if (exceptionState.hadException())
return 0;
// compare to end, and point comes after
- if (compareBoundaryPoints(refNode, offset, m_end.container(), m_end.offset(), es) > 0 && !es.hadException())
+ if (compareBoundaryPoints(refNode, offset, m_end.container(), m_end.offset(), exceptionState) > 0 && !exceptionState.hadException())
return 1;
// point is in the middle of this range, or on the boundary points
return 0;
}
-Range::CompareResults Range::compareNode(Node* refNode, ExceptionState& es) const
+Range::CompareResults Range::compareNode(Node* refNode, ExceptionState& exceptionState) const
{
// http://developer.mozilla.org/en/docs/DOM:range.compareNode
// This method returns 0, 1, 2, or 3 based on if the node is before, after,
// before and after(surrounds), or inside the range, respectively
if (!refNode) {
- es.throwDOMException(NotFoundError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
return NODE_BEFORE;
}
- if (!m_start.container() && refNode->attached()) {
- es.throwDOMException(InvalidStateError);
+ if (!m_start.container() && refNode->inActiveDocument()) {
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
return NODE_BEFORE;
}
- if (m_start.container() && !refNode->attached()) {
+ if (m_start.container() && !refNode->inActiveDocument()) {
// Firefox doesn't throw an exception for this case; it returns 0.
return NODE_BEFORE;
}
- if (&refNode->document() != m_ownerDocument) {
+ if (refNode->document() != m_ownerDocument) {
// Firefox doesn't throw an exception for this case; it returns 0.
return NODE_BEFORE;
}
@@ -388,42 +386,42 @@ Range::CompareResults Range::compareNode(Node* refNode, ExceptionState& es) cons
if (!parentNode) {
// if the node is the top document we should return NODE_BEFORE_AND_AFTER
// but we throw to match firefox behavior
- es.throwDOMException(NotFoundError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
return NODE_BEFORE;
}
- if (comparePoint(parentNode, nodeIndex, es) < 0) { // starts before
- if (comparePoint(parentNode, nodeIndex + 1, es) > 0) // ends after the range
+ if (comparePoint(parentNode, nodeIndex, exceptionState) < 0) { // starts before
+ if (comparePoint(parentNode, nodeIndex + 1, exceptionState) > 0) // ends after the range
return NODE_BEFORE_AND_AFTER;
return NODE_BEFORE; // ends before or in the range
}
// starts at or after the range start
- if (comparePoint(parentNode, nodeIndex + 1, es) > 0) // ends after the range
+ if (comparePoint(parentNode, nodeIndex + 1, exceptionState) > 0) // ends after the range
return NODE_AFTER;
return NODE_INSIDE; // ends inside the range
}
-short Range::compareBoundaryPoints(CompareHow how, const Range* sourceRange, ExceptionState& es) const
+short Range::compareBoundaryPoints(CompareHow how, const Range* sourceRange, ExceptionState& exceptionState) const
{
if (!m_start.container()) {
- es.throwDOMException(InvalidStateError);
+ exceptionState.throwDOMException(InvalidStateError, "The range has no container. Perhaps 'detatch()' has been invoked on this object?");
return 0;
}
if (!sourceRange) {
- es.throwDOMException(NotFoundError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
return 0;
}
- Node* thisCont = commonAncestorContainer(es);
- if (es.hadException())
+ Node* thisCont = commonAncestorContainer(exceptionState);
+ if (exceptionState.hadException())
return 0;
- Node* sourceCont = sourceRange->commonAncestorContainer(es);
- if (es.hadException())
+ Node* sourceCont = sourceRange->commonAncestorContainer(exceptionState);
+ if (exceptionState.hadException())
return 0;
- if (&thisCont->document() != &sourceCont->document()) {
- es.throwDOMException(WrongDocumentError);
+ if (thisCont->document() != sourceCont->document()) {
+ exceptionState.throwUninformativeAndGenericDOMException(WrongDocumentError);
return 0;
}
@@ -434,26 +432,26 @@ short Range::compareBoundaryPoints(CompareHow how, const Range* sourceRange, Exc
while (sourceTop->parentNode())
sourceTop = sourceTop->parentNode();
if (thisTop != sourceTop) { // in different DocumentFragments
- es.throwDOMException(WrongDocumentError);
+ exceptionState.throwUninformativeAndGenericDOMException(WrongDocumentError);
return 0;
}
switch (how) {
case START_TO_START:
- return compareBoundaryPoints(m_start, sourceRange->m_start, es);
+ return compareBoundaryPoints(m_start, sourceRange->m_start, exceptionState);
case START_TO_END:
- return compareBoundaryPoints(m_end, sourceRange->m_start, es);
+ return compareBoundaryPoints(m_end, sourceRange->m_start, exceptionState);
case END_TO_END:
- return compareBoundaryPoints(m_end, sourceRange->m_end, es);
+ return compareBoundaryPoints(m_end, sourceRange->m_end, exceptionState);
case END_TO_START:
- return compareBoundaryPoints(m_start, sourceRange->m_end, es);
+ return compareBoundaryPoints(m_start, sourceRange->m_end, exceptionState);
}
- es.throwDOMException(SyntaxError);
+ exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
return 0;
}
-short Range::compareBoundaryPoints(Node* containerA, int offsetA, Node* containerB, int offsetB, ExceptionState& es)
+short Range::compareBoundaryPoints(Node* containerA, int offsetA, Node* containerB, int offsetB, ExceptionState& exceptionState)
{
ASSERT(containerA);
ASSERT(containerB);
@@ -515,7 +513,7 @@ short Range::compareBoundaryPoints(Node* containerA, int offsetA, Node* containe
// ### we need to do a traversal here instead
Node* commonAncestor = commonAncestorContainer(containerA, containerB);
if (!commonAncestor) {
- es.throwDOMException(WrongDocumentError);
+ exceptionState.throwUninformativeAndGenericDOMException(WrongDocumentError);
return 0;
}
Node* childA = containerA;
@@ -546,42 +544,42 @@ short Range::compareBoundaryPoints(Node* containerA, int offsetA, Node* containe
return 0;
}
-short Range::compareBoundaryPoints(const RangeBoundaryPoint& boundaryA, const RangeBoundaryPoint& boundaryB, ExceptionState& es)
+short Range::compareBoundaryPoints(const RangeBoundaryPoint& boundaryA, const RangeBoundaryPoint& boundaryB, ExceptionState& exceptionState)
{
- return compareBoundaryPoints(boundaryA.container(), boundaryA.offset(), boundaryB.container(), boundaryB.offset(), es);
+ return compareBoundaryPoints(boundaryA.container(), boundaryA.offset(), boundaryB.container(), boundaryB.offset(), exceptionState);
}
bool Range::boundaryPointsValid() const
{
- TrackExceptionState es;
- return m_start.container() && compareBoundaryPoints(m_start, m_end, es) <= 0 && !es.hadException();
+ TrackExceptionState exceptionState;
+ return m_start.container() && compareBoundaryPoints(m_start, m_end, exceptionState) <= 0 && !exceptionState.hadException();
}
-void Range::deleteContents(ExceptionState& es)
+void Range::deleteContents(ExceptionState& exceptionState)
{
- checkDeleteExtract(es);
- if (es.hadException())
+ checkDeleteExtract(exceptionState);
+ if (exceptionState.hadException())
return;
- processContents(DELETE_CONTENTS, es);
+ processContents(DELETE_CONTENTS, exceptionState);
}
-bool Range::intersectsNode(Node* refNode, ExceptionState& es)
+bool Range::intersectsNode(Node* refNode, ExceptionState& exceptionState)
{
// http://developer.mozilla.org/en/docs/DOM:range.intersectsNode
// Returns a bool if the node intersects the range.
// Throw exception if the range is already detached.
if (!m_start.container()) {
- es.throwDOMException(InvalidStateError);
+ exceptionState.throwDOMException(InvalidStateError, "The range has no container. Perhaps 'detatch()' has been invoked on this object?");
return false;
}
if (!refNode) {
- es.throwDOMException(NotFoundError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
return false;
}
- if (!refNode->attached() || &refNode->document() != m_ownerDocument) {
+ if (!refNode->inActiveDocument() || refNode->document() != m_ownerDocument) {
// Firefox doesn't throw an exception for these cases; it returns false.
return false;
}
@@ -592,17 +590,17 @@ bool Range::intersectsNode(Node* refNode, ExceptionState& es)
if (!parentNode) {
// if the node is the top document we should return NODE_BEFORE_AND_AFTER
// but we throw to match firefox behavior
- es.throwDOMException(NotFoundError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
return false;
}
- if (comparePoint(parentNode, nodeIndex, es) < 0 // starts before start
- && comparePoint(parentNode, nodeIndex + 1, es) < 0) { // ends before start
+ if (comparePoint(parentNode, nodeIndex, exceptionState) < 0 // starts before start
+ && comparePoint(parentNode, nodeIndex + 1, exceptionState) < 0) { // ends before start
return false;
}
- if (comparePoint(parentNode, nodeIndex, es) > 0 // starts after end
- && comparePoint(parentNode, nodeIndex + 1, es) > 0) { // ends after end
+ if (comparePoint(parentNode, nodeIndex, exceptionState) > 0 // starts after end
+ && comparePoint(parentNode, nodeIndex + 1, exceptionState) > 0) { // ends after end
return false;
}
@@ -666,7 +664,7 @@ static inline unsigned lengthOfContentsInNode(Node* node)
return 0;
}
-PassRefPtr<DocumentFragment> Range::processContents(ActionType action, ExceptionState& es)
+PassRefPtr<DocumentFragment> Range::processContents(ActionType action, ExceptionState& exceptionState)
{
typedef Vector<RefPtr<Node> > NodeVector;
@@ -674,18 +672,18 @@ PassRefPtr<DocumentFragment> Range::processContents(ActionType action, Exception
if (action == EXTRACT_CONTENTS || action == CLONE_CONTENTS)
fragment = DocumentFragment::create(*m_ownerDocument.get());
- if (collapsed(es))
+ if (collapsed(exceptionState))
return fragment.release();
- if (es.hadException())
+ if (exceptionState.hadException())
return 0;
- RefPtr<Node> commonRoot = commonAncestorContainer(es);
- if (es.hadException())
+ RefPtr<Node> commonRoot = commonAncestorContainer(exceptionState);
+ if (exceptionState.hadException())
return 0;
ASSERT(commonRoot);
if (m_start.container() == m_end.container()) {
- processContentsBetweenOffsets(action, fragment, m_start.container(), m_start.offset(), m_end.offset(), es);
+ processContentsBetweenOffsets(action, fragment, m_start.container(), m_start.offset(), m_end.offset(), exceptionState);
return fragment;
}
@@ -719,14 +717,14 @@ PassRefPtr<DocumentFragment> Range::processContents(ActionType action, Exception
RefPtr<Node> leftContents;
if (originalStart.container() != commonRoot && commonRoot->contains(originalStart.container())) {
- leftContents = processContentsBetweenOffsets(action, 0, originalStart.container(), originalStart.offset(), lengthOfContentsInNode(originalStart.container()), es);
- leftContents = processAncestorsAndTheirSiblings(action, originalStart.container(), ProcessContentsForward, leftContents, commonRoot.get(), es);
+ leftContents = processContentsBetweenOffsets(action, 0, originalStart.container(), originalStart.offset(), lengthOfContentsInNode(originalStart.container()), exceptionState);
+ leftContents = processAncestorsAndTheirSiblings(action, originalStart.container(), ProcessContentsForward, leftContents, commonRoot.get(), exceptionState);
}
RefPtr<Node> rightContents;
if (m_end.container() != commonRoot && commonRoot->contains(originalEnd.container())) {
- rightContents = processContentsBetweenOffsets(action, 0, originalEnd.container(), 0, originalEnd.offset(), es);
- rightContents = processAncestorsAndTheirSiblings(action, originalEnd.container(), ProcessContentsBackward, rightContents, commonRoot.get(), es);
+ rightContents = processContentsBetweenOffsets(action, 0, originalEnd.container(), 0, originalEnd.offset(), exceptionState);
+ rightContents = processAncestorsAndTheirSiblings(action, originalEnd.container(), ProcessContentsBackward, rightContents, commonRoot.get(), exceptionState);
}
// delete all children of commonRoot between the start and end container
@@ -739,14 +737,14 @@ PassRefPtr<DocumentFragment> Range::processContents(ActionType action, Exception
if (action == EXTRACT_CONTENTS || action == DELETE_CONTENTS) {
if (partialStart && commonRoot->contains(partialStart.get())) {
// FIXME: We should not continue if we have an earlier error.
- es.clearException();
- setStart(partialStart->parentNode(), partialStart->nodeIndex() + 1, es);
+ exceptionState.clearException();
+ setStart(partialStart->parentNode(), partialStart->nodeIndex() + 1, exceptionState);
} else if (partialEnd && commonRoot->contains(partialEnd.get())) {
// FIXME: We should not continue if we have an earlier error.
- es.clearException();
- setStart(partialEnd->parentNode(), partialEnd->nodeIndex(), es);
+ exceptionState.clearException();
+ setStart(partialEnd->parentNode(), partialEnd->nodeIndex(), exceptionState);
}
- if (es.hadException())
+ if (exceptionState.hadException())
return 0;
m_end = m_start;
}
@@ -758,31 +756,31 @@ PassRefPtr<DocumentFragment> Range::processContents(ActionType action, Exception
// (or just delete the stuff in between)
if ((action == EXTRACT_CONTENTS || action == CLONE_CONTENTS) && leftContents)
- fragment->appendChild(leftContents, es);
+ fragment->appendChild(leftContents, exceptionState);
if (processStart) {
NodeVector nodes;
for (Node* n = processStart.get(); n && n != processEnd; n = n->nextSibling())
nodes.append(n);
- processNodes(action, nodes, commonRoot, fragment, es);
+ processNodes(action, nodes, commonRoot, fragment, exceptionState);
}
if ((action == EXTRACT_CONTENTS || action == CLONE_CONTENTS) && rightContents)
- fragment->appendChild(rightContents, es);
+ fragment->appendChild(rightContents, exceptionState);
return fragment.release();
}
-static inline void deleteCharacterData(PassRefPtr<CharacterData> data, unsigned startOffset, unsigned endOffset, ExceptionState& es)
+static inline void deleteCharacterData(PassRefPtr<CharacterData> data, unsigned startOffset, unsigned endOffset, ExceptionState& exceptionState)
{
if (data->length() - endOffset)
- data->deleteData(endOffset, data->length() - endOffset, es);
+ data->deleteData(endOffset, data->length() - endOffset, exceptionState);
if (startOffset)
- data->deleteData(0, startOffset, es);
+ data->deleteData(0, startOffset, exceptionState);
}
PassRefPtr<Node> Range::processContentsBetweenOffsets(ActionType action, PassRefPtr<DocumentFragment> fragment,
- Node* container, unsigned startOffset, unsigned endOffset, ExceptionState& es)
+ Node* container, unsigned startOffset, unsigned endOffset, ExceptionState& exceptionState)
{
ASSERT(container);
ASSERT(startOffset <= endOffset);
@@ -796,15 +794,15 @@ PassRefPtr<Node> Range::processContentsBetweenOffsets(ActionType action, PassRef
endOffset = std::min(endOffset, toCharacterData(container)->length());
if (action == EXTRACT_CONTENTS || action == CLONE_CONTENTS) {
RefPtr<CharacterData> c = static_pointer_cast<CharacterData>(container->cloneNode(true));
- deleteCharacterData(c, startOffset, endOffset, es);
+ deleteCharacterData(c, startOffset, endOffset, exceptionState);
if (fragment) {
result = fragment;
- result->appendChild(c.release(), es);
+ result->appendChild(c.release(), exceptionState);
} else
result = c.release();
}
if (action == EXTRACT_CONTENTS || action == DELETE_CONTENTS)
- toCharacterData(container)->deleteData(startOffset, endOffset - startOffset, es);
+ toCharacterData(container)->deleteData(startOffset, endOffset - startOffset, exceptionState);
break;
case Node::PROCESSING_INSTRUCTION_NODE:
endOffset = std::min(endOffset, toProcessingInstruction(container)->data().length());
@@ -813,7 +811,7 @@ PassRefPtr<Node> Range::processContentsBetweenOffsets(ActionType action, PassRef
c->setData(c->data().substring(startOffset, endOffset - startOffset));
if (fragment) {
result = fragment;
- result->appendChild(c.release(), es);
+ result->appendChild(c.release(), exceptionState);
} else
result = c.release();
}
@@ -847,31 +845,31 @@ PassRefPtr<Node> Range::processContentsBetweenOffsets(ActionType action, PassRef
for (unsigned i = startOffset; n && i < endOffset; i++, n = n->nextSibling())
nodes.append(n);
- processNodes(action, nodes, container, result, es);
+ processNodes(action, nodes, container, result, exceptionState);
break;
}
return result.release();
}
-void Range::processNodes(ActionType action, Vector<RefPtr<Node> >& nodes, PassRefPtr<Node> oldContainer, PassRefPtr<Node> newContainer, ExceptionState& es)
+void Range::processNodes(ActionType action, Vector<RefPtr<Node> >& nodes, PassRefPtr<Node> oldContainer, PassRefPtr<Node> newContainer, ExceptionState& exceptionState)
{
for (unsigned i = 0; i < nodes.size(); i++) {
switch (action) {
case DELETE_CONTENTS:
- oldContainer->removeChild(nodes[i].get(), es);
+ oldContainer->removeChild(nodes[i].get(), exceptionState);
break;
case EXTRACT_CONTENTS:
- newContainer->appendChild(nodes[i].release(), es); // will remove n from its parent
+ newContainer->appendChild(nodes[i].release(), exceptionState); // will remove n from its parent
break;
case CLONE_CONTENTS:
- newContainer->appendChild(nodes[i]->cloneNode(true), es);
+ newContainer->appendChild(nodes[i]->cloneNode(true), exceptionState);
break;
}
}
}
-PassRefPtr<Node> Range::processAncestorsAndTheirSiblings(ActionType action, Node* container, ContentsProcessDirection direction, PassRefPtr<Node> passedClonedContainer, Node* commonRoot, ExceptionState& es)
+PassRefPtr<Node> Range::processAncestorsAndTheirSiblings(ActionType action, Node* container, ContentsProcessDirection direction, PassRefPtr<Node> passedClonedContainer, Node* commonRoot, ExceptionState& exceptionState)
{
typedef Vector<RefPtr<Node> > NodeVector;
@@ -885,7 +883,7 @@ PassRefPtr<Node> Range::processAncestorsAndTheirSiblings(ActionType action, Node
RefPtr<Node> ancestor = *it;
if (action == EXTRACT_CONTENTS || action == CLONE_CONTENTS) {
if (RefPtr<Node> clonedAncestor = ancestor->cloneNode(false)) { // Might have been removed already during mutation event.
- clonedAncestor->appendChild(clonedContainer, es);
+ clonedAncestor->appendChild(clonedContainer, exceptionState);
clonedContainer = clonedAncestor;
}
}
@@ -904,19 +902,19 @@ PassRefPtr<Node> Range::processAncestorsAndTheirSiblings(ActionType action, Node
Node* child = it->get();
switch (action) {
case DELETE_CONTENTS:
- ancestor->removeChild(child, es);
+ ancestor->removeChild(child, exceptionState);
break;
case EXTRACT_CONTENTS: // will remove child from ancestor
if (direction == ProcessContentsForward)
- clonedContainer->appendChild(child, es);
+ clonedContainer->appendChild(child, exceptionState);
else
- clonedContainer->insertBefore(child, clonedContainer->firstChild(), es);
+ clonedContainer->insertBefore(child, clonedContainer->firstChild(), exceptionState);
break;
case CLONE_CONTENTS:
if (direction == ProcessContentsForward)
- clonedContainer->appendChild(child->cloneNode(true), es);
+ clonedContainer->appendChild(child->cloneNode(true), exceptionState);
else
- clonedContainer->insertBefore(child->cloneNode(true), clonedContainer->firstChild(), es);
+ clonedContainer->insertBefore(child->cloneNode(true), clonedContainer->firstChild(), exceptionState);
break;
}
}
@@ -926,36 +924,36 @@ PassRefPtr<Node> Range::processAncestorsAndTheirSiblings(ActionType action, Node
return clonedContainer.release();
}
-PassRefPtr<DocumentFragment> Range::extractContents(ExceptionState& es)
+PassRefPtr<DocumentFragment> Range::extractContents(ExceptionState& exceptionState)
{
- checkDeleteExtract(es);
- if (es.hadException())
+ checkDeleteExtract(exceptionState);
+ if (exceptionState.hadException())
return 0;
- return processContents(EXTRACT_CONTENTS, es);
+ return processContents(EXTRACT_CONTENTS, exceptionState);
}
-PassRefPtr<DocumentFragment> Range::cloneContents(ExceptionState& es)
+PassRefPtr<DocumentFragment> Range::cloneContents(ExceptionState& exceptionState)
{
if (!m_start.container()) {
- es.throwDOMException(InvalidStateError);
+ exceptionState.throwDOMException(InvalidStateError, "The range has no container. Perhaps 'detatch()' has been invoked on this object?");
return 0;
}
- return processContents(CLONE_CONTENTS, es);
+ return processContents(CLONE_CONTENTS, exceptionState);
}
-void Range::insertNode(PassRefPtr<Node> prpNewNode, ExceptionState& es)
+void Range::insertNode(PassRefPtr<Node> prpNewNode, ExceptionState& exceptionState)
{
RefPtr<Node> newNode = prpNewNode;
if (!m_start.container()) {
- es.throwDOMException(InvalidStateError);
+ exceptionState.throwDOMException(InvalidStateError, "The range has no container. Perhaps 'detatch()' has been invoked on this object?");
return;
}
if (!newNode) {
- es.throwDOMException(NotFoundError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
return;
}
@@ -965,7 +963,7 @@ void Range::insertNode(PassRefPtr<Node> prpNewNode, ExceptionState& es)
// an extra one here - if a text node is going to split, it must have a parent to insert into
bool startIsText = m_start.container()->isTextNode();
if (startIsText && !m_start.container()->parentNode()) {
- es.throwDOMException(HierarchyRequestError);
+ exceptionState.throwUninformativeAndGenericDOMException(HierarchyRequestError);
return;
}
@@ -984,7 +982,7 @@ void Range::insertNode(PassRefPtr<Node> prpNewNode, ExceptionState& es)
numNewChildren = 0;
for (Node* c = newNode->firstChild(); c; c = c->nextSibling()) {
if (!checkAgainst->childTypeAllowed(c->nodeType())) {
- es.throwDOMException(HierarchyRequestError);
+ exceptionState.throwUninformativeAndGenericDOMException(HierarchyRequestError);
return;
}
++numNewChildren;
@@ -992,14 +990,14 @@ void Range::insertNode(PassRefPtr<Node> prpNewNode, ExceptionState& es)
} else {
numNewChildren = 1;
if (!checkAgainst->childTypeAllowed(newNodeType)) {
- es.throwDOMException(HierarchyRequestError);
+ exceptionState.throwUninformativeAndGenericDOMException(HierarchyRequestError);
return;
}
}
for (Node* n = m_start.container(); n; n = n->parentNode()) {
if (n == newNode) {
- es.throwDOMException(HierarchyRequestError);
+ exceptionState.throwUninformativeAndGenericDOMException(HierarchyRequestError);
return;
}
}
@@ -1010,11 +1008,11 @@ void Range::insertNode(PassRefPtr<Node> prpNewNode, ExceptionState& es)
case Node::ENTITY_NODE:
case Node::NOTATION_NODE:
case Node::DOCUMENT_NODE:
- es.throwDOMException(InvalidNodeTypeError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidNodeTypeError);
return;
default:
if (newNode->isShadowRoot()) {
- es.throwDOMException(InvalidNodeTypeError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidNodeTypeError);
return;
}
break;
@@ -1025,17 +1023,17 @@ void Range::insertNode(PassRefPtr<Node> prpNewNode, ExceptionState& es)
RefPtr<Node> container;
if (startIsText) {
container = m_start.container();
- RefPtr<Text> newText = toText(container.get())->splitText(m_start.offset(), es);
- if (es.hadException())
+ RefPtr<Text> newText = toText(container)->splitText(m_start.offset(), exceptionState);
+ if (exceptionState.hadException())
return;
container = m_start.container();
- container->parentNode()->insertBefore(newNode.release(), newText.get(), es);
- if (es.hadException())
+ container->parentNode()->insertBefore(newNode.release(), newText.get(), exceptionState);
+ if (exceptionState.hadException())
return;
if (collapsed)
- m_end.setToBeforeChild(newText.get());
+ m_end.setToBeforeChild(*newText);
} else {
RefPtr<Node> lastChild = (newNodeType == Node::DOCUMENT_FRAGMENT_NODE) ? newNode->lastChild() : newNode;
if (lastChild && lastChild == m_start.childBefore()) {
@@ -1043,13 +1041,13 @@ void Range::insertNode(PassRefPtr<Node> prpNewNode, ExceptionState& es)
// the inserted nodes.
Node* firstChild = (newNodeType == Node::DOCUMENT_FRAGMENT_NODE) ? newNode->firstChild() : newNode.get();
ASSERT(firstChild);
- m_start.setToBeforeChild(firstChild);
+ m_start.setToBeforeChild(*firstChild);
return;
}
container = m_start.container();
- container->insertBefore(newNode.release(), container->childNode(m_start.offset()), es);
- if (es.hadException())
+ container->insertBefore(newNode.release(), container->childNode(m_start.offset()), exceptionState);
+ if (exceptionState.hadException())
return;
// Note that m_start.offset() may have changed as a result of container->insertBefore,
@@ -1059,17 +1057,17 @@ void Range::insertNode(PassRefPtr<Node> prpNewNode, ExceptionState& es)
}
}
-String Range::toString(ExceptionState& es) const
+String Range::toString(ExceptionState& exceptionState) const
{
if (!m_start.container()) {
- es.throwDOMException(InvalidStateError);
+ exceptionState.throwDOMException(InvalidStateError, "The range has no container. Perhaps 'detatch()' has been invoked on this object?");
return String();
}
StringBuilder builder;
Node* pastLast = pastLastNode();
- for (Node* n = firstNode(); n != pastLast; n = NodeTraversal::next(n)) {
+ for (Node* n = firstNode(); n != pastLast; n = NodeTraversal::next(*n)) {
if (n->nodeType() == Node::TEXT_NODE || n->nodeType() == Node::CDATA_SECTION_NODE) {
String data = toCharacterData(n)->data();
int length = data.length();
@@ -1099,20 +1097,20 @@ String Range::text() const
return plainText(this);
}
-PassRefPtr<DocumentFragment> Range::createContextualFragment(const String& markup, ExceptionState& es)
+PassRefPtr<DocumentFragment> Range::createContextualFragment(const String& markup, ExceptionState& exceptionState)
{
if (!m_start.container()) {
- es.throwDOMException(InvalidStateError);
+ exceptionState.throwDOMException(InvalidStateError, "The range has no container. Perhaps 'detatch()' has been invoked on this object?");
return 0;
}
Node* element = m_start.container()->isElementNode() ? m_start.container() : m_start.container()->parentNode();
if (!element || !element->isHTMLElement()) {
- es.throwDOMException(NotSupportedError);
+ exceptionState.throwDOMException(NotSupportedError, "The range's container must be an HTML element.");
return 0;
}
- RefPtr<DocumentFragment> fragment = WebCore::createContextualFragment(markup, toHTMLElement(element), AllowScriptingContentAndDoNotMarkAlreadyStarted, es);
+ RefPtr<DocumentFragment> fragment = WebCore::createContextualFragment(markup, toHTMLElement(element), AllowScriptingContentAndDoNotMarkAlreadyStarted, exceptionState);
if (!fragment)
return 0;
@@ -1120,11 +1118,11 @@ PassRefPtr<DocumentFragment> Range::createContextualFragment(const String& marku
}
-void Range::detach(ExceptionState& es)
+void Range::detach(ExceptionState& exceptionState)
{
// Check first to see if we've already detached:
if (!m_start.container()) {
- es.throwDOMException(InvalidStateError);
+ exceptionState.throwDOMException(InvalidStateError, "The range has no container. Perhaps 'detatch()' has been invoked on this object?");
return;
}
@@ -1134,23 +1132,23 @@ void Range::detach(ExceptionState& es)
m_end.clear();
}
-Node* Range::checkNodeWOffset(Node* n, int offset, ExceptionState& es) const
+Node* Range::checkNodeWOffset(Node* n, int offset, ExceptionState& exceptionState) const
{
switch (n->nodeType()) {
case Node::DOCUMENT_TYPE_NODE:
case Node::ENTITY_NODE:
case Node::NOTATION_NODE:
- es.throwDOMException(InvalidNodeTypeError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidNodeTypeError);
return 0;
case Node::CDATA_SECTION_NODE:
case Node::COMMENT_NODE:
case Node::TEXT_NODE:
if (static_cast<unsigned>(offset) > toCharacterData(n)->length())
- es.throwDOMException(IndexSizeError);
+ exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
return 0;
case Node::PROCESSING_INSTRUCTION_NODE:
if (static_cast<unsigned>(offset) > toProcessingInstruction(n)->data().length())
- es.throwDOMException(IndexSizeError);
+ exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
return 0;
case Node::ATTRIBUTE_NODE:
case Node::DOCUMENT_FRAGMENT_NODE:
@@ -1161,7 +1159,7 @@ Node* Range::checkNodeWOffset(Node* n, int offset, ExceptionState& es) const
return 0;
Node* childBefore = n->childNode(offset - 1);
if (!childBefore)
- es.throwDOMException(IndexSizeError);
+ exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
return childBefore;
}
}
@@ -1169,15 +1167,15 @@ Node* Range::checkNodeWOffset(Node* n, int offset, ExceptionState& es) const
return 0;
}
-void Range::checkNodeBA(Node* n, ExceptionState& es, const char* methodName) const
+void Range::checkNodeBA(Node* n, ExceptionState& exceptionState) const
{
if (!m_start.container()) {
- es.throwDOMException(InvalidStateError);
+ exceptionState.throwDOMException(InvalidStateError, "The range has no container. Perhaps 'detatch()' has been invoked on this object?");
return;
}
if (!n) {
- es.throwDOMException(NotFoundError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
return;
}
@@ -1186,7 +1184,7 @@ void Range::checkNodeBA(Node* n, ExceptionState& es, const char* methodName) con
// or if refNode is a Document, DocumentFragment, ShadowRoot, Attr, Entity, or Notation node.
if (!n->parentNode()) {
- es.throwDOMException(InvalidNodeTypeError, ExceptionMessages::failedToExecute(methodName, "Range", "the given Node has no parent."));
+ exceptionState.throwDOMException(InvalidNodeTypeError, "the given Node has no parent.");
return;
}
@@ -1196,7 +1194,7 @@ void Range::checkNodeBA(Node* n, ExceptionState& es, const char* methodName) con
case Node::DOCUMENT_NODE:
case Node::ENTITY_NODE:
case Node::NOTATION_NODE:
- es.throwDOMException(InvalidNodeTypeError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidNodeTypeError);
return;
case Node::CDATA_SECTION_NODE:
case Node::COMMENT_NODE:
@@ -1226,62 +1224,62 @@ void Range::checkNodeBA(Node* n, ExceptionState& es, const char* methodName) con
case Node::PROCESSING_INSTRUCTION_NODE:
case Node::TEXT_NODE:
case Node::XPATH_NAMESPACE_NODE:
- es.throwDOMException(InvalidNodeTypeError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidNodeTypeError);
return;
}
}
-PassRefPtr<Range> Range::cloneRange(ExceptionState& es) const
+PassRefPtr<Range> Range::cloneRange(ExceptionState& exceptionState) const
{
if (!m_start.container()) {
- es.throwDOMException(InvalidStateError);
+ exceptionState.throwDOMException(InvalidStateError, "The range has no container. Perhaps 'detatch()' has been invoked on this object?");
return 0;
}
return Range::create(*m_ownerDocument.get(), m_start.container(), m_start.offset(), m_end.container(), m_end.offset());
}
-void Range::setStartAfter(Node* refNode, ExceptionState& es)
+void Range::setStartAfter(Node* refNode, ExceptionState& exceptionState)
{
- checkNodeBA(refNode, es, "setStartAfter");
- if (es.hadException())
+ checkNodeBA(refNode, exceptionState);
+ if (exceptionState.hadException())
return;
- setStart(refNode->parentNode(), refNode->nodeIndex() + 1, es);
+ setStart(refNode->parentNode(), refNode->nodeIndex() + 1, exceptionState);
}
-void Range::setEndBefore(Node* refNode, ExceptionState& es)
+void Range::setEndBefore(Node* refNode, ExceptionState& exceptionState)
{
- checkNodeBA(refNode, es, "setEndBefore");
- if (es.hadException())
+ checkNodeBA(refNode, exceptionState);
+ if (exceptionState.hadException())
return;
- setEnd(refNode->parentNode(), refNode->nodeIndex(), es);
+ setEnd(refNode->parentNode(), refNode->nodeIndex(), exceptionState);
}
-void Range::setEndAfter(Node* refNode, ExceptionState& es)
+void Range::setEndAfter(Node* refNode, ExceptionState& exceptionState)
{
- checkNodeBA(refNode, es, "setEndAfter");
- if (es.hadException())
+ checkNodeBA(refNode, exceptionState);
+ if (exceptionState.hadException())
return;
- setEnd(refNode->parentNode(), refNode->nodeIndex() + 1, es);
+ setEnd(refNode->parentNode(), refNode->nodeIndex() + 1, exceptionState);
}
-void Range::selectNode(Node* refNode, ExceptionState& es)
+void Range::selectNode(Node* refNode, ExceptionState& exceptionState)
{
if (!m_start.container()) {
- es.throwDOMException(InvalidStateError);
+ exceptionState.throwDOMException(InvalidStateError, "The range has no container. Perhaps 'detatch()' has been invoked on this object?");
return;
}
if (!refNode) {
- es.throwDOMException(NotFoundError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
return;
}
if (!refNode->parentNode()) {
- es.throwDOMException(InvalidNodeTypeError, ExceptionMessages::failedToExecute("selectNode", "Range", "the given Node has no parent."));
+ exceptionState.throwDOMException(InvalidNodeTypeError, "the given Node has no parent.");
return;
}
@@ -1303,7 +1301,7 @@ void Range::selectNode(Node* refNode, ExceptionState& es)
case Node::DOCUMENT_TYPE_NODE:
case Node::ENTITY_NODE:
case Node::NOTATION_NODE:
- es.throwDOMException(InvalidNodeTypeError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidNodeTypeError);
return;
}
}
@@ -1322,26 +1320,26 @@ void Range::selectNode(Node* refNode, ExceptionState& es)
case Node::DOCUMENT_NODE:
case Node::ENTITY_NODE:
case Node::NOTATION_NODE:
- es.throwDOMException(InvalidNodeTypeError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidNodeTypeError);
return;
}
- if (m_ownerDocument != &refNode->document())
+ if (m_ownerDocument != refNode->document())
setDocument(refNode->document());
setStartBefore(refNode);
setEndAfter(refNode);
}
-void Range::selectNodeContents(Node* refNode, ExceptionState& es)
+void Range::selectNodeContents(Node* refNode, ExceptionState& exceptionState)
{
if (!m_start.container()) {
- es.throwDOMException(InvalidStateError);
+ exceptionState.throwDOMException(InvalidStateError, "The range has no container. Perhaps 'detatch()' has been invoked on this object?");
return;
}
if (!refNode) {
- es.throwDOMException(NotFoundError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
return;
}
@@ -1362,29 +1360,29 @@ void Range::selectNodeContents(Node* refNode, ExceptionState& es)
case Node::DOCUMENT_TYPE_NODE:
case Node::ENTITY_NODE:
case Node::NOTATION_NODE:
- es.throwDOMException(InvalidNodeTypeError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidNodeTypeError);
return;
}
}
- if (m_ownerDocument != &refNode->document())
+ if (m_ownerDocument != refNode->document())
setDocument(refNode->document());
m_start.setToStartOfNode(refNode);
m_end.setToEndOfNode(refNode);
}
-void Range::surroundContents(PassRefPtr<Node> passNewParent, ExceptionState& es)
+void Range::surroundContents(PassRefPtr<Node> passNewParent, ExceptionState& exceptionState)
{
RefPtr<Node> newParent = passNewParent;
if (!m_start.container()) {
- es.throwDOMException(InvalidStateError);
+ exceptionState.throwDOMException(InvalidStateError, "The range has no container. Perhaps 'detatch()' has been invoked on this object?");
return;
}
if (!newParent) {
- es.throwDOMException(NotFoundError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
return;
}
@@ -1397,7 +1395,7 @@ void Range::surroundContents(PassRefPtr<Node> passNewParent, ExceptionState& es)
case Node::DOCUMENT_TYPE_NODE:
case Node::ENTITY_NODE:
case Node::NOTATION_NODE:
- es.throwDOMException(InvalidNodeTypeError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidNodeTypeError);
return;
case Node::CDATA_SECTION_NODE:
case Node::COMMENT_NODE:
@@ -1417,12 +1415,12 @@ void Range::surroundContents(PassRefPtr<Node> passNewParent, ExceptionState& es)
if (parentOfNewParent->isCharacterDataNode())
parentOfNewParent = parentOfNewParent->parentNode();
if (!parentOfNewParent || !parentOfNewParent->childTypeAllowed(newParent->nodeType())) {
- es.throwDOMException(HierarchyRequestError);
+ exceptionState.throwUninformativeAndGenericDOMException(HierarchyRequestError);
return;
}
if (newParent->contains(m_start.container())) {
- es.throwDOMException(HierarchyRequestError);
+ exceptionState.throwUninformativeAndGenericDOMException(HierarchyRequestError);
return;
}
@@ -1437,50 +1435,50 @@ void Range::surroundContents(PassRefPtr<Node> passNewParent, ExceptionState& es)
if (endNonTextContainer->nodeType() == Node::TEXT_NODE)
endNonTextContainer = endNonTextContainer->parentNode();
if (startNonTextContainer != endNonTextContainer) {
- es.throwDOMException(InvalidStateError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
return;
}
while (Node* n = newParent->firstChild()) {
- toContainerNode(newParent.get())->removeChild(n, es);
- if (es.hadException())
+ toContainerNode(newParent)->removeChild(n, exceptionState);
+ if (exceptionState.hadException())
return;
}
- RefPtr<DocumentFragment> fragment = extractContents(es);
- if (es.hadException())
+ RefPtr<DocumentFragment> fragment = extractContents(exceptionState);
+ if (exceptionState.hadException())
return;
- insertNode(newParent, es);
- if (es.hadException())
+ insertNode(newParent, exceptionState);
+ if (exceptionState.hadException())
return;
- newParent->appendChild(fragment.release(), es);
- if (es.hadException())
+ newParent->appendChild(fragment.release(), exceptionState);
+ if (exceptionState.hadException())
return;
- selectNode(newParent.get(), es);
+ selectNode(newParent.get(), exceptionState);
}
-void Range::setStartBefore(Node* refNode, ExceptionState& es)
+void Range::setStartBefore(Node* refNode, ExceptionState& exceptionState)
{
- checkNodeBA(refNode, es, "setStartBefore");
- if (es.hadException())
+ checkNodeBA(refNode, exceptionState);
+ if (exceptionState.hadException())
return;
- setStart(refNode->parentNode(), refNode->nodeIndex(), es);
+ setStart(refNode->parentNode(), refNode->nodeIndex(), exceptionState);
}
-void Range::checkDeleteExtract(ExceptionState& es)
+void Range::checkDeleteExtract(ExceptionState& exceptionState)
{
if (!m_start.container()) {
- es.throwDOMException(InvalidStateError);
+ exceptionState.throwDOMException(InvalidStateError, "The range has no container. Perhaps 'detatch()' has been invoked on this object?");
return;
}
- if (!commonAncestorContainer(es) || es.hadException())
+ if (!commonAncestorContainer(exceptionState) || exceptionState.hadException())
return;
Node* pastLast = pastLastNode();
- for (Node* n = firstNode(); n != pastLast; n = NodeTraversal::next(n)) {
+ for (Node* n = firstNode(); n != pastLast; n = NodeTraversal::next(*n)) {
if (n->nodeType() == Node::DOCUMENT_TYPE_NODE) {
- es.throwDOMException(HierarchyRequestError);
+ exceptionState.throwUninformativeAndGenericDOMException(HierarchyRequestError);
return;
}
}
@@ -1496,7 +1494,7 @@ Node* Range::firstNode() const
return child;
if (!m_start.offset())
return m_start.container();
- return NodeTraversal::nextSkippingChildren(m_start.container());
+ return NodeTraversal::nextSkippingChildren(*m_start.container());
}
ShadowRoot* Range::shadowRoot() const
@@ -1509,10 +1507,10 @@ Node* Range::pastLastNode() const
if (!m_start.container() || !m_end.container())
return 0;
if (m_end.container()->offsetInCharacters())
- return NodeTraversal::nextSkippingChildren(m_end.container());
+ return NodeTraversal::nextSkippingChildren(*m_end.container());
if (Node* child = m_end.container()->childNode(m_end.offset()))
return child;
- return NodeTraversal::nextSkippingChildren(m_end.container());
+ return NodeTraversal::nextSkippingChildren(*m_end.container());
}
IntRect Range::boundingBox() const
@@ -1541,7 +1539,7 @@ void Range::textRects(Vector<IntRect>& rects, bool useSelectionHeight, RangeInFi
bool someFixed = false;
Node* stopNode = pastLastNode();
- for (Node* node = firstNode(); node != stopNode; node = NodeTraversal::next(node)) {
+ for (Node* node = firstNode(); node != stopNode; node = NodeTraversal::next(*node)) {
RenderObject* r = node->renderer();
if (!r || !r->isText())
continue;
@@ -1573,7 +1571,7 @@ void Range::textQuads(Vector<FloatQuad>& quads, bool useSelectionHeight, RangeIn
bool someFixed = false;
Node* stopNode = pastLastNode();
- for (Node* node = firstNode(); node != stopNode; node = NodeTraversal::next(node)) {
+ for (Node* node = firstNode(); node != stopNode; node = NodeTraversal::next(*node)) {
RenderObject* r = node->renderer();
if (!r || !r->isText())
continue;
@@ -1664,7 +1662,7 @@ static inline void boundaryNodeChildrenChanged(RangeBoundaryPoint& boundary, Con
void Range::nodeChildrenChanged(ContainerNode* container)
{
ASSERT(container);
- ASSERT(&container->document() == m_ownerDocument);
+ ASSERT(container->document() == m_ownerDocument);
boundaryNodeChildrenChanged(m_start, container);
boundaryNodeChildrenChanged(m_end, container);
}
@@ -1689,12 +1687,12 @@ static inline void boundaryNodeChildrenWillBeRemoved(RangeBoundaryPoint& boundar
void Range::nodeChildrenWillBeRemoved(ContainerNode* container)
{
ASSERT(container);
- ASSERT(&container->document() == m_ownerDocument);
+ ASSERT(container->document() == m_ownerDocument);
boundaryNodeChildrenWillBeRemoved(m_start, container);
boundaryNodeChildrenWillBeRemoved(m_end, container);
}
-static inline void boundaryNodeWillBeRemoved(RangeBoundaryPoint& boundary, Node* nodeToBeRemoved)
+static inline void boundaryNodeWillBeRemoved(RangeBoundaryPoint& boundary, Node& nodeToBeRemoved)
{
if (boundary.childBefore() == nodeToBeRemoved) {
boundary.childBeforeWillBeRemoved();
@@ -1709,15 +1707,14 @@ static inline void boundaryNodeWillBeRemoved(RangeBoundaryPoint& boundary, Node*
}
}
-void Range::nodeWillBeRemoved(Node* node)
+void Range::nodeWillBeRemoved(Node& node)
{
- ASSERT(node);
- ASSERT(&node->document() == m_ownerDocument);
+ ASSERT(node.document() == m_ownerDocument);
ASSERT(node != m_ownerDocument);
// FIXME: Once DOMNodeRemovedFromDocument mutation event removed, we
// should change following if-statement to ASSERT(!node->parentNode).
- if (!node->parentNode())
+ if (!node.parentNode())
return;
boundaryNodeWillBeRemoved(m_start, node);
boundaryNodeWillBeRemoved(m_end, node);
@@ -1736,7 +1733,7 @@ static inline void boundaryTextInserted(RangeBoundaryPoint& boundary, Node* text
void Range::didInsertText(Node* text, unsigned offset, unsigned length)
{
ASSERT(text);
- ASSERT(&text->document() == m_ownerDocument);
+ ASSERT(text->document() == m_ownerDocument);
boundaryTextInserted(m_start, text, offset, length);
boundaryTextInserted(m_end, text, offset, length);
}
@@ -1757,7 +1754,7 @@ static inline void boundaryTextRemoved(RangeBoundaryPoint& boundary, Node* text,
void Range::didRemoveText(Node* text, unsigned offset, unsigned length)
{
ASSERT(text);
- ASSERT(&text->document() == m_ownerDocument);
+ ASSERT(text->document() == m_ownerDocument);
boundaryTextRemoved(m_start, text, offset, length);
boundaryTextRemoved(m_end, text, offset, length);
}
@@ -1773,7 +1770,7 @@ static inline void boundaryTextNodesMerged(RangeBoundaryPoint& boundary, NodeWit
void Range::didMergeTextNodes(NodeWithIndex& oldNode, unsigned offset)
{
ASSERT(oldNode.node());
- ASSERT(&oldNode.node()->document() == m_ownerDocument);
+ ASSERT(oldNode.node()->document() == m_ownerDocument);
ASSERT(oldNode.node()->parentNode());
ASSERT(oldNode.node()->isTextNode());
ASSERT(oldNode.node()->previousSibling());
@@ -1795,7 +1792,7 @@ static inline void boundaryTextNodeSplit(RangeBoundaryPoint& boundary, Text* old
void Range::didSplitTextNode(Text* oldNode)
{
ASSERT(oldNode);
- ASSERT(&oldNode->document() == m_ownerDocument);
+ ASSERT(oldNode->document() == m_ownerDocument);
ASSERT(oldNode->parentNode());
ASSERT(oldNode->isTextNode());
ASSERT(oldNode->nextSibling());
@@ -1804,7 +1801,7 @@ void Range::didSplitTextNode(Text* oldNode)
boundaryTextNodeSplit(m_end, oldNode);
}
-void Range::expand(const String& unit, ExceptionState& es)
+void Range::expand(const String& unit, ExceptionState& exceptionState)
{
VisiblePosition start(startPosition());
VisiblePosition end(endPosition());
@@ -1822,8 +1819,8 @@ void Range::expand(const String& unit, ExceptionState& es)
end = endOfDocument(end);
} else
return;
- setStart(start.deepEquivalent().containerNode(), start.deepEquivalent().computeOffsetInContainerNode(), es);
- setEnd(end.deepEquivalent().containerNode(), end.deepEquivalent().computeOffsetInContainerNode(), es);
+ setStart(start.deepEquivalent().containerNode(), start.deepEquivalent().computeOffsetInContainerNode(), exceptionState);
+ setEnd(end.deepEquivalent().containerNode(), end.deepEquivalent().computeOffsetInContainerNode(), exceptionState);
}
PassRefPtr<ClientRectList> Range::getClientRects() const
@@ -1851,30 +1848,30 @@ void Range::getBorderAndTextQuads(Vector<FloatQuad>& quads) const
Node* stopNode = pastLastNode();
HashSet<Node*> nodeSet;
- for (Node* node = firstNode(); node != stopNode; node = NodeTraversal::next(node)) {
+ for (Node* node = firstNode(); node != stopNode; node = NodeTraversal::next(*node)) {
if (node->isElementNode())
nodeSet.add(node);
}
- for (Node* node = firstNode(); node != stopNode; node = NodeTraversal::next(node)) {
+ for (Node* node = firstNode(); node != stopNode; node = NodeTraversal::next(*node)) {
if (node->isElementNode()) {
if (!nodeSet.contains(node->parentNode())) {
if (RenderBoxModelObject* renderBoxModelObject = toElement(node)->renderBoxModelObject()) {
Vector<FloatQuad> elementQuads;
renderBoxModelObject->absoluteQuads(elementQuads);
- m_ownerDocument->adjustFloatQuadsForScrollAndAbsoluteZoom(elementQuads, renderBoxModelObject);
+ m_ownerDocument->adjustFloatQuadsForScrollAndAbsoluteZoom(elementQuads, *renderBoxModelObject);
quads.append(elementQuads);
}
}
} else if (node->isTextNode()) {
if (RenderObject* renderer = toText(node)->renderer()) {
- RenderText* renderText = toRenderText(renderer);
+ RenderText& renderText = toRenderText(*renderer);
int startOffset = (node == startContainer) ? m_start.offset() : 0;
int endOffset = (node == endContainer) ? m_end.offset() : INT_MAX;
Vector<FloatQuad> textQuads;
- renderText->absoluteQuadsForRange(textQuads, startOffset, endOffset);
+ renderText.absoluteQuadsForRange(textQuads, startOffset, endOffset);
m_ownerDocument->adjustFloatQuadsForScrollAndAbsoluteZoom(textQuads, renderText);
quads.append(textQuads);
diff --git a/chromium/third_party/WebKit/Source/core/dom/Range.h b/chromium/third_party/WebKit/Source/core/dom/Range.h
index 88501446fd7..3a662f19cb0 100644
--- a/chromium/third_party/WebKit/Source/core/dom/Range.h
+++ b/chromium/third_party/WebKit/Source/core/dom/Range.h
@@ -28,8 +28,8 @@
#include "bindings/v8/ExceptionStatePlaceholder.h"
#include "bindings/v8/ScriptWrappable.h"
#include "core/dom/RangeBoundaryPoint.h"
-#include "core/platform/graphics/FloatRect.h"
-#include "core/platform/graphics/IntRect.h"
+#include "platform/geometry/FloatRect.h"
+#include "platform/geometry/IntRect.h"
#include "wtf/Forward.h"
#include "wtf/RefCounted.h"
#include "wtf/Vector.h"
@@ -130,7 +130,7 @@ public:
void nodeChildrenChanged(ContainerNode*);
void nodeChildrenWillBeRemoved(ContainerNode*);
- void nodeWillBeRemoved(Node*);
+ void nodeWillBeRemoved(Node&);
void didInsertText(Node*, unsigned offset, unsigned length);
void didRemoveText(Node*, unsigned offset, unsigned length);
@@ -156,7 +156,7 @@ private:
void setDocument(Document&);
Node* checkNodeWOffset(Node*, int offset, ExceptionState&) const;
- void checkNodeBA(Node*, ExceptionState&, const char* methodName) const;
+ void checkNodeBA(Node*, ExceptionState&) const;
void checkDeleteExtract(ExceptionState&);
int maxStartOffset() const;
int maxEndOffset() const;
diff --git a/chromium/third_party/WebKit/Source/core/dom/Range.idl b/chromium/third_party/WebKit/Source/core/dom/Range.idl
index 32edd56faba..d3dd1eb2f0e 100644
--- a/chromium/third_party/WebKit/Source/core/dom/Range.idl
+++ b/chromium/third_party/WebKit/Source/core/dom/Range.idl
@@ -21,27 +21,25 @@
// Introduced in DOM Level 2:
[
Constructor,
- ConstructorCallWith=Document
+ ConstructorCallWith=Document,
] interface Range {
- [GetterRaisesException] readonly attribute Node startContainer;
- [GetterRaisesException] readonly attribute long startOffset;
- [GetterRaisesException] readonly attribute Node endContainer;
- [GetterRaisesException] readonly attribute long endOffset;
- [GetterRaisesException] readonly attribute boolean collapsed;
- [GetterRaisesException] readonly attribute Node commonAncestorContainer;
-
- [RaisesException] void setStart([Default=Undefined] optional Node refNode,
- [Default=Undefined] optional long offset);
- [RaisesException] void setEnd([Default=Undefined] optional Node refNode,
- [Default=Undefined] optional long offset);
- [RaisesException] void setStartBefore([Default=Undefined] optional Node refNode);
- [RaisesException] void setStartAfter([Default=Undefined] optional Node refNode);
- [RaisesException] void setEndBefore([Default=Undefined] optional Node refNode);
- [RaisesException] void setEndAfter([Default=Undefined] optional Node refNode);
+ [RaisesException=Getter] readonly attribute Node startContainer;
+ [RaisesException=Getter] readonly attribute long startOffset;
+ [RaisesException=Getter] readonly attribute Node endContainer;
+ [RaisesException=Getter] readonly attribute long endOffset;
+ [RaisesException=Getter] readonly attribute boolean collapsed;
+ [RaisesException=Getter] readonly attribute Node commonAncestorContainer;
+
+ [RaisesException] void setStart(Node refNode, long offset);
+ [RaisesException] void setEnd(Node refNode, long offset);
+ [RaisesException] void setStartBefore(Node refNode);
+ [RaisesException] void setStartAfter(Node refNode);
+ [RaisesException] void setEndBefore(Node refNode);
+ [RaisesException] void setEndAfter(Node refNode);
[RaisesException] void collapse([Default=Undefined] optional boolean toStart);
- [RaisesException] void selectNode([Default=Undefined] optional Node refNode);
- [RaisesException] void selectNodeContents([Default=Undefined] optional Node refNode);
+ [RaisesException] void selectNode(Node refNode);
+ [RaisesException] void selectNodeContents(Node refNode);
// CompareHow
const unsigned short START_TO_START = 0;
@@ -49,46 +47,41 @@
const unsigned short END_TO_END = 2;
const unsigned short END_TO_START = 3;
- [RaisesException] short compareBoundaryPoints([Default=Undefined] optional CompareHow how,
- [Default=Undefined] optional Range sourceRange);
+ [RaisesException] short compareBoundaryPoints(CompareHow how, Range sourceRange);
- [RaisesException, CustomElementCallbacks=Enable] void deleteContents();
- [RaisesException, CustomElementCallbacks=Enable] DocumentFragment extractContents();
- [RaisesException, CustomElementCallbacks=Enable] DocumentFragment cloneContents();
- [RaisesException, CustomElementCallbacks=Enable] void insertNode([Default=Undefined] optional Node newNode);
- [RaisesException, CustomElementCallbacks=Enable] void surroundContents([Default=Undefined] optional Node newParent);
+ [RaisesException, CustomElementCallbacks] void deleteContents();
+ [RaisesException, CustomElementCallbacks] DocumentFragment extractContents();
+ [RaisesException, CustomElementCallbacks] DocumentFragment cloneContents();
+ [RaisesException, CustomElementCallbacks] void insertNode(Node newNode);
+ [RaisesException, CustomElementCallbacks] void surroundContents(Node newParent);
[RaisesException] Range cloneRange();
[RaisesException] DOMString toString();
[RaisesException] void detach();
+ [RaisesException] boolean isPointInRange(Node refNode, long offset);
+ [RaisesException] short comparePoint(Node refNode, long offset);
+
+ [RaisesException] boolean intersectsNode(Node refNode);
+
// CSSOM View Module API extensions
ClientRectList getClientRects();
ClientRect getBoundingClientRect();
- // extensions
+ // DOM Parsing and Serialization
- [RaisesException, CustomElementCallbacks=Enable] DocumentFragment createContextualFragment([Default=Undefined] optional DOMString html);
+ [RaisesException, CustomElementCallbacks] DocumentFragment createContextualFragment(DOMString html);
// WebKit extensions
- [RaisesException] boolean intersectsNode([Default=Undefined] optional Node refNode);
-
- [RaisesException] short compareNode([Default=Undefined] optional Node refNode);
-
// CompareResults
const unsigned short NODE_BEFORE = 0;
const unsigned short NODE_AFTER = 1;
const unsigned short NODE_BEFORE_AND_AFTER = 2;
const unsigned short NODE_INSIDE = 3;
- [RaisesException] short comparePoint([Default=Undefined] optional Node refNode,
- [Default=Undefined] optional long offset);
-
- [RaisesException] boolean isPointInRange([Default=Undefined] optional Node refNode,
- [Default=Undefined] optional long offset);
+ [RaisesException] short compareNode([Default=Undefined] optional Node refNode);
[RaisesException] void expand([Default=Undefined] optional DOMString unit);
};
-
diff --git a/chromium/third_party/WebKit/Source/core/dom/RangeBoundaryPoint.h b/chromium/third_party/WebKit/Source/core/dom/RangeBoundaryPoint.h
index c1a4625ffdd..7574a89ef48 100644
--- a/chromium/third_party/WebKit/Source/core/dom/RangeBoundaryPoint.h
+++ b/chromium/third_party/WebKit/Source/core/dom/RangeBoundaryPoint.h
@@ -48,7 +48,7 @@ public:
void set(PassRefPtr<Node> container, int offset, Node* childBefore);
void setOffset(int offset);
- void setToBeforeChild(Node*);
+ void setToBeforeChild(Node&);
void setToStartOfNode(PassRefPtr<Node>);
void setToEndOfNode(PassRefPtr<Node>);
@@ -136,12 +136,11 @@ inline void RangeBoundaryPoint::setOffset(int offset)
m_offsetInContainer = offset;
}
-inline void RangeBoundaryPoint::setToBeforeChild(Node* child)
+inline void RangeBoundaryPoint::setToBeforeChild(Node& child)
{
- ASSERT(child);
- ASSERT(child->parentNode());
- m_childBeforeBoundary = child->previousSibling();
- m_containerNode = child->parentNode();
+ ASSERT(child.parentNode());
+ m_childBeforeBoundary = child.previousSibling();
+ m_containerNode = child.parentNode();
m_offsetInContainer = m_childBeforeBoundary ? invalidOffset : 0;
}
diff --git a/chromium/third_party/WebKit/Source/core/dom/RawDataDocumentParser.h b/chromium/third_party/WebKit/Source/core/dom/RawDataDocumentParser.h
index b56a694f7e4..f2adeed32f8 100644
--- a/chromium/third_party/WebKit/Source/core/dom/RawDataDocumentParser.h
+++ b/chromium/third_party/WebKit/Source/core/dom/RawDataDocumentParser.h
@@ -45,17 +45,14 @@ protected:
}
private:
- virtual size_t flush() OVERRIDE
+ virtual void flush() OVERRIDE
{
// Make sure appendBytes is called at least once.
appendBytes(0, 0);
- return 0;
}
virtual void insert(const SegmentedString&)
{
- // <https://bugs.webkit.org/show_bug.cgi?id=25397>: JS code can always call document.write, we need to handle it.
- ASSERT_NOT_REACHED();
}
virtual void append(PassRefPtr<StringImpl>)
diff --git a/chromium/third_party/WebKit/Source/core/dom/RegisteredEventListener.h b/chromium/third_party/WebKit/Source/core/dom/RegisteredEventListener.h
deleted file mode 100644
index 7dde5576a5c..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/RegisteredEventListener.h
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Copyright (C) 2001 Peter Kelly (pmk@post.com)
- * Copyright (C) 2001 Tobias Anton (anton@stud.fbi.fh-darmstadt.de)
- * Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
- * Copyright (C) 2003, 2004, 2005, 2006, 2008, 2009 Apple Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#ifndef RegisteredEventListener_h
-#define RegisteredEventListener_h
-
-#include "core/dom/EventListener.h"
-#include "wtf/RefPtr.h"
-
-namespace WebCore {
-
- class RegisteredEventListener {
- public:
- RegisteredEventListener(PassRefPtr<EventListener> listener, bool useCapture)
- : listener(listener)
- , useCapture(useCapture)
- {
- }
-
- RefPtr<EventListener> listener;
- bool useCapture;
- };
-
- inline bool operator==(const RegisteredEventListener& a, const RegisteredEventListener& b)
- {
- return *a.listener == *b.listener && a.useCapture == b.useCapture;
- }
-
-} // namespace WebCore
-
-#endif // RegisteredEventListener_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/RequestAnimationFrameCallback.h b/chromium/third_party/WebKit/Source/core/dom/RequestAnimationFrameCallback.h
index 768e4a167ae..417f6715a91 100644
--- a/chromium/third_party/WebKit/Source/core/dom/RequestAnimationFrameCallback.h
+++ b/chromium/third_party/WebKit/Source/core/dom/RequestAnimationFrameCallback.h
@@ -31,17 +31,15 @@
#ifndef RequestAnimationFrameCallback_h
#define RequestAnimationFrameCallback_h
-#include "wtf/RefCounted.h"
-
namespace WebCore {
-class RequestAnimationFrameCallback : public RefCounted<RequestAnimationFrameCallback> {
+class RequestAnimationFrameCallback {
public:
virtual ~RequestAnimationFrameCallback() { }
- virtual bool handleEvent(double highResTimeMs) = 0;
+ virtual void handleEvent(double highResTimeMs) = 0;
int m_id;
- bool m_firedOrCancelled;
+ bool m_cancelled;
bool m_useLegacyTimeBase;
};
diff --git a/chromium/third_party/WebKit/Source/core/dom/RequestAnimationFrameCallback.idl b/chromium/third_party/WebKit/Source/core/dom/RequestAnimationFrameCallback.idl
index d2f1d22b653..cb0ec6667be 100644
--- a/chromium/third_party/WebKit/Source/core/dom/RequestAnimationFrameCallback.idl
+++ b/chromium/third_party/WebKit/Source/core/dom/RequestAnimationFrameCallback.idl
@@ -31,5 +31,5 @@
callback interface RequestAnimationFrameCallback{
// highResTime is passed as high resolution timestamp, see
// http://www.w3.org/TR/hr-time/ for details.
- boolean handleEvent(double highResTime);
+ void handleEvent(double highResTime);
};
diff --git a/chromium/third_party/WebKit/Source/core/dom/ResourceProgressEvent.cpp b/chromium/third_party/WebKit/Source/core/dom/ResourceProgressEvent.cpp
deleted file mode 100644
index 55310bb7dc8..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/ResourceProgressEvent.cpp
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/dom/ResourceProgressEvent.h"
-
-namespace WebCore {
-
-ResourceProgressEvent::ResourceProgressEvent()
-{
- ScriptWrappable::init(this);
-}
-
-ResourceProgressEvent::ResourceProgressEvent(const AtomicString& type, bool lengthComputable, unsigned long long loaded, unsigned long long total, const String& url)
- : ProgressEvent(type, lengthComputable, loaded, total)
- , m_url(url)
-{
- ScriptWrappable::init(this);
-}
-
-const String& ResourceProgressEvent::url() const
-{
- return m_url;
-}
-
-const AtomicString& ResourceProgressEvent::interfaceName() const
-{
- return eventNames().interfaceForResourceProgressEvent;
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/dom/ResourceProgressEvent.h b/chromium/third_party/WebKit/Source/core/dom/ResourceProgressEvent.h
deleted file mode 100644
index 50e72263d0f..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/ResourceProgressEvent.h
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ResourceProgressEvent_h
-#define ResourceProgressEvent_h
-
-#include "core/dom/ProgressEvent.h"
-
-namespace WebCore {
-
-// ResourceProgressEvent is a non-standard class that is simply a ProgressEvent
-// with an additional read-only "url" property containing a string URL. This is
-// used by the Chromium NaCl integration to indicate to which resource the
-// event applies. This is useful because the NaCl integration will download
-// (and translate in the case of PNaCl) multiple binary files. It is not
-// constructable by web content at all, and so does not provide the usual
-// EventInit pattern for Event construction.
-class ResourceProgressEvent : public ProgressEvent {
-public:
- static PassRefPtr<ResourceProgressEvent> create()
- {
- return adoptRef(new ResourceProgressEvent);
- }
- static PassRefPtr<ResourceProgressEvent> create(const AtomicString& type, bool lengthComputable, unsigned long long loaded, unsigned long long total, const String& url)
- {
- return adoptRef(new ResourceProgressEvent(type, lengthComputable, loaded, total, url));
- }
-
- const String& url() const;
-
- virtual const AtomicString& interfaceName() const;
-
-protected:
- ResourceProgressEvent();
- ResourceProgressEvent(const AtomicString& type, bool lengthComputable, unsigned long long loaded, unsigned long long total, const String& url);
-
-private:
- String m_url;
-};
-
-} // namespace WebCore
-
-#endif // ResourceProgressEvent_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/SandboxFlags.cpp b/chromium/third_party/WebKit/Source/core/dom/SandboxFlags.cpp
new file mode 100644
index 00000000000..1ebd0c3fe66
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/SandboxFlags.cpp
@@ -0,0 +1,92 @@
+/*
+ * Copyright (C) 2013 Google Inc. All Rights Reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY GOOGLE, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "config.h"
+#include "core/dom/SandboxFlags.h"
+
+#include "core/html/parser/HTMLParserIdioms.h"
+#include "wtf/text/StringBuilder.h"
+
+namespace WebCore {
+
+SandboxFlags parseSandboxPolicy(const String& policy, String& invalidTokensErrorMessage)
+{
+ // http://www.w3.org/TR/html5/the-iframe-element.html#attr-iframe-sandbox
+ // Parse the unordered set of unique space-separated tokens.
+ SandboxFlags flags = SandboxAll;
+ unsigned length = policy.length();
+ unsigned start = 0;
+ unsigned numberOfTokenErrors = 0;
+ StringBuilder tokenErrors;
+ while (true) {
+ while (start < length && isHTMLSpace<UChar>(policy[start]))
+ ++start;
+ if (start >= length)
+ break;
+ unsigned end = start + 1;
+ while (end < length && !isHTMLSpace<UChar>(policy[end]))
+ ++end;
+
+ // Turn off the corresponding sandbox flag if it's set as "allowed".
+ String sandboxToken = policy.substring(start, end - start);
+ if (equalIgnoringCase(sandboxToken, "allow-same-origin")) {
+ flags &= ~SandboxOrigin;
+ } else if (equalIgnoringCase(sandboxToken, "allow-forms")) {
+ flags &= ~SandboxForms;
+ } else if (equalIgnoringCase(sandboxToken, "allow-scripts")) {
+ flags &= ~SandboxScripts;
+ flags &= ~SandboxAutomaticFeatures;
+ } else if (equalIgnoringCase(sandboxToken, "allow-top-navigation")) {
+ flags &= ~SandboxTopNavigation;
+ } else if (equalIgnoringCase(sandboxToken, "allow-popups")) {
+ flags &= ~SandboxPopups;
+ } else if (equalIgnoringCase(sandboxToken, "allow-pointer-lock")) {
+ flags &= ~SandboxPointerLock;
+ } else {
+ if (numberOfTokenErrors)
+ tokenErrors.appendLiteral(", '");
+ else
+ tokenErrors.append('\'');
+ tokenErrors.append(sandboxToken);
+ tokenErrors.append('\'');
+ numberOfTokenErrors++;
+ }
+
+ start = end + 1;
+ }
+
+ if (numberOfTokenErrors) {
+ if (numberOfTokenErrors > 1)
+ tokenErrors.appendLiteral(" are invalid sandbox flags.");
+ else
+ tokenErrors.appendLiteral(" is an invalid sandbox flag.");
+ invalidTokensErrorMessage = tokenErrors.toString();
+ }
+
+ return flags;
+}
+
+}
diff --git a/chromium/third_party/WebKit/Source/core/dom/SandboxFlags.h b/chromium/third_party/WebKit/Source/core/dom/SandboxFlags.h
new file mode 100644
index 00000000000..fa072d1ea9e
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/SandboxFlags.h
@@ -0,0 +1,57 @@
+/*
+ * Copyright (C) 2013 Google Inc. All Rights Reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY GOOGLE, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#ifndef SandboxFlags_h
+#define SandboxFlags_h
+
+#include "wtf/Forward.h"
+
+namespace WebCore {
+
+enum SandboxFlag {
+ // See http://www.whatwg.org/specs/web-apps/current-work/#attr-iframe-sandbox for a list of the sandbox flags.
+ SandboxNone = 0,
+ SandboxNavigation = 1,
+ SandboxPlugins = 1 << 1,
+ SandboxOrigin = 1 << 2,
+ SandboxForms = 1 << 3,
+ SandboxScripts = 1 << 4,
+ SandboxTopNavigation = 1 << 5,
+ SandboxPopups = 1 << 6, // See https://www.w3.org/Bugs/Public/show_bug.cgi?id=12393
+ SandboxAutomaticFeatures = 1 << 7,
+ SandboxSeamlessIframes = 1 << 8,
+ SandboxPointerLock = 1 << 9,
+ SandboxDocumentDomain = 1 << 10,
+ SandboxAll = -1 // Mask with all bits set to 1.
+};
+
+typedef int SandboxFlags;
+
+SandboxFlags parseSandboxPolicy(const String& policy, String& invalidTokensErrorMessage);
+
+}
+
+#endif
diff --git a/chromium/third_party/WebKit/Source/core/dom/ScopedEventQueue.cpp b/chromium/third_party/WebKit/Source/core/dom/ScopedEventQueue.cpp
deleted file mode 100644
index 8072c595c6a..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/ScopedEventQueue.cpp
+++ /dev/null
@@ -1,108 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/dom/ScopedEventQueue.h"
-
-#include "core/dom/Event.h"
-#include "core/dom/EventDispatchMediator.h"
-#include "core/dom/EventDispatcher.h"
-#include "core/dom/EventTarget.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/RefPtr.h"
-
-namespace WebCore {
-
-ScopedEventQueue* ScopedEventQueue::s_instance = 0;
-
-ScopedEventQueue::ScopedEventQueue()
- : m_scopingLevel(0)
-{
-}
-
-ScopedEventQueue::~ScopedEventQueue()
-{
- ASSERT(!m_scopingLevel);
- ASSERT(!m_queuedEventDispatchMediators.size());
-}
-
-void ScopedEventQueue::initialize()
-{
- ASSERT(!s_instance);
- OwnPtr<ScopedEventQueue> instance = adoptPtr(new ScopedEventQueue);
- s_instance = instance.leakPtr();
-}
-
-void ScopedEventQueue::enqueueEventDispatchMediator(PassRefPtr<EventDispatchMediator> mediator)
-{
- if (m_scopingLevel)
- m_queuedEventDispatchMediators.append(mediator);
- else
- dispatchEvent(mediator);
-}
-
-void ScopedEventQueue::dispatchAllEvents()
-{
- Vector<RefPtr<EventDispatchMediator> > queuedEventDispatchMediators;
- queuedEventDispatchMediators.swap(m_queuedEventDispatchMediators);
-
- for (size_t i = 0; i < queuedEventDispatchMediators.size(); i++)
- dispatchEvent(queuedEventDispatchMediators[i].release());
-}
-
-void ScopedEventQueue::dispatchEvent(PassRefPtr<EventDispatchMediator> mediator) const
-{
- ASSERT(mediator->event()->target());
- Node* node = mediator->event()->target()->toNode();
- EventDispatcher::dispatchEvent(node, mediator);
-}
-
-ScopedEventQueue* ScopedEventQueue::instance()
-{
- if (!s_instance)
- initialize();
-
- return s_instance;
-}
-
-void ScopedEventQueue::incrementScopingLevel()
-{
- m_scopingLevel++;
-}
-
-void ScopedEventQueue::decrementScopingLevel()
-{
- ASSERT(m_scopingLevel);
- m_scopingLevel--;
- if (!m_scopingLevel)
- dispatchAllEvents();
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/dom/ScriptExecutionContext.cpp b/chromium/third_party/WebKit/Source/core/dom/ScriptExecutionContext.cpp
deleted file mode 100644
index 9ac54d9fbe7..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/ScriptExecutionContext.cpp
+++ /dev/null
@@ -1,322 +0,0 @@
-/*
- * Copyright (C) 2008 Apple Inc. All Rights Reserved.
- * Copyright (C) 2012 Google Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-#include "config.h"
-#include "core/dom/ScriptExecutionContext.h"
-
-#include "core/dom/ContextLifecycleNotifier.h"
-#include "core/dom/ErrorEvent.h"
-#include "core/dom/EventTarget.h"
-#include "core/dom/MessagePort.h"
-#include "core/html/PublicURLManager.h"
-#include "core/inspector/InspectorInstrumentation.h"
-#include "core/inspector/ScriptCallStack.h"
-#include "core/page/DOMTimer.h"
-#include "core/workers/WorkerGlobalScope.h"
-#include "core/workers/WorkerThread.h"
-#include "modules/webdatabase/DatabaseContext.h"
-#include "wtf/MainThread.h"
-
-namespace WebCore {
-
-class ProcessMessagesSoonTask : public ScriptExecutionContext::Task {
-public:
- static PassOwnPtr<ProcessMessagesSoonTask> create()
- {
- return adoptPtr(new ProcessMessagesSoonTask);
- }
-
- virtual void performTask(ScriptExecutionContext* context)
- {
- context->dispatchMessagePortEvents();
- }
-};
-
-class ScriptExecutionContext::PendingException {
- WTF_MAKE_NONCOPYABLE(PendingException);
-public:
- PendingException(const String& errorMessage, int lineNumber, int columnNumber, const String& sourceURL, PassRefPtr<ScriptCallStack> callStack)
- : m_errorMessage(errorMessage)
- , m_lineNumber(lineNumber)
- , m_columnNumber(columnNumber)
- , m_sourceURL(sourceURL)
- , m_callStack(callStack)
- {
- }
- String m_errorMessage;
- int m_lineNumber;
- int m_columnNumber;
- String m_sourceURL;
- RefPtr<ScriptCallStack> m_callStack;
-};
-
-void ScriptExecutionContext::AddConsoleMessageTask::performTask(ScriptExecutionContext* context)
-{
- context->addConsoleMessage(m_source, m_level, m_message);
-}
-
-ScriptExecutionContext::ScriptExecutionContext()
- : m_circularSequentialID(0)
- , m_inDispatchErrorEvent(false)
- , m_activeDOMObjectsAreSuspended(false)
- , m_reasonForSuspendingActiveDOMObjects(static_cast<ActiveDOMObject::ReasonForSuspension>(-1))
- , m_activeDOMObjectsAreStopped(false)
-{
-}
-
-ScriptExecutionContext::~ScriptExecutionContext()
-{
- HashSet<MessagePort*>::iterator messagePortsEnd = m_messagePorts.end();
- for (HashSet<MessagePort*>::iterator iter = m_messagePorts.begin(); iter != messagePortsEnd; ++iter) {
- ASSERT((*iter)->scriptExecutionContext() == this);
- (*iter)->contextDestroyed();
- }
-}
-
-void ScriptExecutionContext::processMessagePortMessagesSoon()
-{
- postTask(ProcessMessagesSoonTask::create());
-}
-
-void ScriptExecutionContext::dispatchMessagePortEvents()
-{
- RefPtr<ScriptExecutionContext> protect(this);
-
- // Make a frozen copy.
- Vector<MessagePort*> ports;
- copyToVector(m_messagePorts, ports);
-
- unsigned portCount = ports.size();
- for (unsigned i = 0; i < portCount; ++i) {
- MessagePort* port = ports[i];
- // The port may be destroyed, and another one created at the same address, but this is safe, as the worst that can happen
- // as a result is that dispatchMessages() will be called needlessly.
- if (m_messagePorts.contains(port) && port->started())
- port->dispatchMessages();
- }
-}
-
-void ScriptExecutionContext::createdMessagePort(MessagePort* port)
-{
- ASSERT(port);
- ASSERT((isDocument() && isMainThread())
- || (isWorkerGlobalScope() && toWorkerGlobalScope(this)->thread()->isCurrentThread()));
-
- m_messagePorts.add(port);
-}
-
-void ScriptExecutionContext::destroyedMessagePort(MessagePort* port)
-{
- ASSERT(port);
- ASSERT((isDocument() && isMainThread())
- || (isWorkerGlobalScope() && toWorkerGlobalScope(this)->thread()->isCurrentThread()));
-
- m_messagePorts.remove(port);
-}
-
-bool ScriptExecutionContext::canSuspendActiveDOMObjects()
-{
- return lifecycleNotifier()->canSuspendActiveDOMObjects();
-}
-
-bool ScriptExecutionContext::hasPendingActivity()
-{
- if (lifecycleNotifier()->hasPendingActivity())
- return true;
-
- HashSet<MessagePort*>::const_iterator messagePortsEnd = m_messagePorts.end();
- for (HashSet<MessagePort*>::const_iterator iter = m_messagePorts.begin(); iter != messagePortsEnd; ++iter) {
- if ((*iter)->hasPendingActivity())
- return true;
- }
-
- return false;
-}
-
-void ScriptExecutionContext::suspendActiveDOMObjects(ActiveDOMObject::ReasonForSuspension why)
-{
- lifecycleNotifier()->notifySuspendingActiveDOMObjects(why);
- m_activeDOMObjectsAreSuspended = true;
- m_reasonForSuspendingActiveDOMObjects = why;
-}
-
-void ScriptExecutionContext::resumeActiveDOMObjects()
-{
- m_activeDOMObjectsAreSuspended = false;
- lifecycleNotifier()->notifyResumingActiveDOMObjects();
-}
-
-void ScriptExecutionContext::stopActiveDOMObjects()
-{
- m_activeDOMObjectsAreStopped = true;
- lifecycleNotifier()->notifyStoppingActiveDOMObjects();
- // Also close MessagePorts. If they were ActiveDOMObjects (they could be) then they could be stopped instead.
- closeMessagePorts();
-}
-
-void ScriptExecutionContext::suspendActiveDOMObjectIfNeeded(ActiveDOMObject* object)
-{
- ASSERT(lifecycleNotifier()->contains(object));
- // Ensure all ActiveDOMObjects are suspended also newly created ones.
- if (m_activeDOMObjectsAreSuspended)
- object->suspend(m_reasonForSuspendingActiveDOMObjects);
-}
-
-void ScriptExecutionContext::closeMessagePorts() {
- HashSet<MessagePort*>::iterator messagePortsEnd = m_messagePorts.end();
- for (HashSet<MessagePort*>::iterator iter = m_messagePorts.begin(); iter != messagePortsEnd; ++iter) {
- ASSERT((*iter)->scriptExecutionContext() == this);
- (*iter)->close();
- }
-}
-
-bool ScriptExecutionContext::shouldSanitizeScriptError(const String& sourceURL, AccessControlStatus corsStatus)
-{
- return !(securityOrigin()->canRequest(completeURL(sourceURL)) || corsStatus == SharableCrossOrigin);
-}
-
-void ScriptExecutionContext::reportException(PassRefPtr<ErrorEvent> event, PassRefPtr<ScriptCallStack> callStack, AccessControlStatus corsStatus)
-{
- RefPtr<ErrorEvent> errorEvent = event;
- if (m_inDispatchErrorEvent) {
- if (!m_pendingExceptions)
- m_pendingExceptions = adoptPtr(new Vector<OwnPtr<PendingException> >());
- m_pendingExceptions->append(adoptPtr(new PendingException(errorEvent->messageForConsole(), errorEvent->lineno(), errorEvent->colno(), errorEvent->filename(), callStack)));
- return;
- }
-
- // First report the original exception and only then all the nested ones.
- if (!dispatchErrorEvent(errorEvent, corsStatus))
- logExceptionToConsole(errorEvent->messageForConsole(), errorEvent->filename(), errorEvent->lineno(), errorEvent->colno(), callStack);
-
- if (!m_pendingExceptions)
- return;
-
- for (size_t i = 0; i < m_pendingExceptions->size(); i++) {
- PendingException* e = m_pendingExceptions->at(i).get();
- logExceptionToConsole(e->m_errorMessage, e->m_sourceURL, e->m_lineNumber, e->m_columnNumber, e->m_callStack);
- }
- m_pendingExceptions.clear();
-}
-
-void ScriptExecutionContext::addConsoleMessage(MessageSource source, MessageLevel level, const String& message, const String& sourceURL, unsigned lineNumber)
-{
- addMessage(source, level, message, sourceURL, lineNumber, 0);
-}
-
-void ScriptExecutionContext::addConsoleMessage(MessageSource source, MessageLevel level, const String& message, ScriptState* state)
-{
- addMessage(source, level, message, String(), 0, state);
-}
-
-bool ScriptExecutionContext::dispatchErrorEvent(PassRefPtr<ErrorEvent> event, AccessControlStatus corsStatus)
-{
- EventTarget* target = errorEventTarget();
- if (!target)
- return false;
-
- RefPtr<ErrorEvent> errorEvent = event;
- if (shouldSanitizeScriptError(errorEvent->filename(), corsStatus))
- errorEvent = ErrorEvent::createSanitizedError(errorEvent->world());
-
- ASSERT(!m_inDispatchErrorEvent);
- m_inDispatchErrorEvent = true;
- target->dispatchEvent(errorEvent);
- m_inDispatchErrorEvent = false;
- return errorEvent->defaultPrevented();
-}
-
-int ScriptExecutionContext::circularSequentialID()
-{
- ++m_circularSequentialID;
- if (m_circularSequentialID <= 0)
- m_circularSequentialID = 1;
- return m_circularSequentialID;
-}
-
-int ScriptExecutionContext::installNewTimeout(PassOwnPtr<ScheduledAction> action, int timeout, bool singleShot)
-{
- int timeoutID;
- while (true) {
- timeoutID = circularSequentialID();
- if (!m_timeouts.contains(timeoutID))
- break;
- }
- TimeoutMap::AddResult result = m_timeouts.add(timeoutID, DOMTimer::create(this, action, timeout, singleShot, timeoutID));
- ASSERT(result.isNewEntry);
- DOMTimer* timer = result.iterator->value.get();
-
- timer->suspendIfNeeded();
-
- return timer->timeoutID();
-}
-
-void ScriptExecutionContext::removeTimeoutByID(int timeoutID)
-{
- if (timeoutID <= 0)
- return;
- m_timeouts.remove(timeoutID);
-}
-
-PublicURLManager& ScriptExecutionContext::publicURLManager()
-{
- if (!m_publicURLManager)
- m_publicURLManager = PublicURLManager::create(this);
- return *m_publicURLManager;
-}
-
-void ScriptExecutionContext::didChangeTimerAlignmentInterval()
-{
- for (TimeoutMap::iterator iter = m_timeouts.begin(); iter != m_timeouts.end(); ++iter)
- iter->value->didChangeAlignmentInterval();
-}
-
-double ScriptExecutionContext::timerAlignmentInterval() const
-{
- return DOMTimer::visiblePageAlignmentInterval();
-}
-
-ContextLifecycleNotifier* ScriptExecutionContext::lifecycleNotifier()
-{
- return static_cast<ContextLifecycleNotifier*>(LifecycleContext::lifecycleNotifier());
-}
-
-PassOwnPtr<LifecycleNotifier> ScriptExecutionContext::createLifecycleNotifier()
-{
- return ContextLifecycleNotifier::create(this);
-}
-
-ScriptExecutionContext::Task::~Task()
-{
-}
-
-void ScriptExecutionContext::setDatabaseContext(DatabaseContext* databaseContext)
-{
- m_databaseContext = databaseContext;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/ScriptExecutionContext.h b/chromium/third_party/WebKit/Source/core/dom/ScriptExecutionContext.h
deleted file mode 100644
index a595aa184f0..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/ScriptExecutionContext.h
+++ /dev/null
@@ -1,207 +0,0 @@
-/*
- * Copyright (C) 2008 Apple Inc. All Rights Reserved.
- * Copyright (C) 2012 Google Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-#ifndef ScriptExecutionContext_h
-#define ScriptExecutionContext_h
-
-#include "core/dom/ActiveDOMObject.h"
-#include "core/dom/ErrorEvent.h"
-#include "core/dom/SecurityContext.h"
-#include "core/fetch/CrossOriginAccessControl.h"
-#include "core/page/ConsoleTypes.h"
-#include "core/page/DOMTimer.h"
-#include "core/platform/LifecycleContext.h"
-#include "core/platform/Supplementable.h"
-#include "weborigin/KURL.h"
-#include "wtf/HashSet.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/PassOwnPtr.h"
-
-namespace WTF {
-class OrdinalNumber;
-}
-
-namespace WebCore {
-
-class ContextLifecycleNotifier;
-class DOMWindow;
-class DatabaseContext;
-class EventListener;
-class EventQueue;
-class EventTarget;
-class MessagePort;
-class PublicURLManager;
-class ScriptCallStack;
-class ScriptState;
-
-class ScriptExecutionContext : public LifecycleContext, public SecurityContext, public Supplementable<ScriptExecutionContext> {
-public:
- ScriptExecutionContext();
- virtual ~ScriptExecutionContext();
-
- virtual bool isDocument() const { return false; }
- virtual bool isWorkerGlobalScope() const { return false; }
-
- virtual bool isJSExecutionForbidden() const = 0;
-
- virtual DOMWindow* executingWindow() { return 0; }
- virtual void userEventWasHandled() { }
-
- const KURL& url() const { return virtualURL(); }
- KURL completeURL(const String& url) const { return virtualCompleteURL(url); }
-
- virtual String userAgent(const KURL&) const = 0;
-
- virtual void disableEval(const String& errorMessage) = 0;
-
- bool shouldSanitizeScriptError(const String& sourceURL, AccessControlStatus);
- void reportException(PassRefPtr<ErrorEvent>, PassRefPtr<ScriptCallStack>, AccessControlStatus);
-
- void addConsoleMessage(MessageSource, MessageLevel, const String& message, const String& sourceURL, unsigned lineNumber);
- void addConsoleMessage(MessageSource, MessageLevel, const String& message, ScriptState* = 0);
-
- PublicURLManager& publicURLManager();
-
- // Active objects are not garbage collected even if inaccessible, e.g. because their activity may result in callbacks being invoked.
- bool canSuspendActiveDOMObjects();
- bool hasPendingActivity();
-
- // Active objects can be asked to suspend even if canSuspendActiveDOMObjects() returns 'false' -
- // step-by-step JS debugging is one example.
- virtual void suspendActiveDOMObjects(ActiveDOMObject::ReasonForSuspension);
- virtual void resumeActiveDOMObjects();
- virtual void stopActiveDOMObjects();
-
- bool activeDOMObjectsAreSuspended() const { return m_activeDOMObjectsAreSuspended; }
- bool activeDOMObjectsAreStopped() const { return m_activeDOMObjectsAreStopped; }
-
- // Called after the construction of an ActiveDOMObject to synchronize suspend state.
- void suspendActiveDOMObjectIfNeeded(ActiveDOMObject*);
-
- // MessagePort is conceptually a kind of ActiveDOMObject, but it needs to be tracked separately for message dispatch.
- void processMessagePortMessagesSoon();
- void dispatchMessagePortEvents();
- void createdMessagePort(MessagePort*);
- void destroyedMessagePort(MessagePort*);
- const HashSet<MessagePort*>& messagePorts() const { return m_messagePorts; }
-
- void ref() { refScriptExecutionContext(); }
- void deref() { derefScriptExecutionContext(); }
-
- class Task {
- WTF_MAKE_NONCOPYABLE(Task);
- WTF_MAKE_FAST_ALLOCATED;
- public:
- Task() { }
- virtual ~Task();
- virtual void performTask(ScriptExecutionContext*) = 0;
- // Certain tasks get marked specially so that they aren't discarded, and are executed, when the context is shutting down its message queue.
- virtual bool isCleanupTask() const { return false; }
- };
-
- virtual void postTask(PassOwnPtr<Task>) = 0; // Executes the task on context's thread asynchronously.
-
- // Gets the next id in a circular sequence from 1 to 2^31-1.
- int circularSequentialID();
-
- void didChangeTimerAlignmentInterval();
- virtual double timerAlignmentInterval() const;
-
- virtual EventQueue* eventQueue() const = 0;
-
- void setDatabaseContext(DatabaseContext*);
-
-protected:
- class AddConsoleMessageTask : public Task {
- public:
- static PassOwnPtr<AddConsoleMessageTask> create(MessageSource source, MessageLevel level, const String& message)
- {
- return adoptPtr(new AddConsoleMessageTask(source, level, message));
- }
- virtual void performTask(ScriptExecutionContext*);
- private:
- AddConsoleMessageTask(MessageSource source, MessageLevel level, const String& message)
- : m_source(source)
- , m_level(level)
- , m_message(message.isolatedCopy())
- {
- }
- MessageSource m_source;
- MessageLevel m_level;
- String m_message;
- };
-
- ContextLifecycleNotifier* lifecycleNotifier();
-
-private:
- friend class DOMTimer; // For installNewTimeout() and removeTimeoutByID() below.
-
- virtual const KURL& virtualURL() const = 0;
- virtual KURL virtualCompleteURL(const String&) const = 0;
-
- virtual void addMessage(MessageSource, MessageLevel, const String& message, const String& sourceURL, unsigned lineNumber, ScriptState*) = 0;
- virtual EventTarget* errorEventTarget() = 0;
- virtual void logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, int columnNumber, PassRefPtr<ScriptCallStack>) = 0;
- bool dispatchErrorEvent(PassRefPtr<ErrorEvent>, AccessControlStatus);
-
- void closeMessagePorts();
-
- virtual void refScriptExecutionContext() = 0;
- virtual void derefScriptExecutionContext() = 0;
- virtual PassOwnPtr<LifecycleNotifier> createLifecycleNotifier() OVERRIDE;
-
- // Implementation details for DOMTimer. No other classes should call these functions.
- int installNewTimeout(PassOwnPtr<ScheduledAction>, int timeout, bool singleShot);
- void removeTimeoutByID(int timeoutID); // This makes underlying DOMTimer instance destructed.
-
- HashSet<MessagePort*> m_messagePorts;
-
- int m_circularSequentialID;
- typedef HashMap<int, OwnPtr<DOMTimer> > TimeoutMap;
- TimeoutMap m_timeouts;
-
- bool m_inDispatchErrorEvent;
- class PendingException;
- OwnPtr<Vector<OwnPtr<PendingException> > > m_pendingExceptions;
-
- bool m_activeDOMObjectsAreSuspended;
- ActiveDOMObject::ReasonForSuspension m_reasonForSuspendingActiveDOMObjects;
- bool m_activeDOMObjectsAreStopped;
-
- OwnPtr<PublicURLManager> m_publicURLManager;
-
- RefPtr<DatabaseContext> m_databaseContext;
-
- // The location of this member is important; to make sure contextDestroyed() notification on
- // ScriptExecutionContext's members (notably m_timeouts) is called before they are destructed,
- // m_lifecycleNotifer should be placed *after* such members.
- OwnPtr<ContextLifecycleNotifier> m_lifecycleNotifier;
-};
-
-} // namespace WebCore
-
-#endif // ScriptExecutionContext_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/ScriptLoader.cpp b/chromium/third_party/WebKit/Source/core/dom/ScriptLoader.cpp
index 0345ad98500..eaa0e45da91 100644
--- a/chromium/third_party/WebKit/Source/core/dom/ScriptLoader.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/ScriptLoader.cpp
@@ -29,7 +29,7 @@
#include "bindings/v8/ScriptController.h"
#include "bindings/v8/ScriptSourceCode.h"
#include "core/dom/Document.h"
-#include "core/dom/Event.h"
+#include "core/events/Event.h"
#include "core/dom/IgnoreDestructiveWriteCountIncrementer.h"
#include "core/dom/ScriptLoaderClient.h"
#include "core/dom/ScriptRunner.h"
@@ -41,15 +41,14 @@
#include "core/html/HTMLImport.h"
#include "core/html/HTMLScriptElement.h"
#include "core/html/parser/HTMLParserIdioms.h"
-#include "core/page/ContentSecurityPolicy.h"
-#include "core/page/Frame.h"
-#include "core/platform/MIMETypeRegistry.h"
+#include "core/frame/ContentSecurityPolicy.h"
+#include "core/frame/Frame.h"
#include "core/svg/SVGScriptElement.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/MIMETypeRegistry.h"
+#include "platform/weborigin/SecurityOrigin.h"
#include "wtf/StdLibExtras.h"
#include "wtf/text/StringBuilder.h"
#include "wtf/text/StringHash.h"
-#include "wtf/text/TextPosition.h"
namespace WebCore {
@@ -66,6 +65,7 @@ ScriptLoader::ScriptLoader(Element* element, bool parserInserted, bool alreadySt
, m_willExecuteWhenDocumentFinishedParsing(false)
, m_forceAsync(!parserInserted)
, m_willExecuteInOrder(false)
+ , m_isPotentiallyCORSEnabled(false)
{
ASSERT(m_element);
if (parserInserted && element->document().scriptableDocumentParser() && !element->document().isInDocumentWrite())
@@ -135,7 +135,7 @@ static bool isLegacySupportedJavaScriptLanguage(const String& language)
void ScriptLoader::dispatchErrorEvent()
{
- m_element->dispatchEvent(Event::create(eventNames().errorEvent));
+ m_element->dispatchEvent(Event::create(EventTypeNames::error));
}
void ScriptLoader::dispatchLoadEvent()
@@ -241,7 +241,8 @@ bool ScriptLoader::prepareScript(const TextPosition& scriptStartPosition, Legacy
// Reset line numbering for nested writes.
TextPosition position = elementDocument.isInDocumentWrite() ? TextPosition() : scriptStartPosition;
KURL scriptURL = (!elementDocument.isInDocumentWrite() && m_parserInserted) ? elementDocument.url() : KURL();
- executeScript(ScriptSourceCode(scriptContent(), scriptURL, position));
+ if (!executePotentiallyCrossOriginScript(ScriptSourceCode(scriptContent(), scriptURL, position)))
+ return false;
}
return true;
@@ -251,10 +252,10 @@ bool ScriptLoader::fetchScript(const String& sourceUrl)
{
ASSERT(m_element);
- RefPtr<Document> elementDocument = &m_element->document();
+ RefPtr<Document> elementDocument(m_element->document());
if (!m_element->dispatchBeforeLoadEvent(sourceUrl))
return false;
- if (!m_element->inDocument() || &m_element->document() != elementDocument)
+ if (!m_element->inDocument() || m_element->document() != elementDocument)
return false;
ASSERT(!m_resource);
@@ -264,7 +265,8 @@ bool ScriptLoader::fetchScript(const String& sourceUrl)
String crossOriginMode = m_element->fastGetAttribute(HTMLNames::crossoriginAttr);
if (!crossOriginMode.isNull()) {
StoredCredentials allowCredentials = equalIgnoringCase(crossOriginMode, "use-credentials") ? AllowStoredCredentials : DoNotAllowStoredCredentials;
- request.setPotentiallyCrossOriginEnabled(elementDocument->securityOrigin(), allowCredentials);
+ request.setCrossOriginAccessControl(elementDocument->securityOrigin(), allowCredentials);
+ m_isPotentiallyCORSEnabled = true;
}
request.setCharset(scriptCharset());
@@ -276,9 +278,8 @@ bool ScriptLoader::fetchScript(const String& sourceUrl)
m_isExternalScript = true;
}
- if (m_resource) {
+ if (m_resource)
return true;
- }
dispatchErrorEvent();
return false;
@@ -301,14 +302,14 @@ void ScriptLoader::executeScript(const ScriptSourceCode& sourceCode)
if (sourceCode.isEmpty())
return;
- RefPtr<Document> elementDocument = &m_element->document();
+ RefPtr<Document> elementDocument(m_element->document());
RefPtr<Document> contextDocument = elementDocument->contextDocument().get();
if (!contextDocument)
return;
Frame* frame = contextDocument->frame();
- bool shouldBypassMainWorldContentSecurityPolicy = (frame && frame->script()->shouldBypassMainWorldContentSecurityPolicy()) || elementDocument->contentSecurityPolicy()->allowScriptNonce(m_element->fastGetAttribute(HTMLNames::nonceAttr));
+ bool shouldBypassMainWorldContentSecurityPolicy = (frame && frame->script().shouldBypassMainWorldContentSecurityPolicy()) || elementDocument->contentSecurityPolicy()->allowScriptNonce(m_element->fastGetAttribute(HTMLNames::nonceAttr)) || elementDocument->contentSecurityPolicy()->allowScriptHash(sourceCode.source());
if (!m_isExternalScript && (!shouldBypassMainWorldContentSecurityPolicy && !elementDocument->contentSecurityPolicy()->allowInlineScript(elementDocument->url(), m_startLineNumber)))
return;
@@ -331,7 +332,7 @@ void ScriptLoader::executeScript(const ScriptSourceCode& sourceCode)
// Create a script from the script element node, using the script
// block's source and the script block's type.
// Note: This is where the script is compiled and actually executed.
- frame->script()->executeScriptInMainWorld(sourceCode, corsCheck);
+ frame->script().executeScriptInMainWorld(sourceCode, corsCheck);
if (isHTMLScriptLoader(m_element)) {
ASSERT(contextDocument->currentScript() == m_element);
@@ -362,11 +363,23 @@ void ScriptLoader::execute(ScriptResource* resource)
resource->removeClient(this);
}
+bool ScriptLoader::executePotentiallyCrossOriginScript(const ScriptSourceCode& sourceCode)
+{
+ if (sourceCode.resource()
+ && isPotentiallyCORSEnabled()
+ && !m_element->document().fetcher()->canAccess(sourceCode.resource(), PotentiallyCORSEnabled)) {
+ dispatchErrorEvent();
+ return false;
+ }
+ executeScript(sourceCode);
+ return true;
+}
+
void ScriptLoader::notifyFinished(Resource* resource)
{
ASSERT(!m_willBeParserExecuted);
- RefPtr<Document> elementDocument = &m_element->document();
+ RefPtr<Document> elementDocument(m_element->document());
RefPtr<Document> contextDocument = elementDocument->contextDocument().get();
if (!contextDocument)
return;
@@ -378,8 +391,10 @@ void ScriptLoader::notifyFinished(Resource* resource)
ASSERT_UNUSED(resource, resource == m_resource);
if (!m_resource)
return;
- if (!elementDocument->fetcher()->canAccess(m_resource.get())) {
+ CORSEnabled corsEnabled = isPotentiallyCORSEnabled() ? PotentiallyCORSEnabled : NotCORSEnabled;
+ if (!elementDocument->fetcher()->canAccess(m_resource.get(), corsEnabled)) {
dispatchErrorEvent();
+ contextDocument->scriptRunner()->notifyScriptLoadError(this, m_willExecuteInOrder ? ScriptRunner::IN_ORDER_EXECUTION : ScriptRunner::ASYNC_EXECUTION);
return;
}
diff --git a/chromium/third_party/WebKit/Source/core/dom/ScriptLoader.h b/chromium/third_party/WebKit/Source/core/dom/ScriptLoader.h
index e6ba8d3b080..72f51972005 100644
--- a/chromium/third_party/WebKit/Source/core/dom/ScriptLoader.h
+++ b/chromium/third_party/WebKit/Source/core/dom/ScriptLoader.h
@@ -50,6 +50,12 @@ public:
void executeScript(const ScriptSourceCode&);
void execute(ScriptResource*);
+ // Check if potentially cross-origin enabled script is accessible
+ // prior to execution. Returns 'false' if not accessible, signalling
+ // that callers must not dispatch load events as the cross-origin
+ // fetch failed.
+ bool executePotentiallyCrossOriginScript(const ScriptSourceCode&);
+
// XML parser calls these
void dispatchLoadEvent();
void dispatchErrorEvent();
@@ -65,6 +71,7 @@ public:
bool isParserInserted() const { return m_parserInserted; }
bool alreadyStarted() const { return m_alreadyStarted; }
bool forceAsync() const { return m_forceAsync; }
+ bool isPotentiallyCORSEnabled() const { return m_isPotentiallyCORSEnabled; }
// Helper functions used by our parent classes.
void didNotifySubtreeInsertionsToDocument();
@@ -98,6 +105,7 @@ private:
bool m_willExecuteWhenDocumentFinishedParsing : 1;
bool m_forceAsync : 1;
bool m_willExecuteInOrder : 1;
+ bool m_isPotentiallyCORSEnabled : 1;
String m_characterEncoding;
String m_fallbackCharacterEncoding;
};
diff --git a/chromium/third_party/WebKit/Source/core/dom/ScriptRunner.cpp b/chromium/third_party/WebKit/Source/core/dom/ScriptRunner.cpp
index f63ab5056c0..2fbf959c598 100644
--- a/chromium/third_party/WebKit/Source/core/dom/ScriptRunner.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/ScriptRunner.cpp
@@ -47,7 +47,7 @@ ScriptRunner::~ScriptRunner()
m_document->decrementLoadEventDelayCount();
for (size_t i = 0; i < m_scriptsToExecuteInOrder.size(); ++i)
m_document->decrementLoadEventDelayCount();
- for (int i = 0; i < m_pendingAsyncScripts.size(); ++i)
+ for (size_t i = 0; i < m_pendingAsyncScripts.size(); ++i)
m_document->decrementLoadEventDelayCount();
}
@@ -99,6 +99,21 @@ void ScriptRunner::notifyScriptReady(ScriptLoader* scriptLoader, ExecutionType e
m_timer.startOneShot(0);
}
+void ScriptRunner::notifyScriptLoadError(ScriptLoader* scriptLoader, ExecutionType executionType)
+{
+ switch (executionType) {
+ case ASYNC_EXECUTION:
+ ASSERT(m_pendingAsyncScripts.contains(scriptLoader));
+ m_pendingAsyncScripts.remove(scriptLoader);
+ m_document->decrementLoadEventDelayCount();
+ break;
+
+ case IN_ORDER_EXECUTION:
+ ASSERT(!m_scriptsToExecuteInOrder.isEmpty());
+ break;
+ }
+}
+
void ScriptRunner::timerFired(Timer<ScriptRunner>* timer)
{
ASSERT_UNUSED(timer, timer == &m_timer);
diff --git a/chromium/third_party/WebKit/Source/core/dom/ScriptRunner.h b/chromium/third_party/WebKit/Source/core/dom/ScriptRunner.h
index b793589a8e8..b47139c8629 100644
--- a/chromium/third_party/WebKit/Source/core/dom/ScriptRunner.h
+++ b/chromium/third_party/WebKit/Source/core/dom/ScriptRunner.h
@@ -27,7 +27,7 @@
#define ScriptRunner_h
#include "core/fetch/ResourcePtr.h"
-#include "core/platform/Timer.h"
+#include "platform/Timer.h"
#include "wtf/HashMap.h"
#include "wtf/Noncopyable.h"
#include "wtf/PassOwnPtr.h"
@@ -52,6 +52,7 @@ public:
void suspend();
void resume();
void notifyScriptReady(ScriptLoader*, ExecutionType);
+ void notifyScriptLoadError(ScriptLoader*, ExecutionType);
private:
explicit ScriptRunner(Document*);
diff --git a/chromium/third_party/WebKit/Source/core/dom/ScriptableDocumentParser.cpp b/chromium/third_party/WebKit/Source/core/dom/ScriptableDocumentParser.cpp
index 504e6f3eea0..5e8f2f39a2b 100644
--- a/chromium/third_party/WebKit/Source/core/dom/ScriptableDocumentParser.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/ScriptableDocumentParser.cpp
@@ -27,7 +27,7 @@
#include "core/dom/ScriptableDocumentParser.h"
#include "core/dom/Document.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/dom/ScriptedAnimationController.cpp b/chromium/third_party/WebKit/Source/core/dom/ScriptedAnimationController.cpp
index 0a276123e11..27a7f6b463f 100644
--- a/chromium/third_party/WebKit/Source/core/dom/ScriptedAnimationController.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/ScriptedAnimationController.cpp
@@ -28,12 +28,19 @@
#include "core/dom/Document.h"
#include "core/dom/RequestAnimationFrameCallback.h"
+#include "core/events/Event.h"
+#include "core/frame/DOMWindow.h"
+#include "core/frame/FrameView.h"
#include "core/inspector/InspectorInstrumentation.h"
#include "core/loader/DocumentLoader.h"
-#include "core/page/FrameView.h"
namespace WebCore {
+std::pair<EventTarget*, StringImpl*> eventTargetKey(const Event* event)
+{
+ return std::make_pair(event->target(), event->type().impl());
+}
+
ScriptedAnimationController::ScriptedAnimationController(Document* document)
: m_document(document)
, m_nextCallbackId(0)
@@ -56,22 +63,19 @@ void ScriptedAnimationController::resume()
// even when suspend hasn't (if a tab was created in the background).
if (m_suspendCount > 0)
--m_suspendCount;
-
- if (!m_suspendCount && m_callbacks.size())
- scheduleAnimation();
+ scheduleAnimationIfNeeded();
}
-ScriptedAnimationController::CallbackId ScriptedAnimationController::registerCallback(PassRefPtr<RequestAnimationFrameCallback> callback)
+ScriptedAnimationController::CallbackId ScriptedAnimationController::registerCallback(PassOwnPtr<RequestAnimationFrameCallback> callback)
{
ScriptedAnimationController::CallbackId id = ++m_nextCallbackId;
- callback->m_firedOrCancelled = false;
+ callback->m_cancelled = false;
callback->m_id = id;
m_callbacks.append(callback);
+ scheduleAnimationIfNeeded();
InspectorInstrumentation::didRequestAnimationFrame(m_document, id);
- if (!m_suspendCount)
- scheduleAnimation();
return id;
}
@@ -79,17 +83,43 @@ void ScriptedAnimationController::cancelCallback(CallbackId id)
{
for (size_t i = 0; i < m_callbacks.size(); ++i) {
if (m_callbacks[i]->m_id == id) {
- m_callbacks[i]->m_firedOrCancelled = true;
InspectorInstrumentation::didCancelAnimationFrame(m_document, id);
m_callbacks.remove(i);
return;
}
}
+ for (size_t i = 0; i < m_callbacksToInvoke.size(); ++i) {
+ if (m_callbacksToInvoke[i]->m_id == id) {
+ InspectorInstrumentation::didCancelAnimationFrame(m_document, id);
+ m_callbacksToInvoke[i]->m_cancelled = true;
+ // will be removed at the end of executeCallbacks()
+ return;
+ }
+ }
}
-void ScriptedAnimationController::serviceScriptedAnimations(double monotonicTimeNow)
+void ScriptedAnimationController::dispatchEvents()
+{
+ Vector<RefPtr<Event> > events;
+ events.swap(m_eventQueue);
+ m_perFrameEvents.clear();
+
+ for (size_t i = 0; i < events.size(); ++i) {
+ EventTarget* eventTarget = events[i]->target();
+ // FIXME: we should figure out how to make dispatchEvent properly virtual to avoid
+ // special casting window.
+ // FIXME: We should not fire events for nodes that are no longer in the tree.
+ if (DOMWindow* window = eventTarget->toDOMWindow())
+ window->dispatchEvent(events[i], 0);
+ else
+ eventTarget->dispatchEvent(events[i]);
+ }
+}
+
+void ScriptedAnimationController::executeCallbacks(double monotonicTimeNow)
{
- if (!m_callbacks.size() || m_suspendCount)
+ // dispatchEvents() runs script which can cause the document to be destroyed.
+ if (!m_document)
return;
double highResNowMs = 1000.0 * m_document->loader()->timing()->monotonicTimeToZeroBasedDocumentTime(monotonicTimeNow);
@@ -97,16 +127,12 @@ void ScriptedAnimationController::serviceScriptedAnimations(double monotonicTime
// First, generate a list of callbacks to consider. Callbacks registered from this point
// on are considered only for the "next" frame, not this one.
- CallbackList callbacks(m_callbacks);
+ ASSERT(m_callbacksToInvoke.isEmpty());
+ m_callbacksToInvoke.swap(m_callbacks);
- // Invoking callbacks may detach elements from our document, which clears the document's
- // reference to us, so take a defensive reference.
- RefPtr<ScriptedAnimationController> protector(this);
-
- for (size_t i = 0; i < callbacks.size(); ++i) {
- RequestAnimationFrameCallback* callback = callbacks[i].get();
- if (!callback->m_firedOrCancelled) {
- callback->m_firedOrCancelled = true;
+ for (size_t i = 0; i < m_callbacksToInvoke.size(); ++i) {
+ RequestAnimationFrameCallback* callback = m_callbacksToInvoke[i].get();
+ if (!callback->m_cancelled) {
InspectorInstrumentationCookie cookie = InspectorInstrumentation::willFireAnimationFrame(m_document, callback->m_id);
if (callback->m_useLegacyTimeBase)
callback->handleEvent(legacyHighResNowMs);
@@ -116,23 +142,49 @@ void ScriptedAnimationController::serviceScriptedAnimations(double monotonicTime
}
}
- // Remove any callbacks we fired from the list of pending callbacks.
- for (size_t i = 0; i < m_callbacks.size();) {
- if (m_callbacks[i]->m_firedOrCancelled)
- m_callbacks.remove(i);
- else
- ++i;
- }
+ m_callbacksToInvoke.clear();
+}
- if (m_callbacks.size())
- scheduleAnimation();
+void ScriptedAnimationController::serviceScriptedAnimations(double monotonicTimeNow)
+{
+ if (!m_callbacks.size() && !m_eventQueue.size())
+ return;
+
+ if (m_suspendCount)
+ return;
+
+ RefPtr<ScriptedAnimationController> protect(this);
+
+ dispatchEvents();
+ executeCallbacks(monotonicTimeNow);
+
+ scheduleAnimationIfNeeded();
}
-void ScriptedAnimationController::scheduleAnimation()
+void ScriptedAnimationController::enqueueEvent(PassRefPtr<Event> event)
+{
+ m_eventQueue.append(event);
+ scheduleAnimationIfNeeded();
+}
+
+void ScriptedAnimationController::enqueuePerFrameEvent(PassRefPtr<Event> event)
+{
+ if (!m_perFrameEvents.add(eventTargetKey(event.get())).isNewEntry)
+ return;
+ enqueueEvent(event);
+}
+
+void ScriptedAnimationController::scheduleAnimationIfNeeded()
{
if (!m_document)
return;
+ if (m_suspendCount)
+ return;
+
+ if (!m_callbacks.size() && !m_eventQueue.size())
+ return;
+
if (FrameView* frameView = m_document->view())
frameView->scheduleAnimation();
}
diff --git a/chromium/third_party/WebKit/Source/core/dom/ScriptedAnimationController.h b/chromium/third_party/WebKit/Source/core/dom/ScriptedAnimationController.h
index 4379b2a48ac..5f7efb887e9 100644
--- a/chromium/third_party/WebKit/Source/core/dom/ScriptedAnimationController.h
+++ b/chromium/third_party/WebKit/Source/core/dom/ScriptedAnimationController.h
@@ -26,17 +26,20 @@
#ifndef ScriptedAnimationController_h
#define ScriptedAnimationController_h
+#include "wtf/ListHashSet.h"
#include "wtf/RefCounted.h"
#include "wtf/RefPtr.h"
#include "wtf/Vector.h"
+#include "wtf/text/StringImpl.h"
namespace WebCore {
class Document;
+class Event;
+class EventTarget;
class RequestAnimationFrameCallback;
-class ScriptedAnimationController : public RefCounted<ScriptedAnimationController>
-{
+class ScriptedAnimationController : public RefCounted<ScriptedAnimationController> {
public:
static PassRefPtr<ScriptedAnimationController> create(Document* document)
{
@@ -47,24 +50,33 @@ public:
typedef int CallbackId;
- CallbackId registerCallback(PassRefPtr<RequestAnimationFrameCallback>);
+ int registerCallback(PassOwnPtr<RequestAnimationFrameCallback>);
void cancelCallback(CallbackId);
void serviceScriptedAnimations(double monotonicTimeNow);
+ void enqueueEvent(PassRefPtr<Event>);
+ void enqueuePerFrameEvent(PassRefPtr<Event>);
+
void suspend();
void resume();
private:
explicit ScriptedAnimationController(Document*);
- typedef Vector<RefPtr<RequestAnimationFrameCallback> > CallbackList;
+ void scheduleAnimationIfNeeded();
+
+ void dispatchEvents();
+ void executeCallbacks(double monotonicTimeNow);
+
+ typedef Vector<OwnPtr<RequestAnimationFrameCallback> > CallbackList;
CallbackList m_callbacks;
+ CallbackList m_callbacksToInvoke; // only non-empty while inside executeCallbacks
Document* m_document;
CallbackId m_nextCallbackId;
int m_suspendCount;
-
- void scheduleAnimation();
+ Vector<RefPtr<Event> > m_eventQueue;
+ ListHashSet<std::pair<const EventTarget*, const StringImpl*> > m_perFrameEvents;
};
}
diff --git a/chromium/third_party/WebKit/Source/core/dom/SecurityContext.cpp b/chromium/third_party/WebKit/Source/core/dom/SecurityContext.cpp
index c81e923e553..d0c35303076 100644
--- a/chromium/third_party/WebKit/Source/core/dom/SecurityContext.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/SecurityContext.cpp
@@ -27,17 +27,13 @@
#include "config.h"
#include "core/dom/SecurityContext.h"
-#include "core/html/parser/HTMLParserIdioms.h"
-#include "core/page/ContentSecurityPolicy.h"
-#include "weborigin/SecurityOrigin.h"
-#include "wtf/text/StringBuilder.h"
+#include "core/frame/ContentSecurityPolicy.h"
+#include "platform/weborigin/SecurityOrigin.h"
namespace WebCore {
SecurityContext::SecurityContext()
- : m_mayDisplaySeamlesslyWithParent(false)
- , m_haveInitializedSecurityOrigin(false)
- , m_sandboxFlags(SandboxNone)
+ : m_haveInitializedSecurityOrigin(false)
{
}
@@ -68,77 +64,4 @@ bool SecurityContext::isSecureTransitionTo(const KURL& url) const
return securityOrigin()->canAccess(other.get());
}
-void SecurityContext::enforceSandboxFlags(SandboxFlags mask)
-{
- m_sandboxFlags |= mask;
-
- // The SandboxOrigin is stored redundantly in the security origin.
- if (isSandboxed(SandboxOrigin) && securityOrigin() && !securityOrigin()->isUnique()) {
- setSecurityOrigin(SecurityOrigin::createUnique());
- didUpdateSecurityOrigin();
- }
-}
-
-void SecurityContext::didUpdateSecurityOrigin()
-{
- // Subclasses can override this function if the need to do extra work when the security origin changes.
-}
-
-SandboxFlags SecurityContext::parseSandboxPolicy(const String& policy, String& invalidTokensErrorMessage)
-{
- // http://www.w3.org/TR/html5/the-iframe-element.html#attr-iframe-sandbox
- // Parse the unordered set of unique space-separated tokens.
- SandboxFlags flags = SandboxAll;
- unsigned length = policy.length();
- unsigned start = 0;
- unsigned numberOfTokenErrors = 0;
- StringBuilder tokenErrors;
- while (true) {
- while (start < length && isHTMLSpace<UChar>(policy[start]))
- ++start;
- if (start >= length)
- break;
- unsigned end = start + 1;
- while (end < length && !isHTMLSpace<UChar>(policy[end]))
- ++end;
-
- // Turn off the corresponding sandbox flag if it's set as "allowed".
- String sandboxToken = policy.substring(start, end - start);
- if (equalIgnoringCase(sandboxToken, "allow-same-origin"))
- flags &= ~SandboxOrigin;
- else if (equalIgnoringCase(sandboxToken, "allow-forms"))
- flags &= ~SandboxForms;
- else if (equalIgnoringCase(sandboxToken, "allow-scripts")) {
- flags &= ~SandboxScripts;
- flags &= ~SandboxAutomaticFeatures;
- } else if (equalIgnoringCase(sandboxToken, "allow-top-navigation"))
- flags &= ~SandboxTopNavigation;
- else if (equalIgnoringCase(sandboxToken, "allow-popups"))
- flags &= ~SandboxPopups;
- else if (equalIgnoringCase(sandboxToken, "allow-pointer-lock"))
- flags &= ~SandboxPointerLock;
- else {
- if (numberOfTokenErrors)
- tokenErrors.appendLiteral(", '");
- else
- tokenErrors.append('\'');
- tokenErrors.append(sandboxToken);
- tokenErrors.append('\'');
- numberOfTokenErrors++;
- }
-
- start = end + 1;
- }
-
- if (numberOfTokenErrors) {
- if (numberOfTokenErrors > 1)
- tokenErrors.appendLiteral(" are invalid sandbox flags.");
- else
- tokenErrors.appendLiteral(" is an invalid sandbox flag.");
- invalidTokensErrorMessage = tokenErrors.toString();
- }
-
- return flags;
-}
-
}
diff --git a/chromium/third_party/WebKit/Source/core/dom/SecurityContext.h b/chromium/third_party/WebKit/Source/core/dom/SecurityContext.h
index 0674b939bdc..b47c6f4906c 100644
--- a/chromium/third_party/WebKit/Source/core/dom/SecurityContext.h
+++ b/chromium/third_party/WebKit/Source/core/dom/SecurityContext.h
@@ -37,60 +37,29 @@ class SecurityOrigin;
class ContentSecurityPolicy;
class KURL;
-enum SandboxFlag {
- // See http://www.whatwg.org/specs/web-apps/current-work/#attr-iframe-sandbox for a list of the sandbox flags.
- SandboxNone = 0,
- SandboxNavigation = 1,
- SandboxPlugins = 1 << 1,
- SandboxOrigin = 1 << 2,
- SandboxForms = 1 << 3,
- SandboxScripts = 1 << 4,
- SandboxTopNavigation = 1 << 5,
- SandboxPopups = 1 << 6, // See https://www.w3.org/Bugs/Public/show_bug.cgi?id=12393
- SandboxAutomaticFeatures = 1 << 7,
- SandboxSeamlessIframes = 1 << 8,
- SandboxPointerLock = 1 << 9,
- SandboxAll = -1 // Mask with all bits set to 1.
-};
-
-typedef int SandboxFlags;
-
class SecurityContext {
public:
SecurityOrigin* securityOrigin() const { return m_securityOrigin.get(); }
- SandboxFlags sandboxFlags() const { return m_sandboxFlags; }
ContentSecurityPolicy* contentSecurityPolicy() { return m_contentSecurityPolicy.get(); }
bool isSecureTransitionTo(const KURL&) const;
- void enforceSandboxFlags(SandboxFlags mask);
- bool isSandboxed(SandboxFlags mask) const { return m_sandboxFlags & mask; }
-
// Explicitly override the security origin for this security context.
// Note: It is dangerous to change the security origin of a script context
// that already contains content.
void setSecurityOrigin(PassRefPtr<SecurityOrigin>);
- static SandboxFlags parseSandboxPolicy(const String& policy, String& invalidTokensErrorMessage);
-
protected:
SecurityContext();
virtual ~SecurityContext();
- virtual void didUpdateSecurityOrigin();
-
void setContentSecurityPolicy(PassOwnPtr<ContentSecurityPolicy>);
void didFailToInitializeSecurityOrigin() { m_haveInitializedSecurityOrigin = false; }
bool haveInitializedSecurityOrigin() const { return m_haveInitializedSecurityOrigin; }
- // Set in Document::initSecurityContext() at Document creation, per:
- // http://www.whatwg.org/specs/web-apps/current-work/#attr-iframe-seamless
- bool m_mayDisplaySeamlesslyWithParent;
-
private:
bool m_haveInitializedSecurityOrigin;
- SandboxFlags m_sandboxFlags;
RefPtr<SecurityOrigin> m_securityOrigin;
OwnPtr<ContentSecurityPolicy> m_contentSecurityPolicy;
};
diff --git a/chromium/third_party/WebKit/Source/core/dom/SecurityPolicyViolationEvent.h b/chromium/third_party/WebKit/Source/core/dom/SecurityPolicyViolationEvent.h
deleted file mode 100644
index 40ff41b119c..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/SecurityPolicyViolationEvent.h
+++ /dev/null
@@ -1,111 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SecurityPolicyViolationEvent_h
-#define SecurityPolicyViolationEvent_h
-
-#include "core/dom/Event.h"
-#include "core/dom/EventNames.h"
-
-namespace WebCore {
-
-struct SecurityPolicyViolationEventInit : public EventInit {
- SecurityPolicyViolationEventInit()
- {
- }
-
- String documentURI;
- String referrer;
- String blockedURI;
- String violatedDirective;
- String effectiveDirective;
- String originalPolicy;
- String sourceFile;
- int lineNumber;
- int columnNumber;
- int statusCode;
-};
-
-class SecurityPolicyViolationEvent : public Event {
-public:
- static PassRefPtr<SecurityPolicyViolationEvent> create()
- {
- return adoptRef(new SecurityPolicyViolationEvent());
- }
-
- static PassRefPtr<SecurityPolicyViolationEvent> create(const AtomicString& type, const SecurityPolicyViolationEventInit& initializer)
- {
- return adoptRef(new SecurityPolicyViolationEvent(type, initializer));
- }
-
- const String& documentURI() const { return m_documentURI; }
- const String& referrer() const { return m_referrer; }
- const String& blockedURI() const { return m_blockedURI; }
- const String& violatedDirective() const { return m_violatedDirective; }
- const String& effectiveDirective() const { return m_effectiveDirective; }
- const String& originalPolicy() const { return m_originalPolicy; }
- const String& sourceFile() const { return m_sourceFile; }
- int lineNumber() const { return m_lineNumber; }
- int columnNumber() const { return m_columnNumber; }
- int statusCode() const { return m_statusCode; }
-
- virtual const AtomicString& interfaceName() const { return eventNames().interfaceForSecurityPolicyViolationEvent; }
-
-private:
- SecurityPolicyViolationEvent()
- {
- ScriptWrappable::init(this);
- }
-
- SecurityPolicyViolationEvent(const AtomicString& type, const SecurityPolicyViolationEventInit& initializer)
- : Event(type, initializer)
- , m_documentURI(initializer.documentURI)
- , m_referrer(initializer.referrer)
- , m_blockedURI(initializer.blockedURI)
- , m_violatedDirective(initializer.violatedDirective)
- , m_effectiveDirective(initializer.effectiveDirective)
- , m_originalPolicy(initializer.originalPolicy)
- , m_sourceFile(initializer.sourceFile)
- , m_lineNumber(initializer.lineNumber)
- , m_columnNumber(initializer.columnNumber)
- , m_statusCode(initializer.statusCode)
- {
- ScriptWrappable::init(this);
- }
-
- String m_documentURI;
- String m_referrer;
- String m_blockedURI;
- String m_violatedDirective;
- String m_effectiveDirective;
- String m_originalPolicy;
- String m_sourceFile;
- int m_lineNumber;
- int m_columnNumber;
- int m_statusCode;
-};
-
-} // namespace WebCore
-
-#endif // SecurityPolicyViolationEvent_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/SecurityPolicyViolationEvent.idl b/chromium/third_party/WebKit/Source/core/dom/SecurityPolicyViolationEvent.idl
deleted file mode 100644
index d067fab3269..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/SecurityPolicyViolationEvent.idl
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-[
- EnabledAtRuntime=ExperimentalContentSecurityPolicyFeatures,
- ConstructorTemplate=Event
-] interface SecurityPolicyViolationEvent : Event {
- [InitializedByEventConstructor] readonly attribute DOMString documentURI;
- [InitializedByEventConstructor] readonly attribute DOMString referrer;
- [InitializedByEventConstructor] readonly attribute DOMString blockedURI;
- [InitializedByEventConstructor] readonly attribute DOMString violatedDirective;
- [InitializedByEventConstructor] readonly attribute DOMString effectiveDirective;
- [InitializedByEventConstructor] readonly attribute DOMString originalPolicy;
- [InitializedByEventConstructor] readonly attribute DOMString sourceFile;
- [InitializedByEventConstructor] readonly attribute long lineNumber;
- [InitializedByEventConstructor] readonly attribute long columnNumber;
- [InitializedByEventConstructor] readonly attribute long statusCode;
-};
diff --git a/chromium/third_party/WebKit/Source/core/dom/SelectorQuery.cpp b/chromium/third_party/WebKit/Source/core/dom/SelectorQuery.cpp
index 52788443a1c..5fcf2ac55a2 100644
--- a/chromium/third_party/WebKit/Source/core/dom/SelectorQuery.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/SelectorQuery.cpp
@@ -28,12 +28,12 @@
#include "bindings/v8/ExceptionState.h"
#include "core/css/CSSParser.h"
-#include "core/css/CSSSelectorList.h"
#include "core/css/SelectorChecker.h"
#include "core/css/SelectorCheckerFastPath.h"
#include "core/css/SiblingTraversalStrategies.h"
#include "core/dom/Document.h"
#include "core/dom/ElementTraversal.h"
+#include "core/dom/Node.h"
#include "core/dom/StaticNodeList.h"
namespace WebCore {
@@ -64,7 +64,7 @@ private:
class ClassRootNodeList : public SimpleNodeList {
public:
- explicit ClassRootNodeList(Node* rootNode, const AtomicString& className)
+ ClassRootNodeList(Node& rootNode, const AtomicString& className)
: m_className(className)
, m_rootNode(rootNode)
, m_currentElement(nextInternal(ElementTraversal::firstWithin(m_rootNode))) { }
@@ -75,14 +75,14 @@ public:
{
Node* current = m_currentElement;
ASSERT(current);
- m_currentElement = nextInternal(ElementTraversal::nextSkippingChildren(m_currentElement, m_rootNode));
+ m_currentElement = nextInternal(ElementTraversal::nextSkippingChildren(*m_currentElement, &m_rootNode));
return current;
}
private:
Element* nextInternal(Element* element)
{
- for (; element; element = ElementTraversal::next(element, m_rootNode)) {
+ for (; element; element = ElementTraversal::next(*element, &m_rootNode)) {
if (element->hasClass() && element->classNames().contains(m_className))
return element;
}
@@ -90,13 +90,13 @@ private:
}
const AtomicString& m_className;
- Node* m_rootNode;
+ Node& m_rootNode;
Element* m_currentElement;
};
class ClassElementList : public SimpleNodeList {
public:
- explicit ClassElementList(Node* rootNode, const AtomicString& className)
+ ClassElementList(Node& rootNode, const AtomicString& className)
: m_className(className)
, m_rootNode(rootNode)
, m_currentElement(nextInternal(ElementTraversal::firstWithin(rootNode))) { }
@@ -107,14 +107,14 @@ public:
{
Node* current = m_currentElement;
ASSERT(current);
- m_currentElement = nextInternal(ElementTraversal::next(m_currentElement, m_rootNode));
+ m_currentElement = nextInternal(ElementTraversal::next(*m_currentElement, &m_rootNode));
return current;
}
private:
Element* nextInternal(Element* element)
{
- for (; element; element = ElementTraversal::next(element, m_rootNode)) {
+ for (; element; element = ElementTraversal::next(*element, &m_rootNode)) {
if (element->hasClass() && element->classNames().contains(m_className))
return element;
}
@@ -122,7 +122,7 @@ private:
}
const AtomicString& m_className;
- Node* m_rootNode;
+ Node& m_rootNode;
Element* m_currentElement;
};
@@ -139,27 +139,24 @@ void SelectorDataList::initialize(const CSSSelectorList& selectorList)
m_selectors.uncheckedAppend(SelectorData(selector, SelectorCheckerFastPath::canUse(selector)));
}
-inline bool SelectorDataList::selectorMatches(const SelectorData& selectorData, Element* element, const Node* rootNode) const
+inline bool SelectorDataList::selectorMatches(const SelectorData& selectorData, Element& element, const Node& rootNode) const
{
- if (selectorData.isFastCheckable && !element->isSVGElement()) {
+ if (selectorData.isFastCheckable && !element.isSVGElement()) {
SelectorCheckerFastPath selectorCheckerFastPath(selectorData.selector, element);
if (!selectorCheckerFastPath.matchesRightmostSelector(SelectorChecker::VisitedMatchDisabled))
return false;
return selectorCheckerFastPath.matches();
}
- SelectorChecker selectorChecker(element->document(), SelectorChecker::QueryingRules);
- SelectorChecker::SelectorCheckingContext selectorCheckingContext(selectorData.selector, element, SelectorChecker::VisitedMatchDisabled);
+ SelectorChecker selectorChecker(element.document(), SelectorChecker::QueryingRules);
+ SelectorChecker::SelectorCheckingContext selectorCheckingContext(selectorData.selector, &element, SelectorChecker::VisitedMatchDisabled);
selectorCheckingContext.behaviorAtBoundary = SelectorChecker::StaysWithinTreeScope;
- selectorCheckingContext.scope = !rootNode->isDocumentNode() && rootNode->isContainerNode() ? toContainerNode(rootNode) : 0;
- PseudoId ignoreDynamicPseudo = NOPSEUDO;
- return selectorChecker.match(selectorCheckingContext, ignoreDynamicPseudo, DOMSiblingTraversalStrategy()) == SelectorChecker::SelectorMatches;
+ selectorCheckingContext.scope = !rootNode.isDocumentNode() && rootNode.isContainerNode() ? &toContainerNode(rootNode) : 0;
+ return selectorChecker.match(selectorCheckingContext, DOMSiblingTraversalStrategy()) == SelectorChecker::SelectorMatches;
}
-bool SelectorDataList::matches(Element* targetElement) const
+bool SelectorDataList::matches(Element& targetElement) const
{
- ASSERT(targetElement);
-
unsigned selectorCount = m_selectors.size();
for (unsigned i = 0; i < selectorCount; ++i) {
if (selectorMatches(m_selectors[i], targetElement, targetElement))
@@ -169,69 +166,63 @@ bool SelectorDataList::matches(Element* targetElement) const
return false;
}
-PassRefPtr<NodeList> SelectorDataList::queryAll(Node* rootNode) const
+PassRefPtr<NodeList> SelectorDataList::queryAll(Node& rootNode) const
{
Vector<RefPtr<Node> > result;
executeQueryAll(rootNode, result);
return StaticNodeList::adopt(result);
}
-PassRefPtr<Element> SelectorDataList::queryFirst(Node* rootNode) const
+PassRefPtr<Element> SelectorDataList::queryFirst(Node& rootNode) const
{
return executeQueryFirst(rootNode);
}
-static inline bool isTreeScopeRoot(Node* node)
-{
- ASSERT(node);
- return node->isDocumentNode() || node->isShadowRoot();
-}
-
-void SelectorDataList::collectElementsByClassName(Node* rootNode, const AtomicString& className, Vector<RefPtr<Node> >& traversalRoots) const
+void SelectorDataList::collectElementsByClassName(Node& rootNode, const AtomicString& className, Vector<RefPtr<Node> >& traversalRoots) const
{
- for (Element* element = ElementTraversal::firstWithin(rootNode); element; element = ElementTraversal::next(element, rootNode)) {
+ for (Element* element = ElementTraversal::firstWithin(rootNode); element; element = ElementTraversal::next(*element, &rootNode)) {
if (element->hasClass() && element->classNames().contains(className))
traversalRoots.append(element);
}
}
-void SelectorDataList::collectElementsByTagName(Node* rootNode, const QualifiedName& tagName, Vector<RefPtr<Node> >& traversalRoots) const
+void SelectorDataList::collectElementsByTagName(Node& rootNode, const QualifiedName& tagName, Vector<RefPtr<Node> >& traversalRoots) const
{
- for (Element* element = ElementTraversal::firstWithin(rootNode); element; element = ElementTraversal::next(element, rootNode)) {
- if (SelectorChecker::tagMatches(element, tagName))
+ for (Element* element = ElementTraversal::firstWithin(rootNode); element; element = ElementTraversal::next(*element, &rootNode)) {
+ if (SelectorChecker::tagMatches(*element, tagName))
traversalRoots.append(element);
}
}
-Element* SelectorDataList::findElementByClassName(Node* rootNode, const AtomicString& className) const
+Element* SelectorDataList::findElementByClassName(Node& rootNode, const AtomicString& className) const
{
- for (Element* element = ElementTraversal::firstWithin(rootNode); element; element = ElementTraversal::next(element, rootNode)) {
+ for (Element* element = ElementTraversal::firstWithin(rootNode); element; element = ElementTraversal::next(*element, &rootNode)) {
if (element->hasClass() && element->classNames().contains(className))
return element;
}
return 0;
}
-Element* SelectorDataList::findElementByTagName(Node* rootNode, const QualifiedName& tagName) const
+Element* SelectorDataList::findElementByTagName(Node& rootNode, const QualifiedName& tagName) const
{
- for (Element* element = ElementTraversal::firstWithin(rootNode); element; element = ElementTraversal::next(element, rootNode)) {
- if (SelectorChecker::tagMatches(element, tagName))
+ for (Element* element = ElementTraversal::firstWithin(rootNode); element; element = ElementTraversal::next(*element, &rootNode)) {
+ if (SelectorChecker::tagMatches(*element, tagName))
return element;
}
return 0;
}
-inline bool SelectorDataList::canUseFastQuery(Node* rootNode) const
+inline bool SelectorDataList::canUseFastQuery(const Node& rootNode) const
{
- return m_selectors.size() == 1 && rootNode->inDocument() && !rootNode->document().inQuirksMode();
+ return m_selectors.size() == 1 && rootNode.inDocument() && !rootNode.document().inQuirksMode();
}
-inline bool ancestorHasClassName(Node* rootNode, const AtomicString& className)
+inline bool ancestorHasClassName(Node& rootNode, const AtomicString& className)
{
- if (!rootNode->isElementNode())
+ if (!rootNode.isElementNode())
return false;
- for (Element* element = toElement(rootNode); element; element = element->parentElement()) {
+ for (Element* element = &toElement(rootNode); element; element = element->parentElement()) {
if (element->hasClass() && element->classNames().contains(className))
return true;
}
@@ -246,11 +237,10 @@ inline bool ancestorHasClassName(Node* rootNode, const AtomicString& className)
//
// The travseralRoots may be empty, regardless of the returned bool value, if this method finds that the selectors won't
// match any element.
-PassOwnPtr<SimpleNodeList> SelectorDataList::findTraverseRoots(Node* rootNode, bool& matchTraverseRoots) const
+PassOwnPtr<SimpleNodeList> SelectorDataList::findTraverseRoots(Node& rootNode, bool& matchTraverseRoots) const
{
// We need to return the matches in document order. To use id lookup while there is possiblity of multiple matches
// we would need to sort the results. For now, just traverse the document in that case.
- ASSERT(rootNode);
ASSERT(m_selectors.size() == 1);
ASSERT(m_selectors[0].selector);
@@ -258,21 +248,22 @@ PassOwnPtr<SimpleNodeList> SelectorDataList::findTraverseRoots(Node* rootNode, b
bool startFromParent = false;
for (const CSSSelector* selector = m_selectors[0].selector; selector; selector = selector->tagHistory()) {
- if (selector->m_match == CSSSelector::Id && !rootNode->document().containsMultipleElementsWithId(selector->value())) {
- Element* element = rootNode->treeScope().getElementById(selector->value());
- if (element && (isTreeScopeRoot(rootNode) || element->isDescendantOf(rootNode)))
- rootNode = element;
+ if (selector->m_match == CSSSelector::Id && !rootNode.document().containsMultipleElementsWithId(selector->value())) {
+ Element* element = rootNode.treeScope().getElementById(selector->value());
+ Node* adjustedNode = &rootNode;
+ if (element && (isTreeScopeRoot(rootNode) || element->isDescendantOf(&rootNode)))
+ adjustedNode = element;
else if (!element || isRightmostSelector)
- rootNode = 0;
+ adjustedNode = 0;
if (isRightmostSelector) {
matchTraverseRoots = true;
- return adoptPtr(new SingleNodeList(rootNode));
+ return adoptPtr(new SingleNodeList(adjustedNode));
}
- if (startFromParent && rootNode)
- rootNode = rootNode->parentNode();
+ if (startFromParent && adjustedNode)
+ adjustedNode = adjustedNode->parentNode();
matchTraverseRoots = false;
- return adoptPtr(new SingleNodeList(rootNode));
+ return adoptPtr(new SingleNodeList(adjustedNode));
}
// If we have both CSSSelector::Id and CSSSelector::Class at the same time, we should use Id
@@ -285,7 +276,7 @@ PassOwnPtr<SimpleNodeList> SelectorDataList::findTraverseRoots(Node* rootNode, b
matchTraverseRoots = false;
// Since there exists some ancestor element which has the class name, we need to see all children of rootNode.
if (ancestorHasClassName(rootNode, selector->value()))
- return adoptPtr(new SingleNodeList(rootNode));
+ return adoptPtr(new SingleNodeList(&rootNode));
return adoptPtr(new ClassRootNodeList(rootNode, selector->value()));
}
@@ -300,14 +291,14 @@ PassOwnPtr<SimpleNodeList> SelectorDataList::findTraverseRoots(Node* rootNode, b
}
matchTraverseRoots = false;
- return adoptPtr(new SingleNodeList(rootNode));
+ return adoptPtr(new SingleNodeList(&rootNode));
}
-void SelectorDataList::executeSlowQueryAll(Node* rootNode, Vector<RefPtr<Node> >& matchedElements) const
+void SelectorDataList::executeSlowQueryAll(Node& rootNode, Vector<RefPtr<Node> >& matchedElements) const
{
- for (Element* element = ElementTraversal::firstWithin(rootNode); element; element = ElementTraversal::next(element, rootNode)) {
+ for (Element* element = ElementTraversal::firstWithin(rootNode); element; element = ElementTraversal::next(*element, &rootNode)) {
for (unsigned i = 0; i < m_selectors.size(); ++i) {
- if (selectorMatches(m_selectors[i], element, rootNode)) {
+ if (selectorMatches(m_selectors[i], *element, rootNode)) {
matchedElements.append(element);
break;
}
@@ -315,7 +306,7 @@ void SelectorDataList::executeSlowQueryAll(Node* rootNode, Vector<RefPtr<Node> >
}
}
-void SelectorDataList::executeQueryAll(Node* rootNode, Vector<RefPtr<Node> >& matchedElements) const
+void SelectorDataList::executeQueryAll(Node& rootNode, Vector<RefPtr<Node> >& matchedElements) const
{
if (!canUseFastQuery(rootNode))
return executeSlowQueryAll(rootNode, matchedElements);
@@ -330,12 +321,12 @@ void SelectorDataList::executeQueryAll(Node* rootNode, Vector<RefPtr<Node> >& ma
switch (firstSelector->m_match) {
case CSSSelector::Id:
{
- if (rootNode->document().containsMultipleElementsWithId(firstSelector->value()))
+ if (rootNode.document().containsMultipleElementsWithId(firstSelector->value()))
break;
// Just the same as getElementById.
- Element* element = rootNode->treeScope().getElementById(firstSelector->value());
- if (element && (isTreeScopeRoot(rootNode) || element->isDescendantOf(rootNode)))
+ Element* element = rootNode.treeScope().getElementById(firstSelector->value());
+ if (element && (isTreeScopeRoot(rootNode) || element->isDescendantOf(&rootNode)))
matchedElements.append(element);
return;
}
@@ -356,18 +347,19 @@ void SelectorDataList::executeQueryAll(Node* rootNode, Vector<RefPtr<Node> >& ma
const SelectorData& selector = m_selectors[0];
if (matchTraverseRoots) {
while (!traverseRoots->isEmpty()) {
- Node* node = traverseRoots->next();
- Element* element = toElement(node);
+ Node& node = *traverseRoots->next();
+ Element& element = toElement(node);
if (selectorMatches(selector, element, rootNode))
- matchedElements.append(element);
+ matchedElements.append(&element);
}
return;
}
while (!traverseRoots->isEmpty()) {
Node* traverseRoot = traverseRoots->next();
- for (Element* element = ElementTraversal::firstWithin(traverseRoot); element; element = ElementTraversal::next(element, traverseRoot)) {
- if (selectorMatches(selector, element, rootNode))
+ ASSERT(traverseRoot);
+ for (Element* element = ElementTraversal::firstWithin(*traverseRoot); element; element = ElementTraversal::next(*element, traverseRoot)) {
+ if (selectorMatches(selector, *element, rootNode))
matchedElements.append(element);
}
}
@@ -380,31 +372,31 @@ void SelectorDataList::executeQueryAll(Node* rootNode, Vector<RefPtr<Node> >& ma
//
// The returned Node may be 0, regardless of matchTraverseRoot, if this method finds that the selectors won't
// match any element.
-Node* SelectorDataList::findTraverseRoot(Node* rootNode, bool& matchTraverseRoot) const
+Node* SelectorDataList::findTraverseRoot(Node& rootNode, bool& matchTraverseRoot) const
{
// We need to return the matches in document order. To use id lookup while there is possiblity of multiple matches
// we would need to sort the results. For now, just traverse the document in that case.
- ASSERT(rootNode);
ASSERT(m_selectors.size() == 1);
ASSERT(m_selectors[0].selector);
bool matchSingleNode = true;
bool startFromParent = false;
for (const CSSSelector* selector = m_selectors[0].selector; selector; selector = selector->tagHistory()) {
- if (selector->m_match == CSSSelector::Id && !rootNode->document().containsMultipleElementsWithId(selector->value())) {
- Element* element = rootNode->treeScope().getElementById(selector->value());
- if (element && (isTreeScopeRoot(rootNode) || element->isDescendantOf(rootNode)))
- rootNode = element;
+ if (selector->m_match == CSSSelector::Id && !rootNode.document().containsMultipleElementsWithId(selector->value())) {
+ Element* element = rootNode.treeScope().getElementById(selector->value());
+ Node* adjustedRootNode = &rootNode;
+ if (element && (isTreeScopeRoot(rootNode) || element->isDescendantOf(&rootNode)))
+ adjustedRootNode = element;
else if (!element || matchSingleNode)
- rootNode = 0;
+ adjustedRootNode = 0;
if (matchSingleNode) {
matchTraverseRoot = true;
- return rootNode;
+ return adjustedRootNode;
}
- if (startFromParent && rootNode)
- rootNode = rootNode->parentNode();
+ if (startFromParent && adjustedRootNode)
+ adjustedRootNode = adjustedRootNode->parentNode();
matchTraverseRoot = false;
- return rootNode;
+ return adjustedRootNode;
}
if (selector->relation() == CSSSelector::SubSelector)
continue;
@@ -415,21 +407,21 @@ Node* SelectorDataList::findTraverseRoot(Node* rootNode, bool& matchTraverseRoot
startFromParent = false;
}
matchTraverseRoot = false;
- return rootNode;
+ return &rootNode;
}
-Element* SelectorDataList::executeSlowQueryFirst(Node* rootNode) const
+Element* SelectorDataList::executeSlowQueryFirst(Node& rootNode) const
{
- for (Element* element = ElementTraversal::firstWithin(rootNode); element; element = ElementTraversal::next(element, rootNode)) {
+ for (Element* element = ElementTraversal::firstWithin(rootNode); element; element = ElementTraversal::next(*element, &rootNode)) {
for (unsigned i = 0; i < m_selectors.size(); ++i) {
- if (selectorMatches(m_selectors[i], element, rootNode))
+ if (selectorMatches(m_selectors[i], *element, rootNode))
return element;
}
}
return 0;
}
-Element* SelectorDataList::executeQueryFirst(Node* rootNode) const
+Element* SelectorDataList::executeQueryFirst(Node& rootNode) const
{
if (!canUseFastQuery(rootNode))
return executeSlowQueryFirst(rootNode);
@@ -444,10 +436,10 @@ Element* SelectorDataList::executeQueryFirst(Node* rootNode) const
switch (selector->m_match) {
case CSSSelector::Id:
{
- if (rootNode->document().containsMultipleElementsWithId(selector->value()))
+ if (rootNode.document().containsMultipleElementsWithId(selector->value()))
break;
- Element* element = rootNode->treeScope().getElementById(selector->value());
- return element && (isTreeScopeRoot(rootNode) || element->isDescendantOf(rootNode)) ? element : 0;
+ Element* element = rootNode.treeScope().getElementById(selector->value());
+ return element && (isTreeScopeRoot(rootNode) || element->isDescendantOf(&rootNode)) ? element : 0;
}
case CSSSelector::Class:
return findElementByClassName(rootNode, selector->value());
@@ -465,12 +457,12 @@ Element* SelectorDataList::executeQueryFirst(Node* rootNode) const
if (matchTraverseRoot) {
ASSERT(m_selectors.size() == 1);
ASSERT(traverseRootNode->isElementNode());
- Element* element = toElement(traverseRootNode);
- return selectorMatches(m_selectors[0], element, rootNode) ? element : 0;
+ Element& element = toElement(*traverseRootNode);
+ return selectorMatches(m_selectors[0], element, rootNode) ? &element : 0;
}
- for (Element* element = ElementTraversal::firstWithin(traverseRootNode); element; element = ElementTraversal::next(element, traverseRootNode)) {
- if (selectorMatches(m_selectors[0], element, rootNode))
+ for (Element* element = ElementTraversal::firstWithin(*traverseRootNode); element; element = ElementTraversal::next(*element, traverseRootNode)) {
+ if (selectorMatches(m_selectors[0], *element, rootNode))
return element;
}
return 0;
@@ -482,22 +474,22 @@ SelectorQuery::SelectorQuery(const CSSSelectorList& selectorList)
m_selectors.initialize(m_selectorList);
}
-bool SelectorQuery::matches(Element* element) const
+bool SelectorQuery::matches(Element& element) const
{
return m_selectors.matches(element);
}
-PassRefPtr<NodeList> SelectorQuery::queryAll(Node* rootNode) const
+PassRefPtr<NodeList> SelectorQuery::queryAll(Node& rootNode) const
{
return m_selectors.queryAll(rootNode);
}
-PassRefPtr<Element> SelectorQuery::queryFirst(Node* rootNode) const
+PassRefPtr<Element> SelectorQuery::queryFirst(Node& rootNode) const
{
return m_selectors.queryFirst(rootNode);
}
-SelectorQuery* SelectorQueryCache::add(const AtomicString& selectors, const Document& document, ExceptionState& es)
+SelectorQuery* SelectorQueryCache::add(const AtomicString& selectors, const Document& document, ExceptionState& exceptionState)
{
HashMap<AtomicString, OwnPtr<SelectorQuery> >::iterator it = m_entries.find(selectors);
if (it != m_entries.end())
@@ -508,17 +500,17 @@ SelectorQuery* SelectorQueryCache::add(const AtomicString& selectors, const Docu
parser.parseSelector(selectors, selectorList);
if (!selectorList.first()) {
- es.throwDOMException(SyntaxError, "Failed to execute query: '" + selectors + "' is not a valid selector.");
+ exceptionState.throwDOMException(SyntaxError, "'" + selectors + "' is not a valid selector.");
return 0;
}
// throw a NamespaceError if the selector includes any namespace prefixes.
if (selectorList.selectorsNeedNamespaceResolution()) {
- es.throwDOMException(NamespaceError, "Failed to execute query: '" + selectors + "' contains namespaces, which are not supported.");
+ exceptionState.throwDOMException(NamespaceError, "'" + selectors + "' contains namespaces, which are not supported.");
return 0;
}
- const int maximumSelectorQueryCacheSize = 256;
+ const unsigned maximumSelectorQueryCacheSize = 256;
if (m_entries.size() == maximumSelectorQueryCacheSize)
m_entries.remove(m_entries.begin());
diff --git a/chromium/third_party/WebKit/Source/core/dom/SelectorQuery.h b/chromium/third_party/WebKit/Source/core/dom/SelectorQuery.h
index 2f654c41d94..fb787ab9787 100644
--- a/chromium/third_party/WebKit/Source/core/dom/SelectorQuery.h
+++ b/chromium/third_party/WebKit/Source/core/dom/SelectorQuery.h
@@ -45,9 +45,9 @@ class SpaceSplitString;
class SelectorDataList {
public:
void initialize(const CSSSelectorList&);
- bool matches(Element*) const;
- PassRefPtr<NodeList> queryAll(Node* rootNode) const;
- PassRefPtr<Element> queryFirst(Node* rootNode) const;
+ bool matches(Element&) const;
+ PassRefPtr<NodeList> queryAll(Node& rootNode) const;
+ PassRefPtr<Element> queryFirst(Node& rootNode) const;
private:
struct SelectorData {
@@ -56,18 +56,18 @@ private:
bool isFastCheckable;
};
- bool canUseFastQuery(Node* rootNode) const;
- bool selectorMatches(const SelectorData&, Element*, const Node*) const;
- void collectElementsByClassName(Node* rootNode, const AtomicString& className, Vector<RefPtr<Node> >&) const;
- Element* findElementByClassName(Node* rootNode, const AtomicString& className) const;
- void collectElementsByTagName(Node* rootNode, const QualifiedName& tagName, Vector<RefPtr<Node> >&) const;
- Element* findElementByTagName(Node* rootNode, const QualifiedName& tagName) const;
- PassOwnPtr<SimpleNodeList> findTraverseRoots(Node* rootNode, bool& matchTraverseRoots) const;
- void executeSlowQueryAll(Node* rootNode, Vector<RefPtr<Node> >& matchedElements) const;
- void executeQueryAll(Node* rootNode, Vector<RefPtr<Node> >& matchedElements) const;
- Node* findTraverseRoot(Node* rootNode, bool& matchTraverseRoot) const;
- Element* executeSlowQueryFirst(Node* rootNode) const;
- Element* executeQueryFirst(Node* rootNode) const;
+ bool canUseFastQuery(const Node& rootNode) const;
+ bool selectorMatches(const SelectorData&, Element&, const Node&) const;
+ void collectElementsByClassName(Node& rootNode, const AtomicString& className, Vector<RefPtr<Node> >&) const;
+ Element* findElementByClassName(Node& rootNode, const AtomicString& className) const;
+ void collectElementsByTagName(Node& rootNode, const QualifiedName& tagName, Vector<RefPtr<Node> >&) const;
+ Element* findElementByTagName(Node& rootNode, const QualifiedName& tagName) const;
+ PassOwnPtr<SimpleNodeList> findTraverseRoots(Node& rootNode, bool& matchTraverseRoots) const;
+ void executeSlowQueryAll(Node& rootNode, Vector<RefPtr<Node> >& matchedElements) const;
+ void executeQueryAll(Node& rootNode, Vector<RefPtr<Node> >& matchedElements) const;
+ Node* findTraverseRoot(Node& rootNode, bool& matchTraverseRoot) const;
+ Element* executeSlowQueryFirst(Node& rootNode) const;
+ Element* executeQueryFirst(Node& rootNode) const;
Vector<SelectorData> m_selectors;
};
@@ -77,9 +77,9 @@ class SelectorQuery {
WTF_MAKE_FAST_ALLOCATED;
public:
explicit SelectorQuery(const CSSSelectorList&);
- bool matches(Element*) const;
- PassRefPtr<NodeList> queryAll(Node* rootNode) const;
- PassRefPtr<Element> queryFirst(Node* rootNode) const;
+ bool matches(Element&) const;
+ PassRefPtr<NodeList> queryAll(Node& rootNode) const;
+ PassRefPtr<Element> queryFirst(Node& rootNode) const;
private:
SelectorDataList m_selectors;
CSSSelectorList m_selectorList;
diff --git a/chromium/third_party/WebKit/Source/core/dom/ShadowTreeStyleSheetCollection.cpp b/chromium/third_party/WebKit/Source/core/dom/ShadowTreeStyleSheetCollection.cpp
index a952d05b176..4285d26c27f 100644
--- a/chromium/third_party/WebKit/Source/core/dom/ShadowTreeStyleSheetCollection.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/ShadowTreeStyleSheetCollection.cpp
@@ -30,12 +30,11 @@
#include "HTMLNames.h"
#include "core/css/CSSStyleSheet.h"
#include "core/css/resolver/StyleResolver.h"
-#include "core/dom/Document.h"
#include "core/dom/Element.h"
#include "core/dom/StyleEngine.h"
#include "core/dom/shadow/ShadowRoot.h"
#include "core/html/HTMLStyleElement.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
namespace WebCore {
@@ -46,11 +45,8 @@ ShadowTreeStyleSheetCollection::ShadowTreeStyleSheetCollection(ShadowRoot& shado
{
}
-void ShadowTreeStyleSheetCollection::collectStyleSheets(StyleEngine* collections, Vector<RefPtr<StyleSheet> >& styleSheets, Vector<RefPtr<CSSStyleSheet> >& activeSheets)
+void ShadowTreeStyleSheetCollection::collectStyleSheets(StyleEngine* engine, StyleSheetCollectionBase& collection)
{
- if (document()->settings() && !document()->settings()->authorAndUserStylesEnabled())
- return;
-
DocumentOrderedList::iterator begin = m_styleSheetCandidateNodes.begin();
DocumentOrderedList::iterator end = m_styleSheetCandidateNodes.end();
for (DocumentOrderedList::iterator it = begin; it != end; ++it) {
@@ -67,20 +63,20 @@ void ShadowTreeStyleSheetCollection::collectStyleSheets(StyleEngine* collections
sheet = toHTMLStyleElement(node)->sheet();
if (sheet && !sheet->disabled() && sheet->isCSSStyleSheet())
- activeSheet = static_cast<CSSStyleSheet*>(sheet);
+ activeSheet = toCSSStyleSheet(sheet);
// FIXME: clarify how PREFERRED or ALTERNATE works in shadow trees.
// Should we set preferred/selected stylesheets name in shadow trees and
// use the name in document?
AtomicString rel = element->getAttribute(relAttr);
if (!enabledViaScript && sheet && !title.isEmpty()) {
- if (collections->preferredStylesheetSetName().isEmpty()) {
+ if (engine->preferredStylesheetSetName().isEmpty()) {
if (element->hasLocalName(styleTag) || !rel.contains("alternate")) {
- collections->setPreferredStylesheetSetName(title);
- collections->setSelectedStylesheetSetName(title);
+ engine->setPreferredStylesheetSetName(title);
+ engine->setSelectedStylesheetSetName(title);
}
}
- if (title != collections->preferredStylesheetSetName())
+ if (title != engine->preferredStylesheetSetName())
activeSheet = 0;
}
@@ -88,45 +84,42 @@ void ShadowTreeStyleSheetCollection::collectStyleSheets(StyleEngine* collections
activeSheet = 0;
if (sheet)
- styleSheets.append(sheet);
+ collection.appendSheetForList(sheet);
if (activeSheet)
- activeSheets.append(activeSheet);
+ collection.appendActiveStyleSheet(activeSheet);
}
}
-bool ShadowTreeStyleSheetCollection::updateActiveStyleSheets(StyleEngine* collections, StyleResolverUpdateMode updateMode)
+bool ShadowTreeStyleSheetCollection::updateActiveStyleSheets(StyleEngine* engine, StyleResolverUpdateMode updateMode)
{
- Vector<RefPtr<StyleSheet> > styleSheets;
- Vector<RefPtr<CSSStyleSheet> > activeCSSStyleSheets;
- collectStyleSheets(collections, styleSheets, activeCSSStyleSheets);
-
- bool requiresFullStyleRecalc = true;
+ StyleSheetCollectionBase collection;
+ collectStyleSheets(engine, collection);
- // If we have already decided to destroy StyleResolver, we don't need to analyze. Reconstruction will take care.
- if (StyleResolver* styleResolver = document()->styleResolverIfExists()) {
- StyleResolverUpdateType styleResolverUpdateType;
-
- analyzeStyleSheetChange(updateMode, activeAuthorStyleSheets(), activeCSSStyleSheets, styleResolverUpdateType, requiresFullStyleRecalc);
+ StyleSheetChange change;
+ analyzeStyleSheetChange(updateMode, collection, change);
+ if (StyleResolver* styleResolver = engine->resolver()) {
// FIXME: We might have already had styles in child treescope. In this case, we cannot use buildScopedStyleTreeInDocumentOrder.
// Need to change "false" to some valid condition.
styleResolver->setBuildScopedStyleTreeInDocumentOrder(false);
- if (styleResolverUpdateType == Reset || styleResolverUpdateType == Reconstruct) {
+ if (change.styleResolverUpdateType != Additive) {
// We should not destroy StyleResolver when we find any stylesheet update in a shadow tree.
// In this case, we will reset rulesets created from style elements in the shadow tree.
resetAllRuleSetsInTreeScope(styleResolver);
- styleResolver->appendAuthorStyleSheets(0, activeCSSStyleSheets);
+ styleResolver->removePendingAuthorStyleSheets(m_activeAuthorStyleSheets);
+ styleResolver->lazyAppendAuthorStyleSheets(0, collection.activeAuthorStyleSheets());
} else {
- ASSERT(styleResolverUpdateType == Additive);
- styleResolver->appendAuthorStyleSheets(m_activeAuthorStyleSheets.size(), activeCSSStyleSheets);
+ styleResolver->lazyAppendAuthorStyleSheets(m_activeAuthorStyleSheets.size(), collection.activeAuthorStyleSheets());
}
}
+ if (change.requiresFullStyleRecalc)
+ toShadowRoot(m_treeScope.rootNode())->host()->setNeedsStyleRecalc();
+
m_scopingNodesForStyleScoped.didRemoveScopingNodes();
- m_activeAuthorStyleSheets.swap(activeCSSStyleSheets);
- m_styleSheetsForStyleSheetList.swap(styleSheets);
+ collection.swap(*this);
updateUsesRemUnits();
- return requiresFullStyleRecalc;
+ return change.requiresFullStyleRecalc;
}
}
diff --git a/chromium/third_party/WebKit/Source/core/dom/ShadowTreeStyleSheetCollection.h b/chromium/third_party/WebKit/Source/core/dom/ShadowTreeStyleSheetCollection.h
index 253ad63cd12..b7c13cb39cc 100644
--- a/chromium/third_party/WebKit/Source/core/dom/ShadowTreeStyleSheetCollection.h
+++ b/chromium/third_party/WebKit/Source/core/dom/ShadowTreeStyleSheetCollection.h
@@ -46,7 +46,7 @@ public:
bool updateActiveStyleSheets(StyleEngine*, StyleResolverUpdateMode);
private:
- void collectStyleSheets(StyleEngine*, Vector<RefPtr<StyleSheet> >& styleSheets, Vector<RefPtr<CSSStyleSheet> >& activeSheets);
+ void collectStyleSheets(StyleEngine*, StyleSheetCollectionBase&);
};
}
diff --git a/chromium/third_party/WebKit/Source/core/dom/SimulatedClickOptions.h b/chromium/third_party/WebKit/Source/core/dom/SimulatedClickOptions.h
index a49ed749650..8feefed56e6 100644
--- a/chromium/third_party/WebKit/Source/core/dom/SimulatedClickOptions.h
+++ b/chromium/third_party/WebKit/Source/core/dom/SimulatedClickOptions.h
@@ -29,11 +29,6 @@ enum SimulatedClickMouseEventOptions {
SendMouseOverUpDownEvents
};
-enum SimulatedClickVisualOptions {
- DoNotShowPressedLook,
- ShowPressedLook
-};
-
} // namespace WebCore
#endif // SimulatedClickOptions_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/StaticNodeList.h b/chromium/third_party/WebKit/Source/core/dom/StaticNodeList.h
index ece0926d18e..fd66b3aa957 100644
--- a/chromium/third_party/WebKit/Source/core/dom/StaticNodeList.h
+++ b/chromium/third_party/WebKit/Source/core/dom/StaticNodeList.h
@@ -36,31 +36,29 @@
namespace WebCore {
- class Node;
+class Node;
- class StaticNodeList : public NodeList {
- public:
- static PassRefPtr<StaticNodeList> adopt(Vector<RefPtr<Node> >& nodes)
- {
- RefPtr<StaticNodeList> nodeList = adoptRef(new StaticNodeList);
- nodeList->m_nodes.swap(nodes);
- return nodeList.release();
- }
+class StaticNodeList FINAL : public NodeList {
+public:
+ static PassRefPtr<StaticNodeList> adopt(Vector<RefPtr<Node> >& nodes)
+ {
+ RefPtr<StaticNodeList> nodeList = adoptRef(new StaticNodeList);
+ nodeList->m_nodes.swap(nodes);
+ return nodeList.release();
+ }
- static PassRefPtr<StaticNodeList> createEmpty()
- {
- return adoptRef(new StaticNodeList);
- }
+ static PassRefPtr<StaticNodeList> createEmpty()
+ {
+ return adoptRef(new StaticNodeList);
+ }
- virtual unsigned length() const OVERRIDE;
- virtual Node* item(unsigned index) const OVERRIDE;
- virtual Node* namedItem(const AtomicString&) const OVERRIDE;
+ virtual unsigned length() const OVERRIDE;
+ virtual Node* item(unsigned index) const OVERRIDE;
+ virtual Node* namedItem(const AtomicString&) const OVERRIDE;
- private:
- StaticNodeList() { }
-
- Vector<RefPtr<Node> > m_nodes;
- };
+private:
+ Vector<RefPtr<Node> > m_nodes;
+};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/StringCallback.cpp b/chromium/third_party/WebKit/Source/core/dom/StringCallback.cpp
index 092f70e2686..1a1a5fc7495 100644
--- a/chromium/third_party/WebKit/Source/core/dom/StringCallback.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/StringCallback.cpp
@@ -31,41 +31,42 @@
#include "config.h"
#include "core/dom/StringCallback.h"
-#include "core/dom/ScriptExecutionContext.h"
+#include "core/dom/ExecutionContext.h"
+#include "core/dom/ExecutionContextTask.h"
#include "wtf/text/WTFString.h"
namespace WebCore {
namespace {
-class DispatchCallbackTask : public ScriptExecutionContext::Task {
+class DispatchCallbackTask : public ExecutionContextTask {
public:
- static PassOwnPtr<DispatchCallbackTask> create(PassRefPtr<StringCallback> callback, const String& data)
+ static PassOwnPtr<DispatchCallbackTask> create(PassOwnPtr<StringCallback> callback, const String& data)
{
return adoptPtr(new DispatchCallbackTask(callback, data));
}
- virtual void performTask(ScriptExecutionContext*)
+ virtual void performTask(ExecutionContext*)
{
m_callback->handleEvent(m_data);
}
private:
- DispatchCallbackTask(PassRefPtr<StringCallback> callback, const String& data)
+ DispatchCallbackTask(PassOwnPtr<StringCallback> callback, const String& data)
: m_callback(callback)
, m_data(data)
{
}
- RefPtr<StringCallback> m_callback;
+ OwnPtr<StringCallback> m_callback;
const String m_data;
};
} // namespace
-void StringCallback::scheduleCallback(ScriptExecutionContext* context, const String& data)
+void StringCallback::scheduleCallback(PassOwnPtr<StringCallback> callback, ExecutionContext* context, const String& data)
{
- context->postTask(DispatchCallbackTask::create(this, data));
+ context->postTask(DispatchCallbackTask::create(callback, data));
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/StringCallback.h b/chromium/third_party/WebKit/Source/core/dom/StringCallback.h
index e600847a45a..fdd260f01ce 100644
--- a/chromium/third_party/WebKit/Source/core/dom/StringCallback.h
+++ b/chromium/third_party/WebKit/Source/core/dom/StringCallback.h
@@ -32,19 +32,18 @@
#define StringCallback_h
#include "wtf/Forward.h"
-#include "wtf/RefCounted.h"
namespace WebCore {
-class ScriptExecutionContext;
+class ExecutionContext;
-class StringCallback : public RefCounted<StringCallback> {
+class StringCallback {
public:
virtual ~StringCallback() { }
- virtual bool handleEvent(const String& data) = 0;
+ virtual void handleEvent(const String& data) = 0;
// Helper to post callback task.
- void scheduleCallback(ScriptExecutionContext*, const String& data);
+ static void scheduleCallback(PassOwnPtr<StringCallback>, ExecutionContext*, const String& data);
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/StringCallback.idl b/chromium/third_party/WebKit/Source/core/dom/StringCallback.idl
index 9ab79c13ced..b26a090d1b8 100644
--- a/chromium/third_party/WebKit/Source/core/dom/StringCallback.idl
+++ b/chromium/third_party/WebKit/Source/core/dom/StringCallback.idl
@@ -29,5 +29,5 @@
*/
callback interface StringCallback {
- boolean handleEvent(DOMString data);
+ void handleEvent(DOMString data);
};
diff --git a/chromium/third_party/WebKit/Source/core/dom/StyleElement.cpp b/chromium/third_party/WebKit/Source/core/dom/StyleElement.cpp
index cd1d2f47f01..8233785616d 100644
--- a/chromium/third_party/WebKit/Source/core/dom/StyleElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/StyleElement.cpp
@@ -29,9 +29,8 @@
#include "core/dom/ScriptableDocumentParser.h"
#include "core/dom/StyleEngine.h"
#include "core/html/HTMLStyleElement.h"
-#include "core/page/ContentSecurityPolicy.h"
+#include "core/frame/ContentSecurityPolicy.h"
#include "wtf/text/StringBuilder.h"
-#include "wtf/text/TextPosition.h"
namespace WebCore {
@@ -75,9 +74,7 @@ void StyleElement::removedFromDocument(Document& document, Element* element, Con
if (m_sheet)
clearSheet();
- // If we're in document teardown, then we don't need to do any notification of our sheet's removal.
- if (document.renderer())
- document.removedStyleSheet(removedSheet.get());
+ document.removedStyleSheet(removedSheet.get(), RecalcStyleDeferred, AnalyzedStyleUpdate);
}
void StyleElement::clearDocumentData(Document& document, Element* element)
@@ -131,7 +128,8 @@ void StyleElement::createSheet(Element* e, const String& text)
// If type is empty or CSS, this is a CSS style sheet.
const AtomicString& type = this->type();
- if (document.contentSecurityPolicy()->allowInlineStyle(e->document().url(), m_startPosition.m_line) && isCSS(e, type)) {
+ bool passesContentSecurityPolicyChecks = document.contentSecurityPolicy()->allowStyleNonce(e->fastGetAttribute(HTMLNames::nonceAttr)) || document.contentSecurityPolicy()->allowInlineStyle(e->document().url(), m_startPosition.m_line);
+ if (isCSS(e, type) && passesContentSecurityPolicyChecks) {
RefPtr<MediaQuerySet> mediaQueries = MediaQuerySet::create(media());
MediaQueryEvaluator screenEval("screen", true);
diff --git a/chromium/third_party/WebKit/Source/core/dom/StyleEngine.cpp b/chromium/third_party/WebKit/Source/core/dom/StyleEngine.cpp
index 94a218b8fb7..54ce1fe3368 100644
--- a/chromium/third_party/WebKit/Source/core/dom/StyleEngine.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/StyleEngine.cpp
@@ -30,23 +30,24 @@
#include "HTMLNames.h"
#include "SVGNames.h"
+#include "core/css/CSSFontSelector.h"
#include "core/css/CSSStyleSheet.h"
#include "core/css/StyleInvalidationAnalysis.h"
#include "core/css/StyleSheetContents.h"
-#include "core/css/resolver/StyleResolver.h"
-#include "core/dom/Document.h"
#include "core/dom/Element.h"
#include "core/dom/ProcessingInstruction.h"
#include "core/dom/ShadowTreeStyleSheetCollection.h"
#include "core/dom/shadow/ShadowRoot.h"
#include "core/html/HTMLIFrameElement.h"
+#include "core/html/HTMLImport.h"
#include "core/html/HTMLLinkElement.h"
#include "core/html/HTMLStyleElement.h"
+#include "core/inspector/InspectorInstrumentation.h"
#include "core/page/Page.h"
#include "core/page/PageGroup.h"
-#include "core/page/Settings.h"
-#include "core/page/UserContentURLPattern.h"
+#include "core/frame/Settings.h"
#include "core/svg/SVGStyleElement.h"
+#include "platform/URLPatternMatcher.h"
namespace WebCore {
@@ -54,31 +55,50 @@ using namespace HTMLNames;
StyleEngine::StyleEngine(Document& document)
: m_document(document)
+ , m_isMaster(HTMLImport::isMaster(&document))
, m_pendingStylesheets(0)
, m_injectedStyleSheetCacheValid(false)
, m_needsUpdateActiveStylesheetsOnStyleRecalc(false)
+ , m_documentStyleSheetCollection(document)
+ , m_documentScopeDirty(true)
, m_usesSiblingRules(false)
, m_usesSiblingRulesOverride(false)
, m_usesFirstLineRules(false)
, m_usesFirstLetterRules(false)
, m_usesRemUnits(false)
- , m_documentStyleSheetCollection(document)
- , m_needsDocumentStyleSheetsUpdate(true)
+ , m_maxDirectAdjacentSelectors(0)
+ , m_ignorePendingStylesheets(false)
+ , m_didCalculateResolver(false)
+ , m_lastResolverAccessCount(0)
+ , m_resolverThrowawayTimer(this, &StyleEngine::resolverThrowawayTimerFired)
+ // We don't need to create CSSFontSelector for imported document or
+ // HTMLTemplateElement's document, because those documents have no frame.
+ , m_fontSelector(document.frame() ? CSSFontSelector::create(&document) : 0)
{
}
StyleEngine::~StyleEngine()
{
- if (m_pageUserSheet)
- m_pageUserSheet->clearOwnerNode();
- for (unsigned i = 0; i < m_injectedUserStyleSheets.size(); ++i)
- m_injectedUserStyleSheets[i]->clearOwnerNode();
for (unsigned i = 0; i < m_injectedAuthorStyleSheets.size(); ++i)
m_injectedAuthorStyleSheets[i]->clearOwnerNode();
- for (unsigned i = 0; i < m_userStyleSheets.size(); ++i)
- m_userStyleSheets[i]->clearOwnerNode();
for (unsigned i = 0; i < m_authorStyleSheets.size(); ++i)
m_authorStyleSheets[i]->clearOwnerNode();
+
+ if (m_fontSelector) {
+ m_fontSelector->clearDocument();
+ if (m_resolver)
+ m_fontSelector->unregisterForInvalidationCallbacks(m_resolver.get());
+ }
+}
+
+inline Document* StyleEngine::master()
+{
+ if (isMaster())
+ return &m_document;
+ HTMLImport* import = m_document.import();
+ if (!import) // Document::import() can return null while executing its destructor.
+ return 0;
+ return import->master();
}
void StyleEngine::insertTreeScopeInDocumentOrder(TreeScopeSet& treeScopes, TreeScope* treeScope)
@@ -110,7 +130,7 @@ void StyleEngine::insertTreeScopeInDocumentOrder(TreeScopeSet& treeScopes, TreeS
StyleSheetCollection* StyleEngine::ensureStyleSheetCollectionFor(TreeScope& treeScope)
{
- if (&treeScope == &m_document)
+ if (treeScope == m_document)
return &m_documentStyleSheetCollection;
HashMap<TreeScope*, OwnPtr<StyleSheetCollection> >::AddResult result = m_styleSheetCollectionMap.add(&treeScope, nullptr);
@@ -121,7 +141,7 @@ StyleSheetCollection* StyleEngine::ensureStyleSheetCollectionFor(TreeScope& tree
StyleSheetCollection* StyleEngine::styleSheetCollectionFor(TreeScope& treeScope)
{
- if (&treeScope == &m_document)
+ if (treeScope == m_document)
return &m_documentStyleSheetCollection;
HashMap<TreeScope*, OwnPtr<StyleSheetCollection> >::iterator it = m_styleSheetCollectionMap.find(&treeScope);
@@ -130,9 +150,12 @@ StyleSheetCollection* StyleEngine::styleSheetCollectionFor(TreeScope& treeScope)
return it->value.get();
}
-const Vector<RefPtr<StyleSheet> >& StyleEngine::styleSheetsForStyleSheetList()
+const Vector<RefPtr<StyleSheet> >& StyleEngine::styleSheetsForStyleSheetList(TreeScope& treeScope)
{
- return m_documentStyleSheetCollection.styleSheetsForStyleSheetList();
+ if (treeScope == m_document)
+ return m_documentStyleSheetCollection.styleSheetsForStyleSheetList();
+
+ return ensureStyleSheetCollectionFor(treeScope)->styleSheetsForStyleSheetList();
}
const Vector<RefPtr<CSSStyleSheet> >& StyleEngine::activeAuthorStyleSheets() const
@@ -158,55 +181,14 @@ void StyleEngine::combineCSSFeatureFlags(const RuleFeatureSet& features)
// Delay resetting the flags until after next style recalc since unapplying the style may not work without these set (this is true at least with before/after).
m_usesSiblingRules = m_usesSiblingRules || features.usesSiblingRules();
m_usesFirstLineRules = m_usesFirstLineRules || features.usesFirstLineRules();
+ m_maxDirectAdjacentSelectors = max(m_maxDirectAdjacentSelectors, features.maxDirectAdjacentSelectors());
}
void StyleEngine::resetCSSFeatureFlags(const RuleFeatureSet& features)
{
m_usesSiblingRules = features.usesSiblingRules();
m_usesFirstLineRules = features.usesFirstLineRules();
-}
-
-CSSStyleSheet* StyleEngine::pageUserSheet()
-{
- if (m_pageUserSheet)
- return m_pageUserSheet.get();
-
- Page* owningPage = m_document.page();
- if (!owningPage)
- return 0;
-
- String userSheetText = owningPage->userStyleSheet();
- if (userSheetText.isEmpty())
- return 0;
-
- // Parse the sheet and cache it.
- m_pageUserSheet = CSSStyleSheet::createInline(&m_document, m_document.settings()->userStyleSheetLocation());
- m_pageUserSheet->contents()->setIsUserStyleSheet(true);
- m_pageUserSheet->contents()->parseString(userSheetText);
- return m_pageUserSheet.get();
-}
-
-void StyleEngine::clearPageUserSheet()
-{
- if (m_pageUserSheet) {
- RefPtr<StyleSheet> removedSheet = m_pageUserSheet;
- m_pageUserSheet = 0;
- m_document.removedStyleSheet(removedSheet.get());
- }
-}
-
-void StyleEngine::updatePageUserSheet()
-{
- clearPageUserSheet();
- // FIXME: Why is this immediately and not defer?
- if (StyleSheet* addedSheet = pageUserSheet())
- m_document.addedStyleSheet(addedSheet, RecalcStyleImmediately);
-}
-
-const Vector<RefPtr<CSSStyleSheet> >& StyleEngine::injectedUserStyleSheets() const
-{
- updateInjectedStyleSheetCache();
- return m_injectedUserStyleSheets;
+ m_maxDirectAdjacentSelectors = features.maxDirectAdjacentSelectors();
}
const Vector<RefPtr<CSSStyleSheet> >& StyleEngine::injectedAuthorStyleSheets() const
@@ -220,7 +202,6 @@ void StyleEngine::updateInjectedStyleSheetCache() const
if (m_injectedStyleSheetCacheValid)
return;
m_injectedStyleSheetCacheValid = true;
- m_injectedUserStyleSheets.clear();
m_injectedAuthorStyleSheets.clear();
Page* owningPage = m_document.page();
@@ -228,20 +209,15 @@ void StyleEngine::updateInjectedStyleSheetCache() const
return;
const PageGroup& pageGroup = owningPage->group();
- const UserStyleSheetVector& sheets = pageGroup.userStyleSheets();
+ const InjectedStyleSheetVector& sheets = pageGroup.injectedStyleSheets();
for (unsigned i = 0; i < sheets.size(); ++i) {
- const UserStyleSheet* sheet = sheets[i].get();
- if (sheet->injectedFrames() == InjectInTopFrameOnly && m_document.ownerElement())
+ const InjectedStyleSheet* sheet = sheets[i].get();
+ if (sheet->injectedFrames() == InjectStyleInTopFrameOnly && m_document.ownerElement())
continue;
- if (!UserContentURLPattern::matchesPatterns(m_document.url(), sheet->whitelist(), sheet->blacklist()))
+ if (!URLPatternMatcher::matchesPatterns(m_document.url(), sheet->whitelist()))
continue;
- RefPtr<CSSStyleSheet> groupSheet = CSSStyleSheet::createInline(const_cast<Document*>(&m_document), sheet->url());
- bool isUserStyleSheet = sheet->level() == UserStyleUserLevel;
- if (isUserStyleSheet)
- m_injectedUserStyleSheets.append(groupSheet);
- else
- m_injectedAuthorStyleSheets.append(groupSheet);
- groupSheet->contents()->setIsUserStyleSheet(isUserStyleSheet);
+ RefPtr<CSSStyleSheet> groupSheet = CSSStyleSheet::createInline(const_cast<Document*>(&m_document), KURL());
+ m_injectedAuthorStyleSheets.append(groupSheet);
groupSheet->contents()->parseString(sheet->source());
}
}
@@ -249,7 +225,7 @@ void StyleEngine::updateInjectedStyleSheetCache() const
void StyleEngine::invalidateInjectedStyleSheetCache()
{
m_injectedStyleSheetCacheValid = false;
- m_needsDocumentStyleSheetsUpdate = true;
+ markDocumentDirty();
// FIXME: updateInjectedStyleSheetCache is called inside StyleSheetCollection::updateActiveStyleSheets
// and batch updates lots of sheets so we can't call addedStyleSheet() or removedStyleSheet().
m_document.styleResolverChanged(RecalcStyleDeferred);
@@ -257,34 +233,37 @@ void StyleEngine::invalidateInjectedStyleSheetCache()
void StyleEngine::addAuthorSheet(PassRefPtr<StyleSheetContents> authorSheet)
{
- ASSERT(!authorSheet->isUserStyleSheet());
m_authorStyleSheets.append(CSSStyleSheet::create(authorSheet, &m_document));
m_document.addedStyleSheet(m_authorStyleSheets.last().get(), RecalcStyleImmediately);
- m_needsDocumentStyleSheetsUpdate = true;
+ markDocumentDirty();
}
-void StyleEngine::addUserSheet(PassRefPtr<StyleSheetContents> userSheet)
+void StyleEngine::addPendingSheet()
{
- ASSERT(userSheet->isUserStyleSheet());
- m_userStyleSheets.append(CSSStyleSheet::create(userSheet, &m_document));
- m_document.addedStyleSheet(m_userStyleSheets.last().get(), RecalcStyleImmediately);
- m_needsDocumentStyleSheetsUpdate = true;
+ master()->styleEngine()->notifyPendingStyleSheetAdded();
}
// This method is called whenever a top-level stylesheet has finished loading.
void StyleEngine::removePendingSheet(Node* styleSheetCandidateNode, RemovePendingSheetNotificationType notification)
{
+ TreeScope* treeScope = isHTMLStyleElement(styleSheetCandidateNode) ? &styleSheetCandidateNode->treeScope() : &m_document;
+ markTreeScopeDirty(*treeScope);
+ master()->styleEngine()->notifyPendingStyleSheetRemoved(notification);
+}
+
+void StyleEngine::notifyPendingStyleSheetAdded()
+{
+ ASSERT(isMaster());
+ m_pendingStylesheets++;
+}
+
+void StyleEngine::notifyPendingStyleSheetRemoved(RemovePendingSheetNotificationType notification)
+{
+ ASSERT(isMaster());
// Make sure we knew this sheet was pending, and that our count isn't out of sync.
ASSERT(m_pendingStylesheets > 0);
m_pendingStylesheets--;
-
- TreeScope* treeScope = isHTMLStyleElement(styleSheetCandidateNode) ? &styleSheetCandidateNode->treeScope() : &m_document;
- if (treeScope == &m_document)
- m_needsDocumentStyleSheetsUpdate = true;
- else
- m_dirtyTreeScopes.add(treeScope);
-
if (m_pendingStylesheets)
return;
@@ -298,41 +277,48 @@ void StyleEngine::removePendingSheet(Node* styleSheetCandidateNode, RemovePendin
m_document.didRemoveAllPendingStylesheet();
}
+void StyleEngine::modifiedStyleSheet(StyleSheet* sheet)
+{
+ if (!sheet)
+ return;
+
+ Node* node = sheet->ownerNode();
+ if (!node || !node->inDocument())
+ return;
+
+ TreeScope& treeScope = isHTMLStyleElement(node) ? node->treeScope() : m_document;
+ ASSERT(isHTMLStyleElement(node) || treeScope == m_document);
+
+ markTreeScopeDirty(treeScope);
+}
+
void StyleEngine::addStyleSheetCandidateNode(Node* node, bool createdByParser)
{
if (!node->inDocument())
return;
TreeScope& treeScope = isHTMLStyleElement(node) ? node->treeScope() : m_document;
- ASSERT(isHTMLStyleElement(node) || &treeScope == &m_document);
+ ASSERT(isHTMLStyleElement(node) || treeScope == m_document);
StyleSheetCollection* collection = ensureStyleSheetCollectionFor(treeScope);
ASSERT(collection);
collection->addStyleSheetCandidateNode(node, createdByParser);
- if (&treeScope == &m_document) {
- m_needsDocumentStyleSheetsUpdate = true;
- return;
- }
-
- insertTreeScopeInDocumentOrder(m_activeTreeScopes, &treeScope);
- m_dirtyTreeScopes.add(&treeScope);
+ markTreeScopeDirty(treeScope);
+ if (treeScope != m_document)
+ insertTreeScopeInDocumentOrder(m_activeTreeScopes, &treeScope);
}
void StyleEngine::removeStyleSheetCandidateNode(Node* node, ContainerNode* scopingNode)
{
TreeScope& treeScope = scopingNode ? scopingNode->treeScope() : m_document;
- ASSERT(isHTMLStyleElement(node) || &treeScope == &m_document);
+ ASSERT(isHTMLStyleElement(node) || treeScope == m_document);
StyleSheetCollection* collection = styleSheetCollectionFor(treeScope);
ASSERT(collection);
collection->removeStyleSheetCandidateNode(node, scopingNode);
- if (&treeScope == &m_document) {
- m_needsDocumentStyleSheetsUpdate = true;
- return;
- }
- m_dirtyTreeScopes.add(&treeScope);
+ markTreeScopeDirty(treeScope);
m_activeTreeScopes.remove(&treeScope);
}
@@ -342,12 +328,8 @@ void StyleEngine::modifiedStyleSheetCandidateNode(Node* node)
return;
TreeScope& treeScope = isHTMLStyleElement(node) ? node->treeScope() : m_document;
- ASSERT(isHTMLStyleElement(node) || &treeScope == &m_document);
- if (&treeScope == &m_document) {
- m_needsDocumentStyleSheetsUpdate = true;
- return;
- }
- m_dirtyTreeScopes.add(&treeScope);
+ ASSERT(isHTMLStyleElement(node) || treeScope == m_document);
+ markTreeScopeDirty(treeScope);
}
bool StyleEngine::shouldUpdateShadowTreeStyleSheetCollection(StyleResolverUpdateMode updateMode)
@@ -355,8 +337,47 @@ bool StyleEngine::shouldUpdateShadowTreeStyleSheetCollection(StyleResolverUpdate
return !m_dirtyTreeScopes.isEmpty() || updateMode == FullStyleUpdate;
}
+void StyleEngine::clearMediaQueryRuleSetOnTreeScopeStyleSheets(TreeScopeSet treeScopes)
+{
+ for (TreeScopeSet::iterator it = treeScopes.begin(); it != treeScopes.end(); ++it) {
+ TreeScope& treeScope = **it;
+ ASSERT(treeScope != m_document);
+ ShadowTreeStyleSheetCollection* collection = static_cast<ShadowTreeStyleSheetCollection*>(styleSheetCollectionFor(treeScope));
+ ASSERT(collection);
+ collection->clearMediaQueryRuleSetStyleSheets();
+ }
+}
+
+void StyleEngine::clearMediaQueryRuleSetStyleSheets()
+{
+ m_documentStyleSheetCollection.clearMediaQueryRuleSetStyleSheets();
+ clearMediaQueryRuleSetOnTreeScopeStyleSheets(m_activeTreeScopes);
+ clearMediaQueryRuleSetOnTreeScopeStyleSheets(m_dirtyTreeScopes);
+}
+
+void StyleEngine::collectDocumentActiveStyleSheets(StyleSheetCollectionBase& collection)
+{
+ ASSERT(isMaster());
+
+ if (HTMLImport* rootImport = m_document.import()) {
+ for (HTMLImport* import = traverseFirstPostOrder(rootImport); import; import = traverseNextPostOrder(import)) {
+ Document* document = import->document();
+ if (!document)
+ continue;
+ StyleEngine* engine = document->styleEngine();
+ DocumentStyleSheetCollection::CollectFor collectFor = document == &m_document ?
+ DocumentStyleSheetCollection::CollectForList : DocumentStyleSheetCollection::DontCollectForList;
+ engine->m_documentStyleSheetCollection.collectStyleSheets(engine, collection, collectFor);
+ }
+ } else {
+ m_documentStyleSheetCollection.collectStyleSheets(this, collection, DocumentStyleSheetCollection::CollectForList);
+ }
+}
+
bool StyleEngine::updateActiveStyleSheets(StyleResolverUpdateMode updateMode)
{
+ ASSERT(isMaster());
+
if (m_document.inStyleRecalc()) {
// SVG <use> element may manage to invalidate style selector in the middle of a style recalc.
// https://bugs.webkit.org/show_bug.cgi?id=54344
@@ -365,11 +386,11 @@ bool StyleEngine::updateActiveStyleSheets(StyleResolverUpdateMode updateMode)
return false;
}
- if (!m_document.renderer() || !m_document.attached())
+ if (!m_document.isActive())
return false;
bool requiresFullStyleRecalc = false;
- if (m_needsDocumentStyleSheetsUpdate || updateMode == FullStyleUpdate)
+ if (m_documentScopeDirty || updateMode == FullStyleUpdate)
requiresFullStyleRecalc = m_documentStyleSheetCollection.updateActiveStyleSheets(this, updateMode);
if (shouldUpdateShadowTreeStyleSheetCollection(updateMode)) {
@@ -378,7 +399,7 @@ bool StyleEngine::updateActiveStyleSheets(StyleResolverUpdateMode updateMode)
for (TreeScopeSet::iterator it = treeScopes.begin(); it != treeScopes.end(); ++it) {
TreeScope* treeScope = *it;
- ASSERT(treeScope != &m_document);
+ ASSERT(treeScope != m_document);
ShadowTreeStyleSheetCollection* collection = static_cast<ShadowTreeStyleSheetCollection*>(styleSheetCollectionFor(*treeScope));
ASSERT(collection);
collection->updateActiveStyleSheets(this, updateMode);
@@ -388,22 +409,16 @@ bool StyleEngine::updateActiveStyleSheets(StyleResolverUpdateMode updateMode)
if (!treeScopesRemoved.isEmpty())
for (HashSet<TreeScope*>::iterator it = treeScopesRemoved.begin(); it != treeScopesRemoved.end(); ++it)
m_activeTreeScopes.remove(*it);
- m_dirtyTreeScopes.clear();
- }
-
- if (StyleResolver* styleResolver = m_document.styleResolverIfExists()) {
- styleResolver->finishAppendAuthorStyleSheets();
- resetCSSFeatureFlags(styleResolver->ruleFeatureSet());
}
-
m_needsUpdateActiveStylesheetsOnStyleRecalc = false;
activeStyleSheetsUpdatedForInspector();
m_usesRemUnits = m_documentStyleSheetCollection.usesRemUnits();
- if (m_needsDocumentStyleSheetsUpdate || updateMode == FullStyleUpdate) {
+ if (m_documentScopeDirty || updateMode == FullStyleUpdate)
m_document.notifySeamlessChildDocumentsOfStylesheetUpdate();
- m_needsDocumentStyleSheetsUpdate = false;
- }
+
+ m_dirtyTreeScopes.clear();
+ m_documentScopeDirty = false;
return requiresFullStyleRecalc;
}
@@ -436,23 +451,148 @@ void StyleEngine::didRemoveShadowRoot(ShadowRoot* shadowRoot)
m_styleSheetCollectionMap.remove(shadowRoot);
}
-void StyleEngine::appendActiveAuthorStyleSheets(StyleResolver* styleResolver)
+void StyleEngine::appendActiveAuthorStyleSheets()
{
- ASSERT(styleResolver);
+ ASSERT(isMaster());
- styleResolver->setBuildScopedStyleTreeInDocumentOrder(true);
- styleResolver->appendAuthorStyleSheets(0, m_documentStyleSheetCollection.activeAuthorStyleSheets());
+ m_resolver->setBuildScopedStyleTreeInDocumentOrder(true);
+ m_resolver->appendAuthorStyleSheets(0, m_documentStyleSheetCollection.activeAuthorStyleSheets());
TreeScopeSet::iterator begin = m_activeTreeScopes.begin();
TreeScopeSet::iterator end = m_activeTreeScopes.end();
for (TreeScopeSet::iterator it = begin; it != end; ++it) {
if (StyleSheetCollection* collection = m_styleSheetCollectionMap.get(*it)) {
- styleResolver->setBuildScopedStyleTreeInDocumentOrder(!collection->scopingNodesForStyleScoped());
- styleResolver->appendAuthorStyleSheets(0, collection->activeAuthorStyleSheets());
+ m_resolver->setBuildScopedStyleTreeInDocumentOrder(!collection->scopingNodesForStyleScoped());
+ m_resolver->appendAuthorStyleSheets(0, collection->activeAuthorStyleSheets());
}
}
- styleResolver->finishAppendAuthorStyleSheets();
- styleResolver->setBuildScopedStyleTreeInDocumentOrder(false);
+ m_resolver->finishAppendAuthorStyleSheets();
+ m_resolver->setBuildScopedStyleTreeInDocumentOrder(false);
+}
+
+void StyleEngine::createResolver()
+{
+ // It is a programming error to attempt to resolve style on a Document
+ // which is not in a frame. Code which hits this should have checked
+ // Document::isActive() before calling into code which could get here.
+
+ ASSERT(m_document.frame());
+ ASSERT(m_fontSelector);
+
+ m_resolver = adoptPtr(new StyleResolver(m_document));
+ appendActiveAuthorStyleSheets();
+ m_fontSelector->registerForInvalidationCallbacks(m_resolver.get());
+ combineCSSFeatureFlags(m_resolver->ensureRuleFeatureSet());
+}
+
+void StyleEngine::clearResolver()
+{
+ ASSERT(!m_document.inStyleRecalc());
+ ASSERT(isMaster() || !m_resolver);
+ ASSERT(m_fontSelector || !m_resolver);
+ if (m_resolver)
+ m_fontSelector->unregisterForInvalidationCallbacks(m_resolver.get());
+ m_resolver.clear();
+}
+
+void StyleEngine::clearMasterResolver()
+{
+ if (Document* master = this->master())
+ master->styleEngine()->clearResolver();
+}
+
+unsigned StyleEngine::resolverAccessCount() const
+{
+ return m_resolver ? m_resolver->accessCount() : 0;
+}
+
+void StyleEngine::resolverThrowawayTimerFired(Timer<StyleEngine>*)
+{
+ if (resolverAccessCount() == m_lastResolverAccessCount)
+ clearResolver();
+ m_lastResolverAccessCount = resolverAccessCount();
+}
+
+void StyleEngine::didAttach()
+{
+ m_resolverThrowawayTimer.startRepeating(60);
+}
+
+void StyleEngine::didDetach()
+{
+ m_resolverThrowawayTimer.stop();
+ clearResolver();
+}
+
+bool StyleEngine::shouldClearResolver() const
+{
+ return !m_didCalculateResolver && !haveStylesheetsLoaded();
+}
+
+StyleResolverChange StyleEngine::resolverChanged(RecalcStyleTime time, StyleResolverUpdateMode mode)
+{
+ StyleResolverChange change;
+
+ if (!isMaster()) {
+ if (Document* master = this->master())
+ master->styleResolverChanged(time, mode);
+ return change;
+ }
+
+ // Don't bother updating, since we haven't loaded all our style info yet
+ // and haven't calculated the style selector for the first time.
+ if (!m_document.isActive() || shouldClearResolver()) {
+ clearResolver();
+ return change;
+ }
+
+ m_didCalculateResolver = true;
+ if (m_document.didLayoutWithPendingStylesheets() && !hasPendingSheets())
+ change.setNeedsRepaint();
+
+ if (updateActiveStyleSheets(mode))
+ change.setNeedsStyleRecalc();
+
+ return change;
+}
+
+void StyleEngine::resetFontSelector()
+{
+ if (!m_fontSelector)
+ return;
+
+ m_fontSelector->clearDocument();
+ if (m_resolver) {
+ m_fontSelector->unregisterForInvalidationCallbacks(m_resolver.get());
+ m_resolver->invalidateMatchedPropertiesCache();
+ }
+
+ // If the document has been already detached, we don't need to recreate
+ // CSSFontSelector.
+ if (m_document.isActive()) {
+ m_fontSelector = CSSFontSelector::create(&m_document);
+ if (m_resolver)
+ m_fontSelector->registerForInvalidationCallbacks(m_resolver.get());
+ } else {
+ m_fontSelector = 0;
+ }
+}
+
+void StyleEngine::markTreeScopeDirty(TreeScope& scope)
+{
+ if (scope == m_document) {
+ markDocumentDirty();
+ return;
+ }
+
+ m_dirtyTreeScopes.add(&scope);
+}
+
+void StyleEngine::markDocumentDirty()
+{
+ m_documentScopeDirty = true;
+ if (!HTMLImport::isMaster(&m_document))
+ m_document.import()->master()->styleEngine()->markDocumentDirty();
}
}
diff --git a/chromium/third_party/WebKit/Source/core/dom/StyleEngine.h b/chromium/third_party/WebKit/Source/core/dom/StyleEngine.h
index 98d2bae50ff..e6a4c4d8f09 100644
--- a/chromium/third_party/WebKit/Source/core/dom/StyleEngine.h
+++ b/chromium/third_party/WebKit/Source/core/dom/StyleEngine.h
@@ -28,56 +28,85 @@
#ifndef StyleEngine_h
#define StyleEngine_h
+#include "core/css/resolver/StyleResolver.h"
#include "core/dom/Document.h"
#include "core/dom/DocumentOrderedList.h"
#include "core/dom/DocumentStyleSheetCollection.h"
#include "wtf/FastAllocBase.h"
#include "wtf/ListHashSet.h"
#include "wtf/RefPtr.h"
+#include "wtf/TemporaryChange.h"
#include "wtf/Vector.h"
#include "wtf/text/WTFString.h"
namespace WebCore {
+class CSSFontSelector;
class CSSStyleSheet;
+class FontSelector;
class Node;
class RuleFeatureSet;
class ShadowTreeStyleSheetCollection;
+class StyleResolver;
class StyleSheet;
class StyleSheetCollection;
class StyleSheetContents;
class StyleSheetList;
+class StyleResolverChange {
+public:
+ StyleResolverChange()
+ : m_needsRepaint(false)
+ , m_needsStyleRecalc(false)
+ { }
+
+ bool needsRepaint() const { return m_needsRepaint; }
+ bool needsStyleRecalc() const { return m_needsStyleRecalc; }
+ void setNeedsRepaint() { m_needsRepaint = true; }
+ void setNeedsStyleRecalc() { m_needsStyleRecalc = true; }
+
+private:
+ bool m_needsRepaint;
+ bool m_needsStyleRecalc;
+};
+
class StyleEngine {
WTF_MAKE_FAST_ALLOCATED;
public:
+
+ class IgnoringPendingStylesheet : public TemporaryChange<bool> {
+ public:
+ IgnoringPendingStylesheet(StyleEngine* engine)
+ : TemporaryChange<bool>(engine->m_ignorePendingStylesheets, true)
+ {
+ }
+ };
+
+ friend class IgnoringPendingStylesheet;
+
static PassOwnPtr<StyleEngine> create(Document& document) { return adoptPtr(new StyleEngine(document)); }
~StyleEngine();
- const Vector<RefPtr<StyleSheet> >& styleSheetsForStyleSheetList();
+ const Vector<RefPtr<StyleSheet> >& styleSheetsForStyleSheetList(TreeScope&);
const Vector<RefPtr<CSSStyleSheet> >& activeAuthorStyleSheets() const;
- CSSStyleSheet* pageUserSheet();
- const Vector<RefPtr<CSSStyleSheet> >& documentUserStyleSheets() const { return m_userStyleSheets; }
const Vector<RefPtr<CSSStyleSheet> >& documentAuthorStyleSheets() const { return m_authorStyleSheets; }
- const Vector<RefPtr<CSSStyleSheet> >& injectedUserStyleSheets() const;
const Vector<RefPtr<CSSStyleSheet> >& injectedAuthorStyleSheets() const;
+ void modifiedStyleSheet(StyleSheet*);
void addStyleSheetCandidateNode(Node*, bool createdByParser);
void removeStyleSheetCandidateNode(Node*, ContainerNode* scopingNode = 0);
void modifiedStyleSheetCandidateNode(Node*);
- void clearPageUserSheet();
- void updatePageUserSheet();
void invalidateInjectedStyleSheetCache();
void updateInjectedStyleSheetCache() const;
void addAuthorSheet(PassRefPtr<StyleSheetContents> authorSheet);
- void addUserSheet(PassRefPtr<StyleSheetContents> userSheet);
bool needsUpdateActiveStylesheetsOnStyleRecalc() const { return m_needsUpdateActiveStylesheetsOnStyleRecalc; }
+ void clearMediaQueryRuleSetStyleSheets();
bool updateActiveStyleSheets(StyleResolverUpdateMode);
String preferredStylesheetSetName() const { return m_preferredStylesheetSetName; }
@@ -85,7 +114,7 @@ public:
void setPreferredStylesheetSetName(const String& name) { m_preferredStylesheetSetName = name; }
void setSelectedStylesheetSetName(const String& name) { m_selectedStylesheetSetName = name; }
- void addPendingSheet() { m_pendingStylesheets++; }
+ void addPendingSheet();
enum RemovePendingSheetNotificationType {
RemovePendingSheetNotifyImmediately,
RemovePendingSheetNotifyLater
@@ -93,7 +122,10 @@ public:
void removePendingSheet(Node* styleSheetCandidateNode, RemovePendingSheetNotificationType = RemovePendingSheetNotifyImmediately);
bool hasPendingSheets() const { return m_pendingStylesheets > 0; }
+ bool haveStylesheetsLoaded() const { return !hasPendingSheets() || m_ignorePendingStylesheets; }
+ bool ignoringPendingStylesheets() const { return m_ignorePendingStylesheets; }
+ unsigned maxDirectAdjacentSelectors() const { return m_maxDirectAdjacentSelectors; }
bool usesSiblingRules() const { return m_usesSiblingRules || m_usesSiblingRulesOverride; }
void setUsesSiblingRulesOverride(bool b) { m_usesSiblingRulesOverride = b; }
bool usesFirstLineRules() const { return m_usesFirstLineRules; }
@@ -106,11 +138,42 @@ public:
void combineCSSFeatureFlags(const RuleFeatureSet&);
void resetCSSFeatureFlags(const RuleFeatureSet&);
- void didModifySeamlessParentStyleSheet() { m_needsDocumentStyleSheetsUpdate = true; }
+ void didModifySeamlessParentStyleSheet() { markDocumentDirty(); }
void didRemoveShadowRoot(ShadowRoot*);
- void appendActiveAuthorStyleSheets(StyleResolver*);
+ void appendActiveAuthorStyleSheets();
void getActiveAuthorStyleSheets(Vector<const Vector<RefPtr<CSSStyleSheet> >*>& activeAuthorStyleSheets) const;
+ StyleResolver* resolver() const
+ {
+ return m_resolver.get();
+ }
+
+ StyleResolver& ensureResolver()
+ {
+ if (!m_resolver) {
+ createResolver();
+ } else if (m_resolver->hasPendingAuthorStyleSheets()) {
+ m_resolver->appendPendingAuthorStyleSheets();
+ }
+ return *m_resolver.get();
+ }
+
+ bool hasResolver() const { return m_resolver.get(); }
+ void clearResolver();
+ void clearMasterResolver();
+
+ CSSFontSelector* fontSelector() { return m_fontSelector.get(); }
+ void resetFontSelector();
+
+ void didAttach();
+ void didDetach();
+ bool shouldClearResolver() const;
+ StyleResolverChange resolverChanged(RecalcStyleTime, StyleResolverUpdateMode);
+ unsigned resolverAccessCount() const;
+
+ void collectDocumentActiveStyleSheets(StyleSheetCollectionBase&);
+ void markDocumentDirty();
+
private:
StyleEngine(Document&);
@@ -118,11 +181,24 @@ private:
StyleSheetCollection* styleSheetCollectionFor(TreeScope&);
void activeStyleSheetsUpdatedForInspector();
bool shouldUpdateShadowTreeStyleSheetCollection(StyleResolverUpdateMode);
+ void resolverThrowawayTimerFired(Timer<StyleEngine>*);
+
+ void markTreeScopeDirty(TreeScope&);
+
+ bool isMaster() const { return m_isMaster; }
+ Document* master();
typedef ListHashSet<TreeScope*, 16> TreeScopeSet;
static void insertTreeScopeInDocumentOrder(TreeScopeSet&, TreeScope*);
+ void clearMediaQueryRuleSetOnTreeScopeStyleSheets(TreeScopeSet treeScopes);
+
+ void createResolver();
+
+ void notifyPendingStyleSheetAdded();
+ void notifyPendingStyleSheetRemoved(RemovePendingSheetNotificationType);
Document& m_document;
+ bool m_isMaster;
// Track the number of currently loading top-level stylesheets needed for rendering.
// Sheets loaded using the @import directive are not included in this count.
@@ -130,13 +206,9 @@ private:
// elements and when it is safe to execute scripts.
int m_pendingStylesheets;
- RefPtr<CSSStyleSheet> m_pageUserSheet;
-
- mutable Vector<RefPtr<CSSStyleSheet> > m_injectedUserStyleSheets;
mutable Vector<RefPtr<CSSStyleSheet> > m_injectedAuthorStyleSheets;
mutable bool m_injectedStyleSheetCacheValid;
- Vector<RefPtr<CSSStyleSheet> > m_userStyleSheets;
Vector<RefPtr<CSSStyleSheet> > m_authorStyleSheets;
bool m_needsUpdateActiveStylesheetsOnStyleRecalc;
@@ -144,9 +216,9 @@ private:
DocumentStyleSheetCollection m_documentStyleSheetCollection;
HashMap<TreeScope*, OwnPtr<StyleSheetCollection> > m_styleSheetCollectionMap;
+ bool m_documentScopeDirty;
TreeScopeSet m_dirtyTreeScopes;
TreeScopeSet m_activeTreeScopes;
- bool m_needsDocumentStyleSheetsUpdate;
String m_preferredStylesheetSetName;
String m_selectedStylesheetSetName;
@@ -156,6 +228,15 @@ private:
bool m_usesFirstLineRules;
bool m_usesFirstLetterRules;
bool m_usesRemUnits;
+ unsigned m_maxDirectAdjacentSelectors;
+
+ bool m_ignorePendingStylesheets;
+ bool m_didCalculateResolver;
+ unsigned m_lastResolverAccessCount;
+ Timer<StyleEngine> m_resolverThrowawayTimer;
+ OwnPtr<StyleResolver> m_resolver;
+
+ RefPtr<CSSFontSelector> m_fontSelector;
};
}
diff --git a/chromium/third_party/WebKit/Source/core/dom/StyleSheetCollection.cpp b/chromium/third_party/WebKit/Source/core/dom/StyleSheetCollection.cpp
index 6f807b9e277..cb944d876ee 100644
--- a/chromium/third_party/WebKit/Source/core/dom/StyleSheetCollection.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/StyleSheetCollection.cpp
@@ -29,19 +29,50 @@
#include "core/css/CSSStyleSheet.h"
#include "core/css/StyleInvalidationAnalysis.h"
+#include "core/css/StyleRuleImport.h"
#include "core/css/StyleSheetContents.h"
#include "core/css/resolver/StyleResolver.h"
-#include "core/dom/Document.h"
#include "core/dom/Element.h"
#include "core/dom/StyleEngine.h"
#include "core/html/HTMLStyleElement.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
namespace WebCore {
+StyleSheetCollectionBase::StyleSheetCollectionBase()
+{
+}
+
+StyleSheetCollectionBase::~StyleSheetCollectionBase()
+{
+}
+
+void StyleSheetCollectionBase::swap(StyleSheetCollectionBase& other)
+{
+ m_styleSheetsForStyleSheetList.swap(other.m_styleSheetsForStyleSheetList);
+ m_activeAuthorStyleSheets.swap(other.m_activeAuthorStyleSheets);
+}
+
+void StyleSheetCollectionBase::appendActiveStyleSheets(const Vector<RefPtr<CSSStyleSheet> >& sheets)
+{
+ m_activeAuthorStyleSheets.append(sheets);
+}
+
+void StyleSheetCollectionBase::appendActiveStyleSheet(CSSStyleSheet* sheet)
+{
+ m_activeAuthorStyleSheets.append(sheet);
+}
+
+void StyleSheetCollectionBase::appendSheetForList(StyleSheet* sheet)
+{
+ m_styleSheetsForStyleSheetList.append(sheet);
+}
+
+
StyleSheetCollection::StyleSheetCollection(TreeScope& treeScope)
: m_treeScope(treeScope)
, m_hadActiveLoadingStylesheet(false)
+ , m_usesRemUnits(false)
{
}
@@ -77,26 +108,25 @@ void StyleSheetCollection::removeStyleSheetCandidateNode(Node* node, ContainerNo
StyleSheetCollection::StyleResolverUpdateType StyleSheetCollection::compareStyleSheets(const Vector<RefPtr<CSSStyleSheet> >& oldStyleSheets, const Vector<RefPtr<CSSStyleSheet> >& newStylesheets, Vector<StyleSheetContents*>& addedSheets)
{
- // Find out which stylesheets are new.
- unsigned newStylesheetCount = newStylesheets.size();
- unsigned oldStylesheetCount = oldStyleSheets.size();
- if (newStylesheetCount < oldStylesheetCount)
+ unsigned newStyleSheetCount = newStylesheets.size();
+ unsigned oldStyleSheetCount = oldStyleSheets.size();
+ ASSERT(newStyleSheetCount >= oldStyleSheetCount);
+
+ if (!newStyleSheetCount)
return Reconstruct;
unsigned newIndex = 0;
- for (unsigned oldIndex = 0; oldIndex < oldStylesheetCount; ++oldIndex) {
- if (newIndex >= newStylesheetCount)
- return Reconstruct;
+ for (unsigned oldIndex = 0; oldIndex < oldStyleSheetCount; ++oldIndex) {
while (oldStyleSheets[oldIndex] != newStylesheets[newIndex]) {
addedSheets.append(newStylesheets[newIndex]->contents());
- ++newIndex;
- if (newIndex == newStylesheetCount)
+ if (++newIndex == newStyleSheetCount)
return Reconstruct;
}
- ++newIndex;
+ if (++newIndex == newStyleSheetCount)
+ return Reconstruct;
}
bool hasInsertions = !addedSheets.isEmpty();
- while (newIndex < newStylesheetCount) {
+ while (newIndex < newStyleSheetCount) {
addedSheets.append(newStylesheets[newIndex]->contents());
++newIndex;
}
@@ -122,22 +152,67 @@ bool StyleSheetCollection::activeLoadingStyleSheetLoaded(const Vector<RefPtr<CSS
return false;
}
-void StyleSheetCollection::analyzeStyleSheetChange(StyleResolverUpdateMode updateMode, const Vector<RefPtr<CSSStyleSheet> >& oldStyleSheets, const Vector<RefPtr<CSSStyleSheet> >& newStyleSheets, StyleResolverUpdateType& styleResolverUpdateType, bool& requiresFullStyleRecalc)
+static bool styleSheetContentsHasFontFaceRule(Vector<StyleSheetContents*> sheets)
{
- styleResolverUpdateType = Reconstruct;
- requiresFullStyleRecalc = true;
+ for (unsigned i = 0; i < sheets.size(); ++i) {
+ ASSERT(sheets[i]);
+ if (sheets[i]->hasFontFaceRule())
+ return true;
+ }
+ return false;
+}
+
+static bool cssStyleSheetHasFontFaceRule(const Vector<RefPtr<CSSStyleSheet> > sheets)
+{
+ for (unsigned i = 0; i < sheets.size(); ++i) {
+ ASSERT(sheets[i]);
+ if (sheets[i]->contents()->hasFontFaceRule())
+ return true;
+ }
+ return false;
+}
- if (activeLoadingStyleSheetLoaded(newStyleSheets))
+void StyleSheetCollection::analyzeStyleSheetChange(StyleResolverUpdateMode updateMode, const StyleSheetCollectionBase& newCollection, StyleSheetChange& change)
+{
+ if (activeLoadingStyleSheetLoaded(newCollection.activeAuthorStyleSheets()))
return;
if (updateMode != AnalyzedStyleUpdate)
return;
- if (!document()->styleResolverIfExists())
- return;
// Find out which stylesheets are new.
Vector<StyleSheetContents*> addedSheets;
- styleResolverUpdateType = compareStyleSheets(oldStyleSheets, newStyleSheets, addedSheets);
+ if (m_activeAuthorStyleSheets.size() <= newCollection.activeAuthorStyleSheets().size()) {
+ change.styleResolverUpdateType = compareStyleSheets(m_activeAuthorStyleSheets, newCollection.activeAuthorStyleSheets(), addedSheets);
+ } else {
+ StyleResolverUpdateType updateType = compareStyleSheets(newCollection.activeAuthorStyleSheets(), m_activeAuthorStyleSheets, addedSheets);
+ if (updateType != Additive) {
+ change.styleResolverUpdateType = updateType;
+ } else {
+ if (styleSheetContentsHasFontFaceRule(addedSheets)) {
+ change.styleResolverUpdateType = ResetStyleResolverAndFontSelector;
+ return;
+ }
+ // FIXME: since currently all stylesheets are re-added after reseting styleresolver,
+ // fontSelector should be always reset. After creating RuleSet for each StyleSheetContents,
+ // we can avoid appending all stylesheetcontents in reset case.
+ // So we can remove "styleSheetContentsHasFontFaceRule(newSheets)".
+ if (cssStyleSheetHasFontFaceRule(newCollection.activeAuthorStyleSheets()))
+ change.styleResolverUpdateType = ResetStyleResolverAndFontSelector;
+ else
+ change.styleResolverUpdateType = Reset;
+ }
+ }
+
+ // FIXME: If styleResolverUpdateType is Reconstruct, we should return early here since
+ // we need to recalc the whole document. It's wrong to use StyleInvalidationAnalysis since
+ // it only looks at the addedSheets.
+
+ // No point in doing the analysis work if we're just going to recalc the whole document anyways.
+ // This needs to be done after the compareStyleSheets calls above to ensure we don't throw away
+ // the StyleResolver if we don't need to.
+ if (document()->hasPendingForcedStyleRecalc())
+ return;
// If we are already parsing the body and so may have significant amount of elements, put some effort into trying to avoid style recalcs.
if (!document()->body() || document()->hasNodesWithPlaceholderStyle())
@@ -145,8 +220,18 @@ void StyleSheetCollection::analyzeStyleSheetChange(StyleResolverUpdateMode updat
StyleInvalidationAnalysis invalidationAnalysis(addedSheets);
if (invalidationAnalysis.dirtiesAllStyle())
return;
- invalidationAnalysis.invalidateStyle(document());
- requiresFullStyleRecalc = false;
+ invalidationAnalysis.invalidateStyle(*document());
+ change.requiresFullStyleRecalc = false;
+ return;
+}
+
+void StyleSheetCollection::clearMediaQueryRuleSetStyleSheets()
+{
+ for (size_t i = 0; i < m_activeAuthorStyleSheets.size(); ++i) {
+ StyleSheetContents* contents = m_activeAuthorStyleSheets[i]->contents();
+ if (contents->hasMediaQueries())
+ contents->clearRuleSet();
+ }
}
void StyleSheetCollection::resetAllRuleSetsInTreeScope(StyleResolver* styleResolver)
diff --git a/chromium/third_party/WebKit/Source/core/dom/StyleSheetCollection.h b/chromium/third_party/WebKit/Source/core/dom/StyleSheetCollection.h
index 6519617fb72..9c9023355ab 100644
--- a/chromium/third_party/WebKit/Source/core/dom/StyleSheetCollection.h
+++ b/chromium/third_party/WebKit/Source/core/dom/StyleSheetCollection.h
@@ -49,24 +49,47 @@ class StyleSheet;
class StyleSheetContents;
class StyleSheetList;
-class StyleSheetCollection {
- WTF_MAKE_NONCOPYABLE(StyleSheetCollection); WTF_MAKE_FAST_ALLOCATED;
+// FIXME: Should be in separate file and be renamed like:
+// - StyleSheetCollectionBase -> StyleSheetCollection
+// - StyleSheetCollection -> ScopeStyleSheetCollection
+//
+class StyleSheetCollectionBase {
+ WTF_MAKE_NONCOPYABLE(StyleSheetCollectionBase); WTF_MAKE_FAST_ALLOCATED;
public:
- void addStyleSheetCandidateNode(Node*, bool createdByParser);
- void removeStyleSheetCandidateNode(Node*, ContainerNode* scopingNode);
- bool hasStyleSheetCandidateNodes() const { return !m_styleSheetCandidateNodes.isEmpty(); }
+ StyleSheetCollectionBase();
+ ~StyleSheetCollectionBase();
Vector<RefPtr<CSSStyleSheet> >& activeAuthorStyleSheets() { return m_activeAuthorStyleSheets; }
Vector<RefPtr<StyleSheet> >& styleSheetsForStyleSheetList() { return m_styleSheetsForStyleSheetList; }
const Vector<RefPtr<CSSStyleSheet> >& activeAuthorStyleSheets() const { return m_activeAuthorStyleSheets; }
const Vector<RefPtr<StyleSheet> >& styleSheetsForStyleSheetList() const { return m_styleSheetsForStyleSheetList; }
+ void swap(StyleSheetCollectionBase&);
+ void appendActiveStyleSheets(const Vector<RefPtr<CSSStyleSheet> >&);
+ void appendActiveStyleSheet(CSSStyleSheet*);
+ void appendSheetForList(StyleSheet*);
+
+protected:
+ Vector<RefPtr<StyleSheet> > m_styleSheetsForStyleSheetList;
+ Vector<RefPtr<CSSStyleSheet> > m_activeAuthorStyleSheets;
+};
+
+
+class StyleSheetCollection : public StyleSheetCollectionBase {
+public:
+ void addStyleSheetCandidateNode(Node*, bool createdByParser);
+ void removeStyleSheetCandidateNode(Node*, ContainerNode* scopingNode);
+ bool hasStyleSheetCandidateNodes() const { return !m_styleSheetCandidateNodes.isEmpty(); }
+
+
bool usesRemUnits() const { return m_usesRemUnits; }
DocumentOrderedList& styleSheetCandidateNodes() { return m_styleSheetCandidateNodes; }
DocumentOrderedList* scopingNodesForStyleScoped() { return m_scopingNodesForStyleScoped.scopingNodes(); }
ListHashSet<Node*, 4>* scopingNodesRemoved() { return m_scopingNodesForStyleScoped.scopingNodesRemoved(); }
+ void clearMediaQueryRuleSetStyleSheets();
+
protected:
explicit StyleSheetCollection(TreeScope&);
@@ -75,20 +98,28 @@ protected:
enum StyleResolverUpdateType {
Reconstruct,
Reset,
- Additive
+ Additive,
+ ResetStyleResolverAndFontSelector
+ };
+
+ struct StyleSheetChange {
+ StyleResolverUpdateType styleResolverUpdateType;
+ bool requiresFullStyleRecalc;
+
+ StyleSheetChange()
+ : styleResolverUpdateType(Reconstruct)
+ , requiresFullStyleRecalc(true) { }
};
- void analyzeStyleSheetChange(StyleResolverUpdateMode, const Vector<RefPtr<CSSStyleSheet> >& oldStyleSheets, const Vector<RefPtr<CSSStyleSheet> >& newStylesheets, StyleResolverUpdateType&, bool& requiresFullStyleRecalc);
+
+ void analyzeStyleSheetChange(StyleResolverUpdateMode, const StyleSheetCollectionBase&, StyleSheetChange&);
void resetAllRuleSetsInTreeScope(StyleResolver*);
void updateUsesRemUnits();
private:
- StyleResolverUpdateType compareStyleSheets(const Vector<RefPtr<CSSStyleSheet> >& oldStyleSheets, const Vector<RefPtr<CSSStyleSheet> >& newStylesheets, Vector<StyleSheetContents*>& addedSheets);
+ static StyleResolverUpdateType compareStyleSheets(const Vector<RefPtr<CSSStyleSheet> >& oldStyleSheets, const Vector<RefPtr<CSSStyleSheet> >& newStylesheets, Vector<StyleSheetContents*>& addedSheets);
bool activeLoadingStyleSheetLoaded(const Vector<RefPtr<CSSStyleSheet> >& newStyleSheets);
protected:
- Vector<RefPtr<StyleSheet> > m_styleSheetsForStyleSheetList;
- Vector<RefPtr<CSSStyleSheet> > m_activeAuthorStyleSheets;
-
TreeScope& m_treeScope;
bool m_hadActiveLoadingStylesheet;
bool m_usesRemUnits;
diff --git a/chromium/third_party/WebKit/Source/core/dom/StyleSheetScopingNodeList.cpp b/chromium/third_party/WebKit/Source/core/dom/StyleSheetScopingNodeList.cpp
index 7510eb01861..5d809e00904 100644
--- a/chromium/third_party/WebKit/Source/core/dom/StyleSheetScopingNodeList.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/StyleSheetScopingNodeList.cpp
@@ -29,6 +29,7 @@
#include "core/dom/StyleSheetScopingNodeList.h"
#include "core/dom/Document.h"
+#include "core/dom/Node.h"
namespace WebCore {
@@ -51,10 +52,11 @@ void StyleSheetScopingNodeList::remove(ContainerNode* node)
if (isTreeScopeRoot(node) || !m_scopingNodes)
return;
- m_scopingNodes->remove(node);
+ // If the node is still working as a scoping node, we cannot remove.
if (node->inDocument() && node->numberOfScopedHTMLStyleChildren())
return;
+ m_scopingNodes->remove(node);
if (!m_scopingNodesRemoved)
m_scopingNodesRemoved = adoptPtr(new ListHashSet<Node*, 4>());
m_scopingNodesRemoved->add(node);
diff --git a/chromium/third_party/WebKit/Source/core/dom/StyleSheetScopingNodeList.h b/chromium/third_party/WebKit/Source/core/dom/StyleSheetScopingNodeList.h
index 42ebda3462e..e6f61ec5a5d 100644
--- a/chromium/third_party/WebKit/Source/core/dom/StyleSheetScopingNodeList.h
+++ b/chromium/third_party/WebKit/Source/core/dom/StyleSheetScopingNodeList.h
@@ -34,11 +34,6 @@
namespace WebCore {
-inline bool isTreeScopeRoot(const Node* node)
-{
- return !node || node->isDocumentNode() || node->isShadowRoot();
-}
-
class StyleSheetScopingNodeList {
WTF_MAKE_NONCOPYABLE(StyleSheetScopingNodeList); WTF_MAKE_FAST_ALLOCATED;
public:
diff --git a/chromium/third_party/WebKit/Source/core/dom/TagNodeList.cpp b/chromium/third_party/WebKit/Source/core/dom/TagNodeList.cpp
index b0e34f6ba27..39446348179 100644
--- a/chromium/third_party/WebKit/Source/core/dom/TagNodeList.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/TagNodeList.cpp
@@ -24,7 +24,6 @@
#include "config.h"
#include "core/dom/TagNodeList.h"
-#include "core/dom/Element.h"
#include "core/dom/NodeRareData.h"
#include "wtf/Assertions.h"
diff --git a/chromium/third_party/WebKit/Source/core/dom/TagNodeList.h b/chromium/third_party/WebKit/Source/core/dom/TagNodeList.h
index 3ef510b688a..8ec41937666 100644
--- a/chromium/third_party/WebKit/Source/core/dom/TagNodeList.h
+++ b/chromium/third_party/WebKit/Source/core/dom/TagNodeList.h
@@ -56,7 +56,7 @@ protected:
AtomicString m_localName;
};
-class HTMLTagNodeList : public TagNodeList {
+class HTMLTagNodeList FINAL : public TagNodeList {
public:
static PassRefPtr<HTMLTagNodeList> create(PassRefPtr<Node> rootNode, CollectionType type, const AtomicString& localName)
{
@@ -69,7 +69,7 @@ public:
private:
HTMLTagNodeList(PassRefPtr<Node> rootNode, const AtomicString& localName);
- virtual bool nodeMatches(Element*) const;
+ virtual bool nodeMatches(Element*) const OVERRIDE;
AtomicString m_loweredLocalName;
};
diff --git a/chromium/third_party/WebKit/Source/core/dom/TemplateContentDocumentFragment.h b/chromium/third_party/WebKit/Source/core/dom/TemplateContentDocumentFragment.h
index 6c44e6075ee..380e8fa48b2 100644
--- a/chromium/third_party/WebKit/Source/core/dom/TemplateContentDocumentFragment.h
+++ b/chromium/third_party/WebKit/Source/core/dom/TemplateContentDocumentFragment.h
@@ -33,16 +33,16 @@ namespace WebCore {
class TemplateContentDocumentFragment FINAL : public DocumentFragment {
public:
- static PassRefPtr<TemplateContentDocumentFragment> create(Document& document, const Element* host)
+ static PassRefPtr<TemplateContentDocumentFragment> create(Document& document, Element* host)
{
return adoptRef(new TemplateContentDocumentFragment(document, host));
}
- const Element* host() const { return m_host; }
+ Element* host() const { return m_host; }
void clearHost() { m_host = 0; }
private:
- TemplateContentDocumentFragment(Document& document, const Element* host)
+ TemplateContentDocumentFragment(Document& document, Element* host)
: DocumentFragment(&document, CreateDocumentFragment)
, m_host(host)
{
@@ -50,7 +50,7 @@ private:
virtual bool isTemplateContent() const OVERRIDE { return true; }
- const Element* m_host;
+ Element* m_host;
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/Text.cpp b/chromium/third_party/WebKit/Source/core/dom/Text.cpp
index 8b204d355cd..f43f6ecd0e0 100644
--- a/chromium/third_party/WebKit/Source/core/dom/Text.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/Text.cpp
@@ -23,7 +23,6 @@
#include "core/dom/Text.h"
#include "SVGNames.h"
-#include "bindings/v8/ExceptionMessages.h"
#include "bindings/v8/ExceptionState.h"
#include "bindings/v8/ExceptionStatePlaceholder.h"
#include "core/css/resolver/StyleResolver.h"
@@ -31,7 +30,7 @@
#include "core/dom/NodeRenderStyle.h"
#include "core/dom/NodeRenderingContext.h"
#include "core/dom/NodeTraversal.h"
-#include "core/dom/ScopedEventQueue.h"
+#include "core/events/ScopedEventQueue.h"
#include "core/dom/shadow/ShadowRoot.h"
#include "core/rendering/RenderCombineText.h"
#include "core/rendering/RenderText.h"
@@ -60,7 +59,7 @@ PassRefPtr<Node> Text::mergeNextSiblingNodesIfPossible()
// Remove empty text nodes.
if (!length()) {
// Care must be taken to get the next node before removing the current node.
- RefPtr<Node> nextNode(NodeTraversal::nextPostOrder(this));
+ RefPtr<Node> nextNode(NodeTraversal::nextPostOrder(*this));
remove(IGNORE_EXCEPTION);
return nextNode.release();
}
@@ -84,25 +83,31 @@ PassRefPtr<Node> Text::mergeNextSiblingNodesIfPossible()
String oldTextData = data();
setDataWithoutUpdate(data() + nextTextData);
updateTextRenderer(oldTextData.length(), 0);
+
// Empty nextText for layout update.
nextText->setDataWithoutUpdate(emptyString());
+ nextText->updateTextRenderer(0, nextTextData.length());
+
document().didMergeTextNodes(nextText.get(), offset);
+
// Restore nextText for mutation event.
nextText->setDataWithoutUpdate(nextTextData);
+ nextText->updateTextRenderer(0, 0);
+
document().incDOMTreeVersion();
didModifyData(oldTextData);
nextText->remove(IGNORE_EXCEPTION);
}
- return NodeTraversal::nextPostOrder(this);
+ return NodeTraversal::nextPostOrder(*this);
}
-PassRefPtr<Text> Text::splitText(unsigned offset, ExceptionState& es)
+PassRefPtr<Text> Text::splitText(unsigned offset, ExceptionState& exceptionState)
{
// IndexSizeError: Raised if the specified offset is negative or greater than
// the number of 16-bit units in data.
if (offset > length()) {
- es.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("splitText", "Text", "The offset " + String::number(offset) + " is larger than the Text node's length."));
+ exceptionState.throwDOMException(IndexSizeError, "The offset " + String::number(offset) + " is larger than the Text node's length.");
return 0;
}
@@ -114,8 +119,8 @@ PassRefPtr<Text> Text::splitText(unsigned offset, ExceptionState& es)
didModifyData(oldStr);
if (parentNode())
- parentNode()->insertBefore(newText.get(), nextSibling(), es);
- if (es.hadException())
+ parentNode()->insertBefore(newText.get(), nextSibling(), exceptionState);
+ if (exceptionState.hadException())
return 0;
if (renderer())
@@ -221,7 +226,7 @@ PassRefPtr<Text> Text::replaceWholeText(const String& newText)
String Text::nodeName() const
{
- return textAtom.string();
+ return "#text";
}
Node::NodeType Text::nodeType() const
@@ -305,19 +310,18 @@ void Text::attach(const AttachContext& context)
CharacterData::attach(context);
}
-bool Text::recalcTextStyle(StyleRecalcChange change)
+void Text::recalcTextStyle(StyleRecalcChange change, Text* nextTextSibling)
{
if (RenderText* renderer = toRenderText(this->renderer())) {
if (change != NoChange || needsStyleRecalc())
- renderer->setStyle(document().styleResolver()->styleForText(this));
+ renderer->setStyle(document().ensureStyleResolver().styleForText(this));
if (needsStyleRecalc())
renderer->setText(dataImpl());
clearNeedsStyleRecalc();
} else if (needsStyleRecalc() || needsWhitespaceRenderer()) {
reattach();
- return true;
+ reattachWhitespaceSiblings(nextTextSibling);
}
- return false;
}
// If a whitespace node had no renderer and goes through a recalcStyle it may
@@ -332,11 +336,11 @@ bool Text::needsWhitespaceRenderer()
void Text::updateTextRenderer(unsigned offsetOfReplacedData, unsigned lengthOfReplacedData, RecalcStyleBehavior recalcStyleBehavior)
{
- if (!attached())
+ if (!inActiveDocument())
return;
RenderText* textRenderer = toRenderText(renderer());
if (!textRenderer || !textRendererIsNeeded(NodeRenderingContext(this, textRenderer->style()))) {
- lazyReattach();
+ lazyReattachIfAttached();
// FIXME: Editing should be updated so this is not neccesary.
if (recalcStyleBehavior == DeprecatedRecalcStyleImmediatlelyForEditing)
document().updateStyleIfNeeded();
@@ -355,19 +359,6 @@ PassRefPtr<Text> Text::cloneWithData(const String& data)
return create(document(), data);
}
-PassRefPtr<Text> Text::createWithLengthLimit(Document& document, const String& data, unsigned start, unsigned lengthLimit)
-{
- unsigned dataLength = data.length();
-
- if (!start && dataLength <= lengthLimit)
- return create(document, data);
-
- RefPtr<Text> result = Text::create(document, String());
- result->parserAppendData(data, start, lengthLimit);
-
- return result;
-}
-
#ifndef NDEBUG
void Text::formatForDebugger(char *buffer, unsigned length) const
{
diff --git a/chromium/third_party/WebKit/Source/core/dom/Text.h b/chromium/third_party/WebKit/Source/core/dom/Text.h
index df95ff1738b..79540c0b399 100644
--- a/chromium/third_party/WebKit/Source/core/dom/Text.h
+++ b/chromium/third_party/WebKit/Source/core/dom/Text.h
@@ -29,14 +29,13 @@ namespace WebCore {
class ExceptionState;
class RenderText;
-class ScriptExecutionContext;
+class ExecutionContext;
class Text : public CharacterData {
public:
static const unsigned defaultLengthLimit = 1 << 16;
static PassRefPtr<Text> create(Document&, const String&);
- static PassRefPtr<Text> createWithLengthLimit(Document&, const String&, unsigned positionInString, unsigned lengthLimit = defaultLengthLimit);
static PassRefPtr<Text> createEditingText(Document&, const String&);
// mergeNextSiblingNodesIfPossible() merges next sibling nodes if possible
@@ -49,9 +48,9 @@ public:
String wholeText() const;
PassRefPtr<Text> replaceWholeText(const String&);
- bool recalcTextStyle(StyleRecalcChange);
+ void recalcTextStyle(StyleRecalcChange, Text* nextTextSibling);
bool textRendererIsNeeded(const NodeRenderingContext&);
- virtual RenderText* createTextRenderer(RenderStyle*);
+ RenderText* createTextRenderer(RenderStyle*);
void updateTextRenderer(unsigned offsetOfReplacedData, unsigned lengthOfReplacedData, RecalcStyleBehavior = DoNotRecalcStyle);
virtual void attach(const AttachContext& = AttachContext()) OVERRIDE FINAL;
@@ -80,17 +79,7 @@ private:
#endif
};
-inline Text* toText(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->isTextNode());
- return static_cast<Text*>(node);
-}
-
-inline const Text* toText(const Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->isTextNode());
- return static_cast<const Text*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(Text, isTextNode());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/Text.idl b/chromium/third_party/WebKit/Source/core/dom/Text.idl
index af7360a3462..57e6dc0c8f8 100644
--- a/chromium/third_party/WebKit/Source/core/dom/Text.idl
+++ b/chromium/third_party/WebKit/Source/core/dom/Text.idl
@@ -19,7 +19,7 @@
[
Constructor([Default=NullString] optional DOMString data),
ConstructorCallWith=Document,
- CustomToV8
+ Custom=Wrap,
] interface Text : CharacterData {
// DOM Level 1
@@ -30,5 +30,5 @@
[MeasureAs=TextReplaceWholeText] Text replaceWholeText(DOMString content); // Removed from DOM4.
// Shadow DOM API
- [EnabledAtRuntime=ShadowDOM, PerWorldBindings] NodeList getDestinationInsertionPoints();
+ [RuntimeEnabled=ShadowDOM, PerWorldBindings] NodeList getDestinationInsertionPoints();
};
diff --git a/chromium/third_party/WebKit/Source/core/dom/TextEvent.cpp b/chromium/third_party/WebKit/Source/core/dom/TextEvent.cpp
deleted file mode 100644
index e3ee3c8ab70..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/TextEvent.cpp
+++ /dev/null
@@ -1,110 +0,0 @@
-/*
- * Copyright (C) 2007 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-#include "config.h"
-#include "core/dom/TextEvent.h"
-
-#include "core/dom/DocumentFragment.h"
-#include "core/dom/EventNames.h"
-
-namespace WebCore {
-
-PassRefPtr<TextEvent> TextEvent::create()
-{
- return adoptRef(new TextEvent);
-}
-
-PassRefPtr<TextEvent> TextEvent::create(PassRefPtr<AbstractView> view, const String& data, TextEventInputType inputType)
-{
- return adoptRef(new TextEvent(view, data, inputType));
-}
-
-PassRefPtr<TextEvent> TextEvent::createForPlainTextPaste(PassRefPtr<AbstractView> view, const String& data, bool shouldSmartReplace)
-{
- return adoptRef(new TextEvent(view, data, 0, shouldSmartReplace, false));
-}
-
-PassRefPtr<TextEvent> TextEvent::createForFragmentPaste(PassRefPtr<AbstractView> view, PassRefPtr<DocumentFragment> data, bool shouldSmartReplace, bool shouldMatchStyle)
-{
- return adoptRef(new TextEvent(view, "", data, shouldSmartReplace, shouldMatchStyle));
-}
-
-PassRefPtr<TextEvent> TextEvent::createForDrop(PassRefPtr<AbstractView> view, const String& data)
-{
- return adoptRef(new TextEvent(view, data, TextEventInputDrop));
-}
-
-TextEvent::TextEvent()
- : m_inputType(TextEventInputKeyboard)
- , m_shouldSmartReplace(false)
- , m_shouldMatchStyle(false)
-{
- ScriptWrappable::init(this);
-}
-
-TextEvent::TextEvent(PassRefPtr<AbstractView> view, const String& data, TextEventInputType inputType)
- : UIEvent(eventNames().textInputEvent, true, true, view, 0)
- , m_inputType(inputType)
- , m_data(data)
- , m_pastingFragment(0)
- , m_shouldSmartReplace(false)
- , m_shouldMatchStyle(false)
-{
- ScriptWrappable::init(this);
-}
-
-TextEvent::TextEvent(PassRefPtr<AbstractView> view, const String& data, PassRefPtr<DocumentFragment> pastingFragment,
- bool shouldSmartReplace, bool shouldMatchStyle)
- : UIEvent(eventNames().textInputEvent, true, true, view, 0)
- , m_inputType(TextEventInputPaste)
- , m_data(data)
- , m_pastingFragment(pastingFragment)
- , m_shouldSmartReplace(shouldSmartReplace)
- , m_shouldMatchStyle(shouldMatchStyle)
-{
- ScriptWrappable::init(this);
-}
-
-TextEvent::~TextEvent()
-{
-}
-
-void TextEvent::initTextEvent(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<AbstractView> view, const String& data)
-{
- if (dispatched())
- return;
-
- initUIEvent(type, canBubble, cancelable, view, 0);
-
- m_data = data;
-}
-
-const AtomicString& TextEvent::interfaceName() const
-{
- return eventNames().interfaceForTextEvent;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/TextEvent.h b/chromium/third_party/WebKit/Source/core/dom/TextEvent.h
deleted file mode 100644
index a9bb41548f6..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/TextEvent.h
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
- * Copyright (C) 2007, 2008 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-#ifndef TextEvent_h
-#define TextEvent_h
-
-#include "core/dom/EventNames.h"
-#include "core/dom/TextEventInputType.h"
-#include "core/dom/UIEvent.h"
-
-namespace WebCore {
-
- class DocumentFragment;
-
- class TextEvent : public UIEvent {
- public:
-
- static PassRefPtr<TextEvent> create();
- static PassRefPtr<TextEvent> create(PassRefPtr<AbstractView>, const String& data, TextEventInputType = TextEventInputKeyboard);
- static PassRefPtr<TextEvent> createForPlainTextPaste(PassRefPtr<AbstractView> view, const String& data, bool shouldSmartReplace);
- static PassRefPtr<TextEvent> createForFragmentPaste(PassRefPtr<AbstractView> view, PassRefPtr<DocumentFragment> data, bool shouldSmartReplace, bool shouldMatchStyle);
- static PassRefPtr<TextEvent> createForDrop(PassRefPtr<AbstractView> view, const String& data);
-
- virtual ~TextEvent();
-
- void initTextEvent(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<AbstractView>, const String& data);
-
- String data() const { return m_data; }
-
- virtual const AtomicString& interfaceName() const;
-
- bool isLineBreak() const { return m_inputType == TextEventInputLineBreak; }
- bool isComposition() const { return m_inputType == TextEventInputComposition; }
- bool isBackTab() const { return m_inputType == TextEventInputBackTab; }
- bool isPaste() const { return m_inputType == TextEventInputPaste; }
- bool isDrop() const { return m_inputType == TextEventInputDrop; }
-
- bool shouldSmartReplace() const { return m_shouldSmartReplace; }
- bool shouldMatchStyle() const { return m_shouldMatchStyle; }
- DocumentFragment* pastingFragment() const { return m_pastingFragment.get(); }
-
- private:
- TextEvent();
-
- TextEvent(PassRefPtr<AbstractView>, const String& data, TextEventInputType = TextEventInputKeyboard);
- TextEvent(PassRefPtr<AbstractView>, const String& data, PassRefPtr<DocumentFragment>,
- bool shouldSmartReplace, bool shouldMatchStyle);
-
- TextEventInputType m_inputType;
- String m_data;
-
- RefPtr<DocumentFragment> m_pastingFragment;
- bool m_shouldSmartReplace;
- bool m_shouldMatchStyle;
- };
-
-inline TextEvent* toTextEvent(Event* event)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!event || (event->type() == eventNames().textInputEvent && event->hasInterface(eventNames().interfaceForTextEvent)));
- return static_cast<TextEvent*>(event);
-}
-
-} // namespace WebCore
-
-#endif // TextEvent_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/TextLinkColors.h b/chromium/third_party/WebKit/Source/core/dom/TextLinkColors.h
index 6d2728cf4c9..a03a1b8e1c2 100644
--- a/chromium/third_party/WebKit/Source/core/dom/TextLinkColors.h
+++ b/chromium/third_party/WebKit/Source/core/dom/TextLinkColors.h
@@ -28,7 +28,7 @@
#ifndef TextLinkColors_h
#define TextLinkColors_h
-#include "core/platform/graphics/Color.h"
+#include "platform/graphics/Color.h"
#include "wtf/Noncopyable.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/dom/Touch.cpp b/chromium/third_party/WebKit/Source/core/dom/Touch.cpp
index 170af0024d6..a955babbb5d 100644
--- a/chromium/third_party/WebKit/Source/core/dom/Touch.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/Touch.cpp
@@ -27,8 +27,8 @@
#include "core/dom/Touch.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameView.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/dom/Touch.h b/chromium/third_party/WebKit/Source/core/dom/Touch.h
index bc2c28aa788..220d4cf10d4 100644
--- a/chromium/third_party/WebKit/Source/core/dom/Touch.h
+++ b/chromium/third_party/WebKit/Source/core/dom/Touch.h
@@ -27,8 +27,8 @@
#define Touch_h
#include "bindings/v8/ScriptWrappable.h"
-#include "core/dom/EventTarget.h"
-#include "core/platform/graphics/LayoutPoint.h"
+#include "core/events/EventTarget.h"
+#include "platform/geometry/LayoutPoint.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefCounted.h"
#include "wtf/RefPtr.h"
diff --git a/chromium/third_party/WebKit/Source/core/dom/TouchController.cpp b/chromium/third_party/WebKit/Source/core/dom/TouchController.cpp
new file mode 100644
index 00000000000..a24bc81c166
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/TouchController.cpp
@@ -0,0 +1,162 @@
+/*
+ * Copyright (C) 2013 Google, Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/dom/TouchController.h"
+
+#include "core/dom/Document.h"
+#include "core/events/ThreadLocalEventNames.h"
+#include "core/events/TouchEvent.h"
+#include "core/page/Chrome.h"
+#include "core/page/ChromeClient.h"
+#include "core/frame/Frame.h"
+#include "core/page/Page.h"
+#include "core/page/scrolling/ScrollingCoordinator.h"
+
+namespace WebCore {
+
+TouchController::TouchController(Document* document)
+ : DOMWindowLifecycleObserver(document->domWindow())
+ , DocumentLifecycleObserver(document)
+{
+}
+
+TouchController::~TouchController()
+{
+}
+
+const char* TouchController::supplementName()
+{
+ return "TouchController";
+}
+
+TouchController* TouchController::from(Document* document)
+{
+ TouchController* controller = static_cast<TouchController*>(DocumentSupplement::from(document, supplementName()));
+ if (!controller) {
+ controller = new TouchController(document);
+ DocumentSupplement::provideTo(document, supplementName(), adoptPtr(controller));
+ }
+ return controller;
+}
+
+void TouchController::didAddTouchEventHandler(Document* document, Node* handler)
+{
+ if (!m_touchEventTargets)
+ m_touchEventTargets = adoptPtr(new TouchEventTargetSet);
+ m_touchEventTargets->add(handler);
+ if (Document* parent = document->parentDocument()) {
+ TouchController::from(parent)->didAddTouchEventHandler(parent, document);
+ return;
+ }
+ if (Page* page = document->page()) {
+ if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
+ scrollingCoordinator->touchEventTargetRectsDidChange(document);
+ if (m_touchEventTargets->size() == 1)
+ page->chrome().client().needTouchEvents(true);
+ }
+}
+
+void TouchController::didRemoveTouchEventHandler(Document* document, Node* handler)
+{
+ if (!m_touchEventTargets)
+ return;
+ ASSERT(m_touchEventTargets->contains(handler));
+ m_touchEventTargets->remove(handler);
+ if (Document* parent = document->parentDocument()) {
+ TouchController::from(parent)->didRemoveTouchEventHandler(parent, document);
+ return;
+ }
+
+ Page* page = document->page();
+ if (!page)
+ return;
+ if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
+ scrollingCoordinator->touchEventTargetRectsDidChange(document);
+ if (m_touchEventTargets->size())
+ return;
+ for (const Frame* frame = page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
+ if (frame->document() && TouchController::from(frame->document())->hasTouchEventHandlers())
+ return;
+ }
+ page->chrome().client().needTouchEvents(false);
+}
+
+void TouchController::didRemoveEventTargetNode(Document* document, Node* handler)
+{
+ if (m_touchEventTargets && !m_touchEventTargets->isEmpty()) {
+ if (handler == document)
+ m_touchEventTargets->clear();
+ else
+ m_touchEventTargets->removeAll(handler);
+ Document* parent = document->parentDocument();
+ if (m_touchEventTargets->isEmpty() && parent)
+ TouchController::from(parent)->didRemoveEventTargetNode(parent, document);
+ }
+}
+
+void TouchController::didAddEventListener(DOMWindow* window, const AtomicString& eventType)
+{
+ if (isTouchEventType(eventType)) {
+ Document* document = window->document();
+ didAddTouchEventHandler(document, document);
+ }
+}
+
+void TouchController::didRemoveEventListener(DOMWindow* window, const AtomicString& eventType)
+{
+ if (isTouchEventType(eventType)) {
+ Document* document = window->document();
+ didRemoveTouchEventHandler(document, document);
+ }
+}
+
+void TouchController::didRemoveAllEventListeners(DOMWindow* window)
+{
+ if (Document* document = window->document())
+ didRemoveEventTargetNode(document, document);
+}
+
+void TouchController::documentWasDetached()
+{
+ Document* document = static_cast<Document*>(executionContext());
+ Document* parentDocument = document->parentDocument();
+
+ if (parentDocument) {
+ TouchController* parentController = TouchController::from(parentDocument);
+ if (parentController->hasTouchEventHandlers())
+ parentController->didRemoveEventTargetNode(parentDocument, document);
+ }
+}
+
+void TouchController::documentBeingDestroyed()
+{
+ Document* document = static_cast<Document*>(executionContext());
+
+ if (Document* ownerDocument = document->ownerDocument())
+ TouchController::from(ownerDocument)->didRemoveEventTargetNode(ownerDocument, document);
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/TouchController.h b/chromium/third_party/WebKit/Source/core/dom/TouchController.h
new file mode 100644
index 00000000000..8ce5e13e4ab
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/TouchController.h
@@ -0,0 +1,76 @@
+/*
+* Copyright (C) 2013 Google, Inc. All rights reserved.
+*
+* Redistribution and use in source and binary forms, with or without
+* modification, are permitted provided that the following conditions
+* are met:
+* * Redistributions of source code must retain the above copyright
+* notice, this list of conditions and the following disclaimer.
+* * Redistributions in binary form must reproduce the above copyright
+* notice, this list of conditions and the following disclaimer in the
+* documentation and/or other materials provided with the distribution.
+*
+* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
+* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+#ifndef TouchController_h
+#define TouchController_h
+
+#include "core/dom/DocumentLifecycleObserver.h"
+#include "core/events/Event.h"
+#include "core/dom/Node.h"
+#include "core/frame/DOMWindowLifecycleObserver.h"
+#include "platform/Supplementable.h"
+#include "wtf/HashSet.h"
+
+namespace WebCore {
+
+typedef HashCountedSet<Node*> TouchEventTargetSet;
+
+class Document;
+class DOMWindow;
+
+class TouchController : public DocumentSupplement, public DOMWindowLifecycleObserver, public DocumentLifecycleObserver {
+
+public:
+ virtual ~TouchController();
+
+ static const char* supplementName();
+ static TouchController* from(Document*);
+
+ bool hasTouchEventHandlers() const { return m_touchEventTargets ? m_touchEventTargets->size() : false; }
+
+ void didAddTouchEventHandler(Document*, Node*);
+ void didRemoveTouchEventHandler(Document*, Node*);
+ void didRemoveEventTargetNode(Document*, Node*);
+
+ const TouchEventTargetSet* touchEventTargets() const { return m_touchEventTargets.get(); }
+
+ // Inherited from DOMWindowLifecycleObserver
+ virtual void didAddEventListener(DOMWindow*, const AtomicString&) OVERRIDE;
+ virtual void didRemoveEventListener(DOMWindow*, const AtomicString&) OVERRIDE;
+ virtual void didRemoveAllEventListeners(DOMWindow*) OVERRIDE;
+
+ // Inherited from DocumentLifecycleObserver
+ virtual void documentWasDetached() OVERRIDE;
+ virtual void documentBeingDestroyed() OVERRIDE;
+
+private:
+ explicit TouchController(Document*);
+
+ OwnPtr<TouchEventTargetSet> m_touchEventTargets;
+};
+
+} // namespace WebCore
+
+#endif // TouchController_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/TouchEvent.cpp b/chromium/third_party/WebKit/Source/core/dom/TouchEvent.cpp
deleted file mode 100644
index a5c45dcf5fc..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/TouchEvent.cpp
+++ /dev/null
@@ -1,114 +0,0 @@
-/*
- * Copyright 2008, The Android Open Source Project
- * Copyright (C) 2012 Research In Motion Limited. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/dom/TouchEvent.h"
-
-#include "core/dom/EventDispatcher.h"
-#include "core/dom/EventNames.h"
-#include "core/dom/EventRetargeter.h"
-#include "core/dom/TouchList.h"
-
-namespace WebCore {
-
-TouchEvent::TouchEvent()
-{
- ScriptWrappable::init(this);
-}
-
-TouchEvent::TouchEvent(TouchList* touches, TouchList* targetTouches,
- TouchList* changedTouches, const AtomicString& type,
- PassRefPtr<AbstractView> view, int screenX, int screenY, int pageX, int pageY,
- bool ctrlKey, bool altKey, bool shiftKey, bool metaKey)
- : MouseRelatedEvent(type, true, true, view, 0, IntPoint(screenX, screenY),
- IntPoint(pageX, pageY),
- IntPoint(0, 0),
- ctrlKey, altKey, shiftKey, metaKey)
- , m_touches(touches)
- , m_targetTouches(targetTouches)
- , m_changedTouches(changedTouches)
-{
- ScriptWrappable::init(this);
-}
-
-TouchEvent::~TouchEvent()
-{
-}
-
-void TouchEvent::initTouchEvent(TouchList* touches, TouchList* targetTouches,
- TouchList* changedTouches, const AtomicString& type,
- PassRefPtr<AbstractView> view, int screenX, int screenY, int clientX, int clientY,
- bool ctrlKey, bool altKey, bool shiftKey, bool metaKey)
-{
- if (dispatched())
- return;
-
- initUIEvent(type, true, true, view, 0);
-
- m_touches = touches;
- m_targetTouches = targetTouches;
- m_changedTouches = changedTouches;
- m_screenLocation = IntPoint(screenX, screenY);
- m_ctrlKey = ctrlKey;
- m_altKey = altKey;
- m_shiftKey = shiftKey;
- m_metaKey = metaKey;
- initCoordinates(IntPoint(clientX, clientY));
-}
-
-const AtomicString& TouchEvent::interfaceName() const
-{
- return eventNames().interfaceForTouchEvent;
-}
-
-bool TouchEvent::isTouchEvent() const
-{
- return true;
-}
-
-PassRefPtr<TouchEventDispatchMediator> TouchEventDispatchMediator::create(PassRefPtr<TouchEvent> touchEvent)
-{
- return adoptRef(new TouchEventDispatchMediator(touchEvent));
-}
-
-TouchEventDispatchMediator::TouchEventDispatchMediator(PassRefPtr<TouchEvent> touchEvent)
- : EventDispatchMediator(touchEvent)
-{
-}
-
-TouchEvent* TouchEventDispatchMediator::event() const
-{
- return toTouchEvent(EventDispatchMediator::event());
-}
-
-bool TouchEventDispatchMediator::dispatchEvent(EventDispatcher* dispatcher) const
-{
- EventRetargeter::adjustForTouchEvent(dispatcher->node(), *event());
- return dispatcher->dispatch();
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/TouchEvent.h b/chromium/third_party/WebKit/Source/core/dom/TouchEvent.h
deleted file mode 100644
index 45a38dde917..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/TouchEvent.h
+++ /dev/null
@@ -1,104 +0,0 @@
-/*
- * Copyright 2008, The Android Open Source Project
- * Copyright (C) 2012 Research In Motion Limited. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TouchEvent_h
-#define TouchEvent_h
-
-#include "core/dom/EventDispatchMediator.h"
-#include "core/dom/MouseRelatedEvent.h"
-#include "core/dom/TouchList.h"
-
-namespace WebCore {
-
-class TouchEvent : public MouseRelatedEvent {
-public:
- virtual ~TouchEvent();
-
- static PassRefPtr<TouchEvent> create()
- {
- return adoptRef(new TouchEvent);
- }
- static PassRefPtr<TouchEvent> create(TouchList* touches,
- TouchList* targetTouches, TouchList* changedTouches,
- const AtomicString& type, PassRefPtr<AbstractView> view,
- int screenX, int screenY, int pageX, int pageY,
- bool ctrlKey, bool altKey, bool shiftKey, bool metaKey)
- {
- return adoptRef(new TouchEvent(touches, targetTouches, changedTouches,
- type, view, screenX, screenY, pageX, pageY,
- ctrlKey, altKey, shiftKey, metaKey));
- }
-
- void initTouchEvent(TouchList* touches, TouchList* targetTouches,
- TouchList* changedTouches, const AtomicString& type,
- PassRefPtr<AbstractView> view, int screenX, int screenY,
- int clientX, int clientY,
- bool ctrlKey, bool altKey, bool shiftKey, bool metaKey);
-
- TouchList* touches() const { return m_touches.get(); }
- TouchList* targetTouches() const { return m_targetTouches.get(); }
- TouchList* changedTouches() const { return m_changedTouches.get(); }
-
- void setTouches(PassRefPtr<TouchList> touches) { m_touches = touches; }
- void setTargetTouches(PassRefPtr<TouchList> targetTouches) { m_targetTouches = targetTouches; }
- void setChangedTouches(PassRefPtr<TouchList> changedTouches) { m_changedTouches = changedTouches; }
-
- virtual bool isTouchEvent() const OVERRIDE;
-
- virtual const AtomicString& interfaceName() const;
-
-private:
- TouchEvent();
- TouchEvent(TouchList* touches, TouchList* targetTouches,
- TouchList* changedTouches, const AtomicString& type,
- PassRefPtr<AbstractView>, int screenX, int screenY, int pageX,
- int pageY,
- bool ctrlKey, bool altKey, bool shiftKey, bool metaKey);
-
- RefPtr<TouchList> m_touches;
- RefPtr<TouchList> m_targetTouches;
- RefPtr<TouchList> m_changedTouches;
-};
-
-class TouchEventDispatchMediator : public EventDispatchMediator {
-public:
- static PassRefPtr<TouchEventDispatchMediator> create(PassRefPtr<TouchEvent>);
-
-private:
- explicit TouchEventDispatchMediator(PassRefPtr<TouchEvent>);
- TouchEvent* event() const;
- virtual bool dispatchEvent(EventDispatcher*) const OVERRIDE;
-};
-
-inline TouchEvent* toTouchEvent(Event* event)
-{
- ASSERT(event && event->isTouchEvent());
- return static_cast<TouchEvent*>(event);
-}
-
-} // namespace WebCore
-
-#endif // TouchEvent_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/TransitionEvent.cpp b/chromium/third_party/WebKit/Source/core/dom/TransitionEvent.cpp
deleted file mode 100644
index 346a66fa0cb..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/TransitionEvent.cpp
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * Copyright (C) 2007, 2008 Apple Inc. All rights reserved.
- * Copyright (C) 2013 Intel Corporation. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/dom/TransitionEvent.h"
-
-#include "core/dom/EventNames.h"
-
-namespace WebCore {
-
-TransitionEventInit::TransitionEventInit()
- : elapsedTime(0)
-{
-}
-
-TransitionEvent::TransitionEvent()
- : m_elapsedTime(0)
-{
- ScriptWrappable::init(this);
-}
-
-TransitionEvent::TransitionEvent(const AtomicString& type, const String& propertyName, double elapsedTime, const String& pseudoElement)
- : Event(type, true, true)
- , m_propertyName(propertyName)
- , m_elapsedTime(elapsedTime)
- , m_pseudoElement(pseudoElement)
-{
- ScriptWrappable::init(this);
-}
-
-TransitionEvent::TransitionEvent(const AtomicString& type, const TransitionEventInit& initializer)
- : Event(type, initializer)
- , m_propertyName(initializer.propertyName)
- , m_elapsedTime(initializer.elapsedTime)
- , m_pseudoElement(initializer.pseudoElement)
-{
- ScriptWrappable::init(this);
-}
-
-TransitionEvent::~TransitionEvent()
-{
-}
-
-const String& TransitionEvent::propertyName() const
-{
- return m_propertyName;
-}
-
-double TransitionEvent::elapsedTime() const
-{
- return m_elapsedTime;
-}
-
-const String& TransitionEvent::pseudoElement() const
-{
- return m_pseudoElement;
-}
-
-const AtomicString& TransitionEvent::interfaceName() const
-{
- return eventNames().interfaceForTransitionEvent;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/TransitionEvent.h b/chromium/third_party/WebKit/Source/core/dom/TransitionEvent.h
deleted file mode 100644
index 9fe4ffb9922..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/TransitionEvent.h
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * Copyright (C) 2007, 2008 Apple Inc. All rights reserved.
- * Copyright (C) 2013 Intel Corporation. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TransitionEvent_h
-#define TransitionEvent_h
-
-#include "core/dom/Event.h"
-
-namespace WebCore {
-
-struct TransitionEventInit : public EventInit {
- TransitionEventInit();
-
- String propertyName;
- double elapsedTime;
- String pseudoElement;
-};
-
-class TransitionEvent : public Event {
-public:
- static PassRefPtr<TransitionEvent> create()
- {
- return adoptRef(new TransitionEvent);
- }
- static PassRefPtr<TransitionEvent> create(const AtomicString& type, const String& propertyName, double elapsedTime, const String& pseudoElement)
- {
- return adoptRef(new TransitionEvent(type, propertyName, elapsedTime, pseudoElement));
- }
- static PassRefPtr<TransitionEvent> create(const AtomicString& type, const TransitionEventInit& initializer)
- {
- return adoptRef(new TransitionEvent(type, initializer));
- }
-
- virtual ~TransitionEvent();
-
- const String& propertyName() const;
- double elapsedTime() const;
- const String& pseudoElement() const;
-
- virtual const AtomicString& interfaceName() const;
-
-private:
- TransitionEvent();
- TransitionEvent(const AtomicString& type, const String& propertyName, double elapsedTime, const String& pseudoElement);
- TransitionEvent(const AtomicString& type, const TransitionEventInit& initializer);
-
- String m_propertyName;
- double m_elapsedTime;
- String m_pseudoElement;
-};
-
-} // namespace WebCore
-
-#endif // TransitionEvent_h
-
diff --git a/chromium/third_party/WebKit/Source/core/dom/TransitionEvent.idl b/chromium/third_party/WebKit/Source/core/dom/TransitionEvent.idl
deleted file mode 100644
index b2bd8ede7f6..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/TransitionEvent.idl
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Copyright (C) 2007, 2008 Apple Inc. All rights reserved.
- * Copyright (C) 2013 Intel Corporation. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-[
- ConstructorTemplate=Event
-] interface TransitionEvent : Event {
- [InitializedByEventConstructor] readonly attribute DOMString propertyName;
- [InitializedByEventConstructor] readonly attribute double elapsedTime;
- [InitializedByEventConstructor] readonly attribute DOMString pseudoElement;
-};
-
diff --git a/chromium/third_party/WebKit/Source/core/dom/TreeScope.cpp b/chromium/third_party/WebKit/Source/core/dom/TreeScope.cpp
index a4b79d6f424..56ad63782b7 100644
--- a/chromium/third_party/WebKit/Source/core/dom/TreeScope.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/TreeScope.cpp
@@ -32,24 +32,23 @@
#include "core/dom/Document.h"
#include "core/dom/Element.h"
#include "core/dom/ElementTraversal.h"
-#include "core/dom/EventPathWalker.h"
#include "core/dom/IdTargetObserverRegistry.h"
#include "core/dom/TreeScopeAdopter.h"
#include "core/dom/shadow/ElementShadow.h"
#include "core/dom/shadow/ShadowRoot.h"
+#include "core/events/EventPath.h"
#include "core/html/HTMLAnchorElement.h"
#include "core/html/HTMLFrameOwnerElement.h"
#include "core/html/HTMLLabelElement.h"
#include "core/html/HTMLMapElement.h"
#include "core/page/DOMSelection.h"
#include "core/page/FocusController.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameView.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
#include "core/page/Page.h"
#include "core/rendering/HitTestResult.h"
#include "core/rendering/RenderView.h"
#include "wtf/Vector.h"
-#include "wtf/text/AtomicString.h"
namespace WebCore {
@@ -99,7 +98,7 @@ TreeScope::TreeScope()
TreeScope::~TreeScope()
{
ASSERT(!m_guardRefCount);
- m_rootNode->setTreeScope(noDocumentInstance());
+ m_rootNode->setTreeScope(0);
if (m_selection) {
m_selection->clearTreeScope();
@@ -170,7 +169,7 @@ void TreeScope::removeElementById(const AtomicString& elementId, Element* elemen
Node* TreeScope::ancestorInThisScope(Node* node) const
{
while (node) {
- if (&node->treeScope() == this)
+ if (node->treeScope() == this)
return node;
if (!node->isInShadowTree())
return 0;
@@ -214,7 +213,7 @@ HTMLMapElement* TreeScope::getImageMap(const String& url) const
return toHTMLMapElement(m_imageMapsByName->getElementByMapName(AtomicString(name).impl(), this));
}
-Node* nodeFromPoint(Document* document, int x, int y, LayoutPoint* localPoint)
+RenderObject* rendererFromPoint(Document* document, int x, int y, LayoutPoint* localPoint)
{
Frame* frame = document->frame();
@@ -230,21 +229,26 @@ Node* nodeFromPoint(Document* document, int x, int y, LayoutPoint* localPoint)
if (!frameView->visibleContentRect().contains(point))
return 0;
- HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::DisallowShadowContent);
+ HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent);
HitTestResult result(point);
document->renderView()->hitTest(request, result);
if (localPoint)
*localPoint = result.localPoint();
- return result.innerNode();
+ return result.renderer();
}
Element* TreeScope::elementFromPoint(int x, int y) const
{
- Node* node = nodeFromPoint(&rootNode()->document(), x, y);
- if (node && node->isTextNode())
- node = node->parentNode();
+ RenderObject* renderer = rendererFromPoint(&rootNode()->document(), x, y);
+ if (!renderer)
+ return 0;
+ Node* node = renderer->node();
+ if (!node)
+ return 0;
+ if (node->isPseudoElement() || node->isTextNode())
+ node = node->parentOrShadowHostNode();
ASSERT(!node || node->isElementNode() || node->isShadowRoot());
node = ancestorInThisScope(node);
if (!node || !node->isElementNode())
@@ -272,7 +276,8 @@ HTMLLabelElement* TreeScope::labelElementForId(const AtomicString& forAttributeV
if (!m_labelsByForAttribute) {
// Populate the map on first access.
m_labelsByForAttribute = adoptPtr(new DocumentOrderedMap);
- for (Element* element = ElementTraversal::firstWithin(rootNode()); element; element = ElementTraversal::next(element)) {
+ ASSERT(rootNode());
+ for (Element* element = ElementTraversal::firstWithin(*rootNode()); element; element = ElementTraversal::next(*element)) {
if (isHTMLLabelElement(element)) {
HTMLLabelElement* label = toHTMLLabelElement(element);
const AtomicString& forValue = label->fastGetAttribute(forAttr);
@@ -306,7 +311,8 @@ Element* TreeScope::findAnchor(const String& name)
return 0;
if (Element* element = getElementById(name))
return element;
- for (Element* element = ElementTraversal::firstWithin(rootNode()); element; element = ElementTraversal::next(element)) {
+ ASSERT(rootNode());
+ for (Element* element = ElementTraversal::firstWithin(*rootNode()); element; element = ElementTraversal::next(*element)) {
if (isHTMLAnchorElement(element)) {
HTMLAnchorElement* anchor = toHTMLAnchorElement(element);
if (rootNode()->document().inQuirksMode()) {
@@ -328,27 +334,26 @@ bool TreeScope::applyAuthorStyles() const
return !rootNode()->isShadowRoot() || toShadowRoot(rootNode())->applyAuthorStyles();
}
-void TreeScope::adoptIfNeeded(Node* node)
+void TreeScope::adoptIfNeeded(Node& node)
{
ASSERT(this);
- ASSERT(node);
- ASSERT(!node->isDocumentNode());
- ASSERT(!node->m_deletionHasBegun);
- TreeScopeAdopter adopter(node, this);
+ ASSERT(!node.isDocumentNode());
+ ASSERT_WITH_SECURITY_IMPLICATION(!node.m_deletionHasBegun);
+ TreeScopeAdopter adopter(node, *this);
if (adopter.needsScopeChange())
adopter.execute();
}
static Element* focusedFrameOwnerElement(Frame* focusedFrame, Frame* currentFrame)
{
- for (; focusedFrame; focusedFrame = focusedFrame->tree()->parent()) {
- if (focusedFrame->tree()->parent() == currentFrame)
+ for (; focusedFrame; focusedFrame = focusedFrame->tree().parent()) {
+ if (focusedFrame->tree().parent() == currentFrame)
return focusedFrame->ownerElement();
}
return 0;
}
-Element* TreeScope::adjustedFocusedElement()
+Element* TreeScope::adjustedFocusedElement() const
{
Document& document = rootNode()->document();
Element* element = document.focusedElement();
@@ -356,24 +361,16 @@ Element* TreeScope::adjustedFocusedElement()
element = focusedFrameOwnerElement(document.page()->focusController().focusedFrame(), document.frame());
if (!element)
return 0;
- Vector<Node*> targetStack;
- for (EventPathWalker walker(element); walker.node(); walker.moveToParent()) {
- Node* node = walker.node();
- if (targetStack.isEmpty())
- targetStack.append(node);
- else if (walker.isVisitingInsertionPointInReprojection())
- targetStack.append(targetStack.last());
- if (node == rootNode()) {
- // targetStack.last() is one of the followings:
+
+ EventPath eventPath(element);
+ for (size_t i = 0; i < eventPath.size(); ++i) {
+ if (eventPath[i].node() == rootNode()) {
+ // eventPath.at(i).target() is one of the followings:
// - InsertionPoint
// - shadow host
// - Document::focusedElement()
// So, it's safe to do toElement().
- return toElement(targetStack.last());
- }
- if (node->isShadowRoot()) {
- ASSERT(!targetStack.isEmpty());
- targetStack.removeLast();
+ return toElement(eventPath[i].target()->toNode());
}
}
return 0;
@@ -381,7 +378,7 @@ Element* TreeScope::adjustedFocusedElement()
unsigned short TreeScope::comparePosition(const TreeScope& otherScope) const
{
- if (&otherScope == this)
+ if (otherScope == this)
return Node::DOCUMENT_POSITION_EQUIVALENT;
Vector<const TreeScope*, 16> chain1;
@@ -437,7 +434,7 @@ TreeScope* commonTreeScope(Node* nodeA, Node* nodeB)
if (!nodeA || !nodeB)
return 0;
- if (&nodeA->treeScope() == &nodeB->treeScope())
+ if (nodeA->treeScope() == nodeB->treeScope())
return &nodeA->treeScope();
Vector<TreeScope*, 5> treeScopesA;
@@ -454,7 +451,7 @@ TreeScope* commonTreeScope(Node* nodeA, Node* nodeB)
return treeScopesA[indexA] == treeScopesB[indexB] ? treeScopesA[indexA] : 0;
}
-#ifndef NDEBUG
+#if SECURITY_ASSERT_ENABLED
bool TreeScope::deletionHasBegun()
{
return rootNode() && rootNode()->m_deletionHasBegun;
@@ -462,7 +459,6 @@ bool TreeScope::deletionHasBegun()
void TreeScope::beginDeletion()
{
- ASSERT(this != noDocumentInstance());
rootNode()->m_deletionHasBegun = true;
}
#endif
@@ -489,7 +485,8 @@ Element* TreeScope::getElementByAccessKey(const String& key) const
return 0;
Element* result = 0;
Node* root = rootNode();
- for (Element* element = ElementTraversal::firstWithin(root); element; element = ElementTraversal::next(element, root)) {
+ ASSERT(root);
+ for (Element* element = ElementTraversal::firstWithin(*root); element; element = ElementTraversal::next(*element, root)) {
if (equalIgnoringCase(element->fastGetAttribute(accesskeyAttr), key))
result = element;
for (ShadowRoot* shadowRoot = element->youngestShadowRoot(); shadowRoot; shadowRoot = shadowRoot->olderShadowRoot()) {
diff --git a/chromium/third_party/WebKit/Source/core/dom/TreeScope.h b/chromium/third_party/WebKit/Source/core/dom/TreeScope.h
index ecfc8307915..718d7e7fb00 100644
--- a/chromium/third_party/WebKit/Source/core/dom/TreeScope.h
+++ b/chromium/third_party/WebKit/Source/core/dom/TreeScope.h
@@ -42,6 +42,7 @@ class HTMLMapElement;
class LayoutPoint;
class IdTargetObserverRegistry;
class Node;
+class RenderObject;
// A class which inherits both Node and TreeScope must call clearRareData() in its destructor
// so that the Node destructor no longer does problematic NodeList cache manipulation in
@@ -54,7 +55,7 @@ public:
TreeScope* parentTreeScope() const { return m_parentTreeScope; }
void setParentTreeScope(TreeScope*);
- Element* adjustedFocusedElement();
+ Element* adjustedFocusedElement() const;
Element* getElementById(const AtomicString&) const;
bool hasElementWithId(StringImpl* id) const;
bool containsMultipleElementsWithId(const AtomicString& id) const;
@@ -89,18 +90,12 @@ public:
bool applyAuthorStyles() const;
// Used by the basic DOM mutation methods (e.g., appendChild()).
- void adoptIfNeeded(Node*);
+ void adoptIfNeeded(Node&);
Node* rootNode() const { return m_rootNode; }
IdTargetObserverRegistry& idTargetObserverRegistry() const { return *m_idTargetObserverRegistry.get(); }
- static TreeScope* noDocumentInstance()
- {
- DEFINE_STATIC_LOCAL(TreeScope, instance, ());
- return &instance;
- }
-
// Nodes belonging to this scope hold guard references -
// these are enough to keep the scope from being destroyed, but
// not enough to keep it from removing its children. This allows a
@@ -116,7 +111,7 @@ public:
{
ASSERT(!deletionHasBegun());
--m_guardRefCount;
- if (!m_guardRefCount && !refCount() && this != noDocumentInstance() && !rootNodeHasTreeSharedParent()) {
+ if (!m_guardRefCount && !refCount() && !rootNodeHasTreeSharedParent()) {
beginDeletion();
delete this;
}
@@ -139,7 +134,6 @@ protected:
void setDocumentScope(Document* document)
{
ASSERT(document);
- ASSERT(this != noDocumentInstance());
m_documentScope = document;
}
@@ -151,7 +145,7 @@ private:
virtual void dispose() { }
int refCount() const;
-#ifndef NDEBUG
+#if SECURITY_ASSERT_ENABLED
bool deletionHasBegun();
void beginDeletion();
#else
@@ -186,7 +180,14 @@ inline bool TreeScope::containsMultipleElementsWithId(const AtomicString& id) co
return m_elementsById && m_elementsById->containsMultiple(id.impl());
}
-Node* nodeFromPoint(Document*, int x, int y, LayoutPoint* localPoint = 0);
+inline bool operator==(const TreeScope& a, const TreeScope& b) { return &a == &b; }
+inline bool operator==(const TreeScope& a, const TreeScope* b) { return &a == b; }
+inline bool operator==(const TreeScope* a, const TreeScope& b) { return a == &b; }
+inline bool operator!=(const TreeScope& a, const TreeScope& b) { return !(a == b); }
+inline bool operator!=(const TreeScope& a, const TreeScope* b) { return !(a == b); }
+inline bool operator!=(const TreeScope* a, const TreeScope& b) { return !(a == b); }
+
+RenderObject* rendererFromPoint(Document*, int x, int y, LayoutPoint* localPoint = 0);
TreeScope* commonTreeScope(Node*, Node*);
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/TreeScopeAdopter.cpp b/chromium/third_party/WebKit/Source/core/dom/TreeScopeAdopter.cpp
index be8670b91e7..366b4af3fa1 100644
--- a/chromium/third_party/WebKit/Source/core/dom/TreeScopeAdopter.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/TreeScopeAdopter.cpp
@@ -34,27 +34,28 @@
namespace WebCore {
-void TreeScopeAdopter::moveTreeToNewScope(Node* root) const
+void TreeScopeAdopter::moveTreeToNewScope(Node& root) const
{
ASSERT(needsScopeChange());
- m_oldScope->guardRef();
+ m_oldScope.guardRef();
// If an element is moved from a document and then eventually back again the collection cache for
// that element may contain stale data as changes made to it will have updated the DOMTreeVersion
// of the document it was moved to. By increasing the DOMTreeVersion of the donating document here
// we ensure that the collection cache will be invalidated as needed when the element is moved back.
- Document* oldDocument = m_oldScope->documentScope();
- Document* newDocument = m_newScope->documentScope();
+ Document* oldDocument = m_oldScope.documentScope();
+ ASSERT(oldDocument);
+ Document* newDocument = m_newScope.documentScope();
bool willMoveToNewDocument = oldDocument != newDocument;
- if (oldDocument && willMoveToNewDocument)
+ if (willMoveToNewDocument)
oldDocument->incDOMTreeVersion();
- for (Node* node = root; node; node = NodeTraversal::next(node, root)) {
- updateTreeScope(node);
+ for (Node* node = &root; node; node = NodeTraversal::next(*node, &root)) {
+ updateTreeScope(*node);
if (willMoveToNewDocument)
- moveNodeToNewDocument(node, oldDocument, newDocument);
+ moveNodeToNewDocument(*node, *oldDocument, newDocument);
else if (node->hasRareData()) {
NodeRareData* rareData = node->rareData();
if (rareData->nodeLists())
@@ -67,25 +68,25 @@ void TreeScopeAdopter::moveTreeToNewScope(Node* root) const
if (node->hasSyntheticAttrChildNodes()) {
const Vector<RefPtr<Attr> >& attrs = toElement(node)->attrNodeList();
for (unsigned i = 0; i < attrs.size(); ++i)
- moveTreeToNewScope(attrs[i].get());
+ moveTreeToNewScope(*attrs[i]);
}
for (ShadowRoot* shadow = node->youngestShadowRoot(); shadow; shadow = shadow->olderShadowRoot()) {
- shadow->setParentTreeScope(m_newScope);
+ shadow->setParentTreeScope(&m_newScope);
if (willMoveToNewDocument)
- moveTreeToNewDocument(shadow, oldDocument, newDocument);
+ moveTreeToNewDocument(*shadow, *oldDocument, newDocument);
}
}
- m_oldScope->guardDeref();
+ m_oldScope.guardDeref();
}
-void TreeScopeAdopter::moveTreeToNewDocument(Node* root, Document* oldDocument, Document* newDocument) const
+void TreeScopeAdopter::moveTreeToNewDocument(Node& root, Document& oldDocument, Document* newDocument) const
{
- for (Node* node = root; node; node = NodeTraversal::next(node, root)) {
- moveNodeToNewDocument(node, oldDocument, newDocument);
+ for (Node* node = &root; node; node = NodeTraversal::next(*node, &root)) {
+ moveNodeToNewDocument(*node, oldDocument, newDocument);
for (ShadowRoot* shadow = node->youngestShadowRoot(); shadow; shadow = shadow->olderShadowRoot())
- moveTreeToNewDocument(shadow, oldDocument, newDocument);
+ moveTreeToNewDocument(*shadow, oldDocument, newDocument);
}
}
@@ -93,7 +94,7 @@ void TreeScopeAdopter::moveTreeToNewDocument(Node* root, Document* oldDocument,
static bool didMoveToNewDocumentWasCalled = false;
static Document* oldDocumentDidMoveToNewDocumentWasCalledWith = 0;
-void TreeScopeAdopter::ensureDidMoveToNewDocumentWasCalled(Document* oldDocument)
+void TreeScopeAdopter::ensureDidMoveToNewDocumentWasCalled(Document& oldDocument)
{
ASSERT(!didMoveToNewDocumentWasCalled);
ASSERT_UNUSED(oldDocument, oldDocument == oldDocumentDidMoveToNewDocumentWasCalledWith);
@@ -101,37 +102,36 @@ void TreeScopeAdopter::ensureDidMoveToNewDocumentWasCalled(Document* oldDocument
}
#endif
-inline void TreeScopeAdopter::updateTreeScope(Node* node) const
+inline void TreeScopeAdopter::updateTreeScope(Node& node) const
{
- ASSERT(!node->isTreeScope());
- ASSERT(&node->treeScope() == m_oldScope);
- m_newScope->guardRef();
- m_oldScope->guardDeref();
- node->setTreeScope(m_newScope);
+ ASSERT(!node.isTreeScope());
+ ASSERT(node.treeScope() == m_oldScope);
+ m_newScope.guardRef();
+ m_oldScope.guardDeref();
+ node.setTreeScope(&m_newScope);
}
-inline void TreeScopeAdopter::moveNodeToNewDocument(Node* node, Document* oldDocument, Document* newDocument) const
+inline void TreeScopeAdopter::moveNodeToNewDocument(Node& node, Document& oldDocument, Document* newDocument) const
{
- ASSERT(!node->inDocument() || oldDocument != newDocument);
+ ASSERT(!node.inDocument() || oldDocument != newDocument);
- if (node->hasRareData()) {
- NodeRareData* rareData = node->rareData();
+ if (node.hasRareData()) {
+ NodeRareData* rareData = node.rareData();
if (rareData->nodeLists())
- rareData->nodeLists()->adoptDocument(oldDocument, newDocument);
+ rareData->nodeLists()->adoptDocument(&oldDocument, newDocument);
}
- if (oldDocument)
- oldDocument->moveNodeIteratorsToNewDocument(node, newDocument);
+ oldDocument.moveNodeIteratorsToNewDocument(&node, newDocument);
- if (node->isShadowRoot())
- toShadowRoot(node)->setDocumentScope(newDocument);
+ if (node.isShadowRoot())
+ toShadowRoot(node).setDocumentScope(newDocument);
#ifndef NDEBUG
didMoveToNewDocumentWasCalled = false;
- oldDocumentDidMoveToNewDocumentWasCalledWith = oldDocument;
+ oldDocumentDidMoveToNewDocumentWasCalledWith = &oldDocument;
#endif
- node->didMoveToNewDocument(oldDocument);
+ node.didMoveToNewDocument(oldDocument);
ASSERT(didMoveToNewDocumentWasCalled);
}
diff --git a/chromium/third_party/WebKit/Source/core/dom/TreeScopeAdopter.h b/chromium/third_party/WebKit/Source/core/dom/TreeScopeAdopter.h
index 4ad97606d5e..17742ba2553 100644
--- a/chromium/third_party/WebKit/Source/core/dom/TreeScopeAdopter.h
+++ b/chromium/third_party/WebKit/Source/core/dom/TreeScopeAdopter.h
@@ -33,35 +33,33 @@ class TreeScope;
class TreeScopeAdopter {
public:
- explicit TreeScopeAdopter(Node* toAdopt, TreeScope* newScope);
+ TreeScopeAdopter(Node& toAdopt, TreeScope& newScope);
void execute() const { moveTreeToNewScope(m_toAdopt); }
bool needsScopeChange() const { return m_oldScope != m_newScope; }
#ifdef NDEBUG
- static void ensureDidMoveToNewDocumentWasCalled(Document*) { }
+ static void ensureDidMoveToNewDocumentWasCalled(Document&) { }
#else
- static void ensureDidMoveToNewDocumentWasCalled(Document*);
+ static void ensureDidMoveToNewDocumentWasCalled(Document&);
#endif
private:
- void updateTreeScope(Node*) const;
- void moveTreeToNewScope(Node*) const;
- void moveTreeToNewDocument(Node*, Document* oldDocument, Document* newDocument) const;
- void moveNodeToNewDocument(Node*, Document* oldDocument, Document* newDocument) const;
+ void updateTreeScope(Node&) const;
+ void moveTreeToNewScope(Node&) const;
+ void moveTreeToNewDocument(Node&, Document& oldDocument, Document* newDocument) const;
+ void moveNodeToNewDocument(Node&, Document& oldDocument, Document* newDocument) const;
- Node* m_toAdopt;
- TreeScope* m_newScope;
- TreeScope* m_oldScope;
+ Node& m_toAdopt;
+ TreeScope& m_newScope;
+ TreeScope& m_oldScope;
};
-// FIXME: Should take |TreeScope&| instead of |TreeScope*|.
-inline TreeScopeAdopter::TreeScopeAdopter(Node* toAdopt, TreeScope* newScope)
+inline TreeScopeAdopter::TreeScopeAdopter(Node& toAdopt, TreeScope& newScope)
: m_toAdopt(toAdopt)
, m_newScope(newScope)
- , m_oldScope(&toAdopt->treeScope())
+ , m_oldScope(toAdopt.treeScope())
{
- ASSERT(newScope);
}
}
diff --git a/chromium/third_party/WebKit/Source/core/dom/TreeShared.h b/chromium/third_party/WebKit/Source/core/dom/TreeShared.h
new file mode 100644
index 00000000000..8637dc631d0
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/TreeShared.h
@@ -0,0 +1,121 @@
+/*
+ * Copyright (C) 2006, 2007, 2009, 2010, 2012 Apple Inc. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ */
+
+#ifndef TreeShared_h
+#define TreeShared_h
+
+#include "wtf/Assertions.h"
+#include "wtf/MainThread.h"
+#include "wtf/Noncopyable.h"
+
+namespace WebCore {
+
+#if SECURITY_ASSERT_ENABLED
+template<typename NodeType> class TreeShared;
+template<typename NodeType> void adopted(TreeShared<NodeType>*);
+#endif
+
+template<typename NodeType> class TreeShared {
+ WTF_MAKE_NONCOPYABLE(TreeShared);
+protected:
+ TreeShared()
+ : m_refCount(1)
+#if SECURITY_ASSERT_ENABLED
+ , m_deletionHasBegun(false)
+#if !ASSERT_DISABLED
+ , m_inRemovedLastRefFunction(false)
+ , m_adoptionIsRequired(true)
+#endif
+#endif
+ {
+ ASSERT(isMainThread());
+ }
+
+ ~TreeShared()
+ {
+ ASSERT(isMainThread());
+ ASSERT(!m_refCount);
+ ASSERT_WITH_SECURITY_IMPLICATION(m_deletionHasBegun);
+ ASSERT(!m_adoptionIsRequired);
+ }
+
+public:
+ void ref()
+ {
+ ASSERT(isMainThread());
+ ASSERT_WITH_SECURITY_IMPLICATION(!m_deletionHasBegun);
+ ASSERT(!m_inRemovedLastRefFunction);
+ ASSERT(!m_adoptionIsRequired);
+ ++m_refCount;
+ }
+
+ void deref()
+ {
+ ASSERT(isMainThread());
+ ASSERT(m_refCount >= 0);
+ ASSERT_WITH_SECURITY_IMPLICATION(!m_deletionHasBegun);
+ ASSERT(!m_inRemovedLastRefFunction);
+ ASSERT(!m_adoptionIsRequired);
+ NodeType* thisNode = static_cast<NodeType*>(this);
+ if (--m_refCount <= 0 && !thisNode->hasTreeSharedParent()) {
+#if !ASSERT_DISABLED
+ m_inRemovedLastRefFunction = true;
+#endif
+ thisNode->removedLastRef();
+ }
+ }
+
+ int refCount() const
+ {
+ return m_refCount;
+ }
+
+private:
+ int m_refCount;
+
+#if SECURITY_ASSERT_ENABLED
+public:
+ bool m_deletionHasBegun;
+#if !ASSERT_DISABLED
+ bool m_inRemovedLastRefFunction;
+
+private:
+ friend void adopted<>(TreeShared<NodeType>*);
+ bool m_adoptionIsRequired;
+#endif
+#endif
+};
+
+#if SECURITY_ASSERT_ENABLED
+template<typename NodeType> inline void adopted(TreeShared<NodeType>* object)
+{
+ if (!object)
+ return;
+ ASSERT_WITH_SECURITY_IMPLICATION(!object->m_deletionHasBegun);
+#if !ASSERT_DISABLED
+ ASSERT(!object->m_inRemovedLastRefFunction);
+ object->m_adoptionIsRequired = false;
+#endif
+}
+#endif
+
+}
+
+#endif // TreeShared.h
diff --git a/chromium/third_party/WebKit/Source/core/dom/TreeWalker.cpp b/chromium/third_party/WebKit/Source/core/dom/TreeWalker.cpp
index bec5c198992..fa099813850 100644
--- a/chromium/third_party/WebKit/Source/core/dom/TreeWalker.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/TreeWalker.cpp
@@ -25,14 +25,11 @@
#include "config.h"
#include "core/dom/TreeWalker.h"
-#include "bindings/v8/ExceptionMessages.h"
#include "bindings/v8/ExceptionState.h"
#include "bindings/v8/ScriptState.h"
#include "core/dom/ContainerNode.h"
#include "core/dom/ExceptionCode.h"
-#include "core/dom/NodeFilter.h"
#include "core/dom/NodeTraversal.h"
-#include "wtf/PassRefPtr.h"
namespace WebCore {
@@ -43,10 +40,10 @@ TreeWalker::TreeWalker(PassRefPtr<Node> rootNode, unsigned whatToShow, PassRefPt
ScriptWrappable::init(this);
}
-void TreeWalker::setCurrentNode(PassRefPtr<Node> node, ExceptionState& es)
+void TreeWalker::setCurrentNode(PassRefPtr<Node> node, ExceptionState& exceptionState)
{
if (!node) {
- es.throwDOMException(NotSupportedError, ExceptionMessages::failedToExecute("setCurrentNode", "TreeWalker", "The Node provided is invalid."));
+ exceptionState.throwDOMException(NotSupportedError, "The Node provided is invalid.");
return;
}
m_current = node;
@@ -267,7 +264,7 @@ Children:
if (acceptNodeResult == NodeFilter::FILTER_REJECT)
break;
}
- while (Node* nextSibling = NodeTraversal::nextSkippingChildren(node.get(), root())) {
+ while (Node* nextSibling = NodeTraversal::nextSkippingChildren(*node, root())) {
node = nextSibling;
short acceptNodeResult = acceptNode(state, node.get());
if (state && state->hadException())
diff --git a/chromium/third_party/WebKit/Source/core/dom/TreeWalker.idl b/chromium/third_party/WebKit/Source/core/dom/TreeWalker.idl
index dd545b88cb9..6a92eb0a168 100644
--- a/chromium/third_party/WebKit/Source/core/dom/TreeWalker.idl
+++ b/chromium/third_party/WebKit/Source/core/dom/TreeWalker.idl
@@ -20,13 +20,13 @@
// Introduced in DOM Level 2:
[
- CustomToV8
+ SetReference(NodeFilter filter)
] interface TreeWalker {
readonly attribute Node root;
readonly attribute unsigned long whatToShow;
readonly attribute NodeFilter filter;
readonly attribute boolean expandEntityReferences;
- [SetterRaisesException] attribute Node currentNode;
+ [RaisesException=Setter] attribute Node currentNode;
[CallWith=ScriptState] Node parentNode();
[CallWith=ScriptState] Node firstChild();
diff --git a/chromium/third_party/WebKit/Source/core/dom/UIEvent.cpp b/chromium/third_party/WebKit/Source/core/dom/UIEvent.cpp
deleted file mode 100644
index ade38565fe2..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/UIEvent.cpp
+++ /dev/null
@@ -1,118 +0,0 @@
-/*
- * Copyright (C) 2001 Peter Kelly (pmk@post.com)
- * Copyright (C) 2001 Tobias Anton (anton@stud.fbi.fh-darmstadt.de)
- * Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
- * Copyright (C) 2003, 2005, 2006, 2008 Apple Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-#include "core/dom/UIEvent.h"
-
-#include "core/page/DOMWindow.h"
-
-namespace WebCore {
-
-UIEventInit::UIEventInit()
- : view(0)
- , detail(0)
-{
-}
-
-UIEvent::UIEvent()
- : m_detail(0)
-{
- ScriptWrappable::init(this);
-}
-
-UIEvent::UIEvent(const AtomicString& eventType, bool canBubbleArg, bool cancelableArg, PassRefPtr<AbstractView> viewArg, int detailArg)
- : Event(eventType, canBubbleArg, cancelableArg)
- , m_view(viewArg)
- , m_detail(detailArg)
-{
- ScriptWrappable::init(this);
-}
-
-UIEvent::UIEvent(const AtomicString& eventType, const UIEventInit& initializer)
- : Event(eventType, initializer)
- , m_view(initializer.view)
- , m_detail(initializer.detail)
-{
- ScriptWrappable::init(this);
-}
-
-UIEvent::~UIEvent()
-{
-}
-
-void UIEvent::initUIEvent(const AtomicString& typeArg, bool canBubbleArg, bool cancelableArg, PassRefPtr<AbstractView> viewArg, int detailArg)
-{
- if (dispatched())
- return;
-
- initEvent(typeArg, canBubbleArg, cancelableArg);
-
- m_view = viewArg;
- m_detail = detailArg;
-}
-
-bool UIEvent::isUIEvent() const
-{
- return true;
-}
-
-const AtomicString& UIEvent::interfaceName() const
-{
- return eventNames().interfaceForUIEvent;
-}
-
-int UIEvent::keyCode() const
-{
- return 0;
-}
-
-int UIEvent::charCode() const
-{
- return 0;
-}
-
-int UIEvent::layerX()
-{
- return 0;
-}
-
-int UIEvent::layerY()
-{
- return 0;
-}
-
-int UIEvent::pageX() const
-{
- return 0;
-}
-
-int UIEvent::pageY() const
-{
- return 0;
-}
-
-int UIEvent::which() const
-{
- return 0;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/UIEvent.h b/chromium/third_party/WebKit/Source/core/dom/UIEvent.h
deleted file mode 100644
index ae52a89ded6..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/UIEvent.h
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * Copyright (C) 2001 Peter Kelly (pmk@post.com)
- * Copyright (C) 2001 Tobias Anton (anton@stud.fbi.fh-darmstadt.de)
- * Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
- * Copyright (C) 2003, 2004, 2005, 2006, 2008 Apple Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#ifndef UIEvent_h
-#define UIEvent_h
-
-#include "core/dom/Event.h"
-#include "core/dom/EventDispatchMediator.h"
-#include "core/page/DOMWindow.h"
-
-namespace WebCore {
-
-typedef DOMWindow AbstractView;
-
-struct UIEventInit : public EventInit {
- UIEventInit();
-
- RefPtr<AbstractView> view;
- int detail;
-};
-
-class UIEvent : public Event {
-public:
- static PassRefPtr<UIEvent> create()
- {
- return adoptRef(new UIEvent);
- }
- static PassRefPtr<UIEvent> create(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<AbstractView> view, int detail)
- {
- return adoptRef(new UIEvent(type, canBubble, cancelable, view, detail));
- }
- static PassRefPtr<UIEvent> create(const AtomicString& type, const UIEventInit& initializer)
- {
- return adoptRef(new UIEvent(type, initializer));
- }
- virtual ~UIEvent();
-
- void initUIEvent(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<AbstractView>, int detail);
-
- AbstractView* view() const { return m_view.get(); }
- int detail() const { return m_detail; }
-
- virtual const AtomicString& interfaceName() const;
- virtual bool isUIEvent() const;
-
- virtual int keyCode() const;
- virtual int charCode() const;
-
- virtual int layerX();
- virtual int layerY();
-
- virtual int pageX() const;
- virtual int pageY() const;
-
- virtual int which() const;
-
-protected:
- UIEvent();
- UIEvent(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<AbstractView>, int detail);
- UIEvent(const AtomicString&, const UIEventInit&);
-
-private:
- RefPtr<AbstractView> m_view;
- int m_detail;
-};
-
-} // namespace WebCore
-
-#endif // UIEvent_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/UIEvent.idl b/chromium/third_party/WebKit/Source/core/dom/UIEvent.idl
deleted file mode 100644
index bfa6da92568..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/UIEvent.idl
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright (C) 2006 Apple Computer, Inc.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-[
- ConstructorTemplate=Event
-] interface UIEvent : Event {
- [InitializedByEventConstructor] readonly attribute Window view;
- [InitializedByEventConstructor] readonly attribute long detail;
-
- void initUIEvent([Default=Undefined] optional DOMString type,
- [Default=Undefined] optional boolean canBubble,
- [Default=Undefined] optional boolean cancelable,
- [Default=Undefined] optional Window view,
- [Default=Undefined] optional long detail);
-
- // extensions
- readonly attribute long keyCode;
- readonly attribute long charCode;
- readonly attribute long layerX;
- readonly attribute long layerY;
- readonly attribute long pageX;
- readonly attribute long pageY;
- readonly attribute long which;
-};
-
diff --git a/chromium/third_party/WebKit/Source/core/dom/UIEventWithKeyState.cpp b/chromium/third_party/WebKit/Source/core/dom/UIEventWithKeyState.cpp
deleted file mode 100644
index da510d93d4e..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/UIEventWithKeyState.cpp
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Copyright (C) 2006 Apple Computer, Inc.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#include "config.h"
-#include "core/dom/UIEventWithKeyState.h"
-
-namespace WebCore {
-
-UIEventWithKeyState* findEventWithKeyState(Event* event)
-{
- for (Event* e = event; e; e = e->underlyingEvent())
- if (e->isKeyboardEvent() || e->isMouseEvent())
- return static_cast<UIEventWithKeyState*>(e);
- return 0;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/UIEventWithKeyState.h b/chromium/third_party/WebKit/Source/core/dom/UIEventWithKeyState.h
deleted file mode 100644
index bcf9a8090f8..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/UIEventWithKeyState.h
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Copyright (C) 2001 Peter Kelly (pmk@post.com)
- * Copyright (C) 2001 Tobias Anton (anton@stud.fbi.fh-darmstadt.de)
- * Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
- * Copyright (C) 2003, 2004, 2005, 2006, 2008 Apple Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#ifndef UIEventWithKeyState_h
-#define UIEventWithKeyState_h
-
-#include "core/dom/UIEvent.h"
-
-namespace WebCore {
-
- class UIEventWithKeyState : public UIEvent {
- public:
- bool ctrlKey() const { return m_ctrlKey; }
- bool shiftKey() const { return m_shiftKey; }
- bool altKey() const { return m_altKey; }
- bool metaKey() const { return m_metaKey; }
-
- protected:
- UIEventWithKeyState()
- : m_ctrlKey(false)
- , m_altKey(false)
- , m_shiftKey(false)
- , m_metaKey(false)
- {
- }
-
- UIEventWithKeyState(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<AbstractView> view,
- int detail, bool ctrlKey, bool altKey, bool shiftKey, bool metaKey)
- : UIEvent(type, canBubble, cancelable, view, detail)
- , m_ctrlKey(ctrlKey)
- , m_altKey(altKey)
- , m_shiftKey(shiftKey)
- , m_metaKey(metaKey)
- {
- }
-
- // Expose these so init functions can set them.
- bool m_ctrlKey : 1;
- bool m_altKey : 1;
- bool m_shiftKey : 1;
- bool m_metaKey : 1;
- };
-
- UIEventWithKeyState* findEventWithKeyState(Event*);
-
-} // namespace WebCore
-
-#endif // UIEventWithKeyState_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/URL.idl b/chromium/third_party/WebKit/Source/core/dom/URL.idl
new file mode 100644
index 00000000000..30c96c69db2
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/URL.idl
@@ -0,0 +1,40 @@
+/*
+ * Copyright (C) 2011 Google Inc. All rights reserved.
+ * Copyright (C) 2012 Motorola Mobility Inc.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+[
+ GlobalContext=Window&WorkerGlobalScope,
+ RaisesException=Constructor,
+ Constructor(DOMString url),
+ Constructor(DOMString url, URL base),
+ Constructor(DOMString url, DOMString base),
+ ImplementedAs=DOMURL
+] interface URL {
+ [CallWith=ExecutionContext,TreatReturnedNullStringAs=Null] static DOMString createObjectURL(Blob? blob);
+ [CallWith=ExecutionContext] static void revokeObjectURL(DOMString url);
+};
+
+// force rebuild: crbug.com/307023
+URL implements URLUtils;
diff --git a/chromium/third_party/WebKit/Source/core/dom/URLUtils.idl b/chromium/third_party/WebKit/Source/core/dom/URLUtils.idl
new file mode 100644
index 00000000000..9cb7b488597
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/URLUtils.idl
@@ -0,0 +1,49 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+[
+ NoInterfaceObject,
+ ImplementedAs=DOMURLUtils
+] interface URLUtils {
+ attribute DOMString href;
+
+ [NotEnumerable, ImplementedAs=href] DOMString toString();
+
+ readonly attribute DOMString origin;
+ attribute DOMString protocol;
+ attribute DOMString username;
+ attribute DOMString password;
+ attribute DOMString host;
+ attribute DOMString hostname;
+ attribute DOMString port;
+ attribute DOMString pathname;
+ attribute DOMString search;
+
+ // Not yet implemented.
+ // attribute URLQuery? query;
+
+ attribute DOMString hash;
+};
+
diff --git a/chromium/third_party/WebKit/Source/core/dom/URLUtilsReadOnly.idl b/chromium/third_party/WebKit/Source/core/dom/URLUtilsReadOnly.idl
new file mode 100644
index 00000000000..0d36b46d0af
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/URLUtilsReadOnly.idl
@@ -0,0 +1,41 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+[
+ NoInterfaceObject,
+ ImplementedAs=DOMURLUtilsReadOnly
+] interface URLUtilsReadOnly {
+ readonly attribute DOMString href;
+
+ [NotEnumerable, ImplementedAs=href] DOMString toString();
+
+ readonly attribute DOMString protocol;
+ readonly attribute DOMString host;
+ readonly attribute DOMString hostname;
+ readonly attribute DOMString port;
+ readonly attribute DOMString pathname;
+ readonly attribute DOMString search;
+ readonly attribute DOMString hash;
+};
diff --git a/chromium/third_party/WebKit/Source/core/dom/UserGestureIndicator.cpp b/chromium/third_party/WebKit/Source/core/dom/UserGestureIndicator.cpp
deleted file mode 100644
index 1de9fa12e5f..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/UserGestureIndicator.cpp
+++ /dev/null
@@ -1,211 +0,0 @@
-/*
- * Copyright (C) 2010 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/dom/UserGestureIndicator.h"
-#include "wtf/Assertions.h"
-#include "wtf/CurrentTime.h"
-#include "wtf/MainThread.h"
-
-namespace WebCore {
-
-namespace {
-
-// User gestures timeout in 1 second.
-const double userGestureTimeout = 1.0;
-
-// For out of process tokens we allow a 10 second delay.
-const double userGestureOutOfProcessTimeout = 10.0;
-
-class GestureToken : public UserGestureToken {
-public:
- static PassRefPtr<UserGestureToken> create() { return adoptRef(new GestureToken); }
-
- virtual ~GestureToken() { }
- virtual bool hasGestures() const OVERRIDE
- {
- // Do not enforce timeouts for gestures which spawned javascript prompts.
- if (m_consumableGestures < 1 || (WTF::currentTime() - m_timestamp > (m_outOfProcess ? userGestureOutOfProcessTimeout : userGestureTimeout) && !m_javascriptPrompt))
- return false;
- return true;
- }
-
- void addGesture()
- {
- m_consumableGestures++;
- m_timestamp = WTF::currentTime();
- }
-
- void resetTimestamp()
- {
- m_timestamp = WTF::currentTime();
- }
-
- bool consumeGesture()
- {
- if (!m_consumableGestures)
- return false;
- m_consumableGestures--;
- return true;
- }
-
- virtual void setOutOfProcess() OVERRIDE
- {
- if (WTF::currentTime() - m_timestamp > userGestureTimeout)
- return;
- if (hasGestures())
- m_outOfProcess = true;
- }
-
- virtual void setJavascriptPrompt() OVERRIDE
- {
- if (WTF::currentTime() - m_timestamp > userGestureTimeout)
- return;
- if (hasGestures())
- m_javascriptPrompt = true;
- }
-
-private:
- GestureToken()
- : m_consumableGestures(0),
- m_timestamp(0),
- m_outOfProcess(false),
- m_javascriptPrompt(false)
- {
- }
-
- size_t m_consumableGestures;
- double m_timestamp;
- bool m_outOfProcess;
- bool m_javascriptPrompt;
-};
-
-}
-
-static bool isDefinite(ProcessingUserGestureState state)
-{
- return state == DefinitelyProcessingNewUserGesture || state == DefinitelyProcessingUserGesture || state == DefinitelyNotProcessingUserGesture;
-}
-
-ProcessingUserGestureState UserGestureIndicator::s_state = DefinitelyNotProcessingUserGesture;
-UserGestureIndicator* UserGestureIndicator::s_topmostIndicator = 0;
-
-UserGestureIndicator::UserGestureIndicator(ProcessingUserGestureState state)
- : m_previousState(s_state)
-{
- // Silently ignore UserGestureIndicators on non-main threads.
- if (!isMainThread())
- return;
-
- // We overwrite s_state only if the caller is definite about the gesture state.
- if (isDefinite(state)) {
- if (!s_topmostIndicator) {
- s_topmostIndicator = this;
- m_token = GestureToken::create();
- } else
- m_token = s_topmostIndicator->currentToken();
- s_state = state;
- }
-
- if (state == DefinitelyProcessingNewUserGesture)
- static_cast<GestureToken*>(m_token.get())->addGesture();
- else if (state == DefinitelyProcessingUserGesture && s_topmostIndicator == this)
- static_cast<GestureToken*>(m_token.get())->addGesture();
- ASSERT(isDefinite(s_state));
-}
-
-UserGestureIndicator::UserGestureIndicator(PassRefPtr<UserGestureToken> token)
- : m_previousState(s_state)
-{
- // Silently ignore UserGestureIndicators on non-main threads.
- if (!isMainThread())
- return;
-
- if (token) {
- static_cast<GestureToken*>(token.get())->resetTimestamp();
- if (!s_topmostIndicator) {
- s_topmostIndicator = this;
- m_token = token;
- } else {
- m_token = s_topmostIndicator->currentToken();
- if (static_cast<GestureToken*>(token.get())->hasGestures()) {
- static_cast<GestureToken*>(m_token.get())->addGesture();
- static_cast<GestureToken*>(token.get())->consumeGesture();
- }
- }
- s_state = DefinitelyProcessingUserGesture;
- }
-
- ASSERT(isDefinite(s_state));
-}
-
-UserGestureIndicator::~UserGestureIndicator()
-{
- if (!isMainThread())
- return;
- s_state = m_previousState;
- if (s_topmostIndicator == this)
- s_topmostIndicator = 0;
- ASSERT(isDefinite(s_state));
-}
-
-bool UserGestureIndicator::processingUserGesture()
-{
- if (!isMainThread())
- return false;
- return s_topmostIndicator && static_cast<GestureToken*>(s_topmostIndicator->currentToken())->hasGestures() && (s_state == DefinitelyProcessingNewUserGesture || s_state == DefinitelyProcessingUserGesture);
-}
-
-bool UserGestureIndicator::consumeUserGesture()
-{
- if (!isMainThread() || !s_topmostIndicator)
- return false;
- return static_cast<GestureToken*>(s_topmostIndicator->currentToken())->consumeGesture();
-}
-
-UserGestureToken* UserGestureIndicator::currentToken()
-{
- if (!isMainThread() || !s_topmostIndicator)
- return 0;
- return s_topmostIndicator->m_token.get();
-}
-
-UserGestureIndicatorDisabler::UserGestureIndicatorDisabler()
- : m_savedState(UserGestureIndicator::s_state)
- , m_savedIndicator(UserGestureIndicator::s_topmostIndicator)
-{
- RELEASE_ASSERT(isMainThread());
- UserGestureIndicator::s_state = DefinitelyNotProcessingUserGesture;
- UserGestureIndicator::s_topmostIndicator = 0;
-}
-
-UserGestureIndicatorDisabler::~UserGestureIndicatorDisabler()
-{
- RELEASE_ASSERT(isMainThread());
- UserGestureIndicator::s_state = m_savedState;
- UserGestureIndicator::s_topmostIndicator = m_savedIndicator;
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/dom/UserGestureIndicator.h b/chromium/third_party/WebKit/Source/core/dom/UserGestureIndicator.h
deleted file mode 100644
index fd251f21082..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/UserGestureIndicator.h
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- * Copyright (C) 2010 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef UserGestureIndicator_h
-#define UserGestureIndicator_h
-
-#include "wtf/Noncopyable.h"
-#include "wtf/RefCounted.h"
-#include "wtf/RefPtr.h"
-
-namespace WebCore {
-
-class UserGestureIndicator;
-
-enum ProcessingUserGestureState {
- DefinitelyProcessingNewUserGesture,
- DefinitelyProcessingUserGesture,
- PossiblyProcessingUserGesture,
- DefinitelyNotProcessingUserGesture
-};
-
-class UserGestureToken : public RefCounted<UserGestureToken> {
-public:
- virtual ~UserGestureToken() { }
- virtual bool hasGestures() const = 0;
- virtual void setOutOfProcess() = 0;
- virtual void setJavascriptPrompt() = 0;
-};
-
-class UserGestureIndicatorDisabler {
- WTF_MAKE_NONCOPYABLE(UserGestureIndicatorDisabler);
-public:
- UserGestureIndicatorDisabler();
- ~UserGestureIndicatorDisabler();
-
-private:
- ProcessingUserGestureState m_savedState;
- UserGestureIndicator* m_savedIndicator;
-};
-
-class UserGestureIndicator {
- WTF_MAKE_NONCOPYABLE(UserGestureIndicator);
- friend class UserGestureIndicatorDisabler;
-public:
- static bool processingUserGesture();
- static bool consumeUserGesture();
- static UserGestureToken* currentToken();
-
- explicit UserGestureIndicator(ProcessingUserGestureState);
- explicit UserGestureIndicator(PassRefPtr<UserGestureToken>);
- ~UserGestureIndicator();
-
-
-private:
- static ProcessingUserGestureState s_state;
- static UserGestureIndicator* s_topmostIndicator;
- ProcessingUserGestureState m_previousState;
- RefPtr<UserGestureToken> m_token;
-};
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/dom/UserTypingGestureIndicator.cpp b/chromium/third_party/WebKit/Source/core/dom/UserTypingGestureIndicator.cpp
deleted file mode 100644
index e05967e7971..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/UserTypingGestureIndicator.cpp
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright (C) 2010 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/dom/UserTypingGestureIndicator.h"
-
-#include "core/dom/Document.h"
-#include "core/dom/Element.h"
-#include "core/page/Frame.h"
-
-namespace WebCore {
-
-static bool s_processingUserTypingGesture;
-bool UserTypingGestureIndicator::processingUserTypingGesture()
-{
- return s_processingUserTypingGesture;
-}
-
-static RefPtr<Element>& focusedElement()
-{
- DEFINE_STATIC_LOCAL(RefPtr<Element>, element, ());
- return element;
-}
-
-Element* UserTypingGestureIndicator::focusedElementAtGestureStart()
-{
- return focusedElement().get();
-}
-
-UserTypingGestureIndicator::UserTypingGestureIndicator(Frame* frame)
- : m_previousProcessingUserTypingGesture(s_processingUserTypingGesture)
- , m_previousFocusedElement(focusedElement())
-{
- s_processingUserTypingGesture = true;
- focusedElement() = frame->document() ? frame->document()->focusedElement() : 0;
-}
-
-UserTypingGestureIndicator::~UserTypingGestureIndicator()
-{
- s_processingUserTypingGesture = m_previousProcessingUserTypingGesture;
- focusedElement() = m_previousFocusedElement;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/UserTypingGestureIndicator.h b/chromium/third_party/WebKit/Source/core/dom/UserTypingGestureIndicator.h
deleted file mode 100644
index 6625b36a828..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/UserTypingGestureIndicator.h
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright (C) 2010 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef UserTypingGestureIndicator_h
-#define UserTypingGestureIndicator_h
-
-#include "wtf/Noncopyable.h"
-#include "wtf/RefPtr.h"
-
-namespace WebCore {
-
-class Frame;
-class Element;
-
-class UserTypingGestureIndicator {
- WTF_MAKE_NONCOPYABLE(UserTypingGestureIndicator);
-public:
- static bool processingUserTypingGesture();
- static Element* focusedElementAtGestureStart();
-
- explicit UserTypingGestureIndicator(Frame*);
- ~UserTypingGestureIndicator();
-
-private:
- bool m_previousProcessingUserTypingGesture;
- RefPtr<Element> m_previousFocusedElement;
-};
-
-} // namespace WebCore
-
-#endif // UserTypingGestureIndicator_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/ViewportArguments.cpp b/chromium/third_party/WebKit/Source/core/dom/ViewportArguments.cpp
deleted file mode 100644
index 48d56e41ad0..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/ViewportArguments.cpp
+++ /dev/null
@@ -1,398 +0,0 @@
-/*
- * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
- * (C) 1999 Antti Koivisto (koivisto@kde.org)
- * (C) 2001 Dirk Mueller (mueller@kde.org)
- * (C) 2006 Alexey Proskuryakov (ap@webkit.org)
- * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2011 Apple Inc. All rights reserved.
- * Copyright (C) 2008 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
- * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
- * Copyright (C) 2012-2013 Intel Corporation. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#include "config.h"
-#include "core/dom/ViewportArguments.h"
-
-#include "core/dom/Document.h"
-#include "core/page/Page.h"
-#include "core/page/Settings.h"
-#include "wtf/text/WTFString.h"
-
-using namespace std;
-
-namespace WebCore {
-
-static const float& compareIgnoringAuto(const float& value1, const float& value2, const float& (*compare) (const float&, const float&))
-{
- if (value1 == ViewportArguments::ValueAuto)
- return value2;
-
- if (value2 == ViewportArguments::ValueAuto)
- return value1;
-
- return compare(value1, value2);
-}
-
-static inline float clampLengthValue(float value)
-{
- // Limits as defined in the css-device-adapt spec.
- if (value != ViewportArguments::ValueAuto)
- return min(float(10000), max(value, float(1)));
- return value;
-}
-
-static inline float clampScaleValue(float value)
-{
- // Limits as defined in the css-device-adapt spec.
- if (value != ViewportArguments::ValueAuto)
- return min(float(10), max(value, float(0.1)));
- return value;
-}
-
-float ViewportArguments::resolveViewportLength(const Length& length, const FloatSize& initialViewportSize, Direction direction)
-{
- if (length.isAuto())
- return ViewportArguments::ValueAuto;
-
- if (length.isFixed())
- return length.getFloatValue();
-
- if (length.type() == ExtendToZoom)
- return ViewportArguments::ValueExtendToZoom;
-
- if ((length.type() == Percent && direction == Horizontal) || length.type() == ViewportPercentageWidth)
- return initialViewportSize.width() * length.getFloatValue() / 100.0f;
-
- if ((length.type() == Percent && direction == Vertical) || length.type() == ViewportPercentageHeight)
- return initialViewportSize.height() * length.getFloatValue() / 100.0f;
-
- if (length.type() == ViewportPercentageMin)
- return min(initialViewportSize.width(), initialViewportSize.height()) * length.viewportPercentageLength() / 100.0f;
-
- if (length.type() == ViewportPercentageMax)
- return max(initialViewportSize.width(), initialViewportSize.height()) * length.viewportPercentageLength() / 100.0f;
-
- ASSERT_NOT_REACHED();
- return ViewportArguments::ValueAuto;
-}
-
-PageScaleConstraints ViewportArguments::resolve(const FloatSize& initialViewportSize) const
-{
- float resultWidth = ValueAuto;
- float resultMaxWidth = resolveViewportLength(maxWidth, initialViewportSize, Horizontal);
- float resultMinWidth = resolveViewportLength(minWidth, initialViewportSize, Horizontal);
- float resultHeight = ValueAuto;
- float resultMaxHeight = resolveViewportLength(maxHeight, initialViewportSize, Vertical);
- float resultMinHeight = resolveViewportLength(minHeight, initialViewportSize, Vertical);
-
- float resultZoom = zoom;
- float resultMinZoom = minZoom;
- float resultMaxZoom = maxZoom;
- float resultUserZoom = userZoom;
-
- // 1. Resolve min-zoom and max-zoom values.
- if (resultMinZoom != ViewportArguments::ValueAuto && resultMaxZoom != ViewportArguments::ValueAuto)
- resultMaxZoom = max(resultMinZoom, resultMaxZoom);
-
- // 2. Constrain zoom value to the [min-zoom, max-zoom] range.
- if (resultZoom != ViewportArguments::ValueAuto)
- resultZoom = compareIgnoringAuto(resultMinZoom, compareIgnoringAuto(resultMaxZoom, resultZoom, min), max);
-
- float extendZoom = compareIgnoringAuto(resultZoom, resultMaxZoom, min);
-
- // 3. Resolve non-"auto" lengths to pixel lengths.
- if (extendZoom == ViewportArguments::ValueAuto) {
- if (resultMaxWidth == ViewportArguments::ValueExtendToZoom)
- resultMaxWidth = ViewportArguments::ValueAuto;
-
- if (resultMaxHeight == ViewportArguments::ValueExtendToZoom)
- resultMaxHeight = ViewportArguments::ValueAuto;
-
- if (resultMinWidth == ViewportArguments::ValueExtendToZoom)
- resultMinWidth = resultMaxWidth;
-
- if (resultMinHeight == ViewportArguments::ValueExtendToZoom)
- resultMinHeight = resultMaxHeight;
- } else {
- float extendWidth = initialViewportSize.width() / extendZoom;
- float extendHeight = initialViewportSize.height() / extendZoom;
-
- if (resultMaxWidth == ViewportArguments::ValueExtendToZoom)
- resultMaxWidth = extendWidth;
-
- if (resultMaxHeight == ViewportArguments::ValueExtendToZoom)
- resultMaxHeight = extendHeight;
-
- if (resultMinWidth == ViewportArguments::ValueExtendToZoom)
- resultMinWidth = compareIgnoringAuto(extendWidth, resultMaxWidth, max);
-
- if (resultMinHeight == ViewportArguments::ValueExtendToZoom)
- resultMinHeight = compareIgnoringAuto(extendHeight, resultMaxHeight, max);
- }
-
- // 4. Resolve initial width from min/max descriptors.
- if (resultMinWidth != ViewportArguments::ValueAuto || resultMaxWidth != ViewportArguments::ValueAuto)
- resultWidth = compareIgnoringAuto(resultMinWidth, compareIgnoringAuto(resultMaxWidth, initialViewportSize.width(), min), max);
-
- // 5. Resolve initial height from min/max descriptors.
- if (resultMinHeight != ViewportArguments::ValueAuto || resultMaxHeight != ViewportArguments::ValueAuto)
- resultHeight = compareIgnoringAuto(resultMinHeight, compareIgnoringAuto(resultMaxHeight, initialViewportSize.height(), min), max);
-
- // 6-7. Resolve width value.
- if (resultWidth == ViewportArguments::ValueAuto) {
- if (resultHeight == ViewportArguments::ValueAuto || !initialViewportSize.height())
- resultWidth = initialViewportSize.width();
- else
- resultWidth = resultHeight * (initialViewportSize.width() / initialViewportSize.height());
- }
-
- // 8. Resolve height value.
- if (resultHeight == ViewportArguments::ValueAuto) {
- if (!initialViewportSize.width())
- resultHeight = initialViewportSize.height();
- else
- resultHeight = resultWidth * initialViewportSize.height() / initialViewportSize.width();
- }
-
- // Resolve initial-scale value.
- if (resultZoom == ViewportArguments::ValueAuto) {
- if (resultWidth != ViewportArguments::ValueAuto && resultWidth > 0)
- resultZoom = initialViewportSize.width() / resultWidth;
- if (resultHeight != ViewportArguments::ValueAuto && resultHeight > 0) {
- // if 'auto', the initial-scale will be negative here and thus ignored.
- resultZoom = max<float>(resultZoom, initialViewportSize.height() / resultHeight);
- }
- }
-
- // If user-scalable = no, lock the min/max scale to the computed initial
- // scale.
- if (!resultUserZoom)
- resultMinZoom = resultMaxZoom = resultZoom;
-
- // Only set initialScale to a value if it was explicitly set.
- if (zoom == ViewportArguments::ValueAuto)
- resultZoom = ViewportArguments::ValueAuto;
-
- PageScaleConstraints result;
- result.minimumScale = resultMinZoom;
- result.maximumScale = resultMaxZoom;
- result.initialScale = resultZoom;
- result.layoutSize.setWidth(resultWidth);
- result.layoutSize.setHeight(resultHeight);
- return result;
-}
-
-static float numericPrefix(const String& keyString, const String& valueString, Document* document, bool* ok = 0)
-{
- size_t parsedLength;
- float value;
- if (valueString.is8Bit())
- value = charactersToFloat(valueString.characters8(), valueString.length(), parsedLength);
- else
- value = charactersToFloat(valueString.characters16(), valueString.length(), parsedLength);
- if (!parsedLength) {
- reportViewportWarning(document, UnrecognizedViewportArgumentValueError, valueString, keyString);
- if (ok)
- *ok = false;
- return 0;
- }
- if (parsedLength < valueString.length())
- reportViewportWarning(document, TruncatedViewportArgumentValueError, valueString, keyString);
- if (ok)
- *ok = true;
- return value;
-}
-
-static Length findSizeValue(const String& keyString, const String& valueString, Document* document)
-{
- // 1) Non-negative number values are translated to px lengths.
- // 2) Negative number values are translated to auto.
- // 3) device-width and device-height are used as keywords.
- // 4) Other keywords and unknown values translate to 0.0.
-
- if (equalIgnoringCase(valueString, "device-width"))
- return Length(100, ViewportPercentageWidth);
- if (equalIgnoringCase(valueString, "device-height"))
- return Length(100, ViewportPercentageHeight);
-
- float value = numericPrefix(keyString, valueString, document);
-
- if (value < 0)
- return Length(); // auto
-
- if (!static_cast<int>(value) && document->page() && document->page()->settings().viewportMetaZeroValuesQuirk()) {
- if (keyString == "width")
- return Length(100, ViewportPercentageWidth);
- if (keyString == "height")
- return Length(100, ViewportPercentageHeight);
- }
-
- return Length(clampLengthValue(value), Fixed);
-}
-
-static float findScaleValue(const String& keyString, const String& valueString, Document* document)
-{
- // 1) Non-negative number values are translated to <number> values.
- // 2) Negative number values are translated to auto.
- // 3) yes is translated to 1.0.
- // 4) device-width and device-height are translated to 10.0.
- // 5) no and unknown values are translated to 0.0
-
- if (equalIgnoringCase(valueString, "yes"))
- return 1;
- if (equalIgnoringCase(valueString, "no"))
- return 0;
- if (equalIgnoringCase(valueString, "device-width"))
- return 10;
- if (equalIgnoringCase(valueString, "device-height"))
- return 10;
-
- float value = numericPrefix(keyString, valueString, document);
-
- if (value < 0)
- return ViewportArguments::ValueAuto;
-
- if (value > 10.0)
- reportViewportWarning(document, MaximumScaleTooLargeError, String(), String());
-
- if (!static_cast<int>(value) && document->page() && document->page()->settings().viewportMetaZeroValuesQuirk() && (keyString == "minimum-scale" || keyString == "maximum-scale"))
- return ViewportArguments::ValueAuto;
-
- return clampScaleValue(value);
-}
-
-static float findUserScalableValue(const String& keyString, const String& valueString, Document* document)
-{
- // yes and no are used as keywords.
- // Numbers >= 1, numbers <= -1, device-width and device-height are mapped to yes.
- // Numbers in the range <-1, 1>, and unknown values, are mapped to no.
-
- if (equalIgnoringCase(valueString, "yes"))
- return 1;
- if (equalIgnoringCase(valueString, "no"))
- return 0;
- if (equalIgnoringCase(valueString, "device-width"))
- return 1;
- if (equalIgnoringCase(valueString, "device-height"))
- return 1;
-
- float value = numericPrefix(keyString, valueString, document);
-
- if (fabs(value) < 1)
- return 0;
-
- return 1;
-}
-
-static float findTargetDensityDPIValue(const String& keyString, const String& valueString, Document* document)
-{
- if (equalIgnoringCase(valueString, "device-dpi"))
- return ViewportArguments::ValueDeviceDPI;
- if (equalIgnoringCase(valueString, "low-dpi"))
- return ViewportArguments::ValueLowDPI;
- if (equalIgnoringCase(valueString, "medium-dpi"))
- return ViewportArguments::ValueMediumDPI;
- if (equalIgnoringCase(valueString, "high-dpi"))
- return ViewportArguments::ValueHighDPI;
-
- bool ok;
- float value = numericPrefix(keyString, valueString, document, &ok);
- if (!ok || value < 70 || value > 400)
- return ViewportArguments::ValueAuto;
-
- return value;
-}
-
-void setViewportFeature(const String& keyString, const String& valueString, Document* document, void* data)
-{
- ViewportArguments* arguments = static_cast<ViewportArguments*>(data);
-
- if (keyString == "width") {
- const Length& width = findSizeValue(keyString, valueString, document);
- if (!width.isAuto()) {
- arguments->minWidth = Length(ExtendToZoom);
- arguments->maxWidth = width;
- }
- } else if (keyString == "height") {
- const Length& height = findSizeValue(keyString, valueString, document);
- if (!height.isAuto()) {
- arguments->minHeight = Length(ExtendToZoom);
- arguments->maxHeight = height;
- }
- } else if (keyString == "initial-scale") {
- arguments->zoom = findScaleValue(keyString, valueString, document);
- } else if (keyString == "minimum-scale") {
- arguments->minZoom = findScaleValue(keyString, valueString, document);
- } else if (keyString == "maximum-scale") {
- arguments->maxZoom = findScaleValue(keyString, valueString, document);
- } else if (keyString == "user-scalable") {
- arguments->userZoom = findUserScalableValue(keyString, valueString, document);
- } else if (keyString == "target-densitydpi") {
- arguments->deprecatedTargetDensityDPI = findTargetDensityDPIValue(keyString, valueString, document);
- reportViewportWarning(document, TargetDensityDpiUnsupported, String(), String());
- } else {
- reportViewportWarning(document, UnrecognizedViewportArgumentKeyError, keyString, String());
- }
-}
-
-static const char* viewportErrorMessageTemplate(ViewportErrorCode errorCode)
-{
- static const char* const errors[] = {
- "The key \"%replacement1\" is not recognized and ignored.",
- "The value \"%replacement1\" for key \"%replacement2\" is invalid, and has been ignored.",
- "The value \"%replacement1\" for key \"%replacement2\" was truncated to its numeric prefix.",
- "The value for key \"maximum-scale\" is out of bounds and the value has been clamped.",
- "The key \"target-densitydpi\" is not supported.",
- };
-
- return errors[errorCode];
-}
-
-static MessageLevel viewportErrorMessageLevel(ViewportErrorCode errorCode)
-{
- switch (errorCode) {
- case TruncatedViewportArgumentValueError:
- case TargetDensityDpiUnsupported:
- return WarningMessageLevel;
- case UnrecognizedViewportArgumentKeyError:
- case UnrecognizedViewportArgumentValueError:
- case MaximumScaleTooLargeError:
- return ErrorMessageLevel;
- }
-
- ASSERT_NOT_REACHED();
- return ErrorMessageLevel;
-}
-
-void reportViewportWarning(Document* document, ViewportErrorCode errorCode, const String& replacement1, const String& replacement2)
-{
- Frame* frame = document->frame();
- if (!frame)
- return;
-
- String message = viewportErrorMessageTemplate(errorCode);
- if (!replacement1.isNull())
- message.replace("%replacement1", replacement1);
- if (!replacement2.isNull())
- message.replace("%replacement2", replacement2);
-
- // FIXME: This message should be moved off the console once a solution to https://bugs.webkit.org/show_bug.cgi?id=103274 exists.
- document->addConsoleMessage(RenderingMessageSource, viewportErrorMessageLevel(errorCode), message);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/ViewportArguments.h b/chromium/third_party/WebKit/Source/core/dom/ViewportArguments.h
deleted file mode 100644
index e0722b811c4..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/ViewportArguments.h
+++ /dev/null
@@ -1,130 +0,0 @@
-/*
- * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
- * (C) 1999 Antti Koivisto (koivisto@kde.org)
- * (C) 2001 Dirk Mueller (mueller@kde.org)
- * (C) 2006 Alexey Proskuryakov (ap@webkit.org)
- * Copyright (C) 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
- * Copyright (C) 2008 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
- * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
- * Copyright (C) 2012-2013 Intel Corporation. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#ifndef ViewportArguments_h
-#define ViewportArguments_h
-
-#include "core/page/PageScaleConstraints.h"
-#include "core/platform/Length.h"
-#include "core/platform/graphics/FloatSize.h"
-#include "wtf/Forward.h"
-
-namespace WebCore {
-
-class Document;
-
-enum ViewportErrorCode {
- UnrecognizedViewportArgumentKeyError,
- UnrecognizedViewportArgumentValueError,
- TruncatedViewportArgumentValueError,
- MaximumScaleTooLargeError,
- TargetDensityDpiUnsupported
-};
-
-struct ViewportArguments {
-
- enum Type {
- // These are ordered in increasing importance.
- UserAgentStyleSheet,
- HandheldFriendlyMeta,
- MobileOptimizedMeta,
- ViewportMeta,
- AuthorStyleSheet
- } type;
-
- enum {
- ValueAuto = -1,
- ValueDeviceWidth = -2,
- ValueDeviceHeight = -3,
- ValuePortrait = -4,
- ValueLandscape = -5,
- ValueDeviceDPI = -6,
- ValueLowDPI = -7,
- ValueMediumDPI = -8,
- ValueHighDPI = -9,
- ValueExtendToZoom = -10
- };
-
- ViewportArguments(Type type = UserAgentStyleSheet)
- : type(type)
- , zoom(ValueAuto)
- , minZoom(ValueAuto)
- , maxZoom(ValueAuto)
- , userZoom(ValueAuto)
- , orientation(ValueAuto)
- , deprecatedTargetDensityDPI(ValueAuto)
- {
- }
-
- // All arguments are in CSS units.
- PageScaleConstraints resolve(const FloatSize& initialViewportSize) const;
-
- Length minWidth;
- Length maxWidth;
- Length minHeight;
- Length maxHeight;
- float zoom;
- float minZoom;
- float maxZoom;
- float userZoom;
- float orientation;
- float deprecatedTargetDensityDPI; // Only used for Android WebView
-
- bool operator==(const ViewportArguments& other) const
- {
- // Used for figuring out whether to reset the viewport or not,
- // thus we are not taking type into account.
- return minWidth == other.minWidth
- && maxWidth == other.maxWidth
- && minHeight == other.minHeight
- && maxHeight == other.maxHeight
- && zoom == other.zoom
- && minZoom == other.minZoom
- && maxZoom == other.maxZoom
- && userZoom == other.userZoom
- && orientation == other.orientation
- && deprecatedTargetDensityDPI == other.deprecatedTargetDensityDPI;
- }
-
- bool operator!=(const ViewportArguments& other) const
- {
- return !(*this == other);
- }
-
- bool isLegacyViewportType() const { return type >= HandheldFriendlyMeta && type <= ViewportMeta; }
-
-private:
- enum Direction { Horizontal, Vertical };
- static float resolveViewportLength(const Length&, const FloatSize& initialViewportSize, Direction);
-};
-
-void setViewportFeature(const String& keyString, const String& valueString, Document*, void* data);
-void reportViewportWarning(Document*, ViewportErrorCode, const String& replacement1, const String& replacement2);
-
-} // namespace WebCore
-
-#endif // ViewportArguments_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/ViewportDescription.cpp b/chromium/third_party/WebKit/Source/core/dom/ViewportDescription.cpp
new file mode 100644
index 00000000000..77f924e623b
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/ViewportDescription.cpp
@@ -0,0 +1,179 @@
+/*
+ * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
+ * (C) 1999 Antti Koivisto (koivisto@kde.org)
+ * (C) 2001 Dirk Mueller (mueller@kde.org)
+ * (C) 2006 Alexey Proskuryakov (ap@webkit.org)
+ * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2011 Apple Inc. All rights reserved.
+ * Copyright (C) 2008 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
+ * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
+ * Copyright (C) 2012-2013 Intel Corporation. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ */
+
+#include "config.h"
+#include "core/dom/ViewportDescription.h"
+
+using namespace std;
+
+namespace WebCore {
+
+static const float& compareIgnoringAuto(const float& value1, const float& value2, const float& (*compare) (const float&, const float&))
+{
+ if (value1 == ViewportDescription::ValueAuto)
+ return value2;
+
+ if (value2 == ViewportDescription::ValueAuto)
+ return value1;
+
+ return compare(value1, value2);
+}
+
+float ViewportDescription::resolveViewportLength(const Length& length, const FloatSize& initialViewportSize, Direction direction)
+{
+ if (length.isAuto())
+ return ViewportDescription::ValueAuto;
+
+ if (length.isFixed())
+ return length.getFloatValue();
+
+ if (length.type() == ExtendToZoom)
+ return ViewportDescription::ValueExtendToZoom;
+
+ if ((length.type() == Percent && direction == Horizontal) || length.type() == ViewportPercentageWidth)
+ return initialViewportSize.width() * length.getFloatValue() / 100.0f;
+
+ if ((length.type() == Percent && direction == Vertical) || length.type() == ViewportPercentageHeight)
+ return initialViewportSize.height() * length.getFloatValue() / 100.0f;
+
+ if (length.type() == ViewportPercentageMin)
+ return min(initialViewportSize.width(), initialViewportSize.height()) * length.viewportPercentageLength() / 100.0f;
+
+ if (length.type() == ViewportPercentageMax)
+ return max(initialViewportSize.width(), initialViewportSize.height()) * length.viewportPercentageLength() / 100.0f;
+
+ ASSERT_NOT_REACHED();
+ return ViewportDescription::ValueAuto;
+}
+
+PageScaleConstraints ViewportDescription::resolve(const FloatSize& initialViewportSize) const
+{
+ float resultWidth = ValueAuto;
+ float resultMaxWidth = resolveViewportLength(maxWidth, initialViewportSize, Horizontal);
+ float resultMinWidth = resolveViewportLength(minWidth, initialViewportSize, Horizontal);
+ float resultHeight = ValueAuto;
+ float resultMaxHeight = resolveViewportLength(maxHeight, initialViewportSize, Vertical);
+ float resultMinHeight = resolveViewportLength(minHeight, initialViewportSize, Vertical);
+
+ float resultZoom = zoom;
+ float resultMinZoom = minZoom;
+ float resultMaxZoom = maxZoom;
+ float resultUserZoom = userZoom;
+
+ // 1. Resolve min-zoom and max-zoom values.
+ if (resultMinZoom != ViewportDescription::ValueAuto && resultMaxZoom != ViewportDescription::ValueAuto)
+ resultMaxZoom = max(resultMinZoom, resultMaxZoom);
+
+ // 2. Constrain zoom value to the [min-zoom, max-zoom] range.
+ if (resultZoom != ViewportDescription::ValueAuto)
+ resultZoom = compareIgnoringAuto(resultMinZoom, compareIgnoringAuto(resultMaxZoom, resultZoom, min), max);
+
+ float extendZoom = compareIgnoringAuto(resultZoom, resultMaxZoom, min);
+
+ // 3. Resolve non-"auto" lengths to pixel lengths.
+ if (extendZoom == ViewportDescription::ValueAuto) {
+ if (resultMaxWidth == ViewportDescription::ValueExtendToZoom)
+ resultMaxWidth = ViewportDescription::ValueAuto;
+
+ if (resultMaxHeight == ViewportDescription::ValueExtendToZoom)
+ resultMaxHeight = ViewportDescription::ValueAuto;
+
+ if (resultMinWidth == ViewportDescription::ValueExtendToZoom)
+ resultMinWidth = resultMaxWidth;
+
+ if (resultMinHeight == ViewportDescription::ValueExtendToZoom)
+ resultMinHeight = resultMaxHeight;
+ } else {
+ float extendWidth = initialViewportSize.width() / extendZoom;
+ float extendHeight = initialViewportSize.height() / extendZoom;
+
+ if (resultMaxWidth == ViewportDescription::ValueExtendToZoom)
+ resultMaxWidth = extendWidth;
+
+ if (resultMaxHeight == ViewportDescription::ValueExtendToZoom)
+ resultMaxHeight = extendHeight;
+
+ if (resultMinWidth == ViewportDescription::ValueExtendToZoom)
+ resultMinWidth = compareIgnoringAuto(extendWidth, resultMaxWidth, max);
+
+ if (resultMinHeight == ViewportDescription::ValueExtendToZoom)
+ resultMinHeight = compareIgnoringAuto(extendHeight, resultMaxHeight, max);
+ }
+
+ // 4. Resolve initial width from min/max descriptors.
+ if (resultMinWidth != ViewportDescription::ValueAuto || resultMaxWidth != ViewportDescription::ValueAuto)
+ resultWidth = compareIgnoringAuto(resultMinWidth, compareIgnoringAuto(resultMaxWidth, initialViewportSize.width(), min), max);
+
+ // 5. Resolve initial height from min/max descriptors.
+ if (resultMinHeight != ViewportDescription::ValueAuto || resultMaxHeight != ViewportDescription::ValueAuto)
+ resultHeight = compareIgnoringAuto(resultMinHeight, compareIgnoringAuto(resultMaxHeight, initialViewportSize.height(), min), max);
+
+ // 6-7. Resolve width value.
+ if (resultWidth == ViewportDescription::ValueAuto) {
+ if (resultHeight == ViewportDescription::ValueAuto || !initialViewportSize.height())
+ resultWidth = initialViewportSize.width();
+ else
+ resultWidth = resultHeight * (initialViewportSize.width() / initialViewportSize.height());
+ }
+
+ // 8. Resolve height value.
+ if (resultHeight == ViewportDescription::ValueAuto) {
+ if (!initialViewportSize.width())
+ resultHeight = initialViewportSize.height();
+ else
+ resultHeight = resultWidth * initialViewportSize.height() / initialViewportSize.width();
+ }
+
+ // Resolve initial-scale value.
+ if (resultZoom == ViewportDescription::ValueAuto) {
+ if (resultWidth != ViewportDescription::ValueAuto && resultWidth > 0)
+ resultZoom = initialViewportSize.width() / resultWidth;
+ if (resultHeight != ViewportDescription::ValueAuto && resultHeight > 0) {
+ // if 'auto', the initial-scale will be negative here and thus ignored.
+ resultZoom = max<float>(resultZoom, initialViewportSize.height() / resultHeight);
+ }
+ }
+
+ // If user-scalable = no, lock the min/max scale to the computed initial
+ // scale.
+ if (!resultUserZoom)
+ resultMinZoom = resultMaxZoom = resultZoom;
+
+ // Only set initialScale to a value if it was explicitly set.
+ if (zoom == ViewportDescription::ValueAuto)
+ resultZoom = ViewportDescription::ValueAuto;
+
+ PageScaleConstraints result;
+ result.minimumScale = resultMinZoom;
+ result.maximumScale = resultMaxZoom;
+ result.initialScale = resultZoom;
+ result.layoutSize.setWidth(resultWidth);
+ result.layoutSize.setHeight(resultHeight);
+ return result;
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/ViewportDescription.h b/chromium/third_party/WebKit/Source/core/dom/ViewportDescription.h
new file mode 100644
index 00000000000..53eed2688f5
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/ViewportDescription.h
@@ -0,0 +1,118 @@
+/*
+ * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
+ * (C) 1999 Antti Koivisto (koivisto@kde.org)
+ * (C) 2001 Dirk Mueller (mueller@kde.org)
+ * (C) 2006 Alexey Proskuryakov (ap@webkit.org)
+ * Copyright (C) 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
+ * Copyright (C) 2008 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
+ * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
+ * Copyright (C) 2012-2013 Intel Corporation. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ */
+
+#ifndef ViewportDescription_h
+#define ViewportDescription_h
+
+#include "core/page/PageScaleConstraints.h"
+#include "platform/Length.h"
+#include "platform/geometry/FloatSize.h"
+
+namespace WebCore {
+
+struct ViewportDescription {
+
+ enum Type {
+ // These are ordered in increasing importance.
+ UserAgentStyleSheet,
+ HandheldFriendlyMeta,
+ MobileOptimizedMeta,
+ ViewportMeta,
+ AuthorStyleSheet
+ } type;
+
+ enum {
+ ValueAuto = -1,
+ ValueDeviceWidth = -2,
+ ValueDeviceHeight = -3,
+ ValuePortrait = -4,
+ ValueLandscape = -5,
+ ValueDeviceDPI = -6,
+ ValueLowDPI = -7,
+ ValueMediumDPI = -8,
+ ValueHighDPI = -9,
+ ValueExtendToZoom = -10
+ };
+
+ ViewportDescription(Type type = UserAgentStyleSheet)
+ : type(type)
+ , zoom(ValueAuto)
+ , minZoom(ValueAuto)
+ , maxZoom(ValueAuto)
+ , userZoom(ValueAuto)
+ , orientation(ValueAuto)
+ , deprecatedTargetDensityDPI(ValueAuto)
+ {
+ }
+
+ // All arguments are in CSS units.
+ PageScaleConstraints resolve(const FloatSize& initialViewportSize) const;
+
+ Length minWidth;
+ Length maxWidth;
+ Length minHeight;
+ Length maxHeight;
+ float zoom;
+ float minZoom;
+ float maxZoom;
+ float userZoom;
+ float orientation;
+ float deprecatedTargetDensityDPI; // Only used for Android WebView
+
+ bool operator==(const ViewportDescription& other) const
+ {
+ // Used for figuring out whether to reset the viewport or not,
+ // thus we are not taking type into account.
+ return minWidth == other.minWidth
+ && maxWidth == other.maxWidth
+ && minHeight == other.minHeight
+ && maxHeight == other.maxHeight
+ && zoom == other.zoom
+ && minZoom == other.minZoom
+ && maxZoom == other.maxZoom
+ && userZoom == other.userZoom
+ && orientation == other.orientation
+ && deprecatedTargetDensityDPI == other.deprecatedTargetDensityDPI;
+ }
+
+ bool operator!=(const ViewportDescription& other) const
+ {
+ return !(*this == other);
+ }
+
+ bool isLegacyViewportType() const { return type >= HandheldFriendlyMeta && type <= ViewportMeta; }
+ bool isMetaViewportType() const { return type == ViewportMeta; }
+ bool isSpecifiedByAuthor() const { return type != UserAgentStyleSheet; }
+
+private:
+ enum Direction { Horizontal, Vertical };
+ static float resolveViewportLength(const Length&, const FloatSize& initialViewportSize, Direction);
+};
+
+} // namespace WebCore
+
+#endif // ViewportDescription_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/VisitedLinkState.cpp b/chromium/third_party/WebKit/Source/core/dom/VisitedLinkState.cpp
index cf1d417025c..f715a3dfeb9 100644
--- a/chromium/third_party/WebKit/Source/core/dom/VisitedLinkState.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/VisitedLinkState.cpp
@@ -30,45 +30,31 @@
#include "core/dom/VisitedLinkState.h"
#include "HTMLNames.h"
+#include "XLinkNames.h"
#include "core/dom/ElementTraversal.h"
#include "core/html/HTMLAnchorElement.h"
-#include "core/page/Page.h"
#include "public/platform/Platform.h"
namespace WebCore {
-using namespace HTMLNames;
-
-inline static const AtomicString& linkAttribute(Element* element)
+static inline const AtomicString& linkAttribute(const Element& element)
{
- ASSERT(element->isLink());
- if (element->isHTMLElement())
- return element->fastGetAttribute(HTMLNames::hrefAttr);
- ASSERT(element->isSVGElement());
- return element->getAttribute(XLinkNames::hrefAttr);
-}
-
-inline static LinkHash linkHashForElement(Document* document, Element* element)
-{
- if (isHTMLAnchorElement(element))
- return toHTMLAnchorElement(element)->visitedLinkHash();
- return visitedLinkHash(document->baseURL(), linkAttribute(element));
+ ASSERT(element.isLink());
+ if (element.isHTMLElement())
+ return element.fastGetAttribute(HTMLNames::hrefAttr);
+ ASSERT(element.isSVGElement());
+ return element.getAttribute(XLinkNames::hrefAttr);
}
-inline static LinkHash linkHashForElementWithAttribute(Document* document, Element* element, const AtomicString& attribute)
+static inline LinkHash linkHashForElement(const Element& element, const AtomicString& attribute = AtomicString())
{
- ASSERT(linkAttribute(element) == attribute);
+ ASSERT(attribute.isNull() || linkAttribute(element) == attribute);
if (isHTMLAnchorElement(element))
- return toHTMLAnchorElement(element)->visitedLinkHash();
- return visitedLinkHash(document->baseURL(), attribute);
+ return toHTMLAnchorElement(element).visitedLinkHash();
+ return visitedLinkHash(element.document().baseURL(), attribute.isNull() ? linkAttribute(element) : attribute);
}
-PassOwnPtr<VisitedLinkState> VisitedLinkState::create(Document* document)
-{
- return adoptPtr(new VisitedLinkState(document));
-}
-
-VisitedLinkState::VisitedLinkState(Document* document)
+VisitedLinkState::VisitedLinkState(const Document& document)
: m_document(document)
{
}
@@ -77,7 +63,7 @@ void VisitedLinkState::invalidateStyleForAllLinks()
{
if (m_linksCheckedForVisitedState.isEmpty())
return;
- for (Element* element = ElementTraversal::firstWithin(m_document); element; element = ElementTraversal::next(element)) {
+ for (Element* element = ElementTraversal::firstWithin(m_document); element; element = ElementTraversal::next(*element)) {
if (element->isLink())
element->setNeedsStyleRecalc();
}
@@ -87,15 +73,17 @@ void VisitedLinkState::invalidateStyleForLink(LinkHash linkHash)
{
if (!m_linksCheckedForVisitedState.contains(linkHash))
return;
- for (Element* element = ElementTraversal::firstWithin(m_document); element; element = ElementTraversal::next(element)) {
- if (element->isLink() && linkHashForElement(m_document, element) == linkHash)
+ for (Element* element = ElementTraversal::firstWithin(m_document); element; element = ElementTraversal::next(*element)) {
+ if (element->isLink() && linkHashForElement(*element) == linkHash)
element->setNeedsStyleRecalc();
}
}
-EInsideLink VisitedLinkState::determineLinkStateSlowCase(Element* element)
+EInsideLink VisitedLinkState::determineLinkStateSlowCase(const Element& element)
{
- ASSERT(element->isLink());
+ ASSERT(element.isLink());
+ ASSERT(m_document.isActive());
+ ASSERT(m_document == element.document());
const AtomicString& attribute = linkAttribute(element);
@@ -109,18 +97,13 @@ EInsideLink VisitedLinkState::determineLinkStateSlowCase(Element* element)
if (attribute.isEmpty())
return InsideVisitedLink;
- // We null check the Frame here to avoid canonicalizing and hashing
- // URLs in documents that aren't attached to Frames (like documents
- // from XMLHttpRequest).
- if (!m_document->frame())
- return InsideUnvisitedLink;
-
- LinkHash hash = linkHashForElementWithAttribute(m_document, element, attribute);
- if (!hash)
- return InsideUnvisitedLink;
+ if (LinkHash hash = linkHashForElement(element, attribute)) {
+ m_linksCheckedForVisitedState.add(hash);
+ if (blink::Platform::current()->isLinkVisited(hash))
+ return InsideVisitedLink;
+ }
- m_linksCheckedForVisitedState.add(hash);
- return WebKit::Platform::current()->isLinkVisited(hash) ? InsideVisitedLink : InsideUnvisitedLink;
+ return InsideUnvisitedLink;
}
}
diff --git a/chromium/third_party/WebKit/Source/core/dom/VisitedLinkState.h b/chromium/third_party/WebKit/Source/core/dom/VisitedLinkState.h
index 552e22204fc..1f8ab64752b 100644
--- a/chromium/third_party/WebKit/Source/core/dom/VisitedLinkState.h
+++ b/chromium/third_party/WebKit/Source/core/dom/VisitedLinkState.h
@@ -29,10 +29,9 @@
#ifndef VisitedLinkState_h
#define VisitedLinkState_h
-#include "XLinkNames.h"
#include "core/dom/Element.h"
-#include "core/platform/LinkHash.h"
#include "core/rendering/style/RenderStyleConstants.h"
+#include "platform/LinkHash.h"
#include "wtf/HashSet.h"
namespace WebCore {
@@ -42,28 +41,30 @@ class Document;
class VisitedLinkState {
WTF_MAKE_FAST_ALLOCATED;
public:
- static PassOwnPtr<VisitedLinkState> create(Document*);
+ static PassOwnPtr<VisitedLinkState> create(const Document& document)
+ {
+ return adoptPtr(new VisitedLinkState(document));
+ }
void invalidateStyleForAllLinks();
void invalidateStyleForLink(LinkHash);
- EInsideLink determineLinkState(Element*);
+
+ EInsideLink determineLinkState(const Element& element)
+ {
+ if (element.isLink())
+ return determineLinkStateSlowCase(element);
+ return NotInsideLink;
+ }
private:
- explicit VisitedLinkState(Document*);
+ explicit VisitedLinkState(const Document&);
- EInsideLink determineLinkStateSlowCase(Element*);
+ EInsideLink determineLinkStateSlowCase(const Element&);
- Document* m_document;
+ const Document& m_document;
HashSet<LinkHash, LinkHashHash> m_linksCheckedForVisitedState;
};
-inline EInsideLink VisitedLinkState::determineLinkState(Element* element)
-{
- if (!element || !element->isLink())
- return NotInsideLink;
- return determineLinkStateSlowCase(element);
-}
-
}
#endif
diff --git a/chromium/third_party/WebKit/Source/core/dom/WebKitAnimationEvent.cpp b/chromium/third_party/WebKit/Source/core/dom/WebKitAnimationEvent.cpp
deleted file mode 100644
index 777a5a4d373..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/WebKitAnimationEvent.cpp
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * Copyright (C) 2007, 2008 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/dom/WebKitAnimationEvent.h"
-
-#include "core/dom/EventNames.h"
-
-namespace WebCore {
-
-WebKitAnimationEventInit::WebKitAnimationEventInit()
- : animationName()
- , elapsedTime(0.0)
-{
-}
-
-WebKitAnimationEvent::WebKitAnimationEvent()
- : m_elapsedTime(0.0)
-{
- ScriptWrappable::init(this);
-}
-
-WebKitAnimationEvent::WebKitAnimationEvent(const AtomicString& type, const WebKitAnimationEventInit& initializer)
- : Event(type, initializer)
- , m_animationName(initializer.animationName)
- , m_elapsedTime(initializer.elapsedTime)
-{
- ScriptWrappable::init(this);
-}
-
-WebKitAnimationEvent::WebKitAnimationEvent(const AtomicString& type, const String& animationName, double elapsedTime)
- : Event(type, true, true)
- , m_animationName(animationName)
- , m_elapsedTime(elapsedTime)
-{
- ScriptWrappable::init(this);
-}
-
-WebKitAnimationEvent::~WebKitAnimationEvent()
-{
-}
-
-const String& WebKitAnimationEvent::animationName() const
-{
- return m_animationName;
-}
-
-double WebKitAnimationEvent::elapsedTime() const
-{
- return m_elapsedTime;
-}
-
-const AtomicString& WebKitAnimationEvent::interfaceName() const
-{
- return eventNames().interfaceForWebKitAnimationEvent;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/WebKitAnimationEvent.h b/chromium/third_party/WebKit/Source/core/dom/WebKitAnimationEvent.h
deleted file mode 100644
index 8f642bfcd6c..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/WebKitAnimationEvent.h
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * Copyright (C) 2007, 2008 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef WebKitAnimationEvent_h
-#define WebKitAnimationEvent_h
-
-#include "core/dom/Event.h"
-
-namespace WebCore {
-
-// FIXME : This class has a WebKit prefix on purpose so we can use the EventAliases system. When the
-// runtime flag of unprefixed animation will be removed we can rename that class and do the same as
-// the CSS Transitions.
-struct WebKitAnimationEventInit : public EventInit {
- WebKitAnimationEventInit();
-
- String animationName;
- double elapsedTime;
-};
-
-class WebKitAnimationEvent : public Event {
-public:
- static PassRefPtr<WebKitAnimationEvent> create()
- {
- return adoptRef(new WebKitAnimationEvent);
- }
- static PassRefPtr<WebKitAnimationEvent> create(const AtomicString& type, const String& animationName, double elapsedTime)
- {
- return adoptRef(new WebKitAnimationEvent(type, animationName, elapsedTime));
- }
- static PassRefPtr<WebKitAnimationEvent> create(const AtomicString& type, const WebKitAnimationEventInit& initializer)
- {
- return adoptRef(new WebKitAnimationEvent(type, initializer));
- }
-
- virtual ~WebKitAnimationEvent();
-
- const String& animationName() const;
- double elapsedTime() const;
-
- virtual const AtomicString& interfaceName() const;
-
-private:
- WebKitAnimationEvent();
- WebKitAnimationEvent(const AtomicString& type, const String& animationName, double elapsedTime);
- WebKitAnimationEvent(const AtomicString&, const WebKitAnimationEventInit&);
-
- String m_animationName;
- double m_elapsedTime;
-};
-
-} // namespace WebCore
-
-#endif // WebKitAnimationEvent_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/WebKitAnimationEvent.idl b/chromium/third_party/WebKit/Source/core/dom/WebKitAnimationEvent.idl
deleted file mode 100644
index a16830613f6..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/WebKitAnimationEvent.idl
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright (C) 2007, 2008 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-[
- ConstructorTemplate=Event
-] interface WebKitAnimationEvent : Event {
- [InitializedByEventConstructor] readonly attribute DOMString animationName;
- [InitializedByEventConstructor] readonly attribute double elapsedTime;
-};
-
diff --git a/chromium/third_party/WebKit/Source/core/dom/WebKitNamedFlow.idl b/chromium/third_party/WebKit/Source/core/dom/WebKitNamedFlow.idl
index 33cff659a3c..800e26d9b08 100644
--- a/chromium/third_party/WebKit/Source/core/dom/WebKitNamedFlow.idl
+++ b/chromium/third_party/WebKit/Source/core/dom/WebKitNamedFlow.idl
@@ -28,10 +28,10 @@
*/
[
- NoInterfaceObject,
- EnabledAtRuntime=CSSRegions,
+ GenerateVisitDOMWrapper=ownerNode,
ImplementedAs=NamedFlow,
- GenerateIsReachable=ownerNode
+ NoInterfaceObject,
+ RuntimeEnabled=CSSRegions,
] interface WebKitNamedFlow : EventTarget {
readonly attribute DOMString name;
readonly attribute boolean overset;
diff --git a/chromium/third_party/WebKit/Source/core/dom/WebKitNamedFlowCollection.idl b/chromium/third_party/WebKit/Source/core/dom/WebKitNamedFlowCollection.idl
index 92aec8e92c6..4744e069746 100644
--- a/chromium/third_party/WebKit/Source/core/dom/WebKitNamedFlowCollection.idl
+++ b/chromium/third_party/WebKit/Source/core/dom/WebKitNamedFlowCollection.idl
@@ -29,7 +29,7 @@
[
NoInterfaceObject,
- EnabledAtRuntime=CSSRegions,
+ RuntimeEnabled=CSSRegions,
ImplementedAs=DOMNamedFlowCollection
] interface WebKitNamedFlowCollection {
readonly attribute unsigned long length;
diff --git a/chromium/third_party/WebKit/Source/core/dom/WheelController.cpp b/chromium/third_party/WebKit/Source/core/dom/WheelController.cpp
index 48c14a78aa7..68d5b18b2e5 100644
--- a/chromium/third_party/WebKit/Source/core/dom/WheelController.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/WheelController.cpp
@@ -27,9 +27,9 @@
#include "core/dom/WheelController.h"
#include "core/dom/Document.h"
-#include "core/dom/EventNames.h"
-#include "core/dom/WheelEvent.h"
-#include "core/page/Frame.h"
+#include "core/events/ThreadLocalEventNames.h"
+#include "core/events/WheelEvent.h"
+#include "core/frame/Frame.h"
#include "core/page/Page.h"
#include "core/page/scrolling/ScrollingCoordinator.h"
@@ -52,10 +52,10 @@ const char* WheelController::supplementName()
WheelController* WheelController::from(Document* document)
{
- WheelController* controller = static_cast<WheelController*>(Supplement<ScriptExecutionContext>::from(document, supplementName()));
+ WheelController* controller = static_cast<WheelController*>(DocumentSupplement::from(document, supplementName()));
if (!controller) {
controller = new WheelController(document);
- Supplement<ScriptExecutionContext>::provideTo(document, supplementName(), adoptPtr(controller));
+ DocumentSupplement::provideTo(document, supplementName(), adoptPtr(controller));
}
return controller;
}
@@ -102,7 +102,7 @@ void WheelController::didRemoveWheelEventHandler(Document* document)
void WheelController::didAddEventListener(DOMWindow* window, const AtomicString& eventType)
{
- if (eventType != eventNames().wheelEvent && eventType != eventNames().mousewheelEvent)
+ if (eventType != EventTypeNames::wheel && eventType != EventTypeNames::mousewheel)
return;
Document* document = window->document();
@@ -111,7 +111,7 @@ void WheelController::didAddEventListener(DOMWindow* window, const AtomicString&
void WheelController::didRemoveEventListener(DOMWindow* window, const AtomicString& eventType)
{
- if (eventType != eventNames().wheelEvent && eventType != eventNames().mousewheelEvent)
+ if (eventType != EventTypeNames::wheel && eventType != EventTypeNames::mousewheel)
return;
Document* document = window->document();
diff --git a/chromium/third_party/WebKit/Source/core/dom/WheelController.h b/chromium/third_party/WebKit/Source/core/dom/WheelController.h
index 13406ee0c66..550cb09a3c0 100644
--- a/chromium/third_party/WebKit/Source/core/dom/WheelController.h
+++ b/chromium/third_party/WebKit/Source/core/dom/WheelController.h
@@ -26,15 +26,16 @@
#ifndef WheelController_h
#define WheelController_h
-#include "core/dom/Event.h"
-#include "core/page/DOMWindowLifecycleObserver.h"
-#include "core/platform/Supplementable.h"
+#include "core/dom/DocumentSupplementable.h"
+#include "core/events/Event.h"
+#include "core/frame/DOMWindowLifecycleObserver.h"
+
namespace WebCore {
class DOMWindow;
-class WheelController : public Supplement<ScriptExecutionContext>, public DOMWindowLifecycleObserver {
+class WheelController : public DocumentSupplement, public DOMWindowLifecycleObserver {
public:
virtual ~WheelController();
diff --git a/chromium/third_party/WebKit/Source/core/dom/WheelEvent.cpp b/chromium/third_party/WebKit/Source/core/dom/WheelEvent.cpp
deleted file mode 100644
index f2b71f6c848..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/WheelEvent.cpp
+++ /dev/null
@@ -1,155 +0,0 @@
-/*
- * Copyright (C) 2001 Peter Kelly (pmk@post.com)
- * Copyright (C) 2001 Tobias Anton (anton@stud.fbi.fh-darmstadt.de)
- * Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
- * Copyright (C) 2003, 2005, 2006, 2008, 2010 Apple Inc. All rights reserved.
- * Copyright (C) 2013 Samsung Electronics. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-#include "core/dom/WheelEvent.h"
-
-#include "core/dom/Clipboard.h"
-#include "core/dom/EventNames.h"
-#include "core/platform/PlatformWheelEvent.h"
-
-namespace WebCore {
-
-WheelEventInit::WheelEventInit()
- : deltaX(0)
- , deltaY(0)
- , deltaZ(0)
- , wheelDeltaX(0)
- , wheelDeltaY(0)
- , deltaMode(WheelEvent::DOM_DELTA_PIXEL)
-{
-}
-
-WheelEvent::WheelEvent()
- : m_deltaX(0)
- , m_deltaY(0)
- , m_deltaZ(0)
- , m_deltaMode(DOM_DELTA_PIXEL)
- , m_directionInvertedFromDevice(false)
-{
- ScriptWrappable::init(this);
-}
-
-WheelEvent::WheelEvent(const AtomicString& type, const WheelEventInit& initializer)
- : MouseEvent(type, initializer)
- , m_wheelDelta(initializer.wheelDeltaX ? initializer.wheelDeltaX : -initializer.deltaX, initializer.wheelDeltaY ? initializer.wheelDeltaY : -initializer.deltaY)
- , m_deltaX(initializer.deltaX ? initializer.deltaX : -initializer.wheelDeltaX)
- , m_deltaY(initializer.deltaY ? initializer.deltaY : -initializer.wheelDeltaY)
- , m_deltaZ(initializer.deltaZ)
- , m_deltaMode(initializer.deltaMode)
-{
- ScriptWrappable::init(this);
-}
-
-WheelEvent::WheelEvent(const FloatPoint& wheelTicks, const FloatPoint& rawDelta, unsigned deltaMode,
- PassRefPtr<AbstractView> view, const IntPoint& screenLocation, const IntPoint& pageLocation,
- bool ctrlKey, bool altKey, bool shiftKey, bool metaKey, bool directionInvertedFromDevice)
- : MouseEvent(eventNames().wheelEvent,
- true, true, view, 0, screenLocation.x(), screenLocation.y(),
- pageLocation.x(), pageLocation.y(),
- 0, 0,
- ctrlKey, altKey, shiftKey, metaKey, 0, 0, 0, false)
- , m_wheelDelta(wheelTicks.x() * TickMultiplier, wheelTicks.y() * TickMultiplier)
- , m_deltaX(-rawDelta.x())
- , m_deltaY(-rawDelta.y())
- , m_deltaZ(0)
- , m_deltaMode(deltaMode)
- , m_directionInvertedFromDevice(directionInvertedFromDevice)
-{
- ScriptWrappable::init(this);
-}
-
-void WheelEvent::initWheelEvent(int rawDeltaX, int rawDeltaY, PassRefPtr<AbstractView> view,
- int screenX, int screenY, int pageX, int pageY,
- bool ctrlKey, bool altKey, bool shiftKey, bool metaKey)
-{
- if (dispatched())
- return;
-
- initUIEvent(eventNames().wheelEvent, true, true, view, 0);
-
- m_screenLocation = IntPoint(screenX, screenY);
- m_ctrlKey = ctrlKey;
- m_altKey = altKey;
- m_shiftKey = shiftKey;
- m_metaKey = metaKey;
-
- m_wheelDelta = IntPoint(rawDeltaX * TickMultiplier, rawDeltaY * TickMultiplier);
- m_deltaX = -rawDeltaX;
- m_deltaY = -rawDeltaY;
- m_deltaMode = DOM_DELTA_PIXEL;
- m_directionInvertedFromDevice = false;
-
- initCoordinates(IntPoint(pageX, pageY));
-}
-
-void WheelEvent::initWebKitWheelEvent(int rawDeltaX, int rawDeltaY, PassRefPtr<AbstractView> view,
- int screenX, int screenY, int pageX, int pageY,
- bool ctrlKey, bool altKey, bool shiftKey, bool metaKey)
-{
- initWheelEvent(rawDeltaX, rawDeltaY, view, screenX, screenY, pageX, pageY,
- ctrlKey, altKey, shiftKey, metaKey);
-}
-
-const AtomicString& WheelEvent::interfaceName() const
-{
- return eventNames().interfaceForWheelEvent;
-}
-
-bool WheelEvent::isMouseEvent() const
-{
- return false;
-}
-
-inline static unsigned deltaMode(const PlatformWheelEvent& event)
-{
- return event.granularity() == ScrollByPageWheelEvent ? WheelEvent::DOM_DELTA_PAGE : WheelEvent::DOM_DELTA_PIXEL;
-}
-
-PassRefPtr<WheelEventDispatchMediator> WheelEventDispatchMediator::create(const PlatformWheelEvent& event, PassRefPtr<AbstractView> view)
-{
- return adoptRef(new WheelEventDispatchMediator(event, view));
-}
-
-WheelEventDispatchMediator::WheelEventDispatchMediator(const PlatformWheelEvent& event, PassRefPtr<AbstractView> view)
-{
- if (!(event.deltaX() || event.deltaY()))
- return;
-
- setEvent(WheelEvent::create(FloatPoint(event.wheelTicksX(), event.wheelTicksY()), FloatPoint(event.deltaX(), event.deltaY()),
- deltaMode(event), view, event.globalPosition(), event.position(),
- event.ctrlKey(), event.altKey(), event.shiftKey(), event.metaKey(), event.directionInvertedFromDevice()));
-}
-
-WheelEvent* WheelEventDispatchMediator::event() const
-{
- return static_cast<WheelEvent*>(EventDispatchMediator::event());
-}
-
-bool WheelEventDispatchMediator::dispatchEvent(EventDispatcher* dispatcher) const
-{
- ASSERT(event());
- return EventDispatchMediator::dispatchEvent(dispatcher) && !event()->defaultHandled();
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/WheelEvent.h b/chromium/third_party/WebKit/Source/core/dom/WheelEvent.h
deleted file mode 100644
index c393f373b15..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/WheelEvent.h
+++ /dev/null
@@ -1,125 +0,0 @@
-/*
- * Copyright (C) 2001 Peter Kelly (pmk@post.com)
- * Copyright (C) 2001 Tobias Anton (anton@stud.fbi.fh-darmstadt.de)
- * Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
- * Copyright (C) 2003, 2004, 2005, 2006, 2008, 2010 Apple Inc. All rights reserved.
- * Copyright (C) 2013 Samsung Electronics. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#ifndef WheelEvent_h
-#define WheelEvent_h
-
-#include "core/dom/EventDispatchMediator.h"
-#include "core/dom/MouseEvent.h"
-#include "core/platform/graphics/FloatPoint.h"
-
-namespace WebCore {
-
-class PlatformWheelEvent;
-
-struct WheelEventInit : public MouseEventInit {
- WheelEventInit();
-
- double deltaX;
- double deltaY;
- double deltaZ;
- int wheelDeltaX; // Deprecated.
- int wheelDeltaY; // Deprecated.
- unsigned deltaMode;
-};
-
-class WheelEvent : public MouseEvent {
-public:
- enum { TickMultiplier = 120 };
-
- enum DeltaMode {
- DOM_DELTA_PIXEL = 0,
- DOM_DELTA_LINE,
- DOM_DELTA_PAGE
- };
-
- static PassRefPtr<WheelEvent> create()
- {
- return adoptRef(new WheelEvent);
- }
-
- static PassRefPtr<WheelEvent> create(const AtomicString& type, const WheelEventInit& initializer)
- {
- return adoptRef(new WheelEvent(type, initializer));
- }
-
- static PassRefPtr<WheelEvent> create(const FloatPoint& wheelTicks,
- const FloatPoint& rawDelta, unsigned deltaMode, PassRefPtr<AbstractView> view,
- const IntPoint& screenLocation, const IntPoint& pageLocation,
- bool ctrlKey, bool altKey, bool shiftKey, bool metaKey, bool directionInvertedFromDevice)
- {
- return adoptRef(new WheelEvent(wheelTicks, rawDelta, deltaMode, view,
- screenLocation, pageLocation, ctrlKey, altKey, shiftKey, metaKey, directionInvertedFromDevice));
- }
-
- void initWheelEvent(int rawDeltaX, int rawDeltaY, PassRefPtr<AbstractView>,
- int screenX, int screenY, int pageX, int pageY,
- bool ctrlKey, bool altKey, bool shiftKey, bool metaKey);
-
- void initWebKitWheelEvent(int rawDeltaX, int rawDeltaY, PassRefPtr<AbstractView>,
- int screenX, int screenY, int pageX, int pageY,
- bool ctrlKey, bool altKey, bool shiftKey, bool metaKey);
-
- double deltaX() const { return m_deltaX; } // Positive when scrolling right.
- double deltaY() const { return m_deltaY; } // Positive when scrolling down.
- double deltaZ() const { return m_deltaZ; }
- int wheelDelta() const { return wheelDeltaY() ? wheelDeltaY() : wheelDeltaX(); } // Deprecated.
- int wheelDeltaX() const { return m_wheelDelta.x(); } // Deprecated, negative when scrolling right.
- int wheelDeltaY() const { return m_wheelDelta.y(); } // Deprecated, negative when scrolling down.
- unsigned deltaMode() const { return m_deltaMode; }
- float ticksX() const { return static_cast<float>(m_wheelDelta.x()) / TickMultiplier; }
- float ticksY() const { return static_cast<float>(m_wheelDelta.y()) / TickMultiplier; }
-
- bool webkitDirectionInvertedFromDevice() const { return m_directionInvertedFromDevice; }
-
- virtual const AtomicString& interfaceName() const;
- virtual bool isMouseEvent() const;
-
-private:
- WheelEvent();
- WheelEvent(const AtomicString&, const WheelEventInit&);
- WheelEvent(const FloatPoint& wheelTicks, const FloatPoint& rawDelta,
- unsigned, PassRefPtr<AbstractView>, const IntPoint& screenLocation, const IntPoint& pageLocation,
- bool ctrlKey, bool altKey, bool shiftKey, bool metaKey, bool directionInvertedFromDevice);
-
- IntPoint m_wheelDelta;
- double m_deltaX;
- double m_deltaY;
- double m_deltaZ;
- unsigned m_deltaMode;
- bool m_directionInvertedFromDevice;
-};
-
-class WheelEventDispatchMediator : public EventDispatchMediator {
-public:
- static PassRefPtr<WheelEventDispatchMediator> create(const PlatformWheelEvent&, PassRefPtr<AbstractView>);
-private:
- WheelEventDispatchMediator(const PlatformWheelEvent&, PassRefPtr<AbstractView>);
- WheelEvent* event() const;
- virtual bool dispatchEvent(EventDispatcher*) const OVERRIDE;
-};
-
-} // namespace WebCore
-
-#endif // WheelEvent_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/WheelEvent.idl b/chromium/third_party/WebKit/Source/core/dom/WheelEvent.idl
deleted file mode 100644
index 8ee63ae3056..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/WheelEvent.idl
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Copyright (C) 2006, 2007, 2010 Apple Inc. All rights reserved.
- * Copyright (C) 2006 Samuel Weinig <sam.weinig@gmail.com>
- * Copyright (C) 2013 Samsung Electronics. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-// Introduced in DOM Level 3:
-[
- ConstructorTemplate=Event
-] interface WheelEvent : MouseEvent {
- // DeltaModeCode
- const unsigned long DOM_DELTA_PIXEL = 0x00;
- const unsigned long DOM_DELTA_LINE = 0x01;
- const unsigned long DOM_DELTA_PAGE = 0x02;
-
- [InitializedByEventConstructor] readonly attribute double deltaX;
- [InitializedByEventConstructor] readonly attribute double deltaY;
- [InitializedByEventConstructor] readonly attribute double deltaZ;
- [InitializedByEventConstructor] readonly attribute unsigned long deltaMode;
-
- // Non standard API.
- [InitializedByEventConstructor] readonly attribute long wheelDeltaX;
- [InitializedByEventConstructor] readonly attribute long wheelDeltaY;
- readonly attribute long wheelDelta;
-
- // WebKit Extension
- readonly attribute boolean webkitDirectionInvertedFromDevice;
-
- void initWebKitWheelEvent([Default=Undefined] optional long wheelDeltaX,
- [Default=Undefined] optional long wheelDeltaY,
- [Default=Undefined] optional Window view,
- [Default=Undefined] optional long screenX,
- [Default=Undefined] optional long screenY,
- [Default=Undefined] optional long clientX,
- [Default=Undefined] optional long clientY,
- [Default=Undefined] optional boolean ctrlKey,
- [Default=Undefined] optional boolean altKey,
- [Default=Undefined] optional boolean shiftKey,
- [Default=Undefined] optional boolean metaKey);
-};
diff --git a/chromium/third_party/WebKit/Source/core/dom/WhitespaceChildList.h b/chromium/third_party/WebKit/Source/core/dom/WhitespaceChildList.h
deleted file mode 100644
index b5a4fb14f65..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/WhitespaceChildList.h
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef WhitespaceChildList_h
-#define WhitespaceChildList_h
-
-#include "core/dom/Text.h"
-#include "core/rendering/style/RenderStyleConstants.h"
-
-namespace WebCore {
-
-class Text;
-
-// Tracks a limited number of whitespace text children during style recalc
-// to postpone their style recalc as part of optimization to avoid creating
-// unnecessary whitespace text renderers. If we hit the limit, it recalcs
-// the whitespace text's style and clears the list.
-class WhitespaceChildList {
-public:
- WhitespaceChildList(StyleRecalcChange change)
- : m_change(change)
- { }
-
- void append(Text* textChild)
- {
- ASSERT(textChild->containsOnlyWhitespace());
- if (m_list.size() == maxWhitespaceChildrenToDefer) {
- recalcStyle();
- m_list.clear();
- }
- m_list.append(textChild);
- }
-
- void recalcStyle() const
- {
- for (unsigned i = 0; i < m_list.size(); ++i)
- m_list[i]->recalcTextStyle(m_change);
- }
-private:
- StyleRecalcChange m_change;
-
- static const unsigned maxWhitespaceChildrenToDefer = 10;
- Vector<Text*, maxWhitespaceChildrenToDefer> m_list;
-};
-
-} // namespace WebCore
-
-#endif // WhitespaceChildList_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/WindowEventContext.cpp b/chromium/third_party/WebKit/Source/core/dom/WindowEventContext.cpp
deleted file mode 100644
index b9cbaa988cb..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/WindowEventContext.cpp
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-#include "config.h"
-#include "core/dom/WindowEventContext.h"
-
-#include "core/dom/Document.h"
-#include "core/dom/Event.h"
-#include "core/dom/EventContext.h"
-#include "core/dom/Node.h"
-#include "core/page/DOMWindow.h"
-
-namespace WebCore {
-
-WindowEventContext::WindowEventContext(Event* event, PassRefPtr<Node> node, const EventContext* topEventContext)
-{
- // We don't dispatch load events to the window. This quirk was originally
- // added because Mozilla doesn't propagate load events to the window object.
- if (event->type() == eventNames().loadEvent)
- return;
-
- Node* topLevelContainer = topEventContext ? topEventContext->node() : node.get();
- if (!topLevelContainer->isDocumentNode())
- return;
-
- m_window = toDocument(topLevelContainer)->domWindow();
- m_target = topEventContext ? topEventContext->target() : node.get();
-}
-
-bool WindowEventContext::handleLocalEvents(Event* event)
-{
- if (!m_window)
- return false;
-
- event->setTarget(target());
- event->setCurrentTarget(window());
- m_window->fireEventListeners(event);
- return true;
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/dom/custom/CustomElement.cpp b/chromium/third_party/WebKit/Source/core/dom/custom/CustomElement.cpp
new file mode 100644
index 00000000000..0dc1683ca39
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/custom/CustomElement.cpp
@@ -0,0 +1,166 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * 3. Neither the name of Google Inc. nor the names of its contributors
+ * may be used to endorse or promote products derived from this
+ * software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/dom/custom/CustomElement.h"
+
+#include "HTMLNames.h"
+#include "MathMLNames.h"
+#include "RuntimeEnabledFeatures.h"
+#include "SVGNames.h"
+#include "core/dom/Element.h"
+#include "core/dom/custom/CustomElementCallbackScheduler.h"
+#include "core/dom/custom/CustomElementObserver.h"
+
+namespace WebCore {
+
+Vector<AtomicString>& CustomElement::embedderCustomElementNames()
+{
+ DEFINE_STATIC_LOCAL(Vector<AtomicString>, names, ());
+ return names;
+}
+
+void CustomElement::addEmbedderCustomElementName(const AtomicString& name)
+{
+ AtomicString lower = name.lower();
+ if (isValidName(lower, EmbedderNames))
+ return;
+ embedderCustomElementNames().append(lower);
+}
+
+static CustomElement::NameSet enabledNameSet()
+{
+ return CustomElement::NameSet((RuntimeEnabledFeatures::customElementsEnabled() ? CustomElement::StandardNames : 0) | (RuntimeEnabledFeatures::embedderCustomElementsEnabled() ? CustomElement::EmbedderNames : 0));
+}
+
+bool CustomElement::isValidName(const AtomicString& name, NameSet validNames)
+{
+ validNames = NameSet(validNames & enabledNameSet());
+
+ if ((validNames & EmbedderNames) && kNotFound != embedderCustomElementNames().find(name))
+ return Document::isValidName(name);
+
+ if ((validNames & StandardNames) && kNotFound != name.find('-')) {
+ DEFINE_STATIC_LOCAL(Vector<AtomicString>, reservedNames, ());
+ if (reservedNames.isEmpty()) {
+ reservedNames.append(MathMLNames::annotation_xmlTag.localName());
+ // In principle, "color-profile" should exist in the SVGNames
+ // namespace, but we don't implement the color-profile element.
+ reservedNames.append("color-profile");
+ reservedNames.append(SVGNames::font_faceTag.localName());
+ reservedNames.append(SVGNames::font_face_srcTag.localName());
+ reservedNames.append(SVGNames::font_face_uriTag.localName());
+ reservedNames.append(SVGNames::font_face_formatTag.localName());
+ reservedNames.append(SVGNames::font_face_nameTag.localName());
+ reservedNames.append(SVGNames::missing_glyphTag.localName());
+ }
+
+ if (kNotFound == reservedNames.find(name))
+ return Document::isValidName(name.string());
+ }
+
+ return false;
+}
+
+void CustomElement::define(Element* element, PassRefPtr<CustomElementDefinition> passDefinition)
+{
+ RefPtr<CustomElementDefinition> definition(passDefinition);
+
+ switch (element->customElementState()) {
+ case Element::NotCustomElement:
+ case Element::Upgraded:
+ ASSERT_NOT_REACHED();
+ break;
+
+ case Element::WaitingForUpgrade:
+ definitions().add(element, definition);
+ CustomElementCallbackScheduler::scheduleCreatedCallback(definition->callbacks(), element);
+ break;
+ }
+}
+
+CustomElementDefinition* CustomElement::definitionFor(Element* element)
+{
+ CustomElementDefinition* definition = definitions().get(element);
+ ASSERT(definition);
+ return definition;
+}
+
+void CustomElement::attributeDidChange(Element* element, const AtomicString& name, const AtomicString& oldValue, const AtomicString& newValue)
+{
+ ASSERT(element->customElementState() == Element::Upgraded);
+ CustomElementCallbackScheduler::scheduleAttributeChangedCallback(definitionFor(element)->callbacks(), element, name, oldValue, newValue);
+}
+
+void CustomElement::didEnterDocument(Element* element, const Document& document)
+{
+ ASSERT(element->customElementState() == Element::Upgraded);
+ if (!document.domWindow())
+ return;
+ CustomElementCallbackScheduler::scheduleAttachedCallback(definitionFor(element)->callbacks(), element);
+}
+
+void CustomElement::didLeaveDocument(Element* element, const Document& document)
+{
+ ASSERT(element->customElementState() == Element::Upgraded);
+ if (!document.domWindow())
+ return;
+ CustomElementCallbackScheduler::scheduleDetachedCallback(definitionFor(element)->callbacks(), element);
+}
+
+void CustomElement::wasDestroyed(Element* element)
+{
+ switch (element->customElementState()) {
+ case Element::NotCustomElement:
+ ASSERT_NOT_REACHED();
+ break;
+
+ case Element::WaitingForUpgrade:
+ case Element::Upgraded:
+ definitions().remove(element);
+ CustomElementObserver::notifyElementWasDestroyed(element);
+ break;
+ }
+}
+
+void CustomElement::DefinitionMap::add(Element* element, PassRefPtr<CustomElementDefinition> definition)
+{
+ ASSERT(definition.get());
+ DefinitionMap::ElementDefinitionHashMap::AddResult result = m_definitions.add(element, definition);
+ ASSERT_UNUSED(result, result.isNewEntry);
+}
+
+CustomElement::DefinitionMap& CustomElement::definitions()
+{
+ DEFINE_STATIC_LOCAL(DefinitionMap, map, ());
+ return map;
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/custom/CustomElement.h b/chromium/third_party/WebKit/Source/core/dom/custom/CustomElement.h
new file mode 100644
index 00000000000..c50bc0804e4
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/custom/CustomElement.h
@@ -0,0 +1,97 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * 3. Neither the name of Google Inc. nor the names of its contributors
+ * may be used to endorse or promote products derived from this
+ * software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef CustomElement_h
+#define CustomElement_h
+
+#include "core/dom/custom/CustomElementDefinition.h"
+#include "wtf/HashMap.h"
+#include "wtf/Noncopyable.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefPtr.h"
+#include "wtf/Vector.h"
+#include "wtf/text/AtomicString.h"
+
+namespace WebCore {
+
+class Document;
+class Element;
+
+class CustomElement {
+public:
+ enum NameSet {
+ EmbedderNames = 1 << 0,
+ StandardNames = 1 << 1,
+ AllNames = EmbedderNames | StandardNames
+ };
+ static bool isValidName(const AtomicString& name, NameSet validNames = AllNames);
+ static void addEmbedderCustomElementName(const AtomicString& name);
+
+ // API for registration contexts
+ static void define(Element*, PassRefPtr<CustomElementDefinition>);
+
+ // API for wrapper creation, which uses a definition as a key
+ static CustomElementDefinition* definitionFor(Element*);
+
+ // API for Element to kick off changes
+
+ static void didFinishParsingChildren(Element*);
+ static void attributeDidChange(Element*, const AtomicString& name, const AtomicString& oldValue, const AtomicString& newValue);
+ static void didEnterDocument(Element*, const Document&);
+ static void didLeaveDocument(Element*, const Document&);
+ static void wasDestroyed(Element*);
+
+private:
+ CustomElement();
+
+ static Vector<AtomicString>& embedderCustomElementNames();
+
+ // Maps resolved elements to their definitions
+
+ class DefinitionMap {
+ WTF_MAKE_NONCOPYABLE(DefinitionMap);
+ public:
+ DefinitionMap() { }
+ ~DefinitionMap() { }
+
+ void add(Element*, PassRefPtr<CustomElementDefinition>);
+ void remove(Element* element) { m_definitions.remove(element); }
+ CustomElementDefinition* get(Element* element) const { return m_definitions.get(element); }
+
+ private:
+ typedef HashMap<Element*, RefPtr<CustomElementDefinition> > ElementDefinitionHashMap;
+ ElementDefinitionHashMap m_definitions;
+ };
+ static DefinitionMap& definitions();
+};
+
+}
+
+#endif // CustomElement_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementBaseElementQueue.cpp b/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementBaseElementQueue.cpp
new file mode 100644
index 00000000000..0e8561da12e
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementBaseElementQueue.cpp
@@ -0,0 +1,64 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * 3. Neither the name of Google Inc. nor the names of its contributors
+ * may be used to endorse or promote products derived from this
+ * software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/dom/custom/CustomElementBaseElementQueue.h"
+
+#include "core/dom/custom/CustomElementCallbackDispatcher.h"
+#include "core/dom/custom/CustomElementCallbackQueue.h"
+
+namespace WebCore {
+
+void CustomElementBaseElementQueue::enqueue(CustomElementCallbackQueue* queue)
+{
+ m_queue.append(queue);
+}
+
+bool CustomElementBaseElementQueue::dispatch(ElementQueue baseQueueId)
+{
+ ASSERT(!m_inDispatch);
+ m_inDispatch = true;
+
+ bool didWork = m_queue.size();
+
+ for (Vector<CustomElementCallbackQueue*>::iterator it = m_queue.begin(); it != m_queue.end(); ++it) {
+ // The created callback may schedule entered document
+ // callbacks.
+ CustomElementCallbackDispatcher::CallbackDeliveryScope deliveryScope;
+ (*it)->processInElementQueue(baseQueueId);
+ }
+
+ m_queue.resize(0);
+ m_inDispatch = 0;
+
+ return didWork;
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementBaseElementQueue.h b/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementBaseElementQueue.h
new file mode 100644
index 00000000000..78882aa3e0a
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementBaseElementQueue.h
@@ -0,0 +1,58 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * 3. Neither the name of Google Inc. nor the names of its contributors
+ * may be used to endorse or promote products derived from this
+ * software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef CustomElementBaseElementQueue_h
+#define CustomElementBaseElementQueue_h
+
+#include "wtf/Vector.h"
+
+namespace WebCore {
+
+class CustomElementCallbackQueue;
+
+class CustomElementBaseElementQueue {
+ WTF_MAKE_NONCOPYABLE(CustomElementBaseElementQueue);
+public:
+ CustomElementBaseElementQueue() : m_inDispatch(false) { }
+
+ bool isEmpty() const { return m_queue.isEmpty(); }
+ void enqueue(CustomElementCallbackQueue*);
+
+ typedef int ElementQueue;
+ bool dispatch(ElementQueue baseQueueId);
+
+private:
+ bool m_inDispatch;
+ Vector<CustomElementCallbackQueue*> m_queue;
+};
+
+}
+
+#endif // CustomElementBaseElementQueue_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementCallbackDispatcher.cpp b/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementCallbackDispatcher.cpp
new file mode 100644
index 00000000000..450af4ef301
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementCallbackDispatcher.cpp
@@ -0,0 +1,108 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * 3. Neither the name of Google Inc. nor the names of its contributors
+ * may be used to endorse or promote products derived from this
+ * software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/dom/custom/CustomElementCallbackDispatcher.h"
+
+#include "core/dom/custom/CustomElementCallbackQueue.h"
+#include "core/dom/custom/CustomElementCallbackScheduler.h"
+#include "wtf/MainThread.h"
+
+namespace WebCore {
+
+size_t CustomElementCallbackDispatcher::s_elementQueueStart = 0;
+
+// The base of the stack has a null sentinel value.
+size_t CustomElementCallbackDispatcher::s_elementQueueEnd = kNumSentinels;
+
+CustomElementCallbackDispatcher& CustomElementCallbackDispatcher::instance()
+{
+ DEFINE_STATIC_LOCAL(CustomElementCallbackDispatcher, instance, ());
+ return instance;
+}
+
+bool CustomElementCallbackDispatcher::dispatch()
+{
+ ASSERT(isMainThread());
+ if (inCallbackDeliveryScope())
+ return false;
+
+ bool didWork = m_baseElementQueue.dispatch(baseElementQueue());
+ CustomElementCallbackScheduler::clearElementCallbackQueueMap();
+ return didWork;
+}
+
+// Dispatches callbacks when popping the processing stack.
+void CustomElementCallbackDispatcher::processElementQueueAndPop()
+{
+ instance().processElementQueueAndPop(s_elementQueueStart, s_elementQueueEnd);
+}
+
+void CustomElementCallbackDispatcher::processElementQueueAndPop(size_t start, size_t end)
+{
+ ASSERT(isMainThread());
+ ElementQueue thisQueue = currentElementQueue();
+
+ for (size_t i = start; i < end; i++) {
+ {
+ // The created callback may schedule entered document
+ // callbacks.
+ CallbackDeliveryScope deliveryScope;
+ m_flattenedProcessingStack[i]->processInElementQueue(thisQueue);
+ }
+
+ ASSERT(start == s_elementQueueStart);
+ ASSERT(end == s_elementQueueEnd);
+ }
+
+ // Pop the element queue from the processing stack
+ m_flattenedProcessingStack.resize(start);
+ s_elementQueueEnd = start;
+
+ if (start == kNumSentinels && m_baseElementQueue.isEmpty())
+ CustomElementCallbackScheduler::clearElementCallbackQueueMap();
+}
+
+void CustomElementCallbackDispatcher::enqueue(CustomElementCallbackQueue* callbackQueue)
+{
+ if (callbackQueue->owner() == currentElementQueue())
+ return;
+
+ callbackQueue->setOwner(currentElementQueue());
+
+ if (inCallbackDeliveryScope()) {
+ m_flattenedProcessingStack.append(callbackQueue);
+ ++s_elementQueueEnd;
+ } else {
+ m_baseElementQueue.enqueue(callbackQueue);
+ }
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementCallbackDispatcher.h b/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementCallbackDispatcher.h
new file mode 100644
index 00000000000..179219110c1
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementCallbackDispatcher.h
@@ -0,0 +1,121 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * 3. Neither the name of Google Inc. nor the names of its contributors
+ * may be used to endorse or promote products derived from this
+ * software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef CustomElementCallbackDispatcher_h
+#define CustomElementCallbackDispatcher_h
+
+#include "core/dom/custom/CustomElementBaseElementQueue.h"
+#include "wtf/Vector.h"
+
+namespace WebCore {
+
+class CustomElementCallbackQueue;
+class CustomElementCallbackScheduler;
+
+class CustomElementCallbackDispatcher {
+ WTF_MAKE_NONCOPYABLE(CustomElementCallbackDispatcher);
+public:
+ static CustomElementCallbackDispatcher& instance();
+
+ // This is stack allocated in many DOM callbacks. Make it cheap.
+ class CallbackDeliveryScope {
+ public:
+ CallbackDeliveryScope()
+ : m_savedElementQueueStart(s_elementQueueStart)
+ {
+ s_elementQueueStart = s_elementQueueEnd;
+ }
+
+ ~CallbackDeliveryScope()
+ {
+ if (s_elementQueueStart != s_elementQueueEnd)
+ processElementQueueAndPop();
+ s_elementQueueStart = m_savedElementQueueStart;
+ }
+
+ private:
+ size_t m_savedElementQueueStart;
+ };
+
+ // Returns true if more work may have to be performed at the
+ // checkpoint by this or other workers (for example, this work
+ // invoked author scripts)
+ bool dispatch();
+
+protected:
+ friend class CustomElementCallbackScheduler;
+ void enqueue(CustomElementCallbackQueue*);
+
+private:
+ CustomElementCallbackDispatcher()
+ {
+ // Add a null element as a sentinel. This makes it possible to
+ // identify elements queued when there is no
+ // CallbackDeliveryScope active. Also, if the processing stack
+ // is popped when empty, this sentinel will cause a null deref
+ // crash.
+ CustomElementCallbackQueue* sentinel = 0;
+ for (size_t i = 0; i < kNumSentinels; i++)
+ m_flattenedProcessingStack.append(sentinel);
+ ASSERT(s_elementQueueEnd == m_flattenedProcessingStack.size());
+ }
+
+ // The start of the element queue on the top of the processing
+ // stack. An offset into instance().m_flattenedProcessingStack.
+ static size_t s_elementQueueStart;
+
+ // The end of the element queue on the top of the processing
+ // stack. A cache of instance().m_flattenedProcessingStack.size().
+ static size_t s_elementQueueEnd;
+
+ static bool inCallbackDeliveryScope() { return s_elementQueueStart; }
+
+ typedef int ElementQueue;
+ static ElementQueue baseElementQueue() { return ElementQueue(0); }
+ static ElementQueue currentElementQueue() { return ElementQueue(s_elementQueueStart); }
+
+ static void processElementQueueAndPop();
+ void processElementQueueAndPop(size_t start, size_t end);
+
+ // The base element queue, used when no CallbackDeliveryScope is
+ // active. Callbacks for elements created by the parser are
+ // enqueued here.
+ CustomElementBaseElementQueue m_baseElementQueue;
+
+ // The processing stack, flattened. Element queues lower in the
+ // stack appear toward the head of the vector. The first element
+ // is a null sentinel value.
+ static const size_t kNumSentinels = 1;
+ Vector<CustomElementCallbackQueue*> m_flattenedProcessingStack;
+};
+
+}
+
+#endif // CustomElementCallbackDispatcher_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementCallbackInvocation.cpp b/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementCallbackInvocation.cpp
new file mode 100644
index 00000000000..e4fb331b654
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementCallbackInvocation.cpp
@@ -0,0 +1,135 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * 3. Neither the name of Google Inc. nor the names of its contributors
+ * may be used to endorse or promote products derived from this
+ * software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/dom/custom/CustomElementCallbackInvocation.h"
+
+#include "core/dom/Element.h"
+#include "core/dom/custom/CustomElementCallbackScheduler.h"
+
+namespace WebCore {
+
+class CreatedInvocation : public CustomElementCallbackInvocation {
+public:
+ CreatedInvocation(PassRefPtr<CustomElementLifecycleCallbacks> callbacks)
+ : CustomElementCallbackInvocation(callbacks)
+ {
+ }
+
+private:
+ virtual void dispatch(Element*) OVERRIDE;
+ virtual bool isCreated() const OVERRIDE { return true; }
+};
+
+void CreatedInvocation::dispatch(Element* element)
+{
+ if (element->inDocument() && element->document().domWindow())
+ CustomElementCallbackScheduler::scheduleAttachedCallback(callbacks(), element);
+ callbacks()->created(element);
+}
+
+class AttachedDetachedInvocation : public CustomElementCallbackInvocation {
+public:
+ AttachedDetachedInvocation(PassRefPtr<CustomElementLifecycleCallbacks>, CustomElementLifecycleCallbacks::CallbackType which);
+
+private:
+ virtual void dispatch(Element*) OVERRIDE;
+
+ CustomElementLifecycleCallbacks::CallbackType m_which;
+};
+
+AttachedDetachedInvocation::AttachedDetachedInvocation(PassRefPtr<CustomElementLifecycleCallbacks> callbacks, CustomElementLifecycleCallbacks::CallbackType which)
+ : CustomElementCallbackInvocation(callbacks)
+ , m_which(which)
+{
+ ASSERT(m_which == CustomElementLifecycleCallbacks::Attached || m_which == CustomElementLifecycleCallbacks::Detached);
+}
+
+void AttachedDetachedInvocation::dispatch(Element* element)
+{
+ switch (m_which) {
+ case CustomElementLifecycleCallbacks::Attached:
+ callbacks()->attached(element);
+ break;
+ case CustomElementLifecycleCallbacks::Detached:
+ callbacks()->detached(element);
+ break;
+ default:
+ ASSERT_NOT_REACHED();
+ }
+}
+
+class AttributeChangedInvocation : public CustomElementCallbackInvocation {
+public:
+ AttributeChangedInvocation(PassRefPtr<CustomElementLifecycleCallbacks>, const AtomicString& name, const AtomicString& oldValue, const AtomicString& newValue);
+
+private:
+ virtual void dispatch(Element*) OVERRIDE;
+
+ AtomicString m_name;
+ AtomicString m_oldValue;
+ AtomicString m_newValue;
+};
+
+AttributeChangedInvocation::AttributeChangedInvocation(PassRefPtr<CustomElementLifecycleCallbacks> callbacks, const AtomicString& name, const AtomicString& oldValue, const AtomicString& newValue)
+ : CustomElementCallbackInvocation(callbacks)
+ , m_name(name)
+ , m_oldValue(oldValue)
+ , m_newValue(newValue)
+{
+}
+
+void AttributeChangedInvocation::dispatch(Element* element)
+{
+ callbacks()->attributeChanged(element, m_name, m_oldValue, m_newValue);
+}
+
+PassOwnPtr<CustomElementCallbackInvocation> CustomElementCallbackInvocation::createInvocation(PassRefPtr<CustomElementLifecycleCallbacks> callbacks, CustomElementLifecycleCallbacks::CallbackType which)
+{
+ switch (which) {
+ case CustomElementLifecycleCallbacks::Created:
+ return adoptPtr(new CreatedInvocation(callbacks));
+
+ case CustomElementLifecycleCallbacks::Attached:
+ case CustomElementLifecycleCallbacks::Detached:
+ return adoptPtr(new AttachedDetachedInvocation(callbacks, which));
+
+ default:
+ ASSERT_NOT_REACHED();
+ return PassOwnPtr<CustomElementCallbackInvocation>();
+ }
+}
+
+PassOwnPtr<CustomElementCallbackInvocation> CustomElementCallbackInvocation::createAttributeChangedInvocation(PassRefPtr<CustomElementLifecycleCallbacks> callbacks, const AtomicString& name, const AtomicString& oldValue, const AtomicString& newValue)
+{
+ return adoptPtr(new AttributeChangedInvocation(callbacks, name, oldValue, newValue));
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementCallbackInvocation.h b/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementCallbackInvocation.h
new file mode 100644
index 00000000000..097e0918b08
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementCallbackInvocation.h
@@ -0,0 +1,68 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * 3. Neither the name of Google Inc. nor the names of its contributors
+ * may be used to endorse or promote products derived from this
+ * software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef CustomElementCallbackInvocation_h
+#define CustomElementCallbackInvocation_h
+
+#include "core/dom/custom/CustomElementLifecycleCallbacks.h"
+#include "wtf/PassOwnPtr.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefPtr.h"
+#include "wtf/text/AtomicString.h"
+
+namespace WebCore {
+
+class Element;
+
+class CustomElementCallbackInvocation {
+ WTF_MAKE_NONCOPYABLE(CustomElementCallbackInvocation);
+public:
+ static PassOwnPtr<CustomElementCallbackInvocation> createInvocation(PassRefPtr<CustomElementLifecycleCallbacks>, CustomElementLifecycleCallbacks::CallbackType);
+ static PassOwnPtr<CustomElementCallbackInvocation> createAttributeChangedInvocation(PassRefPtr<CustomElementLifecycleCallbacks>, const AtomicString& name, const AtomicString& oldValue, const AtomicString& newValue);
+
+ virtual ~CustomElementCallbackInvocation() { }
+ virtual void dispatch(Element*) = 0;
+ virtual bool isCreated() const { return false; }
+
+protected:
+ CustomElementCallbackInvocation(PassRefPtr<CustomElementLifecycleCallbacks> callbacks)
+ : m_callbacks(callbacks)
+ {
+ }
+
+ CustomElementLifecycleCallbacks* callbacks() { return m_callbacks.get(); }
+
+private:
+ RefPtr<CustomElementLifecycleCallbacks> m_callbacks;
+};
+
+}
+
+#endif // CustomElementCallbackInvocation_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementCallbackQueue.cpp b/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementCallbackQueue.cpp
new file mode 100644
index 00000000000..7da3b717550
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementCallbackQueue.cpp
@@ -0,0 +1,71 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * 3. Neither the name of Google Inc. nor the names of its contributors
+ * may be used to endorse or promote products derived from this
+ * software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/dom/custom/CustomElementCallbackQueue.h"
+
+namespace WebCore {
+
+PassOwnPtr<CustomElementCallbackQueue> CustomElementCallbackQueue::create(PassRefPtr<Element> element)
+{
+ return adoptPtr(new CustomElementCallbackQueue(element));
+}
+
+CustomElementCallbackQueue::CustomElementCallbackQueue(PassRefPtr<Element> element)
+ : m_element(element)
+ , m_owner(-1)
+ , m_index(0)
+ , m_inCreatedCallback(false)
+{
+}
+
+void CustomElementCallbackQueue::processInElementQueue(ElementQueue caller)
+{
+ ASSERT(!m_inCreatedCallback);
+
+ while (m_index < m_queue.size() && owner() == caller) {
+ m_inCreatedCallback = m_queue[m_index]->isCreated();
+
+ // dispatch() may cause recursion which steals this callback
+ // queue and reenters processInQueue. owner() == caller
+ // detects this recursion and cedes processing.
+ m_queue[m_index++]->dispatch(m_element.get());
+ m_inCreatedCallback = false;
+ }
+
+ if (owner() == caller && m_index == m_queue.size()) {
+ // This processInQueue exhausted the queue; shrink it.
+ m_index = 0;
+ m_queue.resize(0);
+ m_owner = -1;
+ }
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementCallbackQueue.h b/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementCallbackQueue.h
new file mode 100644
index 00000000000..269bfd29d4a
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementCallbackQueue.h
@@ -0,0 +1,74 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * 3. Neither the name of Google Inc. nor the names of its contributors
+ * may be used to endorse or promote products derived from this
+ * software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef CustomElementCallbackQueue_h
+#define CustomElementCallbackQueue_h
+
+#include "core/dom/Element.h"
+#include "core/dom/custom/CustomElementCallbackInvocation.h"
+#include "wtf/PassOwnPtr.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefPtr.h"
+#include "wtf/Vector.h"
+
+namespace WebCore {
+
+class CustomElementCallbackQueue {
+ WTF_MAKE_NONCOPYABLE(CustomElementCallbackQueue);
+public:
+ static PassOwnPtr<CustomElementCallbackQueue> create(PassRefPtr<Element>);
+
+ typedef int ElementQueue;
+ ElementQueue owner() { return m_owner; }
+ void setOwner(ElementQueue newOwner)
+ {
+ // ElementCallbackQueues only migrate towards the top of the
+ // processing stack.
+ ASSERT(newOwner >= m_owner);
+ m_owner = newOwner;
+ }
+
+ void append(PassOwnPtr<CustomElementCallbackInvocation> invocation) { m_queue.append(invocation); }
+ void processInElementQueue(ElementQueue);
+ bool inCreatedCallback() const { return m_inCreatedCallback; }
+
+private:
+ CustomElementCallbackQueue(PassRefPtr<Element>);
+
+ RefPtr<Element> m_element;
+ Vector<OwnPtr<CustomElementCallbackInvocation> > m_queue;
+ ElementQueue m_owner;
+ size_t m_index;
+ bool m_inCreatedCallback;
+};
+
+}
+
+#endif // CustomElementCallbackQueue_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementCallbackScheduler.cpp b/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementCallbackScheduler.cpp
new file mode 100644
index 00000000000..fc3c90ca63d
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementCallbackScheduler.cpp
@@ -0,0 +1,121 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * 3. Neither the name of Google Inc. nor the names of its contributors
+ * may be used to endorse or promote products derived from this
+ * software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/dom/custom/CustomElementCallbackScheduler.h"
+
+#include "core/dom/Element.h"
+#include "core/dom/custom/CustomElementCallbackDispatcher.h"
+#include "core/dom/custom/CustomElementLifecycleCallbacks.h"
+
+namespace WebCore {
+
+void CustomElementCallbackScheduler::scheduleAttributeChangedCallback(PassRefPtr<CustomElementLifecycleCallbacks> callbacks, PassRefPtr<Element> element, const AtomicString& name, const AtomicString& oldValue, const AtomicString& newValue)
+{
+ if (!callbacks->hasAttributeChangedCallback())
+ return;
+
+ CustomElementCallbackQueue* queue = instance().schedule(element);
+ queue->append(CustomElementCallbackInvocation::createAttributeChangedInvocation(callbacks, name, oldValue, newValue));
+}
+
+void CustomElementCallbackScheduler::scheduleCreatedCallback(PassRefPtr<CustomElementLifecycleCallbacks> callbacks, PassRefPtr<Element> element)
+{
+ if (!callbacks->hasCreatedCallback())
+ return;
+
+ CustomElementCallbackQueue* queue = instance().scheduleInCurrentElementQueue(element);
+ queue->append(CustomElementCallbackInvocation::createInvocation(callbacks, CustomElementLifecycleCallbacks::Created));
+}
+
+void CustomElementCallbackScheduler::scheduleAttachedCallback(PassRefPtr<CustomElementLifecycleCallbacks> callbacks, PassRefPtr<Element> element)
+{
+ if (!callbacks->hasAttachedCallback())
+ return;
+
+ CustomElementCallbackQueue* queue = instance().schedule(element);
+ queue->append(CustomElementCallbackInvocation::createInvocation(callbacks, CustomElementLifecycleCallbacks::Attached));
+}
+
+void CustomElementCallbackScheduler::scheduleDetachedCallback(PassRefPtr<CustomElementLifecycleCallbacks> callbacks, PassRefPtr<Element> element)
+{
+ if (!callbacks->hasDetachedCallback())
+ return;
+
+ CustomElementCallbackQueue* queue = instance().schedule(element);
+ queue->append(CustomElementCallbackInvocation::createInvocation(callbacks, CustomElementLifecycleCallbacks::Detached));
+}
+
+CustomElementCallbackScheduler& CustomElementCallbackScheduler::instance()
+{
+ DEFINE_STATIC_LOCAL(CustomElementCallbackScheduler, instance, ());
+ return instance;
+}
+
+CustomElementCallbackQueue* CustomElementCallbackScheduler::ensureCallbackQueue(PassRefPtr<Element> element)
+{
+ Element* key = element.get();
+ ElementCallbackQueueMap::iterator it = m_elementCallbackQueueMap.find(key);
+ if (it == m_elementCallbackQueueMap.end())
+ it = m_elementCallbackQueueMap.add(key, CustomElementCallbackQueue::create(element)).iterator;
+ return it->value.get();
+}
+
+void CustomElementCallbackScheduler::clearElementCallbackQueueMap()
+{
+ ElementCallbackQueueMap emptyMap;
+ instance().m_elementCallbackQueueMap.swap(emptyMap);
+}
+
+// Finds or creates the callback queue for element. If the
+// createdCallback has not finished running, the callback queue is not
+// moved to the top-of-stack. Otherwise like
+// scheduleInCurrentElementQueue.
+CustomElementCallbackQueue* CustomElementCallbackScheduler::schedule(PassRefPtr<Element> element)
+{
+ CustomElementCallbackQueue* callbackQueue = ensureCallbackQueue(element);
+ if (!callbackQueue->inCreatedCallback())
+ CustomElementCallbackDispatcher::instance().enqueue(callbackQueue);
+ return callbackQueue;
+}
+
+// Finds or creates the callback queue for element. If the element's
+// callback queue is scheduled in an earlier processing stack frame,
+// its owner is set to the element queue on the top of the processing
+// stack. Because callback queues are processed exhaustively, this
+// effectively moves the callback queue to the top of the stack.
+CustomElementCallbackQueue* CustomElementCallbackScheduler::scheduleInCurrentElementQueue(PassRefPtr<Element> element)
+{
+ CustomElementCallbackQueue* callbackQueue = ensureCallbackQueue(element);
+ CustomElementCallbackDispatcher::instance().enqueue(callbackQueue);
+ return callbackQueue;
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementCallbackScheduler.h b/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementCallbackScheduler.h
new file mode 100644
index 00000000000..741ede220bf
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementCallbackScheduler.h
@@ -0,0 +1,71 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * 3. Neither the name of Google Inc. nor the names of its contributors
+ * may be used to endorse or promote products derived from this
+ * software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef CustomElementCallbackScheduler_h
+#define CustomElementCallbackScheduler_h
+
+#include "core/dom/custom/CustomElementCallbackQueue.h"
+#include "wtf/HashMap.h"
+#include "wtf/OwnPtr.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/text/AtomicString.h"
+
+namespace WebCore {
+
+class CustomElementLifecycleCallbacks;
+class Element;
+
+class CustomElementCallbackScheduler {
+public:
+ static void scheduleAttributeChangedCallback(PassRefPtr<CustomElementLifecycleCallbacks>, PassRefPtr<Element>, const AtomicString& name, const AtomicString& oldValue, const AtomicString& newValue);
+ static void scheduleCreatedCallback(PassRefPtr<CustomElementLifecycleCallbacks>, PassRefPtr<Element>);
+ static void scheduleAttachedCallback(PassRefPtr<CustomElementLifecycleCallbacks>, PassRefPtr<Element>);
+ static void scheduleDetachedCallback(PassRefPtr<CustomElementLifecycleCallbacks>, PassRefPtr<Element>);
+
+protected:
+ friend class CustomElementCallbackDispatcher;
+ static void clearElementCallbackQueueMap();
+
+private:
+ CustomElementCallbackScheduler() { }
+
+ static CustomElementCallbackScheduler& instance();
+
+ CustomElementCallbackQueue* ensureCallbackQueue(PassRefPtr<Element>);
+ CustomElementCallbackQueue* schedule(PassRefPtr<Element>);
+ CustomElementCallbackQueue* scheduleInCurrentElementQueue(PassRefPtr<Element>);
+
+ typedef HashMap<Element*, OwnPtr<CustomElementCallbackQueue> > ElementCallbackQueueMap;
+ ElementCallbackQueueMap m_elementCallbackQueueMap;
+};
+
+}
+
+#endif // CustomElementCallbackScheduler_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementDefinition.cpp b/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementDefinition.cpp
new file mode 100644
index 00000000000..34e07f92a16
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementDefinition.cpp
@@ -0,0 +1,47 @@
+/*
+ * Copyright (C) 2012 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/dom/custom/CustomElementDefinition.h"
+
+namespace WebCore {
+
+PassRefPtr<CustomElementDefinition> CustomElementDefinition::create(const CustomElementDescriptor& descriptor, PassRefPtr<CustomElementLifecycleCallbacks> callbacks)
+{
+ return adoptRef(new CustomElementDefinition(descriptor, callbacks));
+}
+
+CustomElementDefinition::CustomElementDefinition(const CustomElementDescriptor& descriptor, PassRefPtr<CustomElementLifecycleCallbacks> callbacks)
+ : m_descriptor(descriptor)
+ , m_callbacks(callbacks)
+{
+}
+
+}
diff --git a/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementDefinition.h b/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementDefinition.h
new file mode 100644
index 00000000000..72e4121ddbd
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementDefinition.h
@@ -0,0 +1,58 @@
+/*
+ * Copyright (C) 2012 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef CustomElementDefinition_h
+#define CustomElementDefinition_h
+
+#include "core/dom/custom/CustomElementDescriptor.h"
+#include "core/dom/custom/CustomElementLifecycleCallbacks.h"
+#include "wtf/Forward.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefCounted.h"
+
+namespace WebCore {
+
+class CustomElementDefinition FINAL : public RefCounted<CustomElementDefinition> {
+public:
+ static PassRefPtr<CustomElementDefinition> create(const CustomElementDescriptor&, PassRefPtr<CustomElementLifecycleCallbacks>);
+
+ const CustomElementDescriptor& descriptor() const { return m_descriptor; }
+ CustomElementLifecycleCallbacks* callbacks() const { return m_callbacks.get(); }
+
+private:
+ CustomElementDefinition(const CustomElementDescriptor&, PassRefPtr<CustomElementLifecycleCallbacks>);
+
+ CustomElementDescriptor m_descriptor;
+ RefPtr<CustomElementLifecycleCallbacks> m_callbacks;
+};
+
+}
+
+#endif // CustomElementDefinition_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/CustomElementDescriptor.h b/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementDescriptor.h
index 7a3c6719bcc..7a3c6719bcc 100644
--- a/chromium/third_party/WebKit/Source/core/dom/CustomElementDescriptor.h
+++ b/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementDescriptor.h
diff --git a/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementDescriptorHash.h b/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementDescriptorHash.h
new file mode 100644
index 00000000000..fe8bcb5789d
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementDescriptorHash.h
@@ -0,0 +1,66 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef CustomElementDescriptorHash_h
+#define CustomElementDescriptorHash_h
+
+#include "core/dom/custom/CustomElementDescriptor.h"
+#include "wtf/HashFunctions.h"
+#include "wtf/HashTraits.h"
+#include "wtf/text/AtomicStringHash.h"
+
+namespace WebCore {
+
+struct CustomElementDescriptorHash {
+ static unsigned hash(const CustomElementDescriptor& descriptor)
+ {
+ return WTF::pairIntHash(AtomicStringHash::hash(descriptor.type()), WTF::pairIntHash(AtomicStringHash::hash(descriptor.namespaceURI()), AtomicStringHash::hash(descriptor.localName())));
+ }
+
+ static bool equal(const CustomElementDescriptor& a, const CustomElementDescriptor& b)
+ {
+ return a == b;
+ }
+
+ static const bool safeToCompareToEmptyOrDeleted = true;
+};
+
+} // namespace WebCore
+
+namespace WTF {
+
+template<>
+struct HashTraits<WebCore::CustomElementDescriptor> : SimpleClassHashTraits<WebCore::CustomElementDescriptor> {
+ static const bool emptyValueIsZero = HashTraits<AtomicString>::emptyValueIsZero;
+};
+
+} // namespace WTF
+
+#endif // CustomElementDescriptorHash
diff --git a/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementException.cpp b/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementException.cpp
new file mode 100644
index 00000000000..331548af8b6
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementException.cpp
@@ -0,0 +1,95 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * 3. Neither the name of Google Inc. nor the names of its contributors
+ * may be used to endorse or promote products derived from this
+ * software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/dom/custom/CustomElementException.h"
+
+#include "bindings/v8/ExceptionState.h"
+#include "core/dom/ExceptionCode.h"
+
+namespace WebCore {
+
+String CustomElementException::preamble(const AtomicString& type)
+{
+ return "Registration failed for type '" + type + "'. ";
+}
+
+void CustomElementException::throwException(Reason reason, const AtomicString& type, ExceptionState& exceptionState)
+{
+ switch (reason) {
+ case CannotRegisterFromExtension:
+ exceptionState.throwDOMException(NotSupportedError, preamble(type) + "Elements cannot be registered from extensions.");
+ return;
+
+ case ConstructorPropertyNotConfigurable:
+ exceptionState.throwDOMException(NotSupportedError, preamble(type) + "Prototype constructor property is not configurable.");
+ return;
+
+ case ContextDestroyedCheckingPrototype:
+ exceptionState.throwDOMException(InvalidStateError, preamble(type) + "The context is no longer valid.");
+ return;
+
+ case ContextDestroyedCreatingCallbacks:
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
+ return;
+
+ case ContextDestroyedRegisteringDefinition:
+ exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
+ return;
+
+ case ExtendsIsInvalidName:
+ exceptionState.throwDOMException(InvalidCharacterError, preamble(type) + "The tag name specified in 'extends' is not a valid tag name.");
+ return;
+
+ case ExtendsIsCustomElementName:
+ exceptionState.throwDOMException(InvalidCharacterError, preamble(type) + "The tag name specified in 'extends' is a custom element name. Use inheritance instead.");
+ return;
+
+ case InvalidName:
+ exceptionState.throwDOMException(InvalidCharacterError, preamble(type) + "The type name is invalid.");
+ return;
+
+ case PrototypeInUse:
+ exceptionState.throwDOMException(NotSupportedError, preamble(type) + "The prototype is already in-use as an interface prototype object.");
+ return;
+
+ case PrototypeNotAnObject:
+ exceptionState.throwDOMException(InvalidStateError, preamble(type) + "The prototype option is not an object.");
+ return;
+
+ case TypeAlreadyRegistered:
+ exceptionState.throwDOMException(InvalidStateError, preamble(type) + "A type with that name is already registered.");
+ return;
+ }
+
+ ASSERT_NOT_REACHED();
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/CustomElementException.h b/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementException.h
index 30bdb3be981..30bdb3be981 100644
--- a/chromium/third_party/WebKit/Source/core/dom/CustomElementException.h
+++ b/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementException.h
diff --git a/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementLifecycleCallbacks.h b/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementLifecycleCallbacks.h
new file mode 100644
index 00000000000..aa182e625d9
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementLifecycleCallbacks.h
@@ -0,0 +1,74 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef CustomElementLifecycleCallbacks_h
+#define CustomElementLifecycleCallbacks_h
+
+#include "wtf/RefCounted.h"
+#include "wtf/text/AtomicString.h"
+
+namespace WebCore {
+
+class Element;
+
+class CustomElementLifecycleCallbacks : public RefCounted<CustomElementLifecycleCallbacks> {
+public:
+ virtual ~CustomElementLifecycleCallbacks() { }
+
+ bool hasCreatedCallback() const { return m_which & Created; }
+ virtual void created(Element*) = 0;
+
+ bool hasAttachedCallback() const { return m_which & Attached; }
+ virtual void attached(Element*) = 0;
+
+ bool hasDetachedCallback() const { return m_which & Detached; }
+ virtual void detached(Element*) = 0;
+
+ bool hasAttributeChangedCallback() const { return m_which & AttributeChanged; }
+ virtual void attributeChanged(Element*, const AtomicString& name, const AtomicString& oldValue, const AtomicString& newValue) = 0;
+
+ enum CallbackType {
+ None = 0,
+ Created = 1 << 0,
+ Attached = 1 << 1,
+ Detached = 1 << 2,
+ AttributeChanged = 1 << 3
+ };
+
+protected:
+ CustomElementLifecycleCallbacks(CallbackType which) : m_which(which) { }
+
+private:
+ CallbackType m_which;
+};
+
+}
+
+#endif // CustomElementLifecycleCallbacks_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementObserver.cpp b/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementObserver.cpp
new file mode 100644
index 00000000000..94247fccecc
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementObserver.cpp
@@ -0,0 +1,70 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * 3. Neither the name of Google Inc. nor the names of its contributors
+ * may be used to endorse or promote products derived from this
+ * software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/dom/custom/CustomElementObserver.h"
+
+namespace WebCore {
+
+CustomElementObserver::ElementObserverMap& CustomElementObserver::elementObservers()
+{
+ DEFINE_STATIC_LOCAL(ElementObserverMap, map, ());
+ return map;
+}
+
+void CustomElementObserver::notifyElementDidFinishParsingChildren(Element* element)
+{
+ ElementObserverMap::iterator it = elementObservers().find(element);
+ if (it == elementObservers().end())
+ return;
+ it->value->elementDidFinishParsingChildren(element);
+}
+
+void CustomElementObserver::notifyElementWasDestroyed(Element* element)
+{
+ ElementObserverMap::iterator it = elementObservers().find(element);
+ if (it == elementObservers().end())
+ return;
+ it->value->elementWasDestroyed(element);
+}
+
+void CustomElementObserver::observe(Element* element)
+{
+ ElementObserverMap::AddResult result = elementObservers().add(element, this);
+ ASSERT_UNUSED(result, result.isNewEntry);
+}
+
+void CustomElementObserver::unobserve(Element* element)
+{
+ CustomElementObserver* observer = elementObservers().take(element);
+ ASSERT_UNUSED(observer, observer == this);
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/CustomElementObserver.h b/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementObserver.h
index ab7c57dcee8..ab7c57dcee8 100644
--- a/chromium/third_party/WebKit/Source/core/dom/CustomElementObserver.h
+++ b/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementObserver.h
diff --git a/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementRegistrationContext.cpp b/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementRegistrationContext.cpp
new file mode 100644
index 00000000000..e248ab7cbf1
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementRegistrationContext.cpp
@@ -0,0 +1,150 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * 3. Neither the name of Google Inc. nor the names of its contributors
+ * may be used to endorse or promote products derived from this
+ * software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/dom/custom/CustomElementRegistrationContext.h"
+
+#include "HTMLNames.h"
+#include "SVGNames.h"
+#include "bindings/v8/ExceptionState.h"
+#include "core/dom/Element.h"
+#include "core/dom/custom/CustomElement.h"
+#include "core/dom/custom/CustomElementCallbackScheduler.h"
+#include "core/dom/custom/CustomElementDefinition.h"
+#include "core/html/HTMLElement.h"
+#include "core/html/HTMLUnknownElement.h"
+#include "core/svg/SVGUnknownElement.h"
+#include "wtf/RefPtr.h"
+
+namespace WebCore {
+
+void CustomElementRegistrationContext::registerElement(Document* document, CustomElementConstructorBuilder* constructorBuilder, const AtomicString& type, CustomElement::NameSet validNames, ExceptionState& exceptionState)
+{
+ CustomElementDefinition* definition = m_registry.registerElement(document, constructorBuilder, type, validNames, exceptionState);
+
+ if (!definition)
+ return;
+
+ // Upgrade elements that were waiting for this definition.
+ const CustomElementUpgradeCandidateMap::ElementSet& upgradeCandidates = m_candidates.takeUpgradeCandidatesFor(definition->descriptor());
+ for (CustomElementUpgradeCandidateMap::ElementSet::const_iterator it = upgradeCandidates.begin(); it != upgradeCandidates.end(); ++it)
+ didResolveElement(definition, *it);
+}
+
+PassRefPtr<Element> CustomElementRegistrationContext::createCustomTagElement(Document& document, const QualifiedName& tagName)
+{
+ ASSERT(CustomElement::isValidName(tagName.localName()));
+
+ RefPtr<Element> element;
+
+ if (HTMLNames::xhtmlNamespaceURI == tagName.namespaceURI()) {
+ element = HTMLElement::create(tagName, document);
+ } else if (SVGNames::svgNamespaceURI == tagName.namespaceURI()) {
+ element = SVGUnknownElement::create(tagName, document);
+ } else {
+ // XML elements are not custom elements, so return early.
+ return Element::create(tagName, &document);
+ }
+
+ element->setCustomElementState(Element::WaitingForUpgrade);
+ resolve(element.get(), nullAtom);
+ return element.release();
+}
+
+void CustomElementRegistrationContext::didGiveTypeExtension(Element* element, const AtomicString& type)
+{
+ resolve(element, type);
+}
+
+void CustomElementRegistrationContext::resolve(Element* element, const AtomicString& typeExtension)
+{
+ // If an element has a custom tag name it takes precedence over
+ // the "is" attribute (if any).
+ const AtomicString& type = CustomElement::isValidName(element->localName())
+ ? element->localName()
+ : typeExtension;
+ ASSERT(!type.isNull());
+
+ CustomElementDescriptor descriptor(type, element->namespaceURI(), element->localName());
+ CustomElementDefinition* definition = m_registry.find(descriptor);
+ if (definition)
+ didResolveElement(definition, element);
+ else
+ didCreateUnresolvedElement(descriptor, element);
+}
+
+void CustomElementRegistrationContext::didResolveElement(CustomElementDefinition* definition, Element* element)
+{
+ CustomElement::define(element, definition);
+}
+
+void CustomElementRegistrationContext::didCreateUnresolvedElement(const CustomElementDescriptor& descriptor, Element* element)
+{
+ ASSERT(element->customElementState() == Element::WaitingForUpgrade);
+ m_candidates.add(descriptor, element);
+}
+
+PassRefPtr<CustomElementRegistrationContext> CustomElementRegistrationContext::create()
+{
+ return adoptRef(new CustomElementRegistrationContext());
+}
+
+void CustomElementRegistrationContext::setIsAttributeAndTypeExtension(Element* element, const AtomicString& type)
+{
+ ASSERT(element);
+ ASSERT(!type.isEmpty());
+ element->setAttribute(HTMLNames::isAttr, type);
+ setTypeExtension(element, type);
+}
+
+void CustomElementRegistrationContext::setTypeExtension(Element* element, const AtomicString& type)
+{
+ if (!element->isHTMLElement() && !element->isSVGElement())
+ return;
+
+ if (element->isCustomElement()) {
+ // This can happen if:
+ // 1. The element has a custom tag, which takes precedence over
+ // type extensions.
+ // 2. Undoing a command (eg ReplaceNodeWithSpan) recycles an
+ // element but tries to overwrite its attribute list.
+ return;
+ }
+
+ // Custom tags take precedence over type extensions
+ ASSERT(!CustomElement::isValidName(element->localName()));
+
+ element->setCustomElementState(Element::WaitingForUpgrade);
+
+ if (CustomElementRegistrationContext* context = element->document().registrationContext())
+ context->didGiveTypeExtension(element, type);
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementRegistrationContext.h b/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementRegistrationContext.h
new file mode 100644
index 00000000000..97dbc5fbfa7
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementRegistrationContext.h
@@ -0,0 +1,83 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * 3. Neither the name of Google Inc. nor the names of its contributors
+ * may be used to endorse or promote products derived from this
+ * software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef CustomElementRegistrationContext_h
+#define CustomElementRegistrationContext_h
+
+#include "core/dom/QualifiedName.h"
+#include "core/dom/custom/CustomElementDescriptor.h"
+#include "core/dom/custom/CustomElementRegistry.h"
+#include "core/dom/custom/CustomElementUpgradeCandidateMap.h"
+#include "wtf/HashMap.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/text/AtomicString.h"
+
+namespace WebCore {
+
+class CustomElementConstructorBuilder;
+class CustomElementDefinition;
+class Document;
+class Element;
+class ExceptionState;
+
+class CustomElementRegistrationContext : public RefCounted<CustomElementRegistrationContext> {
+public:
+ static PassRefPtr<CustomElementRegistrationContext> create();
+
+ ~CustomElementRegistrationContext() { }
+
+ // Definitions
+ void registerElement(Document*, CustomElementConstructorBuilder*, const AtomicString& type, CustomElement::NameSet validNames, ExceptionState&);
+
+ PassRefPtr<Element> createCustomTagElement(Document&, const QualifiedName&);
+ static void setIsAttributeAndTypeExtension(Element*, const AtomicString& type);
+ static void setTypeExtension(Element*, const AtomicString& type);
+
+protected:
+ CustomElementRegistrationContext() { }
+
+ // Instance creation
+ void didGiveTypeExtension(Element*, const AtomicString& type);
+
+private:
+ void resolve(Element*, const AtomicString& typeExtension);
+ void didResolveElement(CustomElementDefinition*, Element*);
+ void didCreateUnresolvedElement(const CustomElementDescriptor&, Element*);
+
+ CustomElementRegistry m_registry;
+
+ // Element creation
+ CustomElementUpgradeCandidateMap m_candidates;
+};
+
+}
+
+#endif // CustomElementRegistrationContext_h
+
diff --git a/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementRegistry.cpp b/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementRegistry.cpp
new file mode 100644
index 00000000000..b4bd6668dea
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementRegistry.cpp
@@ -0,0 +1,124 @@
+/*
+ * Copyright (C) 2012 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * 3. Neither the name of Google Inc. nor the names of its contributors
+ * may be used to endorse or promote products derived from this
+ * software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/dom/custom/CustomElementRegistry.h"
+
+#include "HTMLNames.h"
+#include "SVGNames.h"
+#include "bindings/v8/CustomElementConstructorBuilder.h"
+#include "core/dom/DocumentLifecycleObserver.h"
+#include "core/dom/custom/CustomElementException.h"
+#include "core/dom/custom/CustomElementRegistrationContext.h"
+
+namespace WebCore {
+
+class RegistrationContextObserver : public DocumentLifecycleObserver {
+public:
+ explicit RegistrationContextObserver(Document* document)
+ : DocumentLifecycleObserver(document)
+ , m_wentAway(!document)
+ {
+ }
+
+ bool registrationContextWentAway() { return m_wentAway; }
+
+private:
+ virtual void documentWasDisposed() OVERRIDE { m_wentAway = true; }
+
+ bool m_wentAway;
+};
+
+CustomElementDefinition* CustomElementRegistry::registerElement(Document* document, CustomElementConstructorBuilder* constructorBuilder, const AtomicString& userSuppliedName, CustomElement::NameSet validNames, ExceptionState& exceptionState)
+{
+ // FIXME: In every instance except one it is the
+ // CustomElementConstructorBuilder that observes document
+ // destruction during registration. This responsibility should be
+ // consolidated in one place.
+ RegistrationContextObserver observer(document);
+
+ AtomicString type = userSuppliedName.lower();
+
+ if (!constructorBuilder->isFeatureAllowed()) {
+ CustomElementException::throwException(CustomElementException::CannotRegisterFromExtension, type, exceptionState);
+ return 0;
+ }
+
+ if (!CustomElement::isValidName(type, validNames)) {
+ CustomElementException::throwException(CustomElementException::InvalidName, type, exceptionState);
+ return 0;
+ }
+
+ QualifiedName tagName = nullQName();
+ if (!constructorBuilder->validateOptions(type, tagName, exceptionState))
+ return 0;
+
+ ASSERT(tagName.namespaceURI() == HTMLNames::xhtmlNamespaceURI || tagName.namespaceURI() == SVGNames::svgNamespaceURI);
+
+ // FIXME: This should be done earlier in validateOptions.
+ if (m_registeredTypeNames.contains(type)) {
+ CustomElementException::throwException(CustomElementException::TypeAlreadyRegistered, type, exceptionState);
+ return 0;
+ }
+
+ ASSERT(!observer.registrationContextWentAway());
+
+ RefPtr<CustomElementLifecycleCallbacks> lifecycleCallbacks = constructorBuilder->createCallbacks();
+
+ // Consulting the constructor builder could execute script and
+ // kill the document.
+ if (observer.registrationContextWentAway()) {
+ CustomElementException::throwException(CustomElementException::ContextDestroyedCreatingCallbacks, type, exceptionState);
+ return 0;
+ }
+
+ const CustomElementDescriptor descriptor(type, tagName.namespaceURI(), tagName.localName());
+ RefPtr<CustomElementDefinition> definition = CustomElementDefinition::create(descriptor, lifecycleCallbacks);
+
+ if (!constructorBuilder->createConstructor(document, definition.get(), exceptionState))
+ return 0;
+
+ m_definitions.add(descriptor, definition);
+ m_registeredTypeNames.add(descriptor.type());
+
+ if (!constructorBuilder->didRegisterDefinition(definition.get())) {
+ CustomElementException::throwException(CustomElementException::ContextDestroyedRegisteringDefinition, type, exceptionState);
+ return 0;
+ }
+
+ return definition.get();
+}
+
+CustomElementDefinition* CustomElementRegistry::find(const CustomElementDescriptor& descriptor) const
+{
+ return m_definitions.get(descriptor);
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementRegistry.h b/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementRegistry.h
new file mode 100644
index 00000000000..c6acc8e6d9d
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementRegistry.h
@@ -0,0 +1,68 @@
+/*
+ * Copyright (C) 2012 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * 3. Neither the name of Google Inc. nor the names of its contributors
+ * may be used to endorse or promote products derived from this
+ * software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef CustomElementRegistry_h
+#define CustomElementRegistry_h
+
+#include "core/dom/custom/CustomElement.h"
+#include "core/dom/custom/CustomElementDefinition.h"
+#include "core/dom/custom/CustomElementDescriptor.h"
+#include "core/dom/custom/CustomElementDescriptorHash.h"
+#include "wtf/HashMap.h"
+#include "wtf/HashSet.h"
+#include "wtf/RefPtr.h"
+#include "wtf/text/AtomicString.h"
+#include "wtf/text/AtomicStringHash.h"
+
+namespace WebCore {
+
+class CustomElementConstructorBuilder;
+class Document;
+class ExceptionState;
+
+class CustomElementRegistry FINAL {
+ WTF_MAKE_NONCOPYABLE(CustomElementRegistry);
+protected:
+ friend class CustomElementRegistrationContext;
+
+ CustomElementRegistry() { }
+
+ CustomElementDefinition* registerElement(Document*, CustomElementConstructorBuilder*, const AtomicString& name, CustomElement::NameSet validNames, ExceptionState&);
+ CustomElementDefinition* find(const CustomElementDescriptor&) const;
+
+private:
+ typedef HashMap<CustomElementDescriptor, RefPtr<CustomElementDefinition> > DefinitionMap;
+ DefinitionMap m_definitions;
+ HashSet<AtomicString> m_registeredTypeNames;
+};
+
+} // namespace WebCore
+
+#endif
diff --git a/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementUpgradeCandidateMap.cpp b/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementUpgradeCandidateMap.cpp
new file mode 100644
index 00000000000..b7ea628bd48
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementUpgradeCandidateMap.cpp
@@ -0,0 +1,110 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/dom/custom/CustomElementUpgradeCandidateMap.h"
+
+#include "core/dom/Element.h"
+
+namespace WebCore {
+
+CustomElementUpgradeCandidateMap::~CustomElementUpgradeCandidateMap()
+{
+ UpgradeCandidateMap::const_iterator::Keys end = m_upgradeCandidates.end().keys();
+ for (UpgradeCandidateMap::const_iterator::Keys it = m_upgradeCandidates.begin().keys(); it != end; ++it)
+ unobserve(*it);
+}
+
+void CustomElementUpgradeCandidateMap::add(const CustomElementDescriptor& descriptor, Element* element)
+{
+ observe(element);
+
+ UpgradeCandidateMap::AddResult result = m_upgradeCandidates.add(element, descriptor);
+ ASSERT_UNUSED(result, result.isNewEntry);
+
+ UnresolvedDefinitionMap::iterator it = m_unresolvedDefinitions.find(descriptor);
+ if (it == m_unresolvedDefinitions.end())
+ it = m_unresolvedDefinitions.add(descriptor, ElementSet()).iterator;
+ it->value.add(element);
+}
+
+void CustomElementUpgradeCandidateMap::remove(Element* element)
+{
+ unobserve(element);
+ removeCommon(element);
+}
+
+void CustomElementUpgradeCandidateMap::elementWasDestroyed(Element* element)
+{
+ CustomElementObserver::elementWasDestroyed(element);
+ removeCommon(element);
+}
+
+void CustomElementUpgradeCandidateMap::removeCommon(Element* element)
+{
+ UpgradeCandidateMap::iterator candidate = m_upgradeCandidates.find(element);
+ ASSERT_WITH_SECURITY_IMPLICATION(candidate != m_upgradeCandidates.end());
+
+ UnresolvedDefinitionMap::iterator elements = m_unresolvedDefinitions.find(candidate->value);
+ ASSERT_WITH_SECURITY_IMPLICATION(elements != m_unresolvedDefinitions.end());
+ elements->value.remove(element);
+ m_upgradeCandidates.remove(candidate);
+}
+
+void CustomElementUpgradeCandidateMap::elementDidFinishParsingChildren(Element* element)
+{
+ // An upgrade candidate finished parsing; reorder so that eventual
+ // upgrade order matches finished-parsing order.
+ moveToEnd(element);
+}
+
+void CustomElementUpgradeCandidateMap::moveToEnd(Element* element)
+{
+ UpgradeCandidateMap::iterator candidate = m_upgradeCandidates.find(element);
+ ASSERT_WITH_SECURITY_IMPLICATION(candidate != m_upgradeCandidates.end());
+
+ UnresolvedDefinitionMap::iterator elements = m_unresolvedDefinitions.find(candidate->value);
+ ASSERT_WITH_SECURITY_IMPLICATION(elements != m_unresolvedDefinitions.end());
+ elements->value.appendOrMoveToLast(element);
+}
+
+ListHashSet<Element*> CustomElementUpgradeCandidateMap::takeUpgradeCandidatesFor(const CustomElementDescriptor& descriptor)
+{
+ const ListHashSet<Element*>& candidates = m_unresolvedDefinitions.take(descriptor);
+
+ for (ElementSet::const_iterator candidate = candidates.begin(); candidate != candidates.end(); ++candidate) {
+ unobserve(*candidate);
+ m_upgradeCandidates.remove(*candidate);
+ }
+
+ return candidates;
+}
+
+}
diff --git a/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementUpgradeCandidateMap.h b/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementUpgradeCandidateMap.h
new file mode 100644
index 00000000000..f68c50b65be
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/dom/custom/CustomElementUpgradeCandidateMap.h
@@ -0,0 +1,75 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef CustomElementUpgradeCandidateMap_h
+#define CustomElementUpgradeCandidateMap_h
+
+#include "core/dom/custom/CustomElementDescriptor.h"
+#include "core/dom/custom/CustomElementDescriptorHash.h"
+#include "core/dom/custom/CustomElementObserver.h"
+#include "wtf/HashMap.h"
+#include "wtf/ListHashSet.h"
+#include "wtf/Noncopyable.h"
+
+namespace WebCore {
+
+class Element;
+
+class CustomElementUpgradeCandidateMap : CustomElementObserver {
+ WTF_MAKE_NONCOPYABLE(CustomElementUpgradeCandidateMap);
+public:
+ CustomElementUpgradeCandidateMap() { }
+ ~CustomElementUpgradeCandidateMap();
+
+ // API for CustomElementRegistrationContext to save and take candidates
+
+ typedef ListHashSet<Element*> ElementSet;
+
+ void add(const CustomElementDescriptor&, Element*);
+ void remove(Element*);
+ ElementSet takeUpgradeCandidatesFor(const CustomElementDescriptor&);
+
+private:
+ virtual void elementWasDestroyed(Element*) OVERRIDE;
+ void removeCommon(Element*);
+
+ virtual void elementDidFinishParsingChildren(Element*) OVERRIDE;
+ void moveToEnd(Element*);
+
+ typedef HashMap<Element*, CustomElementDescriptor> UpgradeCandidateMap;
+ UpgradeCandidateMap m_upgradeCandidates;
+
+ typedef HashMap<CustomElementDescriptor, ElementSet> UnresolvedDefinitionMap;
+ UnresolvedDefinitionMap m_unresolvedDefinitions;
+};
+
+}
+
+#endif // CustomElementUpgradeCandidateMap_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/default/PlatformMessagePortChannel.cpp b/chromium/third_party/WebKit/Source/core/dom/default/PlatformMessagePortChannel.cpp
deleted file mode 100644
index 28375179859..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/default/PlatformMessagePortChannel.cpp
+++ /dev/null
@@ -1,196 +0,0 @@
-/*
- * Copyright (C) 2009 Google Inc. All rights reserved.
- * Copyright (C) 2013 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/dom/default/PlatformMessagePortChannel.h"
-
-#include "core/dom/MessagePort.h"
-#include "core/dom/ScriptExecutionContext.h"
-
-namespace WebCore {
-
-PassOwnPtr<PlatformMessagePortChannel::EventData> PlatformMessagePortChannel::EventData::create(PassRefPtr<SerializedScriptValue> message, PassOwnPtr<MessagePortChannelArray> channels)
-{
- return adoptPtr(new EventData(message, channels));
-}
-
-PlatformMessagePortChannel::EventData::EventData(PassRefPtr<SerializedScriptValue> message, PassOwnPtr<MessagePortChannelArray> channels)
- : m_message(message)
- , m_channels(channels)
-{
-}
-
-void MessagePortChannel::createChannel(PassRefPtr<MessagePort> port1, PassRefPtr<MessagePort> port2)
-{
- RefPtr<PlatformMessagePortChannel::MessagePortQueue> queue1 = PlatformMessagePortChannel::MessagePortQueue::create();
- RefPtr<PlatformMessagePortChannel::MessagePortQueue> queue2 = PlatformMessagePortChannel::MessagePortQueue::create();
-
- OwnPtr<MessagePortChannel> channel1 = adoptPtr(new MessagePortChannel(PlatformMessagePortChannel::create(queue1, queue2)));
- OwnPtr<MessagePortChannel> channel2 = adoptPtr(new MessagePortChannel(PlatformMessagePortChannel::create(queue2, queue1)));
-
- channel1->m_channel->m_entangledChannel = channel2->m_channel;
- channel2->m_channel->m_entangledChannel = channel1->m_channel;
-
- port1->entangle(channel2.release());
- port2->entangle(channel1.release());
-}
-
-MessagePortChannel::MessagePortChannel(PassRefPtr<PlatformMessagePortChannel> channel)
- : m_channel(channel)
-{
-}
-
-MessagePortChannel::~MessagePortChannel()
-{
- close();
-}
-
-bool MessagePortChannel::entangleIfOpen(MessagePort* port)
-{
- // We can't call member functions on our remote pair while holding our mutex or we'll deadlock,
- // but we need to guard against the remote port getting closed/freed, so create a standalone reference.
- RefPtr<PlatformMessagePortChannel> remote = m_channel->entangledChannel();
- if (!remote)
- return false;
- remote->setRemotePort(port);
- return true;
-}
-
-void MessagePortChannel::disentangle()
-{
- RefPtr<PlatformMessagePortChannel> remote = m_channel->entangledChannel();
- if (remote)
- remote->setRemotePort(0);
-}
-
-void MessagePortChannel::postMessageToRemote(PassRefPtr<SerializedScriptValue> message, PassOwnPtr<MessagePortChannelArray> channels)
-{
- MutexLocker lock(m_channel->m_mutex);
- if (!m_channel->m_outgoingQueue)
- return;
- bool wasEmpty = m_channel->m_outgoingQueue->appendAndCheckEmpty(PlatformMessagePortChannel::EventData::create(message, channels));
- if (wasEmpty && m_channel->m_remotePort)
- m_channel->m_remotePort->messageAvailable();
-}
-
-bool MessagePortChannel::tryGetMessageFromRemote(RefPtr<SerializedScriptValue>& message, OwnPtr<MessagePortChannelArray>& channels)
-{
- MutexLocker lock(m_channel->m_mutex);
- OwnPtr<PlatformMessagePortChannel::EventData> result = m_channel->m_incomingQueue->tryGetMessage();
- if (!result)
- return false;
-
- message = result->message();
- channels = result->channels();
-
- return true;
-}
-
-void MessagePortChannel::close()
-{
- RefPtr<PlatformMessagePortChannel> remote = m_channel->entangledChannel();
- if (!remote)
- return;
- m_channel->closeInternal();
- remote->closeInternal();
-}
-
-bool MessagePortChannel::isConnectedTo(MessagePort* port)
-{
- // FIXME: What guarantees that the result remains the same after we release the lock?
- MutexLocker lock(m_channel->m_mutex);
- return m_channel->m_remotePort == port;
-}
-
-bool MessagePortChannel::hasPendingActivity()
-{
- // FIXME: What guarantees that the result remains the same after we release the lock?
- MutexLocker lock(m_channel->m_mutex);
- return !m_channel->m_incomingQueue->isEmpty();
-}
-
-MessagePort* MessagePortChannel::locallyEntangledPort(const ScriptExecutionContext* context)
-{
- MutexLocker lock(m_channel->m_mutex);
- // See if both contexts are run by the same thread (are the same context, or are both documents).
- if (m_channel->m_remotePort) {
- // The remote port's ScriptExecutionContext is guaranteed not to change here - MessagePort::contextDestroyed()
- // will close the port before the context goes away, and close() will block because we are holding the mutex.
- ScriptExecutionContext* remoteContext = m_channel->m_remotePort->scriptExecutionContext();
- if (remoteContext == context || (remoteContext && remoteContext->isDocument() && context->isDocument()))
- return m_channel->m_remotePort;
- }
- return 0;
-}
-
-PassRefPtr<PlatformMessagePortChannel> PlatformMessagePortChannel::create(PassRefPtr<MessagePortQueue> incoming, PassRefPtr<MessagePortQueue> outgoing)
-{
- return adoptRef(new PlatformMessagePortChannel(incoming, outgoing));
-}
-
-PlatformMessagePortChannel::PlatformMessagePortChannel(PassRefPtr<MessagePortQueue> incoming, PassRefPtr<MessagePortQueue> outgoing)
- : m_incomingQueue(incoming)
- , m_outgoingQueue(outgoing)
- , m_remotePort(0)
-{
-}
-
-PlatformMessagePortChannel::~PlatformMessagePortChannel()
-{
-}
-
-void PlatformMessagePortChannel::setRemotePort(MessagePort* port)
-{
- MutexLocker lock(m_mutex);
- // Should never set port if it is already set.
- ASSERT(!port || !m_remotePort);
- m_remotePort = port;
-}
-
-PassRefPtr<PlatformMessagePortChannel> PlatformMessagePortChannel::entangledChannel()
-{
- // FIXME: What guarantees that the result remains the same after we release the lock?
- // This lock only guarantees that the returned pointer will not be pointing to released memory,
- // but not that it will still be pointing to this object's entangled port channel.
- MutexLocker lock(m_mutex);
- return m_entangledChannel;
-}
-
-void PlatformMessagePortChannel::closeInternal()
-{
- MutexLocker lock(m_mutex);
- // Disentangle ourselves from the other end. We still maintain a reference to our incoming queue, since previously-existing messages should still be delivered.
- m_remotePort = 0;
- m_entangledChannel = 0;
- m_outgoingQueue = 0;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/default/PlatformMessagePortChannel.h b/chromium/third_party/WebKit/Source/core/dom/default/PlatformMessagePortChannel.h
deleted file mode 100644
index f8dffd04d0d..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/default/PlatformMessagePortChannel.h
+++ /dev/null
@@ -1,115 +0,0 @@
-/*
- * Copyright (C) 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef PlatformMessagePortChannel_h
-#define PlatformMessagePortChannel_h
-
-#include "core/dom/MessagePortChannel.h"
-
-#include "wtf/MessageQueue.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/Threading.h"
-
-namespace WebCore {
-
- class MessagePort;
-
- // PlatformMessagePortChannel is a platform-dependent interface to the remote side of a message channel.
- // This default implementation supports multiple threads running within a single process. Implementations for multi-process platforms should define these public APIs in their own platform-specific PlatformMessagePortChannel file.
- // The goal of this implementation is to eliminate contention except when cloning or closing the port, so each side of the channel has its own separate mutex.
- class PlatformMessagePortChannel : public ThreadSafeRefCounted<PlatformMessagePortChannel> {
- public:
- class EventData {
- WTF_MAKE_NONCOPYABLE(EventData); WTF_MAKE_FAST_ALLOCATED;
- public:
- static PassOwnPtr<EventData> create(PassRefPtr<SerializedScriptValue>, PassOwnPtr<MessagePortChannelArray>);
-
- PassRefPtr<SerializedScriptValue> message() { return m_message; }
- PassOwnPtr<MessagePortChannelArray> channels() { return m_channels.release(); }
-
- private:
- EventData(PassRefPtr<SerializedScriptValue> message, PassOwnPtr<MessagePortChannelArray>);
- RefPtr<SerializedScriptValue> m_message;
- OwnPtr<MessagePortChannelArray> m_channels;
- };
-
- // Wrapper for MessageQueue that allows us to do thread safe sharing by two proxies.
- class MessagePortQueue : public ThreadSafeRefCounted<MessagePortQueue> {
- public:
- static PassRefPtr<MessagePortQueue> create() { return adoptRef(new MessagePortQueue()); }
-
- PassOwnPtr<PlatformMessagePortChannel::EventData> tryGetMessage()
- {
- return m_queue.tryGetMessage();
- }
-
- bool appendAndCheckEmpty(PassOwnPtr<PlatformMessagePortChannel::EventData> message)
- {
- return m_queue.appendAndCheckEmpty(message);
- }
-
- bool isEmpty()
- {
- return m_queue.isEmpty();
- }
-
- private:
- MessagePortQueue() { }
-
- MessageQueue<PlatformMessagePortChannel::EventData> m_queue;
- };
-
- ~PlatformMessagePortChannel();
-
- static PassRefPtr<PlatformMessagePortChannel> create(PassRefPtr<MessagePortQueue> incoming, PassRefPtr<MessagePortQueue> outgoing);
- PlatformMessagePortChannel(PassRefPtr<MessagePortQueue> incoming, PassRefPtr<MessagePortQueue> outgoing);
-
- PassRefPtr<PlatformMessagePortChannel> entangledChannel();
-
- void setRemotePort(MessagePort*);
- void closeInternal();
-
- // Mutex used to ensure exclusive access to the object internals.
- Mutex m_mutex;
-
- // Pointer to our entangled pair - cleared when close() is called.
- RefPtr<PlatformMessagePortChannel> m_entangledChannel;
-
- // Reference to the message queue for the (local) entangled port.
- RefPtr<MessagePortQueue> m_incomingQueue;
- RefPtr<MessagePortQueue> m_outgoingQueue;
-
- // The port we are connected to (the remote port) - this is the port that is notified when new messages arrive.
- MessagePort* m_remotePort;
- };
-
-} // namespace WebCore
-
-#endif // PlatformMessagePortChannel_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/default/chromium/PlatformMessagePortChannelChromium.cpp b/chromium/third_party/WebKit/Source/core/dom/default/chromium/PlatformMessagePortChannelChromium.cpp
deleted file mode 100644
index 466502fc98a..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/default/chromium/PlatformMessagePortChannelChromium.cpp
+++ /dev/null
@@ -1,251 +0,0 @@
-/*
- * Copyright (C) 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/dom/default/chromium/PlatformMessagePortChannelChromium.h"
-
-#include "bindings/v8/SerializedScriptValue.h"
-#include "core/dom/MessagePort.h"
-
-#include "public/platform/Platform.h"
-#include "public/platform/WebMessagePortChannel.h"
-#include "public/platform/WebString.h"
-
-namespace WebCore {
-
-PassOwnPtr<MessagePortChannel> MessagePortChannel::create(PassRefPtr<PlatformMessagePortChannel> channel)
-{
- return adoptPtr(new MessagePortChannel(channel));
-}
-
-void MessagePortChannel::createChannel(PassRefPtr<MessagePort> port1, PassRefPtr<MessagePort> port2)
-{
- PlatformMessagePortChannel::createChannel(port1, port2);
-}
-
-MessagePortChannel::MessagePortChannel(PassRefPtr<PlatformMessagePortChannel> channel)
- : m_channel(channel)
-{
-}
-
-MessagePortChannel::~MessagePortChannel()
-{
- // Make sure we close our platform channel when the base is freed, to keep the channel objects from leaking.
- m_channel->close();
-}
-
-bool MessagePortChannel::entangleIfOpen(MessagePort* port)
-{
- return m_channel->entangleIfOpen(port);
-}
-
-void MessagePortChannel::disentangle()
-{
- m_channel->disentangle();
-}
-
-void MessagePortChannel::postMessageToRemote(PassRefPtr<SerializedScriptValue> message, PassOwnPtr<MessagePortChannelArray> channels)
-{
- m_channel->postMessageToRemote(message, channels);
-}
-
-bool MessagePortChannel::tryGetMessageFromRemote(RefPtr<SerializedScriptValue>& message, OwnPtr<MessagePortChannelArray>& channels)
-{
- return m_channel->tryGetMessageFromRemote(message, channels);
-}
-
-void MessagePortChannel::close()
-{
- m_channel->close();
-}
-
-bool MessagePortChannel::isConnectedTo(MessagePort* port)
-{
- return m_channel->isConnectedTo(port);
-}
-
-bool MessagePortChannel::hasPendingActivity()
-{
- return m_channel->hasPendingActivity();
-}
-
-MessagePort* MessagePortChannel::locallyEntangledPort(const ScriptExecutionContext* context)
-{
- // This is just an optimization, so return 0 always.
- return 0;
-}
-
-
-PassRefPtr<PlatformMessagePortChannel> PlatformMessagePortChannel::create()
-{
- return adoptRef(new PlatformMessagePortChannel());
-}
-
-PassRefPtr<PlatformMessagePortChannel> PlatformMessagePortChannel::create(
- WebKit::WebMessagePortChannel* channel)
-{
- return adoptRef(new PlatformMessagePortChannel(channel));
-}
-
-
-PlatformMessagePortChannel::PlatformMessagePortChannel()
- : m_localPort(0)
-{
- m_webChannel = WebKit::Platform::current()->createMessagePortChannel();
- if (m_webChannel)
- m_webChannel->setClient(this);
-}
-
-PlatformMessagePortChannel::PlatformMessagePortChannel(WebKit::WebMessagePortChannel* channel)
- : m_localPort(0)
- , m_webChannel(channel)
-{
-}
-
-PlatformMessagePortChannel::~PlatformMessagePortChannel()
-{
- if (m_webChannel)
- m_webChannel->destroy();
-}
-
-void PlatformMessagePortChannel::createChannel(PassRefPtr<MessagePort> port1, PassRefPtr<MessagePort> port2)
-{
- // Create proxies for each endpoint.
- RefPtr<PlatformMessagePortChannel> channel1 = PlatformMessagePortChannel::create();
- RefPtr<PlatformMessagePortChannel> channel2 = PlatformMessagePortChannel::create();
-
- // Entangle the two endpoints.
- channel1->setEntangledChannel(channel2);
- channel2->setEntangledChannel(channel1);
-
- // Now entangle the proxies with the appropriate local ports.
- port1->entangle(MessagePortChannel::create(channel2));
- port2->entangle(MessagePortChannel::create(channel1));
-}
-
-void PlatformMessagePortChannel::messageAvailable()
-{
- MutexLocker lock(m_mutex);
- if (m_localPort)
- m_localPort->messageAvailable();
-}
-
-bool PlatformMessagePortChannel::entangleIfOpen(MessagePort* port)
-{
- MutexLocker lock(m_mutex);
- m_localPort = port;
- return true;
-}
-
-void PlatformMessagePortChannel::disentangle()
-{
- MutexLocker lock(m_mutex);
- m_localPort = 0;
-}
-
-void PlatformMessagePortChannel::postMessageToRemote(PassRefPtr<SerializedScriptValue> message, PassOwnPtr<MessagePortChannelArray> channels)
-{
- if (!m_localPort || !m_webChannel)
- return;
-
- WebKit::WebString messageString = message->toWireString();
- WebKit::WebMessagePortChannelArray* webChannels = 0;
- if (channels && channels->size()) {
- webChannels = new WebKit::WebMessagePortChannelArray(channels->size());
- for (size_t i = 0; i < channels->size(); ++i) {
- PlatformMessagePortChannel* platformChannel = (*channels)[i]->channel();
- (*webChannels)[i] = platformChannel->webChannelRelease();
- (*webChannels)[i]->setClient(0);
- }
- }
- m_webChannel->postMessage(messageString, webChannels);
-}
-
-bool PlatformMessagePortChannel::tryGetMessageFromRemote(RefPtr<SerializedScriptValue>& serializedMessage, OwnPtr<MessagePortChannelArray>& channels)
-{
- if (!m_webChannel)
- return false;
-
- WebKit::WebString message;
- WebKit::WebMessagePortChannelArray webChannels;
- bool rv = m_webChannel->tryGetMessage(&message, webChannels);
- if (rv) {
- if (webChannels.size()) {
- channels = adoptPtr(new MessagePortChannelArray(webChannels.size()));
- for (size_t i = 0; i < webChannels.size(); ++i) {
- RefPtr<PlatformMessagePortChannel> platformChannel = create(webChannels[i]);
- webChannels[i]->setClient(platformChannel.get());
- (*channels)[i] = MessagePortChannel::create(platformChannel);
- }
- }
- serializedMessage = SerializedScriptValue::createFromWire(message);
- }
-
- return rv;
-}
-
-void PlatformMessagePortChannel::close()
-{
- MutexLocker lock(m_mutex);
- // Disentangle ourselves from the other end. We still maintain a reference to m_webChannel,
- // since previously-existing messages should still be delivered.
- m_localPort = 0;
- m_entangledChannel = 0;
-}
-
-bool PlatformMessagePortChannel::isConnectedTo(MessagePort* port)
-{
- MutexLocker lock(m_mutex);
- return m_entangledChannel && m_entangledChannel->m_localPort == port;
-}
-
-bool PlatformMessagePortChannel::hasPendingActivity()
-{
- MutexLocker lock(m_mutex);
- return m_localPort;
-}
-
-void PlatformMessagePortChannel::setEntangledChannel(PassRefPtr<PlatformMessagePortChannel> remote)
-{
- if (m_webChannel)
- m_webChannel->entangle(remote->m_webChannel);
-
- MutexLocker lock(m_mutex);
- m_entangledChannel = remote;
-}
-
-WebKit::WebMessagePortChannel* PlatformMessagePortChannel::webChannelRelease()
-{
- WebKit::WebMessagePortChannel* rv = m_webChannel;
- m_webChannel = 0;
- return rv;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/default/chromium/PlatformMessagePortChannelChromium.h b/chromium/third_party/WebKit/Source/core/dom/default/chromium/PlatformMessagePortChannelChromium.h
deleted file mode 100644
index 7c54ada6abc..00000000000
--- a/chromium/third_party/WebKit/Source/core/dom/default/chromium/PlatformMessagePortChannelChromium.h
+++ /dev/null
@@ -1,92 +0,0 @@
-/*
- * Copyright (C) 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef PlatformMessagePortChannelChromium_h
-#define PlatformMessagePortChannelChromium_h
-
-#include "core/dom/MessagePortChannel.h"
-#include "public/platform/WebMessagePortChannelClient.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/ThreadingPrimitives.h"
-
-namespace WebKit {
-class WebMessagePortChannel;
-}
-
-namespace WebCore {
-
-class MessagePort;
-
-// PlatformMessagePortChannel is a platform-dependent interface to the remote side of a message channel.
-class PlatformMessagePortChannel : public ThreadSafeRefCounted<PlatformMessagePortChannel>,
- public WebKit::WebMessagePortChannelClient {
-public:
- static void createChannel(PassRefPtr<MessagePort>, PassRefPtr<MessagePort>);
- static PassRefPtr<PlatformMessagePortChannel> create();
- static PassRefPtr<PlatformMessagePortChannel> create(WebKit::WebMessagePortChannel*);
-
- // APIs delegated from core/dom/MessagePortChannel.h
- bool entangleIfOpen(MessagePort*);
- void disentangle();
- void postMessageToRemote(PassRefPtr<SerializedScriptValue>, PassOwnPtr<MessagePortChannelArray>);
- bool tryGetMessageFromRemote(RefPtr<SerializedScriptValue>&, OwnPtr<MessagePortChannelArray>&);
- void close();
- bool isConnectedTo(MessagePort*);
- bool hasPendingActivity();
-
- // Releases ownership of the contained web channel.
- WebKit::WebMessagePortChannel* webChannelRelease();
-
- virtual ~PlatformMessagePortChannel();
-
-private:
- PlatformMessagePortChannel();
- PlatformMessagePortChannel(WebKit::WebMessagePortChannel*);
-
- void setEntangledChannel(PassRefPtr<PlatformMessagePortChannel>);
-
- // WebKit::WebMessagePortChannelClient implementation
- virtual void messageAvailable();
-
- // Mutex used to ensure exclusive access to the object internals.
- Mutex m_mutex;
-
- // Pointer to our entangled pair - cleared when close() is called.
- RefPtr<PlatformMessagePortChannel> m_entangledChannel;
-
- // The port we are connected to - this is the port that is notified when new messages arrive.
- MessagePort* m_localPort;
-
- WebKit::WebMessagePortChannel* m_webChannel;
-};
-
-} // namespace WebCore
-
-#endif // PlatformMessagePortChannelChromium_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/shadow/ComposedTreeWalker.cpp b/chromium/third_party/WebKit/Source/core/dom/shadow/ComposedTreeWalker.cpp
index 1e19ddc80b0..2a1561202fc 100644
--- a/chromium/third_party/WebKit/Source/core/dom/shadow/ComposedTreeWalker.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/shadow/ComposedTreeWalker.cpp
@@ -30,7 +30,8 @@
#include "core/dom/Element.h"
#include "core/dom/shadow/ElementShadow.h"
-#include "core/dom/shadow/InsertionPoint.h"
+#include "core/html/shadow/HTMLContentElement.h"
+#include "core/html/shadow/HTMLShadowElement.h"
namespace WebCore {
@@ -41,22 +42,6 @@ static inline ElementShadow* shadowFor(const Node* node)
return 0;
}
-static inline bool nodeCanBeDistributed(const Node* node)
-{
- ASSERT(node);
- Node* parent = parentNodeForDistribution(node);
- if (!parent)
- return false;
-
- if (ShadowRoot* shadowRoot = parent->isShadowRoot() ? toShadowRoot(parent) : 0)
- return shadowRoot->insertionPoint();
-
- if (parent->isElementNode() && toElement(parent)->shadow())
- return true;
-
- return false;
-}
-
Node* ComposedTreeWalker::traverseChild(const Node* node, TraversalDirection direction) const
{
ASSERT(node);
@@ -83,12 +68,13 @@ Node* ComposedTreeWalker::traverseSiblings(const Node* node, TraversalDirection
Node* ComposedTreeWalker::traverseNode(const Node* node, TraversalDirection direction)
{
ASSERT(node);
- if (!isActiveInsertionPoint(node))
+ if (!isActiveInsertionPoint(*node))
return const_cast<Node*>(node);
const InsertionPoint* insertionPoint = toInsertionPoint(node);
if (Node* found = traverseDistributedNodes(direction == TraversalDirectionForward ? insertionPoint->first() : insertionPoint->last(), insertionPoint, direction))
return found;
- return traverseLightChildren(node, direction);
+ ASSERT(isHTMLShadowElement(node) || (isHTMLContentElement(node) && !node->hasChildNodes()));
+ return 0;
}
Node* ComposedTreeWalker::traverseDistributedNodes(const Node* node, const InsertionPoint* insertionPoint, TraversalDirection direction)
@@ -104,10 +90,10 @@ Node* ComposedTreeWalker::traverseSiblingOrBackToInsertionPoint(const Node* node
{
ASSERT(node);
- if (!nodeCanBeDistributed(node))
+ if (!shadowWhereNodeCanBeDistributed(*node))
return traverseSiblingInCurrentTree(node, direction);
- InsertionPoint* insertionPoint = resolveReprojection(node);
+ const InsertionPoint* insertionPoint = resolveReprojection(node);
if (!insertionPoint)
return traverseSiblingInCurrentTree(node, direction);
@@ -123,7 +109,7 @@ Node* ComposedTreeWalker::traverseSiblingInCurrentTree(const Node* node, Travers
return found;
if (Node* next = traverseBackToYoungerShadowRoot(node, direction))
return next;
- return escapeFallbackContentElement(node, direction);
+ return 0;
}
Node* ComposedTreeWalker::traverseBackToYoungerShadowRoot(const Node* node, TraversalDirection direction)
@@ -132,7 +118,7 @@ Node* ComposedTreeWalker::traverseBackToYoungerShadowRoot(const Node* node, Trav
if (node->parentNode() && node->parentNode()->isShadowRoot()) {
ShadowRoot* parentShadowRoot = toShadowRoot(node->parentNode());
if (!parentShadowRoot->isYoungest()) {
- InsertionPoint* assignedInsertionPoint = parentShadowRoot->insertionPoint();
+ HTMLShadowElement* assignedInsertionPoint = parentShadowRoot->shadowInsertionPointOfYoungerShadowRoot();
ASSERT(assignedInsertionPoint);
return traverseSiblingInCurrentTree(assignedInsertionPoint, direction);
}
@@ -140,24 +126,6 @@ Node* ComposedTreeWalker::traverseBackToYoungerShadowRoot(const Node* node, Trav
return 0;
}
-inline Node* ComposedTreeWalker::escapeFallbackContentElement(const Node* node, TraversalDirection direction)
-{
- ASSERT(node);
- if (node->parentNode() && isActiveInsertionPoint(node->parentNode()))
- return traverseSiblingOrBackToInsertionPoint(node->parentNode(), direction);
- return 0;
-}
-
-inline Node* ComposedTreeWalker::traverseNodeEscapingFallbackContents(const Node* node, ParentTraversalDetails* details) const
-{
- ASSERT(node);
- if (!node->isInsertionPoint())
- return const_cast<Node*>(node);
- const InsertionPoint* insertionPoint = toInsertionPoint(node);
- return insertionPoint->hasDistribution() ? 0 :
- insertionPoint->isActive() ? traverseParent(node, details) : const_cast<Node*>(node);
-}
-
// FIXME: Use an iterative algorithm so that it can be inlined.
// https://bugs.webkit.org/show_bug.cgi?id=90415
Node* ComposedTreeWalker::traverseParent(const Node* node, ParentTraversalDetails* details) const
@@ -165,39 +133,34 @@ Node* ComposedTreeWalker::traverseParent(const Node* node, ParentTraversalDetail
if (node->isPseudoElement())
return node->parentOrShadowHostNode();
- if (nodeCanBeDistributed(node)) {
- if (InsertionPoint* insertionPoint = resolveReprojection(node)) {
+ if (shadowWhereNodeCanBeDistributed(*node)) {
+ if (const InsertionPoint* insertionPoint = resolveReprojection(node)) {
if (details)
details->didTraverseInsertionPoint(insertionPoint);
- return traverseParent(insertionPoint, details);
+ // The node is distributed. But the distribution was stopped at this insertion point.
+ if (shadowWhereNodeCanBeDistributed(*insertionPoint))
+ return 0;
+ return traverseParentOrHost(insertionPoint, details);
}
-
- // The node is a non-distributed light child or older shadow's child.
- if (details)
- details->childWasOutOfComposition();
+ return 0;
}
- return traverseParentInCurrentTree(node, details);
+ return traverseParentOrHost(node, details);
}
-inline Node* ComposedTreeWalker::traverseParentInCurrentTree(const Node* node, ParentTraversalDetails* details) const
+inline Node* ComposedTreeWalker::traverseParentOrHost(const Node* node, ParentTraversalDetails* details) const
{
- if (Node* parent = node->parentNode())
- return parent->isShadowRoot() ? traverseParentBackToYoungerShadowRootOrHost(toShadowRoot(parent), details) : traverseNodeEscapingFallbackContents(parent, details);
- return 0;
-}
-
-Node* ComposedTreeWalker::traverseParentBackToYoungerShadowRootOrHost(const ShadowRoot* shadowRoot, ParentTraversalDetails* details) const
-{
- ASSERT(shadowRoot);
- ASSERT(!shadowRoot->insertionPoint());
-
- if (shadowRoot->isYoungest()) {
- if (details)
- details->didTraverseShadowRoot(shadowRoot);
- return shadowRoot->host();
- }
-
- return 0;
+ Node* parent = node->parentNode();
+ if (!parent)
+ return 0;
+ if (!parent->isShadowRoot())
+ return parent;
+ ShadowRoot* shadowRoot = toShadowRoot(parent);
+ ASSERT(!shadowRoot->shadowInsertionPointOfYoungerShadowRoot());
+ if (!shadowRoot->isYoungest())
+ return 0;
+ if (details)
+ details->didTraverseShadowRoot(shadowRoot);
+ return shadowRoot->host();
}
} // namespace
diff --git a/chromium/third_party/WebKit/Source/core/dom/shadow/ComposedTreeWalker.h b/chromium/third_party/WebKit/Source/core/dom/shadow/ComposedTreeWalker.h
index 2fb9cf33957..b750e34c2a0 100644
--- a/chromium/third_party/WebKit/Source/core/dom/shadow/ComposedTreeWalker.h
+++ b/chromium/third_party/WebKit/Source/core/dom/shadow/ComposedTreeWalker.h
@@ -77,7 +77,7 @@ private:
#ifndef NDEBUG
ASSERT(m_node);
ASSERT(!m_node->isShadowRoot());
- ASSERT(!isActiveInsertionPoint(m_node));
+ ASSERT(!isActiveInsertionPoint(*m_node));
#endif
}
@@ -106,11 +106,8 @@ private:
static Node* traverseDistributedNodes(const Node*, const InsertionPoint*, TraversalDirection);
static Node* traverseBackToYoungerShadowRoot(const Node*, TraversalDirection);
- static Node* escapeFallbackContentElement(const Node*, TraversalDirection);
- Node* traverseNodeEscapingFallbackContents(const Node*, ParentTraversalDetails* = 0) const;
- Node* traverseParentInCurrentTree(const Node*, ParentTraversalDetails* = 0) const;
- Node* traverseParentBackToYoungerShadowRootOrHost(const ShadowRoot*, ParentTraversalDetails* = 0) const;
+ Node* traverseParentOrHost(const Node*, ParentTraversalDetails* = 0) const;
const Node* m_node;
};
@@ -118,7 +115,6 @@ private:
inline ComposedTreeWalker::ComposedTreeWalker(const Node* node, StartPolicy startPolicy)
: m_node(node)
{
- UNUSED_PARAM(startPolicy);
#ifndef NDEBUG
if (m_node && startPolicy == CannotStartFromShadowBoundary)
assertPrecondition();
diff --git a/chromium/third_party/WebKit/Source/core/dom/shadow/ContentDistribution.cpp b/chromium/third_party/WebKit/Source/core/dom/shadow/ContentDistribution.cpp
index e0527ad3945..a53ff57b81b 100644
--- a/chromium/third_party/WebKit/Source/core/dom/shadow/ContentDistribution.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/shadow/ContentDistribution.cpp
@@ -39,7 +39,8 @@ void ContentDistribution::swap(ContentDistribution& other)
void ContentDistribution::append(PassRefPtr<Node> node)
{
- ASSERT(!isActiveInsertionPoint(node.get()));
+ ASSERT(node);
+ ASSERT(!isActiveInsertionPoint(*node));
size_t size = m_nodes.size();
m_indices.set(node.get(), size);
m_nodes.append(node);
diff --git a/chromium/third_party/WebKit/Source/core/dom/shadow/ElementShadow.cpp b/chromium/third_party/WebKit/Source/core/dom/shadow/ElementShadow.cpp
index bebad50f004..913bb93efc5 100644
--- a/chromium/third_party/WebKit/Source/core/dom/shadow/ElementShadow.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/shadow/ElementShadow.cpp
@@ -31,13 +31,95 @@
#include "core/dom/ElementTraversal.h"
#include "core/dom/NodeTraversal.h"
#include "core/dom/shadow/ContentDistribution.h"
-#include "core/dom/shadow/InsertionPoint.h"
-#include "core/dom/shadow/ShadowRoot.h"
#include "core/html/shadow/HTMLContentElement.h"
#include "core/html/shadow/HTMLShadowElement.h"
namespace WebCore {
+class DistributionPool {
+public:
+ explicit DistributionPool(const ContainerNode&);
+ void clear();
+ ~DistributionPool();
+ void distributeTo(InsertionPoint*, ElementShadow*);
+ void populateChildren(const ContainerNode&);
+
+private:
+ void detachNonDistributedNodes();
+ Vector<Node*, 32> m_nodes;
+ Vector<bool, 32> m_distributed;
+};
+
+inline DistributionPool::DistributionPool(const ContainerNode& parent)
+{
+ populateChildren(parent);
+}
+
+inline void DistributionPool::clear()
+{
+ detachNonDistributedNodes();
+ m_nodes.clear();
+ m_distributed.clear();
+}
+
+inline void DistributionPool::populateChildren(const ContainerNode& parent)
+{
+ clear();
+ for (Node* child = parent.firstChild(); child; child = child->nextSibling()) {
+ if (isActiveInsertionPoint(*child)) {
+ InsertionPoint* insertionPoint = toInsertionPoint(child);
+ for (size_t i = 0; i < insertionPoint->size(); ++i)
+ m_nodes.append(insertionPoint->at(i));
+ } else {
+ m_nodes.append(child);
+ }
+ }
+ m_distributed.resize(m_nodes.size());
+ m_distributed.fill(false);
+}
+
+void DistributionPool::distributeTo(InsertionPoint* insertionPoint, ElementShadow* elementShadow)
+{
+ ContentDistribution distribution;
+
+ for (size_t i = 0; i < m_nodes.size(); ++i) {
+ if (m_distributed[i])
+ continue;
+
+ if (isHTMLContentElement(insertionPoint) && !toHTMLContentElement(insertionPoint)->canSelectNode(m_nodes, i))
+ continue;
+
+ Node* node = m_nodes[i];
+ distribution.append(node);
+ elementShadow->didDistributeNode(node, insertionPoint);
+ m_distributed[i] = true;
+ }
+
+ // Distributes fallback elements
+ if (insertionPoint->isContentInsertionPoint() && distribution.isEmpty()) {
+ for (Node* fallbackNode = insertionPoint->firstChild(); fallbackNode; fallbackNode = fallbackNode->nextSibling()) {
+ distribution.append(fallbackNode);
+ elementShadow->didDistributeNode(fallbackNode, insertionPoint);
+ }
+ }
+ insertionPoint->setDistribution(distribution);
+}
+
+inline DistributionPool::~DistributionPool()
+{
+ detachNonDistributedNodes();
+}
+
+inline void DistributionPool::detachNonDistributedNodes()
+{
+ for (size_t i = 0; i < m_nodes.size(); ++i) {
+ if (m_distributed[i])
+ continue;
+ if (m_nodes[i]->renderer())
+ m_nodes[i]->lazyReattachIfAttached();
+ }
+}
+
PassOwnPtr<ElementShadow> ElementShadow::create()
{
return adoptPtr(new ElementShadow());
@@ -55,45 +137,46 @@ ElementShadow::~ElementShadow()
removeAllShadowRoots();
}
-ShadowRoot* ElementShadow::addShadowRoot(Element* shadowHost, ShadowRoot::ShadowRootType type)
+ShadowRoot& ElementShadow::addShadowRoot(Element& shadowHost, ShadowRoot::ShadowRootType type)
{
- RefPtr<ShadowRoot> shadowRoot = ShadowRoot::create(&shadowHost->document(), type);
+ RefPtr<ShadowRoot> shadowRoot = ShadowRoot::create(&shadowHost.document(), type);
- shadowRoot->setParentOrShadowHostNode(shadowHost);
- shadowRoot->setParentTreeScope(&shadowHost->treeScope());
+ for (ShadowRoot* root = youngestShadowRoot(); root; root = root->olderShadowRoot())
+ root->lazyReattachIfAttached();
+
+ shadowRoot->setParentOrShadowHostNode(&shadowHost);
+ shadowRoot->setParentTreeScope(&shadowHost.treeScope());
m_shadowRoots.push(shadowRoot.get());
- ChildNodeInsertionNotifier(shadowHost).notify(shadowRoot.get());
+ ChildNodeInsertionNotifier(shadowHost).notify(*shadowRoot);
setNeedsDistributionRecalc();
- shadowHost->lazyReattachIfAttached();
// addShadowRoot() affects apply-author-styles. However, we know that the youngest shadow root has not had any children yet.
// The youngest shadow root's apply-author-styles is default (false). So we can just set m_applyAuthorStyles false.
m_applyAuthorStyles = false;
- shadowHost->didAddShadowRoot(*shadowRoot);
- InspectorInstrumentation::didPushShadowRoot(shadowHost, shadowRoot.get());
+ shadowHost.didAddShadowRoot(*shadowRoot);
+ InspectorInstrumentation::didPushShadowRoot(&shadowHost, shadowRoot.get());
- return shadowRoot.get();
+ ASSERT(m_shadowRoots.head());
+ ASSERT(shadowRoot.get() == m_shadowRoots.head());
+ return *m_shadowRoots.head();
}
void ElementShadow::removeAllShadowRoots()
{
// Dont protect this ref count.
Element* shadowHost = host();
+ ASSERT(shadowHost);
while (RefPtr<ShadowRoot> oldRoot = m_shadowRoots.head()) {
InspectorInstrumentation::willPopShadowRoot(shadowHost, oldRoot.get());
shadowHost->document().removeFocusedElementOfSubtree(oldRoot.get());
-
- if (oldRoot->attached())
- oldRoot->detach();
-
m_shadowRoots.removeHead();
oldRoot->setParentOrShadowHostNode(0);
oldRoot->setParentTreeScope(&shadowHost->document());
oldRoot->setPrev(0);
oldRoot->setNext(0);
- ChildNodeRemovalNotifier(shadowHost).notify(oldRoot.get());
+ ChildNodeRemovalNotifier(*shadowHost).notify(*oldRoot);
}
}
@@ -103,7 +186,7 @@ void ElementShadow::attach(const Node::AttachContext& context)
childrenContext.resolvedStyle = 0;
for (ShadowRoot* root = youngestShadowRoot(); root; root = root->olderShadowRoot()) {
- if (!root->attached())
+ if (root->needsAttach())
root->attach(childrenContext);
}
}
@@ -113,16 +196,14 @@ void ElementShadow::detach(const Node::AttachContext& context)
Node::AttachContext childrenContext(context);
childrenContext.resolvedStyle = 0;
- for (ShadowRoot* root = youngestShadowRoot(); root; root = root->olderShadowRoot()) {
- if (root->attached())
- root->detach(childrenContext);
- }
+ for (ShadowRoot* root = youngestShadowRoot(); root; root = root->olderShadowRoot())
+ root->detach(childrenContext);
}
void ElementShadow::removeAllEventListeners()
{
for (ShadowRoot* root = youngestShadowRoot(); root; root = root->olderShadowRoot()) {
- for (Node* node = root; node; node = NodeTraversal::next(node))
+ for (Node* node = root; node; node = NodeTraversal::next(*node))
node->removeAllEventListeners();
}
}
@@ -169,137 +250,71 @@ bool ElementShadow::resolveApplyAuthorStyles() const
return false;
}
-InsertionPoint* ElementShadow::findInsertionPointFor(const Node* key) const
+const InsertionPoint* ElementShadow::finalDestinationInsertionPointFor(const Node* key) const
{
- return m_nodeToInsertionPoint.get(key);
+ NodeToDestinationInsertionPoints::const_iterator it = m_nodeToInsertionPoints.find(key);
+ return it == m_nodeToInsertionPoints.end() ? 0: it->value.last().get();
}
-void ElementShadow::populate(Node* node, Vector<Node*>& pool)
+const DestinationInsertionPoints* ElementShadow::destinationInsertionPointsFor(const Node* key) const
{
- if (!isActiveInsertionPoint(node)) {
- pool.append(node);
- return;
- }
-
- InsertionPoint* insertionPoint = toInsertionPoint(node);
- if (insertionPoint->hasDistribution()) {
- for (size_t i = 0; i < insertionPoint->size(); ++i)
- pool.append(insertionPoint->at(i));
- } else {
- for (Node* fallbackNode = insertionPoint->firstChild(); fallbackNode; fallbackNode = fallbackNode->nextSibling())
- pool.append(fallbackNode);
- }
+ NodeToDestinationInsertionPoints::const_iterator it = m_nodeToInsertionPoints.find(key);
+ return it == m_nodeToInsertionPoints.end() ? 0: &it->value;
}
void ElementShadow::distribute()
{
- Vector<Node*> pool;
- pool.reserveInitialCapacity(32);
- for (Node* node = host()->firstChild(); node; node = node->nextSibling())
- populate(node, pool);
-
host()->setNeedsStyleRecalc();
+ Vector<HTMLShadowElement*, 32> shadowInsertionPoints;
+ DistributionPool pool(*host());
- Vector<bool> distributed;
- distributed.fill(false, pool.size());
-
- Vector<HTMLShadowElement*, 32> activeShadowInsertionPoints;
for (ShadowRoot* root = youngestShadowRoot(); root; root = root->olderShadowRoot()) {
- HTMLShadowElement* firstActiveShadowInsertionPoint = 0;
-
- const Vector<RefPtr<InsertionPoint> >& insertionPoints = root->childInsertionPoints();
+ HTMLShadowElement* shadowInsertionPoint = 0;
+ const Vector<RefPtr<InsertionPoint> >& insertionPoints = root->descendantInsertionPoints();
for (size_t i = 0; i < insertionPoints.size(); ++i) {
InsertionPoint* point = insertionPoints[i].get();
if (!point->isActive())
continue;
-
if (isHTMLShadowElement(point)) {
- if (!firstActiveShadowInsertionPoint)
- firstActiveShadowInsertionPoint = toHTMLShadowElement(point);
+ if (!shadowInsertionPoint)
+ shadowInsertionPoint = toHTMLShadowElement(point);
} else {
- distributeSelectionsTo(point, pool, distributed);
- if (ElementShadow* shadow = shadowOfParentForDistribution(point))
+ pool.distributeTo(point, this);
+ if (ElementShadow* shadow = shadowWhereNodeCanBeDistributed(*point))
shadow->setNeedsDistributionRecalc();
}
}
-
- if (firstActiveShadowInsertionPoint)
- activeShadowInsertionPoints.append(firstActiveShadowInsertionPoint);
+ if (shadowInsertionPoint) {
+ shadowInsertionPoints.append(shadowInsertionPoint);
+ if (shadowInsertionPoint->hasChildNodes())
+ pool.populateChildren(*shadowInsertionPoint);
+ } else {
+ pool.clear();
+ }
}
- for (size_t i = activeShadowInsertionPoints.size(); i > 0; --i) {
- HTMLShadowElement* shadowElement = activeShadowInsertionPoints[i - 1];
- ShadowRoot* root = shadowElement->containingShadowRoot();
+ for (size_t i = shadowInsertionPoints.size(); i > 0; --i) {
+ HTMLShadowElement* shadowInsertionPoint = shadowInsertionPoints[i - 1];
+ ShadowRoot* root = shadowInsertionPoint->containingShadowRoot();
ASSERT(root);
- if (root->olderShadowRoot() && root->olderShadowRoot()->type() == root->type()) {
+ if (root->isOldest()) {
+ pool.distributeTo(shadowInsertionPoint, this);
+ } else if (root->olderShadowRoot()->type() == root->type()) {
// Only allow reprojecting older shadow roots between the same type to
// disallow reprojecting UA elements into author shadows.
- distributeNodeChildrenTo(shadowElement, root->olderShadowRoot());
- root->olderShadowRoot()->setInsertionPoint(shadowElement);
- } else if (!root->olderShadowRoot()) {
- // There's assumed to always be a UA shadow that selects all nodes.
- // We don't actually add it, instead we just distribute the pool to the
- // <shadow> in the oldest shadow root.
- distributeSelectionsTo(shadowElement, pool, distributed);
+ DistributionPool olderShadowRootPool(*root->olderShadowRoot());
+ olderShadowRootPool.distributeTo(shadowInsertionPoint, this);
+ root->olderShadowRoot()->setShadowInsertionPointOfYoungerShadowRoot(shadowInsertionPoint);
}
- if (ElementShadow* shadow = shadowOfParentForDistribution(shadowElement))
+ if (ElementShadow* shadow = shadowWhereNodeCanBeDistributed(*shadowInsertionPoint))
shadow->setNeedsDistributionRecalc();
}
-
- // Detach all nodes that were not distributed and have a renderer.
- for (size_t i = 0; i < pool.size(); ++i) {
- if (distributed[i])
- continue;
- if (pool[i]->renderer())
- pool[i]->lazyReattachIfAttached();
- }
}
-void ElementShadow::distributeSelectionsTo(InsertionPoint* insertionPoint, const Vector<Node*>& pool, Vector<bool>& distributed)
+void ElementShadow::didDistributeNode(const Node* node, InsertionPoint* insertionPoint)
{
- ContentDistribution distribution;
-
- for (size_t i = 0; i < pool.size(); ++i) {
- if (distributed[i])
- continue;
-
- if (isHTMLContentElement(insertionPoint) && !toHTMLContentElement(insertionPoint)->canSelectNode(pool, i))
- continue;
-
- Node* child = pool[i];
- distribution.append(child);
- m_nodeToInsertionPoint.add(child, insertionPoint);
- distributed[i] = true;
- }
-
- insertionPoint->setDistribution(distribution);
-}
-
-void ElementShadow::distributeNodeChildrenTo(InsertionPoint* insertionPoint, ContainerNode* containerNode)
-{
- ContentDistribution distribution;
- for (Node* node = containerNode->firstChild(); node; node = node->nextSibling()) {
- if (isActiveInsertionPoint(node)) {
- InsertionPoint* innerInsertionPoint = toInsertionPoint(node);
- if (innerInsertionPoint->hasDistribution()) {
- for (size_t i = 0; i < innerInsertionPoint->size(); ++i) {
- Node* nodeToAdd = innerInsertionPoint->at(i);
- distribution.append(nodeToAdd);
- m_nodeToInsertionPoint.add(nodeToAdd, insertionPoint);
- }
- } else {
- for (Node* child = innerInsertionPoint->firstChild(); child; child = child->nextSibling()) {
- distribution.append(child);
- m_nodeToInsertionPoint.add(child, insertionPoint);
- }
- }
- } else {
- distribution.append(node);
- m_nodeToInsertionPoint.add(node, insertionPoint);
- }
- }
-
- insertionPoint->setDistribution(distribution);
+ NodeToDestinationInsertionPoints::AddResult result = m_nodeToInsertionPoints.add(node, DestinationInsertionPoints());
+ result.iterator->value.append(insertionPoint);
}
const SelectRuleFeatureSet& ElementShadow::ensureSelectFeatureSet()
@@ -309,17 +324,17 @@ const SelectRuleFeatureSet& ElementShadow::ensureSelectFeatureSet()
m_selectFeatures.clear();
for (ShadowRoot* root = oldestShadowRoot(); root; root = root->youngerShadowRoot())
- collectSelectFeatureSetFrom(root);
+ collectSelectFeatureSetFrom(*root);
m_needsSelectFeatureSet = false;
return m_selectFeatures;
}
-void ElementShadow::collectSelectFeatureSetFrom(ShadowRoot* root)
+void ElementShadow::collectSelectFeatureSetFrom(ShadowRoot& root)
{
- if (!root->containsShadowRoots() && !root->containsContentElements())
+ if (!root.containsShadowRoots() && !root.containsContentElements())
return;
- for (Element* element = ElementTraversal::firstWithin(root); element; element = ElementTraversal::next(element, root)) {
+ for (Element* element = ElementTraversal::firstWithin(root); element; element = ElementTraversal::next(*element, &root)) {
if (ElementShadow* shadow = element->shadow())
m_selectFeatures.add(shadow->ensureSelectFeatureSet());
if (!isHTMLContentElement(element))
@@ -350,10 +365,10 @@ void ElementShadow::willAffectSelector()
void ElementShadow::clearDistribution()
{
- m_nodeToInsertionPoint.clear();
+ m_nodeToInsertionPoints.clear();
for (ShadowRoot* root = youngestShadowRoot(); root; root = root->olderShadowRoot())
- root->setInsertionPoint(0);
+ root->setShadowInsertionPointOfYoungerShadowRoot(0);
}
} // namespace
diff --git a/chromium/third_party/WebKit/Source/core/dom/shadow/ElementShadow.h b/chromium/third_party/WebKit/Source/core/dom/shadow/ElementShadow.h
index 8ac38e9e585..9017ddcafb7 100644
--- a/chromium/third_party/WebKit/Source/core/dom/shadow/ElementShadow.h
+++ b/chromium/third_party/WebKit/Source/core/dom/shadow/ElementShadow.h
@@ -27,6 +27,7 @@
#ifndef ElementShadow_h
#define ElementShadow_h
+#include "core/dom/shadow/InsertionPoint.h"
#include "core/dom/shadow/SelectRuleFeatureSet.h"
#include "core/dom/shadow/ShadowRoot.h"
#include "wtf/DoublyLinkedList.h"
@@ -38,8 +39,6 @@
namespace WebCore {
-class InsertionPoint;
-
class ElementShadow {
WTF_MAKE_NONCOPYABLE(ElementShadow); WTF_MAKE_FAST_ALLOCATED;
public:
@@ -51,7 +50,7 @@ public:
ShadowRoot* oldestShadowRoot() const { return m_shadowRoots.tail(); }
ElementShadow* containingShadow() const;
- ShadowRoot* addShadowRoot(Element* shadowHost, ShadowRoot::ShadowRootType);
+ ShadowRoot& addShadowRoot(Element& shadowHost, ShadowRoot::ShadowRootType);
bool applyAuthorStyles() const { return m_applyAuthorStyles; }
bool didAffectApplyAuthorStyles();
@@ -69,7 +68,10 @@ public:
void distributeIfNeeded();
void setNeedsDistributionRecalc();
- InsertionPoint* findInsertionPointFor(const Node*) const;
+ const InsertionPoint* finalDestinationInsertionPointFor(const Node*) const;
+ const DestinationInsertionPoints* destinationInsertionPointsFor(const Node*) const;
+
+ void didDistributeNode(const Node*, InsertionPoint*);
private:
ElementShadow();
@@ -79,15 +81,16 @@ private:
void distribute();
void clearDistribution();
- void populate(Node*, Vector<Node*>&);
- void collectSelectFeatureSetFrom(ShadowRoot*);
- void distributeSelectionsTo(InsertionPoint*, const Vector<Node*>& pool, Vector<bool>& distributed);
+
+ void collectSelectFeatureSetFrom(ShadowRoot&);
void distributeNodeChildrenTo(InsertionPoint*, ContainerNode*);
bool needsSelectFeatureSet() const { return m_needsSelectFeatureSet; }
void setNeedsSelectFeatureSet() { m_needsSelectFeatureSet = true; }
- HashMap<const Node*, RefPtr<InsertionPoint> > m_nodeToInsertionPoint;
+ typedef HashMap<const Node*, DestinationInsertionPoints> NodeToDestinationInsertionPoints;
+ NodeToDestinationInsertionPoints m_nodeToInsertionPoints;
+
SelectRuleFeatureSet m_selectFeatures;
DoublyLinkedList<ShadowRoot> m_shadowRoots;
bool m_needsDistributionRecalc;
@@ -103,9 +106,14 @@ inline Element* ElementShadow::host() const
inline ShadowRoot* Node::youngestShadowRoot() const
{
- if (!this->isElementNode())
+ if (!isElementNode())
return 0;
- if (ElementShadow* shadow = toElement(this)->shadow())
+ return toElement(this)->youngestShadowRoot();
+}
+
+inline ShadowRoot* Element::youngestShadowRoot() const
+{
+ if (ElementShadow* shadow = this->shadow())
return shadow->youngestShadowRoot();
return 0;
}
@@ -124,16 +132,6 @@ inline void ElementShadow::distributeIfNeeded()
m_needsDistributionRecalc = false;
}
-inline ElementShadow* shadowOfParent(const Node* node)
-{
- if (!node)
- return 0;
- if (Node* parent = node->parentNode())
- if (parent->isElementNode())
- return toElement(parent)->shadow();
- return 0;
-}
-
} // namespace
#endif
diff --git a/chromium/third_party/WebKit/Source/core/dom/shadow/InsertionPoint.cpp b/chromium/third_party/WebKit/Source/core/dom/shadow/InsertionPoint.cpp
index 7d05daaf2b3..e3c5d4df9fc 100644
--- a/chromium/third_party/WebKit/Source/core/dom/shadow/InsertionPoint.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/shadow/InsertionPoint.cpp
@@ -32,10 +32,12 @@
#include "core/dom/shadow/InsertionPoint.h"
#include "HTMLNames.h"
+#include "core/dom/ElementTraversal.h"
#include "core/dom/QualifiedName.h"
#include "core/dom/StaticNodeList.h"
#include "core/dom/shadow/ElementShadow.h"
-#include "core/dom/shadow/ShadowRoot.h"
+#include "core/html/shadow/HTMLContentElement.h"
+#include "core/html/shadow/HTMLShadowElement.h"
namespace WebCore {
@@ -97,10 +99,12 @@ void InsertionPoint::setDistribution(ContentDistribution& distribution)
void InsertionPoint::attach(const AttachContext& context)
{
- // FIXME: This loop shouldn't be needed since the distributed nodes should
- // never be detached, we can probably remove it.
+ // We need to attach the distribution here so that they're inserted in the right order
+ // otherwise the n^2 protection inside NodeRenderingContext will cause them to be
+ // inserted in the wrong place later. This also lets distributed nodes benefit from
+ // the n^2 protection.
for (size_t i = 0; i < m_distribution.size(); ++i) {
- if (!m_distribution.at(i)->attached())
+ if (m_distribution.at(i)->needsAttach())
m_distribution.at(i)->attach(context);
}
@@ -128,20 +132,53 @@ bool InsertionPoint::shouldUseFallbackElements() const
return isActive() && !hasDistribution();
}
-bool InsertionPoint::isActive() const
+bool InsertionPoint::canBeActive() const
{
- if (!containingShadowRoot())
+ if (!isInShadowTree())
return false;
- const Node* node = parentNode();
- while (node) {
- if (node->isInsertionPoint())
- return false;
+ bool foundShadowElementInAncestors = false;
+ bool thisIsContentHTMLElement = isHTMLContentElement(this);
+ for (Node* node = parentNode(); node; node = node->parentNode()) {
+ if (node->isInsertionPoint()) {
+ // For HTMLContentElement, at most one HTMLShadowElement may appear in its ancestors.
+ if (thisIsContentHTMLElement && isHTMLShadowElement(node) && !foundShadowElementInAncestors)
+ foundShadowElementInAncestors = true;
+ else
+ return false;
+ }
+ }
+ return true;
+}
- node = node->parentNode();
+bool InsertionPoint::isActive() const
+{
+ if (!canBeActive())
+ return false;
+ ShadowRoot* shadowRoot = containingShadowRoot();
+ ASSERT(shadowRoot);
+ if (!isHTMLShadowElement(this) || shadowRoot->descendantShadowElementCount() <= 1)
+ return true;
+
+ // Slow path only when there are more than one shadow elements in a shadow tree. That should be a rare case.
+ const Vector<RefPtr<InsertionPoint> >& insertionPoints = shadowRoot->descendantInsertionPoints();
+ for (size_t i = 0; i < insertionPoints.size(); ++i) {
+ InsertionPoint* point = insertionPoints[i].get();
+ if (isHTMLShadowElement(point))
+ return point == this;
}
return true;
}
+bool InsertionPoint::isShadowInsertionPoint() const
+{
+ return isHTMLShadowElement(this) && isActive();
+}
+
+bool InsertionPoint::isContentInsertionPoint() const
+{
+ return isHTMLContentElement(this) && isActive();
+}
+
PassRefPtr<NodeList> InsertionPoint::getDistributedNodes()
{
document().updateDistributionForNodeIfNeeded(this);
@@ -171,13 +208,12 @@ void InsertionPoint::childrenChanged(bool changedByParser, Node* beforeChange, N
Node::InsertionNotificationRequest InsertionPoint::insertedInto(ContainerNode* insertionPoint)
{
HTMLElement::insertedInto(insertionPoint);
-
if (ShadowRoot* root = containingShadowRoot()) {
if (ElementShadow* rootOwner = root->owner()) {
rootOwner->setNeedsDistributionRecalc();
- if (isActive() && !m_registeredWithShadowRoot && insertionPoint->treeScope().rootNode() == root) {
+ if (canBeActive() && !m_registeredWithShadowRoot && insertionPoint->treeScope().rootNode() == root) {
m_registeredWithShadowRoot = true;
- root->addInsertionPoint(this);
+ root->didAddInsertionPoint(this);
rootOwner->didAffectApplyAuthorStyles();
if (canAffectSelector())
rootOwner->willAffectSelector();
@@ -208,7 +244,7 @@ void InsertionPoint::removedFrom(ContainerNode* insertionPoint)
if (m_registeredWithShadowRoot && insertionPoint->treeScope().rootNode() == root) {
ASSERT(root);
m_registeredWithShadowRoot = false;
- root->removeInsertionPoint(this);
+ root->didRemoveInsertionPoint(this);
if (rootOwner) {
rootOwner->didAffectApplyAuthorStyles();
if (canAffectSelector())
@@ -222,7 +258,7 @@ void InsertionPoint::removedFrom(ContainerNode* insertionPoint)
void InsertionPoint::parseAttribute(const QualifiedName& name, const AtomicString& value)
{
if (name == reset_style_inheritanceAttr) {
- if (!inDocument() || !attached() || !isActive())
+ if (!inDocument() || !isActive())
return;
containingShadowRoot()->host()->setNeedsStyleRecalc();
} else
@@ -239,53 +275,43 @@ void InsertionPoint::setResetStyleInheritance(bool value)
setBooleanAttribute(reset_style_inheritanceAttr, value);
}
-InsertionPoint* resolveReprojection(const Node* projectedNode)
+const InsertionPoint* resolveReprojection(const Node* projectedNode)
{
- InsertionPoint* insertionPoint = 0;
+ ASSERT(projectedNode);
+ const InsertionPoint* insertionPoint = 0;
const Node* current = projectedNode;
-
- while (current) {
- if (ElementShadow* shadow = shadowOfParentForDistribution(current)) {
- if (InsertionPoint* insertedTo = shadow->findInsertionPointFor(projectedNode)) {
- current = insertedTo;
- insertionPoint = insertedTo;
- continue;
- }
- }
-
- if (Node* parent = parentNodeForDistribution(current)) {
- if (InsertionPoint* insertedTo = parent->isShadowRoot() ? toShadowRoot(parent)->insertionPoint() : 0) {
- current = insertedTo;
- insertionPoint = insertedTo;
- continue;
- }
- }
-
- break;
+ ElementShadow* lastElementShadow = 0;
+ while (true) {
+ ElementShadow* shadow = shadowWhereNodeCanBeDistributed(*current);
+ if (!shadow || shadow == lastElementShadow)
+ break;
+ lastElementShadow = shadow;
+ const InsertionPoint* insertedTo = shadow->finalDestinationInsertionPointFor(projectedNode);
+ if (!insertedTo)
+ break;
+ ASSERT(current != insertedTo);
+ current = insertedTo;
+ insertionPoint = insertedTo;
}
-
return insertionPoint;
}
-void collectInsertionPointsWhereNodeIsDistributed(const Node* node, Vector<InsertionPoint*, 8>& results)
+void collectDestinationInsertionPoints(const Node& node, Vector<InsertionPoint*, 8>& results)
{
- const Node* current = node;
+ const Node* current = &node;
+ ElementShadow* lastElementShadow = 0;
while (true) {
- if (ElementShadow* shadow = shadowOfParentForDistribution(current)) {
- if (InsertionPoint* insertedTo = shadow->findInsertionPointFor(node)) {
- current = insertedTo;
- results.append(insertedTo);
- continue;
- }
- }
- if (Node* parent = parentNodeForDistribution(current)) {
- if (InsertionPoint* insertedTo = parent->isShadowRoot() ? toShadowRoot(parent)->insertionPoint() : 0) {
- current = insertedTo;
- results.append(insertedTo);
- continue;
- }
- }
- return;
+ ElementShadow* shadow = shadowWhereNodeCanBeDistributed(*current);
+ if (!shadow || shadow == lastElementShadow)
+ return;
+ lastElementShadow = shadow;
+ const DestinationInsertionPoints* insertionPoints = shadow->destinationInsertionPointsFor(&node);
+ if (!insertionPoints)
+ return;
+ for (size_t i = 0; i < insertionPoints->size(); ++i)
+ results.append(insertionPoints->at(i).get());
+ ASSERT(current != insertionPoints->last().get());
+ current = insertionPoints->last().get();
}
}
diff --git a/chromium/third_party/WebKit/Source/core/dom/shadow/InsertionPoint.h b/chromium/third_party/WebKit/Source/core/dom/shadow/InsertionPoint.h
index d12423b34ab..05f2ac9e070 100644
--- a/chromium/third_party/WebKit/Source/core/dom/shadow/InsertionPoint.h
+++ b/chromium/third_party/WebKit/Source/core/dom/shadow/InsertionPoint.h
@@ -33,6 +33,7 @@
#include "core/css/CSSSelectorList.h"
#include "core/dom/shadow/ContentDistribution.h"
+#include "core/dom/shadow/ShadowRoot.h"
#include "core/html/HTMLElement.h"
#include "wtf/Forward.h"
@@ -46,6 +47,10 @@ public:
void setDistribution(ContentDistribution&);
void clearDistribution() { m_distribution.clear(); }
bool isActive() const;
+ bool canBeActive() const;
+
+ bool isShadowInsertionPoint() const;
+ bool isContentInsertionPoint() const;
PassRefPtr<NodeList> getDistributedNodes();
@@ -76,63 +81,41 @@ protected:
virtual void willRecalcStyle(StyleRecalcChange) OVERRIDE;
private:
-
ContentDistribution m_distribution;
bool m_registeredWithShadowRoot;
};
-inline InsertionPoint* toInsertionPoint(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->isInsertionPoint());
- return static_cast<InsertionPoint*>(node);
-}
+typedef Vector<RefPtr<InsertionPoint> > DestinationInsertionPoints;
-inline const InsertionPoint* toInsertionPoint(const Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->isInsertionPoint());
- return static_cast<const InsertionPoint*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(InsertionPoint, isInsertionPoint());
-inline bool isActiveInsertionPoint(const Node* node)
+inline bool isActiveInsertionPoint(const Node& node)
{
- return node->isInsertionPoint() && toInsertionPoint(node)->isActive();
+ return node.isInsertionPoint() && toInsertionPoint(node).isActive();
}
-inline Node* parentNodeForDistribution(const Node* node)
+inline bool isActiveShadowInsertionPoint(const Node& node)
{
- ASSERT(node);
-
- if (Node* parent = node->parentNode()) {
- if (parent->isInsertionPoint() && toInsertionPoint(parent)->shouldUseFallbackElements())
- return parent->parentNode();
- return parent;
- }
-
- return 0;
+ return node.isInsertionPoint() && toInsertionPoint(node).isShadowInsertionPoint();
}
-inline Element* parentElementForDistribution(const Node* node)
+inline ElementShadow* shadowWhereNodeCanBeDistributed(const Node& node)
{
- if (Node* parent = parentNodeForDistribution(node)) {
- if (parent->isElementNode())
- return toElement(parent);
- }
-
- return 0;
-}
-
-inline ElementShadow* shadowOfParentForDistribution(const Node* node)
-{
- ASSERT(node);
- if (Element* parent = parentElementForDistribution(node))
- return parent->shadow();
-
+ Node* parent = node.parentNode();
+ if (!parent)
+ return 0;
+ if (parent->isShadowRoot() && !toShadowRoot(parent)->isYoungest())
+ return node.shadowHost()->shadow();
+ if (isActiveInsertionPoint(*parent))
+ return node.shadowHost()->shadow();
+ if (parent->isElementNode())
+ return toElement(parent)->shadow();
return 0;
}
-InsertionPoint* resolveReprojection(const Node*);
+const InsertionPoint* resolveReprojection(const Node*);
-void collectInsertionPointsWhereNodeIsDistributed(const Node*, Vector<InsertionPoint*, 8>& results);
+void collectDestinationInsertionPoints(const Node&, Vector<InsertionPoint*, 8>& results);
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/shadow/ShadowRoot.cpp b/chromium/third_party/WebKit/Source/core/dom/shadow/ShadowRoot.cpp
index a0296245d0b..c9f7909eae3 100644
--- a/chromium/third_party/WebKit/Source/core/dom/shadow/ShadowRoot.cpp
+++ b/chromium/third_party/WebKit/Source/core/dom/shadow/ShadowRoot.cpp
@@ -27,18 +27,17 @@
#include "config.h"
#include "core/dom/shadow/ShadowRoot.h"
-#include "bindings/v8/ExceptionMessages.h"
#include "bindings/v8/ExceptionState.h"
+#include "core/css/StyleSheetList.h"
#include "core/css/resolver/StyleResolver.h"
#include "core/dom/ElementTraversal.h"
#include "core/dom/StyleEngine.h"
#include "core/dom/Text.h"
-#include "core/dom/WhitespaceChildList.h"
#include "core/dom/shadow/ElementShadow.h"
#include "core/dom/shadow/InsertionPoint.h"
#include "core/dom/shadow/ShadowRootRareData.h"
#include "core/editing/markup.h"
-#include "core/platform/HistogramSupport.h"
+#include "public/platform/Platform.h"
namespace WebCore {
@@ -65,14 +64,14 @@ ShadowRoot::ShadowRoot(Document* document, ShadowRootType type)
, m_resetStyleInheritance(false)
, m_type(type)
, m_registeredWithParentShadowRoot(false)
- , m_childInsertionPointsIsValid(false)
+ , m_descendantInsertionPointsIsValid(false)
{
ASSERT(document);
ScriptWrappable::init(this);
if (type == ShadowRoot::AuthorShadowRoot) {
ShadowRootUsageOriginType usageType = document->url().protocolIsInHTTPFamily() ? ShadowRootUsageOriginWeb : ShadowRootUsageOriginNotWeb;
- HistogramSupport::histogramEnumeration("WebCore.ShadowRoot.constructor", usageType, ShadowRootUsageOriginMax);
+ blink::Platform::current()->histogramEnumeration("WebCore.ShadowRoot.constructor", usageType, ShadowRootUsageOriginMax);
}
}
@@ -81,13 +80,16 @@ ShadowRoot::~ShadowRoot()
ASSERT(!m_prev);
ASSERT(!m_next);
+ if (m_shadowRootRareData && m_shadowRootRareData->styleSheets())
+ m_shadowRootRareData->styleSheets()->detachFromDocument();
+
documentInternal()->styleEngine()->didRemoveShadowRoot(this);
- // We cannot let ContainerNode destructor call willBeDeletedFrom()
+ // We cannot let ContainerNode destructor call willBeDeletedFromDocument()
// for this ShadowRoot instance because TreeScope destructor
// clears Node::m_treeScope thus ContainerNode is no longer able
// to access it Document reference after that.
- willBeDeletedFrom(documentInternal());
+ willBeDeletedFromDocument();
// We must remove all of our children first before the TreeScope destructor
// runs so we don't go through TreeScopeAdopter for each child with a
@@ -123,9 +125,9 @@ bool ShadowRoot::isOldestAuthorShadowRoot() const
return true;
}
-PassRefPtr<Node> ShadowRoot::cloneNode(bool, ExceptionState& es)
+PassRefPtr<Node> ShadowRoot::cloneNode(bool, ExceptionState& exceptionState)
{
- es.throwDOMException(DataCloneError, ExceptionMessages::failedToExecute("cloneNode", "ShadowRoot", "ShadowRoot nodes are not clonable."));
+ exceptionState.throwDOMException(DataCloneError, "ShadowRoot nodes are not clonable.");
return 0;
}
@@ -134,15 +136,15 @@ String ShadowRoot::innerHTML() const
return createMarkup(this, ChildrenOnly);
}
-void ShadowRoot::setInnerHTML(const String& markup, ExceptionState& es)
+void ShadowRoot::setInnerHTML(const String& markup, ExceptionState& exceptionState)
{
if (isOrphan()) {
- es.throwDOMException(InvalidAccessError, ExceptionMessages::failedToExecute("setInnerHTML", "ShadowRoot", "The ShadowRoot does not have a host."));
+ exceptionState.throwDOMException(InvalidAccessError, "The ShadowRoot does not have a host.");
return;
}
- if (RefPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(markup, host(), AllowScriptingContent, es))
- replaceChildrenWithFragment(this, fragment.release(), es);
+ if (RefPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(markup, host(), AllowScriptingContent, "innerHTML", exceptionState))
+ replaceChildrenWithFragment(this, fragment.release(), exceptionState);
}
bool ShadowRoot::childTypeAllowed(NodeType type) const
@@ -164,38 +166,31 @@ void ShadowRoot::recalcStyle(StyleRecalcChange change)
// ShadowRoot doesn't support custom callbacks.
ASSERT(!hasCustomStyleCallbacks());
- StyleResolver* styleResolver = document().styleResolver();
- styleResolver->pushParentShadowRoot(*this);
-
- if (!attached()) {
- attach();
- return;
- }
+ StyleResolver& styleResolver = document().ensureStyleResolver();
+ styleResolver.pushParentShadowRoot(*this);
- // When we're set to lazyAttach we'll have a SubtreeStyleChange and we'll need
- // to promote the change to a Force for all our descendants so they get a
- // recalc and will attach.
if (styleChangeType() >= SubtreeStyleChange)
change = Force;
+ // There's no style to update so just calling recalcStyle means we're updated.
+ clearNeedsStyleRecalc();
+
// FIXME: This doesn't handle :hover + div properly like Element::recalcStyle does.
- WhitespaceChildList whitespaceChildList(change);
+ Text* lastTextNode = 0;
for (Node* child = lastChild(); child; child = child->previousSibling()) {
if (child->isTextNode()) {
- Text* textChild = toText(child);
- if (textChild->containsOnlyWhitespace())
- whitespaceChildList.append(textChild);
- else
- textChild->recalcTextStyle(change);
- } else if (child->isElementNode() && shouldRecalcStyle(change, child)) {
- toElement(child)->recalcStyle(change);
+ toText(child)->recalcTextStyle(change, lastTextNode);
+ lastTextNode = toText(child);
+ } else if (child->isElementNode()) {
+ if (shouldRecalcStyle(change, child))
+ toElement(child)->recalcStyle(change, lastTextNode);
+ if (child->renderer())
+ lastTextNode = 0;
}
}
- whitespaceChildList.recalcStyle();
+ styleResolver.popParentShadowRoot(*this);
- styleResolver->popParentShadowRoot(*this);
- clearNeedsStyleRecalc();
clearChildNeedsStyleRecalc();
}
@@ -212,7 +207,7 @@ void ShadowRoot::setApplyAuthorStyles(bool value)
if (isOrphan())
return;
- if (m_applyAuthorStyles == value)
+ if (applyAuthorStyles() == value)
return;
m_applyAuthorStyles = value;
@@ -238,7 +233,7 @@ void ShadowRoot::setResetStyleInheritance(bool value)
if (isOrphan())
return;
- if (value == m_resetStyleInheritance)
+ if (value == resetStyleInheritance())
return;
m_resetStyleInheritance = value;
@@ -250,10 +245,10 @@ void ShadowRoot::setResetStyleInheritance(bool value)
void ShadowRoot::attach(const AttachContext& context)
{
- StyleResolver* styleResolver = document().styleResolver();
- styleResolver->pushParentShadowRoot(*this);
+ StyleResolver& styleResolver = document().ensureStyleResolver();
+ styleResolver.pushParentShadowRoot(*this);
DocumentFragment::attach(context);
- styleResolver->popParentShadowRoot(*this);
+ styleResolver.popParentShadowRoot(*this);
}
Node::InsertionNotificationRequest ShadowRoot::insertedInto(ContainerNode* insertionPoint)
@@ -294,7 +289,7 @@ void ShadowRoot::removedFrom(ContainerNode* insertionPoint)
void ShadowRoot::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
{
ContainerNode::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
- if (InsertionPoint* point = insertionPoint()) {
+ if (InsertionPoint* point = shadowInsertionPointOfYoungerShadowRoot()) {
if (ShadowRoot* root = point->containingShadowRoot())
root->owner()->setNeedsDistributionRecalc();
}
@@ -324,46 +319,51 @@ ShadowRootRareData* ShadowRoot::ensureShadowRootRareData()
bool ShadowRoot::containsShadowElements() const
{
- return m_shadowRootRareData ? m_shadowRootRareData->hasShadowElementChildren() : 0;
+ return m_shadowRootRareData ? m_shadowRootRareData->containsShadowElements() : 0;
}
bool ShadowRoot::containsContentElements() const
{
- return m_shadowRootRareData ? m_shadowRootRareData->hasContentElementChildren() : 0;
+ return m_shadowRootRareData ? m_shadowRootRareData->containsContentElements() : 0;
}
bool ShadowRoot::containsShadowRoots() const
{
- return m_shadowRootRareData ? m_shadowRootRareData->hasShadowRootChildren() : 0;
+ return m_shadowRootRareData ? m_shadowRootRareData->containsShadowRoots() : 0;
}
-InsertionPoint* ShadowRoot::insertionPoint() const
+unsigned ShadowRoot::descendantShadowElementCount() const
{
- return m_shadowRootRareData ? m_shadowRootRareData->insertionPoint() : 0;
+ return m_shadowRootRareData ? m_shadowRootRareData->descendantShadowElementCount() : 0;
}
-void ShadowRoot::setInsertionPoint(PassRefPtr<InsertionPoint> insertionPoint)
+HTMLShadowElement* ShadowRoot::shadowInsertionPointOfYoungerShadowRoot() const
{
- if (!m_shadowRootRareData && !insertionPoint)
+ return m_shadowRootRareData ? m_shadowRootRareData->shadowInsertionPointOfYoungerShadowRoot() : 0;
+}
+
+void ShadowRoot::setShadowInsertionPointOfYoungerShadowRoot(PassRefPtr<HTMLShadowElement> shadowInsertionPoint)
+{
+ if (!m_shadowRootRareData && !shadowInsertionPoint)
return;
- ensureShadowRootRareData()->setInsertionPoint(insertionPoint);
+ ensureShadowRootRareData()->setShadowInsertionPointOfYoungerShadowRoot(shadowInsertionPoint);
}
-void ShadowRoot::addInsertionPoint(InsertionPoint* insertionPoint)
+void ShadowRoot::didAddInsertionPoint(InsertionPoint* insertionPoint)
{
- ensureShadowRootRareData()->addInsertionPoint(insertionPoint);
- invalidateChildInsertionPoints();
+ ensureShadowRootRareData()->didAddInsertionPoint(insertionPoint);
+ invalidateDescendantInsertionPoints();
}
-void ShadowRoot::removeInsertionPoint(InsertionPoint* insertionPoint)
+void ShadowRoot::didRemoveInsertionPoint(InsertionPoint* insertionPoint)
{
- m_shadowRootRareData->removeInsertionPoint(insertionPoint);
- invalidateChildInsertionPoints();
+ m_shadowRootRareData->didRemoveInsertionPoint(insertionPoint);
+ invalidateDescendantInsertionPoints();
}
void ShadowRoot::addChildShadowRoot()
{
- ensureShadowRootRareData()->addChildShadowRoot();
+ ensureShadowRootRareData()->didAddChildShadowRoot();
}
void ShadowRoot::removeChildShadowRoot()
@@ -371,7 +371,7 @@ void ShadowRoot::removeChildShadowRoot()
// FIXME: Why isn't this an ASSERT?
if (!m_shadowRootRareData)
return;
- m_shadowRootRareData->removeChildShadowRoot();
+ m_shadowRootRareData->didRemoveChildShadowRoot();
}
unsigned ShadowRoot::childShadowRootCount() const
@@ -379,33 +379,41 @@ unsigned ShadowRoot::childShadowRootCount() const
return m_shadowRootRareData ? m_shadowRootRareData->childShadowRootCount() : 0;
}
-void ShadowRoot::invalidateChildInsertionPoints()
+void ShadowRoot::invalidateDescendantInsertionPoints()
{
- m_childInsertionPointsIsValid = false;
- m_shadowRootRareData->clearChildInsertionPoints();
+ m_descendantInsertionPointsIsValid = false;
+ m_shadowRootRareData->clearDescendantInsertionPoints();
}
-const Vector<RefPtr<InsertionPoint> >& ShadowRoot::childInsertionPoints()
+const Vector<RefPtr<InsertionPoint> >& ShadowRoot::descendantInsertionPoints()
{
DEFINE_STATIC_LOCAL(const Vector<RefPtr<InsertionPoint> >, emptyList, ());
- if (m_shadowRootRareData && m_childInsertionPointsIsValid)
- return m_shadowRootRareData->childInsertionPoints();
+ if (m_shadowRootRareData && m_descendantInsertionPointsIsValid)
+ return m_shadowRootRareData->descendantInsertionPoints();
- m_childInsertionPointsIsValid = true;
+ m_descendantInsertionPointsIsValid = true;
if (!containsInsertionPoints())
return emptyList;
Vector<RefPtr<InsertionPoint> > insertionPoints;
- for (Element* element = ElementTraversal::firstWithin(this); element; element = ElementTraversal::next(element, this)) {
+ for (Element* element = ElementTraversal::firstWithin(*this); element; element = ElementTraversal::next(*element, this)) {
if (element->isInsertionPoint())
insertionPoints.append(toInsertionPoint(element));
}
- ensureShadowRootRareData()->setChildInsertionPoints(insertionPoints);
+ ensureShadowRootRareData()->setDescendantInsertionPoints(insertionPoints);
+
+ return m_shadowRootRareData->descendantInsertionPoints();
+}
+
+StyleSheetList* ShadowRoot::styleSheets()
+{
+ if (!ensureShadowRootRareData()->styleSheets())
+ m_shadowRootRareData->setStyleSheets(StyleSheetList::create(this));
- return m_shadowRootRareData->childInsertionPoints();
+ return m_shadowRootRareData->styleSheets();
}
}
diff --git a/chromium/third_party/WebKit/Source/core/dom/shadow/ShadowRoot.h b/chromium/third_party/WebKit/Source/core/dom/shadow/ShadowRoot.h
index 99bdf973891..62fd4238ad1 100644
--- a/chromium/third_party/WebKit/Source/core/dom/shadow/ShadowRoot.h
+++ b/chromium/third_party/WebKit/Source/core/dom/shadow/ShadowRoot.h
@@ -38,6 +38,7 @@ namespace WebCore {
class ElementShadow;
class ExceptionState;
+class HTMLShadowElement;
class InsertionPoint;
class ShadowRootRareData;
@@ -60,21 +61,10 @@ public:
void recalcStyle(StyleRecalcChange);
- bool applyAuthorStyles() const { return m_applyAuthorStyles; }
- void setApplyAuthorStyles(bool);
- bool resetStyleInheritance() const { return m_resetStyleInheritance; }
- void setResetStyleInheritance(bool);
-
Element* host() const { return toElement(parentOrShadowHostNode()); }
ElementShadow* owner() const { return host() ? host()->shadow() : 0; }
- String innerHTML() const;
- void setInnerHTML(const String&, ExceptionState&);
-
- Element* activeElement() const;
-
ShadowRoot* youngerShadowRoot() const { return prev(); }
- ShadowRoot* olderShadowRoot() const { return next(); }
ShadowRoot* bindingsOlderShadowRoot() const;
bool shouldExposeToBindings() const { return type() == AuthorShadowRoot; }
@@ -96,20 +86,38 @@ public:
bool containsInsertionPoints() const { return containsShadowElements() || containsContentElements(); }
bool containsShadowRoots() const;
+ unsigned descendantShadowElementCount() const;
+
// For Internals, don't use this.
unsigned childShadowRootCount() const;
- InsertionPoint* insertionPoint() const;
- void setInsertionPoint(PassRefPtr<InsertionPoint>);
+ HTMLShadowElement* shadowInsertionPointOfYoungerShadowRoot() const;
+ void setShadowInsertionPointOfYoungerShadowRoot(PassRefPtr<HTMLShadowElement>);
- void addInsertionPoint(InsertionPoint*);
- void removeInsertionPoint(InsertionPoint*);
- const Vector<RefPtr<InsertionPoint> >& childInsertionPoints();
+ void didAddInsertionPoint(InsertionPoint*);
+ void didRemoveInsertionPoint(InsertionPoint*);
+ const Vector<RefPtr<InsertionPoint> >& descendantInsertionPoints();
ShadowRootType type() const { return static_cast<ShadowRootType>(m_type); }
+public:
+ Element* activeElement() const;
+
+ bool applyAuthorStyles() const { return m_applyAuthorStyles; }
+ void setApplyAuthorStyles(bool);
+
+ bool resetStyleInheritance() const { return m_resetStyleInheritance; }
+ void setResetStyleInheritance(bool);
+
+ ShadowRoot* olderShadowRoot() const { return next(); }
+
+ String innerHTML() const;
+ void setInnerHTML(const String&, ExceptionState&);
+
PassRefPtr<Node> cloneNode(bool, ExceptionState&);
- PassRefPtr<Node> cloneNode(ExceptionState& es) { return cloneNode(true, es); }
+ PassRefPtr<Node> cloneNode(ExceptionState& exceptionState) { return cloneNode(true, exceptionState); }
+
+ StyleSheetList* styleSheets();
private:
ShadowRoot(Document*, ShadowRootType);
@@ -123,7 +131,7 @@ private:
void addChildShadowRoot();
void removeChildShadowRoot();
- void invalidateChildInsertionPoints();
+ void invalidateDescendantInsertionPoints();
// ShadowRoots should never be cloned.
virtual PassRefPtr<Node> cloneNode(bool) OVERRIDE { return 0; }
@@ -140,49 +148,16 @@ private:
unsigned m_resetStyleInheritance : 1;
unsigned m_type : 1;
unsigned m_registeredWithParentShadowRoot : 1;
- unsigned m_childInsertionPointsIsValid : 1;
+ unsigned m_descendantInsertionPointsIsValid : 1;
};
inline Element* ShadowRoot::activeElement() const
{
- if (Element* element = treeScope().adjustedFocusedElement())
- return element;
- return 0;
-}
-
-inline const ShadowRoot* toShadowRoot(const Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->isShadowRoot());
- return static_cast<const ShadowRoot*>(node);
-}
-
-inline ShadowRoot* toShadowRoot(Node* node)
-{
- return const_cast<ShadowRoot*>(toShadowRoot(static_cast<const Node*>(node)));
+ return adjustedFocusedElement();
}
-inline const ShadowRoot& toShadowRoot(const Node& node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(node.isShadowRoot());
- return static_cast<const ShadowRoot&>(node);
-}
-
-inline const ShadowRoot* toShadowRoot(const TreeScope* treeScope)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!treeScope || (treeScope->rootNode() && treeScope->rootNode()->isShadowRoot()));
- return static_cast<const ShadowRoot*>(treeScope);
-}
-
-inline ShadowRoot* toShadowRoot(TreeScope* treeScope)
-{
- return const_cast<ShadowRoot*>(toShadowRoot(static_cast<const TreeScope*>(treeScope)));
-}
-
-inline ShadowRoot& toShadowRoot(TreeScope& treeScope)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(treeScope.rootNode() && treeScope.rootNode()->isShadowRoot());
- return static_cast<ShadowRoot&>(treeScope);
-}
+DEFINE_NODE_TYPE_CASTS(ShadowRoot, isShadowRoot());
+DEFINE_TYPE_CASTS(ShadowRoot, TreeScope, treeScope, treeScope->rootNode() && treeScope->rootNode()->isShadowRoot(), treeScope.rootNode() && treeScope.rootNode()->isShadowRoot());
} // namespace
diff --git a/chromium/third_party/WebKit/Source/core/dom/shadow/ShadowRoot.idl b/chromium/third_party/WebKit/Source/core/dom/shadow/ShadowRoot.idl
index 105c0081307..c84d177cba2 100644
--- a/chromium/third_party/WebKit/Source/core/dom/shadow/ShadowRoot.idl
+++ b/chromium/third_party/WebKit/Source/core/dom/shadow/ShadowRoot.idl
@@ -30,9 +30,9 @@
readonly attribute Element activeElement;
attribute boolean applyAuthorStyles;
attribute boolean resetStyleInheritance;
- [EnabledAtRuntime=ShadowDOM, ImplementedAs=bindingsOlderShadowRoot] readonly attribute ShadowRoot olderShadowRoot;
+ [RuntimeEnabled=ShadowDOM, ImplementedAs=bindingsOlderShadowRoot] readonly attribute ShadowRoot olderShadowRoot;
- [TreatNullAs=NullString, CustomElementCallbacks=Enable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds, SetterRaisesException] attribute DOMString innerHTML;
+ [TreatNullAs=NullString, CustomElementCallbacks, PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds, RaisesException=Setter] attribute DOMString innerHTML;
[RaisesException] Node cloneNode([Default=Undefined] optional boolean deep);
Selection getSelection();
@@ -44,4 +44,7 @@
Element elementFromPoint([Default=Undefined] optional long x,
[Default=Undefined] optional long y);
+
+ [RuntimeEnabled=ShadowDOM] readonly attribute StyleSheetList styleSheets;
+ [RuntimeEnabled=ShadowDOM] readonly attribute Element host;
};
diff --git a/chromium/third_party/WebKit/Source/core/dom/shadow/ShadowRootRareData.h b/chromium/third_party/WebKit/Source/core/dom/shadow/ShadowRootRareData.h
index 3a0966deedd..dae72a7837c 100644
--- a/chromium/third_party/WebKit/Source/core/dom/shadow/ShadowRootRareData.h
+++ b/chromium/third_party/WebKit/Source/core/dom/shadow/ShadowRootRareData.h
@@ -42,60 +42,66 @@ namespace WebCore {
class ShadowRootRareData {
public:
ShadowRootRareData()
- : m_childShadowElementCount(0)
- , m_childContentElementCount(0)
+ : m_descendantShadowElementCount(0)
+ , m_descendantContentElementCount(0)
, m_childShadowRootCount(0)
{
}
- InsertionPoint* insertionPoint() const { return m_insertionPoint.get(); }
- void setInsertionPoint(PassRefPtr<InsertionPoint> insertionPoint) { m_insertionPoint = insertionPoint; }
+ HTMLShadowElement* shadowInsertionPointOfYoungerShadowRoot() const { return m_shadowInsertionPointOfYoungerShadowRoot.get(); }
+ void setShadowInsertionPointOfYoungerShadowRoot(PassRefPtr<HTMLShadowElement> shadowInsertionPoint) { m_shadowInsertionPointOfYoungerShadowRoot = shadowInsertionPoint; }
- void addInsertionPoint(InsertionPoint*);
- void removeInsertionPoint(InsertionPoint*);
+ void didAddInsertionPoint(InsertionPoint*);
+ void didRemoveInsertionPoint(InsertionPoint*);
- bool hasShadowElementChildren() const { return m_childShadowElementCount; }
- bool hasContentElementChildren() const { return m_childContentElementCount; }
- bool hasShadowRootChildren() const { return m_childShadowRootCount; }
+ bool containsShadowElements() const { return m_descendantShadowElementCount; }
+ bool containsContentElements() const { return m_descendantContentElementCount; }
+ bool containsShadowRoots() const { return m_childShadowRootCount; }
- void addChildShadowRoot() { ++m_childShadowRootCount; }
- void removeChildShadowRoot() { ASSERT(m_childShadowRootCount > 0); --m_childShadowRootCount; }
+ unsigned descendantShadowElementCount() const { return m_descendantShadowElementCount; }
+
+ void didAddChildShadowRoot() { ++m_childShadowRootCount; }
+ void didRemoveChildShadowRoot() { ASSERT(m_childShadowRootCount > 0); --m_childShadowRootCount; }
unsigned childShadowRootCount() const { return m_childShadowRootCount; }
- const Vector<RefPtr<InsertionPoint> >& childInsertionPoints() { return m_childInsertionPoints; }
- void setChildInsertionPoints(Vector<RefPtr<InsertionPoint> >& list) { m_childInsertionPoints.swap(list); }
- void clearChildInsertionPoints() { m_childInsertionPoints.clear(); }
+ const Vector<RefPtr<InsertionPoint> >& descendantInsertionPoints() { return m_descendantInsertionPoints; }
+ void setDescendantInsertionPoints(Vector<RefPtr<InsertionPoint> >& list) { m_descendantInsertionPoints.swap(list); }
+ void clearDescendantInsertionPoints() { m_descendantInsertionPoints.clear(); }
+
+ StyleSheetList* styleSheets() { return m_styleSheetList.get(); }
+ void setStyleSheets(PassRefPtr<StyleSheetList> styleSheetList) { m_styleSheetList = styleSheetList; }
private:
- RefPtr<InsertionPoint> m_insertionPoint;
- unsigned m_childShadowElementCount;
- unsigned m_childContentElementCount;
+ RefPtr<HTMLShadowElement> m_shadowInsertionPointOfYoungerShadowRoot;
+ unsigned m_descendantShadowElementCount;
+ unsigned m_descendantContentElementCount;
unsigned m_childShadowRootCount;
- Vector<RefPtr<InsertionPoint> > m_childInsertionPoints;
+ Vector<RefPtr<InsertionPoint> > m_descendantInsertionPoints;
+ RefPtr<StyleSheetList> m_styleSheetList;
};
-inline void ShadowRootRareData::addInsertionPoint(InsertionPoint* point)
+inline void ShadowRootRareData::didAddInsertionPoint(InsertionPoint* point)
{
if (isHTMLShadowElement(point))
- ++m_childShadowElementCount;
+ ++m_descendantShadowElementCount;
else if (isHTMLContentElement(point))
- ++m_childContentElementCount;
+ ++m_descendantContentElementCount;
else
ASSERT_NOT_REACHED();
}
-inline void ShadowRootRareData::removeInsertionPoint(InsertionPoint* point)
+inline void ShadowRootRareData::didRemoveInsertionPoint(InsertionPoint* point)
{
if (isHTMLShadowElement(point))
- --m_childShadowElementCount;
+ --m_descendantShadowElementCount;
else if (isHTMLContentElement(point))
- --m_childContentElementCount;
+ --m_descendantContentElementCount;
else
ASSERT_NOT_REACHED();
- ASSERT(m_childContentElementCount >= 0);
- ASSERT(m_childShadowElementCount >= 0);
+ ASSERT(m_descendantContentElementCount >= 0);
+ ASSERT(m_descendantShadowElementCount >= 0);
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/editing/AppendNodeCommand.cpp b/chromium/third_party/WebKit/Source/core/editing/AppendNodeCommand.cpp
index e8047c9a913..0120ec0aa95 100644
--- a/chromium/third_party/WebKit/Source/core/editing/AppendNodeCommand.cpp
+++ b/chromium/third_party/WebKit/Source/core/editing/AppendNodeCommand.cpp
@@ -40,12 +40,12 @@ AppendNodeCommand::AppendNodeCommand(PassRefPtr<ContainerNode> parent, PassRefPt
ASSERT(m_node);
ASSERT(!m_node->parentNode());
- ASSERT(m_parent->rendererIsEditable() || !m_parent->attached());
+ ASSERT(m_parent->rendererIsEditable() || !m_parent->inActiveDocument());
}
void AppendNodeCommand::doApply()
{
- if (!m_parent->rendererIsEditable() && m_parent->attached())
+ if (!m_parent->rendererIsEditable() && m_parent->inActiveDocument())
return;
m_parent->appendChild(m_node.get(), IGNORE_EXCEPTION);
diff --git a/chromium/third_party/WebKit/Source/core/editing/ApplyBlockElementCommand.cpp b/chromium/third_party/WebKit/Source/core/editing/ApplyBlockElementCommand.cpp
index 938ee5b9abc..7049dacad0c 100644
--- a/chromium/third_party/WebKit/Source/core/editing/ApplyBlockElementCommand.cpp
+++ b/chromium/third_party/WebKit/Source/core/editing/ApplyBlockElementCommand.cpp
@@ -117,8 +117,9 @@ void ApplyBlockElementCommand::formatSelection(const VisiblePosition& startOfSel
RefPtr<Element> blockquoteForNextIndent;
VisiblePosition endOfCurrentParagraph = endOfParagraph(startOfSelection);
- VisiblePosition endAfterSelection = endOfParagraph(endOfParagraph(endOfSelection).next());
- m_endOfLastParagraph = endOfParagraph(endOfSelection).deepEquivalent();
+ VisiblePosition endOfLastParagraph = endOfParagraph(endOfSelection);
+ VisiblePosition endAfterSelection = endOfParagraph(endOfLastParagraph.next());
+ m_endOfLastParagraph = endOfLastParagraph.deepEquivalent();
bool atEnd = false;
Position end;
@@ -129,7 +130,6 @@ void ApplyBlockElementCommand::formatSelection(const VisiblePosition& startOfSel
rangeForParagraphSplittingTextNodesIfNeeded(endOfCurrentParagraph, start, end);
endOfCurrentParagraph = end;
- Position afterEnd = end.next();
Node* enclosingCell = enclosingNodeOfType(start, &isTableCell);
VisiblePosition endOfNextParagraph = endOfNextParagrahSplittingTextNodesIfNeeded(endOfCurrentParagraph, start, end);
@@ -146,11 +146,9 @@ void ApplyBlockElementCommand::formatSelection(const VisiblePosition& startOfSel
if (endAfterSelection.isNotNull() && !endAfterSelection.deepEquivalent().inDocument())
break;
// Sanity check: Make sure our moveParagraph calls didn't remove endOfNextParagraph.deepEquivalent().deprecatedNode()
- // If somehow we did, return to prevent crashes.
- if (endOfNextParagraph.isNotNull() && !endOfNextParagraph.deepEquivalent().inDocument()) {
- ASSERT_NOT_REACHED();
+ // If somehow, e.g. mutation event handler, we did, return to prevent crashes.
+ if (endOfNextParagraph.isNotNull() && !endOfNextParagraph.deepEquivalent().inDocument())
return;
- }
endOfCurrentParagraph = endOfNextParagraph;
}
}
@@ -162,9 +160,9 @@ static bool isNewLineAtPosition(const Position& position)
if (!textNode || !textNode->isTextNode() || offset < 0 || offset >= textNode->maxCharacterOffset())
return false;
- TrackExceptionState es;
- String textAtPosition = toText(textNode)->substringData(offset, 1, es);
- if (es.hadException())
+ TrackExceptionState exceptionState;
+ String textAtPosition = toText(textNode)->substringData(offset, 1, exceptionState);
+ if (exceptionState.hadException())
return false;
return textAtPosition[0] == '\n';
diff --git a/chromium/third_party/WebKit/Source/core/editing/ApplyStyleCommand.cpp b/chromium/third_party/WebKit/Source/core/editing/ApplyStyleCommand.cpp
index 43cc1ddea1e..35fa0e67c8a 100644
--- a/chromium/third_party/WebKit/Source/core/editing/ApplyStyleCommand.cpp
+++ b/chromium/third_party/WebKit/Source/core/editing/ApplyStyleCommand.cpp
@@ -39,6 +39,7 @@
#include "core/dom/Text.h"
#include "core/editing/EditingStyle.h"
#include "core/editing/HTMLInterchange.h"
+#include "core/editing/PlainTextRange.h"
#include "core/editing/TextIterator.h"
#include "core/editing/VisibleUnits.h"
#include "core/editing/htmlediting.h"
@@ -272,9 +273,9 @@ void ApplyStyleCommand::applyBlockStyle(EditingStyle *style)
}
ASSERT(!block || block->isHTMLElement());
if (block && block->isHTMLElement()) {
- removeCSSStyle(style, toHTMLElement(block.get()));
+ removeCSSStyle(style, toHTMLElement(block));
if (!m_removeOnly)
- addBlockStyle(styleChange, toHTMLElement(block.get()));
+ addBlockStyle(styleChange, toHTMLElement(block));
}
if (nextParagraphStart.isOrphan())
@@ -285,8 +286,8 @@ void ApplyStyleCommand::applyBlockStyle(EditingStyle *style)
nextParagraphStart = endOfParagraph(paragraphStart).next();
}
- startRange = TextIterator::rangeFromLocationAndLength(toContainerNode(scope), startIndex, 0, true);
- endRange = TextIterator::rangeFromLocationAndLength(toContainerNode(scope), endIndex, 0, true);
+ startRange = PlainTextRange(startIndex).createRangeForSelection(*toContainerNode(scope));
+ endRange = PlainTextRange(endIndex).createRangeForSelection(*toContainerNode(scope));
if (startRange && endRange)
updateStartEnd(startRange->startPosition(), endRange->startPosition());
}
@@ -350,26 +351,27 @@ void ApplyStyleCommand::applyRelativeFontStyleChange(EditingStyle* style)
// an ancestor of the start node), we gather nodes up to the next sibling of the end node
Node *beyondEnd;
if (start.deprecatedNode()->isDescendantOf(end.deprecatedNode()))
- beyondEnd = NodeTraversal::nextSkippingChildren(end.deprecatedNode());
+ beyondEnd = NodeTraversal::nextSkippingChildren(*end.deprecatedNode());
else
- beyondEnd = NodeTraversal::next(end.deprecatedNode());
+ beyondEnd = NodeTraversal::next(*end.deprecatedNode());
start = start.upstream(); // Move upstream to ensure we do not add redundant spans.
Node* startNode = start.deprecatedNode();
+ ASSERT(startNode);
if (startNode->isTextNode() && start.deprecatedEditingOffset() >= caretMaxOffset(startNode)) // Move out of text node if range does not include its characters.
- startNode = NodeTraversal::next(startNode);
+ startNode = NodeTraversal::next(*startNode);
// Store away font size before making any changes to the document.
// This ensures that changes to one node won't effect another.
HashMap<Node*, float> startingFontSizes;
- for (Node *node = startNode; node != beyondEnd; node = NodeTraversal::next(node))
+ for (Node* node = startNode; node != beyondEnd; node = NodeTraversal::next(*node))
startingFontSizes.set(node, computedFontSize(node));
// These spans were added by us. If empty after font size changes, they can be removed.
Vector<RefPtr<HTMLElement> > unstyledSpans;
Node* lastStyledNode = 0;
- for (Node* node = startNode; node != beyondEnd; node = NodeTraversal::next(node)) {
+ for (Node* node = startNode; node != beyondEnd; node = NodeTraversal::next(*node)) {
RefPtr<HTMLElement> element;
if (node->isHTMLElement()) {
// Only work on fully selected nodes.
@@ -398,7 +400,7 @@ void ApplyStyleCommand::applyRelativeFontStyleChange(EditingStyle* style)
}
if (currentFontSize != desiredFontSize) {
inlineStyle->setProperty(CSSPropertyFontSize, cssValuePool().createValue(desiredFontSize, CSSPrimitiveValue::CSS_PX), false);
- setNodeAttribute(element.get(), styleAttr, inlineStyle->asText());
+ setNodeAttribute(element.get(), styleAttr, AtomicString(inlineStyle->asText()));
}
if (inlineStyle->isEmpty()) {
removeNodeAttribute(element.get(), styleAttr);
@@ -434,7 +436,6 @@ void ApplyStyleCommand::cleanupUnstyledAppleStyleSpans(Node* dummySpanAncestor)
next = node->nextSibling();
if (isSpanWithoutAttributesOrUnstyledStyleSpan(node))
removeNodePreservingChildren(node);
- node = next;
}
}
@@ -518,7 +519,7 @@ void ApplyStyleCommand::removeEmbeddingUpToEnclosingBlock(Node* node, Node* unsp
RefPtr<MutableStylePropertySet> inlineStyle = copyStyleOrCreateEmpty(element->inlineStyle());
inlineStyle->setProperty(CSSPropertyUnicodeBidi, CSSValueNormal);
inlineStyle->removeProperty(CSSPropertyDirection);
- setNodeAttribute(element, styleAttr, inlineStyle->asText());
+ setNodeAttribute(element, styleAttr, AtomicString(inlineStyle->asText()));
if (isSpanWithoutAttributesOrUnstyledStyleSpan(element))
removeNodePreservingChildren(element);
}
@@ -671,21 +672,22 @@ void ApplyStyleCommand::applyInlineStyle(EditingStyle* style)
void ApplyStyleCommand::fixRangeAndApplyInlineStyle(EditingStyle* style, const Position& start, const Position& end)
{
Node* startNode = start.deprecatedNode();
+ ASSERT(startNode);
if (start.deprecatedEditingOffset() >= caretMaxOffset(start.deprecatedNode())) {
- startNode = NodeTraversal::next(startNode);
+ startNode = NodeTraversal::next(*startNode);
if (!startNode || comparePositions(end, firstPositionInOrBeforeNode(startNode)) < 0)
return;
}
Node* pastEndNode = end.deprecatedNode();
if (end.deprecatedEditingOffset() >= caretMaxOffset(end.deprecatedNode()))
- pastEndNode = NodeTraversal::nextSkippingChildren(end.deprecatedNode());
+ pastEndNode = NodeTraversal::nextSkippingChildren(*end.deprecatedNode());
// FIXME: Callers should perform this operation on a Range that includes the br
// if they want style applied to the empty line.
if (start == end && start.deprecatedNode()->hasTagName(brTag))
- pastEndNode = NodeTraversal::next(start.deprecatedNode());
+ pastEndNode = NodeTraversal::next(*start.deprecatedNode());
// Start from the highest fully selected ancestor so that we can modify the fully selected node.
// e.g. When applying font-size: large on <font color="blue">hello</font>, we need to include the font element in our run
@@ -700,13 +702,13 @@ void ApplyStyleCommand::fixRangeAndApplyInlineStyle(EditingStyle* style, const P
applyInlineStyleToNodeRange(style, startNode, pastEndNode);
}
-static bool containsNonEditableRegion(Node* node)
+static bool containsNonEditableRegion(Node& node)
{
- if (!node->rendererIsEditable())
+ if (!node.rendererIsEditable())
return true;
Node* sibling = NodeTraversal::nextSkippingChildren(node);
- for (Node* descendent = node->firstChild(); descendent && descendent != sibling; descendent = NodeTraversal::next(descendent)) {
+ for (Node* descendent = node.firstChild(); descendent && descendent != sibling; descendent = NodeTraversal::next(*descendent)) {
if (!descendent->rendererIsEditable())
return true;
}
@@ -746,7 +748,7 @@ void ApplyStyleCommand::applyInlineStyleToNodeRange(EditingStyle* style, PassRef
Vector<InlineRunToApplyStyle> runs;
RefPtr<Node> node = startNode;
for (RefPtr<Node> next; node && node != pastEndNode; node = next) {
- next = NodeTraversal::next(node.get());
+ next = NodeTraversal::next(*node);
if (!node->renderer() || !node->rendererIsEditable())
continue;
@@ -758,11 +760,13 @@ void ApplyStyleCommand::applyInlineStyleToNodeRange(EditingStyle* style, PassRef
if (pastEndNode && pastEndNode->isDescendantOf(node.get()))
break;
// Add to this element's inline style and skip over its contents.
- HTMLElement* element = toHTMLElement(node.get());
+ HTMLElement* element = toHTMLElement(node);
+ next = NodeTraversal::nextSkippingChildren(*node);
+ if (!style->style())
+ continue;
RefPtr<MutableStylePropertySet> inlineStyle = copyStyleOrCreateEmpty(element->inlineStyle());
inlineStyle->mergeAndOverrideOnConflict(style->style());
- setNodeAttribute(element, styleAttr, inlineStyle->asText());
- next = NodeTraversal::nextSkippingChildren(node.get());
+ setNodeAttribute(element, styleAttr, AtomicString(inlineStyle->asText()));
continue;
}
@@ -770,10 +774,10 @@ void ApplyStyleCommand::applyInlineStyleToNodeRange(EditingStyle* style, PassRef
continue;
if (node->childNodeCount()) {
- if (node->contains(pastEndNode.get()) || containsNonEditableRegion(node.get()) || !node->parentNode()->rendererIsEditable())
+ if (node->contains(pastEndNode.get()) || containsNonEditableRegion(*node) || !node->parentNode()->rendererIsEditable())
continue;
if (editingIgnoresContent(node.get())) {
- next = NodeTraversal::nextSkippingChildren(node.get());
+ next = NodeTraversal::nextSkippingChildren(*node);
continue;
}
}
@@ -782,14 +786,15 @@ void ApplyStyleCommand::applyInlineStyleToNodeRange(EditingStyle* style, PassRef
Node* runEnd = node.get();
Node* sibling = node->nextSibling();
while (sibling && sibling != pastEndNode && !sibling->contains(pastEndNode.get())
- && (!isBlock(sibling) || sibling->hasTagName(brTag))
- && !containsNonEditableRegion(sibling)) {
+ && (!isBlock(sibling) || sibling->hasTagName(brTag))
+ && !containsNonEditableRegion(*sibling)) {
runEnd = sibling;
sibling = runEnd->nextSibling();
}
- next = NodeTraversal::nextSkippingChildren(runEnd);
+ ASSERT(runEnd);
+ next = NodeTraversal::nextSkippingChildren(*runEnd);
- Node* pastEndNode = NodeTraversal::nextSkippingChildren(runEnd);
+ Node* pastEndNode = NodeTraversal::nextSkippingChildren(*runEnd);
if (!shouldApplyInlineStyleToRun(style, runStart, pastEndNode))
continue;
@@ -825,7 +830,7 @@ bool ApplyStyleCommand::shouldApplyInlineStyleToRun(EditingStyle* style, Node* r
{
ASSERT(style && runStart);
- for (Node* node = runStart; node && node != pastEndNode; node = NodeTraversal::next(node)) {
+ for (Node* node = runStart; node && node != pastEndNode; node = NodeTraversal::next(*node)) {
if (node->childNodeCount())
continue;
// We don't consider m_isInlineElementToRemoveFunction here because we never apply style when m_isInlineElementToRemoveFunction is specified
@@ -844,16 +849,17 @@ void ApplyStyleCommand::removeConflictingInlineStyleFromRun(EditingStyle* style,
for (RefPtr<Node> node = next; node && node->inDocument() && node != pastEndNode; node = next) {
if (editingIgnoresContent(node.get())) {
ASSERT(!node->contains(pastEndNode.get()));
- next = NodeTraversal::nextSkippingChildren(node.get());
- } else
- next = NodeTraversal::next(node.get());
+ next = NodeTraversal::nextSkippingChildren(*node);
+ } else {
+ next = NodeTraversal::next(*node);
+ }
if (!node->isHTMLElement())
continue;
RefPtr<Node> previousSibling = node->previousSibling();
RefPtr<Node> nextSibling = node->nextSibling();
RefPtr<ContainerNode> parent = node->parentNode();
- removeInlineStyleFromElement(style, toHTMLElement(node.get()), RemoveAlways);
+ removeInlineStyleFromElement(style, toHTMLElement(node), RemoveAlways);
if (!node->inDocument()) {
// FIXME: We might need to update the start and the end of current selection here but need a test.
if (runStart == node)
@@ -999,11 +1005,11 @@ void ApplyStyleCommand::applyInlineStyleToPushDown(Node* node, EditingStyle* sty
// Since addInlineStyleIfNeeded can't add styles to block-flow render objects, add style attribute instead.
// FIXME: applyInlineStyleToRange should be used here instead.
if ((node->renderer()->isRenderBlockFlow() || node->childNodeCount()) && node->isHTMLElement()) {
- setNodeAttribute(toHTMLElement(node), styleAttr, newInlineStyle->style()->asText());
+ setNodeAttribute(toHTMLElement(node), styleAttr, AtomicString(newInlineStyle->style()->asText()));
return;
}
- if (node->renderer()->isText() && static_cast<RenderText*>(node->renderer())->isAllCollapsibleWhitespace())
+ if (node->renderer()->isText() && toRenderText(node->renderer())->isAllCollapsibleWhitespace())
return;
// We can't wrap node with the styled element here because new styled element will never be removed if we did.
@@ -1025,16 +1031,16 @@ void ApplyStyleCommand::pushDownInlineStyleAroundNode(EditingStyle* style, Node*
Vector<RefPtr<Element> > elementsToPushDown;
while (current && current != targetNode && current->contains(targetNode)) {
NodeVector currentChildren;
- getChildNodes(current.get(), currentChildren);
+ getChildNodes(*current, currentChildren);
RefPtr<Element> styledElement;
- if (current->isStyledElement() && isStyledInlineElementToRemove(toElement(current.get()))) {
- styledElement = toElement(current.get());
+ if (current->isStyledElement() && isStyledInlineElementToRemove(toElement(current))) {
+ styledElement = toElement(current);
elementsToPushDown.append(styledElement);
}
RefPtr<EditingStyle> styleToPushDown = EditingStyle::create();
if (current->isHTMLElement())
- removeInlineStyleFromElement(style, toHTMLElement(current.get()), RemoveIfNeeded, styleToPushDown.get());
+ removeInlineStyleFromElement(style, toHTMLElement(current), RemoveIfNeeded, styleToPushDown.get());
// The inner loop will go through children on each level
// FIXME: we should aggregate inline child elements together so that we don't wrap each child separately.
@@ -1103,14 +1109,14 @@ void ApplyStyleCommand::removeInlineStyle(EditingStyle* style, const Position &s
RefPtr<Node> next;
if (editingIgnoresContent(node.get())) {
ASSERT(node == end.deprecatedNode() || !node->contains(end.deprecatedNode()));
- next = NodeTraversal::nextSkippingChildren(node.get());
+ next = NodeTraversal::nextSkippingChildren(*node);
} else {
- next = NodeTraversal::next(node.get());
+ next = NodeTraversal::next(*node);
}
if (node->isHTMLElement() && nodeFullySelected(node.get(), start, end)) {
- RefPtr<HTMLElement> elem = toHTMLElement(node.get());
- RefPtr<Node> prev = NodeTraversal::previousPostOrder(elem.get());
- RefPtr<Node> next = NodeTraversal::next(elem.get());
+ RefPtr<HTMLElement> elem = toHTMLElement(node);
+ RefPtr<Node> prev = NodeTraversal::previousPostOrder(*elem);
+ RefPtr<Node> next = NodeTraversal::next(*elem);
RefPtr<EditingStyle> styleToPushDown;
RefPtr<Node> childNode;
if (isStyledInlineElementToRemove(elem.get())) {
@@ -1351,14 +1357,14 @@ void ApplyStyleCommand::surroundNodeRangeWithElement(PassRefPtr<Node> passedStar
RefPtr<Node> nextSibling = element->nextSibling();
RefPtr<Node> previousSibling = element->previousSibling();
if (nextSibling && nextSibling->isElementNode() && nextSibling->rendererIsEditable()
- && areIdenticalElements(element.get(), toElement(nextSibling.get())))
- mergeIdenticalElements(element.get(), toElement(nextSibling.get()));
+ && areIdenticalElements(element.get(), toElement(nextSibling)))
+ mergeIdenticalElements(element.get(), toElement(nextSibling));
if (previousSibling && previousSibling->isElementNode() && previousSibling->rendererIsEditable()) {
Node* mergedElement = previousSibling->nextSibling();
if (mergedElement->isElementNode() && mergedElement->rendererIsEditable()
- && areIdenticalElements(toElement(previousSibling.get()), toElement(mergedElement)))
- mergeIdenticalElements(toElement(previousSibling.get()), toElement(mergedElement));
+ && areIdenticalElements(toElement(previousSibling), toElement(mergedElement)))
+ mergeIdenticalElements(toElement(previousSibling), toElement(mergedElement));
}
// FIXME: We should probably call updateStartEnd if the start or end was in the node
@@ -1381,7 +1387,7 @@ void ApplyStyleCommand::addBlockStyle(const StyleChange& styleChange, HTMLElemen
cssText.append(' ');
cssText.append(decl->asText());
}
- setNodeAttribute(block, styleAttr, cssText.toString());
+ setNodeAttribute(block, styleAttr, cssText.toAtomicString());
}
void ApplyStyleCommand::addInlineStyleIfNeeded(EditingStyle* style, PassRefPtr<Node> passedStart, PassRefPtr<Node> passedEnd, EAddStyledElement addStyledElement)
@@ -1402,7 +1408,6 @@ void ApplyStyleCommand::addInlineStyleIfNeeded(EditingStyle* style, PassRefPtr<N
Position ApplyStyleCommand::positionToComputeInlineStyleChange(PassRefPtr<Node> startNode, RefPtr<Node>& dummyElement)
{
// It's okay to obtain the style at the startNode because we've removed all relevant styles from the current run.
- Position positionForStyleComparison;
if (!startNode->isElementNode()) {
dummyElement = createStyleSpanElement(document());
insertNodeAt(dummyElement, positionBeforeNode(startNode.get()));
@@ -1438,19 +1443,19 @@ void ApplyStyleCommand::applyInlineStyleChange(PassRefPtr<Node> passedStart, Pas
if (styleChange.applyFontColor() || styleChange.applyFontFace() || styleChange.applyFontSize()) {
if (fontContainer) {
if (styleChange.applyFontColor())
- setNodeAttribute(fontContainer, colorAttr, styleChange.fontColor());
+ setNodeAttribute(fontContainer, colorAttr, AtomicString(styleChange.fontColor()));
if (styleChange.applyFontFace())
- setNodeAttribute(fontContainer, faceAttr, styleChange.fontFace());
+ setNodeAttribute(fontContainer, faceAttr, AtomicString(styleChange.fontFace()));
if (styleChange.applyFontSize())
- setNodeAttribute(fontContainer, sizeAttr, styleChange.fontSize());
+ setNodeAttribute(fontContainer, sizeAttr, AtomicString(styleChange.fontSize()));
} else {
RefPtr<Element> fontElement = createFontElement(document());
if (styleChange.applyFontColor())
- fontElement->setAttribute(colorAttr, styleChange.fontColor());
+ fontElement->setAttribute(colorAttr, AtomicString(styleChange.fontColor()));
if (styleChange.applyFontFace())
- fontElement->setAttribute(faceAttr, styleChange.fontFace());
+ fontElement->setAttribute(faceAttr, AtomicString(styleChange.fontFace()));
if (styleChange.applyFontSize())
- fontElement->setAttribute(sizeAttr, styleChange.fontSize());
+ fontElement->setAttribute(sizeAttr, AtomicString(styleChange.fontSize()));
surroundNodeRangeWithElement(startNode, endNode, fontElement.get());
}
}
@@ -1464,12 +1469,13 @@ void ApplyStyleCommand::applyInlineStyleChange(PassRefPtr<Node> passedStart, Pas
if (!existingText.isEmpty())
cssText.append(' ');
cssText.append(styleChange.cssStyle());
- setNodeAttribute(styleContainer, styleAttr, cssText.toString());
- } else
- setNodeAttribute(styleContainer, styleAttr, styleChange.cssStyle());
+ setNodeAttribute(styleContainer, styleAttr, cssText.toAtomicString());
+ } else {
+ setNodeAttribute(styleContainer, styleAttr, AtomicString(styleChange.cssStyle()));
+ }
} else {
RefPtr<Element> styleElement = createStyleSpanElement(document());
- styleElement->setAttribute(styleAttr, styleChange.cssStyle());
+ styleElement->setAttribute(styleAttr, AtomicString(styleChange.cssStyle()));
surroundNodeRangeWithElement(startNode, endNode, styleElement.release());
}
}
diff --git a/chromium/third_party/WebKit/Source/core/editing/BreakBlockquoteCommand.cpp b/chromium/third_party/WebKit/Source/core/editing/BreakBlockquoteCommand.cpp
index 906492356f8..73f09d90dd0 100644
--- a/chromium/third_party/WebKit/Source/core/editing/BreakBlockquoteCommand.cpp
+++ b/chromium/third_party/WebKit/Source/core/editing/BreakBlockquoteCommand.cpp
@@ -105,18 +105,19 @@ void BreakBlockquoteCommand::doApply()
// startNode is the first node that we need to move to the new blockquote.
Node* startNode = pos.deprecatedNode();
+ ASSERT(startNode);
// Split at pos if in the middle of a text node.
if (startNode->isTextNode()) {
Text* textNode = toText(startNode);
if ((unsigned)pos.deprecatedEditingOffset() >= textNode->length()) {
- startNode = NodeTraversal::next(startNode);
+ startNode = NodeTraversal::next(*startNode);
ASSERT(startNode);
} else if (pos.deprecatedEditingOffset() > 0)
splitTextNode(textNode, pos.deprecatedEditingOffset());
} else if (pos.deprecatedEditingOffset() > 0) {
Node* childAtOffset = startNode->childNode(pos.deprecatedEditingOffset());
- startNode = childAtOffset ? childAtOffset : NodeTraversal::next(startNode);
+ startNode = childAtOffset ? childAtOffset : NodeTraversal::next(*startNode);
ASSERT(startNode);
}
@@ -150,7 +151,7 @@ void BreakBlockquoteCommand::doApply()
while (listChildNode && !listChildNode->hasTagName(liTag))
listChildNode = listChildNode->nextSibling();
if (listChildNode && listChildNode->renderer() && listChildNode->renderer()->isListItem())
- setNodeAttribute(clonedChild, startAttr, String::number(toRenderListItem(listChildNode->renderer())->value()));
+ setNodeAttribute(clonedChild, startAttr, AtomicString::number(toRenderListItem(listChildNode->renderer())->value()));
}
appendNode(clonedChild.get(), clonedAncestor.get());
diff --git a/chromium/third_party/WebKit/Source/core/editing/Caret.cpp b/chromium/third_party/WebKit/Source/core/editing/Caret.cpp
index d1cb06150b2..64f05081576 100644
--- a/chromium/third_party/WebKit/Source/core/editing/Caret.cpp
+++ b/chromium/third_party/WebKit/Source/core/editing/Caret.cpp
@@ -28,18 +28,13 @@
#include "core/dom/Document.h"
#include "core/editing/htmlediting.h"
-#include "core/page/Frame.h"
-#include "core/page/Settings.h"
+#include "core/frame/Frame.h"
+#include "core/frame/Settings.h"
#include "core/rendering/RenderBlock.h"
#include "core/rendering/RenderView.h"
namespace WebCore {
-static inline LayoutUnit NoXPosForVerticalArrowNavigation()
-{
- return LayoutUnit::min();
-}
-
CaretBase::CaretBase(CaretVisibility visibility)
: m_caretRectNeedsUpdate(true)
, m_caretVisibility(visibility)
@@ -78,7 +73,7 @@ void DragCaretController::setCaretPosition(const VisiblePosition& position)
updateCaretRect(document, m_position);
}
-static bool removingNodeRemovesPosition(Node* node, const Position& position)
+static bool removingNodeRemovesPosition(Node& node, const Position& position)
{
if (!position.anchorNode())
return false;
@@ -86,30 +81,22 @@ static bool removingNodeRemovesPosition(Node* node, const Position& position)
if (position.anchorNode() == node)
return true;
- if (!node->isElementNode())
+ if (!node.isElementNode())
return false;
- Element* element = toElement(node);
- return element->containsIncludingShadowDOM(position.anchorNode());
-}
-
-static void clearRenderViewSelection(const Position& position)
-{
- RefPtr<Document> document = position.document();
- document->updateStyleIfNeeded();
- if (RenderView* view = document->renderView())
- view->clearSelection();
+ Element& element = toElement(node);
+ return element.containsIncludingShadowDOM(position.anchorNode());
}
-void DragCaretController::nodeWillBeRemoved(Node* node)
+void DragCaretController::nodeWillBeRemoved(Node& node)
{
- if (!hasCaret() || (node && !node->inDocument()))
+ if (!hasCaret() || !node.inActiveDocument())
return;
if (!removingNodeRemovesPosition(node, m_position.deepEquivalent()))
return;
- clearRenderViewSelection(m_position.deepEquivalent());
+ m_position.deepEquivalent().document()->renderView()->clearSelection();
clear();
}
@@ -120,7 +107,7 @@ void CaretBase::clearCaretRect()
static inline bool caretRendersInsideNode(Node* node)
{
- return node && !isTableElement(node) && !editingIgnoresContent(node);
+ return node && !isRenderedTable(node) && !editingIgnoresContent(node);
}
RenderObject* CaretBase::caretRenderer(Node* node)
diff --git a/chromium/third_party/WebKit/Source/core/editing/Caret.h b/chromium/third_party/WebKit/Source/core/editing/Caret.h
index 5e2c61c0c3d..18c74218038 100644
--- a/chromium/third_party/WebKit/Source/core/editing/Caret.h
+++ b/chromium/third_party/WebKit/Source/core/editing/Caret.h
@@ -27,8 +27,8 @@
#define Caret_h
#include "core/editing/VisiblePosition.h"
-#include "core/platform/graphics/IntRect.h"
-#include "core/platform/graphics/LayoutRect.h"
+#include "platform/geometry/IntRect.h"
+#include "platform/geometry/LayoutRect.h"
#include "wtf/Noncopyable.h"
namespace WebCore {
@@ -88,7 +88,7 @@ public:
void setCaretPosition(const VisiblePosition&);
void clear() { setCaretPosition(VisiblePosition()); }
- void nodeWillBeRemoved(Node*);
+ void nodeWillBeRemoved(Node&);
private:
DragCaretController();
diff --git a/chromium/third_party/WebKit/Source/core/editing/CompositeEditCommand.cpp b/chromium/third_party/WebKit/Source/core/editing/CompositeEditCommand.cpp
index 5afcf1d48f9..24acf2d5182 100644
--- a/chromium/third_party/WebKit/Source/core/editing/CompositeEditCommand.cpp
+++ b/chromium/third_party/WebKit/Source/core/editing/CompositeEditCommand.cpp
@@ -33,7 +33,7 @@
#include "core/dom/DocumentMarkerController.h"
#include "core/dom/NodeTraversal.h"
#include "core/dom/Range.h"
-#include "core/dom/ScopedEventQueue.h"
+#include "core/events/ScopedEventQueue.h"
#include "core/dom/Text.h"
#include "core/editing/AppendNodeCommand.h"
#include "core/editing/ApplyStyleCommand.h"
@@ -45,12 +45,14 @@
#include "core/editing/InsertNodeBeforeCommand.h"
#include "core/editing/InsertParagraphSeparatorCommand.h"
#include "core/editing/MergeIdenticalElementsCommand.h"
+#include "core/editing/PlainTextRange.h"
#include "core/editing/RemoveCSSPropertyCommand.h"
#include "core/editing/RemoveNodeCommand.h"
#include "core/editing/RemoveNodePreservingChildrenCommand.h"
#include "core/editing/ReplaceNodeWithSpanCommand.h"
#include "core/editing/ReplaceSelectionCommand.h"
#include "core/editing/SetNodeAttributeCommand.h"
+#include "core/editing/SpellChecker.h"
#include "core/editing/SplitElementCommand.h"
#include "core/editing/SplitTextNodeCommand.h"
#include "core/editing/SplitTextNodeContainingElementCommand.h"
@@ -60,7 +62,7 @@
#include "core/editing/htmlediting.h"
#include "core/editing/markup.h"
#include "core/html/HTMLElement.h"
-#include "core/page/Frame.h"
+#include "core/frame/Frame.h"
#include "core/rendering/InlineTextBox.h"
#include "core/rendering/RenderBlock.h"
#include "core/rendering/RenderText.h"
@@ -71,6 +73,24 @@ namespace WebCore {
using namespace HTMLNames;
+namespace {
+class ReentrancyGuard {
+public:
+ static bool isRecursiveCall() { return s_nestingCounter; }
+
+ class Scope {
+ public:
+ Scope() { ++s_nestingCounter; }
+ ~Scope() { --s_nestingCounter; }
+ };
+ friend class Scope;
+
+private:
+ static int s_nestingCounter;
+};
+int ReentrancyGuard::s_nestingCounter;
+}
+
PassRefPtr<EditCommandComposition> EditCommandComposition::create(Document* document,
const VisibleSelection& startingSelection, const VisibleSelection& endingSelection, EditAction editAction)
{
@@ -87,6 +107,12 @@ EditCommandComposition::EditCommandComposition(Document* document, const Visible
{
}
+bool EditCommandComposition::belongsTo(const Frame& frame) const
+{
+ ASSERT(m_document);
+ return m_document->frame() == &frame;
+}
+
void EditCommandComposition::unapply()
{
ASSERT(m_document);
@@ -156,6 +182,14 @@ CompositeEditCommand::~CompositeEditCommand()
void CompositeEditCommand::apply()
{
+ // We don't allow recusrive |apply()| to protect against attack code.
+ // Recursive call of |apply()| could be happened by moving iframe
+ // with script triggered by insertion, e.g. <iframe src="javascript:...">
+ // <iframe onload="...">. This usage is valid as of the specification
+ // although, it isn't common use case, rather it is used as attack code.
+ if (ReentrancyGuard::isRecursiveCall())
+ return;
+
if (!endingSelection().isContentRichlyEditable()) {
switch (editingAction()) {
case EditActionTyping:
@@ -180,7 +214,8 @@ void CompositeEditCommand::apply()
Frame* frame = document().frame();
ASSERT(frame);
{
- EventQueueScope scope;
+ EventQueueScope eventQueueScope;
+ ReentrancyGuard::Scope reentrancyGuardScope;
doApply();
}
@@ -675,7 +710,7 @@ void CompositeEditCommand::prepareWhitespaceAtPositionForSplit(Position& positio
// Delete collapsed whitespace so that inserting nbsps doesn't uncollapse it.
Position upstreamPos = position.upstream();
- deleteInsignificantText(position.upstream(), position.downstream());
+ deleteInsignificantText(upstreamPos, position.downstream());
position = upstreamPos.downstream();
VisiblePosition visiblePos(position);
@@ -795,7 +830,7 @@ void CompositeEditCommand::deleteInsignificantText(const Position& start, const
return;
Vector<RefPtr<Text> > nodes;
- for (Node* node = start.deprecatedNode(); node; node = NodeTraversal::next(node)) {
+ for (Node* node = start.deprecatedNode(); node; node = NodeTraversal::next(*node)) {
if (node->isTextNode())
nodes.append(toText(node));
if (node == end.deprecatedNode())
@@ -979,7 +1014,7 @@ void CompositeEditCommand::cloneParagraphUnderNewElement(Position& start, Positi
appendNode(lastNode, blockElement);
}
- if (start.deprecatedNode() != outerNode && lastNode->isElementNode()) {
+ if (start.anchorNode() != outerNode && lastNode->isElementNode() && start.anchorNode()->isDescendantOf(outerNode.get())) {
Vector<RefPtr<Node> > ancestors;
// Insert each node from innerNode to outerNode (excluded) in a list.
@@ -991,7 +1026,7 @@ void CompositeEditCommand::cloneParagraphUnderNewElement(Position& start, Positi
for (size_t i = ancestors.size(); i != 0; --i) {
Node* item = ancestors[i - 1].get();
RefPtr<Node> child = item->cloneNode(isTableElement(item));
- appendNode(child, toElement(lastNode.get()));
+ appendNode(child, toElement(lastNode));
lastNode = child.release();
}
}
@@ -1013,7 +1048,7 @@ void CompositeEditCommand::cloneParagraphUnderNewElement(Position& start, Positi
}
RefPtr<Node> startNode = start.deprecatedNode();
- for (RefPtr<Node> node = NodeTraversal::nextSkippingChildren(startNode.get(), outerNode.get()); node; node = NodeTraversal::nextSkippingChildren(node.get(), outerNode.get())) {
+ for (RefPtr<Node> node = NodeTraversal::nextSkippingChildren(*startNode, outerNode.get()); node; node = NodeTraversal::nextSkippingChildren(*node, outerNode.get())) {
// Move lastNode up in the tree as much as node was moved up in the
// tree by NodeTraversal::nextSkippingChildren, so that the relative depth between
// node and the original start node is maintained in the clone.
@@ -1120,7 +1155,7 @@ void CompositeEditCommand::moveParagraphWithClones(const VisiblePosition& startO
beforeParagraph = VisiblePosition(beforeParagraph.deepEquivalent());
afterParagraph = VisiblePosition(afterParagraph.deepEquivalent());
- if (beforeParagraph.isNotNull() && !isTableElement(beforeParagraph.deepEquivalent().deprecatedNode())
+ if (beforeParagraph.isNotNull() && !isRenderedTable(beforeParagraph.deepEquivalent().deprecatedNode())
&& ((!isEndOfParagraph(beforeParagraph) && !isStartOfParagraph(beforeParagraph)) || beforeParagraph == afterParagraph)) {
// FIXME: Trim text between beforeParagraph and afterParagraph if they aren't equal.
insertNodeAt(createBreakElement(document()), beforeParagraph.deepEquivalent());
@@ -1200,7 +1235,7 @@ void CompositeEditCommand::moveParagraphs(const VisiblePosition& startOfParagrap
// FIXME (5098931): We should add a new insert action "WebViewInsertActionMoved" and call shouldInsertFragment here.
setEndingSelection(VisibleSelection(start, end, DOWNSTREAM));
- document().frame()->editor().clearMisspellingsAndBadGrammar(endingSelection());
+ document().frame()->spellChecker().clearMisspellingsAndBadGrammar(endingSelection());
deleteSelection(false, false, false, false);
ASSERT(destination.deepEquivalent().inDocument());
@@ -1233,7 +1268,7 @@ void CompositeEditCommand::moveParagraphs(const VisiblePosition& startOfParagrap
options |= ReplaceSelectionCommand::MatchStyle;
applyCommandToComposite(ReplaceSelectionCommand::create(document(), fragment, options));
- document().frame()->editor().markMisspellingsAndBadGrammar(endingSelection());
+ document().frame()->spellChecker().markMisspellingsAndBadGrammar(endingSelection());
// If the selection is in an empty paragraph, restore styles from the old empty paragraph to the new empty paragraph.
bool selectionIsEmptyParagraph = endingSelection().isCaret() && isStartOfParagraph(endingSelection().visibleStart()) && isEndOfParagraph(endingSelection().visibleStart());
@@ -1246,8 +1281,8 @@ void CompositeEditCommand::moveParagraphs(const VisiblePosition& startOfParagrap
// causes spaces to be collapsed during the move operation. This results
// in a call to rangeFromLocationAndLength with a location past the end
// of the document (which will return null).
- RefPtr<Range> start = TextIterator::rangeFromLocationAndLength(document().documentElement(), destinationIndex + startIndex, 0, true);
- RefPtr<Range> end = TextIterator::rangeFromLocationAndLength(document().documentElement(), destinationIndex + endIndex, 0, true);
+ RefPtr<Range> start = PlainTextRange(destinationIndex + startIndex).createRangeForSelection(*document().documentElement());
+ RefPtr<Range> end = PlainTextRange(destinationIndex + endIndex).createRangeForSelection(*document().documentElement());
if (start && end)
setEndingSelection(VisibleSelection(start->startPosition(), end->startPosition(), DOWNSTREAM, originalIsDirectional));
}
@@ -1291,12 +1326,12 @@ bool CompositeEditCommand::breakOutOfEmptyListItem()
if (!newBlock)
newBlock = createDefaultParagraphElement(document());
- RefPtr<Node> previousListNode = emptyListItem->isElementNode() ? toElement(emptyListItem.get())->previousElementSibling(): emptyListItem->previousSibling();
- RefPtr<Node> nextListNode = emptyListItem->isElementNode() ? toElement(emptyListItem.get())->nextElementSibling(): emptyListItem->nextSibling();
+ RefPtr<Node> previousListNode = emptyListItem->isElementNode() ? toElement(emptyListItem)->previousElementSibling(): emptyListItem->previousSibling();
+ RefPtr<Node> nextListNode = emptyListItem->isElementNode() ? toElement(emptyListItem)->nextElementSibling(): emptyListItem->nextSibling();
if (isListItem(nextListNode.get()) || isListElement(nextListNode.get())) {
// If emptyListItem follows another list item or nested list, split the list node.
if (isListItem(previousListNode.get()) || isListElement(previousListNode.get()))
- splitElement(toElement(listNode.get()), emptyListItem);
+ splitElement(toElement(listNode), emptyListItem);
// If emptyListItem is followed by other list item or nested list, then insert newBlock before the list node.
// Because we have splitted the element, emptyListItem is the first element in the list node.
diff --git a/chromium/third_party/WebKit/Source/core/editing/CompositeEditCommand.h b/chromium/third_party/WebKit/Source/core/editing/CompositeEditCommand.h
index 8032544f83a..273ed51d520 100644
--- a/chromium/third_party/WebKit/Source/core/editing/CompositeEditCommand.h
+++ b/chromium/third_party/WebKit/Source/core/editing/CompositeEditCommand.h
@@ -42,6 +42,7 @@ class EditCommandComposition : public UndoStep {
public:
static PassRefPtr<EditCommandComposition> create(Document*, const VisibleSelection&, const VisibleSelection&, EditAction);
+ virtual bool belongsTo(const Frame&) const OVERRIDE;
virtual void unapply() OVERRIDE;
virtual void reapply() OVERRIDE;
EditAction editingAction() const OVERRIDE { return m_editAction; }
@@ -172,12 +173,7 @@ private:
RefPtr<EditCommandComposition> m_composition;
};
-inline CompositeEditCommand* toCompositeEditCommand(EditCommand* command)
-{
- ASSERT(command);
- ASSERT(command->isCompositeEditCommand());
- return static_cast<CompositeEditCommand*>(command);
-}
+DEFINE_TYPE_CASTS(CompositeEditCommand, EditCommand, command, command->isCompositeEditCommand(), command.isCompositeEditCommand());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/editing/CompositionUnderline.h b/chromium/third_party/WebKit/Source/core/editing/CompositionUnderline.h
index 5f97ac712ed..025ee75cbf7 100644
--- a/chromium/third_party/WebKit/Source/core/editing/CompositionUnderline.h
+++ b/chromium/third_party/WebKit/Source/core/editing/CompositionUnderline.h
@@ -26,7 +26,7 @@
#ifndef CompositionUnderline_h
#define CompositionUnderline_h
-#include "core/platform/graphics/Color.h"
+#include "platform/graphics/Color.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/editing/CreateLinkCommand.cpp b/chromium/third_party/WebKit/Source/core/editing/CreateLinkCommand.cpp
index 88f969e5e85..7f8adffff9f 100644
--- a/chromium/third_party/WebKit/Source/core/editing/CreateLinkCommand.cpp
+++ b/chromium/third_party/WebKit/Source/core/editing/CreateLinkCommand.cpp
@@ -43,7 +43,7 @@ void CreateLinkCommand::doApply()
return;
RefPtr<HTMLAnchorElement> anchorElement = HTMLAnchorElement::create(document());
- anchorElement->setHref(m_url);
+ anchorElement->setHref(AtomicString(m_url));
if (endingSelection().isRange())
applyStyledElement(anchorElement.get());
diff --git a/chromium/third_party/WebKit/Source/core/editing/DeleteFromTextNodeCommand.cpp b/chromium/third_party/WebKit/Source/core/editing/DeleteFromTextNodeCommand.cpp
index 2ca40f0a81c..bbecaced675 100644
--- a/chromium/third_party/WebKit/Source/core/editing/DeleteFromTextNodeCommand.cpp
+++ b/chromium/third_party/WebKit/Source/core/editing/DeleteFromTextNodeCommand.cpp
@@ -51,12 +51,12 @@ void DeleteFromTextNodeCommand::doApply()
if (!m_node->isContentEditable(Node::UserSelectAllIsAlwaysNonEditable))
return;
- TrackExceptionState es;
- m_text = m_node->substringData(m_offset, m_count, es);
- if (es.hadException())
+ TrackExceptionState exceptionState;
+ m_text = m_node->substringData(m_offset, m_count, exceptionState);
+ if (exceptionState.hadException())
return;
- m_node->deleteData(m_offset, m_count, es, CharacterData::DeprecatedRecalcStyleImmediatlelyForEditing);
+ m_node->deleteData(m_offset, m_count, exceptionState, CharacterData::DeprecatedRecalcStyleImmediatlelyForEditing);
}
void DeleteFromTextNodeCommand::doUnapply()
diff --git a/chromium/third_party/WebKit/Source/core/editing/DeleteSelectionCommand.cpp b/chromium/third_party/WebKit/Source/core/editing/DeleteSelectionCommand.cpp
index adf8e0674dc..ce27bb711cf 100644
--- a/chromium/third_party/WebKit/Source/core/editing/DeleteSelectionCommand.cpp
+++ b/chromium/third_party/WebKit/Source/core/editing/DeleteSelectionCommand.cpp
@@ -37,7 +37,7 @@
#include "core/editing/htmlediting.h"
#include "core/html/HTMLInputElement.h"
#include "core/html/HTMLTableElement.h"
-#include "core/page/Frame.h"
+#include "core/frame/Frame.h"
#include "core/rendering/RenderTableCell.h"
namespace WebCore {
@@ -292,7 +292,7 @@ void DeleteSelectionCommand::saveTypingStyleState()
return;
// Figure out the typing style in effect before the delete is done.
- m_typingStyle = EditingStyle::create(m_selectionToDelete.start());
+ m_typingStyle = EditingStyle::create(m_selectionToDelete.start(), EditingStyle::EditingPropertiesInEffect);
m_typingStyle->removeStyleAddedByNode(enclosingAnchorElement(m_selectionToDelete.start()));
// If we're deleting into a Mail blockquote, save the style at end() instead of start()
@@ -337,7 +337,7 @@ static Position firstEditablePositionInNode(Node* node)
ASSERT(node);
Node* next = node;
while (next && !next->rendererIsEditable())
- next = NodeTraversal::next(next, node);
+ next = NodeTraversal::next(*next, node);
return next ? firstPositionInOrBeforeNode(next) : Position();
}
@@ -429,9 +429,9 @@ void DeleteSelectionCommand::makeStylingElementsDirectChildrenOfEditableRootToPr
RefPtr<Range> range = m_selectionToDelete.toNormalizedRange();
RefPtr<Node> node = range->firstNode();
while (node && node != range->pastLastNode()) {
- RefPtr<Node> nextNode = NodeTraversal::next(node.get());
- if ((node->hasTagName(styleTag) && !(toElement(node.get())->hasAttribute(scopedAttr))) || node->hasTagName(linkTag)) {
- nextNode = NodeTraversal::nextSkippingChildren(node.get());
+ RefPtr<Node> nextNode = NodeTraversal::next(*node);
+ if ((node->hasTagName(styleTag) && !(toElement(node)->hasAttribute(scopedAttr))) || node->hasTagName(linkTag)) {
+ nextNode = NodeTraversal::nextSkippingChildren(*node);
RefPtr<ContainerNode> rootEditableElement = node->rootEditableElement();
if (rootEditableElement.get()) {
removeNode(node);
@@ -449,13 +449,14 @@ void DeleteSelectionCommand::handleGeneralDelete()
int startOffset = m_upstreamStart.deprecatedEditingOffset();
Node* startNode = m_upstreamStart.deprecatedNode();
+ ASSERT(startNode);
makeStylingElementsDirectChildrenOfEditableRootToPreventStyleLoss();
// Never remove the start block unless it's a table, in which case we won't merge content in.
if (startNode->isSameNode(m_startBlock.get()) && !startOffset && canHaveChildrenForEditing(startNode) && !isHTMLTableElement(startNode)) {
startOffset = 0;
- startNode = NodeTraversal::next(startNode);
+ startNode = NodeTraversal::next(*startNode);
if (!startNode)
return;
}
@@ -467,7 +468,7 @@ void DeleteSelectionCommand::handleGeneralDelete()
}
if (startOffset >= lastOffsetForEditing(startNode)) {
- startNode = NodeTraversal::nextSkippingChildren(startNode);
+ startNode = NodeTraversal::nextSkippingChildren(*startNode);
startOffset = 0;
}
@@ -499,9 +500,9 @@ void DeleteSelectionCommand::handleGeneralDelete()
if (startOffset > 0) {
if (startNode->isTextNode()) {
// in a text node that needs to be trimmed
- Text* text = toText(node.get());
+ Text* text = toText(node);
deleteTextFromNode(text, startOffset, text->length() - startOffset);
- node = NodeTraversal::next(node.get());
+ node = NodeTraversal::next(*node);
} else {
node = startNode->childNode(startOffset);
}
@@ -516,19 +517,20 @@ void DeleteSelectionCommand::handleGeneralDelete()
// NodeTraversal::nextSkippingChildren just blew past the end position, so stop deleting
node = 0;
} else if (!m_downstreamEnd.deprecatedNode()->isDescendantOf(node.get())) {
- RefPtr<Node> nextNode = NodeTraversal::nextSkippingChildren(node.get());
+ RefPtr<Node> nextNode = NodeTraversal::nextSkippingChildren(*node);
// if we just removed a node from the end container, update end position so the
// check above will work
updatePositionForNodeRemoval(m_downstreamEnd, node.get());
removeNode(node.get());
node = nextNode.get();
} else {
- Node* n = node->lastDescendant();
- if (m_downstreamEnd.deprecatedNode() == n && m_downstreamEnd.deprecatedEditingOffset() >= caretMaxOffset(n)) {
+ Node& n = node->lastDescendant();
+ if (m_downstreamEnd.deprecatedNode() == n && m_downstreamEnd.deprecatedEditingOffset() >= caretMaxOffset(&n)) {
removeNode(node.get());
node = 0;
- } else
- node = NodeTraversal::next(node.get());
+ } else {
+ node = NodeTraversal::next(*node);
+ }
}
}
diff --git a/chromium/third_party/WebKit/Source/core/editing/EditCommand.cpp b/chromium/third_party/WebKit/Source/core/editing/EditCommand.cpp
index 7fdf04e5bfc..4b318f763d8 100644
--- a/chromium/third_party/WebKit/Source/core/editing/EditCommand.cpp
+++ b/chromium/third_party/WebKit/Source/core/editing/EditCommand.cpp
@@ -30,7 +30,7 @@
#include "core/dom/NodeTraversal.h"
#include "core/editing/CompositeEditCommand.h"
#include "core/editing/FrameSelection.h"
-#include "core/page/Frame.h"
+#include "core/frame/Frame.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/editing/EditCommand.h b/chromium/third_party/WebKit/Source/core/editing/EditCommand.h
index 41d3edf3c8a..e9dc8bea960 100644
--- a/chromium/third_party/WebKit/Source/core/editing/EditCommand.h
+++ b/chromium/third_party/WebKit/Source/core/editing/EditCommand.h
@@ -90,12 +90,7 @@ private:
virtual bool isSimpleEditCommand() const OVERRIDE { return true; }
};
-inline SimpleEditCommand* toSimpleEditCommand(EditCommand* command)
-{
- ASSERT(command);
- ASSERT_WITH_SECURITY_IMPLICATION(command->isSimpleEditCommand());
- return static_cast<SimpleEditCommand*>(command);
-}
+DEFINE_TYPE_CASTS(SimpleEditCommand, EditCommand, command, command->isSimpleEditCommand(), command.isSimpleEditCommand());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/editing/EditingBehavior.h b/chromium/third_party/WebKit/Source/core/editing/EditingBehavior.h
index 6c2f994cd6f..ec1a775463c 100644
--- a/chromium/third_party/WebKit/Source/core/editing/EditingBehavior.h
+++ b/chromium/third_party/WebKit/Source/core/editing/EditingBehavior.h
@@ -79,6 +79,17 @@ public:
// But ctrl+right arrow moves caret to "abc |def |hij |opq" on Windows and "abc| def| hij| opq|" on Mac and Linux.
bool shouldSkipSpaceWhenMovingRight() const { return m_type == EditingWindowsBehavior; }
+ // On Mac, undo of delete/forward-delete of text should select the deleted text. On other platforms deleted text
+ // should not be selected and the cursor should be placed where the deletion started.
+ bool shouldUndoOfDeleteSelectText() const { return m_type == EditingMacBehavior; }
+
+ // Support for global selections, used on platforms like the X Window
+ // System that treat selection as a type of clipboard.
+ bool supportsGlobalSelection() const
+ {
+ return m_type != EditingWindowsBehavior && m_type != EditingMacBehavior;
+ }
+
private:
EditingBehaviorType m_type;
};
diff --git a/chromium/third_party/WebKit/Source/core/editing/EditingStyle.cpp b/chromium/third_party/WebKit/Source/core/editing/EditingStyle.cpp
index a06a083da8c..8fe59c18fdc 100644
--- a/chromium/third_party/WebKit/Source/core/editing/EditingStyle.cpp
+++ b/chromium/third_party/WebKit/Source/core/editing/EditingStyle.cpp
@@ -27,7 +27,6 @@
#include "config.h"
#include "core/editing/EditingStyle.h"
-#include "CSSValueKeywords.h"
#include "HTMLNames.h"
#include "bindings/v8/ExceptionStatePlaceholder.h"
#include "core/css/CSSComputedStyleDeclaration.h"
@@ -36,6 +35,7 @@
#include "core/css/CSSStyleRule.h"
#include "core/css/CSSValueList.h"
#include "core/css/FontSize.h"
+#include "core/css/RuntimeCSSEnabled.h"
#include "core/css/StylePropertySet.h"
#include "core/css/StyleRule.h"
#include "core/css/resolver/StyleResolver.h"
@@ -49,9 +49,8 @@
#include "core/editing/FrameSelection.h"
#include "core/editing/HTMLInterchange.h"
#include "core/editing/htmlediting.h"
+#include "core/frame/Frame.h"
#include "core/html/HTMLFontElement.h"
-#include "core/page/Frame.h"
-#include "core/page/RuntimeCSSEnabled.h"
#include "core/rendering/style/RenderStyle.h"
namespace WebCore {
@@ -712,7 +711,7 @@ TriState EditingStyle::triStateOfStyle(const VisibleSelection& selection) const
TriState state = FalseTriState;
bool nodeIsStart = true;
- for (Node* node = selection.start().deprecatedNode(); node; node = NodeTraversal::next(node)) {
+ for (Node* node = selection.start().deprecatedNode(); node; node = NodeTraversal::next(*node)) {
if (node->renderer() && node->rendererIsEditable()) {
RefPtr<CSSComputedStyleDeclaration> nodeStyle = CSSComputedStyleDeclaration::create(node);
if (nodeStyle) {
@@ -1091,14 +1090,14 @@ PassRefPtr<EditingStyle> EditingStyle::wrappingStyleForSerialization(Node* conte
static void mergeTextDecorationValues(CSSValueList* mergedValue, const CSSValueList* valueToMerge)
{
- DEFINE_STATIC_LOCAL(const RefPtr<CSSPrimitiveValue>, underline, (CSSPrimitiveValue::createIdentifier(CSSValueUnderline)));
- DEFINE_STATIC_LOCAL(const RefPtr<CSSPrimitiveValue>, lineThrough, (CSSPrimitiveValue::createIdentifier(CSSValueLineThrough)));
+ DEFINE_STATIC_REF(CSSPrimitiveValue, underline, (CSSPrimitiveValue::createIdentifier(CSSValueUnderline)));
+ DEFINE_STATIC_REF(CSSPrimitiveValue, lineThrough, (CSSPrimitiveValue::createIdentifier(CSSValueLineThrough)));
- if (valueToMerge->hasValue(underline.get()) && !mergedValue->hasValue(underline.get()))
- mergedValue->append(underline.get());
+ if (valueToMerge->hasValue(underline) && !mergedValue->hasValue(underline))
+ mergedValue->append(underline);
- if (valueToMerge->hasValue(lineThrough.get()) && !mergedValue->hasValue(lineThrough.get()))
- mergedValue->append(lineThrough.get());
+ if (valueToMerge->hasValue(lineThrough) && !mergedValue->hasValue(lineThrough))
+ mergedValue->append(lineThrough);
}
void EditingStyle::mergeStyle(const StylePropertySet* style, CSSPropertyOverrideMode mode)
@@ -1133,14 +1132,11 @@ void EditingStyle::mergeStyle(const StylePropertySet* style, CSSPropertyOverride
static PassRefPtr<MutableStylePropertySet> styleFromMatchedRulesForElement(Element* element, unsigned rulesToInclude)
{
RefPtr<MutableStylePropertySet> style = MutableStylePropertySet::create();
- RefPtr<CSSRuleList> matchedRules = element->document().styleResolver()->styleRulesForElement(element, rulesToInclude);
+ RefPtr<StyleRuleList> matchedRules = element->document().ensureStyleResolver().styleRulesForElement(element, rulesToInclude);
if (matchedRules) {
- for (unsigned i = 0; i < matchedRules->length(); i++) {
- if (matchedRules->item(i)->type() == CSSRule::STYLE_RULE)
- style->mergeAndOverrideOnConflict(static_cast<CSSStyleRule*>(matchedRules->item(i))->styleRule()->properties());
- }
+ for (unsigned i = 0; i < matchedRules->m_list.size(); ++i)
+ style->mergeAndOverrideOnConflict(matchedRules->m_list[i]->properties());
}
-
return style.release();
}
@@ -1303,7 +1299,7 @@ WritingDirection EditingStyle::textDirectionForSelection(const VisibleSelection&
ASSERT(end.document());
Node* pastLast = Range::create(*end.document(), position.parentAnchoredEquivalent(), end.parentAnchoredEquivalent())->pastLastNode();
- for (Node* n = node; n && n != pastLast; n = NodeTraversal::next(n)) {
+ for (Node* n = node; n && n != pastLast; n = NodeTraversal::next(*n)) {
if (!n->isStyledElement())
continue;
@@ -1450,13 +1446,13 @@ void StyleChange::extractTextStyles(Document* document, MutableStylePropertySet*
// Furthermore, text-decoration: none has been trimmed so that text-decoration property is always a CSSValueList.
RefPtr<CSSValue> textDecoration = style->getPropertyCSSValue(textDecorationPropertyForEditing());
if (textDecoration && textDecoration->isValueList()) {
- DEFINE_STATIC_LOCAL(RefPtr<CSSPrimitiveValue>, underline, (CSSPrimitiveValue::createIdentifier(CSSValueUnderline)));
- DEFINE_STATIC_LOCAL(RefPtr<CSSPrimitiveValue>, lineThrough, (CSSPrimitiveValue::createIdentifier(CSSValueLineThrough)));
+ DEFINE_STATIC_REF(CSSPrimitiveValue, underline, (CSSPrimitiveValue::createIdentifier(CSSValueUnderline)));
+ DEFINE_STATIC_REF(CSSPrimitiveValue, lineThrough, (CSSPrimitiveValue::createIdentifier(CSSValueLineThrough)));
RefPtr<CSSValueList> newTextDecoration = toCSSValueList(textDecoration.get())->copy();
- if (newTextDecoration->removeAll(underline.get()))
+ if (newTextDecoration->removeAll(underline))
m_applyUnderline = true;
- if (newTextDecoration->removeAll(lineThrough.get()))
+ if (newTextDecoration->removeAll(lineThrough))
m_applyLineThrough = true;
// If trimTextDecorations, delete underline and line-through
diff --git a/chromium/third_party/WebKit/Source/core/editing/Editor.cpp b/chromium/third_party/WebKit/Source/core/editing/Editor.cpp
index 114338e247f..fcdf0cd5971 100644
--- a/chromium/third_party/WebKit/Source/core/editing/Editor.cpp
+++ b/chromium/third_party/WebKit/Source/core/editing/Editor.cpp
@@ -29,20 +29,19 @@
#include "CSSPropertyNames.h"
#include "HTMLNames.h"
+#include "SVGNames.h"
+#include "XLinkNames.h"
#include "bindings/v8/ExceptionStatePlaceholder.h"
#include "core/accessibility/AXObjectCache.h"
#include "core/css/CSSComputedStyleDeclaration.h"
#include "core/css/StylePropertySet.h"
#include "core/dom/Clipboard.h"
-#include "core/dom/ClipboardEvent.h"
#include "core/dom/DocumentFragment.h"
#include "core/dom/DocumentMarkerController.h"
-#include "core/dom/EventNames.h"
-#include "core/dom/KeyboardEvent.h"
#include "core/dom/NodeList.h"
#include "core/dom/NodeTraversal.h"
+#include "core/dom/ParserContentPolicy.h"
#include "core/dom/Text.h"
-#include "core/dom/TextEvent.h"
#include "core/editing/ApplyStyleCommand.h"
#include "core/editing/DeleteSelectionCommand.h"
#include "core/editing/IndentOutdentCommand.h"
@@ -53,33 +52,37 @@
#include "core/editing/RenderedPosition.h"
#include "core/editing/ReplaceSelectionCommand.h"
#include "core/editing/SimplifyMarkupCommand.h"
-#include "core/editing/SpellCheckRequester.h"
-#include "core/editing/TextCheckingHelper.h"
-#include "core/editing/TextIterator.h"
+#include "core/editing/SpellChecker.h"
#include "core/editing/TypingCommand.h"
+#include "core/editing/UndoStack.h"
#include "core/editing/VisibleUnits.h"
#include "core/editing/htmlediting.h"
#include "core/editing/markup.h"
+#include "core/events/ClipboardEvent.h"
+#include "core/events/KeyboardEvent.h"
+#include "core/events/ScopedEventQueue.h"
+#include "core/events/TextEvent.h"
+#include "core/events/ThreadLocalEventNames.h"
+#include "core/fetch/ImageResource.h"
#include "core/fetch/ResourceFetcher.h"
#include "core/html/HTMLImageElement.h"
#include "core/html/HTMLInputElement.h"
#include "core/html/HTMLTextAreaElement.h"
+#include "core/html/parser/HTMLParserIdioms.h"
#include "core/loader/EmptyClients.h"
#include "core/page/EditorClient.h"
#include "core/page/EventHandler.h"
#include "core/page/FocusController.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameView.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
#include "core/page/Page.h"
-#include "core/page/Settings.h"
-#include "core/platform/KillRing.h"
+#include "core/frame/Settings.h"
#include "core/platform/Pasteboard.h"
-#include "core/platform/Sound.h"
-#include "core/platform/chromium/ClipboardChromium.h"
-#include "core/platform/text/TextCheckerClient.h"
+#include "core/platform/chromium/ChromiumDataObject.h"
#include "core/rendering/HitTestResult.h"
-#include "core/rendering/RenderBlock.h"
-#include "core/rendering/RenderTextControl.h"
+#include "core/rendering/RenderImage.h"
+#include "platform/KillRing.h"
+#include "platform/weborigin/KURL.h"
#include "wtf/unicode/CharacterNames.h"
namespace WebCore {
@@ -100,24 +103,14 @@ Editor::RevealSelectionScope::~RevealSelectionScope()
ASSERT(m_editor->m_preventRevealSelection);
--m_editor->m_preventRevealSelection;
if (!m_editor->m_preventRevealSelection)
- m_editor->m_frame->selection().revealSelection(ScrollAlignment::alignToEdgeIfNeeded, RevealExtent);
+ m_editor->m_frame.selection().revealSelection(ScrollAlignment::alignToEdgeIfNeeded, RevealExtent);
}
-namespace {
-
-bool isSelectionInTextField(const VisibleSelection& selection)
-{
- HTMLTextFormControlElement* textControl = enclosingTextFormControl(selection.start());
- return textControl && textControl->hasTagName(inputTag) && toHTMLInputElement(textControl)->isTextField();
-}
-
-} // namespace
-
// When an event handler has moved the selection outside of a text control
// we should use the target control's selection for this editing operation.
VisibleSelection Editor::selectionForCommand(Event* event)
{
- VisibleSelection selection = m_frame->selection().selection();
+ VisibleSelection selection = m_frame.selection().selection();
if (!event)
return selection;
// If the target is a text control, and the current selection is outside of its shadow tree,
@@ -134,10 +127,10 @@ VisibleSelection Editor::selectionForCommand(Event* event)
// Function considers Mac editing behavior a fallback when Page or Settings is not available.
EditingBehavior Editor::behavior() const
{
- if (!m_frame || !m_frame->settings())
+ if (!m_frame.settings())
return EditingBehavior(EditingMacBehavior);
- return EditingBehavior(m_frame->settings()->editingBehaviorType());
+ return EditingBehavior(m_frame.settings()->editingBehaviorType());
}
static EditorClient& emptyEditorClient()
@@ -148,19 +141,16 @@ static EditorClient& emptyEditorClient()
EditorClient& Editor::client() const
{
- if (Page* page = m_frame->page())
+ if (Page* page = m_frame.page())
return page->editorClient();
return emptyEditorClient();
}
-TextCheckerClient& Editor::textChecker() const
-{
- return client().textChecker();
-}
-
-void Editor::handleKeyboardEvent(KeyboardEvent* event)
+UndoStack* Editor::undoStack() const
{
- client().handleKeyboardEvent(event);
+ if (Page* page = m_frame.page())
+ return &page->undoStack();
+ return 0;
}
bool Editor::handleTextEvent(TextEvent* event)
@@ -190,32 +180,32 @@ bool Editor::handleTextEvent(TextEvent* event)
bool Editor::canEdit() const
{
- return m_frame->selection().rootEditableElement();
+ return m_frame.selection().rootEditableElement();
}
bool Editor::canEditRichly() const
{
- return m_frame->selection().isContentRichlyEditable();
+ return m_frame.selection().isContentRichlyEditable();
}
-// WinIE uses onbeforecut and onbeforepaste to enables the cut and paste menu items. They
+// WinIE uses onbeforecut and onbeforepaste to enables the cut and paste menu items. They
// also send onbeforecopy, apparently for symmetry, but it doesn't affect the menu items.
// We need to use onbeforecopy as a real menu enabler because we allow elements that are not
// normally selectable to implement copy/paste (like divs, or a document body).
bool Editor::canDHTMLCut()
{
- return !m_frame->selection().isInPasswordField() && !dispatchCPPEvent(eventNames().beforecutEvent, ClipboardNumb);
+ return !m_frame.selection().isInPasswordField() && !dispatchCPPEvent(EventTypeNames::beforecut, ClipboardNumb);
}
bool Editor::canDHTMLCopy()
{
- return !m_frame->selection().isInPasswordField() && !dispatchCPPEvent(eventNames().beforecopyEvent, ClipboardNumb);
+ return !m_frame.selection().isInPasswordField() && !dispatchCPPEvent(EventTypeNames::beforecopy, ClipboardNumb);
}
bool Editor::canDHTMLPaste()
{
- return !dispatchCPPEvent(eventNames().beforepasteEvent, ClipboardNumb);
+ return !dispatchCPPEvent(EventTypeNames::beforepaste, ClipboardNumb);
}
bool Editor::canCut() const
@@ -244,9 +234,9 @@ static HTMLImageElement* imageElementFromImageDocument(Document* document)
bool Editor::canCopy() const
{
- if (imageElementFromImageDocument(m_frame->document()))
+ if (imageElementFromImageDocument(m_frame.document()))
return true;
- FrameSelection& selection = m_frame->selection();
+ FrameSelection& selection = m_frame.selection();
return selection.isRange() && !selection.isInPasswordField();
}
@@ -257,7 +247,7 @@ bool Editor::canPaste() const
bool Editor::canDelete() const
{
- FrameSelection& selection = m_frame->selection();
+ FrameSelection& selection = m_frame.selection();
return selection.isRange() && selection.rootEditableElement();
}
@@ -281,19 +271,23 @@ bool Editor::canDeleteRange(Range* range) const
return true;
}
-bool Editor::smartInsertDeleteEnabled()
+bool Editor::smartInsertDeleteEnabled() const
{
- return client().smartInsertDeleteEnabled();
+ if (Settings* settings = m_frame.settings())
+ return settings->smartInsertDeleteEnabled();
+ return false;
}
-bool Editor::canSmartCopyOrDelete()
+bool Editor::canSmartCopyOrDelete() const
{
- return client().smartInsertDeleteEnabled() && m_frame->selection().granularity() == WordGranularity;
+ return smartInsertDeleteEnabled() && m_frame.selection().granularity() == WordGranularity;
}
-bool Editor::isSelectTrailingWhitespaceEnabled()
+bool Editor::isSelectTrailingWhitespaceEnabled() const
{
- return client().isSelectTrailingWhitespaceEnabled();
+ if (Settings* settings = m_frame.settings())
+ return settings->selectTrailingWhitespaceEnabled();
+ return false;
}
bool Editor::deleteWithDirection(SelectionDirection direction, TextGranularity granularity, bool killRing, bool isTypingAction)
@@ -301,10 +295,10 @@ bool Editor::deleteWithDirection(SelectionDirection direction, TextGranularity g
if (!canEdit())
return false;
- if (m_frame->selection().isRange()) {
+ if (m_frame.selection().isRange()) {
if (isTypingAction) {
- ASSERT(m_frame->document());
- TypingCommand::deleteKeyPressed(*m_frame->document(), canSmartCopyOrDelete() ? TypingCommand::SmartDelete : 0, granularity);
+ ASSERT(m_frame.document());
+ TypingCommand::deleteKeyPressed(*m_frame.document(), canSmartCopyOrDelete() ? TypingCommand::SmartDelete : 0, granularity);
revealSelectionAfterEditingOperation();
} else {
if (killRing)
@@ -321,13 +315,13 @@ bool Editor::deleteWithDirection(SelectionDirection direction, TextGranularity g
switch (direction) {
case DirectionForward:
case DirectionRight:
- ASSERT(m_frame->document());
- TypingCommand::forwardDeleteKeyPressed(*m_frame->document(), options, granularity);
+ ASSERT(m_frame.document());
+ TypingCommand::forwardDeleteKeyPressed(*m_frame.document(), options, granularity);
break;
case DirectionBackward:
case DirectionLeft:
- ASSERT(m_frame->document());
- TypingCommand::deleteKeyPressed(*m_frame->document(), options, granularity);
+ ASSERT(m_frame.document());
+ TypingCommand::deleteKeyPressed(*m_frame.document(), options, granularity);
break;
}
revealSelectionAfterEditingOperation();
@@ -344,11 +338,11 @@ bool Editor::deleteWithDirection(SelectionDirection direction, TextGranularity g
void Editor::deleteSelectionWithSmartDelete(bool smartDelete)
{
- if (m_frame->selection().isNone())
+ if (m_frame.selection().isNone())
return;
- ASSERT(m_frame->document());
- DeleteSelectionCommand::create(*m_frame->document(), smartDelete)->apply();
+ ASSERT(m_frame.document());
+ DeleteSelectionCommand::create(*m_frame.document(), smartDelete)->apply();
}
void Editor::pasteAsPlainText(const String& pastingText, bool smartReplace)
@@ -356,7 +350,7 @@ void Editor::pasteAsPlainText(const String& pastingText, bool smartReplace)
Node* target = findEventTargetFromSelection();
if (!target)
return;
- target->dispatchEvent(TextEvent::createForPlainTextPaste(m_frame->domWindow(), pastingText, smartReplace), IGNORE_EXCEPTION);
+ target->dispatchEvent(TextEvent::createForPlainTextPaste(m_frame.domWindow(), pastingText, smartReplace), IGNORE_EXCEPTION);
}
void Editor::pasteAsFragment(PassRefPtr<DocumentFragment> pastingFragment, bool smartReplace, bool matchStyle)
@@ -364,49 +358,137 @@ void Editor::pasteAsFragment(PassRefPtr<DocumentFragment> pastingFragment, bool
Node* target = findEventTargetFromSelection();
if (!target)
return;
- target->dispatchEvent(TextEvent::createForFragmentPaste(m_frame->domWindow(), pastingFragment, smartReplace, matchStyle), IGNORE_EXCEPTION);
+ target->dispatchEvent(TextEvent::createForFragmentPaste(m_frame.domWindow(), pastingFragment, smartReplace, matchStyle), IGNORE_EXCEPTION);
}
-void Editor::pasteAsPlainTextBypassingDHTML()
+bool Editor::tryDHTMLCopy()
{
- pasteAsPlainTextWithPasteboard(Pasteboard::generalPasteboard());
+ if (m_frame.selection().isInPasswordField())
+ return false;
+
+ return !dispatchCPPEvent(EventTypeNames::copy, ClipboardWritable);
+}
+
+bool Editor::tryDHTMLCut()
+{
+ if (m_frame.selection().isInPasswordField())
+ return false;
+
+ return !dispatchCPPEvent(EventTypeNames::cut, ClipboardWritable);
+}
+
+bool Editor::tryDHTMLPaste(PasteMode pasteMode)
+{
+ return !dispatchCPPEvent(EventTypeNames::paste, ClipboardReadable, pasteMode);
}
void Editor::pasteAsPlainTextWithPasteboard(Pasteboard* pasteboard)
{
String text = pasteboard->plainText();
- if (client().shouldInsertText(text, selectedRange().get(), EditorInsertActionPasted))
- pasteAsPlainText(text, canSmartReplaceWithPasteboard(pasteboard));
+ pasteAsPlainText(text, canSmartReplaceWithPasteboard(pasteboard));
}
-void Editor::pasteWithPasteboard(Pasteboard* pasteboard, bool allowPlainText)
+void Editor::pasteWithPasteboard(Pasteboard* pasteboard)
{
RefPtr<Range> range = selectedRange();
- bool chosePlainText;
- RefPtr<DocumentFragment> fragment = pasteboard->documentFragment(m_frame, range, allowPlainText, chosePlainText);
- if (fragment && shouldInsertFragment(fragment, range, EditorInsertActionPasted))
+ RefPtr<DocumentFragment> fragment;
+ bool chosePlainText = false;
+
+ if (pasteboard->isHTMLAvailable()) {
+ unsigned fragmentStart = 0;
+ unsigned fragmentEnd = 0;
+ KURL url;
+ String markup = pasteboard->readHTML(url, fragmentStart, fragmentEnd);
+ if (!markup.isEmpty()) {
+ ASSERT(m_frame.document());
+ fragment = createFragmentFromMarkupWithContext(*m_frame.document(), markup, fragmentStart, fragmentEnd, url, DisallowScriptingAndPluginContent);
+ }
+ }
+
+ if (!fragment) {
+ String text = pasteboard->plainText();
+ if (!text.isEmpty()) {
+ chosePlainText = true;
+ fragment = createFragmentFromText(range.get(), text);
+ }
+ }
+
+ if (fragment)
pasteAsFragment(fragment, canSmartReplaceWithPasteboard(pasteboard), chosePlainText);
}
-bool Editor::canSmartReplaceWithPasteboard(Pasteboard* pasteboard)
+void Editor::writeSelectionToPasteboard(Pasteboard* pasteboard, Range* selectedRange, const String& plainText)
{
- return client().smartInsertDeleteEnabled() && pasteboard->canSmartReplace();
+ String html = createMarkup(selectedRange, 0, AnnotateForInterchange, false, ResolveNonLocalURLs);
+ KURL url = selectedRange->startContainer()->document().url();
+ pasteboard->writeHTML(html, url, plainText, canSmartCopyOrDelete());
}
-bool Editor::shouldInsertFragment(PassRefPtr<DocumentFragment> fragment, PassRefPtr<Range> replacingDOMRange, EditorInsertAction givenAction)
+static void writeImageNodeToPasteboard(Pasteboard* pasteboard, Node* node, const String& title)
{
- if (fragment) {
- Node* child = fragment->firstChild();
- if (child && fragment->lastChild() == child && child->isCharacterDataNode())
- return client().shouldInsertText(toCharacterData(child)->data(), replacingDOMRange.get(), givenAction);
+ ASSERT(pasteboard);
+ ASSERT(node);
+
+ if (!(node->renderer() && node->renderer()->isImage()))
+ return;
+
+ RenderImage* renderer = toRenderImage(node->renderer());
+ ImageResource* cachedImage = renderer->cachedImage();
+ if (!cachedImage || cachedImage->errorOccurred())
+ return;
+ Image* image = cachedImage->imageForRenderer(renderer);
+ ASSERT(image);
+
+ // FIXME: This should probably be reconciled with HitTestResult::absoluteImageURL.
+ AtomicString urlString;
+ if (node->hasTagName(imgTag) || node->hasTagName(inputTag))
+ urlString = toElement(node)->getAttribute(srcAttr);
+ else if (node->hasTagName(SVGNames::imageTag))
+ urlString = toElement(node)->getAttribute(XLinkNames::hrefAttr);
+ else if (node->hasTagName(embedTag) || node->hasTagName(objectTag))
+ urlString = toElement(node)->imageSourceURL();
+ KURL url = urlString.isEmpty() ? KURL() : node->document().completeURL(stripLeadingAndTrailingHTMLSpaces(urlString));
+
+ pasteboard->writeImage(image, url, title);
+}
+
+// Returns whether caller should continue with "the default processing", which is the same as
+// the event handler NOT setting the return value to false
+bool Editor::dispatchCPPEvent(const AtomicString &eventType, ClipboardAccessPolicy policy, PasteMode pasteMode)
+{
+ Node* target = findEventTargetFromSelection();
+ if (!target)
+ return true;
+
+ RefPtr<Clipboard> clipboard = Clipboard::create(
+ Clipboard::CopyAndPaste,
+ policy,
+ policy == ClipboardWritable
+ ? ChromiumDataObject::create()
+ : ChromiumDataObject::createFromPasteboard(pasteMode));
+
+ RefPtr<Event> evt = ClipboardEvent::create(eventType, true, true, clipboard);
+ target->dispatchEvent(evt, IGNORE_EXCEPTION);
+ bool noDefaultProcessing = evt->defaultPrevented();
+ if (noDefaultProcessing && policy == ClipboardWritable) {
+ RefPtr<ChromiumDataObject> dataObject = clipboard->dataObject();
+ Pasteboard::generalPasteboard()->writeDataObject(dataObject.release());
}
- return client().shouldInsertNode(fragment.get(), replacingDOMRange.get(), givenAction);
+ // invalidate clipboard here for security
+ clipboard->setAccessPolicy(ClipboardNumb);
+
+ return !noDefaultProcessing;
+}
+
+bool Editor::canSmartReplaceWithPasteboard(Pasteboard* pasteboard)
+{
+ return smartInsertDeleteEnabled() && pasteboard->canSmartReplace();
}
void Editor::replaceSelectionWithFragment(PassRefPtr<DocumentFragment> fragment, bool selectReplacement, bool smartReplace, bool matchStyle)
{
- if (m_frame->selection().isNone() || !m_frame->selection().isContentEditable() || !fragment)
+ if (m_frame.selection().isNone() || !m_frame.selection().isContentEditable() || !fragment)
return;
ReplaceSelectionCommand::CommandOptions options = ReplaceSelectionCommand::PreventNesting | ReplaceSelectionCommand::SanitizeFragment;
@@ -416,20 +498,13 @@ void Editor::replaceSelectionWithFragment(PassRefPtr<DocumentFragment> fragment,
options |= ReplaceSelectionCommand::SmartReplace;
if (matchStyle)
options |= ReplaceSelectionCommand::MatchStyle;
- ASSERT(m_frame->document());
- ReplaceSelectionCommand::create(*m_frame->document(), fragment, options, EditActionPaste)->apply();
+ ASSERT(m_frame.document());
+ ReplaceSelectionCommand::create(*m_frame.document(), fragment, options, EditActionPaste)->apply();
revealSelectionAfterEditingOperation();
- if (m_frame->selection().isInPasswordField() || !isContinuousSpellCheckingEnabled())
- return;
- Node* nodeToCheck = m_frame->selection().rootEditableElement();
- if (!nodeToCheck)
+ if (m_frame.selection().isInPasswordField() || !spellChecker().isContinuousSpellCheckingEnabled())
return;
-
- RefPtr<Range> rangeToCheck = Range::create(*m_frame->document(), firstPositionInNode(nodeToCheck), lastPositionInNode(nodeToCheck));
- TextCheckingParagraph textToCheck(rangeToCheck, rangeToCheck);
- bool asynchronous = true;
- chunkAndMarkAllMisspellingsAndBadGrammar(resolveTextCheckingTypeMask(TextCheckingTypeSpelling | TextCheckingTypeGrammar), textToCheck, asynchronous);
+ spellChecker().chunkAndMarkAllMisspellingsAndBadGrammar(m_frame.selection().rootEditableElement());
}
void Editor::replaceSelectionWithText(const String& text, bool selectReplacement, bool smartReplace)
@@ -439,9 +514,7 @@ void Editor::replaceSelectionWithText(const String& text, bool selectReplacement
PassRefPtr<Range> Editor::selectedRange()
{
- if (!m_frame)
- return 0;
- return m_frame->selection().toNormalizedRange();
+ return m_frame.selection().toNormalizedRange();
}
bool Editor::shouldDeleteRange(Range* range) const
@@ -449,41 +522,12 @@ bool Editor::shouldDeleteRange(Range* range) const
if (!range || range->collapsed(IGNORE_EXCEPTION))
return false;
- if (!canDeleteRange(range))
- return false;
-
- return client().shouldDeleteRange(range);
-}
-
-bool Editor::tryDHTMLCopy()
-{
- if (m_frame->selection().isInPasswordField())
- return false;
-
- return !dispatchCPPEvent(eventNames().copyEvent, ClipboardWritable);
-}
-
-bool Editor::tryDHTMLCut()
-{
- if (m_frame->selection().isInPasswordField())
- return false;
-
- return !dispatchCPPEvent(eventNames().cutEvent, ClipboardWritable);
-}
-
-bool Editor::tryDHTMLPaste()
-{
- return !dispatchCPPEvent(eventNames().pasteEvent, ClipboardReadable);
-}
-
-bool Editor::shouldInsertText(const String& text, Range* range, EditorInsertAction action) const
-{
- return client().shouldInsertText(text, range, action);
+ return canDeleteRange(range);
}
void Editor::notifyComponentsOnChangedSelection(const VisibleSelection& oldSelection, FrameSelection::SetSelectionOptions options)
{
- client().respondToChangedSelection(m_frame);
+ client().respondToChangedSelection(m_frame.selection().selectionType());
setStartNewKillRingSequence(true);
}
@@ -491,22 +535,22 @@ void Editor::respondToChangedContents(const VisibleSelection& endingSelection)
{
if (AXObjectCache::accessibilityEnabled()) {
Node* node = endingSelection.start().deprecatedNode();
- if (AXObjectCache* cache = m_frame->document()->existingAXObjectCache())
+ if (AXObjectCache* cache = m_frame.document()->existingAXObjectCache())
cache->postNotification(node, AXObjectCache::AXValueChanged, false);
}
- updateMarkersForWordsAffectedByEditing(true);
+ spellChecker().updateMarkersForWordsAffectedByEditing(true);
client().respondToChangedContents();
}
TriState Editor::selectionUnorderedListState() const
{
- if (m_frame->selection().isCaret()) {
- if (enclosingNodeWithTag(m_frame->selection().selection().start(), ulTag))
+ if (m_frame.selection().isCaret()) {
+ if (enclosingNodeWithTag(m_frame.selection().selection().start(), ulTag))
return TrueTriState;
- } else if (m_frame->selection().isRange()) {
- Node* startNode = enclosingNodeWithTag(m_frame->selection().selection().start(), ulTag);
- Node* endNode = enclosingNodeWithTag(m_frame->selection().selection().end(), ulTag);
+ } else if (m_frame.selection().isRange()) {
+ Node* startNode = enclosingNodeWithTag(m_frame.selection().selection().start(), ulTag);
+ Node* endNode = enclosingNodeWithTag(m_frame.selection().selection().end(), ulTag);
if (startNode && endNode && startNode == endNode)
return TrueTriState;
}
@@ -516,12 +560,12 @@ TriState Editor::selectionUnorderedListState() const
TriState Editor::selectionOrderedListState() const
{
- if (m_frame->selection().isCaret()) {
- if (enclosingNodeWithTag(m_frame->selection().selection().start(), olTag))
+ if (m_frame.selection().isCaret()) {
+ if (enclosingNodeWithTag(m_frame.selection().selection().start(), olTag))
return TrueTriState;
- } else if (m_frame->selection().isRange()) {
- Node* startNode = enclosingNodeWithTag(m_frame->selection().selection().start(), olTag);
- Node* endNode = enclosingNodeWithTag(m_frame->selection().selection().end(), olTag);
+ } else if (m_frame.selection().isRange()) {
+ Node* startNode = enclosingNodeWithTag(m_frame.selection().selection().start(), olTag);
+ Node* endNode = enclosingNodeWithTag(m_frame.selection().selection().end(), olTag);
if (startNode && endNode && startNode == endNode)
return TrueTriState;
}
@@ -534,8 +578,8 @@ PassRefPtr<Node> Editor::insertOrderedList()
if (!canEditRichly())
return 0;
- ASSERT(m_frame->document());
- RefPtr<Node> newList = InsertListCommand::insertList(*m_frame->document(), InsertListCommand::OrderedList);
+ ASSERT(m_frame.document());
+ RefPtr<Node> newList = InsertListCommand::insertList(*m_frame.document(), InsertListCommand::OrderedList);
revealSelectionAfterEditingOperation();
return newList;
}
@@ -545,71 +589,71 @@ PassRefPtr<Node> Editor::insertUnorderedList()
if (!canEditRichly())
return 0;
- ASSERT(m_frame->document());
- RefPtr<Node> newList = InsertListCommand::insertList(*m_frame->document(), InsertListCommand::UnorderedList);
+ ASSERT(m_frame.document());
+ RefPtr<Node> newList = InsertListCommand::insertList(*m_frame.document(), InsertListCommand::UnorderedList);
revealSelectionAfterEditingOperation();
return newList;
}
bool Editor::canIncreaseSelectionListLevel()
{
- ASSERT(m_frame->document());
- return canEditRichly() && IncreaseSelectionListLevelCommand::canIncreaseSelectionListLevel(*m_frame->document());
+ ASSERT(m_frame.document());
+ return canEditRichly() && IncreaseSelectionListLevelCommand::canIncreaseSelectionListLevel(*m_frame.document());
}
bool Editor::canDecreaseSelectionListLevel()
{
- ASSERT(m_frame->document());
- return canEditRichly() && DecreaseSelectionListLevelCommand::canDecreaseSelectionListLevel(*m_frame->document());
+ ASSERT(m_frame.document());
+ return canEditRichly() && DecreaseSelectionListLevelCommand::canDecreaseSelectionListLevel(*m_frame.document());
}
PassRefPtr<Node> Editor::increaseSelectionListLevel()
{
- if (!canEditRichly() || m_frame->selection().isNone())
+ if (!canEditRichly() || m_frame.selection().isNone())
return 0;
- ASSERT(m_frame->document());
- RefPtr<Node> newList = IncreaseSelectionListLevelCommand::increaseSelectionListLevel(*m_frame->document());
+ ASSERT(m_frame.document());
+ RefPtr<Node> newList = IncreaseSelectionListLevelCommand::increaseSelectionListLevel(*m_frame.document());
revealSelectionAfterEditingOperation();
return newList;
}
PassRefPtr<Node> Editor::increaseSelectionListLevelOrdered()
{
- if (!canEditRichly() || m_frame->selection().isNone())
+ if (!canEditRichly() || m_frame.selection().isNone())
return 0;
- ASSERT(m_frame->document());
- RefPtr<Node> newList = IncreaseSelectionListLevelCommand::increaseSelectionListLevelOrdered(*m_frame->document());
+ ASSERT(m_frame.document());
+ RefPtr<Node> newList = IncreaseSelectionListLevelCommand::increaseSelectionListLevelOrdered(*m_frame.document());
revealSelectionAfterEditingOperation();
return newList.release();
}
PassRefPtr<Node> Editor::increaseSelectionListLevelUnordered()
{
- if (!canEditRichly() || m_frame->selection().isNone())
+ if (!canEditRichly() || m_frame.selection().isNone())
return 0;
- ASSERT(m_frame->document());
- RefPtr<Node> newList = IncreaseSelectionListLevelCommand::increaseSelectionListLevelUnordered(*m_frame->document());
+ ASSERT(m_frame.document());
+ RefPtr<Node> newList = IncreaseSelectionListLevelCommand::increaseSelectionListLevelUnordered(*m_frame.document());
revealSelectionAfterEditingOperation();
return newList.release();
}
void Editor::decreaseSelectionListLevel()
{
- if (!canEditRichly() || m_frame->selection().isNone())
+ if (!canEditRichly() || m_frame.selection().isNone())
return;
- ASSERT(m_frame->document());
- DecreaseSelectionListLevelCommand::decreaseSelectionListLevel(*m_frame->document());
+ ASSERT(m_frame.document());
+ DecreaseSelectionListLevelCommand::decreaseSelectionListLevel(*m_frame.document());
revealSelectionAfterEditingOperation();
}
void Editor::removeFormattingAndStyle()
{
- ASSERT(m_frame->document());
- RemoveFormatCommand::create(*m_frame->document())->apply();
+ ASSERT(m_frame.document());
+ RemoveFormatCommand::create(*m_frame.document())->apply();
}
void Editor::clearLastEditCommand()
@@ -617,83 +661,44 @@ void Editor::clearLastEditCommand()
m_lastEditCommand.clear();
}
-// Returns whether caller should continue with "the default processing", which is the same as
-// the event handler NOT setting the return value to false
-bool Editor::dispatchCPPEvent(const AtomicString &eventType, ClipboardAccessPolicy policy)
-{
- Node* target = findEventTargetFromSelection();
- if (!target)
- return true;
-
- RefPtr<Clipboard> clipboard = newGeneralClipboard(policy, m_frame);
-
- RefPtr<Event> evt = ClipboardEvent::create(eventType, true, true, clipboard);
- target->dispatchEvent(evt, IGNORE_EXCEPTION);
- bool noDefaultProcessing = evt->defaultPrevented();
- if (noDefaultProcessing && policy == ClipboardWritable) {
- RefPtr<ChromiumDataObject> dataObject = static_cast<ClipboardChromium*>(clipboard.get())->dataObject();
- Pasteboard::generalPasteboard()->writeDataObject(dataObject.release());
- }
-
- // invalidate clipboard here for security
- clipboard->setAccessPolicy(ClipboardNumb);
-
- return !noDefaultProcessing;
-}
-
Node* Editor::findEventTargetFrom(const VisibleSelection& selection) const
{
Node* target = selection.start().element();
if (!target)
- target = m_frame->document()->body();
- if (!target)
- return 0;
+ target = m_frame.document()->body();
return target;
}
Node* Editor::findEventTargetFromSelection() const
{
- return findEventTargetFrom(m_frame->selection().selection());
+ return findEventTargetFrom(m_frame.selection().selection());
}
void Editor::applyStyle(StylePropertySet* style, EditAction editingAction)
{
- switch (m_frame->selection().selectionType()) {
- case VisibleSelection::NoSelection:
+ switch (m_frame.selection().selectionType()) {
+ case NoSelection:
// do nothing
break;
- case VisibleSelection::CaretSelection:
+ case CaretSelection:
computeAndSetTypingStyle(style, editingAction);
break;
- case VisibleSelection::RangeSelection:
+ case RangeSelection:
if (style) {
- ASSERT(m_frame->document());
- ApplyStyleCommand::create(*m_frame->document(), EditingStyle::create(style).get(), editingAction)->apply();
+ ASSERT(m_frame.document());
+ ApplyStyleCommand::create(*m_frame.document(), EditingStyle::create(style).get(), editingAction)->apply();
}
break;
}
}
-bool Editor::shouldApplyStyle(StylePropertySet* style, Range* range)
-{
- return client().shouldApplyStyle(style, range);
-}
-
void Editor::applyParagraphStyle(StylePropertySet* style, EditAction editingAction)
{
- switch (m_frame->selection().selectionType()) {
- case VisibleSelection::NoSelection:
- // do nothing
- break;
- case VisibleSelection::CaretSelection:
- case VisibleSelection::RangeSelection:
- if (style) {
- ASSERT(m_frame->document());
- ApplyStyleCommand::create(*m_frame->document(), EditingStyle::create(style).get(), editingAction, ApplyStyleCommand::ForceBlockProperties)->apply();
- }
- break;
- }
+ if (m_frame.selection().isNone() || !style)
+ return;
+ ASSERT(m_frame.document());
+ ApplyStyleCommand::create(*m_frame.document(), EditingStyle::create(style).get(), editingAction, ApplyStyleCommand::ForceBlockProperties)->apply();
}
void Editor::applyStyleToSelection(StylePropertySet* style, EditAction editingAction)
@@ -701,8 +706,7 @@ void Editor::applyStyleToSelection(StylePropertySet* style, EditAction editingAc
if (!style || style->isEmpty() || !canEditRichly())
return;
- if (client().shouldApplyStyle(style, m_frame->selection().toNormalizedRange().get()))
- applyStyle(style, editingAction);
+ applyStyle(style, editingAction);
}
void Editor::applyParagraphStyleToSelection(StylePropertySet* style, EditAction editingAction)
@@ -710,76 +714,77 @@ void Editor::applyParagraphStyleToSelection(StylePropertySet* style, EditAction
if (!style || style->isEmpty() || !canEditRichly())
return;
- if (client().shouldApplyStyle(style, m_frame->selection().toNormalizedRange().get()))
- applyParagraphStyle(style, editingAction);
+ applyParagraphStyle(style, editingAction);
}
bool Editor::selectionStartHasStyle(CSSPropertyID propertyID, const String& value) const
{
return EditingStyle::create(propertyID, value)->triStateOfStyle(
- EditingStyle::styleAtSelectionStart(m_frame->selection().selection(), propertyID == CSSPropertyBackgroundColor).get());
+ EditingStyle::styleAtSelectionStart(m_frame.selection().selection(), propertyID == CSSPropertyBackgroundColor).get());
}
TriState Editor::selectionHasStyle(CSSPropertyID propertyID, const String& value) const
{
- return EditingStyle::create(propertyID, value)->triStateOfStyle(m_frame->selection().selection());
+ return EditingStyle::create(propertyID, value)->triStateOfStyle(m_frame.selection().selection());
}
String Editor::selectionStartCSSPropertyValue(CSSPropertyID propertyID)
{
- RefPtr<EditingStyle> selectionStyle = EditingStyle::styleAtSelectionStart(m_frame->selection().selection(),
+ RefPtr<EditingStyle> selectionStyle = EditingStyle::styleAtSelectionStart(m_frame.selection().selection(),
propertyID == CSSPropertyBackgroundColor);
if (!selectionStyle || !selectionStyle->style())
return String();
if (propertyID == CSSPropertyFontSize)
- return String::number(selectionStyle->legacyFontSize(m_frame->document()));
+ return String::number(selectionStyle->legacyFontSize(m_frame.document()));
return selectionStyle->style()->getPropertyValue(propertyID);
}
void Editor::indent()
{
- ASSERT(m_frame->document());
- IndentOutdentCommand::create(*m_frame->document(), IndentOutdentCommand::Indent)->apply();
+ ASSERT(m_frame.document());
+ IndentOutdentCommand::create(*m_frame.document(), IndentOutdentCommand::Indent)->apply();
}
void Editor::outdent()
{
- ASSERT(m_frame->document());
- IndentOutdentCommand::create(*m_frame->document(), IndentOutdentCommand::Outdent)->apply();
+ ASSERT(m_frame.document());
+ IndentOutdentCommand::create(*m_frame.document(), IndentOutdentCommand::Outdent)->apply();
}
static void dispatchEditableContentChangedEvents(PassRefPtr<Element> startRoot, PassRefPtr<Element> endRoot)
{
if (startRoot)
- startRoot->dispatchEvent(Event::create(eventNames().webkitEditableContentChangedEvent), IGNORE_EXCEPTION);
+ startRoot->dispatchEvent(Event::create(EventTypeNames::webkitEditableContentChanged), IGNORE_EXCEPTION);
if (endRoot && endRoot != startRoot)
- endRoot->dispatchEvent(Event::create(eventNames().webkitEditableContentChangedEvent), IGNORE_EXCEPTION);
+ endRoot->dispatchEvent(Event::create(EventTypeNames::webkitEditableContentChanged), IGNORE_EXCEPTION);
}
void Editor::appliedEditing(PassRefPtr<CompositeEditCommand> cmd)
{
- m_frame->document()->updateLayout();
+ EventQueueScope scope;
+ m_frame.document()->updateLayout();
EditCommandComposition* composition = cmd->composition();
ASSERT(composition);
+ dispatchEditableContentChangedEvents(composition->startingRootEditableElement(), composition->endingRootEditableElement());
VisibleSelection newSelection(cmd->endingSelection());
- // Don't clear the typing style with this selection change. We do those things elsewhere if necessary.
+ // Don't clear the typing style with this selection change. We do those things elsewhere if necessary.
changeSelectionAfterCommand(newSelection, 0);
- dispatchEditableContentChangedEvents(composition->startingRootEditableElement(), composition->endingRootEditableElement());
if (!cmd->preservesTypingStyle())
- m_frame->selection().clearTypingStyle();
+ m_frame.selection().clearTypingStyle();
// Command will be equal to last edit command only in the case of typing
- if (m_lastEditCommand.get() == cmd)
+ if (m_lastEditCommand.get() == cmd) {
ASSERT(cmd->isTypingCommand());
- else {
+ } else {
// Only register a new undo command if the command passed in is
// different from the last command
m_lastEditCommand = cmd;
- client().registerUndoStep(m_lastEditCommand->ensureComposition());
+ if (UndoStack* undoStack = this->undoStack())
+ undoStack->registerUndoStep(m_lastEditCommand->ensureComposition());
}
respondToChangedContents(newSelection);
@@ -787,38 +792,48 @@ void Editor::appliedEditing(PassRefPtr<CompositeEditCommand> cmd)
void Editor::unappliedEditing(PassRefPtr<EditCommandComposition> cmd)
{
- m_frame->document()->updateLayout();
+ EventQueueScope scope;
+ m_frame.document()->updateLayout();
+
+ dispatchEditableContentChangedEvents(cmd->startingRootEditableElement(), cmd->endingRootEditableElement());
VisibleSelection newSelection(cmd->startingSelection());
changeSelectionAfterCommand(newSelection, FrameSelection::CloseTyping | FrameSelection::ClearTypingStyle);
- dispatchEditableContentChangedEvents(cmd->startingRootEditableElement(), cmd->endingRootEditableElement());
m_lastEditCommand = 0;
- client().registerRedoStep(cmd);
+ if (UndoStack* undoStack = this->undoStack())
+ undoStack->registerRedoStep(cmd);
respondToChangedContents(newSelection);
}
void Editor::reappliedEditing(PassRefPtr<EditCommandComposition> cmd)
{
- m_frame->document()->updateLayout();
+ EventQueueScope scope;
+ m_frame.document()->updateLayout();
+
+ dispatchEditableContentChangedEvents(cmd->startingRootEditableElement(), cmd->endingRootEditableElement());
VisibleSelection newSelection(cmd->endingSelection());
changeSelectionAfterCommand(newSelection, FrameSelection::CloseTyping | FrameSelection::ClearTypingStyle);
- dispatchEditableContentChangedEvents(cmd->startingRootEditableElement(), cmd->endingRootEditableElement());
m_lastEditCommand = 0;
- client().registerUndoStep(cmd);
+ if (UndoStack* undoStack = this->undoStack())
+ undoStack->registerUndoStep(cmd);
respondToChangedContents(newSelection);
}
+PassOwnPtr<Editor> Editor::create(Frame& frame)
+{
+ return adoptPtr(new Editor(frame));
+}
+
Editor::Editor(Frame& frame)
- : FrameDestructionObserver(&frame)
+ : m_frame(frame)
, m_preventRevealSelection(0)
, m_shouldStartNewKillRingSequence(false)
// This is off by default, since most editors want this behavior (this matches IE but not FF).
, m_shouldStyleWithCSS(false)
, m_killRing(adoptPtr(new KillRing))
- , m_spellCheckRequester(adoptPtr(new SpellCheckRequester(frame)))
, m_areMarkedTextMatchesHighlighted(false)
, m_defaultParagraphSeparator(EditorParagraphSeparatorIsDiv)
, m_overwriteModeEnabled(false)
@@ -831,14 +846,14 @@ Editor::~Editor()
void Editor::clear()
{
- m_frame->inputMethodController().clear();
+ m_frame.inputMethodController().clear();
m_shouldStyleWithCSS = false;
m_defaultParagraphSeparator = EditorParagraphSeparatorIsDiv;
}
bool Editor::insertText(const String& text, Event* triggeringEvent)
{
- return m_frame->eventHandler()->handleTextInputEvent(text, triggeringEvent);
+ return m_frame.eventHandler().handleTextInputEvent(text, triggeringEvent);
}
bool Editor::insertTextWithoutSendingTextEvent(const String& text, bool selectInsertedText, TextEvent* triggeringEvent)
@@ -851,11 +866,7 @@ bool Editor::insertTextWithoutSendingTextEvent(const String& text, bool selectIn
return false;
RefPtr<Range> range = selection.toNormalizedRange();
- if (!shouldInsertText(text, range.get(), EditorInsertActionTyped))
- return true;
-
- if (!text.isEmpty())
- updateMarkersForWordsAffectedByEditing(isSpaceOrNewline(text[0]));
+ spellChecker().updateMarkersForWordsAffectedByEditing(isSpaceOrNewline(text[0]));
// Get the selection to use for the event that triggered this insertText.
// If the event handler changed the selection, we may want to use a different selection
@@ -863,8 +874,7 @@ bool Editor::insertTextWithoutSendingTextEvent(const String& text, bool selectIn
selection = selectionForCommand(triggeringEvent);
if (selection.isContentEditable()) {
if (Node* selectionStart = selection.start().deprecatedNode()) {
- RefPtr<Document> document = &selectionStart->document();
- ASSERT(document);
+ RefPtr<Document> document(selectionStart->document());
// Insert the text
TypingCommand::Options options = 0;
@@ -888,13 +898,10 @@ bool Editor::insertLineBreak()
if (!canEdit())
return false;
- if (!shouldInsertText("\n", m_frame->selection().toNormalizedRange().get(), EditorInsertActionTyped))
- return true;
-
- VisiblePosition caret = m_frame->selection().selection().visibleStart();
+ VisiblePosition caret = m_frame.selection().selection().visibleStart();
bool alignToEdge = isEndOfEditableOrNonEditableContent(caret);
- ASSERT(m_frame->document());
- TypingCommand::insertLineBreak(*m_frame->document(), 0);
+ ASSERT(m_frame.document());
+ TypingCommand::insertLineBreak(*m_frame.document(), 0);
revealSelectionAfterEditingOperation(alignToEdge ? ScrollAlignment::alignToEdgeIfNeeded : ScrollAlignment::alignCenterIfNeeded);
return true;
@@ -908,13 +915,10 @@ bool Editor::insertParagraphSeparator()
if (!canEditRichly())
return insertLineBreak();
- if (!shouldInsertText("\n", m_frame->selection().toNormalizedRange().get(), EditorInsertActionTyped))
- return true;
-
- VisiblePosition caret = m_frame->selection().selection().visibleStart();
+ VisiblePosition caret = m_frame.selection().selection().visibleStart();
bool alignToEdge = isEndOfEditableOrNonEditableContent(caret);
- ASSERT(m_frame->document());
- TypingCommand::insertParagraphSeparator(*m_frame->document(), 0);
+ ASSERT(m_frame.document());
+ TypingCommand::insertParagraphSeparator(*m_frame.document(), 0);
revealSelectionAfterEditingOperation(alignToEdge ? ScrollAlignment::alignToEdgeIfNeeded : ScrollAlignment::alignCenterIfNeeded);
return true;
@@ -924,19 +928,17 @@ void Editor::cut()
{
if (tryDHTMLCut())
return; // DHTML did the whole operation
- if (!canCut()) {
- systemBeep();
+ if (!canCut())
return;
- }
RefPtr<Range> selection = selectedRange();
if (shouldDeleteRange(selection.get())) {
- updateMarkersForWordsAffectedByEditing(true);
- String plainText = m_frame->selectedTextForClipboard();
- if (enclosingTextFormControl(m_frame->selection().start())) {
+ spellChecker().updateMarkersForWordsAffectedByEditing(true);
+ String plainText = m_frame.selectedTextForClipboard();
+ if (enclosingTextFormControl(m_frame.selection().start())) {
Pasteboard::generalPasteboard()->writePlainText(plainText,
canSmartCopyOrDelete() ? Pasteboard::CanSmartReplace : Pasteboard::CannotSmartReplace);
} else {
- Pasteboard::generalPasteboard()->writeSelection(selection.get(), canSmartCopyOrDelete(), plainText);
+ writeSelectionToPasteboard(Pasteboard::generalPasteboard(), selection.get(), plainText);
}
deleteSelectionWithSmartDelete(canSmartCopyOrDelete());
}
@@ -946,56 +948,50 @@ void Editor::copy()
{
if (tryDHTMLCopy())
return; // DHTML did the whole operation
- if (!canCopy()) {
- systemBeep();
+ if (!canCopy())
return;
- }
-
- if (enclosingTextFormControl(m_frame->selection().start())) {
- Pasteboard::generalPasteboard()->writePlainText(m_frame->selectedTextForClipboard(),
+ if (enclosingTextFormControl(m_frame.selection().start())) {
+ Pasteboard::generalPasteboard()->writePlainText(m_frame.selectedTextForClipboard(),
canSmartCopyOrDelete() ? Pasteboard::CanSmartReplace : Pasteboard::CannotSmartReplace);
} else {
- Document* document = m_frame->document();
+ Document* document = m_frame.document();
if (HTMLImageElement* imageElement = imageElementFromImageDocument(document))
- Pasteboard::generalPasteboard()->writeImage(imageElement, document->url(), document->title());
+ writeImageNodeToPasteboard(Pasteboard::generalPasteboard(), imageElement, document->title());
else
- Pasteboard::generalPasteboard()->writeSelection(selectedRange().get(), canSmartCopyOrDelete(), m_frame->selectedTextForClipboard());
+ writeSelectionToPasteboard(Pasteboard::generalPasteboard(), selectedRange().get(), m_frame.selectedTextForClipboard());
}
}
void Editor::paste()
{
- ASSERT(m_frame->document());
- if (tryDHTMLPaste())
+ ASSERT(m_frame.document());
+ if (tryDHTMLPaste(AllMimeTypes))
return; // DHTML did the whole operation
if (!canPaste())
return;
- updateMarkersForWordsAffectedByEditing(false);
- ResourceFetcher* loader = m_frame->document()->fetcher();
+ spellChecker().updateMarkersForWordsAffectedByEditing(false);
+ ResourceFetcher* loader = m_frame.document()->fetcher();
ResourceCacheValidationSuppressor validationSuppressor(loader);
- if (m_frame->selection().isContentRichlyEditable())
- pasteWithPasteboard(Pasteboard::generalPasteboard(), true);
+ if (m_frame.selection().isContentRichlyEditable())
+ pasteWithPasteboard(Pasteboard::generalPasteboard());
else
pasteAsPlainTextWithPasteboard(Pasteboard::generalPasteboard());
}
void Editor::pasteAsPlainText()
{
- if (tryDHTMLPaste())
+ if (tryDHTMLPaste(PlainTextOnly))
return;
if (!canPaste())
return;
- updateMarkersForWordsAffectedByEditing(false);
+ spellChecker().updateMarkersForWordsAffectedByEditing(false);
pasteAsPlainTextWithPasteboard(Pasteboard::generalPasteboard());
}
void Editor::performDelete()
{
- if (!canDelete()) {
- systemBeep();
+ if (!canDelete())
return;
- }
-
addToKillRing(selectedRange().get(), false);
deleteSelectionWithSmartDelete(canSmartCopyOrDelete());
@@ -1004,131 +1000,35 @@ void Editor::performDelete()
setStartNewKillRingSequence(false);
}
-void Editor::simplifyMarkup(Node* startNode, Node* endNode)
-{
- if (!startNode)
- return;
- if (endNode) {
- if (&startNode->document() != &endNode->document())
- return;
- // check if start node is before endNode
- Node* node = startNode;
- while (node && node != endNode)
- node = NodeTraversal::next(node);
- if (!node)
- return;
- }
-
- ASSERT(m_frame->document());
- SimplifyMarkupCommand::create(*m_frame->document(), startNode, endNode ? NodeTraversal::next(endNode) : 0)->apply();
-}
-
-void Editor::copyURL(const KURL& url, const String& title)
-{
- Pasteboard::generalPasteboard()->writeURL(url, title);
-}
-
void Editor::copyImage(const HitTestResult& result)
{
- KURL url = result.absoluteLinkURL();
- if (url.isEmpty())
- url = result.absoluteImageURL();
-
- Pasteboard::generalPasteboard()->writeImage(result.innerNonSharedNode(), url, result.altDisplayString());
-}
-
-bool Editor::isContinuousSpellCheckingEnabled() const
-{
- return client().isContinuousSpellCheckingEnabled();
-}
-
-void Editor::toggleContinuousSpellChecking()
-{
- client().toggleContinuousSpellChecking();
- if (isContinuousSpellCheckingEnabled())
- return;
- for (Frame* frame = m_frame->page()->mainFrame(); frame && frame->document(); frame = frame->tree()->traverseNext()) {
- for (Node* node = frame->document()->rootNode(); node; node = NodeTraversal::next(node)) {
- node->setAlreadySpellChecked(false);
- }
- }
-}
-
-bool Editor::isGrammarCheckingEnabled()
-{
- return client().isGrammarCheckingEnabled();
-}
-
-bool Editor::shouldEndEditing(Range* range)
-{
- return client().shouldEndEditing(range);
-}
-
-bool Editor::shouldBeginEditing(Range* range)
-{
- return client().shouldBeginEditing(range);
-}
-
-void Editor::clearUndoRedoOperations()
-{
- client().clearUndoRedoOperations();
+ writeImageNodeToPasteboard(Pasteboard::generalPasteboard(), result.innerNonSharedNode(), result.altDisplayString());
}
bool Editor::canUndo()
{
- return client().canUndo();
+ if (UndoStack* undoStack = this->undoStack())
+ return undoStack->canUndo();
+ return false;
}
void Editor::undo()
{
- client().undo();
+ if (UndoStack* undoStack = this->undoStack())
+ undoStack->undo();
}
bool Editor::canRedo()
{
- return client().canRedo();
+ if (UndoStack* undoStack = this->undoStack())
+ return undoStack->canRedo();
+ return false;
}
void Editor::redo()
{
- client().redo();
-}
-
-void Editor::elementDidBeginEditing(Element* element)
-{
- if (isContinuousSpellCheckingEnabled() && unifiedTextCheckerEnabled()) {
- bool isTextField = false;
- HTMLTextFormControlElement* enclosingHTMLTextFormControlElement = 0;
- if (!isHTMLTextFormControlElement(element))
- enclosingHTMLTextFormControlElement = enclosingTextFormControl(firstPositionInNode(element));
- element = enclosingHTMLTextFormControlElement ? enclosingHTMLTextFormControlElement : element;
- Element* parent = element;
- if (isHTMLTextFormControlElement(element)) {
- HTMLTextFormControlElement* textControl = toHTMLTextFormControlElement(element);
- parent = textControl;
- element = textControl->innerTextElement();
- isTextField = textControl->hasTagName(inputTag) && toHTMLInputElement(textControl)->isTextField();
- }
-
- if (isTextField || !parent->isAlreadySpellChecked()) {
- // We always recheck textfields because markers are removed from them on blur.
- VisibleSelection selection = VisibleSelection::selectionFromContentsOfNode(element);
- markMisspellingsAndBadGrammar(selection);
- if (!isTextField)
- parent->setAlreadySpellChecked(true);
- }
- }
-}
-
-void Editor::didBeginEditing(Element* rootEditableElement)
-{
- elementDidBeginEditing(rootEditableElement);
- client().didBeginEditing();
-}
-
-void Editor::didEndEditing()
-{
- client().didEndEditing();
+ if (UndoStack* undoStack = this->undoStack())
+ undoStack->redo();
}
void Editor::setBaseWritingDirection(WritingDirection direction)
@@ -1148,647 +1048,12 @@ void Editor::setBaseWritingDirection(WritingDirection direction)
applyParagraphStyleToSelection(style.get(), EditActionSetWritingDirection);
}
-WritingDirection Editor::baseWritingDirectionForSelectionStart() const
-{
- WritingDirection result = LeftToRightWritingDirection;
-
- Position pos = m_frame->selection().selection().visibleStart().deepEquivalent();
- Node* node = pos.deprecatedNode();
- if (!node)
- return result;
-
- RenderObject* renderer = node->renderer();
- if (!renderer)
- return result;
-
- if (!renderer->isRenderBlockFlow()) {
- renderer = renderer->containingBlock();
- if (!renderer)
- return result;
- }
-
- RenderStyle* style = renderer->style();
- if (!style)
- return result;
-
- switch (style->direction()) {
- case LTR:
- return LeftToRightWritingDirection;
- case RTL:
- return RightToLeftWritingDirection;
- }
-
- return result;
-}
-
-void Editor::ignoreSpelling()
-{
- if (RefPtr<Range> selectedRange = frame().selection().toNormalizedRange())
- frame().document()->markers()->removeMarkers(selectedRange.get(), DocumentMarker::Spelling);
-}
-
-void Editor::advanceToNextMisspelling(bool startBeforeSelection)
-{
- // The basic approach is to search in two phases - from the selection end to the end of the doc, and
- // then we wrap and search from the doc start to (approximately) where we started.
-
- // Start at the end of the selection, search to edge of document. Starting at the selection end makes
- // repeated "check spelling" commands work.
- VisibleSelection selection(frame().selection().selection());
- RefPtr<Range> spellingSearchRange(rangeOfContents(frame().document()));
-
- bool startedWithSelection = false;
- if (selection.start().deprecatedNode()) {
- startedWithSelection = true;
- if (startBeforeSelection) {
- VisiblePosition start(selection.visibleStart());
- // We match AppKit's rule: Start 1 character before the selection.
- VisiblePosition oneBeforeStart = start.previous();
- setStart(spellingSearchRange.get(), oneBeforeStart.isNotNull() ? oneBeforeStart : start);
- } else
- setStart(spellingSearchRange.get(), selection.visibleEnd());
- }
-
- Position position = spellingSearchRange->startPosition();
- if (!isEditablePosition(position)) {
- // This shouldn't happen in very often because the Spelling menu items aren't enabled unless the
- // selection is editable.
- // This can happen in Mail for a mix of non-editable and editable content (like Stationary),
- // when spell checking the whole document before sending the message.
- // In that case the document might not be editable, but there are editable pockets that need to be spell checked.
-
- position = firstEditablePositionAfterPositionInRoot(position, frame().document()->documentElement()).deepEquivalent();
- if (position.isNull())
- return;
-
- Position rangeCompliantPosition = position.parentAnchoredEquivalent();
- spellingSearchRange->setStart(rangeCompliantPosition.deprecatedNode(), rangeCompliantPosition.deprecatedEditingOffset(), IGNORE_EXCEPTION);
- startedWithSelection = false; // won't need to wrap
- }
-
- // topNode defines the whole range we want to operate on
- Node* topNode = highestEditableRoot(position);
- // FIXME: lastOffsetForEditing() is wrong here if editingIgnoresContent(highestEditableRoot()) returns true (e.g. a <table>)
- spellingSearchRange->setEnd(topNode, lastOffsetForEditing(topNode), IGNORE_EXCEPTION);
-
- // If spellingSearchRange starts in the middle of a word, advance to the next word so we start checking
- // at a word boundary. Going back by one char and then forward by a word does the trick.
- if (startedWithSelection) {
- VisiblePosition oneBeforeStart = startVisiblePosition(spellingSearchRange.get(), DOWNSTREAM).previous();
- if (oneBeforeStart.isNotNull())
- setStart(spellingSearchRange.get(), endOfWord(oneBeforeStart));
- // else we were already at the start of the editable node
- }
-
- if (spellingSearchRange->collapsed(IGNORE_EXCEPTION))
- return; // nothing to search in
-
- // We go to the end of our first range instead of the start of it, just to be sure
- // we don't get foiled by any word boundary problems at the start. It means we might
- // do a tiny bit more searching.
- Node* searchEndNodeAfterWrap = spellingSearchRange->endContainer();
- int searchEndOffsetAfterWrap = spellingSearchRange->endOffset();
-
- int misspellingOffset = 0;
- GrammarDetail grammarDetail;
- int grammarPhraseOffset = 0;
- RefPtr<Range> grammarSearchRange;
- String badGrammarPhrase;
- String misspelledWord;
-
- bool isSpelling = true;
- int foundOffset = 0;
- String foundItem;
- RefPtr<Range> firstMisspellingRange;
- if (unifiedTextCheckerEnabled()) {
- grammarSearchRange = spellingSearchRange->cloneRange(IGNORE_EXCEPTION);
- foundItem = TextCheckingHelper(client(), spellingSearchRange).findFirstMisspellingOrBadGrammar(isGrammarCheckingEnabled(), isSpelling, foundOffset, grammarDetail);
- if (isSpelling) {
- misspelledWord = foundItem;
- misspellingOffset = foundOffset;
- } else {
- badGrammarPhrase = foundItem;
- grammarPhraseOffset = foundOffset;
- }
- } else {
- misspelledWord = TextCheckingHelper(client(), spellingSearchRange).findFirstMisspelling(misspellingOffset, false, firstMisspellingRange);
- grammarSearchRange = spellingSearchRange->cloneRange(IGNORE_EXCEPTION);
- if (!misspelledWord.isEmpty()) {
- // Stop looking at start of next misspelled word
- CharacterIterator chars(grammarSearchRange.get());
- chars.advance(misspellingOffset);
- grammarSearchRange->setEnd(chars.range()->startContainer(), chars.range()->startOffset(), IGNORE_EXCEPTION);
- }
-
- if (isGrammarCheckingEnabled())
- badGrammarPhrase = TextCheckingHelper(client(), grammarSearchRange).findFirstBadGrammar(grammarDetail, grammarPhraseOffset, false);
- }
-
- // If we found neither bad grammar nor a misspelled word, wrap and try again (but don't bother if we started at the beginning of the
- // block rather than at a selection).
- if (startedWithSelection && !misspelledWord && !badGrammarPhrase) {
- spellingSearchRange->setStart(topNode, 0, IGNORE_EXCEPTION);
- // going until the end of the very first chunk we tested is far enough
- spellingSearchRange->setEnd(searchEndNodeAfterWrap, searchEndOffsetAfterWrap, IGNORE_EXCEPTION);
-
- if (unifiedTextCheckerEnabled()) {
- grammarSearchRange = spellingSearchRange->cloneRange(IGNORE_EXCEPTION);
- foundItem = TextCheckingHelper(client(), spellingSearchRange).findFirstMisspellingOrBadGrammar(isGrammarCheckingEnabled(), isSpelling, foundOffset, grammarDetail);
- if (isSpelling) {
- misspelledWord = foundItem;
- misspellingOffset = foundOffset;
- } else {
- badGrammarPhrase = foundItem;
- grammarPhraseOffset = foundOffset;
- }
- } else {
- misspelledWord = TextCheckingHelper(client(), spellingSearchRange).findFirstMisspelling(misspellingOffset, false, firstMisspellingRange);
- grammarSearchRange = spellingSearchRange->cloneRange(IGNORE_EXCEPTION);
- if (!misspelledWord.isEmpty()) {
- // Stop looking at start of next misspelled word
- CharacterIterator chars(grammarSearchRange.get());
- chars.advance(misspellingOffset);
- grammarSearchRange->setEnd(chars.range()->startContainer(), chars.range()->startOffset(), IGNORE_EXCEPTION);
- }
-
- if (isGrammarCheckingEnabled())
- badGrammarPhrase = TextCheckingHelper(client(), grammarSearchRange).findFirstBadGrammar(grammarDetail, grammarPhraseOffset, false);
- }
- }
-
- if (!badGrammarPhrase.isEmpty()) {
- // We found bad grammar. Since we only searched for bad grammar up to the first misspelled word, the bad grammar
- // takes precedence and we ignore any potential misspelled word. Select the grammar detail, update the spelling
- // panel, and store a marker so we draw the green squiggle later.
-
- ASSERT(badGrammarPhrase.length() > 0);
- ASSERT(grammarDetail.location != -1 && grammarDetail.length > 0);
-
- // FIXME 4859190: This gets confused with doubled punctuation at the end of a paragraph
- RefPtr<Range> badGrammarRange = TextIterator::subrange(grammarSearchRange.get(), grammarPhraseOffset + grammarDetail.location, grammarDetail.length);
- frame().selection().setSelection(VisibleSelection(badGrammarRange.get(), SEL_DEFAULT_AFFINITY));
- frame().selection().revealSelection();
-
- frame().document()->markers()->addMarker(badGrammarRange.get(), DocumentMarker::Grammar, grammarDetail.userDescription);
- } else if (!misspelledWord.isEmpty()) {
- // We found a misspelling, but not any earlier bad grammar. Select the misspelling, update the spelling panel, and store
- // a marker so we draw the red squiggle later.
-
- RefPtr<Range> misspellingRange = TextIterator::subrange(spellingSearchRange.get(), misspellingOffset, misspelledWord.length());
- frame().selection().setSelection(VisibleSelection(misspellingRange.get(), DOWNSTREAM));
- frame().selection().revealSelection();
-
- client().updateSpellingUIWithMisspelledWord(misspelledWord);
- frame().document()->markers()->addMarker(misspellingRange.get(), DocumentMarker::Spelling);
- }
-}
-
-String Editor::misspelledWordAtCaretOrRange(Node* clickedNode) const
-{
- if (!isContinuousSpellCheckingEnabled() || !clickedNode || !isSpellCheckingEnabledFor(clickedNode))
- return String();
-
- VisibleSelection selection = m_frame->selection().selection();
- if (!selection.isContentEditable() || selection.isNone())
- return String();
-
- VisibleSelection wordSelection(selection.base());
- wordSelection.expandUsingGranularity(WordGranularity);
- RefPtr<Range> wordRange = wordSelection.toNormalizedRange();
-
- // In compliance with GTK+ applications, additionally allow to provide suggestions when the current
- // selection exactly match the word selection.
- if (selection.isRange() && !areRangesEqual(wordRange.get(), selection.toNormalizedRange().get()))
- return String();
-
- String word = wordRange->text();
- if (word.isEmpty())
- return String();
-
- int wordLength = word.length();
- int misspellingLocation = -1;
- int misspellingLength = 0;
- textChecker().checkSpellingOfString(word, &misspellingLocation, &misspellingLength);
-
- return misspellingLength == wordLength ? word : String();
-}
-
-void Editor::showSpellingGuessPanel()
-{
- if (client().spellingUIIsShowing()) {
- client().showSpellingUI(false);
- return;
- }
-
- advanceToNextMisspelling(true);
- client().showSpellingUI(true);
-}
-
-void Editor::clearMisspellingsAndBadGrammar(const VisibleSelection &movingSelection)
-{
- RefPtr<Range> selectedRange = movingSelection.toNormalizedRange();
- if (selectedRange)
- frame().document()->markers()->removeMarkers(selectedRange.get(), DocumentMarker::MisspellingMarkers());
-}
-
-void Editor::markMisspellingsAndBadGrammar(const VisibleSelection &movingSelection)
-{
- markMisspellingsAndBadGrammar(movingSelection, isContinuousSpellCheckingEnabled() && isGrammarCheckingEnabled(), movingSelection);
-}
-
-void Editor::markMisspellingsAfterTypingToWord(const VisiblePosition &wordStart, const VisibleSelection& selectionAfterTyping)
-{
- if (unifiedTextCheckerEnabled()) {
- TextCheckingTypeMask textCheckingOptions = 0;
-
- if (isContinuousSpellCheckingEnabled())
- textCheckingOptions |= TextCheckingTypeSpelling;
-
- if (!(textCheckingOptions & TextCheckingTypeSpelling))
- return;
-
- if (isGrammarCheckingEnabled())
- textCheckingOptions |= TextCheckingTypeGrammar;
-
- VisibleSelection adjacentWords = VisibleSelection(startOfWord(wordStart, LeftWordIfOnBoundary), endOfWord(wordStart, RightWordIfOnBoundary));
- if (textCheckingOptions & TextCheckingTypeGrammar) {
- VisibleSelection selectedSentence = VisibleSelection(startOfSentence(wordStart), endOfSentence(wordStart));
- markAllMisspellingsAndBadGrammarInRanges(textCheckingOptions, adjacentWords.toNormalizedRange().get(), selectedSentence.toNormalizedRange().get());
- } else
- markAllMisspellingsAndBadGrammarInRanges(textCheckingOptions, adjacentWords.toNormalizedRange().get(), adjacentWords.toNormalizedRange().get());
- return;
- }
-
- if (!isContinuousSpellCheckingEnabled())
- return;
-
- // Check spelling of one word
- RefPtr<Range> misspellingRange;
- markMisspellings(VisibleSelection(startOfWord(wordStart, LeftWordIfOnBoundary), endOfWord(wordStart, RightWordIfOnBoundary)), misspellingRange);
-
- // Autocorrect the misspelled word.
- if (!misspellingRange)
- return;
-
- // Get the misspelled word.
- const String misspelledWord = plainText(misspellingRange.get());
- String autocorrectedString = textChecker().getAutoCorrectSuggestionForMisspelledWord(misspelledWord);
-
- // If autocorrected word is non empty, replace the misspelled word by this word.
- if (!autocorrectedString.isEmpty()) {
- VisibleSelection newSelection(misspellingRange.get(), DOWNSTREAM);
- if (newSelection != frame().selection().selection()) {
- if (!frame().selection().shouldChangeSelection(newSelection))
- return;
- frame().selection().setSelection(newSelection);
- }
-
- if (!frame().editor().shouldInsertText(autocorrectedString, misspellingRange.get(), EditorInsertActionTyped))
- return;
- frame().editor().replaceSelectionWithText(autocorrectedString, false, false);
-
- // Reset the charet one character further.
- frame().selection().moveTo(frame().selection().end());
- frame().selection().modify(FrameSelection::AlterationMove, DirectionForward, CharacterGranularity);
- }
-
- if (!isGrammarCheckingEnabled())
- return;
-
- // Check grammar of entire sentence
- markBadGrammar(VisibleSelection(startOfSentence(wordStart), endOfSentence(wordStart)));
-}
-
-void Editor::markMisspellingsOrBadGrammar(const VisibleSelection& selection, bool checkSpelling, RefPtr<Range>& firstMisspellingRange)
-{
- // This function is called with a selection already expanded to word boundaries.
- // Might be nice to assert that here.
-
- // This function is used only for as-you-type checking, so if that's off we do nothing. Note that
- // grammar checking can only be on if spell checking is also on.
- if (!isContinuousSpellCheckingEnabled())
- return;
-
- RefPtr<Range> searchRange(selection.toNormalizedRange());
- if (!searchRange)
- return;
-
- // If we're not in an editable node, bail.
- Node* editableNode = searchRange->startContainer();
- if (!editableNode || !editableNode->rendererIsEditable())
- return;
-
- if (!isSpellCheckingEnabledFor(editableNode))
- return;
-
- TextCheckingHelper checker(client(), searchRange);
- if (checkSpelling)
- checker.markAllMisspellings(firstMisspellingRange);
- else if (isGrammarCheckingEnabled())
- checker.markAllBadGrammar();
-}
-
-bool Editor::isSpellCheckingEnabledFor(Node* node) const
-{
- if (!node)
- return false;
- const Element* focusedElement = node->isElementNode() ? toElement(node) : node->parentElement();
- if (!focusedElement)
- return false;
- return focusedElement->isSpellCheckingEnabled();
-}
-
-bool Editor::isSpellCheckingEnabledInFocusedNode() const
-{
- return isSpellCheckingEnabledFor(m_frame->selection().start().deprecatedNode());
-}
-
-void Editor::markMisspellings(const VisibleSelection& selection, RefPtr<Range>& firstMisspellingRange)
-{
- markMisspellingsOrBadGrammar(selection, true, firstMisspellingRange);
-}
-
-void Editor::markBadGrammar(const VisibleSelection& selection)
-{
- RefPtr<Range> firstMisspellingRange;
- markMisspellingsOrBadGrammar(selection, false, firstMisspellingRange);
-}
-
-void Editor::markAllMisspellingsAndBadGrammarInRanges(TextCheckingTypeMask textCheckingOptions, Range* spellingRange, Range* grammarRange)
-{
- ASSERT(m_frame);
- ASSERT(unifiedTextCheckerEnabled());
-
- bool shouldMarkGrammar = textCheckingOptions & TextCheckingTypeGrammar;
-
- // This function is called with selections already expanded to word boundaries.
- if (!spellingRange || (shouldMarkGrammar && !grammarRange))
- return;
-
- // If we're not in an editable node, bail.
- Node* editableNode = spellingRange->startContainer();
- if (!editableNode || !editableNode->rendererIsEditable())
- return;
-
- if (!isSpellCheckingEnabledFor(editableNode))
- return;
-
- Range* rangeToCheck = shouldMarkGrammar ? grammarRange : spellingRange;
- TextCheckingParagraph fullParagraphToCheck(rangeToCheck);
-
- bool asynchronous = m_frame && m_frame->settings() && m_frame->settings()->asynchronousSpellCheckingEnabled();
- chunkAndMarkAllMisspellingsAndBadGrammar(textCheckingOptions, fullParagraphToCheck, asynchronous);
-}
-
-void Editor::chunkAndMarkAllMisspellingsAndBadGrammar(TextCheckingTypeMask textCheckingOptions, const TextCheckingParagraph& fullParagraphToCheck, bool asynchronous)
-{
- if (fullParagraphToCheck.isRangeEmpty() || fullParagraphToCheck.isEmpty())
- return;
-
- // Since the text may be quite big chunk it up and adjust to the sentence boundary.
- const int kChunkSize = 16 * 1024;
- int start = fullParagraphToCheck.checkingStart();
- int end = fullParagraphToCheck.checkingEnd();
- start = std::min(start, end);
- end = std::max(start, end);
- const int kNumChunksToCheck = asynchronous ? (end - start + kChunkSize - 1) / (kChunkSize) : 1;
- int currentChunkStart = start;
- RefPtr<Range> checkRange = fullParagraphToCheck.checkingRange();
- if (kNumChunksToCheck == 1 && asynchronous) {
- markAllMisspellingsAndBadGrammarInRanges(textCheckingOptions, checkRange.get(), checkRange.get(), asynchronous, 0);
- return;
- }
-
- for (int iter = 0; iter < kNumChunksToCheck; ++iter) {
- checkRange = fullParagraphToCheck.subrange(currentChunkStart, kChunkSize);
- setStart(checkRange.get(), startOfSentence(checkRange->startPosition()));
- setEnd(checkRange.get(), endOfSentence(checkRange->endPosition()));
-
- int checkingLength = 0;
- markAllMisspellingsAndBadGrammarInRanges(textCheckingOptions, checkRange.get(), checkRange.get(), asynchronous, iter, &checkingLength);
- currentChunkStart += checkingLength;
- }
-}
-
-void Editor::markAllMisspellingsAndBadGrammarInRanges(TextCheckingTypeMask textCheckingOptions, Range* checkRange, Range* paragraphRange, bool asynchronous, int requestNumber, int* checkingLength)
-{
- TextCheckingParagraph sentenceToCheck(checkRange, paragraphRange);
- if (checkingLength)
- *checkingLength = sentenceToCheck.checkingLength();
-
- RefPtr<SpellCheckRequest> request = SpellCheckRequest::create(resolveTextCheckingTypeMask(textCheckingOptions), TextCheckingProcessBatch, checkRange, paragraphRange, requestNumber);
-
- if (asynchronous) {
- m_spellCheckRequester->requestCheckingFor(request);
- } else {
- Vector<TextCheckingResult> results;
- checkTextOfParagraph(textChecker(), sentenceToCheck.text(), resolveTextCheckingTypeMask(textCheckingOptions), results);
- markAndReplaceFor(request, results);
- }
-}
-
-void Editor::markAndReplaceFor(PassRefPtr<SpellCheckRequest> request, const Vector<TextCheckingResult>& results)
-{
- ASSERT(request);
-
- TextCheckingTypeMask textCheckingOptions = request->data().mask();
- TextCheckingParagraph paragraph(request->checkingRange(), request->paragraphRange());
-
- bool shouldMarkSpelling = textCheckingOptions & TextCheckingTypeSpelling;
- bool shouldMarkGrammar = textCheckingOptions & TextCheckingTypeGrammar;
-
- // Expand the range to encompass entire paragraphs, since text checking needs that much context.
- int selectionOffset = 0;
- int ambiguousBoundaryOffset = -1;
- bool selectionChanged = false;
- bool restoreSelectionAfterChange = false;
- bool adjustSelectionForParagraphBoundaries = false;
-
- if (shouldMarkSpelling) {
- if (m_frame->selection().selectionType() == VisibleSelection::CaretSelection) {
- // Attempt to save the caret position so we can restore it later if needed
- Position caretPosition = m_frame->selection().end();
- selectionOffset = paragraph.offsetTo(caretPosition, ASSERT_NO_EXCEPTION);
- restoreSelectionAfterChange = true;
- if (selectionOffset > 0 && (static_cast<unsigned>(selectionOffset) > paragraph.text().length() || paragraph.textCharAt(selectionOffset - 1) == newlineCharacter))
- adjustSelectionForParagraphBoundaries = true;
- if (selectionOffset > 0 && static_cast<unsigned>(selectionOffset) <= paragraph.text().length() && isAmbiguousBoundaryCharacter(paragraph.textCharAt(selectionOffset - 1)))
- ambiguousBoundaryOffset = selectionOffset - 1;
- }
- }
-
- for (unsigned i = 0; i < results.size(); i++) {
- int spellingRangeEndOffset = paragraph.checkingEnd();
- const TextCheckingResult* result = &results[i];
- int resultLocation = result->location + paragraph.checkingStart();
- int resultLength = result->length;
- bool resultEndsAtAmbiguousBoundary = ambiguousBoundaryOffset >= 0 && resultLocation + resultLength == ambiguousBoundaryOffset;
-
- // Only mark misspelling if:
- // 1. Current text checking isn't done for autocorrection, in which case shouldMarkSpelling is false.
- // 2. Result falls within spellingRange.
- // 3. The word in question doesn't end at an ambiguous boundary. For instance, we would not mark
- // "wouldn'" as misspelled right after apostrophe is typed.
- if (shouldMarkSpelling && result->type == TextCheckingTypeSpelling && resultLocation >= paragraph.checkingStart() && resultLocation + resultLength <= spellingRangeEndOffset && !resultEndsAtAmbiguousBoundary) {
- ASSERT(resultLength > 0 && resultLocation >= 0);
- RefPtr<Range> misspellingRange = paragraph.subrange(resultLocation, resultLength);
- misspellingRange->startContainer()->document().markers()->addMarker(misspellingRange.get(), DocumentMarker::Spelling, result->replacement, result->hash);
- } else if (shouldMarkGrammar && result->type == TextCheckingTypeGrammar && paragraph.checkingRangeCovers(resultLocation, resultLength)) {
- ASSERT(resultLength > 0 && resultLocation >= 0);
- for (unsigned j = 0; j < result->details.size(); j++) {
- const GrammarDetail* detail = &result->details[j];
- ASSERT(detail->length > 0 && detail->location >= 0);
- if (paragraph.checkingRangeCovers(resultLocation + detail->location, detail->length)) {
- RefPtr<Range> badGrammarRange = paragraph.subrange(resultLocation + detail->location, detail->length);
- badGrammarRange->startContainer()->document().markers()->addMarker(badGrammarRange.get(), DocumentMarker::Grammar, detail->userDescription, result->hash);
- }
- }
- }
- }
-
- if (selectionChanged) {
- TextCheckingParagraph extendedParagraph(paragraph);
- // Restore the caret position if we have made any replacements
- extendedParagraph.expandRangeToNextEnd();
- if (restoreSelectionAfterChange && selectionOffset >= 0 && selectionOffset <= extendedParagraph.rangeLength()) {
- RefPtr<Range> selectionRange = extendedParagraph.subrange(0, selectionOffset);
- m_frame->selection().moveTo(selectionRange->endPosition(), DOWNSTREAM);
- if (adjustSelectionForParagraphBoundaries)
- m_frame->selection().modify(FrameSelection::AlterationMove, DirectionForward, CharacterGranularity);
- } else {
- // If this fails for any reason, the fallback is to go one position beyond the last replacement
- m_frame->selection().moveTo(m_frame->selection().end());
- m_frame->selection().modify(FrameSelection::AlterationMove, DirectionForward, CharacterGranularity);
- }
- }
-}
-
-void Editor::markMisspellingsAndBadGrammar(const VisibleSelection& spellingSelection, bool markGrammar, const VisibleSelection& grammarSelection)
-{
- if (unifiedTextCheckerEnabled()) {
- if (!isContinuousSpellCheckingEnabled())
- return;
-
- // markMisspellingsAndBadGrammar() is triggered by selection change, in which case we check spelling and grammar, but don't autocorrect misspellings.
- TextCheckingTypeMask textCheckingOptions = TextCheckingTypeSpelling;
- if (markGrammar && isGrammarCheckingEnabled())
- textCheckingOptions |= TextCheckingTypeGrammar;
- markAllMisspellingsAndBadGrammarInRanges(textCheckingOptions, spellingSelection.toNormalizedRange().get(), grammarSelection.toNormalizedRange().get());
- return;
- }
-
- RefPtr<Range> firstMisspellingRange;
- markMisspellings(spellingSelection, firstMisspellingRange);
- if (markGrammar)
- markBadGrammar(grammarSelection);
-}
-
-void Editor::updateMarkersForWordsAffectedByEditing(bool doNotRemoveIfSelectionAtWordBoundary)
-{
- if (textChecker().shouldEraseMarkersAfterChangeSelection(TextCheckingTypeSpelling))
- return;
-
- // We want to remove the markers from a word if an editing command will change the word. This can happen in one of
- // several scenarios:
- // 1. Insert in the middle of a word.
- // 2. Appending non whitespace at the beginning of word.
- // 3. Appending non whitespace at the end of word.
- // Note that, appending only whitespaces at the beginning or end of word won't change the word, so we don't need to
- // remove the markers on that word.
- // Of course, if current selection is a range, we potentially will edit two words that fall on the boundaries of
- // selection, and remove words between the selection boundaries.
- //
- VisiblePosition startOfSelection = frame().selection().selection().start();
- VisiblePosition endOfSelection = frame().selection().selection().end();
- if (startOfSelection.isNull())
- return;
- // First word is the word that ends after or on the start of selection.
- VisiblePosition startOfFirstWord = startOfWord(startOfSelection, LeftWordIfOnBoundary);
- VisiblePosition endOfFirstWord = endOfWord(startOfSelection, LeftWordIfOnBoundary);
- // Last word is the word that begins before or on the end of selection
- VisiblePosition startOfLastWord = startOfWord(endOfSelection, RightWordIfOnBoundary);
- VisiblePosition endOfLastWord = endOfWord(endOfSelection, RightWordIfOnBoundary);
-
- if (startOfFirstWord.isNull()) {
- startOfFirstWord = startOfWord(startOfSelection, RightWordIfOnBoundary);
- endOfFirstWord = endOfWord(startOfSelection, RightWordIfOnBoundary);
- }
-
- if (endOfLastWord.isNull()) {
- startOfLastWord = startOfWord(endOfSelection, LeftWordIfOnBoundary);
- endOfLastWord = endOfWord(endOfSelection, LeftWordIfOnBoundary);
- }
-
- // If doNotRemoveIfSelectionAtWordBoundary is true, and first word ends at the start of selection,
- // we choose next word as the first word.
- if (doNotRemoveIfSelectionAtWordBoundary && endOfFirstWord == startOfSelection) {
- startOfFirstWord = nextWordPosition(startOfFirstWord);
- endOfFirstWord = endOfWord(startOfFirstWord, RightWordIfOnBoundary);
- if (startOfFirstWord == endOfSelection)
- return;
- }
-
- // If doNotRemoveIfSelectionAtWordBoundary is true, and last word begins at the end of selection,
- // we choose previous word as the last word.
- if (doNotRemoveIfSelectionAtWordBoundary && startOfLastWord == endOfSelection) {
- startOfLastWord = previousWordPosition(startOfLastWord);
- endOfLastWord = endOfWord(startOfLastWord, RightWordIfOnBoundary);
- if (endOfLastWord == startOfSelection)
- return;
- }
-
- if (startOfFirstWord.isNull() || endOfFirstWord.isNull() || startOfLastWord.isNull() || endOfLastWord.isNull())
- return;
-
- // Now we remove markers on everything between startOfFirstWord and endOfLastWord.
- // However, if an autocorrection change a single word to multiple words, we want to remove correction mark from all the
- // resulted words even we only edit one of them. For example, assuming autocorrection changes "avantgarde" to "avant
- // garde", we will have CorrectionIndicator marker on both words and on the whitespace between them. If we then edit garde,
- // we would like to remove the marker from word "avant" and whitespace as well. So we need to get the continous range of
- // of marker that contains the word in question, and remove marker on that whole range.
- Document* document = m_frame->document();
- ASSERT(document);
- RefPtr<Range> wordRange = Range::create(*document, startOfFirstWord.deepEquivalent(), endOfLastWord.deepEquivalent());
-
- document->markers()->removeMarkers(wordRange.get(), DocumentMarker::MisspellingMarkers(), DocumentMarkerController::RemovePartiallyOverlappingMarker);
-}
-
-PassRefPtr<Range> Editor::rangeForPoint(const IntPoint& windowPoint)
-{
- Document* document = m_frame->documentAtPoint(windowPoint);
- if (!document)
- return 0;
-
- Frame* frame = document->frame();
- ASSERT(frame);
- FrameView* frameView = frame->view();
- if (!frameView)
- return 0;
- IntPoint framePoint = frameView->windowToContents(windowPoint);
- VisibleSelection selection(frame->visiblePositionForPoint(framePoint));
-
- return selection.toNormalizedRange().get();
-}
-
void Editor::revealSelectionAfterEditingOperation(const ScrollAlignment& alignment, RevealExtentOption revealExtentOption)
{
if (m_preventRevealSelection)
return;
- m_frame->selection().revealSelection(alignment, revealExtentOption);
-}
-
-bool Editor::setSelectionOffsets(int selectionStart, int selectionEnd)
-{
- Element* rootEditableElement = m_frame->selection().rootEditableElement();
- if (!rootEditableElement)
- return false;
-
- RefPtr<Range> range = TextIterator::rangeFromLocationAndLength(rootEditableElement, selectionStart, selectionEnd - selectionStart);
- if (!range)
- return false;
-
- return m_frame->selection().setSelectedRange(range.get(), VP_DEFAULT_AFFINITY, true);
+ m_frame.selection().revealSelection(alignment, revealExtentOption);
}
void Editor::transpose()
@@ -1796,7 +1061,7 @@ void Editor::transpose()
if (!canEdit())
return;
- VisibleSelection selection = m_frame->selection().selection();
+ VisibleSelection selection = m_frame.selection().selection();
if (!selection.isCaret())
return;
@@ -1821,28 +1086,23 @@ void Editor::transpose()
String transposed = text.right(1) + text.left(1);
// Select the two characters.
- if (newSelection != m_frame->selection().selection()) {
- if (!m_frame->selection().shouldChangeSelection(newSelection))
- return;
- m_frame->selection().setSelection(newSelection);
- }
+ if (newSelection != m_frame.selection().selection())
+ m_frame.selection().setSelection(newSelection);
// Insert the transposed characters.
- if (!shouldInsertText(transposed, range.get(), EditorInsertActionTyped))
- return;
replaceSelectionWithText(transposed, false, false);
}
void Editor::addToKillRing(Range* range, bool prepend)
{
if (m_shouldStartNewKillRingSequence)
- killRing()->startNewSequence();
+ killRing().startNewSequence();
String text = plainText(range);
if (prepend)
- killRing()->prepend(text);
+ killRing().prepend(text);
else
- killRing()->append(text);
+ killRing().append(text);
m_shouldStartNewKillRingSequence = false;
}
@@ -1852,13 +1112,9 @@ void Editor::changeSelectionAfterCommand(const VisibleSelection& newSelection,
if (newSelection.start().isOrphan() || newSelection.end().isOrphan())
return;
- // If there is no selection change, don't bother sending shouldChangeSelection, but still call setSelection,
- // because there is work that it must do in this situation.
- // The old selection can be invalid here and calling shouldChangeSelection can produce some strange calls.
// See <rdar://problem/5729315> Some shouldChangeSelectedDOMRange contain Ranges for selections that are no longer valid
- bool selectionDidNotChangeDOMPosition = newSelection == m_frame->selection().selection();
- if (selectionDidNotChangeDOMPosition || m_frame->selection().shouldChangeSelection(newSelection))
- m_frame->selection().setSelection(newSelection, options);
+ bool selectionDidNotChangeDOMPosition = newSelection == m_frame.selection().selection();
+ m_frame.selection().setSelection(newSelection, options);
// Some editing operations change the selection visually without affecting its position within the DOM.
// For example when you press return in the following (the caret is marked by ^):
@@ -1868,7 +1124,7 @@ void Editor::changeSelectionAfterCommand(const VisibleSelection& newSelection,
// does not call EditorClient::respondToChangedSelection(), which, on the Mac, sends selection change notifications and
// starts a new kill ring sequence, but we want to do these things (matches AppKit).
if (selectionDidNotChangeDOMPosition)
- client().respondToChangedSelection(m_frame);
+ client().respondToChangedSelection(m_frame.selection().selectionType());
}
IntRect Editor::firstRectForRange(Range* range) const
@@ -1900,69 +1156,33 @@ IntRect Editor::firstRectForRange(Range* range) const
startCaretRect.height());
}
-bool Editor::shouldChangeSelection(const VisibleSelection& oldSelection, const VisibleSelection& newSelection, EAffinity affinity, bool stillSelecting) const
-{
- return client().shouldChangeSelectedRange(oldSelection.toNormalizedRange().get(), newSelection.toNormalizedRange().get(), affinity, stillSelecting);
-}
-
void Editor::computeAndSetTypingStyle(StylePropertySet* style, EditAction editingAction)
{
if (!style || style->isEmpty()) {
- m_frame->selection().clearTypingStyle();
+ m_frame.selection().clearTypingStyle();
return;
}
// Calculate the current typing style.
RefPtr<EditingStyle> typingStyle;
- if (m_frame->selection().typingStyle()) {
- typingStyle = m_frame->selection().typingStyle()->copy();
+ if (m_frame.selection().typingStyle()) {
+ typingStyle = m_frame.selection().typingStyle()->copy();
typingStyle->overrideWithStyle(style);
- } else
+ } else {
typingStyle = EditingStyle::create(style);
+ }
- typingStyle->prepareToApplyAt(m_frame->selection().selection().visibleStart().deepEquivalent(), EditingStyle::PreserveWritingDirection);
+ typingStyle->prepareToApplyAt(m_frame.selection().selection().visibleStart().deepEquivalent(), EditingStyle::PreserveWritingDirection);
// Handle block styles, substracting these from the typing style.
RefPtr<EditingStyle> blockStyle = typingStyle->extractAndRemoveBlockProperties();
if (!blockStyle->isEmpty()) {
- ASSERT(m_frame->document());
- ApplyStyleCommand::create(*m_frame->document(), blockStyle.get(), editingAction)->apply();
+ ASSERT(m_frame.document());
+ ApplyStyleCommand::create(*m_frame.document(), blockStyle.get(), editingAction)->apply();
}
// Set the remaining style as the typing style.
- m_frame->selection().setTypingStyle(typingStyle);
-}
-
-void Editor::textAreaOrTextFieldDidBeginEditing(Element* e)
-{
- elementDidBeginEditing(e);
-}
-
-void Editor::textFieldDidEndEditing(Element* e)
-{
- // Remove markers when deactivating a selection in an <input type="text"/>.
- // Prevent new ones from appearing too.
- m_spellCheckRequester->cancelCheck();
- HTMLTextFormControlElement* textFormControlElement = toHTMLTextFormControlElement(e);
- HTMLElement* innerText = textFormControlElement->innerTextElement();
- DocumentMarker::MarkerTypes markerTypes(DocumentMarker::Spelling);
- if (isGrammarCheckingEnabled() || unifiedTextCheckerEnabled())
- markerTypes.add(DocumentMarker::Grammar);
- for (Node* node = innerText; node; node = NodeTraversal::next(node, innerText)) {
- m_frame->document()->markers()->removeMarkers(node, markerTypes);
- }
-
- client().textFieldDidEndEditing(e);
-}
-
-void Editor::textDidChangeInTextField(Element* e)
-{
- client().textDidChangeInTextField(e);
-}
-
-bool Editor::doTextFieldCommandFromEvent(Element* e, KeyboardEvent* ke)
-{
- return client().doTextFieldCommandFromEvent(e, ke);
+ m_frame.selection().setTypingStyle(typingStyle);
}
bool Editor::findString(const String& target, bool forward, bool caseFlag, bool wrapFlag, bool startInSelection)
@@ -1973,15 +1193,15 @@ bool Editor::findString(const String& target, bool forward, bool caseFlag, bool
bool Editor::findString(const String& target, FindOptions options)
{
- VisibleSelection selection = m_frame->selection().selection();
+ VisibleSelection selection = m_frame.selection().selection();
RefPtr<Range> resultRange = rangeOfString(target, selection.firstRange().get(), options);
if (!resultRange)
return false;
- m_frame->selection().setSelection(VisibleSelection(resultRange.get(), DOWNSTREAM));
- m_frame->selection().revealSelection();
+ m_frame.selection().setSelection(VisibleSelection(resultRange.get(), DOWNSTREAM));
+ m_frame.selection().revealSelection();
return true;
}
@@ -2004,7 +1224,7 @@ PassRefPtr<Range> Editor::rangeOfString(const String& target, Range* referenceRa
// Start from an edge of the reference range, if there's a reference range that's not in shadow content. Which edge
// is used depends on whether we're searching forward or backward, and whether startInSelection is set.
- RefPtr<Range> searchRange(rangeOfContents(m_frame->document()));
+ RefPtr<Range> searchRange(rangeOfContents(m_frame.document()));
bool forward = !(options & Backwards);
bool startInReferenceRange = referenceRange && (options & StartInSelection);
@@ -2028,7 +1248,7 @@ PassRefPtr<Range> Editor::rangeOfString(const String& target, Range* referenceRa
// Build a selection with the found range to remove collapsed whitespace.
// Compare ranges instead of selection objects to ignore the way that the current selection was made.
if (startInReferenceRange && areRangesEqual(VisibleSelection(resultRange.get()).toNormalizedRange().get(), referenceRange)) {
- searchRange = rangeOfContents(m_frame->document());
+ searchRange = rangeOfContents(m_frame.document());
if (forward)
searchRange->setStart(referenceRange->endPosition());
else
@@ -2046,7 +1266,7 @@ PassRefPtr<Range> Editor::rangeOfString(const String& target, Range* referenceRa
// If nothing was found in the shadow tree, search in main content following the shadow tree.
if (resultRange->collapsed(ASSERT_NO_EXCEPTION) && shadowTreeRoot) {
- searchRange = rangeOfContents(m_frame->document());
+ searchRange = rangeOfContents(m_frame.document());
if (forward)
searchRange->setStartAfter(shadowTreeRoot->shadowHost());
else
@@ -2058,7 +1278,7 @@ PassRefPtr<Range> Editor::rangeOfString(const String& target, Range* referenceRa
// If we didn't find anything and we're wrapping, search again in the entire document (this will
// redundantly re-search the area already searched in some cases).
if (resultRange->collapsed(ASSERT_NO_EXCEPTION) && options & WrapAround) {
- searchRange = rangeOfContents(m_frame->document());
+ searchRange = rangeOfContents(m_frame.document());
resultRange = findPlainText(searchRange.get(), target, options);
// We used to return false here if we ended up with the same range that we started with
// (e.g., the reference range was already the only instance of this text). But we decided that
@@ -2074,147 +1294,25 @@ void Editor::setMarkedTextMatchesAreHighlighted(bool flag)
return;
m_areMarkedTextMatchesHighlighted = flag;
- m_frame->document()->markers()->repaintMarkers(DocumentMarker::TextMatch);
+ m_frame.document()->markers()->repaintMarkers(DocumentMarker::TextMatch);
}
void Editor::respondToChangedSelection(const VisibleSelection& oldSelection, FrameSelection::SetSelectionOptions options)
{
- bool closeTyping = options & FrameSelection::CloseTyping;
- bool isContinuousSpellCheckingEnabled = this->isContinuousSpellCheckingEnabled();
- bool isContinuousGrammarCheckingEnabled = isContinuousSpellCheckingEnabled && isGrammarCheckingEnabled();
- if (isContinuousSpellCheckingEnabled) {
- VisibleSelection newAdjacentWords;
- VisibleSelection newSelectedSentence;
- bool caretBrowsing = m_frame->settings() && m_frame->settings()->caretBrowsingEnabled();
- if (m_frame->selection().selection().isContentEditable() || caretBrowsing) {
- VisiblePosition newStart(m_frame->selection().selection().visibleStart());
- newAdjacentWords = VisibleSelection(startOfWord(newStart, LeftWordIfOnBoundary), endOfWord(newStart, RightWordIfOnBoundary));
- if (isContinuousGrammarCheckingEnabled)
- newSelectedSentence = VisibleSelection(startOfSentence(newStart), endOfSentence(newStart));
- }
-
- // Don't check spelling and grammar if the change of selection is triggered by spelling correction itself.
- bool shouldCheckSpellingAndGrammar = !(options & FrameSelection::SpellCorrectionTriggered);
-
- // When typing we check spelling elsewhere, so don't redo it here.
- // If this is a change in selection resulting from a delete operation,
- // oldSelection may no longer be in the document.
- if (shouldCheckSpellingAndGrammar
- && closeTyping
- && oldSelection.isContentEditable()
- && oldSelection.start().inDocument()
- && !isSelectionInTextField(oldSelection)) {
- spellCheckOldSelection(oldSelection, newAdjacentWords, newSelectedSentence);
- }
-
- if (textChecker().shouldEraseMarkersAfterChangeSelection(TextCheckingTypeSpelling)) {
- if (RefPtr<Range> wordRange = newAdjacentWords.toNormalizedRange())
- m_frame->document()->markers()->removeMarkers(wordRange.get(), DocumentMarker::Spelling);
- }
- if (textChecker().shouldEraseMarkersAfterChangeSelection(TextCheckingTypeGrammar)) {
- if (RefPtr<Range> sentenceRange = newSelectedSentence.toNormalizedRange())
- m_frame->document()->markers()->removeMarkers(sentenceRange.get(), DocumentMarker::Grammar);
- }
- }
-
- // When continuous spell checking is off, existing markers disappear after the selection changes.
- if (!isContinuousSpellCheckingEnabled)
- m_frame->document()->markers()->removeMarkers(DocumentMarker::Spelling);
- if (!isContinuousGrammarCheckingEnabled)
- m_frame->document()->markers()->removeMarkers(DocumentMarker::Grammar);
-
- m_frame->inputMethodController().cancelCompositionIfSelectionIsInvalid();
-
+ spellChecker().respondToChangedSelection(oldSelection, options);
+ m_frame.inputMethodController().cancelCompositionIfSelectionIsInvalid();
notifyComponentsOnChangedSelection(oldSelection, options);
}
-void Editor::spellCheckAfterBlur()
-{
- if (!m_frame->selection().selection().isContentEditable())
- return;
-
- if (isSelectionInTextField(m_frame->selection().selection())) {
- // textFieldDidEndEditing() and textFieldDidBeginEditing() handle this.
- return;
- }
-
- VisibleSelection empty;
- spellCheckOldSelection(m_frame->selection().selection(), empty, empty);
-}
-
-void Editor::spellCheckOldSelection(const VisibleSelection& oldSelection, const VisibleSelection& newAdjacentWords, const VisibleSelection& newSelectedSentence)
+SpellChecker& Editor::spellChecker() const
{
- VisiblePosition oldStart(oldSelection.visibleStart());
- VisibleSelection oldAdjacentWords = VisibleSelection(startOfWord(oldStart, LeftWordIfOnBoundary), endOfWord(oldStart, RightWordIfOnBoundary));
- if (oldAdjacentWords != newAdjacentWords) {
- if (isContinuousSpellCheckingEnabled() && isGrammarCheckingEnabled()) {
- VisibleSelection selectedSentence = VisibleSelection(startOfSentence(oldStart), endOfSentence(oldStart));
- markMisspellingsAndBadGrammar(oldAdjacentWords, selectedSentence != newSelectedSentence, selectedSentence);
- } else {
- markMisspellingsAndBadGrammar(oldAdjacentWords, false, oldAdjacentWords);
- }
- }
-}
-
-static Node* findFirstMarkable(Node* node)
-{
- while (node) {
- if (!node->renderer())
- return 0;
- if (node->renderer()->isText())
- return node;
- if (node->renderer()->isTextControl())
- node = toRenderTextControl(node->renderer())->textFormControlElement()->visiblePositionForIndex(1).deepEquivalent().deprecatedNode();
- else if (node->firstChild())
- node = node->firstChild();
- else
- node = node->nextSibling();
- }
-
- return 0;
-}
-
-bool Editor::selectionStartHasMarkerFor(DocumentMarker::MarkerType markerType, int from, int length) const
-{
- Node* node = findFirstMarkable(m_frame->selection().start().deprecatedNode());
- if (!node)
- return false;
-
- unsigned int startOffset = static_cast<unsigned int>(from);
- unsigned int endOffset = static_cast<unsigned int>(from + length);
- Vector<DocumentMarker*> markers = m_frame->document()->markers()->markersFor(node);
- for (size_t i = 0; i < markers.size(); ++i) {
- DocumentMarker* marker = markers[i];
- if (marker->startOffset() <= startOffset && endOffset <= marker->endOffset() && marker->type() == markerType)
- return true;
- }
-
- return false;
-}
-
-TextCheckingTypeMask Editor::resolveTextCheckingTypeMask(TextCheckingTypeMask textCheckingOptions)
-{
- bool shouldMarkSpelling = textCheckingOptions & TextCheckingTypeSpelling;
- bool shouldMarkGrammar = textCheckingOptions & TextCheckingTypeGrammar;
-
- TextCheckingTypeMask checkingTypes = 0;
- if (shouldMarkSpelling)
- checkingTypes |= TextCheckingTypeSpelling;
- if (shouldMarkGrammar)
- checkingTypes |= TextCheckingTypeGrammar;
-
- return checkingTypes;
-}
-
-bool Editor::unifiedTextCheckerEnabled() const
-{
- return WebCore::unifiedTextCheckerEnabled(m_frame);
+ return m_frame.spellChecker();
}
void Editor::toggleOverwriteModeEnabled()
{
m_overwriteModeEnabled = !m_overwriteModeEnabled;
frame().selection().setShouldShowBlockCursor(m_overwriteModeEnabled);
-};
+}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/editing/Editor.h b/chromium/third_party/WebKit/Source/core/editing/Editor.h
index bca72bbc8a8..15b1ba6ac30 100644
--- a/chromium/third_party/WebKit/Source/core/editing/Editor.h
+++ b/chromium/third_party/WebKit/Source/core/editing/Editor.h
@@ -30,14 +30,13 @@
#include "core/dom/DocumentMarker.h"
#include "core/editing/EditAction.h"
#include "core/editing/EditingBehavior.h"
-#include "core/editing/EditorInsertAction.h"
#include "core/editing/FindOptions.h"
#include "core/editing/FrameSelection.h"
#include "core/editing/TextIterator.h"
#include "core/editing/VisibleSelection.h"
#include "core/editing/WritingDirection.h"
-#include "core/page/FrameDestructionObserver.h"
-#include "core/platform/text/TextChecking.h"
+#include "core/frame/FrameDestructionObserver.h"
+#include "platform/PasteMode.h"
namespace WebCore {
@@ -54,27 +53,24 @@ class KillRing;
class Pasteboard;
class SharedBuffer;
class SimpleFontData;
-class SpellCheckRequest;
-class SpellCheckRequester;
+class SpellChecker;
class StylePropertySet;
class Text;
-class TextCheckerClient;
-class TextCheckingParagraph;
-struct TextCheckingResult;
class TextEvent;
+class UndoStack;
enum EditorCommandSource { CommandFromMenuOrKeyBinding, CommandFromDOM, CommandFromDOMWithUserInterface };
enum EditorParagraphSeparator { EditorParagraphSeparatorIsDiv, EditorParagraphSeparatorIsP };
-class Editor : public FrameDestructionObserver {
+class Editor {
+ WTF_MAKE_NONCOPYABLE(Editor);
public:
- explicit Editor(Frame&);
+ static PassOwnPtr<Editor> create(Frame&);
~Editor();
EditorClient& client() const;
- TextCheckerClient& textChecker() const;
- Frame& frame() const { return *m_frame; }
+ Frame& frame() const { return m_frame; }
CompositeEditCommand* lastEditCommand() { return m_lastEditCommand.get(); }
@@ -87,15 +83,12 @@ public:
bool canDHTMLCut();
bool canDHTMLCopy();
bool canDHTMLPaste();
- bool tryDHTMLCopy();
- bool tryDHTMLCut();
- bool tryDHTMLPaste();
bool canCut() const;
bool canCopy() const;
bool canPaste() const;
bool canDelete() const;
- bool canSmartCopyOrDelete();
+ bool canSmartCopyOrDelete() const;
void cut();
void copy();
@@ -103,17 +96,13 @@ public:
void pasteAsPlainText();
void performDelete();
- void copyURL(const KURL&, const String&);
void copyImage(const HitTestResult&);
void indent();
void outdent();
void transpose();
- bool shouldInsertFragment(PassRefPtr<DocumentFragment>, PassRefPtr<Range>, EditorInsertAction);
- bool shouldInsertText(const String&, Range*, EditorInsertAction) const;
bool shouldDeleteRange(Range*) const;
- bool shouldApplyStyle(StylePropertySet*, Range*);
void respondToChangedContents(const VisibleSelection& endingSelection);
@@ -138,10 +127,6 @@ public:
bool deleteWithDirection(SelectionDirection, TextGranularity, bool killRing, bool isTypingAction);
void deleteSelectionWithSmartDelete(bool smartDelete);
- bool dispatchCPPEvent(const AtomicString&, ClipboardAccessPolicy);
-
- Node* removedAnchor() const { return m_removedAnchor.get(); }
- void setRemovedAnchor(PassRefPtr<Node> n) { m_removedAnchor = n; }
void applyStyle(StylePropertySet*, EditAction = EditActionUnspecified);
void applyParagraphStyle(StylePropertySet*, EditAction = EditActionUnspecified);
@@ -185,60 +170,30 @@ public:
bool insertLineBreak();
bool insertParagraphSeparator();
- bool isContinuousSpellCheckingEnabled() const;
- void toggleContinuousSpellChecking();
- bool isGrammarCheckingEnabled();
- void ignoreSpelling();
- String misspelledWordAtCaretOrRange(Node* clickedNode) const;
- bool isSpellCheckingEnabledInFocusedNode() const;
- bool isSpellCheckingEnabledFor(Node*) const;
- void markMisspellingsAfterTypingToWord(const VisiblePosition &wordStart, const VisibleSelection& selectionAfterTyping);
- void markMisspellings(const VisibleSelection&, RefPtr<Range>& firstMisspellingRange);
- void markBadGrammar(const VisibleSelection&);
- void markMisspellingsAndBadGrammar(const VisibleSelection& spellingSelection, bool markGrammar, const VisibleSelection& grammarSelection);
- void markAndReplaceFor(PassRefPtr<SpellCheckRequest>, const Vector<TextCheckingResult>&);
-
bool isOverwriteModeEnabled() const { return m_overwriteModeEnabled; }
void toggleOverwriteModeEnabled();
- void markAllMisspellingsAndBadGrammarInRanges(TextCheckingTypeMask, Range* spellingRange, Range* grammarRange);
-
- void advanceToNextMisspelling(bool startBeforeSelection = false);
- void showSpellingGuessPanel();
-
- bool shouldBeginEditing(Range*);
- bool shouldEndEditing(Range*);
-
- void clearUndoRedoOperations();
bool canUndo();
void undo();
bool canRedo();
void redo();
- void didBeginEditing(Element*);
- void didEndEditing();
-
void setBaseWritingDirection(WritingDirection);
// smartInsertDeleteEnabled and selectTrailingWhitespaceEnabled are
// mutually exclusive, meaning that enabling one will disable the other.
- bool smartInsertDeleteEnabled();
- bool isSelectTrailingWhitespaceEnabled();
-
- bool setSelectionOffsets(int selectionStart, int selectionEnd);
+ bool smartInsertDeleteEnabled() const;
+ bool isSelectTrailingWhitespaceEnabled() const;
bool preventRevealSelection() const { return m_preventRevealSelection; }
void setStartNewKillRingSequence(bool);
- PassRefPtr<Range> rangeForPoint(const IntPoint& windowPoint);
-
void clear();
VisibleSelection selectionForCommand(Event*);
- KillRing* killRing() const { return m_killRing.get(); }
- SpellCheckRequester& spellCheckRequester() const { return *m_spellCheckRequester; }
+ KillRing& killRing() const { return *m_killRing; }
EditingBehavior behavior() const;
@@ -249,19 +204,12 @@ public:
void pasteAsFragment(PassRefPtr<DocumentFragment>, bool smartReplace, bool matchStyle);
void pasteAsPlainText(const String&, bool smartReplace);
- // This is only called on the mac where paste is implemented primarily at the WebKit level.
- void pasteAsPlainTextBypassingDHTML();
-
- void clearMisspellingsAndBadGrammar(const VisibleSelection&);
- void markMisspellingsAndBadGrammar(const VisibleSelection&);
-
Node* findEventTargetFrom(const VisibleSelection&) const;
bool findString(const String&, FindOptions);
// FIXME: Switch callers over to the FindOptions version and retire this one.
bool findString(const String&, bool forward, bool caseFlag, bool wrapFlag, bool startInSelection);
- PassRefPtr<Range> rangeOfString(const String&, Range*, FindOptions);
PassRefPtr<Range> findStringAndScrollToVisible(const String&, Range*, FindOptions);
const VisibleSelection& mark() const; // Mark, to be used as emacs uses it.
@@ -272,28 +220,12 @@ public:
IntRect firstRectForRange(Range*) const;
void respondToChangedSelection(const VisibleSelection& oldSelection, FrameSelection::SetSelectionOptions);
- bool shouldChangeSelection(const VisibleSelection& oldSelection, const VisibleSelection& newSelection, EAffinity, bool stillSelecting) const;
-
- void spellCheckAfterBlur();
- void spellCheckOldSelection(const VisibleSelection& oldSelection, const VisibleSelection& newAdjacentWords, const VisibleSelection& newSelectedSentence);
bool markedTextMatchesAreHighlighted() const;
void setMarkedTextMatchesAreHighlighted(bool);
- void textAreaOrTextFieldDidBeginEditing(Element*);
- void textFieldDidEndEditing(Element*);
- void textDidChangeInTextField(Element*);
- bool doTextFieldCommandFromEvent(Element*, KeyboardEvent*);
- WritingDirection baseWritingDirectionForSelectionStart() const;
-
void replaceSelectionWithFragment(PassRefPtr<DocumentFragment>, bool selectReplacement, bool smartReplace, bool matchStyle);
void replaceSelectionWithText(const String&, bool selectReplacement, bool smartReplace);
- bool selectionStartHasMarkerFor(DocumentMarker::MarkerType, int from, int length) const;
- void updateMarkersForWordsAffectedByEditing(bool onlyHandleWordsContainingSelection);
-
- void simplifyMarkup(Node* startNode, Node* endNode);
-
- void deviceScaleFactorChanged();
EditorParagraphSeparator defaultParagraphSeparator() const { return m_defaultParagraphSeparator; }
void setDefaultParagraphSeparator(EditorParagraphSeparator separator) { m_defaultParagraphSeparator = separator; }
@@ -308,40 +240,48 @@ public:
};
friend class RevealSelectionScope;
- void elementDidBeginEditing(Element*);
+ // Export interpretKeyEvent only for testing
+ static const char* interpretKeyEvent(const WebCore::KeyboardEvent*);
private:
+ Frame& m_frame;
RefPtr<CompositeEditCommand> m_lastEditCommand;
- RefPtr<Node> m_removedAnchor;
int m_preventRevealSelection;
bool m_shouldStartNewKillRingSequence;
bool m_shouldStyleWithCSS;
- OwnPtr<KillRing> m_killRing;
- const OwnPtr<SpellCheckRequester> m_spellCheckRequester;
+ const OwnPtr<KillRing> m_killRing;
VisibleSelection m_mark;
bool m_areMarkedTextMatchesHighlighted;
EditorParagraphSeparator m_defaultParagraphSeparator;
bool m_overwriteModeEnabled;
+ explicit Editor(Frame&);
+
bool canDeleteRange(Range*) const;
+
+ UndoStack* undoStack() const;
+
+ bool tryDHTMLCopy();
+ bool tryDHTMLCut();
+ bool tryDHTMLPaste(PasteMode);
+
bool canSmartReplaceWithPasteboard(Pasteboard*);
- PassRefPtr<Clipboard> newGeneralClipboard(ClipboardAccessPolicy, Frame*);
void pasteAsPlainTextWithPasteboard(Pasteboard*);
- void pasteWithPasteboard(Pasteboard*, bool allowPlainText);
+ void pasteWithPasteboard(Pasteboard*);
+ void writeSelectionToPasteboard(Pasteboard*, Range*, const String& plainText);
+ bool dispatchCPPEvent(const AtomicString&, ClipboardAccessPolicy, PasteMode = AllMimeTypes);
void revealSelectionAfterEditingOperation(const ScrollAlignment& = ScrollAlignment::alignCenterIfNeeded, RevealExtentOption = DoNotRevealExtent);
- void markMisspellingsOrBadGrammar(const VisibleSelection&, bool checkSpelling, RefPtr<Range>& firstMisspellingRange);
- TextCheckingTypeMask resolveTextCheckingTypeMask(TextCheckingTypeMask);
-
void changeSelectionAfterCommand(const VisibleSelection& newSelection, FrameSelection::SetSelectionOptions);
void notifyComponentsOnChangedSelection(const VisibleSelection& oldSelection, FrameSelection::SetSelectionOptions);
Node* findEventTargetFromSelection() const;
- bool unifiedTextCheckerEnabled() const;
+ PassRefPtr<Range> rangeOfString(const String&, Range*, FindOptions);
+
+ SpellChecker& spellChecker() const;
- void chunkAndMarkAllMisspellingsAndBadGrammar(TextCheckingTypeMask textCheckingOptions, const TextCheckingParagraph& fullParagraphToCheck, bool asynchronous);
- void markAllMisspellingsAndBadGrammarInRanges(TextCheckingTypeMask textCheckingOptions, Range* checkingRange, Range* paragraphRange, bool asynchronous, int requestNumber, int* checkingLength = 0);
+ bool handleEditingKeyboardEvent(WebCore::KeyboardEvent*);
};
inline void Editor::setStartNewKillRingSequence(bool flag)
diff --git a/chromium/third_party/WebKit/Source/core/editing/EditorCommand.cpp b/chromium/third_party/WebKit/Source/core/editing/EditorCommand.cpp
index 8c86f046394..3198fcb2ab9 100644
--- a/chromium/third_party/WebKit/Source/core/editing/EditorCommand.cpp
+++ b/chromium/third_party/WebKit/Source/core/editing/EditorCommand.cpp
@@ -36,13 +36,13 @@
#include "core/css/CSSValueList.h"
#include "core/css/StylePropertySet.h"
#include "core/dom/DocumentFragment.h"
-#include "core/dom/Event.h"
-#include "core/dom/UserTypingGestureIndicator.h"
+#include "core/events/Event.h"
#include "core/editing/CreateLinkCommand.h"
#include "core/editing/FormatBlockCommand.h"
#include "core/editing/IndentOutdentCommand.h"
#include "core/editing/InsertListCommand.h"
#include "core/editing/ReplaceSelectionCommand.h"
+#include "core/editing/SpellChecker.h"
#include "core/editing/TypingCommand.h"
#include "core/editing/UnlinkCommand.h"
#include "core/editing/markup.h"
@@ -52,15 +52,14 @@
#include "core/page/Chrome.h"
#include "core/page/EditorClient.h"
#include "core/page/EventHandler.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameView.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
#include "core/page/Page.h"
-#include "core/page/Settings.h"
-#include "core/platform/KillRing.h"
+#include "core/frame/Settings.h"
#include "core/platform/Pasteboard.h"
-#include "core/platform/Scrollbar.h"
-#include "core/platform/Sound.h"
#include "core/rendering/RenderBox.h"
+#include "platform/KillRing.h"
+#include "platform/scroll/Scrollbar.h"
#include "wtf/text/AtomicString.h"
namespace WebCore {
@@ -201,9 +200,9 @@ static bool executeInsertNode(Frame& frame, PassRefPtr<Node> content)
{
ASSERT(frame.document());
RefPtr<DocumentFragment> fragment = DocumentFragment::create(*frame.document());
- TrackExceptionState es;
- fragment->appendChild(content, es);
- if (es.hadException())
+ TrackExceptionState exceptionState;
+ fragment->appendChild(content, exceptionState);
+ if (exceptionState.hadException())
return false;
return executeInsertFragment(frame, fragment.release());
}
@@ -219,8 +218,6 @@ static bool expandSelectionToGranularity(Frame& frame, TextGranularity granulari
return false;
RefPtr<Range> oldRange = frame.selection().selection().toNormalizedRange();
EAffinity affinity = frame.selection().affinity();
- if (!frame.editor().client().shouldChangeSelectedRange(oldRange.get(), newRange.get(), affinity, false))
- return false;
frame.selection().setSelectedRange(newRange.get(), affinity, true);
return true;
}
@@ -296,14 +293,9 @@ static bool executeCreateLink(Frame& frame, Event*, EditorCommandSource, const S
return true;
}
-static bool executeCut(Frame& frame, Event*, EditorCommandSource source, const String&)
+static bool executeCut(Frame& frame, Event*, EditorCommandSource, const String&)
{
- if (source == CommandFromMenuOrKeyBinding) {
- UserTypingGestureIndicator typingGestureIndicator(&frame);
- frame.editor().cut();
- } else {
- frame.editor().cut();
- }
+ frame.editor().cut();
return true;
}
@@ -322,7 +314,6 @@ static bool executeDelete(Frame& frame, Event*, EditorCommandSource source, cons
switch (source) {
case CommandFromMenuOrKeyBinding: {
// Doesn't modify the text if the current selection isn't a range.
- UserTypingGestureIndicator typingGestureIndicator(&frame);
frame.editor().performDelete();
return true;
}
@@ -346,7 +337,7 @@ static bool executeDeleteBackward(Frame& frame, Event*, EditorCommandSource, con
static bool executeDeleteBackwardByDecomposingPreviousCharacter(Frame& frame, Event*, EditorCommandSource, const String&)
{
- LOG_ERROR("DeleteBackwardByDecomposingPreviousCharacter is not implemented, doing DeleteBackward instead");
+ WTF_LOG_ERROR("DeleteBackwardByDecomposingPreviousCharacter is not implemented, doing DeleteBackward instead");
frame.editor().deleteWithDirection(DirectionBackward, CharacterGranularity, false, true);
return true;
}
@@ -445,8 +436,8 @@ static bool executeFormatBlock(Frame& frame, Event*, EditorCommandSource, const
if (tagName[0] == '<' && tagName[tagName.length() - 1] == '>')
tagName = tagName.substring(1, tagName.length() - 2);
- String localName, prefix;
- if (!Document::parseQualifiedName(tagName, prefix, localName, IGNORE_EXCEPTION))
+ AtomicString localName, prefix;
+ if (!Document::parseQualifiedName(AtomicString(tagName), prefix, localName, IGNORE_EXCEPTION))
return false;
QualifiedName qualifiedTagName(prefix, localName, xhtmlNamespaceURI);
@@ -477,7 +468,7 @@ static bool executeForwardDelete(Frame& frame, Event*, EditorCommandSource sourc
static bool executeIgnoreSpelling(Frame& frame, Event*, EditorCommandSource, const String&)
{
- frame.editor().ignoreSpelling();
+ frame.spellChecker().ignoreSpelling();
return true;
}
@@ -490,7 +481,7 @@ static bool executeIndent(Frame& frame, Event*, EditorCommandSource, const Strin
static bool executeInsertBacktab(Frame& frame, Event* event, EditorCommandSource, const String&)
{
- return targetFrame(frame, event)->eventHandler()->handleTextInputEvent("\t", event, TextEventInputBackTab);
+ return targetFrame(frame, event)->eventHandler().handleTextInputEvent("\t", event, TextEventInputBackTab);
}
static bool executeInsertHorizontalRule(Frame& frame, Event*, EditorCommandSource, const String& value)
@@ -498,7 +489,7 @@ static bool executeInsertHorizontalRule(Frame& frame, Event*, EditorCommandSourc
ASSERT(frame.document());
RefPtr<HTMLHRElement> rule = HTMLHRElement::create(*frame.document());
if (!value.isEmpty())
- rule->setIdAttribute(value);
+ rule->setIdAttribute(AtomicString(value));
return executeInsertNode(frame, rule.release());
}
@@ -521,7 +512,7 @@ static bool executeInsertLineBreak(Frame& frame, Event* event, EditorCommandSour
{
switch (source) {
case CommandFromMenuOrKeyBinding:
- return targetFrame(frame, event)->eventHandler()->handleTextInputEvent("\n", event, TextEventInputLineBreak);
+ return targetFrame(frame, event)->eventHandler().handleTextInputEvent("\n", event, TextEventInputLineBreak);
case CommandFromDOM:
case CommandFromDOMWithUserInterface:
// Doesn't scroll to make the selection visible, or modify the kill ring.
@@ -538,7 +529,7 @@ static bool executeInsertLineBreak(Frame& frame, Event* event, EditorCommandSour
static bool executeInsertNewline(Frame& frame, Event* event, EditorCommandSource, const String&)
{
Frame* targetFrame = WebCore::targetFrame(frame, event);
- return targetFrame->eventHandler()->handleTextInputEvent("\n", event, targetFrame->editor().canEditRichly() ? TextEventInputKeyboard : TextEventInputLineBreak);
+ return targetFrame->eventHandler().handleTextInputEvent("\n", event, targetFrame->editor().canEditRichly() ? TextEventInputKeyboard : TextEventInputLineBreak);
}
static bool executeInsertNewlineInQuotedContent(Frame& frame, Event*, EditorCommandSource, const String&)
@@ -564,7 +555,7 @@ static bool executeInsertParagraph(Frame& frame, Event*, EditorCommandSource, co
static bool executeInsertTab(Frame& frame, Event* event, EditorCommandSource, const String&)
{
- return targetFrame(frame, event)->eventHandler()->handleTextInputEvent("\t", event);
+ return targetFrame(frame, event)->eventHandler().handleTextInputEvent("\t", event);
}
static bool executeInsertText(Frame& frame, Event*, EditorCommandSource, const String& value)
@@ -936,23 +927,17 @@ static bool executeToggleOverwrite(Frame& frame, Event*, EditorCommandSource, co
return true;
}
-static bool executePaste(Frame& frame, Event*, EditorCommandSource source, const String&)
+static bool executePaste(Frame& frame, Event*, EditorCommandSource, const String&)
{
- if (source == CommandFromMenuOrKeyBinding) {
- UserTypingGestureIndicator typingGestureIndicator(&frame);
- frame.editor().paste();
- } else {
- frame.editor().paste();
- }
+ frame.editor().paste();
return true;
}
static bool executePasteGlobalSelection(Frame& frame, Event*, EditorCommandSource source, const String&)
{
- if (!frame.editor().client().supportsGlobalSelection())
+ if (!frame.editor().behavior().supportsGlobalSelection())
return false;
ASSERT_UNUSED(source, source == CommandFromMenuOrKeyBinding);
- UserTypingGestureIndicator typingGestureIndicator(&frame);
bool oldSelectionMode = Pasteboard::generalPasteboard()->isSelectionMode();
Pasteboard::generalPasteboard()->setSelectionMode(true);
@@ -961,25 +946,9 @@ static bool executePasteGlobalSelection(Frame& frame, Event*, EditorCommandSourc
return true;
}
-static bool executePasteAndMatchStyle(Frame& frame, Event*, EditorCommandSource source, const String&)
-{
- if (source == CommandFromMenuOrKeyBinding) {
- UserTypingGestureIndicator typingGestureIndicator(&frame);
- frame.editor().pasteAsPlainText();
- } else {
- frame.editor().pasteAsPlainText();
- }
- return true;
-}
-
-static bool executePasteAsPlainText(Frame& frame, Event*, EditorCommandSource source, const String&)
+static bool executePasteAndMatchStyle(Frame& frame, Event*, EditorCommandSource, const String&)
{
- if (source == CommandFromMenuOrKeyBinding) {
- UserTypingGestureIndicator typingGestureIndicator(&frame);
- frame.editor().pasteAsPlainText();
- } else {
- frame.editor().pasteAsPlainText();
- }
+ frame.editor().pasteAsPlainText();
return true;
}
@@ -1006,32 +975,32 @@ static bool executeRemoveFormat(Frame& frame, Event*, EditorCommandSource, const
static bool executeScrollPageBackward(Frame& frame, Event*, EditorCommandSource, const String&)
{
- return frame.eventHandler()->logicalScrollRecursively(ScrollBlockDirectionBackward, ScrollByPage);
+ return frame.eventHandler().scrollRecursively(ScrollBlockDirectionBackward, ScrollByPage);
}
static bool executeScrollPageForward(Frame& frame, Event*, EditorCommandSource, const String&)
{
- return frame.eventHandler()->logicalScrollRecursively(ScrollBlockDirectionForward, ScrollByPage);
+ return frame.eventHandler().scrollRecursively(ScrollBlockDirectionForward, ScrollByPage);
}
static bool executeScrollLineUp(Frame& frame, Event*, EditorCommandSource, const String&)
{
- return frame.eventHandler()->scrollRecursively(ScrollUp, ScrollByLine);
+ return frame.eventHandler().scrollRecursively(ScrollUp, ScrollByLine);
}
static bool executeScrollLineDown(Frame& frame, Event*, EditorCommandSource, const String&)
{
- return frame.eventHandler()->scrollRecursively(ScrollDown, ScrollByLine);
+ return frame.eventHandler().scrollRecursively(ScrollDown, ScrollByLine);
}
static bool executeScrollToBeginningOfDocument(Frame& frame, Event*, EditorCommandSource, const String&)
{
- return frame.eventHandler()->logicalScrollRecursively(ScrollBlockDirectionBackward, ScrollByDocument);
+ return frame.eventHandler().scrollRecursively(ScrollBlockDirectionBackward, ScrollByDocument);
}
static bool executeScrollToEndOfDocument(Frame& frame, Event*, EditorCommandSource, const String&)
{
- return frame.eventHandler()->logicalScrollRecursively(ScrollBlockDirectionForward, ScrollByDocument);
+ return frame.eventHandler().scrollRecursively(ScrollBlockDirectionForward, ScrollByDocument);
}
static bool executeSelectAll(Frame& frame, Event*, EditorCommandSource, const String&)
@@ -1059,10 +1028,8 @@ static bool executeSelectToMark(Frame& frame, Event*, EditorCommandSource, const
{
RefPtr<Range> mark = frame.editor().mark().toNormalizedRange();
RefPtr<Range> selection = frame.editor().selectedRange();
- if (!mark || !selection) {
- systemBeep();
+ if (!mark || !selection)
return false;
- }
frame.selection().setSelectedRange(unionDOMRanges(mark.get(), selection.get()).get(), DOWNSTREAM, true);
return true;
}
@@ -1110,10 +1077,8 @@ static bool executeSwapWithMark(Frame& frame, Event*, EditorCommandSource, const
{
const VisibleSelection& mark = frame.editor().mark();
const VisibleSelection& selection = frame.selection().selection();
- if (mark.isNone() || selection.isNone()) {
- systemBeep();
+ if (mark.isNone() || selection.isNone())
return false;
- }
frame.selection().setSelection(mark);
frame.editor().setMark(selection);
return true;
@@ -1167,15 +1132,15 @@ static bool executeUnselect(Frame& frame, Event*, EditorCommandSource, const Str
static bool executeYank(Frame& frame, Event*, EditorCommandSource, const String&)
{
- frame.editor().insertTextWithoutSendingTextEvent(frame.editor().killRing()->yank(), false, 0);
- frame.editor().killRing()->setToYankedState();
+ frame.editor().insertTextWithoutSendingTextEvent(frame.editor().killRing().yank(), false, 0);
+ frame.editor().killRing().setToYankedState();
return true;
}
static bool executeYankAndSelect(Frame& frame, Event*, EditorCommandSource, const String&)
{
- frame.editor().insertTextWithoutSendingTextEvent(frame.editor().killRing()->yank(), true, 0);
- frame.editor().killRing()->setToYankedState();
+ frame.editor().insertTextWithoutSendingTextEvent(frame.editor().killRing().yank(), true, 0);
+ frame.editor().killRing().setToYankedState();
return true;
}
@@ -1575,7 +1540,6 @@ static const CommandMap& createCommandMap()
{ "OverWrite", { executeToggleOverwrite, supportedFromMenuOrKeyBinding, enabledInRichlyEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
{ "Paste", { executePaste, supportedPaste, enabledPaste, stateNone, valueNull, notTextInsertion, allowExecutionWhenDisabled } },
{ "PasteAndMatchStyle", { executePasteAndMatchStyle, supportedPaste, enabledPaste, stateNone, valueNull, notTextInsertion, allowExecutionWhenDisabled } },
- { "PasteAsPlainText", { executePasteAsPlainText, supportedPaste, enabledPaste, stateNone, valueNull, notTextInsertion, allowExecutionWhenDisabled } },
{ "PasteGlobalSelection", { executePasteGlobalSelection, supportedFromMenuOrKeyBinding, enabledPaste, stateNone, valueNull, notTextInsertion, allowExecutionWhenDisabled } },
{ "Print", { executePrint, supported, enabled, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
{ "Redo", { executeRedo, supported, enabledRedo, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
@@ -1676,12 +1640,12 @@ static const EditorInternalCommand* internalCommand(const String& commandName)
Editor::Command Editor::command(const String& commandName)
{
- return Command(internalCommand(commandName), CommandFromMenuOrKeyBinding, m_frame);
+ return Command(internalCommand(commandName), CommandFromMenuOrKeyBinding, &m_frame);
}
Editor::Command Editor::command(const String& commandName, EditorCommandSource source)
{
- return Command(internalCommand(commandName), source, m_frame);
+ return Command(internalCommand(commandName), source, &m_frame);
}
bool Editor::commandIsSupportedFromMenuOrKeyBinding(const String& commandName)
diff --git a/chromium/third_party/WebKit/Source/core/editing/EditorInsertAction.h b/chromium/third_party/WebKit/Source/core/editing/EditorInsertAction.h
deleted file mode 100644
index 92ee90607a2..00000000000
--- a/chromium/third_party/WebKit/Source/core/editing/EditorInsertAction.h
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright (C) 2006 Apple Computer, Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef EditorInsertAction_h
-#define EditorInsertAction_h
-
-namespace WebCore {
-
-// This must be kept in sync with WebViewInsertAction defined in WebEditingDelegate.h
-enum EditorInsertAction {
- EditorInsertActionTyped,
- EditorInsertActionPasted,
- EditorInsertActionDropped
-};
-
-} // namespace
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/editing/EditorKeyBindings.cpp b/chromium/third_party/WebKit/Source/core/editing/EditorKeyBindings.cpp
new file mode 100644
index 00000000000..3bd023f4faf
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/editing/EditorKeyBindings.cpp
@@ -0,0 +1,307 @@
+/*
+ * Copyright (C) 2006, 2007 Apple, Inc. All rights reserved.
+ * Copyright (C) 2012 Google, Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/editing/Editor.h"
+
+#include "core/events/KeyboardEvent.h"
+#include "core/frame/Frame.h"
+#include "core/page/EditorClient.h"
+#include "platform/KeyboardCodes.h"
+#include "platform/PlatformKeyboardEvent.h"
+
+namespace WebCore {
+
+//
+// The below code was adapted from the WebKit file webview.cpp
+//
+
+static const unsigned CtrlKey = 1 << 0;
+static const unsigned AltKey = 1 << 1;
+static const unsigned ShiftKey = 1 << 2;
+static const unsigned MetaKey = 1 << 3;
+#if OS(MACOSX)
+// Aliases for the generic key defintions to make kbd shortcuts definitions more
+// readable on OS X.
+static const unsigned OptionKey = AltKey;
+
+// Do not use this constant for anything but cursor movement commands. Keys
+// with cmd set have their |isSystemKey| bit set, so chances are the shortcut
+// will not be executed. Another, less important, reason is that shortcuts
+// defined in the renderer do not blink the menu item that they triggered. See
+// http://crbug.com/25856 and the bugs linked from there for details.
+static const unsigned CommandKey = MetaKey;
+#endif
+
+// Keys with special meaning. These will be delegated to the editor using
+// the execCommand() method
+struct KeyDownEntry {
+ unsigned virtualKey;
+ unsigned modifiers;
+ const char* name;
+};
+
+struct KeyPressEntry {
+ unsigned charCode;
+ unsigned modifiers;
+ const char* name;
+};
+
+// Key bindings with command key on Mac and alt key on other platforms are
+// marked as system key events and will be ignored (with the exception
+// of Command-B and Command-I) so they shouldn't be added here.
+static const KeyDownEntry keyDownEntries[] = {
+ { VKEY_LEFT, 0, "MoveLeft" },
+ { VKEY_LEFT, ShiftKey, "MoveLeftAndModifySelection" },
+#if OS(MACOSX)
+ { VKEY_LEFT, OptionKey, "MoveWordLeft" },
+ { VKEY_LEFT, OptionKey | ShiftKey,
+ "MoveWordLeftAndModifySelection" },
+#else
+ { VKEY_LEFT, CtrlKey, "MoveWordLeft" },
+ { VKEY_LEFT, CtrlKey | ShiftKey,
+ "MoveWordLeftAndModifySelection" },
+#endif
+ { VKEY_RIGHT, 0, "MoveRight" },
+ { VKEY_RIGHT, ShiftKey, "MoveRightAndModifySelection" },
+#if OS(MACOSX)
+ { VKEY_RIGHT, OptionKey, "MoveWordRight" },
+ { VKEY_RIGHT, OptionKey | ShiftKey, "MoveWordRightAndModifySelection" },
+#else
+ { VKEY_RIGHT, CtrlKey, "MoveWordRight" },
+ { VKEY_RIGHT, CtrlKey | ShiftKey, "MoveWordRightAndModifySelection" },
+#endif
+ { VKEY_UP, 0, "MoveUp" },
+ { VKEY_UP, ShiftKey, "MoveUpAndModifySelection" },
+ { VKEY_PRIOR, ShiftKey, "MovePageUpAndModifySelection" },
+ { VKEY_DOWN, 0, "MoveDown" },
+ { VKEY_DOWN, ShiftKey, "MoveDownAndModifySelection" },
+ { VKEY_NEXT, ShiftKey, "MovePageDownAndModifySelection" },
+#if !OS(MACOSX)
+ { VKEY_UP, CtrlKey, "MoveParagraphBackward" },
+ { VKEY_UP, CtrlKey | ShiftKey, "MoveParagraphBackwardAndModifySelection" },
+ { VKEY_DOWN, CtrlKey, "MoveParagraphForward" },
+ { VKEY_DOWN, CtrlKey | ShiftKey, "MoveParagraphForwardAndModifySelection" },
+ { VKEY_PRIOR, 0, "MovePageUp" },
+ { VKEY_NEXT, 0, "MovePageDown" },
+#endif
+ { VKEY_HOME, 0, "MoveToBeginningOfLine" },
+ { VKEY_HOME, ShiftKey,
+ "MoveToBeginningOfLineAndModifySelection" },
+#if OS(MACOSX)
+ { VKEY_PRIOR, OptionKey, "MovePageUp" },
+ { VKEY_NEXT, OptionKey, "MovePageDown" },
+#endif
+#if !OS(MACOSX)
+ { VKEY_HOME, CtrlKey, "MoveToBeginningOfDocument" },
+ { VKEY_HOME, CtrlKey | ShiftKey,
+ "MoveToBeginningOfDocumentAndModifySelection" },
+#endif
+ { VKEY_END, 0, "MoveToEndOfLine" },
+ { VKEY_END, ShiftKey, "MoveToEndOfLineAndModifySelection" },
+#if !OS(MACOSX)
+ { VKEY_END, CtrlKey, "MoveToEndOfDocument" },
+ { VKEY_END, CtrlKey | ShiftKey,
+ "MoveToEndOfDocumentAndModifySelection" },
+#endif
+ { VKEY_BACK, 0, "DeleteBackward" },
+ { VKEY_BACK, ShiftKey, "DeleteBackward" },
+ { VKEY_DELETE, 0, "DeleteForward" },
+#if OS(MACOSX)
+ { VKEY_BACK, OptionKey, "DeleteWordBackward" },
+ { VKEY_DELETE, OptionKey, "DeleteWordForward" },
+#else
+ { VKEY_BACK, CtrlKey, "DeleteWordBackward" },
+ { VKEY_DELETE, CtrlKey, "DeleteWordForward" },
+#endif
+#if OS(MACOSX)
+ { 'B', CommandKey, "ToggleBold" },
+ { 'I', CommandKey, "ToggleItalic" },
+#else
+ { 'B', CtrlKey, "ToggleBold" },
+ { 'I', CtrlKey, "ToggleItalic" },
+#endif
+ { 'U', CtrlKey, "ToggleUnderline" },
+ { VKEY_ESCAPE, 0, "Cancel" },
+ { VKEY_OEM_PERIOD, CtrlKey, "Cancel" },
+ { VKEY_TAB, 0, "InsertTab" },
+ { VKEY_TAB, ShiftKey, "InsertBacktab" },
+ { VKEY_RETURN, 0, "InsertNewline" },
+ { VKEY_RETURN, CtrlKey, "InsertNewline" },
+ { VKEY_RETURN, AltKey, "InsertNewline" },
+ { VKEY_RETURN, AltKey | ShiftKey, "InsertNewline" },
+ { VKEY_RETURN, ShiftKey, "InsertLineBreak" },
+ { VKEY_INSERT, CtrlKey, "Copy" },
+ { VKEY_INSERT, ShiftKey, "Paste" },
+ { VKEY_DELETE, ShiftKey, "Cut" },
+#if !OS(MACOSX)
+ // On OS X, we pipe these back to the browser, so that it can do menu item
+ // blinking.
+ { 'C', CtrlKey, "Copy" },
+ { 'V', CtrlKey, "Paste" },
+ { 'V', CtrlKey | ShiftKey, "PasteAndMatchStyle" },
+ { 'X', CtrlKey, "Cut" },
+ { 'A', CtrlKey, "SelectAll" },
+ { 'Z', CtrlKey, "Undo" },
+ { 'Z', CtrlKey | ShiftKey, "Redo" },
+ { 'Y', CtrlKey, "Redo" },
+#endif
+ { VKEY_INSERT, 0, "OverWrite" },
+};
+
+static const KeyPressEntry keyPressEntries[] = {
+ { '\t', 0, "InsertTab" },
+ { '\t', ShiftKey, "InsertBacktab" },
+ { '\r', 0, "InsertNewline" },
+ { '\r', CtrlKey, "InsertNewline" },
+ { '\r', ShiftKey, "InsertLineBreak" },
+ { '\r', AltKey, "InsertNewline" },
+ { '\r', AltKey | ShiftKey, "InsertNewline" },
+};
+
+const char* Editor::interpretKeyEvent(const KeyboardEvent* evt)
+{
+ const PlatformKeyboardEvent* keyEvent = evt->keyEvent();
+ if (!keyEvent)
+ return "";
+
+ static HashMap<int, const char*>* keyDownCommandsMap = 0;
+ static HashMap<int, const char*>* keyPressCommandsMap = 0;
+
+ if (!keyDownCommandsMap) {
+ keyDownCommandsMap = new HashMap<int, const char*>;
+ keyPressCommandsMap = new HashMap<int, const char*>;
+
+ for (unsigned i = 0; i < arraysize(keyDownEntries); i++) {
+ keyDownCommandsMap->set(keyDownEntries[i].modifiers << 16 | keyDownEntries[i].virtualKey, keyDownEntries[i].name);
+ }
+
+ for (unsigned i = 0; i < arraysize(keyPressEntries); i++) {
+ keyPressCommandsMap->set(keyPressEntries[i].modifiers << 16 | keyPressEntries[i].charCode, keyPressEntries[i].name);
+ }
+ }
+
+ unsigned modifiers = 0;
+ if (keyEvent->shiftKey())
+ modifiers |= ShiftKey;
+ if (keyEvent->altKey())
+ modifiers |= AltKey;
+ if (keyEvent->ctrlKey())
+ modifiers |= CtrlKey;
+ if (keyEvent->metaKey())
+ modifiers |= MetaKey;
+
+ if (keyEvent->type() == PlatformEvent::RawKeyDown) {
+ int mapKey = modifiers << 16 | evt->keyCode();
+ return mapKey ? keyDownCommandsMap->get(mapKey) : 0;
+ }
+
+ int mapKey = modifiers << 16 | evt->charCode();
+ return mapKey ? keyPressCommandsMap->get(mapKey) : 0;
+}
+
+bool Editor::handleEditingKeyboardEvent(KeyboardEvent* evt)
+{
+ const PlatformKeyboardEvent* keyEvent = evt->keyEvent();
+ // do not treat this as text input if it's a system key event
+ if (!keyEvent || keyEvent->isSystemKey())
+ return false;
+
+ String commandName = interpretKeyEvent(evt);
+ Command command = this->command(commandName);
+
+ if (keyEvent->type() == PlatformEvent::RawKeyDown) {
+ // WebKit doesn't have enough information about mode to decide how
+ // commands that just insert text if executed via Editor should be treated,
+ // so we leave it upon WebCore to either handle them immediately
+ // (e.g. Tab that changes focus) or let a keypress event be generated
+ // (e.g. Tab that inserts a Tab character, or Enter).
+ if (command.isTextInsertion() || commandName.isEmpty())
+ return false;
+ if (command.execute(evt)) {
+ client().didExecuteCommand(commandName);
+ return true;
+ }
+ return false;
+ }
+
+ if (command.execute(evt)) {
+ client().didExecuteCommand(commandName);
+ return true;
+ }
+
+ // Here we need to filter key events.
+ // On Gtk/Linux, it emits key events with ASCII text and ctrl on for ctrl-<x>.
+ // In Webkit, EditorClient::handleKeyboardEvent in
+ // WebKit/gtk/WebCoreSupport/EditorClientGtk.cpp drop such events.
+ // On Mac, it emits key events with ASCII text and meta on for Command-<x>.
+ // These key events should not emit text insert event.
+ // Alt key would be used to insert alternative character, so we should let
+ // through. Also note that Ctrl-Alt combination equals to AltGr key which is
+ // also used to insert alternative character.
+ // http://code.google.com/p/chromium/issues/detail?id=10846
+ // Windows sets both alt and meta are on when "Alt" key pressed.
+ // http://code.google.com/p/chromium/issues/detail?id=2215
+ // Also, we should not rely on an assumption that keyboards don't
+ // send ASCII characters when pressing a control key on Windows,
+ // which may be configured to do it so by user.
+ // See also http://en.wikipedia.org/wiki/Keyboard_Layout
+ // FIXME(ukai): investigate more detail for various keyboard layout.
+ if (evt->keyEvent()->text().length() == 1) {
+ UChar ch = evt->keyEvent()->text()[0U];
+
+ // Don't insert null or control characters as they can result in
+ // unexpected behaviour
+ if (ch < ' ')
+ return false;
+#if !OS(WIN)
+ // Don't insert ASCII character if ctrl w/o alt or meta is on.
+ // On Mac, we should ignore events when meta is on (Command-<x>).
+ if (ch < 0x80) {
+ if (evt->keyEvent()->ctrlKey() && !evt->keyEvent()->altKey())
+ return false;
+#if OS(MACOSX)
+ if (evt->keyEvent()->metaKey())
+ return false;
+#endif
+ }
+#endif
+ }
+
+ if (!canEdit())
+ return false;
+
+ return insertText(evt->keyEvent()->text(), evt);
+}
+
+void Editor::handleKeyboardEvent(KeyboardEvent* evt)
+{
+ // Give the embedder a chance to handle the keyboard event.
+ if (client().handleKeyboardEvent() || handleEditingKeyboardEvent(evt))
+ evt->setDefaultHandled();
+}
+
+} // namesace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/editing/FormatBlockCommand.cpp b/chromium/third_party/WebKit/Source/core/editing/FormatBlockCommand.cpp
index 8ea2e4d608d..57b9634a83a 100644
--- a/chromium/third_party/WebKit/Source/core/editing/FormatBlockCommand.cpp
+++ b/chromium/third_party/WebKit/Source/core/editing/FormatBlockCommand.cpp
@@ -32,6 +32,7 @@
#include "core/editing/FormatBlockCommand.h"
#include "core/editing/VisibleUnits.h"
#include "core/editing/htmlediting.h"
+#include "core/html/HTMLElement.h"
namespace WebCore {
@@ -60,16 +61,17 @@ void FormatBlockCommand::formatSelection(const VisiblePosition& startOfSelection
void FormatBlockCommand::formatRange(const Position& start, const Position& end, const Position& endOfSelection, RefPtr<Element>& blockNode)
{
- Node* nodeToSplitTo = enclosingBlockToSplitTreeTo(start.deprecatedNode());
- RefPtr<Node> outerBlock = (start.deprecatedNode() == nodeToSplitTo) ? start.deprecatedNode() : splitTreeToNode(start.deprecatedNode(), nodeToSplitTo);
- RefPtr<Node> nodeAfterInsertionPosition = outerBlock;
-
- RefPtr<Range> range = Range::create(document(), start, endOfSelection);
Element* refNode = enclosingBlockFlowElement(end);
Element* root = editableRootForPosition(start);
// Root is null for elements with contenteditable=false.
if (!root || !refNode)
return;
+
+ Node* nodeToSplitTo = enclosingBlockToSplitTreeTo(start.deprecatedNode());
+ RefPtr<Node> outerBlock = (start.deprecatedNode() == nodeToSplitTo) ? start.deprecatedNode() : splitTreeToNode(start.deprecatedNode(), nodeToSplitTo);
+ RefPtr<Node> nodeAfterInsertionPosition = outerBlock;
+ RefPtr<Range> range = Range::create(document(), start, endOfSelection);
+
if (isElementForFormatBlock(refNode->tagQName()) && start == startOfBlock(start)
&& (end == endOfBlock(end) || isNodeVisiblyContainedWithin(refNode, range.get()))
&& refNode != root && !root->isDescendantOf(refNode)) {
@@ -91,6 +93,10 @@ void FormatBlockCommand::formatRange(const Position& start, const Position& end,
moveParagraphWithClones(start, end, blockNode.get(), outerBlock.get());
+ // Copy the inline style of the original block element to the newly created block-style element.
+ if (outerBlock.get() != nodeAfterInsertionPosition.get() && toHTMLElement(nodeAfterInsertionPosition.get())->hasAttribute(styleAttr))
+ blockNode->setAttribute(styleAttr, toHTMLElement(nodeAfterInsertionPosition.get())->getAttribute(styleAttr));
+
if (wasEndOfParagraph && !isEndOfParagraph(lastParagraphInBlockNode) && !isStartOfParagraph(lastParagraphInBlockNode))
insertBlockPlaceholder(lastParagraphInBlockNode);
}
diff --git a/chromium/third_party/WebKit/Source/core/editing/FrameSelection.cpp b/chromium/third_party/WebKit/Source/core/editing/FrameSelection.cpp
index 2612860755a..05a32fb61b3 100644
--- a/chromium/third_party/WebKit/Source/core/editing/FrameSelection.cpp
+++ b/chromium/third_party/WebKit/Source/core/editing/FrameSelection.cpp
@@ -36,15 +36,16 @@
#include "core/dom/Element.h"
#include "core/dom/ElementTraversal.h"
#include "core/dom/NodeTraversal.h"
-#include "core/dom/Range.h"
#include "core/dom/Text.h"
#include "core/editing/Editor.h"
#include "core/editing/InputMethodController.h"
#include "core/editing/RenderedPosition.h"
+#include "core/editing/SpellChecker.h"
#include "core/editing/TextIterator.h"
#include "core/editing/TypingCommand.h"
#include "core/editing/VisibleUnits.h"
#include "core/editing/htmlediting.h"
+#include "core/frame/DOMWindow.h"
#include "core/html/HTMLFormElement.h"
#include "core/html/HTMLFrameElementBase.h"
#include "core/html/HTMLInputElement.h"
@@ -52,15 +53,12 @@
#include "core/page/EditorClient.h"
#include "core/page/EventHandler.h"
#include "core/page/FocusController.h"
-#include "core/page/Frame.h"
+#include "core/frame/Frame.h"
#include "core/page/FrameTree.h"
-#include "core/page/FrameView.h"
+#include "core/frame/FrameView.h"
#include "core/page/Page.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
#include "core/page/SpatialNavigation.h"
-#include "core/platform/SecureTextInput.h"
-#include "core/platform/graphics/FloatQuad.h"
-#include "core/platform/graphics/GraphicsContext.h"
#include "core/rendering/HitTestRequest.h"
#include "core/rendering/HitTestResult.h"
#include "core/rendering/InlineTextBox.h"
@@ -68,6 +66,9 @@
#include "core/rendering/RenderTheme.h"
#include "core/rendering/RenderView.h"
#include "core/rendering/RenderWidget.h"
+#include "platform/SecureTextInput.h"
+#include "platform/geometry/FloatQuad.h"
+#include "platform/graphics/GraphicsContext.h"
#include "wtf/text/CString.h"
#define EDIT_DEBUG 0
@@ -117,14 +118,6 @@ Node* FrameSelection::rootEditableElementOrTreeScopeRootNode() const
return node ? node->treeScope().rootNode() : 0;
}
-Element* FrameSelection::rootEditableElementRespectingShadowTree() const
-{
- Element* selectionRoot = m_selection.rootEditableElement();
- if (selectionRoot && selectionRoot->isInShadowTree())
- selectionRoot = selectionRoot->shadowHost();
- return selectionRoot;
-}
-
void FrameSelection::moveTo(const VisiblePosition &pos, EUserTriggered userTriggered, CursorAlignOnScroll align)
{
SetSelectionOptions options = CloseTyping | ClearTypingStyle | userTriggered;
@@ -203,11 +196,12 @@ void FrameSelection::setNonDirectionalSelectionIfNeeded(const VisibleSelection&
VisiblePosition base = m_originalBase.isNotNull() ? m_originalBase : newSelection.visibleBase();
VisiblePosition newBase = base;
- VisiblePosition newExtent = newSelection.visibleExtent();
+ VisiblePosition extent = newSelection.visibleExtent();
+ VisiblePosition newExtent = extent;
if (endpointsAdjustmentMode == AdjustEndpointsAtBidiBoundary)
adjustEndpointsAtBidiBoundary(newBase, newExtent);
- if (newBase != base || newExtent != newSelection.visibleExtent()) {
+ if (newBase != base || newExtent != extent) {
m_originalBase = base;
newSelection.setBase(newBase);
newSelection.setExtent(newExtent);
@@ -218,7 +212,7 @@ void FrameSelection::setNonDirectionalSelectionIfNeeded(const VisibleSelection&
}
newSelection.setIsDirectional(isDirectional); // Adjusting base and extent will make newSelection always directional
- if (m_selection == newSelection || !shouldChangeSelection(newSelection))
+ if (m_selection == newSelection)
return;
setSelection(newSelection, granularity);
@@ -243,7 +237,7 @@ void FrameSelection::setSelection(const VisibleSelection& newSelection, SetSelec
// if document->frame() == m_frame we can get into an infinite loop
if (s.base().anchorNode()) {
Document& document = *s.base().document();
- if (document.frame() && document.frame() != m_frame && &document != m_frame->document()) {
+ if (document.frame() && document.frame() != m_frame && document != m_frame->document()) {
RefPtr<Frame> guard = document.frame();
document.frame()->selection().setSelection(s, options, align, granularity);
// It's possible that during the above set selection, this FrameSelection has been modified by
@@ -301,10 +295,10 @@ void FrameSelection::setSelection(const VisibleSelection& newSelection, SetSelec
}
notifyAccessibilityForSelectionChange();
- m_frame->document()->enqueueDocumentEvent(Event::create(eventNames().selectionchangeEvent));
+ m_frame->domWindow()->enqueueDocumentEvent(Event::create(EventTypeNames::selectionchange));
}
-static bool removingNodeRemovesPosition(Node* node, const Position& position)
+static bool removingNodeRemovesPosition(Node& node, const Position& position)
{
if (!position.anchorNode())
return false;
@@ -312,34 +306,28 @@ static bool removingNodeRemovesPosition(Node* node, const Position& position)
if (position.anchorNode() == node)
return true;
- if (!node->isElementNode())
+ if (!node.isElementNode())
return false;
- Element* element = toElement(node);
- return element->containsIncludingShadowDOM(position.anchorNode());
-}
-
-static void clearRenderViewSelection(const Position& position)
-{
- RefPtr<Document> document = position.document();
- document->updateStyleIfNeeded();
- if (RenderView* view = document->renderView())
- view->clearSelection();
+ Element& element = toElement(node);
+ return element.containsIncludingShadowDOM(position.anchorNode());
}
-void FrameSelection::nodeWillBeRemoved(Node* node)
+void FrameSelection::nodeWillBeRemoved(Node& node)
{
// There can't be a selection inside a fragment, so if a fragment's node is being removed,
// the selection in the document that created the fragment needs no adjustment.
- if (isNone() || (node && !node->inDocument()))
+ if (isNone() || !node.inActiveDocument())
return;
respondToNodeModification(node, removingNodeRemovesPosition(node, m_selection.base()), removingNodeRemovesPosition(node, m_selection.extent()),
removingNodeRemovesPosition(node, m_selection.start()), removingNodeRemovesPosition(node, m_selection.end()));
}
-void FrameSelection::respondToNodeModification(Node* node, bool baseRemoved, bool extentRemoved, bool startRemoved, bool endRemoved)
+void FrameSelection::respondToNodeModification(Node& node, bool baseRemoved, bool extentRemoved, bool startRemoved, bool endRemoved)
{
+ ASSERT(node.document().isActive());
+
bool clearRenderTreeSelection = false;
bool clearDOMTreeSelection = false;
@@ -347,9 +335,9 @@ void FrameSelection::respondToNodeModification(Node* node, bool baseRemoved, boo
Position start = m_selection.start();
Position end = m_selection.end();
if (startRemoved)
- updatePositionForNodeRemoval(start, node);
+ updatePositionForNodeRemoval(start, &node);
if (endRemoved)
- updatePositionForNodeRemoval(end, node);
+ updatePositionForNodeRemoval(end, &node);
if (start.isNotNull() && end.isNotNull()) {
if (m_selection.isBaseFirst())
@@ -370,9 +358,9 @@ void FrameSelection::respondToNodeModification(Node* node, bool baseRemoved, boo
else
m_selection.setWithoutValidation(m_selection.end(), m_selection.start());
} else if (RefPtr<Range> range = m_selection.firstRange()) {
- TrackExceptionState es;
- Range::CompareResults compareResult = range->compareNode(node, es);
- if (!es.hadException() && (compareResult == Range::NODE_BEFORE_AND_AFTER || compareResult == Range::NODE_INSIDE)) {
+ TrackExceptionState exceptionState;
+ Range::CompareResults compareResult = range->compareNode(&node, exceptionState);
+ if (!exceptionState.hadException() && (compareResult == Range::NODE_BEFORE_AND_AFTER || compareResult == Range::NODE_INSIDE)) {
// If we did nothing here, when this node's renderer was destroyed, the rect that it
// occupied would be invalidated, but, selection gaps that change as a result of
// the removal wouldn't be invalidated.
@@ -382,7 +370,7 @@ void FrameSelection::respondToNodeModification(Node* node, bool baseRemoved, boo
}
if (clearRenderTreeSelection)
- clearRenderViewSelection(m_selection.start());
+ m_selection.start().document()->renderView()->clearSelection();
if (clearDOMTreeSelection)
setSelection(VisibleSelection(), DoNotSetFocus);
@@ -411,16 +399,10 @@ static Position updatePositionAfterAdoptingTextReplacement(const Position& posit
return Position(toText(node), positionOffset);
}
-static inline bool nodeIsDetachedFromDocument(const Node& node)
-{
- Node* highest = node.highestAncestor();
- return highest->nodeType() == Node::DOCUMENT_FRAGMENT_NODE && !highest->isShadowRoot();
-}
-
void FrameSelection::didUpdateCharacterData(CharacterData* node, unsigned offset, unsigned oldLength, unsigned newLength)
{
// The fragment check is a performance optimization. See http://trac.webkit.org/changeset/30062.
- if (isNone() || !node || nodeIsDetachedFromDocument(*node))
+ if (isNone() || !node || !node->inDocument())
return;
Position base = updatePositionAfterAdoptingTextReplacement(m_selection.base(), node, offset, oldLength, newLength);
@@ -449,7 +431,7 @@ static Position updatePostionAfterAdoptingTextNodesMerged(const Position& positi
void FrameSelection::didMergeTextNodes(const Text& oldNode, unsigned offset)
{
- if (isNone() || nodeIsDetachedFromDocument(oldNode))
+ if (isNone() || !oldNode.inDocument())
return;
Position base = updatePostionAfterAdoptingTextNodesMerged(m_selection.base(), oldNode, offset);
Position extent = updatePostionAfterAdoptingTextNodesMerged(m_selection.extent(), oldNode, offset);
@@ -473,7 +455,7 @@ static Position updatePostionAfterAdoptingTextNodeSplit(const Position& position
void FrameSelection::didSplitTextNode(const Text& oldNode)
{
- if (isNone() || nodeIsDetachedFromDocument(oldNode))
+ if (isNone() || !oldNode.inDocument())
return;
Position base = updatePostionAfterAdoptingTextNodeSplit(m_selection.base(), oldNode);
Position extent = updatePostionAfterAdoptingTextNodeSplit(m_selection.extent(), oldNode);
@@ -957,10 +939,6 @@ bool FrameSelection::modify(EAlteration alter, SelectionDirection direction, Tex
trialFrameSelection.setSelection(m_selection);
trialFrameSelection.modify(alter, direction, granularity, NotUserTriggered);
- bool change = shouldChangeSelection(trialFrameSelection.selection());
- if (!change)
- return false;
-
if (trialFrameSelection.selection().isRange() && m_selection.isCaret() && !dispatchSelectStart())
return false;
}
@@ -1074,10 +1052,6 @@ bool FrameSelection::modify(EAlteration alter, unsigned verticalDistance, Vertic
FrameSelection trialFrameSelection;
trialFrameSelection.setSelection(m_selection);
trialFrameSelection.modify(alter, verticalDistance, direction, NotUserTriggered);
-
- bool change = shouldChangeSelection(trialFrameSelection.selection());
- if (!change)
- return false;
}
willBeModified(alter, direction == DirectionUp ? DirectionBackward : DirectionForward);
@@ -1324,71 +1298,6 @@ void FrameSelection::paintCaret(GraphicsContext* context, const LayoutPoint& pai
CaretBase::paintCaret(m_selection.start().deprecatedNode(), context, paintOffset, clipRect);
}
-void FrameSelection::debugRenderer(RenderObject *r, bool selected) const
-{
- if (r->node()->isElementNode()) {
- Element* element = toElement(r->node());
- fprintf(stderr, "%s%s\n", selected ? "==> " : " ", element->localName().string().utf8().data());
- } else if (r->isText()) {
- RenderText* textRenderer = toRenderText(r);
- if (!textRenderer->textLength() || !textRenderer->firstTextBox()) {
- fprintf(stderr, "%s#text (empty)\n", selected ? "==> " : " ");
- return;
- }
-
- static const int max = 36;
- String text = textRenderer->text();
- int textLength = text.length();
- if (selected) {
- int offset = 0;
- if (r->node() == m_selection.start().containerNode())
- offset = m_selection.start().computeOffsetInContainerNode();
- else if (r->node() == m_selection.end().containerNode())
- offset = m_selection.end().computeOffsetInContainerNode();
-
- int pos;
- InlineTextBox* box = textRenderer->findNextInlineTextBox(offset, pos);
- text = text.substring(box->start(), box->len());
-
- String show;
- int mid = max / 2;
- int caret = 0;
-
- // text is shorter than max
- if (textLength < max) {
- show = text;
- caret = pos;
- } else if (pos - mid < 0) {
- // too few characters to left
- show = text.left(max - 3) + "...";
- caret = pos;
- } else if (pos - mid >= 0 && pos + mid <= textLength) {
- // enough characters on each side
- show = "..." + text.substring(pos - mid + 3, max - 6) + "...";
- caret = mid;
- } else {
- // too few characters on right
- show = "..." + text.right(max - 3);
- caret = pos - (textLength - show.length());
- }
-
- show.replace('\n', ' ');
- show.replace('\r', ' ');
- fprintf(stderr, "==> #text : \"%s\" at offset %d\n", show.utf8().data(), pos);
- fprintf(stderr, " ");
- for (int i = 0; i < caret; i++)
- fprintf(stderr, " ");
- fprintf(stderr, "^\n");
- } else {
- if ((int)text.length() > max)
- text = text.left(max - 3) + "...";
- else
- text = text.left(max);
- fprintf(stderr, " #text : \"%s\"\n", text.utf8().data());
- }
- }
-}
-
bool FrameSelection::contains(const LayoutPoint& point)
{
Document* document = m_frame->document();
@@ -1396,10 +1305,10 @@ bool FrameSelection::contains(const LayoutPoint& point)
// Treat a collapsed selection like no selection.
if (!isRange())
return false;
- if (!document->renderer())
+ if (!document->renderView())
return false;
- HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::DisallowShadowContent);
+ HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent);
HitTestResult result(point);
document->renderView()->hitTest(request, result);
Node* innerNode = result.innerNode();
@@ -1428,7 +1337,7 @@ bool FrameSelection::contains(const LayoutPoint& point)
void FrameSelection::selectFrameElementInParentIfFullySelected()
{
// Find the parent frame; if there is none, then we have nothing to do.
- Frame* parent = m_frame->tree()->parent();
+ Frame* parent = m_frame->tree().parent();
if (!parent)
return;
Page* page = m_frame->page();
@@ -1462,10 +1371,8 @@ void FrameSelection::selectFrameElementInParentIfFullySelected()
// Focus on the parent frame, and then select from before this element to after.
VisibleSelection newSelection(beforeOwnerElement, afterOwnerElement);
- if (parent->selection().shouldChangeSelection(newSelection)) {
- page->focusController().setFocusedFrame(parent);
- parent->selection().setSelection(newSelection);
- }
+ page->focusController().setFocusedFrame(parent);
+ parent->selection().setSelection(newSelection);
}
void FrameSelection::selectAll()
@@ -1500,14 +1407,11 @@ void FrameSelection::selectAll()
if (!root)
return;
- if (selectStartTarget && !selectStartTarget->dispatchEvent(Event::createCancelableBubble(eventNames().selectstartEvent)))
+ if (selectStartTarget && !selectStartTarget->dispatchEvent(Event::createCancelableBubble(EventTypeNames::selectstart)))
return;
VisibleSelection newSelection(VisibleSelection::selectionFromContentsOfNode(root.get()));
-
- if (shouldChangeSelection(newSelection))
- setSelection(newSelection);
-
+ setSelection(newSelection);
selectFrameElementInParentIfFullySelected();
notifyRendererOfSelectionChange(UserTriggered);
}
@@ -1516,15 +1420,15 @@ bool FrameSelection::setSelectedRange(Range* range, EAffinity affinity, bool clo
{
if (!range || !range->startContainer() || !range->endContainer())
return false;
- ASSERT(&range->startContainer()->document() == &range->endContainer()->document());
+ ASSERT(range->startContainer()->document() == range->endContainer()->document());
m_frame->document()->updateLayoutIgnorePendingStylesheets();
// Non-collapsed ranges are not allowed to start at the end of a line that is wrapped,
// they start at the beginning of the next line instead
- TrackExceptionState es;
- bool collapsed = range->collapsed(es);
- if (es.hadException())
+ TrackExceptionState exceptionState;
+ bool collapsed = range->collapsed(exceptionState);
+ if (exceptionState.hadException())
return false;
// FIXME: Can we provide extentAffinity?
@@ -1552,35 +1456,32 @@ void FrameSelection::focusedOrActiveStateChanged()
{
bool activeAndFocused = isFocusedAndActive();
+ RefPtr<Document> document = m_frame->document();
+ document->updateStyleIfNeeded();
+
// Because RenderObject::selectionBackgroundColor() and
// RenderObject::selectionForegroundColor() check if the frame is active,
// we have to update places those colors were painted.
- if (RenderView* view = m_frame->document()->renderView())
+ if (RenderView* view = document->renderView())
view->repaintSelection();
// Caret appears in the active frame.
if (activeAndFocused)
setSelectionFromNone();
else
- m_frame->editor().spellCheckAfterBlur();
+ m_frame->spellChecker().spellCheckAfterBlur();
setCaretVisibility(activeAndFocused ? Visible : Hidden);
// Update for caps lock state
- m_frame->eventHandler()->capsLockStateMayHaveChanged();
-
- // Because StyleResolver::checkOneSelector() and
- // RenderTheme::isFocused() check if the frame is active, we have to
- // update style and theme state that depended on those.
- if (Element* element = m_frame->document()->focusedElement()) {
- element->setNeedsStyleRecalc();
- if (RenderObject* renderer = element->renderer()) {
- if (renderer && renderer->style()->hasAppearance())
- RenderTheme::theme().stateChanged(renderer, FocusState);
- }
- }
+ m_frame->eventHandler().capsLockStateMayHaveChanged();
+
+ // We may have lost active status even though the focusElement hasn't changed
+ // give the element a chance to recalc style if its affected by focus.
+ if (Element* element = document->focusedElement())
+ element->focusStateChanged();
// Secure keyboard entry is set by the active frame.
- if (m_frame->document()->useSecureKeyboardEntryWhenActive())
+ if (document->useSecureKeyboardEntryWhenActive())
setUseSecureKeyboardEntry(activeAndFocused);
}
@@ -1815,39 +1716,18 @@ String FrameSelection::selectedTextForClipboard() const
return selectedText();
}
-bool FrameSelection::shouldDeleteSelection(const VisibleSelection& selection) const
-{
- return m_frame->editor().client().shouldDeleteRange(selection.toNormalizedRange().get());
-}
-
FloatRect FrameSelection::bounds(bool clipToVisibleContent) const
{
- RenderView* root = m_frame->contentRenderer();
- FrameView* view = m_frame->view();
- if (!root || !view)
- return LayoutRect();
-
- LayoutRect selectionRect = root->selectionBounds(clipToVisibleContent);
- return clipToVisibleContent ? intersection(selectionRect, view->visibleContentRect()) : selectionRect;
-}
-
-void FrameSelection::getClippedVisibleTextRectangles(Vector<FloatRect>& rectangles) const
-{
- RenderView* root = m_frame->contentRenderer();
- if (!root)
- return;
+ m_frame->document()->updateStyleIfNeeded();
- FloatRect visibleContentRect = m_frame->view()->visibleContentRect();
+ FrameView* view = m_frame->view();
+ RenderView* renderView = m_frame->contentRenderer();
- Vector<FloatQuad> quads;
- toNormalizedRange()->textQuads(quads, true);
+ if (!view || !renderView)
+ return FloatRect();
- size_t size = quads.size();
- for (size_t i = 0; i < size; ++i) {
- FloatRect intersectionRect = intersection(quads[i].enclosingBoundingBox(), visibleContentRect);
- if (!intersectionRect.isEmpty())
- rectangles.append(intersectionRect);
- }
+ LayoutRect selectionRect = renderView->selectionBounds(clipToVisibleContent);
+ return clipToVisibleContent ? intersection(selectionRect, view->visibleContentRect()) : selectionRect;
}
// Scans logically forward from "start", including any child frames.
@@ -1855,12 +1735,15 @@ static HTMLFormElement* scanForForm(Node* start)
{
if (!start)
return 0;
- Element* element = start->isElementNode() ? toElement(start) : ElementTraversal::next(start);
- for (; element; element = ElementTraversal::next(element)) {
+ Element* element = start->isElementNode() ? toElement(start) : ElementTraversal::next(*start);
+ for (; element; element = ElementTraversal::next(*element)) {
if (element->hasTagName(formTag))
return toHTMLFormElement(element);
- if (element->isHTMLElement() && toHTMLElement(element)->isFormControlElement())
- return toHTMLFormControlElement(element)->form();
+ if (element->isHTMLElement()) {
+ HTMLFormElement* owner = toHTMLElement(element)->formOwner();
+ if (owner)
+ return owner;
+ }
if (element->hasTagName(frameTag) || element->hasTagName(iframeTag)) {
Node* childDocument = toHTMLFrameElementBase(element)->contentDocument();
if (HTMLFormElement* frameResult = scanForForm(childDocument))
@@ -1883,8 +1766,11 @@ HTMLFormElement* FrameSelection::currentForm() const
for (node = start; node; node = node->parentNode()) {
if (node->hasTagName(formTag))
return toHTMLFormElement(node);
- if (node->isHTMLElement() && toHTMLElement(node)->isFormControlElement())
- return toHTMLFormControlElement(node)->form();
+ if (node->isHTMLElement()) {
+ HTMLFormElement* owner = toHTMLElement(node)->formOwner();
+ if (owner)
+ return owner;
+ }
}
// Try walking forward in the node tree to find a form element.
@@ -1896,12 +1782,12 @@ void FrameSelection::revealSelection(const ScrollAlignment& alignment, RevealExt
LayoutRect rect;
switch (selectionType()) {
- case VisibleSelection::NoSelection:
+ case NoSelection:
return;
- case VisibleSelection::CaretSelection:
+ case CaretSelection:
rect = absoluteCaretBounds();
break;
- case VisibleSelection::RangeSelection:
+ case RangeSelection:
rect = revealExtentOption == RevealExtent ? VisiblePosition(extent()).absoluteCaretBounds() : enclosingIntRect(bounds(false));
break;
}
@@ -1929,29 +1815,18 @@ void FrameSelection::setSelectionFromNone()
Node* node = document->documentElement();
while (node && !node->hasTagName(bodyTag))
- node = NodeTraversal::next(node);
+ node = NodeTraversal::next(*node);
if (node)
setSelection(VisibleSelection(firstPositionInOrBeforeNode(node), DOWNSTREAM));
}
-bool FrameSelection::shouldChangeSelection(const VisibleSelection& newSelection) const
-{
- return m_frame->editor().shouldChangeSelection(selection(), newSelection, newSelection.affinity(), false);
-}
-
bool FrameSelection::dispatchSelectStart()
{
Node* selectStartTarget = m_selection.extent().containerNode();
if (!selectStartTarget)
return true;
- return selectStartTarget->dispatchEvent(Event::createCancelableBubble(eventNames().selectstartEvent));
-}
-
-inline bool FrameSelection::visualWordMovementEnabled() const
-{
- Settings* settings = m_frame ? m_frame->settings() : 0;
- return settings && settings->visualWordMovementEnabled();
+ return selectStartTarget->dispatchEvent(Event::createCancelableBubble(EventTypeNames::selectstart));
}
void FrameSelection::setShouldShowBlockCursor(bool shouldShowBlockCursor)
diff --git a/chromium/third_party/WebKit/Source/core/editing/FrameSelection.h b/chromium/third_party/WebKit/Source/core/editing/FrameSelection.h
index 470dce0ce5a..04b65990bd8 100644
--- a/chromium/third_party/WebKit/Source/core/editing/FrameSelection.h
+++ b/chromium/third_party/WebKit/Source/core/editing/FrameSelection.h
@@ -30,10 +30,10 @@
#include "core/editing/Caret.h"
#include "core/editing/EditingStyle.h"
#include "core/editing/VisibleSelection.h"
-#include "core/platform/Timer.h"
-#include "core/platform/graphics/IntRect.h"
-#include "core/platform/graphics/LayoutRect.h"
#include "core/rendering/ScrollBehavior.h"
+#include "platform/Timer.h"
+#include "platform/geometry/IntRect.h"
+#include "platform/geometry/LayoutRect.h"
#include "wtf/Noncopyable.h"
namespace WebCore {
@@ -82,7 +82,6 @@ public:
Element* rootEditableElement() const { return m_selection.rootEditableElement(); }
Element* rootEditableElementOrDocumentElement() const;
Node* rootEditableElementOrTreeScopeRootNode() const;
- Element* rootEditableElementRespectingShadowTree() const;
bool rendererIsEditable() const { return m_selection.rendererIsEditable(); }
bool isContentEditable() const { return m_selection.isContentEditable(); }
@@ -107,7 +106,7 @@ public:
bool contains(const LayoutPoint&);
- VisibleSelection::SelectionType selectionType() const { return m_selection.selectionType(); }
+ SelectionType selectionType() const { return m_selection.selectionType(); }
EAffinity affinity() const { return m_selection.affinity(); }
@@ -152,9 +151,7 @@ public:
PassRefPtr<Range> toNormalizedRange() const { return m_selection.toNormalizedRange(); }
- void debugRenderer(RenderObject*, bool selected) const;
-
- void nodeWillBeRemoved(Node*);
+ void nodeWillBeRemoved(Node&);
void didUpdateCharacterData(CharacterData*, unsigned offset, unsigned oldLength, unsigned newLength);
void didMergeTextNodes(const Text& oldNode, unsigned offset);
void didSplitTextNode(const Text& oldNode);
@@ -184,8 +181,6 @@ public:
void showTreeForThis() const;
#endif
- bool shouldChangeSelection(const VisibleSelection&) const;
- bool shouldDeleteSelection(const VisibleSelection&) const;
enum EndPointsAdjustmentMode { AdjustEndpointsAtBidiBoundary, DoNotAdjsutEndpoints };
void setNonDirectionalSelectionIfNeeded(const VisibleSelection&, TextGranularity, EndPointsAdjustmentMode = DoNotAdjsutEndpoints);
void setFocusedNodeIfNeeded();
@@ -203,8 +198,6 @@ public:
FloatRect bounds(bool clipToVisibleContent = true) const;
- void getClippedVisibleTextRectangles(Vector<FloatRect>&) const;
-
HTMLFormElement* currentForm() const;
void revealSelection(const ScrollAlignment& = ScrollAlignment::alignCenterIfNeeded, RevealExtentOption = DoNotRevealExtent);
@@ -216,7 +209,7 @@ public:
private:
enum EPositionType { START, END, BASE, EXTENT };
- void respondToNodeModification(Node*, bool baseRemoved, bool extentRemoved, bool startRemoved, bool endRemoved);
+ void respondToNodeModification(Node&, bool baseRemoved, bool extentRemoved, bool startRemoved, bool endRemoved);
TextDirection directionOfEnclosingBlock();
TextDirection directionOfSelection();
@@ -249,8 +242,6 @@ private:
bool dispatchSelectStart();
- bool visualWordMovementEnabled() const;
-
void updateSelectionIfNeeded(const Position& base, const Position& extent, const Position& start, const Position& end);
Frame* m_frame;
diff --git a/chromium/third_party/WebKit/Source/core/editing/IndentOutdentCommand.cpp b/chromium/third_party/WebKit/Source/core/editing/IndentOutdentCommand.cpp
index a98c166492e..f882fe03a5e 100644
--- a/chromium/third_party/WebKit/Source/core/editing/IndentOutdentCommand.cpp
+++ b/chromium/third_party/WebKit/Source/core/editing/IndentOutdentCommand.cpp
@@ -69,10 +69,21 @@ bool IndentOutdentCommand::tryIndentingAsListItem(const Position& start, const P
RefPtr<Element> previousList = selectedListItem->previousElementSibling();
RefPtr<Element> nextList = selectedListItem->nextElementSibling();
+ // We should calculate visible range in list item because inserting new
+ // list element will change visibility of list item, e.g. :first-child
+ // CSS selector.
RefPtr<Element> newList = document().createElement(listNode->tagQName(), false);
insertNodeBefore(newList, selectedListItem.get());
- moveParagraphWithClones(start, end, newList.get(), selectedListItem.get());
+ // We should clone all the children of the list item for indenting purposes. However, in case the current
+ // selection does not encompass all its children, we need to explicitally handle the same. The original
+ // list item too would require proper deletion in that case.
+ if (end.anchorNode() == selectedListItem.get() || end.anchorNode()->isDescendantOf(selectedListItem->lastChild())) {
+ moveParagraphWithClones(start, end, newList.get(), selectedListItem.get());
+ } else {
+ moveParagraphWithClones(start, positionAfterNode(selectedListItem->lastChild()), newList.get(), selectedListItem.get());
+ removeNode(selectedListItem.get());
+ }
if (canMergeLists(previousList.get(), newList.get()))
mergeIdenticalElements(previousList.get(), newList.get());
@@ -96,7 +107,6 @@ void IndentOutdentCommand::indentIntoBlockquote(const Position& start, const Pos
if (!nodeToSplitTo)
return;
- RefPtr<Node> nodeAfterStart = start.computeNodeAfterPosition();
RefPtr<Node> outerBlock = (start.containerNode() == nodeToSplitTo) ? start.containerNode() : splitTreeToNode(start.containerNode(), nodeToSplitTo);
VisiblePosition startOfContents = start;
@@ -183,16 +193,16 @@ void IndentOutdentCommand::outdentParagraph()
// FIXME: We should merge this function with ApplyBlockElementCommand::formatSelection
void IndentOutdentCommand::outdentRegion(const VisiblePosition& startOfSelection, const VisiblePosition& endOfSelection)
{
+ VisiblePosition endOfCurrentParagraph = endOfParagraph(startOfSelection);
VisiblePosition endOfLastParagraph = endOfParagraph(endOfSelection);
- if (endOfParagraph(startOfSelection) == endOfLastParagraph) {
+ if (endOfCurrentParagraph == endOfLastParagraph) {
outdentParagraph();
return;
}
Position originalSelectionEnd = endingSelection().end();
- VisiblePosition endOfCurrentParagraph = endOfParagraph(startOfSelection);
- VisiblePosition endAfterSelection = endOfParagraph(endOfParagraph(endOfSelection).next());
+ VisiblePosition endAfterSelection = endOfParagraph(endOfLastParagraph.next());
while (endOfCurrentParagraph != endAfterSelection) {
VisiblePosition endOfNextParagraph = endOfParagraph(endOfCurrentParagraph.next());
diff --git a/chromium/third_party/WebKit/Source/core/editing/InputMethodController.cpp b/chromium/third_party/WebKit/Source/core/editing/InputMethodController.cpp
index 38bc074e820..92eb55ab0a0 100644
--- a/chromium/third_party/WebKit/Source/core/editing/InputMethodController.cpp
+++ b/chromium/third_party/WebKit/Source/core/editing/InputMethodController.cpp
@@ -27,39 +27,22 @@
#include "config.h"
#include "core/editing/InputMethodController.h"
-#include "core/dom/CompositionEvent.h"
+#include "core/events/CompositionEvent.h"
#include "core/dom/Document.h"
#include "core/dom/Element.h"
#include "core/dom/Range.h"
#include "core/dom/Text.h"
-#include "core/dom/UserTypingGestureIndicator.h"
#include "core/editing/Editor.h"
#include "core/editing/TypingCommand.h"
#include "core/html/HTMLTextAreaElement.h"
-#include "core/page/EditorClient.h"
+#include "core/page/Chrome.h"
+#include "core/page/ChromeClient.h"
#include "core/page/EventHandler.h"
-#include "core/page/Frame.h"
+#include "core/frame/Frame.h"
#include "core/rendering/RenderObject.h"
namespace WebCore {
-PlainTextOffsets::PlainTextOffsets()
- : m_start(kNotFound)
- , m_end(kNotFound)
-{
-}
-
-PlainTextOffsets::PlainTextOffsets(int start, int end)
- : m_start(start)
- , m_end(end)
-{
- ASSERT(start != kNotFound);
- ASSERT(end != kNotFound);
- ASSERT(start <= end);
-}
-
-// ----------------------------
-
InputMethodController::SelectionOffsetsScope::SelectionOffsetsScope(InputMethodController* inputMethodController)
: m_inputMethodController(inputMethodController)
, m_offsets(inputMethodController->getSelectionOffsets())
@@ -73,12 +56,12 @@ InputMethodController::SelectionOffsetsScope::~SelectionOffsetsScope()
// ----------------------------
-PassOwnPtr<InputMethodController> InputMethodController::create(Frame* frame)
+PassOwnPtr<InputMethodController> InputMethodController::create(Frame& frame)
{
return adoptPtr(new InputMethodController(frame));
}
-InputMethodController::InputMethodController(Frame* frame)
+InputMethodController::InputMethodController(Frame& frame)
: m_frame(frame)
, m_compositionStart(0)
, m_compositionEnd(0)
@@ -89,14 +72,14 @@ InputMethodController::~InputMethodController()
{
}
-inline Editor& InputMethodController::editor() const
+bool InputMethodController::hasComposition() const
{
- return m_frame->editor();
+ return m_compositionNode && m_compositionNode->isContentEditable();
}
-inline EditorClient& InputMethodController::editorClient() const
+inline Editor& InputMethodController::editor() const
{
- return editor().client();
+ return m_frame.editor();
}
void InputMethodController::clear()
@@ -107,7 +90,7 @@ void InputMethodController::clear()
bool InputMethodController::insertTextForConfirmedComposition(const String& text)
{
- return m_frame->eventHandler()->handleTextInputEvent(text, 0, TextEventInputComposition);
+ return m_frame.eventHandler().handleTextInputEvent(text, 0, TextEventInputComposition);
}
void InputMethodController::selectComposition() const
@@ -120,19 +103,40 @@ void InputMethodController::selectComposition() const
// See <http://bugs.webkit.org/show_bug.cgi?id=15781>
VisibleSelection selection;
selection.setWithoutValidation(range->startPosition(), range->endPosition());
- m_frame->selection().setSelection(selection, 0);
+ m_frame.selection().setSelection(selection, 0);
}
-void InputMethodController::confirmComposition()
+bool InputMethodController::confirmComposition()
{
- if (!m_compositionNode)
- return;
- finishComposition(m_compositionNode->data().substring(m_compositionStart, m_compositionEnd - m_compositionStart), ConfirmComposition);
+ if (!hasComposition())
+ return false;
+ return finishComposition(m_compositionNode->data().substring(m_compositionStart, m_compositionEnd - m_compositionStart), ConfirmComposition);
}
-void InputMethodController::confirmComposition(const String& text)
+bool InputMethodController::confirmComposition(const String& text)
{
- finishComposition(text, ConfirmComposition);
+ return finishComposition(text, ConfirmComposition);
+}
+
+bool InputMethodController::confirmCompositionOrInsertText(const String& text, ConfirmCompositionBehavior confirmBehavior)
+{
+ if (!hasComposition()) {
+ if (!text.length())
+ return false;
+ editor().insertText(text, 0);
+ return true;
+ }
+
+ if (text.length()) {
+ confirmComposition(text);
+ return true;
+ }
+
+ if (confirmBehavior != KeepSelection)
+ return confirmComposition();
+
+ SelectionOffsetsScope selectionOffsetsScope(this);
+ return confirmComposition();
}
void InputMethodController::confirmCompositionAndResetState()
@@ -140,25 +144,12 @@ void InputMethodController::confirmCompositionAndResetState()
if (!hasComposition())
return;
- // We should verify the parent node of this IME composition node are
- // editable because JavaScript may delete a parent node of the composition
- // node. In this case, WebKit crashes while deleting texts from the parent
- // node, which doesn't exist any longer.
- RefPtr<Range> range = compositionRange();
- if (range) {
- Node* node = range->startContainer();
- if (!node || !node->isContentEditable())
- return;
- }
-
- // EditorClient::willSetInputMethodState() resets input method and the composition string is committed.
- editorClient().willSetInputMethodState();
+ // ChromeClient::willSetInputMethodState() resets input method and the composition string is committed.
+ m_frame.chromeClient().willSetInputMethodState();
}
void InputMethodController::cancelComposition()
{
- if (!m_compositionNode)
- return;
finishComposition(emptyString(), CancelComposition);
}
@@ -168,8 +159,8 @@ void InputMethodController::cancelCompositionIfSelectionIsInvalid()
return;
// Check if selection start and selection end are valid.
- Position start = m_frame->selection().start();
- Position end = m_frame->selection().end();
+ Position start = m_frame.selection().start();
+ Position end = m_frame.selection().end();
if (start.containerNode() == m_compositionNode
&& end.containerNode() == m_compositionNode
&& static_cast<unsigned>(start.computeOffsetInContainerNode()) >= m_compositionStart
@@ -177,13 +168,15 @@ void InputMethodController::cancelCompositionIfSelectionIsInvalid()
return;
cancelComposition();
- editorClient().didCancelCompositionOnSelectionChange();
+ m_frame.chromeClient().didCancelCompositionOnSelectionChange();
}
-void InputMethodController::finishComposition(const String& text, FinishCompositionMode mode)
+bool InputMethodController::finishComposition(const String& text, FinishCompositionMode mode)
{
+ if (!hasComposition())
+ return false;
+
ASSERT(mode == ConfirmComposition || mode == CancelComposition);
- UserTypingGestureIndicator typingGestureIndicator(m_frame);
Editor::RevealSelectionScope revealSelectionScope(&editor());
@@ -192,22 +185,22 @@ void InputMethodController::finishComposition(const String& text, FinishComposit
else
selectComposition();
- if (m_frame->selection().isNone())
- return;
+ if (m_frame.selection().isNone())
+ return false;
// Dispatch a compositionend event to the focused node.
// We should send this event before sending a TextEvent as written in Section 6.2.2 and 6.2.3 of
// the DOM Event specification.
- if (Element* target = m_frame->document()->focusedElement()) {
- RefPtr<CompositionEvent> event = CompositionEvent::create(eventNames().compositionendEvent, m_frame->domWindow(), text);
+ if (Element* target = m_frame.document()->focusedElement()) {
+ RefPtr<CompositionEvent> event = CompositionEvent::create(EventTypeNames::compositionend, m_frame.domWindow(), text);
target->dispatchEvent(event, IGNORE_EXCEPTION);
}
// If text is empty, then delete the old composition here. If text is non-empty, InsertTextCommand::input
// will delete the old composition with an optimized replace operation.
if (text.isEmpty() && mode != CancelComposition) {
- ASSERT(m_frame->document());
- TypingCommand::deleteSelection(*m_frame->document(), 0);
+ ASSERT(m_frame.document());
+ TypingCommand::deleteSelection(*m_frame.document(), 0);
}
m_compositionNode = 0;
@@ -217,27 +210,27 @@ void InputMethodController::finishComposition(const String& text, FinishComposit
if (mode == CancelComposition) {
// An open typing command that disagrees about current selection would cause issues with typing later on.
- TypingCommand::closeTyping(m_frame);
+ TypingCommand::closeTyping(&m_frame);
}
+
+ return true;
}
void InputMethodController::setComposition(const String& text, const Vector<CompositionUnderline>& underlines, unsigned selectionStart, unsigned selectionEnd)
{
- UserTypingGestureIndicator typingGestureIndicator(m_frame);
-
Editor::RevealSelectionScope revealSelectionScope(&editor());
// Updates styles before setting selection for composition to prevent
// inserting the previous composition text into text nodes oddly.
// See https://bugs.webkit.org/show_bug.cgi?id=46868
- m_frame->document()->updateStyleIfNeeded();
+ m_frame.document()->updateStyleIfNeeded();
selectComposition();
- if (m_frame->selection().isNone())
+ if (m_frame.selection().isNone())
return;
- if (Element* target = m_frame->document()->focusedElement()) {
+ if (Element* target = m_frame.document()->focusedElement()) {
// Dispatch an appropriate composition event to the focused node.
// We check the composition status and choose an appropriate composition event since this
// function is used for three purposes:
@@ -254,18 +247,18 @@ void InputMethodController::setComposition(const String& text, const Vector<Comp
// Send a compositionend event when function deletes the existing composition node, i.e.
// m_compositionNode != 0 && test.isEmpty().
RefPtr<CompositionEvent> event;
- if (!m_compositionNode) {
+ if (!hasComposition()) {
// We should send a compositionstart event only when the given text is not empty because this
// function doesn't create a composition node when the text is empty.
if (!text.isEmpty()) {
- target->dispatchEvent(CompositionEvent::create(eventNames().compositionstartEvent, m_frame->domWindow(), m_frame->selectedText()));
- event = CompositionEvent::create(eventNames().compositionupdateEvent, m_frame->domWindow(), text);
+ target->dispatchEvent(CompositionEvent::create(EventTypeNames::compositionstart, m_frame.domWindow(), m_frame.selectedText()));
+ event = CompositionEvent::create(EventTypeNames::compositionupdate, m_frame.domWindow(), text);
}
} else {
if (!text.isEmpty())
- event = CompositionEvent::create(eventNames().compositionupdateEvent, m_frame->domWindow(), text);
+ event = CompositionEvent::create(EventTypeNames::compositionupdate, m_frame.domWindow(), text);
else
- event = CompositionEvent::create(eventNames().compositionendEvent, m_frame->domWindow(), text);
+ event = CompositionEvent::create(EventTypeNames::compositionend, m_frame.domWindow(), text);
}
if (event.get())
target->dispatchEvent(event, IGNORE_EXCEPTION);
@@ -274,20 +267,20 @@ void InputMethodController::setComposition(const String& text, const Vector<Comp
// If text is empty, then delete the old composition here. If text is non-empty, InsertTextCommand::input
// will delete the old composition with an optimized replace operation.
if (text.isEmpty()) {
- ASSERT(m_frame->document());
- TypingCommand::deleteSelection(*m_frame->document(), TypingCommand::PreventSpellChecking);
+ ASSERT(m_frame.document());
+ TypingCommand::deleteSelection(*m_frame.document(), TypingCommand::PreventSpellChecking);
}
m_compositionNode = 0;
m_customCompositionUnderlines.clear();
if (!text.isEmpty()) {
- ASSERT(m_frame->document());
- TypingCommand::insertText(*m_frame->document(), text, TypingCommand::SelectInsertedText | TypingCommand::PreventSpellChecking, TypingCommand::TextCompositionUpdate);
+ ASSERT(m_frame.document());
+ TypingCommand::insertText(*m_frame.document(), text, TypingCommand::SelectInsertedText | TypingCommand::PreventSpellChecking, TypingCommand::TextCompositionUpdate);
// Find out what node has the composition now.
- Position base = m_frame->selection().base().downstream();
- Position extent = m_frame->selection().extent();
+ Position base = m_frame.selection().base().downstream();
+ Position extent = m_frame.selection().extent();
Node* baseNode = base.deprecatedNode();
unsigned baseOffset = base.deprecatedEditingOffset();
Node* extentNode = extent.deprecatedNode();
@@ -309,15 +302,15 @@ void InputMethodController::setComposition(const String& text, const Vector<Comp
unsigned start = std::min(baseOffset + selectionStart, extentOffset);
unsigned end = std::min(std::max(start, baseOffset + selectionEnd), extentOffset);
RefPtr<Range> selectedRange = Range::create(baseNode->document(), baseNode, start, baseNode, end);
- m_frame->selection().setSelectedRange(selectedRange.get(), DOWNSTREAM, false);
+ m_frame.selection().setSelectedRange(selectedRange.get(), DOWNSTREAM, false);
}
}
}
void InputMethodController::setCompositionFromExistingText(const Vector<CompositionUnderline>& underlines, unsigned compositionStart, unsigned compositionEnd)
{
- Node* editable = m_frame->selection().rootEditableElement();
- Position base = m_frame->selection().base().downstream();
+ Node* editable = m_frame.selection().rootEditableElement();
+ Position base = m_frame.selection().base().downstream();
Node* baseNode = base.anchorNode();
if (editable->firstChild() == baseNode && editable->lastChild() == baseNode && baseNode->isTextNode()) {
m_compositionNode = 0;
@@ -325,7 +318,7 @@ void InputMethodController::setCompositionFromExistingText(const Vector<Composit
if (base.anchorType() != Position::PositionIsOffsetInAnchor)
return;
- if (!baseNode || baseNode != m_frame->selection().extent().anchorNode())
+ if (!baseNode || baseNode != m_frame.selection().extent().anchorNode())
return;
m_compositionNode = toText(baseNode);
@@ -344,13 +337,13 @@ void InputMethodController::setCompositionFromExistingText(const Vector<Composit
Editor::RevealSelectionScope revealSelectionScope(&editor());
SelectionOffsetsScope selectionOffsetsScope(this);
- setSelectionOffsets(PlainTextOffsets(compositionStart, compositionEnd));
- setComposition(m_frame->selectedText(), underlines, 0, 0);
+ setSelectionOffsets(PlainTextRange(compositionStart, compositionEnd));
+ setComposition(m_frame.selectedText(), underlines, 0, 0);
}
PassRefPtr<Range> InputMethodController::compositionRange() const
{
- if (!m_compositionNode)
+ if (!hasComposition())
return 0;
unsigned length = m_compositionNode->length();
unsigned start = std::min(m_compositionStart, length);
@@ -360,25 +353,47 @@ PassRefPtr<Range> InputMethodController::compositionRange() const
return Range::create(m_compositionNode->document(), m_compositionNode.get(), start, m_compositionNode.get(), end);
}
-PlainTextOffsets InputMethodController::getSelectionOffsets() const
+PlainTextRange InputMethodController::getSelectionOffsets() const
{
- RefPtr<Range> range = m_frame->selection().selection().firstRange();
+ RefPtr<Range> range = m_frame.selection().selection().firstRange();
if (!range)
- return PlainTextOffsets();
- size_t location;
- size_t length;
- // FIXME: We should change TextIterator::getLocationAndLengthFromRange() returns PlainTextOffsets.
- if (TextIterator::getLocationAndLengthFromRange(m_frame->selection().rootEditableElementOrTreeScopeRootNode(), range.get(), location, length))
- return PlainTextOffsets(location, location + length);
- return PlainTextOffsets();
+ return PlainTextRange();
+ Node* editable = m_frame.selection().rootEditableElementOrTreeScopeRootNode();
+ ASSERT(editable);
+ return PlainTextRange::create(*editable, *range.get());
}
-bool InputMethodController::setSelectionOffsets(const PlainTextOffsets& selectionOffsets)
+bool InputMethodController::setSelectionOffsets(const PlainTextRange& selectionOffsets)
{
if (selectionOffsets.isNull())
return false;
- // FIXME: We should move Editor::setSelectionOffsets() into InputMethodController class.
- return editor().setSelectionOffsets(selectionOffsets.start(), selectionOffsets.end());
+ Element* rootEditableElement = m_frame.selection().rootEditableElement();
+ if (!rootEditableElement)
+ return false;
+
+ RefPtr<Range> range = selectionOffsets.createRange(*rootEditableElement);
+ if (!range)
+ return false;
+
+ return m_frame.selection().setSelectedRange(range.get(), VP_DEFAULT_AFFINITY, true);
+}
+
+bool InputMethodController::setEditableSelectionOffsets(const PlainTextRange& selectionOffsets)
+{
+ if (!editor().canEdit())
+ return false;
+ return setSelectionOffsets(selectionOffsets);
+}
+
+void InputMethodController::extendSelectionAndDelete(int before, int after)
+{
+ if (!editor().canEdit())
+ return;
+ PlainTextRange selectionOffsets(getSelectionOffsets());
+ if (selectionOffsets.isNull())
+ return;
+ setSelectionOffsets(PlainTextRange(std::max(static_cast<int>(selectionOffsets.start()) - before, 0), selectionOffsets.end() + after));
+ TypingCommand::deleteSelection(*m_frame.document());
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/editing/InputMethodController.h b/chromium/third_party/WebKit/Source/core/editing/InputMethodController.h
index 5fd3dd283a3..843cd8a8d07 100644
--- a/chromium/third_party/WebKit/Source/core/editing/InputMethodController.h
+++ b/chromium/third_party/WebKit/Source/core/editing/InputMethodController.h
@@ -27,6 +27,7 @@
#define InputMethodController_h
#include "core/editing/CompositionUnderline.h"
+#include "core/editing/PlainTextRange.h"
#include "wtf/Vector.h"
namespace WebCore {
@@ -37,34 +38,30 @@ class Frame;
class Range;
class Text;
-// FIXME: We should move PlainTextOffsets to own file for using InputMethodController
-// and TextIterator and unify PlainTextRange defined in AccessibilityObject.h.
-class PlainTextOffsets {
-public:
- PlainTextOffsets();
- PlainTextOffsets(int start, int length);
- size_t end() const { return m_end; }
- size_t start() const { return m_start; }
- bool isNull() const { return m_start == kNotFound; }
-private:
- size_t m_start;
- size_t m_end;
-};
-
class InputMethodController {
+ WTF_MAKE_NONCOPYABLE(InputMethodController);
public:
- static PassOwnPtr<InputMethodController> create(Frame*);
+ enum ConfirmCompositionBehavior {
+ DoNotKeepSelection,
+ KeepSelection,
+ };
+
+ static PassOwnPtr<InputMethodController> create(Frame&);
~InputMethodController();
// international text input composition
- bool hasComposition() const { return m_compositionNode; }
+ bool hasComposition() const;
void setComposition(const String&, const Vector<CompositionUnderline>&, unsigned selectionStart, unsigned selectionEnd);
void setCompositionFromExistingText(const Vector<CompositionUnderline>&, unsigned compositionStart, unsigned compositionEnd);
- // Inserts the text that is being composed as a regular text.
- // This method does nothing if composition node is not present.
- void confirmComposition();
- // Inserts the given text string in the place of the existing composition, or replaces the selection if composition is not present.
- void confirmComposition(const String& text);
+ // Inserts the text that is being composed as a regular text and returns true
+ // if composition exists.
+ bool confirmComposition();
+ // Inserts the given text string in the place of the existing composition
+ // and returns true.
+ bool confirmComposition(const String& text);
+ // Inserts the text that is being composed or specified non-empty text and
+ // returns true.
+ bool confirmCompositionOrInsertText(const String& text, ConfirmCompositionBehavior);
void confirmCompositionAndResetState();
// Deletes the existing composition text.
void cancelComposition();
@@ -80,6 +77,11 @@ public:
void clear();
+ PlainTextRange getSelectionOffsets() const;
+ // Returns true if setting selection to specified offsets, otherwise false.
+ bool setEditableSelectionOffsets(const PlainTextRange&);
+ void extendSelectionAndDelete(int before, int after);
+
private:
class SelectionOffsetsScope {
WTF_MAKE_NONCOPYABLE(SelectionOffsetsScope);
@@ -88,29 +90,27 @@ private:
~SelectionOffsetsScope();
private:
InputMethodController* m_inputMethodController;
- PlainTextOffsets m_offsets;
+ const PlainTextRange m_offsets;
};
friend class SelectionOffsetsScope;
- Frame* m_frame;
+ Frame& m_frame;
RefPtr<Text> m_compositionNode;
- // FIXME: We should use PlainTextOffsets m_compositionRange instead of
- // m_compositionStart/m_compositionEnd.
+ // We don't use PlainTextRange which is immutable, for composition range.
unsigned m_compositionStart;
unsigned m_compositionEnd;
// startOffset and endOffset of CompositionUnderline are based on
// m_compositionNode.
Vector<CompositionUnderline> m_customCompositionUnderlines;
- explicit InputMethodController(Frame*);
+ explicit InputMethodController(Frame&);
Editor& editor() const;
- EditorClient& editorClient() const;
bool insertTextForConfirmedComposition(const String& text);
void selectComposition() const;
enum FinishCompositionMode { ConfirmComposition, CancelComposition };
- void finishComposition(const String&, FinishCompositionMode);
- PlainTextOffsets getSelectionOffsets() const;
- bool setSelectionOffsets(const PlainTextOffsets&);
+ // Returns true if composition exists.
+ bool finishComposition(const String&, FinishCompositionMode);
+ bool setSelectionOffsets(const PlainTextRange&);
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/editing/InsertIntoTextNodeCommand.cpp b/chromium/third_party/WebKit/Source/core/editing/InsertIntoTextNodeCommand.cpp
index 906274bd87d..43790d9acbd 100644
--- a/chromium/third_party/WebKit/Source/core/editing/InsertIntoTextNodeCommand.cpp
+++ b/chromium/third_party/WebKit/Source/core/editing/InsertIntoTextNodeCommand.cpp
@@ -29,7 +29,7 @@
#include "bindings/v8/ExceptionStatePlaceholder.h"
#include "core/dom/Document.h"
#include "core/dom/Text.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
#include "core/rendering/RenderText.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/editing/InsertLineBreakCommand.cpp b/chromium/third_party/WebKit/Source/core/editing/InsertLineBreakCommand.cpp
index 659c42dc20b..cb4ad37a78a 100644
--- a/chromium/third_party/WebKit/Source/core/editing/InsertLineBreakCommand.cpp
+++ b/chromium/third_party/WebKit/Source/core/editing/InsertLineBreakCommand.cpp
@@ -36,7 +36,7 @@
#include "core/editing/htmlediting.h"
#include "core/html/HTMLElement.h"
#include "core/html/HTMLTableElement.h"
-#include "core/page/Frame.h"
+#include "core/frame/Frame.h"
#include "core/rendering/RenderObject.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/editing/InsertListCommand.cpp b/chromium/third_party/WebKit/Source/core/editing/InsertListCommand.cpp
index 9a702580ad2..aff29397f9c 100644
--- a/chromium/third_party/WebKit/Source/core/editing/InsertListCommand.cpp
+++ b/chromium/third_party/WebKit/Source/core/editing/InsertListCommand.cpp
@@ -134,6 +134,8 @@ void InsertListCommand::doApply()
VisiblePosition startOfLastParagraph = startOfParagraph(endOfSelection, CanSkipOverEditingBoundary);
if (startOfParagraph(startOfSelection, CanSkipOverEditingBoundary) != startOfLastParagraph) {
+ RefPtr<ContainerNode> scope;
+ int indexForEndOfSelection = indexForVisiblePosition(endOfSelection, scope);
bool forceCreateList = !selectionHasListOfType(selection, listTag);
RefPtr<Range> currentSelection = endingSelection().firstRange();
@@ -153,8 +155,6 @@ void InsertListCommand::doApply()
// FIXME: This is an inefficient way to keep selection alive because indexForVisiblePosition walks from
// the beginning of the document to the endOfSelection everytime this code is executed.
// But not using index is hard because there are so many ways we can lose selection inside doApplyForSingleParagraph.
- RefPtr<ContainerNode> scope;
- int indexForEndOfSelection = indexForVisiblePosition(endOfSelection, scope);
doApplyForSingleParagraph(forceCreateList, listTag, currentSelection.get());
if (endOfSelection.isNull() || endOfSelection.isOrphan() || startOfLastParagraph.isNull() || startOfLastParagraph.isOrphan()) {
endOfSelection = visiblePositionForIndex(indexForEndOfSelection, scope.get());
@@ -178,7 +178,11 @@ void InsertListCommand::doApply()
setEndingSelection(endOfSelection);
doApplyForSingleParagraph(forceCreateList, listTag, currentSelection.get());
// Fetch the end of the selection, for the reason mentioned above.
- endOfSelection = endingSelection().visibleEnd();
+ if (endOfSelection.isNull() || endOfSelection.isOrphan()) {
+ endOfSelection = visiblePositionForIndex(indexForEndOfSelection, scope.get());
+ if (endOfSelection.isNull())
+ return;
+ }
setEndingSelection(VisibleSelection(startOfSelection, endOfSelection, endingSelection().isDirectional()));
return;
}
diff --git a/chromium/third_party/WebKit/Source/core/editing/InsertNodeBeforeCommand.cpp b/chromium/third_party/WebKit/Source/core/editing/InsertNodeBeforeCommand.cpp
index 16ff925d004..862d541033e 100644
--- a/chromium/third_party/WebKit/Source/core/editing/InsertNodeBeforeCommand.cpp
+++ b/chromium/third_party/WebKit/Source/core/editing/InsertNodeBeforeCommand.cpp
@@ -43,7 +43,7 @@ InsertNodeBeforeCommand::InsertNodeBeforeCommand(PassRefPtr<Node> insertChild, P
ASSERT(m_refChild);
ASSERT(m_refChild->parentNode());
- ASSERT(m_refChild->parentNode()->rendererIsEditable() || !m_refChild->parentNode()->attached());
+ ASSERT(m_refChild->parentNode()->rendererIsEditable() || !m_refChild->parentNode()->inActiveDocument());
}
void InsertNodeBeforeCommand::doApply()
diff --git a/chromium/third_party/WebKit/Source/core/editing/InsertParagraphSeparatorCommand.cpp b/chromium/third_party/WebKit/Source/core/editing/InsertParagraphSeparatorCommand.cpp
index 5c129488e43..9ad4234a4bb 100644
--- a/chromium/third_party/WebKit/Source/core/editing/InsertParagraphSeparatorCommand.cpp
+++ b/chromium/third_party/WebKit/Source/core/editing/InsertParagraphSeparatorCommand.cpp
@@ -172,7 +172,7 @@ void InsertParagraphSeparatorCommand::doApply()
|| isTableCell(startBlock.get())
|| startBlock->hasTagName(formTag)
// FIXME: If the node is hidden, we don't have a canonical position so we will do the wrong thing for tables and <hr>. https://bugs.webkit.org/show_bug.cgi?id=40342
- || (!canonicalPos.isNull() && canonicalPos.deprecatedNode()->renderer() && canonicalPos.deprecatedNode()->renderer()->isTable())
+ || (!canonicalPos.isNull() && isRenderedTable(canonicalPos.deprecatedNode()))
|| (!canonicalPos.isNull() && canonicalPos.deprecatedNode()->hasTagName(hrTag))) {
applyCommandToComposite(InsertLineBreakCommand::create(document()));
return;
@@ -395,7 +395,7 @@ void InsertParagraphSeparatorCommand::doApply()
else {
Node* splitTo = insertionPosition.containerNode();
if (splitTo->isTextNode() && insertionPosition.offsetInContainerNode() >= caretMaxOffset(splitTo))
- splitTo = NodeTraversal::next(splitTo, startBlock.get());
+ splitTo = NodeTraversal::next(*splitTo, startBlock.get());
ASSERT(splitTo);
splitTreeToNode(splitTo, startBlock.get());
diff --git a/chromium/third_party/WebKit/Source/core/editing/InsertTextCommand.cpp b/chromium/third_party/WebKit/Source/core/editing/InsertTextCommand.cpp
index 639b5189d3b..8a489403ed0 100644
--- a/chromium/third_party/WebKit/Source/core/editing/InsertTextCommand.cpp
+++ b/chromium/third_party/WebKit/Source/core/editing/InsertTextCommand.cpp
@@ -32,7 +32,7 @@
#include "core/editing/Editor.h"
#include "core/editing/VisibleUnits.h"
#include "core/editing/htmlediting.h"
-#include "core/page/Frame.h"
+#include "core/frame/Frame.h"
namespace WebCore {
@@ -174,7 +174,7 @@ void InsertTextCommand::doApply()
// It is possible for the node that contains startPosition to contain only unrendered whitespace,
// and so deleteInsignificantText could remove it. Save the position before the node in case that happens.
Position positionBeforeStartNode(positionInParentBeforeNode(startPosition.containerNode()));
- deleteInsignificantText(startPosition.upstream(), startPosition.downstream());
+ deleteInsignificantText(startPosition, startPosition.downstream());
if (!startPosition.inDocument())
startPosition = positionBeforeStartNode;
if (!startPosition.isCandidate())
diff --git a/chromium/third_party/WebKit/Source/core/editing/MarkupAccumulator.cpp b/chromium/third_party/WebKit/Source/core/editing/MarkupAccumulator.cpp
index 1ccbc83f769..9d5b975badc 100644
--- a/chromium/third_party/WebKit/Source/core/editing/MarkupAccumulator.cpp
+++ b/chromium/third_party/WebKit/Source/core/editing/MarkupAccumulator.cpp
@@ -39,7 +39,7 @@
#include "core/editing/Editor.h"
#include "core/html/HTMLElement.h"
#include "core/html/HTMLTemplateElement.h"
-#include "weborigin/KURL.h"
+#include "platform/weborigin/KURL.h"
#include "wtf/unicode/CharacterNames.h"
namespace WebCore {
@@ -303,14 +303,16 @@ void MarkupAccumulator::appendNamespace(StringBuilder& result, const AtomicStrin
EntityMask MarkupAccumulator::entityMaskForText(Text* text) const
{
+ if (!text->document().isHTMLDocument())
+ return EntityMaskInPCDATA;
+
const QualifiedName* parentName = 0;
if (text->parentElement())
parentName = &(text->parentElement())->tagQName();
if (parentName && (*parentName == scriptTag || *parentName == styleTag || *parentName == xmpTag))
return EntityMaskInCDATA;
-
- return text->document().isHTMLDocument() ? EntityMaskInHTMLPCDATA : EntityMaskInPCDATA;
+ return EntityMaskInHTMLPCDATA;
}
void MarkupAccumulator::appendText(StringBuilder& result, Text* text)
diff --git a/chromium/third_party/WebKit/Source/core/editing/MergeIdenticalElementsCommand.cpp b/chromium/third_party/WebKit/Source/core/editing/MergeIdenticalElementsCommand.cpp
index 2ae2dbba89a..e512319ee52 100644
--- a/chromium/third_party/WebKit/Source/core/editing/MergeIdenticalElementsCommand.cpp
+++ b/chromium/third_party/WebKit/Source/core/editing/MergeIdenticalElementsCommand.cpp
@@ -71,10 +71,10 @@ void MergeIdenticalElementsCommand::doUnapply()
if (!parent || !parent->rendererIsEditable())
return;
- TrackExceptionState es;
+ TrackExceptionState exceptionState;
- parent->insertBefore(m_element1.get(), m_element2.get(), es);
- if (es.hadException())
+ parent->insertBefore(m_element1.get(), m_element2.get(), exceptionState);
+ if (exceptionState.hadException())
return;
Vector<RefPtr<Node> > children;
@@ -83,7 +83,7 @@ void MergeIdenticalElementsCommand::doUnapply()
size_t size = children.size();
for (size_t i = 0; i < size; ++i)
- m_element1->appendChild(children[i].release(), es);
+ m_element1->appendChild(children[i].release(), exceptionState);
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/editing/ModifySelectionListLevel.cpp b/chromium/third_party/WebKit/Source/core/editing/ModifySelectionListLevel.cpp
index 671abea959f..e438eb25b4f 100644
--- a/chromium/third_party/WebKit/Source/core/editing/ModifySelectionListLevel.cpp
+++ b/chromium/third_party/WebKit/Source/core/editing/ModifySelectionListLevel.cpp
@@ -30,7 +30,7 @@
#include "core/editing/FrameSelection.h"
#include "core/editing/htmlediting.h"
#include "core/html/HTMLElement.h"
-#include "core/page/Frame.h"
+#include "core/frame/Frame.h"
#include "core/rendering/RenderObject.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/editing/PlainTextRange.cpp b/chromium/third_party/WebKit/Source/core/editing/PlainTextRange.cpp
new file mode 100644
index 00000000000..82f321566d7
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/editing/PlainTextRange.cpp
@@ -0,0 +1,185 @@
+/*
+ * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2012 Apple Inc. All rights reserved.
+ * Copyright (C) 2005 Alexey Proskuryakov.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/editing/PlainTextRange.h"
+
+#include "core/dom/ContainerNode.h"
+#include "core/dom/Document.h"
+#include "core/dom/Range.h"
+#include "core/editing/TextIterator.h"
+#include "core/editing/VisiblePosition.h"
+
+namespace WebCore {
+
+PlainTextRange::PlainTextRange()
+ : m_start(kNotFound)
+ , m_end(kNotFound)
+{
+}
+
+PlainTextRange::PlainTextRange(int location)
+ : m_start(location)
+ , m_end(location)
+{
+ ASSERT(location >= 0);
+}
+
+PlainTextRange::PlainTextRange(int start, int end)
+ : m_start(start)
+ , m_end(end)
+{
+ ASSERT(start >= 0);
+ ASSERT(end >= 0);
+ ASSERT(start <= end);
+}
+
+PassRefPtr<Range> PlainTextRange::createRange(const ContainerNode& scope) const
+{
+ return createRangeFor(scope, ForGeneric);
+}
+
+PassRefPtr<Range> PlainTextRange::createRangeForSelection(const ContainerNode& scope) const
+{
+ return createRangeFor(scope, ForSelection);
+}
+
+PassRefPtr<Range> PlainTextRange::createRangeFor(const ContainerNode& scope, GetRangeFor getRangeFor) const
+{
+ ASSERT(isNotNull());
+
+ RefPtr<Range> resultRange = scope.document().createRange();
+
+ size_t docTextPosition = 0;
+ bool startRangeFound = false;
+
+ RefPtr<Range> textRunRange;
+
+ TextIterator it(rangeOfContents(const_cast<ContainerNode*>(&scope)).get(), getRangeFor == ForSelection ? TextIteratorEmitsCharactersBetweenAllVisiblePositions : TextIteratorDefaultBehavior);
+
+ // FIXME: the atEnd() check shouldn't be necessary, workaround for <http://bugs.webkit.org/show_bug.cgi?id=6289>.
+ if (!start() && !length() && it.atEnd()) {
+ textRunRange = it.range();
+
+ resultRange->setStart(textRunRange->startContainer(), 0, ASSERT_NO_EXCEPTION);
+ resultRange->setEnd(textRunRange->startContainer(), 0, ASSERT_NO_EXCEPTION);
+
+ return resultRange.release();
+ }
+
+ for (; !it.atEnd(); it.advance()) {
+ int len = it.length();
+ textRunRange = it.range();
+
+ bool foundStart = start() >= docTextPosition && start() <= docTextPosition + len;
+ bool foundEnd = end() >= docTextPosition && end() <= docTextPosition + len;
+
+ // Fix textRunRange->endPosition(), but only if foundStart || foundEnd, because it is only
+ // in those cases that textRunRange is used.
+ if (foundEnd) {
+ // FIXME: This is a workaround for the fact that the end of a run is often at the wrong
+ // position for emitted '\n's.
+ if (len == 1 && it.characterAt(0) == '\n') {
+ scope.document().updateLayoutIgnorePendingStylesheets();
+ it.advance();
+ if (!it.atEnd()) {
+ RefPtr<Range> range = it.range();
+ textRunRange->setEnd(range->startContainer(), range->startOffset(), ASSERT_NO_EXCEPTION);
+ } else {
+ Position runStart = textRunRange->startPosition();
+ Position runEnd = VisiblePosition(runStart).next().deepEquivalent();
+ if (runEnd.isNotNull())
+ textRunRange->setEnd(runEnd.containerNode(), runEnd.computeOffsetInContainerNode(), ASSERT_NO_EXCEPTION);
+ }
+ }
+ }
+
+ if (foundStart) {
+ startRangeFound = true;
+ if (textRunRange->startContainer()->isTextNode()) {
+ int offset = start() - docTextPosition;
+ resultRange->setStart(textRunRange->startContainer(), offset + textRunRange->startOffset(), IGNORE_EXCEPTION);
+ } else {
+ if (start() == docTextPosition)
+ resultRange->setStart(textRunRange->startContainer(), textRunRange->startOffset(), IGNORE_EXCEPTION);
+ else
+ resultRange->setStart(textRunRange->endContainer(), textRunRange->endOffset(), IGNORE_EXCEPTION);
+ }
+ }
+
+ if (foundEnd) {
+ if (textRunRange->startContainer()->isTextNode()) {
+ int offset = end() - docTextPosition;
+ resultRange->setEnd(textRunRange->startContainer(), offset + textRunRange->startOffset(), IGNORE_EXCEPTION);
+ } else {
+ if (end() == docTextPosition)
+ resultRange->setEnd(textRunRange->startContainer(), textRunRange->startOffset(), IGNORE_EXCEPTION);
+ else
+ resultRange->setEnd(textRunRange->endContainer(), textRunRange->endOffset(), IGNORE_EXCEPTION);
+ }
+ docTextPosition += len;
+ break;
+ }
+ docTextPosition += len;
+ }
+
+ if (!startRangeFound)
+ return 0;
+
+ if (length() && end() > docTextPosition) { // end() is out of bounds
+ resultRange->setEnd(textRunRange->endContainer(), textRunRange->endOffset(), IGNORE_EXCEPTION);
+ }
+
+ return resultRange.release();
+}
+
+PlainTextRange PlainTextRange::create(const Node& scope, const Range& range)
+{
+ if (!range.startContainer())
+ return PlainTextRange();
+
+ // The critical assumption is that this only gets called with ranges that
+ // concentrate on a given area containing the selection root. This is done
+ // because of text fields and textareas. The DOM for those is not
+ // directly in the document DOM, so ensure that the range does not cross a
+ // boundary of one of those.
+ if (range.startContainer() != &scope && !range.startContainer()->isDescendantOf(&scope))
+ return PlainTextRange();
+ if (range.endContainer() != scope && !range.endContainer()->isDescendantOf(&scope))
+ return PlainTextRange();
+
+ RefPtr<Range> testRange = Range::create(scope.document(), const_cast<Node*>(&scope), 0, range.startContainer(), range.startOffset());
+ ASSERT(testRange->startContainer() == &scope);
+ size_t start = TextIterator::rangeLength(testRange.get());
+
+ testRange->setEnd(range.endContainer(), range.endOffset(), IGNORE_EXCEPTION);
+ ASSERT(testRange->startContainer() == &scope);
+ size_t end = TextIterator::rangeLength(testRange.get());
+
+ return PlainTextRange(start, end);
+}
+
+}
diff --git a/chromium/third_party/WebKit/Source/core/editing/PlainTextRange.h b/chromium/third_party/WebKit/Source/core/editing/PlainTextRange.h
new file mode 100644
index 00000000000..faf200a334a
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/editing/PlainTextRange.h
@@ -0,0 +1,68 @@
+/*
+ * Copyright (C) 2006, 2007, 2008 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef PlainTextRange_h
+#define PlainTextRange_h
+
+#include "wtf/NotFound.h"
+#include "wtf/PassRefPtr.h"
+
+namespace WebCore {
+
+class ContainerNode;
+class Node;
+class Range;
+
+class PlainTextRange {
+public:
+ PlainTextRange();
+ PlainTextRange(const PlainTextRange&);
+ explicit PlainTextRange(int location);
+ PlainTextRange(int start, int end);
+
+ size_t end() const { ASSERT(!isNull()); return m_end; }
+ size_t start() const { ASSERT(!isNull()); return m_start; }
+ bool isNull() const { return m_start == kNotFound; }
+ bool isNotNull() const { return m_start != kNotFound; }
+ size_t length() const { ASSERT(!isNull()); return m_end - m_start; }
+
+ PassRefPtr<Range> createRange(const ContainerNode& scope) const;
+ PassRefPtr<Range> createRangeForSelection(const ContainerNode& scope) const;
+
+ static PlainTextRange create(const Node& scope, const Range&);
+
+private:
+ PlainTextRange& operator=(const PlainTextRange&) WTF_DELETED_FUNCTION;
+
+ enum GetRangeFor { ForGeneric, ForSelection };
+ PassRefPtr<Range> createRangeFor(const ContainerNode& scope, GetRangeFor) const;
+
+ const size_t m_start;
+ const size_t m_end;
+};
+
+} // namespace WebCore
+
+#endif // PlainTextRange_h
diff --git a/chromium/third_party/WebKit/Source/core/editing/RemoveFormatCommand.cpp b/chromium/third_party/WebKit/Source/core/editing/RemoveFormatCommand.cpp
index 48bff2b4e1e..d36a52790d6 100644
--- a/chromium/third_party/WebKit/Source/core/editing/RemoveFormatCommand.cpp
+++ b/chromium/third_party/WebKit/Source/core/editing/RemoveFormatCommand.cpp
@@ -34,7 +34,7 @@
#include "core/editing/ApplyStyleCommand.h"
#include "core/editing/EditingStyle.h"
#include "core/editing/FrameSelection.h"
-#include "core/page/Frame.h"
+#include "core/frame/Frame.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/editing/RemoveNodeCommand.cpp b/chromium/third_party/WebKit/Source/core/editing/RemoveNodeCommand.cpp
index 0640559a6dc..cffc8c0b8da 100644
--- a/chromium/third_party/WebKit/Source/core/editing/RemoveNodeCommand.cpp
+++ b/chromium/third_party/WebKit/Source/core/editing/RemoveNodeCommand.cpp
@@ -45,9 +45,9 @@ void RemoveNodeCommand::doApply()
{
ContainerNode* parent = m_node->parentNode();
if (!parent || (m_shouldAssumeContentIsAlwaysEditable == DoNotAssumeContentIsAlwaysEditable
- && !parent->isContentEditable(Node::UserSelectAllIsAlwaysNonEditable) && parent->attached()))
+ && !parent->isContentEditable(Node::UserSelectAllIsAlwaysNonEditable) && parent->inActiveDocument()))
return;
- ASSERT(parent->isContentEditable(Node::UserSelectAllIsAlwaysNonEditable) || !parent->attached());
+ ASSERT(parent->isContentEditable(Node::UserSelectAllIsAlwaysNonEditable) || !parent->inActiveDocument());
m_parent = parent;
m_refChild = m_node->nextSibling();
diff --git a/chromium/third_party/WebKit/Source/core/editing/RenderedPosition.cpp b/chromium/third_party/WebKit/Source/core/editing/RenderedPosition.cpp
index 46550733216..a3646533789 100644
--- a/chromium/third_party/WebKit/Source/core/editing/RenderedPosition.cpp
+++ b/chromium/third_party/WebKit/Source/core/editing/RenderedPosition.cpp
@@ -33,7 +33,6 @@
#include "core/dom/Position.h"
#include "core/editing/VisiblePosition.h"
-#include "core/rendering/InlineBox.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/editing/ReplaceNodeWithSpanCommand.cpp b/chromium/third_party/WebKit/Source/core/editing/ReplaceNodeWithSpanCommand.cpp
index 6274c07e343..477177d46ac 100644
--- a/chromium/third_party/WebKit/Source/core/editing/ReplaceNodeWithSpanCommand.cpp
+++ b/chromium/third_party/WebKit/Source/core/editing/ReplaceNodeWithSpanCommand.cpp
@@ -48,11 +48,11 @@ ReplaceNodeWithSpanCommand::ReplaceNodeWithSpanCommand(PassRefPtr<HTMLElement> e
ASSERT(m_elementToReplace);
}
-static void swapInNodePreservingAttributesAndChildren(HTMLElement* newNode, HTMLElement* nodeToReplace)
+static void swapInNodePreservingAttributesAndChildren(HTMLElement* newNode, HTMLElement& nodeToReplace)
{
- ASSERT(nodeToReplace->inDocument());
- RefPtr<ContainerNode> parentNode = nodeToReplace->parentNode();
- parentNode->insertBefore(newNode, nodeToReplace);
+ ASSERT(nodeToReplace.inDocument());
+ RefPtr<ContainerNode> parentNode = nodeToReplace.parentNode();
+ parentNode->insertBefore(newNode, &nodeToReplace);
NodeVector children;
getChildNodes(nodeToReplace, children);
@@ -60,9 +60,9 @@ static void swapInNodePreservingAttributesAndChildren(HTMLElement* newNode, HTML
newNode->appendChild(children[i]);
// FIXME: Fix this to send the proper MutationRecords when MutationObservers are present.
- newNode->cloneDataFromElement(*nodeToReplace);
+ newNode->cloneDataFromElement(nodeToReplace);
- parentNode->removeChild(nodeToReplace, ASSERT_NO_EXCEPTION);
+ parentNode->removeChild(&nodeToReplace, ASSERT_NO_EXCEPTION);
}
void ReplaceNodeWithSpanCommand::doApply()
@@ -71,14 +71,14 @@ void ReplaceNodeWithSpanCommand::doApply()
return;
if (!m_spanElement)
m_spanElement = createHTMLElement(m_elementToReplace->document(), spanTag);
- swapInNodePreservingAttributesAndChildren(m_spanElement.get(), m_elementToReplace.get());
+ swapInNodePreservingAttributesAndChildren(m_spanElement.get(), *m_elementToReplace);
}
void ReplaceNodeWithSpanCommand::doUnapply()
{
if (!m_spanElement->inDocument())
return;
- swapInNodePreservingAttributesAndChildren(m_elementToReplace.get(), m_spanElement.get());
+ swapInNodePreservingAttributesAndChildren(m_elementToReplace.get(), *m_spanElement);
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/editing/ReplaceSelectionCommand.cpp b/chromium/third_party/WebKit/Source/core/editing/ReplaceSelectionCommand.cpp
index e90fac944e3..16d13f62d11 100644
--- a/chromium/third_party/WebKit/Source/core/editing/ReplaceSelectionCommand.cpp
+++ b/chromium/third_party/WebKit/Source/core/editing/ReplaceSelectionCommand.cpp
@@ -32,12 +32,9 @@
#include "bindings/v8/ExceptionStatePlaceholder.h"
#include "core/css/CSSStyleDeclaration.h"
#include "core/css/StylePropertySet.h"
-#include "core/dom/BeforeTextInsertedEvent.h"
#include "core/dom/Document.h"
#include "core/dom/DocumentFragment.h"
#include "core/dom/Element.h"
-#include "core/dom/EventNames.h"
-#include "core/dom/NodeTraversal.h"
#include "core/dom/Text.h"
#include "core/editing/ApplyStyleCommand.h"
#include "core/editing/BreakBlockquoteCommand.h"
@@ -49,10 +46,12 @@
#include "core/editing/VisibleUnits.h"
#include "core/editing/htmlediting.h"
#include "core/editing/markup.h"
+#include "core/events/BeforeTextInsertedEvent.h"
+#include "core/events/ThreadLocalEventNames.h"
#include "core/html/HTMLElement.h"
#include "core/html/HTMLInputElement.h"
#include "core/html/HTMLTitleElement.h"
-#include "core/page/Frame.h"
+#include "core/frame/Frame.h"
#include "core/rendering/RenderObject.h"
#include "core/rendering/RenderText.h"
#include "wtf/StdLibExtras.h"
@@ -154,7 +153,7 @@ ReplacementFragment::ReplacementFragment(Document* document, DocumentFragment* f
Node* shadowAncestorNode = editableRoot->deprecatedShadowAncestorNode();
- if (!editableRoot->getAttributeEventListener(eventNames().webkitBeforeTextInsertedEvent) &&
+ if (!editableRoot->getAttributeEventListener(EventTypeNames::webkitBeforeTextInserted) &&
// FIXME: Remove these checks once textareas and textfields actually register an event handler.
!(shadowAncestorNode && shadowAncestorNode->renderer() && shadowAncestorNode->renderer()->isTextControl()) &&
editableRoot->rendererIsRichlyEditable()) {
@@ -272,7 +271,7 @@ void ReplacementFragment::removeUnrenderedNodes(Node* holder)
{
Vector<RefPtr<Node> > unrendered;
- for (Node* node = holder->firstChild(); node; node = NodeTraversal::next(node, holder))
+ for (Node* node = holder->firstChild(); node; node = NodeTraversal::next(*node, holder))
if (!isNodeRendered(node) && !isTableStructureNode(node))
unrendered.append(node);
@@ -313,51 +312,49 @@ void ReplacementFragment::removeInterchangeNodes(Node* container)
node = container->firstChild();
while (node) {
- RefPtr<Node> next = NodeTraversal::next(node);
+ RefPtr<Node> next = NodeTraversal::next(*node);
if (isInterchangeConvertedSpaceSpan(node)) {
- next = NodeTraversal::nextSkippingChildren(node);
+ next = NodeTraversal::nextSkippingChildren(*node);
removeNodePreservingChildren(node);
}
node = next.get();
}
}
-inline void ReplaceSelectionCommand::InsertedNodes::respondToNodeInsertion(Node* node)
+inline void ReplaceSelectionCommand::InsertedNodes::respondToNodeInsertion(Node& node)
{
- if (!node)
- return;
-
if (!m_firstNodeInserted)
- m_firstNodeInserted = node;
+ m_firstNodeInserted = &node;
- m_lastNodeInserted = node;
+ m_lastNodeInserted = &node;
}
-inline void ReplaceSelectionCommand::InsertedNodes::willRemoveNodePreservingChildren(Node* node)
+inline void ReplaceSelectionCommand::InsertedNodes::willRemoveNodePreservingChildren(Node& node)
{
if (m_firstNodeInserted == node)
m_firstNodeInserted = NodeTraversal::next(node);
if (m_lastNodeInserted == node)
- m_lastNodeInserted = node->lastChild() ? node->lastChild() : NodeTraversal::nextSkippingChildren(node);
+ m_lastNodeInserted = node.lastChild() ? node.lastChild() : NodeTraversal::nextSkippingChildren(node);
}
-inline void ReplaceSelectionCommand::InsertedNodes::willRemoveNode(Node* node)
+inline void ReplaceSelectionCommand::InsertedNodes::willRemoveNode(Node& node)
{
if (m_firstNodeInserted == node && m_lastNodeInserted == node) {
m_firstNodeInserted = 0;
m_lastNodeInserted = 0;
- } else if (m_firstNodeInserted == node)
- m_firstNodeInserted = NodeTraversal::nextSkippingChildren(m_firstNodeInserted.get());
- else if (m_lastNodeInserted == node)
- m_lastNodeInserted = NodeTraversal::previousSkippingChildren(m_lastNodeInserted.get());
+ } else if (m_firstNodeInserted == node) {
+ m_firstNodeInserted = NodeTraversal::nextSkippingChildren(*m_firstNodeInserted);
+ } else if (m_lastNodeInserted == node) {
+ m_lastNodeInserted = NodeTraversal::previousSkippingChildren(*m_lastNodeInserted);
+ }
}
-inline void ReplaceSelectionCommand::InsertedNodes::didReplaceNode(Node* node, Node* newNode)
+inline void ReplaceSelectionCommand::InsertedNodes::didReplaceNode(Node& node, Node& newNode)
{
if (m_firstNodeInserted == node)
- m_firstNodeInserted = newNode;
+ m_firstNodeInserted = &newNode;
if (m_lastNodeInserted == node)
- m_lastNodeInserted = newNode;
+ m_lastNodeInserted = &newNode;
}
ReplaceSelectionCommand::ReplaceSelectionCommand(Document& document, PassRefPtr<DocumentFragment> fragment, CommandOptions options, EditAction editAction)
@@ -471,11 +468,11 @@ void ReplaceSelectionCommand::removeRedundantStylesAndKeepStyleSpanInline(Insert
for (RefPtr<Node> node = insertedNodes.firstNodeInserted(); node && node != pastEndNode; node = next) {
// FIXME: <rdar://problem/5371536> Style rules that match pasted content can change it's appearance
- next = NodeTraversal::next(node.get());
+ next = NodeTraversal::next(*node);
if (!node->isStyledElement())
continue;
- Element* element = toElement(node.get());
+ Element* element = toElement(node);
const StylePropertySet* inlineStyle = element->inlineStyle();
RefPtr<EditingStyle> newInlineStyle = EditingStyle::create(inlineStyle);
@@ -483,12 +480,13 @@ void ReplaceSelectionCommand::removeRedundantStylesAndKeepStyleSpanInline(Insert
if (element->isHTMLElement()) {
Vector<QualifiedName> attributes;
HTMLElement* htmlElement = toHTMLElement(element);
+ ASSERT(htmlElement);
if (newInlineStyle->conflictsWithImplicitStyleOfElement(htmlElement)) {
// e.g. <b style="font-weight: normal;"> is converted to <span style="font-weight: normal;">
node = replaceElementWithSpanPreservingChildrenAndAttributes(htmlElement);
- element = toElement(node.get());
- insertedNodes.didReplaceNode(htmlElement, node.get());
+ element = toElement(node);
+ insertedNodes.didReplaceNode(*htmlElement, *node);
} else if (newInlineStyle->extractConflictingImplicitStyleOfAttributes(htmlElement, EditingStyle::PreserveWritingDirection, 0, attributes,
EditingStyle::DoNotExtractMatchingStyle)) {
// e.g. <font size="3" style="font-size: 20px;"> is converted to <font style="font-size: 20px;">
@@ -510,19 +508,20 @@ void ReplaceSelectionCommand::removeRedundantStylesAndKeepStyleSpanInline(Insert
if (!inlineStyle || newInlineStyle->isEmpty()) {
if (isStyleSpanOrSpanWithOnlyStyleAttribute(element) || isEmptyFontTag(element, AllowNonEmptyStyleAttribute)) {
- insertedNodes.willRemoveNodePreservingChildren(element);
+ insertedNodes.willRemoveNodePreservingChildren(*element);
removeNodePreservingChildren(element);
continue;
}
removeNodeAttribute(element, styleAttr);
- } else if (newInlineStyle->style()->propertyCount() != inlineStyle->propertyCount())
- setNodeAttribute(element, styleAttr, newInlineStyle->style()->asText());
+ } else if (newInlineStyle->style()->propertyCount() != inlineStyle->propertyCount()) {
+ setNodeAttribute(element, styleAttr, AtomicString(newInlineStyle->style()->asText()));
+ }
// FIXME: Tolerate differences in id, class, and style attributes.
if (isNonTableCellHTMLBlockElement(element) && areIdenticalElements(element, element->parentNode())
&& VisiblePosition(firstPositionInNode(element->parentNode())) == VisiblePosition(firstPositionInNode(element))
&& VisiblePosition(lastPositionInNode(element->parentNode())) == VisiblePosition(lastPositionInNode(element))) {
- insertedNodes.willRemoveNodePreservingChildren(element);
+ insertedNodes.willRemoveNodePreservingChildren(*element);
removeNodePreservingChildren(element);
continue;
}
@@ -534,7 +533,7 @@ void ReplaceSelectionCommand::removeRedundantStylesAndKeepStyleSpanInline(Insert
// Keep this code around for backward compatibility
if (isLegacyAppleStyleSpan(element)) {
if (!element->firstChild()) {
- insertedNodes.willRemoveNodePreservingChildren(element);
+ insertedNodes.willRemoveNodePreservingChildren(*element);
removeNodePreservingChildren(element);
continue;
}
@@ -616,12 +615,12 @@ void ReplaceSelectionCommand::makeInsertedContentRoundTrippableWithHTMLTreeBuild
RefPtr<Node> pastEndNode = insertedNodes.pastLastLeaf();
RefPtr<Node> next;
for (RefPtr<Node> node = insertedNodes.firstNodeInserted(); node && node != pastEndNode; node = next) {
- next = NodeTraversal::next(node.get());
+ next = NodeTraversal::next(*node);
if (!node->isHTMLElement())
continue;
- if (isProhibitedParagraphChild(toHTMLElement(node.get())->localName())) {
+ if (isProhibitedParagraphChild(toHTMLElement(node)->localName())) {
if (HTMLElement* paragraphElement = toHTMLElement(enclosingNodeWithTag(positionInParentBeforeNode(node.get()), pTag)))
moveNodeOutOfAncestor(node, paragraphElement);
}
@@ -658,28 +657,28 @@ void ReplaceSelectionCommand::moveNodeOutOfAncestor(PassRefPtr<Node> prpNode, Pa
removeNode(ancestor.release());
}
-static inline bool nodeHasVisibleRenderText(Text* text)
+static inline bool nodeHasVisibleRenderText(Text& text)
{
- return text->renderer() && toRenderText(text->renderer())->renderedTextLength() > 0;
+ return text.renderer() && toRenderText(text.renderer())->renderedTextLength() > 0;
}
void ReplaceSelectionCommand::removeUnrenderedTextNodesAtEnds(InsertedNodes& insertedNodes)
{
document().updateLayoutIgnorePendingStylesheets();
- Node* lastLeafInserted = insertedNodes.lastLeafInserted();
- if (lastLeafInserted && lastLeafInserted->isTextNode() && !nodeHasVisibleRenderText(toText(lastLeafInserted))
- && !enclosingNodeWithTag(firstPositionInOrBeforeNode(lastLeafInserted), selectTag)
- && !enclosingNodeWithTag(firstPositionInOrBeforeNode(lastLeafInserted), scriptTag)) {
+ Node& lastLeafInserted = insertedNodes.lastLeafInserted();
+ if (lastLeafInserted.isTextNode() && !nodeHasVisibleRenderText(toText(lastLeafInserted))
+ && !enclosingNodeWithTag(firstPositionInOrBeforeNode(&lastLeafInserted), selectTag)
+ && !enclosingNodeWithTag(firstPositionInOrBeforeNode(&lastLeafInserted), scriptTag)) {
insertedNodes.willRemoveNode(lastLeafInserted);
- removeNode(lastLeafInserted);
+ removeNode(&lastLeafInserted);
}
// We don't have to make sure that firstNodeInserted isn't inside a select or script element, because
// it is a top level node in the fragment and the user can't insert into those elements.
Node* firstNodeInserted = insertedNodes.firstNodeInserted();
- if (firstNodeInserted && firstNodeInserted->isTextNode() && !nodeHasVisibleRenderText(toText(firstNodeInserted))) {
- insertedNodes.willRemoveNode(firstNodeInserted);
+ if (firstNodeInserted && firstNodeInserted->isTextNode() && !nodeHasVisibleRenderText(toText(*firstNodeInserted))) {
+ insertedNodes.willRemoveNode(*firstNodeInserted);
removeNode(firstNodeInserted);
}
}
@@ -705,10 +704,11 @@ static void removeHeadContents(ReplacementFragment& fragment)
|| node->hasTagName(metaTag)
|| node->hasTagName(styleTag)
|| isHTMLTitleElement(node)) {
- next = NodeTraversal::nextSkippingChildren(node);
+ next = NodeTraversal::nextSkippingChildren(*node);
fragment.removeNode(node);
- } else
- next = NodeTraversal::next(node);
+ } else {
+ next = NodeTraversal::next(*node);
+ }
}
}
@@ -755,7 +755,7 @@ void ReplaceSelectionCommand::handleStyleSpans(InsertedNodes& insertedNodes)
// The style span that contains the source document's default style should be at
// the top of the fragment, but Mail sometimes adds a wrapper (for Paste As Quotation),
// so search for the top level style span instead of assuming it's at the top.
- for (Node* node = insertedNodes.firstNodeInserted(); node; node = NodeTraversal::next(node)) {
+ for (Node* node = insertedNodes.firstNodeInserted(); node; node = NodeTraversal::next(*node)) {
if (isLegacyAppleStyleSpan(node)) {
wrappingStyleSpan = toHTMLElement(node);
break;
@@ -787,10 +787,11 @@ void ReplaceSelectionCommand::handleStyleSpans(InsertedNodes& insertedNodes)
style->removeBlockProperties();
if (style->isEmpty() || !wrappingStyleSpan->firstChild()) {
- insertedNodes.willRemoveNodePreservingChildren(wrappingStyleSpan);
+ insertedNodes.willRemoveNodePreservingChildren(*wrappingStyleSpan);
removeNodePreservingChildren(wrappingStyleSpan);
- } else
- setNodeAttribute(wrappingStyleSpan, styleAttr, style->style()->asText());
+ } else {
+ setNodeAttribute(wrappingStyleSpan, styleAttr, AtomicString(style->style()->asText()));
+ }
}
void ReplaceSelectionCommand::mergeEndIfNeeded()
@@ -1067,6 +1068,7 @@ void ReplaceSelectionCommand::doApply()
InsertedNodes insertedNodes;
RefPtr<Node> refNode = fragment.firstChild();
+ ASSERT(refNode);
RefPtr<Node> node = refNode->nextSibling();
fragment.removeNode(refNode);
@@ -1074,10 +1076,10 @@ void ReplaceSelectionCommand::doApply()
Node* blockStart = enclosingBlock(insertionPos.deprecatedNode());
if ((isListElement(refNode.get()) || (isLegacyAppleStyleSpan(refNode.get()) && isListElement(refNode->firstChild())))
&& blockStart && blockStart->renderer()->isListItem())
- refNode = insertAsListItems(toHTMLElement(refNode.get()), blockStart, insertionPos, insertedNodes);
+ refNode = insertAsListItems(toHTMLElement(refNode), blockStart, insertionPos, insertedNodes);
else {
insertNodeAt(refNode, insertionPos);
- insertedNodes.respondToNodeInsertion(refNode.get());
+ insertedNodes.respondToNodeInsertion(*refNode);
}
// Mutation events (bug 22634) may have already removed the inserted content
@@ -1089,8 +1091,8 @@ void ReplaceSelectionCommand::doApply()
while (node) {
RefPtr<Node> next = node->nextSibling();
fragment.removeNode(node.get());
- insertNodeAfter(node, refNode.get());
- insertedNodes.respondToNodeInsertion(node.get());
+ insertNodeAfter(node, refNode);
+ insertedNodes.respondToNodeInsertion(*node);
// Mutation events (bug 22634) may have already removed the inserted content
if (!node->inDocument())
@@ -1125,10 +1127,10 @@ void ReplaceSelectionCommand::doApply()
if (endBR && (plainTextFragment || shouldRemoveEndBR(endBR, originalVisPosBeforeEndBR))) {
RefPtr<Node> parent = endBR->parentNode();
- insertedNodes.willRemoveNode(endBR);
+ insertedNodes.willRemoveNode(*endBR);
removeNode(endBR);
if (Node* nodeToRemove = highestNodeToRemoveInPruning(parent.get())) {
- insertedNodes.willRemoveNode(nodeToRemove);
+ insertedNodes.willRemoveNode(*nodeToRemove);
removeNode(nodeToRemove);
}
}
@@ -1142,7 +1144,7 @@ void ReplaceSelectionCommand::doApply()
// Setup m_startOfInsertedContent and m_endOfInsertedContent. This should be the last two lines of code that access insertedNodes.
m_startOfInsertedContent = firstPositionInOrBeforeNode(insertedNodes.firstNodeInserted());
- m_endOfInsertedContent = lastPositionInOrAfterNode(insertedNodes.lastLeafInserted());
+ m_endOfInsertedContent = lastPositionInOrAfterNode(&insertedNodes.lastLeafInserted());
// Determine whether or not we should merge the end of inserted content with what's after it before we do
// the start merge so that the start merge doesn't effect our decision.
@@ -1437,10 +1439,10 @@ Node* ReplaceSelectionCommand::insertAsListItems(PassRefPtr<HTMLElement> prpList
listElement->removeChild(listItem.get(), ASSERT_NO_EXCEPTION);
if (isStart || isMiddle) {
insertNodeBefore(listItem, lastNode);
- insertedNodes.respondToNodeInsertion(listItem.get());
+ insertedNodes.respondToNodeInsertion(*listItem);
} else if (isEnd) {
insertNodeAfter(listItem, lastNode);
- insertedNodes.respondToNodeInsertion(listItem.get());
+ insertedNodes.respondToNodeInsertion(*listItem);
lastNode = listItem.get();
} else
ASSERT_NOT_REACHED();
@@ -1458,7 +1460,7 @@ void ReplaceSelectionCommand::updateNodesInserted(Node *node)
if (m_startOfInsertedContent.isNull())
m_startOfInsertedContent = firstPositionInOrBeforeNode(node);
- m_endOfInsertedContent = lastPositionInOrAfterNode(node->lastDescendant());
+ m_endOfInsertedContent = lastPositionInOrAfterNode(&node->lastDescendant());
}
// During simple pastes, where we're just pasting a text node into a run of text, we insert the text node
diff --git a/chromium/third_party/WebKit/Source/core/editing/ReplaceSelectionCommand.h b/chromium/third_party/WebKit/Source/core/editing/ReplaceSelectionCommand.h
index b6eacc70019..ee3879b2258 100644
--- a/chromium/third_party/WebKit/Source/core/editing/ReplaceSelectionCommand.h
+++ b/chromium/third_party/WebKit/Source/core/editing/ReplaceSelectionCommand.h
@@ -60,13 +60,13 @@ private:
class InsertedNodes {
public:
- void respondToNodeInsertion(Node*);
- void willRemoveNodePreservingChildren(Node*);
- void willRemoveNode(Node*);
- void didReplaceNode(Node*, Node* newNode);
+ void respondToNodeInsertion(Node&);
+ void willRemoveNodePreservingChildren(Node&);
+ void willRemoveNode(Node&);
+ void didReplaceNode(Node&, Node& newNode);
Node* firstNodeInserted() const { return m_firstNodeInserted.get(); }
- Node* lastLeafInserted() const { return m_lastNodeInserted->lastDescendant(); }
+ Node& lastLeafInserted() const { ASSERT(m_lastNodeInserted); return m_lastNodeInserted->lastDescendant(); }
Node* pastLastLeaf() const { return m_lastNodeInserted ? NodeTraversal::next(lastLeafInserted()) : 0; }
private:
diff --git a/chromium/third_party/WebKit/Source/core/editing/SelectionType.h b/chromium/third_party/WebKit/Source/core/editing/SelectionType.h
new file mode 100644
index 00000000000..1d5a6067a9d
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/editing/SelectionType.h
@@ -0,0 +1,35 @@
+/*
+ * Copyright (C) 2004 Apple Computer, Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SelectionType_h
+#define SelectionType_h
+
+namespace WebCore {
+
+enum SelectionType { NoSelection, CaretSelection, RangeSelection };
+
+} // namespace WebCore
+
+#endif // SelectionType_h
diff --git a/chromium/third_party/WebKit/Source/core/editing/SetNodeAttributeCommand.cpp b/chromium/third_party/WebKit/Source/core/editing/SetNodeAttributeCommand.cpp
index b4bd12f3a72..2d4b7ee8f9d 100644
--- a/chromium/third_party/WebKit/Source/core/editing/SetNodeAttributeCommand.cpp
+++ b/chromium/third_party/WebKit/Source/core/editing/SetNodeAttributeCommand.cpp
@@ -50,8 +50,7 @@ void SetNodeAttributeCommand::doApply()
void SetNodeAttributeCommand::doUnapply()
{
m_element->setAttribute(m_attribute, m_oldValue);
- StringImpl* nullString = 0;
- m_oldValue = nullString;
+ m_oldValue = nullAtom;
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/editing/SetSelectionCommand.cpp b/chromium/third_party/WebKit/Source/core/editing/SetSelectionCommand.cpp
index 48c86bf0698..dff5416d17f 100644
--- a/chromium/third_party/WebKit/Source/core/editing/SetSelectionCommand.cpp
+++ b/chromium/third_party/WebKit/Source/core/editing/SetSelectionCommand.cpp
@@ -27,7 +27,7 @@
#include "core/editing/SetSelectionCommand.h"
#include "core/dom/Document.h"
-#include "core/page/Frame.h"
+#include "core/frame/Frame.h"
namespace WebCore {
@@ -41,17 +41,14 @@ SetSelectionCommand::SetSelectionCommand(const VisibleSelection& selection, Fram
void SetSelectionCommand::doApply()
{
FrameSelection& selection = document().frame()->selection();
- if (selection.shouldChangeSelection(m_selectionToSet) && m_selectionToSet.isNonOrphanedCaretOrRange()) {
- selection.setSelection(m_selectionToSet, m_options);
- setEndingSelection(m_selectionToSet);
- }
+ selection.setSelection(m_selectionToSet, m_options);
+ setEndingSelection(m_selectionToSet);
}
void SetSelectionCommand::doUnapply()
{
FrameSelection& selection = document().frame()->selection();
- if (selection.shouldChangeSelection(startingSelection()) && startingSelection().isNonOrphanedCaretOrRange())
- selection.setSelection(startingSelection(), m_options);
+ selection.setSelection(startingSelection(), m_options);
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/editing/SimplifyMarkupCommand.cpp b/chromium/third_party/WebKit/Source/core/editing/SimplifyMarkupCommand.cpp
index 4e5fdf71061..8d13312d1e5 100644
--- a/chromium/third_party/WebKit/Source/core/editing/SimplifyMarkupCommand.cpp
+++ b/chromium/third_party/WebKit/Source/core/editing/SimplifyMarkupCommand.cpp
@@ -48,7 +48,7 @@ void SimplifyMarkupCommand::doApply()
// without affecting the style. The goal is to produce leaner markup even when starting
// from a verbose fragment.
// We look at inline elements as well as non top level divs that don't have attributes.
- for (Node* node = m_firstNode.get(); node && node != m_nodeAfterLast; node = NodeTraversal::next(node)) {
+ for (Node* node = m_firstNode.get(); node && node != m_nodeAfterLast; node = NodeTraversal::next(*node)) {
if (node->firstChild() || (node->isTextNode() && node->nextSibling()))
continue;
diff --git a/chromium/third_party/WebKit/Source/core/editing/SpellCheckRequester.cpp b/chromium/third_party/WebKit/Source/core/editing/SpellCheckRequester.cpp
index 5ca2367bdc4..104f446b569 100644
--- a/chromium/third_party/WebKit/Source/core/editing/SpellCheckRequester.cpp
+++ b/chromium/third_party/WebKit/Source/core/editing/SpellCheckRequester.cpp
@@ -29,13 +29,10 @@
#include "core/dom/Document.h"
#include "core/dom/DocumentMarkerController.h"
#include "core/dom/Node.h"
-#include "core/dom/Range.h"
-#include "core/editing/Editor.h"
-#include "core/page/EditorClient.h"
-#include "core/page/Frame.h"
-#include "core/page/Page.h"
-#include "core/page/Settings.h"
-#include "core/platform/text/TextCheckerClient.h"
+#include "core/editing/SpellChecker.h"
+#include "core/frame/Frame.h"
+#include "core/frame/Settings.h"
+#include "platform/text/TextCheckerClient.h"
namespace WebCore {
@@ -71,7 +68,7 @@ PassRefPtr<SpellCheckRequest> SpellCheckRequest::create(TextCheckingTypeMask tex
if (!text.length())
return PassRefPtr<SpellCheckRequest>();
- const Vector<DocumentMarker*>& markers = checkingRange->ownerDocument().markers()->markersInRange(checkingRange.get(), DocumentMarker::MisspellingMarkers());
+ const Vector<DocumentMarker*>& markers = checkingRange->ownerDocument().markers()->markersInRange(checkingRange.get(), DocumentMarker::SpellCheckClientMarkers());
Vector<uint32_t> hashes(markers.size());
Vector<unsigned> offsets(markers.size());
for (size_t i = 0; i < markers.size(); i++) {
@@ -136,7 +133,7 @@ SpellCheckRequester::~SpellCheckRequester()
TextCheckerClient& SpellCheckRequester::client() const
{
- return m_frame.editor().client().textChecker();
+ return m_frame.spellChecker().textChecker();
}
void SpellCheckRequester::timerFiredToProcessQueuedRequest(Timer<SpellCheckRequester>*)
@@ -236,7 +233,7 @@ void SpellCheckRequester::didCheck(int sequence, const Vector<TextCheckingResult
return;
}
- m_frame.editor().markAndReplaceFor(m_processingRequest, results);
+ m_frame.spellChecker().markAndReplaceFor(m_processingRequest, results);
if (m_lastProcessedSequence < sequence)
m_lastProcessedSequence = sequence;
@@ -250,13 +247,12 @@ void SpellCheckRequester::didCheckSucceed(int sequence, const Vector<TextCheckin
{
TextCheckingRequestData requestData = m_processingRequest->data();
if (requestData.sequence() == sequence) {
- unsigned markers = 0;
- if (requestData.mask() & TextCheckingTypeSpelling)
- markers |= DocumentMarker::Spelling;
- if (requestData.mask() & TextCheckingTypeGrammar)
- markers |= DocumentMarker::Grammar;
- if (markers)
- m_frame.document()->markers()->removeMarkers(m_processingRequest->checkingRange().get(), markers);
+ DocumentMarker::MarkerTypes markers = DocumentMarker::SpellCheckClientMarkers();
+ if (!requestData.maskContains(TextCheckingTypeSpelling))
+ markers.remove(DocumentMarker::Spelling);
+ if (!requestData.maskContains(TextCheckingTypeGrammar))
+ markers.remove(DocumentMarker::Grammar);
+ m_frame.document()->markers()->removeMarkers(m_processingRequest->checkingRange().get(), markers);
}
didCheck(sequence, results);
}
diff --git a/chromium/third_party/WebKit/Source/core/editing/SpellCheckRequester.h b/chromium/third_party/WebKit/Source/core/editing/SpellCheckRequester.h
index 9a96f593f91..6eefe8f2583 100644
--- a/chromium/third_party/WebKit/Source/core/editing/SpellCheckRequester.h
+++ b/chromium/third_party/WebKit/Source/core/editing/SpellCheckRequester.h
@@ -28,8 +28,8 @@
#include "core/dom/Element.h"
#include "core/dom/Range.h"
-#include "core/platform/Timer.h"
-#include "core/platform/text/TextChecking.h"
+#include "platform/Timer.h"
+#include "platform/text/TextChecking.h"
#include "wtf/Deque.h"
#include "wtf/Noncopyable.h"
#include "wtf/RefPtr.h"
diff --git a/chromium/third_party/WebKit/Source/core/editing/SpellChecker.cpp b/chromium/third_party/WebKit/Source/core/editing/SpellChecker.cpp
new file mode 100644
index 00000000000..a3c129d74a0
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/editing/SpellChecker.cpp
@@ -0,0 +1,884 @@
+/*
+ * Copyright (C) 2006, 2007, 2008, 2011 Apple Inc. All rights reserved.
+ * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/editing/SpellChecker.h"
+
+#include "HTMLNames.h"
+#include "core/dom/Document.h"
+#include "core/dom/DocumentMarkerController.h"
+#include "core/dom/Element.h"
+#include "core/dom/NodeTraversal.h"
+#include "core/editing/Editor.h"
+#include "core/editing/SpellCheckRequester.h"
+#include "core/editing/TextCheckingHelper.h"
+#include "core/editing/VisibleUnits.h"
+#include "core/editing/htmlediting.h"
+#include "core/frame/Frame.h"
+#include "core/html/HTMLInputElement.h"
+#include "core/loader/EmptyClients.h"
+#include "core/page/Page.h"
+#include "core/frame/Settings.h"
+#include "core/page/SpellCheckerClient.h"
+#include "core/rendering/RenderTextControl.h"
+#include "platform/text/TextCheckerClient.h"
+
+namespace WebCore {
+
+using namespace HTMLNames;
+
+namespace {
+
+bool isSelectionInTextField(const VisibleSelection& selection)
+{
+ HTMLTextFormControlElement* textControl = enclosingTextFormControl(selection.start());
+ return textControl && textControl->hasTagName(inputTag) && toHTMLInputElement(textControl)->isTextField();
+}
+
+} // namespace
+
+PassOwnPtr<SpellChecker> SpellChecker::create(Frame& frame)
+{
+ return adoptPtr(new SpellChecker(frame));
+}
+
+static SpellCheckerClient& emptySpellCheckerClient()
+{
+ DEFINE_STATIC_LOCAL(EmptySpellCheckerClient, client, ());
+ return client;
+}
+
+SpellCheckerClient& SpellChecker::spellCheckerClient() const
+{
+ if (Page* page = m_frame.page())
+ return page->spellCheckerClient();
+ return emptySpellCheckerClient();
+}
+
+TextCheckerClient& SpellChecker::textChecker() const
+{
+ return spellCheckerClient().textChecker();
+}
+
+SpellChecker::SpellChecker(Frame& frame)
+ : m_frame(frame)
+ , m_spellCheckRequester(adoptPtr(new SpellCheckRequester(frame)))
+{
+}
+
+SpellChecker::~SpellChecker()
+{
+}
+
+bool SpellChecker::isContinuousSpellCheckingEnabled() const
+{
+ return spellCheckerClient().isContinuousSpellCheckingEnabled();
+}
+
+void SpellChecker::toggleContinuousSpellChecking()
+{
+ spellCheckerClient().toggleContinuousSpellChecking();
+ if (isContinuousSpellCheckingEnabled())
+ return;
+ for (Frame* frame = m_frame.page()->mainFrame(); frame && frame->document(); frame = frame->tree().traverseNext()) {
+ for (Node* node = frame->document()->rootNode(); node; node = NodeTraversal::next(*node)) {
+ node->setAlreadySpellChecked(false);
+ }
+ }
+}
+
+bool SpellChecker::isGrammarCheckingEnabled()
+{
+ return spellCheckerClient().isGrammarCheckingEnabled();
+}
+
+void SpellChecker::didBeginEditing(Element* element)
+{
+ if (isContinuousSpellCheckingEnabled() && unifiedTextCheckerEnabled()) {
+ bool isTextField = false;
+ HTMLTextFormControlElement* enclosingHTMLTextFormControlElement = 0;
+ if (!isHTMLTextFormControlElement(element))
+ enclosingHTMLTextFormControlElement = enclosingTextFormControl(firstPositionInNode(element));
+ element = enclosingHTMLTextFormControlElement ? enclosingHTMLTextFormControlElement : element;
+ Element* parent = element;
+ if (isHTMLTextFormControlElement(element)) {
+ HTMLTextFormControlElement* textControl = toHTMLTextFormControlElement(element);
+ parent = textControl;
+ element = textControl->innerTextElement();
+ isTextField = textControl->hasTagName(inputTag) && toHTMLInputElement(textControl)->isTextField();
+ }
+
+ if (isTextField || !parent->isAlreadySpellChecked()) {
+ // We always recheck textfields because markers are removed from them on blur.
+ VisibleSelection selection = VisibleSelection::selectionFromContentsOfNode(element);
+ markMisspellingsAndBadGrammar(selection);
+ if (!isTextField)
+ parent->setAlreadySpellChecked(true);
+ }
+ }
+}
+
+void SpellChecker::ignoreSpelling()
+{
+ if (RefPtr<Range> selectedRange = m_frame.selection().toNormalizedRange())
+ m_frame.document()->markers()->removeMarkers(selectedRange.get(), DocumentMarker::Spelling);
+}
+
+void SpellChecker::advanceToNextMisspelling(bool startBeforeSelection)
+{
+ // The basic approach is to search in two phases - from the selection end to the end of the doc, and
+ // then we wrap and search from the doc start to (approximately) where we started.
+
+ // Start at the end of the selection, search to edge of document. Starting at the selection end makes
+ // repeated "check spelling" commands work.
+ VisibleSelection selection(m_frame.selection().selection());
+ RefPtr<Range> spellingSearchRange(rangeOfContents(m_frame.document()));
+
+ bool startedWithSelection = false;
+ if (selection.start().deprecatedNode()) {
+ startedWithSelection = true;
+ if (startBeforeSelection) {
+ VisiblePosition start(selection.visibleStart());
+ // We match AppKit's rule: Start 1 character before the selection.
+ VisiblePosition oneBeforeStart = start.previous();
+ setStart(spellingSearchRange.get(), oneBeforeStart.isNotNull() ? oneBeforeStart : start);
+ } else {
+ setStart(spellingSearchRange.get(), selection.visibleEnd());
+ }
+ }
+
+ Position position = spellingSearchRange->startPosition();
+ if (!isEditablePosition(position)) {
+ // This shouldn't happen in very often because the Spelling menu items aren't enabled unless the
+ // selection is editable.
+ // This can happen in Mail for a mix of non-editable and editable content (like Stationary),
+ // when spell checking the whole document before sending the message.
+ // In that case the document might not be editable, but there are editable pockets that need to be spell checked.
+
+ position = firstEditablePositionAfterPositionInRoot(position, m_frame.document()->documentElement()).deepEquivalent();
+ if (position.isNull())
+ return;
+
+ Position rangeCompliantPosition = position.parentAnchoredEquivalent();
+ spellingSearchRange->setStart(rangeCompliantPosition.deprecatedNode(), rangeCompliantPosition.deprecatedEditingOffset(), IGNORE_EXCEPTION);
+ startedWithSelection = false; // won't need to wrap
+ }
+
+ // topNode defines the whole range we want to operate on
+ Node* topNode = highestEditableRoot(position);
+ // FIXME: lastOffsetForEditing() is wrong here if editingIgnoresContent(highestEditableRoot()) returns true (e.g. a <table>)
+ spellingSearchRange->setEnd(topNode, lastOffsetForEditing(topNode), IGNORE_EXCEPTION);
+
+ // If spellingSearchRange starts in the middle of a word, advance to the next word so we start checking
+ // at a word boundary. Going back by one char and then forward by a word does the trick.
+ if (startedWithSelection) {
+ VisiblePosition oneBeforeStart = startVisiblePosition(spellingSearchRange.get(), DOWNSTREAM).previous();
+ if (oneBeforeStart.isNotNull())
+ setStart(spellingSearchRange.get(), endOfWord(oneBeforeStart));
+ // else we were already at the start of the editable node
+ }
+
+ if (spellingSearchRange->collapsed(IGNORE_EXCEPTION))
+ return; // nothing to search in
+
+ // We go to the end of our first range instead of the start of it, just to be sure
+ // we don't get foiled by any word boundary problems at the start. It means we might
+ // do a tiny bit more searching.
+ Node* searchEndNodeAfterWrap = spellingSearchRange->endContainer();
+ int searchEndOffsetAfterWrap = spellingSearchRange->endOffset();
+
+ int misspellingOffset = 0;
+ GrammarDetail grammarDetail;
+ int grammarPhraseOffset = 0;
+ RefPtr<Range> grammarSearchRange;
+ String badGrammarPhrase;
+ String misspelledWord;
+
+ bool isSpelling = true;
+ int foundOffset = 0;
+ String foundItem;
+ RefPtr<Range> firstMisspellingRange;
+ if (unifiedTextCheckerEnabled()) {
+ grammarSearchRange = spellingSearchRange->cloneRange(IGNORE_EXCEPTION);
+ foundItem = TextCheckingHelper(spellCheckerClient(), spellingSearchRange).findFirstMisspellingOrBadGrammar(isGrammarCheckingEnabled(), isSpelling, foundOffset, grammarDetail);
+ if (isSpelling) {
+ misspelledWord = foundItem;
+ misspellingOffset = foundOffset;
+ } else {
+ badGrammarPhrase = foundItem;
+ grammarPhraseOffset = foundOffset;
+ }
+ } else {
+ misspelledWord = TextCheckingHelper(spellCheckerClient(), spellingSearchRange).findFirstMisspelling(misspellingOffset, false, firstMisspellingRange);
+ grammarSearchRange = spellingSearchRange->cloneRange(IGNORE_EXCEPTION);
+ if (!misspelledWord.isEmpty()) {
+ // Stop looking at start of next misspelled word
+ CharacterIterator chars(grammarSearchRange.get());
+ chars.advance(misspellingOffset);
+ grammarSearchRange->setEnd(chars.range()->startContainer(), chars.range()->startOffset(), IGNORE_EXCEPTION);
+ }
+
+ if (isGrammarCheckingEnabled())
+ badGrammarPhrase = TextCheckingHelper(spellCheckerClient(), grammarSearchRange).findFirstBadGrammar(grammarDetail, grammarPhraseOffset, false);
+ }
+
+ // If we found neither bad grammar nor a misspelled word, wrap and try again (but don't bother if we started at the beginning of the
+ // block rather than at a selection).
+ if (startedWithSelection && !misspelledWord && !badGrammarPhrase) {
+ spellingSearchRange->setStart(topNode, 0, IGNORE_EXCEPTION);
+ // going until the end of the very first chunk we tested is far enough
+ spellingSearchRange->setEnd(searchEndNodeAfterWrap, searchEndOffsetAfterWrap, IGNORE_EXCEPTION);
+
+ if (unifiedTextCheckerEnabled()) {
+ grammarSearchRange = spellingSearchRange->cloneRange(IGNORE_EXCEPTION);
+ foundItem = TextCheckingHelper(spellCheckerClient(), spellingSearchRange).findFirstMisspellingOrBadGrammar(isGrammarCheckingEnabled(), isSpelling, foundOffset, grammarDetail);
+ if (isSpelling) {
+ misspelledWord = foundItem;
+ misspellingOffset = foundOffset;
+ } else {
+ badGrammarPhrase = foundItem;
+ grammarPhraseOffset = foundOffset;
+ }
+ } else {
+ misspelledWord = TextCheckingHelper(spellCheckerClient(), spellingSearchRange).findFirstMisspelling(misspellingOffset, false, firstMisspellingRange);
+ grammarSearchRange = spellingSearchRange->cloneRange(IGNORE_EXCEPTION);
+ if (!misspelledWord.isEmpty()) {
+ // Stop looking at start of next misspelled word
+ CharacterIterator chars(grammarSearchRange.get());
+ chars.advance(misspellingOffset);
+ grammarSearchRange->setEnd(chars.range()->startContainer(), chars.range()->startOffset(), IGNORE_EXCEPTION);
+ }
+
+ if (isGrammarCheckingEnabled())
+ badGrammarPhrase = TextCheckingHelper(spellCheckerClient(), grammarSearchRange).findFirstBadGrammar(grammarDetail, grammarPhraseOffset, false);
+ }
+ }
+
+ if (!badGrammarPhrase.isEmpty()) {
+ // We found bad grammar. Since we only searched for bad grammar up to the first misspelled word, the bad grammar
+ // takes precedence and we ignore any potential misspelled word. Select the grammar detail, update the spelling
+ // panel, and store a marker so we draw the green squiggle later.
+
+ ASSERT(badGrammarPhrase.length() > 0);
+ ASSERT(grammarDetail.location != -1 && grammarDetail.length > 0);
+
+ // FIXME 4859190: This gets confused with doubled punctuation at the end of a paragraph
+ RefPtr<Range> badGrammarRange = TextIterator::subrange(grammarSearchRange.get(), grammarPhraseOffset + grammarDetail.location, grammarDetail.length);
+ m_frame.selection().setSelection(VisibleSelection(badGrammarRange.get(), SEL_DEFAULT_AFFINITY));
+ m_frame.selection().revealSelection();
+
+ m_frame.document()->markers()->addMarker(badGrammarRange.get(), DocumentMarker::Grammar, grammarDetail.userDescription);
+ } else if (!misspelledWord.isEmpty()) {
+ // We found a misspelling, but not any earlier bad grammar. Select the misspelling, update the spelling panel, and store
+ // a marker so we draw the red squiggle later.
+
+ RefPtr<Range> misspellingRange = TextIterator::subrange(spellingSearchRange.get(), misspellingOffset, misspelledWord.length());
+ m_frame.selection().setSelection(VisibleSelection(misspellingRange.get(), DOWNSTREAM));
+ m_frame.selection().revealSelection();
+
+ spellCheckerClient().updateSpellingUIWithMisspelledWord(misspelledWord);
+ m_frame.document()->markers()->addMarker(misspellingRange.get(), DocumentMarker::Spelling);
+ }
+}
+
+String SpellChecker::misspelledWordAtCaretOrRange(Node* clickedNode) const
+{
+ if (!isContinuousSpellCheckingEnabled() || !clickedNode || !isSpellCheckingEnabledFor(clickedNode))
+ return String();
+
+ VisibleSelection selection = m_frame.selection().selection();
+ if (!selection.isContentEditable() || selection.isNone())
+ return String();
+
+ VisibleSelection wordSelection(selection.base());
+ wordSelection.expandUsingGranularity(WordGranularity);
+ RefPtr<Range> wordRange = wordSelection.toNormalizedRange();
+
+ // In compliance with GTK+ applications, additionally allow to provide suggestions when the current
+ // selection exactly match the word selection.
+ if (selection.isRange() && !areRangesEqual(wordRange.get(), selection.toNormalizedRange().get()))
+ return String();
+
+ String word = wordRange->text();
+ if (word.isEmpty())
+ return String();
+
+ int wordLength = word.length();
+ int misspellingLocation = -1;
+ int misspellingLength = 0;
+ textChecker().checkSpellingOfString(word, &misspellingLocation, &misspellingLength);
+
+ return misspellingLength == wordLength ? word : String();
+}
+
+void SpellChecker::showSpellingGuessPanel()
+{
+ if (spellCheckerClient().spellingUIIsShowing()) {
+ spellCheckerClient().showSpellingUI(false);
+ return;
+ }
+
+ advanceToNextMisspelling(true);
+ spellCheckerClient().showSpellingUI(true);
+}
+
+void SpellChecker::clearMisspellingsAndBadGrammar(const VisibleSelection &movingSelection)
+{
+ RefPtr<Range> selectedRange = movingSelection.toNormalizedRange();
+ if (selectedRange)
+ m_frame.document()->markers()->removeMarkers(selectedRange.get(), DocumentMarker::MisspellingMarkers());
+}
+
+void SpellChecker::markMisspellingsAndBadGrammar(const VisibleSelection &movingSelection)
+{
+ markMisspellingsAndBadGrammar(movingSelection, isContinuousSpellCheckingEnabled() && isGrammarCheckingEnabled(), movingSelection);
+}
+
+void SpellChecker::markMisspellingsAfterTypingToWord(const VisiblePosition &wordStart, const VisibleSelection& selectionAfterTyping)
+{
+ if (unifiedTextCheckerEnabled()) {
+ TextCheckingTypeMask textCheckingOptions = 0;
+
+ if (isContinuousSpellCheckingEnabled())
+ textCheckingOptions |= TextCheckingTypeSpelling;
+
+ if (!(textCheckingOptions & TextCheckingTypeSpelling))
+ return;
+
+ if (isGrammarCheckingEnabled())
+ textCheckingOptions |= TextCheckingTypeGrammar;
+
+ VisibleSelection adjacentWords = VisibleSelection(startOfWord(wordStart, LeftWordIfOnBoundary), endOfWord(wordStart, RightWordIfOnBoundary));
+ if (textCheckingOptions & TextCheckingTypeGrammar) {
+ VisibleSelection selectedSentence = VisibleSelection(startOfSentence(wordStart), endOfSentence(wordStart));
+ markAllMisspellingsAndBadGrammarInRanges(textCheckingOptions, adjacentWords.toNormalizedRange().get(), selectedSentence.toNormalizedRange().get());
+ } else {
+ markAllMisspellingsAndBadGrammarInRanges(textCheckingOptions, adjacentWords.toNormalizedRange().get(), adjacentWords.toNormalizedRange().get());
+ }
+ return;
+ }
+
+ if (!isContinuousSpellCheckingEnabled())
+ return;
+
+ // Check spelling of one word
+ RefPtr<Range> misspellingRange;
+ markMisspellings(VisibleSelection(startOfWord(wordStart, LeftWordIfOnBoundary), endOfWord(wordStart, RightWordIfOnBoundary)), misspellingRange);
+
+ // Autocorrect the misspelled word.
+ if (!misspellingRange)
+ return;
+
+ // Get the misspelled word.
+ const String misspelledWord = plainText(misspellingRange.get());
+ String autocorrectedString = textChecker().getAutoCorrectSuggestionForMisspelledWord(misspelledWord);
+
+ // If autocorrected word is non empty, replace the misspelled word by this word.
+ if (!autocorrectedString.isEmpty()) {
+ VisibleSelection newSelection(misspellingRange.get(), DOWNSTREAM);
+ if (newSelection != m_frame.selection().selection()) {
+ m_frame.selection().setSelection(newSelection);
+ }
+
+ m_frame.editor().replaceSelectionWithText(autocorrectedString, false, false);
+
+ // Reset the charet one character further.
+ m_frame.selection().moveTo(m_frame.selection().end());
+ m_frame.selection().modify(FrameSelection::AlterationMove, DirectionForward, CharacterGranularity);
+ }
+
+ if (!isGrammarCheckingEnabled())
+ return;
+
+ // Check grammar of entire sentence
+ markBadGrammar(VisibleSelection(startOfSentence(wordStart), endOfSentence(wordStart)));
+}
+
+void SpellChecker::markMisspellingsOrBadGrammar(const VisibleSelection& selection, bool checkSpelling, RefPtr<Range>& firstMisspellingRange)
+{
+ // This function is called with a selection already expanded to word boundaries.
+ // Might be nice to assert that here.
+
+ // This function is used only for as-you-type checking, so if that's off we do nothing. Note that
+ // grammar checking can only be on if spell checking is also on.
+ if (!isContinuousSpellCheckingEnabled())
+ return;
+
+ RefPtr<Range> searchRange(selection.toNormalizedRange());
+ if (!searchRange)
+ return;
+
+ // If we're not in an editable node, bail.
+ Node* editableNode = searchRange->startContainer();
+ if (!editableNode || !editableNode->rendererIsEditable())
+ return;
+
+ if (!isSpellCheckingEnabledFor(editableNode))
+ return;
+
+ TextCheckingHelper checker(spellCheckerClient(), searchRange);
+ if (checkSpelling)
+ checker.markAllMisspellings(firstMisspellingRange);
+ else if (isGrammarCheckingEnabled())
+ checker.markAllBadGrammar();
+}
+
+bool SpellChecker::isSpellCheckingEnabledFor(Node* node) const
+{
+ if (!node)
+ return false;
+ const Element* focusedElement = node->isElementNode() ? toElement(node) : node->parentElement();
+ if (!focusedElement)
+ return false;
+ return focusedElement->isSpellCheckingEnabled();
+}
+
+bool SpellChecker::isSpellCheckingEnabledInFocusedNode() const
+{
+ return isSpellCheckingEnabledFor(m_frame.selection().start().deprecatedNode());
+}
+
+void SpellChecker::markMisspellings(const VisibleSelection& selection, RefPtr<Range>& firstMisspellingRange)
+{
+ markMisspellingsOrBadGrammar(selection, true, firstMisspellingRange);
+}
+
+void SpellChecker::markBadGrammar(const VisibleSelection& selection)
+{
+ RefPtr<Range> firstMisspellingRange;
+ markMisspellingsOrBadGrammar(selection, false, firstMisspellingRange);
+}
+
+void SpellChecker::markAllMisspellingsAndBadGrammarInRanges(TextCheckingTypeMask textCheckingOptions, Range* spellingRange, Range* grammarRange)
+{
+ ASSERT(unifiedTextCheckerEnabled());
+
+ bool shouldMarkGrammar = textCheckingOptions & TextCheckingTypeGrammar;
+
+ // This function is called with selections already expanded to word boundaries.
+ if (!spellingRange || (shouldMarkGrammar && !grammarRange))
+ return;
+
+ // If we're not in an editable node, bail.
+ Node* editableNode = spellingRange->startContainer();
+ if (!editableNode || !editableNode->rendererIsEditable())
+ return;
+
+ if (!isSpellCheckingEnabledFor(editableNode))
+ return;
+
+ Range* rangeToCheck = shouldMarkGrammar ? grammarRange : spellingRange;
+ TextCheckingParagraph fullParagraphToCheck(rangeToCheck);
+
+ bool asynchronous = m_frame.settings() && m_frame.settings()->asynchronousSpellCheckingEnabled();
+ chunkAndMarkAllMisspellingsAndBadGrammar(textCheckingOptions, fullParagraphToCheck, asynchronous);
+}
+
+void SpellChecker::chunkAndMarkAllMisspellingsAndBadGrammar(Node* node)
+{
+ if (!node)
+ return;
+ RefPtr<Range> rangeToCheck = Range::create(*m_frame.document(), firstPositionInNode(node), lastPositionInNode(node));
+ TextCheckingParagraph textToCheck(rangeToCheck, rangeToCheck);
+ bool asynchronous = true;
+ chunkAndMarkAllMisspellingsAndBadGrammar(resolveTextCheckingTypeMask(TextCheckingTypeSpelling | TextCheckingTypeGrammar), textToCheck, asynchronous);
+}
+
+void SpellChecker::chunkAndMarkAllMisspellingsAndBadGrammar(TextCheckingTypeMask textCheckingOptions, const TextCheckingParagraph& fullParagraphToCheck, bool asynchronous)
+{
+ if (fullParagraphToCheck.isRangeEmpty() || fullParagraphToCheck.isEmpty())
+ return;
+
+ // Since the text may be quite big chunk it up and adjust to the sentence boundary.
+ const int kChunkSize = 16 * 1024;
+ int start = fullParagraphToCheck.checkingStart();
+ int end = fullParagraphToCheck.checkingEnd();
+ start = std::min(start, end);
+ end = std::max(start, end);
+ const int kNumChunksToCheck = asynchronous ? (end - start + kChunkSize - 1) / (kChunkSize) : 1;
+ int currentChunkStart = start;
+ RefPtr<Range> checkRange = fullParagraphToCheck.checkingRange();
+ if (kNumChunksToCheck == 1 && asynchronous) {
+ markAllMisspellingsAndBadGrammarInRanges(textCheckingOptions, checkRange.get(), checkRange.get(), asynchronous, 0);
+ return;
+ }
+
+ for (int iter = 0; iter < kNumChunksToCheck; ++iter) {
+ checkRange = fullParagraphToCheck.subrange(currentChunkStart, kChunkSize);
+ setStart(checkRange.get(), startOfSentence(checkRange->startPosition()));
+ setEnd(checkRange.get(), endOfSentence(checkRange->endPosition()));
+
+ int checkingLength = 0;
+ markAllMisspellingsAndBadGrammarInRanges(textCheckingOptions, checkRange.get(), checkRange.get(), asynchronous, iter, &checkingLength);
+ currentChunkStart += checkingLength;
+ }
+}
+
+void SpellChecker::markAllMisspellingsAndBadGrammarInRanges(TextCheckingTypeMask textCheckingOptions, Range* checkRange, Range* paragraphRange, bool asynchronous, int requestNumber, int* checkingLength)
+{
+ TextCheckingParagraph sentenceToCheck(checkRange, paragraphRange);
+ if (checkingLength)
+ *checkingLength = sentenceToCheck.checkingLength();
+
+ RefPtr<SpellCheckRequest> request = SpellCheckRequest::create(resolveTextCheckingTypeMask(textCheckingOptions), TextCheckingProcessBatch, checkRange, paragraphRange, requestNumber);
+
+ if (asynchronous) {
+ m_spellCheckRequester->requestCheckingFor(request);
+ } else {
+ Vector<TextCheckingResult> results;
+ checkTextOfParagraph(textChecker(), sentenceToCheck.text(), resolveTextCheckingTypeMask(textCheckingOptions), results);
+ markAndReplaceFor(request, results);
+ }
+}
+
+void SpellChecker::markAndReplaceFor(PassRefPtr<SpellCheckRequest> request, const Vector<TextCheckingResult>& results)
+{
+ ASSERT(request);
+
+ TextCheckingTypeMask textCheckingOptions = request->data().mask();
+ TextCheckingParagraph paragraph(request->checkingRange(), request->paragraphRange());
+
+ bool shouldMarkSpelling = textCheckingOptions & TextCheckingTypeSpelling;
+ bool shouldMarkGrammar = textCheckingOptions & TextCheckingTypeGrammar;
+
+ // Expand the range to encompass entire paragraphs, since text checking needs that much context.
+ int selectionOffset = 0;
+ int ambiguousBoundaryOffset = -1;
+ bool selectionChanged = false;
+ bool restoreSelectionAfterChange = false;
+ bool adjustSelectionForParagraphBoundaries = false;
+
+ if (shouldMarkSpelling) {
+ if (m_frame.selection().isCaret()) {
+ // Attempt to save the caret position so we can restore it later if needed
+ Position caretPosition = m_frame.selection().end();
+ selectionOffset = paragraph.offsetTo(caretPosition, ASSERT_NO_EXCEPTION);
+ restoreSelectionAfterChange = true;
+ if (selectionOffset > 0 && (static_cast<unsigned>(selectionOffset) > paragraph.text().length() || paragraph.textCharAt(selectionOffset - 1) == newlineCharacter))
+ adjustSelectionForParagraphBoundaries = true;
+ if (selectionOffset > 0 && static_cast<unsigned>(selectionOffset) <= paragraph.text().length() && isAmbiguousBoundaryCharacter(paragraph.textCharAt(selectionOffset - 1)))
+ ambiguousBoundaryOffset = selectionOffset - 1;
+ }
+ }
+
+ for (unsigned i = 0; i < results.size(); i++) {
+ int spellingRangeEndOffset = paragraph.checkingEnd();
+ const TextCheckingResult* result = &results[i];
+ int resultLocation = result->location + paragraph.checkingStart();
+ int resultLength = result->length;
+ bool resultEndsAtAmbiguousBoundary = ambiguousBoundaryOffset >= 0 && resultLocation + resultLength == ambiguousBoundaryOffset;
+
+ // Only mark misspelling if:
+ // 1. Current text checking isn't done for autocorrection, in which case shouldMarkSpelling is false.
+ // 2. Result falls within spellingRange.
+ // 3. The word in question doesn't end at an ambiguous boundary. For instance, we would not mark
+ // "wouldn'" as misspelled right after apostrophe is typed.
+ if (shouldMarkSpelling && result->decoration == TextDecorationTypeSpelling && resultLocation >= paragraph.checkingStart() && resultLocation + resultLength <= spellingRangeEndOffset && !resultEndsAtAmbiguousBoundary) {
+ ASSERT(resultLength > 0 && resultLocation >= 0);
+ RefPtr<Range> misspellingRange = paragraph.subrange(resultLocation, resultLength);
+ misspellingRange->startContainer()->document().markers()->addMarker(misspellingRange.get(), DocumentMarker::Spelling, result->replacement, result->hash);
+ } else if (shouldMarkGrammar && result->decoration == TextDecorationTypeGrammar && paragraph.checkingRangeCovers(resultLocation, resultLength)) {
+ ASSERT(resultLength > 0 && resultLocation >= 0);
+ for (unsigned j = 0; j < result->details.size(); j++) {
+ const GrammarDetail* detail = &result->details[j];
+ ASSERT(detail->length > 0 && detail->location >= 0);
+ if (paragraph.checkingRangeCovers(resultLocation + detail->location, detail->length)) {
+ RefPtr<Range> badGrammarRange = paragraph.subrange(resultLocation + detail->location, detail->length);
+ badGrammarRange->startContainer()->document().markers()->addMarker(badGrammarRange.get(), DocumentMarker::Grammar, detail->userDescription, result->hash);
+ }
+ }
+ } else if (result->decoration == TextDecorationTypeInvisibleSpellcheck && resultLocation >= paragraph.checkingStart() && resultLocation + resultLength <= spellingRangeEndOffset) {
+ ASSERT(resultLength > 0 && resultLocation >= 0);
+ RefPtr<Range> invisibleSpellcheckRange = paragraph.subrange(resultLocation, resultLength);
+ invisibleSpellcheckRange->startContainer()->document().markers()->addMarker(invisibleSpellcheckRange.get(), DocumentMarker::InvisibleSpellcheck, result->replacement, result->hash);
+ }
+ }
+
+ if (selectionChanged) {
+ TextCheckingParagraph extendedParagraph(paragraph);
+ // Restore the caret position if we have made any replacements
+ extendedParagraph.expandRangeToNextEnd();
+ if (restoreSelectionAfterChange && selectionOffset >= 0 && selectionOffset <= extendedParagraph.rangeLength()) {
+ RefPtr<Range> selectionRange = extendedParagraph.subrange(0, selectionOffset);
+ m_frame.selection().moveTo(selectionRange->endPosition(), DOWNSTREAM);
+ if (adjustSelectionForParagraphBoundaries)
+ m_frame.selection().modify(FrameSelection::AlterationMove, DirectionForward, CharacterGranularity);
+ } else {
+ // If this fails for any reason, the fallback is to go one position beyond the last replacement
+ m_frame.selection().moveTo(m_frame.selection().end());
+ m_frame.selection().modify(FrameSelection::AlterationMove, DirectionForward, CharacterGranularity);
+ }
+ }
+}
+
+void SpellChecker::markMisspellingsAndBadGrammar(const VisibleSelection& spellingSelection, bool markGrammar, const VisibleSelection& grammarSelection)
+{
+ if (unifiedTextCheckerEnabled()) {
+ if (!isContinuousSpellCheckingEnabled())
+ return;
+
+ // markMisspellingsAndBadGrammar() is triggered by selection change, in which case we check spelling and grammar, but don't autocorrect misspellings.
+ TextCheckingTypeMask textCheckingOptions = TextCheckingTypeSpelling;
+ if (markGrammar && isGrammarCheckingEnabled())
+ textCheckingOptions |= TextCheckingTypeGrammar;
+ markAllMisspellingsAndBadGrammarInRanges(textCheckingOptions, spellingSelection.toNormalizedRange().get(), grammarSelection.toNormalizedRange().get());
+ return;
+ }
+
+ RefPtr<Range> firstMisspellingRange;
+ markMisspellings(spellingSelection, firstMisspellingRange);
+ if (markGrammar)
+ markBadGrammar(grammarSelection);
+}
+
+void SpellChecker::updateMarkersForWordsAffectedByEditing(bool doNotRemoveIfSelectionAtWordBoundary)
+{
+ if (textChecker().shouldEraseMarkersAfterChangeSelection(TextCheckingTypeSpelling))
+ return;
+
+ // We want to remove the markers from a word if an editing command will change the word. This can happen in one of
+ // several scenarios:
+ // 1. Insert in the middle of a word.
+ // 2. Appending non whitespace at the beginning of word.
+ // 3. Appending non whitespace at the end of word.
+ // Note that, appending only whitespaces at the beginning or end of word won't change the word, so we don't need to
+ // remove the markers on that word.
+ // Of course, if current selection is a range, we potentially will edit two words that fall on the boundaries of
+ // selection, and remove words between the selection boundaries.
+ //
+ VisiblePosition startOfSelection = m_frame.selection().selection().start();
+ VisiblePosition endOfSelection = m_frame.selection().selection().end();
+ if (startOfSelection.isNull())
+ return;
+ // First word is the word that ends after or on the start of selection.
+ VisiblePosition startOfFirstWord = startOfWord(startOfSelection, LeftWordIfOnBoundary);
+ VisiblePosition endOfFirstWord = endOfWord(startOfSelection, LeftWordIfOnBoundary);
+ // Last word is the word that begins before or on the end of selection
+ VisiblePosition startOfLastWord = startOfWord(endOfSelection, RightWordIfOnBoundary);
+ VisiblePosition endOfLastWord = endOfWord(endOfSelection, RightWordIfOnBoundary);
+
+ if (startOfFirstWord.isNull()) {
+ startOfFirstWord = startOfWord(startOfSelection, RightWordIfOnBoundary);
+ endOfFirstWord = endOfWord(startOfSelection, RightWordIfOnBoundary);
+ }
+
+ if (endOfLastWord.isNull()) {
+ startOfLastWord = startOfWord(endOfSelection, LeftWordIfOnBoundary);
+ endOfLastWord = endOfWord(endOfSelection, LeftWordIfOnBoundary);
+ }
+
+ // If doNotRemoveIfSelectionAtWordBoundary is true, and first word ends at the start of selection,
+ // we choose next word as the first word.
+ if (doNotRemoveIfSelectionAtWordBoundary && endOfFirstWord == startOfSelection) {
+ startOfFirstWord = nextWordPosition(startOfFirstWord);
+ endOfFirstWord = endOfWord(startOfFirstWord, RightWordIfOnBoundary);
+ if (startOfFirstWord == endOfSelection)
+ return;
+ }
+
+ // If doNotRemoveIfSelectionAtWordBoundary is true, and last word begins at the end of selection,
+ // we choose previous word as the last word.
+ if (doNotRemoveIfSelectionAtWordBoundary && startOfLastWord == endOfSelection) {
+ startOfLastWord = previousWordPosition(startOfLastWord);
+ endOfLastWord = endOfWord(startOfLastWord, RightWordIfOnBoundary);
+ if (endOfLastWord == startOfSelection)
+ return;
+ }
+
+ if (startOfFirstWord.isNull() || endOfFirstWord.isNull() || startOfLastWord.isNull() || endOfLastWord.isNull())
+ return;
+
+ // Now we remove markers on everything between startOfFirstWord and endOfLastWord.
+ // However, if an autocorrection change a single word to multiple words, we want to remove correction mark from all the
+ // resulted words even we only edit one of them. For example, assuming autocorrection changes "avantgarde" to "avant
+ // garde", we will have CorrectionIndicator marker on both words and on the whitespace between them. If we then edit garde,
+ // we would like to remove the marker from word "avant" and whitespace as well. So we need to get the continous range of
+ // of marker that contains the word in question, and remove marker on that whole range.
+ Document* document = m_frame.document();
+ ASSERT(document);
+ RefPtr<Range> wordRange = Range::create(*document, startOfFirstWord.deepEquivalent(), endOfLastWord.deepEquivalent());
+
+ document->markers()->removeMarkers(wordRange.get(), DocumentMarker::MisspellingMarkers(), DocumentMarkerController::RemovePartiallyOverlappingMarker);
+}
+
+void SpellChecker::didEndEditingOnTextField(Element* e)
+{
+ // Remove markers when deactivating a selection in an <input type="text"/>.
+ // Prevent new ones from appearing too.
+ m_spellCheckRequester->cancelCheck();
+ HTMLTextFormControlElement* textFormControlElement = toHTMLTextFormControlElement(e);
+ HTMLElement* innerText = textFormControlElement->innerTextElement();
+ DocumentMarker::MarkerTypes markerTypes(DocumentMarker::Spelling);
+ if (isGrammarCheckingEnabled() || unifiedTextCheckerEnabled())
+ markerTypes.add(DocumentMarker::Grammar);
+ for (Node* node = innerText; node; node = NodeTraversal::next(*node, innerText)) {
+ m_frame.document()->markers()->removeMarkers(node, markerTypes);
+ }
+}
+
+void SpellChecker::respondToChangedSelection(const VisibleSelection& oldSelection, FrameSelection::SetSelectionOptions options)
+{
+ bool closeTyping = options & FrameSelection::CloseTyping;
+ bool isContinuousSpellCheckingEnabled = this->isContinuousSpellCheckingEnabled();
+ bool isContinuousGrammarCheckingEnabled = isContinuousSpellCheckingEnabled && isGrammarCheckingEnabled();
+ if (isContinuousSpellCheckingEnabled) {
+ VisibleSelection newAdjacentWords;
+ VisibleSelection newSelectedSentence;
+ bool caretBrowsing = m_frame.settings() && m_frame.settings()->caretBrowsingEnabled();
+ if (m_frame.selection().selection().isContentEditable() || caretBrowsing) {
+ VisiblePosition newStart(m_frame.selection().selection().visibleStart());
+ newAdjacentWords = VisibleSelection(startOfWord(newStart, LeftWordIfOnBoundary), endOfWord(newStart, RightWordIfOnBoundary));
+ if (isContinuousGrammarCheckingEnabled)
+ newSelectedSentence = VisibleSelection(startOfSentence(newStart), endOfSentence(newStart));
+ }
+
+ // Don't check spelling and grammar if the change of selection is triggered by spelling correction itself.
+ bool shouldCheckSpellingAndGrammar = !(options & FrameSelection::SpellCorrectionTriggered);
+
+ // When typing we check spelling elsewhere, so don't redo it here.
+ // If this is a change in selection resulting from a delete operation,
+ // oldSelection may no longer be in the document.
+ if (shouldCheckSpellingAndGrammar
+ && closeTyping
+ && oldSelection.isContentEditable()
+ && oldSelection.start().inDocument()
+ && !isSelectionInTextField(oldSelection)) {
+ spellCheckOldSelection(oldSelection, newAdjacentWords, newSelectedSentence);
+ }
+
+ if (textChecker().shouldEraseMarkersAfterChangeSelection(TextCheckingTypeSpelling)) {
+ if (RefPtr<Range> wordRange = newAdjacentWords.toNormalizedRange())
+ m_frame.document()->markers()->removeMarkers(wordRange.get(), DocumentMarker::Spelling);
+ }
+ if (textChecker().shouldEraseMarkersAfterChangeSelection(TextCheckingTypeGrammar)) {
+ if (RefPtr<Range> sentenceRange = newSelectedSentence.toNormalizedRange())
+ m_frame.document()->markers()->removeMarkers(sentenceRange.get(), DocumentMarker::Grammar);
+ }
+ }
+
+ // When continuous spell checking is off, existing markers disappear after the selection changes.
+ if (!isContinuousSpellCheckingEnabled)
+ m_frame.document()->markers()->removeMarkers(DocumentMarker::Spelling);
+ if (!isContinuousGrammarCheckingEnabled)
+ m_frame.document()->markers()->removeMarkers(DocumentMarker::Grammar);
+}
+
+void SpellChecker::spellCheckAfterBlur()
+{
+ if (!m_frame.selection().selection().isContentEditable())
+ return;
+
+ if (isSelectionInTextField(m_frame.selection().selection())) {
+ // textFieldDidEndEditing() and textFieldDidBeginEditing() handle this.
+ return;
+ }
+
+ VisibleSelection empty;
+ spellCheckOldSelection(m_frame.selection().selection(), empty, empty);
+}
+
+void SpellChecker::spellCheckOldSelection(const VisibleSelection& oldSelection, const VisibleSelection& newAdjacentWords, const VisibleSelection& newSelectedSentence)
+{
+ VisiblePosition oldStart(oldSelection.visibleStart());
+ VisibleSelection oldAdjacentWords = VisibleSelection(startOfWord(oldStart, LeftWordIfOnBoundary), endOfWord(oldStart, RightWordIfOnBoundary));
+ if (oldAdjacentWords != newAdjacentWords) {
+ if (isContinuousSpellCheckingEnabled() && isGrammarCheckingEnabled()) {
+ VisibleSelection selectedSentence = VisibleSelection(startOfSentence(oldStart), endOfSentence(oldStart));
+ markMisspellingsAndBadGrammar(oldAdjacentWords, true, selectedSentence);
+ } else {
+ markMisspellingsAndBadGrammar(oldAdjacentWords, false, oldAdjacentWords);
+ }
+ }
+}
+
+static Node* findFirstMarkable(Node* node)
+{
+ while (node) {
+ if (!node->renderer())
+ return 0;
+ if (node->renderer()->isText())
+ return node;
+ if (node->renderer()->isTextControl())
+ node = toRenderTextControl(node->renderer())->textFormControlElement()->visiblePositionForIndex(1).deepEquivalent().deprecatedNode();
+ else if (node->firstChild())
+ node = node->firstChild();
+ else
+ node = node->nextSibling();
+ }
+
+ return 0;
+}
+
+bool SpellChecker::selectionStartHasMarkerFor(DocumentMarker::MarkerType markerType, int from, int length) const
+{
+ Node* node = findFirstMarkable(m_frame.selection().start().deprecatedNode());
+ if (!node)
+ return false;
+
+ unsigned startOffset = static_cast<unsigned>(from);
+ unsigned endOffset = static_cast<unsigned>(from + length);
+ Vector<DocumentMarker*> markers = m_frame.document()->markers()->markersFor(node);
+ for (size_t i = 0; i < markers.size(); ++i) {
+ DocumentMarker* marker = markers[i];
+ if (marker->startOffset() <= startOffset && endOffset <= marker->endOffset() && marker->type() == markerType)
+ return true;
+ }
+
+ return false;
+}
+
+TextCheckingTypeMask SpellChecker::resolveTextCheckingTypeMask(TextCheckingTypeMask textCheckingOptions)
+{
+ bool shouldMarkSpelling = textCheckingOptions & TextCheckingTypeSpelling;
+ bool shouldMarkGrammar = textCheckingOptions & TextCheckingTypeGrammar;
+
+ TextCheckingTypeMask checkingTypes = 0;
+ if (shouldMarkSpelling)
+ checkingTypes |= TextCheckingTypeSpelling;
+ if (shouldMarkGrammar)
+ checkingTypes |= TextCheckingTypeGrammar;
+
+ return checkingTypes;
+}
+
+bool SpellChecker::unifiedTextCheckerEnabled() const
+{
+ return WebCore::unifiedTextCheckerEnabled(&m_frame);
+}
+
+void SpellChecker::cancelCheck()
+{
+ m_spellCheckRequester->cancelCheck();
+}
+
+void SpellChecker::requestTextChecking(const Element& element)
+{
+ RefPtr<Range> rangeToCheck = rangeOfContents(const_cast<Element*>(&element));
+ m_spellCheckRequester->requestCheckingFor(SpellCheckRequest::create(TextCheckingTypeSpelling | TextCheckingTypeGrammar, TextCheckingProcessBatch, rangeToCheck, rangeToCheck));
+}
+
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/editing/SpellChecker.h b/chromium/third_party/WebKit/Source/core/editing/SpellChecker.h
new file mode 100644
index 00000000000..009cca135a7
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/editing/SpellChecker.h
@@ -0,0 +1,104 @@
+/*
+ * Copyright (C) 2006, 2007, 2008 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SpellChecker_h
+#define SpellChecker_h
+
+#include "core/dom/ClipboardAccessPolicy.h"
+#include "core/dom/DocumentMarker.h"
+#include "core/editing/FrameSelection.h"
+#include "core/editing/VisibleSelection.h"
+#include "platform/text/TextChecking.h"
+
+namespace WebCore {
+
+class Frame;
+class SpellCheckerClient;
+class SpellCheckRequest;
+class SpellCheckRequester;
+class TextCheckerClient;
+class TextCheckingParagraph;
+struct TextCheckingResult;
+
+class SpellChecker {
+ WTF_MAKE_NONCOPYABLE(SpellChecker);
+public:
+ static PassOwnPtr<SpellChecker> create(Frame&);
+
+ ~SpellChecker();
+
+ SpellCheckerClient& spellCheckerClient() const;
+ TextCheckerClient& textChecker() const;
+
+ bool isContinuousSpellCheckingEnabled() const;
+ void toggleContinuousSpellChecking();
+ bool isGrammarCheckingEnabled();
+ void ignoreSpelling();
+ String misspelledWordAtCaretOrRange(Node* clickedNode) const;
+ bool isSpellCheckingEnabledInFocusedNode() const;
+ bool isSpellCheckingEnabledFor(Node*) const;
+ void markMisspellingsAfterTypingToWord(const VisiblePosition &wordStart, const VisibleSelection& selectionAfterTyping);
+ void markMisspellings(const VisibleSelection&, RefPtr<Range>& firstMisspellingRange);
+ void markBadGrammar(const VisibleSelection&);
+ void markMisspellingsAndBadGrammar(const VisibleSelection& spellingSelection, bool markGrammar, const VisibleSelection& grammarSelection);
+ void markAndReplaceFor(PassRefPtr<SpellCheckRequest>, const Vector<TextCheckingResult>&);
+ void markAllMisspellingsAndBadGrammarInRanges(TextCheckingTypeMask, Range* spellingRange, Range* grammarRange);
+ void advanceToNextMisspelling(bool startBeforeSelection = false);
+ void showSpellingGuessPanel();
+ void didBeginEditing(Element*);
+ void clearMisspellingsAndBadGrammar(const VisibleSelection&);
+ void markMisspellingsAndBadGrammar(const VisibleSelection&);
+ void respondToChangedSelection(const VisibleSelection& oldSelection, FrameSelection::SetSelectionOptions);
+ void spellCheckAfterBlur();
+ void spellCheckOldSelection(const VisibleSelection& oldSelection, const VisibleSelection& newAdjacentWords, const VisibleSelection& newSelectedSentence);
+
+ void didEndEditingOnTextField(Element*);
+ bool selectionStartHasMarkerFor(DocumentMarker::MarkerType, int from, int length) const;
+ void updateMarkersForWordsAffectedByEditing(bool onlyHandleWordsContainingSelection);
+ void cancelCheck();
+ void chunkAndMarkAllMisspellingsAndBadGrammar(Node*);
+ void requestTextChecking(const Element&);
+
+ // Exposed for testing only
+ SpellCheckRequester& spellCheckRequester() const { return *m_spellCheckRequester; }
+
+private:
+ Frame& m_frame;
+ const OwnPtr<SpellCheckRequester> m_spellCheckRequester;
+
+ explicit SpellChecker(Frame&);
+
+ void markMisspellingsOrBadGrammar(const VisibleSelection&, bool checkSpelling, RefPtr<Range>& firstMisspellingRange);
+ TextCheckingTypeMask resolveTextCheckingTypeMask(TextCheckingTypeMask);
+
+ bool unifiedTextCheckerEnabled() const;
+
+ void chunkAndMarkAllMisspellingsAndBadGrammar(TextCheckingTypeMask textCheckingOptions, const TextCheckingParagraph& fullParagraphToCheck, bool asynchronous);
+ void markAllMisspellingsAndBadGrammarInRanges(TextCheckingTypeMask textCheckingOptions, Range* checkingRange, Range* paragraphRange, bool asynchronous, int requestNumber, int* checkingLength = 0);
+};
+
+} // namespace WebCore
+
+#endif // SpellChecker_h
diff --git a/chromium/third_party/WebKit/Source/core/editing/SpellingCorrectionCommand.cpp b/chromium/third_party/WebKit/Source/core/editing/SpellingCorrectionCommand.cpp
index e89b81af44b..cc73001b77c 100644
--- a/chromium/third_party/WebKit/Source/core/editing/SpellingCorrectionCommand.cpp
+++ b/chromium/third_party/WebKit/Source/core/editing/SpellingCorrectionCommand.cpp
@@ -30,7 +30,7 @@
#include "core/editing/InsertTextCommand.h"
#include "core/editing/SetSelectionCommand.h"
#include "core/editing/TextIterator.h"
-#include "core/page/Frame.h"
+#include "core/frame/Frame.h"
namespace WebCore {
@@ -48,9 +48,6 @@ void SpellingCorrectionCommand::doApply()
if (!m_corrected.length())
return;
- if (!document().frame()->selection().shouldChangeSelection(m_selectionToBeCorrected))
- return;
-
applyCommandToComposite(SetSelectionCommand::create(m_selectionToBeCorrected, FrameSelection::SpellCorrectionTriggered | FrameSelection::CloseTyping | FrameSelection::ClearTypingStyle));
applyCommandToComposite(InsertTextCommand::create(document(), m_correction));
}
diff --git a/chromium/third_party/WebKit/Source/core/editing/SplitElementCommand.cpp b/chromium/third_party/WebKit/Source/core/editing/SplitElementCommand.cpp
index e4227cad726..128c37097ed 100644
--- a/chromium/third_party/WebKit/Source/core/editing/SplitElementCommand.cpp
+++ b/chromium/third_party/WebKit/Source/core/editing/SplitElementCommand.cpp
@@ -53,13 +53,13 @@ void SplitElementCommand::executeApply()
for (Node* node = m_element2->firstChild(); node != m_atChild; node = node->nextSibling())
children.append(node);
- TrackExceptionState es;
+ TrackExceptionState exceptionState;
ContainerNode* parent = m_element2->parentNode();
if (!parent || !parent->rendererIsEditable())
return;
- parent->insertBefore(m_element1.get(), m_element2.get(), es);
- if (es.hadException())
+ parent->insertBefore(m_element1.get(), m_element2.get(), exceptionState);
+ if (exceptionState.hadException())
return;
// Delete id attribute from the second element because the same id cannot be used for more than one element
@@ -67,7 +67,7 @@ void SplitElementCommand::executeApply()
size_t size = children.size();
for (size_t i = 0; i < size; ++i)
- m_element1->appendChild(children[i], es);
+ m_element1->appendChild(children[i], exceptionState);
}
void SplitElementCommand::doApply()
diff --git a/chromium/third_party/WebKit/Source/core/editing/SplitTextNodeCommand.cpp b/chromium/third_party/WebKit/Source/core/editing/SplitTextNodeCommand.cpp
index b28147bf918..34086598049 100644
--- a/chromium/third_party/WebKit/Source/core/editing/SplitTextNodeCommand.cpp
+++ b/chromium/third_party/WebKit/Source/core/editing/SplitTextNodeCommand.cpp
@@ -72,7 +72,7 @@ void SplitTextNodeCommand::doUnapply()
if (!m_text1 || !m_text1->rendererIsEditable())
return;
- ASSERT(&m_text1->document() == &document());
+ ASSERT(m_text1->document() == document());
String prefixText = m_text1->data();
@@ -96,11 +96,11 @@ void SplitTextNodeCommand::doReapply()
void SplitTextNodeCommand::insertText1AndTrimText2()
{
- TrackExceptionState es;
- m_text2->parentNode()->insertBefore(m_text1.get(), m_text2.get(), es);
- if (es.hadException())
+ TrackExceptionState exceptionState;
+ m_text2->parentNode()->insertBefore(m_text1.get(), m_text2.get(), exceptionState);
+ if (exceptionState.hadException())
return;
- m_text2->deleteData(0, m_offset, es, CharacterData::DeprecatedRecalcStyleImmediatlelyForEditing);
+ m_text2->deleteData(0, m_offset, exceptionState, CharacterData::DeprecatedRecalcStyleImmediatlelyForEditing);
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/editing/TextCheckingHelper.cpp b/chromium/third_party/WebKit/Source/core/editing/TextCheckingHelper.cpp
index 33471b3344e..091585afd09 100644
--- a/chromium/third_party/WebKit/Source/core/editing/TextCheckingHelper.cpp
+++ b/chromium/third_party/WebKit/Source/core/editing/TextCheckingHelper.cpp
@@ -35,10 +35,11 @@
#include "core/editing/TextIterator.h"
#include "core/editing/VisiblePosition.h"
#include "core/editing/VisibleUnits.h"
-#include "core/page/Frame.h"
-#include "core/page/Settings.h"
-#include "core/platform/text/TextBreakIterator.h"
-#include "core/platform/text/TextCheckerClient.h"
+#include "core/frame/Frame.h"
+#include "core/frame/Settings.h"
+#include "core/page/SpellCheckerClient.h"
+#include "platform/text/TextBreakIterator.h"
+#include "platform/text/TextCheckerClient.h"
namespace WebCore {
@@ -57,7 +58,7 @@ static void findBadGrammars(TextCheckerClient& client, const UChar* text, int st
ASSERT(0 <= badGrammarLocation && badGrammarLocation <= checkLength);
ASSERT(0 < badGrammarLength && badGrammarLocation + badGrammarLength <= checkLength);
TextCheckingResult badGrammar;
- badGrammar.type = TextCheckingTypeGrammar;
+ badGrammar.decoration = TextDecorationTypeGrammar;
badGrammar.location = checkLocation + badGrammarLocation;
badGrammar.length = badGrammarLength;
badGrammar.details.swap(badGrammarDetails);
@@ -73,9 +74,9 @@ static void findMisspellings(TextCheckerClient& client, const UChar* text, int s
TextBreakIterator* iterator = wordBreakIterator(text + start, length);
if (!iterator)
return;
- int wordStart = textBreakCurrent(iterator);
+ int wordStart = iterator->current();
while (0 <= wordStart) {
- int wordEnd = textBreakNext(iterator);
+ int wordEnd = iterator->next();
if (wordEnd < 0)
break;
int wordLength = wordEnd - wordStart;
@@ -86,7 +87,7 @@ static void findMisspellings(TextCheckerClient& client, const UChar* text, int s
ASSERT(0 <= misspellingLocation && misspellingLocation <= wordLength);
ASSERT(0 < misspellingLength && misspellingLocation + misspellingLength <= wordLength);
TextCheckingResult misspelling;
- misspelling.type = TextCheckingTypeSpelling;
+ misspelling.decoration = TextDecorationTypeSpelling;
misspelling.location = start + wordStart + misspellingLocation;
misspelling.length = misspellingLength;
misspelling.replacement = client.getAutoCorrectSuggestionForMisspelledWord(String(text + misspelling.location, misspelling.length));
@@ -160,12 +161,12 @@ PassRefPtr<Range> TextCheckingParagraph::subrange(int characterOffset, int chara
return TextIterator::subrange(paragraphRange().get(), characterOffset, characterCount);
}
-int TextCheckingParagraph::offsetTo(const Position& position, ExceptionState& es) const
+int TextCheckingParagraph::offsetTo(const Position& position, ExceptionState& exceptionState) const
{
ASSERT(m_checkingRange);
RefPtr<Range> range = offsetAsRange()->cloneRange(ASSERT_NO_EXCEPTION);
- range->setEnd(position.containerNode(), position.computeOffsetInContainerNode(), es);
- if (es.hadException())
+ range->setEnd(position.containerNode(), position.computeOffsetInContainerNode(), exceptionState);
+ if (exceptionState.hadException())
return 0;
return TextIterator::rangeLength(range.get());
}
@@ -218,7 +219,7 @@ int TextCheckingParagraph::checkingLength() const
return m_checkingLength;
}
-TextCheckingHelper::TextCheckingHelper(EditorClient& client, PassRefPtr<Range> range)
+TextCheckingHelper::TextCheckingHelper(SpellCheckerClient& client, PassRefPtr<Range> range)
: m_client(&client)
, m_range(range)
{
@@ -343,14 +344,14 @@ String TextCheckingHelper::findFirstMisspellingOrBadGrammar(bool checkGrammar, b
for (unsigned i = 0; i < results.size(); i++) {
const TextCheckingResult* result = &results[i];
- if (result->type == TextCheckingTypeSpelling && result->location >= currentStartOffset && result->location + result->length <= currentEndOffset) {
+ if (result->decoration == TextDecorationTypeSpelling && result->location >= currentStartOffset && result->location + result->length <= currentEndOffset) {
ASSERT(result->length > 0 && result->location >= 0);
spellingLocation = result->location;
misspelledWord = paragraphString.substring(result->location, result->length);
ASSERT(misspelledWord.length());
break;
}
- if (checkGrammar && result->type == TextCheckingTypeGrammar && result->location < currentEndOffset && result->location + result->length > currentStartOffset) {
+ if (checkGrammar && result->decoration == TextDecorationTypeGrammar && result->location < currentEndOffset && result->location + result->length > currentStartOffset) {
ASSERT(result->length > 0 && result->location >= 0);
// We can't stop after the first grammar result, since there might still be a spelling result after
// it begins but before the first detail in it, but we can stop if we find a second grammar result.
diff --git a/chromium/third_party/WebKit/Source/core/editing/TextCheckingHelper.h b/chromium/third_party/WebKit/Source/core/editing/TextCheckingHelper.h
index cd1bc09a455..a69116e3345 100644
--- a/chromium/third_party/WebKit/Source/core/editing/TextCheckingHelper.h
+++ b/chromium/third_party/WebKit/Source/core/editing/TextCheckingHelper.h
@@ -21,15 +21,17 @@
#ifndef TextCheckingHelper_h
#define TextCheckingHelper_h
-#include "core/page/EditorClient.h"
-#include "core/platform/text/TextChecking.h"
+#include "platform/text/TextChecking.h"
#include "wtf/text/WTFString.h"
namespace WebCore {
class ExceptionState;
+class Frame;
class Range;
class Position;
+class SpellCheckerClient;
+class TextCheckerClient;
struct TextCheckingResult;
class TextCheckingParagraph {
@@ -77,7 +79,7 @@ private:
class TextCheckingHelper {
WTF_MAKE_NONCOPYABLE(TextCheckingHelper);
public:
- TextCheckingHelper(EditorClient&, PassRefPtr<Range>);
+ TextCheckingHelper(SpellCheckerClient&, PassRefPtr<Range>);
~TextCheckingHelper();
String findFirstMisspelling(int& firstMisspellingOffset, bool markAll, RefPtr<Range>& firstMisspellingRange);
@@ -87,7 +89,7 @@ public:
void markAllBadGrammar();
private:
- EditorClient* m_client;
+ SpellCheckerClient* m_client;
RefPtr<Range> m_range;
int findFirstGrammarDetail(const Vector<GrammarDetail>& grammarDetails, int badGrammarPhraseLocation, int startOffset, int endOffset, bool markAll) const;
diff --git a/chromium/third_party/WebKit/Source/core/editing/TextInsertionBaseCommand.cpp b/chromium/third_party/WebKit/Source/core/editing/TextInsertionBaseCommand.cpp
index 380b27f3c49..918bf755cb8 100644
--- a/chromium/third_party/WebKit/Source/core/editing/TextInsertionBaseCommand.cpp
+++ b/chromium/third_party/WebKit/Source/core/editing/TextInsertionBaseCommand.cpp
@@ -27,11 +27,11 @@
#include "core/editing/TextInsertionBaseCommand.h"
#include "bindings/v8/ExceptionStatePlaceholder.h"
-#include "core/dom/BeforeTextInsertedEvent.h"
+#include "core/events/BeforeTextInsertedEvent.h"
#include "core/dom/Element.h"
#include "core/dom/Node.h"
#include "core/editing/FrameSelection.h"
-#include "core/page/Frame.h"
+#include "core/frame/Frame.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/editing/TextIterator.cpp b/chromium/third_party/WebKit/Source/core/editing/TextIterator.cpp
index 668fde6021b..5fbb4e3f4b1 100644
--- a/chromium/third_party/WebKit/Source/core/editing/TextIterator.cpp
+++ b/chromium/third_party/WebKit/Source/core/editing/TextIterator.cpp
@@ -31,22 +31,22 @@
#include "bindings/v8/ExceptionStatePlaceholder.h"
#include "core/dom/Document.h"
#include "core/dom/NodeTraversal.h"
-#include "core/dom/Range.h"
#include "core/dom/shadow/ShadowRoot.h"
#include "core/editing/VisiblePosition.h"
#include "core/editing/VisibleUnits.h"
#include "core/editing/htmlediting.h"
#include "core/html/HTMLElement.h"
#include "core/html/HTMLTextFormControlElement.h"
-#include "core/platform/graphics/Font.h"
-#include "core/platform/text/TextBoundaries.h"
-#include "core/platform/text/TextBreakIteratorInternalICU.h"
#include "core/rendering/InlineTextBox.h"
#include "core/rendering/RenderImage.h"
#include "core/rendering/RenderTableCell.h"
#include "core/rendering/RenderTableRow.h"
#include "core/rendering/RenderTextControl.h"
#include "core/rendering/RenderTextFragment.h"
+#include "platform/fonts/Font.h"
+#include "platform/text/TextBoundaries.h"
+#include "platform/text/TextBreakIteratorInternalICU.h"
+#include "platform/text/UnicodeUtilities.h"
#include "wtf/text/CString.h"
#include "wtf/text/StringBuilder.h"
#include "wtf/unicode/CharacterNames.h"
@@ -206,6 +206,15 @@ static void pushFullyClippedState(BitStack& stack, Node* node)
{
ASSERT(stack.size() == depthCrossingShadowBoundaries(node));
+ // FIXME: m_fullyClippedStack was added in response to <https://bugs.webkit.org/show_bug.cgi?id=26364>
+ // ("Search can find text that's hidden by overflow:hidden"), but the logic here will not work correctly if
+ // a shadow tree redistributes nodes. m_fullyClippedStack relies on the assumption that DOM node hierarchy matches
+ // the render tree, which is not necessarily true if there happens to be shadow DOM distribution or other mechanics
+ // that shuffle around the render objects regardless of node tree hierarchy (like CSS flexbox).
+ //
+ // A more appropriate way to handle this situation is to detect overflow:hidden blocks by using only rendering
+ // primitives, not with DOM primitives.
+
// Push true if this node full clips its contents, or if a parent already has fully
// clipped and this is not a node that ignores its container's clip.
stack.push(fullyClipsContents(node) || (stack.top() && !ignoresContainerClip(node)));
@@ -229,8 +238,9 @@ static void setUpFullyClippedStack(BitStack& stack, Node* node)
// --------
-TextIterator::TextIterator(const Range* r, TextIteratorBehavior behavior)
- : m_startContainer(0)
+TextIterator::TextIterator(const Range* range, TextIteratorBehaviorFlags behavior)
+ : m_shadowDepth(0)
+ , m_startContainer(0)
, m_startOffset(0)
, m_endContainer(0)
, m_endOffset(0)
@@ -241,29 +251,28 @@ TextIterator::TextIterator(const Range* r, TextIteratorBehavior behavior)
, m_sortedTextBoxesPosition(0)
, m_emitsCharactersBetweenAllVisiblePositions(behavior & TextIteratorEmitsCharactersBetweenAllVisiblePositions)
, m_entersTextControls(behavior & TextIteratorEntersTextControls)
- , m_emitsTextWithoutTranscoding(behavior & TextIteratorEmitsTextsWithoutTranscoding)
, m_emitsOriginalText(behavior & TextIteratorEmitsOriginalText)
, m_handledFirstLetter(false)
, m_ignoresStyleVisibility(behavior & TextIteratorIgnoresStyleVisibility)
- , m_emitsObjectReplacementCharacters(behavior & TextIteratorEmitsObjectReplacementCharacters)
, m_stopsOnFormControls(behavior & TextIteratorStopsOnFormControls)
, m_shouldStop(false)
, m_emitsImageAltText(behavior & TextIteratorEmitsImageAltText)
+ , m_entersAuthorShadowRoots(behavior & TextIteratorEntersAuthorShadowRoots)
{
- if (!r)
+ if (!range)
return;
// get and validate the range endpoints
- Node* startContainer = r->startContainer();
+ Node* startContainer = range->startContainer();
if (!startContainer)
return;
- int startOffset = r->startOffset();
- Node* endContainer = r->endContainer();
- int endOffset = r->endOffset();
+ int startOffset = range->startOffset();
+ Node* endContainer = range->endContainer();
+ int endOffset = range->endOffset();
// Callers should be handing us well-formed ranges. If we discover that this isn't
// the case, we could consider changing this assertion to an early return.
- ASSERT(r->boundaryPointsValid());
+ ASSERT(range->boundaryPointsValid());
// remember range - this does not change
m_startContainer = startContainer;
@@ -272,13 +281,12 @@ TextIterator::TextIterator(const Range* r, TextIteratorBehavior behavior)
m_endOffset = endOffset;
// set up the current node for processing
- m_node = r->firstNode();
+ m_node = range->firstNode();
if (!m_node)
return;
setUpFullyClippedStack(m_fullyClippedStack, m_node);
m_offset = m_node == m_startContainer ? m_startOffset : 0;
- m_handledNode = false;
- m_handledChildren = false;
+ m_iterationProgress = HandledNone;
// calculate first out of bounds node
m_pastEndNode = nextInPreOrderCrossingShadowBoundaries(endContainer, endOffset);
@@ -293,11 +301,6 @@ TextIterator::TextIterator(const Range* r, TextIteratorBehavior behavior)
m_lastTextNodeEndedWithCollapsedSpace = false;
m_lastCharacter = 0;
-#ifndef NDEBUG
- // need this just because of the assert in advance()
- m_positionNode = m_node;
-#endif
-
// identify the first run
advance();
}
@@ -319,7 +322,7 @@ void TextIterator::advance()
if (m_needsAnotherNewline) {
// Emit the extra newline, and position it *inside* m_node, after m_node's
// contents, in case it's a block, in the same way that we position the first
- // newline. The range for the emitted newline should start where the line
+ // newline. The range for the emitted newline should start where the line
// break begins.
// FIXME: It would be cleaner if we emitted two newlines during the last
// iteration, instead of using m_needsAnotherNewline.
@@ -342,7 +345,7 @@ void TextIterator::advance()
return;
}
- while (m_node && m_node != m_pastEndNode) {
+ while (m_node && (m_node != m_pastEndNode || m_shadowDepth > 0)) {
if (!m_shouldStop && m_stopsOnFormControls && HTMLFormControlElement::enclosingFormControlElement(m_node))
m_shouldStop = true;
@@ -350,7 +353,7 @@ void TextIterator::advance()
// position, but not the content, of that element e.g. if the
// node is a blockflow element, emit a newline that
// precedes the element
- if (m_node == m_endContainer && m_endOffset == 0) {
+ if (m_node == m_endContainer && !m_endOffset) {
representNodeOffsetZero();
m_node = 0;
return;
@@ -358,52 +361,124 @@ void TextIterator::advance()
RenderObject* renderer = m_node->renderer();
if (!renderer) {
- m_handledNode = true;
- m_handledChildren = true;
+ if (m_node->isShadowRoot()) {
+ // A shadow root doesn't have a renderer, but we want to visit children anyway.
+ m_iterationProgress = m_iterationProgress < HandledNode ? HandledNode : m_iterationProgress;
+ } else {
+ m_iterationProgress = HandledChildren;
+ }
} else {
- // handle current node according to its type
- if (!m_handledNode) {
- if (renderer->isText() && m_node->nodeType() == Node::TEXT_NODE) // FIXME: What about CDATA_SECTION_NODE?
- m_handledNode = handleTextNode();
- else if (renderer && (renderer->isImage() || renderer->isWidget() ||
- (renderer->node() && renderer->node()->isElementNode() &&
- (toElement(renderer->node())->isFormControlElement()
- || toElement(renderer->node())->hasTagName(legendTag)
- || toElement(renderer->node())->hasTagName(meterTag)
- || toElement(renderer->node())->hasTagName(progressTag)))))
- m_handledNode = handleReplacedElement();
- else
- m_handledNode = handleNonTextNode();
+ // Enter author shadow roots, from youngest, if any and if necessary.
+ if (m_iterationProgress < HandledAuthorShadowRoots) {
+ if (m_entersAuthorShadowRoots && m_node->isElementNode() && toElement(m_node)->hasAuthorShadowRoot()) {
+ ShadowRoot* youngestShadowRoot = toElement(m_node)->shadowRoot();
+ ASSERT(youngestShadowRoot->type() == ShadowRoot::AuthorShadowRoot);
+ m_node = youngestShadowRoot;
+ m_iterationProgress = HandledNone;
+ ++m_shadowDepth;
+ pushFullyClippedState(m_fullyClippedStack, m_node);
+ continue;
+ }
+
+ m_iterationProgress = HandledAuthorShadowRoots;
+ }
+
+ // Enter user-agent shadow root, if necessary.
+ if (m_iterationProgress < HandledUserAgentShadowRoot) {
+ if (m_entersTextControls && renderer->isTextControl()) {
+ ShadowRoot* userAgentShadowRoot = toElement(m_node)->userAgentShadowRoot();
+ ASSERT(userAgentShadowRoot->type() == ShadowRoot::UserAgentShadowRoot);
+ m_node = userAgentShadowRoot;
+ m_iterationProgress = HandledNone;
+ ++m_shadowDepth;
+ pushFullyClippedState(m_fullyClippedStack, m_node);
+ continue;
+ }
+ m_iterationProgress = HandledUserAgentShadowRoot;
+ }
+
+ // Handle the current node according to its type.
+ if (m_iterationProgress < HandledNode) {
+ bool handledNode = false;
+ if (renderer->isText() && m_node->nodeType() == Node::TEXT_NODE) { // FIXME: What about CDATA_SECTION_NODE?
+ handledNode = handleTextNode();
+ } else if (renderer && (renderer->isImage() || renderer->isWidget()
+ || (renderer->node() && renderer->node()->isElementNode()
+ && (toElement(renderer->node())->isFormControlElement()
+ || toElement(renderer->node())->hasTagName(legendTag)
+ || toElement(renderer->node())->hasTagName(meterTag)
+ || toElement(renderer->node())->hasTagName(progressTag))))) {
+ handledNode = handleReplacedElement();
+ } else {
+ handledNode = handleNonTextNode();
+ }
+ if (handledNode)
+ m_iterationProgress = HandledNode;
if (m_positionNode)
return;
}
}
- // find a new current node to handle in depth-first manner,
- // calling exitNode() as we come back thru a parent node
- Node* next = m_handledChildren ? 0 : m_node->firstChild();
+ // Find a new current node to handle in depth-first manner,
+ // calling exitNode() as we come back thru a parent node.
+ //
+ // 1. Iterate over child nodes, if we haven't done yet.
+ Node* next = m_iterationProgress < HandledChildren ? m_node->firstChild() : 0;
m_offset = 0;
if (!next) {
+ // 2. If we've already iterated children or they are not available, go to the next sibling node.
next = m_node->nextSibling();
if (!next) {
- bool pastEnd = NodeTraversal::next(m_node) == m_pastEndNode;
- Node* parentNode = m_node->parentOrShadowHostNode();
+ // 3. If we are at the last child, go up the node tree until we find a next sibling.
+ bool pastEnd = NodeTraversal::next(*m_node) == m_pastEndNode;
+ Node* parentNode = m_node->parentNode();
while (!next && parentNode) {
if ((pastEnd && parentNode == m_endContainer) || m_endContainer->isDescendantOf(parentNode))
return;
bool haveRenderer = m_node->renderer();
m_node = parentNode;
m_fullyClippedStack.pop();
- parentNode = m_node->parentOrShadowHostNode();
+ parentNode = m_node->parentNode();
if (haveRenderer)
exitNode();
if (m_positionNode) {
- m_handledNode = true;
- m_handledChildren = true;
+ m_iterationProgress = HandledChildren;
return;
}
next = m_node->nextSibling();
}
+
+ if (!next && !parentNode && m_shadowDepth > 0) {
+ // 4. Reached the top of a shadow root. If it's created by author, then try to visit the next
+ // sibling shadow root, if any.
+ ShadowRoot* shadowRoot = toShadowRoot(m_node);
+ if (shadowRoot->type() == ShadowRoot::AuthorShadowRoot) {
+ ShadowRoot* nextShadowRoot = shadowRoot->olderShadowRoot();
+ if (nextShadowRoot && nextShadowRoot->type() == ShadowRoot::AuthorShadowRoot) {
+ m_fullyClippedStack.pop();
+ m_node = nextShadowRoot;
+ m_iterationProgress = HandledNone;
+ // m_shadowDepth is unchanged since we exit from a shadow root and enter another.
+ pushFullyClippedState(m_fullyClippedStack, m_node);
+ } else {
+ // We are the last shadow root; exit from here and go back to where we were.
+ m_node = shadowRoot->host();
+ m_iterationProgress = HandledAuthorShadowRoots;
+ --m_shadowDepth;
+ m_fullyClippedStack.pop();
+ }
+ } else {
+ // If we are in a user-agent shadow root, then go back to the host.
+ ASSERT(shadowRoot->type() == ShadowRoot::UserAgentShadowRoot);
+ m_node = shadowRoot->host();
+ m_iterationProgress = HandledUserAgentShadowRoot;
+ --m_shadowDepth;
+ m_fullyClippedStack.pop();
+ }
+ m_handledFirstLetter = false;
+ m_firstLetterText = 0;
+ continue;
+ }
}
m_fullyClippedStack.pop();
}
@@ -412,8 +487,7 @@ void TextIterator::advance()
m_node = next;
if (m_node)
pushFullyClippedState(m_fullyClippedStack, m_node);
- m_handledNode = false;
- m_handledChildren = false;
+ m_iterationProgress = HandledNone;
m_handledFirstLetter = false;
m_firstLetterText = 0;
@@ -440,7 +514,7 @@ UChar TextIterator::characterAt(unsigned index) const
String TextIterator::substring(unsigned position, unsigned length) const
{
- ASSERT_WITH_SECURITY_IMPLICATION(position < static_cast<unsigned>(this->length()));
+ ASSERT_WITH_SECURITY_IMPLICATION(position <= static_cast<unsigned>(this->length()));
ASSERT_WITH_SECURITY_IMPLICATION(position + length <= static_cast<unsigned>(this->length()));
if (!length)
return emptyString();
@@ -483,7 +557,7 @@ bool TextIterator::handleTextNode()
return false;
}
if (!m_handledFirstLetter && renderer->isTextFragment() && !m_offset) {
- handleTextNodeFirstLetter(static_cast<RenderTextFragment*>(renderer));
+ handleTextNodeFirstLetter(toRenderTextFragment(renderer));
if (m_firstLetterText) {
String firstLetter = m_firstLetterText->text();
emitText(m_node, m_firstLetterText, m_offset, m_offset + firstLetter.length());
@@ -510,7 +584,7 @@ bool TextIterator::handleTextNode()
bool shouldHandleFirstLetter = !m_handledFirstLetter && renderer->isTextFragment() && !m_offset;
if (shouldHandleFirstLetter)
- handleTextNodeFirstLetter(static_cast<RenderTextFragment*>(renderer));
+ handleTextNodeFirstLetter(toRenderTextFragment(renderer));
if (!renderer->firstTextBox() && str.length() > 0 && !shouldHandleFirstLetter) {
if (renderer->style()->visibility() != VISIBLE && !m_ignoresStyleVisibility)
@@ -561,8 +635,9 @@ void TextIterator::handleTextBox()
while (spaceRunStart > 0 && str[spaceRunStart - 1] == ' ')
--spaceRunStart;
emitText(m_node, renderer, spaceRunStart, spaceRunStart + 1);
- } else
+ } else {
emitCharacter(' ', m_node, 0, runStart, runStart);
+ }
return;
}
unsigned textBoxEnd = textBoxStart + m_textBox->len();
@@ -573,8 +648,9 @@ void TextIterator::handleTextBox()
if (renderer->containsReversedText()) {
if (m_sortedTextBoxesPosition + 1 < m_sortedTextBoxes.size())
nextTextBox = m_sortedTextBoxes[m_sortedTextBoxesPosition + 1];
- } else
+ } else {
nextTextBox = m_textBox->nextTextBox();
+ }
ASSERT(!nextTextBox || nextTextBox->renderer() == renderer);
if (runStart < runEnd) {
@@ -666,21 +742,12 @@ bool TextIterator::handleReplacedElement()
}
if (m_entersTextControls && renderer->isTextControl()) {
- if (HTMLElement* innerTextElement = toRenderTextControl(renderer)->textFormControlElement()->innerTextElement()) {
- m_node = innerTextElement->containingShadowRoot();
- pushFullyClippedState(m_fullyClippedStack, m_node);
- m_offset = 0;
- return false;
- }
+ // The shadow tree should be already visited.
+ return true;
}
m_hasEmitted = true;
- if (m_emitsObjectReplacementCharacters && renderer && renderer->isReplaced()) {
- emitCharacter(objectReplacementCharacter, m_node->parentNode(), m_node, 0, 1);
- return true;
- }
-
if (m_emitsCharactersBetweenAllVisiblePositions) {
// We want replaced elements to behave like punctuation for boundary
// finding, and to simply take up space for the selection preservation
@@ -715,7 +782,7 @@ bool TextIterator::hasVisibleTextNode(RenderText* renderer)
if (renderer->style()->visibility() == VISIBLE)
return true;
if (renderer->isTextFragment()) {
- RenderTextFragment* fragment = static_cast<RenderTextFragment*>(renderer);
+ RenderTextFragment* fragment = toRenderTextFragment(renderer);
if (fragment->firstLetter() && fragment->firstLetter()->style()->visibility() == VISIBLE)
return true;
}
@@ -745,36 +812,36 @@ static bool shouldEmitNewlineForNode(Node* node, bool emitsOriginalText)
return emitsOriginalText || !(node->isInShadowTree() && node->shadowHost()->hasTagName(inputTag));
}
-static bool shouldEmitNewlinesBeforeAndAfterNode(Node* node)
+static bool shouldEmitNewlinesBeforeAndAfterNode(Node& node)
{
// Block flow (versus inline flow) is represented by having
// a newline both before and after the element.
- RenderObject* r = node->renderer();
+ RenderObject* r = node.renderer();
if (!r) {
- return (node->hasTagName(blockquoteTag)
- || node->hasTagName(ddTag)
- || node->hasTagName(divTag)
- || node->hasTagName(dlTag)
- || node->hasTagName(dtTag)
- || node->hasTagName(h1Tag)
- || node->hasTagName(h2Tag)
- || node->hasTagName(h3Tag)
- || node->hasTagName(h4Tag)
- || node->hasTagName(h5Tag)
- || node->hasTagName(h6Tag)
- || node->hasTagName(hrTag)
- || node->hasTagName(liTag)
- || node->hasTagName(listingTag)
- || node->hasTagName(olTag)
- || node->hasTagName(pTag)
- || node->hasTagName(preTag)
- || node->hasTagName(trTag)
- || node->hasTagName(ulTag));
+ return (node.hasTagName(blockquoteTag)
+ || node.hasTagName(ddTag)
+ || node.hasTagName(divTag)
+ || node.hasTagName(dlTag)
+ || node.hasTagName(dtTag)
+ || node.hasTagName(h1Tag)
+ || node.hasTagName(h2Tag)
+ || node.hasTagName(h3Tag)
+ || node.hasTagName(h4Tag)
+ || node.hasTagName(h5Tag)
+ || node.hasTagName(h6Tag)
+ || node.hasTagName(hrTag)
+ || node.hasTagName(liTag)
+ || node.hasTagName(listingTag)
+ || node.hasTagName(olTag)
+ || node.hasTagName(pTag)
+ || node.hasTagName(preTag)
+ || node.hasTagName(trTag)
+ || node.hasTagName(ulTag));
}
// Need to make an exception for table cells, because they are blocks, but we
// want them tab-delimited rather than having newlines before and after.
- if (isTableCell(node))
+ if (isTableCell(&node))
return false;
// Need to make an exception for table row elements, because they are neither
@@ -789,20 +856,22 @@ static bool shouldEmitNewlinesBeforeAndAfterNode(Node* node)
&& !r->isFloatingOrOutOfFlowPositioned() && !r->isBody() && !r->isRubyText();
}
-static bool shouldEmitNewlineAfterNode(Node* node)
+static bool shouldEmitNewlineAfterNode(Node& node)
{
// FIXME: It should be better but slower to create a VisiblePosition here.
if (!shouldEmitNewlinesBeforeAndAfterNode(node))
return false;
// Check if this is the very last renderer in the document.
// If so, then we should not emit a newline.
- while ((node = NodeTraversal::nextSkippingChildren(node)))
- if (node->renderer())
+ Node* next = &node;
+ while ((next = NodeTraversal::nextSkippingChildren(*next))) {
+ if (next->renderer())
return true;
+ }
return false;
}
-static bool shouldEmitNewlineBeforeNode(Node* node)
+static bool shouldEmitNewlineBeforeNode(Node& node)
{
return shouldEmitNewlinesBeforeAndAfterNode(node);
}
@@ -810,7 +879,7 @@ static bool shouldEmitNewlineBeforeNode(Node* node)
static bool shouldEmitExtraNewlineForNode(Node* node)
{
// When there is a significant collapsed bottom margin, emit an extra
- // newline for a more realistic result. We end up getting the right
+ // newline for a more realistic result. We end up getting the right
// result even without margin collapsing. For example: <div><p>text</p></div>
// will work right even if both the <div> and the <p> have bottom margins.
RenderObject* r = node->renderer();
@@ -863,7 +932,7 @@ static int maxOffsetIncludingCollapsedSpaces(Node* node)
// Whether or not we should emit a character as we enter m_node (if it's a container) or as we hit it (if it's atomic).
bool TextIterator::shouldRepresentNodeOffsetZero()
{
- if (m_emitsCharactersBetweenAllVisiblePositions && m_node->renderer() && m_node->renderer()->isTable())
+ if (m_emitsCharactersBetweenAllVisiblePositions && isRenderedTable(m_node))
return true;
// Leave element positioned flush with start of a paragraph
@@ -898,7 +967,7 @@ bool TextIterator::shouldRepresentNodeOffsetZero()
// so don't second guess that now.
// NOTE: Is this really correct when m_node is not a leftmost descendant? Probably
// immaterial since we likely would have already emitted something by now.
- if (m_startOffset == 0)
+ if (!m_startOffset)
return false;
// If this node is unrendered or invisible the VisiblePosition checks below won't have much meaning.
@@ -919,7 +988,7 @@ bool TextIterator::shouldRepresentNodeOffsetZero()
bool TextIterator::shouldEmitSpaceBeforeAndAfterNode(Node* node)
{
- return node->renderer() && node->renderer()->isTable() && (node->renderer()->isInline() || m_emitsCharactersBetweenAllVisiblePositions);
+ return isRenderedTable(node) && (node->renderer()->isInline() || m_emitsCharactersBetweenAllVisiblePositions);
}
void TextIterator::representNodeOffsetZero()
@@ -927,13 +996,13 @@ void TextIterator::representNodeOffsetZero()
// Emit a character to show the positioning of m_node.
// When we haven't been emitting any characters, shouldRepresentNodeOffsetZero() can
- // create VisiblePositions, which is expensive. So, we perform the inexpensive checks
+ // create VisiblePositions, which is expensive. So, we perform the inexpensive checks
// on m_node to see if it necessitates emitting a character first and will early return
// before encountering shouldRepresentNodeOffsetZero()s worse case behavior.
if (shouldEmitTabBeforeNode(m_node)) {
if (shouldRepresentNodeOffsetZero())
emitCharacter('\t', m_node->parentNode(), m_node, 0, 0);
- } else if (shouldEmitNewlineBeforeNode(m_node)) {
+ } else if (shouldEmitNewlineBeforeNode(*m_node)) {
if (shouldRepresentNodeOffsetZero())
emitCharacter('\n', m_node->parentNode(), m_node, 0, 0);
} else if (shouldEmitSpaceBeforeAndAfterNode(m_node)) {
@@ -968,10 +1037,10 @@ void TextIterator::exitNode()
// emitted character is positioned visually.
Node* baseNode = m_node->lastChild() ? m_node->lastChild() : m_node;
// FIXME: This shouldn't require the m_lastTextNode to be true, but we can't change that without making
- // the logic in _web_attributedStringFromRange match. We'll get that for free when we switch to use
+ // the logic in _web_attributedStringFromRange match. We'll get that for free when we switch to use
// TextIterator in _web_attributedStringFromRange.
// See <rdar://problem/5428427> for an example of how this mismatch will cause problems.
- if (m_lastTextNode && shouldEmitNewlineAfterNode(m_node)) {
+ if (m_lastTextNode && shouldEmitNewlineAfterNode(*m_node)) {
// use extra newline to represent margin bottom, as needed
bool addNewline = shouldEmitExtraNewlineForNode(m_node);
@@ -983,9 +1052,10 @@ void TextIterator::exitNode()
// remember whether to later add a newline for the current node
ASSERT(!m_needsAnotherNewline);
m_needsAnotherNewline = addNewline;
- } else if (addNewline)
+ } else if (addNewline) {
// insert a newline with a position following this block's contents.
emitCharacter('\n', baseNode->parentNode(), baseNode, 1, 1);
+ }
}
// If nothing was emitted, see if we need to emit a space.
@@ -1017,7 +1087,7 @@ void TextIterator::emitCharacter(UChar c, Node* textNode, Node* offsetBaseNode,
void TextIterator::emitText(Node* textNode, RenderObject* renderObject, int textStartOffset, int textEndOffset)
{
RenderText* renderer = toRenderText(renderObject);
- m_text = m_emitsOriginalText ? renderer->originalText() : (m_emitsTextWithoutTranscoding ? renderer->textWithoutTranscoding() : renderer->text());
+ m_text = m_emitsOriginalText ? renderer->originalText() : renderer->text();
ASSERT(!m_text.isEmpty());
ASSERT(0 <= textStartOffset && textStartOffset < static_cast<int>(m_text.length()));
ASSERT(0 <= textEndOffset && textEndOffset <= static_cast<int>(m_text.length()));
@@ -1077,7 +1147,7 @@ Node* TextIterator::node() const
// --------
-SimplifiedBackwardsTextIterator::SimplifiedBackwardsTextIterator(const Range* r, TextIteratorBehavior behavior)
+SimplifiedBackwardsTextIterator::SimplifiedBackwardsTextIterator(const Range* r, TextIteratorBehaviorFlags behavior)
: m_node(0)
, m_offset(0)
, m_handledNode(false)
@@ -1129,7 +1199,7 @@ SimplifiedBackwardsTextIterator::SimplifiedBackwardsTextIterator(const Range* r,
setUpFullyClippedStack(m_fullyClippedStack, m_node);
m_offset = endOffset;
m_handledNode = false;
- m_handledChildren = endOffset == 0;
+ m_handledChildren = !endOffset;
m_startNode = startNode;
m_startOffset = startOffset;
@@ -1166,7 +1236,7 @@ void SimplifiedBackwardsTextIterator::advance()
while (m_node && !m_havePassedStartNode) {
// Don't handle node if we start iterating at [node, 0].
- if (!m_handledNode && !(m_node == m_endNode && m_endOffset == 0)) {
+ if (!m_handledNode && !(m_node == m_endNode && !m_endOffset)) {
RenderObject* renderer = m_node->renderer();
if (renderer && renderer->isText() && m_node->nodeType() == Node::TEXT_NODE) {
// FIXME: What about CDATA_SECTION_NODE?
@@ -1175,8 +1245,9 @@ void SimplifiedBackwardsTextIterator::advance()
} else if (renderer && (renderer->isImage() || renderer->isWidget())) {
if (renderer->style()->visibility() == VISIBLE && m_offset > 0)
m_handledNode = handleReplacedElement();
- } else
+ } else {
m_handledNode = handleNonTextNode();
+ }
if (m_positionNode)
return;
}
@@ -1188,9 +1259,9 @@ void SimplifiedBackwardsTextIterator::advance()
// Exit empty containers as we pass over them or containers
// where [container, 0] is where we started iterating.
if (!m_handledNode
- && canHaveChildrenForEditing(m_node)
- && m_node->parentNode()
- && (!m_node->lastChild() || (m_node == m_endNode && !m_endOffset))) {
+ && canHaveChildrenForEditing(m_node)
+ && m_node->parentNode()
+ && (!m_node->lastChild() || (m_node == m_endNode && !m_endOffset))) {
exitNode();
if (m_positionNode) {
m_handledNode = true;
@@ -1298,7 +1369,7 @@ bool SimplifiedBackwardsTextIterator::handleReplacedElement()
unsigned index = m_node->nodeIndex();
// We want replaced elements to behave like punctuation for boundary
// finding, and to simply take up space for the selection preservation
- // code in moveParagraphs, so we use a comma. Unconditionally emit
+ // code in moveParagraphs, so we use a comma. Unconditionally emit
// here because this iterator is only used for boundary finding.
emitCharacter(',', m_node->parentNode(), index, index + 1);
return true;
@@ -1307,8 +1378,8 @@ bool SimplifiedBackwardsTextIterator::handleReplacedElement()
bool SimplifiedBackwardsTextIterator::handleNonTextNode()
{
// We can use a linefeed in place of a tab because this simple iterator is only used to
- // find boundaries, not actual content. A linefeed breaks words, sentences, and paragraphs.
- if (shouldEmitNewlineForNode(m_node, m_emitsOriginalText) || shouldEmitNewlineAfterNode(m_node) || shouldEmitTabBeforeNode(m_node)) {
+ // find boundaries, not actual content. A linefeed breaks words, sentences, and paragraphs.
+ if (shouldEmitNewlineForNode(m_node, m_emitsOriginalText) || shouldEmitNewlineAfterNode(*m_node) || shouldEmitTabBeforeNode(m_node)) {
unsigned index = m_node->nodeIndex();
// The start of this emitted range is wrong. Ensuring correctness would require
// VisiblePositions and so would be slow. previousBoundary expects this.
@@ -1319,7 +1390,7 @@ bool SimplifiedBackwardsTextIterator::handleNonTextNode()
void SimplifiedBackwardsTextIterator::exitNode()
{
- if (shouldEmitNewlineForNode(m_node, m_emitsOriginalText) || shouldEmitNewlineBeforeNode(m_node) || shouldEmitTabBeforeNode(m_node)) {
+ if (shouldEmitNewlineForNode(m_node, m_emitsOriginalText) || shouldEmitNewlineBeforeNode(*m_node) || shouldEmitTabBeforeNode(m_node)) {
// The start of this emitted range is wrong. Ensuring correctness would require
// VisiblePositions and so would be slow. previousBoundary expects this.
emitCharacter('\n', m_node, 0, 0);
@@ -1358,13 +1429,13 @@ PassRefPtr<Range> SimplifiedBackwardsTextIterator::range() const
// --------
-CharacterIterator::CharacterIterator(const Range* r, TextIteratorBehavior behavior)
+CharacterIterator::CharacterIterator(const Range* r, TextIteratorBehaviorFlags behavior)
: m_offset(0)
, m_runOffset(0)
, m_atBreak(true)
, m_textIterator(r, behavior)
{
- while (!atEnd() && m_textIterator.length() == 0)
+ while (!atEnd() && !m_textIterator.length())
m_textIterator.advance();
}
@@ -1373,7 +1444,7 @@ PassRefPtr<Range> CharacterIterator::range() const
RefPtr<Range> r = m_textIterator.range();
if (!m_textIterator.atEnd()) {
if (m_textIterator.length() <= 1) {
- ASSERT(m_runOffset == 0);
+ ASSERT(!m_runOffset);
} else {
Node* n = r->startContainer();
ASSERT(n == r->endContainer());
@@ -1388,7 +1459,7 @@ PassRefPtr<Range> CharacterIterator::range() const
void CharacterIterator::advance(int count)
{
if (count <= 0) {
- ASSERT(count == 0);
+ ASSERT(!count);
return;
}
@@ -1409,9 +1480,9 @@ void CharacterIterator::advance(int count)
// move to a subsequent m_textIterator run
for (m_textIterator.advance(); !atEnd(); m_textIterator.advance()) {
int runLength = m_textIterator.length();
- if (runLength == 0)
+ if (!runLength) {
m_atBreak = true;
- else {
+ } else {
// see whether this is m_textIterator to use
if (count < runLength) {
m_runOffset = count;
@@ -1457,7 +1528,7 @@ static PassRefPtr<Range> characterSubrange(CharacterIterator& it, int offset, in
end->endContainer(), end->endOffset());
}
-BackwardsCharacterIterator::BackwardsCharacterIterator(const Range* range, TextIteratorBehavior behavior)
+BackwardsCharacterIterator::BackwardsCharacterIterator(const Range* range, TextIteratorBehaviorFlags behavior)
: m_offset(0)
, m_runOffset(0)
, m_atBreak(true)
@@ -1471,9 +1542,9 @@ PassRefPtr<Range> BackwardsCharacterIterator::range() const
{
RefPtr<Range> r = m_textIterator.range();
if (!m_textIterator.atEnd()) {
- if (m_textIterator.length() <= 1)
- ASSERT(m_runOffset == 0);
- else {
+ if (m_textIterator.length() <= 1) {
+ ASSERT(!m_runOffset);
+ } else {
Node* n = r->startContainer();
ASSERT(n == r->endContainer());
int offset = r->endOffset() - m_runOffset;
@@ -1505,9 +1576,9 @@ void BackwardsCharacterIterator::advance(int count)
for (m_textIterator.advance(); !atEnd(); m_textIterator.advance()) {
int runLength = m_textIterator.length();
- if (runLength == 0)
+ if (!runLength) {
m_atBreak = true;
- else {
+ } else {
if (count < runLength) {
m_runOffset = count;
m_offset += count;
@@ -1550,7 +1621,7 @@ void WordAwareIterator::advance()
m_didLookAhead = false;
// Go to next non-empty chunk.
- while (!m_textIterator.atEnd() && m_textIterator.length() == 0)
+ while (!m_textIterator.atEnd() && !m_textIterator.length())
m_textIterator.advance();
m_range = m_textIterator.range();
@@ -1603,32 +1674,6 @@ UChar WordAwareIterator::characterAt(unsigned index) const
// --------
-static inline UChar foldQuoteMarkOrSoftHyphen(UChar c)
-{
- switch (c) {
- case hebrewPunctuationGershayim:
- case leftDoubleQuotationMark:
- case rightDoubleQuotationMark:
- return '"';
- case hebrewPunctuationGeresh:
- case leftSingleQuotationMark:
- case rightSingleQuotationMark:
- return '\'';
- case softHyphen:
- // Replace soft hyphen with an ignorable character so that their presence or absence will
- // not affect string comparison.
- return 0;
- default:
- return c;
- }
-}
-
-static inline void foldQuoteMarksAndSoftHyphens(UChar* data, size_t length)
-{
- for (size_t i = 0; i < length; ++i)
- data[i] = foldQuoteMarkOrSoftHyphen(data[i]);
-}
-
static const size_t minimumSearchBufferSize = 8192;
#ifndef NDEBUG
@@ -1669,241 +1714,6 @@ static inline void unlockSearcher()
#endif
}
-// ICU's search ignores the distinction between small kana letters and ones
-// that are not small, and also characters that differ only in the voicing
-// marks when considering only primary collation strength differences.
-// This is not helpful for end users, since these differences make words
-// distinct, so for our purposes we need these to be considered.
-// The Unicode folks do not think the collation algorithm should be
-// changed. To work around this, we would like to tailor the ICU searcher,
-// but we can't get that to work yet. So instead, we check for cases where
-// these differences occur, and skip those matches.
-
-// We refer to the above technique as the "kana workaround". The next few
-// functions are helper functinos for the kana workaround.
-
-static inline bool isKanaLetter(UChar character)
-{
- // Hiragana letters.
- if (character >= 0x3041 && character <= 0x3096)
- return true;
-
- // Katakana letters.
- if (character >= 0x30A1 && character <= 0x30FA)
- return true;
- if (character >= 0x31F0 && character <= 0x31FF)
- return true;
-
- // Halfwidth katakana letters.
- if (character >= 0xFF66 && character <= 0xFF9D && character != 0xFF70)
- return true;
-
- return false;
-}
-
-static inline bool isSmallKanaLetter(UChar character)
-{
- ASSERT(isKanaLetter(character));
-
- switch (character) {
- case 0x3041: // HIRAGANA LETTER SMALL A
- case 0x3043: // HIRAGANA LETTER SMALL I
- case 0x3045: // HIRAGANA LETTER SMALL U
- case 0x3047: // HIRAGANA LETTER SMALL E
- case 0x3049: // HIRAGANA LETTER SMALL O
- case 0x3063: // HIRAGANA LETTER SMALL TU
- case 0x3083: // HIRAGANA LETTER SMALL YA
- case 0x3085: // HIRAGANA LETTER SMALL YU
- case 0x3087: // HIRAGANA LETTER SMALL YO
- case 0x308E: // HIRAGANA LETTER SMALL WA
- case 0x3095: // HIRAGANA LETTER SMALL KA
- case 0x3096: // HIRAGANA LETTER SMALL KE
- case 0x30A1: // KATAKANA LETTER SMALL A
- case 0x30A3: // KATAKANA LETTER SMALL I
- case 0x30A5: // KATAKANA LETTER SMALL U
- case 0x30A7: // KATAKANA LETTER SMALL E
- case 0x30A9: // KATAKANA LETTER SMALL O
- case 0x30C3: // KATAKANA LETTER SMALL TU
- case 0x30E3: // KATAKANA LETTER SMALL YA
- case 0x30E5: // KATAKANA LETTER SMALL YU
- case 0x30E7: // KATAKANA LETTER SMALL YO
- case 0x30EE: // KATAKANA LETTER SMALL WA
- case 0x30F5: // KATAKANA LETTER SMALL KA
- case 0x30F6: // KATAKANA LETTER SMALL KE
- case 0x31F0: // KATAKANA LETTER SMALL KU
- case 0x31F1: // KATAKANA LETTER SMALL SI
- case 0x31F2: // KATAKANA LETTER SMALL SU
- case 0x31F3: // KATAKANA LETTER SMALL TO
- case 0x31F4: // KATAKANA LETTER SMALL NU
- case 0x31F5: // KATAKANA LETTER SMALL HA
- case 0x31F6: // KATAKANA LETTER SMALL HI
- case 0x31F7: // KATAKANA LETTER SMALL HU
- case 0x31F8: // KATAKANA LETTER SMALL HE
- case 0x31F9: // KATAKANA LETTER SMALL HO
- case 0x31FA: // KATAKANA LETTER SMALL MU
- case 0x31FB: // KATAKANA LETTER SMALL RA
- case 0x31FC: // KATAKANA LETTER SMALL RI
- case 0x31FD: // KATAKANA LETTER SMALL RU
- case 0x31FE: // KATAKANA LETTER SMALL RE
- case 0x31FF: // KATAKANA LETTER SMALL RO
- case 0xFF67: // HALFWIDTH KATAKANA LETTER SMALL A
- case 0xFF68: // HALFWIDTH KATAKANA LETTER SMALL I
- case 0xFF69: // HALFWIDTH KATAKANA LETTER SMALL U
- case 0xFF6A: // HALFWIDTH KATAKANA LETTER SMALL E
- case 0xFF6B: // HALFWIDTH KATAKANA LETTER SMALL O
- case 0xFF6C: // HALFWIDTH KATAKANA LETTER SMALL YA
- case 0xFF6D: // HALFWIDTH KATAKANA LETTER SMALL YU
- case 0xFF6E: // HALFWIDTH KATAKANA LETTER SMALL YO
- case 0xFF6F: // HALFWIDTH KATAKANA LETTER SMALL TU
- return true;
- }
- return false;
-}
-
-enum VoicedSoundMarkType { NoVoicedSoundMark, VoicedSoundMark, SemiVoicedSoundMark };
-
-static inline VoicedSoundMarkType composedVoicedSoundMark(UChar character)
-{
- ASSERT(isKanaLetter(character));
-
- switch (character) {
- case 0x304C: // HIRAGANA LETTER GA
- case 0x304E: // HIRAGANA LETTER GI
- case 0x3050: // HIRAGANA LETTER GU
- case 0x3052: // HIRAGANA LETTER GE
- case 0x3054: // HIRAGANA LETTER GO
- case 0x3056: // HIRAGANA LETTER ZA
- case 0x3058: // HIRAGANA LETTER ZI
- case 0x305A: // HIRAGANA LETTER ZU
- case 0x305C: // HIRAGANA LETTER ZE
- case 0x305E: // HIRAGANA LETTER ZO
- case 0x3060: // HIRAGANA LETTER DA
- case 0x3062: // HIRAGANA LETTER DI
- case 0x3065: // HIRAGANA LETTER DU
- case 0x3067: // HIRAGANA LETTER DE
- case 0x3069: // HIRAGANA LETTER DO
- case 0x3070: // HIRAGANA LETTER BA
- case 0x3073: // HIRAGANA LETTER BI
- case 0x3076: // HIRAGANA LETTER BU
- case 0x3079: // HIRAGANA LETTER BE
- case 0x307C: // HIRAGANA LETTER BO
- case 0x3094: // HIRAGANA LETTER VU
- case 0x30AC: // KATAKANA LETTER GA
- case 0x30AE: // KATAKANA LETTER GI
- case 0x30B0: // KATAKANA LETTER GU
- case 0x30B2: // KATAKANA LETTER GE
- case 0x30B4: // KATAKANA LETTER GO
- case 0x30B6: // KATAKANA LETTER ZA
- case 0x30B8: // KATAKANA LETTER ZI
- case 0x30BA: // KATAKANA LETTER ZU
- case 0x30BC: // KATAKANA LETTER ZE
- case 0x30BE: // KATAKANA LETTER ZO
- case 0x30C0: // KATAKANA LETTER DA
- case 0x30C2: // KATAKANA LETTER DI
- case 0x30C5: // KATAKANA LETTER DU
- case 0x30C7: // KATAKANA LETTER DE
- case 0x30C9: // KATAKANA LETTER DO
- case 0x30D0: // KATAKANA LETTER BA
- case 0x30D3: // KATAKANA LETTER BI
- case 0x30D6: // KATAKANA LETTER BU
- case 0x30D9: // KATAKANA LETTER BE
- case 0x30DC: // KATAKANA LETTER BO
- case 0x30F4: // KATAKANA LETTER VU
- case 0x30F7: // KATAKANA LETTER VA
- case 0x30F8: // KATAKANA LETTER VI
- case 0x30F9: // KATAKANA LETTER VE
- case 0x30FA: // KATAKANA LETTER VO
- return VoicedSoundMark;
- case 0x3071: // HIRAGANA LETTER PA
- case 0x3074: // HIRAGANA LETTER PI
- case 0x3077: // HIRAGANA LETTER PU
- case 0x307A: // HIRAGANA LETTER PE
- case 0x307D: // HIRAGANA LETTER PO
- case 0x30D1: // KATAKANA LETTER PA
- case 0x30D4: // KATAKANA LETTER PI
- case 0x30D7: // KATAKANA LETTER PU
- case 0x30DA: // KATAKANA LETTER PE
- case 0x30DD: // KATAKANA LETTER PO
- return SemiVoicedSoundMark;
- }
- return NoVoicedSoundMark;
-}
-
-static inline bool isCombiningVoicedSoundMark(UChar character)
-{
- switch (character) {
- case 0x3099: // COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK
- case 0x309A: // COMBINING KATAKANA-HIRAGANA SEMI-VOICED SOUND MARK
- return true;
- }
- return false;
-}
-
-static inline bool containsKanaLetters(const String& pattern)
-{
- unsigned length = pattern.length();
- for (unsigned i = 0; i < length; ++i) {
- if (isKanaLetter(pattern[i]))
- return true;
- }
- return false;
-}
-
-static void normalizeCharacters(const UChar* characters, unsigned length, Vector<UChar>& buffer)
-{
- ASSERT(length);
-
- buffer.resize(length);
-
- UErrorCode status = U_ZERO_ERROR;
- size_t bufferSize = unorm_normalize(characters, length, UNORM_NFC, 0, buffer.data(), length, &status);
- ASSERT(status == U_ZERO_ERROR || status == U_STRING_NOT_TERMINATED_WARNING || status == U_BUFFER_OVERFLOW_ERROR);
- ASSERT(bufferSize);
-
- buffer.resize(bufferSize);
-
- if (status == U_ZERO_ERROR || status == U_STRING_NOT_TERMINATED_WARNING)
- return;
-
- status = U_ZERO_ERROR;
- unorm_normalize(characters, length, UNORM_NFC, 0, buffer.data(), bufferSize, &status);
- ASSERT(status == U_STRING_NOT_TERMINATED_WARNING);
-}
-
-static bool isNonLatin1Separator(UChar32 character)
-{
- ASSERT_ARG(character, character >= 256);
-
- return U_GET_GC_MASK(character) & (U_GC_S_MASK | U_GC_P_MASK | U_GC_Z_MASK | U_GC_CF_MASK);
-}
-
-static inline bool isSeparator(UChar32 character)
-{
- static const bool latin1SeparatorTable[256] = {
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // space ! " # $ % & ' ( ) * + , - . /
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, // : ; < = > ?
- 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // @
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, // [ \ ] ^ _
- 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // `
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, // { | } ~
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,
- 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0
- };
-
- if (character < 256)
- return latin1SeparatorTable[character];
-
- return isNonLatin1Separator(character);
-}
-
inline SearchBuffer::SearchBuffer(const String& target, FindOptions options)
: m_options(options)
, m_prefixLength(0)
@@ -1955,7 +1765,7 @@ inline SearchBuffer::SearchBuffer(const String& target, FindOptions options)
// The kana workaround requires a normalized copy of the target string.
if (m_targetRequiresKanaWorkaround)
- normalizeCharacters(m_target.data(), m_target.size(), m_normalizedTarget);
+ normalizeCharactersIntoNFCForm(m_target.data(), m_target.size(), m_normalizedTarget);
}
inline SearchBuffer::~SearchBuffer()
@@ -2041,55 +1851,9 @@ inline bool SearchBuffer::isBadMatch(const UChar* match, size_t matchLength) con
// Normalize into a match buffer. We reuse a single buffer rather than
// creating a new one each time.
- normalizeCharacters(match, matchLength, m_normalizedMatch);
-
- const UChar* a = m_normalizedTarget.begin();
- const UChar* aEnd = m_normalizedTarget.end();
-
- const UChar* b = m_normalizedMatch.begin();
- const UChar* bEnd = m_normalizedMatch.end();
-
- while (true) {
- // Skip runs of non-kana-letter characters. This is necessary so we can
- // correctly handle strings where the target and match have different-length
- // runs of characters that match, while still double checking the correctness
- // of matches of kana letters with other kana letters.
- while (a != aEnd && !isKanaLetter(*a))
- ++a;
- while (b != bEnd && !isKanaLetter(*b))
- ++b;
-
- // If we reached the end of either the target or the match, we should have
- // reached the end of both; both should have the same number of kana letters.
- if (a == aEnd || b == bEnd) {
- ASSERT(a == aEnd);
- ASSERT(b == bEnd);
- return false;
- }
+ normalizeCharactersIntoNFCForm(match, matchLength, m_normalizedMatch);
- // Check for differences in the kana letter character itself.
- if (isSmallKanaLetter(*a) != isSmallKanaLetter(*b))
- return true;
- if (composedVoicedSoundMark(*a) != composedVoicedSoundMark(*b))
- return true;
- ++a;
- ++b;
-
- // Check for differences in combining voiced sound marks found after the letter.
- while (1) {
- if (!(a != aEnd && isCombiningVoicedSoundMark(*a))) {
- if (b != bEnd && isCombiningVoicedSoundMark(*b))
- return true;
- break;
- }
- if (!(b != bEnd && isCombiningVoicedSoundMark(*b)))
- return true;
- if (*a != *b)
- return true;
- ++a;
- ++b;
- }
- }
+ return !checkOnlyKanaLettersInStrings(m_normalizedTarget.begin(), m_normalizedTarget.size(), m_normalizedMatch.begin(), m_normalizedMatch.size());
}
inline bool SearchBuffer::isWordStartMatch(size_t start, size_t length) const
@@ -2231,125 +1995,9 @@ PassRefPtr<Range> TextIterator::subrange(Range* entireRange, int characterOffset
return characterSubrange(entireRangeIterator, characterOffset, characterCount);
}
-PassRefPtr<Range> TextIterator::rangeFromLocationAndLength(ContainerNode* scope, int rangeLocation, int rangeLength, bool forSelectionPreservation)
-{
- RefPtr<Range> resultRange = scope->document().createRange();
-
- int docTextPosition = 0;
- int rangeEnd = rangeLocation + rangeLength;
- bool startRangeFound = false;
-
- RefPtr<Range> textRunRange;
-
- TextIterator it(rangeOfContents(scope).get(), forSelectionPreservation ? TextIteratorEmitsCharactersBetweenAllVisiblePositions : TextIteratorDefaultBehavior);
-
- // FIXME: the atEnd() check shouldn't be necessary, workaround for <http://bugs.webkit.org/show_bug.cgi?id=6289>.
- if (rangeLocation == 0 && rangeLength == 0 && it.atEnd()) {
- textRunRange = it.range();
-
- resultRange->setStart(textRunRange->startContainer(), 0, ASSERT_NO_EXCEPTION);
- resultRange->setEnd(textRunRange->startContainer(), 0, ASSERT_NO_EXCEPTION);
-
- return resultRange.release();
- }
-
- for (; !it.atEnd(); it.advance()) {
- int len = it.length();
- textRunRange = it.range();
-
- bool foundStart = rangeLocation >= docTextPosition && rangeLocation <= docTextPosition + len;
- bool foundEnd = rangeEnd >= docTextPosition && rangeEnd <= docTextPosition + len;
-
- // Fix textRunRange->endPosition(), but only if foundStart || foundEnd, because it is only
- // in those cases that textRunRange is used.
- if (foundEnd) {
- // FIXME: This is a workaround for the fact that the end of a run is often at the wrong
- // position for emitted '\n's.
- if (len == 1 && it.characterAt(0) == '\n') {
- scope->document().updateLayoutIgnorePendingStylesheets();
- it.advance();
- if (!it.atEnd()) {
- RefPtr<Range> range = it.range();
- textRunRange->setEnd(range->startContainer(), range->startOffset(), ASSERT_NO_EXCEPTION);
- } else {
- Position runStart = textRunRange->startPosition();
- Position runEnd = VisiblePosition(runStart).next().deepEquivalent();
- if (runEnd.isNotNull())
- textRunRange->setEnd(runEnd.containerNode(), runEnd.computeOffsetInContainerNode(), ASSERT_NO_EXCEPTION);
- }
- }
- }
-
- if (foundStart) {
- startRangeFound = true;
- if (textRunRange->startContainer()->isTextNode()) {
- int offset = rangeLocation - docTextPosition;
- resultRange->setStart(textRunRange->startContainer(), offset + textRunRange->startOffset(), IGNORE_EXCEPTION);
- } else {
- if (rangeLocation == docTextPosition)
- resultRange->setStart(textRunRange->startContainer(), textRunRange->startOffset(), IGNORE_EXCEPTION);
- else
- resultRange->setStart(textRunRange->endContainer(), textRunRange->endOffset(), IGNORE_EXCEPTION);
- }
- }
-
- if (foundEnd) {
- if (textRunRange->startContainer()->isTextNode()) {
- int offset = rangeEnd - docTextPosition;
- resultRange->setEnd(textRunRange->startContainer(), offset + textRunRange->startOffset(), IGNORE_EXCEPTION);
- } else {
- if (rangeEnd == docTextPosition)
- resultRange->setEnd(textRunRange->startContainer(), textRunRange->startOffset(), IGNORE_EXCEPTION);
- else
- resultRange->setEnd(textRunRange->endContainer(), textRunRange->endOffset(), IGNORE_EXCEPTION);
- }
- docTextPosition += len;
- break;
- }
- docTextPosition += len;
- }
-
- if (!startRangeFound)
- return 0;
-
- if (rangeLength != 0 && rangeEnd > docTextPosition) { // rangeEnd is out of bounds
- resultRange->setEnd(textRunRange->endContainer(), textRunRange->endOffset(), IGNORE_EXCEPTION);
- }
-
- return resultRange.release();
-}
-
-bool TextIterator::getLocationAndLengthFromRange(Node* scope, const Range* range, size_t& location, size_t& length)
-{
- location = kNotFound;
- length = 0;
-
- if (!range->startContainer())
- return false;
-
- // The critical assumption is that this only gets called with ranges that
- // concentrate on a given area containing the selection root. This is done
- // because of text fields and textareas. The DOM for those is not
- // directly in the document DOM, so ensure that the range does not cross a
- // boundary of one of those.
- if (range->startContainer() != scope && !range->startContainer()->isDescendantOf(scope))
- return false;
- if (range->endContainer() != scope && !range->endContainer()->isDescendantOf(scope))
- return false;
-
- RefPtr<Range> testRange = Range::create(scope->document(), scope, 0, range->startContainer(), range->startOffset());
- ASSERT(testRange->startContainer() == scope);
- location = TextIterator::rangeLength(testRange.get());
-
- testRange->setEnd(range->endContainer(), range->endOffset(), IGNORE_EXCEPTION);
- ASSERT(testRange->startContainer() == scope);
- length = TextIterator::rangeLength(testRange.get()) - location;
- return true;
-}
-
// --------
-String plainText(const Range* r, TextIteratorBehavior defaultBehavior, bool isDisplayString)
+String plainText(const Range* r, TextIteratorBehaviorFlags behavior)
{
// The initial buffer size can be critical for performance: https://bugs.webkit.org/show_bug.cgi?id=81192
static const unsigned initialCapacity = 1 << 15;
@@ -2357,9 +2005,6 @@ String plainText(const Range* r, TextIteratorBehavior defaultBehavior, bool isDi
unsigned bufferLength = 0;
StringBuilder builder;
builder.reserveCapacity(initialCapacity);
- TextIteratorBehavior behavior = defaultBehavior;
- if (!isDisplayString)
- behavior = static_cast<TextIteratorBehavior>(behavior | TextIteratorEmitsTextsWithoutTranscoding);
for (TextIterator it(r, behavior); !it.atEnd(); it.advance()) {
it.appendTextToStringBuilder(builder);
@@ -2369,12 +2014,7 @@ String plainText(const Range* r, TextIteratorBehavior defaultBehavior, bool isDi
if (!bufferLength)
return emptyString();
- String result = builder.toString();
-
- if (isDisplayString)
- r->ownerDocument().displayStringModifiedByEncoding(result);
-
- return result;
+ return builder.toString();
}
static PassRefPtr<Range> collapsedToBoundary(const Range* range, bool forward)
@@ -2439,14 +2079,14 @@ PassRefPtr<Range> findPlainText(const Range* range, const String& target, FindOp
size_t matchStart;
size_t matchLength;
{
- CharacterIterator findIterator(range, TextIteratorEntersTextControls);
+ CharacterIterator findIterator(range, TextIteratorEntersTextControls | TextIteratorEntersAuthorShadowRoots);
matchLength = findPlainText(findIterator, target, options, matchStart);
if (!matchLength)
return collapsedToBoundary(range, !(options & Backwards));
}
// Then, find the document position of the start and the end of the text.
- CharacterIterator computeRangeIterator(range, TextIteratorEntersTextControls);
+ CharacterIterator computeRangeIterator(range, TextIteratorEntersTextControls | TextIteratorEntersAuthorShadowRoots);
return characterSubrange(computeRangeIterator, matchStart, matchLength);
}
diff --git a/chromium/third_party/WebKit/Source/core/editing/TextIterator.h b/chromium/third_party/WebKit/Source/core/editing/TextIterator.h
index ecc4c418747..fbcd9f53e81 100644
--- a/chromium/third_party/WebKit/Source/core/editing/TextIterator.h
+++ b/chromium/third_party/WebKit/Source/core/editing/TextIterator.h
@@ -40,13 +40,13 @@ enum TextIteratorBehavior {
TextIteratorDefaultBehavior = 0,
TextIteratorEmitsCharactersBetweenAllVisiblePositions = 1 << 0,
TextIteratorEntersTextControls = 1 << 1,
- TextIteratorEmitsTextsWithoutTranscoding = 1 << 2,
- TextIteratorIgnoresStyleVisibility = 1 << 3,
- TextIteratorEmitsObjectReplacementCharacters = 1 << 4,
- TextIteratorEmitsOriginalText = 1 << 5,
- TextIteratorStopsOnFormControls = 1 << 6,
- TextIteratorEmitsImageAltText = 1 << 7,
+ TextIteratorIgnoresStyleVisibility = 1 << 2,
+ TextIteratorEmitsOriginalText = 1 << 3,
+ TextIteratorStopsOnFormControls = 1 << 4,
+ TextIteratorEmitsImageAltText = 1 << 5,
+ TextIteratorEntersAuthorShadowRoots = 1 << 6
};
+typedef unsigned TextIteratorBehaviorFlags;
// FIXME: Can't really answer this question correctly without knowing the white-space mode.
// FIXME: Move this somewhere else in the editing directory. It doesn't belong here.
@@ -61,7 +61,7 @@ inline bool isCollapsibleWhitespace(UChar c)
}
}
-String plainText(const Range*, TextIteratorBehavior defaultBehavior = TextIteratorDefaultBehavior, bool isDisplayString = false);
+String plainText(const Range*, TextIteratorBehaviorFlags = TextIteratorDefaultBehavior);
PassRefPtr<Range> findPlainText(const Range*, const String&, FindOptions);
class BitStack {
@@ -86,7 +86,7 @@ private:
class TextIterator {
public:
- explicit TextIterator(const Range*, TextIteratorBehavior = TextIteratorDefaultBehavior);
+ explicit TextIterator(const Range*, TextIteratorBehaviorFlags = TextIteratorDefaultBehavior);
~TextIterator();
bool atEnd() const { return !m_positionNode || m_shouldStop; }
@@ -117,11 +117,17 @@ public:
Node* node() const;
static int rangeLength(const Range*, bool spacesForReplacedElements = false);
- static PassRefPtr<Range> rangeFromLocationAndLength(ContainerNode* scope, int rangeLocation, int rangeLength, bool spacesForReplacedElements = false);
- static bool getLocationAndLengthFromRange(Node* scope, const Range*, size_t& location, size_t& length);
static PassRefPtr<Range> subrange(Range* entireRange, int characterOffset, int characterCount);
private:
+ enum IterationProgress {
+ HandledNone,
+ HandledAuthorShadowRoots,
+ HandledUserAgentShadowRoot,
+ HandledNode,
+ HandledChildren
+ };
+
int startOffset() const { return m_positionStartOffset; }
const String& string() const { return m_text; }
void exitNode();
@@ -142,9 +148,9 @@ private:
// as we walk through the DOM tree.
Node* m_node;
int m_offset;
- bool m_handledNode;
- bool m_handledChildren;
+ IterationProgress m_iterationProgress;
BitStack m_fullyClippedStack;
+ int m_shadowDepth;
// The range.
Node* m_startContainer;
@@ -194,22 +200,20 @@ private:
bool m_emitsCharactersBetweenAllVisiblePositions;
bool m_entersTextControls;
- // Used when we want texts for copying, pasting, and transposing.
- bool m_emitsTextWithoutTranscoding;
// Used in pasting inside password field.
bool m_emitsOriginalText;
// Used when deciding text fragment created by :first-letter should be looked into.
bool m_handledFirstLetter;
// Used when the visibility of the style should not affect text gathering.
bool m_ignoresStyleVisibility;
- // Used when emitting the special 0xFFFC character is required.
- bool m_emitsObjectReplacementCharacters;
// Used when the iteration should stop if form controls are reached.
bool m_stopsOnFormControls;
// Used when m_stopsOnFormControls is set to determine if the iterator should keep advancing.
bool m_shouldStop;
bool m_emitsImageAltText;
+
+ bool m_entersAuthorShadowRoots;
};
// Iterates through the DOM range, returning all the text, and 0-length boundaries
@@ -217,13 +221,15 @@ private:
// chunks so as to optimize for performance of the iteration.
class SimplifiedBackwardsTextIterator {
public:
- explicit SimplifiedBackwardsTextIterator(const Range*, TextIteratorBehavior = TextIteratorDefaultBehavior);
+ explicit SimplifiedBackwardsTextIterator(const Range*, TextIteratorBehaviorFlags = TextIteratorDefaultBehavior);
bool atEnd() const { return !m_positionNode || m_shouldStop; }
void advance();
int length() const { return m_textLength; }
+ Node* node() const { return m_node; }
+
template<typename BufferType>
void prependTextTo(BufferType& output)
{
@@ -297,7 +303,7 @@ private:
// character at a time, or faster, as needed. Useful for searching.
class CharacterIterator {
public:
- explicit CharacterIterator(const Range*, TextIteratorBehavior = TextIteratorDefaultBehavior);
+ explicit CharacterIterator(const Range*, TextIteratorBehaviorFlags = TextIteratorDefaultBehavior);
void advance(int numCharacters);
@@ -325,7 +331,7 @@ private:
class BackwardsCharacterIterator {
public:
- explicit BackwardsCharacterIterator(const Range*, TextIteratorBehavior = TextIteratorDefaultBehavior);
+ explicit BackwardsCharacterIterator(const Range*, TextIteratorBehaviorFlags = TextIteratorDefaultBehavior);
void advance(int);
diff --git a/chromium/third_party/WebKit/Source/core/editing/TextIteratorTest.cpp b/chromium/third_party/WebKit/Source/core/editing/TextIteratorTest.cpp
new file mode 100644
index 00000000000..0692414f080
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/editing/TextIteratorTest.cpp
@@ -0,0 +1,431 @@
+/*
+ * Copyright (c) 2013, Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/editing/TextIterator.h"
+
+#include "bindings/v8/ExceptionStatePlaceholder.h"
+#include "core/dom/Document.h"
+#include "core/dom/Element.h"
+#include "core/dom/Node.h"
+#include "core/dom/Range.h"
+#include "core/dom/shadow/ShadowRoot.h"
+#include "core/frame/FrameView.h"
+#include "core/html/HTMLDocument.h"
+#include "core/html/HTMLElement.h"
+#include "core/testing/DummyPageHolder.h"
+#include "platform/geometry/IntSize.h"
+#include "wtf/Compiler.h"
+#include "wtf/OwnPtr.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefPtr.h"
+#include "wtf/StdLibExtras.h"
+#include "wtf/Vector.h"
+#include "wtf/testing/WTFTestHelpers.h"
+#include <gtest/gtest.h>
+
+using namespace WebCore;
+
+namespace {
+
+class TextIteratorTest : public ::testing::Test {
+protected:
+ virtual void SetUp() OVERRIDE;
+
+ HTMLDocument& document() const;
+
+ Vector<String> iterate(TextIteratorBehavior = TextIteratorDefaultBehavior);
+
+ void setBodyInnerHTML(const char*);
+ PassRefPtr<Range> getBodyRange() const;
+
+private:
+ OwnPtr<DummyPageHolder> m_dummyPageHolder;
+
+ HTMLDocument* m_document;
+};
+
+void TextIteratorTest::SetUp()
+{
+ m_dummyPageHolder = DummyPageHolder::create(IntSize(800, 600));
+ m_document = toHTMLDocument(&m_dummyPageHolder->document());
+ ASSERT(m_document);
+}
+
+Vector<String> TextIteratorTest::iterate(TextIteratorBehavior iteratorBehavior)
+{
+ document().view()->updateLayoutAndStyleIfNeededRecursive(); // Force renderers to be created; TextIterator needs them.
+
+ RefPtr<Range> range = getBodyRange();
+ TextIterator textIterator(range.get(), iteratorBehavior);
+ Vector<String> textChunks;
+ while (!textIterator.atEnd()) {
+ textChunks.append(textIterator.substring(0, textIterator.length()));
+ textIterator.advance();
+ }
+ return textChunks;
+}
+
+HTMLDocument& TextIteratorTest::document() const
+{
+ return *m_document;
+}
+
+void TextIteratorTest::setBodyInnerHTML(const char* bodyContent)
+{
+ document().body()->setInnerHTML(String::fromUTF8(bodyContent), ASSERT_NO_EXCEPTION);
+}
+
+PassRefPtr<Range> TextIteratorTest::getBodyRange() const
+{
+ RefPtr<Range> range(Range::create(document()));
+ range->selectNode(document().body());
+ return range.release();
+}
+
+Vector<String> createVectorString(const char* const* rawStrings, size_t size)
+{
+ Vector<String> result;
+ result.append(rawStrings, size);
+ return result;
+}
+
+PassRefPtr<ShadowRoot> createShadowRootForElementWithIDAndSetInnerHTML(TreeScope& scope, const char* hostElementID, const char* shadowRootContent)
+{
+ RefPtr<ShadowRoot> shadowRoot = scope.getElementById(AtomicString::fromUTF8(hostElementID))->createShadowRoot(ASSERT_NO_EXCEPTION);
+ shadowRoot->setInnerHTML(String::fromUTF8(shadowRootContent), ASSERT_NO_EXCEPTION);
+ return shadowRoot.release();
+}
+
+TEST_F(TextIteratorTest, BasicIteration)
+{
+ static const char* input = "<p>Hello, \ntext</p><p>iterator.</p>";
+ static const char* expectedTextChunksRawString[] = {
+ "Hello, ",
+ "text",
+ "\n",
+ "\n",
+ "iterator."
+ };
+ Vector<String> expectedTextChunks = createVectorString(expectedTextChunksRawString, WTF_ARRAY_LENGTH(expectedTextChunksRawString));
+
+ setBodyInnerHTML(input);
+ EXPECT_EQ(expectedTextChunks, iterate());
+}
+
+TEST_F(TextIteratorTest, NotEnteringTextControls)
+{
+ static const char* input = "<p>Hello <input type=\"text\" value=\"input\">!</p>";
+ static const char* expectedTextChunksRawString[] = {
+ "Hello ",
+ "",
+ "!",
+ };
+ Vector<String> expectedTextChunks = createVectorString(expectedTextChunksRawString, WTF_ARRAY_LENGTH(expectedTextChunksRawString));
+
+ setBodyInnerHTML(input);
+ EXPECT_EQ(expectedTextChunks, iterate());
+}
+
+TEST_F(TextIteratorTest, EnteringTextControlsWithOption)
+{
+ static const char* input = "<p>Hello <input type=\"text\" value=\"input\">!</p>";
+ static const char* expectedTextChunksRawString[] = {
+ "Hello ",
+ "\n",
+ "input",
+ "!",
+ };
+ Vector<String> expectedTextChunks = createVectorString(expectedTextChunksRawString, WTF_ARRAY_LENGTH(expectedTextChunksRawString));
+
+ setBodyInnerHTML(input);
+ EXPECT_EQ(expectedTextChunks, iterate(TextIteratorEntersTextControls));
+}
+
+TEST_F(TextIteratorTest, EnteringTextControlsWithOptionComplex)
+{
+ static const char* input = "<input type=\"text\" value=\"Beginning of range\"><div><div><input type=\"text\" value=\"Under DOM nodes\"></div></div><input type=\"text\" value=\"End of range\">";
+ static const char* expectedTextChunksRawString[] = {
+ "\n", // FIXME: Why newline here?
+ "Beginning of range",
+ "\n",
+ "Under DOM nodes",
+ "\n",
+ "End of range"
+ };
+ Vector<String> expectedTextChunks = createVectorString(expectedTextChunksRawString, WTF_ARRAY_LENGTH(expectedTextChunksRawString));
+
+ setBodyInnerHTML(input);
+ EXPECT_EQ(expectedTextChunks, iterate(TextIteratorEntersTextControls));
+}
+
+TEST_F(TextIteratorTest, NotEnteringTextControlHostingShadowTreeEvenWithOption)
+{
+ static const char* bodyContent = "<div>Hello, <input type=\"text\" value=\"input\" id=\"input\"> iterator.</div>";
+ static const char* shadowContent = "<span>shadow</span>";
+ // TextIterator doesn't emit "input" nor "shadow" since (1) the renderer for <input> is not created; and
+ // (2) we don't (yet) recurse into shadow trees.
+ static const char* expectedTextChunksRawString[] = {
+ "Hello, ",
+ "", // FIXME: Why is an empty string emitted here?
+ " iterator."
+ };
+ Vector<String> expectedTextChunks = createVectorString(expectedTextChunksRawString, WTF_ARRAY_LENGTH(expectedTextChunksRawString));
+
+ setBodyInnerHTML(bodyContent);
+ createShadowRootForElementWithIDAndSetInnerHTML(document(), "input", shadowContent);
+
+ EXPECT_EQ(expectedTextChunks, iterate());
+}
+
+TEST_F(TextIteratorTest, NotEnteringShadowTree)
+{
+ static const char* bodyContent = "<div>Hello, <span id=\"host\">text</span> iterator.</div>";
+ static const char* shadowContent = "<span>shadow</span>";
+ static const char* expectedTextChunksRawString[] = {
+ "Hello, ", // TextIterator doesn't emit "text" since its renderer is not created. The shadow tree is ignored.
+ " iterator."
+ };
+ Vector<String> expectedTextChunks = createVectorString(expectedTextChunksRawString, WTF_ARRAY_LENGTH(expectedTextChunksRawString));
+
+ setBodyInnerHTML(bodyContent);
+ createShadowRootForElementWithIDAndSetInnerHTML(document(), "host", shadowContent);
+
+ EXPECT_EQ(expectedTextChunks, iterate());
+}
+
+TEST_F(TextIteratorTest, NotEnteringShadowTreeWithMultipleShadowTrees)
+{
+ static const char* bodyContent = "<div>Hello, <span id=\"host\">text</span> iterator.</div>";
+ static const char* shadowContent1 = "<span>first shadow</span>";
+ static const char* shadowContent2 = "<span>second shadow</span>";
+ static const char* expectedTextChunksRawString[] = {
+ "Hello, ",
+ " iterator."
+ };
+ Vector<String> expectedTextChunks = createVectorString(expectedTextChunksRawString, WTF_ARRAY_LENGTH(expectedTextChunksRawString));
+
+ setBodyInnerHTML(bodyContent);
+ createShadowRootForElementWithIDAndSetInnerHTML(document(), "host", shadowContent1);
+ createShadowRootForElementWithIDAndSetInnerHTML(document(), "host", shadowContent2);
+
+ EXPECT_EQ(expectedTextChunks, iterate());
+}
+
+TEST_F(TextIteratorTest, NotEnteringShadowTreeWithNestedShadowTrees)
+{
+ static const char* bodyContent = "<div>Hello, <span id=\"host-in-document\">text</span> iterator.</div>";
+ static const char* shadowContent1 = "<span>first <span id=\"host-in-shadow\">shadow</span></span>";
+ static const char* shadowContent2 = "<span>second shadow</span>";
+ static const char* expectedTextChunksRawString[] = {
+ "Hello, ",
+ " iterator."
+ };
+ Vector<String> expectedTextChunks = createVectorString(expectedTextChunksRawString, WTF_ARRAY_LENGTH(expectedTextChunksRawString));
+
+ setBodyInnerHTML(bodyContent);
+ RefPtr<ShadowRoot> shadowRoot1 = createShadowRootForElementWithIDAndSetInnerHTML(document(), "host-in-document", shadowContent1);
+ createShadowRootForElementWithIDAndSetInnerHTML(*shadowRoot1, "host-in-shadow", shadowContent2);
+
+ EXPECT_EQ(expectedTextChunks, iterate());
+}
+
+TEST_F(TextIteratorTest, NotEnteringShadowTreeWithContentInsertionPoint)
+{
+ static const char* bodyContent = "<div>Hello, <span id=\"host\">text</span> iterator.</div>";
+ static const char* shadowContent = "<span>shadow <content>content</content></span>";
+ static const char* expectedTextChunksRawString[] = {
+ "Hello, ",
+ "text", // In this case a renderer for "text" is created, so it shows up here.
+ " iterator."
+ };
+ Vector<String> expectedTextChunks = createVectorString(expectedTextChunksRawString, WTF_ARRAY_LENGTH(expectedTextChunksRawString));
+
+ setBodyInnerHTML(bodyContent);
+ createShadowRootForElementWithIDAndSetInnerHTML(document(), "host", shadowContent);
+
+ EXPECT_EQ(expectedTextChunks, iterate());
+}
+
+TEST_F(TextIteratorTest, EnteringShadowTreeWithOption)
+{
+ static const char* bodyContent = "<div>Hello, <span id=\"host\">text</span> iterator.</div>";
+ static const char* shadowContent = "<span>shadow</span>";
+ static const char* expectedTextChunksRawString[] = {
+ "Hello, ",
+ "shadow", // TextIterator emits "shadow" since TextIteratorEntersAuthorShadowRoots is specified.
+ " iterator."
+ };
+ Vector<String> expectedTextChunks = createVectorString(expectedTextChunksRawString, WTF_ARRAY_LENGTH(expectedTextChunksRawString));
+
+ setBodyInnerHTML(bodyContent);
+ createShadowRootForElementWithIDAndSetInnerHTML(document(), "host", shadowContent);
+
+ EXPECT_EQ(expectedTextChunks, iterate(TextIteratorEntersAuthorShadowRoots));
+}
+
+TEST_F(TextIteratorTest, EnteringShadowTreeWithMultipleShadowTreesWithOption)
+{
+ static const char* bodyContent = "<div>Hello, <span id=\"host\">text</span> iterator.</div>";
+ static const char* shadowContent1 = "<span>first shadow</span>";
+ static const char* shadowContent2 = "<span>second shadow</span>";
+ static const char* expectedTextChunksRawString[] = {
+ "Hello, ",
+ "second shadow", // The first isn't emitted because a renderer for the first is not created.
+ " iterator."
+ };
+ Vector<String> expectedTextChunks = createVectorString(expectedTextChunksRawString, WTF_ARRAY_LENGTH(expectedTextChunksRawString));
+
+ setBodyInnerHTML(bodyContent);
+ createShadowRootForElementWithIDAndSetInnerHTML(document(), "host", shadowContent1);
+ createShadowRootForElementWithIDAndSetInnerHTML(document(), "host", shadowContent2);
+
+ EXPECT_EQ(expectedTextChunks, iterate(TextIteratorEntersAuthorShadowRoots));
+}
+
+TEST_F(TextIteratorTest, EnteringShadowTreeWithNestedShadowTreesWithOption)
+{
+ static const char* bodyContent = "<div>Hello, <span id=\"host-in-document\">text</span> iterator.</div>";
+ static const char* shadowContent1 = "<span>first <span id=\"host-in-shadow\">shadow</span></span>";
+ static const char* shadowContent2 = "<span>second shadow</span>";
+ static const char* expectedTextChunksRawString[] = {
+ "Hello, ",
+ "first ",
+ "second shadow",
+ " iterator."
+ };
+ Vector<String> expectedTextChunks = createVectorString(expectedTextChunksRawString, WTF_ARRAY_LENGTH(expectedTextChunksRawString));
+
+ setBodyInnerHTML(bodyContent);
+ RefPtr<ShadowRoot> shadowRoot1 = createShadowRootForElementWithIDAndSetInnerHTML(document(), "host-in-document", shadowContent1);
+ createShadowRootForElementWithIDAndSetInnerHTML(*shadowRoot1, "host-in-shadow", shadowContent2);
+
+ EXPECT_EQ(expectedTextChunks, iterate(TextIteratorEntersAuthorShadowRoots));
+}
+
+TEST_F(TextIteratorTest, EnteringShadowTreeWithContentInsertionPointWithOption)
+{
+ static const char* bodyContent = "<div>Hello, <span id=\"host\">text</span> iterator.</div>";
+ static const char* shadowContent = "<span><content>content</content> shadow</span>";
+ // In this case a renderer for "text" is created, and emitted AFTER any nodes in the shadow tree.
+ // This order does not match the order of the rendered texts, but at this moment it's the expected behavior.
+ // FIXME: Fix this. We probably need pure-renderer-based implementation of TextIterator to achieve this.
+ static const char* expectedTextChunksRawString[] = {
+ "Hello, ",
+ " shadow",
+ "text",
+ " iterator."
+ };
+ Vector<String> expectedTextChunks = createVectorString(expectedTextChunksRawString, WTF_ARRAY_LENGTH(expectedTextChunksRawString));
+
+ setBodyInnerHTML(bodyContent);
+ createShadowRootForElementWithIDAndSetInnerHTML(document(), "host", shadowContent);
+
+ EXPECT_EQ(expectedTextChunks, iterate(TextIteratorEntersAuthorShadowRoots));
+}
+
+TEST_F(TextIteratorTest, FullyClipsContents)
+{
+ static const char* bodyContent =
+ "<div style=\"overflow: hidden; width: 200px; height: 0;\">"
+ "I'm invisible"
+ "</div>";
+ Vector<String> expectedTextChunks; // Empty.
+
+ setBodyInnerHTML(bodyContent);
+ EXPECT_EQ(expectedTextChunks, iterate());
+}
+
+TEST_F(TextIteratorTest, IgnoresContainerClip)
+{
+ static const char* bodyContent =
+ "<div style=\"overflow: hidden; width: 200px; height: 0;\">"
+ "<div>I'm not visible</div>"
+ "<div style=\"position: absolute; width: 200px; height: 200px; top: 0; right: 0;\">"
+ "but I am!"
+ "</div>"
+ "</div>";
+ static const char* expectedTextChunksRawString[] = {
+ "but I am!"
+ };
+ Vector<String> expectedTextChunks = createVectorString(expectedTextChunksRawString, WTF_ARRAY_LENGTH(expectedTextChunksRawString));
+
+ setBodyInnerHTML(bodyContent);
+ EXPECT_EQ(expectedTextChunks, iterate());
+}
+
+TEST_F(TextIteratorTest, FullyClippedContentsDistributed)
+{
+ static const char* bodyContent =
+ "<div id=\"host\">"
+ "<div>Am I visible?</div>"
+ "</div>";
+ static const char* shadowContent =
+ "<div style=\"overflow: hidden; width: 200px; height: 0;\">"
+ "<content></content>"
+ "</div>";
+ static const char* expectedTextChunksRawString[] = {
+ "\n",
+ // FIXME: The text below is actually invisible but TextIterator currently thinks it's visible.
+ "Am I visible?"
+ };
+ Vector<String> expectedTextChunks = createVectorString(expectedTextChunksRawString, WTF_ARRAY_LENGTH(expectedTextChunksRawString));
+
+ setBodyInnerHTML(bodyContent);
+ createShadowRootForElementWithIDAndSetInnerHTML(document(), "host", shadowContent);
+
+ EXPECT_EQ(expectedTextChunks, iterate(TextIteratorEntersAuthorShadowRoots));
+}
+
+TEST_F(TextIteratorTest, IgnoresContainersClipDistributed)
+{
+ static const char* bodyContent =
+ "<div id=\"host\" style=\"overflow: hidden; width: 200px; height: 0;\">"
+ "<div>Nobody can find me!</div>"
+ "</div>";
+ static const char* shadowContent =
+ "<div style=\"position: absolute; width: 200px; height: 200px; top: 0; right: 0;\">"
+ "<content></content>"
+ "</div>";
+ // FIXME: The text below is actually visible but TextIterator currently thinks it's invisible.
+ // static const char* expectedTextChunksRawString[] = {
+ // "\n",
+ // "Nobody can find me!"
+ // };
+ // Vector<String> expectedTextChunks = createVectorString(expectedTextChunksRawString, WTF_ARRAY_LENGTH(expectedTextChunksRawString));
+ Vector<String> expectedTextChunks; // Empty.
+
+ setBodyInnerHTML(bodyContent);
+ createShadowRootForElementWithIDAndSetInnerHTML(document(), "host", shadowContent);
+
+ EXPECT_EQ(expectedTextChunks, iterate(TextIteratorEntersAuthorShadowRoots));
+}
+
+}
diff --git a/chromium/third_party/WebKit/Source/core/editing/TypingCommand.cpp b/chromium/third_party/WebKit/Source/core/editing/TypingCommand.cpp
index fac993be1db..46e1e7de7eb 100644
--- a/chromium/third_party/WebKit/Source/core/editing/TypingCommand.cpp
+++ b/chromium/third_party/WebKit/Source/core/editing/TypingCommand.cpp
@@ -35,11 +35,11 @@
#include "core/editing/InsertLineBreakCommand.h"
#include "core/editing/InsertParagraphSeparatorCommand.h"
#include "core/editing/InsertTextCommand.h"
-#include "core/editing/SpellCheckRequester.h"
+#include "core/editing/SpellChecker.h"
#include "core/editing/VisiblePosition.h"
#include "core/editing/VisibleUnits.h"
#include "core/editing/htmlediting.h"
-#include "core/page/Frame.h"
+#include "core/frame/Frame.h"
#include "core/rendering/RenderObject.h"
namespace WebCore {
@@ -110,11 +110,16 @@ void TypingCommand::deleteSelection(Document& document, Options options)
void TypingCommand::deleteKeyPressed(Document& document, Options options, TextGranularity granularity)
{
if (granularity == CharacterGranularity) {
- if (RefPtr<TypingCommand> lastTypingCommand = lastTypingCommandIfStillOpenForTyping(document.frame())) {
- updateSelectionIfDifferentFromCurrentSelection(lastTypingCommand.get(), document.frame());
- lastTypingCommand->setShouldPreventSpellChecking(options & PreventSpellChecking);
- lastTypingCommand->deleteKeyPressed(granularity, options & KillRing);
- return;
+ Frame* frame = document.frame();
+ if (RefPtr<TypingCommand> lastTypingCommand = lastTypingCommandIfStillOpenForTyping(frame)) {
+ // If the last typing command is not Delete, open a new typing command.
+ // We need to group continuous delete commands alone in a single typing command.
+ if (lastTypingCommand->commandTypeOfOpenCommand() == DeleteKey) {
+ updateSelectionIfDifferentFromCurrentSelection(lastTypingCommand.get(), frame);
+ lastTypingCommand->setShouldPreventSpellChecking(options & PreventSpellChecking);
+ lastTypingCommand->deleteKeyPressed(granularity, options & KillRing);
+ return;
+ }
}
}
@@ -124,8 +129,8 @@ void TypingCommand::deleteKeyPressed(Document& document, Options options, TextGr
void TypingCommand::forwardDeleteKeyPressed(Document& document, Options options, TextGranularity granularity)
{
// FIXME: Forward delete in TextEdit appears to open and close a new typing command.
- Frame* frame = document.frame();
if (granularity == CharacterGranularity) {
+ Frame* frame = document.frame();
if (RefPtr<TypingCommand> lastTypingCommand = lastTypingCommandIfStillOpenForTyping(frame)) {
updateSelectionIfDifferentFromCurrentSelection(lastTypingCommand.get(), frame);
lastTypingCommand->setShouldPreventSpellChecking(options & PreventSpellChecking);
@@ -154,7 +159,7 @@ void TypingCommand::insertText(Document& document, const String& text, Options o
ASSERT(frame);
if (!text.isEmpty())
- document.frame()->editor().updateMarkersForWordsAffectedByEditing(isSpaceOrNewline(text[0]));
+ document.frame()->spellChecker().updateMarkersForWordsAffectedByEditing(isSpaceOrNewline(text[0]));
insertText(document, text, frame->selection().selection(), options, composition);
}
@@ -285,10 +290,10 @@ void TypingCommand::markMisspellingsAfterTyping(ETypingCommand commandType)
if (!frame)
return;
- if (!frame->editor().isContinuousSpellCheckingEnabled())
+ if (!frame->spellChecker().isContinuousSpellCheckingEnabled())
return;
- frame->editor().spellCheckRequester().cancelCheck();
+ frame->spellChecker().cancelCheck();
// Take a look at the selection that results after typing and determine whether we need to spellcheck.
// Since the word containing the current selection is never marked, this does a check to
@@ -300,7 +305,7 @@ void TypingCommand::markMisspellingsAfterTyping(ETypingCommand commandType)
VisiblePosition p1 = startOfWord(previous, LeftWordIfOnBoundary);
VisiblePosition p2 = startOfWord(start, LeftWordIfOnBoundary);
if (p1 != p2)
- frame->editor().markMisspellingsAfterTypingToWord(p1, endingSelection());
+ frame->spellChecker().markMisspellingsAfterTypingToWord(p1, endingSelection());
}
}
@@ -311,6 +316,7 @@ void TypingCommand::typingAddedToOpenCommand(ETypingCommand commandTypeForAddedT
return;
updatePreservesTypingStyle(commandTypeForAddedTyping);
+ updateCommandTypeOfOpenCommand(commandTypeForAddedTyping);
// The old spellchecking code requires that checking be done first, to prevent issues like that in 6864072, where <doesn't> is marked as misspelled.
markMisspellingsAfterTyping(commandTypeForAddedTyping);
@@ -396,17 +402,17 @@ void TypingCommand::deleteKeyPressed(TextGranularity granularity, bool killRing)
if (!frame)
return;
- frame->editor().updateMarkersForWordsAffectedByEditing(false);
+ frame->spellChecker().updateMarkersForWordsAffectedByEditing(false);
VisibleSelection selectionToDelete;
VisibleSelection selectionAfterUndo;
switch (endingSelection().selectionType()) {
- case VisibleSelection::RangeSelection:
+ case RangeSelection:
selectionToDelete = endingSelection();
selectionAfterUndo = selectionToDelete;
break;
- case VisibleSelection::CaretSelection: {
+ case CaretSelection: {
// After breaking out of an empty mail blockquote, we still want continue with the deletion
// so actual content will get deleted, and not just the quote style.
if (breakOutOfEmptyMailBlockquotedParagraph())
@@ -470,7 +476,7 @@ void TypingCommand::deleteKeyPressed(TextGranularity granularity, bool killRing)
selectionAfterUndo.setWithoutValidation(startingSelection().end(), selectionToDelete.extent());
break;
}
- case VisibleSelection::NoSelection:
+ case NoSelection:
ASSERT_NOT_REACHED();
break;
}
@@ -479,15 +485,15 @@ void TypingCommand::deleteKeyPressed(TextGranularity granularity, bool killRing)
if (selectionToDelete.isNone())
return;
- if (selectionToDelete.isCaret() || !frame->selection().shouldDeleteSelection(selectionToDelete))
+ if (selectionToDelete.isCaret())
return;
if (killRing)
frame->editor().addToKillRing(selectionToDelete.toNormalizedRange().get(), false);
- // Make undo select everything that has been deleted, unless an undo will undo more than just this deletion.
+ // On Mac, make undo select everything that has been deleted, unless an undo will undo more than just this deletion.
// FIXME: This behaves like TextEdit except for the case where you open with text insertion and then delete
// more text than you insert. In that case all of the text that was around originally should be selected.
- if (m_openedByBackwardDelete)
+ if (frame->editor().behavior().shouldUndoOfDeleteSelectText() && m_openedByBackwardDelete)
setStartingSelection(selectionAfterUndo);
CompositeEditCommand::deleteSelection(selectionToDelete, m_smartDelete);
setSmartDelete(false);
@@ -500,17 +506,17 @@ void TypingCommand::forwardDeleteKeyPressed(TextGranularity granularity, bool ki
if (!frame)
return;
- frame->editor().updateMarkersForWordsAffectedByEditing(false);
+ frame->spellChecker().updateMarkersForWordsAffectedByEditing(false);
VisibleSelection selectionToDelete;
VisibleSelection selectionAfterUndo;
switch (endingSelection().selectionType()) {
- case VisibleSelection::RangeSelection:
+ case RangeSelection:
selectionToDelete = endingSelection();
selectionAfterUndo = selectionToDelete;
break;
- case VisibleSelection::CaretSelection: {
+ case CaretSelection: {
m_smartDelete = false;
// Handle delete at beginning-of-block case.
@@ -530,8 +536,7 @@ void TypingCommand::forwardDeleteKeyPressed(TextGranularity granularity, bool ki
if (visibleEnd == endOfParagraph(visibleEnd))
downstreamEnd = visibleEnd.next(CannotCrossEditingBoundary).deepEquivalent().downstream();
// When deleting tables: Select the table first, then perform the deletion
- if (downstreamEnd.containerNode() && downstreamEnd.containerNode()->renderer() && downstreamEnd.containerNode()->renderer()->isTable()
- && downstreamEnd.computeOffsetInContainerNode() <= caretMinOffset(downstreamEnd.containerNode())) {
+ if (isRenderedTable(downstreamEnd.containerNode()) && downstreamEnd.computeOffsetInContainerNode() <= caretMinOffset(downstreamEnd.containerNode())) {
setEndingSelection(VisibleSelection(endingSelection().end(), positionAfterNode(downstreamEnd.containerNode()), DOWNSTREAM, endingSelection().isDirectional()));
typingAddedToOpenCommand(ForwardDeleteKey);
return;
@@ -563,7 +568,7 @@ void TypingCommand::forwardDeleteKeyPressed(TextGranularity granularity, bool ki
}
break;
}
- case VisibleSelection::NoSelection:
+ case NoSelection:
ASSERT_NOT_REACHED();
break;
}
@@ -572,13 +577,14 @@ void TypingCommand::forwardDeleteKeyPressed(TextGranularity granularity, bool ki
if (selectionToDelete.isNone())
return;
- if (selectionToDelete.isCaret() || !frame->selection().shouldDeleteSelection(selectionToDelete))
+ if (selectionToDelete.isCaret())
return;
if (killRing)
frame->editor().addToKillRing(selectionToDelete.toNormalizedRange().get(), false);
- // make undo select what was deleted
- setStartingSelection(selectionAfterUndo);
+ // Make undo select what was deleted on Mac alone
+ if (frame->editor().behavior().shouldUndoOfDeleteSelectText())
+ setStartingSelection(selectionAfterUndo);
CompositeEditCommand::deleteSelection(selectionToDelete, m_smartDelete);
setSmartDelete(false);
typingAddedToOpenCommand(ForwardDeleteKey);
diff --git a/chromium/third_party/WebKit/Source/core/editing/TypingCommand.h b/chromium/third_party/WebKit/Source/core/editing/TypingCommand.h
index 90a86b906c7..05032abe59b 100644
--- a/chromium/third_party/WebKit/Source/core/editing/TypingCommand.h
+++ b/chromium/third_party/WebKit/Source/core/editing/TypingCommand.h
@@ -117,6 +117,9 @@ private:
void typingAddedToOpenCommand(ETypingCommand);
bool makeEditableRootEmpty();
+ void updateCommandTypeOfOpenCommand(ETypingCommand typingCommand) { m_commandType = typingCommand; }
+ ETypingCommand commandTypeOfOpenCommand() const { return m_commandType; }
+
ETypingCommand m_commandType;
String m_textToInsert;
bool m_openForMoreTyping;
diff --git a/chromium/third_party/WebKit/Source/core/editing/UndoStack.cpp b/chromium/third_party/WebKit/Source/core/editing/UndoStack.cpp
new file mode 100644
index 00000000000..cdcd9ae4014
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/editing/UndoStack.cpp
@@ -0,0 +1,124 @@
+/*
+ * Copyright (C) 2006, 2007 Apple, Inc. All rights reserved.
+ * Copyright (C) 2012 Google, Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "UndoStack.h"
+
+#include "core/dom/ContainerNode.h"
+#include "core/editing/UndoStep.h"
+#include "wtf/TemporaryChange.h"
+
+namespace WebCore {
+
+// Arbitrary depth limit for the undo stack, to keep it from using
+// unbounded memory. This is the maximum number of distinct undoable
+// actions -- unbroken stretches of typed characters are coalesced
+// into a single action.
+static const size_t maximumUndoStackDepth = 1000;
+
+UndoStack::UndoStack()
+ : m_inRedo(false)
+{
+}
+
+UndoStack::~UndoStack()
+{
+}
+
+PassOwnPtr<UndoStack> UndoStack::create()
+{
+ return adoptPtr(new UndoStack());
+}
+
+void UndoStack::registerUndoStep(PassRefPtr<UndoStep> step)
+{
+ if (m_undoStack.size() == maximumUndoStackDepth)
+ m_undoStack.removeFirst(); // drop oldest item off the far end
+ if (!m_inRedo)
+ m_redoStack.clear();
+ m_undoStack.append(step);
+}
+
+void UndoStack::registerRedoStep(PassRefPtr<UndoStep> step)
+{
+ m_redoStack.append(step);
+}
+
+void UndoStack::didUnloadFrame(const Frame& frame)
+{
+ NoEventDispatchAssertion assertNoEventDispatch;
+ filterOutUndoSteps(m_undoStack, frame);
+ filterOutUndoSteps(m_redoStack, frame);
+}
+
+void UndoStack::filterOutUndoSteps(UndoStepStack& stack, const Frame& frame)
+{
+ UndoStepStack newStack;
+ while (!stack.isEmpty()) {
+ UndoStep* step = stack.first().get();
+ if (!step->belongsTo(frame))
+ newStack.append(step);
+ stack.removeFirst();
+ }
+ stack.swap(newStack);
+}
+
+bool UndoStack::canUndo() const
+{
+ return !m_undoStack.isEmpty();
+}
+
+bool UndoStack::canRedo() const
+{
+ return !m_redoStack.isEmpty();
+}
+
+void UndoStack::undo()
+{
+ if (canUndo()) {
+ UndoStepStack::iterator back = --m_undoStack.end();
+ RefPtr<UndoStep> step(*back);
+ m_undoStack.remove(back);
+ step->unapply();
+ // unapply will call us back to push this command onto the redo stack.
+ }
+}
+
+void UndoStack::redo()
+{
+ if (canRedo()) {
+ UndoStepStack::iterator back = --m_redoStack.end();
+ RefPtr<UndoStep> step(*back);
+ m_redoStack.remove(back);
+
+ ASSERT(!m_inRedo);
+ TemporaryChange<bool> redoScope(m_inRedo, true);
+ step->reapply();
+ // reapply will call us back to push this command onto the undo stack.
+ }
+}
+
+} // namesace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/editing/UndoStack.h b/chromium/third_party/WebKit/Source/core/editing/UndoStack.h
new file mode 100644
index 00000000000..507e8996fb8
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/editing/UndoStack.h
@@ -0,0 +1,69 @@
+/*
+ * Copyright (C) 2009 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef UndoStack_h
+#define UndoStack_h
+
+#include "wtf/Deque.h"
+#include "wtf/Forward.h"
+
+namespace WebCore {
+
+class Frame;
+class UndoStep;
+
+class UndoStack {
+public:
+ static PassOwnPtr<UndoStack> create();
+
+ ~UndoStack();
+
+ void registerUndoStep(PassRefPtr<UndoStep>);
+ void registerRedoStep(PassRefPtr<UndoStep>);
+ void didUnloadFrame(const Frame&);
+ bool canUndo() const;
+ bool canRedo() const;
+ void undo();
+ void redo();
+
+private:
+ UndoStack();
+
+ bool m_inRedo;
+
+ typedef Deque<RefPtr<UndoStep> > UndoStepStack;
+ void filterOutUndoSteps(UndoStepStack&, const Frame&);
+ UndoStepStack m_undoStack;
+ UndoStepStack m_redoStack;
+};
+
+} // namespace WebCore
+
+#endif
diff --git a/chromium/third_party/WebKit/Source/core/editing/UndoStep.h b/chromium/third_party/WebKit/Source/core/editing/UndoStep.h
index bdc2b7cf10a..3084946773b 100644
--- a/chromium/third_party/WebKit/Source/core/editing/UndoStep.h
+++ b/chromium/third_party/WebKit/Source/core/editing/UndoStep.h
@@ -36,10 +36,13 @@
namespace WebCore {
+class Frame;
+
class UndoStep : public RefCounted<UndoStep> {
public:
virtual ~UndoStep() { }
+ virtual bool belongsTo(const Frame&) const = 0;
virtual void unapply() = 0;
virtual void reapply() = 0;
virtual EditAction editingAction() const = 0;
diff --git a/chromium/third_party/WebKit/Source/core/editing/VisiblePosition.cpp b/chromium/third_party/WebKit/Source/core/editing/VisiblePosition.cpp
index e8635680c5e..b158125184c 100644
--- a/chromium/third_party/WebKit/Source/core/editing/VisiblePosition.cpp
+++ b/chromium/third_party/WebKit/Source/core/editing/VisiblePosition.cpp
@@ -36,9 +36,9 @@
#include "core/editing/htmlediting.h"
#include "core/html/HTMLElement.h"
#include "core/html/HTMLHtmlElement.h"
-#include "core/platform/graphics/FloatQuad.h"
#include "core/rendering/RenderBlock.h"
#include "core/rendering/RootInlineBox.h"
+#include "platform/geometry/FloatQuad.h"
#include "wtf/text/CString.h"
#ifndef NDEBUG
@@ -749,9 +749,9 @@ bool setStart(Range *r, const VisiblePosition &visiblePosition)
if (!r)
return false;
Position p = visiblePosition.deepEquivalent().parentAnchoredEquivalent();
- TrackExceptionState es;
- r->setStart(p.containerNode(), p.offsetInContainerNode(), es);
- return !es.hadException();
+ TrackExceptionState exceptionState;
+ r->setStart(p.containerNode(), p.offsetInContainerNode(), exceptionState);
+ return !exceptionState.hadException();
}
bool setEnd(Range *r, const VisiblePosition &visiblePosition)
@@ -759,9 +759,9 @@ bool setEnd(Range *r, const VisiblePosition &visiblePosition)
if (!r)
return false;
Position p = visiblePosition.deepEquivalent().parentAnchoredEquivalent();
- TrackExceptionState es;
- r->setEnd(p.containerNode(), p.offsetInContainerNode(), es);
- return !es.hadException();
+ TrackExceptionState exceptionState;
+ r->setEnd(p.containerNode(), p.offsetInContainerNode(), exceptionState);
+ return !exceptionState.hadException();
}
Element* enclosingBlockFlowElement(const VisiblePosition &visiblePosition)
diff --git a/chromium/third_party/WebKit/Source/core/editing/VisiblePosition.h b/chromium/third_party/WebKit/Source/core/editing/VisiblePosition.h
index 6c3e93b3b60..f48245089f7 100644
--- a/chromium/third_party/WebKit/Source/core/editing/VisiblePosition.h
+++ b/chromium/third_party/WebKit/Source/core/editing/VisiblePosition.h
@@ -28,7 +28,7 @@
#include "core/dom/Position.h"
#include "core/editing/EditingBoundary.h"
-#include "core/platform/text/TextDirection.h"
+#include "platform/text/TextDirection.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/editing/VisibleSelection.cpp b/chromium/third_party/WebKit/Source/core/editing/VisibleSelection.cpp
index 96ae7ec1311..418c1030e0a 100644
--- a/chromium/third_party/WebKit/Source/core/editing/VisibleSelection.cpp
+++ b/chromium/third_party/WebKit/Source/core/editing/VisibleSelection.cpp
@@ -31,11 +31,10 @@
#include "core/dom/Element.h"
#include "core/dom/Range.h"
#include "core/editing/TextIterator.h"
-#include "core/editing/VisiblePosition.h"
#include "core/editing/VisibleUnits.h"
#include "core/editing/htmlediting.h"
-#include "core/platform/graphics/LayoutPoint.h"
#include "core/rendering/RenderObject.h"
+#include "platform/geometry/LayoutPoint.h"
#include "wtf/Assertions.h"
#include "wtf/text/CString.h"
#include "wtf/text/StringBuilder.h"
@@ -218,14 +217,14 @@ static PassRefPtr<Range> makeSearchRange(const Position& pos)
return 0;
RefPtr<Range> searchRange(Range::create(d));
- TrackExceptionState es;
+ TrackExceptionState exceptionState;
Position start(pos.parentAnchoredEquivalent());
- searchRange->selectNodeContents(boundary, es);
- searchRange->setStart(start.containerNode(), start.offsetInContainerNode(), es);
+ searchRange->selectNodeContents(boundary, exceptionState);
+ searchRange->setStart(start.containerNode(), start.offsetInContainerNode(), exceptionState);
- ASSERT(!es.hadException());
- if (es.hadException())
+ ASSERT(!exceptionState.hadException());
+ if (exceptionState.hadException())
return 0;
return searchRange.release();
@@ -472,7 +471,7 @@ static Position adjustPositionForEnd(const Position& currentPosition, Node* star
{
TreeScope& treeScope = startContainerNode->treeScope();
- ASSERT(&currentPosition.containerNode()->treeScope() != &treeScope);
+ ASSERT(currentPosition.containerNode()->treeScope() != treeScope);
if (Node* ancestor = treeScope.ancestorInThisScope(currentPosition.containerNode())) {
if (ancestor->contains(startContainerNode))
@@ -490,7 +489,7 @@ static Position adjustPositionForStart(const Position& currentPosition, Node* en
{
TreeScope& treeScope = endContainerNode->treeScope();
- ASSERT(&currentPosition.containerNode()->treeScope() != &treeScope);
+ ASSERT(currentPosition.containerNode()->treeScope() != treeScope);
if (Node* ancestor = treeScope.ancestorInThisScope(currentPosition.containerNode())) {
if (ancestor->contains(endContainerNode))
@@ -509,7 +508,7 @@ void VisibleSelection::adjustSelectionToAvoidCrossingShadowBoundaries()
if (m_base.isNull() || m_start.isNull() || m_end.isNull())
return;
- if (&m_start.anchorNode()->treeScope() == &m_end.anchorNode()->treeScope())
+ if (m_start.anchorNode()->treeScope() == m_end.anchorNode()->treeScope())
return;
if (m_baseIsFirst) {
@@ -520,7 +519,7 @@ void VisibleSelection::adjustSelectionToAvoidCrossingShadowBoundaries()
m_start = m_extent;
}
- ASSERT(&m_start.anchorNode()->treeScope() == &m_end.anchorNode()->treeScope());
+ ASSERT(m_start.anchorNode()->treeScope() == m_end.anchorNode()->treeScope());
}
void VisibleSelection::adjustSelectionToAvoidCrossingEditingBoundaries()
diff --git a/chromium/third_party/WebKit/Source/core/editing/VisibleSelection.h b/chromium/third_party/WebKit/Source/core/editing/VisibleSelection.h
index 5e515f8e32b..e5e9dd0a2fc 100644
--- a/chromium/third_party/WebKit/Source/core/editing/VisibleSelection.h
+++ b/chromium/third_party/WebKit/Source/core/editing/VisibleSelection.h
@@ -26,6 +26,7 @@
#ifndef VisibleSelection_h
#define VisibleSelection_h
+#include "core/editing/SelectionType.h"
#include "core/editing/TextGranularity.h"
#include "core/editing/VisiblePosition.h"
@@ -39,8 +40,6 @@ enum SelectionDirection { DirectionForward, DirectionBackward, DirectionRight, D
class VisibleSelection {
public:
- enum SelectionType { NoSelection, CaretSelection, RangeSelection };
-
VisibleSelection();
VisibleSelection(const Position&, EAffinity, bool isDirectional = false);
diff --git a/chromium/third_party/WebKit/Source/core/editing/VisibleUnits.cpp b/chromium/third_party/WebKit/Source/core/editing/VisibleUnits.cpp
index 4da6ae5184e..1f39b48d9d9 100644
--- a/chromium/third_party/WebKit/Source/core/editing/VisibleUnits.cpp
+++ b/chromium/third_party/WebKit/Source/core/editing/VisibleUnits.cpp
@@ -39,10 +39,10 @@
#include "core/editing/TextIterator.h"
#include "core/editing/VisiblePosition.h"
#include "core/editing/htmlediting.h"
-#include "core/platform/text/TextBoundaries.h"
#include "core/rendering/InlineTextBox.h"
-#include "core/rendering/RenderBlock.h"
+#include "core/rendering/RenderBlockFlow.h"
#include "core/rendering/RenderObject.h"
+#include "platform/text/TextBoundaries.h"
namespace WebCore {
@@ -326,18 +326,18 @@ static TextBreakIterator* wordBreakIteratorForMaxOffsetBoundary(const VisiblePos
static bool isLogicalStartOfWord(TextBreakIterator* iter, int position, bool hardLineBreak)
{
- bool boundary = hardLineBreak ? true : isTextBreak(iter, position);
+ bool boundary = hardLineBreak ? true : iter->isBoundary(position);
if (!boundary)
return false;
- textBreakFollowing(iter, position);
+ iter->following(position);
// isWordTextBreak returns true after moving across a word and false after moving across a punctuation/space.
return isWordTextBreak(iter);
}
static bool islogicalEndOfWord(TextBreakIterator* iter, int position, bool hardLineBreak)
{
- bool boundary = isTextBreak(iter, position);
+ bool boundary = iter->isBoundary(position);
return (hardLineBreak || boundary) && isWordTextBreak(iter);
}
@@ -391,7 +391,7 @@ static VisiblePosition visualWordPosition(const VisiblePosition& visiblePosition
if (!iter)
break;
- textBreakFirst(iter);
+ iter->first();
int offsetInIterator = offsetInBox - textBox->start() + previousBoxLength;
bool isWordBreak;
@@ -460,11 +460,11 @@ static VisiblePosition previousBoundary(const VisiblePosition& c, BoundarySearch
Vector<UChar, 1024> string;
unsigned suffixLength = 0;
- TrackExceptionState es;
+ TrackExceptionState exceptionState;
if (requiresContextForWordBoundary(c.characterBefore())) {
RefPtr<Range> forwardsScanRange(d.createRange());
- forwardsScanRange->setEndAfter(boundary, es);
- forwardsScanRange->setStart(end.deprecatedNode(), end.deprecatedEditingOffset(), es);
+ forwardsScanRange->setEndAfter(boundary, exceptionState);
+ forwardsScanRange->setStart(end.deprecatedNode(), end.deprecatedEditingOffset(), exceptionState);
TextIterator forwardsIterator(forwardsScanRange.get());
while (!forwardsIterator.atEnd()) {
Vector<UChar, 1024> characters;
@@ -478,18 +478,18 @@ static VisiblePosition previousBoundary(const VisiblePosition& c, BoundarySearch
}
}
- searchRange->setStart(start.deprecatedNode(), start.deprecatedEditingOffset(), es);
- searchRange->setEnd(end.deprecatedNode(), end.deprecatedEditingOffset(), es);
+ searchRange->setStart(start.deprecatedNode(), start.deprecatedEditingOffset(), exceptionState);
+ searchRange->setEnd(end.deprecatedNode(), end.deprecatedEditingOffset(), exceptionState);
- ASSERT(!es.hadException());
- if (es.hadException())
+ ASSERT(!exceptionState.hadException());
+ if (exceptionState.hadException())
return VisiblePosition();
SimplifiedBackwardsTextIterator it(searchRange.get());
unsigned next = 0;
- bool inTextSecurityMode = start.deprecatedNode() && start.deprecatedNode()->renderer() && start.deprecatedNode()->renderer()->style()->textSecurity() != TSNONE;
bool needMoreContext = false;
while (!it.atEnd()) {
+ bool inTextSecurityMode = it.node() && it.node()->renderer() && it.node()->renderer()->style()->textSecurity() != TSNONE;
// iterate to get chunks until the searchFunction returns a non-zero value.
if (!inTextSecurityMode)
it.prependTextTo(string);
@@ -562,11 +562,11 @@ static VisiblePosition nextBoundary(const VisiblePosition& c, BoundarySearchFunc
TextIterator it(searchRange.get(), TextIteratorEmitsCharactersBetweenAllVisiblePositions);
const unsigned invalidOffset = static_cast<unsigned>(-1);
unsigned next = invalidOffset;
- bool inTextSecurityMode = start.deprecatedNode() && start.deprecatedNode()->renderer() && start.deprecatedNode()->renderer()->style()->textSecurity() != TSNONE;
bool needMoreContext = false;
while (!it.atEnd()) {
// Keep asking the iterator for chunks until the search function
// returns an end value not equal to the length of the string passed to it.
+ bool inTextSecurityMode = it.node() && it.node()->renderer() && it.node()->renderer()->style()->textSecurity() != TSNONE;
if (!inTextSecurityMode)
it.appendTextTo(string);
else {
@@ -913,7 +913,7 @@ bool isEndOfLine(const VisiblePosition &p)
static inline IntPoint absoluteLineDirectionPointToLocalPointInBlock(RootInlineBox* root, int lineDirectionPoint)
{
ASSERT(root);
- RenderBlock* containingBlock = root->block();
+ RenderBlockFlow* containingBlock = root->block();
FloatPoint absoluteBlockPoint = containingBlock->localToAbsolute(FloatPoint());
if (containingBlock->hasOverflowClip())
absoluteBlockPoint -= containingBlock->scrolledContentOffset();
@@ -1008,7 +1008,7 @@ VisiblePosition nextLinePosition(const VisiblePosition &visiblePosition, int lin
if (!root) {
// FIXME: We need do the same in previousLinePosition.
Node* child = node->childNode(p.deprecatedEditingOffset());
- node = child ? child : node->lastDescendant();
+ node = child ? child : &node->lastDescendant();
Position position = nextRootInlineBoxCandidatePosition(node, visiblePosition, editableType);
if (position.isNotNull()) {
RenderedPosition renderedPosition(position);
@@ -1043,7 +1043,7 @@ static unsigned startSentenceBoundary(const UChar* characters, unsigned length,
{
TextBreakIterator* iterator = sentenceBreakIterator(characters, length);
// FIXME: The following function can return -1; we don't handle that.
- return textBreakPreceding(iterator, length);
+ return iterator->preceding(length);
}
VisiblePosition startOfSentence(const VisiblePosition &c)
@@ -1054,7 +1054,7 @@ VisiblePosition startOfSentence(const VisiblePosition &c)
static unsigned endSentenceBoundary(const UChar* characters, unsigned length, unsigned, BoundarySearchContextAvailability, bool&)
{
TextBreakIterator* iterator = sentenceBreakIterator(characters, length);
- return textBreakNext(iterator);
+ return iterator->next();
}
// FIXME: This includes the space after the punctuation that marks the end of the sentence.
@@ -1068,7 +1068,7 @@ static unsigned previousSentencePositionBoundary(const UChar* characters, unsign
// FIXME: This is identical to startSentenceBoundary. I'm pretty sure that's not right.
TextBreakIterator* iterator = sentenceBreakIterator(characters, length);
// FIXME: The following function can return -1; we don't handle that.
- return textBreakPreceding(iterator, length);
+ return iterator->preceding(length);
}
VisiblePosition previousSentencePosition(const VisiblePosition &c)
@@ -1082,7 +1082,7 @@ static unsigned nextSentencePositionBoundary(const UChar* characters, unsigned l
// FIXME: This is identical to endSentenceBoundary. This isn't right, it needs to
// move to the equivlant position in the following sentence.
TextBreakIterator* iterator = sentenceBreakIterator(characters, length);
- return textBreakFollowing(iterator, 0);
+ return iterator->following(0);
}
VisiblePosition nextSentencePosition(const VisiblePosition &c)
@@ -1110,23 +1110,24 @@ VisiblePosition startOfParagraph(const VisiblePosition& c, EditingBoundaryCrossi
Position::AnchorType type = p.anchorType();
Node* n = startNode;
+ bool startNodeIsEditable = startNode->rendererIsEditable();
while (n) {
- if (boundaryCrossingRule == CannotCrossEditingBoundary && !Position::nodeIsUserSelectAll(n) && n->rendererIsEditable() != startNode->rendererIsEditable())
+ if (boundaryCrossingRule == CannotCrossEditingBoundary && !Position::nodeIsUserSelectAll(n) && n->rendererIsEditable() != startNodeIsEditable)
break;
if (boundaryCrossingRule == CanSkipOverEditingBoundary) {
- while (n && n->rendererIsEditable() != startNode->rendererIsEditable())
- n = NodeTraversal::previousPostOrder(n, startBlock);
+ while (n && n->rendererIsEditable() != startNodeIsEditable)
+ n = NodeTraversal::previousPostOrder(*n, startBlock);
if (!n || !n->isDescendantOf(highestRoot))
break;
}
RenderObject* r = n->renderer();
if (!r) {
- n = NodeTraversal::previousPostOrder(n, startBlock);
+ n = NodeTraversal::previousPostOrder(*n, startBlock);
continue;
}
RenderStyle* style = r->style();
if (style->visibility() != VISIBLE) {
- n = NodeTraversal::previousPostOrder(n, startBlock);
+ n = NodeTraversal::previousPostOrder(*n, startBlock);
continue;
}
@@ -1149,13 +1150,14 @@ VisiblePosition startOfParagraph(const VisiblePosition& c, EditingBoundaryCrossi
}
node = n;
offset = 0;
- n = NodeTraversal::previousPostOrder(n, startBlock);
- } else if (editingIgnoresContent(n) || isTableElement(n)) {
+ n = NodeTraversal::previousPostOrder(*n, startBlock);
+ } else if (editingIgnoresContent(n) || isRenderedTable(n)) {
node = n;
type = Position::PositionIsBeforeAnchor;
- n = n->previousSibling() ? n->previousSibling() : NodeTraversal::previousPostOrder(n, startBlock);
- } else
- n = NodeTraversal::previousPostOrder(n, startBlock);
+ n = n->previousSibling() ? n->previousSibling() : NodeTraversal::previousPostOrder(*n, startBlock);
+ } else {
+ n = NodeTraversal::previousPostOrder(*n, startBlock);
+ }
}
if (type == Position::PositionIsOffsetInAnchor) {
@@ -1186,24 +1188,25 @@ VisiblePosition endOfParagraph(const VisiblePosition &c, EditingBoundaryCrossing
Position::AnchorType type = p.anchorType();
Node* n = startNode;
+ bool startNodeIsEditable = startNode->rendererIsEditable();
while (n) {
- if (boundaryCrossingRule == CannotCrossEditingBoundary && !Position::nodeIsUserSelectAll(n) && n->rendererIsEditable() != startNode->rendererIsEditable())
+ if (boundaryCrossingRule == CannotCrossEditingBoundary && !Position::nodeIsUserSelectAll(n) && n->rendererIsEditable() != startNodeIsEditable)
break;
if (boundaryCrossingRule == CanSkipOverEditingBoundary) {
- while (n && n->rendererIsEditable() != startNode->rendererIsEditable())
- n = NodeTraversal::next(n, stayInsideBlock);
+ while (n && n->rendererIsEditable() != startNodeIsEditable)
+ n = NodeTraversal::next(*n, stayInsideBlock);
if (!n || !n->isDescendantOf(highestRoot))
break;
}
RenderObject* r = n->renderer();
if (!r) {
- n = NodeTraversal::next(n, stayInsideBlock);
+ n = NodeTraversal::next(*n, stayInsideBlock);
continue;
}
RenderStyle* style = r->style();
if (style->visibility() != VISIBLE) {
- n = NodeTraversal::next(n, stayInsideBlock);
+ n = NodeTraversal::next(*n, stayInsideBlock);
continue;
}
@@ -1225,13 +1228,14 @@ VisiblePosition endOfParagraph(const VisiblePosition &c, EditingBoundaryCrossing
}
node = n;
offset = r->caretMaxOffset();
- n = NodeTraversal::next(n, stayInsideBlock);
- } else if (editingIgnoresContent(n) || isTableElement(n)) {
+ n = NodeTraversal::next(*n, stayInsideBlock);
+ } else if (editingIgnoresContent(n) || isRenderedTable(n)) {
node = n;
type = Position::PositionIsAfterAnchor;
- n = NodeTraversal::nextSkippingChildren(n, stayInsideBlock);
- } else
- n = NodeTraversal::next(n, stayInsideBlock);
+ n = NodeTraversal::nextSkippingChildren(*n, stayInsideBlock);
+ } else {
+ n = NodeTraversal::next(*n, stayInsideBlock);
+ }
}
if (type == Position::PositionIsOffsetInAnchor)
@@ -1366,7 +1370,7 @@ bool inSameDocument(const VisiblePosition &a, const VisiblePosition &b)
if (an == bn)
return true;
- return &an->document() == &bn->document();
+ return an->document() == bn->document();
}
bool isStartOfDocument(const VisiblePosition &p)
diff --git a/chromium/third_party/WebKit/Source/core/editing/VisibleUnits.h b/chromium/third_party/WebKit/Source/core/editing/VisibleUnits.h
index f1b9871bead..598990bd203 100644
--- a/chromium/third_party/WebKit/Source/core/editing/VisibleUnits.h
+++ b/chromium/third_party/WebKit/Source/core/editing/VisibleUnits.h
@@ -27,7 +27,7 @@
#define VisibleUnits_h
#include "core/editing/EditingBoundary.h"
-#include "core/platform/text/TextDirection.h"
+#include "platform/text/TextDirection.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/editing/chromium/EditorChromium.cpp b/chromium/third_party/WebKit/Source/core/editing/chromium/EditorChromium.cpp
deleted file mode 100644
index f8b8be70163..00000000000
--- a/chromium/third_party/WebKit/Source/core/editing/chromium/EditorChromium.cpp
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright (c) 2008, 2009, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/editing/Editor.h"
-
-#include "core/platform/chromium/ChromiumDataObject.h"
-#include "core/platform/chromium/ClipboardChromium.h"
-
-namespace WebCore {
-
-PassRefPtr<Clipboard> Editor::newGeneralClipboard(ClipboardAccessPolicy policy, Frame* frame)
-{
- return ClipboardChromium::create(
- Clipboard::CopyAndPaste,
- policy == ClipboardWritable ? ChromiumDataObject::create() : ChromiumDataObject::createFromPasteboard(),
- policy,
- frame);
-
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/editing/htmlediting.cpp b/chromium/third_party/WebKit/Source/core/editing/htmlediting.cpp
index 858d2e4a51e..6c00bb5d9a3 100644
--- a/chromium/third_party/WebKit/Source/core/editing/htmlediting.cpp
+++ b/chromium/third_party/WebKit/Source/core/editing/htmlediting.cpp
@@ -38,6 +38,7 @@
#include "core/dom/shadow/ShadowRoot.h"
#include "core/editing/Editor.h"
#include "core/editing/HTMLInterchange.h"
+#include "core/editing/PlainTextRange.h"
#include "core/editing/TextIterator.h"
#include "core/editing/VisiblePosition.h"
#include "core/editing/VisibleSelection.h"
@@ -49,12 +50,11 @@
#include "core/html/HTMLParagraphElement.h"
#include "core/html/HTMLTableElement.h"
#include "core/html/HTMLUListElement.h"
-#include "core/page/Frame.h"
+#include "core/frame/Frame.h"
#include "core/rendering/RenderObject.h"
#include "wtf/Assertions.h"
#include "wtf/StdLibExtras.h"
#include "wtf/text/StringBuilder.h"
-#include "wtf/unicode/CharacterNames.h"
using namespace std;
@@ -138,10 +138,6 @@ Node* highestEditableRoot(const Position& position, EditableType editableType)
Node* lowestEditableAncestor(Node* node)
{
- if (!node)
- return 0;
-
- Node* lowestRoot = 0;
while (node) {
if (node->rendererIsEditable())
return node->rootEditableElement();
@@ -150,7 +146,7 @@ Node* lowestEditableAncestor(Node* node)
node = node->parentNode();
}
- return lowestRoot;
+ return 0;
}
bool isEditablePosition(const Position& p, EditableType editableType, EUpdateStyle updateStyle)
@@ -163,7 +159,7 @@ bool isEditablePosition(const Position& p, EditableType editableType, EUpdateSty
else
ASSERT(updateStyle == DoNotUpdateStyle);
- if (node->renderer() && node->renderer()->isTable())
+ if (isTableElement(node))
node = node->parentNode();
return node->rendererIsEditable(editableType);
@@ -182,7 +178,7 @@ bool isRichlyEditablePosition(const Position& p, EditableType editableType)
if (!node)
return false;
- if (node->renderer() && node->renderer()->isTable())
+ if (isTableElement(node))
node = node->parentNode();
return node->rendererIsRichlyEditable(editableType);
@@ -194,7 +190,7 @@ Element* editableRootForPosition(const Position& p, EditableType editableType)
if (!node)
return 0;
- if (node->renderer() && node->renderer()->isTable())
+ if (isTableElement(node))
node = node->parentNode();
return node->rootEditableElement(editableType);
@@ -268,7 +264,7 @@ VisiblePosition firstEditablePositionAfterPositionInRoot(const Position& positio
Position p = position;
- if (&position.deprecatedNode()->treeScope() != &highestRoot->treeScope()) {
+ if (position.deprecatedNode()->treeScope() != highestRoot->treeScope()) {
Node* shadowAncestor = highestRoot->treeScope().ancestorInThisScope(p.deprecatedNode());
if (!shadowAncestor)
return VisiblePosition();
@@ -293,7 +289,7 @@ VisiblePosition lastEditablePositionBeforePositionInRoot(const Position& positio
Position p = position;
- if (&position.deprecatedNode()->treeScope() != &highestRoot->treeScope()) {
+ if (position.deprecatedNode()->treeScope() != highestRoot->treeScope()) {
Node* shadowAncestor = highestRoot->treeScope().ancestorInThisScope(p.deprecatedNode());
if (!shadowAncestor)
return VisiblePosition();
@@ -314,12 +310,12 @@ VisiblePosition lastEditablePositionBeforePositionInRoot(const Position& positio
// Whether or not content before and after this node will collapse onto the same line as it.
bool isBlock(const Node* node)
{
- return node && node->renderer() && !node->renderer()->isInline() && !node->renderer()->isRubyText();
+ return node && node->isElementNode() && node->renderer() && !node->renderer()->isInline() && !node->renderer()->isRubyText();
}
bool isInline(const Node* node)
{
- return node && node->renderer() && node->renderer()->isInline();
+ return node && node->isElementNode() && node->renderer() && node->renderer()->isInline();
}
// FIXME: Deploy this in all of the places where enclosingBlockFlow/enclosingBlockFlowOrTableElement are used.
@@ -329,7 +325,7 @@ bool isInline(const Node* node)
Element* enclosingBlock(Node* node, EditingBoundaryCrossingRule rule)
{
Node* enclosingNode = enclosingNodeOfType(firstPositionInOrBeforeNode(node), isBlock, rule);
- return enclosingNode && enclosingNode->isElementNode() ? toElement(enclosingNode) : 0;
+ return toElement(enclosingNode);
}
TextDirection directionOfEnclosingBlock(const Position& position)
@@ -437,7 +433,7 @@ static Node* firstInSpecialElement(const Position& pos)
if (isSpecialElement(n)) {
VisiblePosition vPos = VisiblePosition(pos, DOWNSTREAM);
VisiblePosition firstInElement = VisiblePosition(firstPositionInOrBeforeNode(n), DOWNSTREAM);
- if (isTableElement(n) && vPos == firstInElement.next())
+ if (isRenderedTable(n) && vPos == firstInElement.next())
return n;
if (vPos == firstInElement)
return n;
@@ -452,7 +448,7 @@ static Node* lastInSpecialElement(const Position& pos)
if (isSpecialElement(n)) {
VisiblePosition vPos = VisiblePosition(pos, DOWNSTREAM);
VisiblePosition lastInElement = VisiblePosition(lastPositionInOrAfterNode(n), DOWNSTREAM);
- if (isTableElement(n) && vPos == lastInElement.previous())
+ if (isRenderedTable(n) && vPos == lastInElement.previous())
return n;
if (vPos == lastInElement)
return n;
@@ -489,7 +485,7 @@ Position positionAfterContainingSpecialElement(const Position& pos, Node **conta
Node* isFirstPositionAfterTable(const VisiblePosition& visiblePosition)
{
Position upstream(visiblePosition.deepEquivalent().upstream());
- if (upstream.deprecatedNode() && upstream.deprecatedNode()->renderer() && upstream.deprecatedNode()->renderer()->isTable() && upstream.atLastEditingPositionForNode())
+ if (isRenderedTable(upstream.deprecatedNode()) && upstream.atLastEditingPositionForNode())
return upstream.deprecatedNode();
return 0;
@@ -498,7 +494,7 @@ Node* isFirstPositionAfterTable(const VisiblePosition& visiblePosition)
Node* isLastPositionBeforeTable(const VisiblePosition& visiblePosition)
{
Position downstream(visiblePosition.deepEquivalent().downstream());
- if (downstream.deprecatedNode() && downstream.deprecatedNode()->renderer() && downstream.deprecatedNode()->renderer()->isTable() && downstream.atFirstEditingPositionForNode())
+ if (isRenderedTable(downstream.deprecatedNode()) && downstream.atFirstEditingPositionForNode())
return downstream.deprecatedNode();
return 0;
@@ -529,12 +525,12 @@ VisiblePosition visiblePositionAfterNode(Node* node)
// Create a range object with two visible positions, start and end.
// create(Document*, const Position&, const Position&); will use deprecatedEditingOffset
// Use this function instead of create a regular range object (avoiding editing offset).
-PassRefPtr<Range> createRange(Document& document, const VisiblePosition& start, const VisiblePosition& end, ExceptionState& es)
+PassRefPtr<Range> createRange(Document& document, const VisiblePosition& start, const VisiblePosition& end, ExceptionState& exceptionState)
{
RefPtr<Range> selectedRange = Range::create(document);
- selectedRange->setStart(start.deepEquivalent().containerNode(), start.deepEquivalent().computeOffsetInContainerNode(), es);
- if (!es.hadException())
- selectedRange->setEnd(end.deepEquivalent().containerNode(), end.deepEquivalent().computeOffsetInContainerNode(), es);
+ selectedRange->setStart(start.deepEquivalent().containerNode(), start.deepEquivalent().computeOffsetInContainerNode(), exceptionState);
+ if (!exceptionState.hadException())
+ selectedRange->setEnd(end.deepEquivalent().containerNode(), end.deepEquivalent().computeOffsetInContainerNode(), exceptionState);
return selectedRange.release();
}
@@ -608,12 +604,12 @@ static bool hasARenderedDescendant(Node* node, Node* excludedNode)
{
for (Node* n = node->firstChild(); n;) {
if (n == excludedNode) {
- n = NodeTraversal::nextSkippingChildren(n, node);
+ n = NodeTraversal::nextSkippingChildren(*n, node);
continue;
}
if (n->renderer())
return true;
- n = NodeTraversal::next(n, node);
+ n = NodeTraversal::next(*n, node);
}
return false;
}
@@ -755,14 +751,21 @@ bool canMergeLists(Element* firstList, Element* secondList)
// Make sure there is no visible content between this li and the previous list
}
-// FIXME: do not require renderer, so that this can be used within fragments, or rename to isRenderedTable()
-bool isTableElement(Node* n)
+bool isTableElement(const Node* node)
{
- if (!n || !n->isElementNode())
+ if (!node || !node->isElementNode())
return false;
- RenderObject* renderer = n->renderer();
- return (renderer && (renderer->style()->display() == TABLE || renderer->style()->display() == INLINE_TABLE));
+ return node->hasTagName(tableTag);
+}
+
+bool isRenderedTable(const Node* node)
+{
+ if (!node || !node->isElementNode())
+ return false;
+
+ RenderObject* renderer = node->renderer();
+ return (renderer && renderer->isTable());
}
bool isTableCell(const Node* node)
@@ -842,12 +845,12 @@ PassRefPtr<HTMLElement> createListItemElement(Document& document)
PassRefPtr<HTMLElement> createHTMLElement(Document& document, const QualifiedName& name)
{
- return HTMLElementFactory::createHTMLElement(name, &document, 0, false);
+ return createHTMLElement(document, name.localName());
}
PassRefPtr<HTMLElement> createHTMLElement(Document& document, const AtomicString& tagName)
{
- return createHTMLElement(document, QualifiedName(nullAtom, tagName, xhtmlNamespaceURI));
+ return HTMLElementFactory::createHTMLElement(tagName, document, 0, false);
}
bool isTabSpanNode(const Node *node)
@@ -1064,7 +1067,9 @@ int indexForVisiblePosition(const VisiblePosition& visiblePosition, RefPtr<Conta
VisiblePosition visiblePositionForIndex(int index, ContainerNode* scope)
{
- RefPtr<Range> range = TextIterator::rangeFromLocationAndLength(scope, index, 0, true);
+ if (!scope)
+ return VisiblePosition();
+ RefPtr<Range> range = PlainTextRange(index).createRangeForSelection(*scope);
// Check for an invalid index. Certain editing operations invalidate indices because
// of problems with TextIteratorEmitsCharactersBetweenAllVisiblePositions.
if (!range)
diff --git a/chromium/third_party/WebKit/Source/core/editing/htmlediting.h b/chromium/third_party/WebKit/Source/core/editing/htmlediting.h
index 7821ebe8c80..1d7e52c49e0 100644
--- a/chromium/third_party/WebKit/Source/core/editing/htmlediting.h
+++ b/chromium/third_party/WebKit/Source/core/editing/htmlediting.h
@@ -28,7 +28,7 @@
#include "core/dom/Position.h"
#include "core/editing/EditingBoundary.h"
-#include "core/platform/text/TextDirection.h"
+#include "platform/text/TextDirection.h"
#include "wtf/Forward.h"
#include "wtf/unicode/CharacterNames.h"
@@ -101,7 +101,8 @@ bool isSpecialElement(const Node*);
bool isTabSpanNode(const Node*);
bool isTabSpanTextNode(const Node*);
bool isMailBlockquote(const Node*);
-bool isTableElement(Node*);
+bool isRenderedTable(const Node*);
+bool isTableElement(const Node*);
bool isTableCell(const Node*);
bool isEmptyTableCell(const Node*);
bool isTableStructureNode(const Node*);
diff --git a/chromium/third_party/WebKit/Source/core/editing/markup.cpp b/chromium/third_party/WebKit/Source/core/editing/markup.cpp
index 7e0f8074103..184ed05a8a2 100644
--- a/chromium/third_party/WebKit/Source/core/editing/markup.cpp
+++ b/chromium/third_party/WebKit/Source/core/editing/markup.cpp
@@ -55,9 +55,9 @@
#include "core/html/HTMLHtmlElement.h"
#include "core/html/HTMLTableElement.h"
#include "core/html/HTMLTextFormControlElement.h"
-#include "core/page/Frame.h"
+#include "core/frame/Frame.h"
#include "core/rendering/RenderObject.h"
-#include "weborigin/KURL.h"
+#include "platform/weborigin/KURL.h"
#include "wtf/StdLibExtras.h"
#include "wtf/text/StringBuilder.h"
@@ -83,7 +83,7 @@ public:
void apply()
{
- m_element->setAttribute(m_name, m_value);
+ m_element->setAttribute(m_name, AtomicString(m_value));
}
private:
@@ -92,13 +92,13 @@ private:
String m_value;
};
-static void completeURLs(DocumentFragment* fragment, const String& baseURL)
+static void completeURLs(DocumentFragment& fragment, const String& baseURL)
{
Vector<AttributeChange> changes;
KURL parsedBaseURL(ParsedURLString, baseURL);
- for (Element* element = ElementTraversal::firstWithin(fragment); element; element = ElementTraversal::next(element, fragment)) {
+ for (Element* element = ElementTraversal::firstWithin(fragment); element; element = ElementTraversal::next(*element, &fragment)) {
if (!element->hasAttributes())
continue;
unsigned length = element->attributeCount();
@@ -354,7 +354,7 @@ Node* StyledMarkupAccumulator::traverseNodesForSerialization(Node* startNode, No
if (!n)
break;
- next = NodeTraversal::next(n);
+ next = NodeTraversal::next(*n);
bool openedTag = false;
if (isBlock(n) && canHaveChildrenForEditing(n) && next == pastEnd)
@@ -362,7 +362,7 @@ Node* StyledMarkupAccumulator::traverseNodesForSerialization(Node* startNode, No
continue;
if (!n->renderer() && !enclosingNodeWithTag(firstPositionInOrBeforeNode(n), selectTag)) {
- next = NodeTraversal::nextSkippingChildren(n);
+ next = NodeTraversal::nextSkippingChildren(*n);
// Don't skip over pastEnd.
if (pastEnd && pastEnd->isDescendantOf(n))
next = pastEnd;
@@ -647,7 +647,7 @@ PassRefPtr<DocumentFragment> createFragmentFromMarkup(Document& document, const
fragment->parseHTML(markup, fakeBody.get(), parserContentPolicy);
if (!baseURL.isEmpty() && baseURL != blankURL() && baseURL != document.baseURL())
- completeURLs(fragment.get(), baseURL);
+ completeURLs(*fragment, baseURL);
return fragment.release();
}
@@ -656,7 +656,7 @@ static const char fragmentMarkerTag[] = "webkit-fragment-marker";
static bool findNodesSurroundingContext(Document* document, RefPtr<Node>& nodeBeforeContext, RefPtr<Node>& nodeAfterContext)
{
- for (Node* node = document->firstChild(); node; node = NodeTraversal::next(node)) {
+ for (Node* node = document->firstChild(); node; node = NodeTraversal::next(*node)) {
if (node->nodeType() == Node::COMMENT_NODE && toCharacterData(node)->data() == fragmentMarkerTag) {
if (!nodeBeforeContext)
nodeBeforeContext = node;
@@ -674,10 +674,10 @@ static void trimFragment(DocumentFragment* fragment, Node* nodeBeforeContext, No
RefPtr<Node> next;
for (RefPtr<Node> node = fragment->firstChild(); node; node = next) {
if (nodeBeforeContext->isDescendantOf(node.get())) {
- next = NodeTraversal::next(node.get());
+ next = NodeTraversal::next(*node);
continue;
}
- next = NodeTraversal::nextSkippingChildren(node.get());
+ next = NodeTraversal::nextSkippingChildren(*node);
ASSERT(!node->contains(nodeAfterContext));
node->parentNode()->removeChild(node.get(), ASSERT_NO_EXCEPTION);
if (nodeBeforeContext == node)
@@ -686,7 +686,7 @@ static void trimFragment(DocumentFragment* fragment, Node* nodeBeforeContext, No
ASSERT(nodeAfterContext->parentNode());
for (RefPtr<Node> node = nodeAfterContext; node; node = next) {
- next = NodeTraversal::nextSkippingChildren(node.get());
+ next = NodeTraversal::nextSkippingChildren(*node);
node->parentNode()->removeChild(node.get(), ASSERT_NO_EXCEPTION);
}
}
@@ -706,7 +706,10 @@ PassRefPtr<DocumentFragment> createFragmentFromMarkupWithContext(Document& docum
RefPtr<DocumentFragment> taggedFragment = createFragmentFromMarkup(document, taggedMarkup.toString(), baseURL, parserContentPolicy);
RefPtr<Document> taggedDocument = Document::create();
taggedDocument->setContextFeatures(document.contextFeatures());
- taggedDocument->takeAllChildrenFrom(taggedFragment.get());
+
+ // FIXME: It's not clear what this code is trying to do. It puts nodes as direct children of a
+ // Document that are not normally allowed by using the parser machinery.
+ taggedDocument->parserTakeAllChildrenFrom(*taggedFragment);
RefPtr<Node> nodeBeforeContext;
RefPtr<Node> nodeAfterContext;
@@ -727,7 +730,7 @@ PassRefPtr<DocumentFragment> createFragmentFromMarkupWithContext(Document& docum
if (specialCommonAncestor)
fragment->appendChild(specialCommonAncestor);
else
- fragment->takeAllChildrenFrom(toContainerNode(commonAncestor));
+ fragment->parserTakeAllChildrenFrom(toContainerNode(*commonAncestor));
trimFragment(fragment.get(), nodeBeforeContext.get(), nodeAfterContext.get());
@@ -939,7 +942,7 @@ String urlToMarkup(const KURL& url, const String& title)
return markup.toString();
}
-PassRefPtr<DocumentFragment> createFragmentForInnerOuterHTML(const String& markup, Element* contextElement, ParserContentPolicy parserContentPolicy, ExceptionState& es)
+PassRefPtr<DocumentFragment> createFragmentForInnerOuterHTML(const String& markup, Element* contextElement, ParserContentPolicy parserContentPolicy, const char* method, ExceptionState& exceptionState)
{
Document& document = contextElement->hasTagName(templateTag) ? contextElement->document().ensureTemplateDocument() : contextElement->document();
RefPtr<DocumentFragment> fragment = DocumentFragment::create(document);
@@ -951,7 +954,7 @@ PassRefPtr<DocumentFragment> createFragmentForInnerOuterHTML(const String& marku
bool wasValid = fragment->parseXML(markup, contextElement, parserContentPolicy);
if (!wasValid) {
- es.throwDOMException(SyntaxError);
+ exceptionState.throwDOMException(SyntaxError, "The provided markup is invalid XML, and therefore cannot be inserted into an XML document.");
return 0;
}
return fragment.release();
@@ -992,21 +995,16 @@ static inline void removeElementPreservingChildren(PassRefPtr<DocumentFragment>
fragment->removeChild(element);
}
-PassRefPtr<DocumentFragment> createContextualFragment(const String& markup, HTMLElement* element, ParserContentPolicy parserContentPolicy, ExceptionState& es)
+PassRefPtr<DocumentFragment> createContextualFragment(const String& markup, HTMLElement* element, ParserContentPolicy parserContentPolicy, ExceptionState& exceptionState)
{
ASSERT(element);
- if (element->ieForbidsInsertHTML()) {
- es.throwDOMException(NotSupportedError);
- return 0;
- }
-
- if (element->hasLocalName(colTag) || element->hasLocalName(colgroupTag) || element->hasLocalName(framesetTag)
+ if (element->ieForbidsInsertHTML() || element->hasLocalName(colTag) || element->hasLocalName(colgroupTag) || element->hasLocalName(framesetTag)
|| element->hasLocalName(headTag) || element->hasLocalName(styleTag) || element->hasLocalName(titleTag)) {
- es.throwDOMException(NotSupportedError);
+ exceptionState.throwDOMException(NotSupportedError, "The range's container is '" + element->localName() + "', which is not supported.");
return 0;
}
- RefPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(markup, element, parserContentPolicy, es);
+ RefPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(markup, element, parserContentPolicy, "createContextualFragment", exceptionState);
if (!fragment)
return 0;
@@ -1018,7 +1016,7 @@ PassRefPtr<DocumentFragment> createContextualFragment(const String& markup, HTML
for (RefPtr<Node> node = fragment->firstChild(); node; node = nextNode) {
nextNode = node->nextSibling();
if (isHTMLHtmlElement(node.get()) || node->hasTagName(headTag) || node->hasTagName(bodyTag)) {
- HTMLElement* element = toHTMLElement(node.get());
+ HTMLElement* element = toHTMLElement(node);
if (Node* firstChild = element->firstChild())
nextNode = firstChild;
removeElementPreservingChildren(fragment, element);
@@ -1027,11 +1025,12 @@ PassRefPtr<DocumentFragment> createContextualFragment(const String& markup, HTML
return fragment.release();
}
-void replaceChildrenWithFragment(ContainerNode* container, PassRefPtr<DocumentFragment> fragment, ExceptionState& es)
+void replaceChildrenWithFragment(ContainerNode* container, PassRefPtr<DocumentFragment> fragment, ExceptionState& exceptionState)
{
+ ASSERT(container);
RefPtr<ContainerNode> containerNode(container);
- ChildListMutationScope mutation(containerNode.get());
+ ChildListMutationScope mutation(*containerNode);
if (!fragment->firstChild()) {
containerNode->removeChildren();
@@ -1044,19 +1043,20 @@ void replaceChildrenWithFragment(ContainerNode* container, PassRefPtr<DocumentFr
}
if (containerNode->hasOneChild()) {
- containerNode->replaceChild(fragment, containerNode->firstChild(), es);
+ containerNode->replaceChild(fragment, containerNode->firstChild(), exceptionState);
return;
}
containerNode->removeChildren();
- containerNode->appendChild(fragment, es);
+ containerNode->appendChild(fragment, exceptionState);
}
-void replaceChildrenWithText(ContainerNode* container, const String& text, ExceptionState& es)
+void replaceChildrenWithText(ContainerNode* container, const String& text, ExceptionState& exceptionState)
{
+ ASSERT(container);
RefPtr<ContainerNode> containerNode(container);
- ChildListMutationScope mutation(containerNode.get());
+ ChildListMutationScope mutation(*containerNode);
if (containerNode->hasOneTextChild()) {
toText(containerNode->firstChild())->setData(text);
@@ -1066,12 +1066,26 @@ void replaceChildrenWithText(ContainerNode* container, const String& text, Excep
RefPtr<Text> textNode = Text::create(containerNode->document(), text);
if (containerNode->hasOneChild()) {
- containerNode->replaceChild(textNode.release(), containerNode->firstChild(), es);
+ containerNode->replaceChild(textNode.release(), containerNode->firstChild(), exceptionState);
return;
}
containerNode->removeChildren();
- containerNode->appendChild(textNode.release(), es);
+ containerNode->appendChild(textNode.release(), exceptionState);
+}
+
+void mergeWithNextTextNode(PassRefPtr<Node> node, ExceptionState& exceptionState)
+{
+ ASSERT(node && node->isTextNode());
+ Node* next = node->nextSibling();
+ if (!next || !next->isTextNode())
+ return;
+
+ RefPtr<Text> textNode = toText(node.get());
+ RefPtr<Text> textNext = toText(next);
+ textNode->appendData(textNext->data());
+ if (textNext->parentNode()) // Might have been removed by mutation event.
+ textNext->remove(exceptionState);
}
}
diff --git a/chromium/third_party/WebKit/Source/core/editing/markup.h b/chromium/third_party/WebKit/Source/core/editing/markup.h
index b29344129fe..f12209269e9 100644
--- a/chromium/third_party/WebKit/Source/core/editing/markup.h
+++ b/chromium/third_party/WebKit/Source/core/editing/markup.h
@@ -51,7 +51,7 @@ PassRefPtr<DocumentFragment> createFragmentFromText(Range* context, const String
PassRefPtr<DocumentFragment> createFragmentFromMarkup(Document&, const String& markup, const String& baseURL, ParserContentPolicy = AllowScriptingContent);
PassRefPtr<DocumentFragment> createFragmentFromMarkupWithContext(Document&, const String& markup, unsigned fragmentStart, unsigned fragmentEnd, const String& baseURL, ParserContentPolicy);
PassRefPtr<DocumentFragment> createFragmentFromNodes(Document*, const Vector<Node*>&);
-PassRefPtr<DocumentFragment> createFragmentForInnerOuterHTML(const String&, Element*, ParserContentPolicy, ExceptionState&);
+PassRefPtr<DocumentFragment> createFragmentForInnerOuterHTML(const String&, Element*, ParserContentPolicy, const char* method, ExceptionState&);
PassRefPtr<DocumentFragment> createFragmentForTransformToFragment(const String&, const String& sourceMIMEType, Document& outputDoc);
PassRefPtr<DocumentFragment> createContextualFragment(const String&, HTMLElement*, ParserContentPolicy, ExceptionState&);
@@ -69,6 +69,7 @@ String createFullMarkup(const Node*);
String createFullMarkup(const Range*);
String urlToMarkup(const KURL&, const String& title);
+void mergeWithNextTextNode(PassRefPtr<Node>, ExceptionState&);
}
diff --git a/chromium/third_party/WebKit/Source/core/events/AutocompleteErrorEvent.h b/chromium/third_party/WebKit/Source/core/events/AutocompleteErrorEvent.h
new file mode 100644
index 00000000000..1eed01deb6f
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/AutocompleteErrorEvent.h
@@ -0,0 +1,83 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef AutocompleteErrorEvent_h
+#define AutocompleteErrorEvent_h
+
+#include "core/events/Event.h"
+#include "core/events/ThreadLocalEventNames.h"
+
+namespace WebCore {
+
+struct AutocompleteErrorEventInit : public EventInit {
+ String reason;
+};
+
+class AutocompleteErrorEvent : public Event {
+public:
+ static PassRefPtr<AutocompleteErrorEvent> create()
+ {
+ return adoptRef(new AutocompleteErrorEvent);
+ }
+
+ static PassRefPtr<AutocompleteErrorEvent> create(const String& reason)
+ {
+ return adoptRef(new AutocompleteErrorEvent(reason));
+ }
+
+ static PassRefPtr<AutocompleteErrorEvent> create(const AtomicString& eventType, const AutocompleteErrorEventInit& initializer)
+ {
+ return adoptRef(new AutocompleteErrorEvent(eventType, initializer));
+ }
+
+ const String& reason() const { return m_reason; }
+
+ virtual const AtomicString& interfaceName() const { return EventNames::AutocompleteErrorEvent; }
+
+private:
+ AutocompleteErrorEvent()
+ {
+ ScriptWrappable::init(this);
+ }
+
+ AutocompleteErrorEvent(const String& reason)
+ : Event(EventTypeNames::autocompleteerror, false, false)
+ , m_reason(reason)
+ {
+ ScriptWrappable::init(this);
+ }
+
+ AutocompleteErrorEvent(const AtomicString& eventType, const AutocompleteErrorEventInit& initializer)
+ : Event(eventType, initializer)
+ , m_reason(initializer.reason)
+ {
+ ScriptWrappable::init(this);
+ }
+
+ String m_reason;
+};
+
+} // namespace WebCore
+
+#endif // AutocompleteErrorEvent_h
diff --git a/chromium/third_party/WebKit/Source/core/events/AutocompleteErrorEvent.idl b/chromium/third_party/WebKit/Source/core/events/AutocompleteErrorEvent.idl
new file mode 100644
index 00000000000..865d62e7469
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/AutocompleteErrorEvent.idl
@@ -0,0 +1,30 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+[
+ EventConstructor,
+] interface AutocompleteErrorEvent : Event {
+ [InitializedByEventConstructor] readonly attribute DOMString reason;
+};
+
diff --git a/chromium/third_party/WebKit/Source/core/events/BeforeLoadEvent.h b/chromium/third_party/WebKit/Source/core/events/BeforeLoadEvent.h
new file mode 100644
index 00000000000..f52c5377f2a
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/BeforeLoadEvent.h
@@ -0,0 +1,89 @@
+/*
+ * Copyright (C) 2009 Apple Inc. All Rights Reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#ifndef BeforeLoadEvent_h
+#define BeforeLoadEvent_h
+
+#include "core/events/Event.h"
+#include "core/events/ThreadLocalEventNames.h"
+
+namespace WebCore {
+
+struct BeforeLoadEventInit : public EventInit {
+ BeforeLoadEventInit()
+ {
+ };
+
+ String url;
+};
+
+class BeforeLoadEvent : public Event {
+public:
+ static PassRefPtr<BeforeLoadEvent> create()
+ {
+ return adoptRef(new BeforeLoadEvent);
+ }
+
+ static PassRefPtr<BeforeLoadEvent> create(const String& url)
+ {
+ return adoptRef(new BeforeLoadEvent(url));
+ }
+
+ static PassRefPtr<BeforeLoadEvent> create(const AtomicString& type, const BeforeLoadEventInit& initializer)
+ {
+ return adoptRef(new BeforeLoadEvent(type, initializer));
+ }
+
+ const String& url() const { return m_url; }
+
+ virtual const AtomicString& interfaceName() const { return EventNames::BeforeLoadEvent; }
+
+private:
+ BeforeLoadEvent()
+ {
+ ScriptWrappable::init(this);
+ }
+
+ explicit BeforeLoadEvent(const String& url)
+ : Event(EventTypeNames::beforeload, false, true)
+ , m_url(url)
+ {
+ ScriptWrappable::init(this);
+ }
+
+ BeforeLoadEvent(const AtomicString& type, const BeforeLoadEventInit& initializer)
+ : Event(type, initializer)
+ , m_url(initializer.url)
+ {
+ ScriptWrappable::init(this);
+ }
+
+ String m_url;
+};
+
+} // namespace WebCore
+
+#endif // BeforeLoadEvent_h
diff --git a/chromium/third_party/WebKit/Source/core/events/BeforeLoadEvent.idl b/chromium/third_party/WebKit/Source/core/events/BeforeLoadEvent.idl
new file mode 100644
index 00000000000..6f8eca6e654
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/BeforeLoadEvent.idl
@@ -0,0 +1,32 @@
+/*
+ * Copyright (C) 2009 Apple Inc. All Rights Reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+[
+ EventConstructor,
+] interface BeforeLoadEvent : Event {
+ [InitializedByEventConstructor] readonly attribute DOMString url;
+};
+
diff --git a/chromium/third_party/WebKit/Source/core/events/BeforeTextInsertedEvent.cpp b/chromium/third_party/WebKit/Source/core/events/BeforeTextInsertedEvent.cpp
new file mode 100644
index 00000000000..fc0ed37f5d1
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/BeforeTextInsertedEvent.cpp
@@ -0,0 +1,48 @@
+/*
+ * Copyright (C) 2005 Apple Computer, Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/events/BeforeTextInsertedEvent.h"
+
+#include "core/events/ThreadLocalEventNames.h"
+
+namespace WebCore {
+
+BeforeTextInsertedEvent::BeforeTextInsertedEvent(const String& text)
+ : Event(EventTypeNames::webkitBeforeTextInserted, false, true), m_text(text)
+{
+}
+
+BeforeTextInsertedEvent::~BeforeTextInsertedEvent()
+{
+}
+
+const AtomicString& BeforeTextInsertedEvent::interfaceName() const
+{
+ // Notice that there is no BeforeTextInsertedEvent.idl.
+ return EventNames::Event;
+}
+
+}
diff --git a/chromium/third_party/WebKit/Source/core/events/BeforeTextInsertedEvent.h b/chromium/third_party/WebKit/Source/core/events/BeforeTextInsertedEvent.h
new file mode 100644
index 00000000000..546c4fb7364
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/BeforeTextInsertedEvent.h
@@ -0,0 +1,56 @@
+/*
+ * Copyright (C) 2006 Apple Computer, Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef BeforeTextInsertedEvent_h
+#define BeforeTextInsertedEvent_h
+
+#include "core/events/Event.h"
+
+namespace WebCore {
+
+class BeforeTextInsertedEvent : public Event {
+public:
+ virtual ~BeforeTextInsertedEvent();
+
+ static PassRefPtr<BeforeTextInsertedEvent> create(const String& text)
+ {
+ return adoptRef(new BeforeTextInsertedEvent(text));
+ }
+
+ virtual const AtomicString& interfaceName() const;
+ virtual bool isBeforeTextInsertedEvent() const { return true; }
+
+ const String& text() const { return m_text; }
+ void setText(const String& s) { m_text = s; }
+
+private:
+ explicit BeforeTextInsertedEvent(const String&);
+
+ String m_text;
+};
+
+} // namespace
+
+#endif
diff --git a/chromium/third_party/WebKit/Source/core/events/BeforeUnloadEvent.cpp b/chromium/third_party/WebKit/Source/core/events/BeforeUnloadEvent.cpp
new file mode 100644
index 00000000000..15dd1ad9520
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/BeforeUnloadEvent.cpp
@@ -0,0 +1,45 @@
+/*
+ * Copyright (C) 2001 Peter Kelly (pmk@post.com)
+ * Copyright (C) 2001 Tobias Anton (anton@stud.fbi.fh-darmstadt.de)
+ * Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
+ * Copyright (C) 2003, 2005, 2006 Apple Computer, Inc.
+ * Copyright (C) 2013 Samsung Electronics.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#include "config.h"
+#include "core/events/BeforeUnloadEvent.h"
+
+
+namespace WebCore {
+
+BeforeUnloadEvent::BeforeUnloadEvent()
+ : Event(EventTypeNames::beforeunload, false, true)
+{
+ ScriptWrappable::init(this);
+}
+
+BeforeUnloadEvent::~BeforeUnloadEvent()
+{
+}
+
+bool BeforeUnloadEvent::isBeforeUnloadEvent() const
+{
+ return true;
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/events/BeforeUnloadEvent.h b/chromium/third_party/WebKit/Source/core/events/BeforeUnloadEvent.h
new file mode 100644
index 00000000000..57136f92ae8
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/BeforeUnloadEvent.h
@@ -0,0 +1,59 @@
+/*
+ * Copyright (C) 2001 Peter Kelly (pmk@post.com)
+ * Copyright (C) 2001 Tobias Anton (anton@stud.fbi.fh-darmstadt.de)
+ * Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
+ * Copyright (C) 2003, 2004, 2005, 2006 Apple Computer, Inc.
+ * Copyright (C) 2013 Samsung Electronics.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ */
+
+#ifndef BeforeUnloadEvent_h
+#define BeforeUnloadEvent_h
+
+#include "core/events/Event.h"
+#include "core/events/ThreadLocalEventNames.h"
+
+namespace WebCore {
+
+class BeforeUnloadEvent : public Event {
+public:
+ virtual ~BeforeUnloadEvent();
+
+ static PassRefPtr<BeforeUnloadEvent> create()
+ {
+ return adoptRef(new BeforeUnloadEvent);
+ }
+
+ virtual bool isBeforeUnloadEvent() const OVERRIDE;
+
+ void setReturnValue(const String& returnValue) { m_returnValue = returnValue; }
+ String returnValue() const { return m_returnValue; }
+
+ virtual const AtomicString& interfaceName() const OVERRIDE { return EventNames::BeforeUnloadEvent; }
+
+private:
+ BeforeUnloadEvent();
+
+ String m_returnValue;
+};
+
+DEFINE_EVENT_TYPE_CASTS(BeforeUnloadEvent);
+
+} // namespace WebCore
+
+#endif // BeforeUnloadEvent_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/BeforeUnloadEvent.idl b/chromium/third_party/WebKit/Source/core/events/BeforeUnloadEvent.idl
index 618d5580939..618d5580939 100644
--- a/chromium/third_party/WebKit/Source/core/dom/BeforeUnloadEvent.idl
+++ b/chromium/third_party/WebKit/Source/core/events/BeforeUnloadEvent.idl
diff --git a/chromium/third_party/WebKit/Source/core/events/ClipboardEvent.cpp b/chromium/third_party/WebKit/Source/core/events/ClipboardEvent.cpp
new file mode 100644
index 00000000000..a8fa4f96699
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/ClipboardEvent.cpp
@@ -0,0 +1,55 @@
+/*
+ * Copyright (C) 2001 Peter Kelly (pmk@post.com)
+ * Copyright (C) 2001 Tobias Anton (anton@stud.fbi.fh-darmstadt.de)
+ * Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
+ * Copyright (C) 2003, 2005, 2006, 2008 Apple Inc. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#include "config.h"
+#include "core/events/ClipboardEvent.h"
+
+#include "core/dom/Clipboard.h"
+#include "core/events/ThreadLocalEventNames.h"
+
+namespace WebCore {
+
+ClipboardEvent::ClipboardEvent()
+{
+}
+
+ClipboardEvent::ClipboardEvent(const AtomicString& eventType, bool canBubble, bool cancelable, PassRefPtr<Clipboard> clipboard)
+ : Event(eventType, canBubble, cancelable), m_clipboard(clipboard)
+{
+}
+
+ClipboardEvent::~ClipboardEvent()
+{
+}
+
+const AtomicString& ClipboardEvent::interfaceName() const
+{
+ // Notice that there is no ClipboardEvent.idl.
+ return EventNames::Event;
+}
+
+bool ClipboardEvent::isClipboardEvent() const
+{
+ return true;
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/events/ClipboardEvent.h b/chromium/third_party/WebKit/Source/core/events/ClipboardEvent.h
new file mode 100644
index 00000000000..671315b39f5
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/ClipboardEvent.h
@@ -0,0 +1,60 @@
+/*
+ * Copyright (C) 2001 Peter Kelly (pmk@post.com)
+ * Copyright (C) 2001 Tobias Anton (anton@stud.fbi.fh-darmstadt.de)
+ * Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
+ * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ */
+
+#ifndef ClipboardEvent_h
+#define ClipboardEvent_h
+
+#include "core/events/Event.h"
+
+namespace WebCore {
+
+ class Clipboard;
+
+ class ClipboardEvent : public Event {
+ public:
+ virtual ~ClipboardEvent();
+
+ static PassRefPtr<ClipboardEvent> create()
+ {
+ return adoptRef(new ClipboardEvent);
+ }
+ static PassRefPtr<ClipboardEvent> create(const AtomicString& type, bool canBubbleArg, bool cancelableArg, PassRefPtr<Clipboard> clipboardArg)
+ {
+ return adoptRef(new ClipboardEvent(type, canBubbleArg, cancelableArg, clipboardArg));
+ }
+
+ Clipboard* clipboard() const { return m_clipboard.get(); }
+
+ private:
+ ClipboardEvent();
+ ClipboardEvent(const AtomicString& type, bool canBubbleArg, bool cancelableArg, PassRefPtr<Clipboard>);
+
+ virtual const AtomicString& interfaceName() const OVERRIDE;
+ virtual bool isClipboardEvent() const OVERRIDE;
+
+ RefPtr<Clipboard> m_clipboard;
+ };
+
+} // namespace WebCore
+
+#endif // ClipboardEvent_h
diff --git a/chromium/third_party/WebKit/Source/core/events/CompositionEvent.cpp b/chromium/third_party/WebKit/Source/core/events/CompositionEvent.cpp
new file mode 100644
index 00000000000..f4ecff6596f
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/CompositionEvent.cpp
@@ -0,0 +1,76 @@
+/*
+ * Copyright (C) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "config.h"
+#include "core/events/CompositionEvent.h"
+
+#include "core/events/ThreadLocalEventNames.h"
+
+namespace WebCore {
+
+CompositionEventInit::CompositionEventInit()
+{
+}
+
+CompositionEvent::CompositionEvent()
+{
+ ScriptWrappable::init(this);
+}
+
+CompositionEvent::CompositionEvent(const AtomicString& type, PassRefPtr<AbstractView> view, const String& data)
+ : UIEvent(type, true, true, view, 0)
+ , m_data(data)
+{
+ ScriptWrappable::init(this);
+}
+
+CompositionEvent::CompositionEvent(const AtomicString& type, const CompositionEventInit& initializer)
+ : UIEvent(type, initializer)
+ , m_data(initializer.data)
+{
+ ScriptWrappable::init(this);
+}
+
+CompositionEvent::~CompositionEvent()
+{
+}
+
+void CompositionEvent::initCompositionEvent(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<AbstractView> view, const String& data)
+{
+ if (dispatched())
+ return;
+
+ initUIEvent(type, canBubble, cancelable, view, 0);
+
+ m_data = data;
+}
+
+const AtomicString& CompositionEvent::interfaceName() const
+{
+ return EventNames::CompositionEvent;
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/events/CompositionEvent.h b/chromium/third_party/WebKit/Source/core/events/CompositionEvent.h
new file mode 100644
index 00000000000..c06da88c196
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/CompositionEvent.h
@@ -0,0 +1,75 @@
+/*
+ * Copyright (C) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#ifndef CompositionEvent_h
+#define CompositionEvent_h
+
+#include "core/events/UIEvent.h"
+
+namespace WebCore {
+
+struct CompositionEventInit : UIEventInit {
+ CompositionEventInit();
+
+ String data;
+};
+
+class CompositionEvent : public UIEvent {
+public:
+ static PassRefPtr<CompositionEvent> create()
+ {
+ return adoptRef(new CompositionEvent);
+ }
+
+ static PassRefPtr<CompositionEvent> create(const AtomicString& type, PassRefPtr<AbstractView> view, const String& data)
+ {
+ return adoptRef(new CompositionEvent(type, view, data));
+ }
+
+ static PassRefPtr<CompositionEvent> create(const AtomicString& type, const CompositionEventInit& initializer)
+ {
+ return adoptRef(new CompositionEvent(type, initializer));
+ }
+
+ virtual ~CompositionEvent();
+
+ void initCompositionEvent(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<AbstractView>, const String& data);
+
+ String data() const { return m_data; }
+
+ virtual const AtomicString& interfaceName() const;
+
+private:
+ CompositionEvent();
+ CompositionEvent(const AtomicString& type, PassRefPtr<AbstractView>, const String&);
+ CompositionEvent(const AtomicString& type, const CompositionEventInit&);
+
+ String m_data;
+};
+
+} // namespace WebCore
+
+#endif // CompositionEvent_h
diff --git a/chromium/third_party/WebKit/Source/core/events/CompositionEvent.idl b/chromium/third_party/WebKit/Source/core/events/CompositionEvent.idl
new file mode 100644
index 00000000000..4e14a952281
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/CompositionEvent.idl
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+[
+ EventConstructor,
+] interface CompositionEvent : UIEvent {
+
+ [InitializedByEventConstructor] readonly attribute DOMString data;
+
+ void initCompositionEvent([Default=Undefined] optional DOMString typeArg,
+ [Default=Undefined] optional boolean canBubbleArg,
+ [Default=Undefined] optional boolean cancelableArg,
+ [Default=Undefined] optional Window viewArg,
+ [Default=Undefined] optional DOMString dataArg);
+
+};
+
diff --git a/chromium/third_party/WebKit/Source/core/events/CustomEvent.cpp b/chromium/third_party/WebKit/Source/core/events/CustomEvent.cpp
new file mode 100644
index 00000000000..ea3ac91b9e3
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/CustomEvent.cpp
@@ -0,0 +1,64 @@
+/*
+ * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/events/CustomEvent.h"
+
+#include "bindings/v8/SerializedScriptValue.h"
+#include "core/events/ThreadLocalEventNames.h"
+
+namespace WebCore {
+
+CustomEvent::CustomEvent()
+{
+ ScriptWrappable::init(this);
+}
+
+CustomEvent::CustomEvent(const AtomicString& type, const CustomEventInit& initializer)
+ : Event(type, initializer)
+{
+ ScriptWrappable::init(this);
+}
+
+CustomEvent::~CustomEvent()
+{
+}
+
+void CustomEvent::initCustomEvent(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<SerializedScriptValue> serializedDetail)
+{
+ if (dispatched())
+ return;
+
+ initEvent(type, canBubble, cancelable);
+
+ m_serializedDetail = serializedDetail;
+}
+
+const AtomicString& CustomEvent::interfaceName() const
+{
+ return EventNames::CustomEvent;
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/events/CustomEvent.h b/chromium/third_party/WebKit/Source/core/events/CustomEvent.h
new file mode 100644
index 00000000000..9be0e119aa7
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/CustomEvent.h
@@ -0,0 +1,72 @@
+/*
+ * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef CustomEvent_h
+#define CustomEvent_h
+
+#include "core/events/Event.h"
+
+namespace WebCore {
+
+class SerializedScriptValue;
+
+typedef EventInit CustomEventInit;
+
+class CustomEvent : public Event {
+public:
+ virtual ~CustomEvent();
+
+ static PassRefPtr<CustomEvent> create()
+ {
+ return adoptRef(new CustomEvent);
+ }
+
+ static PassRefPtr<CustomEvent> create(const AtomicString& type, const CustomEventInit& initializer)
+ {
+ return adoptRef(new CustomEvent(type, initializer));
+ }
+
+ void initCustomEvent(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<SerializedScriptValue>);
+
+ virtual const AtomicString& interfaceName() const;
+
+ SerializedScriptValue* serializedDetail() { return m_serializedDetail.get(); }
+
+ void setSerializedDetail(PassRefPtr<SerializedScriptValue> detail)
+ {
+ ASSERT(!m_serializedDetail);
+ m_serializedDetail = detail;
+ }
+
+private:
+ CustomEvent();
+ CustomEvent(const AtomicString& type, const CustomEventInit& initializer);
+
+ RefPtr<SerializedScriptValue> m_serializedDetail;
+};
+
+} // namespace WebCore
+
+#endif // CustomEvent_h
diff --git a/chromium/third_party/WebKit/Source/core/events/CustomEvent.idl b/chromium/third_party/WebKit/Source/core/events/CustomEvent.idl
new file mode 100644
index 00000000000..4ad348b3126
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/CustomEvent.idl
@@ -0,0 +1,35 @@
+/*
+ * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+[
+ EventConstructor,
+] interface CustomEvent : Event {
+ [Custom=Getter, InitializedByEventConstructor] readonly attribute any detail;
+
+ [Custom] void initCustomEvent([Default=Undefined] optional DOMString typeArg,
+ [Default=Undefined] optional boolean canBubbleArg,
+ [Default=Undefined] optional boolean cancelableArg,
+ [Default=Undefined] optional any detailArg);
+};
diff --git a/chromium/third_party/WebKit/Source/core/events/DOMWindowEventQueue.cpp b/chromium/third_party/WebKit/Source/core/events/DOMWindowEventQueue.cpp
new file mode 100644
index 00000000000..e18530c72a0
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/DOMWindowEventQueue.cpp
@@ -0,0 +1,130 @@
+/*
+ * Copyright (C) 2010 Google Inc. All Rights Reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "config.h"
+#include "core/events/DOMWindowEventQueue.h"
+
+#include "core/dom/Document.h"
+#include "core/events/Event.h"
+#include "core/events/ThreadLocalEventNames.h"
+#include "core/frame/DOMWindow.h"
+#include "core/frame/SuspendableTimer.h"
+
+namespace WebCore {
+
+class DOMWindowEventQueueTimer : public SuspendableTimer {
+ WTF_MAKE_NONCOPYABLE(DOMWindowEventQueueTimer);
+public:
+ DOMWindowEventQueueTimer(DOMWindowEventQueue* eventQueue, ExecutionContext* context)
+ : SuspendableTimer(context)
+ , m_eventQueue(eventQueue) { }
+
+private:
+ virtual void fired() { m_eventQueue->pendingEventTimerFired(); }
+ DOMWindowEventQueue* m_eventQueue;
+};
+
+PassRefPtr<DOMWindowEventQueue> DOMWindowEventQueue::create(ExecutionContext* context)
+{
+ return adoptRef(new DOMWindowEventQueue(context));
+}
+
+DOMWindowEventQueue::DOMWindowEventQueue(ExecutionContext* context)
+ : m_pendingEventTimer(adoptPtr(new DOMWindowEventQueueTimer(this, context)))
+ , m_isClosed(false)
+{
+ m_pendingEventTimer->suspendIfNeeded();
+}
+
+DOMWindowEventQueue::~DOMWindowEventQueue()
+{
+}
+
+bool DOMWindowEventQueue::enqueueEvent(PassRefPtr<Event> event)
+{
+ if (m_isClosed)
+ return false;
+
+ ASSERT(event->target());
+ bool wasAdded = m_queuedEvents.add(event).isNewEntry;
+ ASSERT_UNUSED(wasAdded, wasAdded); // It should not have already been in the list.
+
+ if (!m_pendingEventTimer->isActive())
+ m_pendingEventTimer->startOneShot(0);
+
+ return true;
+}
+
+bool DOMWindowEventQueue::cancelEvent(Event* event)
+{
+ ListHashSet<RefPtr<Event>, 16>::iterator it = m_queuedEvents.find(event);
+ bool found = it != m_queuedEvents.end();
+ if (found)
+ m_queuedEvents.remove(it);
+ if (m_queuedEvents.isEmpty())
+ m_pendingEventTimer->stop();
+ return found;
+}
+
+void DOMWindowEventQueue::close()
+{
+ m_isClosed = true;
+ m_pendingEventTimer->stop();
+ m_queuedEvents.clear();
+}
+
+void DOMWindowEventQueue::pendingEventTimerFired()
+{
+ ASSERT(!m_pendingEventTimer->isActive());
+ ASSERT(!m_queuedEvents.isEmpty());
+
+ // Insert a marker for where we should stop.
+ ASSERT(!m_queuedEvents.contains(0));
+ bool wasAdded = m_queuedEvents.add(0).isNewEntry;
+ ASSERT_UNUSED(wasAdded, wasAdded); // It should not have already been in the list.
+
+ RefPtr<DOMWindowEventQueue> protector(this);
+
+ while (!m_queuedEvents.isEmpty()) {
+ ListHashSet<RefPtr<Event>, 16>::iterator iter = m_queuedEvents.begin();
+ RefPtr<Event> event = *iter;
+ m_queuedEvents.remove(iter);
+ if (!event)
+ break;
+ dispatchEvent(event.get());
+ }
+}
+
+void DOMWindowEventQueue::dispatchEvent(PassRefPtr<Event> event)
+{
+ EventTarget* eventTarget = event->target();
+ if (eventTarget->toDOMWindow())
+ eventTarget->toDOMWindow()->dispatchEvent(event, 0);
+ else
+ eventTarget->dispatchEvent(event);
+}
+
+}
diff --git a/chromium/third_party/WebKit/Source/core/events/DOMWindowEventQueue.h b/chromium/third_party/WebKit/Source/core/events/DOMWindowEventQueue.h
new file mode 100644
index 00000000000..f19e22b5d51
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/DOMWindowEventQueue.h
@@ -0,0 +1,69 @@
+/*
+ * Copyright (C) 2010 Google Inc. All Rights Reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#ifndef DOMWindowEventQueue_h
+#define DOMWindowEventQueue_h
+
+#include "core/events/EventQueue.h"
+#include "wtf/Forward.h"
+#include "wtf/HashSet.h"
+#include "wtf/ListHashSet.h"
+#include "wtf/OwnPtr.h"
+#include "wtf/RefCounted.h"
+
+namespace WebCore {
+
+class Event;
+class DOMWindowEventQueueTimer;
+class Node;
+class ExecutionContext;
+
+class DOMWindowEventQueue : public RefCounted<DOMWindowEventQueue>, public EventQueue {
+public:
+ static PassRefPtr<DOMWindowEventQueue> create(ExecutionContext*);
+ virtual ~DOMWindowEventQueue();
+
+ // EventQueue
+ virtual bool enqueueEvent(PassRefPtr<Event>) OVERRIDE;
+ virtual bool cancelEvent(Event*) OVERRIDE;
+ virtual void close() OVERRIDE;
+
+private:
+ explicit DOMWindowEventQueue(ExecutionContext*);
+
+ void pendingEventTimerFired();
+ void dispatchEvent(PassRefPtr<Event>);
+
+ OwnPtr<DOMWindowEventQueueTimer> m_pendingEventTimer;
+ ListHashSet<RefPtr<Event>, 16> m_queuedEvents;
+ bool m_isClosed;
+
+ friend class DOMWindowEventQueueTimer;
+};
+
+}
+
+#endif // DOMWindowEventQueue_h
diff --git a/chromium/third_party/WebKit/Source/core/events/ErrorEvent.cpp b/chromium/third_party/WebKit/Source/core/events/ErrorEvent.cpp
new file mode 100644
index 00000000000..0bd32f4e9e2
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/ErrorEvent.cpp
@@ -0,0 +1,88 @@
+/*
+ * Copyright (C) 2009 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/events/ErrorEvent.h"
+
+#include "core/events/ThreadLocalEventNames.h"
+
+namespace WebCore {
+
+ErrorEventInit::ErrorEventInit()
+ : message()
+ , filename()
+ , lineno(0)
+ , colno(0)
+{
+}
+
+ErrorEvent::ErrorEvent()
+{
+ ScriptWrappable::init(this);
+}
+
+ErrorEvent::ErrorEvent(const AtomicString& type, const ErrorEventInit& initializer)
+ : Event(type, initializer)
+ , m_sanitizedMessage(initializer.message)
+ , m_fileName(initializer.filename)
+ , m_lineNumber(initializer.lineno)
+ , m_columnNumber(initializer.colno)
+ , m_world(DOMWrapperWorld::current())
+{
+ ScriptWrappable::init(this);
+}
+
+ErrorEvent::ErrorEvent(const String& message, const String& fileName, unsigned lineNumber, unsigned columnNumber, PassRefPtr<DOMWrapperWorld> world)
+ : Event(EventTypeNames::error, false, true)
+ , m_sanitizedMessage(message)
+ , m_fileName(fileName)
+ , m_lineNumber(lineNumber)
+ , m_columnNumber(columnNumber)
+ , m_world(world)
+{
+ ScriptWrappable::init(this);
+}
+
+void ErrorEvent::setUnsanitizedMessage(const String& message)
+{
+ ASSERT(m_unsanitizedMessage.isEmpty());
+ m_unsanitizedMessage = message;
+}
+
+ErrorEvent::~ErrorEvent()
+{
+}
+
+const AtomicString& ErrorEvent::interfaceName() const
+{
+ return EventNames::ErrorEvent;
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/events/ErrorEvent.h b/chromium/third_party/WebKit/Source/core/events/ErrorEvent.h
new file mode 100644
index 00000000000..e0643e4895f
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/ErrorEvent.h
@@ -0,0 +1,101 @@
+/*
+ * Copyright (C) 2009 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef ErrorEvent_h
+#define ErrorEvent_h
+
+#include "bindings/v8/DOMWrapperWorld.h"
+#include "core/events/Event.h"
+#include "wtf/RefPtr.h"
+#include "wtf/text/WTFString.h"
+
+namespace WebCore {
+
+struct ErrorEventInit : public EventInit {
+ ErrorEventInit();
+
+ String message;
+ String filename;
+ unsigned lineno;
+ unsigned colno;
+};
+
+class ErrorEvent : public Event {
+public:
+ static PassRefPtr<ErrorEvent> create()
+ {
+ return adoptRef(new ErrorEvent);
+ }
+ static PassRefPtr<ErrorEvent> create(const String& message, const String& fileName, unsigned lineNumber, unsigned columnNumber, PassRefPtr<DOMWrapperWorld> world)
+ {
+ return adoptRef(new ErrorEvent(message, fileName, lineNumber, columnNumber, world));
+ }
+ static PassRefPtr<ErrorEvent> create(const AtomicString& type, const ErrorEventInit& initializer)
+ {
+ return adoptRef(new ErrorEvent(type, initializer));
+ }
+ static PassRefPtr<ErrorEvent> createSanitizedError(PassRefPtr<DOMWrapperWorld> world)
+ {
+ return adoptRef(new ErrorEvent("Script error.", String(), 0, 0, world));
+ }
+ virtual ~ErrorEvent();
+
+ // As 'message' is exposed to JavaScript, never return unsanitizedMessage.
+ const String& message() const { return m_sanitizedMessage; }
+ const String& filename() const { return m_fileName; }
+ unsigned lineno() const { return m_lineNumber; }
+ unsigned colno() const { return m_columnNumber; }
+
+ // 'messageForConsole' is not exposed to JavaScript, and prefers 'm_unsanitizedMessage'.
+ const String& messageForConsole() const { return !m_unsanitizedMessage.isEmpty() ? m_unsanitizedMessage : m_sanitizedMessage; }
+
+ virtual const AtomicString& interfaceName() const;
+
+ PassRefPtr<DOMWrapperWorld> world() const { return m_world; }
+
+ void setUnsanitizedMessage(const String&);
+
+private:
+ ErrorEvent();
+ ErrorEvent(const String& message, const String& fileName, unsigned lineNumber, unsigned columnNumber, PassRefPtr<DOMWrapperWorld>);
+ ErrorEvent(const AtomicString&, const ErrorEventInit&);
+
+ String m_unsanitizedMessage;
+ String m_sanitizedMessage;
+ String m_fileName;
+ unsigned m_lineNumber;
+ unsigned m_columnNumber;
+
+ RefPtr<DOMWrapperWorld> m_world;
+};
+
+} // namespace WebCore
+
+#endif // ErrorEvent_h
diff --git a/chromium/third_party/WebKit/Source/core/events/ErrorEvent.idl b/chromium/third_party/WebKit/Source/core/events/ErrorEvent.idl
new file mode 100644
index 00000000000..ad122859002
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/ErrorEvent.idl
@@ -0,0 +1,40 @@
+/*
+ * Copyright (C) 2009 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+[
+ EventConstructor,
+] interface ErrorEvent : Event {
+ [InitializedByEventConstructor] readonly attribute DOMString message;
+ [InitializedByEventConstructor] readonly attribute DOMString filename;
+ [InitializedByEventConstructor] readonly attribute unsigned long lineno;
+ [InitializedByEventConstructor] readonly attribute unsigned long colno;
+ [Custom=Getter, InitializedByEventConstructor] readonly attribute any error;
+};
+
diff --git a/chromium/third_party/WebKit/Source/core/events/Event.cpp b/chromium/third_party/WebKit/Source/core/events/Event.cpp
new file mode 100644
index 00000000000..4ec60126722
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/Event.cpp
@@ -0,0 +1,211 @@
+/*
+ * Copyright (C) 2001 Peter Kelly (pmk@post.com)
+ * Copyright (C) 2001 Tobias Anton (anton@stud.fbi.fh-darmstadt.de)
+ * Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
+ * Copyright (C) 2003, 2005, 2006, 2008 Apple Inc. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#include "config.h"
+#include "core/events/Event.h"
+
+#include "core/dom/StaticNodeList.h"
+#include "core/events/EventTarget.h"
+#include "core/events/ThreadLocalEventNames.h"
+#include "wtf/CurrentTime.h"
+
+namespace WebCore {
+
+EventInit::EventInit()
+ : bubbles(false)
+ , cancelable(false)
+{
+}
+
+
+Event::Event()
+ : m_canBubble(false)
+ , m_cancelable(false)
+ , m_propagationStopped(false)
+ , m_immediatePropagationStopped(false)
+ , m_defaultPrevented(false)
+ , m_defaultHandled(false)
+ , m_cancelBubble(false)
+ , m_eventPhase(0)
+ , m_currentTarget(0)
+ , m_createTime(convertSecondsToDOMTimeStamp(currentTime()))
+ , m_eventPath(this)
+{
+ ScriptWrappable::init(this);
+}
+
+Event::Event(const AtomicString& eventType, bool canBubbleArg, bool cancelableArg)
+ : m_type(eventType)
+ , m_canBubble(canBubbleArg)
+ , m_cancelable(cancelableArg)
+ , m_propagationStopped(false)
+ , m_immediatePropagationStopped(false)
+ , m_defaultPrevented(false)
+ , m_defaultHandled(false)
+ , m_cancelBubble(false)
+ , m_eventPhase(0)
+ , m_currentTarget(0)
+ , m_createTime(convertSecondsToDOMTimeStamp(currentTime()))
+ , m_eventPath(this)
+{
+ ScriptWrappable::init(this);
+}
+
+Event::Event(const AtomicString& eventType, const EventInit& initializer)
+ : m_type(eventType)
+ , m_canBubble(initializer.bubbles)
+ , m_cancelable(initializer.cancelable)
+ , m_propagationStopped(false)
+ , m_immediatePropagationStopped(false)
+ , m_defaultPrevented(false)
+ , m_defaultHandled(false)
+ , m_cancelBubble(false)
+ , m_eventPhase(0)
+ , m_currentTarget(0)
+ , m_createTime(convertSecondsToDOMTimeStamp(currentTime()))
+ , m_eventPath(this)
+{
+ ScriptWrappable::init(this);
+}
+
+Event::~Event()
+{
+}
+
+void Event::initEvent(const AtomicString& eventTypeArg, bool canBubbleArg, bool cancelableArg)
+{
+ if (dispatched())
+ return;
+
+ m_propagationStopped = false;
+ m_immediatePropagationStopped = false;
+ m_defaultPrevented = false;
+
+ m_type = eventTypeArg;
+ m_canBubble = canBubbleArg;
+ m_cancelable = cancelableArg;
+}
+
+const AtomicString& Event::interfaceName() const
+{
+ return EventNames::Event;
+}
+
+bool Event::hasInterface(const AtomicString& name) const
+{
+ return interfaceName() == name;
+}
+
+bool Event::isUIEvent() const
+{
+ return false;
+}
+
+bool Event::isMouseEvent() const
+{
+ return false;
+}
+
+bool Event::isFocusEvent() const
+{
+ return false;
+}
+
+bool Event::isKeyboardEvent() const
+{
+ return false;
+}
+
+bool Event::isTouchEvent() const
+{
+ return false;
+}
+
+bool Event::isGestureEvent() const
+{
+ return false;
+}
+
+bool Event::isWheelEvent() const
+{
+ return false;
+}
+
+bool Event::isDragEvent() const
+{
+ return false;
+}
+
+bool Event::isClipboardEvent() const
+{
+ return false;
+}
+
+bool Event::isBeforeTextInsertedEvent() const
+{
+ return false;
+}
+
+bool Event::isBeforeUnloadEvent() const
+{
+ return false;
+}
+
+void Event::setTarget(PassRefPtr<EventTarget> target)
+{
+ if (m_target == target)
+ return;
+
+ m_target = target;
+ if (m_target)
+ receivedTarget();
+}
+
+void Event::receivedTarget()
+{
+}
+
+void Event::setUnderlyingEvent(PassRefPtr<Event> ue)
+{
+ // Prohibit creation of a cycle -- just do nothing in that case.
+ for (Event* e = ue.get(); e; e = e->underlyingEvent())
+ if (e == this)
+ return;
+ m_underlyingEvent = ue;
+}
+
+PassRefPtr<NodeList> Event::path() const
+{
+ if (!m_currentTarget || !m_currentTarget->toNode())
+ return StaticNodeList::createEmpty();
+ Node* node = m_currentTarget->toNode();
+ size_t eventPathSize = m_eventPath.size();
+ for (size_t i = 0; i < eventPathSize; ++i) {
+ if (node == m_eventPath[i].node()) {
+ ASSERT(m_eventPath[i].eventPath());
+ return m_eventPath[i].eventPath();
+ }
+ }
+ return StaticNodeList::createEmpty();
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/events/Event.h b/chromium/third_party/WebKit/Source/core/events/Event.h
new file mode 100644
index 00000000000..b28f7f113d1
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/Event.h
@@ -0,0 +1,217 @@
+/*
+ * Copyright (C) 2001 Peter Kelly (pmk@post.com)
+ * Copyright (C) 2001 Tobias Anton (anton@stud.fbi.fh-darmstadt.de)
+ * Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
+ * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ */
+
+#ifndef Event_h
+#define Event_h
+
+#include "bindings/v8/ScriptWrappable.h"
+#include "core/dom/DOMTimeStamp.h"
+#include "core/events/EventContext.h"
+#include "core/events/EventPath.h"
+#include "wtf/RefCounted.h"
+#include "wtf/text/AtomicString.h"
+
+namespace WebCore {
+
+class Clipboard;
+class EventTarget;
+class EventDispatcher;
+class HTMLIFrameElement;
+
+struct EventInit {
+ EventInit();
+
+ bool bubbles;
+ bool cancelable;
+};
+
+class Event : public ScriptWrappable, public RefCounted<Event> {
+public:
+ enum PhaseType {
+ NONE = 0,
+ CAPTURING_PHASE = 1,
+ AT_TARGET = 2,
+ BUBBLING_PHASE = 3
+ };
+
+ enum EventType {
+ MOUSEDOWN = 1,
+ MOUSEUP = 2,
+ MOUSEOVER = 4,
+ MOUSEOUT = 8,
+ MOUSEMOVE = 16,
+ MOUSEDRAG = 32,
+ CLICK = 64,
+ DBLCLICK = 128,
+ KEYDOWN = 256,
+ KEYUP = 512,
+ KEYPRESS = 1024,
+ DRAGDROP = 2048,
+ FOCUS = 4096,
+ BLUR = 8192,
+ SELECT = 16384,
+ CHANGE = 32768
+ };
+
+ static PassRefPtr<Event> create()
+ {
+ return adoptRef(new Event);
+ }
+
+ // A factory for a simple event. The event doesn't bubble, and isn't
+ // cancelable.
+ // http://www.whatwg.org/specs/web-apps/current-work/multipage/webappapis.html#fire-a-simple-event
+ static PassRefPtr<Event> create(const AtomicString& type)
+ {
+ return adoptRef(new Event(type, false, false));
+ }
+ static PassRefPtr<Event> createCancelable(const AtomicString& type)
+ {
+ return adoptRef(new Event(type, false, true));
+ }
+ static PassRefPtr<Event> createBubble(const AtomicString& type)
+ {
+ return adoptRef(new Event(type, true, false));
+ }
+ static PassRefPtr<Event> createCancelableBubble(const AtomicString& type)
+ {
+ return adoptRef(new Event(type, true, true));
+ }
+
+ static PassRefPtr<Event> create(const AtomicString& type, const EventInit& initializer)
+ {
+ return adoptRef(new Event(type, initializer));
+ }
+
+ virtual ~Event();
+
+ void initEvent(const AtomicString& type, bool canBubble, bool cancelable);
+
+ const AtomicString& type() const { return m_type; }
+ void setType(const AtomicString& type) { m_type = type; }
+
+ EventTarget* target() const { return m_target.get(); }
+ void setTarget(PassRefPtr<EventTarget>);
+
+ EventTarget* currentTarget() const { return m_currentTarget; }
+ void setCurrentTarget(EventTarget* currentTarget) { m_currentTarget = currentTarget; }
+
+ unsigned short eventPhase() const { return m_eventPhase; }
+ void setEventPhase(unsigned short eventPhase) { m_eventPhase = eventPhase; }
+
+ bool bubbles() const { return m_canBubble; }
+ bool cancelable() const { return m_cancelable; }
+ DOMTimeStamp timeStamp() const { return m_createTime; }
+
+ void stopPropagation() { m_propagationStopped = true; }
+ void stopImmediatePropagation() { m_immediatePropagationStopped = true; }
+
+ // IE Extensions
+ EventTarget* srcElement() const { return target(); } // MSIE extension - "the object that fired the event"
+
+ bool legacyReturnValue() const { return !defaultPrevented(); }
+ void setLegacyReturnValue(bool returnValue) { setDefaultPrevented(!returnValue); }
+
+ Clipboard* clipboardData() const { return isClipboardEvent() ? clipboard() : 0; }
+
+ virtual const AtomicString& interfaceName() const;
+ bool hasInterface(const AtomicString&) const;
+
+ // These events are general classes of events.
+ virtual bool isUIEvent() const;
+ virtual bool isMouseEvent() const;
+ virtual bool isFocusEvent() const;
+ virtual bool isKeyboardEvent() const;
+ virtual bool isTouchEvent() const;
+ virtual bool isGestureEvent() const;
+ virtual bool isWheelEvent() const;
+
+ // Drag events are a subset of mouse events.
+ virtual bool isDragEvent() const;
+
+ // These events lack a DOM interface.
+ virtual bool isClipboardEvent() const;
+ virtual bool isBeforeTextInsertedEvent() const;
+
+ virtual bool isBeforeUnloadEvent() const;
+
+ bool propagationStopped() const { return m_propagationStopped || m_immediatePropagationStopped; }
+ bool immediatePropagationStopped() const { return m_immediatePropagationStopped; }
+
+ bool defaultPrevented() const { return m_defaultPrevented; }
+ void preventDefault()
+ {
+ if (m_cancelable)
+ m_defaultPrevented = true;
+ }
+ void setDefaultPrevented(bool defaultPrevented) { m_defaultPrevented = defaultPrevented; }
+
+ bool defaultHandled() const { return m_defaultHandled; }
+ void setDefaultHandled() { m_defaultHandled = true; }
+
+ bool cancelBubble() const { return m_cancelBubble; }
+ void setCancelBubble(bool cancel) { m_cancelBubble = cancel; }
+
+ Event* underlyingEvent() const { return m_underlyingEvent.get(); }
+ void setUnderlyingEvent(PassRefPtr<Event>);
+
+ EventPath& eventPath() { return m_eventPath; }
+ PassRefPtr<NodeList> path() const;
+
+ virtual Clipboard* clipboard() const { return 0; }
+
+ bool isBeingDispatched() const { return eventPhase(); }
+
+protected:
+ Event();
+ Event(const AtomicString& type, bool canBubble, bool cancelable);
+ Event(const AtomicString& type, const EventInit&);
+
+ virtual void receivedTarget();
+ bool dispatched() const { return m_target; }
+
+private:
+ AtomicString m_type;
+ bool m_canBubble;
+ bool m_cancelable;
+
+ bool m_propagationStopped;
+ bool m_immediatePropagationStopped;
+ bool m_defaultPrevented;
+ bool m_defaultHandled;
+ bool m_cancelBubble;
+
+ unsigned short m_eventPhase;
+ EventTarget* m_currentTarget;
+ RefPtr<EventTarget> m_target;
+ DOMTimeStamp m_createTime;
+ RefPtr<Event> m_underlyingEvent;
+ EventPath m_eventPath;
+};
+
+#define DEFINE_EVENT_TYPE_CASTS(typeName) \
+ DEFINE_TYPE_CASTS(typeName, Event, event, event->is##typeName(), event.is##typeName())
+
+} // namespace WebCore
+
+#endif // Event_h
diff --git a/chromium/third_party/WebKit/Source/core/events/Event.idl b/chromium/third_party/WebKit/Source/core/events/Event.idl
new file mode 100644
index 00000000000..3f8e80b0523
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/Event.idl
@@ -0,0 +1,77 @@
+/*
+ * Copyright (C) 2006, 2007, 2009, 2011 Apple Inc. All rights reserved.
+ * Copyright (C) 2006 Samuel Weinig <sam.weinig@gmail.com>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+// Introduced in DOM Level 2:
+[
+ Custom=Wrap,
+ EventConstructor,
+] interface Event {
+
+ // DOM PhaseType
+ const unsigned short NONE = 0;
+ const unsigned short CAPTURING_PHASE = 1;
+ const unsigned short AT_TARGET = 2;
+ const unsigned short BUBBLING_PHASE = 3;
+
+ // Reverse-engineered from Netscape
+ const unsigned short MOUSEDOWN = 1;
+ const unsigned short MOUSEUP = 2;
+ const unsigned short MOUSEOVER = 4;
+ const unsigned short MOUSEOUT = 8;
+ const unsigned short MOUSEMOVE = 16;
+ const unsigned short MOUSEDRAG = 32;
+ const unsigned short CLICK = 64;
+ const unsigned short DBLCLICK = 128;
+ const unsigned short KEYDOWN = 256;
+ const unsigned short KEYUP = 512;
+ const unsigned short KEYPRESS = 1024;
+ const unsigned short DRAGDROP = 2048;
+ const unsigned short FOCUS = 4096;
+ const unsigned short BLUR = 8192;
+ const unsigned short SELECT = 16384;
+ const unsigned short CHANGE = 32768;
+
+ readonly attribute DOMString type;
+ readonly attribute EventTarget target;
+ readonly attribute EventTarget currentTarget;
+ readonly attribute unsigned short eventPhase;
+ [InitializedByEventConstructor] readonly attribute boolean bubbles;
+ [InitializedByEventConstructor] readonly attribute boolean cancelable;
+ readonly attribute DOMTimeStamp timeStamp;
+
+ void stopPropagation();
+ void preventDefault();
+ void initEvent([Default=Undefined] optional DOMString eventTypeArg,
+ [Default=Undefined] optional boolean canBubbleArg,
+ [Default=Undefined] optional boolean cancelableArg);
+
+ // DOM Level 3 Additions.
+ readonly attribute boolean defaultPrevented;
+ void stopImmediatePropagation();
+
+ // IE Extensions
+ readonly attribute EventTarget srcElement;
+ [ImplementedAs=legacyReturnValue, DeprecateAs=EventReturnValue] attribute boolean returnValue;
+ attribute boolean cancelBubble;
+
+ [RuntimeEnabled=ShadowDOM] readonly attribute NodeList path;
+
+ [Custom=Getter] readonly attribute Clipboard clipboardData;
+};
diff --git a/chromium/third_party/WebKit/Source/core/events/EventAliases.in b/chromium/third_party/WebKit/Source/core/events/EventAliases.in
new file mode 100644
index 00000000000..82b3a744fc9
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/EventAliases.in
@@ -0,0 +1,14 @@
+# Aliases
+AnimationEvent ImplementedAs=WebKitAnimationEvent, RuntimeEnabled=cssAnimationUnprefixedEnabled
+Events ImplementedAs=Event
+HTMLEvents ImplementedAs=Event
+KeyboardEvents ImplementedAs=KeyboardEvent
+MouseEvents ImplementedAs=MouseEvent
+MutationEvents ImplementedAs=MutationEvent
+OrientationEvent ImplementedAs=Event, Conditional=ORIENTATION_EVENTS
+SVGEvents ImplementedAs=Event
+SVGZoomEvents ImplementedAs=SVGZoomEvent
+UIEvents ImplementedAs=UIEvent
+WebKitTransitionEvent ImplementedAs=TransitionEvent
+
+core/events/TouchEvent RuntimeEnabled=touchEnabled
diff --git a/chromium/third_party/WebKit/Source/core/events/EventContext.cpp b/chromium/third_party/WebKit/Source/core/events/EventContext.cpp
new file mode 100644
index 00000000000..5fa4d5e42a4
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/EventContext.cpp
@@ -0,0 +1,100 @@
+/*
+ * Copyright (C) 2010 Google Inc. All Rights Reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "config.h"
+#include "core/events/EventContext.h"
+
+#include "core/events/Event.h"
+#include "core/events/FocusEvent.h"
+#include "core/events/MouseEvent.h"
+#include "core/events/TouchEvent.h"
+#include "core/dom/TouchList.h"
+
+namespace WebCore {
+
+EventContext::EventContext(PassRefPtr<Node> node, PassRefPtr<EventTarget> currentTarget)
+ : m_node(node)
+ , m_currentTarget(currentTarget)
+{
+ ASSERT(m_node);
+}
+
+EventContext::~EventContext()
+{
+}
+
+void EventContext::adoptEventPath(Vector<RefPtr<Node> >& nodes)
+{
+ m_eventPath = StaticNodeList::adopt(nodes);
+}
+
+void EventContext::handleLocalEvents(Event* event) const
+{
+ if (m_touchEventContext) {
+ m_touchEventContext->handleLocalEvents(event);
+ } else if (m_relatedTarget && event->isMouseEvent()) {
+ toMouseEvent(event)->setRelatedTarget(m_relatedTarget.get());
+ } else if (m_relatedTarget && event->isFocusEvent()) {
+ toFocusEvent(event)->setRelatedTarget(m_relatedTarget.get());
+ }
+ event->setTarget(m_target);
+ event->setCurrentTarget(m_currentTarget.get());
+ m_node->handleLocalEvents(event);
+}
+
+TouchEventContext* EventContext::ensureTouchEventContext()
+{
+ if (!m_touchEventContext)
+ m_touchEventContext = TouchEventContext::create();
+ return m_touchEventContext.get();
+}
+
+PassRefPtr<TouchEventContext> TouchEventContext::create()
+{
+ return adoptRef(new TouchEventContext);
+}
+
+TouchEventContext::TouchEventContext()
+ : m_touches(TouchList::create())
+ , m_targetTouches(TouchList::create())
+ , m_changedTouches(TouchList::create())
+{
+}
+
+TouchEventContext::~TouchEventContext()
+{
+}
+
+void TouchEventContext::handleLocalEvents(Event* event) const
+{
+ ASSERT(event->isTouchEvent());
+ TouchEvent* touchEvent = toTouchEvent(event);
+ touchEvent->setTouches(m_touches);
+ touchEvent->setTargetTouches(m_targetTouches);
+ touchEvent->setChangedTouches(m_changedTouches);
+}
+
+}
diff --git a/chromium/third_party/WebKit/Source/core/events/EventContext.h b/chromium/third_party/WebKit/Source/core/events/EventContext.h
new file mode 100644
index 00000000000..c51c90d4aaf
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/EventContext.h
@@ -0,0 +1,117 @@
+/*
+ * Copyright (C) 2010 Google Inc. All Rights Reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#ifndef EventContext_h
+#define EventContext_h
+
+#include "core/events/EventTarget.h"
+#include "core/dom/Node.h"
+#include "core/dom/StaticNodeList.h"
+#include "core/dom/TreeScope.h"
+#include "wtf/RefPtr.h"
+
+namespace WebCore {
+
+class Event;
+class TouchList;
+
+class TouchEventContext : public RefCounted<TouchEventContext> {
+public:
+ static PassRefPtr<TouchEventContext> create();
+ ~TouchEventContext();
+ void handleLocalEvents(Event*) const;
+ TouchList* touches() { return m_touches.get(); }
+ TouchList* targetTouches() { return m_targetTouches.get(); }
+ TouchList* changedTouches() { return m_changedTouches.get(); }
+
+private:
+ TouchEventContext();
+
+ RefPtr<TouchList> m_touches;
+ RefPtr<TouchList> m_targetTouches;
+ RefPtr<TouchList> m_changedTouches;
+};
+
+class EventContext {
+public:
+ // FIXME: Use ContainerNode instead of Node.
+ EventContext(PassRefPtr<Node>, PassRefPtr<EventTarget> currentTarget);
+ ~EventContext();
+
+ Node* node() const { return m_node.get(); }
+ EventTarget* currentTarget() const { return m_currentTarget.get(); }
+
+ EventTarget* target() const { return m_target.get(); }
+ void setTarget(PassRefPtr<EventTarget>);
+
+ EventTarget* relatedTarget() const { return m_relatedTarget.get(); }
+ void setRelatedTarget(PassRefPtr<EventTarget>);
+
+ TouchEventContext* touchEventContext() const { return m_touchEventContext.get(); }
+ TouchEventContext* ensureTouchEventContext();
+
+ PassRefPtr<NodeList> eventPath() const { return m_eventPath; }
+ void adoptEventPath(Vector<RefPtr<Node> >&);
+ void setEventPath(PassRefPtr<NodeList> nodeList) { m_eventPath = nodeList; }
+
+ bool currentTargetSameAsTarget() const { return m_currentTarget.get() == m_target.get(); }
+ void handleLocalEvents(Event*) const;
+
+protected:
+#ifndef NDEBUG
+ bool isUnreachableNode(EventTarget*);
+#endif
+ RefPtr<Node> m_node;
+ RefPtr<EventTarget> m_currentTarget;
+ RefPtr<EventTarget> m_target;
+ RefPtr<EventTarget> m_relatedTarget;
+ RefPtr<NodeList> m_eventPath;
+ RefPtr<TouchEventContext> m_touchEventContext;
+};
+
+#ifndef NDEBUG
+inline bool EventContext::isUnreachableNode(EventTarget* target)
+{
+ // FIXME: Checks also for SVG elements.
+ return target && target->toNode() && !target->toNode()->isSVGElement() && !target->toNode()->treeScope().isInclusiveAncestorOf(m_node->treeScope());
+}
+#endif
+
+inline void EventContext::setTarget(PassRefPtr<EventTarget> target)
+{
+ ASSERT(!isUnreachableNode(target.get()));
+ m_target = target;
+}
+
+inline void EventContext::setRelatedTarget(PassRefPtr<EventTarget> relatedTarget)
+{
+ ASSERT(!isUnreachableNode(relatedTarget.get()));
+ m_relatedTarget = relatedTarget;
+}
+
+}
+
+#endif // EventContext_h
diff --git a/chromium/third_party/WebKit/Source/core/events/EventDispatchMediator.cpp b/chromium/third_party/WebKit/Source/core/events/EventDispatchMediator.cpp
new file mode 100644
index 00000000000..032d0b8f9ad
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/EventDispatchMediator.cpp
@@ -0,0 +1,55 @@
+/*
+ * Copyright (C) 2011 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/events/EventDispatchMediator.h"
+
+#include "core/events/Event.h"
+#include "core/events/EventDispatcher.h"
+
+namespace WebCore {
+
+PassRefPtr<EventDispatchMediator> EventDispatchMediator::create(PassRefPtr<Event> event)
+{
+ return adoptRef(new EventDispatchMediator(event));
+}
+
+EventDispatchMediator::EventDispatchMediator(PassRefPtr<Event> event)
+ : m_event(event)
+{
+}
+
+bool EventDispatchMediator::dispatchEvent(EventDispatcher* dispatcher) const
+{
+ ASSERT(m_event.get() == dispatcher->event());
+ return dispatcher->dispatch();
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/dom/EventDispatchMediator.h b/chromium/third_party/WebKit/Source/core/events/EventDispatchMediator.h
index 00ab327689a..00ab327689a 100644
--- a/chromium/third_party/WebKit/Source/core/dom/EventDispatchMediator.h
+++ b/chromium/third_party/WebKit/Source/core/events/EventDispatchMediator.h
diff --git a/chromium/third_party/WebKit/Source/core/events/EventDispatcher.cpp b/chromium/third_party/WebKit/Source/core/events/EventDispatcher.cpp
new file mode 100644
index 00000000000..fa5698ebce9
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/EventDispatcher.cpp
@@ -0,0 +1,226 @@
+/*
+ * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
+ * (C) 1999 Antti Koivisto (koivisto@kde.org)
+ * (C) 2001 Dirk Mueller (mueller@kde.org)
+ * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
+ * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
+ * Copyright (C) 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
+ * Copyright (C) 2011 Google Inc. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#include "config.h"
+#include "core/events/EventDispatcher.h"
+
+#include "core/dom/ContainerNode.h"
+#include "core/events/EventDispatchMediator.h"
+#include "core/events/EventRetargeter.h"
+#include "core/events/MouseEvent.h"
+#include "core/events/ScopedEventQueue.h"
+#include "core/events/WindowEventContext.h"
+#include "core/inspector/InspectorInstrumentation.h"
+#include "core/frame/FrameView.h"
+#include "wtf/RefPtr.h"
+
+namespace WebCore {
+
+static HashSet<Node*>* gNodesDispatchingSimulatedClicks = 0;
+
+bool EventDispatcher::dispatchEvent(Node* node, PassRefPtr<EventDispatchMediator> mediator)
+{
+ ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
+ if (!mediator->event())
+ return true;
+ EventDispatcher dispatcher(node, mediator->event());
+ return mediator->dispatchEvent(&dispatcher);
+}
+
+EventDispatcher::EventDispatcher(Node* node, PassRefPtr<Event> event)
+ : m_node(node)
+ , m_event(event)
+#ifndef NDEBUG
+ , m_eventDispatched(false)
+#endif
+{
+ ASSERT(node);
+ ASSERT(m_event.get());
+ ASSERT(!m_event->type().isNull()); // JavaScript code can create an event with an empty name, but not null.
+ m_view = node->document().view();
+ m_event->eventPath().resetWith(m_node.get());
+}
+
+void EventDispatcher::dispatchScopedEvent(Node* node, PassRefPtr<EventDispatchMediator> mediator)
+{
+ // We need to set the target here because it can go away by the time we actually fire the event.
+ mediator->event()->setTarget(EventPath::eventTargetRespectingTargetRules(node));
+ ScopedEventQueue::instance()->enqueueEventDispatchMediator(mediator);
+}
+
+void EventDispatcher::dispatchSimulatedClick(Node* node, Event* underlyingEvent, SimulatedClickMouseEventOptions mouseEventOptions)
+{
+ if (isDisabledFormControl(node))
+ return;
+
+ if (!gNodesDispatchingSimulatedClicks)
+ gNodesDispatchingSimulatedClicks = new HashSet<Node*>;
+ else if (gNodesDispatchingSimulatedClicks->contains(node))
+ return;
+
+ gNodesDispatchingSimulatedClicks->add(node);
+
+ if (mouseEventOptions == SendMouseOverUpDownEvents)
+ EventDispatcher(node, SimulatedMouseEvent::create(EventTypeNames::mouseover, node->document().domWindow(), underlyingEvent)).dispatch();
+
+ if (mouseEventOptions != SendNoEvents)
+ EventDispatcher(node, SimulatedMouseEvent::create(EventTypeNames::mousedown, node->document().domWindow(), underlyingEvent)).dispatch();
+ node->setActive(true);
+ if (mouseEventOptions != SendNoEvents)
+ EventDispatcher(node, SimulatedMouseEvent::create(EventTypeNames::mouseup, node->document().domWindow(), underlyingEvent)).dispatch();
+ node->setActive(false);
+
+ // always send click
+ EventDispatcher(node, SimulatedMouseEvent::create(EventTypeNames::click, node->document().domWindow(), underlyingEvent)).dispatch();
+
+ gNodesDispatchingSimulatedClicks->remove(node);
+}
+
+bool EventDispatcher::dispatch()
+{
+#ifndef NDEBUG
+ ASSERT(!m_eventDispatched);
+ m_eventDispatched = true;
+#endif
+ ChildNodesLazySnapshot::takeChildNodesLazySnapshot();
+
+ m_event->setTarget(EventPath::eventTargetRespectingTargetRules(m_node.get()));
+ ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
+ ASSERT(m_event->target());
+ WindowEventContext windowEventContext(m_event.get(), m_node.get(), topEventContext());
+ InspectorInstrumentationCookie cookie = InspectorInstrumentation::willDispatchEvent(&m_node->document(), *m_event, windowEventContext.window(), m_node.get(), m_event->eventPath());
+
+ void* preDispatchEventHandlerResult;
+ if (dispatchEventPreProcess(preDispatchEventHandlerResult) == ContinueDispatching)
+ if (dispatchEventAtCapturing(windowEventContext) == ContinueDispatching)
+ if (dispatchEventAtTarget() == ContinueDispatching)
+ dispatchEventAtBubbling(windowEventContext);
+ dispatchEventPostProcess(preDispatchEventHandlerResult);
+
+ // Ensure that after event dispatch, the event's target object is the
+ // outermost shadow DOM boundary.
+ m_event->setTarget(windowEventContext.target());
+ m_event->setCurrentTarget(0);
+ InspectorInstrumentation::didDispatchEvent(cookie);
+
+ return !m_event->defaultPrevented();
+}
+
+inline EventDispatchContinuation EventDispatcher::dispatchEventPreProcess(void*& preDispatchEventHandlerResult)
+{
+ // Give the target node a chance to do some work before DOM event handlers get a crack.
+ preDispatchEventHandlerResult = m_node->preDispatchEventHandler(m_event.get());
+ return (m_event->eventPath().isEmpty() || m_event->propagationStopped()) ? DoneDispatching : ContinueDispatching;
+}
+
+inline EventDispatchContinuation EventDispatcher::dispatchEventAtCapturing(WindowEventContext& windowEventContext)
+{
+ // Trigger capturing event handlers, starting at the top and working our way down.
+ m_event->setEventPhase(Event::CAPTURING_PHASE);
+
+ if (windowEventContext.handleLocalEvents(m_event.get()) && m_event->propagationStopped())
+ return DoneDispatching;
+
+ for (size_t i = m_event->eventPath().size() - 1; i > 0; --i) {
+ const EventContext& eventContext = m_event->eventPath()[i];
+ if (eventContext.currentTargetSameAsTarget())
+ continue;
+ eventContext.handleLocalEvents(m_event.get());
+ if (m_event->propagationStopped())
+ return DoneDispatching;
+ }
+
+ return ContinueDispatching;
+}
+
+inline EventDispatchContinuation EventDispatcher::dispatchEventAtTarget()
+{
+ m_event->setEventPhase(Event::AT_TARGET);
+ m_event->eventPath()[0].handleLocalEvents(m_event.get());
+ return m_event->propagationStopped() ? DoneDispatching : ContinueDispatching;
+}
+
+inline void EventDispatcher::dispatchEventAtBubbling(WindowEventContext& windowContext)
+{
+ // Trigger bubbling event handlers, starting at the bottom and working our way up.
+ size_t size = m_event->eventPath().size();
+ for (size_t i = 1; i < size; ++i) {
+ const EventContext& eventContext = m_event->eventPath()[i];
+ if (eventContext.currentTargetSameAsTarget())
+ m_event->setEventPhase(Event::AT_TARGET);
+ else if (m_event->bubbles() && !m_event->cancelBubble())
+ m_event->setEventPhase(Event::BUBBLING_PHASE);
+ else
+ continue;
+ eventContext.handleLocalEvents(m_event.get());
+ if (m_event->propagationStopped())
+ return;
+ }
+ if (m_event->bubbles() && !m_event->cancelBubble()) {
+ m_event->setEventPhase(Event::BUBBLING_PHASE);
+ windowContext.handleLocalEvents(m_event.get());
+ }
+}
+
+inline void EventDispatcher::dispatchEventPostProcess(void* preDispatchEventHandlerResult)
+{
+ m_event->setTarget(EventPath::eventTargetRespectingTargetRules(m_node.get()));
+ m_event->setCurrentTarget(0);
+ m_event->setEventPhase(0);
+
+ // Pass the data from the preDispatchEventHandler to the postDispatchEventHandler.
+ m_node->postDispatchEventHandler(m_event.get(), preDispatchEventHandlerResult);
+
+ // Call default event handlers. While the DOM does have a concept of preventing
+ // default handling, the detail of which handlers are called is an internal
+ // implementation detail and not part of the DOM.
+ if (!m_event->defaultPrevented() && !m_event->defaultHandled()) {
+ // Non-bubbling events call only one default event handler, the one for the target.
+ m_node->willCallDefaultEventHandler(*m_event);
+ m_node->defaultEventHandler(m_event.get());
+ ASSERT(!m_event->defaultPrevented());
+ if (m_event->defaultHandled())
+ return;
+ // For bubbling events, call default event handlers on the same targets in the
+ // same order as the bubbling phase.
+ if (m_event->bubbles()) {
+ size_t size = m_event->eventPath().size();
+ for (size_t i = 1; i < size; ++i) {
+ m_event->eventPath()[i].node()->willCallDefaultEventHandler(*m_event);
+ m_event->eventPath()[i].node()->defaultEventHandler(m_event.get());
+ ASSERT(!m_event->defaultPrevented());
+ if (m_event->defaultHandled())
+ return;
+ }
+ }
+ }
+}
+
+const EventContext* EventDispatcher::topEventContext()
+{
+ return m_event->eventPath().isEmpty() ? 0 : &m_event->eventPath().last();
+}
+
+}
diff --git a/chromium/third_party/WebKit/Source/core/events/EventDispatcher.h b/chromium/third_party/WebKit/Source/core/events/EventDispatcher.h
new file mode 100644
index 00000000000..aae65a2d7f2
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/EventDispatcher.h
@@ -0,0 +1,83 @@
+/*
+ * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
+ * (C) 1999 Antti Koivisto (koivisto@kde.org)
+ * (C) 2001 Dirk Mueller (mueller@kde.org)
+ * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010 Apple Inc. All rights reserved.
+ * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
+ * Copyright (C) 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
+ * Copyright (C) 2011 Google Inc. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#ifndef EventDispatcher_h
+#define EventDispatcher_h
+
+#include "core/events/EventContext.h"
+#include "core/dom/SimulatedClickOptions.h"
+#include "wtf/Forward.h"
+#include "wtf/PassRefPtr.h"
+
+namespace WebCore {
+
+class Event;
+class EventDispatchMediator;
+class EventTarget;
+class FrameView;
+class Node;
+class PlatformKeyboardEvent;
+class PlatformMouseEvent;
+class ShadowRoot;
+class TreeScope;
+class WindowEventContext;
+
+enum EventDispatchContinuation {
+ ContinueDispatching,
+ DoneDispatching
+};
+
+class EventDispatcher {
+public:
+ static bool dispatchEvent(Node*, PassRefPtr<EventDispatchMediator>);
+ static void dispatchScopedEvent(Node*, PassRefPtr<EventDispatchMediator>);
+
+ static void dispatchSimulatedClick(Node*, Event* underlyingEvent, SimulatedClickMouseEventOptions);
+
+ bool dispatch();
+ Node* node() const { return m_node.get(); }
+ Event* event() const { return m_event.get(); }
+
+private:
+ EventDispatcher(Node*, PassRefPtr<Event>);
+ const EventContext* topEventContext();
+
+ EventDispatchContinuation dispatchEventPreProcess(void*& preDispatchEventHandlerResult);
+ EventDispatchContinuation dispatchEventAtCapturing(WindowEventContext&);
+ EventDispatchContinuation dispatchEventAtTarget();
+ void dispatchEventAtBubbling(WindowEventContext&);
+ void dispatchEventPostProcess(void* preDispatchEventHandlerResult);
+
+ RefPtr<Node> m_node;
+ RefPtr<Event> m_event;
+ RefPtr<FrameView> m_view;
+#ifndef NDEBUG
+ bool m_eventDispatched;
+#endif
+};
+
+}
+
+#endif
diff --git a/chromium/third_party/WebKit/Source/core/dom/EventFactory.h b/chromium/third_party/WebKit/Source/core/events/EventFactory.h
index 2436e3f0000..2436e3f0000 100644
--- a/chromium/third_party/WebKit/Source/core/dom/EventFactory.h
+++ b/chromium/third_party/WebKit/Source/core/events/EventFactory.h
diff --git a/chromium/third_party/WebKit/Source/core/events/EventListener.h b/chromium/third_party/WebKit/Source/core/events/EventListener.h
new file mode 100644
index 00000000000..78291043e83
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/EventListener.h
@@ -0,0 +1,65 @@
+/*
+ * Copyright (C) 2006, 2008, 2009 Apple Inc. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ */
+
+#ifndef EventListener_h
+#define EventListener_h
+
+#include "wtf/RefCounted.h"
+
+namespace WebCore {
+
+ class DOMWrapperWorld;
+ class Event;
+ class ExecutionContext;
+
+ class EventListener : public RefCounted<EventListener> {
+ public:
+ enum Type {
+ JSEventListenerType,
+ ImageEventListenerType,
+ CPPEventListenerType,
+ ConditionEventListenerType,
+ NativeEventListenerType,
+ };
+
+ virtual ~EventListener() { }
+ virtual bool operator==(const EventListener&) = 0;
+ virtual void handleEvent(ExecutionContext*, Event*) = 0;
+ virtual bool wasCreatedFromMarkup() const { return false; }
+ virtual DOMWrapperWorld* world() const { return 0; }
+
+ bool isAttribute() const { return virtualisAttribute(); }
+ Type type() const { return m_type; }
+
+ protected:
+ explicit EventListener(Type type)
+ : m_type(type)
+ {
+ }
+
+ private:
+ virtual bool virtualisAttribute() const { return false; }
+
+ Type m_type;
+ };
+
+}
+
+#endif
diff --git a/chromium/third_party/WebKit/Source/core/dom/EventListener.idl b/chromium/third_party/WebKit/Source/core/events/EventListener.idl
index fc4b8bc62b4..fc4b8bc62b4 100644
--- a/chromium/third_party/WebKit/Source/core/dom/EventListener.idl
+++ b/chromium/third_party/WebKit/Source/core/events/EventListener.idl
diff --git a/chromium/third_party/WebKit/Source/core/events/EventListenerMap.cpp b/chromium/third_party/WebKit/Source/core/events/EventListenerMap.cpp
new file mode 100644
index 00000000000..901f06314ac
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/EventListenerMap.cpp
@@ -0,0 +1,272 @@
+/*
+ * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
+ * (C) 1999 Antti Koivisto (koivisto@kde.org)
+ * (C) 2001 Dirk Mueller (mueller@kde.org)
+ * Copyright (C) 2004, 2005, 2006, 2007 Apple Inc. All rights reserved.
+ * Copyright (C) 2006 Alexey Proskuryakov (ap@webkit.org)
+ * (C) 2007, 2008 Nikolas Zimmermann <zimmermann@kde.org>
+ * Copyright (C) 2011 Andreas Kling (kling@webkit.org)
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "config.h"
+#include "core/events/EventListenerMap.h"
+
+#include "core/events/EventTarget.h"
+#include "wtf/StdLibExtras.h"
+#include "wtf/Vector.h"
+
+#ifndef NDEBUG
+#include "wtf/ThreadingPrimitives.h"
+#endif
+
+using namespace WTF;
+
+namespace WebCore {
+
+#ifndef NDEBUG
+static Mutex& activeIteratorCountMutex()
+{
+ DEFINE_STATIC_LOCAL(Mutex, mutex, ());
+ return mutex;
+}
+
+void EventListenerMap::assertNoActiveIterators()
+{
+ MutexLocker locker(activeIteratorCountMutex());
+ ASSERT(!m_activeIteratorCount);
+}
+#endif
+
+EventListenerMap::EventListenerMap()
+#ifndef NDEBUG
+ : m_activeIteratorCount(0)
+#endif
+{
+}
+
+bool EventListenerMap::contains(const AtomicString& eventType) const
+{
+ for (unsigned i = 0; i < m_entries.size(); ++i) {
+ if (m_entries[i].first == eventType)
+ return true;
+ }
+ return false;
+}
+
+bool EventListenerMap::containsCapturing(const AtomicString& eventType) const
+{
+ for (unsigned i = 0; i < m_entries.size(); ++i) {
+ if (m_entries[i].first == eventType) {
+ const EventListenerVector* vector = m_entries[i].second.get();
+ for (unsigned j = 0; j < vector->size(); ++j) {
+ if (vector->at(j).useCapture)
+ return true;
+ }
+ }
+ }
+ return false;
+}
+
+void EventListenerMap::clear()
+{
+ assertNoActiveIterators();
+
+ m_entries.clear();
+}
+
+Vector<AtomicString> EventListenerMap::eventTypes() const
+{
+ Vector<AtomicString> types;
+ types.reserveInitialCapacity(m_entries.size());
+
+ for (unsigned i = 0; i < m_entries.size(); ++i)
+ types.uncheckedAppend(m_entries[i].first);
+
+ return types;
+}
+
+static bool addListenerToVector(EventListenerVector* vector, PassRefPtr<EventListener> listener, bool useCapture)
+{
+ RegisteredEventListener registeredListener(listener, useCapture);
+
+ if (vector->find(registeredListener) != kNotFound)
+ return false; // Duplicate listener.
+
+ vector->append(registeredListener);
+ return true;
+}
+
+bool EventListenerMap::add(const AtomicString& eventType, PassRefPtr<EventListener> listener, bool useCapture)
+{
+ assertNoActiveIterators();
+
+ for (unsigned i = 0; i < m_entries.size(); ++i) {
+ if (m_entries[i].first == eventType)
+ return addListenerToVector(m_entries[i].second.get(), listener, useCapture);
+ }
+
+ m_entries.append(std::make_pair(eventType, adoptPtr(new EventListenerVector)));
+ return addListenerToVector(m_entries.last().second.get(), listener, useCapture);
+}
+
+static bool removeListenerFromVector(EventListenerVector* listenerVector, EventListener* listener, bool useCapture, size_t& indexOfRemovedListener)
+{
+ RegisteredEventListener registeredListener(listener, useCapture);
+ indexOfRemovedListener = listenerVector->find(registeredListener);
+ if (indexOfRemovedListener == kNotFound)
+ return false;
+ listenerVector->remove(indexOfRemovedListener);
+ return true;
+}
+
+bool EventListenerMap::remove(const AtomicString& eventType, EventListener* listener, bool useCapture, size_t& indexOfRemovedListener)
+{
+ assertNoActiveIterators();
+
+ for (unsigned i = 0; i < m_entries.size(); ++i) {
+ if (m_entries[i].first == eventType) {
+ bool wasRemoved = removeListenerFromVector(m_entries[i].second.get(), listener, useCapture, indexOfRemovedListener);
+ if (m_entries[i].second->isEmpty())
+ m_entries.remove(i);
+ return wasRemoved;
+ }
+ }
+
+ return false;
+}
+
+EventListenerVector* EventListenerMap::find(const AtomicString& eventType)
+{
+ assertNoActiveIterators();
+
+ for (unsigned i = 0; i < m_entries.size(); ++i) {
+ if (m_entries[i].first == eventType)
+ return m_entries[i].second.get();
+ }
+
+ return 0;
+}
+
+static void removeFirstListenerCreatedFromMarkup(EventListenerVector* listenerVector)
+{
+ bool foundListener = false;
+
+ for (size_t i = 0; i < listenerVector->size(); ++i) {
+ if (!listenerVector->at(i).listener->wasCreatedFromMarkup())
+ continue;
+ foundListener = true;
+ listenerVector->remove(i);
+ break;
+ }
+
+ ASSERT_UNUSED(foundListener, foundListener);
+}
+
+void EventListenerMap::removeFirstEventListenerCreatedFromMarkup(const AtomicString& eventType)
+{
+ assertNoActiveIterators();
+
+ for (unsigned i = 0; i < m_entries.size(); ++i) {
+ if (m_entries[i].first == eventType) {
+ removeFirstListenerCreatedFromMarkup(m_entries[i].second.get());
+ if (m_entries[i].second->isEmpty())
+ m_entries.remove(i);
+ return;
+ }
+ }
+}
+
+static void copyListenersNotCreatedFromMarkupToTarget(const AtomicString& eventType, EventListenerVector* listenerVector, EventTarget* target)
+{
+ for (size_t i = 0; i < listenerVector->size(); ++i) {
+ // Event listeners created from markup have already been transfered to the shadow tree during cloning.
+ if ((*listenerVector)[i].listener->wasCreatedFromMarkup())
+ continue;
+ target->addEventListener(eventType, (*listenerVector)[i].listener, (*listenerVector)[i].useCapture);
+ }
+}
+
+void EventListenerMap::copyEventListenersNotCreatedFromMarkupToTarget(EventTarget* target)
+{
+ assertNoActiveIterators();
+
+ for (unsigned i = 0; i < m_entries.size(); ++i)
+ copyListenersNotCreatedFromMarkupToTarget(m_entries[i].first, m_entries[i].second.get(), target);
+}
+
+EventListenerIterator::EventListenerIterator()
+ : m_map(0)
+ , m_entryIndex(0)
+ , m_index(0)
+{
+}
+
+EventListenerIterator::EventListenerIterator(EventTarget* target)
+ : m_map(0)
+ , m_entryIndex(0)
+ , m_index(0)
+{
+ ASSERT(target);
+ EventTargetData* data = target->eventTargetData();
+
+ if (!data)
+ return;
+
+ m_map = &data->eventListenerMap;
+
+#ifndef NDEBUG
+ {
+ MutexLocker locker(activeIteratorCountMutex());
+ m_map->m_activeIteratorCount++;
+ }
+#endif
+}
+
+#ifndef NDEBUG
+EventListenerIterator::~EventListenerIterator()
+{
+ if (m_map) {
+ MutexLocker locker(activeIteratorCountMutex());
+ m_map->m_activeIteratorCount--;
+ }
+}
+#endif
+
+EventListener* EventListenerIterator::nextListener()
+{
+ if (!m_map)
+ return 0;
+
+ for (; m_entryIndex < m_map->m_entries.size(); ++m_entryIndex) {
+ EventListenerVector& listeners = *m_map->m_entries[m_entryIndex].second;
+ if (m_index < listeners.size())
+ return listeners[m_index++].listener.get();
+ m_index = 0;
+ }
+
+ return 0;
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/events/EventListenerMap.h b/chromium/third_party/WebKit/Source/core/events/EventListenerMap.h
new file mode 100644
index 00000000000..fa39f2b23c1
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/EventListenerMap.h
@@ -0,0 +1,99 @@
+/*
+ * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
+ * (C) 1999 Antti Koivisto (koivisto@kde.org)
+ * (C) 2001 Dirk Mueller (mueller@kde.org)
+ * Copyright (C) 2004, 2005, 2006, 2007, 2012 Apple Inc. All rights reserved.
+ * Copyright (C) 2006 Alexey Proskuryakov (ap@webkit.org)
+ * (C) 2007, 2008 Nikolas Zimmermann <zimmermann@kde.org>
+ * Copyright (C) 2011 Andreas Kling (kling@webkit.org)
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#ifndef EventListenerMap_h
+#define EventListenerMap_h
+
+#include "core/events/RegisteredEventListener.h"
+#include "wtf/Forward.h"
+#include "wtf/PassOwnPtr.h"
+#include "wtf/text/AtomicStringHash.h"
+
+namespace WebCore {
+
+class EventTarget;
+
+typedef Vector<RegisteredEventListener, 1> EventListenerVector;
+
+class EventListenerMap {
+public:
+ EventListenerMap();
+
+ bool isEmpty() const { return m_entries.isEmpty(); }
+ bool contains(const AtomicString& eventType) const;
+ bool containsCapturing(const AtomicString& eventType) const;
+
+ void clear();
+ bool add(const AtomicString& eventType, PassRefPtr<EventListener>, bool useCapture);
+ bool remove(const AtomicString& eventType, EventListener*, bool useCapture, size_t& indexOfRemovedListener);
+ EventListenerVector* find(const AtomicString& eventType);
+ Vector<AtomicString> eventTypes() const;
+
+ void removeFirstEventListenerCreatedFromMarkup(const AtomicString& eventType);
+ void copyEventListenersNotCreatedFromMarkupToTarget(EventTarget*);
+
+private:
+ friend class EventListenerIterator;
+
+ void assertNoActiveIterators();
+
+ Vector<std::pair<AtomicString, OwnPtr<EventListenerVector> >, 2> m_entries;
+
+#ifndef NDEBUG
+ int m_activeIteratorCount;
+#endif
+};
+
+class EventListenerIterator {
+ WTF_MAKE_NONCOPYABLE(EventListenerIterator);
+public:
+ EventListenerIterator();
+ EventListenerIterator(EventTarget*);
+#ifndef NDEBUG
+ ~EventListenerIterator();
+#endif
+
+ EventListener* nextListener();
+
+private:
+ EventListenerMap* m_map;
+ unsigned m_entryIndex;
+ unsigned m_index;
+};
+
+#ifdef NDEBUG
+inline void EventListenerMap::assertNoActiveIterators() { }
+#endif
+
+} // namespace WebCore
+
+#endif // EventListenerMap_h
diff --git a/chromium/third_party/WebKit/Source/core/events/EventPath.cpp b/chromium/third_party/WebKit/Source/core/events/EventPath.cpp
new file mode 100644
index 00000000000..ca9a57dcdfa
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/EventPath.cpp
@@ -0,0 +1,257 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/events/EventPath.h"
+
+#include "EventNames.h"
+#include "RuntimeEnabledFeatures.h"
+#include "SVGNames.h"
+#include "core/dom/FullscreenElementStack.h"
+#include "core/dom/shadow/ElementShadow.h"
+#include "core/dom/shadow/InsertionPoint.h"
+#include "core/dom/shadow/ShadowRoot.h"
+#include "core/html/shadow/HTMLShadowElement.h"
+#include "core/svg/SVGElementInstance.h"
+#include "core/svg/SVGUseElement.h"
+
+namespace WebCore {
+
+Node* EventPath::parent(Node* node)
+{
+ EventPath eventPath(node);
+ return eventPath.size() > 1 ? eventPath[1].node() : 0;
+}
+
+EventTarget* EventPath::eventTargetRespectingTargetRules(Node* referenceNode)
+{
+ ASSERT(referenceNode);
+
+ if (referenceNode->isPseudoElement())
+ return referenceNode->parentNode();
+
+ if (!referenceNode->isSVGElement() || !referenceNode->isInShadowTree())
+ return referenceNode;
+
+ // Spec: The event handling for the non-exposed tree works as if the referenced element had been textually included
+ // as a deeply cloned child of the 'use' element, except that events are dispatched to the SVGElementInstance objects.
+ Node* rootNode = referenceNode->treeScope().rootNode();
+ Element* shadowHostElement = rootNode->isShadowRoot() ? toShadowRoot(rootNode)->host() : 0;
+ // At this time, SVG nodes are not supported in non-<use> shadow trees.
+ if (!shadowHostElement || !shadowHostElement->hasTagName(SVGNames::useTag))
+ return referenceNode;
+ SVGUseElement* useElement = toSVGUseElement(shadowHostElement);
+ if (SVGElementInstance* instance = useElement->instanceForShadowTreeElement(referenceNode))
+ return instance;
+
+ return referenceNode;
+}
+
+static inline bool inTheSameScope(ShadowRoot* shadowRoot, EventTarget* target)
+{
+ return target->toNode() && target->toNode()->treeScope().rootNode() == shadowRoot;
+}
+
+static inline EventDispatchBehavior determineDispatchBehavior(Event* event, ShadowRoot* shadowRoot, EventTarget* target)
+{
+ // Video-only full screen is a mode where we use the shadow DOM as an implementation
+ // detail that should not be detectable by the web content.
+ if (Element* element = FullscreenElementStack::currentFullScreenElementFrom(&target->toNode()->document())) {
+ // FIXME: We assume that if the full screen element is a media element that it's
+ // the video-only full screen. Both here and elsewhere. But that is probably wrong.
+ if (element->isMediaElement() && shadowRoot && shadowRoot->host() == element)
+ return StayInsideShadowDOM;
+ }
+
+ // WebKit never allowed selectstart event to cross the the shadow DOM boundary.
+ // Changing this breaks existing sites.
+ // See https://bugs.webkit.org/show_bug.cgi?id=52195 for details.
+ const AtomicString eventType = event->type();
+ if (inTheSameScope(shadowRoot, target)
+ && (eventType == EventTypeNames::abort
+ || eventType == EventTypeNames::change
+ || eventType == EventTypeNames::error
+ || eventType == EventTypeNames::load
+ || eventType == EventTypeNames::reset
+ || eventType == EventTypeNames::resize
+ || eventType == EventTypeNames::scroll
+ || eventType == EventTypeNames::select
+ || eventType == EventTypeNames::selectstart))
+ return StayInsideShadowDOM;
+
+ return RetargetEvent;
+}
+
+EventPath::EventPath(Event* event)
+ : m_node(0)
+ , m_event(event)
+{
+}
+
+EventPath::EventPath(Node* node)
+ : m_node(node)
+ , m_event(0)
+{
+ resetWith(node);
+}
+
+void EventPath::resetWith(Node* node)
+{
+ ASSERT(node);
+ m_node = node;
+ m_eventContexts.clear();
+ calculatePath();
+ calculateAdjustedTargets();
+ calculateAdjustedEventPathForEachNode();
+}
+
+void EventPath::addEventContext(Node* node)
+{
+ m_eventContexts.append(EventContext(node, eventTargetRespectingTargetRules(node)));
+}
+
+void EventPath::calculatePath()
+{
+ ASSERT(m_node);
+ ASSERT(m_eventContexts.isEmpty());
+ m_node->document().updateDistributionForNodeIfNeeded(const_cast<Node*>(m_node));
+
+ Node* current = m_node;
+ addEventContext(current);
+ if (!m_node->inDocument())
+ return;
+ while (current) {
+ if (current->isShadowRoot() && m_event && determineDispatchBehavior(m_event, toShadowRoot(current), m_node) == StayInsideShadowDOM)
+ break;
+ Vector<InsertionPoint*, 8> insertionPoints;
+ collectDestinationInsertionPoints(*current, insertionPoints);
+ if (!insertionPoints.isEmpty()) {
+ for (size_t i = 0; i < insertionPoints.size(); ++i) {
+ InsertionPoint* insertionPoint = insertionPoints[i];
+ if (insertionPoint->isShadowInsertionPoint()) {
+ ShadowRoot* containingShadowRoot = insertionPoint->containingShadowRoot();
+ ASSERT(containingShadowRoot);
+ if (!containingShadowRoot->isOldest())
+ addEventContext(containingShadowRoot->olderShadowRoot());
+ }
+ addEventContext(insertionPoint);
+ }
+ current = insertionPoints.last();
+ continue;
+ }
+ if (current->isShadowRoot()) {
+ current = current->shadowHost();
+ addEventContext(current);
+ } else {
+ current = current->parentNode();
+ if (current)
+ addEventContext(current);
+ }
+ }
+}
+
+void EventPath::calculateAdjustedEventPathForEachNode()
+{
+ if (!RuntimeEnabledFeatures::shadowDOMEnabled())
+ return;
+ TreeScope* lastScope = 0;
+ for (size_t i = 0; i < size(); ++i) {
+ TreeScope* currentScope = &at(i).node()->treeScope();
+ if (currentScope == lastScope) {
+ // Fast path.
+ at(i).setEventPath(at(i - 1).eventPath());
+ continue;
+ }
+ lastScope = currentScope;
+ Vector<RefPtr<Node> > nodes;
+ nodes.reserveInitialCapacity(size());
+ for (size_t j = 0; j < size(); ++j) {
+ if (at(j).node()->treeScope().isInclusiveAncestorOf(*currentScope))
+ nodes.append(at(j).node());
+ }
+ at(i).adoptEventPath(nodes);
+ }
+}
+
+#ifndef NDEBUG
+static inline bool movedFromOlderToYounger(const TreeScope& lastTreeScope, const TreeScope& currentTreeScope)
+{
+ Node* rootNode = lastTreeScope.rootNode();
+ return rootNode->isShadowRoot() && toShadowRoot(rootNode)->youngerShadowRoot() == currentTreeScope.rootNode();
+}
+
+static inline bool movedFromYoungerToOlder(const TreeScope& lastTreeScope, const TreeScope& currentTreeScope)
+{
+ Node* rootNode = lastTreeScope.rootNode();
+ return rootNode->isShadowRoot() && toShadowRoot(rootNode)->olderShadowRoot() == currentTreeScope.rootNode();
+}
+#endif
+
+static inline bool movedFromChildToParent(const TreeScope& lastTreeScope, const TreeScope& currentTreeScope)
+{
+ return lastTreeScope.parentTreeScope() == &currentTreeScope;
+}
+
+static inline bool movedFromParentToChild(const TreeScope& lastTreeScope, const TreeScope& currentTreeScope)
+{
+ return currentTreeScope.parentTreeScope() == &lastTreeScope;
+}
+
+void EventPath::calculateAdjustedTargets()
+{
+ Vector<Node*, 32> targetStack;
+ const TreeScope* lastTreeScope = 0;
+ bool isSVGElement = at(0).node()->isSVGElement();
+
+ for (size_t i = 0; i < size(); ++i) {
+ Node* current = at(i).node();
+ const TreeScope& currentTreeScope = current->treeScope();
+ if (targetStack.isEmpty()) {
+ targetStack.append(current);
+ } else if (*lastTreeScope != currentTreeScope && !isSVGElement) {
+ if (movedFromParentToChild(*lastTreeScope, currentTreeScope)) {
+ targetStack.append(targetStack.last());
+ } else if (movedFromChildToParent(*lastTreeScope, currentTreeScope)) {
+ ASSERT(!targetStack.isEmpty());
+ targetStack.removeLast();
+ if (targetStack.isEmpty())
+ targetStack.append(current);
+ } else {
+ ASSERT(movedFromYoungerToOlder(*lastTreeScope, currentTreeScope) || movedFromOlderToYounger(*lastTreeScope, currentTreeScope));
+ ASSERT(!targetStack.isEmpty());
+ targetStack.removeLast();
+ if (targetStack.isEmpty())
+ targetStack.append(current);
+ else
+ targetStack.append(targetStack.last());
+ }
+ }
+ at(i).setTarget(eventTargetRespectingTargetRules(targetStack.last()));
+ lastTreeScope = &currentTreeScope;
+ }
+}
+
+} // namespace
diff --git a/chromium/third_party/WebKit/Source/core/events/EventPath.h b/chromium/third_party/WebKit/Source/core/events/EventPath.h
new file mode 100644
index 00000000000..e5db6c4caf1
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/EventPath.h
@@ -0,0 +1,82 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef EventPath_h
+#define EventPath_h
+
+#include "core/events/EventContext.h"
+
+#include "wtf/OwnPtr.h"
+#include "wtf/Vector.h"
+
+namespace WebCore {
+
+class Event;
+class EventTarget;
+class Node;
+
+enum EventDispatchBehavior {
+ RetargetEvent,
+ StayInsideShadowDOM
+};
+
+class EventPath {
+public:
+ explicit EventPath(Event*);
+ explicit EventPath(Node*);
+ void resetWith(Node*);
+
+ EventContext& operator[](size_t index) { return m_eventContexts[index]; }
+ const EventContext& operator[](size_t index) const { return m_eventContexts[index]; }
+ const EventContext& last() const { return m_eventContexts[size() - 1]; }
+
+ bool isEmpty() const { return m_eventContexts.isEmpty(); }
+ size_t size() const { return m_eventContexts.size(); }
+
+ void shrink(size_t newSize) { m_eventContexts.shrink(newSize); }
+
+ static Node* parent(Node*);
+ static EventTarget* eventTargetRespectingTargetRules(Node*);
+
+private:
+ EventPath();
+
+ EventContext& at(size_t index) { return m_eventContexts[index]; }
+
+ void addEventContext(Node*);
+
+ void calculatePath();
+ void calculateAdjustedTargets();
+ void calculateAdjustedEventPathForEachNode();
+
+ Vector<EventContext, 64> m_eventContexts;
+ Node* m_node;
+ Event* m_event;
+};
+
+} // namespace
+
+#endif
diff --git a/chromium/third_party/WebKit/Source/core/dom/EventQueue.h b/chromium/third_party/WebKit/Source/core/events/EventQueue.h
index 770ae797d21..770ae797d21 100644
--- a/chromium/third_party/WebKit/Source/core/dom/EventQueue.h
+++ b/chromium/third_party/WebKit/Source/core/events/EventQueue.h
diff --git a/chromium/third_party/WebKit/Source/core/events/EventRetargeter.cpp b/chromium/third_party/WebKit/Source/core/events/EventRetargeter.cpp
new file mode 100644
index 00000000000..d225dbc94b9
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/EventRetargeter.cpp
@@ -0,0 +1,187 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#include "config.h"
+#include "core/events/EventRetargeter.h"
+
+#include "RuntimeEnabledFeatures.h"
+#include "core/dom/ContainerNode.h"
+#include "core/dom/FullscreenElementStack.h"
+#include "core/dom/Touch.h"
+#include "core/dom/TouchList.h"
+#include "core/dom/TreeScope.h"
+#include "core/dom/shadow/InsertionPoint.h"
+#include "core/dom/shadow/ShadowRoot.h"
+#include "core/events/EventContext.h"
+#include "core/events/EventPath.h"
+#include "core/events/FocusEvent.h"
+#include "core/events/MouseEvent.h"
+#include "core/events/TouchEvent.h"
+#include "wtf/PassRefPtr.h"
+
+namespace WebCore {
+
+void EventRetargeter::adjustForMouseEvent(Node* node, MouseEvent& mouseEvent)
+{
+ adjustForRelatedTarget(node, mouseEvent.relatedTarget(), mouseEvent.eventPath());
+}
+
+void EventRetargeter::adjustForFocusEvent(Node* node, FocusEvent& focusEvent)
+{
+ adjustForRelatedTarget(node, focusEvent.relatedTarget(), focusEvent.eventPath());
+}
+
+void EventRetargeter::adjustForTouchEvent(Node* node, TouchEvent& touchEvent)
+{
+ EventPath& eventPath = touchEvent.eventPath();
+ size_t eventPathSize = eventPath.size();
+
+ EventPathTouchLists eventPathTouches(eventPathSize);
+ EventPathTouchLists eventPathTargetTouches(eventPathSize);
+ EventPathTouchLists eventPathChangedTouches(eventPathSize);
+
+ for (size_t i = 0; i < eventPathSize; ++i) {
+ TouchEventContext* touchEventContext = eventPath[i].ensureTouchEventContext();
+ eventPathTouches[i] = touchEventContext->touches();
+ eventPathTargetTouches[i] = touchEventContext->targetTouches();
+ eventPathChangedTouches[i] = touchEventContext->changedTouches();
+ }
+
+ adjustTouchList(node, touchEvent.touches(), eventPath, eventPathTouches);
+ adjustTouchList(node, touchEvent.targetTouches(), eventPath, eventPathTargetTouches);
+ adjustTouchList(node, touchEvent.changedTouches(), eventPath, eventPathChangedTouches);
+
+#ifndef NDEBUG
+ for (size_t i = 0; i < eventPathSize; ++i) {
+ checkReachability(node, eventPath[i].touchEventContext()->touches());
+ checkReachability(node, eventPath[i].touchEventContext()->targetTouches());
+ checkReachability(node, eventPath[i].touchEventContext()->changedTouches());
+ }
+#endif
+}
+
+#ifndef NDEBUG
+void EventRetargeter::checkReachability(Node* node, TouchList* touchList)
+{
+ for (size_t i = 0; i < touchList->length(); ++i)
+ ASSERT(touchList->item(i)->target()->toNode()->treeScope().isInclusiveAncestorOf(node->treeScope()));
+}
+#endif
+
+void EventRetargeter::adjustTouchList(const Node* node, const TouchList* touchList, const EventPath& eventPath, EventPathTouchLists& eventPathTouchLists)
+{
+ if (!touchList)
+ return;
+ size_t eventPathSize = eventPath.size();
+ ASSERT(eventPathTouchLists.size() == eventPathSize);
+ for (size_t i = 0; i < touchList->length(); ++i) {
+ const Touch& touch = *touchList->item(i);
+ AdjustedTargets adjustedNodes;
+ calculateAdjustedNodes(node, touch.target()->toNode(), DoesNotStopAtBoundary, const_cast<EventPath&>(eventPath), adjustedNodes);
+ ASSERT(adjustedNodes.size() == eventPathSize);
+ for (size_t j = 0; j < eventPathSize; ++j)
+ eventPathTouchLists[j]->append(touch.cloneWithNewTarget(adjustedNodes[j].get()));
+ }
+}
+
+void EventRetargeter::adjustForRelatedTarget(const Node* node, EventTarget* relatedTarget, EventPath& eventPath)
+{
+ if (!node)
+ return;
+ if (!relatedTarget)
+ return;
+ Node* relatedNode = relatedTarget->toNode();
+ if (!relatedNode)
+ return;
+ AdjustedTargets adjustedNodes;
+ calculateAdjustedNodes(node, relatedNode, StopAtBoundaryIfNeeded, eventPath, adjustedNodes);
+ ASSERT(adjustedNodes.size() <= eventPath.size());
+ for (size_t i = 0; i < adjustedNodes.size(); ++i) {
+ eventPath[i].setRelatedTarget(adjustedNodes[i]);
+ }
+}
+
+void EventRetargeter::calculateAdjustedNodes(const Node* node, const Node* relatedNode, EventWithRelatedTargetDispatchBehavior eventWithRelatedTargetDispatchBehavior, EventPath& eventPath, AdjustedTargets& adjustedTargets)
+{
+ RelatedTargetMap relatedNodeMap;
+ buildRelatedNodeMap(relatedNode, relatedNodeMap);
+
+ // Synthetic mouse events can have a relatedTarget which is identical to the target.
+ bool targetIsIdenticalToToRelatedTarget = (node == relatedNode);
+
+ TreeScope* lastTreeScope = 0;
+ EventTarget* adjustedTarget = 0;
+
+ for (size_t i = 0; i < eventPath.size(); ++i) {
+ TreeScope* scope = &eventPath[i].node()->treeScope();
+ if (scope == lastTreeScope) {
+ // Re-use the previous adjustedRelatedTarget if treeScope does not change. Just for the performance optimization.
+ adjustedTargets.append(adjustedTarget);
+ } else {
+ adjustedTarget = findRelatedNode(scope, relatedNodeMap);
+ adjustedTargets.append(adjustedTarget);
+ }
+ lastTreeScope = scope;
+ if (eventWithRelatedTargetDispatchBehavior == DoesNotStopAtBoundary)
+ continue;
+ if (targetIsIdenticalToToRelatedTarget) {
+ if (node->treeScope().rootNode() == eventPath[i].node()) {
+ eventPath.shrink(i + 1);
+ break;
+ }
+ } else if (eventPath[i].target() == adjustedTarget) {
+ // Event dispatching should be stopped here.
+ eventPath.shrink(i);
+ adjustedTargets.shrink(adjustedTargets.size() - 1);
+ break;
+ }
+ }
+}
+
+void EventRetargeter::buildRelatedNodeMap(const Node* relatedNode, RelatedTargetMap& relatedTargetMap)
+{
+ TreeScope* lastTreeScope = 0;
+ EventPath eventPath(const_cast<Node*>(relatedNode));
+ for (size_t i = 0; i < eventPath.size(); ++i) {
+ TreeScope* treeScope = &eventPath[i].node()->treeScope();
+ if (treeScope != lastTreeScope)
+ relatedTargetMap.add(treeScope, eventPath[i].target());
+ lastTreeScope = treeScope;
+ }
+}
+
+EventTarget* EventRetargeter::findRelatedNode(TreeScope* scope, RelatedTargetMap& relatedTargetMap)
+{
+ Vector<TreeScope*, 32> parentTreeScopes;
+ EventTarget* relatedNode = 0;
+ while (scope) {
+ parentTreeScopes.append(scope);
+ RelatedTargetMap::const_iterator found = relatedTargetMap.find(scope);
+ if (found != relatedTargetMap.end()) {
+ relatedNode = found->value;
+ break;
+ }
+ scope = scope->parentTreeScope();
+ }
+ for (Vector<TreeScope*, 32>::iterator iter = parentTreeScopes.begin(); iter < parentTreeScopes.end(); ++iter)
+ relatedTargetMap.add(*iter, relatedNode);
+ return relatedNode;
+}
+
+}
diff --git a/chromium/third_party/WebKit/Source/core/events/EventRetargeter.h b/chromium/third_party/WebKit/Source/core/events/EventRetargeter.h
new file mode 100644
index 00000000000..38d391c348b
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/EventRetargeter.h
@@ -0,0 +1,64 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#ifndef EventRetargeter_h
+#define EventRetargeter_h
+
+#include "wtf/HashMap.h"
+#include "wtf/RefPtr.h"
+#include "wtf/Vector.h"
+
+namespace WebCore {
+
+class EventPath;
+class EventTarget;
+class FocusEvent;
+class MouseEvent;
+class Node;
+class TouchEvent;
+class TouchList;
+class TreeScope;
+
+class EventRetargeter {
+public:
+ static void adjustForMouseEvent(Node*, MouseEvent&);
+ static void adjustForFocusEvent(Node*, FocusEvent&);
+ typedef Vector<RefPtr<TouchList> > EventPathTouchLists;
+ static void adjustForTouchEvent(Node*, TouchEvent&);
+
+private:
+ typedef Vector<RefPtr<EventTarget> > AdjustedTargets;
+ typedef HashMap<TreeScope*, EventTarget*> RelatedTargetMap;
+ enum EventWithRelatedTargetDispatchBehavior {
+ StopAtBoundaryIfNeeded,
+ DoesNotStopAtBoundary
+ };
+ static void adjustForRelatedTarget(const Node*, EventTarget* relatedTarget, EventPath&);
+ static void calculateAdjustedNodes(const Node*, const Node* relatedNode, EventWithRelatedTargetDispatchBehavior, EventPath&, AdjustedTargets&);
+ static void buildRelatedNodeMap(const Node*, RelatedTargetMap&);
+ static EventTarget* findRelatedNode(TreeScope*, RelatedTargetMap&);
+ static void adjustTouchList(const Node*, const TouchList*, const EventPath&, EventPathTouchLists&);
+#ifndef NDEBUG
+ static void checkReachability(Node*, TouchList*);
+#endif
+};
+
+}
+
+#endif // EventRetargeter_h
diff --git a/chromium/third_party/WebKit/Source/core/events/EventSender.h b/chromium/third_party/WebKit/Source/core/events/EventSender.h
new file mode 100644
index 00000000000..f07678f23c4
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/EventSender.h
@@ -0,0 +1,113 @@
+/*
+ * Copyright (C) 2012 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef EventSender_h
+#define EventSender_h
+
+#include "platform/Timer.h"
+#include "wtf/Vector.h"
+#include "wtf/text/AtomicString.h"
+
+namespace WebCore {
+
+template<typename T> class EventSender {
+ WTF_MAKE_NONCOPYABLE(EventSender); WTF_MAKE_FAST_ALLOCATED;
+public:
+ explicit EventSender(const AtomicString& eventType);
+
+ const AtomicString& eventType() const { return m_eventType; }
+ void dispatchEventSoon(T*);
+ void cancelEvent(T*);
+ void dispatchPendingEvents();
+
+#ifndef NDEBUG
+ bool hasPendingEvents(T* sender) const
+ {
+ return m_dispatchSoonList.find(sender) != kNotFound || m_dispatchingList.find(sender) != kNotFound;
+ }
+#endif
+
+private:
+ void timerFired(Timer<EventSender<T> >*) { dispatchPendingEvents(); }
+
+ AtomicString m_eventType;
+ Timer<EventSender<T> > m_timer;
+ Vector<T*> m_dispatchSoonList;
+ Vector<T*> m_dispatchingList;
+};
+
+template<typename T> EventSender<T>::EventSender(const AtomicString& eventType)
+ : m_eventType(eventType)
+ , m_timer(this, &EventSender::timerFired)
+{
+}
+
+template<typename T> void EventSender<T>::dispatchEventSoon(T* sender)
+{
+ m_dispatchSoonList.append(sender);
+ if (!m_timer.isActive())
+ m_timer.startOneShot(0);
+}
+
+template<typename T> void EventSender<T>::cancelEvent(T* sender)
+{
+ // Remove instances of this sender from both lists.
+ // Use loops because we allow multiple instances to get into the lists.
+ size_t size = m_dispatchSoonList.size();
+ for (size_t i = 0; i < size; ++i) {
+ if (m_dispatchSoonList[i] == sender)
+ m_dispatchSoonList[i] = 0;
+ }
+ size = m_dispatchingList.size();
+ for (size_t i = 0; i < size; ++i) {
+ if (m_dispatchingList[i] == sender)
+ m_dispatchingList[i] = 0;
+ }
+}
+
+template<typename T> void EventSender<T>::dispatchPendingEvents()
+{
+ // Need to avoid re-entering this function; if new dispatches are
+ // scheduled before the parent finishes processing the list, they
+ // will set a timer and eventually be processed.
+ if (!m_dispatchingList.isEmpty())
+ return;
+
+ m_timer.stop();
+
+ m_dispatchingList.swap(m_dispatchSoonList);
+ size_t size = m_dispatchingList.size();
+ for (size_t i = 0; i < size; ++i) {
+ if (T* sender = m_dispatchingList[i]) {
+ m_dispatchingList[i] = 0;
+ sender->dispatchPendingEvent(this);
+ }
+ }
+ m_dispatchingList.clear();
+}
+
+} // namespace WebCore
+
+#endif // EventSender_h
diff --git a/chromium/third_party/WebKit/Source/core/events/EventTarget.cpp b/chromium/third_party/WebKit/Source/core/events/EventTarget.cpp
new file mode 100644
index 00000000000..6e96b47c6cd
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/EventTarget.cpp
@@ -0,0 +1,377 @@
+/*
+ * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
+ * (C) 1999 Antti Koivisto (koivisto@kde.org)
+ * (C) 2001 Dirk Mueller (mueller@kde.org)
+ * Copyright (C) 2004, 2005, 2006, 2007 Apple Inc. All rights reserved.
+ * Copyright (C) 2006 Alexey Proskuryakov (ap@webkit.org)
+ * (C) 2007, 2008 Nikolas Zimmermann <zimmermann@kde.org>
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "config.h"
+#include "core/events/EventTarget.h"
+
+#include "RuntimeEnabledFeatures.h"
+#include "bindings/v8/DOMWrapperWorld.h"
+#include "bindings/v8/ExceptionState.h"
+#include "core/events/Event.h"
+#include "core/dom/ExceptionCode.h"
+#include "core/inspector/InspectorInstrumentation.h"
+#include "core/frame/DOMWindow.h"
+#include "platform/UserGestureIndicator.h"
+#include "wtf/StdLibExtras.h"
+#include "wtf/Vector.h"
+
+using namespace WTF;
+
+namespace WebCore {
+
+EventTargetData::EventTargetData()
+{
+}
+
+EventTargetData::~EventTargetData()
+{
+}
+
+EventTarget::~EventTarget()
+{
+}
+
+Node* EventTarget::toNode()
+{
+ return 0;
+}
+
+DOMWindow* EventTarget::toDOMWindow()
+{
+ return 0;
+}
+
+MessagePort* EventTarget::toMessagePort()
+{
+ return 0;
+}
+
+inline DOMWindow* EventTarget::executingWindow()
+{
+ if (ExecutionContext* context = executionContext())
+ return context->executingWindow();
+ return 0;
+}
+
+bool EventTarget::addEventListener(const AtomicString& eventType, PassRefPtr<EventListener> listener, bool useCapture)
+{
+ return ensureEventTargetData().eventListenerMap.add(eventType, listener, useCapture);
+}
+
+bool EventTarget::removeEventListener(const AtomicString& eventType, EventListener* listener, bool useCapture)
+{
+ EventTargetData* d = eventTargetData();
+ if (!d)
+ return false;
+
+ size_t indexOfRemovedListener;
+
+ if (!d->eventListenerMap.remove(eventType, listener, useCapture, indexOfRemovedListener))
+ return false;
+
+ // Notify firing events planning to invoke the listener at 'index' that
+ // they have one less listener to invoke.
+ if (!d->firingEventIterators)
+ return true;
+ for (size_t i = 0; i < d->firingEventIterators->size(); ++i) {
+ FiringEventIterator& firingIterator = d->firingEventIterators->at(i);
+ if (eventType != firingIterator.eventType)
+ continue;
+
+ if (indexOfRemovedListener >= firingIterator.end)
+ continue;
+
+ --firingIterator.end;
+ if (indexOfRemovedListener <= firingIterator.iterator)
+ --firingIterator.iterator;
+ }
+
+ return true;
+}
+
+bool EventTarget::setAttributeEventListener(const AtomicString& eventType, PassRefPtr<EventListener> listener, DOMWrapperWorld* isolatedWorld)
+{
+ clearAttributeEventListener(eventType, isolatedWorld);
+ if (!listener)
+ return false;
+ return addEventListener(eventType, listener, false);
+}
+
+EventListener* EventTarget::getAttributeEventListener(const AtomicString& eventType, DOMWrapperWorld* isolatedWorld)
+{
+ const EventListenerVector& entry = getEventListeners(eventType);
+ for (size_t i = 0; i < entry.size(); ++i) {
+ EventListener* listener = entry[i].listener.get();
+ if (listener->isAttribute()) {
+ DOMWrapperWorld* listenerWorld = listener->world();
+ // Worker listener
+ if (!listenerWorld) {
+ ASSERT(!isolatedWorld);
+ return listener;
+ }
+ if (listenerWorld->isMainWorld() && !isolatedWorld)
+ return listener;
+ if (listenerWorld == isolatedWorld)
+ return listener;
+ }
+ }
+ return 0;
+}
+
+bool EventTarget::clearAttributeEventListener(const AtomicString& eventType, DOMWrapperWorld* isolatedWorld)
+{
+ EventListener* listener = getAttributeEventListener(eventType, isolatedWorld);
+ if (!listener)
+ return false;
+ return removeEventListener(eventType, listener, false);
+}
+
+bool EventTarget::dispatchEvent(PassRefPtr<Event> event, ExceptionState& exceptionState)
+{
+ if (!event) {
+ exceptionState.throwDOMException(InvalidStateError, "The event provided is null.");
+ return false;
+ }
+ if (event->type().isEmpty()) {
+ exceptionState.throwDOMException(InvalidStateError, "The event provided is uninitialized.");
+ return false;
+ }
+ if (event->isBeingDispatched()) {
+ exceptionState.throwDOMException(InvalidStateError, "The event is already being dispatched.");
+ return false;
+ }
+
+ if (!executionContext())
+ return false;
+
+ return dispatchEvent(event);
+}
+
+bool EventTarget::dispatchEvent(PassRefPtr<Event> event)
+{
+ event->setTarget(this);
+ event->setCurrentTarget(this);
+ event->setEventPhase(Event::AT_TARGET);
+ bool defaultPrevented = fireEventListeners(event.get());
+ event->setEventPhase(0);
+ return defaultPrevented;
+}
+
+void EventTarget::uncaughtExceptionInEventHandler()
+{
+}
+
+static AtomicString legacyType(const Event* event)
+{
+ if (event->type() == EventTypeNames::transitionend)
+ return EventTypeNames::webkitTransitionEnd;
+
+ if (event->type() == EventTypeNames::animationstart)
+ return EventTypeNames::webkitAnimationStart;
+
+ if (event->type() == EventTypeNames::animationend)
+ return EventTypeNames::webkitAnimationEnd;
+
+ if (event->type() == EventTypeNames::animationiteration)
+ return EventTypeNames::webkitAnimationIteration;
+
+ if (event->type() == EventTypeNames::wheel)
+ return EventTypeNames::mousewheel;
+
+ return emptyString();
+}
+
+void EventTarget::countLegacyEvents(const AtomicString& legacyTypeName, EventListenerVector* listenersVector, EventListenerVector* legacyListenersVector)
+{
+ UseCounter::Feature unprefixedFeature;
+ UseCounter::Feature prefixedFeature;
+ UseCounter::Feature prefixedAndUnprefixedFeature;
+ bool shouldCount = false;
+
+ if (legacyTypeName == EventTypeNames::webkitTransitionEnd) {
+ prefixedFeature = UseCounter::PrefixedTransitionEndEvent;
+ unprefixedFeature = UseCounter::UnprefixedTransitionEndEvent;
+ prefixedAndUnprefixedFeature = UseCounter::PrefixedAndUnprefixedTransitionEndEvent;
+ shouldCount = true;
+ } else if (legacyTypeName == EventTypeNames::webkitAnimationEnd) {
+ prefixedFeature = UseCounter::PrefixedAnimationEndEvent;
+ unprefixedFeature = UseCounter::UnprefixedAnimationEndEvent;
+ prefixedAndUnprefixedFeature = UseCounter::PrefixedAndUnprefixedAnimationEndEvent;
+ shouldCount = true;
+ } else if (legacyTypeName == EventTypeNames::webkitAnimationStart) {
+ prefixedFeature = UseCounter::PrefixedAnimationStartEvent;
+ unprefixedFeature = UseCounter::UnprefixedAnimationStartEvent;
+ prefixedAndUnprefixedFeature = UseCounter::PrefixedAndUnprefixedAnimationStartEvent;
+ shouldCount = true;
+ } else if (legacyTypeName == EventTypeNames::webkitAnimationIteration) {
+ prefixedFeature = UseCounter::PrefixedAnimationIterationEvent;
+ unprefixedFeature = UseCounter::UnprefixedAnimationIterationEvent;
+ prefixedAndUnprefixedFeature = UseCounter::PrefixedAndUnprefixedAnimationIterationEvent;
+ shouldCount = true;
+ }
+
+ if (shouldCount) {
+ if (DOMWindow* executingWindow = this->executingWindow()) {
+ if (legacyListenersVector) {
+ if (listenersVector)
+ UseCounter::count(executingWindow, prefixedAndUnprefixedFeature);
+ else
+ UseCounter::count(executingWindow, prefixedFeature);
+ } else if (listenersVector) {
+ UseCounter::count(executingWindow, unprefixedFeature);
+ }
+ }
+ }
+}
+
+bool EventTarget::fireEventListeners(Event* event)
+{
+ ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
+ ASSERT(event && !event->type().isEmpty());
+
+ EventTargetData* d = eventTargetData();
+ if (!d)
+ return true;
+
+ EventListenerVector* legacyListenersVector = 0;
+ AtomicString legacyTypeName = legacyType(event);
+ if (!legacyTypeName.isEmpty())
+ legacyListenersVector = d->eventListenerMap.find(legacyTypeName);
+
+ EventListenerVector* listenersVector = d->eventListenerMap.find(event->type());
+ if (!RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled() && (event->type() == EventTypeNames::animationiteration || event->type() == EventTypeNames::animationend
+ || event->type() == EventTypeNames::animationstart))
+ listenersVector = 0;
+
+ if (listenersVector) {
+ fireEventListeners(event, d, *listenersVector);
+ } else if (legacyListenersVector) {
+ AtomicString unprefixedTypeName = event->type();
+ event->setType(legacyTypeName);
+ fireEventListeners(event, d, *legacyListenersVector);
+ event->setType(unprefixedTypeName);
+ }
+
+ countLegacyEvents(legacyTypeName, listenersVector, legacyListenersVector);
+ return !event->defaultPrevented();
+}
+
+void EventTarget::fireEventListeners(Event* event, EventTargetData* d, EventListenerVector& entry)
+{
+ RefPtr<EventTarget> protect = this;
+
+ // Fire all listeners registered for this event. Don't fire listeners removed
+ // during event dispatch. Also, don't fire event listeners added during event
+ // dispatch. Conveniently, all new event listeners will be added after or at
+ // index |size|, so iterating up to (but not including) |size| naturally excludes
+ // new event listeners.
+
+ if (event->type() == EventTypeNames::beforeunload) {
+ if (DOMWindow* executingWindow = this->executingWindow()) {
+ if (executingWindow->top())
+ UseCounter::count(executingWindow, UseCounter::SubFrameBeforeUnloadFired);
+ UseCounter::count(executingWindow, UseCounter::DocumentBeforeUnloadFired);
+ }
+ } else if (event->type() == EventTypeNames::unload) {
+ if (DOMWindow* executingWindow = this->executingWindow())
+ UseCounter::count(executingWindow, UseCounter::DocumentUnloadFired);
+ }
+
+ bool userEventWasHandled = false;
+ size_t i = 0;
+ size_t size = entry.size();
+ if (!d->firingEventIterators)
+ d->firingEventIterators = adoptPtr(new FiringEventIteratorVector);
+ d->firingEventIterators->append(FiringEventIterator(event->type(), i, size));
+ for ( ; i < size; ++i) {
+ RegisteredEventListener& registeredListener = entry[i];
+ if (event->eventPhase() == Event::CAPTURING_PHASE && !registeredListener.useCapture)
+ continue;
+ if (event->eventPhase() == Event::BUBBLING_PHASE && registeredListener.useCapture)
+ continue;
+
+ // If stopImmediatePropagation has been called, we just break out immediately, without
+ // handling any more events on this target.
+ if (event->immediatePropagationStopped())
+ break;
+
+ ExecutionContext* context = executionContext();
+ if (!context)
+ break;
+
+ InspectorInstrumentationCookie cookie = InspectorInstrumentation::willHandleEvent(context, event);
+ // To match Mozilla, the AT_TARGET phase fires both capturing and bubbling
+ // event listeners, even though that violates some versions of the DOM spec.
+ registeredListener.listener->handleEvent(context, event);
+ if (!userEventWasHandled && UserGestureIndicator::processingUserGesture())
+ userEventWasHandled = true;
+ InspectorInstrumentation::didHandleEvent(cookie);
+ }
+ d->firingEventIterators->removeLast();
+ if (userEventWasHandled) {
+ if (ExecutionContext* context = executionContext())
+ context->userEventWasHandled();
+ }
+}
+
+const EventListenerVector& EventTarget::getEventListeners(const AtomicString& eventType)
+{
+ DEFINE_STATIC_LOCAL(EventListenerVector, emptyVector, ());
+
+ EventTargetData* d = eventTargetData();
+ if (!d)
+ return emptyVector;
+
+ EventListenerVector* listenerVector = d->eventListenerMap.find(eventType);
+ if (!listenerVector)
+ return emptyVector;
+
+ return *listenerVector;
+}
+
+void EventTarget::removeAllEventListeners()
+{
+ EventTargetData* d = eventTargetData();
+ if (!d)
+ return;
+ d->eventListenerMap.clear();
+
+ // Notify firing events planning to invoke the listener at 'index' that
+ // they have one less listener to invoke.
+ if (d->firingEventIterators) {
+ for (size_t i = 0; i < d->firingEventIterators->size(); ++i) {
+ d->firingEventIterators->at(i).iterator = 0;
+ d->firingEventIterators->at(i).end = 0;
+ }
+ }
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/events/EventTarget.h b/chromium/third_party/WebKit/Source/core/events/EventTarget.h
new file mode 100644
index 00000000000..fa2192538a2
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/EventTarget.h
@@ -0,0 +1,253 @@
+/*
+ * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
+ * (C) 1999 Antti Koivisto (koivisto@kde.org)
+ * (C) 2001 Dirk Mueller (mueller@kde.org)
+ * Copyright (C) 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
+ * Copyright (C) 2006 Alexey Proskuryakov (ap@webkit.org)
+ * (C) 2007, 2008 Nikolas Zimmermann <zimmermann@kde.org>
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#ifndef EventTarget_h
+#define EventTarget_h
+
+#include "core/events/EventListenerMap.h"
+#include "core/events/ThreadLocalEventNames.h"
+#include "wtf/Forward.h"
+
+namespace WebCore {
+
+class ApplicationCache;
+class AudioContext;
+class DOMWindow;
+class DedicatedWorkerGlobalScope;
+class Event;
+class EventListener;
+class EventSource;
+class ExceptionState;
+class FileReader;
+class FileWriter;
+class IDBDatabase;
+class IDBRequest;
+class IDBTransaction;
+class MIDIAccess;
+class MIDIInput;
+class MIDIPort;
+class MediaController;
+class MediaStream;
+class MessagePort;
+class NamedFlow;
+class Node;
+class Notification;
+class SVGElementInstance;
+class ExecutionContext;
+class ScriptProcessorNode;
+class SharedWorker;
+class SharedWorkerGlobalScope;
+class TextTrack;
+class TextTrackCue;
+class WebSocket;
+class Worker;
+class XMLHttpRequest;
+class XMLHttpRequestUpload;
+
+struct FiringEventIterator {
+ FiringEventIterator(const AtomicString& eventType, size_t& iterator, size_t& end)
+ : eventType(eventType)
+ , iterator(iterator)
+ , end(end)
+ {
+ }
+
+ const AtomicString& eventType;
+ size_t& iterator;
+ size_t& end;
+};
+typedef Vector<FiringEventIterator, 1> FiringEventIteratorVector;
+
+struct EventTargetData {
+ WTF_MAKE_NONCOPYABLE(EventTargetData); WTF_MAKE_FAST_ALLOCATED;
+public:
+ EventTargetData();
+ ~EventTargetData();
+
+ EventListenerMap eventListenerMap;
+ OwnPtr<FiringEventIteratorVector> firingEventIterators;
+};
+
+class EventTarget {
+public:
+ void ref() { refEventTarget(); }
+ void deref() { derefEventTarget(); }
+
+ virtual const AtomicString& interfaceName() const = 0;
+ virtual ExecutionContext* executionContext() const = 0;
+
+ virtual Node* toNode();
+ virtual DOMWindow* toDOMWindow();
+ virtual MessagePort* toMessagePort();
+
+ virtual bool addEventListener(const AtomicString& eventType, PassRefPtr<EventListener>, bool useCapture);
+ virtual bool removeEventListener(const AtomicString& eventType, EventListener*, bool useCapture);
+ virtual void removeAllEventListeners();
+ virtual bool dispatchEvent(PassRefPtr<Event>);
+ bool dispatchEvent(PassRefPtr<Event>, ExceptionState&); // DOM API
+ virtual void uncaughtExceptionInEventHandler();
+
+ // Used for legacy "onEvent" attribute APIs.
+ bool setAttributeEventListener(const AtomicString& eventType, PassRefPtr<EventListener>, DOMWrapperWorld* isolatedWorld = 0);
+ EventListener* getAttributeEventListener(const AtomicString& eventType, DOMWrapperWorld* isolatedWorld = 0);
+
+ bool hasEventListeners() const;
+ bool hasEventListeners(const AtomicString& eventType) const;
+ bool hasCapturingEventListeners(const AtomicString& eventType);
+ const EventListenerVector& getEventListeners(const AtomicString& eventType);
+
+ bool fireEventListeners(Event*);
+ bool isFiringEventListeners();
+
+protected:
+ virtual ~EventTarget();
+
+ // Subclasses should likely not override these themselves; instead, they should subclass EventTargetWithInlineData.
+ virtual EventTargetData* eventTargetData() = 0;
+ virtual EventTargetData& ensureEventTargetData() = 0;
+
+private:
+ // Subclasses should likely not override these themselves; instead, they should use the REFCOUNTED_EVENT_TARGET() macro.
+ virtual void refEventTarget() = 0;
+ virtual void derefEventTarget() = 0;
+
+ DOMWindow* executingWindow();
+ void fireEventListeners(Event*, EventTargetData*, EventListenerVector&);
+ void countLegacyEvents(const AtomicString& legacyTypeName, EventListenerVector*, EventListenerVector*);
+
+ bool clearAttributeEventListener(const AtomicString& eventType, DOMWrapperWorld* isolatedWorld);
+
+ friend class EventListenerIterator;
+};
+
+class EventTargetWithInlineData : public EventTarget {
+protected:
+ virtual EventTargetData* eventTargetData() OVERRIDE FINAL { return &m_eventTargetData; }
+ virtual EventTargetData& ensureEventTargetData() OVERRIDE FINAL { return m_eventTargetData; }
+private:
+ EventTargetData m_eventTargetData;
+};
+
+// FIXME: These macros should be split into separate DEFINE and DECLARE
+// macros to avoid causing so many header includes.
+#define DEFINE_ATTRIBUTE_EVENT_LISTENER(attribute) \
+ EventListener* on##attribute(DOMWrapperWorld* isolatedWorld) { return getAttributeEventListener(EventTypeNames::attribute, isolatedWorld); } \
+ void setOn##attribute(PassRefPtr<EventListener> listener, DOMWrapperWorld* isolatedWorld = 0) { setAttributeEventListener(EventTypeNames::attribute, listener, isolatedWorld); } \
+
+#define DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(attribute) \
+ static EventListener* on##attribute(EventTarget* eventTarget, DOMWrapperWorld* isolatedWorld) { return eventTarget->getAttributeEventListener(EventTypeNames::attribute, isolatedWorld); } \
+ static void setOn##attribute(EventTarget* eventTarget, PassRefPtr<EventListener> listener, DOMWrapperWorld* isolatedWorld = 0) { eventTarget->setAttributeEventListener(EventTypeNames::attribute, listener, isolatedWorld); } \
+
+#define DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(attribute) \
+ EventListener* on##attribute(DOMWrapperWorld* isolatedWorld) { return document().getWindowAttributeEventListener(EventTypeNames::attribute, isolatedWorld); } \
+ void setOn##attribute(PassRefPtr<EventListener> listener, DOMWrapperWorld* isolatedWorld) { document().setWindowAttributeEventListener(EventTypeNames::attribute, listener, isolatedWorld); } \
+
+#define DEFINE_STATIC_WINDOW_ATTRIBUTE_EVENT_LISTENER(attribute) \
+ static EventListener* on##attribute(EventTarget* eventTarget, DOMWrapperWorld* isolatedWorld) { \
+ if (Node* node = eventTarget->toNode()) \
+ return node->document().getWindowAttributeEventListener(EventTypeNames::attribute, isolatedWorld); \
+ ASSERT(eventTarget->toDOMWindow()); \
+ return eventTarget->getAttributeEventListener(EventTypeNames::attribute, isolatedWorld); \
+ } \
+ static void setOn##attribute(EventTarget* eventTarget, PassRefPtr<EventListener> listener, DOMWrapperWorld* isolatedWorld) { \
+ if (Node* node = eventTarget->toNode()) \
+ node->document().setWindowAttributeEventListener(EventTypeNames::attribute, listener, isolatedWorld); \
+ else { \
+ ASSERT(eventTarget->toDOMWindow()); \
+ eventTarget->setAttributeEventListener(EventTypeNames::attribute, listener, isolatedWorld); \
+ } \
+ }
+
+#define DEFINE_MAPPED_ATTRIBUTE_EVENT_LISTENER(attribute, eventName) \
+ EventListener* on##attribute(DOMWrapperWorld* isolatedWorld) { return getAttributeEventListener(EventTypeNames::eventName, isolatedWorld); } \
+ void setOn##attribute(PassRefPtr<EventListener> listener, DOMWrapperWorld* isolatedWorld) { setAttributeEventListener(EventTypeNames::eventName, listener, isolatedWorld); } \
+
+#define DECLARE_FORWARDING_ATTRIBUTE_EVENT_LISTENER(recipient, attribute) \
+ EventListener* on##attribute(DOMWrapperWorld* isolatedWorld); \
+ void setOn##attribute(PassRefPtr<EventListener> listener, DOMWrapperWorld* isolatedWorld);
+
+#define DEFINE_FORWARDING_ATTRIBUTE_EVENT_LISTENER(type, recipient, attribute) \
+ EventListener* type::on##attribute(DOMWrapperWorld* isolatedWorld) { return recipient ? recipient->getAttributeEventListener(EventTypeNames::attribute, isolatedWorld) : 0; } \
+ void type::setOn##attribute(PassRefPtr<EventListener> listener, DOMWrapperWorld* isolatedWorld) \
+ { \
+ if (recipient) \
+ recipient->setAttributeEventListener(EventTypeNames::attribute, listener, isolatedWorld); \
+ }
+
+inline bool EventTarget::isFiringEventListeners()
+{
+ EventTargetData* d = eventTargetData();
+ if (!d)
+ return false;
+ return d->firingEventIterators && !d->firingEventIterators->isEmpty();
+}
+
+inline bool EventTarget::hasEventListeners() const
+{
+ // FIXME: We should have a const version of eventTargetData.
+ if (const EventTargetData* d = const_cast<EventTarget*>(this)->eventTargetData())
+ return !d->eventListenerMap.isEmpty();
+ return false;
+}
+
+inline bool EventTarget::hasEventListeners(const AtomicString& eventType) const
+{
+ // FIXME: We should have const version of eventTargetData.
+ if (const EventTargetData* d = const_cast<EventTarget*>(this)->eventTargetData())
+ return d->eventListenerMap.contains(eventType);
+ return false;
+}
+
+inline bool EventTarget::hasCapturingEventListeners(const AtomicString& eventType)
+{
+ EventTargetData* d = eventTargetData();
+ if (!d)
+ return false;
+ return d->eventListenerMap.containsCapturing(eventType);
+}
+
+} // namespace WebCore
+
+#define DEFINE_EVENT_TARGET_REFCOUNTING(baseClass) \
+public: \
+ using baseClass::ref; \
+ using baseClass::deref; \
+private: \
+ virtual void refEventTarget() OVERRIDE FINAL { ref(); } \
+ virtual void derefEventTarget() OVERRIDE FINAL { deref(); } \
+ typedef int thisIsHereToForceASemiColonAfterThisEventTargetMacro
+
+// Use this macro if your EventTarget subclass is also a subclass of WTF::RefCounted.
+// A ref-counted class that uses a different method of refcounting should use DEFINE_EVENT_TARGET_REFCOUNTING directly.
+// Both of these macros are meant to be placed just before the "public:" section of the class declaration.
+#define REFCOUNTED_EVENT_TARGET(className) DEFINE_EVENT_TARGET_REFCOUNTING(RefCounted<className>)
+
+#endif // EventTarget_h
diff --git a/chromium/third_party/WebKit/Source/core/events/EventTarget.idl b/chromium/third_party/WebKit/Source/core/events/EventTarget.idl
new file mode 100644
index 00000000000..0cd1b1718f0
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/EventTarget.idl
@@ -0,0 +1,31 @@
+/*
+ * Copyright (C) 2006, 2007 Apple Inc. All rights reserved.
+ * Copyright (C) 2006 Samuel Weinig <sam.weinig@gmail.com>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+[
+ Custom=ToV8,
+] interface EventTarget {
+ void addEventListener(DOMString type,
+ EventListener listener,
+ optional boolean useCapture);
+ void removeEventListener(DOMString type,
+ EventListener listener,
+ optional boolean useCapture);
+ [RaisesException] boolean dispatchEvent(Event event);
+};
diff --git a/chromium/third_party/WebKit/Source/core/events/EventTargetFactory.in b/chromium/third_party/WebKit/Source/core/events/EventTargetFactory.in
new file mode 100644
index 00000000000..fcb0aff0a75
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/EventTargetFactory.in
@@ -0,0 +1,50 @@
+namespace="EventTarget"
+
+core/css/FontFaceSet
+core/dom/MessagePort
+core/dom/Node
+core/dom/WebKitNamedFlow ImplementedAs=NamedFlow
+core/fileapi/FileReader
+core/html/MediaController
+core/html/ime/InputMethodContext
+core/html/track/TextTrack
+core/html/track/TextTrackCue
+core/html/track/TextTrackList
+core/loader/appcache/ApplicationCache
+core/page/EventSource
+core/timing/Performance
+core/frame/Window ImplementedAs=DOMWindow
+core/svg/SVGElementInstance
+core/workers/DedicatedWorkerGlobalScope
+core/workers/SharedWorker
+core/workers/SharedWorkerGlobalScope
+core/workers/Worker
+core/xml/XMLHttpRequest
+core/xml/XMLHttpRequestUpload
+modules/encryptedmedia/MediaKeySession
+modules/filesystem/FileWriter
+modules/indexeddb/IDBDatabase
+modules/indexeddb/IDBOpenDBRequest
+modules/indexeddb/IDBRequest
+modules/indexeddb/IDBTransaction
+modules/mediasource/MediaSource
+modules/mediasource/SourceBuffer
+modules/mediasource/SourceBufferList
+modules/mediasource/WebKitMediaSource
+modules/mediasource/WebKitSourceBufferList
+modules/mediastream/MediaStream
+modules/mediastream/MediaStreamTrack
+modules/mediastream/RTCDTMFSender
+modules/mediastream/RTCDataChannel
+modules/mediastream/RTCPeerConnection
+modules/notifications/Notification
+modules/notifications/WebKitNotification Conditional=LEGACY_NOTIFICATIONS
+modules/serviceworkers/ServiceWorkerGlobalScope
+modules/speech/SpeechRecognition
+modules/speech/SpeechSynthesisUtterance
+modules/webaudio/AudioContext Conditional=WEB_AUDIO
+modules/webaudio/AudioNode Conditional=WEB_AUDIO
+modules/webmidi/MIDIAccess
+modules/webmidi/MIDIInput
+modules/webmidi/MIDIPort
+modules/websockets/WebSocket
diff --git a/chromium/third_party/WebKit/Source/core/events/EventTypeNames.in b/chromium/third_party/WebKit/Source/core/events/EventTypeNames.in
new file mode 100644
index 00000000000..b8148018635
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/EventTypeNames.in
@@ -0,0 +1,230 @@
+namespace="EventType"
+
+DOMActivate
+DOMCharacterDataModified
+DOMContentLoaded
+DOMFocusIn
+DOMFocusOut
+DOMNodeInserted
+DOMNodeInsertedIntoDocument
+DOMNodeRemoved
+DOMNodeRemovedFromDocument
+DOMSubtreeModified
+abort
+activate
+addsourcebuffer
+addstream
+addtrack
+animationend
+animationiteration
+animationstart
+audioend
+audioprocess
+audiostart
+autocomplete
+autocompleteerror
+beforecopy
+beforecut
+beforeload
+beforepaste
+beforeunload
+beginEvent
+blocked
+blur
+boundary
+cached
+cancel
+candidatewindowhide
+candidatewindowshow
+candidatewindowupdate
+canplay
+canplaythrough
+change
+chargingchange
+chargingtimechange
+checking
+click
+close
+complete
+compositionend
+compositionstart
+compositionupdate
+connect
+connecting
+contextmenu
+copy
+cuechange
+cut
+datachannel
+dblclick
+devicemotion
+deviceorientation
+dischargingtimechange
+disconnect
+display
+downloading
+drag
+dragend
+dragenter
+dragleave
+dragover
+dragstart
+drop
+durationchange
+emptied
+end
+ended
+endEvent
+enter
+error
+exit
+fetch
+focus
+focusin
+focusout
+gesturescrollend
+gesturescrollstart
+gesturescrollupdate
+gestureshowpress
+gesturetap
+gesturetapdown
+gesturetapunconfirmed
+hashchange
+icecandidate
+iceconnectionstatechange
+input
+install
+invalid
+keydown
+keypress
+keyup
+levelchange
+load
+loadeddata
+loadedmetadata
+loadend
+loading
+loadingdone
+loadingerror
+loadstart
+mark
+message
+midimessage
+mousedown
+mouseenter
+mouseleave
+mousemove
+mouseout
+mouseover
+mouseup
+mousewheel
+mute
+negotiationneeded
+nomatch
+noupdate
+obsolete
+offline
+online
+open
+orientationchange
+overflowchanged
+pagehide
+pageshow
+paste
+pause
+play
+playing
+popstate
+progress
+ratechange
+readystatechange
+removesourcebuffer
+removestream
+removetrack
+repeatEvent
+reset
+resize
+result
+resume
+scroll
+search
+securitypolicyviolation
+seeked
+seeking
+select
+selectionchange
+selectstart
+show
+signalingstatechange
+soundend
+soundstart
+sourceclose
+sourceended
+sourceopen
+speechend
+speechstart
+stalled
+start
+storage
+submit
+success
+suspend
+textInput
+timeout
+timeupdate
+tonechange
+touchcancel
+touchend
+touchmove
+touchstart
+transitionend
+unload
+unmute
+update
+updateend
+updateready
+updatestart
+upgradeneeded
+versionchange
+visibilitychange
+voiceschanged
+volumechange
+waiting
+webglcontextcreationerror
+webglcontextlost
+webglcontextrestored
+webkitAnimationEnd
+webkitAnimationIteration
+webkitAnimationStart
+webkitBeforeTextInserted
+webkitEditableContentChanged
+webkitTransitionEnd
+webkitaddsourcebuffer
+webkitdeviceproximity
+webkitfullscreenchange
+webkitfullscreenerror
+webkitkeyadded
+webkitkeyerror
+webkitkeymessage
+webkitneedkey
+webkitnetworkinfochange
+webkitpointerlockchange
+webkitpointerlockerror
+webkitprerenderdomcontentloaded
+webkitprerenderload
+webkitprerenderstart
+webkitprerenderstop
+webkitregionlayoutupdate
+webkitregionoversetchange
+webkitremovesourcebuffer
+webkitresourcetimingbufferfull
+webkitsourceclose
+webkitsourceended
+webkitsourceopen
+webkitspeechchange
+webkitvisibilitychange
+wheel
+write
+writeend
+writestart
+zoom
diff --git a/chromium/third_party/WebKit/Source/core/events/FocusEvent.cpp b/chromium/third_party/WebKit/Source/core/events/FocusEvent.cpp
new file mode 100644
index 00000000000..e201de0c419
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/FocusEvent.cpp
@@ -0,0 +1,134 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/events/FocusEvent.h"
+
+#include "core/events/Event.h"
+#include "core/events/EventDispatcher.h"
+#include "core/events/EventRetargeter.h"
+#include "core/events/ThreadLocalEventNames.h"
+
+namespace WebCore {
+
+FocusEventInit::FocusEventInit()
+ : relatedTarget(0)
+{
+}
+
+const AtomicString& FocusEvent::interfaceName() const
+{
+ return EventNames::FocusEvent;
+}
+
+bool FocusEvent::isFocusEvent() const
+{
+ return true;
+}
+
+FocusEvent::FocusEvent()
+{
+ ScriptWrappable::init(this);
+}
+
+FocusEvent::FocusEvent(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<AbstractView> view, int detail, EventTarget* relatedTarget)
+ : UIEvent(type, canBubble, cancelable, view, detail)
+ , m_relatedTarget(relatedTarget)
+{
+ ScriptWrappable::init(this);
+}
+
+FocusEvent::FocusEvent(const AtomicString& type, const FocusEventInit& initializer)
+ : UIEvent(type, initializer)
+ , m_relatedTarget(initializer.relatedTarget)
+{
+ ScriptWrappable::init(this);
+}
+
+PassRefPtr<FocusEventDispatchMediator> FocusEventDispatchMediator::create(PassRefPtr<FocusEvent> focusEvent)
+{
+ return adoptRef(new FocusEventDispatchMediator(focusEvent));
+}
+
+FocusEventDispatchMediator::FocusEventDispatchMediator(PassRefPtr<FocusEvent> focusEvent)
+ : EventDispatchMediator(focusEvent)
+{
+}
+
+bool FocusEventDispatchMediator::dispatchEvent(EventDispatcher* dispatcher) const
+{
+ EventRetargeter::adjustForFocusEvent(dispatcher->node(), *event());
+ return EventDispatchMediator::dispatchEvent(dispatcher);
+}
+
+PassRefPtr<BlurEventDispatchMediator> BlurEventDispatchMediator::create(PassRefPtr<FocusEvent> focusEvent)
+{
+ return adoptRef(new BlurEventDispatchMediator(focusEvent));
+}
+
+BlurEventDispatchMediator::BlurEventDispatchMediator(PassRefPtr<FocusEvent> focusEvent)
+ : EventDispatchMediator(focusEvent)
+{
+}
+
+bool BlurEventDispatchMediator::dispatchEvent(EventDispatcher* dispatcher) const
+{
+ EventRetargeter::adjustForFocusEvent(dispatcher->node(), *event());
+ return EventDispatchMediator::dispatchEvent(dispatcher);
+}
+
+PassRefPtr<FocusInEventDispatchMediator> FocusInEventDispatchMediator::create(PassRefPtr<FocusEvent> focusEvent)
+{
+ return adoptRef(new FocusInEventDispatchMediator(focusEvent));
+}
+
+FocusInEventDispatchMediator::FocusInEventDispatchMediator(PassRefPtr<FocusEvent> focusEvent)
+ : EventDispatchMediator(focusEvent)
+{
+}
+
+bool FocusInEventDispatchMediator::dispatchEvent(EventDispatcher* dispatcher) const
+{
+ EventRetargeter::adjustForFocusEvent(dispatcher->node(), *event());
+ return EventDispatchMediator::dispatchEvent(dispatcher);
+}
+
+PassRefPtr<FocusOutEventDispatchMediator> FocusOutEventDispatchMediator::create(PassRefPtr<FocusEvent> focusEvent)
+{
+ return adoptRef(new FocusOutEventDispatchMediator(focusEvent));
+}
+
+FocusOutEventDispatchMediator::FocusOutEventDispatchMediator(PassRefPtr<FocusEvent> focusEvent)
+ : EventDispatchMediator(focusEvent)
+{
+}
+
+bool FocusOutEventDispatchMediator::dispatchEvent(EventDispatcher* dispatcher) const
+{
+ EventRetargeter::adjustForFocusEvent(dispatcher->node(), *event());
+ return EventDispatchMediator::dispatchEvent(dispatcher);
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/events/FocusEvent.h b/chromium/third_party/WebKit/Source/core/events/FocusEvent.h
new file mode 100644
index 00000000000..20a9a28c0fe
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/FocusEvent.h
@@ -0,0 +1,114 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef FocusEvent_h
+#define FocusEvent_h
+
+#include "core/events/EventTarget.h"
+#include "core/events/UIEvent.h"
+
+namespace WebCore {
+
+class Node;
+
+struct FocusEventInit : public UIEventInit {
+ FocusEventInit();
+
+ RefPtr<EventTarget> relatedTarget;
+};
+
+class FocusEvent : public UIEvent {
+public:
+ static PassRefPtr<FocusEvent> create()
+ {
+ return adoptRef(new FocusEvent);
+ }
+
+ static PassRefPtr<FocusEvent> create(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<AbstractView> view, int detail, EventTarget* relatedTarget)
+ {
+ return adoptRef(new FocusEvent(type, canBubble, cancelable, view, detail, relatedTarget));
+ }
+
+ static PassRefPtr<FocusEvent> create(const AtomicString& type, const FocusEventInit& initializer)
+ {
+ return adoptRef(new FocusEvent(type, initializer));
+ }
+
+ EventTarget* relatedTarget() const { return m_relatedTarget.get(); }
+ EventTarget* relatedTarget(bool& isNull) const { isNull = !m_relatedTarget; return m_relatedTarget.get(); }
+ void setRelatedTarget(EventTarget* relatedTarget) { m_relatedTarget = relatedTarget; }
+
+ virtual const AtomicString& interfaceName() const;
+ virtual bool isFocusEvent() const;
+
+private:
+ FocusEvent();
+ FocusEvent(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<AbstractView>, int, EventTarget*);
+ FocusEvent(const AtomicString& type, const FocusEventInit&);
+
+ RefPtr<EventTarget> m_relatedTarget;
+};
+
+DEFINE_EVENT_TYPE_CASTS(FocusEvent);
+
+class FocusEventDispatchMediator : public EventDispatchMediator {
+public:
+ static PassRefPtr<FocusEventDispatchMediator> create(PassRefPtr<FocusEvent>);
+private:
+ explicit FocusEventDispatchMediator(PassRefPtr<FocusEvent>);
+ FocusEvent* event() const { return static_cast<FocusEvent*>(EventDispatchMediator::event()); }
+ virtual bool dispatchEvent(EventDispatcher*) const OVERRIDE;
+};
+
+class BlurEventDispatchMediator : public EventDispatchMediator {
+public:
+ static PassRefPtr<BlurEventDispatchMediator> create(PassRefPtr<FocusEvent>);
+private:
+ explicit BlurEventDispatchMediator(PassRefPtr<FocusEvent>);
+ FocusEvent* event() const { return static_cast<FocusEvent*>(EventDispatchMediator::event()); }
+ virtual bool dispatchEvent(EventDispatcher*) const OVERRIDE;
+};
+
+class FocusInEventDispatchMediator : public EventDispatchMediator {
+public:
+ static PassRefPtr<FocusInEventDispatchMediator> create(PassRefPtr<FocusEvent>);
+private:
+ explicit FocusInEventDispatchMediator(PassRefPtr<FocusEvent>);
+ FocusEvent* event() const { return static_cast<FocusEvent*>(EventDispatchMediator::event()); }
+ virtual bool dispatchEvent(EventDispatcher*) const OVERRIDE;
+};
+
+class FocusOutEventDispatchMediator : public EventDispatchMediator {
+public:
+ static PassRefPtr<FocusOutEventDispatchMediator> create(PassRefPtr<FocusEvent>);
+private:
+ explicit FocusOutEventDispatchMediator(PassRefPtr<FocusEvent>);
+ FocusEvent* event() const { return static_cast<FocusEvent*>(EventDispatchMediator::event()); }
+ virtual bool dispatchEvent(EventDispatcher*) const OVERRIDE;
+};
+
+} // namespace WebCore
+
+#endif // FocusEvent_h
diff --git a/chromium/third_party/WebKit/Source/core/events/FocusEvent.idl b/chromium/third_party/WebKit/Source/core/events/FocusEvent.idl
new file mode 100644
index 00000000000..0a189d3f05e
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/FocusEvent.idl
@@ -0,0 +1,30 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+[
+ EventConstructor,
+] interface FocusEvent : UIEvent {
+ [InitializedByEventConstructor] readonly attribute EventTarget? relatedTarget;
+};
diff --git a/chromium/third_party/WebKit/Source/core/events/GenericEventQueue.cpp b/chromium/third_party/WebKit/Source/core/events/GenericEventQueue.cpp
new file mode 100644
index 00000000000..b35f85c09f9
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/GenericEventQueue.cpp
@@ -0,0 +1,124 @@
+/*
+ * Copyright (C) 2012 Victor Carbune (victor@rosedu.org)
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+
+#include "core/events/GenericEventQueue.h"
+
+#include "core/events/Event.h"
+#include "platform/TraceEvent.h"
+
+namespace WebCore {
+
+PassOwnPtr<GenericEventQueue> GenericEventQueue::create(EventTarget* owner)
+{
+ return adoptPtr(new GenericEventQueue(owner));
+}
+
+GenericEventQueue::GenericEventQueue(EventTarget* owner)
+ : m_owner(owner)
+ , m_timer(this, &GenericEventQueue::timerFired)
+ , m_isClosed(false)
+{
+}
+
+GenericEventQueue::~GenericEventQueue()
+{
+}
+
+bool GenericEventQueue::enqueueEvent(PassRefPtr<Event> event)
+{
+ if (m_isClosed)
+ return false;
+
+ if (event->target() == m_owner)
+ event->setTarget(0);
+
+ TRACE_EVENT_ASYNC_BEGIN1("event", "GenericEventQueue:enqueueEvent", event.get(), "type", event->type().string().ascii());
+ m_pendingEvents.append(event);
+
+ if (!m_timer.isActive())
+ m_timer.startOneShot(0);
+
+ return true;
+}
+
+bool GenericEventQueue::cancelEvent(Event* event)
+{
+ bool found = m_pendingEvents.contains(event);
+
+ if (found) {
+ m_pendingEvents.remove(m_pendingEvents.find(event));
+ TRACE_EVENT_ASYNC_END2("event", "GenericEventQueue:enqueueEvent", event, "type", event->type().string().ascii(), "status", "cancelled");
+ }
+
+ if (m_pendingEvents.isEmpty())
+ m_timer.stop();
+
+ return found;
+}
+
+void GenericEventQueue::timerFired(Timer<GenericEventQueue>*)
+{
+ ASSERT(!m_timer.isActive());
+ ASSERT(!m_pendingEvents.isEmpty());
+
+ Vector<RefPtr<Event> > pendingEvents;
+ m_pendingEvents.swap(pendingEvents);
+
+ RefPtr<EventTarget> protect(m_owner);
+ for (size_t i = 0; i < pendingEvents.size(); ++i) {
+ Event* event = pendingEvents[i].get();
+ EventTarget* target = event->target() ? event->target() : m_owner;
+ CString type(event->type().string().ascii());
+ TRACE_EVENT_ASYNC_STEP_INTO1("event", "GenericEventQueue:enqueueEvent", event, "dispatch", "type", type);
+ target->dispatchEvent(pendingEvents[i].release());
+ TRACE_EVENT_ASYNC_END1("event", "GenericEventQueue:enqueueEvent", event, "type", type);
+ }
+}
+
+void GenericEventQueue::close()
+{
+ m_isClosed = true;
+ cancelAllEvents();
+}
+
+void GenericEventQueue::cancelAllEvents()
+{
+ m_timer.stop();
+
+ for (size_t i = 0; i < m_pendingEvents.size(); ++i) {
+ Event* event = m_pendingEvents[i].get();
+ TRACE_EVENT_ASYNC_END2("event", "GenericEventQueue:enqueueEvent", event, "type", event->type().string().ascii(), "status", "cancelled");
+ }
+ m_pendingEvents.clear();
+}
+
+bool GenericEventQueue::hasPendingEvents() const
+{
+ return m_pendingEvents.size();
+}
+
+}
diff --git a/chromium/third_party/WebKit/Source/core/events/GenericEventQueue.h b/chromium/third_party/WebKit/Source/core/events/GenericEventQueue.h
new file mode 100644
index 00000000000..ab80f89a8ff
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/GenericEventQueue.h
@@ -0,0 +1,65 @@
+/*
+ * Copyright (C) 2012 Victor Carbune (victor@rosedu.org)
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef GenericEventQueue_h
+#define GenericEventQueue_h
+
+#include "core/events/EventQueue.h"
+#include "core/events/EventTarget.h"
+#include "platform/Timer.h"
+#include "wtf/PassOwnPtr.h"
+#include "wtf/RefPtr.h"
+#include "wtf/Vector.h"
+
+namespace WebCore {
+
+class GenericEventQueue : public EventQueue {
+ WTF_MAKE_FAST_ALLOCATED;
+public:
+ explicit GenericEventQueue(EventTarget*);
+ static PassOwnPtr<GenericEventQueue> create(EventTarget*);
+ virtual ~GenericEventQueue();
+
+ // EventQueue
+ virtual bool enqueueEvent(PassRefPtr<Event>) OVERRIDE;
+ virtual bool cancelEvent(Event*) OVERRIDE;
+ virtual void close() OVERRIDE;
+
+ void cancelAllEvents();
+ bool hasPendingEvents() const;
+
+private:
+ void timerFired(Timer<GenericEventQueue>*);
+
+ EventTarget* m_owner;
+ Vector<RefPtr<Event> > m_pendingEvents;
+ Timer<GenericEventQueue> m_timer;
+
+ bool m_isClosed;
+};
+
+}
+
+#endif
diff --git a/chromium/third_party/WebKit/Source/core/events/GestureEvent.cpp b/chromium/third_party/WebKit/Source/core/events/GestureEvent.cpp
new file mode 100644
index 00000000000..13d5f6f2a01
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/GestureEvent.cpp
@@ -0,0 +1,137 @@
+/*
+ * Copyright (C) 2012 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/dom/Element.h"
+#include "core/events/GestureEvent.h"
+#include "wtf/text/AtomicString.h"
+
+namespace WebCore {
+
+PassRefPtr<GestureEvent> GestureEvent::create()
+{
+ return adoptRef(new GestureEvent);
+}
+
+PassRefPtr<GestureEvent> GestureEvent::create(PassRefPtr<AbstractView> view, const PlatformGestureEvent& event)
+{
+ AtomicString eventType;
+ float deltaX = 0;
+ float deltaY = 0;
+ switch (event.type()) {
+ case PlatformEvent::GestureScrollBegin:
+ eventType = EventTypeNames::gesturescrollstart; break;
+ case PlatformEvent::GestureScrollEnd:
+ eventType = EventTypeNames::gesturescrollend; break;
+ case PlatformEvent::GestureScrollUpdate:
+ case PlatformEvent::GestureScrollUpdateWithoutPropagation:
+ // Only deltaX/Y are used when converting this
+ // back to a PlatformGestureEvent.
+ eventType = EventTypeNames::gesturescrollupdate;
+ deltaX = event.deltaX();
+ deltaY = event.deltaY();
+ break;
+ case PlatformEvent::GestureTap:
+ eventType = EventTypeNames::gesturetap; break;
+ case PlatformEvent::GestureTapUnconfirmed:
+ eventType = EventTypeNames::gesturetapunconfirmed; break;
+ case PlatformEvent::GestureTapDown:
+ eventType = EventTypeNames::gesturetapdown; break;
+ case PlatformEvent::GestureShowPress:
+ eventType = EventTypeNames::gestureshowpress; break;
+ case PlatformEvent::GestureTwoFingerTap:
+ case PlatformEvent::GestureLongPress:
+ case PlatformEvent::GesturePinchBegin:
+ case PlatformEvent::GesturePinchEnd:
+ case PlatformEvent::GesturePinchUpdate:
+ case PlatformEvent::GestureTapDownCancel:
+ default:
+ return 0;
+ }
+ return adoptRef(new GestureEvent(eventType, view, event.globalPosition().x(), event.globalPosition().y(), event.position().x(), event.position().y(), event.ctrlKey(), event.altKey(), event.shiftKey(), event.metaKey(), deltaX, deltaY));
+}
+
+void GestureEvent::initGestureEvent(const AtomicString& type, PassRefPtr<AbstractView> view, int screenX, int screenY, int clientX, int clientY, bool ctrlKey, bool altKey, bool shiftKey, bool metaKey, float deltaX, float deltaY)
+{
+ if (dispatched())
+ return;
+
+ initUIEvent(type, true, true, view, 0);
+ m_screenLocation = IntPoint(screenX, screenY);
+ m_ctrlKey = ctrlKey;
+ m_altKey = altKey;
+ m_shiftKey = shiftKey;
+ m_metaKey = metaKey;
+
+ m_deltaX = deltaX;
+ m_deltaY = deltaY;
+
+ initCoordinates(IntPoint(clientX, clientY));
+}
+
+const AtomicString& GestureEvent::interfaceName() const
+{
+ // FIXME: when a GestureEvent.idl interface is defined, return the string "GestureEvent".
+ // Until that happens, do not advertise an interface that does not exist, since it will
+ // trip up the bindings integrity checks.
+ return UIEvent::interfaceName();
+}
+
+bool GestureEvent::isGestureEvent() const
+{
+ return true;
+}
+
+GestureEvent::GestureEvent()
+ : m_deltaX(0)
+ , m_deltaY(0)
+{
+}
+
+GestureEvent::GestureEvent(const AtomicString& type, PassRefPtr<AbstractView> view, int screenX, int screenY, int clientX, int clientY, bool ctrlKey, bool altKey, bool shiftKey, bool metaKey, float deltaX, float deltaY)
+ : MouseRelatedEvent(type, true, true, view, 0, IntPoint(screenX, screenY), IntPoint(clientX, clientY), IntPoint(0, 0), ctrlKey, altKey, shiftKey, metaKey)
+ , m_deltaX(deltaX)
+ , m_deltaY(deltaY)
+{
+}
+
+GestureEventDispatchMediator::GestureEventDispatchMediator(PassRefPtr<GestureEvent> gestureEvent)
+ : EventDispatchMediator(gestureEvent)
+{
+}
+
+GestureEvent* GestureEventDispatchMediator::event() const
+{
+ return toGestureEvent(EventDispatchMediator::event());
+}
+
+bool GestureEventDispatchMediator::dispatchEvent(EventDispatcher* dispatcher) const
+{
+ dispatcher->dispatch();
+ ASSERT(!event()->defaultPrevented());
+ return event()->defaultHandled() || event()->defaultPrevented();
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/events/GestureEvent.h b/chromium/third_party/WebKit/Source/core/events/GestureEvent.h
new file mode 100644
index 00000000000..fe982006c92
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/GestureEvent.h
@@ -0,0 +1,78 @@
+/*
+ * Copyright (C) 2012 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef GestureEvent_h
+#define GestureEvent_h
+
+#include "core/events/EventDispatcher.h"
+#include "core/events/MouseRelatedEvent.h"
+#include "platform/PlatformGestureEvent.h"
+
+namespace WebCore {
+
+class GestureEvent : public MouseRelatedEvent {
+public:
+ virtual ~GestureEvent() { }
+
+ static PassRefPtr<GestureEvent> create();
+ static PassRefPtr<GestureEvent> create(PassRefPtr<AbstractView>, const PlatformGestureEvent&);
+
+ void initGestureEvent(const AtomicString& type, PassRefPtr<AbstractView>, int screenX, int screenY, int clientX, int clientY, bool ctrlKey, bool altKey, bool shiftKey, bool metaKey, float deltaX, float deltaY);
+
+ virtual bool isGestureEvent() const OVERRIDE;
+
+ virtual const AtomicString& interfaceName() const;
+
+ float deltaX() const { return m_deltaX; }
+ float deltaY() const { return m_deltaY; }
+
+private:
+ GestureEvent();
+ GestureEvent(const AtomicString& type, PassRefPtr<AbstractView>, int screenX, int screenY, int clientX, int clientY, bool ctrlKey, bool altKey, bool shiftKey, bool metaKey, float deltaX, float deltaY);
+
+ float m_deltaX;
+ float m_deltaY;
+};
+
+class GestureEventDispatchMediator : public EventDispatchMediator {
+public:
+ static PassRefPtr<GestureEventDispatchMediator> create(PassRefPtr<GestureEvent> gestureEvent)
+ {
+ return adoptRef(new GestureEventDispatchMediator(gestureEvent));
+ }
+
+private:
+ explicit GestureEventDispatchMediator(PassRefPtr<GestureEvent>);
+
+ GestureEvent* event() const;
+
+ virtual bool dispatchEvent(EventDispatcher*) const OVERRIDE;
+};
+
+DEFINE_EVENT_TYPE_CASTS(GestureEvent);
+
+} // namespace WebCore
+
+#endif // GestureEvent_h
diff --git a/chromium/third_party/WebKit/Source/core/events/HashChangeEvent.h b/chromium/third_party/WebKit/Source/core/events/HashChangeEvent.h
new file mode 100644
index 00000000000..e652df8dca6
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/HashChangeEvent.h
@@ -0,0 +1,99 @@
+/*
+ * Copyright (C) 2010 Apple Inc. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ */
+
+#ifndef HashChangeEvent_h
+#define HashChangeEvent_h
+
+#include "core/events/Event.h"
+#include "core/events/ThreadLocalEventNames.h"
+
+namespace WebCore {
+
+struct HashChangeEventInit : public EventInit {
+ HashChangeEventInit()
+ {
+ };
+
+ String oldURL;
+ String newURL;
+};
+
+class HashChangeEvent : public Event {
+public:
+ static PassRefPtr<HashChangeEvent> create()
+ {
+ return adoptRef(new HashChangeEvent);
+ }
+
+ static PassRefPtr<HashChangeEvent> create(const String& oldURL, const String& newURL)
+ {
+ return adoptRef(new HashChangeEvent(oldURL, newURL));
+ }
+
+ static PassRefPtr<HashChangeEvent> create(const AtomicString& type, const HashChangeEventInit& initializer)
+ {
+ return adoptRef(new HashChangeEvent(type, initializer));
+ }
+
+ void initHashChangeEvent(const AtomicString& eventType, bool canBubble, bool cancelable, const String& oldURL, const String& newURL)
+ {
+ if (dispatched())
+ return;
+
+ initEvent(eventType, canBubble, cancelable);
+
+ m_oldURL = oldURL;
+ m_newURL = newURL;
+ }
+
+ const String& oldURL() const { return m_oldURL; }
+ const String& newURL() const { return m_newURL; }
+
+ virtual const AtomicString& interfaceName() const { return EventNames::HashChangeEvent; }
+
+private:
+ HashChangeEvent()
+ {
+ ScriptWrappable::init(this);
+ }
+
+ HashChangeEvent(const String& oldURL, const String& newURL)
+ : Event(EventTypeNames::hashchange, false, false)
+ , m_oldURL(oldURL)
+ , m_newURL(newURL)
+ {
+ ScriptWrappable::init(this);
+ }
+
+ HashChangeEvent(const AtomicString& type, const HashChangeEventInit& initializer)
+ : Event(type, initializer)
+ , m_oldURL(initializer.oldURL)
+ , m_newURL(initializer.newURL)
+ {
+ ScriptWrappable::init(this);
+ }
+
+ String m_oldURL;
+ String m_newURL;
+};
+
+} // namespace WebCore
+
+#endif // HashChangeEvent_h
diff --git a/chromium/third_party/WebKit/Source/core/events/HashChangeEvent.idl b/chromium/third_party/WebKit/Source/core/events/HashChangeEvent.idl
new file mode 100644
index 00000000000..e5101b8d991
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/HashChangeEvent.idl
@@ -0,0 +1,32 @@
+/*
+ * Copyright (C) 2010 Apple Inc. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+// Introduced in http://www.whatwg.org/specs/web-apps/current-work/multiframe/History.html#event-hashchange
+[
+ EventConstructor,
+] interface HashChangeEvent : Event {
+ void initHashChangeEvent([Default=Undefined] optional DOMString type,
+ [Default=Undefined] optional boolean canBubble,
+ [Default=Undefined] optional boolean cancelable,
+ [Default=Undefined] optional DOMString oldURL,
+ [Default=Undefined] optional DOMString newURL);
+ [InitializedByEventConstructor] readonly attribute DOMString oldURL;
+ [InitializedByEventConstructor] readonly attribute DOMString newURL;
+};
+
diff --git a/chromium/third_party/WebKit/Source/core/events/KeyboardEvent.cpp b/chromium/third_party/WebKit/Source/core/events/KeyboardEvent.cpp
new file mode 100644
index 00000000000..c03712edadd
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/KeyboardEvent.cpp
@@ -0,0 +1,245 @@
+/**
+ * Copyright (C) 2001 Peter Kelly (pmk@post.com)
+ * Copyright (C) 2001 Tobias Anton (anton@stud.fbi.fh-darmstadt.de)
+ * Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
+ * Copyright (C) 2003, 2005, 2006, 2007 Apple Inc. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#include "config.h"
+#include "core/events/KeyboardEvent.h"
+
+#include "core/events/ThreadLocalEventNames.h"
+#include "platform/PlatformKeyboardEvent.h"
+#include "platform/WindowsKeyboardCodes.h"
+
+namespace WebCore {
+
+static inline const AtomicString& eventTypeForKeyboardEventType(PlatformEvent::Type type)
+{
+ switch (type) {
+ case PlatformEvent::KeyUp:
+ return EventTypeNames::keyup;
+ case PlatformEvent::RawKeyDown:
+ return EventTypeNames::keydown;
+ case PlatformEvent::Char:
+ return EventTypeNames::keypress;
+ case PlatformEvent::KeyDown:
+ // The caller should disambiguate the combined event into RawKeyDown or Char events.
+ break;
+ default:
+ break;
+ }
+ ASSERT_NOT_REACHED();
+ return EventTypeNames::keydown;
+}
+
+static inline int windowsVirtualKeyCodeWithoutLocation(int keycode)
+{
+ switch (keycode) {
+ case VK_LCONTROL:
+ case VK_RCONTROL:
+ return VK_CONTROL;
+ case VK_LSHIFT:
+ case VK_RSHIFT:
+ return VK_SHIFT;
+ case VK_LMENU:
+ case VK_RMENU:
+ return VK_MENU;
+ default:
+ return keycode;
+ }
+}
+
+static inline KeyboardEvent::KeyLocationCode keyLocationCode(const PlatformKeyboardEvent& key)
+{
+ if (key.isKeypad())
+ return KeyboardEvent::DOM_KEY_LOCATION_NUMPAD;
+
+ switch (key.windowsVirtualKeyCode()) {
+ case VK_LCONTROL:
+ case VK_LSHIFT:
+ case VK_LMENU:
+ case VK_LWIN:
+ return KeyboardEvent::DOM_KEY_LOCATION_LEFT;
+ case VK_RCONTROL:
+ case VK_RSHIFT:
+ case VK_RMENU:
+ case VK_RWIN:
+ return KeyboardEvent::DOM_KEY_LOCATION_RIGHT;
+ default:
+ return KeyboardEvent::DOM_KEY_LOCATION_STANDARD;
+ }
+}
+
+KeyboardEventInit::KeyboardEventInit()
+ : location(0)
+ , ctrlKey(false)
+ , altKey(false)
+ , shiftKey(false)
+ , metaKey(false)
+ , repeat(false)
+{
+}
+
+KeyboardEvent::KeyboardEvent()
+ : m_location(DOM_KEY_LOCATION_STANDARD)
+ , m_altGraphKey(false)
+ , m_isAutoRepeat(false)
+{
+ ScriptWrappable::init(this);
+}
+
+KeyboardEvent::KeyboardEvent(const PlatformKeyboardEvent& key, AbstractView* view)
+ : UIEventWithKeyState(eventTypeForKeyboardEventType(key.type()),
+ true, true, view, 0, key.ctrlKey(), key.altKey(), key.shiftKey(), key.metaKey())
+ , m_keyEvent(adoptPtr(new PlatformKeyboardEvent(key)))
+ , m_keyIdentifier(key.keyIdentifier())
+ , m_location(keyLocationCode(key))
+ , m_altGraphKey(false)
+ , m_isAutoRepeat(key.isAutoRepeat())
+{
+ ScriptWrappable::init(this);
+}
+
+KeyboardEvent::KeyboardEvent(const AtomicString& eventType, const KeyboardEventInit& initializer)
+ : UIEventWithKeyState(eventType, initializer.bubbles, initializer.cancelable, initializer.view, initializer.detail, initializer.ctrlKey, initializer.altKey, initializer.shiftKey, initializer.metaKey)
+ , m_keyIdentifier(initializer.keyIdentifier)
+ , m_location(initializer.location)
+ , m_altGraphKey(false)
+ , m_isAutoRepeat(initializer.repeat)
+{
+ ScriptWrappable::init(this);
+}
+
+KeyboardEvent::KeyboardEvent(const AtomicString& eventType, bool canBubble, bool cancelable, AbstractView *view,
+ const String &keyIdentifier, unsigned location,
+ bool ctrlKey, bool altKey, bool shiftKey, bool metaKey, bool altGraphKey)
+ : UIEventWithKeyState(eventType, canBubble, cancelable, view, 0, ctrlKey, altKey, shiftKey, metaKey)
+ , m_keyIdentifier(keyIdentifier)
+ , m_location(location)
+ , m_altGraphKey(altGraphKey)
+ , m_isAutoRepeat(false)
+{
+ ScriptWrappable::init(this);
+}
+
+KeyboardEvent::~KeyboardEvent()
+{
+}
+
+void KeyboardEvent::initKeyboardEvent(const AtomicString& type, bool canBubble, bool cancelable, AbstractView* view,
+ const String &keyIdentifier, unsigned location,
+ bool ctrlKey, bool altKey, bool shiftKey, bool metaKey, bool altGraphKey)
+{
+ if (dispatched())
+ return;
+
+ initUIEvent(type, canBubble, cancelable, view, 0);
+
+ m_keyIdentifier = keyIdentifier;
+ m_location = location;
+ m_ctrlKey = ctrlKey;
+ m_shiftKey = shiftKey;
+ m_altKey = altKey;
+ m_metaKey = metaKey;
+ m_altGraphKey = altGraphKey;
+}
+
+bool KeyboardEvent::getModifierState(const String& keyIdentifier) const
+{
+ // FIXME: The following keyIdentifiers are not supported yet (crbug.com/265458):
+ // "AltGraph", "CapsLock", "Fn", "NumLock", "ScrollLock", "SymbolLock", "OS".
+ if (keyIdentifier == "Control")
+ return ctrlKey();
+ if (keyIdentifier == "Shift")
+ return shiftKey();
+ if (keyIdentifier == "Alt")
+ return altKey();
+ if (keyIdentifier == "Meta")
+ return metaKey();
+ return false;
+}
+
+int KeyboardEvent::keyCode() const
+{
+ // IE: virtual key code for keyup/keydown, character code for keypress
+ // Firefox: virtual key code for keyup/keydown, zero for keypress
+ // We match IE.
+ if (!m_keyEvent)
+ return 0;
+ if (type() == EventTypeNames::keydown || type() == EventTypeNames::keyup)
+ return windowsVirtualKeyCodeWithoutLocation(m_keyEvent->windowsVirtualKeyCode());
+
+ return charCode();
+}
+
+int KeyboardEvent::charCode() const
+{
+ // IE: not supported
+ // Firefox: 0 for keydown/keyup events, character code for keypress
+ // We match Firefox
+
+ if (!m_keyEvent || (type() != EventTypeNames::keypress))
+ return 0;
+ String text = m_keyEvent->text();
+ return static_cast<int>(text.characterStartingAt(0));
+}
+
+const AtomicString& KeyboardEvent::interfaceName() const
+{
+ return EventNames::KeyboardEvent;
+}
+
+bool KeyboardEvent::isKeyboardEvent() const
+{
+ return true;
+}
+
+int KeyboardEvent::which() const
+{
+ // Netscape's "which" returns a virtual key code for keydown and keyup, and a character code for keypress.
+ // That's exactly what IE's "keyCode" returns. So they are the same for keyboard events.
+ return keyCode();
+}
+
+KeyboardEvent* findKeyboardEvent(Event* event)
+{
+ for (Event* e = event; e; e = e->underlyingEvent()) {
+ if (e->isKeyboardEvent())
+ return toKeyboardEvent(e);
+ }
+ return 0;
+}
+
+PassRefPtr<KeyboardEventDispatchMediator> KeyboardEventDispatchMediator::create(PassRefPtr<KeyboardEvent> event)
+{
+ return adoptRef(new KeyboardEventDispatchMediator(event));
+}
+
+KeyboardEventDispatchMediator::KeyboardEventDispatchMediator(PassRefPtr<KeyboardEvent> event)
+ : EventDispatchMediator(event)
+{
+}
+
+bool KeyboardEventDispatchMediator::dispatchEvent(EventDispatcher* dispatcher) const
+{
+ // Make sure not to return true if we already took default action while handling the event.
+ return EventDispatchMediator::dispatchEvent(dispatcher) && !event()->defaultHandled();
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/events/KeyboardEvent.h b/chromium/third_party/WebKit/Source/core/events/KeyboardEvent.h
new file mode 100644
index 00000000000..e4d1e9e6462
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/KeyboardEvent.h
@@ -0,0 +1,132 @@
+/*
+ * Copyright (C) 2001 Peter Kelly (pmk@post.com)
+ * Copyright (C) 2001 Tobias Anton (anton@stud.fbi.fh-darmstadt.de)
+ * Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
+ * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ */
+
+#ifndef KeyboardEvent_h
+#define KeyboardEvent_h
+
+#include "core/events/EventDispatchMediator.h"
+#include "core/events/UIEventWithKeyState.h"
+
+namespace WebCore {
+
+class EventDispatcher;
+class Node;
+class PlatformKeyboardEvent;
+
+struct KeyboardEventInit : public UIEventInit {
+ KeyboardEventInit();
+
+ String keyIdentifier;
+ unsigned location;
+ bool ctrlKey;
+ bool altKey;
+ bool shiftKey;
+ bool metaKey;
+ bool repeat;
+};
+
+class KeyboardEvent : public UIEventWithKeyState {
+public:
+ enum KeyLocationCode {
+ DOM_KEY_LOCATION_STANDARD = 0x00,
+ DOM_KEY_LOCATION_LEFT = 0x01,
+ DOM_KEY_LOCATION_RIGHT = 0x02,
+ DOM_KEY_LOCATION_NUMPAD = 0x03
+ };
+
+ static PassRefPtr<KeyboardEvent> create()
+ {
+ return adoptRef(new KeyboardEvent);
+ }
+
+ static PassRefPtr<KeyboardEvent> create(const PlatformKeyboardEvent& platformEvent, AbstractView* view)
+ {
+ return adoptRef(new KeyboardEvent(platformEvent, view));
+ }
+
+ static PassRefPtr<KeyboardEvent> create(const AtomicString& type, const KeyboardEventInit& initializer)
+ {
+ return adoptRef(new KeyboardEvent(type, initializer));
+ }
+
+ static PassRefPtr<KeyboardEvent> create(const AtomicString& type, bool canBubble, bool cancelable, AbstractView* view,
+ const String& keyIdentifier, unsigned location,
+ bool ctrlKey, bool altKey, bool shiftKey, bool metaKey, bool altGraphKey)
+ {
+ return adoptRef(new KeyboardEvent(type, canBubble, cancelable, view, keyIdentifier, location,
+ ctrlKey, altKey, shiftKey, metaKey, altGraphKey));
+ }
+
+ virtual ~KeyboardEvent();
+
+ void initKeyboardEvent(const AtomicString& type, bool canBubble, bool cancelable, AbstractView*,
+ const String& keyIdentifier, unsigned location,
+ bool ctrlKey, bool altKey, bool shiftKey, bool metaKey, bool altGraphKey = false);
+
+ const String& keyIdentifier() const { return m_keyIdentifier; }
+ unsigned location() const { return m_location; }
+
+ bool getModifierState(const String& keyIdentifier) const;
+
+ bool altGraphKey() const { return m_altGraphKey; }
+
+ const PlatformKeyboardEvent* keyEvent() const { return m_keyEvent.get(); }
+
+ int keyCode() const; // key code for keydown and keyup, character for keypress
+ int charCode() const; // character code for keypress, 0 for keydown and keyup
+ bool repeat() const { return m_isAutoRepeat; }
+
+ virtual const AtomicString& interfaceName() const;
+ virtual bool isKeyboardEvent() const;
+ virtual int which() const;
+
+private:
+ KeyboardEvent();
+ KeyboardEvent(const PlatformKeyboardEvent&, AbstractView*);
+ KeyboardEvent(const AtomicString&, const KeyboardEventInit&);
+ KeyboardEvent(const AtomicString& type, bool canBubble, bool cancelable, AbstractView*,
+ const String& keyIdentifier, unsigned location,
+ bool ctrlKey, bool altKey, bool shiftKey, bool metaKey, bool altGraphKey);
+
+ OwnPtr<PlatformKeyboardEvent> m_keyEvent;
+ String m_keyIdentifier;
+ unsigned m_location;
+ bool m_altGraphKey : 1;
+ bool m_isAutoRepeat : 1;
+};
+
+KeyboardEvent* findKeyboardEvent(Event*);
+
+class KeyboardEventDispatchMediator : public EventDispatchMediator {
+public:
+ static PassRefPtr<KeyboardEventDispatchMediator> create(PassRefPtr<KeyboardEvent>);
+private:
+ explicit KeyboardEventDispatchMediator(PassRefPtr<KeyboardEvent>);
+ virtual bool dispatchEvent(EventDispatcher*) const OVERRIDE;
+};
+
+DEFINE_EVENT_TYPE_CASTS(KeyboardEvent);
+
+} // namespace WebCore
+
+#endif // KeyboardEvent_h
diff --git a/chromium/third_party/WebKit/Source/core/events/KeyboardEvent.idl b/chromium/third_party/WebKit/Source/core/events/KeyboardEvent.idl
new file mode 100644
index 00000000000..9a16319a51c
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/KeyboardEvent.idl
@@ -0,0 +1,54 @@
+/*
+ * Copyright (C) 2006 Apple Computer, Inc.
+ * Copyright (C) 2006 Samuel Weinig <sam.weinig@gmail.com>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+[
+ EventConstructor,
+] interface KeyboardEvent : UIEvent {
+ const unsigned long DOM_KEY_LOCATION_STANDARD = 0x00;
+ const unsigned long DOM_KEY_LOCATION_LEFT = 0x01;
+ const unsigned long DOM_KEY_LOCATION_RIGHT = 0x02;
+ const unsigned long DOM_KEY_LOCATION_NUMPAD = 0x03;
+
+ [InitializedByEventConstructor] readonly attribute DOMString keyIdentifier;
+ [InitializedByEventConstructor] readonly attribute unsigned long location;
+ [ImplementedAs=location, DeprecateAs=KeyboardEventKeyLocation, InitializedByEventConstructor] readonly attribute unsigned long keyLocation; // Deprecated.
+ [InitializedByEventConstructor] readonly attribute boolean ctrlKey;
+ [InitializedByEventConstructor] readonly attribute boolean shiftKey;
+ [InitializedByEventConstructor] readonly attribute boolean altKey;
+ [InitializedByEventConstructor] readonly attribute boolean metaKey;
+ [InitializedByEventConstructor] readonly attribute boolean repeat;
+ readonly attribute boolean altGraphKey;
+
+ boolean getModifierState(DOMString keyArgument);
+
+ // FIXME: this does not match the version in the DOM spec.
+ void initKeyboardEvent([Default=Undefined] optional DOMString type,
+ [Default=Undefined] optional boolean canBubble,
+ [Default=Undefined] optional boolean cancelable,
+ [Default=Undefined] optional Window view,
+ [Default=Undefined] optional DOMString keyIdentifier,
+ [Default=Undefined] optional unsigned long location,
+ [Default=Undefined] optional boolean ctrlKey,
+ [Default=Undefined] optional boolean altKey,
+ [Default=Undefined] optional boolean shiftKey,
+ [Default=Undefined] optional boolean metaKey,
+ [Default=Undefined] optional boolean altGraphKey);
+};
+
diff --git a/chromium/third_party/WebKit/Source/core/events/MessageEvent.cpp b/chromium/third_party/WebKit/Source/core/events/MessageEvent.cpp
new file mode 100644
index 00000000000..883b1f969e5
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/MessageEvent.cpp
@@ -0,0 +1,188 @@
+/*
+ * Copyright (C) 2007 Henry Mason (hmason@mac.com)
+ * Copyright (C) 2003, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "config.h"
+#include "core/events/MessageEvent.h"
+
+#include "bindings/v8/ExceptionMessages.h"
+#include "bindings/v8/ExceptionState.h"
+#include "core/events/ThreadLocalEventNames.h"
+
+namespace WebCore {
+
+static inline bool isValidSource(EventTarget* source)
+{
+ return !source || source->toDOMWindow() || source->toMessagePort();
+}
+
+MessageEventInit::MessageEventInit()
+{
+}
+
+MessageEvent::MessageEvent()
+ : m_dataType(DataTypeScriptValue)
+{
+ ScriptWrappable::init(this);
+}
+
+MessageEvent::MessageEvent(const AtomicString& type, const MessageEventInit& initializer)
+ : Event(type, initializer)
+ , m_dataType(DataTypeScriptValue)
+ , m_origin(initializer.origin)
+ , m_lastEventId(initializer.lastEventId)
+ , m_source(isValidSource(initializer.source.get()) ? initializer.source : 0)
+ , m_ports(adoptPtr(new MessagePortArray(initializer.ports)))
+{
+ ScriptWrappable::init(this);
+ ASSERT(isValidSource(m_source.get()));
+}
+
+MessageEvent::MessageEvent(const String& origin, const String& lastEventId, PassRefPtr<EventTarget> source, PassOwnPtr<MessagePortArray> ports)
+ : Event(EventTypeNames::message, false, false)
+ , m_dataType(DataTypeScriptValue)
+ , m_origin(origin)
+ , m_lastEventId(lastEventId)
+ , m_source(source)
+ , m_ports(ports)
+{
+ ScriptWrappable::init(this);
+ ASSERT(isValidSource(m_source.get()));
+}
+
+MessageEvent::MessageEvent(PassRefPtr<SerializedScriptValue> data, const String& origin, const String& lastEventId, PassRefPtr<EventTarget> source, PassOwnPtr<MessagePortArray> ports)
+ : Event(EventTypeNames::message, false, false)
+ , m_dataType(DataTypeSerializedScriptValue)
+ , m_dataAsSerializedScriptValue(data)
+ , m_origin(origin)
+ , m_lastEventId(lastEventId)
+ , m_source(source)
+ , m_ports(ports)
+{
+ ScriptWrappable::init(this);
+ if (m_dataAsSerializedScriptValue)
+ m_dataAsSerializedScriptValue->registerMemoryAllocatedWithCurrentScriptContext();
+ ASSERT(isValidSource(m_source.get()));
+}
+
+MessageEvent::MessageEvent(PassRefPtr<SerializedScriptValue> data, const String& origin, const String& lastEventId, PassRefPtr<EventTarget> source, PassOwnPtr<MessagePortChannelArray> channels)
+ : Event(EventTypeNames::message, false, false)
+ , m_dataType(DataTypeSerializedScriptValue)
+ , m_dataAsSerializedScriptValue(data)
+ , m_origin(origin)
+ , m_lastEventId(lastEventId)
+ , m_source(source)
+ , m_channels(channels)
+{
+ ScriptWrappable::init(this);
+ if (m_dataAsSerializedScriptValue)
+ m_dataAsSerializedScriptValue->registerMemoryAllocatedWithCurrentScriptContext();
+ ASSERT(isValidSource(m_source.get()));
+}
+
+MessageEvent::MessageEvent(const String& data, const String& origin)
+ : Event(EventTypeNames::message, false, false)
+ , m_dataType(DataTypeString)
+ , m_dataAsString(data)
+ , m_origin(origin)
+{
+ ScriptWrappable::init(this);
+}
+
+MessageEvent::MessageEvent(PassRefPtr<Blob> data, const String& origin)
+ : Event(EventTypeNames::message, false, false)
+ , m_dataType(DataTypeBlob)
+ , m_dataAsBlob(data)
+ , m_origin(origin)
+{
+ ScriptWrappable::init(this);
+}
+
+MessageEvent::MessageEvent(PassRefPtr<ArrayBuffer> data, const String& origin)
+ : Event(EventTypeNames::message, false, false)
+ , m_dataType(DataTypeArrayBuffer)
+ , m_dataAsArrayBuffer(data)
+ , m_origin(origin)
+{
+ ScriptWrappable::init(this);
+}
+
+MessageEvent::~MessageEvent()
+{
+}
+
+PassRefPtr<MessageEvent> MessageEvent::create(const AtomicString& type, const MessageEventInit& initializer, ExceptionState& exceptionState)
+{
+ if (initializer.source.get() && !isValidSource(initializer.source.get())) {
+ exceptionState.throwTypeError("The optional 'source' property is neither a Window nor MessagePort.");
+ return 0;
+ }
+ return adoptRef(new MessageEvent(type, initializer));
+}
+
+void MessageEvent::initMessageEvent(const AtomicString& type, bool canBubble, bool cancelable, const String& origin, const String& lastEventId, DOMWindow* source, PassOwnPtr<MessagePortArray> ports)
+{
+ if (dispatched())
+ return;
+
+ initEvent(type, canBubble, cancelable);
+
+ m_dataType = DataTypeScriptValue;
+ m_origin = origin;
+ m_lastEventId = lastEventId;
+ m_source = source;
+ m_ports = ports;
+}
+
+void MessageEvent::initMessageEvent(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<SerializedScriptValue> data, const String& origin, const String& lastEventId, DOMWindow* source, PassOwnPtr<MessagePortArray> ports)
+{
+ if (dispatched())
+ return;
+
+ initEvent(type, canBubble, cancelable);
+
+ m_dataType = DataTypeSerializedScriptValue;
+ m_dataAsSerializedScriptValue = data;
+ m_origin = origin;
+ m_lastEventId = lastEventId;
+ m_source = source;
+ m_ports = ports;
+
+ if (m_dataAsSerializedScriptValue)
+ m_dataAsSerializedScriptValue->registerMemoryAllocatedWithCurrentScriptContext();
+}
+
+const AtomicString& MessageEvent::interfaceName() const
+{
+ return EventNames::MessageEvent;
+}
+
+void MessageEvent::entangleMessagePorts(ExecutionContext* context)
+{
+ m_ports = MessagePort::entanglePorts(*context, m_channels.release());
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/events/MessageEvent.h b/chromium/third_party/WebKit/Source/core/events/MessageEvent.h
new file mode 100644
index 00000000000..64df40f7718
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/MessageEvent.h
@@ -0,0 +1,144 @@
+/*
+ * Copyright (C) 2007 Henry Mason (hmason@mac.com)
+ * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#ifndef MessageEvent_h
+#define MessageEvent_h
+
+#include "bindings/v8/SerializedScriptValue.h"
+#include "core/events/Event.h"
+#include "core/events/EventTarget.h"
+#include "core/dom/MessagePort.h"
+#include "core/fileapi/Blob.h"
+#include "core/frame/DOMWindow.h"
+#include "wtf/ArrayBuffer.h"
+
+namespace WebCore {
+
+struct MessageEventInit : public EventInit {
+ MessageEventInit();
+
+ String origin;
+ String lastEventId;
+ RefPtr<EventTarget> source;
+ MessagePortArray ports;
+};
+
+class MessageEvent : public Event {
+public:
+ static PassRefPtr<MessageEvent> create()
+ {
+ return adoptRef(new MessageEvent);
+ }
+ static PassRefPtr<MessageEvent> create(PassOwnPtr<MessagePortArray> ports, const String& origin = String(), const String& lastEventId = String(), PassRefPtr<EventTarget> source = 0)
+ {
+ return adoptRef(new MessageEvent(origin, lastEventId, source, ports));
+ }
+ static PassRefPtr<MessageEvent> create(PassOwnPtr<MessagePortArray> ports, PassRefPtr<SerializedScriptValue> data, const String& origin = String(), const String& lastEventId = String(), PassRefPtr<EventTarget> source = 0)
+ {
+ return adoptRef(new MessageEvent(data, origin, lastEventId, source, ports));
+ }
+ static PassRefPtr<MessageEvent> create(PassOwnPtr<MessagePortChannelArray> channels, PassRefPtr<SerializedScriptValue> data, const String& origin = String(), const String& lastEventId = String(), PassRefPtr<EventTarget> source = 0)
+ {
+ return adoptRef(new MessageEvent(data, origin, lastEventId, source, channels));
+ }
+ static PassRefPtr<MessageEvent> create(const String& data, const String& origin = String())
+ {
+ return adoptRef(new MessageEvent(data, origin));
+ }
+ static PassRefPtr<MessageEvent> create(PassRefPtr<Blob> data, const String& origin = String())
+ {
+ return adoptRef(new MessageEvent(data, origin));
+ }
+ static PassRefPtr<MessageEvent> create(PassRefPtr<ArrayBuffer> data, const String& origin = String())
+ {
+ return adoptRef(new MessageEvent(data, origin));
+ }
+ static PassRefPtr<MessageEvent> create(const AtomicString& type, const MessageEventInit& initializer, ExceptionState&);
+ virtual ~MessageEvent();
+
+ void initMessageEvent(const AtomicString& type, bool canBubble, bool cancelable, const String& origin, const String& lastEventId, DOMWindow* source, PassOwnPtr<MessagePortArray>);
+ void initMessageEvent(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<SerializedScriptValue> data, const String& origin, const String& lastEventId, DOMWindow* source, PassOwnPtr<MessagePortArray>);
+
+ const String& origin() const { return m_origin; }
+ const String& lastEventId() const { return m_lastEventId; }
+ EventTarget* source() const { return m_source.get(); }
+ EventTarget* source(bool& isNull) const { isNull = !m_source; return m_source.get(); }
+ MessagePortArray ports() const { return m_ports ? *m_ports : MessagePortArray(); }
+ MessagePortChannelArray* channels() const { return m_channels ? m_channels.get() : 0; }
+
+ virtual const AtomicString& interfaceName() const;
+
+ enum DataType {
+ DataTypeScriptValue,
+ DataTypeSerializedScriptValue,
+ DataTypeString,
+ DataTypeBlob,
+ DataTypeArrayBuffer
+ };
+ DataType dataType() const { return m_dataType; }
+ SerializedScriptValue* dataAsSerializedScriptValue() const { ASSERT(m_dataType == DataTypeScriptValue || m_dataType == DataTypeSerializedScriptValue); return m_dataAsSerializedScriptValue.get(); }
+ String dataAsString() const { ASSERT(m_dataType == DataTypeString); return m_dataAsString; }
+ Blob* dataAsBlob() const { ASSERT(m_dataType == DataTypeBlob); return m_dataAsBlob.get(); }
+ ArrayBuffer* dataAsArrayBuffer() const { ASSERT(m_dataType == DataTypeArrayBuffer); return m_dataAsArrayBuffer.get(); }
+
+ void setSerializedData(PassRefPtr<SerializedScriptValue> data)
+ {
+ ASSERT(!m_dataAsSerializedScriptValue);
+ m_dataAsSerializedScriptValue = data;
+ }
+
+ void entangleMessagePorts(ExecutionContext*);
+
+private:
+ MessageEvent();
+ MessageEvent(const AtomicString&, const MessageEventInit&);
+ MessageEvent(const String& origin, const String& lastEventId, PassRefPtr<EventTarget> source, PassOwnPtr<MessagePortArray>);
+ MessageEvent(PassRefPtr<SerializedScriptValue> data, const String& origin, const String& lastEventId, PassRefPtr<EventTarget> source, PassOwnPtr<MessagePortArray>);
+ MessageEvent(PassRefPtr<SerializedScriptValue> data, const String& origin, const String& lastEventId, PassRefPtr<EventTarget> source, PassOwnPtr<MessagePortChannelArray>);
+
+ explicit MessageEvent(const String& data, const String& origin);
+ explicit MessageEvent(PassRefPtr<Blob> data, const String& origin);
+ explicit MessageEvent(PassRefPtr<ArrayBuffer> data, const String& origin);
+
+ DataType m_dataType;
+ RefPtr<SerializedScriptValue> m_dataAsSerializedScriptValue;
+ String m_dataAsString;
+ RefPtr<Blob> m_dataAsBlob;
+ RefPtr<ArrayBuffer> m_dataAsArrayBuffer;
+ String m_origin;
+ String m_lastEventId;
+ RefPtr<EventTarget> m_source;
+ // m_ports are the MessagePorts in an engtangled state, and m_channels are
+ // the MessageChannels in a disentangled state. Only one of them can be
+ // non-empty at a time. entangleMessagePorts() moves between the states.
+ OwnPtr<MessagePortArray> m_ports;
+ OwnPtr<MessagePortChannelArray> m_channels;
+};
+
+} // namespace WebCore
+
+#endif // MessageEvent_h
diff --git a/chromium/third_party/WebKit/Source/core/events/MessageEvent.idl b/chromium/third_party/WebKit/Source/core/events/MessageEvent.idl
new file mode 100644
index 00000000000..c482b082cfb
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/MessageEvent.idl
@@ -0,0 +1,56 @@
+/*
+ * Copyright (C) 2007 Henry Mason <hmason@mac.com>
+ * Copyright (C) 2011 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+[
+ EventConstructor,
+ GlobalContext=Window&WorkerGlobalScope,
+ RaisesException=Constructor,
+] interface MessageEvent : Event {
+ [InitializedByEventConstructor] readonly attribute DOMString origin;
+ [InitializedByEventConstructor] readonly attribute DOMString lastEventId;
+ [InitializedByEventConstructor] readonly attribute EventTarget? source; // May be a Window or a MessagePort
+ [InitializedByEventConstructor, Custom=Getter] readonly attribute any data;
+ [InitializedByEventConstructor] readonly attribute MessagePort[] ports;
+ [Custom] void initMessageEvent([Default=Undefined] optional DOMString typeArg,
+ [Default=Undefined] optional boolean canBubbleArg,
+ [Default=Undefined] optional boolean cancelableArg,
+ [Default=Undefined] optional any dataArg,
+ [Default=Undefined] optional DOMString originArg,
+ [Default=Undefined] optional DOMString lastEventIdArg,
+ [Default=Undefined] optional Window sourceArg,
+ [Default=Undefined] optional Array messagePorts);
+
+ [Custom] void webkitInitMessageEvent([Default=Undefined] optional DOMString typeArg,
+ [Default=Undefined] optional boolean canBubbleArg,
+ [Default=Undefined] optional boolean cancelableArg,
+ [Default=Undefined] optional any dataArg,
+ [Default=Undefined] optional DOMString originArg,
+ [Default=Undefined] optional DOMString lastEventIdArg,
+ [Default=Undefined] optional Window sourceArg,
+ [Default=Undefined] optional Array transferables);
+};
+
diff --git a/chromium/third_party/WebKit/Source/core/events/MouseEvent.cpp b/chromium/third_party/WebKit/Source/core/events/MouseEvent.cpp
new file mode 100644
index 00000000000..1e6a6979b81
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/MouseEvent.cpp
@@ -0,0 +1,291 @@
+/*
+ * Copyright (C) 2001 Peter Kelly (pmk@post.com)
+ * Copyright (C) 2001 Tobias Anton (anton@stud.fbi.fh-darmstadt.de)
+ * Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
+ * Copyright (C) 2003, 2005, 2006, 2008 Apple Inc. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#include "config.h"
+#include "core/events/MouseEvent.h"
+
+#include "core/dom/Clipboard.h"
+#include "core/dom/Element.h"
+#include "core/events/EventDispatcher.h"
+#include "core/events/EventRetargeter.h"
+#include "core/events/ThreadLocalEventNames.h"
+#include "platform/PlatformMouseEvent.h"
+
+namespace WebCore {
+
+MouseEventInit::MouseEventInit()
+ : screenX(0)
+ , screenY(0)
+ , clientX(0)
+ , clientY(0)
+ , ctrlKey(false)
+ , altKey(false)
+ , shiftKey(false)
+ , metaKey(false)
+ , button(0)
+ , relatedTarget(0)
+{
+}
+
+PassRefPtr<MouseEvent> MouseEvent::create(const AtomicString& type, const MouseEventInit& initializer)
+{
+ return adoptRef(new MouseEvent(type, initializer));
+}
+
+PassRefPtr<MouseEvent> MouseEvent::create(const AtomicString& eventType, PassRefPtr<AbstractView> view, const PlatformMouseEvent& event, int detail, PassRefPtr<Node> relatedTarget)
+{
+ ASSERT(event.type() == PlatformEvent::MouseMoved || event.button() != NoButton);
+
+ bool isMouseEnterOrLeave = eventType == EventTypeNames::mouseenter || eventType == EventTypeNames::mouseleave;
+ bool isCancelable = !isMouseEnterOrLeave;
+ bool isBubbling = !isMouseEnterOrLeave;
+
+ return MouseEvent::create(eventType, isBubbling, isCancelable, view,
+ detail, event.globalPosition().x(), event.globalPosition().y(), event.position().x(), event.position().y(),
+ event.movementDelta().x(), event.movementDelta().y(),
+ event.ctrlKey(), event.altKey(), event.shiftKey(), event.metaKey(), event.button(),
+ relatedTarget, 0, false);
+}
+
+PassRefPtr<MouseEvent> MouseEvent::create(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<AbstractView> view,
+ int detail, int screenX, int screenY, int pageX, int pageY,
+ int movementX, int movementY,
+ bool ctrlKey, bool altKey, bool shiftKey, bool metaKey, unsigned short button,
+ PassRefPtr<EventTarget> relatedTarget)
+
+{
+ return MouseEvent::create(type, canBubble, cancelable, view,
+ detail, screenX, screenY, pageX, pageY,
+ movementX, movementY,
+ ctrlKey, altKey, shiftKey, metaKey, button, relatedTarget, 0, false);
+}
+
+PassRefPtr<MouseEvent> MouseEvent::create(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<AbstractView> view,
+ int detail, int screenX, int screenY, int pageX, int pageY,
+ int movementX, int movementY,
+ bool ctrlKey, bool altKey, bool shiftKey, bool metaKey, unsigned short button,
+ PassRefPtr<EventTarget> relatedTarget, PassRefPtr<Clipboard> clipboard, bool isSimulated)
+{
+ return adoptRef(new MouseEvent(type, canBubble, cancelable, view,
+ detail, screenX, screenY, pageX, pageY,
+ movementX, movementY,
+ ctrlKey, altKey, shiftKey, metaKey, button, relatedTarget, clipboard, isSimulated));
+}
+
+MouseEvent::MouseEvent()
+ : m_button(0)
+ , m_buttonDown(false)
+{
+ ScriptWrappable::init(this);
+}
+
+MouseEvent::MouseEvent(const AtomicString& eventType, bool canBubble, bool cancelable, PassRefPtr<AbstractView> view,
+ int detail, int screenX, int screenY, int pageX, int pageY,
+ int movementX, int movementY,
+ bool ctrlKey, bool altKey, bool shiftKey, bool metaKey,
+ unsigned short button, PassRefPtr<EventTarget> relatedTarget,
+ PassRefPtr<Clipboard> clipboard, bool isSimulated)
+ : MouseRelatedEvent(eventType, canBubble, cancelable, view, detail, IntPoint(screenX, screenY),
+ IntPoint(pageX, pageY),
+ IntPoint(movementX, movementY),
+ ctrlKey, altKey, shiftKey, metaKey, isSimulated)
+ , m_button(button == (unsigned short)-1 ? 0 : button)
+ , m_buttonDown(button != (unsigned short)-1)
+ , m_relatedTarget(relatedTarget)
+ , m_clipboard(clipboard)
+{
+ ScriptWrappable::init(this);
+}
+
+MouseEvent::MouseEvent(const AtomicString& eventType, const MouseEventInit& initializer)
+ : MouseRelatedEvent(eventType, initializer.bubbles, initializer.cancelable, initializer.view, initializer.detail, IntPoint(initializer.screenX, initializer.screenY),
+ IntPoint(0 /* pageX */, 0 /* pageY */),
+ IntPoint(0 /* movementX */, 0 /* movementY */),
+ initializer.ctrlKey, initializer.altKey, initializer.shiftKey, initializer.metaKey, false /* isSimulated */)
+ , m_button(initializer.button == (unsigned short)-1 ? 0 : initializer.button)
+ , m_buttonDown(initializer.button != (unsigned short)-1)
+ , m_relatedTarget(initializer.relatedTarget)
+ , m_clipboard(0 /* clipboard */)
+{
+ ScriptWrappable::init(this);
+ initCoordinates(IntPoint(initializer.clientX, initializer.clientY));
+}
+
+MouseEvent::~MouseEvent()
+{
+}
+
+void MouseEvent::initMouseEvent(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<AbstractView> view,
+ int detail, int screenX, int screenY, int clientX, int clientY,
+ bool ctrlKey, bool altKey, bool shiftKey, bool metaKey,
+ unsigned short button, PassRefPtr<EventTarget> relatedTarget)
+{
+ if (dispatched())
+ return;
+
+ initUIEvent(type, canBubble, cancelable, view, detail);
+
+ m_screenLocation = IntPoint(screenX, screenY);
+ m_ctrlKey = ctrlKey;
+ m_altKey = altKey;
+ m_shiftKey = shiftKey;
+ m_metaKey = metaKey;
+ m_button = button == (unsigned short)-1 ? 0 : button;
+ m_buttonDown = button != (unsigned short)-1;
+ m_relatedTarget = relatedTarget;
+
+ initCoordinates(IntPoint(clientX, clientY));
+
+ // FIXME: m_isSimulated is not set to false here.
+ // FIXME: m_clipboard is not set to 0 here.
+}
+
+const AtomicString& MouseEvent::interfaceName() const
+{
+ return EventNames::MouseEvent;
+}
+
+bool MouseEvent::isMouseEvent() const
+{
+ return true;
+}
+
+bool MouseEvent::isDragEvent() const
+{
+ const AtomicString& t = type();
+ return t == EventTypeNames::dragenter || t == EventTypeNames::dragover || t == EventTypeNames::dragleave || t == EventTypeNames::drop
+ || t == EventTypeNames::dragstart|| t == EventTypeNames::drag || t == EventTypeNames::dragend;
+}
+
+int MouseEvent::which() const
+{
+ // For the DOM, the return values for left, middle and right mouse buttons are 0, 1, 2, respectively.
+ // For the Netscape "which" property, the return values for left, middle and right mouse buttons are 1, 2, 3, respectively.
+ // So we must add 1.
+ if (!m_buttonDown)
+ return 0;
+ return m_button + 1;
+}
+
+Node* MouseEvent::toElement() const
+{
+ // MSIE extension - "the object toward which the user is moving the mouse pointer"
+ if (type() == EventTypeNames::mouseout || type() == EventTypeNames::mouseleave)
+ return relatedTarget() ? relatedTarget()->toNode() : 0;
+
+ return target() ? target()->toNode() : 0;
+}
+
+Node* MouseEvent::fromElement() const
+{
+ // MSIE extension - "object from which activation or the mouse pointer is exiting during the event" (huh?)
+ if (type() != EventTypeNames::mouseout && type() != EventTypeNames::mouseleave)
+ return relatedTarget() ? relatedTarget()->toNode() : 0;
+
+ return target() ? target()->toNode() : 0;
+}
+
+PassRefPtr<SimulatedMouseEvent> SimulatedMouseEvent::create(const AtomicString& eventType, PassRefPtr<AbstractView> view, PassRefPtr<Event> underlyingEvent)
+{
+ return adoptRef(new SimulatedMouseEvent(eventType, view, underlyingEvent));
+}
+
+SimulatedMouseEvent::~SimulatedMouseEvent()
+{
+}
+
+SimulatedMouseEvent::SimulatedMouseEvent(const AtomicString& eventType, PassRefPtr<AbstractView> view, PassRefPtr<Event> underlyingEvent)
+ : MouseEvent(eventType, true, true, view, 0, 0, 0, 0, 0,
+ 0, 0,
+ false, false, false, false, 0, 0, 0, true)
+{
+ if (UIEventWithKeyState* keyStateEvent = findEventWithKeyState(underlyingEvent.get())) {
+ m_ctrlKey = keyStateEvent->ctrlKey();
+ m_altKey = keyStateEvent->altKey();
+ m_shiftKey = keyStateEvent->shiftKey();
+ m_metaKey = keyStateEvent->metaKey();
+ }
+ setUnderlyingEvent(underlyingEvent);
+
+ if (this->underlyingEvent() && this->underlyingEvent()->isMouseEvent()) {
+ MouseEvent* mouseEvent = toMouseEvent(this->underlyingEvent());
+ m_screenLocation = mouseEvent->screenLocation();
+ initCoordinates(mouseEvent->clientLocation());
+ }
+}
+
+PassRefPtr<MouseEventDispatchMediator> MouseEventDispatchMediator::create(PassRefPtr<MouseEvent> mouseEvent, MouseEventType mouseEventType)
+{
+ return adoptRef(new MouseEventDispatchMediator(mouseEvent, mouseEventType));
+}
+
+MouseEventDispatchMediator::MouseEventDispatchMediator(PassRefPtr<MouseEvent> mouseEvent, MouseEventType mouseEventType)
+ : EventDispatchMediator(mouseEvent), m_mouseEventType(mouseEventType)
+{
+}
+
+MouseEvent* MouseEventDispatchMediator::event() const
+{
+ return toMouseEvent(EventDispatchMediator::event());
+}
+
+bool MouseEventDispatchMediator::dispatchEvent(EventDispatcher* dispatcher) const
+{
+ if (isSyntheticMouseEvent()) {
+ EventRetargeter::adjustForMouseEvent(dispatcher->node(), *event());
+ return dispatcher->dispatch();
+ }
+
+ if (isDisabledFormControl(dispatcher->node()))
+ return false;
+
+ if (event()->type().isEmpty())
+ return true; // Shouldn't happen.
+
+ ASSERT(!event()->target() || event()->target() != event()->relatedTarget());
+
+ EventTarget* relatedTarget = event()->relatedTarget();
+ EventRetargeter::adjustForMouseEvent(dispatcher->node(), *event());
+
+ dispatcher->dispatch();
+ bool swallowEvent = event()->defaultHandled() || event()->defaultPrevented();
+
+ if (event()->type() != EventTypeNames::click || event()->detail() != 2)
+ return !swallowEvent;
+
+ // Special case: If it's a double click event, we also send the dblclick event. This is not part
+ // of the DOM specs, but is used for compatibility with the ondblclick="" attribute. This is treated
+ // as a separate event in other DOM-compliant browsers like Firefox, and so we do the same.
+ RefPtr<MouseEvent> doubleClickEvent = MouseEvent::create();
+ doubleClickEvent->initMouseEvent(EventTypeNames::dblclick, event()->bubbles(), event()->cancelable(), event()->view(),
+ event()->detail(), event()->screenX(), event()->screenY(), event()->clientX(), event()->clientY(),
+ event()->ctrlKey(), event()->altKey(), event()->shiftKey(), event()->metaKey(),
+ event()->button(), relatedTarget);
+ if (event()->defaultHandled())
+ doubleClickEvent->setDefaultHandled();
+ EventDispatcher::dispatchEvent(dispatcher->node(), MouseEventDispatchMediator::create(doubleClickEvent));
+ if (doubleClickEvent->defaultHandled() || doubleClickEvent->defaultPrevented())
+ return false;
+ return !swallowEvent;
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/events/MouseEvent.h b/chromium/third_party/WebKit/Source/core/events/MouseEvent.h
new file mode 100644
index 00000000000..41ab261eb8e
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/MouseEvent.h
@@ -0,0 +1,147 @@
+/*
+ * Copyright (C) 2001 Peter Kelly (pmk@post.com)
+ * Copyright (C) 2001 Tobias Anton (anton@stud.fbi.fh-darmstadt.de)
+ * Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
+ * Copyright (C) 2003, 2004, 2005, 2006, 2008 Apple Inc. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ */
+
+#ifndef MouseEvent_h
+#define MouseEvent_h
+
+#include "core/events/EventDispatchMediator.h"
+#include "core/events/MouseRelatedEvent.h"
+
+namespace WebCore {
+
+class Clipboard;
+class EventDispatcher;
+class PlatformMouseEvent;
+
+struct MouseEventInit : public UIEventInit {
+ MouseEventInit();
+
+ int screenX;
+ int screenY;
+ int clientX;
+ int clientY;
+ bool ctrlKey;
+ bool altKey;
+ bool shiftKey;
+ bool metaKey;
+ unsigned short button;
+ RefPtr<EventTarget> relatedTarget;
+};
+
+class MouseEvent : public MouseRelatedEvent {
+public:
+ static PassRefPtr<MouseEvent> create()
+ {
+ return adoptRef(new MouseEvent);
+ }
+
+ static PassRefPtr<MouseEvent> create(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<AbstractView>,
+ int detail, int screenX, int screenY, int pageX, int pageY,
+ int movementX, int movementY,
+ bool ctrlKey, bool altKey, bool shiftKey, bool metaKey, unsigned short button,
+ PassRefPtr<EventTarget> relatedTarget);
+
+ static PassRefPtr<MouseEvent> create(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<AbstractView>,
+ int detail, int screenX, int screenY, int pageX, int pageY,
+ int movementX, int movementY,
+ bool ctrlKey, bool altKey, bool shiftKey, bool metaKey, unsigned short button,
+ PassRefPtr<EventTarget> relatedTarget, PassRefPtr<Clipboard>, bool isSimulated = false);
+
+ static PassRefPtr<MouseEvent> create(const AtomicString& eventType, PassRefPtr<AbstractView>, const PlatformMouseEvent&, int detail, PassRefPtr<Node> relatedTarget);
+
+ static PassRefPtr<MouseEvent> create(const AtomicString& eventType, const MouseEventInit&);
+
+ virtual ~MouseEvent();
+
+ void initMouseEvent(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<AbstractView>,
+ int detail, int screenX, int screenY, int clientX, int clientY,
+ bool ctrlKey, bool altKey, bool shiftKey, bool metaKey,
+ unsigned short button, PassRefPtr<EventTarget> relatedTarget);
+
+ // WinIE uses 1,4,2 for left/middle/right but not for click (just for mousedown/up, maybe others),
+ // but we will match the standard DOM.
+ unsigned short button() const { return m_button; }
+ bool buttonDown() const { return m_buttonDown; }
+ EventTarget* relatedTarget() const { return m_relatedTarget.get(); }
+ EventTarget* relatedTarget(bool& isNull) const { isNull = !m_relatedTarget; return m_relatedTarget.get(); }
+ void setRelatedTarget(PassRefPtr<EventTarget> relatedTarget) { m_relatedTarget = relatedTarget; }
+
+ Clipboard* clipboard() const { return m_clipboard.get(); }
+
+ Node* toElement() const;
+ Node* fromElement() const;
+
+ Clipboard* dataTransfer() const { return isDragEvent() ? m_clipboard.get() : 0; }
+
+ virtual const AtomicString& interfaceName() const;
+
+ virtual bool isMouseEvent() const;
+ virtual bool isDragEvent() const;
+ virtual int which() const;
+
+protected:
+ MouseEvent(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<AbstractView>,
+ int detail, int screenX, int screenY, int pageX, int pageY,
+ int movementX, int movementY,
+ bool ctrlKey, bool altKey, bool shiftKey, bool metaKey, unsigned short button,
+ PassRefPtr<EventTarget> relatedTarget, PassRefPtr<Clipboard>, bool isSimulated);
+
+ MouseEvent(const AtomicString& type, const MouseEventInit&);
+
+ MouseEvent();
+
+private:
+ unsigned short m_button;
+ bool m_buttonDown;
+ RefPtr<EventTarget> m_relatedTarget;
+ RefPtr<Clipboard> m_clipboard;
+};
+
+class SimulatedMouseEvent : public MouseEvent {
+public:
+ static PassRefPtr<SimulatedMouseEvent> create(const AtomicString& eventType, PassRefPtr<AbstractView>, PassRefPtr<Event> underlyingEvent);
+ virtual ~SimulatedMouseEvent();
+
+private:
+ SimulatedMouseEvent(const AtomicString& eventType, PassRefPtr<AbstractView>, PassRefPtr<Event> underlyingEvent);
+};
+
+class MouseEventDispatchMediator : public EventDispatchMediator {
+public:
+ enum MouseEventType { SyntheticMouseEvent, NonSyntheticMouseEvent};
+ static PassRefPtr<MouseEventDispatchMediator> create(PassRefPtr<MouseEvent>, MouseEventType = NonSyntheticMouseEvent);
+
+private:
+ explicit MouseEventDispatchMediator(PassRefPtr<MouseEvent>, MouseEventType);
+ MouseEvent* event() const;
+
+ virtual bool dispatchEvent(EventDispatcher*) const OVERRIDE;
+ bool isSyntheticMouseEvent() const { return m_mouseEventType == SyntheticMouseEvent; }
+ MouseEventType m_mouseEventType;
+};
+
+DEFINE_EVENT_TYPE_CASTS(MouseEvent);
+
+} // namespace WebCore
+
+#endif // MouseEvent_h
diff --git a/chromium/third_party/WebKit/Source/core/events/MouseEvent.idl b/chromium/third_party/WebKit/Source/core/events/MouseEvent.idl
new file mode 100644
index 00000000000..7dd8284bf78
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/MouseEvent.idl
@@ -0,0 +1,62 @@
+/*
+ * Copyright (C) 2006, 2007 Apple Inc. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+[
+ EventConstructor,
+] interface MouseEvent : UIEvent {
+ [InitializedByEventConstructor] readonly attribute long screenX;
+ [InitializedByEventConstructor] readonly attribute long screenY;
+ [InitializedByEventConstructor] readonly attribute long clientX;
+ [InitializedByEventConstructor] readonly attribute long clientY;
+ [InitializedByEventConstructor] readonly attribute boolean ctrlKey;
+ [InitializedByEventConstructor] readonly attribute boolean shiftKey;
+ [InitializedByEventConstructor] readonly attribute boolean altKey;
+ [InitializedByEventConstructor] readonly attribute boolean metaKey;
+ [InitializedByEventConstructor] readonly attribute unsigned short button;
+ [InitializedByEventConstructor] readonly attribute EventTarget? relatedTarget;
+ readonly attribute long webkitMovementX;
+ readonly attribute long webkitMovementY;
+
+ void initMouseEvent([Default=Undefined] optional DOMString type,
+ [Default=Undefined] optional boolean canBubble,
+ [Default=Undefined] optional boolean cancelable,
+ [Default=Undefined] optional Window view,
+ [Default=Undefined] optional long detail,
+ [Default=Undefined] optional long screenX,
+ [Default=Undefined] optional long screenY,
+ [Default=Undefined] optional long clientX,
+ [Default=Undefined] optional long clientY,
+ [Default=Undefined] optional boolean ctrlKey,
+ [Default=Undefined] optional boolean altKey,
+ [Default=Undefined] optional boolean shiftKey,
+ [Default=Undefined] optional boolean metaKey,
+ [Default=Undefined] optional unsigned short button,
+ [Default=Undefined] optional EventTarget relatedTarget);
+
+ // extensions
+ readonly attribute long offsetX;
+ readonly attribute long offsetY;
+ readonly attribute long x;
+ readonly attribute long y;
+ readonly attribute Node fromElement;
+ readonly attribute Node toElement;
+
+ readonly attribute Clipboard dataTransfer;
+};
+
diff --git a/chromium/third_party/WebKit/Source/core/events/MouseRelatedEvent.cpp b/chromium/third_party/WebKit/Source/core/events/MouseRelatedEvent.cpp
new file mode 100644
index 00000000000..4953243cae1
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/MouseRelatedEvent.cpp
@@ -0,0 +1,230 @@
+/*
+ * Copyright (C) 2001 Peter Kelly (pmk@post.com)
+ * Copyright (C) 2001 Tobias Anton (anton@stud.fbi.fh-darmstadt.de)
+ * Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
+ * Copyright (C) 2003, 2005, 2006, 2008 Apple Inc. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#include "config.h"
+#include "core/events/MouseRelatedEvent.h"
+
+#include "core/dom/Document.h"
+#include "core/frame/DOMWindow.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
+#include "core/rendering/RenderLayer.h"
+#include "core/rendering/RenderObject.h"
+
+namespace WebCore {
+
+MouseRelatedEvent::MouseRelatedEvent()
+ : m_isSimulated(false)
+ , m_hasCachedRelativePosition(false)
+{
+}
+
+static LayoutSize contentsScrollOffset(AbstractView* abstractView)
+{
+ if (!abstractView)
+ return LayoutSize();
+ Frame* frame = abstractView->frame();
+ if (!frame)
+ return LayoutSize();
+ FrameView* frameView = frame->view();
+ if (!frameView)
+ return LayoutSize();
+ float scaleFactor = frame->pageZoomFactor();
+ return LayoutSize(frameView->scrollX() / scaleFactor, frameView->scrollY() / scaleFactor);
+}
+
+MouseRelatedEvent::MouseRelatedEvent(const AtomicString& eventType, bool canBubble, bool cancelable, PassRefPtr<AbstractView> abstractView,
+ int detail, const IntPoint& screenLocation, const IntPoint& windowLocation,
+ const IntPoint& movementDelta,
+ bool ctrlKey, bool altKey, bool shiftKey, bool metaKey, bool isSimulated)
+ : UIEventWithKeyState(eventType, canBubble, cancelable, abstractView, detail, ctrlKey, altKey, shiftKey, metaKey)
+ , m_screenLocation(screenLocation)
+ , m_movementDelta(movementDelta)
+ , m_isSimulated(isSimulated)
+{
+ LayoutPoint adjustedPageLocation;
+ LayoutPoint scrollPosition;
+
+ Frame* frame = view() ? view()->frame() : 0;
+ if (frame && !isSimulated) {
+ if (FrameView* frameView = frame->view()) {
+ scrollPosition = frameView->scrollPosition();
+ adjustedPageLocation = frameView->windowToContents(windowLocation);
+ float scaleFactor = 1 / frame->pageZoomFactor();
+ if (scaleFactor != 1.0f) {
+ adjustedPageLocation.scale(scaleFactor, scaleFactor);
+ scrollPosition.scale(scaleFactor, scaleFactor);
+ }
+ }
+ }
+
+ m_clientLocation = adjustedPageLocation - toLayoutSize(scrollPosition);
+ m_pageLocation = adjustedPageLocation;
+
+ initCoordinates();
+}
+
+void MouseRelatedEvent::initCoordinates()
+{
+ // Set up initial values for coordinates.
+ // Correct values are computed lazily, see computeRelativePosition.
+ m_layerLocation = m_pageLocation;
+ m_offsetLocation = m_pageLocation;
+
+ computePageLocation();
+ m_hasCachedRelativePosition = false;
+}
+
+void MouseRelatedEvent::initCoordinates(const LayoutPoint& clientLocation)
+{
+ // Set up initial values for coordinates.
+ // Correct values are computed lazily, see computeRelativePosition.
+ m_clientLocation = clientLocation;
+ m_pageLocation = clientLocation + contentsScrollOffset(view());
+
+ m_layerLocation = m_pageLocation;
+ m_offsetLocation = m_pageLocation;
+
+ computePageLocation();
+ m_hasCachedRelativePosition = false;
+}
+
+static float pageZoomFactor(const UIEvent* event)
+{
+ DOMWindow* window = event->view();
+ if (!window)
+ return 1;
+ Frame* frame = window->frame();
+ if (!frame)
+ return 1;
+ return frame->pageZoomFactor();
+}
+
+void MouseRelatedEvent::computePageLocation()
+{
+ float scaleFactor = pageZoomFactor(this);
+ setAbsoluteLocation(roundedLayoutPoint(FloatPoint(pageX() * scaleFactor, pageY() * scaleFactor)));
+}
+
+void MouseRelatedEvent::receivedTarget()
+{
+ m_hasCachedRelativePosition = false;
+}
+
+void MouseRelatedEvent::computeRelativePosition()
+{
+ Node* targetNode = target() ? target()->toNode() : 0;
+ if (!targetNode)
+ return;
+
+ // Compute coordinates that are based on the target.
+ m_layerLocation = m_pageLocation;
+ m_offsetLocation = m_pageLocation;
+
+ // Must have an updated render tree for this math to work correctly.
+ targetNode->document().updateLayoutIgnorePendingStylesheets();
+
+ // Adjust offsetLocation to be relative to the target's position.
+ if (RenderObject* r = targetNode->renderer()) {
+ FloatPoint localPos = r->absoluteToLocal(absoluteLocation(), UseTransforms);
+ m_offsetLocation = roundedLayoutPoint(localPos);
+ float scaleFactor = 1 / pageZoomFactor(this);
+ if (scaleFactor != 1.0f)
+ m_offsetLocation.scale(scaleFactor, scaleFactor);
+ }
+
+ // Adjust layerLocation to be relative to the layer.
+ // FIXME: event.layerX and event.layerY are poorly defined,
+ // and probably don't always correspond to RenderLayer offsets.
+ // https://bugs.webkit.org/show_bug.cgi?id=21868
+ Node* n = targetNode;
+ while (n && !n->renderer())
+ n = n->parentNode();
+
+ RenderLayer* layer;
+ if (n && (layer = n->renderer()->enclosingLayer())) {
+ for (; layer; layer = layer->parent()) {
+ m_layerLocation -= toLayoutSize(layer->location());
+ }
+ }
+
+ m_hasCachedRelativePosition = true;
+}
+
+int MouseRelatedEvent::layerX()
+{
+ if (!m_hasCachedRelativePosition)
+ computeRelativePosition();
+ return m_layerLocation.x();
+}
+
+int MouseRelatedEvent::layerY()
+{
+ if (!m_hasCachedRelativePosition)
+ computeRelativePosition();
+ return m_layerLocation.y();
+}
+
+int MouseRelatedEvent::offsetX()
+{
+ if (!m_hasCachedRelativePosition)
+ computeRelativePosition();
+ return roundToInt(m_offsetLocation.x());
+}
+
+int MouseRelatedEvent::offsetY()
+{
+ if (!m_hasCachedRelativePosition)
+ computeRelativePosition();
+ return roundToInt(m_offsetLocation.y());
+}
+
+int MouseRelatedEvent::pageX() const
+{
+ return m_pageLocation.x();
+}
+
+int MouseRelatedEvent::pageY() const
+{
+ return m_pageLocation.y();
+}
+
+const LayoutPoint& MouseRelatedEvent::pageLocation() const
+{
+ return m_pageLocation;
+}
+
+int MouseRelatedEvent::x() const
+{
+ // FIXME: This is not correct.
+ // See Microsoft documentation and <http://www.quirksmode.org/dom/w3c_events.html>.
+ return m_clientLocation.x();
+}
+
+int MouseRelatedEvent::y() const
+{
+ // FIXME: This is not correct.
+ // See Microsoft documentation and <http://www.quirksmode.org/dom/w3c_events.html>.
+ return m_clientLocation.y();
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/events/MouseRelatedEvent.h b/chromium/third_party/WebKit/Source/core/events/MouseRelatedEvent.h
new file mode 100644
index 00000000000..fbaeb9c68aa
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/MouseRelatedEvent.h
@@ -0,0 +1,91 @@
+/*
+ * Copyright (C) 2001 Peter Kelly (pmk@post.com)
+ * Copyright (C) 2001 Tobias Anton (anton@stud.fbi.fh-darmstadt.de)
+ * Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
+ * Copyright (C) 2003, 2004, 2005, 2006 Apple Computer, Inc.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ */
+
+#ifndef MouseRelatedEvent_h
+#define MouseRelatedEvent_h
+
+#include "core/events/UIEventWithKeyState.h"
+#include "platform/geometry/LayoutPoint.h"
+
+namespace WebCore {
+
+ // Internal only: Helper class for what's common between mouse and wheel events.
+ class MouseRelatedEvent : public UIEventWithKeyState {
+ public:
+ // Note that these values are adjusted to counter the effects of zoom, so that values
+ // exposed via DOM APIs are invariant under zooming.
+ int screenX() const { return m_screenLocation.x(); }
+ int screenY() const { return m_screenLocation.y(); }
+ const IntPoint& screenLocation() const { return m_screenLocation; }
+ int clientX() const { return m_clientLocation.x(); }
+ int clientY() const { return m_clientLocation.y(); }
+ int webkitMovementX() const { return m_movementDelta.x(); }
+ int webkitMovementY() const { return m_movementDelta.y(); }
+ const LayoutPoint& clientLocation() const { return m_clientLocation; }
+ int layerX();
+ int layerY();
+ int offsetX();
+ int offsetY();
+ bool isSimulated() const { return m_isSimulated; }
+ virtual int pageX() const;
+ virtual int pageY() const;
+ virtual const LayoutPoint& pageLocation() const;
+ int x() const;
+ int y() const;
+
+ // Page point in "absolute" coordinates (i.e. post-zoomed, page-relative coords,
+ // usable with RenderObject::absoluteToLocal).
+ const LayoutPoint& absoluteLocation() const { return m_absoluteLocation; }
+ void setAbsoluteLocation(const LayoutPoint& p) { m_absoluteLocation = p; }
+
+ protected:
+ MouseRelatedEvent();
+ MouseRelatedEvent(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<AbstractView>,
+ int detail, const IntPoint& screenLocation, const IntPoint& windowLocation,
+ const IntPoint& movementDelta,
+ bool ctrlKey, bool altKey, bool shiftKey, bool metaKey, bool isSimulated = false);
+
+ void initCoordinates();
+ void initCoordinates(const LayoutPoint& clientLocation);
+ virtual void receivedTarget();
+
+ void computePageLocation();
+ void computeRelativePosition();
+
+ // Expose these so MouseEvent::initMouseEvent can set them.
+ IntPoint m_screenLocation;
+ LayoutPoint m_clientLocation;
+ LayoutPoint m_movementDelta;
+
+ private:
+ LayoutPoint m_pageLocation;
+ LayoutPoint m_layerLocation;
+ LayoutPoint m_offsetLocation;
+ LayoutPoint m_absoluteLocation;
+ bool m_isSimulated;
+ bool m_hasCachedRelativePosition;
+ };
+
+} // namespace WebCore
+
+#endif // MouseRelatedEvent_h
diff --git a/chromium/third_party/WebKit/Source/core/events/MutationEvent.cpp b/chromium/third_party/WebKit/Source/core/events/MutationEvent.cpp
new file mode 100644
index 00000000000..542b304505b
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/MutationEvent.cpp
@@ -0,0 +1,74 @@
+/*
+ * Copyright (C) 2001 Peter Kelly (pmk@post.com)
+ * Copyright (C) 2001 Tobias Anton (anton@stud.fbi.fh-darmstadt.de)
+ * Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
+ * Copyright (C) 2003, 2005, 2006, 2008 Apple Inc. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#include "config.h"
+#include "core/events/MutationEvent.h"
+
+#include "core/events/ThreadLocalEventNames.h"
+
+namespace WebCore {
+
+MutationEvent::MutationEvent()
+ : m_attrChange(0)
+{
+ ScriptWrappable::init(this);
+}
+
+MutationEvent::MutationEvent(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<Node> relatedNode,
+ const String& prevValue, const String& newValue,
+ const String& attrName, unsigned short attrChange)
+ : Event(type, canBubble, cancelable)
+ , m_relatedNode(relatedNode)
+ , m_prevValue(prevValue)
+ , m_newValue(newValue)
+ , m_attrName(attrName)
+ , m_attrChange(attrChange)
+{
+ ScriptWrappable::init(this);
+}
+
+MutationEvent::~MutationEvent()
+{
+}
+
+void MutationEvent::initMutationEvent(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<Node> relatedNode,
+ const String& prevValue, const String& newValue,
+ const String& attrName, unsigned short attrChange)
+{
+ if (dispatched())
+ return;
+
+ initEvent(type, canBubble, cancelable);
+
+ m_relatedNode = relatedNode;
+ m_prevValue = prevValue;
+ m_newValue = newValue;
+ m_attrName = attrName;
+ m_attrChange = attrChange;
+}
+
+const AtomicString& MutationEvent::interfaceName() const
+{
+ return EventNames::MutationEvent;
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/events/MutationEvent.h b/chromium/third_party/WebKit/Source/core/events/MutationEvent.h
new file mode 100644
index 00000000000..f0ef13e5b6c
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/MutationEvent.h
@@ -0,0 +1,80 @@
+/*
+ * Copyright (C) 2001 Peter Kelly (pmk@post.com)
+ * Copyright (C) 2001 Tobias Anton (anton@stud.fbi.fh-darmstadt.de)
+ * Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
+ * Copyright (C) 2003, 2004, 2005, 2006, 2008 Apple Inc. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ */
+
+#ifndef MutationEvent_h
+#define MutationEvent_h
+
+#include "core/events/Event.h"
+#include "core/dom/Node.h"
+
+namespace WebCore {
+
+ class MutationEvent : public Event {
+ public:
+ virtual ~MutationEvent();
+
+ enum attrChangeType {
+ MODIFICATION = 1,
+ ADDITION = 2,
+ REMOVAL = 3
+ };
+
+ static PassRefPtr<MutationEvent> create()
+ {
+ return adoptRef(new MutationEvent);
+ }
+
+ static PassRefPtr<MutationEvent> create(const AtomicString& type, bool canBubble, PassRefPtr<Node> relatedNode = 0,
+ const String& prevValue = String(), const String& newValue = String(), const String& attrName = String(), unsigned short attrChange = 0)
+ {
+ return adoptRef(new MutationEvent(type, canBubble, false, relatedNode, prevValue, newValue, attrName, attrChange));
+ }
+
+ void initMutationEvent(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<Node> relatedNode,
+ const String& prevValue, const String& newValue,
+ const String& attrName, unsigned short attrChange);
+
+ Node* relatedNode() const { return m_relatedNode.get(); }
+ String prevValue() const { return m_prevValue; }
+ String newValue() const { return m_newValue; }
+ String attrName() const { return m_attrName; }
+ unsigned short attrChange() const { return m_attrChange; }
+
+ virtual const AtomicString& interfaceName() const;
+
+ private:
+ MutationEvent();
+ MutationEvent(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<Node> relatedNode,
+ const String& prevValue, const String& newValue,
+ const String& attrName, unsigned short attrChange);
+
+ RefPtr<Node> m_relatedNode;
+ String m_prevValue;
+ String m_newValue;
+ String m_attrName;
+ unsigned short m_attrChange;
+ };
+
+} // namespace WebCore
+
+#endif // MutationEvent_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/MutationEvent.idl b/chromium/third_party/WebKit/Source/core/events/MutationEvent.idl
index 0aae4e31df9..0aae4e31df9 100644
--- a/chromium/third_party/WebKit/Source/core/dom/MutationEvent.idl
+++ b/chromium/third_party/WebKit/Source/core/events/MutationEvent.idl
diff --git a/chromium/third_party/WebKit/Source/core/events/NavigatorEvents.cpp b/chromium/third_party/WebKit/Source/core/events/NavigatorEvents.cpp
new file mode 100644
index 00000000000..a4285c21ef8
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/NavigatorEvents.cpp
@@ -0,0 +1,50 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/events/NavigatorEvents.h"
+
+#include "core/frame/Frame.h"
+#include "core/frame/Navigator.h"
+#include "core/frame/Settings.h"
+
+namespace WebCore {
+
+long NavigatorEvents::maxTouchPoints(Navigator* navigator)
+{
+ Frame* frame = navigator->frame();
+ if (!frame)
+ return 0;
+ if (Settings* settings = frame->settings())
+ return settings->maxTouchPoints();
+ return 0;
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/events/NavigatorEvents.h b/chromium/third_party/WebKit/Source/core/events/NavigatorEvents.h
new file mode 100644
index 00000000000..44cead91197
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/NavigatorEvents.h
@@ -0,0 +1,45 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef NavigatorEvents_h
+#define NavigatorEvents_h
+
+namespace WebCore {
+
+class Navigator;
+
+class NavigatorEvents {
+public:
+ static long maxTouchPoints(Navigator*);
+};
+
+} // namespace WebCore
+
+#endif // NavigatorEvents_h
diff --git a/chromium/third_party/WebKit/Source/core/events/NavigatorEvents.idl b/chromium/third_party/WebKit/Source/core/events/NavigatorEvents.idl
new file mode 100644
index 00000000000..fe899fc50b8
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/NavigatorEvents.idl
@@ -0,0 +1,34 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+partial interface Navigator {
+ [RuntimeEnabled=PointerEventsMaxTouchPoints]
+ readonly attribute long maxTouchPoints;
+}; \ No newline at end of file
diff --git a/chromium/third_party/WebKit/Source/core/events/OverflowEvent.cpp b/chromium/third_party/WebKit/Source/core/events/OverflowEvent.cpp
new file mode 100644
index 00000000000..c958ce655e6
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/OverflowEvent.cpp
@@ -0,0 +1,89 @@
+/*
+ * Copyright (C) 2006, 2007 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/events/OverflowEvent.h"
+
+#include "core/events/ThreadLocalEventNames.h"
+
+namespace WebCore {
+
+OverflowEventInit::OverflowEventInit()
+ : orient(0)
+ , horizontalOverflow(false)
+ , verticalOverflow(false)
+{
+}
+
+OverflowEvent::OverflowEvent()
+ : Event(EventTypeNames::overflowchanged, false, false)
+ , m_orient(VERTICAL)
+ , m_horizontalOverflow(false)
+ , m_verticalOverflow(false)
+{
+ ScriptWrappable::init(this);
+}
+
+OverflowEvent::OverflowEvent(bool horizontalOverflowChanged, bool horizontalOverflow, bool verticalOverflowChanged, bool verticalOverflow)
+ : Event(EventTypeNames::overflowchanged, false, false)
+ , m_horizontalOverflow(horizontalOverflow)
+ , m_verticalOverflow(verticalOverflow)
+{
+ ASSERT(horizontalOverflowChanged || verticalOverflowChanged);
+ ScriptWrappable::init(this);
+
+ if (horizontalOverflowChanged && verticalOverflowChanged)
+ m_orient = BOTH;
+ else if (horizontalOverflowChanged)
+ m_orient = HORIZONTAL;
+ else
+ m_orient = VERTICAL;
+}
+
+OverflowEvent::OverflowEvent(const AtomicString& type, const OverflowEventInit& initializer)
+ : Event(type, initializer)
+ , m_orient(initializer.orient)
+ , m_horizontalOverflow(initializer.horizontalOverflow)
+ , m_verticalOverflow(initializer.verticalOverflow)
+{
+ ScriptWrappable::init(this);
+}
+
+const AtomicString& OverflowEvent::interfaceName() const
+{
+ return EventNames::OverflowEvent;
+}
+
+void OverflowEvent::initOverflowEvent(unsigned short orient, bool horizontalOverflow, bool verticalOverflow)
+{
+ if (dispatched())
+ return;
+
+ m_orient = orient;
+ m_horizontalOverflow = horizontalOverflow;
+ m_verticalOverflow = verticalOverflow;
+}
+
+}
diff --git a/chromium/third_party/WebKit/Source/core/events/OverflowEvent.h b/chromium/third_party/WebKit/Source/core/events/OverflowEvent.h
new file mode 100644
index 00000000000..96c220b2198
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/OverflowEvent.h
@@ -0,0 +1,82 @@
+/*
+ * Copyright (C) 2006, 2007, 2008 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef OverflowEvent_h
+#define OverflowEvent_h
+
+#include "core/events/Event.h"
+
+namespace WebCore {
+
+struct OverflowEventInit : public EventInit {
+ OverflowEventInit();
+
+ unsigned short orient;
+ bool horizontalOverflow;
+ bool verticalOverflow;
+};
+
+class OverflowEvent : public Event {
+public:
+ enum orientType {
+ HORIZONTAL = 0,
+ VERTICAL = 1,
+ BOTH = 2
+ };
+
+ static PassRefPtr<OverflowEvent> create()
+ {
+ return adoptRef(new OverflowEvent);
+ }
+ static PassRefPtr<OverflowEvent> create(bool horizontalOverflowChanged, bool horizontalOverflow, bool verticalOverflowChanged, bool verticalOverflow)
+ {
+ return adoptRef(new OverflowEvent(horizontalOverflowChanged, horizontalOverflow, verticalOverflowChanged, verticalOverflow));
+ }
+ static PassRefPtr<OverflowEvent> create(const AtomicString& type, const OverflowEventInit& initializer)
+ {
+ return adoptRef(new OverflowEvent(type, initializer));
+ }
+
+ void initOverflowEvent(unsigned short orient, bool horizontalOverflow, bool verticalOverflow);
+
+ unsigned short orient() const { return m_orient; }
+ bool horizontalOverflow() const { return m_horizontalOverflow; }
+ bool verticalOverflow() const { return m_verticalOverflow; }
+
+ virtual const AtomicString& interfaceName() const;
+
+private:
+ OverflowEvent();
+ OverflowEvent(bool horizontalOverflowChanged, bool horizontalOverflow, bool verticalOverflowChanged, bool verticalOverflow);
+ OverflowEvent(const AtomicString&, const OverflowEventInit&);
+
+ unsigned short m_orient;
+ bool m_horizontalOverflow;
+ bool m_verticalOverflow;
+};
+
+}
+
+#endif // OverflowEvent_h
diff --git a/chromium/third_party/WebKit/Source/core/events/OverflowEvent.idl b/chromium/third_party/WebKit/Source/core/events/OverflowEvent.idl
new file mode 100644
index 00000000000..be779e4e48a
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/OverflowEvent.idl
@@ -0,0 +1,37 @@
+/*
+ * Copyright (C) 2006, 2007 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+[
+ EventConstructor,
+] interface OverflowEvent : Event {
+ const unsigned short HORIZONTAL = 0;
+ const unsigned short VERTICAL = 1;
+ const unsigned short BOTH = 2;
+
+ [InitializedByEventConstructor] readonly attribute unsigned short orient;
+ [InitializedByEventConstructor] readonly attribute boolean horizontalOverflow;
+ [InitializedByEventConstructor] readonly attribute boolean verticalOverflow;
+};
+
diff --git a/chromium/third_party/WebKit/Source/core/events/PageTransitionEvent.cpp b/chromium/third_party/WebKit/Source/core/events/PageTransitionEvent.cpp
new file mode 100644
index 00000000000..a1878c468c5
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/PageTransitionEvent.cpp
@@ -0,0 +1,67 @@
+/*
+ * Copyright (C) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/events/PageTransitionEvent.h"
+
+#include "core/events/ThreadLocalEventNames.h"
+
+namespace WebCore {
+
+PageTransitionEventInit::PageTransitionEventInit()
+ : persisted(false)
+{
+}
+
+PageTransitionEvent::PageTransitionEvent()
+ : m_persisted(false)
+{
+ ScriptWrappable::init(this);
+}
+
+PageTransitionEvent::PageTransitionEvent(const AtomicString& type, bool persisted)
+ : Event(type, true, true)
+ , m_persisted(persisted)
+{
+ ScriptWrappable::init(this);
+}
+
+PageTransitionEvent::PageTransitionEvent(const AtomicString& type, const PageTransitionEventInit& initializer)
+ : Event(type, initializer)
+ , m_persisted(initializer.persisted)
+{
+ ScriptWrappable::init(this);
+}
+
+PageTransitionEvent::~PageTransitionEvent()
+{
+}
+
+const AtomicString& PageTransitionEvent::interfaceName() const
+{
+ return EventNames::PageTransitionEvent;
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/events/PageTransitionEvent.h b/chromium/third_party/WebKit/Source/core/events/PageTransitionEvent.h
new file mode 100644
index 00000000000..1002f5562ad
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/PageTransitionEvent.h
@@ -0,0 +1,70 @@
+/*
+ * Copyright (C) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef PageTransitionEvent_h
+#define PageTransitionEvent_h
+
+#include "core/events/Event.h"
+
+namespace WebCore {
+
+struct PageTransitionEventInit : public EventInit {
+ PageTransitionEventInit();
+
+ bool persisted;
+};
+
+class PageTransitionEvent : public Event {
+public:
+ static PassRefPtr<PageTransitionEvent> create()
+ {
+ return adoptRef(new PageTransitionEvent);
+ }
+ static PassRefPtr<PageTransitionEvent> create(const AtomicString& type, bool persisted)
+ {
+ return adoptRef(new PageTransitionEvent(type, persisted));
+ }
+ static PassRefPtr<PageTransitionEvent> create(const AtomicString& type, const PageTransitionEventInit& initializer)
+ {
+ return adoptRef(new PageTransitionEvent(type, initializer));
+ }
+
+ virtual ~PageTransitionEvent();
+
+ virtual const AtomicString& interfaceName() const;
+
+ bool persisted() const { return m_persisted; }
+
+private:
+ PageTransitionEvent();
+ PageTransitionEvent(const AtomicString& type, bool persisted);
+ PageTransitionEvent(const AtomicString&, const PageTransitionEventInit&);
+
+ bool m_persisted;
+};
+
+} // namespace WebCore
+
+#endif // PageTransitionEvent_h
diff --git a/chromium/third_party/WebKit/Source/core/events/PageTransitionEvent.idl b/chromium/third_party/WebKit/Source/core/events/PageTransitionEvent.idl
new file mode 100644
index 00000000000..679d51edc5a
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/PageTransitionEvent.idl
@@ -0,0 +1,31 @@
+/*
+ * Copyright (C) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+[
+ EventConstructor,
+] interface PageTransitionEvent : Event {
+ [InitializedByEventConstructor] readonly attribute boolean persisted;
+};
+
diff --git a/chromium/third_party/WebKit/Source/core/events/PopStateEvent.cpp b/chromium/third_party/WebKit/Source/core/events/PopStateEvent.cpp
new file mode 100644
index 00000000000..2ab213a18f2
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/PopStateEvent.cpp
@@ -0,0 +1,83 @@
+/*
+ * Copyright (C) 2009 Apple Inc. All Rights Reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "config.h"
+#include "core/events/PopStateEvent.h"
+
+#include "bindings/v8/SerializedScriptValue.h"
+#include "core/events/ThreadLocalEventNames.h"
+#include "core/frame/History.h"
+
+namespace WebCore {
+
+PopStateEvent::PopStateEvent()
+ : Event(EventTypeNames::popstate, false, true)
+ , m_serializedState(0)
+ , m_history(0)
+{
+ ScriptWrappable::init(this);
+}
+
+PopStateEvent::PopStateEvent(const AtomicString& type, const PopStateEventInit& initializer)
+ : Event(type, initializer)
+ , m_history(0)
+{
+ ScriptWrappable::init(this);
+}
+
+PopStateEvent::PopStateEvent(PassRefPtr<SerializedScriptValue> serializedState, PassRefPtr<History> history)
+ : Event(EventTypeNames::popstate, false, true)
+ , m_serializedState(serializedState)
+ , m_history(history)
+{
+ ScriptWrappable::init(this);
+}
+
+PopStateEvent::~PopStateEvent()
+{
+}
+
+PassRefPtr<PopStateEvent> PopStateEvent::create()
+{
+ return adoptRef(new PopStateEvent);
+}
+
+PassRefPtr<PopStateEvent> PopStateEvent::create(PassRefPtr<SerializedScriptValue> serializedState, PassRefPtr<History> history)
+{
+ return adoptRef(new PopStateEvent(serializedState, history));
+}
+
+PassRefPtr<PopStateEvent> PopStateEvent::create(const AtomicString& type, const PopStateEventInit& initializer)
+{
+ return adoptRef(new PopStateEvent(type, initializer));
+}
+
+const AtomicString& PopStateEvent::interfaceName() const
+{
+ return EventNames::PopStateEvent;
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/events/PopStateEvent.h b/chromium/third_party/WebKit/Source/core/events/PopStateEvent.h
new file mode 100644
index 00000000000..5f874ea0174
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/PopStateEvent.h
@@ -0,0 +1,67 @@
+/*
+ * Copyright (C) 2009 Apple Inc. All Rights Reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#ifndef PopStateEvent_h
+#define PopStateEvent_h
+
+#include "core/events/Event.h"
+
+namespace WebCore {
+
+class History;
+class SerializedScriptValue;
+
+typedef EventInit PopStateEventInit;
+
+class PopStateEvent : public Event {
+public:
+ virtual ~PopStateEvent();
+ static PassRefPtr<PopStateEvent> create();
+ static PassRefPtr<PopStateEvent> create(PassRefPtr<SerializedScriptValue>, PassRefPtr<History>);
+ static PassRefPtr<PopStateEvent> create(const AtomicString&, const PopStateEventInit&);
+
+ SerializedScriptValue* serializedState() const { return m_serializedState.get(); }
+ void setSerializedState(PassRefPtr<SerializedScriptValue> state)
+ {
+ ASSERT(!m_serializedState);
+ m_serializedState = state;
+ }
+ History* history() const { return m_history.get(); }
+
+ virtual const AtomicString& interfaceName() const;
+
+private:
+ PopStateEvent();
+ PopStateEvent(const AtomicString&, const PopStateEventInit&);
+ explicit PopStateEvent(PassRefPtr<SerializedScriptValue>, PassRefPtr<History>);
+
+ RefPtr<SerializedScriptValue> m_serializedState;
+ RefPtr<History> m_history;
+};
+
+} // namespace WebCore
+
+#endif // PopStateEvent_h
diff --git a/chromium/third_party/WebKit/Source/core/events/PopStateEvent.idl b/chromium/third_party/WebKit/Source/core/events/PopStateEvent.idl
new file mode 100644
index 00000000000..a1ccf169560
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/PopStateEvent.idl
@@ -0,0 +1,31 @@
+/*
+ * Copyright (C) 2009 Apple Inc. All Rights Reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+[
+ EventConstructor,
+] interface PopStateEvent : Event {
+ [InitializedByEventConstructor, Custom=Getter] readonly attribute any state;
+};
diff --git a/chromium/third_party/WebKit/Source/core/events/ProgressEvent.cpp b/chromium/third_party/WebKit/Source/core/events/ProgressEvent.cpp
new file mode 100644
index 00000000000..d50bdad5edf
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/ProgressEvent.cpp
@@ -0,0 +1,71 @@
+/*
+ * Copyright (C) 2007, 2008 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/events/ProgressEvent.h"
+
+#include "core/events/ThreadLocalEventNames.h"
+
+namespace WebCore {
+
+ProgressEventInit::ProgressEventInit()
+ : lengthComputable(false)
+ , loaded(0)
+ , total(0)
+{
+}
+
+ProgressEvent::ProgressEvent()
+ : m_lengthComputable(false)
+ , m_loaded(0)
+ , m_total(0)
+{
+ ScriptWrappable::init(this);
+}
+
+ProgressEvent::ProgressEvent(const AtomicString& type, const ProgressEventInit& initializer)
+ : Event(type, initializer)
+ , m_lengthComputable(initializer.lengthComputable)
+ , m_loaded(initializer.loaded)
+ , m_total(initializer.total)
+{
+ ScriptWrappable::init(this);
+}
+
+ProgressEvent::ProgressEvent(const AtomicString& type, bool lengthComputable, unsigned long long loaded, unsigned long long total)
+ : Event(type, false, true)
+ , m_lengthComputable(lengthComputable)
+ , m_loaded(loaded)
+ , m_total(total)
+{
+ ScriptWrappable::init(this);
+}
+
+const AtomicString& ProgressEvent::interfaceName() const
+{
+ return EventNames::ProgressEvent;
+}
+
+}
diff --git a/chromium/third_party/WebKit/Source/core/events/ProgressEvent.h b/chromium/third_party/WebKit/Source/core/events/ProgressEvent.h
new file mode 100644
index 00000000000..eb5edb72a21
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/ProgressEvent.h
@@ -0,0 +1,74 @@
+/*
+ * Copyright (C) 2007, 2008 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef ProgressEvent_h
+#define ProgressEvent_h
+
+#include "core/events/Event.h"
+
+namespace WebCore {
+
+struct ProgressEventInit : public EventInit {
+ ProgressEventInit();
+
+ bool lengthComputable;
+ unsigned long long loaded;
+ unsigned long long total;
+};
+
+class ProgressEvent : public Event {
+public:
+ static PassRefPtr<ProgressEvent> create()
+ {
+ return adoptRef(new ProgressEvent);
+ }
+ static PassRefPtr<ProgressEvent> create(const AtomicString& type, bool lengthComputable, unsigned long long loaded, unsigned long long total)
+ {
+ return adoptRef(new ProgressEvent(type, lengthComputable, loaded, total));
+ }
+ static PassRefPtr<ProgressEvent> create(const AtomicString& type, const ProgressEventInit& initializer)
+ {
+ return adoptRef(new ProgressEvent(type, initializer));
+ }
+
+ bool lengthComputable() const { return m_lengthComputable; }
+ unsigned long long loaded() const { return m_loaded; }
+ unsigned long long total() const { return m_total; }
+
+ virtual const AtomicString& interfaceName() const;
+
+protected:
+ ProgressEvent();
+ ProgressEvent(const AtomicString& type, bool lengthComputable, unsigned long long loaded, unsigned long long total);
+ ProgressEvent(const AtomicString&, const ProgressEventInit&);
+
+private:
+ bool m_lengthComputable;
+ unsigned long long m_loaded;
+ unsigned long long m_total;
+};
+}
+
+#endif // ProgressEvent_h
diff --git a/chromium/third_party/WebKit/Source/core/events/ProgressEvent.idl b/chromium/third_party/WebKit/Source/core/events/ProgressEvent.idl
new file mode 100644
index 00000000000..8e49d7097c9
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/ProgressEvent.idl
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) 2007 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+[
+ EventConstructor,
+] interface ProgressEvent : Event {
+ [InitializedByEventConstructor] readonly attribute boolean lengthComputable;
+ [InitializedByEventConstructor] readonly attribute unsigned long long loaded;
+ [InitializedByEventConstructor] readonly attribute unsigned long long total;
+};
+
diff --git a/chromium/third_party/WebKit/Source/core/events/RegisteredEventListener.h b/chromium/third_party/WebKit/Source/core/events/RegisteredEventListener.h
new file mode 100644
index 00000000000..5da1fb9ebaf
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/RegisteredEventListener.h
@@ -0,0 +1,51 @@
+/*
+ * Copyright (C) 2001 Peter Kelly (pmk@post.com)
+ * Copyright (C) 2001 Tobias Anton (anton@stud.fbi.fh-darmstadt.de)
+ * Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
+ * Copyright (C) 2003, 2004, 2005, 2006, 2008, 2009 Apple Inc. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ */
+
+#ifndef RegisteredEventListener_h
+#define RegisteredEventListener_h
+
+#include "core/events/EventListener.h"
+#include "wtf/RefPtr.h"
+
+namespace WebCore {
+
+ class RegisteredEventListener {
+ public:
+ RegisteredEventListener(PassRefPtr<EventListener> listener, bool useCapture)
+ : listener(listener)
+ , useCapture(useCapture)
+ {
+ }
+
+ RefPtr<EventListener> listener;
+ bool useCapture;
+ };
+
+ inline bool operator==(const RegisteredEventListener& a, const RegisteredEventListener& b)
+ {
+ return *a.listener == *b.listener && a.useCapture == b.useCapture;
+ }
+
+} // namespace WebCore
+
+#endif // RegisteredEventListener_h
diff --git a/chromium/third_party/WebKit/Source/core/events/ResourceProgressEvent.cpp b/chromium/third_party/WebKit/Source/core/events/ResourceProgressEvent.cpp
new file mode 100644
index 00000000000..59d10d4d27d
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/ResourceProgressEvent.cpp
@@ -0,0 +1,54 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/events/ResourceProgressEvent.h"
+
+namespace WebCore {
+
+ResourceProgressEvent::ResourceProgressEvent()
+{
+ ScriptWrappable::init(this);
+}
+
+ResourceProgressEvent::ResourceProgressEvent(const AtomicString& type, bool lengthComputable, unsigned long long loaded, unsigned long long total, const String& url)
+ : ProgressEvent(type, lengthComputable, loaded, total)
+ , m_url(url)
+{
+ ScriptWrappable::init(this);
+}
+
+const String& ResourceProgressEvent::url() const
+{
+ return m_url;
+}
+
+const AtomicString& ResourceProgressEvent::interfaceName() const
+{
+ return EventNames::ResourceProgressEvent;
+}
+
+}
diff --git a/chromium/third_party/WebKit/Source/core/events/ResourceProgressEvent.h b/chromium/third_party/WebKit/Source/core/events/ResourceProgressEvent.h
new file mode 100644
index 00000000000..9c88b193d38
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/ResourceProgressEvent.h
@@ -0,0 +1,70 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef ResourceProgressEvent_h
+#define ResourceProgressEvent_h
+
+#include "core/events/ProgressEvent.h"
+
+namespace WebCore {
+
+// ResourceProgressEvent is a non-standard class that is simply a ProgressEvent
+// with an additional read-only "url" property containing a string URL. This is
+// used by the Chromium NaCl integration to indicate to which resource the
+// event applies. This is useful because the NaCl integration will download
+// (and translate in the case of PNaCl) multiple binary files. It is not
+// constructable by web content at all, and so does not provide the usual
+// EventInit pattern for Event construction.
+class ResourceProgressEvent : public ProgressEvent {
+public:
+ static PassRefPtr<ResourceProgressEvent> create()
+ {
+ return adoptRef(new ResourceProgressEvent);
+ }
+ static PassRefPtr<ResourceProgressEvent> create(const AtomicString& type, bool lengthComputable, unsigned long long loaded, unsigned long long total, const String& url)
+ {
+ return adoptRef(new ResourceProgressEvent(type, lengthComputable, loaded, total, url));
+ }
+
+ const String& url() const;
+
+ virtual const AtomicString& interfaceName() const;
+
+protected:
+ ResourceProgressEvent();
+ ResourceProgressEvent(const AtomicString& type, bool lengthComputable, unsigned long long loaded, unsigned long long total, const String& url);
+
+private:
+ String m_url;
+};
+
+} // namespace WebCore
+
+#endif // ResourceProgressEvent_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/ResourceProgressEvent.idl b/chromium/third_party/WebKit/Source/core/events/ResourceProgressEvent.idl
index 660b8b16105..660b8b16105 100644
--- a/chromium/third_party/WebKit/Source/core/dom/ResourceProgressEvent.idl
+++ b/chromium/third_party/WebKit/Source/core/events/ResourceProgressEvent.idl
diff --git a/chromium/third_party/WebKit/Source/core/events/ScopedEventQueue.cpp b/chromium/third_party/WebKit/Source/core/events/ScopedEventQueue.cpp
new file mode 100644
index 00000000000..459816941b0
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/ScopedEventQueue.cpp
@@ -0,0 +1,107 @@
+/*
+ * Copyright (C) 2010 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/events/ScopedEventQueue.h"
+
+#include "core/events/Event.h"
+#include "core/events/EventDispatchMediator.h"
+#include "core/events/EventDispatcher.h"
+#include "core/events/EventTarget.h"
+#include "wtf/OwnPtr.h"
+
+namespace WebCore {
+
+ScopedEventQueue* ScopedEventQueue::s_instance = 0;
+
+ScopedEventQueue::ScopedEventQueue()
+ : m_scopingLevel(0)
+{
+}
+
+ScopedEventQueue::~ScopedEventQueue()
+{
+ ASSERT(!m_scopingLevel);
+ ASSERT(!m_queuedEventDispatchMediators.size());
+}
+
+void ScopedEventQueue::initialize()
+{
+ ASSERT(!s_instance);
+ OwnPtr<ScopedEventQueue> instance = adoptPtr(new ScopedEventQueue);
+ s_instance = instance.leakPtr();
+}
+
+void ScopedEventQueue::enqueueEventDispatchMediator(PassRefPtr<EventDispatchMediator> mediator)
+{
+ if (m_scopingLevel)
+ m_queuedEventDispatchMediators.append(mediator);
+ else
+ dispatchEvent(mediator);
+}
+
+void ScopedEventQueue::dispatchAllEvents()
+{
+ Vector<RefPtr<EventDispatchMediator> > queuedEventDispatchMediators;
+ queuedEventDispatchMediators.swap(m_queuedEventDispatchMediators);
+
+ for (size_t i = 0; i < queuedEventDispatchMediators.size(); i++)
+ dispatchEvent(queuedEventDispatchMediators[i].release());
+}
+
+void ScopedEventQueue::dispatchEvent(PassRefPtr<EventDispatchMediator> mediator) const
+{
+ ASSERT(mediator->event()->target());
+ Node* node = mediator->event()->target()->toNode();
+ EventDispatcher::dispatchEvent(node, mediator);
+}
+
+ScopedEventQueue* ScopedEventQueue::instance()
+{
+ if (!s_instance)
+ initialize();
+
+ return s_instance;
+}
+
+void ScopedEventQueue::incrementScopingLevel()
+{
+ m_scopingLevel++;
+}
+
+void ScopedEventQueue::decrementScopingLevel()
+{
+ ASSERT(m_scopingLevel);
+ m_scopingLevel--;
+ if (!m_scopingLevel)
+ dispatchAllEvents();
+}
+
+}
diff --git a/chromium/third_party/WebKit/Source/core/dom/ScopedEventQueue.h b/chromium/third_party/WebKit/Source/core/events/ScopedEventQueue.h
index 4f3c928cb70..4f3c928cb70 100644
--- a/chromium/third_party/WebKit/Source/core/dom/ScopedEventQueue.h
+++ b/chromium/third_party/WebKit/Source/core/events/ScopedEventQueue.h
diff --git a/chromium/third_party/WebKit/Source/core/events/SecurityPolicyViolationEvent.h b/chromium/third_party/WebKit/Source/core/events/SecurityPolicyViolationEvent.h
new file mode 100644
index 00000000000..cc88d03875e
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/SecurityPolicyViolationEvent.h
@@ -0,0 +1,111 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SecurityPolicyViolationEvent_h
+#define SecurityPolicyViolationEvent_h
+
+#include "core/events/Event.h"
+#include "core/events/ThreadLocalEventNames.h"
+
+namespace WebCore {
+
+struct SecurityPolicyViolationEventInit : public EventInit {
+ SecurityPolicyViolationEventInit()
+ {
+ }
+
+ String documentURI;
+ String referrer;
+ String blockedURI;
+ String violatedDirective;
+ String effectiveDirective;
+ String originalPolicy;
+ String sourceFile;
+ int lineNumber;
+ int columnNumber;
+ int statusCode;
+};
+
+class SecurityPolicyViolationEvent : public Event {
+public:
+ static PassRefPtr<SecurityPolicyViolationEvent> create()
+ {
+ return adoptRef(new SecurityPolicyViolationEvent());
+ }
+
+ static PassRefPtr<SecurityPolicyViolationEvent> create(const AtomicString& type, const SecurityPolicyViolationEventInit& initializer)
+ {
+ return adoptRef(new SecurityPolicyViolationEvent(type, initializer));
+ }
+
+ const String& documentURI() const { return m_documentURI; }
+ const String& referrer() const { return m_referrer; }
+ const String& blockedURI() const { return m_blockedURI; }
+ const String& violatedDirective() const { return m_violatedDirective; }
+ const String& effectiveDirective() const { return m_effectiveDirective; }
+ const String& originalPolicy() const { return m_originalPolicy; }
+ const String& sourceFile() const { return m_sourceFile; }
+ int lineNumber() const { return m_lineNumber; }
+ int columnNumber() const { return m_columnNumber; }
+ int statusCode() const { return m_statusCode; }
+
+ virtual const AtomicString& interfaceName() const { return EventNames::SecurityPolicyViolationEvent; }
+
+private:
+ SecurityPolicyViolationEvent()
+ {
+ ScriptWrappable::init(this);
+ }
+
+ SecurityPolicyViolationEvent(const AtomicString& type, const SecurityPolicyViolationEventInit& initializer)
+ : Event(type, initializer)
+ , m_documentURI(initializer.documentURI)
+ , m_referrer(initializer.referrer)
+ , m_blockedURI(initializer.blockedURI)
+ , m_violatedDirective(initializer.violatedDirective)
+ , m_effectiveDirective(initializer.effectiveDirective)
+ , m_originalPolicy(initializer.originalPolicy)
+ , m_sourceFile(initializer.sourceFile)
+ , m_lineNumber(initializer.lineNumber)
+ , m_columnNumber(initializer.columnNumber)
+ , m_statusCode(initializer.statusCode)
+ {
+ ScriptWrappable::init(this);
+ }
+
+ String m_documentURI;
+ String m_referrer;
+ String m_blockedURI;
+ String m_violatedDirective;
+ String m_effectiveDirective;
+ String m_originalPolicy;
+ String m_sourceFile;
+ int m_lineNumber;
+ int m_columnNumber;
+ int m_statusCode;
+};
+
+} // namespace WebCore
+
+#endif // SecurityPolicyViolationEvent_h
diff --git a/chromium/third_party/WebKit/Source/core/events/SecurityPolicyViolationEvent.idl b/chromium/third_party/WebKit/Source/core/events/SecurityPolicyViolationEvent.idl
new file mode 100644
index 00000000000..5ac10f27e01
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/SecurityPolicyViolationEvent.idl
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+[
+ EventConstructor,
+ RuntimeEnabled=ExperimentalContentSecurityPolicyFeatures,
+] interface SecurityPolicyViolationEvent : Event {
+ [InitializedByEventConstructor] readonly attribute DOMString documentURI;
+ [InitializedByEventConstructor] readonly attribute DOMString referrer;
+ [InitializedByEventConstructor] readonly attribute DOMString blockedURI;
+ [InitializedByEventConstructor] readonly attribute DOMString violatedDirective;
+ [InitializedByEventConstructor] readonly attribute DOMString effectiveDirective;
+ [InitializedByEventConstructor] readonly attribute DOMString originalPolicy;
+ [InitializedByEventConstructor] readonly attribute DOMString sourceFile;
+ [InitializedByEventConstructor] readonly attribute long lineNumber;
+ [InitializedByEventConstructor] readonly attribute long columnNumber;
+ [InitializedByEventConstructor] readonly attribute long statusCode;
+};
diff --git a/chromium/third_party/WebKit/Source/core/events/TextEvent.cpp b/chromium/third_party/WebKit/Source/core/events/TextEvent.cpp
new file mode 100644
index 00000000000..2ed8274e580
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/TextEvent.cpp
@@ -0,0 +1,109 @@
+/*
+ * Copyright (C) 2007 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "config.h"
+#include "core/events/TextEvent.h"
+
+#include "core/dom/DocumentFragment.h"
+
+namespace WebCore {
+
+PassRefPtr<TextEvent> TextEvent::create()
+{
+ return adoptRef(new TextEvent);
+}
+
+PassRefPtr<TextEvent> TextEvent::create(PassRefPtr<AbstractView> view, const String& data, TextEventInputType inputType)
+{
+ return adoptRef(new TextEvent(view, data, inputType));
+}
+
+PassRefPtr<TextEvent> TextEvent::createForPlainTextPaste(PassRefPtr<AbstractView> view, const String& data, bool shouldSmartReplace)
+{
+ return adoptRef(new TextEvent(view, data, 0, shouldSmartReplace, false));
+}
+
+PassRefPtr<TextEvent> TextEvent::createForFragmentPaste(PassRefPtr<AbstractView> view, PassRefPtr<DocumentFragment> data, bool shouldSmartReplace, bool shouldMatchStyle)
+{
+ return adoptRef(new TextEvent(view, "", data, shouldSmartReplace, shouldMatchStyle));
+}
+
+PassRefPtr<TextEvent> TextEvent::createForDrop(PassRefPtr<AbstractView> view, const String& data)
+{
+ return adoptRef(new TextEvent(view, data, TextEventInputDrop));
+}
+
+TextEvent::TextEvent()
+ : m_inputType(TextEventInputKeyboard)
+ , m_shouldSmartReplace(false)
+ , m_shouldMatchStyle(false)
+{
+ ScriptWrappable::init(this);
+}
+
+TextEvent::TextEvent(PassRefPtr<AbstractView> view, const String& data, TextEventInputType inputType)
+ : UIEvent(EventTypeNames::textInput, true, true, view, 0)
+ , m_inputType(inputType)
+ , m_data(data)
+ , m_pastingFragment(0)
+ , m_shouldSmartReplace(false)
+ , m_shouldMatchStyle(false)
+{
+ ScriptWrappable::init(this);
+}
+
+TextEvent::TextEvent(PassRefPtr<AbstractView> view, const String& data, PassRefPtr<DocumentFragment> pastingFragment,
+ bool shouldSmartReplace, bool shouldMatchStyle)
+ : UIEvent(EventTypeNames::textInput, true, true, view, 0)
+ , m_inputType(TextEventInputPaste)
+ , m_data(data)
+ , m_pastingFragment(pastingFragment)
+ , m_shouldSmartReplace(shouldSmartReplace)
+ , m_shouldMatchStyle(shouldMatchStyle)
+{
+ ScriptWrappable::init(this);
+}
+
+TextEvent::~TextEvent()
+{
+}
+
+void TextEvent::initTextEvent(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<AbstractView> view, const String& data)
+{
+ if (dispatched())
+ return;
+
+ initUIEvent(type, canBubble, cancelable, view, 0);
+
+ m_data = data;
+}
+
+const AtomicString& TextEvent::interfaceName() const
+{
+ return EventNames::TextEvent;
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/events/TextEvent.h b/chromium/third_party/WebKit/Source/core/events/TextEvent.h
new file mode 100644
index 00000000000..6c2f256cf14
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/TextEvent.h
@@ -0,0 +1,89 @@
+/*
+ * Copyright (C) 2007, 2008 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#ifndef TextEvent_h
+#define TextEvent_h
+
+#include "core/events/TextEventInputType.h"
+#include "core/events/ThreadLocalEventNames.h"
+#include "core/events/UIEvent.h"
+
+namespace WebCore {
+
+ class DocumentFragment;
+
+ class TextEvent : public UIEvent {
+ public:
+
+ static PassRefPtr<TextEvent> create();
+ static PassRefPtr<TextEvent> create(PassRefPtr<AbstractView>, const String& data, TextEventInputType = TextEventInputKeyboard);
+ static PassRefPtr<TextEvent> createForPlainTextPaste(PassRefPtr<AbstractView> view, const String& data, bool shouldSmartReplace);
+ static PassRefPtr<TextEvent> createForFragmentPaste(PassRefPtr<AbstractView> view, PassRefPtr<DocumentFragment> data, bool shouldSmartReplace, bool shouldMatchStyle);
+ static PassRefPtr<TextEvent> createForDrop(PassRefPtr<AbstractView> view, const String& data);
+
+ virtual ~TextEvent();
+
+ void initTextEvent(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<AbstractView>, const String& data);
+
+ String data() const { return m_data; }
+
+ virtual const AtomicString& interfaceName() const;
+
+ bool isLineBreak() const { return m_inputType == TextEventInputLineBreak; }
+ bool isComposition() const { return m_inputType == TextEventInputComposition; }
+ bool isBackTab() const { return m_inputType == TextEventInputBackTab; }
+ bool isPaste() const { return m_inputType == TextEventInputPaste; }
+ bool isDrop() const { return m_inputType == TextEventInputDrop; }
+
+ bool shouldSmartReplace() const { return m_shouldSmartReplace; }
+ bool shouldMatchStyle() const { return m_shouldMatchStyle; }
+ DocumentFragment* pastingFragment() const { return m_pastingFragment.get(); }
+
+ private:
+ TextEvent();
+
+ TextEvent(PassRefPtr<AbstractView>, const String& data, TextEventInputType = TextEventInputKeyboard);
+ TextEvent(PassRefPtr<AbstractView>, const String& data, PassRefPtr<DocumentFragment>,
+ bool shouldSmartReplace, bool shouldMatchStyle);
+
+ TextEventInputType m_inputType;
+ String m_data;
+
+ RefPtr<DocumentFragment> m_pastingFragment;
+ bool m_shouldSmartReplace;
+ bool m_shouldMatchStyle;
+ };
+
+inline bool isTextEvent(const Event& event)
+{
+ return event.type() == EventTypeNames::textInput && event.hasInterface(EventNames::TextEvent);
+}
+
+DEFINE_TYPE_CASTS(TextEvent, Event, event, isTextEvent(*event), isTextEvent(event));
+
+} // namespace WebCore
+
+#endif // TextEvent_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/TextEvent.idl b/chromium/third_party/WebKit/Source/core/events/TextEvent.idl
index 3d03594e043..3d03594e043 100644
--- a/chromium/third_party/WebKit/Source/core/dom/TextEvent.idl
+++ b/chromium/third_party/WebKit/Source/core/events/TextEvent.idl
diff --git a/chromium/third_party/WebKit/Source/core/dom/TextEventInputType.h b/chromium/third_party/WebKit/Source/core/events/TextEventInputType.h
index fc98a6c791e..fc98a6c791e 100644
--- a/chromium/third_party/WebKit/Source/core/dom/TextEventInputType.h
+++ b/chromium/third_party/WebKit/Source/core/events/TextEventInputType.h
diff --git a/chromium/third_party/WebKit/Source/core/events/ThreadLocalEventNames.h b/chromium/third_party/WebKit/Source/core/events/ThreadLocalEventNames.h
new file mode 100644
index 00000000000..efde7b6d451
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/ThreadLocalEventNames.h
@@ -0,0 +1,44 @@
+/*
+ * Copyright (C) 2005, 2007 Apple Inc. All rights reserved.
+ * Copyright (C) 2006 Jon Shier (jshier@iastate.edu)
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ */
+
+#ifndef ThreadLocalEventNames_h
+#define ThreadLocalEventNames_h
+
+#include "EventInterfaces.h"
+#include "EventNames.h"
+#include "EventTargetInterfaces.h"
+#include "EventTargetNames.h"
+#include "EventTypeNames.h"
+#include "wtf/text/AtomicString.h"
+
+namespace WebCore {
+
+inline bool isTouchEventType(const AtomicString& eventType)
+{
+ return eventType == EventTypeNames::touchstart
+ || eventType == EventTypeNames::touchmove
+ || eventType == EventTypeNames::touchend
+ || eventType == EventTypeNames::touchcancel;
+}
+
+}
+
+#endif
diff --git a/chromium/third_party/WebKit/Source/core/events/TouchEvent.cpp b/chromium/third_party/WebKit/Source/core/events/TouchEvent.cpp
new file mode 100644
index 00000000000..f0527eda7f4
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/TouchEvent.cpp
@@ -0,0 +1,113 @@
+/*
+ * Copyright 2008, The Android Open Source Project
+ * Copyright (C) 2012 Research In Motion Limited. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+
+#include "core/events/TouchEvent.h"
+
+#include "core/events/EventDispatcher.h"
+#include "core/events/EventRetargeter.h"
+#include "core/events/ThreadLocalEventNames.h"
+
+namespace WebCore {
+
+TouchEvent::TouchEvent()
+{
+ ScriptWrappable::init(this);
+}
+
+TouchEvent::TouchEvent(TouchList* touches, TouchList* targetTouches,
+ TouchList* changedTouches, const AtomicString& type,
+ PassRefPtr<AbstractView> view, int screenX, int screenY, int pageX, int pageY,
+ bool ctrlKey, bool altKey, bool shiftKey, bool metaKey)
+ : MouseRelatedEvent(type, true, true, view, 0, IntPoint(screenX, screenY),
+ IntPoint(pageX, pageY),
+ IntPoint(0, 0),
+ ctrlKey, altKey, shiftKey, metaKey)
+ , m_touches(touches)
+ , m_targetTouches(targetTouches)
+ , m_changedTouches(changedTouches)
+{
+ ScriptWrappable::init(this);
+}
+
+TouchEvent::~TouchEvent()
+{
+}
+
+void TouchEvent::initTouchEvent(TouchList* touches, TouchList* targetTouches,
+ TouchList* changedTouches, const AtomicString& type,
+ PassRefPtr<AbstractView> view, int screenX, int screenY, int clientX, int clientY,
+ bool ctrlKey, bool altKey, bool shiftKey, bool metaKey)
+{
+ if (dispatched())
+ return;
+
+ initUIEvent(type, true, true, view, 0);
+
+ m_touches = touches;
+ m_targetTouches = targetTouches;
+ m_changedTouches = changedTouches;
+ m_screenLocation = IntPoint(screenX, screenY);
+ m_ctrlKey = ctrlKey;
+ m_altKey = altKey;
+ m_shiftKey = shiftKey;
+ m_metaKey = metaKey;
+ initCoordinates(IntPoint(clientX, clientY));
+}
+
+const AtomicString& TouchEvent::interfaceName() const
+{
+ return EventNames::TouchEvent;
+}
+
+bool TouchEvent::isTouchEvent() const
+{
+ return true;
+}
+
+PassRefPtr<TouchEventDispatchMediator> TouchEventDispatchMediator::create(PassRefPtr<TouchEvent> touchEvent)
+{
+ return adoptRef(new TouchEventDispatchMediator(touchEvent));
+}
+
+TouchEventDispatchMediator::TouchEventDispatchMediator(PassRefPtr<TouchEvent> touchEvent)
+ : EventDispatchMediator(touchEvent)
+{
+}
+
+TouchEvent* TouchEventDispatchMediator::event() const
+{
+ return toTouchEvent(EventDispatchMediator::event());
+}
+
+bool TouchEventDispatchMediator::dispatchEvent(EventDispatcher* dispatcher) const
+{
+ EventRetargeter::adjustForTouchEvent(dispatcher->node(), *event());
+ return dispatcher->dispatch();
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/events/TouchEvent.h b/chromium/third_party/WebKit/Source/core/events/TouchEvent.h
new file mode 100644
index 00000000000..25c6f610c63
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/TouchEvent.h
@@ -0,0 +1,100 @@
+/*
+ * Copyright 2008, The Android Open Source Project
+ * Copyright (C) 2012 Research In Motion Limited. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef TouchEvent_h
+#define TouchEvent_h
+
+#include "core/events/EventDispatchMediator.h"
+#include "core/events/MouseRelatedEvent.h"
+#include "core/dom/TouchList.h"
+
+namespace WebCore {
+
+class TouchEvent : public MouseRelatedEvent {
+public:
+ virtual ~TouchEvent();
+
+ static PassRefPtr<TouchEvent> create()
+ {
+ return adoptRef(new TouchEvent);
+ }
+ static PassRefPtr<TouchEvent> create(TouchList* touches,
+ TouchList* targetTouches, TouchList* changedTouches,
+ const AtomicString& type, PassRefPtr<AbstractView> view,
+ int screenX, int screenY, int pageX, int pageY,
+ bool ctrlKey, bool altKey, bool shiftKey, bool metaKey)
+ {
+ return adoptRef(new TouchEvent(touches, targetTouches, changedTouches,
+ type, view, screenX, screenY, pageX, pageY,
+ ctrlKey, altKey, shiftKey, metaKey));
+ }
+
+ void initTouchEvent(TouchList* touches, TouchList* targetTouches,
+ TouchList* changedTouches, const AtomicString& type,
+ PassRefPtr<AbstractView> view, int screenX, int screenY,
+ int clientX, int clientY,
+ bool ctrlKey, bool altKey, bool shiftKey, bool metaKey);
+
+ TouchList* touches() const { return m_touches.get(); }
+ TouchList* targetTouches() const { return m_targetTouches.get(); }
+ TouchList* changedTouches() const { return m_changedTouches.get(); }
+
+ void setTouches(PassRefPtr<TouchList> touches) { m_touches = touches; }
+ void setTargetTouches(PassRefPtr<TouchList> targetTouches) { m_targetTouches = targetTouches; }
+ void setChangedTouches(PassRefPtr<TouchList> changedTouches) { m_changedTouches = changedTouches; }
+
+ virtual bool isTouchEvent() const OVERRIDE;
+
+ virtual const AtomicString& interfaceName() const;
+
+private:
+ TouchEvent();
+ TouchEvent(TouchList* touches, TouchList* targetTouches,
+ TouchList* changedTouches, const AtomicString& type,
+ PassRefPtr<AbstractView>, int screenX, int screenY, int pageX,
+ int pageY,
+ bool ctrlKey, bool altKey, bool shiftKey, bool metaKey);
+
+ RefPtr<TouchList> m_touches;
+ RefPtr<TouchList> m_targetTouches;
+ RefPtr<TouchList> m_changedTouches;
+};
+
+class TouchEventDispatchMediator : public EventDispatchMediator {
+public:
+ static PassRefPtr<TouchEventDispatchMediator> create(PassRefPtr<TouchEvent>);
+
+private:
+ explicit TouchEventDispatchMediator(PassRefPtr<TouchEvent>);
+ TouchEvent* event() const;
+ virtual bool dispatchEvent(EventDispatcher*) const OVERRIDE;
+};
+
+DEFINE_EVENT_TYPE_CASTS(TouchEvent);
+
+} // namespace WebCore
+
+#endif // TouchEvent_h
diff --git a/chromium/third_party/WebKit/Source/core/dom/TouchEvent.idl b/chromium/third_party/WebKit/Source/core/events/TouchEvent.idl
index f4b396e01f1..f4b396e01f1 100644
--- a/chromium/third_party/WebKit/Source/core/dom/TouchEvent.idl
+++ b/chromium/third_party/WebKit/Source/core/events/TouchEvent.idl
diff --git a/chromium/third_party/WebKit/Source/core/events/TransitionEvent.cpp b/chromium/third_party/WebKit/Source/core/events/TransitionEvent.cpp
new file mode 100644
index 00000000000..dfc32fd33e1
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/TransitionEvent.cpp
@@ -0,0 +1,87 @@
+/*
+ * Copyright (C) 2007, 2008 Apple Inc. All rights reserved.
+ * Copyright (C) 2013 Intel Corporation. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/events/TransitionEvent.h"
+
+#include "core/events/ThreadLocalEventNames.h"
+
+namespace WebCore {
+
+TransitionEventInit::TransitionEventInit()
+ : elapsedTime(0)
+{
+}
+
+TransitionEvent::TransitionEvent()
+ : m_elapsedTime(0)
+{
+ ScriptWrappable::init(this);
+}
+
+TransitionEvent::TransitionEvent(const AtomicString& type, const String& propertyName, double elapsedTime, const String& pseudoElement)
+ : Event(type, true, true)
+ , m_propertyName(propertyName)
+ , m_elapsedTime(elapsedTime)
+ , m_pseudoElement(pseudoElement)
+{
+ ScriptWrappable::init(this);
+}
+
+TransitionEvent::TransitionEvent(const AtomicString& type, const TransitionEventInit& initializer)
+ : Event(type, initializer)
+ , m_propertyName(initializer.propertyName)
+ , m_elapsedTime(initializer.elapsedTime)
+ , m_pseudoElement(initializer.pseudoElement)
+{
+ ScriptWrappable::init(this);
+}
+
+TransitionEvent::~TransitionEvent()
+{
+}
+
+const String& TransitionEvent::propertyName() const
+{
+ return m_propertyName;
+}
+
+double TransitionEvent::elapsedTime() const
+{
+ return m_elapsedTime;
+}
+
+const String& TransitionEvent::pseudoElement() const
+{
+ return m_pseudoElement;
+}
+
+const AtomicString& TransitionEvent::interfaceName() const
+{
+ return EventNames::TransitionEvent;
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/events/TransitionEvent.h b/chromium/third_party/WebKit/Source/core/events/TransitionEvent.h
new file mode 100644
index 00000000000..e1d5fa26082
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/TransitionEvent.h
@@ -0,0 +1,78 @@
+/*
+ * Copyright (C) 2007, 2008 Apple Inc. All rights reserved.
+ * Copyright (C) 2013 Intel Corporation. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef TransitionEvent_h
+#define TransitionEvent_h
+
+#include "core/events/Event.h"
+
+namespace WebCore {
+
+struct TransitionEventInit : public EventInit {
+ TransitionEventInit();
+
+ String propertyName;
+ double elapsedTime;
+ String pseudoElement;
+};
+
+class TransitionEvent : public Event {
+public:
+ static PassRefPtr<TransitionEvent> create()
+ {
+ return adoptRef(new TransitionEvent);
+ }
+ static PassRefPtr<TransitionEvent> create(const AtomicString& type, const String& propertyName, double elapsedTime, const String& pseudoElement)
+ {
+ return adoptRef(new TransitionEvent(type, propertyName, elapsedTime, pseudoElement));
+ }
+ static PassRefPtr<TransitionEvent> create(const AtomicString& type, const TransitionEventInit& initializer)
+ {
+ return adoptRef(new TransitionEvent(type, initializer));
+ }
+
+ virtual ~TransitionEvent();
+
+ const String& propertyName() const;
+ double elapsedTime() const;
+ const String& pseudoElement() const;
+
+ virtual const AtomicString& interfaceName() const;
+
+private:
+ TransitionEvent();
+ TransitionEvent(const AtomicString& type, const String& propertyName, double elapsedTime, const String& pseudoElement);
+ TransitionEvent(const AtomicString& type, const TransitionEventInit& initializer);
+
+ String m_propertyName;
+ double m_elapsedTime;
+ String m_pseudoElement;
+};
+
+} // namespace WebCore
+
+#endif // TransitionEvent_h
+
diff --git a/chromium/third_party/WebKit/Source/core/events/TransitionEvent.idl b/chromium/third_party/WebKit/Source/core/events/TransitionEvent.idl
new file mode 100644
index 00000000000..94ee353b285
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/TransitionEvent.idl
@@ -0,0 +1,34 @@
+/*
+ * Copyright (C) 2007, 2008 Apple Inc. All rights reserved.
+ * Copyright (C) 2013 Intel Corporation. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+[
+ EventConstructor,
+] interface TransitionEvent : Event {
+ [InitializedByEventConstructor] readonly attribute DOMString propertyName;
+ [InitializedByEventConstructor] readonly attribute double elapsedTime;
+ [InitializedByEventConstructor] readonly attribute DOMString pseudoElement;
+};
+
diff --git a/chromium/third_party/WebKit/Source/core/events/UIEvent.cpp b/chromium/third_party/WebKit/Source/core/events/UIEvent.cpp
new file mode 100644
index 00000000000..6a0db63dac8
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/UIEvent.cpp
@@ -0,0 +1,117 @@
+/*
+ * Copyright (C) 2001 Peter Kelly (pmk@post.com)
+ * Copyright (C) 2001 Tobias Anton (anton@stud.fbi.fh-darmstadt.de)
+ * Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
+ * Copyright (C) 2003, 2005, 2006, 2008 Apple Inc. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#include "config.h"
+#include "core/events/UIEvent.h"
+
+
+namespace WebCore {
+
+UIEventInit::UIEventInit()
+ : view(0)
+ , detail(0)
+{
+}
+
+UIEvent::UIEvent()
+ : m_detail(0)
+{
+ ScriptWrappable::init(this);
+}
+
+UIEvent::UIEvent(const AtomicString& eventType, bool canBubbleArg, bool cancelableArg, PassRefPtr<AbstractView> viewArg, int detailArg)
+ : Event(eventType, canBubbleArg, cancelableArg)
+ , m_view(viewArg)
+ , m_detail(detailArg)
+{
+ ScriptWrappable::init(this);
+}
+
+UIEvent::UIEvent(const AtomicString& eventType, const UIEventInit& initializer)
+ : Event(eventType, initializer)
+ , m_view(initializer.view)
+ , m_detail(initializer.detail)
+{
+ ScriptWrappable::init(this);
+}
+
+UIEvent::~UIEvent()
+{
+}
+
+void UIEvent::initUIEvent(const AtomicString& typeArg, bool canBubbleArg, bool cancelableArg, PassRefPtr<AbstractView> viewArg, int detailArg)
+{
+ if (dispatched())
+ return;
+
+ initEvent(typeArg, canBubbleArg, cancelableArg);
+
+ m_view = viewArg;
+ m_detail = detailArg;
+}
+
+bool UIEvent::isUIEvent() const
+{
+ return true;
+}
+
+const AtomicString& UIEvent::interfaceName() const
+{
+ return EventNames::UIEvent;
+}
+
+int UIEvent::keyCode() const
+{
+ return 0;
+}
+
+int UIEvent::charCode() const
+{
+ return 0;
+}
+
+int UIEvent::layerX()
+{
+ return 0;
+}
+
+int UIEvent::layerY()
+{
+ return 0;
+}
+
+int UIEvent::pageX() const
+{
+ return 0;
+}
+
+int UIEvent::pageY() const
+{
+ return 0;
+}
+
+int UIEvent::which() const
+{
+ return 0;
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/events/UIEvent.h b/chromium/third_party/WebKit/Source/core/events/UIEvent.h
new file mode 100644
index 00000000000..27503311307
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/UIEvent.h
@@ -0,0 +1,90 @@
+/*
+ * Copyright (C) 2001 Peter Kelly (pmk@post.com)
+ * Copyright (C) 2001 Tobias Anton (anton@stud.fbi.fh-darmstadt.de)
+ * Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
+ * Copyright (C) 2003, 2004, 2005, 2006, 2008 Apple Inc. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ */
+
+#ifndef UIEvent_h
+#define UIEvent_h
+
+#include "core/events/Event.h"
+#include "core/events/EventDispatchMediator.h"
+#include "core/frame/DOMWindow.h"
+
+namespace WebCore {
+
+typedef DOMWindow AbstractView;
+
+struct UIEventInit : public EventInit {
+ UIEventInit();
+
+ RefPtr<AbstractView> view;
+ int detail;
+};
+
+class UIEvent : public Event {
+public:
+ static PassRefPtr<UIEvent> create()
+ {
+ return adoptRef(new UIEvent);
+ }
+ static PassRefPtr<UIEvent> create(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<AbstractView> view, int detail)
+ {
+ return adoptRef(new UIEvent(type, canBubble, cancelable, view, detail));
+ }
+ static PassRefPtr<UIEvent> create(const AtomicString& type, const UIEventInit& initializer)
+ {
+ return adoptRef(new UIEvent(type, initializer));
+ }
+ virtual ~UIEvent();
+
+ void initUIEvent(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<AbstractView>, int detail);
+
+ AbstractView* view() const { return m_view.get(); }
+ AbstractView* view(bool& isNull) const { isNull = !m_view; return m_view.get(); }
+ int detail() const { return m_detail; }
+
+ virtual const AtomicString& interfaceName() const;
+ virtual bool isUIEvent() const;
+
+ virtual int keyCode() const;
+ virtual int charCode() const;
+
+ virtual int layerX();
+ virtual int layerY();
+
+ virtual int pageX() const;
+ virtual int pageY() const;
+
+ virtual int which() const;
+
+protected:
+ UIEvent();
+ UIEvent(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<AbstractView>, int detail);
+ UIEvent(const AtomicString&, const UIEventInit&);
+
+private:
+ RefPtr<AbstractView> m_view;
+ int m_detail;
+};
+
+} // namespace WebCore
+
+#endif // UIEvent_h
diff --git a/chromium/third_party/WebKit/Source/core/events/UIEvent.idl b/chromium/third_party/WebKit/Source/core/events/UIEvent.idl
new file mode 100644
index 00000000000..df8ec347ddc
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/UIEvent.idl
@@ -0,0 +1,41 @@
+/*
+ * Copyright (C) 2006 Apple Computer, Inc.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+[
+ EventConstructor,
+] interface UIEvent : Event {
+ [InitializedByEventConstructor] readonly attribute Window? view;
+ [InitializedByEventConstructor] readonly attribute long detail;
+
+ void initUIEvent([Default=Undefined] optional DOMString type,
+ [Default=Undefined] optional boolean canBubble,
+ [Default=Undefined] optional boolean cancelable,
+ [Default=Undefined] optional Window view,
+ [Default=Undefined] optional long detail);
+
+ // extensions
+ readonly attribute long keyCode;
+ readonly attribute long charCode;
+ readonly attribute long layerX;
+ readonly attribute long layerY;
+ readonly attribute long pageX;
+ readonly attribute long pageY;
+ readonly attribute long which;
+};
+
diff --git a/chromium/third_party/WebKit/Source/core/events/UIEventWithKeyState.cpp b/chromium/third_party/WebKit/Source/core/events/UIEventWithKeyState.cpp
new file mode 100644
index 00000000000..9c8ab576c58
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/UIEventWithKeyState.cpp
@@ -0,0 +1,34 @@
+/*
+ * Copyright (C) 2006 Apple Computer, Inc.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ */
+
+#include "config.h"
+#include "core/events/UIEventWithKeyState.h"
+
+namespace WebCore {
+
+UIEventWithKeyState* findEventWithKeyState(Event* event)
+{
+ for (Event* e = event; e; e = e->underlyingEvent())
+ if (e->isKeyboardEvent() || e->isMouseEvent())
+ return static_cast<UIEventWithKeyState*>(e);
+ return 0;
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/events/UIEventWithKeyState.h b/chromium/third_party/WebKit/Source/core/events/UIEventWithKeyState.h
new file mode 100644
index 00000000000..29c8c190044
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/UIEventWithKeyState.h
@@ -0,0 +1,68 @@
+/*
+ * Copyright (C) 2001 Peter Kelly (pmk@post.com)
+ * Copyright (C) 2001 Tobias Anton (anton@stud.fbi.fh-darmstadt.de)
+ * Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
+ * Copyright (C) 2003, 2004, 2005, 2006, 2008 Apple Inc. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ */
+
+#ifndef UIEventWithKeyState_h
+#define UIEventWithKeyState_h
+
+#include "core/events/UIEvent.h"
+
+namespace WebCore {
+
+ class UIEventWithKeyState : public UIEvent {
+ public:
+ bool ctrlKey() const { return m_ctrlKey; }
+ bool shiftKey() const { return m_shiftKey; }
+ bool altKey() const { return m_altKey; }
+ bool metaKey() const { return m_metaKey; }
+
+ protected:
+ UIEventWithKeyState()
+ : m_ctrlKey(false)
+ , m_altKey(false)
+ , m_shiftKey(false)
+ , m_metaKey(false)
+ {
+ }
+
+ UIEventWithKeyState(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<AbstractView> view,
+ int detail, bool ctrlKey, bool altKey, bool shiftKey, bool metaKey)
+ : UIEvent(type, canBubble, cancelable, view, detail)
+ , m_ctrlKey(ctrlKey)
+ , m_altKey(altKey)
+ , m_shiftKey(shiftKey)
+ , m_metaKey(metaKey)
+ {
+ }
+
+ // Expose these so init functions can set them.
+ bool m_ctrlKey : 1;
+ bool m_altKey : 1;
+ bool m_shiftKey : 1;
+ bool m_metaKey : 1;
+ };
+
+ UIEventWithKeyState* findEventWithKeyState(Event*);
+
+} // namespace WebCore
+
+#endif // UIEventWithKeyState_h
diff --git a/chromium/third_party/WebKit/Source/core/events/WebKitAnimationEvent.cpp b/chromium/third_party/WebKit/Source/core/events/WebKitAnimationEvent.cpp
new file mode 100644
index 00000000000..cefe08f766c
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/WebKitAnimationEvent.cpp
@@ -0,0 +1,80 @@
+/*
+ * Copyright (C) 2007, 2008 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/events/WebKitAnimationEvent.h"
+
+#include "core/events/ThreadLocalEventNames.h"
+
+namespace WebCore {
+
+WebKitAnimationEventInit::WebKitAnimationEventInit()
+ : animationName()
+ , elapsedTime(0.0)
+{
+}
+
+WebKitAnimationEvent::WebKitAnimationEvent()
+ : m_elapsedTime(0.0)
+{
+ ScriptWrappable::init(this);
+}
+
+WebKitAnimationEvent::WebKitAnimationEvent(const AtomicString& type, const WebKitAnimationEventInit& initializer)
+ : Event(type, initializer)
+ , m_animationName(initializer.animationName)
+ , m_elapsedTime(initializer.elapsedTime)
+{
+ ScriptWrappable::init(this);
+}
+
+WebKitAnimationEvent::WebKitAnimationEvent(const AtomicString& type, const String& animationName, double elapsedTime)
+ : Event(type, true, true)
+ , m_animationName(animationName)
+ , m_elapsedTime(elapsedTime)
+{
+ ScriptWrappable::init(this);
+}
+
+WebKitAnimationEvent::~WebKitAnimationEvent()
+{
+}
+
+const String& WebKitAnimationEvent::animationName() const
+{
+ return m_animationName;
+}
+
+double WebKitAnimationEvent::elapsedTime() const
+{
+ return m_elapsedTime;
+}
+
+const AtomicString& WebKitAnimationEvent::interfaceName() const
+{
+ return EventNames::WebKitAnimationEvent;
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/events/WebKitAnimationEvent.h b/chromium/third_party/WebKit/Source/core/events/WebKitAnimationEvent.h
new file mode 100644
index 00000000000..b91c98005bd
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/WebKitAnimationEvent.h
@@ -0,0 +1,76 @@
+/*
+ * Copyright (C) 2007, 2008 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef WebKitAnimationEvent_h
+#define WebKitAnimationEvent_h
+
+#include "core/events/Event.h"
+
+namespace WebCore {
+
+// FIXME : This class has a WebKit prefix on purpose so we can use the EventAliases system. When the
+// runtime flag of unprefixed animation will be removed we can rename that class and do the same as
+// the CSS Transitions.
+struct WebKitAnimationEventInit : public EventInit {
+ WebKitAnimationEventInit();
+
+ String animationName;
+ double elapsedTime;
+};
+
+class WebKitAnimationEvent : public Event {
+public:
+ static PassRefPtr<WebKitAnimationEvent> create()
+ {
+ return adoptRef(new WebKitAnimationEvent);
+ }
+ static PassRefPtr<WebKitAnimationEvent> create(const AtomicString& type, const String& animationName, double elapsedTime)
+ {
+ return adoptRef(new WebKitAnimationEvent(type, animationName, elapsedTime));
+ }
+ static PassRefPtr<WebKitAnimationEvent> create(const AtomicString& type, const WebKitAnimationEventInit& initializer)
+ {
+ return adoptRef(new WebKitAnimationEvent(type, initializer));
+ }
+
+ virtual ~WebKitAnimationEvent();
+
+ const String& animationName() const;
+ double elapsedTime() const;
+
+ virtual const AtomicString& interfaceName() const;
+
+private:
+ WebKitAnimationEvent();
+ WebKitAnimationEvent(const AtomicString& type, const String& animationName, double elapsedTime);
+ WebKitAnimationEvent(const AtomicString&, const WebKitAnimationEventInit&);
+
+ String m_animationName;
+ double m_elapsedTime;
+};
+
+} // namespace WebCore
+
+#endif // WebKitAnimationEvent_h
diff --git a/chromium/third_party/WebKit/Source/core/events/WebKitAnimationEvent.idl b/chromium/third_party/WebKit/Source/core/events/WebKitAnimationEvent.idl
new file mode 100644
index 00000000000..44f32660bf8
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/WebKitAnimationEvent.idl
@@ -0,0 +1,32 @@
+/*
+ * Copyright (C) 2007, 2008 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+[
+ EventConstructor,
+] interface WebKitAnimationEvent : Event {
+ [InitializedByEventConstructor] readonly attribute DOMString animationName;
+ [InitializedByEventConstructor] readonly attribute double elapsedTime;
+};
+
diff --git a/chromium/third_party/WebKit/Source/core/events/WheelEvent.cpp b/chromium/third_party/WebKit/Source/core/events/WheelEvent.cpp
new file mode 100644
index 00000000000..0c23299b6fc
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/WheelEvent.cpp
@@ -0,0 +1,160 @@
+/*
+ * Copyright (C) 2001 Peter Kelly (pmk@post.com)
+ * Copyright (C) 2001 Tobias Anton (anton@stud.fbi.fh-darmstadt.de)
+ * Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
+ * Copyright (C) 2003, 2005, 2006, 2008, 2010 Apple Inc. All rights reserved.
+ * Copyright (C) 2013 Samsung Electronics. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#include "config.h"
+#include "core/events/WheelEvent.h"
+
+#include "core/dom/Clipboard.h"
+#include "core/events/ThreadLocalEventNames.h"
+#include "platform/PlatformWheelEvent.h"
+
+namespace WebCore {
+
+WheelEventInit::WheelEventInit()
+ : deltaX(0)
+ , deltaY(0)
+ , deltaZ(0)
+ , wheelDeltaX(0)
+ , wheelDeltaY(0)
+ , deltaMode(WheelEvent::DOM_DELTA_PIXEL)
+{
+}
+
+WheelEvent::WheelEvent()
+ : m_deltaX(0)
+ , m_deltaY(0)
+ , m_deltaZ(0)
+ , m_deltaMode(DOM_DELTA_PIXEL)
+ , m_directionInvertedFromDevice(false)
+{
+ ScriptWrappable::init(this);
+}
+
+WheelEvent::WheelEvent(const AtomicString& type, const WheelEventInit& initializer)
+ : MouseEvent(type, initializer)
+ , m_wheelDelta(initializer.wheelDeltaX ? initializer.wheelDeltaX : -initializer.deltaX, initializer.wheelDeltaY ? initializer.wheelDeltaY : -initializer.deltaY)
+ , m_deltaX(initializer.deltaX ? initializer.deltaX : -initializer.wheelDeltaX)
+ , m_deltaY(initializer.deltaY ? initializer.deltaY : -initializer.wheelDeltaY)
+ , m_deltaZ(initializer.deltaZ)
+ , m_deltaMode(initializer.deltaMode)
+{
+ ScriptWrappable::init(this);
+}
+
+WheelEvent::WheelEvent(const FloatPoint& wheelTicks, const FloatPoint& rawDelta, unsigned deltaMode,
+ PassRefPtr<AbstractView> view, const IntPoint& screenLocation, const IntPoint& pageLocation,
+ bool ctrlKey, bool altKey, bool shiftKey, bool metaKey, bool directionInvertedFromDevice)
+ : MouseEvent(EventTypeNames::wheel,
+ true, true, view, 0, screenLocation.x(), screenLocation.y(),
+ pageLocation.x(), pageLocation.y(),
+ 0, 0,
+ ctrlKey, altKey, shiftKey, metaKey, 0, 0, 0, false)
+ , m_wheelDelta(wheelTicks.x() * TickMultiplier, wheelTicks.y() * TickMultiplier)
+ , m_deltaX(-rawDelta.x())
+ , m_deltaY(-rawDelta.y())
+ , m_deltaZ(0)
+ , m_deltaMode(deltaMode)
+ , m_directionInvertedFromDevice(directionInvertedFromDevice)
+{
+ ScriptWrappable::init(this);
+}
+
+void WheelEvent::initWheelEvent(int rawDeltaX, int rawDeltaY, PassRefPtr<AbstractView> view,
+ int screenX, int screenY, int pageX, int pageY,
+ bool ctrlKey, bool altKey, bool shiftKey, bool metaKey)
+{
+ if (dispatched())
+ return;
+
+ initUIEvent(EventTypeNames::wheel, true, true, view, 0);
+
+ m_screenLocation = IntPoint(screenX, screenY);
+ m_ctrlKey = ctrlKey;
+ m_altKey = altKey;
+ m_shiftKey = shiftKey;
+ m_metaKey = metaKey;
+
+ m_wheelDelta = IntPoint(rawDeltaX * TickMultiplier, rawDeltaY * TickMultiplier);
+ m_deltaX = -rawDeltaX;
+ m_deltaY = -rawDeltaY;
+ m_deltaMode = DOM_DELTA_PIXEL;
+ m_directionInvertedFromDevice = false;
+
+ initCoordinates(IntPoint(pageX, pageY));
+}
+
+void WheelEvent::initWebKitWheelEvent(int rawDeltaX, int rawDeltaY, PassRefPtr<AbstractView> view,
+ int screenX, int screenY, int pageX, int pageY,
+ bool ctrlKey, bool altKey, bool shiftKey, bool metaKey)
+{
+ initWheelEvent(rawDeltaX, rawDeltaY, view, screenX, screenY, pageX, pageY,
+ ctrlKey, altKey, shiftKey, metaKey);
+}
+
+const AtomicString& WheelEvent::interfaceName() const
+{
+ return EventNames::WheelEvent;
+}
+
+bool WheelEvent::isMouseEvent() const
+{
+ return false;
+}
+
+bool WheelEvent::isWheelEvent() const
+{
+ return true;
+}
+
+inline static unsigned deltaMode(const PlatformWheelEvent& event)
+{
+ return event.granularity() == ScrollByPageWheelEvent ? WheelEvent::DOM_DELTA_PAGE : WheelEvent::DOM_DELTA_PIXEL;
+}
+
+PassRefPtr<WheelEventDispatchMediator> WheelEventDispatchMediator::create(const PlatformWheelEvent& event, PassRefPtr<AbstractView> view)
+{
+ return adoptRef(new WheelEventDispatchMediator(event, view));
+}
+
+WheelEventDispatchMediator::WheelEventDispatchMediator(const PlatformWheelEvent& event, PassRefPtr<AbstractView> view)
+{
+ if (!(event.deltaX() || event.deltaY()))
+ return;
+
+ setEvent(WheelEvent::create(FloatPoint(event.wheelTicksX(), event.wheelTicksY()), FloatPoint(event.deltaX(), event.deltaY()),
+ deltaMode(event), view, event.globalPosition(), event.position(),
+ event.ctrlKey(), event.altKey(), event.shiftKey(), event.metaKey(), event.directionInvertedFromDevice()));
+}
+
+WheelEvent* WheelEventDispatchMediator::event() const
+{
+ return toWheelEvent(EventDispatchMediator::event());
+}
+
+bool WheelEventDispatchMediator::dispatchEvent(EventDispatcher* dispatcher) const
+{
+ ASSERT(event());
+ return EventDispatchMediator::dispatchEvent(dispatcher) && !event()->defaultHandled();
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/events/WheelEvent.h b/chromium/third_party/WebKit/Source/core/events/WheelEvent.h
new file mode 100644
index 00000000000..6c8ea020cba
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/WheelEvent.h
@@ -0,0 +1,128 @@
+/*
+ * Copyright (C) 2001 Peter Kelly (pmk@post.com)
+ * Copyright (C) 2001 Tobias Anton (anton@stud.fbi.fh-darmstadt.de)
+ * Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
+ * Copyright (C) 2003, 2004, 2005, 2006, 2008, 2010 Apple Inc. All rights reserved.
+ * Copyright (C) 2013 Samsung Electronics. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ */
+
+#ifndef WheelEvent_h
+#define WheelEvent_h
+
+#include "core/events/EventDispatchMediator.h"
+#include "core/events/MouseEvent.h"
+#include "platform/geometry/FloatPoint.h"
+
+namespace WebCore {
+
+class PlatformWheelEvent;
+
+struct WheelEventInit : public MouseEventInit {
+ WheelEventInit();
+
+ double deltaX;
+ double deltaY;
+ double deltaZ;
+ int wheelDeltaX; // Deprecated.
+ int wheelDeltaY; // Deprecated.
+ unsigned deltaMode;
+};
+
+class WheelEvent : public MouseEvent {
+public:
+ enum { TickMultiplier = 120 };
+
+ enum DeltaMode {
+ DOM_DELTA_PIXEL = 0,
+ DOM_DELTA_LINE,
+ DOM_DELTA_PAGE
+ };
+
+ static PassRefPtr<WheelEvent> create()
+ {
+ return adoptRef(new WheelEvent);
+ }
+
+ static PassRefPtr<WheelEvent> create(const AtomicString& type, const WheelEventInit& initializer)
+ {
+ return adoptRef(new WheelEvent(type, initializer));
+ }
+
+ static PassRefPtr<WheelEvent> create(const FloatPoint& wheelTicks,
+ const FloatPoint& rawDelta, unsigned deltaMode, PassRefPtr<AbstractView> view,
+ const IntPoint& screenLocation, const IntPoint& pageLocation,
+ bool ctrlKey, bool altKey, bool shiftKey, bool metaKey, bool directionInvertedFromDevice)
+ {
+ return adoptRef(new WheelEvent(wheelTicks, rawDelta, deltaMode, view,
+ screenLocation, pageLocation, ctrlKey, altKey, shiftKey, metaKey, directionInvertedFromDevice));
+ }
+
+ void initWheelEvent(int rawDeltaX, int rawDeltaY, PassRefPtr<AbstractView>,
+ int screenX, int screenY, int pageX, int pageY,
+ bool ctrlKey, bool altKey, bool shiftKey, bool metaKey);
+
+ void initWebKitWheelEvent(int rawDeltaX, int rawDeltaY, PassRefPtr<AbstractView>,
+ int screenX, int screenY, int pageX, int pageY,
+ bool ctrlKey, bool altKey, bool shiftKey, bool metaKey);
+
+ double deltaX() const { return m_deltaX; } // Positive when scrolling right.
+ double deltaY() const { return m_deltaY; } // Positive when scrolling down.
+ double deltaZ() const { return m_deltaZ; }
+ int wheelDelta() const { return wheelDeltaY() ? wheelDeltaY() : wheelDeltaX(); } // Deprecated.
+ int wheelDeltaX() const { return m_wheelDelta.x(); } // Deprecated, negative when scrolling right.
+ int wheelDeltaY() const { return m_wheelDelta.y(); } // Deprecated, negative when scrolling down.
+ unsigned deltaMode() const { return m_deltaMode; }
+ float ticksX() const { return static_cast<float>(m_wheelDelta.x()) / TickMultiplier; }
+ float ticksY() const { return static_cast<float>(m_wheelDelta.y()) / TickMultiplier; }
+
+ bool webkitDirectionInvertedFromDevice() const { return m_directionInvertedFromDevice; }
+
+ virtual const AtomicString& interfaceName() const;
+ virtual bool isMouseEvent() const OVERRIDE;
+ virtual bool isWheelEvent() const OVERRIDE;
+
+private:
+ WheelEvent();
+ WheelEvent(const AtomicString&, const WheelEventInit&);
+ WheelEvent(const FloatPoint& wheelTicks, const FloatPoint& rawDelta,
+ unsigned, PassRefPtr<AbstractView>, const IntPoint& screenLocation, const IntPoint& pageLocation,
+ bool ctrlKey, bool altKey, bool shiftKey, bool metaKey, bool directionInvertedFromDevice);
+
+ IntPoint m_wheelDelta;
+ double m_deltaX;
+ double m_deltaY;
+ double m_deltaZ;
+ unsigned m_deltaMode;
+ bool m_directionInvertedFromDevice;
+};
+
+DEFINE_EVENT_TYPE_CASTS(WheelEvent);
+
+class WheelEventDispatchMediator : public EventDispatchMediator {
+public:
+ static PassRefPtr<WheelEventDispatchMediator> create(const PlatformWheelEvent&, PassRefPtr<AbstractView>);
+private:
+ WheelEventDispatchMediator(const PlatformWheelEvent&, PassRefPtr<AbstractView>);
+ WheelEvent* event() const;
+ virtual bool dispatchEvent(EventDispatcher*) const OVERRIDE;
+};
+
+} // namespace WebCore
+
+#endif // WheelEvent_h
diff --git a/chromium/third_party/WebKit/Source/core/events/WheelEvent.idl b/chromium/third_party/WebKit/Source/core/events/WheelEvent.idl
new file mode 100644
index 00000000000..1cba713f668
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/WheelEvent.idl
@@ -0,0 +1,55 @@
+/*
+ * Copyright (C) 2006, 2007, 2010 Apple Inc. All rights reserved.
+ * Copyright (C) 2006 Samuel Weinig <sam.weinig@gmail.com>
+ * Copyright (C) 2013 Samsung Electronics. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+// Introduced in DOM Level 3:
+[
+ EventConstructor,
+] interface WheelEvent : MouseEvent {
+ // DeltaModeCode
+ const unsigned long DOM_DELTA_PIXEL = 0x00;
+ const unsigned long DOM_DELTA_LINE = 0x01;
+ const unsigned long DOM_DELTA_PAGE = 0x02;
+
+ [InitializedByEventConstructor] readonly attribute double deltaX;
+ [InitializedByEventConstructor] readonly attribute double deltaY;
+ [InitializedByEventConstructor] readonly attribute double deltaZ;
+ [InitializedByEventConstructor] readonly attribute unsigned long deltaMode;
+
+ // Non standard API.
+ [InitializedByEventConstructor] readonly attribute long wheelDeltaX;
+ [InitializedByEventConstructor] readonly attribute long wheelDeltaY;
+ readonly attribute long wheelDelta;
+
+ // WebKit Extension
+ readonly attribute boolean webkitDirectionInvertedFromDevice;
+
+ void initWebKitWheelEvent([Default=Undefined] optional long wheelDeltaX,
+ [Default=Undefined] optional long wheelDeltaY,
+ [Default=Undefined] optional Window view,
+ [Default=Undefined] optional long screenX,
+ [Default=Undefined] optional long screenY,
+ [Default=Undefined] optional long clientX,
+ [Default=Undefined] optional long clientY,
+ [Default=Undefined] optional boolean ctrlKey,
+ [Default=Undefined] optional boolean altKey,
+ [Default=Undefined] optional boolean shiftKey,
+ [Default=Undefined] optional boolean metaKey);
+};
diff --git a/chromium/third_party/WebKit/Source/core/events/WindowEventContext.cpp b/chromium/third_party/WebKit/Source/core/events/WindowEventContext.cpp
new file mode 100644
index 00000000000..673ef36f5c6
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/events/WindowEventContext.cpp
@@ -0,0 +1,64 @@
+/*
+ * Copyright (C) 2010 Google Inc. All Rights Reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "config.h"
+#include "core/events/WindowEventContext.h"
+
+#include "core/dom/Document.h"
+#include "core/events/Event.h"
+#include "core/events/EventContext.h"
+#include "core/dom/Node.h"
+#include "core/frame/DOMWindow.h"
+
+namespace WebCore {
+
+WindowEventContext::WindowEventContext(Event* event, PassRefPtr<Node> node, const EventContext* topEventContext)
+{
+ // We don't dispatch load events to the window. This quirk was originally
+ // added because Mozilla doesn't propagate load events to the window object.
+ if (event->type() == EventTypeNames::load)
+ return;
+
+ Node* topLevelContainer = topEventContext ? topEventContext->node() : node.get();
+ if (!topLevelContainer->isDocumentNode())
+ return;
+
+ m_window = toDocument(topLevelContainer)->domWindow();
+ m_target = topEventContext ? topEventContext->target() : node.get();
+}
+
+bool WindowEventContext::handleLocalEvents(Event* event)
+{
+ if (!m_window)
+ return false;
+
+ event->setTarget(target());
+ event->setCurrentTarget(window());
+ m_window->fireEventListeners(event);
+ return true;
+}
+
+}
diff --git a/chromium/third_party/WebKit/Source/core/dom/WindowEventContext.h b/chromium/third_party/WebKit/Source/core/events/WindowEventContext.h
index 25c5079c257..25c5079c257 100644
--- a/chromium/third_party/WebKit/Source/core/dom/WindowEventContext.h
+++ b/chromium/third_party/WebKit/Source/core/events/WindowEventContext.h
diff --git a/chromium/third_party/WebKit/Source/core/features.gypi b/chromium/third_party/WebKit/Source/core/features.gypi
deleted file mode 100644
index 979137d6a6a..00000000000
--- a/chromium/third_party/WebKit/Source/core/features.gypi
+++ /dev/null
@@ -1,106 +0,0 @@
-#
-# Copyright (C) 2009 Google Inc. All rights reserved.
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions are
-# met:
-#
-# * Redistributions of source code must retain the above copyright
-# notice, this list of conditions and the following disclaimer.
-# * Redistributions in binary form must reproduce the above
-# copyright notice, this list of conditions and the following disclaimer
-# in the documentation and/or other materials provided with the
-# distribution.
-# * Neither the name of Google Inc. nor the names of its
-# contributors may be used to endorse or promote products derived from
-# this software without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-#
-
-{
- # The following defines turn WebKit features on and off.
- 'variables': {
- 'feature_defines': [
- 'ENABLE_CSS3_TEXT=0',
- 'ENABLE_CSS_EXCLUSIONS=1',
- 'ENABLE_CSS_REGIONS=1',
- 'ENABLE_CUSTOM_SCHEME_HANDLER=0',
- 'ENABLE_ENCRYPTED_MEDIA_V2=1',
- 'ENABLE_SVG_FONTS=1',
- 'ENABLE_TOUCH_ICON_LOADING=<(enable_touch_icon_loading)',
- 'ENABLE_GDI_FONTS_ON_WINDOWS=1',
- # WTF_USE_DYNAMIC_ANNOTATIONS=1 may be defined in build/common.gypi
- # We can't define it here because it should be present only
- # in Debug or release_valgrind_build=1 builds.
- ],
- # We have to nest variables inside variables so that they can be overridden
- # through GYP_DEFINES.
- 'variables': {
- 'enable_touch_icon_loading%' : 0,
- },
- 'conditions': [
- ['use_concatenated_impulse_responses==1', {
- # Use concatenated HRTF impulse responses
- 'feature_defines': ['WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1'],
- }],
- ['OS=="android"', {
- 'feature_defines': [
- 'ENABLE_CALENDAR_PICKER=0',
- 'ENABLE_FAST_MOBILE_SCROLLING=1',
- 'ENABLE_INPUT_SPEECH=0',
- 'ENABLE_LEGACY_NOTIFICATIONS=0',
- 'ENABLE_MEDIA_CAPTURE=1',
- 'ENABLE_ORIENTATION_EVENTS=1',
- 'ENABLE_NAVIGATOR_CONTENT_UTILS=0',
- ],
- 'enable_touch_icon_loading': 1,
- }, { # OS!="android"
- 'feature_defines': [
- 'ENABLE_CALENDAR_PICKER=1',
- 'ENABLE_INPUT_SPEECH=1',
- 'ENABLE_INPUT_MULTIPLE_FIELDS_UI=1',
- 'ENABLE_LEGACY_NOTIFICATIONS=1',
- 'ENABLE_MEDIA_CAPTURE=0',
- 'ENABLE_NAVIGATOR_CONTENT_UTILS=1',
- 'ENABLE_ORIENTATION_EVENTS=0',
- 'ENABLE_WEB_AUDIO=1',
- ],
- }],
- # Mac OS X uses Accelerate.framework FFT by default instead of FFmpeg.
- ['OS!="mac" and OS!="android"', {
- 'feature_defines': [
- 'WTF_USE_WEBAUDIO_FFMPEG=1',
- ],
- }],
- ['OS=="android" and use_openmax_dl_fft!=0', {
- 'feature_defines': [
- 'WTF_USE_WEBAUDIO_OPENMAX_DL_FFT=1',
- # Enabling the FFT is enough to enable WebAudio support to
- # allow most WebAudio features to work on Android.
- 'ENABLE_WEB_AUDIO=1',
- ],
- }],
- ['OS=="win" or OS=="android" or OS=="linux"', {
- 'feature_defines': [
- 'ENABLE_OPENTYPE_VERTICAL=1',
- ],
- }],
- ['use_default_render_theme==1', {
- 'feature_defines': [
- 'ENABLE_DEFAULT_RENDER_THEME=1',
- ],
- }],
- ],
- },
-}
diff --git a/chromium/third_party/WebKit/Source/core/fetch/CSSStyleSheetResource.cpp b/chromium/third_party/WebKit/Source/core/fetch/CSSStyleSheetResource.cpp
index 78a3455a66d..7952ec5da2e 100644
--- a/chromium/third_party/WebKit/Source/core/fetch/CSSStyleSheetResource.cpp
+++ b/chromium/third_party/WebKit/Source/core/fetch/CSSStyleSheetResource.cpp
@@ -31,15 +31,15 @@
#include "core/fetch/ResourceClientWalker.h"
#include "core/fetch/StyleSheetResourceClient.h"
#include "core/fetch/TextResourceDecoder.h"
-#include "core/platform/SharedBuffer.h"
-#include "core/platform/network/HTTPParsers.h"
+#include "platform/SharedBuffer.h"
+#include "platform/network/HTTPParsers.h"
#include "wtf/CurrentTime.h"
#include "wtf/Vector.h"
namespace WebCore {
CSSStyleSheetResource::CSSStyleSheetResource(const ResourceRequest& resourceRequest, const String& charset)
- : Resource(resourceRequest, CSSStyleSheet)
+ : StyleSheetResource(resourceRequest, CSSStyleSheet)
, m_decoder(TextResourceDecoder::create("text/css", charset))
{
DEFINE_STATIC_LOCAL(const AtomicString, acceptCSS, ("text/css,*/*;q=0.1", AtomicString::ConstructFromLiteral));
@@ -123,7 +123,7 @@ bool CSSStyleSheetResource::canUseSheet(bool enforceMIMEType, bool* hasValidMIME
//
// This code defaults to allowing the stylesheet for non-HTTP protocols so
// folks can use standards mode for local HTML documents.
- String mimeType = extractMIMETypeFromMediaType(response().httpHeaderField("Content-Type"));
+ const AtomicString& mimeType = extractMIMETypeFromMediaType(response().httpHeaderField("Content-Type"));
bool typeOK = mimeType.isEmpty() || equalIgnoringCase(mimeType, "text/css") || equalIgnoringCase(mimeType, "application/x-unknown-content-type");
if (hasValidMIMEType)
*hasValidMIMEType = typeOK;
diff --git a/chromium/third_party/WebKit/Source/core/fetch/CSSStyleSheetResource.h b/chromium/third_party/WebKit/Source/core/fetch/CSSStyleSheetResource.h
index 3ecf34ba82e..4ca19857c87 100644
--- a/chromium/third_party/WebKit/Source/core/fetch/CSSStyleSheetResource.h
+++ b/chromium/third_party/WebKit/Source/core/fetch/CSSStyleSheetResource.h
@@ -26,16 +26,17 @@
#ifndef CSSStyleSheetResource_h
#define CSSStyleSheetResource_h
-#include "core/fetch/Resource.h"
+#include "core/fetch/ResourcePtr.h"
+#include "core/fetch/StyleSheetResource.h"
namespace WebCore {
+class CSSParserContext;
class ResourceClient;
class StyleSheetContents;
class TextResourceDecoder;
-struct CSSParserContext;
-class CSSStyleSheetResource : public Resource {
+class CSSStyleSheetResource : public StyleSheetResource {
public:
CSSStyleSheetResource(const ResourceRequest&, const String& charset);
virtual ~CSSStyleSheetResource();
@@ -56,12 +57,14 @@ private:
protected:
virtual void checkNotify();
- RefPtr<TextResourceDecoder> m_decoder;
+ OwnPtr<TextResourceDecoder> m_decoder;
String m_decodedSheetText;
RefPtr<StyleSheetContents> m_parsedStyleSheetCache;
};
+DEFINE_RESOURCE_TYPE_CASTS(CSSStyleSheet);
+
}
#endif
diff --git a/chromium/third_party/WebKit/Source/core/fetch/CachePolicy.h b/chromium/third_party/WebKit/Source/core/fetch/CachePolicy.h
index bffddfe1d96..0bb84a68b73 100644
--- a/chromium/third_party/WebKit/Source/core/fetch/CachePolicy.h
+++ b/chromium/third_party/WebKit/Source/core/fetch/CachePolicy.h
@@ -29,7 +29,6 @@
namespace WebCore {
enum CachePolicy {
- CachePolicyCache,
CachePolicyVerify,
CachePolicyRevalidate,
CachePolicyReload,
diff --git a/chromium/third_party/WebKit/Source/core/fetch/CrossOriginAccessControl.cpp b/chromium/third_party/WebKit/Source/core/fetch/CrossOriginAccessControl.cpp
index 2647a8e7955..f35116c73f8 100644
--- a/chromium/third_party/WebKit/Source/core/fetch/CrossOriginAccessControl.cpp
+++ b/chromium/third_party/WebKit/Source/core/fetch/CrossOriginAccessControl.cpp
@@ -27,10 +27,9 @@
#include "config.h"
#include "core/fetch/CrossOriginAccessControl.h"
-#include "core/platform/network/HTTPParsers.h"
-#include "core/platform/network/ResourceRequest.h"
-#include "core/platform/network/ResourceResponse.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/network/HTTPParsers.h"
+#include "platform/network/ResourceResponse.h"
+#include "platform/weborigin/SecurityOrigin.h"
#include "wtf/Threading.h"
#include "wtf/text/AtomicString.h"
#include "wtf/text/StringBuilder.h"
@@ -42,7 +41,7 @@ bool isOnAccessControlSimpleRequestMethodWhitelist(const String& method)
return method == "GET" || method == "HEAD" || method == "POST";
}
-bool isOnAccessControlSimpleRequestHeaderWhitelist(const String& name, const String& value)
+bool isOnAccessControlSimpleRequestHeaderWhitelist(const AtomicString& name, const AtomicString& value)
{
if (equalIgnoringCase(name, "accept")
|| equalIgnoringCase(name, "accept-language")
@@ -53,7 +52,7 @@ bool isOnAccessControlSimpleRequestHeaderWhitelist(const String& name, const Str
// Preflight is required for MIME types that can not be sent via form submission.
if (equalIgnoringCase(name, "content-type")) {
- String mimeType = extractMIMETypeFromMediaType(value);
+ AtomicString mimeType = extractMIMETypeFromMediaType(value);
return equalIgnoringCase(mimeType, "application/x-www-form-urlencoded")
|| equalIgnoringCase(mimeType, "multipart/form-data")
|| equalIgnoringCase(mimeType, "text/plain");
@@ -124,8 +123,7 @@ ResourceRequest createAccessControlPreflightRequest(const ResourceRequest& reque
HTTPHeaderMap::const_iterator end = requestHeaderFields.end();
for (; it != end; ++it) {
- headerBuffer.append(',');
- headerBuffer.append(' ');
+ headerBuffer.appendLiteral(", ");
headerBuffer.append(it->key);
}
@@ -135,6 +133,11 @@ ResourceRequest createAccessControlPreflightRequest(const ResourceRequest& reque
return preflightRequest;
}
+static bool isOriginSeparator(UChar ch)
+{
+ return isASCIISpace(ch) || ch == ',';
+}
+
bool passesAccessControlCheck(const ResourceResponse& response, StoredCredentials includeCredentials, SecurityOrigin* securityOrigin, String& errorDescription)
{
AtomicallyInitializedStatic(AtomicString&, accessControlAllowOrigin = *new AtomicString("access-control-allow-origin", AtomicString::ConstructFromLiteral));
@@ -142,28 +145,29 @@ bool passesAccessControlCheck(const ResourceResponse& response, StoredCredential
// A wildcard Access-Control-Allow-Origin can not be used if credentials are to be sent,
// even with Access-Control-Allow-Credentials set to true.
- const String& accessControlOriginString = response.httpHeaderField(accessControlAllowOrigin);
- if (accessControlOriginString == "*" && includeCredentials == DoNotAllowStoredCredentials)
+ const AtomicString& accessControlOriginString = response.httpHeaderField(accessControlAllowOrigin);
+ if (accessControlOriginString == starAtom && includeCredentials == DoNotAllowStoredCredentials)
return true;
- // FIXME: Access-Control-Allow-Origin can contain a list of origins.
if (accessControlOriginString != securityOrigin->toString()) {
- if (accessControlOriginString == "*") {
- errorDescription = "Wildcards cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true. Origin '" + securityOrigin->toString() + "' is therefore not allowed access.";
+ if (accessControlOriginString == starAtom) {
+ errorDescription = "A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true. Origin '" + securityOrigin->toString() + "' is therefore not allowed access.";
} else if (accessControlOriginString.isEmpty()) {
errorDescription = "No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '" + securityOrigin->toString() + "' is therefore not allowed access.";
+ } else if (accessControlOriginString.string().find(isOriginSeparator, 0) != kNotFound) {
+ errorDescription = "The 'Access-Control-Allow-Origin' header contains multiple values '" + accessControlOriginString + "', but only one is allowed. Origin '" + securityOrigin->toString() + "' is therefore not allowed access.";
} else {
KURL headerOrigin(KURL(), accessControlOriginString);
if (!headerOrigin.isValid())
errorDescription = "The 'Access-Control-Allow-Origin' header contains the invalid value '" + accessControlOriginString + "'. Origin '" + securityOrigin->toString() + "' is therefore not allowed access.";
else
- errorDescription = "The 'Access-Control-Allow-Origin' whitelists only '" + accessControlOriginString + "'. Origin '" + securityOrigin->toString() + "' is not in the list, and is therefore not allowed access.";
+ errorDescription = "The 'Access-Control-Allow-Origin' header has a value '" + accessControlOriginString + "' that is not equal to the supplied origin. Origin '" + securityOrigin->toString() + "' is therefore not allowed access.";
}
return false;
}
if (includeCredentials == AllowStoredCredentials) {
- const String& accessControlCredentialsString = response.httpHeaderField(accessControlAllowCredentials);
+ const AtomicString& accessControlCredentialsString = response.httpHeaderField(accessControlAllowCredentials);
if (accessControlCredentialsString != "true") {
errorDescription = "Credentials flag is 'true', but the 'Access-Control-Allow-Credentials' header is '" + accessControlCredentialsString + "'. It must be 'true' to allow credentials.";
return false;
diff --git a/chromium/third_party/WebKit/Source/core/fetch/CrossOriginAccessControl.h b/chromium/third_party/WebKit/Source/core/fetch/CrossOriginAccessControl.h
index 0d58400e69c..450c342253f 100644
--- a/chromium/third_party/WebKit/Source/core/fetch/CrossOriginAccessControl.h
+++ b/chromium/third_party/WebKit/Source/core/fetch/CrossOriginAccessControl.h
@@ -28,7 +28,7 @@
#define CrossOriginAccessControl_h
#include "core/fetch/ResourceLoaderOptions.h"
-#include "core/platform/network/ResourceRequest.h"
+#include "platform/network/ResourceRequest.h"
#include "wtf/Forward.h"
#include "wtf/HashSet.h"
@@ -47,7 +47,7 @@ enum AccessControlStatus {
bool isSimpleCrossOriginAccessRequest(const String& method, const HTTPHeaderMap&);
bool isOnAccessControlSimpleRequestMethodWhitelist(const String&);
-bool isOnAccessControlSimpleRequestHeaderWhitelist(const String& name, const String& value);
+bool isOnAccessControlSimpleRequestHeaderWhitelist(const AtomicString& name, const AtomicString& value);
bool isOnAccessControlResponseHeaderWhitelist(const String&);
void updateRequestForAccessControl(ResourceRequest&, SecurityOrigin*, StoredCredentials);
diff --git a/chromium/third_party/WebKit/Source/core/fetch/DocumentResource.cpp b/chromium/third_party/WebKit/Source/core/fetch/DocumentResource.cpp
index 5c18d847e45..61521b06ae2 100644
--- a/chromium/third_party/WebKit/Source/core/fetch/DocumentResource.cpp
+++ b/chromium/third_party/WebKit/Source/core/fetch/DocumentResource.cpp
@@ -24,9 +24,7 @@
#include "core/fetch/DocumentResource.h"
-#include "core/fetch/ResourceClient.h"
-#include "core/fetch/ResourcePtr.h"
-#include "core/platform/SharedBuffer.h"
+#include "platform/SharedBuffer.h"
#include "core/svg/SVGDocument.h"
#include "wtf/text/StringBuilder.h"
diff --git a/chromium/third_party/WebKit/Source/core/fetch/DocumentResource.h b/chromium/third_party/WebKit/Source/core/fetch/DocumentResource.h
index efa77d93257..292f977d01a 100644
--- a/chromium/third_party/WebKit/Source/core/fetch/DocumentResource.h
+++ b/chromium/third_party/WebKit/Source/core/fetch/DocumentResource.h
@@ -34,6 +34,8 @@ class Document;
class DocumentResource : public Resource {
public:
+ typedef ResourceClient ClientType;
+
DocumentResource(const ResourceRequest&, Type);
virtual ~DocumentResource();
@@ -47,9 +49,12 @@ private:
PassRefPtr<Document> createDocument(const KURL&);
RefPtr<Document> m_document;
- RefPtr<TextResourceDecoder> m_decoder;
+ OwnPtr<TextResourceDecoder> m_decoder;
};
+DEFINE_TYPE_CASTS(DocumentResource, Resource, resource, resource->type() == Resource::SVGDocument, resource.type() == Resource::SVGDocument); \
+inline DocumentResource* toDocumentResource(const ResourcePtr<Resource>& ptr) { return toDocumentResource(ptr.get()); }
+
class DocumentResourceClient : public ResourceClient {
public:
virtual ~DocumentResourceClient() { }
diff --git a/chromium/third_party/WebKit/Source/core/fetch/FetchContext.cpp b/chromium/third_party/WebKit/Source/core/fetch/FetchContext.cpp
index 037e629ab1d..cc7a6d9ce6a 100644
--- a/chromium/third_party/WebKit/Source/core/fetch/FetchContext.cpp
+++ b/chromium/third_party/WebKit/Source/core/fetch/FetchContext.cpp
@@ -52,7 +52,7 @@ void FetchContext::addAdditionalRequestHeaders(Document&, ResourceRequest&, Reso
{
}
-CachePolicy FetchContext::cachePolicy(Resource::Type) const
+CachePolicy FetchContext::cachePolicy(Document*) const
{
return CachePolicyVerify;
}
@@ -73,6 +73,10 @@ void FetchContext::dispatchDidReceiveData(DocumentLoader*, unsigned long, const
{
}
+void FetchContext::dispatchDidDownloadData(DocumentLoader*, unsigned long, int, int)
+{
+}
+
void FetchContext::dispatchDidFinishLoading(DocumentLoader*, unsigned long, double)
{
}
@@ -81,7 +85,7 @@ void FetchContext::dispatchDidFail(DocumentLoader*, unsigned long, const Resourc
{
}
-void FetchContext::sendRemainingDelegateMessages(DocumentLoader*, unsigned long, const ResourceResponse&, const char*, int, int, const ResourceError&)
+void FetchContext::sendRemainingDelegateMessages(DocumentLoader*, unsigned long, const ResourceResponse&, int)
{
}
diff --git a/chromium/third_party/WebKit/Source/core/fetch/FetchContext.h b/chromium/third_party/WebKit/Source/core/fetch/FetchContext.h
index 1eb55964a1f..48803408e00 100644
--- a/chromium/third_party/WebKit/Source/core/fetch/FetchContext.h
+++ b/chromium/third_party/WebKit/Source/core/fetch/FetchContext.h
@@ -34,11 +34,12 @@
#include "core/fetch/CachePolicy.h"
#include "core/fetch/FetchInitiatorInfo.h"
#include "core/fetch/Resource.h"
-#include "core/platform/network/ResourceLoadPriority.h"
+#include "platform/network/ResourceLoadPriority.h"
#include "wtf/Noncopyable.h"
namespace WebCore {
+class Document;
class DocumentLoader;
class Frame;
class KURL;
@@ -58,16 +59,17 @@ public:
virtual void reportLocalLoadFailed(const KURL&);
virtual void addAdditionalRequestHeaders(Document&, ResourceRequest&, Resource::Type);
- virtual CachePolicy cachePolicy(Resource::Type) const;
+ virtual CachePolicy cachePolicy(Document*) const;
virtual void dispatchDidChangeResourcePriority(unsigned long identifier, ResourceLoadPriority);
virtual void dispatchWillSendRequest(DocumentLoader*, unsigned long identifier, ResourceRequest&, const ResourceResponse& redirectResponse, const FetchInitiatorInfo& = FetchInitiatorInfo());
virtual void dispatchDidLoadResourceFromMemoryCache(const ResourceRequest&, const ResourceResponse&);
virtual void dispatchDidReceiveResponse(DocumentLoader*, unsigned long identifier, const ResourceResponse&, ResourceLoader* = 0);
virtual void dispatchDidReceiveData(DocumentLoader*, unsigned long identifier, const char* data, int dataLength, int encodedDataLength);
+ virtual void dispatchDidDownloadData(DocumentLoader*, unsigned long identifier, int dataLength, int encodedDataLength);
virtual void dispatchDidFinishLoading(DocumentLoader*, unsigned long identifier, double finishTime);
virtual void dispatchDidFail(DocumentLoader*, unsigned long identifier, const ResourceError&);
- virtual void sendRemainingDelegateMessages(DocumentLoader*, unsigned long identifier, const ResourceResponse&, const char* data, int dataLength, int encodedDataLength, const ResourceError&);
+ virtual void sendRemainingDelegateMessages(DocumentLoader*, unsigned long identifier, const ResourceResponse&, int dataLength);
};
}
diff --git a/chromium/third_party/WebKit/Source/core/fetch/FetchInitiatorTypeNames.in b/chromium/third_party/WebKit/Source/core/fetch/FetchInitiatorTypeNames.in
index 5f429b02922..f0cf1b83884 100644
--- a/chromium/third_party/WebKit/Source/core/fetch/FetchInitiatorTypeNames.in
+++ b/chromium/third_party/WebKit/Source/core/fetch/FetchInitiatorTypeNames.in
@@ -1,7 +1,9 @@
+namespace="FetchInitiatorType"
+
css
document
icon
-inspector
+internal
link
processinginstruction
texttrack
diff --git a/chromium/third_party/WebKit/Source/core/fetch/FetchRequest.cpp b/chromium/third_party/WebKit/Source/core/fetch/FetchRequest.cpp
index d8d95121899..956ae9630f2 100644
--- a/chromium/third_party/WebKit/Source/core/fetch/FetchRequest.cpp
+++ b/chromium/third_party/WebKit/Source/core/fetch/FetchRequest.cpp
@@ -26,9 +26,7 @@
#include "config.h"
#include "core/fetch/FetchRequest.h"
-#include "core/dom/Element.h"
#include "core/fetch/CrossOriginAccessControl.h"
-#include "core/fetch/FetchInitiatorInfo.h"
#include "core/fetch/ResourceFetcher.h"
namespace WebCore {
@@ -40,6 +38,7 @@ FetchRequest::FetchRequest(const ResourceRequest& resourceRequest, const AtomicS
, m_priority(priority)
, m_forPreload(false)
, m_defer(NoDefer)
+ , m_originRestriction(UseDefaultOriginRestrictionForType)
{
m_options.initiatorInfo.name = initiator;
}
@@ -50,6 +49,7 @@ FetchRequest::FetchRequest(const ResourceRequest& resourceRequest, const AtomicS
, m_priority(ResourceLoadPriorityUnresolved)
, m_forPreload(false)
, m_defer(NoDefer)
+ , m_originRestriction(UseDefaultOriginRestrictionForType)
{
m_options.initiatorInfo.name = initiator;
}
@@ -60,6 +60,7 @@ FetchRequest::FetchRequest(const ResourceRequest& resourceRequest, const FetchIn
, m_priority(ResourceLoadPriorityUnresolved)
, m_forPreload(false)
, m_defer(NoDefer)
+ , m_originRestriction(UseDefaultOriginRestrictionForType)
{
m_options.initiatorInfo = initiator;
}
@@ -68,11 +69,9 @@ FetchRequest::~FetchRequest()
{
}
-void FetchRequest::setPotentiallyCrossOriginEnabled(SecurityOrigin* origin, StoredCredentials allowCredentials)
+void FetchRequest::setCrossOriginAccessControl(SecurityOrigin* origin, StoredCredentials allowCredentials)
{
updateRequestForAccessControl(m_resourceRequest, origin, allowCredentials);
- ASSERT(m_options.requestOriginPolicy == UseDefaultOriginRestrictionsForType); // Allows only tightening from the default value.
- m_options.requestOriginPolicy = PotentiallyCrossOriginEnabled;
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/fetch/FetchRequest.h b/chromium/third_party/WebKit/Source/core/fetch/FetchRequest.h
index b9d5fec3978..1954cedbeef 100644
--- a/chromium/third_party/WebKit/Source/core/fetch/FetchRequest.h
+++ b/chromium/third_party/WebKit/Source/core/fetch/FetchRequest.h
@@ -29,8 +29,8 @@
#include "core/dom/Element.h"
#include "core/fetch/FetchInitiatorInfo.h"
#include "core/fetch/ResourceLoaderOptions.h"
-#include "core/platform/network/ResourceLoadPriority.h"
-#include "core/platform/network/ResourceRequest.h"
+#include "platform/network/ResourceLoadPriority.h"
+#include "platform/network/ResourceRequest.h"
#include "wtf/text/AtomicString.h"
namespace WebCore {
@@ -39,6 +39,7 @@ class SecurityOrigin;
class FetchRequest {
public:
enum DeferOption { NoDefer, DeferredByClient };
+ enum OriginRestriction { UseDefaultOriginRestrictionForType, RestrictToSameOrigin };
explicit FetchRequest(const ResourceRequest&, const AtomicString& initiator, const String& charset = String(), ResourceLoadPriority = ResourceLoadPriorityUnresolved);
FetchRequest(const ResourceRequest&, const AtomicString& initiator, const ResourceLoaderOptions&);
@@ -58,7 +59,9 @@ public:
DeferOption defer() const { return m_defer; }
void setDefer(DeferOption defer) { m_defer = defer; }
void setContentSecurityCheck(ContentSecurityPolicyCheck contentSecurityPolicyOption) { m_options.contentSecurityPolicyOption = contentSecurityPolicyOption; }
- void setPotentiallyCrossOriginEnabled(SecurityOrigin*, StoredCredentials);
+ void setCrossOriginAccessControl(SecurityOrigin*, StoredCredentials);
+ OriginRestriction originRestriction() const { return m_originRestriction; }
+ void setOriginRestriction(OriginRestriction restriction) { m_originRestriction = restriction; }
private:
ResourceRequest m_resourceRequest;
@@ -67,6 +70,7 @@ private:
ResourceLoadPriority m_priority;
bool m_forPreload;
DeferOption m_defer;
+ OriginRestriction m_originRestriction;
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/fetch/FontResource.cpp b/chromium/third_party/WebKit/Source/core/fetch/FontResource.cpp
index d4db35a6646..0fdbcc1d39e 100644
--- a/chromium/third_party/WebKit/Source/core/fetch/FontResource.cpp
+++ b/chromium/third_party/WebKit/Source/core/fetch/FontResource.cpp
@@ -27,13 +27,12 @@
#include "config.h"
#include "core/fetch/FontResource.h"
-#include "core/fetch/ResourceClient.h"
#include "core/fetch/ResourceClientWalker.h"
#include "core/fetch/TextResourceDecoder.h"
-#include "core/platform/HistogramSupport.h"
-#include "core/platform/SharedBuffer.h"
-#include "core/platform/graphics/FontCustomPlatformData.h"
-#include "core/platform/graphics/FontPlatformData.h"
+#include "platform/SharedBuffer.h"
+#include "platform/fonts/FontCustomPlatformData.h"
+#include "platform/fonts/FontPlatformData.h"
+#include "public/platform/Platform.h"
#include "wtf/CurrentTime.h"
#if ENABLE(SVG_FONTS)
@@ -79,14 +78,14 @@ void FontResource::beginLoadIfNeeded(ResourceFetcher* dl)
ResourceClientWalker<FontResourceClient> walker(m_clients);
while (FontResourceClient* client = walker.next())
client->didStartFontLoad(this);
- m_histograms.loadStarted();
}
}
bool FontResource::ensureCustomFontData()
{
- if (!m_fontData && !errorOccurred() && !isLoading() && m_data) {
- m_fontData = FontCustomPlatformData::create(m_data.get());
+ if (!m_fontData && !errorOccurred() && !isLoading()) {
+ if (m_data)
+ m_fontData = FontCustomPlatformData::create(m_data.get());
if (!m_fontData)
setStatus(DecodeError);
}
@@ -100,23 +99,27 @@ FontPlatformData FontResource::platformDataFromCustomData(float size, bool bold,
return FontPlatformData(size, bold, italic);
#endif
ASSERT(m_fontData);
- return m_fontData->fontPlatformData(static_cast<int>(size), bold, italic, orientation, widthVariant);
+ return m_fontData->fontPlatformData(size, bold, italic, orientation, widthVariant);
}
#if ENABLE(SVG_FONTS)
bool FontResource::ensureSVGFontData()
{
- if (!m_externalSVGDocument && !errorOccurred() && !isLoading() && m_data) {
- m_externalSVGDocument = SVGDocument::create();
+ if (!m_externalSVGDocument && !errorOccurred() && !isLoading()) {
+ if (m_data) {
+ m_externalSVGDocument = SVGDocument::create();
- RefPtr<TextResourceDecoder> decoder = TextResourceDecoder::create("application/xml");
- String svgSource = decoder->decode(m_data->data(), m_data->size());
- svgSource.append(decoder->flush());
+ OwnPtr<TextResourceDecoder> decoder = TextResourceDecoder::create("application/xml");
+ String svgSource = decoder->decode(m_data->data(), m_data->size());
+ svgSource.append(decoder->flush());
- m_externalSVGDocument->setContent(svgSource);
+ m_externalSVGDocument->setContent(svgSource);
- if (decoder->sawError())
- m_externalSVGDocument = 0;
+ if (decoder->sawError())
+ m_externalSVGDocument = 0;
+ }
+ if (!m_externalSVGDocument)
+ setStatus(DecodeError);
}
return m_externalSVGDocument;
@@ -165,36 +168,4 @@ void FontResource::checkNotify()
c->fontLoaded(this);
}
-void FontResource::willUseFontData()
-{
- if (!isLoaded())
- m_histograms.willUseFontData();
-}
-
-FontResource::FontResourceHistograms::~FontResourceHistograms()
-{
- if (m_styledTime > 0)
- HistogramSupport::histogramEnumeration("WebFont.Resource.UsageType", StyledButNotUsed, UsageTypeMax);
-}
-
-void FontResource::FontResourceHistograms::willUseFontData()
-{
- if (!m_styledTime)
- m_styledTime = currentTimeMS();
-}
-
-void FontResource::FontResourceHistograms::loadStarted()
-{
- if (m_styledTime < 0)
- return;
- if (!m_styledTime) {
- HistogramSupport::histogramEnumeration("WebFont.Resource.UsageType", NotStyledButUsed, UsageTypeMax);
- } else {
- int duration = static_cast<int>(currentTimeMS() - m_styledTime);
- HistogramSupport::histogramCustomCounts("WebFont.Resource.StyleRecalcToDownloadLatency", duration, 0, 10000, 50);
- HistogramSupport::histogramEnumeration("WebFont.Resource.UsageType", StyledAndUsed, UsageTypeMax);
- }
- m_styledTime = -1;
-}
-
}
diff --git a/chromium/third_party/WebKit/Source/core/fetch/FontResource.h b/chromium/third_party/WebKit/Source/core/fetch/FontResource.h
index a910f8efaa9..f92d7d21bd6 100644
--- a/chromium/third_party/WebKit/Source/core/fetch/FontResource.h
+++ b/chromium/third_party/WebKit/Source/core/fetch/FontResource.h
@@ -26,10 +26,10 @@
#ifndef FontResource_h
#define FontResource_h
-#include "core/fetch/Resource.h"
#include "core/fetch/ResourceClient.h"
-#include "core/platform/graphics/FontOrientation.h"
-#include "core/platform/graphics/FontWidthVariant.h"
+#include "core/fetch/ResourcePtr.h"
+#include "platform/fonts/FontOrientation.h"
+#include "platform/fonts/FontWidthVariant.h"
#include "wtf/OwnPtr.h"
namespace WebCore {
@@ -42,6 +42,8 @@ class FontCustomPlatformData;
class FontResource : public Resource {
public:
+ typedef ResourceClient ClientType;
+
FontResource(const ResourceRequest&);
virtual ~FontResource();
@@ -50,7 +52,6 @@ public:
virtual void didAddClient(ResourceClient*);
virtual void allClientsRemoved();
- void willUseFontData();
void beginLoadIfNeeded(ResourceFetcher* dl);
bool stillNeedsLoad() const { return !m_loadInitiated; }
@@ -70,26 +71,12 @@ private:
#if ENABLE(SVG_FONTS)
RefPtr<WebCore::SVGDocument> m_externalSVGDocument;
#endif
- class FontResourceHistograms {
- public:
- enum UsageType {
- StyledAndUsed,
- StyledButNotUsed,
- NotStyledButUsed,
- UsageTypeMax
- };
- FontResourceHistograms() : m_styledTime(0) { }
- ~FontResourceHistograms();
- void willUseFontData();
- void loadStarted();
- private:
- double m_styledTime;
- };
- FontResourceHistograms m_histograms;
friend class MemoryCache;
};
+DEFINE_RESOURCE_TYPE_CASTS(Font);
+
class FontResourceClient : public ResourceClient {
public:
virtual ~FontResourceClient() { }
diff --git a/chromium/third_party/WebKit/Source/core/fetch/ImageResource.cpp b/chromium/third_party/WebKit/Source/core/fetch/ImageResource.cpp
index 0912aec77be..598e616f1fa 100644
--- a/chromium/third_party/WebKit/Source/core/fetch/ImageResource.cpp
+++ b/chromium/third_party/WebKit/Source/core/fetch/ImageResource.cpp
@@ -24,16 +24,17 @@
#include "config.h"
#include "core/fetch/ImageResource.h"
+#include "RuntimeEnabledFeatures.h"
#include "core/fetch/ImageResourceClient.h"
#include "core/fetch/MemoryCache.h"
#include "core/fetch/ResourceClient.h"
#include "core/fetch/ResourceClientWalker.h"
#include "core/fetch/ResourceFetcher.h"
-#include "core/page/FrameView.h"
-#include "core/platform/SharedBuffer.h"
-#include "core/platform/graphics/BitmapImage.h"
+#include "core/frame/FrameView.h"
#include "core/rendering/RenderObject.h"
#include "core/svg/graphics/SVGImage.h"
+#include "platform/SharedBuffer.h"
+#include "platform/graphics/BitmapImage.h"
#include "wtf/CurrentTime.h"
#include "wtf/StdLibExtras.h"
#include "wtf/Vector.h"
@@ -44,8 +45,10 @@ namespace WebCore {
ImageResource::ImageResource(const ResourceRequest& resourceRequest)
: Resource(resourceRequest, Image)
+ , m_devicePixelRatioHeaderValue(1.0)
, m_image(0)
, m_loadingMultipartContent(false)
+ , m_hasDevicePixelRatioHeaderValue(false)
{
setStatus(Unknown);
setCustomAcceptHeader();
@@ -110,7 +113,7 @@ void ImageResource::switchClientsToRevalidatedResource()
for (ContainerSizeRequests::iterator it = m_pendingContainerSizeRequests.begin(); it != m_pendingContainerSizeRequests.end(); ++it)
switchContainerSizeRequests.set(it->key, it->value);
Resource::switchClientsToRevalidatedResource();
- ImageResource* revalidatedImageResource = static_cast<ImageResource*>(resourceToRevalidate());
+ ImageResource* revalidatedImageResource = toImageResource(resourceToRevalidate());
for (ContainerSizeRequests::iterator it = switchContainerSizeRequests.begin(); it != switchContainerSizeRequests.end(); ++it)
revalidatedImageResource->setContainerSizeForRenderer(it->key, it->value.first, it->value.second);
return;
@@ -130,12 +133,12 @@ void ImageResource::allClientsRemoved()
pair<WebCore::Image*, float> ImageResource::brokenImage(float deviceScaleFactor)
{
if (deviceScaleFactor >= 2) {
- DEFINE_STATIC_LOCAL(RefPtr<WebCore::Image>, brokenImageHiRes, (WebCore::Image::loadPlatformResource("missingImage@2x")));
- return std::make_pair(brokenImageHiRes.get(), 2);
+ DEFINE_STATIC_REF(WebCore::Image, brokenImageHiRes, (WebCore::Image::loadPlatformResource("missingImage@2x")));
+ return std::make_pair(brokenImageHiRes, 2);
}
- DEFINE_STATIC_LOCAL(RefPtr<WebCore::Image>, brokenImageLoRes, (WebCore::Image::loadPlatformResource("missingImage")));
- return std::make_pair(brokenImageLoRes.get(), 1);
+ DEFINE_STATIC_REF(WebCore::Image, brokenImageLoRes, (WebCore::Image::loadPlatformResource("missingImage")));
+ return std::make_pair(brokenImageLoRes, 1);
}
bool ImageResource::willPaintBrokenImage() const
@@ -235,7 +238,7 @@ LayoutSize ImageResource::imageSizeForRenderer(const RenderObject* renderer, flo
LayoutSize imageSize;
if (m_image->isBitmapImage() && (renderer && renderer->shouldRespectImageOrientation() == RespectImageOrientation))
- imageSize = static_cast<BitmapImage*>(m_image.get())->sizeRespectingOrientation();
+ imageSize = toBitmapImage(m_image.get())->sizeRespectingOrientation();
else if (m_image->isSVGImage() && sizeType == NormalSize)
imageSize = m_svgImageCache->imageSizeForRenderer(renderer);
else
@@ -323,6 +326,8 @@ void ImageResource::appendData(const char* data, int length)
void ImageResource::updateImage(bool allDataReceived)
{
+ TRACE_EVENT0("webkit", "ImageResource::updateImage");
+
if (m_data)
createImage();
@@ -375,6 +380,13 @@ void ImageResource::responseReceived(const ResourceResponse& response)
finishOnePart();
else if (response.isMultipart())
m_loadingMultipartContent = true;
+ if (RuntimeEnabledFeatures::clientHintsDprEnabled()) {
+ m_devicePixelRatioHeaderValue = response.httpHeaderField("DPR").toFloat(&m_hasDevicePixelRatioHeaderValue);
+ if (!m_hasDevicePixelRatioHeaderValue || m_devicePixelRatioHeaderValue <= 0.0) {
+ m_devicePixelRatioHeaderValue = 1.0;
+ m_hasDevicePixelRatioHeaderValue = false;
+ }
+ }
Resource::responseReceived(response);
}
@@ -448,4 +460,13 @@ bool ImageResource::currentFrameKnownToBeOpaque(const RenderObject* renderer)
return image->currentFrameKnownToBeOpaque();
}
+bool ImageResource::isAccessAllowed(SecurityOrigin* securityOrigin)
+{
+ if (!image()->currentFrameHasSingleSecurityOrigin())
+ return false;
+ if (passesAccessControlCheck(securityOrigin))
+ return true;
+ return !securityOrigin->taintsCanvas(response().url());
+}
+
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/fetch/ImageResource.h b/chromium/third_party/WebKit/Source/core/fetch/ImageResource.h
index 15fc953a0c2..f04260641db 100644
--- a/chromium/third_party/WebKit/Source/core/fetch/ImageResource.h
+++ b/chromium/third_party/WebKit/Source/core/fetch/ImageResource.h
@@ -23,12 +23,12 @@
#ifndef ImageResource_h
#define ImageResource_h
-#include "core/fetch/Resource.h"
-#include "core/platform/graphics/ImageObserver.h"
-#include "core/platform/graphics/IntRect.h"
-#include "core/platform/graphics/IntSizeHash.h"
-#include "core/platform/graphics/LayoutSize.h"
+#include "core/fetch/ResourcePtr.h"
#include "core/svg/graphics/SVGImageCache.h"
+#include "platform/geometry/IntRect.h"
+#include "platform/geometry/IntSizeHash.h"
+#include "platform/geometry/LayoutSize.h"
+#include "platform/graphics/ImageObserver.h"
#include "wtf/HashMap.h"
namespace WebCore {
@@ -36,14 +36,17 @@ namespace WebCore {
class ImageResourceClient;
class ResourceFetcher;
class FloatSize;
+class Length;
class MemoryCache;
class RenderObject;
-struct Length;
+class SecurityOrigin;
class ImageResource : public Resource, public ImageObserver {
friend class MemoryCache;
public:
+ typedef ImageResourceClient ClientType;
+
ImageResource(const ResourceRequest&);
ImageResource(WebCore::Image*);
virtual ~ImageResource();
@@ -64,6 +67,9 @@ public:
bool usesImageContainerSize() const;
bool imageHasRelativeWidth() const;
bool imageHasRelativeHeight() const;
+ // The device pixel ratio we got from the server for this image, or 1.0.
+ float devicePixelRatioHeaderValue() const { return m_devicePixelRatioHeaderValue; }
+ bool hasDevicePixelRatioHeaderValue() const { return m_hasDevicePixelRatioHeaderValue; }
enum SizeType {
NormalSize, // Report the size of the image associated with a certain renderer
@@ -73,6 +79,8 @@ public:
LayoutSize imageSizeForRenderer(const RenderObject*, float multiplier, SizeType = NormalSize); // returns the size of the complete image.
void computeIntrinsicDimensions(Length& intrinsicWidth, Length& intrinsicHeight, FloatSize& intrinsicRatio);
+ bool isAccessAllowed(SecurityOrigin*);
+
virtual void didAddClient(ResourceClient*);
virtual void didRemoveClient(ResourceClient*);
@@ -113,12 +121,16 @@ private:
typedef pair<IntSize, float> SizeAndZoom;
typedef HashMap<const ImageResourceClient*, SizeAndZoom> ContainerSizeRequests;
ContainerSizeRequests m_pendingContainerSizeRequests;
+ float m_devicePixelRatioHeaderValue;
RefPtr<WebCore::Image> m_image;
OwnPtr<SVGImageCache> m_svgImageCache;
bool m_loadingMultipartContent;
+ bool m_hasDevicePixelRatioHeaderValue;
};
+DEFINE_RESOURCE_TYPE_CASTS(Image);
+
}
#endif
diff --git a/chromium/third_party/WebKit/Source/core/fetch/ImageResourceTest.cpp b/chromium/third_party/WebKit/Source/core/fetch/ImageResourceTest.cpp
index f1a269a5478..c54767ec5eb 100644
--- a/chromium/third_party/WebKit/Source/core/fetch/ImageResourceTest.cpp
+++ b/chromium/third_party/WebKit/Source/core/fetch/ImageResourceTest.cpp
@@ -37,13 +37,10 @@
#include "core/fetch/ResourceFetcher.h"
#include "core/fetch/ResourcePtr.h"
#include "core/loader/DocumentLoader.h"
-#include "core/loader/EmptyClients.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameView.h"
-#include "core/page/Page.h"
-#include "core/platform/SharedBuffer.h"
+#include "core/testing/DummyPageHolder.h"
+#include "core/testing/UnitTestHelpers.h"
+#include "platform/SharedBuffer.h"
#include "public/platform/Platform.h"
-#include "public/platform/WebThread.h"
#include "public/platform/WebURL.h"
#include "public/platform/WebURLResponse.h"
#include "public/platform/WebUnitTestSupport.h"
@@ -52,20 +49,6 @@ using namespace WebCore;
namespace {
-class QuitTask : public WebKit::WebThread::Task {
-public:
- virtual void run()
- {
- WebKit::Platform::current()->currentThread()->exitRunLoop();
- }
-};
-
-void runPendingTasks()
-{
- WebKit::Platform::current()->currentThread()->postTask(new QuitTask);
- WebKit::Platform::current()->currentThread()->enterRunLoop();
-}
-
TEST(ImageResourceTest, MultipartImage)
{
ResourcePtr<ImageResource> cachedImage = new ImageResource(ResourceRequest());
@@ -114,23 +97,17 @@ TEST(ImageResourceTest, CancelOnDetach)
{
KURL testURL(ParsedURLString, "http://www.test.com/cancelTest.html");
- WebKit::WebURLResponse response;
+ blink::WebURLResponse response;
response.initialize();
response.setMIMEType("text/html");
- WTF::String localPath = WebKit::Platform::current()->unitTestSupport()->webKitRootDir();
+ WTF::String localPath = blink::Platform::current()->unitTestSupport()->webKitRootDir();
localPath.append("/Source/web/tests/data/cancelTest.html");
- WebKit::Platform::current()->unitTestSupport()->registerMockedURL(testURL, response, localPath);
+ blink::Platform::current()->unitTestSupport()->registerMockedURL(testURL, response, localPath);
// Create enough of a mocked world to get a functioning ResourceLoader.
- Page::PageClients pageClients;
- fillWithEmptyClients(pageClients);
- EmptyFrameLoaderClient frameLoaderClient;
- Page page(pageClients);
- RefPtr<Frame> frame = Frame::create(&page, 0, &frameLoaderClient);
- frame->setView(FrameView::create(frame.get()));
- frame->init();
+ OwnPtr<DummyPageHolder> dummyPageHolder = DummyPageHolder::create();
RefPtr<DocumentLoader> documentLoader = DocumentLoader::create(ResourceRequest(testURL), SubstituteData());
- documentLoader->setFrame(frame.get());
+ documentLoader->setFrame(&dummyPageHolder->frame());
// Emulate starting a real load.
ResourcePtr<ImageResource> cachedImage = new ImageResource(ResourceRequest(testURL));
@@ -147,11 +124,11 @@ TEST(ImageResourceTest, CancelOnDetach)
EXPECT_NE(reinterpret_cast<Resource*>(0), memoryCache()->resourceForURL(testURL));
// Trigger the cancel timer, ensure the load was cancelled and the resource was evicted from the cache.
- runPendingTasks();
+ WebCore::testing::runPendingTasks();
EXPECT_EQ(Resource::LoadError, cachedImage->status());
EXPECT_EQ(reinterpret_cast<Resource*>(0), memoryCache()->resourceForURL(testURL));
- WebKit::Platform::current()->unitTestSupport()->unregisterMockedURL(testURL);
+ blink::Platform::current()->unitTestSupport()->unregisterMockedURL(testURL);
}
} // namespace
diff --git a/chromium/third_party/WebKit/Source/core/fetch/MemoryCache.cpp b/chromium/third_party/WebKit/Source/core/fetch/MemoryCache.cpp
index af4809ecff4..bdc1df2a4b3 100644
--- a/chromium/third_party/WebKit/Source/core/fetch/MemoryCache.cpp
+++ b/chromium/third_party/WebKit/Source/core/fetch/MemoryCache.cpp
@@ -25,17 +25,16 @@
#include "core/dom/CrossThreadTask.h"
#include "core/dom/Document.h"
-#include "core/fetch/Resource.h"
#include "core/fetch/ResourcePtr.h"
-#include "core/page/FrameView.h"
-#include "core/platform/Logging.h"
-#include "core/platform/chromium/TraceEvent.h"
+#include "core/frame/FrameView.h"
#include "core/workers/WorkerGlobalScope.h"
#include "core/workers/WorkerLoaderProxy.h"
#include "core/workers/WorkerThread.h"
+#include "platform/Logging.h"
+#include "platform/TraceEvent.h"
+#include "platform/weborigin/SecurityOrigin.h"
+#include "platform/weborigin/SecurityOriginHash.h"
#include "public/platform/Platform.h"
-#include "weborigin/SecurityOrigin.h"
-#include "weborigin/SecurityOriginHash.h"
#include "wtf/Assertions.h"
#include "wtf/CurrentTime.h"
#include "wtf/MathExtras.h"
@@ -75,9 +74,9 @@ MemoryCache::MemoryCache()
, m_minDeadCapacity(0)
, m_maxDeadCapacity(cDefaultCacheCapacity)
, m_maxDeferredPruneDeadCapacity(cDeferredPruneDeadCapacityFactor * cDefaultCacheCapacity)
+ , m_delayBeforeLiveDecodedPrune(cMinDelayBeforeLiveDecodedPrune)
, m_liveSize(0)
, m_deadSize(0)
- , m_delayBeforeLiveDecodedPrune(cMinDelayBeforeLiveDecodedPrune)
#ifdef MEMORY_CACHE_STATS
, m_statsTimer(this, &MemoryCache::dumpStats)
#endif
@@ -92,7 +91,7 @@ MemoryCache::MemoryCache()
MemoryCache::~MemoryCache()
{
if (m_prunePending)
- WebKit::Platform::current()->currentThread()->removeTaskObserver(this);
+ blink::Platform::current()->currentThread()->removeTaskObserver(this);
}
KURL MemoryCache::removeFragmentIdentifierIfNeeded(const KURL& originalURL)
@@ -116,7 +115,7 @@ void MemoryCache::add(Resource* resource)
resource->setInCache(true);
resource->updateForAccess();
- LOG(ResourceLoading, "MemoryCache::add Added '%s', resource %p\n", resource->url().string().latin1().data(), resource);
+ WTF_LOG(ResourceLoading, "MemoryCache::add Added '%s', resource %p\n", resource->url().string().latin1().data(), resource);
}
void MemoryCache::replace(Resource* newResource, Resource* oldResource)
@@ -146,16 +145,16 @@ Resource* MemoryCache::resourceForURL(const KURL& resourceURL)
return resource;
}
-unsigned MemoryCache::deadCapacity() const
+size_t MemoryCache::deadCapacity() const
{
// Dead resource capacity is whatever space is not occupied by live resources, bounded by an independent minimum and maximum.
- unsigned capacity = m_capacity - min(m_liveSize, m_capacity); // Start with available capacity.
+ size_t capacity = m_capacity - min(m_liveSize, m_capacity); // Start with available capacity.
capacity = max(capacity, m_minDeadCapacity); // Make sure it's above the minimum.
capacity = min(capacity, m_maxDeadCapacity); // Make sure it's below the maximum.
return capacity;
}
-unsigned MemoryCache::liveCapacity() const
+size_t MemoryCache::liveCapacity() const
{
// Live resource capacity is whatever is left over after calculating dead resource capacity.
return m_capacity - deadCapacity();
@@ -164,11 +163,11 @@ unsigned MemoryCache::liveCapacity() const
void MemoryCache::pruneLiveResources()
{
ASSERT(!m_prunePending);
- unsigned capacity = liveCapacity();
+ size_t capacity = liveCapacity();
if (!m_liveSize || (capacity && m_liveSize <= capacity))
return;
- unsigned targetSize = static_cast<unsigned>(capacity * cTargetPrunePercentage); // Cut by a percentage to avoid immediately pruning again.
+ size_t targetSize = static_cast<size_t>(capacity * cTargetPrunePercentage); // Cut by a percentage to avoid immediately pruning again.
// Destroy any decoded data in live objects that we can.
// Start from the tail, since this is the lowest priority
@@ -207,11 +206,11 @@ void MemoryCache::pruneLiveResources()
void MemoryCache::pruneDeadResources()
{
- unsigned capacity = deadCapacity();
+ size_t capacity = deadCapacity();
if (!m_deadSize || (capacity && m_deadSize <= capacity))
return;
- unsigned targetSize = static_cast<unsigned>(capacity * cTargetPrunePercentage); // Cut by a percentage to avoid immediately pruning again.
+ size_t targetSize = static_cast<size_t>(capacity * cTargetPrunePercentage); // Cut by a percentage to avoid immediately pruning again.
int size = m_allResources.size();
@@ -281,7 +280,7 @@ void MemoryCache::pruneDeadResources()
}
}
-void MemoryCache::setCapacities(unsigned minDeadBytes, unsigned maxDeadBytes, unsigned totalBytes)
+void MemoryCache::setCapacities(size_t minDeadBytes, size_t maxDeadBytes, size_t totalBytes)
{
ASSERT(minDeadBytes <= maxDeadBytes);
ASSERT(maxDeadBytes <= totalBytes);
@@ -295,7 +294,7 @@ void MemoryCache::setCapacities(unsigned minDeadBytes, unsigned maxDeadBytes, un
void MemoryCache::evict(Resource* resource)
{
ASSERT(WTF::isMainThread());
- LOG(ResourceLoading, "Evicting resource %p for '%s' from cache", resource, resource->url().string().latin1().data());
+ WTF_LOG(ResourceLoading, "Evicting resource %p for '%s' from cache", resource, resource->url().string().latin1().data());
// The resource may have already been removed by someone other than our caller,
// who needed a fresh copy for a reload. See <http://bugs.webkit.org/show_bug.cgi?id=12479#c6>.
if (resource->inCache()) {
@@ -306,7 +305,7 @@ void MemoryCache::evict(Resource* resource)
// Remove from the appropriate LRU list.
removeFromLRUList(resource);
removeFromLiveDecodedResourcesList(resource);
- adjustSize(resource->hasClients(), -static_cast<int>(resource->size()));
+ adjustSize(resource->hasClients(), -static_cast<ptrdiff_t>(resource->size()));
} else {
ASSERT(m_resources.get(resource->url()) != resource);
}
@@ -477,28 +476,30 @@ void MemoryCache::insertInLiveDecodedResourcesList(Resource* resource)
void MemoryCache::addToLiveResourcesSize(Resource* resource)
{
+ ASSERT(m_deadSize >= resource->size());
m_liveSize += resource->size();
m_deadSize -= resource->size();
}
void MemoryCache::removeFromLiveResourcesSize(Resource* resource)
{
+ ASSERT(m_liveSize >= resource->size());
m_liveSize -= resource->size();
m_deadSize += resource->size();
}
-void MemoryCache::adjustSize(bool live, int delta)
+void MemoryCache::adjustSize(bool live, ptrdiff_t delta)
{
if (live) {
- ASSERT(delta >= 0 || ((int)m_liveSize + delta >= 0));
+ ASSERT(delta >= 0 || m_liveSize >= static_cast<size_t>(-delta) );
m_liveSize += delta;
} else {
- ASSERT(delta >= 0 || ((int)m_deadSize + delta >= 0));
+ ASSERT(delta >= 0 || m_deadSize >= static_cast<size_t>(-delta) );
m_deadSize += delta;
}
}
-void MemoryCache::removeURLFromCache(ScriptExecutionContext* context, const KURL& url)
+void MemoryCache::removeURLFromCache(ExecutionContext* context, const KURL& url)
{
if (context->isWorkerGlobalScope()) {
WorkerGlobalScope* workerGlobalScope = toWorkerGlobalScope(context);
@@ -508,7 +509,7 @@ void MemoryCache::removeURLFromCache(ScriptExecutionContext* context, const KURL
removeURLFromCacheInternal(context, url);
}
-void MemoryCache::removeURLFromCacheInternal(ScriptExecutionContext*, const KURL& url)
+void MemoryCache::removeURLFromCacheInternal(ExecutionContext*, const KURL& url)
{
if (Resource* resource = memoryCache()->resourceForURL(url))
memoryCache()->remove(resource);
@@ -518,7 +519,7 @@ void MemoryCache::TypeStatistic::addResource(Resource* o)
{
bool purged = o->wasPurged();
bool purgeable = o->isPurgeable() && !purged;
- int pageSize = (o->encodedSize() + o->overheadSize() + 4095) & ~4095;
+ size_t pageSize = (o->encodedSize() + o->overheadSize() + 4095) & ~4095;
count++;
size += purged ? 0 : o->size();
liveSize += o->hasClients() ? o->size() : 0;
@@ -595,7 +596,7 @@ void MemoryCache::prune(Resource* justReleasedResource)
pruneNow(currentTime); // Delay exceeded, prune now.
} else {
// Defer.
- WebKit::Platform::current()->currentThread()->addTaskObserver(this);
+ blink::Platform::current()->currentThread()->addTaskObserver(this);
m_prunePending = true;
}
}
@@ -630,7 +631,7 @@ void MemoryCache::pruneNow(double currentTime)
{
if (m_prunePending) {
m_prunePending = false;
- WebKit::Platform::current()->currentThread()->removeTaskObserver(this);
+ blink::Platform::current()->currentThread()->removeTaskObserver(this);
}
TemporaryChange<bool> reentrancyProtector(m_inPruneResources, true);
diff --git a/chromium/third_party/WebKit/Source/core/fetch/MemoryCache.h b/chromium/third_party/WebKit/Source/core/fetch/MemoryCache.h
index f038244d45c..7944256513d 100644
--- a/chromium/third_party/WebKit/Source/core/fetch/MemoryCache.h
+++ b/chromium/third_party/WebKit/Source/core/fetch/MemoryCache.h
@@ -39,7 +39,7 @@ class CSSStyleSheetResource;
class Resource;
class ResourceFetcher;
class KURL;
-class ScriptExecutionContext;
+class ExecutionContext;
class SecurityOrigin;
struct SecurityOriginHash;
@@ -59,7 +59,7 @@ struct SecurityOriginHash;
// Enable this macro to periodically log information about the memory cache.
#undef MEMORY_CACHE_STATS
-class MemoryCache : public WebKit::WebThread::TaskObserver {
+class MemoryCache : public blink::WebThread::TaskObserver {
WTF_MAKE_NONCOPYABLE(MemoryCache); WTF_MAKE_FAST_ALLOCATED;
public:
MemoryCache();
@@ -120,7 +120,7 @@ public:
// - minDeadBytes: The maximum number of bytes that dead resources should consume when the cache is under pressure.
// - maxDeadBytes: The maximum number of bytes that dead resources should consume when the cache is not under pressure.
// - totalBytes: The maximum number of bytes that the cache should consume overall.
- void setCapacities(unsigned minDeadBytes, unsigned maxDeadBytes, unsigned totalBytes);
+ void setCapacities(size_t minDeadBytes, size_t maxDeadBytes, size_t totalBytes);
void setDelayBeforeLiveDecodedPrune(double seconds) { m_delayBeforeLiveDecodedPrune = seconds; }
void setMaxPruneDeferralDelay(double seconds) { m_maxPruneDeferralDelay = seconds; }
@@ -133,7 +133,7 @@ public:
void removeFromLRUList(Resource*);
// Called to adjust the cache totals when a resource changes size.
- void adjustSize(bool live, int delta);
+ void adjustSize(bool live, ptrdiff_t delta);
// Track decoded resources that are in the cache and referenced by a Web page.
void insertInLiveDecodedResourcesList(Resource*);
@@ -142,15 +142,15 @@ public:
void addToLiveResourcesSize(Resource*);
void removeFromLiveResourcesSize(Resource*);
- static void removeURLFromCache(ScriptExecutionContext*, const KURL&);
+ static void removeURLFromCache(ExecutionContext*, const KURL&);
Statistics getStatistics();
- unsigned minDeadCapacity() const { return m_minDeadCapacity; }
- unsigned maxDeadCapacity() const { return m_maxDeadCapacity; }
- unsigned capacity() const { return m_capacity; }
- unsigned liveSize() const { return m_liveSize; }
- unsigned deadSize() const { return m_deadSize; }
+ size_t minDeadCapacity() const { return m_minDeadCapacity; }
+ size_t maxDeadCapacity() const { return m_maxDeadCapacity; }
+ size_t capacity() const { return m_capacity; }
+ size_t liveSize() const { return m_liveSize; }
+ size_t deadSize() const { return m_deadSize; }
// TaskObserver implementation
virtual void willProcessTask() OVERRIDE;
@@ -164,8 +164,8 @@ private:
void dumpLRULists(bool includeLive) const;
#endif
- unsigned liveCapacity() const;
- unsigned deadCapacity() const;
+ size_t liveCapacity() const;
+ size_t deadCapacity() const;
// pruneDeadResources() - Flush decoded and encoded data from resources not referenced by Web pages.
// pruneLiveResources() - Flush decoded data from resources still referenced by Web pages.
@@ -175,7 +175,7 @@ private:
void evict(Resource*);
- static void removeURLFromCacheInternal(ScriptExecutionContext*, const KURL&);
+ static void removeURLFromCacheInternal(ExecutionContext*, const KURL&);
bool m_inPruneResources;
bool m_prunePending;
@@ -184,15 +184,15 @@ private:
double m_pruneTimeStamp;
double m_pruneFrameTimeStamp;
- unsigned m_capacity;
- unsigned m_minDeadCapacity;
- unsigned m_maxDeadCapacity;
- unsigned m_maxDeferredPruneDeadCapacity;
+ size_t m_capacity;
+ size_t m_minDeadCapacity;
+ size_t m_maxDeadCapacity;
+ size_t m_maxDeferredPruneDeadCapacity;
double m_delayBeforeLiveDecodedPrune;
double m_deadDecodedDataDeletionInterval;
- unsigned m_liveSize; // The number of bytes currently consumed by "live" resources in the cache.
- unsigned m_deadSize; // The number of bytes currently consumed by "dead" resources in the cache.
+ size_t m_liveSize; // The number of bytes currently consumed by "live" resources in the cache.
+ size_t m_deadSize; // The number of bytes currently consumed by "dead" resources in the cache.
// Size-adjusted and popularity-aware LRU list collection for cache objects. This collection can hold
// more resources than the cached resource map, since it can also hold "stale" multiple versions of objects that are
diff --git a/chromium/third_party/WebKit/Source/core/fetch/MemoryCacheTest.cpp b/chromium/third_party/WebKit/Source/core/fetch/MemoryCacheTest.cpp
index b5a4dfaf783..90fecd0ca2e 100644
--- a/chromium/third_party/WebKit/Source/core/fetch/MemoryCacheTest.cpp
+++ b/chromium/third_party/WebKit/Source/core/fetch/MemoryCacheTest.cpp
@@ -34,7 +34,7 @@
#include "core/fetch/MockImageResourceClient.h"
#include "core/fetch/RawResource.h"
#include "core/fetch/ResourcePtr.h"
-#include "core/platform/network/ResourceRequest.h"
+#include "platform/network/ResourceRequest.h"
#include "public/platform/Platform.h"
#include "wtf/OwnPtr.h"
@@ -63,6 +63,19 @@ public:
}
};
+ class FakeResource : public WebCore::Resource {
+ public:
+ FakeResource(const ResourceRequest& request, Type type)
+ : Resource(request, type)
+ {
+ }
+
+ void fakeEncodedSize(size_t size)
+ {
+ setEncodedSize(size);
+ }
+ };
+
protected:
virtual void SetUp()
{
@@ -89,16 +102,45 @@ protected:
// Verifies that setters and getters for cache capacities work correcty.
TEST_F(MemoryCacheTest, CapacityAccounting)
{
- const unsigned totalCapacity = 100;
- const unsigned minDeadCapacity = 10;
- const unsigned maxDeadCapacity = 50;
+ const size_t sizeMax = ~static_cast<size_t>(0);
+ const size_t totalCapacity = sizeMax / 4;
+ const size_t minDeadCapacity = sizeMax / 16;
+ const size_t maxDeadCapacity = sizeMax / 8;
memoryCache()->setCapacities(minDeadCapacity, maxDeadCapacity, totalCapacity);
-
ASSERT_EQ(totalCapacity, memoryCache()->capacity());
ASSERT_EQ(minDeadCapacity, memoryCache()->minDeadCapacity());
ASSERT_EQ(maxDeadCapacity, memoryCache()->maxDeadCapacity());
}
+TEST_F(MemoryCacheTest, VeryLargeResourceAccounting)
+{
+ const size_t sizeMax = ~static_cast<size_t>(0);
+ const size_t totalCapacity = sizeMax / 4;
+ const size_t minDeadCapacity = sizeMax / 16;
+ const size_t maxDeadCapacity = sizeMax / 8;
+ const size_t resourceSize1 = sizeMax / 16;
+ const size_t resourceSize2 = sizeMax / 20;
+ memoryCache()->setCapacities(minDeadCapacity, maxDeadCapacity, totalCapacity);
+ ResourcePtr<FakeResource> cachedResource =
+ new FakeResource(ResourceRequest(""), Resource::Raw);
+ cachedResource->fakeEncodedSize(resourceSize1);
+
+ ASSERT_EQ(0u, memoryCache()->deadSize());
+ ASSERT_EQ(0u, memoryCache()->liveSize());
+ memoryCache()->add(cachedResource.get());
+ ASSERT_EQ(cachedResource->size(), memoryCache()->deadSize());
+ ASSERT_EQ(0u, memoryCache()->liveSize());
+
+ MockImageResourceClient client;
+ cachedResource->addClient(&client);
+ ASSERT_EQ(0u, memoryCache()->deadSize());
+ ASSERT_EQ(cachedResource->size(), memoryCache()->liveSize());
+
+ cachedResource->fakeEncodedSize(resourceSize2);
+ ASSERT_EQ(0u, memoryCache()->deadSize());
+ ASSERT_EQ(cachedResource->size(), memoryCache()->liveSize());
+}
+
// Verifies that dead resources that exceed dead resource capacity are evicted
// from cache when pruning.
TEST_F(MemoryCacheTest, DeadResourceEviction)
@@ -149,7 +191,7 @@ TEST_F(MemoryCacheTest, LiveResourceEvictionAtEndOfTask)
cachedLiveResource->addClient(&client);
cachedLiveResource->appendData(data, 4);
- class Task1 : public WebKit::WebThread::Task {
+ class Task1 : public blink::WebThread::Task {
public:
Task1(const ResourcePtr<Resource>& live, const ResourcePtr<Resource>& dead)
: m_live(live)
@@ -183,7 +225,7 @@ TEST_F(MemoryCacheTest, LiveResourceEvictionAtEndOfTask)
ResourcePtr<Resource> m_live, m_dead;
};
- class Task2 : public WebKit::WebThread::Task {
+ class Task2 : public blink::WebThread::Task {
public:
Task2(unsigned liveSizeWithoutDecode)
: m_liveSizeWithoutDecode(liveSizeWithoutDecode) { }
@@ -193,7 +235,7 @@ TEST_F(MemoryCacheTest, LiveResourceEvictionAtEndOfTask)
// Next task: now, the live resource was evicted.
ASSERT_EQ(0u, memoryCache()->deadSize());
ASSERT_EQ(m_liveSizeWithoutDecode, memoryCache()->liveSize());
- WebKit::Platform::current()->currentThread()->exitRunLoop();
+ blink::Platform::current()->currentThread()->exitRunLoop();
}
private:
@@ -201,9 +243,9 @@ TEST_F(MemoryCacheTest, LiveResourceEvictionAtEndOfTask)
};
- WebKit::Platform::current()->currentThread()->postTask(new Task1(cachedLiveResource, cachedDeadResource));
- WebKit::Platform::current()->currentThread()->postTask(new Task2(cachedLiveResource->encodedSize() + cachedLiveResource->overheadSize()));
- WebKit::Platform::current()->currentThread()->enterRunLoop();
+ blink::Platform::current()->currentThread()->postTask(new Task1(cachedLiveResource, cachedDeadResource));
+ blink::Platform::current()->currentThread()->postTask(new Task2(cachedLiveResource->encodedSize() + cachedLiveResource->overheadSize()));
+ blink::Platform::current()->currentThread()->enterRunLoop();
cachedLiveResource->removeClient(&client);
}
diff --git a/chromium/third_party/WebKit/Source/core/fetch/RawResource.cpp b/chromium/third_party/WebKit/Source/core/fetch/RawResource.cpp
index 5745d93c470..c58b8440f54 100644
--- a/chromium/third_party/WebKit/Source/core/fetch/RawResource.cpp
+++ b/chromium/third_party/WebKit/Source/core/fetch/RawResource.cpp
@@ -26,11 +26,10 @@
#include "config.h"
#include "core/fetch/RawResource.h"
-#include "core/fetch/ResourceClient.h"
#include "core/fetch/ResourceClientWalker.h"
#include "core/fetch/ResourceFetcher.h"
#include "core/fetch/ResourceLoader.h"
-#include "core/platform/SharedBuffer.h"
+#include "platform/SharedBuffer.h"
namespace WebCore {
@@ -93,7 +92,7 @@ void RawResource::willSendRequest(ResourceRequest& request, const ResourceRespon
void RawResource::responseReceived(const ResourceResponse& response)
{
- ResourcePtr<RawResource> protect(this);
+ InternalResourcePtr protect(this);
Resource::responseReceived(response);
ResourceClientWalker<RawResourceClient> w(m_clients);
while (RawResourceClient* c = w.next())
@@ -131,7 +130,6 @@ static bool shouldIgnoreHeaderForCacheReuse(AtomicString headerName)
// FIXME: This list of headers that don't affect cache policy almost certainly isn't complete.
DEFINE_STATIC_LOCAL(HashSet<AtomicString>, m_headers, ());
if (m_headers.isEmpty()) {
- m_headers.add("Accept");
m_headers.add("Cache-Control");
m_headers.add("If-Modified-Since");
m_headers.add("If-None-Match");
diff --git a/chromium/third_party/WebKit/Source/core/fetch/RawResource.h b/chromium/third_party/WebKit/Source/core/fetch/RawResource.h
index 0ed0bc08ce1..e1b6753e0c9 100644
--- a/chromium/third_party/WebKit/Source/core/fetch/RawResource.h
+++ b/chromium/third_party/WebKit/Source/core/fetch/RawResource.h
@@ -23,8 +23,8 @@
#ifndef RawResource_h
#define RawResource_h
-#include "core/fetch/Resource.h"
#include "core/fetch/ResourceClient.h"
+#include "core/fetch/ResourcePtr.h"
namespace WebCore {
class RawResourceCallback;
@@ -32,6 +32,8 @@ class RawResourceClient;
class RawResource : public Resource {
public:
+ typedef RawResourceClient ClientType;
+
RawResource(const ResourceRequest&, Type);
// FIXME: AssociatedURLLoader shouldn't be a DocumentThreadableLoader and therefore shouldn't
@@ -71,6 +73,18 @@ private:
Vector<RedirectPair> m_redirectChain;
};
+#ifdef SECURITY_ASSERT_ENABLED
+inline bool isRawResource(const Resource& resource)
+{
+ Resource::Type type = resource.type();
+ return type == Resource::MainResource || type == Resource::Raw || type == Resource::TextTrack || type == Resource::ImportResource;
+}
+#endif
+inline RawResource* toRawResource(const ResourcePtr<Resource>& resource)
+{
+ ASSERT_WITH_SECURITY_IMPLICATION(!resource || isRawResource(*resource.get()));
+ return static_cast<RawResource*>(resource.get());
+}
class RawResourceClient : public ResourceClient {
public:
diff --git a/chromium/third_party/WebKit/Source/core/fetch/RawResourceTest.cpp b/chromium/third_party/WebKit/Source/core/fetch/RawResourceTest.cpp
new file mode 100644
index 00000000000..3c4d0099479
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/fetch/RawResourceTest.cpp
@@ -0,0 +1,89 @@
+/*
+ * Copyright (c) 2013, Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/fetch/RawResource.h"
+
+#include "core/fetch/ImageResourceClient.h"
+#include "core/fetch/MemoryCache.h"
+#include "core/fetch/MockImageResourceClient.h"
+#include "core/fetch/ResourceFetcher.h"
+#include "core/fetch/ResourcePtr.h"
+#include "core/loader/DocumentLoader.h"
+#include "core/testing/DummyPageHolder.h"
+#include "core/testing/UnitTestHelpers.h"
+#include "platform/SharedBuffer.h"
+#include "public/platform/Platform.h"
+#include "public/platform/WebURL.h"
+#include "public/platform/WebURLResponse.h"
+#include "public/platform/WebUnitTestSupport.h"
+
+using namespace WebCore;
+
+namespace {
+
+TEST(RawResourceTest, DontIgnoreAcceptForCacheReuse)
+{
+ ResourceRequest jpegRequest;
+ jpegRequest.setHTTPAccept("image/jpeg");
+
+ RawResource jpegResource(jpegRequest, Resource::Raw);
+
+ ResourceRequest pngRequest;
+ pngRequest.setHTTPAccept("image/png");
+
+ ASSERT_FALSE(jpegResource.canReuse(pngRequest));
+}
+
+TEST(RawResourceTest, RevalidationSucceeded)
+{
+ // Create two RawResources and set one to revalidate the other.
+ RawResource* oldResourcePointer = new RawResource(ResourceRequest("data:text/html,"), Resource::Raw);
+ RawResource* newResourcePointer = new RawResource(ResourceRequest("data:text/html,"), Resource::Raw);
+ newResourcePointer->setResourceToRevalidate(oldResourcePointer);
+ ResourcePtr<Resource> oldResource = oldResourcePointer;
+ ResourcePtr<Resource> newResource = newResourcePointer;
+ memoryCache()->add(oldResource.get());
+ memoryCache()->remove(oldResource.get());
+ memoryCache()->add(newResource.get());
+
+ // Simulate a successful revalidation.
+ // The revalidated resource (oldResource) should now be in the cache, newResource
+ // should have been sliently switched to point to the revalidated resource, and
+ // we shouldn't hit any ASSERTs.
+ ResourceResponse response;
+ response.setHTTPStatusCode(304);
+ newResource->responseReceived(response);
+ EXPECT_EQ(memoryCache()->resourceForURL(KURL(ParsedURLString, "data:text/html,")), oldResource.get());
+ EXPECT_EQ(oldResource.get(), newResource.get());
+ EXPECT_NE(newResource.get(), newResourcePointer);
+}
+
+} // namespace
diff --git a/chromium/third_party/WebKit/Source/core/fetch/Resource.cpp b/chromium/third_party/WebKit/Source/core/fetch/Resource.cpp
index 0736d26f803..8f56b290ade 100644
--- a/chromium/third_party/WebKit/Source/core/fetch/Resource.cpp
+++ b/chromium/third_party/WebKit/Source/core/fetch/Resource.cpp
@@ -33,11 +33,11 @@
#include "core/fetch/ResourceLoader.h"
#include "core/fetch/ResourcePtr.h"
#include "core/inspector/InspectorInstrumentation.h"
-#include "core/platform/Logging.h"
-#include "core/platform/PurgeableBuffer.h"
-#include "core/platform/SharedBuffer.h"
+#include "platform/Logging.h"
+#include "platform/PurgeableBuffer.h"
+#include "platform/SharedBuffer.h"
+#include "platform/weborigin/KURL.h"
#include "public/platform/Platform.h"
-#include "weborigin/KURL.h"
#include "wtf/CurrentTime.h"
#include "wtf/MathExtras.h"
#include "wtf/RefCountedLeakCounter.h"
@@ -105,6 +105,7 @@ Resource::Resource(const ResourceRequest& request, Type type)
, m_accessCount(0)
, m_handleCount(0)
, m_preloadCount(0)
+ , m_protectorCount(0)
, m_preloadResult(PreloadNotReferenced)
, m_cacheLiveResourcePriority(CacheLiveResourcePriorityLow)
, m_inLiveDecodedResourcesList(false)
@@ -155,7 +156,7 @@ Resource::~Resource()
void Resource::failBeforeStarting()
{
- LOG(ResourceLoading, "Cannot start loading '%s'", url().string().latin1().data());
+ WTF_LOG(ResourceLoading, "Cannot start loading '%s'", url().string().latin1().data());
error(Resource::LoadError);
}
@@ -182,6 +183,11 @@ void Resource::load(ResourceFetcher* fetcher, const ResourceLoaderOptions& optio
m_fragmentIdentifierForRequest = String();
}
m_status = Pending;
+ if (m_loader) {
+ RELEASE_ASSERT(m_options.synchronousPolicy == RequestSynchronously);
+ m_loader->changeToSynchronous();
+ return;
+ }
m_loader = ResourceLoader::create(fetcher, this, request, options);
m_loader->start();
}
@@ -198,6 +204,7 @@ void Resource::checkNotify()
void Resource::appendData(const char* data, int length)
{
+ TRACE_EVENT0("webkit", "Resource::appendData");
ASSERT(!m_resourceToRevalidate);
ASSERT(!errorOccurred());
if (m_options.dataBufferingPolicy == DoNotBufferData)
@@ -345,7 +352,7 @@ void Resource::setCachedMetadata(unsigned dataTypeID, const char* data, size_t s
m_cachedMetadata = CachedMetadata::create(dataTypeID, data, size);
const Vector<char>& serializedData = m_cachedMetadata->serialize();
- WebKit::Platform::current()->cacheMetadata(m_response.url(), m_response.responseTime(), serializedData.data(), serializedData.size());
+ blink::Platform::current()->cacheMetadata(m_response.url(), m_response.responseTime(), serializedData.data(), serializedData.size());
}
CachedMetadata* Resource::cachedMetadata(unsigned dataTypeID) const
@@ -357,7 +364,7 @@ CachedMetadata* Resource::cachedMetadata(unsigned dataTypeID) const
void Resource::setCacheLiveResourcePriority(CacheLiveResourcePriority priority)
{
- if (inCache() && m_inLiveDecodedResourcesList && m_cacheLiveResourcePriority != priority) {
+ if (inCache() && m_inLiveDecodedResourcesList && cacheLiveResourcePriority() != static_cast<unsigned>(priority)) {
memoryCache()->removeFromLiveDecodedResourcesList(this);
m_cacheLiveResourcePriority = priority;
memoryCache()->insertInLiveDecodedResourcesList(this);
@@ -493,12 +500,12 @@ bool Resource::deleteIfPossible()
return false;
}
-void Resource::setDecodedSize(unsigned size)
+void Resource::setDecodedSize(size_t size)
{
if (size == m_decodedSize)
return;
- int delta = size - m_decodedSize;
+ ptrdiff_t delta = size - m_decodedSize;
// The object must now be moved to a different queue, since its size has been changed.
// We have to remove explicitly before updating m_decodedSize, so that we find the correct previous
@@ -529,12 +536,12 @@ void Resource::setDecodedSize(unsigned size)
}
}
-void Resource::setEncodedSize(unsigned size)
+void Resource::setEncodedSize(size_t size)
{
if (size == m_encodedSize)
return;
- int delta = size - m_encodedSize;
+ ptrdiff_t delta = size - m_encodedSize;
// The object must now be moved to a different queue, since its size has been changed.
// We have to remove explicitly before updating m_encodedSize, so that we find the correct previous
@@ -583,7 +590,7 @@ void Resource::setResourceToRevalidate(Resource* resource)
ASSERT(m_handlesToRevalidate.isEmpty());
ASSERT(resource->type() == type());
- LOG(ResourceLoading, "Resource %p setResourceToRevalidate %p", this, resource);
+ WTF_LOG(ResourceLoading, "Resource %p setResourceToRevalidate %p", this, resource);
// The following assert should be investigated whenever it occurs. Although it should never fire, it currently does in rare circumstances.
// https://bugs.webkit.org/show_bug.cgi?id=28604.
@@ -616,7 +623,7 @@ void Resource::switchClientsToRevalidatedResource()
ASSERT(m_resourceToRevalidate->inCache());
ASSERT(!inCache());
- LOG(ResourceLoading, "Resource %p switchClientsToRevalidatedResource %p", this, m_resourceToRevalidate);
+ WTF_LOG(ResourceLoading, "Resource %p switchClientsToRevalidatedResource %p", this, m_resourceToRevalidate);
m_resourceToRevalidate->m_identifier = m_identifier;
@@ -704,7 +711,7 @@ void Resource::revalidationSucceeded(const ResourceResponse& response)
void Resource::revalidationFailed()
{
ASSERT(WTF::isMainThread());
- LOG(ResourceLoading, "Revalidation failed for %p", this);
+ WTF_LOG(ResourceLoading, "Revalidation failed for %p", this);
ASSERT(resourceToRevalidate());
clearResourceToRevalidate();
}
@@ -754,29 +761,15 @@ bool Resource::canUseCacheValidator() const
return m_response.hasCacheValidatorFields();
}
-bool Resource::mustRevalidateDueToCacheHeaders(CachePolicy cachePolicy) const
+bool Resource::mustRevalidateDueToCacheHeaders() const
{
- ASSERT(cachePolicy == CachePolicyRevalidate || cachePolicy == CachePolicyCache || cachePolicy == CachePolicyVerify);
-
- if (cachePolicy == CachePolicyRevalidate)
- return true;
-
if (m_response.cacheControlContainsNoCache() || m_response.cacheControlContainsNoStore()) {
- LOG(ResourceLoading, "Resource %p mustRevalidate because of m_response.cacheControlContainsNoCache() || m_response.cacheControlContainsNoStore()\n", this);
+ WTF_LOG(ResourceLoading, "Resource %p mustRevalidate because of m_response.cacheControlContainsNoCache() || m_response.cacheControlContainsNoStore()\n", this);
return true;
}
- if (cachePolicy == CachePolicyCache) {
- if (m_response.cacheControlContainsMustRevalidate() && isExpired()) {
- LOG(ResourceLoading, "Resource %p mustRevalidate because of cachePolicy == CachePolicyCache and m_response.cacheControlContainsMustRevalidate() && isExpired()\n", this);
- return true;
- }
- return false;
- }
-
- // CachePolicyVerify
if (isExpired()) {
- LOG(ResourceLoading, "Resource %p mustRevalidate because of isExpired()\n", this);
+ WTF_LOG(ResourceLoading, "Resource %p mustRevalidate because of isExpired()\n", this);
return true;
}
@@ -837,7 +830,7 @@ bool Resource::wasPurged() const
return m_purgeableData && m_purgeableData->wasPurged();
}
-unsigned Resource::overheadSize() const
+size_t Resource::overheadSize() const
{
static const int kAverageClientsHashMapSize = 384;
return sizeof(Resource) + m_response.memoryUsage() + kAverageClientsHashMapSize + m_resourceRequest.url().string().length() * 2;
@@ -885,5 +878,40 @@ void Resource::ResourceCallback::timerFired(Timer<ResourceCallback>*)
resources[i]->finishPendingClients();
}
+#if !LOG_DISABLED
+const char* ResourceTypeName(Resource::Type type)
+{
+ switch (type) {
+ case Resource::MainResource:
+ return "MainResource";
+ case Resource::Image:
+ return "Image";
+ case Resource::CSSStyleSheet:
+ return "CSSStyleSheet";
+ case Resource::Script:
+ return "Script";
+ case Resource::Font:
+ return "Font";
+ case Resource::Raw:
+ return "Raw";
+ case Resource::SVGDocument:
+ return "SVGDocument";
+ case Resource::XSLStyleSheet:
+ return "XSLStyleSheet";
+ case Resource::LinkPrefetch:
+ return "LinkPrefetch";
+ case Resource::LinkSubresource:
+ return "LinkSubresource";
+ case Resource::TextTrack:
+ return "TextTrack";
+ case Resource::Shader:
+ return "Shader";
+ case Resource::ImportResource:
+ return "ImportResource";
+ }
+ ASSERT_NOT_REACHED();
+ return "Unknown";
}
+#endif // !LOG_DISABLED
+}
diff --git a/chromium/third_party/WebKit/Source/core/fetch/Resource.h b/chromium/third_party/WebKit/Source/core/fetch/Resource.h
index ba300c96dac..968e7577264 100644
--- a/chromium/third_party/WebKit/Source/core/fetch/Resource.h
+++ b/chromium/third_party/WebKit/Source/core/fetch/Resource.h
@@ -23,13 +23,12 @@
#ifndef Resource_h
#define Resource_h
-#include "core/fetch/CachePolicy.h"
#include "core/fetch/ResourceLoaderOptions.h"
-#include "core/platform/Timer.h"
-#include "core/platform/network/ResourceError.h"
-#include "core/platform/network/ResourceLoadPriority.h"
-#include "core/platform/network/ResourceRequest.h"
-#include "core/platform/network/ResourceResponse.h"
+#include "platform/Timer.h"
+#include "platform/network/ResourceError.h"
+#include "platform/network/ResourceLoadPriority.h"
+#include "platform/network/ResourceRequest.h"
+#include "platform/network/ResourceResponse.h"
#include "wtf/HashCountedSet.h"
#include "wtf/HashSet.h"
#include "wtf/OwnPtr.h"
@@ -109,7 +108,8 @@ public:
ResourceRequest& resourceRequest() { return m_resourceRequest; }
const KURL& url() const { return m_resourceRequest.url();}
Type type() const { return static_cast<Type>(m_type); }
- const ResourceLoaderOptions& options() const { return m_options; }
+ const ResourceLoaderOptions& options() const { return m_options; }
+ void setOptions(const ResourceLoaderOptions& options) { m_options = options; }
void didChangePriority(ResourceLoadPriority);
@@ -135,10 +135,10 @@ public:
Status status() const { return static_cast<Status>(m_status); }
void setStatus(Status status) { m_status = status; }
- unsigned size() const { return encodedSize() + decodedSize() + overheadSize(); }
- unsigned encodedSize() const { return m_encodedSize; }
- unsigned decodedSize() const { return m_decodedSize; }
- unsigned overheadSize() const;
+ size_t size() const { return encodedSize() + decodedSize() + overheadSize(); }
+ size_t encodedSize() const { return m_encodedSize; }
+ size_t decodedSize() const { return m_decodedSize; }
+ size_t overheadSize() const;
bool isLoaded() const { return !m_loading; } // FIXME. Method name is inaccurate. Loading might not have started yet.
@@ -200,7 +200,7 @@ public:
// Returns cached metadata of the given type associated with this resource.
CachedMetadata* cachedMetadata(unsigned dataTypeID) const;
- bool canDelete() const { return !hasClients() && !m_loader && !m_preloadCount && !m_handleCount && !m_resourceToRevalidate && !m_proxyResource; }
+ bool canDelete() const { return !hasClients() && !m_loader && !m_preloadCount && !m_handleCount && !m_protectorCount && !m_resourceToRevalidate && !m_proxyResource; }
bool hasOneHandle() const { return m_handleCount == 1; }
bool isExpired() const;
@@ -227,7 +227,7 @@ public:
void unregisterHandle(ResourcePtrBase* h);
bool canUseCacheValidator() const;
- bool mustRevalidateDueToCacheHeaders(CachePolicy) const;
+ bool mustRevalidateDueToCacheHeaders() const;
bool isCacheValidator() const { return m_resourceToRevalidate; }
Resource* resourceToRevalidate() const { return m_resourceToRevalidate; }
void setResourceToRevalidate(Resource*);
@@ -251,8 +251,34 @@ protected:
virtual void checkNotify();
virtual void finishOnePart();
- void setEncodedSize(unsigned);
- void setDecodedSize(unsigned);
+ // Normal resource pointers will silently switch what Resource* they reference when we
+ // successfully revalidated the resource. We need a way to guarantee that the Resource
+ // that received the 304 response survives long enough to switch everything over to the
+ // revalidatedresource. The normal mechanisms for keeping a Resource alive externally
+ // (ResourcePtrs and ResourceClients registering themselves) don't work in this case, so
+ // have a separate internal protector).
+ class InternalResourcePtr {
+ public:
+ explicit InternalResourcePtr(Resource* resource)
+ : m_resource(resource)
+ {
+ m_resource->incrementProtectorCount();
+ }
+
+ ~InternalResourcePtr()
+ {
+ m_resource->decrementProtectorCount();
+ m_resource->deleteIfPossible();
+ }
+ private:
+ Resource* m_resource;
+ };
+
+ void incrementProtectorCount() { m_protectorCount++; }
+ void decrementProtectorCount() { m_protectorCount--; }
+
+ void setEncodedSize(size_t);
+ void setDecodedSize(size_t);
void didAccessDecodedData(double timeStamp);
bool isSafeToMakePurgeable() const;
@@ -315,11 +341,12 @@ private:
unsigned long m_identifier;
- unsigned m_encodedSize;
- unsigned m_decodedSize;
+ size_t m_encodedSize;
+ size_t m_decodedSize;
unsigned m_accessCount;
unsigned m_handleCount;
unsigned m_preloadCount;
+ unsigned m_protectorCount;
unsigned m_preloadResult : 2; // PreloadResult
unsigned m_cacheLiveResourcePriority : 2; // CacheLiveResourcePriority
@@ -358,6 +385,15 @@ private:
HashSet<ResourcePtrBase*> m_handlesToRevalidate;
};
+#if !LOG_DISABLED
+// Intended to be used in LOG statements.
+const char* ResourceTypeName(Resource::Type);
+#endif
+
+#define DEFINE_RESOURCE_TYPE_CASTS(typeName) \
+ DEFINE_TYPE_CASTS(typeName##Resource, Resource, resource, resource->type() == Resource::typeName, resource.type() == Resource::typeName); \
+ inline typeName##Resource* to##typeName##Resource(const ResourcePtr<Resource>& ptr) { return to##typeName##Resource(ptr.get()); }
+
}
#endif
diff --git a/chromium/third_party/WebKit/Source/core/fetch/ResourceClient.h b/chromium/third_party/WebKit/Source/core/fetch/ResourceClient.h
index ae7b7bbcf0c..937f78731cc 100644
--- a/chromium/third_party/WebKit/Source/core/fetch/ResourceClient.h
+++ b/chromium/third_party/WebKit/Source/core/fetch/ResourceClient.h
@@ -44,7 +44,6 @@ public:
virtual ~ResourceClient() { }
virtual void notifyFinished(Resource*) { }
- virtual void deprecatedDidReceiveResource(Resource*) { }
static ResourceClientType expectedType() { return BaseResourceType; }
virtual ResourceClientType resourceClientType() const { return expectedType(); }
diff --git a/chromium/third_party/WebKit/Source/core/fetch/ResourceFetcher.cpp b/chromium/third_party/WebKit/Source/core/fetch/ResourceFetcher.cpp
index 337a6779252..799fc87065d 100644
--- a/chromium/third_party/WebKit/Source/core/fetch/ResourceFetcher.cpp
+++ b/chromium/third_party/WebKit/Source/core/fetch/ResourceFetcher.cpp
@@ -27,12 +27,12 @@
#include "config.h"
#include "core/fetch/ResourceFetcher.h"
+#include "RuntimeEnabledFeatures.h"
#include "bindings/v8/ScriptController.h"
#include "core/dom/Document.h"
#include "core/fetch/CSSStyleSheetResource.h"
#include "core/fetch/DocumentResource.h"
#include "core/fetch/FetchContext.h"
-#include "core/fetch/FetchRequest.h"
#include "core/fetch/FontResource.h"
#include "core/fetch/ImageResource.h"
#include "core/fetch/MemoryCache.h"
@@ -41,7 +41,6 @@
#include "core/fetch/ResourceLoaderSet.h"
#include "core/fetch/ScriptResource.h"
#include "core/fetch/ShaderResource.h"
-#include "core/fetch/TextTrackResource.h"
#include "core/fetch/XSLStyleSheetResource.h"
#include "core/html/HTMLElement.h"
#include "core/html/HTMLFrameOwnerElement.h"
@@ -53,18 +52,18 @@
#include "core/loader/PingLoader.h"
#include "core/loader/UniqueIdentifier.h"
#include "core/loader/appcache/ApplicationCacheHost.h"
-#include "core/page/ContentSecurityPolicy.h"
-#include "core/page/DOMWindow.h"
-#include "core/page/Frame.h"
-#include "core/page/Performance.h"
-#include "core/page/ResourceTimingInfo.h"
-#include "core/page/Settings.h"
-#include "core/platform/Logging.h"
-#include "core/platform/chromium/TraceEvent.h"
+#include "core/frame/ContentSecurityPolicy.h"
+#include "core/frame/DOMWindow.h"
+#include "core/frame/Frame.h"
+#include "core/timing/Performance.h"
+#include "core/timing/ResourceTimingInfo.h"
+#include "core/frame/Settings.h"
+#include "platform/Logging.h"
+#include "platform/TraceEvent.h"
+#include "platform/weborigin/SecurityOrigin.h"
+#include "platform/weborigin/SecurityPolicy.h"
#include "public/platform/Platform.h"
#include "public/platform/WebURL.h"
-#include "weborigin/SecurityOrigin.h"
-#include "weborigin/SecurityPolicy.h"
#include "wtf/text/CString.h"
#include "wtf/text/WTFString.h"
@@ -85,8 +84,9 @@ static Resource* createResource(Resource::Type type, const ResourceRequest& requ
return new DocumentResource(request, Resource::SVGDocument);
case Resource::Font:
return new FontResource(request);
- case Resource::Raw:
case Resource::MainResource:
+ case Resource::Raw:
+ case Resource::TextTrack:
return new RawResource(request, type);
case Resource::XSLStyleSheet:
return new XSLStyleSheetResource(request);
@@ -94,8 +94,6 @@ static Resource* createResource(Resource::Type type, const ResourceRequest& requ
return new Resource(request, Resource::LinkPrefetch);
case Resource::LinkSubresource:
return new Resource(request, Resource::LinkSubresource);
- case Resource::TextTrack:
- return new TextTrackResource(request);
case Resource::Shader:
return new ShaderResource(request);
case Resource::ImportResource:
@@ -123,8 +121,11 @@ static ResourceLoadPriority loadPriority(Resource::Type type, const FetchRequest
case Resource::ImportResource:
return ResourceLoadPriorityMedium;
case Resource::Image:
- return request.forPreload() ? ResourceLoadPriorityVeryLow : ResourceLoadPriorityLow;
+ // We'll default images to VeryLow, and promote whatever is visible. This improves
+ // speed-index by ~5% on average, ~14% at the 99th percentile.
+ return ResourceLoadPriorityVeryLow;
case Resource::XSLStyleSheet:
+ ASSERT(RuntimeEnabledFeatures::xsltEnabled());
return ResourceLoadPriorityHigh;
case Resource::SVGDocument:
return ResourceLoadPriorityLow;
@@ -141,19 +142,20 @@ static ResourceLoadPriority loadPriority(Resource::Type type, const FetchRequest
return ResourceLoadPriorityUnresolved;
}
-static Resource* resourceFromDataURIRequest(const ResourceRequest& request)
+static Resource* resourceFromDataURIRequest(const ResourceRequest& request, const ResourceLoaderOptions& resourceOptions)
{
const KURL& url = request.url();
ASSERT(url.protocolIsData());
- WebKit::WebString mimetype;
- WebKit::WebString charset;
- RefPtr<SharedBuffer> data = PassRefPtr<SharedBuffer>(WebKit::Platform::current()->parseDataURL(url, mimetype, charset));
+ blink::WebString mimetype;
+ blink::WebString charset;
+ RefPtr<SharedBuffer> data = PassRefPtr<SharedBuffer>(blink::Platform::current()->parseDataURL(url, mimetype, charset));
if (!data)
return 0;
ResourceResponse response(url, mimetype, data->size(), charset, String());
Resource* resource = createResource(Resource::Image, request, charset);
+ resource->setOptions(resourceOptions);
resource->responseReceived(response);
// FIXME: AppendData causes an unnecessary memcpy.
if (data->size())
@@ -162,11 +164,67 @@ static Resource* resourceFromDataURIRequest(const ResourceRequest& request)
return resource;
}
+static void populateResourceTiming(ResourceTimingInfo* info, Resource* resource, bool clearLoadTimings)
+{
+ info->setInitialRequest(resource->resourceRequest());
+ info->setFinalResponse(resource->response());
+ if (clearLoadTimings)
+ info->clearLoadTimings();
+ info->setLoadFinishTime(resource->loadFinishTime());
+}
+
+static void reportResourceTiming(ResourceTimingInfo* info, Document* initiatorDocument, bool isMainResource)
+{
+ if (initiatorDocument && isMainResource)
+ initiatorDocument = initiatorDocument->parentDocument();
+ if (!initiatorDocument || !initiatorDocument->loader())
+ return;
+ if (DOMWindow* initiatorWindow = initiatorDocument->domWindow()) {
+ if (Performance* performance = initiatorWindow->performance())
+ performance->addResourceTiming(*info, initiatorDocument);
+ }
+}
+
+static ResourceRequest::TargetType requestTargetType(const ResourceFetcher* fetcher, const ResourceRequest& request, Resource::Type type)
+{
+ switch (type) {
+ case Resource::MainResource:
+ if (fetcher->frame()->tree().parent())
+ return ResourceRequest::TargetIsSubframe;
+ return ResourceRequest::TargetIsMainFrame;
+ case Resource::XSLStyleSheet:
+ ASSERT(RuntimeEnabledFeatures::xsltEnabled());
+ case Resource::CSSStyleSheet:
+ return ResourceRequest::TargetIsStyleSheet;
+ case Resource::Script:
+ return ResourceRequest::TargetIsScript;
+ case Resource::Font:
+ return ResourceRequest::TargetIsFont;
+ case Resource::Image:
+ return ResourceRequest::TargetIsImage;
+ case Resource::Shader:
+ case Resource::Raw:
+ case Resource::ImportResource:
+ return ResourceRequest::TargetIsSubresource;
+ case Resource::LinkPrefetch:
+ return ResourceRequest::TargetIsPrefetch;
+ case Resource::LinkSubresource:
+ return ResourceRequest::TargetIsSubresource;
+ case Resource::TextTrack:
+ return ResourceRequest::TargetIsTextTrack;
+ case Resource::SVGDocument:
+ return ResourceRequest::TargetIsImage;
+ }
+ ASSERT_NOT_REACHED();
+ return ResourceRequest::TargetIsSubresource;
+}
+
ResourceFetcher::ResourceFetcher(DocumentLoader* documentLoader)
: m_document(0)
, m_documentLoader(documentLoader)
, m_requestCount(0)
, m_garbageCollectDocumentResourcesTimer(this, &ResourceFetcher::garbageCollectDocumentResourcesTimerFired)
+ , m_resourceTimingReportTimer(this, &ResourceFetcher::resourceTimingReportTimerFired)
, m_autoLoadImages(true)
, m_imagesEnabled(true)
, m_allowStaleResources(false)
@@ -227,7 +285,7 @@ ResourcePtr<ImageResource> ResourceFetcher::fetchImage(FetchRequest& request)
if (Frame* f = frame()) {
if (f->document()->pageDismissalEventBeingDispatched() != Document::NoDismissal) {
KURL requestURL = request.resourceRequest().url();
- if (requestURL.isValid() && canRequest(Resource::Image, requestURL, request.options(), request.forPreload()))
+ if (requestURL.isValid() && canRequest(Resource::Image, requestURL, request.options(), request.forPreload(), request.originRestriction()))
PingLoader::loadImage(f, requestURL);
return 0;
}
@@ -237,7 +295,7 @@ ResourcePtr<ImageResource> ResourceFetcher::fetchImage(FetchRequest& request)
preCacheDataURIImage(request);
request.setDefer(clientDefersImage(request.resourceRequest().url()) ? FetchRequest::DeferredByClient : FetchRequest::NoDefer);
- return static_cast<ImageResource*>(requestResource(Resource::Image, request).get());
+ return toImageResource(requestResource(Resource::Image, request));
}
void ResourceFetcher::preCacheDataURIImage(const FetchRequest& request)
@@ -245,36 +303,31 @@ void ResourceFetcher::preCacheDataURIImage(const FetchRequest& request)
const KURL& url = request.resourceRequest().url();
ASSERT(url.protocolIsData());
- if (Resource* existing = memoryCache()->resourceForURL(url))
+ if (memoryCache()->resourceForURL(url))
return;
- if (Resource* resource = resourceFromDataURIRequest(request.resourceRequest()))
+ if (Resource* resource = resourceFromDataURIRequest(request.resourceRequest(), request.options()))
memoryCache()->add(resource);
}
ResourcePtr<FontResource> ResourceFetcher::fetchFont(FetchRequest& request)
{
- return static_cast<FontResource*>(requestResource(Resource::Font, request).get());
-}
-
-ResourcePtr<TextTrackResource> ResourceFetcher::fetchTextTrack(FetchRequest& request)
-{
- return static_cast<TextTrackResource*>(requestResource(Resource::TextTrack, request).get());
+ return toFontResource(requestResource(Resource::Font, request));
}
ResourcePtr<ShaderResource> ResourceFetcher::fetchShader(FetchRequest& request)
{
- return static_cast<ShaderResource*>(requestResource(Resource::Shader, request).get());
+ return toShaderResource(requestResource(Resource::Shader, request));
}
ResourcePtr<RawResource> ResourceFetcher::fetchImport(FetchRequest& request)
{
- return static_cast<RawResource*>(requestResource(Resource::ImportResource, request).get());
+ return toRawResource(requestResource(Resource::ImportResource, request));
}
ResourcePtr<CSSStyleSheetResource> ResourceFetcher::fetchCSSStyleSheet(FetchRequest& request)
{
- return static_cast<CSSStyleSheetResource*>(requestResource(Resource::CSSStyleSheet, request).get());
+ return toCSSStyleSheetResource(requestResource(Resource::CSSStyleSheet, request));
}
ResourcePtr<CSSStyleSheetResource> ResourceFetcher::fetchUserCSSStyleSheet(FetchRequest& request)
@@ -283,27 +336,28 @@ ResourcePtr<CSSStyleSheetResource> ResourceFetcher::fetchUserCSSStyleSheet(Fetch
if (Resource* existing = memoryCache()->resourceForURL(url)) {
if (existing->type() == Resource::CSSStyleSheet)
- return static_cast<CSSStyleSheetResource*>(existing);
+ return toCSSStyleSheetResource(existing);
memoryCache()->remove(existing);
}
- request.setOptions(ResourceLoaderOptions(DoNotSendCallbacks, SniffContent, BufferData, AllowStoredCredentials, ClientRequestedCredentials, AskClientForCrossOriginCredentials, SkipSecurityCheck, CheckContentSecurityPolicy, UseDefaultOriginRestrictionsForType, DocumentContext));
- return static_cast<CSSStyleSheetResource*>(requestResource(Resource::CSSStyleSheet, request).get());
+ request.setOptions(ResourceLoaderOptions(DoNotSendCallbacks, SniffContent, BufferData, AllowStoredCredentials, ClientRequestedCredentials, AskClientForCrossOriginCredentials, SkipSecurityCheck, CheckContentSecurityPolicy, DocumentContext));
+ return toCSSStyleSheetResource(requestResource(Resource::CSSStyleSheet, request));
}
ResourcePtr<ScriptResource> ResourceFetcher::fetchScript(FetchRequest& request)
{
- return static_cast<ScriptResource*>(requestResource(Resource::Script, request).get());
+ return toScriptResource(requestResource(Resource::Script, request));
}
ResourcePtr<XSLStyleSheetResource> ResourceFetcher::fetchXSLStyleSheet(FetchRequest& request)
{
- return static_cast<XSLStyleSheetResource*>(requestResource(Resource::XSLStyleSheet, request).get());
+ ASSERT(RuntimeEnabledFeatures::xsltEnabled());
+ return toXSLStyleSheetResource(requestResource(Resource::XSLStyleSheet, request));
}
ResourcePtr<DocumentResource> ResourceFetcher::fetchSVGDocument(FetchRequest& request)
{
- return static_cast<DocumentResource*>(requestResource(Resource::SVGDocument, request).get());
+ return toDocumentResource(requestResource(Resource::SVGDocument, request));
}
ResourcePtr<Resource> ResourceFetcher::fetchLinkResource(Resource::Type type, FetchRequest& request)
@@ -315,20 +369,21 @@ ResourcePtr<Resource> ResourceFetcher::fetchLinkResource(Resource::Type type, Fe
ResourcePtr<RawResource> ResourceFetcher::fetchRawResource(FetchRequest& request)
{
- return static_cast<RawResource*>(requestResource(Resource::Raw, request).get());
+ return toRawResource(requestResource(Resource::Raw, request));
}
ResourcePtr<RawResource> ResourceFetcher::fetchMainResource(FetchRequest& request)
{
- return static_cast<RawResource*>(requestResource(Resource::MainResource, request).get());
+ return toRawResource(requestResource(Resource::MainResource, request));
}
bool ResourceFetcher::checkInsecureContent(Resource::Type type, const KURL& url, MixedContentBlockingTreatment treatment) const
{
if (treatment == TreatAsDefaultForType) {
switch (type) {
- case Resource::Script:
case Resource::XSLStyleSheet:
+ ASSERT(RuntimeEnabledFeatures::xsltEnabled());
+ case Resource::Script:
case Resource::SVGDocument:
case Resource::CSSStyleSheet:
case Resource::ImportResource:
@@ -356,13 +411,16 @@ bool ResourceFetcher::checkInsecureContent(Resource::Type type, const KURL& url,
}
if (treatment == TreatAsActiveContent) {
if (Frame* f = frame()) {
- if (!f->loader()->mixedContentChecker()->canRunInsecureContent(m_document->securityOrigin(), url))
+ if (!f->loader().mixedContentChecker()->canRunInsecureContent(m_document->securityOrigin(), url))
+ return false;
+ Frame* top = f->tree().top();
+ if (top != f && !top->loader().mixedContentChecker()->canRunInsecureContent(top->document()->securityOrigin(), url))
return false;
}
} else if (treatment == TreatAsPassiveContent) {
if (Frame* f = frame()) {
- Frame* top = f->tree()->top();
- if (!top->loader()->mixedContentChecker()->canDisplayInsecureContent(top->document()->securityOrigin(), url))
+ Frame* top = f->tree().top();
+ if (!top->loader().mixedContentChecker()->canDisplayInsecureContent(top->document()->securityOrigin(), url))
return false;
}
} else {
@@ -371,17 +429,21 @@ bool ResourceFetcher::checkInsecureContent(Resource::Type type, const KURL& url,
return true;
}
-bool ResourceFetcher::canRequest(Resource::Type type, const KURL& url, const ResourceLoaderOptions& options, bool forPreload)
+bool ResourceFetcher::canRequest(Resource::Type type, const KURL& url, const ResourceLoaderOptions& options, bool forPreload, FetchRequest::OriginRestriction originRestriction)
{
- if (document() && !document()->securityOrigin()->canDisplay(url)) {
+ SecurityOrigin* securityOrigin = options.securityOrigin.get();
+ if (!securityOrigin && document())
+ securityOrigin = document()->securityOrigin();
+
+ if (securityOrigin && !securityOrigin->canDisplay(url)) {
if (!forPreload)
context().reportLocalLoadFailed(url);
- LOG(ResourceLoading, "ResourceFetcher::requestResource URL was not allowed by SecurityOrigin::canDisplay");
+ WTF_LOG(ResourceLoading, "ResourceFetcher::requestResource URL was not allowed by SecurityOrigin::canDisplay");
return 0;
}
// FIXME: Convert this to check the isolated world's Content Security Policy once webkit.org/b/104520 is solved.
- bool shouldBypassMainWorldContentSecurityPolicy = (frame() && frame()->script()->shouldBypassMainWorldContentSecurityPolicy()) || (options.contentSecurityPolicyOption == DoNotCheckContentSecurityPolicy);
+ bool shouldBypassMainWorldContentSecurityPolicy = (frame() && frame()->script().shouldBypassMainWorldContentSecurityPolicy()) || (options.contentSecurityPolicyOption == DoNotCheckContentSecurityPolicy);
// Some types of resources can be loaded only from the same origin. Other
// types of resources, like Images, Scripts, and CSS, can be loaded from
@@ -400,14 +462,15 @@ bool ResourceFetcher::canRequest(Resource::Type type, const KURL& url, const Res
case Resource::ImportResource:
// By default these types of resources can be loaded from any origin.
// FIXME: Are we sure about Resource::Font?
- if (options.requestOriginPolicy == RestrictToSameOrigin && !m_document->securityOrigin()->canRequest(url)) {
+ if (originRestriction == FetchRequest::RestrictToSameOrigin && !securityOrigin->canRequest(url)) {
printAccessDeniedMessage(url);
return false;
}
break;
- case Resource::SVGDocument:
case Resource::XSLStyleSheet:
- if (!m_document->securityOrigin()->canRequest(url)) {
+ ASSERT(RuntimeEnabledFeatures::xsltEnabled());
+ case Resource::SVGDocument:
+ if (!securityOrigin->canRequest(url)) {
printAccessDeniedMessage(url);
return false;
}
@@ -416,6 +479,7 @@ bool ResourceFetcher::canRequest(Resource::Type type, const KURL& url, const Res
switch (type) {
case Resource::XSLStyleSheet:
+ ASSERT(RuntimeEnabledFeatures::xsltEnabled());
if (!shouldBypassMainWorldContentSecurityPolicy && !m_document->contentSecurityPolicy()->allowScriptFromSource(url))
return false;
break;
@@ -426,8 +490,8 @@ bool ResourceFetcher::canRequest(Resource::Type type, const KURL& url, const Res
if (frame()) {
Settings* settings = frame()->settings();
- if (!frame()->loader()->client()->allowScriptFromSource(!settings || settings->isScriptEnabled(), url)) {
- frame()->loader()->client()->didNotAllowScript();
+ if (!frame()->loader().client()->allowScriptFromSource(!settings || settings->isScriptEnabled(), url)) {
+ frame()->loader().client()->didNotAllowScript();
return false;
}
}
@@ -454,8 +518,6 @@ bool ResourceFetcher::canRequest(Resource::Type type, const KURL& url, const Res
case Resource::LinkSubresource:
break;
case Resource::TextTrack:
- // Cues aren't called out in the CPS spec yet, but they only work with a media element
- // so use the media policy.
if (!shouldBypassMainWorldContentSecurityPolicy && !m_document->contentSecurityPolicy()->allowMediaFromSource(url))
return false;
break;
@@ -472,17 +534,17 @@ bool ResourceFetcher::canRequest(Resource::Type type, const KURL& url, const Res
return true;
}
-bool ResourceFetcher::canAccess(Resource* resource)
+bool ResourceFetcher::canAccess(Resource* resource, CORSEnabled corsEnabled, FetchRequest::OriginRestriction originRestriction)
{
// Redirects can change the response URL different from one of request.
- if (!canRequest(resource->type(), resource->response().url(), resource->options(), false))
+ if (!canRequest(resource->type(), resource->response().url(), resource->options(), false, originRestriction))
return false;
String error;
switch (resource->type()) {
case Resource::Script:
case Resource::ImportResource:
- if (resource->options().requestOriginPolicy == PotentiallyCrossOriginEnabled
+ if (corsEnabled == PotentiallyCORSEnabled
&& !m_document->securityOrigin()->canRequest(resource->response().url())
&& !resource->passesAccessControlCheck(m_document->securityOrigin(), error)) {
if (frame() && frame()->document())
@@ -505,7 +567,20 @@ bool ResourceFetcher::shouldLoadNewResource() const
return false;
if (!m_documentLoader)
return true;
- return m_documentLoader == frame()->loader()->activeDocumentLoader();
+ if (m_documentLoader == frame()->loader().activeDocumentLoader())
+ return true;
+ return document() && document()->pageDismissalEventBeingDispatched() != Document::NoDismissal;
+}
+
+bool ResourceFetcher::resourceNeedsLoad(Resource* resource, const FetchRequest& request, RevalidationPolicy policy)
+{
+ if (FetchRequest::DeferredByClient == request.defer())
+ return false;
+ if (policy != Use)
+ return true;
+ if (resource->stillNeedsLoad())
+ return true;
+ return request.options().synchronousPolicy == RequestSynchronously && resource->isLoading();
}
ResourcePtr<Resource> ResourceFetcher::requestResource(Resource::Type type, FetchRequest& request)
@@ -514,7 +589,7 @@ ResourcePtr<Resource> ResourceFetcher::requestResource(Resource::Type type, Fetc
KURL url = request.resourceRequest().url();
- LOG(ResourceLoading, "ResourceFetcher::requestResource '%s', charset '%s', priority=%d, forPreload=%u", url.elidedString().latin1().data(), request.charset().latin1().data(), request.priority(), request.forPreload());
+ WTF_LOG(ResourceLoading, "ResourceFetcher::requestResource '%s', charset '%s', priority=%d, forPreload=%u, type=%s", url.elidedString().latin1().data(), request.charset().latin1().data(), request.priority(), request.forPreload(), ResourceTypeName(type));
// If only the fragment identifiers differ, it is the same resource.
url = MemoryCache::removeFragmentIdentifierIfNeeded(url);
@@ -522,11 +597,11 @@ ResourcePtr<Resource> ResourceFetcher::requestResource(Resource::Type type, Fetc
if (!url.isValid())
return 0;
- if (!canRequest(type, url, request.options(), request.forPreload()))
+ if (!canRequest(type, url, request.options(), request.forPreload(), request.originRestriction()))
return 0;
if (Frame* f = frame())
- f->loader()->client()->dispatchWillRequestResource(&request);
+ f->loader().client()->dispatchWillRequestResource(&request);
// See if we can use an existing resource from the cache.
ResourcePtr<Resource> resource = memoryCache()->resourceForURL(url);
@@ -562,7 +637,7 @@ ResourcePtr<Resource> ResourceFetcher::requestResource(Resource::Type type, Fetc
}
}
- if ((policy != Use || resource->stillNeedsLoad()) && FetchRequest::NoDefer == request.defer()) {
+ if (resourceNeedsLoad(resource.get(), request, policy)) {
if (!shouldLoadNewResource()) {
if (resource->inCache())
memoryCache()->remove(resource.get());
@@ -600,67 +675,47 @@ ResourcePtr<Resource> ResourceFetcher::requestResource(Resource::Type type, Fetc
return 0;
}
- if (!request.resourceRequest().url().protocolIsData())
+ if (!request.resourceRequest().url().protocolIsData()) {
+ if (policy == Use && !m_validatedURLs.contains(request.resourceRequest().url())) {
+ // Resources loaded from memory cache should be reported the first time they're used.
+ RefPtr<ResourceTimingInfo> info = ResourceTimingInfo::create(request.options().initiatorInfo.name, monotonicallyIncreasingTime());
+ populateResourceTiming(info.get(), resource.get(), true);
+ m_scheduledResourceTimingReports.add(info, resource->type() == Resource::MainResource);
+ if (!m_resourceTimingReportTimer.isActive())
+ m_resourceTimingReportTimer.startOneShot(0);
+ }
+
m_validatedURLs.add(request.resourceRequest().url());
+ }
ASSERT(resource->url() == url.string());
m_documentResources.set(resource->url(), resource);
return resource;
}
-void ResourceFetcher::determineTargetType(ResourceRequest& request, Resource::Type type)
+void ResourceFetcher::resourceTimingReportTimerFired(Timer<ResourceFetcher>* timer)
{
- ResourceRequest::TargetType targetType;
-
- switch (type) {
- case Resource::MainResource:
- if (frame()->tree()->parent())
- targetType = ResourceRequest::TargetIsSubframe;
- else
- targetType = ResourceRequest::TargetIsMainFrame;
- break;
- case Resource::CSSStyleSheet:
- case Resource::XSLStyleSheet:
- targetType = ResourceRequest::TargetIsStyleSheet;
- break;
- case Resource::Script:
- targetType = ResourceRequest::TargetIsScript;
- break;
- case Resource::Font:
- targetType = ResourceRequest::TargetIsFont;
- break;
- case Resource::Image:
- targetType = ResourceRequest::TargetIsImage;
- break;
- case Resource::Shader:
- case Resource::Raw:
- case Resource::ImportResource:
- targetType = ResourceRequest::TargetIsSubresource;
- break;
- case Resource::LinkPrefetch:
- targetType = ResourceRequest::TargetIsPrefetch;
- break;
- case Resource::LinkSubresource:
- targetType = ResourceRequest::TargetIsSubresource;
- break;
- case Resource::TextTrack:
- targetType = ResourceRequest::TargetIsTextTrack;
- break;
- case Resource::SVGDocument:
- targetType = ResourceRequest::TargetIsImage;
- break;
- default:
- ASSERT_NOT_REACHED();
- targetType = ResourceRequest::TargetIsSubresource;
- break;
+ ASSERT_UNUSED(timer, timer == &m_resourceTimingReportTimer);
+ HashMap<RefPtr<ResourceTimingInfo>, bool> timingReports;
+ timingReports.swap(m_scheduledResourceTimingReports);
+ HashMap<RefPtr<ResourceTimingInfo>, bool>::iterator end = timingReports.end();
+ for (HashMap<RefPtr<ResourceTimingInfo>, bool>::iterator it = timingReports.begin(); it != end; ++it) {
+ RefPtr<ResourceTimingInfo> info = it->key;
+ bool isMainResource = it->value;
+ reportResourceTiming(info.get(), document(), isMainResource);
}
+}
+
+void ResourceFetcher::determineTargetType(ResourceRequest& request, Resource::Type type)
+{
+ ResourceRequest::TargetType targetType = requestTargetType(this, request, type);
request.setTargetType(targetType);
}
ResourceRequestCachePolicy ResourceFetcher::resourceRequestCachePolicy(const ResourceRequest& request, Resource::Type type)
{
if (type == Resource::MainResource) {
- FrameLoadType frameLoadType = frame()->loader()->loadType();
+ FrameLoadType frameLoadType = frame()->loader().loadType();
bool isReload = frameLoadType == FrameLoadTypeReload || frameLoadType == FrameLoadTypeReloadFromOrigin;
if (request.httpMethod() == "POST" && frameLoadType == FrameLoadTypeBackForward)
return ReturnCacheDataDontLoad;
@@ -668,6 +723,8 @@ ResourceRequestCachePolicy ResourceFetcher::resourceRequestCachePolicy(const Res
return ReturnCacheDataElseLoad;
if (isReload || frameLoadType == FrameLoadTypeSame || request.isConditional() || request.httpMethod() == "POST")
return ReloadIgnoringCacheData;
+ if (Frame* parent = frame()->tree().parent())
+ return parent->document()->fetcher()->resourceRequestCachePolicy(request, type);
return UseProtocolCachePolicy;
}
@@ -711,11 +768,11 @@ ResourcePtr<Resource> ResourceFetcher::revalidateResource(const FetchRequest& re
ResourceRequest revalidatingRequest(resource->resourceRequest());
addAdditionalRequestHeaders(revalidatingRequest, resource->type());
- const String& lastModified = resource->response().httpHeaderField("Last-Modified");
- const String& eTag = resource->response().httpHeaderField("ETag");
+ const AtomicString& lastModified = resource->response().httpHeaderField("Last-Modified");
+ const AtomicString& eTag = resource->response().httpHeaderField("ETag");
if (!lastModified.isEmpty() || !eTag.isEmpty()) {
- ASSERT(context().cachePolicy(resource->type()) != CachePolicyReload);
- if (context().cachePolicy(resource->type()) == CachePolicyRevalidate)
+ ASSERT(context().cachePolicy(document()) != CachePolicyReload);
+ if (context().cachePolicy(document()) == CachePolicyRevalidate)
revalidatingRequest.setHTTPHeaderField("Cache-Control", "max-age=0");
if (!lastModified.isEmpty())
revalidatingRequest.setHTTPHeaderField("If-Modified-Since", lastModified);
@@ -725,7 +782,7 @@ ResourcePtr<Resource> ResourceFetcher::revalidateResource(const FetchRequest& re
ResourcePtr<Resource> newResource = createResource(resource->type(), revalidatingRequest, resource->encoding());
- LOG(ResourceLoading, "Resource %p created to revalidate %p", newResource.get(), resource);
+ WTF_LOG(ResourceLoading, "Resource %p created to revalidate %p", newResource.get(), resource);
newResource->setResourceToRevalidate(resource);
memoryCache()->remove(resource);
@@ -739,7 +796,7 @@ ResourcePtr<Resource> ResourceFetcher::loadResource(Resource::Type type, FetchRe
{
ASSERT(!memoryCache()->resourceForURL(request.resourceRequest().url()));
- LOG(ResourceLoading, "Loading Resource for '%s'.", request.resourceRequest().url().elidedString().latin1().data());
+ WTF_LOG(ResourceLoading, "Loading Resource for '%s'.", request.resourceRequest().url().elidedString().latin1().data());
addAdditionalRequestHeaders(request.mutableResourceRequest(), type);
ResourcePtr<Resource> resource = createResource(type, request.mutableResourceRequest(), charset);
@@ -780,7 +837,7 @@ ResourceFetcher::RevalidationPolicy ResourceFetcher::determineRevalidationPolicy
// If the same URL has been loaded as a different type, we need to reload.
if (existingResource->type() != type) {
- LOG(ResourceLoading, "ResourceFetcher::determineRevalidationPolicy reloading due to type mismatch.");
+ WTF_LOG(ResourceLoading, "ResourceFetcher::determineRevalidationPolicy reloading due to type mismatch.");
return Reload;
}
@@ -812,12 +869,13 @@ ResourceFetcher::RevalidationPolicy ResourceFetcher::determineRevalidationPolicy
return Use;
// CachePolicyHistoryBuffer uses the cache no matter what.
- if (context().cachePolicy(type) == CachePolicyHistoryBuffer)
+ CachePolicy cachePolicy = context().cachePolicy(document());
+ if (cachePolicy == CachePolicyHistoryBuffer)
return Use;
// Don't reuse resources with Cache-control: no-store.
if (existingResource->response().cacheControlContainsNoStore()) {
- LOG(ResourceLoading, "ResourceFetcher::determineRevalidationPolicy reloading due to Cache-control: no-store.");
+ WTF_LOG(ResourceLoading, "ResourceFetcher::determineRevalidationPolicy reloading due to Cache-control: no-store.");
return Reload;
}
@@ -828,23 +886,24 @@ ResourceFetcher::RevalidationPolicy ResourceFetcher::determineRevalidationPolicy
// "Access-Control-Allow-Origin: *" all the time, but some of the
// client's requests are made without CORS and some with.
if (existingResource->resourceRequest().allowCookies() != request.allowCookies()) {
- LOG(ResourceLoading, "ResourceFetcher::determineRevalidationPolicy reloading due to difference in credentials settings.");
+ WTF_LOG(ResourceLoading, "ResourceFetcher::determineRevalidationPolicy reloading due to difference in credentials settings.");
return Reload;
}
- // During the initial load, avoid loading the same resource multiple times for a single document, even if the cache policies would tell us to.
- if (document() && !document()->loadEventFinished() && m_validatedURLs.contains(existingResource->url()))
+ // During the initial load, avoid loading the same resource multiple times for a single document,
+ // even if the cache policies would tell us to. Raw resources are exempted.
+ if (type != Resource::Raw && document() && !document()->loadEventFinished() && m_validatedURLs.contains(existingResource->url()))
return Use;
// CachePolicyReload always reloads
- if (context().cachePolicy(type) == CachePolicyReload) {
- LOG(ResourceLoading, "ResourceFetcher::determineRevalidationPolicy reloading due to CachePolicyReload.");
+ if (cachePolicy == CachePolicyReload) {
+ WTF_LOG(ResourceLoading, "ResourceFetcher::determineRevalidationPolicy reloading due to CachePolicyReload.");
return Reload;
}
// We'll try to reload the resource if it failed last time.
if (existingResource->errorOccurred()) {
- LOG(ResourceLoading, "ResourceFetcher::determineRevalidationPolicye reloading due to resource being in the error state");
+ WTF_LOG(ResourceLoading, "ResourceFetcher::determineRevalidationPolicye reloading due to resource being in the error state");
return Reload;
}
@@ -853,13 +912,13 @@ ResourceFetcher::RevalidationPolicy ResourceFetcher::determineRevalidationPolicy
return Use;
// Check if the cache headers requires us to revalidate (cache expiration for example).
- if (existingResource->mustRevalidateDueToCacheHeaders(context().cachePolicy(type))) {
+ if (cachePolicy == CachePolicyRevalidate || existingResource->mustRevalidateDueToCacheHeaders()) {
// See if the resource has usable ETag or Last-modified headers.
if (existingResource->canUseCacheValidator())
return Revalidate;
// No, must reload.
- LOG(ResourceLoading, "ResourceFetcher::determineRevalidationPolicy reloading due to missing cache validators.");
+ WTF_LOG(ResourceLoading, "ResourceFetcher::determineRevalidationPolicy reloading due to missing cache validators.");
return Reload;
}
@@ -911,7 +970,7 @@ void ResourceFetcher::setImagesEnabled(bool enable)
bool ResourceFetcher::clientDefersImage(const KURL& url) const
{
- return frame() && !frame()->loader()->client()->allowImage(m_imagesEnabled, url);
+ return frame() && !frame()->loader().client()->allowImage(m_imagesEnabled, url);
}
bool ResourceFetcher::shouldDeferImageLoad(const KURL& url) const
@@ -944,22 +1003,15 @@ void ResourceFetcher::didLoadResource(Resource* resource)
if (resource && resource->response().isHTTP() && ((!resource->errorOccurred() && !resource->wasCanceled()) || resource->response().httpStatusCode() == 304) && document()) {
ResourceTimingInfoMap::iterator it = m_resourceTimingInfoMap.find(resource);
if (it != m_resourceTimingInfoMap.end()) {
- Document* initiatorDocument = document();
- if (resource->type() == Resource::MainResource)
- initiatorDocument = document()->parentDocument();
- ASSERT(initiatorDocument);
RefPtr<ResourceTimingInfo> info = it->value;
m_resourceTimingInfoMap.remove(it);
- info->setInitialRequest(resource->resourceRequest());
- info->setFinalResponse(resource->response());
- info->setLoadFinishTime(resource->loadFinishTime());
- if (DOMWindow* initiatorWindow = initiatorDocument->domWindow())
- initiatorWindow->performance()->addResourceTiming(*info, initiatorDocument);
+ populateResourceTiming(info.get(), resource, false);
+ reportResourceTiming(info.get(), document(), resource->type() == Resource::MainResource);
}
}
if (frame())
- frame()->loader()->loadDone();
+ frame()->loader().loadDone();
performPostLoadActions();
if (!m_garbageCollectDocumentResourcesTimer.isActive())
@@ -1010,7 +1062,7 @@ void ResourceFetcher::notifyLoadedFromMemoryCache(Resource* resource)
// FIXME: If willSendRequest changes the request, we don't respect it.
willSendRequest(identifier, request, ResourceResponse(), resource->options());
InspectorInstrumentation::markResourceAsCached(frame()->page(), identifier);
- context().sendRemainingDelegateMessages(m_documentLoader, identifier, resource->response(), 0, resource->encodedSize(), 0, ResourceError());
+ context().sendRemainingDelegateMessages(m_documentLoader, identifier, resource->response(), resource->encodedSize());
}
void ResourceFetcher::incrementRequestCount(const Resource* res)
@@ -1032,24 +1084,12 @@ void ResourceFetcher::decrementRequestCount(const Resource* res)
void ResourceFetcher::preload(Resource::Type type, FetchRequest& request, const String& charset)
{
- bool delaySubresourceLoad = true;
- delaySubresourceLoad = false;
- if (delaySubresourceLoad) {
- bool hasRendering = m_document->body() && m_document->body()->renderer();
- bool canBlockParser = type == Resource::Script || type == Resource::CSSStyleSheet;
- if (!hasRendering && !canBlockParser) {
- // Don't preload subresources that can't block the parser before we have something to draw.
- // This helps prevent preloads from delaying first display when bandwidth is limited.
- PendingPreload pendingPreload = { type, request, charset };
- m_pendingPreloads.append(pendingPreload);
- return;
- }
- }
requestPreload(type, request, charset);
}
void ResourceFetcher::checkForPendingPreloads()
{
+ // FIXME: It seems wrong to poke body()->renderer() here.
if (m_pendingPreloads.isEmpty() || !m_document->body() || !m_document->body()->renderer())
return;
while (!m_pendingPreloads.isEmpty()) {
@@ -1065,7 +1105,7 @@ void ResourceFetcher::requestPreload(Resource::Type type, FetchRequest& request,
{
String encoding;
if (type == Resource::Script || type == Resource::CSSStyleSheet)
- encoding = charset.isEmpty() ? m_document->charset() : charset;
+ encoding = charset.isEmpty() ? m_document->charset().string() : charset;
request.setCharset(encoding);
request.setForPreload(true);
@@ -1073,7 +1113,7 @@ void ResourceFetcher::requestPreload(Resource::Type type, FetchRequest& request,
ResourcePtr<Resource> resource = requestResource(type, request);
if (!resource || (m_preloads && m_preloads->contains(resource.get())))
return;
- TRACE_EVENT_ASYNC_STEP0("net", "Resource", resource.get(), "Preload");
+ TRACE_EVENT_ASYNC_STEP_INTO0("net", "Resource", resource.get(), "Preload");
resource->increasePreloadCount();
if (!m_preloads)
@@ -1141,7 +1181,7 @@ void ResourceFetcher::didFinishLoading(const Resource* resource, double finishTi
void ResourceFetcher::didChangeLoadingPriority(const Resource* resource, ResourceLoadPriority loadPriority)
{
- TRACE_EVENT_ASYNC_STEP1("net", "Resource", resource, "ChangePriority", "priority", loadPriority);
+ TRACE_EVENT_ASYNC_STEP_INTO1("net", "Resource", resource, "ChangePriority", "priority", loadPriority);
context().dispatchDidChangeResourcePriority(resource->identifier(), loadPriority);
}
@@ -1178,6 +1218,15 @@ void ResourceFetcher::didReceiveData(const Resource* resource, const char* data,
InspectorInstrumentation::didReceiveResourceData(cookie);
}
+void ResourceFetcher::didDownloadData(const Resource* resource, int dataLength, int encodedDataLength, const ResourceLoaderOptions& options)
+{
+ InspectorInstrumentationCookie cookie = InspectorInstrumentation::willReceiveResourceData(frame(), resource->identifier(), encodedDataLength);
+ if (options.sendLoadCallbacks != SendCallbacks)
+ return;
+ context().dispatchDidDownloadData(m_documentLoader, resource->identifier(), dataLength, encodedDataLength);
+ InspectorInstrumentation::didReceiveResourceData(cookie);
+}
+
void ResourceFetcher::subresourceLoaderFinishedLoadingOnePart(ResourceLoader* loader)
{
if (m_multipartLoaders)
@@ -1185,7 +1234,7 @@ void ResourceFetcher::subresourceLoaderFinishedLoadingOnePart(ResourceLoader* lo
if (m_loaders)
m_loaders->remove(loader);
if (Frame* frame = this->frame())
- return frame->loader()->checkLoadComplete(m_documentLoader);
+ return frame->loader().checkLoadComplete(m_documentLoader);
}
void ResourceFetcher::didInitializeResourceLoader(ResourceLoader* loader)
@@ -1204,7 +1253,7 @@ void ResourceFetcher::willTerminateResourceLoader(ResourceLoader* loader)
return;
m_loaders->remove(loader);
if (Frame* frame = this->frame())
- frame->loader()->checkLoadComplete(m_documentLoader);
+ frame->loader().checkLoadComplete(m_documentLoader);
}
void ResourceFetcher::willStartLoadingResource(ResourceRequest& request)
@@ -1246,7 +1295,7 @@ bool ResourceFetcher::isLoadedBy(ResourceLoaderHost* possibleOwner) const
bool ResourceFetcher::shouldRequest(Resource* resource, const ResourceRequest& request, const ResourceLoaderOptions& options)
{
- if (!canRequest(resource->type(), request.url(), options))
+ if (!canRequest(resource->type(), request.url(), options, false, FetchRequest::UseDefaultOriginRestrictionForType))
return false;
if (resource->type() == Resource::Image && shouldDeferImageLoad(request.url()))
return false;
@@ -1314,7 +1363,7 @@ void ResourceFetcher::printPreloadStats()
const ResourceLoaderOptions& ResourceFetcher::defaultResourceOptions()
{
- DEFINE_STATIC_LOCAL(ResourceLoaderOptions, options, (SendCallbacks, SniffContent, BufferData, AllowStoredCredentials, ClientRequestedCredentials, AskClientForCrossOriginCredentials, DoSecurityCheck, CheckContentSecurityPolicy, UseDefaultOriginRestrictionsForType, DocumentContext));
+ DEFINE_STATIC_LOCAL(ResourceLoaderOptions, options, (SendCallbacks, SniffContent, BufferData, AllowStoredCredentials, ClientRequestedCredentials, AskClientForCrossOriginCredentials, DoSecurityCheck, CheckContentSecurityPolicy, DocumentContext));
return options;
}
diff --git a/chromium/third_party/WebKit/Source/core/fetch/ResourceFetcher.h b/chromium/third_party/WebKit/Source/core/fetch/ResourceFetcher.h
index 3508cf2eb25..bb1995ed325 100644
--- a/chromium/third_party/WebKit/Source/core/fetch/ResourceFetcher.h
+++ b/chromium/third_party/WebKit/Source/core/fetch/ResourceFetcher.h
@@ -33,7 +33,7 @@
#include "core/fetch/ResourceLoaderHost.h"
#include "core/fetch/ResourceLoaderOptions.h"
#include "core/fetch/ResourcePtr.h"
-#include "core/platform/Timer.h"
+#include "platform/Timer.h"
#include "wtf/Deque.h"
#include "wtf/HashMap.h"
#include "wtf/HashSet.h"
@@ -50,7 +50,6 @@ class ImageResource;
class RawResource;
class ScriptResource;
class ShaderResource;
-class TextTrackResource;
class XSLStyleSheetResource;
class Document;
class DocumentLoader;
@@ -61,6 +60,11 @@ class KURL;
class ResourceTimingInfo;
class ResourceLoaderSet;
+enum CORSEnabled {
+ NotCORSEnabled,
+ PotentiallyCORSEnabled // Indicates "potentially CORS-enabled fetch" in HTML standard.
+};
+
// The ResourceFetcher provides a per-context interface to the MemoryCache
// and enforces a bunch of security checks and rules for resource revalidation.
// Its lifetime is roughly per-DocumentLoader, in that it is generally created
@@ -92,7 +96,6 @@ public:
ResourcePtr<DocumentResource> fetchSVGDocument(FetchRequest&);
ResourcePtr<XSLStyleSheetResource> fetchXSLStyleSheet(FetchRequest&);
ResourcePtr<Resource> fetchLinkResource(Resource::Type, FetchRequest&);
- ResourcePtr<TextTrackResource> fetchTextTrack(FetchRequest&);
ResourcePtr<ShaderResource> fetchShader(FetchRequest&);
ResourcePtr<RawResource> fetchImport(FetchRequest&);
@@ -130,7 +133,7 @@ public:
void preload(Resource::Type, FetchRequest&, const String& charset);
void checkForPendingPreloads();
void printPreloadStats();
- bool canAccess(Resource*);
+ bool canAccess(Resource*, CORSEnabled, FetchRequest::OriginRestriction = FetchRequest::UseDefaultOriginRestrictionForType);
void setDefersLoading(bool);
void stopFetching();
@@ -147,6 +150,7 @@ public:
virtual void willSendRequest(unsigned long identifier, ResourceRequest&, const ResourceResponse& redirectResponse, const ResourceLoaderOptions&) OVERRIDE;
virtual void didReceiveResponse(const Resource*, const ResourceResponse&, const ResourceLoaderOptions&) OVERRIDE;
virtual void didReceiveData(const Resource*, const char* data, int dataLength, int encodedDataLength, const ResourceLoaderOptions&) OVERRIDE;
+ virtual void didDownloadData(const Resource*, int dataLength, int encodedDataLength, const ResourceLoaderOptions&) OVERRIDE;
virtual void subresourceLoaderFinishedLoadingOnePart(ResourceLoader*) OVERRIDE;
virtual void didInitializeResourceLoader(ResourceLoader*) OVERRIDE;
virtual void willTerminateResourceLoader(ResourceLoader*) OVERRIDE;
@@ -178,12 +182,17 @@ private:
ResourceRequestCachePolicy resourceRequestCachePolicy(const ResourceRequest&, Resource::Type);
void addAdditionalRequestHeaders(ResourceRequest&, Resource::Type);
- bool canRequest(Resource::Type, const KURL&, const ResourceLoaderOptions&, bool forPreload = false);
+ bool canRequest(Resource::Type, const KURL&, const ResourceLoaderOptions&, bool forPreload, FetchRequest::OriginRestriction);
bool checkInsecureContent(Resource::Type, const KURL&, MixedContentBlockingTreatment) const;
+ static bool resourceNeedsLoad(Resource*, const FetchRequest&, RevalidationPolicy);
+
void notifyLoadedFromMemoryCache(Resource*);
void garbageCollectDocumentResourcesTimerFired(Timer<ResourceFetcher>*);
+
+ void resourceTimingReportTimerFired(Timer<ResourceFetcher>*);
+
void performPostLoadActions();
bool clientDefersImage(const KURL&) const;
@@ -205,10 +214,13 @@ private:
Deque<PendingPreload> m_pendingPreloads;
Timer<ResourceFetcher> m_garbageCollectDocumentResourcesTimer;
+ Timer<ResourceFetcher> m_resourceTimingReportTimer;
typedef HashMap<Resource*, RefPtr<ResourceTimingInfo> > ResourceTimingInfoMap;
ResourceTimingInfoMap m_resourceTimingInfoMap;
+ HashMap<RefPtr<ResourceTimingInfo>, bool> m_scheduledResourceTimingReports;
+
OwnPtr<ResourceLoaderSet> m_loaders;
OwnPtr<ResourceLoaderSet> m_multipartLoaders;
diff --git a/chromium/third_party/WebKit/Source/core/fetch/ResourceFetcherTest.cpp b/chromium/third_party/WebKit/Source/core/fetch/ResourceFetcherTest.cpp
index 49866ec44eb..adc8b4bb803 100644
--- a/chromium/third_party/WebKit/Source/core/fetch/ResourceFetcherTest.cpp
+++ b/chromium/third_party/WebKit/Source/core/fetch/ResourceFetcherTest.cpp
@@ -31,14 +31,14 @@
#include "config.h"
#include "core/fetch/ResourceFetcher.h"
+#include <gtest/gtest.h>
#include "core/fetch/FetchInitiatorInfo.h"
#include "core/fetch/FetchRequest.h"
#include "core/fetch/MemoryCache.h"
#include "core/fetch/ResourcePtr.h"
#include "core/html/HTMLDocument.h"
#include "core/loader/DocumentLoader.h"
-#include "core/platform/network/ResourceRequest.h"
-#include <gtest/gtest.h>
+#include "platform/network/ResourceRequest.h"
using namespace WebCore;
diff --git a/chromium/third_party/WebKit/Source/core/fetch/ResourceLoadPriorityOptimizer.cpp b/chromium/third_party/WebKit/Source/core/fetch/ResourceLoadPriorityOptimizer.cpp
new file mode 100644
index 00000000000..29882526a7c
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/fetch/ResourceLoadPriorityOptimizer.cpp
@@ -0,0 +1,79 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/fetch/ResourceLoadPriorityOptimizer.h"
+
+namespace WebCore {
+
+ResourceLoadPriorityOptimizer::ResourceAndVisibility::ResourceAndVisibility(ImageResource* image, VisibilityStatus v)
+ : imageResource(image)
+ , status(v)
+{
+}
+
+ResourceLoadPriorityOptimizer::ResourceAndVisibility::~ResourceAndVisibility()
+{
+}
+
+ResourceLoadPriorityOptimizer::ResourceLoadPriorityOptimizer()
+{
+}
+
+ResourceLoadPriorityOptimizer::~ResourceLoadPriorityOptimizer()
+{
+ updateImageResourcesWithLoadPriority();
+}
+
+void ResourceLoadPriorityOptimizer::updateImageResourcesWithLoadPriority()
+{
+ for (ImageResourceMap::iterator it = m_imageResources.begin(); it != m_imageResources.end(); ++it) {
+ ResourceLoadPriority priority = it->value->status == Visible ?
+ ResourceLoadPriorityLow : ResourceLoadPriorityVeryLow;
+
+ if (priority != it->value->imageResource->resourceRequest().priority()) {
+ it->value->imageResource->resourceRequest().setPriority(priority);
+ it->value->imageResource->didChangePriority(priority);
+ }
+ }
+ m_imageResources.clear();
+}
+
+void ResourceLoadPriorityOptimizer::notifyImageResourceVisibility(ImageResource* img, VisibilityStatus status)
+{
+ if (!img || img->isLoaded())
+ return;
+
+ ImageResourceMap::AddResult result = m_imageResources.add(img->identifier(), adoptPtr(new ResourceAndVisibility(img, status)));
+ if (!result.isNewEntry && status == Visible)
+ result.iterator->value->status = status;
+}
+
+}
diff --git a/chromium/third_party/WebKit/Source/core/fetch/ResourceLoadPriorityOptimizer.h b/chromium/third_party/WebKit/Source/core/fetch/ResourceLoadPriorityOptimizer.h
new file mode 100644
index 00000000000..cb58320a410
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/fetch/ResourceLoadPriorityOptimizer.h
@@ -0,0 +1,69 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef ResourceLoadPriorityOptimizer_h
+#define ResourceLoadPriorityOptimizer_h
+
+#include "core/fetch/ImageResource.h"
+#include "core/fetch/ResourcePtr.h"
+#include "platform/geometry/LayoutRect.h"
+
+#include "wtf/HashMap.h"
+#include "wtf/OwnPtr.h"
+
+namespace WebCore {
+
+class ResourceLoadPriorityOptimizer {
+public:
+ enum VisibilityStatus {
+ NotVisible,
+ Visible,
+ };
+ ResourceLoadPriorityOptimizer();
+ ~ResourceLoadPriorityOptimizer();
+ void notifyImageResourceVisibility(ImageResource*, VisibilityStatus);
+
+private:
+ void updateImageResourcesWithLoadPriority();
+
+ struct ResourceAndVisibility {
+ ResourceAndVisibility(ImageResource*, VisibilityStatus);
+ ~ResourceAndVisibility();
+ ResourcePtr<ImageResource> imageResource;
+ VisibilityStatus status;
+ };
+
+ typedef HashMap<unsigned long, OwnPtr<ResourceAndVisibility> > ImageResourceMap;
+ ImageResourceMap m_imageResources;
+};
+
+}
+
+#endif
diff --git a/chromium/third_party/WebKit/Source/core/fetch/ResourceLoader.cpp b/chromium/third_party/WebKit/Source/core/fetch/ResourceLoader.cpp
index 7c042ca58d3..f1356b75b53 100644
--- a/chromium/third_party/WebKit/Source/core/fetch/ResourceLoader.cpp
+++ b/chromium/third_party/WebKit/Source/core/fetch/ResourceLoader.cpp
@@ -33,11 +33,11 @@
#include "core/fetch/Resource.h"
#include "core/fetch/ResourceLoaderHost.h"
#include "core/fetch/ResourcePtr.h"
-#include "core/platform/Logging.h"
-#include "core/platform/SharedBuffer.h"
-#include "core/platform/chromium/support/WrappedResourceRequest.h"
-#include "core/platform/chromium/support/WrappedResourceResponse.h"
-#include "core/platform/network/ResourceError.h"
+#include "platform/Logging.h"
+#include "platform/SharedBuffer.h"
+#include "platform/exported/WrappedResourceRequest.h"
+#include "platform/exported/WrappedResourceResponse.h"
+#include "platform/network/ResourceError.h"
#include "public/platform/Platform.h"
#include "public/platform/WebData.h"
#include "public/platform/WebURLError.h"
@@ -148,13 +148,24 @@ void ResourceLoader::start()
RELEASE_ASSERT(m_connectionState == ConnectionStateNew);
m_connectionState = ConnectionStateStarted;
- m_loader = adoptPtr(WebKit::Platform::current()->createURLLoader());
+ m_loader = adoptPtr(blink::Platform::current()->createURLLoader());
ASSERT(m_loader);
- WebKit::WrappedResourceRequest wrappedRequest(m_request);
+ blink::WrappedResourceRequest wrappedRequest(m_request);
wrappedRequest.setAllowStoredCredentials(m_options.allowCredentials == AllowStoredCredentials);
m_loader->loadAsynchronously(wrappedRequest, this);
}
+void ResourceLoader::changeToSynchronous()
+{
+ ASSERT(m_options.synchronousPolicy == RequestAsynchronously);
+ ASSERT(m_loader);
+ m_loader->cancel();
+ m_loader.clear();
+ m_request.setPriority(ResourceLoadPriorityHighest);
+ m_connectionState = ConnectionStateNew;
+ requestSynchronously();
+}
+
void ResourceLoader::setDefersLoading(bool defers)
{
m_defersLoading = defers;
@@ -167,10 +178,11 @@ void ResourceLoader::setDefersLoading(bool defers)
}
}
-void ResourceLoader::didDownloadData(WebKit::WebURLLoader*, int length, int encodedDataLength)
+void ResourceLoader::didDownloadData(blink::WebURLLoader*, int length, int encodedDataLength)
{
RefPtr<ResourceLoader> protect(this);
RELEASE_ASSERT(m_connectionState == ConnectionStateReceivedResponse);
+ m_host->didDownloadData(m_resource, length, encodedDataLength, m_options);
m_resource->didDownloadData(length);
}
@@ -191,7 +203,7 @@ void ResourceLoader::didChangePriority(ResourceLoadPriority loadPriority)
{
if (m_loader) {
m_host->didChangeLoadingPriority(m_resource, loadPriority);
- m_loader->didChangePriority(static_cast<WebKit::WebURLRequest::Priority>(loadPriority));
+ m_loader->didChangePriority(static_cast<blink::WebURLRequest::Priority>(loadPriority));
}
}
@@ -223,7 +235,7 @@ void ResourceLoader::cancel(const ResourceError& error)
// something that causes the last reference to this object to go away.
RefPtr<ResourceLoader> protector(this);
- LOG(ResourceLoading, "Cancelled load of '%s'.\n", m_resource->url().string().latin1().data());
+ WTF_LOG(ResourceLoading, "Cancelled load of '%s'.\n", m_resource->url().string().latin1().data());
if (m_state == Initialized)
m_state = Finishing;
m_resource->setResourceError(nonNullError);
@@ -242,7 +254,7 @@ void ResourceLoader::cancel(const ResourceError& error)
releaseResources();
}
-void ResourceLoader::willSendRequest(WebKit::WebURLLoader*, WebKit::WebURLRequest& passedRequest, const WebKit::WebURLResponse& passedRedirectResponse)
+void ResourceLoader::willSendRequest(blink::WebURLLoader*, blink::WebURLRequest& passedRequest, const blink::WebURLResponse& passedRedirectResponse)
{
RefPtr<ResourceLoader> protect(this);
@@ -265,21 +277,21 @@ void ResourceLoader::willSendRequest(WebKit::WebURLLoader*, WebKit::WebURLReques
m_request = request;
}
-void ResourceLoader::didReceiveCachedMetadata(WebKit::WebURLLoader*, const char* data, int length)
+void ResourceLoader::didReceiveCachedMetadata(blink::WebURLLoader*, const char* data, int length)
{
RELEASE_ASSERT(m_connectionState == ConnectionStateReceivedResponse || m_connectionState == ConnectionStateReceivingData);
ASSERT(m_state == Initialized);
m_resource->setSerializedCachedMetadata(data, length);
}
-void ResourceLoader::didSendData(WebKit::WebURLLoader*, unsigned long long bytesSent, unsigned long long totalBytesToBeSent)
+void ResourceLoader::didSendData(blink::WebURLLoader*, unsigned long long bytesSent, unsigned long long totalBytesToBeSent)
{
ASSERT(m_state == Initialized);
RefPtr<ResourceLoader> protect(this);
m_resource->didSendData(bytesSent, totalBytesToBeSent);
}
-void ResourceLoader::didReceiveResponse(WebKit::WebURLLoader*, const WebKit::WebURLResponse& response)
+void ResourceLoader::didReceiveResponse(blink::WebURLLoader*, const blink::WebURLResponse& response)
{
ASSERT(!response.isNull());
ASSERT(m_state == Initialized);
@@ -320,7 +332,7 @@ void ResourceLoader::didReceiveResponse(WebKit::WebURLLoader*, const WebKit::Web
cancel();
}
-void ResourceLoader::didReceiveData(WebKit::WebURLLoader*, const char* data, int length, int encodedDataLength)
+void ResourceLoader::didReceiveData(blink::WebURLLoader*, const char* data, int length, int encodedDataLength)
{
RELEASE_ASSERT(m_connectionState == ConnectionStateReceivedResponse || m_connectionState == ConnectionStateReceivingData);
m_connectionState = ConnectionStateReceivingData;
@@ -342,14 +354,14 @@ void ResourceLoader::didReceiveData(WebKit::WebURLLoader*, const char* data, int
m_resource->appendData(data, length);
}
-void ResourceLoader::didFinishLoading(WebKit::WebURLLoader*, double finishTime)
+void ResourceLoader::didFinishLoading(blink::WebURLLoader*, double finishTime)
{
RELEASE_ASSERT(m_connectionState == ConnectionStateReceivedResponse || m_connectionState == ConnectionStateReceivingData);
m_connectionState = ConnectionStateFinishedLoading;
if (m_state != Initialized)
return;
ASSERT(m_state != Terminated);
- LOG(ResourceLoading, "Received '%s'.", m_resource->url().string().latin1().data());
+ WTF_LOG(ResourceLoading, "Received '%s'.", m_resource->url().string().latin1().data());
RefPtr<ResourceLoader> protect(this);
ResourcePtr<Resource> protectResource(m_resource);
@@ -364,11 +376,11 @@ void ResourceLoader::didFinishLoading(WebKit::WebURLLoader*, double finishTime)
releaseResources();
}
-void ResourceLoader::didFail(WebKit::WebURLLoader*, const WebKit::WebURLError& error)
+void ResourceLoader::didFail(blink::WebURLLoader*, const blink::WebURLError& error)
{
m_connectionState = ConnectionStateFailed;
ASSERT(m_state != Terminated);
- LOG(ResourceLoading, "Failed to load '%s'.\n", m_resource->url().string().latin1().data());
+ WTF_LOG(ResourceLoading, "Failed to load '%s'.\n", m_resource->url().string().latin1().data());
RefPtr<ResourceLoader> protect(this);
RefPtr<ResourceLoaderHost> protectHost(m_host);
@@ -395,24 +407,30 @@ bool ResourceLoader::isLoadedBy(ResourceLoaderHost* loader) const
void ResourceLoader::requestSynchronously()
{
- OwnPtr<WebKit::WebURLLoader> loader = adoptPtr(WebKit::Platform::current()->createURLLoader());
+ OwnPtr<blink::WebURLLoader> loader = adoptPtr(blink::Platform::current()->createURLLoader());
ASSERT(loader);
+ RefPtr<ResourceLoader> protect(this);
+ RefPtr<ResourceLoaderHost> protectHost(m_host);
+ ResourcePtr<Resource> protectResource(m_resource);
+
RELEASE_ASSERT(m_connectionState == ConnectionStateNew);
m_connectionState = ConnectionStateStarted;
- WebKit::WrappedResourceRequest requestIn(m_request);
+ blink::WrappedResourceRequest requestIn(m_request);
requestIn.setAllowStoredCredentials(m_options.allowCredentials == AllowStoredCredentials);
- WebKit::WebURLResponse responseOut;
+ blink::WebURLResponse responseOut;
responseOut.initialize();
- WebKit::WebURLError errorOut;
- WebKit::WebData dataOut;
+ blink::WebURLError errorOut;
+ blink::WebData dataOut;
loader->loadSynchronously(requestIn, responseOut, errorOut, dataOut);
if (errorOut.reason) {
didFail(0, errorOut);
return;
}
didReceiveResponse(0, responseOut);
+ if (m_state == Terminated)
+ return;
RefPtr<ResourceLoadInfo> resourceLoadInfo = responseOut.toResourceResponse().resourceLoadInfo();
m_host->didReceiveData(m_resource, dataOut.data(), dataOut.size(), resourceLoadInfo ? resourceLoadInfo->encodedDataLength : -1, m_options);
m_resource->setResourceBuffer(dataOut);
diff --git a/chromium/third_party/WebKit/Source/core/fetch/ResourceLoader.h b/chromium/third_party/WebKit/Source/core/fetch/ResourceLoader.h
index f53b9f5434f..814cecf6850 100644
--- a/chromium/third_party/WebKit/Source/core/fetch/ResourceLoader.h
+++ b/chromium/third_party/WebKit/Source/core/fetch/ResourceLoader.h
@@ -30,7 +30,7 @@
#define ResourceLoader_h
#include "core/fetch/ResourceLoaderOptions.h"
-#include "core/platform/network/ResourceRequest.h"
+#include "platform/network/ResourceRequest.h"
#include "public/platform/WebURLLoader.h"
#include "public/platform/WebURLLoaderClient.h"
#include "wtf/Forward.h"
@@ -44,12 +44,13 @@ class ResourceError;
class ResourceResponse;
class ResourceLoaderHost;
-class ResourceLoader : public RefCounted<ResourceLoader>, protected WebKit::WebURLLoaderClient {
+class ResourceLoader : public RefCounted<ResourceLoader>, protected blink::WebURLLoaderClient {
public:
static PassRefPtr<ResourceLoader> create(ResourceLoaderHost*, Resource*, const ResourceRequest&, const ResourceLoaderOptions&);
virtual ~ResourceLoader();
void start();
+ void changeToSynchronous();
void cancel();
void cancel(const ResourceError&);
@@ -66,14 +67,14 @@ public:
void didChangePriority(ResourceLoadPriority);
// WebURLLoaderClient
- virtual void willSendRequest(WebKit::WebURLLoader*, WebKit::WebURLRequest&, const WebKit::WebURLResponse& redirectResponse) OVERRIDE;
- virtual void didSendData(WebKit::WebURLLoader*, unsigned long long bytesSent, unsigned long long totalBytesToBeSent) OVERRIDE;
- virtual void didReceiveResponse(WebKit::WebURLLoader*, const WebKit::WebURLResponse&) OVERRIDE;
- virtual void didReceiveData(WebKit::WebURLLoader*, const char*, int, int encodedDataLength) OVERRIDE;
- virtual void didReceiveCachedMetadata(WebKit::WebURLLoader*, const char* data, int length) OVERRIDE;
- virtual void didFinishLoading(WebKit::WebURLLoader*, double finishTime) OVERRIDE;
- virtual void didFail(WebKit::WebURLLoader*, const WebKit::WebURLError&) OVERRIDE;
- virtual void didDownloadData(WebKit::WebURLLoader*, int, int) OVERRIDE;
+ virtual void willSendRequest(blink::WebURLLoader*, blink::WebURLRequest&, const blink::WebURLResponse& redirectResponse) OVERRIDE;
+ virtual void didSendData(blink::WebURLLoader*, unsigned long long bytesSent, unsigned long long totalBytesToBeSent) OVERRIDE;
+ virtual void didReceiveResponse(blink::WebURLLoader*, const blink::WebURLResponse&) OVERRIDE;
+ virtual void didReceiveData(blink::WebURLLoader*, const char*, int, int encodedDataLength) OVERRIDE;
+ virtual void didReceiveCachedMetadata(blink::WebURLLoader*, const char* data, int length) OVERRIDE;
+ virtual void didFinishLoading(blink::WebURLLoader*, double finishTime) OVERRIDE;
+ virtual void didFail(blink::WebURLLoader*, const blink::WebURLError&) OVERRIDE;
+ virtual void didDownloadData(blink::WebURLLoader*, int, int) OVERRIDE;
const KURL& url() const { return m_request.url(); }
bool shouldSendResourceLoadCallbacks() const { return m_options.sendLoadCallbacks == SendCallbacks; }
@@ -91,7 +92,7 @@ private:
void didFinishLoadingOnePart(double finishTime);
- OwnPtr<WebKit::WebURLLoader> m_loader;
+ OwnPtr<blink::WebURLLoader> m_loader;
RefPtr<ResourceLoaderHost> m_host;
ResourceRequest m_request;
diff --git a/chromium/third_party/WebKit/Source/core/fetch/ResourceLoaderHost.h b/chromium/third_party/WebKit/Source/core/fetch/ResourceLoaderHost.h
index 888ccc54db3..6748276d57b 100644
--- a/chromium/third_party/WebKit/Source/core/fetch/ResourceLoaderHost.h
+++ b/chromium/third_party/WebKit/Source/core/fetch/ResourceLoaderHost.h
@@ -31,8 +31,8 @@
#ifndef ResourceLoaderHost_h
#define ResourceLoaderHost_h
-#include "core/platform/network/ResourceError.h"
-#include "core/platform/network/ResourceLoadPriority.h"
+#include "platform/network/ResourceError.h"
+#include "platform/network/ResourceLoadPriority.h"
namespace WebCore {
@@ -63,6 +63,7 @@ public:
virtual void willSendRequest(unsigned long identifier, ResourceRequest&, const ResourceResponse& redirectResponse, const ResourceLoaderOptions&) = 0;
virtual void didReceiveResponse(const Resource*, const ResourceResponse&, const ResourceLoaderOptions&) = 0;
virtual void didReceiveData(const Resource*, const char* data, int dataLength, int encodedDataLength, const ResourceLoaderOptions&) = 0;
+ virtual void didDownloadData(const Resource*, int dataLength, int encodedDataLength, const ResourceLoaderOptions&) = 0;
virtual void subresourceLoaderFinishedLoadingOnePart(ResourceLoader*) = 0;
virtual void didInitializeResourceLoader(ResourceLoader*) = 0;
diff --git a/chromium/third_party/WebKit/Source/core/fetch/ResourceLoaderOptions.h b/chromium/third_party/WebKit/Source/core/fetch/ResourceLoaderOptions.h
index 124b7d57505..59136225c33 100644
--- a/chromium/third_party/WebKit/Source/core/fetch/ResourceLoaderOptions.h
+++ b/chromium/third_party/WebKit/Source/core/fetch/ResourceLoaderOptions.h
@@ -32,6 +32,7 @@
#define ResourceLoaderOptions_h
#include "core/fetch/FetchInitiatorInfo.h"
+#include "platform/weborigin/SecurityOrigin.h"
namespace WebCore {
@@ -65,12 +66,6 @@ enum ContentSecurityPolicyCheck {
DoNotCheckContentSecurityPolicy
};
-enum RequestOriginPolicy {
- UseDefaultOriginRestrictionsForType,
- RestrictToSameOrigin,
- PotentiallyCrossOriginEnabled // Indicates "potentially CORS-enabled fetch" in HTML standard.
-};
-
enum RequestInitiatorContext {
DocumentContext,
WorkerContext,
@@ -112,7 +107,6 @@ struct ResourceLoaderOptions {
, crossOriginCredentialPolicy(DoNotAskClientForCrossOriginCredentials)
, securityCheck(DoSecurityCheck)
, contentSecurityPolicyOption(CheckContentSecurityPolicy)
- , requestOriginPolicy(UseDefaultOriginRestrictionsForType)
, requestInitiatorContext(DocumentContext)
, mixedContentBlockingTreatment(TreatAsDefaultForType)
, synchronousPolicy(RequestAsynchronously)
@@ -128,7 +122,6 @@ struct ResourceLoaderOptions {
ClientCrossOriginCredentialPolicy crossOriginCredentialPolicy,
SecurityCheckPolicy securityCheck,
ContentSecurityPolicyCheck contentSecurityPolicyOption,
- RequestOriginPolicy requestOriginPolicy,
RequestInitiatorContext requestInitiatorContext)
: sendLoadCallbacks(sendLoadCallbacks)
, sniffContent(sniffContent)
@@ -138,7 +131,6 @@ struct ResourceLoaderOptions {
, crossOriginCredentialPolicy(crossOriginCredentialPolicy)
, securityCheck(securityCheck)
, contentSecurityPolicyOption(contentSecurityPolicyOption)
- , requestOriginPolicy(requestOriginPolicy)
, requestInitiatorContext(requestInitiatorContext)
, mixedContentBlockingTreatment(TreatAsDefaultForType)
, synchronousPolicy(RequestAsynchronously)
@@ -154,10 +146,10 @@ struct ResourceLoaderOptions {
SecurityCheckPolicy securityCheck;
ContentSecurityPolicyCheck contentSecurityPolicyOption;
FetchInitiatorInfo initiatorInfo;
- RequestOriginPolicy requestOriginPolicy;
RequestInitiatorContext requestInitiatorContext;
MixedContentBlockingTreatment mixedContentBlockingTreatment;
SynchronousPolicy synchronousPolicy;
+ RefPtr<SecurityOrigin> securityOrigin;
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/fetch/ResourceOwner.h b/chromium/third_party/WebKit/Source/core/fetch/ResourceOwner.h
new file mode 100644
index 00000000000..ebadbe916cc
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/fetch/ResourceOwner.h
@@ -0,0 +1,116 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef ResourceOwner_h
+#define ResourceOwner_h
+
+#include "core/fetch/ResourcePtr.h"
+
+namespace WebCore {
+
+
+template<class R, class C = typename R::ClientType>
+class ResourceOwner : public C {
+public:
+ typedef R ResourceType;
+
+ virtual ~ResourceOwner();
+ ResourceType* resource() const { return m_resource.get(); }
+
+protected:
+ ResourceOwner();
+ ResourceOwner(const ResourceOwner& other) { setResource(other.resource()); }
+ explicit ResourceOwner(const ResourcePtr<ResourceType>&);
+
+ void setResource(const ResourcePtr<ResourceType>&);
+ void clearResource();
+
+ ResourceOwner& operator=(const ResourceOwner& other);
+
+private:
+ ResourcePtr<ResourceType> m_resource;
+};
+
+template<class R, class C>
+inline ResourceOwner<R, C>::ResourceOwner()
+{
+}
+
+template<class R, class C>
+inline ResourceOwner<R, C>::~ResourceOwner()
+{
+ clearResource();
+}
+
+template<class R, class C>
+inline ResourceOwner<R, C>::ResourceOwner(const ResourcePtr<R>& resource)
+ : m_resource(resource)
+{
+ if (m_resource)
+ m_resource->addClient(this);
+}
+
+template<class R, class C>
+inline void ResourceOwner<R, C>::setResource(const ResourcePtr<R>& newResource)
+{
+ if (newResource == m_resource)
+ return;
+
+ // Some ResourceClient implementations reenter this so
+ // we need to prevent double removal.
+ if (ResourcePtr<ResourceType> oldResource = m_resource) {
+ m_resource.clear();
+ oldResource->removeClient(this);
+ }
+
+ if (newResource) {
+ m_resource = newResource;
+ m_resource->addClient(this);
+ }
+}
+
+template<class R, class C>
+inline void ResourceOwner<R, C>::clearResource()
+{
+ setResource(0);
+}
+
+template<class R, class C>
+inline ResourceOwner<R, C>& ResourceOwner<R, C>::operator=(const ResourceOwner<R, C>& other)
+{
+ if (this == &other)
+ return *this;
+ setResource(other.resource());
+ return *this;
+}
+
+} // namespace WebCore
+
+#endif
diff --git a/chromium/third_party/WebKit/Source/core/fetch/ResourcePtr.h b/chromium/third_party/WebKit/Source/core/fetch/ResourcePtr.h
index a9bdd5fcd79..f913365c0f4 100644
--- a/chromium/third_party/WebKit/Source/core/fetch/ResourcePtr.h
+++ b/chromium/third_party/WebKit/Source/core/fetch/ResourcePtr.h
@@ -36,6 +36,7 @@ public:
Resource* get() const { return m_resource; }
bool operator!() const { return !m_resource; }
+ void clear() { setResource(0); }
// This conversion operator allows implicit conversion to bool but not to other integer types.
typedef Resource* ResourcePtrBase::*UnspecifiedBoolType;
diff --git a/chromium/third_party/WebKit/Source/core/fetch/ScriptResource.cpp b/chromium/third_party/WebKit/Source/core/fetch/ScriptResource.cpp
index 7bbfdeb9b32..873ef332272 100644
--- a/chromium/third_party/WebKit/Source/core/fetch/ScriptResource.cpp
+++ b/chromium/third_party/WebKit/Source/core/fetch/ScriptResource.cpp
@@ -28,9 +28,9 @@
#include "core/fetch/ScriptResource.h"
#include "core/fetch/TextResourceDecoder.h"
-#include "core/platform/MIMETypeRegistry.h"
-#include "core/platform/SharedBuffer.h"
-#include "core/platform/network/HTTPParsers.h"
+#include "platform/MIMETypeRegistry.h"
+#include "platform/SharedBuffer.h"
+#include "platform/network/HTTPParsers.h"
namespace WebCore {
@@ -60,7 +60,7 @@ String ScriptResource::encoding() const
return m_decoder->encoding().name();
}
-String ScriptResource::mimeType() const
+AtomicString ScriptResource::mimeType() const
{
return extractMIMETypeFromMediaType(m_response.httpHeaderField("Content-Type")).lower();
}
diff --git a/chromium/third_party/WebKit/Source/core/fetch/ScriptResource.h b/chromium/third_party/WebKit/Source/core/fetch/ScriptResource.h
index 441a3b06099..09502e3eddf 100644
--- a/chromium/third_party/WebKit/Source/core/fetch/ScriptResource.h
+++ b/chromium/third_party/WebKit/Source/core/fetch/ScriptResource.h
@@ -26,7 +26,7 @@
#ifndef ScriptResource_h
#define ScriptResource_h
-#include "core/fetch/Resource.h"
+#include "core/fetch/ResourcePtr.h"
namespace WebCore {
@@ -35,6 +35,8 @@ class TextResourceDecoder;
class ScriptResource : public Resource {
public:
+ typedef ResourceClient ClientType;
+
ScriptResource(const ResourceRequest&, const String& charset);
virtual ~ScriptResource();
@@ -42,14 +44,17 @@ public:
virtual void setEncoding(const String&);
virtual String encoding() const;
- String mimeType() const;
+ AtomicString mimeType() const;
bool mimeTypeAllowedByNosniff() const;
private:
AtomicString m_script;
- RefPtr<TextResourceDecoder> m_decoder;
+ OwnPtr<TextResourceDecoder> m_decoder;
};
+
+DEFINE_RESOURCE_TYPE_CASTS(Script);
+
}
#endif
diff --git a/chromium/third_party/WebKit/Source/core/fetch/ShaderResource.cpp b/chromium/third_party/WebKit/Source/core/fetch/ShaderResource.cpp
index cbd25df0fd9..da0fa7ef847 100644
--- a/chromium/third_party/WebKit/Source/core/fetch/ShaderResource.cpp
+++ b/chromium/third_party/WebKit/Source/core/fetch/ShaderResource.cpp
@@ -31,7 +31,7 @@
#include "core/fetch/ShaderResource.h"
#include "core/fetch/TextResourceDecoder.h"
-#include "core/platform/SharedBuffer.h"
+#include "platform/SharedBuffer.h"
#include "wtf/text/StringBuilder.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/fetch/ShaderResource.h b/chromium/third_party/WebKit/Source/core/fetch/ShaderResource.h
index 94856638aa8..fb975b8d9d1 100644
--- a/chromium/third_party/WebKit/Source/core/fetch/ShaderResource.h
+++ b/chromium/third_party/WebKit/Source/core/fetch/ShaderResource.h
@@ -30,7 +30,7 @@
#ifndef ShaderResource_h
#define ShaderResource_h
-#include "core/fetch/Resource.h"
+#include "core/fetch/ResourcePtr.h"
namespace WebCore {
@@ -38,16 +38,20 @@ class TextResourceDecoder;
class ShaderResource : public Resource {
public:
+ typedef ResourceClient ClientType;
+
ShaderResource(const ResourceRequest&);
virtual ~ShaderResource();
const String& shaderString();
private:
- RefPtr<TextResourceDecoder> m_decoder;
+ OwnPtr<TextResourceDecoder> m_decoder;
String m_shaderString;
};
+DEFINE_RESOURCE_TYPE_CASTS(Shader);
+
}
diff --git a/chromium/third_party/WebKit/Source/core/fetch/StyleSheetResource.h b/chromium/third_party/WebKit/Source/core/fetch/StyleSheetResource.h
new file mode 100644
index 00000000000..d714ac5555d
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/fetch/StyleSheetResource.h
@@ -0,0 +1,51 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef StyleSheetResource_h
+#define StyleSheetResource_h
+
+#include "core/fetch/Resource.h"
+
+namespace WebCore {
+
+class StyleSheetResourceClient;
+
+class StyleSheetResource : public Resource {
+public:
+ typedef StyleSheetResourceClient ClientType;
+
+ StyleSheetResource(const ResourceRequest& request, Type type)
+ : Resource(request, type)
+ { }
+};
+
+}
+
+#endif
diff --git a/chromium/third_party/WebKit/Source/core/fetch/StyleSheetResourceClient.h b/chromium/third_party/WebKit/Source/core/fetch/StyleSheetResourceClient.h
index 6c12bf39a0c..8597200568a 100644
--- a/chromium/third_party/WebKit/Source/core/fetch/StyleSheetResourceClient.h
+++ b/chromium/third_party/WebKit/Source/core/fetch/StyleSheetResourceClient.h
@@ -27,7 +27,7 @@
#define StyleSheetResourceClient_h
#include "core/fetch/ResourceClient.h"
-#include "weborigin/KURL.h"
+#include "platform/weborigin/KURL.h"
#include "wtf/Forward.h"
namespace WebCore {
@@ -41,6 +41,7 @@ public:
virtual void setCSSStyleSheet(const String& /* href */, const KURL& /* baseURL */, const String& /* charset */, const CSSStyleSheetResource*) { }
virtual void setXSLStyleSheet(const String& /* href */, const KURL& /* baseURL */, const String& /* sheet */) { }
};
+
}
#endif // StyleSheetResourceClient_h
diff --git a/chromium/third_party/WebKit/Source/core/fetch/TextResourceDecoder.cpp b/chromium/third_party/WebKit/Source/core/fetch/TextResourceDecoder.cpp
index b6759bffb89..5a21dd5e233 100644
--- a/chromium/third_party/WebKit/Source/core/fetch/TextResourceDecoder.cpp
+++ b/chromium/third_party/WebKit/Source/core/fetch/TextResourceDecoder.cpp
@@ -26,10 +26,9 @@
#include "HTMLNames.h"
#include "core/dom/DOMImplementation.h"
#include "core/html/parser/HTMLMetaCharsetParser.h"
-#include "core/platform/text/TextEncodingDetector.h"
+#include "platform/text/TextEncodingDetector.h"
#include "wtf/StringExtras.h"
#include "wtf/text/TextCodec.h"
-#include "wtf/text/TextEncoding.h"
#include "wtf/text/TextEncodingRegistry.h"
using namespace WTF;
@@ -38,16 +37,6 @@ namespace WebCore {
using namespace HTMLNames;
-static inline bool bytesEqual(const char* p, char b0, char b1)
-{
- return p[0] == b0 && p[1] == b1;
-}
-
-static inline bool bytesEqual(const char* p, char b0, char b1, char b2)
-{
- return p[0] == b0 && p[1] == b1 && p[2] == b2;
-}
-
static inline bool bytesEqual(const char* p, char b0, char b1, char b2, char b3, char b4)
{
return p[0] == b0 && p[1] == b1 && p[2] == b2 && p[3] == b3 && p[4] == b4;
@@ -99,215 +88,6 @@ static WTF::TextEncoding findTextEncoding(const char* encodingName, int length)
return buffer.data();
}
-class KanjiCode {
-public:
- enum Type { ASCII, JIS, EUC, SJIS, UTF16, UTF8 };
- static enum Type judge(const char* str, int length);
- static const int ESC = 0x1b;
- static const unsigned char sjisMap[256];
- static int ISkanji(int code)
- {
- if (code >= 0x100)
- return 0;
- return sjisMap[code & 0xff] & 1;
- }
- static int ISkana(int code)
- {
- if (code >= 0x100)
- return 0;
- return sjisMap[code & 0xff] & 2;
- }
-};
-
-const unsigned char KanjiCode::sjisMap[256] = {
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0
-};
-
-/*
- * EUC-JP is
- * [0xa1 - 0xfe][0xa1 - 0xfe]
- * 0x8e[0xa1 - 0xfe](SS2)
- * 0x8f[0xa1 - 0xfe][0xa1 - 0xfe](SS3)
- *
- * Shift_Jis is
- * [0x81 - 0x9f, 0xe0 - 0xef(0xfe?)][0x40 - 0x7e, 0x80 - 0xfc]
- *
- * Shift_Jis Hankaku Kana is
- * [0xa1 - 0xdf]
- */
-
-/*
- * KanjiCode::judge() is based on judge_jcode() from jvim
- * http://hp.vector.co.jp/authors/VA003457/vim/
- *
- * Special Thanks to Kenichi Tsuchida
- */
-
-enum KanjiCode::Type KanjiCode::judge(const char* str, int size)
-{
- enum Type code;
- int i;
- int bfr = false; /* Kana Moji */
- int bfk = 0; /* EUC Kana */
- int sjis = 0;
- int euc = 0;
-
- const unsigned char* ptr = reinterpret_cast<const unsigned char*>(str);
-
- code = ASCII;
-
- i = 0;
- while (i < size) {
- if (ptr[i] == ESC && (size - i >= 3)) {
- if (bytesEqual(str + i + 1, '$', 'B')
- || bytesEqual(str + i + 1, '(', 'B')
- || bytesEqual(str + i + 1, '$', '@')
- || bytesEqual(str + i + 1, '(', 'J')) {
- code = JIS;
- goto breakBreak;
- }
- if (bytesEqual(str + i + 1, '(', 'I') || bytesEqual(str + i + 1, ')', 'I')) {
- code = JIS;
- i += 3;
- } else {
- i++;
- }
- bfr = false;
- bfk = 0;
- } else {
- if (ptr[i] < 0x20) {
- bfr = false;
- bfk = 0;
- /* ?? check kudokuten ?? && ?? hiragana ?? */
- if ((i >= 2) && (ptr[i - 2] == 0x81)
- && (0x41 <= ptr[i - 1] && ptr[i - 1] <= 0x49)) {
- code = SJIS;
- sjis += 100; /* kudokuten */
- } else if ((i >= 2) && (ptr[i - 2] == 0xa1) && (0xa2 <= ptr[i - 1] && ptr[i - 1] <= 0xaa)) {
- code = EUC;
- euc += 100; /* kudokuten */
- } else if ((i >= 2) && (ptr[i - 2] == 0x82) && (0xa0 <= ptr[i - 1])) {
- sjis += 40; /* hiragana */
- } else if ((i >= 2) && (ptr[i - 2] == 0xa4) && (0xa0 <= ptr[i - 1])) {
- euc += 40; /* hiragana */
- }
- } else {
- /* ?? check hiragana or katana ?? */
- if ((size - i > 1) && (ptr[i] == 0x82) && (0xa0 <= ptr[i + 1])) {
- sjis++; /* hiragana */
- } else if ((size - i > 1) && (ptr[i] == 0x83) && (0x40 <= ptr[i + 1] && ptr[i + 1] <= 0x9f)) {
- sjis++; /* katakana */
- } else if ((size - i > 1) && (ptr[i] == 0xa4) && (0xa0 <= ptr[i + 1])) {
- euc++; /* hiragana */
- } else if ((size - i > 1) && (ptr[i] == 0xa5) && (0xa0 <= ptr[i + 1])) {
- euc++; /* katakana */
- }
- if (bfr) {
- if ((i >= 1) && (0x40 <= ptr[i] && ptr[i] <= 0xa0) && ISkanji(ptr[i - 1])) {
- code = SJIS;
- goto breakBreak;
- }
-
- if ((i >= 1) && (0x81 <= ptr[i - 1] && ptr[i - 1] <= 0x9f) && ((0x40 <= ptr[i] && ptr[i] < 0x7e) || (0x7e < ptr[i] && ptr[i] <= 0xfc))) {
- code = SJIS;
- goto breakBreak;
- }
-
- if ((i >= 1) && (0xfd <= ptr[i] && ptr[i] <= 0xfe) && (0xa1 <= ptr[i - 1] && ptr[i - 1] <= 0xfe)) {
- code = EUC;
- goto breakBreak;
- }
-
- if ((i >= 1) && (0xfd <= ptr[i - 1] && ptr[i - 1] <= 0xfe) && (0xa1 <= ptr[i] && ptr[i] <= 0xfe)) {
- code = EUC;
- goto breakBreak;
- }
-
- if ((i >= 1) && (ptr[i] < 0xa0 || 0xdf < ptr[i]) && (0x8e == ptr[i - 1])) {
- code = SJIS;
- goto breakBreak;
- }
-
- if (ptr[i] <= 0x7f) {
- code = SJIS;
- goto breakBreak;
- }
-
- if (0xa1 <= ptr[i] && ptr[i] <= 0xa6) {
- euc++; /* sjis hankaku kana kigo */
- } else if (0xa1 <= ptr[i] && ptr[i] <= 0xdf) {
- /* sjis hankaku kana */
- } else if (0xa1 <= ptr[i] && ptr[i] <= 0xfe) {
- euc++;
- } else if (0x8e == ptr[i]) {
- euc++;
- } else if (0x20 <= ptr[i] && ptr[i] <= 0x7f) {
- sjis++;
- }
-
- bfr = false;
- bfk = 0;
- } else if (0x8e == ptr[i]) {
- if (size - i <= 1) {
-
- } else if (0xa1 <= ptr[i + 1] && ptr[i + 1] <= 0xdf) {
- /* EUC KANA or SJIS KANJI */
- if (bfk == 1) {
- euc += 100;
- }
- bfk++;
- i++;
- } else {
- /* SJIS only */
- code = SJIS;
- goto breakBreak;
- }
- } else if (0x81 <= ptr[i] && ptr[i] <= 0x9f) {
- /* SJIS only */
- code = SJIS;
- if ((size - i >= 1) && ((0x40 <= ptr[i + 1] && ptr[i + 1] <= 0x7e) || (0x80 <= ptr[i + 1] && ptr[i + 1] <= 0xfc)))
- goto breakBreak;
- } else if (0xfd <= ptr[i] && ptr[i] <= 0xfe) {
- /* EUC only */
- code = EUC;
- if ((size - i >= 1) && (0xa1 <= ptr[i + 1] && ptr[i + 1] <= 0xfe))
- goto breakBreak;
- } else if (ptr[i] <= 0x7f) {
-
- } else {
- bfr = true;
- bfk = 0;
- }
- }
- i++;
- }
- }
- if (code == ASCII) {
- if (sjis > euc) {
- code = SJIS;
- } else if (sjis < euc) {
- code = EUC;
- }
- }
-breakBreak:
- return (code);
-}
-
TextResourceDecoder::ContentType TextResourceDecoder::determineContentType(const String& mimeType)
{
if (equalIgnoringCase(mimeType, "text/css"))
@@ -408,14 +188,6 @@ static int findXMLEncoding(const char* str, int len, int& encodingLength)
return pos;
}
-// true if there is more to parse
-static inline bool skipWhitespace(const char*& pos, const char* dataEnd)
-{
- while (pos < dataEnd && (*pos == '\t' || *pos == ' '))
- ++pos;
- return pos != dataEnd;
-}
-
size_t TextResourceDecoder::checkForBOM(const char* data, size_t len)
{
// Check for UTF-16/32 or UTF-8 BOM mark at the beginning, which is a sure sign of a Unicode encoding.
@@ -571,25 +343,6 @@ void TextResourceDecoder::checkForMetaCharset(const char* data, size_t length)
return;
}
-void TextResourceDecoder::detectJapaneseEncoding(const char* data, size_t len)
-{
- switch (KanjiCode::judge(data, len)) {
- case KanjiCode::JIS:
- setEncoding("ISO-2022-JP", EncodingFromContentSniffing);
- break;
- case KanjiCode::EUC:
- setEncoding("EUC-JP", EncodingFromContentSniffing);
- break;
- case KanjiCode::SJIS:
- setEncoding("Shift_JIS", EncodingFromContentSniffing);
- break;
- case KanjiCode::ASCII:
- case KanjiCode::UTF16:
- case KanjiCode::UTF8:
- break;
- }
-}
-
// We use the encoding detector in two cases:
// 1. Encoding detector is turned ON and no other encoding source is
// available (that is, it's DefaultEncoding).
@@ -625,20 +378,6 @@ String TextResourceDecoder::decode(const char* data, size_t len)
return emptyString();
}
- // FIXME: It would be more efficient to move this logic below checkForMetaCharset because
- // checkForMetaCharset can overrule these detections.
- if (shouldAutoDetect()) {
- if (m_encoding.isJapanese()) {
- detectJapaneseEncoding(data, len); // FIXME: We should use detectTextEncoding() for all languages.
- } else {
- WTF::TextEncoding detectedEncoding;
- if (detectTextEncoding(data, len, m_hintEncoding, &detectedEncoding))
- setEncoding(detectedEncoding, EncodingFromContentSniffing);
- }
- }
-
- ASSERT(m_encoding.isValid());
-
const char* dataForDecode = data + lengthOfBOM;
size_t lengthForDecode = len - lengthOfBOM;
@@ -656,6 +395,14 @@ String TextResourceDecoder::decode(const char* data, size_t len)
if (m_contentType == HTML && !m_checkedForMetaCharset)
checkForMetaCharset(dataForDecode, lengthForDecode);
+ if (shouldAutoDetect()) {
+ WTF::TextEncoding detectedEncoding;
+ if (detectTextEncoding(data, len, m_hintEncoding, &detectedEncoding))
+ setEncoding(detectedEncoding, EncodingFromContentSniffing);
+ }
+
+ ASSERT(m_encoding.isValid());
+
if (!m_codec)
m_codec = newTextCodec(m_encoding);
diff --git a/chromium/third_party/WebKit/Source/core/fetch/TextResourceDecoder.h b/chromium/third_party/WebKit/Source/core/fetch/TextResourceDecoder.h
index 14baa35edd2..4c773478148 100644
--- a/chromium/third_party/WebKit/Source/core/fetch/TextResourceDecoder.h
+++ b/chromium/third_party/WebKit/Source/core/fetch/TextResourceDecoder.h
@@ -30,7 +30,7 @@ namespace WebCore {
class HTMLMetaCharsetParser;
-class TextResourceDecoder : public RefCounted<TextResourceDecoder> {
+class TextResourceDecoder {
public:
enum EncodingSource {
DefaultEncoding,
@@ -44,24 +44,26 @@ public:
EncodingFromParentFrame
};
- static PassRefPtr<TextResourceDecoder> create(const String& mimeType, const WTF::TextEncoding& defaultEncoding = WTF::TextEncoding(), bool usesEncodingDetector = false)
+ static PassOwnPtr<TextResourceDecoder> create(const String& mimeType, const WTF::TextEncoding& defaultEncoding = WTF::TextEncoding(), bool usesEncodingDetector = false)
{
- return adoptRef(new TextResourceDecoder(mimeType, defaultEncoding, usesEncodingDetector));
+ return adoptPtr(new TextResourceDecoder(mimeType, defaultEncoding, usesEncodingDetector));
}
~TextResourceDecoder();
void setEncoding(const WTF::TextEncoding&, EncodingSource);
const WTF::TextEncoding& encoding() const { return m_encoding; }
+ bool encodingWasDetectedHeuristically() const
+ {
+ return m_source == AutoDetectedEncoding
+ || m_source == EncodingFromContentSniffing;
+ }
String decode(const char* data, size_t length);
String flush();
- void setHintEncoding(const TextResourceDecoder* hintDecoder)
+ void setHintEncoding(const WTF::TextEncoding& encoding)
{
- // hintEncoding is for use with autodetection, which should be
- // only invoked when hintEncoding comes from auto-detection.
- if (hintDecoder && hintDecoder->wasDetectedHueristically())
- m_hintEncoding = hintDecoder->encoding().name();
+ m_hintEncoding = encoding.name();
}
void useLenientXMLDecoding() { m_useLenientXMLDecoding = true; }
@@ -74,8 +76,6 @@ private:
static ContentType determineContentType(const String& mimeType);
static const WTF::TextEncoding& defaultEncoding(ContentType, const WTF::TextEncoding& defaultEncoding);
- bool wasDetectedHueristically() const { return m_source == AutoDetectedEncoding || m_source == EncodingFromContentSniffing; }
-
size_t checkForBOM(const char*, size_t);
bool checkForCSSCharset(const char*, size_t, bool& movedDataToBuffer);
bool checkForXMLCharset(const char*, size_t, bool& movedDataToBuffer);
diff --git a/chromium/third_party/WebKit/Source/core/fetch/TextTrackResource.cpp b/chromium/third_party/WebKit/Source/core/fetch/TextTrackResource.cpp
deleted file mode 100644
index 5093d7e26d3..00000000000
--- a/chromium/third_party/WebKit/Source/core/fetch/TextTrackResource.cpp
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright (C) 2011 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/fetch/TextTrackResource.h"
-
-#include "core/fetch/ResourceClient.h"
-#include "core/fetch/ResourceClientWalker.h"
-
-namespace WebCore {
-
-TextTrackResource::TextTrackResource(const ResourceRequest& resourceRequest)
- : Resource(resourceRequest, TextTrack)
-{
-}
-
-TextTrackResource::~TextTrackResource()
-{
-}
-
-void TextTrackResource::appendData(const char* data, int length)
-{
- Resource::appendData(data, length);
- ResourceClientWalker<ResourceClient> walker(m_clients);
- while (ResourceClient *client = walker.next())
- client->deprecatedDidReceiveResource(this);
-}
-
-}
-
diff --git a/chromium/third_party/WebKit/Source/core/fetch/TextTrackResource.h b/chromium/third_party/WebKit/Source/core/fetch/TextTrackResource.h
deleted file mode 100644
index 3599f0bfa4d..00000000000
--- a/chromium/third_party/WebKit/Source/core/fetch/TextTrackResource.h
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright (C) 2011 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TextTrackResource_h
-#define TextTrackResource_h
-
-#include "core/fetch/Resource.h"
-
-namespace WebCore {
-
-class TextTrackResource : public Resource {
-public:
- TextTrackResource(const ResourceRequest&);
- virtual ~TextTrackResource();
-
- virtual void appendData(const char*, int) OVERRIDE;
-};
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/fetch/XSLStyleSheetResource.cpp b/chromium/third_party/WebKit/Source/core/fetch/XSLStyleSheetResource.cpp
index 6179a479375..053a445d456 100644
--- a/chromium/third_party/WebKit/Source/core/fetch/XSLStyleSheetResource.cpp
+++ b/chromium/third_party/WebKit/Source/core/fetch/XSLStyleSheetResource.cpp
@@ -27,18 +27,20 @@
#include "config.h"
#include "core/fetch/XSLStyleSheetResource.h"
+#include "RuntimeEnabledFeatures.h"
#include "core/fetch/ResourceClientWalker.h"
#include "core/fetch/StyleSheetResourceClient.h"
#include "core/fetch/TextResourceDecoder.h"
-#include "core/platform/SharedBuffer.h"
+#include "platform/SharedBuffer.h"
#include "wtf/Vector.h"
namespace WebCore {
XSLStyleSheetResource::XSLStyleSheetResource(const ResourceRequest& resourceRequest)
- : Resource(resourceRequest, XSLStyleSheet)
+ : StyleSheetResource(resourceRequest, XSLStyleSheet)
, m_decoder(TextResourceDecoder::create("text/xsl"))
{
+ ASSERT(RuntimeEnabledFeatures::xsltEnabled());
DEFINE_STATIC_LOCAL(const AtomicString, acceptXSLT, ("text/xml, application/xml, application/xhtml+xml, text/xsl, application/rss+xml, application/atom+xml", AtomicString::ConstructFromLiteral));
// It's XML we want.
diff --git a/chromium/third_party/WebKit/Source/core/fetch/XSLStyleSheetResource.h b/chromium/third_party/WebKit/Source/core/fetch/XSLStyleSheetResource.h
index 52e6814f635..353b9da6a84 100644
--- a/chromium/third_party/WebKit/Source/core/fetch/XSLStyleSheetResource.h
+++ b/chromium/third_party/WebKit/Source/core/fetch/XSLStyleSheetResource.h
@@ -26,14 +26,15 @@
#ifndef XSLStyleSheetResource_h
#define XSLStyleSheetResource_h
-#include "core/fetch/Resource.h"
+#include "core/fetch/ResourcePtr.h"
+#include "core/fetch/StyleSheetResource.h"
namespace WebCore {
class ResourceFetcher;
class TextResourceDecoder;
-class XSLStyleSheetResource : public Resource {
+class XSLStyleSheetResource : public StyleSheetResource {
public:
XSLStyleSheetResource(const ResourceRequest&);
@@ -47,9 +48,11 @@ protected:
virtual void checkNotify();
String m_sheet;
- RefPtr<TextResourceDecoder> m_decoder;
+ OwnPtr<TextResourceDecoder> m_decoder;
};
+DEFINE_RESOURCE_TYPE_CASTS(XSLStyleSheet);
+
} // namespace WebCore
#endif
diff --git a/chromium/third_party/WebKit/Source/core/fileapi/Blob.cpp b/chromium/third_party/WebKit/Source/core/fileapi/Blob.cpp
index f93b428a802..def1ae0cb4b 100644
--- a/chromium/third_party/WebKit/Source/core/fileapi/Blob.cpp
+++ b/chromium/third_party/WebKit/Source/core/fileapi/Blob.cpp
@@ -31,12 +31,14 @@
#include "config.h"
#include "core/fileapi/Blob.h"
-#include "core/fileapi/BlobRegistry.h"
-#include "core/fileapi/BlobURL.h"
#include "core/fileapi/File.h"
+#include "platform/blob/BlobRegistry.h"
+#include "platform/blob/BlobURL.h"
namespace WebCore {
+namespace {
+
class BlobURLRegistry : public URLRegistry {
public:
virtual void registerURL(SecurityOrigin*, const KURL&, URLRegistrable*) OVERRIDE;
@@ -45,16 +47,15 @@ public:
static URLRegistry& registry();
};
-
void BlobURLRegistry::registerURL(SecurityOrigin* origin, const KURL& publicURL, URLRegistrable* blob)
{
ASSERT(&blob->registry() == this);
- BlobRegistry::registerBlobURL(origin, publicURL, static_cast<Blob*>(blob)->url());
+ BlobRegistry::registerPublicBlobURL(origin, publicURL, static_cast<Blob*>(blob)->blobDataHandle());
}
-void BlobURLRegistry::unregisterURL(const KURL& url)
+void BlobURLRegistry::unregisterURL(const KURL& publicURL)
{
- BlobRegistry::unregisterBlobURL(url);
+ BlobRegistry::revokePublicBlobURL(publicURL);
}
URLRegistry& BlobURLRegistry::registry()
@@ -63,44 +64,16 @@ URLRegistry& BlobURLRegistry::registry()
return instance;
}
+} // namespace
-Blob::Blob()
- : m_size(0)
+Blob::Blob(PassRefPtr<BlobDataHandle> dataHandle)
+ : m_blobDataHandle(dataHandle)
{
ScriptWrappable::init(this);
- OwnPtr<BlobData> blobData = BlobData::create();
-
- // Create a new internal URL and register it with the provided blob data.
- m_internalURL = BlobURL::createInternalURL();
- BlobRegistry::registerBlobURL(m_internalURL, blobData.release());
-}
-
-Blob::Blob(PassOwnPtr<BlobData> blobData, long long size)
- : m_type(blobData->contentType())
- , m_size(size)
-{
- ASSERT(blobData);
- ScriptWrappable::init(this);
-
- // Create a new internal URL and register it with the provided blob data.
- m_internalURL = BlobURL::createInternalURL();
- BlobRegistry::registerBlobURL(m_internalURL, blobData);
-}
-
-Blob::Blob(const KURL& srcURL, const String& type, long long size)
- : m_type(type)
- , m_size(size)
-{
- ScriptWrappable::init(this);
-
- // Create a new internal URL and register it with the same blob data as the source URL.
- m_internalURL = BlobURL::createInternalURL();
- BlobRegistry::registerBlobURL(0, m_internalURL, srcURL);
}
Blob::~Blob()
{
- BlobRegistry::unregisterBlobURL(m_internalURL);
}
PassRefPtr<Blob> Blob::slice(long long start, long long end, const String& contentType) const
@@ -109,12 +82,12 @@ PassRefPtr<Blob> Blob::slice(long long start, long long end, const String& conte
// The modification time will be used to verify if the file has been changed or not, when the underlying data are accessed.
long long size;
double modificationTime;
- if (isFile()) {
+ if (hasBackingFile()) {
// FIXME: This involves synchronous file operation. We need to figure out how to make it asynchronous.
toFile(this)->captureSnapshot(size, modificationTime);
} else {
- ASSERT(m_size != -1);
- size = m_size;
+ size = this->size();
+ ASSERT(size != -1);
}
// Convert the negative value that is used to select from the end.
@@ -139,15 +112,15 @@ PassRefPtr<Blob> Blob::slice(long long start, long long end, const String& conte
long long length = end - start;
OwnPtr<BlobData> blobData = BlobData::create();
blobData->setContentType(contentType);
- if (isFile()) {
+ if (hasBackingFile()) {
if (!toFile(this)->fileSystemURL().isEmpty())
- blobData->appendURL(toFile(this)->fileSystemURL(), start, length, modificationTime);
+ blobData->appendFileSystemURL(toFile(this)->fileSystemURL(), start, length, modificationTime);
else
blobData->appendFile(toFile(this)->path(), start, length, modificationTime);
- } else
- blobData->appendBlob(m_internalURL, start, length);
-
- return Blob::create(blobData.release(), length);
+ } else {
+ blobData->appendBlob(m_blobDataHandle, start, length);
+ }
+ return Blob::create(BlobDataHandle::create(blobData.release(), length));
}
URLRegistry& Blob::registry() const
diff --git a/chromium/third_party/WebKit/Source/core/fileapi/Blob.h b/chromium/third_party/WebKit/Source/core/fileapi/Blob.h
index 958aa283bb1..6a721554590 100644
--- a/chromium/third_party/WebKit/Source/core/fileapi/Blob.h
+++ b/chromium/third_party/WebKit/Source/core/fileapi/Blob.h
@@ -33,8 +33,7 @@
#include "bindings/v8/ScriptWrappable.h"
#include "core/html/URLRegistry.h"
-#include "core/platform/network/BlobData.h"
-#include "weborigin/KURL.h"
+#include "platform/blob/BlobData.h"
#include "wtf/PassOwnPtr.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefCounted.h"
@@ -42,53 +41,41 @@
namespace WebCore {
-class ScriptExecutionContext;
+class ExecutionContext;
class Blob : public ScriptWrappable, public URLRegistrable, public RefCounted<Blob> {
public:
static PassRefPtr<Blob> create()
{
- return adoptRef(new Blob);
+ return adoptRef(new Blob(BlobDataHandle::create()));
}
- static PassRefPtr<Blob> create(PassOwnPtr<BlobData> blobData, long long size)
+ static PassRefPtr<Blob> create(PassRefPtr<BlobDataHandle> blobDataHandle)
{
- return adoptRef(new Blob(blobData, size));
- }
-
- // For deserialization.
- static PassRefPtr<Blob> create(const KURL& srcURL, const String& type, long long size)
- {
- return adoptRef(new Blob(srcURL, type, size));
+ return adoptRef(new Blob(blobDataHandle));
}
virtual ~Blob();
- const KURL& url() const { return m_internalURL; }
- const String& type() const { return m_type; }
-
- virtual unsigned long long size() const { return static_cast<unsigned long long>(m_size); }
+ String uuid() const { return m_blobDataHandle->uuid(); }
+ String type() const { return m_blobDataHandle->type(); }
+ virtual unsigned long long size() const { return m_blobDataHandle->size(); }
+ // True for all File instances, including the user-built ones.
virtual bool isFile() const { return false; }
+ // Only true for File instances that are backed by platform files.
+ virtual bool hasBackingFile() const { return false; }
+ PassRefPtr<BlobDataHandle> blobDataHandle() const { return m_blobDataHandle; }
+ PassRefPtr<Blob> slice(long long start = 0, long long end = std::numeric_limits<long long>::max(), const String& contentType = String()) const;
- // URLRegistrable
+ // URLRegistrable to support PublicURLs.
virtual URLRegistry& registry() const OVERRIDE;
- PassRefPtr<Blob> slice(long long start = 0, long long end = std::numeric_limits<long long>::max(), const String& contentType = String()) const;
-
protected:
- Blob();
- Blob(PassOwnPtr<BlobData>, long long size);
-
- // For deserialization.
- Blob(const KURL& srcURL, const String& type, long long size);
+ explicit Blob(PassRefPtr<BlobDataHandle>);
- // This is an internal URL referring to the blob data associated with this object. It serves
- // as an identifier for this blob. The internal URL is never used to source the blob's content
- // into an HTML or for FileRead'ing, public blob URLs must be used for those purposes.
- KURL m_internalURL;
-
- String m_type;
- long long m_size;
+private:
+ Blob();
+ RefPtr<BlobDataHandle> m_blobDataHandle;
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/fileapi/Blob.idl b/chromium/third_party/WebKit/Source/core/fileapi/Blob.idl
index 8dddc35ae02..28fd1aaec37 100644
--- a/chromium/third_party/WebKit/Source/core/fileapi/Blob.idl
+++ b/chromium/third_party/WebKit/Source/core/fileapi/Blob.idl
@@ -29,10 +29,10 @@
*/
[
- GlobalContext=Window&WorkerGlobalScope,
- CustomToV8,
CustomConstructor,
- CustomConstructor(sequence<any> blobParts, optional BlobPropertyBag options)
+ CustomConstructor(sequence<any> blobParts, optional BlobPropertyBag options),
+ GlobalContext=Window&WorkerGlobalScope,
+ SpecialWrapFor=File,
] interface Blob {
readonly attribute unsigned long long size;
readonly attribute DOMString type;
diff --git a/chromium/third_party/WebKit/Source/core/fileapi/BlobBuilder.cpp b/chromium/third_party/WebKit/Source/core/fileapi/BlobBuilder.cpp
index dfd1562246b..70583af4105 100644
--- a/chromium/third_party/WebKit/Source/core/fileapi/BlobBuilder.cpp
+++ b/chromium/third_party/WebKit/Source/core/fileapi/BlobBuilder.cpp
@@ -34,7 +34,7 @@
#include "core/fileapi/Blob.h"
#include "core/fileapi/File.h"
-#include "core/platform/text/LineEnding.h"
+#include "platform/text/LineEnding.h"
#include "wtf/ArrayBuffer.h"
#include "wtf/ArrayBufferView.h"
#include "wtf/PassRefPtr.h"
@@ -94,7 +94,7 @@ void BlobBuilder::append(Blob* blob)
{
if (!blob)
return;
- if (blob->isFile()) {
+ if (blob->hasBackingFile()) {
File* file = toFile(blob);
// If the blob is file that is not snapshoted, capture the snapshot now.
// FIXME: This involves synchronous file operation. We need to figure out how to make it asynchronous.
@@ -110,7 +110,7 @@ void BlobBuilder::append(Blob* blob)
} else {
long long blobSize = static_cast<long long>(blob->size());
m_size += blobSize;
- m_items.append(BlobDataItem(blob->url(), 0, blobSize));
+ m_items.append(BlobDataItem(blob->blobDataHandle(), 0, blobSize));
}
}
@@ -122,19 +122,34 @@ void BlobBuilder::appendBytesData(const void* data, size_t length)
m_size += buffer.size() - oldSize;
}
-PassRefPtr<Blob> BlobBuilder::getBlob(const String& contentType)
+PassRefPtr<Blob> BlobBuilder::createBlob(const String& contentType)
{
OwnPtr<BlobData> blobData = BlobData::create();
blobData->setContentType(contentType);
blobData->swapItems(m_items);
- RefPtr<Blob> blob = Blob::create(blobData.release(), m_size);
+ RefPtr<Blob> blob = Blob::create(BlobDataHandle::create(blobData.release(), m_size));
- // After creating a blob from the current blob data, we do not need to keep the data around any more. Instead, we only
- // need to keep a reference to the URL of the blob just created.
- m_items.append(BlobDataItem(blob->url(), 0, m_size));
+ // After creating a blob from the current blob data, we do not need to keep the data around any more.
+ // Instead, we only need to keep a reference to the blob data just created.
+ m_items.append(BlobDataItem(blob->blobDataHandle(), 0, m_size));
- return blob;
+ return blob.release();
+}
+
+PassRefPtr<File> BlobBuilder::createFile(const String& contentType, const String& fileName, double modificationTime)
+{
+ OwnPtr<BlobData> blobData = BlobData::create();
+ blobData->setContentType(contentType);
+ blobData->swapItems(m_items);
+
+ RefPtr<File> file = File::create(fileName, modificationTime, BlobDataHandle::create(blobData.release(), m_size));
+
+ // After creating a file from the current blob data, we do not need to keep the data around any more.
+ // Instead, we only need to keep a reference to the blob data just created.
+ m_items.append(BlobDataItem(file->blobDataHandle(), 0, m_size));
+
+ return file.release();
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/fileapi/BlobBuilder.h b/chromium/third_party/WebKit/Source/core/fileapi/BlobBuilder.h
index 6e57f30dfa0..cdf3cc562a9 100644
--- a/chromium/third_party/WebKit/Source/core/fileapi/BlobBuilder.h
+++ b/chromium/third_party/WebKit/Source/core/fileapi/BlobBuilder.h
@@ -31,18 +31,13 @@
#ifndef BlobBuilder_h
#define BlobBuilder_h
-#include "core/platform/network/BlobData.h"
+#include "platform/blob/BlobData.h"
#include "wtf/Forward.h"
-namespace WTF{
-class TextEncoding;
-}
-
namespace WebCore {
class Blob;
-
-typedef int ExceptionCode;
+class File;
class BlobBuilder {
public:
@@ -53,7 +48,8 @@ public:
void append(ArrayBuffer*);
void append(ArrayBufferView*);
- PassRefPtr<Blob> getBlob(const String& contentType);
+ PassRefPtr<Blob> createBlob(const String& contentType);
+ PassRefPtr<File> createFile(const String& contentType, const String& fileName, double modificationTime);
private:
void appendBytesData(const void*, size_t);
diff --git a/chromium/third_party/WebKit/Source/core/fileapi/BlobRegistry.cpp b/chromium/third_party/WebKit/Source/core/fileapi/BlobRegistry.cpp
deleted file mode 100644
index b649b2697be..00000000000
--- a/chromium/third_party/WebKit/Source/core/fileapi/BlobRegistry.cpp
+++ /dev/null
@@ -1,326 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/fileapi/BlobRegistry.h"
-
-#include "core/fileapi/BlobURL.h"
-#include "core/platform/network/BlobData.h"
-#include "public/platform/Platform.h"
-#include "public/platform/WebBlobData.h"
-#include "public/platform/WebBlobRegistry.h"
-#include "public/platform/WebString.h"
-#include "public/platform/WebThreadSafeData.h"
-#include "weborigin/SecurityOrigin.h"
-#include "weborigin/SecurityOriginCache.h"
-#include "wtf/Assertions.h"
-#include "wtf/HashMap.h"
-#include "wtf/MainThread.h"
-#include "wtf/RefPtr.h"
-#include "wtf/ThreadSpecific.h"
-#include "wtf/Threading.h"
-#include "wtf/text/StringHash.h"
-#include "wtf/text/WTFString.h"
-
-using WebKit::WebBlobData;
-using WebKit::WebBlobRegistry;
-using WebKit::WebThreadSafeData;
-using WTF::ThreadSpecific;
-
-namespace WebCore {
-
-class BlobOriginCache : public SecurityOriginCache {
-public:
- BlobOriginCache();
- virtual SecurityOrigin* cachedOrigin(const KURL&) OVERRIDE;
-};
-
-struct BlobRegistryContext {
- WTF_MAKE_FAST_ALLOCATED;
-public:
- BlobRegistryContext(const KURL& url, PassOwnPtr<BlobData> blobData)
- : url(url.copy())
- , blobData(blobData)
- {
- this->blobData->detachFromCurrentThread();
- }
-
- BlobRegistryContext(const KURL& url, const String& type)
- : url(url.copy())
- , type(type.isolatedCopy())
- {
- }
-
- BlobRegistryContext(const KURL& url, const KURL& srcURL)
- : url(url.copy())
- , srcURL(srcURL.copy())
- {
- }
-
- BlobRegistryContext(const KURL& url, PassRefPtr<RawData> streamData)
- : url(url.copy())
- , streamData(streamData)
- {
- }
-
- BlobRegistryContext(const KURL& url)
- : url(url.copy())
- {
- }
-
- KURL url;
- KURL srcURL;
- OwnPtr<BlobData> blobData;
- PassRefPtr<RawData> streamData;
- String type;
-};
-
-static WebBlobRegistry* blobRegistry()
-{
- ASSERT(isMainThread());
- return WebKit::Platform::current()->blobRegistry();
-}
-
-typedef HashMap<String, RefPtr<SecurityOrigin> > BlobURLOriginMap;
-static ThreadSpecific<BlobURLOriginMap>& originMap()
-{
- // We want to create the BlobOriginCache exactly once because it is shared by all the threads.
- AtomicallyInitializedStatic(BlobOriginCache*, cache = new BlobOriginCache);
-
- AtomicallyInitializedStatic(ThreadSpecific<BlobURLOriginMap>*, map = new ThreadSpecific<BlobURLOriginMap>);
- return *map;
-}
-
-static void saveToOriginMap(SecurityOrigin* origin, const KURL& url)
-{
- // If the blob URL contains null origin, as in the context with unique
- // security origin or file URL, save the mapping between url and origin so
- // that the origin can be retrived when doing security origin check.
- if (origin && BlobURL::getOrigin(url) == "null")
- originMap()->add(url.string(), origin);
-}
-
-static void removeFromOriginMap(const KURL& url)
-{
- if (BlobURL::getOrigin(url) == "null")
- originMap()->remove(url.string());
-}
-
-static void registerBlobURLTask(void* context)
-{
- OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context));
- if (WebBlobRegistry* registry = blobRegistry()) {
- WebBlobData webBlobData(blobRegistryContext->blobData.release());
- registry->registerBlobURL(blobRegistryContext->url, webBlobData);
- }
-}
-
-void BlobRegistry::registerBlobURL(const KURL& url, PassOwnPtr<BlobData> blobData)
-{
- if (isMainThread()) {
- if (WebBlobRegistry* registry = blobRegistry()) {
- WebBlobData webBlobData(blobData);
- registry->registerBlobURL(url, webBlobData);
- }
- } else {
- OwnPtr<BlobRegistryContext> context = adoptPtr(new BlobRegistryContext(url, blobData));
- callOnMainThread(&registerBlobURLTask, context.leakPtr());
- }
-}
-
-static void registerBlobURLFromTask(void* context)
-{
- OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context));
- if (WebBlobRegistry* registry = blobRegistry())
- registry->registerBlobURL(blobRegistryContext->url, blobRegistryContext->srcURL);
-}
-
-void BlobRegistry::registerBlobURL(SecurityOrigin* origin, const KURL& url, const KURL& srcURL)
-{
- saveToOriginMap(origin, url);
-
- if (isMainThread()) {
- if (WebBlobRegistry* registry = blobRegistry())
- registry->registerBlobURL(url, srcURL);
- } else {
- OwnPtr<BlobRegistryContext> context = adoptPtr(new BlobRegistryContext(url, srcURL));
- callOnMainThread(&registerBlobURLFromTask, context.leakPtr());
- }
-}
-
-static void unregisterBlobURLTask(void* context)
-{
- OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context));
- if (WebBlobRegistry* registry = blobRegistry())
- registry->unregisterBlobURL(blobRegistryContext->url);
-}
-
-void BlobRegistry::unregisterBlobURL(const KURL& url)
-{
- removeFromOriginMap(url);
-
- if (isMainThread()) {
- if (WebBlobRegistry* registry = blobRegistry())
- registry->unregisterBlobURL(url);
- } else {
- OwnPtr<BlobRegistryContext> context = adoptPtr(new BlobRegistryContext(url));
- callOnMainThread(&unregisterBlobURLTask, context.leakPtr());
- }
-}
-
-static void registerStreamURLTask(void* context)
-{
- OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context));
- if (WebBlobRegistry* registry = blobRegistry())
- registry->registerStreamURL(blobRegistryContext->url, blobRegistryContext->type);
-}
-
-void BlobRegistry::registerStreamURL(const KURL& url, const String& type)
-{
- if (isMainThread()) {
- if (WebBlobRegistry* registry = blobRegistry())
- registry->registerStreamURL(url, type);
- } else {
- OwnPtr<BlobRegistryContext> context = adoptPtr(new BlobRegistryContext(url, type));
- callOnMainThread(&registerStreamURLTask, context.leakPtr());
- }
-}
-
-static void registerStreamURLFromTask(void* context)
-{
- OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context));
- if (WebBlobRegistry* registry = blobRegistry())
- registry->registerStreamURL(blobRegistryContext->url, blobRegistryContext->srcURL);
-}
-
-void BlobRegistry::registerStreamURL(SecurityOrigin* origin, const KURL& url, const KURL& srcURL)
-{
- saveToOriginMap(origin, url);
-
- if (isMainThread()) {
- if (WebBlobRegistry* registry = blobRegistry())
- registry->registerStreamURL(url, srcURL);
- } else {
- OwnPtr<BlobRegistryContext> context = adoptPtr(new BlobRegistryContext(url, srcURL));
- callOnMainThread(&registerStreamURLFromTask, context.leakPtr());
- }
-}
-
-static void addDataToStreamTask(void* context)
-{
- OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context));
- if (WebBlobRegistry* registry = blobRegistry()) {
- WebThreadSafeData webThreadSafeData(blobRegistryContext->streamData);
- registry->addDataToStream(blobRegistryContext->url, webThreadSafeData);
- }
-}
-
-void BlobRegistry::addDataToStream(const KURL& url, PassRefPtr<RawData> streamData)
-{
- if (isMainThread()) {
- if (WebBlobRegistry* registry = blobRegistry()) {
- WebThreadSafeData webThreadSafeData(streamData);
- registry->addDataToStream(url, webThreadSafeData);
- }
- } else {
- OwnPtr<BlobRegistryContext> context = adoptPtr(new BlobRegistryContext(url, streamData));
- callOnMainThread(&addDataToStreamTask, context.leakPtr());
- }
-}
-
-static void finalizeStreamTask(void* context)
-{
- OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context));
- if (WebBlobRegistry* registry = blobRegistry())
- registry->finalizeStream(blobRegistryContext->url);
-}
-
-void BlobRegistry::finalizeStream(const KURL& url)
-{
- if (isMainThread()) {
- if (WebBlobRegistry* registry = blobRegistry())
- registry->finalizeStream(url);
- } else {
- OwnPtr<BlobRegistryContext> context = adoptPtr(new BlobRegistryContext(url));
- callOnMainThread(&finalizeStreamTask, context.leakPtr());
- }
-}
-
-static void abortStreamTask(void* context)
-{
- OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context));
- if (WebBlobRegistry* registry = blobRegistry())
- registry->abortStream(blobRegistryContext->url);
-}
-
-void BlobRegistry::abortStream(const KURL& url)
-{
- if (isMainThread()) {
- if (WebBlobRegistry* registry = blobRegistry())
- registry->abortStream(url);
- } else {
- OwnPtr<BlobRegistryContext> context = adoptPtr(new BlobRegistryContext(url));
- callOnMainThread(&abortStreamTask, context.leakPtr());
- }
-}
-
-static void unregisterStreamURLTask(void* context)
-{
- OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context));
- if (WebBlobRegistry* registry = blobRegistry())
- registry->unregisterStreamURL(blobRegistryContext->url);
-}
-
-void BlobRegistry::unregisterStreamURL(const KURL& url)
-{
- removeFromOriginMap(url);
-
- if (isMainThread()) {
- if (WebBlobRegistry* registry = blobRegistry())
- registry->unregisterStreamURL(url);
- } else {
- OwnPtr<BlobRegistryContext> context = adoptPtr(new BlobRegistryContext(url));
- callOnMainThread(&unregisterStreamURLTask, context.leakPtr());
- }
-}
-
-BlobOriginCache::BlobOriginCache()
-{
- SecurityOrigin::setCache(this);
-}
-
-SecurityOrigin* BlobOriginCache::cachedOrigin(const KURL& url)
-{
- if (url.protocolIs("blob"))
- return originMap()->get(url.string());
- return 0;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/fileapi/BlobRegistry.h b/chromium/third_party/WebKit/Source/core/fileapi/BlobRegistry.h
deleted file mode 100644
index 2889b19d441..00000000000
--- a/chromium/third_party/WebKit/Source/core/fileapi/BlobRegistry.h
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef BlobRegistry_h
-#define BlobRegistry_h
-
-#include "wtf/Forward.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/PassRefPtr.h"
-
-namespace WebCore {
-
-class BlobData;
-class KURL;
-class RawData;
-class SecurityOrigin;
-
-// A bridging class for calling WebKit::WebBlobRegistry methods on the main
-// thread. Each method gets the WebBlobRegistry implementation instance and
-// calls the corresponding method (the same name) on it using callOnMainThread()
-// if necessary.
-class BlobRegistry {
-public:
- // Methods for controlling Blobs.
- static void registerBlobURL(const KURL&, PassOwnPtr<BlobData>);
- static void registerBlobURL(SecurityOrigin*, const KURL&, const KURL& srcURL);
- static void unregisterBlobURL(const KURL&);
-
- // Methods for controlling Streams.
- static void registerStreamURL(const KURL&, const String&);
- static void registerStreamURL(SecurityOrigin*, const KURL&, const KURL& srcURL);
- static void addDataToStream(const KURL&, PassRefPtr<RawData>);
- static void finalizeStream(const KURL&);
- static void abortStream(const KURL&);
- static void unregisterStreamURL(const KURL&);
-};
-
-} // namespace WebCore
-
-#endif // BlobRegistry_h
diff --git a/chromium/third_party/WebKit/Source/core/fileapi/BlobURL.cpp b/chromium/third_party/WebKit/Source/core/fileapi/BlobURL.cpp
deleted file mode 100644
index 1d9b7d8dc15..00000000000
--- a/chromium/third_party/WebKit/Source/core/fileapi/BlobURL.cpp
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/fileapi/BlobURL.h"
-
-#include "core/platform/UUID.h"
-#include "weborigin/KURL.h"
-#include "weborigin/SecurityOrigin.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-const char BlobURL::kBlobProtocol[] = "blob";
-
-KURL BlobURL::createPublicURL(SecurityOrigin* securityOrigin)
-{
- ASSERT(securityOrigin);
- return createBlobURL(securityOrigin->toString());
-}
-
-KURL BlobURL::createInternalURL()
-{
- return createBlobURL("blobinternal://");
-}
-
-String BlobURL::getOrigin(const KURL& url)
-{
- ASSERT(url.protocolIs(kBlobProtocol));
-
- unsigned startIndex = url.pathStart();
- unsigned endIndex = url.pathAfterLastSlash();
- return url.string().substring(startIndex, endIndex - startIndex - 1);
-}
-
-String BlobURL::getIdentifier(const KURL& url)
-{
- ASSERT(url.protocolIs(kBlobProtocol));
-
- unsigned startIndex = url.pathAfterLastSlash();
- return url.string().substring(startIndex);
-}
-
-KURL BlobURL::createBlobURL(const String& originString)
-{
- ASSERT(!originString.isEmpty());
- String urlString = "blob:" + encodeWithURLEscapeSequences(originString) + '/' + createCanonicalUUIDString();
- return KURL::createIsolated(ParsedURLString, urlString);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/fileapi/BlobURL.h b/chromium/third_party/WebKit/Source/core/fileapi/BlobURL.h
deleted file mode 100644
index 719b34635bb..00000000000
--- a/chromium/third_party/WebKit/Source/core/fileapi/BlobURL.h
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef BlobURL_h
-#define BlobURL_h
-
-#include "wtf/Forward.h"
-
-namespace WebCore {
-
-class KURL;
-class SecurityOrigin;
-
-// Blob URLs are of the form
-// blob:%escaped_origin%/%UUID%
-// For public urls, the origin of the host page is encoded in the URL value to
-// allow easy lookup of the origin when security checks need to be performed.
-// When loading blobs via ResourceHandle or when reading blobs via FileReader
-// the loader conducts security checks that examine the origin of host page
-// encoded in the public blob url. The origin baked into internal blob urls
-// is a simple constant value, "blobinternal://", internal urls should not
-// be used with ResourceHandle or FileReader.
-class BlobURL {
-public:
- static KURL createPublicURL(SecurityOrigin*);
- static KURL createInternalURL();
- static String getOrigin(const KURL&);
- static String getIdentifier(const KURL&);
- static const char* blobProtocol() { return kBlobProtocol; }
-
-private:
- static KURL createBlobURL(const String& originString);
- static const char kBlobProtocol[];
- BlobURL() { }
-};
-
-}
-
-#endif // BlobURL_h
diff --git a/chromium/third_party/WebKit/Source/core/fileapi/File.cpp b/chromium/third_party/WebKit/Source/core/fileapi/File.cpp
index cb0466492b5..16a810ae833 100644
--- a/chromium/third_party/WebKit/Source/core/fileapi/File.cpp
+++ b/chromium/third_party/WebKit/Source/core/fileapi/File.cpp
@@ -26,14 +26,12 @@
#include "config.h"
#include "core/fileapi/File.h"
-#include "core/platform/FileMetadata.h"
-#include "core/platform/FileSystem.h"
-#include "core/platform/MIMETypeRegistry.h"
+#include "platform/FileMetadata.h"
+#include "platform/MIMETypeRegistry.h"
#include "public/platform/Platform.h"
#include "public/platform/WebFileUtilities.h"
#include "wtf/CurrentTime.h"
#include "wtf/DateMath.h"
-#include "wtf/text/WTFString.h"
namespace WebCore {
@@ -82,7 +80,7 @@ static PassOwnPtr<BlobData> createBlobDataForFileSystemURL(const KURL& fileSyste
{
OwnPtr<BlobData> blobData = BlobData::create();
blobData->setContentType(getContentTypeFromFileName(fileSystemURL.path(), File::WellKnownContentTypes));
- blobData->appendURL(fileSystemURL, 0, metadata.length, metadata.modificationTime);
+ blobData->appendFileSystemURL(fileSystemURL, 0, metadata.length, metadata.modificationTime);
return blobData.release();
}
@@ -94,40 +92,52 @@ PassRefPtr<File> File::createWithRelativePath(const String& path, const String&
}
File::File(const String& path, ContentTypeLookupPolicy policy)
- : Blob(createBlobDataForFile(path, policy), -1)
+ : Blob(BlobDataHandle::create(createBlobDataForFile(path, policy), -1))
+ , m_hasBackingFile(true)
, m_path(path)
- , m_name(WebKit::Platform::current()->fileUtilities()->baseName(path))
+ , m_name(blink::Platform::current()->fileUtilities()->baseName(path))
, m_snapshotSize(-1)
, m_snapshotModificationTime(invalidFileTime())
{
ScriptWrappable::init(this);
}
-File::File(const String& path, const KURL& url, const String& type)
- : Blob(url, type, -1)
+File::File(const String& path, const String& name, ContentTypeLookupPolicy policy)
+ : Blob(BlobDataHandle::create(createBlobDataForFileWithName(path, name, policy), -1))
+ , m_hasBackingFile(true)
, m_path(path)
+ , m_name(name)
, m_snapshotSize(-1)
, m_snapshotModificationTime(invalidFileTime())
{
ScriptWrappable::init(this);
- m_name = WebKit::Platform::current()->fileUtilities()->baseName(path);
- // FIXME: File object serialization/deserialization does not include
- // newer file object data members: m_name and m_relativePath.
- // See SerializedScriptValue.cpp for js and v8.
}
-File::File(const String& path, const String& name, ContentTypeLookupPolicy policy)
- : Blob(createBlobDataForFileWithName(path, name, policy), -1)
+File::File(const String& path, const String& name, const String& relativePath, bool hasSnaphotData, uint64_t size, double lastModified, PassRefPtr<BlobDataHandle> blobDataHandle)
+ : Blob(blobDataHandle)
+ , m_hasBackingFile(!path.isEmpty() || !relativePath.isEmpty())
, m_path(path)
, m_name(name)
- , m_snapshotSize(-1)
- , m_snapshotModificationTime(invalidFileTime())
+ , m_snapshotSize(hasSnaphotData ? static_cast<long long>(size) : -1)
+ , m_snapshotModificationTime(hasSnaphotData ? lastModified : invalidFileTime())
+ , m_relativePath(relativePath)
+{
+ ScriptWrappable::init(this);
+}
+
+File::File(const String& name, double modificationTime, PassRefPtr<BlobDataHandle> blobDataHandle)
+ : Blob(blobDataHandle)
+ , m_hasBackingFile(false)
+ , m_name(name)
+ , m_snapshotSize(Blob::size())
+ , m_snapshotModificationTime(modificationTime)
{
ScriptWrappable::init(this);
}
File::File(const String& name, const FileMetadata& metadata)
- : Blob(createBlobDataForFileWithMetadata(name, metadata), metadata.length)
+ : Blob(BlobDataHandle::create(createBlobDataForFileWithMetadata(name, metadata), metadata.length))
+ , m_hasBackingFile(true)
, m_path(metadata.platformPath)
, m_name(name)
, m_snapshotSize(metadata.length)
@@ -137,7 +147,8 @@ File::File(const String& name, const FileMetadata& metadata)
}
File::File(const KURL& fileSystemURL, const FileMetadata& metadata)
- : Blob(createBlobDataForFileSystemURL(fileSystemURL, metadata), metadata.length)
+ : Blob(BlobDataHandle::create(createBlobDataForFileSystemURL(fileSystemURL, metadata), metadata.length))
+ , m_hasBackingFile(true)
, m_fileSystemURL(fileSystemURL)
, m_snapshotSize(metadata.length)
, m_snapshotModificationTime(metadata.modificationTime)
diff --git a/chromium/third_party/WebKit/Source/core/fileapi/File.h b/chromium/third_party/WebKit/Source/core/fileapi/File.h
index 063315daf86..6ff3c5b2e9b 100644
--- a/chromium/third_party/WebKit/Source/core/fileapi/File.h
+++ b/chromium/third_party/WebKit/Source/core/fileapi/File.h
@@ -49,10 +49,15 @@ public:
return adoptRef(new File(path, policy));
}
+ static PassRefPtr<File> create(const String& name, double modificationTime, PassRefPtr<BlobDataHandle> blobDataHandle)
+ {
+ return adoptRef(new File(name, modificationTime, blobDataHandle));
+ }
+
// For deserialization.
- static PassRefPtr<File> create(const String& path, const KURL& srcURL, const String& type)
+ static PassRefPtr<File> create(const String& path, const String& name, const String& relativePath, bool hasSnaphotData, uint64_t size, double lastModified, PassRefPtr<BlobDataHandle> blobDataHandle)
{
- return adoptRef(new File(path, srcURL, type));
+ return adoptRef(new File(path, name, relativePath, hasSnaphotData, size, lastModified, blobDataHandle));
}
static PassRefPtr<File> createWithRelativePath(const String& path, const String& relativePath);
@@ -70,7 +75,7 @@ public:
return adoptRef(new File(url, metadata));
}
- KURL fileSystemURL() const { return m_fileSystemURL; }
+ KURL fileSystemURL() const { ASSERT(m_hasBackingFile); return m_fileSystemURL; }
// Create a file with a name exposed to the author (via File.name and associated DOM properties) that differs from the one provided in the path.
static PassRefPtr<File> createWithName(const String& path, const String& name, ContentTypeLookupPolicy policy = WellKnownContentTypes)
@@ -80,10 +85,11 @@ public:
return adoptRef(new File(path, name, policy));
}
- virtual unsigned long long size() const;
- virtual bool isFile() const { return true; }
+ virtual unsigned long long size() const OVERRIDE;
+ virtual bool isFile() const OVERRIDE { return true; }
+ virtual bool hasBackingFile() const OVERRIDE { return m_hasBackingFile; }
- const String& path() const { return m_path; }
+ const String& path() const { ASSERT(m_hasBackingFile); return m_path; }
const String& name() const { return m_name; }
// This returns the current date and time if the file's last modifiecation date is not known (per spec: http://www.w3.org/TR/FileAPI/#dfn-lastModifiedDate).
@@ -95,18 +101,18 @@ public:
// Note that this involves synchronous file operation. Think twice before calling this function.
void captureSnapshot(long long& snapshotSize, double& snapshotModificationTime) const;
+ // Returns true if this has a valid snapshot metadata (i.e. m_snapshotSize >= 0).
+ bool hasValidSnapshotMetadata() const { return m_snapshotSize >= 0; }
+
private:
File(const String& path, ContentTypeLookupPolicy);
-
- // For deserialization.
- File(const String& path, const KURL& srcURL, const String& type);
File(const String& path, const String& name, ContentTypeLookupPolicy);
+ File(const String& path, const String& name, const String& relativePath, bool hasSnaphotData, uint64_t size, double lastModified, PassRefPtr<BlobDataHandle>);
+ File(const String& name, double modificationTime, PassRefPtr<BlobDataHandle>);
File(const String& name, const FileMetadata&);
File(const KURL& fileSystemURL, const FileMetadata&);
- // Returns true if this has a valid snapshot metadata (i.e. m_snapshotSize >= 0).
- bool hasValidSnapshotMetadata() const { return m_snapshotSize >= 0; }
-
+ bool m_hasBackingFile;
String m_path;
String m_name;
@@ -120,17 +126,7 @@ private:
String m_relativePath;
};
-inline File* toFile(Blob* blob)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!blob || blob->isFile());
- return static_cast<File*>(blob);
-}
-
-inline const File* toFile(const Blob* blob)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!blob || blob->isFile());
- return static_cast<const File*>(blob);
-}
+DEFINE_TYPE_CASTS(File, Blob, blob, blob->isFile(), blob.isFile());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/fileapi/File.idl b/chromium/third_party/WebKit/Source/core/fileapi/File.idl
index 2d2ea186a05..2daf799c2ca 100644
--- a/chromium/third_party/WebKit/Source/core/fileapi/File.idl
+++ b/chromium/third_party/WebKit/Source/core/fileapi/File.idl
@@ -23,9 +23,12 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-interface File : Blob {
+[
+ CustomConstructor(sequence<any> blobParts, DOMString fileName, optional BlobPropertyBag options),
+ GlobalContext=Window&WorkerGlobalScope,
+] interface File : Blob {
readonly attribute DOMString name;
- readonly attribute Date lastModifiedDate;
- [EnabledAtRuntime=DirectoryUpload] readonly attribute DOMString webkitRelativePath;
+ [Custom=Getter, MeasureAs=FileGetLastModifiedDate] readonly attribute Date lastModifiedDate;
+ [Custom=Getter, RuntimeEnabled=FileConstructor] readonly attribute long long lastModified;
+ [RuntimeEnabled=DirectoryUpload] readonly attribute DOMString webkitRelativePath;
};
-
diff --git a/chromium/third_party/WebKit/Source/core/fileapi/FileError.cpp b/chromium/third_party/WebKit/Source/core/fileapi/FileError.cpp
index 2fa857639e7..693b52c3c73 100644
--- a/chromium/third_party/WebKit/Source/core/fileapi/FileError.cpp
+++ b/chromium/third_party/WebKit/Source/core/fileapi/FileError.cpp
@@ -123,18 +123,18 @@ const char* errorCodeToMessage(FileError::ErrorCode code)
} // namespace
-void FileError::throwDOMException(ExceptionState& es, ErrorCode code)
+void FileError::throwDOMException(ExceptionState& exceptionState, ErrorCode code)
{
if (code == FileError::OK)
return;
// SecurityError is special-cased, as we want to route those exceptions through ExceptionState::throwSecurityError.
if (code == FileError::SECURITY_ERR) {
- es.throwSecurityError(FileError::securityErrorMessage);
+ exceptionState.throwSecurityError(FileError::securityErrorMessage);
return;
}
- es.throwDOMException(errorCodeToExceptionCode(code), errorCodeToMessage(code));
+ exceptionState.throwDOMException(errorCodeToExceptionCode(code), errorCodeToMessage(code));
}
FileError::FileError(ErrorCode code)
diff --git a/chromium/third_party/WebKit/Source/core/fileapi/FileList.cpp b/chromium/third_party/WebKit/Source/core/fileapi/FileList.cpp
index 1b507c6fce5..267a7f5d056 100644
--- a/chromium/third_party/WebKit/Source/core/fileapi/FileList.cpp
+++ b/chromium/third_party/WebKit/Source/core/fileapi/FileList.cpp
@@ -26,7 +26,6 @@
#include "config.h"
#include "core/fileapi/FileList.h"
-#include "core/fileapi/File.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/fileapi/FileReader.cpp b/chromium/third_party/WebKit/Source/core/fileapi/FileReader.cpp
index 6568c2f1d1b..c94eadb93f6 100644
--- a/chromium/third_party/WebKit/Source/core/fileapi/FileReader.cpp
+++ b/chromium/third_party/WebKit/Source/core/fileapi/FileReader.cpp
@@ -34,40 +34,104 @@
#include "bindings/v8/ExceptionState.h"
#include "core/dom/CrossThreadTask.h"
#include "core/dom/ExceptionCode.h"
-#include "core/dom/ProgressEvent.h"
-#include "core/dom/ScriptExecutionContext.h"
+#include "core/dom/ExecutionContext.h"
+#include "core/events/ProgressEvent.h"
#include "core/fileapi/File.h"
-#include "core/platform/Logging.h"
+#include "platform/Logging.h"
#include "wtf/ArrayBuffer.h"
#include "wtf/CurrentTime.h"
+#include "wtf/Deque.h"
+#include "wtf/HashSet.h"
+#include "wtf/ThreadSpecific.h"
+#include "wtf/Threading.h"
#include "wtf/text/CString.h"
namespace WebCore {
namespace {
-const CString utf8BlobURL(Blob* blob)
+#if !LOG_DISABLED
+const CString utf8BlobUUID(Blob* blob)
{
- return blob->url().string().utf8();
+ return blob->uuid().utf8();
}
const CString utf8FilePath(Blob* blob)
{
- return blob->isFile() ? toFile(blob)->path().utf8() : "";
+ return blob->hasBackingFile() ? toFile(blob)->path().utf8() : "";
}
+#endif
} // namespace
+// Embedders like chromium limit the number of simultaneous requests to avoid
+// excessive IPC congestion. We limit this to 100 per thread to throttle the
+// requests (the value is arbitrarily chosen).
+static const size_t kMaxOutstandingRequestsPerThread = 100;
static const double progressNotificationIntervalMS = 50;
-PassRefPtr<FileReader> FileReader::create(ScriptExecutionContext* context)
+class FileReader::ThrottlingController {
+public:
+ ThrottlingController() : m_maxRunningReaders(kMaxOutstandingRequestsPerThread) { }
+ ~ThrottlingController() { }
+
+ void pushReader(FileReader* reader)
+ {
+ reader->setPendingActivity(reader);
+ if (m_pendingReaders.isEmpty()
+ && m_runningReaders.size() < m_maxRunningReaders) {
+ reader->executePendingRead();
+ m_runningReaders.add(reader);
+ return;
+ }
+ m_pendingReaders.append(reader);
+ executeReaders();
+ }
+
+ void removeReader(FileReader* reader)
+ {
+ HashSet<FileReader*>::const_iterator hashIter = m_runningReaders.find(reader);
+ if (hashIter != m_runningReaders.end()) {
+ m_runningReaders.remove(hashIter);
+ reader->unsetPendingActivity(reader);
+ executeReaders();
+ return;
+ }
+ Deque<FileReader*>::const_iterator dequeEnd = m_pendingReaders.end();
+ for (Deque<FileReader*>::const_iterator it = m_pendingReaders.begin(); it != dequeEnd; ++it) {
+ if (*it == reader) {
+ m_pendingReaders.remove(it);
+ reader->unsetPendingActivity(reader);
+ return;
+ }
+ }
+ }
+
+private:
+ void executeReaders()
+ {
+ while (m_runningReaders.size() < m_maxRunningReaders) {
+ if (m_pendingReaders.isEmpty())
+ return;
+ FileReader* reader = m_pendingReaders.takeFirst();
+ reader->executePendingRead();
+ m_runningReaders.add(reader);
+ }
+ }
+
+ const size_t m_maxRunningReaders;
+ Deque<FileReader*> m_pendingReaders;
+ HashSet<FileReader*> m_runningReaders;
+};
+
+PassRefPtr<FileReader> FileReader::create(ExecutionContext* context)
{
RefPtr<FileReader> fileReader(adoptRef(new FileReader(context)));
fileReader->suspendIfNeeded();
return fileReader.release();
}
-FileReader::FileReader(ScriptExecutionContext* context)
+FileReader::FileReader(ExecutionContext* context)
: ActiveDOMObject(context)
, m_state(EMPTY)
, m_loadingState(LoadingStateNone)
@@ -84,103 +148,114 @@ FileReader::~FileReader()
const AtomicString& FileReader::interfaceName() const
{
- return eventNames().interfaceForFileReader;
-}
-
-bool FileReader::canSuspend() const
-{
- // FIXME: It is not currently possible to suspend a FileReader, so pages with FileReader can not go into page cache.
- return false;
+ return EventTargetNames::FileReader;
}
void FileReader::stop()
{
+ if (m_loadingState == LoadingStateLoading || m_loadingState == LoadingStatePending)
+ throttlingController()->removeReader(this);
terminate();
}
-void FileReader::readAsArrayBuffer(Blob* blob, ExceptionState& es)
+void FileReader::readAsArrayBuffer(Blob* blob, ExceptionState& exceptionState)
{
- if (!blob)
+ if (!blob) {
+ exceptionState.throwTypeError("The argument is not a Blob.");
return;
+ }
- LOG(FileAPI, "FileReader: reading as array buffer: %s %s\n", utf8BlobURL(blob).data(), utf8FilePath(blob).data());
+ WTF_LOG(FileAPI, "FileReader: reading as array buffer: %s %s\n", utf8BlobUUID(blob).data(), utf8FilePath(blob).data());
- readInternal(blob, FileReaderLoader::ReadAsArrayBuffer, es);
+ readInternal(blob, FileReaderLoader::ReadAsArrayBuffer, exceptionState);
}
-void FileReader::readAsBinaryString(Blob* blob, ExceptionState& es)
+void FileReader::readAsBinaryString(Blob* blob, ExceptionState& exceptionState)
{
- if (!blob)
+ if (!blob) {
+ exceptionState.throwTypeError("The argument is not a Blob.");
return;
+ }
- LOG(FileAPI, "FileReader: reading as binary: %s %s\n", utf8BlobURL(blob).data(), utf8FilePath(blob).data());
+ WTF_LOG(FileAPI, "FileReader: reading as binary: %s %s\n", utf8BlobUUID(blob).data(), utf8FilePath(blob).data());
- readInternal(blob, FileReaderLoader::ReadAsBinaryString, es);
+ readInternal(blob, FileReaderLoader::ReadAsBinaryString, exceptionState);
}
-void FileReader::readAsText(Blob* blob, const String& encoding, ExceptionState& es)
+void FileReader::readAsText(Blob* blob, const String& encoding, ExceptionState& exceptionState)
{
- if (!blob)
+ if (!blob) {
+ exceptionState.throwTypeError("The argument is not a Blob.");
return;
+ }
- LOG(FileAPI, "FileReader: reading as text: %s %s\n", utf8BlobURL(blob).data(), utf8FilePath(blob).data());
+ WTF_LOG(FileAPI, "FileReader: reading as text: %s %s\n", utf8BlobUUID(blob).data(), utf8FilePath(blob).data());
m_encoding = encoding;
- readInternal(blob, FileReaderLoader::ReadAsText, es);
+ readInternal(blob, FileReaderLoader::ReadAsText, exceptionState);
}
-void FileReader::readAsText(Blob* blob, ExceptionState& es)
+void FileReader::readAsText(Blob* blob, ExceptionState& exceptionState)
{
- readAsText(blob, String(), es);
+ readAsText(blob, String(), exceptionState);
}
-void FileReader::readAsDataURL(Blob* blob, ExceptionState& es)
+void FileReader::readAsDataURL(Blob* blob, ExceptionState& exceptionState)
{
- if (!blob)
+ if (!blob) {
+ exceptionState.throwTypeError("The argument is not a Blob.");
return;
+ }
- LOG(FileAPI, "FileReader: reading as data URL: %s %s\n", utf8BlobURL(blob).data(), utf8FilePath(blob).data());
+ WTF_LOG(FileAPI, "FileReader: reading as data URL: %s %s\n", utf8BlobUUID(blob).data(), utf8FilePath(blob).data());
- readInternal(blob, FileReaderLoader::ReadAsDataURL, es);
+ readInternal(blob, FileReaderLoader::ReadAsDataURL, exceptionState);
}
-void FileReader::readInternal(Blob* blob, FileReaderLoader::ReadType type, ExceptionState& es)
+void FileReader::readInternal(Blob* blob, FileReaderLoader::ReadType type, ExceptionState& exceptionState)
{
// If multiple concurrent read methods are called on the same FileReader, InvalidStateError should be thrown when the state is LOADING.
if (m_state == LOADING) {
- es.throwDOMException(InvalidStateError);
+ exceptionState.throwDOMException(InvalidStateError, "The object is already busy reading Blobs.");
return;
}
- setPendingActivity(this);
-
m_blob = blob;
m_readType = type;
m_state = LOADING;
- m_loadingState = LoadingStateLoading;
+ m_loadingState = LoadingStatePending;
m_error = 0;
+ throttlingController()->pushReader(this);
+}
+
+void FileReader::executePendingRead()
+{
+ ASSERT(m_loadingState == LoadingStatePending);
+ m_loadingState = LoadingStateLoading;
m_loader = adoptPtr(new FileReaderLoader(m_readType, this));
m_loader->setEncoding(m_encoding);
m_loader->setDataType(m_blob->type());
- m_loader->start(scriptExecutionContext(), *m_blob);
+ m_loader->start(executionContext(), m_blob->blobDataHandle());
}
-static void delayedAbort(ScriptExecutionContext*, FileReader* reader)
+static void delayedAbort(ExecutionContext*, FileReader* reader)
{
reader->doAbort();
}
void FileReader::abort()
{
- LOG(FileAPI, "FileReader: aborting\n");
+ WTF_LOG(FileAPI, "FileReader: aborting\n");
- if (m_loadingState != LoadingStateLoading)
+ if (m_loadingState != LoadingStateLoading
+ && m_loadingState != LoadingStatePending) {
return;
+ }
m_loadingState = LoadingStateAborted;
// Schedule to have the abort done later since abort() might be called from the event handler and we do not want the resource loading code to be in the stack.
- scriptExecutionContext()->postTask(
+ executionContext()->postTask(
createCallbackTask(&delayedAbort, AllowAccessLater(this)));
}
@@ -192,12 +267,12 @@ void FileReader::doAbort()
m_error = FileError::create(FileError::ABORT_ERR);
- fireEvent(eventNames().errorEvent);
- fireEvent(eventNames().abortEvent);
- fireEvent(eventNames().loadendEvent);
+ fireEvent(EventTypeNames::error);
+ fireEvent(EventTypeNames::abort);
+ fireEvent(EventTypeNames::loadend);
// All possible events have fired and we're done, no more pending activity.
- unsetPendingActivity(this);
+ throttlingController()->removeReader(this);
}
void FileReader::terminate()
@@ -212,7 +287,7 @@ void FileReader::terminate()
void FileReader::didStartLoading()
{
- fireEvent(eventNames().loadstartEvent);
+ fireEvent(EventTypeNames::loadstart);
}
void FileReader::didReceiveData()
@@ -222,7 +297,7 @@ void FileReader::didReceiveData()
if (!m_lastProgressNotificationTimeMS)
m_lastProgressNotificationTimeMS = now;
else if (now - m_lastProgressNotificationTimeMS > progressNotificationIntervalMS) {
- fireEvent(eventNames().progressEvent);
+ fireEvent(EventTypeNames::progress);
m_lastProgressNotificationTimeMS = now;
}
}
@@ -238,16 +313,16 @@ void FileReader::didFinishLoading()
// if we're still loading (therefore we need abort process) or not.
m_loadingState = LoadingStateNone;
- fireEvent(eventNames().progressEvent);
+ fireEvent(EventTypeNames::progress);
ASSERT(m_state != DONE);
m_state = DONE;
- fireEvent(eventNames().loadEvent);
- fireEvent(eventNames().loadendEvent);
+ fireEvent(EventTypeNames::load);
+ fireEvent(EventTypeNames::loadend);
// All possible events have fired and we're done, no more pending activity.
- unsetPendingActivity(this);
+ throttlingController()->removeReader(this);
}
void FileReader::didFail(FileError::ErrorCode errorCode)
@@ -261,16 +336,30 @@ void FileReader::didFail(FileError::ErrorCode errorCode)
m_state = DONE;
m_error = FileError::create(static_cast<FileError::ErrorCode>(errorCode));
- fireEvent(eventNames().errorEvent);
- fireEvent(eventNames().loadendEvent);
+ fireEvent(EventTypeNames::error);
+ fireEvent(EventTypeNames::loadend);
// All possible events have fired and we're done, no more pending activity.
- unsetPendingActivity(this);
+ throttlingController()->removeReader(this);
}
void FileReader::fireEvent(const AtomicString& type)
{
- dispatchEvent(ProgressEvent::create(type, true, m_loader ? m_loader->bytesLoaded() : 0, m_loader ? m_loader->totalBytes() : 0));
+ if (!m_loader) {
+ dispatchEvent(ProgressEvent::create(type, false, 0, 0));
+ return;
+ }
+
+ if (m_loader->totalBytes() >= 0)
+ dispatchEvent(ProgressEvent::create(type, true, m_loader->bytesLoaded(), m_loader->totalBytes()));
+ else
+ dispatchEvent(ProgressEvent::create(type, false, m_loader->bytesLoaded(), 0));
+}
+
+ThreadSpecific<FileReader::ThrottlingController>& FileReader::throttlingController()
+{
+ AtomicallyInitializedStatic(ThreadSpecific<FileReader::ThrottlingController>*, controller = new ThreadSpecific<FileReader::ThrottlingController>);
+ return *controller;
}
PassRefPtr<ArrayBuffer> FileReader::arrayBufferResult() const
diff --git a/chromium/third_party/WebKit/Source/core/fileapi/FileReader.h b/chromium/third_party/WebKit/Source/core/fileapi/FileReader.h
index aabd5d57e24..65fd97aa18a 100644
--- a/chromium/third_party/WebKit/Source/core/fileapi/FileReader.h
+++ b/chromium/third_party/WebKit/Source/core/fileapi/FileReader.h
@@ -33,23 +33,25 @@
#include "bindings/v8/ScriptWrappable.h"
#include "core/dom/ActiveDOMObject.h"
-#include "core/dom/EventTarget.h"
+#include "core/events/EventTarget.h"
#include "core/fileapi/FileError.h"
#include "core/fileapi/FileReaderLoader.h"
#include "core/fileapi/FileReaderLoaderClient.h"
#include "wtf/Forward.h"
#include "wtf/RefCounted.h"
+#include "wtf/ThreadSpecific.h"
#include "wtf/text/WTFString.h"
namespace WebCore {
class Blob;
class ExceptionState;
-class ScriptExecutionContext;
+class ExecutionContext;
-class FileReader : public RefCounted<FileReader>, public ScriptWrappable, public ActiveDOMObject, public EventTarget, public FileReaderLoaderClient {
+class FileReader : public RefCounted<FileReader>, public ScriptWrappable, public ActiveDOMObject, public EventTargetWithInlineData, public FileReaderLoaderClient {
+ REFCOUNTED_EVENT_TARGET(FileReader);
public:
- static PassRefPtr<FileReader> create(ScriptExecutionContext*);
+ static PassRefPtr<FileReader> create(ExecutionContext*);
virtual ~FileReader();
@@ -75,12 +77,11 @@ public:
String stringResult();
// ActiveDOMObject
- virtual bool canSuspend() const;
virtual void stop();
// EventTarget
- virtual const AtomicString& interfaceName() const;
- virtual ScriptExecutionContext* scriptExecutionContext() const { return ActiveDOMObject::scriptExecutionContext(); }
+ virtual const AtomicString& interfaceName() const OVERRIDE;
+ virtual ExecutionContext* executionContext() const OVERRIDE { return ActiveDOMObject::executionContext(); }
// FileReaderLoaderClient
virtual void didStartLoading();
@@ -88,9 +89,6 @@ public:
virtual void didFinishLoading();
virtual void didFail(FileError::ErrorCode);
- using RefCounted<FileReader>::ref;
- using RefCounted<FileReader>::deref;
-
DEFINE_ATTRIBUTE_EVENT_LISTENER(loadstart);
DEFINE_ATTRIBUTE_EVENT_LISTENER(progress);
DEFINE_ATTRIBUTE_EVENT_LISTENER(load);
@@ -99,32 +97,30 @@ public:
DEFINE_ATTRIBUTE_EVENT_LISTENER(loadend);
private:
- FileReader(ScriptExecutionContext*);
+ class ThrottlingController;
- // EventTarget
- virtual void refEventTarget() { ref(); }
- virtual void derefEventTarget() { deref(); }
- virtual EventTargetData* eventTargetData() { return &m_eventTargetData; }
- virtual EventTargetData* ensureEventTargetData() { return &m_eventTargetData; }
+ FileReader(ExecutionContext*);
void terminate();
void readInternal(Blob*, FileReaderLoader::ReadType, ExceptionState&);
void fireErrorEvent(int httpStatusCode);
void fireEvent(const AtomicString& type);
+ static ThreadSpecific<ThrottlingController>& throttlingController();
+ void executePendingRead();
+
ReadyState m_state;
// Internal loading state, which could differ from ReadyState as it's
// for script-visible state while this one's for internal state.
enum LoadingState {
LoadingStateNone,
+ LoadingStatePending,
LoadingStateLoading,
LoadingStateAborted
};
LoadingState m_loadingState;
- EventTargetData m_eventTargetData;
-
RefPtr<Blob> m_blob;
FileReaderLoader::ReadType m_readType;
String m_encoding;
diff --git a/chromium/third_party/WebKit/Source/core/fileapi/FileReader.idl b/chromium/third_party/WebKit/Source/core/fileapi/FileReader.idl
index d43e34e75a3..6faaffff29e 100644
--- a/chromium/third_party/WebKit/Source/core/fileapi/FileReader.idl
+++ b/chromium/third_party/WebKit/Source/core/fileapi/FileReader.idl
@@ -30,10 +30,10 @@
*/
[
- GlobalContext=Window&WorkerGlobalScope,
ActiveDOMObject,
Constructor,
- ConstructorCallWith=ScriptExecutionContext
+ ConstructorCallWith=ExecutionContext,
+ GlobalContext=Window&WorkerGlobalScope,
] interface FileReader : EventTarget {
// ready states
const unsigned short EMPTY = 0;
@@ -50,7 +50,7 @@
void abort();
// file data
- [Custom] readonly attribute any result;
+ [Custom=Getter] readonly attribute object result;
readonly attribute FileError error;
diff --git a/chromium/third_party/WebKit/Source/core/fileapi/FileReaderLoader.cpp b/chromium/third_party/WebKit/Source/core/fileapi/FileReaderLoader.cpp
index 7448e678d29..29827a4ab34 100644
--- a/chromium/third_party/WebKit/Source/core/fileapi/FileReaderLoader.cpp
+++ b/chromium/third_party/WebKit/Source/core/fileapi/FileReaderLoader.cpp
@@ -32,17 +32,18 @@
#include "core/fileapi/FileReaderLoader.h"
-#include "core/dom/ScriptExecutionContext.h"
+#include "FetchInitiatorTypeNames.h"
+#include "core/dom/ExecutionContext.h"
#include "core/fetch/TextResourceDecoder.h"
#include "core/fileapi/Blob.h"
-#include "core/fileapi/BlobRegistry.h"
-#include "core/fileapi/BlobURL.h"
#include "core/fileapi/FileReaderLoaderClient.h"
#include "core/fileapi/Stream.h"
#include "core/loader/ThreadableLoader.h"
-#include "core/platform/network/ResourceRequest.h"
-#include "core/platform/network/ResourceResponse.h"
-#include "wtf/ArrayBuffer.h"
+#include "platform/blob/BlobRegistry.h"
+#include "platform/blob/BlobURL.h"
+#include "platform/network/ResourceRequest.h"
+#include "platform/network/ResourceResponse.h"
+#include "wtf/PassOwnPtr.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefPtr.h"
#include "wtf/Vector.h"
@@ -53,17 +54,15 @@ using namespace std;
namespace WebCore {
-const int defaultBufferLength = 32768;
-
FileReaderLoader::FileReaderLoader(ReadType readType, FileReaderLoaderClient* client)
: m_readType(readType)
, m_client(client)
, m_urlForReadingIsStream(false)
, m_isRawDataConverted(false)
, m_stringResult("")
- , m_variableLength(false)
+ , m_finishedLoading(false)
, m_bytesLoaded(0)
- , m_totalBytes(0)
+ , m_totalBytes(-1)
, m_hasRange(false)
, m_rangeStart(0)
, m_rangeEnd(0)
@@ -78,23 +77,26 @@ FileReaderLoader::~FileReaderLoader()
if (m_urlForReadingIsStream)
BlobRegistry::unregisterStreamURL(m_urlForReading);
else
- BlobRegistry::unregisterBlobURL(m_urlForReading);
+ BlobRegistry::revokePublicBlobURL(m_urlForReading);
}
}
-void FileReaderLoader::startForURL(ScriptExecutionContext* scriptExecutionContext, const KURL& url)
+void FileReaderLoader::startInternal(ExecutionContext* executionContext, const Stream* stream, PassRefPtr<BlobDataHandle> blobData)
{
// The blob is read by routing through the request handling layer given a temporary public url.
- m_urlForReading = BlobURL::createPublicURL(scriptExecutionContext->securityOrigin());
+ m_urlForReading = BlobURL::createPublicURL(executionContext->securityOrigin());
if (m_urlForReading.isEmpty()) {
failed(FileError::SECURITY_ERR);
return;
}
- if (m_urlForReadingIsStream)
- BlobRegistry::registerStreamURL(scriptExecutionContext->securityOrigin(), m_urlForReading, url);
- else
- BlobRegistry::registerBlobURL(scriptExecutionContext->securityOrigin(), m_urlForReading, url);
+ if (blobData) {
+ ASSERT(!stream);
+ BlobRegistry::registerPublicBlobURL(executionContext->securityOrigin(), m_urlForReading, blobData);
+ } else {
+ ASSERT(stream);
+ BlobRegistry::registerStreamURL(executionContext->securityOrigin(), m_urlForReading, stream->url());
+ }
// Construct and load the request.
ResourceRequest request(m_urlForReading);
@@ -110,20 +112,22 @@ void FileReaderLoader::startForURL(ScriptExecutionContext* scriptExecutionContex
options.crossOriginRequestPolicy = DenyCrossOriginRequests;
// FIXME: Is there a directive to which this load should be subject?
options.contentSecurityPolicyEnforcement = DoNotEnforceContentSecurityPolicy;
+ // Use special initiator to hide the request from the inspector.
+ options.initiator = FetchInitiatorTypeNames::internal;
if (m_client)
- m_loader = ThreadableLoader::create(scriptExecutionContext, this, request, options);
+ m_loader = ThreadableLoader::create(executionContext, this, request, options);
else
- ThreadableLoader::loadResourceSynchronously(scriptExecutionContext, request, *this, options);
+ ThreadableLoader::loadResourceSynchronously(executionContext, request, *this, options);
}
-void FileReaderLoader::start(ScriptExecutionContext* scriptExecutionContext, const Blob& blob)
+void FileReaderLoader::start(ExecutionContext* executionContext, PassRefPtr<BlobDataHandle> blobData)
{
m_urlForReadingIsStream = false;
- startForURL(scriptExecutionContext, blob.url());
+ startInternal(executionContext, 0, blobData);
}
-void FileReaderLoader::start(ScriptExecutionContext* scriptExecutionContext, const Stream& stream, unsigned readSize)
+void FileReaderLoader::start(ExecutionContext* executionContext, const Stream& stream, unsigned readSize)
{
if (readSize > 0) {
m_hasRange = true;
@@ -132,7 +136,7 @@ void FileReaderLoader::start(ScriptExecutionContext* scriptExecutionContext, con
}
m_urlForReadingIsStream = true;
- startForURL(scriptExecutionContext, stream.url());
+ startInternal(executionContext, &stream, 0);
}
void FileReaderLoader::cancel()
@@ -155,9 +159,10 @@ void FileReaderLoader::cleanup()
// If we get any error, we do not need to keep a buffer around.
if (m_errorCode) {
- m_rawData = 0;
+ m_rawData.clear();
m_stringResult = "";
m_isRawDataConverted = true;
+ m_decoder.clear();
}
}
@@ -168,35 +173,48 @@ void FileReaderLoader::didReceiveResponse(unsigned long, const ResourceResponse&
return;
}
- unsigned long long length = response.expectedContentLength();
-
- // A value larger than INT_MAX means that the content length wasn't
- // specified, so the buffer will need to be dynamically grown.
- if (length > INT_MAX) {
- m_variableLength = true;
- if (m_hasRange)
- length = 1 + m_rangeEnd - m_rangeStart;
- else
- length = defaultBufferLength;
- }
-
- // Check that we can cast to unsigned since we have to do
- // so to call ArrayBuffer's create function.
- // FIXME: Support reading more than the current size limit of ArrayBuffer.
- if (length > numeric_limits<unsigned>::max()) {
- failed(FileError::NOT_READABLE_ERR);
- return;
+ // A negative value means that the content length wasn't specified.
+ m_totalBytes = response.expectedContentLength();
+
+ long long initialBufferLength = -1;
+
+ if (m_totalBytes >= 0) {
+ initialBufferLength = m_totalBytes;
+ } else if (m_hasRange) {
+ // Set m_totalBytes and allocate a buffer based on the specified range.
+ m_totalBytes = 1LL + m_rangeEnd - m_rangeStart;
+ initialBufferLength = m_totalBytes;
+ } else {
+ // Nothing is known about the size of the resource. Normalize
+ // m_totalBytes to -1 and initialize the buffer for receiving with the
+ // default size.
+ m_totalBytes = -1;
}
ASSERT(!m_rawData);
- m_rawData = ArrayBuffer::create(static_cast<unsigned>(length), 1);
- if (!m_rawData) {
- failed(FileError::NOT_READABLE_ERR);
- return;
- }
+ if (m_readType != ReadByClient) {
+ // Check that we can cast to unsigned since we have to do
+ // so to call ArrayBuffer's create function.
+ // FIXME: Support reading more than the current size limit of ArrayBuffer.
+ if (initialBufferLength > numeric_limits<unsigned>::max()) {
+ failed(FileError::NOT_READABLE_ERR);
+ return;
+ }
- m_totalBytes = static_cast<unsigned>(length);
+ if (initialBufferLength < 0) {
+ m_rawData = adoptPtr(new ArrayBufferBuilder());
+ } else {
+ m_rawData = adoptPtr(new ArrayBufferBuilder(static_cast<unsigned>(initialBufferLength)));
+ // Total size is known. Set m_rawData to ignore overflowed data.
+ m_rawData->setVariableCapacity(false);
+ }
+
+ if (!m_rawData) {
+ failed(FileError::NOT_READABLE_ERR);
+ return;
+ }
+ }
if (m_client)
m_client->didStartLoading();
@@ -219,34 +237,14 @@ void FileReaderLoader::didReceiveData(const char* data, int dataLength)
return;
}
- int length = dataLength;
- unsigned remainingBufferSpace = m_totalBytes - m_bytesLoaded;
- if (length > static_cast<long long>(remainingBufferSpace)) {
- // If the buffer has hit maximum size, it can't be grown any more.
- if (m_totalBytes >= numeric_limits<unsigned>::max()) {
- failed(FileError::NOT_READABLE_ERR);
- return;
- }
- if (m_variableLength) {
- unsigned long long newLength = m_totalBytes * 2;
- if (newLength > numeric_limits<unsigned>::max())
- newLength = numeric_limits<unsigned>::max();
- RefPtr<ArrayBuffer> newData =
- ArrayBuffer::create(static_cast<unsigned>(newLength), 1);
- memcpy(static_cast<char*>(newData->data()), static_cast<char*>(m_rawData->data()), m_bytesLoaded);
-
- m_rawData = newData;
- m_totalBytes = static_cast<unsigned>(newLength);
- } else
- length = remainingBufferSpace;
- }
-
- if (length <= 0)
+ unsigned bytesAppended = m_rawData->append(data, static_cast<unsigned>(dataLength));
+ if (!bytesAppended) {
+ m_rawData.clear();
+ m_bytesLoaded = 0;
+ failed(FileError::NOT_READABLE_ERR);
return;
-
- memcpy(static_cast<char*>(m_rawData->data()) + m_bytesLoaded, data, length);
- m_bytesLoaded += length;
-
+ }
+ m_bytesLoaded += bytesAppended;
m_isRawDataConverted = false;
if (m_client)
@@ -255,14 +253,18 @@ void FileReaderLoader::didReceiveData(const char* data, int dataLength)
void FileReaderLoader::didFinishLoading(unsigned long, double)
{
- if (m_readType != ReadByClient && m_variableLength && m_totalBytes > m_bytesLoaded) {
- RefPtr<ArrayBuffer> newData = m_rawData->slice(0, m_bytesLoaded);
-
- m_rawData = newData;
+ if (m_readType != ReadByClient && m_rawData) {
+ m_rawData->shrinkToFit();
m_isRawDataConverted = false;
+ }
+ if (m_totalBytes == -1) {
+ // Update m_totalBytes only when in dynamic buffer grow mode.
m_totalBytes = m_bytesLoaded;
}
+
+ m_finishedLoading = true;
+
cleanup();
if (m_client)
m_client->didFinishLoading();
@@ -305,12 +307,7 @@ PassRefPtr<ArrayBuffer> FileReaderLoader::arrayBufferResult() const
if (!m_rawData || m_errorCode)
return 0;
- // If completed, we can simply return our buffer.
- if (isCompleted())
- return m_rawData;
-
- // Otherwise, return a copy.
- return m_rawData->slice(0, m_bytesLoaded);
+ return m_rawData->toArrayBuffer();
}
String FileReaderLoader::stringResult()
@@ -330,7 +327,7 @@ String FileReaderLoader::stringResult()
// No conversion is needed.
break;
case ReadAsBinaryString:
- m_stringResult = String(static_cast<const char*>(m_rawData->data()), m_bytesLoaded);
+ m_stringResult = m_rawData->toString();
m_isRawDataConverted = true;
break;
case ReadAsText:
@@ -338,7 +335,7 @@ String FileReaderLoader::stringResult()
break;
case ReadAsDataURL:
// Partial data is not supported when reading as data URL.
- if (isCompleted())
+ if (m_finishedLoading)
convertToDataURL();
break;
default:
@@ -365,9 +362,9 @@ void FileReaderLoader::convertToText()
StringBuilder builder;
if (!m_decoder)
m_decoder = TextResourceDecoder::create("text/plain", m_encoding.isValid() ? m_encoding : UTF8Encoding());
- builder.append(m_decoder->decode(static_cast<const char*>(m_rawData->data()), m_bytesLoaded));
+ builder.append(m_decoder->decode(static_cast<const char*>(m_rawData->data()), m_rawData->byteLength()));
- if (isCompleted())
+ if (m_finishedLoading)
builder.append(m_decoder->flush());
m_stringResult = builder.toString();
@@ -389,18 +386,13 @@ void FileReaderLoader::convertToDataURL()
builder.append(";base64,");
Vector<char> out;
- base64Encode(static_cast<const char*>(m_rawData->data()), m_bytesLoaded, out);
+ base64Encode(static_cast<const char*>(m_rawData->data()), m_rawData->byteLength(), out);
out.append('\0');
builder.append(out.data());
m_stringResult = builder.toString();
}
-bool FileReaderLoader::isCompleted() const
-{
- return m_bytesLoaded == m_totalBytes;
-}
-
void FileReaderLoader::setEncoding(const String& encoding)
{
if (!encoding.isEmpty())
diff --git a/chromium/third_party/WebKit/Source/core/fileapi/FileReaderLoader.h b/chromium/third_party/WebKit/Source/core/fileapi/FileReaderLoader.h
index 0eb8f5edd14..6bb4459ae07 100644
--- a/chromium/third_party/WebKit/Source/core/fileapi/FileReaderLoader.h
+++ b/chromium/third_party/WebKit/Source/core/fileapi/FileReaderLoader.h
@@ -33,16 +33,19 @@
#include "core/fileapi/FileError.h"
#include "core/loader/ThreadableLoaderClient.h"
-#include "weborigin/KURL.h"
+#include "platform/weborigin/KURL.h"
+#include "wtf/ArrayBuffer.h"
+#include "wtf/ArrayBufferBuilder.h"
#include "wtf/Forward.h"
+#include "wtf/OwnPtr.h"
#include "wtf/text/TextEncoding.h"
#include "wtf/text/WTFString.h"
namespace WebCore {
-class Blob;
+class BlobDataHandle;
class FileReaderLoaderClient;
-class ScriptExecutionContext;
+class ExecutionContext;
class Stream;
class TextResourceDecoder;
class ThreadableLoader;
@@ -62,8 +65,8 @@ public:
FileReaderLoader(ReadType, FileReaderLoaderClient*);
~FileReaderLoader();
- void start(ScriptExecutionContext*, const Blob&);
- void start(ScriptExecutionContext*, const Stream&, unsigned readSize);
+ void start(ExecutionContext*, PassRefPtr<BlobDataHandle>);
+ void start(ExecutionContext*, const Stream&, unsigned readSize);
void cancel();
// ThreadableLoaderClient
@@ -74,26 +77,36 @@ public:
String stringResult();
PassRefPtr<ArrayBuffer> arrayBufferResult() const;
- unsigned bytesLoaded() const { return m_bytesLoaded; }
- unsigned totalBytes() const { return m_totalBytes; }
+
+ // Returns the total bytes received. Bytes ignored by m_rawData won't be
+ // counted.
+ //
+ // This value doesn't grow more than numeric_limits<unsigned> when
+ // m_readType is not set to ReadByClient.
+ long long bytesLoaded() const { return m_bytesLoaded; }
+
+ // Before didReceiveResponse() is called: Returns -1.
+ // After didReceiveResponse() is called:
+ // - If the size of the resource is known (from
+ // m_response.expectedContentLength() or once didFinishLoading() is
+ // called), returns it.
+ // - Otherwise, returns -1.
+ long long totalBytes() const { return m_totalBytes; }
+
FileError::ErrorCode errorCode() const { return m_errorCode; }
void setEncoding(const String&);
void setDataType(const String& dataType) { m_dataType = dataType; }
private:
- // We have start() methods for Blob and Stream instead of exposing this
- // method so that users don't misuse this by calling with non Blob/Stream
- // URL.
- void startForURL(ScriptExecutionContext*, const KURL&);
+ void startInternal(ExecutionContext*, const Stream*, PassRefPtr<BlobDataHandle>);
void terminate();
void cleanup();
+
void failed(FileError::ErrorCode);
void convertToText();
void convertToDataURL();
- bool isCompleted() const;
-
static FileError::ErrorCode httpStatusCodeToErrorCode(int);
ReadType m_readType;
@@ -105,18 +118,22 @@ private:
bool m_urlForReadingIsStream;
RefPtr<ThreadableLoader> m_loader;
- RefPtr<ArrayBuffer> m_rawData;
+ OwnPtr<ArrayBufferBuilder> m_rawData;
bool m_isRawDataConverted;
String m_stringResult;
- RefPtr<Blob> m_blobResult;
// The decoder used to decode the text data.
- RefPtr<TextResourceDecoder> m_decoder;
-
- bool m_variableLength;
- unsigned m_bytesLoaded;
- unsigned m_totalBytes;
+ OwnPtr<TextResourceDecoder> m_decoder;
+
+ bool m_finishedLoading;
+ long long m_bytesLoaded;
+ // If the total size of the resource is unknown, m_totalBytes is set to -1
+ // until completion of loading, and the buffer for receiving data is set to
+ // dynamically grow. Otherwise, m_totalBytes is set to the total size and
+ // the buffer for receiving data of m_totalBytes is allocated and never grow
+ // even when extra data is appeneded.
+ long long m_totalBytes;
bool m_hasRange;
unsigned m_rangeStart;
diff --git a/chromium/third_party/WebKit/Source/core/fileapi/FileReaderSync.cpp b/chromium/third_party/WebKit/Source/core/fileapi/FileReaderSync.cpp
index 9fc6dd5d997..cbef4c1608e 100644
--- a/chromium/third_party/WebKit/Source/core/fileapi/FileReaderSync.cpp
+++ b/chromium/third_party/WebKit/Source/core/fileapi/FileReaderSync.cpp
@@ -46,62 +46,62 @@ FileReaderSync::FileReaderSync()
ScriptWrappable::init(this);
}
-PassRefPtr<ArrayBuffer> FileReaderSync::readAsArrayBuffer(ScriptExecutionContext* scriptExecutionContext, Blob* blob, ExceptionState& es)
+PassRefPtr<ArrayBuffer> FileReaderSync::readAsArrayBuffer(ExecutionContext* executionContext, Blob* blob, ExceptionState& exceptionState)
{
if (!blob) {
- es.throwDOMException(NotFoundError, FileError::notFoundErrorMessage);
+ exceptionState.throwDOMException(NotFoundError, FileError::notFoundErrorMessage);
return 0;
}
FileReaderLoader loader(FileReaderLoader::ReadAsArrayBuffer, 0);
- startLoading(scriptExecutionContext, loader, *blob, es);
+ startLoading(executionContext, loader, *blob, exceptionState);
return loader.arrayBufferResult();
}
-String FileReaderSync::readAsBinaryString(ScriptExecutionContext* scriptExecutionContext, Blob* blob, ExceptionState& es)
+String FileReaderSync::readAsBinaryString(ExecutionContext* executionContext, Blob* blob, ExceptionState& exceptionState)
{
if (!blob) {
- es.throwDOMException(NotFoundError, FileError::notFoundErrorMessage);
+ exceptionState.throwDOMException(NotFoundError, FileError::notFoundErrorMessage);
return String();
}
FileReaderLoader loader(FileReaderLoader::ReadAsBinaryString, 0);
- startLoading(scriptExecutionContext, loader, *blob, es);
+ startLoading(executionContext, loader, *blob, exceptionState);
return loader.stringResult();
}
-String FileReaderSync::readAsText(ScriptExecutionContext* scriptExecutionContext, Blob* blob, const String& encoding, ExceptionState& es)
+String FileReaderSync::readAsText(ExecutionContext* executionContext, Blob* blob, const String& encoding, ExceptionState& exceptionState)
{
if (!blob) {
- es.throwDOMException(NotFoundError, FileError::notFoundErrorMessage);
+ exceptionState.throwDOMException(NotFoundError, FileError::notFoundErrorMessage);
return String();
}
FileReaderLoader loader(FileReaderLoader::ReadAsText, 0);
loader.setEncoding(encoding);
- startLoading(scriptExecutionContext, loader, *blob, es);
+ startLoading(executionContext, loader, *blob, exceptionState);
return loader.stringResult();
}
-String FileReaderSync::readAsDataURL(ScriptExecutionContext* scriptExecutionContext, Blob* blob, ExceptionState& es)
+String FileReaderSync::readAsDataURL(ExecutionContext* executionContext, Blob* blob, ExceptionState& exceptionState)
{
if (!blob) {
- es.throwDOMException(NotFoundError, FileError::notFoundErrorMessage);
+ exceptionState.throwDOMException(NotFoundError, FileError::notFoundErrorMessage);
return String();
}
FileReaderLoader loader(FileReaderLoader::ReadAsDataURL, 0);
loader.setDataType(blob->type());
- startLoading(scriptExecutionContext, loader, *blob, es);
+ startLoading(executionContext, loader, *blob, exceptionState);
return loader.stringResult();
}
-void FileReaderSync::startLoading(ScriptExecutionContext* scriptExecutionContext, FileReaderLoader& loader, const Blob& blob, ExceptionState& es)
+void FileReaderSync::startLoading(ExecutionContext* executionContext, FileReaderLoader& loader, const Blob& blob, ExceptionState& exceptionState)
{
- loader.start(scriptExecutionContext, blob);
+ loader.start(executionContext, blob.blobDataHandle());
if (loader.errorCode())
- FileError::throwDOMException(es, loader.errorCode());
+ FileError::throwDOMException(exceptionState, loader.errorCode());
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/fileapi/FileReaderSync.h b/chromium/third_party/WebKit/Source/core/fileapi/FileReaderSync.h
index 122fb75af8b..060633e738d 100644
--- a/chromium/third_party/WebKit/Source/core/fileapi/FileReaderSync.h
+++ b/chromium/third_party/WebKit/Source/core/fileapi/FileReaderSync.h
@@ -41,7 +41,7 @@ namespace WebCore {
class Blob;
class ExceptionState;
class FileReaderLoader;
-class ScriptExecutionContext;
+class ExecutionContext;
class FileReaderSync : public RefCounted<FileReaderSync>, public ScriptWrappable {
public:
@@ -52,19 +52,19 @@ public:
virtual ~FileReaderSync() { }
- PassRefPtr<ArrayBuffer> readAsArrayBuffer(ScriptExecutionContext*, Blob*, ExceptionState&);
- String readAsBinaryString(ScriptExecutionContext*, Blob*, ExceptionState&);
- String readAsText(ScriptExecutionContext* scriptExecutionContext, Blob* blob, ExceptionState& ec)
+ PassRefPtr<ArrayBuffer> readAsArrayBuffer(ExecutionContext*, Blob*, ExceptionState&);
+ String readAsBinaryString(ExecutionContext*, Blob*, ExceptionState&);
+ String readAsText(ExecutionContext* executionContext, Blob* blob, ExceptionState& ec)
{
- return readAsText(scriptExecutionContext, blob, "", ec);
+ return readAsText(executionContext, blob, "", ec);
}
- String readAsText(ScriptExecutionContext*, Blob*, const String& encoding, ExceptionState&);
- String readAsDataURL(ScriptExecutionContext*, Blob*, ExceptionState&);
+ String readAsText(ExecutionContext*, Blob*, const String& encoding, ExceptionState&);
+ String readAsDataURL(ExecutionContext*, Blob*, ExceptionState&);
private:
FileReaderSync();
- void startLoading(ScriptExecutionContext*, FileReaderLoader&, const Blob&, ExceptionState&);
+ void startLoading(ExecutionContext*, FileReaderLoader&, const Blob&, ExceptionState&);
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/fileapi/FileReaderSync.idl b/chromium/third_party/WebKit/Source/core/fileapi/FileReaderSync.idl
index 493068708d6..125e002cbd0 100644
--- a/chromium/third_party/WebKit/Source/core/fileapi/FileReaderSync.idl
+++ b/chromium/third_party/WebKit/Source/core/fileapi/FileReaderSync.idl
@@ -32,8 +32,8 @@
GlobalContext=WorkerGlobalScope,
Constructor
] interface FileReaderSync {
- [CallWith=ScriptExecutionContext, RaisesException] ArrayBuffer readAsArrayBuffer(Blob blob);
- [CallWith=ScriptExecutionContext, RaisesException] DOMString readAsBinaryString(Blob blob);
- [CallWith=ScriptExecutionContext, RaisesException] DOMString readAsText(Blob blob, optional DOMString encoding);
- [CallWith=ScriptExecutionContext, RaisesException] DOMString readAsDataURL(Blob blob);
+ [CallWith=ExecutionContext, RaisesException] ArrayBuffer readAsArrayBuffer(Blob blob);
+ [CallWith=ExecutionContext, RaisesException] DOMString readAsBinaryString(Blob blob);
+ [CallWith=ExecutionContext, RaisesException] DOMString readAsText(Blob blob, optional DOMString encoding);
+ [CallWith=ExecutionContext, RaisesException] DOMString readAsDataURL(Blob blob);
};
diff --git a/chromium/third_party/WebKit/Source/core/fileapi/Stream.cpp b/chromium/third_party/WebKit/Source/core/fileapi/Stream.cpp
index da28e23a534..6cf822f755a 100644
--- a/chromium/third_party/WebKit/Source/core/fileapi/Stream.cpp
+++ b/chromium/third_party/WebKit/Source/core/fileapi/Stream.cpp
@@ -31,21 +31,22 @@
#include "config.h"
#include "core/fileapi/Stream.h"
-#include "core/fileapi/BlobRegistry.h"
-#include "core/fileapi/BlobURL.h"
-#include "core/platform/network/BlobData.h"
+#include "platform/blob/BlobData.h"
+#include "platform/blob/BlobRegistry.h"
+#include "platform/blob/BlobURL.h"
namespace WebCore {
-Stream::Stream(const String& mediaType)
- : m_mediaType(mediaType)
+Stream::Stream(ExecutionContext* context, const String& mediaType)
+ : ActiveDOMObject(context)
+ , m_mediaType(mediaType)
, m_isNeutered(false)
{
ScriptWrappable::init(this);
// Create a new internal URL for a stream and register it with the provided
// media type.
- m_internalURL = BlobURL::createInternalURL();
+ m_internalURL = BlobURL::createInternalStreamURL();
BlobRegistry::registerStreamURL(m_internalURL, m_mediaType);
}
@@ -72,4 +73,18 @@ Stream::~Stream()
BlobRegistry::unregisterStreamURL(m_internalURL);
}
+void Stream::suspend()
+{
+}
+
+void Stream::resume()
+{
+}
+
+void Stream::stop()
+{
+ neuter();
+ abort();
+}
+
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/fileapi/Stream.h b/chromium/third_party/WebKit/Source/core/fileapi/Stream.h
index d80cc2403cb..3e9b3e04984 100644
--- a/chromium/third_party/WebKit/Source/core/fileapi/Stream.h
+++ b/chromium/third_party/WebKit/Source/core/fileapi/Stream.h
@@ -32,18 +32,23 @@
#define Stream_h
#include "bindings/v8/ScriptWrappable.h"
-#include "weborigin/KURL.h"
+#include "core/dom/ActiveDOMObject.h"
+#include "platform/weborigin/KURL.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefCounted.h"
#include "wtf/text/WTFString.h"
namespace WebCore {
-class Stream : public ScriptWrappable, public RefCounted<Stream> {
+class ExecutionContext;
+
+class Stream : public ScriptWrappable, public ActiveDOMObject, public RefCounted<Stream> {
public:
- static PassRefPtr<Stream> create(const String& mediaType)
+ static PassRefPtr<Stream> create(ExecutionContext* context, const String& mediaType)
{
- return adoptRef(new Stream(mediaType));
+ RefPtr<Stream> stream = adoptRef(new Stream(context, mediaType));
+ stream->suspendIfNeeded();
+ return stream.release();
}
virtual ~Stream();
@@ -68,8 +73,15 @@ public:
void neuter() { m_isNeutered = true; }
bool isNeutered() const { return m_isNeutered; }
+ // Implementation of ActiveDOMObject.
+ //
+ // FIXME: Implement suspend() and resume() when necessary.
+ virtual void suspend() OVERRIDE;
+ virtual void resume() OVERRIDE;
+ virtual void stop() OVERRIDE;
+
protected:
- explicit Stream(const String& mediaType);
+ Stream(ExecutionContext*, const String& mediaType);
// This is an internal URL referring to the blob data associated with this object. It serves
// as an identifier for this blob. The internal URL is never used to source the blob's content
diff --git a/chromium/third_party/WebKit/Source/core/fileapi/Stream.idl b/chromium/third_party/WebKit/Source/core/fileapi/Stream.idl
index 6ead7574693..1406b7bbde8 100644
--- a/chromium/third_party/WebKit/Source/core/fileapi/Stream.idl
+++ b/chromium/third_party/WebKit/Source/core/fileapi/Stream.idl
@@ -37,7 +37,8 @@
// FIXME: Make the Blob a subclass of the Stream.
[
- EnabledAtRuntime=Stream
+ RuntimeEnabled=Stream,
+ ActiveDOMObject
] interface Stream {
readonly attribute DOMString type;
};
diff --git a/chromium/third_party/WebKit/Source/core/page/AdjustViewSizeOrNot.h b/chromium/third_party/WebKit/Source/core/frame/AdjustViewSizeOrNot.h
index 0137ad9102c..0137ad9102c 100644
--- a/chromium/third_party/WebKit/Source/core/page/AdjustViewSizeOrNot.h
+++ b/chromium/third_party/WebKit/Source/core/frame/AdjustViewSizeOrNot.h
diff --git a/chromium/third_party/WebKit/Source/core/frame/BarProp.cpp b/chromium/third_party/WebKit/Source/core/frame/BarProp.cpp
new file mode 100644
index 00000000000..cc987187cd7
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/BarProp.cpp
@@ -0,0 +1,75 @@
+/*
+ * Copyright (C) 2007, 2010 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/frame/BarProp.h"
+
+#include "core/page/Chrome.h"
+#include "core/frame/Frame.h"
+#include "core/page/Page.h"
+
+namespace WebCore {
+
+BarProp::BarProp(Frame* frame, Type type)
+ : DOMWindowProperty(frame)
+ , m_type(type)
+{
+ ScriptWrappable::init(this);
+}
+
+BarProp::Type BarProp::type() const
+{
+ return m_type;
+}
+
+bool BarProp::visible() const
+{
+ if (!m_frame)
+ return false;
+ Page* page = m_frame->page();
+ if (!page)
+ return false;
+
+ switch (m_type) {
+ case Locationbar:
+ case Personalbar:
+ case Toolbar:
+ return page->chrome().toolbarsVisible();
+ case Menubar:
+ return page->chrome().menubarVisible();
+ case Scrollbars:
+ return page->chrome().scrollbarsVisible();
+ case Statusbar:
+ return page->chrome().statusbarVisible();
+ }
+
+ ASSERT_NOT_REACHED();
+ return false;
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/frame/BarProp.h b/chromium/third_party/WebKit/Source/core/frame/BarProp.h
new file mode 100644
index 00000000000..1d188e14a84
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/BarProp.h
@@ -0,0 +1,57 @@
+/*
+ * Copyright (C) 2007 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef BarProp_h
+#define BarProp_h
+
+#include "bindings/v8/ScriptWrappable.h"
+#include "core/frame/DOMWindowProperty.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefCounted.h"
+
+namespace WebCore {
+
+ class Frame;
+
+ class BarProp : public ScriptWrappable, public RefCounted<BarProp>, public DOMWindowProperty {
+ public:
+ enum Type { Locationbar, Menubar, Personalbar, Scrollbars, Statusbar, Toolbar };
+
+ static PassRefPtr<BarProp> create(Frame* frame, Type type) { return adoptRef(new BarProp(frame, type)); }
+
+ Type type() const;
+ bool visible() const;
+
+ private:
+ BarProp(Frame*, Type);
+ Type m_type;
+ };
+
+} // namespace WebCore
+
+#endif // BarProp_h
diff --git a/chromium/third_party/WebKit/Source/core/page/BarProp.idl b/chromium/third_party/WebKit/Source/core/frame/BarProp.idl
index cc9ce71cedf..cc9ce71cedf 100644
--- a/chromium/third_party/WebKit/Source/core/page/BarProp.idl
+++ b/chromium/third_party/WebKit/Source/core/frame/BarProp.idl
diff --git a/chromium/third_party/WebKit/Source/core/frame/Console.cpp b/chromium/third_party/WebKit/Source/core/frame/Console.cpp
new file mode 100644
index 00000000000..12cff31d383
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/Console.cpp
@@ -0,0 +1,87 @@
+/*
+ * Copyright (C) 2007 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/frame/Console.h"
+
+#include "bindings/v8/ScriptCallStackFactory.h"
+#include "core/frame/ConsoleTypes.h"
+#include "core/inspector/ConsoleAPITypes.h"
+#include "core/inspector/ScriptArguments.h"
+#include "core/inspector/ScriptCallStack.h"
+#include "core/page/Chrome.h"
+#include "core/page/ChromeClient.h"
+#include "core/frame/Frame.h"
+#include "core/page/Page.h"
+#include "core/page/PageConsole.h"
+#include "core/timing/MemoryInfo.h"
+#include "wtf/text/CString.h"
+#include "wtf/text/WTFString.h"
+
+#include "platform/TraceEvent.h"
+
+namespace WebCore {
+
+Console::Console(Frame* frame)
+ : DOMWindowProperty(frame)
+{
+ ScriptWrappable::init(this);
+}
+
+Console::~Console()
+{
+}
+
+ExecutionContext* Console::context()
+{
+ if (!m_frame)
+ return 0;
+ return m_frame->document();
+}
+
+void Console::reportMessageToClient(MessageLevel level, const String& message, PassRefPtr<ScriptCallStack> callStack)
+{
+ if (!m_frame || !m_frame->page() || !callStack.get())
+ return;
+
+ String stackTrace;
+ if (m_frame->page()->chrome().client().shouldReportDetailedMessageForSource(callStack->at(0).sourceURL())) {
+ RefPtr<ScriptCallStack> fullStack = createScriptCallStack(ScriptCallStack::maxCallStackSizeToCapture);
+ stackTrace = PageConsole::formatStackTraceString(message, fullStack);
+ }
+ m_frame->page()->chrome().client().addMessageToConsole(ConsoleAPIMessageSource, level, message, callStack->at(0).lineNumber(), callStack->at(0).sourceURL(), stackTrace);
+}
+
+PassRefPtr<MemoryInfo> Console::memory() const
+{
+ // FIXME: Because we create a new object here each time,
+ // console.memory !== console.memory, which seems wrong.
+ return MemoryInfo::create(m_frame);
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/frame/Console.h b/chromium/third_party/WebKit/Source/core/frame/Console.h
new file mode 100644
index 00000000000..0cdfffdc5e3
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/Console.h
@@ -0,0 +1,71 @@
+/*
+ * Copyright (C) 2007 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef Console_h
+#define Console_h
+
+#include "bindings/v8/ScriptState.h"
+#include "bindings/v8/ScriptWrappable.h"
+#include "core/frame/ConsoleBase.h"
+#include "core/frame/DOMWindowProperty.h"
+#include "wtf/Forward.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefCounted.h"
+
+namespace WebCore {
+
+class Frame;
+class MemoryInfo;
+class Page;
+class ScriptArguments;
+
+class Console : public RefCounted<Console>, public ConsoleBase, public ScriptWrappable, public DOMWindowProperty {
+public:
+ using RefCounted<Console>::ref;
+ using RefCounted<Console>::deref;
+
+ static PassRefPtr<Console> create(Frame* frame) { return adoptRef(new Console(frame)); }
+ virtual ~Console();
+
+ PassRefPtr<MemoryInfo> memory() const;
+
+protected:
+ virtual ExecutionContext* context();
+ virtual void reportMessageToClient(MessageLevel, const String& message, PassRefPtr<ScriptCallStack>) OVERRIDE;
+
+private:
+ explicit Console(Frame*);
+ inline Page* page() const;
+
+ virtual void refConsole() { ref(); }
+ virtual void derefConsole() { deref(); }
+};
+
+} // namespace WebCore
+
+#endif // Console_h
diff --git a/chromium/third_party/WebKit/Source/core/page/Console.idl b/chromium/third_party/WebKit/Source/core/frame/Console.idl
index de3bc19a1a4..de3bc19a1a4 100644
--- a/chromium/third_party/WebKit/Source/core/page/Console.idl
+++ b/chromium/third_party/WebKit/Source/core/frame/Console.idl
diff --git a/chromium/third_party/WebKit/Source/core/frame/ConsoleBase.cpp b/chromium/third_party/WebKit/Source/core/frame/ConsoleBase.cpp
new file mode 100644
index 00000000000..8f54d86c0d1
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/ConsoleBase.cpp
@@ -0,0 +1,185 @@
+/*
+ * Copyright (C) 2007 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/frame/Console.h"
+
+#include "bindings/v8/ScriptCallStackFactory.h"
+#include "core/dom/Document.h"
+#include "core/inspector/InspectorConsoleInstrumentation.h"
+#include "core/inspector/ScriptArguments.h"
+#include "platform/TraceEvent.h"
+#include "wtf/text/CString.h"
+#include "wtf/text/WTFString.h"
+
+namespace WebCore {
+
+ConsoleBase::~ConsoleBase()
+{
+}
+
+void ConsoleBase::debug(ScriptState* state, PassRefPtr<ScriptArguments> arguments)
+{
+ internalAddMessage(LogMessageType, DebugMessageLevel, state, arguments);
+}
+
+void ConsoleBase::error(ScriptState* state, PassRefPtr<ScriptArguments> arguments)
+{
+ internalAddMessage(LogMessageType, ErrorMessageLevel, state, arguments);
+}
+
+void ConsoleBase::info(ScriptState* state, PassRefPtr<ScriptArguments> arguments)
+{
+ internalAddMessage(LogMessageType, InfoMessageLevel, state, arguments);
+}
+
+void ConsoleBase::log(ScriptState* state, PassRefPtr<ScriptArguments> arguments)
+{
+ internalAddMessage(LogMessageType, LogMessageLevel, state, arguments);
+}
+
+void ConsoleBase::warn(ScriptState* state, PassRefPtr<ScriptArguments> arguments)
+{
+ internalAddMessage(LogMessageType, WarningMessageLevel, state, arguments);
+}
+
+void ConsoleBase::dir(ScriptState* state, PassRefPtr<ScriptArguments> arguments)
+{
+ internalAddMessage(DirMessageType, LogMessageLevel, state, arguments);
+}
+
+void ConsoleBase::dirxml(ScriptState* state, PassRefPtr<ScriptArguments> arguments)
+{
+ internalAddMessage(DirXMLMessageType, LogMessageLevel, state, arguments);
+}
+
+void ConsoleBase::table(ScriptState* state, PassRefPtr<ScriptArguments> arguments)
+{
+ internalAddMessage(TableMessageType, LogMessageLevel, state, arguments);
+}
+
+void ConsoleBase::clear(ScriptState* state, PassRefPtr<ScriptArguments> arguments)
+{
+ InspectorInstrumentation::addMessageToConsole(context(), ConsoleAPIMessageSource, ClearMessageType, LogMessageLevel, String(), state, arguments);
+}
+
+void ConsoleBase::trace(ScriptState* state, PassRefPtr<ScriptArguments> arguments)
+{
+ internalAddMessage(TraceMessageType, LogMessageLevel, state, arguments, true, true);
+}
+
+void ConsoleBase::assertCondition(ScriptState* state, PassRefPtr<ScriptArguments> arguments, bool condition)
+{
+ if (condition)
+ return;
+
+ internalAddMessage(AssertMessageType, ErrorMessageLevel, state, arguments, true);
+}
+
+void ConsoleBase::count(ScriptState* state, PassRefPtr<ScriptArguments> arguments)
+{
+ InspectorInstrumentation::consoleCount(context(), state, arguments);
+}
+
+void ConsoleBase::markTimeline(const String& title)
+{
+ InspectorInstrumentation::consoleTimeStamp(context(), title);
+}
+
+void ConsoleBase::profile(ScriptState* state, const String& title)
+{
+ InspectorInstrumentation::consoleProfile(context(), title, state);
+}
+
+void ConsoleBase::profileEnd(ScriptState* state, const String& title)
+{
+ InspectorInstrumentation::consoleProfileEnd(context(), title);
+}
+
+void ConsoleBase::time(const String& title)
+{
+ InspectorInstrumentation::consoleTime(context(), title);
+ TRACE_EVENT_COPY_ASYNC_BEGIN0("webkit.console", title.utf8().data(), this);
+}
+
+void ConsoleBase::timeEnd(ScriptState* state, const String& title)
+{
+ TRACE_EVENT_COPY_ASYNC_END0("webkit.console", title.utf8().data(), this);
+ InspectorInstrumentation::consoleTimeEnd(context(), title, state);
+}
+
+void ConsoleBase::timeStamp(const String& title)
+{
+ InspectorInstrumentation::consoleTimeStamp(context(), title);
+}
+
+void ConsoleBase::timeline(ScriptState* state, const String& title)
+{
+ InspectorInstrumentation::consoleTimeline(context(), title, state);
+}
+
+void ConsoleBase::timelineEnd(ScriptState* state, const String& title)
+{
+ InspectorInstrumentation::consoleTimelineEnd(context(), title, state);
+}
+
+void ConsoleBase::group(ScriptState* state, PassRefPtr<ScriptArguments> arguments)
+{
+ InspectorInstrumentation::addMessageToConsole(context(), ConsoleAPIMessageSource, StartGroupMessageType, LogMessageLevel, String(), state, arguments);
+}
+
+void ConsoleBase::groupCollapsed(ScriptState* state, PassRefPtr<ScriptArguments> arguments)
+{
+ InspectorInstrumentation::addMessageToConsole(context(), ConsoleAPIMessageSource, StartGroupCollapsedMessageType, LogMessageLevel, String(), state, arguments);
+}
+
+void ConsoleBase::groupEnd()
+{
+ InspectorInstrumentation::addMessageToConsole(context(), ConsoleAPIMessageSource, EndGroupMessageType, LogMessageLevel, String(), 0);
+}
+
+void ConsoleBase::internalAddMessage(MessageType type, MessageLevel level, ScriptState* state, PassRefPtr<ScriptArguments> scriptArguments, bool acceptNoArguments, bool printTrace)
+{
+ if (!context())
+ return;
+
+ RefPtr<ScriptArguments> arguments = scriptArguments;
+ if (!acceptNoArguments && !arguments->argumentCount())
+ return;
+
+ size_t stackSize = printTrace ? ScriptCallStack::maxCallStackSizeToCapture : 1;
+ RefPtr<ScriptCallStack> callStack(createScriptCallStackForConsole(stackSize));
+
+ String message;
+ bool gotStringMessage = arguments->getFirstArgumentAsString(message);
+ InspectorInstrumentation::addMessageToConsole(context(), ConsoleAPIMessageSource, type, level, message, state, arguments);
+ if (gotStringMessage)
+ reportMessageToClient(level, message, callStack);
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/frame/ConsoleBase.h b/chromium/third_party/WebKit/Source/core/frame/ConsoleBase.h
new file mode 100644
index 00000000000..30858d02731
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/ConsoleBase.h
@@ -0,0 +1,90 @@
+/*
+ * Copyright (C) 2007 Apple Inc. All rights reserved.
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef ConsoleBase_h
+#define ConsoleBase_h
+
+#include "bindings/v8/ScriptState.h"
+#include "bindings/v8/ScriptWrappable.h"
+#include "core/inspector/ConsoleAPITypes.h"
+#include "core/inspector/ScriptCallStack.h"
+#include "core/frame/ConsoleTypes.h"
+#include "core/frame/DOMWindowProperty.h"
+#include "wtf/Forward.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefCounted.h"
+
+namespace WebCore {
+
+class ScriptArguments;
+
+class ConsoleBase {
+public:
+ void ref() { refConsole(); }
+ void deref() { derefConsole(); }
+
+ void debug(ScriptState*, PassRefPtr<ScriptArguments>);
+ void error(ScriptState*, PassRefPtr<ScriptArguments>);
+ void info(ScriptState*, PassRefPtr<ScriptArguments>);
+ void log(ScriptState*, PassRefPtr<ScriptArguments>);
+ void clear(ScriptState*, PassRefPtr<ScriptArguments>);
+ void warn(ScriptState*, PassRefPtr<ScriptArguments>);
+ void dir(ScriptState*, PassRefPtr<ScriptArguments>);
+ void dirxml(ScriptState*, PassRefPtr<ScriptArguments>);
+ void table(ScriptState*, PassRefPtr<ScriptArguments>);
+ void trace(ScriptState*, PassRefPtr<ScriptArguments>);
+ void assertCondition(ScriptState*, PassRefPtr<ScriptArguments>, bool condition);
+ void count(ScriptState*, PassRefPtr<ScriptArguments>);
+ void markTimeline(const String&);
+ void profile(ScriptState*, const String&);
+ void profileEnd(ScriptState*, const String&);
+ void time(const String&);
+ void timeEnd(ScriptState*, const String&);
+ void timeStamp(const String&);
+ void timeline(ScriptState*, const String&);
+ void timelineEnd(ScriptState*, const String&);
+ void group(ScriptState*, PassRefPtr<ScriptArguments>);
+ void groupCollapsed(ScriptState*, PassRefPtr<ScriptArguments>);
+ void groupEnd();
+
+protected:
+ virtual ~ConsoleBase();
+ virtual ExecutionContext* context() = 0;
+ virtual void reportMessageToClient(MessageLevel, const String& message, PassRefPtr<ScriptCallStack>) = 0;
+
+private:
+ virtual void refConsole() = 0;
+ virtual void derefConsole() = 0;
+
+ void internalAddMessage(MessageType, MessageLevel, ScriptState*, PassRefPtr<ScriptArguments>, bool acceptNoArguments = false, bool printTrace = false);
+};
+
+} // namespace WebCore
+
+#endif // ConsoleBase_h
diff --git a/chromium/third_party/WebKit/Source/core/frame/ConsoleBase.idl b/chromium/third_party/WebKit/Source/core/frame/ConsoleBase.idl
new file mode 100644
index 00000000000..b63a7f5aca2
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/ConsoleBase.idl
@@ -0,0 +1,60 @@
+/*
+ * Copyright (C) 2007, 2008 Apple Inc. All rights reserved.
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+[
+ NoInterfaceObject,
+] interface ConsoleBase {
+ [CallWith=ScriptArguments&ScriptState] void debug();
+ [CallWith=ScriptArguments&ScriptState] void error();
+ [CallWith=ScriptArguments&ScriptState] void info();
+ [CallWith=ScriptArguments&ScriptState] void log();
+ [CallWith=ScriptArguments&ScriptState] void warn();
+ [CallWith=ScriptArguments&ScriptState] void dir();
+ [CallWith=ScriptArguments&ScriptState] void dirxml();
+ [CallWith=ScriptArguments&ScriptState] void table();
+ [CallWith=ScriptArguments&ScriptState] void trace();
+ [CallWith=ScriptArguments&ScriptState, ImplementedAs=assertCondition] void assert([Default=Undefined] optional boolean condition);
+ [CallWith=ScriptArguments&ScriptState] void count();
+ [DeprecateAs=ConsoleMarkTimeline] void markTimeline([Default=NullString] optional DOMString title);
+
+ [CallWith=ScriptState] void profile([Default=NullString] optional DOMString title);
+ [CallWith=ScriptState] void profileEnd([Default=NullString] optional DOMString title);
+
+ void time([Default=NullString] optional DOMString title);
+ [CallWith=ScriptState] void timeEnd([Default=NullString] optional DOMString title);
+ void timeStamp([Default=NullString] optional DOMString title);
+
+ [CallWith=ScriptState] void timeline([Default=NullString] optional DOMString title);
+ [CallWith=ScriptState] void timelineEnd([Default=NullString] optional DOMString title);
+
+ [CallWith=ScriptArguments&ScriptState] void group();
+ [CallWith=ScriptArguments&ScriptState] void groupCollapsed();
+ void groupEnd();
+ [CallWith=ScriptArguments&ScriptState] void clear();
+};
diff --git a/chromium/third_party/WebKit/Source/core/frame/ConsoleTypes.h b/chromium/third_party/WebKit/Source/core/frame/ConsoleTypes.h
new file mode 100644
index 00000000000..d37949bb7f7
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/ConsoleTypes.h
@@ -0,0 +1,55 @@
+/*
+ * Copyright (C) 2011 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef ConsoleTypes_h
+#define ConsoleTypes_h
+
+namespace WebCore {
+
+enum MessageSource {
+ XMLMessageSource,
+ JSMessageSource,
+ NetworkMessageSource,
+ ConsoleAPIMessageSource,
+ StorageMessageSource,
+ AppCacheMessageSource,
+ RenderingMessageSource,
+ CSSMessageSource,
+ SecurityMessageSource,
+ OtherMessageSource,
+ DeprecationMessageSource,
+};
+
+enum MessageLevel {
+ DebugMessageLevel = 4,
+ LogMessageLevel = 1,
+ InfoMessageLevel = 5,
+ WarningMessageLevel = 2,
+ ErrorMessageLevel = 3
+};
+
+} // namespace WebCore
+
+#endif // ConsoleTypes_h
diff --git a/chromium/third_party/WebKit/Source/core/frame/ContentSecurityPolicy.cpp b/chromium/third_party/WebKit/Source/core/frame/ContentSecurityPolicy.cpp
new file mode 100644
index 00000000000..4c3cbe42472
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/ContentSecurityPolicy.cpp
@@ -0,0 +1,2032 @@
+/*
+ * Copyright (C) 2011 Google, Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY GOOGLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/frame/ContentSecurityPolicy.h"
+
+#include "RuntimeEnabledFeatures.h"
+#include "bindings/v8/ScriptCallStackFactory.h"
+#include "bindings/v8/ScriptController.h"
+#include "core/dom/DOMStringList.h"
+#include "core/dom/Document.h"
+#include "core/events/SecurityPolicyViolationEvent.h"
+#include "core/frame/ContentSecurityPolicyResponseHeaders.h"
+#include "core/frame/DOMWindow.h"
+#include "core/frame/Frame.h"
+#include "core/inspector/InspectorInstrumentation.h"
+#include "core/inspector/ScriptCallStack.h"
+#include "core/loader/DocumentLoader.h"
+#include "core/loader/PingLoader.h"
+#include "core/frame/UseCounter.h"
+#include "platform/JSONValues.h"
+#include "platform/NotImplemented.h"
+#include "platform/ParsingUtilities.h"
+#include "platform/network/FormData.h"
+#include "platform/network/ResourceResponse.h"
+#include "platform/weborigin/KURL.h"
+#include "platform/weborigin/KnownPorts.h"
+#include "platform/weborigin/SchemeRegistry.h"
+#include "platform/weborigin/SecurityOrigin.h"
+#include "wtf/SHA1.h"
+#include "wtf/StringHasher.h"
+#include "wtf/text/Base64.h"
+#include "wtf/text/StringBuilder.h"
+
+namespace WTF {
+
+struct VectorIntHash {
+ static unsigned hash(const Vector<uint8_t>& v) { return StringHasher::computeHash(v.data(), v.size()); }
+ static bool equal(const Vector<uint8_t>& a, const Vector<uint8_t>& b) { return a == b; };
+ static const bool safeToCompareToEmptyOrDeleted = true;
+};
+template<> struct DefaultHash<Vector<uint8_t> > {
+ typedef VectorIntHash Hash;
+};
+
+} // namespace WTF
+
+namespace WebCore {
+
+typedef std::pair<unsigned, Vector<uint8_t> > SourceHashValue;
+
+// Normally WebKit uses "static" for internal linkage, but using "static" for
+// these functions causes a compile error because these functions are used as
+// template parameters.
+namespace {
+
+bool isDirectiveNameCharacter(UChar c)
+{
+ return isASCIIAlphanumeric(c) || c == '-';
+}
+
+bool isDirectiveValueCharacter(UChar c)
+{
+ return isASCIISpace(c) || (c >= 0x21 && c <= 0x7e); // Whitespace + VCHAR
+}
+
+// Only checks for general Base64 encoded chars, not '=' chars since '=' is
+// positional and may only appear at the end of a Base64 encoded string.
+bool isBase64EncodedCharacter(UChar c)
+{
+ return isASCIIAlphanumeric(c) || c == '+' || c == '/';
+}
+
+bool isNonceCharacter(UChar c)
+{
+ return isBase64EncodedCharacter(c) || c == '=';
+}
+
+bool isSourceCharacter(UChar c)
+{
+ return !isASCIISpace(c);
+}
+
+bool isPathComponentCharacter(UChar c)
+{
+ return c != '?' && c != '#';
+}
+
+bool isHostCharacter(UChar c)
+{
+ return isASCIIAlphanumeric(c) || c == '-';
+}
+
+bool isSchemeContinuationCharacter(UChar c)
+{
+ return isASCIIAlphanumeric(c) || c == '+' || c == '-' || c == '.';
+}
+
+bool isNotASCIISpace(UChar c)
+{
+ return !isASCIISpace(c);
+}
+
+bool isNotColonOrSlash(UChar c)
+{
+ return c != ':' && c != '/';
+}
+
+bool isMediaTypeCharacter(UChar c)
+{
+ return !isASCIISpace(c) && c != '/';
+}
+
+// CSP 1.0 Directives
+static const char connectSrc[] = "connect-src";
+static const char defaultSrc[] = "default-src";
+static const char fontSrc[] = "font-src";
+static const char frameSrc[] = "frame-src";
+static const char imgSrc[] = "img-src";
+static const char mediaSrc[] = "media-src";
+static const char objectSrc[] = "object-src";
+static const char reportURI[] = "report-uri";
+static const char sandbox[] = "sandbox";
+static const char scriptSrc[] = "script-src";
+static const char styleSrc[] = "style-src";
+
+// CSP 1.1 Directives
+static const char baseURI[] = "base-uri";
+static const char formAction[] = "form-action";
+static const char pluginTypes[] = "plugin-types";
+static const char reflectedXSS[] = "reflected-xss";
+
+bool isDirectiveName(const String& name)
+{
+ return (equalIgnoringCase(name, connectSrc)
+ || equalIgnoringCase(name, defaultSrc)
+ || equalIgnoringCase(name, fontSrc)
+ || equalIgnoringCase(name, frameSrc)
+ || equalIgnoringCase(name, imgSrc)
+ || equalIgnoringCase(name, mediaSrc)
+ || equalIgnoringCase(name, objectSrc)
+ || equalIgnoringCase(name, reportURI)
+ || equalIgnoringCase(name, sandbox)
+ || equalIgnoringCase(name, scriptSrc)
+ || equalIgnoringCase(name, styleSrc)
+ || equalIgnoringCase(name, baseURI)
+ || equalIgnoringCase(name, formAction)
+ || equalIgnoringCase(name, pluginTypes)
+ || equalIgnoringCase(name, reflectedXSS)
+ );
+}
+
+UseCounter::Feature getUseCounterType(ContentSecurityPolicy::HeaderType type)
+{
+ switch (type) {
+ case ContentSecurityPolicy::Enforce:
+ return UseCounter::ContentSecurityPolicy;
+ case ContentSecurityPolicy::Report:
+ return UseCounter::ContentSecurityPolicyReportOnly;
+ }
+ ASSERT_NOT_REACHED();
+ return UseCounter::NumberOfFeatures;
+}
+
+} // namespace
+
+static bool isSourceListNone(const UChar* begin, const UChar* end)
+{
+ skipWhile<UChar, isASCIISpace>(begin, end);
+
+ const UChar* position = begin;
+ skipWhile<UChar, isSourceCharacter>(position, end);
+ if (!equalIgnoringCase("'none'", begin, position - begin))
+ return false;
+
+ skipWhile<UChar, isASCIISpace>(position, end);
+ if (position != end)
+ return false;
+
+ return true;
+}
+
+class CSPSource {
+public:
+ CSPSource(ContentSecurityPolicy* policy, const String& scheme, const String& host, int port, const String& path, bool hostHasWildcard, bool portHasWildcard)
+ : m_policy(policy)
+ , m_scheme(scheme)
+ , m_host(host)
+ , m_port(port)
+ , m_path(path)
+ , m_hostHasWildcard(hostHasWildcard)
+ , m_portHasWildcard(portHasWildcard)
+ {
+ }
+
+ bool matches(const KURL& url) const
+ {
+ if (!schemeMatches(url))
+ return false;
+ if (isSchemeOnly())
+ return true;
+ return hostMatches(url) && portMatches(url) && pathMatches(url);
+ }
+
+private:
+ bool schemeMatches(const KURL& url) const
+ {
+ if (m_scheme.isEmpty()) {
+ String protectedResourceScheme(m_policy->securityOrigin()->protocol());
+ if (equalIgnoringCase("http", protectedResourceScheme))
+ return url.protocolIs("http") || url.protocolIs("https");
+ return equalIgnoringCase(url.protocol(), protectedResourceScheme);
+ }
+ return equalIgnoringCase(url.protocol(), m_scheme);
+ }
+
+ bool hostMatches(const KURL& url) const
+ {
+ const String& host = url.host();
+ if (equalIgnoringCase(host, m_host))
+ return true;
+ return m_hostHasWildcard && host.endsWith("." + m_host, false);
+
+ }
+
+ bool pathMatches(const KURL& url) const
+ {
+ if (m_path.isEmpty())
+ return true;
+
+ String path = decodeURLEscapeSequences(url.path());
+
+ if (m_path.endsWith("/"))
+ return path.startsWith(m_path, false);
+
+ return path == m_path;
+ }
+
+ bool portMatches(const KURL& url) const
+ {
+ if (m_portHasWildcard)
+ return true;
+
+ int port = url.port();
+
+ if (port == m_port)
+ return true;
+
+ if (!port)
+ return isDefaultPortForProtocol(m_port, url.protocol());
+
+ if (!m_port)
+ return isDefaultPortForProtocol(port, url.protocol());
+
+ return false;
+ }
+
+ bool isSchemeOnly() const { return m_host.isEmpty(); }
+
+ ContentSecurityPolicy* m_policy;
+ String m_scheme;
+ String m_host;
+ int m_port;
+ String m_path;
+
+ bool m_hostHasWildcard;
+ bool m_portHasWildcard;
+};
+
+class CSPSourceList {
+public:
+ CSPSourceList(ContentSecurityPolicy*, const String& directiveName);
+
+ void parse(const UChar* begin, const UChar* end);
+
+ bool matches(const KURL&);
+ bool allowInline() const { return m_allowInline; }
+ bool allowEval() const { return m_allowEval; }
+ bool allowNonce(const String& nonce) const { return !nonce.isNull() && m_nonces.contains(nonce); }
+ bool allowHash(const SourceHashValue& hashValue) const { return m_hashes.contains(hashValue); }
+ uint8_t hashAlgorithmsUsed() const { return m_hashAlgorithmsUsed; }
+
+private:
+ bool parseSource(const UChar* begin, const UChar* end, String& scheme, String& host, int& port, String& path, bool& hostHasWildcard, bool& portHasWildcard);
+ bool parseScheme(const UChar* begin, const UChar* end, String& scheme);
+ bool parseHost(const UChar* begin, const UChar* end, String& host, bool& hostHasWildcard);
+ bool parsePort(const UChar* begin, const UChar* end, int& port, bool& portHasWildcard);
+ bool parsePath(const UChar* begin, const UChar* end, String& path);
+ bool parseNonce(const UChar* begin, const UChar* end, String& nonce);
+ bool parseHash(const UChar* begin, const UChar* end, Vector<uint8_t>& hash, ContentSecurityPolicy::HashAlgorithms&);
+
+ void addSourceSelf();
+ void addSourceStar();
+ void addSourceUnsafeInline();
+ void addSourceUnsafeEval();
+ void addSourceNonce(const String& nonce);
+ void addSourceHash(const ContentSecurityPolicy::HashAlgorithms&, const Vector<uint8_t>& hash);
+
+ ContentSecurityPolicy* m_policy;
+ Vector<CSPSource> m_list;
+ String m_directiveName;
+ bool m_allowStar;
+ bool m_allowInline;
+ bool m_allowEval;
+ HashSet<String> m_nonces;
+ HashSet<SourceHashValue> m_hashes;
+ uint8_t m_hashAlgorithmsUsed;
+};
+
+CSPSourceList::CSPSourceList(ContentSecurityPolicy* policy, const String& directiveName)
+ : m_policy(policy)
+ , m_directiveName(directiveName)
+ , m_allowStar(false)
+ , m_allowInline(false)
+ , m_allowEval(false)
+ , m_hashAlgorithmsUsed(0)
+{
+}
+
+bool CSPSourceList::matches(const KURL& url)
+{
+ if (m_allowStar)
+ return true;
+
+ KURL effectiveURL = SecurityOrigin::shouldUseInnerURL(url) ? SecurityOrigin::extractInnerURL(url) : url;
+
+ for (size_t i = 0; i < m_list.size(); ++i) {
+ if (m_list[i].matches(effectiveURL))
+ return true;
+ }
+
+ return false;
+}
+
+// source-list = *WSP [ source *( 1*WSP source ) *WSP ]
+// / *WSP "'none'" *WSP
+//
+void CSPSourceList::parse(const UChar* begin, const UChar* end)
+{
+ // We represent 'none' as an empty m_list.
+ if (isSourceListNone(begin, end))
+ return;
+
+ const UChar* position = begin;
+ while (position < end) {
+ skipWhile<UChar, isASCIISpace>(position, end);
+ if (position == end)
+ return;
+
+ const UChar* beginSource = position;
+ skipWhile<UChar, isSourceCharacter>(position, end);
+
+ String scheme, host, path;
+ int port = 0;
+ bool hostHasWildcard = false;
+ bool portHasWildcard = false;
+
+ if (parseSource(beginSource, position, scheme, host, port, path, hostHasWildcard, portHasWildcard)) {
+ // Wildcard hosts and keyword sources ('self', 'unsafe-inline',
+ // etc.) aren't stored in m_list, but as attributes on the source
+ // list itself.
+ if (scheme.isEmpty() && host.isEmpty())
+ continue;
+ if (isDirectiveName(host))
+ m_policy->reportDirectiveAsSourceExpression(m_directiveName, host);
+ m_list.append(CSPSource(m_policy, scheme, host, port, path, hostHasWildcard, portHasWildcard));
+ } else {
+ m_policy->reportInvalidSourceExpression(m_directiveName, String(beginSource, position - beginSource));
+ }
+
+ ASSERT(position == end || isASCIISpace(*position));
+ }
+}
+
+// source = scheme ":"
+// / ( [ scheme "://" ] host [ port ] [ path ] )
+// / "'self'"
+bool CSPSourceList::parseSource(const UChar* begin, const UChar* end, String& scheme, String& host, int& port, String& path, bool& hostHasWildcard, bool& portHasWildcard)
+{
+ if (begin == end)
+ return false;
+
+ if (equalIgnoringCase("'none'", begin, end - begin))
+ return false;
+
+ if (end - begin == 1 && *begin == '*') {
+ addSourceStar();
+ return true;
+ }
+
+ if (equalIgnoringCase("'self'", begin, end - begin)) {
+ addSourceSelf();
+ return true;
+ }
+
+ if (equalIgnoringCase("'unsafe-inline'", begin, end - begin)) {
+ addSourceUnsafeInline();
+ return true;
+ }
+
+ if (equalIgnoringCase("'unsafe-eval'", begin, end - begin)) {
+ addSourceUnsafeEval();
+ return true;
+ }
+
+ if (m_policy->experimentalFeaturesEnabled()) {
+ String nonce;
+ if (!parseNonce(begin, end, nonce))
+ return false;
+
+ if (!nonce.isNull()) {
+ addSourceNonce(nonce);
+ return true;
+ }
+
+ Vector<uint8_t> hash;
+ ContentSecurityPolicy::HashAlgorithms algorithm = ContentSecurityPolicy::HashAlgorithmsNone;
+ if (!parseHash(begin, end, hash, algorithm))
+ return false;
+
+ if (hash.size() > 0) {
+ addSourceHash(algorithm, hash);
+ return true;
+ }
+ }
+
+ const UChar* position = begin;
+ const UChar* beginHost = begin;
+ const UChar* beginPath = end;
+ const UChar* beginPort = 0;
+
+ skipWhile<UChar, isNotColonOrSlash>(position, end);
+
+ if (position == end) {
+ // host
+ // ^
+ return parseHost(beginHost, position, host, hostHasWildcard);
+ }
+
+ if (position < end && *position == '/') {
+ // host/path || host/ || /
+ // ^ ^ ^
+ return parseHost(beginHost, position, host, hostHasWildcard) && parsePath(position, end, path);
+ }
+
+ if (position < end && *position == ':') {
+ if (end - position == 1) {
+ // scheme:
+ // ^
+ return parseScheme(begin, position, scheme);
+ }
+
+ if (position[1] == '/') {
+ // scheme://host || scheme://
+ // ^ ^
+ if (!parseScheme(begin, position, scheme)
+ || !skipExactly<UChar>(position, end, ':')
+ || !skipExactly<UChar>(position, end, '/')
+ || !skipExactly<UChar>(position, end, '/'))
+ return false;
+ if (position == end)
+ return true;
+ beginHost = position;
+ skipWhile<UChar, isNotColonOrSlash>(position, end);
+ }
+
+ if (position < end && *position == ':') {
+ // host:port || scheme://host:port
+ // ^ ^
+ beginPort = position;
+ skipUntil<UChar>(position, end, '/');
+ }
+ }
+
+ if (position < end && *position == '/') {
+ // scheme://host/path || scheme://host:port/path
+ // ^ ^
+ if (position == beginHost)
+ return false;
+ beginPath = position;
+ }
+
+ if (!parseHost(beginHost, beginPort ? beginPort : beginPath, host, hostHasWildcard))
+ return false;
+
+ if (beginPort) {
+ if (!parsePort(beginPort, beginPath, port, portHasWildcard))
+ return false;
+ } else {
+ port = 0;
+ }
+
+ if (beginPath != end) {
+ if (!parsePath(beginPath, end, path))
+ return false;
+ }
+
+ return true;
+}
+
+// nonce-source = "'nonce-" nonce-value "'"
+// nonce-value = 1*( ALPHA / DIGIT / "+" / "/" / "=" )
+//
+bool CSPSourceList::parseNonce(const UChar* begin, const UChar* end, String& nonce)
+{
+ DEFINE_STATIC_LOCAL(const String, noncePrefix, ("'nonce-"));
+
+ if (!equalIgnoringCase(noncePrefix.characters8(), begin, noncePrefix.length()))
+ return true;
+
+ const UChar* position = begin + noncePrefix.length();
+ const UChar* nonceBegin = position;
+
+ skipWhile<UChar, isNonceCharacter>(position, end);
+ ASSERT(nonceBegin <= position);
+
+ if ((position + 1) != end || *position != '\'' || !(position - nonceBegin))
+ return false;
+
+ nonce = String(nonceBegin, position - nonceBegin);
+ return true;
+}
+
+// hash-source = "'" hash-algorithm "-" hash-value "'"
+// hash-algorithm = "sha1" / "sha256"
+// hash-value = 1*( ALPHA / DIGIT / "+" / "/" / "=" )
+//
+bool CSPSourceList::parseHash(const UChar* begin, const UChar* end, Vector<uint8_t>& hash, ContentSecurityPolicy::HashAlgorithms& hashAlgorithm)
+{
+ DEFINE_STATIC_LOCAL(const String, sha1Prefix, ("'sha1-"));
+ DEFINE_STATIC_LOCAL(const String, sha256Prefix, ("'sha256-"));
+
+ String prefix;
+ if (equalIgnoringCase(sha1Prefix.characters8(), begin, sha1Prefix.length())) {
+ prefix = sha1Prefix;
+ hashAlgorithm = ContentSecurityPolicy::HashAlgorithmsSha1;
+ } else if (equalIgnoringCase(sha256Prefix.characters8(), begin, sha256Prefix.length())) {
+ notImplemented();
+ } else {
+ return true;
+ }
+
+ const UChar* position = begin + prefix.length();
+ const UChar* hashBegin = position;
+
+ skipWhile<UChar, isBase64EncodedCharacter>(position, end);
+ ASSERT(hashBegin <= position);
+
+ // Base64 encodings may end with exactly one or two '=' characters
+ skipExactly<UChar>(position, position + 1, '=');
+ skipExactly<UChar>(position, position + 1, '=');
+
+ if ((position + 1) != end || *position != '\'' || !(position - hashBegin))
+ return false;
+
+ Vector<char> hashVector;
+ base64Decode(hashBegin, position - hashBegin, hashVector);
+ hash.append(reinterpret_cast<uint8_t*>(hashVector.data()), hashVector.size());
+ return true;
+}
+
+// ; <scheme> production from RFC 3986
+// scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
+//
+bool CSPSourceList::parseScheme(const UChar* begin, const UChar* end, String& scheme)
+{
+ ASSERT(begin <= end);
+ ASSERT(scheme.isEmpty());
+
+ if (begin == end)
+ return false;
+
+ const UChar* position = begin;
+
+ if (!skipExactly<UChar, isASCIIAlpha>(position, end))
+ return false;
+
+ skipWhile<UChar, isSchemeContinuationCharacter>(position, end);
+
+ if (position != end)
+ return false;
+
+ scheme = String(begin, end - begin);
+ return true;
+}
+
+// host = [ "*." ] 1*host-char *( "." 1*host-char )
+// / "*"
+// host-char = ALPHA / DIGIT / "-"
+//
+bool CSPSourceList::parseHost(const UChar* begin, const UChar* end, String& host, bool& hostHasWildcard)
+{
+ ASSERT(begin <= end);
+ ASSERT(host.isEmpty());
+ ASSERT(!hostHasWildcard);
+
+ if (begin == end)
+ return false;
+
+ const UChar* position = begin;
+
+ if (skipExactly<UChar>(position, end, '*')) {
+ hostHasWildcard = true;
+
+ if (position == end)
+ return true;
+
+ if (!skipExactly<UChar>(position, end, '.'))
+ return false;
+ }
+
+ const UChar* hostBegin = position;
+
+ while (position < end) {
+ if (!skipExactly<UChar, isHostCharacter>(position, end))
+ return false;
+
+ skipWhile<UChar, isHostCharacter>(position, end);
+
+ if (position < end && !skipExactly<UChar>(position, end, '.'))
+ return false;
+ }
+
+ ASSERT(position == end);
+ host = String(hostBegin, end - hostBegin);
+ return true;
+}
+
+bool CSPSourceList::parsePath(const UChar* begin, const UChar* end, String& path)
+{
+ ASSERT(begin <= end);
+ ASSERT(path.isEmpty());
+
+ const UChar* position = begin;
+ skipWhile<UChar, isPathComponentCharacter>(position, end);
+ // path/to/file.js?query=string || path/to/file.js#anchor
+ // ^ ^
+ if (position < end)
+ m_policy->reportInvalidPathCharacter(m_directiveName, String(begin, end - begin), *position);
+
+ path = decodeURLEscapeSequences(String(begin, position - begin));
+
+ ASSERT(position <= end);
+ ASSERT(position == end || (*position == '#' || *position == '?'));
+ return true;
+}
+
+// port = ":" ( 1*DIGIT / "*" )
+//
+bool CSPSourceList::parsePort(const UChar* begin, const UChar* end, int& port, bool& portHasWildcard)
+{
+ ASSERT(begin <= end);
+ ASSERT(!port);
+ ASSERT(!portHasWildcard);
+
+ if (!skipExactly<UChar>(begin, end, ':'))
+ ASSERT_NOT_REACHED();
+
+ if (begin == end)
+ return false;
+
+ if (end - begin == 1 && *begin == '*') {
+ port = 0;
+ portHasWildcard = true;
+ return true;
+ }
+
+ const UChar* position = begin;
+ skipWhile<UChar, isASCIIDigit>(position, end);
+
+ if (position != end)
+ return false;
+
+ bool ok;
+ port = charactersToIntStrict(begin, end - begin, &ok);
+ return ok;
+}
+
+void CSPSourceList::addSourceSelf()
+{
+ m_list.append(CSPSource(m_policy, m_policy->securityOrigin()->protocol(), m_policy->securityOrigin()->host(), m_policy->securityOrigin()->port(), String(), false, false));
+}
+
+void CSPSourceList::addSourceStar()
+{
+ m_allowStar = true;
+}
+
+void CSPSourceList::addSourceUnsafeInline()
+{
+ m_allowInline = true;
+}
+
+void CSPSourceList::addSourceUnsafeEval()
+{
+ m_allowEval = true;
+}
+
+void CSPSourceList::addSourceNonce(const String& nonce)
+{
+ m_nonces.add(nonce);
+}
+
+void CSPSourceList::addSourceHash(const ContentSecurityPolicy::HashAlgorithms& algorithm, const Vector<uint8_t>& hash)
+{
+ m_hashes.add(SourceHashValue(algorithm, hash));
+ m_hashAlgorithmsUsed |= algorithm;
+}
+
+class CSPDirective {
+public:
+ CSPDirective(const String& name, const String& value, ContentSecurityPolicy* policy)
+ : m_name(name)
+ , m_text(name + ' ' + value)
+ , m_policy(policy)
+ {
+ }
+
+ const String& text() const { return m_text; }
+
+protected:
+ const ContentSecurityPolicy* policy() const { return m_policy; }
+
+private:
+ String m_name;
+ String m_text;
+ ContentSecurityPolicy* m_policy;
+};
+
+class MediaListDirective : public CSPDirective {
+public:
+ MediaListDirective(const String& name, const String& value, ContentSecurityPolicy* policy)
+ : CSPDirective(name, value, policy)
+ {
+ Vector<UChar> characters;
+ value.appendTo(characters);
+ parse(characters.data(), characters.data() + characters.size());
+ }
+
+ bool allows(const String& type)
+ {
+ return m_pluginTypes.contains(type);
+ }
+
+private:
+ void parse(const UChar* begin, const UChar* end)
+ {
+ const UChar* position = begin;
+
+ // 'plugin-types ____;' OR 'plugin-types;'
+ if (position == end) {
+ policy()->reportInvalidPluginTypes(String());
+ return;
+ }
+
+ while (position < end) {
+ // _____ OR _____mime1/mime1
+ // ^ ^
+ skipWhile<UChar, isASCIISpace>(position, end);
+ if (position == end)
+ return;
+
+ // mime1/mime1 mime2/mime2
+ // ^
+ begin = position;
+ if (!skipExactly<UChar, isMediaTypeCharacter>(position, end)) {
+ skipWhile<UChar, isNotASCIISpace>(position, end);
+ policy()->reportInvalidPluginTypes(String(begin, position - begin));
+ continue;
+ }
+ skipWhile<UChar, isMediaTypeCharacter>(position, end);
+
+ // mime1/mime1 mime2/mime2
+ // ^
+ if (!skipExactly<UChar>(position, end, '/')) {
+ skipWhile<UChar, isNotASCIISpace>(position, end);
+ policy()->reportInvalidPluginTypes(String(begin, position - begin));
+ continue;
+ }
+
+ // mime1/mime1 mime2/mime2
+ // ^
+ if (!skipExactly<UChar, isMediaTypeCharacter>(position, end)) {
+ skipWhile<UChar, isNotASCIISpace>(position, end);
+ policy()->reportInvalidPluginTypes(String(begin, position - begin));
+ continue;
+ }
+ skipWhile<UChar, isMediaTypeCharacter>(position, end);
+
+ // mime1/mime1 mime2/mime2 OR mime1/mime1 OR mime1/mime1/error
+ // ^ ^ ^
+ if (position < end && isNotASCIISpace(*position)) {
+ skipWhile<UChar, isNotASCIISpace>(position, end);
+ policy()->reportInvalidPluginTypes(String(begin, position - begin));
+ continue;
+ }
+ m_pluginTypes.add(String(begin, position - begin));
+
+ ASSERT(position == end || isASCIISpace(*position));
+ }
+ }
+
+ HashSet<String> m_pluginTypes;
+};
+
+class SourceListDirective : public CSPDirective {
+public:
+ SourceListDirective(const String& name, const String& value, ContentSecurityPolicy* policy)
+ : CSPDirective(name, value, policy)
+ , m_sourceList(policy, name)
+ {
+ Vector<UChar> characters;
+ value.appendTo(characters);
+
+ m_sourceList.parse(characters.data(), characters.data() + characters.size());
+ }
+
+ bool allows(const KURL& url)
+ {
+ return m_sourceList.matches(url.isEmpty() ? policy()->url() : url);
+ }
+
+ bool allowInline() const { return m_sourceList.allowInline(); }
+ bool allowEval() const { return m_sourceList.allowEval(); }
+ bool allowNonce(const String& nonce) const { return m_sourceList.allowNonce(nonce.stripWhiteSpace()); }
+ bool allowHash(const SourceHashValue& hashValue) const { return m_sourceList.allowHash(hashValue); }
+
+ uint8_t hashAlgorithmsUsed() const { return m_sourceList.hashAlgorithmsUsed(); }
+
+private:
+ CSPSourceList m_sourceList;
+};
+
+class CSPDirectiveList {
+ WTF_MAKE_FAST_ALLOCATED;
+public:
+ static PassOwnPtr<CSPDirectiveList> create(ContentSecurityPolicy*, const UChar* begin, const UChar* end, ContentSecurityPolicy::HeaderType);
+
+ void parse(const UChar* begin, const UChar* end);
+
+ const String& header() const { return m_header; }
+ ContentSecurityPolicy::HeaderType headerType() const { return m_headerType; }
+
+ bool allowJavaScriptURLs(const String& contextURL, const WTF::OrdinalNumber& contextLine, ContentSecurityPolicy::ReportingStatus) const;
+ bool allowInlineEventHandlers(const String& contextURL, const WTF::OrdinalNumber& contextLine, ContentSecurityPolicy::ReportingStatus) const;
+ bool allowInlineScript(const String& contextURL, const WTF::OrdinalNumber& contextLine, ContentSecurityPolicy::ReportingStatus) const;
+ bool allowInlineStyle(const String& contextURL, const WTF::OrdinalNumber& contextLine, ContentSecurityPolicy::ReportingStatus) const;
+ bool allowEval(ScriptState*, ContentSecurityPolicy::ReportingStatus) const;
+ bool allowPluginType(const String& type, const String& typeAttribute, const KURL&, ContentSecurityPolicy::ReportingStatus) const;
+
+ bool allowScriptFromSource(const KURL&, ContentSecurityPolicy::ReportingStatus) const;
+ bool allowObjectFromSource(const KURL&, ContentSecurityPolicy::ReportingStatus) const;
+ bool allowChildFrameFromSource(const KURL&, ContentSecurityPolicy::ReportingStatus) const;
+ bool allowImageFromSource(const KURL&, ContentSecurityPolicy::ReportingStatus) const;
+ bool allowStyleFromSource(const KURL&, ContentSecurityPolicy::ReportingStatus) const;
+ bool allowFontFromSource(const KURL&, ContentSecurityPolicy::ReportingStatus) const;
+ bool allowMediaFromSource(const KURL&, ContentSecurityPolicy::ReportingStatus) const;
+ bool allowConnectToSource(const KURL&, ContentSecurityPolicy::ReportingStatus) const;
+ bool allowFormAction(const KURL&, ContentSecurityPolicy::ReportingStatus) const;
+ bool allowBaseURI(const KURL&, ContentSecurityPolicy::ReportingStatus) const;
+ bool allowScriptNonce(const String&) const;
+ bool allowStyleNonce(const String&) const;
+ bool allowScriptHash(const SourceHashValue&) const;
+
+ void gatherReportURIs(DOMStringList&) const;
+ const String& evalDisabledErrorMessage() const { return m_evalDisabledErrorMessage; }
+ ReflectedXSSDisposition reflectedXSSDisposition() const { return m_reflectedXSSDisposition; }
+ bool isReportOnly() const { return m_reportOnly; }
+ const Vector<KURL>& reportURIs() const { return m_reportURIs; }
+
+private:
+ CSPDirectiveList(ContentSecurityPolicy*, ContentSecurityPolicy::HeaderType);
+
+ bool parseDirective(const UChar* begin, const UChar* end, String& name, String& value);
+ void parseReportURI(const String& name, const String& value);
+ void parsePluginTypes(const String& name, const String& value);
+ void parseReflectedXSS(const String& name, const String& value);
+ void addDirective(const String& name, const String& value);
+ void applySandboxPolicy(const String& name, const String& sandboxPolicy);
+
+ template <class CSPDirectiveType>
+ void setCSPDirective(const String& name, const String& value, OwnPtr<CSPDirectiveType>&);
+
+ SourceListDirective* operativeDirective(SourceListDirective*) const;
+ void reportViolation(const String& directiveText, const String& effectiveDirective, const String& consoleMessage, const KURL& blockedURL) const;
+ void reportViolationWithLocation(const String& directiveText, const String& effectiveDirective, const String& consoleMessage, const KURL& blockedURL, const String& contextURL, const WTF::OrdinalNumber& contextLine) const;
+ void reportViolationWithState(const String& directiveText, const String& effectiveDirective, const String& consoleMessage, const KURL& blockedURL, ScriptState*) const;
+
+ bool checkEval(SourceListDirective*) const;
+ bool checkInline(SourceListDirective*) const;
+ bool checkNonce(SourceListDirective*, const String&) const;
+ bool checkHash(SourceListDirective*, const SourceHashValue&) const;
+ bool checkSource(SourceListDirective*, const KURL&) const;
+ bool checkMediaType(MediaListDirective*, const String& type, const String& typeAttribute) const;
+
+ void setEvalDisabledErrorMessage(const String& errorMessage) { m_evalDisabledErrorMessage = errorMessage; }
+
+ bool checkEvalAndReportViolation(SourceListDirective*, const String& consoleMessage, ScriptState*) const;
+ bool checkInlineAndReportViolation(SourceListDirective*, const String& consoleMessage, const String& contextURL, const WTF::OrdinalNumber& contextLine, bool isScript) const;
+
+ bool checkSourceAndReportViolation(SourceListDirective*, const KURL&, const String& effectiveDirective) const;
+ bool checkMediaTypeAndReportViolation(MediaListDirective*, const String& type, const String& typeAttribute, const String& consoleMessage) const;
+
+ bool denyIfEnforcingPolicy() const { return m_reportOnly; }
+
+ ContentSecurityPolicy* m_policy;
+
+ String m_header;
+ ContentSecurityPolicy::HeaderType m_headerType;
+
+ bool m_reportOnly;
+ bool m_haveSandboxPolicy;
+ ReflectedXSSDisposition m_reflectedXSSDisposition;
+
+ OwnPtr<MediaListDirective> m_pluginTypes;
+ OwnPtr<SourceListDirective> m_baseURI;
+ OwnPtr<SourceListDirective> m_connectSrc;
+ OwnPtr<SourceListDirective> m_defaultSrc;
+ OwnPtr<SourceListDirective> m_fontSrc;
+ OwnPtr<SourceListDirective> m_formAction;
+ OwnPtr<SourceListDirective> m_frameSrc;
+ OwnPtr<SourceListDirective> m_imgSrc;
+ OwnPtr<SourceListDirective> m_mediaSrc;
+ OwnPtr<SourceListDirective> m_objectSrc;
+ OwnPtr<SourceListDirective> m_scriptSrc;
+ OwnPtr<SourceListDirective> m_styleSrc;
+
+ Vector<KURL> m_reportURIs;
+
+ String m_evalDisabledErrorMessage;
+};
+
+CSPDirectiveList::CSPDirectiveList(ContentSecurityPolicy* policy, ContentSecurityPolicy::HeaderType type)
+ : m_policy(policy)
+ , m_headerType(type)
+ , m_reportOnly(false)
+ , m_haveSandboxPolicy(false)
+ , m_reflectedXSSDisposition(ReflectedXSSUnset)
+{
+ m_reportOnly = type == ContentSecurityPolicy::Report;
+}
+
+PassOwnPtr<CSPDirectiveList> CSPDirectiveList::create(ContentSecurityPolicy* policy, const UChar* begin, const UChar* end, ContentSecurityPolicy::HeaderType type)
+{
+ OwnPtr<CSPDirectiveList> directives = adoptPtr(new CSPDirectiveList(policy, type));
+ directives->parse(begin, end);
+
+ if (!directives->checkEval(directives->operativeDirective(directives->m_scriptSrc.get()))) {
+ String message = "Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: \"" + directives->operativeDirective(directives->m_scriptSrc.get())->text() + "\".\n";
+ directives->setEvalDisabledErrorMessage(message);
+ }
+
+ if (directives->isReportOnly() && directives->reportURIs().isEmpty())
+ policy->reportMissingReportURI(String(begin, end - begin));
+
+ return directives.release();
+}
+
+void CSPDirectiveList::reportViolation(const String& directiveText, const String& effectiveDirective, const String& consoleMessage, const KURL& blockedURL) const
+{
+ String message = m_reportOnly ? "[Report Only] " + consoleMessage : consoleMessage;
+ m_policy->client()->addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, message);
+ m_policy->reportViolation(directiveText, effectiveDirective, message, blockedURL, m_reportURIs, m_header);
+}
+
+void CSPDirectiveList::reportViolationWithLocation(const String& directiveText, const String& effectiveDirective, const String& consoleMessage, const KURL& blockedURL, const String& contextURL, const WTF::OrdinalNumber& contextLine) const
+{
+ String message = m_reportOnly ? "[Report Only] " + consoleMessage : consoleMessage;
+ m_policy->client()->addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, message, contextURL, contextLine.oneBasedInt());
+ m_policy->reportViolation(directiveText, effectiveDirective, message, blockedURL, m_reportURIs, m_header);
+}
+
+void CSPDirectiveList::reportViolationWithState(const String& directiveText, const String& effectiveDirective, const String& consoleMessage, const KURL& blockedURL, ScriptState* state) const
+{
+ String message = m_reportOnly ? "[Report Only] " + consoleMessage : consoleMessage;
+ m_policy->client()->addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, message, state);
+ m_policy->reportViolation(directiveText, effectiveDirective, message, blockedURL, m_reportURIs, m_header);
+}
+
+bool CSPDirectiveList::checkEval(SourceListDirective* directive) const
+{
+ return !directive || directive->allowEval();
+}
+
+bool CSPDirectiveList::checkInline(SourceListDirective* directive) const
+{
+ return !directive || directive->allowInline();
+}
+
+bool CSPDirectiveList::checkNonce(SourceListDirective* directive, const String& nonce) const
+{
+ return !directive || directive->allowNonce(nonce);
+}
+
+bool CSPDirectiveList::checkHash(SourceListDirective* directive, const SourceHashValue& hashValue) const
+{
+ return !directive || directive->allowHash(hashValue);
+}
+
+bool CSPDirectiveList::checkSource(SourceListDirective* directive, const KURL& url) const
+{
+ return !directive || directive->allows(url);
+}
+
+bool CSPDirectiveList::checkMediaType(MediaListDirective* directive, const String& type, const String& typeAttribute) const
+{
+ if (!directive)
+ return true;
+ if (typeAttribute.isEmpty() || typeAttribute.stripWhiteSpace() != type)
+ return false;
+ return directive->allows(type);
+}
+
+SourceListDirective* CSPDirectiveList::operativeDirective(SourceListDirective* directive) const
+{
+ return directive ? directive : m_defaultSrc.get();
+}
+
+bool CSPDirectiveList::checkEvalAndReportViolation(SourceListDirective* directive, const String& consoleMessage, ScriptState* state) const
+{
+ if (checkEval(directive))
+ return true;
+
+ String suffix = String();
+ if (directive == m_defaultSrc)
+ suffix = " Note that 'script-src' was not explicitly set, so 'default-src' is used as a fallback.";
+
+ reportViolationWithState(directive->text(), scriptSrc, consoleMessage + "\"" + directive->text() + "\"." + suffix + "\n", KURL(), state);
+ if (!m_reportOnly) {
+ m_policy->reportBlockedScriptExecutionToInspector(directive->text());
+ return false;
+ }
+ return true;
+}
+
+bool CSPDirectiveList::checkMediaTypeAndReportViolation(MediaListDirective* directive, const String& type, const String& typeAttribute, const String& consoleMessage) const
+{
+ if (checkMediaType(directive, type, typeAttribute))
+ return true;
+
+ String message = consoleMessage + "\'" + directive->text() + "\'.";
+ if (typeAttribute.isEmpty())
+ message = message + " When enforcing the 'plugin-types' directive, the plugin's media type must be explicitly declared with a 'type' attribute on the containing element (e.g. '<object type=\"[TYPE GOES HERE]\" ...>').";
+
+ reportViolation(directive->text(), pluginTypes, message + "\n", KURL());
+ return denyIfEnforcingPolicy();
+}
+
+bool CSPDirectiveList::checkInlineAndReportViolation(SourceListDirective* directive, const String& consoleMessage, const String& contextURL, const WTF::OrdinalNumber& contextLine, bool isScript) const
+{
+ if (checkInline(directive))
+ return true;
+
+ String suffix = String();
+ if (directive == m_defaultSrc)
+ suffix = " Note that '" + String(isScript ? "script" : "style") + "-src' was not explicitly set, so 'default-src' is used as a fallback.";
+
+ reportViolationWithLocation(directive->text(), isScript ? scriptSrc : styleSrc, consoleMessage + "\"" + directive->text() + "\"." + suffix + "\n", KURL(), contextURL, contextLine);
+
+ if (!m_reportOnly) {
+ if (isScript)
+ m_policy->reportBlockedScriptExecutionToInspector(directive->text());
+ return false;
+ }
+ return true;
+}
+
+bool CSPDirectiveList::checkSourceAndReportViolation(SourceListDirective* directive, const KURL& url, const String& effectiveDirective) const
+{
+ if (checkSource(directive, url))
+ return true;
+
+ String prefix;
+ if (baseURI == effectiveDirective)
+ prefix = "Refused to set the document's base URI to '";
+ else if (connectSrc == effectiveDirective)
+ prefix = "Refused to connect to '";
+ else if (fontSrc == effectiveDirective)
+ prefix = "Refused to load the font '";
+ else if (formAction == effectiveDirective)
+ prefix = "Refused to send form data to '";
+ else if (frameSrc == effectiveDirective)
+ prefix = "Refused to frame '";
+ else if (imgSrc == effectiveDirective)
+ prefix = "Refused to load the image '";
+ else if (mediaSrc == effectiveDirective)
+ prefix = "Refused to load media from '";
+ else if (objectSrc == effectiveDirective)
+ prefix = "Refused to load plugin data from '";
+ else if (scriptSrc == effectiveDirective)
+ prefix = "Refused to load the script '";
+ else if (styleSrc == effectiveDirective)
+ prefix = "Refused to load the stylesheet '";
+
+ String suffix = String();
+ if (directive == m_defaultSrc)
+ suffix = " Note that '" + effectiveDirective + "' was not explicitly set, so 'default-src' is used as a fallback.";
+
+ reportViolation(directive->text(), effectiveDirective, prefix + url.elidedString() + "' because it violates the following Content Security Policy directive: \"" + directive->text() + "\"." + suffix + "\n", url);
+ return denyIfEnforcingPolicy();
+}
+
+bool CSPDirectiveList::allowJavaScriptURLs(const String& contextURL, const WTF::OrdinalNumber& contextLine, ContentSecurityPolicy::ReportingStatus reportingStatus) const
+{
+ DEFINE_STATIC_LOCAL(String, consoleMessage, ("Refused to execute JavaScript URL because it violates the following Content Security Policy directive: "));
+ if (reportingStatus == ContentSecurityPolicy::SendReport)
+ return checkInlineAndReportViolation(operativeDirective(m_scriptSrc.get()), consoleMessage, contextURL, contextLine, true);
+
+ return checkInline(operativeDirective(m_scriptSrc.get()));
+}
+
+bool CSPDirectiveList::allowInlineEventHandlers(const String& contextURL, const WTF::OrdinalNumber& contextLine, ContentSecurityPolicy::ReportingStatus reportingStatus) const
+{
+ DEFINE_STATIC_LOCAL(String, consoleMessage, ("Refused to execute inline event handler because it violates the following Content Security Policy directive: "));
+ if (reportingStatus == ContentSecurityPolicy::SendReport)
+ return checkInlineAndReportViolation(operativeDirective(m_scriptSrc.get()), consoleMessage, contextURL, contextLine, true);
+ return checkInline(operativeDirective(m_scriptSrc.get()));
+}
+
+bool CSPDirectiveList::allowInlineScript(const String& contextURL, const WTF::OrdinalNumber& contextLine, ContentSecurityPolicy::ReportingStatus reportingStatus) const
+{
+ DEFINE_STATIC_LOCAL(String, consoleMessage, ("Refused to execute inline script because it violates the following Content Security Policy directive: "));
+ return reportingStatus == ContentSecurityPolicy::SendReport ?
+ checkInlineAndReportViolation(operativeDirective(m_scriptSrc.get()), consoleMessage, contextURL, contextLine, true) :
+ checkInline(operativeDirective(m_scriptSrc.get()));
+}
+
+bool CSPDirectiveList::allowInlineStyle(const String& contextURL, const WTF::OrdinalNumber& contextLine, ContentSecurityPolicy::ReportingStatus reportingStatus) const
+{
+ DEFINE_STATIC_LOCAL(String, consoleMessage, ("Refused to apply inline style because it violates the following Content Security Policy directive: "));
+ return reportingStatus == ContentSecurityPolicy::SendReport ?
+ checkInlineAndReportViolation(operativeDirective(m_styleSrc.get()), consoleMessage, contextURL, contextLine, false) :
+ checkInline(operativeDirective(m_styleSrc.get()));
+}
+
+bool CSPDirectiveList::allowEval(ScriptState* state, ContentSecurityPolicy::ReportingStatus reportingStatus) const
+{
+ DEFINE_STATIC_LOCAL(String, consoleMessage, ("Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "));
+
+ return reportingStatus == ContentSecurityPolicy::SendReport ?
+ checkEvalAndReportViolation(operativeDirective(m_scriptSrc.get()), consoleMessage, state) :
+ checkEval(operativeDirective(m_scriptSrc.get()));
+}
+
+bool CSPDirectiveList::allowPluginType(const String& type, const String& typeAttribute, const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
+{
+ return reportingStatus == ContentSecurityPolicy::SendReport ?
+ checkMediaTypeAndReportViolation(m_pluginTypes.get(), type, typeAttribute, "Refused to load '" + url.elidedString() + "' (MIME type '" + typeAttribute + "') because it violates the following Content Security Policy Directive: ") :
+ checkMediaType(m_pluginTypes.get(), type, typeAttribute);
+}
+
+bool CSPDirectiveList::allowScriptFromSource(const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
+{
+ return reportingStatus == ContentSecurityPolicy::SendReport ?
+ checkSourceAndReportViolation(operativeDirective(m_scriptSrc.get()), url, scriptSrc) :
+ checkSource(operativeDirective(m_scriptSrc.get()), url);
+}
+
+bool CSPDirectiveList::allowObjectFromSource(const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
+{
+ if (url.isBlankURL())
+ return true;
+ return reportingStatus == ContentSecurityPolicy::SendReport ?
+ checkSourceAndReportViolation(operativeDirective(m_objectSrc.get()), url, objectSrc) :
+ checkSource(operativeDirective(m_objectSrc.get()), url);
+}
+
+bool CSPDirectiveList::allowChildFrameFromSource(const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
+{
+ if (url.isBlankURL())
+ return true;
+ return reportingStatus == ContentSecurityPolicy::SendReport ?
+ checkSourceAndReportViolation(operativeDirective(m_frameSrc.get()), url, frameSrc) :
+ checkSource(operativeDirective(m_frameSrc.get()), url);
+}
+
+bool CSPDirectiveList::allowImageFromSource(const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
+{
+ return reportingStatus == ContentSecurityPolicy::SendReport ?
+ checkSourceAndReportViolation(operativeDirective(m_imgSrc.get()), url, imgSrc) :
+ checkSource(operativeDirective(m_imgSrc.get()), url);
+}
+
+bool CSPDirectiveList::allowStyleFromSource(const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
+{
+ return reportingStatus == ContentSecurityPolicy::SendReport ?
+ checkSourceAndReportViolation(operativeDirective(m_styleSrc.get()), url, styleSrc) :
+ checkSource(operativeDirective(m_styleSrc.get()), url);
+}
+
+bool CSPDirectiveList::allowFontFromSource(const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
+{
+ return reportingStatus == ContentSecurityPolicy::SendReport ?
+ checkSourceAndReportViolation(operativeDirective(m_fontSrc.get()), url, fontSrc) :
+ checkSource(operativeDirective(m_fontSrc.get()), url);
+}
+
+bool CSPDirectiveList::allowMediaFromSource(const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
+{
+ return reportingStatus == ContentSecurityPolicy::SendReport ?
+ checkSourceAndReportViolation(operativeDirective(m_mediaSrc.get()), url, mediaSrc) :
+ checkSource(operativeDirective(m_mediaSrc.get()), url);
+}
+
+bool CSPDirectiveList::allowConnectToSource(const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
+{
+ return reportingStatus == ContentSecurityPolicy::SendReport ?
+ checkSourceAndReportViolation(operativeDirective(m_connectSrc.get()), url, connectSrc) :
+ checkSource(operativeDirective(m_connectSrc.get()), url);
+}
+
+void CSPDirectiveList::gatherReportURIs(DOMStringList& list) const
+{
+ for (size_t i = 0; i < m_reportURIs.size(); ++i)
+ list.append(m_reportURIs[i].string());
+}
+
+bool CSPDirectiveList::allowFormAction(const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
+{
+ return reportingStatus == ContentSecurityPolicy::SendReport ?
+ checkSourceAndReportViolation(m_formAction.get(), url, formAction) :
+ checkSource(m_formAction.get(), url);
+}
+
+bool CSPDirectiveList::allowBaseURI(const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
+{
+ return reportingStatus == ContentSecurityPolicy::SendReport ?
+ checkSourceAndReportViolation(m_baseURI.get(), url, baseURI) :
+ checkSource(m_baseURI.get(), url);
+}
+
+bool CSPDirectiveList::allowScriptNonce(const String& nonce) const
+{
+ return checkNonce(operativeDirective(m_scriptSrc.get()), nonce);
+}
+
+bool CSPDirectiveList::allowStyleNonce(const String& nonce) const
+{
+ return checkNonce(operativeDirective(m_styleSrc.get()), nonce);
+}
+
+bool CSPDirectiveList::allowScriptHash(const SourceHashValue& hashValue) const
+{
+ return checkHash(operativeDirective(m_scriptSrc.get()), hashValue);
+}
+
+// policy = directive-list
+// directive-list = [ directive *( ";" [ directive ] ) ]
+//
+void CSPDirectiveList::parse(const UChar* begin, const UChar* end)
+{
+ m_header = String(begin, end - begin);
+
+ if (begin == end)
+ return;
+
+ const UChar* position = begin;
+ while (position < end) {
+ const UChar* directiveBegin = position;
+ skipUntil<UChar>(position, end, ';');
+
+ String name, value;
+ if (parseDirective(directiveBegin, position, name, value)) {
+ ASSERT(!name.isEmpty());
+ addDirective(name, value);
+ }
+
+ ASSERT(position == end || *position == ';');
+ skipExactly<UChar>(position, end, ';');
+ }
+}
+
+// directive = *WSP [ directive-name [ WSP directive-value ] ]
+// directive-name = 1*( ALPHA / DIGIT / "-" )
+// directive-value = *( WSP / <VCHAR except ";"> )
+//
+bool CSPDirectiveList::parseDirective(const UChar* begin, const UChar* end, String& name, String& value)
+{
+ ASSERT(name.isEmpty());
+ ASSERT(value.isEmpty());
+
+ const UChar* position = begin;
+ skipWhile<UChar, isASCIISpace>(position, end);
+
+ // Empty directive (e.g. ";;;"). Exit early.
+ if (position == end)
+ return false;
+
+ const UChar* nameBegin = position;
+ skipWhile<UChar, isDirectiveNameCharacter>(position, end);
+
+ // The directive-name must be non-empty.
+ if (nameBegin == position) {
+ skipWhile<UChar, isNotASCIISpace>(position, end);
+ m_policy->reportUnsupportedDirective(String(nameBegin, position - nameBegin));
+ return false;
+ }
+
+ name = String(nameBegin, position - nameBegin);
+
+ if (position == end)
+ return true;
+
+ if (!skipExactly<UChar, isASCIISpace>(position, end)) {
+ skipWhile<UChar, isNotASCIISpace>(position, end);
+ m_policy->reportUnsupportedDirective(String(nameBegin, position - nameBegin));
+ return false;
+ }
+
+ skipWhile<UChar, isASCIISpace>(position, end);
+
+ const UChar* valueBegin = position;
+ skipWhile<UChar, isDirectiveValueCharacter>(position, end);
+
+ if (position != end) {
+ m_policy->reportInvalidDirectiveValueCharacter(name, String(valueBegin, end - valueBegin));
+ return false;
+ }
+
+ // The directive-value may be empty.
+ if (valueBegin == position)
+ return true;
+
+ value = String(valueBegin, position - valueBegin);
+ return true;
+}
+
+void CSPDirectiveList::parseReportURI(const String& name, const String& value)
+{
+ if (!m_reportURIs.isEmpty()) {
+ m_policy->reportDuplicateDirective(name);
+ return;
+ }
+
+ Vector<UChar> characters;
+ value.appendTo(characters);
+
+ const UChar* position = characters.data();
+ const UChar* end = position + characters.size();
+
+ while (position < end) {
+ skipWhile<UChar, isASCIISpace>(position, end);
+
+ const UChar* urlBegin = position;
+ skipWhile<UChar, isNotASCIISpace>(position, end);
+
+ if (urlBegin < position) {
+ String url = String(urlBegin, position - urlBegin);
+ m_reportURIs.append(m_policy->completeURL(url));
+ }
+ }
+}
+
+
+template<class CSPDirectiveType>
+void CSPDirectiveList::setCSPDirective(const String& name, const String& value, OwnPtr<CSPDirectiveType>& directive)
+{
+ if (directive) {
+ m_policy->reportDuplicateDirective(name);
+ return;
+ }
+ directive = adoptPtr(new CSPDirectiveType(name, value, m_policy));
+}
+
+void CSPDirectiveList::applySandboxPolicy(const String& name, const String& sandboxPolicy)
+{
+ if (m_haveSandboxPolicy) {
+ m_policy->reportDuplicateDirective(name);
+ return;
+ }
+ m_haveSandboxPolicy = true;
+ String invalidTokens;
+ m_policy->enforceSandboxFlags(parseSandboxPolicy(sandboxPolicy, invalidTokens));
+ if (!invalidTokens.isNull())
+ m_policy->reportInvalidSandboxFlags(invalidTokens);
+}
+
+void CSPDirectiveList::parseReflectedXSS(const String& name, const String& value)
+{
+ if (m_reflectedXSSDisposition != ReflectedXSSUnset) {
+ m_policy->reportDuplicateDirective(name);
+ m_reflectedXSSDisposition = ReflectedXSSInvalid;
+ return;
+ }
+
+ if (value.isEmpty()) {
+ m_reflectedXSSDisposition = ReflectedXSSInvalid;
+ m_policy->reportInvalidReflectedXSS(value);
+ return;
+ }
+
+ Vector<UChar> characters;
+ value.appendTo(characters);
+
+ const UChar* position = characters.data();
+ const UChar* end = position + characters.size();
+
+ skipWhile<UChar, isASCIISpace>(position, end);
+ const UChar* begin = position;
+ skipWhile<UChar, isNotASCIISpace>(position, end);
+
+ // value1
+ // ^
+ if (equalIgnoringCase("allow", begin, position - begin)) {
+ m_reflectedXSSDisposition = AllowReflectedXSS;
+ } else if (equalIgnoringCase("filter", begin, position - begin)) {
+ m_reflectedXSSDisposition = FilterReflectedXSS;
+ } else if (equalIgnoringCase("block", begin, position - begin)) {
+ m_reflectedXSSDisposition = BlockReflectedXSS;
+ } else {
+ m_reflectedXSSDisposition = ReflectedXSSInvalid;
+ m_policy->reportInvalidReflectedXSS(value);
+ return;
+ }
+
+ skipWhile<UChar, isASCIISpace>(position, end);
+ if (position == end && m_reflectedXSSDisposition != ReflectedXSSUnset)
+ return;
+
+ // value1 value2
+ // ^
+ m_reflectedXSSDisposition = ReflectedXSSInvalid;
+ m_policy->reportInvalidReflectedXSS(value);
+}
+
+void CSPDirectiveList::addDirective(const String& name, const String& value)
+{
+ ASSERT(!name.isEmpty());
+
+ if (equalIgnoringCase(name, defaultSrc)) {
+ setCSPDirective<SourceListDirective>(name, value, m_defaultSrc);
+ } else if (equalIgnoringCase(name, scriptSrc)) {
+ setCSPDirective<SourceListDirective>(name, value, m_scriptSrc);
+ m_policy->usesScriptHashAlgorithms(m_scriptSrc->hashAlgorithmsUsed());
+ } else if (equalIgnoringCase(name, objectSrc)) {
+ setCSPDirective<SourceListDirective>(name, value, m_objectSrc);
+ } else if (equalIgnoringCase(name, frameSrc)) {
+ setCSPDirective<SourceListDirective>(name, value, m_frameSrc);
+ } else if (equalIgnoringCase(name, imgSrc)) {
+ setCSPDirective<SourceListDirective>(name, value, m_imgSrc);
+ } else if (equalIgnoringCase(name, styleSrc)) {
+ setCSPDirective<SourceListDirective>(name, value, m_styleSrc);
+ } else if (equalIgnoringCase(name, fontSrc)) {
+ setCSPDirective<SourceListDirective>(name, value, m_fontSrc);
+ } else if (equalIgnoringCase(name, mediaSrc)) {
+ setCSPDirective<SourceListDirective>(name, value, m_mediaSrc);
+ } else if (equalIgnoringCase(name, connectSrc)) {
+ setCSPDirective<SourceListDirective>(name, value, m_connectSrc);
+ } else if (equalIgnoringCase(name, sandbox)) {
+ applySandboxPolicy(name, value);
+ } else if (equalIgnoringCase(name, reportURI)) {
+ parseReportURI(name, value);
+ } else if (m_policy->experimentalFeaturesEnabled()) {
+ if (equalIgnoringCase(name, baseURI))
+ setCSPDirective<SourceListDirective>(name, value, m_baseURI);
+ else if (equalIgnoringCase(name, formAction))
+ setCSPDirective<SourceListDirective>(name, value, m_formAction);
+ else if (equalIgnoringCase(name, pluginTypes))
+ setCSPDirective<MediaListDirective>(name, value, m_pluginTypes);
+ else if (equalIgnoringCase(name, reflectedXSS))
+ parseReflectedXSS(name, value);
+ else
+ m_policy->reportUnsupportedDirective(name);
+ } else {
+ m_policy->reportUnsupportedDirective(name);
+ }
+}
+
+ContentSecurityPolicy::ContentSecurityPolicy(ExecutionContextClient* client)
+ : m_client(client)
+ , m_overrideInlineStyleAllowed(false)
+ , m_sourceHashAlgorithmsUsed(HashAlgorithmsNone)
+{
+}
+
+ContentSecurityPolicy::~ContentSecurityPolicy()
+{
+}
+
+void ContentSecurityPolicy::copyStateFrom(const ContentSecurityPolicy* other)
+{
+ ASSERT(m_policies.isEmpty());
+ for (CSPDirectiveListVector::const_iterator iter = other->m_policies.begin(); iter != other->m_policies.end(); ++iter)
+ addPolicyFromHeaderValue((*iter)->header(), (*iter)->headerType());
+}
+
+void ContentSecurityPolicy::didReceiveHeaders(const ContentSecurityPolicyResponseHeaders& headers)
+{
+ if (!headers.contentSecurityPolicy().isEmpty())
+ didReceiveHeader(headers.contentSecurityPolicy(), ContentSecurityPolicy::Enforce);
+ if (!headers.contentSecurityPolicyReportOnly().isEmpty())
+ didReceiveHeader(headers.contentSecurityPolicyReportOnly(), ContentSecurityPolicy::Report);
+
+ // FIXME: Remove this reporting (and the 'xWebKitCSP*' methods) after the next release branch.
+ if (m_client->isDocument()) {
+ Document* document = static_cast<Document*>(m_client);
+ if (!headers.xWebKitCSP().isEmpty())
+ UseCounter::countDeprecation(*document, UseCounter::PrefixedContentSecurityPolicy);
+ if (!headers.xWebKitCSPReportOnly().isEmpty())
+ UseCounter::countDeprecation(*document, UseCounter::PrefixedContentSecurityPolicyReportOnly);
+ }
+}
+
+void ContentSecurityPolicy::didReceiveHeader(const String& header, HeaderType type)
+{
+ addPolicyFromHeaderValue(header, type);
+}
+
+void ContentSecurityPolicy::addPolicyFromHeaderValue(const String& header, HeaderType type)
+{
+ if (m_client->isDocument()) {
+ Document* document = static_cast<Document*>(m_client);
+ UseCounter::count(*document, getUseCounterType(type));
+ }
+
+ Vector<UChar> characters;
+ header.appendTo(characters);
+
+ const UChar* begin = characters.data();
+ const UChar* end = begin + characters.size();
+
+ // RFC2616, section 4.2 specifies that headers appearing multiple times can
+ // be combined with a comma. Walk the header string, and parse each comma
+ // separated chunk as a separate header.
+ const UChar* position = begin;
+ while (position < end) {
+ skipUntil<UChar>(position, end, ',');
+
+ // header1,header2 OR header1
+ // ^ ^
+ OwnPtr<CSPDirectiveList> policy = CSPDirectiveList::create(this, begin, position, type);
+
+ // We disable 'eval()' even in the case of report-only policies, and rely on the check in the V8Initializer::codeGenerationCheckCallbackInMainThread callback to determine whether the call should execute or not.
+ if (!policy->allowEval(0, SuppressReport))
+ m_client->disableEval(policy->evalDisabledErrorMessage());
+
+ m_policies.append(policy.release());
+
+ // Skip the comma, and begin the next header from the current position.
+ ASSERT(position == end || *position == ',');
+ skipExactly<UChar>(position, end, ',');
+ begin = position;
+ }
+}
+
+void ContentSecurityPolicy::setOverrideAllowInlineStyle(bool value)
+{
+ m_overrideInlineStyleAllowed = value;
+}
+
+const String& ContentSecurityPolicy::deprecatedHeader() const
+{
+ return m_policies.isEmpty() ? emptyString() : m_policies[0]->header();
+}
+
+ContentSecurityPolicy::HeaderType ContentSecurityPolicy::deprecatedHeaderType() const
+{
+ return m_policies.isEmpty() ? Enforce : m_policies[0]->headerType();
+}
+
+template<bool (CSPDirectiveList::*allowed)(ContentSecurityPolicy::ReportingStatus) const>
+bool isAllowedByAll(const CSPDirectiveListVector& policies, ContentSecurityPolicy::ReportingStatus reportingStatus)
+{
+ for (size_t i = 0; i < policies.size(); ++i) {
+ if (!(policies[i].get()->*allowed)(reportingStatus))
+ return false;
+ }
+ return true;
+}
+
+template<bool (CSPDirectiveList::*allowed)(ScriptState* state, ContentSecurityPolicy::ReportingStatus) const>
+bool isAllowedByAllWithState(const CSPDirectiveListVector& policies, ScriptState* state, ContentSecurityPolicy::ReportingStatus reportingStatus)
+{
+ for (size_t i = 0; i < policies.size(); ++i) {
+ if (!(policies[i].get()->*allowed)(state, reportingStatus))
+ return false;
+ }
+ return true;
+}
+
+template<bool (CSPDirectiveList::*allowed)(const String&, const WTF::OrdinalNumber&, ContentSecurityPolicy::ReportingStatus) const>
+bool isAllowedByAllWithContext(const CSPDirectiveListVector& policies, const String& contextURL, const WTF::OrdinalNumber& contextLine, ContentSecurityPolicy::ReportingStatus reportingStatus)
+{
+ for (size_t i = 0; i < policies.size(); ++i) {
+ if (!(policies[i].get()->*allowed)(contextURL, contextLine, reportingStatus))
+ return false;
+ }
+ return true;
+}
+
+template<bool (CSPDirectiveList::*allowed)(const String&) const>
+bool isAllowedByAllWithNonce(const CSPDirectiveListVector& policies, const String& nonce)
+{
+ for (size_t i = 0; i < policies.size(); ++i) {
+ if (!(policies[i].get()->*allowed)(nonce))
+ return false;
+ }
+ return true;
+}
+
+template<bool (CSPDirectiveList::*allowed)(const SourceHashValue&) const>
+bool isAllowedByAllWithHash(const CSPDirectiveListVector& policies, const SourceHashValue& hashValue)
+{
+ for (size_t i = 0; i < policies.size(); ++i) {
+ if (!(policies[i].get()->*allowed)(hashValue))
+ return false;
+ }
+ return true;
+}
+
+template<bool (CSPDirectiveList::*allowFromURL)(const KURL&, ContentSecurityPolicy::ReportingStatus) const>
+bool isAllowedByAllWithURL(const CSPDirectiveListVector& policies, const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus)
+{
+ if (SchemeRegistry::schemeShouldBypassContentSecurityPolicy(url.protocol()))
+ return true;
+
+ for (size_t i = 0; i < policies.size(); ++i) {
+ if (!(policies[i].get()->*allowFromURL)(url, reportingStatus))
+ return false;
+ }
+ return true;
+}
+
+bool ContentSecurityPolicy::allowJavaScriptURLs(const String& contextURL, const WTF::OrdinalNumber& contextLine, ContentSecurityPolicy::ReportingStatus reportingStatus) const
+{
+ return isAllowedByAllWithContext<&CSPDirectiveList::allowJavaScriptURLs>(m_policies, contextURL, contextLine, reportingStatus);
+}
+
+bool ContentSecurityPolicy::allowInlineEventHandlers(const String& contextURL, const WTF::OrdinalNumber& contextLine, ContentSecurityPolicy::ReportingStatus reportingStatus) const
+{
+ return isAllowedByAllWithContext<&CSPDirectiveList::allowInlineEventHandlers>(m_policies, contextURL, contextLine, reportingStatus);
+}
+
+bool ContentSecurityPolicy::allowInlineScript(const String& contextURL, const WTF::OrdinalNumber& contextLine, ContentSecurityPolicy::ReportingStatus reportingStatus) const
+{
+ return isAllowedByAllWithContext<&CSPDirectiveList::allowInlineScript>(m_policies, contextURL, contextLine, reportingStatus);
+}
+
+bool ContentSecurityPolicy::allowInlineStyle(const String& contextURL, const WTF::OrdinalNumber& contextLine, ContentSecurityPolicy::ReportingStatus reportingStatus) const
+{
+ if (m_overrideInlineStyleAllowed)
+ return true;
+ return isAllowedByAllWithContext<&CSPDirectiveList::allowInlineStyle>(m_policies, contextURL, contextLine, reportingStatus);
+}
+
+bool ContentSecurityPolicy::allowEval(ScriptState* state, ContentSecurityPolicy::ReportingStatus reportingStatus) const
+{
+ return isAllowedByAllWithState<&CSPDirectiveList::allowEval>(m_policies, state, reportingStatus);
+}
+
+String ContentSecurityPolicy::evalDisabledErrorMessage() const
+{
+ for (size_t i = 0; i < m_policies.size(); ++i) {
+ if (!m_policies[i]->allowEval(0, SuppressReport))
+ return m_policies[i]->evalDisabledErrorMessage();
+ }
+ return String();
+}
+
+bool ContentSecurityPolicy::allowPluginType(const String& type, const String& typeAttribute, const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
+{
+ for (size_t i = 0; i < m_policies.size(); ++i) {
+ if (!m_policies[i]->allowPluginType(type, typeAttribute, url, reportingStatus))
+ return false;
+ }
+ return true;
+}
+
+bool ContentSecurityPolicy::allowScriptFromSource(const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
+{
+ return isAllowedByAllWithURL<&CSPDirectiveList::allowScriptFromSource>(m_policies, url, reportingStatus);
+}
+
+bool ContentSecurityPolicy::allowScriptNonce(const String& nonce) const
+{
+ return isAllowedByAllWithNonce<&CSPDirectiveList::allowScriptNonce>(m_policies, nonce);
+}
+
+bool ContentSecurityPolicy::allowStyleNonce(const String& nonce) const
+{
+ return isAllowedByAllWithNonce<&CSPDirectiveList::allowStyleNonce>(m_policies, nonce);
+}
+
+bool ContentSecurityPolicy::allowScriptHash(const String& source) const
+{
+ // TODO(jww) We don't currently have a WTF SHA256 implementation. Once we
+ // have that, we should implement a proper check for sha256 hash values here.
+ if (HashAlgorithmsSha1 & m_sourceHashAlgorithmsUsed) {
+ Vector<uint8_t, 20> digest;
+ SHA1 sourceSha1;
+ sourceSha1.addBytes(UTF8Encoding().normalizeAndEncode(source, WTF::EntitiesForUnencodables));
+ sourceSha1.computeHash(digest);
+
+ if (isAllowedByAllWithHash<&CSPDirectiveList::allowScriptHash>(m_policies, SourceHashValue(HashAlgorithmsSha1, Vector<uint8_t>(digest))))
+ return true;
+ }
+
+ return false;
+}
+
+void ContentSecurityPolicy::usesScriptHashAlgorithms(uint8_t algorithms)
+{
+ m_sourceHashAlgorithmsUsed |= algorithms;
+}
+
+bool ContentSecurityPolicy::allowObjectFromSource(const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
+{
+ return isAllowedByAllWithURL<&CSPDirectiveList::allowObjectFromSource>(m_policies, url, reportingStatus);
+}
+
+bool ContentSecurityPolicy::allowChildFrameFromSource(const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
+{
+ return isAllowedByAllWithURL<&CSPDirectiveList::allowChildFrameFromSource>(m_policies, url, reportingStatus);
+}
+
+bool ContentSecurityPolicy::allowImageFromSource(const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
+{
+ return isAllowedByAllWithURL<&CSPDirectiveList::allowImageFromSource>(m_policies, url, reportingStatus);
+}
+
+bool ContentSecurityPolicy::allowStyleFromSource(const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
+{
+ return isAllowedByAllWithURL<&CSPDirectiveList::allowStyleFromSource>(m_policies, url, reportingStatus);
+}
+
+bool ContentSecurityPolicy::allowFontFromSource(const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
+{
+ return isAllowedByAllWithURL<&CSPDirectiveList::allowFontFromSource>(m_policies, url, reportingStatus);
+}
+
+bool ContentSecurityPolicy::allowMediaFromSource(const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
+{
+ return isAllowedByAllWithURL<&CSPDirectiveList::allowMediaFromSource>(m_policies, url, reportingStatus);
+}
+
+bool ContentSecurityPolicy::allowConnectToSource(const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
+{
+ return isAllowedByAllWithURL<&CSPDirectiveList::allowConnectToSource>(m_policies, url, reportingStatus);
+}
+
+bool ContentSecurityPolicy::allowFormAction(const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
+{
+ return isAllowedByAllWithURL<&CSPDirectiveList::allowFormAction>(m_policies, url, reportingStatus);
+}
+
+bool ContentSecurityPolicy::allowBaseURI(const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
+{
+ return isAllowedByAllWithURL<&CSPDirectiveList::allowBaseURI>(m_policies, url, reportingStatus);
+}
+
+bool ContentSecurityPolicy::isActive() const
+{
+ return !m_policies.isEmpty();
+}
+
+ReflectedXSSDisposition ContentSecurityPolicy::reflectedXSSDisposition() const
+{
+ ReflectedXSSDisposition disposition = ReflectedXSSUnset;
+ for (size_t i = 0; i < m_policies.size(); ++i) {
+ if (m_policies[i]->reflectedXSSDisposition() > disposition)
+ disposition = std::max(disposition, m_policies[i]->reflectedXSSDisposition());
+ }
+ return disposition;
+}
+
+void ContentSecurityPolicy::gatherReportURIs(DOMStringList& list) const
+{
+ for (size_t i = 0; i < m_policies.size(); ++i)
+ m_policies[i]->gatherReportURIs(list);
+}
+
+SecurityOrigin* ContentSecurityPolicy::securityOrigin() const
+{
+ return m_client->securityContext().securityOrigin();
+}
+
+const KURL ContentSecurityPolicy::url() const
+{
+ return m_client->contextURL();
+}
+
+KURL ContentSecurityPolicy::completeURL(const String& url) const
+{
+ return m_client->contextCompleteURL(url);
+}
+
+void ContentSecurityPolicy::enforceSandboxFlags(SandboxFlags mask) const
+{
+ if (m_client->isDocument())
+ static_cast<Document*>(m_client)->enforceSandboxFlags(mask);
+}
+
+static String stripURLForUseInReport(Document* document, const KURL& url)
+{
+ if (!url.isValid())
+ return String();
+ if (!url.isHierarchical() || url.protocolIs("file"))
+ return url.protocol();
+ return document->securityOrigin()->canRequest(url) ? url.strippedForUseAsReferrer() : SecurityOrigin::create(url)->toString();
+}
+
+static void gatherSecurityPolicyViolationEventData(SecurityPolicyViolationEventInit& init, Document* document, const String& directiveText, const String& effectiveDirective, const KURL& blockedURL, const String& header)
+{
+ init.documentURI = document->url().string();
+ init.referrer = document->referrer();
+ init.blockedURI = stripURLForUseInReport(document, blockedURL);
+ init.violatedDirective = directiveText;
+ init.effectiveDirective = effectiveDirective;
+ init.originalPolicy = header;
+ init.sourceFile = String();
+ init.lineNumber = 0;
+ init.columnNumber = 0;
+ init.statusCode = 0;
+
+ if (!SecurityOrigin::isSecure(document->url()) && document->loader())
+ init.statusCode = document->loader()->response().httpStatusCode();
+
+ RefPtr<ScriptCallStack> stack = createScriptCallStack(1, false);
+ if (!stack)
+ return;
+
+ const ScriptCallFrame& callFrame = stack->at(0);
+
+ if (callFrame.lineNumber()) {
+ KURL source = KURL(ParsedURLString, callFrame.sourceURL());
+ init.sourceFile = stripURLForUseInReport(document, source);
+ init.lineNumber = callFrame.lineNumber();
+ init.columnNumber = callFrame.columnNumber();
+ }
+}
+
+void ContentSecurityPolicy::reportViolation(const String& directiveText, const String& effectiveDirective, const String& consoleMessage, const KURL& blockedURL, const Vector<KURL>& reportURIs, const String& header)
+{
+ // FIXME: Support sending reports from worker.
+ if (!m_client->isDocument())
+ return;
+
+ Document* document = static_cast<Document*>(m_client);
+ Frame* frame = document->frame();
+ if (!frame)
+ return;
+
+ SecurityPolicyViolationEventInit violationData;
+ gatherSecurityPolicyViolationEventData(violationData, document, directiveText, effectiveDirective, blockedURL, header);
+
+ if (experimentalFeaturesEnabled())
+ frame->domWindow()->enqueueDocumentEvent(SecurityPolicyViolationEvent::create(EventTypeNames::securitypolicyviolation, violationData));
+
+ if (reportURIs.isEmpty())
+ return;
+
+ // We need to be careful here when deciding what information to send to the
+ // report-uri. Currently, we send only the current document's URL and the
+ // directive that was violated. The document's URL is safe to send because
+ // it's the document itself that's requesting that it be sent. You could
+ // make an argument that we shouldn't send HTTPS document URLs to HTTP
+ // report-uris (for the same reasons that we supress the Referer in that
+ // case), but the Referer is sent implicitly whereas this request is only
+ // sent explicitly. As for which directive was violated, that's pretty
+ // harmless information.
+
+ RefPtr<JSONObject> cspReport = JSONObject::create();
+ cspReport->setString("document-uri", violationData.documentURI);
+ cspReport->setString("referrer", violationData.referrer);
+ cspReport->setString("violated-directive", violationData.violatedDirective);
+ if (experimentalFeaturesEnabled())
+ cspReport->setString("effective-directive", violationData.effectiveDirective);
+ cspReport->setString("original-policy", violationData.originalPolicy);
+ cspReport->setString("blocked-uri", violationData.blockedURI);
+ if (!violationData.sourceFile.isEmpty() && violationData.lineNumber) {
+ cspReport->setString("source-file", violationData.sourceFile);
+ cspReport->setNumber("line-number", violationData.lineNumber);
+ cspReport->setNumber("column-number", violationData.columnNumber);
+ }
+ cspReport->setNumber("status-code", violationData.statusCode);
+
+ RefPtr<JSONObject> reportObject = JSONObject::create();
+ reportObject->setObject("csp-report", cspReport.release());
+ String stringifiedReport = reportObject->toJSONString();
+
+ if (!shouldSendViolationReport(stringifiedReport))
+ return;
+
+ RefPtr<FormData> report = FormData::create(stringifiedReport.utf8());
+
+ for (size_t i = 0; i < reportURIs.size(); ++i)
+ PingLoader::sendViolationReport(frame, reportURIs[i], report, PingLoader::ContentSecurityPolicyViolationReport);
+
+ didSendViolationReport(stringifiedReport);
+}
+
+void ContentSecurityPolicy::reportUnsupportedDirective(const String& name) const
+{
+ DEFINE_STATIC_LOCAL(String, allow, ("allow"));
+ DEFINE_STATIC_LOCAL(String, options, ("options"));
+ DEFINE_STATIC_LOCAL(String, policyURI, ("policy-uri"));
+ DEFINE_STATIC_LOCAL(String, allowMessage, ("The 'allow' directive has been replaced with 'default-src'. Please use that directive instead, as 'allow' has no effect."));
+ DEFINE_STATIC_LOCAL(String, optionsMessage, ("The 'options' directive has been replaced with 'unsafe-inline' and 'unsafe-eval' source expressions for the 'script-src' and 'style-src' directives. Please use those directives instead, as 'options' has no effect."));
+ DEFINE_STATIC_LOCAL(String, policyURIMessage, ("The 'policy-uri' directive has been removed from the specification. Please specify a complete policy via the Content-Security-Policy header."));
+
+ String message = "Unrecognized Content-Security-Policy directive '" + name + "'.\n";
+ if (equalIgnoringCase(name, allow))
+ message = allowMessage;
+ else if (equalIgnoringCase(name, options))
+ message = optionsMessage;
+ else if (equalIgnoringCase(name, policyURI))
+ message = policyURIMessage;
+
+ logToConsole(message);
+}
+
+void ContentSecurityPolicy::reportDirectiveAsSourceExpression(const String& directiveName, const String& sourceExpression) const
+{
+ String message = "The Content Security Policy directive '" + directiveName + "' contains '" + sourceExpression + "' as a source expression. Did you mean '" + directiveName + " ...; " + sourceExpression + "...' (note the semicolon)?";
+ logToConsole(message);
+}
+
+void ContentSecurityPolicy::reportDuplicateDirective(const String& name) const
+{
+ String message = "Ignoring duplicate Content-Security-Policy directive '" + name + "'.\n";
+ logToConsole(message);
+}
+
+void ContentSecurityPolicy::reportInvalidPluginTypes(const String& pluginType) const
+{
+ String message;
+ if (pluginType.isNull())
+ message = "'plugin-types' Content Security Policy directive is empty; all plugins will be blocked.\n";
+ else
+ message = "Invalid plugin type in 'plugin-types' Content Security Policy directive: '" + pluginType + "'.\n";
+ logToConsole(message);
+}
+
+void ContentSecurityPolicy::reportInvalidSandboxFlags(const String& invalidFlags) const
+{
+ logToConsole("Error while parsing the 'sandbox' Content Security Policy directive: " + invalidFlags);
+}
+
+void ContentSecurityPolicy::reportInvalidReflectedXSS(const String& invalidValue) const
+{
+ logToConsole("The 'reflected-xss' Content Security Policy directive has the invalid value \"" + invalidValue + "\". Valid values are \"allow\", \"filter\", and \"block\".");
+}
+
+void ContentSecurityPolicy::reportInvalidDirectiveValueCharacter(const String& directiveName, const String& value) const
+{
+ String message = "The value for Content Security Policy directive '" + directiveName + "' contains an invalid character: '" + value + "'. Non-whitespace characters outside ASCII 0x21-0x7E must be percent-encoded, as described in RFC 3986, section 2.1: http://tools.ietf.org/html/rfc3986#section-2.1.";
+ logToConsole(message);
+}
+
+void ContentSecurityPolicy::reportInvalidPathCharacter(const String& directiveName, const String& value, const char invalidChar) const
+{
+ ASSERT(invalidChar == '#' || invalidChar == '?');
+
+ String ignoring = "The fragment identifier, including the '#', will be ignored.";
+ if (invalidChar == '?')
+ ignoring = "The query component, including the '?', will be ignored.";
+ String message = "The source list for Content Security Policy directive '" + directiveName + "' contains a source with an invalid path: '" + value + "'. " + ignoring;
+ logToConsole(message);
+}
+
+void ContentSecurityPolicy::reportInvalidSourceExpression(const String& directiveName, const String& source) const
+{
+ String message = "The source list for Content Security Policy directive '" + directiveName + "' contains an invalid source: '" + source + "'. It will be ignored.";
+ if (equalIgnoringCase(source, "'none'"))
+ message = message + " Note that 'none' has no effect unless it is the only expression in the source list.";
+ logToConsole(message);
+}
+
+void ContentSecurityPolicy::reportMissingReportURI(const String& policy) const
+{
+ logToConsole("The Content Security Policy '" + policy + "' was delivered in report-only mode, but does not specify a 'report-uri'; the policy will have no effect. Please either add a 'report-uri' directive, or deliver the policy via the 'Content-Security-Policy' header.");
+}
+
+void ContentSecurityPolicy::logToConsole(const String& message) const
+{
+ m_client->addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, message);
+}
+
+void ContentSecurityPolicy::reportBlockedScriptExecutionToInspector(const String& directiveText) const
+{
+ m_client->reportBlockedScriptExecutionToInspector(directiveText);
+}
+
+bool ContentSecurityPolicy::experimentalFeaturesEnabled() const
+{
+ return RuntimeEnabledFeatures::experimentalContentSecurityPolicyFeaturesEnabled();
+}
+
+bool ContentSecurityPolicy::shouldBypassMainWorld(ExecutionContext* context)
+{
+ if (context && context->isDocument()) {
+ Document* document = toDocument(context);
+ if (document->frame())
+ return document->frame()->script().shouldBypassMainWorldContentSecurityPolicy();
+ }
+ return false;
+}
+
+bool ContentSecurityPolicy::shouldSendViolationReport(const String& report) const
+{
+ // Collisions have no security impact, so we can save space by storing only the string's hash rather than the whole report.
+ return !m_violationReportsSent.contains(report.impl()->hash());
+}
+
+void ContentSecurityPolicy::didSendViolationReport(const String& report)
+{
+ m_violationReportsSent.add(report.impl()->hash());
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/frame/ContentSecurityPolicy.h b/chromium/third_party/WebKit/Source/core/frame/ContentSecurityPolicy.h
new file mode 100644
index 00000000000..0720123a02d
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/ContentSecurityPolicy.h
@@ -0,0 +1,171 @@
+/*
+ * Copyright (C) 2011 Google, Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY GOOGLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef ContentSecurityPolicy_h
+#define ContentSecurityPolicy_h
+
+#include "bindings/v8/ScriptState.h"
+#include "platform/network/HTTPParsers.h"
+#include "wtf/HashSet.h"
+#include "wtf/PassOwnPtr.h"
+#include "wtf/Vector.h"
+#include "wtf/text/StringHash.h"
+#include "wtf/text/TextPosition.h"
+#include "wtf/text/WTFString.h"
+
+namespace WTF {
+class OrdinalNumber;
+}
+
+namespace WebCore {
+
+class ContentSecurityPolicyResponseHeaders;
+class CSPDirectiveList;
+class DOMStringList;
+class JSONObject;
+class KURL;
+class ExecutionContextClient;
+class SecurityOrigin;
+
+typedef int SandboxFlags;
+typedef Vector<OwnPtr<CSPDirectiveList> > CSPDirectiveListVector;
+
+class ContentSecurityPolicy {
+ WTF_MAKE_FAST_ALLOCATED;
+public:
+ static PassOwnPtr<ContentSecurityPolicy> create(ExecutionContextClient* client)
+ {
+ return adoptPtr(new ContentSecurityPolicy(client));
+ }
+ ~ContentSecurityPolicy();
+
+ void copyStateFrom(const ContentSecurityPolicy*);
+
+ enum HeaderType {
+ Report,
+ Enforce,
+ };
+
+ enum ReportingStatus {
+ SendReport,
+ SuppressReport
+ };
+
+ enum HashAlgorithms {
+ HashAlgorithmsNone = 0,
+ HashAlgorithmsSha1 = 1 << 1,
+ HashAlgorithmsSha256 = 1 << 2
+ };
+
+ void didReceiveHeaders(const ContentSecurityPolicyResponseHeaders&);
+ void didReceiveHeader(const String&, HeaderType);
+
+ // These functions are wrong because they assume that there is only one header.
+ // FIXME: Replace them with functions that return vectors.
+ const String& deprecatedHeader() const;
+ HeaderType deprecatedHeaderType() const;
+
+ bool allowJavaScriptURLs(const String& contextURL, const WTF::OrdinalNumber& contextLine, ReportingStatus = SendReport) const;
+ bool allowInlineEventHandlers(const String& contextURL, const WTF::OrdinalNumber& contextLine, ReportingStatus = SendReport) const;
+ bool allowInlineScript(const String& contextURL, const WTF::OrdinalNumber& contextLine, ReportingStatus = SendReport) const;
+ bool allowInlineStyle(const String& contextURL, const WTF::OrdinalNumber& contextLine, ReportingStatus = SendReport) const;
+ bool allowEval(ScriptState* = 0, ReportingStatus = SendReport) const;
+ bool allowPluginType(const String& type, const String& typeAttribute, const KURL&, ReportingStatus = SendReport) const;
+
+ bool allowScriptFromSource(const KURL&, ReportingStatus = SendReport) const;
+ bool allowObjectFromSource(const KURL&, ReportingStatus = SendReport) const;
+ bool allowChildFrameFromSource(const KURL&, ReportingStatus = SendReport) const;
+ bool allowImageFromSource(const KURL&, ReportingStatus = SendReport) const;
+ bool allowStyleFromSource(const KURL&, ReportingStatus = SendReport) const;
+ bool allowFontFromSource(const KURL&, ReportingStatus = SendReport) const;
+ bool allowMediaFromSource(const KURL&, ReportingStatus = SendReport) const;
+ bool allowConnectToSource(const KURL&, ReportingStatus = SendReport) const;
+ bool allowFormAction(const KURL&, ReportingStatus = SendReport) const;
+ bool allowBaseURI(const KURL&, ReportingStatus = SendReport) const;
+ // The nonce and hash allow functions are guaranteed to not have any side
+ // effects, including reporting.
+ bool allowScriptNonce(const String& nonce) const;
+ bool allowStyleNonce(const String& nonce) const;
+ bool allowScriptHash(const String& source) const;
+
+ void usesScriptHashAlgorithms(uint8_t HashAlgorithms);
+
+ ReflectedXSSDisposition reflectedXSSDisposition() const;
+
+ void setOverrideAllowInlineStyle(bool);
+
+ bool isActive() const;
+ void gatherReportURIs(DOMStringList&) const;
+
+ void reportDirectiveAsSourceExpression(const String& directiveName, const String& sourceExpression) const;
+ void reportDuplicateDirective(const String&) const;
+ void reportInvalidDirectiveValueCharacter(const String& directiveName, const String& value) const;
+ void reportInvalidPathCharacter(const String& directiveName, const String& value, const char) const;
+ void reportInvalidPluginTypes(const String&) const;
+ void reportInvalidSandboxFlags(const String&) const;
+ void reportInvalidSourceExpression(const String& directiveName, const String& source) const;
+ void reportInvalidReflectedXSS(const String&) const;
+ void reportMissingReportURI(const String&) const;
+ void reportUnsupportedDirective(const String&) const;
+ void reportViolation(const String& directiveText, const String& effectiveDirective, const String& consoleMessage, const KURL& blockedURL, const Vector<KURL>& reportURIs, const String& header);
+
+ void reportBlockedScriptExecutionToInspector(const String& directiveText) const;
+
+ const KURL url() const;
+ KURL completeURL(const String&) const;
+ SecurityOrigin* securityOrigin() const;
+ void enforceSandboxFlags(SandboxFlags) const;
+ String evalDisabledErrorMessage() const;
+
+ bool experimentalFeaturesEnabled() const;
+
+ static bool shouldBypassMainWorld(ExecutionContext*);
+
+ ExecutionContextClient* client() { return m_client; }
+
+private:
+ explicit ContentSecurityPolicy(ExecutionContextClient*);
+
+ void logToConsole(const String& message) const;
+ void addPolicyFromHeaderValue(const String&, HeaderType);
+
+ bool shouldSendViolationReport(const String&) const;
+ void didSendViolationReport(const String&);
+
+ ExecutionContextClient* m_client;
+ bool m_overrideInlineStyleAllowed;
+ CSPDirectiveListVector m_policies;
+
+ HashSet<unsigned, AlreadyHashed> m_violationReportsSent;
+
+ // We put the hash functions used on the policy object so that we only need
+ // to calculate a script hash once and then distribute it to all of the
+ // directives for validation.
+ uint8_t m_sourceHashAlgorithmsUsed;
+};
+
+}
+
+#endif
diff --git a/chromium/third_party/WebKit/Source/core/frame/ContentSecurityPolicyResponseHeaders.cpp b/chromium/third_party/WebKit/Source/core/frame/ContentSecurityPolicyResponseHeaders.cpp
new file mode 100644
index 00000000000..1b58eac6c72
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/ContentSecurityPolicyResponseHeaders.cpp
@@ -0,0 +1,41 @@
+/*
+ * Copyright (C) 2013 Google, Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY GOOGLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/frame/ContentSecurityPolicyResponseHeaders.h"
+
+#include "platform/network/ResourceResponse.h"
+
+namespace WebCore {
+
+ContentSecurityPolicyResponseHeaders::ContentSecurityPolicyResponseHeaders(const ResourceResponse& response)
+ : m_contentSecurityPolicy(response.httpHeaderField("Content-Security-Policy"))
+ , m_contentSecurityPolicyReportOnly(response.httpHeaderField("Content-Security-Policy-Report-Only"))
+ , m_xWebKitCSP(response.httpHeaderField("X-WebKit-CSP"))
+ , m_xWebKitCSPReportOnly(response.httpHeaderField("X-WebKit-CSP-Report-Only"))
+{
+}
+
+}
diff --git a/chromium/third_party/WebKit/Source/core/page/ContentSecurityPolicyResponseHeaders.h b/chromium/third_party/WebKit/Source/core/frame/ContentSecurityPolicyResponseHeaders.h
index d5076d4a062..d5076d4a062 100644
--- a/chromium/third_party/WebKit/Source/core/page/ContentSecurityPolicyResponseHeaders.h
+++ b/chromium/third_party/WebKit/Source/core/frame/ContentSecurityPolicyResponseHeaders.h
diff --git a/chromium/third_party/WebKit/Source/core/frame/DOMPoint.h b/chromium/third_party/WebKit/Source/core/frame/DOMPoint.h
new file mode 100644
index 00000000000..ae8478b25af
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/DOMPoint.h
@@ -0,0 +1,66 @@
+/*
+ * Copyright (C) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef DOMPoint_h
+#define DOMPoint_h
+
+#include "bindings/v8/ScriptWrappable.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefCounted.h"
+
+namespace WebCore {
+
+class DOMPoint : public RefCounted<DOMPoint>, public ScriptWrappable {
+public:
+ static PassRefPtr<DOMPoint> create()
+ {
+ return adoptRef(new DOMPoint());
+ }
+ static PassRefPtr<DOMPoint> create(float x, float y)
+ {
+ return adoptRef(new DOMPoint(x, y));
+ }
+
+ float x() const { return m_x; }
+ float y() const { return m_y; }
+
+ void setX(float x) { m_x = x; }
+ void setY(float y) { m_y = y; }
+
+private:
+ DOMPoint(float x = 0, float y = 0)
+ : m_x(x)
+ , m_y(y)
+ {
+ ScriptWrappable::init(this);
+ }
+
+ float m_x;
+ float m_y;
+};
+
+} // namespace WebCore
+
+#endif // DOMPoint_h
diff --git a/chromium/third_party/WebKit/Source/core/frame/DOMSecurityPolicy.cpp b/chromium/third_party/WebKit/Source/core/frame/DOMSecurityPolicy.cpp
new file mode 100644
index 00000000000..c60cdadc168
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/DOMSecurityPolicy.cpp
@@ -0,0 +1,174 @@
+/*
+ * Copyright (C) 2012 Google, Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY GOOGLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/frame/DOMSecurityPolicy.h"
+
+#include "core/dom/DOMStringList.h"
+#include "core/dom/ExecutionContext.h"
+#include "core/frame/ContentSecurityPolicy.h"
+#include "wtf/text/TextPosition.h"
+
+namespace WebCore {
+
+namespace {
+
+bool isPolicyActiveInContext(ExecutionContext* context)
+{
+ // If the ExecutionContext has been destroyed, there's no active policy.
+ if (!context)
+ return false;
+
+ return context->contentSecurityPolicy()->isActive();
+}
+
+template<bool (ContentSecurityPolicy::*allowWithType)(const String&, const String&, const KURL&, ContentSecurityPolicy::ReportingStatus) const>
+bool isAllowedWithType(ExecutionContext* context, const String& type)
+{
+ if (!isPolicyActiveInContext(context))
+ return true;
+
+ return (context->contentSecurityPolicy()->*allowWithType)(type, type, KURL(), ContentSecurityPolicy::SuppressReport);
+}
+
+template<bool (ContentSecurityPolicy::*allowWithURL)(const KURL&, ContentSecurityPolicy::ReportingStatus) const>
+bool isAllowedWithURL(ExecutionContext* context, const String& url)
+{
+ if (!isPolicyActiveInContext(context))
+ return true;
+
+ KURL parsedURL = context->completeURL(url);
+ if (!parsedURL.isValid())
+ return false; // FIXME: Figure out how to throw a JavaScript error.
+
+ return (context->contentSecurityPolicy()->*allowWithURL)(parsedURL, ContentSecurityPolicy::SuppressReport);
+}
+
+template<bool (ContentSecurityPolicy::*allowWithContext)(const String&, const WTF::OrdinalNumber&, ContentSecurityPolicy::ReportingStatus) const>
+bool isAllowed(ExecutionContext* context)
+{
+ if (!isPolicyActiveInContext(context))
+ return true;
+
+ return (context->contentSecurityPolicy()->*allowWithContext)(String(), WTF::OrdinalNumber::beforeFirst(), ContentSecurityPolicy::SuppressReport);
+}
+
+} // namespace
+
+DOMSecurityPolicy::DOMSecurityPolicy(ExecutionContext* context)
+ : ContextLifecycleObserver(context)
+{
+ ScriptWrappable::init(this);
+}
+
+DOMSecurityPolicy::~DOMSecurityPolicy()
+{
+}
+
+bool DOMSecurityPolicy::isActive() const
+{
+ return isPolicyActiveInContext(executionContext());
+}
+
+PassRefPtr<DOMStringList> DOMSecurityPolicy::reportURIs() const
+{
+ RefPtr<DOMStringList> result = DOMStringList::create();
+
+ if (isActive())
+ executionContext()->contentSecurityPolicy()->gatherReportURIs(*result.get());
+
+ return result.release();
+}
+
+bool DOMSecurityPolicy::allowsInlineScript() const
+{
+ return isAllowed<&ContentSecurityPolicy::allowInlineScript>(executionContext());
+}
+
+bool DOMSecurityPolicy::allowsInlineStyle() const
+{
+ return isAllowed<&ContentSecurityPolicy::allowInlineStyle>(executionContext());
+}
+
+bool DOMSecurityPolicy::allowsEval() const
+{
+ if (!isActive())
+ return true;
+
+ return executionContext()->contentSecurityPolicy()->allowEval(0, ContentSecurityPolicy::SuppressReport);
+}
+
+
+bool DOMSecurityPolicy::allowsConnectionTo(const String& url) const
+{
+ return isAllowedWithURL<&ContentSecurityPolicy::allowConnectToSource>(executionContext(), url);
+}
+
+bool DOMSecurityPolicy::allowsFontFrom(const String& url) const
+{
+ return isAllowedWithURL<&ContentSecurityPolicy::allowFontFromSource>(executionContext(), url);
+}
+
+bool DOMSecurityPolicy::allowsFormAction(const String& url) const
+{
+ return isAllowedWithURL<&ContentSecurityPolicy::allowFormAction>(executionContext(), url);
+}
+
+bool DOMSecurityPolicy::allowsFrameFrom(const String& url) const
+{
+ return isAllowedWithURL<&ContentSecurityPolicy::allowChildFrameFromSource>(executionContext(), url);
+}
+
+bool DOMSecurityPolicy::allowsImageFrom(const String& url) const
+{
+ return isAllowedWithURL<&ContentSecurityPolicy::allowImageFromSource>(executionContext(), url);
+}
+
+bool DOMSecurityPolicy::allowsMediaFrom(const String& url) const
+{
+ return isAllowedWithURL<&ContentSecurityPolicy::allowMediaFromSource>(executionContext(), url);
+}
+
+bool DOMSecurityPolicy::allowsObjectFrom(const String& url) const
+{
+ return isAllowedWithURL<&ContentSecurityPolicy::allowObjectFromSource>(executionContext(), url);
+}
+
+bool DOMSecurityPolicy::allowsPluginType(const String& type) const
+{
+ return isAllowedWithType<&ContentSecurityPolicy::allowPluginType>(executionContext(), type);
+}
+
+bool DOMSecurityPolicy::allowsScriptFrom(const String& url) const
+{
+ return isAllowedWithURL<&ContentSecurityPolicy::allowScriptFromSource>(executionContext(), url);
+}
+
+bool DOMSecurityPolicy::allowsStyleFrom(const String& url) const
+{
+ return isAllowedWithURL<&ContentSecurityPolicy::allowStyleFromSource>(executionContext(), url);
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/frame/DOMSecurityPolicy.h b/chromium/third_party/WebKit/Source/core/frame/DOMSecurityPolicy.h
new file mode 100644
index 00000000000..78813013993
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/DOMSecurityPolicy.h
@@ -0,0 +1,72 @@
+/*
+ * Copyright (C) 2011 Google, Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY GOOGLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef DOMSecurityPolicy_h
+#define DOMSecurityPolicy_h
+
+#include "bindings/v8/ScriptWrappable.h"
+#include "core/dom/ContextLifecycleObserver.h"
+#include "wtf/RefCounted.h"
+#include "wtf/text/WTFString.h"
+
+namespace WebCore {
+
+class ContentSecurityPolicy;
+class DOMStringList;
+class Frame;
+
+class DOMSecurityPolicy : public RefCounted<DOMSecurityPolicy>, public ScriptWrappable, public ContextLifecycleObserver {
+public:
+ static PassRefPtr<DOMSecurityPolicy> create(ExecutionContext* context)
+ {
+ return adoptRef(new DOMSecurityPolicy(context));
+ }
+ ~DOMSecurityPolicy();
+
+ bool isActive() const;
+ PassRefPtr<DOMStringList> reportURIs() const;
+
+ bool allowsInlineScript() const;
+ bool allowsInlineStyle() const;
+ bool allowsEval() const;
+
+ bool allowsConnectionTo(const String& url) const;
+ bool allowsFontFrom(const String& url) const;
+ bool allowsFormAction(const String& url) const;
+ bool allowsFrameFrom(const String& url) const;
+ bool allowsImageFrom(const String& url) const;
+ bool allowsMediaFrom(const String& url) const;
+ bool allowsObjectFrom(const String& url) const;
+ bool allowsPluginType(const String& type) const;
+ bool allowsScriptFrom(const String& url) const;
+ bool allowsStyleFrom(const String& url) const;
+
+private:
+ explicit DOMSecurityPolicy(ExecutionContext*);
+};
+
+}
+
+#endif
diff --git a/chromium/third_party/WebKit/Source/core/frame/DOMTimer.cpp b/chromium/third_party/WebKit/Source/core/frame/DOMTimer.cpp
new file mode 100644
index 00000000000..a41845ddc25
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/DOMTimer.cpp
@@ -0,0 +1,200 @@
+/*
+ * Copyright (C) 2008 Apple Inc. All Rights Reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "config.h"
+#include "core/frame/DOMTimer.h"
+
+#include "core/dom/ExecutionContext.h"
+#include "core/inspector/InspectorInstrumentation.h"
+#include "wtf/CurrentTime.h"
+
+using namespace std;
+
+namespace WebCore {
+
+static const int maxIntervalForUserGestureForwarding = 1000; // One second matches Gecko.
+static const int maxTimerNestingLevel = 5;
+static const double oneMillisecond = 0.001;
+// Chromium uses a minimum timer interval of 4ms. We'd like to go
+// lower; however, there are poorly coded websites out there which do
+// create CPU-spinning loops. Using 4ms prevents the CPU from
+// spinning too busily and provides a balance between CPU spinning and
+// the smallest possible interval timer.
+static const double minimumInterval = 0.004;
+
+static int timerNestingLevel = 0;
+
+static inline bool shouldForwardUserGesture(int interval, int nestingLevel)
+{
+ return UserGestureIndicator::processingUserGesture()
+ && interval <= maxIntervalForUserGestureForwarding
+ && nestingLevel == 1; // Gestures should not be forwarded to nested timers.
+}
+
+double DOMTimer::hiddenPageAlignmentInterval()
+{
+ // Timers on hidden pages are aligned so that they fire once per
+ // second at most.
+ return 1.0;
+}
+
+double DOMTimer::visiblePageAlignmentInterval()
+{
+ // Alignment does not apply to timers on visible pages.
+ return 0;
+}
+
+int DOMTimer::install(ExecutionContext* context, PassOwnPtr<ScheduledAction> action, int timeout, bool singleShot)
+{
+ int timeoutID = context->installNewTimeout(action, timeout, singleShot);
+ InspectorInstrumentation::didInstallTimer(context, timeoutID, timeout, singleShot);
+ return timeoutID;
+}
+
+void DOMTimer::removeByID(ExecutionContext* context, int timeoutID)
+{
+ context->removeTimeoutByID(timeoutID);
+ InspectorInstrumentation::didRemoveTimer(context, timeoutID);
+}
+
+DOMTimer::DOMTimer(ExecutionContext* context, PassOwnPtr<ScheduledAction> action, int interval, bool singleShot, int timeoutID)
+ : SuspendableTimer(context)
+ , m_timeoutID(timeoutID)
+ , m_nestingLevel(timerNestingLevel + 1)
+ , m_action(action)
+{
+ ASSERT(timeoutID > 0);
+ if (shouldForwardUserGesture(interval, m_nestingLevel))
+ m_userGestureToken = UserGestureIndicator::currentToken();
+
+ double intervalMilliseconds = max(oneMillisecond, interval * oneMillisecond);
+ if (intervalMilliseconds < minimumInterval && m_nestingLevel >= maxTimerNestingLevel)
+ intervalMilliseconds = minimumInterval;
+ if (singleShot)
+ startOneShot(intervalMilliseconds);
+ else
+ startRepeating(intervalMilliseconds);
+}
+
+DOMTimer::~DOMTimer()
+{
+}
+
+int DOMTimer::timeoutID() const
+{
+ return m_timeoutID;
+}
+
+void DOMTimer::fired()
+{
+ ExecutionContext* context = executionContext();
+ timerNestingLevel = m_nestingLevel;
+ ASSERT(!context->activeDOMObjectsAreSuspended());
+ // Only the first execution of a multi-shot timer should get an affirmative user gesture indicator.
+ UserGestureIndicator gestureIndicator(m_userGestureToken.release());
+
+ InspectorInstrumentationCookie cookie = InspectorInstrumentation::willFireTimer(context, m_timeoutID);
+
+ // Simple case for non-one-shot timers.
+ if (isActive()) {
+ if (repeatInterval() && repeatInterval() < minimumInterval) {
+ m_nestingLevel++;
+ if (m_nestingLevel >= maxTimerNestingLevel)
+ augmentRepeatInterval(minimumInterval - repeatInterval());
+ }
+
+ // No access to member variables after this point, it can delete the timer.
+ m_action->execute(context);
+
+ InspectorInstrumentation::didFireTimer(cookie);
+
+ return;
+ }
+
+ // Delete timer before executing the action for one-shot timers.
+ OwnPtr<ScheduledAction> action = m_action.release();
+
+ // This timer is being deleted; no access to member variables allowed after this point.
+ context->removeTimeoutByID(m_timeoutID);
+
+ action->execute(context);
+
+ InspectorInstrumentation::didFireTimer(cookie);
+
+ timerNestingLevel = 0;
+}
+
+void DOMTimer::contextDestroyed()
+{
+ SuspendableTimer::contextDestroyed();
+}
+
+void DOMTimer::stop()
+{
+ SuspendableTimer::stop();
+ // Need to release JS objects potentially protected by ScheduledAction
+ // because they can form circular references back to the ExecutionContext
+ // which will cause a memory leak.
+ m_action.clear();
+}
+
+double DOMTimer::alignedFireTime(double fireTime) const
+{
+ double alignmentInterval = executionContext()->timerAlignmentInterval();
+ if (alignmentInterval) {
+ double currentTime = monotonicallyIncreasingTime();
+ if (fireTime <= currentTime)
+ return fireTime;
+
+ // When a repeating timer is scheduled for exactly the
+ // background page alignment interval, because it's impossible
+ // for the timer to be rescheduled instantaneously, it misses
+ // every other fire time. Avoid this by looking at the next
+ // fire time rounded both down and up.
+
+ double alignedTimeRoundedDown = floor(fireTime / alignmentInterval) * alignmentInterval;
+ double alignedTimeRoundedUp = ceil(fireTime / alignmentInterval) * alignmentInterval;
+
+ // If the version rounded down is in the past, discard it
+ // immediately.
+
+ if (alignedTimeRoundedDown <= currentTime)
+ return alignedTimeRoundedUp;
+
+ // Only use the rounded-down time if it's within a certain
+ // tolerance of the fire time. This avoids speeding up timers
+ // on background pages in the common case.
+
+ if (fireTime - alignedTimeRoundedDown < minimumInterval)
+ return alignedTimeRoundedDown;
+
+ return alignedTimeRoundedUp;
+ }
+
+ return fireTime;
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/frame/DOMTimer.h b/chromium/third_party/WebKit/Source/core/frame/DOMTimer.h
new file mode 100644
index 00000000000..95c094b0605
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/DOMTimer.h
@@ -0,0 +1,82 @@
+/*
+ * Copyright (C) 2008 Apple Inc. All Rights Reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#ifndef DOMTimer_h
+#define DOMTimer_h
+
+#include "bindings/v8/ScheduledAction.h"
+#include "core/frame/SuspendableTimer.h"
+#include "platform/UserGestureIndicator.h"
+#include "wtf/Compiler.h"
+#include "wtf/OwnPtr.h"
+#include "wtf/PassOwnPtr.h"
+
+namespace WebCore {
+
+class ExecutionContext;
+
+class DOMTimer : public SuspendableTimer {
+public:
+ // Creates a new timer owned by the ExecutionContext, starts it and returns its ID.
+ static int install(ExecutionContext*, PassOwnPtr<ScheduledAction>, int timeout, bool singleShot);
+ static void removeByID(ExecutionContext*, int timeoutID);
+
+ virtual ~DOMTimer();
+
+ int timeoutID() const;
+
+ // ActiveDOMObject
+ virtual void contextDestroyed() OVERRIDE;
+ virtual void stop() OVERRIDE;
+
+ // The following are essentially constants. All intervals are in seconds.
+ static double hiddenPageAlignmentInterval();
+ static double visiblePageAlignmentInterval();
+
+private:
+ friend class ExecutionContext; // For create().
+
+ // Should only be used by ExecutionContext.
+ static PassOwnPtr<DOMTimer> create(ExecutionContext* context, PassOwnPtr<ScheduledAction> action, int timeout, bool singleShot, int timeoutID)
+ {
+ return adoptPtr(new DOMTimer(context, action, timeout, singleShot, timeoutID));
+ }
+
+ DOMTimer(ExecutionContext*, PassOwnPtr<ScheduledAction>, int interval, bool singleShot, int timeoutID);
+ virtual void fired();
+
+ // Retuns timer fire time rounded to the next multiple of timer alignment interval.
+ virtual double alignedFireTime(double) const;
+
+ int m_timeoutID;
+ int m_nestingLevel;
+ OwnPtr<ScheduledAction> m_action;
+ RefPtr<UserGestureToken> m_userGestureToken;
+};
+
+} // namespace WebCore
+
+#endif // DOMTimer_h
diff --git a/chromium/third_party/WebKit/Source/core/frame/DOMWindow.cpp b/chromium/third_party/WebKit/Source/core/frame/DOMWindow.cpp
new file mode 100644
index 00000000000..bc36d37e3fe
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/DOMWindow.cpp
@@ -0,0 +1,1890 @@
+/*
+ * Copyright (C) 2006, 2007, 2008, 2010 Apple Inc. All rights reserved.
+ * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/frame/DOMWindow.h"
+
+#include <algorithm>
+#include "RuntimeEnabledFeatures.h"
+#include "bindings/v8/ExceptionMessages.h"
+#include "bindings/v8/ExceptionState.h"
+#include "bindings/v8/ExceptionStatePlaceholder.h"
+#include "bindings/v8/ScriptCallStackFactory.h"
+#include "bindings/v8/ScriptController.h"
+#include "bindings/v8/SerializedScriptValue.h"
+#include "core/css/CSSComputedStyleDeclaration.h"
+#include "core/css/CSSRuleList.h"
+#include "core/css/DOMWindowCSS.h"
+#include "core/css/MediaQueryList.h"
+#include "core/css/MediaQueryMatcher.h"
+#include "core/css/StyleMedia.h"
+#include "core/css/resolver/StyleResolver.h"
+#include "core/dom/ContextFeatures.h"
+#include "core/dom/DOMImplementation.h"
+#include "core/dom/Document.h"
+#include "core/dom/Element.h"
+#include "core/dom/ExceptionCode.h"
+#include "core/dom/ExecutionContext.h"
+#include "core/dom/RequestAnimationFrameCallback.h"
+#include "core/editing/Editor.h"
+#include "core/events/DOMWindowEventQueue.h"
+#include "core/events/EventListener.h"
+#include "core/events/HashChangeEvent.h"
+#include "core/events/MessageEvent.h"
+#include "core/events/PageTransitionEvent.h"
+#include "core/events/PopStateEvent.h"
+#include "core/events/ThreadLocalEventNames.h"
+#include "core/frame/BarProp.h"
+#include "core/frame/Console.h"
+#include "core/frame/DOMPoint.h"
+#include "core/frame/DOMWindowLifecycleNotifier.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
+#include "core/frame/History.h"
+#include "core/frame/Location.h"
+#include "core/frame/Navigator.h"
+#include "core/frame/Screen.h"
+#include "core/frame/Settings.h"
+#include "core/html/HTMLFrameOwnerElement.h"
+#include "core/inspector/InspectorInstrumentation.h"
+#include "core/inspector/ScriptCallStack.h"
+#include "core/loader/DocumentLoader.h"
+#include "core/loader/FrameLoadRequest.h"
+#include "core/loader/FrameLoader.h"
+#include "core/loader/FrameLoaderClient.h"
+#include "core/loader/SinkDocument.h"
+#include "core/loader/appcache/ApplicationCache.h"
+#include "core/page/BackForwardClient.h"
+#include "core/page/Chrome.h"
+#include "core/page/ChromeClient.h"
+#include "core/page/CreateWindow.h"
+#include "core/page/EventHandler.h"
+#include "core/page/FrameTree.h"
+#include "core/page/Page.h"
+#include "core/page/PageConsole.h"
+#include "core/page/PageGroup.h"
+#include "core/page/WindowFeatures.h"
+#include "core/page/WindowFocusAllowedIndicator.h"
+#include "core/page/scrolling/ScrollingCoordinator.h"
+#include "core/storage/Storage.h"
+#include "core/storage/StorageArea.h"
+#include "core/storage/StorageNamespace.h"
+#include "core/timing/Performance.h"
+#include "platform/PlatformScreen.h"
+#include "platform/UserGestureIndicator.h"
+#include "platform/geometry/FloatRect.h"
+#include "platform/graphics/media/MediaPlayer.h"
+#include "platform/weborigin/KURL.h"
+#include "platform/weborigin/SecurityOrigin.h"
+#include "platform/weborigin/SecurityPolicy.h"
+#include "public/platform/Platform.h"
+#include "wtf/MainThread.h"
+#include "wtf/MathExtras.h"
+#include "wtf/text/WTFString.h"
+
+using std::min;
+using std::max;
+
+namespace WebCore {
+
+class PostMessageTimer : public TimerBase {
+public:
+ PostMessageTimer(DOMWindow* window, PassRefPtr<SerializedScriptValue> message, const String& sourceOrigin, PassRefPtr<DOMWindow> source, PassOwnPtr<MessagePortChannelArray> channels, SecurityOrigin* targetOrigin, PassRefPtr<ScriptCallStack> stackTrace)
+ : m_window(window)
+ , m_message(message)
+ , m_origin(sourceOrigin)
+ , m_source(source)
+ , m_channels(channels)
+ , m_targetOrigin(targetOrigin)
+ , m_stackTrace(stackTrace)
+ {
+ }
+
+ PassRefPtr<MessageEvent> event()
+ {
+ return MessageEvent::create(m_channels.release(), m_message, m_origin, String(), m_source);
+
+ }
+ SecurityOrigin* targetOrigin() const { return m_targetOrigin.get(); }
+ ScriptCallStack* stackTrace() const { return m_stackTrace.get(); }
+
+private:
+ virtual void fired()
+ {
+ m_window->postMessageTimerFired(adoptPtr(this));
+ // This object is deleted now.
+ }
+
+ RefPtr<DOMWindow> m_window;
+ RefPtr<SerializedScriptValue> m_message;
+ String m_origin;
+ RefPtr<DOMWindow> m_source;
+ OwnPtr<MessagePortChannelArray> m_channels;
+ RefPtr<SecurityOrigin> m_targetOrigin;
+ RefPtr<ScriptCallStack> m_stackTrace;
+};
+
+static void disableSuddenTermination()
+{
+ blink::Platform::current()->suddenTerminationChanged(false);
+}
+
+static void enableSuddenTermination()
+{
+ blink::Platform::current()->suddenTerminationChanged(true);
+}
+
+typedef HashCountedSet<DOMWindow*> DOMWindowSet;
+
+static DOMWindowSet& windowsWithUnloadEventListeners()
+{
+ DEFINE_STATIC_LOCAL(DOMWindowSet, windowsWithUnloadEventListeners, ());
+ return windowsWithUnloadEventListeners;
+}
+
+static DOMWindowSet& windowsWithBeforeUnloadEventListeners()
+{
+ DEFINE_STATIC_LOCAL(DOMWindowSet, windowsWithBeforeUnloadEventListeners, ());
+ return windowsWithBeforeUnloadEventListeners;
+}
+
+static void addUnloadEventListener(DOMWindow* domWindow)
+{
+ DOMWindowSet& set = windowsWithUnloadEventListeners();
+ if (set.isEmpty())
+ disableSuddenTermination();
+ set.add(domWindow);
+}
+
+static void removeUnloadEventListener(DOMWindow* domWindow)
+{
+ DOMWindowSet& set = windowsWithUnloadEventListeners();
+ DOMWindowSet::iterator it = set.find(domWindow);
+ if (it == set.end())
+ return;
+ set.remove(it);
+ if (set.isEmpty())
+ enableSuddenTermination();
+}
+
+static void removeAllUnloadEventListeners(DOMWindow* domWindow)
+{
+ DOMWindowSet& set = windowsWithUnloadEventListeners();
+ DOMWindowSet::iterator it = set.find(domWindow);
+ if (it == set.end())
+ return;
+ set.removeAll(it);
+ if (set.isEmpty())
+ enableSuddenTermination();
+}
+
+static void addBeforeUnloadEventListener(DOMWindow* domWindow)
+{
+ DOMWindowSet& set = windowsWithBeforeUnloadEventListeners();
+ if (set.isEmpty())
+ disableSuddenTermination();
+ set.add(domWindow);
+}
+
+static void removeBeforeUnloadEventListener(DOMWindow* domWindow)
+{
+ DOMWindowSet& set = windowsWithBeforeUnloadEventListeners();
+ DOMWindowSet::iterator it = set.find(domWindow);
+ if (it == set.end())
+ return;
+ set.remove(it);
+ if (set.isEmpty())
+ enableSuddenTermination();
+}
+
+static void removeAllBeforeUnloadEventListeners(DOMWindow* domWindow)
+{
+ DOMWindowSet& set = windowsWithBeforeUnloadEventListeners();
+ DOMWindowSet::iterator it = set.find(domWindow);
+ if (it == set.end())
+ return;
+ set.removeAll(it);
+ if (set.isEmpty())
+ enableSuddenTermination();
+}
+
+static bool allowsBeforeUnloadListeners(DOMWindow* window)
+{
+ ASSERT_ARG(window, window);
+ Frame* frame = window->frame();
+ if (!frame)
+ return false;
+ return frame->isMainFrame();
+}
+
+unsigned DOMWindow::pendingUnloadEventListeners() const
+{
+ return windowsWithUnloadEventListeners().count(const_cast<DOMWindow*>(this));
+}
+
+// This function:
+// 1) Validates the pending changes are not changing any value to NaN; in that case keep original value.
+// 2) Constrains the window rect to the minimum window size and no bigger than the float rect's dimensions.
+// 3) Constrains the window rect to within the top and left boundaries of the available screen rect.
+// 4) Constrains the window rect to within the bottom and right boundaries of the available screen rect.
+// 5) Translate the window rect coordinates to be within the coordinate space of the screen.
+FloatRect DOMWindow::adjustWindowRect(Page* page, const FloatRect& pendingChanges)
+{
+ ASSERT(page);
+
+ FloatRect screen = screenAvailableRect(page->mainFrame()->view());
+ FloatRect window = page->chrome().windowRect();
+
+ // Make sure we're in a valid state before adjusting dimensions.
+ ASSERT(std::isfinite(screen.x()));
+ ASSERT(std::isfinite(screen.y()));
+ ASSERT(std::isfinite(screen.width()));
+ ASSERT(std::isfinite(screen.height()));
+ ASSERT(std::isfinite(window.x()));
+ ASSERT(std::isfinite(window.y()));
+ ASSERT(std::isfinite(window.width()));
+ ASSERT(std::isfinite(window.height()));
+
+ // Update window values if new requested values are not NaN.
+ if (!std::isnan(pendingChanges.x()))
+ window.setX(pendingChanges.x());
+ if (!std::isnan(pendingChanges.y()))
+ window.setY(pendingChanges.y());
+ if (!std::isnan(pendingChanges.width()))
+ window.setWidth(pendingChanges.width());
+ if (!std::isnan(pendingChanges.height()))
+ window.setHeight(pendingChanges.height());
+
+ FloatSize minimumSize = page->chrome().client().minimumWindowSize();
+ // Let size 0 pass through, since that indicates default size, not minimum size.
+ if (window.width())
+ window.setWidth(min(max(minimumSize.width(), window.width()), screen.width()));
+ if (window.height())
+ window.setHeight(min(max(minimumSize.height(), window.height()), screen.height()));
+
+ // Constrain the window position within the valid screen area.
+ window.setX(max(screen.x(), min(window.x(), screen.maxX() - window.width())));
+ window.setY(max(screen.y(), min(window.y(), screen.maxY() - window.height())));
+
+ return window;
+}
+
+bool DOMWindow::allowPopUp(Frame* firstFrame)
+{
+ ASSERT(firstFrame);
+
+ if (UserGestureIndicator::processingUserGesture())
+ return true;
+
+ Settings* settings = firstFrame->settings();
+ return settings && settings->javaScriptCanOpenWindowsAutomatically();
+}
+
+bool DOMWindow::allowPopUp()
+{
+ return m_frame && allowPopUp(m_frame);
+}
+
+bool DOMWindow::canShowModalDialog(const Frame* frame)
+{
+ if (!frame)
+ return false;
+ Page* page = frame->page();
+ if (!page)
+ return false;
+ return page->chrome().canRunModal();
+}
+
+bool DOMWindow::canShowModalDialogNow(const Frame* frame)
+{
+ if (!frame)
+ return false;
+ Page* page = frame->page();
+ if (!page)
+ return false;
+ return page->chrome().canRunModalNow();
+}
+
+DOMWindow::DOMWindow(Frame* frame)
+ : FrameDestructionObserver(frame)
+ , m_shouldPrintWhenFinishedLoading(false)
+{
+ ASSERT(frame);
+ ScriptWrappable::init(this);
+}
+
+void DOMWindow::clearDocument()
+{
+ if (!m_document)
+ return;
+
+ if (m_document->isActive()) {
+ // FIXME: We don't call willRemove here. Why is that OK?
+ // This detach() call is also mostly redundant. Most of the calls to
+ // this function come via DocumentLoader::createWriterFor, which
+ // always detaches the previous Document first. Only XSLTProcessor
+ // depends on this detach() call, so it seems like there's some room
+ // for cleanup.
+ m_document->detach();
+ }
+
+ // FIXME: This should be part of ActiveDOM Object shutdown
+ clearEventQueue();
+
+ m_document->clearDOMWindow();
+ m_document = 0;
+}
+
+void DOMWindow::clearEventQueue()
+{
+ if (!m_eventQueue)
+ return;
+ m_eventQueue->close();
+ m_eventQueue.clear();
+}
+
+PassRefPtr<Document> DOMWindow::createDocument(const String& mimeType, const DocumentInit& init, bool forceXHTML)
+{
+ RefPtr<Document> document;
+ if (forceXHTML) {
+ // This is a hack for XSLTProcessor. See XSLTProcessor::createDocumentFromSource().
+ document = Document::create(init);
+ } else {
+ document = DOMImplementation::createDocument(mimeType, init, init.frame() ? init.frame()->inViewSourceMode() : false);
+ if (document->isPluginDocument() && document->isSandboxed(SandboxPlugins))
+ document = SinkDocument::create(init);
+ }
+
+ return document.release();
+}
+
+PassRefPtr<Document> DOMWindow::installNewDocument(const String& mimeType, const DocumentInit& init, bool forceXHTML)
+{
+ ASSERT(init.frame() == m_frame);
+
+ clearDocument();
+
+ m_document = createDocument(mimeType, init, forceXHTML);
+ m_eventQueue = DOMWindowEventQueue::create(m_document.get());
+ m_document->attach();
+
+ if (!m_frame)
+ return m_document;
+
+ m_frame->script().updateDocument();
+ m_document->updateViewportDescription();
+
+ if (m_frame->page() && m_frame->view()) {
+ if (ScrollingCoordinator* scrollingCoordinator = m_frame->page()->scrollingCoordinator()) {
+ scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(m_frame->view(), HorizontalScrollbar);
+ scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(m_frame->view(), VerticalScrollbar);
+ scrollingCoordinator->scrollableAreaScrollLayerDidChange(m_frame->view());
+ }
+ }
+
+ m_frame->selection().updateSecureKeyboardEntryIfActive();
+
+ if (m_frame->isMainFrame()) {
+ m_frame->page()->mainFrame()->notifyChromeClientWheelEventHandlerCountChanged();
+ if (m_document->hasTouchEventHandlers())
+ m_frame->page()->chrome().client().needTouchEvents(true);
+ }
+
+ return m_document;
+}
+
+EventQueue* DOMWindow::eventQueue() const
+{
+ return m_eventQueue.get();
+}
+
+void DOMWindow::enqueueWindowEvent(PassRefPtr<Event> event)
+{
+ if (!m_eventQueue)
+ return;
+ event->setTarget(this);
+ m_eventQueue->enqueueEvent(event);
+}
+
+void DOMWindow::enqueueDocumentEvent(PassRefPtr<Event> event)
+{
+ if (!m_eventQueue)
+ return;
+ event->setTarget(m_document);
+ m_eventQueue->enqueueEvent(event);
+}
+
+void DOMWindow::dispatchWindowLoadEvent()
+{
+ ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
+ dispatchLoadEvent();
+}
+
+void DOMWindow::documentWasClosed()
+{
+ dispatchWindowLoadEvent();
+ enqueuePageshowEvent(PageshowEventNotPersisted);
+ enqueuePopstateEvent(m_pendingStateObject ? m_pendingStateObject.release() : SerializedScriptValue::nullValue());
+}
+
+void DOMWindow::enqueuePageshowEvent(PageshowEventPersistence persisted)
+{
+ // FIXME: https://bugs.webkit.org/show_bug.cgi?id=36334 Pageshow event needs to fire asynchronously.
+ dispatchEvent(PageTransitionEvent::create(EventTypeNames::pageshow, persisted), m_document.get());
+}
+
+void DOMWindow::enqueueHashchangeEvent(const String& oldURL, const String& newURL)
+{
+ enqueueWindowEvent(HashChangeEvent::create(oldURL, newURL));
+}
+
+void DOMWindow::enqueuePopstateEvent(PassRefPtr<SerializedScriptValue> stateObject)
+{
+ if (!ContextFeatures::pushStateEnabled(document()))
+ return;
+
+ // FIXME: https://bugs.webkit.org/show_bug.cgi?id=36202 Popstate event needs to fire asynchronously
+ dispatchEvent(PopStateEvent::create(stateObject, history()));
+}
+
+void DOMWindow::statePopped(PassRefPtr<SerializedScriptValue> stateObject)
+{
+ if (!frame())
+ return;
+
+ // Per step 11 of section 6.5.9 (history traversal) of the HTML5 spec, we
+ // defer firing of popstate until we're in the complete state.
+ if (document()->isLoadCompleted())
+ enqueuePopstateEvent(stateObject);
+ else
+ m_pendingStateObject = stateObject;
+}
+
+DOMWindow::~DOMWindow()
+{
+ ASSERT(!m_screen);
+ ASSERT(!m_history);
+ ASSERT(!m_locationbar);
+ ASSERT(!m_menubar);
+ ASSERT(!m_personalbar);
+ ASSERT(!m_scrollbars);
+ ASSERT(!m_statusbar);
+ ASSERT(!m_toolbar);
+ ASSERT(!m_console);
+ ASSERT(!m_navigator);
+ ASSERT(!m_performance);
+ ASSERT(!m_location);
+ ASSERT(!m_media);
+ ASSERT(!m_sessionStorage);
+ ASSERT(!m_localStorage);
+ ASSERT(!m_applicationCache);
+
+ reset();
+
+ removeAllEventListeners();
+
+ ASSERT(m_document->isStopped());
+ clearDocument();
+}
+
+const AtomicString& DOMWindow::interfaceName() const
+{
+ return EventTargetNames::DOMWindow;
+}
+
+ExecutionContext* DOMWindow::executionContext() const
+{
+ return m_document.get();
+}
+
+DOMWindow* DOMWindow::toDOMWindow()
+{
+ return this;
+}
+
+PassRefPtr<MediaQueryList> DOMWindow::matchMedia(const String& media)
+{
+ return document() ? document()->mediaQueryMatcher().matchMedia(media) : 0;
+}
+
+Page* DOMWindow::page()
+{
+ return frame() ? frame()->page() : 0;
+}
+
+void DOMWindow::frameDestroyed()
+{
+ FrameDestructionObserver::frameDestroyed();
+ reset();
+}
+
+void DOMWindow::willDetachPage()
+{
+ InspectorInstrumentation::frameWindowDiscarded(m_frame, this);
+}
+
+void DOMWindow::willDestroyDocumentInFrame()
+{
+ // It is necessary to copy m_properties to a separate vector because the DOMWindowProperties may
+ // unregister themselves from the DOMWindow as a result of the call to willDestroyGlobalObjectInFrame.
+ Vector<DOMWindowProperty*> properties;
+ copyToVector(m_properties, properties);
+ for (size_t i = 0; i < properties.size(); ++i)
+ properties[i]->willDestroyGlobalObjectInFrame();
+}
+
+void DOMWindow::willDetachDocumentFromFrame()
+{
+ // It is necessary to copy m_properties to a separate vector because the DOMWindowProperties may
+ // unregister themselves from the DOMWindow as a result of the call to willDetachGlobalObjectFromFrame.
+ Vector<DOMWindowProperty*> properties;
+ copyToVector(m_properties, properties);
+ for (size_t i = 0; i < properties.size(); ++i)
+ properties[i]->willDetachGlobalObjectFromFrame();
+}
+
+void DOMWindow::registerProperty(DOMWindowProperty* property)
+{
+ m_properties.add(property);
+}
+
+void DOMWindow::unregisterProperty(DOMWindowProperty* property)
+{
+ m_properties.remove(property);
+}
+
+void DOMWindow::reset()
+{
+ willDestroyDocumentInFrame();
+ resetDOMWindowProperties();
+}
+
+void DOMWindow::resetDOMWindowProperties()
+{
+ m_properties.clear();
+
+ m_screen = 0;
+ m_history = 0;
+ m_locationbar = 0;
+ m_menubar = 0;
+ m_personalbar = 0;
+ m_scrollbars = 0;
+ m_statusbar = 0;
+ m_toolbar = 0;
+ m_console = 0;
+ m_navigator = 0;
+ m_performance = 0;
+ m_location = 0;
+ m_media = 0;
+ m_sessionStorage = 0;
+ m_localStorage = 0;
+ m_applicationCache = 0;
+}
+
+bool DOMWindow::isCurrentlyDisplayedInFrame() const
+{
+ return m_frame && m_frame->domWindow() == this;
+}
+
+#if ENABLE(ORIENTATION_EVENTS)
+int DOMWindow::orientation() const
+{
+ if (!m_frame)
+ return 0;
+
+ return m_frame->orientation();
+}
+#endif
+
+Screen* DOMWindow::screen() const
+{
+ if (!isCurrentlyDisplayedInFrame())
+ return 0;
+ if (!m_screen)
+ m_screen = Screen::create(m_frame);
+ return m_screen.get();
+}
+
+History* DOMWindow::history() const
+{
+ if (!isCurrentlyDisplayedInFrame())
+ return 0;
+ if (!m_history)
+ m_history = History::create(m_frame);
+ return m_history.get();
+}
+
+BarProp* DOMWindow::locationbar() const
+{
+ UseCounter::count(this, UseCounter::BarPropLocationbar);
+ if (!isCurrentlyDisplayedInFrame())
+ return 0;
+ if (!m_locationbar)
+ m_locationbar = BarProp::create(m_frame, BarProp::Locationbar);
+ return m_locationbar.get();
+}
+
+BarProp* DOMWindow::menubar() const
+{
+ UseCounter::count(this, UseCounter::BarPropMenubar);
+ if (!isCurrentlyDisplayedInFrame())
+ return 0;
+ if (!m_menubar)
+ m_menubar = BarProp::create(m_frame, BarProp::Menubar);
+ return m_menubar.get();
+}
+
+BarProp* DOMWindow::personalbar() const
+{
+ UseCounter::count(this, UseCounter::BarPropPersonalbar);
+ if (!isCurrentlyDisplayedInFrame())
+ return 0;
+ if (!m_personalbar)
+ m_personalbar = BarProp::create(m_frame, BarProp::Personalbar);
+ return m_personalbar.get();
+}
+
+BarProp* DOMWindow::scrollbars() const
+{
+ UseCounter::count(this, UseCounter::BarPropScrollbars);
+ if (!isCurrentlyDisplayedInFrame())
+ return 0;
+ if (!m_scrollbars)
+ m_scrollbars = BarProp::create(m_frame, BarProp::Scrollbars);
+ return m_scrollbars.get();
+}
+
+BarProp* DOMWindow::statusbar() const
+{
+ UseCounter::count(this, UseCounter::BarPropStatusbar);
+ if (!isCurrentlyDisplayedInFrame())
+ return 0;
+ if (!m_statusbar)
+ m_statusbar = BarProp::create(m_frame, BarProp::Statusbar);
+ return m_statusbar.get();
+}
+
+BarProp* DOMWindow::toolbar() const
+{
+ UseCounter::count(this, UseCounter::BarPropToolbar);
+ if (!isCurrentlyDisplayedInFrame())
+ return 0;
+ if (!m_toolbar)
+ m_toolbar = BarProp::create(m_frame, BarProp::Toolbar);
+ return m_toolbar.get();
+}
+
+Console* DOMWindow::console() const
+{
+ if (!isCurrentlyDisplayedInFrame())
+ return 0;
+ if (!m_console)
+ m_console = Console::create(m_frame);
+ return m_console.get();
+}
+
+PageConsole* DOMWindow::pageConsole() const
+{
+ if (!isCurrentlyDisplayedInFrame())
+ return 0;
+ return m_frame->page() ? &m_frame->page()->console() : 0;
+}
+
+ApplicationCache* DOMWindow::applicationCache() const
+{
+ if (!isCurrentlyDisplayedInFrame())
+ return 0;
+ if (!m_applicationCache)
+ m_applicationCache = ApplicationCache::create(m_frame);
+ return m_applicationCache.get();
+}
+
+Navigator* DOMWindow::navigator() const
+{
+ if (!isCurrentlyDisplayedInFrame())
+ return 0;
+ if (!m_navigator)
+ m_navigator = Navigator::create(m_frame);
+ return m_navigator.get();
+}
+
+Performance* DOMWindow::performance() const
+{
+ if (!isCurrentlyDisplayedInFrame())
+ return 0;
+ if (!m_performance)
+ m_performance = Performance::create(m_frame);
+ return m_performance.get();
+}
+
+Location* DOMWindow::location() const
+{
+ if (!isCurrentlyDisplayedInFrame())
+ return 0;
+ if (!m_location)
+ m_location = Location::create(m_frame);
+ return m_location.get();
+}
+
+Storage* DOMWindow::sessionStorage(ExceptionState& exceptionState) const
+{
+ if (!isCurrentlyDisplayedInFrame())
+ return 0;
+
+ Document* document = this->document();
+ if (!document)
+ return 0;
+
+ String accessDeniedMessage = "Access is denied for this document.";
+ if (!document->securityOrigin()->canAccessLocalStorage()) {
+ if (document->isSandboxed(SandboxOrigin))
+ exceptionState.throwSecurityError("The document is sandboxed and lacks the 'allow-same-origin' flag.");
+ else if (document->url().protocolIs("data"))
+ exceptionState.throwSecurityError("Storage is disabled inside 'data:' URLs.");
+ else
+ exceptionState.throwSecurityError(accessDeniedMessage);
+ return 0;
+ }
+
+ if (m_sessionStorage) {
+ if (!m_sessionStorage->area()->canAccessStorage(m_frame)) {
+ exceptionState.throwSecurityError(accessDeniedMessage);
+ return 0;
+ }
+ return m_sessionStorage.get();
+ }
+
+ Page* page = document->page();
+ if (!page)
+ return 0;
+
+ OwnPtr<StorageArea> storageArea = page->sessionStorage()->storageArea(document->securityOrigin());
+ if (!storageArea->canAccessStorage(m_frame)) {
+ exceptionState.throwSecurityError(accessDeniedMessage);
+ return 0;
+ }
+
+ m_sessionStorage = Storage::create(m_frame, storageArea.release());
+ return m_sessionStorage.get();
+}
+
+Storage* DOMWindow::localStorage(ExceptionState& exceptionState) const
+{
+ if (!isCurrentlyDisplayedInFrame())
+ return 0;
+
+ Document* document = this->document();
+ if (!document)
+ return 0;
+
+ String accessDeniedMessage = "Access is denied for this document.";
+ if (!document->securityOrigin()->canAccessLocalStorage()) {
+ if (document->isSandboxed(SandboxOrigin))
+ exceptionState.throwSecurityError("The document is sandboxed and lacks the 'allow-same-origin' flag.");
+ else if (document->url().protocolIs("data"))
+ exceptionState.throwSecurityError("Storage is disabled inside 'data:' URLs.");
+ else
+ exceptionState.throwSecurityError(accessDeniedMessage);
+ return 0;
+ }
+
+ if (m_localStorage) {
+ if (!m_localStorage->area()->canAccessStorage(m_frame)) {
+ exceptionState.throwSecurityError(accessDeniedMessage);
+ return 0;
+ }
+ return m_localStorage.get();
+ }
+
+ Page* page = document->page();
+ if (!page)
+ return 0;
+
+ if (!page->settings().localStorageEnabled())
+ return 0;
+
+ OwnPtr<StorageArea> storageArea = StorageNamespace::localStorageArea(document->securityOrigin());
+ if (!storageArea->canAccessStorage(m_frame)) {
+ exceptionState.throwSecurityError(accessDeniedMessage);
+ return 0;
+ }
+
+ m_localStorage = Storage::create(m_frame, storageArea.release());
+ return m_localStorage.get();
+}
+
+void DOMWindow::postMessage(PassRefPtr<SerializedScriptValue> message, const MessagePortArray* ports, const String& targetOrigin, DOMWindow* source, ExceptionState& exceptionState)
+{
+ if (!isCurrentlyDisplayedInFrame())
+ return;
+
+ Document* sourceDocument = source->document();
+
+ // Compute the target origin. We need to do this synchronously in order
+ // to generate the SyntaxError exception correctly.
+ RefPtr<SecurityOrigin> target;
+ if (targetOrigin == "/") {
+ if (!sourceDocument)
+ return;
+ target = sourceDocument->securityOrigin();
+ } else if (targetOrigin != "*") {
+ target = SecurityOrigin::createFromString(targetOrigin);
+ // It doesn't make sense target a postMessage at a unique origin
+ // because there's no way to represent a unique origin in a string.
+ if (target->isUnique()) {
+ exceptionState.throwDOMException(SyntaxError, "Invalid target origin '" + targetOrigin + "' in a call to 'postMessage'.");
+ return;
+ }
+ }
+
+ OwnPtr<MessagePortChannelArray> channels = MessagePort::disentanglePorts(ports, exceptionState);
+ if (exceptionState.hadException())
+ return;
+
+ // Capture the source of the message. We need to do this synchronously
+ // in order to capture the source of the message correctly.
+ if (!sourceDocument)
+ return;
+ String sourceOrigin = sourceDocument->securityOrigin()->toString();
+
+ // Capture stack trace only when inspector front-end is loaded as it may be time consuming.
+ RefPtr<ScriptCallStack> stackTrace;
+ if (InspectorInstrumentation::consoleAgentEnabled(sourceDocument))
+ stackTrace = createScriptCallStack(ScriptCallStack::maxCallStackSizeToCapture, true);
+
+ // Schedule the message.
+ PostMessageTimer* timer = new PostMessageTimer(this, message, sourceOrigin, source, channels.release(), target.get(), stackTrace.release());
+ timer->startOneShot(0);
+}
+
+void DOMWindow::postMessageTimerFired(PassOwnPtr<PostMessageTimer> t)
+{
+ OwnPtr<PostMessageTimer> timer(t);
+
+ if (!document() || !isCurrentlyDisplayedInFrame())
+ return;
+
+ RefPtr<MessageEvent> event = timer->event();
+
+ // Give the embedder a chance to intercept this postMessage because this
+ // DOMWindow might be a proxy for another in browsers that support
+ // postMessage calls across WebKit instances.
+ if (m_frame->loader().client()->willCheckAndDispatchMessageEvent(timer->targetOrigin(), event.get()))
+ return;
+
+ event->entangleMessagePorts(document());
+ dispatchMessageEventWithOriginCheck(timer->targetOrigin(), event, timer->stackTrace());
+}
+
+void DOMWindow::dispatchMessageEventWithOriginCheck(SecurityOrigin* intendedTargetOrigin, PassRefPtr<Event> event, PassRefPtr<ScriptCallStack> stackTrace)
+{
+ if (intendedTargetOrigin) {
+ // Check target origin now since the target document may have changed since the timer was scheduled.
+ if (!intendedTargetOrigin->isSameSchemeHostPort(document()->securityOrigin())) {
+ String message = ExceptionMessages::failedToExecute("postMessage", "DOMWindow", "The target origin provided ('" + intendedTargetOrigin->toString() + "') does not match the recipient window's origin ('" + document()->securityOrigin()->toString() + "').");
+ pageConsole()->addMessage(SecurityMessageSource, ErrorMessageLevel, message, stackTrace);
+ return;
+ }
+ }
+
+ dispatchEvent(event);
+}
+
+DOMSelection* DOMWindow::getSelection()
+{
+ if (!isCurrentlyDisplayedInFrame() || !m_frame)
+ return 0;
+
+ return m_frame->document()->getSelection();
+}
+
+Element* DOMWindow::frameElement() const
+{
+ if (!m_frame)
+ return 0;
+
+ return m_frame->ownerElement();
+}
+
+void DOMWindow::focus(ExecutionContext* context)
+{
+ if (!m_frame)
+ return;
+
+ Page* page = m_frame->page();
+ if (!page)
+ return;
+
+ bool allowFocus = WindowFocusAllowedIndicator::windowFocusAllowed();
+ if (context) {
+ ASSERT(isMainThread());
+ Document* activeDocument = toDocument(context);
+ if (opener() && opener() != this && activeDocument->domWindow() == opener())
+ allowFocus = true;
+ }
+
+ // If we're a top level window, bring the window to the front.
+ if (m_frame->isMainFrame() && allowFocus)
+ page->chrome().focus();
+
+ if (!m_frame)
+ return;
+
+ m_frame->eventHandler().focusDocumentView();
+}
+
+void DOMWindow::blur()
+{
+}
+
+void DOMWindow::close(ExecutionContext* context)
+{
+ if (!m_frame)
+ return;
+
+ Page* page = m_frame->page();
+ if (!page)
+ return;
+
+ if (m_frame != page->mainFrame())
+ return;
+
+ if (context) {
+ ASSERT(isMainThread());
+ Document* activeDocument = toDocument(context);
+ if (!activeDocument)
+ return;
+
+ if (!activeDocument->canNavigate(m_frame))
+ return;
+ }
+
+ Settings* settings = m_frame->settings();
+ bool allowScriptsToCloseWindows = settings && settings->allowScriptsToCloseWindows();
+
+ if (!(page->openedByDOM() || page->backForward().backForwardListCount() <= 1 || allowScriptsToCloseWindows)) {
+ pageConsole()->addMessage(JSMessageSource, WarningMessageLevel, "Scripts may close only the windows that were opened by it.");
+ return;
+ }
+
+ if (!m_frame->loader().shouldClose())
+ return;
+
+ page->chrome().closeWindowSoon();
+}
+
+void DOMWindow::print()
+{
+ if (!m_frame)
+ return;
+
+ Page* page = m_frame->page();
+ if (!page)
+ return;
+
+ if (m_frame->loader().activeDocumentLoader()->isLoading()) {
+ m_shouldPrintWhenFinishedLoading = true;
+ return;
+ }
+ m_shouldPrintWhenFinishedLoading = false;
+ page->chrome().print(m_frame);
+}
+
+void DOMWindow::stop()
+{
+ if (!m_frame)
+ return;
+ m_frame->loader().stopAllLoaders();
+}
+
+void DOMWindow::alert(const String& message)
+{
+ if (!m_frame)
+ return;
+
+ m_frame->document()->updateStyleIfNeeded();
+
+ Page* page = m_frame->page();
+ if (!page)
+ return;
+
+ page->chrome().runJavaScriptAlert(m_frame, message);
+}
+
+bool DOMWindow::confirm(const String& message)
+{
+ if (!m_frame)
+ return false;
+
+ m_frame->document()->updateStyleIfNeeded();
+
+ Page* page = m_frame->page();
+ if (!page)
+ return false;
+
+ return page->chrome().runJavaScriptConfirm(m_frame, message);
+}
+
+String DOMWindow::prompt(const String& message, const String& defaultValue)
+{
+ if (!m_frame)
+ return String();
+
+ m_frame->document()->updateStyleIfNeeded();
+
+ Page* page = m_frame->page();
+ if (!page)
+ return String();
+
+ String returnValue;
+ if (page->chrome().runJavaScriptPrompt(m_frame, message, defaultValue, returnValue))
+ return returnValue;
+
+ return String();
+}
+
+bool DOMWindow::find(const String& string, bool caseSensitive, bool backwards, bool wrap, bool /*wholeWord*/, bool /*searchInFrames*/, bool /*showDialog*/) const
+{
+ if (!isCurrentlyDisplayedInFrame())
+ return false;
+
+ // |m_frame| can be destructed during |Editor::findString()| via
+ // |Document::updateLayou()|, e.g. event handler removes a frame.
+ RefPtr<Frame> protectFrame(m_frame);
+
+ // FIXME (13016): Support wholeWord, searchInFrames and showDialog
+ return m_frame->editor().findString(string, !backwards, caseSensitive, wrap, false);
+}
+
+bool DOMWindow::offscreenBuffering() const
+{
+ return true;
+}
+
+int DOMWindow::outerHeight() const
+{
+ if (!m_frame)
+ return 0;
+
+ Page* page = m_frame->page();
+ if (!page)
+ return 0;
+
+ if (page->settings().reportScreenSizeInPhysicalPixelsQuirk())
+ return lroundf(page->chrome().windowRect().height() * page->deviceScaleFactor());
+ return static_cast<int>(page->chrome().windowRect().height());
+}
+
+int DOMWindow::outerWidth() const
+{
+ if (!m_frame)
+ return 0;
+
+ Page* page = m_frame->page();
+ if (!page)
+ return 0;
+
+ if (page->settings().reportScreenSizeInPhysicalPixelsQuirk())
+ return lroundf(page->chrome().windowRect().width() * page->deviceScaleFactor());
+ return static_cast<int>(page->chrome().windowRect().width());
+}
+
+int DOMWindow::innerHeight() const
+{
+ if (!m_frame)
+ return 0;
+
+ FrameView* view = m_frame->view();
+ if (!view)
+ return 0;
+
+ // FIXME: This is potentially too much work. We really only need to know the dimensions of the parent frame's renderer.
+ if (Frame* parent = m_frame->tree().parent())
+ parent->document()->updateLayoutIgnorePendingStylesheets();
+
+ return adjustForAbsoluteZoom(view->visibleContentRect(ScrollableArea::IncludeScrollbars).height(), m_frame->pageZoomFactor());
+}
+
+int DOMWindow::innerWidth() const
+{
+ if (!m_frame)
+ return 0;
+
+ FrameView* view = m_frame->view();
+ if (!view)
+ return 0;
+
+ // FIXME: This is potentially too much work. We really only need to know the dimensions of the parent frame's renderer.
+ if (Frame* parent = m_frame->tree().parent())
+ parent->document()->updateLayoutIgnorePendingStylesheets();
+
+ return adjustForAbsoluteZoom(view->visibleContentRect(ScrollableArea::IncludeScrollbars).width(), m_frame->pageZoomFactor());
+}
+
+int DOMWindow::screenX() const
+{
+ if (!m_frame)
+ return 0;
+
+ Page* page = m_frame->page();
+ if (!page)
+ return 0;
+
+ if (page->settings().reportScreenSizeInPhysicalPixelsQuirk())
+ return lroundf(page->chrome().windowRect().x() * page->deviceScaleFactor());
+ return static_cast<int>(page->chrome().windowRect().x());
+}
+
+int DOMWindow::screenY() const
+{
+ if (!m_frame)
+ return 0;
+
+ Page* page = m_frame->page();
+ if (!page)
+ return 0;
+
+ if (page->settings().reportScreenSizeInPhysicalPixelsQuirk())
+ return lroundf(page->chrome().windowRect().y() * page->deviceScaleFactor());
+ return static_cast<int>(page->chrome().windowRect().y());
+}
+
+int DOMWindow::scrollX() const
+{
+ if (!m_frame)
+ return 0;
+
+ FrameView* view = m_frame->view();
+ if (!view)
+ return 0;
+
+ m_frame->document()->updateLayoutIgnorePendingStylesheets();
+
+ return adjustForAbsoluteZoom(view->scrollX(), m_frame->pageZoomFactor());
+}
+
+int DOMWindow::scrollY() const
+{
+ if (!m_frame)
+ return 0;
+
+ FrameView* view = m_frame->view();
+ if (!view)
+ return 0;
+
+ m_frame->document()->updateLayoutIgnorePendingStylesheets();
+
+ return adjustForAbsoluteZoom(view->scrollY(), m_frame->pageZoomFactor());
+}
+
+bool DOMWindow::closed() const
+{
+ return !m_frame;
+}
+
+unsigned DOMWindow::length() const
+{
+ if (!isCurrentlyDisplayedInFrame())
+ return 0;
+
+ return m_frame->tree().scopedChildCount();
+}
+
+const AtomicString& DOMWindow::name() const
+{
+ if (!m_frame)
+ return nullAtom;
+
+ return m_frame->tree().name();
+}
+
+void DOMWindow::setName(const AtomicString& name)
+{
+ if (!m_frame)
+ return;
+
+ m_frame->tree().setName(name);
+ m_frame->loader().client()->didChangeName(name);
+}
+
+void DOMWindow::setStatus(const String& string)
+{
+ m_status = string;
+
+ if (!m_frame)
+ return;
+
+ Page* page = m_frame->page();
+ if (!page)
+ return;
+
+ ASSERT(m_frame->document()); // Client calls shouldn't be made when the frame is in inconsistent state.
+ page->chrome().setStatusbarText(m_frame, m_status);
+}
+
+void DOMWindow::setDefaultStatus(const String& string)
+{
+ m_defaultStatus = string;
+
+ if (!m_frame)
+ return;
+
+ Page* page = m_frame->page();
+ if (!page)
+ return;
+
+ ASSERT(m_frame->document()); // Client calls shouldn't be made when the frame is in inconsistent state.
+ page->chrome().setStatusbarText(m_frame, m_defaultStatus);
+}
+
+DOMWindow* DOMWindow::self() const
+{
+ if (!m_frame)
+ return 0;
+
+ return m_frame->domWindow();
+}
+
+DOMWindow* DOMWindow::opener() const
+{
+ if (!m_frame)
+ return 0;
+
+ Frame* opener = m_frame->loader().opener();
+ if (!opener)
+ return 0;
+
+ return opener->domWindow();
+}
+
+DOMWindow* DOMWindow::parent() const
+{
+ if (!m_frame)
+ return 0;
+
+ Frame* parent = m_frame->tree().parent();
+ if (parent)
+ return parent->domWindow();
+
+ return m_frame->domWindow();
+}
+
+DOMWindow* DOMWindow::top() const
+{
+ if (!m_frame)
+ return 0;
+
+ Page* page = m_frame->page();
+ if (!page)
+ return 0;
+
+ return m_frame->tree().top()->domWindow();
+}
+
+Document* DOMWindow::document() const
+{
+ return m_document.get();
+}
+
+PassRefPtr<StyleMedia> DOMWindow::styleMedia() const
+{
+ if (!isCurrentlyDisplayedInFrame())
+ return 0;
+ if (!m_media)
+ m_media = StyleMedia::create(m_frame);
+ return m_media.get();
+}
+
+PassRefPtr<CSSStyleDeclaration> DOMWindow::getComputedStyle(Element* elt, const String& pseudoElt) const
+{
+ if (!elt)
+ return 0;
+
+ return CSSComputedStyleDeclaration::create(elt, false, pseudoElt);
+}
+
+PassRefPtr<CSSRuleList> DOMWindow::getMatchedCSSRules(Element* element, const String& pseudoElement, bool authorOnly) const
+{
+ UseCounter::count(this, UseCounter::GetMatchedCSSRules);
+ if (!element)
+ return 0;
+
+ if (!isCurrentlyDisplayedInFrame())
+ return 0;
+
+ unsigned colonStart = pseudoElement[0] == ':' ? (pseudoElement[1] == ':' ? 2 : 1) : 0;
+ CSSSelector::PseudoType pseudoType = CSSSelector::parsePseudoType(AtomicString(pseudoElement.substring(colonStart)));
+ if (pseudoType == CSSSelector::PseudoUnknown && !pseudoElement.isEmpty())
+ return 0;
+
+ unsigned rulesToInclude = StyleResolver::AuthorCSSRules;
+ if (!authorOnly)
+ rulesToInclude |= StyleResolver::UAAndUserCSSRules;
+
+ PseudoId pseudoId = CSSSelector::pseudoId(pseudoType);
+
+ return m_frame->document()->ensureStyleResolver().pseudoCSSRulesForElement(element, pseudoId, rulesToInclude);
+}
+
+PassRefPtr<DOMPoint> DOMWindow::webkitConvertPointFromNodeToPage(Node* node, const DOMPoint* p) const
+{
+ if (!node || !p)
+ return 0;
+
+ if (!document())
+ return 0;
+
+ document()->updateLayoutIgnorePendingStylesheets();
+
+ FloatPoint pagePoint(p->x(), p->y());
+ pagePoint = node->convertToPage(pagePoint);
+ return DOMPoint::create(pagePoint.x(), pagePoint.y());
+}
+
+PassRefPtr<DOMPoint> DOMWindow::webkitConvertPointFromPageToNode(Node* node, const DOMPoint* p) const
+{
+ if (!node || !p)
+ return 0;
+
+ if (!document())
+ return 0;
+
+ document()->updateLayoutIgnorePendingStylesheets();
+
+ FloatPoint nodePoint(p->x(), p->y());
+ nodePoint = node->convertFromPage(nodePoint);
+ return DOMPoint::create(nodePoint.x(), nodePoint.y());
+}
+
+double DOMWindow::devicePixelRatio() const
+{
+ if (!m_frame)
+ return 0.0;
+
+ return m_frame->devicePixelRatio();
+}
+
+void DOMWindow::scrollBy(int x, int y) const
+{
+ if (!isCurrentlyDisplayedInFrame())
+ return;
+
+ document()->updateLayoutIgnorePendingStylesheets();
+
+ FrameView* view = m_frame->view();
+ if (!view)
+ return;
+
+
+ IntSize scaledOffset(x * m_frame->pageZoomFactor(), y * m_frame->pageZoomFactor());
+ view->scrollBy(scaledOffset);
+}
+
+void DOMWindow::scrollTo(int x, int y) const
+{
+ if (!isCurrentlyDisplayedInFrame())
+ return;
+
+ document()->updateLayoutIgnorePendingStylesheets();
+
+ RefPtr<FrameView> view = m_frame->view();
+ if (!view)
+ return;
+
+ IntPoint layoutPos(x * m_frame->pageZoomFactor(), y * m_frame->pageZoomFactor());
+ view->setScrollPosition(layoutPos);
+}
+
+void DOMWindow::moveBy(float x, float y) const
+{
+ if (!m_frame)
+ return;
+
+ Page* page = m_frame->page();
+ if (!page)
+ return;
+
+ if (m_frame != page->mainFrame())
+ return;
+
+ FloatRect fr = page->chrome().windowRect();
+ FloatRect update = fr;
+ update.move(x, y);
+ // Security check (the spec talks about UniversalBrowserWrite to disable this check...)
+ page->chrome().setWindowRect(adjustWindowRect(page, update));
+}
+
+void DOMWindow::moveTo(float x, float y) const
+{
+ if (!m_frame)
+ return;
+
+ Page* page = m_frame->page();
+ if (!page)
+ return;
+
+ if (m_frame != page->mainFrame())
+ return;
+
+ FloatRect update = page->chrome().windowRect();
+ update.setLocation(FloatPoint(x, y));
+ // Security check (the spec talks about UniversalBrowserWrite to disable this check...)
+ page->chrome().setWindowRect(adjustWindowRect(page, update));
+}
+
+void DOMWindow::resizeBy(float x, float y) const
+{
+ if (!m_frame)
+ return;
+
+ Page* page = m_frame->page();
+ if (!page)
+ return;
+
+ if (m_frame != page->mainFrame())
+ return;
+
+ FloatRect fr = page->chrome().windowRect();
+ FloatSize dest = fr.size() + FloatSize(x, y);
+ FloatRect update(fr.location(), dest);
+ page->chrome().setWindowRect(adjustWindowRect(page, update));
+}
+
+void DOMWindow::resizeTo(float width, float height) const
+{
+ if (!m_frame)
+ return;
+
+ Page* page = m_frame->page();
+ if (!page)
+ return;
+
+ if (m_frame != page->mainFrame())
+ return;
+
+ FloatRect fr = page->chrome().windowRect();
+ FloatSize dest = FloatSize(width, height);
+ FloatRect update(fr.location(), dest);
+ page->chrome().setWindowRect(adjustWindowRect(page, update));
+}
+
+int DOMWindow::requestAnimationFrame(PassOwnPtr<RequestAnimationFrameCallback> callback)
+{
+ callback->m_useLegacyTimeBase = false;
+ if (Document* d = document())
+ return d->requestAnimationFrame(callback);
+ return 0;
+}
+
+int DOMWindow::webkitRequestAnimationFrame(PassOwnPtr<RequestAnimationFrameCallback> callback)
+{
+ callback->m_useLegacyTimeBase = true;
+ if (Document* d = document())
+ return d->requestAnimationFrame(callback);
+ return 0;
+}
+
+void DOMWindow::cancelAnimationFrame(int id)
+{
+ if (Document* d = document())
+ d->cancelAnimationFrame(id);
+}
+
+DOMWindowCSS* DOMWindow::css()
+{
+ if (!m_css)
+ m_css = DOMWindowCSS::create();
+ return m_css.get();
+}
+
+static void didAddStorageEventListener(DOMWindow* window)
+{
+ // Creating these WebCore::Storage objects informs the system that we'd like to receive
+ // notifications about storage events that might be triggered in other processes. Rather
+ // than subscribe to these notifications explicitly, we subscribe to them implicitly to
+ // simplify the work done by the system.
+ window->localStorage(IGNORE_EXCEPTION);
+ window->sessionStorage(IGNORE_EXCEPTION);
+}
+
+bool DOMWindow::addEventListener(const AtomicString& eventType, PassRefPtr<EventListener> listener, bool useCapture)
+{
+ if (!EventTarget::addEventListener(eventType, listener, useCapture))
+ return false;
+
+ if (Document* document = this->document()) {
+ document->addListenerTypeIfNeeded(eventType);
+ if (isTouchEventType(eventType))
+ document->didAddTouchEventHandler(document);
+ else if (eventType == EventTypeNames::storage)
+ didAddStorageEventListener(this);
+ }
+
+ lifecycleNotifier().notifyAddEventListener(this, eventType);
+
+ if (eventType == EventTypeNames::unload) {
+ UseCounter::count(this, UseCounter::DocumentUnloadRegistered);
+ addUnloadEventListener(this);
+ } else if (eventType == EventTypeNames::beforeunload) {
+ UseCounter::count(this, UseCounter::DocumentBeforeUnloadRegistered);
+ if (allowsBeforeUnloadListeners(this)) {
+ // This is confusingly named. It doesn't actually add the listener. It just increments a count
+ // so that we know we have listeners registered for the purposes of determining if we can
+ // fast terminate the renderer process.
+ addBeforeUnloadEventListener(this);
+ } else {
+ // Subframes return false from allowsBeforeUnloadListeners.
+ UseCounter::count(this, UseCounter::SubFrameBeforeUnloadRegistered);
+ }
+ }
+
+ return true;
+}
+
+bool DOMWindow::removeEventListener(const AtomicString& eventType, EventListener* listener, bool useCapture)
+{
+ if (!EventTarget::removeEventListener(eventType, listener, useCapture))
+ return false;
+
+ if (Document* document = this->document()) {
+ if (isTouchEventType(eventType))
+ document->didRemoveTouchEventHandler(document);
+ }
+
+ lifecycleNotifier().notifyRemoveEventListener(this, eventType);
+
+ if (eventType == EventTypeNames::unload) {
+ removeUnloadEventListener(this);
+ } else if (eventType == EventTypeNames::beforeunload && allowsBeforeUnloadListeners(this)) {
+ removeBeforeUnloadEventListener(this);
+ }
+
+ return true;
+}
+
+void DOMWindow::dispatchLoadEvent()
+{
+ RefPtr<Event> loadEvent(Event::create(EventTypeNames::load));
+ if (m_frame && m_frame->loader().documentLoader() && !m_frame->loader().documentLoader()->timing()->loadEventStart()) {
+ // The DocumentLoader (and thus its DocumentLoadTiming) might get destroyed while dispatching
+ // the event, so protect it to prevent writing the end time into freed memory.
+ RefPtr<DocumentLoader> documentLoader = m_frame->loader().documentLoader();
+ DocumentLoadTiming* timing = documentLoader->timing();
+ timing->markLoadEventStart();
+ dispatchEvent(loadEvent, document());
+ timing->markLoadEventEnd();
+ } else
+ dispatchEvent(loadEvent, document());
+
+ // For load events, send a separate load event to the enclosing frame only.
+ // This is a DOM extension and is independent of bubbling/capturing rules of
+ // the DOM.
+ Element* ownerElement = m_frame ? m_frame->ownerElement() : 0;
+ if (ownerElement)
+ ownerElement->dispatchEvent(Event::create(EventTypeNames::load));
+
+ InspectorInstrumentation::loadEventFired(frame());
+}
+
+bool DOMWindow::dispatchEvent(PassRefPtr<Event> prpEvent, PassRefPtr<EventTarget> prpTarget)
+{
+ ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
+
+ RefPtr<EventTarget> protect = this;
+ RefPtr<Event> event = prpEvent;
+
+ event->setTarget(prpTarget ? prpTarget : this);
+ event->setCurrentTarget(this);
+ event->setEventPhase(Event::AT_TARGET);
+
+ InspectorInstrumentationCookie cookie = InspectorInstrumentation::willDispatchEventOnWindow(frame(), *event, this);
+
+ bool result = fireEventListeners(event.get());
+
+ InspectorInstrumentation::didDispatchEventOnWindow(cookie);
+
+ return result;
+}
+
+void DOMWindow::removeAllEventListeners()
+{
+ EventTarget::removeAllEventListeners();
+
+ lifecycleNotifier().notifyRemoveAllEventListeners(this);
+
+ if (Document* document = this->document())
+ document->didRemoveEventTargetNode(document);
+
+ removeAllUnloadEventListeners(this);
+ removeAllBeforeUnloadEventListeners(this);
+}
+
+void DOMWindow::finishedLoading()
+{
+ if (m_shouldPrintWhenFinishedLoading) {
+ m_shouldPrintWhenFinishedLoading = false;
+ print();
+ }
+}
+
+void DOMWindow::setLocation(const String& urlString, DOMWindow* activeWindow, DOMWindow* firstWindow, SetLocationLocking locking)
+{
+ if (!isCurrentlyDisplayedInFrame())
+ return;
+
+ Document* activeDocument = activeWindow->document();
+ if (!activeDocument)
+ return;
+
+ if (!activeDocument->canNavigate(m_frame))
+ return;
+
+ Frame* firstFrame = firstWindow->frame();
+ if (!firstFrame)
+ return;
+
+ KURL completedURL = firstFrame->document()->completeURL(urlString);
+ if (completedURL.isNull())
+ return;
+
+ if (isInsecureScriptAccess(activeWindow, completedURL))
+ return;
+
+ // We want a new history item if we are processing a user gesture.
+ m_frame->navigationScheduler().scheduleLocationChange(activeDocument,
+ // FIXME: What if activeDocument()->frame() is 0?
+ completedURL, activeDocument->outgoingReferrer(),
+ locking != LockHistoryBasedOnGestureState);
+}
+
+void DOMWindow::printErrorMessage(const String& message)
+{
+ if (message.isEmpty())
+ return;
+
+ pageConsole()->addMessage(JSMessageSource, ErrorMessageLevel, message);
+}
+
+// FIXME: Once we're throwing exceptions for cross-origin access violations, we will always sanitize the target
+// frame details, so we can safely combine 'crossDomainAccessErrorMessage' with this method after considering
+// exactly which details may be exposed to JavaScript.
+//
+// http://crbug.com/17325
+String DOMWindow::sanitizedCrossDomainAccessErrorMessage(DOMWindow* activeWindow)
+{
+ if (!activeWindow || !activeWindow->document())
+ return String();
+
+ const KURL& activeWindowURL = activeWindow->document()->url();
+ if (activeWindowURL.isNull())
+ return String();
+
+ ASSERT(!activeWindow->document()->securityOrigin()->canAccess(document()->securityOrigin()));
+
+ SecurityOrigin* activeOrigin = activeWindow->document()->securityOrigin();
+ String message = "Blocked a frame with origin \"" + activeOrigin->toString() + "\" from accessing a cross-origin frame.";
+
+ // FIXME: Evaluate which details from 'crossDomainAccessErrorMessage' may safely be reported to JavaScript.
+
+ return message;
+}
+
+String DOMWindow::crossDomainAccessErrorMessage(DOMWindow* activeWindow)
+{
+ if (!activeWindow || !activeWindow->document())
+ return String();
+
+ const KURL& activeWindowURL = activeWindow->document()->url();
+ if (activeWindowURL.isNull())
+ return String();
+
+ ASSERT(!activeWindow->document()->securityOrigin()->canAccess(document()->securityOrigin()));
+
+ // FIXME: This message, and other console messages, have extra newlines. Should remove them.
+ SecurityOrigin* activeOrigin = activeWindow->document()->securityOrigin();
+ SecurityOrigin* targetOrigin = document()->securityOrigin();
+ String message = "Blocked a frame with origin \"" + activeOrigin->toString() + "\" from accessing a frame with origin \"" + targetOrigin->toString() + "\". ";
+
+ // Sandbox errors: Use the origin of the frames' location, rather than their actual origin (since we know that at least one will be "null").
+ KURL activeURL = activeWindow->document()->url();
+ KURL targetURL = document()->url();
+ if (document()->isSandboxed(SandboxOrigin) || activeWindow->document()->isSandboxed(SandboxOrigin)) {
+ message = "Blocked a frame at \"" + SecurityOrigin::create(activeURL)->toString() + "\" from accessing a frame at \"" + SecurityOrigin::create(targetURL)->toString() + "\". ";
+ if (document()->isSandboxed(SandboxOrigin) && activeWindow->document()->isSandboxed(SandboxOrigin))
+ return "Sandbox access violation: " + message + " Both frames are sandboxed and lack the \"allow-same-origin\" flag.";
+ if (document()->isSandboxed(SandboxOrigin))
+ return "Sandbox access violation: " + message + " The frame being accessed is sandboxed and lacks the \"allow-same-origin\" flag.";
+ return "Sandbox access violation: " + message + " The frame requesting access is sandboxed and lacks the \"allow-same-origin\" flag.";
+ }
+
+ // Protocol errors: Use the URL's protocol rather than the origin's protocol so that we get a useful message for non-heirarchal URLs like 'data:'.
+ if (targetOrigin->protocol() != activeOrigin->protocol())
+ return message + " The frame requesting access has a protocol of \"" + activeURL.protocol() + "\", the frame being accessed has a protocol of \"" + targetURL.protocol() + "\". Protocols must match.\n";
+
+ // 'document.domain' errors.
+ if (targetOrigin->domainWasSetInDOM() && activeOrigin->domainWasSetInDOM())
+ return message + "The frame requesting access set \"document.domain\" to \"" + activeOrigin->domain() + "\", the frame being accessed set it to \"" + targetOrigin->domain() + "\". Both must set \"document.domain\" to the same value to allow access.";
+ if (activeOrigin->domainWasSetInDOM())
+ return message + "The frame requesting access set \"document.domain\" to \"" + activeOrigin->domain() + "\", but the frame being accessed did not. Both must set \"document.domain\" to the same value to allow access.";
+ if (targetOrigin->domainWasSetInDOM())
+ return message + "The frame being accessed set \"document.domain\" to \"" + targetOrigin->domain() + "\", but the frame requesting access did not. Both must set \"document.domain\" to the same value to allow access.";
+
+ // Default.
+ return message + "Protocols, domains, and ports must match.";
+}
+
+bool DOMWindow::isInsecureScriptAccess(DOMWindow* activeWindow, const String& urlString)
+{
+ if (!protocolIsJavaScript(urlString))
+ return false;
+
+ // If this DOMWindow isn't currently active in the Frame, then there's no
+ // way we should allow the access.
+ // FIXME: Remove this check if we're able to disconnect DOMWindow from
+ // Frame on navigation: https://bugs.webkit.org/show_bug.cgi?id=62054
+ if (isCurrentlyDisplayedInFrame()) {
+ // FIXME: Is there some way to eliminate the need for a separate "activeWindow == this" check?
+ if (activeWindow == this)
+ return false;
+
+ // FIXME: The name canAccess seems to be a roundabout way to ask "can execute script".
+ // Can we name the SecurityOrigin function better to make this more clear?
+ if (activeWindow->document()->securityOrigin()->canAccess(document()->securityOrigin()))
+ return false;
+ }
+
+ printErrorMessage(crossDomainAccessErrorMessage(activeWindow));
+ return true;
+}
+
+PassRefPtr<DOMWindow> DOMWindow::open(const String& urlString, const AtomicString& frameName, const String& windowFeaturesString,
+ DOMWindow* activeWindow, DOMWindow* firstWindow)
+{
+ if (!isCurrentlyDisplayedInFrame())
+ return 0;
+ Document* activeDocument = activeWindow->document();
+ if (!activeDocument)
+ return 0;
+ Frame* firstFrame = firstWindow->frame();
+ if (!firstFrame)
+ return 0;
+
+ if (!firstWindow->allowPopUp()) {
+ // Because FrameTree::find() returns true for empty strings, we must check for empty frame names.
+ // Otherwise, illegitimate window.open() calls with no name will pass right through the popup blocker.
+ if (frameName.isEmpty() || !m_frame->tree().find(frameName))
+ return 0;
+ }
+
+ // Get the target frame for the special cases of _top and _parent.
+ // In those cases, we schedule a location change right now and return early.
+ Frame* targetFrame = 0;
+ if (frameName == "_top")
+ targetFrame = m_frame->tree().top();
+ else if (frameName == "_parent") {
+ if (Frame* parent = m_frame->tree().parent())
+ targetFrame = parent;
+ else
+ targetFrame = m_frame;
+ }
+ if (targetFrame) {
+ if (!activeDocument->canNavigate(targetFrame))
+ return 0;
+
+ KURL completedURL = firstFrame->document()->completeURL(urlString);
+
+ if (targetFrame->domWindow()->isInsecureScriptAccess(activeWindow, completedURL))
+ return targetFrame->domWindow();
+
+ if (urlString.isEmpty())
+ return targetFrame->domWindow();
+
+ // For whatever reason, Firefox uses the first window rather than the active window to
+ // determine the outgoing referrer. We replicate that behavior here.
+ targetFrame->navigationScheduler().scheduleLocationChange(
+ activeDocument,
+ completedURL,
+ firstFrame->document()->outgoingReferrer(),
+ false);
+ return targetFrame->domWindow();
+ }
+
+ WindowFeatures windowFeatures(windowFeaturesString);
+ Frame* result = createWindow(urlString, frameName, windowFeatures, activeWindow, firstFrame, m_frame);
+ return result ? result->domWindow() : 0;
+}
+
+void DOMWindow::showModalDialog(const String& urlString, const String& dialogFeaturesString,
+ DOMWindow* activeWindow, DOMWindow* firstWindow, PrepareDialogFunction function, void* functionContext)
+{
+ if (!isCurrentlyDisplayedInFrame())
+ return;
+ Frame* activeFrame = activeWindow->frame();
+ if (!activeFrame)
+ return;
+ Frame* firstFrame = firstWindow->frame();
+ if (!firstFrame)
+ return;
+
+ if (!canShowModalDialogNow(m_frame) || !firstWindow->allowPopUp())
+ return;
+
+ UseCounter::countDeprecation(this, UseCounter::ShowModalDialog);
+
+ WindowFeatures windowFeatures(dialogFeaturesString, screenAvailableRect(m_frame->view()));
+ Frame* dialogFrame = createWindow(urlString, emptyAtom, windowFeatures,
+ activeWindow, firstFrame, m_frame, function, functionContext);
+ if (!dialogFrame)
+ return;
+ UserGestureIndicatorDisabler disabler;
+ dialogFrame->page()->chrome().runModal();
+}
+
+DOMWindow* DOMWindow::anonymousIndexedGetter(uint32_t index)
+{
+ Frame* frame = this->frame();
+ if (!frame)
+ return 0;
+
+ Frame* child = frame->tree().scopedChild(index);
+ if (child)
+ return child->domWindow();
+
+ return 0;
+}
+
+DOMWindowLifecycleNotifier& DOMWindow::lifecycleNotifier()
+{
+ return static_cast<DOMWindowLifecycleNotifier&>(LifecycleContext<DOMWindow>::lifecycleNotifier());
+}
+
+PassOwnPtr<LifecycleNotifier<DOMWindow> > DOMWindow::createLifecycleNotifier()
+{
+ return DOMWindowLifecycleNotifier::create(this);
+}
+
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/frame/DOMWindow.h b/chromium/third_party/WebKit/Source/core/frame/DOMWindow.h
new file mode 100644
index 00000000000..f4590573794
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/DOMWindow.h
@@ -0,0 +1,390 @@
+/*
+ * Copyright (C) 2006, 2007, 2009, 2010 Apple Inc. All rights reserved.
+ * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef DOMWindow_h
+#define DOMWindow_h
+
+#include "bindings/v8/ScriptWrappable.h"
+#include "core/events/EventTarget.h"
+#include "core/frame/FrameDestructionObserver.h"
+#include "platform/LifecycleContext.h"
+#include "platform/Supplementable.h"
+
+#include "wtf/Forward.h"
+
+namespace WebCore {
+ class ApplicationCache;
+ class BarProp;
+ class CSSRuleList;
+ class CSSStyleDeclaration;
+ class Console;
+ class DOMPoint;
+ class DOMSelection;
+ class DOMURL;
+ class DOMWindowProperty;
+ class Database;
+ class DatabaseCallback;
+ class Document;
+ class DocumentInit;
+ class DOMWindowEventQueue;
+ class DOMWindowLifecycleNotifier;
+ class Element;
+ class EventListener;
+ class EventQueue;
+ class ExceptionState;
+ class FloatRect;
+ class Frame;
+ class History;
+ class IDBFactory;
+ class Location;
+ class MediaQueryList;
+ class MessageEvent;
+ class Navigator;
+ class Node;
+ class Page;
+ class PageConsole;
+ class Performance;
+ class PostMessageTimer;
+ class RequestAnimationFrameCallback;
+ class ScheduledAction;
+ class Screen;
+ class ScriptCallStack;
+ class SecurityOrigin;
+ class SerializedScriptValue;
+ class Storage;
+ class StyleMedia;
+ class DOMWindowCSS;
+
+ struct WindowFeatures;
+
+ typedef Vector<RefPtr<MessagePort>, 1> MessagePortArray;
+
+enum PageshowEventPersistence {
+ PageshowEventNotPersisted = 0,
+ PageshowEventPersisted = 1
+};
+
+ enum SetLocationLocking { LockHistoryBasedOnGestureState, LockHistoryAndBackForwardList };
+
+ class DOMWindow : public RefCounted<DOMWindow>, public ScriptWrappable, public EventTargetWithInlineData, public FrameDestructionObserver, public Supplementable<DOMWindow>, public LifecycleContext<DOMWindow> {
+ REFCOUNTED_EVENT_TARGET(DOMWindow);
+ public:
+ static PassRefPtr<Document> createDocument(const String& mimeType, const DocumentInit&, bool forceXHTML);
+ static PassRefPtr<DOMWindow> create(Frame* frame) { return adoptRef(new DOMWindow(frame)); }
+ virtual ~DOMWindow();
+
+ PassRefPtr<Document> installNewDocument(const String& mimeType, const DocumentInit&, bool forceXHTML = false);
+
+ virtual const AtomicString& interfaceName() const OVERRIDE;
+ virtual ExecutionContext* executionContext() const OVERRIDE;
+
+ virtual DOMWindow* toDOMWindow();
+
+ void registerProperty(DOMWindowProperty*);
+ void unregisterProperty(DOMWindowProperty*);
+
+ void reset();
+
+ PassRefPtr<MediaQueryList> matchMedia(const String&);
+
+ unsigned pendingUnloadEventListeners() const;
+
+ static FloatRect adjustWindowRect(Page*, const FloatRect& pendingChanges);
+
+ bool allowPopUp(); // Call on first window, not target window.
+ static bool allowPopUp(Frame* firstFrame);
+ static bool canShowModalDialog(const Frame*);
+ static bool canShowModalDialogNow(const Frame*);
+
+ // DOM Level 0
+
+ Screen* screen() const;
+ History* history() const;
+ BarProp* locationbar() const;
+ BarProp* menubar() const;
+ BarProp* personalbar() const;
+ BarProp* scrollbars() const;
+ BarProp* statusbar() const;
+ BarProp* toolbar() const;
+ Navigator* navigator() const;
+ Navigator* clientInformation() const { return navigator(); }
+
+ Location* location() const;
+ void setLocation(const String& location, DOMWindow* activeWindow, DOMWindow* firstWindow,
+ SetLocationLocking = LockHistoryBasedOnGestureState);
+
+ DOMSelection* getSelection();
+
+ Element* frameElement() const;
+
+ void focus(ExecutionContext* = 0);
+ void blur();
+ void close(ExecutionContext* = 0);
+ void print();
+ void stop();
+
+ PassRefPtr<DOMWindow> open(const String& urlString, const AtomicString& frameName, const String& windowFeaturesString,
+ DOMWindow* activeWindow, DOMWindow* firstWindow);
+
+ typedef void (*PrepareDialogFunction)(DOMWindow*, void* context);
+ void showModalDialog(const String& urlString, const String& dialogFeaturesString,
+ DOMWindow* activeWindow, DOMWindow* firstWindow, PrepareDialogFunction, void* functionContext);
+
+ void alert(const String& message);
+ bool confirm(const String& message);
+ String prompt(const String& message, const String& defaultValue);
+
+ bool find(const String&, bool caseSensitive, bool backwards, bool wrap, bool wholeWord, bool searchInFrames, bool showDialog) const;
+
+ bool offscreenBuffering() const;
+
+ int outerHeight() const;
+ int outerWidth() const;
+ int innerHeight() const;
+ int innerWidth() const;
+ int screenX() const;
+ int screenY() const;
+ int screenLeft() const { return screenX(); }
+ int screenTop() const { return screenY(); }
+ int scrollX() const;
+ int scrollY() const;
+ int pageXOffset() const { return scrollX(); }
+ int pageYOffset() const { return scrollY(); }
+
+ bool closed() const;
+
+ unsigned length() const;
+
+ const AtomicString& name() const;
+ void setName(const AtomicString&);
+
+ String status() const;
+ void setStatus(const String&);
+ String defaultStatus() const;
+ void setDefaultStatus(const String&);
+
+ // Self-referential attributes
+
+ DOMWindow* self() const;
+ DOMWindow* window() const { return self(); }
+ DOMWindow* frames() const { return self(); }
+
+ DOMWindow* opener() const;
+ DOMWindow* parent() const;
+ DOMWindow* top() const;
+
+ // DOM Level 2 AbstractView Interface
+
+ Document* document() const;
+
+ // CSSOM View Module
+
+ PassRefPtr<StyleMedia> styleMedia() const;
+
+ // DOM Level 2 Style Interface
+
+ PassRefPtr<CSSStyleDeclaration> getComputedStyle(Element*, const String& pseudoElt) const;
+
+ // WebKit extensions
+
+ PassRefPtr<CSSRuleList> getMatchedCSSRules(Element*, const String& pseudoElt, bool authorOnly = true) const;
+ double devicePixelRatio() const;
+
+ PassRefPtr<DOMPoint> webkitConvertPointFromPageToNode(Node*, const DOMPoint*) const;
+ PassRefPtr<DOMPoint> webkitConvertPointFromNodeToPage(Node*, const DOMPoint*) const;
+
+ Console* console() const;
+ PageConsole* pageConsole() const;
+
+ void printErrorMessage(const String&);
+ String crossDomainAccessErrorMessage(DOMWindow* activeWindow);
+ String sanitizedCrossDomainAccessErrorMessage(DOMWindow* activeWindow);
+
+ void postMessage(PassRefPtr<SerializedScriptValue> message, const MessagePortArray*, const String& targetOrigin, DOMWindow* source, ExceptionState&);
+ void postMessageTimerFired(PassOwnPtr<PostMessageTimer>);
+ void dispatchMessageEventWithOriginCheck(SecurityOrigin* intendedTargetOrigin, PassRefPtr<Event>, PassRefPtr<ScriptCallStack>);
+
+ void scrollBy(int x, int y) const;
+ void scrollTo(int x, int y) const;
+ void scroll(int x, int y) const { scrollTo(x, y); }
+
+ void moveBy(float x, float y) const;
+ void moveTo(float x, float y) const;
+
+ void resizeBy(float x, float y) const;
+ void resizeTo(float width, float height) const;
+
+ // WebKit animation extensions
+ int requestAnimationFrame(PassOwnPtr<RequestAnimationFrameCallback>);
+ int webkitRequestAnimationFrame(PassOwnPtr<RequestAnimationFrameCallback>);
+ void cancelAnimationFrame(int id);
+
+ DOMWindowCSS* css();
+
+ // Events
+ // EventTarget API
+ virtual bool addEventListener(const AtomicString& eventType, PassRefPtr<EventListener>, bool useCapture) OVERRIDE;
+ virtual bool removeEventListener(const AtomicString& eventType, EventListener*, bool useCapture) OVERRIDE;
+ virtual void removeAllEventListeners() OVERRIDE;
+
+ using EventTarget::dispatchEvent;
+ bool dispatchEvent(PassRefPtr<Event> prpEvent, PassRefPtr<EventTarget> prpTarget);
+
+ void dispatchLoadEvent();
+
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(animationend);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(animationiteration);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(animationstart);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(search);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(transitionend);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(wheel);
+
+ DEFINE_MAPPED_ATTRIBUTE_EVENT_LISTENER(webkitanimationstart, webkitAnimationStart);
+ DEFINE_MAPPED_ATTRIBUTE_EVENT_LISTENER(webkitanimationiteration, webkitAnimationIteration);
+ DEFINE_MAPPED_ATTRIBUTE_EVENT_LISTENER(webkitanimationend, webkitAnimationEnd);
+ DEFINE_MAPPED_ATTRIBUTE_EVENT_LISTENER(webkittransitionend, webkitTransitionEnd);
+
+ void captureEvents() { }
+ void releaseEvents() { }
+
+ void finishedLoading();
+
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(devicemotion);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(deviceorientation);
+
+ // HTML 5 key/value storage
+ Storage* sessionStorage(ExceptionState&) const;
+ Storage* localStorage(ExceptionState&) const;
+ Storage* optionalSessionStorage() const { return m_sessionStorage.get(); }
+ Storage* optionalLocalStorage() const { return m_localStorage.get(); }
+
+ ApplicationCache* applicationCache() const;
+ ApplicationCache* optionalApplicationCache() const { return m_applicationCache.get(); }
+
+#if ENABLE(ORIENTATION_EVENTS)
+ // This is the interface orientation in degrees. Some examples are:
+ // 0 is straight up; -90 is when the device is rotated 90 clockwise;
+ // 90 is when rotated counter clockwise.
+ int orientation() const;
+
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(orientationchange);
+#endif
+
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(touchstart);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(touchmove);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(touchend);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(touchcancel);
+
+ Performance* performance() const;
+
+ // FIXME: When this DOMWindow is no longer the active DOMWindow (i.e.,
+ // when its document is no longer the document that is displayed in its
+ // frame), we would like to zero out m_frame to avoid being confused
+ // by the document that is currently active in m_frame.
+ bool isCurrentlyDisplayedInFrame() const;
+
+ void willDetachDocumentFromFrame();
+ DOMWindow* anonymousIndexedGetter(uint32_t);
+
+ bool isInsecureScriptAccess(DOMWindow* activeWindow, const String& urlString);
+
+ PassOwnPtr<LifecycleNotifier<DOMWindow> > createLifecycleNotifier();
+
+ EventQueue* eventQueue() const;
+ void enqueueWindowEvent(PassRefPtr<Event>);
+ void enqueueDocumentEvent(PassRefPtr<Event>);
+ void enqueuePageshowEvent(PageshowEventPersistence);
+ void enqueueHashchangeEvent(const String& oldURL, const String& newURL);
+ void enqueuePopstateEvent(PassRefPtr<SerializedScriptValue>);
+ void dispatchWindowLoadEvent();
+ void documentWasClosed();
+ void statePopped(PassRefPtr<SerializedScriptValue>);
+
+ // FIXME: This shouldn't be public once DOMWindow becomes ExecutionContext.
+ void clearEventQueue();
+
+ protected:
+ DOMWindowLifecycleNotifier& lifecycleNotifier();
+
+ private:
+ explicit DOMWindow(Frame*);
+
+ Page* page();
+
+ virtual void frameDestroyed() OVERRIDE;
+ virtual void willDetachPage() OVERRIDE;
+
+ void clearDocument();
+ void resetDOMWindowProperties();
+ void willDestroyDocumentInFrame();
+
+ RefPtr<Document> m_document;
+
+ bool m_shouldPrintWhenFinishedLoading;
+
+ HashSet<DOMWindowProperty*> m_properties;
+
+ mutable RefPtr<Screen> m_screen;
+ mutable RefPtr<History> m_history;
+ mutable RefPtr<BarProp> m_locationbar;
+ mutable RefPtr<BarProp> m_menubar;
+ mutable RefPtr<BarProp> m_personalbar;
+ mutable RefPtr<BarProp> m_scrollbars;
+ mutable RefPtr<BarProp> m_statusbar;
+ mutable RefPtr<BarProp> m_toolbar;
+ mutable RefPtr<Console> m_console;
+ mutable RefPtr<Navigator> m_navigator;
+ mutable RefPtr<Location> m_location;
+ mutable RefPtr<StyleMedia> m_media;
+
+ String m_status;
+ String m_defaultStatus;
+
+ mutable RefPtr<Storage> m_sessionStorage;
+ mutable RefPtr<Storage> m_localStorage;
+ mutable RefPtr<ApplicationCache> m_applicationCache;
+
+ mutable RefPtr<Performance> m_performance;
+
+ mutable RefPtr<DOMWindowCSS> m_css;
+
+ RefPtr<DOMWindowEventQueue> m_eventQueue;
+ RefPtr<SerializedScriptValue> m_pendingStateObject;
+ };
+
+ inline String DOMWindow::status() const
+ {
+ return m_status;
+ }
+
+ inline String DOMWindow::defaultStatus() const
+ {
+ return m_defaultStatus;
+ }
+
+} // namespace WebCore
+
+#endif // DOMWindow_h
diff --git a/chromium/third_party/WebKit/Source/core/frame/DOMWindowBase64.cpp b/chromium/third_party/WebKit/Source/core/frame/DOMWindowBase64.cpp
new file mode 100644
index 00000000000..2f43d507a77
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/DOMWindowBase64.cpp
@@ -0,0 +1,78 @@
+/*
+ * Copyright (C) 2006, 2007, 2008, 2010 Apple Inc. All rights reserved.
+ * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
+ * Copyright (C) 2013 Samsung Electronics. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/frame/DOMWindowBase64.h"
+
+#include "bindings/v8/ExceptionState.h"
+#include "core/dom/ExceptionCode.h"
+#include "core/html/parser/HTMLParserIdioms.h"
+#include "wtf/text/Base64.h"
+
+namespace WebCore {
+
+namespace DOMWindowBase64 {
+
+String btoa(void*, const String& stringToEncode, ExceptionState& exceptionState)
+{
+ if (stringToEncode.isNull())
+ return String();
+
+ if (!stringToEncode.containsOnlyLatin1()) {
+ exceptionState.throwDOMException(InvalidCharacterError, "The string to be encoded contains characters outside of the Latin1 range.");
+ return String();
+ }
+
+ return base64Encode(stringToEncode.latin1());
+}
+
+String atob(void*, const String& encodedString, ExceptionState& exceptionState)
+{
+ if (encodedString.isNull())
+ return String();
+
+ if (!encodedString.containsOnlyLatin1()) {
+ exceptionState.throwDOMException(InvalidCharacterError, "The string to be decoded contains characters outside of the Latin1 range.");
+ return String();
+ }
+ Vector<char> out;
+ if (!base64Decode(encodedString, out, isHTMLSpace<UChar>, Base64ValidatePadding)) {
+ exceptionState.throwDOMException(InvalidCharacterError, "The string to be decoded is not correctly encoded.");
+ return String();
+ }
+
+ return String(out.data(), out.size());
+}
+
+} // namespace DOMWindowBase64
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/page/DOMWindowBase64.h b/chromium/third_party/WebKit/Source/core/frame/DOMWindowBase64.h
index 21001e0bf62..21001e0bf62 100644
--- a/chromium/third_party/WebKit/Source/core/page/DOMWindowBase64.h
+++ b/chromium/third_party/WebKit/Source/core/frame/DOMWindowBase64.h
diff --git a/chromium/third_party/WebKit/Source/core/frame/DOMWindowEventHandlers.h b/chromium/third_party/WebKit/Source/core/frame/DOMWindowEventHandlers.h
new file mode 100644
index 00000000000..bf897717772
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/DOMWindowEventHandlers.h
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) 2013, Opera Software ASA. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Opera Software ASA nor the names of its
+ * contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef DOMWindowEventHandlers_h
+#define DOMWindowEventHandlers_h
+
+#include "core/events/EventTarget.h"
+
+namespace WebCore {
+
+namespace DOMWindowEventHandlers {
+DEFINE_STATIC_WINDOW_ATTRIBUTE_EVENT_LISTENER(beforeunload);
+DEFINE_STATIC_WINDOW_ATTRIBUTE_EVENT_LISTENER(hashchange);
+DEFINE_STATIC_WINDOW_ATTRIBUTE_EVENT_LISTENER(message);
+DEFINE_STATIC_WINDOW_ATTRIBUTE_EVENT_LISTENER(offline);
+DEFINE_STATIC_WINDOW_ATTRIBUTE_EVENT_LISTENER(online);
+DEFINE_STATIC_WINDOW_ATTRIBUTE_EVENT_LISTENER(pagehide);
+DEFINE_STATIC_WINDOW_ATTRIBUTE_EVENT_LISTENER(pageshow);
+DEFINE_STATIC_WINDOW_ATTRIBUTE_EVENT_LISTENER(popstate);
+DEFINE_STATIC_WINDOW_ATTRIBUTE_EVENT_LISTENER(resize);
+DEFINE_STATIC_WINDOW_ATTRIBUTE_EVENT_LISTENER(storage);
+DEFINE_STATIC_WINDOW_ATTRIBUTE_EVENT_LISTENER(unload);
+}
+
+} // namespace
+
+#endif
diff --git a/chromium/third_party/WebKit/Source/core/frame/DOMWindowLifecycleNotifier.cpp b/chromium/third_party/WebKit/Source/core/frame/DOMWindowLifecycleNotifier.cpp
new file mode 100644
index 00000000000..92fafea2796
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/DOMWindowLifecycleNotifier.cpp
@@ -0,0 +1,83 @@
+/*
+ * Copyright (C) 2013 Google Inc. All Rights Reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+
+#include "config.h"
+#include "core/frame/DOMWindowLifecycleNotifier.h"
+
+namespace WebCore {
+
+DOMWindowLifecycleNotifier::DOMWindowLifecycleNotifier(DOMWindow* context)
+ : LifecycleNotifier<DOMWindow>(context)
+{
+}
+
+void DOMWindowLifecycleNotifier::addObserver(DOMWindowLifecycleNotifier::Observer* observer)
+{
+ if (observer->observerType() == Observer::DOMWindowLifecycleObserverType) {
+ RELEASE_ASSERT(m_iterating != IteratingOverDOMWindowObservers);
+ m_windowObservers.add(static_cast<DOMWindowLifecycleObserver*>(observer));
+ }
+
+ LifecycleNotifier<DOMWindow>::addObserver(observer);
+}
+
+void DOMWindowLifecycleNotifier::removeObserver(DOMWindowLifecycleNotifier::Observer* observer)
+{
+ if (observer->observerType() == Observer::DOMWindowLifecycleObserverType) {
+ RELEASE_ASSERT(m_iterating != IteratingOverDOMWindowObservers);
+ m_windowObservers.remove(static_cast<DOMWindowLifecycleObserver*>(observer));
+ }
+
+ LifecycleNotifier<DOMWindow>::removeObserver(observer);
+}
+
+PassOwnPtr<DOMWindowLifecycleNotifier> DOMWindowLifecycleNotifier::create(DOMWindow* context)
+{
+ return adoptPtr(new DOMWindowLifecycleNotifier(context));
+}
+
+void DOMWindowLifecycleNotifier::notifyAddEventListener(DOMWindow* window, const AtomicString& eventType)
+{
+ TemporaryChange<IterationType> scope(this->m_iterating, IteratingOverDOMWindowObservers);
+ for (DOMWindowObserverSet::iterator it = m_windowObservers.begin(); it != m_windowObservers.end(); ++it)
+ (*it)->didAddEventListener(window, eventType);
+}
+
+void DOMWindowLifecycleNotifier::notifyRemoveEventListener(DOMWindow* window, const AtomicString& eventType)
+{
+ TemporaryChange<IterationType> scope(this->m_iterating, IteratingOverDOMWindowObservers);
+ for (DOMWindowObserverSet::iterator it = m_windowObservers.begin(); it != m_windowObservers.end(); ++it)
+ (*it)->didRemoveEventListener(window, eventType);
+}
+
+void DOMWindowLifecycleNotifier::notifyRemoveAllEventListeners(DOMWindow* window)
+{
+ TemporaryChange<IterationType> scope(this->m_iterating, IteratingOverDOMWindowObservers);
+ for (DOMWindowObserverSet::iterator it = m_windowObservers.begin(); it != m_windowObservers.end(); ++it)
+ (*it)->didRemoveAllEventListeners(window);
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/frame/DOMWindowLifecycleNotifier.h b/chromium/third_party/WebKit/Source/core/frame/DOMWindowLifecycleNotifier.h
new file mode 100644
index 00000000000..7db48593e52
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/DOMWindowLifecycleNotifier.h
@@ -0,0 +1,59 @@
+/*
+ * Copyright (C) 2013 Google Inc. All Rights Reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef DOMWindowLifecycleNotifier_h
+#define DOMWindowLifecycleNotifier_h
+
+#include "core/frame/DOMWindowLifecycleObserver.h"
+#include "platform/LifecycleNotifier.h"
+#include "wtf/PassOwnPtr.h"
+#include "wtf/TemporaryChange.h"
+#include "wtf/text/WTFString.h"
+
+namespace WebCore {
+
+class DOMWindow;
+
+class DOMWindowLifecycleNotifier : public LifecycleNotifier<DOMWindow> {
+public:
+ static PassOwnPtr<DOMWindowLifecycleNotifier> create(DOMWindow*);
+
+ void notifyAddEventListener(DOMWindow*, const AtomicString& eventType);
+ void notifyRemoveEventListener(DOMWindow*, const AtomicString& eventType);
+ void notifyRemoveAllEventListeners(DOMWindow*);
+
+ virtual void addObserver(Observer*) OVERRIDE;
+ virtual void removeObserver(Observer*) OVERRIDE;
+
+private:
+ explicit DOMWindowLifecycleNotifier(DOMWindow*);
+
+ typedef HashSet<DOMWindowLifecycleObserver*> DOMWindowObserverSet;
+ DOMWindowObserverSet m_windowObservers;
+};
+
+} // namespace WebCore
+
+#endif // DOMWindowLifecycleNotifier_h
diff --git a/chromium/third_party/WebKit/Source/core/frame/DOMWindowLifecycleObserver.cpp b/chromium/third_party/WebKit/Source/core/frame/DOMWindowLifecycleObserver.cpp
new file mode 100644
index 00000000000..aa4f97b8661
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/DOMWindowLifecycleObserver.cpp
@@ -0,0 +1,58 @@
+/*
+ * Copyright (C) 2013 Google Inc. All Rights Reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+
+#include "config.h"
+#include "core/frame/DOMWindowLifecycleObserver.h"
+
+#include "core/frame/DOMWindow.h"
+
+namespace WebCore {
+
+template<> void observerContext(DOMWindow* context, LifecycleObserver<DOMWindow>* observer)
+{
+ context->wasObservedBy(observer);
+}
+
+template<> void unobserverContext(DOMWindow* context, LifecycleObserver<DOMWindow>* observer)
+{
+ context->wasUnobservedBy(observer);
+}
+
+DOMWindowLifecycleObserver::DOMWindowLifecycleObserver(DOMWindow* window)
+ : LifecycleObserver<DOMWindow>(window, DOMWindowLifecycleObserverType)
+{
+}
+
+DOMWindowLifecycleObserver::~DOMWindowLifecycleObserver()
+{
+}
+
+DOMWindow* DOMWindowLifecycleObserver::window() const
+{
+ return static_cast<DOMWindow*>(lifecycleContext());
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/frame/DOMWindowLifecycleObserver.h b/chromium/third_party/WebKit/Source/core/frame/DOMWindowLifecycleObserver.h
new file mode 100644
index 00000000000..de49449697a
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/DOMWindowLifecycleObserver.h
@@ -0,0 +1,54 @@
+
+/*
+ * Copyright (C) 2013 Google Inc. All Rights Reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef DOMWindowLifecycleObserver_h
+#define DOMWindowLifecycleObserver_h
+
+#include "platform/LifecycleObserver.h"
+#include "wtf/text/WTFString.h"
+
+namespace WebCore {
+
+class DOMWindow;
+
+template<> void observerContext(DOMWindow*, LifecycleObserver<DOMWindow>*);
+template<> void unobserverContext(DOMWindow*, LifecycleObserver<DOMWindow>*);
+
+class DOMWindowLifecycleObserver : public LifecycleObserver<DOMWindow> {
+public:
+ explicit DOMWindowLifecycleObserver(DOMWindow*);
+ virtual ~DOMWindowLifecycleObserver();
+
+ DOMWindow* window() const;
+
+ virtual void didAddEventListener(DOMWindow*, const AtomicString&) { }
+ virtual void didRemoveEventListener(DOMWindow*, const AtomicString&) { }
+ virtual void didRemoveAllEventListeners(DOMWindow*) { }
+};
+
+} // namespace WebCore
+
+#endif // DOMWindowLifecycleObserver_h
diff --git a/chromium/third_party/WebKit/Source/core/frame/DOMWindowProperty.cpp b/chromium/third_party/WebKit/Source/core/frame/DOMWindowProperty.cpp
new file mode 100644
index 00000000000..6649a2f7947
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/DOMWindowProperty.cpp
@@ -0,0 +1,79 @@
+/*
+ * Copyright (C) 2011 Google, Inc. All Rights Reserved.
+ * Copyright (C) 2012 Apple Inc. All Rights Reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY GOOGLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/frame/DOMWindowProperty.h"
+
+#include "core/dom/Document.h"
+#include "core/frame/DOMWindow.h"
+#include "core/frame/Frame.h"
+
+namespace WebCore {
+
+DOMWindowProperty::DOMWindowProperty(Frame* frame)
+ : m_frame(frame)
+ , m_associatedDOMWindow(0)
+{
+ // FIXME: For now it *is* acceptable for a DOMWindowProperty to be created with a null frame.
+ // See fast/dom/navigator-detached-no-crash.html for the recipe.
+ // We should fix that. <rdar://problem/11567132>
+ if (m_frame) {
+ m_associatedDOMWindow = m_frame->domWindow();
+ m_associatedDOMWindow->registerProperty(this);
+ }
+}
+
+DOMWindowProperty::~DOMWindowProperty()
+{
+ if (m_associatedDOMWindow)
+ m_associatedDOMWindow->unregisterProperty(this);
+
+ m_associatedDOMWindow = 0;
+ m_frame = 0;
+}
+
+void DOMWindowProperty::willDestroyGlobalObjectInFrame()
+{
+ // If the property is getting this callback it must have been created with a Frame/DOMWindow and it should still have them.
+ ASSERT(m_frame);
+ ASSERT(m_associatedDOMWindow);
+
+ // DOMWindowProperty lifetime isn't tied directly to the DOMWindow itself so it is important that it unregister
+ // itself from any DOMWindow it is associated with if that DOMWindow is going away.
+ if (m_associatedDOMWindow)
+ m_associatedDOMWindow->unregisterProperty(this);
+ m_associatedDOMWindow = 0;
+ m_frame = 0;
+}
+
+void DOMWindowProperty::willDetachGlobalObjectFromFrame()
+{
+ // If the property is getting this callback it must have been created with a Frame/DOMWindow and it should still have them.
+ ASSERT(m_frame);
+ ASSERT(m_associatedDOMWindow);
+}
+
+}
diff --git a/chromium/third_party/WebKit/Source/core/page/DOMWindowProperty.h b/chromium/third_party/WebKit/Source/core/frame/DOMWindowProperty.h
index 3a4645c9081..3a4645c9081 100644
--- a/chromium/third_party/WebKit/Source/core/page/DOMWindowProperty.h
+++ b/chromium/third_party/WebKit/Source/core/frame/DOMWindowProperty.h
diff --git a/chromium/third_party/WebKit/Source/core/frame/DOMWindowTimers.cpp b/chromium/third_party/WebKit/Source/core/frame/DOMWindowTimers.cpp
new file mode 100644
index 00000000000..b0e082c27ed
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/DOMWindowTimers.cpp
@@ -0,0 +1,67 @@
+/*
+ * Copyright (C) 2006, 2007, 2008, 2010 Apple Inc. All rights reserved.
+ * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
+ * Copyright (C) 2013 Samsung Electronics. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/frame/DOMWindowTimers.h"
+
+#include "core/events/EventTarget.h"
+#include "core/frame/DOMTimer.h"
+
+namespace WebCore {
+
+namespace DOMWindowTimers {
+
+int setTimeout(EventTarget* eventTarget, PassOwnPtr<ScheduledAction> action, int timeout)
+{
+ return DOMTimer::install(eventTarget->executionContext(), action, timeout, true);
+}
+
+int setInterval(EventTarget* eventTarget, PassOwnPtr<ScheduledAction> action, int timeout)
+{
+ return DOMTimer::install(eventTarget->executionContext(), action, timeout, false);
+}
+
+void clearTimeout(EventTarget* eventTarget, int timeoutID)
+{
+ if (ExecutionContext* context = eventTarget->executionContext())
+ DOMTimer::removeByID(context, timeoutID);
+}
+
+void clearInterval(EventTarget* eventTarget, int timeoutID)
+{
+ if (ExecutionContext* context = eventTarget->executionContext())
+ DOMTimer::removeByID(context, timeoutID);
+}
+
+} // namespace DOMWindowTimers
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/page/DOMWindowTimers.h b/chromium/third_party/WebKit/Source/core/frame/DOMWindowTimers.h
index 2a28f81810c..2a28f81810c 100644
--- a/chromium/third_party/WebKit/Source/core/page/DOMWindowTimers.h
+++ b/chromium/third_party/WebKit/Source/core/frame/DOMWindowTimers.h
diff --git a/chromium/third_party/WebKit/Source/core/frame/Frame.cpp b/chromium/third_party/WebKit/Source/core/frame/Frame.cpp
new file mode 100644
index 00000000000..cac41bdafc9
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/Frame.cpp
@@ -0,0 +1,708 @@
+/*
+ * Copyright (C) 1998, 1999 Torben Weis <weis@kde.org>
+ * 1999 Lars Knoll <knoll@kde.org>
+ * 1999 Antti Koivisto <koivisto@kde.org>
+ * 2000 Simon Hausmann <hausmann@kde.org>
+ * 2000 Stefan Schimanski <1Stein@gmx.de>
+ * 2001 George Staikos <staikos@kde.org>
+ * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
+ * Copyright (C) 2005 Alexey Proskuryakov <ap@nypop.com>
+ * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
+ * Copyright (C) 2008 Eric Seidel <eric@webkit.org>
+ * Copyright (C) 2008 Google Inc.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#include "config.h"
+#include "core/frame/Frame.h"
+
+#include "RuntimeEnabledFeatures.h"
+#include "bindings/v8/ScriptController.h"
+#include "core/dom/DocumentType.h"
+#include "core/dom/WheelController.h"
+#include "core/editing/Editor.h"
+#include "core/editing/FrameSelection.h"
+#include "core/editing/InputMethodController.h"
+#include "core/editing/SpellChecker.h"
+#include "core/editing/htmlediting.h"
+#include "core/editing/markup.h"
+#include "core/events/Event.h"
+#include "core/fetch/ResourceFetcher.h"
+#include "core/frame/DOMWindow.h"
+#include "core/frame/FrameDestructionObserver.h"
+#include "core/frame/FrameView.h"
+#include "core/frame/Settings.h"
+#include "core/frame/animation/AnimationController.h"
+#include "core/html/HTMLFrameElementBase.h"
+#include "core/inspector/InspectorInstrumentation.h"
+#include "core/loader/EmptyClients.h"
+#include "core/loader/FrameLoaderClient.h"
+#include "core/page/Chrome.h"
+#include "core/page/ChromeClient.h"
+#include "core/page/EventHandler.h"
+#include "core/page/FocusController.h"
+#include "core/page/Page.h"
+#include "core/page/scrolling/ScrollingCoordinator.h"
+#include "core/platform/DragImage.h"
+#include "core/rendering/HitTestResult.h"
+#include "core/rendering/RenderLayerCompositor.h"
+#include "core/rendering/RenderPart.h"
+#include "core/rendering/RenderView.h"
+#include "core/svg/SVGDocument.h"
+#include "platform/graphics/GraphicsContext.h"
+#include "platform/graphics/ImageBuffer.h"
+#include "public/platform/WebLayer.h"
+#include "wtf/PassOwnPtr.h"
+#include "wtf/RefCountedLeakCounter.h"
+#include "wtf/StdLibExtras.h"
+
+using namespace std;
+
+namespace WebCore {
+
+using namespace HTMLNames;
+
+DEFINE_DEBUG_ONLY_GLOBAL(WTF::RefCountedLeakCounter, frameCounter, ("Frame"));
+
+static inline Frame* parentFromOwnerElement(HTMLFrameOwnerElement* ownerElement)
+{
+ if (!ownerElement)
+ return 0;
+ return ownerElement->document().frame();
+}
+
+static inline float parentPageZoomFactor(Frame* frame)
+{
+ Frame* parent = frame->tree().parent();
+ if (!parent)
+ return 1;
+ return parent->pageZoomFactor();
+}
+
+static inline float parentTextZoomFactor(Frame* frame)
+{
+ Frame* parent = frame->tree().parent();
+ if (!parent)
+ return 1;
+ return parent->textZoomFactor();
+}
+
+inline Frame::Frame(PassRefPtr<FrameInit> frameInit)
+ : m_page(frameInit->page())
+ , m_treeNode(this, parentFromOwnerElement(frameInit->ownerElement()))
+ , m_loader(this, frameInit->frameLoaderClient())
+ , m_navigationScheduler(this)
+ , m_script(adoptPtr(new ScriptController(this)))
+ , m_editor(Editor::create(*this))
+ , m_spellChecker(SpellChecker::create(*this))
+ , m_selection(adoptPtr(new FrameSelection(this)))
+ , m_eventHandler(adoptPtr(new EventHandler(this)))
+ , m_animationController(adoptPtr(new AnimationController(this)))
+ , m_inputMethodController(InputMethodController::create(*this))
+ , m_frameInit(frameInit)
+ , m_pageZoomFactor(parentPageZoomFactor(this))
+ , m_textZoomFactor(parentTextZoomFactor(this))
+#if ENABLE(ORIENTATION_EVENTS)
+ , m_orientation(0)
+#endif
+ , m_inViewSourceMode(false)
+ , m_remotePlatformLayer(0)
+{
+ ASSERT(m_page);
+
+ if (ownerElement()) {
+ m_page->incrementSubframeCount();
+ ownerElement()->setContentFrame(*this);
+ }
+
+#ifndef NDEBUG
+ frameCounter.increment();
+#endif
+}
+
+PassRefPtr<Frame> Frame::create(PassRefPtr<FrameInit> frameInit)
+{
+ RefPtr<Frame> frame = adoptRef(new Frame(frameInit));
+ if (!frame->ownerElement())
+ frame->page()->setMainFrame(frame);
+ InspectorInstrumentation::frameAttachedToParent(frame.get());
+ return frame.release();
+}
+
+Frame::~Frame()
+{
+ setView(0);
+ loader().clear(ClearScriptObjects | ClearWindowObject);
+
+ // FIXME: We should not be doing all this work inside the destructor
+
+#ifndef NDEBUG
+ frameCounter.decrement();
+#endif
+
+ disconnectOwnerElement();
+
+ HashSet<FrameDestructionObserver*>::iterator stop = m_destructionObservers.end();
+ for (HashSet<FrameDestructionObserver*>::iterator it = m_destructionObservers.begin(); it != stop; ++it)
+ (*it)->frameDestroyed();
+}
+
+bool Frame::inScope(TreeScope* scope) const
+{
+ ASSERT(scope);
+ Document* doc = document();
+ if (!doc)
+ return false;
+ HTMLFrameOwnerElement* owner = doc->ownerElement();
+ if (!owner)
+ return false;
+ return owner->treeScope() == scope;
+}
+
+void Frame::addDestructionObserver(FrameDestructionObserver* observer)
+{
+ m_destructionObservers.add(observer);
+}
+
+void Frame::removeDestructionObserver(FrameDestructionObserver* observer)
+{
+ m_destructionObservers.remove(observer);
+}
+
+void Frame::setView(PassRefPtr<FrameView> view)
+{
+ // We the custom scroll bars as early as possible to prevent m_doc->detach()
+ // from messing with the view such that its scroll bars won't be torn down.
+ // FIXME: We should revisit this.
+ if (m_view)
+ m_view->prepareForDetach();
+
+ // Prepare for destruction now, so any unload event handlers get run and the DOMWindow is
+ // notified. If we wait until the view is destroyed, then things won't be hooked up enough for
+ // these calls to work.
+ if (!view && document() && document()->isActive()) {
+ // FIXME: We don't call willRemove here. Why is that OK?
+ document()->prepareForDestruction();
+ }
+
+ if (m_view)
+ m_view->unscheduleRelayout();
+
+ eventHandler().clear();
+
+ m_view = view;
+
+ if (m_view && isMainFrame())
+ m_view->setVisibleContentScaleFactor(m_page->pageScaleFactor());
+}
+
+#if ENABLE(ORIENTATION_EVENTS)
+void Frame::sendOrientationChangeEvent(int orientation)
+{
+ m_orientation = orientation;
+ if (DOMWindow* window = domWindow())
+ window->dispatchEvent(Event::create(EventTypeNames::orientationchange));
+}
+#endif // ENABLE(ORIENTATION_EVENTS)
+
+Settings* Frame::settings() const
+{
+ return m_page ? &m_page->settings() : 0;
+}
+
+void Frame::setPrinting(bool printing, const FloatSize& pageSize, const FloatSize& originalPageSize, float maximumShrinkRatio, AdjustViewSizeOrNot shouldAdjustViewSize)
+{
+ // In setting printing, we should not validate resources already cached for the document.
+ // See https://bugs.webkit.org/show_bug.cgi?id=43704
+ ResourceCacheValidationSuppressor validationSuppressor(document()->fetcher());
+
+ document()->setPrinting(printing);
+ view()->adjustMediaTypeForPrinting(printing);
+
+ document()->styleResolverChanged(RecalcStyleImmediately);
+ if (shouldUsePrintingLayout()) {
+ view()->forceLayoutForPagination(pageSize, originalPageSize, maximumShrinkRatio, shouldAdjustViewSize);
+ } else {
+ view()->forceLayout();
+ if (shouldAdjustViewSize == AdjustViewSize)
+ view()->adjustViewSize();
+ }
+
+ // Subframes of the one we're printing don't lay out to the page size.
+ for (RefPtr<Frame> child = tree().firstChild(); child; child = child->tree().nextSibling())
+ child->setPrinting(printing, FloatSize(), FloatSize(), 0, shouldAdjustViewSize);
+}
+
+bool Frame::shouldUsePrintingLayout() const
+{
+ // Only top frame being printed should be fit to page size.
+ // Subframes should be constrained by parents only.
+ return document()->printing() && (!tree().parent() || !tree().parent()->document()->printing());
+}
+
+FloatSize Frame::resizePageRectsKeepingRatio(const FloatSize& originalSize, const FloatSize& expectedSize)
+{
+ FloatSize resultSize;
+ if (!contentRenderer())
+ return FloatSize();
+
+ if (contentRenderer()->style()->isHorizontalWritingMode()) {
+ ASSERT(fabs(originalSize.width()) > numeric_limits<float>::epsilon());
+ float ratio = originalSize.height() / originalSize.width();
+ resultSize.setWidth(floorf(expectedSize.width()));
+ resultSize.setHeight(floorf(resultSize.width() * ratio));
+ } else {
+ ASSERT(fabs(originalSize.height()) > numeric_limits<float>::epsilon());
+ float ratio = originalSize.width() / originalSize.height();
+ resultSize.setHeight(floorf(expectedSize.height()));
+ resultSize.setWidth(floorf(resultSize.height() * ratio));
+ }
+ return resultSize;
+}
+
+void Frame::setDOMWindow(PassRefPtr<DOMWindow> domWindow)
+{
+ m_domWindow = domWindow;
+}
+
+static ChromeClient& emptyChromeClient()
+{
+ DEFINE_STATIC_LOCAL(EmptyChromeClient, client, ());
+ return client;
+}
+
+ChromeClient& Frame::chromeClient() const
+{
+ if (Page* page = this->page())
+ return page->chrome().client();
+ return emptyChromeClient();
+}
+
+Document* Frame::document() const
+{
+ return m_domWindow ? m_domWindow->document() : 0;
+}
+
+RenderView* Frame::contentRenderer() const
+{
+ return document() ? document()->renderView() : 0;
+}
+
+RenderPart* Frame::ownerRenderer() const
+{
+ if (!ownerElement())
+ return 0;
+ RenderObject* object = ownerElement()->renderer();
+ if (!object)
+ return 0;
+ // FIXME: If <object> is ever fixed to disassociate itself from frames
+ // that it has started but canceled, then this can turn into an ASSERT
+ // since ownerElement() would be 0 when the load is canceled.
+ // https://bugs.webkit.org/show_bug.cgi?id=18585
+ if (!object->isRenderPart())
+ return 0;
+ return toRenderPart(object);
+}
+
+void Frame::dispatchVisibilityStateChangeEvent()
+{
+ if (document())
+ document()->dispatchVisibilityStateChangeEvent();
+
+ Vector<RefPtr<Frame> > childFrames;
+ for (Frame* child = tree().firstChild(); child; child = child->tree().nextSibling())
+ childFrames.append(child);
+
+ for (size_t i = 0; i < childFrames.size(); ++i)
+ childFrames[i]->dispatchVisibilityStateChangeEvent();
+}
+
+void Frame::willDetachPage()
+{
+ // We should never be detatching the page during a Layout.
+ RELEASE_ASSERT(!m_view || !m_view->isInLayout());
+
+ if (Frame* parent = tree().parent())
+ parent->loader().checkLoadComplete();
+
+ HashSet<FrameDestructionObserver*>::iterator stop = m_destructionObservers.end();
+ for (HashSet<FrameDestructionObserver*>::iterator it = m_destructionObservers.begin(); it != stop; ++it)
+ (*it)->willDetachPage();
+
+ // FIXME: It's unclear as to why this is called more than once, but it is,
+ // so page() could be NULL.
+ if (page() && page()->focusController().focusedFrame() == this)
+ page()->focusController().setFocusedFrame(0);
+
+ if (page() && page()->scrollingCoordinator() && m_view)
+ page()->scrollingCoordinator()->willDestroyScrollableArea(m_view.get());
+
+ script().clearScriptObjects();
+}
+
+void Frame::detachFromPage()
+{
+ // We should never be detatching the page during a Layout.
+ RELEASE_ASSERT(!m_view || !m_view->isInLayout());
+ m_page = 0;
+}
+
+void Frame::disconnectOwnerElement()
+{
+ if (ownerElement()) {
+ if (Document* doc = document())
+ doc->topDocument()->clearAXObjectCache();
+ ownerElement()->clearContentFrame();
+ if (m_page)
+ m_page->decrementSubframeCount();
+ }
+ m_frameInit->setOwnerElement(0);
+}
+
+bool Frame::isMainFrame() const
+{
+ return m_page && this == m_page->mainFrame();
+}
+
+String Frame::documentTypeString() const
+{
+ if (DocumentType* doctype = document()->doctype())
+ return createMarkup(doctype);
+
+ return String();
+}
+
+String Frame::selectedText() const
+{
+ return selection().selectedText();
+}
+
+String Frame::selectedTextForClipboard() const
+{
+ return selection().selectedTextForClipboard();
+}
+
+VisiblePosition Frame::visiblePositionForPoint(const IntPoint& framePoint)
+{
+ HitTestResult result = eventHandler().hitTestResultAtPoint(framePoint);
+ Node* node = result.innerNonSharedNode();
+ if (!node)
+ return VisiblePosition();
+ RenderObject* renderer = node->renderer();
+ if (!renderer)
+ return VisiblePosition();
+ VisiblePosition visiblePos = VisiblePosition(renderer->positionForPoint(result.localPoint()));
+ if (visiblePos.isNull())
+ visiblePos = firstPositionInOrBeforeNode(node);
+ return visiblePos;
+}
+
+Document* Frame::documentAtPoint(const IntPoint& point)
+{
+ if (!view())
+ return 0;
+
+ IntPoint pt = view()->windowToContents(point);
+ HitTestResult result = HitTestResult(pt);
+
+ if (contentRenderer())
+ result = eventHandler().hitTestResultAtPoint(pt, HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent);
+ return result.innerNode() ? &result.innerNode()->document() : 0;
+}
+
+PassRefPtr<Range> Frame::rangeForPoint(const IntPoint& framePoint)
+{
+ VisiblePosition position = visiblePositionForPoint(framePoint);
+ if (position.isNull())
+ return 0;
+
+ VisiblePosition previous = position.previous();
+ if (previous.isNotNull()) {
+ RefPtr<Range> previousCharacterRange = makeRange(previous, position);
+ LayoutRect rect = editor().firstRectForRange(previousCharacterRange.get());
+ if (rect.contains(framePoint))
+ return previousCharacterRange.release();
+ }
+
+ VisiblePosition next = position.next();
+ if (RefPtr<Range> nextCharacterRange = makeRange(position, next)) {
+ LayoutRect rect = editor().firstRectForRange(nextCharacterRange.get());
+ if (rect.contains(framePoint))
+ return nextCharacterRange.release();
+ }
+
+ return 0;
+}
+
+void Frame::createView(const IntSize& viewportSize, const Color& backgroundColor, bool transparent,
+ ScrollbarMode horizontalScrollbarMode, bool horizontalLock,
+ ScrollbarMode verticalScrollbarMode, bool verticalLock)
+{
+ ASSERT(this);
+ ASSERT(m_page);
+
+ bool isMainFrame = this->isMainFrame();
+
+ if (isMainFrame && view())
+ view()->setParentVisible(false);
+
+ setView(0);
+
+ RefPtr<FrameView> frameView;
+ if (isMainFrame) {
+ frameView = FrameView::create(this, viewportSize);
+
+ // The layout size is set by WebViewImpl to support @viewport
+ frameView->setLayoutSizeFixedToFrameSize(false);
+ } else
+ frameView = FrameView::create(this);
+
+ frameView->setScrollbarModes(horizontalScrollbarMode, verticalScrollbarMode, horizontalLock, verticalLock);
+
+ setView(frameView);
+
+ if (backgroundColor.isValid())
+ frameView->updateBackgroundRecursively(backgroundColor, transparent);
+
+ if (isMainFrame)
+ frameView->setParentVisible(true);
+
+ if (ownerRenderer())
+ ownerRenderer()->setWidget(frameView);
+
+ if (HTMLFrameOwnerElement* owner = ownerElement())
+ view()->setCanHaveScrollbars(owner->scrollingMode() != ScrollbarAlwaysOff);
+}
+
+String Frame::layerTreeAsText(unsigned flags) const
+{
+ document()->updateLayout();
+
+ if (!contentRenderer())
+ return String();
+
+ return contentRenderer()->compositor()->layerTreeAsText(static_cast<LayerTreeFlags>(flags));
+}
+
+String Frame::trackedRepaintRectsAsText() const
+{
+ if (!m_view)
+ return String();
+ return m_view->trackedRepaintRectsAsText();
+}
+
+void Frame::setPageZoomFactor(float factor)
+{
+ setPageAndTextZoomFactors(factor, m_textZoomFactor);
+}
+
+void Frame::setTextZoomFactor(float factor)
+{
+ setPageAndTextZoomFactors(m_pageZoomFactor, factor);
+}
+
+void Frame::setPageAndTextZoomFactors(float pageZoomFactor, float textZoomFactor)
+{
+ if (m_pageZoomFactor == pageZoomFactor && m_textZoomFactor == textZoomFactor)
+ return;
+
+ Page* page = this->page();
+ if (!page)
+ return;
+
+ Document* document = this->document();
+ if (!document)
+ return;
+
+ // Respect SVGs zoomAndPan="disabled" property in standalone SVG documents.
+ // FIXME: How to handle compound documents + zoomAndPan="disabled"? Needs SVG WG clarification.
+ if (document->isSVGDocument()) {
+ if (!toSVGDocument(document)->zoomAndPanEnabled())
+ return;
+ }
+
+ if (m_pageZoomFactor != pageZoomFactor) {
+ if (FrameView* view = this->view()) {
+ // Update the scroll position when doing a full page zoom, so the content stays in relatively the same position.
+ LayoutPoint scrollPosition = view->scrollPosition();
+ float percentDifference = (pageZoomFactor / m_pageZoomFactor);
+ view->setScrollPosition(IntPoint(scrollPosition.x() * percentDifference, scrollPosition.y() * percentDifference));
+ }
+ }
+
+ m_pageZoomFactor = pageZoomFactor;
+ m_textZoomFactor = textZoomFactor;
+
+ document->recalcStyle(Force);
+
+ for (RefPtr<Frame> child = tree().firstChild(); child; child = child->tree().nextSibling())
+ child->setPageAndTextZoomFactors(m_pageZoomFactor, m_textZoomFactor);
+
+ if (FrameView* view = this->view()) {
+ if (document->renderer() && document->renderer()->needsLayout() && view->didFirstLayout())
+ view->layout();
+ }
+}
+
+void Frame::deviceOrPageScaleFactorChanged()
+{
+ document()->mediaQueryAffectingValueChanged();
+ for (RefPtr<Frame> child = tree().firstChild(); child; child = child->tree().nextSibling())
+ child->deviceOrPageScaleFactorChanged();
+}
+
+void Frame::notifyChromeClientWheelEventHandlerCountChanged() const
+{
+ // Ensure that this method is being called on the main frame of the page.
+ ASSERT(isMainFrame());
+
+ unsigned count = 0;
+ for (const Frame* frame = this; frame; frame = frame->tree().traverseNext()) {
+ if (frame->document())
+ count += WheelController::from(frame->document())->wheelEventHandlerCount();
+ }
+
+ m_page->chrome().client().numWheelEventHandlersChanged(count);
+}
+
+bool Frame::isURLAllowed(const KURL& url) const
+{
+ // We allow one level of self-reference because some sites depend on that,
+ // but we don't allow more than one.
+ if (m_page->subframeCount() >= Page::maxNumberOfFrames)
+ return false;
+ bool foundSelfReference = false;
+ for (const Frame* frame = this; frame; frame = frame->tree().parent()) {
+ if (equalIgnoringFragmentIdentifier(frame->document()->url(), url)) {
+ if (foundSelfReference)
+ return false;
+ foundSelfReference = true;
+ }
+ }
+ return true;
+}
+
+struct ScopedFramePaintingState {
+ ScopedFramePaintingState(Frame* frame, Node* node)
+ : frame(frame)
+ , node(node)
+ , paintBehavior(frame->view()->paintBehavior())
+ , backgroundColor(frame->view()->baseBackgroundColor())
+ {
+ ASSERT(!node || node->renderer());
+ if (node)
+ node->renderer()->updateDragState(true);
+ }
+
+ ~ScopedFramePaintingState()
+ {
+ if (node && node->renderer())
+ node->renderer()->updateDragState(false);
+ frame->view()->setPaintBehavior(paintBehavior);
+ frame->view()->setBaseBackgroundColor(backgroundColor);
+ frame->view()->setNodeToDraw(0);
+ }
+
+ Frame* frame;
+ Node* node;
+ PaintBehavior paintBehavior;
+ Color backgroundColor;
+};
+
+PassOwnPtr<DragImage> Frame::nodeImage(Node* node)
+{
+ if (!node->renderer())
+ return nullptr;
+
+ const ScopedFramePaintingState state(this, node);
+
+ m_view->setPaintBehavior(state.paintBehavior | PaintBehaviorFlattenCompositingLayers);
+
+ // When generating the drag image for an element, ignore the document background.
+ m_view->setBaseBackgroundColor(Color::transparent);
+ document()->updateLayout();
+ m_view->setNodeToDraw(node); // Enable special sub-tree drawing mode.
+
+ // Document::updateLayout may have blown away the original RenderObject.
+ RenderObject* renderer = node->renderer();
+ if (!renderer)
+ return nullptr;
+
+ LayoutRect topLevelRect;
+ IntRect paintingRect = pixelSnappedIntRect(renderer->paintingRootRect(topLevelRect));
+
+ float deviceScaleFactor = 1;
+ if (m_page)
+ deviceScaleFactor = m_page->deviceScaleFactor();
+ paintingRect.setWidth(paintingRect.width() * deviceScaleFactor);
+ paintingRect.setHeight(paintingRect.height() * deviceScaleFactor);
+
+ OwnPtr<ImageBuffer> buffer = ImageBuffer::create(paintingRect.size());
+ if (!buffer)
+ return nullptr;
+ buffer->context()->scale(FloatSize(deviceScaleFactor, deviceScaleFactor));
+ buffer->context()->translate(-paintingRect.x(), -paintingRect.y());
+ buffer->context()->clip(FloatRect(0, 0, paintingRect.maxX(), paintingRect.maxY()));
+
+ m_view->paintContents(buffer->context(), paintingRect);
+
+ RefPtr<Image> image = buffer->copyImage();
+ return DragImage::create(image.get(), renderer->shouldRespectImageOrientation(), deviceScaleFactor);
+}
+
+PassOwnPtr<DragImage> Frame::dragImageForSelection()
+{
+ if (!selection().isRange())
+ return nullptr;
+
+ const ScopedFramePaintingState state(this, 0);
+ m_view->setPaintBehavior(PaintBehaviorSelectionOnly | PaintBehaviorFlattenCompositingLayers);
+ document()->updateLayout();
+
+ IntRect paintingRect = enclosingIntRect(selection().bounds());
+
+ float deviceScaleFactor = 1;
+ if (m_page)
+ deviceScaleFactor = m_page->deviceScaleFactor();
+ paintingRect.setWidth(paintingRect.width() * deviceScaleFactor);
+ paintingRect.setHeight(paintingRect.height() * deviceScaleFactor);
+
+ OwnPtr<ImageBuffer> buffer = ImageBuffer::create(paintingRect.size());
+ if (!buffer)
+ return nullptr;
+ buffer->context()->scale(FloatSize(deviceScaleFactor, deviceScaleFactor));
+ buffer->context()->translate(-paintingRect.x(), -paintingRect.y());
+ buffer->context()->clip(FloatRect(0, 0, paintingRect.maxX(), paintingRect.maxY()));
+
+ m_view->paintContents(buffer->context(), paintingRect);
+
+ RefPtr<Image> image = buffer->copyImage();
+ return DragImage::create(image.get(), DoNotRespectImageOrientation, deviceScaleFactor);
+}
+
+double Frame::devicePixelRatio() const
+{
+ if (!m_page)
+ return 0;
+
+ double ratio = m_page->deviceScaleFactor();
+ if (RuntimeEnabledFeatures::devicePixelRatioIncludesZoomEnabled())
+ ratio *= pageZoomFactor();
+ return ratio;
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/frame/Frame.h b/chromium/third_party/WebKit/Source/core/frame/Frame.h
new file mode 100644
index 00000000000..3c669f7db3d
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/Frame.h
@@ -0,0 +1,338 @@
+/*
+ * Copyright (C) 1998, 1999 Torben Weis <weis@kde.org>
+ * 1999-2001 Lars Knoll <knoll@kde.org>
+ * 1999-2001 Antti Koivisto <koivisto@kde.org>
+ * 2000-2001 Simon Hausmann <hausmann@kde.org>
+ * 2000-2001 Dirk Mueller <mueller@kde.org>
+ * 2000 Stefan Schimanski <1Stein@gmx.de>
+ * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010 Apple Inc. All rights reserved.
+ * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
+ * Copyright (C) 2008 Eric Seidel <eric@webkit.org>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#ifndef Frame_h
+#define Frame_h
+
+#include "core/loader/FrameLoader.h"
+#include "core/loader/NavigationScheduler.h"
+#include "core/frame/AdjustViewSizeOrNot.h"
+#include "core/page/FrameTree.h"
+#include "platform/geometry/IntSize.h"
+#include "platform/scroll/ScrollTypes.h"
+#include "wtf/Forward.h"
+#include "wtf/RefCounted.h"
+
+namespace blink {
+class WebLayer;
+}
+
+namespace WebCore {
+
+ class AnimationController;
+ class ChromeClient;
+ class Color;
+ class DOMWindow;
+ class Document;
+ class DragImage;
+ class Editor;
+ class Element;
+ class EventHandler;
+ class FetchContext;
+ class FloatSize;
+ class FrameDestructionObserver;
+ class FrameSelection;
+ class FrameView;
+ class HTMLFrameOwnerElement;
+ class HTMLTableCellElement;
+ class InputMethodController;
+ class IntPoint;
+ class Node;
+ class Range;
+ class RenderPart;
+ class RenderView;
+ class TreeScope;
+ class ScriptController;
+ class Settings;
+ class SpellChecker;
+ class TreeScope;
+ class VisiblePosition;
+ class Widget;
+
+ class FrameInit : public RefCounted<FrameInit> {
+ public:
+ // For creating a dummy Frame
+ static PassRefPtr<FrameInit> create(int64_t frameID, Page* page, FrameLoaderClient* client)
+ {
+ return adoptRef(new FrameInit(frameID, page, client));
+ }
+
+ void setFrameLoaderClient(FrameLoaderClient* client) { m_client = client; }
+ FrameLoaderClient* frameLoaderClient() const { return m_client; }
+
+ int64_t frameID() const { return m_frameID; }
+
+ void setPage(Page* page) { m_page = page; }
+ Page* page() const { return m_page; }
+
+ void setOwnerElement(HTMLFrameOwnerElement* ownerElement) { m_ownerElement = ownerElement; }
+ HTMLFrameOwnerElement* ownerElement() const { return m_ownerElement; }
+
+ protected:
+ FrameInit(int64_t frameID, Page* page = 0, FrameLoaderClient* client = 0)
+ : m_frameID(frameID)
+ , m_client(client)
+ , m_page(page)
+ , m_ownerElement(0)
+ {
+ }
+
+ private:
+ int64_t m_frameID;
+ FrameLoaderClient* m_client;
+ Page* m_page;
+ HTMLFrameOwnerElement* m_ownerElement;
+ };
+
+ class Frame : public RefCounted<Frame> {
+ public:
+ static PassRefPtr<Frame> create(PassRefPtr<FrameInit>);
+
+ void init();
+ void setView(PassRefPtr<FrameView>);
+ void createView(const IntSize&, const Color&, bool,
+ ScrollbarMode = ScrollbarAuto, bool horizontalLock = false,
+ ScrollbarMode = ScrollbarAuto, bool verticalLock = false);
+
+ ~Frame();
+
+ void addDestructionObserver(FrameDestructionObserver*);
+ void removeDestructionObserver(FrameDestructionObserver*);
+
+ void willDetachPage();
+ void detachFromPage();
+ void disconnectOwnerElement();
+
+ Page* page() const;
+ HTMLFrameOwnerElement* ownerElement() const;
+ bool isMainFrame() const;
+
+ void setDOMWindow(PassRefPtr<DOMWindow>);
+ DOMWindow* domWindow() const;
+ Document* document() const;
+ FrameView* view() const;
+
+ ChromeClient& chromeClient() const;
+ Editor& editor() const;
+ EventHandler& eventHandler() const;
+ FrameLoader& loader() const;
+ NavigationScheduler& navigationScheduler() const;
+ FrameSelection& selection() const;
+ FrameTree& tree() const;
+ AnimationController& animation() const;
+ InputMethodController& inputMethodController() const;
+ FetchContext& fetchContext() const { return loader().fetchContext(); }
+ ScriptController& script();
+ SpellChecker& spellChecker() const;
+
+ RenderView* contentRenderer() const; // Root of the render tree for the document contained in this frame.
+ RenderPart* ownerRenderer() const; // Renderer for the element that contains this frame.
+
+ void dispatchVisibilityStateChangeEvent();
+
+ int64_t frameID() const { return m_frameInit->frameID(); }
+
+ void setRemotePlatformLayer(blink::WebLayer* remotePlatformLayer) { m_remotePlatformLayer = remotePlatformLayer; }
+ blink::WebLayer* remotePlatformLayer() const { return m_remotePlatformLayer; }
+
+ // ======== All public functions below this point are candidates to move out of Frame into another class. ========
+
+ bool inScope(TreeScope*) const;
+
+ // See GraphicsLayerClient.h for accepted flags.
+ String layerTreeAsText(unsigned flags = 0) const;
+ String trackedRepaintRectsAsText() const;
+
+ Settings* settings() const; // can be NULL
+
+ void setPrinting(bool printing, const FloatSize& pageSize, const FloatSize& originalPageSize, float maximumShrinkRatio, AdjustViewSizeOrNot);
+ bool shouldUsePrintingLayout() const;
+ FloatSize resizePageRectsKeepingRatio(const FloatSize& originalSize, const FloatSize& expectedSize);
+
+ bool inViewSourceMode() const;
+ void setInViewSourceMode(bool = true);
+
+ void setPageZoomFactor(float factor);
+ float pageZoomFactor() const { return m_pageZoomFactor; }
+ void setTextZoomFactor(float factor);
+ float textZoomFactor() const { return m_textZoomFactor; }
+ void setPageAndTextZoomFactors(float pageZoomFactor, float textZoomFactor);
+
+ void deviceOrPageScaleFactorChanged();
+ double devicePixelRatio() const;
+
+#if ENABLE(ORIENTATION_EVENTS)
+ // Orientation is the interface orientation in degrees. Some examples are:
+ // 0 is straight up; -90 is when the device is rotated 90 clockwise;
+ // 90 is when rotated counter clockwise.
+ void sendOrientationChangeEvent(int orientation);
+ int orientation() const { return m_orientation; }
+#endif
+
+ String documentTypeString() const;
+
+ PassOwnPtr<DragImage> nodeImage(Node*);
+ PassOwnPtr<DragImage> dragImageForSelection();
+
+ String selectedText() const;
+ String selectedTextForClipboard() const;
+
+ VisiblePosition visiblePositionForPoint(const IntPoint& framePoint);
+ Document* documentAtPoint(const IntPoint& windowPoint);
+ PassRefPtr<Range> rangeForPoint(const IntPoint& framePoint);
+
+ // Should only be called on the main frame of a page.
+ void notifyChromeClientWheelEventHandlerCountChanged() const;
+
+ bool isURLAllowed(const KURL&) const;
+
+ // ========
+
+ private:
+ Frame(PassRefPtr<FrameInit>);
+
+ HashSet<FrameDestructionObserver*> m_destructionObservers;
+
+ Page* m_page;
+ mutable FrameTree m_treeNode;
+ mutable FrameLoader m_loader;
+ mutable NavigationScheduler m_navigationScheduler;
+
+ RefPtr<FrameView> m_view;
+ RefPtr<DOMWindow> m_domWindow;
+
+ OwnPtr<ScriptController> m_script;
+ const OwnPtr<Editor> m_editor;
+ const OwnPtr<SpellChecker> m_spellChecker;
+ const OwnPtr<FrameSelection> m_selection;
+ const OwnPtr<EventHandler> m_eventHandler;
+ OwnPtr<AnimationController> m_animationController;
+ OwnPtr<InputMethodController> m_inputMethodController;
+
+ RefPtr<FrameInit> m_frameInit;
+
+ float m_pageZoomFactor;
+ float m_textZoomFactor;
+
+#if ENABLE(ORIENTATION_EVENTS)
+ int m_orientation;
+#endif
+
+ bool m_inViewSourceMode;
+
+ blink::WebLayer* m_remotePlatformLayer;
+ };
+
+ inline void Frame::init()
+ {
+ m_loader.init();
+ }
+
+ inline FrameLoader& Frame::loader() const
+ {
+ return m_loader;
+ }
+
+ inline NavigationScheduler& Frame::navigationScheduler() const
+ {
+ return m_navigationScheduler;
+ }
+
+ inline FrameView* Frame::view() const
+ {
+ return m_view.get();
+ }
+
+ inline ScriptController& Frame::script()
+ {
+ return *m_script;
+ }
+
+ inline DOMWindow* Frame::domWindow() const
+ {
+ return m_domWindow.get();
+ }
+
+ inline FrameSelection& Frame::selection() const
+ {
+ return *m_selection;
+ }
+
+ inline Editor& Frame::editor() const
+ {
+ return *m_editor;
+ }
+
+ inline SpellChecker& Frame::spellChecker() const
+ {
+ return *m_spellChecker;
+ }
+
+ inline AnimationController& Frame::animation() const
+ {
+ return *m_animationController;
+ }
+
+ inline InputMethodController& Frame::inputMethodController() const
+ {
+ return *m_inputMethodController;
+ }
+
+ inline HTMLFrameOwnerElement* Frame::ownerElement() const
+ {
+ return m_frameInit->ownerElement();
+ }
+
+ inline bool Frame::inViewSourceMode() const
+ {
+ return m_inViewSourceMode;
+ }
+
+ inline void Frame::setInViewSourceMode(bool mode)
+ {
+ m_inViewSourceMode = mode;
+ }
+
+ inline FrameTree& Frame::tree() const
+ {
+ return m_treeNode;
+ }
+
+ inline Page* Frame::page() const
+ {
+ return m_page;
+ }
+
+ inline EventHandler& Frame::eventHandler() const
+ {
+ ASSERT(m_eventHandler);
+ return *m_eventHandler;
+ }
+
+} // namespace WebCore
+
+#endif // Frame_h
diff --git a/chromium/third_party/WebKit/Source/core/frame/FrameDestructionObserver.cpp b/chromium/third_party/WebKit/Source/core/frame/FrameDestructionObserver.cpp
new file mode 100644
index 00000000000..ea3923e5cdc
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/FrameDestructionObserver.cpp
@@ -0,0 +1,66 @@
+/*
+ * Copyright (C) 2011 Google, Inc. All Rights Reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY GOOGLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/frame/FrameDestructionObserver.h"
+
+#include "core/frame/Frame.h"
+
+namespace WebCore {
+
+FrameDestructionObserver::FrameDestructionObserver(Frame* frame)
+ : m_frame(0)
+{
+ observeFrame(frame);
+}
+
+FrameDestructionObserver::~FrameDestructionObserver()
+{
+ observeFrame(0);
+
+}
+
+void FrameDestructionObserver::observeFrame(Frame* frame)
+{
+ if (m_frame)
+ m_frame->removeDestructionObserver(this);
+
+ m_frame = frame;
+
+ if (m_frame)
+ m_frame->addDestructionObserver(this);
+}
+
+void FrameDestructionObserver::frameDestroyed()
+{
+ m_frame = 0;
+}
+
+void FrameDestructionObserver::willDetachPage()
+{
+ // Subclasses should override this function to handle this notification.
+}
+
+}
diff --git a/chromium/third_party/WebKit/Source/core/page/FrameDestructionObserver.h b/chromium/third_party/WebKit/Source/core/frame/FrameDestructionObserver.h
index 8989e4a9f53..8989e4a9f53 100644
--- a/chromium/third_party/WebKit/Source/core/page/FrameDestructionObserver.h
+++ b/chromium/third_party/WebKit/Source/core/frame/FrameDestructionObserver.h
diff --git a/chromium/third_party/WebKit/Source/core/frame/FrameView.cpp b/chromium/third_party/WebKit/Source/core/frame/FrameView.cpp
new file mode 100644
index 00000000000..5bb9474eec3
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/FrameView.cpp
@@ -0,0 +1,3513 @@
+/*
+ * Copyright (C) 1998, 1999 Torben Weis <weis@kde.org>
+ * 1999 Lars Knoll <knoll@kde.org>
+ * 1999 Antti Koivisto <koivisto@kde.org>
+ * 2000 Dirk Mueller <mueller@kde.org>
+ * Copyright (C) 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
+ * (C) 2006 Graham Dennis (graham.dennis@gmail.com)
+ * (C) 2006 Alexey Proskuryakov (ap@nypop.com)
+ * Copyright (C) 2009 Google Inc. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#include "config.h"
+#include "core/frame/FrameView.h"
+
+#include "HTMLNames.h"
+#include "RuntimeEnabledFeatures.h"
+#include "core/accessibility/AXObjectCache.h"
+#include "core/animation/DocumentAnimations.h"
+#include "core/css/FontFaceSet.h"
+#include "core/css/resolver/StyleResolver.h"
+#include "core/dom/DocumentMarkerController.h"
+#include "core/editing/FrameSelection.h"
+#include "core/events/OverflowEvent.h"
+#include "core/fetch/ResourceFetcher.h"
+#include "core/fetch/ResourceLoadPriorityOptimizer.h"
+#include "core/fetch/TextResourceDecoder.h"
+#include "core/frame/Frame.h"
+#include "core/frame/GraphicsLayerDebugInfo.h"
+#include "core/frame/Settings.h"
+#include "core/frame/animation/AnimationController.h"
+#include "core/html/HTMLFrameElement.h"
+#include "core/html/HTMLHtmlElement.h"
+#include "core/html/HTMLPlugInElement.h"
+#include "core/inspector/InspectorInstrumentation.h"
+#include "core/loader/FrameLoader.h"
+#include "core/loader/FrameLoaderClient.h"
+#include "core/page/Chrome.h"
+#include "core/page/ChromeClient.h"
+#include "core/page/EventHandler.h"
+#include "core/page/FocusController.h"
+#include "core/page/FrameTree.h"
+#include "core/page/scrolling/ScrollingCoordinator.h"
+#include "core/rendering/CompositedLayerMapping.h"
+#include "core/rendering/LayoutIndicator.h"
+#include "core/rendering/RenderCounter.h"
+#include "core/rendering/RenderEmbeddedObject.h"
+#include "core/rendering/RenderLayer.h"
+#include "core/rendering/RenderLayerCompositor.h"
+#include "core/rendering/RenderPart.h"
+#include "core/rendering/RenderScrollbar.h"
+#include "core/rendering/RenderScrollbarPart.h"
+#include "core/rendering/RenderTheme.h"
+#include "core/rendering/RenderView.h"
+#include "core/rendering/TextAutosizer.h"
+#include "core/rendering/style/RenderStyle.h"
+#include "core/rendering/svg/RenderSVGRoot.h"
+#include "core/svg/SVGDocument.h"
+#include "core/svg/SVGSVGElement.h"
+#include "platform/TraceEvent.h"
+#include "platform/fonts/FontCache.h"
+#include "platform/geometry/FloatRect.h"
+#include "platform/graphics/GraphicsContext.h"
+#include "platform/scroll/ScrollAnimator.h"
+#include "platform/scroll/ScrollbarTheme.h"
+#include "platform/text/TextStream.h"
+#include "wtf/CurrentTime.h"
+#include "wtf/TemporaryChange.h"
+
+namespace WebCore {
+
+using namespace HTMLNames;
+
+double FrameView::s_currentFrameTimeStamp = 0.0;
+bool FrameView::s_inPaintContents = false;
+
+
+// REPAINT_THROTTLING now chooses default values for throttling parameters.
+// Should be removed when applications start using runtime configuration.
+#if ENABLE(REPAINT_THROTTLING)
+// Normal delay
+double FrameView::s_normalDeferredRepaintDelay = 0.016;
+// Negative value would mean that first few repaints happen without a delay
+double FrameView::s_initialDeferredRepaintDelayDuringLoading = 0;
+// The delay grows on each repaint to this maximum value
+double FrameView::s_maxDeferredRepaintDelayDuringLoading = 2.5;
+// On each repaint the delay increses by this amount
+double FrameView::s_deferredRepaintDelayIncrementDuringLoading = 0.5;
+#else
+// FIXME: Repaint throttling could be good to have on all platform.
+// The balance between CPU use and repaint frequency will need some tuning for desktop.
+// More hooks may be needed to reset the delay on things like GIF and CSS animations.
+double FrameView::s_normalDeferredRepaintDelay = 0;
+double FrameView::s_initialDeferredRepaintDelayDuringLoading = 0;
+double FrameView::s_maxDeferredRepaintDelayDuringLoading = 0;
+double FrameView::s_deferredRepaintDelayIncrementDuringLoading = 0;
+#endif
+
+// The maximum number of updateWidgets iterations that should be done before returning.
+static const unsigned maxUpdateWidgetsIterations = 2;
+
+static RenderLayer::UpdateLayerPositionsFlags updateLayerPositionFlags(RenderLayer* layer, bool isRelayoutingSubtree, bool didFullRepaint)
+{
+ RenderLayer::UpdateLayerPositionsFlags flags = RenderLayer::defaultFlags;
+
+ if (didFullRepaint) {
+ flags &= ~RenderLayer::CheckForRepaint;
+ flags |= RenderLayer::NeedsFullRepaintInBacking;
+ }
+ if (isRelayoutingSubtree && layer->isPaginated())
+ flags |= RenderLayer::UpdatePagination;
+ return flags;
+}
+
+Pagination::Mode paginationModeForRenderStyle(RenderStyle* style)
+{
+ EOverflow overflow = style->overflowY();
+ if (overflow != OPAGEDX && overflow != OPAGEDY)
+ return Pagination::Unpaginated;
+
+ bool isHorizontalWritingMode = style->isHorizontalWritingMode();
+ TextDirection textDirection = style->direction();
+ WritingMode writingMode = style->writingMode();
+
+ // paged-x always corresponds to LeftToRightPaginated or RightToLeftPaginated. If the WritingMode
+ // is horizontal, then we use TextDirection to choose between those options. If the WritingMode
+ // is vertical, then the direction of the verticality dictates the choice.
+ if (overflow == OPAGEDX) {
+ if ((isHorizontalWritingMode && textDirection == LTR) || writingMode == LeftToRightWritingMode)
+ return Pagination::LeftToRightPaginated;
+ return Pagination::RightToLeftPaginated;
+ }
+
+ // paged-y always corresponds to TopToBottomPaginated or BottomToTopPaginated. If the WritingMode
+ // is horizontal, then the direction of the horizontality dictates the choice. If the WritingMode
+ // is vertical, then we use TextDirection to choose between those options.
+ if (writingMode == TopToBottomWritingMode || (!isHorizontalWritingMode && textDirection == RTL))
+ return Pagination::TopToBottomPaginated;
+ return Pagination::BottomToTopPaginated;
+}
+
+FrameView::DeferredRepaintScope::DeferredRepaintScope(FrameView& view)
+ : m_view(&view)
+{
+ m_view->beginDeferredRepaints();
+}
+
+FrameView::DeferredRepaintScope::~DeferredRepaintScope()
+{
+ m_view->endDeferredRepaints();
+}
+
+FrameView::FrameView(Frame* frame)
+ : m_frame(frame)
+ , m_canHaveScrollbars(true)
+ , m_slowRepaintObjectCount(0)
+ , m_layoutTimer(this, &FrameView::layoutTimerFired)
+ , m_layoutRoot(0)
+ , m_inSynchronousPostLayout(false)
+ , m_postLayoutTasksTimer(this, &FrameView::postLayoutTimerFired)
+ , m_updateWidgetsTimer(this, &FrameView::updateWidgetsTimerFired)
+ , m_isTransparent(false)
+ , m_baseBackgroundColor(Color::white)
+ , m_mediaType("screen")
+ , m_overflowStatusDirty(true)
+ , m_viewportRenderer(0)
+ , m_wasScrolledByUser(false)
+ , m_inProgrammaticScroll(false)
+ , m_safeToPropagateScrollToParent(true)
+ , m_deferredRepaintTimer(this, &FrameView::deferredRepaintTimerFired)
+ , m_isTrackingRepaints(false)
+ , m_shouldUpdateWhileOffscreen(true)
+ , m_scrollCorner(0)
+ , m_shouldAutoSize(false)
+ , m_inAutoSize(false)
+ , m_didRunAutosize(false)
+ , m_hasSoftwareFilters(false)
+ , m_visibleContentScaleFactor(1)
+ , m_inputEventsScaleFactorForEmulation(1)
+ , m_partialLayout()
+ , m_layoutSizeFixedToFrameSize(true)
+{
+ ASSERT(m_frame);
+ init();
+
+ if (!isMainFrame())
+ return;
+
+ ScrollableArea::setVerticalScrollElasticity(ScrollElasticityAllowed);
+ ScrollableArea::setHorizontalScrollElasticity(ScrollElasticityAllowed);
+}
+
+PassRefPtr<FrameView> FrameView::create(Frame* frame)
+{
+ RefPtr<FrameView> view = adoptRef(new FrameView(frame));
+ view->show();
+ return view.release();
+}
+
+PassRefPtr<FrameView> FrameView::create(Frame* frame, const IntSize& initialSize)
+{
+ RefPtr<FrameView> view = adoptRef(new FrameView(frame));
+ view->Widget::setFrameRect(IntRect(view->location(), initialSize));
+ view->setLayoutSizeInternal(initialSize);
+
+ view->show();
+ return view.release();
+}
+
+FrameView::~FrameView()
+{
+ if (m_postLayoutTasksTimer.isActive())
+ m_postLayoutTasksTimer.stop();
+
+ removeFromAXObjectCache();
+ resetScrollbars();
+
+ // Custom scrollbars should already be destroyed at this point
+ ASSERT(!horizontalScrollbar() || !horizontalScrollbar()->isCustomScrollbar());
+ ASSERT(!verticalScrollbar() || !verticalScrollbar()->isCustomScrollbar());
+
+ setHasHorizontalScrollbar(false); // Remove native scrollbars now before we lose the connection to the HostWindow.
+ setHasVerticalScrollbar(false);
+
+ ASSERT(!m_scrollCorner);
+
+ ASSERT(m_frame);
+ ASSERT(m_frame->view() != this || !m_frame->contentRenderer());
+ RenderPart* renderer = m_frame->ownerRenderer();
+ if (renderer && renderer->widget() == this)
+ renderer->setWidget(0);
+}
+
+void FrameView::reset()
+{
+ m_cannotBlitToWindow = false;
+ m_isOverlapped = false;
+ m_contentIsOpaque = false;
+ m_borderX = 30;
+ m_borderY = 30;
+ m_layoutTimer.stop();
+ m_layoutRoot = 0;
+ m_delayedLayout = false;
+ m_doFullRepaint = true;
+ m_layoutSchedulingEnabled = true;
+ m_inLayout = false;
+ m_doingPreLayoutStyleUpdate = false;
+ m_inSynchronousPostLayout = false;
+ m_layoutCount = 0;
+ m_nestedLayoutCount = 0;
+ m_postLayoutTasksTimer.stop();
+ m_updateWidgetsTimer.stop();
+ m_firstLayout = true;
+ m_firstLayoutCallbackPending = false;
+ m_wasScrolledByUser = false;
+ m_safeToPropagateScrollToParent = true;
+ m_lastViewportSize = IntSize();
+ m_lastZoomFactor = 1.0f;
+ m_deferringRepaints = 0;
+ m_repaintCount = 0;
+ m_repaintRects.clear();
+ m_deferredRepaintDelay = s_initialDeferredRepaintDelayDuringLoading;
+ m_deferredRepaintTimer.stop();
+ m_isTrackingRepaints = false;
+ m_trackedRepaintRects.clear();
+ m_lastPaintTime = 0;
+ m_paintBehavior = PaintBehaviorNormal;
+ m_isPainting = false;
+ m_visuallyNonEmptyCharacterCount = 0;
+ m_visuallyNonEmptyPixelCount = 0;
+ m_isVisuallyNonEmpty = false;
+ m_firstVisuallyNonEmptyLayoutCallbackPending = true;
+ m_maintainScrollPositionAnchor = 0;
+ m_partialLayout.reset();
+ m_viewportConstrainedObjects.clear();
+}
+
+void FrameView::removeFromAXObjectCache()
+{
+ if (AXObjectCache* cache = axObjectCache())
+ cache->remove(this);
+}
+
+void FrameView::resetScrollbars()
+{
+ // Reset the document's scrollbars back to our defaults before we yield the floor.
+ m_firstLayout = true;
+ setScrollbarsSuppressed(true);
+ if (m_canHaveScrollbars)
+ setScrollbarModes(ScrollbarAuto, ScrollbarAuto);
+ else
+ setScrollbarModes(ScrollbarAlwaysOff, ScrollbarAlwaysOff);
+ setScrollbarsSuppressed(false);
+}
+
+void FrameView::init()
+{
+ reset();
+
+ m_margins = LayoutSize(-1, -1); // undefined
+ m_size = LayoutSize();
+
+ // Propagate the marginwidth/height and scrolling modes to the view.
+ Element* ownerElement = m_frame->ownerElement();
+ if (ownerElement && (ownerElement->hasTagName(frameTag) || ownerElement->hasTagName(iframeTag))) {
+ HTMLFrameElementBase* frameElt = toHTMLFrameElementBase(ownerElement);
+ if (frameElt->scrollingMode() == ScrollbarAlwaysOff)
+ setCanHaveScrollbars(false);
+ LayoutUnit marginWidth = frameElt->marginWidth();
+ LayoutUnit marginHeight = frameElt->marginHeight();
+ if (marginWidth != -1)
+ setMarginWidth(marginWidth);
+ if (marginHeight != -1)
+ setMarginHeight(marginHeight);
+ }
+}
+
+void FrameView::prepareForDetach()
+{
+ RELEASE_ASSERT(!isInLayout());
+
+ if (ScrollAnimator* scrollAnimator = existingScrollAnimator())
+ scrollAnimator->cancelAnimations();
+
+ detachCustomScrollbars();
+ // When the view is no longer associated with a frame, it needs to be removed from the ax object cache
+ // right now, otherwise it won't be able to reach the topDocument()'s axObject cache later.
+ removeFromAXObjectCache();
+
+ if (m_frame->page()) {
+ if (ScrollingCoordinator* scrollingCoordinator = m_frame->page()->scrollingCoordinator())
+ scrollingCoordinator->willDestroyScrollableArea(this);
+ }
+}
+
+void FrameView::detachCustomScrollbars()
+{
+ Scrollbar* horizontalBar = horizontalScrollbar();
+ if (horizontalBar && horizontalBar->isCustomScrollbar())
+ setHasHorizontalScrollbar(false);
+
+ Scrollbar* verticalBar = verticalScrollbar();
+ if (verticalBar && verticalBar->isCustomScrollbar())
+ setHasVerticalScrollbar(false);
+
+ if (m_scrollCorner) {
+ m_scrollCorner->destroy();
+ m_scrollCorner = 0;
+ }
+}
+
+void FrameView::recalculateScrollbarOverlayStyle()
+{
+ ScrollbarOverlayStyle oldOverlayStyle = scrollbarOverlayStyle();
+ ScrollbarOverlayStyle overlayStyle = ScrollbarOverlayStyleDefault;
+
+ Color backgroundColor = documentBackgroundColor();
+ if (backgroundColor.isValid()) {
+ // Reduce the background color from RGB to a lightness value
+ // and determine which scrollbar style to use based on a lightness
+ // heuristic.
+ double hue, saturation, lightness;
+ backgroundColor.getHSL(hue, saturation, lightness);
+ if (lightness <= .5)
+ overlayStyle = ScrollbarOverlayStyleLight;
+ }
+
+ if (oldOverlayStyle != overlayStyle)
+ setScrollbarOverlayStyle(overlayStyle);
+}
+
+void FrameView::clear()
+{
+ setCanBlitOnScroll(true);
+
+ reset();
+
+ if (RenderPart* renderer = m_frame->ownerRenderer())
+ renderer->viewCleared();
+
+ setScrollbarsSuppressed(true);
+}
+
+bool FrameView::didFirstLayout() const
+{
+ return !m_firstLayout;
+}
+
+void FrameView::invalidateRect(const IntRect& rect)
+{
+ if (!parent()) {
+ if (HostWindow* window = hostWindow())
+ window->invalidateContentsAndRootView(rect);
+ return;
+ }
+
+ RenderPart* renderer = m_frame->ownerRenderer();
+ if (!renderer)
+ return;
+
+ IntRect repaintRect = rect;
+ repaintRect.move(renderer->borderLeft() + renderer->paddingLeft(),
+ renderer->borderTop() + renderer->paddingTop());
+ renderer->repaintRectangle(repaintRect);
+}
+
+void FrameView::setFrameRect(const IntRect& newRect)
+{
+ IntRect oldRect = frameRect();
+ if (newRect == oldRect)
+ return;
+
+ // Autosized font sizes depend on the width of the viewing area.
+ if (newRect.width() != oldRect.width()) {
+ Page* page = m_frame->page();
+ if (isMainFrame() && page->settings().textAutosizingEnabled()) {
+ TextAutosizer* textAutosizer = m_frame->document()->textAutosizer();
+ if (textAutosizer) {
+ for (Frame* frame = page->mainFrame(); frame; frame = frame->tree().traverseNext())
+ textAutosizer->recalculateMultipliers();
+ }
+ }
+ }
+
+ ScrollView::setFrameRect(newRect);
+
+ updateScrollableAreaSet();
+
+ if (RenderView* renderView = this->renderView()) {
+ if (renderView->usesCompositing())
+ renderView->compositor()->frameViewDidChangeSize();
+ }
+}
+
+bool FrameView::scheduleAnimation()
+{
+ if (HostWindow* window = hostWindow()) {
+ window->scheduleAnimation();
+ return true;
+ }
+ return false;
+}
+
+RenderView* FrameView::renderView() const
+{
+ return frame().contentRenderer();
+}
+
+void FrameView::setMarginWidth(LayoutUnit w)
+{
+ // make it update the rendering area when set
+ m_margins.setWidth(w);
+}
+
+void FrameView::setMarginHeight(LayoutUnit h)
+{
+ // make it update the rendering area when set
+ m_margins.setHeight(h);
+}
+
+void FrameView::setCanHaveScrollbars(bool canHaveScrollbars)
+{
+ m_canHaveScrollbars = canHaveScrollbars;
+ ScrollView::setCanHaveScrollbars(canHaveScrollbars);
+}
+
+void FrameView::updateCanHaveScrollbars()
+{
+ ScrollbarMode hMode;
+ ScrollbarMode vMode;
+ scrollbarModes(hMode, vMode);
+ if (hMode == ScrollbarAlwaysOff && vMode == ScrollbarAlwaysOff)
+ setCanHaveScrollbars(false);
+ else
+ setCanHaveScrollbars(true);
+}
+
+bool FrameView::shouldUseCustomScrollbars(Element*& customScrollbarElement, Frame*& customScrollbarFrame)
+{
+ customScrollbarElement = 0;
+ customScrollbarFrame = 0;
+
+ if (Settings* settings = m_frame->settings()) {
+ if (!settings->allowCustomScrollbarInMainFrame() && isMainFrame())
+ return false;
+ }
+
+ // FIXME: We need to update the scrollbar dynamically as documents change (or as doc elements and bodies get discovered that have custom styles).
+ Document* doc = m_frame->document();
+
+ // Try the <body> element first as a scrollbar source.
+ Element* body = doc ? doc->body() : 0;
+ if (body && body->renderer() && body->renderer()->style()->hasPseudoStyle(SCROLLBAR)) {
+ customScrollbarElement = body;
+ return true;
+ }
+
+ // If the <body> didn't have a custom style, then the root element might.
+ Element* docElement = doc ? doc->documentElement() : 0;
+ if (docElement && docElement->renderer() && docElement->renderer()->style()->hasPseudoStyle(SCROLLBAR)) {
+ customScrollbarElement = docElement;
+ return true;
+ }
+
+ // If we have an owning ipage/Frame element, then it can set the custom scrollbar also.
+ RenderPart* frameRenderer = m_frame->ownerRenderer();
+ if (frameRenderer && frameRenderer->style()->hasPseudoStyle(SCROLLBAR)) {
+ customScrollbarFrame = m_frame.get();
+ return true;
+ }
+
+ return false;
+}
+
+PassRefPtr<Scrollbar> FrameView::createScrollbar(ScrollbarOrientation orientation)
+{
+ Element* customScrollbarElement = 0;
+ Frame* customScrollbarFrame = 0;
+ if (shouldUseCustomScrollbars(customScrollbarElement, customScrollbarFrame))
+ return RenderScrollbar::createCustomScrollbar(this, orientation, customScrollbarElement, customScrollbarFrame);
+
+ // Nobody set a custom style, so we just use a native scrollbar.
+ return ScrollView::createScrollbar(orientation);
+}
+
+void FrameView::setContentsSize(const IntSize& size)
+{
+ if (size == contentsSize())
+ return;
+
+ ScrollView::setContentsSize(size);
+ ScrollView::contentsResized();
+
+ Page* page = frame().page();
+ if (!page)
+ return;
+
+ updateScrollableAreaSet();
+
+ page->chrome().contentsSizeChanged(m_frame.get(), size);
+}
+
+void FrameView::adjustViewSize()
+{
+ RenderView* renderView = this->renderView();
+ if (!renderView)
+ return;
+
+ ASSERT(m_frame->view() == this);
+
+ const IntRect rect = renderView->documentRect();
+ const IntSize& size = rect.size();
+ ScrollView::setScrollOrigin(IntPoint(-rect.x(), -rect.y()), !m_frame->document()->printing(), size == contentsSize());
+
+ setContentsSize(size);
+}
+
+void FrameView::applyOverflowToViewport(RenderObject* o, ScrollbarMode& hMode, ScrollbarMode& vMode)
+{
+ // Handle the overflow:hidden/scroll case for the body/html elements. WinIE treats
+ // overflow:hidden and overflow:scroll on <body> as applying to the document's
+ // scrollbars. The CSS2.1 draft states that HTML UAs should use the <html> or <body> element and XML/XHTML UAs should
+ // use the root element.
+
+ EOverflow overflowX = o->style()->overflowX();
+ EOverflow overflowY = o->style()->overflowY();
+
+ if (o->isSVGRoot()) {
+ // overflow is ignored in stand-alone SVG documents.
+ if (!toRenderSVGRoot(o)->isEmbeddedThroughFrameContainingSVGDocument())
+ return;
+ overflowX = OHIDDEN;
+ overflowY = OHIDDEN;
+ }
+
+ bool ignoreOverflowHidden = false;
+ if (m_frame->settings()->ignoreMainFrameOverflowHiddenQuirk() && m_frame->isMainFrame())
+ ignoreOverflowHidden = true;
+
+ switch (overflowX) {
+ case OHIDDEN:
+ if (!ignoreOverflowHidden)
+ hMode = ScrollbarAlwaysOff;
+ break;
+ case OSCROLL:
+ hMode = ScrollbarAlwaysOn;
+ break;
+ case OAUTO:
+ hMode = ScrollbarAuto;
+ break;
+ default:
+ // Don't set it at all.
+ ;
+ }
+
+ switch (overflowY) {
+ case OHIDDEN:
+ if (!ignoreOverflowHidden)
+ vMode = ScrollbarAlwaysOff;
+ break;
+ case OSCROLL:
+ vMode = ScrollbarAlwaysOn;
+ break;
+ case OAUTO:
+ vMode = ScrollbarAuto;
+ break;
+ default:
+ // Don't set it at all. Values of OPAGEDX and OPAGEDY are handled by applyPaginationToViewPort().
+ ;
+ }
+
+ m_viewportRenderer = o;
+}
+
+void FrameView::applyPaginationToViewport()
+{
+ Document* document = m_frame->document();
+ Node* documentElement = document->documentElement();
+ RenderObject* documentRenderer = documentElement ? documentElement->renderer() : 0;
+ RenderObject* documentOrBodyRenderer = documentRenderer;
+ Node* body = document->body();
+ if (body && body->renderer()) {
+ if (body->hasTagName(bodyTag))
+ documentOrBodyRenderer = documentRenderer->style()->overflowX() == OVISIBLE && isHTMLHtmlElement(documentElement) ? body->renderer() : documentRenderer;
+ }
+
+ Pagination pagination;
+
+ if (!documentOrBodyRenderer) {
+ setPagination(pagination);
+ return;
+ }
+
+ EOverflow overflowY = documentOrBodyRenderer->style()->overflowY();
+ if (overflowY == OPAGEDX || overflowY == OPAGEDY) {
+ pagination.mode = WebCore::paginationModeForRenderStyle(documentOrBodyRenderer->style());
+ pagination.gap = static_cast<unsigned>(documentOrBodyRenderer->style()->columnGap());
+ }
+
+ setPagination(pagination);
+}
+
+void FrameView::calculateScrollbarModesForLayout(ScrollbarMode& hMode, ScrollbarMode& vMode, ScrollbarModesCalculationStrategy strategy)
+{
+ m_viewportRenderer = 0;
+
+ const HTMLFrameOwnerElement* owner = m_frame->ownerElement();
+ if (owner && (owner->scrollingMode() == ScrollbarAlwaysOff)) {
+ hMode = ScrollbarAlwaysOff;
+ vMode = ScrollbarAlwaysOff;
+ return;
+ }
+
+ if (m_canHaveScrollbars || strategy == RulesFromWebContentOnly) {
+ hMode = ScrollbarAuto;
+ // Seamless documents begin with heights of 0; we special case that here
+ // to correctly render documents that don't need scrollbars.
+ IntSize fullVisibleSize = visibleContentRect(IncludeScrollbars).size();
+ bool isSeamlessDocument = frame().document() && frame().document()->shouldDisplaySeamlesslyWithParent();
+ vMode = (isSeamlessDocument && !fullVisibleSize.height()) ? ScrollbarAlwaysOff : ScrollbarAuto;
+ } else {
+ hMode = ScrollbarAlwaysOff;
+ vMode = ScrollbarAlwaysOff;
+ }
+
+ if (!m_layoutRoot) {
+ Document* document = m_frame->document();
+ Node* documentElement = document->documentElement();
+ RenderObject* rootRenderer = documentElement ? documentElement->renderer() : 0;
+ Node* body = document->body();
+ if (body && body->renderer()) {
+ if (body->hasTagName(framesetTag)) {
+ vMode = ScrollbarAlwaysOff;
+ hMode = ScrollbarAlwaysOff;
+ } else if (body->hasTagName(bodyTag)) {
+ // It's sufficient to just check the X overflow,
+ // since it's illegal to have visible in only one direction.
+ RenderObject* o = rootRenderer->style()->overflowX() == OVISIBLE && isHTMLHtmlElement(document->documentElement()) ? body->renderer() : rootRenderer;
+ if (o->style())
+ applyOverflowToViewport(o, hMode, vMode);
+ }
+ } else if (rootRenderer)
+ applyOverflowToViewport(rootRenderer, hMode, vMode);
+ }
+}
+
+void FrameView::updateCompositingLayersAfterStyleChange()
+{
+ TRACE_EVENT0("webkit", "FrameView::updateCompositingLayersAfterStyleChange");
+ RenderView* renderView = this->renderView();
+ if (!renderView)
+ return;
+
+ // If we expect to update compositing after an incipient layout, don't do so here.
+ if (m_doingPreLayoutStyleUpdate || layoutPending() || renderView->needsLayout())
+ return;
+
+ // This call will make sure the cached hasAcceleratedCompositing is updated from the pref
+ renderView->compositor()->cacheAcceleratedCompositingFlags();
+
+ // Sometimes we will change a property (for example, z-index) that will not
+ // cause a layout, but will require us to update compositing state. We only
+ // need to do this if a layout is not already scheduled.
+ if (!needsLayout())
+ renderView->compositor()->updateCompositingRequirementsState();
+
+ renderView->compositor()->updateCompositingLayers(CompositingUpdateAfterStyleChange);
+}
+
+void FrameView::updateCompositingLayersAfterLayout()
+{
+ TRACE_EVENT0("webkit", "FrameView::updateCompositingLayersAfterLayout");
+ RenderView* renderView = this->renderView();
+ if (!renderView)
+ return;
+
+ // This call will make sure the cached hasAcceleratedCompositing is updated from the pref
+ renderView->compositor()->cacheAcceleratedCompositingFlags();
+ renderView->compositor()->updateCompositingRequirementsState();
+ renderView->compositor()->updateCompositingLayers(CompositingUpdateAfterLayout);
+}
+
+bool FrameView::usesCompositedScrolling() const
+{
+ RenderView* renderView = this->renderView();
+ if (!renderView)
+ return false;
+ if (m_frame->settings() && m_frame->settings()->compositedScrollingForFramesEnabled())
+ return renderView->compositor()->inForcedCompositingMode();
+ return false;
+}
+
+GraphicsLayer* FrameView::layerForScrolling() const
+{
+ RenderView* renderView = this->renderView();
+ if (!renderView)
+ return 0;
+ return renderView->compositor()->scrollLayer();
+}
+
+GraphicsLayer* FrameView::layerForHorizontalScrollbar() const
+{
+ RenderView* renderView = this->renderView();
+ if (!renderView)
+ return 0;
+ return renderView->compositor()->layerForHorizontalScrollbar();
+}
+
+GraphicsLayer* FrameView::layerForVerticalScrollbar() const
+{
+ RenderView* renderView = this->renderView();
+ if (!renderView)
+ return 0;
+ return renderView->compositor()->layerForVerticalScrollbar();
+}
+
+GraphicsLayer* FrameView::layerForScrollCorner() const
+{
+ RenderView* renderView = this->renderView();
+ if (!renderView)
+ return 0;
+ return renderView->compositor()->layerForScrollCorner();
+}
+
+bool FrameView::hasCompositedContent() const
+{
+ if (RenderView* renderView = this->renderView())
+ return renderView->compositor()->inCompositingMode();
+ return false;
+}
+
+bool FrameView::isEnclosedInCompositingLayer() const
+{
+ RenderObject* frameOwnerRenderer = m_frame->ownerRenderer();
+ if (frameOwnerRenderer && frameOwnerRenderer->containerForRepaint())
+ return true;
+
+ if (FrameView* parentView = parentFrameView())
+ return parentView->isEnclosedInCompositingLayer();
+
+ return false;
+}
+
+bool FrameView::isSoftwareRenderable() const
+{
+ RenderView* renderView = this->renderView();
+ return !renderView || !renderView->compositor()->has3DContent();
+}
+
+RenderObject* FrameView::layoutRoot(bool onlyDuringLayout) const
+{
+ return onlyDuringLayout && layoutPending() ? 0 : m_layoutRoot;
+}
+
+static inline void collectFrameViewChildren(FrameView* frameView, Vector<RefPtr<FrameView> >& frameViews)
+{
+ const HashSet<RefPtr<Widget> >* viewChildren = frameView->children();
+ ASSERT(viewChildren);
+
+ const HashSet<RefPtr<Widget> >::iterator end = viewChildren->end();
+ for (HashSet<RefPtr<Widget> >::iterator current = viewChildren->begin(); current != end; ++current) {
+ Widget* widget = (*current).get();
+ if (widget->isFrameView())
+ frameViews.append(toFrameView(widget));
+ }
+}
+
+inline void FrameView::forceLayoutParentViewIfNeeded()
+{
+ RenderPart* ownerRenderer = m_frame->ownerRenderer();
+ if (!ownerRenderer || !ownerRenderer->frame())
+ return;
+
+ RenderBox* contentBox = embeddedContentBox();
+ if (!contentBox)
+ return;
+
+ RenderSVGRoot* svgRoot = toRenderSVGRoot(contentBox);
+ if (svgRoot->everHadLayout() && !svgRoot->needsLayout())
+ return;
+
+ // If the embedded SVG document appears the first time, the ownerRenderer has already finished
+ // layout without knowing about the existence of the embedded SVG document, because RenderReplaced
+ // embeddedContentBox() returns 0, as long as the embedded document isn't loaded yet. Before
+ // bothering to lay out the SVG document, mark the ownerRenderer needing layout and ask its
+ // FrameView for a layout. After that the RenderEmbeddedObject (ownerRenderer) carries the
+ // correct size, which RenderSVGRoot::computeReplacedLogicalWidth/Height rely on, when laying
+ // out for the first time, or when the RenderSVGRoot size has changed dynamically (eg. via <script>).
+ RefPtr<FrameView> frameView = ownerRenderer->frame()->view();
+
+ // Mark the owner renderer as needing layout.
+ ownerRenderer->setNeedsLayoutAndPrefWidthsRecalc();
+
+ // Synchronously enter layout, to layout the view containing the host object/embed/iframe.
+ ASSERT(frameView);
+ frameView->layout();
+}
+
+void FrameView::performPreLayoutTasks()
+{
+ // Don't schedule more layouts, we're in one.
+ TemporaryChange<bool> changeSchedulingEnabled(m_layoutSchedulingEnabled, false);
+
+ if (!m_nestedLayoutCount && !m_inSynchronousPostLayout && m_postLayoutTasksTimer.isActive() && !frame().document()->shouldDisplaySeamlesslyWithParent()) {
+ // This is a new top-level layout. If there are any remaining tasks from the previous layout, finish them now.
+ m_inSynchronousPostLayout = true;
+ performPostLayoutTasks();
+ m_inSynchronousPostLayout = false;
+ }
+
+ // Viewport-dependent media queries may cause us to need completely different style information.
+ Document* document = m_frame->document();
+ if (!document->styleResolver() || document->styleResolver()->affectedByViewportChange()) {
+ document->styleResolverChanged(RecalcStyleDeferred);
+ document->mediaQueryAffectingValueChanged();
+
+ // FIXME: This instrumentation event is not strictly accurate since cached media query results
+ // do not persist across StyleResolver rebuilds.
+ InspectorInstrumentation::mediaQueryResultChanged(document);
+ } else {
+ document->evaluateMediaQueryList();
+ }
+
+ // If there is any pagination to apply, it will affect the RenderView's style, so we should
+ // take care of that now.
+ applyPaginationToViewport();
+
+ // Always ensure our style info is up-to-date. This can happen in situations where
+ // the layout beats any sort of style recalc update that needs to occur.
+ TemporaryChange<bool> changeDoingPreLayoutStyleUpdate(m_doingPreLayoutStyleUpdate, true);
+ document->updateStyleIfNeeded();
+}
+
+void FrameView::performLayout(RenderObject* rootForThisLayout, bool inSubtreeLayout)
+{
+ // performLayout is the actual guts of layout().
+ // FIXME: The 300 other lines in layout() probably belong in other helper functions
+ // so that a single human could understand what layout() is actually doing.
+ FrameView::DeferredRepaintScope deferRepaints(*this);
+
+ {
+ bool disableLayoutState = false;
+ if (inSubtreeLayout) {
+ RenderView* view = rootForThisLayout->view();
+ disableLayoutState = view->shouldDisableLayoutStateForSubtree(rootForThisLayout);
+ view->pushLayoutState(rootForThisLayout);
+ }
+ LayoutStateDisabler layoutStateDisabler(disableLayoutState ? rootForThisLayout->view() : 0);
+
+ m_inLayout = true;
+
+ forceLayoutParentViewIfNeeded();
+
+ // Text Autosizing requires two-pass layout which is incompatible with partial layout.
+ // If enabled, only do partial layout for the second layout.
+ // FIXME (crbug.com/256657): Do not do two layouts for text autosizing.
+ PartialLayoutDisabler partialLayoutDisabler(partialLayout(), m_frame->settings() && m_frame->settings()->textAutosizingEnabled());
+
+ LayoutIndicator layoutIndicator;
+ rootForThisLayout->layout();
+ gatherDebugLayoutRects(rootForThisLayout);
+
+ ResourceLoadPriorityOptimizer modifier;
+ rootForThisLayout->didLayout(modifier);
+ }
+
+ TextAutosizer* textAutosizer = frame().document()->textAutosizer();
+ bool autosized = textAutosizer && textAutosizer->processSubtree(rootForThisLayout);
+ if (autosized && rootForThisLayout->needsLayout()) {
+ TRACE_EVENT0("webkit", "2nd layout due to Text Autosizing");
+ LayoutIndicator layoutIndicator;
+ rootForThisLayout->layout();
+ gatherDebugLayoutRects(rootForThisLayout);
+
+ ResourceLoadPriorityOptimizer modifier;
+ rootForThisLayout->didLayout(modifier);
+ }
+
+ m_inLayout = false;
+
+ if (inSubtreeLayout)
+ rootForThisLayout->view()->popLayoutState(rootForThisLayout);
+}
+
+void FrameView::scheduleOrPerformPostLayoutTasks()
+{
+ if (m_postLayoutTasksTimer.isActive())
+ return;
+
+ // Partial layouts should not happen with synchronous post layouts.
+ ASSERT(!(m_inSynchronousPostLayout && partialLayout().isStopping()));
+
+ if (!m_inSynchronousPostLayout) {
+ if (frame().document()->shouldDisplaySeamlesslyWithParent()) {
+ if (RenderView* renderView = this->renderView())
+ renderView->updateWidgetPositions();
+ } else {
+ m_inSynchronousPostLayout = true;
+ // Calls resumeScheduledEvents()
+ performPostLayoutTasks();
+ m_inSynchronousPostLayout = false;
+ }
+ }
+
+ if (!m_postLayoutTasksTimer.isActive() && (needsLayout() || m_inSynchronousPostLayout || frame().document()->shouldDisplaySeamlesslyWithParent())) {
+ // If we need layout or are already in a synchronous call to postLayoutTasks(),
+ // defer widget updates and event dispatch until after we return. postLayoutTasks()
+ // can make us need to update again, and we can get stuck in a nasty cycle unless
+ // we call it through the timer here.
+ m_postLayoutTasksTimer.startOneShot(0);
+ if (!partialLayout().isStopping() && needsLayout())
+ layout();
+ }
+}
+
+void FrameView::layout(bool allowSubtree)
+{
+ // We should never layout a Document which is not in a Frame.
+ ASSERT(m_frame);
+ ASSERT(m_frame->view() == this);
+ ASSERT(m_frame->page());
+
+ if (m_inLayout)
+ return;
+
+ if (!m_frame->document()->isActive())
+ return;
+
+ ASSERT(!partialLayout().isStopping());
+
+ TRACE_EVENT0("webkit", "FrameView::layout");
+ TRACE_EVENT_SCOPED_SAMPLING_STATE("Blink", "Layout");
+
+ // Protect the view from being deleted during layout (in recalcStyle)
+ RefPtr<FrameView> protector(this);
+
+ // Every scroll that happens during layout is programmatic.
+ TemporaryChange<bool> changeInProgrammaticScroll(m_inProgrammaticScroll, true);
+
+ m_layoutTimer.stop();
+ m_delayedLayout = false;
+
+ // we shouldn't enter layout() while painting
+ ASSERT(!isPainting());
+ if (isPainting())
+ return;
+
+ // Store the current maximal outline size to use when computing the old/new
+ // outline rects for repainting.
+ renderView()->setOldMaximalOutlineSize(renderView()->maximalOutlineSize());
+
+ InspectorInstrumentationCookie cookie = InspectorInstrumentation::willLayout(m_frame.get());
+
+ if (!allowSubtree && m_layoutRoot) {
+ m_layoutRoot->markContainingBlocksForLayout(false);
+ m_layoutRoot = 0;
+ }
+
+ performPreLayoutTasks();
+
+ // If there is only one ref to this view left, then its going to be destroyed as soon as we exit,
+ // so there's no point to continuing to layout
+ if (protector->hasOneRef())
+ return;
+
+ Document* document = m_frame->document();
+ bool inSubtreeLayout = m_layoutRoot;
+ RenderObject* rootForThisLayout = inSubtreeLayout ? m_layoutRoot : document->renderer();
+ if (!rootForThisLayout) {
+ // FIXME: Do we need to set m_size here?
+ ASSERT_NOT_REACHED();
+ return;
+ }
+
+ bool isPartialLayout = partialLayout().isPartialLayout();
+
+ FontCachePurgePreventer fontCachePurgePreventer;
+ RenderLayer* layer;
+ {
+ TemporaryChange<bool> changeSchedulingEnabled(m_layoutSchedulingEnabled, false);
+
+ m_nestedLayoutCount++;
+ if (!m_layoutRoot) {
+ Document* document = m_frame->document();
+ Node* body = document->body();
+ if (body && body->renderer()) {
+ if (body->hasTagName(framesetTag)) {
+ body->renderer()->setChildNeedsLayout();
+ } else if (body->hasTagName(bodyTag)) {
+ if (!m_firstLayout && m_size.height() != layoutSize().height() && body->renderer()->enclosingBox()->stretchesToViewport())
+ body->renderer()->setChildNeedsLayout();
+ }
+ }
+ }
+ updateCounters();
+ autoSizeIfEnabled();
+
+ ScrollbarMode hMode;
+ ScrollbarMode vMode;
+ calculateScrollbarModesForLayout(hMode, vMode);
+
+ m_doFullRepaint = !inSubtreeLayout && !isPartialLayout && (m_firstLayout || toRenderView(rootForThisLayout)->document().printing());
+
+ if (!inSubtreeLayout && !isPartialLayout) {
+ // Now set our scrollbar state for the layout.
+ ScrollbarMode currentHMode = horizontalScrollbarMode();
+ ScrollbarMode currentVMode = verticalScrollbarMode();
+
+ if (m_firstLayout || (hMode != currentHMode || vMode != currentVMode)) {
+ if (m_firstLayout) {
+ setScrollbarsSuppressed(true);
+
+ m_firstLayout = false;
+ m_firstLayoutCallbackPending = true;
+ m_lastViewportSize = layoutSize(IncludeScrollbars);
+ m_lastZoomFactor = rootForThisLayout->style()->zoom();
+
+ // Set the initial vMode to AlwaysOn if we're auto.
+ if (vMode == ScrollbarAuto)
+ setVerticalScrollbarMode(ScrollbarAlwaysOn); // This causes a vertical scrollbar to appear.
+ // Set the initial hMode to AlwaysOff if we're auto.
+ if (hMode == ScrollbarAuto)
+ setHorizontalScrollbarMode(ScrollbarAlwaysOff); // This causes a horizontal scrollbar to disappear.
+
+ setScrollbarModes(hMode, vMode);
+ setScrollbarsSuppressed(false, true);
+ } else
+ setScrollbarModes(hMode, vMode);
+ }
+
+ LayoutSize oldSize = m_size;
+
+ m_size = LayoutSize(layoutSize().width(), layoutSize().height());
+
+ if (oldSize != m_size) {
+ m_doFullRepaint = true;
+ if (!m_firstLayout) {
+ RenderBox* rootRenderer = document->documentElement() ? document->documentElement()->renderBox() : 0;
+ RenderBox* bodyRenderer = rootRenderer && document->body() ? document->body()->renderBox() : 0;
+ if (bodyRenderer && bodyRenderer->stretchesToViewport())
+ bodyRenderer->setChildNeedsLayout();
+ else if (rootRenderer && rootRenderer->stretchesToViewport())
+ rootRenderer->setChildNeedsLayout();
+ }
+ }
+ }
+
+ layer = rootForThisLayout->enclosingLayer();
+
+ performLayout(rootForThisLayout, inSubtreeLayout);
+
+ m_layoutRoot = 0;
+ } // Reset m_layoutSchedulingEnabled to its previous value.
+
+ bool neededFullRepaint = m_doFullRepaint;
+
+ if (!inSubtreeLayout && !isPartialLayout && !toRenderView(rootForThisLayout)->document().printing())
+ adjustViewSize();
+
+ m_doFullRepaint = neededFullRepaint;
+
+ {
+ // FIXME: Can this scope just encompass this entire function?
+ FrameView::DeferredRepaintScope deferRepaints(*this);
+
+ if (RuntimeEnabledFeatures::repaintAfterLayoutEnabled()) {
+ if (m_doFullRepaint)
+ renderView()->setShouldDoFullRepaintAfterLayout(true);
+
+ if (m_doFullRepaint || !partialLayout().isStopping())
+ repaintTree(rootForThisLayout);
+
+ } else if (m_doFullRepaint) {
+ // FIXME: This isn't really right, since the RenderView doesn't fully encompass
+ // the visibleContentRect(). It just happens to work out most of the time,
+ // since first layouts and printing don't have you scrolled anywhere.
+ renderView()->repaint();
+ }
+ layer->updateLayerPositionsAfterLayout(renderView()->layer(), updateLayerPositionFlags(layer, inSubtreeLayout, m_doFullRepaint));
+ }
+ updateCompositingLayersAfterLayout();
+
+ m_layoutCount++;
+
+ if (AXObjectCache* cache = rootForThisLayout->document().existingAXObjectCache())
+ cache->postNotification(rootForThisLayout, AXObjectCache::AXLayoutComplete, true);
+ updateAnnotatedRegions();
+
+ ASSERT(partialLayout().isStopping() || !rootForThisLayout->needsLayout());
+
+ updateCanBlitOnScrollRecursively();
+
+ if (document->hasListenerType(Document::OVERFLOWCHANGED_LISTENER))
+ updateOverflowStatus(layoutSize().width() < contentsWidth(), layoutSize().height() < contentsHeight());
+
+ scheduleOrPerformPostLayoutTasks();
+
+ InspectorInstrumentation::didLayout(cookie, rootForThisLayout);
+
+ m_nestedLayoutCount--;
+ if (m_nestedLayoutCount)
+ return;
+
+ if (partialLayout().isStopping())
+ return;
+
+#ifndef NDEBUG
+ // Post-layout assert that nobody was re-marked as needing layout during layout.
+ document->renderer()->assertSubtreeIsLaidOut();
+#endif
+
+ // FIXME: It should be not possible to remove the FrameView from the frame/page during layout
+ // however m_inLayout is not set for most of this function, so none of our RELEASE_ASSERTS
+ // in Frame/Page will fire. One of the post-layout tasks is disconnecting the Frame from
+ // the page in fast/frames/crash-remove-iframe-during-object-beforeload-2.html
+ // necessitating this check here.
+ // ASSERT(frame()->page());
+ if (frame().page())
+ frame().page()->chrome().client().layoutUpdated(m_frame.get());
+}
+
+// The plan is to move to compositor-queried repainting, in which case this
+// method would setNeedsRedraw on the GraphicsLayers with invalidations and
+// let the compositor pick which to actually draw.
+// See http://crbug.com/306706
+void FrameView::repaintTree(RenderObject* root)
+{
+ ASSERT(RuntimeEnabledFeatures::repaintAfterLayoutEnabled());
+ ASSERT(!root->needsLayout());
+
+ for (RenderObject* renderer = root; renderer; renderer = renderer->nextInPreOrder()) {
+ const LayoutRect& oldRepaintRect = renderer->oldRepaintRect();
+ const LayoutRect& newRepaintRect = renderer->newRepaintRect();
+
+ LayoutRect oldOutlineRect = oldRepaintRect;
+ oldOutlineRect.inflate(renderView()->oldMaximalOutlineSize());
+
+ LayoutRect newOutlineRect = newRepaintRect;
+ newOutlineRect.inflate(renderView()->maximalOutlineSize());
+
+ // FIXME: Currently renderers with layers will get repainted when we call updateLayerPositionsAfterLayout.
+ // That call should be broken apart to position the layers be done before
+ // the repaintTree call so this will repaint everything.
+ bool didFullRepaint = false;
+ if (!renderer->hasLayer()) {
+ if (!renderer->layoutDidGetCalled()) {
+ if (renderer->shouldDoFullRepaintAfterLayout()) {
+ renderer->repaint();
+ didFullRepaint = true;
+ }
+
+ } else {
+ didFullRepaint = renderer->repaintAfterLayoutIfNeeded(renderer->containerForRepaint(), renderer->shouldDoFullRepaintAfterLayout(),
+ oldRepaintRect, oldOutlineRect, &newRepaintRect, &newOutlineRect);
+ }
+ }
+ if (!didFullRepaint && renderer->shouldRepaintOverflowIfNeeded())
+ renderer->repaintOverflow();
+ renderer->clearRepaintRects();
+ }
+ renderView()->setOldMaximalOutlineSize(0);
+}
+
+void FrameView::gatherDebugLayoutRects(RenderObject* layoutRoot)
+{
+ bool isTracing;
+ TRACE_EVENT_CATEGORY_GROUP_ENABLED(TRACE_DISABLED_BY_DEFAULT("blink.debug.layout"), &isTracing);
+ if (!isTracing)
+ return;
+ if (!layoutRoot->enclosingLayer()->hasCompositedLayerMapping())
+ return;
+ GraphicsLayer* graphicsLayer = layoutRoot->enclosingLayer()->compositedLayerMapping()->mainGraphicsLayer();
+ if (!graphicsLayer)
+ return;
+
+ GraphicsLayerDebugInfo* debugInfo = new GraphicsLayerDebugInfo();
+ for (RenderObject* renderer = layoutRoot; renderer; renderer = renderer->nextInPreOrder()) {
+ if (renderer->layoutDidGetCalled()) {
+ LayoutRect rect = renderer->newRepaintRect();
+ debugInfo->m_currentLayoutRects.append(rect);
+ renderer->setLayoutDidGetCalled(false);
+ }
+ }
+
+ graphicsLayer->setDebugInfo(debugInfo);
+}
+
+
+RenderBox* FrameView::embeddedContentBox() const
+{
+ RenderView* renderView = this->renderView();
+ if (!renderView)
+ return 0;
+
+ RenderObject* firstChild = renderView->firstChild();
+ if (!firstChild || !firstChild->isBox())
+ return 0;
+
+ // Curently only embedded SVG documents participate in the size-negotiation logic.
+ if (firstChild->isSVGRoot())
+ return toRenderBox(firstChild);
+
+ return 0;
+}
+
+void FrameView::addWidgetToUpdate(RenderEmbeddedObject& object)
+{
+ // Tell the DOM element that it needs a widget update.
+ Node* node = object.node();
+ if (node->hasTagName(objectTag) || node->hasTagName(embedTag))
+ toHTMLPlugInElement(node)->setNeedsWidgetUpdate(true);
+
+ m_widgetUpdateSet.add(&object);
+}
+
+void FrameView::setMediaType(const AtomicString& mediaType)
+{
+ ASSERT(m_frame->document());
+ m_frame->document()->mediaQueryAffectingValueChanged();
+ m_mediaType = mediaType;
+}
+
+AtomicString FrameView::mediaType() const
+{
+ // See if we have an override type.
+ String overrideType;
+ InspectorInstrumentation::applyEmulatedMedia(m_frame.get(), &overrideType);
+ if (!overrideType.isNull())
+ return overrideType;
+ return m_mediaType;
+}
+
+void FrameView::adjustMediaTypeForPrinting(bool printing)
+{
+ if (printing) {
+ if (m_mediaTypeWhenNotPrinting.isNull())
+ m_mediaTypeWhenNotPrinting = mediaType();
+ setMediaType("print");
+ } else {
+ if (!m_mediaTypeWhenNotPrinting.isNull())
+ setMediaType(m_mediaTypeWhenNotPrinting);
+ m_mediaTypeWhenNotPrinting = nullAtom;
+ }
+}
+
+bool FrameView::useSlowRepaints(bool considerOverlap) const
+{
+ bool mustBeSlow = m_slowRepaintObjectCount > 0;
+
+ if (contentsInCompositedLayer())
+ return mustBeSlow;
+
+ // The chromium compositor does not support scrolling a non-composited frame within a composited page through
+ // the fast scrolling path, so force slow scrolling in that case.
+ if (m_frame->ownerElement() && !hasCompositedContent() && m_frame->page() && m_frame->page()->mainFrame()->view()->hasCompositedContent())
+ return true;
+
+ bool isOverlapped = m_isOverlapped && considerOverlap;
+
+ if (mustBeSlow || m_cannotBlitToWindow || isOverlapped || !m_contentIsOpaque)
+ return true;
+
+ if (FrameView* parentView = parentFrameView())
+ return parentView->useSlowRepaints(considerOverlap);
+
+ return false;
+}
+
+bool FrameView::useSlowRepaintsIfNotOverlapped() const
+{
+ return useSlowRepaints(false);
+}
+
+void FrameView::updateCanBlitOnScrollRecursively()
+{
+ for (Frame* frame = m_frame.get(); frame; frame = frame->tree().traverseNext(m_frame.get())) {
+ if (FrameView* view = frame->view())
+ view->setCanBlitOnScroll(!view->useSlowRepaints());
+ }
+}
+
+bool FrameView::contentsInCompositedLayer() const
+{
+ RenderView* renderView = this->renderView();
+ if (renderView && renderView->compositingState() == PaintsIntoOwnBacking) {
+ GraphicsLayer* layer = renderView->layer()->compositedLayerMapping()->mainGraphicsLayer();
+ if (layer && layer->drawsContent())
+ return true;
+ }
+
+ return false;
+}
+
+void FrameView::setCannotBlitToWindow()
+{
+ m_cannotBlitToWindow = true;
+ updateCanBlitOnScrollRecursively();
+}
+
+void FrameView::addSlowRepaintObject()
+{
+ if (!m_slowRepaintObjectCount++) {
+ updateCanBlitOnScrollRecursively();
+
+ if (Page* page = m_frame->page()) {
+ if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
+ scrollingCoordinator->frameViewHasSlowRepaintObjectsDidChange(this);
+ }
+ }
+}
+
+void FrameView::removeSlowRepaintObject()
+{
+ ASSERT(m_slowRepaintObjectCount > 0);
+ m_slowRepaintObjectCount--;
+ if (!m_slowRepaintObjectCount) {
+ updateCanBlitOnScrollRecursively();
+
+ if (Page* page = m_frame->page()) {
+ if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
+ scrollingCoordinator->frameViewHasSlowRepaintObjectsDidChange(this);
+ }
+ }
+}
+
+void FrameView::addViewportConstrainedObject(RenderObject* object)
+{
+ if (!m_viewportConstrainedObjects)
+ m_viewportConstrainedObjects = adoptPtr(new ViewportConstrainedObjectSet);
+
+ if (!m_viewportConstrainedObjects->contains(object)) {
+ m_viewportConstrainedObjects->add(object);
+
+ if (Page* page = m_frame->page()) {
+ if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
+ scrollingCoordinator->frameViewFixedObjectsDidChange(this);
+ }
+ }
+}
+
+void FrameView::removeViewportConstrainedObject(RenderObject* object)
+{
+ if (m_viewportConstrainedObjects && m_viewportConstrainedObjects->contains(object)) {
+ m_viewportConstrainedObjects->remove(object);
+ if (Page* page = m_frame->page()) {
+ if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
+ scrollingCoordinator->frameViewFixedObjectsDidChange(this);
+ }
+
+ // FIXME: In addFixedObject() we only call this if there's a platform widget,
+ // why isn't the same check being made here?
+ updateCanBlitOnScrollRecursively();
+ }
+}
+
+LayoutRect FrameView::viewportConstrainedVisibleContentRect() const
+{
+ LayoutRect viewportRect = visibleContentRect();
+ // Ignore overhang. No-op when not using rubber banding.
+ viewportRect.setLocation(clampScrollPosition(scrollPosition()));
+ return viewportRect;
+}
+
+
+IntSize FrameView::scrollOffsetForFixedPosition() const
+{
+ return toIntSize(clampScrollPosition(scrollPosition()));
+}
+
+IntPoint FrameView::lastKnownMousePosition() const
+{
+ return m_frame->eventHandler().lastKnownMousePosition();
+}
+
+bool FrameView::shouldSetCursor() const
+{
+ Page* page = frame().page();
+ return page && page->visibilityState() != PageVisibilityStateHidden && page->focusController().isActive();
+}
+
+bool FrameView::scrollContentsFastPath(const IntSize& scrollDelta, const IntRect& rectToScroll, const IntRect& clipRect)
+{
+ if (!m_viewportConstrainedObjects || m_viewportConstrainedObjects->isEmpty()) {
+ hostWindow()->scroll(scrollDelta, rectToScroll, clipRect);
+ return true;
+ }
+
+ const bool isCompositedContentLayer = contentsInCompositedLayer();
+
+ // Get the rects of the fixed objects visible in the rectToScroll
+ Region regionToUpdate;
+ ViewportConstrainedObjectSet::const_iterator end = m_viewportConstrainedObjects->end();
+ for (ViewportConstrainedObjectSet::const_iterator it = m_viewportConstrainedObjects->begin(); it != end; ++it) {
+ RenderObject* renderer = *it;
+ if (!renderer->style()->hasViewportConstrainedPosition())
+ continue;
+
+ // Fixed items should always have layers.
+ ASSERT(renderer->hasLayer());
+ RenderLayer* layer = toRenderBoxModelObject(renderer)->layer();
+
+ // Layers that paint into their ancestor or into a grouped backing will still need
+ // to apply a repaint invalidation. If the layer paints into its own backing, then
+ // it does not need repainting just to scroll.
+ if (layer->compositingState() == PaintsIntoOwnBacking)
+ continue;
+
+ if (layer->viewportConstrainedNotCompositedReason() == RenderLayer::NotCompositedForBoundsOutOfView
+ || layer->viewportConstrainedNotCompositedReason() == RenderLayer::NotCompositedForNoVisibleContent) {
+ // Don't invalidate for invisible fixed layers.
+ continue;
+ }
+
+ if (layer->hasAncestorWithFilterOutsets()) {
+ // If the fixed layer has a blur/drop-shadow filter applied on at least one of its parents, we cannot
+ // scroll using the fast path, otherwise the outsets of the filter will be moved around the page.
+ return false;
+ }
+
+ IntRect updateRect = pixelSnappedIntRect(layer->repainter().repaintRectIncludingNonCompositingDescendants());
+
+ RenderLayer* enclosingCompositingLayer = layer->enclosingCompositingLayer(false);
+ if (enclosingCompositingLayer && !enclosingCompositingLayer->renderer()->isRenderView()) {
+ // If the fixed-position layer is contained by a composited layer that is not its containing block,
+ // then we have to invlidate that enclosing layer, not the RenderView.
+ updateRect.moveBy(scrollPosition());
+ IntRect previousRect = updateRect;
+ previousRect.move(scrollDelta);
+ updateRect.unite(previousRect);
+ enclosingCompositingLayer->repainter().setBackingNeedsRepaintInRect(updateRect);
+ } else {
+ // Coalesce the repaints that will be issued to the renderView.
+ updateRect = contentsToRootView(updateRect);
+ if (!isCompositedContentLayer && clipsRepaints())
+ updateRect.intersect(rectToScroll);
+ if (!updateRect.isEmpty())
+ regionToUpdate.unite(updateRect);
+ }
+ }
+
+ // 1) scroll
+ hostWindow()->scroll(scrollDelta, rectToScroll, clipRect);
+
+ // 2) update the area of fixed objects that has been invalidated
+ Vector<IntRect> subRectsToUpdate = regionToUpdate.rects();
+ size_t viewportConstrainedObjectsCount = subRectsToUpdate.size();
+ for (size_t i = 0; i < viewportConstrainedObjectsCount; ++i) {
+ IntRect updateRect = subRectsToUpdate[i];
+ IntRect scrolledRect = updateRect;
+ scrolledRect.move(scrollDelta);
+ updateRect.unite(scrolledRect);
+ if (isCompositedContentLayer) {
+ updateRect = rootViewToContents(updateRect);
+ ASSERT(renderView());
+ renderView()->layer()->repainter().setBackingNeedsRepaintInRect(updateRect);
+ continue;
+ }
+ if (clipsRepaints())
+ updateRect.intersect(rectToScroll);
+ hostWindow()->invalidateContentsAndRootView(updateRect);
+ }
+
+ return true;
+}
+
+void FrameView::scrollContentsSlowPath(const IntRect& updateRect)
+{
+ if (contentsInCompositedLayer()) {
+ IntRect updateRect = visibleContentRect();
+ ASSERT(renderView());
+ renderView()->layer()->repainter().setBackingNeedsRepaintInRect(updateRect);
+ }
+ if (RenderPart* frameRenderer = m_frame->ownerRenderer()) {
+ if (isEnclosedInCompositingLayer()) {
+ LayoutRect rect(frameRenderer->borderLeft() + frameRenderer->paddingLeft(),
+ frameRenderer->borderTop() + frameRenderer->paddingTop(),
+ visibleWidth(), visibleHeight());
+ frameRenderer->repaintRectangle(rect);
+ return;
+ }
+ }
+
+ ScrollView::scrollContentsSlowPath(updateRect);
+}
+
+// Note that this gets called at painting time.
+void FrameView::setIsOverlapped(bool isOverlapped)
+{
+ if (isOverlapped == m_isOverlapped)
+ return;
+
+ m_isOverlapped = isOverlapped;
+ updateCanBlitOnScrollRecursively();
+}
+
+bool FrameView::isOverlappedIncludingAncestors() const
+{
+ if (isOverlapped())
+ return true;
+
+ if (FrameView* parentView = parentFrameView()) {
+ if (parentView->isOverlapped())
+ return true;
+ }
+
+ return false;
+}
+
+void FrameView::setContentIsOpaque(bool contentIsOpaque)
+{
+ if (contentIsOpaque == m_contentIsOpaque)
+ return;
+
+ m_contentIsOpaque = contentIsOpaque;
+ updateCanBlitOnScrollRecursively();
+}
+
+void FrameView::restoreScrollbar()
+{
+ setScrollbarsSuppressed(false);
+}
+
+bool FrameView::scrollToFragment(const KURL& url)
+{
+ // If our URL has no ref, then we have no place we need to jump to.
+ // OTOH If CSS target was set previously, we want to set it to 0, recalc
+ // and possibly repaint because :target pseudo class may have been
+ // set (see bug 11321).
+ if (!url.hasFragmentIdentifier() && !m_frame->document()->cssTarget())
+ return false;
+
+ String fragmentIdentifier = url.fragmentIdentifier();
+ if (scrollToAnchor(fragmentIdentifier))
+ return true;
+
+ // Try again after decoding the ref, based on the document's encoding.
+ if (m_frame->document()->encoding().isValid())
+ return scrollToAnchor(decodeURLEscapeSequences(fragmentIdentifier, m_frame->document()->encoding()));
+
+ return false;
+}
+
+bool FrameView::scrollToAnchor(const String& name)
+{
+ ASSERT(m_frame->document());
+
+ if (!m_frame->document()->haveStylesheetsLoaded()) {
+ m_frame->document()->setGotoAnchorNeededAfterStylesheetsLoad(true);
+ return false;
+ }
+
+ m_frame->document()->setGotoAnchorNeededAfterStylesheetsLoad(false);
+
+ Element* anchorNode = m_frame->document()->findAnchor(name);
+
+ // Setting to null will clear the current target.
+ m_frame->document()->setCSSTarget(anchorNode);
+
+ if (m_frame->document()->isSVGDocument()) {
+ if (SVGSVGElement* svg = toSVGDocument(m_frame->document())->rootElement()) {
+ svg->setupInitialView(name, anchorNode);
+ if (!anchorNode)
+ return true;
+ }
+ }
+
+ // Implement the rule that "" and "top" both mean top of page as in other browsers.
+ if (!anchorNode && !(name.isEmpty() || equalIgnoringCase(name, "top")))
+ return false;
+
+ maintainScrollPositionAtAnchor(anchorNode ? static_cast<Node*>(anchorNode) : m_frame->document());
+
+ // If the anchor accepts keyboard focus, move focus there to aid users relying on keyboard navigation.
+ if (anchorNode && anchorNode->isFocusable())
+ m_frame->document()->setFocusedElement(anchorNode);
+
+ return true;
+}
+
+void FrameView::maintainScrollPositionAtAnchor(Node* anchorNode)
+{
+ m_maintainScrollPositionAnchor = anchorNode;
+ if (!m_maintainScrollPositionAnchor)
+ return;
+
+ // We need to update the layout before scrolling, otherwise we could
+ // really mess things up if an anchor scroll comes at a bad moment.
+ m_frame->document()->updateStyleIfNeeded();
+ // Only do a layout if changes have occurred that make it necessary.
+ RenderView* renderView = this->renderView();
+ if (renderView && renderView->needsLayout())
+ layout();
+ else
+ scrollToAnchor();
+}
+
+void FrameView::scrollElementToRect(Element* element, const IntRect& rect)
+{
+ m_frame->document()->updateLayoutIgnorePendingStylesheets();
+
+ LayoutRect bounds = element->boundingBox();
+ int centeringOffsetX = (rect.width() - bounds.width()) / 2;
+ int centeringOffsetY = (rect.height() - bounds.height()) / 2;
+ setScrollPosition(IntPoint(bounds.x() - centeringOffsetX - rect.x(), bounds.y() - centeringOffsetY - rect.y()));
+}
+
+void FrameView::setScrollPosition(const IntPoint& scrollPoint)
+{
+ TemporaryChange<bool> changeInProgrammaticScroll(m_inProgrammaticScroll, true);
+ m_maintainScrollPositionAnchor = 0;
+
+ IntPoint newScrollPosition = adjustScrollPositionWithinRange(scrollPoint);
+
+ if (newScrollPosition == scrollPosition())
+ return;
+
+ ScrollView::setScrollPosition(newScrollPosition);
+}
+
+void FrameView::setScrollPositionNonProgrammatically(const IntPoint& scrollPoint)
+{
+ IntPoint newScrollPosition = adjustScrollPositionWithinRange(scrollPoint);
+
+ if (newScrollPosition == scrollPosition())
+ return;
+
+ TemporaryChange<bool> changeInProgrammaticScroll(m_inProgrammaticScroll, false);
+ notifyScrollPositionChanged(newScrollPosition);
+}
+
+void FrameView::setViewportConstrainedObjectsNeedLayout()
+{
+ if (!hasViewportConstrainedObjects())
+ return;
+
+ ViewportConstrainedObjectSet::const_iterator end = m_viewportConstrainedObjects->end();
+ for (ViewportConstrainedObjectSet::const_iterator it = m_viewportConstrainedObjects->begin(); it != end; ++it) {
+ RenderObject* renderer = *it;
+ renderer->setNeedsLayout();
+ }
+}
+
+IntSize FrameView::layoutSize(IncludeScrollbarsInRect scrollbarInclusion) const
+{
+ return scrollbarInclusion == ExcludeScrollbars ? excludeScrollbars(m_layoutSize) : m_layoutSize;
+}
+
+void FrameView::setLayoutSize(const IntSize& size)
+{
+ ASSERT(!layoutSizeFixedToFrameSize());
+
+ setLayoutSizeInternal(size);
+}
+
+void FrameView::scrollPositionChanged()
+{
+ setWasScrolledByUser(true);
+
+ Document* document = m_frame->document();
+ document->enqueueScrollEventForNode(document);
+
+ m_frame->eventHandler().dispatchFakeMouseMoveEventSoon();
+
+ if (RenderView* renderView = document->renderView()) {
+ if (renderView->usesCompositing())
+ renderView->compositor()->frameViewDidScroll();
+ }
+
+ if (m_frame->document() && m_frame->document()->renderer()) {
+ ResourceLoadPriorityOptimizer modifier;
+ m_frame->document()->renderer()->didScroll(modifier);
+ }
+}
+
+void FrameView::repaintFixedElementsAfterScrolling()
+{
+ // For fixed position elements, update widget positions and compositing layers after scrolling,
+ // but only if we're not inside of layout.
+ if (!m_nestedLayoutCount && hasViewportConstrainedObjects()) {
+ if (RenderView* renderView = this->renderView()) {
+ renderView->updateWidgetPositions();
+ renderView->layer()->updateLayerPositionsAfterDocumentScroll();
+ }
+ }
+}
+
+void FrameView::updateFixedElementsAfterScrolling()
+{
+ if (m_nestedLayoutCount <= 1 && hasViewportConstrainedObjects()) {
+ if (RenderView* renderView = this->renderView())
+ renderView->compositor()->updateCompositingLayers(CompositingUpdateOnScroll);
+ }
+}
+
+bool FrameView::shouldRubberBandInDirection(ScrollDirection direction) const
+{
+ Page* page = frame().page();
+ if (!page)
+ return ScrollView::shouldRubberBandInDirection(direction);
+ return page->chrome().client().shouldRubberBandInDirection(direction);
+}
+
+bool FrameView::isRubberBandInProgress() const
+{
+ if (scrollbarsSuppressed())
+ return false;
+
+ // If the main thread updates the scroll position for this FrameView, we should return
+ // ScrollAnimator::isRubberBandInProgress().
+ if (ScrollAnimator* scrollAnimator = existingScrollAnimator())
+ return scrollAnimator->isRubberBandInProgress();
+
+ return false;
+}
+
+HostWindow* FrameView::hostWindow() const
+{
+ Page* page = frame().page();
+ if (!page)
+ return 0;
+ return &page->chrome();
+}
+
+const unsigned cRepaintRectUnionThreshold = 25;
+
+void FrameView::repaintContentRectangle(const IntRect& r)
+{
+ ASSERT(!m_frame->ownerElement());
+
+ if (m_isTrackingRepaints) {
+ IntRect repaintRect = r;
+ repaintRect.move(-scrollOffset());
+ m_trackedRepaintRects.append(repaintRect);
+ }
+
+ double delay = m_deferringRepaints ? 0 : adjustedDeferredRepaintDelay();
+ if (m_deferringRepaints || m_deferredRepaintTimer.isActive() || delay) {
+ IntRect paintRect = r;
+ if (clipsRepaints() && !paintsEntireContents())
+ paintRect.intersect(visibleContentRect());
+ if (paintRect.isEmpty())
+ return;
+ if (m_repaintCount == cRepaintRectUnionThreshold) {
+ IntRect unionedRect;
+ for (unsigned i = 0; i < cRepaintRectUnionThreshold; ++i)
+ unionedRect.unite(pixelSnappedIntRect(m_repaintRects[i]));
+ m_repaintRects.clear();
+ m_repaintRects.append(unionedRect);
+ }
+ if (m_repaintCount < cRepaintRectUnionThreshold)
+ m_repaintRects.append(paintRect);
+ else
+ m_repaintRects[0].unite(paintRect);
+ m_repaintCount++;
+
+ if (!m_deferringRepaints)
+ startDeferredRepaintTimer(delay);
+
+ return;
+ }
+
+ if (!shouldUpdate())
+ return;
+
+ ScrollView::repaintContentRectangle(r);
+}
+
+void FrameView::contentsResized()
+{
+ ScrollView::contentsResized();
+ setNeedsLayout();
+}
+
+void FrameView::scrollbarExistenceDidChange()
+{
+ // We check to make sure the view is attached to a frame() as this method can
+ // be triggered before the view is attached by Frame::createView(...) setting
+ // various values such as setScrollBarModes(...) for example. An ASSERT is
+ // triggered when a view is layout before being attached to a frame().
+ if (!frame().view())
+ return;
+
+ // Note that simply having overlay scrollbars is not sufficient to be
+ // certain that scrollbars' presence does not impact layout. This should
+ // also check if custom scrollbars (as reported by shouldUseCustomScrollbars)
+ // are in use as well.
+ // http://crbug.com/269692
+ bool useOverlayScrollbars = ScrollbarTheme::theme()->usesOverlayScrollbars();
+
+ if (!useOverlayScrollbars && needsLayout())
+ layout();
+
+ if (renderView() && renderView()->usesCompositing()) {
+ renderView()->compositor()->frameViewScrollbarsExistenceDidChange();
+
+ if (!useOverlayScrollbars)
+ renderView()->compositor()->frameViewDidChangeSize();
+ }
+}
+
+void FrameView::beginDeferredRepaints()
+{
+ Page* page = m_frame->page();
+ ASSERT(page);
+
+ if (!isMainFrame()) {
+ page->mainFrame()->view()->beginDeferredRepaints();
+ return;
+ }
+
+ m_deferringRepaints++;
+}
+
+void FrameView::endDeferredRepaints()
+{
+ Page* page = m_frame->page();
+ ASSERT(page);
+
+ if (!isMainFrame()) {
+ page->mainFrame()->view()->endDeferredRepaints();
+ return;
+ }
+
+ ASSERT(m_deferringRepaints > 0);
+
+ if (--m_deferringRepaints)
+ return;
+
+ if (m_deferredRepaintTimer.isActive())
+ return;
+
+ if (double delay = adjustedDeferredRepaintDelay()) {
+ startDeferredRepaintTimer(delay);
+ return;
+ }
+
+ doDeferredRepaints();
+}
+
+void FrameView::startDeferredRepaintTimer(double delay)
+{
+ if (m_deferredRepaintTimer.isActive())
+ return;
+
+ m_deferredRepaintTimer.startOneShot(delay);
+}
+
+void FrameView::handleLoadCompleted()
+{
+ // Once loading has completed, allow autoSize one last opportunity to
+ // reduce the size of the frame.
+ autoSizeIfEnabled();
+ if (shouldUseLoadTimeDeferredRepaintDelay())
+ return;
+ m_deferredRepaintDelay = s_normalDeferredRepaintDelay;
+ flushDeferredRepaints();
+}
+
+void FrameView::flushDeferredRepaints()
+{
+ if (!m_deferredRepaintTimer.isActive())
+ return;
+ m_deferredRepaintTimer.stop();
+ doDeferredRepaints();
+}
+
+void FrameView::doDeferredRepaints()
+{
+ ASSERT(!m_deferringRepaints);
+ if (!shouldUpdate()) {
+ m_repaintRects.clear();
+ m_repaintCount = 0;
+ return;
+ }
+ unsigned size = m_repaintRects.size();
+ for (unsigned i = 0; i < size; i++) {
+ ScrollView::repaintContentRectangle(pixelSnappedIntRect(m_repaintRects[i]));
+ }
+ m_repaintRects.clear();
+ m_repaintCount = 0;
+
+ updateDeferredRepaintDelayAfterRepaint();
+}
+
+bool FrameView::shouldUseLoadTimeDeferredRepaintDelay() const
+{
+ // Don't defer after the initial load of the page has been completed.
+ if (m_frame->tree().top()->document()->loadEventFinished())
+ return false;
+ Document* document = m_frame->document();
+ if (!document)
+ return false;
+ if (document->parsing())
+ return true;
+ if (document->fetcher()->requestCount())
+ return true;
+ return false;
+}
+
+void FrameView::updateDeferredRepaintDelayAfterRepaint()
+{
+ if (!shouldUseLoadTimeDeferredRepaintDelay()) {
+ m_deferredRepaintDelay = s_normalDeferredRepaintDelay;
+ return;
+ }
+ double incrementedRepaintDelay = m_deferredRepaintDelay + s_deferredRepaintDelayIncrementDuringLoading;
+ m_deferredRepaintDelay = std::min(incrementedRepaintDelay, s_maxDeferredRepaintDelayDuringLoading);
+}
+
+void FrameView::resetDeferredRepaintDelay()
+{
+ m_deferredRepaintDelay = 0;
+ if (m_deferredRepaintTimer.isActive()) {
+ m_deferredRepaintTimer.stop();
+ if (!m_deferringRepaints)
+ doDeferredRepaints();
+ }
+}
+
+double FrameView::adjustedDeferredRepaintDelay() const
+{
+ ASSERT(!m_deferringRepaints);
+ if (!m_deferredRepaintDelay)
+ return 0;
+ double timeSinceLastPaint = currentTime() - m_lastPaintTime;
+ return max(0., m_deferredRepaintDelay - timeSinceLastPaint);
+}
+
+void FrameView::deferredRepaintTimerFired(Timer<FrameView>*)
+{
+ doDeferredRepaints();
+}
+
+void FrameView::layoutTimerFired(Timer<FrameView>*)
+{
+ layout();
+}
+
+void FrameView::scheduleRelayout()
+{
+ ASSERT(m_frame->view() == this);
+
+ if (m_layoutRoot) {
+ m_layoutRoot->markContainingBlocksForLayout(false);
+ m_layoutRoot = 0;
+ }
+ if (!m_layoutSchedulingEnabled)
+ return;
+ if (!needsLayout())
+ return;
+ if (!m_frame->document()->shouldScheduleLayout())
+ return;
+ InspectorInstrumentation::didInvalidateLayout(m_frame.get());
+
+ // When frame seamless is enabled, the contents of the frame could affect the layout of the parent frames.
+ // Also invalidate parent frame starting from the owner element of this frame.
+ if (m_frame->ownerRenderer() && m_frame->document()->shouldDisplaySeamlesslyWithParent())
+ m_frame->ownerRenderer()->setNeedsLayout();
+
+ int delay = m_frame->document()->minimumLayoutDelay();
+ if (m_layoutTimer.isActive() && m_delayedLayout && !delay)
+ unscheduleRelayout();
+ if (m_layoutTimer.isActive())
+ return;
+
+ m_delayedLayout = delay != 0;
+ m_layoutTimer.startOneShot(delay * 0.001);
+}
+
+static bool isObjectAncestorContainerOf(RenderObject* ancestor, RenderObject* descendant)
+{
+ for (RenderObject* r = descendant; r; r = r->container()) {
+ if (r == ancestor)
+ return true;
+ }
+ return false;
+}
+
+void FrameView::scheduleRelayoutOfSubtree(RenderObject* relayoutRoot)
+{
+ ASSERT(m_frame->view() == this);
+
+ RenderView* renderView = this->renderView();
+ if (renderView && renderView->needsLayout()) {
+ if (relayoutRoot)
+ relayoutRoot->markContainingBlocksForLayout(false);
+ return;
+ }
+
+ if (layoutPending() || !m_layoutSchedulingEnabled) {
+ if (m_layoutRoot != relayoutRoot) {
+ if (isObjectAncestorContainerOf(m_layoutRoot, relayoutRoot)) {
+ // Keep the current root
+ relayoutRoot->markContainingBlocksForLayout(false, m_layoutRoot);
+ ASSERT(!m_layoutRoot->container() || !m_layoutRoot->container()->needsLayout());
+ } else if (m_layoutRoot && isObjectAncestorContainerOf(relayoutRoot, m_layoutRoot)) {
+ // Re-root at relayoutRoot
+ m_layoutRoot->markContainingBlocksForLayout(false, relayoutRoot);
+ m_layoutRoot = relayoutRoot;
+ ASSERT(!m_layoutRoot->container() || !m_layoutRoot->container()->needsLayout());
+ InspectorInstrumentation::didInvalidateLayout(m_frame.get());
+ } else {
+ // Just do a full relayout
+ if (m_layoutRoot)
+ m_layoutRoot->markContainingBlocksForLayout(false);
+ m_layoutRoot = 0;
+ relayoutRoot->markContainingBlocksForLayout(false);
+ InspectorInstrumentation::didInvalidateLayout(m_frame.get());
+ }
+ }
+ } else if (m_layoutSchedulingEnabled) {
+ int delay = m_frame->document()->minimumLayoutDelay();
+ m_layoutRoot = relayoutRoot;
+ ASSERT(!m_layoutRoot->container() || !m_layoutRoot->container()->needsLayout());
+ InspectorInstrumentation::didInvalidateLayout(m_frame.get());
+ m_delayedLayout = delay != 0;
+ m_layoutTimer.startOneShot(delay * 0.001);
+ }
+}
+
+bool FrameView::layoutPending() const
+{
+ return m_layoutTimer.isActive();
+}
+
+bool FrameView::needsLayout() const
+{
+ // This can return true in cases where the document does not have a body yet.
+ // Document::shouldScheduleLayout takes care of preventing us from scheduling
+ // layout in that case.
+
+ RenderView* renderView = this->renderView();
+ return layoutPending()
+ || (renderView && renderView->needsLayout())
+ || m_layoutRoot;
+}
+
+void FrameView::setNeedsLayout()
+{
+ if (RenderView* renderView = this->renderView())
+ renderView->setNeedsLayout();
+}
+
+void FrameView::unscheduleRelayout()
+{
+ if (!m_layoutTimer.isActive())
+ return;
+
+ m_layoutTimer.stop();
+ m_delayedLayout = false;
+}
+
+void FrameView::serviceScriptedAnimations(double monotonicAnimationStartTime)
+{
+ for (RefPtr<Frame> frame = m_frame; frame; frame = frame->tree().traverseNext()) {
+ frame->view()->serviceScrollAnimations();
+ if (!RuntimeEnabledFeatures::webAnimationsCSSEnabled())
+ frame->animation().serviceAnimations();
+
+ DocumentAnimations::serviceOnAnimationFrame(*frame->document(), monotonicAnimationStartTime);
+ }
+
+ Vector<RefPtr<Document> > documents;
+ for (Frame* frame = m_frame.get(); frame; frame = frame->tree().traverseNext())
+ documents.append(frame->document());
+
+ for (size_t i = 0; i < documents.size(); ++i)
+ documents[i]->serviceScriptedAnimations(monotonicAnimationStartTime);
+}
+
+bool FrameView::isTransparent() const
+{
+ return m_isTransparent;
+}
+
+void FrameView::setTransparent(bool isTransparent)
+{
+ m_isTransparent = isTransparent;
+ if (renderView() && renderView()->layer()->hasCompositedLayerMapping())
+ renderView()->layer()->compositedLayerMapping()->updateContentsOpaque();
+}
+
+bool FrameView::hasOpaqueBackground() const
+{
+ return !m_isTransparent && !m_baseBackgroundColor.hasAlpha();
+}
+
+Color FrameView::baseBackgroundColor() const
+{
+ return m_baseBackgroundColor;
+}
+
+void FrameView::setBaseBackgroundColor(const Color& backgroundColor)
+{
+ if (!backgroundColor.isValid())
+ m_baseBackgroundColor = Color::white;
+ else
+ m_baseBackgroundColor = backgroundColor;
+
+ if (renderView() && renderView()->layer()->hasCompositedLayerMapping()) {
+ CompositedLayerMappingPtr compositedLayerMapping = renderView()->layer()->compositedLayerMapping();
+ compositedLayerMapping->updateContentsOpaque();
+ if (compositedLayerMapping->mainGraphicsLayer())
+ compositedLayerMapping->mainGraphicsLayer()->setNeedsDisplay();
+ }
+ recalculateScrollbarOverlayStyle();
+}
+
+void FrameView::updateBackgroundRecursively(const Color& backgroundColor, bool transparent)
+{
+ for (Frame* frame = m_frame.get(); frame; frame = frame->tree().traverseNext(m_frame.get())) {
+ if (FrameView* view = frame->view()) {
+ view->setTransparent(transparent);
+ view->setBaseBackgroundColor(backgroundColor);
+ }
+ }
+}
+
+bool FrameView::shouldUpdateWhileOffscreen() const
+{
+ return m_shouldUpdateWhileOffscreen;
+}
+
+void FrameView::setShouldUpdateWhileOffscreen(bool shouldUpdateWhileOffscreen)
+{
+ m_shouldUpdateWhileOffscreen = shouldUpdateWhileOffscreen;
+}
+
+bool FrameView::shouldUpdate() const
+{
+ if (isOffscreen() && !shouldUpdateWhileOffscreen())
+ return false;
+ return true;
+}
+
+void FrameView::scrollToAnchor()
+{
+ RefPtr<Node> anchorNode = m_maintainScrollPositionAnchor;
+ if (!anchorNode)
+ return;
+
+ if (!anchorNode->renderer())
+ return;
+
+ LayoutRect rect;
+ if (anchorNode != m_frame->document())
+ rect = anchorNode->boundingBox();
+
+ // Scroll nested layers and frames to reveal the anchor.
+ // Align to the top and to the closest side (this matches other browsers).
+ anchorNode->renderer()->scrollRectToVisible(rect, ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignTopAlways);
+
+ if (AXObjectCache* cache = m_frame->document()->existingAXObjectCache())
+ cache->handleScrolledToAnchor(anchorNode.get());
+
+ // scrollRectToVisible can call into setScrollPosition(), which resets m_maintainScrollPositionAnchor.
+ m_maintainScrollPositionAnchor = anchorNode;
+}
+
+bool FrameView::updateWidgets()
+{
+ if (m_nestedLayoutCount > 1 || m_widgetUpdateSet.isEmpty())
+ return true;
+
+ // Need to swap because script will run inside the below loop and invalidate the iterator.
+ EmbeddedObjectSet objects;
+ objects.swap(m_widgetUpdateSet);
+
+ for (EmbeddedObjectSet::iterator it = objects.begin(); it != objects.end(); ++it) {
+ RenderEmbeddedObject& object = **it;
+ HTMLPlugInElement* element = toHTMLPlugInElement(object.node());
+
+ // The object may have already been destroyed (thus node cleared),
+ // but FrameView holds a manual ref, so it won't have been deleted.
+ if (!element)
+ continue;
+
+ // No need to update if it's already crashed or known to be missing.
+ if (object.showsUnavailablePluginIndicator())
+ continue;
+
+ if (element->needsWidgetUpdate())
+ element->updateWidget();
+ object.updateWidgetPosition();
+
+ // Prevent plugins from causing infinite updates of themselves.
+ // FIXME: Do we really need to prevent this?
+ m_widgetUpdateSet.remove(&object);
+ }
+
+ return m_widgetUpdateSet.isEmpty();
+}
+
+void FrameView::updateWidgetsTimerFired(Timer<FrameView>*)
+{
+ RefPtr<FrameView> protect(this);
+ m_updateWidgetsTimer.stop();
+ for (unsigned i = 0; i < maxUpdateWidgetsIterations; ++i) {
+ if (updateWidgets())
+ return;
+ }
+}
+
+void FrameView::flushAnyPendingPostLayoutTasks()
+{
+ if (m_postLayoutTasksTimer.isActive())
+ performPostLayoutTasks();
+ if (m_updateWidgetsTimer.isActive())
+ updateWidgetsTimerFired(0);
+}
+
+void FrameView::performPostLayoutTasks()
+{
+ TRACE_EVENT0("webkit", "FrameView::performPostLayoutTasks");
+ RefPtr<FrameView> protect(this);
+
+ m_postLayoutTasksTimer.stop();
+
+ m_frame->selection().setCaretRectNeedsUpdate();
+ m_frame->selection().updateAppearance();
+
+ if (m_nestedLayoutCount <= 1) {
+ if (m_firstLayoutCallbackPending) {
+ m_firstLayoutCallbackPending = false;
+ m_frame->loader().didFirstLayout();
+ }
+
+ // Ensure that we always send this eventually.
+ if (!m_frame->document()->parsing() && m_frame->loader().stateMachine()->committedFirstRealDocumentLoad())
+ m_isVisuallyNonEmpty = true;
+
+ // If the layout was done with pending sheets, we are not in fact visually non-empty yet.
+ if (m_isVisuallyNonEmpty && !m_frame->document()->didLayoutWithPendingStylesheets() && m_firstVisuallyNonEmptyLayoutCallbackPending) {
+ m_firstVisuallyNonEmptyLayoutCallbackPending = false;
+ // FIXME: This callback is probably not needed, but is currently used
+ // by android for setting the background color.
+ m_frame->loader().client()->dispatchDidFirstVisuallyNonEmptyLayout();
+ }
+ }
+
+ FontFaceSet::didLayout(m_frame->document());
+
+ RenderView* renderView = this->renderView();
+ if (renderView)
+ renderView->updateWidgetPositions();
+
+ if (!m_updateWidgetsTimer.isActive())
+ m_updateWidgetsTimer.startOneShot(0);
+
+ if (Page* page = m_frame->page()) {
+ if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
+ scrollingCoordinator->notifyLayoutUpdated();
+ }
+
+ scrollToAnchor();
+
+ sendResizeEventIfNeeded();
+}
+
+void FrameView::sendResizeEventIfNeeded()
+{
+ ASSERT(m_frame);
+
+ RenderView* renderView = this->renderView();
+ if (!renderView || renderView->document().printing())
+ return;
+
+ IntSize currentSize = layoutSize(IncludeScrollbars);
+ float currentZoomFactor = renderView->style()->zoom();
+
+ bool shouldSendResizeEvent = currentSize != m_lastViewportSize || currentZoomFactor != m_lastZoomFactor;
+
+ m_lastViewportSize = currentSize;
+ m_lastZoomFactor = currentZoomFactor;
+
+ if (!shouldSendResizeEvent)
+ return;
+
+ m_frame->document()->enqueueResizeEvent();
+
+ if (isMainFrame())
+ InspectorInstrumentation::didResizeMainFrame(m_frame->page());
+}
+
+void FrameView::postLayoutTimerFired(Timer<FrameView>*)
+{
+ performPostLayoutTasks();
+}
+
+void FrameView::updateCounters()
+{
+ RenderView* view = renderView();
+ if (!view->hasRenderCounters())
+ return;
+
+ for (RenderObject* renderer = view; renderer; renderer = renderer->nextInPreOrder()) {
+ if (!renderer->isCounter())
+ continue;
+
+ toRenderCounter(renderer)->updateCounter();
+ }
+}
+
+void FrameView::autoSizeIfEnabled()
+{
+ if (!m_shouldAutoSize)
+ return;
+
+ if (m_inAutoSize)
+ return;
+
+ TemporaryChange<bool> changeInAutoSize(m_inAutoSize, true);
+
+ Document* document = frame().document();
+ if (!document)
+ return;
+
+ RenderView* documentView = document->renderView();
+ Element* documentElement = document->documentElement();
+ if (!documentView || !documentElement)
+ return;
+
+ RenderBox* documentRenderBox = documentElement->renderBox();
+ if (!documentRenderBox)
+ return;
+
+ // If this is the first time we run autosize, start from small height and
+ // allow it to grow.
+ if (!m_didRunAutosize)
+ resize(frameRect().width(), m_minAutoSize.height());
+
+ IntSize size = frameRect().size();
+
+ // Do the resizing twice. The first time is basically a rough calculation using the preferred width
+ // which may result in a height change during the second iteration.
+ for (int i = 0; i < 2; i++) {
+ // Update various sizes including contentsSize, scrollHeight, etc.
+ document->updateLayoutIgnorePendingStylesheets();
+ int width = documentView->minPreferredLogicalWidth();
+ int height = documentRenderBox->scrollHeight();
+ IntSize newSize(width, height);
+
+ // Check to see if a scrollbar is needed for a given dimension and
+ // if so, increase the other dimension to account for the scrollbar.
+ // Since the dimensions are only for the view rectangle, once a
+ // dimension exceeds the maximum, there is no need to increase it further.
+ if (newSize.width() > m_maxAutoSize.width()) {
+ RefPtr<Scrollbar> localHorizontalScrollbar = horizontalScrollbar();
+ if (!localHorizontalScrollbar)
+ localHorizontalScrollbar = createScrollbar(HorizontalScrollbar);
+ if (!localHorizontalScrollbar->isOverlayScrollbar())
+ newSize.setHeight(newSize.height() + localHorizontalScrollbar->height());
+
+ // Don't bother checking for a vertical scrollbar because the width is at
+ // already greater the maximum.
+ } else if (newSize.height() > m_maxAutoSize.height()) {
+ RefPtr<Scrollbar> localVerticalScrollbar = verticalScrollbar();
+ if (!localVerticalScrollbar)
+ localVerticalScrollbar = createScrollbar(VerticalScrollbar);
+ if (!localVerticalScrollbar->isOverlayScrollbar())
+ newSize.setWidth(newSize.width() + localVerticalScrollbar->width());
+
+ // Don't bother checking for a horizontal scrollbar because the height is
+ // already greater the maximum.
+ }
+
+ // Ensure the size is at least the min bounds.
+ newSize = newSize.expandedTo(m_minAutoSize);
+
+ // Bound the dimensions by the max bounds and determine what scrollbars to show.
+ ScrollbarMode horizonalScrollbarMode = ScrollbarAlwaysOff;
+ if (newSize.width() > m_maxAutoSize.width()) {
+ newSize.setWidth(m_maxAutoSize.width());
+ horizonalScrollbarMode = ScrollbarAlwaysOn;
+ }
+ ScrollbarMode verticalScrollbarMode = ScrollbarAlwaysOff;
+ if (newSize.height() > m_maxAutoSize.height()) {
+ newSize.setHeight(m_maxAutoSize.height());
+ verticalScrollbarMode = ScrollbarAlwaysOn;
+ }
+
+ if (newSize == size)
+ continue;
+
+ // While loading only allow the size to increase (to avoid twitching during intermediate smaller states)
+ // unless autoresize has just been turned on or the maximum size is smaller than the current size.
+ if (m_didRunAutosize && size.height() <= m_maxAutoSize.height() && size.width() <= m_maxAutoSize.width()
+ && !m_frame->document()->loadEventFinished() && (newSize.height() < size.height() || newSize.width() < size.width()))
+ break;
+
+ resize(newSize.width(), newSize.height());
+ // Force the scrollbar state to avoid the scrollbar code adding them and causing them to be needed. For example,
+ // a vertical scrollbar may cause text to wrap and thus increase the height (which is the only reason the scollbar is needed).
+ setVerticalScrollbarLock(false);
+ setHorizontalScrollbarLock(false);
+ setScrollbarModes(horizonalScrollbarMode, verticalScrollbarMode, true, true);
+ }
+ m_didRunAutosize = true;
+}
+
+void FrameView::updateOverflowStatus(bool horizontalOverflow, bool verticalOverflow)
+{
+ if (!m_viewportRenderer)
+ return;
+
+ if (m_overflowStatusDirty) {
+ m_horizontalOverflow = horizontalOverflow;
+ m_verticalOverflow = verticalOverflow;
+ m_overflowStatusDirty = false;
+ return;
+ }
+
+ bool horizontalOverflowChanged = (m_horizontalOverflow != horizontalOverflow);
+ bool verticalOverflowChanged = (m_verticalOverflow != verticalOverflow);
+
+ if (horizontalOverflowChanged || verticalOverflowChanged) {
+ m_horizontalOverflow = horizontalOverflow;
+ m_verticalOverflow = verticalOverflow;
+
+ RefPtr<OverflowEvent> event = OverflowEvent::create(horizontalOverflowChanged, horizontalOverflow, verticalOverflowChanged, verticalOverflow);
+ event->setTarget(m_viewportRenderer->node());
+ m_frame->document()->enqueueAnimationFrameEvent(event.release());
+ }
+
+}
+
+const Pagination& FrameView::pagination() const
+{
+ if (m_pagination != Pagination())
+ return m_pagination;
+
+ if (isMainFrame())
+ return m_frame->page()->pagination();
+
+ return m_pagination;
+}
+
+void FrameView::setPagination(const Pagination& pagination)
+{
+ if (m_pagination == pagination)
+ return;
+
+ m_pagination = pagination;
+
+ m_frame->document()->styleResolverChanged(RecalcStyleDeferred);
+}
+
+IntRect FrameView::windowClipRect(bool clipToContents) const
+{
+ ASSERT(m_frame->view() == this);
+
+ if (paintsEntireContents())
+ return IntRect(IntPoint(), contentsSize());
+
+ // Set our clip rect to be our contents.
+ IntRect clipRect = contentsToWindow(visibleContentRect(clipToContents ? ExcludeScrollbars : IncludeScrollbars));
+ if (!m_frame->ownerElement())
+ return clipRect;
+
+ // Take our owner element and get its clip rect.
+ HTMLFrameOwnerElement* ownerElement = m_frame->ownerElement();
+ FrameView* parentView = ownerElement->document().view();
+ if (parentView)
+ clipRect.intersect(parentView->windowClipRectForFrameOwner(ownerElement, true));
+ return clipRect;
+}
+
+IntRect FrameView::windowClipRectForFrameOwner(const HTMLFrameOwnerElement* ownerElement, bool clipToLayerContents) const
+{
+ // The renderer can sometimes be null when style="display:none" interacts
+ // with external content and plugins.
+ if (!ownerElement->renderer())
+ return windowClipRect();
+
+ // If we have no layer, just return our window clip rect.
+ const RenderLayer* enclosingLayer = ownerElement->renderer()->enclosingLayer();
+ if (!enclosingLayer)
+ return windowClipRect();
+
+ // Apply the clip from the layer.
+ IntRect clipRect;
+ if (clipToLayerContents)
+ clipRect = pixelSnappedIntRect(enclosingLayer->childrenClipRect());
+ else
+ clipRect = pixelSnappedIntRect(enclosingLayer->selfClipRect());
+ clipRect = contentsToWindow(clipRect);
+ return intersection(clipRect, windowClipRect());
+}
+
+bool FrameView::isActive() const
+{
+ Page* page = frame().page();
+ return page && page->focusController().isActive();
+}
+
+void FrameView::scrollTo(const IntSize& newOffset)
+{
+ LayoutSize offset = scrollOffset();
+ ScrollView::scrollTo(newOffset);
+ if (offset != scrollOffset())
+ scrollPositionChanged();
+ frame().loader().client()->didChangeScrollOffset();
+}
+
+void FrameView::invalidateScrollbarRect(Scrollbar* scrollbar, const IntRect& rect)
+{
+ // Add in our offset within the FrameView.
+ IntRect dirtyRect = rect;
+ dirtyRect.moveBy(scrollbar->location());
+ invalidateRect(dirtyRect);
+}
+
+void FrameView::getTickmarks(Vector<IntRect>& tickmarks) const
+{
+ tickmarks = frame().document()->markers()->renderedRectsForMarkers(DocumentMarker::TextMatch);
+}
+
+IntRect FrameView::windowResizerRect() const
+{
+ Page* page = frame().page();
+ if (!page)
+ return IntRect();
+ return page->chrome().windowResizerRect();
+}
+
+void FrameView::setVisibleContentScaleFactor(float visibleContentScaleFactor)
+{
+ if (m_visibleContentScaleFactor == visibleContentScaleFactor)
+ return;
+
+ m_visibleContentScaleFactor = visibleContentScaleFactor;
+ updateScrollbars(scrollOffset());
+}
+
+void FrameView::setInputEventsTransformForEmulation(const IntSize& offset, float contentScaleFactor)
+{
+ m_inputEventsOffsetForEmulation = offset;
+ m_inputEventsScaleFactorForEmulation = contentScaleFactor;
+}
+
+IntSize FrameView::inputEventsOffsetForEmulation() const
+{
+ return m_inputEventsOffsetForEmulation;
+}
+
+float FrameView::inputEventsScaleFactor() const
+{
+ return visibleContentScaleFactor() * m_inputEventsScaleFactorForEmulation;
+}
+
+bool FrameView::scrollbarsCanBeActive() const
+{
+ if (m_frame->view() != this)
+ return false;
+
+ return !!m_frame->document();
+}
+
+ScrollableArea* FrameView::enclosingScrollableArea() const
+{
+ // FIXME: Walk up the frame tree and look for a scrollable parent frame or RenderLayer.
+ return 0;
+}
+
+IntRect FrameView::scrollableAreaBoundingBox() const
+{
+ RenderPart* ownerRenderer = frame().ownerRenderer();
+ if (!ownerRenderer)
+ return frameRect();
+
+ return ownerRenderer->absoluteContentQuad().enclosingBoundingBox();
+}
+
+bool FrameView::isScrollable()
+{
+ // Check for:
+ // 1) If there an actual overflow.
+ // 2) display:none or visibility:hidden set to self or inherited.
+ // 3) overflow{-x,-y}: hidden;
+ // 4) scrolling: no;
+
+ // Covers #1
+ IntSize contentsSize = this->contentsSize();
+ IntSize visibleContentSize = visibleContentRect().size();
+ if ((contentsSize.height() <= visibleContentSize.height() && contentsSize.width() <= visibleContentSize.width()))
+ return false;
+
+ // Covers #2.
+ HTMLFrameOwnerElement* owner = m_frame->ownerElement();
+ if (owner && (!owner->renderer() || !owner->renderer()->visibleToHitTesting()))
+ return false;
+
+ // Cover #3 and #4.
+ ScrollbarMode horizontalMode;
+ ScrollbarMode verticalMode;
+ calculateScrollbarModesForLayout(horizontalMode, verticalMode, RulesFromWebContentOnly);
+ if (horizontalMode == ScrollbarAlwaysOff && verticalMode == ScrollbarAlwaysOff)
+ return false;
+
+ return true;
+}
+
+void FrameView::updateScrollableAreaSet()
+{
+ // That ensures that only inner frames are cached.
+ FrameView* parentFrameView = this->parentFrameView();
+ if (!parentFrameView)
+ return;
+
+ if (!isScrollable()) {
+ parentFrameView->removeScrollableArea(this);
+ return;
+ }
+
+ parentFrameView->addScrollableArea(this);
+}
+
+bool FrameView::shouldSuspendScrollAnimations() const
+{
+ return m_frame->loader().state() != FrameStateComplete;
+}
+
+void FrameView::scrollbarStyleChanged(int newStyle, bool forceUpdate)
+{
+ if (!isMainFrame())
+ return;
+
+ if (forceUpdate)
+ ScrollView::scrollbarStyleChanged(newStyle, forceUpdate);
+}
+
+void FrameView::setAnimatorsAreActive()
+{
+ Page* page = m_frame->page();
+ if (!page)
+ return;
+
+ if (ScrollAnimator* scrollAnimator = existingScrollAnimator())
+ scrollAnimator->setIsActive();
+
+ if (!m_scrollableAreas)
+ return;
+
+ for (HashSet<ScrollableArea*>::const_iterator it = m_scrollableAreas->begin(), end = m_scrollableAreas->end(); it != end; ++it) {
+ ScrollableArea* scrollableArea = *it;
+
+ ASSERT(scrollableArea->scrollbarsCanBeActive());
+ scrollableArea->scrollAnimator()->setIsActive();
+ }
+}
+
+void FrameView::notifyPageThatContentAreaWillPaint() const
+{
+ Page* page = m_frame->page();
+ if (!page)
+ return;
+
+ contentAreaWillPaint();
+
+ if (!m_scrollableAreas)
+ return;
+
+ for (HashSet<ScrollableArea*>::const_iterator it = m_scrollableAreas->begin(), end = m_scrollableAreas->end(); it != end; ++it) {
+ ScrollableArea* scrollableArea = *it;
+
+ if (!scrollableArea->scrollbarsCanBeActive())
+ continue;
+
+ scrollableArea->contentAreaWillPaint();
+ }
+}
+
+bool FrameView::scrollAnimatorEnabled() const
+{
+ if (m_frame->settings())
+ return m_frame->settings()->scrollAnimatorEnabled();
+ return false;
+}
+
+void FrameView::updateAnnotatedRegions()
+{
+ Document* document = m_frame->document();
+ if (!document->hasAnnotatedRegions())
+ return;
+ Vector<AnnotatedRegionValue> newRegions;
+ document->renderBox()->collectAnnotatedRegions(newRegions);
+ if (newRegions == document->annotatedRegions())
+ return;
+ document->setAnnotatedRegions(newRegions);
+ if (Page* page = m_frame->page())
+ page->chrome().client().annotatedRegionsChanged();
+}
+
+void FrameView::updateScrollCorner()
+{
+ RefPtr<RenderStyle> cornerStyle;
+ IntRect cornerRect = scrollCornerRect();
+ Document* doc = m_frame->document();
+
+ if (doc && !cornerRect.isEmpty()) {
+ // Try the <body> element first as a scroll corner source.
+ if (Element* body = doc->body()) {
+ if (RenderObject* renderer = body->renderer())
+ cornerStyle = renderer->getUncachedPseudoStyle(PseudoStyleRequest(SCROLLBAR_CORNER), renderer->style());
+ }
+
+ if (!cornerStyle) {
+ // If the <body> didn't have a custom style, then the root element might.
+ if (Element* docElement = doc->documentElement()) {
+ if (RenderObject* renderer = docElement->renderer())
+ cornerStyle = renderer->getUncachedPseudoStyle(PseudoStyleRequest(SCROLLBAR_CORNER), renderer->style());
+ }
+ }
+
+ if (!cornerStyle) {
+ // If we have an owning ipage/Frame element, then it can set the custom scrollbar also.
+ if (RenderPart* renderer = m_frame->ownerRenderer())
+ cornerStyle = renderer->getUncachedPseudoStyle(PseudoStyleRequest(SCROLLBAR_CORNER), renderer->style());
+ }
+ }
+
+ if (cornerStyle) {
+ if (!m_scrollCorner)
+ m_scrollCorner = RenderScrollbarPart::createAnonymous(doc);
+ m_scrollCorner->setStyle(cornerStyle.release());
+ invalidateScrollCorner(cornerRect);
+ } else if (m_scrollCorner) {
+ m_scrollCorner->destroy();
+ m_scrollCorner = 0;
+ }
+
+ ScrollView::updateScrollCorner();
+}
+
+void FrameView::paintScrollCorner(GraphicsContext* context, const IntRect& cornerRect)
+{
+ if (context->updatingControlTints()) {
+ updateScrollCorner();
+ return;
+ }
+
+ if (m_scrollCorner) {
+ bool needsBackgorund = isMainFrame();
+ if (needsBackgorund)
+ context->fillRect(cornerRect, baseBackgroundColor());
+ m_scrollCorner->paintIntoRect(context, cornerRect.location(), cornerRect);
+ return;
+ }
+
+ ScrollView::paintScrollCorner(context, cornerRect);
+}
+
+void FrameView::paintScrollbar(GraphicsContext* context, Scrollbar* bar, const IntRect& rect)
+{
+ bool needsBackgorund = bar->isCustomScrollbar() && isMainFrame();
+ if (needsBackgorund) {
+ IntRect toFill = bar->frameRect();
+ toFill.intersect(rect);
+ context->fillRect(toFill, baseBackgroundColor());
+ }
+
+ ScrollView::paintScrollbar(context, bar, rect);
+}
+
+Color FrameView::documentBackgroundColor() const
+{
+ // <https://bugs.webkit.org/show_bug.cgi?id=59540> We blend the background color of
+ // the document and the body against the base background color of the frame view.
+ // Background images are unfortunately impractical to include.
+
+ // Return invalid Color objects whenever there is insufficient information.
+ if (!frame().document())
+ return Color();
+
+ Element* htmlElement = frame().document()->documentElement();
+ Element* bodyElement = frame().document()->body();
+
+ // Start with invalid colors.
+ Color htmlBackgroundColor;
+ Color bodyBackgroundColor;
+ if (htmlElement && htmlElement->renderer())
+ htmlBackgroundColor = htmlElement->renderer()->style()->visitedDependentColor(CSSPropertyBackgroundColor);
+ if (bodyElement && bodyElement->renderer())
+ bodyBackgroundColor = bodyElement->renderer()->style()->visitedDependentColor(CSSPropertyBackgroundColor);
+
+ if (!bodyBackgroundColor.isValid()) {
+ if (!htmlBackgroundColor.isValid())
+ return Color();
+ return baseBackgroundColor().blend(htmlBackgroundColor);
+ }
+
+ if (!htmlBackgroundColor.isValid())
+ return baseBackgroundColor().blend(bodyBackgroundColor);
+
+ // We take the aggregate of the base background color
+ // the <html> background color, and the <body>
+ // background color to find the document color. The
+ // addition of the base background color is not
+ // technically part of the document background, but it
+ // otherwise poses problems when the aggregate is not
+ // fully opaque.
+ return baseBackgroundColor().blend(htmlBackgroundColor).blend(bodyBackgroundColor);
+}
+
+bool FrameView::hasCustomScrollbars() const
+{
+ const HashSet<RefPtr<Widget> >* viewChildren = children();
+ HashSet<RefPtr<Widget> >::const_iterator end = viewChildren->end();
+ for (HashSet<RefPtr<Widget> >::const_iterator current = viewChildren->begin(); current != end; ++current) {
+ Widget* widget = current->get();
+ if (widget->isFrameView()) {
+ if (toFrameView(widget)->hasCustomScrollbars())
+ return true;
+ } else if (widget->isScrollbar()) {
+ Scrollbar* scrollbar = static_cast<Scrollbar*>(widget);
+ if (scrollbar->isCustomScrollbar())
+ return true;
+ }
+ }
+
+ return false;
+}
+
+FrameView* FrameView::parentFrameView() const
+{
+ if (!parent())
+ return 0;
+
+ if (Frame* parentFrame = m_frame->tree().parent())
+ return parentFrame->view();
+
+ return 0;
+}
+
+void FrameView::updateControlTints()
+{
+ // This is called when control tints are changed from aqua/graphite to clear and vice versa.
+ // We do a "fake" paint, and when the theme gets a paint call, it can then do an invalidate.
+ // This is only done if the theme supports control tinting. It's up to the theme and platform
+ // to define when controls get the tint and to call this function when that changes.
+
+ // Optimize the common case where we bring a window to the front while it's still empty.
+ if (m_frame->document()->url().isEmpty())
+ return;
+
+ if (RenderTheme::theme().supportsControlTints() || hasCustomScrollbars())
+ paintControlTints();
+}
+
+void FrameView::paintControlTints()
+{
+ if (needsLayout())
+ layout();
+ // FIXME: The use of paint seems like overkill: crbug.com/236892
+ GraphicsContext context(0); // NULL canvas to get a non-painting context.
+ context.setUpdatingControlTints(true);
+ paint(&context, frameRect());
+}
+
+bool FrameView::wasScrolledByUser() const
+{
+ return m_wasScrolledByUser;
+}
+
+void FrameView::setWasScrolledByUser(bool wasScrolledByUser)
+{
+ if (m_inProgrammaticScroll)
+ return;
+ m_maintainScrollPositionAnchor = 0;
+ m_wasScrolledByUser = wasScrolledByUser;
+}
+
+void FrameView::paintContents(GraphicsContext* p, const IntRect& rect)
+{
+ Document* document = m_frame->document();
+
+#ifndef NDEBUG
+ bool fillWithRed;
+ if (document->printing())
+ fillWithRed = false; // Printing, don't fill with red (can't remember why).
+ else if (m_frame->ownerElement())
+ fillWithRed = false; // Subframe, don't fill with red.
+ else if (isTransparent())
+ fillWithRed = false; // Transparent, don't fill with red.
+ else if (m_paintBehavior & PaintBehaviorSelectionOnly)
+ fillWithRed = false; // Selections are transparent, don't fill with red.
+ else if (m_nodeToDraw)
+ fillWithRed = false; // Element images are transparent, don't fill with red.
+ else
+ fillWithRed = true;
+
+ if (fillWithRed)
+ p->fillRect(rect, Color(0xFF, 0, 0));
+#endif
+
+ RenderView* renderView = this->renderView();
+ if (!renderView) {
+ WTF_LOG_ERROR("called FrameView::paint with nil renderer");
+ return;
+ }
+
+ ASSERT(!needsLayout());
+ if (needsLayout())
+ return;
+
+ InspectorInstrumentation::willPaint(renderView, 0);
+
+ bool isTopLevelPainter = !s_inPaintContents;
+ s_inPaintContents = true;
+
+ FontCachePurgePreventer fontCachePurgePreventer;
+
+ PaintBehavior oldPaintBehavior = m_paintBehavior;
+
+ if (FrameView* parentView = parentFrameView()) {
+ if (parentView->paintBehavior() & PaintBehaviorFlattenCompositingLayers)
+ m_paintBehavior |= PaintBehaviorFlattenCompositingLayers;
+ }
+
+ if (m_paintBehavior == PaintBehaviorNormal)
+ document->markers()->invalidateRenderedRectsForMarkersInRect(rect);
+
+ if (document->printing())
+ m_paintBehavior |= PaintBehaviorFlattenCompositingLayers;
+
+ ASSERT(!m_isPainting);
+ m_isPainting = true;
+
+ // m_nodeToDraw is used to draw only one element (and its descendants)
+ RenderObject* eltRenderer = m_nodeToDraw ? m_nodeToDraw->renderer() : 0;
+ RenderLayer* rootLayer = renderView->layer();
+
+#ifndef NDEBUG
+ renderView->assertSubtreeIsLaidOut();
+ RenderObject::SetLayoutNeededForbiddenScope forbidSetNeedsLayout(rootLayer->renderer());
+#endif
+
+ RenderObject* enclosingLayerRenderer = eltRenderer->enclosingLayer() ? eltRenderer->enclosingLayer()->renderer() : eltRenderer;
+ rootLayer->paint(p, rect, m_paintBehavior, enclosingLayerRenderer);
+
+ if (rootLayer->containsDirtyOverlayScrollbars())
+ rootLayer->paintOverlayScrollbars(p, rect, m_paintBehavior, eltRenderer);
+
+ m_isPainting = false;
+
+ m_paintBehavior = oldPaintBehavior;
+ m_lastPaintTime = currentTime();
+
+ // Regions may have changed as a result of the visibility/z-index of element changing.
+ if (document->annotatedRegionsDirty())
+ updateAnnotatedRegions();
+
+ if (isTopLevelPainter) {
+ // Everythin that happens after paintContents completions is considered
+ // to be part of the next frame.
+ s_currentFrameTimeStamp = currentTime();
+ s_inPaintContents = false;
+ }
+
+ InspectorInstrumentation::didPaint(renderView, 0, p, rect);
+}
+
+void FrameView::setPaintBehavior(PaintBehavior behavior)
+{
+ m_paintBehavior = behavior;
+}
+
+PaintBehavior FrameView::paintBehavior() const
+{
+ return m_paintBehavior;
+}
+
+bool FrameView::isPainting() const
+{
+ return m_isPainting;
+}
+
+void FrameView::setNodeToDraw(Node* node)
+{
+ m_nodeToDraw = node;
+}
+
+void FrameView::paintOverhangAreas(GraphicsContext* context, const IntRect& horizontalOverhangArea, const IntRect& verticalOverhangArea, const IntRect& dirtyRect)
+{
+ if (context->paintingDisabled())
+ return;
+
+ if (m_frame->document()->printing())
+ return;
+
+ if (isMainFrame()) {
+ if (m_frame->page()->chrome().client().paintCustomOverhangArea(context, horizontalOverhangArea, verticalOverhangArea, dirtyRect))
+ return;
+ }
+
+ ScrollView::paintOverhangAreas(context, horizontalOverhangArea, verticalOverhangArea, dirtyRect);
+}
+
+void FrameView::updateLayoutAndStyleIfNeededRecursive()
+{
+ // We have to crawl our entire tree looking for any FrameViews that need
+ // layout and make sure they are up to date.
+ // Mac actually tests for intersection with the dirty region and tries not to
+ // update layout for frames that are outside the dirty region. Not only does this seem
+ // pointless (since those frames will have set a zero timer to layout anyway), but
+ // it is also incorrect, since if two frames overlap, the first could be excluded from the dirty
+ // region but then become included later by the second frame adding rects to the dirty region
+ // when it lays out.
+
+ m_frame->document()->updateStyleIfNeeded();
+
+ if (needsLayout())
+ layout();
+
+ // Grab a copy of the children() set, as it may be mutated by the following updateLayoutAndStyleIfNeededRecursive
+ // calls, as they can potentially re-enter a layout of the parent frame view, which may add/remove scrollbars
+ // and thus mutates the children() set.
+ Vector<RefPtr<FrameView> > frameViews;
+ collectFrameViewChildren(this, frameViews);
+
+ const Vector<RefPtr<FrameView> >::iterator end = frameViews.end();
+ for (Vector<RefPtr<FrameView> >::iterator it = frameViews.begin(); it != end; ++it)
+ (*it)->updateLayoutAndStyleIfNeededRecursive();
+
+ // updateLayoutAndStyleIfNeededRecursive is called when we need to make sure style and layout are up-to-date before
+ // painting, so we need to flush out any deferred repaints too.
+ flushDeferredRepaints();
+
+ // When seamless is on, child frame can mark parent frame dirty. In such case, child frame
+ // needs to call layout on parent frame recursively.
+ // This assert ensures that parent frames are clean, when child frames finished updating layout and style.
+ ASSERT(!needsLayout());
+}
+
+void FrameView::enableAutoSizeMode(bool enable, const IntSize& minSize, const IntSize& maxSize)
+{
+ ASSERT(!enable || !minSize.isEmpty());
+ ASSERT(minSize.width() <= maxSize.width());
+ ASSERT(minSize.height() <= maxSize.height());
+
+ if (m_shouldAutoSize == enable && m_minAutoSize == minSize && m_maxAutoSize == maxSize)
+ return;
+
+
+ m_shouldAutoSize = enable;
+ m_minAutoSize = minSize;
+ m_maxAutoSize = maxSize;
+ m_didRunAutosize = false;
+
+ setLayoutSizeFixedToFrameSize(enable);
+ setNeedsLayout();
+ scheduleRelayout();
+ if (m_shouldAutoSize)
+ return;
+
+ // Since autosize mode forces the scrollbar mode, change them to being auto.
+ setVerticalScrollbarLock(false);
+ setHorizontalScrollbarLock(false);
+ setScrollbarModes(ScrollbarAuto, ScrollbarAuto);
+}
+
+void FrameView::forceLayout(bool allowSubtree)
+{
+ layout(allowSubtree);
+}
+
+void FrameView::forceLayoutForPagination(const FloatSize& pageSize, const FloatSize& originalPageSize, float maximumShrinkFactor, AdjustViewSizeOrNot shouldAdjustViewSize)
+{
+ // Dumping externalRepresentation(m_frame->renderer()).ascii() is a good trick to see
+ // the state of things before and after the layout
+ if (RenderView* renderView = this->renderView()) {
+ float pageLogicalWidth = renderView->style()->isHorizontalWritingMode() ? pageSize.width() : pageSize.height();
+ float pageLogicalHeight = renderView->style()->isHorizontalWritingMode() ? pageSize.height() : pageSize.width();
+
+ LayoutUnit flooredPageLogicalWidth = static_cast<LayoutUnit>(pageLogicalWidth);
+ LayoutUnit flooredPageLogicalHeight = static_cast<LayoutUnit>(pageLogicalHeight);
+ renderView->setLogicalWidth(flooredPageLogicalWidth);
+ renderView->setPageLogicalHeight(flooredPageLogicalHeight);
+ renderView->setNeedsLayoutAndPrefWidthsRecalc();
+ forceLayout();
+
+ // If we don't fit in the given page width, we'll lay out again. If we don't fit in the
+ // page width when shrunk, we will lay out at maximum shrink and clip extra content.
+ // FIXME: We are assuming a shrink-to-fit printing implementation. A cropping
+ // implementation should not do this!
+ bool horizontalWritingMode = renderView->style()->isHorizontalWritingMode();
+ const LayoutRect& documentRect = renderView->documentRect();
+ LayoutUnit docLogicalWidth = horizontalWritingMode ? documentRect.width() : documentRect.height();
+ if (docLogicalWidth > pageLogicalWidth) {
+ int expectedPageWidth = std::min<float>(documentRect.width(), pageSize.width() * maximumShrinkFactor);
+ int expectedPageHeight = std::min<float>(documentRect.height(), pageSize.height() * maximumShrinkFactor);
+ FloatSize maxPageSize = m_frame->resizePageRectsKeepingRatio(FloatSize(originalPageSize.width(), originalPageSize.height()), FloatSize(expectedPageWidth, expectedPageHeight));
+ pageLogicalWidth = horizontalWritingMode ? maxPageSize.width() : maxPageSize.height();
+ pageLogicalHeight = horizontalWritingMode ? maxPageSize.height() : maxPageSize.width();
+
+ flooredPageLogicalWidth = static_cast<LayoutUnit>(pageLogicalWidth);
+ flooredPageLogicalHeight = static_cast<LayoutUnit>(pageLogicalHeight);
+ renderView->setLogicalWidth(flooredPageLogicalWidth);
+ renderView->setPageLogicalHeight(flooredPageLogicalHeight);
+ renderView->setNeedsLayoutAndPrefWidthsRecalc();
+ forceLayout();
+
+ const LayoutRect& updatedDocumentRect = renderView->documentRect();
+ LayoutUnit docLogicalHeight = horizontalWritingMode ? updatedDocumentRect.height() : updatedDocumentRect.width();
+ LayoutUnit docLogicalTop = horizontalWritingMode ? updatedDocumentRect.y() : updatedDocumentRect.x();
+ LayoutUnit docLogicalRight = horizontalWritingMode ? updatedDocumentRect.maxX() : updatedDocumentRect.maxY();
+ LayoutUnit clippedLogicalLeft = 0;
+ if (!renderView->style()->isLeftToRightDirection())
+ clippedLogicalLeft = docLogicalRight - pageLogicalWidth;
+ LayoutRect overflow(clippedLogicalLeft, docLogicalTop, pageLogicalWidth, docLogicalHeight);
+
+ if (!horizontalWritingMode)
+ overflow = overflow.transposedRect();
+ renderView->clearLayoutOverflow();
+ renderView->addLayoutOverflow(overflow); // This is how we clip in case we overflow again.
+ }
+ }
+
+ if (shouldAdjustViewSize)
+ adjustViewSize();
+}
+
+IntRect FrameView::convertFromRenderer(const RenderObject* renderer, const IntRect& rendererRect) const
+{
+ IntRect rect = pixelSnappedIntRect(enclosingLayoutRect(renderer->localToAbsoluteQuad(FloatRect(rendererRect)).boundingBox()));
+
+ // Convert from page ("absolute") to FrameView coordinates.
+ rect.moveBy(-scrollPosition());
+
+ return rect;
+}
+
+IntRect FrameView::convertToRenderer(const RenderObject* renderer, const IntRect& viewRect) const
+{
+ IntRect rect = viewRect;
+
+ // Convert from FrameView coords into page ("absolute") coordinates.
+ rect.moveBy(scrollPosition());
+
+ // FIXME: we don't have a way to map an absolute rect down to a local quad, so just
+ // move the rect for now.
+ rect.setLocation(roundedIntPoint(renderer->absoluteToLocal(rect.location(), UseTransforms)));
+ return rect;
+}
+
+IntPoint FrameView::convertFromRenderer(const RenderObject* renderer, const IntPoint& rendererPoint) const
+{
+ IntPoint point = roundedIntPoint(renderer->localToAbsolute(rendererPoint, UseTransforms));
+
+ // Convert from page ("absolute") to FrameView coordinates.
+ point.moveBy(-scrollPosition());
+ return point;
+}
+
+IntPoint FrameView::convertToRenderer(const RenderObject* renderer, const IntPoint& viewPoint) const
+{
+ IntPoint point = viewPoint;
+
+ // Convert from FrameView coords into page ("absolute") coordinates.
+ point += IntSize(scrollX(), scrollY());
+
+ return roundedIntPoint(renderer->absoluteToLocal(point, UseTransforms));
+}
+
+IntRect FrameView::convertToContainingView(const IntRect& localRect) const
+{
+ if (const ScrollView* parentScrollView = toScrollView(parent())) {
+ if (parentScrollView->isFrameView()) {
+ const FrameView* parentView = toFrameView(parentScrollView);
+ // Get our renderer in the parent view
+ RenderPart* renderer = m_frame->ownerRenderer();
+ if (!renderer)
+ return localRect;
+
+ IntRect rect(localRect);
+ // Add borders and padding??
+ rect.move(renderer->borderLeft() + renderer->paddingLeft(),
+ renderer->borderTop() + renderer->paddingTop());
+ return parentView->convertFromRenderer(renderer, rect);
+ }
+
+ return Widget::convertToContainingView(localRect);
+ }
+
+ return localRect;
+}
+
+IntRect FrameView::convertFromContainingView(const IntRect& parentRect) const
+{
+ if (const ScrollView* parentScrollView = toScrollView(parent())) {
+ if (parentScrollView->isFrameView()) {
+ const FrameView* parentView = toFrameView(parentScrollView);
+
+ // Get our renderer in the parent view
+ RenderPart* renderer = m_frame->ownerRenderer();
+ if (!renderer)
+ return parentRect;
+
+ IntRect rect = parentView->convertToRenderer(renderer, parentRect);
+ // Subtract borders and padding
+ rect.move(-renderer->borderLeft() - renderer->paddingLeft(),
+ -renderer->borderTop() - renderer->paddingTop());
+ return rect;
+ }
+
+ return Widget::convertFromContainingView(parentRect);
+ }
+
+ return parentRect;
+}
+
+IntPoint FrameView::convertToContainingView(const IntPoint& localPoint) const
+{
+ if (const ScrollView* parentScrollView = toScrollView(parent())) {
+ if (parentScrollView->isFrameView()) {
+ const FrameView* parentView = toFrameView(parentScrollView);
+
+ // Get our renderer in the parent view
+ RenderPart* renderer = m_frame->ownerRenderer();
+ if (!renderer)
+ return localPoint;
+
+ IntPoint point(localPoint);
+
+ // Add borders and padding
+ point.move(renderer->borderLeft() + renderer->paddingLeft(),
+ renderer->borderTop() + renderer->paddingTop());
+ return parentView->convertFromRenderer(renderer, point);
+ }
+
+ return Widget::convertToContainingView(localPoint);
+ }
+
+ return localPoint;
+}
+
+IntPoint FrameView::convertFromContainingView(const IntPoint& parentPoint) const
+{
+ if (const ScrollView* parentScrollView = toScrollView(parent())) {
+ if (parentScrollView->isFrameView()) {
+ const FrameView* parentView = toFrameView(parentScrollView);
+
+ // Get our renderer in the parent view
+ RenderPart* renderer = m_frame->ownerRenderer();
+ if (!renderer)
+ return parentPoint;
+
+ IntPoint point = parentView->convertToRenderer(renderer, parentPoint);
+ // Subtract borders and padding
+ point.move(-renderer->borderLeft() - renderer->paddingLeft(),
+ -renderer->borderTop() - renderer->paddingTop());
+ return point;
+ }
+
+ return Widget::convertFromContainingView(parentPoint);
+ }
+
+ return parentPoint;
+}
+
+// Normal delay
+void FrameView::setRepaintThrottlingDeferredRepaintDelay(double p)
+{
+ s_normalDeferredRepaintDelay = p;
+}
+
+// Negative value would mean that first few repaints happen without a delay
+void FrameView::setRepaintThrottlingnInitialDeferredRepaintDelayDuringLoading(double p)
+{
+ s_initialDeferredRepaintDelayDuringLoading = p;
+}
+
+// The delay grows on each repaint to this maximum value
+void FrameView::setRepaintThrottlingMaxDeferredRepaintDelayDuringLoading(double p)
+{
+ s_maxDeferredRepaintDelayDuringLoading = p;
+}
+
+// On each repaint the delay increases by this amount
+void FrameView::setRepaintThrottlingDeferredRepaintDelayIncrementDuringLoading(double p)
+{
+ s_deferredRepaintDelayIncrementDuringLoading = p;
+}
+
+void FrameView::setTracksRepaints(bool trackRepaints)
+{
+ if (trackRepaints == m_isTrackingRepaints)
+ return;
+
+ for (Frame* frame = m_frame->tree().top(); frame; frame = frame->tree().traverseNext()) {
+ if (RenderView* renderView = frame->contentRenderer())
+ renderView->compositor()->setTracksRepaints(trackRepaints);
+ }
+
+ resetTrackedRepaints();
+ m_isTrackingRepaints = trackRepaints;
+}
+
+void FrameView::resetTrackedRepaints()
+{
+ m_trackedRepaintRects.clear();
+ if (RenderView* renderView = this->renderView())
+ renderView->compositor()->resetTrackedRepaintRects();
+}
+
+String FrameView::trackedRepaintRectsAsText() const
+{
+ TextStream ts;
+ if (!m_trackedRepaintRects.isEmpty()) {
+ ts << "(repaint rects\n";
+ for (size_t i = 0; i < m_trackedRepaintRects.size(); ++i)
+ ts << " (rect " << m_trackedRepaintRects[i].x() << " " << m_trackedRepaintRects[i].y() << " " << m_trackedRepaintRects[i].width() << " " << m_trackedRepaintRects[i].height() << ")\n";
+ ts << ")\n";
+ }
+ return ts.release();
+}
+
+void FrameView::addResizerArea(RenderBox* resizerBox)
+{
+ if (!m_resizerAreas)
+ m_resizerAreas = adoptPtr(new ResizerAreaSet);
+ m_resizerAreas->add(resizerBox);
+}
+
+void FrameView::removeResizerArea(RenderBox* resizerBox)
+{
+ if (!m_resizerAreas)
+ return;
+
+ ResizerAreaSet::iterator it = m_resizerAreas->find(resizerBox);
+ if (it != m_resizerAreas->end())
+ m_resizerAreas->remove(it);
+}
+
+bool FrameView::addScrollableArea(ScrollableArea* scrollableArea)
+{
+ ASSERT(scrollableArea);
+ if (!m_scrollableAreas)
+ m_scrollableAreas = adoptPtr(new ScrollableAreaSet);
+ return m_scrollableAreas->add(scrollableArea).isNewEntry;
+}
+
+bool FrameView::removeScrollableArea(ScrollableArea* scrollableArea)
+{
+ if (!m_scrollableAreas)
+ return false;
+
+ ScrollableAreaSet::iterator it = m_scrollableAreas->find(scrollableArea);
+ if (it == m_scrollableAreas->end())
+ return false;
+
+ m_scrollableAreas->remove(it);
+ return true;
+}
+
+bool FrameView::containsScrollableArea(const ScrollableArea* scrollableArea) const
+{
+ ASSERT(scrollableArea);
+ if (!m_scrollableAreas || !scrollableArea)
+ return false;
+ return m_scrollableAreas->contains(const_cast<ScrollableArea*>(scrollableArea));
+}
+
+void FrameView::removeChild(Widget* widget)
+{
+ if (widget->isFrameView())
+ removeScrollableArea(toFrameView(widget));
+
+ ScrollView::removeChild(widget);
+}
+
+bool FrameView::wheelEvent(const PlatformWheelEvent& wheelEvent)
+{
+ // Note that to allow for rubber-band over-scroll behavior, even non-scrollable views
+ // should handle wheel events.
+#if !USE(RUBBER_BANDING)
+ if (!isScrollable())
+ return false;
+#endif
+
+ // We don't allow mouse wheeling to happen in a ScrollView that has had its scrollbars explicitly disabled.
+ if (!canHaveScrollbars())
+ return false;
+
+ return ScrollableArea::handleWheelEvent(wheelEvent);
+}
+
+bool FrameView::isVerticalDocument() const
+{
+ RenderView* renderView = this->renderView();
+ if (!renderView)
+ return true;
+
+ return renderView->style()->isHorizontalWritingMode();
+}
+
+bool FrameView::isFlippedDocument() const
+{
+ RenderView* renderView = this->renderView();
+ if (!renderView)
+ return false;
+
+ return renderView->style()->isFlippedBlocksWritingMode();
+}
+
+AXObjectCache* FrameView::axObjectCache() const
+{
+ if (frame().document())
+ return frame().document()->existingAXObjectCache();
+ return 0;
+}
+
+void FrameView::setCursor(const Cursor& cursor)
+{
+ Page* page = frame().page();
+ if (!page)
+ return;
+ page->chrome().setCursor(cursor);
+}
+
+bool FrameView::isMainFrame() const
+{
+ return m_frame->isMainFrame();
+}
+
+void FrameView::frameRectsChanged()
+{
+ if (layoutSizeFixedToFrameSize())
+ setLayoutSizeInternal(frameRect().size());
+
+ ScrollView::frameRectsChanged();
+}
+
+void FrameView::setLayoutSizeInternal(const IntSize& size)
+{
+ if (m_layoutSize == size)
+ return;
+
+ m_layoutSize = size;
+ contentsResized();
+}
+
+void FrameView::didAddScrollbar(Scrollbar* scrollbar, ScrollbarOrientation orientation)
+{
+ ScrollableArea::didAddScrollbar(scrollbar, orientation);
+ if (AXObjectCache* cache = axObjectCache())
+ cache->handleScrollbarUpdate(this);
+}
+
+void FrameView::willRemoveScrollbar(Scrollbar* scrollbar, ScrollbarOrientation orientation)
+{
+ ScrollableArea::willRemoveScrollbar(scrollbar, orientation);
+ if (AXObjectCache* cache = axObjectCache()) {
+ cache->remove(scrollbar);
+ cache->handleScrollbarUpdate(this);
+ }
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/frame/FrameView.h b/chromium/third_party/WebKit/Source/core/frame/FrameView.h
new file mode 100644
index 00000000000..e408b984c70
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/FrameView.h
@@ -0,0 +1,590 @@
+/*
+ Copyright (C) 1997 Martin Jones (mjones@kde.org)
+ (C) 1998 Waldo Bastian (bastian@kde.org)
+ (C) 1998, 1999 Torben Weis (weis@kde.org)
+ (C) 1999 Lars Knoll (knoll@kde.org)
+ (C) 1999 Antti Koivisto (koivisto@kde.org)
+ Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#ifndef FrameView_h
+#define FrameView_h
+
+#include "core/frame/AdjustViewSizeOrNot.h"
+#include "core/rendering/Pagination.h"
+#include "core/rendering/PaintPhase.h"
+#include "core/rendering/PartialLayoutState.h"
+#include "platform/geometry/LayoutRect.h"
+#include "platform/graphics/Color.h"
+#include "platform/scroll/ScrollView.h"
+#include "wtf/Forward.h"
+#include "wtf/OwnPtr.h"
+#include "wtf/text/WTFString.h"
+
+namespace WebCore {
+
+class AXObjectCache;
+class Element;
+class FloatSize;
+class Frame;
+class KURL;
+class Node;
+class Page;
+class RenderBox;
+class RenderEmbeddedObject;
+class RenderObject;
+class RenderScrollbarPart;
+class RenderStyle;
+
+Pagination::Mode paginationModeForRenderStyle(RenderStyle*);
+
+typedef unsigned long long DOMTimeStamp;
+
+class FrameView : public ScrollView {
+public:
+ friend class RenderView;
+ friend class Internals;
+
+ static PassRefPtr<FrameView> create(Frame*);
+ static PassRefPtr<FrameView> create(Frame*, const IntSize& initialSize);
+
+ virtual ~FrameView();
+
+ virtual HostWindow* hostWindow() const;
+
+ virtual void invalidateRect(const IntRect&);
+ virtual void setFrameRect(const IntRect&);
+
+ virtual bool scheduleAnimation();
+
+ Frame& frame() const { return *m_frame; }
+
+ RenderView* renderView() const;
+
+ LayoutUnit marginWidth() const { return m_margins.width(); } // -1 means default
+ LayoutUnit marginHeight() const { return m_margins.height(); } // -1 means default
+ void setMarginWidth(LayoutUnit);
+ void setMarginHeight(LayoutUnit);
+
+ virtual void setCanHaveScrollbars(bool);
+ void updateCanHaveScrollbars();
+
+ virtual PassRefPtr<Scrollbar> createScrollbar(ScrollbarOrientation);
+
+ virtual void setContentsSize(const IntSize&);
+
+ void layout(bool allowSubtree = true);
+ bool didFirstLayout() const;
+ void layoutTimerFired(Timer<FrameView>*);
+ void scheduleRelayout();
+ void scheduleRelayoutOfSubtree(RenderObject*);
+ void unscheduleRelayout();
+ bool layoutPending() const;
+ bool isInLayout() const { return m_inLayout; }
+
+ RenderObject* layoutRoot(bool onlyDuringLayout = false) const;
+ void clearLayoutRoot() { m_layoutRoot = 0; }
+ int layoutCount() const { return m_layoutCount; }
+
+ bool needsLayout() const;
+ void setNeedsLayout();
+ void setViewportConstrainedObjectsNeedLayout();
+
+ // Methods for getting/setting the size Blink should use to layout the contents.
+ IntSize layoutSize(IncludeScrollbarsInRect = ExcludeScrollbars) const;
+ void setLayoutSize(const IntSize&);
+
+ // If this is set to false, the layout size will need to be explicitly set by the owner.
+ // E.g. WebViewImpl sets its mainFrame's layout size manually
+ void setLayoutSizeFixedToFrameSize(bool isFixed) { m_layoutSizeFixedToFrameSize = isFixed; }
+ bool layoutSizeFixedToFrameSize() { return m_layoutSizeFixedToFrameSize; }
+
+ bool needsFullRepaint() const { return m_doFullRepaint; }
+
+ void serviceScriptedAnimations(double monotonicAnimationStartTime);
+
+ void updateCompositingLayersAfterStyleChange();
+ void updateCompositingLayersAfterLayout();
+
+ bool hasCompositedContent() const;
+ bool isEnclosedInCompositingLayer() const;
+
+ // Returns true when a paint with the PaintBehaviorFlattenCompositingLayers flag set gives
+ // a faithful representation of the content.
+ bool isSoftwareRenderable() const;
+
+ void resetScrollbars();
+ void prepareForDetach();
+ void detachCustomScrollbars();
+ virtual void recalculateScrollbarOverlayStyle();
+
+ void clear();
+
+ bool isTransparent() const;
+ void setTransparent(bool isTransparent);
+
+ // True if the FrameView is not transparent, and the base background color is opaque.
+ bool hasOpaqueBackground() const;
+
+ Color baseBackgroundColor() const;
+ void setBaseBackgroundColor(const Color&);
+ void updateBackgroundRecursively(const Color&, bool);
+
+ bool shouldUpdateWhileOffscreen() const;
+ void setShouldUpdateWhileOffscreen(bool);
+ bool shouldUpdate() const;
+
+ void adjustViewSize();
+
+ virtual IntRect windowClipRect(bool clipToContents = true) const;
+ IntRect windowClipRectForFrameOwner(const HTMLFrameOwnerElement*, bool clipToLayerContents) const;
+
+ virtual IntRect windowResizerRect() const;
+
+ virtual float visibleContentScaleFactor() const OVERRIDE { return m_visibleContentScaleFactor; }
+ void setVisibleContentScaleFactor(float);
+
+ virtual float inputEventsScaleFactor() const OVERRIDE;
+ virtual IntSize inputEventsOffsetForEmulation() const OVERRIDE;
+ void setInputEventsTransformForEmulation(const IntSize&, float);
+
+ virtual void setScrollPosition(const IntPoint&) OVERRIDE;
+ virtual void repaintFixedElementsAfterScrolling();
+ virtual void updateFixedElementsAfterScrolling();
+ virtual bool shouldRubberBandInDirection(ScrollDirection) const;
+ virtual bool isRubberBandInProgress() const OVERRIDE;
+ void setScrollPositionNonProgrammatically(const IntPoint&);
+
+ // This is different than visibleContentRect() in that it ignores negative (or overly positive)
+ // offsets from rubber-banding, and it takes zooming into account.
+ LayoutRect viewportConstrainedVisibleContentRect() const;
+
+ AtomicString mediaType() const;
+ void setMediaType(const AtomicString&);
+ void adjustMediaTypeForPrinting(bool printing);
+
+ void setCannotBlitToWindow();
+ void setIsOverlapped(bool);
+ bool isOverlapped() const { return m_isOverlapped; }
+ bool isOverlappedIncludingAncestors() const;
+ void setContentIsOpaque(bool);
+
+ void addSlowRepaintObject();
+ void removeSlowRepaintObject();
+ bool hasSlowRepaintObjects() const { return m_slowRepaintObjectCount; }
+
+ // Includes fixed- and sticky-position objects.
+ typedef HashSet<RenderObject*> ViewportConstrainedObjectSet;
+ void addViewportConstrainedObject(RenderObject*);
+ void removeViewportConstrainedObject(RenderObject*);
+ const ViewportConstrainedObjectSet* viewportConstrainedObjects() const { return m_viewportConstrainedObjects.get(); }
+ bool hasViewportConstrainedObjects() const { return m_viewportConstrainedObjects && m_viewportConstrainedObjects->size() > 0; }
+
+ void handleLoadCompleted();
+ void resetDeferredRepaintDelay();
+
+ void updateAnnotatedRegions();
+ void updateControlTints();
+
+ void restoreScrollbar();
+
+ void postLayoutTimerFired(Timer<FrameView>*);
+
+ bool wasScrolledByUser() const;
+ void setWasScrolledByUser(bool);
+
+ bool safeToPropagateScrollToParent() const { return m_safeToPropagateScrollToParent; }
+ void setSafeToPropagateScrollToParent(bool isSafe) { m_safeToPropagateScrollToParent = isSafe; }
+
+ void addWidgetToUpdate(RenderEmbeddedObject&);
+
+ virtual void paintContents(GraphicsContext*, const IntRect& damageRect);
+ void setPaintBehavior(PaintBehavior);
+ PaintBehavior paintBehavior() const;
+ bool isPainting() const;
+ bool hasEverPainted() const { return m_lastPaintTime; }
+ void setLastPaintTime(double lastPaintTime) { m_lastPaintTime = lastPaintTime; }
+ void setNodeToDraw(Node*);
+
+ virtual void paintOverhangAreas(GraphicsContext*, const IntRect& horizontalOverhangArea, const IntRect& verticalOverhangArea, const IntRect& dirtyRect);
+ virtual void paintScrollCorner(GraphicsContext*, const IntRect& cornerRect);
+ virtual void paintScrollbar(GraphicsContext*, Scrollbar*, const IntRect&) OVERRIDE;
+
+ Color documentBackgroundColor() const;
+
+ static double currentFrameTimeStamp() { return s_currentFrameTimeStamp; }
+
+ void updateLayoutAndStyleIfNeededRecursive();
+
+ void incrementVisuallyNonEmptyCharacterCount(unsigned);
+ void incrementVisuallyNonEmptyPixelCount(const IntSize&);
+ void setIsVisuallyNonEmpty() { m_isVisuallyNonEmpty = true; }
+ bool isVisuallyNonEmpty() const { return m_isVisuallyNonEmpty; }
+ void enableAutoSizeMode(bool enable, const IntSize& minSize, const IntSize& maxSize);
+
+ void forceLayout(bool allowSubtree = false);
+ void forceLayoutForPagination(const FloatSize& pageSize, const FloatSize& originalPageSize, float maximumShrinkFactor, AdjustViewSizeOrNot);
+
+ bool scrollToFragment(const KURL&);
+ bool scrollToAnchor(const String&);
+ void maintainScrollPositionAtAnchor(Node*);
+ void scrollElementToRect(Element*, const IntRect&);
+
+ // Methods to convert points and rects between the coordinate space of the renderer, and this view.
+ virtual IntRect convertFromRenderer(const RenderObject*, const IntRect&) const;
+ virtual IntRect convertToRenderer(const RenderObject*, const IntRect&) const;
+ virtual IntPoint convertFromRenderer(const RenderObject*, const IntPoint&) const;
+ virtual IntPoint convertToRenderer(const RenderObject*, const IntPoint&) const;
+
+ bool isFrameViewScrollCorner(RenderScrollbarPart* scrollCorner) const { return m_scrollCorner == scrollCorner; }
+
+ bool isScrollable();
+
+ enum ScrollbarModesCalculationStrategy { RulesFromWebContentOnly, AnyRule };
+ void calculateScrollbarModesForLayout(ScrollbarMode& hMode, ScrollbarMode& vMode, ScrollbarModesCalculationStrategy = AnyRule);
+
+ // Normal delay
+ static void setRepaintThrottlingDeferredRepaintDelay(double);
+ // Negative value would mean that first few repaints happen without a delay
+ static void setRepaintThrottlingnInitialDeferredRepaintDelayDuringLoading(double);
+ // The delay grows on each repaint to this maximum value
+ static void setRepaintThrottlingMaxDeferredRepaintDelayDuringLoading(double);
+ // On each repaint the delay increses by this amount
+ static void setRepaintThrottlingDeferredRepaintDelayIncrementDuringLoading(double);
+
+ virtual IntPoint lastKnownMousePosition() const;
+ bool shouldSetCursor() const;
+
+ void setCursor(const Cursor&);
+
+ virtual bool scrollbarsCanBeActive() const OVERRIDE;
+
+ // FIXME: Remove this method once plugin loading is decoupled from layout.
+ void flushAnyPendingPostLayoutTasks();
+
+ virtual bool shouldSuspendScrollAnimations() const;
+ virtual void scrollbarStyleChanged(int newStyle, bool forceUpdate);
+
+ void setAnimatorsAreActive();
+
+ RenderBox* embeddedContentBox() const;
+
+ void setTracksRepaints(bool);
+ bool isTrackingRepaints() const { return m_isTrackingRepaints; }
+ void resetTrackedRepaints();
+ const Vector<IntRect>& trackedRepaintRects() const { return m_trackedRepaintRects; }
+ String trackedRepaintRectsAsText() const;
+
+ typedef HashSet<ScrollableArea*> ScrollableAreaSet;
+ // Returns whether the scrollable area has just been newly added.
+ bool addScrollableArea(ScrollableArea*);
+ // Returns whether the scrollable area has just been removed.
+ bool removeScrollableArea(ScrollableArea*);
+ bool containsScrollableArea(const ScrollableArea*) const;
+ const ScrollableAreaSet* scrollableAreas() const { return m_scrollableAreas.get(); }
+
+ // With CSS style "resize:" enabled, a little resizer handle will appear at the bottom
+ // right of the object. We keep track of these resizer areas for checking if touches
+ // (implemented using Scroll gesture) are targeting the resizer.
+ typedef HashSet<RenderBox*> ResizerAreaSet;
+ void addResizerArea(RenderBox*);
+ void removeResizerArea(RenderBox*);
+ const ResizerAreaSet* resizerAreas() const { return m_resizerAreas.get(); }
+
+ virtual void removeChild(Widget*) OVERRIDE;
+
+ // This function exists for ports that need to handle wheel events manually.
+ // On Mac WebKit1 the underlying NSScrollView just does the scrolling, but on most other platforms
+ // we need this function in order to do the scroll ourselves.
+ bool wheelEvent(const PlatformWheelEvent&);
+
+ // Page and FrameView both store a Pagination value. Page::pagination() is set only by API,
+ // and FrameView::pagination() is set only by CSS. Page::pagination() will affect all
+ // FrameViews in the page cache, but FrameView::pagination() only affects the current
+ // FrameView. FrameView::pagination() will return m_pagination if it has been set. Otherwise,
+ // it will return Page::pagination() since currently there are no callers that need to
+ // distinguish between the two.
+ const Pagination& pagination() const;
+ void setPagination(const Pagination&);
+
+ bool inProgrammaticScroll() const { return m_inProgrammaticScroll; }
+ void setInProgrammaticScroll(bool programmaticScroll) { m_inProgrammaticScroll = programmaticScroll; }
+
+ void setHasSoftwareFilters(bool hasSoftwareFilters) { m_hasSoftwareFilters = hasSoftwareFilters; }
+ bool hasSoftwareFilters() const { return m_hasSoftwareFilters; }
+
+ virtual bool isActive() const OVERRIDE;
+
+ // DEPRECATED: Use viewportConstrainedVisibleContentRect() instead.
+ IntSize scrollOffsetForFixedPosition() const;
+
+ PartialLayoutState& partialLayout() { return m_partialLayout; }
+
+ // Override scrollbar notifications to update the AXObject cache.
+ virtual void didAddScrollbar(Scrollbar*, ScrollbarOrientation) OVERRIDE;
+ virtual void willRemoveScrollbar(Scrollbar*, ScrollbarOrientation) OVERRIDE;
+
+ class DeferredRepaintScope {
+ public:
+ DeferredRepaintScope(FrameView&);
+ ~DeferredRepaintScope();
+ private:
+ RefPtr<FrameView> m_view;
+ };
+
+protected:
+ virtual bool scrollContentsFastPath(const IntSize& scrollDelta, const IntRect& rectToScroll, const IntRect& clipRect);
+ virtual void scrollContentsSlowPath(const IntRect& updateRect);
+
+ virtual bool isVerticalDocument() const;
+ virtual bool isFlippedDocument() const;
+
+private:
+ explicit FrameView(Frame*);
+
+ void beginDeferredRepaints();
+ void endDeferredRepaints();
+ void flushDeferredRepaints();
+ void startDeferredRepaintTimer(double delay);
+
+ void reset();
+ void init();
+
+ virtual void frameRectsChanged();
+ virtual bool isFrameView() const OVERRIDE { return true; }
+
+ friend class RenderWidget;
+ bool useSlowRepaints(bool considerOverlap = true) const;
+ bool useSlowRepaintsIfNotOverlapped() const;
+ void updateCanBlitOnScrollRecursively();
+ bool contentsInCompositedLayer() const;
+
+ void applyOverflowToViewport(RenderObject*, ScrollbarMode& hMode, ScrollbarMode& vMode);
+ void applyPaginationToViewport();
+
+ void updateOverflowStatus(bool horizontalOverflow, bool verticalOverflow);
+
+ void paintControlTints();
+
+ void updateCounters();
+ void autoSizeIfEnabled();
+ void forceLayoutParentViewIfNeeded();
+ void performPreLayoutTasks();
+ void performLayout(RenderObject* rootForThisLayout, bool inSubtreeLayout);
+ void scheduleOrPerformPostLayoutTasks();
+ void performPostLayoutTasks();
+
+ void repaintTree(RenderObject* root);
+
+ virtual void gatherDebugLayoutRects(RenderObject* layoutRoot);
+
+ virtual void repaintContentRectangle(const IntRect&);
+ virtual void contentsResized() OVERRIDE;
+ virtual void scrollbarExistenceDidChange();
+
+ // Override ScrollView methods to do point conversion via renderers, in order to
+ // take transforms into account.
+ virtual IntRect convertToContainingView(const IntRect&) const OVERRIDE;
+ virtual IntRect convertFromContainingView(const IntRect&) const OVERRIDE;
+ virtual IntPoint convertToContainingView(const IntPoint&) const OVERRIDE;
+ virtual IntPoint convertFromContainingView(const IntPoint&) const OVERRIDE;
+
+ // ScrollableArea interface
+ virtual void invalidateScrollbarRect(Scrollbar*, const IntRect&) OVERRIDE;
+ virtual void getTickmarks(Vector<IntRect>&) const OVERRIDE;
+ virtual void scrollTo(const IntSize&) OVERRIDE;
+ virtual ScrollableArea* enclosingScrollableArea() const OVERRIDE;
+ virtual IntRect scrollableAreaBoundingBox() const OVERRIDE;
+ virtual bool scrollAnimatorEnabled() const OVERRIDE;
+ virtual bool usesCompositedScrolling() const OVERRIDE;
+ virtual GraphicsLayer* layerForScrolling() const OVERRIDE;
+ virtual GraphicsLayer* layerForHorizontalScrollbar() const OVERRIDE;
+ virtual GraphicsLayer* layerForVerticalScrollbar() const OVERRIDE;
+ virtual GraphicsLayer* layerForScrollCorner() const OVERRIDE;
+
+ void sendResizeEventIfNeeded();
+
+ void updateScrollableAreaSet();
+
+ virtual void notifyPageThatContentAreaWillPaint() const;
+
+ bool shouldUseLoadTimeDeferredRepaintDelay() const;
+ void deferredRepaintTimerFired(Timer<FrameView>*);
+ void doDeferredRepaints();
+ void updateDeferredRepaintDelayAfterRepaint();
+ double adjustedDeferredRepaintDelay() const;
+
+ void updateWidgetsTimerFired(Timer<FrameView>*);
+ bool updateWidgets();
+
+ void scrollToAnchor();
+ void scrollPositionChanged();
+
+ bool hasCustomScrollbars() const;
+ bool shouldUseCustomScrollbars(Element*& customScrollbarElement, Frame*& customScrollbarFrame);
+
+ virtual void updateScrollCorner();
+
+ FrameView* parentFrameView() const;
+
+ virtual AXObjectCache* axObjectCache() const;
+ void removeFromAXObjectCache();
+
+ bool isMainFrame() const;
+
+ void setLayoutSizeInternal(const IntSize&);
+
+ static double s_currentFrameTimeStamp; // used for detecting decoded resource thrash in the cache
+ static bool s_inPaintContents;
+
+ LayoutSize m_size;
+ LayoutSize m_margins;
+
+ typedef HashSet<RefPtr<RenderEmbeddedObject> > EmbeddedObjectSet;
+ EmbeddedObjectSet m_widgetUpdateSet;
+
+ RefPtr<Frame> m_frame;
+
+ bool m_doFullRepaint;
+
+ bool m_canHaveScrollbars;
+ bool m_cannotBlitToWindow;
+ bool m_isOverlapped;
+ bool m_contentIsOpaque;
+ unsigned m_slowRepaintObjectCount;
+ int m_borderX;
+ int m_borderY;
+
+ Timer<FrameView> m_layoutTimer;
+ bool m_delayedLayout;
+ RenderObject* m_layoutRoot;
+
+ bool m_layoutSchedulingEnabled;
+ bool m_inLayout;
+ bool m_doingPreLayoutStyleUpdate;
+ bool m_inSynchronousPostLayout;
+ int m_layoutCount;
+ unsigned m_nestedLayoutCount;
+ Timer<FrameView> m_postLayoutTasksTimer;
+ Timer<FrameView> m_updateWidgetsTimer;
+ bool m_firstLayoutCallbackPending;
+
+ bool m_firstLayout;
+ bool m_isTransparent;
+ Color m_baseBackgroundColor;
+ IntSize m_lastViewportSize;
+ float m_lastZoomFactor;
+
+ AtomicString m_mediaType;
+ AtomicString m_mediaTypeWhenNotPrinting;
+
+ bool m_overflowStatusDirty;
+ bool m_horizontalOverflow;
+ bool m_verticalOverflow;
+ RenderObject* m_viewportRenderer;
+
+ Pagination m_pagination;
+
+ bool m_wasScrolledByUser;
+ bool m_inProgrammaticScroll;
+ bool m_safeToPropagateScrollToParent;
+
+ unsigned m_deferringRepaints;
+ unsigned m_repaintCount;
+ Vector<LayoutRect> m_repaintRects;
+ Timer<FrameView> m_deferredRepaintTimer;
+ double m_deferredRepaintDelay;
+ double m_lastPaintTime;
+
+ bool m_isTrackingRepaints; // Used for testing.
+ Vector<IntRect> m_trackedRepaintRects;
+
+ bool m_shouldUpdateWhileOffscreen;
+
+ RefPtr<Node> m_nodeToDraw;
+ PaintBehavior m_paintBehavior;
+ bool m_isPainting;
+
+ unsigned m_visuallyNonEmptyCharacterCount;
+ unsigned m_visuallyNonEmptyPixelCount;
+ bool m_isVisuallyNonEmpty;
+ bool m_firstVisuallyNonEmptyLayoutCallbackPending;
+
+ RefPtr<Node> m_maintainScrollPositionAnchor;
+
+ // Renderer to hold our custom scroll corner.
+ RenderScrollbarPart* m_scrollCorner;
+
+ // If true, automatically resize the frame view around its content.
+ bool m_shouldAutoSize;
+ bool m_inAutoSize;
+ // True if autosize has been run since m_shouldAutoSize was set.
+ bool m_didRunAutosize;
+ // The lower bound on the size when autosizing.
+ IntSize m_minAutoSize;
+ // The upper bound on the size when autosizing.
+ IntSize m_maxAutoSize;
+
+ OwnPtr<ScrollableAreaSet> m_scrollableAreas;
+ OwnPtr<ResizerAreaSet> m_resizerAreas;
+ OwnPtr<ViewportConstrainedObjectSet> m_viewportConstrainedObjects;
+
+ static double s_normalDeferredRepaintDelay;
+ static double s_initialDeferredRepaintDelayDuringLoading;
+ static double s_maxDeferredRepaintDelayDuringLoading;
+ static double s_deferredRepaintDelayIncrementDuringLoading;
+
+ bool m_hasSoftwareFilters;
+
+ float m_visibleContentScaleFactor;
+ IntSize m_inputEventsOffsetForEmulation;
+ float m_inputEventsScaleFactorForEmulation;
+
+ PartialLayoutState m_partialLayout;
+ IntSize m_layoutSize;
+ bool m_layoutSizeFixedToFrameSize;
+};
+
+inline void FrameView::incrementVisuallyNonEmptyCharacterCount(unsigned count)
+{
+ if (m_isVisuallyNonEmpty)
+ return;
+ m_visuallyNonEmptyCharacterCount += count;
+ // Use a threshold value to prevent very small amounts of visible content from triggering didFirstVisuallyNonEmptyLayout.
+ // The first few hundred characters rarely contain the interesting content of the page.
+ static const unsigned visualCharacterThreshold = 200;
+ if (m_visuallyNonEmptyCharacterCount > visualCharacterThreshold)
+ setIsVisuallyNonEmpty();
+}
+
+inline void FrameView::incrementVisuallyNonEmptyPixelCount(const IntSize& size)
+{
+ if (m_isVisuallyNonEmpty)
+ return;
+ m_visuallyNonEmptyPixelCount += size.width() * size.height();
+ // Use a threshold value to prevent very small amounts of visible content from triggering didFirstVisuallyNonEmptyLayout
+ static const unsigned visualPixelThreshold = 32 * 32;
+ if (m_visuallyNonEmptyPixelCount > visualPixelThreshold)
+ setIsVisuallyNonEmpty();
+}
+
+DEFINE_TYPE_CASTS(FrameView, Widget, widget, widget->isFrameView(), widget.isFrameView());
+
+} // namespace WebCore
+
+#endif // FrameView_h
diff --git a/chromium/third_party/WebKit/Source/core/frame/GraphicsLayerDebugInfo.cpp b/chromium/third_party/WebKit/Source/core/frame/GraphicsLayerDebugInfo.cpp
new file mode 100644
index 00000000000..51470a2210e
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/GraphicsLayerDebugInfo.cpp
@@ -0,0 +1,46 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#include "config.h"
+
+#include "core/frame/GraphicsLayerDebugInfo.h"
+
+#include "platform/JSONValues.h"
+#include "wtf/text/CString.h"
+
+namespace WebCore {
+
+void GraphicsLayerDebugInfo::appendAsTraceFormat(blink::WebString* out) const
+{
+ RefPtr<JSONArray> jsonArray = JSONArray::create();
+ for (size_t i = 0; i < m_currentLayoutRects.size(); i++) {
+ const LayoutRect& rect = m_currentLayoutRects[i];
+ RefPtr<JSONObject> rectContainer = JSONObject::create();
+ RefPtr<JSONArray> rectArray = JSONArray::create();
+ rectArray->pushNumber(rect.x().toFloat());
+ rectArray->pushNumber(rect.y().toFloat());
+ rectArray->pushNumber(rect.maxX().toFloat());
+ rectArray->pushNumber(rect.maxY().toFloat());
+ rectContainer->setArray("geometry_rect", rectArray);
+ jsonArray->pushObject(rectContainer);
+ }
+ *out = jsonArray->toJSONString();
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/frame/GraphicsLayerDebugInfo.h b/chromium/third_party/WebKit/Source/core/frame/GraphicsLayerDebugInfo.h
new file mode 100644
index 00000000000..26d2fce117a
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/GraphicsLayerDebugInfo.h
@@ -0,0 +1,50 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef GraphicsLayerDebugInfo_h
+#define GraphicsLayerDebugInfo_h
+
+#include "platform/geometry/LayoutRect.h"
+#include "public/platform/WebGraphicsLayerDebugInfo.h"
+
+#include "wtf/Vector.h"
+
+namespace WebCore {
+
+class GraphicsLayerDebugInfo FINAL : public blink::WebGraphicsLayerDebugInfo {
+public:
+ virtual void appendAsTraceFormat(blink::WebString* out) const OVERRIDE;
+ virtual ~GraphicsLayerDebugInfo() { };
+ Vector<LayoutRect> m_currentLayoutRects;
+};
+
+} // namespace WebCore
+
+#endif
diff --git a/chromium/third_party/WebKit/Source/core/frame/History.cpp b/chromium/third_party/WebKit/Source/core/frame/History.cpp
new file mode 100644
index 00000000000..863c93683ca
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/History.cpp
@@ -0,0 +1,140 @@
+/*
+ * Copyright (C) 2007 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/frame/History.h"
+
+#include "bindings/v8/ExceptionState.h"
+#include "core/dom/Document.h"
+#include "core/dom/ExceptionCode.h"
+#include "core/history/HistoryItem.h"
+#include "core/loader/DocumentLoader.h"
+#include "core/loader/FrameLoader.h"
+#include "core/loader/FrameLoaderClient.h"
+#include "core/frame/Frame.h"
+#include "core/page/BackForwardClient.h"
+#include "core/page/Page.h"
+#include "platform/weborigin/KURL.h"
+#include "platform/weborigin/SecurityOrigin.h"
+#include "wtf/MainThread.h"
+
+namespace WebCore {
+
+History::History(Frame* frame)
+ : DOMWindowProperty(frame)
+ , m_lastStateObjectRequested(0)
+{
+ ScriptWrappable::init(this);
+}
+
+unsigned History::length() const
+{
+ if (!m_frame)
+ return 0;
+ if (!m_frame->page())
+ return 0;
+ return m_frame->page()->backForward().backForwardListCount();
+}
+
+SerializedScriptValue* History::state()
+{
+ m_lastStateObjectRequested = stateInternal();
+ return m_lastStateObjectRequested.get();
+}
+
+SerializedScriptValue* History::stateInternal() const
+{
+ if (!m_frame)
+ return 0;
+
+ if (HistoryItem* historyItem = m_frame->loader().currentItem())
+ return historyItem->stateObject();
+
+ return 0;
+}
+
+bool History::stateChanged() const
+{
+ return m_lastStateObjectRequested != stateInternal();
+}
+
+bool History::isSameAsCurrentState(SerializedScriptValue* state) const
+{
+ return state == stateInternal();
+}
+
+void History::back(ExecutionContext* context)
+{
+ go(context, -1);
+}
+
+void History::forward(ExecutionContext* context)
+{
+ go(context, 1);
+}
+
+void History::go(ExecutionContext* context, int distance)
+{
+ if (!m_frame)
+ return;
+
+ ASSERT(isMainThread());
+ Document* activeDocument = toDocument(context);
+ if (!activeDocument)
+ return;
+
+ if (!activeDocument->canNavigate(m_frame))
+ return;
+
+ m_frame->navigationScheduler().scheduleHistoryNavigation(distance);
+}
+
+KURL History::urlForState(const String& urlString)
+{
+ Document* document = m_frame->document();
+
+ if (urlString.isNull())
+ return document->url();
+ if (urlString.isEmpty())
+ return document->baseURL();
+
+ return KURL(document->baseURL(), urlString);
+}
+
+void History::stateObjectAdded(PassRefPtr<SerializedScriptValue> data, const String& /* title */, const String& urlString, SameDocumentNavigationSource sameDocumentNavigationSource, ExceptionState& exceptionState)
+{
+ if (!m_frame || !m_frame->page())
+ return;
+
+ KURL fullURL = urlForState(urlString);
+ if (!fullURL.isValid() || !m_frame->document()->securityOrigin()->canRequest(fullURL)) {
+ // We can safely expose the URL to JavaScript, as a) no redirection takes place: JavaScript already had this URL, b) JavaScript can only access a same-origin History object.
+ exceptionState.throwSecurityError("A history state object with URL '" + fullURL.elidedString() + "' cannot be created in a document with origin '" + m_frame->document()->securityOrigin()->toString() + "'.");
+ return;
+ }
+ m_frame->loader().updateForSameDocumentNavigation(fullURL, sameDocumentNavigationSource, data, FrameLoader::DoNotUpdateBackForwardList);
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/frame/History.h b/chromium/third_party/WebKit/Source/core/frame/History.h
new file mode 100644
index 00000000000..42ec3456a02
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/History.h
@@ -0,0 +1,72 @@
+/*
+ * Copyright (C) 2007 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef History_h
+#define History_h
+
+#include "bindings/v8/ScriptWrappable.h"
+#include "bindings/v8/SerializedScriptValue.h"
+#include "core/loader/FrameLoaderTypes.h"
+#include "core/frame/DOMWindowProperty.h"
+#include "wtf/Forward.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefCounted.h"
+
+namespace WebCore {
+
+class Frame;
+class KURL;
+class ExecutionContext;
+class ExceptionState;
+
+class History : public ScriptWrappable, public RefCounted<History>, public DOMWindowProperty {
+public:
+ static PassRefPtr<History> create(Frame* frame) { return adoptRef(new History(frame)); }
+
+ unsigned length() const;
+ SerializedScriptValue* state();
+
+ void back(ExecutionContext*);
+ void forward(ExecutionContext*);
+ void go(ExecutionContext*, int distance);
+
+ bool stateChanged() const;
+ bool isSameAsCurrentState(SerializedScriptValue*) const;
+
+ void stateObjectAdded(PassRefPtr<SerializedScriptValue>, const String& title, const String& url, SameDocumentNavigationSource, ExceptionState&);
+
+private:
+ explicit History(Frame*);
+
+ KURL urlForState(const String& url);
+
+ SerializedScriptValue* stateInternal() const;
+
+ RefPtr<SerializedScriptValue> m_lastStateObjectRequested;
+};
+
+} // namespace WebCore
+
+#endif // History_h
diff --git a/chromium/third_party/WebKit/Source/core/frame/History.idl b/chromium/third_party/WebKit/Source/core/frame/History.idl
new file mode 100644
index 00000000000..6bd64396230
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/History.idl
@@ -0,0 +1,36 @@
+/*
+ * Copyright (C) 2007, 2008 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+interface History {
+ readonly attribute unsigned long length;
+ [Custom=Getter] readonly attribute SerializedScriptValue state;
+
+ [CallWith=ExecutionContext] void back();
+ [CallWith=ExecutionContext] void forward();
+ [CallWith=ExecutionContext] void go([Default=Undefined] optional long distance);
+
+ [Custom, PerContextEnabled=PushState, RaisesException] void pushState(any data, DOMString title, optional DOMString url);
+ [Custom, PerContextEnabled=PushState, RaisesException] void replaceState(any data, DOMString title, optional DOMString url);
+};
diff --git a/chromium/third_party/WebKit/Source/core/frame/ImageBitmap.cpp b/chromium/third_party/WebKit/Source/core/frame/ImageBitmap.cpp
new file mode 100644
index 00000000000..ec54c645533
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/ImageBitmap.cpp
@@ -0,0 +1,203 @@
+// Copyright 2013 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "config.h"
+#include "core/frame/ImageBitmap.h"
+
+#include "core/html/HTMLCanvasElement.h"
+#include "core/html/HTMLVideoElement.h"
+#include "core/html/ImageData.h"
+#include "core/html/canvas/CanvasRenderingContext.h"
+#include "platform/graphics/BitmapImage.h"
+#include "platform/graphics/GraphicsContext.h"
+#include "platform/graphics/ImageBuffer.h"
+#include "wtf/RefPtr.h"
+
+using namespace std;
+
+namespace WebCore {
+
+static inline IntRect normalizeRect(const IntRect& rect)
+{
+ return IntRect(min(rect.x(), rect.maxX()),
+ min(rect.y(), rect.maxY()),
+ max(rect.width(), -rect.width()),
+ max(rect.height(), -rect.height()));
+}
+
+static inline PassRefPtr<Image> cropImage(Image* image, const IntRect& cropRect)
+{
+ IntRect intersectRect = intersection(IntRect(IntPoint(), image->size()), cropRect);
+ if (!intersectRect.width() || !intersectRect.height())
+ return 0;
+
+ SkBitmap cropped;
+ image->nativeImageForCurrentFrame()->bitmap().extractSubset(&cropped, intersectRect);
+ return BitmapImage::create(NativeImageSkia::create(cropped));
+}
+
+ImageBitmap::ImageBitmap(HTMLImageElement* image, const IntRect& cropRect)
+ : m_imageElement(image)
+ , m_bitmap(0)
+ , m_cropRect(cropRect)
+{
+ IntRect srcRect = intersection(cropRect, IntRect(0, 0, image->width(), image->height()));
+ m_bitmapRect = IntRect(IntPoint(max(0, -cropRect.x()), max(0, -cropRect.y())), srcRect.size());
+ m_bitmapOffset = srcRect.location();
+
+ if (!srcRect.width() || !srcRect.height())
+ m_imageElement = 0;
+ else
+ m_imageElement->addClient(this);
+
+ ScriptWrappable::init(this);
+}
+
+ImageBitmap::ImageBitmap(HTMLVideoElement* video, const IntRect& cropRect)
+ : m_imageElement(0)
+ , m_cropRect(cropRect)
+ , m_bitmapOffset(IntPoint())
+{
+ IntRect videoRect = IntRect(IntPoint(), video->player()->naturalSize());
+ IntRect srcRect = intersection(cropRect, videoRect);
+ IntRect dstRect(IntPoint(), srcRect.size());
+
+ OwnPtr<ImageBuffer> buf = ImageBuffer::create(videoRect.size());
+ if (!buf)
+ return;
+ GraphicsContext* c = buf->context();
+ c->clip(dstRect);
+ c->translate(-srcRect.x(), -srcRect.y());
+ video->paintCurrentFrameInContext(c, videoRect);
+ m_bitmap = buf->copyImage(DontCopyBackingStore);
+ m_bitmapRect = IntRect(IntPoint(max(0, -cropRect.x()), max(0, -cropRect.y())), srcRect.size());
+
+ ScriptWrappable::init(this);
+}
+
+ImageBitmap::ImageBitmap(HTMLCanvasElement* canvas, const IntRect& cropRect)
+ : m_imageElement(0)
+ , m_cropRect(cropRect)
+ , m_bitmapOffset(IntPoint())
+{
+ CanvasRenderingContext* sourceContext = canvas->renderingContext();
+ if (sourceContext && sourceContext->is3d())
+ sourceContext->paintRenderingResultsToCanvas();
+
+ IntRect srcRect = intersection(cropRect, IntRect(IntPoint(), canvas->size()));
+ m_bitmapRect = IntRect(IntPoint(max(0, -cropRect.x()), max(0, -cropRect.y())), srcRect.size());
+ m_bitmap = cropImage(canvas->buffer()->copyImage(CopyBackingStore).get(), cropRect);
+
+ ScriptWrappable::init(this);
+}
+
+ImageBitmap::ImageBitmap(ImageData* data, const IntRect& cropRect)
+ : m_imageElement(0)
+ , m_cropRect(cropRect)
+ , m_bitmapOffset(IntPoint())
+{
+ IntRect srcRect = intersection(cropRect, IntRect(IntPoint(), data->size()));
+
+ OwnPtr<ImageBuffer> buf = ImageBuffer::create(data->size());
+ if (!buf)
+ return;
+ if (srcRect.width() > 0 && srcRect.height() > 0)
+ buf->putByteArray(Premultiplied, data->data(), data->size(), srcRect, IntPoint(min(0, -cropRect.x()), min(0, -cropRect.y())));
+
+ m_bitmap = buf->copyImage(DontCopyBackingStore);
+ m_bitmapRect = IntRect(IntPoint(max(0, -cropRect.x()), max(0, -cropRect.y())), srcRect.size());
+
+ ScriptWrappable::init(this);
+}
+
+ImageBitmap::ImageBitmap(ImageBitmap* bitmap, const IntRect& cropRect)
+ : m_imageElement(bitmap->imageElement())
+ , m_bitmap(0)
+ , m_cropRect(cropRect)
+ , m_bitmapOffset(IntPoint())
+{
+ IntRect oldBitmapRect = bitmap->bitmapRect();
+ IntRect srcRect = intersection(cropRect, oldBitmapRect);
+ m_bitmapRect = IntRect(IntPoint(max(0, oldBitmapRect.x() - cropRect.x()), max(0, oldBitmapRect.y() - cropRect.y())), srcRect.size());
+
+ if (m_imageElement) {
+ m_imageElement->addClient(this);
+ m_bitmapOffset = srcRect.location();
+ } else if (bitmap->bitmapImage()) {
+ IntRect adjustedCropRect(IntPoint(cropRect.x() -oldBitmapRect.x(), cropRect.y() - oldBitmapRect.y()), cropRect.size());
+ m_bitmap = cropImage(bitmap->bitmapImage().get(), adjustedCropRect);
+ }
+
+ ScriptWrappable::init(this);
+}
+
+ImageBitmap::ImageBitmap(Image* image, const IntRect& cropRect)
+ : m_imageElement(0)
+ , m_cropRect(cropRect)
+{
+ IntRect srcRect = intersection(cropRect, IntRect(IntPoint(), image->size()));
+ m_bitmap = cropImage(image, cropRect);
+ m_bitmapRect = IntRect(IntPoint(max(0, -cropRect.x()), max(0, -cropRect.y())), srcRect.size());
+
+ ScriptWrappable::init(this);
+}
+
+ImageBitmap::~ImageBitmap()
+{
+ if (m_imageElement)
+ m_imageElement->removeClient(this);
+}
+
+PassRefPtr<ImageBitmap> ImageBitmap::create(HTMLImageElement* image, const IntRect& cropRect)
+{
+ IntRect normalizedCropRect = normalizeRect(cropRect);
+ return adoptRef(new ImageBitmap(image, normalizedCropRect));
+}
+
+PassRefPtr<ImageBitmap> ImageBitmap::create(HTMLVideoElement* video, const IntRect& cropRect)
+{
+ IntRect normalizedCropRect = normalizeRect(cropRect);
+ return adoptRef(new ImageBitmap(video, normalizedCropRect));
+}
+
+PassRefPtr<ImageBitmap> ImageBitmap::create(HTMLCanvasElement* canvas, const IntRect& cropRect)
+{
+ IntRect normalizedCropRect = normalizeRect(cropRect);
+ return adoptRef(new ImageBitmap(canvas, normalizedCropRect));
+}
+
+PassRefPtr<ImageBitmap> ImageBitmap::create(ImageData* data, const IntRect& cropRect)
+{
+ IntRect normalizedCropRect = normalizeRect(cropRect);
+ return adoptRef(new ImageBitmap(data, normalizedCropRect));
+}
+
+PassRefPtr<ImageBitmap> ImageBitmap::create(ImageBitmap* bitmap, const IntRect& cropRect)
+{
+ IntRect normalizedCropRect = normalizeRect(cropRect);
+ return adoptRef(new ImageBitmap(bitmap, normalizedCropRect));
+}
+
+PassRefPtr<ImageBitmap> ImageBitmap::create(Image* image, const IntRect& cropRect)
+{
+ IntRect normalizedCropRect = normalizeRect(cropRect);
+ return adoptRef(new ImageBitmap(image, normalizedCropRect));
+}
+
+void ImageBitmap::notifyImageSourceChanged()
+{
+ m_bitmap = cropImage(m_imageElement->cachedImage()->image(), m_cropRect);
+ m_bitmapOffset = IntPoint();
+ m_imageElement = 0;
+}
+
+PassRefPtr<Image> ImageBitmap::bitmapImage() const
+{
+ ASSERT((m_imageElement || m_bitmap || !m_bitmapRect.width() || !m_bitmapRect.height()) && (!m_imageElement || !m_bitmap));
+ if (m_imageElement)
+ return m_imageElement->cachedImage()->image();
+ return m_bitmap;
+}
+
+}
diff --git a/chromium/third_party/WebKit/Source/core/frame/ImageBitmap.h b/chromium/third_party/WebKit/Source/core/frame/ImageBitmap.h
new file mode 100644
index 00000000000..8c9229d5102
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/ImageBitmap.h
@@ -0,0 +1,72 @@
+// Copyright 2013 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef ImageBitmap_h
+#define ImageBitmap_h
+
+#include "bindings/v8/ScriptWrappable.h"
+#include "core/html/HTMLImageElement.h"
+#include "platform/geometry/IntRect.h"
+#include "platform/graphics/Image.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefCounted.h"
+
+namespace WebCore {
+
+class HTMLCanvasElement;
+class HTMLVideoElement;
+class ImageData;
+
+class ImageBitmap : public RefCounted<ImageBitmap>, public ScriptWrappable, public ImageLoaderClient {
+
+public:
+ static PassRefPtr<ImageBitmap> create(HTMLImageElement*, const IntRect&);
+ static PassRefPtr<ImageBitmap> create(HTMLVideoElement*, const IntRect&);
+ static PassRefPtr<ImageBitmap> create(HTMLCanvasElement*, const IntRect&);
+ static PassRefPtr<ImageBitmap> create(ImageData*, const IntRect&);
+ static PassRefPtr<ImageBitmap> create(ImageBitmap*, const IntRect&);
+ static PassRefPtr<ImageBitmap> create(Image*, const IntRect&);
+
+ PassRefPtr<Image> bitmapImage() const;
+ PassRefPtr<HTMLImageElement> imageElement() const { return m_imageElement; }
+
+ IntRect bitmapRect() const { return m_bitmapRect; }
+ IntPoint bitmapOffset() const { return m_bitmapOffset; }
+
+ int width() const { return m_cropRect.width(); }
+ int height() const { return m_cropRect.height(); }
+ IntSize size() const { return m_cropRect.size(); }
+
+ virtual ~ImageBitmap();
+
+private:
+ ImageBitmap(HTMLImageElement*, const IntRect&);
+ ImageBitmap(HTMLVideoElement*, const IntRect&);
+ ImageBitmap(HTMLCanvasElement*, const IntRect&);
+ ImageBitmap(ImageData*, const IntRect&);
+ ImageBitmap(ImageBitmap*, const IntRect&);
+ ImageBitmap(Image*, const IntRect&);
+
+ // ImageLoaderClient
+ virtual void notifyImageSourceChanged();
+ virtual bool requestsHighLiveResourceCachePriority() { return true; }
+
+ // ImageBitmaps constructed from HTMLImageElements hold a reference to the HTMLImageElement until
+ // the image source changes.
+ RefPtr<HTMLImageElement> m_imageElement;
+ RefPtr<Image> m_bitmap;
+
+ IntRect m_bitmapRect; // The rect where the underlying Image should be placed in reference to the ImageBitmap.
+ IntRect m_cropRect;
+
+ // The offset by which the desired Image is stored internally.
+ // ImageBitmaps constructed from HTMLImageElements reference the entire ImageResource and may have a non-zero bitmap offset.
+ // ImageBitmaps not constructed from HTMLImageElements always pre-crop and store the image at (0, 0).
+ IntPoint m_bitmapOffset;
+
+};
+
+} // namespace WebCore
+
+#endif // ImageBitmap_h
diff --git a/chromium/third_party/WebKit/Source/core/frame/ImageBitmap.idl b/chromium/third_party/WebKit/Source/core/frame/ImageBitmap.idl
new file mode 100644
index 00000000000..903a2d7421f
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/ImageBitmap.idl
@@ -0,0 +1,9 @@
+// Copyright 2013 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+[
+] interface ImageBitmap {
+ readonly attribute long width;
+ readonly attribute long height;
+};
diff --git a/chromium/third_party/WebKit/Source/core/frame/ImageBitmapTest.cpp b/chromium/third_party/WebKit/Source/core/frame/ImageBitmapTest.cpp
new file mode 100644
index 00000000000..6a6626ae7ab
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/ImageBitmapTest.cpp
@@ -0,0 +1,209 @@
+/*
+ * Copyright (c) 2013, Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/frame/ImageBitmap.h"
+
+#include "SkPixelRef.h"
+#include "core/dom/Document.h"
+#include "core/fetch/ImageResource.h"
+#include "core/fetch/MemoryCache.h"
+#include "core/fetch/MockImageResourceClient.h"
+#include "core/fetch/ResourcePtr.h"
+#include "core/html/HTMLCanvasElement.h"
+#include "core/html/HTMLImageElement.h"
+#include "core/html/canvas/CanvasRenderingContext2D.h"
+#include "platform/graphics/BitmapImage.h"
+#include "platform/graphics/skia/NativeImageSkia.h"
+#include "platform/network/ResourceRequest.h"
+#include "wtf/OwnPtr.h"
+
+#include <gtest/gtest.h>
+
+namespace WebCore {
+
+class ImageBitmapTest : public ::testing::Test {
+protected:
+ virtual void SetUp()
+ {
+ m_bitmap.setConfig(SkBitmap::kARGB_8888_Config, 10, 10);
+ m_bitmap.allocPixels();
+ m_bitmap.eraseColor(0xFFFFFFFF);
+
+ m_bitmap2.setConfig(SkBitmap::kARGB_8888_Config, 5, 5);
+ m_bitmap2.allocPixels();
+ m_bitmap2.eraseColor(0xAAAAAAAA);
+
+ // Save the global memory cache to restore it upon teardown.
+ m_globalMemoryCache = adoptPtr(memoryCache());
+ // Create the test memory cache instance and hook it in.
+ m_testingMemoryCache = adoptPtr(new MemoryCache());
+ setMemoryCacheForTesting(m_testingMemoryCache.leakPtr());
+ }
+ virtual void TearDown()
+ {
+ // Regain the ownership of testing memory cache, so that it will be
+ // destroyed.
+ m_testingMemoryCache = adoptPtr(memoryCache());
+ // Yield the ownership of the global memory cache back.
+ setMemoryCacheForTesting(m_globalMemoryCache.leakPtr());
+ }
+
+ SkBitmap m_bitmap, m_bitmap2;
+ OwnPtr<MemoryCache> m_testingMemoryCache;
+ OwnPtr<MemoryCache> m_globalMemoryCache;
+};
+
+// Verifies that the image resource held by an ImageBitmap is the same as the
+// one held by the HTMLImageElement.
+TEST_F(ImageBitmapTest, ImageResourceConsistency)
+{
+ RefPtr<HTMLImageElement> imageElement = HTMLImageElement::create(*Document::create().get());
+ imageElement->setImageResource(new ImageResource(BitmapImage::create(NativeImageSkia::create(m_bitmap)).get()));
+
+ RefPtr<ImageBitmap> imageBitmapNoCrop = ImageBitmap::create(imageElement.get(), IntRect(0, 0, m_bitmap.width(), m_bitmap.height()));
+ RefPtr<ImageBitmap> imageBitmapInteriorCrop = ImageBitmap::create(imageElement.get(), IntRect(m_bitmap.width() / 2, m_bitmap.height() / 2, m_bitmap.width() / 2, m_bitmap.height() / 2));
+ RefPtr<ImageBitmap> imageBitmapExteriorCrop = ImageBitmap::create(imageElement.get(), IntRect(-m_bitmap.width() / 2, -m_bitmap.height() / 2, m_bitmap.width(), m_bitmap.height()));
+ RefPtr<ImageBitmap> imageBitmapOutsideCrop = ImageBitmap::create(imageElement.get(), IntRect(-m_bitmap.width(), -m_bitmap.height(), m_bitmap.width(), m_bitmap.height()));
+
+ ASSERT_EQ(imageBitmapNoCrop->bitmapImage().get(), imageElement->cachedImage()->image());
+ ASSERT_EQ(imageBitmapInteriorCrop->bitmapImage().get(), imageElement->cachedImage()->image());
+ ASSERT_EQ(imageBitmapExteriorCrop->bitmapImage().get(), imageElement->cachedImage()->image());
+
+ RefPtr<Image> emptyImage = imageBitmapOutsideCrop->bitmapImage();
+ ASSERT_NE(emptyImage.get(), imageElement->cachedImage()->image());
+}
+
+// Verifies that HTMLImageElements are given an elevated CacheLiveResourcePriority when used to construct an ImageBitmap.
+// ImageBitmaps that have crop rects outside of the bounds of the HTMLImageElement do not have elevated CacheLiveResourcePriority.
+TEST_F(ImageBitmapTest, ImageBitmapLiveResourcePriority)
+{
+ RefPtr<HTMLImageElement> imageNoCrop = HTMLImageElement::create(*Document::create().get());
+ ResourcePtr<ImageResource> cachedImageNoCrop = new ImageResource(BitmapImage::create(NativeImageSkia::create(m_bitmap)).get());
+ imageNoCrop->setImageResource(cachedImageNoCrop.get());
+
+ RefPtr<HTMLImageElement> imageInteriorCrop = HTMLImageElement::create(*Document::create().get());
+ ResourcePtr<ImageResource> cachedImageInteriorCrop = new ImageResource(BitmapImage::create(NativeImageSkia::create(m_bitmap)).get());
+ imageInteriorCrop->setImageResource(cachedImageInteriorCrop.get());
+
+ RefPtr<HTMLImageElement> imageExteriorCrop = HTMLImageElement::create(*Document::create().get());
+ ResourcePtr<ImageResource> cachedImageExteriorCrop = new ImageResource(BitmapImage::create(NativeImageSkia::create(m_bitmap)).get());
+ imageExteriorCrop->setImageResource(cachedImageExteriorCrop.get());
+
+ RefPtr<HTMLImageElement> imageOutsideCrop = HTMLImageElement::create(*Document::create().get());
+ ResourcePtr<ImageResource> cachedImageOutsideCrop = new ImageResource(BitmapImage::create(NativeImageSkia::create(m_bitmap)).get());
+ imageOutsideCrop->setImageResource(cachedImageOutsideCrop.get());
+
+ MockImageResourceClient mockClient1, mockClient2, mockClient3, mockClient4;
+ cachedImageNoCrop->addClient(&mockClient1);
+ cachedImageInteriorCrop->addClient(&mockClient2);
+ cachedImageExteriorCrop->addClient(&mockClient3);
+ cachedImageOutsideCrop->addClient(&mockClient4);
+
+ memoryCache()->add(cachedImageNoCrop.get());
+ memoryCache()->add(cachedImageInteriorCrop.get());
+ memoryCache()->add(cachedImageExteriorCrop.get());
+ memoryCache()->add(cachedImageOutsideCrop.get());
+ memoryCache()->insertInLiveDecodedResourcesList(cachedImageNoCrop.get());
+ memoryCache()->insertInLiveDecodedResourcesList(cachedImageInteriorCrop.get());
+ memoryCache()->insertInLiveDecodedResourcesList(cachedImageExteriorCrop.get());
+ memoryCache()->insertInLiveDecodedResourcesList(cachedImageOutsideCrop.get());
+
+ // HTMLImageElements should default to CacheLiveResourcePriorityLow.
+ ASSERT_EQ(imageNoCrop->cachedImage()->cacheLiveResourcePriority(), Resource::CacheLiveResourcePriorityLow);
+ ASSERT_EQ(imageInteriorCrop->cachedImage()->cacheLiveResourcePriority(), Resource::CacheLiveResourcePriorityLow);
+ ASSERT_EQ(imageExteriorCrop->cachedImage()->cacheLiveResourcePriority(), Resource::CacheLiveResourcePriorityLow);
+ ASSERT_EQ(imageOutsideCrop->cachedImage()->cacheLiveResourcePriority(), Resource::CacheLiveResourcePriorityLow);
+
+ RefPtr<ImageBitmap> imageBitmapInteriorCrop = ImageBitmap::create(imageInteriorCrop.get(), IntRect(m_bitmap.width() / 2, m_bitmap.height() / 2, m_bitmap.width(), m_bitmap.height()));
+ {
+ RefPtr<ImageBitmap> imageBitmapNoCrop = ImageBitmap::create(imageNoCrop.get(), IntRect(0, 0, m_bitmap.width(), m_bitmap.height()));
+ RefPtr<ImageBitmap> imageBitmapInteriorCrop2 = ImageBitmap::create(imageInteriorCrop.get(), IntRect(m_bitmap.width() / 2, m_bitmap.height() / 2, m_bitmap.width(), m_bitmap.height()));
+ RefPtr<ImageBitmap> imageBitmapExteriorCrop = ImageBitmap::create(imageExteriorCrop.get(), IntRect(-m_bitmap.width() / 2, -m_bitmap.height() / 2, m_bitmap.width(), m_bitmap.height()));
+ RefPtr<ImageBitmap> imageBitmapOutsideCrop = ImageBitmap::create(imageOutsideCrop.get(), IntRect(-m_bitmap.width(), -m_bitmap.height(), m_bitmap.width(), m_bitmap.height()));
+
+ // Images that are referenced by ImageBitmaps have CacheLiveResourcePriorityHigh.
+ ASSERT_EQ(imageNoCrop->cachedImage()->cacheLiveResourcePriority(), Resource::CacheLiveResourcePriorityHigh);
+ ASSERT_EQ(imageInteriorCrop->cachedImage()->cacheLiveResourcePriority(), Resource::CacheLiveResourcePriorityHigh);
+ ASSERT_EQ(imageExteriorCrop->cachedImage()->cacheLiveResourcePriority(), Resource::CacheLiveResourcePriorityHigh);
+
+ // ImageBitmaps that do not contain any of the source image do not elevate CacheLiveResourcePriority.
+ ASSERT_EQ(imageOutsideCrop->cachedImage()->cacheLiveResourcePriority(), Resource::CacheLiveResourcePriorityLow);
+ }
+
+ // CacheLiveResourcePriroity should return to CacheLiveResourcePriorityLow when no ImageBitmaps reference the image.
+ ASSERT_EQ(imageNoCrop->cachedImage()->cacheLiveResourcePriority(), Resource::CacheLiveResourcePriorityLow);
+ ASSERT_EQ(imageExteriorCrop->cachedImage()->cacheLiveResourcePriority(), Resource::CacheLiveResourcePriorityLow);
+ ASSERT_EQ(imageOutsideCrop->cachedImage()->cacheLiveResourcePriority(), Resource::CacheLiveResourcePriorityLow);
+
+ // There is still an ImageBitmap that references this image.
+ ASSERT_EQ(imageInteriorCrop->cachedImage()->cacheLiveResourcePriority(), Resource::CacheLiveResourcePriorityHigh);
+}
+
+// Verifies that ImageBitmaps constructed from HTMLImageElements hold a reference to the original Image if the HTMLImageElement src is changed.
+TEST_F(ImageBitmapTest, ImageBitmapSourceChanged)
+{
+ RefPtr<HTMLImageElement> image = HTMLImageElement::create(*Document::create().get());
+ ResourcePtr<ImageResource> originalImageResource = new ImageResource(BitmapImage::create(NativeImageSkia::create(m_bitmap)).get());
+ image->setImageResource(originalImageResource.get());
+
+ RefPtr<ImageBitmap> imageBitmap = ImageBitmap::create(image.get(), IntRect(0, 0, m_bitmap.width(), m_bitmap.height()));
+ ASSERT_EQ(imageBitmap->bitmapImage().get(), originalImageResource->image());
+
+ ResourcePtr<ImageResource> newImageResource = new ImageResource(BitmapImage::create(NativeImageSkia::create(m_bitmap2)).get());
+ image->setImageResource(newImageResource.get());
+
+ // The ImageBitmap should contain the same data as the original cached image but should no longer hold a reference.
+ ASSERT_NE(imageBitmap->bitmapImage().get(), originalImageResource->image());
+ ASSERT_EQ(imageBitmap->bitmapImage()->nativeImageForCurrentFrame()->bitmap().pixelRef()->pixels(),
+ originalImageResource->image()->nativeImageForCurrentFrame()->bitmap().pixelRef()->pixels());
+
+ ASSERT_NE(imageBitmap->bitmapImage().get(), newImageResource->image());
+ ASSERT_NE(imageBitmap->bitmapImage()->nativeImageForCurrentFrame()->bitmap().pixelRef()->pixels(),
+ newImageResource->image()->nativeImageForCurrentFrame()->bitmap().pixelRef()->pixels());
+}
+
+// Verifies that ImageBitmaps constructed from ImageBitmaps hold onto their own Image.
+TEST_F(ImageBitmapTest, ImageResourceLifetime)
+{
+ RefPtr<HTMLCanvasElement> canvasElement = HTMLCanvasElement::create(*Document::create().get());
+ canvasElement->setHeight(40);
+ canvasElement->setWidth(40);
+ RefPtr<ImageBitmap> imageBitmapDerived;
+ {
+ RefPtr<ImageBitmap> imageBitmapFromCanvas = ImageBitmap::create(canvasElement.get(), IntRect(0, 0, canvasElement->width(), canvasElement->height()));
+ imageBitmapDerived = ImageBitmap::create(imageBitmapFromCanvas.get(), IntRect(0, 0, 20, 20));
+ }
+ CanvasRenderingContext* context = canvasElement->getContext("2d");
+ TrackExceptionState exceptionState;
+ toCanvasRenderingContext2D(context)->drawImage(imageBitmapDerived.get(), 0, 0, exceptionState);
+}
+
+} // namespace
diff --git a/chromium/third_party/WebKit/Source/core/frame/Location.cpp b/chromium/third_party/WebKit/Source/core/frame/Location.cpp
new file mode 100644
index 00000000000..e38b2fde82e
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/Location.cpp
@@ -0,0 +1,252 @@
+/*
+ * Copyright (C) 2008, 2010 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/frame/Location.h"
+
+#include "bindings/v8/ExceptionState.h"
+#include "core/dom/DOMURLUtilsReadOnly.h"
+#include "core/dom/Document.h"
+#include "core/dom/ExceptionCode.h"
+#include "core/frame/DOMWindow.h"
+#include "core/frame/Frame.h"
+#include "core/loader/FrameLoader.h"
+#include "platform/weborigin/KURL.h"
+#include "platform/weborigin/SecurityOrigin.h"
+
+namespace WebCore {
+
+Location::Location(Frame* frame)
+ : DOMWindowProperty(frame)
+{
+ ScriptWrappable::init(this);
+}
+
+inline const KURL& Location::url() const
+{
+ ASSERT(m_frame);
+
+ const KURL& url = m_frame->document()->url();
+ if (!url.isValid())
+ return blankURL(); // Use "about:blank" while the page is still loading (before we have a frame).
+
+ return url;
+}
+
+String Location::href() const
+{
+ if (!m_frame)
+ return String();
+
+ return url().string();
+}
+
+String Location::protocol() const
+{
+ if (!m_frame)
+ return String();
+ return DOMURLUtilsReadOnly::protocol(url());
+}
+
+String Location::host() const
+{
+ if (!m_frame)
+ return String();
+ return DOMURLUtilsReadOnly::host(url());
+}
+
+String Location::hostname() const
+{
+ if (!m_frame)
+ return String();
+ return DOMURLUtilsReadOnly::hostname(url());
+}
+
+String Location::port() const
+{
+ if (!m_frame)
+ return String();
+ return DOMURLUtilsReadOnly::port(url());
+}
+
+String Location::pathname() const
+{
+ if (!m_frame)
+ return String();
+ return DOMURLUtilsReadOnly::pathname(url());
+}
+
+String Location::search() const
+{
+ if (!m_frame)
+ return String();
+ return DOMURLUtilsReadOnly::search(url());
+}
+
+String Location::origin() const
+{
+ if (!m_frame)
+ return String();
+ return DOMURLUtilsReadOnly::origin(url());
+}
+
+PassRefPtr<DOMStringList> Location::ancestorOrigins() const
+{
+ RefPtr<DOMStringList> origins = DOMStringList::create();
+ if (!m_frame)
+ return origins.release();
+ for (Frame* frame = m_frame->tree().parent(); frame; frame = frame->tree().parent())
+ origins->append(frame->document()->securityOrigin()->toString());
+ return origins.release();
+}
+
+String Location::hash() const
+{
+ if (!m_frame)
+ return String();
+
+ return DOMURLUtilsReadOnly::hash(url());
+}
+
+void Location::setHref(DOMWindow* activeWindow, DOMWindow* firstWindow, const String& url)
+{
+ if (!m_frame)
+ return;
+ setLocation(url, activeWindow, firstWindow);
+}
+
+void Location::setProtocol(DOMWindow* activeWindow, DOMWindow* firstWindow, const String& protocol, ExceptionState& exceptionState)
+{
+ if (!m_frame)
+ return;
+ KURL url = m_frame->document()->url();
+ if (!url.setProtocol(protocol)) {
+ exceptionState.throwDOMException(SyntaxError, "'" + protocol + "' is an invalid protocol.");
+ return;
+ }
+ setLocation(url.string(), activeWindow, firstWindow);
+}
+
+void Location::setHost(DOMWindow* activeWindow, DOMWindow* firstWindow, const String& host)
+{
+ if (!m_frame)
+ return;
+ KURL url = m_frame->document()->url();
+ url.setHostAndPort(host);
+ setLocation(url.string(), activeWindow, firstWindow);
+}
+
+void Location::setHostname(DOMWindow* activeWindow, DOMWindow* firstWindow, const String& hostname)
+{
+ if (!m_frame)
+ return;
+ KURL url = m_frame->document()->url();
+ url.setHost(hostname);
+ setLocation(url.string(), activeWindow, firstWindow);
+}
+
+void Location::setPort(DOMWindow* activeWindow, DOMWindow* firstWindow, const String& portString)
+{
+ if (!m_frame)
+ return;
+ KURL url = m_frame->document()->url();
+ url.setPort(portString);
+ setLocation(url.string(), activeWindow, firstWindow);
+}
+
+void Location::setPathname(DOMWindow* activeWindow, DOMWindow* firstWindow, const String& pathname)
+{
+ if (!m_frame)
+ return;
+ KURL url = m_frame->document()->url();
+ url.setPath(pathname);
+ setLocation(url.string(), activeWindow, firstWindow);
+}
+
+void Location::setSearch(DOMWindow* activeWindow, DOMWindow* firstWindow, const String& search)
+{
+ if (!m_frame)
+ return;
+ KURL url = m_frame->document()->url();
+ url.setQuery(search);
+ setLocation(url.string(), activeWindow, firstWindow);
+}
+
+void Location::setHash(DOMWindow* activeWindow, DOMWindow* firstWindow, const String& hash)
+{
+ if (!m_frame)
+ return;
+ KURL url = m_frame->document()->url();
+ String oldFragmentIdentifier = url.fragmentIdentifier();
+ String newFragmentIdentifier = hash;
+ if (hash[0] == '#')
+ newFragmentIdentifier = hash.substring(1);
+ url.setFragmentIdentifier(newFragmentIdentifier);
+ // Note that by parsing the URL and *then* comparing fragments, we are
+ // comparing fragments post-canonicalization, and so this handles the
+ // cases where fragment identifiers are ignored or invalid.
+ if (equalIgnoringNullity(oldFragmentIdentifier, url.fragmentIdentifier()))
+ return;
+ setLocation(url.string(), activeWindow, firstWindow);
+}
+
+void Location::assign(DOMWindow* activeWindow, DOMWindow* firstWindow, const String& url)
+{
+ if (!m_frame)
+ return;
+ setLocation(url, activeWindow, firstWindow);
+}
+
+void Location::replace(DOMWindow* activeWindow, DOMWindow* firstWindow, const String& url)
+{
+ if (!m_frame)
+ return;
+ // Note: We call DOMWindow::setLocation directly here because replace() always operates on the current frame.
+ m_frame->domWindow()->setLocation(url, activeWindow, firstWindow, LockHistoryAndBackForwardList);
+}
+
+void Location::reload(DOMWindow* activeWindow)
+{
+ if (!m_frame)
+ return;
+ if (protocolIsJavaScript(m_frame->document()->url()))
+ return;
+ m_frame->navigationScheduler().scheduleRefresh();
+}
+
+void Location::setLocation(const String& url, DOMWindow* activeWindow, DOMWindow* firstWindow)
+{
+ ASSERT(m_frame);
+ // We call findFrameForNavigation to handle the case of a seamless iframe correctly.
+ Frame* frame = m_frame->loader().findFrameForNavigation(String(), activeWindow->document());
+ if (!frame)
+ return;
+ frame->domWindow()->setLocation(url, activeWindow, firstWindow);
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/frame/Location.h b/chromium/third_party/WebKit/Source/core/frame/Location.h
new file mode 100644
index 00000000000..50b4b23cd87
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/Location.h
@@ -0,0 +1,85 @@
+/*
+ * Copyright (C) 2008, 2010 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef Location_h
+#define Location_h
+
+#include "bindings/v8/ScriptWrappable.h"
+#include "core/dom/DOMStringList.h"
+#include "core/frame/DOMWindowProperty.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefCounted.h"
+#include "wtf/text/WTFString.h"
+
+namespace WebCore {
+
+class DOMWindow;
+class ExceptionState;
+class Frame;
+class KURL;
+
+class Location : public ScriptWrappable, public RefCounted<Location>, public DOMWindowProperty {
+public:
+ static PassRefPtr<Location> create(Frame* frame) { return adoptRef(new Location(frame)); }
+
+ void setHref(DOMWindow* activeWindow, DOMWindow* firstWindow, const String&);
+ String href() const;
+
+ void assign(DOMWindow* activeWindow, DOMWindow* firstWindow, const String&);
+ void replace(DOMWindow* activeWindow, DOMWindow* firstWindow, const String&);
+ void reload(DOMWindow* activeWindow);
+
+ void setProtocol(DOMWindow* activeWindow, DOMWindow* firstWindow, const String&, ExceptionState&);
+ String protocol() const;
+ void setHost(DOMWindow* activeWindow, DOMWindow* firstWindow, const String&);
+ String host() const;
+ void setHostname(DOMWindow* activeWindow, DOMWindow* firstWindow, const String&);
+ String hostname() const;
+ void setPort(DOMWindow* activeWindow, DOMWindow* firstWindow, const String&);
+ String port() const;
+ void setPathname(DOMWindow* activeWindow, DOMWindow* firstWindow, const String&);
+ String pathname() const;
+ void setSearch(DOMWindow* activeWindow, DOMWindow* firstWindow, const String&);
+ String search() const;
+ void setHash(DOMWindow* activeWindow, DOMWindow* firstWindow, const String&);
+ String hash() const;
+ String origin() const;
+
+ PassRefPtr<DOMStringList> ancestorOrigins() const;
+
+private:
+ explicit Location(Frame*);
+
+ void setLocation(const String&, DOMWindow* activeWindow, DOMWindow* firstWindow);
+
+ const KURL& url() const;
+};
+
+} // namespace WebCore
+
+#endif // Location_h
diff --git a/chromium/third_party/WebKit/Source/core/frame/Location.idl b/chromium/third_party/WebKit/Source/core/frame/Location.idl
new file mode 100644
index 00000000000..5ce29901ece
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/Location.idl
@@ -0,0 +1,59 @@
+/*
+ * Copyright (C) 2008 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+[
+ CheckSecurity=Frame,
+] interface Location {
+ // |assign|, |replace|, and *writing* |href| do not require a security
+ // check, as they *change* the page, and thus these do not change any
+ // property of an *existing* document at a different origin.
+ // However, *reading* |href|, or accessing any component, is a security
+ // problem, since that allows tracking navigation.
+ [SetterCallWith=ActiveWindow&FirstWindow, DoNotCheckSecurity=Setter, Unforgeable] attribute DOMString href;
+
+ [CallWith=ActiveWindow&FirstWindow, DoNotCheckSecurity, Unforgeable, ReadOnly, PerWorldBindings, ActivityLogging=ForIsolatedWorlds] void assign(DOMString url);
+ [CallWith=ActiveWindow&FirstWindow, DoNotCheckSecurity, Unforgeable, ReadOnly, PerWorldBindings, ActivityLogging=ForIsolatedWorlds] void replace(DOMString url);
+ [CallWith=ActiveWindow, Unforgeable, ReadOnly] void reload();
+
+ // URI decomposition attributes
+ [SetterCallWith=ActiveWindow&FirstWindow, RaisesException=Setter] attribute DOMString protocol;
+ [SetterCallWith=ActiveWindow&FirstWindow] attribute DOMString host;
+ [SetterCallWith=ActiveWindow&FirstWindow] attribute DOMString hostname;
+ [SetterCallWith=ActiveWindow&FirstWindow] attribute DOMString port;
+ [SetterCallWith=ActiveWindow&FirstWindow] attribute DOMString pathname;
+ [SetterCallWith=ActiveWindow&FirstWindow] attribute DOMString search;
+ [SetterCallWith=ActiveWindow&FirstWindow] attribute DOMString hash;
+
+ readonly attribute DOMString origin;
+
+ readonly attribute DOMStringList ancestorOrigins;
+
+ [NotEnumerable, Unforgeable, ReadOnly, ImplementedAs=href] DOMString toString();
+ [NotEnumerable, Custom, Unforgeable, ReadOnly] any valueOf();
+};
+
diff --git a/chromium/third_party/WebKit/Source/core/frame/Navigator.cpp b/chromium/third_party/WebKit/Source/core/frame/Navigator.cpp
new file mode 100644
index 00000000000..37b0b6f4121
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/Navigator.cpp
@@ -0,0 +1,159 @@
+/*
+ * Copyright (C) 2000 Harri Porten (porten@kde.org)
+ * Copyright (c) 2000 Daniel Molkentin (molkentin@kde.org)
+ * Copyright (c) 2000 Stefan Schimanski (schimmi@kde.org)
+ * Copyright (C) 2003, 2004, 2005, 2006 Apple Computer, Inc.
+ * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "config.h"
+#include "core/frame/Navigator.h"
+
+#include "bindings/v8/ScriptController.h"
+#include "core/dom/Document.h"
+#include "core/frame/NavigatorID.h"
+#include "core/loader/CookieJar.h"
+#include "core/loader/FrameLoader.h"
+#include "core/frame/Frame.h"
+#include "core/frame/Settings.h"
+#include "core/plugins/DOMMimeTypeArray.h"
+#include "core/plugins/DOMPluginArray.h"
+#include "platform/Language.h"
+
+#ifndef WEBCORE_NAVIGATOR_PRODUCT_SUB
+#define WEBCORE_NAVIGATOR_PRODUCT_SUB "20030107"
+#endif // ifndef WEBCORE_NAVIGATOR_PRODUCT_SUB
+
+#ifndef WEBCORE_NAVIGATOR_VENDOR
+#define WEBCORE_NAVIGATOR_VENDOR "Google Inc."
+#endif // ifndef WEBCORE_NAVIGATOR_VENDOR
+
+#ifndef WEBCORE_NAVIGATOR_VENDOR_SUB
+#define WEBCORE_NAVIGATOR_VENDOR_SUB ""
+#endif // ifndef WEBCORE_NAVIGATOR_VENDOR_SUB
+
+namespace WebCore {
+
+Navigator::Navigator(Frame* frame)
+ : DOMWindowProperty(frame)
+{
+ ScriptWrappable::init(this);
+}
+
+Navigator::~Navigator()
+{
+}
+
+// If this function returns true, we need to hide the substring "4." that would otherwise
+// appear in the appVersion string. This is to avoid problems with old versions of a
+// library called OpenCube QuickMenu, which as of this writing is still being used on
+// sites such as nwa.com -- the library thinks Safari is Netscape 4 if we don't do this!
+static bool shouldHideFourDot(Frame* frame)
+{
+ const String* sourceURL = frame->script().sourceURL();
+ if (!sourceURL)
+ return false;
+ if (!(sourceURL->endsWith("/dqm_script.js") || sourceURL->endsWith("/dqm_loader.js") || sourceURL->endsWith("/tdqm_loader.js")))
+ return false;
+ Settings* settings = frame->settings();
+ if (!settings)
+ return false;
+ return settings->needsSiteSpecificQuirks();
+}
+
+String Navigator::appVersion() const
+{
+ if (!m_frame)
+ return String();
+ String appVersion = NavigatorID::appVersion(this);
+ if (shouldHideFourDot(m_frame))
+ appVersion.replace("4.", "4_");
+ return appVersion;
+}
+
+String Navigator::language() const
+{
+ return defaultLanguage();
+}
+
+String Navigator::productSub() const
+{
+ return WEBCORE_NAVIGATOR_PRODUCT_SUB;
+}
+
+String Navigator::vendor() const
+{
+ return WEBCORE_NAVIGATOR_VENDOR;
+}
+
+String Navigator::vendorSub() const
+{
+ return WEBCORE_NAVIGATOR_VENDOR_SUB;
+}
+
+String Navigator::userAgent() const
+{
+ // If the frame is already detached it no longer has a meaningful useragent.
+ if (!m_frame || !m_frame->page())
+ return String();
+
+ return m_frame->loader().userAgent(m_frame->document()->url());
+}
+
+DOMPluginArray* Navigator::plugins() const
+{
+ if (!m_plugins)
+ m_plugins = DOMPluginArray::create(m_frame);
+ return m_plugins.get();
+}
+
+DOMMimeTypeArray* Navigator::mimeTypes() const
+{
+ if (!m_mimeTypes)
+ m_mimeTypes = DOMMimeTypeArray::create(m_frame);
+ return m_mimeTypes.get();
+}
+
+bool Navigator::cookieEnabled() const
+{
+ if (!m_frame)
+ return false;
+
+ Settings* settings = m_frame->settings();
+ if (!settings || !settings->cookieEnabled())
+ return false;
+
+ return cookiesEnabled(m_frame->document());
+}
+
+bool Navigator::javaEnabled() const
+{
+ if (!m_frame || !m_frame->settings())
+ return false;
+
+ if (!m_frame->settings()->javaEnabled())
+ return false;
+
+ return true;
+}
+
+void Navigator::getStorageUpdates()
+{
+ // FIXME: Remove this method or rename to yieldForStorageUpdates.
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/frame/Navigator.h b/chromium/third_party/WebKit/Source/core/frame/Navigator.h
new file mode 100644
index 00000000000..0f289b3910e
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/Navigator.h
@@ -0,0 +1,71 @@
+/*
+ Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Library General Public
+ License as published by the Free Software Foundation; either
+ version 2 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Library General Public License for more details.
+
+ You should have received a copy of the GNU Library General Public License
+ along with this library; see the file COPYING.LIB. If not, write to
+ the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ Boston, MA 02110-1301, USA.
+*/
+
+#ifndef Navigator_h
+#define Navigator_h
+
+#include "bindings/v8/ScriptWrappable.h"
+#include "core/frame/DOMWindowProperty.h"
+#include "core/frame/NavigatorBase.h"
+#include "platform/Supplementable.h"
+#include "wtf/Forward.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefCounted.h"
+#include "wtf/RefPtr.h"
+
+namespace WebCore {
+
+class DOMMimeTypeArray;
+class DOMPluginArray;
+class Frame;
+class PluginData;
+
+typedef int ExceptionCode;
+
+class Navigator : public NavigatorBase, public ScriptWrappable, public RefCounted<Navigator>, public DOMWindowProperty, public Supplementable<Navigator> {
+public:
+ static PassRefPtr<Navigator> create(Frame* frame) { return adoptRef(new Navigator(frame)); }
+ virtual ~Navigator();
+
+ String appVersion() const;
+ String language() const;
+ DOMPluginArray* plugins() const;
+ DOMMimeTypeArray* mimeTypes() const;
+ bool cookieEnabled() const;
+ bool javaEnabled() const;
+
+ String productSub() const;
+ String vendor() const;
+ String vendorSub() const;
+
+ virtual String userAgent() const OVERRIDE;
+
+ // Relinquishes the storage lock, if one exists.
+ void getStorageUpdates();
+
+private:
+ explicit Navigator(Frame*);
+
+ mutable RefPtr<DOMPluginArray> m_plugins;
+ mutable RefPtr<DOMMimeTypeArray> m_mimeTypes;
+};
+
+}
+
+#endif
diff --git a/chromium/third_party/WebKit/Source/core/page/Navigator.idl b/chromium/third_party/WebKit/Source/core/frame/Navigator.idl
index 546e3e0f809..546e3e0f809 100644
--- a/chromium/third_party/WebKit/Source/core/page/Navigator.idl
+++ b/chromium/third_party/WebKit/Source/core/frame/Navigator.idl
diff --git a/chromium/third_party/WebKit/Source/core/page/NavigatorBase.h b/chromium/third_party/WebKit/Source/core/frame/NavigatorBase.h
index 38ae2660553..38ae2660553 100644
--- a/chromium/third_party/WebKit/Source/core/page/NavigatorBase.h
+++ b/chromium/third_party/WebKit/Source/core/frame/NavigatorBase.h
diff --git a/chromium/third_party/WebKit/Source/core/frame/NavigatorID.cpp b/chromium/third_party/WebKit/Source/core/frame/NavigatorID.cpp
new file mode 100644
index 00000000000..1b771dd1488
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/NavigatorID.cpp
@@ -0,0 +1,92 @@
+/*
+ * Copyright (C) 2008 Apple Inc. All Rights Reserved.
+ * Copyright (C) 2013 Samsung Electronics. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "NavigatorID.h"
+
+#include "core/frame/NavigatorBase.h"
+
+#if !defined(WEBCORE_NAVIGATOR_PLATFORM) && OS(POSIX) && !OS(MACOSX)
+#include "wtf/StdLibExtras.h"
+#include <sys/utsname.h>
+#endif
+
+#ifndef WEBCORE_NAVIGATOR_PRODUCT
+#define WEBCORE_NAVIGATOR_PRODUCT "Gecko"
+#endif // ifndef WEBCORE_NAVIGATOR_PRODUCT
+
+namespace WebCore {
+
+String NavigatorID::appName(const NavigatorBase*)
+{
+ return "Netscape";
+}
+
+String NavigatorID::appVersion(const NavigatorBase* navigator)
+{
+ // Version is everything in the user agent string past the "Mozilla/" prefix.
+ const String& agent = navigator->userAgent();
+ return agent.substring(agent.find('/') + 1);
+}
+
+String NavigatorID::userAgent(const NavigatorBase* navigator)
+{
+ return navigator->userAgent();
+}
+
+String NavigatorID::platform(const NavigatorBase*)
+{
+#if defined(WEBCORE_NAVIGATOR_PLATFORM)
+ return WEBCORE_NAVIGATOR_PLATFORM;
+#elif OS(MACOSX)
+ // Match Safari and Mozilla on Mac x86.
+ return "MacIntel";
+#elif OS(WIN)
+ // Match Safari and Mozilla on Windows.
+ return "Win32";
+#else // Unix-like systems
+ struct utsname osname;
+ DEFINE_STATIC_LOCAL(String, platformName, (uname(&osname) >= 0 ? String(osname.sysname) + String(" ") + String(osname.machine) : emptyString()));
+ return platformName;
+#endif
+}
+
+String NavigatorID::appCodeName(const NavigatorBase*)
+{
+ return "Mozilla";
+}
+
+String NavigatorID::product(const NavigatorBase*)
+{
+ return WEBCORE_NAVIGATOR_PRODUCT;
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/page/NavigatorID.h b/chromium/third_party/WebKit/Source/core/frame/NavigatorID.h
index 9e31d3100ee..9e31d3100ee 100644
--- a/chromium/third_party/WebKit/Source/core/page/NavigatorID.h
+++ b/chromium/third_party/WebKit/Source/core/frame/NavigatorID.h
diff --git a/chromium/third_party/WebKit/Source/core/page/NavigatorID.idl b/chromium/third_party/WebKit/Source/core/frame/NavigatorID.idl
index c581ad98bf2..c581ad98bf2 100644
--- a/chromium/third_party/WebKit/Source/core/page/NavigatorID.idl
+++ b/chromium/third_party/WebKit/Source/core/frame/NavigatorID.idl
diff --git a/chromium/third_party/WebKit/Source/core/frame/NavigatorOnLine.h b/chromium/third_party/WebKit/Source/core/frame/NavigatorOnLine.h
new file mode 100644
index 00000000000..5ae204d437c
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/NavigatorOnLine.h
@@ -0,0 +1,48 @@
+/*
+ * Copyright (C) 2013 Samsung Electronics. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef NavigatorOnLine_h
+#define NavigatorOnLine_h
+
+#include "core/page/NetworkStateNotifier.h"
+
+namespace WebCore {
+
+class NavigatorOnLine {
+public:
+ static bool onLine(void*)
+ {
+ return networkStateNotifier().onLine();
+ }
+};
+
+}
+
+#endif // NavigatorOnLine_h
diff --git a/chromium/third_party/WebKit/Source/core/page/NavigatorOnLine.idl b/chromium/third_party/WebKit/Source/core/frame/NavigatorOnLine.idl
index db4b08c1e0f..db4b08c1e0f 100644
--- a/chromium/third_party/WebKit/Source/core/page/NavigatorOnLine.idl
+++ b/chromium/third_party/WebKit/Source/core/frame/NavigatorOnLine.idl
diff --git a/chromium/third_party/WebKit/Source/core/frame/Screen.cpp b/chromium/third_party/WebKit/Source/core/frame/Screen.cpp
new file mode 100644
index 00000000000..18b22d63503
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/Screen.cpp
@@ -0,0 +1,123 @@
+/*
+ * Copyright (C) 2007 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+
+#include "config.h"
+#include "core/frame/Screen.h"
+
+#include "core/inspector/InspectorInstrumentation.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
+#include "core/page/Page.h"
+#include "core/frame/Settings.h"
+#include "platform/PlatformScreen.h"
+#include "platform/geometry/FloatRect.h"
+
+namespace WebCore {
+
+Screen::Screen(Frame* frame)
+ : DOMWindowProperty(frame)
+{
+ ScriptWrappable::init(this);
+}
+
+unsigned Screen::height() const
+{
+ if (!m_frame)
+ return 0;
+ Page* page = m_frame->page();
+ if (page && page->settings().reportScreenSizeInPhysicalPixelsQuirk())
+ return lroundf(screenRect(m_frame->view()).height() * page->deviceScaleFactor());
+ return static_cast<unsigned>(screenRect(m_frame->view()).height());
+}
+
+unsigned Screen::width() const
+{
+ if (!m_frame)
+ return 0;
+ Page* page = m_frame->page();
+ if (page && page->settings().reportScreenSizeInPhysicalPixelsQuirk())
+ return lroundf(screenRect(m_frame->view()).width() * page->deviceScaleFactor());
+ return static_cast<unsigned>(screenRect(m_frame->view()).width());
+}
+
+unsigned Screen::colorDepth() const
+{
+ if (!m_frame)
+ return 0;
+ return static_cast<unsigned>(screenDepth(m_frame->view()));
+}
+
+unsigned Screen::pixelDepth() const
+{
+ if (!m_frame)
+ return 0;
+ return static_cast<unsigned>(screenDepth(m_frame->view()));
+}
+
+int Screen::availLeft() const
+{
+ if (!m_frame)
+ return 0;
+ Page* page = m_frame->page();
+ if (page && page->settings().reportScreenSizeInPhysicalPixelsQuirk())
+ return lroundf(screenAvailableRect(m_frame->view()).x() * page->deviceScaleFactor());
+ return static_cast<int>(screenAvailableRect(m_frame->view()).x());
+}
+
+int Screen::availTop() const
+{
+ if (!m_frame)
+ return 0;
+ Page* page = m_frame->page();
+ if (page && page->settings().reportScreenSizeInPhysicalPixelsQuirk())
+ return lroundf(screenAvailableRect(m_frame->view()).y() * page->deviceScaleFactor());
+ return static_cast<int>(screenAvailableRect(m_frame->view()).y());
+}
+
+unsigned Screen::availHeight() const
+{
+ if (!m_frame)
+ return 0;
+ Page* page = m_frame->page();
+ if (page && page->settings().reportScreenSizeInPhysicalPixelsQuirk())
+ return lroundf(screenAvailableRect(m_frame->view()).height() * page->deviceScaleFactor());
+ return static_cast<unsigned>(screenAvailableRect(m_frame->view()).height());
+}
+
+unsigned Screen::availWidth() const
+{
+ if (!m_frame)
+ return 0;
+ Page* page = m_frame->page();
+ if (page && page->settings().reportScreenSizeInPhysicalPixelsQuirk())
+ return lroundf(screenAvailableRect(m_frame->view()).width() * page->deviceScaleFactor());
+ return static_cast<unsigned>(screenAvailableRect(m_frame->view()).width());
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/frame/Screen.h b/chromium/third_party/WebKit/Source/core/frame/Screen.h
new file mode 100644
index 00000000000..7b2036b677e
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/Screen.h
@@ -0,0 +1,61 @@
+/*
+ * Copyright (C) 2007 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+
+#ifndef Screen_h
+#define Screen_h
+
+#include "bindings/v8/ScriptWrappable.h"
+#include "core/frame/DOMWindowProperty.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefCounted.h"
+
+namespace WebCore {
+
+ class Frame;
+
+ class Screen : public ScriptWrappable, public RefCounted<Screen>, public DOMWindowProperty {
+ public:
+ static PassRefPtr<Screen> create(Frame *frame) { return adoptRef(new Screen(frame)); }
+
+ unsigned height() const;
+ unsigned width() const;
+ unsigned colorDepth() const;
+ unsigned pixelDepth() const;
+ int availLeft() const;
+ int availTop() const;
+ unsigned availHeight() const;
+ unsigned availWidth() const;
+
+ private:
+ explicit Screen(Frame*);
+ };
+
+} // namespace WebCore
+
+#endif // Screen_h
diff --git a/chromium/third_party/WebKit/Source/core/page/Screen.idl b/chromium/third_party/WebKit/Source/core/frame/Screen.idl
index 184a863c4d9..184a863c4d9 100644
--- a/chromium/third_party/WebKit/Source/core/page/Screen.idl
+++ b/chromium/third_party/WebKit/Source/core/frame/Screen.idl
diff --git a/chromium/third_party/WebKit/Source/core/page/SecurityPolicy.idl b/chromium/third_party/WebKit/Source/core/frame/SecurityPolicy.idl
index f5651dac093..f5651dac093 100644
--- a/chromium/third_party/WebKit/Source/core/page/SecurityPolicy.idl
+++ b/chromium/third_party/WebKit/Source/core/frame/SecurityPolicy.idl
diff --git a/chromium/third_party/WebKit/Source/core/frame/Settings.cpp b/chromium/third_party/WebKit/Source/core/frame/Settings.cpp
new file mode 100644
index 00000000000..b7d8d76b6ab
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/Settings.cpp
@@ -0,0 +1,167 @@
+/*
+ * Copyright (C) 2006, 2007, 2008, 2009, 2011, 2012 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/frame/Settings.h"
+
+#include "core/inspector/InspectorInstrumentation.h"
+#include "platform/scroll/ScrollbarTheme.h"
+
+namespace WebCore {
+
+// NOTEs
+// 1) EditingMacBehavior comprises builds on Mac;
+// 2) EditingWindowsBehavior comprises builds on Windows;
+// 3) EditingUnixBehavior comprises all unix-based systems, but Darwin/MacOS/Android (and then abusing the terminology);
+// 4) EditingAndroidBehavior comprises Android builds.
+// 99) MacEditingBehavior is used a fallback.
+static EditingBehaviorType editingBehaviorTypeForPlatform()
+{
+ return
+#if OS(MACOSX)
+ EditingMacBehavior
+#elif OS(WIN)
+ EditingWindowsBehavior
+#elif OS(ANDROID)
+ EditingAndroidBehavior
+#else // Rest of the UNIX-like systems
+ EditingUnixBehavior
+#endif
+ ;
+}
+
+static const bool defaultUnifiedTextCheckerEnabled = false;
+#if OS(MACOSX)
+static const bool defaultSmartInsertDeleteEnabled = true;
+#else
+static const bool defaultSmartInsertDeleteEnabled = false;
+#endif
+#if OS(WIN)
+static const bool defaultSelectTrailingWhitespaceEnabled = true;
+#else
+static const bool defaultSelectTrailingWhitespaceEnabled = false;
+#endif
+
+Settings::Settings()
+ : m_deviceScaleAdjustment(1.0f)
+#if HACK_FORCE_TEXT_AUTOSIZING_ON_DESKTOP
+ , m_textAutosizingWindowSizeOverride(320, 480)
+ , m_textAutosizingEnabled(true)
+#else
+ , m_textAutosizingEnabled(false)
+#endif
+ SETTINGS_INITIALIZER_LIST
+ , m_isScriptEnabled(false)
+ , m_openGLMultisamplingEnabled(false)
+{
+}
+
+PassOwnPtr<Settings> Settings::create()
+{
+ return adoptPtr(new Settings);
+}
+
+SETTINGS_SETTER_BODIES
+
+void Settings::setDelegate(SettingsDelegate* delegate)
+{
+ m_delegate = delegate;
+}
+
+void Settings::invalidate(SettingsDelegate::ChangeType changeType)
+{
+ if (m_delegate)
+ m_delegate->settingsChanged(changeType);
+}
+
+// This is a total hack and should be removed.
+Page* Settings::pageOfShame() const
+{
+ if (!m_delegate)
+ return 0;
+ return m_delegate->page();
+}
+
+void Settings::setTextAutosizingEnabled(bool textAutosizingEnabled)
+{
+ if (m_textAutosizingEnabled == textAutosizingEnabled)
+ return;
+
+ m_textAutosizingEnabled = textAutosizingEnabled;
+ invalidate(SettingsDelegate::StyleChange);
+}
+
+bool Settings::textAutosizingEnabled() const
+{
+ return InspectorInstrumentation::overrideTextAutosizing(pageOfShame(), m_textAutosizingEnabled);
+}
+
+// FIXME: Move to Settings.in once make_settings can understand IntSize.
+void Settings::setTextAutosizingWindowSizeOverride(const IntSize& textAutosizingWindowSizeOverride)
+{
+ if (m_textAutosizingWindowSizeOverride == textAutosizingWindowSizeOverride)
+ return;
+
+ m_textAutosizingWindowSizeOverride = textAutosizingWindowSizeOverride;
+ invalidate(SettingsDelegate::StyleChange);
+}
+
+void Settings::setDeviceScaleAdjustment(float deviceScaleAdjustment)
+{
+ m_deviceScaleAdjustment = deviceScaleAdjustment;
+ invalidate(SettingsDelegate::TextAutosizingChange);
+}
+
+float Settings::deviceScaleAdjustment() const
+{
+ return InspectorInstrumentation::overrideFontScaleFactor(pageOfShame(), m_deviceScaleAdjustment);
+}
+
+void Settings::setScriptEnabled(bool isScriptEnabled)
+{
+ m_isScriptEnabled = isScriptEnabled;
+ InspectorInstrumentation::scriptsEnabled(pageOfShame(), m_isScriptEnabled);
+}
+
+void Settings::setMockScrollbarsEnabled(bool flag)
+{
+ ScrollbarTheme::setMockScrollbarsEnabled(flag);
+}
+
+bool Settings::mockScrollbarsEnabled()
+{
+ return ScrollbarTheme::mockScrollbarsEnabled();
+}
+
+void Settings::setOpenGLMultisamplingEnabled(bool flag)
+{
+ if (m_openGLMultisamplingEnabled == flag)
+ return;
+
+ m_openGLMultisamplingEnabled = flag;
+ invalidate(SettingsDelegate::MultisamplingChange);
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/frame/Settings.h b/chromium/third_party/WebKit/Source/core/frame/Settings.h
new file mode 100644
index 00000000000..76f5ac5097f
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/Settings.h
@@ -0,0 +1,115 @@
+/*
+ * Copyright (C) 2003, 2006, 2007, 2008, 2009, 2011, 2012 Apple Inc. All rights reserved.
+ * (C) 2006 Graham Dennis (graham.dennis@gmail.com)
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef Settings_h
+#define Settings_h
+
+#include "SettingsMacros.h"
+#include "core/editing/EditingBehaviorTypes.h"
+#include "core/frame/SettingsDelegate.h"
+#include "platform/Timer.h"
+#include "platform/fonts/GenericFontFamilySettings.h"
+#include "platform/geometry/IntSize.h"
+#include "platform/weborigin/KURL.h"
+#include "wtf/HashSet.h"
+#include "wtf/RefCounted.h"
+
+namespace WebCore {
+
+class Page; // For inspector, remove after http://crbug.com/327476
+
+enum EditableLinkBehavior {
+ EditableLinkDefaultBehavior,
+ EditableLinkAlwaysLive,
+ EditableLinkOnlyLiveWithShiftKey,
+ EditableLinkLiveWhenNotFocused,
+ EditableLinkNeverLive
+};
+
+class Settings {
+ WTF_MAKE_NONCOPYABLE(Settings); WTF_MAKE_FAST_ALLOCATED;
+public:
+ static PassOwnPtr<Settings> create();
+
+ GenericFontFamilySettings& genericFontFamilySettings() { return m_genericFontFamilySettings; }
+
+ void setTextAutosizingEnabled(bool);
+ bool textAutosizingEnabled() const;
+
+ // Compensates for poor text legibility on mobile devices. This value is
+ // multiplied by the font scale factor when performing text autosizing of
+ // websites that do not set an explicit viewport description.
+ void setDeviceScaleAdjustment(float);
+ float deviceScaleAdjustment() const;
+
+ // Only set by Layout Tests, and only used if textAutosizingEnabled() returns true.
+ void setTextAutosizingWindowSizeOverride(const IntSize&);
+ const IntSize& textAutosizingWindowSizeOverride() const { return m_textAutosizingWindowSizeOverride; }
+
+ // Clients that execute script should call ScriptController::canExecuteScripts()
+ // instead of this function. ScriptController::canExecuteScripts() checks the
+ // HTML sandbox, plug-in sandboxing, and other important details.
+ bool isScriptEnabled() const { return m_isScriptEnabled; }
+ void setScriptEnabled(bool);
+
+ SETTINGS_GETTERS_AND_SETTERS
+
+ // FIXME: This does not belong here.
+ static void setMockScrollbarsEnabled(bool flag);
+ static bool mockScrollbarsEnabled();
+
+ // FIXME: naming_utilities.py isn't smart enough to handle OpenGL yet.
+ // It could handle "GL", but that seems a bit overly broad.
+ void setOpenGLMultisamplingEnabled(bool flag);
+ bool openGLMultisamplingEnabled() { return m_openGLMultisamplingEnabled; }
+
+ void setDelegate(SettingsDelegate*);
+
+private:
+ Settings();
+
+ void invalidate(SettingsDelegate::ChangeType);
+
+ // FIXME: pageOfShame() is a hack for the inspector code:
+ // http://crbug.com/327476
+ Page* pageOfShame() const;
+
+ SettingsDelegate* m_delegate;
+
+ GenericFontFamilySettings m_genericFontFamilySettings;
+ float m_deviceScaleAdjustment;
+ IntSize m_textAutosizingWindowSizeOverride;
+ bool m_textAutosizingEnabled : 1;
+
+ SETTINGS_MEMBER_VARIABLES
+
+ bool m_isScriptEnabled : 1;
+ bool m_openGLMultisamplingEnabled : 1;
+};
+
+} // namespace WebCore
+
+#endif // Settings_h
diff --git a/chromium/third_party/WebKit/Source/core/frame/Settings.in b/chromium/third_party/WebKit/Source/core/frame/Settings.in
new file mode 100644
index 00000000000..b45c89ad2cd
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/Settings.in
@@ -0,0 +1,289 @@
+# Defines properties which are available on the Settings object.
+#
+# Please think carefully before adding a new Setting. Some questions to
+# consider are:
+# - Should this be a RuntimeEnabledFeature instead? Settings are for things
+# which we support either values of at runtime. Features are set at renderer
+# process startup and are never changed. Features also tend to be set to a
+# value based on the platform or the stability of the code in question, where
+# as settings both codepaths need to be stable.
+# - How will you ensure test coverage of all relevant values of your setting?
+# - Is the default value appropriate for other platforms or ports which may
+# not be aware of your setting?
+# - Can your setting result in behavior differences observable to web
+# developers?
+# - Should this setting ideally be removed in the future? If so please file
+# a bug and reference it in the comments for your setting.
+#
+# One reason to add a Setting is to manage the risk associated with adding a
+# new feature. For example, we may choose to ship a new UI behavior or
+# performance optimization to ChromeOS users first (in order to gather feedback
+# and metrics on its use from the wild) before attempting to ship it to
+# Windows.
+#
+# FIXME: Add support for global settings.
+# FIXME: Add support for custom getters/setters.
+
+defaultTextEncodingName type=String
+editableLinkBehavior type=EditableLinkBehavior, initial=EditableLinkDefaultBehavior
+
+# Do not hide chars typed in password fields immediately, but let the last char stay
+# visible for N seconds, configured by the passwordEchoDurationInSeconds setting
+# FIXME: Enable automatically if passwordEchoDurationInSeconds is set to a positive value.
+passwordEchoEnabled initial=false
+
+# Configure how long the last char should say visible in seconds.
+passwordEchoDurationInSeconds type=double, initial=1
+
+# Sets the magnification value for validation message timer. If the
+# magnification value is N, a validation message disappears automatically after
+# <message length> * N / 1000 seconds. If N is equal to or less than 0, a
+# validation message doesn't disappears automaticaly.
+validationMessageTimerMagnification type=int, initial=50
+
+# Number of pixels below which 2D canvas is rendered in software
+# even if hardware acceleration is enabled.
+# Hardware acceleration is useful for large canvases where it can avoid the
+# pixel bandwidth between the CPU and GPU. But GPU acceleration comes at
+# a price - extra back-buffer and texture copy. Small canvases are also
+# widely used for stylized fonts. Anti-aliasing text in hardware at that
+# scale is generally slower. So below a certain size it is better to
+# draw canvas in software.
+minimumAccelerated2dCanvasSize type=int, initial=257*256
+
+# The layout width used with --enable-viewport when no viewport meta tag was defined.
+# FIXME: This should get the value from the @viewport UA sheet instead.
+layoutFallbackWidth type=int, initial=980
+
+minimumFontSize type=int, initial=0, invalidate=Style
+minimumLogicalFontSize type=int, initial=0, invalidate=Style
+defaultFontSize type=int, initial=0, invalidate=Style
+defaultFixedFontSize type=int, initial=0, invalidate=Style
+
+editingBehaviorType type=EditingBehaviorType, initial=editingBehaviorTypeForPlatform()
+
+caretBrowsingEnabled initial=false
+localStorageEnabled initial=false
+allowUniversalAccessFromFileURLs initial=true
+allowFileAccessFromFileURLs initial=true
+javaScriptCanOpenWindowsAutomatically initial=false
+supportsMultipleWindows initial=true
+javaScriptCanAccessClipboard initial=false
+shouldPrintBackgrounds initial=false
+shouldClearDocumentBackground initial=true
+
+textAreasAreResizable initial=false, invalidate=Style
+acceleratedCompositingEnabled initial=true, invalidate=Style
+
+# Debugging feature used for accelerated compositing layers.
+showRepaintCounter initial=false, invalidate=Style
+
+shrinksStandaloneImagesToFit initial=true
+
+# FIXME: Does this do anything now that we don't support page cache?
+pageCacheSupportsPlugins initial=false
+
+needsSiteSpecificQuirks initial=false
+offlineWebApplicationCacheEnabled initial=false
+usesEncodingDetector initial=false
+allowScriptsToCloseWindows initial=false
+acceleratedFiltersEnabled initial=false
+regionBasedColumnsEnabled initial=false
+
+# FIXME: This should really be disabled by default as it makes platforms that
+# don't support the feature download files they can't use by.
+# Leaving enabled for now to not change existing behavior.
+downloadableBinaryFontsEnabled initial=true
+
+xssAuditorEnabled initial=false
+unsafePluginPastingEnabled initial=true
+treatIPAddressAsDomain initial=false
+
+acceleratedCompositingFor3DTransformsEnabled initial=true
+acceleratedCompositingForVideoEnabled initial=true
+acceleratedCompositingForPluginsEnabled initial=true
+acceleratedCompositingForCanvasEnabled initial=true
+acceleratedCompositingForAnimationEnabled initial=true
+acceleratedCompositingForFiltersEnabled initial=false
+acceleratedCompositingForFixedPositionEnabled initial=false
+acceleratedCompositingForOverflowScrollEnabled initial=false
+acceleratedCompositingForTransitionEnabled initial=false
+acceleratedCompositingForFixedRootBackgroundEnabled initial=false
+
+forceCompositingMode initial=false
+
+# Works only in conjunction with forceCompositingMode.
+# crbug.com/304900 tracks removal once enabled on all platforms.
+acceleratedCompositingForScrollableFramesEnabled initial=false
+compositedScrollingForFramesEnabled initial=false
+
+# 3D canvas (WebGL) support.
+webGLEnabled initial=false
+
+webGLErrorsToConsoleEnabled initial=true
+privilegedWebGLExtensionsEnabled initial=false
+accelerated2dCanvasEnabled initial=false
+antialiased2dCanvasEnabled initial=true
+accelerated2dCanvasMSAASampleCount type=int, initial=0
+
+# WebAudio support.
+webAudioEnabled initial=false
+
+fullScreenEnabled initial=false
+asynchronousSpellCheckingEnabled initial=false
+memoryInfoEnabled initial=false
+
+hyperlinkAuditingEnabled initial=false
+allowDisplayOfInsecureContent initial=true
+allowRunningOfInsecureContent initial=true
+mediaPlaybackRequiresUserGesture initial=false
+mediaFullscreenRequiresUserGesture initial=true
+visualWordMovementEnabled initial=false
+shouldDisplaySubtitles initial=false
+shouldDisplayCaptions initial=false
+shouldDisplayTextDescriptions initial=false
+
+scrollingCoordinatorEnabled initial=false
+scrollAnimatorEnabled initial=true
+
+shouldRespectImageOrientation initial=false
+
+# Limited use by features which behave differently depending on the input
+# devices available. For example, the pointer and hover media queries.
+# Note that we need to be careful when basing behavior or UI on this -
+# just because a device is present doesn't mean the user cares about it
+# or uses it (i.e. Chromebook Pixel users generally don't want to give up
+# screen real estate just because they happen to have a touchscreen).
+deviceSupportsTouch initial=false
+deviceSupportsMouse initial=true
+
+# This value indicates the number of simultaneous multi-touch points supported
+# by the currently connected screen/digitizer that supports the most points.
+# From Pointer Events spec:
+# http://www.w3.org/TR/pointerevents/#widl-Navigator-maxTouchPoints
+maxTouchPoints type=int, initial=0
+
+# Whether touch gestures should be "fuzzed" to nearest touch targets.
+# It's expected that this is enabled everywhere by default, but it may be
+# disabled for testing purposes as the algorithm is not yet perfect.
+# crbug.com/304895 tracks removal once we're satisfied with the algorithm.
+touchAdjustmentEnabled initial=true
+
+# A mostly-stable performance optimization. crbug.com/304518 tracks removal.
+compositorTouchHitTesting initial=true
+
+fixedPositionCreatesStackingContext initial=false
+syncXHRInDocumentsEnabled initial=true
+cookieEnabled initial=true
+mediaEnabled initial=true
+DOMPasteAllowed initial=false
+
+threadedHTMLParser initial=false
+useThreadedHTMLParserForDataURLs initial=false
+
+applyPageScaleFactorInCompositor initial=false
+
+allowCustomScrollbarInMainFrame initial=true
+webSecurityEnabled initial=true
+
+# Special keyboard navigation mode intented for platforms with no
+# proper mouse or touch support, such as a TV controller with a remote.
+spatialNavigationEnabled initial=false
+
+# This setting adds a means to enable/disable touch initiated drag & drop. If
+# enabled, the user can initiate drag using long press.
+# crbug.com/304894 tracks removal once it's been enabled on all platforms.
+touchDragDropEnabled initial=false
+
+unifiedTextCheckerEnabled initial=defaultUnifiedTextCheckerEnabled
+
+# Some apps could have a default video poster if it is not set.
+defaultVideoPosterURL type=String
+
+smartInsertDeleteEnabled initial=defaultSmartInsertDeleteEnabled
+selectTrailingWhitespaceEnabled initial=defaultSelectTrailingWhitespaceEnabled
+
+selectionIncludesAltImageText initial=false
+useLegacyBackgroundSizeShorthandBehavior initial=false
+
+# This quirk is to maintain compatibility with Android apps built on
+# the Android SDK prior to and including version 18.
+# Presumably, this can be removed any time after 2015.
+# See http://crbug.com/282130.
+viewportMetaZeroValuesQuirk initial=false
+
+# Another Android SDK <= 18 quirk, removable 2015.
+# See http://crbug.com/295287
+ignoreMainFrameOverflowHiddenQuirk initial=false
+
+# Yet another Android SDK <= 18 quirk, removable 2015.
+# See http://crbug.com/305236
+reportScreenSizeInPhysicalPixelsQuirk initial=false
+
+# One more Android SDK <= 18 quirk, removable 2015.
+# See http://crbug.com/306548
+viewportMetaMergeContentQuirk initial=false
+
+# This quirk is to maintain compatibility with Android apps.
+# It will be possible to remove it once WebSettings.{get|set}UseWideViewPort
+# API function will be removed.
+# See http://crbug.com/288037.
+wideViewportQuirkEnabled initial=false
+
+# Touch based text selection and editing on desktop.
+# crbug.com/304873 tracks removal once it's been enabled on all platforms.
+touchEditingEnabled initial=false
+
+experimentalWebSocketEnabled initial=false
+
+# Settings for experimental desktop pinch-zoom support (with semantics
+# optimized for large screens). Pinch-zoom generally is implemented mainly
+# outside of blink (in the compositor) and doesn't require any settings.
+# These settings are for an experimental modification to how pinch-zoom
+# behaves. TODO(wjmaclean): link to design document.
+# crbug.com/304869 tracks removal.
+pinchVirtualViewportEnabled initial=false
+useSolidColorScrollbars initial=false
+
+mainFrameClipsContent initial=true
+
+# Enable decoration shadow nodes to test password genration feature
+# crbug.com/114092. This flag should not be enabled for production.
+passwordGenerationDecorationEnabled initial=false
+
+
+# Presumably used by LayoutTests? Unclear.
+useWideViewport initial=true, invalidate=ViewportDescription
+loadWithOverviewMode initial=true, invalidate=ViewportDescription
+
+
+# Font scale factor for accessibility, applied as part of text autosizing.
+accessibilityFontScaleFactor type=double, initial=1.0, invalidate=TextAutosizing
+
+
+# Only set by Layout Tests.
+mediaTypeOverride type=String, initial="screen", invalidate=MediaType
+
+# loadsImagesAutomatically only suppresses the network load of
+# the image URL. A cached image will still be rendered if requested.
+loadsImagesAutomatically initial=false, invalidate=ImageLoading
+imagesEnabled initial=true, invalidate=ImageLoading
+
+javaEnabled initial=false
+pluginsEnabled initial=false
+
+viewportEnabled initial=false, invalidate=ViewportDescription
+viewportMetaEnabled initial=false
+
+dnsPrefetchingEnabled initial=false, invalidate=DNSPrefetching
+
+touchEventEmulationEnabled initial=false
+
+
+# FIXME: This is a temporary flag and should be removed once
+# accelerated overflow scroll is ready (crbug.com/254111).
+compositorDrivenAcceleratedScrollingEnabled initial=false
+
+# FIXME: This is a temporary flag and should be removed
+# when squashing is ready. (crbug.com/261605)
+layerSquashingEnabled initial=false
diff --git a/chromium/third_party/WebKit/Source/core/frame/SettingsDelegate.cpp b/chromium/third_party/WebKit/Source/core/frame/SettingsDelegate.cpp
new file mode 100644
index 00000000000..47c5ce5e501
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/SettingsDelegate.cpp
@@ -0,0 +1,51 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/frame/SettingsDelegate.h"
+
+#include "core/frame/Settings.h"
+
+namespace WebCore {
+
+SettingsDelegate::SettingsDelegate(PassOwnPtr<Settings> settings)
+ : m_settings(settings)
+{
+ if (m_settings)
+ m_settings->setDelegate(this);
+}
+
+SettingsDelegate::~SettingsDelegate()
+{
+ if (m_settings)
+ m_settings->setDelegate(0);
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/frame/SettingsDelegate.h b/chromium/third_party/WebKit/Source/core/frame/SettingsDelegate.h
new file mode 100644
index 00000000000..2ea0bf2fe07
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/SettingsDelegate.h
@@ -0,0 +1,73 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SettingsDelegate_h
+#define SettingsDelegate_h
+
+#include "wtf/OwnPtr.h"
+#include "wtf/PassOwnPtr.h"
+
+namespace WebCore {
+
+class Page;
+class Settings;
+
+class SettingsDelegate {
+public:
+ explicit SettingsDelegate(PassOwnPtr<Settings>);
+ virtual ~SettingsDelegate();
+
+ Settings* settings() const { return m_settings.get(); }
+
+ // We currently use an enum instead of individual invalidation
+ // functions to make generating Settings.in slightly easier.
+ enum ChangeType {
+ StyleChange,
+ ViewportDescriptionChange,
+ MediaTypeChange,
+ DNSPrefetchingChange,
+ MultisamplingChange,
+ ImageLoadingChange,
+ TextAutosizingChange,
+ };
+
+ virtual void settingsChanged(ChangeType) = 0;
+
+ // FIXME: This is a hack until the Inspector code can
+ // be removed from Settings. http://crbug.com/327476
+ virtual Page* page() = 0;
+
+protected:
+ OwnPtr<Settings> const m_settings;
+};
+
+} // namespace WebCore
+
+#endif // SettingsDelegate_h
diff --git a/chromium/third_party/WebKit/Source/core/frame/SmartClip.cpp b/chromium/third_party/WebKit/Source/core/frame/SmartClip.cpp
new file mode 100644
index 00000000000..52f9b03dabd
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/SmartClip.cpp
@@ -0,0 +1,294 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/frame/SmartClip.h"
+
+#include "core/dom/ContainerNode.h"
+#include "core/dom/Document.h"
+#include "core/dom/NodeTraversal.h"
+#include "core/frame/DOMWindow.h"
+#include "core/frame/FrameView.h"
+#include "core/html/HTMLFrameOwnerElement.h"
+#include "core/page/Page.h"
+#include "wtf/text/StringBuilder.h"
+
+namespace WebCore {
+
+static IntRect applyScaleWithoutCollapsingToZero(const IntRect& rect, float scale)
+{
+ IntRect result = rect;
+ result.scale(scale);
+ if (rect.width() > 0 && !result.width())
+ result.setWidth(1);
+ if (rect.height() > 0 && !result.height())
+ result.setHeight(1);
+ return result;
+}
+
+static Node* nodeInsideFrame(Node* node)
+{
+ if (node->isFrameOwnerElement())
+ return toHTMLFrameOwnerElement(node)->contentDocument();
+ return 0;
+}
+
+// FIXME: SmartClipData is eventually returned via
+// SLookSmartClip.DataExtractionListener:
+// http://img-developer.samsung.com/onlinedocs/sms/com/samsung/android/sdk/look/...
+// however the original author of this change chose to use a string-serialization
+// format (presumably to make IPC easy?).
+// If we're going to use this as a Pickle format, we should at least have the
+// read/write code in one place!
+String SmartClipData::toString()
+{
+ if (!m_node)
+ return emptyString();
+
+ const UChar fieldSeparator = 0xFFFE;
+ const UChar rowSeparator = 0xFFFF;
+
+ StringBuilder result;
+ result.append(String::number(m_rect.x()));
+ result.append(fieldSeparator);
+ result.append(String::number(m_rect.y()));
+ result.append(fieldSeparator);
+ result.append(String::number(m_rect.width()));
+ result.append(fieldSeparator);
+ result.append(String::number(m_rect.height()));
+ result.append(fieldSeparator);
+ result.append(m_string);
+ result.append(rowSeparator);
+ return result.toString();
+}
+
+SmartClip::SmartClip(PassRefPtr<Frame> frame)
+ : m_frame(frame)
+{
+}
+
+SmartClipData SmartClip::dataForRect(const IntRect& cropRect)
+{
+ IntRect resizedCropRect = applyScaleWithoutCollapsingToZero(cropRect, 1 / pageScaleFactor());
+
+ Node* bestNode = findBestOverlappingNode(m_frame->document(), resizedCropRect);
+ if (!bestNode)
+ return SmartClipData();
+
+ if (Node* nodeFromFrame = nodeInsideFrame(bestNode)) {
+ // FIXME: This code only hit-tests a single iframe. It seems like we ought support nested frames.
+ if (Node* bestNodeInFrame = findBestOverlappingNode(nodeFromFrame, resizedCropRect))
+ bestNode = bestNodeInFrame;
+ }
+
+ Vector<Node*> hitNodes;
+ collectOverlappingChildNodes(bestNode, resizedCropRect, hitNodes);
+
+ if (hitNodes.isEmpty() || hitNodes.size() == bestNode->childNodeCount()) {
+ hitNodes.clear();
+ hitNodes.append(bestNode);
+ }
+
+ // Unite won't work with the empty rect, so we initialize to the first rect.
+ IntRect unitedRects = hitNodes[0]->pixelSnappedBoundingBox();
+ StringBuilder collectedText;
+ for (size_t i = 0; i < hitNodes.size(); ++i) {
+ collectedText.append(extractTextFromNode(hitNodes[i]));
+ unitedRects.unite(hitNodes[i]->pixelSnappedBoundingBox());
+ }
+
+ return SmartClipData(bestNode, convertRectToWindow(unitedRects), collectedText.toString());
+}
+
+float SmartClip::pageScaleFactor()
+{
+ return m_frame->page()->pageScaleFactor();
+}
+
+// This function is a bit of a mystery. If you understand what it does, please
+// consider adding a more descriptive name.
+Node* SmartClip::minNodeContainsNodes(Node* minNode, Node* newNode)
+{
+ if (!newNode)
+ return minNode;
+ if (!minNode)
+ return newNode;
+
+ IntRect minNodeRect = minNode->pixelSnappedBoundingBox();
+ IntRect newNodeRect = newNode->pixelSnappedBoundingBox();
+
+ Node* parentMinNode = minNode->parentNode();
+ Node* parentNewNode = newNode->parentNode();
+
+ if (minNodeRect.contains(newNodeRect)) {
+ if (parentMinNode && parentNewNode && parentNewNode->parentNode() == parentMinNode)
+ return parentMinNode;
+ return minNode;
+ }
+
+ if (newNodeRect.contains(minNodeRect)) {
+ if (parentMinNode && parentNewNode && parentMinNode->parentNode() == parentNewNode)
+ return parentNewNode;
+ return newNode;
+ }
+
+ // This loop appears to find the nearest ancestor of minNode (in DOM order)
+ // that contains the newNodeRect. It's very unclear to me why that's an
+ // interesting node to find. Presumably this loop will often just return
+ // the documentElement.
+ Node* node = minNode;
+ while (node) {
+ if (node->renderer()) {
+ IntRect nodeRect = node->pixelSnappedBoundingBox();
+ if (nodeRect.contains(newNodeRect)) {
+ return node;
+ }
+ }
+ node = node->parentNode();
+ }
+
+ return 0;
+}
+
+Node* SmartClip::findBestOverlappingNode(Node* rootNode, const IntRect& cropRect)
+{
+ if (!rootNode)
+ return 0;
+
+ IntRect resizedCropRect = rootNode->document().view()->windowToContents(cropRect);
+
+ Node* node = rootNode;
+ Node* minNode = 0;
+
+ while (node) {
+ IntRect nodeRect = node->pixelSnappedBoundingBox();
+
+ if (node->isElementNode() && equalIgnoringCase(toElement(node)->fastGetAttribute(HTMLNames::aria_hiddenAttr), "true")) {
+ node = NodeTraversal::nextSkippingChildren(*node, rootNode);
+ continue;
+ }
+
+ RenderObject* renderer = node->renderer();
+ if (renderer && !nodeRect.isEmpty()) {
+ if (renderer->isText()
+ || renderer->isRenderImage()
+ || node->isFrameOwnerElement()
+ || (renderer->style()->hasBackgroundImage() && !shouldSkipBackgroundImage(node))) {
+ if (resizedCropRect.intersects(nodeRect)) {
+ minNode = minNodeContainsNodes(minNode, node);
+ } else {
+ node = NodeTraversal::nextSkippingChildren(*node, rootNode);
+ continue;
+ }
+ }
+ }
+ node = NodeTraversal::next(*node, rootNode);
+ }
+
+ return minNode;
+}
+
+// This function appears to heuristically guess whether to include a background
+// image in the smart clip. It seems to want to include sprites created from
+// CSS background images but to skip actual backgrounds.
+bool SmartClip::shouldSkipBackgroundImage(Node* node)
+{
+ // Apparently we're only interested in background images on spans and divs.
+ if (!node->hasTagName(HTMLNames::spanTag) && !node->hasTagName(HTMLNames::divTag))
+ return true;
+
+ // This check actually makes a bit of sense. If you're going to sprite an
+ // image out of a CSS background, you're probably going to specify a height
+ // or a width. On the other hand, if we've got a legit background image,
+ // it's very likely the height or the width will be set to auto.
+ RenderObject* renderer = node->renderer();
+ if (renderer && (renderer->style()->logicalHeight().isAuto() || renderer->style()->logicalWidth().isAuto()))
+ return true;
+
+ return false;
+}
+
+void SmartClip::collectOverlappingChildNodes(Node* parentNode, const IntRect& cropRect, Vector<Node*>& hitNodes)
+{
+ if (!parentNode)
+ return;
+ IntRect resizedCropRect = parentNode->document().view()->windowToContents(cropRect);
+ for (Node* child = parentNode->firstChild(); child; child = child->nextSibling()) {
+ IntRect childRect = child->pixelSnappedBoundingBox();
+ if (resizedCropRect.intersects(childRect))
+ hitNodes.append(child);
+ }
+}
+
+IntRect SmartClip::convertRectToWindow(const IntRect& nodeRect)
+{
+ IntRect result = m_frame->document()->view()->contentsToWindow(nodeRect);
+ result.scale(pageScaleFactor());
+ return result;
+}
+
+String SmartClip::extractTextFromNode(Node* node)
+{
+ // Science has proven that no text nodes are ever positioned at y == -99999.
+ int prevYPos = -99999;
+
+ StringBuilder result;
+ for (Node* currentNode = node; currentNode; currentNode = NodeTraversal::next(*currentNode, node)) {
+ RenderStyle* style = currentNode->computedStyle();
+ if (style && style->userSelect() == SELECT_NONE)
+ continue;
+
+ if (Node* nodeFromFrame = nodeInsideFrame(currentNode))
+ result.append(extractTextFromNode(nodeFromFrame));
+
+ IntRect nodeRect = currentNode->pixelSnappedBoundingBox();
+ if (currentNode->renderer() && !nodeRect.isEmpty()) {
+ if (currentNode->isTextNode()) {
+ String nodeValue = currentNode->nodeValue();
+
+ // It's unclear why we blacklist solitary "\n" node values.
+ // Maybe we're trying to ignore <br> tags somehow?
+ if (nodeValue == "\n")
+ nodeValue = "";
+
+ if (nodeRect.y() != prevYPos) {
+ prevYPos = nodeRect.y();
+ result.append('\n');
+ }
+
+ result.append(nodeValue);
+ }
+ }
+ }
+
+ return result.toString();
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/frame/SmartClip.h b/chromium/third_party/WebKit/Source/core/frame/SmartClip.h
new file mode 100644
index 00000000000..7481b2a3879
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/SmartClip.h
@@ -0,0 +1,86 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SmartClip_h
+#define SmartClip_h
+
+#include "core/dom/Node.h"
+#include "core/frame/Frame.h"
+
+namespace WebCore {
+
+class SmartClipData {
+public:
+ SmartClipData()
+ {
+ }
+
+ SmartClipData(Node* node, IntRect rect, String string)
+ : m_node(node)
+ , m_rect(rect)
+ , m_string(string)
+ {
+ }
+
+ String toString();
+
+private:
+ RefPtr<Node> m_node;
+ IntRect m_rect;
+ String m_string;
+};
+
+// SmartClip implements support for the copy operation
+// with an S-Pen on Samsung devices. The behavior of this
+// class is quirky and poorly tested. It's approximately
+// trying to do a poor-mans implementation of columnar
+// selection followed by a copy operation.
+class SmartClip {
+public:
+ explicit SmartClip(PassRefPtr<Frame>);
+
+ SmartClipData dataForRect(const IntRect&);
+
+private:
+ float pageScaleFactor();
+
+ Node* minNodeContainsNodes(Node* minNode, Node* newNode);
+ Node* findBestOverlappingNode(Node*, const IntRect& cropRect);
+ bool shouldSkipBackgroundImage(Node*);
+ void collectOverlappingChildNodes(Node* parentNode, const IntRect& cropRect, Vector<Node*>& overlappingNodeInfoTable);
+ IntRect convertRectToWindow(const IntRect& nodeRect);
+ String extractTextFromNode(Node*);
+
+ RefPtr<Frame> m_frame;
+};
+
+} // namespace WebCore
+
+#endif // SmartClip_h
diff --git a/chromium/third_party/WebKit/Source/core/frame/SuspendableTimer.cpp b/chromium/third_party/WebKit/Source/core/frame/SuspendableTimer.cpp
new file mode 100644
index 00000000000..e3ffcf819ae
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/SuspendableTimer.cpp
@@ -0,0 +1,81 @@
+/*
+ * Copyright (C) 2008 Apple Inc. All Rights Reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "config.h"
+#include "core/frame/SuspendableTimer.h"
+
+namespace WebCore {
+
+SuspendableTimer::SuspendableTimer(ExecutionContext* context)
+ : ActiveDOMObject(context)
+ , m_nextFireInterval(0)
+ , m_repeatInterval(0)
+ , m_active(false)
+#if !ASSERT_DISABLED
+ , m_suspended(false)
+#endif
+{
+}
+
+SuspendableTimer::~SuspendableTimer()
+{
+}
+
+bool SuspendableTimer::hasPendingActivity() const
+{
+ return isActive();
+}
+
+void SuspendableTimer::stop()
+{
+ TimerBase::stop();
+}
+
+void SuspendableTimer::suspend()
+{
+#if !ASSERT_DISABLED
+ ASSERT(!m_suspended);
+ m_suspended = true;
+#endif
+ m_active = isActive();
+ if (m_active) {
+ m_nextFireInterval = nextUnalignedFireInterval();
+ m_repeatInterval = repeatInterval();
+ TimerBase::stop();
+ }
+}
+
+void SuspendableTimer::resume()
+{
+#if !ASSERT_DISABLED
+ ASSERT(m_suspended);
+ m_suspended = false;
+#endif
+ if (m_active)
+ start(m_nextFireInterval, m_repeatInterval);
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/frame/SuspendableTimer.h b/chromium/third_party/WebKit/Source/core/frame/SuspendableTimer.h
new file mode 100644
index 00000000000..3981ab7e077
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/SuspendableTimer.h
@@ -0,0 +1,59 @@
+/*
+ * Copyright (C) 2008 Apple Inc. All Rights Reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#ifndef SuspendableTimer_h
+#define SuspendableTimer_h
+
+#include "core/dom/ActiveDOMObject.h"
+#include "platform/Timer.h"
+
+namespace WebCore {
+
+class SuspendableTimer : public TimerBase, public ActiveDOMObject {
+public:
+ explicit SuspendableTimer(ExecutionContext*);
+ virtual ~SuspendableTimer();
+
+ // ActiveDOMObject
+ virtual bool hasPendingActivity() const;
+ virtual void stop();
+ virtual void suspend();
+ virtual void resume();
+
+private:
+ virtual void fired() = 0;
+
+ double m_nextFireInterval;
+ double m_repeatInterval;
+ bool m_active;
+#if !ASSERT_DISABLED
+ bool m_suspended;
+#endif
+};
+
+} // namespace WebCore
+
+#endif // SuspendableTimer_h
diff --git a/chromium/third_party/WebKit/Source/core/frame/UseCounter.cpp b/chromium/third_party/WebKit/Source/core/frame/UseCounter.cpp
new file mode 100644
index 00000000000..667e5f9313d
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/UseCounter.cpp
@@ -0,0 +1,732 @@
+
+/*
+ * Copyright (C) 2012 Google, Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY GOOGLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/frame/UseCounter.h"
+
+#include "core/css/CSSStyleSheet.h"
+#include "core/css/StyleSheetContents.h"
+#include "core/dom/Document.h"
+#include "core/dom/ExecutionContext.h"
+#include "core/frame/DOMWindow.h"
+#include "core/page/Page.h"
+#include "core/page/PageConsole.h"
+#include "public/platform/Platform.h"
+
+namespace WebCore {
+
+static int totalPagesMeasuredCSSSampleId() { return 1; }
+
+// FIXME : This mapping should be autogenerated. This function should
+// be moved to a separate file and a script run at build time
+// to detect new values in CSSPropertyID and add them to the
+// end of this function. This file would be checked in.
+// https://code.google.com/p/chromium/issues/detail?id=234940
+int UseCounter::mapCSSPropertyIdToCSSSampleIdForHistogram(int id)
+{
+ CSSPropertyID cssPropertyID = convertToCSSPropertyID(id);
+
+ switch (cssPropertyID) {
+ // Begin at 2, because 1 is reserved for totalPagesMeasuredCSSSampleId.
+ case CSSPropertyColor: return 2;
+ case CSSPropertyDirection: return 3;
+ case CSSPropertyDisplay: return 4;
+ case CSSPropertyFont: return 5;
+ case CSSPropertyFontFamily: return 6;
+ case CSSPropertyFontSize: return 7;
+ case CSSPropertyFontStyle: return 8;
+ case CSSPropertyFontVariant: return 9;
+ case CSSPropertyFontWeight: return 10;
+ case CSSPropertyTextRendering: return 11;
+ case CSSPropertyWebkitFontFeatureSettings: return 12;
+ case CSSPropertyFontKerning: return 13;
+ case CSSPropertyWebkitFontSmoothing: return 14;
+ case CSSPropertyWebkitFontVariantLigatures: return 15;
+ case CSSPropertyWebkitLocale: return 16;
+ case CSSPropertyWebkitTextOrientation: return 17;
+ case CSSPropertyWebkitWritingMode: return 18;
+ case CSSPropertyZoom: return 19;
+ case CSSPropertyLineHeight: return 20;
+ case CSSPropertyBackground: return 21;
+ case CSSPropertyBackgroundAttachment: return 22;
+ case CSSPropertyBackgroundClip: return 23;
+ case CSSPropertyBackgroundColor: return 24;
+ case CSSPropertyBackgroundImage: return 25;
+ case CSSPropertyBackgroundOrigin: return 26;
+ case CSSPropertyBackgroundPosition: return 27;
+ case CSSPropertyBackgroundPositionX: return 28;
+ case CSSPropertyBackgroundPositionY: return 29;
+ case CSSPropertyBackgroundRepeat: return 30;
+ case CSSPropertyBackgroundRepeatX: return 31;
+ case CSSPropertyBackgroundRepeatY: return 32;
+ case CSSPropertyBackgroundSize: return 33;
+ case CSSPropertyBorder: return 34;
+ case CSSPropertyBorderBottom: return 35;
+ case CSSPropertyBorderBottomColor: return 36;
+ case CSSPropertyBorderBottomLeftRadius: return 37;
+ case CSSPropertyBorderBottomRightRadius: return 38;
+ case CSSPropertyBorderBottomStyle: return 39;
+ case CSSPropertyBorderBottomWidth: return 40;
+ case CSSPropertyBorderCollapse: return 41;
+ case CSSPropertyBorderColor: return 42;
+ case CSSPropertyBorderImage: return 43;
+ case CSSPropertyBorderImageOutset: return 44;
+ case CSSPropertyBorderImageRepeat: return 45;
+ case CSSPropertyBorderImageSlice: return 46;
+ case CSSPropertyBorderImageSource: return 47;
+ case CSSPropertyBorderImageWidth: return 48;
+ case CSSPropertyBorderLeft: return 49;
+ case CSSPropertyBorderLeftColor: return 50;
+ case CSSPropertyBorderLeftStyle: return 51;
+ case CSSPropertyBorderLeftWidth: return 52;
+ case CSSPropertyBorderRadius: return 53;
+ case CSSPropertyBorderRight: return 54;
+ case CSSPropertyBorderRightColor: return 55;
+ case CSSPropertyBorderRightStyle: return 56;
+ case CSSPropertyBorderRightWidth: return 57;
+ case CSSPropertyBorderSpacing: return 58;
+ case CSSPropertyBorderStyle: return 59;
+ case CSSPropertyBorderTop: return 60;
+ case CSSPropertyBorderTopColor: return 61;
+ case CSSPropertyBorderTopLeftRadius: return 62;
+ case CSSPropertyBorderTopRightRadius: return 63;
+ case CSSPropertyBorderTopStyle: return 64;
+ case CSSPropertyBorderTopWidth: return 65;
+ case CSSPropertyBorderWidth: return 66;
+ case CSSPropertyBottom: return 67;
+ case CSSPropertyBoxShadow: return 68;
+ case CSSPropertyBoxSizing: return 69;
+ case CSSPropertyCaptionSide: return 70;
+ case CSSPropertyClear: return 71;
+ case CSSPropertyClip: return 72;
+ case CSSPropertyWebkitClipPath: return 73;
+ case CSSPropertyContent: return 74;
+ case CSSPropertyCounterIncrement: return 75;
+ case CSSPropertyCounterReset: return 76;
+ case CSSPropertyCursor: return 77;
+ case CSSPropertyEmptyCells: return 78;
+ case CSSPropertyFloat: return 79;
+ case CSSPropertyFontStretch: return 80;
+ case CSSPropertyHeight: return 81;
+ case CSSPropertyImageRendering: return 82;
+ case CSSPropertyLeft: return 83;
+ case CSSPropertyLetterSpacing: return 84;
+ case CSSPropertyListStyle: return 85;
+ case CSSPropertyListStyleImage: return 86;
+ case CSSPropertyListStylePosition: return 87;
+ case CSSPropertyListStyleType: return 88;
+ case CSSPropertyMargin: return 89;
+ case CSSPropertyMarginBottom: return 90;
+ case CSSPropertyMarginLeft: return 91;
+ case CSSPropertyMarginRight: return 92;
+ case CSSPropertyMarginTop: return 93;
+ case CSSPropertyMaxHeight: return 94;
+ case CSSPropertyMaxWidth: return 95;
+ case CSSPropertyMinHeight: return 96;
+ case CSSPropertyMinWidth: return 97;
+ case CSSPropertyOpacity: return 98;
+ case CSSPropertyOrphans: return 99;
+ case CSSPropertyOutline: return 100;
+ case CSSPropertyOutlineColor: return 101;
+ case CSSPropertyOutlineOffset: return 102;
+ case CSSPropertyOutlineStyle: return 103;
+ case CSSPropertyOutlineWidth: return 104;
+ case CSSPropertyOverflow: return 105;
+ case CSSPropertyOverflowWrap: return 106;
+ case CSSPropertyOverflowX: return 107;
+ case CSSPropertyOverflowY: return 108;
+ case CSSPropertyPadding: return 109;
+ case CSSPropertyPaddingBottom: return 110;
+ case CSSPropertyPaddingLeft: return 111;
+ case CSSPropertyPaddingRight: return 112;
+ case CSSPropertyPaddingTop: return 113;
+ case CSSPropertyPage: return 114;
+ case CSSPropertyPageBreakAfter: return 115;
+ case CSSPropertyPageBreakBefore: return 116;
+ case CSSPropertyPageBreakInside: return 117;
+ case CSSPropertyPointerEvents: return 118;
+ case CSSPropertyPosition: return 119;
+ case CSSPropertyQuotes: return 120;
+ case CSSPropertyResize: return 121;
+ case CSSPropertyRight: return 122;
+ case CSSPropertySize: return 123;
+ case CSSPropertySrc: return 124;
+ case CSSPropertySpeak: return 125;
+ case CSSPropertyTableLayout: return 126;
+ case CSSPropertyTabSize: return 127;
+ case CSSPropertyTextAlign: return 128;
+ case CSSPropertyTextDecoration: return 129;
+ case CSSPropertyTextIndent: return 130;
+ /* Removed CSSPropertyTextLineThrough - 131 */
+ case CSSPropertyTextLineThroughColor: return 132;
+ case CSSPropertyTextLineThroughMode: return 133;
+ case CSSPropertyTextLineThroughStyle: return 134;
+ case CSSPropertyTextLineThroughWidth: return 135;
+ case CSSPropertyTextOverflow: return 136;
+ /* Removed CSSPropertyTextOverline - 137 */
+ case CSSPropertyTextOverlineColor: return 138;
+ case CSSPropertyTextOverlineMode: return 139;
+ case CSSPropertyTextOverlineStyle: return 140;
+ case CSSPropertyTextOverlineWidth: return 141;
+ case CSSPropertyTextShadow: return 142;
+ case CSSPropertyTextTransform: return 143;
+ /* Removed CSSPropertyTextUnderline - 144 */
+ case CSSPropertyTextUnderlineColor: return 145;
+ case CSSPropertyTextUnderlineMode: return 146;
+ case CSSPropertyTextUnderlineStyle: return 147;
+ case CSSPropertyTextUnderlineWidth: return 148;
+ case CSSPropertyTop: return 149;
+ case CSSPropertyTransition: return 150;
+ case CSSPropertyTransitionDelay: return 151;
+ case CSSPropertyTransitionDuration: return 152;
+ case CSSPropertyTransitionProperty: return 153;
+ case CSSPropertyTransitionTimingFunction: return 154;
+ case CSSPropertyUnicodeBidi: return 155;
+ case CSSPropertyUnicodeRange: return 156;
+ case CSSPropertyVerticalAlign: return 157;
+ case CSSPropertyVisibility: return 158;
+ case CSSPropertyWhiteSpace: return 159;
+ case CSSPropertyWidows: return 160;
+ case CSSPropertyWidth: return 161;
+ case CSSPropertyWordBreak: return 162;
+ case CSSPropertyWordSpacing: return 163;
+ case CSSPropertyWordWrap: return 164;
+ case CSSPropertyZIndex: return 165;
+ case CSSPropertyWebkitAnimation: return 166;
+ case CSSPropertyWebkitAnimationDelay: return 167;
+ case CSSPropertyWebkitAnimationDirection: return 168;
+ case CSSPropertyWebkitAnimationDuration: return 169;
+ case CSSPropertyWebkitAnimationFillMode: return 170;
+ case CSSPropertyWebkitAnimationIterationCount: return 171;
+ case CSSPropertyWebkitAnimationName: return 172;
+ case CSSPropertyWebkitAnimationPlayState: return 173;
+ case CSSPropertyWebkitAnimationTimingFunction: return 174;
+ case CSSPropertyWebkitAppearance: return 175;
+ case CSSPropertyWebkitAspectRatio: return 176;
+ case CSSPropertyWebkitBackfaceVisibility: return 177;
+ case CSSPropertyWebkitBackgroundClip: return 178;
+ case CSSPropertyWebkitBackgroundComposite: return 179;
+ case CSSPropertyWebkitBackgroundOrigin: return 180;
+ case CSSPropertyWebkitBackgroundSize: return 181;
+ case CSSPropertyWebkitBorderAfter: return 182;
+ case CSSPropertyWebkitBorderAfterColor: return 183;
+ case CSSPropertyWebkitBorderAfterStyle: return 184;
+ case CSSPropertyWebkitBorderAfterWidth: return 185;
+ case CSSPropertyWebkitBorderBefore: return 186;
+ case CSSPropertyWebkitBorderBeforeColor: return 187;
+ case CSSPropertyWebkitBorderBeforeStyle: return 188;
+ case CSSPropertyWebkitBorderBeforeWidth: return 189;
+ case CSSPropertyWebkitBorderEnd: return 190;
+ case CSSPropertyWebkitBorderEndColor: return 191;
+ case CSSPropertyWebkitBorderEndStyle: return 192;
+ case CSSPropertyWebkitBorderEndWidth: return 193;
+ case CSSPropertyWebkitBorderFit: return 194;
+ case CSSPropertyWebkitBorderHorizontalSpacing: return 195;
+ case CSSPropertyWebkitBorderImage: return 196;
+ case CSSPropertyWebkitBorderRadius: return 197;
+ case CSSPropertyWebkitBorderStart: return 198;
+ case CSSPropertyWebkitBorderStartColor: return 199;
+ case CSSPropertyWebkitBorderStartStyle: return 200;
+ case CSSPropertyWebkitBorderStartWidth: return 201;
+ case CSSPropertyWebkitBorderVerticalSpacing: return 202;
+ case CSSPropertyWebkitBoxAlign: return 203;
+ case CSSPropertyWebkitBoxDirection: return 204;
+ case CSSPropertyWebkitBoxFlex: return 205;
+ case CSSPropertyWebkitBoxFlexGroup: return 206;
+ case CSSPropertyWebkitBoxLines: return 207;
+ case CSSPropertyWebkitBoxOrdinalGroup: return 208;
+ case CSSPropertyWebkitBoxOrient: return 209;
+ case CSSPropertyWebkitBoxPack: return 210;
+ case CSSPropertyWebkitBoxReflect: return 211;
+ case CSSPropertyWebkitBoxShadow: return 212;
+ case CSSPropertyWebkitColumnAxis: return 214;
+ case CSSPropertyWebkitColumnBreakAfter: return 215;
+ case CSSPropertyWebkitColumnBreakBefore: return 216;
+ case CSSPropertyWebkitColumnBreakInside: return 217;
+ case CSSPropertyWebkitColumnCount: return 218;
+ case CSSPropertyWebkitColumnGap: return 219;
+ case CSSPropertyWebkitColumnProgression: return 220;
+ case CSSPropertyWebkitColumnRule: return 221;
+ case CSSPropertyWebkitColumnRuleColor: return 222;
+ case CSSPropertyWebkitColumnRuleStyle: return 223;
+ case CSSPropertyWebkitColumnRuleWidth: return 224;
+ case CSSPropertyWebkitColumnSpan: return 225;
+ case CSSPropertyWebkitColumnWidth: return 226;
+ case CSSPropertyWebkitColumns: return 227;
+#if defined(ENABLE_CSS_BOX_DECORATION_BREAK) && ENABLE_CSS_BOX_DECORATION_BREAK
+ case CSSPropertyWebkitBoxDecorationBreak: return 228;
+#endif
+#if defined(ENABLE_CSS_FILTERS) && ENABLE_CSS_FILTERS
+ case CSSPropertyWebkitFilter: return 229;
+#endif
+ case CSSPropertyAlignContent: return 230;
+ case CSSPropertyAlignItems: return 231;
+ case CSSPropertyAlignSelf: return 232;
+ case CSSPropertyFlex: return 233;
+ case CSSPropertyFlexBasis: return 234;
+ case CSSPropertyFlexDirection: return 235;
+ case CSSPropertyFlexFlow: return 236;
+ case CSSPropertyFlexGrow: return 237;
+ case CSSPropertyFlexShrink: return 238;
+ case CSSPropertyFlexWrap: return 239;
+ case CSSPropertyJustifyContent: return 240;
+ case CSSPropertyWebkitFontSizeDelta: return 241;
+ case CSSPropertyGridDefinitionColumns: return 242;
+ case CSSPropertyGridDefinitionRows: return 243;
+ case CSSPropertyGridColumnStart: return 244;
+ case CSSPropertyGridColumnEnd: return 245;
+ case CSSPropertyGridRowStart: return 246;
+ case CSSPropertyGridRowEnd: return 247;
+ case CSSPropertyGridColumn: return 248;
+ case CSSPropertyGridRow: return 249;
+ case CSSPropertyGridAutoFlow: return 250;
+ case CSSPropertyWebkitHighlight: return 251;
+ case CSSPropertyWebkitHyphenateCharacter: return 252;
+ case CSSPropertyWebkitLineBoxContain: return 257;
+ case CSSPropertyWebkitLineAlign: return 258;
+ case CSSPropertyWebkitLineBreak: return 259;
+ case CSSPropertyWebkitLineClamp: return 260;
+ case CSSPropertyWebkitLineGrid: return 261;
+ case CSSPropertyWebkitLineSnap: return 262;
+ case CSSPropertyWebkitLogicalWidth: return 263;
+ case CSSPropertyWebkitLogicalHeight: return 264;
+ case CSSPropertyWebkitMarginAfterCollapse: return 265;
+ case CSSPropertyWebkitMarginBeforeCollapse: return 266;
+ case CSSPropertyWebkitMarginBottomCollapse: return 267;
+ case CSSPropertyWebkitMarginTopCollapse: return 268;
+ case CSSPropertyWebkitMarginCollapse: return 269;
+ case CSSPropertyWebkitMarginAfter: return 270;
+ case CSSPropertyWebkitMarginBefore: return 271;
+ case CSSPropertyWebkitMarginEnd: return 272;
+ case CSSPropertyWebkitMarginStart: return 273;
+ // CSSPropertyWebkitMarquee was 274.
+ // CSSPropertyInternalMarquee* were 275-279.
+ case CSSPropertyWebkitMask: return 280;
+ case CSSPropertyWebkitMaskBoxImage: return 281;
+ case CSSPropertyWebkitMaskBoxImageOutset: return 282;
+ case CSSPropertyWebkitMaskBoxImageRepeat: return 283;
+ case CSSPropertyWebkitMaskBoxImageSlice: return 284;
+ case CSSPropertyWebkitMaskBoxImageSource: return 285;
+ case CSSPropertyWebkitMaskBoxImageWidth: return 286;
+ case CSSPropertyWebkitMaskClip: return 287;
+ case CSSPropertyWebkitMaskComposite: return 288;
+ case CSSPropertyWebkitMaskImage: return 289;
+ case CSSPropertyWebkitMaskOrigin: return 290;
+ case CSSPropertyWebkitMaskPosition: return 291;
+ case CSSPropertyWebkitMaskPositionX: return 292;
+ case CSSPropertyWebkitMaskPositionY: return 293;
+ case CSSPropertyWebkitMaskRepeat: return 294;
+ case CSSPropertyWebkitMaskRepeatX: return 295;
+ case CSSPropertyWebkitMaskRepeatY: return 296;
+ case CSSPropertyWebkitMaskSize: return 297;
+ case CSSPropertyWebkitMaxLogicalWidth: return 298;
+ case CSSPropertyWebkitMaxLogicalHeight: return 299;
+ case CSSPropertyWebkitMinLogicalWidth: return 300;
+ case CSSPropertyWebkitMinLogicalHeight: return 301;
+ // WebkitNbspMode has been deleted, was return 302;
+ case CSSPropertyOrder: return 303;
+ case CSSPropertyWebkitPaddingAfter: return 304;
+ case CSSPropertyWebkitPaddingBefore: return 305;
+ case CSSPropertyWebkitPaddingEnd: return 306;
+ case CSSPropertyWebkitPaddingStart: return 307;
+ case CSSPropertyWebkitPerspective: return 308;
+ case CSSPropertyWebkitPerspectiveOrigin: return 309;
+ case CSSPropertyWebkitPerspectiveOriginX: return 310;
+ case CSSPropertyWebkitPerspectiveOriginY: return 311;
+ case CSSPropertyWebkitPrintColorAdjust: return 312;
+ case CSSPropertyWebkitRtlOrdering: return 313;
+ case CSSPropertyWebkitRubyPosition: return 314;
+ case CSSPropertyWebkitTextCombine: return 315;
+ case CSSPropertyWebkitTextDecorationsInEffect: return 316;
+ case CSSPropertyWebkitTextEmphasis: return 317;
+ case CSSPropertyWebkitTextEmphasisColor: return 318;
+ case CSSPropertyWebkitTextEmphasisPosition: return 319;
+ case CSSPropertyWebkitTextEmphasisStyle: return 320;
+ case CSSPropertyWebkitTextFillColor: return 321;
+ case CSSPropertyWebkitTextSecurity: return 322;
+ case CSSPropertyWebkitTextStroke: return 323;
+ case CSSPropertyWebkitTextStrokeColor: return 324;
+ case CSSPropertyWebkitTextStrokeWidth: return 325;
+ case CSSPropertyWebkitTransform: return 326;
+ case CSSPropertyWebkitTransformOrigin: return 327;
+ case CSSPropertyWebkitTransformOriginX: return 328;
+ case CSSPropertyWebkitTransformOriginY: return 329;
+ case CSSPropertyWebkitTransformOriginZ: return 330;
+ case CSSPropertyWebkitTransformStyle: return 331;
+ case CSSPropertyWebkitTransition: return 332;
+ case CSSPropertyWebkitTransitionDelay: return 333;
+ case CSSPropertyWebkitTransitionDuration: return 334;
+ case CSSPropertyWebkitTransitionProperty: return 335;
+ case CSSPropertyWebkitTransitionTimingFunction: return 336;
+ case CSSPropertyWebkitUserDrag: return 337;
+ case CSSPropertyWebkitUserModify: return 338;
+ case CSSPropertyWebkitUserSelect: return 339;
+ case CSSPropertyWebkitFlowInto: return 340;
+ case CSSPropertyWebkitFlowFrom: return 341;
+ case CSSPropertyWebkitRegionFragment: return 342;
+ case CSSPropertyWebkitRegionBreakAfter: return 343;
+ case CSSPropertyWebkitRegionBreakBefore: return 344;
+ case CSSPropertyWebkitRegionBreakInside: return 345;
+ case CSSPropertyShapeInside: return 346;
+ case CSSPropertyShapeOutside: return 347;
+ case CSSPropertyShapeMargin: return 348;
+ case CSSPropertyShapePadding: return 349;
+ case CSSPropertyWebkitWrapFlow: return 350;
+ case CSSPropertyWebkitWrapThrough: return 351;
+ // CSSPropertyWebkitWrap was 352.
+#if defined(ENABLE_TOUCH_EVENTS) && ENABLE_TOUCH_EVENTS
+ case CSSPropertyWebkitTapHighlightColor: return 353;
+#endif
+#if defined(ENABLE_DRAGGABLE_REGION) && ENABLE_DRAGGABLE_REGION
+ case CSSPropertyWebkitAppRegion: return 354;
+#endif
+ case CSSPropertyClipPath: return 355;
+ case CSSPropertyClipRule: return 356;
+ case CSSPropertyMask: return 357;
+ case CSSPropertyEnableBackground: return 358;
+ case CSSPropertyFilter: return 359;
+ case CSSPropertyFloodColor: return 360;
+ case CSSPropertyFloodOpacity: return 361;
+ case CSSPropertyLightingColor: return 362;
+ case CSSPropertyStopColor: return 363;
+ case CSSPropertyStopOpacity: return 364;
+ case CSSPropertyColorInterpolation: return 365;
+ case CSSPropertyColorInterpolationFilters: return 366;
+ case CSSPropertyColorProfile: return 367;
+ case CSSPropertyColorRendering: return 368;
+ case CSSPropertyFill: return 369;
+ case CSSPropertyFillOpacity: return 370;
+ case CSSPropertyFillRule: return 371;
+ case CSSPropertyMarker: return 372;
+ case CSSPropertyMarkerEnd: return 373;
+ case CSSPropertyMarkerMid: return 374;
+ case CSSPropertyMarkerStart: return 375;
+ case CSSPropertyMaskType: return 376;
+ case CSSPropertyShapeRendering: return 377;
+ case CSSPropertyStroke: return 378;
+ case CSSPropertyStrokeDasharray: return 379;
+ case CSSPropertyStrokeDashoffset: return 380;
+ case CSSPropertyStrokeLinecap: return 381;
+ case CSSPropertyStrokeLinejoin: return 382;
+ case CSSPropertyStrokeMiterlimit: return 383;
+ case CSSPropertyStrokeOpacity: return 384;
+ case CSSPropertyStrokeWidth: return 385;
+ case CSSPropertyAlignmentBaseline: return 386;
+ case CSSPropertyBaselineShift: return 387;
+ case CSSPropertyDominantBaseline: return 388;
+ case CSSPropertyGlyphOrientationHorizontal: return 389;
+ case CSSPropertyGlyphOrientationVertical: return 390;
+ case CSSPropertyKerning: return 391;
+ case CSSPropertyTextAnchor: return 392;
+ case CSSPropertyVectorEffect: return 393;
+ case CSSPropertyWritingMode: return 394;
+ // CSSPropertyWebkitSvgShadow has been removed, was return 395;
+#if defined(ENABLE_CURSOR_VISIBILITY) && ENABLE_CURSOR_VISIBILITY
+ case CSSPropertyWebkitCursorVisibility: return 396;
+#endif
+ // CSSPropertyImageOrientation has been removed, was return 397;
+ // CSSPropertyImageResolution has been removed, was return 398;
+#if defined(ENABLE_CSS_COMPOSITING) && ENABLE_CSS_COMPOSITING
+ case CSSPropertyWebkitBlendMode: return 399;
+ case CSSPropertyWebkitBackgroundBlendMode: return 400;
+#endif
+ case CSSPropertyTextDecorationLine: return 401;
+ case CSSPropertyTextDecorationStyle: return 402;
+ case CSSPropertyTextDecorationColor: return 403;
+ case CSSPropertyTextAlignLast: return 404;
+ case CSSPropertyTextUnderlinePosition: return 405;
+ case CSSPropertyMaxZoom: return 406;
+ case CSSPropertyMinZoom: return 407;
+ case CSSPropertyOrientation: return 408;
+ case CSSPropertyUserZoom: return 409;
+ // CSSPropertyWebkitDashboardRegion was 410.
+ // CSSPropertyWebkitOverflowScrolling was 411.
+ case CSSPropertyWebkitAppRegion: return 412;
+ case CSSPropertyWebkitFilter: return 413;
+ case CSSPropertyWebkitBoxDecorationBreak: return 414;
+ case CSSPropertyWebkitTapHighlightColor: return 415;
+ case CSSPropertyBufferedRendering: return 416;
+ case CSSPropertyGridAutoRows: return 417;
+ case CSSPropertyGridAutoColumns: return 418;
+ case CSSPropertyBackgroundBlendMode: return 419;
+ case CSSPropertyMixBlendMode: return 420;
+ case CSSPropertyTouchAction: return 421;
+ case CSSPropertyGridArea: return 422;
+ case CSSPropertyGridTemplate: return 423;
+ case CSSPropertyAnimation: return 424;
+ case CSSPropertyAnimationDelay: return 425;
+ case CSSPropertyAnimationDirection: return 426;
+ case CSSPropertyAnimationDuration: return 427;
+ case CSSPropertyAnimationFillMode: return 428;
+ case CSSPropertyAnimationIterationCount: return 429;
+ case CSSPropertyAnimationName: return 430;
+ case CSSPropertyAnimationPlayState: return 431;
+ case CSSPropertyAnimationTimingFunction: return 432;
+ case CSSPropertyObjectFit: return 433;
+ case CSSPropertyPaintOrder: return 434;
+ case CSSPropertyMaskSourceType: return 435;
+ case CSSPropertyIsolation: return 436;
+ case CSSPropertyObjectPosition: return 437;
+ case CSSPropertyInternalCallback: return 438;
+ case CSSPropertyShapeImageThreshold: return 439;
+ case CSSPropertyColumnFill: return 440;
+ case CSSPropertyTextJustify: return 441;
+ case CSSPropertyTouchActionDelay: return 442;
+
+ // Add new features above this line (don't change the assigned numbers of the existing
+ // items) and update maximumCSSSampleId() with the new maximum value.
+
+ // Internal properties should not be counted.
+ case CSSPropertyInternalMarqueeDirection:
+ case CSSPropertyInternalMarqueeIncrement:
+ case CSSPropertyInternalMarqueeRepetition:
+ case CSSPropertyInternalMarqueeSpeed:
+ case CSSPropertyInternalMarqueeStyle:
+ case CSSPropertyInvalid:
+ case CSSPropertyVariable:
+ ASSERT_NOT_REACHED();
+ return 0;
+ }
+
+ ASSERT_NOT_REACHED();
+ return 0;
+}
+
+static int maximumCSSSampleId() { return 442; }
+
+UseCounter::UseCounter()
+{
+ m_CSSFeatureBits.ensureSize(lastCSSProperty + 1);
+ m_CSSFeatureBits.clearAll();
+}
+
+UseCounter::~UseCounter()
+{
+ // We always log PageDestruction so that we have a scale for the rest of the features.
+ blink::Platform::current()->histogramEnumeration("WebCore.FeatureObserver", PageDestruction, NumberOfFeatures);
+
+ updateMeasurements();
+}
+
+void UseCounter::updateMeasurements()
+{
+ blink::Platform::current()->histogramEnumeration("WebCore.FeatureObserver", PageVisits, NumberOfFeatures);
+
+ if (m_countBits) {
+ for (unsigned i = 0; i < NumberOfFeatures; ++i) {
+ if (m_countBits->quickGet(i))
+ blink::Platform::current()->histogramEnumeration("WebCore.FeatureObserver", i, NumberOfFeatures);
+ }
+ // Clearing count bits is timing sensitive.
+ m_countBits->clearAll();
+ }
+
+ // FIXME: Sometimes this function is called more than once per page. The following
+ // bool guards against incrementing the page count when there are no CSS
+ // bits set. http://crbug.com/236262.
+ bool needsPagesMeasuredUpdate = false;
+ for (int i = firstCSSProperty; i <= lastCSSProperty; ++i) {
+ if (m_CSSFeatureBits.quickGet(i)) {
+ int cssSampleId = mapCSSPropertyIdToCSSSampleIdForHistogram(i);
+ blink::Platform::current()->histogramEnumeration("WebCore.FeatureObserver.CSSProperties", cssSampleId, maximumCSSSampleId());
+ needsPagesMeasuredUpdate = true;
+ }
+ }
+
+ if (needsPagesMeasuredUpdate)
+ blink::Platform::current()->histogramEnumeration("WebCore.FeatureObserver.CSSProperties", totalPagesMeasuredCSSSampleId(), maximumCSSSampleId());
+
+ m_CSSFeatureBits.clearAll();
+}
+
+void UseCounter::didCommitLoad()
+{
+ updateMeasurements();
+}
+
+void UseCounter::count(const Document& document, Feature feature)
+{
+ Page* page = document.page();
+ if (!page)
+ return;
+
+ ASSERT(page->useCounter().deprecationMessage(feature).isEmpty());
+ page->useCounter().recordMeasurement(feature);
+}
+
+void UseCounter::count(const DOMWindow* domWindow, Feature feature)
+{
+ ASSERT(domWindow);
+ if (!domWindow->document())
+ return;
+ count(*domWindow->document(), feature);
+}
+
+void UseCounter::countDeprecation(ExecutionContext* context, Feature feature)
+{
+ if (!context || !context->isDocument())
+ return;
+ UseCounter::countDeprecation(*toDocument(context), feature);
+}
+
+void UseCounter::countDeprecation(const DOMWindow* window, Feature feature)
+{
+ if (!window || !window->document())
+ return;
+ UseCounter::countDeprecation(*window->document(), feature);
+}
+
+void UseCounter::countDeprecation(const Document& document, Feature feature)
+{
+ Page* page = document.page();
+ if (!page)
+ return;
+
+ if (page->useCounter().recordMeasurement(feature)) {
+ ASSERT(!page->useCounter().deprecationMessage(feature).isEmpty());
+ page->console().addMessage(DeprecationMessageSource, WarningMessageLevel, page->useCounter().deprecationMessage(feature));
+ }
+}
+
+String UseCounter::deprecationMessage(Feature feature)
+{
+ switch (feature) {
+ // Content Security Policy
+ case PrefixedContentSecurityPolicy:
+ case PrefixedContentSecurityPolicyReportOnly:
+ return "The 'X-WebKit-CSP' headers are no longer supported. Please consider using the canonical 'Content-Security-Policy' header instead.";
+
+ // HTMLMediaElement
+ case PrefixedMediaGenerateKeyRequest:
+ return "'HTMLMediaElement.webkitGenerateKeyRequest()' is deprecated. Please use 'MediaKeys.createSession()' instead.";
+
+ // Quota
+ case StorageInfo:
+ return "'window.webkitStorageInfo' is deprecated. Please use 'navigator.webkitTemporaryStorage' or 'navigator.webkitPersistentStorage' instead.";
+
+ // Performance
+ case PrefixedPerformanceTimeline:
+ return "'window.performance.webkitGet*' methods have been deprecated. Please use the unprefixed 'performance.get*' methods instead.";
+ case PrefixedUserTiming:
+ return "'window.performance.webkit*' methods have been deprecated. Please use the unprefixed 'window.performance.*' methods instead.";
+
+ // Web Audio
+ case WebAudioLooping:
+ return "AudioBufferSourceNode 'looping' attribute is deprecated. Use 'loop' instead.";
+
+ case DocumentClear:
+ return "document.clear() is deprecated. This method doesn't do anything.";
+
+ case PrefixedTransitionMediaFeature:
+ return "The '(-webkit-transition)' media query feature is deprecated; please consider using the more exact conditional \"@supports('(transition-property: prop_name)')\" instead.";
+
+ // Web Components
+ case HTMLShadowElementOlderShadowRoot:
+ return "HTMLShadowElement.olderShadowRoot is deprecated.";
+
+ // HTML Media Capture
+ case CaptureAttributeAsEnum:
+ return "Using the 'capture' attribute as an enum is deprecated. Please use it as a boolean and specify the media types that should be accepted in the 'accept' attribute.";
+
+ // Keyboard Event (DOM Level 3)
+ case KeyboardEventKeyLocation:
+ return "'KeyboardEvent.keyLocation'' is deprecated. Please use 'KeyboardEvent.location' instead.";
+
+ case CaptureEvents:
+ return "captureEvents() is deprecated. This method doesn't do anything.";
+
+ case ReleaseEvents:
+ return "releaseEvents() is deprecated. This method doesn't do anything.";
+
+ case ConsoleMarkTimeline:
+ return "console.markTimeline is deprecated. Please use the console.timeStamp instead.";
+
+ case FileError:
+ return "FileError is deprecated. Please use the 'name' or 'message' attributes of DOMError rather than 'code'.";
+
+ case EventReturnValue:
+ return "event.returnValue is deprecated. Please use the standard event.preventDefault() instead.";
+
+ case ScrollTopBodyNotQuirksMode:
+ return "body.scrollTop is deprecated in strict mode. Please use 'documentElement.scrollTop' if in strict mode and 'body.scrollTop' only if in quirks mode.";
+
+ case ScrollLeftBodyNotQuirksMode:
+ return "body.scrollLeft is deprecated in strict mode. Please use 'documentElement.scrollLeft' if in strict mode and 'body.scrollLeft' only if in quirks mode.";
+
+ case ShowModalDialog:
+ return "Chromium is considering deprecating showModalDialog. Please use window.open and postMessage instead.";
+
+ case CSSStyleSheetInsertRuleOptionalArg:
+ return "Calling CSSStyleSheet.insertRule() with one argument is deprecated. Please pass the index argument as well: insertRule(x, 0).";
+
+ // Features that aren't deprecated don't have a deprecation message.
+ default:
+ return String();
+ }
+}
+
+void UseCounter::count(CSSParserContext context, CSSPropertyID feature)
+{
+ ASSERT(feature >= firstCSSProperty);
+ ASSERT(feature <= lastCSSProperty);
+ ASSERT(!isInternalProperty(feature));
+
+ if (!isUseCounterEnabledForMode(context.mode()))
+ return;
+
+ m_CSSFeatureBits.quickSet(feature);
+}
+
+void UseCounter::count(Feature feature)
+{
+ ASSERT(deprecationMessage(feature).isEmpty());
+ recordMeasurement(feature);
+}
+
+UseCounter* UseCounter::getFrom(const Document* document)
+{
+ if (document && document->page())
+ return &document->page()->useCounter();
+ return 0;
+}
+
+UseCounter* UseCounter::getFrom(const CSSStyleSheet* sheet)
+{
+ if (sheet)
+ return getFrom(sheet->contents());
+ return 0;
+}
+
+UseCounter* UseCounter::getFrom(const StyleSheetContents* sheetContents)
+{
+ // FIXME: We may want to handle stylesheets that have multiple owners
+ // http://crbug.com/242125
+ if (sheetContents && sheetContents->hasSingleOwnerNode())
+ return getFrom(sheetContents->singleOwnerDocument());
+ return 0;
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/frame/UseCounter.h b/chromium/third_party/WebKit/Source/core/frame/UseCounter.h
new file mode 100644
index 00000000000..4f0c2fde527
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/UseCounter.h
@@ -0,0 +1,338 @@
+/*
+ * Copyright (C) 2012 Google, Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY GOOGLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef UseCounter_h
+#define UseCounter_h
+
+#include "CSSPropertyNames.h"
+#include "wtf/BitVector.h"
+#include "wtf/Noncopyable.h"
+#include "wtf/OwnPtr.h"
+#include "wtf/PassOwnPtr.h"
+#include "wtf/text/WTFString.h"
+
+namespace WebCore {
+
+class CSSStyleSheet;
+class DOMWindow;
+class Document;
+class ExecutionContext;
+class StyleSheetContents;
+
+// UseCounter is used for counting the number of times features of
+// Blink are used on real web pages and help us know commonly
+// features are used and thus when it's safe to remove or change them.
+//
+// The Chromium Content layer controls what is done with this data.
+// For instance, in Google Chrome, these counts are submitted
+// anonymously through the Histogram recording system in Chrome
+// for users who opt-in to "Usage Statistics" submission
+// during their install of Google Chrome:
+// http://www.google.com/chrome/intl/en/privacy.html
+
+class UseCounter {
+ WTF_MAKE_NONCOPYABLE(UseCounter);
+public:
+ UseCounter();
+ ~UseCounter();
+
+ enum Feature {
+ PageDestruction,
+ LegacyNotifications,
+ MultipartMainResource,
+ PrefixedIndexedDB,
+ WorkerStart,
+ SharedWorkerStart,
+ LegacyWebAudio,
+ WebAudioStart,
+ PrefixedContentSecurityPolicy,
+ UnprefixedIndexedDB,
+ OpenWebDatabase,
+ UnusedSlot01, // Prior to 7/2013, we used this slot for LegacyHTMLNotifications.
+ LegacyTextNotifications,
+ UnprefixedRequestAnimationFrame,
+ PrefixedRequestAnimationFrame,
+ ContentSecurityPolicy,
+ ContentSecurityPolicyReportOnly,
+ PrefixedContentSecurityPolicyReportOnly,
+ PrefixedTransitionEndEvent,
+ UnprefixedTransitionEndEvent,
+ PrefixedAndUnprefixedTransitionEndEvent,
+ AutoFocusAttribute,
+ UnusedSlot02, // Prior to 4/2013, we used this slot for AutoSaveAttribute.
+ DataListElement,
+ FormAttribute,
+ IncrementalAttribute,
+ InputTypeColor,
+ InputTypeDate,
+ InputTypeDateTime,
+ InputTypeDateTimeFallback,
+ InputTypeDateTimeLocal,
+ InputTypeEmail,
+ InputTypeMonth,
+ InputTypeNumber,
+ InputTypeRange,
+ InputTypeSearch,
+ InputTypeTel,
+ InputTypeTime,
+ InputTypeURL,
+ InputTypeWeek,
+ InputTypeWeekFallback,
+ ListAttribute,
+ MaxAttribute,
+ MinAttribute,
+ PatternAttribute,
+ PlaceholderAttribute,
+ PrecisionAttribute,
+ PrefixedDirectoryAttribute,
+ PrefixedSpeechAttribute,
+ RequiredAttribute,
+ ResultsAttribute,
+ StepAttribute,
+ PageVisits,
+ HTMLMarqueeElement,
+ UnusedSlot03, // Removed, was tracking overflow: -webkit-marquee.
+ Reflection,
+ CursorVisibility, // Removed, was -webkit-cursor-visibility.
+ StorageInfo,
+ XFrameOptions,
+ XFrameOptionsSameOrigin,
+ XFrameOptionsSameOriginWithBadAncestorChain,
+ DeprecatedFlexboxWebContent,
+ DeprecatedFlexboxChrome,
+ DeprecatedFlexboxChromeExtension,
+ UnusedSlot04,
+ UnprefixedPerformanceTimeline,
+ PrefixedPerformanceTimeline,
+ UnprefixedUserTiming,
+ PrefixedUserTiming,
+ WindowEvent,
+ ContentSecurityPolicyWithBaseElement,
+ PrefixedMediaAddKey,
+ PrefixedMediaGenerateKeyRequest,
+ WebAudioLooping,
+ DocumentClear,
+ PrefixedTransitionMediaFeature,
+ SVGFontElement,
+ XMLDocument,
+ XSLProcessingInstruction,
+ XSLTProcessor,
+ SVGSwitchElement,
+ UnusedSlot05, // Removed, was document.webkitRegister
+ HTMLShadowElementOlderShadowRoot,
+ DocumentAll,
+ FormElement,
+ DemotedFormElement,
+ CaptureAttributeAsEnum,
+ ShadowDOMPrefixedPseudo,
+ ShadowDOMPrefixedCreateShadowRoot,
+ ShadowDOMPrefixedShadowRoot,
+ SVGAnimationElement,
+ KeyboardEventKeyLocation,
+ CaptureEvents,
+ ReleaseEvents,
+ CSSDisplayRunIn,
+ CSSDisplayCompact,
+ LineClamp,
+ SubFrameBeforeUnloadRegistered,
+ SubFrameBeforeUnloadFired,
+ CSSPseudoElementPrefixedDistributed,
+ TextReplaceWholeText,
+ PrefixedShadowRootConstructor,
+ ConsoleMarkTimeline,
+ CSSPseudoElementUserAgentCustomPseudo,
+ DocumentTypeEntities, // Removed from DOM4.
+ DocumentTypeInternalSubset, // Removed from DOM4.
+ DocumentTypeNotations, // Removed from DOM4.
+ ElementGetAttributeNode, // Removed from DOM4.
+ ElementSetAttributeNode, // Removed from DOM4.
+ ElementRemoveAttributeNode, // Removed from DOM4.
+ ElementGetAttributeNodeNS, // Removed from DOM4.
+ DocumentCreateAttribute, // Removed from DOM4.
+ DocumentCreateAttributeNS, // Removed from DOM4.
+ DocumentCreateCDATASection, // Removed from DOM4.
+ DocumentInputEncoding, // Removed from DOM4.
+ DocumentXMLEncoding, // Removed from DOM4.
+ DocumentXMLStandalone, // Removed from DOM4.
+ DocumentXMLVersion, // Removed from DOM4.
+ NodeIsSameNode, // Removed from DOM4.
+ NodeIsSupported, // Removed from DOM4.
+ NodeNamespaceURI, // Removed from DOM4.
+ NodePrefix, // Removed from DOM4.
+ NodeLocalName, // Removed from DOM4.
+ NavigatorProductSub,
+ NavigatorVendor,
+ NavigatorVendorSub,
+ FileError,
+ DocumentCharset, // Documented as IE extensions, from KHTML days.
+ PrefixedAnimationEndEvent,
+ UnprefixedAnimationEndEvent,
+ PrefixedAndUnprefixedAnimationEndEvent,
+ PrefixedAnimationStartEvent,
+ UnprefixedAnimationStartEvent,
+ PrefixedAndUnprefixedAnimationStartEvent,
+ PrefixedAnimationIterationEvent,
+ UnprefixedAnimationIterationEvent,
+ PrefixedAndUnprefixedAnimationIterationEvent,
+ EventReturnValue, // Legacy IE extension.
+ SVGSVGElement,
+ SVGAnimateColorElement,
+ InsertAdjacentText,
+ InsertAdjacentElement,
+ HasAttributes, // Removed from DOM4.
+ DOMSubtreeModifiedEvent,
+ DOMNodeInsertedEvent,
+ DOMNodeRemovedEvent,
+ DOMNodeRemovedFromDocumentEvent,
+ DOMNodeInsertedIntoDocumentEvent,
+ DOMCharacterDataModifiedEvent,
+ DocumentAllTags,
+ DocumentAllLegacyCall,
+ HTMLAppletElementLegacyCall,
+ HTMLEmbedElementLegacyCall,
+ HTMLObjectElementLegacyCall,
+ BeforeLoadEvent,
+ GetMatchedCSSRules,
+ SVGFontInCSS,
+ ScrollTopBodyNotQuirksMode,
+ ScrollLeftBodyNotQuirksMode,
+ AttributeIsId, // Removed in DOM4.
+ AttributeOwnerElement, // Removed in DOM4.
+ AttributeSetPrefix, // Attribute prefix is readonly in DOM4.
+ AttributeSpecified, // Removed in DOM4.
+ BeforeLoadEventInIsolatedWorld,
+ PrefixedAudioDecodedByteCount,
+ PrefixedVideoDecodedByteCount,
+ PrefixedVideoSupportsFullscreen,
+ PrefixedVideoDisplayingFullscreen,
+ PrefixedVideoEnterFullscreen,
+ PrefixedVideoExitFullscreen,
+ PrefixedVideoEnterFullScreen,
+ PrefixedVideoExitFullScreen,
+ PrefixedVideoDecodedFrameCount,
+ PrefixedVideoDroppedFrameCount,
+ SourceElementCandidate,
+ SourceElementNonMatchingMedia,
+ PrefixedElementRequestFullscreen,
+ PrefixedElementRequestFullScreen,
+ BarPropLocationbar,
+ BarPropMenubar,
+ BarPropPersonalbar,
+ BarPropScrollbars,
+ BarPropStatusbar,
+ BarPropToolbar,
+ InputTypeEmailMultiple,
+ InputTypeEmailMaxLength,
+ InputTypeEmailMultipleMaxLength,
+ TextTrackCueConstructor,
+ CSSStyleDeclarationPropertyName, // Removed in CSSOM.
+ CSSStyleDeclarationFloatPropertyName, // Pending removal in CSSOM.
+ InputTypeText,
+ InputTypeTextMaxLength,
+ InputTypePassword,
+ InputTypePasswordMaxLength,
+ SVGInstanceRoot,
+ ShowModalDialog,
+ PrefixedPageVisibility,
+ HTMLFrameElementLocation,
+ CSSStyleSheetInsertRuleOptionalArg, // Inconsistent with the specification and other browsers.
+ CSSWebkitRegionAtRule, // @region rule changed to ::region()
+ DocumentBeforeUnloadRegistered,
+ DocumentBeforeUnloadFired,
+ DocumentUnloadRegistered,
+ DocumentUnloadFired,
+ SVGLocatableNearestViewportElement,
+ SVGLocatableFarthestViewportElement,
+ IsIndexElement,
+ HTMLHeadElementProfile,
+ OverflowChangedEvent,
+ SVGPointMatrixTransform,
+ HTMLHtmlElementManifest,
+ DOMFocusInOutEvent,
+ FileGetLastModifiedDate,
+ HTMLElementInnerText,
+ HTMLElementOuterText,
+ ReplaceDocumentViaJavaScriptURL,
+ ElementSetAttributeNodeNS, // Removed from DOM4.
+ ElementPrefixedMatchesSelector,
+ DOMImplementationCreateCSSStyleSheet,
+ CSSStyleSheetRules,
+ CSSStyleSheetAddRule,
+ CSSStyleSheetRemoveRule,
+ // Add new features immediately above this line. Don't change assigned
+ // numbers of each items, and don't reuse unused slots.
+ NumberOfFeatures, // This enum value must be last.
+ };
+
+ // "count" sets the bit for this feature to 1. Repeated calls are ignored.
+ static void count(const Document&, Feature);
+ static void count(const DOMWindow*, Feature);
+ void count(CSSParserContext, CSSPropertyID);
+ void count(Feature);
+
+ // "countDeprecation" sets the bit for this feature to 1, and sends a deprecation
+ // warning to the console. Repeated calls are ignored.
+ //
+ // Be considerate to developers' consoles: features should only send deprecation warnings
+ // when we're actively interested in removing them from the platform.
+ static void countDeprecation(const DOMWindow*, Feature);
+ static void countDeprecation(ExecutionContext*, Feature);
+ static void countDeprecation(const Document&, Feature);
+ String deprecationMessage(Feature);
+
+ void didCommitLoad();
+
+ static UseCounter* getFrom(const Document*);
+ static UseCounter* getFrom(const CSSStyleSheet*);
+ static UseCounter* getFrom(const StyleSheetContents*);
+
+ static int mapCSSPropertyIdToCSSSampleIdForHistogram(int id);
+
+private:
+ bool recordMeasurement(Feature feature)
+ {
+ ASSERT(feature != PageDestruction); // PageDestruction is reserved as a scaling factor.
+ ASSERT(feature < NumberOfFeatures);
+ if (!m_countBits) {
+ m_countBits = adoptPtr(new BitVector(NumberOfFeatures));
+ m_countBits->clearAll();
+ }
+
+ if (m_countBits->quickGet(feature))
+ return false;
+
+ m_countBits->quickSet(feature);
+ return true;
+ }
+
+ void updateMeasurements();
+
+ OwnPtr<BitVector> m_countBits;
+ BitVector m_CSSFeatureBits;
+};
+
+} // namespace WebCore
+
+#endif // UseCounter_h
diff --git a/chromium/third_party/WebKit/Source/core/frame/WebKitPoint.idl b/chromium/third_party/WebKit/Source/core/frame/WebKitPoint.idl
new file mode 100644
index 00000000000..88b4be2a4ad
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/WebKitPoint.idl
@@ -0,0 +1,34 @@
+/*
+ * Copyright (C) 2009, 2010 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+[
+ CustomConstructor,
+ CustomConstructor(float x, float y),
+ ImplementedAs=DOMPoint,
+] interface WebKitPoint {
+ attribute float x;
+ attribute float y;
+};
+
diff --git a/chromium/third_party/WebKit/Source/core/frame/Window.idl b/chromium/third_party/WebKit/Source/core/frame/Window.idl
new file mode 100644
index 00000000000..632e3a26b45
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/Window.idl
@@ -0,0 +1,243 @@
+/*
+ * Copyright (C) 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
+ * Copyright (C) 2011 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+// HTML 5 draft spec:
+// http://www.w3.org/html/wg/drafts/html/master/browsers.html#window
+// FIXME: explain all uses of [DoNotCheckSecurity]
+[
+ CheckSecurity=Frame,
+ Custom=ToV8,
+ ImplementedAs=DOMWindow,
+] interface Window : EventTarget {
+ // DOM Level 0
+ [Replaceable] readonly attribute Screen screen;
+ [Replaceable] readonly attribute History history;
+ [Replaceable] readonly attribute BarProp locationbar;
+ [Replaceable] readonly attribute BarProp menubar;
+ [Replaceable] readonly attribute BarProp personalbar;
+ [Replaceable] readonly attribute BarProp scrollbars;
+ [Replaceable] readonly attribute BarProp statusbar;
+ [Replaceable] readonly attribute BarProp toolbar;
+ [Replaceable, PerWorldBindings, ActivityLogging=GetterForIsolatedWorlds] readonly attribute Navigator navigator;
+ [Replaceable] readonly attribute Navigator clientInformation;
+ [DoNotCheckSecurity, Unforgeable, Replaceable, PerWorldBindings, ActivityLogging=ForIsolatedWorlds, PutForwards=href] readonly attribute Location location;
+ [Custom, MeasureAs=WindowEvent, NotEnumerable] attribute Event event;
+
+ Selection getSelection();
+
+ [CheckSecurity=Node, Custom=Getter] readonly attribute Element frameElement;
+
+ [DoNotCheckSecurity, CallWith=ExecutionContext] void focus();
+ [DoNotCheckSecurity] void blur();
+ [DoNotCheckSecurity, CallWith=ExecutionContext] void close();
+
+ void print();
+ void stop();
+
+ [Custom] Window open(DOMString url,
+ DOMString name,
+ optional DOMString options);
+
+ [Custom] any showModalDialog(DOMString url,
+ optional any dialogArgs,
+ optional DOMString featureArgs);
+
+ void alert([Default=Undefined] optional DOMString message);
+ boolean confirm([Default=Undefined] optional DOMString message);
+ [TreatReturnedNullStringAs=Null] DOMString prompt([Default=Undefined] optional DOMString message,
+ [TreatNullAs=NullString, TreatUndefinedAs=NullString,Default=Undefined] optional DOMString defaultValue);
+
+ boolean find([Default=Undefined] optional DOMString string,
+ [Default=Undefined] optional boolean caseSensitive,
+ [Default=Undefined] optional boolean backwards,
+ [Default=Undefined] optional boolean wrap,
+ [Default=Undefined] optional boolean wholeWord,
+ [Default=Undefined] optional boolean searchInFrames,
+ [Default=Undefined] optional boolean showDialog);
+
+ [Replaceable] readonly attribute boolean offscreenBuffering;
+
+ [Replaceable] readonly attribute long outerHeight;
+ [Replaceable] readonly attribute long outerWidth;
+ [Replaceable] readonly attribute long innerHeight;
+ [Replaceable] readonly attribute long innerWidth;
+ [Replaceable] readonly attribute long screenX;
+ [Replaceable] readonly attribute long screenY;
+ [Replaceable] readonly attribute long screenLeft;
+ [Replaceable] readonly attribute long screenTop;
+ [Replaceable] readonly attribute long scrollX;
+ [Replaceable] readonly attribute long scrollY;
+ readonly attribute long pageXOffset;
+ readonly attribute long pageYOffset;
+
+ void scrollBy(long x, long y);
+ void scrollTo(long x, long y);
+ void scroll(long x, long y);
+ void moveBy([Default=Undefined] optional float x, [Default=Undefined] optional float y); // FIXME: this should take longs not floats.
+ void moveTo([Default=Undefined] optional float x, [Default=Undefined] optional float y); // FIXME: this should take longs not floats.
+ void resizeBy([Default=Undefined] optional float x, [Default=Undefined] optional float y); // FIXME: this should take longs not floats.
+ void resizeTo([Default=Undefined] optional float width, [Default=Undefined] optional float height); // FIXME: this should take longs not floats.
+
+ [DoNotCheckSecurity] readonly attribute boolean closed;
+
+ [Replaceable, DoNotCheckSecurity] readonly attribute unsigned long length;
+
+ attribute DOMString name;
+
+ attribute DOMString status;
+ attribute DOMString defaultStatus;
+ // This attribute is an alias of defaultStatus and is necessary for legacy uses.
+ [ImplementedAs=defaultStatus] attribute DOMString defaultstatus;
+
+ // Self referential attributes
+ [Replaceable, DoNotCheckSecurity] readonly attribute Window self;
+ [DoNotCheckSecurity, Unforgeable] readonly attribute Window window;
+ [Replaceable, DoNotCheckSecurity] readonly attribute Window frames;
+
+ [DoNotCheckSecurity, Custom=Setter] attribute Window opener;
+ [Replaceable, DoNotCheckSecurity] readonly attribute Window parent;
+ [DoNotCheckSecurity, Unforgeable] readonly attribute Window top;
+
+ // DOM Level 2 AbstractView Interface
+ readonly attribute Document document;
+
+ // CSSOM View Module
+ MediaQueryList matchMedia(DOMString query);
+
+ // styleMedia has been removed from the CSSOM View specification.
+ readonly attribute StyleMedia styleMedia;
+
+ // DOM Level 2 Style Interface
+ [PerWorldBindings] CSSStyleDeclaration getComputedStyle([Default=Undefined] optional Element element,
+ [TreatNullAs=NullString, TreatUndefinedAs=NullString,Default=Undefined] optional DOMString pseudoElement);
+
+ // WebKit extensions
+ CSSRuleList getMatchedCSSRules([Default=Undefined] optional Element element,
+ [TreatNullAs=NullString, TreatUndefinedAs=NullString,Default=Undefined] optional DOMString pseudoElement);
+
+ [Replaceable] readonly attribute double devicePixelRatio;
+
+ WebKitPoint webkitConvertPointFromPageToNode([Default=Undefined] optional Node node,
+ [Default=Undefined] optional WebKitPoint p);
+ WebKitPoint webkitConvertPointFromNodeToPage([Default=Undefined] optional Node node,
+ [Default=Undefined] optional WebKitPoint p);
+
+ [RuntimeEnabled=ApplicationCache, PerWorldBindings, ActivityLogging=GetterForIsolatedWorlds] readonly attribute ApplicationCache applicationCache;
+
+ [RuntimeEnabled=SessionStorage, PerWorldBindings, ActivityLogging=GetterForIsolatedWorlds, RaisesException=Getter] readonly attribute Storage sessionStorage;
+ [RuntimeEnabled=LocalStorage, PerWorldBindings, ActivityLogging=GetterForIsolatedWorlds, RaisesException=Getter] readonly attribute Storage localStorage;
+
+ // This is the interface orientation in degrees. Some examples are:
+ // 0 is straight up; -90 is when the device is rotated 90 clockwise;
+ // 90 is when rotated counter clockwise.
+ [Conditional=ORIENTATION_EVENTS] readonly attribute long orientation;
+
+ [Replaceable] readonly attribute Console console;
+
+ // cross-document messaging
+ [DoNotCheckSecurity, Custom, RaisesException] void postMessage(SerializedScriptValue message, DOMString targetOrigin, optional Array messagePorts);
+
+ [Replaceable] readonly attribute Performance performance;
+
+ [MeasureAs=UnprefixedRequestAnimationFrame] long requestAnimationFrame(RequestAnimationFrameCallback callback);
+ void cancelAnimationFrame(long id);
+ [MeasureAs=PrefixedRequestAnimationFrame] long webkitRequestAnimationFrame(RequestAnimationFrameCallback callback);
+ [ImplementedAs=cancelAnimationFrame] void webkitCancelAnimationFrame(long id);
+ [ImplementedAs=cancelAnimationFrame] void webkitCancelRequestAnimationFrame(long id); // This is a deprecated alias for webkitCancelAnimationFrame(). Remove this when removing vendor prefix.
+
+ [Replaceable] readonly attribute CSS CSS;
+
+ // Event handler attributes
+ [RuntimeEnabled=CSSAnimationUnprefixed] attribute EventHandler onanimationend;
+ [RuntimeEnabled=CSSAnimationUnprefixed] attribute EventHandler onanimationiteration;
+ [RuntimeEnabled=CSSAnimationUnprefixed] attribute EventHandler onanimationstart;
+ [RuntimeEnabled=DeviceMotion] attribute EventHandler ondevicemotion;
+ [RuntimeEnabled=DeviceOrientation] attribute EventHandler ondeviceorientation;
+ [Conditional=ORIENTATION_EVENTS] attribute EventHandler onorientationchange;
+ attribute EventHandler onsearch;
+ [RuntimeEnabled=Touch] attribute EventHandler ontouchcancel;
+ [RuntimeEnabled=Touch] attribute EventHandler ontouchend;
+ [RuntimeEnabled=Touch] attribute EventHandler ontouchmove;
+ [RuntimeEnabled=Touch] attribute EventHandler ontouchstart;
+ attribute EventHandler ontransitionend;
+ attribute EventHandler onwebkitanimationend;
+ attribute EventHandler onwebkitanimationiteration;
+ attribute EventHandler onwebkitanimationstart;
+ attribute EventHandler onwebkittransitionend;
+ [PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute EventHandler onwheel;
+
+ [DeprecateAs=CaptureEvents] void captureEvents();
+ [DeprecateAs=ReleaseEvents] void releaseEvents();
+
+ // Additional constructors.
+ attribute TransitionEventConstructor WebKitTransitionEvent;
+ [RuntimeEnabled=CSSAnimationUnprefixed] attribute WebKitAnimationEventConstructor AnimationEvent;
+ // Mozilla has a separate XMLDocument object for XML documents.
+ // We just use Document for this.
+ attribute DocumentConstructor XMLDocument;
+ attribute URLConstructor webkitURL; // FIXME: deprecate this.
+ attribute MutationObserverConstructor WebKitMutationObserver; // FIXME: Add metrics to determine when we can remove this.
+ attribute IDBCursorConstructor webkitIDBCursor;
+ attribute IDBDatabaseConstructor webkitIDBDatabase;
+ attribute IDBFactoryConstructor webkitIDBFactory;
+ attribute IDBIndexConstructor webkitIDBIndex;
+ attribute IDBKeyRangeConstructor webkitIDBKeyRange;
+ attribute IDBObjectStoreConstructor webkitIDBObjectStore;
+ attribute IDBRequestConstructor webkitIDBRequest;
+ attribute IDBTransactionConstructor webkitIDBTransaction;
+
+ // Constructors whose name does not match the interface name.
+ // FIXME: Remove these once [ImplementedAs] is used and once constructor names match interface names.
+ [RuntimeEnabled=MediaStream] attribute MediaStreamConstructor webkitMediaStream;
+ [Conditional=WEB_AUDIO, RuntimeEnabled=WebAudio] attribute AudioContextConstructor webkitAudioContext;
+ [Conditional=WEB_AUDIO, RuntimeEnabled=WebAudio] attribute OfflineAudioContextConstructor webkitOfflineAudioContext;
+ [RuntimeEnabled=PeerConnection] attribute RTCPeerConnectionConstructor webkitRTCPeerConnection;
+ [RuntimeEnabled=ScriptedSpeech] attribute SpeechGrammarConstructor webkitSpeechGrammar;
+ [RuntimeEnabled=ScriptedSpeech] attribute SpeechGrammarListConstructor webkitSpeechGrammarList;
+ [RuntimeEnabled=ScriptedSpeech] attribute SpeechRecognitionConstructor webkitSpeechRecognition;
+ [RuntimeEnabled=ScriptedSpeech] attribute SpeechRecognitionErrorConstructor webkitSpeechRecognitionError;
+ [RuntimeEnabled=ScriptedSpeech] attribute SpeechRecognitionEventConstructor webkitSpeechRecognitionEvent;
+ [Conditional=WEB_AUDIO] attribute PannerNodeConstructor webkitAudioPannerNode;
+
+ // Prefixed ShadowRoot constructor should be phased out eventually, but for the moment it must be always exposed.
+ // Unprefixed ShadowRoot constructor should be visible when the feature flag is enabled.
+ // FIXME: When it's ready to remove WebKitShadowRoot, get rid of both constructors from Window.idl and remove
+ // [NoInterfaceObject] from ShadowRoot interface definition.
+ [RuntimeEnabled=ShadowDOM] attribute ShadowRootConstructor ShadowRoot;
+ [MeasureAs=PrefixedShadowRootConstructor] attribute ShadowRootConstructor WebKitShadowRoot;
+
+ // window.toString() requires special handling in V8
+ [DoNotCheckSignature, DoNotCheckSecurity, Custom, NotEnumerable] DOMString toString();
+
+ [ImplementedAs=anonymousIndexedGetter, NotEnumerable] getter Window(unsigned long index);
+ [Custom, NotEnumerable] getter Window (DOMString name);
+};
+
+Window implements GlobalEventHandlers;
+Window implements ImageBitmapFactories;
+Window implements WindowBase64;
+Window implements WindowEventHandlers;
+Window implements WindowTimers;
diff --git a/chromium/third_party/WebKit/Source/core/frame/WindowBase64.idl b/chromium/third_party/WebKit/Source/core/frame/WindowBase64.idl
new file mode 100644
index 00000000000..134018ddc3e
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/WindowBase64.idl
@@ -0,0 +1,34 @@
+/*
+ * Copyright (C) 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
+ * Copyright (C) 2011 Google Inc. All rights reserved.
+ * Copyright (C) 2013 Samsung Electronics. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+[
+ ImplementedAs=DOMWindowBase64,
+ NoInterfaceObject,
+] interface WindowBase64 {
+ [RaisesException] DOMString atob(DOMString string);
+ [RaisesException] DOMString btoa(DOMString string);
+};
diff --git a/chromium/third_party/WebKit/Source/core/frame/WindowEventHandlers.idl b/chromium/third_party/WebKit/Source/core/frame/WindowEventHandlers.idl
new file mode 100644
index 00000000000..b7634ae98bf
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/WindowEventHandlers.idl
@@ -0,0 +1,47 @@
+/*
+ * Copyright (c) 2013, Opera Software ASA. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Opera Software ASA nor the names of its
+ * contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+[
+ NoInterfaceObject,
+ ImplementedAs=DOMWindowEventHandlers
+] interface WindowEventHandlers {
+ //attribute EventHandler onafterprint;
+ //attribute EventHandler onbeforeprint;
+ attribute EventHandler onbeforeunload;
+ attribute EventHandler onhashchange;
+ attribute EventHandler onmessage;
+ attribute EventHandler onoffline;
+ attribute EventHandler ononline;
+ attribute EventHandler onpagehide;
+ attribute EventHandler onpageshow;
+ attribute EventHandler onpopstate;
+ attribute EventHandler onresize;
+ attribute EventHandler onstorage;
+ attribute EventHandler onunload;
+};
diff --git a/chromium/third_party/WebKit/Source/core/page/WindowTimers.idl b/chromium/third_party/WebKit/Source/core/frame/WindowTimers.idl
index 744567d39e1..744567d39e1 100644
--- a/chromium/third_party/WebKit/Source/core/page/WindowTimers.idl
+++ b/chromium/third_party/WebKit/Source/core/frame/WindowTimers.idl
diff --git a/chromium/third_party/WebKit/Source/core/frame/animation/AnimationBase.cpp b/chromium/third_party/WebKit/Source/core/frame/animation/AnimationBase.cpp
new file mode 100644
index 00000000000..5dafb2de2fd
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/animation/AnimationBase.cpp
@@ -0,0 +1,585 @@
+/*
+ * Copyright (C) 2007, 2008, 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/frame/animation/AnimationBase.h"
+
+#include "core/frame/animation/AnimationControllerPrivate.h"
+#include "core/frame/animation/CompositeAnimation.h"
+#include "core/platform/animation/TimingFunction.h"
+#include "core/rendering/RenderBox.h"
+#include "platform/animation/AnimationUtilities.h"
+#include <algorithm>
+
+using namespace std;
+
+namespace WebCore {
+
+AnimationBase::AnimationBase(const CSSAnimationData* transition, RenderObject& renderer, CompositeAnimation* compAnim)
+ : m_animState(AnimationStateNew)
+ , m_isAccelerated(false)
+ , m_transformFunctionListValid(false)
+ , m_filterFunctionListsMatch(false)
+ , m_startTime(0)
+ , m_pauseTime(-1)
+ , m_requestedStartTime(0)
+ , m_totalDuration(-1)
+ , m_nextIterationDuration(-1)
+ , m_object(&renderer)
+ , m_animation(const_cast<CSSAnimationData*>(transition))
+ , m_compAnim(compAnim)
+{
+ // Compute the total duration
+ if (m_animation->iterationCount() > 0)
+ m_totalDuration = m_animation->duration() * m_animation->iterationCount();
+}
+
+void AnimationBase::setNeedsStyleRecalc(Node* node)
+{
+ if (node)
+ node->setNeedsStyleRecalc(LocalStyleChange);
+}
+
+double AnimationBase::duration() const
+{
+ return m_animation->duration();
+}
+
+bool AnimationBase::playStatePlaying() const
+{
+ return m_animation->playState() == AnimPlayStatePlaying;
+}
+
+void AnimationBase::updateStateMachine(AnimStateInput input, double param)
+{
+ if (!m_compAnim)
+ return;
+
+ // If we get AnimationStateInputRestartAnimation then we force a new animation, regardless of state.
+ if (input == AnimationStateInputMakeNew) {
+ if (m_animState == AnimationStateStartWaitStyleAvailable)
+ m_compAnim->animationController()->removeFromAnimationsWaitingForStyle(this);
+ m_animState = AnimationStateNew;
+ m_startTime = 0;
+ m_pauseTime = -1;
+ m_requestedStartTime = 0;
+ m_nextIterationDuration = -1;
+ endAnimation();
+ return;
+ }
+
+ if (input == AnimationStateInputRestartAnimation) {
+ if (m_animState == AnimationStateStartWaitStyleAvailable)
+ m_compAnim->animationController()->removeFromAnimationsWaitingForStyle(this);
+ m_animState = AnimationStateNew;
+ m_startTime = 0;
+ m_pauseTime = -1;
+ m_requestedStartTime = 0;
+ m_nextIterationDuration = -1;
+ endAnimation();
+
+ if (!paused())
+ updateStateMachine(AnimationStateInputStartAnimation, -1);
+ return;
+ }
+
+ if (input == AnimationStateInputEndAnimation) {
+ if (m_animState == AnimationStateStartWaitStyleAvailable)
+ m_compAnim->animationController()->removeFromAnimationsWaitingForStyle(this);
+ m_animState = AnimationStateDone;
+ endAnimation();
+ return;
+ }
+
+ if (input == AnimationStateInputPauseOverride) {
+ if (m_animState == AnimationStateStartWaitResponse) {
+ // If we are in AnimationStateStartWaitResponse, the animation will get canceled before
+ // we get a response, so move to the next state.
+ endAnimation();
+ updateStateMachine(AnimationStateInputStartTimeSet, beginAnimationUpdateTime());
+ }
+ return;
+ }
+
+ if (input == AnimationStateInputResumeOverride) {
+ if (m_animState == AnimationStateLooping || m_animState == AnimationStateEnding) {
+ // Start the animation
+ startAnimation(beginAnimationUpdateTime() - m_startTime);
+ }
+ return;
+ }
+
+ // Execute state machine
+ switch (m_animState) {
+ case AnimationStateNew:
+ ASSERT(input == AnimationStateInputStartAnimation || input == AnimationStateInputPlayStateRunning || input == AnimationStateInputPlayStatePaused);
+ if (input == AnimationStateInputStartAnimation || input == AnimationStateInputPlayStateRunning) {
+ m_requestedStartTime = beginAnimationUpdateTime();
+ m_animState = AnimationStateStartWaitTimer;
+ }
+ break;
+ case AnimationStateStartWaitTimer:
+ ASSERT(input == AnimationStateInputStartTimerFired || input == AnimationStateInputPlayStatePaused);
+
+ if (input == AnimationStateInputStartTimerFired) {
+ ASSERT(param >= 0);
+ // Start timer has fired, tell the animation to start and wait for it to respond with start time
+ m_animState = AnimationStateStartWaitStyleAvailable;
+ m_compAnim->animationController()->addToAnimationsWaitingForStyle(this);
+
+ // Trigger a render so we can start the animation
+ if (m_object)
+ m_compAnim->animationController()->addNodeChangeToDispatch(m_object->node());
+ } else {
+ ASSERT(!paused());
+ // We're waiting for the start timer to fire and we got a pause. Cancel the timer, pause and wait
+ m_pauseTime = beginAnimationUpdateTime();
+ m_animState = AnimationStatePausedWaitTimer;
+ }
+ break;
+ case AnimationStateStartWaitStyleAvailable:
+ ASSERT(input == AnimationStateInputStyleAvailable || input == AnimationStateInputPlayStatePaused);
+
+ if (input == AnimationStateInputStyleAvailable) {
+ // Start timer has fired, tell the animation to start and wait for it to respond with start time
+ m_animState = AnimationStateStartWaitResponse;
+
+ overrideAnimations();
+
+ // Start the animation
+ if (overridden()) {
+ m_animState = AnimationStateStartWaitResponse;
+ updateStateMachine(AnimationStateInputStartTimeSet, beginAnimationUpdateTime());
+ } else {
+ double timeOffset = 0;
+ // If the value for 'animation-delay' is negative then the animation appears to have started in the past.
+ if (m_animation->delay() < 0)
+ timeOffset = -m_animation->delay();
+ startAnimation(timeOffset);
+ m_compAnim->animationController()->addToAnimationsWaitingForStartTimeResponse(this, isAccelerated());
+ }
+ } else {
+ // We're waiting for the style to be available and we got a pause. Pause and wait
+ m_pauseTime = beginAnimationUpdateTime();
+ m_animState = AnimationStatePausedWaitStyleAvailable;
+ }
+ break;
+ case AnimationStateStartWaitResponse:
+ ASSERT(input == AnimationStateInputStartTimeSet || input == AnimationStateInputPlayStatePaused);
+
+ if (input == AnimationStateInputStartTimeSet) {
+ ASSERT(param >= 0);
+ // We have a start time, set it, unless the startTime is already set
+ if (m_startTime <= 0) {
+ m_startTime = param;
+ // If the value for 'animation-delay' is negative then the animation appears to have started in the past.
+ if (m_animation->delay() < 0)
+ m_startTime += m_animation->delay();
+ }
+
+ // Now that we know the start time, fire the start event.
+ onAnimationStart(0); // The elapsedTime is 0.
+
+ // Decide whether to go into looping or ending state
+ goIntoEndingOrLoopingState();
+
+ // Dispatch updateStyleIfNeeded so we can start the animation
+ if (m_object)
+ m_compAnim->animationController()->addNodeChangeToDispatch(m_object->node());
+ } else {
+ // We are pausing while waiting for a start response. Cancel the animation and wait. When
+ // we unpause, we will act as though the start timer just fired
+ m_pauseTime = beginAnimationUpdateTime();
+ pauseAnimation(beginAnimationUpdateTime() - m_startTime);
+ m_animState = AnimationStatePausedWaitResponse;
+ }
+ break;
+ case AnimationStateLooping:
+ ASSERT(input == AnimationStateInputLoopTimerFired || input == AnimationStateInputPlayStatePaused);
+
+ if (input == AnimationStateInputLoopTimerFired) {
+ ASSERT(param >= 0);
+ // Loop timer fired, loop again or end.
+ onAnimationIteration(param);
+
+ // Decide whether to go into looping or ending state
+ goIntoEndingOrLoopingState();
+ } else {
+ // We are pausing while running. Cancel the animation and wait
+ m_pauseTime = beginAnimationUpdateTime();
+ pauseAnimation(beginAnimationUpdateTime() - m_startTime);
+ m_animState = AnimationStatePausedRun;
+ }
+ break;
+ case AnimationStateEnding:
+#if !LOG_DISABLED
+ if (input != AnimationStateInputEndTimerFired && input != AnimationStateInputPlayStatePaused)
+ WTF_LOG_ERROR("State is AnimationStateEnding, but input is not AnimationStateInputEndTimerFired or AnimationStateInputPlayStatePaused. It is %d.", input);
+#endif
+ if (input == AnimationStateInputEndTimerFired) {
+
+ ASSERT(param >= 0);
+ // End timer fired, finish up
+ onAnimationEnd(param);
+
+ m_animState = AnimationStateDone;
+
+ if (m_object) {
+ if (m_animation->fillsForwards())
+ m_animState = AnimationStateFillingForwards;
+ else
+ resumeOverriddenAnimations();
+
+ // Fire off another style change so we can set the final value
+ m_compAnim->animationController()->addNodeChangeToDispatch(m_object->node());
+ }
+ } else {
+ // We are pausing while running. Cancel the animation and wait
+ m_pauseTime = beginAnimationUpdateTime();
+ pauseAnimation(beginAnimationUpdateTime() - m_startTime);
+ m_animState = AnimationStatePausedRun;
+ }
+ // |this| may be deleted here
+ break;
+ case AnimationStatePausedWaitTimer:
+ ASSERT(input == AnimationStateInputPlayStateRunning);
+ ASSERT(paused());
+ // Update the times
+ m_startTime += beginAnimationUpdateTime() - m_pauseTime;
+ m_pauseTime = -1;
+
+ // we were waiting for the start timer to fire, go back and wait again
+ m_animState = AnimationStateNew;
+ updateStateMachine(AnimationStateInputStartAnimation, 0);
+ break;
+ case AnimationStatePausedWaitResponse:
+ case AnimationStatePausedWaitStyleAvailable:
+ case AnimationStatePausedRun:
+ // We treat these two cases the same. The only difference is that, when we are in
+ // AnimationStatePausedWaitResponse, we don't yet have a valid startTime, so we send 0 to startAnimation.
+ // When the AnimationStateInputStartTimeSet comes in and we were in AnimationStatePausedRun, we will notice
+ // that we have already set the startTime and will ignore it.
+ ASSERT(input == AnimationStateInputPlayStateRunning || input == AnimationStateInputStartTimeSet || input == AnimationStateInputStyleAvailable);
+ ASSERT(paused());
+
+ if (input == AnimationStateInputPlayStateRunning) {
+ // Update the times
+ if (m_animState == AnimationStatePausedRun)
+ m_startTime += beginAnimationUpdateTime() - m_pauseTime;
+ else
+ m_startTime = 0;
+ m_pauseTime = -1;
+
+ if (m_animState == AnimationStatePausedWaitStyleAvailable)
+ m_animState = AnimationStateStartWaitStyleAvailable;
+ else {
+ // We were either running or waiting for a begin time response from the animation.
+ // Either way we need to restart the animation (possibly with an offset if we
+ // had already been running) and wait for it to start.
+ m_animState = AnimationStateStartWaitResponse;
+
+ // Start the animation
+ if (overridden()) {
+ updateStateMachine(AnimationStateInputStartTimeSet, beginAnimationUpdateTime());
+ } else {
+ startAnimation(beginAnimationUpdateTime() - m_startTime);
+ m_compAnim->animationController()->addToAnimationsWaitingForStartTimeResponse(this, isAccelerated());
+ }
+ }
+ break;
+ }
+
+ if (input == AnimationStateInputStartTimeSet) {
+ ASSERT(m_animState == AnimationStatePausedWaitResponse);
+
+ // We are paused but we got the callback that notifies us that an accelerated animation started.
+ // We ignore the start time and just move into the paused-run state.
+ m_animState = AnimationStatePausedRun;
+ ASSERT(m_startTime == 0);
+ m_startTime = param;
+ m_pauseTime += m_startTime;
+ break;
+ }
+
+ ASSERT(m_animState == AnimationStatePausedWaitStyleAvailable);
+ // We are paused but we got the callback that notifies us that style has been updated.
+ // We move to the AnimationStatePausedWaitResponse state
+ m_animState = AnimationStatePausedWaitResponse;
+ overrideAnimations();
+ break;
+ case AnimationStateFillingForwards:
+ case AnimationStateDone:
+ // We're done. Stay in this state until we are deleted
+ break;
+ }
+}
+
+void AnimationBase::fireAnimationEventsIfNeeded()
+{
+ if (!m_compAnim)
+ return;
+
+ // If we are waiting for the delay time to expire and it has, go to the next state
+ if (m_animState != AnimationStateStartWaitTimer && m_animState != AnimationStateLooping && m_animState != AnimationStateEnding)
+ return;
+
+ // We have to make sure to keep a ref to the this pointer, because it could get destroyed
+ // during an animation callback that might get called. Since the owner is a CompositeAnimation
+ // and it ref counts this object, we will keep a ref to that instead. That way the AnimationBase
+ // can still access the resources of its CompositeAnimation as needed.
+ RefPtr<AnimationBase> protector(this);
+ RefPtr<CompositeAnimation> compProtector(m_compAnim);
+
+ // Check for start timeout
+ if (m_animState == AnimationStateStartWaitTimer) {
+ if (beginAnimationUpdateTime() - m_requestedStartTime >= m_animation->delay())
+ updateStateMachine(AnimationStateInputStartTimerFired, 0);
+ return;
+ }
+
+ double elapsedDuration = getElapsedTime();
+
+ // Check for end timeout
+ if (m_totalDuration >= 0 && elapsedDuration >= m_totalDuration) {
+ // We may still be in AnimationStateLooping if we've managed to skip a
+ // whole iteration, in which case we should jump to the end state.
+ m_animState = AnimationStateEnding;
+
+ // Fire an end event
+ updateStateMachine(AnimationStateInputEndTimerFired, m_totalDuration);
+ } else {
+ // Check for iteration timeout
+ if (m_nextIterationDuration < 0) {
+ // Hasn't been set yet, set it
+ double durationLeft = m_animation->duration() - fmod(elapsedDuration, m_animation->duration());
+ m_nextIterationDuration = elapsedDuration + durationLeft;
+ }
+
+ if (elapsedDuration >= m_nextIterationDuration) {
+ // Set to the next iteration
+ double previous = m_nextIterationDuration;
+ double durationLeft = m_animation->duration() - fmod(elapsedDuration, m_animation->duration());
+ m_nextIterationDuration = elapsedDuration + durationLeft;
+
+ // Send the event
+ updateStateMachine(AnimationStateInputLoopTimerFired, previous);
+ }
+ }
+}
+
+void AnimationBase::updatePlayState(EAnimPlayState playState)
+{
+ if (!m_compAnim)
+ return;
+
+ // Set the state machine to the desired state.
+ bool pause = playState == AnimPlayStatePaused;
+
+ if (pause == paused() && !isNew())
+ return;
+
+ updateStateMachine(pause ? AnimationStateInputPlayStatePaused : AnimationStateInputPlayStateRunning, -1);
+}
+
+double AnimationBase::timeToNextService()
+{
+ // Returns the time at which next service is required. -1 means no service is required. 0 means
+ // service is required now, and > 0 means service is required that many seconds in the future.
+ if (paused() || isNew() || m_animState == AnimationStateFillingForwards)
+ return -1;
+
+ if (m_animState == AnimationStateStartWaitTimer) {
+ double timeFromNow = m_animation->delay() - (beginAnimationUpdateTime() - m_requestedStartTime);
+ return max(timeFromNow, 0.0);
+ }
+
+ fireAnimationEventsIfNeeded();
+
+ // In all other cases, we need service right away.
+ return 0;
+}
+
+// Compute the fractional time, taking into account direction.
+// There is no need to worry about iterations, we assume that we would have
+// short circuited above if we were done.
+
+double AnimationBase::fractionalTime(double scale, double elapsedTime, double offset) const
+{
+ double fractionalTime = m_animation->duration() ? (elapsedTime / m_animation->duration()) : 1;
+ // FIXME: startTime can be before the current animation "frame" time. This is to sync with the frame time
+ // concept in AnimationTimeController. So we need to somehow sync the two. Until then, the possible
+ // error is small and will probably not be noticeable. Until we fix this, remove the assert.
+ // https://bugs.webkit.org/show_bug.cgi?id=52037
+ // ASSERT(fractionalTime >= 0);
+ if (fractionalTime < 0)
+ fractionalTime = 0;
+
+ int integralTime = static_cast<int>(fractionalTime);
+ const int integralIterationCount = static_cast<int>(m_animation->iterationCount());
+ const bool iterationCountHasFractional = m_animation->iterationCount() - integralIterationCount;
+ if (m_animation->iterationCount() != CSSAnimationData::IterationCountInfinite && !iterationCountHasFractional)
+ integralTime = min(integralTime, integralIterationCount - 1);
+
+ fractionalTime -= integralTime;
+
+ // Thie method can be called with an elapsedTime which very slightly
+ // exceeds the end of the animation. In this case, clamp the
+ // fractionalTime.
+ if (fractionalTime > 1)
+ fractionalTime = 1;
+ ASSERT(fractionalTime >= 0 && fractionalTime <= 1);
+
+ if (((m_animation->direction() == CSSAnimationData::AnimationDirectionAlternate) && (integralTime & 1))
+ || ((m_animation->direction() == CSSAnimationData::AnimationDirectionAlternateReverse) && !(integralTime & 1))
+ || m_animation->direction() == CSSAnimationData::AnimationDirectionReverse)
+ fractionalTime = 1 - fractionalTime;
+
+ fractionalTime -= offset;
+ // Note that if fractionalTime == 0 here, scale may be infinity, but in
+ // this case we don't need to apply scale anyway.
+ if (scale != 1.0 && fractionalTime) {
+ ASSERT(scale >= 0 && !std::isinf(scale));
+ fractionalTime *= scale;
+ }
+
+ ASSERT(fractionalTime >= 0 && fractionalTime <= 1);
+ return fractionalTime;
+}
+
+double AnimationBase::progress(double scale, double offset, const TimingFunction* timingFunction) const
+{
+ if (preActive())
+ return 0;
+
+ double dur = m_animation->duration();
+ if (m_animation->iterationCount() > 0)
+ dur *= m_animation->iterationCount();
+
+ if (postActive() || !m_animation->duration())
+ return 1.0;
+
+ double elapsedTime = getElapsedTime();
+ if (m_animation->iterationCount() > 0 && elapsedTime >= dur) {
+ const int integralIterationCount = static_cast<int>(m_animation->iterationCount());
+ const bool iterationCountHasFractional = m_animation->iterationCount() - integralIterationCount;
+ return (integralIterationCount % 2 || iterationCountHasFractional) ? 1.0 : 0.0;
+ }
+
+ const double fractionalTime = this->fractionalTime(scale, elapsedTime, offset);
+
+ if (!timingFunction)
+ timingFunction = m_animation->timingFunction();
+
+ return timingFunction->evaluate(fractionalTime, accuracyForDuration(m_animation->duration()));
+}
+
+void AnimationBase::getTimeToNextEvent(double& time, bool& isLooping) const
+{
+ if (postActive()) {
+ time = -1;
+ isLooping = false;
+ return;
+ }
+
+ // Decide when the end or loop event needs to fire
+ const double elapsedDuration = getElapsedTime();
+ double durationLeft = 0;
+ double nextIterationTime = m_totalDuration;
+
+ if (m_totalDuration < 0 || elapsedDuration < m_totalDuration) {
+ durationLeft = m_animation->duration() > 0 ? (m_animation->duration() - fmod(elapsedDuration, m_animation->duration())) : 0;
+ nextIterationTime = elapsedDuration + durationLeft;
+ }
+
+ if (m_totalDuration < 0 || nextIterationTime < m_totalDuration) {
+ // We are not at the end yet
+ ASSERT(m_totalDuration < 0 || nextIterationTime > 0);
+ isLooping = true;
+ } else {
+ // We are at the end
+ isLooping = false;
+ }
+
+ time = durationLeft;
+}
+
+void AnimationBase::goIntoEndingOrLoopingState()
+{
+ double t;
+ bool isLooping;
+ getTimeToNextEvent(t, isLooping);
+ m_animState = isLooping ? AnimationStateLooping : AnimationStateEnding;
+}
+
+void AnimationBase::freezeAtTime(double t)
+{
+ if (!m_compAnim)
+ return;
+
+ if (!m_startTime) {
+ // If we haven't started yet, make it as if we started.
+ m_animState = AnimationStateStartWaitResponse;
+ onAnimationStartResponse(beginAnimationUpdateTime());
+ }
+
+ ASSERT(m_startTime); // if m_startTime is zero, we haven't started yet, so we'll get a bad pause time.
+ if (t <= m_animation->delay())
+ m_pauseTime = m_startTime;
+ else
+ m_pauseTime = m_startTime + t - m_animation->delay();
+
+ // It is possible that m_isAccelerated is true and m_object->compositingState() is NotComposited, because of style change.
+ // So, both conditions need to be checked.
+ if (m_object && m_object->compositingState() == PaintsIntoOwnBacking && isAccelerated())
+ pauseAnimation(t);
+}
+
+double AnimationBase::beginAnimationUpdateTime() const
+{
+ if (!m_compAnim)
+ return 0;
+
+ return m_compAnim->animationController()->beginAnimationUpdateTime();
+}
+
+double AnimationBase::getElapsedTime() const
+{
+ ASSERT(!postActive());
+ if (paused())
+ return m_pauseTime - m_startTime;
+ if (m_startTime <= 0)
+ return 0;
+
+ double elapsedTime = beginAnimationUpdateTime() - m_startTime;
+ // It's possible for the start time to be ahead of the last update time
+ // if the compositor has just sent notification for the start of an
+ // accelerated animation.
+ return max(elapsedTime, 0.0);
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/frame/animation/AnimationBase.h b/chromium/third_party/WebKit/Source/core/frame/animation/AnimationBase.h
new file mode 100644
index 00000000000..6ab1d5801e4
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/animation/AnimationBase.h
@@ -0,0 +1,228 @@
+/*
+ * Copyright (C) 2007 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef AnimationBase_h
+#define AnimationBase_h
+
+#include "CSSPropertyNames.h"
+#include "core/platform/animation/CSSAnimationData.h"
+#include "core/rendering/style/RenderStyleConstants.h"
+#include "wtf/RefCounted.h"
+
+namespace WebCore {
+
+class AnimationBase;
+class AnimationController;
+class CompositeAnimation;
+class Element;
+class Node;
+class RenderObject;
+class RenderStyle;
+class TimingFunction;
+
+class AnimationBase : public RefCounted<AnimationBase> {
+ friend class CompositeAnimation;
+ friend class CSSPropertyAnimation;
+
+public:
+ AnimationBase(const CSSAnimationData* transition, RenderObject& renderer, CompositeAnimation* compAnim);
+ virtual ~AnimationBase() { }
+
+ RenderObject* renderer() const { return m_object; }
+ void clear()
+ {
+ endAnimation();
+ m_object = 0;
+ m_compAnim = 0;
+ }
+
+ double duration() const;
+
+ // Animations and Transitions go through the states below. When entering the STARTED state
+ // the animation is started. This may or may not require deferred response from the animator.
+ // If so, we stay in this state until that response is received (and it returns the start time).
+ // Otherwise, we use the current time as the start time and go immediately to AnimationStateLooping
+ // or AnimationStateEnding.
+ enum AnimState {
+ AnimationStateNew, // animation just created, animation not running yet
+ AnimationStateStartWaitTimer, // start timer running, waiting for fire
+ AnimationStateStartWaitStyleAvailable, // waiting for style setup so we can start animations
+ AnimationStateStartWaitResponse, // animation started, waiting for response
+ AnimationStateLooping, // response received, animation running, loop timer running, waiting for fire
+ AnimationStateEnding, // received, animation running, end timer running, waiting for fire
+ AnimationStatePausedWaitTimer, // in pause mode when animation started
+ AnimationStatePausedWaitStyleAvailable, // in pause mode when waiting for style setup
+ AnimationStatePausedWaitResponse, // animation paused when in STARTING state
+ AnimationStatePausedRun, // animation paused when in LOOPING or ENDING state
+ AnimationStateDone, // end timer fired, animation finished and removed
+ AnimationStateFillingForwards // animation has ended and is retaining its final value
+ };
+
+ enum AnimStateInput {
+ AnimationStateInputMakeNew, // reset back to new from any state
+ AnimationStateInputStartAnimation, // animation requests a start
+ AnimationStateInputRestartAnimation, // force a restart from any state
+ AnimationStateInputStartTimerFired, // start timer fired
+ AnimationStateInputStyleAvailable, // style is setup, ready to start animating
+ AnimationStateInputStartTimeSet, // m_startTime was set
+ AnimationStateInputLoopTimerFired, // loop timer fired
+ AnimationStateInputEndTimerFired, // end timer fired
+ AnimationStateInputPauseOverride, // pause an animation due to override
+ AnimationStateInputResumeOverride, // resume an overridden animation
+ AnimationStateInputPlayStateRunning, // play state paused -> running
+ AnimationStateInputPlayStatePaused, // play state running -> paused
+ AnimationStateInputEndAnimation // force an end from any state
+ };
+
+ // Called when animation is in AnimationStateNew to start animation
+ void updateStateMachine(AnimStateInput, double param);
+
+ // Animation has actually started, at passed time
+ void onAnimationStartResponse(double startTime)
+ {
+ updateStateMachine(AnimationBase::AnimationStateInputStartTimeSet, startTime);
+ }
+
+ // Called to change to or from paused state
+ void updatePlayState(EAnimPlayState);
+ bool playStatePlaying() const;
+
+ bool waitingToStart() const { return m_animState == AnimationStateNew || m_animState == AnimationStateStartWaitTimer; }
+ bool preActive() const
+ {
+ return m_animState == AnimationStateNew || m_animState == AnimationStateStartWaitTimer || m_animState == AnimationStateStartWaitStyleAvailable || m_animState == AnimationStateStartWaitResponse;
+ }
+
+ bool postActive() const { return m_animState == AnimationStateDone; }
+ bool active() const { return !postActive() && !preActive(); }
+ bool running() const { return !isNew() && !postActive(); }
+ bool paused() const { return m_pauseTime >= 0; }
+ bool isNew() const { return m_animState == AnimationStateNew; }
+ bool waitingForStartTime() const { return m_animState == AnimationStateStartWaitResponse; }
+ bool waitingForStyleAvailable() const { return m_animState == AnimationStateStartWaitStyleAvailable; }
+
+ virtual double timeToNextService();
+
+ double progress(double scale, double offset, const TimingFunction*) const;
+
+ virtual void animate(CompositeAnimation*, RenderObject*, const RenderStyle* /*currentStyle*/, RenderStyle* /*targetStyle*/, RefPtr<RenderStyle>& /*animatedStyle*/) = 0;
+ virtual void getAnimatedStyle(RefPtr<RenderStyle>& /*animatedStyle*/) = 0;
+
+ virtual bool shouldFireEvents() const { return false; }
+
+ void fireAnimationEventsIfNeeded();
+
+ void setAnimation(const CSSAnimationData* anim) { m_animation = const_cast<CSSAnimationData*>(anim); }
+
+ // Return true if this animation is overridden. This will only be the case for
+ // ImplicitAnimations and is used to determine whether or not we should force
+ // set the start time. If an animation is overridden, it will probably not get
+ // back the AnimationStateInputStartTimeSet input.
+ virtual bool overridden() const { return false; }
+
+ // Does this animation/transition involve the given property?
+ virtual bool affectsProperty(CSSPropertyID /*property*/) const { return false; }
+
+ bool isAnimatingProperty(CSSPropertyID property, bool acceleratedOnly, bool isRunningNow) const
+ {
+ if (acceleratedOnly && !m_isAccelerated)
+ return false;
+
+ if (isRunningNow)
+ return (!waitingToStart() && !postActive()) && affectsProperty(property);
+
+ return !postActive() && affectsProperty(property);
+ }
+
+ // FIXME: rename this using the "lists match" terminology.
+ bool isTransformFunctionListValid() const { return m_transformFunctionListValid; }
+ bool filterFunctionListsMatch() const { return m_filterFunctionListsMatch; }
+
+ // Freeze the animation; used by DumpRenderTree.
+ void freezeAtTime(double t);
+
+ double beginAnimationUpdateTime() const;
+
+ double getElapsedTime() const;
+
+ void styleAvailable()
+ {
+ ASSERT(waitingForStyleAvailable());
+ updateStateMachine(AnimationBase::AnimationStateInputStyleAvailable, -1);
+ }
+
+ const CSSAnimationData* animation() const { return m_animation.get(); }
+
+protected:
+ virtual void overrideAnimations() { }
+ virtual void resumeOverriddenAnimations() { }
+
+ CompositeAnimation* compositeAnimation() { return m_compAnim; }
+
+ // These are called when the corresponding timer fires so subclasses can do any extra work
+ virtual void onAnimationStart(double /*elapsedTime*/) { }
+ virtual void onAnimationIteration(double /*elapsedTime*/) { }
+ virtual void onAnimationEnd(double /*elapsedTime*/) { }
+
+ // timeOffset is an offset from the current time when the animation should start. Negative values are OK.
+ virtual void startAnimation(double /*timeOffset*/) { }
+ // timeOffset is the time at which the animation is being paused.
+ virtual void pauseAnimation(double /*timeOffset*/) { }
+ virtual void endAnimation() { }
+
+ void goIntoEndingOrLoopingState();
+
+ bool isAccelerated() const { return m_isAccelerated; }
+
+ static void setNeedsStyleRecalc(Node*);
+
+ void getTimeToNextEvent(double& time, bool& isLooping) const;
+
+ double fractionalTime(double scale, double elapsedTime, double offset) const;
+
+ AnimState m_animState;
+
+ bool m_isAccelerated;
+ bool m_transformFunctionListValid;
+ bool m_filterFunctionListsMatch;
+ double m_startTime;
+ double m_pauseTime;
+ double m_requestedStartTime;
+
+ double m_totalDuration;
+ double m_nextIterationDuration;
+
+ RenderObject* m_object;
+
+ RefPtr<CSSAnimationData> m_animation;
+ CompositeAnimation* m_compAnim;
+};
+
+} // namespace WebCore
+
+#endif // AnimationBase_h
diff --git a/chromium/third_party/WebKit/Source/core/frame/animation/AnimationController.cpp b/chromium/third_party/WebKit/Source/core/frame/animation/AnimationController.cpp
new file mode 100644
index 00000000000..8521e139a08
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/animation/AnimationController.cpp
@@ -0,0 +1,542 @@
+/*
+ * Copyright (C) 2007, 2008, 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/frame/animation/AnimationController.h"
+
+#include "core/dom/PseudoElement.h"
+#include "core/events/ThreadLocalEventNames.h"
+#include "core/events/TransitionEvent.h"
+#include "core/events/WebKitAnimationEvent.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
+#include "core/page/Page.h"
+#include "core/frame/animation/AnimationBase.h"
+#include "core/frame/animation/AnimationControllerPrivate.h"
+#include "core/frame/animation/CSSPropertyAnimation.h"
+#include "core/frame/animation/CompositeAnimation.h"
+#include "core/rendering/RenderView.h"
+#include "wtf/CurrentTime.h"
+
+namespace WebCore {
+
+static const double cBeginAnimationUpdateTimeNotSet = -1;
+
+AnimationControllerPrivate::AnimationControllerPrivate(Frame* frame)
+ : m_animationTimer(this, &AnimationControllerPrivate::animationTimerFired)
+ , m_updateStyleIfNeededDispatcher(this, &AnimationControllerPrivate::updateStyleIfNeededDispatcherFired)
+ , m_frame(frame)
+ , m_beginAnimationUpdateTime(cBeginAnimationUpdateTimeNotSet)
+ , m_animationsWaitingForStyle()
+ , m_animationsWaitingForStartTimeResponse()
+ , m_animationsWaitingForAsyncStartNotification()
+{
+}
+
+AnimationControllerPrivate::~AnimationControllerPrivate()
+{
+}
+
+PassRefPtr<CompositeAnimation> AnimationControllerPrivate::accessCompositeAnimation(RenderObject& renderer)
+{
+ RefPtr<CompositeAnimation> animation = m_compositeAnimations.get(&renderer);
+ if (!animation) {
+ animation = CompositeAnimation::create(this);
+ m_compositeAnimations.set(&renderer, animation);
+ }
+ return animation;
+}
+
+bool AnimationControllerPrivate::clear(RenderObject* renderer)
+{
+ // Return false if we didn't do anything.
+ PassRefPtr<CompositeAnimation> animation = m_compositeAnimations.take(renderer);
+ if (!animation)
+ return false;
+ animation->clearRenderer();
+ return true;
+}
+
+void AnimationControllerPrivate::updateAnimations(double& timeToNextService, double& timeToNextEvent, SetNeedsStyleRecalc callSetNeedsStyleRecalc/* = DoNotCallSetNeedsStyleRecalc*/)
+{
+ double minTimeToNextService = -1;
+ double minTimeToNextEvent = -1;
+ bool updateStyleNeeded = false;
+
+ RenderObjectAnimationMap::const_iterator animationsEnd = m_compositeAnimations.end();
+ for (RenderObjectAnimationMap::const_iterator it = m_compositeAnimations.begin(); it != animationsEnd; ++it) {
+ CompositeAnimation* compAnim = it->value.get();
+ if (compAnim->hasAnimations()) {
+ double t = compAnim->timeToNextService();
+ if (t != -1 && (t < minTimeToNextService || minTimeToNextService == -1))
+ minTimeToNextService = t;
+ double nextEvent = compAnim->timeToNextEvent();
+ if (nextEvent != -1 && (nextEvent < minTimeToNextEvent || minTimeToNextEvent == -1))
+ minTimeToNextEvent = nextEvent;
+ if (callSetNeedsStyleRecalc == CallSetNeedsStyleRecalc) {
+ if (!t) {
+ Node* node = it->key->node();
+ node->setNeedsStyleRecalc(LocalStyleChange, StyleChangeFromRenderer);
+ updateStyleNeeded = true;
+ }
+ } else if (!minTimeToNextService && !minTimeToNextEvent) {
+ // Found the minimum values and do not need to mark for style recalc.
+ break;
+ }
+ }
+ }
+
+ if (updateStyleNeeded)
+ m_frame->document()->updateStyleIfNeeded();
+
+ timeToNextService = minTimeToNextService;
+ timeToNextEvent = minTimeToNextEvent;
+}
+
+void AnimationControllerPrivate::scheduleServiceForRenderer(RenderObject& renderer)
+{
+ double timeToNextService = -1;
+ double timeToNextEvent = -1;
+
+ RefPtr<CompositeAnimation> compAnim = m_compositeAnimations.get(&renderer);
+ if (compAnim->hasAnimations()) {
+ timeToNextService = compAnim->timeToNextService();
+ timeToNextEvent = compAnim->timeToNextEvent();
+ }
+
+ if (timeToNextService >= 0)
+ scheduleService(timeToNextService, timeToNextEvent);
+}
+
+void AnimationControllerPrivate::scheduleService()
+{
+ double timeToNextService = -1;
+ double timeToNextEvent = -1;
+ updateAnimations(timeToNextService, timeToNextEvent, DoNotCallSetNeedsStyleRecalc);
+ scheduleService(timeToNextService, timeToNextEvent);
+}
+
+void AnimationControllerPrivate::scheduleService(double timeToNextService, double timeToNextEvent)
+{
+ if (!m_frame->page())
+ return;
+
+ bool visible = m_frame->page()->visibilityState() == WebCore::PageVisibilityStateVisible;
+
+ // This std::max to 1 second limits how often we service animations on background tabs.
+ // Without this, plus and gmail were recalculating style as every 200ms or even more
+ // often, burning CPU needlessly for background tabs.
+ // FIXME: Do we want to fire events at all on background tabs?
+ if (!visible)
+ timeToNextService = std::max(timeToNextEvent, 1.0);
+
+ if (visible && !timeToNextService) {
+ m_frame->document()->view()->scheduleAnimation();
+ if (m_animationTimer.isActive())
+ m_animationTimer.stop();
+ return;
+ }
+
+ if (timeToNextService < 0) {
+ if (m_animationTimer.isActive())
+ m_animationTimer.stop();
+ return;
+ }
+
+ if (m_animationTimer.isActive() && m_animationTimer.nextFireInterval() <= timeToNextService)
+ return;
+
+ m_animationTimer.startOneShot(timeToNextService);
+}
+
+void AnimationControllerPrivate::updateStyleIfNeededDispatcherFired(Timer<AnimationControllerPrivate>*)
+{
+ fireEventsAndUpdateStyle();
+}
+
+void AnimationControllerPrivate::fireEventsAndUpdateStyle()
+{
+ // Protect the frame from getting destroyed in the event handler
+ RefPtr<Frame> protector = m_frame;
+
+ bool updateStyle = !m_eventsToDispatch.isEmpty() || !m_nodeChangesToDispatch.isEmpty();
+
+ // fire all the events
+ Vector<EventToDispatch> eventsToDispatch = m_eventsToDispatch;
+ m_eventsToDispatch.clear();
+ Vector<EventToDispatch>::const_iterator eventsToDispatchEnd = eventsToDispatch.end();
+ for (Vector<EventToDispatch>::const_iterator it = eventsToDispatch.begin(); it != eventsToDispatchEnd; ++it) {
+ Element* element = it->element.get();
+ if (it->eventType == EventTypeNames::transitionend)
+ element->dispatchEvent(TransitionEvent::create(it->eventType, it->name, it->elapsedTime, PseudoElement::pseudoElementNameForEvents(element->pseudoId())));
+ else
+ element->dispatchEvent(WebKitAnimationEvent::create(it->eventType, it->name, it->elapsedTime));
+ }
+
+ // call setChanged on all the elements
+ Vector<RefPtr<Node> >::const_iterator nodeChangesToDispatchEnd = m_nodeChangesToDispatch.end();
+ for (Vector<RefPtr<Node> >::const_iterator it = m_nodeChangesToDispatch.begin(); it != nodeChangesToDispatchEnd; ++it)
+ (*it)->setNeedsStyleRecalc(LocalStyleChange, StyleChangeFromRenderer);
+
+ m_nodeChangesToDispatch.clear();
+
+ if (updateStyle && m_frame)
+ m_frame->document()->updateStyleIfNeeded();
+}
+
+void AnimationControllerPrivate::startUpdateStyleIfNeededDispatcher()
+{
+ if (!m_updateStyleIfNeededDispatcher.isActive())
+ m_updateStyleIfNeededDispatcher.startOneShot(0);
+}
+
+void AnimationControllerPrivate::addEventToDispatch(PassRefPtr<Element> element, const AtomicString& eventType, const String& name, double elapsedTime)
+{
+ m_eventsToDispatch.grow(m_eventsToDispatch.size()+1);
+ EventToDispatch& event = m_eventsToDispatch[m_eventsToDispatch.size()-1];
+ event.element = element;
+ event.eventType = eventType;
+ event.name = name;
+ event.elapsedTime = elapsedTime;
+
+ startUpdateStyleIfNeededDispatcher();
+}
+
+void AnimationControllerPrivate::addNodeChangeToDispatch(PassRefPtr<Node> node)
+{
+ if (!node)
+ return;
+
+ m_nodeChangesToDispatch.append(node);
+ startUpdateStyleIfNeededDispatcher();
+}
+
+void AnimationControllerPrivate::serviceAnimations()
+{
+ double timeToNextService = -1;
+ double timeToNextEvent = -1;
+ updateAnimations(timeToNextService, timeToNextEvent, CallSetNeedsStyleRecalc);
+ scheduleService(timeToNextService, timeToNextEvent);
+
+ // Fire events right away, to avoid a flash of unanimated style after an animation completes, and before
+ // the 'end' event fires.
+ fireEventsAndUpdateStyle();
+}
+
+void AnimationControllerPrivate::animationTimerFired(Timer<AnimationControllerPrivate>*)
+{
+ // Make sure animationUpdateTime is updated, so that it is current even if no
+ // styleChange has happened (e.g. accelerated animations)
+ setBeginAnimationUpdateTime(cBeginAnimationUpdateTimeNotSet);
+ serviceAnimations();
+}
+
+bool AnimationControllerPrivate::isRunningAnimationOnRenderer(RenderObject* renderer, CSSPropertyID property, bool isRunningNow) const
+{
+ RefPtr<CompositeAnimation> animation = m_compositeAnimations.get(renderer);
+ if (!animation)
+ return false;
+
+ return animation->isAnimatingProperty(property, false, isRunningNow);
+}
+
+bool AnimationControllerPrivate::isRunningAcceleratableAnimationOnRenderer(RenderObject *renderer) const
+{
+ RefPtr<CompositeAnimation> animation = m_compositeAnimations.get(renderer);
+ if (!animation)
+ return false;
+
+ bool acceleratedOnly = false;
+ bool isRunningNow = true;
+ return animation->isAnimatingProperty(CSSPropertyOpacity, acceleratedOnly, isRunningNow)
+ || animation->isAnimatingProperty(CSSPropertyWebkitTransform, acceleratedOnly, isRunningNow)
+ || animation->isAnimatingProperty(CSSPropertyWebkitFilter, acceleratedOnly, isRunningNow);
+}
+
+bool AnimationControllerPrivate::isRunningAcceleratedAnimationOnRenderer(RenderObject* renderer, CSSPropertyID property, bool isRunningNow) const
+{
+ RefPtr<CompositeAnimation> animation = m_compositeAnimations.get(renderer);
+ if (!animation)
+ return false;
+
+ return animation->isAnimatingProperty(property, true, isRunningNow);
+}
+
+void AnimationControllerPrivate::pauseAnimationsForTesting(double t)
+{
+ RenderObjectAnimationMap::const_iterator animationsEnd = m_compositeAnimations.end();
+ for (RenderObjectAnimationMap::const_iterator it = m_compositeAnimations.begin(); it != animationsEnd; ++it) {
+ it->value->pauseAnimationsForTesting(t);
+ it->key->node()->setNeedsStyleRecalc(LocalStyleChange, StyleChangeFromRenderer);
+ }
+}
+
+double AnimationControllerPrivate::beginAnimationUpdateTime()
+{
+ if (m_beginAnimationUpdateTime == cBeginAnimationUpdateTimeNotSet)
+ m_beginAnimationUpdateTime = currentTime();
+ return m_beginAnimationUpdateTime;
+}
+
+void AnimationControllerPrivate::endAnimationUpdate()
+{
+ styleAvailable();
+ if (m_animationsWaitingForAsyncStartNotification.isEmpty())
+ startTimeResponse(beginAnimationUpdateTime());
+}
+
+void AnimationControllerPrivate::receivedStartTimeResponse(double time)
+{
+ startTimeResponse(time);
+}
+
+PassRefPtr<RenderStyle> AnimationControllerPrivate::getAnimatedStyleForRenderer(RenderObject* renderer)
+{
+ if (!renderer)
+ return 0;
+
+ RefPtr<CompositeAnimation> rendererAnimations = m_compositeAnimations.get(renderer);
+ if (!rendererAnimations)
+ return renderer->style();
+
+ RefPtr<RenderStyle> animatingStyle = rendererAnimations->getAnimatedStyle();
+ if (!animatingStyle)
+ animatingStyle = renderer->style();
+
+ return animatingStyle.release();
+}
+
+unsigned AnimationControllerPrivate::numberOfActiveAnimations(Document* document) const
+{
+ unsigned count = 0;
+
+ RenderObjectAnimationMap::const_iterator animationsEnd = m_compositeAnimations.end();
+ for (RenderObjectAnimationMap::const_iterator it = m_compositeAnimations.begin(); it != animationsEnd; ++it) {
+ RenderObject* renderer = it->key;
+ CompositeAnimation* compAnim = it->value.get();
+ if (renderer->document() == document)
+ count += compAnim->numberOfActiveAnimations();
+ }
+
+ return count;
+}
+
+void AnimationControllerPrivate::addToAnimationsWaitingForStyle(AnimationBase* animation)
+{
+ // Make sure this animation is not in the start time waiters
+ m_animationsWaitingForStartTimeResponse.remove(animation);
+ m_animationsWaitingForAsyncStartNotification.remove(animation);
+
+ m_animationsWaitingForStyle.add(animation);
+}
+
+void AnimationControllerPrivate::removeFromAnimationsWaitingForStyle(AnimationBase* animationToRemove)
+{
+ m_animationsWaitingForStyle.remove(animationToRemove);
+}
+
+void AnimationControllerPrivate::styleAvailable()
+{
+ // Go through list of waiters and send them on their way
+ WaitingAnimationsSet::const_iterator it = m_animationsWaitingForStyle.begin();
+ WaitingAnimationsSet::const_iterator end = m_animationsWaitingForStyle.end();
+ for (; it != end; ++it)
+ (*it)->styleAvailable();
+
+ m_animationsWaitingForStyle.clear();
+}
+
+void AnimationControllerPrivate::addToAnimationsWaitingForStartTimeResponse(AnimationBase* animation, bool willGetResponse)
+{
+ // If willGetResponse is true, it means this animation is actually waiting for a response
+ // (which will come in as a call to notifyAnimationStarted()).
+ // In that case we don't need to add it to this list. We just set a waitingForAResponse flag
+ // which says we are waiting for the response. If willGetResponse is false, this animation
+ // is not waiting for a response for itself, but rather for a notifyXXXStarted() call for
+ // another animation to which it will sync.
+ //
+ // When endAnimationUpdate() is called we check to see if the waitingForAResponse flag is
+ // true. If so, we just return and will do our work when the first notifyXXXStarted() call
+ // comes in. If it is false, we will not be getting a notifyXXXStarted() call, so we will
+ // do our work right away. In both cases we call the onAnimationStartResponse() method
+ // on each animation. In the first case we send in the time we got from notifyXXXStarted().
+ // In the second case, we just pass in the beginAnimationUpdateTime().
+ //
+ // This will synchronize all software and accelerated animations started in the same
+ // updateStyleIfNeeded cycle.
+ //
+
+ if (willGetResponse)
+ m_animationsWaitingForAsyncStartNotification.add(animation);
+
+ m_animationsWaitingForStartTimeResponse.add(animation);
+}
+
+void AnimationControllerPrivate::removeFromAnimationsWaitingForStartTimeResponse(AnimationBase* animationToRemove)
+{
+ m_animationsWaitingForStartTimeResponse.remove(animationToRemove);
+ m_animationsWaitingForAsyncStartNotification.remove(animationToRemove);
+}
+
+void AnimationControllerPrivate::startTimeResponse(double time)
+{
+ // Go through list of waiters and send them on their way
+
+ WaitingAnimationsSet::const_iterator it = m_animationsWaitingForStartTimeResponse.begin();
+ WaitingAnimationsSet::const_iterator end = m_animationsWaitingForStartTimeResponse.end();
+ for (; it != end; ++it)
+ (*it)->onAnimationStartResponse(time);
+
+ m_animationsWaitingForStartTimeResponse.clear();
+ m_animationsWaitingForAsyncStartNotification.clear();
+}
+
+void AnimationControllerPrivate::animationWillBeRemoved(AnimationBase* animation)
+{
+ removeFromAnimationsWaitingForStyle(animation);
+ removeFromAnimationsWaitingForStartTimeResponse(animation);
+}
+
+AnimationController::AnimationController(Frame* frame)
+ : m_data(adoptPtr(new AnimationControllerPrivate(frame)))
+ , m_beginAnimationUpdateCount(0)
+{
+}
+
+AnimationController::~AnimationController()
+{
+}
+
+void AnimationController::cancelAnimations(RenderObject* renderer)
+{
+ if (!m_data->hasAnimations())
+ return;
+
+ if (m_data->clear(renderer)) {
+ if (Node* node = renderer->node())
+ node->setNeedsStyleRecalc(LocalStyleChange, StyleChangeFromRenderer);
+ }
+}
+
+PassRefPtr<RenderStyle> AnimationController::updateAnimations(RenderObject& renderer, RenderStyle& newStyle)
+{
+ RenderStyle* oldStyle = renderer.style();
+
+ if ((!oldStyle || (!oldStyle->animations() && !oldStyle->transitions())) && (!newStyle.animations() && !newStyle.transitions()))
+ return PassRefPtr<RenderStyle>(newStyle);
+
+ // Don't run transitions when printing.
+ if (renderer.view()->document().printing())
+ return PassRefPtr<RenderStyle>(newStyle);
+
+ // Fetch our current set of implicit animations from a hashtable. We then compare them
+ // against the animations in the style and make sure we're in sync. If destination values
+ // have changed, we reset the animation. We then do a blend to get new values and we return
+ // a new style.
+
+ // We don't support anonymous pseudo elements like :first-line or :first-letter.
+ ASSERT(renderer.node());
+
+ RefPtr<CompositeAnimation> rendererAnimations = m_data->accessCompositeAnimation(renderer);
+ RefPtr<RenderStyle> blendedStyle = rendererAnimations->animate(renderer, oldStyle, newStyle);
+
+ if (renderer.parent() || newStyle.animations() || (oldStyle && oldStyle->animations())) {
+ m_data->scheduleServiceForRenderer(renderer);
+ }
+
+ if (blendedStyle != &newStyle) {
+ // If the animations/transitions change opacity or transform, we need to update
+ // the style to impose the stacking rules. Note that this is also
+ // done in StyleResolver::adjustRenderStyle().
+ if (blendedStyle->hasAutoZIndex() && (blendedStyle->opacity() < 1.0f || blendedStyle->hasTransform()))
+ blendedStyle->setZIndex(0);
+ }
+ return blendedStyle.release();
+}
+
+PassRefPtr<RenderStyle> AnimationController::getAnimatedStyleForRenderer(RenderObject* renderer)
+{
+ return m_data->getAnimatedStyleForRenderer(renderer);
+}
+
+void AnimationController::notifyAnimationStarted(RenderObject*, double startTime)
+{
+ m_data->receivedStartTimeResponse(startTime);
+}
+
+void AnimationController::pauseAnimationsForTesting(double t)
+{
+ m_data->pauseAnimationsForTesting(t);
+}
+
+unsigned AnimationController::numberOfActiveAnimations(Document* document) const
+{
+ return m_data->numberOfActiveAnimations(document);
+}
+
+bool AnimationController::isRunningAnimationOnRenderer(RenderObject* renderer, CSSPropertyID property, bool isRunningNow) const
+{
+ return m_data->isRunningAnimationOnRenderer(renderer, property, isRunningNow);
+}
+
+bool AnimationController::isRunningAcceleratableAnimationOnRenderer(RenderObject* renderer) const
+{
+ return m_data->isRunningAcceleratableAnimationOnRenderer(renderer);
+}
+
+bool AnimationController::isRunningAcceleratedAnimationOnRenderer(RenderObject* renderer, CSSPropertyID property, bool isRunningNow) const
+{
+ return m_data->isRunningAcceleratedAnimationOnRenderer(renderer, property, isRunningNow);
+}
+
+void AnimationController::serviceAnimations()
+{
+ m_data->serviceAnimations();
+}
+
+void AnimationController::beginAnimationUpdate()
+{
+ if (!m_beginAnimationUpdateCount)
+ m_data->setBeginAnimationUpdateTime(cBeginAnimationUpdateTimeNotSet);
+ ++m_beginAnimationUpdateCount;
+}
+
+void AnimationController::endAnimationUpdate()
+{
+ ASSERT(m_beginAnimationUpdateCount > 0);
+ --m_beginAnimationUpdateCount;
+ if (!m_beginAnimationUpdateCount)
+ m_data->endAnimationUpdate();
+}
+
+bool AnimationController::supportsAcceleratedAnimationOfProperty(CSSPropertyID property)
+{
+ return CSSPropertyAnimation::animationOfPropertyIsAccelerated(property);
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/frame/animation/AnimationController.h b/chromium/third_party/WebKit/Source/core/frame/animation/AnimationController.h
new file mode 100644
index 00000000000..01cf32699ba
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/animation/AnimationController.h
@@ -0,0 +1,104 @@
+/*
+ * Copyright (C) 2007 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef AnimationController_h
+#define AnimationController_h
+
+#include "CSSPropertyNames.h"
+#include "wtf/Forward.h"
+#include "wtf/OwnPtr.h"
+
+namespace WebCore {
+
+class AnimationBase;
+class AnimationControllerPrivate;
+class Document;
+class Element;
+class Frame;
+class Node;
+class RenderObject;
+class RenderStyle;
+
+class AnimationController {
+public:
+ AnimationController(Frame*);
+ ~AnimationController();
+
+ void cancelAnimations(RenderObject*);
+ PassRefPtr<RenderStyle> updateAnimations(RenderObject&, RenderStyle& newStyle);
+ PassRefPtr<RenderStyle> getAnimatedStyleForRenderer(RenderObject*);
+
+ // This is called when an accelerated animation or transition has actually started to animate.
+ void notifyAnimationStarted(RenderObject*, double startTime);
+
+ void pauseAnimationsForTesting(double t);
+ unsigned numberOfActiveAnimations(Document*) const; // To be used only for testing
+
+ bool isRunningAnimationOnRenderer(RenderObject*, CSSPropertyID, bool isRunningNow = true) const;
+ bool isRunningAcceleratableAnimationOnRenderer(RenderObject*) const;
+ bool isRunningAcceleratedAnimationOnRenderer(RenderObject*, CSSPropertyID, bool isRunningNow = true) const;
+
+ void serviceAnimations();
+
+ void beginAnimationUpdate();
+ void endAnimationUpdate();
+
+ static bool supportsAcceleratedAnimationOfProperty(CSSPropertyID);
+
+private:
+ OwnPtr<AnimationControllerPrivate> m_data;
+ int m_beginAnimationUpdateCount;
+};
+
+class AnimationUpdateBlock {
+public:
+ explicit AnimationUpdateBlock(AnimationController* animationController)
+ : m_animationController(animationController)
+ {
+ if (m_animationController)
+ m_animationController->beginAnimationUpdate();
+ }
+
+ explicit AnimationUpdateBlock(AnimationController& animationController)
+ : m_animationController(&animationController)
+ {
+ m_animationController->beginAnimationUpdate();
+ }
+
+ ~AnimationUpdateBlock()
+ {
+ if (m_animationController)
+ m_animationController->endAnimationUpdate();
+ }
+
+ AnimationController* m_animationController;
+};
+
+} // namespace WebCore
+
+#endif // AnimationController_h
diff --git a/chromium/third_party/WebKit/Source/core/frame/animation/AnimationControllerPrivate.h b/chromium/third_party/WebKit/Source/core/frame/animation/AnimationControllerPrivate.h
new file mode 100644
index 00000000000..671ec89b573
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/animation/AnimationControllerPrivate.h
@@ -0,0 +1,140 @@
+/*
+ * Copyright (C) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef AnimationControllerPrivate_h
+#define AnimationControllerPrivate_h
+
+#include "CSSPropertyNames.h"
+#include "platform/Timer.h"
+#include "wtf/HashMap.h"
+#include "wtf/HashSet.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefPtr.h"
+#include "wtf/Vector.h"
+#include "wtf/text/AtomicString.h"
+#include "wtf/text/WTFString.h"
+
+namespace WebCore {
+
+class AnimationBase;
+class CompositeAnimation;
+class Document;
+class Element;
+class Frame;
+class Node;
+class RenderObject;
+class RenderStyle;
+
+enum SetNeedsStyleRecalc {
+ DoNotCallSetNeedsStyleRecalc = 0,
+ CallSetNeedsStyleRecalc = 1
+};
+
+class AnimationControllerPrivate {
+ WTF_MAKE_NONCOPYABLE(AnimationControllerPrivate); WTF_MAKE_FAST_ALLOCATED;
+public:
+ AnimationControllerPrivate(Frame*);
+ ~AnimationControllerPrivate();
+
+ void updateAnimations(double& timeToNextService, double& timeToNextEvent, SetNeedsStyleRecalc callSetNeedsStyleRecalc = DoNotCallSetNeedsStyleRecalc);
+ void scheduleService();
+
+ PassRefPtr<CompositeAnimation> accessCompositeAnimation(RenderObject&);
+ bool clear(RenderObject*);
+
+ void updateStyleIfNeededDispatcherFired(Timer<AnimationControllerPrivate>*);
+ void startUpdateStyleIfNeededDispatcher();
+ void addEventToDispatch(PassRefPtr<Element> element, const AtomicString& eventType, const String& name, double elapsedTime);
+ void addNodeChangeToDispatch(PassRefPtr<Node>);
+
+ bool hasAnimations() const { return !m_compositeAnimations.isEmpty(); }
+
+ void serviceAnimations();
+
+ bool isRunningAnimationOnRenderer(RenderObject*, CSSPropertyID, bool isRunningNow) const;
+ bool isRunningAcceleratableAnimationOnRenderer(RenderObject*) const;
+ bool isRunningAcceleratedAnimationOnRenderer(RenderObject*, CSSPropertyID, bool isRunningNow) const;
+
+ void pauseAnimationsForTesting(double t);
+ unsigned numberOfActiveAnimations(Document*) const;
+
+ PassRefPtr<RenderStyle> getAnimatedStyleForRenderer(RenderObject* renderer);
+
+ double beginAnimationUpdateTime();
+ void setBeginAnimationUpdateTime(double t) { m_beginAnimationUpdateTime = t; }
+ void endAnimationUpdate();
+ void receivedStartTimeResponse(double);
+
+ void addToAnimationsWaitingForStyle(AnimationBase*);
+ void removeFromAnimationsWaitingForStyle(AnimationBase*);
+
+ void addToAnimationsWaitingForStartTimeResponse(AnimationBase*, bool willGetResponse);
+ void removeFromAnimationsWaitingForStartTimeResponse(AnimationBase*);
+
+ void animationWillBeRemoved(AnimationBase*);
+
+ void scheduleServiceForRenderer(RenderObject&);
+
+private:
+ void animationTimerFired(Timer<AnimationControllerPrivate>*);
+
+ void scheduleService(double timeToNextService, double timeToNextEvent);
+
+ void styleAvailable();
+ void fireEventsAndUpdateStyle();
+ void startTimeResponse(double t);
+
+ typedef HashMap<RenderObject*, RefPtr<CompositeAnimation> > RenderObjectAnimationMap;
+
+ RenderObjectAnimationMap m_compositeAnimations;
+ Timer<AnimationControllerPrivate> m_animationTimer;
+ Timer<AnimationControllerPrivate> m_updateStyleIfNeededDispatcher;
+ Frame* m_frame;
+
+ class EventToDispatch {
+ public:
+ RefPtr<Element> element;
+ AtomicString eventType;
+ String name;
+ double elapsedTime;
+ };
+
+ Vector<EventToDispatch> m_eventsToDispatch;
+ Vector<RefPtr<Node> > m_nodeChangesToDispatch;
+
+ double m_beginAnimationUpdateTime;
+
+ typedef HashSet<RefPtr<AnimationBase> > WaitingAnimationsSet;
+ WaitingAnimationsSet m_animationsWaitingForStyle;
+ WaitingAnimationsSet m_animationsWaitingForStartTimeResponse;
+ WaitingAnimationsSet m_animationsWaitingForAsyncStartNotification;
+};
+
+} // namespace WebCore
+
+#endif // AnimationControllerPrivate_h
diff --git a/chromium/third_party/WebKit/Source/core/frame/animation/CSSPropertyAnimation.cpp b/chromium/third_party/WebKit/Source/core/frame/animation/CSSPropertyAnimation.cpp
new file mode 100644
index 00000000000..4d07ebf1e86
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/animation/CSSPropertyAnimation.cpp
@@ -0,0 +1,1153 @@
+/*
+ * Copyright (C) 2007, 2008, 2009 Apple Inc. All rights reserved.
+ * Copyright (C) 2012 Adobe Systems Incorporated. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/frame/animation/CSSPropertyAnimation.h"
+
+#include <algorithm>
+#include "StylePropertyShorthand.h"
+#include "core/animation/css/CSSAnimations.h"
+#include "core/css/CSSCrossfadeValue.h"
+#include "core/css/CSSImageValue.h"
+#include "core/css/CSSPrimitiveValue.h"
+#include "core/fetch/ImageResource.h"
+#include "core/frame/animation/AnimationBase.h"
+#include "core/rendering/ClipPathOperation.h"
+#include "core/rendering/RenderBox.h"
+#include "core/rendering/style/RenderStyle.h"
+#include "core/rendering/style/ShadowList.h"
+#include "core/rendering/style/StyleFetchedImage.h"
+#include "core/rendering/style/StyleGeneratedImage.h"
+#include "platform/FloatConversion.h"
+#include "wtf/Noncopyable.h"
+
+namespace WebCore {
+
+template <typename T>
+static inline T blendFunc(const AnimationBase*, T from, T to, double progress)
+{
+ return blend(from, to, progress);
+}
+
+static inline float blendFunc(const AnimationBase*, float from, float to, double progress)
+{
+ return narrowPrecisionToFloat(from + (to - from) * progress);
+}
+
+static inline Color blendFunc(const AnimationBase*, const Color& from, const Color& to, double progress)
+{
+ return blend(from, to, progress);
+}
+
+static inline Length blendFunc(const AnimationBase*, const Length& from, const Length& to, double progress)
+{
+ return to.blend(from, progress, ValueRangeAll);
+}
+
+static inline BorderImageLength blendFunc(const AnimationBase* anim, const BorderImageLength& from, const BorderImageLength& to, double progress)
+{
+ if (from.isNumber() && to.isNumber())
+ return BorderImageLength(blendFunc(anim, from.number(), to.number(), progress));
+
+ if (from.isLength() && to.isLength())
+ return BorderImageLength(blendFunc(anim, from.length(), to.length(), progress));
+
+ // FIXME: Converting numbers to lengths using the computed border
+ // width would make it possible to interpolate between numbers and
+ // lengths.
+ // https://code.google.com/p/chromium/issues/detail?id=316164
+ return to;
+}
+
+static inline BorderImageLengthBox blendFunc(const AnimationBase* anim, const BorderImageLengthBox& from,
+ const BorderImageLengthBox& to, double progress)
+{
+ return BorderImageLengthBox(blendFunc(anim, from.top(), to.top(), progress),
+ blendFunc(anim, from.right(), to.right(), progress),
+ blendFunc(anim, from.bottom(), to.bottom(), progress),
+ blendFunc(anim, from.left(), to.left(), progress));
+}
+
+static inline LengthSize blendFunc(const AnimationBase* anim, const LengthSize& from, const LengthSize& to, double progress)
+{
+ return LengthSize(blendFunc(anim, from.width(), to.width(), progress),
+ blendFunc(anim, from.height(), to.height(), progress));
+}
+
+static inline LengthPoint blendFunc(const AnimationBase* anim, const LengthPoint& from, const LengthPoint& to, double progress)
+{
+ return LengthPoint(blendFunc(anim, from.x(), to.x(), progress), blendFunc(anim, from.y(), to.y(), progress));
+}
+
+static inline TransformOperations blendFunc(const AnimationBase* anim, const TransformOperations& from, const TransformOperations& to, double progress)
+{
+ if (anim->isTransformFunctionListValid())
+ return to.blendByMatchingOperations(from, progress);
+ return to.blendByUsingMatrixInterpolation(from, progress);
+}
+
+static inline PassRefPtr<ClipPathOperation> blendFunc(const AnimationBase*, ClipPathOperation* from, ClipPathOperation* to, double progress)
+{
+ // Other clip-path operations than BasicShapes can not be animated.
+ if (!from || !to || from->type() != ClipPathOperation::SHAPE || to->type() != ClipPathOperation::SHAPE)
+ return to;
+
+ const BasicShape* fromShape = toShapeClipPathOperation(from)->basicShape();
+ const BasicShape* toShape = toShapeClipPathOperation(to)->basicShape();
+
+ if (!fromShape->canBlend(toShape))
+ return to;
+
+ return ShapeClipPathOperation::create(toShape->blend(fromShape, progress));
+}
+
+static inline PassRefPtr<ShapeValue> blendFunc(const AnimationBase*, ShapeValue* from, ShapeValue* to, double progress)
+{
+ // FIXME Bug 102723: Shape-inside should be able to animate a value of 'outside-shape' when shape-outside is set to a BasicShape
+ if (!from || !to || from->type() != ShapeValue::Shape || to->type() != ShapeValue::Shape)
+ return to;
+
+ const BasicShape* fromShape = from->shape();
+ const BasicShape* toShape = to->shape();
+
+ if (!fromShape->canBlend(toShape))
+ return to;
+
+ return ShapeValue::createShapeValue(toShape->blend(fromShape, progress));
+}
+
+static inline FilterOperations blendFunc(const AnimationBase* anim, const FilterOperations& from, const FilterOperations& to, double progress)
+{
+ FilterOperations result;
+
+ // If we have a filter function list, use that to do a per-function animation.
+ if (anim->filterFunctionListsMatch()) {
+ size_t fromSize = from.operations().size();
+ size_t toSize = to.operations().size();
+ size_t size = max(fromSize, toSize);
+ for (size_t i = 0; i < size; i++) {
+ const FilterOperation* fromOp = (i < fromSize) ? from.operations()[i].get() : 0;
+ const FilterOperation* toOp = (i < toSize) ? to.operations()[i].get() : 0;
+ RefPtr<FilterOperation> blendedOp = FilterOperation::blend(fromOp, toOp, progress);
+ if (blendedOp)
+ result.operations().append(blendedOp);
+ else
+ ASSERT_NOT_REACHED();
+ }
+ } else {
+ // If the filter function lists don't match, we could try to cross-fade, but don't yet have a way to represent that in CSS.
+ // For now we'll just fail to animate.
+ result = to;
+ }
+
+ return result;
+}
+
+static inline EVisibility blendFunc(const AnimationBase* anim, EVisibility from, EVisibility to, double progress)
+{
+ // Any non-zero result means we consider the object to be visible. Only at 0 do we consider the object to be
+ // invisible. The invisible value we use (HIDDEN vs. COLLAPSE) depends on the specified from/to values.
+ double fromVal = from == VISIBLE ? 1. : 0.;
+ double toVal = to == VISIBLE ? 1. : 0.;
+ if (fromVal == toVal)
+ return to;
+ double result = blendFunc(anim, fromVal, toVal, progress);
+ return result > 0. ? VISIBLE : (to != VISIBLE ? to : from);
+}
+
+static inline LengthBox blendFunc(const AnimationBase* anim, const LengthBox& from, const LengthBox& to, double progress)
+{
+ // Length types have to match to animate
+ if (from.top().type() != to.top().type()
+ || from.right().type() != to.right().type()
+ || from.bottom().type() != to.bottom().type()
+ || from.left().type() != to.left().type())
+ return to;
+
+ LengthBox result(blendFunc(anim, from.top(), to.top(), progress),
+ blendFunc(anim, from.right(), to.right(), progress),
+ blendFunc(anim, from.bottom(), to.bottom(), progress),
+ blendFunc(anim, from.left(), to.left(), progress));
+ return result;
+}
+
+static inline SVGLength blendFunc(const AnimationBase*, const SVGLength& from, const SVGLength& to, double progress)
+{
+ return to.blend(from, narrowPrecisionToFloat(progress));
+}
+
+static inline Vector<SVGLength> blendFunc(const AnimationBase*, const Vector<SVGLength>& from, const Vector<SVGLength>& to, double progress)
+{
+ size_t fromLength = from.size();
+ size_t toLength = to.size();
+ if (!fromLength)
+ return !progress ? from : to;
+ if (!toLength)
+ return progress == 1 ? from : to;
+
+ size_t resultLength = fromLength;
+ if (fromLength != toLength) {
+ if (!(fromLength % toLength))
+ resultLength = fromLength;
+ else if (!(toLength % fromLength))
+ resultLength = toLength;
+ else
+ resultLength = fromLength * toLength;
+ }
+ Vector<SVGLength> result(resultLength);
+ for (size_t i = 0; i < resultLength; ++i)
+ result[i] = to[i % toLength].blend(from[i % fromLength], narrowPrecisionToFloat(progress));
+ return result;
+}
+
+static inline PassRefPtr<StyleImage> crossfadeBlend(const AnimationBase*, StyleFetchedImage* fromStyleImage, StyleFetchedImage* toStyleImage, double progress)
+{
+ // If progress is at one of the extremes, we want getComputedStyle to show the image,
+ // not a completed cross-fade, so we hand back one of the existing images.
+ if (!progress)
+ return fromStyleImage;
+ if (progress == 1)
+ return toStyleImage;
+
+ ImageResource* fromImageResource = static_cast<ImageResource*>(fromStyleImage->data());
+ ImageResource* toImageResource = static_cast<ImageResource*>(toStyleImage->data());
+
+ RefPtr<CSSImageValue> fromImageValue = CSSImageValue::create(fromImageResource->url(), fromStyleImage);
+ RefPtr<CSSImageValue> toImageValue = CSSImageValue::create(toImageResource->url(), toStyleImage);
+ RefPtr<CSSCrossfadeValue> crossfadeValue = CSSCrossfadeValue::create(fromImageValue, toImageValue);
+
+ crossfadeValue->setPercentage(CSSPrimitiveValue::create(progress, CSSPrimitiveValue::CSS_NUMBER));
+
+ return StyleGeneratedImage::create(crossfadeValue.get());
+}
+
+static inline PassRefPtr<StyleImage> blendFunc(const AnimationBase* anim, StyleImage* from, StyleImage* to, double progress)
+{
+ if (!from || !to)
+ return to;
+
+ if (from->isImageResource() && to->isImageResource())
+ return crossfadeBlend(anim, toStyleFetchedImage(from), toStyleFetchedImage(to), progress);
+
+ // FIXME: Support transitioning generated images as well. (gradients, etc.)
+
+ return to;
+}
+
+class AnimationPropertyWrapperBase {
+ WTF_MAKE_NONCOPYABLE(AnimationPropertyWrapperBase);
+ WTF_MAKE_FAST_ALLOCATED;
+public:
+ AnimationPropertyWrapperBase(CSSPropertyID prop)
+ : m_prop(prop)
+ {
+ }
+
+ virtual ~AnimationPropertyWrapperBase() { }
+
+ virtual bool isShorthandWrapper() const { return false; }
+ virtual bool equals(const RenderStyle* a, const RenderStyle* b) const = 0;
+ virtual void blend(const AnimationBase*, RenderStyle*, const RenderStyle*, const RenderStyle*, double) const = 0;
+
+ CSSPropertyID property() const { return m_prop; }
+
+ virtual bool animationIsAccelerated() const { return false; }
+
+private:
+ CSSPropertyID m_prop;
+};
+
+static int gPropertyWrapperMap[numCSSProperties];
+static const int cInvalidPropertyWrapperIndex = -1;
+static Vector<AnimationPropertyWrapperBase*>* gPropertyWrappers = 0;
+
+static void addPropertyWrapper(CSSPropertyID propertyID, AnimationPropertyWrapperBase* wrapper)
+{
+ int propIndex = propertyID - firstCSSProperty;
+
+ ASSERT(gPropertyWrapperMap[propIndex] == cInvalidPropertyWrapperIndex);
+
+ unsigned wrapperIndex = gPropertyWrappers->size();
+ gPropertyWrappers->append(wrapper);
+ gPropertyWrapperMap[propIndex] = wrapperIndex;
+}
+
+static AnimationPropertyWrapperBase* wrapperForProperty(CSSPropertyID propertyID)
+{
+ int propIndex = propertyID - firstCSSProperty;
+ if (propIndex >= 0 && propIndex < numCSSProperties) {
+ int wrapperIndex = gPropertyWrapperMap[propIndex];
+ if (wrapperIndex >= 0)
+ return (*gPropertyWrappers)[wrapperIndex];
+ }
+ return 0;
+}
+
+template <typename T>
+class PropertyWrapperGetter : public AnimationPropertyWrapperBase {
+public:
+ PropertyWrapperGetter(CSSPropertyID prop, T (RenderStyle::*getter)() const)
+ : AnimationPropertyWrapperBase(prop)
+ , m_getter(getter)
+ {
+ }
+
+ virtual bool equals(const RenderStyle* a, const RenderStyle* b) const
+ {
+ // If the style pointers are the same, don't bother doing the test.
+ // If either is null, return false. If both are null, return true.
+ if ((!a && !b) || a == b)
+ return true;
+ if (!a || !b)
+ return false;
+ return (a->*m_getter)() == (b->*m_getter)();
+ }
+
+protected:
+ T (RenderStyle::*m_getter)() const;
+};
+
+template <typename T>
+class PropertyWrapper : public PropertyWrapperGetter<T> {
+public:
+ PropertyWrapper(CSSPropertyID prop, T (RenderStyle::*getter)() const, void (RenderStyle::*setter)(T))
+ : PropertyWrapperGetter<T>(prop, getter)
+ , m_setter(setter)
+ {
+ }
+
+ virtual void blend(const AnimationBase* anim, RenderStyle* dst, const RenderStyle* a, const RenderStyle* b, double progress) const
+ {
+ (dst->*m_setter)(blendFunc(anim, (a->*PropertyWrapperGetter<T>::m_getter)(), (b->*PropertyWrapperGetter<T>::m_getter)(), progress));
+ }
+
+protected:
+ void (RenderStyle::*m_setter)(T);
+};
+
+class NonNegativeLengthWrapper : public PropertyWrapper<Length> {
+public:
+ NonNegativeLengthWrapper(CSSPropertyID prop, Length (RenderStyle::*getter)() const, void (RenderStyle::*setter)(Length))
+ : PropertyWrapper<Length>(prop, getter, setter)
+ {
+ }
+
+ virtual void blend(const AnimationBase* anim, RenderStyle* dst, const RenderStyle* a, const RenderStyle* b, double progress) const
+ {
+ Length from = (a->*PropertyWrapperGetter<Length>::m_getter)();
+ Length to = (b->*PropertyWrapperGetter<Length>::m_getter)();
+ (dst->*PropertyWrapper<Length>::m_setter)(to.blend(from, progress, ValueRangeNonNegative));
+ }
+};
+
+template <typename T>
+class RefCountedPropertyWrapper : public PropertyWrapperGetter<T*> {
+public:
+ RefCountedPropertyWrapper(CSSPropertyID prop, T* (RenderStyle::*getter)() const, void (RenderStyle::*setter)(PassRefPtr<T>))
+ : PropertyWrapperGetter<T*>(prop, getter)
+ , m_setter(setter)
+ {
+ }
+
+ virtual void blend(const AnimationBase* anim, RenderStyle* dst, const RenderStyle* a, const RenderStyle* b, double progress) const
+ {
+ (dst->*m_setter)(blendFunc(anim, (a->*PropertyWrapperGetter<T*>::m_getter)(), (b->*PropertyWrapperGetter<T*>::m_getter)(), progress));
+ }
+
+protected:
+ void (RenderStyle::*m_setter)(PassRefPtr<T>);
+};
+
+
+class PropertyWrapperClipPath : public RefCountedPropertyWrapper<ClipPathOperation> {
+public:
+ PropertyWrapperClipPath(CSSPropertyID prop, ClipPathOperation* (RenderStyle::*getter)() const, void (RenderStyle::*setter)(PassRefPtr<ClipPathOperation>))
+ : RefCountedPropertyWrapper<ClipPathOperation>(prop, getter, setter)
+ {
+ }
+};
+
+class PropertyWrapperShape : public RefCountedPropertyWrapper<ShapeValue> {
+public:
+ PropertyWrapperShape(CSSPropertyID prop, ShapeValue* (RenderStyle::*getter)() const, void (RenderStyle::*setter)(PassRefPtr<ShapeValue>))
+ : RefCountedPropertyWrapper<ShapeValue>(prop, getter, setter)
+ {
+ }
+};
+
+class StyleImagePropertyWrapper : public RefCountedPropertyWrapper<StyleImage> {
+public:
+ StyleImagePropertyWrapper(CSSPropertyID prop, StyleImage* (RenderStyle::*getter)() const, void (RenderStyle::*setter)(PassRefPtr<StyleImage>))
+ : RefCountedPropertyWrapper<StyleImage>(prop, getter, setter)
+ {
+ }
+
+ virtual bool equals(const RenderStyle* a, const RenderStyle* b) const
+ {
+ // If the style pointers are the same, don't bother doing the test.
+ // If either is null, return false. If both are null, return true.
+ if (a == b)
+ return true;
+ if (!a || !b)
+ return false;
+
+ StyleImage* imageA = (a->*m_getter)();
+ StyleImage* imageB = (b->*m_getter)();
+ return StyleImage::imagesEquivalent(imageA, imageB);
+ }
+};
+
+class PropertyWrapperColor : public PropertyWrapperGetter<Color> {
+public:
+ PropertyWrapperColor(CSSPropertyID prop, Color (RenderStyle::*getter)() const, void (RenderStyle::*setter)(const Color&))
+ : PropertyWrapperGetter<Color>(prop, getter)
+ , m_setter(setter)
+ {
+ }
+
+ virtual void blend(const AnimationBase* anim, RenderStyle* dst, const RenderStyle* a, const RenderStyle* b, double progress) const
+ {
+ (dst->*m_setter)(blendFunc(anim, (a->*PropertyWrapperGetter<Color>::m_getter)(), (b->*PropertyWrapperGetter<Color>::m_getter)(), progress));
+ }
+
+protected:
+ void (RenderStyle::*m_setter)(const Color&);
+};
+
+class PropertyWrapperAcceleratedOpacity : public PropertyWrapper<float> {
+public:
+ PropertyWrapperAcceleratedOpacity()
+ : PropertyWrapper<float>(CSSPropertyOpacity, &RenderStyle::opacity, &RenderStyle::setOpacity)
+ {
+ }
+
+ virtual bool animationIsAccelerated() const { return true; }
+
+ virtual void blend(const AnimationBase* anim, RenderStyle* dst, const RenderStyle* a, const RenderStyle* b, double progress) const
+ {
+ float fromOpacity = a->opacity();
+
+ // This makes sure we put the object being animated into a RenderLayer during the animation
+ dst->setOpacity(blendFunc(anim, (fromOpacity == 1) ? 0.999999f : fromOpacity, b->opacity(), progress));
+ }
+};
+
+class PropertyWrapperAcceleratedTransform : public PropertyWrapper<const TransformOperations&> {
+public:
+ PropertyWrapperAcceleratedTransform()
+ : PropertyWrapper<const TransformOperations&>(CSSPropertyWebkitTransform, &RenderStyle::transform, &RenderStyle::setTransform)
+ {
+ }
+
+ virtual bool animationIsAccelerated() const { return true; }
+
+ virtual void blend(const AnimationBase* anim, RenderStyle* dst, const RenderStyle* a, const RenderStyle* b, double progress) const
+ {
+ dst->setTransform(blendFunc(anim, a->transform(), b->transform(), progress));
+ }
+};
+
+class PropertyWrapperAcceleratedFilter : public PropertyWrapper<const FilterOperations&> {
+public:
+ PropertyWrapperAcceleratedFilter()
+ : PropertyWrapper<const FilterOperations&>(CSSPropertyWebkitFilter, &RenderStyle::filter, &RenderStyle::setFilter)
+ {
+ }
+
+ virtual bool animationIsAccelerated() const { return true; }
+
+ virtual void blend(const AnimationBase* anim, RenderStyle* dst, const RenderStyle* a, const RenderStyle* b, double progress) const
+ {
+ dst->setFilter(blendFunc(anim, a->filter(), b->filter(), progress));
+ }
+};
+
+class PropertyWrapperShadow : public AnimationPropertyWrapperBase {
+public:
+ PropertyWrapperShadow(CSSPropertyID prop, ShadowList* (RenderStyle::*getter)() const, void (RenderStyle::*setter)(PassRefPtr<ShadowList>))
+ : AnimationPropertyWrapperBase(prop)
+ , m_getter(getter)
+ , m_setter(setter)
+ {
+ }
+
+ virtual bool equals(const RenderStyle* a, const RenderStyle* b) const
+ {
+ const ShadowList* shadowA = (a->*m_getter)();
+ const ShadowList* shadowB = (b->*m_getter)();
+ if (shadowA == shadowB)
+ return true;
+ if (shadowA && shadowB)
+ return *shadowA == *shadowB;
+ return false;
+ }
+
+ virtual void blend(const AnimationBase* anim, RenderStyle* dst, const RenderStyle* a, const RenderStyle* b, double progress) const
+ {
+ (dst->*m_setter)(ShadowList::blend((a->*m_getter)(), (b->*m_getter)(), progress));
+ }
+
+ ShadowList* (RenderStyle::*m_getter)() const;
+ void (RenderStyle::*m_setter)(PassRefPtr<ShadowList>);
+};
+
+class PropertyWrapperMaybeInvalidColor : public AnimationPropertyWrapperBase {
+public:
+ PropertyWrapperMaybeInvalidColor(CSSPropertyID prop, Color (RenderStyle::*getter)() const, void (RenderStyle::*setter)(const Color&))
+ : AnimationPropertyWrapperBase(prop)
+ , m_getter(getter)
+ , m_setter(setter)
+ {
+ }
+
+ virtual bool equals(const RenderStyle* a, const RenderStyle* b) const
+ {
+ Color fromColor = (a->*m_getter)();
+ Color toColor = (b->*m_getter)();
+
+ if (!fromColor.isValid() && !toColor.isValid())
+ return true;
+
+ if (!fromColor.isValid())
+ fromColor = a->color();
+ if (!toColor.isValid())
+ toColor = b->color();
+
+ return fromColor == toColor;
+ }
+
+ virtual void blend(const AnimationBase* anim, RenderStyle* dst, const RenderStyle* a, const RenderStyle* b, double progress) const
+ {
+ Color fromColor = (a->*m_getter)();
+ Color toColor = (b->*m_getter)();
+
+ if (!fromColor.isValid() && !toColor.isValid())
+ return;
+
+ if (!fromColor.isValid())
+ fromColor = a->color();
+ if (!toColor.isValid())
+ toColor = b->color();
+ (dst->*m_setter)(blendFunc(anim, fromColor, toColor, progress));
+ }
+
+private:
+ Color (RenderStyle::*m_getter)() const;
+ void (RenderStyle::*m_setter)(const Color&);
+};
+
+
+enum MaybeInvalidColorTag { MaybeInvalidColor };
+class PropertyWrapperVisitedAffectedColor : public AnimationPropertyWrapperBase {
+public:
+ PropertyWrapperVisitedAffectedColor(CSSPropertyID prop, Color (RenderStyle::*getter)() const, void (RenderStyle::*setter)(const Color&),
+ Color (RenderStyle::*visitedGetter)() const, void (RenderStyle::*visitedSetter)(const Color&))
+ : AnimationPropertyWrapperBase(prop)
+ , m_wrapper(adoptPtr(new PropertyWrapperColor(prop, getter, setter)))
+ , m_visitedWrapper(adoptPtr(new PropertyWrapperColor(prop, visitedGetter, visitedSetter)))
+ {
+ }
+ PropertyWrapperVisitedAffectedColor(CSSPropertyID prop, MaybeInvalidColorTag, Color (RenderStyle::*getter)() const, void (RenderStyle::*setter)(const Color&),
+ Color (RenderStyle::*visitedGetter)() const, void (RenderStyle::*visitedSetter)(const Color&))
+ : AnimationPropertyWrapperBase(prop)
+ , m_wrapper(adoptPtr(new PropertyWrapperMaybeInvalidColor(prop, getter, setter)))
+ , m_visitedWrapper(adoptPtr(new PropertyWrapperMaybeInvalidColor(prop, visitedGetter, visitedSetter)))
+ {
+ }
+ virtual bool equals(const RenderStyle* a, const RenderStyle* b) const
+ {
+ return m_wrapper->equals(a, b) && m_visitedWrapper->equals(a, b);
+ }
+ virtual void blend(const AnimationBase* anim, RenderStyle* dst, const RenderStyle* a, const RenderStyle* b, double progress) const
+ {
+ m_wrapper->blend(anim, dst, a, b, progress);
+ m_visitedWrapper->blend(anim, dst, a, b, progress);
+ }
+
+private:
+ OwnPtr<AnimationPropertyWrapperBase> m_wrapper;
+ OwnPtr<AnimationPropertyWrapperBase> m_visitedWrapper;
+};
+
+// Wrapper base class for an animatable property in a FillLayer
+class FillLayerAnimationPropertyWrapperBase {
+public:
+ FillLayerAnimationPropertyWrapperBase()
+ {
+ }
+
+ virtual ~FillLayerAnimationPropertyWrapperBase() { }
+
+ virtual bool equals(const FillLayer*, const FillLayer*) const = 0;
+ virtual void blend(const AnimationBase*, FillLayer*, const FillLayer*, const FillLayer*, double) const = 0;
+};
+
+template <typename T>
+class FillLayerPropertyWrapperGetter : public FillLayerAnimationPropertyWrapperBase {
+ WTF_MAKE_NONCOPYABLE(FillLayerPropertyWrapperGetter);
+public:
+ FillLayerPropertyWrapperGetter(T (FillLayer::*getter)() const)
+ : m_getter(getter)
+ {
+ }
+
+ virtual bool equals(const FillLayer* a, const FillLayer* b) const
+ {
+ // If the style pointers are the same, don't bother doing the test.
+ // If either is null, return false. If both are null, return true.
+ if ((!a && !b) || a == b)
+ return true;
+ if (!a || !b)
+ return false;
+ return (a->*m_getter)() == (b->*m_getter)();
+ }
+
+protected:
+ T (FillLayer::*m_getter)() const;
+};
+
+template <typename T>
+class FillLayerPropertyWrapper : public FillLayerPropertyWrapperGetter<T> {
+public:
+ FillLayerPropertyWrapper(T (FillLayer::*getter)() const, void (FillLayer::*setter)(T))
+ : FillLayerPropertyWrapperGetter<T>(getter)
+ , m_setter(setter)
+ {
+ }
+
+ virtual void blend(const AnimationBase* anim, FillLayer* dst, const FillLayer* a, const FillLayer* b, double progress) const
+ {
+ (dst->*m_setter)(blendFunc(anim, (a->*FillLayerPropertyWrapperGetter<T>::m_getter)(), (b->*FillLayerPropertyWrapperGetter<T>::m_getter)(), progress));
+ }
+
+protected:
+ void (FillLayer::*m_setter)(T);
+};
+
+template <typename T>
+class FillLayerRefCountedPropertyWrapper : public FillLayerPropertyWrapperGetter<T*> {
+public:
+ FillLayerRefCountedPropertyWrapper(T* (FillLayer::*getter)() const, void (FillLayer::*setter)(PassRefPtr<T>))
+ : FillLayerPropertyWrapperGetter<T*>(getter)
+ , m_setter(setter)
+ {
+ }
+
+ virtual void blend(const AnimationBase* anim, FillLayer* dst, const FillLayer* a, const FillLayer* b, double progress) const
+ {
+ (dst->*m_setter)(blendFunc(anim, (a->*FillLayerPropertyWrapperGetter<T*>::m_getter)(), (b->*FillLayerPropertyWrapperGetter<T*>::m_getter)(), progress));
+ }
+
+protected:
+ void (FillLayer::*m_setter)(PassRefPtr<T>);
+};
+
+class FillLayerStyleImagePropertyWrapper : public FillLayerRefCountedPropertyWrapper<StyleImage> {
+public:
+ FillLayerStyleImagePropertyWrapper(StyleImage* (FillLayer::*getter)() const, void (FillLayer::*setter)(PassRefPtr<StyleImage>))
+ : FillLayerRefCountedPropertyWrapper<StyleImage>(getter, setter)
+ {
+ }
+
+ virtual bool equals(const FillLayer* a, const FillLayer* b) const
+ {
+ // If the style pointers are the same, don't bother doing the test.
+ // If either is null, return false. If both are null, return true.
+ if (a == b)
+ return true;
+ if (!a || !b)
+ return false;
+
+ StyleImage* imageA = (a->*m_getter)();
+ StyleImage* imageB = (b->*m_getter)();
+ return StyleImage::imagesEquivalent(imageA, imageB);
+ }
+};
+
+
+class FillLayersPropertyWrapper : public AnimationPropertyWrapperBase {
+public:
+ typedef const FillLayer* (RenderStyle::*LayersGetter)() const;
+ typedef FillLayer* (RenderStyle::*LayersAccessor)();
+
+ FillLayersPropertyWrapper(CSSPropertyID prop, LayersGetter getter, LayersAccessor accessor)
+ : AnimationPropertyWrapperBase(prop)
+ , m_layersGetter(getter)
+ , m_layersAccessor(accessor)
+ {
+ switch (prop) {
+ case CSSPropertyBackgroundPositionX:
+ case CSSPropertyWebkitMaskPositionX:
+ m_fillLayerPropertyWrapper = new FillLayerPropertyWrapper<Length>(&FillLayer::xPosition, &FillLayer::setXPosition);
+ break;
+ case CSSPropertyBackgroundPositionY:
+ case CSSPropertyWebkitMaskPositionY:
+ m_fillLayerPropertyWrapper = new FillLayerPropertyWrapper<Length>(&FillLayer::yPosition, &FillLayer::setYPosition);
+ break;
+ case CSSPropertyBackgroundSize:
+ case CSSPropertyWebkitBackgroundSize:
+ case CSSPropertyWebkitMaskSize:
+ m_fillLayerPropertyWrapper = new FillLayerPropertyWrapper<LengthSize>(&FillLayer::sizeLength, &FillLayer::setSizeLength);
+ break;
+ case CSSPropertyBackgroundImage:
+ m_fillLayerPropertyWrapper = new FillLayerStyleImagePropertyWrapper(&FillLayer::image, &FillLayer::setImage);
+ break;
+ default:
+ break;
+ }
+ }
+
+ virtual bool equals(const RenderStyle* a, const RenderStyle* b) const
+ {
+ const FillLayer* fromLayer = (a->*m_layersGetter)();
+ const FillLayer* toLayer = (b->*m_layersGetter)();
+
+ while (fromLayer && toLayer) {
+ if (!m_fillLayerPropertyWrapper->equals(fromLayer, toLayer))
+ return false;
+
+ fromLayer = fromLayer->next();
+ toLayer = toLayer->next();
+ }
+
+ return true;
+ }
+
+ virtual void blend(const AnimationBase* anim, RenderStyle* dst, const RenderStyle* a, const RenderStyle* b, double progress) const
+ {
+ const FillLayer* aLayer = (a->*m_layersGetter)();
+ const FillLayer* bLayer = (b->*m_layersGetter)();
+ FillLayer* dstLayer = (dst->*m_layersAccessor)();
+
+ while (aLayer && bLayer && dstLayer) {
+ m_fillLayerPropertyWrapper->blend(anim, dstLayer, aLayer, bLayer, progress);
+ aLayer = aLayer->next();
+ bLayer = bLayer->next();
+ dstLayer = dstLayer->next();
+ }
+ }
+
+private:
+ FillLayerAnimationPropertyWrapperBase* m_fillLayerPropertyWrapper;
+
+ LayersGetter m_layersGetter;
+ LayersAccessor m_layersAccessor;
+};
+
+class ShorthandPropertyWrapper : public AnimationPropertyWrapperBase {
+public:
+ ShorthandPropertyWrapper(CSSPropertyID property, const StylePropertyShorthand& shorthand)
+ : AnimationPropertyWrapperBase(property)
+ {
+ for (unsigned i = 0; i < shorthand.length(); ++i) {
+ AnimationPropertyWrapperBase* wrapper = wrapperForProperty(shorthand.properties()[i]);
+ if (wrapper)
+ m_propertyWrappers.append(wrapper);
+ }
+ }
+
+ virtual bool isShorthandWrapper() const { return true; }
+
+ virtual bool equals(const RenderStyle* a, const RenderStyle* b) const
+ {
+ Vector<AnimationPropertyWrapperBase*>::const_iterator end = m_propertyWrappers.end();
+ for (Vector<AnimationPropertyWrapperBase*>::const_iterator it = m_propertyWrappers.begin(); it != end; ++it) {
+ if (!(*it)->equals(a, b))
+ return false;
+ }
+ return true;
+ }
+
+ virtual void blend(const AnimationBase* anim, RenderStyle* dst, const RenderStyle* a, const RenderStyle* b, double progress) const
+ {
+ Vector<AnimationPropertyWrapperBase*>::const_iterator end = m_propertyWrappers.end();
+ for (Vector<AnimationPropertyWrapperBase*>::const_iterator it = m_propertyWrappers.begin(); it != end; ++it)
+ (*it)->blend(anim, dst, a, b, progress);
+ }
+
+ const Vector<AnimationPropertyWrapperBase*> propertyWrappers() const { return m_propertyWrappers; }
+
+private:
+ Vector<AnimationPropertyWrapperBase*> m_propertyWrappers;
+};
+
+class PropertyWrapperFlex : public AnimationPropertyWrapperBase {
+public:
+ PropertyWrapperFlex()
+ : AnimationPropertyWrapperBase(CSSPropertyFlex)
+ {
+ }
+
+ virtual bool equals(const RenderStyle* a, const RenderStyle* b) const
+ {
+ // If the style pointers are the same, don't bother doing the test.
+ // If either is null, return false. If both are null, return true.
+ if ((!a && !b) || a == b)
+ return true;
+ if (!a || !b)
+ return false;
+
+ return a->flexBasis() == b->flexBasis() && a->flexGrow() == b->flexGrow() && a->flexShrink() == b->flexShrink();
+ }
+
+ virtual void blend(const AnimationBase* anim, RenderStyle* dst, const RenderStyle* a, const RenderStyle* b, double progress) const
+ {
+ dst->setFlexBasis(blendFunc(anim, a->flexBasis(), b->flexBasis(), progress));
+ dst->setFlexGrow(blendFunc(anim, a->flexGrow(), b->flexGrow(), progress));
+ dst->setFlexShrink(blendFunc(anim, a->flexShrink(), b->flexShrink(), progress));
+ }
+};
+
+class PropertyWrapperSVGPaint : public AnimationPropertyWrapperBase {
+public:
+ PropertyWrapperSVGPaint(CSSPropertyID prop, const SVGPaint::SVGPaintType& (RenderStyle::*paintTypeGetter)() const, Color (RenderStyle::*getter)() const, void (RenderStyle::*setter)(const Color&))
+ : AnimationPropertyWrapperBase(prop)
+ , m_paintTypeGetter(paintTypeGetter)
+ , m_getter(getter)
+ , m_setter(setter)
+ {
+ }
+
+ virtual bool equals(const RenderStyle* a, const RenderStyle* b) const
+ {
+ if ((a->*m_paintTypeGetter)() != (b->*m_paintTypeGetter)())
+ return false;
+
+ // We only support animations between SVGPaints that are pure Color values.
+ // For everything else we must return true for this method, otherwise
+ // we will try to animate between values forever.
+ if ((a->*m_paintTypeGetter)() == SVGPaint::SVG_PAINTTYPE_RGBCOLOR) {
+ Color fromColor = (a->*m_getter)();
+ Color toColor = (b->*m_getter)();
+
+ if (!fromColor.isValid() && !toColor.isValid())
+ return true;
+
+ if (!fromColor.isValid())
+ fromColor = Color();
+ if (!toColor.isValid())
+ toColor = Color();
+
+ return fromColor == toColor;
+ }
+ return true;
+ }
+
+ virtual void blend(const AnimationBase* anim, RenderStyle* dst, const RenderStyle* a, const RenderStyle* b, double progress) const
+ {
+ if ((a->*m_paintTypeGetter)() != SVGPaint::SVG_PAINTTYPE_RGBCOLOR
+ || (b->*m_paintTypeGetter)() != SVGPaint::SVG_PAINTTYPE_RGBCOLOR)
+ return;
+
+ Color fromColor = (a->*m_getter)();
+ Color toColor = (b->*m_getter)();
+
+ if (!fromColor.isValid() && !toColor.isValid())
+ return;
+
+ if (!fromColor.isValid())
+ fromColor = Color();
+ if (!toColor.isValid())
+ toColor = Color();
+ (dst->*m_setter)(blendFunc(anim, fromColor, toColor, progress));
+ }
+
+private:
+ const SVGPaint::SVGPaintType& (RenderStyle::*m_paintTypeGetter)() const;
+ Color (RenderStyle::*m_getter)() const;
+ void (RenderStyle::*m_setter)(const Color&);
+};
+
+static void addShorthandProperties()
+{
+ static const CSSPropertyID animatableShorthandProperties[] = {
+ CSSPropertyBackground, // for background-color, background-position, background-image
+ CSSPropertyBackgroundPosition,
+ CSSPropertyFont, // for font-size, font-weight
+ CSSPropertyWebkitMask, // for mask-position
+ CSSPropertyWebkitMaskPosition,
+ CSSPropertyBorderTop, CSSPropertyBorderRight, CSSPropertyBorderBottom, CSSPropertyBorderLeft,
+ CSSPropertyBorderColor,
+ CSSPropertyBorderRadius,
+ CSSPropertyBorderWidth,
+ CSSPropertyBorder,
+ CSSPropertyBorderImage,
+ CSSPropertyBorderSpacing,
+ CSSPropertyListStyle, // for list-style-image
+ CSSPropertyMargin,
+ CSSPropertyOutline,
+ CSSPropertyPadding,
+ CSSPropertyWebkitTextStroke,
+ CSSPropertyWebkitColumnRule,
+ CSSPropertyWebkitBorderRadius,
+ CSSPropertyWebkitTransformOrigin
+ };
+
+ for (size_t i = 0; i < WTF_ARRAY_LENGTH(animatableShorthandProperties); ++i) {
+ CSSPropertyID propertyID = animatableShorthandProperties[i];
+ StylePropertyShorthand shorthand = shorthandForProperty(propertyID);
+ if (shorthand.length() > 0)
+ addPropertyWrapper(propertyID, new ShorthandPropertyWrapper(propertyID, shorthand));
+ }
+}
+
+void CSSPropertyAnimation::ensurePropertyMap()
+{
+ // FIXME: This data is never destroyed. Maybe we should ref count it and toss it when the last AnimationController is destroyed?
+ if (gPropertyWrappers)
+ return;
+
+ gPropertyWrappers = new Vector<AnimationPropertyWrapperBase*>();
+
+ // build the list of property wrappers to do the comparisons and blends
+ gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyLeft, &RenderStyle::left, &RenderStyle::setLeft));
+ gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyRight, &RenderStyle::right, &RenderStyle::setRight));
+ gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyTop, &RenderStyle::top, &RenderStyle::setTop));
+ gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyBottom, &RenderStyle::bottom, &RenderStyle::setBottom));
+
+ gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyWidth, &RenderStyle::width, &RenderStyle::setWidth));
+ gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyMinWidth, &RenderStyle::minWidth, &RenderStyle::setMinWidth));
+ gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyMaxWidth, &RenderStyle::maxWidth, &RenderStyle::setMaxWidth));
+
+ gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyHeight, &RenderStyle::height, &RenderStyle::setHeight));
+ gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyMinHeight, &RenderStyle::minHeight, &RenderStyle::setMinHeight));
+ gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyMaxHeight, &RenderStyle::maxHeight, &RenderStyle::setMaxHeight));
+
+ if (!RuntimeEnabledFeatures::webAnimationsCSSEnabled())
+ gPropertyWrappers->append(new PropertyWrapperFlex());
+
+ gPropertyWrappers->append(new PropertyWrapper<unsigned>(CSSPropertyBorderLeftWidth, &RenderStyle::borderLeftWidth, &RenderStyle::setBorderLeftWidth));
+ gPropertyWrappers->append(new PropertyWrapper<unsigned>(CSSPropertyBorderRightWidth, &RenderStyle::borderRightWidth, &RenderStyle::setBorderRightWidth));
+ gPropertyWrappers->append(new PropertyWrapper<unsigned>(CSSPropertyBorderTopWidth, &RenderStyle::borderTopWidth, &RenderStyle::setBorderTopWidth));
+ gPropertyWrappers->append(new PropertyWrapper<unsigned>(CSSPropertyBorderBottomWidth, &RenderStyle::borderBottomWidth, &RenderStyle::setBorderBottomWidth));
+ gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyMarginLeft, &RenderStyle::marginLeft, &RenderStyle::setMarginLeft));
+ gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyMarginRight, &RenderStyle::marginRight, &RenderStyle::setMarginRight));
+ gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyMarginTop, &RenderStyle::marginTop, &RenderStyle::setMarginTop));
+ gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyMarginBottom, &RenderStyle::marginBottom, &RenderStyle::setMarginBottom));
+ gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyPaddingLeft, &RenderStyle::paddingLeft, &RenderStyle::setPaddingLeft));
+ gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyPaddingRight, &RenderStyle::paddingRight, &RenderStyle::setPaddingRight));
+ gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyPaddingTop, &RenderStyle::paddingTop, &RenderStyle::setPaddingTop));
+ gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyPaddingBottom, &RenderStyle::paddingBottom, &RenderStyle::setPaddingBottom));
+ gPropertyWrappers->append(new PropertyWrapperVisitedAffectedColor(CSSPropertyColor, &RenderStyle::color, &RenderStyle::setColor, &RenderStyle::visitedLinkColor, &RenderStyle::setVisitedLinkColor));
+
+ gPropertyWrappers->append(new PropertyWrapperVisitedAffectedColor(CSSPropertyBackgroundColor, &RenderStyle::backgroundColor, &RenderStyle::setBackgroundColor, &RenderStyle::visitedLinkBackgroundColor, &RenderStyle::setVisitedLinkBackgroundColor));
+
+ gPropertyWrappers->append(new FillLayersPropertyWrapper(CSSPropertyBackgroundImage, &RenderStyle::backgroundLayers, &RenderStyle::accessBackgroundLayers));
+ gPropertyWrappers->append(new StyleImagePropertyWrapper(CSSPropertyListStyleImage, &RenderStyle::listStyleImage, &RenderStyle::setListStyleImage));
+ gPropertyWrappers->append(new StyleImagePropertyWrapper(CSSPropertyWebkitMaskImage, &RenderStyle::maskImage, &RenderStyle::setMaskImage));
+
+ gPropertyWrappers->append(new StyleImagePropertyWrapper(CSSPropertyBorderImageSource, &RenderStyle::borderImageSource, &RenderStyle::setBorderImageSource));
+ gPropertyWrappers->append(new PropertyWrapper<LengthBox>(CSSPropertyBorderImageSlice, &RenderStyle::borderImageSlices, &RenderStyle::setBorderImageSlices));
+ gPropertyWrappers->append(new PropertyWrapper<const BorderImageLengthBox&>(CSSPropertyBorderImageWidth, &RenderStyle::borderImageWidth, &RenderStyle::setBorderImageWidth));
+ gPropertyWrappers->append(new PropertyWrapper<const BorderImageLengthBox&>(CSSPropertyBorderImageOutset, &RenderStyle::borderImageOutset, &RenderStyle::setBorderImageOutset));
+
+ gPropertyWrappers->append(new StyleImagePropertyWrapper(CSSPropertyWebkitMaskBoxImageSource, &RenderStyle::maskBoxImageSource, &RenderStyle::setMaskBoxImageSource));
+ gPropertyWrappers->append(new PropertyWrapper<LengthBox>(CSSPropertyWebkitMaskBoxImageSlice, &RenderStyle::maskBoxImageSlices, &RenderStyle::setMaskBoxImageSlices));
+ gPropertyWrappers->append(new PropertyWrapper<const BorderImageLengthBox&>(CSSPropertyWebkitMaskBoxImageWidth, &RenderStyle::maskBoxImageWidth, &RenderStyle::setMaskBoxImageWidth));
+ gPropertyWrappers->append(new PropertyWrapper<const BorderImageLengthBox&>(CSSPropertyWebkitMaskBoxImageOutset, &RenderStyle::maskBoxImageOutset, &RenderStyle::setMaskBoxImageOutset));
+
+ gPropertyWrappers->append(new FillLayersPropertyWrapper(CSSPropertyBackgroundPositionX, &RenderStyle::backgroundLayers, &RenderStyle::accessBackgroundLayers));
+ gPropertyWrappers->append(new FillLayersPropertyWrapper(CSSPropertyBackgroundPositionY, &RenderStyle::backgroundLayers, &RenderStyle::accessBackgroundLayers));
+ gPropertyWrappers->append(new FillLayersPropertyWrapper(CSSPropertyBackgroundSize, &RenderStyle::backgroundLayers, &RenderStyle::accessBackgroundLayers));
+ gPropertyWrappers->append(new FillLayersPropertyWrapper(CSSPropertyWebkitBackgroundSize, &RenderStyle::backgroundLayers, &RenderStyle::accessBackgroundLayers));
+
+ gPropertyWrappers->append(new FillLayersPropertyWrapper(CSSPropertyWebkitMaskPositionX, &RenderStyle::maskLayers, &RenderStyle::accessMaskLayers));
+ gPropertyWrappers->append(new FillLayersPropertyWrapper(CSSPropertyWebkitMaskPositionY, &RenderStyle::maskLayers, &RenderStyle::accessMaskLayers));
+ gPropertyWrappers->append(new FillLayersPropertyWrapper(CSSPropertyWebkitMaskSize, &RenderStyle::maskLayers, &RenderStyle::accessMaskLayers));
+
+ gPropertyWrappers->append(new PropertyWrapper<LengthPoint>(CSSPropertyObjectPosition, &RenderStyle::objectPosition, &RenderStyle::setObjectPosition));
+
+ gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyFontSize,
+ // Must pass a specified size to setFontSize if Text Autosizing is enabled, but a computed size
+ // if text zoom is enabled (if neither is enabled it's irrelevant as they're probably the same).
+ // FIXME: Should we introduce an option to pass the computed font size here, allowing consumers to
+ // enable text zoom rather than Text Autosizing? See http://crbug.com/227545.
+ &RenderStyle::specifiedFontSize,
+ &RenderStyle::setFontSize));
+ gPropertyWrappers->append(new PropertyWrapper<unsigned short>(CSSPropertyWebkitColumnRuleWidth, &RenderStyle::columnRuleWidth, &RenderStyle::setColumnRuleWidth));
+ gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyWebkitColumnGap, &RenderStyle::columnGap, &RenderStyle::setColumnGap));
+ gPropertyWrappers->append(new PropertyWrapper<unsigned short>(CSSPropertyWebkitColumnCount, &RenderStyle::columnCount, &RenderStyle::setColumnCount));
+ gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyWebkitColumnWidth, &RenderStyle::columnWidth, &RenderStyle::setColumnWidth));
+ gPropertyWrappers->append(new PropertyWrapper<short>(CSSPropertyWebkitBorderHorizontalSpacing, &RenderStyle::horizontalBorderSpacing, &RenderStyle::setHorizontalBorderSpacing));
+ gPropertyWrappers->append(new PropertyWrapper<short>(CSSPropertyWebkitBorderVerticalSpacing, &RenderStyle::verticalBorderSpacing, &RenderStyle::setVerticalBorderSpacing));
+ gPropertyWrappers->append(new PropertyWrapper<int>(CSSPropertyZIndex, &RenderStyle::zIndex, &RenderStyle::setZIndex));
+ gPropertyWrappers->append(new PropertyWrapper<short>(CSSPropertyOrphans, &RenderStyle::orphans, &RenderStyle::setOrphans));
+ gPropertyWrappers->append(new PropertyWrapper<short>(CSSPropertyWidows, &RenderStyle::widows, &RenderStyle::setWidows));
+ gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyLineHeight, &RenderStyle::specifiedLineHeight, &RenderStyle::setLineHeight));
+ gPropertyWrappers->append(new PropertyWrapper<int>(CSSPropertyOutlineOffset, &RenderStyle::outlineOffset, &RenderStyle::setOutlineOffset));
+ gPropertyWrappers->append(new PropertyWrapper<unsigned short>(CSSPropertyOutlineWidth, &RenderStyle::outlineWidth, &RenderStyle::setOutlineWidth));
+ gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyLetterSpacing, &RenderStyle::letterSpacing, &RenderStyle::setLetterSpacing));
+ gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyWordSpacing, &RenderStyle::wordSpacing, &RenderStyle::setWordSpacing));
+ gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyTextIndent, &RenderStyle::textIndent, &RenderStyle::setTextIndent));
+
+ gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyWebkitPerspective, &RenderStyle::perspective, &RenderStyle::setPerspective));
+ gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyWebkitPerspectiveOriginX, &RenderStyle::perspectiveOriginX, &RenderStyle::setPerspectiveOriginX));
+ gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyWebkitPerspectiveOriginY, &RenderStyle::perspectiveOriginY, &RenderStyle::setPerspectiveOriginY));
+ gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyWebkitTransformOriginX, &RenderStyle::transformOriginX, &RenderStyle::setTransformOriginX));
+ gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyWebkitTransformOriginY, &RenderStyle::transformOriginY, &RenderStyle::setTransformOriginY));
+ gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyWebkitTransformOriginZ, &RenderStyle::transformOriginZ, &RenderStyle::setTransformOriginZ));
+ gPropertyWrappers->append(new PropertyWrapper<LengthSize>(CSSPropertyBorderTopLeftRadius, &RenderStyle::borderTopLeftRadius, &RenderStyle::setBorderTopLeftRadius));
+ gPropertyWrappers->append(new PropertyWrapper<LengthSize>(CSSPropertyBorderTopRightRadius, &RenderStyle::borderTopRightRadius, &RenderStyle::setBorderTopRightRadius));
+ gPropertyWrappers->append(new PropertyWrapper<LengthSize>(CSSPropertyBorderBottomLeftRadius, &RenderStyle::borderBottomLeftRadius, &RenderStyle::setBorderBottomLeftRadius));
+ gPropertyWrappers->append(new PropertyWrapper<LengthSize>(CSSPropertyBorderBottomRightRadius, &RenderStyle::borderBottomRightRadius, &RenderStyle::setBorderBottomRightRadius));
+ gPropertyWrappers->append(new PropertyWrapper<EVisibility>(CSSPropertyVisibility, &RenderStyle::visibility, &RenderStyle::setVisibility));
+ gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyZoom, &RenderStyle::zoom, &RenderStyle::setZoomWithoutReturnValue));
+
+ gPropertyWrappers->append(new PropertyWrapper<LengthBox>(CSSPropertyClip, &RenderStyle::clip, &RenderStyle::setClip));
+
+ gPropertyWrappers->append(new PropertyWrapperAcceleratedOpacity());
+ gPropertyWrappers->append(new PropertyWrapperAcceleratedTransform());
+ gPropertyWrappers->append(new PropertyWrapperAcceleratedFilter());
+
+ gPropertyWrappers->append(new PropertyWrapperClipPath(CSSPropertyWebkitClipPath, &RenderStyle::clipPath, &RenderStyle::setClipPath));
+
+ gPropertyWrappers->append(new PropertyWrapperShape(CSSPropertyShapeInside, &RenderStyle::shapeInside, &RenderStyle::setShapeInside));
+ gPropertyWrappers->append(new PropertyWrapperShape(CSSPropertyShapeOutside, &RenderStyle::shapeOutside, &RenderStyle::setShapeOutside));
+ gPropertyWrappers->append(new NonNegativeLengthWrapper(CSSPropertyShapeMargin, &RenderStyle::shapeMargin, &RenderStyle::setShapeMargin));
+ gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyShapeImageThreshold, &RenderStyle::shapeImageThreshold, &RenderStyle::setShapeImageThreshold));
+
+ gPropertyWrappers->append(new PropertyWrapperVisitedAffectedColor(CSSPropertyWebkitColumnRuleColor, MaybeInvalidColor, &RenderStyle::columnRuleColor, &RenderStyle::setColumnRuleColor, &RenderStyle::visitedLinkColumnRuleColor, &RenderStyle::setVisitedLinkColumnRuleColor));
+ gPropertyWrappers->append(new PropertyWrapperVisitedAffectedColor(CSSPropertyWebkitTextStrokeColor, MaybeInvalidColor, &RenderStyle::textStrokeColor, &RenderStyle::setTextStrokeColor, &RenderStyle::visitedLinkTextStrokeColor, &RenderStyle::setVisitedLinkTextStrokeColor));
+ gPropertyWrappers->append(new PropertyWrapperVisitedAffectedColor(CSSPropertyBorderLeftColor, MaybeInvalidColor, &RenderStyle::borderLeftColor, &RenderStyle::setBorderLeftColor, &RenderStyle::visitedLinkBorderLeftColor, &RenderStyle::setVisitedLinkBorderLeftColor));
+ gPropertyWrappers->append(new PropertyWrapperVisitedAffectedColor(CSSPropertyBorderRightColor, MaybeInvalidColor, &RenderStyle::borderRightColor, &RenderStyle::setBorderRightColor, &RenderStyle::visitedLinkBorderRightColor, &RenderStyle::setVisitedLinkBorderRightColor));
+ gPropertyWrappers->append(new PropertyWrapperVisitedAffectedColor(CSSPropertyBorderTopColor, MaybeInvalidColor, &RenderStyle::borderTopColor, &RenderStyle::setBorderTopColor, &RenderStyle::visitedLinkBorderTopColor, &RenderStyle::setVisitedLinkBorderTopColor));
+ gPropertyWrappers->append(new PropertyWrapperVisitedAffectedColor(CSSPropertyBorderBottomColor, MaybeInvalidColor, &RenderStyle::borderBottomColor, &RenderStyle::setBorderBottomColor, &RenderStyle::visitedLinkBorderBottomColor, &RenderStyle::setVisitedLinkBorderBottomColor));
+ gPropertyWrappers->append(new PropertyWrapperVisitedAffectedColor(CSSPropertyOutlineColor, MaybeInvalidColor, &RenderStyle::outlineColor, &RenderStyle::setOutlineColor, &RenderStyle::visitedLinkOutlineColor, &RenderStyle::setVisitedLinkOutlineColor));
+
+ gPropertyWrappers->append(new PropertyWrapperShadow(CSSPropertyBoxShadow, &RenderStyle::boxShadow, &RenderStyle::setBoxShadow));
+ gPropertyWrappers->append(new PropertyWrapperShadow(CSSPropertyWebkitBoxShadow, &RenderStyle::boxShadow, &RenderStyle::setBoxShadow));
+ gPropertyWrappers->append(new PropertyWrapperShadow(CSSPropertyTextShadow, &RenderStyle::textShadow, &RenderStyle::setTextShadow));
+
+ gPropertyWrappers->append(new PropertyWrapperSVGPaint(CSSPropertyFill, &RenderStyle::fillPaintType, &RenderStyle::fillPaintColor, &RenderStyle::setFillPaintColor));
+ gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyFillOpacity, &RenderStyle::fillOpacity, &RenderStyle::setFillOpacity));
+
+ gPropertyWrappers->append(new PropertyWrapperSVGPaint(CSSPropertyStroke, &RenderStyle::strokePaintType, &RenderStyle::strokePaintColor, &RenderStyle::setStrokePaintColor));
+ gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyStrokeOpacity, &RenderStyle::strokeOpacity, &RenderStyle::setStrokeOpacity));
+ gPropertyWrappers->append(new PropertyWrapper<SVGLength>(CSSPropertyStrokeWidth, &RenderStyle::strokeWidth, &RenderStyle::setStrokeWidth));
+ gPropertyWrappers->append(new PropertyWrapper< Vector<SVGLength> >(CSSPropertyStrokeDasharray, &RenderStyle::strokeDashArray, &RenderStyle::setStrokeDashArray));
+ gPropertyWrappers->append(new PropertyWrapper<SVGLength>(CSSPropertyStrokeDashoffset, &RenderStyle::strokeDashOffset, &RenderStyle::setStrokeDashOffset));
+ gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyStrokeMiterlimit, &RenderStyle::strokeMiterLimit, &RenderStyle::setStrokeMiterLimit));
+
+ gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyFloodOpacity, &RenderStyle::floodOpacity, &RenderStyle::setFloodOpacity));
+ gPropertyWrappers->append(new PropertyWrapperMaybeInvalidColor(CSSPropertyFloodColor, &RenderStyle::floodColor, &RenderStyle::setFloodColor));
+
+ gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyStopOpacity, &RenderStyle::stopOpacity, &RenderStyle::setStopOpacity));
+ gPropertyWrappers->append(new PropertyWrapperMaybeInvalidColor(CSSPropertyStopColor, &RenderStyle::stopColor, &RenderStyle::setStopColor));
+
+ gPropertyWrappers->append(new PropertyWrapperMaybeInvalidColor(CSSPropertyLightingColor, &RenderStyle::lightingColor, &RenderStyle::setLightingColor));
+
+ gPropertyWrappers->append(new PropertyWrapper<SVGLength>(CSSPropertyBaselineShift, &RenderStyle::baselineShiftValue, &RenderStyle::setBaselineShiftValue));
+ gPropertyWrappers->append(new PropertyWrapper<SVGLength>(CSSPropertyKerning, &RenderStyle::kerning, &RenderStyle::setKerning));
+
+ if (RuntimeEnabledFeatures::webAnimationsCSSEnabled()) {
+ gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyFlexGrow, &RenderStyle::flexGrow, &RenderStyle::setFlexGrow));
+ gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyFlexShrink, &RenderStyle::flexShrink, &RenderStyle::setFlexShrink));
+ gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyFlexBasis, &RenderStyle::flexBasis, &RenderStyle::setFlexBasis));
+ }
+
+ // TODO:
+ //
+ // CSSPropertyVerticalAlign
+ //
+ // Compound properties that have components that should be animatable:
+ //
+ // CSSPropertyWebkitColumns
+ // CSSPropertyWebkitBoxReflect
+
+ // Make sure unused slots have a value
+ for (unsigned int i = 0; i < static_cast<unsigned int>(numCSSProperties); ++i)
+ gPropertyWrapperMap[i] = cInvalidPropertyWrapperIndex;
+
+ // First we put the non-shorthand property wrappers into the map, so the shorthand-building
+ // code can find them.
+ size_t n = gPropertyWrappers->size();
+ for (unsigned int i = 0; i < n; ++i) {
+ CSSPropertyID property = (*gPropertyWrappers)[i]->property();
+ ASSERT_WITH_MESSAGE(RuntimeEnabledFeatures::webAnimationsCSSEnabled() || CSSAnimations::isAnimatableProperty(property), "%s is not whitelisted for animation", getPropertyNameString(property).utf8().data());
+ ASSERT(property - firstCSSProperty < numCSSProperties);
+ gPropertyWrapperMap[property - firstCSSProperty] = i;
+ }
+
+ // Now add the shorthand wrappers.
+ addShorthandProperties();
+}
+
+// Returns true if we need to start animation timers
+bool CSSPropertyAnimation::blendProperties(const AnimationBase* anim, CSSPropertyID prop, RenderStyle* dst, const RenderStyle* a, const RenderStyle* b, double progress)
+{
+ ASSERT(prop != CSSPropertyInvalid);
+
+ ensurePropertyMap();
+
+ AnimationPropertyWrapperBase* wrapper = wrapperForProperty(prop);
+ if (wrapper) {
+ wrapper->blend(anim, dst, a, b, progress);
+ return !wrapper->animationIsAccelerated() || !anim->isAccelerated();
+ }
+
+ return false;
+}
+
+bool CSSPropertyAnimation::animationOfPropertyIsAccelerated(CSSPropertyID prop)
+{
+ ensurePropertyMap();
+ AnimationPropertyWrapperBase* wrapper = wrapperForProperty(prop);
+ return wrapper ? wrapper->animationIsAccelerated() : false;
+}
+
+bool CSSPropertyAnimation::propertiesEqual(CSSPropertyID prop, const RenderStyle* a, const RenderStyle* b)
+{
+ ensurePropertyMap();
+
+ AnimationPropertyWrapperBase* wrapper = wrapperForProperty(prop);
+ if (wrapper)
+ return wrapper->equals(a, b);
+ return true;
+}
+
+CSSPropertyID CSSPropertyAnimation::getPropertyAtIndex(int i, bool& isShorthand)
+{
+ ensurePropertyMap();
+
+ if (i < 0 || i >= getNumProperties())
+ return CSSPropertyInvalid;
+
+ AnimationPropertyWrapperBase* wrapper = (*gPropertyWrappers)[i];
+ isShorthand = wrapper->isShorthandWrapper();
+ return wrapper->property();
+}
+
+int CSSPropertyAnimation::getNumProperties()
+{
+ ensurePropertyMap();
+
+ return gPropertyWrappers->size();
+}
+
+}
diff --git a/chromium/third_party/WebKit/Source/core/page/animation/CSSPropertyAnimation.h b/chromium/third_party/WebKit/Source/core/frame/animation/CSSPropertyAnimation.h
index 6ffd75c1a83..6ffd75c1a83 100644
--- a/chromium/third_party/WebKit/Source/core/page/animation/CSSPropertyAnimation.h
+++ b/chromium/third_party/WebKit/Source/core/frame/animation/CSSPropertyAnimation.h
diff --git a/chromium/third_party/WebKit/Source/core/frame/animation/CompositeAnimation.cpp b/chromium/third_party/WebKit/Source/core/frame/animation/CompositeAnimation.cpp
new file mode 100644
index 00000000000..f20f6856683
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/animation/CompositeAnimation.cpp
@@ -0,0 +1,510 @@
+/*
+ * Copyright (C) 2007 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/frame/animation/CompositeAnimation.h"
+
+#include "CSSPropertyNames.h"
+#include "core/frame/animation/AnimationControllerPrivate.h"
+#include "core/frame/animation/CSSPropertyAnimation.h"
+#include "core/rendering/style/RenderStyle.h"
+
+namespace WebCore {
+
+CompositeAnimation::~CompositeAnimation()
+{
+ // Toss the refs to all animations, but make sure we remove them from
+ // any waiting lists first.
+
+ clearRenderer();
+ m_transitions.clear();
+ m_keyframeAnimations.clear();
+}
+
+void CompositeAnimation::clearRenderer()
+{
+ if (!m_transitions.isEmpty()) {
+ // Clear the renderers from all running animations, in case we are in the middle of
+ // an animation callback (see https://bugs.webkit.org/show_bug.cgi?id=22052)
+ CSSPropertyTransitionsMap::const_iterator transitionsEnd = m_transitions.end();
+ for (CSSPropertyTransitionsMap::const_iterator it = m_transitions.begin(); it != transitionsEnd; ++it) {
+ ImplicitAnimation* transition = it->value.get();
+ animationController()->animationWillBeRemoved(transition);
+ transition->clear();
+ }
+ }
+ if (!m_keyframeAnimations.isEmpty()) {
+ AnimationNameMap::const_iterator animationsEnd = m_keyframeAnimations.end();
+ for (AnimationNameMap::const_iterator it = m_keyframeAnimations.begin(); it != animationsEnd; ++it) {
+ KeyframeAnimation* anim = it->value.get();
+ animationController()->animationWillBeRemoved(anim);
+ anim->clear();
+ }
+ }
+}
+
+void CompositeAnimation::updateTransitions(RenderObject& renderer, RenderStyle* currentStyle, RenderStyle& targetStyle)
+{
+ // If currentStyle is null or there are no old or new transitions, just skip it
+ if (!currentStyle || (!targetStyle.transitions() && m_transitions.isEmpty()))
+ return;
+
+ // Mark all existing transitions as no longer active. We will mark the still active ones
+ // in the next loop and then toss the ones that didn't get marked.
+ CSSPropertyTransitionsMap::const_iterator end = m_transitions.end();
+ for (CSSPropertyTransitionsMap::const_iterator it = m_transitions.begin(); it != end; ++it)
+ it->value->setActive(false);
+
+ RefPtr<RenderStyle> modifiedCurrentStyle;
+
+ // Check to see if we need to update the active transitions
+ if (targetStyle.transitions()) {
+ for (size_t i = 0; i < targetStyle.transitions()->size(); ++i) {
+ const CSSAnimationData* anim = targetStyle.transitions()->animation(i);
+ bool isActiveTransition = anim->duration() || anim->delay() > 0;
+
+ CSSAnimationData::AnimationMode mode = anim->animationMode();
+ if (mode == CSSAnimationData::AnimateNone)
+ continue;
+
+ CSSPropertyID prop = anim->property();
+
+ bool all = mode == CSSAnimationData::AnimateAll;
+
+ // Handle both the 'all' and single property cases. For the single prop case, we make only one pass
+ // through the loop.
+ for (int propertyIndex = 0; propertyIndex < CSSPropertyAnimation::getNumProperties(); ++propertyIndex) {
+ if (all) {
+ // Get the next property which is not a shorthand.
+ bool isShorthand;
+ prop = CSSPropertyAnimation::getPropertyAtIndex(propertyIndex, isShorthand);
+ if (isShorthand)
+ continue;
+ }
+
+ // ImplicitAnimations are always hashed by actual properties, never animateAll.
+ ASSERT(prop >= firstCSSProperty && prop < (firstCSSProperty + numCSSProperties));
+
+ // If there is a running animation for this property, the transition is overridden
+ // and we have to use the unanimatedStyle from the animation. We do the test
+ // against the unanimated style here, but we "override" the transition later.
+ RefPtr<KeyframeAnimation> keyframeAnim = getAnimationForProperty(prop);
+ RenderStyle* fromStyle = keyframeAnim ? keyframeAnim->unanimatedStyle() : currentStyle;
+
+ // See if there is a current transition for this prop
+ ImplicitAnimation* implAnim = m_transitions.get(prop);
+ bool equal = true;
+
+ if (implAnim) {
+ // If we are post active don't bother setting the active flag. This will cause
+ // this animation to get removed at the end of this function.
+ if (!implAnim->postActive())
+ implAnim->setActive(true);
+
+ // This might be a transition that is just finishing. That would be the case
+ // if it were postActive. But we still need to check for equality because
+ // it could be just finishing AND changing to a new goal state.
+ //
+ // This implAnim might also not be an already running transition. It might be
+ // newly added to the list in a previous iteration. This would happen if
+ // you have both an explicit transition-property and 'all' in the same
+ // list. In this case, the latter one overrides the earlier one, so we
+ // behave as though this is a running animation being replaced.
+ if (!implAnim->isTargetPropertyEqual(prop, &targetStyle)) {
+ // For accelerated animations we need to return a new RenderStyle with the _current_ value
+ // of the property, so that restarted transitions use the correct starting point.
+ if (CSSPropertyAnimation::animationOfPropertyIsAccelerated(prop) && implAnim->isAccelerated()) {
+ if (!modifiedCurrentStyle)
+ modifiedCurrentStyle = RenderStyle::clone(currentStyle);
+
+ implAnim->blendPropertyValueInStyle(prop, modifiedCurrentStyle.get());
+ }
+ animationController()->animationWillBeRemoved(implAnim);
+ m_transitions.remove(prop);
+ equal = false;
+ }
+ } else {
+ // We need to start a transition if it is active and the properties don't match
+ equal = !isActiveTransition || CSSPropertyAnimation::propertiesEqual(prop, fromStyle, &targetStyle);
+ }
+
+ // We can be in this loop with an inactive transition (!isActiveTransition). We need
+ // to do that to check to see if we are canceling a transition. But we don't want to
+ // start one of the inactive transitions. So short circuit that here. (See
+ // <https://bugs.webkit.org/show_bug.cgi?id=24787>
+ if (!equal && isActiveTransition) {
+ // Add the new transition
+ m_transitions.set(prop, ImplicitAnimation::create(const_cast<CSSAnimationData*>(anim), prop, renderer, this, modifiedCurrentStyle ? modifiedCurrentStyle.get() : fromStyle));
+ }
+
+ // We only need one pass for the single prop case
+ if (!all)
+ break;
+ }
+ }
+ }
+
+ // Make a list of transitions to be removed
+ Vector<int> toBeRemoved;
+ end = m_transitions.end();
+ for (CSSPropertyTransitionsMap::const_iterator it = m_transitions.begin(); it != end; ++it) {
+ ImplicitAnimation* anim = it->value.get();
+ if (!anim->active()) {
+ animationController()->animationWillBeRemoved(anim);
+ toBeRemoved.append(anim->animatingProperty());
+ }
+ }
+
+ // Now remove the transitions from the list
+ for (size_t j = 0; j < toBeRemoved.size(); ++j)
+ m_transitions.remove(toBeRemoved[j]);
+}
+
+void CompositeAnimation::updateKeyframeAnimations(RenderObject& renderer, RenderStyle* currentStyle, RenderStyle& targetStyle)
+{
+ // Nothing to do if we don't have any animations, and didn't have any before
+ if (m_keyframeAnimations.isEmpty() && !targetStyle.hasAnimations())
+ return;
+
+ AnimationNameMap::const_iterator kfend = m_keyframeAnimations.end();
+
+ if (currentStyle && currentStyle->hasAnimations() && targetStyle.hasAnimations() && *(currentStyle->animations()) == *(targetStyle.animations())) {
+ // The current and target animations are the same so we just need to toss any
+ // animation which is finished (postActive).
+ for (AnimationNameMap::const_iterator it = m_keyframeAnimations.begin(); it != kfend; ++it) {
+ if (it->value->postActive())
+ it->value->setIndex(-1);
+ }
+ } else {
+ // Mark all existing animations as no longer active.
+ for (AnimationNameMap::const_iterator it = m_keyframeAnimations.begin(); it != kfend; ++it)
+ it->value->setIndex(-1);
+
+ // Toss the animation order map.
+ m_keyframeAnimationOrderList.clear();
+
+ DEFINE_STATIC_LOCAL(const AtomicString, none, ("none", AtomicString::ConstructFromLiteral));
+
+ // Now mark any still active animations as active and add any new animations.
+ if (targetStyle.animations()) {
+ int numAnims = targetStyle.animations()->size();
+ for (int i = 0; i < numAnims; ++i) {
+ const CSSAnimationData* anim = targetStyle.animations()->animation(i);
+ if (!anim->isValidAnimation())
+ continue;
+
+ // See if there is a current animation for this name.
+ AtomicString name(anim->name());
+ RefPtr<KeyframeAnimation> keyframeAnim = m_keyframeAnimations.get(name);
+ if (keyframeAnim) {
+ // If this animation is postActive, skip it so it gets removed at the end of this function.
+ if (keyframeAnim->postActive())
+ continue;
+
+ // This one is still active.
+
+ // Animations match, but play states may differ. Update if needed.
+ keyframeAnim->updatePlayState(anim->playState());
+
+ // Set the saved animation to this new one, just in case the play state has changed.
+ keyframeAnim->setAnimation(anim);
+ keyframeAnim->setIndex(i);
+ } else if ((anim->duration() || anim->delay()) && anim->iterationCount() && name != none) {
+ keyframeAnim = KeyframeAnimation::create(const_cast<CSSAnimationData*>(anim), renderer, i, this, targetStyle);
+ m_keyframeAnimations.set(name, keyframeAnim);
+ }
+
+ // Add this to the animation order map.
+ if (keyframeAnim)
+ m_keyframeAnimationOrderList.append(name);
+ }
+ }
+ }
+
+ // Make a list of animations to be removed.
+ Vector<AtomicString> animsToBeRemoved;
+ kfend = m_keyframeAnimations.end();
+ for (AnimationNameMap::const_iterator it = m_keyframeAnimations.begin(); it != kfend; ++it) {
+ KeyframeAnimation* keyframeAnim = it->value.get();
+ if (keyframeAnim->index() < 0) {
+ animsToBeRemoved.append(keyframeAnim->name());
+ animationController()->animationWillBeRemoved(keyframeAnim);
+ keyframeAnim->clear();
+ }
+ }
+
+ // Now remove the animations from the list, and keep stale keys out of the order list.
+ if (animsToBeRemoved.size()) {
+ for (size_t j = 0; j < animsToBeRemoved.size(); ++j) {
+ ASSERT(m_keyframeAnimations.contains(animsToBeRemoved[j]));
+ m_keyframeAnimations.remove(animsToBeRemoved[j]);
+ }
+ Vector<AtomicString> newOrderList;
+ for (size_t j = 0; j < m_keyframeAnimationOrderList.size(); ++j) {
+ AtomicString key = m_keyframeAnimationOrderList[j];
+ if (m_keyframeAnimations.contains(key))
+ newOrderList.append(key);
+ }
+ m_keyframeAnimationOrderList.swap(newOrderList);
+ }
+}
+
+PassRefPtr<RenderStyle> CompositeAnimation::animate(RenderObject& renderer, RenderStyle* currentStyle, RenderStyle& targetStyle)
+{
+ RefPtr<RenderStyle> resultStyle;
+
+ // We don't do any transitions if we don't have a currentStyle (on startup).
+ updateTransitions(renderer, currentStyle, targetStyle);
+ updateKeyframeAnimations(renderer, currentStyle, targetStyle);
+
+ if (currentStyle) {
+ // Now that we have transition objects ready, let them know about the new goal state. We want them
+ // to fill in a RenderStyle*& only if needed.
+ if (!m_transitions.isEmpty()) {
+ CSSPropertyTransitionsMap::const_iterator end = m_transitions.end();
+ for (CSSPropertyTransitionsMap::const_iterator it = m_transitions.begin(); it != end; ++it) {
+ if (ImplicitAnimation* anim = it->value.get())
+ anim->animate(this, &renderer, currentStyle, &targetStyle, resultStyle);
+ }
+ }
+ }
+
+ // Now that we have animation objects ready, let them know about the new goal state. We want them
+ // to fill in a RenderStyle*& only if needed.
+ for (Vector<AtomicString>::const_iterator it = m_keyframeAnimationOrderList.begin(); it != m_keyframeAnimationOrderList.end(); ++it) {
+ RefPtr<KeyframeAnimation> keyframeAnim = m_keyframeAnimations.get(*it);
+ ASSERT(keyframeAnim);
+ keyframeAnim->animate(this, &renderer, currentStyle, &targetStyle, resultStyle);
+ }
+
+ return resultStyle ? resultStyle.release() : PassRefPtr<RenderStyle>(targetStyle);
+}
+
+PassRefPtr<RenderStyle> CompositeAnimation::getAnimatedStyle() const
+{
+ RefPtr<RenderStyle> resultStyle;
+ CSSPropertyTransitionsMap::const_iterator end = m_transitions.end();
+ for (CSSPropertyTransitionsMap::const_iterator it = m_transitions.begin(); it != end; ++it) {
+ if (ImplicitAnimation* implicitAnimation = it->value.get())
+ implicitAnimation->getAnimatedStyle(resultStyle);
+ }
+
+ for (Vector<AtomicString>::const_iterator it = m_keyframeAnimationOrderList.begin(); it != m_keyframeAnimationOrderList.end(); ++it) {
+ RefPtr<KeyframeAnimation> keyframeAnimation = m_keyframeAnimations.get(*it);
+ ASSERT(keyframeAnimation);
+ keyframeAnimation->getAnimatedStyle(resultStyle);
+ }
+
+ return resultStyle;
+}
+
+double CompositeAnimation::timeToNextService() const
+{
+ // Returns the time at which next service is required. -1 means no service is required. 0 means
+ // service is required now, and > 0 means service is required that many seconds in the future.
+ double minT = -1;
+
+ if (!m_transitions.isEmpty()) {
+ CSSPropertyTransitionsMap::const_iterator transitionsEnd = m_transitions.end();
+ for (CSSPropertyTransitionsMap::const_iterator it = m_transitions.begin(); it != transitionsEnd; ++it) {
+ ImplicitAnimation* transition = it->value.get();
+ double t = transition ? transition->timeToNextService() : -1;
+ if (t < minT || minT == -1)
+ minT = t;
+ if (minT == 0)
+ return 0;
+ }
+ }
+ if (!m_keyframeAnimations.isEmpty()) {
+ AnimationNameMap::const_iterator animationsEnd = m_keyframeAnimations.end();
+ for (AnimationNameMap::const_iterator it = m_keyframeAnimations.begin(); it != animationsEnd; ++it) {
+ KeyframeAnimation* animation = it->value.get();
+ double t = animation ? animation->timeToNextService() : -1;
+ if (t < minT || minT == -1)
+ minT = t;
+ if (minT == 0)
+ return 0;
+ }
+ }
+
+ return minT;
+}
+
+double CompositeAnimation::timeToNextEvent() const
+{
+ // Returns the time at which next service to trigger events is required. -1 means no service is required. 0 means
+ // service is required now, and > 0 means service is required that many seconds in the future.
+ double minT = -1;
+
+ if (!m_transitions.isEmpty()) {
+ CSSPropertyTransitionsMap::const_iterator transitionsEnd = m_transitions.end();
+ for (CSSPropertyTransitionsMap::const_iterator it = m_transitions.begin(); it != transitionsEnd; ++it) {
+ ImplicitAnimation* transition = it->value.get();
+ double t = -1;
+ bool isLooping;
+ if (transition)
+ transition->getTimeToNextEvent(t, isLooping);
+ if (t < minT || minT == -1)
+ minT = t;
+ if (!minT)
+ return 0;
+ }
+ }
+ if (!m_keyframeAnimations.isEmpty()) {
+ AnimationNameMap::const_iterator animationsEnd = m_keyframeAnimations.end();
+ for (AnimationNameMap::const_iterator it = m_keyframeAnimations.begin(); it != animationsEnd; ++it) {
+ KeyframeAnimation* animation = it->value.get();
+ double t = -1;
+ bool isLooping;
+ if (animation)
+ animation->getTimeToNextEvent(t, isLooping);
+ if (t < minT || minT == -1)
+ minT = t;
+ if (!minT)
+ return 0;
+ }
+ }
+
+ return minT;
+}
+
+PassRefPtr<KeyframeAnimation> CompositeAnimation::getAnimationForProperty(CSSPropertyID property) const
+{
+ RefPtr<KeyframeAnimation> retval;
+
+ // We want to send back the last animation with the property if there are multiples.
+ // So we need to iterate through all animations
+ if (!m_keyframeAnimations.isEmpty()) {
+ AnimationNameMap::const_iterator animationsEnd = m_keyframeAnimations.end();
+ for (AnimationNameMap::const_iterator it = m_keyframeAnimations.begin(); it != animationsEnd; ++it) {
+ RefPtr<KeyframeAnimation> anim = it->value;
+ if (anim->hasAnimationForProperty(property))
+ retval = anim;
+ }
+ }
+
+ return retval;
+}
+
+void CompositeAnimation::overrideImplicitAnimations(CSSPropertyID property)
+{
+ CSSPropertyTransitionsMap::const_iterator end = m_transitions.end();
+ if (!m_transitions.isEmpty()) {
+ for (CSSPropertyTransitionsMap::const_iterator it = m_transitions.begin(); it != end; ++it) {
+ ImplicitAnimation* anim = it->value.get();
+ if (anim && anim->animatingProperty() == property)
+ anim->setOverridden(true);
+ }
+ }
+}
+
+void CompositeAnimation::resumeOverriddenImplicitAnimations(CSSPropertyID property)
+{
+ if (!m_transitions.isEmpty()) {
+ CSSPropertyTransitionsMap::const_iterator end = m_transitions.end();
+ for (CSSPropertyTransitionsMap::const_iterator it = m_transitions.begin(); it != end; ++it) {
+ ImplicitAnimation* anim = it->value.get();
+ if (anim && anim->animatingProperty() == property)
+ anim->setOverridden(false);
+ }
+ }
+}
+
+bool CompositeAnimation::isAnimatingProperty(CSSPropertyID property, bool acceleratedOnly, bool isRunningNow) const
+{
+ if (!m_keyframeAnimations.isEmpty()) {
+ AnimationNameMap::const_iterator animationsEnd = m_keyframeAnimations.end();
+ for (AnimationNameMap::const_iterator it = m_keyframeAnimations.begin(); it != animationsEnd; ++it) {
+ KeyframeAnimation* anim = it->value.get();
+ if (anim && anim->isAnimatingProperty(property, acceleratedOnly, isRunningNow))
+ return true;
+ }
+ }
+
+ if (!m_transitions.isEmpty()) {
+ CSSPropertyTransitionsMap::const_iterator transitionsEnd = m_transitions.end();
+ for (CSSPropertyTransitionsMap::const_iterator it = m_transitions.begin(); it != transitionsEnd; ++it) {
+ ImplicitAnimation* anim = it->value.get();
+ if (anim && anim->isAnimatingProperty(property, acceleratedOnly, isRunningNow))
+ return true;
+ }
+ }
+ return false;
+}
+
+void CompositeAnimation::pauseAnimationsForTesting(double t)
+{
+ AnimationNameMap::const_iterator animationsEnd = m_keyframeAnimations.end();
+ for (AnimationNameMap::const_iterator it = m_keyframeAnimations.begin(); it != animationsEnd; ++it) {
+ RefPtr<KeyframeAnimation> keyframeAnim = it->value;
+ if (!keyframeAnim || !keyframeAnim->running())
+ continue;
+
+ double count = keyframeAnim->m_animation->iterationCount();
+ if ((t >= 0.0) && ((count == CSSAnimationData::IterationCountInfinite) || (t <= count * keyframeAnim->duration())))
+ keyframeAnim->freezeAtTime(t);
+ }
+
+ CSSPropertyTransitionsMap::const_iterator transitionsEnd = m_transitions.end();
+ for (CSSPropertyTransitionsMap::const_iterator it = m_transitions.begin(); it != transitionsEnd; ++it) {
+ RefPtr<ImplicitAnimation> implAnim = it->value;
+
+ if (!implAnim->running())
+ continue;
+
+ if ((t >= 0.0) && (t <= implAnim->duration()))
+ implAnim->freezeAtTime(t);
+ }
+}
+
+unsigned CompositeAnimation::numberOfActiveAnimations() const
+{
+ unsigned count = 0;
+
+ if (!m_keyframeAnimations.isEmpty()) {
+ AnimationNameMap::const_iterator animationsEnd = m_keyframeAnimations.end();
+ for (AnimationNameMap::const_iterator it = m_keyframeAnimations.begin(); it != animationsEnd; ++it) {
+ KeyframeAnimation* anim = it->value.get();
+ if (anim->running())
+ ++count;
+ }
+ }
+
+ if (!m_transitions.isEmpty()) {
+ CSSPropertyTransitionsMap::const_iterator transitionsEnd = m_transitions.end();
+ for (CSSPropertyTransitionsMap::const_iterator it = m_transitions.begin(); it != transitionsEnd; ++it) {
+ ImplicitAnimation* anim = it->value.get();
+ if (anim->running())
+ ++count;
+ }
+ }
+
+ return count;
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/frame/animation/CompositeAnimation.h b/chromium/third_party/WebKit/Source/core/frame/animation/CompositeAnimation.h
new file mode 100644
index 00000000000..ee0bd467288
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/animation/CompositeAnimation.h
@@ -0,0 +1,96 @@
+/*
+ * Copyright (C) 2007 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef CompositeAnimation_h
+#define CompositeAnimation_h
+
+#include "core/frame/animation/ImplicitAnimation.h"
+#include "core/frame/animation/KeyframeAnimation.h"
+#include "wtf/HashMap.h"
+
+namespace WebCore {
+
+class AnimationControllerPrivate;
+class AnimationController;
+class RenderObject;
+class RenderStyle;
+
+// A CompositeAnimation represents a collection of animations that are running
+// on a single RenderObject, such as a number of properties transitioning at once.
+class CompositeAnimation : public RefCounted<CompositeAnimation> {
+public:
+ static PassRefPtr<CompositeAnimation> create(AnimationControllerPrivate* animationController)
+ {
+ return adoptRef(new CompositeAnimation(animationController));
+ };
+
+ ~CompositeAnimation();
+
+ void clearRenderer();
+
+ PassRefPtr<RenderStyle> animate(RenderObject&, RenderStyle* currentStyle, RenderStyle& targetStyle);
+ PassRefPtr<RenderStyle> getAnimatedStyle() const;
+
+ double timeToNextService() const;
+ double timeToNextEvent() const;
+
+ AnimationControllerPrivate* animationController() const { return m_animationController; }
+
+ bool hasAnimations() const { return !m_transitions.isEmpty() || !m_keyframeAnimations.isEmpty(); }
+
+ bool isAnimatingProperty(CSSPropertyID, bool acceleratedOnly, bool isRunningNow) const;
+
+ PassRefPtr<KeyframeAnimation> getAnimationForProperty(CSSPropertyID) const;
+
+ void overrideImplicitAnimations(CSSPropertyID);
+ void resumeOverriddenImplicitAnimations(CSSPropertyID);
+
+ void pauseAnimationsForTesting(double t);
+ unsigned numberOfActiveAnimations() const;
+
+private:
+ CompositeAnimation(AnimationControllerPrivate* animationController)
+ : m_animationController(animationController)
+ {
+ }
+
+ void updateTransitions(RenderObject&, RenderStyle* currentStyle, RenderStyle& targetStyle);
+ void updateKeyframeAnimations(RenderObject&, RenderStyle* currentStyle, RenderStyle& targetStyle);
+
+ typedef HashMap<int, RefPtr<ImplicitAnimation> > CSSPropertyTransitionsMap;
+ typedef HashMap<AtomicString, RefPtr<KeyframeAnimation> > AnimationNameMap;
+
+ AnimationControllerPrivate* m_animationController;
+ CSSPropertyTransitionsMap m_transitions;
+ AnimationNameMap m_keyframeAnimations;
+ Vector<AtomicString> m_keyframeAnimationOrderList;
+};
+
+} // namespace WebCore
+
+#endif // CompositeAnimation_h
diff --git a/chromium/third_party/WebKit/Source/core/frame/animation/ImplicitAnimation.cpp b/chromium/third_party/WebKit/Source/core/frame/animation/ImplicitAnimation.cpp
new file mode 100644
index 00000000000..2cf82b64b2b
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/animation/ImplicitAnimation.cpp
@@ -0,0 +1,283 @@
+/*
+ * Copyright (C) 2007 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+
+#include "core/events/ThreadLocalEventNames.h"
+#include "core/frame/UseCounter.h"
+#include "core/frame/animation/AnimationControllerPrivate.h"
+#include "core/frame/animation/CSSPropertyAnimation.h"
+#include "core/frame/animation/CompositeAnimation.h"
+#include "core/frame/animation/ImplicitAnimation.h"
+#include "core/frame/animation/KeyframeAnimation.h"
+#include "core/rendering/RenderBoxModelObject.h"
+#include "public/platform/Platform.h"
+
+namespace WebCore {
+
+ImplicitAnimation::ImplicitAnimation(const CSSAnimationData* transition, CSSPropertyID animatingProperty, RenderObject& renderer, CompositeAnimation* compAnim, RenderStyle* fromStyle)
+ : AnimationBase(transition, renderer, compAnim)
+ , m_transitionProperty(transition->property())
+ , m_animatingProperty(animatingProperty)
+ , m_overridden(false)
+ , m_active(true)
+ , m_fromStyle(fromStyle)
+{
+ ASSERT(animatingProperty != CSSPropertyInvalid);
+ blink::Platform::current()->histogramSparse("WebCore.Animation.CSSProperties", UseCounter::mapCSSPropertyIdToCSSSampleIdForHistogram(m_animatingProperty));
+}
+
+ImplicitAnimation::~ImplicitAnimation()
+{
+ // // Make sure to tell the renderer that we are ending. This will make sure any accelerated animations are removed.
+ if (!postActive())
+ endAnimation();
+}
+
+bool ImplicitAnimation::shouldSendEventForListener(Document::ListenerType inListenerType) const
+{
+ return m_object->document().hasListenerType(inListenerType);
+}
+
+void ImplicitAnimation::animate(CompositeAnimation*, RenderObject*, const RenderStyle*, RenderStyle* targetStyle, RefPtr<RenderStyle>& animatedStyle)
+{
+ // If we get this far and the animation is done, it means we are cleaning up a just finished animation.
+ // So just return. Everything is already all cleaned up.
+ if (postActive())
+ return;
+
+ // Reset to start the transition if we are new
+ if (isNew())
+ reset(targetStyle);
+
+ // Run a cycle of animation.
+ // We know we will need a new render style, so make one if needed
+ if (!animatedStyle)
+ animatedStyle = RenderStyle::clone(targetStyle);
+
+ bool needsAnim = CSSPropertyAnimation::blendProperties(this, m_animatingProperty, animatedStyle.get(), m_fromStyle.get(), m_toStyle.get(), progress(1, 0, 0));
+ // FIXME: we also need to detect cases where we have to software animate for other reasons,
+ // such as a child using inheriting the transform. https://bugs.webkit.org/show_bug.cgi?id=23902
+ if (!needsAnim)
+ // If we are running an accelerated animation, set a flag in the style which causes the style
+ // to compare as different to any other style. This ensures that changes to the property
+ // that is animating are correctly detected during the animation (e.g. when a transition
+ // gets interrupted).
+ animatedStyle->setIsRunningAcceleratedAnimation();
+
+ // Fire the start timeout if needed
+ fireAnimationEventsIfNeeded();
+}
+
+void ImplicitAnimation::getAnimatedStyle(RefPtr<RenderStyle>& animatedStyle)
+{
+ if (!animatedStyle)
+ animatedStyle = RenderStyle::clone(m_toStyle.get());
+
+ CSSPropertyAnimation::blendProperties(this, m_animatingProperty, animatedStyle.get(), m_fromStyle.get(), m_toStyle.get(), progress(1, 0, 0));
+}
+
+void ImplicitAnimation::startAnimation(double timeOffset)
+{
+ if (m_object && m_object->compositingState() == PaintsIntoOwnBacking)
+ m_isAccelerated = toRenderBoxModelObject(m_object)->startTransition(timeOffset, m_animatingProperty, m_fromStyle.get(), m_toStyle.get());
+}
+
+void ImplicitAnimation::pauseAnimation(double timeOffset)
+{
+ if (!m_object)
+ return;
+
+ if (m_object && m_object->compositingState() == PaintsIntoOwnBacking && isAccelerated())
+ toRenderBoxModelObject(m_object)->transitionPaused(timeOffset, m_animatingProperty);
+
+ // Restore the original (unanimated) style
+ if (!paused())
+ setNeedsStyleRecalc(m_object->node());
+}
+
+void ImplicitAnimation::endAnimation()
+{
+ if (m_object && m_object->compositingState() == PaintsIntoOwnBacking && isAccelerated())
+ toRenderBoxModelObject(m_object)->transitionFinished(m_animatingProperty);
+ m_isAccelerated = false;
+}
+
+void ImplicitAnimation::onAnimationEnd(double elapsedTime)
+{
+ // If we have a keyframe animation on this property, this transition is being overridden. The keyframe
+ // animation keeps an unanimated style in case a transition starts while the keyframe animation is
+ // running. But now that the transition has completed, we need to update this style with its new
+ // destination. If we didn't, the next time through we would think a transition had started
+ // (comparing the old unanimated style with the new final style of the transition).
+ RefPtr<KeyframeAnimation> keyframeAnim = m_compAnim->getAnimationForProperty(m_animatingProperty);
+ if (keyframeAnim)
+ keyframeAnim->setUnanimatedStyle(m_toStyle);
+
+ sendTransitionEvent(EventTypeNames::transitionend, elapsedTime);
+ endAnimation();
+}
+
+bool ImplicitAnimation::sendTransitionEvent(const AtomicString& eventType, double elapsedTime)
+{
+ if (eventType == EventTypeNames::transitionend) {
+ Document::ListenerType listenerType = Document::TRANSITIONEND_LISTENER;
+
+ if (shouldSendEventForListener(listenerType)) {
+ String propertyName = getPropertyNameString(m_animatingProperty);
+
+ // Dispatch the event
+ RefPtr<Element> element = 0;
+ if (m_object->node() && m_object->node()->isElementNode())
+ element = toElement(m_object->node());
+
+ if (!element)
+ return false;
+
+ // Schedule event handling
+ m_compAnim->animationController()->addEventToDispatch(element, eventType, propertyName, elapsedTime);
+
+ // Restore the original (unanimated) style
+ if (eventType == EventTypeNames::transitionend && element->renderer())
+ setNeedsStyleRecalc(element.get());
+
+ return true; // Did dispatch an event
+ }
+ }
+
+ return false; // Didn't dispatch an event
+}
+
+void ImplicitAnimation::reset(RenderStyle* to)
+{
+ ASSERT(to);
+ ASSERT(m_fromStyle);
+
+ m_toStyle = to;
+
+ // Restart the transition
+ if (m_fromStyle && m_toStyle)
+ updateStateMachine(AnimationStateInputRestartAnimation, -1);
+
+ // set the transform animation list
+ validateTransformFunctionList();
+ checkForMatchingFilterFunctionLists();
+}
+
+void ImplicitAnimation::setOverridden(bool b)
+{
+ if (b == m_overridden)
+ return;
+
+ m_overridden = b;
+ updateStateMachine(m_overridden ? AnimationStateInputPauseOverride : AnimationStateInputResumeOverride, -1);
+}
+
+bool ImplicitAnimation::affectsProperty(CSSPropertyID property) const
+{
+ return (m_animatingProperty == property);
+}
+
+bool ImplicitAnimation::isTargetPropertyEqual(CSSPropertyID prop, const RenderStyle* targetStyle)
+{
+ // We can get here for a transition that has not started yet. This would make m_toStyle unset and null.
+ // So we check that here (see <https://bugs.webkit.org/show_bug.cgi?id=26706>)
+ if (!m_toStyle)
+ return false;
+ return CSSPropertyAnimation::propertiesEqual(prop, m_toStyle.get(), targetStyle);
+}
+
+void ImplicitAnimation::blendPropertyValueInStyle(CSSPropertyID prop, RenderStyle* currentStyle)
+{
+ // We should never add a transition with a 0 duration and delay. But if we ever did
+ // it would have a null toStyle. So just in case, let's check that here. (See
+ // <https://bugs.webkit.org/show_bug.cgi?id=24787>
+ if (!m_toStyle)
+ return;
+
+ CSSPropertyAnimation::blendProperties(this, prop, currentStyle, m_fromStyle.get(), m_toStyle.get(), progress(1, 0, 0));
+}
+
+void ImplicitAnimation::validateTransformFunctionList()
+{
+ m_transformFunctionListValid = false;
+
+ if (!m_fromStyle || !m_toStyle)
+ return;
+
+ const TransformOperations* val = &m_fromStyle->transform();
+ const TransformOperations* toVal = &m_toStyle->transform();
+
+ if (val->operations().isEmpty())
+ val = toVal;
+
+ if (val->operations().isEmpty())
+ return;
+
+ // An emtpy transform list matches anything.
+ if (val != toVal && !toVal->operations().isEmpty() && !val->operationsMatch(*toVal))
+ return;
+
+ // Transform lists match.
+ m_transformFunctionListValid = true;
+}
+
+void ImplicitAnimation::checkForMatchingFilterFunctionLists()
+{
+ m_filterFunctionListsMatch = false;
+
+ if (!m_fromStyle || !m_toStyle)
+ return;
+
+ const FilterOperations* val = &m_fromStyle->filter();
+ const FilterOperations* toVal = &m_toStyle->filter();
+
+ if (!val->canInterpolateWith(*toVal))
+ return;
+
+ // Filter lists match.
+ m_filterFunctionListsMatch = true;
+}
+
+double ImplicitAnimation::timeToNextService()
+{
+ double t = AnimationBase::timeToNextService();
+ if (t != 0 || preActive())
+ return t;
+
+ // A return value of 0 means we need service. But if this is an accelerated animation we
+ // only need service at the end of the transition.
+ if (CSSPropertyAnimation::animationOfPropertyIsAccelerated(m_animatingProperty) && isAccelerated()) {
+ bool isLooping;
+ getTimeToNextEvent(t, isLooping);
+ }
+
+ return t;
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/frame/animation/ImplicitAnimation.h b/chromium/third_party/WebKit/Source/core/frame/animation/ImplicitAnimation.h
new file mode 100644
index 00000000000..c531b36a81d
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/animation/ImplicitAnimation.h
@@ -0,0 +1,98 @@
+/*
+ * Copyright (C) 2007 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef ImplicitAnimation_h
+#define ImplicitAnimation_h
+
+#include "CSSPropertyNames.h"
+#include "core/dom/Document.h"
+#include "core/frame/animation/AnimationBase.h"
+
+namespace WebCore {
+
+// An ImplicitAnimation tracks the state of a transition of a specific CSS property
+// for a single RenderObject.
+class ImplicitAnimation : public AnimationBase {
+public:
+ static PassRefPtr<ImplicitAnimation> create(const CSSAnimationData* animation, CSSPropertyID animatingProperty, RenderObject& renderer, CompositeAnimation* compositeAnimation, RenderStyle* fromStyle)
+ {
+ return adoptRef(new ImplicitAnimation(animation, animatingProperty, renderer, compositeAnimation, fromStyle));
+ };
+
+ CSSPropertyID transitionProperty() const { return m_transitionProperty; }
+ CSSPropertyID animatingProperty() const { return m_animatingProperty; }
+
+ virtual void onAnimationEnd(double elapsedTime);
+ virtual void startAnimation(double timeOffset);
+ virtual void pauseAnimation(double /*timeOffset*/);
+ virtual void endAnimation();
+
+ virtual void animate(CompositeAnimation*, RenderObject*, const RenderStyle* currentStyle, RenderStyle* targetStyle, RefPtr<RenderStyle>& animatedStyle);
+ virtual void getAnimatedStyle(RefPtr<RenderStyle>& animatedStyle);
+ virtual void reset(RenderStyle* to);
+
+ void setOverridden(bool);
+ virtual bool overridden() const { return m_overridden; }
+
+ virtual bool affectsProperty(CSSPropertyID) const;
+
+ bool hasStyle() const { return m_fromStyle && m_toStyle; }
+
+ bool isTargetPropertyEqual(CSSPropertyID, const RenderStyle*);
+
+ void blendPropertyValueInStyle(CSSPropertyID, RenderStyle*);
+
+ virtual double timeToNextService();
+
+ bool active() const { return m_active; }
+ void setActive(bool b) { m_active = b; }
+
+protected:
+ bool shouldSendEventForListener(Document::ListenerType) const;
+ bool sendTransitionEvent(const AtomicString&, double elapsedTime);
+
+ void validateTransformFunctionList();
+ void checkForMatchingFilterFunctionLists();
+
+private:
+ ImplicitAnimation(const CSSAnimationData*, CSSPropertyID, RenderObject&, CompositeAnimation*, RenderStyle*);
+ virtual ~ImplicitAnimation();
+
+ CSSPropertyID m_transitionProperty; // Transition property as specified in the RenderStyle.
+ CSSPropertyID m_animatingProperty; // Specific property for this ImplicitAnimation
+ bool m_overridden; // true when there is a keyframe animation that overrides the transitioning property
+ bool m_active; // used for culling the list of transitions
+
+ // The two styles that we are blending.
+ RefPtr<RenderStyle> m_fromStyle;
+ RefPtr<RenderStyle> m_toStyle;
+};
+
+} // namespace WebCore
+
+#endif // ImplicitAnimation_h
diff --git a/chromium/third_party/WebKit/Source/core/frame/animation/KeyframeAnimation.cpp b/chromium/third_party/WebKit/Source/core/frame/animation/KeyframeAnimation.cpp
new file mode 100644
index 00000000000..948ca03ce42
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/animation/KeyframeAnimation.cpp
@@ -0,0 +1,455 @@
+/*
+ * Copyright (C) 2007, 2012 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/frame/animation/KeyframeAnimation.h"
+
+#include "CSSPropertyNames.h"
+#include "core/css/resolver/StyleResolver.h"
+#include "core/events/ThreadLocalEventNames.h"
+#include "core/frame/UseCounter.h"
+#include "core/frame/animation/AnimationControllerPrivate.h"
+#include "core/frame/animation/CSSPropertyAnimation.h"
+#include "core/frame/animation/CompositeAnimation.h"
+#include "core/rendering/RenderBoxModelObject.h"
+#include "core/rendering/style/RenderStyle.h"
+#include "public/platform/Platform.h"
+
+using namespace std;
+
+namespace WebCore {
+
+KeyframeAnimation::KeyframeAnimation(const CSSAnimationData* animation, RenderObject& renderer, int index, CompositeAnimation* compAnim, RenderStyle& unanimatedStyle)
+ : AnimationBase(animation, renderer, compAnim)
+ , m_keyframes(renderer, animation->name())
+ , m_index(index)
+ , m_startEventDispatched(false)
+ , m_unanimatedStyle(unanimatedStyle)
+{
+ // Get the keyframe RenderStyles
+ if (m_object && m_object->node() && m_object->node()->isElementNode())
+ m_object->document().ensureStyleResolver().keyframeStylesForAnimation(toElement(m_object->node()), unanimatedStyle, m_keyframes);
+
+ // Update the m_transformFunctionListValid flag based on whether the function lists in the keyframes match.
+ validateTransformFunctionList();
+ checkForMatchingFilterFunctionLists();
+ HashSet<CSSPropertyID>::const_iterator endProperties = m_keyframes.endProperties();
+ for (HashSet<CSSPropertyID>::const_iterator it = m_keyframes.beginProperties(); it != endProperties; ++it)
+ blink::Platform::current()->histogramSparse("WebCore.Animation.CSSProperties", UseCounter::mapCSSPropertyIdToCSSSampleIdForHistogram(*it));
+}
+
+KeyframeAnimation::~KeyframeAnimation()
+{
+ // Make sure to tell the renderer that we are ending. This will make sure any accelerated animations are removed.
+ if (!postActive())
+ endAnimation();
+}
+
+void KeyframeAnimation::fetchIntervalEndpointsForProperty(CSSPropertyID property, const RenderStyle*& fromStyle, const RenderStyle*& toStyle, double& prog) const
+{
+ // Find the first key
+ double elapsedTime = getElapsedTime();
+ if (m_animation->duration() && m_animation->iterationCount() != CSSAnimationData::IterationCountInfinite)
+ elapsedTime = min(elapsedTime, m_animation->duration() * m_animation->iterationCount());
+
+ const double fractionalTime = this->fractionalTime(1, elapsedTime, 0);
+
+ size_t numKeyframes = m_keyframes.size();
+ if (!numKeyframes)
+ return;
+
+ ASSERT(!m_keyframes[0].key());
+ ASSERT(m_keyframes[m_keyframes.size() - 1].key() == 1);
+
+ size_t currentIndex = 0;
+ size_t firstIndex = 0;
+ size_t lastIndex = numKeyframes - 1;
+ size_t distance = numKeyframes;
+
+ // Find keyframe that is closest to elapsed time.
+ while (distance > 1) {
+ currentIndex = (lastIndex + firstIndex) >> 1;
+ double key = m_keyframes[currentIndex].key();
+ distance = lastIndex - currentIndex;
+
+ if (key < fractionalTime) {
+ if (distance < 2)
+ currentIndex++;
+ firstIndex = currentIndex;
+ } else {
+ lastIndex = currentIndex;
+ }
+ }
+
+ int prevIndex = -1;
+ int nextIndex = -1;
+
+ // Iterate forward to find next keyframe that is used to animate CSS property.
+ for (size_t i = currentIndex; i < numKeyframes; ++i) {
+ const KeyframeValue& keyFrame = m_keyframes[i];
+ if (keyFrame.key() > fractionalTime && keyFrame.containsProperty(property)) {
+ nextIndex = i;
+ break;
+ }
+ }
+
+ // Iterate backward to find previous keyframe.
+ for (int i = currentIndex; i >= 0; --i) {
+ const KeyframeValue& keyFrame = m_keyframes[i];
+ if (keyFrame.key() <= fractionalTime && keyFrame.containsProperty(property)) {
+ prevIndex = i;
+ break;
+ }
+ }
+
+ double scale = 1;
+ double offset = 0;
+
+ if (prevIndex == -1)
+ prevIndex = 0;
+
+ if (nextIndex == -1)
+ nextIndex = numKeyframes - 1;
+
+ const KeyframeValue& prevKeyframe = m_keyframes[prevIndex];
+ const KeyframeValue& nextKeyframe = m_keyframes[nextIndex];
+
+ fromStyle = prevKeyframe.style();
+ toStyle = nextKeyframe.style();
+
+ offset = prevKeyframe.key();
+ scale = 1.0 / (nextKeyframe.key() - prevKeyframe.key());
+ // A scale of infinity is handled in AnimationBase::fractionalTime().
+ ASSERT(scale >= 0 && (!std::isinf(scale) || prevIndex == nextIndex));
+
+ prog = progress(scale, offset, KeyframeValue::timingFunction(*prevKeyframe.style()));
+}
+
+void KeyframeAnimation::animate(CompositeAnimation*, RenderObject*, const RenderStyle*, RenderStyle* targetStyle, RefPtr<RenderStyle>& animatedStyle)
+{
+ // Fire the start timeout if needed
+ fireAnimationEventsIfNeeded();
+
+ // If we have not yet started, we will not have a valid start time, so just start the animation if needed.
+ if (isNew() && m_animation->playState() == AnimPlayStatePlaying)
+ updateStateMachine(AnimationStateInputStartAnimation, -1);
+
+ // If we get this far and the animation is done, it means we are cleaning up a just finished animation.
+ // If so, we need to send back the targetStyle.
+ if (postActive()) {
+ if (!animatedStyle)
+ animatedStyle = const_cast<RenderStyle*>(targetStyle);
+ return;
+ }
+
+ // If we are waiting for the start timer, we don't want to change the style yet.
+ // Special case 1 - if the delay time is 0, then we do want to set the first frame of the
+ // animation right away. This avoids a flash when the animation starts.
+ // Special case 2 - if there is a backwards fill mode, then we want to continue
+ // through to the style blend so that we get the fromStyle.
+ if (waitingToStart() && m_animation->delay() > 0 && !m_animation->fillsBackwards())
+ return;
+
+ // If we have no keyframes, don't animate.
+ if (!m_keyframes.size()) {
+ updateStateMachine(AnimationStateInputEndAnimation, -1);
+ return;
+ }
+
+ // Run a cycle of animation.
+ // We know we will need a new render style, so make one if needed.
+ if (!animatedStyle)
+ animatedStyle = RenderStyle::clone(targetStyle);
+
+ // FIXME: we need to be more efficient about determining which keyframes we are animating between.
+ // We should cache the last pair or something.
+ HashSet<CSSPropertyID>::const_iterator endProperties = m_keyframes.endProperties();
+ for (HashSet<CSSPropertyID>::const_iterator it = m_keyframes.beginProperties(); it != endProperties; ++it) {
+ // Get the from/to styles and progress between
+ const RenderStyle* fromStyle = 0;
+ const RenderStyle* toStyle = 0;
+ double progress = 0.0;
+ fetchIntervalEndpointsForProperty(*it, fromStyle, toStyle, progress);
+
+ bool needsAnim = CSSPropertyAnimation::blendProperties(this, *it, animatedStyle.get(), fromStyle, toStyle, progress);
+ if (!needsAnim)
+ // If we are running an accelerated animation, set a flag in the style
+ // to indicate it. This can be used to make sure we get an updated
+ // style for hit testing, etc.
+ animatedStyle->setIsRunningAcceleratedAnimation();
+ }
+}
+
+void KeyframeAnimation::getAnimatedStyle(RefPtr<RenderStyle>& animatedStyle)
+{
+ // If we're in the delay phase and we're not backwards filling, tell the caller
+ // to use the current style.
+ if (waitingToStart() && m_animation->delay() > 0 && !m_animation->fillsBackwards())
+ return;
+
+ if (!m_keyframes.size())
+ return;
+
+ if (!animatedStyle)
+ animatedStyle = RenderStyle::clone(m_object->style());
+
+ HashSet<CSSPropertyID>::const_iterator endProperties = m_keyframes.endProperties();
+ for (HashSet<CSSPropertyID>::const_iterator it = m_keyframes.beginProperties(); it != endProperties; ++it) {
+ // Get the from/to styles and progress between
+ const RenderStyle* fromStyle = 0;
+ const RenderStyle* toStyle = 0;
+ double progress = 0.0;
+ fetchIntervalEndpointsForProperty(*it, fromStyle, toStyle, progress);
+
+ CSSPropertyAnimation::blendProperties(this, *it, animatedStyle.get(), fromStyle, toStyle, progress);
+ }
+}
+
+bool KeyframeAnimation::hasAnimationForProperty(CSSPropertyID property) const
+{
+ return m_keyframes.containsProperty(property);
+}
+
+void KeyframeAnimation::startAnimation(double timeOffset)
+{
+ if (m_object && m_object->compositingState() == PaintsIntoOwnBacking)
+ m_isAccelerated = toRenderBoxModelObject(m_object)->startAnimation(timeOffset, m_animation.get(), m_keyframes);
+}
+
+void KeyframeAnimation::pauseAnimation(double timeOffset)
+{
+ if (!m_object)
+ return;
+
+ if (m_object && m_object->compositingState() == PaintsIntoOwnBacking && isAccelerated())
+ toRenderBoxModelObject(m_object)->animationPaused(timeOffset, m_keyframes.animationName());
+
+ // Restore the original (unanimated) style
+ if (!paused())
+ setNeedsStyleRecalc(m_object->node());
+}
+
+void KeyframeAnimation::endAnimation()
+{
+ if (!m_object)
+ return;
+
+ if (m_object && m_object->compositingState() == PaintsIntoOwnBacking && isAccelerated())
+ toRenderBoxModelObject(m_object)->animationFinished(m_keyframes.animationName());
+ m_isAccelerated = false;
+
+ // Restore the original (unanimated) style
+ if (!paused())
+ setNeedsStyleRecalc(m_object->node());
+}
+
+bool KeyframeAnimation::shouldSendEventForListener(Document::ListenerType listenerType) const
+{
+ return m_object->document().hasListenerType(listenerType);
+}
+
+void KeyframeAnimation::onAnimationStart(double elapsedTime)
+{
+ sendAnimationEvent(EventTypeNames::animationstart, elapsedTime);
+}
+
+void KeyframeAnimation::onAnimationIteration(double elapsedTime)
+{
+ sendAnimationEvent(EventTypeNames::animationiteration, elapsedTime);
+}
+
+void KeyframeAnimation::onAnimationEnd(double elapsedTime)
+{
+ sendAnimationEvent(EventTypeNames::animationend, elapsedTime);
+ // End the animation if we don't fill forwards. Forward filling
+ // animations are ended properly in the class destructor.
+ if (!m_animation->fillsForwards())
+ endAnimation();
+}
+
+bool KeyframeAnimation::sendAnimationEvent(const AtomicString& eventType, double elapsedTime)
+{
+ Document::ListenerType listenerType;
+ if (eventType == EventTypeNames::animationiteration)
+ listenerType = Document::ANIMATIONITERATION_LISTENER;
+ else if (eventType == EventTypeNames::animationend)
+ listenerType = Document::ANIMATIONEND_LISTENER;
+ else {
+ ASSERT(eventType == EventTypeNames::animationstart);
+ if (m_startEventDispatched)
+ return false;
+ m_startEventDispatched = true;
+ listenerType = Document::ANIMATIONSTART_LISTENER;
+ }
+
+ if (shouldSendEventForListener(listenerType)) {
+ // Dispatch the event
+ RefPtr<Element> element;
+ if (m_object->node() && m_object->node()->isElementNode())
+ element = toElement(m_object->node());
+
+ if (!element)
+ return false;
+
+ // Schedule event handling
+ m_compAnim->animationController()->addEventToDispatch(element, eventType, m_keyframes.animationName(), elapsedTime);
+
+ // Restore the original (unanimated) style
+ if (eventType == EventTypeNames::animationend && element->renderer())
+ setNeedsStyleRecalc(element.get());
+
+ return true; // Did dispatch an event
+ }
+
+ return false; // Did not dispatch an event
+}
+
+void KeyframeAnimation::overrideAnimations()
+{
+ // This will override implicit animations that match the properties in the keyframe animation
+ HashSet<CSSPropertyID>::const_iterator end = m_keyframes.endProperties();
+ for (HashSet<CSSPropertyID>::const_iterator it = m_keyframes.beginProperties(); it != end; ++it)
+ compositeAnimation()->overrideImplicitAnimations(*it);
+}
+
+void KeyframeAnimation::resumeOverriddenAnimations()
+{
+ // This will resume overridden implicit animations
+ HashSet<CSSPropertyID>::const_iterator end = m_keyframes.endProperties();
+ for (HashSet<CSSPropertyID>::const_iterator it = m_keyframes.beginProperties(); it != end; ++it)
+ compositeAnimation()->resumeOverriddenImplicitAnimations(*it);
+}
+
+bool KeyframeAnimation::affectsProperty(CSSPropertyID property) const
+{
+ return m_keyframes.containsProperty(property);
+}
+
+void KeyframeAnimation::validateTransformFunctionList()
+{
+ m_transformFunctionListValid = false;
+
+ if (m_keyframes.size() < 2 || !m_keyframes.containsProperty(CSSPropertyWebkitTransform))
+ return;
+
+ // Empty transforms match anything, so find the first non-empty entry as the reference
+ size_t numKeyframes = m_keyframes.size();
+ size_t firstNonEmptyTransformKeyframeIndex = numKeyframes;
+
+ for (size_t i = 0; i < numKeyframes; ++i) {
+ const KeyframeValue& currentKeyframe = m_keyframes[i];
+ if (currentKeyframe.style()->transform().operations().size()) {
+ firstNonEmptyTransformKeyframeIndex = i;
+ break;
+ }
+ }
+
+ if (firstNonEmptyTransformKeyframeIndex == numKeyframes)
+ return;
+
+ const TransformOperations* firstVal = &m_keyframes[firstNonEmptyTransformKeyframeIndex].style()->transform();
+
+ // See if the keyframes are valid
+ for (size_t i = firstNonEmptyTransformKeyframeIndex + 1; i < numKeyframes; ++i) {
+ const KeyframeValue& currentKeyframe = m_keyframes[i];
+ const TransformOperations* val = &currentKeyframe.style()->transform();
+
+ // An emtpy transform list matches anything.
+ if (val->operations().isEmpty())
+ continue;
+
+ if (!firstVal->operationsMatch(*val))
+ return;
+ }
+
+ // Keyframes are valid
+ m_transformFunctionListValid = true;
+}
+
+void KeyframeAnimation::checkForMatchingFilterFunctionLists()
+{
+ m_filterFunctionListsMatch = false;
+
+ if (m_keyframes.size() < 2 || !m_keyframes.containsProperty(CSSPropertyWebkitFilter))
+ return;
+
+ // Empty filters match anything, so find the first non-empty entry as the reference
+ size_t numKeyframes = m_keyframes.size();
+ size_t firstNonEmptyFilterKeyframeIndex = numKeyframes;
+
+ for (size_t i = 0; i < numKeyframes; ++i) {
+ const KeyframeValue& currentKeyframe = m_keyframes[i];
+ if (currentKeyframe.style()->filter().operations().size()) {
+ firstNonEmptyFilterKeyframeIndex = i;
+ break;
+ }
+ }
+
+ if (firstNonEmptyFilterKeyframeIndex == numKeyframes)
+ return;
+
+ const FilterOperations* firstVal = &m_keyframes[firstNonEmptyFilterKeyframeIndex].style()->filter();
+
+ for (size_t i = firstNonEmptyFilterKeyframeIndex + 1; i < numKeyframes; ++i) {
+ const KeyframeValue& currentKeyframe = m_keyframes[i];
+ const FilterOperations* val = &currentKeyframe.style()->filter();
+
+ if (!firstVal->canInterpolateWith(*val))
+ return;
+ }
+
+ m_filterFunctionListsMatch = true;
+}
+
+double KeyframeAnimation::timeToNextService()
+{
+ double t = AnimationBase::timeToNextService();
+ if (t != 0 || preActive())
+ return t;
+
+ // A return value of 0 means we need service. But if we only have accelerated animations we
+ // only need service at the end of the transition
+ HashSet<CSSPropertyID>::const_iterator endProperties = m_keyframes.endProperties();
+ bool acceleratedPropertiesOnly = true;
+
+ for (HashSet<CSSPropertyID>::const_iterator it = m_keyframes.beginProperties(); it != endProperties; ++it) {
+ if (!CSSPropertyAnimation::animationOfPropertyIsAccelerated(*it) || !isAccelerated()) {
+ acceleratedPropertiesOnly = false;
+ break;
+ }
+ }
+
+ if (acceleratedPropertiesOnly) {
+ bool isLooping;
+ getTimeToNextEvent(t, isLooping);
+ }
+
+ return t;
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/frame/animation/KeyframeAnimation.h b/chromium/third_party/WebKit/Source/core/frame/animation/KeyframeAnimation.h
new file mode 100644
index 00000000000..93334d93c62
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/frame/animation/KeyframeAnimation.h
@@ -0,0 +1,102 @@
+/*
+ * Copyright (C) 2007 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef KeyframeAnimation_h
+#define KeyframeAnimation_h
+
+#include "core/dom/Document.h"
+#include "core/frame/animation/AnimationBase.h"
+#include "core/rendering/style/KeyframeList.h"
+
+namespace WebCore {
+
+class RenderStyle;
+
+// A KeyframeAnimation tracks the state of an explicit animation
+// for a single RenderObject.
+class KeyframeAnimation : public AnimationBase {
+public:
+ static PassRefPtr<KeyframeAnimation> create(const CSSAnimationData* animation, RenderObject& renderer, int index, CompositeAnimation* compositeAnimation, RenderStyle& unanimatedStyle)
+ {
+ return adoptRef(new KeyframeAnimation(animation, renderer, index, compositeAnimation, unanimatedStyle));
+ };
+
+ virtual void animate(CompositeAnimation*, RenderObject*, const RenderStyle* currentStyle, RenderStyle* targetStyle, RefPtr<RenderStyle>& animatedStyle);
+ virtual void getAnimatedStyle(RefPtr<RenderStyle>& animatedStyle);
+
+ const AtomicString& name() const { return m_keyframes.animationName(); }
+ int index() const { return m_index; }
+ void setIndex(int i) { m_index = i; }
+
+ bool hasAnimationForProperty(CSSPropertyID) const;
+
+ void setUnanimatedStyle(PassRefPtr<RenderStyle> style) { m_unanimatedStyle = style; }
+ RenderStyle* unanimatedStyle() const { return m_unanimatedStyle.get(); }
+
+ virtual double timeToNextService();
+
+protected:
+ virtual void onAnimationStart(double elapsedTime);
+ virtual void onAnimationIteration(double elapsedTime);
+ virtual void onAnimationEnd(double elapsedTime);
+ virtual void startAnimation(double timeOffset);
+ virtual void pauseAnimation(double timeOffset);
+ virtual void endAnimation();
+
+ virtual void overrideAnimations();
+ virtual void resumeOverriddenAnimations();
+
+ bool shouldSendEventForListener(Document::ListenerType inListenerType) const;
+ bool sendAnimationEvent(const AtomicString&, double elapsedTime);
+
+ virtual bool affectsProperty(CSSPropertyID) const;
+
+ void validateTransformFunctionList();
+ void checkForMatchingFilterFunctionLists();
+
+private:
+ KeyframeAnimation(const CSSAnimationData*, RenderObject&, int index, CompositeAnimation*, RenderStyle& unanimatedStyle);
+ virtual ~KeyframeAnimation();
+
+ // Get the styles for the given property surrounding the current animation time and the progress between them.
+ void fetchIntervalEndpointsForProperty(CSSPropertyID, const RenderStyle*& fromStyle, const RenderStyle*& toStyle, double& progress) const;
+
+ // The keyframes that we are blending.
+ KeyframeList m_keyframes;
+
+ // The order in which this animation appears in the animation-name style.
+ int m_index;
+ bool m_startEventDispatched;
+
+ // The style just before we started animation
+ RefPtr<RenderStyle> m_unanimatedStyle;
+};
+
+} // namespace WebCore
+
+#endif // KeyframeAnimation_h
diff --git a/chromium/third_party/WebKit/Source/core/history/BackForwardClient.h b/chromium/third_party/WebKit/Source/core/history/BackForwardClient.h
deleted file mode 100644
index 0a3cf738f91..00000000000
--- a/chromium/third_party/WebKit/Source/core/history/BackForwardClient.h
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Copyright (C) 2006, 2010 Apple Inc. All rights reserved.
- * Copyright (C) 2008 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
- * Copyright (C) 2009 Google, Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef BackForwardClient_h
-#define BackForwardClient_h
-
-#include "wtf/PassRefPtr.h"
-
-namespace WebCore {
-
-class HistoryItem;
-
-class BackForwardClient {
-public:
- virtual ~BackForwardClient() { }
-
- virtual void didAddItem() = 0;
- virtual int backListCount() = 0;
- virtual int forwardListCount() = 0;
-};
-
-} // namespace WebCore
-
-#endif // BackForwardClient_h
diff --git a/chromium/third_party/WebKit/Source/core/history/BackForwardController.cpp b/chromium/third_party/WebKit/Source/core/history/BackForwardController.cpp
deleted file mode 100644
index 45fde048b80..00000000000
--- a/chromium/third_party/WebKit/Source/core/history/BackForwardController.cpp
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- * Copyright (C) 2010 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/history/BackForwardController.h"
-
-#include "core/history/BackForwardClient.h"
-#include "core/history/HistoryItem.h"
-#include "core/loader/FrameLoader.h"
-#include "core/loader/FrameLoaderClient.h"
-#include "core/page/Frame.h"
-#include "core/page/Page.h"
-
-namespace WebCore {
-
-BackForwardController::BackForwardController(Page* page, BackForwardClient* client)
- : m_page(page)
- , m_client(client)
-{
- ASSERT(m_client);
-}
-
-BackForwardController::~BackForwardController()
-{
-}
-
-PassOwnPtr<BackForwardController> BackForwardController::create(Page* page, BackForwardClient* client)
-{
- return adoptPtr(new BackForwardController(page, client));
-}
-
-bool BackForwardController::goBackOrForward(int distance)
-{
- ASSERT(distance);
- if (distance > forwardCount())
- distance = forwardCount();
- else if (distance < -backCount())
- distance = backCount();
-
- if (!distance)
- return false;
- m_page->mainFrame()->loader()->client()->navigateBackForward(distance);
- return true;
-}
-
-void BackForwardController::addItem(PassRefPtr<HistoryItem> item)
-{
- m_currentItem = item;
- m_client->didAddItem();
-}
-
-void BackForwardController::setCurrentItem(HistoryItem* item)
-{
- m_currentItem = item;
-}
-
-int BackForwardController::count() const
-{
- return backCount() + 1 + forwardCount();
-}
-
-int BackForwardController::backCount() const
-{
- return m_client->backListCount();
-}
-
-int BackForwardController::forwardCount() const
-{
- return m_client->forwardListCount();
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/history/BackForwardController.h b/chromium/third_party/WebKit/Source/core/history/BackForwardController.h
deleted file mode 100644
index 79c48a02a5a..00000000000
--- a/chromium/third_party/WebKit/Source/core/history/BackForwardController.h
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * Copyright (C) 2010 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef BackForwardController_h
-#define BackForwardController_h
-
-#include "wtf/Forward.h"
-#include "wtf/Noncopyable.h"
-#include "wtf/RefPtr.h"
-
-namespace WebCore {
-
-class BackForwardClient;
-class HistoryItem;
-class Page;
-
-// FIXME: Why does this class exist? It seems to delegate almost entirely to Page, and perhaps should be part of Page's implementation.
-class BackForwardController {
- WTF_MAKE_NONCOPYABLE(BackForwardController); WTF_MAKE_FAST_ALLOCATED;
-public:
- ~BackForwardController();
-
- static PassOwnPtr<BackForwardController> create(Page*, BackForwardClient*);
-
- BackForwardClient* client() const { return m_client; }
-
- bool goBackOrForward(int distance);
- bool goBack() { return goBackOrForward(-1); }
- bool goForward() { return goBackOrForward(1); }
-
- void addItem(PassRefPtr<HistoryItem>);
- void setCurrentItem(HistoryItem*);
- HistoryItem* currentItem() { return m_currentItem.get(); }
-
- int count() const;
- int backCount() const;
- int forwardCount() const;
-
-private:
- BackForwardController(Page*, BackForwardClient*);
-
- Page* m_page;
- BackForwardClient* m_client;
-
- // FIXME: Ideally, we could derive this from HistoryController, but the rules for setting it are non-obvious.
- RefPtr<HistoryItem> m_currentItem;
-};
-
-} // namespace WebCore
-
-#endif // BackForwardController_h
diff --git a/chromium/third_party/WebKit/Source/core/history/HistoryItem.cpp b/chromium/third_party/WebKit/Source/core/history/HistoryItem.cpp
index a61fc2cf0b0..a26929a2865 100644
--- a/chromium/third_party/WebKit/Source/core/history/HistoryItem.cpp
+++ b/chromium/third_party/WebKit/Source/core/history/HistoryItem.cpp
@@ -26,16 +26,11 @@
#include "config.h"
#include "core/history/HistoryItem.h"
-#include "bindings/v8/SerializedScriptValue.h"
#include "core/dom/Document.h"
-#include "core/platform/network/ResourceRequest.h"
+#include "platform/network/ResourceRequest.h"
#include "wtf/CurrentTime.h"
#include "wtf/text/CString.h"
-#ifndef NDEBUG
-#include <stdio.h>
-#endif
-
namespace WebCore {
static long long generateSequenceNumber()
@@ -47,12 +42,10 @@ static long long generateSequenceNumber()
}
HistoryItem::HistoryItem()
- : m_lastVisitedTime(0)
- , m_pageScaleFactor(0)
- , m_isTargetItem(false)
- , m_visitCount(0)
+ : m_pageScaleFactor(0)
, m_itemSequenceNumber(generateSequenceNumber())
, m_documentSequenceNumber(generateSequenceNumber())
+ , m_targetFrameID(0)
{
}
@@ -66,16 +59,13 @@ inline HistoryItem::HistoryItem(const HistoryItem& item)
, m_originalURLString(item.m_originalURLString)
, m_referrer(item.m_referrer)
, m_target(item.m_target)
- , m_parent(item.m_parent)
- , m_title(item.m_title)
- , m_displayTitle(item.m_displayTitle)
- , m_lastVisitedTime(item.m_lastVisitedTime)
, m_scrollPoint(item.m_scrollPoint)
, m_pageScaleFactor(item.m_pageScaleFactor)
- , m_isTargetItem(item.m_isTargetItem)
- , m_visitCount(item.m_visitCount)
+ , m_documentState(item.m_documentState)
, m_itemSequenceNumber(item.m_itemSequenceNumber)
, m_documentSequenceNumber(item.m_documentSequenceNumber)
+ , m_targetFrameID(item.m_targetFrameID)
+ , m_stateObject(item.m_stateObject)
, m_formContentType(item.m_formContentType)
{
if (item.m_formData)
@@ -96,25 +86,14 @@ void HistoryItem::reset()
{
m_urlString = String();
m_originalURLString = String();
- m_referrer = String();
+ m_referrer = nullAtom;
m_target = String();
- m_parent = String();
- m_title = String();
- m_displayTitle = String();
-
- m_lastVisitedTime = 0;
-
- m_isTargetItem = false;
- m_visitCount = 0;
-
m_itemSequenceNumber = generateSequenceNumber();
-
m_stateObject = 0;
m_documentSequenceNumber = generateSequenceNumber();
-
+ m_targetFrameID = 0;
m_formData = 0;
- m_formContentType = String();
-
+ m_formContentType = nullAtom;
clearChildren();
}
@@ -130,21 +109,6 @@ const String& HistoryItem::originalURLString() const
return m_originalURLString;
}
-const String& HistoryItem::title() const
-{
- return m_title;
-}
-
-const String& HistoryItem::alternateTitle() const
-{
- return m_displayTitle;
-}
-
-double HistoryItem::lastVisitedTime() const
-{
- return m_lastVisitedTime;
-}
-
KURL HistoryItem::url() const
{
return KURL(ParsedURLString, m_urlString);
@@ -155,7 +119,7 @@ KURL HistoryItem::originalURL() const
return KURL(ParsedURLString, m_originalURLString);
}
-const String& HistoryItem::referrer() const
+const AtomicString& HistoryItem::referrer() const
{
return m_referrer;
}
@@ -165,16 +129,6 @@ const String& HistoryItem::target() const
return m_target;
}
-const String& HistoryItem::parent() const
-{
- return m_parent;
-}
-
-void HistoryItem::setAlternateTitle(const String& alternateTitle)
-{
- m_displayTitle = alternateTitle;
-}
-
void HistoryItem::setURLString(const String& urlString)
{
if (m_urlString != urlString)
@@ -192,48 +146,16 @@ void HistoryItem::setOriginalURLString(const String& urlString)
m_originalURLString = urlString;
}
-void HistoryItem::setReferrer(const String& referrer)
+void HistoryItem::setReferrer(const AtomicString& referrer)
{
m_referrer = referrer;
}
-void HistoryItem::setTitle(const String& title)
-{
- m_title = title;
-}
-
void HistoryItem::setTarget(const String& target)
{
m_target = target;
}
-void HistoryItem::setParent(const String& parent)
-{
- m_parent = parent;
-}
-
-void HistoryItem::recordVisitAtTime(double time)
-{
- m_lastVisitedTime = time;
- ++m_visitCount;
-}
-
-void HistoryItem::setLastVisitedTime(double time)
-{
- if (m_lastVisitedTime != time)
- recordVisitAtTime(time);
-}
-
-int HistoryItem::visitCount() const
-{
- return m_visitCount;
-}
-
-void HistoryItem::setVisitCount(int count)
-{
- m_visitCount = count;
-}
-
const IntPoint& HistoryItem::scrollPoint() const
{
return m_scrollPoint;
@@ -275,16 +197,6 @@ void HistoryItem::clearDocumentState()
m_documentState.clear();
}
-bool HistoryItem::isTargetItem() const
-{
- return m_isTargetItem;
-}
-
-void HistoryItem::setIsTargetItem(bool flag)
-{
- m_isTargetItem = flag;
-}
-
void HistoryItem::setStateObject(PassRefPtr<SerializedScriptValue> object)
{
m_stateObject = object;
@@ -292,44 +204,9 @@ void HistoryItem::setStateObject(PassRefPtr<SerializedScriptValue> object)
void HistoryItem::addChildItem(PassRefPtr<HistoryItem> child)
{
- ASSERT(!childItemWithTarget(child->target()));
m_children.append(child);
}
-void HistoryItem::setChildItem(PassRefPtr<HistoryItem> child)
-{
- ASSERT(!child->isTargetItem());
- unsigned size = m_children.size();
- for (unsigned i = 0; i < size; ++i) {
- if (m_children[i]->target() == child->target()) {
- child->setIsTargetItem(m_children[i]->isTargetItem());
- m_children[i] = child;
- return;
- }
- }
- m_children.append(child);
-}
-
-HistoryItem* HistoryItem::childItemWithTarget(const String& target) const
-{
- unsigned size = m_children.size();
- for (unsigned i = 0; i < size; ++i) {
- if (m_children[i]->target() == target)
- return m_children[i].get();
- }
- return 0;
-}
-
-HistoryItem* HistoryItem::childItemWithDocumentSequenceNumber(long long number) const
-{
- unsigned size = m_children.size();
- for (unsigned i = 0; i < size; ++i) {
- if (m_children[i]->documentSequenceNumber() == number)
- return m_children[i].get();
- }
- return 0;
-}
-
const HistoryItemVector& HistoryItem::children() const
{
return m_children;
@@ -340,74 +217,7 @@ void HistoryItem::clearChildren()
m_children.clear();
}
-bool HistoryItem::isAncestorOf(const HistoryItem* item) const
-{
- for (size_t i = 0; i < m_children.size(); ++i) {
- HistoryItem* child = m_children[i].get();
- if (child == item)
- return true;
- if (child->isAncestorOf(item))
- return true;
- }
- return false;
-}
-
-// We do same-document navigation if going to a different item and if either of the following is true:
-// - The other item corresponds to the same document (for history entries created via pushState or fragment changes).
-// - The other item corresponds to the same set of documents, including frames (for history entries created via regular navigation)
-bool HistoryItem::shouldDoSameDocumentNavigationTo(HistoryItem* otherItem) const
-{
- if (this == otherItem)
- return false;
-
- if (stateObject() || otherItem->stateObject())
- return documentSequenceNumber() == otherItem->documentSequenceNumber();
-
- if ((url().hasFragmentIdentifier() || otherItem->url().hasFragmentIdentifier()) && equalIgnoringFragmentIdentifier(url(), otherItem->url()))
- return documentSequenceNumber() == otherItem->documentSequenceNumber();
-
- return hasSameDocumentTree(otherItem);
-}
-
-// Does a recursive check that this item and its descendants have the same
-// document sequence numbers as the other item.
-bool HistoryItem::hasSameDocumentTree(HistoryItem* otherItem) const
-{
- if (documentSequenceNumber() != otherItem->documentSequenceNumber())
- return false;
-
- if (children().size() != otherItem->children().size())
- return false;
-
- for (size_t i = 0; i < children().size(); i++) {
- HistoryItem* child = children()[i].get();
- HistoryItem* otherChild = otherItem->childItemWithDocumentSequenceNumber(child->documentSequenceNumber());
- if (!otherChild || !child->hasSameDocumentTree(otherChild))
- return false;
- }
-
- return true;
-}
-
-// Does a non-recursive check that this item and its immediate children have the
-// same frames as the other item.
-bool HistoryItem::hasSameFrames(HistoryItem* otherItem) const
-{
- if (target() != otherItem->target())
- return false;
-
- if (children().size() != otherItem->children().size())
- return false;
-
- for (size_t i = 0; i < children().size(); i++) {
- if (!otherItem->childItemWithTarget(children()[i]->target()))
- return false;
- }
-
- return true;
-}
-
-String HistoryItem::formContentType() const
+const AtomicString& HistoryItem::formContentType() const
{
return m_formContentType;
}
@@ -423,7 +233,7 @@ void HistoryItem::setFormInfoFromRequest(const ResourceRequest& request)
m_formContentType = request.httpContentType();
} else {
m_formData = 0;
- m_formContentType = String();
+ m_formContentType = nullAtom;
}
}
@@ -432,7 +242,7 @@ void HistoryItem::setFormData(PassRefPtr<FormData> formData)
m_formData = formData;
}
-void HistoryItem::setFormContentType(const String& formContentType)
+void HistoryItem::setFormContentType(const AtomicString& formContentType)
{
m_formContentType = formContentType;
}
@@ -448,37 +258,5 @@ bool HistoryItem::isCurrentDocument(Document* doc) const
return equalIgnoringFragmentIdentifier(url(), doc->url());
}
-#ifndef NDEBUG
-
-int HistoryItem::showTree() const
-{
- return showTreeWithIndent(0);
-}
-
-int HistoryItem::showTreeWithIndent(unsigned indentLevel) const
-{
- Vector<char> prefix;
- for (unsigned i = 0; i < indentLevel; ++i)
- prefix.append(" ", 2);
- prefix.append("\0", 1);
-
- fprintf(stderr, "%s+-%s (%p)\n", prefix.data(), m_urlString.utf8().data(), this);
-
- int totalSubItems = 0;
- for (unsigned i = 0; i < m_children.size(); ++i)
- totalSubItems += m_children[i]->showTreeWithIndent(indentLevel + 1);
- return totalSubItems + 1;
-}
-
-#endif
-
} // namespace WebCore
-#ifndef NDEBUG
-
-int showTree(const WebCore::HistoryItem* item)
-{
- return item->showTree();
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/history/HistoryItem.h b/chromium/third_party/WebKit/Source/core/history/HistoryItem.h
index 8ac78ab71be..e2fa91eb49a 100644
--- a/chromium/third_party/WebKit/Source/core/history/HistoryItem.h
+++ b/chromium/third_party/WebKit/Source/core/history/HistoryItem.h
@@ -28,7 +28,7 @@
#define HistoryItem_h
#include "bindings/v8/SerializedScriptValue.h"
-#include "core/platform/graphics/IntPoint.h"
+#include "platform/geometry/IntPoint.h"
#include "wtf/RefCounted.h"
#include "wtf/text/WTFString.h"
@@ -56,24 +56,14 @@ public:
const String& originalURLString() const;
const String& urlString() const;
- const String& title() const;
-
- double lastVisitedTime() const;
-
- void setAlternateTitle(const String& alternateTitle);
- const String& alternateTitle() const;
-
- const String& parent() const;
KURL url() const;
KURL originalURL() const;
- const String& referrer() const;
+
+ const AtomicString& referrer() const;
const String& target() const;
- bool isTargetItem() const;
FormData* formData();
- String formContentType() const;
-
- int visitCount() const;
+ const AtomicString& formContentType() const;
const IntPoint& scrollPoint() const;
void setScrollPoint(const IntPoint&);
@@ -89,11 +79,8 @@ public:
void setURL(const KURL&);
void setURLString(const String&);
void setOriginalURLString(const String&);
- void setReferrer(const String&);
+ void setReferrer(const AtomicString&);
void setTarget(const String&);
- void setParent(const String&);
- void setTitle(const String&);
- void setIsTargetItem(bool);
void setStateObject(PassRefPtr<SerializedScriptValue> object);
SerializedScriptValue* stateObject() const { return m_stateObject.get(); }
@@ -104,49 +91,27 @@ public:
void setDocumentSequenceNumber(long long number) { m_documentSequenceNumber = number; }
long long documentSequenceNumber() const { return m_documentSequenceNumber; }
+ void setTargetFrameID(int64_t id) { m_targetFrameID = id; }
+ int64_t targetFrameID() const { return m_targetFrameID; }
+
void setFormInfoFromRequest(const ResourceRequest&);
void setFormData(PassRefPtr<FormData>);
- void setFormContentType(const String&);
-
- void setVisitCount(int);
+ void setFormContentType(const AtomicString&);
void addChildItem(PassRefPtr<HistoryItem>);
- void setChildItem(PassRefPtr<HistoryItem>);
- HistoryItem* childItemWithTarget(const String&) const;
- HistoryItem* childItemWithDocumentSequenceNumber(long long number) const;
const HistoryItemVector& children() const;
void clearChildren();
- bool isAncestorOf(const HistoryItem*) const;
-
- bool shouldDoSameDocumentNavigationTo(HistoryItem* otherItem) const;
- bool hasSameFrames(HistoryItem* otherItem) const;
-
- void setLastVisitedTime(double);
bool isCurrentDocument(Document*) const;
-#ifndef NDEBUG
- int showTree() const;
- int showTreeWithIndent(unsigned indentLevel) const;
-#endif
-
private:
HistoryItem();
explicit HistoryItem(const HistoryItem&);
- void recordVisitAtTime(double);
-
- bool hasSameDocumentTree(HistoryItem* otherItem) const;
-
String m_urlString;
String m_originalURLString;
- String m_referrer;
+ AtomicString m_referrer;
String m_target;
- String m_parent;
- String m_title;
- String m_displayTitle;
-
- double m_lastVisitedTime;
IntPoint m_scrollPoint;
float m_pageScaleFactor;
@@ -154,9 +119,6 @@ private:
HistoryItemVector m_children;
- bool m_isTargetItem;
- int m_visitCount;
-
// If two HistoryItems have the same item sequence number, then they are
// clones of one another. Traversing history from one such HistoryItem to
// another is a no-op. HistoryItem clones are created for parent and
@@ -168,20 +130,17 @@ private:
// such HistoryItem to another preserves the document.
int64_t m_documentSequenceNumber;
+ int64_t m_targetFrameID;
+
// Support for HTML5 History
RefPtr<SerializedScriptValue> m_stateObject;
// info used to repost form data
RefPtr<FormData> m_formData;
- String m_formContentType;
+ AtomicString m_formContentType;
}; //class HistoryItem
} //namespace WebCore
-#ifndef NDEBUG
-// Outside the WebCore namespace for ease of invocation from gdb.
-extern "C" int showTree(const WebCore::HistoryItem*);
-#endif
-
#endif // HISTORYITEM_H
diff --git a/chromium/third_party/WebKit/Source/core/html/ClassList.cpp b/chromium/third_party/WebKit/Source/core/html/ClassList.cpp
index 4f435e3f49c..ba44f7b0b0d 100644
--- a/chromium/third_party/WebKit/Source/core/html/ClassList.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/ClassList.cpp
@@ -25,7 +25,6 @@
#include "config.h"
#include "core/html/ClassList.h"
-#include "core/dom/SpaceSplitString.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/html/DOMURL.cpp b/chromium/third_party/WebKit/Source/core/html/DOMURL.cpp
deleted file mode 100644
index a7b7f7175cb..00000000000
--- a/chromium/third_party/WebKit/Source/core/html/DOMURL.cpp
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- * Copyright (C) 2012 Motorola Mobility Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/html/DOMURL.h"
-
-#include "core/dom/ScriptExecutionContext.h"
-#include "core/fetch/MemoryCache.h"
-#include "core/fileapi/Blob.h"
-#include "core/fileapi/BlobURL.h"
-#include "core/html/PublicURLManager.h"
-#include "weborigin/KURL.h"
-#include "wtf/MainThread.h"
-
-namespace WebCore {
-
-String DOMURL::createObjectURL(ScriptExecutionContext* scriptExecutionContext, Blob* blob)
-{
- if (!scriptExecutionContext || !blob)
- return String();
- return createPublicURL(scriptExecutionContext, blob);
-}
-
-String DOMURL::createPublicURL(ScriptExecutionContext* scriptExecutionContext, URLRegistrable* registrable)
-{
- KURL publicURL = BlobURL::createPublicURL(scriptExecutionContext->securityOrigin());
- if (publicURL.isEmpty())
- return String();
-
- scriptExecutionContext->publicURLManager().registerURL(scriptExecutionContext->securityOrigin(), publicURL, registrable);
-
- return publicURL.string();
-}
-
-void DOMURL::revokeObjectURL(ScriptExecutionContext* scriptExecutionContext, const String& urlString)
-{
- if (!scriptExecutionContext)
- return;
-
- KURL url(KURL(), urlString);
- MemoryCache::removeURLFromCache(scriptExecutionContext, url);
- scriptExecutionContext->publicURLManager().revoke(url);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/html/DOMURL.h b/chromium/third_party/WebKit/Source/core/html/DOMURL.h
deleted file mode 100644
index a3784de69e5..00000000000
--- a/chromium/third_party/WebKit/Source/core/html/DOMURL.h
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- * Copyright (C) 2012 Motorola Mobility Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef DOMURL_h
-#define DOMURL_h
-
-#include "wtf/Forward.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-
-namespace WebCore {
-
-class Blob;
-class ScriptExecutionContext;
-class URLRegistrable;
-
-class DOMURL : public RefCounted<DOMURL> {
-
-public:
- static PassRefPtr<DOMURL> create() { return adoptRef(new DOMURL); }
-
- static String createObjectURL(ScriptExecutionContext*, Blob*);
- static void revokeObjectURL(ScriptExecutionContext*, const String&);
-
- static String createPublicURL(ScriptExecutionContext*, URLRegistrable*);
-};
-
-} // namespace WebCore
-
-#endif // DOMURL_h
diff --git a/chromium/third_party/WebKit/Source/core/html/FormAssociatedElement.cpp b/chromium/third_party/WebKit/Source/core/html/FormAssociatedElement.cpp
index e800826d4fb..ce1f4b58ddb 100644
--- a/chromium/third_party/WebKit/Source/core/html/FormAssociatedElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/FormAssociatedElement.cpp
@@ -66,10 +66,10 @@ ValidityState* FormAssociatedElement::validity()
return m_validityState.get();
}
-void FormAssociatedElement::didMoveToNewDocument(Document* oldDocument)
+void FormAssociatedElement::didMoveToNewDocument(Document& oldDocument)
{
HTMLElement* element = toHTMLElement(this);
- if (oldDocument && element->fastHasAttribute(formAttr))
+ if (element->fastHasAttribute(formAttr))
m_formAttributeTargetObserver = nullptr;
}
@@ -122,8 +122,9 @@ HTMLFormElement* FormAssociatedElement::findAssociatedForm(const HTMLElement* el
void FormAssociatedElement::formRemovedFromTree(const Node* formRoot)
{
ASSERT(m_form);
- if (toHTMLElement(this)->highestAncestor() != formRoot)
- setForm(0);
+ if (toHTMLElement(this)->highestAncestor() == formRoot)
+ return;
+ setForm(0);
}
void FormAssociatedElement::setForm(HTMLFormElement* newForm)
@@ -135,7 +136,7 @@ void FormAssociatedElement::setForm(HTMLFormElement* newForm)
m_form->removeFormElement(this);
m_form = newForm;
if (m_form)
- m_form->registerFormElement(this);
+ m_form->registerFormElement(*this);
didChangeForm();
}
@@ -274,19 +275,30 @@ bool FormAssociatedElement::isFormControlElementWithState() const
return false;
}
-const HTMLElement* toHTMLElement(const FormAssociatedElement* associatedElement)
+const HTMLElement& toHTMLElement(const FormAssociatedElement& associatedElement)
{
- if (associatedElement->isFormControlElement())
+ if (associatedElement.isFormControlElement())
return toHTMLFormControlElement(associatedElement);
// Assumes the element is an HTMLObjectElement
return toHTMLObjectElement(associatedElement);
}
+const HTMLElement* toHTMLElement(const FormAssociatedElement* associatedElement)
+{
+ ASSERT(associatedElement);
+ return &toHTMLElement(*associatedElement);
+}
+
HTMLElement* toHTMLElement(FormAssociatedElement* associatedElement)
{
return const_cast<HTMLElement*>(toHTMLElement(static_cast<const FormAssociatedElement*>(associatedElement)));
}
+HTMLElement& toHTMLElement(FormAssociatedElement& associatedElement)
+{
+ return const_cast<HTMLElement&>(toHTMLElement(static_cast<const FormAssociatedElement&>(associatedElement)));
+}
+
PassOwnPtr<FormAttributeTargetObserver> FormAttributeTargetObserver::create(const AtomicString& id, FormAssociatedElement* element)
{
return adoptPtr(new FormAttributeTargetObserver(id, element));
diff --git a/chromium/third_party/WebKit/Source/core/html/FormAssociatedElement.h b/chromium/third_party/WebKit/Source/core/html/FormAssociatedElement.h
index 85b5e74355c..15f2fa1fbc8 100644
--- a/chromium/third_party/WebKit/Source/core/html/FormAssociatedElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/FormAssociatedElement.h
@@ -93,7 +93,7 @@ protected:
void insertedInto(ContainerNode*);
void removedFrom(ContainerNode*);
- void didMoveToNewDocument(Document* oldDocument);
+ void didMoveToNewDocument(Document& oldDocument);
void setForm(HTMLFormElement*);
void formAttributeChanged();
@@ -119,7 +119,9 @@ private:
};
HTMLElement* toHTMLElement(FormAssociatedElement*);
+HTMLElement& toHTMLElement(FormAssociatedElement&);
const HTMLElement* toHTMLElement(const FormAssociatedElement*);
+const HTMLElement& toHTMLElement(const FormAssociatedElement&);
} // namespace
diff --git a/chromium/third_party/WebKit/Source/core/html/FormData.idl b/chromium/third_party/WebKit/Source/core/html/FormData.idl
index 0391d3adc99..73dcbfb9479 100644
--- a/chromium/third_party/WebKit/Source/core/html/FormData.idl
+++ b/chromium/third_party/WebKit/Source/core/html/FormData.idl
@@ -29,7 +29,7 @@
*/
[
- CustomConstructor(optional HTMLFormElement form),
+ Constructor([Default=Undefined] optional HTMLFormElement form),
ImplementedAs=DOMFormData
] interface FormData {
// void append(DOMString name, DOMString value);
diff --git a/chromium/third_party/WebKit/Source/core/html/FormDataList.cpp b/chromium/third_party/WebKit/Source/core/html/FormDataList.cpp
index 6096a232ad7..b564d2cc102 100644
--- a/chromium/third_party/WebKit/Source/core/html/FormDataList.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/FormDataList.cpp
@@ -21,7 +21,9 @@
#include "config.h"
#include "core/html/FormDataList.h"
-#include "core/platform/text/LineEnding.h"
+#include "core/fileapi/File.h"
+#include "platform/network/FormDataBuilder.h"
+#include "platform/text/LineEnding.h"
namespace WebCore {
@@ -46,4 +48,101 @@ void FormDataList::appendBlob(PassRefPtr<Blob> blob, const String& filename)
m_items.append(Item(blob, filename));
}
+PassRefPtr<FormData> FormDataList::createFormData(const WTF::TextEncoding& encoding, FormData::EncodingType encodingType)
+{
+ RefPtr<FormData> result = FormData::create();
+ appendKeyValuePairItemsTo(result.get(), encoding, false, encodingType);
+ return result.release();
+}
+
+PassRefPtr<FormData> FormDataList::createMultiPartFormData(const WTF::TextEncoding& encoding)
+{
+ RefPtr<FormData> result = FormData::create();
+ appendKeyValuePairItemsTo(result.get(), encoding, true);
+ return result.release();
+}
+
+void FormDataList::appendKeyValuePairItemsTo(FormData* formData, const WTF::TextEncoding& encoding, bool isMultiPartForm, FormData::EncodingType encodingType)
+{
+ if (isMultiPartForm)
+ formData->setBoundary(FormDataBuilder::generateUniqueBoundaryString());
+
+ Vector<char> encodedData;
+
+ const Vector<FormDataList::Item>& items = this->items();
+ size_t formDataListSize = items.size();
+ ASSERT(!(formDataListSize % 2));
+ for (size_t i = 0; i < formDataListSize; i += 2) {
+ const FormDataList::Item& key = items[i];
+ const FormDataList::Item& value = items[i + 1];
+ if (isMultiPartForm) {
+ Vector<char> header;
+ FormDataBuilder::beginMultiPartHeader(header, formData->boundary().data(), key.data());
+
+ // If the current type is blob, then we also need to include the filename
+ if (value.blob()) {
+ String name;
+ if (value.blob()->isFile()) {
+ File* file = toFile(value.blob());
+ // For file blob, use the filename (or relative path if it is present) as the name.
+ name = file->webkitRelativePath().isEmpty() ? file->name() : file->webkitRelativePath();
+
+ // If a filename is passed in FormData.append(), use it instead of the file blob's name.
+ if (!value.filename().isNull())
+ name = value.filename();
+ } else {
+ // For non-file blob, use the filename if it is passed in FormData.append().
+ if (!value.filename().isNull())
+ name = value.filename();
+ else
+ name = "blob";
+ }
+
+ // We have to include the filename=".." part in the header, even if the filename is empty
+ FormDataBuilder::addFilenameToMultiPartHeader(header, encoding, name);
+
+ // Add the content type if available, or "application/octet-stream" otherwise (RFC 1867).
+ String contentType;
+ if (value.blob()->type().isEmpty())
+ contentType = "application/octet-stream";
+ else
+ contentType = value.blob()->type();
+ FormDataBuilder::addContentTypeToMultiPartHeader(header, contentType.latin1());
+ }
+
+ FormDataBuilder::finishMultiPartHeader(header);
+
+ // Append body
+ formData->appendData(header.data(), header.size());
+ if (value.blob()) {
+ if (value.blob()->hasBackingFile()) {
+ File* file = toFile(value.blob());
+ // Do not add the file if the path is empty.
+ if (!file->path().isEmpty())
+ formData->appendFile(file->path());
+ if (!file->fileSystemURL().isEmpty())
+ formData->appendFileSystemURL(file->fileSystemURL());
+ } else {
+ formData->appendBlob(value.blob()->uuid(), value.blob()->blobDataHandle());
+ }
+ } else {
+ formData->appendData(value.data().data(), value.data().length());
+ }
+ formData->appendData("\r\n", 2);
+ } else {
+ // Omit the name "isindex" if it's the first form data element.
+ // FIXME: Why is this a good rule? Is this obsolete now?
+ if (encodedData.isEmpty() && key.data() == "isindex")
+ FormDataBuilder::encodeStringAsFormData(encodedData, value.data());
+ else
+ FormDataBuilder::addKeyValuePairAsFormData(encodedData, key.data(), value.data(), encodingType);
+ }
+ }
+
+ if (isMultiPartForm)
+ FormDataBuilder::addBoundaryToMultiPartHeader(encodedData, formData->boundary().data(), true);
+
+ formData->appendData(encodedData.data(), encodedData.size());
+}
+
} // namespace
diff --git a/chromium/third_party/WebKit/Source/core/html/FormDataList.h b/chromium/third_party/WebKit/Source/core/html/FormDataList.h
index 0a6e3a482f8..123e566f621 100644
--- a/chromium/third_party/WebKit/Source/core/html/FormDataList.h
+++ b/chromium/third_party/WebKit/Source/core/html/FormDataList.h
@@ -22,6 +22,7 @@
#define FormDataList_h
#include "core/fileapi/Blob.h"
+#include "platform/network/FormData.h"
#include "wtf/Forward.h"
#include "wtf/text/CString.h"
#include "wtf/text/TextEncoding.h"
@@ -72,7 +73,12 @@ public:
const Vector<Item>& items() const { return m_items; }
const WTF::TextEncoding& encoding() const { return m_encoding; }
+ PassRefPtr<FormData> createFormData(const WTF::TextEncoding&, FormData::EncodingType = FormData::FormURLEncoded);
+ PassRefPtr<FormData> createMultiPartFormData(const WTF::TextEncoding&);
+
private:
+ void appendKeyValuePairItemsTo(FormData*, const WTF::TextEncoding&, bool isMultiPartForm, FormData::EncodingType = FormData::FormURLEncoded);
+
void appendString(const CString&);
void appendString(const String&);
void appendBlob(PassRefPtr<Blob>, const String& filename);
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLAllCollection.h b/chromium/third_party/WebKit/Source/core/html/HTMLAllCollection.h
index bf6cddf4b39..d5f1106ac5d 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLAllCollection.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLAllCollection.h
@@ -30,7 +30,7 @@
namespace WebCore {
-class HTMLAllCollection : public HTMLCollection {
+class HTMLAllCollection FINAL : public HTMLCollection {
public:
static PassRefPtr<HTMLAllCollection> create(Node*, CollectionType);
virtual ~HTMLAllCollection();
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLAllCollection.idl b/chromium/third_party/WebKit/Source/core/html/HTMLAllCollection.idl
index 9f87dd441de..3508f8bc731 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLAllCollection.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLAllCollection.idl
@@ -24,10 +24,9 @@
*/
[
- CustomLegacyCall,
- MasqueradesAsUndefined,
- GenerateIsReachable=ownerNode,
- DependentLifetime
+ Custom=LegacyCallAsFunction,
+ DependentLifetime,
+ GenerateVisitDOMWrapper=ownerNode,
] interface HTMLAllCollection {
readonly attribute unsigned long length;
[ImplementedAs=item] getter Node (unsigned long index);
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLAnchorElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLAnchorElement.cpp
index ec288edf168..8a0e9f372d8 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLAnchorElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLAnchorElement.cpp
@@ -24,12 +24,12 @@
#include "config.h"
#include "core/html/HTMLAnchorElement.h"
-#include "HTMLNames.h"
#include "core/dom/Attribute.h"
-#include "core/dom/EventNames.h"
-#include "core/dom/KeyboardEvent.h"
-#include "core/dom/MouseEvent.h"
#include "core/editing/FrameSelection.h"
+#include "core/events/KeyboardEvent.h"
+#include "core/events/MouseEvent.h"
+#include "core/events/ThreadLocalEventNames.h"
+#include "core/frame/Frame.h"
#include "core/html/HTMLFormElement.h"
#include "core/html/HTMLImageElement.h"
#include "core/html/parser/HTMLParserIdioms.h"
@@ -40,30 +40,28 @@
#include "core/loader/PingLoader.h"
#include "core/page/Chrome.h"
#include "core/page/ChromeClient.h"
-#include "core/page/Frame.h"
#include "core/page/Page.h"
-#include "core/page/Settings.h"
-#include "core/platform/HistogramSupport.h"
-#include "core/platform/PlatformMouseEvent.h"
-#include "core/platform/network/DNS.h"
-#include "core/platform/network/ResourceRequest.h"
+#include "core/frame/Settings.h"
#include "core/rendering/RenderImage.h"
#include "core/svg/graphics/SVGImage.h"
+#include "platform/PlatformMouseEvent.h"
+#include "platform/network/DNS.h"
+#include "platform/network/ResourceRequest.h"
+#include "platform/weborigin/KnownPorts.h"
+#include "platform/weborigin/SecurityOrigin.h"
+#include "platform/weborigin/SecurityPolicy.h"
#include "public/platform/Platform.h"
#include "public/platform/WebPrescientNetworking.h"
#include "public/platform/WebURL.h"
-#include "weborigin/KnownPorts.h"
-#include "weborigin/SecurityOrigin.h"
-#include "weborigin/SecurityPolicy.h"
#include "wtf/text/StringBuilder.h"
namespace WebCore {
namespace {
-void preconnectToURL(const KURL& url, WebKit::WebPreconnectMotivation motivation)
+void preconnectToURL(const KURL& url, blink::WebPreconnectMotivation motivation)
{
- WebKit::WebPrescientNetworking* prescientNetworking = WebKit::Platform::current()->prescientNetworking();
+ blink::WebPrescientNetworking* prescientNetworking = blink::Platform::current()->prescientNetworking();
if (!prescientNetworking)
return;
@@ -92,11 +90,11 @@ private:
void handleMouseOut(Event* event);
void handleLeftMouseDown(Event* event);
void handleGestureTapUnconfirmed(Event*);
- void handleGestureTapDown(Event*);
+ void handleGestureShowPress(Event*);
void handleClick(Event* event);
bool shouldPrefetch(const KURL&);
- void prefetch(WebKit::WebPreconnectMotivation);
+ void prefetch(blink::WebPreconnectMotivation);
HTMLAnchorElement* m_anchorElement;
double m_mouseOverTimestamp;
@@ -134,15 +132,6 @@ HTMLAnchorElement::~HTMLAnchorElement()
clearRootEditableElementForSelectionOnMouseDown();
}
-// This function does not allow leading spaces before the port number.
-static unsigned parsePortFromStringPosition(const String& value, unsigned portStart, unsigned& portEnd)
-{
- portEnd = portStart;
- while (isASCIIDigit(value[portEnd]))
- ++portEnd;
- return value.substring(portStart, portEnd - portStart).toUInt();
-}
-
bool HTMLAnchorElement::supportsFocus() const
{
if (rendererIsEditable())
@@ -225,10 +214,10 @@ void HTMLAnchorElement::defaultEventHandler(Event* event)
if (rendererIsEditable()) {
// This keeps track of the editable block that the selection was in (if it was in one) just before the link was clicked
// for the LiveWhenNotFocused editable link behavior
- if (event->type() == eventNames().mousedownEvent && event->isMouseEvent() && toMouseEvent(event)->button() != RightButton && document().frame()) {
+ if (event->type() == EventTypeNames::mousedown && event->isMouseEvent() && toMouseEvent(event)->button() != RightButton && document().frame()) {
setRootEditableElementForSelectionOnMouseDown(document().frame()->selection().rootEditableElement());
m_wasShiftKeyDownOnMouseDown = toMouseEvent(event)->shiftKey();
- } else if (event->type() == eventNames().mouseoverEvent) {
+ } else if (event->type() == EventTypeNames::mouseover) {
// These are cleared on mouseover and not mouseout because their values are needed for drag events,
// but drag events happen after mouse out events.
clearRootEditableElementForSelectionOnMouseDown();
@@ -240,7 +229,7 @@ void HTMLAnchorElement::defaultEventHandler(Event* event)
HTMLElement::defaultEventHandler(event);
}
-void HTMLAnchorElement::setActive(bool down, bool pause)
+void HTMLAnchorElement::setActive(bool down)
{
if (rendererIsEditable()) {
EditableLinkBehavior editableLinkBehavior = EditableLinkDefaultBehavior;
@@ -269,7 +258,7 @@ void HTMLAnchorElement::setActive(bool down, bool pause)
}
- ContainerNode::setActive(down, pause);
+ ContainerNode::setActive(down);
}
void HTMLAnchorElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
@@ -343,6 +332,26 @@ void HTMLAnchorElement::setHref(const AtomicString& value)
setAttribute(hrefAttr, value);
}
+KURL HTMLAnchorElement::url() const
+{
+ return href();
+}
+
+void HTMLAnchorElement::setURL(const KURL& url)
+{
+ setHref(AtomicString(url.string()));
+}
+
+String HTMLAnchorElement::input() const
+{
+ return getAttribute(hrefAttr);
+}
+
+void HTMLAnchorElement::setInput(const String& value)
+{
+ setHref(value);
+}
+
bool HTMLAnchorElement::hasRel(uint32_t relation) const
{
return m_linkRelations & relation;
@@ -373,180 +382,12 @@ String HTMLAnchorElement::target() const
return getAttribute(targetAttr);
}
-String HTMLAnchorElement::hash() const
-{
- String fragmentIdentifier = href().fragmentIdentifier();
- if (fragmentIdentifier.isEmpty())
- return emptyString();
- return AtomicString(String("#" + fragmentIdentifier));
-}
-
-void HTMLAnchorElement::setHash(const String& value)
-{
- KURL url = href();
- if (value[0] == '#')
- url.setFragmentIdentifier(value.substring(1));
- else
- url.setFragmentIdentifier(value);
- setHref(url.string());
-}
-
-String HTMLAnchorElement::host() const
-{
- const KURL& url = href();
- if (url.hostEnd() == url.pathStart())
- return url.host();
- if (isDefaultPortForProtocol(url.port(), url.protocol()))
- return url.host();
- return url.host() + ":" + String::number(url.port());
-}
-
-void HTMLAnchorElement::setHost(const String& value)
-{
- if (value.isEmpty())
- return;
- KURL url = href();
- if (!url.canSetHostOrPort())
- return;
-
- size_t separator = value.find(':');
- if (!separator)
- return;
-
- if (separator == kNotFound)
- url.setHostAndPort(value);
- else {
- unsigned portEnd;
- unsigned port = parsePortFromStringPosition(value, separator + 1, portEnd);
- if (!port) {
- // http://dev.w3.org/html5/spec/infrastructure.html#url-decomposition-idl-attributes
- // specifically goes against RFC 3986 (p3.2) and
- // requires setting the port to "0" if it is set to empty string.
- url.setHostAndPort(value.substring(0, separator + 1) + "0");
- } else {
- if (isDefaultPortForProtocol(port, url.protocol()))
- url.setHostAndPort(value.substring(0, separator));
- else
- url.setHostAndPort(value.substring(0, portEnd));
- }
- }
- setHref(url.string());
-}
-
-String HTMLAnchorElement::hostname() const
-{
- return href().host();
-}
-
-void HTMLAnchorElement::setHostname(const String& value)
-{
- // Before setting new value:
- // Remove all leading U+002F SOLIDUS ("/") characters.
- unsigned i = 0;
- unsigned hostLength = value.length();
- while (value[i] == '/')
- i++;
-
- if (i == hostLength)
- return;
-
- KURL url = href();
- if (!url.canSetHostOrPort())
- return;
-
- url.setHost(value.substring(i));
- setHref(url.string());
-}
-
-String HTMLAnchorElement::pathname() const
-{
- return href().path();
-}
-
-void HTMLAnchorElement::setPathname(const String& value)
-{
- KURL url = href();
- if (!url.canSetPathname())
- return;
-
- if (value[0] == '/')
- url.setPath(value);
- else
- url.setPath("/" + value);
-
- setHref(url.string());
-}
-
-String HTMLAnchorElement::port() const
-{
- if (href().hasPort())
- return String::number(href().port());
-
- return emptyString();
-}
-
-void HTMLAnchorElement::setPort(const String& value)
-{
- KURL url = href();
- if (!url.canSetHostOrPort())
- return;
-
- // http://dev.w3.org/html5/spec/infrastructure.html#url-decomposition-idl-attributes
- // specifically goes against RFC 3986 (p3.2) and
- // requires setting the port to "0" if it is set to empty string.
- unsigned port = value.toUInt();
- if (isDefaultPortForProtocol(port, url.protocol()))
- url.removePort();
- else
- url.setPort(port);
-
- setHref(url.string());
-}
-
-String HTMLAnchorElement::protocol() const
-{
- return href().protocol() + ":";
-}
-
-void HTMLAnchorElement::setProtocol(const String& value)
-{
- KURL url = href();
- url.setProtocol(value);
- setHref(url.string());
-}
-
-String HTMLAnchorElement::search() const
-{
- String query = href().query();
- return query.isEmpty() ? emptyString() : "?" + query;
-}
-
-String HTMLAnchorElement::origin() const
-{
- RefPtr<SecurityOrigin> origin = SecurityOrigin::create(href());
- return origin->toString();
-}
-
-void HTMLAnchorElement::setSearch(const String& value)
-{
- KURL url = href();
- String newSearch = (value[0] == '?') ? value.substring(1) : value;
- // Make sure that '#' in the query does not leak to the hash.
- url.setQuery(newSearch.replaceWithLiteral('#', "%23"));
-
- setHref(url.string());
-}
String HTMLAnchorElement::text()
{
return innerText();
}
-String HTMLAnchorElement::toString() const
-{
- return href().string();
-}
-
bool HTMLAnchorElement::isLiveLink() const
{
return isLink() && treatLinkAsLiveForEventType(m_wasShiftKeyDownOnMouseDown ? MouseEventWithShiftKey : MouseEventWithoutShiftKey);
@@ -575,26 +416,28 @@ void HTMLAnchorElement::handleClick(Event* event)
appendServerMapMousePosition(url, event);
KURL completedURL = document().completeURL(url.toString());
+ // Schedule the ping before the frame load. Prerender in Chrome may kill the renderer as soon as the navigation is
+ // sent out.
+ sendPings(completedURL);
+
ResourceRequest request(completedURL);
if (prefetchEventHandler()->hasIssuedPreconnect())
- frame->loader()->client()->dispatchWillRequestAfterPreconnect(request);
+ frame->loader().client()->dispatchWillRequestAfterPreconnect(request);
if (hasAttribute(downloadAttr)) {
if (!hasRel(RelationNoReferrer)) {
- String referrer = SecurityPolicy::generateReferrerHeader(document().referrerPolicy(), completedURL, frame->loader()->outgoingReferrer());
+ String referrer = SecurityPolicy::generateReferrerHeader(document().referrerPolicy(), completedURL, document().outgoingReferrer());
if (!referrer.isEmpty())
request.setHTTPReferrer(referrer);
}
- frame->loader()->client()->loadURLExternally(request, NavigationPolicyDownload, fastGetAttribute(downloadAttr));
+ frame->loader().client()->loadURLExternally(request, NavigationPolicyDownload, fastGetAttribute(downloadAttr));
} else {
- FrameLoadRequest frameRequest(document().securityOrigin(), request, target());
+ FrameLoadRequest frameRequest(&document(), request, target());
frameRequest.setTriggeringEvent(event);
if (hasRel(RelationNoReferrer))
frameRequest.setShouldSendReferrer(NeverSendReferrer);
- frame->loader()->load(frameRequest);
+ frame->loader().load(frameRequest);
}
-
- sendPings(completedURL);
}
HTMLAnchorElement::EventType HTMLAnchorElement::eventType(Event* event)
@@ -636,12 +479,12 @@ bool HTMLAnchorElement::treatLinkAsLiveForEventType(EventType eventType) const
bool isEnterKeyKeydownEvent(Event* event)
{
- return event->type() == eventNames().keydownEvent && event->isKeyboardEvent() && toKeyboardEvent(event)->keyIdentifier() == "Enter";
+ return event->type() == EventTypeNames::keydown && event->isKeyboardEvent() && toKeyboardEvent(event)->keyIdentifier() == "Enter";
}
bool isLinkClick(Event* event)
{
- return event->type() == eventNames().clickEvent && (!event->isMouseEvent() || toMouseEvent(event)->button() != RightButton);
+ return event->type() == EventTypeNames::click && (!event->isMouseEvent() || toMouseEvent(event)->button() != RightButton);
}
bool HTMLAnchorElement::willRespondToMouseClickEvents()
@@ -714,15 +557,15 @@ void HTMLAnchorElement::PrefetchEventHandler::handleEvent(Event* event)
if (!shouldPrefetch(m_anchorElement->href()))
return;
- if (event->type() == eventNames().mouseoverEvent)
+ if (event->type() == EventTypeNames::mouseover)
handleMouseOver(event);
- else if (event->type() == eventNames().mouseoutEvent)
+ else if (event->type() == EventTypeNames::mouseout)
handleMouseOut(event);
- else if (event->type() == eventNames().mousedownEvent && event->isMouseEvent() && toMouseEvent(event)->button() == LeftButton)
+ else if (event->type() == EventTypeNames::mousedown && event->isMouseEvent() && toMouseEvent(event)->button() == LeftButton)
handleLeftMouseDown(event);
- else if (event->type() == eventNames().gesturetapdownEvent)
- handleGestureTapDown(event);
- else if (event->type() == eventNames().gesturetapunconfirmedEvent)
+ else if (event->type() == EventTypeNames::gestureshowpress)
+ handleGestureShowPress(event);
+ else if (event->type() == EventTypeNames::gesturetapunconfirmed)
handleGestureTapUnconfirmed(event);
else if (isLinkClick(event))
handleClick(event);
@@ -733,9 +576,9 @@ void HTMLAnchorElement::PrefetchEventHandler::handleMouseOver(Event* event)
if (m_mouseOverTimestamp == 0.0) {
m_mouseOverTimestamp = event->timeStamp();
- HistogramSupport::histogramEnumeration("MouseEventPrefetch.MouseOvers", 0, 2);
+ blink::Platform::current()->histogramEnumeration("MouseEventPrefetch.MouseOvers", 0, 2);
- prefetch(WebKit::WebPreconnectMotivationLinkMouseOver);
+ prefetch(blink::WebPreconnectMotivationLinkMouseOver);
}
}
@@ -743,7 +586,7 @@ void HTMLAnchorElement::PrefetchEventHandler::handleMouseOut(Event* event)
{
if (m_mouseOverTimestamp > 0.0) {
double mouseOverDuration = convertDOMTimeStampToSeconds(event->timeStamp() - m_mouseOverTimestamp);
- HistogramSupport::histogramCustomCounts("MouseEventPrefetch.MouseOverDuration_NoClick", mouseOverDuration * 1000, 0, 10000, 100);
+ blink::Platform::current()->histogramCustomCounts("MouseEventPrefetch.MouseOverDuration_NoClick", mouseOverDuration * 1000, 0, 10000, 100);
m_mouseOverTimestamp = 0.0;
}
@@ -753,27 +596,27 @@ void HTMLAnchorElement::PrefetchEventHandler::handleLeftMouseDown(Event* event)
{
m_mouseDownTimestamp = event->timeStamp();
- HistogramSupport::histogramEnumeration("MouseEventPrefetch.MouseDowns", 0, 2);
+ blink::Platform::current()->histogramEnumeration("MouseEventPrefetch.MouseDowns", 0, 2);
- prefetch(WebKit::WebPreconnectMotivationLinkMouseDown);
+ prefetch(blink::WebPreconnectMotivationLinkMouseDown);
}
void HTMLAnchorElement::PrefetchEventHandler::handleGestureTapUnconfirmed(Event* event)
{
m_hadTapUnconfirmed = true;
- HistogramSupport::histogramEnumeration("MouseEventPrefetch.TapUnconfirmeds", 0, 2);
+ blink::Platform::current()->histogramEnumeration("MouseEventPrefetch.TapUnconfirmeds", 0, 2);
- prefetch(WebKit::WebPreconnectMotivationLinkTapUnconfirmed);
+ prefetch(blink::WebPreconnectMotivationLinkTapUnconfirmed);
}
-void HTMLAnchorElement::PrefetchEventHandler::handleGestureTapDown(Event* event)
+void HTMLAnchorElement::PrefetchEventHandler::handleGestureShowPress(Event* event)
{
m_tapDownTimestamp = event->timeStamp();
- HistogramSupport::histogramEnumeration("MouseEventPrefetch.TapDowns", 0, 2);
+ blink::Platform::current()->histogramEnumeration("MouseEventPrefetch.TapDowns", 0, 2);
- prefetch(WebKit::WebPreconnectMotivationLinkTapDown);
+ prefetch(blink::WebPreconnectMotivationLinkTapDown);
}
void HTMLAnchorElement::PrefetchEventHandler::handleClick(Event* event)
@@ -782,27 +625,27 @@ void HTMLAnchorElement::PrefetchEventHandler::handleClick(Event* event)
if (capturedMouseOver) {
double mouseOverDuration = convertDOMTimeStampToSeconds(event->timeStamp() - m_mouseOverTimestamp);
- HistogramSupport::histogramCustomCounts("MouseEventPrefetch.MouseOverDuration_Click", mouseOverDuration * 1000, 0, 10000, 100);
+ blink::Platform::current()->histogramCustomCounts("MouseEventPrefetch.MouseOverDuration_Click", mouseOverDuration * 1000, 0, 10000, 100);
}
bool capturedMouseDown = (m_mouseDownTimestamp > 0.0);
- HistogramSupport::histogramEnumeration("MouseEventPrefetch.MouseDownFollowedByClick", capturedMouseDown, 2);
+ blink::Platform::current()->histogramEnumeration("MouseEventPrefetch.MouseDownFollowedByClick", capturedMouseDown, 2);
if (capturedMouseDown) {
double mouseDownDuration = convertDOMTimeStampToSeconds(event->timeStamp() - m_mouseDownTimestamp);
- HistogramSupport::histogramCustomCounts("MouseEventPrefetch.MouseDownDuration_Click", mouseDownDuration * 1000, 0, 10000, 100);
+ blink::Platform::current()->histogramCustomCounts("MouseEventPrefetch.MouseDownDuration_Click", mouseDownDuration * 1000, 0, 10000, 100);
}
bool capturedTapDown = (m_tapDownTimestamp > 0.0);
if (capturedTapDown) {
double tapDownDuration = convertDOMTimeStampToSeconds(event->timeStamp() - m_tapDownTimestamp);
- HistogramSupport::histogramCustomCounts("MouseEventPrefetch.TapDownDuration_Click", tapDownDuration * 1000, 0, 10000, 100);
+ blink::Platform::current()->histogramCustomCounts("MouseEventPrefetch.TapDownDuration_Click", tapDownDuration * 1000, 0, 10000, 100);
}
int flags = (m_hadTapUnconfirmed ? 2 : 0) | (capturedTapDown ? 1 : 0);
- HistogramSupport::histogramEnumeration("MouseEventPrefetch.PreTapEventsFollowedByClick", flags, 4);
+ blink::Platform::current()->histogramEnumeration("MouseEventPrefetch.PreTapEventsFollowedByClick", flags, 4);
}
bool HTMLAnchorElement::PrefetchEventHandler::shouldPrefetch(const KURL& url)
@@ -810,7 +653,7 @@ bool HTMLAnchorElement::PrefetchEventHandler::shouldPrefetch(const KURL& url)
if (m_hadHREFChanged)
return false;
- if (m_anchorElement->hasEventListeners(eventNames().clickEvent))
+ if (m_anchorElement->hasEventListeners(EventTypeNames::click))
return false;
if (!url.protocolIsInHTTPFamily())
@@ -835,7 +678,7 @@ bool HTMLAnchorElement::PrefetchEventHandler::shouldPrefetch(const KURL& url)
return true;
}
-void HTMLAnchorElement::PrefetchEventHandler::prefetch(WebKit::WebPreconnectMotivation motivation)
+void HTMLAnchorElement::PrefetchEventHandler::prefetch(blink::WebPreconnectMotivation motivation)
{
const KURL& url = m_anchorElement->href();
@@ -843,7 +686,7 @@ void HTMLAnchorElement::PrefetchEventHandler::prefetch(WebKit::WebPreconnectMoti
return;
// The precision of current MouseOver trigger is too low to actually trigger preconnects.
- if (motivation == WebKit::WebPreconnectMotivationLinkMouseOver)
+ if (motivation == blink::WebPreconnectMotivationLinkMouseOver)
return;
preconnectToURL(url, motivation);
@@ -852,7 +695,7 @@ void HTMLAnchorElement::PrefetchEventHandler::prefetch(WebKit::WebPreconnectMoti
bool HTMLAnchorElement::isInteractiveContent() const
{
- return true;
+ return isLink();
}
}
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLAnchorElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLAnchorElement.h
index cf32f898cb4..bfb0d634729 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLAnchorElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLAnchorElement.h
@@ -25,8 +25,9 @@
#define HTMLAnchorElement_h
#include "HTMLNames.h"
+#include "core/dom/DOMURLUtils.h"
#include "core/html/HTMLElement.h"
-#include "core/platform/LinkHash.h"
+#include "platform/LinkHash.h"
namespace WebCore {
@@ -53,7 +54,7 @@ enum {
// RelationUp = 0x00020000,
};
-class HTMLAnchorElement : public HTMLElement {
+class HTMLAnchorElement : public HTMLElement, public DOMURLUtils {
public:
static PassRefPtr<HTMLAnchorElement> create(Document&);
static PassRefPtr<HTMLAnchorElement> create(const QualifiedName&, Document&);
@@ -65,33 +66,14 @@ public:
const AtomicString& name() const;
- String hash() const;
- void setHash(const String&);
+ virtual KURL url() const OVERRIDE;
+ virtual void setURL(const KURL&) OVERRIDE;
- String host() const;
- void setHost(const String&);
-
- String hostname() const;
- void setHostname(const String&);
-
- String pathname() const;
- void setPathname(const String&);
-
- String port() const;
- void setPort(const String&);
-
- String protocol() const;
- void setProtocol(const String&);
-
- String search() const;
- void setSearch(const String&);
-
- String origin() const;
+ virtual String input() const OVERRIDE;
+ virtual void setInput(const String&) OVERRIDE;
String text();
- String toString() const;
-
bool isLiveLink() const;
virtual bool willRespondToMouseClickEvents() OVERRIDE;
@@ -112,7 +94,7 @@ private:
virtual bool isMouseFocusable() const;
virtual bool isKeyboardFocusable() const OVERRIDE;
virtual void defaultEventHandler(Event*);
- virtual void setActive(bool active = true, bool pause = false);
+ virtual void setActive(bool = true) OVERRIDE FINAL;
virtual void accessKeyAction(bool sendMouseEvents);
virtual bool isURLAttribute(const Attribute&) const OVERRIDE;
virtual bool canStartSelection() const;
@@ -169,12 +151,13 @@ inline bool isHTMLAnchorElement(const Element* element)
return element->hasTagName(HTMLNames::aTag);
}
-inline HTMLAnchorElement* toHTMLAnchorElement(Node* node)
+inline bool isHTMLAnchorElement(const Element& element)
{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || isHTMLAnchorElement(node));
- return static_cast<HTMLAnchorElement*>(node);
+ return element.hasTagName(HTMLNames::aTag);
}
+DEFINE_NODE_TYPE_CASTS(HTMLAnchorElement, hasTagName(HTMLNames::aTag));
+
} // namespace WebCore
#endif // HTMLAnchorElement_h
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLAnchorElement.idl b/chromium/third_party/WebKit/Source/core/html/HTMLAnchorElement.idl
index e0c70687ad9..525c307807f 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLAnchorElement.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLAnchorElement.idl
@@ -22,7 +22,6 @@ interface HTMLAnchorElement : HTMLElement {
[Reflect] attribute DOMString charset;
[Reflect] attribute DOMString coords;
[Reflect] attribute DOMString download;
- [Reflect, URL] attribute DOMString href;
[Reflect] attribute DOMString hreflang;
[Reflect] attribute DOMString name;
[Reflect] attribute DOMString ping;
@@ -32,18 +31,8 @@ interface HTMLAnchorElement : HTMLElement {
[Reflect] attribute DOMString target;
[Reflect] attribute DOMString type;
- [TreatNullAs=NullString] attribute DOMString hash;
- [TreatNullAs=NullString] attribute DOMString host;
- [TreatNullAs=NullString] attribute DOMString hostname;
- [TreatNullAs=NullString] attribute DOMString pathname;
- [TreatNullAs=NullString] attribute DOMString port;
- [TreatNullAs=NullString] attribute DOMString protocol;
- [TreatNullAs=NullString] attribute DOMString search;
-
- [TreatNullAs=NullString] readonly attribute DOMString origin;
-
readonly attribute DOMString text;
-
- [NotEnumerable] DOMString toString();
};
+// force rebuild: crbug.com/307023
+HTMLAnchorElement implements URLUtils;
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLAppletElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLAppletElement.cpp
index 74756882c43..242e2ea2110 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLAppletElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLAppletElement.cpp
@@ -25,32 +25,35 @@
#include "core/html/HTMLAppletElement.h"
#include "HTMLNames.h"
+#include "core/dom/shadow/ShadowRoot.h"
#include "core/html/HTMLParamElement.h"
#include "core/loader/FrameLoader.h"
#include "core/loader/FrameLoaderClient.h"
-#include "core/page/ContentSecurityPolicy.h"
-#include "core/page/Frame.h"
-#include "core/page/Settings.h"
-#include "core/platform/Widget.h"
+#include "core/frame/ContentSecurityPolicy.h"
+#include "core/frame/Frame.h"
+#include "core/frame/Settings.h"
#include "core/rendering/RenderApplet.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/Widget.h"
+#include "platform/weborigin/KURL.h"
+#include "platform/weborigin/SecurityOrigin.h"
namespace WebCore {
using namespace HTMLNames;
-HTMLAppletElement::HTMLAppletElement(const QualifiedName& tagName, Document& document, bool createdByParser)
- : HTMLPlugInImageElement(tagName, document, createdByParser, ShouldNotPreferPlugInsForImages)
+HTMLAppletElement::HTMLAppletElement(Document& document, bool createdByParser)
+ : HTMLPlugInElement(appletTag, document, createdByParser, ShouldNotPreferPlugInsForImages)
{
- ASSERT(hasTagName(appletTag));
ScriptWrappable::init(this);
m_serviceType = "application/x-java-applet";
}
-PassRefPtr<HTMLAppletElement> HTMLAppletElement::create(const QualifiedName& tagName, Document& document, bool createdByParser)
+PassRefPtr<HTMLAppletElement> HTMLAppletElement::create(Document& document, bool createdByParser)
{
- return adoptRef(new HTMLAppletElement(tagName, document, createdByParser));
+ RefPtr<HTMLAppletElement> element = adoptRef(new HTMLAppletElement(document, createdByParser));
+ element->ensureUserAgentShadowRoot();
+ return element.release();
}
void HTMLAppletElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
@@ -65,19 +68,25 @@ void HTMLAppletElement::parseAttribute(const QualifiedName& name, const AtomicSt
return;
}
- HTMLPlugInImageElement::parseAttribute(name, value);
+ HTMLPlugInElement::parseAttribute(name, value);
+}
+
+bool HTMLAppletElement::isURLAttribute(const Attribute& attribute) const
+{
+ return attribute.name() == codebaseAttr || attribute.name() == objectAttr
+ || HTMLPlugInElement::isURLAttribute(attribute);
}
bool HTMLAppletElement::rendererIsNeeded(const RenderStyle& style)
{
- if (!fastHasAttribute(codeAttr))
+ if (!fastHasAttribute(codeAttr) && !hasAuthorShadowRoot())
return false;
- return HTMLPlugInImageElement::rendererIsNeeded(style);
+ return HTMLPlugInElement::rendererIsNeeded(style);
}
RenderObject* HTMLAppletElement::createRenderer(RenderStyle* style)
{
- if (!canEmbedJava())
+ if (!canEmbedJava() || hasAuthorShadowRoot())
return RenderObject::createObject(this, style);
return new RenderApplet(this);
@@ -87,7 +96,7 @@ RenderWidget* HTMLAppletElement::renderWidgetForJSBindings() const
{
if (!canEmbedJava())
return 0;
- return HTMLPlugInImageElement::renderWidgetForJSBindings();
+ return HTMLPlugInElement::renderWidgetForJSBindings();
}
RenderWidget* HTMLAppletElement::existingRenderWidget() const
@@ -95,8 +104,9 @@ RenderWidget* HTMLAppletElement::existingRenderWidget() const
return renderPart();
}
-void HTMLAppletElement::updateWidget(PluginCreationOption)
+void HTMLAppletElement::updateWidgetInternal()
{
+ ASSERT(!m_isDelayingLoadEvent);
setNeedsWidgetUpdate(false);
// FIXME: This should ASSERT isFinishedParsingChildren() instead.
if (!isFinishedParsingChildren())
@@ -115,36 +125,43 @@ void HTMLAppletElement::updateWidget(PluginCreationOption)
Vector<String> paramNames;
Vector<String> paramValues;
- paramNames.append("code");
- paramValues.append(getAttribute(codeAttr).string());
-
const AtomicString& codeBase = getAttribute(codebaseAttr);
if (!codeBase.isNull()) {
KURL codeBaseURL = document().completeURL(codeBase);
- if (!document().securityOrigin()->canDisplay(codeBaseURL)) {
- FrameLoader::reportLocalLoadFailed(frame, codeBaseURL.string());
- return;
- }
- const char javaAppletMimeType[] = "application/x-java-applet";
- if (!document().contentSecurityPolicy()->allowObjectFromSource(codeBaseURL)
- || !document().contentSecurityPolicy()->allowPluginType(javaAppletMimeType, javaAppletMimeType, codeBaseURL))
- return;
paramNames.append("codeBase");
paramValues.append(codeBase.string());
}
- const AtomicString& name = document().isHTMLDocument() ? getNameAttribute() : getIdAttribute();
- if (!name.isNull()) {
- paramNames.append("name");
- paramValues.append(name.string());
- }
-
const AtomicString& archive = getAttribute(archiveAttr);
if (!archive.isNull()) {
paramNames.append("archive");
paramValues.append(archive.string());
}
+ const AtomicString& code = getAttribute(codeAttr);
+ paramNames.append("code");
+ paramValues.append(code.string());
+
+ // If the 'codebase' attribute is set, it serves as a relative root for the file that the Java
+ // plugin will load. If the 'code' attribute is set, and the 'archive' is not set, then we need
+ // to check the url generated by resolving 'code' against 'codebase'. If the 'archive'
+ // attribute is set, then 'code' points to a class inside the archive, so we need to check the
+ // url generated by resolving 'archive' against 'codebase'.
+ KURL urlToCheck;
+ KURL rootURL = codeBase.isNull() ? document().url() : document().completeURL(codeBase);
+ if (!archive.isNull())
+ urlToCheck = KURL(rootURL, archive);
+ else if (!code.isNull())
+ urlToCheck = KURL(rootURL, code);
+ if (!canEmbedURL(urlToCheck))
+ return;
+
+ const AtomicString& name = document().isHTMLDocument() ? getNameAttribute() : getIdAttribute();
+ if (!name.isNull()) {
+ paramNames.append("name");
+ paramValues.append(name.string());
+ }
+
paramNames.append("baseURL");
KURL baseURL = document().baseURL();
paramValues.append(baseURL.string());
@@ -168,15 +185,15 @@ void HTMLAppletElement::updateWidget(PluginCreationOption)
}
RefPtr<Widget> widget;
- if (frame->loader()->allowPlugins(AboutToInstantiatePlugin))
- widget = frame->loader()->client()->createJavaAppletWidget(roundedIntSize(LayoutSize(contentWidth, contentHeight)), this, baseURL, paramNames, paramValues);
+ if (frame->loader().allowPlugins(AboutToInstantiatePlugin))
+ widget = frame->loader().client()->createJavaAppletWidget(roundedIntSize(LayoutSize(contentWidth, contentHeight)), this, baseURL, paramNames, paramValues);
if (!widget) {
if (!renderer->showsUnavailablePluginIndicator())
renderer->setPluginUnavailabilityReason(RenderEmbeddedObject::PluginMissing);
return;
}
- frame->loader()->setContainsPlugins();
+ document().setContainsPlugins();
renderer->setWidget(widget);
}
@@ -189,10 +206,27 @@ bool HTMLAppletElement::canEmbedJava() const
if (!settings)
return false;
- if (!settings->isJavaEnabled())
+ if (!settings->javaEnabled())
return false;
return true;
}
+bool HTMLAppletElement::canEmbedURL(const KURL& url) const
+{
+ DEFINE_STATIC_LOCAL(String, appletMimeType, ("application/x-java-applet"));
+
+ if (!document().securityOrigin()->canDisplay(url)) {
+ FrameLoader::reportLocalLoadFailed(document().frame(), url.string());
+ return false;
+ }
+
+ if (!document().contentSecurityPolicy()->allowObjectFromSource(url)
+ || !document().contentSecurityPolicy()->allowPluginType(appletMimeType, appletMimeType, url)) {
+ renderEmbeddedObject()->setPluginUnavailabilityReason(RenderEmbeddedObject::PluginBlockedByContentSecurityPolicy);
+ return false;
+ }
+ return true;
+}
+
}
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLAppletElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLAppletElement.h
index 0408a3b2dee..41c5193a81e 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLAppletElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLAppletElement.h
@@ -23,29 +23,33 @@
#ifndef HTMLAppletElement_h
#define HTMLAppletElement_h
-#include "core/html/HTMLPlugInImageElement.h"
+#include "core/html/HTMLPlugInElement.h"
namespace WebCore {
-class HTMLAppletElement FINAL : public HTMLPlugInImageElement {
+class KURL;
+
+class HTMLAppletElement FINAL : public HTMLPlugInElement {
public:
- static PassRefPtr<HTMLAppletElement> create(const QualifiedName&, Document&, bool createdByParser);
+ static PassRefPtr<HTMLAppletElement> create(Document&, bool createdByParser);
protected:
virtual RenderWidget* renderWidgetForJSBindings() const OVERRIDE;
private:
- HTMLAppletElement(const QualifiedName&, Document&, bool createdByParser);
+ HTMLAppletElement(Document&, bool createdByParser);
virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
+ virtual bool isURLAttribute(const Attribute&) const OVERRIDE;
virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE;
virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
virtual RenderWidget* existingRenderWidget() const OVERRIDE;
- virtual void updateWidget(PluginCreationOption) OVERRIDE;
+ virtual void updateWidgetInternal() OVERRIDE;
bool canEmbedJava() const;
+ bool canEmbedURL(const KURL&) const;
virtual bool shouldRegisterAsNamedItem() const OVERRIDE { return true; }
virtual bool shouldRegisterAsExtraNamedItem() const OVERRIDE { return true; }
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLAppletElement.idl b/chromium/third_party/WebKit/Source/core/html/HTMLAppletElement.idl
index efb2855afd4..283e205ffdf 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLAppletElement.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLAppletElement.idl
@@ -19,22 +19,21 @@
*/
[
- CustomLegacyCall
+ Custom=LegacyCallAsFunction,
] interface HTMLAppletElement : HTMLElement {
[Reflect] attribute DOMString align;
[Reflect] attribute DOMString alt;
[Reflect] attribute DOMString archive;
[Reflect] attribute DOMString code;
- [Reflect] attribute DOMString codeBase;
+ [Reflect, URL] attribute DOMString codeBase;
[Reflect] attribute DOMString height;
- [Reflect] attribute DOMString hspace;
+ [Reflect] attribute unsigned long hspace;
[Reflect] attribute DOMString name;
- [Reflect] attribute DOMString _object; // "object" is a reserved word
- [Reflect] attribute DOMString vspace;
+ [Reflect, URL] attribute DOMString _object; // "object" is a reserved word
+ [Reflect] attribute unsigned long vspace;
[Reflect] attribute DOMString width;
[Custom, NotEnumerable] getter boolean (unsigned long index);
[Custom] setter boolean (unsigned long index, Node value);
[Custom, NotEnumerable] getter Node (DOMString name);
[Custom] setter Node (DOMString name, Node value);
};
-
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLAreaElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLAreaElement.cpp
index 46ee04ac109..73cd5fb7ac0 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLAreaElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLAreaElement.cpp
@@ -25,11 +25,11 @@
#include "HTMLNames.h"
#include "core/html/HTMLImageElement.h"
#include "core/html/HTMLMapElement.h"
-#include "core/platform/graphics/Path.h"
-#include "core/platform/graphics/transforms/AffineTransform.h"
#include "core/rendering/HitTestResult.h"
#include "core/rendering/RenderImage.h"
#include "core/rendering/RenderView.h"
+#include "platform/graphics/Path.h"
+#include "platform/transforms/AffineTransform.h"
using namespace std;
@@ -37,18 +37,17 @@ namespace WebCore {
using namespace HTMLNames;
-inline HTMLAreaElement::HTMLAreaElement(const QualifiedName& tagName, Document& document)
- : HTMLAnchorElement(tagName, document)
+inline HTMLAreaElement::HTMLAreaElement(Document& document)
+ : HTMLAnchorElement(areaTag, document)
, m_lastSize(-1, -1)
, m_shape(Unknown)
{
- ASSERT(hasTagName(areaTag));
ScriptWrappable::init(this);
}
-PassRefPtr<HTMLAreaElement> HTMLAreaElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<HTMLAreaElement> HTMLAreaElement::create(Document& document)
{
- return adoptRef(new HTMLAreaElement(tagName, document));
+ return adoptRef(new HTMLAreaElement(document));
}
void HTMLAreaElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLAreaElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLAreaElement.h
index 2fc4cebc81c..35f34387d52 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLAreaElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLAreaElement.h
@@ -24,7 +24,7 @@
#define HTMLAreaElement_h
#include "core/html/HTMLAnchorElement.h"
-#include "core/platform/graphics/LayoutRect.h"
+#include "platform/geometry/LayoutRect.h"
namespace WebCore {
@@ -34,7 +34,7 @@ class Path;
class HTMLAreaElement FINAL : public HTMLAnchorElement {
public:
- static PassRefPtr<HTMLAreaElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<HTMLAreaElement> create(Document&);
bool isDefault() const { return m_shape == Default; }
@@ -47,7 +47,7 @@ public:
HTMLImageElement* imageElement() const;
private:
- HTMLAreaElement(const QualifiedName&, Document&);
+ explicit HTMLAreaElement(Document&);
virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
virtual bool supportsFocus() const;
@@ -78,11 +78,7 @@ inline bool isHTMLAreaElement(const Element* element)
return element->hasTagName(HTMLNames::areaTag);
}
-inline HTMLAreaElement* toHTMLAreaElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || isHTMLAreaElement(node));
- return static_cast<HTMLAreaElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(HTMLAreaElement, hasTagName(HTMLNames::areaTag));
} //namespace
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLAreaElement.idl b/chromium/third_party/WebKit/Source/core/html/HTMLAreaElement.idl
index a9c1fa7dea6..1ad7233a1f9 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLAreaElement.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLAreaElement.idl
@@ -21,19 +21,11 @@
interface HTMLAreaElement : HTMLElement {
[Reflect] attribute DOMString alt;
[Reflect] attribute DOMString coords;
- [Reflect, URL] attribute DOMString href;
[Reflect] attribute boolean noHref;
[Reflect] attribute DOMString ping;
[Reflect] attribute DOMString shape;
[Reflect] attribute DOMString target;
-
- // IE Extensions
- readonly attribute DOMString hash;
- readonly attribute DOMString host;
- readonly attribute DOMString hostname;
- readonly attribute DOMString pathname;
- readonly attribute DOMString port;
- readonly attribute DOMString protocol;
- readonly attribute DOMString search;
};
+// force rebuild: crbug.com/307023
+HTMLAreaElement implements URLUtils;
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLAttributeNames.in b/chromium/third_party/WebKit/Source/core/html/HTMLAttributeNames.in
index 02f566703e7..4ae7745ae45 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLAttributeNames.in
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLAttributeNames.in
@@ -4,7 +4,7 @@ namespaceURI="http://www.w3.org/1999/xhtml"
attrsNullNamespace
abbr
-accept_charset
+accept-charset
accept
accesskey
action
@@ -121,7 +121,7 @@ high
href
hreflang
hspace
-http_equiv
+http-equiv
id
incremental
indeterminate
@@ -180,12 +180,15 @@ onbeforeload
onbeforepaste
onbeforeunload
onblur
+oncancel
oncanplay
oncanplaythrough
onchange
onclick
+onclose
oncontextmenu
oncopy
+oncuechange
oncut
ondblclick
ondrag
@@ -212,6 +215,7 @@ onload
onloadeddata
onloadedmetadata
onloadstart
+onmessage
onmousedown
onmouseenter
onmouseleave
@@ -242,6 +246,7 @@ onselect
onselectstart
onselectionchange
onwebkitspeechchange
+onshow
onstalled
onstorage
onsuspend
@@ -271,7 +276,6 @@ onwebkittransitionend
onwheel
open
optimum
-part
pattern
placeholder
pluginspage
@@ -339,7 +343,6 @@ valign
value
valuetype
version
-viewsource
vlink
vspace
webkitallowfullscreen
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLAudioElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLAudioElement.cpp
index c83650a247b..bdc0d9f3a04 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLAudioElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLAudioElement.cpp
@@ -32,28 +32,25 @@ namespace WebCore {
using namespace HTMLNames;
-HTMLAudioElement::HTMLAudioElement(const QualifiedName& tagName, Document& document, bool createdByParser)
- : HTMLMediaElement(tagName, document, createdByParser)
+HTMLAudioElement::HTMLAudioElement(Document& document, bool createdByParser)
+ : HTMLMediaElement(audioTag, document, createdByParser)
{
- ASSERT(hasTagName(audioTag));
ScriptWrappable::init(this);
}
-PassRefPtr<HTMLAudioElement> HTMLAudioElement::create(const QualifiedName& tagName, Document& document, bool createdByParser)
+PassRefPtr<HTMLAudioElement> HTMLAudioElement::create(Document& document, bool createdByParser)
{
- RefPtr<HTMLAudioElement> audioElement(adoptRef(new HTMLAudioElement(tagName, document, createdByParser)));
+ RefPtr<HTMLAudioElement> audioElement(adoptRef(new HTMLAudioElement(document, createdByParser)));
audioElement->suspendIfNeeded();
return audioElement.release();
}
-PassRefPtr<HTMLAudioElement> HTMLAudioElement::createForJSConstructor(Document& document, const String& src)
+PassRefPtr<HTMLAudioElement> HTMLAudioElement::createForJSConstructor(Document& document, const AtomicString& src)
{
- RefPtr<HTMLAudioElement> audio = adoptRef(new HTMLAudioElement(audioTag, document, false));
+ RefPtr<HTMLAudioElement> audio = adoptRef(new HTMLAudioElement(document, false));
audio->setPreload("auto");
- if (!src.isNull()) {
+ if (!src.isNull())
audio->setSrc(src);
- audio->scheduleDelayedAction(HTMLMediaElement::LoadMediaResource);
- }
audio->suspendIfNeeded();
return audio.release();
}
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLAudioElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLAudioElement.h
index 131891e6953..c69a3057630 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLAudioElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLAudioElement.h
@@ -35,13 +35,13 @@ class Document;
class HTMLAudioElement FINAL : public HTMLMediaElement {
public:
- static PassRefPtr<HTMLAudioElement> create(const QualifiedName&, Document&, bool);
- static PassRefPtr<HTMLAudioElement> createForJSConstructor(Document&, const String& src);
+ static PassRefPtr<HTMLAudioElement> create(Document&, bool);
+ static PassRefPtr<HTMLAudioElement> createForJSConstructor(Document&, const AtomicString& src);
private:
- HTMLAudioElement(const QualifiedName&, Document&, bool);
+ HTMLAudioElement(Document&, bool);
- virtual bool isVideo() const { return false; }
+ virtual bool isVideo() const OVERRIDE { return false; }
};
} //namespace
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLAudioElement.idl b/chromium/third_party/WebKit/Source/core/html/HTMLAudioElement.idl
index cbed9d663f9..ffb4769c23f 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLAudioElement.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLAudioElement.idl
@@ -24,7 +24,7 @@
*/
[
- EnabledAtRuntime=Media,
+ RuntimeEnabled=Media,
NamedConstructor=Audio([Default=NullString] optional DOMString src)
] interface HTMLAudioElement : HTMLMediaElement {
};
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLBDIElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLBDIElement.h
index d72e4a0cc0b..b5050a6ddee 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLBDIElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLBDIElement.h
@@ -27,14 +27,14 @@ namespace WebCore {
class HTMLBDIElement FINAL : public HTMLElement {
public:
- static PassRefPtr<HTMLBDIElement> create(const QualifiedName& name, Document& document)
+ static PassRefPtr<HTMLBDIElement> create(Document& document)
{
- return adoptRef(new HTMLBDIElement(name, document));
+ return adoptRef(new HTMLBDIElement(document));
}
private:
- HTMLBDIElement(const QualifiedName& name, Document& document)
- : HTMLElement(name, document)
+ explicit HTMLBDIElement(Document& document)
+ : HTMLElement(HTMLNames::bdiTag, document)
{
// FIXME: Rename setSelfOrAncestorHasDirAutoAttribute to reflect the fact bdi also uses this flag.
setSelfOrAncestorHasDirAutoAttribute(true);
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLBRElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLBRElement.cpp
index d92ac0c3e00..19b3aa9dab9 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLBRElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLBRElement.cpp
@@ -32,21 +32,15 @@ namespace WebCore {
using namespace HTMLNames;
-HTMLBRElement::HTMLBRElement(const QualifiedName& tagName, Document& document)
- : HTMLElement(tagName, document)
+HTMLBRElement::HTMLBRElement(Document& document)
+ : HTMLElement(brTag, document)
{
- ASSERT(hasTagName(brTag));
ScriptWrappable::init(this);
}
PassRefPtr<HTMLBRElement> HTMLBRElement::create(Document& document)
{
- return adoptRef(new HTMLBRElement(brTag, document));
-}
-
-PassRefPtr<HTMLBRElement> HTMLBRElement::create(const QualifiedName& tagName, Document& document)
-{
- return adoptRef(new HTMLBRElement(tagName, document));
+ return adoptRef(new HTMLBRElement(document));
}
bool HTMLBRElement::isPresentationAttribute(const QualifiedName& name) const
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLBRElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLBRElement.h
index fc6d5c48672..0188c71bd41 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLBRElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLBRElement.h
@@ -31,12 +31,11 @@ namespace WebCore {
class HTMLBRElement FINAL : public HTMLElement {
public:
static PassRefPtr<HTMLBRElement> create(Document&);
- static PassRefPtr<HTMLBRElement> create(const QualifiedName&, Document&);
virtual bool canContainRangeEndPoint() const { return false; }
private:
- HTMLBRElement(const QualifiedName&, Document&);
+ explicit HTMLBRElement(Document&);
virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
virtual void collectStyleForPresentationAttribute(const QualifiedName&, const AtomicString&, MutableStylePropertySet*) OVERRIDE;
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLBaseElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLBaseElement.cpp
index 34e5de2130f..6ec6654c17f 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLBaseElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLBaseElement.cpp
@@ -33,16 +33,15 @@ namespace WebCore {
using namespace HTMLNames;
-inline HTMLBaseElement::HTMLBaseElement(const QualifiedName& tagName, Document& document)
- : HTMLElement(tagName, document)
+inline HTMLBaseElement::HTMLBaseElement(Document& document)
+ : HTMLElement(baseTag, document)
{
- ASSERT(hasTagName(baseTag));
ScriptWrappable::init(this);
}
-PassRefPtr<HTMLBaseElement> HTMLBaseElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<HTMLBaseElement> HTMLBaseElement::create(Document& document)
{
- return adoptRef(new HTMLBaseElement(tagName, document));
+ return adoptRef(new HTMLBaseElement(document));
}
void HTMLBaseElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLBaseElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLBaseElement.h
index 7a52c37f8f2..39c8bfeadff 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLBaseElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLBaseElement.h
@@ -29,13 +29,13 @@ namespace WebCore {
class HTMLBaseElement FINAL : public HTMLElement {
public:
- static PassRefPtr<HTMLBaseElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<HTMLBaseElement> create(Document&);
KURL href() const;
void setHref(const AtomicString&);
private:
- HTMLBaseElement(const QualifiedName&, Document&);
+ explicit HTMLBaseElement(Document&);
virtual String target() const;
virtual bool isURLAttribute(const Attribute&) const OVERRIDE;
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLBaseElement.idl b/chromium/third_party/WebKit/Source/core/html/HTMLBaseElement.idl
index 4d9d39f0f45..87e614f6f9e 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLBaseElement.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLBaseElement.idl
@@ -18,6 +18,6 @@
*/
interface HTMLBaseElement : HTMLElement {
- [TreatNullAs=NullString] attribute DOMString href;
+ attribute DOMString href;
[Reflect] attribute DOMString target;
};
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLBaseFontElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLBaseFontElement.cpp
deleted file mode 100644
index a12f10fde34..00000000000
--- a/chromium/third_party/WebKit/Source/core/html/HTMLBaseFontElement.cpp
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
- * (C) 1999 Antti Koivisto (koivisto@kde.org)
- * Copyright (C) 2003, 2004, 2005, 2006, 2009, 2010 Apple Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#include "config.h"
-#include "core/html/HTMLBaseFontElement.h"
-
-#include "HTMLNames.h"
-
-namespace WebCore {
-
-using namespace HTMLNames;
-
-inline HTMLBaseFontElement::HTMLBaseFontElement(const QualifiedName& tagName, Document& document)
- : HTMLElement(tagName, document)
-{
- ASSERT(hasTagName(basefontTag));
- ScriptWrappable::init(this);
-}
-
-PassRefPtr<HTMLBaseFontElement> HTMLBaseFontElement::create(const QualifiedName& tagName, Document& document)
-{
- return adoptRef(new HTMLBaseFontElement(tagName, document));
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLBaseFontElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLBaseFontElement.h
deleted file mode 100644
index e66cc11f9ff..00000000000
--- a/chromium/third_party/WebKit/Source/core/html/HTMLBaseFontElement.h
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
- * (C) 1999 Antti Koivisto (koivisto@kde.org)
- * Copyright (C) 2003, 2004, 2005, 2006, 2009, 2010 Apple Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#ifndef HTMLBaseFontElement_h
-#define HTMLBaseFontElement_h
-
-#include "core/html/HTMLElement.h"
-
-namespace WebCore {
-
-class HTMLBaseFontElement FINAL : public HTMLElement {
-public:
- static PassRefPtr<HTMLBaseFontElement> create(const QualifiedName&, Document&);
-
-private:
- HTMLBaseFontElement(const QualifiedName&, Document&);
-};
-
-} // namespace
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLBaseFontElement.idl b/chromium/third_party/WebKit/Source/core/html/HTMLBaseFontElement.idl
deleted file mode 100644
index b885a0529ee..00000000000
--- a/chromium/third_party/WebKit/Source/core/html/HTMLBaseFontElement.idl
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (C) 2006, 2009, 2010 Apple Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-interface HTMLBaseFontElement : HTMLElement {
- [Reflect] attribute DOMString color;
- [Reflect] attribute DOMString face;
- [Reflect] attribute long size;
-};
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLBodyElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLBodyElement.cpp
index b373e9a3799..44a1572fec5 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLBodyElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLBodyElement.cpp
@@ -31,31 +31,25 @@
#include "core/css/CSSParser.h"
#include "core/css/StylePropertySet.h"
#include "core/dom/Attribute.h"
-#include "core/dom/EventNames.h"
+#include "core/events/ThreadLocalEventNames.h"
#include "core/html/HTMLFrameElementBase.h"
#include "core/html/parser/HTMLParserIdioms.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameView.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
namespace WebCore {
using namespace HTMLNames;
-HTMLBodyElement::HTMLBodyElement(const QualifiedName& tagName, Document& document)
- : HTMLElement(tagName, document)
+HTMLBodyElement::HTMLBodyElement(Document& document)
+ : HTMLElement(bodyTag, document)
{
- ASSERT(hasTagName(bodyTag));
ScriptWrappable::init(this);
}
PassRefPtr<HTMLBodyElement> HTMLBodyElement::create(Document& document)
{
- return adoptRef(new HTMLBodyElement(bodyTag, document));
-}
-
-PassRefPtr<HTMLBodyElement> HTMLBodyElement::create(const QualifiedName& tagName, Document& document)
-{
- return adoptRef(new HTMLBodyElement(tagName, document));
+ return adoptRef(new HTMLBodyElement(document));
}
HTMLBodyElement::~HTMLBodyElement()
@@ -119,39 +113,43 @@ void HTMLBodyElement::parseAttribute(const QualifiedName& name, const AtomicStri
setNeedsStyleRecalc();
} else if (name == onloadAttr)
- document().setWindowAttributeEventListener(eventNames().loadEvent, createAttributeEventListener(document().frame(), name, value));
+ document().setWindowAttributeEventListener(EventTypeNames::load, createAttributeEventListener(document().frame(), name, value));
else if (name == onbeforeunloadAttr)
- document().setWindowAttributeEventListener(eventNames().beforeunloadEvent, createAttributeEventListener(document().frame(), name, value));
+ document().setWindowAttributeEventListener(EventTypeNames::beforeunload, createAttributeEventListener(document().frame(), name, value));
else if (name == onunloadAttr)
- document().setWindowAttributeEventListener(eventNames().unloadEvent, createAttributeEventListener(document().frame(), name, value));
+ document().setWindowAttributeEventListener(EventTypeNames::unload, createAttributeEventListener(document().frame(), name, value));
else if (name == onpagehideAttr)
- document().setWindowAttributeEventListener(eventNames().pagehideEvent, createAttributeEventListener(document().frame(), name, value));
+ document().setWindowAttributeEventListener(EventTypeNames::pagehide, createAttributeEventListener(document().frame(), name, value));
else if (name == onpageshowAttr)
- document().setWindowAttributeEventListener(eventNames().pageshowEvent, createAttributeEventListener(document().frame(), name, value));
+ document().setWindowAttributeEventListener(EventTypeNames::pageshow, createAttributeEventListener(document().frame(), name, value));
else if (name == onpopstateAttr)
- document().setWindowAttributeEventListener(eventNames().popstateEvent, createAttributeEventListener(document().frame(), name, value));
+ document().setWindowAttributeEventListener(EventTypeNames::popstate, createAttributeEventListener(document().frame(), name, value));
else if (name == onblurAttr)
- document().setWindowAttributeEventListener(eventNames().blurEvent, createAttributeEventListener(document().frame(), name, value));
+ document().setWindowAttributeEventListener(EventTypeNames::blur, createAttributeEventListener(document().frame(), name, value));
+ else if (name == onerrorAttr)
+ document().setWindowAttributeEventListener(EventTypeNames::error, createAttributeEventListener(document().frame(), name, value));
else if (name == onfocusAttr)
- document().setWindowAttributeEventListener(eventNames().focusEvent, createAttributeEventListener(document().frame(), name, value));
+ document().setWindowAttributeEventListener(EventTypeNames::focus, createAttributeEventListener(document().frame(), name, value));
#if ENABLE(ORIENTATION_EVENTS)
else if (name == onorientationchangeAttr)
- document().setWindowAttributeEventListener(eventNames().orientationchangeEvent, createAttributeEventListener(document().frame(), name, value));
+ document().setWindowAttributeEventListener(EventTypeNames::orientationchange, createAttributeEventListener(document().frame(), name, value));
#endif
else if (name == onhashchangeAttr)
- document().setWindowAttributeEventListener(eventNames().hashchangeEvent, createAttributeEventListener(document().frame(), name, value));
+ document().setWindowAttributeEventListener(EventTypeNames::hashchange, createAttributeEventListener(document().frame(), name, value));
+ else if (name == onmessageAttr)
+ document().setWindowAttributeEventListener(EventTypeNames::message, createAttributeEventListener(document().frame(), name, value));
else if (name == onresizeAttr)
- document().setWindowAttributeEventListener(eventNames().resizeEvent, createAttributeEventListener(document().frame(), name, value));
+ document().setWindowAttributeEventListener(EventTypeNames::resize, createAttributeEventListener(document().frame(), name, value));
else if (name == onscrollAttr)
- document().setWindowAttributeEventListener(eventNames().scrollEvent, createAttributeEventListener(document().frame(), name, value));
+ document().setWindowAttributeEventListener(EventTypeNames::scroll, createAttributeEventListener(document().frame(), name, value));
else if (name == onselectionchangeAttr)
- document().setAttributeEventListener(eventNames().selectionchangeEvent, createAttributeEventListener(document().frame(), name, value));
+ document().setAttributeEventListener(EventTypeNames::selectionchange, createAttributeEventListener(document().frame(), name, value));
else if (name == onstorageAttr)
- document().setWindowAttributeEventListener(eventNames().storageEvent, createAttributeEventListener(document().frame(), name, value));
+ document().setWindowAttributeEventListener(EventTypeNames::storage, createAttributeEventListener(document().frame(), name, value));
else if (name == ononlineAttr)
- document().setWindowAttributeEventListener(eventNames().onlineEvent, createAttributeEventListener(document().frame(), name, value));
+ document().setWindowAttributeEventListener(EventTypeNames::online, createAttributeEventListener(document().frame(), name, value));
else if (name == onofflineAttr)
- document().setWindowAttributeEventListener(eventNames().offlineEvent, createAttributeEventListener(document().frame(), name, value));
+ document().setWindowAttributeEventListener(EventTypeNames::offline, createAttributeEventListener(document().frame(), name, value));
else
HTMLElement::parseAttribute(name, value);
}
@@ -168,10 +166,10 @@ Node::InsertionNotificationRequest HTMLBodyElement::insertedInto(ContainerNode*
HTMLFrameElementBase* ownerFrameElement = toHTMLFrameElementBase(ownerElement);
int marginWidth = ownerFrameElement->marginWidth();
if (marginWidth != -1)
- setAttribute(marginwidthAttr, String::number(marginWidth));
+ setIntegralAttribute(marginwidthAttr, marginWidth);
int marginHeight = ownerFrameElement->marginHeight();
if (marginHeight != -1)
- setAttribute(marginheightAttr, String::number(marginHeight));
+ setIntegralAttribute(marginheightAttr, marginHeight);
}
}
return InsertionDone;
@@ -189,56 +187,6 @@ bool HTMLBodyElement::supportsFocus() const
return rendererIsEditable() || HTMLElement::supportsFocus();
}
-String HTMLBodyElement::aLink() const
-{
- return getAttribute(alinkAttr);
-}
-
-void HTMLBodyElement::setALink(const String& value)
-{
- setAttribute(alinkAttr, value);
-}
-
-String HTMLBodyElement::bgColor() const
-{
- return getAttribute(bgcolorAttr);
-}
-
-void HTMLBodyElement::setBgColor(const String& value)
-{
- setAttribute(bgcolorAttr, value);
-}
-
-String HTMLBodyElement::link() const
-{
- return getAttribute(linkAttr);
-}
-
-void HTMLBodyElement::setLink(const String& value)
-{
- setAttribute(linkAttr, value);
-}
-
-String HTMLBodyElement::text() const
-{
- return getAttribute(textAttr);
-}
-
-void HTMLBodyElement::setText(const String& value)
-{
- setAttribute(textAttr, value);
-}
-
-String HTMLBodyElement::vLink() const
-{
- return getAttribute(vlinkAttr);
-}
-
-void HTMLBodyElement::setVLink(const String& value)
-{
- setAttribute(vlinkAttr, value);
-}
-
static int adjustForZoom(int value, Document* document)
{
Frame* frame = document->frame();
@@ -251,11 +199,21 @@ static int adjustForZoom(int value, Document* document)
return static_cast<int>(value / zoomFactor);
}
+// FIXME: There are cases where body.scrollLeft is allowed to return
+// non-zero values in both quirks and strict mode. It happens when
+// <body> has an overflow that is not the Frame overflow.
+// http://dev.w3.org/csswg/cssom-view/#dom-element-scrollleft
+// http://code.google.com/p/chromium/issues/detail?id=312435
int HTMLBodyElement::scrollLeft()
{
- // Update the document's layout.
Document& document = this->document();
document.updateLayoutIgnorePendingStylesheets();
+
+ if (RuntimeEnabledFeatures::scrollTopLeftInteropEnabled()) {
+ if (!document.inQuirksMode())
+ return 0;
+ }
+
FrameView* view = document.view();
return view ? adjustForZoom(view->scrollX(), &document) : 0;
}
@@ -264,6 +222,12 @@ void HTMLBodyElement::setScrollLeft(int scrollLeft)
{
Document& document = this->document();
document.updateLayoutIgnorePendingStylesheets();
+
+ if (RuntimeEnabledFeatures::scrollTopLeftInteropEnabled()) {
+ if (!document.inQuirksMode())
+ return;
+ }
+
Frame* frame = document.frame();
if (!frame)
return;
@@ -275,9 +239,14 @@ void HTMLBodyElement::setScrollLeft(int scrollLeft)
int HTMLBodyElement::scrollTop()
{
- // Update the document's layout.
Document& document = this->document();
document.updateLayoutIgnorePendingStylesheets();
+
+ if (RuntimeEnabledFeatures::scrollTopLeftInteropEnabled()) {
+ if (!document.inQuirksMode())
+ return 0;
+ }
+
FrameView* view = document.view();
return view ? adjustForZoom(view->scrollY(), &document) : 0;
}
@@ -286,6 +255,12 @@ void HTMLBodyElement::setScrollTop(int scrollTop)
{
Document& document = this->document();
document.updateLayoutIgnorePendingStylesheets();
+
+ if (RuntimeEnabledFeatures::scrollTopLeftInteropEnabled()) {
+ if (!document.inQuirksMode())
+ return;
+ }
+
Frame* frame = document.frame();
if (!frame)
return;
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLBodyElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLBodyElement.h
index fd1a960d37c..d7a5c45da0a 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLBodyElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLBodyElement.h
@@ -33,42 +33,20 @@ class Document;
class HTMLBodyElement FINAL : public HTMLElement {
public:
static PassRefPtr<HTMLBodyElement> create(Document&);
- static PassRefPtr<HTMLBodyElement> create(const QualifiedName&, Document&);
virtual ~HTMLBodyElement();
- String aLink() const;
- void setALink(const String&);
- String bgColor() const;
- void setBgColor(const String&);
- String link() const;
- void setLink(const String&);
- String text() const;
- void setText(const String&);
- String vLink() const;
- void setVLink(const String&);
-
- // Declared virtual in Element
DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(blur);
DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(error);
DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(focus);
DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(load);
-
- DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(beforeunload);
- DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(hashchange);
- DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(message);
- DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(offline);
- DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(online);
- DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(popstate);
- DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(resize);
- DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(storage);
- DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(unload);
+ DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(scroll);
#if ENABLE(ORIENTATION_EVENTS)
DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(orientationchange);
#endif
private:
- HTMLBodyElement(const QualifiedName&, Document&);
+ explicit HTMLBodyElement(Document&);
virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
@@ -92,11 +70,7 @@ private:
virtual void addSubresourceAttributeURLs(ListHashSet<KURL>&) const;
};
-inline HTMLBodyElement* toHTMLBodyElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::bodyTag));
- return static_cast<HTMLBodyElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(HTMLBodyElement, hasTagName(HTMLNames::bodyTag));
} //namespace
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLBodyElement.idl b/chromium/third_party/WebKit/Source/core/html/HTMLBodyElement.idl
index dfbd9071cd6..139b34a52a1 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLBodyElement.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLBodyElement.idl
@@ -19,36 +19,21 @@
*/
interface HTMLBodyElement : HTMLElement {
- [Reflect] attribute DOMString aLink;
+ [Reflect, TreatNullAs=NullString] attribute DOMString aLink;
[Reflect] attribute DOMString background;
- [Reflect] attribute DOMString bgColor;
- [Reflect] attribute DOMString link;
- [Reflect] attribute DOMString text;
- [Reflect] attribute DOMString vLink;
+ [Reflect, TreatNullAs=NullString] attribute DOMString bgColor;
+ [Reflect, TreatNullAs=NullString] attribute DOMString link;
+ [Reflect, TreatNullAs=NullString] attribute DOMString text;
+ [Reflect, TreatNullAs=NullString] attribute DOMString vLink;
- // Event handler attributes
- [NotEnumerable] attribute EventHandler onbeforeunload;
- [NotEnumerable] attribute EventHandler onhashchange;
- [NotEnumerable] attribute EventHandler onmessage;
- [NotEnumerable] attribute EventHandler onoffline;
- [NotEnumerable] attribute EventHandler ononline;
- [NotEnumerable] attribute EventHandler onpopstate;
- [NotEnumerable] attribute EventHandler onresize;
- [NotEnumerable] attribute EventHandler onstorage;
- [NotEnumerable] attribute EventHandler onunload;
+ [Conditional=ORIENTATION_EVENTS] attribute EventHandler onorientationchange;
- [Conditional=ORIENTATION_EVENTS, NotEnumerable] attribute EventHandler onorientationchange;
-
- // Overrides of Element attributes (with different implementation in bindings).
- [NotEnumerable] attribute EventHandler onblur;
- [NotEnumerable] attribute EventHandler onerror;
- [NotEnumerable] attribute EventHandler onfocus;
- [NotEnumerable] attribute EventHandler onload;
-
- // Not implemented yet.
- // attribute [NotEnumerable] EventHandler onafterprint;
- // attribute [NotEnumerable] EventHandler onbeforeprint;
- // attribute [NotEnumerable] EventHandler onredo;
- // attribute [NotEnumerable] EventHandler onundo;
+ // Overrides of GlobalEventHandler attributes
+ attribute EventHandler onblur;
+ attribute EventHandler onerror;
+ attribute EventHandler onfocus;
+ attribute EventHandler onload;
+ attribute EventHandler onscroll;
};
+HTMLBodyElement implements WindowEventHandlers;
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLButtonElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLButtonElement.cpp
index 712d7ec1dab..4b3c235fdab 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLButtonElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLButtonElement.cpp
@@ -28,8 +28,8 @@
#include "HTMLNames.h"
#include "core/dom/Attribute.h"
-#include "core/dom/EventNames.h"
-#include "core/dom/KeyboardEvent.h"
+#include "core/events/KeyboardEvent.h"
+#include "core/events/ThreadLocalEventNames.h"
#include "core/html/FormDataList.h"
#include "core/html/HTMLFormElement.h"
#include "core/rendering/RenderButton.h"
@@ -39,18 +39,17 @@ namespace WebCore {
using namespace HTMLNames;
-inline HTMLButtonElement::HTMLButtonElement(const QualifiedName& tagName, Document& document, HTMLFormElement* form)
- : HTMLFormControlElement(tagName, document, form)
+inline HTMLButtonElement::HTMLButtonElement(Document& document, HTMLFormElement* form)
+ : HTMLFormControlElement(buttonTag, document, form)
, m_type(SUBMIT)
, m_isActivatedSubmit(false)
{
- ASSERT(hasTagName(buttonTag));
ScriptWrappable::init(this);
}
-PassRefPtr<HTMLButtonElement> HTMLButtonElement::create(const QualifiedName& tagName, Document& document, HTMLFormElement* form)
+PassRefPtr<HTMLButtonElement> HTMLButtonElement::create(Document& document, HTMLFormElement* form)
{
- return adoptRef(new HTMLButtonElement(tagName, document, form));
+ return adoptRef(new HTMLButtonElement(document, form));
}
void HTMLButtonElement::setType(const AtomicString& type)
@@ -111,7 +110,7 @@ void HTMLButtonElement::parseAttribute(const QualifiedName& name, const AtomicSt
void HTMLButtonElement::defaultEventHandler(Event* event)
{
- if (event->type() == eventNames().DOMActivateEvent && !isDisabledFormControl()) {
+ if (event->type() == EventTypeNames::DOMActivate && !isDisabledFormControl()) {
if (form() && m_type == SUBMIT) {
m_isActivatedSubmit = true;
form()->prepareForSubmission(event);
@@ -125,12 +124,12 @@ void HTMLButtonElement::defaultEventHandler(Event* event)
}
if (event->isKeyboardEvent()) {
- if (event->type() == eventNames().keydownEvent && toKeyboardEvent(event)->keyIdentifier() == "U+0020") {
- setActive(true, true);
+ if (event->type() == EventTypeNames::keydown && toKeyboardEvent(event)->keyIdentifier() == "U+0020") {
+ setActive(true);
// No setDefaultHandled() - IE dispatches a keypress in this case.
return;
}
- if (event->type() == eventNames().keypressEvent) {
+ if (event->type() == EventTypeNames::keypress) {
switch (toKeyboardEvent(event)->charCode()) {
case '\r':
dispatchSimulatedClick(event);
@@ -142,7 +141,7 @@ void HTMLButtonElement::defaultEventHandler(Event* event)
return;
}
}
- if (event->type() == eventNames().keyupEvent && toKeyboardEvent(event)->keyIdentifier() == "U+0020") {
+ if (event->type() == EventTypeNames::keyup && toKeyboardEvent(event)->keyIdentifier() == "U+0020") {
if (active())
dispatchSimulatedClick(event);
event->setDefaultHandled();
@@ -160,11 +159,9 @@ bool HTMLButtonElement::willRespondToMouseClickEvents()
return HTMLFormControlElement::willRespondToMouseClickEvents();
}
-bool HTMLButtonElement::isSuccessfulSubmitButton() const
+bool HTMLButtonElement::canBeSuccessfulSubmitButton() const
{
- // HTML spec says that buttons must have names to be considered successful.
- // However, other browsers do not impose this constraint.
- return m_type == SUBMIT && !isDisabledFormControl();
+ return m_type == SUBMIT;
}
bool HTMLButtonElement::isActivatedSubmit() const
@@ -197,7 +194,7 @@ bool HTMLButtonElement::isURLAttribute(const Attribute& attribute) const
return attribute.name() == formactionAttr || HTMLFormControlElement::isURLAttribute(attribute);
}
-String HTMLButtonElement::value() const
+const AtomicString& HTMLButtonElement::value() const
{
return getAttribute(valueAttr);
}
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLButtonElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLButtonElement.h
index 8d3189304de..5032c386975 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLButtonElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLButtonElement.h
@@ -30,16 +30,16 @@ namespace WebCore {
class HTMLButtonElement FINAL : public HTMLFormControlElement {
public:
- static PassRefPtr<HTMLButtonElement> create(const QualifiedName&, Document&, HTMLFormElement*);
+ static PassRefPtr<HTMLButtonElement> create(Document&, HTMLFormElement*);
void setType(const AtomicString&);
- String value() const;
+ const AtomicString& value() const;
virtual bool willRespondToMouseClickEvents() OVERRIDE;
private:
- HTMLButtonElement(const QualifiedName& tagName, Document&, HTMLFormElement*);
+ HTMLButtonElement(Document&, HTMLFormElement*);
enum Type { SUBMIT, RESET, BUTTON };
@@ -60,7 +60,7 @@ private:
virtual bool supportLabels() const OVERRIDE { return true; }
virtual bool isInteractiveContent() const OVERRIDE;
- virtual bool isSuccessfulSubmitButton() const;
+ virtual bool canBeSuccessfulSubmitButton() const OVERRIDE;
virtual bool isActivatedSubmit() const;
virtual void setActivatedSubmit(bool flag);
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLButtonElement.idl b/chromium/third_party/WebKit/Source/core/html/HTMLButtonElement.idl
index eb3832fea2e..aa402325ce4 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLButtonElement.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLButtonElement.idl
@@ -21,14 +21,14 @@
interface HTMLButtonElement : HTMLElement {
[Reflect] attribute boolean autofocus;
[Reflect] attribute boolean disabled;
- readonly attribute HTMLFormElement form;
- [Reflect, URL] attribute DOMString formAction;
- [TreatNullAs=NullString] attribute DOMString formEnctype;
- [TreatNullAs=NullString] attribute DOMString formMethod;
+ [ImplementedAs=formOwner] readonly attribute HTMLFormElement form;
+ [Reflect, URL, PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute DOMString formAction;
+ attribute DOMString formEnctype;
+ attribute DOMString formMethod;
[Reflect] attribute boolean formNoValidate;
[Reflect] attribute DOMString formTarget;
[Reflect] attribute DOMString name;
- [TreatNullAs=NullString] attribute DOMString type;
+ attribute DOMString type;
[Reflect] attribute DOMString value;
readonly attribute boolean willValidate;
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLCanvasElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLCanvasElement.cpp
index 280951c60fb..ba778484dbc 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLCanvasElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLCanvasElement.cpp
@@ -41,13 +41,15 @@
#include "core/html/canvas/CanvasRenderingContext2D.h"
#include "core/html/canvas/WebGLContextAttributes.h"
#include "core/html/canvas/WebGLRenderingContext.h"
-#include "core/page/Frame.h"
-#include "core/page/Settings.h"
-#include "core/platform/HistogramSupport.h"
-#include "core/platform/MIMETypeRegistry.h"
-#include "core/platform/graphics/GraphicsContextStateSaver.h"
-#include "core/platform/graphics/ImageBuffer.h"
+#include "core/frame/Frame.h"
+#include "core/frame/Settings.h"
#include "core/rendering/RenderHTMLCanvas.h"
+#include "platform/MIMETypeRegistry.h"
+#include "platform/graphics/Canvas2DImageBufferSurface.h"
+#include "platform/graphics/GraphicsContextStateSaver.h"
+#include "platform/graphics/ImageBuffer.h"
+#include "platform/graphics/UnacceleratedImageBufferSurface.h"
+#include "platform/graphics/gpu/WebGLImageBufferSurface.h"
#include "public/platform/Platform.h"
namespace WebCore {
@@ -61,35 +63,28 @@ static const int DefaultHeight = 150;
// Firefox limits width/height to 32767 pixels, but slows down dramatically before it
// reaches that limit. We limit by area instead, giving us larger maximum dimensions,
// in exchange for a smaller maximum canvas size.
-static const float MaxCanvasArea = 32768 * 8192; // Maximum canvas area in CSS pixels
+static const int MaxCanvasArea = 32768 * 8192; // Maximum canvas area in CSS pixels
//In Skia, we will also limit width/height to 32767.
-static const float MaxSkiaDim = 32767.0F; // Maximum width/height in CSS pixels.
+static const int MaxSkiaDim = 32767; // Maximum width/height in CSS pixels.
-HTMLCanvasElement::HTMLCanvasElement(const QualifiedName& tagName, Document& document)
- : HTMLElement(tagName, document)
+HTMLCanvasElement::HTMLCanvasElement(Document& document)
+ : HTMLElement(canvasTag, document)
, m_size(DefaultWidth, DefaultHeight)
, m_rendererIsCanvas(false)
, m_ignoreReset(false)
- , m_deviceScaleFactor(1)
- , m_originClean(true)
- , m_hasCreatedImageBuffer(false)
- , m_didClearImageBuffer(false)
, m_accelerationDisabled(false)
, m_externallyAllocatedMemory(0)
+ , m_originClean(true)
+ , m_didFailToCreateImageBuffer(false)
+ , m_didClearImageBuffer(false)
{
- ASSERT(hasTagName(canvasTag));
ScriptWrappable::init(this);
}
PassRefPtr<HTMLCanvasElement> HTMLCanvasElement::create(Document& document)
{
- return adoptRef(new HTMLCanvasElement(canvasTag, document));
-}
-
-PassRefPtr<HTMLCanvasElement> HTMLCanvasElement::create(const QualifiedName& tagName, Document& document)
-{
- return adoptRef(new HTMLCanvasElement(tagName, document));
+ return adoptRef(new HTMLCanvasElement(document));
}
HTMLCanvasElement::~HTMLCanvasElement()
@@ -112,7 +107,7 @@ void HTMLCanvasElement::parseAttribute(const QualifiedName& name, const AtomicSt
RenderObject* HTMLCanvasElement::createRenderer(RenderStyle* style)
{
Frame* frame = document().frame();
- if (frame && frame->script()->canExecuteScripts(NotAboutToExecuteScript)) {
+ if (frame && frame->script().canExecuteScripts(NotAboutToExecuteScript)) {
m_rendererIsCanvas = true;
return new RenderHTMLCanvas(this);
}
@@ -139,12 +134,12 @@ void HTMLCanvasElement::removeObserver(CanvasObserver* observer)
void HTMLCanvasElement::setHeight(int value)
{
- setAttribute(heightAttr, String::number(value));
+ setIntegralAttribute(heightAttr, value);
}
void HTMLCanvasElement::setWidth(int value)
{
- setAttribute(widthAttr, String::number(value));
+ setIntegralAttribute(widthAttr, value);
}
CanvasRenderingContext* HTMLCanvasElement::getContext(const String& type, CanvasContextAttributes* attrs)
@@ -169,8 +164,8 @@ CanvasRenderingContext* HTMLCanvasElement::getContext(const String& type, Canvas
if (m_context && !m_context->is2d())
return 0;
if (!m_context) {
- HistogramSupport::histogramEnumeration("Canvas.ContextType", Context2d, ContextTypeCount);
- m_context = CanvasRenderingContext2D::create(this, RuntimeEnabledFeatures::experimentalCanvasFeaturesEnabled() ? static_cast<Canvas2DContextAttributes*>(attrs) : 0, document().inQuirksMode());
+ blink::Platform::current()->histogramEnumeration("Canvas.ContextType", Context2d, ContextTypeCount);
+ m_context = CanvasRenderingContext2D::create(this, static_cast<Canvas2DContextAttributes*>(attrs), document().inQuirksMode());
if (m_context)
scheduleLayerUpdate();
}
@@ -196,7 +191,7 @@ CanvasRenderingContext* HTMLCanvasElement::getContext(const String& type, Canvas
if (m_context && !m_context->is3d())
return 0;
if (!m_context) {
- HistogramSupport::histogramEnumeration("Canvas.ContextType", contextType, ContextTypeCount);
+ blink::Platform::current()->histogramEnumeration("Canvas.ContextType", contextType, ContextTypeCount);
m_context = WebGLRenderingContext::create(this, static_cast<WebGLContextAttributes*>(attrs));
if (m_context)
scheduleLayerUpdate();
@@ -238,7 +233,7 @@ void HTMLCanvasElement::reset()
return;
bool ok;
- bool hadImageBuffer = hasCreatedImageBuffer();
+ bool hadImageBuffer = hasImageBuffer();
int w = getAttribute(widthAttr).toInt(&ok);
if (!ok || w < 0)
@@ -254,29 +249,24 @@ void HTMLCanvasElement::reset()
m_contextStateSaver->save();
}
- if (m_context && m_context->is2d()) {
- CanvasRenderingContext2D* context2D = static_cast<CanvasRenderingContext2D*>(m_context.get());
- context2D->reset();
- }
+ if (m_context && m_context->is2d())
+ toCanvasRenderingContext2D(m_context.get())->reset();
IntSize oldSize = size();
IntSize newSize(w, h);
- float newDeviceScaleFactor = 1;
// If the size of an existing buffer matches, we can just clear it instead of reallocating.
// This optimization is only done for 2D canvases for now.
- if (m_hasCreatedImageBuffer && oldSize == newSize && m_deviceScaleFactor == newDeviceScaleFactor && m_context && m_context->is2d()) {
+ if (hadImageBuffer && oldSize == newSize && m_context && m_context->is2d()) {
if (!m_didClearImageBuffer)
clearImageBuffer();
return;
}
- m_deviceScaleFactor = newDeviceScaleFactor;
-
setSurfaceSize(newSize);
if (m_context && m_context->is3d() && oldSize != size())
- static_cast<WebGLRenderingContext*>(m_context.get())->reshape(width(), height());
+ toWebGLRenderingContext(m_context.get())->reshape(width(), height());
if (RenderObject* renderer = this->renderer()) {
if (m_rendererIsCanvas) {
@@ -323,19 +313,19 @@ void HTMLCanvasElement::paint(GraphicsContext* context, const LayoutRect& r, boo
m_context->paintRenderingResultsToCanvas();
}
- if (hasCreatedImageBuffer()) {
+ if (hasImageBuffer()) {
ImageBuffer* imageBuffer = buffer();
if (imageBuffer) {
CompositeOperator compositeOperator = !m_context || m_context->hasAlpha() ? CompositeSourceOver : CompositeCopy;
if (m_presentedImage)
context->drawImage(m_presentedImage.get(), pixelSnappedIntRect(r), compositeOperator, DoNotRespectImageOrientation, useLowQualityScale);
else
- context->drawImageBuffer(imageBuffer, pixelSnappedIntRect(r), compositeOperator, BlendModeNormal, useLowQualityScale);
+ context->drawImageBuffer(imageBuffer, pixelSnappedIntRect(r), compositeOperator, blink::WebBlendModeNormal, useLowQualityScale);
}
}
if (is3D())
- static_cast<WebGLRenderingContext*>(m_context.get())->markLayerComposited();
+ toWebGLRenderingContext(m_context.get())->markLayerComposited();
}
bool HTMLCanvasElement::is3D() const
@@ -359,7 +349,7 @@ void HTMLCanvasElement::clearPresentationCopy()
void HTMLCanvasElement::setSurfaceSize(const IntSize& size)
{
m_size = size;
- m_hasCreatedImageBuffer = false;
+ m_didFailToCreateImageBuffer = false;
m_contextStateSaver.clear();
m_imageBuffer.clear();
setExternallyAllocatedMemory(0);
@@ -377,10 +367,10 @@ String HTMLCanvasElement::toEncodingMimeType(const String& mimeType)
return lowercaseMimeType;
}
-String HTMLCanvasElement::toDataURL(const String& mimeType, const double* quality, ExceptionState& es)
+String HTMLCanvasElement::toDataURL(const String& mimeType, const double* quality, ExceptionState& exceptionState)
{
if (!m_originClean) {
- es.throwSecurityError(ExceptionMessages::failedToExecute("toDataURL", "HTMLCanvasElement", "tainted canvases may not be exported."));
+ exceptionState.throwSecurityError("Tainted canvases may not be exported.");
return String();
}
@@ -393,7 +383,7 @@ String HTMLCanvasElement::toDataURL(const String& mimeType, const double* qualit
RefPtr<ImageData> imageData = getImageData();
if (imageData)
- return ImageDataToDataURL(*imageData, encodingMimeType, quality);
+ return ImageDataToDataURL(ImageDataBuffer(imageData->size(), imageData->data()), encodingMimeType, quality);
if (m_context)
m_context->paintRenderingResultsToCanvas();
@@ -405,41 +395,7 @@ PassRefPtr<ImageData> HTMLCanvasElement::getImageData()
{
if (!m_context || !m_context->is3d())
return 0;
-
- WebGLRenderingContext* ctx = static_cast<WebGLRenderingContext*>(m_context.get());
-
- return ctx->paintRenderingResultsToImageData();
-}
-
-FloatRect HTMLCanvasElement::convertLogicalToDevice(const FloatRect& logicalRect) const
-{
- FloatRect deviceRect(logicalRect);
- deviceRect.scale(m_deviceScaleFactor);
-
- float x = floorf(deviceRect.x());
- float y = floorf(deviceRect.y());
- float w = ceilf(deviceRect.maxX() - x);
- float h = ceilf(deviceRect.maxY() - y);
- deviceRect.setX(x);
- deviceRect.setY(y);
- deviceRect.setWidth(w);
- deviceRect.setHeight(h);
-
- return deviceRect;
-}
-
-FloatSize HTMLCanvasElement::convertLogicalToDevice(const FloatSize& logicalSize) const
-{
- float width = ceilf(logicalSize.width() * m_deviceScaleFactor);
- float height = ceilf(logicalSize.height() * m_deviceScaleFactor);
- return FloatSize(width, height);
-}
-
-FloatSize HTMLCanvasElement::convertDeviceToLogical(const FloatSize& deviceSize) const
-{
- float width = ceilf(deviceSize.width() / m_deviceScaleFactor);
- float height = ceilf(deviceSize.height() / m_deviceScaleFactor);
- return FloatSize(width, height);
+ return toWebGLRenderingContext(m_context.get())->paintRenderingResultsToImageData();
}
SecurityOrigin* HTMLCanvasElement::securityOrigin() const
@@ -447,11 +403,6 @@ SecurityOrigin* HTMLCanvasElement::securityOrigin() const
return document().securityOrigin();
}
-StyleResolver* HTMLCanvasElement::styleResolver()
-{
- return document().styleResolver();
-}
-
bool HTMLCanvasElement::shouldAccelerate(const IntSize& size) const
{
if (m_context && !m_context->is2d())
@@ -468,43 +419,70 @@ bool HTMLCanvasElement::shouldAccelerate(const IntSize& size) const
if (size.width() * size.height() < settings->minimumAccelerated2dCanvasSize())
return false;
- if (!WebKit::Platform::current()->canAccelerate2dCanvas())
+ if (!blink::Platform::current()->canAccelerate2dCanvas())
return false;
return true;
}
+PassOwnPtr<ImageBufferSurface> HTMLCanvasElement::createImageBufferSurface(const IntSize& deviceSize, int* msaaSampleCount)
+{
+ OpacityMode opacityMode = !m_context || m_context->hasAlpha() ? NonOpaque : Opaque;
+
+ *msaaSampleCount = 0;
+ if (is3D())
+ return adoptPtr(new WebGLImageBufferSurface(size(), opacityMode));
+
+ if (shouldAccelerate(deviceSize)) {
+ if (document().settings())
+ *msaaSampleCount = document().settings()->accelerated2dCanvasMSAASampleCount();
+ OwnPtr<ImageBufferSurface> surface = adoptPtr(new Canvas2DImageBufferSurface(size(), opacityMode, *msaaSampleCount));
+ if (surface->isValid())
+ return surface.release();
+ }
+
+ return adoptPtr(new UnacceleratedImageBufferSurface(size(), opacityMode));
+}
+
void HTMLCanvasElement::createImageBuffer()
{
ASSERT(!m_imageBuffer);
- m_hasCreatedImageBuffer = true;
+ m_didFailToCreateImageBuffer = true;
m_didClearImageBuffer = true;
- FloatSize logicalSize = size();
- FloatSize deviceSize = convertLogicalToDevice(logicalSize);
- if (!deviceSize.isExpressibleAsIntSize())
- return;
-
+ IntSize deviceSize = size();
if (deviceSize.width() * deviceSize.height() > MaxCanvasArea)
return;
if (deviceSize.width() > MaxSkiaDim || deviceSize.height() > MaxSkiaDim)
return;
- IntSize bufferSize(deviceSize.width(), deviceSize.height());
- if (!bufferSize.width() || !bufferSize.height())
+ if (!deviceSize.width() || !deviceSize.height())
return;
- RenderingMode renderingMode = shouldAccelerate(bufferSize) ? Accelerated : UnacceleratedNonPlatformBuffer;
- OpacityMode opacityMode = !m_context || m_context->hasAlpha() ? NonOpaque : Opaque;
- m_imageBuffer = ImageBuffer::create(size(), m_deviceScaleFactor, renderingMode, opacityMode);
- if (!m_imageBuffer)
+ int msaaSampleCount;
+ OwnPtr<ImageBufferSurface> surface = createImageBufferSurface(deviceSize, &msaaSampleCount);
+ if (!surface->isValid())
return;
+ m_imageBuffer = ImageBuffer::create(surface.release());
+
+ m_didFailToCreateImageBuffer = false;
+
setExternallyAllocatedMemory(4 * width() * height());
+
+ if (is3D()) {
+ // Early out for WebGL canvases
+ m_contextStateSaver.clear();
+ return;
+ }
+
m_imageBuffer->context()->setShouldClampToSourceRect(false);
m_imageBuffer->context()->setImageInterpolationQuality(DefaultInterpolationQuality);
- if (document().settings() && !document().settings()->antialiased2dCanvasEnabled())
+ // Enabling MSAA overrides a request to disable antialiasing. This is true regardless of whether the
+ // rendering mode is accelerated or not. For consistency, we don't want to apply AA in accelerated
+ // canvases but not in unaccelerated canvases.
+ if (!msaaSampleCount && document().settings() && !document().settings()->antialiased2dCanvasEnabled())
m_imageBuffer->context()->setShouldAntialias(false);
// GraphicsContext's defaults don't always agree with the 2d canvas spec.
// See CanvasRenderingContext2D::State::State() for more information.
@@ -513,13 +491,13 @@ void HTMLCanvasElement::createImageBuffer()
m_contextStateSaver = adoptPtr(new GraphicsContextStateSaver(*m_imageBuffer->context()));
// Recalculate compositing requirements if acceleration state changed.
- if (m_context && m_context->is2d())
+ if (m_context)
scheduleLayerUpdate();
}
void HTMLCanvasElement::setExternallyAllocatedMemory(intptr_t externallyAllocatedMemory)
{
- v8::V8::AdjustAmountOfExternalAllocatedMemory(externallyAllocatedMemory - m_externallyAllocatedMemory);
+ v8::Isolate::GetCurrent()->AdjustAmountOfExternalAllocatedMemory(externallyAllocatedMemory - m_externallyAllocatedMemory);
m_externallyAllocatedMemory = externallyAllocatedMemory;
}
@@ -530,19 +508,31 @@ GraphicsContext* HTMLCanvasElement::drawingContext() const
GraphicsContext* HTMLCanvasElement::existingDrawingContext() const
{
- if (!m_hasCreatedImageBuffer)
+ if (m_didFailToCreateImageBuffer) {
+ ASSERT(!hasImageBuffer());
return 0;
+ }
return drawingContext();
}
ImageBuffer* HTMLCanvasElement::buffer() const
{
- if (!m_hasCreatedImageBuffer)
+ if (!hasImageBuffer() && !m_didFailToCreateImageBuffer)
const_cast<HTMLCanvasElement*>(this)->createImageBuffer();
return m_imageBuffer.get();
}
+void HTMLCanvasElement::ensureUnacceleratedImageBuffer()
+{
+ if ((hasImageBuffer() && !m_imageBuffer->isAccelerated()) || m_didFailToCreateImageBuffer)
+ return;
+ m_imageBuffer.clear();
+ OpacityMode opacityMode = !m_context || m_context->hasAlpha() ? NonOpaque : Opaque;
+ m_imageBuffer = ImageBuffer::create(size(), opacityMode);
+ m_didFailToCreateImageBuffer = !m_imageBuffer;
+}
+
Image* HTMLCanvasElement::copiedImage() const
{
if (!m_copiedImage && buffer()) {
@@ -555,16 +545,16 @@ Image* HTMLCanvasElement::copiedImage() const
void HTMLCanvasElement::clearImageBuffer()
{
- ASSERT(m_hasCreatedImageBuffer);
+ ASSERT(hasImageBuffer() && !m_didFailToCreateImageBuffer);
ASSERT(!m_didClearImageBuffer);
ASSERT(m_context);
m_didClearImageBuffer = true;
if (m_context->is2d()) {
- CanvasRenderingContext2D* context2D = static_cast<CanvasRenderingContext2D*>(m_context.get());
- // No need to undo transforms/clip/etc. because we are called right after the context is reset.
- context2D->clearRect(0, 0, width(), height());
+ // No need to undo transforms/clip/etc. because we are called right
+ // after the context is reset.
+ toCanvasRenderingContext2D(m_context.get())->clearRect(0, 0, width(), height());
}
}
@@ -576,14 +566,8 @@ void HTMLCanvasElement::clearCopiedImage()
AffineTransform HTMLCanvasElement::baseTransform() const
{
- ASSERT(m_hasCreatedImageBuffer);
- FloatSize unscaledSize = size();
- FloatSize deviceSize = convertLogicalToDevice(unscaledSize);
- IntSize size(deviceSize.width(), deviceSize.height());
- AffineTransform transform;
- if (size.width() && size.height())
- transform.scaleNonUniform(size.width() / unscaledSize.width(), size.height() / unscaledSize.height());
- return m_imageBuffer->baseTransform() * transform;
+ ASSERT(hasImageBuffer() && !m_didFailToCreateImageBuffer);
+ return m_imageBuffer->baseTransform();
}
}
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLCanvasElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLCanvasElement.h
index a9daa99a7e7..8db8a6d70a0 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLCanvasElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLCanvasElement.h
@@ -29,8 +29,8 @@
#define HTMLCanvasElement_h
#include "core/html/HTMLElement.h"
-#include "core/platform/graphics/FloatRect.h"
-#include "core/platform/graphics/IntSize.h"
+#include "platform/geometry/FloatRect.h"
+#include "platform/geometry/IntSize.h"
#include "wtf/Forward.h"
#define DefaultInterpolationQuality InterpolationMedium
@@ -45,6 +45,7 @@ class HTMLCanvasElement;
class Image;
class ImageData;
class ImageBuffer;
+class ImageBufferSurface;
class IntSize;
class CanvasObserver {
@@ -59,7 +60,6 @@ public:
class HTMLCanvasElement FINAL : public HTMLElement {
public:
static PassRefPtr<HTMLCanvasElement> create(Document&);
- static PassRefPtr<HTMLCanvasElement> create(const QualifiedName&, Document&);
virtual ~HTMLCanvasElement();
void addObserver(CanvasObserver*);
@@ -78,7 +78,7 @@ public:
void setSize(const IntSize& newSize)
{
- if (newSize == size() && m_deviceScaleFactor == 1)
+ if (newSize == size())
return;
m_ignoreReset = true;
setWidth(newSize.width());
@@ -91,7 +91,7 @@ public:
static String toEncodingMimeType(const String& mimeType);
String toDataURL(const String& mimeType, const double* quality, ExceptionState&);
- String toDataURL(const String& mimeType, ExceptionState& es) { return toDataURL(mimeType, 0, es); }
+ String toDataURL(const String& mimeType, ExceptionState& exceptionState) { return toDataURL(mimeType, 0, exceptionState); }
// Used for rendering
void didDraw(const FloatRect&);
@@ -104,6 +104,7 @@ public:
CanvasRenderingContext* renderingContext() const { return m_context.get(); }
+ void ensureUnacceleratedImageBuffer();
ImageBuffer* buffer() const;
Image* copiedImage() const;
void clearCopiedImage();
@@ -111,31 +112,22 @@ public:
void makePresentationCopy();
void clearPresentationCopy();
- FloatRect convertLogicalToDevice(const FloatRect&) const;
- FloatSize convertLogicalToDevice(const FloatSize&) const;
-
- FloatSize convertDeviceToLogical(const FloatSize&) const;
-
SecurityOrigin* securityOrigin() const;
void setOriginTainted() { m_originClean = false; }
bool originClean() const { return m_originClean; }
- StyleResolver* styleResolver();
-
AffineTransform baseTransform() const;
bool is3D() const;
- bool hasCreatedImageBuffer() const { return m_hasCreatedImageBuffer; }
+ bool hasImageBuffer() const { return m_imageBuffer.get(); }
bool shouldAccelerate(const IntSize&) const;
- float deviceScaleFactor() const { return m_deviceScaleFactor; }
-
InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
private:
- HTMLCanvasElement(const QualifiedName&, Document&);
+ explicit HTMLCanvasElement(Document&);
virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
virtual RenderObject* createRenderer(RenderStyle*);
@@ -143,6 +135,7 @@ private:
void reset();
+ PassOwnPtr<ImageBufferSurface> createImageBufferSurface(const IntSize& deviceSize, int* msaaSampleCount);
void createImageBuffer();
void clearImageBuffer();
@@ -166,11 +159,11 @@ private:
intptr_t m_externallyAllocatedMemory;
- float m_deviceScaleFactor; // FIXME: This is always 1 and should probable be deleted
bool m_originClean;
- // m_createdImageBuffer means we tried to malloc the buffer. We didn't necessarily get it.
- mutable bool m_hasCreatedImageBuffer;
+ // It prevents HTMLCanvasElement::buffer() from continuously re-attempting to allocate an imageBuffer
+ // after the first attempt failed.
+ mutable bool m_didFailToCreateImageBuffer;
mutable bool m_didClearImageBuffer;
OwnPtr<ImageBuffer> m_imageBuffer;
mutable OwnPtr<GraphicsContextStateSaver> m_contextStateSaver;
@@ -179,11 +172,7 @@ private:
mutable RefPtr<Image> m_copiedImage; // FIXME: This is temporary for platforms that have to copy the image buffer to render (and for CSSCanvasValue).
};
-inline HTMLCanvasElement* toHTMLCanvasElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::canvasTag));
- return static_cast<HTMLCanvasElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(HTMLCanvasElement, hasTagName(HTMLNames::canvasTag));
} //namespace
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLCanvasElement.idl b/chromium/third_party/WebKit/Source/core/html/HTMLCanvasElement.idl
index c0957962ab0..0bee59fe085 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLCanvasElement.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLCanvasElement.idl
@@ -32,6 +32,6 @@ interface HTMLCanvasElement : HTMLElement {
[Custom, RaisesException] DOMString toDataURL([TreatNullAs=NullString, TreatUndefinedAs=NullString,Default=Undefined] optional DOMString type);
// The custom binding is needed to handle context creation attributes.
- [Custom, PerWorldBindings, ActivityLog=AccessForIsolatedWorlds] any getContext([Default=Undefined] optional DOMString contextId);
+ [Custom, PerWorldBindings, ActivityLogging=ForIsolatedWorlds] any getContext([Default=Undefined] optional DOMString contextId);
};
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLCollection.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLCollection.cpp
index f891743f786..a0edbbc2f20 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLCollection.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLCollection.cpp
@@ -253,30 +253,30 @@ template <> inline bool isMatchingElement(const ClassNodeList* nodeList, Element
return nodeList->nodeMatchesInlined(element);
}
-static Node* previousNode(Node* base, Node* previous, bool onlyIncludeDirectChildren)
+static Node* previousNode(Node& base, Node& previous, bool onlyIncludeDirectChildren)
{
- return onlyIncludeDirectChildren ? previous->previousSibling() : NodeTraversal::previous(previous, base);
+ return onlyIncludeDirectChildren ? previous.previousSibling() : NodeTraversal::previous(previous, &base);
}
-static inline Node* lastDescendent(Node* node)
+static inline Node* lastDescendent(Node& node)
{
- node = node->lastChild();
- for (Node* current = node; current; current = current->lastChild())
- node = current;
- return node;
+ Node* descendent = node.lastChild();
+ for (Node* current = descendent; current; current = current->lastChild())
+ descendent = current;
+ return descendent;
}
-static Node* lastNode(Node* rootNode, bool onlyIncludeDirectChildren)
+static Node* lastNode(Node& rootNode, bool onlyIncludeDirectChildren)
{
- return onlyIncludeDirectChildren ? rootNode->lastChild() : lastDescendent(rootNode);
+ return onlyIncludeDirectChildren ? rootNode.lastChild() : lastDescendent(rootNode);
}
ALWAYS_INLINE Node* LiveNodeListBase::iterateForPreviousNode(Node* current) const
{
bool onlyIncludeDirectChildren = shouldOnlyIncludeDirectChildren();
CollectionType collectionType = type();
- Node* rootNode = this->rootNode();
- for (; current; current = previousNode(rootNode, current, onlyIncludeDirectChildren)) {
+ Node& rootNode = this->rootNode();
+ for (; current; current = previousNode(rootNode, *current, onlyIncludeDirectChildren)) {
if (isNodeList(collectionType)) {
if (current->isElementNode() && isMatchingElement(static_cast<const LiveNodeList*>(this), toElement(current)))
return toElement(current);
@@ -292,7 +292,7 @@ ALWAYS_INLINE Node* LiveNodeListBase::itemBefore(Node* previous) const
{
Node* current;
if (LIKELY(!!previous)) // Without this LIKELY, length() and item() can be 10% slower.
- current = previousNode(rootNode(), previous, shouldOnlyIncludeDirectChildren());
+ current = previousNode(rootNode(), *previous, shouldOnlyIncludeDirectChildren());
else
current = lastNode(rootNode(), shouldOnlyIncludeDirectChildren());
@@ -302,30 +302,32 @@ ALWAYS_INLINE Node* LiveNodeListBase::itemBefore(Node* previous) const
}
template <class NodeListType>
-inline Element* firstMatchingElement(const NodeListType* nodeList, ContainerNode* root)
+inline Element* firstMatchingElement(const NodeListType* nodeList, ContainerNode& root)
{
Element* element = ElementTraversal::firstWithin(root);
while (element && !isMatchingElement(nodeList, element))
- element = ElementTraversal::next(element, root);
+ element = ElementTraversal::next(*element, &root);
return element;
}
template <class NodeListType>
-inline Element* nextMatchingElement(const NodeListType* nodeList, Element* current, ContainerNode* root)
+inline Element* nextMatchingElement(const NodeListType* nodeList, Element& current, ContainerNode* root)
{
+ Element* next = &current;
do {
- current = ElementTraversal::next(current, root);
- } while (current && !isMatchingElement(nodeList, current));
- return current;
+ next = ElementTraversal::next(*next, root);
+ } while (next && !isMatchingElement(nodeList, next));
+ return next;
}
template <class NodeListType>
-inline Element* traverseMatchingElementsForwardToOffset(const NodeListType* nodeList, unsigned offset, Element* currentElement, unsigned& currentOffset, ContainerNode* root)
+inline Element* traverseMatchingElementsForwardToOffset(const NodeListType* nodeList, unsigned offset, Element& currentElement, unsigned& currentOffset, ContainerNode* root)
{
ASSERT(currentOffset < offset);
- while ((currentElement = nextMatchingElement(nodeList, currentElement, root))) {
+ Element* next = &currentElement;
+ while ((next = nextMatchingElement(nodeList, *next, root))) {
if (++currentOffset == offset)
- return currentElement;
+ return next;
}
return 0;
}
@@ -343,7 +345,7 @@ inline Node* LiveNodeListBase::traverseChildNodeListForwardToOffset(unsigned off
}
// FIXME: This should be in LiveNodeList
-inline Element* LiveNodeListBase::traverseLiveNodeListFirstElement(ContainerNode* root) const
+inline Element* LiveNodeListBase::traverseLiveNodeListFirstElement(ContainerNode& root) const
{
ASSERT(isNodeList(type()));
ASSERT(type() != ChildNodeListType);
@@ -355,7 +357,7 @@ inline Element* LiveNodeListBase::traverseLiveNodeListFirstElement(ContainerNode
}
// FIXME: This should be in LiveNodeList
-inline Element* LiveNodeListBase::traverseLiveNodeListForwardToOffset(unsigned offset, Element* currentElement, unsigned& currentOffset, ContainerNode* root) const
+inline Element* LiveNodeListBase::traverseLiveNodeListForwardToOffset(unsigned offset, Element& currentElement, unsigned& currentOffset, ContainerNode* root) const
{
ASSERT(isNodeList(type()));
ASSERT(type() != ChildNodeListType);
@@ -433,9 +435,9 @@ Node* LiveNodeListBase::item(unsigned offset) const
if (type() == ChildNodeListType)
firstItem = root->firstChild();
else if (isNodeList(type()))
- firstItem = traverseLiveNodeListFirstElement(root);
+ firstItem = traverseLiveNodeListFirstElement(*root);
else
- firstItem = static_cast<const HTMLCollection*>(this)->traverseFirstElement(offsetInArray, root);
+ firstItem = static_cast<const HTMLCollection*>(this)->traverseFirstElement(offsetInArray, *root);
if (!firstItem) {
setLengthCache(0);
@@ -476,9 +478,9 @@ inline Node* LiveNodeListBase::itemBeforeOrAfterCachedItem(unsigned offset, Cont
if (type() == ChildNodeListType)
currentItem = traverseChildNodeListForwardToOffset(offset, currentItem, currentOffset);
else if (isNodeList(type()))
- currentItem = traverseLiveNodeListForwardToOffset(offset, toElement(currentItem), currentOffset, root);
+ currentItem = traverseLiveNodeListForwardToOffset(offset, toElement(*currentItem), currentOffset, root);
else
- currentItem = static_cast<const HTMLCollection*>(this)->traverseForwardToOffset(offset, toElement(currentItem), currentOffset, offsetInArray, root);
+ currentItem = static_cast<const HTMLCollection*>(this)->traverseForwardToOffset(offset, toElement(*currentItem), currentOffset, offsetInArray, root);
if (!currentItem) {
// Did not find the item. On plus side, we now know the length.
@@ -523,23 +525,24 @@ bool HTMLCollection::checkForNameMatch(Element* element, bool checkName, const A
return e->getNameAttribute() == name && e->getIdAttribute() != name;
}
-inline Element* firstMatchingChildElement(const HTMLCollection* nodeList, ContainerNode* root)
+inline Element* firstMatchingChildElement(const HTMLCollection* nodeList, ContainerNode& root)
{
Element* element = ElementTraversal::firstWithin(root);
while (element && !isMatchingElement(nodeList, element))
- element = ElementTraversal::nextSkippingChildren(element, root);
+ element = ElementTraversal::nextSkippingChildren(*element, &root);
return element;
}
-inline Element* nextMatchingChildElement(const HTMLCollection* nodeList, Element* current, ContainerNode* root)
+inline Element* nextMatchingChildElement(const HTMLCollection* nodeList, Element& current, ContainerNode* root)
{
+ Element* next = &current;
do {
- current = ElementTraversal::nextSkippingChildren(current, root);
- } while (current && !isMatchingElement(nodeList, current));
- return current;
+ next = ElementTraversal::nextSkippingChildren(*next, root);
+ } while (next && !isMatchingElement(nodeList, next));
+ return next;
}
-inline Element* HTMLCollection::traverseFirstElement(unsigned& offsetInArray, ContainerNode* root) const
+inline Element* HTMLCollection::traverseFirstElement(unsigned& offsetInArray, ContainerNode& root) const
{
if (overridesItemAfter())
return virtualItemAfter(offsetInArray, 0);
@@ -549,31 +552,33 @@ inline Element* HTMLCollection::traverseFirstElement(unsigned& offsetInArray, Co
return firstMatchingElement(static_cast<const HTMLCollection*>(this), root);
}
-inline Element* HTMLCollection::traverseNextElement(unsigned& offsetInArray, Element* previous, ContainerNode* root) const
+inline Element* HTMLCollection::traverseNextElement(unsigned& offsetInArray, Element& previous, ContainerNode* root) const
{
if (overridesItemAfter())
- return virtualItemAfter(offsetInArray, previous);
+ return virtualItemAfter(offsetInArray, &previous);
ASSERT(!offsetInArray);
if (shouldOnlyIncludeDirectChildren())
return nextMatchingChildElement(this, previous, root);
return nextMatchingElement(this, previous, root);
}
-inline Element* HTMLCollection::traverseForwardToOffset(unsigned offset, Element* currentElement, unsigned& currentOffset, unsigned& offsetInArray, ContainerNode* root) const
+inline Element* HTMLCollection::traverseForwardToOffset(unsigned offset, Element& currentElement, unsigned& currentOffset, unsigned& offsetInArray, ContainerNode* root) const
{
ASSERT(currentOffset < offset);
if (overridesItemAfter()) {
offsetInArray = m_cachedElementsArrayOffset;
- while ((currentElement = virtualItemAfter(offsetInArray, currentElement))) {
+ Element* next = &currentElement;
+ while ((next = virtualItemAfter(offsetInArray, next))) {
if (++currentOffset == offset)
- return currentElement;
+ return next;
}
return 0;
}
if (shouldOnlyIncludeDirectChildren()) {
- while ((currentElement = nextMatchingChildElement(this, currentElement, root))) {
+ Element* next = &currentElement;
+ while ((next = nextMatchingChildElement(this, *next, root))) {
if (++currentOffset == offset)
- return currentElement;
+ return next;
}
return 0;
}
@@ -594,7 +599,7 @@ Node* HTMLCollection::namedItem(const AtomicString& name) const
unsigned arrayOffset = 0;
unsigned i = 0;
- for (Element* element = traverseFirstElement(arrayOffset, root); element; element = traverseNextElement(arrayOffset, element, root)) {
+ for (Element* element = traverseFirstElement(arrayOffset, *root); element; element = traverseNextElement(arrayOffset, *element, root)) {
if (checkForNameMatch(element, /* checkName */ false, name)) {
setItemCache(element, i, arrayOffset);
return element;
@@ -603,7 +608,7 @@ Node* HTMLCollection::namedItem(const AtomicString& name) const
}
i = 0;
- for (Element* element = traverseFirstElement(arrayOffset, root); element; element = traverseNextElement(arrayOffset, element, root)) {
+ for (Element* element = traverseFirstElement(arrayOffset, *root); element; element = traverseNextElement(arrayOffset, *element, root)) {
if (checkForNameMatch(element, /* checkName */ true, name)) {
setItemCache(element, i, arrayOffset);
return element;
@@ -624,7 +629,7 @@ void HTMLCollection::updateNameCache() const
return;
unsigned arrayOffset = 0;
- for (Element* element = traverseFirstElement(arrayOffset, root); element; element = traverseNextElement(arrayOffset, element, root)) {
+ for (Element* element = traverseFirstElement(arrayOffset, *root); element; element = traverseNextElement(arrayOffset, *element, root)) {
const AtomicString& idAttrVal = element->getIdAttribute();
if (!idAttrVal.isEmpty())
appendIdCache(idAttrVal, element);
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLCollection.h b/chromium/third_party/WebKit/Source/core/html/HTMLCollection.h
index 4ff5e71f5d0..967b247db4d 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLCollection.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLCollection.h
@@ -61,8 +61,8 @@ public:
virtual Element* virtualItemAfter(unsigned& offsetInArray, Element*) const;
- Element* traverseFirstElement(unsigned& offsetInArray, ContainerNode* root) const;
- Element* traverseForwardToOffset(unsigned offset, Element* currentElement, unsigned& currentOffset, unsigned& offsetInArray, ContainerNode* root) const;
+ Element* traverseFirstElement(unsigned& offsetInArray, ContainerNode& root) const;
+ Element* traverseForwardToOffset(unsigned offset, Element& currentElement, unsigned& currentOffset, unsigned& offsetInArray, ContainerNode* root) const;
protected:
HTMLCollection(Node* base, CollectionType, ItemAfterOverrideType);
@@ -77,7 +77,7 @@ protected:
private:
bool checkForNameMatch(Element*, bool checkName, const AtomicString& name) const;
- Element* traverseNextElement(unsigned& offsetInArray, Element* previous, ContainerNode* root) const;
+ Element* traverseNextElement(unsigned& offsetInArray, Element& previous, ContainerNode* root) const;
virtual bool isLiveNodeList() const OVERRIDE { ASSERT_NOT_REACHED(); return true; }
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLCollection.idl b/chromium/third_party/WebKit/Source/core/html/HTMLCollection.idl
index 319d8782b11..0198742a6cb 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLCollection.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLCollection.idl
@@ -19,9 +19,9 @@
*/
[
- CustomToV8,
- GenerateIsReachable=ownerNode,
- DependentLifetime
+ Custom=Wrap,
+ DependentLifetime,
+ GenerateVisitDOMWrapper=ownerNode,
] interface HTMLCollection {
readonly attribute unsigned long length;
getter Node item([Default=Undefined] optional unsigned long index);
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLContentElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLContentElement.h
new file mode 100644
index 00000000000..9d14a277dc7
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLContentElement.h
@@ -0,0 +1,2 @@
+// FIXME: Move HTMLContentElement.h here.
+#include "core/html/shadow/HTMLContentElement.h"
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLDListElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLDListElement.cpp
index 4b14c695604..7196698f622 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLDListElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLDListElement.cpp
@@ -29,16 +29,15 @@ namespace WebCore {
using namespace HTMLNames;
-inline HTMLDListElement::HTMLDListElement(const QualifiedName& tagName, Document& document)
- : HTMLElement(tagName, document)
+inline HTMLDListElement::HTMLDListElement(Document& document)
+ : HTMLElement(dlTag, document)
{
- ASSERT(hasTagName(dlTag));
ScriptWrappable::init(this);
}
-PassRefPtr<HTMLDListElement> HTMLDListElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<HTMLDListElement> HTMLDListElement::create(Document& document)
{
- return adoptRef(new HTMLDListElement(tagName, document));
+ return adoptRef(new HTMLDListElement(document));
}
}
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLDListElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLDListElement.h
index 1909af69d41..24aeb814c09 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLDListElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLDListElement.h
@@ -29,10 +29,10 @@ namespace WebCore {
class HTMLDListElement FINAL : public HTMLElement {
public:
- static PassRefPtr<HTMLDListElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<HTMLDListElement> create(Document&);
private:
- HTMLDListElement(const QualifiedName&, Document&);
+ explicit HTMLDListElement(Document&);
};
} //namespace
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLDataListElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLDataListElement.cpp
index 42e2d680e99..d8666e88e91 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLDataListElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLDataListElement.cpp
@@ -32,21 +32,22 @@
#include "config.h"
#include "core/html/HTMLDataListElement.h"
+#include "HTMLNames.h"
#include "core/dom/IdTargetObserverRegistry.h"
-#include "core/page/UseCounter.h"
+#include "core/frame/UseCounter.h"
namespace WebCore {
-inline HTMLDataListElement::HTMLDataListElement(const QualifiedName& tagName, Document& document)
- : HTMLElement(tagName, document)
+inline HTMLDataListElement::HTMLDataListElement(Document& document)
+ : HTMLElement(HTMLNames::datalistTag, document)
{
ScriptWrappable::init(this);
}
-PassRefPtr<HTMLDataListElement> HTMLDataListElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<HTMLDataListElement> HTMLDataListElement::create(Document& document)
{
- UseCounter::count(&document, UseCounter::DataListElement);
- return adoptRef(new HTMLDataListElement(tagName, document));
+ UseCounter::count(document, UseCounter::DataListElement);
+ return adoptRef(new HTMLDataListElement(document));
}
PassRefPtr<HTMLCollection> HTMLDataListElement::options()
@@ -54,6 +55,18 @@ PassRefPtr<HTMLCollection> HTMLDataListElement::options()
return ensureCachedHTMLCollection(DataListOptions);
}
+void HTMLDataListElement::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
+{
+ HTMLElement::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
+ if (!changedByParser)
+ treeScope().idTargetObserverRegistry().notifyObservers(getIdAttribute());
+}
+
+void HTMLDataListElement::finishParsingChildren()
+{
+ treeScope().idTargetObserverRegistry().notifyObservers(getIdAttribute());
+}
+
void HTMLDataListElement::optionElementChildrenChanged()
{
treeScope().idTargetObserverRegistry().notifyObservers(getIdAttribute());
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLDataListElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLDataListElement.h
index 7deb03a8a8b..e19686bfa5c 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLDataListElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLDataListElement.h
@@ -39,21 +39,19 @@ namespace WebCore {
class HTMLDataListElement FINAL : public HTMLElement {
public:
- static PassRefPtr<HTMLDataListElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<HTMLDataListElement> create(Document&);
PassRefPtr<HTMLCollection> options();
void optionElementChildrenChanged();
private:
- HTMLDataListElement(const QualifiedName&, Document&);
+ HTMLDataListElement(Document&);
+ virtual void childrenChanged(bool, Node*, Node*, int) OVERRIDE;
+ virtual void finishParsingChildren() OVERRIDE;
};
-inline HTMLDataListElement* toHTMLDataListElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::datalistTag));
- return static_cast<HTMLDataListElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(HTMLDataListElement, hasTagName(HTMLNames::datalistTag));
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLDataListElement.idl b/chromium/third_party/WebKit/Source/core/html/HTMLDataListElement.idl
index f87df9a3c55..93c8663c2bb 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLDataListElement.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLDataListElement.idl
@@ -29,7 +29,7 @@
*/
[
- EnabledAtRuntime=DataListElement
+ RuntimeEnabled=DataListElement
] interface HTMLDataListElement : HTMLElement {
readonly attribute HTMLCollection options;
};
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLDetailsElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLDetailsElement.cpp
index a147f121296..28c6bbeae6c 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLDetailsElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLDetailsElement.cpp
@@ -27,25 +27,24 @@
#include "core/dom/shadow/ShadowRoot.h"
#include "core/html/HTMLSummaryElement.h"
#include "core/html/shadow/HTMLContentElement.h"
-#include "core/platform/LocalizedStrings.h"
#include "core/rendering/RenderBlockFlow.h"
+#include "platform/text/PlatformLocale.h"
namespace WebCore {
using namespace HTMLNames;
-PassRefPtr<HTMLDetailsElement> HTMLDetailsElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<HTMLDetailsElement> HTMLDetailsElement::create(Document& document)
{
- RefPtr<HTMLDetailsElement> details = adoptRef(new HTMLDetailsElement(tagName, document));
+ RefPtr<HTMLDetailsElement> details = adoptRef(new HTMLDetailsElement(document));
details->ensureUserAgentShadowRoot();
return details.release();
}
-HTMLDetailsElement::HTMLDetailsElement(const QualifiedName& tagName, Document& document)
- : HTMLElement(tagName, document)
+HTMLDetailsElement::HTMLDetailsElement(Document& document)
+ : HTMLElement(detailsTag, document)
, m_isOpen(false)
{
- ASSERT(hasTagName(detailsTag));
ScriptWrappable::init(this);
}
@@ -54,19 +53,19 @@ RenderObject* HTMLDetailsElement::createRenderer(RenderStyle*)
return new RenderBlockFlow(this);
}
-void HTMLDetailsElement::didAddUserAgentShadowRoot(ShadowRoot* root)
+void HTMLDetailsElement::didAddUserAgentShadowRoot(ShadowRoot& root)
{
- DEFINE_STATIC_LOCAL(AtomicString, summarySelector, ("summary:first-of-type", AtomicString::ConstructFromLiteral));
+ DEFINE_STATIC_LOCAL(const AtomicString, summarySelector, ("summary:first-of-type", AtomicString::ConstructFromLiteral));
- RefPtr<HTMLSummaryElement> defaultSummary = HTMLSummaryElement::create(summaryTag, document());
- defaultSummary->appendChild(Text::create(document(), defaultDetailsSummaryText()));
+ RefPtr<HTMLSummaryElement> defaultSummary = HTMLSummaryElement::create(document());
+ defaultSummary->appendChild(Text::create(document(), locale().queryString(blink::WebLocalizedString::DetailsLabel)));
RefPtr<HTMLContentElement> content = HTMLContentElement::create(document());
content->setAttribute(selectAttr, summarySelector);
content->appendChild(defaultSummary);
- root->appendChild(content);
- root->appendChild(HTMLContentElement::create(document()));
+ root.appendChild(content);
+ root.appendChild(HTMLContentElement::create(document()));
}
Element* HTMLDetailsElement::findMainSummary() const
@@ -99,7 +98,7 @@ bool HTMLDetailsElement::childShouldCreateRenderer(const Node& child) const
return HTMLElement::childShouldCreateRenderer(child);
if (!child.hasTagName(summaryTag))
return false;
- return &child == findMainSummary() && HTMLElement::childShouldCreateRenderer(child);
+ return child == findMainSummary() && HTMLElement::childShouldCreateRenderer(child);
}
void HTMLDetailsElement::toggleOpen()
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLDetailsElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLDetailsElement.h
index 55e635c74d3..d5a6b4a6169 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLDetailsElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLDetailsElement.h
@@ -27,18 +27,18 @@ namespace WebCore {
class HTMLDetailsElement FINAL : public HTMLElement {
public:
- static PassRefPtr<HTMLDetailsElement> create(const QualifiedName& tagName, Document&);
+ static PassRefPtr<HTMLDetailsElement> create(Document&);
void toggleOpen();
Element* findMainSummary() const;
private:
- HTMLDetailsElement(const QualifiedName&, Document&);
+ explicit HTMLDetailsElement(Document&);
virtual RenderObject* createRenderer(RenderStyle*);
virtual bool childShouldCreateRenderer(const Node& child) const OVERRIDE;
virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
- virtual void didAddUserAgentShadowRoot(ShadowRoot*) OVERRIDE;
+ virtual void didAddUserAgentShadowRoot(ShadowRoot&) OVERRIDE;
virtual bool isInteractiveContent() const OVERRIDE;
bool m_isOpen;
@@ -54,11 +54,7 @@ inline bool isHTMLDetailsElement(const Element* element)
return element->hasTagName(HTMLNames::detailsTag);
}
-inline HTMLDetailsElement* toHTMLDetailsElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || isHTMLDetailsElement(node));
- return static_cast<HTMLDetailsElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(HTMLDetailsElement, hasTagName(HTMLNames::detailsTag));
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLDialogElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLDialogElement.cpp
index 2f030139411..59d5bc04a5e 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLDialogElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLDialogElement.cpp
@@ -27,8 +27,11 @@
#include "core/html/HTMLDialogElement.h"
#include "bindings/v8/ExceptionState.h"
+#include "core/accessibility/AXObjectCache.h"
#include "core/dom/ExceptionCode.h"
-#include "core/page/FrameView.h"
+#include "core/dom/NodeTraversal.h"
+#include "core/html/HTMLFormControlElement.h"
+#include "core/frame/FrameView.h"
#include "core/rendering/RenderBlock.h"
#include "core/rendering/style/RenderStyle.h"
@@ -36,31 +39,75 @@ namespace WebCore {
using namespace HTMLNames;
-static bool needsCenteredPositioning(const RenderStyle* style)
+// This function chooses the focused element when showModal() is invoked, as described in the spec for showModal().
+static void setFocusForModalDialog(HTMLDialogElement* dialog)
{
- return style->position() == AbsolutePosition && style->hasAutoTopAndBottom();
+ Element* focusableDescendant = 0;
+ Node* next = 0;
+ for (Node* node = dialog->firstChild(); node; node = next) {
+ if (node->hasTagName(dialogTag))
+ next = NodeTraversal::nextSkippingChildren(*node, dialog);
+ else
+ next = NodeTraversal::next(*node, dialog);
+
+ if (!node->isElementNode())
+ continue;
+ Element* element = toElement(node);
+ if (element->isFormControlElement()) {
+ HTMLFormControlElement* control = toHTMLFormControlElement(node);
+ if (control->isAutofocusable()) {
+ control->focus();
+ control->setAutofocused();
+ return;
+ }
+ }
+ if (!focusableDescendant && element->isFocusable())
+ focusableDescendant = element;
+ }
+
+ if (focusableDescendant) {
+ focusableDescendant->focus();
+ return;
+ }
+
+ if (dialog->isFocusable()) {
+ dialog->focus();
+ return;
+ }
+
+ dialog->document().setFocusedElement(0);
}
-HTMLDialogElement::HTMLDialogElement(const QualifiedName& tagName, Document& document)
- : HTMLElement(tagName, document)
- , m_topIsValid(false)
- , m_top(0)
+static void inertSubtreesChanged(Document& document)
+{
+ // When a modal dialog opens or closes, nodes all over the accessibility
+ // tree can change inertness which means they must be added or removed from
+ // the tree. The most foolproof way is to clear the entire tree and rebuild
+ // it, though a more clever way is probably possible.
+ Document* topDocument = document.topDocument();
+ topDocument->clearAXObjectCache();
+ if (AXObjectCache* cache = topDocument->axObjectCache())
+ cache->childrenChanged(cache->getOrCreate(topDocument));
+}
+
+HTMLDialogElement::HTMLDialogElement(Document& document)
+ : HTMLElement(dialogTag, document)
+ , m_centeringMode(Uninitialized)
+ , m_centeredPosition(0)
, m_returnValue("")
{
- ASSERT(hasTagName(dialogTag));
- setHasCustomStyleCallbacks();
ScriptWrappable::init(this);
}
-PassRefPtr<HTMLDialogElement> HTMLDialogElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<HTMLDialogElement> HTMLDialogElement::create(Document& document)
{
- return adoptRef(new HTMLDialogElement(tagName, document));
+ return adoptRef(new HTMLDialogElement(document));
}
-void HTMLDialogElement::close(const String& returnValue, ExceptionState& es)
+void HTMLDialogElement::close(const String& returnValue, ExceptionState& exceptionState)
{
if (!fastHasAttribute(openAttr)) {
- es.throwDOMException(InvalidStateError);
+ exceptionState.throwDOMException(InvalidStateError, "The element does not have an 'open' attribute, and therefore cannot be closed.");
return;
}
closeDialog(returnValue);
@@ -68,48 +115,27 @@ void HTMLDialogElement::close(const String& returnValue, ExceptionState& es)
void HTMLDialogElement::closeDialog(const String& returnValue)
{
+ if (!fastHasAttribute(openAttr))
+ return;
setBooleanAttribute(openAttr, false);
+
+ HTMLDialogElement* activeModalDialog = document().activeModalDialog();
document().removeFromTopLayer(this);
- m_topIsValid = false;
+ if (activeModalDialog == this)
+ inertSubtreesChanged(document());
if (!returnValue.isNull())
m_returnValue = returnValue;
- dispatchEvent(Event::create(eventNames().closeEvent));
-}
-
-PassRefPtr<RenderStyle> HTMLDialogElement::customStyleForRenderer()
-{
- RefPtr<RenderStyle> originalStyle = originalStyleForRenderer();
- RefPtr<RenderStyle> style = RenderStyle::clone(originalStyle.get());
-
- // Override top to remain centered after style recalcs.
- if (needsCenteredPositioning(style.get()) && m_topIsValid)
- style->setTop(Length(m_top.toInt(), WebCore::Fixed));
-
- return style.release();
+ dispatchScopedEvent(Event::create(EventTypeNames::close));
}
-void HTMLDialogElement::reposition()
+void HTMLDialogElement::forceLayoutForCentering()
{
- // Layout because we need to know our ancestors' positions and our own height.
+ m_centeringMode = Uninitialized;
document().updateLayoutIgnorePendingStylesheets();
-
- RenderBox* box = renderBox();
- if (!box || !needsCenteredPositioning(box->style()))
- return;
-
- // Set up dialog's position to be safe-centered in the viewport.
- // FIXME: Figure out what to do in vertical writing mode.
- FrameView* frameView = document().view();
- int scrollTop = frameView->scrollOffset().height();
- int visibleHeight = frameView->visibleContentRect(ScrollableArea::IncludeScrollbars).height();
- m_top = scrollTop;
- if (box->height() < visibleHeight)
- m_top += (visibleHeight - box->height()) / 2;
- m_topIsValid = true;
-
- setNeedsStyleRecalc(LocalStyleChange);
+ if (m_centeringMode == Uninitialized)
+ m_centeringMode = NotCentered;
}
void HTMLDialogElement::show()
@@ -117,18 +143,42 @@ void HTMLDialogElement::show()
if (fastHasAttribute(openAttr))
return;
setBooleanAttribute(openAttr, true);
- reposition();
+ forceLayoutForCentering();
}
-void HTMLDialogElement::showModal(ExceptionState& es)
+void HTMLDialogElement::showModal(ExceptionState& exceptionState)
{
- if (fastHasAttribute(openAttr) || !inDocument()) {
- es.throwDOMException(InvalidStateError);
+ if (fastHasAttribute(openAttr)) {
+ exceptionState.throwDOMException(InvalidStateError, "The element already has an 'open' attribute, and therefore cannot be opened modally.");
+ return;
+ }
+ if (!inDocument()) {
+ exceptionState.throwDOMException(InvalidStateError, "The element is not in a Document.");
return;
}
+
document().addToTopLayer(this);
setBooleanAttribute(openAttr, true);
- reposition();
+
+ // Throw away the AX cache first, so the subsequent steps don't have a chance of queuing up
+ // AX events on objects that would be invalidated when the cache is thrown away.
+ inertSubtreesChanged(document());
+
+ forceLayoutForCentering();
+ setFocusForModalDialog(this);
+}
+
+void HTMLDialogElement::setCentered(LayoutUnit centeredPosition)
+{
+ ASSERT(m_centeringMode == Uninitialized);
+ m_centeredPosition = centeredPosition;
+ m_centeringMode = Centered;
+}
+
+void HTMLDialogElement::setNotCentered()
+{
+ ASSERT(m_centeringMode == Uninitialized);
+ m_centeringMode = NotCentered;
}
bool HTMLDialogElement::isPresentationAttribute(const QualifiedName& name) const
@@ -143,7 +193,7 @@ bool HTMLDialogElement::isPresentationAttribute(const QualifiedName& name) const
void HTMLDialogElement::defaultEventHandler(Event* event)
{
- if (event->type() == eventNames().cancelEvent) {
+ if (event->type() == EventTypeNames::cancel) {
closeDialog();
event->setDefaultHandled();
return;
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLDialogElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLDialogElement.h
index f17bc844068..248044e98f8 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLDialogElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLDialogElement.h
@@ -26,6 +26,7 @@
#ifndef HTMLDialogElement_h
#define HTMLDialogElement_h
+#include "RuntimeEnabledFeatures.h"
#include "core/html/HTMLElement.h"
namespace WebCore {
@@ -36,34 +37,44 @@ class QualifiedName;
class HTMLDialogElement FINAL : public HTMLElement {
public:
- static PassRefPtr<HTMLDialogElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<HTMLDialogElement> create(Document&);
void close(const String& returnValue, ExceptionState&);
+ void closeDialog(const String& returnValue = String());
void show();
void showModal(ExceptionState&);
+ enum CenteringMode { Uninitialized, Centered, NotCentered };
+ CenteringMode centeringMode() const { return m_centeringMode; }
+ LayoutUnit centeredPosition() const
+ {
+ ASSERT(m_centeringMode == Centered);
+ return m_centeredPosition;
+ }
+ void setCentered(LayoutUnit centeredPosition);
+ void setNotCentered();
+
String returnValue() const { return m_returnValue; }
void setReturnValue(const String& returnValue) { m_returnValue = returnValue; }
private:
- HTMLDialogElement(const QualifiedName&, Document&);
+ explicit HTMLDialogElement(Document&);
- virtual PassRefPtr<RenderStyle> customStyleForRenderer() OVERRIDE;
virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
virtual void defaultEventHandler(Event*) OVERRIDE;
virtual bool shouldBeReparentedUnderRenderView(const RenderStyle*) const OVERRIDE;
- void closeDialog(const String& returnValue = String());
- void reposition();
+ void forceLayoutForCentering();
- bool m_topIsValid;
- LayoutUnit m_top;
+ CenteringMode m_centeringMode;
+ LayoutUnit m_centeredPosition;
String m_returnValue;
};
inline HTMLDialogElement* toHTMLDialogElement(Node* node)
{
ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::dialogTag));
+ ASSERT_WITH_SECURITY_IMPLICATION(RuntimeEnabledFeatures::dialogElementEnabled());
return static_cast<HTMLDialogElement*>(node);
}
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLDialogElement.idl b/chromium/third_party/WebKit/Source/core/html/HTMLDialogElement.idl
index 41732ab70aa..6c2d0c8c0fe 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLDialogElement.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLDialogElement.idl
@@ -24,7 +24,7 @@
*/
[
- EnabledAtRuntime=DialogElement
+ RuntimeEnabled=DialogElement
] interface HTMLDialogElement : HTMLElement {
[Reflect] attribute boolean open;
attribute DOMString returnValue;
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLDimension.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLDimension.cpp
index 959b9fe2f4b..e15acbe7a87 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLDimension.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLDimension.cpp
@@ -62,7 +62,6 @@ static HTMLDimension parseDimension(const CharacterType* characters, size_t last
if (position < endOfCurrentToken && characters[position] == '.') {
++position;
- size_t fractionStart = position;
Vector<CharacterType> fractionNumbers;
while (position < endOfCurrentToken && (isASCIIDigit(characters[position]) || isASCIISpace(characters[position]))) {
if (isASCIIDigit(characters[position]))
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLDimensionTest.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLDimensionTest.cpp
new file mode 100644
index 00000000000..4ef334bed00
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLDimensionTest.cpp
@@ -0,0 +1,227 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/html/HTMLDimension.h"
+
+#include "wtf/text/WTFString.h"
+#include <gtest/gtest.h>
+
+namespace WebCore {
+
+// This assertion-prettify function needs to be in the WebCore namespace.
+void PrintTo(const HTMLDimension& dimension, ::std::ostream* os)
+{
+ *os << "HTMLDimension => type: " << dimension.type() << ", value=" << dimension.value();
+}
+
+}
+
+using namespace WebCore;
+
+namespace {
+
+TEST(WebCoreHTMLDimension, parseListOfDimensionsEmptyString)
+{
+ Vector<HTMLDimension> result = parseListOfDimensions(String(""));
+ ASSERT_EQ(Vector<HTMLDimension>(), result);
+}
+
+TEST(WebCoreHTMLDimension, parseListOfDimensionsNoNumberAbsolute)
+{
+ Vector<HTMLDimension> result = parseListOfDimensions(String(" \t"));
+ ASSERT_EQ(1U, result.size());
+ ASSERT_EQ(HTMLDimension(0, HTMLDimension::Relative), result[0]);
+}
+
+TEST(WebCoreHTMLDimension, parseListOfDimensionsNoNumberPercent)
+{
+ Vector<HTMLDimension> result = parseListOfDimensions(String(" \t%"));
+ ASSERT_EQ(1U, result.size());
+ ASSERT_EQ(HTMLDimension(0, HTMLDimension::Percentage), result[0]);
+}
+
+TEST(WebCoreHTMLDimension, parseListOfDimensionsNoNumberRelative)
+{
+ Vector<HTMLDimension> result = parseListOfDimensions(String("\t *"));
+ ASSERT_EQ(1U, result.size());
+ ASSERT_EQ(HTMLDimension(0, HTMLDimension::Relative), result[0]);
+}
+
+TEST(WebCoreHTMLDimension, parseListOfDimensionsSingleAbsolute)
+{
+ Vector<HTMLDimension> result = parseListOfDimensions(String("10"));
+
+ ASSERT_EQ(1U, result.size());
+ ASSERT_EQ(HTMLDimension(10, HTMLDimension::Absolute), result[0]);
+}
+
+TEST(WebCoreHTMLDimension, parseListOfDimensionsSinglePercentageWithSpaces)
+{
+ Vector<HTMLDimension> result = parseListOfDimensions(String("50 %"));
+
+ ASSERT_EQ(1U, result.size());
+ ASSERT_EQ(HTMLDimension(50, HTMLDimension::Percentage), result[0]);
+}
+
+TEST(WebCoreHTMLDimension, parseListOfDimensionsSingleRelative)
+{
+ Vector<HTMLDimension> result = parseListOfDimensions(String("25*"));
+
+ ASSERT_EQ(1U, result.size());
+ ASSERT_EQ(HTMLDimension(25, HTMLDimension::Relative), result[0]);
+}
+
+TEST(WebCoreHTMLDimension, parseListOfDimensionsDoubleAbsolute)
+{
+ Vector<HTMLDimension> result = parseListOfDimensions(String("10.054"));
+
+ ASSERT_EQ(1U, result.size());
+ ASSERT_EQ(HTMLDimension(10.054, HTMLDimension::Absolute), result[0]);
+}
+
+TEST(WebCoreHTMLDimension, parseListOfDimensionsLeadingSpaceAbsolute)
+{
+ Vector<HTMLDimension> result = parseListOfDimensions(String("\t \t 10"));
+
+ ASSERT_EQ(1U, result.size());
+ ASSERT_EQ(HTMLDimension(10, HTMLDimension::Absolute), result[0]);
+}
+
+TEST(WebCoreHTMLDimension, parseListOfDimensionsLeadingSpaceRelative)
+{
+ Vector<HTMLDimension> result = parseListOfDimensions(String(" \r25*"));
+
+ ASSERT_EQ(1U, result.size());
+ ASSERT_EQ(HTMLDimension(25, HTMLDimension::Relative), result[0]);
+}
+
+TEST(WebCoreHTMLDimension, parseListOfDimensionsLeadingSpacePercentage)
+{
+ Vector<HTMLDimension> result = parseListOfDimensions(String("\n 25%"));
+
+ ASSERT_EQ(1U, result.size());
+ ASSERT_EQ(HTMLDimension(25, HTMLDimension::Percentage), result[0]);
+}
+
+TEST(WebCoreHTMLDimension, parseListOfDimensionsDoublePercentage)
+{
+ Vector<HTMLDimension> result = parseListOfDimensions(String("10.054%"));
+
+ ASSERT_EQ(1U, result.size());
+ ASSERT_EQ(HTMLDimension(10.054, HTMLDimension::Percentage), result[0]);
+}
+
+TEST(WebCoreHTMLDimension, parseListOfDimensionsDoubleRelative)
+{
+ Vector<HTMLDimension> result = parseListOfDimensions(String("10.054*"));
+
+ ASSERT_EQ(1U, result.size());
+ ASSERT_EQ(HTMLDimension(10.054, HTMLDimension::Relative), result[0]);
+}
+
+TEST(WebCoreHTMLDimension, parseListOfDimensionsSpacesInIntegerDoubleAbsolute)
+{
+ Vector<HTMLDimension> result = parseListOfDimensions(String("1\n0 .025%"));
+
+ ASSERT_EQ(1U, result.size());
+ ASSERT_EQ(HTMLDimension(1, HTMLDimension::Absolute), result[0]);
+}
+
+TEST(WebCoreHTMLDimension, parseListOfDimensionsSpacesInIntegerDoublePercent)
+{
+ Vector<HTMLDimension> result = parseListOfDimensions(String("1\n0 .025%"));
+
+ ASSERT_EQ(1U, result.size());
+ ASSERT_EQ(HTMLDimension(1, HTMLDimension::Absolute), result[0]);
+}
+
+TEST(WebCoreHTMLDimension, parseListOfDimensionsSpacesInIntegerDoubleRelative)
+{
+ Vector<HTMLDimension> result = parseListOfDimensions(String("1\n0 .025*"));
+
+ ASSERT_EQ(1U, result.size());
+ ASSERT_EQ(HTMLDimension(1, HTMLDimension::Absolute), result[0]);
+}
+
+TEST(WebCoreHTMLDimension, parseListOfDimensionsSpacesInFractionAfterDotDoublePercent)
+{
+ Vector<HTMLDimension> result = parseListOfDimensions(String("10. 0 25%"));
+
+ ASSERT_EQ(1U, result.size());
+ ASSERT_EQ(HTMLDimension(10.025, HTMLDimension::Percentage), result[0]);
+}
+
+TEST(WebCoreHTMLDimension, parseListOfDimensionsSpacesInFractionAfterDigitDoublePercent)
+{
+ Vector<HTMLDimension> result = parseListOfDimensions(String("10.05\r25%"));
+
+ ASSERT_EQ(1U, result.size());
+ ASSERT_EQ(HTMLDimension(10.0525, HTMLDimension::Percentage), result[0]);
+}
+
+TEST(WebCoreHTMLDimension, parseListOfDimensionsTrailingComma)
+{
+ Vector<HTMLDimension> result = parseListOfDimensions(String("10,"));
+
+ ASSERT_EQ(1U, result.size());
+ ASSERT_EQ(HTMLDimension(10, HTMLDimension::Absolute), result[0]);
+}
+
+TEST(WebCoreHTMLDimension, parseListOfDimensionsTwoDimensions)
+{
+ Vector<HTMLDimension> result = parseListOfDimensions(String("10*,25 %"));
+
+ ASSERT_EQ(2U, result.size());
+ ASSERT_EQ(HTMLDimension(10, HTMLDimension::Relative), result[0]);
+ ASSERT_EQ(HTMLDimension(25, HTMLDimension::Percentage), result[1]);
+}
+
+TEST(WebCoreHTMLDimension, parseListOfDimensionsMultipleDimensionsWithSpaces)
+{
+ Vector<HTMLDimension> result = parseListOfDimensions(String("10 * ,\t25 , 10.05\n5%"));
+
+ ASSERT_EQ(3U, result.size());
+ ASSERT_EQ(HTMLDimension(10, HTMLDimension::Relative), result[0]);
+ ASSERT_EQ(HTMLDimension(25, HTMLDimension::Absolute), result[1]);
+ ASSERT_EQ(HTMLDimension(10.055, HTMLDimension::Percentage), result[2]);
+}
+
+TEST(WebCoreHTMLDimension, parseListOfDimensionsMultipleDimensionsWithOneEmpty)
+{
+ Vector<HTMLDimension> result = parseListOfDimensions(String("2*,,8.%"));
+
+ ASSERT_EQ(3U, result.size());
+ ASSERT_EQ(HTMLDimension(2, HTMLDimension::Relative), result[0]);
+ ASSERT_EQ(HTMLDimension(0, HTMLDimension::Relative), result[1]);
+ ASSERT_EQ(HTMLDimension(8., HTMLDimension::Percentage), result[2]);
+}
+
+}
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLDirectoryElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLDirectoryElement.cpp
index 0068dfa4d42..2010c5a5178 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLDirectoryElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLDirectoryElement.cpp
@@ -29,16 +29,15 @@ namespace WebCore {
using namespace HTMLNames;
-inline HTMLDirectoryElement::HTMLDirectoryElement(const QualifiedName& tagName, Document& document)
- : HTMLElement(tagName, document)
+inline HTMLDirectoryElement::HTMLDirectoryElement(Document& document)
+ : HTMLElement(dirTag, document)
{
- ASSERT(hasTagName(dirTag));
ScriptWrappable::init(this);
}
-PassRefPtr<HTMLDirectoryElement> HTMLDirectoryElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<HTMLDirectoryElement> HTMLDirectoryElement::create(Document& document)
{
- return adoptRef(new HTMLDirectoryElement(tagName, document));
+ return adoptRef(new HTMLDirectoryElement(document));
}
}
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLDirectoryElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLDirectoryElement.h
index 99efc0de722..7c0dcaa7951 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLDirectoryElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLDirectoryElement.h
@@ -29,10 +29,10 @@ namespace WebCore {
class HTMLDirectoryElement FINAL : public HTMLElement {
public:
- static PassRefPtr<HTMLDirectoryElement> create(const QualifiedName& tagName, Document&);
+ static PassRefPtr<HTMLDirectoryElement> create(Document&);
private:
- HTMLDirectoryElement(const QualifiedName&, Document&);
+ explicit HTMLDirectoryElement(Document&);
};
} //namespace
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLDivElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLDivElement.cpp
index 8ed60f14523..af3d8938783 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLDivElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLDivElement.cpp
@@ -31,21 +31,15 @@ namespace WebCore {
using namespace HTMLNames;
-HTMLDivElement::HTMLDivElement(const QualifiedName& tagName, Document& document)
- : HTMLElement(tagName, document)
+HTMLDivElement::HTMLDivElement(Document& document)
+ : HTMLElement(divTag, document)
{
- ASSERT(hasTagName(divTag));
ScriptWrappable::init(this);
}
PassRefPtr<HTMLDivElement> HTMLDivElement::create(Document& document)
{
- return adoptRef(new HTMLDivElement(divTag, document));
-}
-
-PassRefPtr<HTMLDivElement> HTMLDivElement::create(const QualifiedName& tagName, Document& document)
-{
- return adoptRef(new HTMLDivElement(tagName, document));
+ return adoptRef(new HTMLDivElement(document));
}
bool HTMLDivElement::isPresentationAttribute(const QualifiedName& name) const
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLDivElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLDivElement.h
index 72b1153f71f..12e230088b2 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLDivElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLDivElement.h
@@ -30,21 +30,16 @@ namespace WebCore {
class HTMLDivElement : public HTMLElement {
public:
static PassRefPtr<HTMLDivElement> create(Document&);
- static PassRefPtr<HTMLDivElement> create(const QualifiedName&, Document&);
protected:
- HTMLDivElement(const QualifiedName&, Document&);
+ explicit HTMLDivElement(Document&);
private:
virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
virtual void collectStyleForPresentationAttribute(const QualifiedName&, const AtomicString&, MutableStylePropertySet*) OVERRIDE;
};
-inline HTMLDivElement* toHTMLDivElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::divTag));
- return static_cast<HTMLDivElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(HTMLDivElement, hasTagName(HTMLNames::divTag));
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLDivElement.idl b/chromium/third_party/WebKit/Source/core/html/HTMLDivElement.idl
index 5793564e43d..f8ab12231b0 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLDivElement.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLDivElement.idl
@@ -17,8 +17,6 @@
* Boston, MA 02110-1301, USA.
*/
-[
-] interface HTMLDivElement : HTMLElement {
+interface HTMLDivElement : HTMLElement {
[Reflect] attribute DOMString align;
};
-
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLDocument.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLDocument.cpp
index a38ac89648b..761a6e3093a 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLDocument.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLDocument.cpp
@@ -55,12 +55,14 @@
#include "HTMLNames.h"
#include "bindings/v8/ScriptController.h"
+#include "core/frame/DOMWindow.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
#include "core/html/HTMLBodyElement.h"
#include "core/page/FocusController.h"
-#include "core/page/Frame.h"
#include "core/page/FrameTree.h"
-#include "core/page/FrameView.h"
#include "core/page/Page.h"
+#include "wtf/text/StringBuilder.h"
namespace WebCore {
@@ -77,15 +79,15 @@ HTMLDocument::~HTMLDocument()
{
}
-String HTMLDocument::dir()
+const AtomicString& HTMLDocument::dir()
{
HTMLElement* b = body();
if (!b)
- return String();
+ return nullAtom;
return b->getAttribute(dirAttr);
}
-void HTMLDocument::setDir(const String& value)
+void HTMLDocument::setDir(const AtomicString& value)
{
HTMLElement* b = body();
if (b)
@@ -124,96 +126,90 @@ bool HTMLDocument::hasFocus()
if (!page->focusController().isActive() || !page->focusController().isFocused())
return false;
if (Frame* focusedFrame = page->focusController().focusedFrame()) {
- if (focusedFrame->tree()->isDescendantOf(frame()))
+ if (focusedFrame->tree().isDescendantOf(frame()))
return true;
}
return false;
}
-inline HTMLBodyElement* HTMLDocument::bodyAsHTMLBodyElement() const
+HTMLBodyElement* HTMLDocument::htmlBodyElement() const
{
- HTMLElement* element = body();
- return (element && element->hasTagName(bodyTag)) ? toHTMLBodyElement(element) : 0;
+ HTMLElement* body = this->body();
+ return (body && body->hasTagName(bodyTag)) ? toHTMLBodyElement(body) : 0;
}
-String HTMLDocument::bgColor()
+const AtomicString& HTMLDocument::bodyAttributeValue(const QualifiedName& name) const
{
- if (HTMLBodyElement* bodyElement = bodyAsHTMLBodyElement())
- return bodyElement->bgColor();
- return String();
+ if (HTMLBodyElement* body = htmlBodyElement())
+ return body->fastGetAttribute(name);
+ return nullAtom;
}
-void HTMLDocument::setBgColor(const String& value)
+void HTMLDocument::setBodyAttribute(const QualifiedName& name, const AtomicString& value)
{
- if (HTMLBodyElement* bodyElement = bodyAsHTMLBodyElement())
- bodyElement->setBgColor(value);
+ if (HTMLBodyElement* body = htmlBodyElement()) {
+ // FIXME: This check is apparently for benchmarks that set the same value repeatedly.
+ // It's not clear what benchmarks though, it's also not clear why we don't avoid
+ // causing a style recalc when setting the same value to a presentational attribute
+ // in the common case.
+ if (body->fastGetAttribute(name) != value)
+ body->setAttribute(name, value);
+ }
}
-String HTMLDocument::fgColor()
+const AtomicString& HTMLDocument::bgColor() const
{
- if (HTMLBodyElement* bodyElement = bodyAsHTMLBodyElement())
- return bodyElement->text();
- return String();
+ return bodyAttributeValue(bgcolorAttr);
}
-void HTMLDocument::setFgColor(const String& value)
+void HTMLDocument::setBgColor(const AtomicString& value)
{
- if (HTMLBodyElement* bodyElement = bodyAsHTMLBodyElement())
- bodyElement->setText(value);
+ setBodyAttribute(bgcolorAttr, value);
}
-String HTMLDocument::alinkColor()
+const AtomicString& HTMLDocument::fgColor() const
{
- if (HTMLBodyElement* bodyElement = bodyAsHTMLBodyElement())
- return bodyElement->aLink();
- return String();
+ return bodyAttributeValue(textAttr);
}
-void HTMLDocument::setAlinkColor(const String& value)
+void HTMLDocument::setFgColor(const AtomicString& value)
{
- if (HTMLBodyElement* bodyElement = bodyAsHTMLBodyElement()) {
- // This check is a bit silly, but some benchmarks like to set the
- // document's link colors over and over to the same value and we
- // don't want to incur a style update each time.
- if (bodyElement->aLink() != value)
- bodyElement->setALink(value);
- }
+ setBodyAttribute(textAttr, value);
}
-String HTMLDocument::linkColor()
+const AtomicString& HTMLDocument::alinkColor() const
{
- if (HTMLBodyElement* bodyElement = bodyAsHTMLBodyElement())
- return bodyElement->link();
- return String();
+ return bodyAttributeValue(alinkAttr);
}
-void HTMLDocument::setLinkColor(const String& value)
+void HTMLDocument::setAlinkColor(const AtomicString& value)
{
- if (HTMLBodyElement* bodyElement = bodyAsHTMLBodyElement()) {
- // This check is a bit silly, but some benchmarks like to set the
- // document's link colors over and over to the same value and we
- // don't want to incur a style update each time.
- if (bodyElement->link() != value)
- bodyElement->setLink(value);
- }
+ setBodyAttribute(alinkAttr, value);
}
-String HTMLDocument::vlinkColor()
+const AtomicString& HTMLDocument::linkColor() const
{
- if (HTMLBodyElement* bodyElement = bodyAsHTMLBodyElement())
- return bodyElement->vLink();
- return String();
+ return bodyAttributeValue(linkAttr);
}
-void HTMLDocument::setVlinkColor(const String& value)
+void HTMLDocument::setLinkColor(const AtomicString& value)
{
- if (HTMLBodyElement* bodyElement = bodyAsHTMLBodyElement()) {
- // This check is a bit silly, but some benchmarks like to set the
- // document's link colors over and over to the same value and we
- // don't want to incur a style update each time.
- if (bodyElement->vLink() != value)
- bodyElement->setVLink(value);
- }
+ setBodyAttribute(linkAttr, value);
+}
+
+const AtomicString& HTMLDocument::vlinkColor() const
+{
+ return bodyAttributeValue(vlinkAttr);
+}
+
+void HTMLDocument::setVlinkColor(const AtomicString& value)
+{
+ setBodyAttribute(vlinkAttr, value);
+}
+
+PassRefPtr<Document> HTMLDocument::cloneDocumentWithoutChildren()
+{
+ return create(DocumentInit(url()).withRegistrationContext(registrationContext()));
}
// --------------------------------------------------------------------------
@@ -226,7 +222,7 @@ void HTMLDocument::addItemToMap(HashCountedSet<AtomicString>& map, const AtomicS
return;
map.add(name);
if (Frame* f = frame())
- f->script()->namedItemAdded(this, name);
+ f->script().namedItemAdded(this, name);
}
void HTMLDocument::removeItemFromMap(HashCountedSet<AtomicString>& map, const AtomicString& name)
@@ -235,7 +231,7 @@ void HTMLDocument::removeItemFromMap(HashCountedSet<AtomicString>& map, const At
return;
map.remove(name);
if (Frame* f = frame())
- f->script()->namedItemRemoved(this, name);
+ f->script().namedItemRemoved(this, name);
}
void HTMLDocument::addNamedItem(const AtomicString& name)
@@ -332,4 +328,22 @@ void HTMLDocument::clear()
// But I do see it in the documentation for Mozilla.
}
+void HTMLDocument::write(DOMWindow* activeWindow, const Vector<String>& text)
+{
+ ASSERT(activeWindow);
+ StringBuilder builder;
+ for (size_t i = 0; i < text.size(); ++i)
+ builder.append(text[i]);
+ write(builder.toString(), activeWindow->document());
+}
+
+void HTMLDocument::writeln(DOMWindow* activeWindow, const Vector<String>& text)
+{
+ ASSERT(activeWindow);
+ StringBuilder builder;
+ for (size_t i = 0; i < text.size(); ++i)
+ builder.append(text[i]);
+ writeln(builder.toString(), activeWindow->document());
+}
+
}
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLDocument.h b/chromium/third_party/WebKit/Source/core/html/HTMLDocument.h
index f34c8d2a153..aa52f77ac85 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLDocument.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLDocument.h
@@ -41,8 +41,8 @@ public:
}
virtual ~HTMLDocument();
- String dir();
- void setDir(const String&);
+ const AtomicString& dir();
+ void setDir(const AtomicString&);
String designMode() const;
void setDesignMode(const String&);
@@ -50,16 +50,16 @@ public:
Element* activeElement();
bool hasFocus();
- String bgColor();
- void setBgColor(const String&);
- String fgColor();
- void setFgColor(const String&);
- String alinkColor();
- void setAlinkColor(const String&);
- String linkColor();
- void setLinkColor(const String&);
- String vlinkColor();
- void setVlinkColor(const String&);
+ const AtomicString& bgColor() const;
+ void setBgColor(const AtomicString&);
+ const AtomicString& fgColor() const;
+ void setFgColor(const AtomicString&);
+ const AtomicString& alinkColor() const;
+ void setAlinkColor(const AtomicString&);
+ const AtomicString& linkColor() const;
+ void setLinkColor(const AtomicString&);
+ const AtomicString& vlinkColor() const;
+ void setVlinkColor(const AtomicString&);
void clear();
@@ -74,13 +74,24 @@ public:
void removeExtraNamedItem(const AtomicString& name);
bool hasExtraNamedItem(const AtomicString& name);
+ using Document::write;
+ using Document::writeln;
+ void write(DOMWindow*, const Vector<String>& text);
+ void writeln(DOMWindow*, const Vector<String>& text);
+
static bool isCaseSensitiveAttribute(const QualifiedName&);
+ virtual PassRefPtr<Document> cloneDocumentWithoutChildren() OVERRIDE FINAL;
+
protected:
HTMLDocument(const DocumentInit&, DocumentClassFlags extendedDocumentClasses = DefaultDocumentClass);
private:
- HTMLBodyElement* bodyAsHTMLBodyElement() const;
+ HTMLBodyElement* htmlBodyElement() const;
+
+ const AtomicString& bodyAttributeValue(const QualifiedName&) const;
+ void setBodyAttribute(const QualifiedName&, const AtomicString&);
+
void addItemToMap(HashCountedSet<AtomicString>&, const AtomicString&);
void removeItemFromMap(HashCountedSet<AtomicString>&, const AtomicString&);
@@ -98,32 +109,7 @@ inline bool HTMLDocument::hasExtraNamedItem(const AtomicString& name)
return m_extraNamedItemCounts.contains(name);
}
-inline HTMLDocument* toHTMLDocument(Document* document)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!document || document->isHTMLDocument());
- return static_cast<HTMLDocument*>(document);
-}
-
-inline const HTMLDocument* toHTMLDocument(const Document* document)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!document || document->isHTMLDocument());
- return static_cast<const HTMLDocument*>(document);
-}
-
-inline HTMLDocument& toHTMLDocument(Document& document)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(document.isHTMLDocument());
- return static_cast<HTMLDocument&>(document);
-}
-
-inline const HTMLDocument& toHTMLDocument(const Document& document)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(document.isHTMLDocument());
- return static_cast<const HTMLDocument&>(document);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toHTMLDocument(const HTMLDocument*);
+DEFINE_DOCUMENT_TYPE_CASTS(HTMLDocument);
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLDocument.idl b/chromium/third_party/WebKit/Source/core/html/HTMLDocument.idl
index e44baeeb678..84328c8565f 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLDocument.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLDocument.idl
@@ -18,16 +18,18 @@
* Boston, MA 02110-1301, USA.
*/
-[
- CustomToV8
-] interface HTMLDocument : Document {
- [Custom, CustomElementCallbacks=Enable] void open();
+interface HTMLDocument : Document {
+ [Custom, CustomElementCallbacks] void open();
void close();
- [Custom, PerWorldBindings, ActivityLog=AccessForIsolatedWorlds, CustomElementCallbacks=Enable] void write([Default=Undefined] optional DOMString text);
- [Custom, PerWorldBindings, ActivityLog=AccessForIsolatedWorlds, CustomElementCallbacks=Enable] void writeln([Default=Undefined] optional DOMString text);
+
+ // We support multiple DOMString arguments to match FF / IE, e.g.:
+ // document.write("a", "b", "c") --> document.write("abc")
+ // document.write() --> document.write("")
+ [CallWith=ActiveWindow, PerWorldBindings, ActivityLogging=ForIsolatedWorlds, CustomElementCallbacks] void write(DOMString... text);
+ [CallWith=ActiveWindow, PerWorldBindings, ActivityLogging=ForIsolatedWorlds, CustomElementCallbacks] void writeln(DOMString... text);
readonly attribute HTMLCollection embeds;
- readonly attribute HTMLCollection plugins;
+ [ImplementedAs=embeds] readonly attribute HTMLCollection plugins;
readonly attribute HTMLCollection scripts;
// Extensions
@@ -39,18 +41,18 @@
[DeprecateAs=CaptureEvents] void captureEvents();
[DeprecateAs=ReleaseEvents] void releaseEvents();
- [TreatNullAs=NullString, CustomElementCallbacks=Enable] attribute DOMString dir;
- [TreatNullAs=NullString, CustomElementCallbacks=Enable] attribute DOMString designMode;
+ [TreatNullAs=NullString, CustomElementCallbacks] attribute DOMString dir;
+ [TreatNullAs=NullString, CustomElementCallbacks] attribute DOMString designMode;
readonly attribute DOMString compatMode;
readonly attribute Element activeElement;
boolean hasFocus();
// Deprecated attributes
- [TreatNullAs=NullString, CustomElementCallbacks=Enable] attribute DOMString bgColor;
- [TreatNullAs=NullString, CustomElementCallbacks=Enable] attribute DOMString fgColor;
- [TreatNullAs=NullString, CustomElementCallbacks=Enable] attribute DOMString alinkColor;
- [TreatNullAs=NullString, CustomElementCallbacks=Enable] attribute DOMString linkColor;
- [TreatNullAs=NullString, CustomElementCallbacks=Enable] attribute DOMString vlinkColor;
+ [TreatNullAs=NullString, CustomElementCallbacks] attribute DOMString bgColor;
+ [TreatNullAs=NullString, CustomElementCallbacks] attribute DOMString fgColor;
+ [TreatNullAs=NullString, CustomElementCallbacks] attribute DOMString alinkColor;
+ [TreatNullAs=NullString, CustomElementCallbacks] attribute DOMString linkColor;
+ [TreatNullAs=NullString, CustomElementCallbacks] attribute DOMString vlinkColor;
};
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLElement.cpp
index 7384e904c82..8fcff5b5bfb 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLElement.cpp
@@ -36,13 +36,13 @@
#include "core/css/CSSValuePool.h"
#include "core/css/StylePropertySet.h"
#include "core/dom/DocumentFragment.h"
-#include "core/dom/EventListener.h"
-#include "core/dom/EventNames.h"
#include "core/dom/ExceptionCode.h"
-#include "core/dom/KeyboardEvent.h"
#include "core/dom/NodeTraversal.h"
#include "core/dom/Text.h"
#include "core/editing/markup.h"
+#include "core/events/EventListener.h"
+#include "core/events/KeyboardEvent.h"
+#include "core/events/ThreadLocalEventNames.h"
#include "core/html/HTMLBRElement.h"
#include "core/html/HTMLFormElement.h"
#include "core/html/HTMLInputElement.h"
@@ -50,9 +50,11 @@
#include "core/html/HTMLTextFormControlElement.h"
#include "core/html/parser/HTMLParserIdioms.h"
#include "core/loader/FrameLoader.h"
-#include "core/page/Frame.h"
-#include "core/page/Settings.h"
+#include "core/frame/Frame.h"
+#include "core/frame/Settings.h"
#include "core/rendering/RenderWordBreak.h"
+#include "platform/text/BidiResolver.h"
+#include "platform/text/TextRunIterator.h"
#include "wtf/StdLibExtras.h"
#include "wtf/text/CString.h"
@@ -150,6 +152,11 @@ bool HTMLElement::isPresentationAttribute(const QualifiedName& name) const
return Element::isPresentationAttribute(name);
}
+static inline bool isValidDirAttribute(const AtomicString& value)
+{
+ return equalIgnoringCase(value, "auto") || equalIgnoringCase(value, "ltr") || equalIgnoringCase(value, "rtl");
+}
+
void HTMLElement::collectStyleForPresentationAttribute(const QualifiedName& name, const AtomicString& value, MutableStylePropertySet* style)
{
if (name == alignAttr) {
@@ -180,7 +187,10 @@ void HTMLElement::collectStyleForPresentationAttribute(const QualifiedName& name
if (equalIgnoringCase(value, "auto"))
addPropertyToPresentationAttributeStyle(style, CSSPropertyUnicodeBidi, unicodeBidiAttributeForDirAuto(this));
else {
- addPropertyToPresentationAttributeStyle(style, CSSPropertyDirection, value);
+ if (isValidDirAttribute(value))
+ addPropertyToPresentationAttributeStyle(style, CSSPropertyDirection, value);
+ else
+ addPropertyToPresentationAttributeStyle(style, CSSPropertyDirection, "ltr");
if (!hasTagName(bdiTag) && !hasTagName(bdoTag) && !hasTagName(outputTag))
addPropertyToPresentationAttributeStyle(style, CSSPropertyUnicodeBidi, CSSValueEmbed);
}
@@ -194,91 +204,95 @@ void HTMLElement::collectStyleForPresentationAttribute(const QualifiedName& name
Element::collectStyleForPresentationAttribute(name, value, style);
}
-AtomicString HTMLElement::eventNameForAttributeName(const QualifiedName& attrName) const
+const AtomicString& HTMLElement::eventNameForAttributeName(const QualifiedName& attrName) const
{
if (!attrName.namespaceURI().isNull())
- return AtomicString();
+ return nullAtom;
typedef HashMap<AtomicString, AtomicString> StringToStringMap;
DEFINE_STATIC_LOCAL(StringToStringMap, attributeNameToEventNameMap, ());
if (!attributeNameToEventNameMap.size()) {
- attributeNameToEventNameMap.set(onanimationstartAttr.localName(), eventNames().animationstartEvent);
- attributeNameToEventNameMap.set(onanimationiterationAttr.localName(), eventNames().animationiterationEvent);
- attributeNameToEventNameMap.set(onanimationendAttr.localName(), eventNames().animationendEvent);
- attributeNameToEventNameMap.set(onclickAttr.localName(), eventNames().clickEvent);
- attributeNameToEventNameMap.set(oncontextmenuAttr.localName(), eventNames().contextmenuEvent);
- attributeNameToEventNameMap.set(ondblclickAttr.localName(), eventNames().dblclickEvent);
- attributeNameToEventNameMap.set(onmousedownAttr.localName(), eventNames().mousedownEvent);
- attributeNameToEventNameMap.set(onmouseenterAttr.localName(), eventNames().mouseenterEvent);
- attributeNameToEventNameMap.set(onmouseleaveAttr.localName(), eventNames().mouseleaveEvent);
- attributeNameToEventNameMap.set(onmousemoveAttr.localName(), eventNames().mousemoveEvent);
- attributeNameToEventNameMap.set(onmouseoutAttr.localName(), eventNames().mouseoutEvent);
- attributeNameToEventNameMap.set(onmouseoverAttr.localName(), eventNames().mouseoverEvent);
- attributeNameToEventNameMap.set(onmouseupAttr.localName(), eventNames().mouseupEvent);
- attributeNameToEventNameMap.set(onmousewheelAttr.localName(), eventNames().mousewheelEvent);
- attributeNameToEventNameMap.set(onwheelAttr.localName(), eventNames().wheelEvent);
- attributeNameToEventNameMap.set(onfocusAttr.localName(), eventNames().focusEvent);
- attributeNameToEventNameMap.set(onfocusinAttr.localName(), eventNames().focusinEvent);
- attributeNameToEventNameMap.set(onfocusoutAttr.localName(), eventNames().focusoutEvent);
- attributeNameToEventNameMap.set(onblurAttr.localName(), eventNames().blurEvent);
- attributeNameToEventNameMap.set(onkeydownAttr.localName(), eventNames().keydownEvent);
- attributeNameToEventNameMap.set(onkeypressAttr.localName(), eventNames().keypressEvent);
- attributeNameToEventNameMap.set(onkeyupAttr.localName(), eventNames().keyupEvent);
- attributeNameToEventNameMap.set(onscrollAttr.localName(), eventNames().scrollEvent);
- attributeNameToEventNameMap.set(onbeforecutAttr.localName(), eventNames().beforecutEvent);
- attributeNameToEventNameMap.set(oncutAttr.localName(), eventNames().cutEvent);
- attributeNameToEventNameMap.set(onbeforecopyAttr.localName(), eventNames().beforecopyEvent);
- attributeNameToEventNameMap.set(oncopyAttr.localName(), eventNames().copyEvent);
- attributeNameToEventNameMap.set(onbeforepasteAttr.localName(), eventNames().beforepasteEvent);
- attributeNameToEventNameMap.set(onpasteAttr.localName(), eventNames().pasteEvent);
- attributeNameToEventNameMap.set(ondragenterAttr.localName(), eventNames().dragenterEvent);
- attributeNameToEventNameMap.set(ondragoverAttr.localName(), eventNames().dragoverEvent);
- attributeNameToEventNameMap.set(ondragleaveAttr.localName(), eventNames().dragleaveEvent);
- attributeNameToEventNameMap.set(ondropAttr.localName(), eventNames().dropEvent);
- attributeNameToEventNameMap.set(ondragstartAttr.localName(), eventNames().dragstartEvent);
- attributeNameToEventNameMap.set(ondragAttr.localName(), eventNames().dragEvent);
- attributeNameToEventNameMap.set(ondragendAttr.localName(), eventNames().dragendEvent);
- attributeNameToEventNameMap.set(onselectstartAttr.localName(), eventNames().selectstartEvent);
- attributeNameToEventNameMap.set(onsubmitAttr.localName(), eventNames().submitEvent);
- attributeNameToEventNameMap.set(onerrorAttr.localName(), eventNames().errorEvent);
- attributeNameToEventNameMap.set(onwebkitanimationstartAttr.localName(), eventNames().webkitAnimationStartEvent);
- attributeNameToEventNameMap.set(onwebkitanimationiterationAttr.localName(), eventNames().webkitAnimationIterationEvent);
- attributeNameToEventNameMap.set(onwebkitanimationendAttr.localName(), eventNames().webkitAnimationEndEvent);
- attributeNameToEventNameMap.set(onwebkittransitionendAttr.localName(), eventNames().webkitTransitionEndEvent);
- attributeNameToEventNameMap.set(ontransitionendAttr.localName(), eventNames().webkitTransitionEndEvent);
- attributeNameToEventNameMap.set(oninputAttr.localName(), eventNames().inputEvent);
- attributeNameToEventNameMap.set(oninvalidAttr.localName(), eventNames().invalidEvent);
- attributeNameToEventNameMap.set(ontouchstartAttr.localName(), eventNames().touchstartEvent);
- attributeNameToEventNameMap.set(ontouchmoveAttr.localName(), eventNames().touchmoveEvent);
- attributeNameToEventNameMap.set(ontouchendAttr.localName(), eventNames().touchendEvent);
- attributeNameToEventNameMap.set(ontouchcancelAttr.localName(), eventNames().touchcancelEvent);
- attributeNameToEventNameMap.set(onwebkitfullscreenchangeAttr.localName(), eventNames().webkitfullscreenchangeEvent);
- attributeNameToEventNameMap.set(onwebkitfullscreenerrorAttr.localName(), eventNames().webkitfullscreenerrorEvent);
- attributeNameToEventNameMap.set(onabortAttr.localName(), eventNames().abortEvent);
- attributeNameToEventNameMap.set(oncanplayAttr.localName(), eventNames().canplayEvent);
- attributeNameToEventNameMap.set(oncanplaythroughAttr.localName(), eventNames().canplaythroughEvent);
- attributeNameToEventNameMap.set(onchangeAttr.localName(), eventNames().changeEvent);
- attributeNameToEventNameMap.set(ondurationchangeAttr.localName(), eventNames().durationchangeEvent);
- attributeNameToEventNameMap.set(onemptiedAttr.localName(), eventNames().emptiedEvent);
- attributeNameToEventNameMap.set(onendedAttr.localName(), eventNames().endedEvent);
- attributeNameToEventNameMap.set(onloadeddataAttr.localName(), eventNames().loadeddataEvent);
- attributeNameToEventNameMap.set(onloadedmetadataAttr.localName(), eventNames().loadedmetadataEvent);
- attributeNameToEventNameMap.set(onloadstartAttr.localName(), eventNames().loadstartEvent);
- attributeNameToEventNameMap.set(onpauseAttr.localName(), eventNames().pauseEvent);
- attributeNameToEventNameMap.set(onplayAttr.localName(), eventNames().playEvent);
- attributeNameToEventNameMap.set(onplayingAttr.localName(), eventNames().playingEvent);
- attributeNameToEventNameMap.set(onprogressAttr.localName(), eventNames().progressEvent);
- attributeNameToEventNameMap.set(onratechangeAttr.localName(), eventNames().ratechangeEvent);
- attributeNameToEventNameMap.set(onresetAttr.localName(), eventNames().resetEvent);
- attributeNameToEventNameMap.set(onseekedAttr.localName(), eventNames().seekedEvent);
- attributeNameToEventNameMap.set(onseekingAttr.localName(), eventNames().seekingEvent);
- attributeNameToEventNameMap.set(onselectAttr.localName(), eventNames().selectEvent);
- attributeNameToEventNameMap.set(onstalledAttr.localName(), eventNames().stalledEvent);
- attributeNameToEventNameMap.set(onsuspendAttr.localName(), eventNames().suspendEvent);
- attributeNameToEventNameMap.set(ontimeupdateAttr.localName(), eventNames().timeupdateEvent);
- attributeNameToEventNameMap.set(onvolumechangeAttr.localName(), eventNames().volumechangeEvent);
- attributeNameToEventNameMap.set(onwaitingAttr.localName(), eventNames().waitingEvent);
- attributeNameToEventNameMap.set(onloadAttr.localName(), eventNames().loadEvent);
+ attributeNameToEventNameMap.set(onanimationstartAttr.localName(), EventTypeNames::animationstart);
+ attributeNameToEventNameMap.set(onanimationiterationAttr.localName(), EventTypeNames::animationiteration);
+ attributeNameToEventNameMap.set(onanimationendAttr.localName(), EventTypeNames::animationend);
+ attributeNameToEventNameMap.set(oncancelAttr.localName(), EventTypeNames::cancel);
+ attributeNameToEventNameMap.set(onclickAttr.localName(), EventTypeNames::click);
+ attributeNameToEventNameMap.set(oncloseAttr.localName(), EventTypeNames::close);
+ attributeNameToEventNameMap.set(oncontextmenuAttr.localName(), EventTypeNames::contextmenu);
+ attributeNameToEventNameMap.set(ondblclickAttr.localName(), EventTypeNames::dblclick);
+ attributeNameToEventNameMap.set(onmousedownAttr.localName(), EventTypeNames::mousedown);
+ attributeNameToEventNameMap.set(onmouseenterAttr.localName(), EventTypeNames::mouseenter);
+ attributeNameToEventNameMap.set(onmouseleaveAttr.localName(), EventTypeNames::mouseleave);
+ attributeNameToEventNameMap.set(onmousemoveAttr.localName(), EventTypeNames::mousemove);
+ attributeNameToEventNameMap.set(onmouseoutAttr.localName(), EventTypeNames::mouseout);
+ attributeNameToEventNameMap.set(onmouseoverAttr.localName(), EventTypeNames::mouseover);
+ attributeNameToEventNameMap.set(onmouseupAttr.localName(), EventTypeNames::mouseup);
+ attributeNameToEventNameMap.set(onmousewheelAttr.localName(), EventTypeNames::mousewheel);
+ attributeNameToEventNameMap.set(onwheelAttr.localName(), EventTypeNames::wheel);
+ attributeNameToEventNameMap.set(onfocusAttr.localName(), EventTypeNames::focus);
+ attributeNameToEventNameMap.set(onfocusinAttr.localName(), EventTypeNames::focusin);
+ attributeNameToEventNameMap.set(onfocusoutAttr.localName(), EventTypeNames::focusout);
+ attributeNameToEventNameMap.set(onblurAttr.localName(), EventTypeNames::blur);
+ attributeNameToEventNameMap.set(onkeydownAttr.localName(), EventTypeNames::keydown);
+ attributeNameToEventNameMap.set(onkeypressAttr.localName(), EventTypeNames::keypress);
+ attributeNameToEventNameMap.set(onkeyupAttr.localName(), EventTypeNames::keyup);
+ attributeNameToEventNameMap.set(onscrollAttr.localName(), EventTypeNames::scroll);
+ attributeNameToEventNameMap.set(onbeforecutAttr.localName(), EventTypeNames::beforecut);
+ attributeNameToEventNameMap.set(oncutAttr.localName(), EventTypeNames::cut);
+ attributeNameToEventNameMap.set(onbeforecopyAttr.localName(), EventTypeNames::beforecopy);
+ attributeNameToEventNameMap.set(oncopyAttr.localName(), EventTypeNames::copy);
+ attributeNameToEventNameMap.set(onbeforepasteAttr.localName(), EventTypeNames::beforepaste);
+ attributeNameToEventNameMap.set(onpasteAttr.localName(), EventTypeNames::paste);
+ attributeNameToEventNameMap.set(ondragenterAttr.localName(), EventTypeNames::dragenter);
+ attributeNameToEventNameMap.set(ondragoverAttr.localName(), EventTypeNames::dragover);
+ attributeNameToEventNameMap.set(ondragleaveAttr.localName(), EventTypeNames::dragleave);
+ attributeNameToEventNameMap.set(ondropAttr.localName(), EventTypeNames::drop);
+ attributeNameToEventNameMap.set(ondragstartAttr.localName(), EventTypeNames::dragstart);
+ attributeNameToEventNameMap.set(ondragAttr.localName(), EventTypeNames::drag);
+ attributeNameToEventNameMap.set(ondragendAttr.localName(), EventTypeNames::dragend);
+ attributeNameToEventNameMap.set(onselectstartAttr.localName(), EventTypeNames::selectstart);
+ attributeNameToEventNameMap.set(onsubmitAttr.localName(), EventTypeNames::submit);
+ attributeNameToEventNameMap.set(onerrorAttr.localName(), EventTypeNames::error);
+ attributeNameToEventNameMap.set(onwebkitanimationstartAttr.localName(), EventTypeNames::webkitAnimationStart);
+ attributeNameToEventNameMap.set(onwebkitanimationiterationAttr.localName(), EventTypeNames::webkitAnimationIteration);
+ attributeNameToEventNameMap.set(onwebkitanimationendAttr.localName(), EventTypeNames::webkitAnimationEnd);
+ attributeNameToEventNameMap.set(onwebkittransitionendAttr.localName(), EventTypeNames::webkitTransitionEnd);
+ attributeNameToEventNameMap.set(ontransitionendAttr.localName(), EventTypeNames::webkitTransitionEnd);
+ attributeNameToEventNameMap.set(oninputAttr.localName(), EventTypeNames::input);
+ attributeNameToEventNameMap.set(oninvalidAttr.localName(), EventTypeNames::invalid);
+ attributeNameToEventNameMap.set(ontouchstartAttr.localName(), EventTypeNames::touchstart);
+ attributeNameToEventNameMap.set(ontouchmoveAttr.localName(), EventTypeNames::touchmove);
+ attributeNameToEventNameMap.set(ontouchendAttr.localName(), EventTypeNames::touchend);
+ attributeNameToEventNameMap.set(ontouchcancelAttr.localName(), EventTypeNames::touchcancel);
+ attributeNameToEventNameMap.set(onwebkitfullscreenchangeAttr.localName(), EventTypeNames::webkitfullscreenchange);
+ attributeNameToEventNameMap.set(onwebkitfullscreenerrorAttr.localName(), EventTypeNames::webkitfullscreenerror);
+ attributeNameToEventNameMap.set(onabortAttr.localName(), EventTypeNames::abort);
+ attributeNameToEventNameMap.set(oncanplayAttr.localName(), EventTypeNames::canplay);
+ attributeNameToEventNameMap.set(oncanplaythroughAttr.localName(), EventTypeNames::canplaythrough);
+ attributeNameToEventNameMap.set(onchangeAttr.localName(), EventTypeNames::change);
+ attributeNameToEventNameMap.set(oncuechangeAttr.localName(), EventTypeNames::cuechange);
+ attributeNameToEventNameMap.set(ondurationchangeAttr.localName(), EventTypeNames::durationchange);
+ attributeNameToEventNameMap.set(onemptiedAttr.localName(), EventTypeNames::emptied);
+ attributeNameToEventNameMap.set(onendedAttr.localName(), EventTypeNames::ended);
+ attributeNameToEventNameMap.set(onloadeddataAttr.localName(), EventTypeNames::loadeddata);
+ attributeNameToEventNameMap.set(onloadedmetadataAttr.localName(), EventTypeNames::loadedmetadata);
+ attributeNameToEventNameMap.set(onloadstartAttr.localName(), EventTypeNames::loadstart);
+ attributeNameToEventNameMap.set(onpauseAttr.localName(), EventTypeNames::pause);
+ attributeNameToEventNameMap.set(onplayAttr.localName(), EventTypeNames::play);
+ attributeNameToEventNameMap.set(onplayingAttr.localName(), EventTypeNames::playing);
+ attributeNameToEventNameMap.set(onprogressAttr.localName(), EventTypeNames::progress);
+ attributeNameToEventNameMap.set(onratechangeAttr.localName(), EventTypeNames::ratechange);
+ attributeNameToEventNameMap.set(onresetAttr.localName(), EventTypeNames::reset);
+ attributeNameToEventNameMap.set(onseekedAttr.localName(), EventTypeNames::seeked);
+ attributeNameToEventNameMap.set(onseekingAttr.localName(), EventTypeNames::seeking);
+ attributeNameToEventNameMap.set(onselectAttr.localName(), EventTypeNames::select);
+ attributeNameToEventNameMap.set(onshowAttr.localName(), EventTypeNames::show);
+ attributeNameToEventNameMap.set(onstalledAttr.localName(), EventTypeNames::stalled);
+ attributeNameToEventNameMap.set(onsuspendAttr.localName(), EventTypeNames::suspend);
+ attributeNameToEventNameMap.set(ontimeupdateAttr.localName(), EventTypeNames::timeupdate);
+ attributeNameToEventNameMap.set(onvolumechangeAttr.localName(), EventTypeNames::volumechange);
+ attributeNameToEventNameMap.set(onwaitingAttr.localName(), EventTypeNames::waiting);
+ attributeNameToEventNameMap.set(onloadAttr.localName(), EventTypeNames::load);
}
return attributeNameToEventNameMap.get(attrName.localName());
@@ -305,71 +319,13 @@ void HTMLElement::parseAttribute(const QualifiedName& name, const AtomicString&
setTabIndexExplicitly(max(static_cast<int>(std::numeric_limits<short>::min()), min(tabindex, static_cast<int>(std::numeric_limits<short>::max()))));
}
} else {
- AtomicString eventName = eventNameForAttributeName(name);
+ const AtomicString& eventName = eventNameForAttributeName(name);
if (!eventName.isNull())
setAttributeEventListener(eventName, createAttributeEventListener(this, name, value));
}
}
-String HTMLElement::innerHTML() const
-{
- return createMarkup(this, ChildrenOnly);
-}
-
-String HTMLElement::outerHTML() const
-{
- return createMarkup(this);
-}
-
-void HTMLElement::setInnerHTML(const String& html, ExceptionState& es)
-{
- if (RefPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(html, this, AllowScriptingContent, es)) {
- ContainerNode* container = this;
- if (hasLocalName(templateTag))
- container = toHTMLTemplateElement(this)->content();
- replaceChildrenWithFragment(container, fragment.release(), es);
- }
-}
-
-static void mergeWithNextTextNode(PassRefPtr<Node> node, ExceptionState& es)
-{
- ASSERT(node && node->isTextNode());
- Node* next = node->nextSibling();
- if (!next || !next->isTextNode())
- return;
-
- RefPtr<Text> textNode = toText(node.get());
- RefPtr<Text> textNext = toText(next);
- textNode->appendData(textNext->data());
- if (textNext->parentNode()) // Might have been removed by mutation event.
- textNext->remove(es);
-}
-
-void HTMLElement::setOuterHTML(const String& html, ExceptionState& es)
-{
- Node* p = parentNode();
- if (!p || !p->isHTMLElement()) {
- es.throwDOMException(NoModificationAllowedError);
- return;
- }
- RefPtr<HTMLElement> parent = toHTMLElement(p);
- RefPtr<Node> prev = previousSibling();
- RefPtr<Node> next = nextSibling();
-
- RefPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(html, parent.get(), AllowScriptingContent, es);
- if (es.hadException())
- return;
-
- parent->replaceChild(fragment.release(), this, es);
- RefPtr<Node> node = next ? next->previousSibling() : 0;
- if (!es.hadException() && node && node->isTextNode())
- mergeWithNextTextNode(node.release(), es);
-
- if (!es.hadException() && prev && prev->isTextNode())
- mergeWithNextTextNode(prev.release(), es);
-}
-
-PassRefPtr<DocumentFragment> HTMLElement::textToFragment(const String& text, ExceptionState& es)
+PassRefPtr<DocumentFragment> HTMLElement::textToFragment(const String& text, ExceptionState& exceptionState)
{
RefPtr<DocumentFragment> fragment = DocumentFragment::create(document());
unsigned int i, length = text.length();
@@ -383,13 +339,13 @@ PassRefPtr<DocumentFragment> HTMLElement::textToFragment(const String& text, Exc
break;
}
- fragment->appendChild(Text::create(document(), text.substring(start, i - start)), es);
- if (es.hadException())
+ fragment->appendChild(Text::create(document(), text.substring(start, i - start)), exceptionState);
+ if (exceptionState.hadException())
return 0;
if (c == '\r' || c == '\n') {
- fragment->appendChild(HTMLBRElement::create(document()), es);
- if (es.hadException())
+ fragment->appendChild(HTMLBRElement::create(document()), exceptionState);
+ if (exceptionState.hadException())
return 0;
// Make sure \r\n doesn't result in two line breaks.
if (c == '\r' && i + 1 < length && text[i + 1] == '\n')
@@ -402,17 +358,17 @@ PassRefPtr<DocumentFragment> HTMLElement::textToFragment(const String& text, Exc
return fragment;
}
-void HTMLElement::setInnerText(const String& text, ExceptionState& es)
+void HTMLElement::setInnerText(const String& text, ExceptionState& exceptionState)
{
if (ieForbidsInsertHTML()) {
- es.throwDOMException(NoModificationAllowedError);
+ exceptionState.throwDOMException(NoModificationAllowedError, "The '" + localName() + "' element does not support text insertion.");
return;
}
if (hasLocalName(colTag) || hasLocalName(colgroupTag) || hasLocalName(framesetTag) ||
hasLocalName(headTag) || hasLocalName(htmlTag) || hasLocalName(tableTag) ||
hasLocalName(tbodyTag) || hasLocalName(tfootTag) || hasLocalName(theadTag) ||
hasLocalName(trTag)) {
- es.throwDOMException(NoModificationAllowedError);
+ exceptionState.throwDOMException(NoModificationAllowedError, "The '" + localName() + "' element does not support text insertion.");
return;
}
@@ -423,7 +379,7 @@ void HTMLElement::setInnerText(const String& text, ExceptionState& es)
removeChildren();
return;
}
- replaceChildrenWithText(this, text, es);
+ replaceChildrenWithText(this, text, exceptionState);
return;
}
@@ -433,39 +389,39 @@ void HTMLElement::setInnerText(const String& text, ExceptionState& es)
RenderObject* r = renderer();
if (r && r->style()->preserveNewline()) {
if (!text.contains('\r')) {
- replaceChildrenWithText(this, text, es);
+ replaceChildrenWithText(this, text, exceptionState);
return;
}
String textWithConsistentLineBreaks = text;
textWithConsistentLineBreaks.replace("\r\n", "\n");
textWithConsistentLineBreaks.replace('\r', '\n');
- replaceChildrenWithText(this, textWithConsistentLineBreaks, es);
+ replaceChildrenWithText(this, textWithConsistentLineBreaks, exceptionState);
return;
}
// Add text nodes and <br> elements.
- RefPtr<DocumentFragment> fragment = textToFragment(text, es);
- if (!es.hadException())
- replaceChildrenWithFragment(this, fragment.release(), es);
+ RefPtr<DocumentFragment> fragment = textToFragment(text, exceptionState);
+ if (!exceptionState.hadException())
+ replaceChildrenWithFragment(this, fragment.release(), exceptionState);
}
-void HTMLElement::setOuterText(const String &text, ExceptionState& es)
+void HTMLElement::setOuterText(const String &text, ExceptionState& exceptionState)
{
if (ieForbidsInsertHTML()) {
- es.throwDOMException(NoModificationAllowedError);
+ exceptionState.throwDOMException(NoModificationAllowedError, "The '" + localName() + "' element does not support text insertion.");
return;
}
if (hasLocalName(colTag) || hasLocalName(colgroupTag) || hasLocalName(framesetTag) ||
hasLocalName(headTag) || hasLocalName(htmlTag) || hasLocalName(tableTag) ||
hasLocalName(tbodyTag) || hasLocalName(tfootTag) || hasLocalName(theadTag) ||
hasLocalName(trTag)) {
- es.throwDOMException(NoModificationAllowedError);
+ exceptionState.throwDOMException(NoModificationAllowedError, "The '" + localName() + "' element does not support text insertion.");
return;
}
ContainerNode* parent = parentNode();
if (!parent) {
- es.throwDOMException(NoModificationAllowedError);
+ exceptionState.throwDOMException(NoModificationAllowedError, "The element has no parent.");
return;
}
@@ -475,110 +431,43 @@ void HTMLElement::setOuterText(const String &text, ExceptionState& es)
// Convert text to fragment with <br> tags instead of linebreaks if needed.
if (text.contains('\r') || text.contains('\n'))
- newChild = textToFragment(text, es);
+ newChild = textToFragment(text, exceptionState);
else
newChild = Text::create(document(), text);
+ // textToFragment might cause mutation events.
if (!this || !parentNode())
- es.throwDOMException(HierarchyRequestError);
- if (es.hadException())
- return;
- parent->replaceChild(newChild.release(), this, es);
-
- RefPtr<Node> node = next ? next->previousSibling() : 0;
- if (!es.hadException() && node && node->isTextNode())
- mergeWithNextTextNode(node.release(), es);
+ exceptionState.throwDOMException(HierarchyRequestError, "The element has no parent.");
- if (!es.hadException() && prev && prev->isTextNode())
- mergeWithNextTextNode(prev.release(), es);
-}
-
-Node* HTMLElement::insertAdjacent(const String& where, Node* newChild, ExceptionState& es)
-{
- // In Internet Explorer if the element has no parent and where is "beforeBegin" or "afterEnd",
- // a document fragment is created and the elements appended in the correct order. This document
- // fragment isn't returned anywhere.
- //
- // This is impossible for us to implement as the DOM tree does not allow for such structures,
- // Opera also appears to disallow such usage.
-
- if (equalIgnoringCase(where, "beforeBegin")) {
- if (ContainerNode* parent = this->parentNode()) {
- parent->insertBefore(newChild, this, es);
- if (!es.hadException())
- return newChild;
- }
- return 0;
- }
+ if (exceptionState.hadException())
+ return;
- if (equalIgnoringCase(where, "afterBegin")) {
- insertBefore(newChild, firstChild(), es);
- return es.hadException() ? 0 : newChild;
- }
+ parent->replaceChild(newChild.release(), this, exceptionState);
- if (equalIgnoringCase(where, "beforeEnd")) {
- appendChild(newChild, es);
- return es.hadException() ? 0 : newChild;
- }
-
- if (equalIgnoringCase(where, "afterEnd")) {
- if (ContainerNode* parent = this->parentNode()) {
- parent->insertBefore(newChild, nextSibling(), es);
- if (!es.hadException())
- return newChild;
- }
- return 0;
- }
+ RefPtr<Node> node = next ? next->previousSibling() : 0;
+ if (!exceptionState.hadException() && node && node->isTextNode())
+ mergeWithNextTextNode(node.release(), exceptionState);
- // IE throws COM Exception E_INVALIDARG; this is the best DOM exception alternative.
- es.throwDOMException(NotSupportedError);
- return 0;
+ if (!exceptionState.hadException() && prev && prev->isTextNode())
+ mergeWithNextTextNode(prev.release(), exceptionState);
}
-Element* HTMLElement::insertAdjacentElement(const String& where, Element* newChild, ExceptionState& es)
+Element* HTMLElement::insertAdjacentElement(const String& where, Element* newChild, ExceptionState& exceptionState)
{
if (!newChild) {
// IE throws COM Exception E_INVALIDARG; this is the best DOM exception alternative.
- es.throwDOMException(TypeMismatchError);
+ exceptionState.throwTypeError("The node provided is null.");
return 0;
}
- Node* returnValue = insertAdjacent(where, newChild, es);
+ Node* returnValue = insertAdjacent(where, newChild, exceptionState);
return toElement(returnValue);
}
-// Step 3 of http://www.whatwg.org/specs/web-apps/current-work/multipage/apis-in-html-documents.html#insertadjacenthtml()
-static Element* contextElementForInsertion(const String& where, Element* element, ExceptionState& es)
-{
- if (equalIgnoringCase(where, "beforeBegin") || equalIgnoringCase(where, "afterEnd")) {
- ContainerNode* parent = element->parentNode();
- if (parent && !parent->isElementNode()) {
- es.throwDOMException(NoModificationAllowedError);
- return 0;
- }
- return toElement(parent);
- }
- if (equalIgnoringCase(where, "afterBegin") || equalIgnoringCase(where, "beforeEnd"))
- return element;
- es.throwDOMException(SyntaxError);
- return 0;
-}
-
-void HTMLElement::insertAdjacentHTML(const String& where, const String& markup, ExceptionState& es)
-{
- Element* contextElement = contextElementForInsertion(where, this, es);
- if (!contextElement)
- return;
- RefPtr<DocumentFragment> fragment = createFragmentForInnerOuterHTML(markup, contextElement, AllowScriptingContent, es);
- if (!fragment)
- return;
- insertAdjacent(where, fragment.get(), es);
-}
-
-void HTMLElement::insertAdjacentText(const String& where, const String& text, ExceptionState& es)
+void HTMLElement::insertAdjacentText(const String& where, const String& text, ExceptionState& exceptionState)
{
RefPtr<Text> textNode = document().createTextNode(text);
- insertAdjacent(where, textNode.get(), es);
+ insertAdjacent(where, textNode.get(), exceptionState);
}
void HTMLElement::applyAlignmentAttributeToStyle(const AtomicString& alignment, MutableStylePropertySet* style)
@@ -631,11 +520,10 @@ bool HTMLElement::supportsSpatialNavigationFocus() const
if (!document().settings() || !document().settings()->spatialNavigationEnabled())
return false;
- EventTarget* target = const_cast<HTMLElement*>(this);
- return target->hasEventListeners(eventNames().clickEvent)
- || target->hasEventListeners(eventNames().keydownEvent)
- || target->hasEventListeners(eventNames().keypressEvent)
- || target->hasEventListeners(eventNames().keyupEvent);
+ return hasEventListeners(EventTypeNames::click)
+ || hasEventListeners(EventTypeNames::keydown)
+ || hasEventListeners(EventTypeNames::keypress)
+ || hasEventListeners(EventTypeNames::keyup);
}
bool HTMLElement::supportsFocus() const
@@ -665,7 +553,7 @@ String HTMLElement::contentEditable() const
return "inherit";
}
-void HTMLElement::setContentEditable(const String& enabled, ExceptionState& es)
+void HTMLElement::setContentEditable(const String& enabled, ExceptionState& exceptionState)
{
if (equalIgnoringCase(enabled, "true"))
setAttribute(contenteditableAttr, "true");
@@ -676,7 +564,7 @@ void HTMLElement::setContentEditable(const String& enabled, ExceptionState& es)
else if (equalIgnoringCase(enabled, "inherit"))
removeAttribute(contenteditableAttr);
else
- es.throwDOMException(SyntaxError);
+ exceptionState.throwDOMException(SyntaxError, "The value provided ('" + enabled + "') is not one of 'true', 'false', 'plaintext-only', or 'inherit'.");
}
bool HTMLElement::draggable() const
@@ -702,7 +590,7 @@ void HTMLElement::setSpellcheck(bool enable)
void HTMLElement::click()
{
- dispatchSimulatedClick(0, SendNoEvents, DoNotShowPressedLook);
+ dispatchSimulatedClick(0, SendNoEvents);
}
void HTMLElement::accessKeyAction(bool sendMouseEvents)
@@ -724,7 +612,7 @@ short HTMLElement::tabIndex() const
void HTMLElement::setTabIndex(int value)
{
- setAttribute(tabindexAttr, String::number(value));
+ setIntegralAttribute(tabindexAttr, value);
}
TranslateAttributeMode HTMLElement::translateAttributeMode() const
@@ -766,11 +654,11 @@ bool HTMLElement::rendererIsNeeded(const RenderStyle& style)
{
if (hasLocalName(noscriptTag)) {
Frame* frame = document().frame();
- if (frame && frame->script()->canExecuteScripts(NotAboutToExecuteScript))
+ if (frame && frame->script().canExecuteScripts(NotAboutToExecuteScript))
return false;
} else if (hasLocalName(noembedTag)) {
Frame* frame = document().frame();
- if (frame && frame->loader()->allowPlugins(NotAboutToInstantiatePlugin))
+ if (frame && frame->loader().allowPlugins(NotAboutToInstantiatePlugin))
return false;
}
return Element::rendererIsNeeded(style);
@@ -792,11 +680,6 @@ HTMLFormElement* HTMLElement::findFormAncestor() const
return 0;
}
-HTMLFormElement* HTMLElement::virtualForm() const
-{
- return findFormAncestor();
-}
-
static inline bool elementAffectsDirectionality(const Node* node)
{
return node->isHTMLElement() && (node->hasTagName(bdiTag) || toHTMLElement(node)->hasAttribute(dirAttr));
@@ -815,13 +698,13 @@ static void setHasDirAutoFlagRecursively(Node* firstNode, bool flag, Node* lastN
if (elementAffectsDirectionality(node)) {
if (node == lastNode)
return;
- node = NodeTraversal::nextSkippingChildren(node, firstNode);
+ node = NodeTraversal::nextSkippingChildren(*node, firstNode);
continue;
}
node->setSelfOrAncestorHasDirAutoAttribute(flag);
if (node == lastNode)
return;
- node = NodeTraversal::next(node, firstNode);
+ node = NodeTraversal::next(*node, firstNode);
}
}
@@ -848,15 +731,24 @@ TextDirection HTMLElement::directionalityIfhasDirAutoAttribute(bool& isAuto) con
return directionality();
}
+static TextDirection determineDirectionality(const String& value, bool& hasStrongDirectionality)
+{
+ TextRun run(value);
+ BidiResolver<TextRunIterator, BidiCharacterRun> bidiResolver;
+ bidiResolver.setStatus(BidiStatus(run.direction(), run.directionalOverride()));
+ bidiResolver.setPositionIgnoringNestedIsolates(TextRunIterator(&run, 0));
+ return bidiResolver.determineParagraphDirectionality(&hasStrongDirectionality);
+}
+
TextDirection HTMLElement::directionality(Node** strongDirectionalityTextNode) const
{
if (hasTagName(inputTag)) {
HTMLInputElement* inputElement = toHTMLInputElement(const_cast<HTMLElement*>(this));
bool hasStrongDirectionality;
- Unicode::Direction textDirection = inputElement->value().defaultWritingDirection(&hasStrongDirectionality);
+ TextDirection textDirection = determineDirectionality(inputElement->value(), hasStrongDirectionality);
if (strongDirectionalityTextNode)
*strongDirectionalityTextNode = hasStrongDirectionality ? inputElement : 0;
- return (textDirection == Unicode::LeftToRight) ? LTR : RTL;
+ return textDirection;
}
Node* node = firstChild();
@@ -864,29 +756,29 @@ TextDirection HTMLElement::directionality(Node** strongDirectionalityTextNode) c
// Skip bdi, script, style and text form controls.
if (equalIgnoringCase(node->nodeName(), "bdi") || node->hasTagName(scriptTag) || node->hasTagName(styleTag)
|| (node->isElementNode() && toElement(node)->isTextFormControl())) {
- node = NodeTraversal::nextSkippingChildren(node, this);
+ node = NodeTraversal::nextSkippingChildren(*node, this);
continue;
}
// Skip elements with valid dir attribute
if (node->isElementNode()) {
AtomicString dirAttributeValue = toElement(node)->fastGetAttribute(dirAttr);
- if (equalIgnoringCase(dirAttributeValue, "rtl") || equalIgnoringCase(dirAttributeValue, "ltr") || equalIgnoringCase(dirAttributeValue, "auto")) {
- node = NodeTraversal::nextSkippingChildren(node, this);
+ if (isValidDirAttribute(dirAttributeValue)) {
+ node = NodeTraversal::nextSkippingChildren(*node, this);
continue;
}
}
if (node->isTextNode()) {
bool hasStrongDirectionality;
- WTF::Unicode::Direction textDirection = node->textContent(true).defaultWritingDirection(&hasStrongDirectionality);
+ TextDirection textDirection = determineDirectionality(node->textContent(true), hasStrongDirectionality);
if (hasStrongDirectionality) {
if (strongDirectionalityTextNode)
*strongDirectionalityTextNode = node;
- return (textDirection == WTF::Unicode::LeftToRight) ? LTR : RTL;
+ return textDirection;
}
}
- node = NodeTraversal::next(node, this);
+ node = NodeTraversal::next(*node, this);
}
if (strongDirectionalityTextNode)
*strongDirectionalityTextNode = 0;
@@ -933,8 +825,8 @@ void HTMLElement::calculateAndAdjustDirectionality()
void HTMLElement::adjustDirectionalityIfNeededAfterChildrenChanged(Node* beforeChange, int childCountDelta)
{
if (document().renderer() && childCountDelta < 0) {
- Node* node = beforeChange ? NodeTraversal::nextSkippingChildren(beforeChange) : 0;
- for (int counter = 0; node && counter < childCountDelta; counter++, node = NodeTraversal::nextSkippingChildren(node)) {
+ Node* node = beforeChange ? NodeTraversal::nextSkippingChildren(*beforeChange) : 0;
+ for (int counter = 0; node && counter < childCountDelta; counter++, node = NodeTraversal::nextSkippingChildren(*node)) {
if (elementAffectsDirectionality(node))
continue;
@@ -945,9 +837,9 @@ void HTMLElement::adjustDirectionalityIfNeededAfterChildrenChanged(Node* beforeC
if (!selfOrAncestorHasDirAutoAttribute())
return;
- Node* oldMarkedNode = beforeChange ? NodeTraversal::nextSkippingChildren(beforeChange) : 0;
+ Node* oldMarkedNode = beforeChange ? NodeTraversal::nextSkippingChildren(*beforeChange) : 0;
while (oldMarkedNode && elementAffectsDirectionality(oldMarkedNode))
- oldMarkedNode = NodeTraversal::nextSkippingChildren(oldMarkedNode, this);
+ oldMarkedNode = NodeTraversal::nextSkippingChildren(*oldMarkedNode, this);
if (oldMarkedNode)
setHasDirAutoFlagRecursively(oldMarkedNode, false);
@@ -1077,7 +969,7 @@ bool HTMLElement::isInteractiveContent() const
void HTMLElement::defaultEventHandler(Event* event)
{
- if (event->type() == eventNames().keypressEvent && event->isKeyboardEvent()) {
+ if (event->type() == EventTypeNames::keypress && event->isKeyboardEvent()) {
handleKeypressEvent(toKeyboardEvent(event));
if (event->defaultHandled())
return;
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLElement.h
index 9c56c7815f4..ef4736aa9bc 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLElement.h
@@ -47,15 +47,10 @@ public:
virtual short tabIndex() const;
void setTabIndex(int);
- String innerHTML() const;
- String outerHTML() const;
- void setInnerHTML(const String&, ExceptionState&);
- void setOuterHTML(const String&, ExceptionState&);
void setInnerText(const String&, ExceptionState&);
void setOuterText(const String&, ExceptionState&);
Element* insertAdjacentElement(const String& where, Element* newChild, ExceptionState&);
- void insertAdjacentHTML(const String& where, const String& html, ExceptionState&);
void insertAdjacentText(const String& where, const String& text, ExceptionState&);
virtual bool hasCustomFocusLogic() const;
@@ -82,7 +77,7 @@ public:
virtual bool rendererIsNeeded(const RenderStyle&);
virtual RenderObject* createRenderer(RenderStyle*);
- HTMLFormElement* form() const { return virtualForm(); }
+ virtual HTMLFormElement* formOwner() const { return 0; }
HTMLFormElement* findFormAncestor() const;
@@ -118,9 +113,6 @@ private:
void mapLanguageAttributeToLocale(const AtomicString&, MutableStylePropertySet*);
- virtual HTMLFormElement* virtualForm() const;
-
- Node* insertAdjacent(const String& where, Node* newChild, ExceptionState&);
PassRefPtr<DocumentFragment> textToFragment(const String&, ExceptionState&);
void dirAttributeChanged(const AtomicString&);
@@ -130,31 +122,18 @@ private:
TranslateAttributeMode translateAttributeMode() const;
- AtomicString eventNameForAttributeName(const QualifiedName& attrName) const;
+ const AtomicString& eventNameForAttributeName(const QualifiedName& attrName) const;
void handleKeypressEvent(KeyboardEvent*);
bool supportsSpatialNavigationFocus() const;
};
-inline HTMLElement* toHTMLElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->isHTMLElement());
- return static_cast<HTMLElement*>(node);
-}
-
-inline const HTMLElement* toHTMLElement(const Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->isHTMLElement());
- return static_cast<const HTMLElement*>(node);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toHTMLElement(const HTMLElement*);
+DEFINE_NODE_TYPE_CASTS(HTMLElement, isHTMLElement());
inline HTMLElement::HTMLElement(const QualifiedName& tagName, Document& document, ConstructionType type = CreateHTMLElement)
: Element(tagName, &document, type)
{
- ASSERT(tagName.localName().impl());
+ ASSERT(!tagName.localName().isNull());
ScriptWrappable::init(this);
}
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLElement.idl b/chromium/third_party/WebKit/Source/core/html/HTMLElement.idl
index d65a413c63c..5d065681ee8 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLElement.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLElement.idl
@@ -19,35 +19,31 @@
*/
[
- CustomToV8
+ Custom=Wrap,
] interface HTMLElement : Element {
- [Reflect] attribute DOMString title;
- [Reflect] attribute DOMString lang;
- attribute boolean translate;
- [Reflect] attribute DOMString dir;
+ [Reflect] attribute DOMString title;
+ [Reflect] attribute DOMString lang;
+ attribute boolean translate;
+ [Reflect] attribute DOMString dir;
- [CustomElementCallbacks=Enable] attribute long tabIndex;
- [CustomElementCallbacks=Enable] attribute boolean draggable;
- [Reflect] attribute DOMString webkitdropzone;
- [Reflect] attribute boolean hidden;
- [Reflect] attribute DOMString accessKey;
+ [CustomElementCallbacks] attribute long tabIndex;
+ [CustomElementCallbacks] attribute boolean draggable;
+ [Reflect, TreatNullAs=NullString] attribute DOMString webkitdropzone;
+ [Reflect] attribute boolean hidden;
+ [Reflect] attribute DOMString accessKey;
// Extensions
- [TreatNullAs=NullString, CustomElementCallbacks=Enable, PerWorldBindings, ActivityLog=SetterForIsolatedWorlds, SetterRaisesException] attribute DOMString innerHTML;
- [TreatNullAs=NullString, CustomElementCallbacks=Enable, SetterRaisesException] attribute DOMString innerText;
- [TreatNullAs=NullString, CustomElementCallbacks=Enable, SetterRaisesException] attribute DOMString outerHTML;
- [TreatNullAs=NullString, CustomElementCallbacks=Enable, SetterRaisesException] attribute DOMString outerText;
+ [TreatNullAs=NullString, CustomElementCallbacks, RaisesException=Setter, MeasureAs=HTMLElementInnerText] attribute DOMString innerText;
+ [TreatNullAs=NullString, CustomElementCallbacks, RaisesException=Setter, MeasureAs=HTMLElementOuterText] attribute DOMString outerText;
- [RaisesException, CustomElementCallbacks=Enable, MeasureAs=InsertAdjacentElement] Element insertAdjacentElement([Default=Undefined] optional DOMString where,
+ [RaisesException, CustomElementCallbacks, MeasureAs=InsertAdjacentElement] Element insertAdjacentElement([Default=Undefined] optional DOMString where,
[Default=Undefined] optional Element element);
- [CustomElementCallbacks=Enable, RaisesException] void insertAdjacentHTML([Default=Undefined] optional DOMString where,
- [Default=Undefined] optional DOMString html);
[RaisesException, MeasureAs=InsertAdjacentText] void insertAdjacentText([Default=Undefined] optional DOMString where,
[Default=Undefined] optional DOMString text);
- [EnabledAtRuntime=IMEAPI] readonly attribute InputMethodContext inputMethodContext;
+ [RuntimeEnabled=IMEAPI] readonly attribute InputMethodContext inputMethodContext;
- [TreatNullAs=NullString, CustomElementCallbacks=Enable, SetterRaisesException] attribute DOMString contentEditable;
+ [CustomElementCallbacks, RaisesException=Setter] attribute DOMString contentEditable;
readonly attribute boolean isContentEditable;
attribute boolean spellcheck;
@@ -55,3 +51,4 @@
void click();
};
+HTMLElement implements GlobalEventHandlers;
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLEmbedElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLEmbedElement.cpp
index 5bdc27c3654..c6bde0181e1 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLEmbedElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLEmbedElement.cpp
@@ -27,6 +27,7 @@
#include "CSSPropertyNames.h"
#include "HTMLNames.h"
#include "core/dom/Attribute.h"
+#include "core/dom/shadow/ShadowRoot.h"
#include "core/html/HTMLImageLoader.h"
#include "core/html/HTMLObjectElement.h"
#include "core/html/PluginDocument.h"
@@ -38,21 +39,17 @@ namespace WebCore {
using namespace HTMLNames;
-inline HTMLEmbedElement::HTMLEmbedElement(const QualifiedName& tagName, Document& document, bool createdByParser)
- : HTMLPlugInImageElement(tagName, document, createdByParser, ShouldPreferPlugInsForImages)
+inline HTMLEmbedElement::HTMLEmbedElement(Document& document, bool createdByParser)
+ : HTMLPlugInElement(embedTag, document, createdByParser, ShouldPreferPlugInsForImages)
{
- ASSERT(hasTagName(embedTag));
ScriptWrappable::init(this);
}
-PassRefPtr<HTMLEmbedElement> HTMLEmbedElement::create(const QualifiedName& tagName, Document& document, bool createdByParser)
+PassRefPtr<HTMLEmbedElement> HTMLEmbedElement::create(Document& document, bool createdByParser)
{
- return adoptRef(new HTMLEmbedElement(tagName, document, createdByParser));
-}
-
-PassRefPtr<HTMLEmbedElement> HTMLEmbedElement::create(Document& document)
-{
- return create(embedTag, document, false);
+ RefPtr<HTMLEmbedElement> element = adoptRef(new HTMLEmbedElement(document, createdByParser));
+ element->ensureUserAgentShadowRoot();
+ return element.release();
}
static inline RenderWidget* findWidgetRenderer(const Node* n)
@@ -77,7 +74,7 @@ bool HTMLEmbedElement::isPresentationAttribute(const QualifiedName& name) const
{
if (name == hiddenAttr)
return true;
- return HTMLPlugInImageElement::isPresentationAttribute(name);
+ return HTMLPlugInElement::isPresentationAttribute(name);
}
void HTMLEmbedElement::collectStyleForPresentationAttribute(const QualifiedName& name, const AtomicString& value, MutableStylePropertySet* style)
@@ -87,8 +84,9 @@ void HTMLEmbedElement::collectStyleForPresentationAttribute(const QualifiedName&
addPropertyToPresentationAttributeStyle(style, CSSPropertyWidth, 0, CSSPrimitiveValue::CSS_PX);
addPropertyToPresentationAttributeStyle(style, CSSPropertyHeight, 0, CSSPrimitiveValue::CSS_PX);
}
- } else
- HTMLPlugInImageElement::collectStyleForPresentationAttribute(name, value, style);
+ } else {
+ HTMLPlugInElement::collectStyleForPresentationAttribute(name, value, style);
+ }
}
void HTMLEmbedElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
@@ -98,17 +96,18 @@ void HTMLEmbedElement::parseAttribute(const QualifiedName& name, const AtomicStr
size_t pos = m_serviceType.find(";");
if (pos != kNotFound)
m_serviceType = m_serviceType.left(pos);
- } else if (name == codeAttr)
+ } else if (name == codeAttr) {
m_url = stripLeadingAndTrailingHTMLSpaces(value);
- else if (name == srcAttr) {
+ } else if (name == srcAttr) {
m_url = stripLeadingAndTrailingHTMLSpaces(value);
if (renderer() && isImageType()) {
if (!m_imageLoader)
m_imageLoader = adoptPtr(new HTMLImageLoader(this));
m_imageLoader->updateFromElementIgnoringPreviousError();
}
- } else
- HTMLPlugInImageElement::parseAttribute(name, value);
+ } else {
+ HTMLPlugInElement::parseAttribute(name, value);
+ }
}
void HTMLEmbedElement::parametersForPlugin(Vector<String>& paramNames, Vector<String>& paramValues)
@@ -124,8 +123,8 @@ void HTMLEmbedElement::parametersForPlugin(Vector<String>& paramNames, Vector<St
}
// FIXME: This should be unified with HTMLObjectElement::updateWidget and
-// moved down into HTMLPluginImageElement.cpp
-void HTMLEmbedElement::updateWidget(PluginCreationOption pluginCreationOption)
+// moved down into HTMLPluginElement.cpp
+void HTMLEmbedElement::updateWidgetInternal()
{
ASSERT(!renderEmbeddedObject()->showsUnavailablePluginIndicator());
ASSERT(needsWidgetUpdate());
@@ -139,15 +138,6 @@ void HTMLEmbedElement::updateWidget(PluginCreationOption pluginCreationOption)
if (!allowedToLoadFrameURL(m_url))
return;
- // FIXME: It's sadness that we have this special case here.
- // See http://trac.webkit.org/changeset/25128 and
- // plugins/netscape-plugin-setwindow-size.html
- if (pluginCreationOption == CreateOnlyNonNetscapePlugins && wouldLoadAsNetscapePlugin(m_url, m_serviceType)) {
- // Ensure updateWidget() is called again during layout to create the Netscape plug-in.
- setNeedsWidgetUpdate(true);
- return;
- }
-
// FIXME: These should be joined into a PluginParameters class.
Vector<String> paramNames;
Vector<String> paramValues;
@@ -174,7 +164,7 @@ void HTMLEmbedElement::updateWidget(PluginCreationOption pluginCreationOption)
bool HTMLEmbedElement::rendererIsNeeded(const RenderStyle& style)
{
if (isImageType())
- return HTMLPlugInImageElement::rendererIsNeeded(style);
+ return HTMLPlugInElement::rendererIsNeeded(style);
Frame* frame = document().frame();
if (!frame)
@@ -190,12 +180,12 @@ bool HTMLEmbedElement::rendererIsNeeded(const RenderStyle& style)
return false;
}
}
- return HTMLPlugInImageElement::rendererIsNeeded(style);
+ return HTMLPlugInElement::rendererIsNeeded(style);
}
bool HTMLEmbedElement::isURLAttribute(const Attribute& attribute) const
{
- return attribute.name() == srcAttr || HTMLPlugInImageElement::isURLAttribute(attribute);
+ return attribute.name() == srcAttr || HTMLPlugInElement::isURLAttribute(attribute);
}
const AtomicString HTMLEmbedElement::imageSourceURL() const
@@ -205,7 +195,7 @@ const AtomicString HTMLEmbedElement::imageSourceURL() const
void HTMLEmbedElement::addSubresourceAttributeURLs(ListHashSet<KURL>& urls) const
{
- HTMLPlugInImageElement::addSubresourceAttributeURLs(urls);
+ HTMLPlugInElement::addSubresourceAttributeURLs(urls);
addSubresourceURL(urls, document().completeURL(getAttribute(srcAttr)));
}
@@ -215,4 +205,14 @@ bool HTMLEmbedElement::isInteractiveContent() const
return true;
}
+bool HTMLEmbedElement::isExposed() const
+{
+ // http://www.whatwg.org/specs/web-apps/current-work/#exposed
+ for (Node* ancestor = parentNode(); ancestor; ancestor = ancestor->parentNode()) {
+ if (ancestor->hasTagName(objectTag) && toHTMLObjectElement(ancestor)->isExposed())
+ return false;
+ }
+ return true;
+}
+
}
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLEmbedElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLEmbedElement.h
index abe1e581700..8107fd188f2 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLEmbedElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLEmbedElement.h
@@ -23,17 +23,18 @@
#ifndef HTMLEmbedElement_h
#define HTMLEmbedElement_h
-#include "core/html/HTMLPlugInImageElement.h"
+#include "core/html/HTMLPlugInElement.h"
namespace WebCore {
-class HTMLEmbedElement FINAL : public HTMLPlugInImageElement {
+class HTMLEmbedElement FINAL : public HTMLPlugInElement {
public:
- static PassRefPtr<HTMLEmbedElement> create(Document&);
- static PassRefPtr<HTMLEmbedElement> create(const QualifiedName&, Document&, bool createdByParser);
+ static PassRefPtr<HTMLEmbedElement> create(Document&, bool createdByParser = false);
+
+ bool isExposed() const;
private:
- HTMLEmbedElement(const QualifiedName&, Document&, bool createdByParser);
+ HTMLEmbedElement(Document&, bool createdByParser);
virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
@@ -46,7 +47,7 @@ private:
virtual RenderWidget* existingRenderWidget() const OVERRIDE;
- virtual void updateWidget(PluginCreationOption);
+ virtual void updateWidgetInternal() OVERRIDE;
virtual void addSubresourceAttributeURLs(ListHashSet<KURL>&) const;
@@ -56,6 +57,8 @@ private:
virtual bool isInteractiveContent() const OVERRIDE;
};
+DEFINE_NODE_TYPE_CASTS(HTMLEmbedElement, hasTagName(HTMLNames::embedTag));
+
}
#endif
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLEmbedElement.idl b/chromium/third_party/WebKit/Source/core/html/HTMLEmbedElement.idl
index 98dc8549e9f..74524f3ec05 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLEmbedElement.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLEmbedElement.idl
@@ -19,19 +19,18 @@
*/
[
- CustomLegacyCall,
+ Custom=LegacyCallAsFunction,
] interface HTMLEmbedElement : HTMLElement {
-[Reflect] attribute DOMString align;
-[Reflect] attribute DOMString height;
-[Reflect] attribute DOMString name;
-[Reflect, URL] attribute DOMString src;
-[Reflect] attribute DOMString type;
-[Reflect] attribute DOMString width;
-[Custom, NotEnumerable] getter boolean (unsigned long index);
-[Custom] setter boolean (unsigned long index, Node value);
-[Custom, NotEnumerable] getter Node (DOMString name);
-[Custom] setter Node (DOMString name, Node value);
+ [Reflect] attribute DOMString align;
+ [Reflect] attribute DOMString height;
+ [Reflect] attribute DOMString name;
+ [Reflect, URL, PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute DOMString src;
+ [Reflect] attribute DOMString type;
+ [Reflect] attribute DOMString width;
+ [Custom, NotEnumerable] getter boolean (unsigned long index);
+ [Custom] setter boolean (unsigned long index, Node value);
+ [Custom, NotEnumerable] getter Node (DOMString name);
+ [Custom] setter Node (DOMString name, Node value);
-[CheckSecurityForNode, RaisesException] SVGDocument getSVGDocument();
+ [CheckSecurity=Node, RaisesException] SVGDocument getSVGDocument();
};
-
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLFieldSetElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLFieldSetElement.cpp
index 66ef5374076..bf568d1417c 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLFieldSetElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLFieldSetElement.cpp
@@ -37,22 +37,21 @@ namespace WebCore {
using namespace HTMLNames;
-inline HTMLFieldSetElement::HTMLFieldSetElement(const QualifiedName& tagName, Document& document, HTMLFormElement* form)
- : HTMLFormControlElement(tagName, document, form)
+inline HTMLFieldSetElement::HTMLFieldSetElement(Document& document, HTMLFormElement* form)
+ : HTMLFormControlElement(fieldsetTag, document, form)
, m_documentVersion(0)
{
- ASSERT(hasTagName(fieldsetTag));
ScriptWrappable::init(this);
}
-PassRefPtr<HTMLFieldSetElement> HTMLFieldSetElement::create(const QualifiedName& tagName, Document& document, HTMLFormElement* form)
+PassRefPtr<HTMLFieldSetElement> HTMLFieldSetElement::create(Document& document, HTMLFormElement* form)
{
- return adoptRef(new HTMLFieldSetElement(tagName, document, form));
+ return adoptRef(new HTMLFieldSetElement(document, form));
}
-void HTMLFieldSetElement::invalidateDisabledStateUnder(Element* base)
+void HTMLFieldSetElement::invalidateDisabledStateUnder(Element& base)
{
- for (Element* element = ElementTraversal::firstWithin(base); element; element = ElementTraversal::next(element, base)) {
+ for (Element* element = ElementTraversal::firstWithin(base); element; element = ElementTraversal::next(*element, &base)) {
if (element->isFormControlElement())
toHTMLFormControlElement(element)->ancestorDisabledStateWasChanged();
}
@@ -62,15 +61,15 @@ void HTMLFieldSetElement::disabledAttributeChanged()
{
// This element must be updated before the style of nodes in its subtree gets recalculated.
HTMLFormControlElement::disabledAttributeChanged();
- invalidateDisabledStateUnder(this);
+ invalidateDisabledStateUnder(*this);
}
void HTMLFieldSetElement::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
{
HTMLFormControlElement::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
- for (Element* element = ElementTraversal::firstWithin(this); element; element = ElementTraversal::nextSkippingChildren(element, this)) {
+ for (Element* element = ElementTraversal::firstWithin(*this); element; element = ElementTraversal::nextSkippingChildren(*element, this)) {
if (element->hasTagName(legendTag))
- invalidateDisabledStateUnder(element);
+ invalidateDisabledStateUnder(*element);
}
}
@@ -92,7 +91,7 @@ RenderObject* HTMLFieldSetElement::createRenderer(RenderStyle*)
HTMLLegendElement* HTMLFieldSetElement::legend() const
{
- for (Element* child = ElementTraversal::firstWithin(this); child; child = ElementTraversal::nextSkippingChildren(child, this)) {
+ for (Element* child = ElementTraversal::firstWithin(*this); child; child = ElementTraversal::nextSkippingChildren(*child, this)) {
if (child->hasTagName(legendTag))
return toHTMLLegendElement(child);
}
@@ -114,7 +113,7 @@ void HTMLFieldSetElement::refreshElementsIfNeeded() const
m_associatedElements.clear();
- for (Element* element = ElementTraversal::firstWithin(this); element; element = ElementTraversal::next(element, this)) {
+ for (Element* element = ElementTraversal::firstWithin(*this); element; element = ElementTraversal::next(*element, this)) {
if (element->hasTagName(objectTag)) {
m_associatedElements.append(toHTMLObjectElement(element));
continue;
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLFieldSetElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLFieldSetElement.h
index 2d522f2498e..e0835449cdf 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLFieldSetElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLFieldSetElement.h
@@ -33,7 +33,7 @@ class HTMLCollection;
class HTMLFieldSetElement FINAL : public HTMLFormControlElement {
public:
- static PassRefPtr<HTMLFieldSetElement> create(const QualifiedName&, Document&, HTMLFormElement*);
+ static PassRefPtr<HTMLFieldSetElement> create(Document&, HTMLFormElement*);
HTMLLegendElement* legend() const;
PassRefPtr<HTMLCollection> elements();
@@ -45,7 +45,7 @@ protected:
virtual void disabledAttributeChanged() OVERRIDE;
private:
- HTMLFieldSetElement(const QualifiedName&, Document&, HTMLFormElement*);
+ HTMLFieldSetElement(Document&, HTMLFormElement*);
virtual bool isEnumeratable() const { return true; }
virtual bool supportsFocus() const;
@@ -55,7 +55,7 @@ private:
virtual void childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta) OVERRIDE;
virtual bool areAuthorShadowsAllowed() const OVERRIDE { return false; }
- static void invalidateDisabledStateUnder(Element*);
+ static void invalidateDisabledStateUnder(Element&);
void refreshElementsIfNeeded() const;
mutable Vector<FormAssociatedElement*> m_associatedElements;
@@ -63,11 +63,7 @@ private:
mutable uint64_t m_documentVersion;
};
-inline HTMLFieldSetElement* toHTMLFieldSetElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::fieldsetTag));
- return static_cast<HTMLFieldSetElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(HTMLFieldSetElement, hasTagName(HTMLNames::fieldsetTag));
} // namespace
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLFieldSetElement.idl b/chromium/third_party/WebKit/Source/core/html/HTMLFieldSetElement.idl
index 4e77da909ef..94d9f0f60aa 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLFieldSetElement.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLFieldSetElement.idl
@@ -19,7 +19,7 @@
interface HTMLFieldSetElement : HTMLElement {
[Reflect] attribute boolean disabled;
- readonly attribute HTMLFormElement form;
+ [ImplementedAs=formOwner] readonly attribute HTMLFormElement form;
[Reflect] attribute DOMString name;
readonly attribute DOMString type;
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLFontElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLFontElement.cpp
index 928b1e9afd6..853eae4a786 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLFontElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLFontElement.cpp
@@ -38,16 +38,15 @@ namespace WebCore {
using namespace HTMLNames;
-HTMLFontElement::HTMLFontElement(const QualifiedName& tagName, Document& document)
- : HTMLElement(tagName, document)
+HTMLFontElement::HTMLFontElement(Document& document)
+ : HTMLElement(fontTag, document)
{
- ASSERT(hasTagName(fontTag));
ScriptWrappable::init(this);
}
-PassRefPtr<HTMLFontElement> HTMLFontElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<HTMLFontElement> HTMLFontElement::create(Document& document)
{
- return adoptRef(new HTMLFontElement(tagName, document));
+ return adoptRef(new HTMLFontElement(document));
}
// http://www.whatwg.org/specs/web-apps/current-work/multipage/rendering.html#fonts-and-colors
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLFontElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLFontElement.h
index 7c85f6f3031..229c5c94896 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLFontElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLFontElement.h
@@ -30,12 +30,12 @@ namespace WebCore {
class HTMLFontElement FINAL : public HTMLElement {
public:
- static PassRefPtr<HTMLFontElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<HTMLFontElement> create(Document&);
static bool cssValueFromFontSizeNumber(const String&, CSSValueID&);
private:
- HTMLFontElement(const QualifiedName&, Document&);
+ explicit HTMLFontElement(Document&);
virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
virtual void collectStyleForPresentationAttribute(const QualifiedName&, const AtomicString&, MutableStylePropertySet*) OVERRIDE;
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLFontElement.idl b/chromium/third_party/WebKit/Source/core/html/HTMLFontElement.idl
index d2da3a9eb94..c0c56d4814a 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLFontElement.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLFontElement.idl
@@ -18,8 +18,7 @@
*/
interface HTMLFontElement : HTMLElement {
- [Reflect] attribute DOMString color;
+ [Reflect, TreatNullAs=NullString] attribute DOMString color;
[Reflect] attribute DOMString face;
[Reflect] attribute DOMString size;
};
-
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLFormControlElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLFormControlElement.cpp
index 7cdf855570d..4c68907eaf4 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLFormControlElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLFormControlElement.cpp
@@ -25,9 +25,9 @@
#include "config.h"
#include "core/html/HTMLFormControlElement.h"
-#include "core/dom/Event.h"
-#include "core/dom/EventNames.h"
#include "core/dom/PostAttachCallbacks.h"
+#include "core/events/Event.h"
+#include "core/events/ThreadLocalEventNames.h"
#include "core/html/HTMLFieldSetElement.h"
#include "core/html/HTMLFormElement.h"
#include "core/html/HTMLInputElement.h"
@@ -35,7 +35,7 @@
#include "core/html/HTMLTextAreaElement.h"
#include "core/html/ValidityState.h"
#include "core/html/forms/ValidationMessage.h"
-#include "core/page/UseCounter.h"
+#include "core/frame/UseCounter.h"
#include "core/rendering/RenderBox.h"
#include "core/rendering/RenderTheme.h"
#include "wtf/Vector.h"
@@ -48,6 +48,7 @@ using namespace std;
HTMLFormControlElement::HTMLFormControlElement(const QualifiedName& tagName, Document& document, HTMLFormElement* form)
: LabelableElement(tagName, document)
, m_disabled(false)
+ , m_isAutofilled(false)
, m_isReadOnly(false)
, m_isRequired(false)
, m_valueMatchesRenderer(false)
@@ -77,7 +78,7 @@ String HTMLFormControlElement::formEnctype() const
return FormSubmission::Attributes::parseEncodingType(formEnctypeAttr);
}
-void HTMLFormControlElement::setFormEnctype(const String& value)
+void HTMLFormControlElement::setFormEnctype(const AtomicString& value)
{
setAttribute(formenctypeAttr, value);
}
@@ -90,7 +91,7 @@ String HTMLFormControlElement::formMethod() const
return FormSubmission::Attributes::methodString(FormSubmission::Attributes::parseMethodType(formMethodAttr));
}
-void HTMLFormControlElement::setFormMethod(const String& value)
+void HTMLFormControlElement::setFormMethod(const AtomicString& value)
{
setAttribute(formmethodAttr, value);
}
@@ -121,11 +122,17 @@ void HTMLFormControlElement::ancestorDisabledStateWasChanged()
disabledAttributeChanged();
}
+void HTMLFormControlElement::reset()
+{
+ setAutofilled(false);
+ resetImpl();
+}
+
void HTMLFormControlElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
{
if (name == formAttr) {
formAttributeChanged();
- UseCounter::count(&document(), UseCounter::FormAttribute);
+ UseCounter::count(document(), UseCounter::FormAttribute);
} else if (name == disabledAttr) {
bool oldDisabled = m_disabled;
m_disabled = !value.isNull();
@@ -145,10 +152,10 @@ void HTMLFormControlElement::parseAttribute(const QualifiedName& name, const Ato
m_isRequired = !value.isNull();
if (wasRequired != m_isRequired)
requiredAttributeChanged();
- UseCounter::count(&document(), UseCounter::RequiredAttribute);
+ UseCounter::count(document(), UseCounter::RequiredAttribute);
} else if (name == autofocusAttr) {
HTMLElement::parseAttribute(name, value);
- UseCounter::count(&document(), UseCounter::AutoFocusAttribute);
+ UseCounter::count(document(), UseCounter::AutoFocusAttribute);
} else
HTMLElement::parseAttribute(name, value);
}
@@ -174,62 +181,76 @@ void HTMLFormControlElement::requiredAttributeChanged()
setNeedsStyleRecalc();
}
-static bool shouldAutofocus(HTMLFormControlElement* element)
+static void focusPostAttach(Node* element)
{
- if (!element->fastHasAttribute(autofocusAttr))
- return false;
- if (!element->renderer())
- return false;
- if (element->document().ignoreAutofocus())
- return false;
- if (element->document().isSandboxed(SandboxAutomaticFeatures)) {
- // FIXME: This message should be moved off the console once a solution to https://bugs.webkit.org/show_bug.cgi?id=103274 exists.
- element->document().addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, "Blocked autofocusing on a form control because the form's frame is sandboxed and the 'allow-scripts' permission is not set.");
- return false;
- }
- if (element->hasAutofocused())
+ toElement(element)->focus();
+ element->deref();
+}
+
+bool HTMLFormControlElement::isAutofocusable() const
+{
+ if (!fastHasAttribute(autofocusAttr))
return false;
// FIXME: Should this set of hasTagName checks be replaced by a
// virtual member function?
- if (element->hasTagName(inputTag))
- return !toHTMLInputElement(element)->isInputTypeHidden();
- if (element->hasTagName(selectTag))
+ if (hasTagName(inputTag))
+ return !toHTMLInputElement(this)->isInputTypeHidden();
+ if (hasTagName(selectTag))
return true;
- if (element->hasTagName(keygenTag))
+ if (hasTagName(keygenTag))
return true;
- if (element->hasTagName(buttonTag))
+ if (hasTagName(buttonTag))
return true;
- if (isHTMLTextAreaElement(element))
+ if (isHTMLTextAreaElement(this))
return true;
-
return false;
}
-static void focusPostAttach(Node* element)
+void HTMLFormControlElement::setAutofilled(bool autofilled)
{
- toElement(element)->focus();
- element->deref();
+ if (autofilled == m_isAutofilled)
+ return;
+
+ m_isAutofilled = autofilled;
+ setNeedsStyleRecalc();
+}
+
+static bool shouldAutofocusOnAttach(const HTMLFormControlElement* element)
+{
+ if (!element->isAutofocusable())
+ return false;
+ if (element->hasAutofocused())
+ return false;
+ if (element->document().isSandboxed(SandboxAutomaticFeatures)) {
+ // FIXME: This message should be moved off the console once a solution to https://bugs.webkit.org/show_bug.cgi?id=103274 exists.
+ element->document().addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, "Blocked autofocusing on a form control because the form's frame is sandboxed and the 'allow-scripts' permission is not set.");
+ return false;
+ }
+
+ return true;
}
void HTMLFormControlElement::attach(const AttachContext& context)
{
HTMLElement::attach(context);
+ if (!renderer())
+ return;
+
// The call to updateFromElement() needs to go after the call through
// to the base class's attach() because that can sometimes do a close
// on the renderer.
- if (renderer())
- renderer()->updateFromElement();
+ renderer()->updateFromElement();
- if (shouldAutofocus(this)) {
+ if (shouldAutofocusOnAttach(this)) {
setAutofocused();
ref();
PostAttachCallbacks::queueCallback(focusPostAttach, this);
}
}
-void HTMLFormControlElement::didMoveToNewDocument(Document* oldDocument)
+void HTMLFormControlElement::didMoveToNewDocument(Document& oldDocument)
{
FormAssociatedElement::didMoveToNewDocument(oldDocument);
HTMLElement::didMoveToNewDocument(oldDocument);
@@ -276,6 +297,11 @@ void HTMLFormControlElement::dispatchFormControlInputEvent()
HTMLElement::dispatchInputEvent();
}
+HTMLFormElement* HTMLFormControlElement::formOwner() const
+{
+ return FormAssociatedElement::form();
+}
+
bool HTMLFormControlElement::isDisabledFormControl() const
{
if (m_disabled)
@@ -291,6 +317,11 @@ bool HTMLFormControlElement::isRequired() const
return m_isRequired;
}
+String HTMLFormControlElement::resultForDialogSubmit()
+{
+ return fastGetAttribute(valueAttr);
+}
+
static void updateFromElementCallback(Node* node)
{
ASSERT_ARG(node, node->isElementNode());
@@ -338,7 +369,7 @@ bool HTMLFormControlElement::shouldHaveFocusAppearance() const
void HTMLFormControlElement::willCallDefaultEventHandler(const Event& event)
{
- if (!event.isKeyboardEvent() || event.type() != eventNames().keydownEvent)
+ if (!event.isKeyboardEvent() || event.type() != EventTypeNames::keydown)
return;
if (!m_wasFocusedByMouse)
return;
@@ -428,9 +459,9 @@ bool HTMLFormControlElement::checkValidity(Vector<RefPtr<FormAssociatedElement>
return false;
// An event handler can deref this object.
RefPtr<HTMLFormControlElement> protector(this);
- RefPtr<Document> originalDocument(&document());
- bool needsDefaultAction = dispatchEvent(Event::createCancelable(eventNames().invalidEvent));
- if (needsDefaultAction && unhandledInvalidControls && inDocument() && originalDocument == &document())
+ RefPtr<Document> originalDocument(document());
+ bool needsDefaultAction = dispatchEvent(Event::createCancelable(EventTypeNames::invalid));
+ if (needsDefaultAction && unhandledInvalidControls && inDocument() && originalDocument == document())
unhandledInvalidControls->append(this);
return false;
}
@@ -439,13 +470,13 @@ bool HTMLFormControlElement::isValidFormControlElement()
{
// If the following assertion fails, setNeedsValidityCheck() is not called
// correctly when something which changes validity is updated.
- ASSERT(m_isValid == validity()->valid());
+ ASSERT(m_isValid == valid());
return m_isValid;
}
void HTMLFormControlElement::setNeedsValidityCheck()
{
- bool newIsValid = validity()->valid();
+ bool newIsValid = valid();
if (willValidate() && newIsValid != m_isValid) {
// Update style for pseudo classes such as :valid :invalid.
setNeedsStyleRecalc();
@@ -472,9 +503,9 @@ void HTMLFormControlElement::dispatchBlurEvent(Element* newFocusedElement)
hideVisibleValidationMessage();
}
-HTMLFormElement* HTMLFormControlElement::virtualForm() const
+bool HTMLFormControlElement::isSuccessfulSubmitButton() const
{
- return FormAssociatedElement::form();
+ return canBeSuccessfulSubmitButton() && !isDisabledFormControl();
}
bool HTMLFormControlElement::isDefaultButtonForForm() const
@@ -491,4 +522,15 @@ HTMLFormControlElement* HTMLFormControlElement::enclosingFormControlElement(Node
return 0;
}
+String HTMLFormControlElement::nameForAutofill() const
+{
+ String fullName = name();
+ String trimmedName = fullName.stripWhiteSpace();
+ if (!trimmedName.isEmpty())
+ return trimmedName;
+ fullName = getIdAttribute();
+ trimmedName = fullName.stripWhiteSpace();
+ return trimmedName;
+}
+
} // namespace Webcore
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLFormControlElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLFormControlElement.h
index 2189f95a3b0..bb5cdd8c8a2 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLFormControlElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLFormControlElement.h
@@ -43,17 +43,15 @@ class HTMLFormControlElement : public LabelableElement, public FormAssociatedEle
public:
virtual ~HTMLFormControlElement();
- HTMLFormElement* form() const { return FormAssociatedElement::form(); }
-
String formEnctype() const;
- void setFormEnctype(const String&);
+ void setFormEnctype(const AtomicString&);
String formMethod() const;
- void setFormMethod(const String&);
+ void setFormMethod(const AtomicString&);
bool formNoValidate() const;
void ancestorDisabledStateWasChanged();
- virtual void reset() { }
+ void reset();
virtual bool formControlValueMatchesRenderer() const { return m_valueMatchesRenderer; }
virtual void setFormControlValueMatchesRenderer(bool b) { m_valueMatchesRenderer = b; }
@@ -64,6 +62,8 @@ public:
virtual void dispatchFormControlChangeEvent();
virtual void dispatchFormControlInputEvent();
+ virtual HTMLFormElement* formOwner() const OVERRIDE;
+
virtual bool isDisabledFormControl() const OVERRIDE;
virtual bool isEnumeratable() const { return false; }
@@ -79,8 +79,10 @@ public:
// Override in derived classes to get the encoded name=value pair for submitting.
// Return true for a successful control (see HTML4-17.13.2).
virtual bool appendFormData(FormDataList&, bool) { return false; }
+ virtual String resultForDialogSubmit();
- virtual bool isSuccessfulSubmitButton() const { return false; }
+ virtual bool canBeSuccessfulSubmitButton() const { return false; }
+ bool isSuccessfulSubmitButton() const;
virtual bool isActivatedSubmit() const { return false; }
virtual void setActivatedSubmit(bool) { }
@@ -97,11 +99,17 @@ public:
bool isReadOnly() const { return m_isReadOnly; }
bool isDisabledOrReadOnly() const { return isDisabledFormControl() || m_isReadOnly; }
- bool hasAutofocused() { return m_hasAutofocused; }
+ bool hasAutofocused() const { return m_hasAutofocused; }
void setAutofocused() { m_hasAutofocused = true; }
+ bool isAutofocusable() const;
+
+ bool isAutofilled() const { return m_isAutofilled; }
+ void setAutofilled(bool = true);
static HTMLFormControlElement* enclosingFormControlElement(Node*);
+ String nameForAutofill() const;
+
using Node::ref;
using Node::deref;
@@ -114,7 +122,7 @@ protected:
virtual void attach(const AttachContext& = AttachContext()) OVERRIDE;
virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
virtual void removedFrom(ContainerNode*) OVERRIDE;
- virtual void didMoveToNewDocument(Document* oldDocument) OVERRIDE;
+ virtual void didMoveToNewDocument(Document& oldDocument) OVERRIDE;
virtual bool supportsFocus() const OVERRIDE;
virtual bool isKeyboardFocusable() const OVERRIDE;
@@ -130,6 +138,8 @@ protected:
void setNeedsWillValidateCheck();
virtual bool recalcWillValidate() const;
+ virtual void resetImpl() { }
+
private:
virtual void refFormAssociatedElement() { ref(); }
virtual void derefFormAssociatedElement() { deref(); }
@@ -139,13 +149,13 @@ private:
virtual short tabIndex() const;
- virtual HTMLFormElement* virtualForm() const;
virtual bool isDefaultButtonForForm() const;
virtual bool isValidFormControlElement();
void updateAncestorDisabledState() const;
OwnPtr<ValidationMessage> m_validationMessage;
bool m_disabled : 1;
+ bool m_isAutofilled : 1;
bool m_isReadOnly : 1;
bool m_isRequired : 1;
bool m_valueMatchesRenderer : 1;
@@ -161,7 +171,7 @@ private:
mutable bool m_willValidateInitialized: 1;
mutable bool m_willValidate : 1;
- // Cache of validity()->valid().
+ // Cache of valid().
// But "candidate for constraint validation" doesn't affect m_isValid.
bool m_isValid : 1;
@@ -170,23 +180,13 @@ private:
bool m_hasAutofocused : 1;
};
-inline HTMLFormControlElement* toHTMLFormControlElement(Node* node)
+inline bool isHTMLFormControlElement(const Node& node)
{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || (node->isElementNode() && toElement(node)->isFormControlElement()));
- return static_cast<HTMLFormControlElement*>(node);
+ return node.isElementNode() && toElement(node).isFormControlElement();
}
-inline HTMLFormControlElement* toHTMLFormControlElement(FormAssociatedElement* control)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!control || control->isFormControlElement());
- return static_cast<HTMLFormControlElement*>(control);
-}
-
-inline const HTMLFormControlElement* toHTMLFormControlElement(const FormAssociatedElement* control)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!control || control->isFormControlElement());
- return static_cast<const HTMLFormControlElement*>(control);
-}
+DEFINE_NODE_TYPE_CASTS_WITH_FUNCTION(HTMLFormControlElement);
+DEFINE_TYPE_CASTS(HTMLFormControlElement, FormAssociatedElement, control, control->isFormControlElement(), control.isFormControlElement());
} // namespace
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLFormControlElementWithState.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLFormControlElementWithState.cpp
index 0b62d225155..1508d798f18 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLFormControlElementWithState.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLFormControlElementWithState.cpp
@@ -29,7 +29,7 @@
#include "core/html/forms/FormController.h"
#include "core/page/Chrome.h"
#include "core/page/ChromeClient.h"
-#include "core/page/Frame.h"
+#include "core/frame/Frame.h"
#include "core/page/Page.h"
namespace WebCore {
@@ -77,7 +77,7 @@ void HTMLFormControlElementWithState::notifyFormStateChanged()
bool HTMLFormControlElementWithState::shouldSaveAndRestoreFormControlState() const
{
// We don't save/restore control state in a form with autocomplete=off.
- return attached() && shouldAutocomplete();
+ return inActiveDocument() && shouldAutocomplete();
}
FormControlState HTMLFormControlElementWithState::saveFormControlState() const
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLFormControlElementWithState.h b/chromium/third_party/WebKit/Source/core/html/HTMLFormControlElementWithState.h
index 57bd66a368c..0328920e53a 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLFormControlElementWithState.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLFormControlElementWithState.h
@@ -52,11 +52,7 @@ protected:
virtual bool isFormControlElementWithState() const OVERRIDE;
};
-inline HTMLFormControlElementWithState* toHTMLFormControlElementWithState(FormAssociatedElement* element)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!element || element->isFormControlElementWithState());
- return static_cast<HTMLFormControlElementWithState*>(element);
-}
+DEFINE_TYPE_CASTS(HTMLFormControlElementWithState, FormAssociatedElement, control, control->isFormControlElementWithState(), control.isFormControlElementWithState());
} // namespace
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLFormControlsCollection.h b/chromium/third_party/WebKit/Source/core/html/HTMLFormControlsCollection.h
index eafaaea4681..45b286ccb78 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLFormControlsCollection.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLFormControlsCollection.h
@@ -36,7 +36,7 @@ class QualifiedName;
// This class is just a big hack to find form elements even in malformed HTML elements.
// The famous <table><tr><form><td> problem.
-class HTMLFormControlsCollection : public HTMLCollection {
+class HTMLFormControlsCollection FINAL : public HTMLCollection {
public:
static PassRefPtr<HTMLFormControlsCollection> create(Node*, CollectionType);
@@ -46,9 +46,9 @@ public:
void namedGetter(const AtomicString& name, bool&, RefPtr<RadioNodeList>&, bool&, RefPtr<Node>&);
private:
- HTMLFormControlsCollection(Node*);
+ explicit HTMLFormControlsCollection(Node*);
- virtual void updateNameCache() const;
+ virtual void updateNameCache() const OVERRIDE;
const Vector<FormAssociatedElement*>& formControlElements() const;
const Vector<HTMLImageElement*>& formImageElements() const;
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLFormControlsCollection.idl b/chromium/third_party/WebKit/Source/core/html/HTMLFormControlsCollection.idl
index e7b757e0f9b..f483a675a31 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLFormControlsCollection.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLFormControlsCollection.idl
@@ -19,8 +19,8 @@
*/
[
- GenerateIsReachable=ownerNode,
- DependentLifetime
+ DependentLifetime,
+ GenerateVisitDOMWrapper=ownerNode,
] interface HTMLFormControlsCollection : HTMLCollection {
[ImplementedAs=item] getter Node(unsigned long index);
[Custom] Node namedItem([Default=Undefined] optional DOMString name);
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLFormElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLFormElement.cpp
index 9c2bb0b7735..0e5cc98d302 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLFormElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLFormElement.cpp
@@ -25,30 +25,33 @@
#include "config.h"
#include "core/html/HTMLFormElement.h"
+#include <limits>
#include "HTMLNames.h"
#include "bindings/v8/ScriptController.h"
#include "bindings/v8/ScriptEventListener.h"
#include "core/dom/Attribute.h"
-#include "core/dom/AutocompleteErrorEvent.h"
#include "core/dom/Document.h"
#include "core/dom/ElementTraversal.h"
-#include "core/dom/Event.h"
-#include "core/dom/EventNames.h"
#include "core/dom/NamedNodesCollection.h"
+#include "core/events/AutocompleteErrorEvent.h"
+#include "core/events/Event.h"
+#include "core/events/ScopedEventQueue.h"
+#include "core/events/ThreadLocalEventNames.h"
#include "core/html/HTMLCollection.h"
+#include "core/html/HTMLDialogElement.h"
#include "core/html/HTMLImageElement.h"
#include "core/html/HTMLInputElement.h"
#include "core/html/HTMLObjectElement.h"
#include "core/html/HTMLTableElement.h"
#include "core/html/forms/FormController.h"
-#include "core/loader/FormState.h"
#include "core/loader/FrameLoader.h"
#include "core/loader/FrameLoaderClient.h"
-#include "core/page/ContentSecurityPolicy.h"
-#include "core/page/Frame.h"
-#include "core/page/UseCounter.h"
+#include "core/frame/ContentSecurityPolicy.h"
+#include "core/frame/DOMWindow.h"
+#include "core/frame/Frame.h"
+#include "core/frame/UseCounter.h"
#include "core/rendering/RenderTextControl.h"
-#include <limits>
+#include "platform/UserGestureIndicator.h"
using namespace std;
@@ -56,8 +59,8 @@ namespace WebCore {
using namespace HTMLNames;
-HTMLFormElement::HTMLFormElement(const QualifiedName& tagName, Document& document)
- : HTMLElement(tagName, document)
+HTMLFormElement::HTMLFormElement(Document& document)
+ : HTMLElement(formTag, document)
, m_associatedElementsBeforeIndex(0)
, m_associatedElementsAfterIndex(0)
, m_wasUserSubmitted(false)
@@ -67,20 +70,13 @@ HTMLFormElement::HTMLFormElement(const QualifiedName& tagName, Document& documen
, m_wasDemoted(false)
, m_requestAutocompleteTimer(this, &HTMLFormElement::requestAutocompleteTimerFired)
{
- ASSERT(hasTagName(formTag));
ScriptWrappable::init(this);
}
PassRefPtr<HTMLFormElement> HTMLFormElement::create(Document& document)
{
- UseCounter::count(&document, UseCounter::FormElement);
- return adoptRef(new HTMLFormElement(formTag, document));
-}
-
-PassRefPtr<HTMLFormElement> HTMLFormElement::create(const QualifiedName& tagName, Document& document)
-{
- UseCounter::count(&document, UseCounter::FormElement);
- return adoptRef(new HTMLFormElement(tagName, document));
+ UseCounter::count(document, UseCounter::FormElement);
+ return adoptRef(new HTMLFormElement(document));
}
HTMLFormElement::~HTMLFormElement()
@@ -153,7 +149,7 @@ void HTMLFormElement::removedFrom(ContainerNode* insertionPoint)
void HTMLFormElement::handleLocalEvents(Event* event)
{
Node* targetNode = event->target()->toNode();
- if (event->eventPhase() != Event::CAPTURING_PHASE && targetNode && targetNode != this && (event->type() == eventNames().submitEvent || event->type() == eventNames().resetEvent)) {
+ if (event->eventPhase() != Event::CAPTURING_PHASE && targetNode && targetNode != this && (event->type() == EventTypeNames::submit || event->type() == EventTypeNames::reset)) {
event->stopPropagation();
return;
}
@@ -177,18 +173,27 @@ Node* HTMLFormElement::item(unsigned index)
void HTMLFormElement::submitImplicitly(Event* event, bool fromImplicitSubmissionTrigger)
{
int submissionTriggerCount = 0;
+ bool seenDefaultButton = false;
for (unsigned i = 0; i < m_associatedElements.size(); ++i) {
FormAssociatedElement* formAssociatedElement = m_associatedElements[i];
if (!formAssociatedElement->isFormControlElement())
continue;
HTMLFormControlElement* control = toHTMLFormControlElement(formAssociatedElement);
- if (control->isSuccessfulSubmitButton()) {
- if (control->renderer()) {
- control->dispatchSimulatedClick(event);
+ if (!seenDefaultButton && control->canBeSuccessfulSubmitButton()) {
+ if (fromImplicitSubmissionTrigger)
+ seenDefaultButton = true;
+ if (control->isSuccessfulSubmitButton()) {
+ if (control->renderer()) {
+ control->dispatchSimulatedClick(event);
+ return;
+ }
+ } else if (fromImplicitSubmissionTrigger) {
+ // Default (submit) button is not activated; no implicit submission.
return;
}
- } else if (control->canTriggerImplicitSubmission())
+ } else if (control->canTriggerImplicitSubmission()) {
++submissionTriggerCount;
+ }
}
if (fromImplicitSubmissionTrigger && submissionTriggerCount == 1)
prepareForSubmission(event);
@@ -276,9 +281,9 @@ bool HTMLFormElement::prepareForSubmission(Event* event)
StringPairVector controlNamesAndValues;
getTextFieldValues(controlNamesAndValues);
RefPtr<FormState> formState = FormState::create(this, controlNamesAndValues, &document(), NotSubmittedByJavaScript);
- frame->loader()->client()->dispatchWillSendSubmitEvent(formState.release());
+ frame->loader().client()->dispatchWillSendSubmitEvent(formState.release());
- if (dispatchEvent(Event::createCancelableBubble(eventNames().submitEvent)))
+ if (dispatchEvent(Event::createCancelableBubble(EventTypeNames::submit)))
m_shouldSubmit = true;
m_isSubmittingOrPreparingForSubmission = false;
@@ -296,7 +301,7 @@ void HTMLFormElement::submit()
void HTMLFormElement::submitFromJavaScript()
{
- submit(0, false, ScriptController::processingUserGesture(), SubmittedByJavaScript);
+ submit(0, false, UserGestureIndicator::processingUserGesture(), SubmittedByJavaScript);
}
void HTMLFormElement::getTextFieldValues(StringPairVector& fieldNamesAndValues) const
@@ -318,6 +323,16 @@ void HTMLFormElement::getTextFieldValues(StringPairVector& fieldNamesAndValues)
}
}
+void HTMLFormElement::submitDialog(PassRefPtr<FormSubmission> formSubmission)
+{
+ for (Node* node = this; node; node = node->parentOrShadowHostNode()) {
+ if (node->hasTagName(dialogTag)) {
+ toHTMLDialogElement(node)->closeDialog(formSubmission->result());
+ return;
+ }
+ }
+}
+
void HTMLFormElement::submit(Event* event, bool activateSubmitButton, bool processingUserGesture, FormSubmissionTrigger formSubmissionTrigger)
{
FrameView* view = document().view();
@@ -352,7 +367,12 @@ void HTMLFormElement::submit(Event* event, bool activateSubmitButton, bool proce
if (needButtonActivation && firstSuccessfulSubmitButton)
firstSuccessfulSubmitButton->setActivatedSubmit(true);
- scheduleFormSubmission(FormSubmission::create(this, m_attributes, event, formSubmissionTrigger));
+ RefPtr<FormSubmission> formSubmission = FormSubmission::create(this, m_attributes, event, formSubmissionTrigger);
+ EventQueueScope scopeForDialogClose; // Delay dispatching 'close' to dialog until done submitting.
+ if (formSubmission->method() == FormSubmission::DialogMethod)
+ submitDialog(formSubmission.release());
+ else
+ scheduleFormSubmission(formSubmission.release());
if (needButtonActivation && firstSuccessfulSubmitButton)
firstSuccessfulSubmitButton->setActivatedSubmit(false);
@@ -377,13 +397,25 @@ void HTMLFormElement::scheduleFormSubmission(PassRefPtr<FormSubmission> submissi
if (protocolIsJavaScript(submission->action())) {
if (!document().contentSecurityPolicy()->allowFormAction(KURL(submission->action())))
return;
- document().frame()->script()->executeScriptIfJavaScriptURL(submission->action());
+ document().frame()->script().executeScriptIfJavaScriptURL(submission->action());
return;
}
- submission->setReferrer(document().frame()->loader()->outgoingReferrer());
- submission->setOrigin(document().frame()->loader()->outgoingOrigin());
- document().frame()->navigationScheduler()->scheduleFormSubmission(submission);
+ Frame* targetFrame = document().frame()->loader().findFrameForNavigation(submission->target(), submission->state()->sourceDocument());
+ if (!targetFrame) {
+ if (!DOMWindow::allowPopUp(document().frame()) && !UserGestureIndicator::processingUserGesture())
+ return;
+ targetFrame = document().frame();
+ } else {
+ submission->clearTarget();
+ }
+ if (!targetFrame->page())
+ return;
+
+ submission->setReferrer(document().outgoingReferrer());
+ submission->setOrigin(document().outgoingOrigin());
+
+ targetFrame->navigationScheduler().scheduleFormSubmission(submission);
}
void HTMLFormElement::reset()
@@ -394,7 +426,7 @@ void HTMLFormElement::reset()
m_isInResetFunction = true;
- if (!dispatchEvent(Event::createCancelableBubble(eventNames().resetEvent))) {
+ if (!dispatchEvent(Event::createCancelableBubble(EventTypeNames::reset))) {
m_isInResetFunction = false;
return;
}
@@ -413,7 +445,7 @@ void HTMLFormElement::requestAutocomplete()
if (!frame)
return;
- if (!shouldAutocomplete() || !ScriptController::processingUserGesture()) {
+ if (!shouldAutocomplete() || !UserGestureIndicator::processingUserGesture()) {
finishRequestAutocomplete(AutocompleteResultErrorDisabled);
return;
}
@@ -421,14 +453,14 @@ void HTMLFormElement::requestAutocomplete()
StringPairVector controlNamesAndValues;
getTextFieldValues(controlNamesAndValues);
RefPtr<FormState> formState = FormState::create(this, controlNamesAndValues, &document(), SubmittedByJavaScript);
- frame->loader()->client()->didRequestAutocomplete(formState.release());
+ frame->loader().client()->didRequestAutocomplete(formState.release());
}
void HTMLFormElement::finishRequestAutocomplete(AutocompleteResult result)
{
RefPtr<Event> event;
if (result == AutocompleteResultSuccess)
- event = Event::create(eventNames().autocompleteEvent);
+ event = Event::create(EventTypeNames::autocomplete);
else if (result == AutocompleteResultErrorDisabled)
event = AutocompleteErrorEvent::create("disabled");
else if (result == AutocompleteResultErrorCancel)
@@ -465,9 +497,9 @@ void HTMLFormElement::parseAttribute(const QualifiedName& name, const AtomicStri
else if (name == accept_charsetAttr)
m_attributes.setAcceptCharset(value);
else if (name == onautocompleteAttr)
- setAttributeEventListener(eventNames().autocompleteEvent, createAttributeEventListener(this, name, value));
+ setAttributeEventListener(EventTypeNames::autocomplete, createAttributeEventListener(this, name, value));
else if (name == onautocompleteerrorAttr)
- setAttributeEventListener(eventNames().autocompleteerrorEvent, createAttributeEventListener(this, name, value));
+ setAttributeEventListener(EventTypeNames::autocompleteerror, createAttributeEventListener(this, name, value));
else
HTMLElement::parseAttribute(name, value);
}
@@ -515,20 +547,20 @@ unsigned HTMLFormElement::formElementIndexWithFormAttribute(Element* element, un
return left + 1;
}
-unsigned HTMLFormElement::formElementIndex(FormAssociatedElement* associatedElement)
+unsigned HTMLFormElement::formElementIndex(FormAssociatedElement& associatedElement)
{
- HTMLElement* associatedHTMLElement = toHTMLElement(associatedElement);
+ HTMLElement& associatedHTMLElement = toHTMLElement(associatedElement);
// Treats separately the case where this element has the form attribute
// for performance consideration.
- if (associatedHTMLElement->fastHasAttribute(formAttr)) {
- unsigned short position = compareDocumentPosition(associatedHTMLElement);
+ if (associatedHTMLElement.fastHasAttribute(formAttr)) {
+ unsigned short position = compareDocumentPosition(&associatedHTMLElement);
if (position & DOCUMENT_POSITION_PRECEDING) {
++m_associatedElementsBeforeIndex;
++m_associatedElementsAfterIndex;
- return HTMLFormElement::formElementIndexWithFormAttribute(associatedHTMLElement, 0, m_associatedElementsBeforeIndex - 1);
+ return HTMLFormElement::formElementIndexWithFormAttribute(&associatedHTMLElement, 0, m_associatedElementsBeforeIndex - 1);
}
if (position & DOCUMENT_POSITION_FOLLOWING && !(position & DOCUMENT_POSITION_CONTAINED_BY))
- return HTMLFormElement::formElementIndexWithFormAttribute(associatedHTMLElement, m_associatedElementsAfterIndex, m_associatedElements.size());
+ return HTMLFormElement::formElementIndexWithFormAttribute(&associatedHTMLElement, m_associatedElementsAfterIndex, m_associatedElements.size());
}
// Check for the special case where this element is the very last thing in
@@ -537,14 +569,14 @@ unsigned HTMLFormElement::formElementIndex(FormAssociatedElement* associatedElem
// that says "add this form element to the end of the array".
if (ElementTraversal::next(associatedHTMLElement, this)) {
unsigned i = m_associatedElementsBeforeIndex;
- for (Element* element = this; element; element = ElementTraversal::next(element, this)) {
+ for (Element* element = this; element; element = ElementTraversal::next(*element, this)) {
if (element == associatedHTMLElement) {
++m_associatedElementsAfterIndex;
return i;
}
if (!element->isFormControlElement() && !element->hasTagName(objectTag))
continue;
- if (!element->isHTMLElement() || toHTMLElement(element)->form() != this)
+ if (!element->isHTMLElement() || toHTMLElement(element)->formOwner() != this)
continue;
++i;
}
@@ -552,9 +584,9 @@ unsigned HTMLFormElement::formElementIndex(FormAssociatedElement* associatedElem
return m_associatedElementsAfterIndex++;
}
-void HTMLFormElement::registerFormElement(FormAssociatedElement* e)
+void HTMLFormElement::registerFormElement(FormAssociatedElement& e)
{
- m_associatedElements.insert(formElementIndex(e), e);
+ m_associatedElements.insert(formElementIndex(e), &e);
}
void HTMLFormElement::removeFormElement(FormAssociatedElement* e)
@@ -609,17 +641,17 @@ bool HTMLFormElement::noValidate() const
// FIXME: This function should be removed because it does not do the same thing as the
// JavaScript binding for action, which treats action as a URL attribute. Last time I
// (Darin Adler) removed this, someone added it back, so I am leaving it in for now.
-String HTMLFormElement::action() const
+const AtomicString& HTMLFormElement::action() const
{
return getAttribute(actionAttr);
}
-void HTMLFormElement::setAction(const String &value)
+void HTMLFormElement::setAction(const AtomicString& value)
{
setAttribute(actionAttr, value);
}
-void HTMLFormElement::setEnctype(const String &value)
+void HTMLFormElement::setEnctype(const AtomicString& value)
{
setAttribute(enctypeAttr, value);
}
@@ -629,7 +661,7 @@ String HTMLFormElement::method() const
return FormSubmission::Attributes::methodString(m_attributes.method());
}
-void HTMLFormElement::setMethod(const String &value)
+void HTMLFormElement::setMethod(const AtomicString& value)
{
setAttribute(methodAttr, value);
}
@@ -681,7 +713,7 @@ bool HTMLFormElement::checkInvalidControlsAndCollectUnhandled(Vector<RefPtr<Form
for (unsigned i = 0; i < elements.size(); ++i) {
if (elements[i]->form() == this && elements[i]->isFormControlElement()) {
HTMLFormControlElement* control = toHTMLFormControlElement(elements[i].get());
- if (!control->checkValidity(unhandledInvalidControls, dispatchEvents) && control->form() == this)
+ if (!control->checkValidity(unhandledInvalidControls, dispatchEvents) && control->formOwner() == this)
hasInvalidControls = true;
}
}
@@ -692,11 +724,11 @@ Node* HTMLFormElement::elementFromPastNamesMap(const AtomicString& pastName) con
{
if (pastName.isEmpty() || !m_pastNamesMap)
return 0;
- Node* node = m_pastNamesMap->get(pastName.impl());
+ Node* node = m_pastNamesMap->get(pastName);
#if !ASSERT_DISABLED
if (!node)
return 0;
- ASSERT_WITH_SECURITY_IMPLICATION(toHTMLElement(node)->form() == this);
+ ASSERT_WITH_SECURITY_IMPLICATION(toHTMLElement(node)->formOwner() == this);
if (node->hasTagName(imgTag)) {
ASSERT_WITH_SECURITY_IMPLICATION(m_imageElements.find(node) != kNotFound);
} else if (node->hasTagName(objectTag)) {
@@ -714,7 +746,7 @@ void HTMLFormElement::addToPastNamesMap(Node* element, const AtomicString& pastN
return;
if (!m_pastNamesMap)
m_pastNamesMap = adoptPtr(new PastNamesMap);
- m_pastNamesMap->set(pastName.impl(), element);
+ m_pastNamesMap->set(pastName, element);
}
void HTMLFormElement::removeFromPastNamesMap(HTMLElement& element)
@@ -723,7 +755,7 @@ void HTMLFormElement::removeFromPastNamesMap(HTMLElement& element)
return;
PastNamesMap::iterator end = m_pastNamesMap->end();
for (PastNamesMap::iterator it = m_pastNamesMap->begin(); it != end; ++it) {
- if (it->value.get() == &element) {
+ if (it->value == &element) {
it->value = 0;
// Keep looping. Single element can have multiple names.
}
@@ -790,7 +822,7 @@ void HTMLFormElement::anonymousNamedGetter(const AtomicString& name, bool& retur
void HTMLFormElement::setDemoted(bool demoted)
{
if (demoted)
- UseCounter::count(&document(), UseCounter::DemotedFormElement);
+ UseCounter::count(document(), UseCounter::DemotedFormElement);
m_wasDemoted = demoted;
}
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLFormElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLFormElement.h
index f733e71d0ac..d2f118e08c3 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLFormElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLFormElement.h
@@ -47,7 +47,6 @@ class HTMLInputElement;
class HTMLFormElement FINAL : public HTMLElement {
public:
static PassRefPtr<HTMLFormElement> create(Document&);
- static PassRefPtr<HTMLFormElement> create(const QualifiedName&, Document&);
virtual ~HTMLFormElement();
PassRefPtr<HTMLCollection> elements();
@@ -57,15 +56,15 @@ public:
Node* item(unsigned index);
String enctype() const { return m_attributes.encodingType(); }
- void setEnctype(const String&);
+ void setEnctype(const AtomicString&);
String encoding() const { return m_attributes.encodingType(); }
- void setEncoding(const String& value) { setEnctype(value); }
+ void setEncoding(const AtomicString& value) { setEnctype(value); }
bool shouldAutocomplete() const;
// FIXME: Should rename these two functions to say "form control" or "form-associated element" instead of "form element".
- void registerFormElement(FormAssociatedElement*);
+ void registerFormElement(FormAssociatedElement&);
void removeFormElement(FormAssociatedElement*);
void registerImgElement(HTMLImageElement*);
@@ -85,14 +84,11 @@ public:
bool noValidate() const;
- String acceptCharset() const { return m_attributes.acceptCharset(); }
- void setAcceptCharset(const String&);
-
- String action() const;
- void setAction(const String&);
+ const AtomicString& action() const;
+ void setAction(const AtomicString&);
String method() const;
- void setMethod(const String&);
+ void setMethod(const AtomicString&);
virtual String target() const;
@@ -125,7 +121,7 @@ public:
void anonymousNamedGetter(const AtomicString& name, bool&, RefPtr<NodeList>&, bool&, RefPtr<Node>&);
private:
- HTMLFormElement(const QualifiedName&, Document&);
+ explicit HTMLFormElement(Document&);
virtual bool rendererIsNeeded(const RenderStyle&);
virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
@@ -141,12 +137,13 @@ private:
virtual void copyNonAttributePropertiesFromElement(const Element&) OVERRIDE;
+ void submitDialog(PassRefPtr<FormSubmission>);
void submit(Event*, bool activateSubmitButton, bool processingUserGesture, FormSubmissionTrigger);
void scheduleFormSubmission(PassRefPtr<FormSubmission>);
unsigned formElementIndexWithFormAttribute(Element*, unsigned rangeStart, unsigned rangeEnd);
- unsigned formElementIndex(FormAssociatedElement*);
+ unsigned formElementIndex(FormAssociatedElement&);
// Returns true if the submission should proceed.
bool validateInteractively(Event*);
@@ -160,7 +157,7 @@ private:
void addToPastNamesMap(Node*, const AtomicString& pastName);
void removeFromPastNamesMap(HTMLElement&);
- typedef HashMap<AtomicString, RefPtr<Node> > PastNamesMap;
+ typedef HashMap<AtomicString, Node*> PastNamesMap;
FormSubmission::Attributes m_attributes;
OwnPtr<PastNamesMap> m_pastNamesMap;
@@ -186,11 +183,7 @@ private:
Timer<HTMLFormElement> m_requestAutocompleteTimer;
};
-inline HTMLFormElement* toHTMLFormElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::formTag));
- return static_cast<HTMLFormElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(HTMLFormElement, hasTagName(HTMLNames::formTag));
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLFormElement.idl b/chromium/third_party/WebKit/Source/core/html/HTMLFormElement.idl
index f1bcb0efa2b..6ba5f418c01 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLFormElement.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLFormElement.idl
@@ -20,11 +20,11 @@
interface HTMLFormElement : HTMLElement {
[Reflect=accept_charset] attribute DOMString acceptCharset;
- [Reflect, URL] attribute DOMString action;
+ [Reflect, URL, PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute DOMString action;
[Reflect] attribute DOMString autocomplete;
- [TreatNullAs=NullString, CustomElementCallbacks=Enable] attribute DOMString enctype;
- [TreatNullAs=NullString, CustomElementCallbacks=Enable] attribute DOMString encoding;
- [TreatNullAs=NullString, CustomElementCallbacks=Enable] attribute DOMString method;
+ [CustomElementCallbacks] attribute DOMString enctype;
+ [CustomElementCallbacks] attribute DOMString encoding;
+ [CustomElementCallbacks] attribute DOMString method;
[Reflect] attribute DOMString name;
[Reflect] attribute boolean noValidate;
[Reflect] attribute DOMString target;
@@ -34,11 +34,11 @@ interface HTMLFormElement : HTMLElement {
[ImplementedAs=item] getter Node(unsigned long index);
[ImplementedAs=anonymousNamedGetter, OverrideBuiltins, NotEnumerable] getter (NodeList or Node)(DOMString name);
- [ImplementedAs=submitFromJavaScript] void submit();
- [CustomElementCallbacks=Enable] void reset();
+ [ImplementedAs=submitFromJavaScript, PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] void submit();
+ [CustomElementCallbacks] void reset();
boolean checkValidity();
- [EnabledAtRuntime=RequestAutocomplete] void requestAutocomplete();
- [EnabledAtRuntime=RequestAutocomplete, NotEnumerable] attribute EventHandler onautocomplete;
- [EnabledAtRuntime=RequestAutocomplete, NotEnumerable] attribute EventHandler onautocompleteerror;
+ [RuntimeEnabled=RequestAutocomplete] void requestAutocomplete();
+ [RuntimeEnabled=RequestAutocomplete] attribute EventHandler onautocomplete;
+ [RuntimeEnabled=RequestAutocomplete] attribute EventHandler onautocompleteerror;
};
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLFrameElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLFrameElement.cpp
index 38e82ca8dfd..218a2216167 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLFrameElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLFrameElement.cpp
@@ -32,18 +32,17 @@ namespace WebCore {
using namespace HTMLNames;
-inline HTMLFrameElement::HTMLFrameElement(const QualifiedName& tagName, Document& document)
- : HTMLFrameElementBase(tagName, document)
+inline HTMLFrameElement::HTMLFrameElement(Document& document)
+ : HTMLFrameElementBase(frameTag, document)
, m_frameBorder(true)
, m_frameBorderSet(false)
{
- ASSERT(hasTagName(frameTag));
ScriptWrappable::init(this);
}
-PassRefPtr<HTMLFrameElement> HTMLFrameElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<HTMLFrameElement> HTMLFrameElement::create(Document& document)
{
- return adoptRef(new HTMLFrameElement(tagName, document));
+ return adoptRef(new HTMLFrameElement(document));
}
bool HTMLFrameElement::rendererIsNeeded(const RenderStyle&)
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLFrameElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLFrameElement.h
index 1cd3ab065aa..72ca10399ab 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLFrameElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLFrameElement.h
@@ -30,14 +30,14 @@ namespace WebCore {
class HTMLFrameElement FINAL : public HTMLFrameElementBase {
public:
- static PassRefPtr<HTMLFrameElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<HTMLFrameElement> create(Document&);
bool hasFrameBorder() const { return m_frameBorder; }
bool noResize() const;
private:
- HTMLFrameElement(const QualifiedName&, Document&);
+ explicit HTMLFrameElement(Document&);
virtual void attach(const AttachContext& = AttachContext()) OVERRIDE;
@@ -52,11 +52,7 @@ private:
bool m_frameBorderSet;
};
-inline HTMLFrameElement* toHTMLFrameElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::frameTag));
- return static_cast<HTMLFrameElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(HTMLFrameElement, hasTagName(HTMLNames::frameTag));
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLFrameElement.idl b/chromium/third_party/WebKit/Source/core/html/HTMLFrameElement.idl
index c702fd6951d..1ab494ce552 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLFrameElement.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLFrameElement.idl
@@ -21,26 +21,24 @@
interface HTMLFrameElement : HTMLElement {
[Reflect] attribute DOMString frameBorder;
- [Reflect] attribute DOMString longDesc;
- [Reflect] attribute DOMString marginHeight;
- [Reflect] attribute DOMString marginWidth;
+ [Reflect, URL] attribute DOMString longDesc;
+ [Reflect, TreatNullAs=NullString] attribute DOMString marginHeight;
+ [Reflect, TreatNullAs=NullString] attribute DOMString marginWidth;
[Reflect] attribute DOMString name;
[Reflect] attribute boolean noResize;
[Reflect] attribute DOMString scrolling;
- [Reflect, URL] attribute DOMString src;
+ [Reflect, URL, PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute DOMString src;
// Introduced in DOM Level 2:
- [CheckSecurityForNode] readonly attribute Document contentDocument;
+ [CheckSecurity=Node] readonly attribute Document contentDocument;
// Extensions
readonly attribute Window contentWindow;
- [CheckSecurityForNode, RaisesException] SVGDocument getSVGDocument();
+ [CheckSecurity=Node, RaisesException] SVGDocument getSVGDocument();
- [TreatNullAs=NullString, CustomSetter] attribute DOMString location;
+ [TreatNullAs=NullString, Custom=Setter, MeasureAs=HTMLFrameElementLocation] attribute DOMString location;
readonly attribute long width;
readonly attribute long height;
-
};
-
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLFrameElementBase.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLFrameElementBase.cpp
index 3b9925bc9d2..fc6bfb98c35 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLFrameElementBase.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLFrameElementBase.cpp
@@ -29,12 +29,12 @@
#include "bindings/v8/ScriptEventListener.h"
#include "core/dom/Attribute.h"
#include "core/dom/Document.h"
-#include "core/dom/EventNames.h"
+#include "core/events/ThreadLocalEventNames.h"
#include "core/html/parser/HTMLParserIdioms.h"
#include "core/loader/FrameLoader.h"
#include "core/page/FocusController.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameView.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
#include "core/page/Page.h"
#include "core/rendering/RenderPart.h"
@@ -94,7 +94,7 @@ void HTMLFrameElementBase::openURL(bool lockBackForwardList)
return;
if (!contentFrame() || scriptURL.isEmpty())
return;
- contentFrame()->script()->executeScriptIfJavaScriptURL(scriptURL);
+ contentFrame()->script().executeScriptIfJavaScriptURL(scriptURL);
}
void HTMLFrameElementBase::parseAttribute(const QualifiedName& name, const AtomicString& value)
@@ -126,10 +126,10 @@ void HTMLFrameElementBase::parseAttribute(const QualifiedName& name, const Atomi
m_scrolling = ScrollbarAlwaysOff;
// FIXME: If we are already attached, this has no effect.
} else if (name == onbeforeloadAttr)
- setAttributeEventListener(eventNames().beforeloadEvent, createAttributeEventListener(this, name, value));
+ setAttributeEventListener(EventTypeNames::beforeload, createAttributeEventListener(this, name, value));
else if (name == onbeforeunloadAttr) {
// FIXME: should <frame> elements have beforeunload handlers?
- setAttributeEventListener(eventNames().beforeunloadEvent, createAttributeEventListener(this, name, value));
+ setAttributeEventListener(EventTypeNames::beforeunload, createAttributeEventListener(this, name, value));
} else
HTMLFrameOwnerElement::parseAttribute(name, value);
}
@@ -153,7 +153,7 @@ void HTMLFrameElementBase::didNotifySubtreeInsertionsToDocument()
if (!document().frame())
return;
- if (!SubframeLoadingDisabler::canLoadFrame(this))
+ if (!SubframeLoadingDisabler::canLoadFrame(*this))
return;
setNameAndOpenURL();
@@ -202,7 +202,8 @@ void HTMLFrameElementBase::setFocus(bool received)
bool HTMLFrameElementBase::isURLAttribute(const Attribute& attribute) const
{
- return attribute.name() == srcAttr || HTMLFrameOwnerElement::isURLAttribute(attribute);
+ return attribute.name() == longdescAttr || attribute.name() == srcAttr
+ || HTMLFrameOwnerElement::isURLAttribute(attribute);
}
bool HTMLFrameElementBase::isHTMLContentAttribute(const Attribute& attribute) const
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLFrameElementBase.h b/chromium/third_party/WebKit/Source/core/html/HTMLFrameElementBase.h
index a384652c5e9..9352e4e7056 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLFrameElementBase.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLFrameElementBase.h
@@ -25,7 +25,7 @@
#define HTMLFrameElementBase_h
#include "core/html/HTMLFrameOwnerElement.h"
-#include "core/platform/ScrollTypes.h"
+#include "platform/scroll/ScrollTypes.h"
namespace WebCore {
@@ -77,12 +77,13 @@ private:
int m_marginHeight;
};
-inline HTMLFrameElementBase* toHTMLFrameElementBase(Node* node)
+inline bool isHTMLFrameElementBase(const Node& node)
{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || (node->isElementNode() && toElement(node)->isFrameElementBase()));
- return static_cast<HTMLFrameElementBase*>(node);
+ return node.isElementNode() && toElement(node).isFrameElementBase();
}
+DEFINE_NODE_TYPE_CASTS_WITH_FUNCTION(HTMLFrameElementBase);
+
} // namespace WebCore
#endif // HTMLFrameElementBase_h
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLFrameOwnerElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLFrameOwnerElement.cpp
index dbcbd5ec74c..aaa73ff224c 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLFrameOwnerElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLFrameOwnerElement.cpp
@@ -21,16 +21,17 @@
#include "config.h"
#include "core/html/HTMLFrameOwnerElement.h"
+#include "bindings/v8/ExceptionMessages.h"
#include "bindings/v8/ExceptionState.h"
#include "core/dom/ExceptionCode.h"
#include "core/loader/FrameLoader.h"
#include "core/loader/FrameLoaderClient.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameView.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
#include "core/rendering/RenderPart.h"
#include "core/svg/SVGDocument.h"
-#include "weborigin/SecurityOrigin.h"
-#include "weborigin/SecurityPolicy.h"
+#include "platform/weborigin/SecurityOrigin.h"
+#include "platform/weborigin/SecurityPolicy.h"
namespace WebCore {
@@ -50,14 +51,13 @@ RenderPart* HTMLFrameOwnerElement::renderPart() const
return toRenderPart(renderer());
}
-void HTMLFrameOwnerElement::setContentFrame(Frame* frame)
+void HTMLFrameOwnerElement::setContentFrame(Frame& frame)
{
// Make sure we will not end up with two frames referencing the same owner element.
ASSERT(!m_contentFrame || m_contentFrame->ownerElement() != this);
- ASSERT(frame);
// Disconnected frames should not be allowed to load.
ASSERT(inDocument());
- m_contentFrame = frame;
+ m_contentFrame = &frame;
for (ContainerNode* node = this; node; node = node->parentOrShadowHostNode())
node->incrementConnectedSubframeCount();
@@ -82,7 +82,7 @@ void HTMLFrameOwnerElement::disconnectContentFrame()
// see if this behavior is really needed as Gecko does not allow this.
if (Frame* frame = contentFrame()) {
RefPtr<Frame> protect(frame);
- frame->loader()->frameDetached();
+ frame->loader().frameDetached();
frame->disconnectOwnerElement();
}
}
@@ -113,13 +113,11 @@ bool HTMLFrameOwnerElement::isKeyboardFocusable() const
return m_contentFrame && HTMLElement::isKeyboardFocusable();
}
-SVGDocument* HTMLFrameOwnerElement::getSVGDocument(ExceptionState& es) const
+SVGDocument* HTMLFrameOwnerElement::getSVGDocument(ExceptionState& exceptionState) const
{
Document* doc = contentDocument();
if (doc && doc->isSVGDocument())
return toSVGDocument(doc);
- // Spec: http://www.w3.org/TR/SVG/struct.html#InterfaceGetSVGDocument
- es.throwDOMException(NotSupportedError);
return 0;
}
@@ -127,7 +125,7 @@ bool HTMLFrameOwnerElement::loadOrRedirectSubframe(const KURL& url, const Atomic
{
RefPtr<Frame> parentFrame = document().frame();
if (contentFrame()) {
- contentFrame()->navigationScheduler()->scheduleLocationChange(document().securityOrigin(), url.string(), parentFrame->loader()->outgoingReferrer(), lockBackForwardList);
+ contentFrame()->navigationScheduler().scheduleLocationChange(&document(), url.string(), document().outgoingReferrer(), lockBackForwardList);
return true;
}
@@ -136,14 +134,14 @@ bool HTMLFrameOwnerElement::loadOrRedirectSubframe(const KURL& url, const Atomic
return false;
}
- if (!SubframeLoadingDisabler::canLoadFrame(this))
+ if (!SubframeLoadingDisabler::canLoadFrame(*this))
return false;
- String referrer = SecurityPolicy::generateReferrerHeader(document().referrerPolicy(), url, parentFrame->loader()->outgoingReferrer());
- RefPtr<Frame> childFrame = parentFrame->loader()->client()->createFrame(url, frameName, referrer, this);
+ String referrer = SecurityPolicy::generateReferrerHeader(document().referrerPolicy(), url, document().outgoingReferrer());
+ RefPtr<Frame> childFrame = parentFrame->loader().client()->createFrame(url, frameName, referrer, this);
if (!childFrame) {
- parentFrame->loader()->checkCompleted();
+ parentFrame->loader().checkCompleted();
return false;
}
@@ -153,7 +151,7 @@ bool HTMLFrameOwnerElement::loadOrRedirectSubframe(const KURL& url, const Atomic
// actually completed below. (Note that we set m_isComplete to false even for synchronous
// loads, so that checkCompleted() below won't bail early.)
// FIXME: Can we remove this entirely? m_isComplete normally gets set to false when a load is committed.
- childFrame->loader()->started();
+ childFrame->loader().started();
RenderObject* renderObject = renderer();
FrameView* view = childFrame->view();
@@ -169,8 +167,8 @@ bool HTMLFrameOwnerElement::loadOrRedirectSubframe(const KURL& url, const Atomic
// FIXME: In this case the Frame will have finished loading before
// it's being added to the child list. It would be a good idea to
// create the child first, then invoke the loader separately.
- if (childFrame->loader()->state() == FrameStateComplete && !childFrame->loader()->policyDocumentLoader())
- childFrame->loader()->checkCompleted();
+ if (childFrame->loader().state() == FrameStateComplete && !childFrame->loader().policyDocumentLoader())
+ childFrame->loader().checkCompleted();
return true;
}
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLFrameOwnerElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLFrameOwnerElement.h
index ed1b7abbbd2..834ac123c70 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLFrameOwnerElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLFrameOwnerElement.h
@@ -40,7 +40,7 @@ public:
DOMWindow* contentWindow() const;
Document* contentDocument() const;
- void setContentFrame(Frame*);
+ void setContentFrame(Frame&);
void clearContentFrame();
void disconnectContentFrame();
@@ -77,34 +77,24 @@ private:
SandboxFlags m_sandboxFlags;
};
-inline HTMLFrameOwnerElement* toHTMLFrameOwnerElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->isFrameOwnerElement());
- return static_cast<HTMLFrameOwnerElement*>(node);
-}
-
-inline const HTMLFrameOwnerElement* toHTMLFrameOwnerElement(const Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->isFrameOwnerElement());
- return static_cast<const HTMLFrameOwnerElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(HTMLFrameOwnerElement, isFrameOwnerElement());
class SubframeLoadingDisabler {
public:
- explicit SubframeLoadingDisabler(Node* root)
+ explicit SubframeLoadingDisabler(Node& root)
: m_root(root)
{
- disabledSubtreeRoots().add(m_root);
+ disabledSubtreeRoots().add(&m_root);
}
~SubframeLoadingDisabler()
{
- disabledSubtreeRoots().remove(m_root);
+ disabledSubtreeRoots().remove(&m_root);
}
- static bool canLoadFrame(HTMLFrameOwnerElement* owner)
+ static bool canLoadFrame(HTMLFrameOwnerElement& owner)
{
- for (Node* node = owner; node; node = node->parentOrShadowHostNode()) {
+ for (Node* node = &owner; node; node = node->parentOrShadowHostNode()) {
if (disabledSubtreeRoots().contains(node))
return false;
}
@@ -118,7 +108,7 @@ private:
return nodes;
}
- Node* m_root;
+ Node& m_root;
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLFrameSetElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLFrameSetElement.cpp
index e8055534752..cfa41341e71 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLFrameSetElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLFrameSetElement.cpp
@@ -28,22 +28,21 @@
#include "HTMLNames.h"
#include "bindings/v8/ScriptEventListener.h"
#include "core/dom/Document.h"
-#include "core/dom/Event.h"
-#include "core/dom/EventNames.h"
-#include "core/dom/MouseEvent.h"
+#include "core/events/Event.h"
+#include "core/events/MouseEvent.h"
+#include "core/events/ThreadLocalEventNames.h"
#include "core/html/HTMLCollection.h"
-#include "core/html/HTMLDimension.h"
#include "core/html/HTMLFrameElement.h"
#include "core/loader/FrameLoaderClient.h"
-#include "core/page/Frame.h"
+#include "core/frame/Frame.h"
#include "core/rendering/RenderFrameSet.h"
namespace WebCore {
using namespace HTMLNames;
-HTMLFrameSetElement::HTMLFrameSetElement(const QualifiedName& tagName, Document& document)
- : HTMLElement(tagName, document)
+HTMLFrameSetElement::HTMLFrameSetElement(Document& document)
+ : HTMLElement(framesetTag, document)
, m_border(6)
, m_borderSet(false)
, m_borderColorSet(false)
@@ -51,14 +50,13 @@ HTMLFrameSetElement::HTMLFrameSetElement(const QualifiedName& tagName, Document&
, m_frameborderSet(false)
, m_noresize(false)
{
- ASSERT(hasTagName(framesetTag));
ScriptWrappable::init(this);
setHasCustomStyleCallbacks();
}
-PassRefPtr<HTMLFrameSetElement> HTMLFrameSetElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<HTMLFrameSetElement> HTMLFrameSetElement::create(Document& document)
{
- return adoptRef(new HTMLFrameSetElement(tagName, document));
+ return adoptRef(new HTMLFrameSetElement(document));
}
bool HTMLFrameSetElement::isPresentationAttribute(const QualifiedName& name) const
@@ -111,37 +109,45 @@ void HTMLFrameSetElement::parseAttribute(const QualifiedName& name, const Atomic
} else if (name == bordercolorAttr)
m_borderColorSet = !value.isEmpty();
else if (name == onloadAttr)
- document().setWindowAttributeEventListener(eventNames().loadEvent, createAttributeEventListener(document().frame(), name, value));
+ document().setWindowAttributeEventListener(EventTypeNames::load, createAttributeEventListener(document().frame(), name, value));
else if (name == onbeforeunloadAttr)
- document().setWindowAttributeEventListener(eventNames().beforeunloadEvent, createAttributeEventListener(document().frame(), name, value));
+ document().setWindowAttributeEventListener(EventTypeNames::beforeunload, createAttributeEventListener(document().frame(), name, value));
else if (name == onunloadAttr)
- document().setWindowAttributeEventListener(eventNames().unloadEvent, createAttributeEventListener(document().frame(), name, value));
+ document().setWindowAttributeEventListener(EventTypeNames::unload, createAttributeEventListener(document().frame(), name, value));
+ else if (name == onpagehideAttr)
+ document().setWindowAttributeEventListener(EventTypeNames::pagehide, createAttributeEventListener(document().frame(), name, value));
+ else if (name == onpageshowAttr)
+ document().setWindowAttributeEventListener(EventTypeNames::pageshow, createAttributeEventListener(document().frame(), name, value));
else if (name == onblurAttr)
- document().setWindowAttributeEventListener(eventNames().blurEvent, createAttributeEventListener(document().frame(), name, value));
+ document().setWindowAttributeEventListener(EventTypeNames::blur, createAttributeEventListener(document().frame(), name, value));
+ else if (name == onerrorAttr)
+ document().setWindowAttributeEventListener(EventTypeNames::error, createAttributeEventListener(document().frame(), name, value));
else if (name == onfocusAttr)
- document().setWindowAttributeEventListener(eventNames().focusEvent, createAttributeEventListener(document().frame(), name, value));
+ document().setWindowAttributeEventListener(EventTypeNames::focus, createAttributeEventListener(document().frame(), name, value));
else if (name == onfocusinAttr)
- document().setWindowAttributeEventListener(eventNames().focusinEvent, createAttributeEventListener(document().frame(), name, value));
+ document().setWindowAttributeEventListener(EventTypeNames::focusin, createAttributeEventListener(document().frame(), name, value));
else if (name == onfocusoutAttr)
- document().setWindowAttributeEventListener(eventNames().focusoutEvent, createAttributeEventListener(document().frame(), name, value));
+ document().setWindowAttributeEventListener(EventTypeNames::focusout, createAttributeEventListener(document().frame(), name, value));
#if ENABLE(ORIENTATION_EVENTS)
else if (name == onorientationchangeAttr)
- document().setWindowAttributeEventListener(eventNames().orientationchangeEvent, createAttributeEventListener(document().frame(), name, value));
+ document().setWindowAttributeEventListener(EventTypeNames::orientationchange, createAttributeEventListener(document().frame(), name, value));
#endif
else if (name == onhashchangeAttr)
- document().setWindowAttributeEventListener(eventNames().hashchangeEvent, createAttributeEventListener(document().frame(), name, value));
+ document().setWindowAttributeEventListener(EventTypeNames::hashchange, createAttributeEventListener(document().frame(), name, value));
+ else if (name == onmessageAttr)
+ document().setWindowAttributeEventListener(EventTypeNames::message, createAttributeEventListener(document().frame(), name, value));
else if (name == onresizeAttr)
- document().setWindowAttributeEventListener(eventNames().resizeEvent, createAttributeEventListener(document().frame(), name, value));
+ document().setWindowAttributeEventListener(EventTypeNames::resize, createAttributeEventListener(document().frame(), name, value));
else if (name == onscrollAttr)
- document().setWindowAttributeEventListener(eventNames().scrollEvent, createAttributeEventListener(document().frame(), name, value));
+ document().setWindowAttributeEventListener(EventTypeNames::scroll, createAttributeEventListener(document().frame(), name, value));
else if (name == onstorageAttr)
- document().setWindowAttributeEventListener(eventNames().storageEvent, createAttributeEventListener(document().frame(), name, value));
+ document().setWindowAttributeEventListener(EventTypeNames::storage, createAttributeEventListener(document().frame(), name, value));
else if (name == ononlineAttr)
- document().setWindowAttributeEventListener(eventNames().onlineEvent, createAttributeEventListener(document().frame(), name, value));
+ document().setWindowAttributeEventListener(EventTypeNames::online, createAttributeEventListener(document().frame(), name, value));
else if (name == onofflineAttr)
- document().setWindowAttributeEventListener(eventNames().offlineEvent, createAttributeEventListener(document().frame(), name, value));
+ document().setWindowAttributeEventListener(EventTypeNames::offline, createAttributeEventListener(document().frame(), name, value));
else if (name == onpopstateAttr)
- document().setWindowAttributeEventListener(eventNames().popstateEvent, createAttributeEventListener(document().frame(), name, value));
+ document().setWindowAttributeEventListener(EventTypeNames::popstate, createAttributeEventListener(document().frame(), name, value));
else
HTMLElement::parseAttribute(name, value);
}
@@ -200,7 +206,7 @@ Node::InsertionNotificationRequest HTMLFrameSetElement::insertedInto(ContainerNo
{
if (insertionPoint->inDocument() && document().frame()) {
// A document using <frameset> likely won't literally have a body, but as far as the client is concerned, the frameset is effectively the body.
- document().frame()->loader()->client()->dispatchWillInsertBody();
+ document().frame()->loader().client()->dispatchWillInsertBody();
}
return HTMLElement::insertedInto(insertionPoint);
}
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLFrameSetElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLFrameSetElement.h
index 9c3b4f78e80..3138495cd2b 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLFrameSetElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLFrameSetElement.h
@@ -31,7 +31,7 @@ namespace WebCore {
class HTMLFrameSetElement FINAL : public HTMLElement {
public:
- static PassRefPtr<HTMLFrameSetElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<HTMLFrameSetElement> create(Document&);
bool hasFrameBorder() const { return m_frameborder; }
bool noResize() const { return m_noresize; }
@@ -47,27 +47,18 @@ public:
DOMWindow* anonymousNamedGetter(const AtomicString&);
- // Declared virtual in Element
DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(blur);
DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(error);
DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(focus);
DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(load);
+ DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(scroll);
- DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(beforeunload);
- DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(hashchange);
- DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(message);
- DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(offline);
- DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(online);
- DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(popstate);
- DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(resize);
- DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(storage);
- DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(unload);
#if ENABLE(ORIENTATION_EVENTS)
DEFINE_WINDOW_ATTRIBUTE_EVENT_LISTENER(orientationchange);
#endif
private:
- HTMLFrameSetElement(const QualifiedName&, Document&);
+ explicit HTMLFrameSetElement(Document&);
virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
@@ -95,11 +86,7 @@ private:
bool m_noresize;
};
-inline HTMLFrameSetElement* toHTMLFrameSetElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::framesetTag));
- return static_cast<HTMLFrameSetElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(HTMLFrameSetElement, hasTagName(HTMLNames::framesetTag));
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLFrameSetElement.idl b/chromium/third_party/WebKit/Source/core/html/HTMLFrameSetElement.idl
index 0a356846b4e..38a5f21424b 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLFrameSetElement.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLFrameSetElement.idl
@@ -23,29 +23,14 @@ interface HTMLFrameSetElement : HTMLElement {
[Reflect] attribute DOMString cols;
[Reflect] attribute DOMString rows;
- // Event handler attributes
- [NotEnumerable] attribute EventHandler onbeforeunload;
- [NotEnumerable] attribute EventHandler onhashchange;
- [NotEnumerable] attribute EventHandler onmessage;
- [NotEnumerable] attribute EventHandler onoffline;
- [NotEnumerable] attribute EventHandler ononline;
- [NotEnumerable] attribute EventHandler onpopstate;
- [NotEnumerable] attribute EventHandler onresize;
- [NotEnumerable] attribute EventHandler onstorage;
- [NotEnumerable] attribute EventHandler onunload;
+ [Conditional=ORIENTATION_EVENTS] attribute EventHandler onorientationchange;
- [Conditional=ORIENTATION_EVENTS, NotEnumerable] attribute EventHandler onorientationchange;
-
- // Overrides of Element attributes (with different implementation in bindings).
- [NotEnumerable] attribute EventHandler onblur;
- [NotEnumerable] attribute EventHandler onerror;
- [NotEnumerable] attribute EventHandler onfocus;
- [NotEnumerable] attribute EventHandler onload;
-
- // Not implemented yet.
- // attribute [NotEnumerable] EventHandler onafterprint;
- // attribute [NotEnumerable] EventHandler onbeforeprint;
- // attribute [NotEnumerable] EventHandler onredo;
- // attribute [NotEnumerable] EventHandler onundo;
+ // Overrides of GlobalEventHandler attributes
+ attribute EventHandler onblur;
+ attribute EventHandler onerror;
+ attribute EventHandler onfocus;
+ attribute EventHandler onload;
+ attribute EventHandler onscroll;
};
+HTMLFrameSetElement implements WindowEventHandlers;
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLHRElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLHRElement.cpp
index a71a4d38580..7a6edf88eb5 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLHRElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLHRElement.cpp
@@ -33,21 +33,15 @@ namespace WebCore {
using namespace HTMLNames;
-HTMLHRElement::HTMLHRElement(const QualifiedName& tagName, Document& document)
- : HTMLElement(tagName, document)
+HTMLHRElement::HTMLHRElement(Document& document)
+ : HTMLElement(hrTag, document)
{
- ASSERT(hasTagName(hrTag));
ScriptWrappable::init(this);
}
PassRefPtr<HTMLHRElement> HTMLHRElement::create(Document& document)
{
- return adoptRef(new HTMLHRElement(hrTag, document));
-}
-
-PassRefPtr<HTMLHRElement> HTMLHRElement::create(const QualifiedName& tagName, Document& document)
-{
- return adoptRef(new HTMLHRElement(tagName, document));
+ return adoptRef(new HTMLHRElement(document));
}
bool HTMLHRElement::isPresentationAttribute(const QualifiedName& name) const
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLHRElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLHRElement.h
index 7fc185def08..ec5bcb01442 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLHRElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLHRElement.h
@@ -30,12 +30,11 @@ namespace WebCore {
class HTMLHRElement FINAL : public HTMLElement {
public:
static PassRefPtr<HTMLHRElement> create(Document&);
- static PassRefPtr<HTMLHRElement> create(const QualifiedName&, Document&);
virtual bool canContainRangeEndPoint() const { return hasChildNodes(); }
private:
- HTMLHRElement(const QualifiedName&, Document&);
+ explicit HTMLHRElement(Document&);
virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
virtual void collectStyleForPresentationAttribute(const QualifiedName&, const AtomicString&, MutableStylePropertySet*) OVERRIDE;
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLHRElement.idl b/chromium/third_party/WebKit/Source/core/html/HTMLHRElement.idl
index babe467cd04..95950eb2357 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLHRElement.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLHRElement.idl
@@ -19,8 +19,8 @@
interface HTMLHRElement : HTMLElement {
[Reflect] attribute DOMString align;
+ [Reflect] attribute DOMString color;
[Reflect] attribute boolean noShade;
[Reflect] attribute DOMString size;
[Reflect] attribute DOMString width;
};
-
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLHeadElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLHeadElement.cpp
index a0afa3049c3..8a25aa6a51d 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLHeadElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLHeadElement.cpp
@@ -30,21 +30,15 @@ namespace WebCore {
using namespace HTMLNames;
-HTMLHeadElement::HTMLHeadElement(const QualifiedName& tagName, Document& document)
- : HTMLElement(tagName, document)
+HTMLHeadElement::HTMLHeadElement(Document& document)
+ : HTMLElement(headTag, document)
{
- ASSERT(hasTagName(headTag));
ScriptWrappable::init(this);
}
PassRefPtr<HTMLHeadElement> HTMLHeadElement::create(Document& document)
{
- return adoptRef(new HTMLHeadElement(headTag, document));
-}
-
-PassRefPtr<HTMLHeadElement> HTMLHeadElement::create(const QualifiedName& tagName, Document& document)
-{
- return adoptRef(new HTMLHeadElement(tagName, document));
+ return adoptRef(new HTMLHeadElement(document));
}
}
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLHeadElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLHeadElement.h
index 8a5040c058e..7abcac7df45 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLHeadElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLHeadElement.h
@@ -31,17 +31,12 @@ namespace WebCore {
class HTMLHeadElement FINAL : public HTMLElement {
public:
static PassRefPtr<HTMLHeadElement> create(Document&);
- static PassRefPtr<HTMLHeadElement> create(const QualifiedName&, Document&);
private:
- HTMLHeadElement(const QualifiedName&, Document&);
+ explicit HTMLHeadElement(Document&);
};
-inline HTMLHeadElement* toHTMLHeadElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::headTag));
- return static_cast<HTMLHeadElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(HTMLHeadElement, hasTagName(HTMLNames::headTag));
} // namespace
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLHeadElement.idl b/chromium/third_party/WebKit/Source/core/html/HTMLHeadElement.idl
index 6a784bdd766..738deb73d92 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLHeadElement.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLHeadElement.idl
@@ -18,6 +18,5 @@
*/
interface HTMLHeadElement : HTMLElement {
- [Reflect] attribute DOMString profile;
+ [Reflect, TreatNullAs=NullString, MeasureAs=HTMLHeadElementProfile] attribute DOMString profile;
};
-
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLHeadingElement.idl b/chromium/third_party/WebKit/Source/core/html/HTMLHeadingElement.idl
index 288f439025c..fe558d26bda 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLHeadingElement.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLHeadingElement.idl
@@ -20,4 +20,3 @@
interface HTMLHeadingElement : HTMLElement {
[Reflect] attribute DOMString align;
};
-
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLHtmlElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLHtmlElement.cpp
index 87d00e9bfc8..e4a56c917c4 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLHtmlElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLHtmlElement.cpp
@@ -30,27 +30,21 @@
#include "core/loader/DocumentLoader.h"
#include "core/loader/FrameLoader.h"
#include "core/loader/appcache/ApplicationCacheHost.h"
-#include "core/page/Frame.h"
+#include "core/frame/Frame.h"
namespace WebCore {
using namespace HTMLNames;
-HTMLHtmlElement::HTMLHtmlElement(const QualifiedName& tagName, Document& document)
- : HTMLElement(tagName, document)
+HTMLHtmlElement::HTMLHtmlElement(Document& document)
+ : HTMLElement(htmlTag, document)
{
- ASSERT(hasTagName(htmlTag));
ScriptWrappable::init(this);
}
PassRefPtr<HTMLHtmlElement> HTMLHtmlElement::create(Document& document)
{
- return adoptRef(new HTMLHtmlElement(htmlTag, document));
-}
-
-PassRefPtr<HTMLHtmlElement> HTMLHtmlElement::create(const QualifiedName& tagName, Document& document)
-{
- return adoptRef(new HTMLHtmlElement(tagName, document));
+ return adoptRef(new HTMLHtmlElement(document));
}
bool HTMLHtmlElement::isURLAttribute(const Attribute& attribute) const
@@ -67,7 +61,7 @@ void HTMLHtmlElement::insertedByParser()
if (!document().frame())
return;
- DocumentLoader* documentLoader = document().frame()->loader()->documentLoader();
+ DocumentLoader* documentLoader = document().frame()->loader().documentLoader();
if (!documentLoader)
return;
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLHtmlElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLHtmlElement.h
index e66f0619c12..4976aac0c8c 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLHtmlElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLHtmlElement.h
@@ -31,12 +31,11 @@ namespace WebCore {
class HTMLHtmlElement FINAL : public HTMLElement {
public:
static PassRefPtr<HTMLHtmlElement> create(Document&);
- static PassRefPtr<HTMLHtmlElement> create(const QualifiedName&, Document&);
void insertedByParser();
private:
- HTMLHtmlElement(const QualifiedName&, Document&);
+ explicit HTMLHtmlElement(Document&);
virtual bool isURLAttribute(const Attribute&) const OVERRIDE;
};
@@ -51,11 +50,7 @@ inline bool isHTMLHtmlElement(const Element* element)
return element->hasTagName(HTMLNames::htmlTag);
}
-inline HTMLHtmlElement* toHTMLHtmlElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || isHTMLHtmlElement(node));
- return static_cast<HTMLHtmlElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(HTMLHtmlElement, hasTagName(HTMLNames::htmlTag));
} // namespace
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLHtmlElement.idl b/chromium/third_party/WebKit/Source/core/html/HTMLHtmlElement.idl
index 430cdc6f805..3e329da57d1 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLHtmlElement.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLHtmlElement.idl
@@ -19,6 +19,5 @@
interface HTMLHtmlElement : HTMLElement {
[Reflect] attribute DOMString version;
- [Reflect, URL] attribute DOMString manifest;
+ [Reflect, TreatNullAs=NullString, URL, PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds, MeasureAs=HTMLHtmlElementManifest] attribute DOMString manifest;
};
-
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLIFrameElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLIFrameElement.cpp
index e198cad6ec0..016fba4ec0e 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLIFrameElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLIFrameElement.cpp
@@ -34,18 +34,17 @@ namespace WebCore {
using namespace HTMLNames;
-inline HTMLIFrameElement::HTMLIFrameElement(const QualifiedName& tagName, Document& document)
- : HTMLFrameElementBase(tagName, document)
+inline HTMLIFrameElement::HTMLIFrameElement(Document& document)
+ : HTMLFrameElementBase(iframeTag, document)
, m_didLoadNonEmptyDocument(false)
{
- ASSERT(hasTagName(iframeTag));
ScriptWrappable::init(this);
setHasCustomStyleCallbacks();
}
-PassRefPtr<HTMLIFrameElement> HTMLIFrameElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<HTMLIFrameElement> HTMLIFrameElement::create(Document& document)
{
- return adoptRef(new HTMLIFrameElement(tagName, document));
+ return adoptRef(new HTMLIFrameElement(document));
}
bool HTMLIFrameElement::isPresentationAttribute(const QualifiedName& name) const
@@ -85,7 +84,7 @@ void HTMLIFrameElement::parseAttribute(const QualifiedName& name, const AtomicSt
m_name = value;
} else if (name == sandboxAttr) {
String invalidTokens;
- setSandboxFlags(value.isNull() ? SandboxNone : SecurityContext::parseSandboxPolicy(value, invalidTokens));
+ setSandboxFlags(value.isNull() ? SandboxNone : parseSandboxPolicy(value, invalidTokens));
if (!invalidTokens.isNull())
document().addConsoleMessage(OtherMessageSource, ErrorMessageLevel, "Error while parsing the 'sandbox' attribute: " + invalidTokens);
} else if (name == seamlessAttr) {
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLIFrameElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLIFrameElement.h
index 87a5344029c..eab2678af2c 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLIFrameElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLIFrameElement.h
@@ -30,12 +30,12 @@ namespace WebCore {
class HTMLIFrameElement FINAL : public HTMLFrameElementBase {
public:
- static PassRefPtr<HTMLIFrameElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<HTMLIFrameElement> create(Document&);
bool shouldDisplaySeamlessly() const;
private:
- HTMLIFrameElement(const QualifiedName&, Document&);
+ explicit HTMLIFrameElement(Document&);
virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
@@ -57,11 +57,7 @@ private:
bool m_didLoadNonEmptyDocument;
};
-inline HTMLIFrameElement* toHTMLIFrameElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::iframeTag));
- return static_cast<HTMLIFrameElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(HTMLIFrameElement, hasTagName(HTMLNames::iframeTag));
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLIFrameElement.idl b/chromium/third_party/WebKit/Source/core/html/HTMLIFrameElement.idl
index d47b1b7e303..d8a8a8eb700 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLIFrameElement.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLIFrameElement.idl
@@ -22,23 +22,22 @@ interface HTMLIFrameElement : HTMLElement {
[Reflect] attribute DOMString align;
[Reflect] attribute DOMString frameBorder;
[Reflect] attribute DOMString height;
- [Reflect] attribute DOMString longDesc;
- [Reflect] attribute DOMString marginHeight;
- [Reflect] attribute DOMString marginWidth;
+ [Reflect, URL] attribute DOMString longDesc;
+ [Reflect, TreatNullAs=NullString] attribute DOMString marginHeight;
+ [Reflect, TreatNullAs=NullString] attribute DOMString marginWidth;
[Reflect] attribute DOMString name;
- [Reflect] attribute DOMString sandbox;
- [Reflect, EnabledAtRuntime=SeamlessIFrames] attribute boolean seamless;
+ [Reflect, TreatNullAs=NullString] attribute DOMString sandbox;
+ [Reflect, RuntimeEnabled=SeamlessIFrames] attribute boolean seamless;
[Reflect] attribute DOMString scrolling;
- [Reflect, URL] attribute DOMString src;
+ [Reflect, URL, PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute DOMString src;
[Reflect] attribute DOMString srcdoc;
[Reflect] attribute DOMString width;
// Introduced in DOM Level 2:
- [CheckSecurityForNode] readonly attribute Document contentDocument;
+ [CheckSecurity=Node] readonly attribute Document contentDocument;
// Extensions
readonly attribute Window contentWindow;
- [CheckSecurityForNode, RaisesException] SVGDocument getSVGDocument();
+ [CheckSecurity=Node, RaisesException] SVGDocument getSVGDocument();
};
-
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLImageElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLImageElement.cpp
index 114d814681b..d7d8c971b57 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLImageElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLImageElement.cpp
@@ -28,7 +28,7 @@
#include "RuntimeEnabledFeatures.h"
#include "bindings/v8/ScriptEventListener.h"
#include "core/dom/Attribute.h"
-#include "core/dom/EventNames.h"
+#include "core/events/ThreadLocalEventNames.h"
#include "core/fetch/ImageResource.h"
#include "core/html/HTMLAnchorElement.h"
#include "core/html/HTMLFormElement.h"
@@ -42,13 +42,13 @@ namespace WebCore {
using namespace HTMLNames;
-HTMLImageElement::HTMLImageElement(const QualifiedName& tagName, Document& document, HTMLFormElement* form)
- : HTMLElement(tagName, document)
+HTMLImageElement::HTMLImageElement(Document& document, HTMLFormElement* form)
+ : HTMLElement(imgTag, document)
, m_imageLoader(this)
, m_form(form)
, m_compositeOperator(CompositeSourceOver)
+ , m_imageDevicePixelRatio(1.0f)
{
- ASSERT(hasTagName(imgTag));
ScriptWrappable::init(this);
if (form)
form->registerImgElement(this);
@@ -56,12 +56,12 @@ HTMLImageElement::HTMLImageElement(const QualifiedName& tagName, Document& docum
PassRefPtr<HTMLImageElement> HTMLImageElement::create(Document& document)
{
- return adoptRef(new HTMLImageElement(imgTag, document));
+ return adoptRef(new HTMLImageElement(document));
}
-PassRefPtr<HTMLImageElement> HTMLImageElement::create(const QualifiedName& tagName, Document& document, HTMLFormElement* form)
+PassRefPtr<HTMLImageElement> HTMLImageElement::create(Document& document, HTMLFormElement* form)
{
- return adoptRef(new HTMLImageElement(tagName, document, form));
+ return adoptRef(new HTMLImageElement(document, form));
}
HTMLImageElement::~HTMLImageElement()
@@ -70,13 +70,13 @@ HTMLImageElement::~HTMLImageElement()
m_form->removeImgElement(this);
}
-PassRefPtr<HTMLImageElement> HTMLImageElement::createForJSConstructor(Document& document, const int* optionalWidth, const int* optionalHeight)
+PassRefPtr<HTMLImageElement> HTMLImageElement::createForJSConstructor(Document& document, int width, int height)
{
- RefPtr<HTMLImageElement> image = adoptRef(new HTMLImageElement(imgTag, document));
- if (optionalWidth)
- image->setWidth(*optionalWidth);
- if (optionalHeight)
- image->setHeight(*optionalHeight);
+ RefPtr<HTMLImageElement> image = adoptRef(new HTMLImageElement(document));
+ if (width)
+ image->setWidth(width);
+ if (height)
+ image->setHeight(height);
return image.release();
}
@@ -114,39 +114,50 @@ const AtomicString HTMLImageElement::imageSourceURL() const
return m_bestFitImageURL.isNull() ? fastGetAttribute(srcAttr) : m_bestFitImageURL;
}
+HTMLFormElement* HTMLImageElement::formOwner() const
+{
+ return findFormAncestor();
+}
+
void HTMLImageElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
{
if (name == altAttr) {
if (renderer() && renderer()->isImage())
toRenderImage(renderer())->updateAltText();
} else if (name == srcAttr || name == srcsetAttr) {
- if (RuntimeEnabledFeatures::srcsetEnabled())
- m_bestFitImageURL = bestFitSourceForImageAttributes(document().devicePixelRatio(), fastGetAttribute(srcAttr), fastGetAttribute(srcsetAttr));
+ if (RuntimeEnabledFeatures::srcsetEnabled()) {
+ ImageCandidate candidate = bestFitSourceForImageAttributes(document().devicePixelRatio(), fastGetAttribute(srcAttr), fastGetAttribute(srcsetAttr));
+ m_bestFitImageURL = candidate.toString();
+ float candidateScaleFactor = candidate.scaleFactor();
+ if (candidateScaleFactor > 0)
+ m_imageDevicePixelRatio = 1 / candidateScaleFactor;
+ if (renderer() && renderer()->isImage())
+ toRenderImage(renderer())->setImageDevicePixelRatio(m_imageDevicePixelRatio);
+ }
m_imageLoader.updateFromElementIgnoringPreviousError();
}
else if (name == usemapAttr)
setIsLink(!value.isNull());
else if (name == onbeforeloadAttr)
- setAttributeEventListener(eventNames().beforeloadEvent, createAttributeEventListener(this, name, value));
+ setAttributeEventListener(EventTypeNames::beforeload, createAttributeEventListener(this, name, value));
else if (name == compositeAttr) {
// FIXME: images don't support blend modes in their compositing attribute.
- BlendMode blendOp = BlendModeNormal;
+ blink::WebBlendMode blendOp = blink::WebBlendModeNormal;
if (!parseCompositeAndBlendOperator(value, m_compositeOperator, blendOp))
m_compositeOperator = CompositeSourceOver;
} else
HTMLElement::parseAttribute(name, value);
}
-String HTMLImageElement::altText() const
+const AtomicString& HTMLImageElement::altText() const
{
// lets figure out the alt text.. magic stuff
// http://www.w3.org/TR/1998/REC-html40-19980424/appendix/notes.html#altgen
// also heavily discussed by Hixie on bugzilla
- String alt = getAttribute(altAttr);
+ if (!getAttribute(altAttr).isNull())
+ return getAttribute(altAttr);
// fall back to title attribute
- if (alt.isNull())
- alt = getAttribute(titleAttr);
- return alt;
+ return getAttribute(titleAttr);
}
RenderObject* HTMLImageElement::createRenderer(RenderStyle* style)
@@ -156,6 +167,7 @@ RenderObject* HTMLImageElement::createRenderer(RenderStyle* style)
RenderImage* image = new RenderImage(this);
image->setImageResource(RenderImageResource::create());
+ image->setImageDevicePixelRatio(m_imageDevicePixelRatio);
return image;
}
@@ -301,7 +313,7 @@ bool HTMLImageElement::draggable() const
void HTMLImageElement::setHeight(int value)
{
- setAttribute(heightAttr, String::number(value));
+ setIntegralAttribute(heightAttr, value);
}
KURL HTMLImageElement::src() const
@@ -311,12 +323,12 @@ KURL HTMLImageElement::src() const
void HTMLImageElement::setSrc(const String& value)
{
- setAttribute(srcAttr, value);
+ setAttribute(srcAttr, AtomicString(value));
}
void HTMLImageElement::setWidth(int value)
{
- setAttribute(widthAttr, String::number(value));
+ setIntegralAttribute(widthAttr, value);
}
int HTMLImageElement::x() const
@@ -355,7 +367,7 @@ void HTMLImageElement::addSubresourceAttributeURLs(ListHashSet<KURL>& urls) cons
addSubresourceURL(urls, document().completeURL(getAttribute(usemapAttr)));
}
-void HTMLImageElement::didMoveToNewDocument(Document* oldDocument)
+void HTMLImageElement::didMoveToNewDocument(Document& oldDocument)
{
m_imageLoader.elementDidMoveToNewDocument();
HTMLElement::didMoveToNewDocument(oldDocument);
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLImageElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLImageElement.h
index a7e547cb67f..05c5d81db3f 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLImageElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLImageElement.h
@@ -26,7 +26,7 @@
#include "core/html/HTMLElement.h"
#include "core/html/HTMLImageLoader.h"
-#include "core/platform/graphics/GraphicsTypes.h"
+#include "platform/graphics/GraphicsTypes.h"
namespace WebCore {
@@ -36,8 +36,8 @@ class HTMLImageElement FINAL : public HTMLElement {
friend class HTMLFormElement;
public:
static PassRefPtr<HTMLImageElement> create(Document&);
- static PassRefPtr<HTMLImageElement> create(const QualifiedName&, Document&, HTMLFormElement*);
- static PassRefPtr<HTMLImageElement> createForJSConstructor(Document&, const int* optionalWidth, const int* optionalHeight);
+ static PassRefPtr<HTMLImageElement> create(Document&, HTMLFormElement*);
+ static PassRefPtr<HTMLImageElement> createForJSConstructor(Document&, int width, int height);
virtual ~HTMLImageElement();
@@ -49,7 +49,7 @@ public:
bool isServerMap() const;
- String altText() const;
+ const AtomicString& altText() const;
CompositeOperator compositeOperator() const { return m_compositeOperator; }
@@ -81,10 +81,12 @@ public:
virtual const AtomicString imageSourceURL() const OVERRIDE;
+ virtual HTMLFormElement* formOwner() const OVERRIDE;
+
protected:
- HTMLImageElement(const QualifiedName&, Document&, HTMLFormElement* = 0);
+ explicit HTMLImageElement(Document&, HTMLFormElement* = 0);
- virtual void didMoveToNewDocument(Document* oldDocument) OVERRIDE;
+ virtual void didMoveToNewDocument(Document& oldDocument) OVERRIDE;
private:
virtual bool areAuthorShadowsAllowed() const OVERRIDE { return false; }
@@ -115,19 +117,10 @@ private:
HTMLFormElement* m_form;
CompositeOperator m_compositeOperator;
AtomicString m_bestFitImageURL;
+ float m_imageDevicePixelRatio;
};
-inline HTMLImageElement* toHTMLImageElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::imgTag));
- return static_cast<HTMLImageElement*>(node);
-}
-
-inline const HTMLImageElement* toHTMLImageElement(const Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::imgTag));
- return static_cast<const HTMLImageElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(HTMLImageElement, hasTagName(HTMLNames::imgTag));
} //namespace
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLImageElement.idl b/chromium/third_party/WebKit/Source/core/html/HTMLImageElement.idl
index efd1c6a2f4c..a5480236fd6 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLImageElement.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLImageElement.idl
@@ -18,29 +18,31 @@
* Boston, MA 02110-1301, USA.
*/
+// FIXME: NamedConstructor does not support optional without Default. Fortunately using Undefined makes
+// us use 0 which happens to be the default width and height anyway.
[
+ NamedConstructor=Image([Default=Undefined] optional long width, [Default=Undefined] optional long height)
] interface HTMLImageElement : HTMLElement {
- [Reflect] attribute DOMString name;
[Reflect] attribute DOMString align;
[Reflect] attribute DOMString alt;
- [Reflect] attribute DOMString border;
+ [Reflect, TreatNullAs=NullString] attribute DOMString border;
+ readonly attribute boolean complete;
[Reflect] attribute DOMString crossOrigin;
attribute long height;
[Reflect] attribute long hspace;
[Reflect] attribute boolean isMap;
- [Reflect, URL] attribute DOMString longDesc;
- [Reflect, URL] attribute DOMString src;
- [Reflect, EnabledAtRuntime=Srcset] attribute DOMString srcset;
+ [Reflect, URL, PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute DOMString longDesc;
+ [Reflect, URL, PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute DOMString lowsrc;
+ [Reflect] attribute DOMString name;
+ readonly attribute long naturalHeight;
+ readonly attribute long naturalWidth;
+ [Reflect, URL, PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute DOMString src;
+ [Reflect, RuntimeEnabled=Srcset] attribute DOMString srcset;
[Reflect] attribute DOMString useMap;
[Reflect] attribute long vspace;
attribute long width;
// Extensions
- readonly attribute boolean complete;
- [Reflect,URL] attribute DOMString lowsrc;
- readonly attribute long naturalHeight;
- readonly attribute long naturalWidth;
readonly attribute long x;
readonly attribute long y;
};
-
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLImageLoader.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLImageLoader.cpp
index 55a287fb40c..9a50c5f94db 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLImageLoader.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLImageLoader.cpp
@@ -24,8 +24,8 @@
#include "HTMLNames.h"
#include "core/dom/Element.h"
-#include "core/dom/Event.h"
-#include "core/dom/EventNames.h"
+#include "core/events/Event.h"
+#include "core/events/ThreadLocalEventNames.h"
#include "core/fetch/ImageResource.h"
#include "core/html/HTMLObjectElement.h"
#include "core/html/HTMLVideoElement.h"
@@ -51,7 +51,7 @@ void HTMLImageLoader::dispatchLoadEvent()
bool errorOccurred = image()->errorOccurred();
if (!errorOccurred && image()->response().httpStatusCode() >= 400)
errorOccurred = element()->hasTagName(HTMLNames::objectTag); // An <object> considers a 404 to be an error and should fire onerror.
- element()->dispatchEvent(Event::create(errorOccurred ? eventNames().errorEvent : eventNames().loadEvent));
+ element()->dispatchEvent(Event::create(errorOccurred ? EventTypeNames::error : EventTypeNames::load));
}
String HTMLImageLoader::sourceURI(const AtomicString& attr) const
@@ -69,7 +69,7 @@ void HTMLImageLoader::notifyFinished(Resource*)
bool loadError = cachedImage->errorOccurred() || cachedImage->response().httpStatusCode() >= 400;
if (loadError && element->hasTagName(HTMLNames::objectTag))
- toHTMLObjectElement(element.get())->renderFallbackContent();
+ toHTMLObjectElement(element)->renderFallbackContent();
}
}
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLImport.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLImport.cpp
index 9b1230de755..8ac2d7d127c 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLImport.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLImport.cpp
@@ -52,19 +52,18 @@ HTMLImportsController* HTMLImport::controller()
void HTMLImport::appendChild(HTMLImport* child)
{
- ASSERT(child->parent() == this);
- ASSERT(!child->hasChildren());
-
- if (isBlocked())
- child->block();
- m_children.append(child);
+ if (isScriptBlocked())
+ child->blockScript();
+ if (lastChild() && !lastChild()->isDone())
+ child->blockDocument();
+ TreeNode<HTMLImport>::appendChild(child);
blockAfter(child);
}
bool HTMLImport::areChilrenLoaded() const
{
- for (size_t i = 0; i < m_children.size(); ++i) {
- if (!m_children[i]->isLoaded())
+ for (HTMLImport* child = firstChild(); child; child = child->next()) {
+ if (!child->isLoaded())
return false;
}
@@ -77,8 +76,7 @@ bool HTMLImport::arePredecessorsLoaded() const
if (!parent)
return true;
- for (size_t i = 0; i < parent->m_children.size(); ++i) {
- HTMLImport* sibling = parent->m_children[i];
+ for (HTMLImport* sibling = parent->firstChild(); sibling; sibling = sibling->next()) {
if (sibling == this)
break;
if (!sibling->isLoaded())
@@ -88,22 +86,24 @@ bool HTMLImport::arePredecessorsLoaded() const
return true;
}
-void HTMLImport::block()
+void HTMLImport::blockScript()
{
- m_blocked = true;
+ m_scriptBlocked = true;
}
-void HTMLImport::unblock()
+void HTMLImport::unblockScript()
{
- bool wasBlocked = m_blocked;
- m_blocked = false;
+ bool wasBlocked = m_scriptBlocked;
+ m_scriptBlocked = false;
if (wasBlocked)
- didUnblock();
+ didUnblockScript();
}
-void HTMLImport::didUnblock()
+void HTMLImport::didUnblockScript()
{
- ASSERT(!isBlocked());
+ ASSERT(!isDocumentBlocked());
+ ASSERT(!isScriptBlocked());
+
if (!isProcessing())
return;
@@ -111,45 +111,80 @@ void HTMLImport::didUnblock()
document->didLoadAllImports();
}
+
+void HTMLImport::blockDocument()
+{
+ m_documentBlocked = true;
+}
+
+void HTMLImport::unblockDocument()
+{
+ bool wasBlocked = m_documentBlocked;
+ m_documentBlocked = false;
+ if (wasBlocked)
+ didUnblockDocument();
+}
+
+void HTMLImport::didUnblockDocument()
+{
+ ASSERT(!isDocumentBlocked());
+ ASSERT(isScriptBlocked());
+}
+
+inline bool HTMLImport::needsBlockingDocument() const
+{
+ ASSERT(isDocumentBlocked());
+ HTMLImport* elder = previous();
+ return (elder && !elder->isDone());
+}
+
bool HTMLImport::unblock(HTMLImport* import)
{
ASSERT(import->arePredecessorsLoaded());
- ASSERT(import->isBlocked() || import->areChilrenLoaded());
+ ASSERT(import->isScriptBlocked() || import->areChilrenLoaded());
+
+ if (import->isDocumentBlocked() && import->needsBlockingDocument())
+ return false;
+ import->unblockDocument();
- if (import->isBlocked()) {
- for (size_t i = 0; i < import->m_children.size(); ++i) {
- if (!unblock(import->m_children[i]))
+ if (import->isScriptBlocked()) {
+ for (HTMLImport* child = import->firstChild(); child; child = child->next()) {
+ if (!unblock(child))
return false;
}
}
- import->unblock();
+ import->unblockScript();
return import->isLoaded();
}
void HTMLImport::block(HTMLImport* import)
{
- import->block();
- for (size_t i = 0; i < import->m_children.size(); ++i)
- block(import->m_children[i]);
+ for (HTMLImport* child = import; child; child = traverseNext(child, import))
+ child->blockScript();
}
void HTMLImport::blockAfter(HTMLImport* child)
{
ASSERT(child->parent() == this);
- for (size_t i = 0; i < m_children.size(); ++i) {
- HTMLImport* sibling = m_children[m_children.size() - i - 1];
+ for (HTMLImport* sibling = lastChild(); sibling; sibling = sibling->previous()) {
if (sibling == child)
break;
HTMLImport::block(sibling);
}
- this->block();
+ this->blockScript();
if (HTMLImport* parent = this->parent())
parent->blockAfter(this);
}
+bool HTMLImport::isMaster(Document* document)
+{
+ if (!document->import())
+ return true;
+ return (document->import()->master() == document);
+}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLImport.h b/chromium/third_party/WebKit/Source/core/html/HTMLImport.h
index 215dad97006..2c80c9775e9 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLImport.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLImport.h
@@ -31,6 +31,7 @@
#ifndef HTMLImport_h
#define HTMLImport_h
+#include "wtf/TreeNode.h"
#include "wtf/Vector.h"
namespace WebCore {
@@ -38,12 +39,99 @@ namespace WebCore {
class Frame;
class Document;
class Frame;
+class HTMLImportChild;
class HTMLImportRoot;
class HTMLImportsController;
-
-class HTMLImport {
+class KURL;
+
+//
+// # Basic Data Structure and Algorithms of HTML Imports implemenation.
+//
+// ## The Import Tree
+//
+// HTML Imports form a tree:
+//
+// * The root of the tree is HTMLImportsController, which is owned by the master
+// document as a DocumentSupplement. HTMLImportsController has an abstract class called
+// HTMLImportRoot to deal with cycler dependency.
+//
+// * The non-root nodes are HTMLImportChild, which is owned by LinkStyle, that is owned by HTMLLinkElement.
+// LinkStyle is wired into HTMLImportChild by implementing HTMLImportChildClient interface
+//
+// * Both HTMLImportsController and HTMLImportChild are derived from HTMLImport superclass
+// that models the tree data structure using WTF::TreeNode and provides a set of
+// virtual functions.
+//
+// HTMLImportsController also owns all loaders in the tree and manages their lifetime through it.
+// One assumption is that the tree is append-only and nodes are never inserted in the middle of the tree nor removed.
+//
+//
+// HTMLImport <|- HTMLImportRoot <|- HTMLImportsController <- Document
+// *
+// |
+// <|- HTMLImportChild <- LinkStyle <- HTMLLinkElement
+//
+//
+// # Import Sharing and HTMLImportLoader
+//
+// The HTML Imports spec calls for de-dup mechanism to share already loaded imports.
+// To implement this, the actual loading machinery is split out from HTMLImportChild to
+// HTMLImportLoader, and each loader shares HTMLImportLoader with other loader if the URL is same.
+// Check around HTMLImportsController::findLink() for more detail.
+//
+// Note that HTMLImportLoader provides HTMLImportLoaderClient to hook it up.
+// As it can be shared, HTMLImportLoader supports multiple clients.
+//
+// HTMLImportChild (1)-->(*) HTMLImportLoader
+//
+//
+// # Script Blocking
+//
+// The HTML parser blocks on <script> when preceding <link>s aren't finish loading imports.
+// Each HTMLImport instance tracks such a blocking state, that is called "script-blocked"
+// or HTMLImport::isScriptBlocked().
+//
+// ## Blocking Imports
+//
+// Each imports can become being script-blocked when new imports are added to the import tree.
+// For example, the parser of a parent import is blocked when new child import is given.
+// See HTMLImport::appendChild() to see how it is handled. Note that this blocking-ness is
+// transitive. HTMLImport::blockAfter() flips the flags iteratively to fullfill this transitivity.
+//
+// ## Unblocking Imports
+//
+// The blocking state can change when one of the imports finish loading. The Document notices it through
+// HTMLImportRoot::blockerGone(). The blockerGone() triggers HTMLImport::unblockScript(), which traverses
+// whole import tree and find unblock-able imports and unblock them.
+// Unblocked imported documents are notified through Document::didLoadAllImports() so that
+// it can resume its parser.
+//
+// # Document Blocking
+//
+// There is another type of blocking state that is called
+// "document-blocked". If the import is document-blocked, it cannot
+// create its own document object because sharable imported document
+// can appear later. The spec defines the loading order of the
+// import: The earlier one in the import-tree order should win and
+// later ones should share earlier one.
+//
+// The "document-blocked" state keeps the tree node from loading its
+// import until all preceding imports are ready t respect the
+// order. Note that the node may fetch the bytes from the URL
+// speculatively, even though it doesn't process it.
+//
+// The node is "document-unblocked" when there are unfinished,
+// preceeding import loading. Unblocking attempt for
+// "document-blocked" happens at the same timing as unblocking
+// "script-blocked".
+//
+
+// The superclass of HTMLImportsController and HTMLImportChild
+// This represents the import tree data structure.
+class HTMLImport : public TreeNode<HTMLImport> {
public:
static bool unblock(HTMLImport*);
+ static bool isMaster(Document*);
virtual ~HTMLImport() { }
@@ -51,42 +139,53 @@ public:
Document* master();
HTMLImportsController* controller();
- bool isLoaded() const { return !isBlocked() && !isProcessing(); }
- bool isBlocked() const { return m_blocked; }
+ bool isLoaded() const { return !isScriptBlocked() && !isProcessing(); }
+ bool isScriptBlocked() const { return m_scriptBlocked; }
+ bool isDocumentBlocked() const { return m_documentBlocked; }
+ bool isBlocked() const { return m_scriptBlocked || m_documentBlocked; }
+
void appendChild(HTMLImport*);
virtual HTMLImportRoot* root() = 0;
- virtual HTMLImport* parent() const = 0;
virtual Document* document() const = 0;
virtual void wasDetachedFromDocument() = 0;
virtual void didFinishParsing() = 0;
virtual bool isProcessing() const = 0;
+ virtual bool isDone() const = 0;
protected:
HTMLImport()
- : m_blocked(false)
+ : m_scriptBlocked(false)
+ , m_documentBlocked(false)
{ }
+ virtual void didUnblockDocument();
+
private:
static void block(HTMLImport*);
void blockAfter(HTMLImport* child);
- void block();
- void unblock();
- void didUnblock();
+ void blockScript();
+ void unblockScript();
+ void didUnblockScript();
+
+ void blockDocument();
+ void unblockDocument();
+ bool needsBlockingDocument() const;
bool arePredecessorsLoaded() const;
bool areChilrenLoaded() const;
- bool hasChildren() const { return !m_children.isEmpty(); }
- Vector<HTMLImport*> m_children;
- bool m_blocked; // If any of decendants or predecessors is in processing, it is blocked.
+ bool m_scriptBlocked; // If any of decendants or predecessors is in processing, the parser blocks on <script>.
+ bool m_documentBlocked; // If its predecessor is not done yet, the document creation is blocked.
};
+// An abstract class to decouple its sublcass HTMLImportsController.
class HTMLImportRoot : public HTMLImport {
public:
- virtual void importWasDisposed() = 0;
+ virtual void blockerGone() = 0;
virtual HTMLImportsController* toController() = 0;
+ virtual HTMLImportChild* findLinkFor(const KURL&, HTMLImport* excluding = 0) const = 0;
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLImportChild.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLImportChild.cpp
new file mode 100644
index 00000000000..52445f355ea
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLImportChild.cpp
@@ -0,0 +1,174 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/html/HTMLImportChild.h"
+
+#include "core/dom/Document.h"
+#include "core/html/HTMLImportChildClient.h"
+#include "core/html/HTMLImportLoader.h"
+
+namespace WebCore {
+
+HTMLImportChild::HTMLImportChild(const KURL& url, HTMLImportChildClient* client)
+ : m_url(url)
+ , m_client(client)
+{
+}
+
+HTMLImportChild::~HTMLImportChild()
+{
+ // importDestroyed() should be called before the destruction.
+ ASSERT(!m_loader);
+}
+
+void HTMLImportChild::wasAlreadyLoadedAs(HTMLImportChild* found)
+{
+ ASSERT(!m_loader);
+ ASSERT(m_client);
+ shareLoader(found);
+}
+
+void HTMLImportChild::startLoading(const ResourcePtr<RawResource>& resource)
+{
+ ASSERT(!hasResource());
+ ASSERT(!m_loader);
+
+ HTMLImportResourceOwner::setResource(resource);
+
+ // If the node is "document blocked", it cannot create HTMLImportLoader
+ // even if there is no sharable one found, as there is possibility that
+ // preceding imports load the sharable imports.
+ // In that case preceding one should win because it comes first in the tree order.
+ // See also didUnblockDocument().
+ if (isDocumentBlocked())
+ return;
+
+ createLoader();
+}
+
+void HTMLImportChild::didFinish()
+{
+ if (m_client)
+ m_client->didFinish();
+ clearResource();
+ root()->blockerGone();
+}
+
+Document* HTMLImportChild::importedDocument() const
+{
+ if (!m_loader)
+ return 0;
+ return m_loader->importedDocument();
+}
+
+void HTMLImportChild::importDestroyed()
+{
+ if (parent())
+ parent()->removeChild(this);
+ if (m_loader) {
+ m_loader->removeClient(this);
+ m_loader.clear();
+ }
+}
+
+HTMLImportRoot* HTMLImportChild::root()
+{
+ return parent() ? parent()->root() : 0;
+}
+
+Document* HTMLImportChild::document() const
+{
+ return (m_loader && m_loader->isOwnedBy(this)) ? m_loader->document() : 0;
+}
+
+void HTMLImportChild::wasDetachedFromDocument()
+{
+ // For imported documens this shouldn't be called because Document::m_import is
+ // cleared before Document is destroyed by HTMLImportChild::importDestroyed().
+ ASSERT_NOT_REACHED();
+}
+
+void HTMLImportChild::didFinishParsing()
+{
+ ASSERT(m_loader->isOwnedBy(this));
+ m_loader->didFinishParsing();
+}
+
+// Once all preceding imports are loaded and "document blocking" ends,
+// HTMLImportChild can decide whether it should load the import by itself
+// or it can share existing one.
+void HTMLImportChild::didUnblockDocument()
+{
+ HTMLImport::didUnblockDocument();
+ ASSERT(!isDocumentBlocked());
+ ASSERT(!m_loader || !m_loader->isOwnedBy(this));
+
+ if (m_loader)
+ return;
+ if (HTMLImportChild* found = root()->findLinkFor(m_url, this))
+ shareLoader(found);
+ else
+ createLoader();
+}
+
+void HTMLImportChild::createLoader()
+{
+ ASSERT(!isDocumentBlocked());
+ ASSERT(!m_loader);
+ m_loader = HTMLImportLoader::create(this, parent()->document()->fetcher());
+ m_loader->addClient(this);
+ m_loader->startLoading(resource());
+}
+
+void HTMLImportChild::shareLoader(HTMLImportChild* loader)
+{
+ ASSERT(!m_loader);
+ m_loader = loader->m_loader;
+ m_loader->addClient(this);
+ root()->blockerGone();
+}
+
+bool HTMLImportChild::isProcessing() const
+{
+ return m_loader && m_loader->isOwnedBy(this) && m_loader->isProcessing();
+}
+
+bool HTMLImportChild::isDone() const
+{
+ return m_loader && m_loader->isDone();
+}
+
+bool HTMLImportChild::isLoaded() const
+{
+ return m_loader->isLoaded();
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLImportChild.h b/chromium/third_party/WebKit/Source/core/html/HTMLImportChild.h
new file mode 100644
index 00000000000..72f0329c2c5
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLImportChild.h
@@ -0,0 +1,97 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef HTMLImportChild_h
+#define HTMLImportChild_h
+
+#include "core/html/HTMLImport.h"
+#include "core/html/HTMLImportLoaderClient.h"
+#include "core/html/HTMLImportResourceOwner.h"
+#include "platform/weborigin/KURL.h"
+
+namespace WebCore {
+
+class HTMLImportLoader;
+class HTMLImportChildClient;
+
+//
+// An import tree node subclas to encapsulate imported document
+// lifecycle. This class is owned by LinkStyle. The actual loading
+// is done by HTMLImportLoader, which can be shared among multiple
+// HTMLImportChild of same link URL.
+//
+// HTMLImportChild implements ResourceClient through HTMLImportResourceOwner
+// so that it can speculatively request linked resources while it is unblocked.
+//
+class HTMLImportChild : public HTMLImport, public HTMLImportLoaderClient, public HTMLImportResourceOwner {
+public:
+ HTMLImportChild(const KURL&, HTMLImportChildClient*);
+ virtual ~HTMLImportChild();
+
+ Document* importedDocument() const;
+ const KURL& url() const { return m_url; }
+
+ void wasAlreadyLoadedAs(HTMLImportChild* found);
+ void startLoading(const ResourcePtr<RawResource>&);
+ void importDestroyed();
+ bool isLoaded() const;
+
+ // HTMLImport
+ virtual HTMLImportRoot* root() OVERRIDE;
+ virtual Document* document() const OVERRIDE;
+ virtual void wasDetachedFromDocument() OVERRIDE;
+ virtual void didFinishParsing() OVERRIDE;
+ virtual bool isProcessing() const OVERRIDE;
+ virtual bool isDone() const OVERRIDE;
+ virtual void didUnblockDocument() OVERRIDE;
+
+ void clearClient() { m_client = 0; }
+
+private:
+ // RawResourceOwner doing nothing.
+ // HTMLImportChild owns the resource so that the contents of prefetched Resource doesn't go away.
+ virtual void responseReceived(Resource*, const ResourceResponse&) OVERRIDE { }
+ virtual void dataReceived(Resource*, const char*, int) OVERRIDE { }
+ virtual void notifyFinished(Resource*) OVERRIDE { }
+
+ // HTMLImportLoaderClient
+ virtual void didFinish() OVERRIDE;
+
+ void createLoader();
+ void shareLoader(HTMLImportChild*);
+
+ KURL m_url;
+ HTMLImportChildClient* m_client;
+ RefPtr<HTMLImportLoader> m_loader;
+};
+
+} // namespace WebCore
+
+#endif // HTMLImportChild_h
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLImportChildClient.h b/chromium/third_party/WebKit/Source/core/html/HTMLImportChildClient.h
new file mode 100644
index 00000000000..62866e8c4f7
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLImportChildClient.h
@@ -0,0 +1,45 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef HTMLImportChildClient_h
+#define HTMLImportChildClient_h
+
+namespace WebCore {
+
+class HTMLImportChildClient {
+public:
+ virtual ~HTMLImportChildClient() { }
+ virtual void didFinish() = 0;
+ virtual void loaderWillBeDestroyed() = 0;
+};
+
+} // namespace WebCore
+
+#endif // HTMLImportChildClient_h
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLImportLoader.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLImportLoader.cpp
index 283b757e15e..5781c79791e 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLImportLoader.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLImportLoader.cpp
@@ -31,40 +31,50 @@
#include "config.h"
#include "core/html/HTMLImportLoader.h"
-#include "core/dom/CustomElementRegistrationContext.h"
#include "core/dom/Document.h"
+#include "core/dom/custom/CustomElementRegistrationContext.h"
#include "core/fetch/ResourceFetcher.h"
+#include "core/frame/ContentSecurityPolicyResponseHeaders.h"
#include "core/html/HTMLDocument.h"
+#include "core/html/HTMLImport.h"
#include "core/html/HTMLImportLoaderClient.h"
#include "core/loader/DocumentWriter.h"
-#include "core/page/ContentSecurityPolicyResponseHeaders.h"
+
namespace WebCore {
-HTMLImportLoader::HTMLImportLoader(HTMLImport* parent, const KURL& url)
- : m_parent(parent)
+PassRefPtr<HTMLImportLoader> HTMLImportLoader::create(HTMLImport* import, ResourceFetcher* fetcher)
+{
+ RefPtr<HTMLImportLoader> self = adoptRef(new HTMLImportLoader(import, fetcher));
+ return self.release();
+}
+
+HTMLImportLoader::HTMLImportLoader(HTMLImport* import, ResourceFetcher* fetcher)
+ : m_import(import)
+ , m_fetcher(fetcher)
, m_state(StateLoading)
- , m_url(url)
{
}
HTMLImportLoader::~HTMLImportLoader()
{
- // importDestroyed() should be called before the destruction.
- ASSERT(!m_parent);
- ASSERT(!m_importedDocument);
- if (m_resource)
- m_resource->removeClient(this);
+ if (m_importedDocument)
+ m_importedDocument->setImport(0);
}
-void HTMLImportLoader::setResource(const ResourcePtr<RawResource>& resource)
+void HTMLImportLoader::startLoading(const ResourcePtr<RawResource>& resource)
{
- m_resource = resource;
- m_resource->addClient(this);
+ setResource(resource);
}
-void HTMLImportLoader::responseReceived(Resource*, const ResourceResponse& response)
+void HTMLImportLoader::responseReceived(Resource* resource, const ResourceResponse& response)
{
+ // Current canAccess() implementation isn't sufficient for catching cross-domain redirects: http://crbug.com/256976
+ if (!m_fetcher->canAccess(resource, PotentiallyCORSEnabled)) {
+ setState(StateError);
+ return;
+ }
+
setState(startWritingAndParsing(response));
}
@@ -74,50 +84,22 @@ void HTMLImportLoader::dataReceived(Resource*, const char* data, int length)
m_writer->addData(data, length);
}
-void HTMLImportLoader::notifyFinished(Resource*)
-{
- setState(finishWriting());
-}
-
-void HTMLImportLoader::setState(State state)
+void HTMLImportLoader::notifyFinished(Resource* resource)
{
- if (m_state == state)
+ // The writer instance indicates that a part of the document can be already loaded.
+ // We don't take such a case as an error because the partially-loaded document has been visible from script at this point.
+ if (resource->loadFailedOrCanceled() && !m_writer) {
+ setState(StateError);
return;
-
- m_state = state;
-
- if (m_state == StateReady || m_state == StateError || m_state == StateWritten) {
- if (RefPtr<DocumentWriter> writer = m_writer.release())
- writer->end();
}
- // Since DocumentWriter::end() let setState() reenter, we shouldn't refer to m_state here.
- if (state == StateReady || state == StateError)
- didFinish();
-}
-
-void HTMLImportLoader::didFinish()
-{
- for (size_t i = 0; i < m_clients.size(); ++i)
- m_clients[i]->didFinish();
-
- if (m_resource) {
- m_resource->removeClient(this);
- m_resource = 0;
- }
-
- ASSERT(!document() || !document()->parsing());
- root()->importWasDisposed();
+ setState(finishWriting());
}
HTMLImportLoader::State HTMLImportLoader::startWritingAndParsing(const ResourceResponse& response)
{
- // Current canAccess() implementation isn't sufficient for catching cross-domain redirects: http://crbug.com/256976
- if (!m_parent->document()->fetcher()->canAccess(m_resource.get()))
- return StateError;
-
- DocumentInit init = DocumentInit(response.url(), 0, root()->document()->contextDocument(), this)
- .withRegistrationContext(root()->document()->registrationContext());
+ DocumentInit init = DocumentInit(response.url(), 0, m_import->master()->contextDocument(), m_import)
+ .withRegistrationContext(m_import->master()->registrationContext());
m_importedDocument = HTMLDocument::create(init);
m_importedDocument->initContentSecurityPolicy(ContentSecurityPolicyResponseHeaders(response));
m_writer = DocumentWriter::create(m_importedDocument.get(), response.mimeType(), response.textEncodingName());
@@ -127,83 +109,73 @@ HTMLImportLoader::State HTMLImportLoader::startWritingAndParsing(const ResourceR
HTMLImportLoader::State HTMLImportLoader::finishWriting()
{
- if (!m_parent)
- return StateError;
- // The writer instance indicates that a part of the document can be already loaded.
- // We don't take such a case as an error because the partially-loaded document has been visible from script at this point.
- if (m_resource->loadFailedOrCanceled() && !m_writer)
- return StateError;
-
return StateWritten;
}
HTMLImportLoader::State HTMLImportLoader::finishParsing()
{
- if (!m_parent)
- return StateError;
return StateReady;
}
-Document* HTMLImportLoader::importedDocument() const
+void HTMLImportLoader::setState(State state)
{
- if (m_state == StateError)
- return 0;
- return m_importedDocument.get();
-}
+ if (m_state == state)
+ return;
-void HTMLImportLoader::addClient(HTMLImportLoaderClient* client)
-{
- ASSERT(kNotFound == m_clients.find(client));
- m_clients.append(client);
- if (isDone())
- client->didFinish();
-}
+ m_state = state;
-void HTMLImportLoader::removeClient(HTMLImportLoaderClient* client)
-{
- ASSERT(kNotFound != m_clients.find(client));
- m_clients.remove(m_clients.find(client));
-}
+ if (m_state == StateReady || m_state == StateError || m_state == StateWritten) {
+ if (RefPtr<DocumentWriter> writer = m_writer.release())
+ writer->end();
+ }
-void HTMLImportLoader::importDestroyed()
-{
- m_parent = 0;
- if (RefPtr<Document> document = m_importedDocument.release())
- document->setImport(0);
+ // Since DocumentWriter::end() can let setState() reenter, we shouldn't refer to m_state here.
+ if (state == StateReady || state == StateError)
+ didFinish();
}
-HTMLImportRoot* HTMLImportLoader::root()
+void HTMLImportLoader::didFinishParsing()
{
- return m_parent ? m_parent->root() : 0;
+ setState(finishParsing());
}
-HTMLImport* HTMLImportLoader::parent() const
+Document* HTMLImportLoader::importedDocument() const
{
- return m_parent;
+ if (m_state == StateError)
+ return 0;
+ return m_importedDocument.get();
}
-Document* HTMLImportLoader::document() const
+bool HTMLImportLoader::isProcessing() const
{
- return m_importedDocument.get();
+ if (!m_importedDocument)
+ return !isDone();
+ return m_importedDocument->parsing();
}
-void HTMLImportLoader::wasDetachedFromDocument()
+void HTMLImportLoader::didFinish()
{
- // For imported documens this shouldn't be called because Document::m_import is
- // cleared before Document is destroyed by HTMLImportLoader::importDestroyed().
- ASSERT_NOT_REACHED();
+ for (size_t i = 0; i < m_clients.size(); ++i)
+ m_clients[i]->didFinish();
+
+ clearResource();
+
+ ASSERT(!m_importedDocument || !m_importedDocument->parsing());
}
-void HTMLImportLoader::didFinishParsing()
+void HTMLImportLoader::addClient(HTMLImportLoaderClient* client)
{
- setState(finishParsing());
+ ASSERT(kNotFound == m_clients.find(client));
+ m_clients.append(client);
+ if (isDone())
+ client->didFinish();
}
-bool HTMLImportLoader::isProcessing() const
+void HTMLImportLoader::removeClient(HTMLImportLoaderClient* client)
{
- if (!m_importedDocument)
- return !isDone();
- return m_importedDocument->parsing();
+ ASSERT(kNotFound != m_clients.find(client));
+ m_clients.remove(m_clients.find(client));
}
+
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLImportLoader.h b/chromium/third_party/WebKit/Source/core/html/HTMLImportLoader.h
index 5406049ac84..83ea998e310 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLImportLoader.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLImportLoader.h
@@ -31,19 +31,23 @@
#ifndef HTMLImportLoader_h
#define HTMLImportLoader_h
-#include "core/fetch/RawResource.h"
-#include "core/fetch/ResourcePtr.h"
-#include "core/html/HTMLImport.h"
-#include "weborigin/KURL.h"
-#include "wtf/RefCounted.h"
+#include "core/html/HTMLImportResourceOwner.h"
#include "wtf/Vector.h"
namespace WebCore {
+class Document;
class DocumentWriter;
+class HTMLImport;
class HTMLImportLoaderClient;
-class HTMLImportLoader : public RefCounted<HTMLImportLoader>, public HTMLImport, public RawResourceClient {
+//
+// Owning imported Document lifetime. It also implements ResourceClient through HTMLImportResourceOwner
+// to feed fetched bytes to the DocumentWriter of the imported document.
+// HTMLImportLoader is owned by and shared between HTMLImportChild.
+//
+//
+class HTMLImportLoader : public RefCounted<HTMLImportLoader>, public HTMLImportResourceOwner {
public:
enum State {
StateLoading,
@@ -52,28 +56,25 @@ public:
StateReady
};
- HTMLImportLoader(HTMLImport*, const KURL&);
+ static PassRefPtr<HTMLImportLoader> create(HTMLImport*, ResourceFetcher*);
+
virtual ~HTMLImportLoader();
+ Document* document() const { return m_importedDocument.get(); }
Document* importedDocument() const;
- const KURL& url() const { return m_url; }
-
- void setResource(const ResourcePtr<RawResource>&);
void addClient(HTMLImportLoaderClient*);
void removeClient(HTMLImportLoaderClient*);
- void importDestroyed();
+
bool isDone() const { return m_state == StateReady || m_state == StateError; }
bool isLoaded() const { return m_state == StateReady; }
+ bool isProcessing() const;
- // HTMLImport
- virtual HTMLImportRoot* root() OVERRIDE;
- virtual HTMLImport* parent() const OVERRIDE;
- virtual Document* document() const OVERRIDE;
- virtual void wasDetachedFromDocument() OVERRIDE;
- virtual void didFinishParsing() OVERRIDE;
- virtual bool isProcessing() const OVERRIDE;
+ void startLoading(const ResourcePtr<RawResource>&);
+ void didFinishParsing();
+ bool isOwnedBy(const HTMLImport* import) const { return m_import == import; }
private:
+ HTMLImportLoader(HTMLImport*, ResourceFetcher*);
// RawResourceClient
virtual void responseReceived(Resource*, const ResourceResponse&) OVERRIDE;
@@ -87,11 +88,10 @@ private:
void setState(State);
void didFinish();
- HTMLImport* m_parent;
+ HTMLImport* m_import;
+ ResourceFetcher* m_fetcher;
Vector<HTMLImportLoaderClient*> m_clients;
State m_state;
- KURL m_url;
- ResourcePtr<RawResource> m_resource;
RefPtr<Document> m_importedDocument;
RefPtr<DocumentWriter> m_writer;
};
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLImportLoaderClient.h b/chromium/third_party/WebKit/Source/core/html/HTMLImportLoaderClient.h
index 0cac67f2dca..5d510d1248b 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLImportLoaderClient.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLImportLoaderClient.h
@@ -39,6 +39,6 @@ public:
virtual void didFinish() = 0;
};
-} // namespace WebCore
+}
#endif // HTMLImportLoaderClient_h
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLImportResourceOwner.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLImportResourceOwner.cpp
new file mode 100644
index 00000000000..3a3109c477d
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLImportResourceOwner.cpp
@@ -0,0 +1,60 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/html/HTMLImportResourceOwner.h"
+
+namespace WebCore {
+
+HTMLImportResourceOwner::HTMLImportResourceOwner()
+{
+}
+
+HTMLImportResourceOwner::~HTMLImportResourceOwner()
+{
+ clearResource();
+}
+
+void HTMLImportResourceOwner::setResource(const ResourcePtr<RawResource>& resource)
+{
+ ASSERT(!hasResource());
+ m_resource = resource;
+ m_resource->addClient(this);
+}
+
+void HTMLImportResourceOwner::clearResource()
+{
+ if (!hasResource())
+ return;
+ m_resource->removeClient(this);
+ m_resource = 0;
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLImportResourceOwner.h b/chromium/third_party/WebKit/Source/core/html/HTMLImportResourceOwner.h
new file mode 100644
index 00000000000..a8f5c52a193
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLImportResourceOwner.h
@@ -0,0 +1,64 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef HTMLImportResourceOwner_h
+#define HTMLImportResourceOwner_h
+
+#include "core/fetch/RawResource.h"
+#include "core/fetch/ResourcePtr.h"
+
+namespace WebCore {
+
+// A RawResourceClient implenetation which is responsible for
+// owning RawResource object and adding/removing itself as a client
+// according to its lifetime.
+//
+// FIXME: This could be geneeric ResouceOwner<ResourceType> once it is
+// found that this class is broadly useful even outside HTMLImports module.
+//
+class HTMLImportResourceOwner : public RawResourceClient {
+public:
+ HTMLImportResourceOwner();
+ virtual ~HTMLImportResourceOwner();
+
+protected:
+ const ResourcePtr<RawResource>& resource() const { return m_resource; }
+
+ void setResource(const ResourcePtr<RawResource>&);
+ void clearResource();
+ bool hasResource() const { return m_resource.get(); }
+
+private:
+ ResourcePtr<RawResource> m_resource;
+};
+
+} // namespace WebCore
+
+#endif // HTMLImportResourceOwner_h
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLImportsController.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLImportsController.cpp
index 7b1b6e28a10..bc057d50390 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLImportsController.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLImportsController.cpp
@@ -33,8 +33,8 @@
#include "core/dom/Document.h"
#include "core/fetch/ResourceFetcher.h"
-#include "core/html/HTMLImportLoader.h"
-#include "core/html/HTMLImportLoaderClient.h"
+#include "core/html/HTMLImportChild.h"
+#include "core/html/HTMLImportChildClient.h"
namespace WebCore {
@@ -43,7 +43,7 @@ void HTMLImportsController::provideTo(Document* master)
DEFINE_STATIC_LOCAL(const char*, name, ("HTMLImportsController"));
OwnPtr<HTMLImportsController> controller = adoptPtr(new HTMLImportsController(master));
master->setImport(controller.get());
- Supplement<ScriptExecutionContext>::provideTo(master, name, controller.release());
+ DocumentSupplement::provideTo(master, name, controller.release());
}
HTMLImportsController::HTMLImportsController(Document* master)
@@ -66,27 +66,35 @@ void HTMLImportsController::clear()
m_master = 0;
}
-PassRefPtr<HTMLImportLoader> HTMLImportsController::createLoader(HTMLImport* parent, FetchRequest request)
+HTMLImportChild* HTMLImportsController::createChild(const KURL& url, HTMLImport* parent, HTMLImportChildClient* client)
+{
+ OwnPtr<HTMLImportChild> loader = adoptPtr(new HTMLImportChild(url, client));
+ parent->appendChild(loader.get());
+ m_imports.append(loader.release());
+ return m_imports.last().get();
+}
+
+HTMLImportChild* HTMLImportsController::load(HTMLImport* parent, HTMLImportChildClient* client, FetchRequest request)
{
ASSERT(!request.url().isEmpty() && request.url().isValid());
- if (RefPtr<HTMLImportLoader> found = findLinkFor(request.url()))
- return found.release();
+ if (HTMLImportChild* found = findLinkFor(request.url())) {
+ HTMLImportChild* child = createChild(request.url(), parent, client);
+ child->wasAlreadyLoadedAs(found);
+ return child;
+ }
- request.setPotentiallyCrossOriginEnabled(securityOrigin(), DoNotAllowStoredCredentials);
+ request.setCrossOriginAccessControl(securityOrigin(), DoNotAllowStoredCredentials);
ResourcePtr<RawResource> resource = parent->document()->fetcher()->fetchImport(request);
if (!resource)
return 0;
- RefPtr<HTMLImportLoader> loader = adoptRef(new HTMLImportLoader(parent, request.url()));
- parent->appendChild(loader.get());
- m_imports.append(loader);
-
+ HTMLImportChild* child = createChild(request.url(), parent, client);
// We set resource after the import tree is built since
// Resource::addClient() immediately calls back to feed the bytes when the resource is cached.
- loader->setResource(resource);
+ child->startLoading(resource);
- return loader.release();
+ return child;
}
void HTMLImportsController::showSecurityErrorMessage(const String& message)
@@ -94,11 +102,12 @@ void HTMLImportsController::showSecurityErrorMessage(const String& message)
m_master->addConsoleMessage(JSMessageSource, ErrorMessageLevel, message);
}
-PassRefPtr<HTMLImportLoader> HTMLImportsController::findLinkFor(const KURL& url) const
+HTMLImportChild* HTMLImportsController::findLinkFor(const KURL& url, HTMLImport* excluding) const
{
for (size_t i = 0; i < m_imports.size(); ++i) {
- if (equalIgnoringFragmentIdentifier(m_imports[i]->url(), url))
- return m_imports[i];
+ HTMLImportChild* candidate = m_imports[i].get();
+ if (candidate != excluding && equalIgnoringFragmentIdentifier(candidate->url(), url) && !candidate->isDocumentBlocked())
+ return candidate;
}
return 0;
@@ -119,11 +128,6 @@ HTMLImportRoot* HTMLImportsController::root()
return this;
}
-HTMLImport* HTMLImportsController::parent() const
-{
- return 0;
-}
-
Document* HTMLImportsController::document() const
{
return m_master;
@@ -143,7 +147,12 @@ bool HTMLImportsController::isProcessing() const
return m_master->parsing();
}
-void HTMLImportsController::importWasDisposed()
+bool HTMLImportsController::isDone() const
+{
+ return !m_master->parsing();
+}
+
+void HTMLImportsController::blockerGone()
{
scheduleUnblock();
}
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLImportsController.h b/chromium/third_party/WebKit/Source/core/html/HTMLImportsController.h
index 0a06c4ef1fb..7cc1b92ea08 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLImportsController.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLImportsController.h
@@ -34,8 +34,8 @@
#include "core/fetch/RawResource.h"
#include "core/html/HTMLImport.h"
#include "core/html/LinkResource.h"
-#include "core/platform/Supplementable.h"
-#include "core/platform/Timer.h"
+#include "platform/Supplementable.h"
+#include "platform/Timer.h"
#include "wtf/FastAllocBase.h"
#include "wtf/PassOwnPtr.h"
#include "wtf/Vector.h"
@@ -43,12 +43,12 @@
namespace WebCore {
class FetchRequest;
-class ScriptExecutionContext;
+class ExecutionContext;
class ResourceFetcher;
-class HTMLImportLoader;
-class HTMLImportLoaderClient;
+class HTMLImportChild;
+class HTMLImportChildClient;
-class HTMLImportsController : public HTMLImportRoot, public Supplement<ScriptExecutionContext> {
+class HTMLImportsController : public HTMLImportRoot, public DocumentSupplement {
WTF_MAKE_FAST_ALLOCATED;
public:
static void provideTo(Document*);
@@ -58,18 +58,20 @@ public:
// HTMLImport
virtual HTMLImportRoot* root() OVERRIDE;
- virtual HTMLImport* parent() const OVERRIDE;
virtual Document* document() const OVERRIDE;
virtual void wasDetachedFromDocument() OVERRIDE;
virtual void didFinishParsing() OVERRIDE;
virtual bool isProcessing() const OVERRIDE;
+ virtual bool isDone() const OVERRIDE;
+
// HTMLImportRoot
- virtual void importWasDisposed() OVERRIDE;
- virtual HTMLImportsController* toController() { return this; }
+ virtual void blockerGone() OVERRIDE;
+ virtual HTMLImportsController* toController() OVERRIDE { return this; }
+ virtual HTMLImportChild* findLinkFor(const KURL&, HTMLImport* excluding = 0) const OVERRIDE;
- PassRefPtr<HTMLImportLoader> createLoader(HTMLImport* parent, FetchRequest);
+ HTMLImportChild* load(HTMLImport* parent, HTMLImportChildClient*, FetchRequest);
void showSecurityErrorMessage(const String&);
- PassRefPtr<HTMLImportLoader> findLinkFor(const KURL&) const;
+
SecurityOrigin* securityOrigin() const;
ResourceFetcher* fetcher() const;
@@ -77,13 +79,14 @@ public:
void unblockTimerFired(Timer<HTMLImportsController>*);
private:
+ HTMLImportChild* createChild(const KURL&, HTMLImport* parent, HTMLImportChildClient*);
void clear();
Document* m_master;
Timer<HTMLImportsController> m_unblockTimer;
// List of import which has been loaded or being loaded.
- typedef Vector<RefPtr<HTMLImportLoader> > ImportList;
+ typedef Vector<OwnPtr<HTMLImportChild> > ImportList;
ImportList m_imports;
};
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLInputElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLInputElement.cpp
index afa1d3fa2b9..6d2e2e8eeb6 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLInputElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLInputElement.cpp
@@ -32,24 +32,27 @@
#include "CSSPropertyNames.h"
#include "HTMLNames.h"
#include "RuntimeEnabledFeatures.h"
+#include "bindings/v8/ExceptionMessages.h"
#include "bindings/v8/ExceptionState.h"
#include "bindings/v8/ScriptEventListener.h"
#include "core/accessibility/AXObjectCache.h"
-#include "core/dom/BeforeTextInsertedEvent.h"
#include "core/dom/Document.h"
-#include "core/dom/EventNames.h"
#include "core/dom/ExceptionCode.h"
#include "core/dom/IdTargetObserver.h"
-#include "core/dom/KeyboardEvent.h"
-#include "core/dom/MouseEvent.h"
-#include "core/dom/ScopedEventQueue.h"
-#include "core/dom/TouchEvent.h"
#include "core/dom/shadow/ElementShadow.h"
#include "core/dom/shadow/InsertionPoint.h"
#include "core/dom/shadow/ShadowRoot.h"
-#include "core/editing/Editor.h"
#include "core/editing/FrameSelection.h"
+#include "core/editing/SpellChecker.h"
+#include "core/events/BeforeTextInsertedEvent.h"
+#include "core/events/KeyboardEvent.h"
+#include "core/events/MouseEvent.h"
+#include "core/events/ScopedEventQueue.h"
+#include "core/events/ThreadLocalEventNames.h"
+#include "core/events/TouchEvent.h"
#include "core/fileapi/FileList.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
#include "core/html/HTMLCollection.h"
#include "core/html/HTMLDataListElement.h"
#include "core/html/HTMLFormElement.h"
@@ -61,15 +64,17 @@
#include "core/html/forms/InputType.h"
#include "core/html/forms/SearchInputType.h"
#include "core/html/parser/HTMLParserIdioms.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameView.h"
-#include "core/page/UseCounter.h"
-#include "core/platform/DateTimeChooser.h"
-#include "core/platform/Language.h"
-#include "core/platform/LocalizedStrings.h"
-#include "core/platform/PlatformMouseEvent.h"
+#include "core/html/shadow/ShadowElementNames.h"
+#include "core/frame/UseCounter.h"
+#include "core/page/Chrome.h"
+#include "core/page/ChromeClient.h"
+#include "core/page/Page.h"
#include "core/rendering/RenderTextControlSingleLine.h"
#include "core/rendering/RenderTheme.h"
+#include "platform/DateTimeChooser.h"
+#include "platform/Language.h"
+#include "platform/PlatformMouseEvent.h"
+#include "platform/text/PlatformLocale.h"
#include "wtf/MathExtras.h"
using namespace std;
@@ -94,12 +99,12 @@ private:
// large. However, due to https://bugs.webkit.org/show_bug.cgi?id=14536 things
// get rather sluggish when a text field has a larger number of characters than
// this, even when just clicking in the text field.
-const unsigned HTMLInputElement::maximumLength = 524288;
+const int HTMLInputElement::maximumLength = 524288;
const int defaultSize = 20;
const int maxSavedResults = 256;
-HTMLInputElement::HTMLInputElement(const QualifiedName& tagName, Document& document, HTMLFormElement* form, bool createdByParser)
- : HTMLTextFormControlElement(tagName, document, form)
+HTMLInputElement::HTMLInputElement(Document& document, HTMLFormElement* form, bool createdByParser)
+ : HTMLTextFormControlElement(inputTag, document, form)
, m_size(defaultSize)
, m_maxLength(maximumLength)
, m_maxResults(-1)
@@ -109,27 +114,24 @@ HTMLInputElement::HTMLInputElement(const QualifiedName& tagName, Document& docum
, m_hasType(false)
, m_isActivatedSubmit(false)
, m_autocomplete(Uninitialized)
- , m_isAutofilled(false)
, m_hasNonEmptyList(false)
, m_stateRestored(false)
, m_parsingInProgress(createdByParser)
, m_valueAttributeWasUpdatedAfterParsing(false)
- , m_wasModifiedByUser(false)
, m_canReceiveDroppedFiles(false)
, m_hasTouchEventHandler(false)
- , m_inputType(InputType::createText(this))
+ , m_inputType(InputType::createText(*this))
, m_inputTypeView(m_inputType)
{
- ASSERT(hasTagName(inputTag) || hasTagName(isindexTag));
#if ENABLE(INPUT_MULTIPLE_FIELDS_UI)
setHasCustomStyleCallbacks();
#endif
ScriptWrappable::init(this);
}
-PassRefPtr<HTMLInputElement> HTMLInputElement::create(const QualifiedName& tagName, Document& document, HTMLFormElement* form, bool createdByParser)
+PassRefPtr<HTMLInputElement> HTMLInputElement::create(Document& document, HTMLFormElement* form, bool createdByParser)
{
- RefPtr<HTMLInputElement> inputElement = adoptRef(new HTMLInputElement(tagName, document, form, createdByParser));
+ RefPtr<HTMLInputElement> inputElement = adoptRef(new HTMLInputElement(document, form, createdByParser));
inputElement->ensureUserAgentShadowRoot();
return inputElement.release();
}
@@ -141,16 +143,18 @@ HTMLImageLoader* HTMLInputElement::imageLoader()
return m_imageLoader.get();
}
-void HTMLInputElement::didAddUserAgentShadowRoot(ShadowRoot*)
+void HTMLInputElement::didAddUserAgentShadowRoot(ShadowRoot&)
{
- m_inputType->createShadowSubtree();
+ m_inputTypeView->createShadowSubtree();
}
void HTMLInputElement::didAddShadowRoot(ShadowRoot& root)
{
if (!root.isOldestAuthorShadowRoot())
return;
- m_inputTypeView = InputTypeView::create(this);
+ m_inputTypeView->destroyShadowSubtree();
+ m_inputTypeView = InputTypeView::create(*this);
+ lazyReattachIfAttached();
}
HTMLInputElement::~HTMLInputElement()
@@ -176,19 +180,9 @@ Vector<FileChooserFileInfo> HTMLInputElement::filesFromFileInputFormControlState
return FileInputType::filesFromFormControlState(state);
}
-HTMLElement* HTMLInputElement::containerElement() const
-{
- return m_inputType->containerElement();
-}
-
-HTMLElement* HTMLInputElement::innerTextElement() const
-{
- return m_inputType->innerTextElement();
-}
-
HTMLElement* HTMLInputElement::passwordGeneratorButtonElement() const
{
- return m_inputType->passwordGeneratorButtonElement();
+ return toHTMLElement(userAgentShadowRoot()->getElementById(ShadowElementNames::passwordGenerator()));
}
bool HTMLInputElement::shouldAutocomplete() const
@@ -250,7 +244,7 @@ bool HTMLInputElement::tooLong(const String& value, NeedsToCheckDirtyFlag check)
if (check == CheckDirtyFlag) {
// Return false for the default value or a value set by a script even if
// it is longer than maxLength.
- if (!hasDirtyValue() || !m_wasModifiedByUser)
+ if (!hasDirtyValue() || !lastChangeWasUserEdit())
return false;
}
return value.length() > static_cast<unsigned>(max);
@@ -307,14 +301,14 @@ Decimal HTMLInputElement::findClosestTickMarkValue(const Decimal& value)
return m_inputType->findClosestTickMarkValue(value);
}
-void HTMLInputElement::stepUp(int n, ExceptionState& es)
+void HTMLInputElement::stepUp(int n, ExceptionState& exceptionState)
{
- m_inputType->stepUp(n, es);
+ m_inputType->stepUp(n, exceptionState);
}
-void HTMLInputElement::stepDown(int n, ExceptionState& es)
+void HTMLInputElement::stepDown(int n, ExceptionState& exceptionState)
{
- m_inputType->stepUp(-n, es);
+ m_inputType->stepUp(-n, exceptionState);
}
void HTMLInputElement::blur()
@@ -361,7 +355,7 @@ void HTMLInputElement::beginEditing()
return;
if (Frame* frame = document().frame())
- frame->editor().textAreaOrTextFieldDidBeginEditing(this);
+ frame->spellChecker().didBeginEditing(this);
}
void HTMLInputElement::endEditing()
@@ -369,8 +363,11 @@ void HTMLInputElement::endEditing()
if (!isTextField())
return;
- if (Frame* frame = document().frame())
- frame->editor().textFieldDidEndEditing(this);
+ if (Frame* frame = document().frame()) {
+ frame->spellChecker().didEndEditingOnTextField(this);
+ if (Page* page = frame->page())
+ page->chrome().client().didEndEditingOnTextField(*this);
+ }
}
bool HTMLInputElement::shouldUseInputMethod()
@@ -390,7 +387,7 @@ void HTMLInputElement::handleBlurEvent()
m_inputTypeView->handleBlurEvent();
}
-void HTMLInputElement::setType(const String& type)
+void HTMLInputElement::setType(const AtomicString& type)
{
// FIXME: This should just call setAttribute. No reason to handle the empty string specially.
// We should write a test case to show that setting to the empty string does not remove the
@@ -417,24 +414,21 @@ void HTMLInputElement::updateType()
return;
}
- RefPtr<InputType> newType = InputType::create(this, newTypeName);
+ RefPtr<InputType> newType = InputType::create(*this, newTypeName);
removeFromRadioButtonGroup();
bool didStoreValue = m_inputType->storesValueSeparateFromAttribute();
bool didRespectHeightAndWidth = m_inputType->shouldRespectHeightAndWidthAttributes();
- m_inputType->destroyShadowSubtree();
-
- bool wasAttached = attached();
- if (wasAttached)
- detach();
+ m_inputTypeView->destroyShadowSubtree();
+ lazyReattachIfAttached();
m_inputType = newType.release();
if (hasAuthorShadowRoot())
- m_inputTypeView = InputTypeView::create(this);
+ m_inputTypeView = InputTypeView::create(*this);
else
m_inputTypeView = m_inputType;
- m_inputType->createShadowSubtree();
+ m_inputTypeView->createShadowSubtree();
bool hasTouchEventHandler = m_inputTypeView->hasTouchEventHandler();
if (hasTouchEventHandler != m_hasTouchEventHandler) {
@@ -450,7 +444,7 @@ void HTMLInputElement::updateType()
bool willStoreValue = m_inputType->storesValueSeparateFromAttribute();
if (didStoreValue && !willStoreValue && hasDirtyValue()) {
- setAttribute(valueAttr, m_valueIfDirty);
+ setAttribute(valueAttr, AtomicString(m_valueIfDirty));
m_valueIfDirty = String();
}
if (!didStoreValue && willStoreValue) {
@@ -460,9 +454,7 @@ void HTMLInputElement::updateType()
updateValueIfNeeded();
setFormControlValueMatchesRenderer(false);
- m_inputType->updateInnerTextValue();
-
- m_wasModifiedByUser = false;
+ m_inputTypeView->updateView();
if (didRespectHeightAndWidth != m_inputType->shouldRespectHeightAndWidthAttributes()) {
ASSERT(elementData());
@@ -474,11 +466,8 @@ void HTMLInputElement::updateType()
attributeChanged(alignAttr, align->value());
}
- if (wasAttached) {
- lazyAttach();
- if (document().focusedElement() == this)
- document().updateFocusAppearanceSoon(true /* restore selection */);
- }
+ if (document().focusedElement() == this)
+ document().updateFocusAppearanceSoon(true /* restore selection */);
setChangedSinceLastFormControlChangeEvent(false);
@@ -530,73 +519,73 @@ bool HTMLInputElement::canHaveSelection() const
return isTextField();
}
-int HTMLInputElement::selectionStartForBinding(ExceptionState& es) const
+int HTMLInputElement::selectionStartForBinding(ExceptionState& exceptionState) const
{
- if (!canHaveSelection()) {
- es.throwDOMException(InvalidStateError);
+ if (!m_inputType->supportsSelectionAPI()) {
+ exceptionState.throwDOMException(InvalidStateError, "The input element's type ('" + m_inputType->formControlType() + "') does not support selection.");
return 0;
}
return HTMLTextFormControlElement::selectionStart();
}
-int HTMLInputElement::selectionEndForBinding(ExceptionState& es) const
+int HTMLInputElement::selectionEndForBinding(ExceptionState& exceptionState) const
{
- if (!canHaveSelection()) {
- es.throwDOMException(InvalidStateError);
+ if (!m_inputType->supportsSelectionAPI()) {
+ exceptionState.throwDOMException(InvalidStateError, "The input element's type ('" + m_inputType->formControlType() + "') does not support selection.");
return 0;
}
return HTMLTextFormControlElement::selectionEnd();
}
-String HTMLInputElement::selectionDirectionForBinding(ExceptionState& es) const
+String HTMLInputElement::selectionDirectionForBinding(ExceptionState& exceptionState) const
{
- if (!canHaveSelection()) {
- es.throwDOMException(InvalidStateError);
+ if (!m_inputType->supportsSelectionAPI()) {
+ exceptionState.throwDOMException(InvalidStateError, "The input element's type ('" + m_inputType->formControlType() + "') does not support selection.");
return String();
}
return HTMLTextFormControlElement::selectionDirection();
}
-void HTMLInputElement::setSelectionStartForBinding(int start, ExceptionState& es)
+void HTMLInputElement::setSelectionStartForBinding(int start, ExceptionState& exceptionState)
{
- if (!canHaveSelection()) {
- es.throwDOMException(InvalidStateError);
+ if (!m_inputType->supportsSelectionAPI()) {
+ exceptionState.throwDOMException(InvalidStateError, "The input element's type ('" + m_inputType->formControlType() + "') does not support selection.");
return;
}
HTMLTextFormControlElement::setSelectionStart(start);
}
-void HTMLInputElement::setSelectionEndForBinding(int end, ExceptionState& es)
+void HTMLInputElement::setSelectionEndForBinding(int end, ExceptionState& exceptionState)
{
- if (!canHaveSelection()) {
- es.throwDOMException(InvalidStateError);
+ if (!m_inputType->supportsSelectionAPI()) {
+ exceptionState.throwDOMException(InvalidStateError, "The input element's type ('" + m_inputType->formControlType() + "') does not support selection.");
return;
}
HTMLTextFormControlElement::setSelectionEnd(end);
}
-void HTMLInputElement::setSelectionDirectionForBinding(const String& direction, ExceptionState& es)
+void HTMLInputElement::setSelectionDirectionForBinding(const String& direction, ExceptionState& exceptionState)
{
- if (!canHaveSelection()) {
- es.throwDOMException(InvalidStateError);
+ if (!m_inputType->supportsSelectionAPI()) {
+ exceptionState.throwDOMException(InvalidStateError, "The input element's type ('" + m_inputType->formControlType() + "') does not support selection.");
return;
}
HTMLTextFormControlElement::setSelectionDirection(direction);
}
-void HTMLInputElement::setSelectionRangeForBinding(int start, int end, ExceptionState& es)
+void HTMLInputElement::setSelectionRangeForBinding(int start, int end, ExceptionState& exceptionState)
{
- if (!canHaveSelection()) {
- es.throwDOMException(InvalidStateError);
+ if (!m_inputType->supportsSelectionAPI()) {
+ exceptionState.throwDOMException(InvalidStateError, "The input element's type ('" + m_inputType->formControlType() + "') does not support selection.");
return;
}
HTMLTextFormControlElement::setSelectionRange(start, end);
}
-void HTMLInputElement::setSelectionRangeForBinding(int start, int end, const String& direction, ExceptionState& es)
+void HTMLInputElement::setSelectionRangeForBinding(int start, int end, const String& direction, ExceptionState& exceptionState)
{
- if (!canHaveSelection()) {
- es.throwDOMException(InvalidStateError);
+ if (!m_inputType->supportsSelectionAPI()) {
+ exceptionState.throwDOMException(InvalidStateError, "The input element's type ('" + m_inputType->formControlType() + "') does not support selection.");
return;
}
HTMLTextFormControlElement::setSelectionRange(start, end, direction);
@@ -690,7 +679,7 @@ void HTMLInputElement::parseAttribute(const QualifiedName& name, const AtomicStr
// FIXME: ignore for the moment
} else if (name == onsearchAttr) {
// Search field and slider attributes all just cause updateFromElement to be called through style recalcing.
- setAttributeEventListener(eventNames().searchEvent, createAttributeEventListener(this, name, value));
+ setAttributeEventListener(EventTypeNames::search, createAttributeEventListener(this, name, value));
} else if (name == resultsAttr) {
int oldResults = m_maxResults;
m_maxResults = !value.isNull() ? std::min(value.toInt(), maxSavedResults) : -1;
@@ -699,32 +688,32 @@ void HTMLInputElement::parseAttribute(const QualifiedName& name, const AtomicStr
if (m_maxResults != oldResults && (m_maxResults <= 0 || oldResults <= 0))
lazyReattachIfAttached();
setNeedsStyleRecalc();
- UseCounter::count(&document(), UseCounter::ResultsAttribute);
+ UseCounter::count(document(), UseCounter::ResultsAttribute);
} else if (name == incrementalAttr) {
setNeedsStyleRecalc();
- UseCounter::count(&document(), UseCounter::IncrementalAttribute);
+ UseCounter::count(document(), UseCounter::IncrementalAttribute);
} else if (name == minAttr) {
m_inputTypeView->minOrMaxAttributeChanged();
m_inputType->sanitizeValueInResponseToMinOrMaxAttributeChange();
setNeedsValidityCheck();
- UseCounter::count(&document(), UseCounter::MinAttribute);
+ UseCounter::count(document(), UseCounter::MinAttribute);
} else if (name == maxAttr) {
m_inputTypeView->minOrMaxAttributeChanged();
setNeedsValidityCheck();
- UseCounter::count(&document(), UseCounter::MaxAttribute);
+ UseCounter::count(document(), UseCounter::MaxAttribute);
} else if (name == multipleAttr) {
m_inputTypeView->multipleAttributeChanged();
setNeedsValidityCheck();
} else if (name == stepAttr) {
m_inputTypeView->stepAttributeChanged();
setNeedsValidityCheck();
- UseCounter::count(&document(), UseCounter::StepAttribute);
+ UseCounter::count(document(), UseCounter::StepAttribute);
} else if (name == patternAttr) {
setNeedsValidityCheck();
- UseCounter::count(&document(), UseCounter::PatternAttribute);
+ UseCounter::count(document(), UseCounter::PatternAttribute);
} else if (name == precisionAttr) {
setNeedsValidityCheck();
- UseCounter::count(&document(), UseCounter::PrecisionAttribute);
+ UseCounter::count(document(), UseCounter::PrecisionAttribute);
} else if (name == disabledAttr) {
HTMLTextFormControlElement::parseAttribute(name, value);
m_inputTypeView->disabledAttributeChanged();
@@ -737,7 +726,7 @@ void HTMLInputElement::parseAttribute(const QualifiedName& name, const AtomicStr
resetListAttributeTargetObserver();
listAttributeTargetChanged();
}
- UseCounter::count(&document(), UseCounter::ListAttribute);
+ UseCounter::count(document(), UseCounter::ListAttribute);
}
#if ENABLE(INPUT_SPEECH)
else if (name == webkitspeechAttr) {
@@ -746,18 +735,18 @@ void HTMLInputElement::parseAttribute(const QualifiedName& name, const AtomicStr
// styles depending on whether the speech button is visible or
// not. So we reset the whole thing and recreate to get the right
// styles and layout.
- m_inputType->destroyShadowSubtree();
+ m_inputTypeView->destroyShadowSubtree();
lazyReattachIfAttached();
- m_inputType->createShadowSubtree();
+ m_inputTypeView->createShadowSubtree();
setFormControlValueMatchesRenderer(false);
}
- UseCounter::count(&document(), UseCounter::PrefixedSpeechAttribute);
+ UseCounter::count(document(), UseCounter::PrefixedSpeechAttribute);
} else if (name == onwebkitspeechchangeAttr)
- setAttributeEventListener(eventNames().webkitspeechchangeEvent, createAttributeEventListener(this, name, value));
+ setAttributeEventListener(EventTypeNames::webkitspeechchange, createAttributeEventListener(this, name, value));
#endif
else if (name == webkitdirectoryAttr) {
HTMLTextFormControlElement::parseAttribute(name, value);
- UseCounter::count(&document(), UseCounter::PrefixedDirectoryAttribute);
+ UseCounter::count(document(), UseCounter::PrefixedDirectoryAttribute);
}
else
HTMLTextFormControlElement::parseAttribute(name, value);
@@ -793,7 +782,7 @@ void HTMLInputElement::attach(const AttachContext& context)
HTMLTextFormControlElement::attach(context);
- m_inputTypeView->attach();
+ m_inputTypeView->startResourceLoading();
m_inputType->countUsage();
if (document().focusedElement() == this)
@@ -804,7 +793,7 @@ void HTMLInputElement::detach(const AttachContext& context)
{
HTMLTextFormControlElement::detach(context);
setFormControlValueMatchesRenderer(false);
- m_inputType->detach();
+ m_inputTypeView->closePopupView();
}
String HTMLInputElement::altText() const
@@ -819,15 +808,13 @@ String HTMLInputElement::altText() const
if (alt.isNull())
alt = getAttribute(valueAttr);
if (alt.isEmpty())
- alt = inputElementAltText();
+ alt = locale().queryString(blink::WebLocalizedString::InputElementAltText);
return alt;
}
-bool HTMLInputElement::isSuccessfulSubmitButton() const
+bool HTMLInputElement::canBeSuccessfulSubmitButton() const
{
- // HTML spec says that buttons must have names to be considered successful.
- // However, other browsers do not impose this constraint. So we do not.
- return !isDisabledFormControl() && m_inputType->canBeSuccessfulSubmitButton();
+ return m_inputType->canBeSuccessfulSubmitButton();
}
bool HTMLInputElement::isActivatedSubmit() const
@@ -845,12 +832,16 @@ bool HTMLInputElement::appendFormData(FormDataList& encoding, bool multipart)
return m_inputType->isFormDataAppendable() && m_inputType->appendFormData(encoding, multipart);
}
-void HTMLInputElement::reset()
+String HTMLInputElement::resultForDialogSubmit()
+{
+ return m_inputType->resultForDialogSubmit();
+}
+
+void HTMLInputElement::resetImpl()
{
if (m_inputType->storesValueSeparateFromAttribute())
setValue(String());
- setAutofilled(false);
setChecked(hasAttribute(checkedAttr));
m_reflectsCheckedAttribute = true;
}
@@ -930,7 +921,6 @@ void HTMLInputElement::copyNonAttributePropertiesFromElement(const Element& sour
const HTMLInputElement& sourceElement = static_cast<const HTMLInputElement&>(source);
m_valueIfDirty = sourceElement.m_valueIfDirty;
- m_wasModifiedByUser = false;
setChecked(sourceElement.m_isChecked);
m_reflectsCheckedAttribute = sourceElement.m_reflectsCheckedAttribute;
m_isIndeterminate = sourceElement.m_isIndeterminate;
@@ -938,7 +928,7 @@ void HTMLInputElement::copyNonAttributePropertiesFromElement(const Element& sour
HTMLTextFormControlElement::copyNonAttributePropertiesFromElement(source);
setFormControlValueMatchesRenderer(false);
- m_inputTypeView->updateInnerTextValue();
+ m_inputTypeView->updateView();
}
String HTMLInputElement::value() const
@@ -986,7 +976,7 @@ void HTMLInputElement::setSuggestedValue(const String& value)
setFormControlValueMatchesRenderer(false);
m_suggestedValue = sanitizeValue(value);
setNeedsStyleRecalc();
- m_inputType->updateInnerTextValue();
+ m_inputTypeView->updateView();
}
void HTMLInputElement::setEditingValue(const String& value)
@@ -1005,10 +995,10 @@ void HTMLInputElement::setEditingValue(const String& value)
dispatchInputEvent();
}
-void HTMLInputElement::setValue(const String& value, ExceptionState& es, TextFieldEventBehavior eventBehavior)
+void HTMLInputElement::setValue(const String& value, ExceptionState& exceptionState, TextFieldEventBehavior eventBehavior)
{
if (isFileUpload() && !value.isEmpty()) {
- es.throwDOMException(InvalidStateError);
+ exceptionState.throwDOMException(InvalidStateError, "This input element accepts a filename, which may only be programatically set to the empty string.");
return;
}
setValue(value, eventBehavior);
@@ -1042,7 +1032,6 @@ void HTMLInputElement::setValue(const String& value, TextFieldEventBehavior even
void HTMLInputElement::setValueInternal(const String& sanitizedValue, TextFieldEventBehavior eventBehavior)
{
m_valueIfDirty = sanitizedValue;
- m_wasModifiedByUser = eventBehavior != DispatchNoEvent;
setNeedsValidityCheck();
}
@@ -1051,9 +1040,9 @@ double HTMLInputElement::valueAsDate() const
return m_inputType->valueAsDate();
}
-void HTMLInputElement::setValueAsDate(double value, ExceptionState& es)
+void HTMLInputElement::setValueAsDate(double value, ExceptionState& exceptionState)
{
- m_inputType->setValueAsDate(value, es);
+ m_inputType->setValueAsDate(value, exceptionState);
}
double HTMLInputElement::valueAsNumber() const
@@ -1061,13 +1050,13 @@ double HTMLInputElement::valueAsNumber() const
return m_inputType->valueAsDouble();
}
-void HTMLInputElement::setValueAsNumber(double newValue, ExceptionState& es, TextFieldEventBehavior eventBehavior)
+void HTMLInputElement::setValueAsNumber(double newValue, ExceptionState& exceptionState, TextFieldEventBehavior eventBehavior)
{
if (!std::isfinite(newValue)) {
- es.throwDOMException(NotSupportedError);
+ exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::notAFiniteNumber(newValue));
return;
}
- m_inputType->setValueAsDouble(newValue, eventBehavior, es);
+ m_inputType->setValueAsDouble(newValue, eventBehavior, exceptionState);
}
void HTMLInputElement::setValueFromRenderer(const String& value)
@@ -1083,7 +1072,6 @@ void HTMLInputElement::setValueFromRenderer(const String& value)
m_valueIfDirty = value;
setFormControlValueMatchesRenderer(true);
- m_wasModifiedByUser = true;
// Input event is fired by the Node::defaultEventHandler for editable controls.
if (!isTextField())
@@ -1098,11 +1086,11 @@ void HTMLInputElement::setValueFromRenderer(const String& value)
void* HTMLInputElement::preDispatchEventHandler(Event* event)
{
- if (event->type() == eventNames().textInputEvent && m_inputTypeView->shouldSubmitImplicitly(event)) {
+ if (event->type() == EventTypeNames::textInput && m_inputTypeView->shouldSubmitImplicitly(event)) {
event->stopPropagation();
return 0;
}
- if (event->type() != eventNames().clickEvent)
+ if (event->type() != EventTypeNames::click)
return 0;
if (!event->isMouseEvent() || toMouseEvent(event)->button() != LeftButton)
return 0;
@@ -1120,7 +1108,7 @@ void HTMLInputElement::postDispatchEventHandler(Event* event, void* dataFromPreD
void HTMLInputElement::defaultEventHandler(Event* evt)
{
- if (evt->isMouseEvent() && evt->type() == eventNames().clickEvent && toMouseEvent(evt)->button() == LeftButton) {
+ if (evt->isMouseEvent() && evt->type() == EventTypeNames::click && toMouseEvent(evt)->button() == LeftButton) {
m_inputTypeView->handleClickEvent(toMouseEvent(evt));
if (evt->defaultHandled())
return;
@@ -1132,7 +1120,7 @@ void HTMLInputElement::defaultEventHandler(Event* evt)
return;
}
- if (evt->isKeyboardEvent() && evt->type() == eventNames().keydownEvent) {
+ if (evt->isKeyboardEvent() && evt->type() == EventTypeNames::keydown) {
m_inputTypeView->handleKeydownEvent(toKeyboardEvent(evt));
if (evt->defaultHandled())
return;
@@ -1140,7 +1128,7 @@ void HTMLInputElement::defaultEventHandler(Event* evt)
// Call the base event handler before any of our own event handling for almost all events in text fields.
// Makes editing keyboard handling take precedence over the keydown and keypress handling in this function.
- bool callBaseClassEarly = isTextField() && (evt->type() == eventNames().keydownEvent || evt->type() == eventNames().keypressEvent);
+ bool callBaseClassEarly = isTextField() && (evt->type() == EventTypeNames::keydown || evt->type() == EventTypeNames::keypress);
if (callBaseClassEarly) {
HTMLTextFormControlElement::defaultEventHandler(evt);
if (evt->defaultHandled())
@@ -1151,7 +1139,7 @@ void HTMLInputElement::defaultEventHandler(Event* evt)
// actually submitting the form. For reset inputs, the form is reset. These events are sent when the user clicks
// on the element, or presses enter while it is the active element. JavaScript code wishing to activate the element
// must dispatch a DOMActivate event - a click event will not do the job.
- if (evt->type() == eventNames().DOMActivateEvent) {
+ if (evt->type() == EventTypeNames::DOMActivate) {
m_inputType->handleDOMActivateEvent(evt);
if (evt->defaultHandled())
return;
@@ -1159,13 +1147,13 @@ void HTMLInputElement::defaultEventHandler(Event* evt)
// Use key press event here since sending simulated mouse events
// on key down blocks the proper sending of the key press event.
- if (evt->isKeyboardEvent() && evt->type() == eventNames().keypressEvent) {
+ if (evt->isKeyboardEvent() && evt->type() == EventTypeNames::keypress) {
m_inputTypeView->handleKeypressEvent(toKeyboardEvent(evt));
if (evt->defaultHandled())
return;
}
- if (evt->isKeyboardEvent() && evt->type() == eventNames().keyupEvent) {
+ if (evt->isKeyboardEvent() && evt->type() == EventTypeNames::keyup) {
m_inputTypeView->handleKeyupEvent(toKeyboardEvent(evt));
if (evt->defaultHandled())
return;
@@ -1191,7 +1179,7 @@ void HTMLInputElement::defaultEventHandler(Event* evt)
if (evt->isBeforeTextInsertedEvent())
m_inputTypeView->handleBeforeTextInsertedEvent(static_cast<BeforeTextInsertedEvent*>(evt));
- if (evt->isMouseEvent() && evt->type() == eventNames().mousedownEvent) {
+ if (evt->isMouseEvent() && evt->type() == EventTypeNames::mousedown) {
m_inputTypeView->handleMouseDownEvent(toMouseEvent(evt));
if (evt->defaultHandled())
return;
@@ -1217,12 +1205,12 @@ bool HTMLInputElement::isURLAttribute(const Attribute& attribute) const
return attribute.name() == srcAttr || attribute.name() == formactionAttr || HTMLTextFormControlElement::isURLAttribute(attribute);
}
-String HTMLInputElement::defaultValue() const
+const AtomicString& HTMLInputElement::defaultValue() const
{
return fastGetAttribute(valueAttr);
}
-void HTMLInputElement::setDefaultValue(const String &value)
+void HTMLInputElement::setDefaultValue(const AtomicString& value)
{
setAttribute(valueAttr, value);
}
@@ -1281,12 +1269,12 @@ Vector<String> HTMLInputElement::acceptFileExtensions()
return parseAcceptAttribute(fastGetAttribute(acceptAttr), isValidFileExtension);
}
-String HTMLInputElement::accept() const
+const AtomicString& HTMLInputElement::accept() const
{
return fastGetAttribute(acceptAttr);
}
-String HTMLInputElement::alt() const
+const AtomicString& HTMLInputElement::alt() const
{
return fastGetAttribute(altAttr);
}
@@ -1296,12 +1284,12 @@ int HTMLInputElement::maxLength() const
return m_maxLength;
}
-void HTMLInputElement::setMaxLength(int maxLength, ExceptionState& es)
+void HTMLInputElement::setMaxLength(int maxLength, ExceptionState& exceptionState)
{
if (maxLength < 0)
- es.throwDOMException(IndexSizeError);
+ exceptionState.throwDOMException(IndexSizeError, "The value provided (" + String::number(maxLength) + ") is negative.");
else
- setAttribute(maxlengthAttr, String::number(maxLength));
+ setIntegralAttribute(maxlengthAttr, maxLength);
}
bool HTMLInputElement::multiple() const
@@ -1311,13 +1299,13 @@ bool HTMLInputElement::multiple() const
void HTMLInputElement::setSize(unsigned size)
{
- setAttribute(sizeAttr, String::number(size));
+ setUnsignedIntegralAttribute(sizeAttr, size);
}
-void HTMLInputElement::setSize(unsigned size, ExceptionState& es)
+void HTMLInputElement::setSize(unsigned size, ExceptionState& exceptionState)
{
if (!size)
- es.throwDOMException(IndexSizeError);
+ exceptionState.throwDOMException(IndexSizeError, "The value provided is 0, which is an invalid size.");
else
setSize(size);
}
@@ -1327,15 +1315,6 @@ KURL HTMLInputElement::src() const
return document().completeURL(fastGetAttribute(srcAttr));
}
-void HTMLInputElement::setAutofilled(bool autofilled)
-{
- if (autofilled == m_isAutofilled)
- return;
-
- m_isAutofilled = autofilled;
- setNeedsStyleRecalc();
-}
-
FileList* HTMLInputElement::files()
{
return m_inputType->files();
@@ -1419,7 +1398,7 @@ void HTMLInputElement::onSearch()
ASSERT(isSearchField());
if (m_inputType)
static_cast<SearchInputType*>(m_inputType.get())->stopSearchEventTimer();
- dispatchEvent(Event::createBubble(eventNames().searchEvent));
+ dispatchEvent(Event::createBubble(EventTypeNames::search));
}
void HTMLInputElement::updateClearButtonVisibility()
@@ -1457,17 +1436,15 @@ void HTMLInputElement::removedFrom(ContainerNode* insertionPoint)
resetListAttributeTargetObserver();
}
-void HTMLInputElement::didMoveToNewDocument(Document* oldDocument)
+void HTMLInputElement::didMoveToNewDocument(Document& oldDocument)
{
if (hasImageLoader())
imageLoader()->elementDidMoveToNewDocument();
- if (oldDocument) {
- if (isRadioButton())
- oldDocument->formController()->checkedRadioButtons().removeButton(this);
- if (m_hasTouchEventHandler)
- oldDocument->didRemoveEventTargetNode(this);
- }
+ if (isRadioButton())
+ oldDocument.formController()->checkedRadioButtons().removeButton(this);
+ if (m_hasTouchEventHandler)
+ oldDocument.didRemoveEventTargetNode(this);
if (m_hasTouchEventHandler)
document().didAddTouchEventHandler(this);
@@ -1524,6 +1501,19 @@ HTMLDataListElement* HTMLInputElement::dataList() const
return toHTMLDataListElement(element);
}
+bool HTMLInputElement::hasValidDataListOptions() const
+{
+ HTMLDataListElement* dataList = this->dataList();
+ if (!dataList)
+ return false;
+ RefPtr<HTMLCollection> options = dataList->options();
+ for (unsigned i = 0; HTMLOptionElement* option = toHTMLOptionElement(options->item(i)); ++i) {
+ if (isValidValue(option->value()))
+ return true;
+ }
+ return false;
+}
+
void HTMLInputElement::resetListAttributeTargetObserver()
{
if (inDocument())
@@ -1726,9 +1716,9 @@ bool HTMLInputElement::capture() const
// supposed to be used as a boolean.
bool hasDeprecatedUsage = !fastGetAttribute(captureAttr).isNull();
if (hasDeprecatedUsage)
- UseCounter::countDeprecation(&document(), UseCounter::CaptureAttributeAsEnum);
+ UseCounter::countDeprecation(document(), UseCounter::CaptureAttributeAsEnum);
else
- UseCounter::count(&document(), UseCounter::CaptureAttributeAsEnum);
+ UseCounter::count(document(), UseCounter::CaptureAttributeAsEnum);
return true;
}
@@ -1784,12 +1774,12 @@ unsigned HTMLInputElement::width() const
void HTMLInputElement::setHeight(unsigned height)
{
- setAttribute(heightAttr, String::number(height));
+ setUnsignedIntegralAttribute(heightAttr, height);
}
void HTMLInputElement::setWidth(unsigned width)
{
- setAttribute(widthAttr, String::number(width));
+ setUnsignedIntegralAttribute(widthAttr, width);
}
PassOwnPtr<ListAttributeTargetObserver> ListAttributeTargetObserver::create(const AtomicString& id, HTMLInputElement* element)
@@ -1808,24 +1798,24 @@ void ListAttributeTargetObserver::idTargetChanged()
m_element->listAttributeTargetChanged();
}
-void HTMLInputElement::setRangeText(const String& replacement, ExceptionState& es)
+void HTMLInputElement::setRangeText(const String& replacement, ExceptionState& exceptionState)
{
if (!m_inputType->supportsSelectionAPI()) {
- es.throwDOMException(InvalidStateError);
+ exceptionState.throwDOMException(InvalidStateError, "The input element's type ('" + m_inputType->formControlType() + "') does not support selection.");
return;
}
- HTMLTextFormControlElement::setRangeText(replacement, es);
+ HTMLTextFormControlElement::setRangeText(replacement, exceptionState);
}
-void HTMLInputElement::setRangeText(const String& replacement, unsigned start, unsigned end, const String& selectionMode, ExceptionState& es)
+void HTMLInputElement::setRangeText(const String& replacement, unsigned start, unsigned end, const String& selectionMode, ExceptionState& exceptionState)
{
if (!m_inputType->supportsSelectionAPI()) {
- es.throwDOMException(InvalidStateError);
+ exceptionState.throwDOMException(InvalidStateError, "The input element's type ('" + m_inputType->formControlType() + "') does not support selection.");
return;
}
- HTMLTextFormControlElement::setRangeText(replacement, start, end, selectionMode, es);
+ HTMLTextFormControlElement::setRangeText(replacement, start, end, selectionMode, exceptionState);
}
bool HTMLInputElement::setupDateTimeChooserParameters(DateTimeChooserParameters& parameters)
@@ -1855,6 +1845,7 @@ bool HTMLInputElement::setupDateTimeChooserParameters(DateTimeChooserParameters&
parameters.anchorRectInRootView = document().view()->contentsToRootView(pixelSnappedBoundingBox());
parameters.currentValue = value();
+ parameters.doubleValue = m_inputType->valueAsDouble();
parameters.isAnchorElementRTL = computedStyle()->direction() == RTL;
if (RuntimeEnabledFeatures::dataListElementEnabled()) {
if (HTMLDataListElement* dataList = this->dataList()) {
@@ -1862,9 +1853,13 @@ bool HTMLInputElement::setupDateTimeChooserParameters(DateTimeChooserParameters&
for (unsigned i = 0; HTMLOptionElement* option = toHTMLOptionElement(options->item(i)); ++i) {
if (!isValidValue(option->value()))
continue;
- parameters.suggestionValues.append(sanitizeValue(option->value()));
- parameters.localizedSuggestionValues.append(localizeValue(option->value()));
- parameters.suggestionLabels.append(option->value() == option->label() ? String() : option->label());
+ DateTimeSuggestion suggestion;
+ suggestion.value = m_inputType->parseToNumber(option->value(), Decimal::nan()).toDouble();
+ if (std::isnan(suggestion.value))
+ continue;
+ suggestion.localizedValue = localizeValue(option->value());
+ suggestion.label = option->value() == option->label() ? String() : option->label();
+ parameters.suggestions.append(suggestion);
}
}
}
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLInputElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLInputElement.h
index 5bf002bed17..4e61ec102c2 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLInputElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLInputElement.h
@@ -27,7 +27,7 @@
#include "core/html/HTMLTextFormControlElement.h"
#include "core/html/forms/StepRange.h"
-#include "core/platform/FileChooser.h"
+#include "platform/FileChooser.h"
namespace WebCore {
@@ -47,7 +47,7 @@ struct DateTimeChooserParameters;
class HTMLInputElement : public HTMLTextFormControlElement {
public:
- static PassRefPtr<HTMLInputElement> create(const QualifiedName&, Document&, HTMLFormElement*, bool createdByParser);
+ static PassRefPtr<HTMLInputElement> create(Document&, HTMLFormElement*, bool createdByParser);
virtual ~HTMLInputElement();
DEFINE_ATTRIBUTE_EVENT_LISTENER(webkitspeechchange);
@@ -80,8 +80,8 @@ public:
// Implementations of HTMLInputElement::stepUp() and stepDown().
void stepUp(int, ExceptionState&);
void stepDown(int, ExceptionState&);
- void stepUp(ExceptionState& es) { stepUp(1, es); }
- void stepDown(ExceptionState& es) { stepDown(1, es); }
+ void stepUp(ExceptionState& exceptionState) { stepUp(1, exceptionState); }
+ void stepDown(ExceptionState& exceptionState) { stepDown(1, exceptionState); }
// stepUp()/stepDown() for user-interaction.
bool isSteppable() const;
@@ -119,8 +119,6 @@ public:
bool isSpeechEnabled() const;
#endif
- HTMLElement* containerElement() const;
- virtual HTMLElement* innerTextElement() const;
HTMLElement* passwordGeneratorButtonElement() const;
bool checked() const { return m_isChecked; }
@@ -136,7 +134,7 @@ public:
int size() const;
bool sizeShouldIncludeDecoration(int& preferredSize) const;
- void setType(const String&);
+ void setType(const AtomicString&);
String value() const;
void setValue(const String&, ExceptionState&, TextFieldEventBehavior = DispatchNoEvent);
@@ -192,13 +190,13 @@ public:
int maxResults() const { return m_maxResults; }
- String defaultValue() const;
- void setDefaultValue(const String&);
+ const AtomicString& defaultValue() const;
+ void setDefaultValue(const AtomicString&);
Vector<String> acceptMIMETypes();
Vector<String> acceptFileExtensions();
- String accept() const;
- String alt() const;
+ const AtomicString& accept() const;
+ const AtomicString& alt() const;
void setSize(unsigned);
void setSize(unsigned, ExceptionState&);
@@ -210,9 +208,6 @@ public:
bool multiple() const;
- bool isAutofilled() const { return m_isAutofilled; }
- void setAutofilled(bool = true);
-
FileList* files();
void setFiles(PassRefPtr<FileList>);
@@ -235,6 +230,7 @@ public:
HTMLElement* list() const;
HTMLDataListElement* dataList() const;
+ bool hasValidDataListOptions() const;
void listAttributeTargetChanged();
HTMLInputElement* checkedRadioButtonForGroup() const;
@@ -255,7 +251,7 @@ public:
bool capture() const;
#endif
- static const unsigned maximumLength;
+ static const int maximumLength;
unsigned height() const;
unsigned width() const;
@@ -285,21 +281,21 @@ public:
bool supportsInputModeAttribute() const;
protected:
- HTMLInputElement(const QualifiedName&, Document&, HTMLFormElement*, bool createdByParser);
+ HTMLInputElement(Document&, HTMLFormElement*, bool createdByParser);
virtual void defaultEventHandler(Event*);
private:
enum AutoCompleteSetting { Uninitialized, On, Off };
- virtual void didAddUserAgentShadowRoot(ShadowRoot*) OVERRIDE;
+ virtual void didAddUserAgentShadowRoot(ShadowRoot&) OVERRIDE;
virtual void didAddShadowRoot(ShadowRoot&) OVERRIDE;
virtual void willChangeForm() OVERRIDE;
virtual void didChangeForm() OVERRIDE;
virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
virtual void removedFrom(ContainerNode*) OVERRIDE;
- virtual void didMoveToNewDocument(Document* oldDocument) OVERRIDE;
+ virtual void didMoveToNewDocument(Document& oldDocument) OVERRIDE;
virtual bool hasCustomFocusLogic() const OVERRIDE;
virtual bool isKeyboardFocusable() const OVERRIDE;
@@ -333,11 +329,12 @@ private:
virtual void attach(const AttachContext& = AttachContext()) OVERRIDE;
- virtual bool appendFormData(FormDataList&, bool);
+ virtual bool appendFormData(FormDataList&, bool) OVERRIDE;
+ virtual String resultForDialogSubmit() OVERRIDE;
- virtual bool isSuccessfulSubmitButton() const;
+ virtual bool canBeSuccessfulSubmitButton() const OVERRIDE;
- virtual void reset();
+ virtual void resetImpl() OVERRIDE;
virtual void* preDispatchEventHandler(Event*);
virtual void postDispatchEventHandler(Event*, void* dataFromPreDispatch);
@@ -394,12 +391,10 @@ private:
bool m_hasType : 1;
bool m_isActivatedSubmit : 1;
unsigned m_autocomplete : 2; // AutoCompleteSetting
- bool m_isAutofilled : 1;
bool m_hasNonEmptyList : 1;
bool m_stateRestored : 1;
bool m_parsingInProgress : 1;
bool m_valueAttributeWasUpdatedAfterParsing : 1;
- bool m_wasModifiedByUser : 1;
bool m_canReceiveDroppedFiles : 1;
bool m_hasTouchEventHandler : 1;
RefPtr<InputType> m_inputType;
@@ -411,21 +406,7 @@ private:
OwnPtr<ListAttributeTargetObserver> m_listAttributeTargetObserver;
};
-inline HTMLInputElement* toHTMLInputElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::inputTag));
- return static_cast<HTMLInputElement*>(node);
-}
-
-inline const HTMLInputElement* toHTMLInputElement(const Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::inputTag));
- return static_cast<const HTMLInputElement*>(node);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toHTMLElement(const HTMLElement*);
-
+DEFINE_NODE_TYPE_CASTS(HTMLInputElement, hasTagName(HTMLNames::inputTag));
} //namespace
#endif
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLInputElement.idl b/chromium/third_party/WebKit/Source/core/html/HTMLInputElement.idl
index fd6151d373c..6c2fa4e818d 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLInputElement.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLInputElement.idl
@@ -19,9 +19,9 @@
* Boston, MA 02110-1301, USA.
*/
-[
-] interface HTMLInputElement : HTMLElement {
+interface HTMLInputElement : HTMLElement {
[Reflect] attribute DOMString accept;
+ [Reflect] attribute DOMString align;
[Reflect] attribute DOMString alt;
[Reflect] attribute DOMString autocomplete;
[Reflect] attribute boolean autofocus;
@@ -29,20 +29,21 @@
attribute boolean checked;
[Reflect] attribute DOMString dirName;
[Reflect] attribute boolean disabled;
- readonly attribute HTMLFormElement form;
+ [ImplementedAs=formOwner] readonly attribute HTMLFormElement form;
// The 'files' attribute is intentionally not readonly.
// https://www.w3.org/Bugs/Public/show_bug.cgi?id=22682
attribute FileList files;
- [Reflect, URL] attribute DOMString formAction;
- [TreatNullAs=NullString, CustomElementCallbacks=Enable] attribute DOMString formEnctype;
- [TreatNullAs=NullString, CustomElementCallbacks=Enable] attribute DOMString formMethod;
+ [Reflect, URL, PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute DOMString formAction;
+ [CustomElementCallbacks] attribute DOMString formEnctype;
+ [CustomElementCallbacks] attribute DOMString formMethod;
[Reflect] attribute boolean formNoValidate;
[Reflect] attribute DOMString formTarget;
- [CustomElementCallbacks=Enable] attribute unsigned long height;
+ [CustomElementCallbacks] attribute unsigned long height;
attribute boolean indeterminate;
- [EnabledAtRuntime=DataListElement] readonly attribute HTMLElement list;
+ [RuntimeEnabled=InputModeAttribute, Reflect] attribute DOMString inputMode;
+ [RuntimeEnabled=DataListElement] readonly attribute HTMLElement list;
[Reflect] attribute DOMString max;
- [SetterRaisesException, CustomElementCallbacks=Enable] attribute long maxLength;
+ [RaisesException=Setter, CustomElementCallbacks] attribute long maxLength;
[Reflect] attribute DOMString min;
[Reflect] attribute boolean multiple;
[Reflect] attribute DOMString name;
@@ -50,21 +51,21 @@
[Reflect] attribute DOMString placeholder;
[Reflect] attribute boolean readOnly;
[Reflect] attribute boolean required;
- [SetterRaisesException, CustomElementCallbacks=Enable] attribute unsigned long size; // Changed string -> long -> unsigned long
- [Reflect, URL] attribute DOMString src;
+ [RaisesException=Setter, CustomElementCallbacks] attribute unsigned long size; // Changed string -> long -> unsigned long
+ [Reflect, URL, PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute DOMString src;
[Reflect] attribute DOMString step;
- [TreatNullAs=NullString, CustomElementCallbacks=Enable] attribute DOMString type; // readonly dropped as part of DOM level 2
- [TreatNullAs=NullString, CustomElementCallbacks=Enable] attribute DOMString defaultValue;
+ [CustomElementCallbacks] attribute DOMString type; // readonly dropped as part of DOM level 2
+ [CustomElementCallbacks] attribute DOMString defaultValue;
+ [Reflect] attribute DOMString useMap;
// See the discussion in https://bugs.webkit.org/show_bug.cgi?id=100085
- [TreatNullAs=NullString, SetterRaisesException, CustomElementCallbacks=Enable] attribute DOMString value;
- [SetterRaisesException, CustomElementCallbacks=Enable] attribute Date valueAsDate;
- [SetterRaisesException, CustomElementCallbacks=Enable] attribute double valueAsNumber;
- [EnabledAtRuntime=InputModeAttribute, Reflect] attribute DOMString inputMode;
+ [TreatNullAs=NullString, RaisesException=Setter, CustomElementCallbacks] attribute DOMString value;
+ [RaisesException=Setter, CustomElementCallbacks] attribute Date valueAsDate;
+ [RaisesException=Setter, CustomElementCallbacks] attribute double valueAsNumber;
- [RaisesException, CustomElementCallbacks=Enable] void stepUp(optional long n);
- [RaisesException, CustomElementCallbacks=Enable] void stepDown(optional long n);
+ [RaisesException, CustomElementCallbacks] void stepUp(optional long n);
+ [RaisesException, CustomElementCallbacks] void stepDown(optional long n);
- [CustomElementCallbacks=Enable] attribute unsigned long width;
+ [CustomElementCallbacks] attribute unsigned long width;
readonly attribute boolean willValidate;
readonly attribute ValidityState validity;
readonly attribute DOMString validationMessage;
@@ -90,13 +91,11 @@
optional DOMString direction);
// Non-standard attributes
- [Reflect] attribute DOMString align;
- [Reflect, EnabledAtRuntime=DirectoryUpload] attribute boolean webkitdirectory;
- [Reflect] attribute DOMString useMap;
+ [Reflect, RuntimeEnabled=DirectoryUpload] attribute boolean webkitdirectory;
[Reflect] attribute boolean incremental;
- [Conditional=INPUT_SPEECH, Reflect, EnabledAtRuntime=SpeechInput] attribute boolean webkitSpeech;
- [Conditional=INPUT_SPEECH, Reflect, EnabledAtRuntime=SpeechInput] attribute boolean webkitGrammar;
- [Conditional=INPUT_SPEECH, NotEnumerable] attribute EventHandler onwebkitspeechchange;
+ [Conditional=INPUT_SPEECH, Reflect, RuntimeEnabled=SpeechInput] attribute boolean webkitSpeech;
+ [Conditional=INPUT_SPEECH, Reflect, RuntimeEnabled=SpeechInput] attribute boolean webkitGrammar;
+ [Conditional=INPUT_SPEECH] attribute EventHandler onwebkitspeechchange;
// See http://www.w3.org/TR/html-media-capture/
[Conditional=MEDIA_CAPTURE, Reflect] attribute boolean capture;
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLKeygenElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLKeygenElement.cpp
index df2d0be160e..e6c80d009ae 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLKeygenElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLKeygenElement.cpp
@@ -33,7 +33,7 @@
#include "core/html/FormDataList.h"
#include "core/html/HTMLOptionElement.h"
#include "core/html/HTMLSelectElement.h"
-#include "core/platform/SSLKeyGenerator.h"
+#include "platform/SSLKeyGenerator.h"
#include "wtf/StdLibExtras.h"
using namespace WebCore;
@@ -42,31 +42,30 @@ namespace WebCore {
using namespace HTMLNames;
-HTMLKeygenElement::HTMLKeygenElement(const QualifiedName& tagName, Document& document, HTMLFormElement* form)
- : HTMLFormControlElementWithState(tagName, document, form)
+HTMLKeygenElement::HTMLKeygenElement(Document& document, HTMLFormElement* form)
+ : HTMLFormControlElementWithState(keygenTag, document, form)
{
- ASSERT(hasTagName(keygenTag));
ScriptWrappable::init(this);
ensureUserAgentShadowRoot();
}
-void HTMLKeygenElement::didAddUserAgentShadowRoot(ShadowRoot* root)
+void HTMLKeygenElement::didAddUserAgentShadowRoot(ShadowRoot& root)
{
DEFINE_STATIC_LOCAL(AtomicString, keygenSelectPseudoId, ("-webkit-keygen-select", AtomicString::ConstructFromLiteral));
Vector<String> keys;
- getSupportedKeySizes(keys);
+ getSupportedKeySizes(locale(), keys);
// Create a select element with one option element for each key size.
RefPtr<HTMLSelectElement> select = HTMLSelectElement::create(document());
- select->setPart(keygenSelectPseudoId);
+ select->setPseudo(keygenSelectPseudoId);
for (size_t i = 0; i < keys.size(); ++i) {
RefPtr<HTMLOptionElement> option = HTMLOptionElement::create(document());
option->appendChild(Text::create(document(), keys[i]));
select->appendChild(option);
}
- root->appendChild(select);
+ root.appendChild(select);
}
void HTMLKeygenElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
@@ -97,7 +96,7 @@ const AtomicString& HTMLKeygenElement::formControlType() const
return keygen;
}
-void HTMLKeygenElement::reset()
+void HTMLKeygenElement::resetImpl()
{
shadowSelect()->reset();
}
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLKeygenElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLKeygenElement.h
index bd6913d514f..292a78ea29d 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLKeygenElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLKeygenElement.h
@@ -32,15 +32,15 @@ class HTMLSelectElement;
class HTMLKeygenElement FINAL : public HTMLFormControlElementWithState {
public:
- static PassRefPtr<HTMLKeygenElement> create(const QualifiedName& tagName, Document& document, HTMLFormElement* form)
+ static PassRefPtr<HTMLKeygenElement> create(Document& document, HTMLFormElement* form)
{
- return adoptRef(new HTMLKeygenElement(tagName, document, form));
+ return adoptRef(new HTMLKeygenElement(document, form));
}
virtual bool willValidate() const OVERRIDE { return false; }
private:
- HTMLKeygenElement(const QualifiedName&, Document&, HTMLFormElement*);
+ HTMLKeygenElement(Document&, HTMLFormElement*);
virtual bool areAuthorShadowsAllowed() const OVERRIDE { return false; }
@@ -56,10 +56,10 @@ private:
virtual bool isInteractiveContent() const OVERRIDE;
virtual bool supportLabels() const OVERRIDE { return true; }
- virtual void reset() OVERRIDE;
+ virtual void resetImpl() OVERRIDE;
virtual bool shouldSaveAndRestoreFormControlState() const OVERRIDE { return false; }
- virtual void didAddUserAgentShadowRoot(ShadowRoot*) OVERRIDE;
+ virtual void didAddUserAgentShadowRoot(ShadowRoot&) OVERRIDE;
HTMLSelectElement* shadowSelect() const;
};
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLKeygenElement.idl b/chromium/third_party/WebKit/Source/core/html/HTMLKeygenElement.idl
index c8361d8eb7e..59af63817b0 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLKeygenElement.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLKeygenElement.idl
@@ -32,7 +32,7 @@ interface HTMLKeygenElement : HTMLElement {
[Reflect] attribute boolean autofocus;
[Reflect] attribute DOMString challenge;
[Reflect] attribute boolean disabled;
- readonly attribute HTMLFormElement form;
+ [ImplementedAs=formOwner] readonly attribute HTMLFormElement form;
[Reflect] attribute DOMString keytype;
[Reflect] attribute DOMString name;
@@ -46,4 +46,3 @@ interface HTMLKeygenElement : HTMLElement {
readonly attribute NodeList labels;
};
-
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLLIElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLLIElement.cpp
index fac38308ec7..aba20072981 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLLIElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLLIElement.cpp
@@ -32,21 +32,15 @@ namespace WebCore {
using namespace HTMLNames;
-HTMLLIElement::HTMLLIElement(const QualifiedName& tagName, Document& document)
- : HTMLElement(tagName, document)
+HTMLLIElement::HTMLLIElement(Document& document)
+ : HTMLElement(liTag, document)
{
- ASSERT(hasTagName(liTag));
ScriptWrappable::init(this);
}
PassRefPtr<HTMLLIElement> HTMLLIElement::create(Document& document)
{
- return adoptRef(new HTMLLIElement(liTag, document));
-}
-
-PassRefPtr<HTMLLIElement> HTMLLIElement::create(const QualifiedName& tagName, Document& document)
-{
- return adoptRef(new HTMLLIElement(tagName, document));
+ return adoptRef(new HTMLLIElement(document));
}
bool HTMLLIElement::isPresentationAttribute(const QualifiedName& name) const
@@ -86,8 +80,6 @@ void HTMLLIElement::parseAttribute(const QualifiedName& name, const AtomicString
void HTMLLIElement::attach(const AttachContext& context)
{
- ASSERT(!attached());
-
HTMLElement::attach(context);
if (renderer() && renderer()->isListItem()) {
@@ -106,8 +98,10 @@ void HTMLLIElement::attach(const AttachContext& context)
// If we are not in a list, tell the renderer so it can position us inside.
// We don't want to change our style to say "inside" since that would affect nested nodes.
- if (!listNode)
+ if (!listNode) {
listItemRenderer->setNotInList(true);
+ listItemRenderer->updateMarkerLocation();
+ }
parseValue(fastGetAttribute(valueAttr));
}
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLLIElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLLIElement.h
index 969a9387c8f..a16f4b06f85 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLLIElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLLIElement.h
@@ -30,10 +30,9 @@ namespace WebCore {
class HTMLLIElement FINAL : public HTMLElement {
public:
static PassRefPtr<HTMLLIElement> create(Document&);
- static PassRefPtr<HTMLLIElement> create(const QualifiedName&, Document&);
private:
- HTMLLIElement(const QualifiedName&, Document&);
+ explicit HTMLLIElement(Document&);
virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLLIElement.idl b/chromium/third_party/WebKit/Source/core/html/HTMLLIElement.idl
index f79f1cb556a..43b242f4ed0 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLLIElement.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLLIElement.idl
@@ -21,4 +21,3 @@ interface HTMLLIElement : HTMLElement {
[Reflect] attribute DOMString type;
[Reflect] attribute long value;
};
-
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLLabelElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLLabelElement.cpp
index 77f145298b6..6e8fa3d5ea0 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLLabelElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLLabelElement.cpp
@@ -27,8 +27,8 @@
#include "HTMLNames.h"
#include "core/dom/ElementTraversal.h"
-#include "core/dom/Event.h"
-#include "core/dom/EventNames.h"
+#include "core/events/Event.h"
+#include "core/events/ThreadLocalEventNames.h"
#include "core/html/FormAssociatedElement.h"
namespace WebCore {
@@ -44,16 +44,15 @@ static bool supportsLabels(Element* element)
return toLabelableElement(element)->supportLabels();
}
-inline HTMLLabelElement::HTMLLabelElement(const QualifiedName& tagName, Document& document)
- : HTMLElement(tagName, document)
+inline HTMLLabelElement::HTMLLabelElement(Document& document)
+ : HTMLElement(labelTag, document)
{
- ASSERT(hasTagName(labelTag));
ScriptWrappable::init(this);
}
-PassRefPtr<HTMLLabelElement> HTMLLabelElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<HTMLLabelElement> HTMLLabelElement::create(Document& document)
{
- return adoptRef(new HTMLLabelElement(tagName, document));
+ return adoptRef(new HTMLLabelElement(document));
}
bool HTMLLabelElement::rendererIsFocusable() const
@@ -70,7 +69,7 @@ LabelableElement* HTMLLabelElement::control()
// per http://dev.w3.org/html5/spec/Overview.html#the-label-element
// the form element must be "labelable form-associated element".
Element* element = this;
- while ((element = ElementTraversal::next(element, this))) {
+ while ((element = ElementTraversal::next(*element, this))) {
if (!supportsLabels(element))
continue;
return toLabelableElement(element);
@@ -86,22 +85,22 @@ LabelableElement* HTMLLabelElement::control()
return 0;
}
-HTMLFormElement* HTMLLabelElement::form() const
+HTMLFormElement* HTMLLabelElement::formOwner() const
{
return FormAssociatedElement::findAssociatedForm(this, 0);
}
-void HTMLLabelElement::setActive(bool down, bool pause)
+void HTMLLabelElement::setActive(bool down)
{
if (down == active())
return;
// Update our status first.
- HTMLElement::setActive(down, pause);
+ HTMLElement::setActive(down);
// Also update our corresponding control.
if (HTMLElement* element = control())
- element->setActive(down, pause);
+ element->setActive(down);
}
void HTMLLabelElement::setHovered(bool over)
@@ -138,7 +137,7 @@ void HTMLLabelElement::defaultEventHandler(Event* evt)
{
static bool processingClick = false;
- if (evt->type() == eventNames().clickEvent && !processingClick) {
+ if (evt->type() == EventTypeNames::click && !processingClick) {
RefPtr<HTMLElement> element = control();
// If we can't find a control or if the control received the click
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLLabelElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLLabelElement.h
index f19939559e6..8ad7c6770ae 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLLabelElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLLabelElement.h
@@ -31,15 +31,16 @@ namespace WebCore {
class HTMLLabelElement FINAL : public HTMLElement {
public:
- static PassRefPtr<HTMLLabelElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<HTMLLabelElement> create(Document&);
LabelableElement* control();
- HTMLFormElement* form() const;
virtual bool willRespondToMouseClickEvents() OVERRIDE;
+ virtual HTMLFormElement* formOwner() const OVERRIDE;
+
private:
- HTMLLabelElement(const QualifiedName&, Document&);
+ explicit HTMLLabelElement(Document&);
bool isInInteractiveContent(Node*) const;
virtual bool rendererIsFocusable() const OVERRIDE;
@@ -47,8 +48,8 @@ private:
virtual void accessKeyAction(bool sendMouseEvents);
// Overridden to update the hover/active state of the corresponding control.
- virtual void setActive(bool = true, bool pause = false);
- virtual void setHovered(bool = true);
+ virtual void setActive(bool = true) OVERRIDE;
+ virtual void setHovered(bool = true) OVERRIDE;
// Overridden to either click() or focus() the corresponding control.
virtual void defaultEventHandler(Event*);
@@ -66,11 +67,7 @@ inline bool isHTMLLabelElement(const Element* element)
return element->hasTagName(HTMLNames::labelTag);
}
-inline HTMLLabelElement* toHTMLLabelElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || isHTMLLabelElement(node));
- return static_cast<HTMLLabelElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(HTMLLabelElement, hasTagName(HTMLNames::labelTag));
} //namespace
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLLabelElement.idl b/chromium/third_party/WebKit/Source/core/html/HTMLLabelElement.idl
index fa37360b775..0f73764d500 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLLabelElement.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLLabelElement.idl
@@ -19,8 +19,7 @@
*/
interface HTMLLabelElement : HTMLElement {
- readonly attribute HTMLFormElement form;
+ [ImplementedAs=formOwner] readonly attribute HTMLFormElement form;
[Reflect=for] attribute DOMString htmlFor;
readonly attribute HTMLElement control;
};
-
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLLegendElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLLegendElement.cpp
index 515932622ea..f15aed3010b 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLLegendElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLLegendElement.cpp
@@ -35,16 +35,15 @@ namespace WebCore {
using namespace HTMLNames;
-inline HTMLLegendElement::HTMLLegendElement(const QualifiedName& tagName, Document& document)
- : HTMLElement(tagName, document)
+inline HTMLLegendElement::HTMLLegendElement(Document& document)
+ : HTMLElement(legendTag, document)
{
- ASSERT(hasTagName(legendTag));
ScriptWrappable::init(this);
}
-PassRefPtr<HTMLLegendElement> HTMLLegendElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<HTMLLegendElement> HTMLLegendElement::create(Document& document)
{
- return adoptRef(new HTMLLegendElement(tagName, document));
+ return adoptRef(new HTMLLegendElement(document));
}
HTMLFormControlElement* HTMLLegendElement::associatedControl()
@@ -59,7 +58,7 @@ HTMLFormControlElement* HTMLLegendElement::associatedControl()
// Find first form element inside the fieldset that is not a legend element.
// FIXME: Should we consider tabindex?
Element* element = fieldset;
- while ((element = ElementTraversal::next(element, fieldset))) {
+ while ((element = ElementTraversal::next(*element, fieldset))) {
if (element->isFormControlElement())
return toHTMLFormControlElement(element);
}
@@ -83,7 +82,7 @@ void HTMLLegendElement::accessKeyAction(bool sendMouseEvents)
control->accessKeyAction(sendMouseEvents);
}
-HTMLFormElement* HTMLLegendElement::virtualForm() const
+HTMLFormElement* HTMLLegendElement::form() const
{
// According to the specification, If the legend has a fieldset element as
// its parent, then the form attribute must return the same value as the
@@ -92,7 +91,7 @@ HTMLFormElement* HTMLLegendElement::virtualForm() const
if (!fieldset || !fieldset->hasTagName(fieldsetTag))
return 0;
- return toHTMLFieldSetElement(fieldset)->form();
+ return toHTMLFieldSetElement(fieldset)->formOwner();
}
} // namespace
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLLegendElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLLegendElement.h
index 4ee68b2433d..74290a8ea33 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLLegendElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLLegendElement.h
@@ -32,24 +32,21 @@ class HTMLFormControlElement;
class HTMLLegendElement FINAL : public HTMLElement {
public:
- static PassRefPtr<HTMLLegendElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<HTMLLegendElement> create(Document&);
+
+ HTMLFormElement* form() const;
private:
- HTMLLegendElement(const QualifiedName&, Document&);
+ explicit HTMLLegendElement(Document&);
// Control in the legend's fieldset that gets focus and access key.
HTMLFormControlElement* associatedControl();
virtual void accessKeyAction(bool sendMouseEvents);
virtual void focus(bool restorePreviousSelection, FocusDirection) OVERRIDE;
- virtual HTMLFormElement* virtualForm() const OVERRIDE;
};
-inline HTMLLegendElement* toHTMLLegendElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::legendTag));
- return static_cast<HTMLLegendElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(HTMLLegendElement, hasTagName(HTMLNames::legendTag));
} //namespace
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLLegendElement.idl b/chromium/third_party/WebKit/Source/core/html/HTMLLegendElement.idl
index e8e88719a2f..d5107069993 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLLegendElement.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLLegendElement.idl
@@ -22,4 +22,3 @@ interface HTMLLegendElement : HTMLElement {
readonly attribute HTMLFormElement form;
[Reflect] attribute DOMString align;
};
-
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLLinkElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLLinkElement.cpp
index e41bf00e2ea..eea0d9d3d27 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLLinkElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLLinkElement.cpp
@@ -34,8 +34,8 @@
#include "core/css/resolver/StyleResolver.h"
#include "core/dom/Attribute.h"
#include "core/dom/Document.h"
-#include "core/dom/Event.h"
-#include "core/dom/EventSender.h"
+#include "core/events/Event.h"
+#include "core/events/EventSender.h"
#include "core/dom/StyleEngine.h"
#include "core/fetch/CSSStyleSheetResource.h"
#include "core/fetch/FetchRequest.h"
@@ -43,9 +43,9 @@
#include "core/html/LinkImport.h"
#include "core/loader/FrameLoader.h"
#include "core/loader/FrameLoaderClient.h"
-#include "core/page/ContentSecurityPolicy.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameView.h"
+#include "core/frame/ContentSecurityPolicy.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
#include "wtf/StdLibExtras.h"
namespace WebCore {
@@ -54,25 +54,24 @@ using namespace HTMLNames;
static LinkEventSender& linkLoadEventSender()
{
- DEFINE_STATIC_LOCAL(LinkEventSender, sharedLoadEventSender, (eventNames().loadEvent));
+ DEFINE_STATIC_LOCAL(LinkEventSender, sharedLoadEventSender, (EventTypeNames::load));
return sharedLoadEventSender;
}
-inline HTMLLinkElement::HTMLLinkElement(const QualifiedName& tagName, Document& document, bool createdByParser)
- : HTMLElement(tagName, document)
+inline HTMLLinkElement::HTMLLinkElement(Document& document, bool createdByParser)
+ : HTMLElement(linkTag, document)
, m_linkLoader(this)
, m_sizes(DOMSettableTokenList::create())
, m_createdByParser(createdByParser)
, m_isInShadowTree(false)
, m_beforeLoadRecurseCount(0)
{
- ASSERT(hasTagName(linkTag));
ScriptWrappable::init(this);
}
-PassRefPtr<HTMLLinkElement> HTMLLinkElement::create(const QualifiedName& tagName, Document& document, bool createdByParser)
+PassRefPtr<HTMLLinkElement> HTMLLinkElement::create(Document& document, bool createdByParser)
{
- return adoptRef(new HTMLLinkElement(tagName, document, createdByParser));
+ return adoptRef(new HTMLLinkElement(document, createdByParser));
}
HTMLLinkElement::~HTMLLinkElement()
@@ -96,7 +95,7 @@ void HTMLLinkElement::parseAttribute(const QualifiedName& name, const AtomicStri
m_type = value;
process();
} else if (name == sizesAttr) {
- setSizes(value);
+ m_sizes->setValue(value);
process();
} else if (name == mediaAttr) {
m_media = value.string().lower();
@@ -105,7 +104,7 @@ void HTMLLinkElement::parseAttribute(const QualifiedName& name, const AtomicStri
if (LinkStyle* link = linkStyle())
link->setDisabledState(!value.isNull());
} else if (name == onbeforeloadAttr)
- setAttributeEventListener(eventNames().beforeloadEvent, createAttributeEventListener(this, name, value));
+ setAttributeEventListener(EventTypeNames::beforeload, createAttributeEventListener(this, name, value));
else {
if (name == titleAttr) {
if (LinkStyle* link = linkStyle())
@@ -119,13 +118,13 @@ void HTMLLinkElement::parseAttribute(const QualifiedName& name, const AtomicStri
bool HTMLLinkElement::shouldLoadLink()
{
bool continueLoad = true;
- RefPtr<Document> originalDocument = &document();
+ RefPtr<Document> originalDocument(document());
int recursionRank = ++m_beforeLoadRecurseCount;
if (!dispatchBeforeLoadEvent(getNonEmptyURLAttribute(hrefAttr)))
continueLoad = false;
// A beforeload handler might have removed us from the document or changed the document.
- if (continueLoad && (!inDocument() || &document() != originalDocument))
+ if (continueLoad && (!inDocument() || document() != originalDocument))
continueLoad = false;
// If the beforeload handler recurses into the link element by mutating it, we should only
@@ -151,7 +150,7 @@ LinkResource* HTMLLinkElement::linkResourceToProcess()
if (m_relAttribute.isImport() && RuntimeEnabledFeatures::htmlImportsEnabled())
m_link = LinkImport::create(this);
else {
- RefPtr<LinkStyle> link = LinkStyle::create(this);
+ OwnPtr<LinkStyle> link = LinkStyle::create(this);
if (fastHasAttribute(disabledAttr))
link->setDisabledState(true);
m_link = link.release();
@@ -178,7 +177,7 @@ LinkImport* HTMLLinkElement::linkImport() const
Document* HTMLLinkElement::import() const
{
if (LinkImport* link = linkImport())
- return linkImport()->importedDocument();
+ return link->importedDocument();
return 0;
}
@@ -223,8 +222,7 @@ void HTMLLinkElement::removedFrom(ContainerNode* insertionPoint)
if (m_link)
m_link->ownerRemoved();
- if (document().renderer())
- document().removedStyleSheet(removedSheet.get());
+ document().removedStyleSheet(removedSheet.get());
}
void HTMLLinkElement::finishParsingChildren()
@@ -240,32 +238,32 @@ bool HTMLLinkElement::styleSheetIsLoading() const
void HTMLLinkElement::linkLoaded()
{
- dispatchEvent(Event::create(eventNames().loadEvent));
+ dispatchEvent(Event::create(EventTypeNames::load));
}
void HTMLLinkElement::linkLoadingErrored()
{
- dispatchEvent(Event::create(eventNames().errorEvent));
+ dispatchEvent(Event::create(EventTypeNames::error));
}
void HTMLLinkElement::didStartLinkPrerender()
{
- dispatchEvent(Event::create(eventNames().webkitprerenderstartEvent));
+ dispatchEvent(Event::create(EventTypeNames::webkitprerenderstart));
}
void HTMLLinkElement::didStopLinkPrerender()
{
- dispatchEvent(Event::create(eventNames().webkitprerenderstopEvent));
+ dispatchEvent(Event::create(EventTypeNames::webkitprerenderstop));
}
void HTMLLinkElement::didSendLoadForLinkPrerender()
{
- dispatchEvent(Event::create(eventNames().webkitprerenderloadEvent));
+ dispatchEvent(Event::create(EventTypeNames::webkitprerenderload));
}
void HTMLLinkElement::didSendDOMContentLoadedForLinkPrerender()
{
- dispatchEvent(Event::create(eventNames().webkitprerenderdomcontentloadedEvent));
+ dispatchEvent(Event::create(EventTypeNames::webkitprerenderdomcontentloaded));
}
bool HTMLLinkElement::sheetLoaded()
@@ -316,7 +314,7 @@ KURL HTMLLinkElement::href() const
return document().completeURL(getAttribute(hrefAttr));
}
-String HTMLLinkElement::rel() const
+const AtomicString& HTMLLinkElement::rel() const
{
return getAttribute(relAttr);
}
@@ -326,7 +324,7 @@ String HTMLLinkElement::target() const
return getAttribute(targetAttr);
}
-String HTMLLinkElement::type() const
+const AtomicString& HTMLLinkElement::type() const
{
return getAttribute(typeAttr);
}
@@ -365,15 +363,9 @@ DOMSettableTokenList* HTMLLinkElement::sizes() const
return m_sizes.get();
}
-void HTMLLinkElement::setSizes(const String& value)
+PassOwnPtr<LinkStyle> LinkStyle::create(HTMLLinkElement* owner)
{
- m_sizes->setValue(value);
-}
-
-
-PassRefPtr<LinkStyle> LinkStyle::create(HTMLLinkElement* owner)
-{
- return adoptRef(new LinkStyle(owner));
+ return adoptPtr(new LinkStyle(owner));
}
LinkStyle::LinkStyle(HTMLLinkElement* owner)
@@ -390,9 +382,6 @@ LinkStyle::~LinkStyle()
{
if (m_sheet)
m_sheet->clearOwnerNode();
-
- if (m_resource)
- m_resource->removeClient(this);
}
Document& LinkStyle::document()
@@ -578,31 +567,31 @@ void LinkStyle::process()
if (!document().contentSecurityPolicy()->allowImageFromSource(builder.url()))
return;
if (document().frame())
- document().frame()->loader()->client()->dispatchDidChangeIcons(m_owner->relAttribute().iconType());
+ document().frame()->loader().client()->dispatchDidChangeIcons(m_owner->relAttribute().iconType());
}
if (!m_owner->loadLink(type, builder.url()))
return;
if ((m_disabledState != Disabled) && m_owner->relAttribute().isStyleSheet()
- && document().frame() && builder.url().isValid()) {
+ && shouldLoadResource() && builder.url().isValid()) {
- if (m_resource) {
+ if (resource()) {
removePendingSheet();
- m_resource->removeClient(this);
- m_resource = 0;
+ clearResource();
}
if (!m_owner->shouldLoadLink())
return;
+ Frame* frame = loadingFrame();
m_loading = true;
bool mediaQueryMatches = true;
if (!m_owner->media().isEmpty()) {
RefPtr<RenderStyle> documentStyle = StyleResolver::styleForDocument(document());
RefPtr<MediaQuerySet> media = MediaQuerySet::create(m_owner->media());
- MediaQueryEvaluator evaluator(document().frame()->view()->mediaType(), document().frame(), documentStyle.get());
+ MediaQueryEvaluator evaluator(frame->view()->mediaType(), frame, documentStyle.get());
mediaQueryMatches = evaluator.eval(media.get());
}
@@ -613,11 +602,9 @@ void LinkStyle::process()
// Load stylesheets that are not needed for the rendering immediately with low priority.
FetchRequest request = builder.build(blocking);
- m_resource = document().fetcher()->fetchCSSStyleSheet(request);
+ setResource(document().fetcher()->fetchCSSStyleSheet(request));
- if (m_resource)
- m_resource->addClient(this);
- else {
+ if (!resource()) {
// The request may have been denied if (for example) the stylesheet is local and the document is remote.
m_loading = false;
removePendingSheet();
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLLinkElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLLinkElement.h
index ba8bb73966b..28b01dff582 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLLinkElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLLinkElement.h
@@ -27,7 +27,8 @@
#include "core/css/CSSStyleSheet.h"
#include "core/dom/DOMSettableTokenList.h"
#include "core/dom/IconURL.h"
-#include "core/fetch/ResourcePtr.h"
+#include "core/fetch/ResourceOwner.h"
+#include "core/fetch/StyleSheetResource.h"
#include "core/fetch/StyleSheetResourceClient.h"
#include "core/html/HTMLElement.h"
#include "core/html/LinkRelAttribute.h"
@@ -54,10 +55,10 @@ typedef EventSender<HTMLLinkElement> LinkEventSender;
// changing @rel makes it harder to move such a design so we are
// sticking current way so far.
//
-class LinkStyle FINAL : public LinkResource, StyleSheetResourceClient {
+class LinkStyle FINAL : public LinkResource, ResourceOwner<StyleSheetResource> {
WTF_MAKE_FAST_ALLOCATED;
public:
- static PassRefPtr<LinkStyle> create(HTMLLinkElement* owner);
+ static PassOwnPtr<LinkStyle> create(HTMLLinkElement* owner);
explicit LinkStyle(HTMLLinkElement* owner);
virtual ~LinkStyle();
@@ -84,7 +85,7 @@ public:
private:
// From ResourceClient
- virtual void setCSSStyleSheet(const String& href, const KURL& baseURL, const String& charset, const CSSStyleSheetResource*);
+ virtual void setCSSStyleSheet(const String& href, const KURL& baseURL, const String& charset, const CSSStyleSheetResource*) OVERRIDE;
enum DisabledState {
Unset,
@@ -108,7 +109,6 @@ private:
void removePendingSheet(RemovePendingSheetNotificationType = RemovePendingSheetNotifyImmediately);
Document& document();
- ResourcePtr<CSSStyleSheetResource> m_resource;
RefPtr<CSSStyleSheet> m_sheet;
DisabledState m_disabledState;
PendingSheetType m_pendingSheetType;
@@ -120,18 +120,18 @@ private:
class HTMLLinkElement FINAL : public HTMLElement, public LinkLoaderClient {
public:
- static PassRefPtr<HTMLLinkElement> create(const QualifiedName&, Document&, bool createdByParser);
+ static PassRefPtr<HTMLLinkElement> create(Document&, bool createdByParser);
virtual ~HTMLLinkElement();
KURL href() const;
- String rel() const;
+ const AtomicString& rel() const;
String media() const { return m_media; }
String typeValue() const { return m_type; }
const LinkRelAttribute& relAttribute() const { return m_relAttribute; }
virtual String target() const;
- String type() const;
+ const AtomicString& type() const;
IconType iconType() const;
@@ -145,7 +145,6 @@ public:
bool isDisabled() const { return linkStyle() && linkStyle()->isDisabled(); }
bool isEnabledViaScript() const { return linkStyle() && linkStyle()->isEnabledViaScript(); }
- void setSizes(const String&);
DOMSettableTokenList* sizes() const;
void dispatchPendingEvent(LinkEventSender*);
@@ -189,9 +188,9 @@ private:
virtual void didSendDOMContentLoadedForLinkPrerender() OVERRIDE;
private:
- HTMLLinkElement(const QualifiedName&, Document&, bool createdByParser);
+ HTMLLinkElement(Document&, bool createdByParser);
- RefPtr<LinkResource> m_link;
+ OwnPtr<LinkResource> m_link;
LinkLoader m_linkLoader;
String m_type;
@@ -204,11 +203,7 @@ private:
int m_beforeLoadRecurseCount;
};
-inline HTMLLinkElement* toHTMLLinkElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::linkTag));
- return static_cast<HTMLLinkElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(HTMLLinkElement, hasTagName(HTMLNames::linkTag));
} //namespace
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLLinkElement.idl b/chromium/third_party/WebKit/Source/core/html/HTMLLinkElement.idl
index 25e900a7d23..73c2426ce04 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLLinkElement.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLLinkElement.idl
@@ -22,18 +22,17 @@
interface HTMLLinkElement : HTMLElement {
[Reflect] attribute boolean disabled;
[Reflect] attribute DOMString charset;
- [Reflect, URL] attribute DOMString href;
+ [Reflect, URL, PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute DOMString href;
[Reflect] attribute DOMString hreflang;
[Reflect] attribute DOMString media;
[Reflect] attribute DOMString rel;
[Reflect] attribute DOMString rev;
- [CustomSetter] attribute DOMSettableTokenList sizes;
+ [PutForwards=value] readonly attribute DOMSettableTokenList sizes;
[Reflect] attribute DOMString target;
[Reflect] attribute DOMString type;
// DOM Level 2 Style
readonly attribute StyleSheet sheet;
- [EnabledAtRuntime=HTMLImports] readonly attribute Document import;
+ [RuntimeEnabled=HTMLImports] readonly attribute Document import;
};
-
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLMapElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLMapElement.cpp
index bdded68b16b..d1f055a2fc6 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLMapElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLMapElement.cpp
@@ -36,21 +36,15 @@ namespace WebCore {
using namespace HTMLNames;
-HTMLMapElement::HTMLMapElement(const QualifiedName& tagName, Document& document)
- : HTMLElement(tagName, document)
+HTMLMapElement::HTMLMapElement(Document& document)
+ : HTMLElement(mapTag, document)
{
- ASSERT(hasTagName(mapTag));
ScriptWrappable::init(this);
}
PassRefPtr<HTMLMapElement> HTMLMapElement::create(Document& document)
{
- return adoptRef(new HTMLMapElement(mapTag, document));
-}
-
-PassRefPtr<HTMLMapElement> HTMLMapElement::create(const QualifiedName& tagName, Document& document)
-{
- return adoptRef(new HTMLMapElement(tagName, document));
+ return adoptRef(new HTMLMapElement(document));
}
HTMLMapElement::~HTMLMapElement()
@@ -61,7 +55,7 @@ bool HTMLMapElement::mapMouseEvent(LayoutPoint location, const LayoutSize& size,
{
HTMLAreaElement* defaultArea = 0;
Element* element = this;
- while ((element = ElementTraversal::next(element, this))) {
+ while ((element = ElementTraversal::next(*element, this))) {
if (isHTMLAreaElement(element)) {
HTMLAreaElement* areaElt = toHTMLAreaElement(element);
if (areaElt->isDefault()) {
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLMapElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLMapElement.h
index dedcef2fcb9..cdd5c7654a8 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLMapElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLMapElement.h
@@ -33,7 +33,6 @@ class HTMLImageElement;
class HTMLMapElement FINAL : public HTMLElement {
public:
static PassRefPtr<HTMLMapElement> create(Document&);
- static PassRefPtr<HTMLMapElement> create(const QualifiedName&, Document&);
virtual ~HTMLMapElement();
const AtomicString& getName() const { return m_name; }
@@ -44,7 +43,7 @@ public:
PassRefPtr<HTMLCollection> areas();
private:
- HTMLMapElement(const QualifiedName&, Document&);
+ explicit HTMLMapElement(Document&);
virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
@@ -54,11 +53,7 @@ private:
AtomicString m_name;
};
-inline HTMLMapElement* toHTMLMapElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::mapTag));
- return static_cast<HTMLMapElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(HTMLMapElement, hasTagName(HTMLNames::mapTag));
} //namespace
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLMapElement.idl b/chromium/third_party/WebKit/Source/core/html/HTMLMapElement.idl
index 01dcae007c8..6616bede1d6 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLMapElement.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLMapElement.idl
@@ -22,4 +22,3 @@ interface HTMLMapElement : HTMLElement {
readonly attribute HTMLCollection areas;
[Reflect] attribute DOMString name;
};
-
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLMarqueeElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLMarqueeElement.cpp
index 5c1fe6dc7b1..882cb06c454 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLMarqueeElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLMarqueeElement.cpp
@@ -34,17 +34,16 @@ namespace WebCore {
using namespace HTMLNames;
-inline HTMLMarqueeElement::HTMLMarqueeElement(const QualifiedName& tagName, Document& document)
- : HTMLElement(tagName, document)
+inline HTMLMarqueeElement::HTMLMarqueeElement(Document& document)
+ : HTMLElement(marqueeTag, document)
, ActiveDOMObject(&document)
{
- ASSERT(hasTagName(marqueeTag));
ScriptWrappable::init(this);
}
-PassRefPtr<HTMLMarqueeElement> HTMLMarqueeElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<HTMLMarqueeElement> HTMLMarqueeElement::create(Document& document)
{
- RefPtr<HTMLMarqueeElement> marqueeElement(adoptRef(new HTMLMarqueeElement(tagName, document)));
+ RefPtr<HTMLMarqueeElement> marqueeElement(adoptRef(new HTMLMarqueeElement(document)));
marqueeElement->suspendIfNeeded();
return marqueeElement.release();
}
@@ -128,10 +127,10 @@ int HTMLMarqueeElement::scrollAmount() const
return ok && scrollAmount >= 0 ? scrollAmount : RenderStyle::initialMarqueeIncrement().intValue();
}
-void HTMLMarqueeElement::setScrollAmount(int scrollAmount, ExceptionState& es)
+void HTMLMarqueeElement::setScrollAmount(int scrollAmount, ExceptionState& exceptionState)
{
if (scrollAmount < 0)
- es.throwDOMException(IndexSizeError);
+ exceptionState.throwDOMException(IndexSizeError, "The provided value (" + String::number(scrollAmount) + ") is negative.");
else
setIntegralAttribute(scrollamountAttr, scrollAmount);
}
@@ -143,10 +142,10 @@ int HTMLMarqueeElement::scrollDelay() const
return ok && scrollDelay >= 0 ? scrollDelay : RenderStyle::initialMarqueeSpeed();
}
-void HTMLMarqueeElement::setScrollDelay(int scrollDelay, ExceptionState& es)
+void HTMLMarqueeElement::setScrollDelay(int scrollDelay, ExceptionState& exceptionState)
{
if (scrollDelay < 0)
- es.throwDOMException(IndexSizeError);
+ exceptionState.throwDOMException(IndexSizeError, "The provided value (" + String::number(scrollDelay) + ") is negative.");
else
setIntegralAttribute(scrolldelayAttr, scrollDelay);
}
@@ -158,20 +157,15 @@ int HTMLMarqueeElement::loop() const
return ok && loopValue > 0 ? loopValue : -1;
}
-void HTMLMarqueeElement::setLoop(int loop, ExceptionState& es)
+void HTMLMarqueeElement::setLoop(int loop, ExceptionState& exceptionState)
{
if (loop <= 0 && loop != -1)
- es.throwDOMException(IndexSizeError);
+ exceptionState.throwDOMException(IndexSizeError, "The provided value (" + String::number(loop) + ") is neither positive nor -1.");
else
setIntegralAttribute(loopAttr, loop);
}
-bool HTMLMarqueeElement::canSuspend() const
-{
- return true;
-}
-
-void HTMLMarqueeElement::suspend(ReasonForSuspension)
+void HTMLMarqueeElement::suspend()
{
if (RenderMarquee* marqueeRenderer = renderMarquee())
marqueeRenderer->suspend();
@@ -195,4 +189,16 @@ RenderObject* HTMLMarqueeElement::createRenderer(RenderStyle*)
return new RenderMarquee(this);
}
+void HTMLMarqueeElement::timerFired(Timer<HTMLMarqueeElement>*)
+{
+ if (!renderer())
+ return;
+
+ document().updateLayout();
+
+ // The updateLayout() could have destroyed renderer(), so this re-check is very important.
+ if (renderer())
+ toRenderMarquee(renderer())->timerFired();
+}
+
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLMarqueeElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLMarqueeElement.h
index 9169908586a..90add468471 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLMarqueeElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLMarqueeElement.h
@@ -33,7 +33,7 @@ class RenderMarquee;
class HTMLMarqueeElement FINAL : public HTMLElement, private ActiveDOMObject {
public:
- static PassRefPtr<HTMLMarqueeElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<HTMLMarqueeElement> create(Document&);
int minimumDelay() const;
@@ -51,15 +51,16 @@ public:
int loop() const;
void setLoop(int, ExceptionState&);
+ void timerFired(Timer<HTMLMarqueeElement>*);
+
private:
- HTMLMarqueeElement(const QualifiedName&, Document&);
+ explicit HTMLMarqueeElement(Document&);
virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
virtual void collectStyleForPresentationAttribute(const QualifiedName&, const AtomicString&, MutableStylePropertySet*) OVERRIDE;
// ActiveDOMObject
- virtual bool canSuspend() const;
- virtual void suspend(ReasonForSuspension);
+ virtual void suspend();
virtual void resume();
virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE FINAL;
@@ -67,11 +68,7 @@ private:
RenderMarquee* renderMarquee() const;
};
-inline HTMLMarqueeElement* toHTMLMarqueeElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::marqueeTag));
- return static_cast<HTMLMarqueeElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(HTMLMarqueeElement, hasTagName(HTMLNames::marqueeTag));
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLMarqueeElement.idl b/chromium/third_party/WebKit/Source/core/html/HTMLMarqueeElement.idl
index b5bda0cd847..0188f6c5149 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLMarqueeElement.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLMarqueeElement.idl
@@ -26,9 +26,9 @@ interface HTMLMarqueeElement : HTMLElement {
[Reflect] attribute DOMString direction;
[Reflect] attribute DOMString height;
[Reflect] attribute unsigned long hspace;
- [SetterRaisesException] attribute long loop;
- [SetterRaisesException] attribute long scrollAmount;
- [SetterRaisesException] attribute long scrollDelay;
+ [RaisesException=Setter] attribute long loop;
+ [RaisesException=Setter] attribute long scrollAmount;
+ [RaisesException=Setter] attribute long scrollDelay;
[Reflect] attribute boolean trueSpeed;
[Reflect] attribute unsigned long vspace;
[Reflect] attribute DOMString width;
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLMediaElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLMediaElement.cpp
index 6494ba7b6d3..c43d49009f1 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLMediaElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLMediaElement.cpp
@@ -26,6 +26,7 @@
#include "config.h"
#include "core/html/HTMLMediaElement.h"
+#include <limits>
#include "HTMLNames.h"
#include "RuntimeEnabledFeatures.h"
#include "bindings/v8/ExceptionState.h"
@@ -35,11 +36,15 @@
#include "core/css/MediaList.h"
#include "core/css/MediaQueryEvaluator.h"
#include "core/dom/Attribute.h"
-#include "core/dom/Event.h"
-#include "core/dom/EventNames.h"
#include "core/dom/ExceptionCode.h"
#include "core/dom/FullscreenElementStack.h"
#include "core/dom/shadow/ShadowRoot.h"
+#include "core/events/Event.h"
+#include "core/events/ThreadLocalEventNames.h"
+#include "core/frame/ContentSecurityPolicy.h"
+#include "core/frame/Frame.h"
+#include "core/frame/Settings.h"
+#include "core/frame/UseCounter.h"
#include "core/html/HTMLMediaSource.h"
#include "core/html/HTMLSourceElement.h"
#include "core/html/HTMLTrackElement.h"
@@ -54,44 +59,38 @@
#include "core/html/track/TextTrackCueList.h"
#include "core/html/track/TextTrackList.h"
#include "core/loader/FrameLoader.h"
-#include "core/page/ContentSecurityPolicy.h"
-#include "core/page/Frame.h"
-#include "core/page/Page.h"
-#include "core/page/Settings.h"
-#include "core/platform/ContentType.h"
-#include "core/platform/Language.h"
-#include "core/platform/Logging.h"
-#include "core/platform/MIMETypeFromURL.h"
-#include "core/platform/MIMETypeRegistry.h"
-#include "core/platform/NotImplemented.h"
-#include "core/platform/graphics/InbandTextTrackPrivate.h"
-#include "core/platform/graphics/MediaPlayer.h"
#include "core/rendering/RenderLayerCompositor.h"
#include "core/rendering/RenderVideo.h"
#include "core/rendering/RenderView.h"
+// FIXME: Remove dependency on modules/encryptedmedia (http://crbug.com/242754).
+#include "modules/encryptedmedia/MediaKeyNeededEvent.h"
+#include "modules/encryptedmedia/MediaKeys.h"
#include "modules/mediastream/MediaStreamRegistry.h"
+#include "platform/ContentType.h"
+#include "platform/Language.h"
+#include "platform/Logging.h"
+#include "platform/MIMETypeFromURL.h"
+#include "platform/MIMETypeRegistry.h"
+#include "platform/NotImplemented.h"
+#include "platform/UserGestureIndicator.h"
+#include "platform/graphics/GraphicsLayer.h"
+#include "platform/weborigin/SecurityOrigin.h"
#include "public/platform/Platform.h"
-#include "weborigin/SecurityOrigin.h"
+#include "public/platform/WebInbandTextTrack.h"
#include "wtf/CurrentTime.h"
#include "wtf/MathExtras.h"
#include "wtf/NonCopyingSort.h"
#include "wtf/Uint8Array.h"
#include "wtf/text/CString.h"
-#include <limits>
#if ENABLE(WEB_AUDIO)
-#include "core/platform/audio/AudioSourceProvider.h"
+#include "platform/audio/AudioSourceProvider.h"
#include "modules/webaudio/MediaElementAudioSourceNode.h"
#endif
-#if ENABLE(ENCRYPTED_MEDIA_V2)
-// FIXME: Remove dependency on modules/encryptedmedia (http://crbug.com/242754).
-#include "modules/encryptedmedia/MediaKeyNeededEvent.h"
-#include "modules/encryptedmedia/MediaKeys.h"
-#endif
-
using namespace std;
-using WebKit::WebMimeRegistry;
+using blink::WebInbandTextTrack;
+using blink::WebMimeRegistry;
namespace WebCore {
@@ -124,7 +123,7 @@ static const char* boolString(bool val)
#endif
// URL protocol used to signal that the media source API is being used.
-static const char* mediaSourceBlobProtocol = "blob";
+static const char mediaSourceBlobProtocol[] = "blob";
using namespace HTMLNames;
using namespace std;
@@ -153,16 +152,19 @@ static void removeElementFromDocumentMap(HTMLMediaElement* element, Document* do
map.add(document, set);
}
-static void throwExceptionForMediaKeyException(MediaPlayer::MediaKeyException exception, ExceptionState& es)
+static void throwExceptionForMediaKeyException(MediaPlayer::MediaKeyException exception, ExceptionState& exceptionState)
{
switch (exception) {
case MediaPlayer::NoError:
return;
case MediaPlayer::InvalidPlayerState:
- es.throwDOMException(InvalidStateError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
return;
case MediaPlayer::KeySystemNotSupported:
- es.throwDOMException(NotSupportedError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
+ return;
+ case MediaPlayer::InvalidAccess:
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return;
}
@@ -208,7 +210,7 @@ static bool canLoadURL(const KURL& url, const ContentType& contentType, const St
// when used with parameters, e.g. "application/octet-stream;codecs=theora", is a type that the user agent knows
// it cannot render.
if (contentMIMEType != "application/octet-stream" || contentTypeCodecs.isEmpty()) {
- WebMimeRegistry::SupportsType supported = WebKit::Platform::current()->mimeRegistry()->supportsMediaMIMEType(contentMIMEType, contentTypeCodecs, keySystem.lower());
+ WebMimeRegistry::SupportsType supported = blink::Platform::current()->mimeRegistry()->supportsMediaMIMEType(contentMIMEType, contentTypeCodecs, keySystem.lower());
return supported > WebMimeRegistry::IsNotSupported;
}
@@ -236,7 +238,7 @@ WebMimeRegistry::SupportsType HTMLMediaElement::supportsType(const ContentType&
if (type == "application/octet-stream")
return WebMimeRegistry::IsNotSupported;
- return WebKit::Platform::current()->mimeRegistry()->supportsMediaMIMEType(type, typeCodecs, system);
+ return blink::Platform::current()->mimeRegistry()->supportsMediaMIMEType(type, typeCodecs, system);
}
HTMLMediaElement::HTMLMediaElement(const QualifiedName& tagName, Document& document, bool createdByParser)
@@ -249,7 +251,6 @@ HTMLMediaElement::HTMLMediaElement(const QualifiedName& tagName, Document& docum
, m_asyncEventQueue(GenericEventQueue::create(this))
, m_playbackRate(1.0f)
, m_defaultPlaybackRate(1.0f)
- , m_webkitPreservesPitch(true)
, m_networkState(NETWORK_EMPTY)
, m_readyState(HAVE_NOTHING)
, m_readyStateMaximum(HAVE_NOTHING)
@@ -260,6 +261,8 @@ HTMLMediaElement::HTMLMediaElement(const QualifiedName& tagName, Document& docum
, m_lastTimeUpdateEventWallTime(0)
, m_lastTimeUpdateEventMovieTime(numeric_limits<double>::max())
, m_loadState(WaitingForSource)
+ , m_webLayer(0)
+ , m_opaque(false)
, m_restrictions(RequirePageConsentToLoadMediaRestriction)
, m_preload(MediaPlayer::Auto)
, m_displayMode(Unknown)
@@ -272,7 +275,7 @@ HTMLMediaElement::HTMLMediaElement(const QualifiedName& tagName, Document& docum
, m_playing(false)
, m_shouldDelayLoadEvent(false)
, m_haveFiredLoadedData(false)
- , m_inActiveDocument(true)
+ , m_active(true)
, m_autoplaying(true)
, m_muted(false)
, m_paused(true)
@@ -280,9 +283,7 @@ HTMLMediaElement::HTMLMediaElement(const QualifiedName& tagName, Document& docum
, m_sentStalledEvent(false)
, m_sentEndEvent(false)
, m_pausedInternal(false)
- , m_sendProgressEvents(true)
, m_closedCaptionsVisible(false)
- , m_dispatchingCanPlayEvent(false)
, m_loadInitiatedByUserGesture(false)
, m_completelyLoaded(false)
, m_havePreparedToPlay(false)
@@ -299,7 +300,7 @@ HTMLMediaElement::HTMLMediaElement(const QualifiedName& tagName, Document& docum
{
ASSERT(RuntimeEnabledFeatures::mediaEnabled());
- LOG(Media, "HTMLMediaElement::HTMLMediaElement");
+ WTF_LOG(Media, "HTMLMediaElement::HTMLMediaElement");
ScriptWrappable::init(this);
if (document.settings()) {
@@ -319,7 +320,7 @@ HTMLMediaElement::HTMLMediaElement(const QualifiedName& tagName, Document& docum
HTMLMediaElement::~HTMLMediaElement()
{
- LOG(Media, "HTMLMediaElement::~HTMLMediaElement");
+ WTF_LOG(Media, "HTMLMediaElement::~HTMLMediaElement");
m_asyncEventQueue->close();
@@ -331,14 +332,14 @@ HTMLMediaElement::~HTMLMediaElement()
m_textTracks->item(i)->clearClient();
}
- if (m_mediaController)
+ if (m_mediaController) {
m_mediaController->removeMediaElement(this);
+ m_mediaController = 0;
+ }
closeMediaSource();
-#if ENABLE(ENCRYPTED_MEDIA_V2)
setMediaKeys(0);
-#endif
removeElementFromDocumentMap(this, &document());
@@ -356,32 +357,28 @@ HTMLMediaElement::~HTMLMediaElement()
// object destruction, we use Document::incrementLoadEventDelayCount().
// See http://crbug.com/275223 for more details.
document().incrementLoadEventDelayCount();
- m_player.clear();
-#if ENABLE(WEB_AUDIO)
- if (audioSourceProvider())
- audioSourceProvider()->setClient(0);
-#endif
+
+ clearMediaPlayerAndAudioSourceProviderClient();
+
document().decrementLoadEventDelayCount();
}
-void HTMLMediaElement::didMoveToNewDocument(Document* oldDocument)
+void HTMLMediaElement::didMoveToNewDocument(Document& oldDocument)
{
- LOG(Media, "HTMLMediaElement::didMoveToNewDocument");
+ WTF_LOG(Media, "HTMLMediaElement::didMoveToNewDocument");
if (m_shouldDelayLoadEvent) {
document().incrementLoadEventDelayCount();
// Note: Keeping the load event delay count increment on oldDocument that was added
// when m_shouldDelayLoadEvent was set so that destruction of m_player can not
// cause load event dispatching in oldDocument.
- } else if (oldDocument) {
+ } else {
// Incrementing the load event delay count so that destruction of m_player can not
// cause load event dispatching in oldDocument.
- oldDocument->incrementLoadEventDelayCount();
+ oldDocument.incrementLoadEventDelayCount();
}
- if (oldDocument)
- removeElementFromDocumentMap(this, oldDocument);
-
+ removeElementFromDocumentMap(this, &oldDocument);
addElementToDocumentMap(this, &document());
// FIXME: This is a temporary fix to prevent this object from causing the
@@ -393,8 +390,7 @@ void HTMLMediaElement::didMoveToNewDocument(Document* oldDocument)
// Decrement the load event delay count on oldDocument now that m_player has been destroyed
// and there is no risk of dispatching a load event from within the destructor.
- if (oldDocument)
- oldDocument->decrementLoadEventDelayCount();
+ oldDocument.decrementLoadEventDelayCount();
HTMLElement::didMoveToNewDocument(oldDocument);
}
@@ -445,52 +441,8 @@ void HTMLMediaElement::parseAttribute(const QualifiedName& name, const AtomicStr
} else if (name == mediagroupAttr)
setMediaGroup(value);
- else if (name == onabortAttr)
- setAttributeEventListener(eventNames().abortEvent, createAttributeEventListener(this, name, value));
else if (name == onbeforeloadAttr)
- setAttributeEventListener(eventNames().beforeloadEvent, createAttributeEventListener(this, name, value));
- else if (name == oncanplayAttr)
- setAttributeEventListener(eventNames().canplayEvent, createAttributeEventListener(this, name, value));
- else if (name == oncanplaythroughAttr)
- setAttributeEventListener(eventNames().canplaythroughEvent, createAttributeEventListener(this, name, value));
- else if (name == ondurationchangeAttr)
- setAttributeEventListener(eventNames().durationchangeEvent, createAttributeEventListener(this, name, value));
- else if (name == onemptiedAttr)
- setAttributeEventListener(eventNames().emptiedEvent, createAttributeEventListener(this, name, value));
- else if (name == onendedAttr)
- setAttributeEventListener(eventNames().endedEvent, createAttributeEventListener(this, name, value));
- else if (name == onerrorAttr)
- setAttributeEventListener(eventNames().errorEvent, createAttributeEventListener(this, name, value));
- else if (name == onloadeddataAttr)
- setAttributeEventListener(eventNames().loadeddataEvent, createAttributeEventListener(this, name, value));
- else if (name == onloadedmetadataAttr)
- setAttributeEventListener(eventNames().loadedmetadataEvent, createAttributeEventListener(this, name, value));
- else if (name == onloadstartAttr)
- setAttributeEventListener(eventNames().loadstartEvent, createAttributeEventListener(this, name, value));
- else if (name == onpauseAttr)
- setAttributeEventListener(eventNames().pauseEvent, createAttributeEventListener(this, name, value));
- else if (name == onplayAttr)
- setAttributeEventListener(eventNames().playEvent, createAttributeEventListener(this, name, value));
- else if (name == onplayingAttr)
- setAttributeEventListener(eventNames().playingEvent, createAttributeEventListener(this, name, value));
- else if (name == onprogressAttr)
- setAttributeEventListener(eventNames().progressEvent, createAttributeEventListener(this, name, value));
- else if (name == onratechangeAttr)
- setAttributeEventListener(eventNames().ratechangeEvent, createAttributeEventListener(this, name, value));
- else if (name == onseekedAttr)
- setAttributeEventListener(eventNames().seekedEvent, createAttributeEventListener(this, name, value));
- else if (name == onseekingAttr)
- setAttributeEventListener(eventNames().seekingEvent, createAttributeEventListener(this, name, value));
- else if (name == onstalledAttr)
- setAttributeEventListener(eventNames().stalledEvent, createAttributeEventListener(this, name, value));
- else if (name == onsuspendAttr)
- setAttributeEventListener(eventNames().suspendEvent, createAttributeEventListener(this, name, value));
- else if (name == ontimeupdateAttr)
- setAttributeEventListener(eventNames().timeupdateEvent, createAttributeEventListener(this, name, value));
- else if (name == onvolumechangeAttr)
- setAttributeEventListener(eventNames().volumechangeEvent, createAttributeEventListener(this, name, value));
- else if (name == onwaitingAttr)
- setAttributeEventListener(eventNames().waitingEvent, createAttributeEventListener(this, name, value));
+ setAttributeEventListener(EventTypeNames::beforeload, createAttributeEventListener(this, name, value));
else
HTMLElement::parseAttribute(name, value);
}
@@ -528,11 +480,11 @@ bool HTMLMediaElement::childShouldCreateRenderer(const Node& child) const
Node::InsertionNotificationRequest HTMLMediaElement::insertedInto(ContainerNode* insertionPoint)
{
- LOG(Media, "HTMLMediaElement::insertedInto");
+ WTF_LOG(Media, "HTMLMediaElement::insertedInto");
HTMLElement::insertedInto(insertionPoint);
if (insertionPoint->inDocument()) {
- m_inActiveDocument = true;
+ m_active = true;
if (!getAttribute(srcAttr).isEmpty() && m_networkState == NETWORK_EMPTY)
scheduleDelayedAction(LoadMediaResource);
@@ -544,9 +496,9 @@ Node::InsertionNotificationRequest HTMLMediaElement::insertedInto(ContainerNode*
void HTMLMediaElement::removedFrom(ContainerNode* insertionPoint)
{
- LOG(Media, "HTMLMediaElement::removedFrom");
+ WTF_LOG(Media, "HTMLMediaElement::removedFrom");
- m_inActiveDocument = false;
+ m_active = false;
if (insertionPoint->inDocument()) {
configureMediaControls();
if (m_networkState > NETWORK_EMPTY)
@@ -558,8 +510,6 @@ void HTMLMediaElement::removedFrom(ContainerNode* insertionPoint)
void HTMLMediaElement::attach(const AttachContext& context)
{
- ASSERT(!attached());
-
HTMLElement::attach(context);
if (renderer())
@@ -574,7 +524,7 @@ void HTMLMediaElement::didRecalcStyle(StyleRecalcChange)
void HTMLMediaElement::scheduleDelayedAction(DelayedActionType actionType)
{
- LOG(Media, "HTMLMediaElement::scheduleLoad");
+ WTF_LOG(Media, "HTMLMediaElement::scheduleDelayedAction");
if ((actionType & LoadMediaResource) && !(m_pendingActionFlags & LoadMediaResource)) {
prepareForLoad();
@@ -598,7 +548,7 @@ void HTMLMediaElement::scheduleNextSourceChild()
void HTMLMediaElement::scheduleEvent(const AtomicString& eventName)
{
#if LOG_MEDIA_EVENTS
- LOG(Media, "HTMLMediaElement::scheduleEvent - scheduling '%s'", eventName.string().ascii().data());
+ WTF_LOG(Media, "HTMLMediaElement::scheduleEvent - scheduling '%s'", eventName.string().ascii().data());
#endif
m_asyncEventQueue->enqueueEvent(Event::createCancelable(eventName));
}
@@ -625,7 +575,7 @@ PassRefPtr<MediaError> HTMLMediaElement::error() const
return m_error;
}
-void HTMLMediaElement::setSrc(const String& url)
+void HTMLMediaElement::setSrc(const AtomicString& url)
{
setAttribute(srcAttr, url);
}
@@ -654,7 +604,7 @@ String HTMLMediaElement::canPlayType(const String& mimeType, const String& keySy
break;
}
- LOG(Media, "HTMLMediaElement::canPlayType(%s, %s, %s) -> %s", mimeType.utf8().data(), keySystem.utf8().data(), url.elidedString().utf8().data(), canPlay.utf8().data());
+ WTF_LOG(Media, "HTMLMediaElement::canPlayType(%s, %s, %s) -> %s", mimeType.utf8().data(), keySystem.utf8().data(), url.elidedString().utf8().data(), canPlay.utf8().data());
return canPlay;
}
@@ -663,12 +613,15 @@ void HTMLMediaElement::load()
{
RefPtr<HTMLMediaElement> protect(this); // loadInternal may result in a 'beforeload' event, which can make arbitrary DOM mutations.
- LOG(Media, "HTMLMediaElement::load()");
+ WTF_LOG(Media, "HTMLMediaElement::load()");
- if (userGestureRequiredForLoad() && !ScriptController::processingUserGesture())
+ if (document().settings() && !document().settings()->mediaEnabled())
return;
- m_loadInitiatedByUserGesture = ScriptController::processingUserGesture();
+ if (userGestureRequiredForLoad() && !UserGestureIndicator::processingUserGesture())
+ return;
+
+ m_loadInitiatedByUserGesture = UserGestureIndicator::processingUserGesture();
if (m_loadInitiatedByUserGesture)
removeBehaviorsRestrictionsAfterFirstUserGesture();
prepareForLoad();
@@ -678,7 +631,7 @@ void HTMLMediaElement::load()
void HTMLMediaElement::prepareForLoad()
{
- LOG(Media, "HTMLMediaElement::prepareForLoad");
+ WTF_LOG(Media, "HTMLMediaElement::prepareForLoad");
// Perform the cleanup required for the resource load algorithm to run.
stopPeriodicTimers();
@@ -701,7 +654,7 @@ void HTMLMediaElement::prepareForLoad()
// 3 - If the media element's networkState is set to NETWORK_LOADING or NETWORK_IDLE, queue
// a task to fire a simple event named abort at the media element.
if (m_networkState == NETWORK_LOADING || m_networkState == NETWORK_IDLE)
- scheduleEvent(eventNames().abortEvent);
+ scheduleEvent(EventTypeNames::abort);
closeMediaSource();
@@ -716,7 +669,7 @@ void HTMLMediaElement::prepareForLoad()
m_paused = true;
m_seeking = false;
invalidateCachedTime();
- scheduleEvent(eventNames().emptiedEvent);
+ scheduleEvent(EventTypeNames::emptied);
updateMediaController();
if (RuntimeEnabledFeatures::videoTrackEnabled())
updateActiveTextTrackCues(0);
@@ -781,7 +734,7 @@ void HTMLMediaElement::loadInternal()
void HTMLMediaElement::selectMediaResource()
{
- LOG(Media, "HTMLMediaElement::selectMediaResource");
+ WTF_LOG(Media, "HTMLMediaElement::selectMediaResource");
enum Mode { attribute, children };
@@ -809,7 +762,7 @@ void HTMLMediaElement::selectMediaResource()
setShouldDelayLoadEvent(false);
m_networkState = NETWORK_EMPTY;
- LOG(Media, "HTMLMediaElement::selectMediaResource, nothing to load");
+ WTF_LOG(Media, "HTMLMediaElement::selectMediaResource, nothing to load");
return;
}
}
@@ -820,7 +773,7 @@ void HTMLMediaElement::selectMediaResource()
m_networkState = NETWORK_LOADING;
// 5 - Queue a task to fire a simple event named loadstart at the media element.
- scheduleEvent(eventNames().loadstartEvent);
+ scheduleEvent(EventTypeNames::loadstart);
// 6 - If mode is attribute, then run these substeps
if (mode == attribute) {
@@ -830,7 +783,7 @@ void HTMLMediaElement::selectMediaResource()
KURL mediaURL = getNonEmptyURLAttribute(srcAttr);
if (mediaURL.isEmpty()) {
mediaLoadingFailed(MediaPlayer::FormatError);
- LOG(Media, "HTMLMediaElement::selectMediaResource, empty 'src'");
+ WTF_LOG(Media, "HTMLMediaElement::selectMediaResource, empty 'src'");
return;
}
@@ -844,7 +797,7 @@ void HTMLMediaElement::selectMediaResource()
// will have to pick a media engine based on the file extension.
ContentType contentType((String()));
loadResource(mediaURL, contentType, String());
- LOG(Media, "HTMLMediaElement::selectMediaResource, using 'src' attribute url");
+ WTF_LOG(Media, "HTMLMediaElement::selectMediaResource, using 'src' attribute url");
return;
}
@@ -873,7 +826,7 @@ void HTMLMediaElement::loadResource(const KURL& url, ContentType& contentType, c
{
ASSERT(isSafeToLoadURL(url, Complain));
- LOG(Media, "HTMLMediaElement::loadResource(%s, %s, %s)", urlForLoggingMedia(url).utf8().data(), contentType.raw().utf8().data(), keySystem.utf8().data());
+ WTF_LOG(Media, "HTMLMediaElement::loadResource(%s, %s, %s)", urlForLoggingMedia(url).utf8().data(), contentType.raw().utf8().data(), keySystem.utf8().data());
Frame* frame = document().frame();
if (!frame) {
@@ -888,13 +841,12 @@ void HTMLMediaElement::loadResource(const KURL& url, ContentType& contentType, c
// cache is an internal detail not exposed through the media element API.
m_currentSrc = url;
- LOG(Media, "HTMLMediaElement::loadResource - m_currentSrc -> %s", urlForLoggingMedia(m_currentSrc).utf8().data());
+ WTF_LOG(Media, "HTMLMediaElement::loadResource - m_currentSrc -> %s", urlForLoggingMedia(m_currentSrc).utf8().data());
if (MediaStreamRegistry::registry().lookupMediaStreamDescriptor(url.string()))
removeBehaviorRestriction(RequireUserGestureForRateChangeRestriction);
- if (m_sendProgressEvents)
- startProgressEventTimer();
+ startProgressEventTimer();
// Reset display mode to force a recalculation of what to show because we are resetting the player.
setDisplayMode(Unknown);
@@ -971,7 +923,7 @@ void HTMLMediaElement::updateActiveTextTrackCues(double movieTime)
if (ignoreTrackDisplayUpdateRequests())
return;
- LOG(Media, "HTMLMediaElement::updateActiveTextTrackCues");
+ WTF_LOG(Media, "HTMLMediaElement::updateActiveTextTrackCues");
// 1 - Let current cues be a list of cues, initialized to contain all the
// cues of all the hidden, showing, or showing by default text tracks of the
@@ -1029,7 +981,7 @@ void HTMLMediaElement::updateActiveTextTrackCues(double movieTime)
// fired as part of the overall process of changing the current playback
// position.)
if (!m_seeking && m_lastSeekTime <= lastTime)
- scheduleTimeupdateEvent(false);
+ scheduleTimeupdateEvent(true);
// Explicitly cache vector sizes, as their content is constant from here.
size_t currentCuesSize = currentCues.size();
@@ -1052,16 +1004,8 @@ void HTMLMediaElement::updateActiveTextTrackCues(double movieTime)
activeSetChanged = true;
}
- if (!activeSetChanged) {
- // Even though the active set has not changed, it is possible that the
- // the mode of a track has changed from 'hidden' to 'showing' and the
- // cues have not yet been rendered.
- // Note: don't call updateTextTrackDisplay() unless we have controls because it will
- // create them.
- if (hasMediaControls())
- updateTextTrackDisplay();
+ if (!activeSetChanged)
return;
- }
// 7 - If the time was reached through the usual monotonic increase of the
// current playback position during normal playback, and there are cues in
@@ -1142,18 +1086,18 @@ void HTMLMediaElement::updateActiveTextTrackCues(double movieTime)
// correctly identifies the type of the event, if the startTime is
// less than the endTime in the cue.
if (eventTasks[i].second->startTime() >= eventTasks[i].second->endTime()) {
- event = Event::create(eventNames().enterEvent);
+ event = Event::create(EventTypeNames::enter);
event->setTarget(eventTasks[i].second);
m_asyncEventQueue->enqueueEvent(event.release());
- event = Event::create(eventNames().exitEvent);
+ event = Event::create(EventTypeNames::exit);
event->setTarget(eventTasks[i].second);
m_asyncEventQueue->enqueueEvent(event.release());
} else {
if (eventTasks[i].first == eventTasks[i].second->startTime())
- event = Event::create(eventNames().enterEvent);
+ event = Event::create(EventTypeNames::enter);
else
- event = Event::create(eventNames().exitEvent);
+ event = Event::create(EventTypeNames::exit);
event->setTarget(eventTasks[i].second);
m_asyncEventQueue->enqueueEvent(event.release());
@@ -1167,7 +1111,7 @@ void HTMLMediaElement::updateActiveTextTrackCues(double movieTime)
// 15 - For each text track in affected tracks, in the list order, queue a
// task to fire a simple event named cuechange at the TextTrack object, and, ...
for (size_t i = 0; i < affectedTracks.size(); ++i) {
- RefPtr<Event> event = Event::create(eventNames().cuechangeEvent);
+ RefPtr<Event> event = Event::create(EventTypeNames::cuechange);
event->setTarget(affectedTracks[i]);
m_asyncEventQueue->enqueueEvent(event.release());
@@ -1175,7 +1119,7 @@ void HTMLMediaElement::updateActiveTextTrackCues(double movieTime)
// ... if the text track has a corresponding track element, to then fire a
// simple event named cuechange at the track element as well.
if (affectedTracks[i]->trackType() == TextTrack::TrackElement) {
- RefPtr<Event> event = Event::create(eventNames().cuechangeEvent);
+ RefPtr<Event> event = Event::create(EventTypeNames::cuechange);
HTMLTrackElement* trackElement = static_cast<LoadableTextTrack*>(affectedTracks[i])->trackElement();
ASSERT(trackElement);
event->setTarget(trackElement);
@@ -1255,15 +1199,17 @@ void HTMLMediaElement::textTrackModeChanged(TextTrack* track)
// If this is the first added track, create the list of text tracks.
if (!m_textTracks)
- m_textTracks = TextTrackList::create(this, ActiveDOMObject::scriptExecutionContext());
+ m_textTracks = TextTrackList::create(this);
}
break;
}
} else if (track->trackType() == TextTrack::AddTrack && track->mode() != TextTrack::disabledKeyword())
textTrackAddCues(track, track->cues());
- configureTextTrackDisplay();
- updateActiveTextTrackCues(currentTime());
+ configureTextTrackDisplay(AssumeVisibleChange);
+
+ ASSERT(textTracks()->contains(track));
+ textTracks()->scheduleChangeEvent();
}
void HTMLMediaElement::textTrackKindChanged(TextTrack* track)
@@ -1281,13 +1227,13 @@ void HTMLMediaElement::endIgnoringTrackDisplayUpdateRequests()
{
ASSERT(m_ignoreTrackDisplayUpdate);
--m_ignoreTrackDisplayUpdate;
- if (!m_ignoreTrackDisplayUpdate && m_inActiveDocument)
+ if (!m_ignoreTrackDisplayUpdate && m_active)
updateActiveTextTrackCues(currentTime());
}
void HTMLMediaElement::textTrackAddCues(TextTrack* track, const TextTrackCueList* cues)
{
- LOG(Media, "HTMLMediaElement::textTrackAddCues");
+ WTF_LOG(Media, "HTMLMediaElement::textTrackAddCues");
if (track->mode() == TextTrack::disabledKeyword())
return;
@@ -1298,7 +1244,7 @@ void HTMLMediaElement::textTrackAddCues(TextTrack* track, const TextTrackCueList
void HTMLMediaElement::textTrackRemoveCues(TextTrack*, const TextTrackCueList* cues)
{
- LOG(Media, "HTMLMediaElement::textTrackRemoveCues");
+ WTF_LOG(Media, "HTMLMediaElement::textTrackRemoveCues");
TrackDisplayUpdateScope scope(this);
for (size_t i = 0; i < cues->length(); ++i)
@@ -1329,21 +1275,27 @@ void HTMLMediaElement::textTrackRemoveCue(TextTrack*, PassRefPtr<TextTrackCue> c
CueInterval interval = m_cueTree.createInterval(cue->startTime(), endTime, cue.get());
m_cueTree.remove(interval);
+ // Since the cue will be removed from the media element and likely the
+ // TextTrack might also be destructed, notifying the region of the cue
+ // removal shouldn't be done.
+ cue->notifyRegionWhenRemovingDisplayTree(false);
+
size_t index = m_currentlyActiveCues.find(interval);
if (index != kNotFound) {
m_currentlyActiveCues.remove(index);
cue->setIsActive(false);
}
-
cue->removeDisplayTree();
updateActiveTextTrackCues(currentTime());
+
+ cue->notifyRegionWhenRemovingDisplayTree(true);
}
bool HTMLMediaElement::isSafeToLoadURL(const KURL& url, InvalidURLAction actionIfInvalid)
{
if (!url.isValid()) {
- LOG(Media, "HTMLMediaElement::isSafeToLoadURL(%s) -> FALSE because url is invalid", urlForLoggingMedia(url).utf8().data());
+ WTF_LOG(Media, "HTMLMediaElement::isSafeToLoadURL(%s) -> FALSE because url is invalid", urlForLoggingMedia(url).utf8().data());
return false;
}
@@ -1351,12 +1303,12 @@ bool HTMLMediaElement::isSafeToLoadURL(const KURL& url, InvalidURLAction actionI
if (!frame || !document().securityOrigin()->canDisplay(url)) {
if (actionIfInvalid == Complain)
FrameLoader::reportLocalLoadFailed(frame, url.elidedString());
- LOG(Media, "HTMLMediaElement::isSafeToLoadURL(%s) -> FALSE rejected by SecurityOrigin", urlForLoggingMedia(url).utf8().data());
+ WTF_LOG(Media, "HTMLMediaElement::isSafeToLoadURL(%s) -> FALSE rejected by SecurityOrigin", urlForLoggingMedia(url).utf8().data());
return false;
}
if (!document().contentSecurityPolicy()->allowMediaFromSource(url)) {
- LOG(Media, "HTMLMediaElement::isSafeToLoadURL(%s) -> rejected by Content Security Policy", urlForLoggingMedia(url).utf8().data());
+ WTF_LOG(Media, "HTMLMediaElement::isSafeToLoadURL(%s) -> rejected by Content Security Policy", urlForLoggingMedia(url).utf8().data());
return false;
}
@@ -1375,7 +1327,7 @@ void HTMLMediaElement::startProgressEventTimer()
void HTMLMediaElement::waitForSourceChange()
{
- LOG(Media, "HTMLMediaElement::waitForSourceChange");
+ WTF_LOG(Media, "HTMLMediaElement::waitForSourceChange");
stopPeriodicTimers();
m_loadState = WaitingForSource;
@@ -1394,7 +1346,7 @@ void HTMLMediaElement::waitForSourceChange()
void HTMLMediaElement::noneSupported()
{
- LOG(Media, "HTMLMediaElement::noneSupported");
+ WTF_LOG(Media, "HTMLMediaElement::noneSupported");
stopPeriodicTimers();
m_loadState = WaitingForSource;
@@ -1414,7 +1366,7 @@ void HTMLMediaElement::noneSupported()
m_networkState = NETWORK_NO_SOURCE;
// 7 - Queue a task to fire a simple event named error at the media element.
- scheduleEvent(eventNames().errorEvent);
+ scheduleEvent(EventTypeNames::error);
closeMediaSource();
@@ -1432,7 +1384,7 @@ void HTMLMediaElement::noneSupported()
void HTMLMediaElement::mediaEngineError(PassRefPtr<MediaError> err)
{
- LOG(Media, "HTMLMediaElement::mediaEngineError(%d)", static_cast<int>(err->code()));
+ WTF_LOG(Media, "HTMLMediaElement::mediaEngineError(%d)", static_cast<int>(err->code()));
// 1 - The user agent should cancel the fetching process.
stopPeriodicTimers();
@@ -1443,14 +1395,14 @@ void HTMLMediaElement::mediaEngineError(PassRefPtr<MediaError> err)
m_error = err;
// 3 - Queue a task to fire a simple event named error at the media element.
- scheduleEvent(eventNames().errorEvent);
+ scheduleEvent(EventTypeNames::error);
closeMediaSource();
// 4 - Set the element's networkState attribute to the NETWORK_EMPTY value and queue a
// task to fire a simple event called emptied at the element.
m_networkState = NETWORK_EMPTY;
- scheduleEvent(eventNames().emptiedEvent);
+ scheduleEvent(EventTypeNames::emptied);
// 5 - Set the element's delaying-the-load-event flag to false. This stops delaying the load event.
setShouldDelayLoadEvent(false);
@@ -1461,7 +1413,7 @@ void HTMLMediaElement::mediaEngineError(PassRefPtr<MediaError> err)
void HTMLMediaElement::cancelPendingEventsAndCallbacks()
{
- LOG(Media, "HTMLMediaElement::cancelPendingEventsAndCallbacks");
+ WTF_LOG(Media, "HTMLMediaElement::cancelPendingEventsAndCallbacks");
m_asyncEventQueue->cancelAllEvents();
for (Node* node = firstChild(); node; node = node->nextSibling()) {
@@ -1486,13 +1438,13 @@ void HTMLMediaElement::mediaLoadingFailed(MediaPlayer::NetworkState error)
if (m_currentSourceNode)
m_currentSourceNode->scheduleErrorEvent();
else
- LOG(Media, "HTMLMediaElement::setNetworkState - error event not sent, <source> was removed");
+ WTF_LOG(Media, "HTMLMediaElement::setNetworkState - error event not sent, <source> was removed");
if (havePotentialSourceChild()) {
- LOG(Media, "HTMLMediaElement::setNetworkState - scheduling next <source>");
+ WTF_LOG(Media, "HTMLMediaElement::setNetworkState - scheduling next <source>");
scheduleNextSourceChild();
} else {
- LOG(Media, "HTMLMediaElement::setNetworkState - no more <source> elements, waiting");
+ WTF_LOG(Media, "HTMLMediaElement::setNetworkState - no more <source> elements, waiting");
waitForSourceChange();
}
@@ -1515,7 +1467,7 @@ void HTMLMediaElement::mediaLoadingFailed(MediaPlayer::NetworkState error)
void HTMLMediaElement::setNetworkState(MediaPlayer::NetworkState state)
{
- LOG(Media, "HTMLMediaElement::setNetworkState(%d) - current state is %d", static_cast<int>(state), static_cast<int>(m_networkState));
+ WTF_LOG(Media, "HTMLMediaElement::setNetworkState(%d) - current state is %d", static_cast<int>(state), static_cast<int>(m_networkState));
if (state == MediaPlayer::Empty) {
// Just update the cached state and leave, we can't do anything.
@@ -1561,8 +1513,8 @@ void HTMLMediaElement::changeNetworkStateFromLoadingToIdle()
// Schedule one last progress event so we guarantee that at least one is fired
// for files that load very quickly.
- scheduleEvent(eventNames().progressEvent);
- scheduleEvent(eventNames().suspendEvent);
+ scheduleEvent(EventTypeNames::progress);
+ scheduleEvent(EventTypeNames::suspend);
m_networkState = NETWORK_IDLE;
}
@@ -1573,7 +1525,7 @@ void HTMLMediaElement::mediaPlayerReadyStateChanged()
void HTMLMediaElement::setReadyState(MediaPlayer::ReadyState state)
{
- LOG(Media, "HTMLMediaElement::setReadyState(%d) - current state is %d,", static_cast<int>(state), static_cast<int>(m_readyState));
+ WTF_LOG(Media, "HTMLMediaElement::setReadyState(%d) - current state is %d,", static_cast<int>(state), static_cast<int>(m_readyState));
// Set "wasPotentiallyPlaying" BEFORE updating m_readyState, potentiallyPlaying() uses it
bool wasPotentiallyPlaying = potentiallyPlaying();
@@ -1610,7 +1562,7 @@ void HTMLMediaElement::setReadyState(MediaPlayer::ReadyState state)
// it started seeking, but seeking caused its readyState attribute to change to a value
// lower than HAVE_FUTURE_DATA, then a waiting will be fired at the element.
if (wasPotentiallyPlaying && m_readyState < HAVE_FUTURE_DATA)
- scheduleEvent(eventNames().waitingEvent);
+ scheduleEvent(EventTypeNames::waiting);
// 4.8.10.9 steps 12-14
if (m_readyState >= HAVE_CURRENT_DATA)
@@ -1619,14 +1571,14 @@ void HTMLMediaElement::setReadyState(MediaPlayer::ReadyState state)
if (wasPotentiallyPlaying && m_readyState < HAVE_FUTURE_DATA) {
// 4.8.10.8
scheduleTimeupdateEvent(false);
- scheduleEvent(eventNames().waitingEvent);
+ scheduleEvent(EventTypeNames::waiting);
}
}
if (m_readyState >= HAVE_METADATA && oldState < HAVE_METADATA) {
prepareMediaFragmentURI();
- scheduleEvent(eventNames().durationchangeEvent);
- scheduleEvent(eventNames().loadedmetadataEvent);
+ scheduleEvent(EventTypeNames::durationchange);
+ scheduleEvent(EventTypeNames::loadedmetadata);
if (hasMediaControls())
mediaControls()->loadedMetadata();
if (renderer())
@@ -1638,33 +1590,33 @@ void HTMLMediaElement::setReadyState(MediaPlayer::ReadyState state)
if (m_readyState >= HAVE_CURRENT_DATA && oldState < HAVE_CURRENT_DATA && !m_haveFiredLoadedData) {
m_haveFiredLoadedData = true;
shouldUpdateDisplayState = true;
- scheduleEvent(eventNames().loadeddataEvent);
+ scheduleEvent(EventTypeNames::loadeddata);
setShouldDelayLoadEvent(false);
applyMediaFragmentURI();
}
bool isPotentiallyPlaying = potentiallyPlaying();
if (m_readyState == HAVE_FUTURE_DATA && oldState <= HAVE_CURRENT_DATA && tracksAreReady) {
- scheduleEvent(eventNames().canplayEvent);
+ scheduleEvent(EventTypeNames::canplay);
if (isPotentiallyPlaying)
- scheduleEvent(eventNames().playingEvent);
+ scheduleEvent(EventTypeNames::playing);
shouldUpdateDisplayState = true;
}
if (m_readyState == HAVE_ENOUGH_DATA && oldState < HAVE_ENOUGH_DATA && tracksAreReady) {
if (oldState <= HAVE_CURRENT_DATA)
- scheduleEvent(eventNames().canplayEvent);
+ scheduleEvent(EventTypeNames::canplay);
- scheduleEvent(eventNames().canplaythroughEvent);
+ scheduleEvent(EventTypeNames::canplaythrough);
if (isPotentiallyPlaying && oldState <= HAVE_CURRENT_DATA)
- scheduleEvent(eventNames().playingEvent);
+ scheduleEvent(EventTypeNames::playing);
if (m_autoplaying && m_paused && autoplay() && !document().isSandboxed(SandboxAutomaticFeatures) && !userGestureRequiredForRateChange()) {
m_paused = false;
invalidateCachedTime();
- scheduleEvent(eventNames().playEvent);
- scheduleEvent(eventNames().playingEvent);
+ scheduleEvent(EventTypeNames::play);
+ scheduleEvent(EventTypeNames::playing);
}
shouldUpdateDisplayState = true;
@@ -1692,7 +1644,7 @@ void HTMLMediaElement::mediaPlayerKeyAdded(const String& keySystem, const String
initializer.bubbles = false;
initializer.cancelable = false;
- RefPtr<Event> event = MediaKeyEvent::create(eventNames().webkitkeyaddedEvent, initializer);
+ RefPtr<Event> event = MediaKeyEvent::create(EventTypeNames::webkitkeyadded, initializer);
event->setTarget(this);
m_asyncEventQueue->enqueueEvent(event.release());
}
@@ -1729,7 +1681,7 @@ void HTMLMediaElement::mediaPlayerKeyError(const String& keySystem, const String
initializer.bubbles = false;
initializer.cancelable = false;
- RefPtr<Event> event = MediaKeyEvent::create(eventNames().webkitkeyerrorEvent, initializer);
+ RefPtr<Event> event = MediaKeyEvent::create(EventTypeNames::webkitkeyerror, initializer);
event->setTarget(this);
m_asyncEventQueue->enqueueEvent(event.release());
}
@@ -1744,16 +1696,16 @@ void HTMLMediaElement::mediaPlayerKeyMessage(const String& keySystem, const Stri
initializer.bubbles = false;
initializer.cancelable = false;
- RefPtr<Event> event = MediaKeyEvent::create(eventNames().webkitkeymessageEvent, initializer);
+ RefPtr<Event> event = MediaKeyEvent::create(EventTypeNames::webkitkeymessage, initializer);
event->setTarget(this);
m_asyncEventQueue->enqueueEvent(event.release());
}
bool HTMLMediaElement::mediaPlayerKeyNeeded(const String& keySystem, const String& sessionId, const unsigned char* initData, unsigned initDataLength)
{
- if (!hasEventListeners(eventNames().webkitneedkeyEvent)) {
+ if (!hasEventListeners(EventTypeNames::webkitneedkey)) {
m_error = MediaError::create(MediaError::MEDIA_ERR_ENCRYPTED);
- scheduleEvent(eventNames().errorEvent);
+ scheduleEvent(EventTypeNames::error);
return false;
}
@@ -1764,18 +1716,17 @@ bool HTMLMediaElement::mediaPlayerKeyNeeded(const String& keySystem, const Strin
initializer.bubbles = false;
initializer.cancelable = false;
- RefPtr<Event> event = MediaKeyEvent::create(eventNames().webkitneedkeyEvent, initializer);
+ RefPtr<Event> event = MediaKeyEvent::create(EventTypeNames::webkitneedkey, initializer);
event->setTarget(this);
m_asyncEventQueue->enqueueEvent(event.release());
return true;
}
-#if ENABLE(ENCRYPTED_MEDIA_V2)
bool HTMLMediaElement::mediaPlayerKeyNeeded(Uint8Array* initData)
{
if (!hasEventListeners("webkitneedkey")) {
m_error = MediaError::create(MediaError::MEDIA_ERR_ENCRYPTED);
- scheduleEvent(eventNames().errorEvent);
+ scheduleEvent(EventTypeNames::error);
return false;
}
@@ -1784,7 +1735,7 @@ bool HTMLMediaElement::mediaPlayerKeyNeeded(Uint8Array* initData)
initializer.bubbles = false;
initializer.cancelable = false;
- RefPtr<Event> event = MediaKeyNeededEvent::create(eventNames().webkitneedkeyEvent, initializer);
+ RefPtr<Event> event = MediaKeyNeededEvent::create(EventTypeNames::webkitneedkey, initializer);
event->setTarget(this);
m_asyncEventQueue->enqueueEvent(event.release());
@@ -1802,7 +1753,6 @@ void HTMLMediaElement::setMediaKeys(MediaKeys* mediaKeys)
if (m_mediaKeys)
m_mediaKeys->setMediaElement(this);
}
-#endif
void HTMLMediaElement::progressEventTimerFired(Timer<HTMLMediaElement>*)
{
@@ -1814,7 +1764,7 @@ void HTMLMediaElement::progressEventTimerFired(Timer<HTMLMediaElement>*)
double timedelta = time - m_previousProgressTime;
if (m_player->didLoadingProgress()) {
- scheduleEvent(eventNames().progressEvent);
+ scheduleEvent(EventTypeNames::progress);
m_previousProgressTime = time;
m_sentStalledEvent = false;
if (renderer())
@@ -1822,7 +1772,7 @@ void HTMLMediaElement::progressEventTimerFired(Timer<HTMLMediaElement>*)
if (hasMediaControls())
mediaControls()->bufferingProgressed();
} else if (timedelta > 3.0 && !m_sentStalledEvent) {
- scheduleEvent(eventNames().stalledEvent);
+ scheduleEvent(EventTypeNames::stalled);
m_sentStalledEvent = true;
setShouldDelayLoadEvent(false);
}
@@ -1830,7 +1780,7 @@ void HTMLMediaElement::progressEventTimerFired(Timer<HTMLMediaElement>*)
void HTMLMediaElement::addPlayedRange(double start, double end)
{
- LOG(Media, "HTMLMediaElement::addPlayedRange(%f, %f)", start, end);
+ WTF_LOG(Media, "HTMLMediaElement::addPlayedRange(%f, %f)", start, end);
if (!m_playedTimeRanges)
m_playedTimeRanges = TimeRanges::create();
m_playedTimeRanges->add(start, end);
@@ -1843,22 +1793,22 @@ bool HTMLMediaElement::supportsSave() const
void HTMLMediaElement::prepareToPlay()
{
- LOG(Media, "HTMLMediaElement::prepareToPlay(%p)", this);
+ WTF_LOG(Media, "HTMLMediaElement::prepareToPlay(%p)", this);
if (m_havePreparedToPlay)
return;
m_havePreparedToPlay = true;
m_player->prepareToPlay();
}
-void HTMLMediaElement::seek(double time, ExceptionState& es)
+void HTMLMediaElement::seek(double time, ExceptionState& exceptionState)
{
- LOG(Media, "HTMLMediaElement::seek(%f)", time);
+ WTF_LOG(Media, "HTMLMediaElement::seek(%f)", time);
// 4.8.10.9 Seeking
// 1 - If the media element's readyState is HAVE_NOTHING, then raise an InvalidStateError exception.
if (m_readyState == HAVE_NOTHING || !m_player) {
- es.throwDOMException(InvalidStateError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
return;
}
@@ -1894,7 +1844,7 @@ void HTMLMediaElement::seek(double time, ExceptionState& es)
#if !LOG_DISABLED
double mediaTime = m_player->mediaTimeForTimeValue(time);
if (time != mediaTime)
- LOG(Media, "HTMLMediaElement::seek(%f) - media timeline equivalent is %f", time, mediaTime);
+ WTF_LOG(Media, "HTMLMediaElement::seek(%f) - media timeline equivalent is %f", time, mediaTime);
#endif
time = m_player->mediaTimeForTimeValue(time);
@@ -1916,11 +1866,11 @@ void HTMLMediaElement::seek(double time, ExceptionState& es)
if (noSeekRequired) {
if (time == now) {
- scheduleEvent(eventNames().seekingEvent);
+ scheduleEvent(EventTypeNames::seeking);
// FIXME: There must be a stable state before timeupdate+seeked are dispatched and seeking
// is reset to false. See http://crbug.com/266631
scheduleTimeupdateEvent(false);
- scheduleEvent(eventNames().seekedEvent);
+ scheduleEvent(EventTypeNames::seeked);
}
m_seeking = false;
return;
@@ -1935,7 +1885,7 @@ void HTMLMediaElement::seek(double time, ExceptionState& es)
m_sentEndEvent = false;
// 8 - Queue a task to fire a simple event named seeking at the element.
- scheduleEvent(eventNames().seekingEvent);
+ scheduleEvent(EventTypeNames::seeking);
// 9 - Set the current playback position to the given new playback position
m_player->seek(time);
@@ -1946,7 +1896,7 @@ void HTMLMediaElement::seek(double time, ExceptionState& es)
void HTMLMediaElement::finishSeek()
{
- LOG(Media, "HTMLMediaElement::finishSeek");
+ WTF_LOG(Media, "HTMLMediaElement::finishSeek");
// 4.8.10.9 Seeking completion
// 12 - Set the seeking IDL attribute to false.
@@ -1956,7 +1906,7 @@ void HTMLMediaElement::finishSeek()
scheduleTimeupdateEvent(false);
// 14 - Queue a task to fire a simple event named seeked at the element.
- scheduleEvent(eventNames().seekedEvent);
+ scheduleEvent(EventTypeNames::seeked);
setDisplayMode(Video);
}
@@ -1984,7 +1934,7 @@ void HTMLMediaElement::refreshCachedTime() const
void HTMLMediaElement::invalidateCachedTime()
{
- LOG(Media, "HTMLMediaElement::invalidateCachedTime");
+ WTF_LOG(Media, "HTMLMediaElement::invalidateCachedTime");
// Don't try to cache movie time when playback first starts as the time reported by the engine
// sometimes fluctuates for a short amount of time, so the cached time will be off if we take it
@@ -2006,7 +1956,7 @@ double HTMLMediaElement::currentTime() const
return 0;
if (m_seeking) {
- LOG(Media, "HTMLMediaElement::currentTime - seeking, returning %f", m_lastSeekTime);
+ WTF_LOG(Media, "HTMLMediaElement::currentTime - seeking, returning %f", m_lastSeekTime);
return m_lastSeekTime;
}
@@ -2014,7 +1964,7 @@ double HTMLMediaElement::currentTime() const
#if LOG_CACHED_TIME_WARNINGS
double delta = m_cachedTime - m_player->currentTime();
if (delta > minCachedDeltaForWarning)
- LOG(Media, "HTMLMediaElement::currentTime - WARNING, cached time is %f seconds off of media time when paused", delta);
+ WTF_LOG(Media, "HTMLMediaElement::currentTime - WARNING, cached time is %f seconds off of media time when paused", delta);
#endif
return m_cachedTime;
}
@@ -2024,26 +1974,13 @@ double HTMLMediaElement::currentTime() const
return m_cachedTime;
}
-void HTMLMediaElement::setCurrentTime(double time, ExceptionState& es)
+void HTMLMediaElement::setCurrentTime(double time, ExceptionState& exceptionState)
{
if (m_mediaController) {
- es.throwDOMException(InvalidStateError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
return;
}
- seek(time, es);
-}
-
-double HTMLMediaElement::startTime() const
-{
- return 0;
-}
-
-double HTMLMediaElement::initialTime() const
-{
- if (m_fragmentStartTime != MediaPlayer::invalidTime())
- return m_fragmentStartTime;
-
- return 0;
+ seek(time, exceptionState);
}
double HTMLMediaElement::duration() const
@@ -2081,7 +2018,7 @@ void HTMLMediaElement::setDefaultPlaybackRate(double rate)
{
if (m_defaultPlaybackRate != rate) {
m_defaultPlaybackRate = rate;
- scheduleEvent(eventNames().ratechangeEvent);
+ scheduleEvent(EventTypeNames::ratechange);
}
}
@@ -2092,12 +2029,12 @@ double HTMLMediaElement::playbackRate() const
void HTMLMediaElement::setPlaybackRate(double rate)
{
- LOG(Media, "HTMLMediaElement::setPlaybackRate(%f)", rate);
+ WTF_LOG(Media, "HTMLMediaElement::setPlaybackRate(%f)", rate);
if (m_playbackRate != rate) {
m_playbackRate = rate;
invalidateCachedTime();
- scheduleEvent(eventNames().ratechangeEvent);
+ scheduleEvent(EventTypeNames::ratechange);
}
if (m_player && potentiallyPlaying() && m_player->rate() != rate && !m_mediaController)
@@ -2111,19 +2048,6 @@ void HTMLMediaElement::updatePlaybackRate()
m_player->setRate(effectiveRate);
}
-bool HTMLMediaElement::webkitPreservesPitch() const
-{
- return m_webkitPreservesPitch;
-}
-
-void HTMLMediaElement::setWebkitPreservesPitch(bool preservesPitch)
-{
- LOG(Media, "HTMLMediaElement::setWebkitPreservesPitch(%s)", boolString(preservesPitch));
-
- m_webkitPreservesPitch = preservesPitch;
- notImplemented();
-}
-
bool HTMLMediaElement::ended() const
{
// 4.8.10.8 Playing the media resource
@@ -2137,12 +2061,6 @@ bool HTMLMediaElement::autoplay() const
return fastHasAttribute(autoplayAttr);
}
-void HTMLMediaElement::setAutoplay(bool b)
-{
- LOG(Media, "HTMLMediaElement::setAutoplay(%s)", boolString(b));
- setBooleanAttribute(autoplayAttr, b);
-}
-
String HTMLMediaElement::preload() const
{
switch (m_preload) {
@@ -2163,35 +2081,25 @@ String HTMLMediaElement::preload() const
void HTMLMediaElement::setPreload(const String& preload)
{
- LOG(Media, "HTMLMediaElement::setPreload(%s)", preload.utf8().data());
+ WTF_LOG(Media, "HTMLMediaElement::setPreload(%s)", preload.utf8().data());
setAttribute(preloadAttr, preload);
}
void HTMLMediaElement::play()
{
- LOG(Media, "HTMLMediaElement::play()");
+ WTF_LOG(Media, "HTMLMediaElement::play()");
- if (userGestureRequiredForRateChange() && !ScriptController::processingUserGesture())
+ if (userGestureRequiredForRateChange() && !UserGestureIndicator::processingUserGesture())
return;
- if (ScriptController::processingUserGesture())
+ if (UserGestureIndicator::processingUserGesture())
removeBehaviorsRestrictionsAfterFirstUserGesture();
- Settings* settings = document().settings();
- if (settings && settings->needsSiteSpecificQuirks() && m_dispatchingCanPlayEvent && !m_loadInitiatedByUserGesture) {
- // It should be impossible to be processing the canplay event while handling a user gesture
- // since it is dispatched asynchronously.
- ASSERT(!ScriptController::processingUserGesture());
- String host = document().baseURL().host();
- if (host.endsWith(".npr.org", false) || equalIgnoringCase(host, "npr.org"))
- return;
- }
-
playInternal();
}
void HTMLMediaElement::playInternal()
{
- LOG(Media, "HTMLMediaElement::playInternal");
+ WTF_LOG(Media, "HTMLMediaElement::playInternal");
// 4.8.10.9. Playing the media resource
if (!m_player || m_networkState == NETWORK_EMPTY)
@@ -2206,12 +2114,12 @@ void HTMLMediaElement::playInternal()
if (m_paused) {
m_paused = false;
invalidateCachedTime();
- scheduleEvent(eventNames().playEvent);
+ scheduleEvent(EventTypeNames::play);
if (m_readyState <= HAVE_CURRENT_DATA)
- scheduleEvent(eventNames().waitingEvent);
+ scheduleEvent(EventTypeNames::waiting);
else if (m_readyState >= HAVE_FUTURE_DATA)
- scheduleEvent(eventNames().playingEvent);
+ scheduleEvent(EventTypeNames::playing);
}
m_autoplaying = false;
@@ -2221,9 +2129,9 @@ void HTMLMediaElement::playInternal()
void HTMLMediaElement::pause()
{
- LOG(Media, "HTMLMediaElement::pause()");
+ WTF_LOG(Media, "HTMLMediaElement::pause()");
- if (userGestureRequiredForRateChange() && !ScriptController::processingUserGesture())
+ if (userGestureRequiredForRateChange() && !UserGestureIndicator::processingUserGesture())
return;
pauseInternal();
@@ -2232,7 +2140,7 @@ void HTMLMediaElement::pause()
void HTMLMediaElement::pauseInternal()
{
- LOG(Media, "HTMLMediaElement::pauseInternal");
+ WTF_LOG(Media, "HTMLMediaElement::pauseInternal");
// 4.8.10.9. Playing the media resource
if (!m_player || m_networkState == NETWORK_EMPTY)
@@ -2243,7 +2151,7 @@ void HTMLMediaElement::pauseInternal()
if (!m_paused) {
m_paused = true;
scheduleTimeupdateEvent(false);
- scheduleEvent(eventNames().pauseEvent);
+ scheduleEvent(EventTypeNames::pause);
}
updatePlayState();
@@ -2258,15 +2166,15 @@ void HTMLMediaElement::closeMediaSource()
m_mediaSource = 0;
}
-void HTMLMediaElement::webkitGenerateKeyRequest(const String& keySystem, PassRefPtr<Uint8Array> initData, ExceptionState& es)
+void HTMLMediaElement::webkitGenerateKeyRequest(const String& keySystem, PassRefPtr<Uint8Array> initData, ExceptionState& exceptionState)
{
if (keySystem.isEmpty()) {
- es.throwDOMException(SyntaxError);
+ exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
return;
}
if (!m_player) {
- es.throwDOMException(InvalidStateError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
return;
}
@@ -2278,33 +2186,33 @@ void HTMLMediaElement::webkitGenerateKeyRequest(const String& keySystem, PassRef
}
MediaPlayer::MediaKeyException result = m_player->generateKeyRequest(keySystem, initDataPointer, initDataLength);
- throwExceptionForMediaKeyException(result, es);
+ throwExceptionForMediaKeyException(result, exceptionState);
}
-void HTMLMediaElement::webkitGenerateKeyRequest(const String& keySystem, ExceptionState& es)
+void HTMLMediaElement::webkitGenerateKeyRequest(const String& keySystem, ExceptionState& exceptionState)
{
- webkitGenerateKeyRequest(keySystem, Uint8Array::create(0), es);
+ webkitGenerateKeyRequest(keySystem, Uint8Array::create(0), exceptionState);
}
-void HTMLMediaElement::webkitAddKey(const String& keySystem, PassRefPtr<Uint8Array> key, PassRefPtr<Uint8Array> initData, const String& sessionId, ExceptionState& es)
+void HTMLMediaElement::webkitAddKey(const String& keySystem, PassRefPtr<Uint8Array> key, PassRefPtr<Uint8Array> initData, const String& sessionId, ExceptionState& exceptionState)
{
if (keySystem.isEmpty()) {
- es.throwDOMException(SyntaxError);
+ exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
return;
}
if (!key) {
- es.throwDOMException(SyntaxError);
+ exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
return;
}
if (!key->length()) {
- es.throwDOMException(TypeMismatchError);
+ exceptionState.throwUninformativeAndGenericDOMException(TypeMismatchError);
return;
}
if (!m_player) {
- es.throwDOMException(InvalidStateError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
return;
}
@@ -2316,28 +2224,28 @@ void HTMLMediaElement::webkitAddKey(const String& keySystem, PassRefPtr<Uint8Arr
}
MediaPlayer::MediaKeyException result = m_player->addKey(keySystem, key->data(), key->length(), initDataPointer, initDataLength, sessionId);
- throwExceptionForMediaKeyException(result, es);
+ throwExceptionForMediaKeyException(result, exceptionState);
}
-void HTMLMediaElement::webkitAddKey(const String& keySystem, PassRefPtr<Uint8Array> key, ExceptionState& es)
+void HTMLMediaElement::webkitAddKey(const String& keySystem, PassRefPtr<Uint8Array> key, ExceptionState& exceptionState)
{
- webkitAddKey(keySystem, key, Uint8Array::create(0), String(), es);
+ webkitAddKey(keySystem, key, Uint8Array::create(0), String(), exceptionState);
}
-void HTMLMediaElement::webkitCancelKeyRequest(const String& keySystem, const String& sessionId, ExceptionState& es)
+void HTMLMediaElement::webkitCancelKeyRequest(const String& keySystem, const String& sessionId, ExceptionState& exceptionState)
{
if (keySystem.isEmpty()) {
- es.throwDOMException(SyntaxError);
+ exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
return;
}
if (!m_player) {
- es.throwDOMException(InvalidStateError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
return;
}
MediaPlayer::MediaKeyException result = m_player->cancelKeyRequest(keySystem, sessionId);
- throwExceptionForMediaKeyException(result, es);
+ throwExceptionForMediaKeyException(result, exceptionState);
}
bool HTMLMediaElement::loop() const
@@ -2347,7 +2255,7 @@ bool HTMLMediaElement::loop() const
void HTMLMediaElement::setLoop(bool b)
{
- LOG(Media, "HTMLMediaElement::setLoop(%s)", boolString(b));
+ WTF_LOG(Media, "HTMLMediaElement::setLoop(%s)", boolString(b));
setBooleanAttribute(loopAttr, b);
}
@@ -2356,7 +2264,7 @@ bool HTMLMediaElement::controls() const
Frame* frame = document().frame();
// always show controls when scripting is disabled
- if (frame && !frame->script()->canExecuteScripts(NotAboutToExecuteScript))
+ if (frame && !frame->script().canExecuteScripts(NotAboutToExecuteScript))
return true;
// Always show controls when in full screen mode.
@@ -2368,7 +2276,7 @@ bool HTMLMediaElement::controls() const
void HTMLMediaElement::setControls(bool b)
{
- LOG(Media, "HTMLMediaElement::setControls(%s)", boolString(b));
+ WTF_LOG(Media, "HTMLMediaElement::setControls(%s)", boolString(b));
setBooleanAttribute(controlsAttr, b);
}
@@ -2377,19 +2285,19 @@ double HTMLMediaElement::volume() const
return m_volume;
}
-void HTMLMediaElement::setVolume(double vol, ExceptionState& es)
+void HTMLMediaElement::setVolume(double vol, ExceptionState& exceptionState)
{
- LOG(Media, "HTMLMediaElement::setVolume(%f)", vol);
+ WTF_LOG(Media, "HTMLMediaElement::setVolume(%f)", vol);
if (vol < 0.0f || vol > 1.0f) {
- es.throwDOMException(IndexSizeError);
+ exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
return;
}
if (m_volume != vol) {
m_volume = vol;
updateVolume();
- scheduleEvent(eventNames().volumechangeEvent);
+ scheduleEvent(EventTypeNames::volumechange);
}
}
@@ -2400,7 +2308,7 @@ bool HTMLMediaElement::muted() const
void HTMLMediaElement::setMuted(bool muted)
{
- LOG(Media, "HTMLMediaElement::setMuted(%s)", boolString(muted));
+ WTF_LOG(Media, "HTMLMediaElement::setMuted(%s)", boolString(muted));
if (m_muted != muted) {
m_muted = muted;
@@ -2409,13 +2317,13 @@ void HTMLMediaElement::setMuted(bool muted)
if (hasMediaControls())
mediaControls()->changedMute();
}
- scheduleEvent(eventNames().volumechangeEvent);
+ scheduleEvent(EventTypeNames::volumechange);
}
}
void HTMLMediaElement::togglePlayState()
{
- LOG(Media, "HTMLMediaElement::togglePlayState - canPlay() is %s", boolString(canPlay()));
+ WTF_LOG(Media, "HTMLMediaElement::togglePlayState - canPlay() is %s", boolString(canPlay()));
// We can safely call the internal play/pause methods, which don't check restrictions, because
// this method is only called from the built-in media controller
@@ -2428,7 +2336,7 @@ void HTMLMediaElement::togglePlayState()
void HTMLMediaElement::beginScrubbing()
{
- LOG(Media, "HTMLMediaElement::beginScrubbing - paused() is %s", boolString(paused()));
+ WTF_LOG(Media, "HTMLMediaElement::beginScrubbing - paused() is %s", boolString(paused()));
if (!paused()) {
if (ended()) {
@@ -2447,7 +2355,7 @@ void HTMLMediaElement::beginScrubbing()
void HTMLMediaElement::endScrubbing()
{
- LOG(Media, "HTMLMediaElement::endScrubbing - m_pausedInternal is %s", boolString(m_pausedInternal));
+ WTF_LOG(Media, "HTMLMediaElement::endScrubbing - m_pausedInternal is %s", boolString(m_pausedInternal));
if (m_pausedInternal)
setPausedInternal(false);
@@ -2504,7 +2412,7 @@ void HTMLMediaElement::scheduleTimeupdateEvent(bool periodicEvent)
// event at a given time so filter here
double movieTime = currentTime();
if (movieTime != m_lastTimeUpdateEventMovieTime) {
- scheduleEvent(eventNames().timeupdateEvent);
+ scheduleEvent(EventTypeNames::timeupdate);
m_lastTimeUpdateEventWallTime = now;
m_lastTimeUpdateEventMovieTime = movieTime;
}
@@ -2534,14 +2442,14 @@ double HTMLMediaElement::percentLoaded() const
return buffered / duration;
}
-void HTMLMediaElement::mediaPlayerDidAddTrack(PassRefPtr<InbandTextTrackPrivate> prpTrack)
+void HTMLMediaElement::mediaPlayerDidAddTrack(WebInbandTextTrack* webTrack)
{
if (!RuntimeEnabledFeatures::videoTrackEnabled())
return;
// 4.8.10.12.2 Sourcing in-band text tracks
// 1. Associate the relevant data with a new text track and its corresponding new TextTrack object.
- RefPtr<InbandTextTrack> textTrack = InbandTextTrack::create(ActiveDOMObject::scriptExecutionContext(), this, prpTrack);
+ RefPtr<InbandTextTrack> textTrack = InbandTextTrack::create(document(), this, webTrack);
// 2. Set the new text track's kind, label, and language based on the semantics of the relevant data,
// as defined by the relevant specification. If there is no label in that data, then the label must
@@ -2569,7 +2477,7 @@ void HTMLMediaElement::mediaPlayerDidAddTrack(PassRefPtr<InbandTextTrackPrivate>
addTrack(textTrack.get());
}
-void HTMLMediaElement::mediaPlayerDidRemoveTrack(PassRefPtr<InbandTextTrackPrivate> prpTrack)
+void HTMLMediaElement::mediaPlayerDidRemoveTrack(WebInbandTextTrack* webTrack)
{
if (!RuntimeEnabledFeatures::videoTrackEnabled())
return;
@@ -2577,9 +2485,9 @@ void HTMLMediaElement::mediaPlayerDidRemoveTrack(PassRefPtr<InbandTextTrackPriva
if (!m_textTracks)
return;
- // This cast is safe because we created the InbandTextTrack with the InbandTextTrackPrivate
+ // This cast is safe because we created the InbandTextTrack with the WebInbandTextTrack
// passed to mediaPlayerDidAddTrack.
- RefPtr<InbandTextTrack> textTrack = static_cast<InbandTextTrack*>(prpTrack->client());
+ RefPtr<InbandTextTrack> textTrack = static_cast<InbandTextTrack*>(webTrack->client());
if (!textTrack)
return;
@@ -2624,17 +2532,16 @@ void HTMLMediaElement::removeAllInbandTracks()
}
}
-PassRefPtr<TextTrack> HTMLMediaElement::addTextTrack(const String& kind, const String& label, const String& language, ExceptionState& es)
+PassRefPtr<TextTrack> HTMLMediaElement::addTextTrack(const String& kind, const String& label, const String& language, ExceptionState& exceptionState)
{
- if (!RuntimeEnabledFeatures::videoTrackEnabled())
- return 0;
+ ASSERT(RuntimeEnabledFeatures::videoTrackEnabled());
// 4.8.10.12.4 Text track API
// The addTextTrack(kind, label, language) method of media elements, when invoked, must run the following steps:
// 1. If kind is not one of the following strings, then throw a SyntaxError exception and abort these steps
if (!TextTrack::isValidKindKeyword(kind)) {
- es.throwDOMException(SyntaxError);
+ exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
return 0;
}
@@ -2644,7 +2551,7 @@ PassRefPtr<TextTrack> HTMLMediaElement::addTextTrack(const String& kind, const S
// 5. Create a new text track corresponding to the new object, and set its text track kind to kind, its text
// track label to label, its text track language to language...
- RefPtr<TextTrack> textTrack = TextTrack::create(ActiveDOMObject::scriptExecutionContext(), this, kind, label, language);
+ RefPtr<TextTrack> textTrack = TextTrack::create(document(), this, kind, label, language);
// Note, due to side effects when changing track parameters, we have to
// first append the track to the text track list.
@@ -2663,11 +2570,10 @@ PassRefPtr<TextTrack> HTMLMediaElement::addTextTrack(const String& kind, const S
TextTrackList* HTMLMediaElement::textTracks()
{
- if (!RuntimeEnabledFeatures::videoTrackEnabled())
- return 0;
+ ASSERT(RuntimeEnabledFeatures::videoTrackEnabled());
if (!m_textTracks)
- m_textTracks = TextTrackList::create(this, ActiveDOMObject::scriptExecutionContext());
+ m_textTracks = TextTrackList::create(this);
return m_textTracks.get();
}
@@ -2708,7 +2614,7 @@ void HTMLMediaElement::didRemoveTrack(HTMLTrackElement* trackElement)
#if !LOG_DISABLED
if (trackElement->hasTagName(trackTag)) {
KURL url = trackElement->getNonEmptyURLAttribute(srcAttr);
- LOG(Media, "HTMLMediaElement::didRemoveTrack - 'src' is %s", urlForLoggingMedia(url).utf8().data());
+ WTF_LOG(Media, "HTMLMediaElement::didRemoveTrack - 'src' is %s", urlForLoggingMedia(url).utf8().data());
}
#endif
@@ -2769,10 +2675,9 @@ void HTMLMediaElement::configureTextTrackGroup(const TrackGroup& group)
{
ASSERT(group.tracks.size());
- LOG(Media, "HTMLMediaElement::configureTextTrackGroup(%d)", group.kind);
+ WTF_LOG(Media, "HTMLMediaElement::configureTextTrackGroup(%d)", group.kind);
- Page* page = document().page();
- Settings* settings = page ? &page->settings() : 0;
+ Settings* settings = document().settings();
// First, find the track in the group that should be enabled (if any).
Vector<RefPtr<TextTrack> > currentlyEnabledTracks;
@@ -2921,13 +2826,13 @@ KURL HTMLMediaElement::selectNextSourceChild(ContentType* contentType, String* k
// Don't log if this was just called to find out if there are any valid <source> elements.
bool shouldLog = actionIfInvalid != DoNothing;
if (shouldLog)
- LOG(Media, "HTMLMediaElement::selectNextSourceChild");
+ WTF_LOG(Media, "HTMLMediaElement::selectNextSourceChild");
#endif
if (!m_nextChildNodeToConsider) {
#if !LOG_DISABLED
if (shouldLog)
- LOG(Media, "HTMLMediaElement::selectNextSourceChild -> 0x0000, \"\"");
+ WTF_LOG(Media, "HTMLMediaElement::selectNextSourceChild -> 0x0000, \"\"");
#endif
return KURL();
}
@@ -2942,7 +2847,7 @@ KURL HTMLMediaElement::selectNextSourceChild(ContentType* contentType, String* k
bool okToLoadSourceURL;
NodeVector potentialSourceNodes;
- getChildNodes(this, potentialSourceNodes);
+ getChildNodes(*this, potentialSourceNodes);
for (unsigned i = 0; !canUseSourceElement && i < potentialSourceNodes.size(); ++i) {
node = potentialSourceNodes[i].get();
@@ -2955,13 +2860,14 @@ KURL HTMLMediaElement::selectNextSourceChild(ContentType* contentType, String* k
if (node->parentNode() != this)
continue;
+ UseCounter::count(document(), UseCounter::SourceElementCandidate);
source = toHTMLSourceElement(node);
// If candidate does not have a src attribute, or if its src attribute's value is the empty string ... jump down to the failed step below
mediaURL = source->getNonEmptyURLAttribute(srcAttr);
#if !LOG_DISABLED
if (shouldLog)
- LOG(Media, "HTMLMediaElement::selectNextSourceChild - 'src' is %s", urlForLoggingMedia(mediaURL).utf8().data());
+ WTF_LOG(Media, "HTMLMediaElement::selectNextSourceChild - 'src' is %s", urlForLoggingMedia(mediaURL).utf8().data());
#endif
if (mediaURL.isEmpty())
goto check_again;
@@ -2971,10 +2877,12 @@ KURL HTMLMediaElement::selectNextSourceChild(ContentType* contentType, String* k
RefPtr<MediaQuerySet> media = MediaQuerySet::create(source->media());
#if !LOG_DISABLED
if (shouldLog)
- LOG(Media, "HTMLMediaElement::selectNextSourceChild - 'media' is %s", source->media().utf8().data());
+ WTF_LOG(Media, "HTMLMediaElement::selectNextSourceChild - 'media' is %s", source->media().string().utf8().data());
#endif
- if (!screenEval.eval(media.get()))
+ if (!screenEval.eval(media.get())) {
+ UseCounter::count(document(), UseCounter::SourceElementNonMatchingMedia);
goto check_again;
+ }
}
type = source->type();
@@ -2984,7 +2892,7 @@ KURL HTMLMediaElement::selectNextSourceChild(ContentType* contentType, String* k
if (!type.isEmpty() || !system.isEmpty()) {
#if !LOG_DISABLED
if (shouldLog)
- LOG(Media, "HTMLMediaElement::selectNextSourceChild - 'type' is '%s' - key system is '%s'", type.utf8().data(), system.utf8().data());
+ WTF_LOG(Media, "HTMLMediaElement::selectNextSourceChild - 'type' is '%s' - key system is '%s'", type.utf8().data(), system.utf8().data());
#endif
if (!supportsType(ContentType(type), system))
goto check_again;
@@ -2995,7 +2903,7 @@ KURL HTMLMediaElement::selectNextSourceChild(ContentType* contentType, String* k
// A 'beforeload' event handler can mutate the DOM, so check to see if the source element is still a child node.
if (node->parentNode() != this) {
- LOG(Media, "HTMLMediaElement::selectNextSourceChild : 'beforeload' removed current element");
+ WTF_LOG(Media, "HTMLMediaElement::selectNextSourceChild : 'beforeload' removed current element");
source = 0;
goto check_again;
}
@@ -3025,19 +2933,19 @@ check_again:
#if !LOG_DISABLED
if (shouldLog)
- LOG(Media, "HTMLMediaElement::selectNextSourceChild -> %p, %s", m_currentSourceNode.get(), canUseSourceElement ? urlForLoggingMedia(mediaURL).utf8().data() : "");
+ WTF_LOG(Media, "HTMLMediaElement::selectNextSourceChild -> %p, %s", m_currentSourceNode.get(), canUseSourceElement ? urlForLoggingMedia(mediaURL).utf8().data() : "");
#endif
return canUseSourceElement ? mediaURL : KURL();
}
void HTMLMediaElement::sourceWasAdded(HTMLSourceElement* source)
{
- LOG(Media, "HTMLMediaElement::sourceWasAdded(%p)", source);
+ WTF_LOG(Media, "HTMLMediaElement::sourceWasAdded(%p)", source);
#if !LOG_DISABLED
if (source->hasTagName(sourceTag)) {
KURL url = source->getNonEmptyURLAttribute(srcAttr);
- LOG(Media, "HTMLMediaElement::sourceWasAdded - 'src' is %s", urlForLoggingMedia(url).utf8().data());
+ WTF_LOG(Media, "HTMLMediaElement::sourceWasAdded - 'src' is %s", urlForLoggingMedia(url).utf8().data());
}
#endif
@@ -3055,7 +2963,7 @@ void HTMLMediaElement::sourceWasAdded(HTMLSourceElement* source)
}
if (m_currentSourceNode && source == m_currentSourceNode->nextSibling()) {
- LOG(Media, "HTMLMediaElement::sourceWasAdded - <source> inserted immediately after current source");
+ WTF_LOG(Media, "HTMLMediaElement::sourceWasAdded - <source> inserted immediately after current source");
m_nextChildNodeToConsider = source;
return;
}
@@ -3080,12 +2988,12 @@ void HTMLMediaElement::sourceWasAdded(HTMLSourceElement* source)
void HTMLMediaElement::sourceWasRemoved(HTMLSourceElement* source)
{
- LOG(Media, "HTMLMediaElement::sourceWasRemoved(%p)", source);
+ WTF_LOG(Media, "HTMLMediaElement::sourceWasRemoved(%p)", source);
#if !LOG_DISABLED
if (source->hasTagName(sourceTag)) {
KURL url = source->getNonEmptyURLAttribute(srcAttr);
- LOG(Media, "HTMLMediaElement::sourceWasRemoved - 'src' is %s", urlForLoggingMedia(url).utf8().data());
+ WTF_LOG(Media, "HTMLMediaElement::sourceWasRemoved - 'src' is %s", urlForLoggingMedia(url).utf8().data());
}
#endif
@@ -3095,19 +3003,19 @@ void HTMLMediaElement::sourceWasRemoved(HTMLSourceElement* source)
if (source == m_nextChildNodeToConsider) {
if (m_currentSourceNode)
m_nextChildNodeToConsider = m_currentSourceNode->nextSibling();
- LOG(Media, "HTMLMediaElement::sourceRemoved - m_nextChildNodeToConsider set to %p", m_nextChildNodeToConsider.get());
+ WTF_LOG(Media, "HTMLMediaElement::sourceRemoved - m_nextChildNodeToConsider set to %p", m_nextChildNodeToConsider.get());
} else if (source == m_currentSourceNode) {
// Clear the current source node pointer, but don't change the movie as the spec says:
// 4.8.8 - Dynamically modifying a source element and its attribute when the element is already
// inserted in a video or audio element will have no effect.
m_currentSourceNode = 0;
- LOG(Media, "HTMLMediaElement::sourceRemoved - m_currentSourceNode set to 0");
+ WTF_LOG(Media, "HTMLMediaElement::sourceRemoved - m_currentSourceNode set to 0");
}
}
void HTMLMediaElement::mediaPlayerTimeChanged()
{
- LOG(Media, "HTMLMediaElement::mediaPlayerTimeChanged");
+ WTF_LOG(Media, "HTMLMediaElement::mediaPlayerTimeChanged");
if (RuntimeEnabledFeatures::videoTrackEnabled())
updateActiveTextTrackCues(currentTime());
@@ -3133,7 +3041,7 @@ void HTMLMediaElement::mediaPlayerTimeChanged()
if (loop() && !m_mediaController) {
m_sentEndEvent = false;
// then seek to the earliest possible position of the media resource and abort these steps.
- seek(startTime(), IGNORE_EXCEPTION);
+ seek(0, IGNORE_EXCEPTION);
} else {
// If the media element does not have a current media controller, and the media element
// has still ended playback, and the direction of playback is still forwards, and paused
@@ -3141,12 +3049,12 @@ void HTMLMediaElement::mediaPlayerTimeChanged()
if (!m_mediaController && !m_paused) {
// changes paused to true and fires a simple event named pause at the media element.
m_paused = true;
- scheduleEvent(eventNames().pauseEvent);
+ scheduleEvent(EventTypeNames::pause);
}
// Queue a task to fire a simple event named ended at the media element.
if (!m_sentEndEvent) {
m_sentEndEvent = true;
- scheduleEvent(eventNames().endedEvent);
+ scheduleEvent(EventTypeNames::ended);
}
// If the media element has a current media controller, then report the controller state
// for the media element's current media controller.
@@ -3161,20 +3069,20 @@ void HTMLMediaElement::mediaPlayerTimeChanged()
void HTMLMediaElement::mediaPlayerDurationChanged()
{
- LOG(Media, "HTMLMediaElement::mediaPlayerDurationChanged");
+ WTF_LOG(Media, "HTMLMediaElement::mediaPlayerDurationChanged");
durationChanged(duration());
}
void HTMLMediaElement::durationChanged(double duration)
{
- LOG(Media, "HTMLMediaElement::durationChanged(%f)", duration);
+ WTF_LOG(Media, "HTMLMediaElement::durationChanged(%f)", duration);
// Abort if duration unchanged.
if (m_duration == duration)
return;
m_duration = duration;
- scheduleEvent(eventNames().durationchangeEvent);
+ scheduleEvent(EventTypeNames::durationchange);
if (hasMediaControls())
mediaControls()->reset();
@@ -3187,7 +3095,7 @@ void HTMLMediaElement::durationChanged(double duration)
void HTMLMediaElement::mediaPlayerPlaybackStateChanged()
{
- LOG(Media, "HTMLMediaElement::mediaPlayerPlaybackStateChanged");
+ WTF_LOG(Media, "HTMLMediaElement::mediaPlayerPlaybackStateChanged");
if (!m_player || m_pausedInternal)
return;
@@ -3198,6 +3106,12 @@ void HTMLMediaElement::mediaPlayerPlaybackStateChanged()
playInternal();
}
+void HTMLMediaElement::mediaPlayerRequestFullscreen()
+{
+ WTF_LOG(Media, "HTMLMediaElement::mediaPlayerRequestFullscreen");
+ enterFullscreen();
+}
+
void HTMLMediaElement::mediaPlayerRequestSeek(double time)
{
// The player is the source of this seek request.
@@ -3211,6 +3125,9 @@ void HTMLMediaElement::mediaPlayerRequestSeek(double time)
// MediaPlayerPresentation methods
void HTMLMediaElement::mediaPlayerRepaint()
{
+ if (m_webLayer)
+ m_webLayer->invalidate();
+
updateDisplayState();
if (renderer())
renderer()->repaint();
@@ -3218,15 +3135,11 @@ void HTMLMediaElement::mediaPlayerRepaint()
void HTMLMediaElement::mediaPlayerSizeChanged()
{
- LOG(Media, "HTMLMediaElement::mediaPlayerSizeChanged");
+ WTF_LOG(Media, "HTMLMediaElement::mediaPlayerSizeChanged");
- if (renderer())
- renderer()->updateFromElement();
-}
+ if (m_readyState > HAVE_NOTHING)
+ scheduleEvent(EventTypeNames::resize);
-void HTMLMediaElement::mediaPlayerEngineUpdated()
-{
- LOG(Media, "HTMLMediaElement::mediaPlayerEngineUpdated");
if (renderer())
renderer()->updateFromElement();
}
@@ -3258,8 +3171,12 @@ PassRefPtr<TimeRanges> HTMLMediaElement::played()
PassRefPtr<TimeRanges> HTMLMediaElement::seekable() const
{
- double maxSeekable = maxTimeSeekable();
- return maxSeekable ? TimeRanges::create(0, maxSeekable) : TimeRanges::create();
+ if (m_player) {
+ double maxTimeSeekable = m_player->maxTimeSeekable();
+ if (maxTimeSeekable)
+ return TimeRanges::create(0, maxTimeSeekable);
+ }
+ return TimeRanges::create();
}
bool HTMLMediaElement::potentiallyPlaying() const
@@ -3321,16 +3238,6 @@ bool HTMLMediaElement::pausedForUserInteraction() const
return false;
}
-double HTMLMediaElement::minTimeSeekable() const
-{
- return 0;
-}
-
-double HTMLMediaElement::maxTimeSeekable() const
-{
- return m_player ? m_player->maxTimeSeekable() : 0;
-}
-
void HTMLMediaElement::updateVolume()
{
if (!m_player)
@@ -3369,7 +3276,7 @@ void HTMLMediaElement::updatePlayState()
bool shouldBePlaying = potentiallyPlaying();
bool playerPaused = m_player->paused();
- LOG(Media, "HTMLMediaElement::updatePlayState - shouldBePlaying = %s, playerPaused = %s",
+ WTF_LOG(Media, "HTMLMediaElement::updatePlayState - shouldBePlaying = %s, playerPaused = %s",
boolString(shouldBePlaying), boolString(playerPaused));
if (shouldBePlaying) {
@@ -3428,7 +3335,7 @@ void HTMLMediaElement::stopPeriodicTimers()
void HTMLMediaElement::userCancelledLoad()
{
- LOG(Media, "HTMLMediaElement::userCancelledLoad");
+ WTF_LOG(Media, "HTMLMediaElement::userCancelledLoad");
// If the media data fetching process is aborted by the user:
@@ -3442,7 +3349,7 @@ void HTMLMediaElement::userCancelledLoad()
m_error = MediaError::create(MediaError::MEDIA_ERR_ABORTED);
// 3 - Queue a task to fire a simple event named error at the media element.
- scheduleEvent(eventNames().abortEvent);
+ scheduleEvent(EventTypeNames::abort);
closeMediaSource();
@@ -3452,7 +3359,7 @@ void HTMLMediaElement::userCancelledLoad()
// attribute to the NETWORK_IDLE value.
if (m_readyState == HAVE_NOTHING) {
m_networkState = NETWORK_EMPTY;
- scheduleEvent(eventNames().emptiedEvent);
+ scheduleEvent(EventTypeNames::emptied);
}
else
m_networkState = NETWORK_IDLE;
@@ -3470,17 +3377,32 @@ void HTMLMediaElement::userCancelledLoad()
updateActiveTextTrackCues(0);
}
-void HTMLMediaElement::clearMediaPlayer(int flags)
+void HTMLMediaElement::clearMediaPlayerAndAudioSourceProviderClient()
{
- removeAllInbandTracks();
+#if ENABLE(WEB_AUDIO)
+ if (m_audioSourceNode)
+ m_audioSourceNode->lock();
- closeMediaSource();
+ if (audioSourceProvider())
+ audioSourceProvider()->setClient(0);
+#endif
m_player.clear();
+
#if ENABLE(WEB_AUDIO)
- if (audioSourceProvider())
- audioSourceProvider()->setClient(0);
+ if (m_audioSourceNode)
+ m_audioSourceNode->unlock();
#endif
+}
+
+void HTMLMediaElement::clearMediaPlayer(int flags)
+{
+ removeAllInbandTracks();
+
+ closeMediaSource();
+
+ clearMediaPlayerAndAudioSourceProviderClient();
+
stopPeriodicTimers();
m_loadTimer.stop();
@@ -3488,19 +3410,14 @@ void HTMLMediaElement::clearMediaPlayer(int flags)
m_loadState = WaitingForSource;
if (m_textTracks)
- configureTextTrackDisplay();
-}
-
-bool HTMLMediaElement::canSuspend() const
-{
- return true;
+ configureTextTrackDisplay(AssumeNoVisibleChange);
}
void HTMLMediaElement::stop()
{
- LOG(Media, "HTMLMediaElement::stop");
+ WTF_LOG(Media, "HTMLMediaElement::stop");
- m_inActiveDocument = false;
+ m_active = false;
userCancelledLoad();
// Stop the playback without generating events
@@ -3516,45 +3433,16 @@ void HTMLMediaElement::stop()
m_asyncEventQueue->close();
}
-void HTMLMediaElement::suspend(ReasonForSuspension why)
-{
- LOG(Media, "HTMLMediaElement::suspend");
-
- switch (why)
- {
- case DocumentWillBecomeInactive:
- stop();
- break;
- case JavaScriptDebuggerPaused:
- case WillDeferLoading:
- // Do nothing, we don't pause media playback in these cases.
- break;
- }
-}
-
-void HTMLMediaElement::resume()
+bool HTMLMediaElement::hasPendingActivity() const
{
- LOG(Media, "HTMLMediaElement::resume");
-
- m_inActiveDocument = true;
- setPausedInternal(false);
-
- if (m_error && m_error->code() == MediaError::MEDIA_ERR_ABORTED) {
- // Restart the load if it was aborted in the middle by moving the document to the page cache.
- // m_error is only left at MEDIA_ERR_ABORTED when the document becomes inactive (it is set to
- // MEDIA_ERR_ABORTED while the abortEvent is being sent, but cleared immediately afterwards).
- // This behavior is not specified but it seems like a sensible thing to do.
- // As it is not safe to immedately start loading now, let's schedule a load.
- scheduleDelayedAction(LoadMediaResource);
- }
-
- if (renderer())
- renderer()->updateFromElement();
+ return (hasAudio() && isPlaying()) || m_asyncEventQueue->hasPendingEvents();
}
-bool HTMLMediaElement::hasPendingActivity() const
+void HTMLMediaElement::contextDestroyed()
{
- return (hasAudio() && isPlaying()) || m_asyncEventQueue->hasPendingEvents();
+ if (m_mediaController)
+ m_mediaController->clearExecutionContext();
+ ActiveDOMObject::contextDestroyed();
}
bool HTMLMediaElement::isFullscreen() const
@@ -3564,20 +3452,15 @@ bool HTMLMediaElement::isFullscreen() const
void HTMLMediaElement::enterFullscreen()
{
- LOG(Media, "HTMLMediaElement::enterFullscreen");
+ WTF_LOG(Media, "HTMLMediaElement::enterFullscreen");
- bool processingUserGesture = ScriptController::processingUserGesture();
if (document().settings() && document().settings()->fullScreenEnabled())
FullscreenElementStack::from(&document())->requestFullScreenForElement(this, 0, FullscreenElementStack::ExemptIFrameAllowFullScreenRequirement);
- // If gesture is consumed by FullscreenElementStack, remove all the behavior
- // restrictions as other media operations may depend on the same gesture.
- if (processingUserGesture && !ScriptController::processingUserGesture())
- removeBehaviorsRestrictionsAfterFirstUserGesture();
}
void HTMLMediaElement::exitFullscreen()
{
- LOG(Media, "HTMLMediaElement::exitFullscreen");
+ WTF_LOG(Media, "HTMLMediaElement::exitFullscreen");
if (document().settings() && document().settings()->fullScreenEnabled() && isFullscreen())
FullscreenElementStack::from(&document())->webkitCancelFullScreen();
@@ -3599,9 +3482,9 @@ void HTMLMediaElement::willStopBeingFullscreenElement()
document().renderView()->compositor()->setCompositingLayersNeedRebuild(true);
}
-WebKit::WebLayer* HTMLMediaElement::platformLayer() const
+blink::WebLayer* HTMLMediaElement::platformLayer() const
{
- return m_player ? m_player->platformLayer() : 0;
+ return m_webLayer;
}
bool HTMLMediaElement::hasClosedCaptions() const
@@ -3626,7 +3509,7 @@ bool HTMLMediaElement::closedCaptionsVisible() const
void HTMLMediaElement::updateTextTrackDisplay()
{
- LOG(Media, "HTMLMediaElement::updateTextTrackDisplay");
+ WTF_LOG(Media, "HTMLMediaElement::updateTextTrackDisplay");
if (!hasMediaControls() && !createMediaControls())
return;
@@ -3636,7 +3519,7 @@ void HTMLMediaElement::updateTextTrackDisplay()
void HTMLMediaElement::setClosedCaptionsVisible(bool closedCaptionVisible)
{
- LOG(Media, "HTMLMediaElement::setClosedCaptionsVisible(%s)", boolString(closedCaptionVisible));
+ WTF_LOG(Media, "HTMLMediaElement::setClosedCaptionsVisible(%s)", boolString(closedCaptionVisible));
if (!m_player || !hasClosedCaptions())
return;
@@ -3652,22 +3535,6 @@ void HTMLMediaElement::setClosedCaptionsVisible(bool closedCaptionVisible)
}
}
-void HTMLMediaElement::setWebkitClosedCaptionsVisible(bool visible)
-{
- setClosedCaptionsVisible(visible);
-}
-
-bool HTMLMediaElement::webkitClosedCaptionsVisible() const
-{
- return closedCaptionsVisible();
-}
-
-
-bool HTMLMediaElement::webkitHasClosedCaptions() const
-{
- return hasClosedCaptions();
-}
-
unsigned HTMLMediaElement::webkitAudioDecodedByteCount() const
{
if (!m_player)
@@ -3692,7 +3559,7 @@ void HTMLMediaElement::setShouldDelayLoadEvent(bool shouldDelay)
if (m_shouldDelayLoadEvent == shouldDelay)
return;
- LOG(Media, "HTMLMediaElement::setShouldDelayLoadEvent(%s)", boolString(shouldDelay));
+ WTF_LOG(Media, "HTMLMediaElement::setShouldDelayLoadEvent(%s)", boolString(shouldDelay));
m_shouldDelayLoadEvent = shouldDelay;
if (shouldDelay)
@@ -3732,7 +3599,7 @@ bool HTMLMediaElement::createMediaControls()
if (isFullscreen())
mediaControls->enteredFullscreen();
- ensureUserAgentShadowRoot()->appendChild(mediaControls);
+ ensureUserAgentShadowRoot().appendChild(mediaControls);
if (!controls() || !inDocument())
mediaControls->hide();
@@ -3754,10 +3621,10 @@ void HTMLMediaElement::configureMediaControls()
mediaControls()->show();
}
-void HTMLMediaElement::configureTextTrackDisplay()
+void HTMLMediaElement::configureTextTrackDisplay(VisibilityChangeAssumption assumption)
{
ASSERT(m_textTracks);
- LOG(Media, "HTMLMediaElement::configureTextTrackDisplay");
+ WTF_LOG(Media, "HTMLMediaElement::configureTextTrackDisplay");
if (m_processingPreferenceChange)
return;
@@ -3770,8 +3637,11 @@ void HTMLMediaElement::configureTextTrackDisplay()
}
}
- if (m_haveVisibleTextTrack == haveVisibleTextTrack)
+ if (assumption == AssumeNoVisibleChange
+ && m_haveVisibleTextTrack == haveVisibleTextTrack) {
+ updateActiveTextTrackCues(currentTime());
return;
+ }
m_haveVisibleTextTrack = haveVisibleTextTrack;
m_closedCaptionsVisible = m_haveVisibleTextTrack;
@@ -3782,8 +3652,10 @@ void HTMLMediaElement::configureTextTrackDisplay()
mediaControls()->changedClosedCaptionsVisibility();
- if (RuntimeEnabledFeatures::videoTrackEnabled())
+ if (RuntimeEnabledFeatures::videoTrackEnabled()) {
+ updateActiveTextTrackCues(currentTime());
updateTextTrackDisplay();
+ }
}
void HTMLMediaElement::markCaptionAndSubtitleTracksAsUnconfigured()
@@ -3809,7 +3681,7 @@ void HTMLMediaElement::markCaptionAndSubtitleTracksAsUnconfigured()
void* HTMLMediaElement::preDispatchEventHandler(Event* event)
{
- if (event && event->type() == eventNames().webkitfullscreenchangeEvent)
+ if (event && event->type() == EventTypeNames::webkitfullscreenchange)
configureMediaControls();
return 0;
@@ -3843,8 +3715,14 @@ void HTMLMediaElement::setAudioSourceNode(MediaElementAudioSourceNode* sourceNod
{
m_audioSourceNode = sourceNode;
+ if (m_audioSourceNode)
+ m_audioSourceNode->lock();
+
if (audioSourceProvider())
audioSourceProvider()->setClient(m_audioSourceNode);
+
+ if (m_audioSourceNode)
+ m_audioSourceNode->unlock();
}
AudioSourceProvider* HTMLMediaElement::audioSourceProvider()
@@ -3856,22 +3734,18 @@ AudioSourceProvider* HTMLMediaElement::audioSourceProvider()
}
#endif
-const String& HTMLMediaElement::mediaGroup() const
+const AtomicString& HTMLMediaElement::mediaGroup() const
{
- return m_mediaGroup;
+ return fastGetAttribute(mediagroupAttr);
}
-void HTMLMediaElement::setMediaGroup(const String& group)
+void HTMLMediaElement::setMediaGroup(const AtomicString& group)
{
- if (m_mediaGroup == group)
- return;
- m_mediaGroup = group;
-
// When a media element is created with a mediagroup attribute, and when a media element's mediagroup
// attribute is set, changed, or removed, the user agent must run the following steps:
// 1. Let m [this] be the media element in question.
// 2. Let m have no current media controller, if it currently has one.
- setController(0);
+ setControllerInternal(0);
// 3. If m's mediagroup attribute is being removed, then abort these steps.
if (group.isNull() || group.isEmpty())
@@ -3888,13 +3762,13 @@ void HTMLMediaElement::setMediaGroup(const String& group)
// the new value of m's mediagroup attribute,
if ((*i)->mediaGroup() == group) {
// then let controller be that media element's current media controller.
- setController((*i)->controller());
+ setControllerInternal((*i)->controller());
return;
}
}
// Otherwise, let controller be a newly created MediaController.
- setController(MediaController::create(Node::scriptExecutionContext()));
+ setControllerInternal(MediaController::create(Node::executionContext()));
}
MediaController* HTMLMediaElement::controller() const
@@ -3904,6 +3778,15 @@ MediaController* HTMLMediaElement::controller() const
void HTMLMediaElement::setController(PassRefPtr<MediaController> controller)
{
+ // 4.8.10.11.2 Media controllers: controller attribute.
+ // On setting, it must first remove the element's mediagroup attribute, if any,
+ removeAttribute(mediagroupAttr);
+ // and then set the current media controller to the given value.
+ setControllerInternal(controller);
+}
+
+void HTMLMediaElement::setControllerInternal(PassRefPtr<MediaController> controller)
+{
if (m_mediaController)
m_mediaController->removeMediaElement(this);
@@ -3922,24 +3805,6 @@ void HTMLMediaElement::updateMediaController()
m_mediaController->reportControllerState();
}
-bool HTMLMediaElement::dispatchEvent(PassRefPtr<Event> event)
-{
- bool dispatchResult;
- bool isCanPlayEvent;
-
- isCanPlayEvent = (event->type() == eventNames().canplayEvent);
-
- if (isCanPlayEvent)
- m_dispatchingCanPlayEvent = true;
-
- dispatchResult = HTMLElement::dispatchEvent(event);
-
- if (isCanPlayEvent)
- m_dispatchingCanPlayEvent = false;
-
- return dispatchResult;
-}
-
bool HTMLMediaElement::isBlocked() const
{
// A media element is a blocked media element if its readyState attribute is in the
@@ -3965,7 +3830,7 @@ bool HTMLMediaElement::isBlockedOnMediaController() const
// position relative to the MediaController's timeline or after the end of the media resource
// relative to the MediaController's timeline.
double mediaControllerPosition = m_mediaController->currentTime();
- if (mediaControllerPosition < startTime() || mediaControllerPosition > startTime() + duration())
+ if (mediaControllerPosition < 0 || mediaControllerPosition > duration())
return true;
return false;
@@ -4006,9 +3871,9 @@ void HTMLMediaElement::applyMediaFragmentURI()
MediaPlayerClient::CORSMode HTMLMediaElement::mediaPlayerCORSMode() const
{
- if (!fastHasAttribute(HTMLNames::crossoriginAttr))
+ if (!fastHasAttribute(crossoriginAttr))
return Unspecified;
- if (equalIgnoringCase(fastGetAttribute(HTMLNames::crossoriginAttr), "use-credentials"))
+ if (equalIgnoringCase(fastGetAttribute(crossoriginAttr), "use-credentials"))
return UseCredentials;
return Anonymous;
}
@@ -4018,9 +3883,29 @@ void HTMLMediaElement::removeBehaviorsRestrictionsAfterFirstUserGesture()
m_restrictions = NoRestrictions;
}
-void HTMLMediaElement::mediaPlayerScheduleLayerUpdate()
+void HTMLMediaElement::mediaPlayerSetWebLayer(blink::WebLayer* webLayer)
+{
+ if (webLayer == m_webLayer)
+ return;
+
+ // If either of the layers is null we need to enable or disable compositing. This is done by triggering a style recalc.
+ if (!m_webLayer || !webLayer)
+ scheduleLayerUpdate();
+
+ if (m_webLayer)
+ GraphicsLayer::unregisterContentsLayer(m_webLayer);
+ m_webLayer = webLayer;
+ if (m_webLayer) {
+ m_webLayer->setOpaque(m_opaque);
+ GraphicsLayer::registerContentsLayer(m_webLayer);
+ }
+}
+
+void HTMLMediaElement::mediaPlayerSetOpaque(bool opaque)
{
- scheduleLayerUpdate();
+ m_opaque = opaque;
+ if (m_webLayer)
+ m_webLayer->setOpaque(m_opaque);
}
bool HTMLMediaElement::isInteractiveContent() const
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLMediaElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLMediaElement.h
index 705d4c5aa9b..18374c781bb 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLMediaElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLMediaElement.h
@@ -27,16 +27,20 @@
#define HTMLMediaElement_h
#include "core/dom/ActiveDOMObject.h"
-#include "core/dom/GenericEventQueue.h"
+#include "core/events/GenericEventQueue.h"
#include "core/html/HTMLElement.h"
#include "core/html/MediaControllerInterface.h"
#include "core/html/track/TextTrack.h"
#include "core/html/track/TextTrackCue.h"
-#include "core/platform/PODIntervalTree.h"
-#include "core/platform/graphics/MediaPlayer.h"
+#include "core/html/track/vtt/VTTCue.h"
+#include "platform/PODIntervalTree.h"
+#include "platform/graphics/media/MediaPlayer.h"
#include "public/platform/WebMimeRegistry.h"
-namespace WebKit { class WebLayer; }
+namespace blink {
+class WebInbandTextTrack;
+class WebLayer;
+}
namespace WebCore {
@@ -53,14 +57,10 @@ class KURL;
class MediaController;
class MediaControls;
class MediaError;
+class MediaKeys;
class HTMLMediaSource;
class TextTrackList;
class TimeRanges;
-#if ENABLE(ENCRYPTED_MEDIA_V2)
-class MediaKeys;
-#endif
-
-class InbandTextTrackPrivate;
typedef PODIntervalTree<double, TextTrackCue*> CueIntervalTree;
typedef CueIntervalTree::IntervalType CueInterval;
@@ -74,20 +74,20 @@ class HTMLMediaElement : public HTMLElement, public MediaPlayerClient, public Ac
, private TextTrackClient
{
public:
- static WebKit::WebMimeRegistry::SupportsType supportsType(const ContentType&, const String& keySystem = String());
+ static blink::WebMimeRegistry::SupportsType supportsType(const ContentType&, const String& keySystem = String());
MediaPlayer* player() const { return m_player.get(); }
virtual bool isVideo() const = 0;
- virtual bool hasVideo() const { return false; }
- virtual bool hasAudio() const;
+ virtual bool hasVideo() const OVERRIDE { return false; }
+ virtual bool hasAudio() const OVERRIDE;
// Eventually overloaded in HTMLVideoElement
- virtual bool supportsFullscreen() const { return false; };
+ virtual bool supportsFullscreen() const OVERRIDE { return false; };
- virtual bool supportsSave() const;
+ bool supportsSave() const;
- WebKit::WebLayer* platformLayer() const;
+ blink::WebLayer* platformLayer() const;
enum DelayedActionType {
LoadMediaResource = 1 << 0,
@@ -96,14 +96,13 @@ public:
};
void scheduleDelayedAction(DelayedActionType);
- bool inActiveDocument() const { return m_inActiveDocument; }
+ bool isActive() const { return m_active; }
-// DOM API
-// error state
+ // error state
PassRefPtr<MediaError> error() const;
-// network state
- void setSrc(const String&);
+ // network state
+ void setSrc(const AtomicString&);
const KURL& currentSrc() const { return m_currentSrc; }
enum NetworkState { NETWORK_EMPTY, NETWORK_IDLE, NETWORK_LOADING, NETWORK_NO_SOURCE };
@@ -116,15 +115,13 @@ public:
void load();
String canPlayType(const String& mimeType, const String& keySystem = String(), const KURL& = KURL()) const;
-// ready state
+ // ready state
ReadyState readyState() const;
bool seeking() const;
-// playback state
+ // playback state
double currentTime() const;
void setCurrentTime(double, ExceptionState&);
- double initialTime() const;
- double startTime() const;
double duration() const;
bool paused() const;
double defaultPlaybackRate() const;
@@ -132,32 +129,24 @@ public:
double playbackRate() const;
void setPlaybackRate(double);
void updatePlaybackRate();
- bool webkitPreservesPitch() const;
- void setWebkitPreservesPitch(bool);
PassRefPtr<TimeRanges> played();
PassRefPtr<TimeRanges> seekable() const;
bool ended() const;
bool autoplay() const;
- void setAutoplay(bool b);
bool loop() const;
void setLoop(bool b);
void play();
void pause();
-// captions
- bool webkitHasClosedCaptions() const;
- bool webkitClosedCaptionsVisible() const;
- void setWebkitClosedCaptionsVisible(bool);
-
-// Statistics
+ // statistics
unsigned webkitAudioDecodedByteCount() const;
unsigned webkitVideoDecodedByteCount() const;
-// Media Source.
+ // media source extensions
void closeMediaSource();
-
void durationChanged(double duration);
+ // encrypted media extensions
void webkitGenerateKeyRequest(const String& keySystem, PassRefPtr<Uint8Array> initData, ExceptionState&);
void webkitGenerateKeyRequest(const String& keySystem, ExceptionState&);
void webkitAddKey(const String& keySystem, PassRefPtr<Uint8Array> key, PassRefPtr<Uint8Array> initData, const String& sessionId, ExceptionState&);
@@ -169,12 +158,10 @@ public:
DEFINE_ATTRIBUTE_EVENT_LISTENER(webkitkeymessage);
DEFINE_ATTRIBUTE_EVENT_LISTENER(webkitneedkey);
-#if ENABLE(ENCRYPTED_MEDIA_V2)
MediaKeys* mediaKeys() const { return m_mediaKeys.get(); }
void setMediaKeys(MediaKeys*);
-#endif
-// controls
+ // controls
bool controls() const;
void setControls(bool);
double volume() const;
@@ -191,8 +178,8 @@ public:
double percentLoaded() const;
PassRefPtr<TextTrack> addTextTrack(const String& kind, const String& label, const String& language, ExceptionState&);
- PassRefPtr<TextTrack> addTextTrack(const String& kind, const String& label, ExceptionState& es) { return addTextTrack(kind, label, emptyString(), es); }
- PassRefPtr<TextTrack> addTextTrack(const String& kind, ExceptionState& es) { return addTextTrack(kind, emptyString(), emptyString(), es); }
+ PassRefPtr<TextTrack> addTextTrack(const String& kind, const String& label, ExceptionState& exceptionState) { return addTextTrack(kind, label, emptyString(), exceptionState); }
+ PassRefPtr<TextTrack> addTextTrack(const String& kind, ExceptionState& exceptionState) { return addTextTrack(kind, emptyString(), emptyString(), exceptionState); }
TextTrackList* textTracks();
CueList currentlyActiveCues() const { return m_currentlyActiveCues; }
@@ -203,11 +190,11 @@ public:
void closeCaptionTracksChanged();
void notifyMediaPlayerOfTextTrackChanges();
- virtual void didAddTrack(HTMLTrackElement*);
- virtual void didRemoveTrack(HTMLTrackElement*);
+ void didAddTrack(HTMLTrackElement*);
+ void didRemoveTrack(HTMLTrackElement*);
- virtual void mediaPlayerDidAddTrack(PassRefPtr<InbandTextTrackPrivate>) OVERRIDE;
- virtual void mediaPlayerDidRemoveTrack(PassRefPtr<InbandTextTrackPrivate>) OVERRIDE;
+ virtual void mediaPlayerDidAddTrack(blink::WebInbandTextTrack*) OVERRIDE;
+ virtual void mediaPlayerDidRemoveTrack(blink::WebInbandTextTrack*) OVERRIDE;
struct TrackGroup {
enum GroupKind { CaptionsAndSubtitles, Description, Chapter, Metadata, Other };
@@ -232,24 +219,28 @@ public:
void configureTextTrackGroup(const TrackGroup&);
bool textTracksAreReady() const;
- void configureTextTrackDisplay();
+ enum VisibilityChangeAssumption {
+ AssumeNoVisibleChange,
+ AssumeVisibleChange
+ };
+ void configureTextTrackDisplay(VisibilityChangeAssumption);
void updateTextTrackDisplay();
+ void textTrackReadyStateChanged(TextTrack*);
// TextTrackClient
- virtual void textTrackReadyStateChanged(TextTrack*);
- virtual void textTrackKindChanged(TextTrack*);
- virtual void textTrackModeChanged(TextTrack*);
- virtual void textTrackAddCues(TextTrack*, const TextTrackCueList*);
- virtual void textTrackRemoveCues(TextTrack*, const TextTrackCueList*);
- virtual void textTrackAddCue(TextTrack*, PassRefPtr<TextTrackCue>);
- virtual void textTrackRemoveCue(TextTrack*, PassRefPtr<TextTrackCue>);
+ virtual void textTrackKindChanged(TextTrack*) OVERRIDE;
+ virtual void textTrackModeChanged(TextTrack*) OVERRIDE;
+ virtual void textTrackAddCues(TextTrack*, const TextTrackCueList*) OVERRIDE;
+ virtual void textTrackRemoveCues(TextTrack*, const TextTrackCueList*) OVERRIDE;
+ virtual void textTrackAddCue(TextTrack*, PassRefPtr<TextTrackCue>) OVERRIDE;
+ virtual void textTrackRemoveCue(TextTrack*, PassRefPtr<TextTrackCue>) OVERRIDE;
// EventTarget function.
// Both Node (via HTMLElement) and ActiveDOMObject define this method, which
// causes an ambiguity error at compile time. This class's constructor
// ensures that both implementations return document, so return the result
// of one of them here.
- virtual ScriptExecutionContext* scriptExecutionContext() const OVERRIDE { return HTMLElement::scriptExecutionContext(); }
+ virtual ExecutionContext* executionContext() const OVERRIDE { return HTMLElement::executionContext(); }
bool hasSingleSecurityOrigin() const { return !m_player || m_player->hasSingleSecurityOrigin(); }
@@ -268,7 +259,9 @@ public:
bool isPlaying() const { return m_playing; }
- virtual bool hasPendingActivity() const;
+ // ActiveDOMObject functions.
+ virtual bool hasPendingActivity() const OVERRIDE;
+ virtual void contextDestroyed() OVERRIDE;
#if ENABLE(WEB_AUDIO)
MediaElementAudioSourceNode* audioSourceNode() { return m_audioSourceNode; }
@@ -280,30 +273,27 @@ public:
enum InvalidURLAction { DoNothing, Complain };
bool isSafeToLoadURL(const KURL&, InvalidURLAction);
- const String& mediaGroup() const;
- void setMediaGroup(const String&);
-
MediaController* controller() const;
- void setController(PassRefPtr<MediaController>);
-
- virtual bool dispatchEvent(PassRefPtr<Event>) OVERRIDE;
+ void setController(PassRefPtr<MediaController>); // Resets the MediaGroup and sets the MediaController.
protected:
HTMLMediaElement(const QualifiedName&, Document&, bool);
virtual ~HTMLMediaElement();
virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
- virtual void finishParsingChildren();
+ virtual void finishParsingChildren() OVERRIDE;
virtual bool isURLAttribute(const Attribute&) const OVERRIDE;
virtual void attach(const AttachContext& = AttachContext()) OVERRIDE;
- virtual void didMoveToNewDocument(Document* oldDocument) OVERRIDE;
+ virtual void didMoveToNewDocument(Document& oldDocument) OVERRIDE;
enum DisplayMode { Unknown, None, Poster, PosterWaitingForVideo, Video };
DisplayMode displayMode() const { return m_displayMode; }
virtual void setDisplayMode(DisplayMode mode) { m_displayMode = mode; }
- virtual bool isMediaElement() const { return true; }
+ virtual bool isMediaElement() const OVERRIDE { return true; }
+
+ void setControllerInternal(PassRefPtr<MediaController>);
// Restrictions to change default behaviors.
enum BehaviorRestrictionFlags {
@@ -334,24 +324,21 @@ private:
virtual bool areAuthorShadowsAllowed() const OVERRIDE { return false; }
virtual bool hasCustomFocusLogic() const OVERRIDE;
- virtual bool supportsFocus() const;
- virtual bool isMouseFocusable() const;
- virtual bool rendererIsNeeded(const RenderStyle&);
- virtual RenderObject* createRenderer(RenderStyle*);
+ virtual bool supportsFocus() const OVERRIDE;
+ virtual bool isMouseFocusable() const OVERRIDE;
+ virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE;
+ virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
virtual bool childShouldCreateRenderer(const Node& child) const OVERRIDE;
virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
virtual void removedFrom(ContainerNode*) OVERRIDE;
- virtual void didRecalcStyle(StyleRecalcChange);
+ virtual void didRecalcStyle(StyleRecalcChange) OVERRIDE;
- virtual void didBecomeFullscreenElement();
- virtual void willStopBeingFullscreenElement();
+ virtual void didBecomeFullscreenElement() OVERRIDE;
+ virtual void willStopBeingFullscreenElement() OVERRIDE;
virtual bool isInteractiveContent() const OVERRIDE;
// ActiveDOMObject functions.
- virtual bool canSuspend() const;
- virtual void suspend(ReasonForSuspension);
- virtual void resume();
- virtual void stop();
+ virtual void stop() OVERRIDE;
virtual void updateDisplayState() { }
@@ -363,23 +350,21 @@ private:
virtual void mediaPlayerTimeChanged() OVERRIDE;
virtual void mediaPlayerDurationChanged() OVERRIDE;
virtual void mediaPlayerPlaybackStateChanged() OVERRIDE;
+ virtual void mediaPlayerRequestFullscreen() OVERRIDE;
virtual void mediaPlayerRequestSeek(double) OVERRIDE;
virtual void mediaPlayerRepaint() OVERRIDE;
virtual void mediaPlayerSizeChanged() OVERRIDE;
- virtual void mediaPlayerEngineUpdated() OVERRIDE;
virtual void mediaPlayerKeyAdded(const String& keySystem, const String& sessionId) OVERRIDE;
virtual void mediaPlayerKeyError(const String& keySystem, const String& sessionId, MediaPlayerClient::MediaKeyErrorCode, unsigned short systemCode) OVERRIDE;
virtual void mediaPlayerKeyMessage(const String& keySystem, const String& sessionId, const unsigned char* message, unsigned messageLength, const KURL& defaultURL) OVERRIDE;
virtual bool mediaPlayerKeyNeeded(const String& keySystem, const String& sessionId, const unsigned char* initData, unsigned initDataLength) OVERRIDE;
-
-#if ENABLE(ENCRYPTED_MEDIA_V2)
virtual bool mediaPlayerKeyNeeded(Uint8Array*) OVERRIDE;
-#endif
virtual CORSMode mediaPlayerCORSMode() const OVERRIDE;
- virtual void mediaPlayerScheduleLayerUpdate() OVERRIDE;
+ virtual void mediaPlayerSetWebLayer(blink::WebLayer*) OVERRIDE;
+ virtual void mediaPlayerSetOpaque(bool) OVERRIDE;
void loadTimerFired(Timer<HTMLMediaElement>*);
void progressEventTimerFired(Timer<HTMLMediaElement>*);
@@ -403,6 +388,7 @@ private:
void loadNextSourceChild();
void userCancelledLoad();
void clearMediaPlayer(int flags);
+ void clearMediaPlayerAndAudioSourceProviderClient();
bool havePotentialSourceChild();
void noneSupported();
void mediaEngineError(PassRefPtr<MediaError> err);
@@ -435,9 +421,6 @@ private:
bool pausedForUserInteraction() const;
bool couldPlayIfEnoughData() const;
- double minTimeSeekable() const;
- double maxTimeSeekable() const;
-
// Pauses playback without changing any states or generating events
void setPausedInternal(bool);
@@ -454,12 +437,14 @@ private:
void prepareMediaFragmentURI();
void applyMediaFragmentURI();
- virtual void* preDispatchEventHandler(Event*);
+ virtual void* preDispatchEventHandler(Event*) OVERRIDE;
void changeNetworkStateFromLoadingToIdle();
void removeBehaviorsRestrictionsAfterFirstUserGesture();
+ const AtomicString& mediaGroup() const;
+ void setMediaGroup(const AtomicString&);
void updateMediaController();
bool isBlocked() const;
bool isBlockedOnMediaController() const;
@@ -474,7 +459,6 @@ private:
double m_playbackRate;
double m_defaultPlaybackRate;
- bool m_webkitPreservesPitch;
NetworkState m_networkState;
ReadyState m_readyState;
ReadyState m_readyStateMaximum;
@@ -504,6 +488,8 @@ private:
RefPtr<Node> m_nextChildNodeToConsider;
OwnPtr<MediaPlayer> m_player;
+ blink::WebLayer* m_webLayer;
+ bool m_opaque;
BehaviorRestrictions m_restrictions;
@@ -523,10 +509,11 @@ private:
typedef unsigned PendingActionFlags;
PendingActionFlags m_pendingActionFlags;
+ // FIXME: MediaElement has way too many state bits.
bool m_playing : 1;
bool m_shouldDelayLoadEvent : 1;
bool m_haveFiredLoadedData : 1;
- bool m_inActiveDocument : 1;
+ bool m_active : 1;
bool m_autoplaying : 1;
bool m_muted : 1;
bool m_paused : 1;
@@ -540,13 +527,8 @@ private:
bool m_pausedInternal : 1;
- // Not all media engines provide enough information about a file to be able to
- // support progress events so setting m_sendProgressEvents disables them
- bool m_sendProgressEvents : 1;
-
bool m_closedCaptionsVisible : 1;
- bool m_dispatchingCanPlayEvent : 1;
bool m_loadInitiatedByUserGesture : 1;
bool m_completelyLoaded : 1;
bool m_havePreparedToPlay : 1;
@@ -572,15 +554,12 @@ private:
MediaElementAudioSourceNode* m_audioSourceNode;
#endif
- String m_mediaGroup;
friend class MediaController;
RefPtr<MediaController> m_mediaController;
friend class TrackDisplayUpdateScope;
-#if ENABLE(ENCRYPTED_MEDIA_V2)
RefPtr<MediaKeys> m_mediaKeys;
-#endif
};
#ifndef NDEBUG
@@ -597,7 +576,7 @@ template <>
struct ValueToString<TextTrackCue*> {
static String string(TextTrackCue* const& cue)
{
- return String::format("%p id=%s interval=%f-->%f cue=%s)", cue, cue->id().utf8().data(), cue->startTime(), cue->endTime(), cue->text().utf8().data());
+ return cue->toString();
}
};
#endif
@@ -607,12 +586,13 @@ inline bool isHTMLMediaElement(Node* node)
return node && node->isElementNode() && toElement(node)->isMediaElement();
}
-inline HTMLMediaElement* toHTMLMediaElement(Node* node)
+inline bool isHTMLMediaElement(const Node& node)
{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || isHTMLMediaElement(node));
- return static_cast<HTMLMediaElement*>(node);
+ return node.isElementNode() && toElement(node).isMediaElement();
}
+DEFINE_NODE_TYPE_CASTS_WITH_FUNCTION(HTMLMediaElement);
+
} //namespace
#endif
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLMediaElement.idl b/chromium/third_party/WebKit/Source/core/html/HTMLMediaElement.idl
index 873aeeb8e9f..a4dbf6fdf6d 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLMediaElement.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLMediaElement.idl
@@ -24,84 +24,81 @@
*/
[
- EnabledAtRuntime=Media,
+ RuntimeEnabled=Media,
ActiveDOMObject
] interface HTMLMediaElement : HTMLElement {
-// error state
-readonly attribute MediaError error;
+ // error state
+ readonly attribute MediaError error;
-// network state
-[Reflect, URL] attribute DOMString src;
-[URL] readonly attribute DOMString currentSrc;
+ // network state
+ [Reflect, URL, PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute DOMString src;
+ [URL, PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] readonly attribute DOMString currentSrc;
+ [Reflect] attribute DOMString crossOrigin;
-const unsigned short NETWORK_EMPTY = 0;
-const unsigned short NETWORK_IDLE = 1;
-const unsigned short NETWORK_LOADING = 2;
-const unsigned short NETWORK_NO_SOURCE = 3;
-readonly attribute unsigned short networkState;
-attribute DOMString preload;
+ const unsigned short NETWORK_EMPTY = 0;
+ const unsigned short NETWORK_IDLE = 1;
+ const unsigned short NETWORK_LOADING = 2;
+ const unsigned short NETWORK_NO_SOURCE = 3;
+ readonly attribute unsigned short networkState;
+ attribute DOMString preload;
-readonly attribute TimeRanges buffered;
-void load();
+ readonly attribute TimeRanges buffered;
+ void load();
DOMString canPlayType([Default=Undefined] optional DOMString type, [Default=Undefined, TreatNullAs=NullString, TreatUndefinedAs=NullString] optional DOMString keySystem);
-// ready state
-const unsigned short HAVE_NOTHING = 0;
-const unsigned short HAVE_METADATA = 1;
-const unsigned short HAVE_CURRENT_DATA = 2;
-const unsigned short HAVE_FUTURE_DATA = 3;
-const unsigned short HAVE_ENOUGH_DATA = 4;
-readonly attribute unsigned short readyState;
-readonly attribute boolean seeking;
-
-// playback state
-[SetterRaisesException] attribute double currentTime;
-readonly attribute double initialTime;
-readonly attribute double startTime;
-readonly attribute double duration;
-readonly attribute boolean paused;
-attribute double defaultPlaybackRate;
-attribute double playbackRate;
-readonly attribute TimeRanges played;
-readonly attribute TimeRanges seekable;
-readonly attribute boolean ended;
-[Reflect] attribute boolean autoplay;
-[Reflect] attribute boolean loop;
-void play();
-void pause();
-
-// controls
-attribute boolean controls;
-[SetterRaisesException] attribute double volume;
-attribute boolean muted;
-[Reflect=muted] attribute boolean defaultMuted;
-
-// WebKit extensions
-attribute boolean webkitPreservesPitch;
-
-readonly attribute boolean webkitHasClosedCaptions;
-attribute boolean webkitClosedCaptionsVisible;
-
-// The number of bytes consumed by the media decoder.
-readonly attribute unsigned long webkitAudioDecodedByteCount;
-readonly attribute unsigned long webkitVideoDecodedByteCount;
-
-// FIXME: add DeprecateAs=PrefixedMediaGenerateKeyRequest when MediaKeys is ready.
-[EnabledAtRuntime=LegacyEncryptedMedia, RaisesException] void webkitGenerateKeyRequest([TreatNullAs=NullString, TreatUndefinedAs=NullString] DOMString keySystem, optional Uint8Array initData);
-[EnabledAtRuntime=LegacyEncryptedMedia, RaisesException] void webkitAddKey([TreatNullAs=NullString, TreatUndefinedAs=NullString] DOMString keySystem, Uint8Array key, optional Uint8Array initData, [Default=NullString] optional DOMString sessionId);
-[EnabledAtRuntime=LegacyEncryptedMedia, RaisesException] void webkitCancelKeyRequest([TreatNullAs=NullString, TreatUndefinedAs=NullString] DOMString keySystem, [Default=NullString] optional DOMString sessionId);
-
-[EnabledAtRuntime=LegacyEncryptedMedia] attribute EventHandler onwebkitkeyadded;
-[EnabledAtRuntime=LegacyEncryptedMedia] attribute EventHandler onwebkitkeyerror;
-[EnabledAtRuntime=LegacyEncryptedMedia] attribute EventHandler onwebkitkeymessage;
-[EnabledAtRuntime=LegacyEncryptedMedia] attribute EventHandler onwebkitneedkey;
-
-[EnabledAtRuntime=EncryptedMedia, Conditional=ENCRYPTED_MEDIA_V2] attribute MediaKeys mediaKeys;
-
-[EnabledAtRuntime=VideoTrack, RaisesException] TextTrack addTextTrack(DOMString kind, optional DOMString label, optional DOMString language);
-[EnabledAtRuntime=VideoTrack] readonly attribute TextTrackList textTracks;
-
-[Reflect, TreatNullAs=NullString] attribute DOMString mediaGroup;
-[CustomSetter] attribute MediaController controller;
+ // ready state
+ const unsigned short HAVE_NOTHING = 0;
+ const unsigned short HAVE_METADATA = 1;
+ const unsigned short HAVE_CURRENT_DATA = 2;
+ const unsigned short HAVE_FUTURE_DATA = 3;
+ const unsigned short HAVE_ENOUGH_DATA = 4;
+ readonly attribute unsigned short readyState;
+ readonly attribute boolean seeking;
+
+ // playback state
+ [RaisesException=Setter] attribute double currentTime;
+ readonly attribute double duration;
+ readonly attribute boolean paused;
+ attribute double defaultPlaybackRate;
+ attribute double playbackRate;
+ readonly attribute TimeRanges played;
+ readonly attribute TimeRanges seekable;
+ readonly attribute boolean ended;
+ [Reflect] attribute boolean autoplay;
+ [Reflect] attribute boolean loop;
+ void play();
+ void pause();
+
+ // media controller
+ [Reflect] attribute DOMString mediaGroup;
+ [StrictTypeChecking] attribute MediaController controller;
+
+ // controls
+ attribute boolean controls;
+ [RaisesException=Setter] attribute double volume;
+ attribute boolean muted;
+ [Reflect=muted] attribute boolean defaultMuted;
+
+ // tracks
+ [RuntimeEnabled=VideoTrack] readonly attribute TextTrackList textTracks;
+ [RuntimeEnabled=VideoTrack, RaisesException] TextTrack addTextTrack(DOMString kind, optional DOMString label, optional DOMString language);
+
+ // WebKit extensions
+
+ // The number of bytes consumed by the media decoder.
+ [MeasureAs=PrefixedAudioDecodedByteCount] readonly attribute unsigned long webkitAudioDecodedByteCount;
+ [MeasureAs=PrefixedVideoDecodedByteCount] readonly attribute unsigned long webkitVideoDecodedByteCount;
+
+ // FIXME: add DeprecateAs=PrefixedMediaGenerateKeyRequest when MediaKeys is ready.
+ [RuntimeEnabled=PrefixedEncryptedMedia, RaisesException] void webkitGenerateKeyRequest([TreatNullAs=NullString, TreatUndefinedAs=NullString] DOMString keySystem, optional Uint8Array initData);
+ [RuntimeEnabled=PrefixedEncryptedMedia, RaisesException] void webkitAddKey([TreatNullAs=NullString, TreatUndefinedAs=NullString] DOMString keySystem, Uint8Array key, optional Uint8Array initData, [Default=NullString] optional DOMString sessionId);
+ [RuntimeEnabled=PrefixedEncryptedMedia, RaisesException] void webkitCancelKeyRequest([TreatNullAs=NullString, TreatUndefinedAs=NullString] DOMString keySystem, [Default=NullString] optional DOMString sessionId);
+
+ [RuntimeEnabled=PrefixedEncryptedMedia] attribute EventHandler onwebkitkeyadded;
+ [RuntimeEnabled=PrefixedEncryptedMedia] attribute EventHandler onwebkitkeyerror;
+ [RuntimeEnabled=PrefixedEncryptedMedia] attribute EventHandler onwebkitkeymessage;
+ [RuntimeEnabled=PrefixedEncryptedMedia] attribute EventHandler onwebkitneedkey;
+
+ [RuntimeEnabled=EncryptedMedia] attribute MediaKeys mediaKeys;
};
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLMediaSource.h b/chromium/third_party/WebKit/Source/core/html/HTMLMediaSource.h
index ddf0aefb81b..f40206ce094 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLMediaSource.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLMediaSource.h
@@ -35,9 +35,12 @@
#include "core/html/URLRegistry.h"
#include "wtf/Forward.h"
+namespace blink {
+class WebMediaSource;
+}
+
namespace WebCore {
-class MediaSourcePrivate;
class TimeRanges;
class HTMLMediaSource : public URLRegistrable {
@@ -56,7 +59,7 @@ public:
// Once attached, the source uses the element to synchronously service some
// API operations like duration change that may need to initiate seek.
virtual bool attachToElement(HTMLMediaElement*) = 0;
- virtual void setPrivateAndOpen(PassOwnPtr<MediaSourcePrivate>) = 0;
+ virtual void setWebMediaSourceAndOpen(PassOwnPtr<blink::WebMediaSource>) = 0;
virtual void close() = 0;
virtual bool isClosed() const = 0;
virtual double duration() const = 0;
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLMenuElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLMenuElement.cpp
index dd110d43f4c..2783c047b6a 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLMenuElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLMenuElement.cpp
@@ -29,16 +29,15 @@ namespace WebCore {
using namespace HTMLNames;
-inline HTMLMenuElement::HTMLMenuElement(const QualifiedName& tagName, Document& document)
- : HTMLElement(tagName, document)
+inline HTMLMenuElement::HTMLMenuElement(Document& document)
+ : HTMLElement(menuTag, document)
{
- ASSERT(hasTagName(menuTag));
ScriptWrappable::init(this);
}
-PassRefPtr<HTMLMenuElement> HTMLMenuElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<HTMLMenuElement> HTMLMenuElement::create(Document& document)
{
- return adoptRef(new HTMLMenuElement(tagName, document));
+ return adoptRef(new HTMLMenuElement(document));
}
}
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLMenuElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLMenuElement.h
index af7070d06c0..b1fdab64b05 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLMenuElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLMenuElement.h
@@ -29,10 +29,10 @@ namespace WebCore {
class HTMLMenuElement FINAL : public HTMLElement {
public:
- static PassRefPtr<HTMLMenuElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<HTMLMenuElement> create(Document&);
private:
- HTMLMenuElement(const QualifiedName&, Document&);
+ explicit HTMLMenuElement(Document&);
};
} //namespace
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLMetaElement-in.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLMetaElement-in.cpp
new file mode 100644
index 00000000000..02060a45742
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLMetaElement-in.cpp
@@ -0,0 +1,489 @@
+/*
+ * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
+ * (C) 1999 Antti Koivisto (koivisto@kde.org)
+ * (C) 2001 Dirk Mueller (mueller@kde.org)
+ * Copyright (C) 2003, 2010 Apple Inc. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#include "config.h"
+#include "core/html/HTMLMetaElement.h"
+
+#include "HTMLNames.h"
+#include "core/dom/Document.h"
+#include "core/frame/Settings.h"
+
+namespace WebCore {
+
+#define DEFINE_ARRAY_FOR_MATCHING(name, source, maxMatchLength) \
+const UChar* name; \
+const unsigned uMaxMatchLength = maxMatchLength; \
+UChar characterBuffer[uMaxMatchLength]; \
+if (!source.is8Bit()) { \
+ name = source.characters16(); \
+} else { \
+ unsigned bufferLength = std::min(uMaxMatchLength, source.length()); \
+ const LChar* characters8 = source.characters8(); \
+ for (unsigned i = 0; i < bufferLength; ++i) \
+ characterBuffer[i] = characters8[i]; \
+ name = characterBuffer; \
+}
+
+using namespace HTMLNames;
+
+inline HTMLMetaElement::HTMLMetaElement(Document& document)
+ : HTMLElement(metaTag, document)
+{
+ ScriptWrappable::init(this);
+}
+
+PassRefPtr<HTMLMetaElement> HTMLMetaElement::create(Document& document)
+{
+ return adoptRef(new HTMLMetaElement(document));
+}
+
+static bool isInvalidSeparator(UChar c)
+{
+ return c == ';';
+}
+
+// Though isspace() considers \t and \v to be whitespace, Win IE doesn't.
+static bool isSeparator(UChar c)
+{
+ return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '=' || c == ',' || c == '\0';
+}
+
+void HTMLMetaElement::parseContentAttribute(const String& content, KeyValuePairCallback callback, void* data)
+{
+ bool error = false;
+
+ // Tread lightly in this code -- it was specifically designed to mimic Win IE's parsing behavior.
+ int keyBegin, keyEnd;
+ int valueBegin, valueEnd;
+
+ int i = 0;
+ int length = content.length();
+ String buffer = content.lower();
+ while (i < length) {
+ // skip to first non-separator, but don't skip past the end of the string
+ while (isSeparator(buffer[i])) {
+ if (i >= length)
+ break;
+ i++;
+ }
+ keyBegin = i;
+
+ // skip to first separator
+ while (!isSeparator(buffer[i])) {
+ error |= isInvalidSeparator(buffer[i]);
+ i++;
+ }
+ keyEnd = i;
+
+ // skip to first '=', but don't skip past a ',' or the end of the string
+ while (buffer[i] != '=') {
+ error |= isInvalidSeparator(buffer[i]);
+ if (buffer[i] == ',' || i >= length)
+ break;
+ i++;
+ }
+
+ // skip to first non-separator, but don't skip past a ',' or the end of the string
+ while (isSeparator(buffer[i])) {
+ if (buffer[i] == ',' || i >= length)
+ break;
+ i++;
+ }
+ valueBegin = i;
+
+ // skip to first separator
+ while (!isSeparator(buffer[i])) {
+ error |= isInvalidSeparator(buffer[i]);
+ i++;
+ }
+ valueEnd = i;
+
+ ASSERT_WITH_SECURITY_IMPLICATION(i <= length);
+
+ String keyString = buffer.substring(keyBegin, keyEnd - keyBegin);
+ String valueString = buffer.substring(valueBegin, valueEnd - valueBegin);
+ (this->*callback)(keyString, valueString, data);
+ }
+ if (error) {
+ String message = "Error parsing a meta element's content: ';' is not a valid key-value pair separator. Please use ',' instead.";
+ document().addConsoleMessage(RenderingMessageSource, WarningMessageLevel, message);
+ }
+}
+
+static inline float clampLengthValue(float value)
+{
+ // Limits as defined in the css-device-adapt spec.
+ if (value != ViewportDescription::ValueAuto)
+ return std::min(float(10000), std::max(value, float(1)));
+ return value;
+}
+
+static inline float clampScaleValue(float value)
+{
+ // Limits as defined in the css-device-adapt spec.
+ if (value != ViewportDescription::ValueAuto)
+ return std::min(float(10), std::max(value, float(0.1)));
+ return value;
+}
+
+float HTMLMetaElement::parsePositiveNumber(const String& keyString, const String& valueString, bool* ok)
+{
+ size_t parsedLength;
+ float value;
+ if (valueString.is8Bit())
+ value = charactersToFloat(valueString.characters8(), valueString.length(), parsedLength);
+ else
+ value = charactersToFloat(valueString.characters16(), valueString.length(), parsedLength);
+ if (!parsedLength) {
+ reportViewportWarning(UnrecognizedViewportArgumentValueError, valueString, keyString);
+ if (ok)
+ *ok = false;
+ return 0;
+ }
+ if (parsedLength < valueString.length())
+ reportViewportWarning(TruncatedViewportArgumentValueError, valueString, keyString);
+ if (ok)
+ *ok = true;
+ return value;
+}
+
+Length HTMLMetaElement::parseViewportValueAsLength(const String& keyString, const String& valueString)
+{
+ // 1) Non-negative number values are translated to px lengths.
+ // 2) Negative number values are translated to auto.
+ // 3) device-width and device-height are used as keywords.
+ // 4) Other keywords and unknown values translate to 0.0.
+
+ unsigned length = valueString.length();
+ DEFINE_ARRAY_FOR_MATCHING(characters, valueString, 13);
+ SWITCH(characters, length) {
+ CASE("device-width") {
+ return Length(100, ViewportPercentageWidth);
+ }
+ CASE("device-height") {
+ return Length(100, ViewportPercentageHeight);
+ }
+ }
+
+ float value = parsePositiveNumber(keyString, valueString);
+
+ if (value < 0)
+ return Length(); // auto
+
+ return Length(clampLengthValue(value), Fixed);
+}
+
+float HTMLMetaElement::parseViewportValueAsZoom(const String& keyString, const String& valueString)
+{
+ // 1) Non-negative number values are translated to <number> values.
+ // 2) Negative number values are translated to auto.
+ // 3) yes is translated to 1.0.
+ // 4) device-width and device-height are translated to 10.0.
+ // 5) no and unknown values are translated to 0.0
+
+ unsigned length = valueString.length();
+ DEFINE_ARRAY_FOR_MATCHING(characters, valueString, 13);
+ SWITCH(characters, length) {
+ CASE("yes") {
+ return 1;
+ }
+ CASE("no") {
+ return 0;
+ }
+ CASE("device-width") {
+ return 10;
+ }
+ CASE("device-height") {
+ return 10;
+ }
+ }
+
+ float value = parsePositiveNumber(keyString, valueString);
+
+ if (value < 0)
+ return ViewportDescription::ValueAuto;
+
+ if (value > 10.0)
+ reportViewportWarning(MaximumScaleTooLargeError, String(), String());
+
+ if (!value && document().settings() && document().settings()->viewportMetaZeroValuesQuirk())
+ return ViewportDescription::ValueAuto;
+
+ return clampScaleValue(value);
+}
+
+float HTMLMetaElement::parseViewportValueAsUserZoom(const String& keyString, const String& valueString)
+{
+ // yes and no are used as keywords.
+ // Numbers >= 1, numbers <= -1, device-width and device-height are mapped to yes.
+ // Numbers in the range <-1, 1>, and unknown values, are mapped to no.
+
+ unsigned length = valueString.length();
+ DEFINE_ARRAY_FOR_MATCHING(characters, valueString, 13);
+ SWITCH(characters, length) {
+ CASE("yes") {
+ return 1;
+ }
+ CASE("no") {
+ return 0;
+ }
+ CASE("device-width") {
+ return 1;
+ }
+ CASE("device-height") {
+ return 1;
+ }
+ }
+
+ float value = parsePositiveNumber(keyString, valueString);
+ if (fabs(value) < 1)
+ return 0;
+
+ return 1;
+}
+
+float HTMLMetaElement::parseViewportValueAsDPI(const String& keyString, const String& valueString)
+{
+ unsigned length = valueString.length();
+ DEFINE_ARRAY_FOR_MATCHING(characters, valueString, 10);
+ SWITCH(characters, length) {
+ CASE("device-dpi") {
+ return ViewportDescription::ValueDeviceDPI;
+ }
+ CASE("low-dpi") {
+ return ViewportDescription::ValueLowDPI;
+ }
+ CASE("medium-dpi") {
+ return ViewportDescription::ValueMediumDPI;
+ }
+ CASE("high-dpi") {
+ return ViewportDescription::ValueHighDPI;
+ }
+ }
+
+ bool ok;
+ float value = parsePositiveNumber(keyString, valueString, &ok);
+ if (!ok || value < 70 || value > 400)
+ return ViewportDescription::ValueAuto;
+
+ return value;
+}
+
+void HTMLMetaElement::processViewportKeyValuePair(const String& keyString, const String& valueString, void* data)
+{
+ ViewportDescription* description = static_cast<ViewportDescription*>(data);
+
+ unsigned length = keyString.length();
+
+ DEFINE_ARRAY_FOR_MATCHING(characters, keyString, 17);
+ SWITCH(characters, length) {
+ CASE("width") {
+ const Length& width = parseViewportValueAsLength(keyString, valueString);
+ if (width.isAuto())
+ return;
+ description->minWidth = Length(ExtendToZoom);
+ description->maxWidth = width;
+ return;
+ }
+ CASE("height") {
+ const Length& height = parseViewportValueAsLength(keyString, valueString);
+ if (height.isAuto())
+ return;
+ description->minHeight = Length(ExtendToZoom);
+ description->maxHeight = height;
+ return;
+ }
+ CASE("initial-scale") {
+ description->zoom = parseViewportValueAsZoom(keyString, valueString);
+ return;
+ }
+ CASE("minimum-scale") {
+ description->minZoom = parseViewportValueAsZoom(keyString, valueString);
+ return;
+ }
+ CASE("maximum-scale") {
+ description->maxZoom = parseViewportValueAsZoom(keyString, valueString);
+ return;
+ }
+ CASE("user-scalable") {
+ description->userZoom = parseViewportValueAsUserZoom(keyString, valueString);
+ return;
+ }
+ CASE("target-densitydpi") {
+ description->deprecatedTargetDensityDPI = parseViewportValueAsDPI(keyString, valueString);
+ reportViewportWarning(TargetDensityDpiUnsupported, String(), String());
+ return;
+ }
+ }
+ reportViewportWarning(UnrecognizedViewportArgumentKeyError, keyString, String());
+}
+
+static const char* viewportErrorMessageTemplate(ViewportErrorCode errorCode)
+{
+ static const char* const errors[] = {
+ "The key \"%replacement1\" is not recognized and ignored.",
+ "The value \"%replacement1\" for key \"%replacement2\" is invalid, and has been ignored.",
+ "The value \"%replacement1\" for key \"%replacement2\" was truncated to its numeric prefix.",
+ "The value for key \"maximum-scale\" is out of bounds and the value has been clamped.",
+ "The key \"target-densitydpi\" is not supported.",
+ };
+
+ return errors[errorCode];
+}
+
+static MessageLevel viewportErrorMessageLevel(ViewportErrorCode errorCode)
+{
+ switch (errorCode) {
+ case TruncatedViewportArgumentValueError:
+ case TargetDensityDpiUnsupported:
+ return WarningMessageLevel;
+ case UnrecognizedViewportArgumentKeyError:
+ case UnrecognizedViewportArgumentValueError:
+ case MaximumScaleTooLargeError:
+ return ErrorMessageLevel;
+ }
+
+ ASSERT_NOT_REACHED();
+ return ErrorMessageLevel;
+}
+
+void HTMLMetaElement::reportViewportWarning(ViewportErrorCode errorCode, const String& replacement1, const String& replacement2)
+{
+ if (!document().frame())
+ return;
+
+ String message = viewportErrorMessageTemplate(errorCode);
+ if (!replacement1.isNull())
+ message.replace("%replacement1", replacement1);
+ if (!replacement2.isNull())
+ message.replace("%replacement2", replacement2);
+
+ // FIXME: This message should be moved off the console once a solution to https://bugs.webkit.org/show_bug.cgi?id=103274 exists.
+ document().addConsoleMessage(RenderingMessageSource, viewportErrorMessageLevel(errorCode), message);
+}
+
+void HTMLMetaElement::processViewportContentAttribute(const String& content, ViewportDescription::Type origin)
+{
+ ASSERT(!content.isNull());
+
+ if (!document().settings())
+ return;
+
+ if (!document().shouldOverrideLegacyDescription(origin))
+ return;
+
+ ViewportDescription descriptionFromLegacyTag(origin);
+ if (document().shouldMergeWithLegacyDescription(origin))
+ descriptionFromLegacyTag = document().viewportDescription();
+
+ parseContentAttribute(content, &HTMLMetaElement::processViewportKeyValuePair, (void*)&descriptionFromLegacyTag);
+
+ if (descriptionFromLegacyTag.minZoom == ViewportDescription::ValueAuto)
+ descriptionFromLegacyTag.minZoom = 0.25;
+
+ if (descriptionFromLegacyTag.maxZoom == ViewportDescription::ValueAuto) {
+ descriptionFromLegacyTag.maxZoom = 5;
+ descriptionFromLegacyTag.minZoom = std::min(descriptionFromLegacyTag.minZoom, float(5));
+ }
+
+ const Settings* settings = document().settings();
+
+ if (descriptionFromLegacyTag.maxWidth.isAuto()) {
+ if (descriptionFromLegacyTag.zoom == ViewportDescription::ValueAuto) {
+ descriptionFromLegacyTag.minWidth = Length(ExtendToZoom);
+ descriptionFromLegacyTag.maxWidth = Length(settings->layoutFallbackWidth(), Fixed);
+ } else if (descriptionFromLegacyTag.maxHeight.isAuto()) {
+ descriptionFromLegacyTag.minWidth = Length(ExtendToZoom);
+ descriptionFromLegacyTag.maxWidth = Length(ExtendToZoom);
+ }
+ }
+
+ document().setViewportDescription(descriptionFromLegacyTag);
+}
+
+
+void HTMLMetaElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
+{
+ if (name == http_equivAttr || name == contentAttr) {
+ process();
+ return;
+ }
+
+ if (name != nameAttr)
+ HTMLElement::parseAttribute(name, value);
+}
+
+Node::InsertionNotificationRequest HTMLMetaElement::insertedInto(ContainerNode* insertionPoint)
+{
+ HTMLElement::insertedInto(insertionPoint);
+ if (insertionPoint->inDocument())
+ process();
+ return InsertionDone;
+}
+
+void HTMLMetaElement::process()
+{
+ if (!inDocument())
+ return;
+
+ // All below situations require a content attribute (which can be the empty string).
+ const AtomicString& contentValue = fastGetAttribute(contentAttr);
+ if (contentValue.isNull())
+ return;
+
+ const AtomicString& nameValue = fastGetAttribute(nameAttr);
+ if (nameValue.isNull()) {
+ // Get the document to process the tag, but only if we're actually part of DOM
+ // tree (changing a meta tag while it's not in the tree shouldn't have any effect
+ // on the document).
+ const AtomicString& httpEquivValue = fastGetAttribute(http_equivAttr);
+ if (!httpEquivValue.isNull())
+ document().processHttpEquiv(httpEquivValue, contentValue);
+ return;
+ }
+
+ if (equalIgnoringCase(nameValue, "viewport"))
+ processViewportContentAttribute(contentValue, ViewportDescription::ViewportMeta);
+ else if (equalIgnoringCase(nameValue, "referrer"))
+ document().processReferrerPolicy(contentValue);
+ else if (equalIgnoringCase(nameValue, "handheldfriendly") && equalIgnoringCase(contentValue, "true"))
+ processViewportContentAttribute("width=device-width", ViewportDescription::HandheldFriendlyMeta);
+ else if (equalIgnoringCase(nameValue, "mobileoptimized"))
+ processViewportContentAttribute("width=device-width, initial-scale=1", ViewportDescription::MobileOptimizedMeta);
+}
+
+const AtomicString& HTMLMetaElement::content() const
+{
+ return getAttribute(contentAttr);
+}
+
+const AtomicString& HTMLMetaElement::httpEquiv() const
+{
+ return getAttribute(http_equivAttr);
+}
+
+const AtomicString& HTMLMetaElement::name() const
+{
+ return getNameAttribute();
+}
+
+}
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLMetaElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLMetaElement.cpp
deleted file mode 100644
index 4218d13e9e8..00000000000
--- a/chromium/third_party/WebKit/Source/core/html/HTMLMetaElement.cpp
+++ /dev/null
@@ -1,110 +0,0 @@
-/*
- * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
- * (C) 1999 Antti Koivisto (koivisto@kde.org)
- * (C) 2001 Dirk Mueller (mueller@kde.org)
- * Copyright (C) 2003, 2010 Apple Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-#include "core/html/HTMLMetaElement.h"
-
-#include "HTMLNames.h"
-#include "core/dom/Document.h"
-
-namespace WebCore {
-
-using namespace HTMLNames;
-
-inline HTMLMetaElement::HTMLMetaElement(const QualifiedName& tagName, Document& document)
- : HTMLElement(tagName, document)
-{
- ASSERT(hasTagName(metaTag));
- ScriptWrappable::init(this);
-}
-
-PassRefPtr<HTMLMetaElement> HTMLMetaElement::create(Document& document)
-{
- return adoptRef(new HTMLMetaElement(metaTag, document));
-}
-
-PassRefPtr<HTMLMetaElement> HTMLMetaElement::create(const QualifiedName& tagName, Document& document)
-{
- return adoptRef(new HTMLMetaElement(tagName, document));
-}
-
-void HTMLMetaElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
-{
- if (name == http_equivAttr)
- process();
- else if (name == contentAttr)
- process();
- else if (name == nameAttr) {
- // Do nothing
- } else
- HTMLElement::parseAttribute(name, value);
-}
-
-Node::InsertionNotificationRequest HTMLMetaElement::insertedInto(ContainerNode* insertionPoint)
-{
- HTMLElement::insertedInto(insertionPoint);
- if (insertionPoint->inDocument())
- process();
- return InsertionDone;
-}
-
-void HTMLMetaElement::process()
-{
- if (!inDocument())
- return;
-
- const AtomicString& contentValue = fastGetAttribute(contentAttr);
- if (contentValue.isNull())
- return;
-
- if (equalIgnoringCase(name(), "viewport"))
- document().processViewport(contentValue, ViewportArguments::ViewportMeta);
- else if (equalIgnoringCase(name(), "referrer"))
- document().processReferrerPolicy(contentValue);
- else if (equalIgnoringCase(name(), "handheldfriendly") && equalIgnoringCase(contentValue, "true"))
- document().processViewport("width=device-width", ViewportArguments::HandheldFriendlyMeta);
- else if (equalIgnoringCase(name(), "mobileoptimized"))
- document().processViewport("width=device-width, initial-scale=1", ViewportArguments::MobileOptimizedMeta);
-
- // Get the document to process the tag, but only if we're actually part of DOM tree (changing a meta tag while
- // it's not in the tree shouldn't have any effect on the document)
- const AtomicString& httpEquivValue = fastGetAttribute(http_equivAttr);
- if (!httpEquivValue.isNull())
- document().processHttpEquiv(httpEquivValue, contentValue);
-}
-
-String HTMLMetaElement::content() const
-{
- return getAttribute(contentAttr);
-}
-
-String HTMLMetaElement::httpEquiv() const
-{
- return getAttribute(http_equivAttr);
-}
-
-String HTMLMetaElement::name() const
-{
- return getNameAttribute();
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLMetaElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLMetaElement.h
index 4d2db881fd6..c859a33c744 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLMetaElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLMetaElement.h
@@ -27,35 +27,46 @@
namespace WebCore {
+enum ViewportErrorCode {
+ UnrecognizedViewportArgumentKeyError,
+ UnrecognizedViewportArgumentValueError,
+ TruncatedViewportArgumentValueError,
+ MaximumScaleTooLargeError,
+ TargetDensityDpiUnsupported
+};
+
class HTMLMetaElement FINAL : public HTMLElement {
public:
static PassRefPtr<HTMLMetaElement> create(Document&);
- static PassRefPtr<HTMLMetaElement> create(const QualifiedName&, Document&);
- String content() const;
- String httpEquiv() const;
- String name() const;
+ const AtomicString& content() const;
+ const AtomicString& httpEquiv() const;
+ const AtomicString& name() const;
private:
- HTMLMetaElement(const QualifiedName&, Document&);
+ explicit HTMLMetaElement(Document&);
+
+ typedef void (HTMLMetaElement::*KeyValuePairCallback)(const String& key, const String& value, void* data);
+ void processViewportKeyValuePair(const String& key, const String& value, void* data);
+ void parseContentAttribute(const String& content, KeyValuePairCallback, void* data);
virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
+ float parsePositiveNumber(const String& key, const String& value, bool* ok = 0);
+
+ Length parseViewportValueAsLength(const String& key, const String& value);
+ float parseViewportValueAsZoom(const String& key, const String& value);
+ float parseViewportValueAsUserZoom(const String& key, const String& value);
+ float parseViewportValueAsDPI(const String& key, const String& value);
+
+ void reportViewportWarning(ViewportErrorCode, const String& replacement1, const String& replacement2);
+
void process();
+ void processViewportContentAttribute(const String& content, ViewportDescription::Type origin);
};
-inline HTMLMetaElement* toHTMLMetaElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::metaTag));
- return static_cast<HTMLMetaElement*>(node);
-}
-
-inline const HTMLMetaElement* toHTMLMetaElement(const Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::metaTag));
- return static_cast<const HTMLMetaElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(HTMLMetaElement, hasTagName(HTMLNames::metaTag));
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLMetaElement.idl b/chromium/third_party/WebKit/Source/core/html/HTMLMetaElement.idl
index 4f7e9cd00e1..41d369e22ca 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLMetaElement.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLMetaElement.idl
@@ -23,4 +23,3 @@ interface HTMLMetaElement : HTMLElement {
[Reflect] attribute DOMString name;
[Reflect] attribute DOMString scheme;
};
-
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLMeterElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLMeterElement.cpp
index 738aea3ee63..41e536d9944 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLMeterElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLMeterElement.cpp
@@ -23,13 +23,13 @@
#include "core/html/HTMLMeterElement.h"
#include "HTMLNames.h"
+#include "bindings/v8/ExceptionMessages.h"
#include "bindings/v8/ExceptionState.h"
#include "bindings/v8/ExceptionStatePlaceholder.h"
#include "core/dom/ExceptionCode.h"
#include "core/dom/shadow/ShadowRoot.h"
#include "core/html/parser/HTMLParserIdioms.h"
#include "core/html/shadow/MeterShadowElement.h"
-#include "core/page/Page.h"
#include "core/rendering/RenderMeter.h"
#include "core/rendering/RenderTheme.h"
@@ -37,10 +37,9 @@ namespace WebCore {
using namespace HTMLNames;
-HTMLMeterElement::HTMLMeterElement(const QualifiedName& tagName, Document& document)
- : LabelableElement(tagName, document)
+HTMLMeterElement::HTMLMeterElement(Document& document)
+ : LabelableElement(meterTag, document)
{
- ASSERT(hasTagName(meterTag));
ScriptWrappable::init(this);
}
@@ -48,9 +47,9 @@ HTMLMeterElement::~HTMLMeterElement()
{
}
-PassRefPtr<HTMLMeterElement> HTMLMeterElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<HTMLMeterElement> HTMLMeterElement::create(Document& document)
{
- RefPtr<HTMLMeterElement> meter = adoptRef(new HTMLMeterElement(tagName, document));
+ RefPtr<HTMLMeterElement> meter = adoptRef(new HTMLMeterElement(document));
meter->ensureUserAgentShadowRoot();
return meter;
}
@@ -73,90 +72,90 @@ void HTMLMeterElement::parseAttribute(const QualifiedName& name, const AtomicStr
double HTMLMeterElement::min() const
{
- return parseToDoubleForNumberType(getAttribute(minAttr), 0);
+ return getFloatingPointAttribute(minAttr, 0);
}
-void HTMLMeterElement::setMin(double min, ExceptionState& es)
+void HTMLMeterElement::setMin(double min, ExceptionState& exceptionState)
{
if (!std::isfinite(min)) {
- es.throwDOMException(NotSupportedError);
+ exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::notAFiniteNumber(min));
return;
}
- setAttribute(minAttr, String::number(min));
+ setFloatingPointAttribute(minAttr, min);
}
double HTMLMeterElement::max() const
{
- return std::max(parseToDoubleForNumberType(getAttribute(maxAttr), std::max(1.0, min())), min());
+ return std::max(getFloatingPointAttribute(maxAttr, std::max(1.0, min())), min());
}
-void HTMLMeterElement::setMax(double max, ExceptionState& es)
+void HTMLMeterElement::setMax(double max, ExceptionState& exceptionState)
{
if (!std::isfinite(max)) {
- es.throwDOMException(NotSupportedError);
+ exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::notAFiniteNumber(max));
return;
}
- setAttribute(maxAttr, String::number(max));
+ setFloatingPointAttribute(maxAttr, max);
}
double HTMLMeterElement::value() const
{
- double value = parseToDoubleForNumberType(getAttribute(valueAttr), 0);
+ double value = getFloatingPointAttribute(valueAttr, 0);
return std::min(std::max(value, min()), max());
}
-void HTMLMeterElement::setValue(double value, ExceptionState& es)
+void HTMLMeterElement::setValue(double value, ExceptionState& exceptionState)
{
if (!std::isfinite(value)) {
- es.throwDOMException(NotSupportedError);
+ exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::notAFiniteNumber(value));
return;
}
- setAttribute(valueAttr, String::number(value));
+ setFloatingPointAttribute(valueAttr, value);
}
double HTMLMeterElement::low() const
{
- double low = parseToDoubleForNumberType(getAttribute(lowAttr), min());
+ double low = getFloatingPointAttribute(lowAttr, min());
return std::min(std::max(low, min()), max());
}
-void HTMLMeterElement::setLow(double low, ExceptionState& es)
+void HTMLMeterElement::setLow(double low, ExceptionState& exceptionState)
{
if (!std::isfinite(low)) {
- es.throwDOMException(NotSupportedError);
+ exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::notAFiniteNumber(low));
return;
}
- setAttribute(lowAttr, String::number(low));
+ setFloatingPointAttribute(lowAttr, low);
}
double HTMLMeterElement::high() const
{
- double high = parseToDoubleForNumberType(getAttribute(highAttr), max());
+ double high = getFloatingPointAttribute(highAttr, max());
return std::min(std::max(high, low()), max());
}
-void HTMLMeterElement::setHigh(double high, ExceptionState& es)
+void HTMLMeterElement::setHigh(double high, ExceptionState& exceptionState)
{
if (!std::isfinite(high)) {
- es.throwDOMException(NotSupportedError);
+ exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::notAFiniteNumber(high));
return;
}
- setAttribute(highAttr, String::number(high));
+ setFloatingPointAttribute(highAttr, high);
}
double HTMLMeterElement::optimum() const
{
- double optimum = parseToDoubleForNumberType(getAttribute(optimumAttr), (max() + min()) / 2);
+ double optimum = getFloatingPointAttribute(optimumAttr, (max() + min()) / 2);
return std::min(std::max(optimum, min()), max());
}
-void HTMLMeterElement::setOptimum(double optimum, ExceptionState& es)
+void HTMLMeterElement::setOptimum(double optimum, ExceptionState& exceptionState)
{
if (!std::isfinite(optimum)) {
- es.throwDOMException(NotSupportedError);
+ exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::notAFiniteNumber(optimum));
return;
}
- setAttribute(optimumAttr, String::number(optimum));
+ setFloatingPointAttribute(optimumAttr, optimum);
}
HTMLMeterElement::GaugeRegion HTMLMeterElement::gaugeRegion() const
@@ -217,16 +216,15 @@ RenderMeter* HTMLMeterElement::renderMeter() const
return toRenderMeter(renderer());
RenderObject* renderObject = userAgentShadowRoot()->firstChild()->renderer();
- ASSERT(!renderObject || renderObject->isMeter());
return toRenderMeter(renderObject);
}
-void HTMLMeterElement::didAddUserAgentShadowRoot(ShadowRoot* root)
+void HTMLMeterElement::didAddUserAgentShadowRoot(ShadowRoot& root)
{
ASSERT(!m_value);
RefPtr<MeterInnerElement> inner = MeterInnerElement::create(document());
- root->appendChild(inner);
+ root.appendChild(inner);
RefPtr<MeterBarElement> bar = MeterBarElement::create(document());
m_value = MeterValueElement::create(document());
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLMeterElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLMeterElement.h
index 2e1d6b654b0..e815e602442 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLMeterElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLMeterElement.h
@@ -31,7 +31,7 @@ class RenderMeter;
class HTMLMeterElement FINAL : public LabelableElement {
public:
- static PassRefPtr<HTMLMeterElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<HTMLMeterElement> create(Document&);
enum GaugeRegion {
GaugeRegionOptimum,
@@ -63,7 +63,7 @@ public:
bool canContainRangeEndPoint() const { return false; }
private:
- HTMLMeterElement(const QualifiedName&, Document&);
+ explicit HTMLMeterElement(Document&);
virtual ~HTMLMeterElement();
virtual bool areAuthorShadowsAllowed() const OVERRIDE { return false; }
@@ -76,7 +76,7 @@ private:
virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
void didElementStateChange();
- virtual void didAddUserAgentShadowRoot(ShadowRoot*) OVERRIDE;
+ virtual void didAddUserAgentShadowRoot(ShadowRoot&) OVERRIDE;
RefPtr<MeterValueElement> m_value;
};
@@ -86,11 +86,7 @@ inline bool isHTMLMeterElement(Node* node)
return node->hasTagName(HTMLNames::meterTag);
}
-inline HTMLMeterElement* toHTMLMeterElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || isHTMLMeterElement(node));
- return static_cast<HTMLMeterElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(HTMLMeterElement, hasTagName(HTMLNames::meterTag));
} // namespace
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLMeterElement.idl b/chromium/third_party/WebKit/Source/core/html/HTMLMeterElement.idl
index 12f067af753..fde8591538e 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLMeterElement.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLMeterElement.idl
@@ -18,11 +18,11 @@
*/
interface HTMLMeterElement : HTMLElement {
- [SetterRaisesException] attribute double value;
- [SetterRaisesException] attribute double min;
- [SetterRaisesException] attribute double max;
- [SetterRaisesException] attribute double low;
- [SetterRaisesException] attribute double high;
- [SetterRaisesException] attribute double optimum;
+ [RaisesException=Setter] attribute double value;
+ [RaisesException=Setter] attribute double min;
+ [RaisesException=Setter] attribute double max;
+ [RaisesException=Setter] attribute double low;
+ [RaisesException=Setter] attribute double high;
+ [RaisesException=Setter] attribute double optimum;
readonly attribute NodeList labels;
};
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLModElement.idl b/chromium/third_party/WebKit/Source/core/html/HTMLModElement.idl
index ccb8da46647..c066b68c0ec 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLModElement.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLModElement.idl
@@ -18,7 +18,6 @@
*/
interface HTMLModElement : HTMLElement {
- [Reflect, URL] attribute DOMString cite;
+ [Reflect, URL, PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute DOMString cite;
[Reflect] attribute DOMString dateTime;
};
-
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLNameCollection.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLNameCollection.cpp
index 57a181d6505..9941f554c51 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLNameCollection.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLNameCollection.cpp
@@ -27,6 +27,7 @@
#include "core/dom/Element.h"
#include "core/dom/ElementTraversal.h"
#include "core/dom/NodeRareData.h"
+#include "core/html/HTMLEmbedElement.h"
#include "core/html/HTMLObjectElement.h"
namespace WebCore {
@@ -55,11 +56,11 @@ Element* HTMLNameCollection::virtualItemAfter(unsigned& offsetInArray, Element*
Element* current;
if (!previous)
- current = ElementTraversal::firstWithin(ownerNode());
+ current = ElementTraversal::firstWithin(*ownerNode());
else
- current = ElementTraversal::next(previous, ownerNode());
+ current = ElementTraversal::next(*previous, ownerNode());
- for (; current; current = ElementTraversal::next(current, ownerNode())) {
+ for (; current; current = ElementTraversal::next(*current, ownerNode())) {
switch (type()) {
case WindowNamedItems:
// find only images, forms, applets, embeds and objects by name,
@@ -79,16 +80,15 @@ Element* HTMLNameCollection::virtualItemAfter(unsigned& offsetInArray, Element*
// find images, forms, applets, embeds, objects and iframes by name,
// applets and object by id, and images by id but only if they have
// a name attribute (this very strange rule matches IE)
- if (current->hasTagName(formTag) || current->hasTagName(embedTag) || current->hasTagName(iframeTag)) {
+ if (current->hasTagName(formTag)
+ || current->hasTagName(iframeTag)
+ || (current->hasTagName(embedTag) && toHTMLEmbedElement(current)->isExposed())) {
if (current->getNameAttribute() == m_name)
return current;
- } else if (current->hasTagName(appletTag)) {
+ } else if (current->hasTagName(appletTag)
+ || (current->hasTagName(objectTag) && toHTMLObjectElement(current)->isExposed())) {
if (current->getNameAttribute() == m_name || current->getIdAttribute() == m_name)
return current;
- } else if (current->hasTagName(objectTag)) {
- if ((current->getNameAttribute() == m_name || current->getIdAttribute() == m_name)
- && toHTMLObjectElement(current)->isDocNamedItem())
- return current;
} else if (current->hasTagName(imgTag)) {
if (current->getNameAttribute() == m_name || (current->getIdAttribute() == m_name && current->hasName()))
return current;
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLNameCollection.h b/chromium/third_party/WebKit/Source/core/html/HTMLNameCollection.h
index a13039df8c4..435d4395860 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLNameCollection.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLNameCollection.h
@@ -31,7 +31,7 @@ namespace WebCore {
class Document;
-class HTMLNameCollection : public HTMLCollection {
+class HTMLNameCollection FINAL : public HTMLCollection {
public:
static PassRefPtr<HTMLNameCollection> create(Node* document, CollectionType type, const AtomicString& name)
{
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLOListElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLOListElement.cpp
index 8ad5bbbdc05..03675516a07 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLOListElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLOListElement.cpp
@@ -32,26 +32,20 @@ namespace WebCore {
using namespace HTMLNames;
-HTMLOListElement::HTMLOListElement(const QualifiedName& tagName, Document& document)
- : HTMLElement(tagName, document)
+HTMLOListElement::HTMLOListElement(Document& document)
+ : HTMLElement(olTag, document)
, m_start(0xBADBEEF)
, m_itemCount(0)
, m_hasExplicitStart(false)
, m_isReversed(false)
, m_shouldRecalculateItemCount(false)
{
- ASSERT(hasTagName(olTag));
ScriptWrappable::init(this);
}
PassRefPtr<HTMLOListElement> HTMLOListElement::create(Document& document)
{
- return adoptRef(new HTMLOListElement(olTag, document));
-}
-
-PassRefPtr<HTMLOListElement> HTMLOListElement::create(const QualifiedName& tagName, Document& document)
-{
- return adoptRef(new HTMLOListElement(tagName, document));
+ return adoptRef(new HTMLOListElement(document));
}
bool HTMLOListElement::isPresentationAttribute(const QualifiedName& name) const
@@ -101,7 +95,7 @@ void HTMLOListElement::parseAttribute(const QualifiedName& name, const AtomicStr
void HTMLOListElement::setStart(int start)
{
- setAttribute(startAttr, String::number(start));
+ setIntegralAttribute(startAttr, start);
}
void HTMLOListElement::updateItemValues()
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLOListElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLOListElement.h
index 130a7940a10..0da2e2c713d 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLOListElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLOListElement.h
@@ -30,7 +30,6 @@ namespace WebCore {
class HTMLOListElement FINAL : public HTMLElement {
public:
static PassRefPtr<HTMLOListElement> create(Document&);
- static PassRefPtr<HTMLOListElement> create(const QualifiedName&, Document&);
int start() const { return m_hasExplicitStart ? m_start : (m_isReversed ? itemCount() : 1); }
void setStart(int);
@@ -40,7 +39,7 @@ public:
void itemCountChanged() { m_shouldRecalculateItemCount = true; }
private:
- HTMLOListElement(const QualifiedName&, Document&);
+ explicit HTMLOListElement(Document&);
void updateItemValues();
@@ -65,11 +64,7 @@ private:
bool m_shouldRecalculateItemCount : 1;
};
-inline HTMLOListElement* toHTMLOListElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::olTag));
- return static_cast<HTMLOListElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(HTMLOListElement, hasTagName(HTMLNames::olTag));
} //namespace
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLOListElement.idl b/chromium/third_party/WebKit/Source/core/html/HTMLOListElement.idl
index 1e516155677..01cbabdaff2 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLOListElement.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLOListElement.idl
@@ -23,4 +23,3 @@ interface HTMLOListElement : HTMLElement {
[Reflect] attribute boolean reversed;
[Reflect] attribute DOMString type;
};
-
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLObjectElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLObjectElement.cpp
index c9a3e465e38..87a5c3eae98 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLObjectElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLObjectElement.cpp
@@ -28,9 +28,10 @@
#include "bindings/v8/ScriptEventListener.h"
#include "core/dom/Attribute.h"
#include "core/dom/ElementTraversal.h"
-#include "core/dom/EventNames.h"
#include "core/dom/NodeList.h"
#include "core/dom/Text.h"
+#include "core/dom/shadow/ShadowRoot.h"
+#include "core/events/ThreadLocalEventNames.h"
#include "core/fetch/ImageResource.h"
#include "core/html/FormDataList.h"
#include "core/html/HTMLDocument.h"
@@ -38,23 +39,20 @@
#include "core/html/HTMLMetaElement.h"
#include "core/html/HTMLParamElement.h"
#include "core/html/parser/HTMLParserIdioms.h"
-#include "core/page/Page.h"
-#include "core/page/Settings.h"
-#include "core/platform/MIMETypeRegistry.h"
-#include "core/platform/Widget.h"
+#include "core/frame/Settings.h"
#include "core/plugins/PluginView.h"
#include "core/rendering/RenderEmbeddedObject.h"
+#include "platform/MIMETypeRegistry.h"
+#include "platform/Widget.h"
namespace WebCore {
using namespace HTMLNames;
-inline HTMLObjectElement::HTMLObjectElement(const QualifiedName& tagName, Document& document, HTMLFormElement* form, bool createdByParser)
- : HTMLPlugInImageElement(tagName, document, createdByParser, ShouldNotPreferPlugInsForImages)
- , m_docNamedItem(true)
+inline HTMLObjectElement::HTMLObjectElement(Document& document, HTMLFormElement* form, bool createdByParser)
+ : HTMLPlugInElement(objectTag, document, createdByParser, ShouldNotPreferPlugInsForImages)
, m_useFallbackContent(false)
{
- ASSERT(hasTagName(objectTag));
setForm(form ? form : findFormAncestor());
ScriptWrappable::init(this);
}
@@ -64,9 +62,11 @@ inline HTMLObjectElement::~HTMLObjectElement()
setForm(0);
}
-PassRefPtr<HTMLObjectElement> HTMLObjectElement::create(const QualifiedName& tagName, Document& document, HTMLFormElement* form, bool createdByParser)
+PassRefPtr<HTMLObjectElement> HTMLObjectElement::create(Document& document, HTMLFormElement* form, bool createdByParser)
{
- return adoptRef(new HTMLObjectElement(tagName, document, form, createdByParser));
+ RefPtr<HTMLObjectElement> element = adoptRef(new HTMLObjectElement(document, form, createdByParser));
+ element->ensureUserAgentShadowRoot();
+ return element.release();
}
RenderWidget* HTMLObjectElement::existingRenderWidget() const
@@ -78,7 +78,7 @@ bool HTMLObjectElement::isPresentationAttribute(const QualifiedName& name) const
{
if (name == borderAttr)
return true;
- return HTMLPlugInImageElement::isPresentationAttribute(name);
+ return HTMLPlugInElement::isPresentationAttribute(name);
}
void HTMLObjectElement::collectStyleForPresentationAttribute(const QualifiedName& name, const AtomicString& value, MutableStylePropertySet* style)
@@ -86,7 +86,7 @@ void HTMLObjectElement::collectStyleForPresentationAttribute(const QualifiedName
if (name == borderAttr)
applyBorderAttributeToStyle(value, style);
else
- HTMLPlugInImageElement::collectStyleForPresentationAttribute(name, value, style);
+ HTMLPlugInElement::collectStyleForPresentationAttribute(name, value, style);
}
void HTMLObjectElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
@@ -114,10 +114,11 @@ void HTMLObjectElement::parseAttribute(const QualifiedName& name, const AtomicSt
m_classId = value;
if (renderer())
setNeedsWidgetUpdate(true);
- } else if (name == onbeforeloadAttr)
- setAttributeEventListener(eventNames().beforeloadEvent, createAttributeEventListener(this, name, value));
- else
- HTMLPlugInImageElement::parseAttribute(name, value);
+ } else if (name == onbeforeloadAttr) {
+ setAttributeEventListener(EventTypeNames::beforeload, createAttributeEventListener(this, name, value));
+ } else {
+ HTMLPlugInElement::parseAttribute(name, value);
+ }
}
static void mapDataParamToSrc(Vector<String>* paramNames, Vector<String>* paramValues)
@@ -230,8 +231,8 @@ bool HTMLObjectElement::shouldAllowQuickTimeClassIdQuirk()
// 'generator' meta tag is present. Only apply this quirk if there is no
// fallback content, which ensures the quirk will disable itself if Wiki
// Server is updated to generate an alternate embed tag as fallback content.
- if (!document().page()
- || !document().page()->settings().needsSiteSpecificQuirks()
+ if (!document().settings()
+ || !document().settings()->needsSiteSpecificQuirks()
|| hasFallbackContent()
|| !equalIgnoringCase(classId(), "clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B"))
return false;
@@ -250,7 +251,7 @@ bool HTMLObjectElement::shouldAllowQuickTimeClassIdQuirk()
bool HTMLObjectElement::hasValidClassId()
{
- if (MIMETypeRegistry::isJavaAppletMIMEType(serviceType()) && classId().startsWith("java:", false))
+ if (MIMETypeRegistry::isJavaAppletMIMEType(m_serviceType) && classId().startsWith("java:", false))
return true;
if (shouldAllowQuickTimeClassIdQuirk())
@@ -262,8 +263,8 @@ bool HTMLObjectElement::hasValidClassId()
}
// FIXME: This should be unified with HTMLEmbedElement::updateWidget and
-// moved down into HTMLPluginImageElement.cpp
-void HTMLObjectElement::updateWidget(PluginCreationOption pluginCreationOption)
+// moved down into HTMLPluginElement.cpp
+void HTMLObjectElement::updateWidgetInternal()
{
ASSERT(!renderEmbeddedObject()->showsUnavailablePluginIndicator());
ASSERT(needsWidgetUpdate());
@@ -275,11 +276,11 @@ void HTMLObjectElement::updateWidget(PluginCreationOption pluginCreationOption)
// FIXME: I'm not sure it's ever possible to get into updateWidget during a
// removal, but just in case we should avoid loading the frame to prevent
// security bugs.
- if (!SubframeLoadingDisabler::canLoadFrame(this))
+ if (!SubframeLoadingDisabler::canLoadFrame(*this))
return;
String url = this->url();
- String serviceType = this->serviceType();
+ String serviceType = m_serviceType;
// FIXME: These should be joined into a PluginParameters class.
Vector<String> paramNames;
@@ -293,15 +294,6 @@ void HTMLObjectElement::updateWidget(PluginCreationOption pluginCreationOption)
bool fallbackContent = hasFallbackContent();
renderEmbeddedObject()->setHasFallbackContent(fallbackContent);
- // FIXME: It's sadness that we have this special case here.
- // See http://trac.webkit.org/changeset/25128 and
- // plugins/netscape-plugin-setwindow-size.html
- if (pluginCreationOption == CreateOnlyNonNetscapePlugins && wouldLoadAsNetscapePlugin(url, serviceType)) {
- // Ensure updateWidget() is called again during layout to create the Netscape plug-in.
- setNeedsWidgetUpdate(true);
- return;
- }
-
RefPtr<HTMLObjectElement> protect(this); // beforeload and plugin loading can make arbitrary DOM mutations.
bool beforeLoadAllowedLoad = dispatchBeforeLoadEvent(url);
if (!renderer()) // Do not load the plugin if beforeload removed this element or its renderer.
@@ -315,39 +307,38 @@ void HTMLObjectElement::updateWidget(PluginCreationOption pluginCreationOption)
bool HTMLObjectElement::rendererIsNeeded(const RenderStyle& style)
{
// FIXME: This check should not be needed, detached documents never render!
- Frame* frame = document().frame();
- if (!frame)
+ if (!document().frame())
return false;
-
- return HTMLPlugInImageElement::rendererIsNeeded(style);
+ return HTMLPlugInElement::rendererIsNeeded(style);
}
Node::InsertionNotificationRequest HTMLObjectElement::insertedInto(ContainerNode* insertionPoint)
{
- HTMLPlugInImageElement::insertedInto(insertionPoint);
+ HTMLPlugInElement::insertedInto(insertionPoint);
FormAssociatedElement::insertedInto(insertionPoint);
return InsertionDone;
}
void HTMLObjectElement::removedFrom(ContainerNode* insertionPoint)
{
- HTMLPlugInImageElement::removedFrom(insertionPoint);
+ HTMLPlugInElement::removedFrom(insertionPoint);
FormAssociatedElement::removedFrom(insertionPoint);
}
void HTMLObjectElement::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
{
- updateDocNamedItem();
if (inDocument() && !useFallbackContent()) {
setNeedsWidgetUpdate(true);
setNeedsStyleRecalc();
}
- HTMLPlugInImageElement::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
+ HTMLPlugInElement::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
}
bool HTMLObjectElement::isURLAttribute(const Attribute& attribute) const
{
- return attribute.name() == dataAttr || (attribute.name() == usemapAttr && attribute.value().string()[0] != '#') || HTMLPlugInImageElement::isURLAttribute(attribute);
+ return attribute.name() == codebaseAttr || attribute.name() == dataAttr
+ || (attribute.name() == usemapAttr && attribute.value().string()[0] != '#')
+ || HTMLPlugInElement::isURLAttribute(attribute);
}
const AtomicString HTMLObjectElement::imageSourceURL() const
@@ -363,7 +354,7 @@ void HTMLObjectElement::reattachFallbackContent()
if (document().inStyleRecalc())
reattach();
else
- lazyReattach();
+ lazyReattachIfAttached();
}
void HTMLObjectElement::renderFallbackContent()
@@ -391,63 +382,18 @@ void HTMLObjectElement::renderFallbackContent()
reattachFallbackContent();
}
-// FIXME: This should be removed, all callers are almost certainly wrong.
-static bool isRecognizedTagName(const QualifiedName& tagName)
+bool HTMLObjectElement::isExposed() const
{
- DEFINE_STATIC_LOCAL(HashSet<StringImpl*>, tagList, ());
- if (tagList.isEmpty()) {
- QualifiedName** tags = HTMLNames::getHTMLTags();
- for (size_t i = 0; i < HTMLNames::HTMLTagsCount; i++) {
- if (*tags[i] == bgsoundTag
- || *tags[i] == commandTag
- || *tags[i] == detailsTag
- || *tags[i] == figcaptionTag
- || *tags[i] == figureTag
- || *tags[i] == summaryTag
- || *tags[i] == trackTag) {
- // Even though we have atoms for these tags, we don't want to
- // treat them as "recognized tags" for the purpose of parsing
- // because that changes how we parse documents.
- continue;
- }
- tagList.add(tags[i]->localName().impl());
- }
+ // http://www.whatwg.org/specs/web-apps/current-work/#exposed
+ for (Node* ancestor = parentNode(); ancestor; ancestor = ancestor->parentNode()) {
+ if (ancestor->hasTagName(objectTag) && toHTMLObjectElement(ancestor)->isExposed())
+ return false;
}
- return tagList.contains(tagName.localName().impl());
-}
-
-void HTMLObjectElement::updateDocNamedItem()
-{
- // The rule is "<object> elements with no children other than
- // <param> elements, unknown elements and whitespace can be
- // found by name in a document, and other <object> elements cannot."
- bool wasNamedItem = m_docNamedItem;
- bool isNamedItem = true;
- Node* child = firstChild();
- while (child && isNamedItem) {
- if (child->isElementNode()) {
- Element* element = toElement(child);
- // FIXME: Use of isRecognizedTagName is almost certainly wrong here.
- if (isRecognizedTagName(element->tagQName()) && !element->hasTagName(paramTag))
- isNamedItem = false;
- } else if (child->isTextNode()) {
- if (!toText(child)->containsOnlyWhitespace())
- isNamedItem = false;
- } else
- isNamedItem = false;
- child = child->nextSibling();
- }
- if (isNamedItem != wasNamedItem && document().isHTMLDocument()) {
- HTMLDocument& document = toHTMLDocument(this->document());
- if (isNamedItem) {
- document.addNamedItem(getNameAttribute());
- document.addExtraNamedItem(getIdAttribute());
- } else {
- document.removeNamedItem(getNameAttribute());
- document.removeExtraNamedItem(getIdAttribute());
- }
+ for (Node* node = firstChild(); node; node = NodeTraversal::next(*node, this)) {
+ if (node->hasTagName(objectTag) || node->hasTagName(embedTag))
+ return false;
}
- m_docNamedItem = isNamedItem;
+ return true;
}
bool HTMLObjectElement::containsJavaApplet() const
@@ -455,7 +401,7 @@ bool HTMLObjectElement::containsJavaApplet() const
if (MIMETypeRegistry::isJavaAppletMIMEType(getAttribute(typeAttr)))
return true;
- for (Element* child = ElementTraversal::firstWithin(this); child; child = ElementTraversal::nextSkippingChildren(child, this)) {
+ for (Element* child = ElementTraversal::firstWithin(*this); child; child = ElementTraversal::nextSkippingChildren(*child, this)) {
if (child->hasTagName(paramTag)
&& equalIgnoringCase(child->getNameAttribute(), "type")
&& MIMETypeRegistry::isJavaAppletMIMEType(child->getAttribute(valueAttr).string()))
@@ -471,7 +417,7 @@ bool HTMLObjectElement::containsJavaApplet() const
void HTMLObjectElement::addSubresourceAttributeURLs(ListHashSet<KURL>& urls) const
{
- HTMLPlugInImageElement::addSubresourceAttributeURLs(urls);
+ HTMLPlugInElement::addSubresourceAttributeURLs(urls);
addSubresourceURL(urls, document().completeURL(getAttribute(dataAttr)));
@@ -482,10 +428,10 @@ void HTMLObjectElement::addSubresourceAttributeURLs(ListHashSet<KURL>& urls) con
addSubresourceURL(urls, document().completeURL(useMap));
}
-void HTMLObjectElement::didMoveToNewDocument(Document* oldDocument)
+void HTMLObjectElement::didMoveToNewDocument(Document& oldDocument)
{
FormAssociatedElement::didMoveToNewDocument(oldDocument);
- HTMLPlugInImageElement::didMoveToNewDocument(oldDocument);
+ HTMLPlugInElement::didMoveToNewDocument(oldDocument);
}
bool HTMLObjectElement::appendFormData(FormDataList& encoding, bool)
@@ -503,7 +449,7 @@ bool HTMLObjectElement::appendFormData(FormDataList& encoding, bool)
return true;
}
-HTMLFormElement* HTMLObjectElement::virtualForm() const
+HTMLFormElement* HTMLObjectElement::formOwner() const
{
return FormAssociatedElement::form();
}
@@ -513,4 +459,9 @@ bool HTMLObjectElement::isInteractiveContent() const
return fastHasAttribute(usemapAttr);
}
+bool HTMLObjectElement::useFallbackContent() const
+{
+ return HTMLPlugInElement::useFallbackContent() || m_useFallbackContent;
+}
+
}
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLObjectElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLObjectElement.h
index 57f232e5f08..fc2c20860b5 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLObjectElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLObjectElement.h
@@ -24,29 +24,26 @@
#define HTMLObjectElement_h
#include "core/html/FormAssociatedElement.h"
-#include "core/html/HTMLPlugInImageElement.h"
+#include "core/html/HTMLPlugInElement.h"
namespace WebCore {
class HTMLFormElement;
-class HTMLObjectElement FINAL : public HTMLPlugInImageElement, public FormAssociatedElement {
+class HTMLObjectElement FINAL : public HTMLPlugInElement, public FormAssociatedElement {
public:
- static PassRefPtr<HTMLObjectElement> create(const QualifiedName&, Document&, HTMLFormElement*, bool createdByParser);
+ static PassRefPtr<HTMLObjectElement> create(Document&, HTMLFormElement*, bool createdByParser);
virtual ~HTMLObjectElement();
- bool isDocNamedItem() const { return m_docNamedItem; }
-
const String& classId() const { return m_classId; }
+ virtual HTMLFormElement* formOwner() const OVERRIDE;
+
bool containsJavaApplet() const;
- virtual bool useFallbackContent() const { return m_useFallbackContent; }
+ virtual bool useFallbackContent() const OVERRIDE;
virtual void renderFallbackContent() OVERRIDE;
- // Implementations of FormAssociatedElement
- HTMLFormElement* form() const { return FormAssociatedElement::form(); }
-
virtual bool isFormControlElement() const { return false; }
virtual bool isEnumeratable() const { return true; }
@@ -66,8 +63,10 @@ public:
virtual bool canContainRangeEndPoint() const { return useFallbackContent(); }
+ bool isExposed() const;
+
private:
- HTMLObjectElement(const QualifiedName&, Document&, HTMLFormElement*, bool createdByParser);
+ HTMLObjectElement(Document&, HTMLFormElement*, bool createdByParser);
virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
@@ -77,7 +76,7 @@ private:
virtual void removedFrom(ContainerNode*) OVERRIDE;
virtual bool rendererIsNeeded(const RenderStyle&);
- virtual void didMoveToNewDocument(Document* oldDocument) OVERRIDE;
+ virtual void didMoveToNewDocument(Document& oldDocument) OVERRIDE;
virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0);
@@ -88,7 +87,7 @@ private:
virtual void addSubresourceAttributeURLs(ListHashSet<KURL>&) const;
- virtual void updateWidget(PluginCreationOption);
+ virtual void updateWidgetInternal() OVERRIDE;
void updateDocNamedItem();
void reattachFallbackContent();
@@ -104,21 +103,15 @@ private:
virtual void refFormAssociatedElement() { ref(); }
virtual void derefFormAssociatedElement() { deref(); }
- virtual HTMLFormElement* virtualForm() const;
- virtual bool shouldRegisterAsNamedItem() const OVERRIDE { return isDocNamedItem(); }
- virtual bool shouldRegisterAsExtraNamedItem() const OVERRIDE { return isDocNamedItem(); }
+ virtual bool shouldRegisterAsNamedItem() const OVERRIDE { return true; }
+ virtual bool shouldRegisterAsExtraNamedItem() const OVERRIDE { return true; }
String m_classId;
- bool m_docNamedItem : 1;
bool m_useFallbackContent : 1;
};
-inline HTMLObjectElement* toHTMLObjectElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::objectTag));
- return static_cast<HTMLObjectElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(HTMLObjectElement, hasTagName(HTMLNames::objectTag));
inline const HTMLObjectElement* toHTMLObjectElement(const FormAssociatedElement* element)
{
@@ -130,6 +123,16 @@ inline const HTMLObjectElement* toHTMLObjectElement(const FormAssociatedElement*
return objectElement;
}
+inline const HTMLObjectElement& toHTMLObjectElement(const FormAssociatedElement& element)
+{
+ ASSERT_WITH_SECURITY_IMPLICATION(!element.isFormControlElement());
+ const HTMLObjectElement& objectElement = static_cast<const HTMLObjectElement&>(element);
+ // We need to assert after the cast because FormAssociatedElement doesn't
+ // have hasTagName.
+ ASSERT_WITH_SECURITY_IMPLICATION(objectElement.hasTagName(HTMLNames::objectTag));
+ return objectElement;
+}
+
}
#endif
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLObjectElement.idl b/chromium/third_party/WebKit/Source/core/html/HTMLObjectElement.idl
index 8c33b249954..2393f057dd9 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLObjectElement.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLObjectElement.idl
@@ -19,16 +19,16 @@
*/
[
- CustomLegacyCall
+ Custom=LegacyCallAsFunction,
] interface HTMLObjectElement : HTMLElement {
- readonly attribute HTMLFormElement form;
+ [ImplementedAs=formOwner] readonly attribute HTMLFormElement form;
[Reflect] attribute DOMString code;
[Reflect] attribute DOMString align;
[Reflect] attribute DOMString archive;
- [Reflect] attribute DOMString border;
- [Reflect] attribute DOMString codeBase;
+ [Reflect, TreatNullAs=NullString] attribute DOMString border;
+ [Reflect, URL] attribute DOMString codeBase;
[Reflect] attribute DOMString codeType;
- [Reflect, URL] attribute DOMString data;
+ [Reflect, URL, PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute DOMString data;
[Reflect] attribute boolean declare;
[Reflect] attribute DOMString height;
[Reflect] attribute long hspace;
@@ -45,12 +45,11 @@
void setCustomValidity([TreatNullAs=NullString, TreatUndefinedAs=NullString] DOMString error);
// Introduced in DOM Level 2:
- [CheckSecurityForNode] readonly attribute Document contentDocument;
+ [CheckSecurity=Node] readonly attribute Document contentDocument;
[Custom, NotEnumerable] getter boolean (unsigned long index);
[Custom] setter boolean (unsigned long index, Node value);
[Custom, NotEnumerable] getter Node (DOMString name);
[Custom] setter Node (DOMString name, Node value);
- [CheckSecurityForNode, RaisesException] SVGDocument getSVGDocument();
+ [CheckSecurity=Node, RaisesException] SVGDocument getSVGDocument();
};
-
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLOptGroupElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLOptGroupElement.cpp
index e7823e2a313..c9963b0ece4 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLOptGroupElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLOptGroupElement.cpp
@@ -35,17 +35,16 @@ namespace WebCore {
using namespace HTMLNames;
-inline HTMLOptGroupElement::HTMLOptGroupElement(const QualifiedName& tagName, Document& document)
- : HTMLElement(tagName, document)
+inline HTMLOptGroupElement::HTMLOptGroupElement(Document& document)
+ : HTMLElement(optgroupTag, document)
{
- ASSERT(hasTagName(optgroupTag));
setHasCustomStyleCallbacks();
ScriptWrappable::init(this);
}
-PassRefPtr<HTMLOptGroupElement> HTMLOptGroupElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<HTMLOptGroupElement> HTMLOptGroupElement::create(Document& document)
{
- return adoptRef(new HTMLOptGroupElement(tagName, document));
+ return adoptRef(new HTMLOptGroupElement(document));
}
bool HTMLOptGroupElement::isDisabledFormControl() const
@@ -125,7 +124,7 @@ PassRefPtr<RenderStyle> HTMLOptGroupElement::customStyleForRenderer()
String HTMLOptGroupElement::groupLabelText() const
{
- String itemText = document().displayStringModifiedByEncoding(getAttribute(labelAttr));
+ String itemText = getAttribute(labelAttr);
// In WinIE, leading and trailing whitespace is ignored in options and optgroups. We match this behavior.
itemText = itemText.stripWhiteSpace();
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLOptGroupElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLOptGroupElement.h
index b7592189df5..54ed7b5647d 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLOptGroupElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLOptGroupElement.h
@@ -32,7 +32,7 @@ class HTMLSelectElement;
class HTMLOptGroupElement FINAL : public HTMLElement {
public:
- static PassRefPtr<HTMLOptGroupElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<HTMLOptGroupElement> create(Document&);
virtual bool isDisabledFormControl() const OVERRIDE;
HTMLSelectElement* ownerSelectElement() const;
@@ -40,7 +40,7 @@ public:
String groupLabelText() const;
private:
- HTMLOptGroupElement(const QualifiedName&, Document&);
+ explicit HTMLOptGroupElement(Document&);
virtual const AtomicString& formControlType() const;
virtual bool rendererIsFocusable() const OVERRIDE;
@@ -73,12 +73,13 @@ inline bool isHTMLOptGroupElement(const Element* element)
return element->hasTagName(HTMLNames::optgroupTag);
}
-inline HTMLOptGroupElement* toHTMLOptGroupElement(Node* node)
+inline bool isHTMLOptGroupElement(const Element& element)
{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || isHTMLOptGroupElement(node));
- return static_cast<HTMLOptGroupElement*>(node);
+ return element.hasTagName(HTMLNames::optgroupTag);
}
+DEFINE_NODE_TYPE_CASTS(HTMLOptGroupElement, hasTagName(HTMLNames::optgroupTag));
+
} //namespace
#endif
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLOptGroupElement.idl b/chromium/third_party/WebKit/Source/core/html/HTMLOptGroupElement.idl
index 26a782fd5c7..c06ee82a4ae 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLOptGroupElement.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLOptGroupElement.idl
@@ -21,4 +21,3 @@ interface HTMLOptGroupElement : HTMLElement {
[Reflect] attribute boolean disabled;
[Reflect] attribute DOMString label;
};
-
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLOptionElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLOptionElement.cpp
index dbe4d00c148..0240fb2871e 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLOptionElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLOptionElement.cpp
@@ -46,35 +46,29 @@ namespace WebCore {
using namespace HTMLNames;
-HTMLOptionElement::HTMLOptionElement(const QualifiedName& tagName, Document& document)
- : HTMLElement(tagName, document)
+HTMLOptionElement::HTMLOptionElement(Document& document)
+ : HTMLElement(optionTag, document)
, m_disabled(false)
, m_isSelected(false)
{
- ASSERT(hasTagName(optionTag));
setHasCustomStyleCallbacks();
ScriptWrappable::init(this);
}
PassRefPtr<HTMLOptionElement> HTMLOptionElement::create(Document& document)
{
- return adoptRef(new HTMLOptionElement(optionTag, document));
+ return adoptRef(new HTMLOptionElement(document));
}
-PassRefPtr<HTMLOptionElement> HTMLOptionElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<HTMLOptionElement> HTMLOptionElement::createForJSConstructor(Document& document, const String& data, const AtomicString& value,
+ bool defaultSelected, bool selected, ExceptionState& exceptionState)
{
- return adoptRef(new HTMLOptionElement(tagName, document));
-}
-
-PassRefPtr<HTMLOptionElement> HTMLOptionElement::createForJSConstructor(Document& document, const String& data, const String& value,
- bool defaultSelected, bool selected, ExceptionState& es)
-{
- RefPtr<HTMLOptionElement> element = adoptRef(new HTMLOptionElement(optionTag, document));
+ RefPtr<HTMLOptionElement> element = adoptRef(new HTMLOptionElement(document));
RefPtr<Text> text = Text::create(document, data.isNull() ? "" : data);
- element->appendChild(text.release(), es);
- if (es.hadException())
+ element->appendChild(text.release(), exceptionState);
+ if (exceptionState.hadException())
return 0;
if (!value.isNull())
@@ -123,12 +117,10 @@ String HTMLOptionElement::text() const
if (text.isEmpty())
text = collectOptionInnerText();
- // FIXME: Is displayStringModifiedByEncoding helpful here?
- // If it's correct here, then isn't it needed in the value and label functions too?
- return document.displayStringModifiedByEncoding(text).stripWhiteSpace(isHTMLSpace<UChar>).simplifyWhiteSpace(isHTMLSpace<UChar>);
+ return text.stripWhiteSpace(isHTMLSpace<UChar>).simplifyWhiteSpace(isHTMLSpace<UChar>);
}
-void HTMLOptionElement::setText(const String &text, ExceptionState& es)
+void HTMLOptionElement::setText(const String &text, ExceptionState& exceptionState)
{
RefPtr<Node> protectFromMutationEvents(this);
@@ -145,7 +137,7 @@ void HTMLOptionElement::setText(const String &text, ExceptionState& es)
toText(child)->setData(text);
else {
removeChildren();
- appendChild(Text::create(document(), text), es);
+ appendChild(Text::create(document(), text), exceptionState);
}
if (selectIsMenuList && select->selectedIndex() != oldSelectedIndex)
@@ -210,7 +202,7 @@ String HTMLOptionElement::value() const
return collectOptionInnerText().stripWhiteSpace(isHTMLSpace<UChar>).simplifyWhiteSpace(isHTMLSpace<UChar>);
}
-void HTMLOptionElement::setValue(const String& value)
+void HTMLOptionElement::setValue(const AtomicString& value)
{
setAttribute(valueAttr, value);
}
@@ -293,7 +285,7 @@ String HTMLOptionElement::label() const
return collectOptionInnerText().stripWhiteSpace(isHTMLSpace<UChar>).simplifyWhiteSpace(isHTMLSpace<UChar>);
}
-void HTMLOptionElement::setLabel(const String& label)
+void HTMLOptionElement::setLabel(const AtomicString& label)
{
setAttribute(labelAttr, label);
}
@@ -367,11 +359,20 @@ String HTMLOptionElement::collectOptionInnerText() const
text.append(node->nodeValue());
// Text nodes inside script elements are not part of the option text.
if (node->isElementNode() && toScriptLoaderIfPossible(toElement(node)))
- node = NodeTraversal::nextSkippingChildren(node, this);
+ node = NodeTraversal::nextSkippingChildren(*node, this);
else
- node = NodeTraversal::next(node, this);
+ node = NodeTraversal::next(*node, this);
}
return text.toString();
}
+HTMLFormElement* HTMLOptionElement::form() const
+{
+ HTMLSelectElement* selectElement = ownerSelectElement();
+ if (!selectElement)
+ return 0;
+
+ return selectElement->formOwner();
+}
+
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLOptionElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLOptionElement.h
index c2e55a3f37b..1f79a1bd81a 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLOptionElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLOptionElement.h
@@ -36,8 +36,7 @@ class HTMLSelectElement;
class HTMLOptionElement FINAL : public HTMLElement {
public:
static PassRefPtr<HTMLOptionElement> create(Document&);
- static PassRefPtr<HTMLOptionElement> create(const QualifiedName&, Document&);
- static PassRefPtr<HTMLOptionElement> createForJSConstructor(Document&, const String& data, const String& value,
+ static PassRefPtr<HTMLOptionElement> createForJSConstructor(Document&, const String& data, const AtomicString& value,
bool defaultSelected, bool selected, ExceptionState&);
virtual String text() const;
@@ -46,7 +45,7 @@ public:
int index() const;
String value() const;
- void setValue(const String&);
+ void setValue(const AtomicString&);
bool selected();
void setSelected(bool);
@@ -55,7 +54,7 @@ public:
HTMLSelectElement* ownerSelectElement() const;
String label() const;
- void setLabel(const String&);
+ void setLabel(const AtomicString&);
bool ownElementDisabled() const { return m_disabled; }
@@ -65,8 +64,10 @@ public:
void setSelectedState(bool);
+ HTMLFormElement* form() const;
+
private:
- HTMLOptionElement(const QualifiedName&, Document&);
+ explicit HTMLOptionElement(Document&);
virtual bool rendererIsFocusable() const OVERRIDE;
virtual bool rendererIsNeeded(const RenderStyle&) { return false; }
@@ -94,19 +95,7 @@ private:
RefPtr<RenderStyle> m_style;
};
-void toHTMLOptionElement(const HTMLOptionElement*); // This overload will catch anyone doing an unnecessary cast.
-
-inline HTMLOptionElement* toHTMLOptionElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::optionTag));
- return static_cast<HTMLOptionElement*>(node);
-}
-
-inline const HTMLOptionElement* toHTMLOptionElement(const Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::optionTag));
- return static_cast<const HTMLOptionElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(HTMLOptionElement, hasTagName(HTMLNames::optionTag));
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLOptionElement.idl b/chromium/third_party/WebKit/Source/core/html/HTMLOptionElement.idl
index d315551886c..41c6592f239 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLOptionElement.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLOptionElement.idl
@@ -20,7 +20,7 @@
[
NamedConstructor=Option([Default=NullString] optional DOMString data, [Default=NullString] optional DOMString value, [Default=Undefined] optional boolean defaultSelected, [Default=Undefined] optional boolean selected),
- ConstructorRaisesException
+ RaisesException=Constructor
] interface HTMLOptionElement : HTMLElement {
[Reflect] attribute boolean disabled;
readonly attribute HTMLFormElement form;
@@ -29,6 +29,6 @@
attribute boolean selected;
attribute DOMString value;
- [SetterRaisesException] attribute DOMString text;
+ [RaisesException=Setter] attribute DOMString text;
readonly attribute long index;
};
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLOptionsCollection.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLOptionsCollection.cpp
index ea2c28c4463..aae87b078b9 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLOptionsCollection.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLOptionsCollection.cpp
@@ -21,6 +21,7 @@
#include "config.h"
#include "core/html/HTMLOptionsCollection.h"
+#include "bindings/v8/ExceptionMessages.h"
#include "bindings/v8/ExceptionState.h"
#include "core/dom/ExceptionCode.h"
#include "core/dom/NamedNodesCollection.h"
@@ -41,33 +42,33 @@ PassRefPtr<HTMLOptionsCollection> HTMLOptionsCollection::create(Node* select, Co
return adoptRef(new HTMLOptionsCollection(select));
}
-void HTMLOptionsCollection::add(PassRefPtr<HTMLOptionElement> element, ExceptionState& es)
+void HTMLOptionsCollection::add(PassRefPtr<HTMLOptionElement> element, ExceptionState& exceptionState)
{
- add(element, length(), es);
+ add(element, length(), exceptionState);
}
-void HTMLOptionsCollection::add(PassRefPtr<HTMLOptionElement> element, int index, ExceptionState& es)
+void HTMLOptionsCollection::add(PassRefPtr<HTMLOptionElement> element, int index, ExceptionState& exceptionState)
{
HTMLOptionElement* newOption = element.get();
if (!newOption) {
- es.throwDOMException(TypeMismatchError);
+ exceptionState.throwTypeError("The element provided was not an HTMLOptionElement.");
return;
}
if (index < -1) {
- es.throwDOMException(IndexSizeError);
+ exceptionState.throwDOMException(IndexSizeError, "The index provided (" + String::number(index) + ") is less than -1.");
return;
}
HTMLSelectElement* select = toHTMLSelectElement(ownerNode());
if (index == -1 || unsigned(index) >= length())
- select->add(newOption, 0, es);
+ select->add(newOption, 0, exceptionState);
else
- select->add(newOption, toHTMLOptionElement(item(index)), es);
+ select->add(newOption, toHTMLOptionElement(item(index)), exceptionState);
- ASSERT(!es.hadException());
+ ASSERT(!exceptionState.hadException());
}
void HTMLOptionsCollection::remove(int index)
@@ -90,9 +91,9 @@ void HTMLOptionsCollection::setSelectedIndex(int index)
toHTMLSelectElement(ownerNode())->setSelectedIndex(index);
}
-void HTMLOptionsCollection::setLength(unsigned length, ExceptionState& es)
+void HTMLOptionsCollection::setLength(unsigned length, ExceptionState& exceptionState)
{
- toHTMLSelectElement(ownerNode())->setLength(length, es);
+ toHTMLSelectElement(ownerNode())->setLength(length, exceptionState);
}
void HTMLOptionsCollection::anonymousNamedGetter(const AtomicString& name, bool& returnValue0Enabled, RefPtr<NodeList>& returnValue0, bool& returnValue1Enabled, RefPtr<Node>& returnValue1)
@@ -113,21 +114,21 @@ void HTMLOptionsCollection::anonymousNamedGetter(const AtomicString& name, bool&
returnValue0 = NamedNodesCollection::create(namedItems);
}
-bool HTMLOptionsCollection::anonymousIndexedSetterRemove(unsigned index, ExceptionState& es)
+bool HTMLOptionsCollection::anonymousIndexedSetterRemove(unsigned index, ExceptionState& exceptionState)
{
HTMLSelectElement* base = toHTMLSelectElement(ownerNode());
base->remove(index);
return true;
}
-bool HTMLOptionsCollection::anonymousIndexedSetter(unsigned index, PassRefPtr<HTMLOptionElement> value, ExceptionState& es)
+bool HTMLOptionsCollection::anonymousIndexedSetter(unsigned index, PassRefPtr<HTMLOptionElement> value, ExceptionState& exceptionState)
{
HTMLSelectElement* base = toHTMLSelectElement(ownerNode());
if (!value) {
- es.throwDOMException(TypeMismatchError);
+ exceptionState.throwTypeError(ExceptionMessages::failedToSet(String::number(index), "HTMLOptionsCollection", "The element provided was not an HTMLOptionElement."));
return true;
}
- base->setOption(index, value.get(), es);
+ base->setOption(index, value.get(), exceptionState);
return true;
}
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLOptionsCollection.h b/chromium/third_party/WebKit/Source/core/html/HTMLOptionsCollection.h
index 52aa8574ec1..fe5ad5d746e 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLOptionsCollection.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLOptionsCollection.h
@@ -32,7 +32,7 @@ class ExceptionState;
class HTMLOptionElement;
class HTMLSelectElement;
-class HTMLOptionsCollection : public HTMLCollection {
+class HTMLOptionsCollection FINAL : public HTMLCollection {
public:
static PassRefPtr<HTMLOptionsCollection> create(Node*, CollectionType);
@@ -50,7 +50,7 @@ public:
bool anonymousIndexedSetterRemove(unsigned, ExceptionState&);
private:
- HTMLOptionsCollection(Node*);
+ explicit HTMLOptionsCollection(Node*);
};
} //namespace
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLOptionsCollection.idl b/chromium/third_party/WebKit/Source/core/html/HTMLOptionsCollection.idl
index aa47617cb3f..32c414795d1 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLOptionsCollection.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLOptionsCollection.idl
@@ -20,11 +20,11 @@
*/
[
- GenerateIsReachable=ownerNode,
- DependentLifetime
+ DependentLifetime,
+ GenerateVisitDOMWrapper=ownerNode,
] interface HTMLOptionsCollection : HTMLCollection {
attribute long selectedIndex;
- [CustomSetter, SetterRaisesException] attribute unsigned long length;
+ [Custom=Setter, RaisesException=Setter] attribute unsigned long length;
[ImplementedAs=item] getter Node(unsigned long index);
[ImplementedAs=anonymousIndexedSetter, RaisesException] setter HTMLOptionElement (unsigned long index, [TreatNullAs=anonymousIndexedSetterRemove, TreatUndefinedAs=anonymousIndexedSetterRemove] HTMLOptionElement value);
[ImplementedAs=anonymousNamedGetter, NotEnumerable] getter (NodeList or Node)(DOMString name);
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLOutputElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLOutputElement.cpp
index 4990e99bee4..00d04356f9c 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLOutputElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLOutputElement.cpp
@@ -36,8 +36,8 @@
namespace WebCore {
-inline HTMLOutputElement::HTMLOutputElement(const QualifiedName& tagName, Document& document, HTMLFormElement* form)
- : HTMLFormControlElement(tagName, document, form)
+inline HTMLOutputElement::HTMLOutputElement(Document& document, HTMLFormElement* form)
+ : HTMLFormControlElement(HTMLNames::outputTag, document, form)
, m_isDefaultValueMode(true)
, m_isSetTextContentInProgress(false)
, m_defaultValue("")
@@ -46,9 +46,9 @@ inline HTMLOutputElement::HTMLOutputElement(const QualifiedName& tagName, Docume
ScriptWrappable::init(this);
}
-PassRefPtr<HTMLOutputElement> HTMLOutputElement::create(const QualifiedName& tagName, Document& document, HTMLFormElement* form)
+PassRefPtr<HTMLOutputElement> HTMLOutputElement::create(Document& document, HTMLFormElement* form)
{
- return adoptRef(new HTMLOutputElement(tagName, document, form));
+ return adoptRef(new HTMLOutputElement(document, form));
}
const AtomicString& HTMLOutputElement::formControlType() const
@@ -93,7 +93,7 @@ void HTMLOutputElement::childrenChanged(bool createdByParser, Node* beforeChange
m_defaultValue = textContent();
}
-void HTMLOutputElement::reset()
+void HTMLOutputElement::resetImpl()
{
// The reset algorithm for output elements is to set the element's
// value mode flag to "default" and then to set the element's textContent
@@ -138,7 +138,7 @@ void HTMLOutputElement::setTextContentInternal(const String& value)
{
ASSERT(!m_isSetTextContentInProgress);
m_isSetTextContentInProgress = true;
- setTextContent(value, IGNORE_EXCEPTION);
+ setTextContent(value);
}
} // namespace
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLOutputElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLOutputElement.h
index 9f198f42780..bf1e469e715 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLOutputElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLOutputElement.h
@@ -38,7 +38,7 @@ namespace WebCore {
class HTMLOutputElement FINAL : public HTMLFormControlElement {
public:
- static PassRefPtr<HTMLOutputElement> create(const QualifiedName&, Document&, HTMLFormElement*);
+ static PassRefPtr<HTMLOutputElement> create(Document&, HTMLFormElement*);
virtual bool willValidate() const { return false; }
@@ -52,7 +52,7 @@ public:
virtual bool canContainRangeEndPoint() const { return false; }
private:
- HTMLOutputElement(const QualifiedName&, Document&, HTMLFormElement*);
+ HTMLOutputElement(Document&, HTMLFormElement*);
virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
virtual const AtomicString& formControlType() const;
@@ -60,7 +60,7 @@ private:
virtual bool supportLabels() const OVERRIDE { return true; }
virtual bool supportsFocus() const;
virtual void childrenChanged(bool createdByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0);
- virtual void reset();
+ virtual void resetImpl() OVERRIDE;
void setTextContentInternal(const String&);
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLOutputElement.idl b/chromium/third_party/WebKit/Source/core/html/HTMLOutputElement.idl
index 7edaca2a9c5..ec24c461ee7 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLOutputElement.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLOutputElement.idl
@@ -23,13 +23,13 @@
*/
interface HTMLOutputElement : HTMLElement {
- readonly attribute DOMSettableTokenList htmlFor;
- readonly attribute HTMLFormElement form;
+ [PutForwards=value] readonly attribute DOMSettableTokenList htmlFor;
+ [ImplementedAs=formOwner] readonly attribute HTMLFormElement form;
[Reflect] attribute DOMString name;
readonly attribute DOMString type;
- [TreatNullAs=NullString] attribute DOMString defaultValue;
- [TreatNullAs=NullString] attribute DOMString value;
+ attribute DOMString defaultValue;
+ attribute DOMString value;
readonly attribute boolean willValidate;
readonly attribute ValidityState validity;
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLParagraphElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLParagraphElement.cpp
index 626e8d56f8c..459800856f9 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLParagraphElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLParagraphElement.cpp
@@ -31,21 +31,15 @@ namespace WebCore {
using namespace HTMLNames;
-inline HTMLParagraphElement::HTMLParagraphElement(const QualifiedName& tagName, Document& document)
- : HTMLElement(tagName, document)
+inline HTMLParagraphElement::HTMLParagraphElement(Document& document)
+ : HTMLElement(pTag, document)
{
- ASSERT(hasTagName(pTag));
ScriptWrappable::init(this);
}
PassRefPtr<HTMLParagraphElement> HTMLParagraphElement::create(Document& document)
{
- return adoptRef(new HTMLParagraphElement(pTag, document));
-}
-
-PassRefPtr<HTMLParagraphElement> HTMLParagraphElement::create(const QualifiedName& tagName, Document& document)
-{
- return adoptRef(new HTMLParagraphElement(tagName, document));
+ return adoptRef(new HTMLParagraphElement(document));
}
bool HTMLParagraphElement::isPresentationAttribute(const QualifiedName& name) const
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLParagraphElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLParagraphElement.h
index 9e80fda87f9..4bfbbf64425 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLParagraphElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLParagraphElement.h
@@ -30,10 +30,9 @@ namespace WebCore {
class HTMLParagraphElement FINAL : public HTMLElement {
public:
static PassRefPtr<HTMLParagraphElement> create(Document&);
- static PassRefPtr<HTMLParagraphElement> create(const QualifiedName&, Document&);
private:
- HTMLParagraphElement(const QualifiedName&, Document&);
+ explicit HTMLParagraphElement(Document&);
virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
virtual void collectStyleForPresentationAttribute(const QualifiedName&, const AtomicString&, MutableStylePropertySet*) OVERRIDE;
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLParagraphElement.idl b/chromium/third_party/WebKit/Source/core/html/HTMLParagraphElement.idl
index e6bd9e8bdd3..83242a10e44 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLParagraphElement.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLParagraphElement.idl
@@ -20,4 +20,3 @@
interface HTMLParagraphElement : HTMLElement {
[Reflect] attribute DOMString align;
};
-
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLParamElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLParamElement.cpp
index cf558480abb..982d53d993f 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLParamElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLParamElement.cpp
@@ -31,26 +31,25 @@ namespace WebCore {
using namespace HTMLNames;
-inline HTMLParamElement::HTMLParamElement(const QualifiedName& tagName, Document& document)
- : HTMLElement(tagName, document)
+inline HTMLParamElement::HTMLParamElement(Document& document)
+ : HTMLElement(paramTag, document)
{
- ASSERT(hasTagName(paramTag));
ScriptWrappable::init(this);
}
-PassRefPtr<HTMLParamElement> HTMLParamElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<HTMLParamElement> HTMLParamElement::create(Document& document)
{
- return adoptRef(new HTMLParamElement(tagName, document));
+ return adoptRef(new HTMLParamElement(document));
}
-String HTMLParamElement::name() const
+const AtomicString& HTMLParamElement::name() const
{
if (hasName())
return getNameAttribute();
return document().isHTMLDocument() ? emptyAtom : getIdAttribute();
}
-String HTMLParamElement::value() const
+const AtomicString& HTMLParamElement::value() const
{
return fastGetAttribute(valueAttr);
}
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLParamElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLParamElement.h
index 55953fe7c87..991e9595db9 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLParamElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLParamElement.h
@@ -29,26 +29,22 @@ namespace WebCore {
class HTMLParamElement FINAL : public HTMLElement {
public:
- static PassRefPtr<HTMLParamElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<HTMLParamElement> create(Document&);
- String name() const;
- String value() const;
+ const AtomicString& name() const;
+ const AtomicString& value() const;
static bool isURLParameter(const String&);
private:
- HTMLParamElement(const QualifiedName&, Document&);
+ explicit HTMLParamElement(Document&);
virtual bool isURLAttribute(const Attribute&) const OVERRIDE;
virtual void addSubresourceAttributeURLs(ListHashSet<KURL>&) const;
};
-inline HTMLParamElement* toHTMLParamElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::paramTag));
- return static_cast<HTMLParamElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(HTMLParamElement, hasTagName(HTMLNames::paramTag));
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLParamElement.idl b/chromium/third_party/WebKit/Source/core/html/HTMLParamElement.idl
index fea259445ea..d832e2c3c48 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLParamElement.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLParamElement.idl
@@ -23,4 +23,3 @@ interface HTMLParamElement : HTMLElement {
[Reflect] attribute DOMString value;
[Reflect] attribute DOMString valueType;
};
-
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLPlugInElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLPlugInElement.cpp
index c6ed4a557fa..c4ba8d0a939 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLPlugInElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLPlugInElement.cpp
@@ -28,32 +28,53 @@
#include "bindings/v8/ScriptController.h"
#include "bindings/v8/npruntime_impl.h"
#include "core/dom/Document.h"
-#include "core/dom/Event.h"
+#include "core/dom/PostAttachCallbacks.h"
+#include "core/dom/shadow/ShadowRoot.h"
+#include "core/events/Event.h"
+#include "core/frame/ContentSecurityPolicy.h"
+#include "core/frame/Frame.h"
+#include "core/html/HTMLImageLoader.h"
+#include "core/html/PluginDocument.h"
+#include "core/html/shadow/HTMLContentElement.h"
+#include "core/loader/FrameLoaderClient.h"
#include "core/page/EventHandler.h"
-#include "core/page/Frame.h"
-#include "core/platform/Widget.h"
+#include "core/page/Page.h"
+#include "core/frame/Settings.h"
#include "core/plugins/PluginView.h"
#include "core/rendering/RenderEmbeddedObject.h"
+#include "core/rendering/RenderImage.h"
#include "core/rendering/RenderWidget.h"
-#include "wtf/UnusedParam.h"
-
+#include "platform/Logging.h"
+#include "platform/MIMETypeFromURL.h"
+#include "platform/MIMETypeRegistry.h"
+#include "platform/Widget.h"
+#include "platform/plugins/PluginData.h"
namespace WebCore {
using namespace HTMLNames;
-HTMLPlugInElement::HTMLPlugInElement(const QualifiedName& tagName, Document& doc)
+HTMLPlugInElement::HTMLPlugInElement(const QualifiedName& tagName, Document& doc, bool createdByParser, PreferPlugInsForImagesOption preferPlugInsForImagesOption)
: HTMLFrameOwnerElement(tagName, doc)
+ , m_isDelayingLoadEvent(false)
, m_NPObject(0)
, m_isCapturingMouseEvents(false)
, m_inBeforeLoadEventHandler(false)
+ // m_needsWidgetUpdate(!createdByParser) allows HTMLObjectElement to delay
+ // widget updates until after all children are parsed. For HTMLEmbedElement
+ // this delay is unnecessary, but it is simpler to make both classes share
+ // the same codepath in this class.
+ , m_needsWidgetUpdate(!createdByParser)
+ , m_shouldPreferPlugInsForImages(preferPlugInsForImagesOption == ShouldPreferPlugInsForImages)
, m_displayState(Playing)
{
+ setHasCustomStyleCallbacks();
}
HTMLPlugInElement::~HTMLPlugInElement()
{
- ASSERT(!m_instance); // cleared in detach()
+ ASSERT(!m_pluginWrapper); // cleared in detach()
+ ASSERT(!m_isDelayingLoadEvent);
if (m_NPObject) {
_NPN_ReleaseObject(m_NPObject);
@@ -63,8 +84,7 @@ HTMLPlugInElement::~HTMLPlugInElement()
bool HTMLPlugInElement::canProcessDrag() const
{
- const PluginView* plugin = pluginWidget() && pluginWidget()->isPluginView() ? toPluginView(pluginWidget()) : 0;
- return plugin ? plugin->canProcessDrag() : false;
+ return pluginWidget() && pluginWidget()->isPluginView() && toPluginView(pluginWidget())->canProcessDrag();
}
bool HTMLPlugInElement::willRespondToMouseClickEvents()
@@ -72,11 +92,7 @@ bool HTMLPlugInElement::willRespondToMouseClickEvents()
if (isDisabledFormControl())
return false;
RenderObject* r = renderer();
- if (!r)
- return false;
- if (!r->isEmbeddedObject() && !r->isWidget())
- return false;
- return true;
+ return r && (r->isEmbeddedObject() || r->isWidget());
}
void HTMLPlugInElement::removeAllEventListeners()
@@ -88,13 +104,59 @@ void HTMLPlugInElement::removeAllEventListeners()
}
}
+void HTMLPlugInElement::didMoveToNewDocument(Document& oldDocument)
+{
+ if (m_imageLoader)
+ m_imageLoader->elementDidMoveToNewDocument();
+ HTMLFrameOwnerElement::didMoveToNewDocument(oldDocument);
+}
+
+void HTMLPlugInElement::attach(const AttachContext& context)
+{
+ HTMLFrameOwnerElement::attach(context);
+
+ if (!renderer() || useFallbackContent())
+ return;
+ if (isImageType()) {
+ if (!m_imageLoader)
+ m_imageLoader = adoptPtr(new HTMLImageLoader(this));
+ m_imageLoader->updateFromElement();
+ } else if (needsWidgetUpdate()
+ && renderEmbeddedObject()
+ && !renderEmbeddedObject()->showsUnavailablePluginIndicator()
+ && !wouldLoadAsNetscapePlugin(m_url, m_serviceType)
+ && !m_isDelayingLoadEvent) {
+ m_isDelayingLoadEvent = true;
+ document().incrementLoadEventDelayCount();
+ }
+}
+
+void HTMLPlugInElement::updateWidget()
+{
+ RefPtr<HTMLPlugInElement> protector(this);
+ updateWidgetInternal();
+ if (m_isDelayingLoadEvent) {
+ m_isDelayingLoadEvent = false;
+ document().decrementLoadEventDelayCount();
+ }
+}
+
void HTMLPlugInElement::detach(const AttachContext& context)
{
- m_instance.clear();
+ // Update the widget the next time we attach (detaching destroys the plugin).
+ // FIXME: None of this "needsWidgetUpdate" related code looks right.
+ if (renderer() && !useFallbackContent())
+ setNeedsWidgetUpdate(true);
+ if (m_isDelayingLoadEvent) {
+ m_isDelayingLoadEvent = false;
+ document().decrementLoadEventDelayCount();
+ }
+
+ resetInstance();
if (m_isCapturingMouseEvents) {
if (Frame* frame = document().frame())
- frame->eventHandler()->setCapturingMouseEventsNode(0);
+ frame->eventHandler().setCapturingMouseEventsNode(0);
m_isCapturingMouseEvents = false;
}
@@ -106,26 +168,60 @@ void HTMLPlugInElement::detach(const AttachContext& context)
HTMLFrameOwnerElement::detach(context);
}
+RenderObject* HTMLPlugInElement::createRenderer(RenderStyle* style)
+{
+ // Fallback content breaks the DOM->Renderer class relationship of this
+ // class and all superclasses because createObject won't necessarily
+ // return a RenderEmbeddedObject, RenderPart or even RenderWidget.
+ if (useFallbackContent())
+ return RenderObject::createObject(this, style);
+
+ if (isImageType()) {
+ RenderImage* image = new RenderImage(this);
+ image->setImageResource(RenderImageResource::create());
+ return image;
+ }
+
+ return new RenderEmbeddedObject(this);
+}
+
+void HTMLPlugInElement::willRecalcStyle(StyleRecalcChange)
+{
+ // FIXME: Why is this necessary? Manual re-attach is almost always wrong.
+ if (!useFallbackContent() && needsWidgetUpdate() && renderer() && !isImageType())
+ reattach();
+}
+
+void HTMLPlugInElement::finishParsingChildren()
+{
+ HTMLFrameOwnerElement::finishParsingChildren();
+ if (useFallbackContent())
+ return;
+
+ setNeedsWidgetUpdate(true);
+ if (inDocument())
+ setNeedsStyleRecalc();
+}
+
void HTMLPlugInElement::resetInstance()
{
- m_instance.clear();
+ m_pluginWrapper.clear();
}
-PassScriptInstance HTMLPlugInElement::getInstance()
+SharedPersistent<v8::Object>* HTMLPlugInElement::pluginWrapper()
{
Frame* frame = document().frame();
if (!frame)
return 0;
- // If the host dynamically turns off JavaScript (or Java) we will still return
- // the cached allocated Bindings::Instance. Not supporting this edge-case is OK.
- if (m_instance)
- return m_instance;
-
- if (Widget* widget = pluginWidget())
- m_instance = frame->script()->createScriptInstanceForWidget(widget);
-
- return m_instance;
+ // If the host dynamically turns off JavaScript (or Java) we will still
+ // return the cached allocated Bindings::Instance. Not supporting this
+ // edge-case is OK.
+ if (!m_pluginWrapper) {
+ if (Widget* widget = pluginWidget())
+ m_pluginWrapper = frame->script().createPluginWrapper(widget);
+ }
+ return m_pluginWrapper.get();
}
bool HTMLPlugInElement::dispatchBeforeLoadEvent(const String& sourceURL)
@@ -144,16 +240,15 @@ bool HTMLPlugInElement::dispatchBeforeLoadEvent(const String& sourceURL)
Widget* HTMLPlugInElement::pluginWidget() const
{
if (m_inBeforeLoadEventHandler) {
- // The plug-in hasn't loaded yet, and it makes no sense to try to load if beforeload handler happened to touch the plug-in element.
- // That would recursively call beforeload for the same element.
+ // The plug-in hasn't loaded yet, and it makes no sense to try to load
+ // if beforeload handler happened to touch the plug-in element. That
+ // would recursively call beforeload for the same element.
return 0;
}
- RenderWidget* renderWidget = renderWidgetForJSBindings();
- if (!renderWidget)
- return 0;
-
- return renderWidget->widget();
+ if (RenderWidget* renderWidget = renderWidgetForJSBindings())
+ return renderWidget->widget();
+ return 0;
}
bool HTMLPlugInElement::isPresentationAttribute(const QualifiedName& name) const
@@ -165,41 +260,44 @@ bool HTMLPlugInElement::isPresentationAttribute(const QualifiedName& name) const
void HTMLPlugInElement::collectStyleForPresentationAttribute(const QualifiedName& name, const AtomicString& value, MutableStylePropertySet* style)
{
- if (name == widthAttr)
+ if (name == widthAttr) {
addHTMLLengthToStyle(style, CSSPropertyWidth, value);
- else if (name == heightAttr)
+ } else if (name == heightAttr) {
addHTMLLengthToStyle(style, CSSPropertyHeight, value);
- else if (name == vspaceAttr) {
+ } else if (name == vspaceAttr) {
addHTMLLengthToStyle(style, CSSPropertyMarginTop, value);
addHTMLLengthToStyle(style, CSSPropertyMarginBottom, value);
} else if (name == hspaceAttr) {
addHTMLLengthToStyle(style, CSSPropertyMarginLeft, value);
addHTMLLengthToStyle(style, CSSPropertyMarginRight, value);
- } else if (name == alignAttr)
+ } else if (name == alignAttr) {
applyAlignmentAttributeToStyle(value, style);
- else
+ } else {
HTMLFrameOwnerElement::collectStyleForPresentationAttribute(name, value, style);
+ }
}
void HTMLPlugInElement::defaultEventHandler(Event* event)
{
- // Firefox seems to use a fake event listener to dispatch events to plug-in (tested with mouse events only).
- // This is observable via different order of events - in Firefox, event listeners specified in HTML attributes fires first, then an event
- // gets dispatched to plug-in, and only then other event listeners fire. Hopefully, this difference does not matter in practice.
+ // Firefox seems to use a fake event listener to dispatch events to plug-in
+ // (tested with mouse events only). This is observable via different order
+ // of events - in Firefox, event listeners specified in HTML attributes
+ // fires first, then an event gets dispatched to plug-in, and only then
+ // other event listeners fire. Hopefully, this difference does not matter in
+ // practice.
- // FIXME: Mouse down and scroll events are passed down to plug-in via custom code in EventHandler; these code paths should be united.
+ // FIXME: Mouse down and scroll events are passed down to plug-in via custom
+ // code in EventHandler; these code paths should be united.
RenderObject* r = renderer();
- if (r && r->isEmbeddedObject()) {
+ if (!r || !r->isWidget())
+ return;
+ if (r->isEmbeddedObject()) {
if (toRenderEmbeddedObject(r)->showsUnavailablePluginIndicator())
return;
-
if (displayState() < Playing)
return;
}
-
- if (!r || !r->isWidget())
- return;
RefPtr<Widget> widget = toRenderWidget(r)->widget();
if (!widget)
return;
@@ -211,20 +309,23 @@ void HTMLPlugInElement::defaultEventHandler(Event* event)
RenderWidget* HTMLPlugInElement::renderWidgetForJSBindings() const
{
- document().updateLayoutIgnorePendingStylesheets();
+ // Needs to load the plugin immediatedly because this function is called
+ // when JavaScript code accesses the plugin.
+ // FIXME: Check if dispatching events here is safe.
+ document().updateLayoutIgnorePendingStylesheets(Document::RunPostLayoutTasksSynchronously);
return existingRenderWidget();
}
bool HTMLPlugInElement::isKeyboardFocusable() const
{
- if (!document().page())
+ if (!document().isActive())
return false;
+ return pluginWidget() && pluginWidget()->isPluginView() && toPluginView(pluginWidget())->supportsKeyboardFocus();
+}
- const PluginView* plugin = pluginWidget() && pluginWidget()->isPluginView() ? toPluginView(pluginWidget()) : 0;
- if (plugin)
- return plugin->supportsKeyboardFocus();
-
- return false;
+bool HTMLPlugInElement::hasCustomFocusLogic() const
+{
+ return !hasAuthorShadowRoot();
}
bool HTMLPlugInElement::isPluginElement() const
@@ -246,8 +347,185 @@ NPObject* HTMLPlugInElement::getNPObject()
{
ASSERT(document().frame());
if (!m_NPObject)
- m_NPObject = document().frame()->script()->createScriptObjectForPluginElement(this);
+ m_NPObject = document().frame()->script().createScriptObjectForPluginElement(this);
return m_NPObject;
}
+bool HTMLPlugInElement::isImageType()
+{
+ if (m_serviceType.isEmpty() && protocolIs(m_url, "data"))
+ m_serviceType = mimeTypeFromDataURL(m_url);
+
+ if (Frame* frame = document().frame()) {
+ KURL completedURL = document().completeURL(m_url);
+ return frame->loader().client()->objectContentType(completedURL, m_serviceType, shouldPreferPlugInsForImages()) == ObjectContentImage;
+ }
+
+ return Image::supportsType(m_serviceType);
+}
+
+const String HTMLPlugInElement::loadedMimeType() const
+{
+ String mimeType = m_serviceType;
+ if (mimeType.isEmpty())
+ mimeType = mimeTypeFromURL(m_loadedUrl);
+ return mimeType;
+}
+
+RenderEmbeddedObject* HTMLPlugInElement::renderEmbeddedObject() const
+{
+ // HTMLObjectElement and HTMLEmbedElement may return arbitrary renderers
+ // when using fallback content.
+ if (!renderer() || !renderer()->isEmbeddedObject())
+ return 0;
+ return toRenderEmbeddedObject(renderer());
+}
+
+// We don't use m_url, as it may not be the final URL that the object loads,
+// depending on <param> values.
+bool HTMLPlugInElement::allowedToLoadFrameURL(const String& url)
+{
+ KURL completeURL = document().completeURL(url);
+ if (contentFrame() && protocolIsJavaScript(completeURL)
+ && !document().securityOrigin()->canAccess(contentDocument()->securityOrigin()))
+ return false;
+ return document().frame()->isURLAllowed(completeURL);
+}
+
+// We don't use m_url, or m_serviceType as they may not be the final values
+// that <object> uses depending on <param> values.
+bool HTMLPlugInElement::wouldLoadAsNetscapePlugin(const String& url, const String& serviceType)
+{
+ ASSERT(document().frame());
+ KURL completedURL;
+ if (!url.isEmpty())
+ completedURL = document().completeURL(url);
+ return document().frame()->loader().client()->objectContentType(completedURL, serviceType, shouldPreferPlugInsForImages()) == ObjectContentNetscapePlugin;
+}
+
+bool HTMLPlugInElement::requestObject(const String& url, const String& mimeType, const Vector<String>& paramNames, const Vector<String>& paramValues)
+{
+ if (url.isEmpty() && mimeType.isEmpty())
+ return false;
+
+ // FIXME: None of this code should use renderers!
+ RenderEmbeddedObject* renderer = renderEmbeddedObject();
+ ASSERT(renderer);
+ if (!renderer)
+ return false;
+
+ KURL completedURL = document().completeURL(url);
+
+ bool useFallback;
+ if (shouldUsePlugin(completedURL, mimeType, renderer->hasFallbackContent(), useFallback))
+ return loadPlugin(completedURL, mimeType, paramNames, paramValues, useFallback);
+
+ // If the plug-in element already contains a subframe,
+ // loadOrRedirectSubframe will re-use it. Otherwise, it will create a new
+ // frame and set it as the RenderPart's widget, causing what was previously
+ // in the widget to be torn down.
+ return loadOrRedirectSubframe(completedURL, getNameAttribute(), true);
+}
+
+bool HTMLPlugInElement::loadPlugin(const KURL& url, const String& mimeType, const Vector<String>& paramNames, const Vector<String>& paramValues, bool useFallback)
+{
+ Frame* frame = document().frame();
+
+ if (!frame->loader().allowPlugins(AboutToInstantiatePlugin))
+ return false;
+
+ if (!pluginIsLoadable(url, mimeType))
+ return false;
+
+ RenderEmbeddedObject* renderer = renderEmbeddedObject();
+ // FIXME: This code should not depend on renderer!
+ if (!renderer || useFallback)
+ return false;
+
+ WTF_LOG(Plugins, "%p Plug-in URL: %s", this, m_url.utf8().data());
+ WTF_LOG(Plugins, " Loaded URL: %s", url.string().utf8().data());
+ m_loadedUrl = url;
+
+ IntSize contentSize = roundedIntSize(LayoutSize(renderer->contentWidth(), renderer->contentHeight()));
+ bool loadManually = document().isPluginDocument() && !document().containsPlugins() && toPluginDocument(document()).shouldLoadPluginManually();
+ RefPtr<Widget> widget = frame->loader().client()->createPlugin(contentSize, this, url, paramNames, paramValues, mimeType, loadManually);
+
+ if (!widget) {
+ if (!renderer->showsUnavailablePluginIndicator())
+ renderer->setPluginUnavailabilityReason(RenderEmbeddedObject::PluginMissing);
+ return false;
+ }
+
+ renderer->setWidget(widget);
+ document().setContainsPlugins();
+ setNeedsStyleRecalc(LocalStyleChange, StyleChangeFromRenderer);
+ return true;
+}
+
+bool HTMLPlugInElement::shouldUsePlugin(const KURL& url, const String& mimeType, bool hasFallback, bool& useFallback)
+{
+ // Allow other plug-ins to win over QuickTime because if the user has
+ // installed a plug-in that can handle TIFF (which QuickTime can also
+ // handle) they probably intended to override QT.
+ if (document().frame()->page() && (mimeType == "image/tiff" || mimeType == "image/tif" || mimeType == "image/x-tiff")) {
+ const PluginData* pluginData = document().frame()->page()->pluginData();
+ String pluginName = pluginData ? pluginData->pluginNameForMimeType(mimeType) : String();
+ if (!pluginName.isEmpty() && !pluginName.contains("QuickTime", false))
+ return true;
+ }
+
+ ObjectContentType objectType = document().frame()->loader().client()->objectContentType(url, mimeType, shouldPreferPlugInsForImages());
+ // If an object's content can't be handled and it has no fallback, let
+ // it be handled as a plugin to show the broken plugin icon.
+ useFallback = objectType == ObjectContentNone && hasFallback;
+ return objectType == ObjectContentNone || objectType == ObjectContentNetscapePlugin || objectType == ObjectContentOtherPlugin;
+
+}
+
+bool HTMLPlugInElement::pluginIsLoadable(const KURL& url, const String& mimeType)
+{
+ Frame* frame = document().frame();
+ Settings* settings = frame->settings();
+ if (!settings)
+ return false;
+
+ if (MIMETypeRegistry::isJavaAppletMIMEType(mimeType) && !settings->javaEnabled())
+ return false;
+
+ if (document().isSandboxed(SandboxPlugins))
+ return false;
+
+ if (!document().securityOrigin()->canDisplay(url)) {
+ FrameLoader::reportLocalLoadFailed(frame, url.string());
+ return false;
+ }
+
+ AtomicString declaredMimeType = document().isPluginDocument() && document().ownerElement() ?
+ document().ownerElement()->fastGetAttribute(HTMLNames::typeAttr) :
+ fastGetAttribute(HTMLNames::typeAttr);
+ if (!document().contentSecurityPolicy()->allowObjectFromSource(url)
+ || !document().contentSecurityPolicy()->allowPluginType(mimeType, declaredMimeType, url)) {
+ renderEmbeddedObject()->setPluginUnavailabilityReason(RenderEmbeddedObject::PluginBlockedByContentSecurityPolicy);
+ return false;
+ }
+
+ return frame->loader().mixedContentChecker()->canRunInsecureContent(document().securityOrigin(), url);
+}
+
+void HTMLPlugInElement::didAddUserAgentShadowRoot(ShadowRoot&)
+{
+ userAgentShadowRoot()->appendChild(HTMLContentElement::create(document()));
+}
+
+void HTMLPlugInElement::didAddShadowRoot(ShadowRoot& root)
+{
+ if (root.isOldestAuthorShadowRoot())
+ lazyReattachIfAttached();
+}
+
+bool HTMLPlugInElement::useFallbackContent() const
+{
+ return hasAuthorShadowRoot();
+}
+
}
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLPlugInElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLPlugInElement.h
index 0647dfd3d24..37d631466b5 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLPlugInElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLPlugInElement.h
@@ -23,100 +23,120 @@
#ifndef HTMLPlugInElement_h
#define HTMLPlugInElement_h
+#include "bindings/v8/SharedPersistent.h"
#include "core/html/HTMLFrameOwnerElement.h"
-#include "bindings/v8/ScriptInstance.h"
-
struct NPObject;
namespace WebCore {
+class HTMLImageLoader;
class RenderEmbeddedObject;
class RenderWidget;
class Widget;
+enum PreferPlugInsForImagesOption {
+ ShouldPreferPlugInsForImages,
+ ShouldNotPreferPlugInsForImages
+};
+
class HTMLPlugInElement : public HTMLFrameOwnerElement {
public:
virtual ~HTMLPlugInElement();
void resetInstance();
-
- PassScriptInstance getInstance();
-
+ SharedPersistent<v8::Object>* pluginWrapper();
Widget* pluginWidget() const;
-
- enum DisplayState {
- Restarting,
- RestartingWithPendingMouseClick,
- Playing
- };
- DisplayState displayState() const { return m_displayState; }
- virtual void setDisplayState(DisplayState state) { m_displayState = state; }
-
NPObject* getNPObject();
-
- bool isCapturingMouseEvents() const { return m_isCapturingMouseEvents; }
- void setIsCapturingMouseEvents(bool capturing) { m_isCapturingMouseEvents = capturing; }
-
- bool canContainRangeEndPoint() const { return false; }
-
bool canProcessDrag() const;
+ const String& url() const { return m_url; }
- virtual bool willRespondToMouseClickEvents() OVERRIDE;
-
- virtual bool isPlugInImageElement() const { return false; }
-
- virtual void removeAllEventListeners() OVERRIDE FINAL;
+ // Public for FrameView::addWidgetToUpdate()
+ bool needsWidgetUpdate() const { return m_needsWidgetUpdate; }
+ void setNeedsWidgetUpdate(bool needsWidgetUpdate) { m_needsWidgetUpdate = needsWidgetUpdate; }
+ void updateWidget();
protected:
- HTMLPlugInElement(const QualifiedName& tagName, Document&);
+ HTMLPlugInElement(const QualifiedName& tagName, Document&, bool createdByParser, PreferPlugInsForImagesOption);
- virtual void detach(const AttachContext& = AttachContext()) OVERRIDE;
+ // Node functions:
+ virtual void didMoveToNewDocument(Document& oldDocument) OVERRIDE;
+ virtual bool dispatchBeforeLoadEvent(const String& sourceURL) OVERRIDE;
+
+ // Element functions:
virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
virtual void collectStyleForPresentationAttribute(const QualifiedName&, const AtomicString&, MutableStylePropertySet*) OVERRIDE;
- virtual bool useFallbackContent() const { return false; }
+ virtual bool useFallbackContent() const;
+ // Create or update the RenderWidget and return it, triggering layout if
+ // necessary.
+ virtual RenderWidget* renderWidgetForJSBindings() const;
- virtual bool dispatchBeforeLoadEvent(const String& sourceURL) OVERRIDE;
+ bool isImageType();
+ bool shouldPreferPlugInsForImages() const { return m_shouldPreferPlugInsForImages; }
+ RenderEmbeddedObject* renderEmbeddedObject() const;
+ bool allowedToLoadFrameURL(const String& url);
+ bool requestObject(const String& url, const String& mimeType, const Vector<String>& paramNames, const Vector<String>& paramValues);
+ bool shouldUsePlugin(const KURL&, const String& mimeType, bool hasFallback, bool& useFallback);
- // Create or update the RenderWidget and return it, triggering layout if necessary.
- virtual RenderWidget* renderWidgetForJSBindings() const;
+ String m_serviceType;
+ String m_url;
+ KURL m_loadedUrl;
+ OwnPtr<HTMLImageLoader> m_imageLoader;
+ bool m_isDelayingLoadEvent;
private:
- virtual bool areAuthorShadowsAllowed() const OVERRIDE { return false; }
-
- virtual void defaultEventHandler(Event*);
+ // EventTarget functions:
+ virtual void removeAllEventListeners() OVERRIDE FINAL;
- // Return any existing RenderWidget without triggering relayout, or 0 if it doesn't yet exist.
- virtual RenderWidget* existingRenderWidget() const = 0;
+ // Node functions:
+ virtual bool canContainRangeEndPoint() const OVERRIDE { return false; }
+ virtual bool willRespondToMouseClickEvents() OVERRIDE;
+ virtual void defaultEventHandler(Event*) OVERRIDE;
+ virtual void attach(const AttachContext& = AttachContext()) OVERRIDE;
+ virtual void detach(const AttachContext& = AttachContext()) OVERRIDE;
+ virtual void finishParsingChildren() OVERRIDE;
+ virtual bool isPluginElement() const OVERRIDE;
+ // Element functions:
+ virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
+ virtual void willRecalcStyle(StyleRecalcChange) OVERRIDE FINAL;
virtual bool supportsFocus() const OVERRIDE { return true; };
virtual bool rendererIsFocusable() const OVERRIDE;
-
virtual bool isKeyboardFocusable() const OVERRIDE;
- virtual bool isPluginElement() const;
+ virtual void didAddUserAgentShadowRoot(ShadowRoot&) OVERRIDE;
+ virtual void didAddShadowRoot(ShadowRoot&) OVERRIDE;
+
+ // HTMLElement function:
+ virtual bool hasCustomFocusLogic() const OVERRIDE;
- mutable ScriptInstance m_instance;
+ // Return any existing RenderWidget without triggering relayout, or 0 if it
+ // doesn't yet exist.
+ virtual RenderWidget* existingRenderWidget() const = 0;
+ virtual void updateWidgetInternal() = 0;
+
+ enum DisplayState {
+ Restarting,
+ RestartingWithPendingMouseClick,
+ Playing
+ };
+ DisplayState displayState() const { return m_displayState; }
+ void setDisplayState(DisplayState state) { m_displayState = state; }
+ const String loadedMimeType() const;
+ bool loadPlugin(const KURL&, const String& mimeType, const Vector<String>& paramNames, const Vector<String>& paramValues, bool useFallback);
+ bool pluginIsLoadable(const KURL&, const String& mimeType);
+ bool wouldLoadAsNetscapePlugin(const String& url, const String& serviceType);
+
+ mutable RefPtr<SharedPersistent<v8::Object> > m_pluginWrapper;
NPObject* m_NPObject;
bool m_isCapturingMouseEvents;
bool m_inBeforeLoadEventHandler;
+ bool m_needsWidgetUpdate;
+ bool m_shouldPreferPlugInsForImages;
DisplayState m_displayState;
};
-inline HTMLPlugInElement* toHTMLPlugInElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->isPluginElement());
- return static_cast<HTMLPlugInElement*>(node);
-}
-
-inline const HTMLPlugInElement* toHTMLPlugInElement(const Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->isPluginElement());
- return static_cast<const HTMLPlugInElement*>(node);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toHTMLPlugInElement(const HTMLPlugInElement*);
+DEFINE_NODE_TYPE_CASTS(HTMLPlugInElement, isPluginElement());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLPlugInImageElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLPlugInImageElement.cpp
deleted file mode 100644
index 51e23426c79..00000000000
--- a/chromium/third_party/WebKit/Source/core/html/HTMLPlugInImageElement.cpp
+++ /dev/null
@@ -1,330 +0,0 @@
-/*
- * Copyright (C) 2008, 2011, 2012 Apple Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#include "config.h"
-#include "core/html/HTMLPlugInImageElement.h"
-
-#include "bindings/v8/ScriptController.h"
-#include "core/dom/PostAttachCallbacks.h"
-#include "core/html/HTMLImageLoader.h"
-#include "core/html/PluginDocument.h"
-#include "core/loader/FrameLoader.h"
-#include "core/loader/FrameLoaderClient.h"
-#include "core/page/ContentSecurityPolicy.h"
-#include "core/page/Frame.h"
-#include "core/page/Page.h"
-#include "core/page/Settings.h"
-#include "core/platform/Logging.h"
-#include "core/platform/MIMETypeFromURL.h"
-#include "core/platform/MIMETypeRegistry.h"
-#include "core/platform/graphics/Image.h"
-#include "core/plugins/PluginData.h"
-#include "core/rendering/RenderEmbeddedObject.h"
-#include "core/rendering/RenderImage.h"
-#include "weborigin/SecurityOrigin.h"
-
-namespace WebCore {
-
-using namespace HTMLNames;
-
-typedef Vector<RefPtr<HTMLPlugInImageElement> > HTMLPlugInImageElementList;
-
-static const int sizingTinyDimensionThreshold = 40;
-static const int sizingSmallWidthThreshold = 250;
-static const int sizingMediumWidthThreshold = 450;
-static const int sizingMediumHeightThreshold = 300;
-static const float sizingFullPageAreaRatioThreshold = 0.96;
-static const float autostartSoonAfterUserGestureThreshold = 5.0;
-
-HTMLPlugInImageElement::HTMLPlugInImageElement(const QualifiedName& tagName, Document& document, bool createdByParser, PreferPlugInsForImagesOption preferPlugInsForImagesOption)
- : HTMLPlugInElement(tagName, document)
- // m_needsWidgetUpdate(!createdByParser) allows HTMLObjectElement to delay
- // widget updates until after all children are parsed. For HTMLEmbedElement
- // this delay is unnecessary, but it is simpler to make both classes share
- // the same codepath in this class.
- , m_needsWidgetUpdate(!createdByParser)
- , m_shouldPreferPlugInsForImages(preferPlugInsForImagesOption == ShouldPreferPlugInsForImages)
- , m_createdDuringUserGesture(ScriptController::processingUserGesture())
-{
- setHasCustomStyleCallbacks();
-}
-
-HTMLPlugInImageElement::~HTMLPlugInImageElement()
-{
-}
-
-void HTMLPlugInImageElement::setDisplayState(DisplayState state)
-{
- HTMLPlugInElement::setDisplayState(state);
-}
-
-RenderEmbeddedObject* HTMLPlugInImageElement::renderEmbeddedObject() const
-{
- // HTMLObjectElement and HTMLEmbedElement may return arbitrary renderers
- // when using fallback content.
- if (!renderer() || !renderer()->isEmbeddedObject())
- return 0;
- return toRenderEmbeddedObject(renderer());
-}
-
-bool HTMLPlugInImageElement::isImageType()
-{
- if (m_serviceType.isEmpty() && protocolIs(m_url, "data"))
- m_serviceType = mimeTypeFromDataURL(m_url);
-
- if (Frame* frame = document().frame()) {
- KURL completedURL = document().completeURL(m_url);
- return frame->loader()->client()->objectContentType(completedURL, m_serviceType, shouldPreferPlugInsForImages()) == ObjectContentImage;
- }
-
- return Image::supportsType(m_serviceType);
-}
-
-// We don't use m_url, as it may not be the final URL that the object loads,
-// depending on <param> values.
-bool HTMLPlugInImageElement::allowedToLoadFrameURL(const String& url)
-{
- KURL completeURL = document().completeURL(url);
-
- if (contentFrame() && protocolIsJavaScript(completeURL)
- && !document().securityOrigin()->canAccess(contentDocument()->securityOrigin()))
- return false;
-
- return document().frame()->isURLAllowed(completeURL);
-}
-
-// We don't use m_url, or m_serviceType as they may not be the final values
-// that <object> uses depending on <param> values.
-bool HTMLPlugInImageElement::wouldLoadAsNetscapePlugin(const String& url, const String& serviceType)
-{
- ASSERT(document().frame());
- KURL completedURL;
- if (!url.isEmpty())
- completedURL = document().completeURL(url);
-
- FrameLoader* frameLoader = document().frame()->loader();
- ASSERT(frameLoader);
- if (frameLoader->client()->objectContentType(completedURL, serviceType, shouldPreferPlugInsForImages()) == ObjectContentNetscapePlugin)
- return true;
- return false;
-}
-
-RenderObject* HTMLPlugInImageElement::createRenderer(RenderStyle* style)
-{
- // Fallback content breaks the DOM->Renderer class relationship of this
- // class and all superclasses because createObject won't necessarily
- // return a RenderEmbeddedObject, RenderPart or even RenderWidget.
- if (useFallbackContent())
- return RenderObject::createObject(this, style);
-
- if (isImageType()) {
- RenderImage* image = new RenderImage(this);
- image->setImageResource(RenderImageResource::create());
- return image;
- }
-
- return new RenderEmbeddedObject(this);
-}
-
-void HTMLPlugInImageElement::willRecalcStyle(StyleRecalcChange)
-{
- // FIXME: Why is this necessary? Manual re-attach is almost always wrong.
- if (!useFallbackContent() && needsWidgetUpdate() && renderer() && !isImageType())
- reattach();
-}
-
-void HTMLPlugInImageElement::attach(const AttachContext& context)
-{
- bool isImage = isImageType();
-
- if (!isImage)
- PostAttachCallbacks::queueCallback(HTMLPlugInImageElement::updateWidgetCallback, this);
-
- HTMLPlugInElement::attach(context);
-
- if (isImage && renderer() && !useFallbackContent()) {
- if (!m_imageLoader)
- m_imageLoader = adoptPtr(new HTMLImageLoader(this));
- m_imageLoader->updateFromElement();
- }
-}
-
-void HTMLPlugInImageElement::detach(const AttachContext& context)
-{
- // FIXME: Because of the insanity that is HTMLPlugInImageElement::recalcStyle,
- // we can end up detaching during an attach() call, before we even have a
- // renderer. In that case, don't mark the widget for update.
- if (attached() && renderer() && !useFallbackContent())
- // Update the widget the next time we attach (detaching destroys the plugin).
- setNeedsWidgetUpdate(true);
- HTMLPlugInElement::detach(context);
-}
-
-void HTMLPlugInImageElement::updateWidgetIfNecessary()
-{
- document().updateStyleIfNeeded();
-
- if (!needsWidgetUpdate() || useFallbackContent() || isImageType())
- return;
-
- if (!renderEmbeddedObject() || renderEmbeddedObject()->showsUnavailablePluginIndicator())
- return;
-
- updateWidget(CreateOnlyNonNetscapePlugins);
-}
-
-void HTMLPlugInImageElement::finishParsingChildren()
-{
- HTMLPlugInElement::finishParsingChildren();
- if (useFallbackContent())
- return;
-
- setNeedsWidgetUpdate(true);
- if (inDocument())
- setNeedsStyleRecalc();
-}
-
-void HTMLPlugInImageElement::didMoveToNewDocument(Document* oldDocument)
-{
- if (m_imageLoader)
- m_imageLoader->elementDidMoveToNewDocument();
- HTMLPlugInElement::didMoveToNewDocument(oldDocument);
-}
-
-void HTMLPlugInImageElement::updateWidgetCallback(Node* n)
-{
- toHTMLPlugInImageElement(n)->updateWidgetIfNecessary();
-}
-
-bool HTMLPlugInImageElement::requestObject(const String& url, const String& mimeType, const Vector<String>& paramNames, const Vector<String>& paramValues)
-{
- if (url.isEmpty() && mimeType.isEmpty())
- return false;
-
- // FIXME: None of this code should use renderers!
- RenderEmbeddedObject* renderer = renderEmbeddedObject();
- ASSERT(renderer);
- if (!renderer)
- return false;
-
- KURL completedURL = document().completeURL(url);
-
- bool useFallback;
- if (shouldUsePlugin(completedURL, mimeType, renderer->hasFallbackContent(), useFallback)) {
- bool success = loadPlugin(completedURL, mimeType, paramNames, paramValues, useFallback);
- return success;
- }
-
- // If the plug-in element already contains a subframe, loadOrRedirectSubframe will re-use it. Otherwise,
- // it will create a new frame and set it as the RenderPart's widget, causing what was previously
- // in the widget to be torn down.
- return loadOrRedirectSubframe(completedURL, getNameAttribute(), true);
-}
-
-bool HTMLPlugInImageElement::loadPlugin(const KURL& url, const String& mimeType, const Vector<String>& paramNames, const Vector<String>& paramValues, bool useFallback)
-{
- Frame* frame = document().frame();
-
- if (!frame->loader()->allowPlugins(AboutToInstantiatePlugin))
- return false;
-
- if (!pluginIsLoadable(url, mimeType))
- return false;
-
- RenderEmbeddedObject* renderer = renderEmbeddedObject();
-
- // FIXME: This code should not depend on renderer!
- if (!renderer || useFallback)
- return false;
-
- LOG(Plugins, "%p Plug-in URL: %s", this, m_url.utf8().data());
- LOG(Plugins, " Loaded URL: %s", url.string().utf8().data());
- m_loadedUrl = url;
-
- IntSize contentSize = roundedIntSize(LayoutSize(renderer->contentWidth(), renderer->contentHeight()));
- bool loadManually = document().isPluginDocument() && !frame->loader()->containsPlugins() && toPluginDocument(document()).shouldLoadPluginManually();
- RefPtr<Widget> widget = frame->loader()->client()->createPlugin(contentSize, this, url, paramNames, paramValues, mimeType, loadManually);
-
- if (!widget) {
- if (!renderer->showsUnavailablePluginIndicator())
- renderer->setPluginUnavailabilityReason(RenderEmbeddedObject::PluginMissing);
- return false;
- }
-
- renderer->setWidget(widget);
- frame->loader()->setContainsPlugins();
- setNeedsStyleRecalc(LocalStyleChange, StyleChangeFromRenderer);
- return true;
-}
-
-bool HTMLPlugInImageElement::shouldUsePlugin(const KURL& url, const String& mimeType, bool hasFallback, bool& useFallback)
-{
- // Allow other plug-ins to win over QuickTime because if the user has installed a plug-in that
- // can handle TIFF (which QuickTime can also handle) they probably intended to override QT.
- if (document().frame()->page() && (mimeType == "image/tiff" || mimeType == "image/tif" || mimeType == "image/x-tiff")) {
- const PluginData* pluginData = document().frame()->page()->pluginData();
- String pluginName = pluginData ? pluginData->pluginNameForMimeType(mimeType) : String();
- if (!pluginName.isEmpty() && !pluginName.contains("QuickTime", false))
- return true;
- }
-
- ObjectContentType objectType = document().frame()->loader()->client()->objectContentType(url, mimeType, shouldPreferPlugInsForImages());
- // If an object's content can't be handled and it has no fallback, let
- // it be handled as a plugin to show the broken plugin icon.
- useFallback = objectType == ObjectContentNone && hasFallback;
- return objectType == ObjectContentNone || objectType == ObjectContentNetscapePlugin || objectType == ObjectContentOtherPlugin;
-
-}
-
-bool HTMLPlugInImageElement::pluginIsLoadable(const KURL& url, const String& mimeType)
-{
- Frame* frame = document().frame();
- Settings* settings = frame->settings();
- if (!settings)
- return false;
-
- if (MIMETypeRegistry::isJavaAppletMIMEType(mimeType)) {
- if (!settings->isJavaEnabled())
- return false;
- }
-
- if (document().isSandboxed(SandboxPlugins))
- return false;
-
- if (!document().securityOrigin()->canDisplay(url)) {
- FrameLoader::reportLocalLoadFailed(frame, url.string());
- return false;
- }
-
- String declaredMimeType = document().isPluginDocument() && document().ownerElement() ?
- document().ownerElement()->fastGetAttribute(HTMLNames::typeAttr) :
- fastGetAttribute(HTMLNames::typeAttr);
- if (!document().contentSecurityPolicy()->allowObjectFromSource(url)
- || !document().contentSecurityPolicy()->allowPluginType(mimeType, declaredMimeType, url)) {
- renderEmbeddedObject()->setPluginUnavailabilityReason(RenderEmbeddedObject::PluginBlockedByContentSecurityPolicy);
- return false;
- }
-
- if (frame->loader() && !frame->loader()->mixedContentChecker()->canRunInsecureContent(document().securityOrigin(), url))
- return false;
- return true;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLPlugInImageElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLPlugInImageElement.h
deleted file mode 100644
index f994810aa9f..00000000000
--- a/chromium/third_party/WebKit/Source/core/html/HTMLPlugInImageElement.h
+++ /dev/null
@@ -1,142 +0,0 @@
-/*
- * Copyright (C) 2008, 2009, 2011, 2012 Apple Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#ifndef HTMLPlugInImageElement_h
-#define HTMLPlugInImageElement_h
-
-#include "core/html/HTMLPlugInElement.h"
-
-#include "core/platform/MIMETypeFromURL.h"
-#include "core/rendering/style/RenderStyle.h"
-#include "wtf/OwnPtr.h"
-
-namespace WebCore {
-
-class HTMLImageLoader;
-class FrameLoader;
-class Image;
-class MouseEvent;
-class Widget;
-
-enum PluginCreationOption {
- CreateAnyWidgetType,
- CreateOnlyNonNetscapePlugins,
-};
-
-enum PreferPlugInsForImagesOption {
- ShouldPreferPlugInsForImages,
- ShouldNotPreferPlugInsForImages
-};
-
-// Base class for HTMLObjectElement and HTMLEmbedElement
-class HTMLPlugInImageElement : public HTMLPlugInElement {
-public:
- virtual ~HTMLPlugInImageElement();
-
- RenderEmbeddedObject* renderEmbeddedObject() const;
-
- virtual void setDisplayState(DisplayState) OVERRIDE;
-
- virtual void updateWidget(PluginCreationOption) = 0;
-
- const String& serviceType() const { return m_serviceType; }
- const String& url() const { return m_url; }
- const KURL& loadedUrl() const { return m_loadedUrl; }
-
- const String loadedMimeType() const
- {
- String mimeType = serviceType();
- if (mimeType.isEmpty())
- mimeType = mimeTypeFromURL(m_loadedUrl);
- return mimeType;
- }
-
- bool shouldPreferPlugInsForImages() const { return m_shouldPreferPlugInsForImages; }
-
- // Public for FrameView::addWidgetToUpdate()
- bool needsWidgetUpdate() const { return m_needsWidgetUpdate; }
- void setNeedsWidgetUpdate(bool needsWidgetUpdate) { m_needsWidgetUpdate = needsWidgetUpdate; }
-
-protected:
- HTMLPlugInImageElement(const QualifiedName& tagName, Document&, bool createdByParser, PreferPlugInsForImagesOption);
-
- bool isImageType();
-
- OwnPtr<HTMLImageLoader> m_imageLoader;
- String m_serviceType;
- String m_url;
- KURL m_loadedUrl;
-
- static void updateWidgetCallback(Node*);
- virtual void attach(const AttachContext& = AttachContext()) OVERRIDE;
- virtual void detach(const AttachContext& = AttachContext()) OVERRIDE;
-
- bool allowedToLoadFrameURL(const String& url);
- bool wouldLoadAsNetscapePlugin(const String& url, const String& serviceType);
-
- virtual void didMoveToNewDocument(Document* oldDocument) OVERRIDE;
-
- bool requestObject(const String& url, const String& mimeType, const Vector<String>& paramNames, const Vector<String>& paramValues);
- bool shouldUsePlugin(const KURL&, const String& mimeType, bool hasFallback, bool& useFallback);
-
-private:
- virtual RenderObject* createRenderer(RenderStyle*);
- virtual void willRecalcStyle(StyleRecalcChange) OVERRIDE FINAL;
-
- virtual void finishParsingChildren();
-
- void updateWidgetIfNecessary();
-
- void swapRendererTimerFired(Timer<HTMLPlugInImageElement>*);
-
- void restartSimilarPlugIns();
-
- bool loadPlugin(const KURL&, const String& mimeType, const Vector<String>& paramNames, const Vector<String>& paramValues, bool useFallback);
- bool pluginIsLoadable(const KURL&, const String& mimeType);
-
- virtual bool isPlugInImageElement() const OVERRIDE { return true; }
-
- bool m_needsWidgetUpdate;
- bool m_shouldPreferPlugInsForImages;
- bool m_createdDuringUserGesture;
-};
-
-inline HTMLPlugInImageElement* toHTMLPlugInImageElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->isPluginElement());
- HTMLPlugInElement* plugInElement = static_cast<HTMLPlugInElement*>(node);
- ASSERT_WITH_SECURITY_IMPLICATION(plugInElement->isPlugInImageElement());
- return static_cast<HTMLPlugInImageElement*>(plugInElement);
-}
-
-inline const HTMLPlugInImageElement* toHTMLPlugInImageElement(const Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->isPluginElement());
- const HTMLPlugInElement* plugInElement = static_cast<const HTMLPlugInElement*>(node);
- ASSERT_WITH_SECURITY_IMPLICATION(plugInElement->isPlugInImageElement());
- return static_cast<const HTMLPlugInImageElement*>(plugInElement);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toHTMLPlugInImageElement(const HTMLPlugInImageElement*);
-
-} // namespace WebCore
-
-#endif // HTMLPlugInImageElement_h
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLProgressElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLProgressElement.cpp
index 34ecdb63819..3baeb6506a6 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLProgressElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLProgressElement.cpp
@@ -23,6 +23,7 @@
#include "core/html/HTMLProgressElement.h"
#include "HTMLNames.h"
+#include "bindings/v8/ExceptionMessages.h"
#include "bindings/v8/ExceptionState.h"
#include "bindings/v8/ExceptionStatePlaceholder.h"
#include "core/dom/ExceptionCode.h"
@@ -38,11 +39,10 @@ using namespace HTMLNames;
const double HTMLProgressElement::IndeterminatePosition = -1;
const double HTMLProgressElement::InvalidPosition = -2;
-HTMLProgressElement::HTMLProgressElement(const QualifiedName& tagName, Document& document)
- : LabelableElement(tagName, document)
+HTMLProgressElement::HTMLProgressElement(Document& document)
+ : LabelableElement(progressTag, document)
, m_value(0)
{
- ASSERT(hasTagName(progressTag));
ScriptWrappable::init(this);
}
@@ -50,9 +50,9 @@ HTMLProgressElement::~HTMLProgressElement()
{
}
-PassRefPtr<HTMLProgressElement> HTMLProgressElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<HTMLProgressElement> HTMLProgressElement::create(Document& document)
{
- RefPtr<HTMLProgressElement> progress = adoptRef(new HTMLProgressElement(tagName, document));
+ RefPtr<HTMLProgressElement> progress = adoptRef(new HTMLProgressElement(document));
progress->ensureUserAgentShadowRoot();
return progress.release();
}
@@ -94,32 +94,33 @@ void HTMLProgressElement::attach(const AttachContext& context)
double HTMLProgressElement::value() const
{
- double value = parseToDoubleForNumberType(fastGetAttribute(valueAttr));
+ double value = getFloatingPointAttribute(valueAttr);
return !std::isfinite(value) || value < 0 ? 0 : std::min(value, max());
}
-void HTMLProgressElement::setValue(double value, ExceptionState& es)
+void HTMLProgressElement::setValue(double value, ExceptionState& exceptionState)
{
if (!std::isfinite(value)) {
- es.throwDOMException(NotSupportedError);
+ exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::notAFiniteNumber(value));
return;
}
- setAttribute(valueAttr, String::number(value >= 0 ? value : 0));
+ setFloatingPointAttribute(valueAttr, std::max(value, 0.));
}
double HTMLProgressElement::max() const
{
- double max = parseToDoubleForNumberType(getAttribute(maxAttr));
+ double max = getFloatingPointAttribute(maxAttr);
return !std::isfinite(max) || max <= 0 ? 1 : max;
}
-void HTMLProgressElement::setMax(double max, ExceptionState& es)
+void HTMLProgressElement::setMax(double max, ExceptionState& exceptionState)
{
if (!std::isfinite(max)) {
- es.throwDOMException(NotSupportedError);
+ exceptionState.throwDOMException(NotSupportedError, ExceptionMessages::notAFiniteNumber(max));
return;
}
- setAttribute(maxAttr, String::number(max > 0 ? max : 1));
+ // FIXME: The specification says we should ignore the input value if it is inferior or equal to 0.
+ setFloatingPointAttribute(maxAttr, max > 0 ? max : 1);
}
double HTMLProgressElement::position() const
@@ -145,19 +146,19 @@ void HTMLProgressElement::didElementStateChange()
}
}
-void HTMLProgressElement::didAddUserAgentShadowRoot(ShadowRoot* root)
+void HTMLProgressElement::didAddUserAgentShadowRoot(ShadowRoot& root)
{
ASSERT(!m_value);
RefPtr<ProgressInnerElement> inner = ProgressInnerElement::create(document());
- inner->setPart(AtomicString("-webkit-progress-inner-element", AtomicString::ConstructFromLiteral));
- root->appendChild(inner);
+ inner->setPseudo(AtomicString("-webkit-progress-inner-element", AtomicString::ConstructFromLiteral));
+ root.appendChild(inner);
RefPtr<ProgressBarElement> bar = ProgressBarElement::create(document());
- bar->setPart(AtomicString("-webkit-progress-bar", AtomicString::ConstructFromLiteral));
+ bar->setPseudo(AtomicString("-webkit-progress-bar", AtomicString::ConstructFromLiteral));
RefPtr<ProgressValueElement> value = ProgressValueElement::create(document());
m_value = value.get();
- m_value->setPart(AtomicString("-webkit-progress-value", AtomicString::ConstructFromLiteral));
+ m_value->setPseudo(AtomicString("-webkit-progress-value", AtomicString::ConstructFromLiteral));
m_value->setWidthPercentage(HTMLProgressElement::IndeterminatePosition * 100);
bar->appendChild(m_value);
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLProgressElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLProgressElement.h
index e9f624e4342..6162ded1570 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLProgressElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLProgressElement.h
@@ -34,7 +34,7 @@ public:
static const double IndeterminatePosition;
static const double InvalidPosition;
- static PassRefPtr<HTMLProgressElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<HTMLProgressElement> create(Document&);
double value() const;
void setValue(double, ExceptionState&);
@@ -47,7 +47,7 @@ public:
virtual bool canContainRangeEndPoint() const { return false; }
private:
- HTMLProgressElement(const QualifiedName&, Document&);
+ explicit HTMLProgressElement(Document&);
virtual ~HTMLProgressElement();
virtual bool areAuthorShadowsAllowed() const OVERRIDE { return false; }
@@ -62,7 +62,7 @@ private:
virtual void attach(const AttachContext& = AttachContext()) OVERRIDE;
void didElementStateChange();
- virtual void didAddUserAgentShadowRoot(ShadowRoot*) OVERRIDE;
+ virtual void didAddUserAgentShadowRoot(ShadowRoot&) OVERRIDE;
bool isDeterminate() const;
ProgressValueElement* m_value;
@@ -74,11 +74,7 @@ inline bool isHTMLProgressElement(Node* node)
return node->hasTagName(HTMLNames::progressTag);
}
-inline HTMLProgressElement* toHTMLProgressElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || isHTMLProgressElement(node));
- return static_cast<HTMLProgressElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(HTMLProgressElement, hasTagName(HTMLNames::progressTag));
} // namespace
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLProgressElement.idl b/chromium/third_party/WebKit/Source/core/html/HTMLProgressElement.idl
index a2f3f328e16..b2f5a9cdbba 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLProgressElement.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLProgressElement.idl
@@ -18,8 +18,8 @@
*/
interface HTMLProgressElement : HTMLElement {
- [SetterRaisesException] attribute double value;
- [SetterRaisesException] attribute double max;
+ [RaisesException=Setter] attribute double value;
+ [RaisesException=Setter] attribute double max;
readonly attribute double position;
readonly attribute NodeList labels;
};
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLQuoteElement.idl b/chromium/third_party/WebKit/Source/core/html/HTMLQuoteElement.idl
index c53a1a2f1ef..93a2aff07ea 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLQuoteElement.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLQuoteElement.idl
@@ -18,5 +18,5 @@
*/
interface HTMLQuoteElement : HTMLElement {
- [Reflect, URL] attribute DOMString cite;
+ [Reflect, URL, PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute DOMString cite;
};
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLScriptElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLScriptElement.cpp
index 4f59a671bff..fd54cc283c2 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLScriptElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLScriptElement.cpp
@@ -28,26 +28,25 @@
#include "bindings/v8/ScriptEventListener.h"
#include "core/dom/Attribute.h"
#include "core/dom/Document.h"
-#include "core/dom/Event.h"
-#include "core/dom/EventNames.h"
#include "core/dom/ScriptLoader.h"
#include "core/dom/Text.h"
+#include "core/events/Event.h"
+#include "core/events/ThreadLocalEventNames.h"
namespace WebCore {
using namespace HTMLNames;
-inline HTMLScriptElement::HTMLScriptElement(const QualifiedName& tagName, Document& document, bool wasInsertedByParser, bool alreadyStarted)
- : HTMLElement(tagName, document)
+inline HTMLScriptElement::HTMLScriptElement(Document& document, bool wasInsertedByParser, bool alreadyStarted)
+ : HTMLElement(scriptTag, document)
, m_loader(ScriptLoader::create(this, wasInsertedByParser, alreadyStarted))
{
- ASSERT(hasTagName(scriptTag));
ScriptWrappable::init(this);
}
-PassRefPtr<HTMLScriptElement> HTMLScriptElement::create(const QualifiedName& tagName, Document& document, bool wasInsertedByParser, bool alreadyStarted)
+PassRefPtr<HTMLScriptElement> HTMLScriptElement::create(Document& document, bool wasInsertedByParser, bool alreadyStarted)
{
- return adoptRef(new HTMLScriptElement(tagName, document, wasInsertedByParser, alreadyStarted));
+ return adoptRef(new HTMLScriptElement(document, wasInsertedByParser, alreadyStarted));
}
bool HTMLScriptElement::isURLAttribute(const Attribute& attribute) const
@@ -68,7 +67,7 @@ void HTMLScriptElement::parseAttribute(const QualifiedName& name, const AtomicSt
else if (name == asyncAttr)
m_loader->handleAsyncAttribute();
else if (name == onbeforeloadAttr)
- setAttributeEventListener(eventNames().beforeloadEvent, createAttributeEventListener(this, name, value));
+ setAttributeEventListener(EventTypeNames::beforeload, createAttributeEventListener(this, name, value));
else
HTMLElement::parseAttribute(name, value);
}
@@ -168,12 +167,12 @@ bool HTMLScriptElement::hasSourceAttribute() const
void HTMLScriptElement::dispatchLoadEvent()
{
ASSERT(!m_loader->haveFiredLoadEvent());
- dispatchEvent(Event::create(eventNames().loadEvent));
+ dispatchEvent(Event::create(EventTypeNames::load));
}
PassRefPtr<Element> HTMLScriptElement::cloneElementWithoutAttributesAndChildren()
{
- return adoptRef(new HTMLScriptElement(tagQName(), document(), false, m_loader->alreadyStarted()));
+ return adoptRef(new HTMLScriptElement(document(), false, m_loader->alreadyStarted()));
}
}
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLScriptElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLScriptElement.h
index 3340cfdfb00..d4e0efd047e 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLScriptElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLScriptElement.h
@@ -33,7 +33,7 @@ class ScriptLoader;
class HTMLScriptElement FINAL : public HTMLElement, public ScriptLoaderClient {
public:
- static PassRefPtr<HTMLScriptElement> create(const QualifiedName&, Document&, bool wasInsertedByParser, bool alreadyStarted = false);
+ static PassRefPtr<HTMLScriptElement> create(Document&, bool wasInsertedByParser, bool alreadyStarted = false);
String text() { return textFromChildren(); }
void setText(const String&);
@@ -46,7 +46,7 @@ public:
ScriptLoader* loader() const { return m_loader.get(); }
private:
- HTMLScriptElement(const QualifiedName&, Document&, bool wasInsertedByParser, bool alreadyStarted);
+ HTMLScriptElement(Document&, bool wasInsertedByParser, bool alreadyStarted);
virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
@@ -74,11 +74,7 @@ private:
OwnPtr<ScriptLoader> m_loader;
};
-inline HTMLScriptElement* toHTMLScriptElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::scriptTag));
- return static_cast<HTMLScriptElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(HTMLScriptElement, hasTagName(HTMLNames::scriptTag));
} //namespace
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLScriptElement.idl b/chromium/third_party/WebKit/Source/core/html/HTMLScriptElement.idl
index ef68a4dd87c..1f1e260a7f9 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLScriptElement.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLScriptElement.idl
@@ -18,14 +18,14 @@
*/
interface HTMLScriptElement : HTMLElement {
- [TreatNullAs=NullString] attribute DOMString text;
+ attribute DOMString text;
[Reflect=for] attribute DOMString htmlFor;
[Reflect] attribute DOMString event;
[Reflect] attribute DOMString charset;
attribute boolean async;
[Reflect] attribute boolean defer;
- [Reflect, URL] attribute DOMString src;
+ [Reflect, URL, PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute DOMString src;
[Reflect] attribute DOMString type;
[Reflect] attribute DOMString crossOrigin;
- [Reflect, EnabledAtRuntime=ExperimentalContentSecurityPolicyFeatures] attribute DOMString nonce;
+ [Reflect, RuntimeEnabled=ExperimentalContentSecurityPolicyFeatures] attribute DOMString nonce;
};
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLSelectElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLSelectElement.cpp
index 653ddae3f32..8d8332a3e86 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLSelectElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLSelectElement.cpp
@@ -29,30 +29,29 @@
#include "core/html/HTMLSelectElement.h"
#include "HTMLNames.h"
+#include "bindings/v8/ExceptionMessages.h"
#include "bindings/v8/ExceptionState.h"
#include "bindings/v8/ExceptionStatePlaceholder.h"
#include "core/accessibility/AXObjectCache.h"
#include "core/dom/Attribute.h"
#include "core/dom/ElementTraversal.h"
-#include "core/dom/EventNames.h"
-#include "core/dom/KeyboardEvent.h"
-#include "core/dom/MouseEvent.h"
#include "core/dom/NodeTraversal.h"
+#include "core/events/KeyboardEvent.h"
+#include "core/events/MouseEvent.h"
+#include "core/events/ThreadLocalEventNames.h"
#include "core/html/FormDataList.h"
#include "core/html/HTMLFormElement.h"
#include "core/html/HTMLOptGroupElement.h"
#include "core/html/HTMLOptionElement.h"
-#include "core/html/HTMLOptionsCollection.h"
#include "core/html/forms/FormController.h"
#include "core/page/EventHandler.h"
-#include "core/page/Frame.h"
-#include "core/page/Page.h"
+#include "core/frame/Frame.h"
#include "core/page/SpatialNavigation.h"
-#include "core/platform/LocalizedStrings.h"
-#include "core/platform/PlatformMouseEvent.h"
#include "core/rendering/RenderListBox.h"
#include "core/rendering/RenderMenuList.h"
#include "core/rendering/RenderTheme.h"
+#include "platform/PlatformMouseEvent.h"
+#include "platform/text/PlatformLocale.h"
using namespace std;
using namespace WTF::Unicode;
@@ -64,8 +63,8 @@ using namespace HTMLNames;
// Upper limit agreed upon with representatives of Opera and Mozilla.
static const unsigned maxSelectItems = 10000;
-HTMLSelectElement::HTMLSelectElement(const QualifiedName& tagName, Document& document, HTMLFormElement* form, bool createdByParser)
- : HTMLFormControlElementWithState(tagName, document, form)
+HTMLSelectElement::HTMLSelectElement(Document& document, HTMLFormElement* form, bool createdByParser)
+ : HTMLFormControlElementWithState(selectTag, document, form)
, m_typeAhead(this)
, m_size(0)
, m_lastOnChangeIndex(-1)
@@ -77,19 +76,17 @@ HTMLSelectElement::HTMLSelectElement(const QualifiedName& tagName, Document& doc
, m_shouldRecalcListItems(false)
, m_isParsingInProgress(createdByParser)
{
- ASSERT(hasTagName(selectTag));
ScriptWrappable::init(this);
}
PassRefPtr<HTMLSelectElement> HTMLSelectElement::create(Document& document)
{
- return adoptRef(new HTMLSelectElement(selectTag, document, 0, false));
+ return adoptRef(new HTMLSelectElement(document, 0, false));
}
-PassRefPtr<HTMLSelectElement> HTMLSelectElement::create(const QualifiedName& tagName, Document& document, HTMLFormElement* form, bool createdByParser)
+PassRefPtr<HTMLSelectElement> HTMLSelectElement::create(Document& document, HTMLFormElement* form, bool createdByParser)
{
- ASSERT(tagName.matches(selectTag));
- return adoptRef(new HTMLSelectElement(tagName, document, form, createdByParser));
+ return adoptRef(new HTMLSelectElement(document, form, createdByParser));
}
const AtomicString& HTMLSelectElement::formControlType() const
@@ -154,11 +151,11 @@ String HTMLSelectElement::validationMessage() const
{
if (!willValidate())
return String();
-
if (customError())
return customValidationMessage();
-
- return valueMissing() ? validationMessageValueMissingForSelectText() : String();
+ if (valueMissing())
+ return locale().queryString(blink::WebLocalizedString::ValidationValueMissingForSelect);
+ return String();
}
bool HTMLSelectElement::valueMissing() const
@@ -209,7 +206,7 @@ int HTMLSelectElement::activeSelectionEndListIndex() const
return lastSelectedListIndex();
}
-void HTMLSelectElement::add(HTMLElement* element, HTMLElement* before, ExceptionState& es)
+void HTMLSelectElement::add(HTMLElement* element, HTMLElement* before, ExceptionState& exceptionState)
{
// Make sure the element is ref'd and deref'd so we don't leak it.
RefPtr<HTMLElement> protectNewChild(element);
@@ -217,7 +214,7 @@ void HTMLSelectElement::add(HTMLElement* element, HTMLElement* before, Exception
if (!element || !(element->hasLocalName(optionTag) || element->hasLocalName(hrTag)))
return;
- insertBefore(element, before, es);
+ insertBefore(element, before, exceptionState);
setNeedsValidityCheck();
}
@@ -290,7 +287,7 @@ void HTMLSelectElement::parseAttribute(const QualifiedName& name, const AtomicSt
// Set the attribute value to a number.
// This is important since the style rules for this attribute can determine the appearance property.
int size = value.toInt();
- String attrSize = String::number(size);
+ AtomicString attrSize = AtomicString::number(size);
if (attrSize != value) {
// FIXME: This is horribly factored.
if (Attribute* sizeAttribute = ensureUniqueElementData()->getAttributeItem(sizeAttr))
@@ -304,8 +301,8 @@ void HTMLSelectElement::parseAttribute(const QualifiedName& name, const AtomicSt
m_size = size;
setNeedsValidityCheck();
- if (m_size != oldSize && attached()) {
- lazyReattach();
+ if (m_size != oldSize && inActiveDocument()) {
+ lazyReattachIfAttached();
setRecalcListItems();
}
} else if (name == multipleAttr)
@@ -392,7 +389,7 @@ void HTMLSelectElement::setMultiple(bool multiple)
{
bool oldMultiple = this->multiple();
int oldSelectedIndex = selectedIndex();
- setAttribute(multipleAttr, multiple ? "" : 0);
+ setAttribute(multipleAttr, multiple ? emptyAtom : nullAtom);
// Restore selectedIndex after changing the multiple flag to preserve
// selection as single-line and multi-line has different defaults.
@@ -402,7 +399,7 @@ void HTMLSelectElement::setMultiple(bool multiple)
void HTMLSelectElement::setSize(int size)
{
- setAttribute(sizeAttr, String::number(size));
+ setIntegralAttribute(sizeAttr, size);
}
Node* HTMLSelectElement::namedItem(const AtomicString& name)
@@ -415,7 +412,7 @@ Node* HTMLSelectElement::item(unsigned index)
return options()->item(index);
}
-void HTMLSelectElement::setOption(unsigned index, HTMLOptionElement* option, ExceptionState& es)
+void HTMLSelectElement::setOption(unsigned index, HTMLOptionElement* option, ExceptionState& exceptionState)
{
if (index > maxSelectItems - 1)
index = maxSelectItems - 1;
@@ -423,21 +420,21 @@ void HTMLSelectElement::setOption(unsigned index, HTMLOptionElement* option, Exc
RefPtr<HTMLElement> before = 0;
// Out of array bounds? First insert empty dummies.
if (diff > 0) {
- setLength(index, es);
+ setLength(index, exceptionState);
// Replace an existing entry?
} else if (diff < 0) {
before = toHTMLElement(options()->item(index+1));
remove(index);
}
// Finally add the new element.
- if (!es.hadException()) {
- add(option, before.get(), es);
+ if (!exceptionState.hadException()) {
+ add(option, before.get(), exceptionState);
if (diff >= 0 && option->selected())
optionSelectionStateChanged(option, true);
}
}
-void HTMLSelectElement::setLength(unsigned newLen, ExceptionState& es)
+void HTMLSelectElement::setLength(unsigned newLen, ExceptionState& exceptionState)
{
if (newLen > maxSelectItems)
newLen = maxSelectItems;
@@ -447,8 +444,8 @@ void HTMLSelectElement::setLength(unsigned newLen, ExceptionState& es)
do {
RefPtr<Element> option = document().createElement(optionTag, false);
ASSERT(option);
- add(toHTMLElement(option.get()), 0, es);
- if (es.hadException())
+ add(toHTMLElement(option), 0, exceptionState);
+ if (exceptionState.hadException())
break;
} while (++diff);
} else {
@@ -469,7 +466,7 @@ void HTMLSelectElement::setLength(unsigned newLen, ExceptionState& es)
for (size_t i = 0; i < itemsToRemove.size(); ++i) {
Element* item = itemsToRemove[i].get();
if (item->parentNode())
- item->parentNode()->removeChild(item, es);
+ item->parentNode()->removeChild(item, exceptionState);
}
}
setNeedsValidityCheck();
@@ -707,6 +704,9 @@ void HTMLSelectElement::invalidateSelectedItems()
void HTMLSelectElement::setRecalcListItems()
{
+ // FIXME: This function does a bunch of confusing things depending on if it
+ // is in the document or not.
+
m_shouldRecalcListItems = true;
// Manual selection anchor is reset when manipulating the select programmatically.
m_activeSelectionAnchorIndex = -1;
@@ -733,44 +733,44 @@ void HTMLSelectElement::recalcListItems(bool updateSelectedStates) const
HTMLOptionElement* foundSelected = 0;
HTMLOptionElement* firstOption = 0;
- for (Element* currentElement = ElementTraversal::firstWithin(this); currentElement; ) {
+ for (Element* currentElement = ElementTraversal::firstWithin(*this); currentElement; ) {
if (!currentElement->isHTMLElement()) {
- currentElement = ElementTraversal::nextSkippingChildren(currentElement, this);
+ currentElement = ElementTraversal::nextSkippingChildren(*currentElement, this);
continue;
}
- HTMLElement* current = toHTMLElement(currentElement);
+ HTMLElement& current = toHTMLElement(*currentElement);
// optgroup tags may not nest. However, both FireFox and IE will
// flatten the tree automatically, so we follow suit.
// (http://www.w3.org/TR/html401/interact/forms.html#h-17.6)
if (isHTMLOptGroupElement(current)) {
- m_listItems.append(current);
+ m_listItems.append(&current);
if (Element* nextElement = ElementTraversal::firstWithin(current)) {
currentElement = nextElement;
continue;
}
}
- if (current->hasTagName(optionTag)) {
- m_listItems.append(current);
+ if (current.hasTagName(optionTag)) {
+ m_listItems.append(&current);
if (updateSelectedStates && !m_multiple) {
- HTMLOptionElement* option = toHTMLOptionElement(current);
+ HTMLOptionElement& option = toHTMLOptionElement(current);
if (!firstOption)
- firstOption = option;
- if (option->selected()) {
+ firstOption = &option;
+ if (option.selected()) {
if (foundSelected)
foundSelected->setSelectedState(false);
- foundSelected = option;
- } else if (m_size <= 1 && !foundSelected && !option->isDisabledFormControl()) {
- foundSelected = option;
+ foundSelected = &option;
+ } else if (m_size <= 1 && !foundSelected && !option.isDisabledFormControl()) {
+ foundSelected = &option;
foundSelected->setSelectedState(true);
}
}
}
- if (current->hasTagName(hrTag))
- m_listItems.append(current);
+ if (current.hasTagName(hrTag))
+ m_listItems.append(&current);
// In conforming HTML code, only <optgroup> and <option> will be found
// within a <select>. We call NodeTraversal::nextSkippingChildren so that we only step
@@ -778,7 +778,7 @@ void HTMLSelectElement::recalcListItems(bool updateSelectedStates) const
// with the case where odd tags like a <div> have been added but we
// handle this because such tags have already been removed from the
// <select>'s subtree at this point.
- currentElement = ElementTraversal::nextSkippingChildren(currentElement, this);
+ currentElement = ElementTraversal::nextSkippingChildren(*currentElement, this);
}
if (!foundSelected && m_size <= 1 && firstOption && !firstOption->selected())
@@ -813,7 +813,7 @@ void HTMLSelectElement::optionSelectionStateChanged(HTMLOptionElement* option, b
ASSERT(option->ownerSelectElement() == this);
if (optionIsSelected)
selectOption(option->index());
- else if (!usesMenuList())
+ else if (!usesMenuList() || multiple())
selectOption(-1);
else
selectOption(nextSelectableListIndex(-1));
@@ -1027,7 +1027,7 @@ bool HTMLSelectElement::appendFormData(FormDataList& list, bool)
return successful;
}
-void HTMLSelectElement::reset()
+void HTMLSelectElement::resetImpl()
{
HTMLOptionElement* firstOption = 0;
HTMLOptionElement* selectedOption = 0;
@@ -1093,7 +1093,7 @@ void HTMLSelectElement::menuListDefaultEventHandler(Event* event)
{
RenderTheme& renderTheme = RenderTheme::theme();
- if (event->type() == eventNames().keydownEvent) {
+ if (event->type() == EventTypeNames::keydown) {
if (!renderer() || !event->isKeyboardEvent())
return;
@@ -1137,7 +1137,7 @@ void HTMLSelectElement::menuListDefaultEventHandler(Event* event)
// Use key press event here since sending simulated mouse events
// on key down blocks the proper sending of the key press event.
- if (event->type() == eventNames().keypressEvent) {
+ if (event->type() == EventTypeNames::keypress) {
if (!renderer() || !event->isKeyboardEvent())
return;
@@ -1198,7 +1198,7 @@ void HTMLSelectElement::menuListDefaultEventHandler(Event* event)
event->setDefaultHandled();
}
- if (event->type() == eventNames().mousedownEvent && event->isMouseEvent() && toMouseEvent(event)->button() == LeftButton) {
+ if (event->type() == EventTypeNames::mousedown && event->isMouseEvent() && toMouseEvent(event)->button() == LeftButton) {
focus();
if (renderer() && renderer()->isMenuList()) {
if (RenderMenuList* menuList = toRenderMenuList(renderer())) {
@@ -1218,7 +1218,7 @@ void HTMLSelectElement::menuListDefaultEventHandler(Event* event)
event->setDefaultHandled();
}
- if (event->type() == eventNames().blurEvent) {
+ if (event->type() == EventTypeNames::blur) {
if (RenderMenuList* menuList = toRenderMenuList(renderer())) {
if (menuList->popupIsVisible())
menuList->hidePopup();
@@ -1279,7 +1279,7 @@ void HTMLSelectElement::listBoxDefaultEventHandler(Event* event)
{
const Vector<HTMLElement*>& listItems = this->listItems();
- if (event->type() == eventNames().mousedownEvent && event->isMouseEvent() && toMouseEvent(event)->button() == LeftButton) {
+ if (event->type() == EventTypeNames::mousedown && event->isMouseEvent() && toMouseEvent(event)->button() == LeftButton) {
focus();
// Calling focus() may cause us to lose our renderer, in which case do not want to handle the event.
if (!renderer())
@@ -1298,11 +1298,11 @@ void HTMLSelectElement::listBoxDefaultEventHandler(Event* event)
#endif
}
if (Frame* frame = document().frame())
- frame->eventHandler()->setMouseDownMayStartAutoscroll();
+ frame->eventHandler().setMouseDownMayStartAutoscroll();
event->setDefaultHandled();
}
- } else if (event->type() == eventNames().mousemoveEvent && event->isMouseEvent() && !toRenderBox(renderer())->canBeScrolledAndHasScrollableArea()) {
+ } else if (event->type() == EventTypeNames::mousemove && event->isMouseEvent() && !toRenderBox(renderer())->canBeScrolledAndHasScrollableArea()) {
MouseEvent* mouseEvent = toMouseEvent(event);
if (mouseEvent->button() != LeftButton || !mouseEvent->buttonDown())
return;
@@ -1326,7 +1326,7 @@ void HTMLSelectElement::listBoxDefaultEventHandler(Event* event)
}
event->setDefaultHandled();
}
- } else if (event->type() == eventNames().mouseupEvent && event->isMouseEvent() && toMouseEvent(event)->button() == LeftButton && renderer() && !toRenderBox(renderer())->autoscrollInProgress()) {
+ } else if (event->type() == EventTypeNames::mouseup && event->isMouseEvent() && toMouseEvent(event)->button() == LeftButton && renderer() && !toRenderBox(renderer())->autoscrollInProgress()) {
// We didn't start this click/drag on any options.
if (m_lastOnChangeSelection.isEmpty())
return;
@@ -1334,7 +1334,7 @@ void HTMLSelectElement::listBoxDefaultEventHandler(Event* event)
// click. For drag selection, onChange will fire when the autoscroll
// timer stops.
listBoxOnChange();
- } else if (event->type() == eventNames().keydownEvent) {
+ } else if (event->type() == EventTypeNames::keydown) {
if (!event->isKeyboardEvent())
return;
const String& keyIdentifier = toKeyboardEvent(event)->keyIdentifier();
@@ -1417,7 +1417,7 @@ void HTMLSelectElement::listBoxDefaultEventHandler(Event* event)
event->setDefaultHandled();
}
- } else if (event->type() == eventNames().keypressEvent) {
+ } else if (event->type() == EventTypeNames::keypress) {
if (!event->isKeyboardEvent())
return;
int keyCode = toKeyboardEvent(event)->keyCode();
@@ -1453,7 +1453,7 @@ void HTMLSelectElement::defaultEventHandler(Event* event)
if (event->defaultHandled())
return;
- if (event->type() == eventNames().keypressEvent && event->isKeyboardEvent()) {
+ if (event->type() == EventTypeNames::keypress && event->isKeyboardEvent()) {
KeyboardEvent* keyboardEvent = toKeyboardEvent(event);
if (!keyboardEvent->ctrlKey() && !keyboardEvent->altKey() && !keyboardEvent->metaKey() && isPrintableChar(keyboardEvent->charCode())) {
typeAheadFind(keyboardEvent);
@@ -1562,17 +1562,17 @@ void HTMLSelectElement::finishParsingChildren()
updateListItemSelectedStates();
}
-bool HTMLSelectElement::anonymousIndexedSetter(unsigned index, PassRefPtr<HTMLOptionElement> value, ExceptionState& es)
+bool HTMLSelectElement::anonymousIndexedSetter(unsigned index, PassRefPtr<HTMLOptionElement> value, ExceptionState& exceptionState)
{
if (!value) {
- es.throwDOMException(TypeMismatchError);
+ exceptionState.throwTypeError(ExceptionMessages::failedToSet(String::number(index), "HTMLSelectElement", "The value provided was not an HTMLOptionElement."));
return false;
}
- setOption(index, value.get(), es);
+ setOption(index, value.get(), exceptionState);
return true;
}
-bool HTMLSelectElement::anonymousIndexedSetterRemove(unsigned index, ExceptionState& es)
+bool HTMLSelectElement::anonymousIndexedSetterRemove(unsigned index, ExceptionState& exceptionState)
{
remove(index);
return true;
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLSelectElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLSelectElement.h
index 7be5dc487f9..7564360b5cc 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLSelectElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLSelectElement.h
@@ -26,7 +26,7 @@
#ifndef HTMLSelectElement_h
#define HTMLSelectElement_h
-#include "core/dom/Event.h"
+#include "core/events/Event.h"
#include "core/html/HTMLFormControlElementWithState.h"
#include "core/html/HTMLOptionsCollection.h"
#include "core/html/forms/TypeAhead.h"
@@ -40,7 +40,7 @@ class HTMLOptionElement;
class HTMLSelectElement FINAL : public HTMLFormControlElementWithState, public TypeAheadDataSource {
public:
static PassRefPtr<HTMLSelectElement> create(Document&);
- static PassRefPtr<HTMLSelectElement> create(const QualifiedName&, Document&, HTMLFormElement*, bool createdByParser);
+ static PassRefPtr<HTMLSelectElement> create(Document&, HTMLFormElement*, bool createdByParser);
int selectedIndex() const;
void setSelectedIndex(int);
@@ -51,7 +51,7 @@ public:
virtual String validationMessage() const OVERRIDE;
virtual bool valueMissing() const OVERRIDE;
- virtual void reset() OVERRIDE;
+ virtual void resetImpl() OVERRIDE;
unsigned length() const;
@@ -115,7 +115,7 @@ public:
bool anonymousIndexedSetterRemove(unsigned, ExceptionState&);
protected:
- HTMLSelectElement(const QualifiedName&, Document&, HTMLFormElement*, bool createdByParser);
+ HTMLSelectElement(Document&, HTMLFormElement*, bool createdByParser);
private:
virtual const AtomicString& formControlType() const;
@@ -211,13 +211,7 @@ private:
bool m_isParsingInProgress;
};
-inline HTMLSelectElement* toHTMLSelectElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::selectTag));
- return static_cast<HTMLSelectElement*>(node);
-}
-
-void toHTMLSelectElement(const HTMLSelectElement*); // This overload will catch anyone doing an unnecessary cast.
+DEFINE_NODE_TYPE_CASTS(HTMLSelectElement, hasTagName(HTMLNames::selectTag));
} // namespace
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLSelectElement.idl b/chromium/third_party/WebKit/Source/core/html/HTMLSelectElement.idl
index 8c92af58db4..b61f5128247 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLSelectElement.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLSelectElement.idl
@@ -22,7 +22,7 @@
interface HTMLSelectElement : HTMLElement {
[Reflect] attribute boolean autofocus;
[Reflect] attribute boolean disabled;
- readonly attribute HTMLFormElement form;
+ [ImplementedAs=formOwner] readonly attribute HTMLFormElement form;
attribute boolean multiple;
[Reflect] attribute DOMString name;
[Reflect] attribute boolean required;
@@ -31,7 +31,7 @@ interface HTMLSelectElement : HTMLElement {
readonly attribute DOMString type;
readonly attribute HTMLOptionsCollection options;
- [SetterRaisesException] attribute unsigned long length;
+ [RaisesException=Setter] attribute unsigned long length;
getter Node item(unsigned long index);
[ImplementedAs=anonymousIndexedSetter, RaisesException] setter HTMLOptionElement (unsigned long index, [TreatNullAs=anonymousIndexedSetterRemove, TreatUndefinedAs=anonymousIndexedSetterRemove] HTMLOptionElement value);
@@ -43,7 +43,7 @@ interface HTMLSelectElement : HTMLElement {
[RaisesException] void remove();
readonly attribute HTMLCollection selectedOptions;
attribute long selectedIndex;
- [TreatNullAs=NullString] attribute DOMString value;
+ attribute DOMString value;
readonly attribute boolean willValidate;
readonly attribute ValidityState validity;
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLSelectElementWin.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLSelectElementWin.cpp
index 1c4be11df6e..b6119504b49 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLSelectElementWin.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLSelectElementWin.cpp
@@ -29,7 +29,7 @@
#if OS(WIN)
#include "core/dom/Element.h"
-#include "core/dom/KeyboardEvent.h"
+#include "core/events/KeyboardEvent.h"
#include "core/rendering/RenderMenuList.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLShadowElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLShadowElement.h
new file mode 100644
index 00000000000..70833399beb
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLShadowElement.h
@@ -0,0 +1,2 @@
+// FIXME: Move HTMLShadowElement.h here.
+#include "core/html/shadow/HTMLShadowElement.h"
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLSourceElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLSourceElement.cpp
index 733ac998770..75daceb07a4 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLSourceElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLSourceElement.cpp
@@ -27,10 +27,10 @@
#include "core/html/HTMLSourceElement.h"
#include "HTMLNames.h"
-#include "core/dom/Event.h"
-#include "core/dom/EventNames.h"
+#include "core/events/Event.h"
+#include "core/events/ThreadLocalEventNames.h"
#include "core/html/HTMLMediaElement.h"
-#include "core/platform/Logging.h"
+#include "platform/Logging.h"
using namespace std;
@@ -38,18 +38,17 @@ namespace WebCore {
using namespace HTMLNames;
-inline HTMLSourceElement::HTMLSourceElement(const QualifiedName& tagName, Document& document)
- : HTMLElement(tagName, document)
+inline HTMLSourceElement::HTMLSourceElement(Document& document)
+ : HTMLElement(sourceTag, document)
, m_errorEventTimer(this, &HTMLSourceElement::errorEventTimerFired)
{
- LOG(Media, "HTMLSourceElement::HTMLSourceElement - %p", this);
- ASSERT(hasTagName(sourceTag));
+ WTF_LOG(Media, "HTMLSourceElement::HTMLSourceElement - %p", this);
ScriptWrappable::init(this);
}
-PassRefPtr<HTMLSourceElement> HTMLSourceElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<HTMLSourceElement> HTMLSourceElement::create(Document& document)
{
- return adoptRef(new HTMLSourceElement(tagName, document));
+ return adoptRef(new HTMLSourceElement(document));
}
Node::InsertionNotificationRequest HTMLSourceElement::insertedInto(ContainerNode* insertionPoint)
@@ -73,32 +72,32 @@ void HTMLSourceElement::removedFrom(ContainerNode* removalRoot)
void HTMLSourceElement::setSrc(const String& url)
{
- setAttribute(srcAttr, url);
+ setAttribute(srcAttr, AtomicString(url));
}
-String HTMLSourceElement::media() const
+const AtomicString& HTMLSourceElement::media() const
{
return getAttribute(mediaAttr);
}
-void HTMLSourceElement::setMedia(const String& media)
+void HTMLSourceElement::setMedia(const AtomicString& media)
{
setAttribute(mediaAttr, media);
}
-String HTMLSourceElement::type() const
+const AtomicString& HTMLSourceElement::type() const
{
return getAttribute(typeAttr);
}
-void HTMLSourceElement::setType(const String& type)
+void HTMLSourceElement::setType(const AtomicString& type)
{
setAttribute(typeAttr, type);
}
void HTMLSourceElement::scheduleErrorEvent()
{
- LOG(Media, "HTMLSourceElement::scheduleErrorEvent - %p", this);
+ WTF_LOG(Media, "HTMLSourceElement::scheduleErrorEvent - %p", this);
if (m_errorEventTimer.isActive())
return;
@@ -107,14 +106,14 @@ void HTMLSourceElement::scheduleErrorEvent()
void HTMLSourceElement::cancelPendingErrorEvent()
{
- LOG(Media, "HTMLSourceElement::cancelPendingErrorEvent - %p", this);
+ WTF_LOG(Media, "HTMLSourceElement::cancelPendingErrorEvent - %p", this);
m_errorEventTimer.stop();
}
void HTMLSourceElement::errorEventTimerFired(Timer<HTMLSourceElement>*)
{
- LOG(Media, "HTMLSourceElement::errorEventTimerFired - %p", this);
- dispatchEvent(Event::createCancelable(eventNames().errorEvent));
+ WTF_LOG(Media, "HTMLSourceElement::errorEventTimerFired - %p", this);
+ dispatchEvent(Event::createCancelable(EventTypeNames::error));
}
bool HTMLSourceElement::isURLAttribute(const Attribute& attribute) const
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLSourceElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLSourceElement.h
index 02378ccf5b9..0002d210706 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLSourceElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLSourceElement.h
@@ -27,26 +27,25 @@
#define HTMLSourceElement_h
#include "core/html/HTMLElement.h"
-#include "core/platform/Timer.h"
+#include "platform/Timer.h"
namespace WebCore {
class HTMLSourceElement FINAL : public HTMLElement {
public:
- static PassRefPtr<HTMLSourceElement> create(Document& document) { return create(HTMLNames::sourceTag, document); }
- static PassRefPtr<HTMLSourceElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<HTMLSourceElement> create(Document&);
- String media() const;
- String type() const;
+ const AtomicString& media() const;
+ const AtomicString& type() const;
void setSrc(const String&);
- void setMedia(const String&);
- void setType(const String&);
+ void setMedia(const AtomicString&);
+ void setType(const AtomicString&);
void scheduleErrorEvent();
void cancelPendingErrorEvent();
private:
- HTMLSourceElement(const QualifiedName&, Document&);
+ explicit HTMLSourceElement(Document&);
virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
virtual void removedFrom(ContainerNode*) OVERRIDE;
@@ -57,11 +56,7 @@ private:
Timer<HTMLSourceElement> m_errorEventTimer;
};
-inline HTMLSourceElement* toHTMLSourceElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::sourceTag));
- return static_cast<HTMLSourceElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(HTMLSourceElement, hasTagName(HTMLNames::sourceTag));
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLSourceElement.idl b/chromium/third_party/WebKit/Source/core/html/HTMLSourceElement.idl
index 5adb052756d..4e10349051e 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLSourceElement.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLSourceElement.idl
@@ -24,9 +24,9 @@
*/
[
- EnabledAtRuntime=Media
+ RuntimeEnabled=Media
] interface HTMLSourceElement : HTMLElement {
-[Reflect, URL] attribute DOMString src;
+ [Reflect, URL, PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute DOMString src;
attribute DOMString type;
attribute DOMString media;
};
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLSpanElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLSpanElement.cpp
index e648e3e02b5..193c659b84d 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLSpanElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLSpanElement.cpp
@@ -32,16 +32,15 @@ namespace WebCore {
using namespace HTMLNames;
-HTMLSpanElement::HTMLSpanElement(const QualifiedName& tagName, Document& document)
- : HTMLElement(tagName, document)
+HTMLSpanElement::HTMLSpanElement(Document& document)
+ : HTMLElement(spanTag, document)
{
- ASSERT(hasTagName(spanTag));
ScriptWrappable::init(this);
}
-PassRefPtr<HTMLSpanElement> HTMLSpanElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<HTMLSpanElement> HTMLSpanElement::create(Document& document)
{
- return adoptRef(new HTMLSpanElement(tagName, document));
+ return adoptRef(new HTMLSpanElement(document));
}
}
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLSpanElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLSpanElement.h
index cf1df976012..ca77b867cfb 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLSpanElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLSpanElement.h
@@ -32,10 +32,10 @@ namespace WebCore {
class HTMLSpanElement : public HTMLElement {
public:
- static PassRefPtr<HTMLSpanElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<HTMLSpanElement> create(Document&);
protected:
- HTMLSpanElement(const QualifiedName&, Document&);
+ explicit HTMLSpanElement(Document&);
};
}
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLStyleElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLStyleElement.cpp
index 259ddc34827..c3d7e1c31aa 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLStyleElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLStyleElement.cpp
@@ -29,8 +29,8 @@
#include "core/css/StyleSheetContents.h"
#include "core/dom/ContextFeatures.h"
#include "core/dom/Document.h"
-#include "core/dom/Event.h"
-#include "core/dom/EventSender.h"
+#include "core/events/Event.h"
+#include "core/events/EventSender.h"
#include "core/dom/StyleEngine.h"
#include "core/dom/shadow/ShadowRoot.h"
@@ -40,18 +40,17 @@ using namespace HTMLNames;
static StyleEventSender& styleLoadEventSender()
{
- DEFINE_STATIC_LOCAL(StyleEventSender, sharedLoadEventSender, (eventNames().loadEvent));
+ DEFINE_STATIC_LOCAL(StyleEventSender, sharedLoadEventSender, (EventTypeNames::load));
return sharedLoadEventSender;
}
-inline HTMLStyleElement::HTMLStyleElement(const QualifiedName& tagName, Document& document, bool createdByParser)
- : HTMLElement(tagName, document)
+inline HTMLStyleElement::HTMLStyleElement(Document& document, bool createdByParser)
+ : HTMLElement(styleTag, document)
, StyleElement(&document, createdByParser)
, m_firedLoad(false)
, m_loadedSheet(false)
, m_scopedStyleRegistrationState(NotRegistered)
{
- ASSERT(hasTagName(styleTag));
ScriptWrappable::init(this);
}
@@ -64,9 +63,9 @@ HTMLStyleElement::~HTMLStyleElement()
styleLoadEventSender().cancelEvent(this);
}
-PassRefPtr<HTMLStyleElement> HTMLStyleElement::create(const QualifiedName& tagName, Document& document, bool createdByParser)
+PassRefPtr<HTMLStyleElement> HTMLStyleElement::create(Document& document, bool createdByParser)
{
- return adoptRef(new HTMLStyleElement(tagName, document, createdByParser));
+ return adoptRef(new HTMLStyleElement(document, createdByParser));
}
void HTMLStyleElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
@@ -75,7 +74,7 @@ void HTMLStyleElement::parseAttribute(const QualifiedName& name, const AtomicStr
m_sheet->setTitle(value);
} else if (name == scopedAttr && ContextFeatures::styleScopedEnabled(&document())) {
scopedAttributeChanged(!value.isNull());
- } else if (name == mediaAttr && inDocument() && document().renderer() && m_sheet) {
+ } else if (name == mediaAttr && inDocument() && document().isActive() && m_sheet) {
m_sheet->setMediaQueries(MediaQuerySet::create(value));
// FIXME: This shold be RecalcStyleDeferred.
document().modifiedStyleSheet(m_sheet.get(), RecalcStyleImmediately);
@@ -115,8 +114,8 @@ void HTMLStyleElement::scopedAttributeChanged(bool scoped)
if (m_scopedStyleRegistrationState != RegisteredAsScoped)
return;
- document().styleEngine()->removeStyleSheetCandidateNode(this, parentNode());
unregisterWithScopingNode(parentNode());
+ document().styleEngine()->removeStyleSheetCandidateNode(this, parentNode());
// As any <style> in a shadow tree is treated as "scoped",
// need to add the <style> to its shadow root.
@@ -124,6 +123,9 @@ void HTMLStyleElement::scopedAttributeChanged(bool scoped)
registerWithScopingNode(false);
document().styleEngine()->addStyleSheetCandidateNode(this, false);
+ // FIXME: currently need to use FullStyleUpdate here.
+ // Because ShadowTreeStyleSheetCollection doesn't know old scoping node.
+ // So setNeedsStyleRecalc for old scoping node is not invoked.
document().modifiedStyleSheet(sheet());
}
@@ -256,7 +258,7 @@ void HTMLStyleElement::dispatchPendingLoadEvents()
void HTMLStyleElement::dispatchPendingEvent(StyleEventSender* eventSender)
{
ASSERT_UNUSED(eventSender, eventSender == &styleLoadEventSender());
- dispatchEvent(Event::create(m_loadedSheet ? eventNames().loadEvent : eventNames().errorEvent));
+ dispatchEvent(Event::create(m_loadedSheet ? EventTypeNames::load : EventTypeNames::error));
}
void HTMLStyleElement::notifyLoadedSheetAndAllCriticalSubresources(bool errorOccurred)
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLStyleElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLStyleElement.h
index 252d4412c1e..3ab95c6c0ee 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLStyleElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLStyleElement.h
@@ -36,7 +36,7 @@ typedef EventSender<HTMLStyleElement> StyleEventSender;
class HTMLStyleElement FINAL : public HTMLElement, private StyleElement {
public:
- static PassRefPtr<HTMLStyleElement> create(const QualifiedName&, Document&, bool createdByParser);
+ static PassRefPtr<HTMLStyleElement> create(Document&, bool createdByParser);
virtual ~HTMLStyleElement();
void setType(const AtomicString&);
@@ -67,7 +67,7 @@ public:
static void dispatchPendingLoadEvents();
private:
- HTMLStyleElement(const QualifiedName&, Document&, bool createdByParser);
+ HTMLStyleElement(Document&, bool createdByParser);
// overload from HTMLElement
virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
@@ -109,11 +109,7 @@ inline bool isHTMLStyleElement(Node* node)
return node->hasTagName(HTMLNames::styleTag);
}
-inline HTMLStyleElement* toHTMLStyleElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::styleTag));
- return static_cast<HTMLStyleElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(HTMLStyleElement, hasTagName(HTMLNames::styleTag));
} //namespace
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLStyleElement.idl b/chromium/third_party/WebKit/Source/core/html/HTMLStyleElement.idl
index a5fd4f35dee..42a38de99d4 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLStyleElement.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLStyleElement.idl
@@ -20,11 +20,10 @@
interface HTMLStyleElement : HTMLElement {
attribute boolean disabled;
- [EnabledAtRuntime=StyleScoped] attribute boolean scoped;
+ [RuntimeEnabled=StyleScoped] attribute boolean scoped;
[Reflect] attribute DOMString media;
[Reflect] attribute DOMString type;
// DOM Level 2 Style
readonly attribute StyleSheet sheet;
};
-
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLSummaryElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLSummaryElement.cpp
index ed09699cfb5..7f13462137e 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLSummaryElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLSummaryElement.cpp
@@ -23,7 +23,7 @@
#include "HTMLNames.h"
#include "bindings/v8/ExceptionStatePlaceholder.h"
-#include "core/dom/KeyboardEvent.h"
+#include "core/events/KeyboardEvent.h"
#include "core/dom/NodeRenderingTraversal.h"
#include "core/dom/shadow/ShadowRoot.h"
#include "core/html/HTMLDetailsElement.h"
@@ -35,17 +35,16 @@ namespace WebCore {
using namespace HTMLNames;
-PassRefPtr<HTMLSummaryElement> HTMLSummaryElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<HTMLSummaryElement> HTMLSummaryElement::create(Document& document)
{
- RefPtr<HTMLSummaryElement> summary = adoptRef(new HTMLSummaryElement(tagName, document));
+ RefPtr<HTMLSummaryElement> summary = adoptRef(new HTMLSummaryElement(document));
summary->ensureUserAgentShadowRoot();
return summary.release();
}
-HTMLSummaryElement::HTMLSummaryElement(const QualifiedName& tagName, Document& document)
- : HTMLElement(tagName, document)
+HTMLSummaryElement::HTMLSummaryElement(Document& document)
+ : HTMLElement(summaryTag, document)
{
- ASSERT(hasTagName(summaryTag));
}
RenderObject* HTMLSummaryElement::createRenderer(RenderStyle*)
@@ -53,10 +52,10 @@ RenderObject* HTMLSummaryElement::createRenderer(RenderStyle*)
return new RenderBlockFlow(this);
}
-void HTMLSummaryElement::didAddUserAgentShadowRoot(ShadowRoot* root)
+void HTMLSummaryElement::didAddUserAgentShadowRoot(ShadowRoot& root)
{
- root->appendChild(DetailsMarkerControl::create(document()));
- root->appendChild(HTMLContentElement::create(document()));
+ root.appendChild(DetailsMarkerControl::create(document()));
+ root.appendChild(HTMLContentElement::create(document()));
}
HTMLDetailsElement* HTMLSummaryElement::detailsElement() const
@@ -94,7 +93,7 @@ bool HTMLSummaryElement::supportsFocus() const
void HTMLSummaryElement::defaultEventHandler(Event* event)
{
if (isMainSummary() && renderer()) {
- if (event->type() == eventNames().DOMActivateEvent && !isClickableControl(event->target()->toNode())) {
+ if (event->type() == EventTypeNames::DOMActivate && !isClickableControl(event->target()->toNode())) {
if (HTMLDetailsElement* details = detailsElement())
details->toggleOpen();
event->setDefaultHandled();
@@ -102,12 +101,12 @@ void HTMLSummaryElement::defaultEventHandler(Event* event)
}
if (event->isKeyboardEvent()) {
- if (event->type() == eventNames().keydownEvent && toKeyboardEvent(event)->keyIdentifier() == "U+0020") {
- setActive(true, true);
+ if (event->type() == EventTypeNames::keydown && toKeyboardEvent(event)->keyIdentifier() == "U+0020") {
+ setActive(true);
// No setDefaultHandled() - IE dispatches a keypress in this case.
return;
}
- if (event->type() == eventNames().keypressEvent) {
+ if (event->type() == EventTypeNames::keypress) {
switch (toKeyboardEvent(event)->charCode()) {
case '\r':
dispatchSimulatedClick(event);
@@ -119,7 +118,7 @@ void HTMLSummaryElement::defaultEventHandler(Event* event)
return;
}
}
- if (event->type() == eventNames().keyupEvent && toKeyboardEvent(event)->keyIdentifier() == "U+0020") {
+ if (event->type() == EventTypeNames::keyup && toKeyboardEvent(event)->keyIdentifier() == "U+0020") {
if (active())
dispatchSimulatedClick(event);
event->setDefaultHandled();
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLSummaryElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLSummaryElement.h
index 01316113eb4..45f14630a86 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLSummaryElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLSummaryElement.h
@@ -29,26 +29,22 @@ class HTMLDetailsElement;
class HTMLSummaryElement FINAL : public HTMLElement {
public:
- static PassRefPtr<HTMLSummaryElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<HTMLSummaryElement> create(Document&);
bool isMainSummary() const;
virtual bool willRespondToMouseClickEvents() OVERRIDE;
private:
- HTMLSummaryElement(const QualifiedName&, Document&);
+ explicit HTMLSummaryElement(Document&);
virtual RenderObject* createRenderer(RenderStyle*);
virtual void defaultEventHandler(Event*);
- virtual void didAddUserAgentShadowRoot(ShadowRoot*) OVERRIDE;
+ virtual void didAddUserAgentShadowRoot(ShadowRoot&) OVERRIDE;
HTMLDetailsElement* detailsElement() const;
bool supportsFocus() const OVERRIDE;
};
-inline HTMLSummaryElement* toHTMLSummaryElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::summaryTag));
- return static_cast<HTMLSummaryElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(HTMLSummaryElement, hasTagName(HTMLNames::summaryTag));
}
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLTableCaptionElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLTableCaptionElement.cpp
index 870d7b43a13..0212e3249e4 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLTableCaptionElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLTableCaptionElement.cpp
@@ -32,16 +32,15 @@ namespace WebCore {
using namespace HTMLNames;
-inline HTMLTableCaptionElement::HTMLTableCaptionElement(const QualifiedName& tagName, Document& document)
- : HTMLElement(tagName, document)
+inline HTMLTableCaptionElement::HTMLTableCaptionElement(Document& document)
+ : HTMLElement(captionTag, document)
{
- ASSERT(hasTagName(captionTag));
ScriptWrappable::init(this);
}
-PassRefPtr<HTMLTableCaptionElement> HTMLTableCaptionElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<HTMLTableCaptionElement> HTMLTableCaptionElement::create(Document& document)
{
- return adoptRef(new HTMLTableCaptionElement(tagName, document));
+ return adoptRef(new HTMLTableCaptionElement(document));
}
bool HTMLTableCaptionElement::isPresentationAttribute(const QualifiedName& name) const
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLTableCaptionElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLTableCaptionElement.h
index ce30265587d..33315acfdb0 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLTableCaptionElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLTableCaptionElement.h
@@ -32,20 +32,16 @@ namespace WebCore {
class HTMLTableCaptionElement FINAL : public HTMLElement {
public:
- static PassRefPtr<HTMLTableCaptionElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<HTMLTableCaptionElement> create(Document&);
private:
- HTMLTableCaptionElement(const QualifiedName&, Document&);
+ HTMLTableCaptionElement(Document&);
virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
virtual void collectStyleForPresentationAttribute(const QualifiedName&, const AtomicString&, MutableStylePropertySet*) OVERRIDE;
};
-inline HTMLTableCaptionElement* toHTMLTableCaptionElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::captionTag));
- return static_cast<HTMLTableCaptionElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(HTMLTableCaptionElement, hasTagName(HTMLNames::captionTag));
} // namespace
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLTableCaptionElement.idl b/chromium/third_party/WebKit/Source/core/html/HTMLTableCaptionElement.idl
index e29f097db7e..cd2025932de 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLTableCaptionElement.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLTableCaptionElement.idl
@@ -21,4 +21,3 @@
interface HTMLTableCaptionElement : HTMLElement {
[Reflect] attribute DOMString align;
};
-
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLTableCellElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLTableCellElement.cpp
index 34f7bada2af..01b712585fc 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLTableCellElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLTableCellElement.cpp
@@ -130,32 +130,32 @@ bool HTMLTableCellElement::isURLAttribute(const Attribute& attribute) const
return attribute.name() == backgroundAttr || HTMLTablePartElement::isURLAttribute(attribute);
}
-String HTMLTableCellElement::abbr() const
+const AtomicString& HTMLTableCellElement::abbr() const
{
return getAttribute(abbrAttr);
}
-String HTMLTableCellElement::axis() const
+const AtomicString& HTMLTableCellElement::axis() const
{
return getAttribute(axisAttr);
}
void HTMLTableCellElement::setColSpan(int n)
{
- setAttribute(colspanAttr, String::number(n));
+ setIntegralAttribute(colspanAttr, n);
}
-String HTMLTableCellElement::headers() const
+const AtomicString& HTMLTableCellElement::headers() const
{
return getAttribute(headersAttr);
}
void HTMLTableCellElement::setRowSpan(int n)
{
- setAttribute(rowspanAttr, String::number(n));
+ setIntegralAttribute(rowspanAttr, n);
}
-String HTMLTableCellElement::scope() const
+const AtomicString& HTMLTableCellElement::scope() const
{
return getAttribute(scopeAttr);
}
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLTableCellElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLTableCellElement.h
index 413ccd92431..8c22cccfb38 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLTableCellElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLTableCellElement.h
@@ -41,12 +41,12 @@ public:
void setCellIndex(int);
- String abbr() const;
- String axis() const;
+ const AtomicString& abbr() const;
+ const AtomicString& axis() const;
void setColSpan(int);
- String headers() const;
+ const AtomicString& headers() const;
void setRowSpan(int);
- String scope() const;
+ const AtomicString& scope() const;
HTMLTableCellElement* cellAbove() const;
@@ -63,20 +63,12 @@ private:
virtual void addSubresourceAttributeURLs(ListHashSet<KURL>&) const;
};
-inline HTMLTableCellElement* toHTMLTableCellElement(Node* node)
+inline bool isHTMLTableCellElement(const Node& node)
{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::tdTag) || node->hasTagName(HTMLNames::thTag));
- return static_cast<HTMLTableCellElement*>(node);
+ return node.hasTagName(HTMLNames::tdTag) || node.hasTagName(HTMLNames::thTag);
}
-inline const HTMLTableCellElement* toHTMLTableCellElement(const Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::tdTag) || node->hasTagName(HTMLNames::thTag));
- return static_cast<const HTMLTableCellElement*>(node);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toHTMLTableCellElement(const HTMLTableCellElement*);
+DEFINE_NODE_TYPE_CASTS_WITH_FUNCTION(HTMLTableCellElement);
} // namespace
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLTableCellElement.idl b/chromium/third_party/WebKit/Source/core/html/HTMLTableCellElement.idl
index 3b949f3904d..8f823e4ac7f 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLTableCellElement.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLTableCellElement.idl
@@ -23,11 +23,11 @@ interface HTMLTableCellElement : HTMLElement {
[Reflect] attribute DOMString abbr;
[Reflect] attribute DOMString align;
[Reflect] attribute DOMString axis;
- [Reflect] attribute DOMString bgColor;
+ [Reflect, TreatNullAs=NullString] attribute DOMString bgColor;
[Reflect=char] attribute DOMString ch;
[Reflect=charoff] attribute DOMString chOff;
attribute long colSpan;
- [Reflect] attribute DOMString headers;
+ [Reflect, TreatNullAs=NullString] attribute DOMString headers;
[Reflect] attribute DOMString height;
[Reflect] attribute boolean noWrap;
attribute long rowSpan;
@@ -35,4 +35,3 @@ interface HTMLTableCellElement : HTMLElement {
[Reflect] attribute DOMString vAlign;
[Reflect] attribute DOMString width;
};
-
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLTableColElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLTableColElement.cpp
index bf46d4d9bb7..19e301d95c0 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLTableColElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLTableColElement.cpp
@@ -91,10 +91,10 @@ const StylePropertySet* HTMLTableColElement::additionalPresentationAttributeStyl
void HTMLTableColElement::setSpan(int n)
{
- setAttribute(spanAttr, String::number(n));
+ setIntegralAttribute(spanAttr, n);
}
-String HTMLTableColElement::width() const
+const AtomicString& HTMLTableColElement::width() const
{
return getAttribute(widthAttr);
}
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLTableColElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLTableColElement.h
index 635c661761e..ecd3f73f241 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLTableColElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLTableColElement.h
@@ -37,7 +37,7 @@ public:
int span() const { return m_span; }
void setSpan(int);
- String width() const;
+ const AtomicString& width() const;
private:
HTMLTableColElement(const QualifiedName& tagName, Document&);
@@ -50,12 +50,13 @@ private:
int m_span;
};
-inline HTMLTableColElement* toHTMLTableColElement(Node* node)
+inline bool isHTMLTableColElement(const Node& node)
{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::colTag) || node->hasTagName(HTMLNames::colgroupTag));
- return static_cast<HTMLTableColElement*>(node);
+ return node.hasTagName(HTMLNames::colTag) || node.hasTagName(HTMLNames::colgroupTag);
}
+DEFINE_NODE_TYPE_CASTS_WITH_FUNCTION(HTMLTableColElement);
+
} // namespace WebCore
#endif
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLTableColElement.idl b/chromium/third_party/WebKit/Source/core/html/HTMLTableColElement.idl
index 725e05dec7a..577b7e55fa0 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLTableColElement.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLTableColElement.idl
@@ -26,4 +26,3 @@ interface HTMLTableColElement : HTMLElement {
[Reflect] attribute DOMString vAlign;
[Reflect] attribute DOMString width;
};
-
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLTableElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLTableElement.cpp
index 54cca884bb5..c963c1f65a0 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLTableElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLTableElement.cpp
@@ -41,31 +41,26 @@
#include "core/html/HTMLTableSectionElement.h"
#include "core/html/parser/HTMLParserIdioms.h"
#include "core/rendering/RenderTable.h"
+#include "wtf/StdLibExtras.h"
namespace WebCore {
using namespace HTMLNames;
-HTMLTableElement::HTMLTableElement(const QualifiedName& tagName, Document& document)
- : HTMLElement(tagName, document)
+HTMLTableElement::HTMLTableElement(Document& document)
+ : HTMLElement(tableTag, document)
, m_borderAttr(false)
, m_borderColorAttr(false)
, m_frameAttr(false)
, m_rulesAttr(UnsetRules)
, m_padding(1)
{
- ASSERT(hasTagName(tableTag));
ScriptWrappable::init(this);
}
PassRefPtr<HTMLTableElement> HTMLTableElement::create(Document& document)
{
- return adoptRef(new HTMLTableElement(tableTag, document));
-}
-
-PassRefPtr<HTMLTableElement> HTMLTableElement::create(const QualifiedName& tagName, Document& document)
-{
- return adoptRef(new HTMLTableElement(tagName, document));
+ return adoptRef(new HTMLTableElement(document));
}
HTMLTableCaptionElement* HTMLTableElement::caption() const
@@ -77,10 +72,10 @@ HTMLTableCaptionElement* HTMLTableElement::caption() const
return 0;
}
-void HTMLTableElement::setCaption(PassRefPtr<HTMLTableCaptionElement> newCaption, ExceptionState& es)
+void HTMLTableElement::setCaption(PassRefPtr<HTMLTableCaptionElement> newCaption, ExceptionState& exceptionState)
{
deleteCaption();
- insertBefore(newCaption, firstChild(), es);
+ insertBefore(newCaption, firstChild(), exceptionState);
}
HTMLTableSectionElement* HTMLTableElement::tHead() const
@@ -92,7 +87,7 @@ HTMLTableSectionElement* HTMLTableElement::tHead() const
return 0;
}
-void HTMLTableElement::setTHead(PassRefPtr<HTMLTableSectionElement> newHead, ExceptionState& es)
+void HTMLTableElement::setTHead(PassRefPtr<HTMLTableSectionElement> newHead, ExceptionState& exceptionState)
{
deleteTHead();
@@ -101,7 +96,7 @@ void HTMLTableElement::setTHead(PassRefPtr<HTMLTableSectionElement> newHead, Exc
if (child->isElementNode() && !child->hasTagName(captionTag) && !child->hasTagName(colgroupTag))
break;
- insertBefore(newHead, child, es);
+ insertBefore(newHead, child, exceptionState);
}
HTMLTableSectionElement* HTMLTableElement::tFoot() const
@@ -113,7 +108,7 @@ HTMLTableSectionElement* HTMLTableElement::tFoot() const
return 0;
}
-void HTMLTableElement::setTFoot(PassRefPtr<HTMLTableSectionElement> newFoot, ExceptionState& es)
+void HTMLTableElement::setTFoot(PassRefPtr<HTMLTableSectionElement> newFoot, ExceptionState& exceptionState)
{
deleteTFoot();
@@ -122,7 +117,7 @@ void HTMLTableElement::setTFoot(PassRefPtr<HTMLTableSectionElement> newFoot, Exc
if (child->isElementNode() && !child->hasTagName(captionTag) && !child->hasTagName(colgroupTag) && !child->hasTagName(theadTag))
break;
- insertBefore(newFoot, child, es);
+ insertBefore(newFoot, child, exceptionState);
}
PassRefPtr<HTMLElement> HTMLTableElement::createTHead()
@@ -166,7 +161,7 @@ PassRefPtr<HTMLElement> HTMLTableElement::createCaption()
{
if (HTMLTableCaptionElement* existingCaption = caption())
return existingCaption;
- RefPtr<HTMLTableCaptionElement> caption = HTMLTableCaptionElement::create(captionTag, document());
+ RefPtr<HTMLTableCaptionElement> caption = HTMLTableCaptionElement::create(document());
setCaption(caption, IGNORE_EXCEPTION);
return caption.release();
}
@@ -185,10 +180,10 @@ HTMLTableSectionElement* HTMLTableElement::lastBody() const
return 0;
}
-PassRefPtr<HTMLElement> HTMLTableElement::insertRow(int index, ExceptionState& es)
+PassRefPtr<HTMLElement> HTMLTableElement::insertRow(int index, ExceptionState& exceptionState)
{
if (index < -1) {
- es.throwDOMException(IndexSizeError);
+ exceptionState.throwDOMException(IndexSizeError, "The index provided (" + String::number(index) + ") is less than -1.");
return 0;
}
@@ -203,7 +198,7 @@ PassRefPtr<HTMLElement> HTMLTableElement::insertRow(int index, ExceptionState& e
row = HTMLTableRowsCollection::rowAfter(this, lastRow.get());
if (!row) {
if (i != index) {
- es.throwDOMException(IndexSizeError);
+ exceptionState.throwDOMException(IndexSizeError, "The index provided (" + String::number(index) + ") is greater than the number of rows in the table (" + String::number(i) + ").");
return 0;
}
break;
@@ -220,34 +215,40 @@ PassRefPtr<HTMLElement> HTMLTableElement::insertRow(int index, ExceptionState& e
if (!parent) {
RefPtr<HTMLTableSectionElement> newBody = HTMLTableSectionElement::create(tbodyTag, document());
RefPtr<HTMLTableRowElement> newRow = HTMLTableRowElement::create(document());
- newBody->appendChild(newRow, es);
- appendChild(newBody.release(), es);
+ newBody->appendChild(newRow, exceptionState);
+ appendChild(newBody.release(), exceptionState);
return newRow.release();
}
}
RefPtr<HTMLTableRowElement> newRow = HTMLTableRowElement::create(document());
- parent->insertBefore(newRow, row.get(), es);
+ parent->insertBefore(newRow, row.get(), exceptionState);
return newRow.release();
}
-void HTMLTableElement::deleteRow(int index, ExceptionState& es)
+void HTMLTableElement::deleteRow(int index, ExceptionState& exceptionState)
{
+ if (index < -1) {
+ exceptionState.throwDOMException(IndexSizeError, "The index provided (" + String::number(index) + ") is less than -1.");
+ return;
+ }
+
HTMLTableRowElement* row = 0;
+ int i = 0;
if (index == -1)
row = HTMLTableRowsCollection::lastRow(this);
else {
- for (int i = 0; i <= index; ++i) {
+ for (i = 0; i <= index; ++i) {
row = HTMLTableRowsCollection::rowAfter(this, row);
if (!row)
break;
}
}
if (!row) {
- es.throwDOMException(IndexSizeError);
+ exceptionState.throwDOMException(IndexSizeError, "The index provided (" + String::number(index) + ") is greater than the number of rows in the table (" + String::number(i) + ").");
return;
}
- row->remove(es);
+ row->remove(exceptionState);
}
static inline bool isTableCellAncestor(Node* n)
@@ -414,14 +415,14 @@ void HTMLTableElement::parseAttribute(const QualifiedName& name, const AtomicStr
}
}
-static StylePropertySet* leakBorderStyle(CSSValueID value)
+static PassRefPtr<StylePropertySet> createBorderStyle(CSSValueID value)
{
RefPtr<MutableStylePropertySet> style = MutableStylePropertySet::create();
style->setProperty(CSSPropertyBorderTopStyle, value);
style->setProperty(CSSPropertyBorderBottomStyle, value);
style->setProperty(CSSPropertyBorderLeftStyle, value);
style->setProperty(CSSPropertyBorderRightStyle, value);
- return style.release().leakRef();
+ return style.release();
}
const StylePropertySet* HTMLTableElement::additionalPresentationAttributeStyle()
@@ -433,17 +434,17 @@ const StylePropertySet* HTMLTableElement::additionalPresentationAttributeStyle()
// Setting the border to 'hidden' allows it to win over any border
// set on the table's cells during border-conflict resolution.
if (m_rulesAttr != UnsetRules) {
- static StylePropertySet* solidBorderStyle = leakBorderStyle(CSSValueHidden);
+ DEFINE_STATIC_REF(StylePropertySet, solidBorderStyle, (createBorderStyle(CSSValueHidden)));
return solidBorderStyle;
}
return 0;
}
if (m_borderColorAttr) {
- static StylePropertySet* solidBorderStyle = leakBorderStyle(CSSValueSolid);
+ DEFINE_STATIC_REF(StylePropertySet, solidBorderStyle, (createBorderStyle(CSSValueSolid)));
return solidBorderStyle;
}
- static StylePropertySet* outsetBorderStyle = leakBorderStyle(CSSValueOutset);
+ DEFINE_STATIC_REF(StylePropertySet, outsetBorderStyle, (createBorderStyle(CSSValueOutset)));
return outsetBorderStyle;
}
@@ -517,7 +518,7 @@ const StylePropertySet* HTMLTableElement::additionalCellStyle()
return m_sharedCellStyle.get();
}
-static StylePropertySet* leakGroupBorderStyle(int rows)
+static PassRefPtr<StylePropertySet> createGroupBorderStyle(int rows)
{
RefPtr<MutableStylePropertySet> style = MutableStylePropertySet::create();
if (rows) {
@@ -531,7 +532,7 @@ static StylePropertySet* leakGroupBorderStyle(int rows)
style->setProperty(CSSPropertyBorderLeftStyle, CSSValueSolid);
style->setProperty(CSSPropertyBorderRightStyle, CSSValueSolid);
}
- return style.release().leakRef();
+ return style.release();
}
const StylePropertySet* HTMLTableElement::additionalGroupStyle(bool rows)
@@ -540,10 +541,10 @@ const StylePropertySet* HTMLTableElement::additionalGroupStyle(bool rows)
return 0;
if (rows) {
- static StylePropertySet* rowBorderStyle = leakGroupBorderStyle(true);
+ DEFINE_STATIC_REF(StylePropertySet, rowBorderStyle, (createGroupBorderStyle(true)));
return rowBorderStyle;
}
- static StylePropertySet* columnBorderStyle = leakGroupBorderStyle(false);
+ DEFINE_STATIC_REF(StylePropertySet, columnBorderStyle, (createGroupBorderStyle(false)));
return columnBorderStyle;
}
@@ -562,12 +563,12 @@ PassRefPtr<HTMLCollection> HTMLTableElement::tBodies()
return ensureCachedHTMLCollection(TableTBodies);
}
-String HTMLTableElement::rules() const
+const AtomicString& HTMLTableElement::rules() const
{
return getAttribute(rulesAttr);
}
-String HTMLTableElement::summary() const
+const AtomicString& HTMLTableElement::summary() const
{
return getAttribute(summaryAttr);
}
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLTableElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLTableElement.h
index 4ec167481b3..d25a23c59bf 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLTableElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLTableElement.h
@@ -39,7 +39,6 @@ class HTMLTableSectionElement;
class HTMLTableElement FINAL : public HTMLElement {
public:
static PassRefPtr<HTMLTableElement> create(Document&);
- static PassRefPtr<HTMLTableElement> create(const QualifiedName&, Document&);
HTMLTableCaptionElement* caption() const;
void setCaption(PassRefPtr<HTMLTableCaptionElement>, ExceptionState&);
@@ -63,14 +62,14 @@ public:
PassRefPtr<HTMLCollection> rows();
PassRefPtr<HTMLCollection> tBodies();
- String rules() const;
- String summary() const;
+ const AtomicString& rules() const;
+ const AtomicString& summary() const;
const StylePropertySet* additionalCellStyle();
const StylePropertySet* additionalGroupStyle(bool rows);
private:
- HTMLTableElement(const QualifiedName&, Document&);
+ explicit HTMLTableElement(Document&);
virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
@@ -111,11 +110,7 @@ inline bool isHTMLTableElement(const Element* element)
return element->hasTagName(HTMLNames::tableTag);
}
-inline HTMLTableElement* toHTMLTableElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || isHTMLTableElement(node));
- return static_cast<HTMLTableElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(HTMLTableElement, hasTagName(HTMLNames::tableTag));
} //namespace
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLTableElement.idl b/chromium/third_party/WebKit/Source/core/html/HTMLTableElement.idl
index 1881de3ea17..4cd6d6f573b 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLTableElement.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLTableElement.idl
@@ -19,17 +19,17 @@
*/
interface HTMLTableElement : HTMLElement {
- [SetterRaisesException] attribute HTMLTableCaptionElement caption;
- [SetterRaisesException] attribute HTMLTableSectionElement tHead;
- [SetterRaisesException] attribute HTMLTableSectionElement tFoot;
+ [RaisesException=Setter] attribute HTMLTableCaptionElement caption;
+ [RaisesException=Setter] attribute HTMLTableSectionElement tHead;
+ [RaisesException=Setter] attribute HTMLTableSectionElement tFoot;
readonly attribute HTMLCollection rows;
readonly attribute HTMLCollection tBodies;
[Reflect] attribute DOMString align;
- [Reflect] attribute DOMString bgColor;
+ [Reflect, TreatNullAs=NullString] attribute DOMString bgColor;
[Reflect] attribute DOMString border;
- [Reflect] attribute DOMString cellPadding;
- [Reflect] attribute DOMString cellSpacing;
+ [Reflect, TreatNullAs=NullString] attribute DOMString cellPadding;
+ [Reflect, TreatNullAs=NullString] attribute DOMString cellSpacing;
[Reflect] attribute DOMString frame;
@@ -48,4 +48,3 @@ interface HTMLTableElement : HTMLElement {
[RaisesException] HTMLElement insertRow([Default=Undefined] optional long index);
[RaisesException] void deleteRow([Default=Undefined] optional long index);
};
-
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLTableRowElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLTableRowElement.cpp
index e50eaf81f5a..b643924cf72 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLTableRowElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLTableRowElement.cpp
@@ -37,21 +37,15 @@ namespace WebCore {
using namespace HTMLNames;
-HTMLTableRowElement::HTMLTableRowElement(const QualifiedName& tagName, Document& document)
- : HTMLTablePartElement(tagName, document)
+HTMLTableRowElement::HTMLTableRowElement(Document& document)
+ : HTMLTablePartElement(trTag, document)
{
- ASSERT(hasTagName(trTag));
ScriptWrappable::init(this);
}
PassRefPtr<HTMLTableRowElement> HTMLTableRowElement::create(Document& document)
{
- return adoptRef(new HTMLTableRowElement(trTag, document));
-}
-
-PassRefPtr<HTMLTableRowElement> HTMLTableRowElement::create(const QualifiedName& tagName, Document& document)
-{
- return adoptRef(new HTMLTableRowElement(tagName, document));
+ return adoptRef(new HTMLTableRowElement(document));
}
int HTMLTableRowElement::rowIndex() const
@@ -118,30 +112,30 @@ int HTMLTableRowElement::sectionRowIndex() const
return rIndex;
}
-PassRefPtr<HTMLElement> HTMLTableRowElement::insertCell(int index, ExceptionState& es)
+PassRefPtr<HTMLElement> HTMLTableRowElement::insertCell(int index, ExceptionState& exceptionState)
{
RefPtr<HTMLCollection> children = cells();
int numCells = children ? children->length() : 0;
if (index < -1 || index > numCells) {
- es.throwDOMException(IndexSizeError);
+ exceptionState.throwDOMException(IndexSizeError, "The value provided (" + String::number(index) + ") is outside the range [-1, " + String::number(numCells) + "].");
return 0;
}
RefPtr<HTMLTableCellElement> cell = HTMLTableCellElement::create(tdTag, document());
if (index < 0 || index >= numCells)
- appendChild(cell, es);
+ appendChild(cell, exceptionState);
else {
Node* n;
if (index < 1)
n = firstChild();
else
n = children->item(index);
- insertBefore(cell, n, es);
+ insertBefore(cell, n, exceptionState);
}
return cell.release();
}
-void HTMLTableRowElement::deleteCell(int index, ExceptionState& es)
+void HTMLTableRowElement::deleteCell(int index, ExceptionState& exceptionState)
{
RefPtr<HTMLCollection> children = cells();
int numCells = children ? children->length() : 0;
@@ -149,9 +143,9 @@ void HTMLTableRowElement::deleteCell(int index, ExceptionState& es)
index = numCells-1;
if (index >= 0 && index < numCells) {
RefPtr<Node> cell = children->item(index);
- HTMLElement::removeChild(cell.get(), es);
+ HTMLElement::removeChild(cell.get(), exceptionState);
} else {
- es.throwDOMException(IndexSizeError);
+ exceptionState.throwDOMException(IndexSizeError, "The value provided (" + String::number(index) + ") is outside the range [0, " + String::number(numCells) + ").");
}
}
@@ -160,9 +154,4 @@ PassRefPtr<HTMLCollection> HTMLTableRowElement::cells()
return ensureCachedHTMLCollection(TRCells);
}
-void HTMLTableRowElement::setCells(HTMLCollection*, ExceptionState& es)
-{
- es.throwDOMException(NoModificationAllowedError);
-}
-
}
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLTableRowElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLTableRowElement.h
index 0c1bff826c1..1fe3867218b 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLTableRowElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLTableRowElement.h
@@ -35,22 +35,18 @@ class ExceptionState;
class HTMLTableRowElement FINAL : public HTMLTablePartElement {
public:
static PassRefPtr<HTMLTableRowElement> create(Document&);
- static PassRefPtr<HTMLTableRowElement> create(const QualifiedName&, Document&);
int rowIndex() const;
- void setRowIndex(int);
int sectionRowIndex() const;
- void setSectionRowIndex(int);
PassRefPtr<HTMLElement> insertCell(int index, ExceptionState&);
void deleteCell(int index, ExceptionState&);
PassRefPtr<HTMLCollection> cells();
- void setCells(HTMLCollection *, ExceptionState&);
private:
- HTMLTableRowElement(const QualifiedName&, Document&);
+ explicit HTMLTableRowElement(Document&);
};
inline bool isHTMLTableRowElement(const Node* node)
@@ -58,11 +54,7 @@ inline bool isHTMLTableRowElement(const Node* node)
return node->hasTagName(HTMLNames::trTag);
}
-inline HTMLTableRowElement* toHTMLTableRowElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || isHTMLTableRowElement(node));
- return static_cast<HTMLTableRowElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(HTMLTableRowElement, hasTagName(HTMLNames::trTag));
} // namespace
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLTableRowElement.idl b/chromium/third_party/WebKit/Source/core/html/HTMLTableRowElement.idl
index a56f70a46e9..aa7b9cae5bd 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLTableRowElement.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLTableRowElement.idl
@@ -23,11 +23,10 @@ interface HTMLTableRowElement : HTMLElement {
readonly attribute long sectionRowIndex;
readonly attribute HTMLCollection cells;
[Reflect] attribute DOMString align;
- [Reflect] attribute DOMString bgColor;
+ [Reflect, TreatNullAs=NullString] attribute DOMString bgColor;
[Reflect=char] attribute DOMString ch;
[Reflect=charoff] attribute DOMString chOff;
[Reflect] attribute DOMString vAlign;
[RaisesException] HTMLElement insertCell([Default=Undefined] optional long index);
[RaisesException] void deleteCell([Default=Undefined] optional long index);
};
-
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLTableRowsCollection.h b/chromium/third_party/WebKit/Source/core/html/HTMLTableRowsCollection.h
index e92500ee69f..d643d430de4 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLTableRowsCollection.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLTableRowsCollection.h
@@ -36,7 +36,7 @@ namespace WebCore {
class HTMLTableElement;
class HTMLTableRowElement;
-class HTMLTableRowsCollection : public HTMLCollection {
+class HTMLTableRowsCollection FINAL : public HTMLCollection {
public:
static PassRefPtr<HTMLTableRowsCollection> create(Node*, CollectionType);
@@ -44,7 +44,7 @@ public:
static HTMLTableRowElement* lastRow(HTMLTableElement*);
private:
- HTMLTableRowsCollection(Node*);
+ explicit HTMLTableRowsCollection(Node*);
virtual Element* virtualItemAfter(unsigned& offsetInArray, Element*) const OVERRIDE;
};
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLTableSectionElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLTableSectionElement.cpp
index c84d6b99f8f..01ec777a27f 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLTableSectionElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLTableSectionElement.cpp
@@ -56,30 +56,30 @@ const StylePropertySet* HTMLTableSectionElement::additionalPresentationAttribute
// these functions are rather slow, since we need to get the row at
// the index... but they aren't used during usual HTML parsing anyway
-PassRefPtr<HTMLElement> HTMLTableSectionElement::insertRow(int index, ExceptionState& es)
+PassRefPtr<HTMLElement> HTMLTableSectionElement::insertRow(int index, ExceptionState& exceptionState)
{
RefPtr<HTMLTableRowElement> row;
RefPtr<HTMLCollection> children = rows();
int numRows = children ? (int)children->length() : 0;
if (index < -1 || index > numRows)
- es.throwDOMException(IndexSizeError); // per the DOM
+ exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError); // per the DOM
else {
- row = HTMLTableRowElement::create(trTag, document());
+ row = HTMLTableRowElement::create(document());
if (numRows == index || index == -1)
- appendChild(row, es);
+ appendChild(row, exceptionState);
else {
Node* n;
if (index < 1)
n = firstChild();
else
n = children->item(index);
- insertBefore(row, n, es);
+ insertBefore(row, n, exceptionState);
}
}
return row.release();
}
-void HTMLTableSectionElement::deleteRow(int index, ExceptionState& es)
+void HTMLTableSectionElement::deleteRow(int index, ExceptionState& exceptionState)
{
RefPtr<HTMLCollection> children = rows();
int numRows = children ? (int)children->length() : 0;
@@ -87,9 +87,9 @@ void HTMLTableSectionElement::deleteRow(int index, ExceptionState& es)
index = numRows - 1;
if (index >= 0 && index < numRows) {
RefPtr<Node> row = children->item(index);
- HTMLElement::removeChild(row.get(), es);
+ HTMLElement::removeChild(row.get(), exceptionState);
} else {
- es.throwDOMException(IndexSizeError);
+ exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
}
}
@@ -106,42 +106,42 @@ int HTMLTableSectionElement::numRows() const
return rows;
}
-String HTMLTableSectionElement::align() const
+const AtomicString& HTMLTableSectionElement::align() const
{
return getAttribute(alignAttr);
}
-void HTMLTableSectionElement::setAlign(const String &value)
+void HTMLTableSectionElement::setAlign(const AtomicString& value)
{
setAttribute(alignAttr, value);
}
-String HTMLTableSectionElement::ch() const
+const AtomicString& HTMLTableSectionElement::ch() const
{
return getAttribute(charAttr);
}
-void HTMLTableSectionElement::setCh(const String &value)
+void HTMLTableSectionElement::setCh(const AtomicString& value)
{
setAttribute(charAttr, value);
}
-String HTMLTableSectionElement::chOff() const
+const AtomicString& HTMLTableSectionElement::chOff() const
{
return getAttribute(charoffAttr);
}
-void HTMLTableSectionElement::setChOff(const String &value)
+void HTMLTableSectionElement::setChOff(const AtomicString& value)
{
setAttribute(charoffAttr, value);
}
-String HTMLTableSectionElement::vAlign() const
+const AtomicString& HTMLTableSectionElement::vAlign() const
{
return getAttribute(valignAttr);
}
-void HTMLTableSectionElement::setVAlign(const String &value)
+void HTMLTableSectionElement::setVAlign(const AtomicString& value)
{
setAttribute(valignAttr, value);
}
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLTableSectionElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLTableSectionElement.h
index f2d271b0e26..02d55167adb 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLTableSectionElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLTableSectionElement.h
@@ -41,17 +41,17 @@ public:
int numRows() const;
- String align() const;
- void setAlign(const String&);
+ const AtomicString& align() const;
+ void setAlign(const AtomicString&);
- String ch() const;
- void setCh(const String&);
+ const AtomicString& ch() const;
+ void setCh(const AtomicString&);
- String chOff() const;
- void setChOff(const String&);
+ const AtomicString& chOff() const;
+ void setChOff(const AtomicString&);
- String vAlign() const;
- void setVAlign(const String&);
+ const AtomicString& vAlign() const;
+ void setVAlign(const AtomicString&);
PassRefPtr<HTMLCollection> rows();
@@ -61,12 +61,13 @@ private:
virtual const StylePropertySet* additionalPresentationAttributeStyle() OVERRIDE;
};
-inline HTMLTableSectionElement* toHTMLTableSectionElement(Node* node)
+inline bool isHTMLTableSectionElement(const Node& node)
{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::tbodyTag) || node->hasTagName(HTMLNames::tfootTag) || node->hasTagName(HTMLNames::theadTag));
- return static_cast<HTMLTableSectionElement*>(node);
+ return node.hasTagName(HTMLNames::tbodyTag) || node.hasTagName(HTMLNames::tfootTag) || node.hasTagName(HTMLNames::theadTag);
}
+DEFINE_NODE_TYPE_CASTS_WITH_FUNCTION(HTMLTableSectionElement);
+
} //namespace
#endif
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLTableSectionElement.idl b/chromium/third_party/WebKit/Source/core/html/HTMLTableSectionElement.idl
index 3126d7763c7..836b712c43e 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLTableSectionElement.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLTableSectionElement.idl
@@ -27,4 +27,3 @@ interface HTMLTableSectionElement : HTMLElement {
[RaisesException] HTMLElement insertRow([Default=Undefined] optional long index);
[RaisesException] void deleteRow([Default=Undefined] optional long index);
};
-
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLTagNames.in b/chromium/third_party/WebKit/Source/core/html/HTMLTagNames.in
index f2ab1eb6ae3..ee8c92f89f3 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLTagNames.in
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLTagNames.in
@@ -11,7 +11,7 @@ applet constructorNeedsCreatedByParser
area
article interfaceName=HTMLElement
aside interfaceName=HTMLElement
-audio wrapperOnlyIfMediaIsAvailable, constructorNeedsCreatedByParser
+audio runtimeEnabled=media, constructorNeedsCreatedByParser
b interfaceName=HTMLElement
base
basefont interfaceName=HTMLElement
@@ -32,7 +32,6 @@ col interfaceName=HTMLTableColElement
colgroup interfaceName=HTMLTableColElement
command interfaceName=HTMLElement
content interfaceName=HTMLContentElement
-webkitShadowContent interfaceName=HTMLElement, noConstructor
datalist interfaceName=HTMLDataListElement
dd interfaceName=HTMLElement
del interfaceName=HTMLModElement
@@ -66,7 +65,7 @@ hr interfaceName=HTMLHRElement
html
i interfaceName=HTMLElement
iframe interfaceName=HTMLIFrameElement
-image mapToTagName=img
+image interfaceName=HTMLUnknownElement
img interfaceName=HTMLImageElement, constructorNeedsFormElement
input constructorNeedsFormElement, constructorNeedsCreatedByParser
ins interfaceName=HTMLModElement
@@ -112,7 +111,7 @@ script constructorNeedsCreatedByParser
section interfaceName=HTMLElement
select constructorNeedsFormElement, constructorNeedsCreatedByParser
small interfaceName=HTMLElement
-source wrapperOnlyIfMediaIsAvailable
+source runtimeEnabled=media
span
strike interfaceName=HTMLElement
strong interfaceName=HTMLElement
@@ -130,12 +129,12 @@ th interfaceName=HTMLTableCellElement
thead interfaceName=HTMLTableSectionElement
title
tr interfaceName=HTMLTableRowElement
-track wrapperOnlyIfMediaIsAvailable
+track runtimeEnabled=videoTrack
tt interfaceName=HTMLElement
u interfaceName=HTMLElement
ul interfaceName=HTMLUListElement
var interfaceName=HTMLElement
-video wrapperOnlyIfMediaIsAvailable, constructorNeedsCreatedByParser
+video runtimeEnabled=media, constructorNeedsCreatedByParser
wbr interfaceName=HTMLElement
xmp interfaceName=HTMLPreElement
noscript interfaceName=HTMLElement
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLTemplateElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLTemplateElement.cpp
index 52e614eba66..2990838c707 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLTemplateElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLTemplateElement.cpp
@@ -39,8 +39,8 @@ namespace WebCore {
using namespace HTMLNames;
-inline HTMLTemplateElement::HTMLTemplateElement(const QualifiedName& tagName, Document& document)
- : HTMLElement(tagName, document)
+inline HTMLTemplateElement::HTMLTemplateElement(Document& document)
+ : HTMLElement(templateTag, document)
{
ScriptWrappable::init(this);
}
@@ -51,15 +51,15 @@ HTMLTemplateElement::~HTMLTemplateElement()
m_content->clearHost();
}
-PassRefPtr<HTMLTemplateElement> HTMLTemplateElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<HTMLTemplateElement> HTMLTemplateElement::create(Document& document)
{
- return adoptRef(new HTMLTemplateElement(tagName, document));
+ return adoptRef(new HTMLTemplateElement(document));
}
DocumentFragment* HTMLTemplateElement::content() const
{
if (!m_content)
- m_content = TemplateContentDocumentFragment::create(document().ensureTemplateDocument(), this);
+ m_content = TemplateContentDocumentFragment::create(document().ensureTemplateDocument(), const_cast<HTMLTemplateElement*>(this));
return m_content.get();
}
@@ -75,12 +75,12 @@ PassRefPtr<Node> HTMLTemplateElement::cloneNode(bool deep)
return clone.release();
}
-void HTMLTemplateElement::didMoveToNewDocument(Document* oldDocument)
+void HTMLTemplateElement::didMoveToNewDocument(Document& oldDocument)
{
HTMLElement::didMoveToNewDocument(oldDocument);
if (!m_content)
return;
- document().ensureTemplateDocument().adoptIfNeeded(m_content.get());
+ document().ensureTemplateDocument().adoptIfNeeded(*m_content);
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLTemplateElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLTemplateElement.h
index 82a48468b7e..b27958dafb1 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLTemplateElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLTemplateElement.h
@@ -40,31 +40,21 @@ class TemplateContentDocumentFragment;
class HTMLTemplateElement FINAL : public HTMLElement {
public:
- static PassRefPtr<HTMLTemplateElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<HTMLTemplateElement> create(Document&);
virtual ~HTMLTemplateElement();
DocumentFragment* content() const;
private:
virtual PassRefPtr<Node> cloneNode(bool deep = true) OVERRIDE;
- virtual void didMoveToNewDocument(Document* oldDocument) OVERRIDE;
+ virtual void didMoveToNewDocument(Document& oldDocument) OVERRIDE;
- HTMLTemplateElement(const QualifiedName&, Document&);
+ explicit HTMLTemplateElement(Document&);
mutable RefPtr<TemplateContentDocumentFragment> m_content;
};
-inline HTMLTemplateElement* toHTMLTemplateElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || (node->isHTMLElement() && node->hasTagName(HTMLNames::templateTag)));
- return static_cast<HTMLTemplateElement*>(node);
-}
-
-inline const HTMLTemplateElement* toHTMLTemplateElement(const Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || (node->isHTMLElement() && node->hasTagName(HTMLNames::templateTag)));
- return static_cast<const HTMLTemplateElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(HTMLTemplateElement, hasTagName(HTMLNames::templateTag));
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLTemplateElement.idl b/chromium/third_party/WebKit/Source/core/html/HTMLTemplateElement.idl
index 46c66967145..e950fcecfa4 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLTemplateElement.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLTemplateElement.idl
@@ -29,6 +29,6 @@
*/
interface HTMLTemplateElement : HTMLElement {
- [KeepAttributeAliveForGC] readonly attribute DocumentFragment content;
+ readonly attribute DocumentFragment content;
};
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLTextAreaElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLTextAreaElement.cpp
index 9fa7619ea79..ca7494e2af6 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLTextAreaElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLTextAreaElement.cpp
@@ -30,24 +30,23 @@
#include "HTMLNames.h"
#include "bindings/v8/ExceptionState.h"
#include "bindings/v8/ExceptionStatePlaceholder.h"
-#include "core/dom/BeforeTextInsertedEvent.h"
#include "core/dom/Document.h"
-#include "core/dom/Event.h"
-#include "core/dom/EventNames.h"
#include "core/dom/ExceptionCode.h"
#include "core/dom/Text.h"
#include "core/dom/shadow/ShadowRoot.h"
-#include "core/editing/Editor.h"
#include "core/editing/FrameSelection.h"
+#include "core/editing/SpellChecker.h"
#include "core/editing/TextIterator.h"
+#include "core/events/BeforeTextInsertedEvent.h"
+#include "core/events/Event.h"
+#include "core/events/ThreadLocalEventNames.h"
#include "core/html/FormDataList.h"
#include "core/html/forms/FormController.h"
#include "core/html/shadow/ShadowElementNames.h"
#include "core/html/shadow/TextControlInnerElements.h"
-#include "core/page/Frame.h"
-#include "core/platform/LocalizedStrings.h"
-#include "core/platform/text/PlatformLocale.h"
+#include "core/frame/Frame.h"
#include "core/rendering/RenderTextControlMultiLine.h"
+#include "platform/text/PlatformLocale.h"
#include "wtf/StdLibExtras.h"
#include "wtf/text/StringBuilder.h"
@@ -60,11 +59,6 @@ static const int defaultCols = 20;
// On submission, LF characters are converted into CRLF.
// This function returns number of characters considering this.
-static inline unsigned computeLengthForSubmission(const String& text, unsigned numberOfLineBreaks)
-{
- return text.length() + numberOfLineBreaks;
-}
-
static unsigned numberOfLineBreaks(const String& text)
{
unsigned length = text.length();
@@ -81,29 +75,27 @@ static inline unsigned computeLengthForSubmission(const String& text)
return text.length() + numberOfLineBreaks(text);
}
-HTMLTextAreaElement::HTMLTextAreaElement(const QualifiedName& tagName, Document& document, HTMLFormElement* form)
- : HTMLTextFormControlElement(tagName, document, form)
+HTMLTextAreaElement::HTMLTextAreaElement(Document& document, HTMLFormElement* form)
+ : HTMLTextFormControlElement(textareaTag, document, form)
, m_rows(defaultRows)
, m_cols(defaultCols)
, m_wrap(SoftWrap)
, m_isDirty(false)
- , m_wasModifiedByUser(false)
{
- ASSERT(hasTagName(textareaTag));
setFormControlValueMatchesRenderer(true);
ScriptWrappable::init(this);
}
-PassRefPtr<HTMLTextAreaElement> HTMLTextAreaElement::create(const QualifiedName& tagName, Document& document, HTMLFormElement* form)
+PassRefPtr<HTMLTextAreaElement> HTMLTextAreaElement::create(Document& document, HTMLFormElement* form)
{
- RefPtr<HTMLTextAreaElement> textArea = adoptRef(new HTMLTextAreaElement(tagName, document, form));
+ RefPtr<HTMLTextAreaElement> textArea = adoptRef(new HTMLTextAreaElement(document, form));
textArea->ensureUserAgentShadowRoot();
return textArea.release();
}
-void HTMLTextAreaElement::didAddUserAgentShadowRoot(ShadowRoot* root)
+void HTMLTextAreaElement::didAddUserAgentShadowRoot(ShadowRoot& root)
{
- root->appendChild(TextControlInnerTextElement::create(document()));
+ root.appendChild(TextControlInnerTextElement::create(document()));
}
const AtomicString& HTMLTextAreaElement::formControlType() const
@@ -223,7 +215,7 @@ bool HTMLTextAreaElement::appendFormData(FormDataList& encoding, bool)
return true;
}
-void HTMLTextAreaElement::reset()
+void HTMLTextAreaElement::resetImpl()
{
setNonDirtyValue(defaultValue());
}
@@ -260,7 +252,7 @@ void HTMLTextAreaElement::updateFocusAppearance(bool restorePreviousSelection)
void HTMLTextAreaElement::defaultEventHandler(Event* event)
{
- if (renderer() && (event->isMouseEvent() || event->isDragEvent() || event->hasInterface(eventNames().interfaceForWheelEvent) || event->type() == eventNames().blurEvent))
+ if (renderer() && (event->isMouseEvent() || event->isDragEvent() || event->hasInterface(EventNames::WheelEvent) || event->type() == EventTypeNames::blur))
forwardEvent(event);
else if (renderer() && event->isBeforeTextInsertedEvent())
handleBeforeTextInsertedEvent(static_cast<BeforeTextInsertedEvent*>(event));
@@ -271,7 +263,7 @@ void HTMLTextAreaElement::defaultEventHandler(Event* event)
void HTMLTextAreaElement::handleFocusEvent(Element*, FocusDirection)
{
if (Frame* frame = document().frame())
- frame->editor().textAreaOrTextFieldDidBeginEditing(this);
+ frame->spellChecker().didBeginEditing(this);
}
void HTMLTextAreaElement::subtreeHasChanged()
@@ -320,13 +312,6 @@ String HTMLTextAreaElement::sanitizeUserInputValue(const String& proposedValue,
return proposedValue.left(maxLength);
}
-HTMLElement* HTMLTextAreaElement::innerTextElement() const
-{
- Node* node = userAgentShadowRoot()->firstChild();
- ASSERT(!node || node->hasTagName(divTag));
- return toHTMLElement(node);
-}
-
void HTMLTextAreaElement::rendererWillBeDestroyed()
{
updateValue();
@@ -342,7 +327,6 @@ void HTMLTextAreaElement::updateValue() const
const_cast<HTMLTextAreaElement*>(this)->setFormControlValueMatchesRenderer(true);
const_cast<HTMLTextAreaElement*>(this)->notifyFormStateChanged();
m_isDirty = true;
- m_wasModifiedByUser = true;
const_cast<HTMLTextAreaElement*>(this)->updatePlaceholderVisibility(false);
}
@@ -368,7 +352,6 @@ void HTMLTextAreaElement::setNonDirtyValue(const String& value)
void HTMLTextAreaElement::setValueCommon(const String& newValue)
{
- m_wasModifiedByUser = false;
// Code elsewhere normalizes line endings added by the user via the keyboard or pasting.
// We normalize line endings coming from JavaScript here.
String normalizedValue = newValue.isNull() ? "" : newValue;
@@ -442,12 +425,12 @@ int HTMLTextAreaElement::maxLength() const
return ok && value >= 0 ? value : -1;
}
-void HTMLTextAreaElement::setMaxLength(int newValue, ExceptionState& es)
+void HTMLTextAreaElement::setMaxLength(int newValue, ExceptionState& exceptionState)
{
if (newValue < 0)
- es.throwDOMException(IndexSizeError);
+ exceptionState.throwDOMException(IndexSizeError, "The value provided (" + String::number(newValue) + ") is not positive or 0.");
else
- setAttribute(maxlengthAttr, String::number(newValue));
+ setIntegralAttribute(maxlengthAttr, newValue);
}
String HTMLTextAreaElement::validationMessage() const
@@ -459,7 +442,7 @@ String HTMLTextAreaElement::validationMessage() const
return customValidationMessage();
if (valueMissing())
- return validationMessageValueMissingText();
+ return locale().queryString(blink::WebLocalizedString::ValidationValueMissing);
if (tooLong())
return locale().validationMessageTooLongText(computeLengthForSubmission(value()), maxLength());
@@ -481,7 +464,7 @@ bool HTMLTextAreaElement::tooLong(const String& value, NeedsToCheckDirtyFlag che
{
// Return false for the default value or value set by script even if it is
// longer than maxLength.
- if (check == CheckDirtyFlag && !m_wasModifiedByUser)
+ if (check == CheckDirtyFlag && !lastChangeWasUserEdit())
return false;
int max = maxLength();
@@ -502,12 +485,12 @@ void HTMLTextAreaElement::accessKeyAction(bool)
void HTMLTextAreaElement::setCols(int cols)
{
- setAttribute(colsAttr, String::number(cols));
+ setIntegralAttribute(colsAttr, cols);
}
void HTMLTextAreaElement::setRows(int rows)
{
- setAttribute(rowsAttr, String::number(rows));
+ setIntegralAttribute(rowsAttr, rows);
}
bool HTMLTextAreaElement::shouldUseInputMethod()
@@ -537,11 +520,11 @@ void HTMLTextAreaElement::updatePlaceholderText()
if (!placeholder) {
RefPtr<HTMLDivElement> newElement = HTMLDivElement::create(document());
placeholder = newElement.get();
- placeholder->setPart(AtomicString("-webkit-input-placeholder", AtomicString::ConstructFromLiteral));
+ placeholder->setPseudo(AtomicString("-webkit-input-placeholder", AtomicString::ConstructFromLiteral));
placeholder->setAttribute(idAttr, ShadowElementNames::placeholder());
userAgentShadowRoot()->insertBefore(placeholder, innerTextElement()->nextSibling());
}
- placeholder->setTextContent(placeholderText, ASSERT_NO_EXCEPTION);
+ placeholder->setTextContent(placeholderText);
}
bool HTMLTextAreaElement::isInteractiveContent() const
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLTextAreaElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLTextAreaElement.h
index a2ce2a0afa8..a5693348c08 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLTextAreaElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLTextAreaElement.h
@@ -34,7 +34,7 @@ class VisibleSelection;
class HTMLTextAreaElement FINAL : public HTMLTextFormControlElement {
public:
- static PassRefPtr<HTMLTextAreaElement> create(const QualifiedName&, Document&, HTMLFormElement*);
+ static PassRefPtr<HTMLTextAreaElement> create(Document&, HTMLFormElement*);
int cols() const { return m_cols; }
int rows() const { return m_rows; }
@@ -54,19 +54,17 @@ public:
virtual bool tooLong() const OVERRIDE;
bool isValidValue(const String&) const;
- virtual HTMLElement* innerTextElement() const;
-
void rendererWillBeDestroyed();
void setCols(int);
void setRows(int);
private:
- HTMLTextAreaElement(const QualifiedName&, Document&, HTMLFormElement*);
+ HTMLTextAreaElement(Document&, HTMLFormElement*);
enum WrapMethod { NoWrap, SoftWrap, HardWrap };
- virtual void didAddUserAgentShadowRoot(ShadowRoot*) OVERRIDE;
+ virtual void didAddUserAgentShadowRoot(ShadowRoot&) OVERRIDE;
// FIXME: Author shadows should be allowed
// https://bugs.webkit.org/show_bug.cgi?id=92608
virtual bool areAuthorShadowsAllowed() const OVERRIDE { return false; }
@@ -106,7 +104,7 @@ private:
virtual void collectStyleForPresentationAttribute(const QualifiedName&, const AtomicString&, MutableStylePropertySet*) OVERRIDE;
virtual RenderObject* createRenderer(RenderStyle*);
virtual bool appendFormData(FormDataList&, bool);
- virtual void reset();
+ virtual void resetImpl() OVERRIDE;
virtual bool hasCustomFocusLogic() const OVERRIDE;
virtual bool shouldShowFocusRingOnMouseFocus() const OVERRIDE;
virtual bool isKeyboardFocusable() const OVERRIDE;
@@ -126,7 +124,6 @@ private:
WrapMethod m_wrap;
mutable String m_value;
mutable bool m_isDirty;
- mutable bool m_wasModifiedByUser;
};
inline bool isHTMLTextAreaElement(const Node* node)
@@ -139,11 +136,7 @@ inline bool isHTMLTextAreaElement(const Element* element)
return element->hasTagName(HTMLNames::textareaTag);
}
-inline HTMLTextAreaElement* toHTMLTextAreaElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || isHTMLTextAreaElement(node));
- return static_cast<HTMLTextAreaElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(HTMLTextAreaElement, hasTagName(HTMLNames::textareaTag));
} //namespace
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLTextAreaElement.idl b/chromium/third_party/WebKit/Source/core/html/HTMLTextAreaElement.idl
index 51c84199ab1..e5d79264392 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLTextAreaElement.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLTextAreaElement.idl
@@ -24,18 +24,18 @@ interface HTMLTextAreaElement : HTMLElement {
attribute long cols;
[Reflect] attribute DOMString dirName;
[Reflect] attribute boolean disabled;
- readonly attribute HTMLFormElement form;
- [SetterRaisesException] attribute long maxLength;
+ [ImplementedAs=formOwner] readonly attribute HTMLFormElement form;
+ [RaisesException=Setter] attribute long maxLength;
[Reflect] attribute DOMString name;
[Reflect] attribute DOMString placeholder;
[Reflect] attribute boolean readOnly;
[Reflect] attribute boolean required;
attribute long rows;
[Reflect] attribute DOMString wrap;
- [EnabledAtRuntime=InputModeAttribute, Reflect] attribute DOMString inputMode;
+ [RuntimeEnabled=InputModeAttribute, Reflect] attribute DOMString inputMode;
readonly attribute DOMString type;
- [TreatNullAs=NullString] attribute DOMString defaultValue;
+ attribute DOMString defaultValue;
[TreatNullAs=NullString] attribute DOMString value;
readonly attribute unsigned long textLength;
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLTextFormControlElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLTextFormControlElement.cpp
index dd3f8fa0aa0..d4b83cb03d8 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLTextFormControlElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLTextFormControlElement.cpp
@@ -30,17 +30,17 @@
#include "bindings/v8/ExceptionStatePlaceholder.h"
#include "core/accessibility/AXObjectCache.h"
#include "core/dom/Document.h"
-#include "core/dom/Event.h"
-#include "core/dom/EventNames.h"
#include "core/dom/NodeTraversal.h"
#include "core/dom/Text.h"
#include "core/dom/shadow/ShadowRoot.h"
#include "core/editing/FrameSelection.h"
#include "core/editing/TextIterator.h"
+#include "core/events/Event.h"
+#include "core/events/ThreadLocalEventNames.h"
#include "core/html/HTMLBRElement.h"
#include "core/html/shadow/ShadowElementNames.h"
-#include "core/page/Frame.h"
-#include "core/page/UseCounter.h"
+#include "core/frame/Frame.h"
+#include "core/frame/UseCounter.h"
#include "core/rendering/RenderBlock.h"
#include "core/rendering/RenderTheme.h"
#include "wtf/text/StringBuilder.h"
@@ -91,7 +91,7 @@ void HTMLTextFormControlElement::dispatchBlurEvent(Element* newFocusedElement)
void HTMLTextFormControlElement::defaultEventHandler(Event* event)
{
- if (event->type() == eventNames().webkitEditableContentChangedEvent && renderer() && renderer()->isTextControl()) {
+ if (event->type() == EventTypeNames::webkitEditableContentChanged && renderer() && renderer()->isTextControl()) {
m_lastChangeWasUserEdit = true;
subtreeHasChanged();
return;
@@ -102,7 +102,7 @@ void HTMLTextFormControlElement::defaultEventHandler(Event* event)
void HTMLTextFormControlElement::forwardEvent(Event* event)
{
- if (event->type() == eventNames().blurEvent || event->type() == eventNames().focusEvent)
+ if (event->type() == EventTypeNames::blur || event->type() == EventTypeNames::focus)
return;
innerTextElement()->defaultEventHandler(event);
}
@@ -205,15 +205,15 @@ static inline bool hasVisibleTextArea(RenderObject* renderer, HTMLElement* inner
}
-void HTMLTextFormControlElement::setRangeText(const String& replacement, ExceptionState& es)
+void HTMLTextFormControlElement::setRangeText(const String& replacement, ExceptionState& exceptionState)
{
- setRangeText(replacement, selectionStart(), selectionEnd(), String(), es);
+ setRangeText(replacement, selectionStart(), selectionEnd(), String(), exceptionState);
}
-void HTMLTextFormControlElement::setRangeText(const String& replacement, unsigned start, unsigned end, const String& selectionMode, ExceptionState& es)
+void HTMLTextFormControlElement::setRangeText(const String& replacement, unsigned start, unsigned end, const String& selectionMode, ExceptionState& exceptionState)
{
if (start > end) {
- es.throwDOMException(IndexSizeError);
+ exceptionState.throwDOMException(IndexSizeError, "The provided start value (" + String::number(start) + ") is larger than the provided end value (" + String::number(end) + ").");
return;
}
@@ -445,7 +445,7 @@ PassRefPtr<Range> HTMLTextFormControlElement::selection() const
int offset = 0;
Node* startNode = 0;
Node* endNode = 0;
- for (Node* node = innerText->firstChild(); node; node = NodeTraversal::next(node, innerText)) {
+ for (Node* node = innerText->firstChild(); node; node = NodeTraversal::next(*node, innerText)) {
ASSERT(!node->firstChild());
ASSERT(node->isTextNode() || node->hasTagName(brTag));
int length = node->isTextNode() ? lastOffsetInNode(node) : 1;
@@ -482,7 +482,7 @@ void HTMLTextFormControlElement::selectionChanged(bool userTriggered)
if (Frame* frame = document().frame()) {
if (frame->selection().isRange() && userTriggered)
- dispatchEvent(Event::createBubble(eventNames().selectEvent));
+ dispatchEvent(Event::createBubble(EventTypeNames::select));
}
}
@@ -490,7 +490,7 @@ void HTMLTextFormControlElement::parseAttribute(const QualifiedName& name, const
{
if (name == placeholderAttr) {
updatePlaceholderVisibility(true);
- UseCounter::count(&document(), UseCounter::PlaceholderAttribute);
+ UseCounter::count(document(), UseCounter::PlaceholderAttribute);
} else
HTMLFormControlElementWithState::parseAttribute(name, value);
}
@@ -538,7 +538,7 @@ String HTMLTextFormControlElement::innerTextValue() const
return emptyString();
StringBuilder result;
- for (Node* node = innerText; node; node = NodeTraversal::next(node, innerText)) {
+ for (Node* node = innerText; node; node = NodeTraversal::next(*node, innerText)) {
if (node->hasTagName(brTag))
result.append(newlineCharacter);
else if (node->isTextNode())
@@ -585,7 +585,7 @@ String HTMLTextFormControlElement::valueWithHardLineBreaks() const
getNextSoftBreak(line, breakNode, breakOffset);
StringBuilder result;
- for (Node* node = innerText->firstChild(); node; node = NodeTraversal::next(node, innerText)) {
+ for (Node* node = innerText->firstChild(); node; node = NodeTraversal::next(*node, innerText)) {
if (node->hasTagName(brTag))
result.append(newlineCharacter);
else if (node->isTextNode()) {
@@ -621,19 +621,19 @@ HTMLTextFormControlElement* enclosingTextFormControl(const Position& position)
return ancestor && isHTMLTextFormControlElement(ancestor) ? toHTMLTextFormControlElement(ancestor) : 0;
}
-static const Element* parentHTMLElement(const Element* element)
+static const HTMLElement* parentHTMLElement(const Element* element)
{
while (element) {
element = element->parentElement();
if (element && element->isHTMLElement())
- return element;
+ return toHTMLElement(element);
}
return 0;
}
String HTMLTextFormControlElement::directionForFormData() const
{
- for (const Element* element = this; element; element = parentHTMLElement(element)) {
+ for (const HTMLElement* element = this; element; element = parentHTMLElement(element)) {
const AtomicString& dirAttributeValue = element->fastGetAttribute(dirAttr);
if (dirAttributeValue.isNull())
continue;
@@ -643,7 +643,7 @@ String HTMLTextFormControlElement::directionForFormData() const
if (equalIgnoringCase(dirAttributeValue, "auto")) {
bool isAuto;
- TextDirection textDirection = static_cast<const HTMLElement*>(element)->directionalityIfhasDirAutoAttribute(isAuto);
+ TextDirection textDirection = element->directionalityIfhasDirAutoAttribute(isAuto);
return textDirection == RTL ? "rtl" : "ltr";
}
}
@@ -651,4 +651,9 @@ String HTMLTextFormControlElement::directionForFormData() const
return "ltr";
}
+HTMLElement* HTMLTextFormControlElement::innerTextElement() const
+{
+ return toHTMLElement(userAgentShadowRoot()->getElementById(ShadowElementNames::innerEditor()));
+}
+
} // namespace Webcore
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLTextFormControlElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLTextFormControlElement.h
index 66562b6f626..2c7a9bf8895 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLTextFormControlElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLTextFormControlElement.h
@@ -77,7 +77,7 @@ public:
virtual int maxLength() const = 0;
virtual String value() const = 0;
- virtual HTMLElement* innerTextElement() const = 0;
+ HTMLElement* innerTextElement() const;
void selectionChanged(bool userTriggered);
bool lastChangeWasUserEdit() const;
@@ -142,12 +142,13 @@ inline bool isHTMLTextFormControlElement(const Node* node)
return node->isElementNode() && toElement(node)->isTextFormControl();
}
-inline HTMLTextFormControlElement* toHTMLTextFormControlElement(Node* node)
+inline bool isHTMLTextFormControlElement(const Node& node)
{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || isHTMLTextFormControlElement(node));
- return static_cast<HTMLTextFormControlElement*>(node);
+ return node.isElementNode() && toElement(node).isTextFormControl();
}
+DEFINE_NODE_TYPE_CASTS_WITH_FUNCTION(HTMLTextFormControlElement);
+
HTMLTextFormControlElement* enclosingTextFormControl(const Position&);
} // namespace
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLTitleElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLTitleElement.cpp
index 48ed56ea3e0..c9fdaedc0f2 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLTitleElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLTitleElement.cpp
@@ -35,17 +35,16 @@ namespace WebCore {
using namespace HTMLNames;
-inline HTMLTitleElement::HTMLTitleElement(const QualifiedName& tagName, Document& document)
- : HTMLElement(tagName, document)
+inline HTMLTitleElement::HTMLTitleElement(Document& document)
+ : HTMLElement(titleTag, document)
{
- ASSERT(hasTagName(titleTag));
setHasCustomStyleCallbacks();
ScriptWrappable::init(this);
}
-PassRefPtr<HTMLTitleElement> HTMLTitleElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<HTMLTitleElement> HTMLTitleElement::create(Document& document)
{
- return adoptRef(new HTMLTitleElement(tagName, document));
+ return adoptRef(new HTMLTitleElement(document));
}
Node::InsertionNotificationRequest HTMLTitleElement::insertedInto(ContainerNode* insertionPoint)
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLTitleElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLTitleElement.h
index 580a291c3a4..988f77ac96e 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLTitleElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLTitleElement.h
@@ -28,13 +28,13 @@ namespace WebCore {
class HTMLTitleElement FINAL : public HTMLElement {
public:
- static PassRefPtr<HTMLTitleElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<HTMLTitleElement> create(Document&);
String text() const;
void setText(const String&);
private:
- HTMLTitleElement(const QualifiedName&, Document&);
+ explicit HTMLTitleElement(Document&);
virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
virtual void removedFrom(ContainerNode*) OVERRIDE;
@@ -51,11 +51,7 @@ inline bool isHTMLTitleElement(const Element* element)
return element->hasTagName(HTMLNames::titleTag);
}
-inline HTMLTitleElement* toHTMLTitleElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || isHTMLTitleElement(node));
- return static_cast<HTMLTitleElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(HTMLTitleElement, hasTagName(HTMLNames::titleTag));
} //namespace
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLTitleElement.idl b/chromium/third_party/WebKit/Source/core/html/HTMLTitleElement.idl
index f5639fe1706..291318ff11b 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLTitleElement.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLTitleElement.idl
@@ -18,6 +18,5 @@
*/
interface HTMLTitleElement : HTMLElement {
- [TreatNullAs=NullString] attribute DOMString text;
+ attribute DOMString text;
};
-
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLTrackElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLTrackElement.cpp
index dfbbc45d041..0182bcef28f 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLTrackElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLTrackElement.cpp
@@ -28,11 +28,10 @@
#include "HTMLNames.h"
#include "bindings/v8/ExceptionStatePlaceholder.h"
-#include "core/dom/Event.h"
+#include "core/events/Event.h"
#include "core/html/HTMLMediaElement.h"
-#include "core/page/ContentSecurityPolicy.h"
-#include "RuntimeEnabledFeatures.h"
-#include "core/platform/Logging.h"
+#include "core/frame/ContentSecurityPolicy.h"
+#include "platform/Logging.h"
using namespace std;
@@ -51,12 +50,11 @@ static String urlForLoggingTrack(const KURL& url)
}
#endif
-inline HTMLTrackElement::HTMLTrackElement(const QualifiedName& tagName, Document& document)
- : HTMLElement(tagName, document)
+inline HTMLTrackElement::HTMLTrackElement(Document& document)
+ : HTMLElement(trackTag, document)
, m_loadTimer(this, &HTMLTrackElement::loadTimerFired)
{
- LOG(Media, "HTMLTrackElement::HTMLTrackElement - %p", this);
- ASSERT(hasTagName(trackTag));
+ WTF_LOG(Media, "HTMLTrackElement::HTMLTrackElement - %p", this);
ScriptWrappable::init(this);
}
@@ -66,14 +64,14 @@ HTMLTrackElement::~HTMLTrackElement()
m_track->clearClient();
}
-PassRefPtr<HTMLTrackElement> HTMLTrackElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<HTMLTrackElement> HTMLTrackElement::create(Document& document)
{
- return adoptRef(new HTMLTrackElement(tagName, document));
+ return adoptRef(new HTMLTrackElement(document));
}
Node::InsertionNotificationRequest HTMLTrackElement::insertedInto(ContainerNode* insertionPoint)
{
- LOG(Media, "HTMLTrackElement::insertedInto");
+ WTF_LOG(Media, "HTMLTrackElement::insertedInto");
// Since we've moved to a new parent, we may now be able to load.
scheduleLoad();
@@ -94,86 +92,44 @@ void HTMLTrackElement::removedFrom(ContainerNode* insertionPoint)
void HTMLTrackElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
{
- if (RuntimeEnabledFeatures::videoTrackEnabled()) {
- if (name == srcAttr) {
- if (!value.isEmpty())
- scheduleLoad();
- else if (m_track)
- m_track->removeAllCues();
-
- // 4.8.10.12.3 Sourcing out-of-band text tracks
- // As the kind, label, and srclang attributes are set, changed, or removed, the text track must update accordingly...
- } else if (name == kindAttr)
- track()->setKind(value.lower());
- else if (name == labelAttr)
- track()->setLabel(value);
- else if (name == srclangAttr)
- track()->setLanguage(value);
- else if (name == defaultAttr)
- track()->setIsDefault(!value.isNull());
+ if (name == srcAttr) {
+ if (!value.isEmpty())
+ scheduleLoad();
+ else if (m_track)
+ m_track->removeAllCues();
+
+ // 4.8.10.12.3 Sourcing out-of-band text tracks
+ // As the kind, label, and srclang attributes are set, changed, or removed, the text track must update accordingly...
+ } else if (name == kindAttr) {
+ track()->setKind(value.lower());
+ } else if (name == labelAttr) {
+ track()->setLabel(value);
+ } else if (name == srclangAttr) {
+ track()->setLanguage(value);
+ } else if (name == idAttr) {
+ track()->setId(value);
+ } else if (name == defaultAttr) {
+ track()->setIsDefault(!value.isNull());
}
HTMLElement::parseAttribute(name, value);
}
-KURL HTMLTrackElement::src() const
-{
- return document().completeURL(getAttribute(srcAttr));
-}
-
-void HTMLTrackElement::setSrc(const String& url)
-{
- setAttribute(srcAttr, url);
-}
-
-String HTMLTrackElement::kind()
+const AtomicString& HTMLTrackElement::kind()
{
return track()->kind();
}
-void HTMLTrackElement::setKind(const String& kind)
+void HTMLTrackElement::setKind(const AtomicString& kind)
{
setAttribute(kindAttr, kind);
}
-String HTMLTrackElement::srclang() const
-{
- return getAttribute(srclangAttr);
-}
-
-void HTMLTrackElement::setSrclang(const String& srclang)
-{
- setAttribute(srclangAttr, srclang);
-}
-
-String HTMLTrackElement::label() const
-{
- return getAttribute(labelAttr);
-}
-
-void HTMLTrackElement::setLabel(const String& label)
-{
- setAttribute(labelAttr, label);
-}
-
-bool HTMLTrackElement::isDefault() const
-{
- return fastHasAttribute(defaultAttr);
-}
-
-void HTMLTrackElement::setIsDefault(bool isDefault)
-{
- setBooleanAttribute(defaultAttr, isDefault);
-}
-
LoadableTextTrack* HTMLTrackElement::ensureTrack()
{
if (!m_track) {
- // The kind attribute is an enumerated attribute, limited only to know values. It defaults to 'subtitles' if missing or invalid.
- String kind = getAttribute(kindAttr).lower();
- if (!TextTrack::isValidKindKeyword(kind))
- kind = TextTrack::subtitlesKeyword();
- m_track = LoadableTextTrack::create(this, kind, label(), srclang());
+ // kind, label and language are updated by parseAttribute
+ m_track = LoadableTextTrack::create(this);
}
return m_track.get();
}
@@ -190,16 +146,13 @@ bool HTMLTrackElement::isURLAttribute(const Attribute& attribute) const
void HTMLTrackElement::scheduleLoad()
{
- LOG(Media, "HTMLTrackElement::scheduleLoad");
+ WTF_LOG(Media, "HTMLTrackElement::scheduleLoad");
// 1. If another occurrence of this algorithm is already running for this text track and its track element,
// abort these steps, letting that other algorithm take care of this element.
if (m_loadTimer.isActive())
return;
- if (!RuntimeEnabledFeatures::videoTrackEnabled())
- return;
-
// 2. If the text track's text track mode is not set to one of hidden or showing, abort these steps.
if (ensureTrack()->mode() != TextTrack::hiddenKeyword() && ensureTrack()->mode() != TextTrack::showingKeyword())
return;
@@ -217,7 +170,7 @@ void HTMLTrackElement::loadTimerFired(Timer<HTMLTrackElement>*)
if (!fastHasAttribute(srcAttr))
return;
- LOG(Media, "HTMLTrackElement::loadTimerFired");
+ WTF_LOG(Media, "HTMLTrackElement::loadTimerFired");
// 6. Set the text track readiness state to loading.
setReadyState(HTMLTrackElement::LOADING);
@@ -228,7 +181,7 @@ void HTMLTrackElement::loadTimerFired(Timer<HTMLTrackElement>*)
// 8. If the track element's parent is a media element then let CORS mode be the state of the parent media
// element's crossorigin content attribute. Otherwise, let CORS mode be No CORS.
if (!canLoadUrl(url)) {
- didCompleteLoad(ensureTrack(), HTMLTrackElement::Failure);
+ didCompleteLoad(HTMLTrackElement::Failure);
return;
}
@@ -237,9 +190,6 @@ void HTMLTrackElement::loadTimerFired(Timer<HTMLTrackElement>*)
bool HTMLTrackElement::canLoadUrl(const KURL& url)
{
- if (!RuntimeEnabledFeatures::videoTrackEnabled())
- return false;
-
HTMLMediaElement* parent = mediaElement();
if (!parent)
return false;
@@ -253,14 +203,14 @@ bool HTMLTrackElement::canLoadUrl(const KURL& url)
return false;
if (!document().contentSecurityPolicy()->allowMediaFromSource(url)) {
- LOG(Media, "HTMLTrackElement::canLoadUrl(%s) -> rejected by Content Security Policy", urlForLoggingTrack(url).utf8().data());
+ WTF_LOG(Media, "HTMLTrackElement::canLoadUrl(%s) -> rejected by Content Security Policy", urlForLoggingTrack(url).utf8().data());
return false;
}
return dispatchBeforeLoadEvent(url.string());
}
-void HTMLTrackElement::didCompleteLoad(LoadableTextTrack*, LoadStatus status)
+void HTMLTrackElement::didCompleteLoad(LoadStatus status)
{
// 4.8.10.12.3 Sourcing out-of-band text tracks (continued)
@@ -274,7 +224,7 @@ void HTMLTrackElement::didCompleteLoad(LoadableTextTrack*, LoadStatus status)
if (status == Failure) {
setReadyState(HTMLTrackElement::TRACK_ERROR);
- dispatchEvent(Event::create(eventNames().errorEvent), IGNORE_EXCEPTION);
+ dispatchEvent(Event::create(EventTypeNames::error), IGNORE_EXCEPTION);
return;
}
@@ -285,7 +235,7 @@ void HTMLTrackElement::didCompleteLoad(LoadableTextTrack*, LoadStatus status)
// 2. If the file was successfully processed, fire a simple event named load at the
// track element.
- dispatchEvent(Event::create(eventNames().loadEvent), IGNORE_EXCEPTION);
+ dispatchEvent(Event::create(EventTypeNames::load), IGNORE_EXCEPTION);
}
// NOTE: The values in the TextTrack::ReadinessState enum must stay in sync with those in HTMLTrackElement::ReadyState.
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLTrackElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLTrackElement.h
index adfc36ee1ee..9e70146d56d 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLTrackElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLTrackElement.h
@@ -36,22 +36,10 @@ class HTMLMediaElement;
class HTMLTrackElement FINAL : public HTMLElement, public TextTrackClient {
public:
- static PassRefPtr<HTMLTrackElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<HTMLTrackElement> create(Document&);
- KURL src() const;
- void setSrc(const String&);
-
- String kind();
- void setKind(const String&);
-
- String srclang() const;
- void setSrclang(const String&);
-
- String label() const;
- void setLabel(const String&);
-
- bool isDefault() const;
- void setIsDefault(bool);
+ const AtomicString& kind();
+ void setKind(const AtomicString&);
enum ReadyState { NONE = 0, LOADING = 1, LOADED = 2, TRACK_ERROR = 3 };
ReadyState readyState();
@@ -62,12 +50,12 @@ public:
void scheduleLoad();
enum LoadStatus { Failure, Success };
- virtual void didCompleteLoad(LoadableTextTrack*, LoadStatus);
+ void didCompleteLoad(LoadStatus);
const AtomicString& mediaElementCrossOriginAttribute() const;
private:
- HTMLTrackElement(const QualifiedName&, Document&);
+ explicit HTMLTrackElement(Document&);
virtual ~HTMLTrackElement();
virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
@@ -82,25 +70,21 @@ private:
HTMLMediaElement* mediaElement() const;
// TextTrackClient
- virtual void textTrackModeChanged(TextTrack*);
- virtual void textTrackKindChanged(TextTrack*);
- virtual void textTrackAddCues(TextTrack*, const TextTrackCueList*);
- virtual void textTrackRemoveCues(TextTrack*, const TextTrackCueList*);
- virtual void textTrackAddCue(TextTrack*, PassRefPtr<TextTrackCue>);
- virtual void textTrackRemoveCue(TextTrack*, PassRefPtr<TextTrackCue>);
+ virtual void textTrackModeChanged(TextTrack*) OVERRIDE;
+ virtual void textTrackKindChanged(TextTrack*) OVERRIDE;
+ virtual void textTrackAddCues(TextTrack*, const TextTrackCueList*) OVERRIDE;
+ virtual void textTrackRemoveCues(TextTrack*, const TextTrackCueList*) OVERRIDE;
+ virtual void textTrackAddCue(TextTrack*, PassRefPtr<TextTrackCue>) OVERRIDE;
+ virtual void textTrackRemoveCue(TextTrack*, PassRefPtr<TextTrackCue>) OVERRIDE;
LoadableTextTrack* ensureTrack();
- virtual bool canLoadUrl(const KURL&);
+ bool canLoadUrl(const KURL&);
RefPtr<LoadableTextTrack> m_track;
Timer<HTMLTrackElement> m_loadTimer;
};
-inline HTMLTrackElement* toHTMLTrackElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::trackTag));
- return static_cast<HTMLTrackElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(HTMLTrackElement, hasTagName(HTMLNames::trackTag));
}
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLTrackElement.idl b/chromium/third_party/WebKit/Source/core/html/HTMLTrackElement.idl
index 9c4e1bf7064..da7e22e9e64 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLTrackElement.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLTrackElement.idl
@@ -24,12 +24,12 @@
*/
[
- EnabledAtRuntime=VideoTrack
+ RuntimeEnabled=VideoTrack
] interface HTMLTrackElement : HTMLElement {
attribute DOMString kind;
- [Reflect, URL] attribute DOMString src;
- attribute DOMString srclang;
- attribute DOMString label;
+ [Reflect, URL, PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute DOMString src;
+ [Reflect] attribute DOMString srclang;
+ [Reflect] attribute DOMString label;
[Reflect] attribute boolean default;
const unsigned short NONE = 0;
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLUListElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLUListElement.cpp
index e5b804c2de2..9eb6e55e679 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLUListElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLUListElement.cpp
@@ -30,21 +30,15 @@ namespace WebCore {
using namespace HTMLNames;
-HTMLUListElement::HTMLUListElement(const QualifiedName& tagName, Document& document)
- : HTMLElement(tagName, document)
+HTMLUListElement::HTMLUListElement(Document& document)
+ : HTMLElement(ulTag, document)
{
- ASSERT(hasTagName(ulTag));
ScriptWrappable::init(this);
}
PassRefPtr<HTMLUListElement> HTMLUListElement::create(Document& document)
{
- return adoptRef(new HTMLUListElement(ulTag, document));
-}
-
-PassRefPtr<HTMLUListElement> HTMLUListElement::create(const QualifiedName& tagName, Document& document)
-{
- return adoptRef(new HTMLUListElement(tagName, document));
+ return adoptRef(new HTMLUListElement(document));
}
bool HTMLUListElement::isPresentationAttribute(const QualifiedName& name) const
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLUListElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLUListElement.h
index 5954ed4bdf2..899467c4945 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLUListElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLUListElement.h
@@ -30,10 +30,9 @@ namespace WebCore {
class HTMLUListElement FINAL : public HTMLElement {
public:
static PassRefPtr<HTMLUListElement> create(Document&);
- static PassRefPtr<HTMLUListElement> create(const QualifiedName&, Document&);
private:
- HTMLUListElement(const QualifiedName&, Document&);
+ explicit HTMLUListElement(Document&);
virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
virtual void collectStyleForPresentationAttribute(const QualifiedName&, const AtomicString&, MutableStylePropertySet*) OVERRIDE;
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLUListElement.idl b/chromium/third_party/WebKit/Source/core/html/HTMLUListElement.idl
index e40350d83d1..d7d123ae482 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLUListElement.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLUListElement.idl
@@ -21,4 +21,3 @@ interface HTMLUListElement : HTMLElement {
[Reflect] attribute boolean compact;
[Reflect] attribute DOMString type;
};
-
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLUnknownElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLUnknownElement.h
index be493b1bf4e..1c1794c0ed5 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLUnknownElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLUnknownElement.h
@@ -51,12 +51,13 @@ private:
}
};
-inline HTMLUnknownElement* toHTMLUnknownElement(HTMLElement* element)
+inline bool isHTMLUnknownElement(const Node& node)
{
- ASSERT_WITH_SECURITY_IMPLICATION(!element || element->isHTMLUnknownElement());
- return static_cast<HTMLUnknownElement*>(element);
+ return node.isElementNode() && toHTMLElement(node).isHTMLUnknownElement();
}
+DEFINE_NODE_TYPE_CASTS_WITH_FUNCTION(HTMLUnknownElement);
+
} // namespace
#endif
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLVideoElement.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLVideoElement.cpp
index ded6f09305a..b5c1c00ebb4 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLVideoElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLVideoElement.cpp
@@ -29,32 +29,31 @@
#include "CSSPropertyNames.h"
#include "HTMLNames.h"
#include "bindings/v8/ExceptionState.h"
-#include "bindings/v8/ScriptController.h"
#include "core/dom/Attribute.h"
#include "core/dom/Document.h"
#include "core/dom/ExceptionCode.h"
#include "core/html/HTMLImageLoader.h"
#include "core/html/parser/HTMLParserIdioms.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
#include "core/rendering/RenderImage.h"
#include "core/rendering/RenderVideo.h"
+#include "platform/UserGestureIndicator.h"
namespace WebCore {
using namespace HTMLNames;
-inline HTMLVideoElement::HTMLVideoElement(const QualifiedName& tagName, Document& document, bool createdByParser)
- : HTMLMediaElement(tagName, document, createdByParser)
+inline HTMLVideoElement::HTMLVideoElement(Document& document, bool createdByParser)
+ : HTMLMediaElement(videoTag, document, createdByParser)
{
- ASSERT(hasTagName(videoTag));
ScriptWrappable::init(this);
if (document.settings())
m_defaultPosterURL = document.settings()->defaultVideoPosterURL();
}
-PassRefPtr<HTMLVideoElement> HTMLVideoElement::create(const QualifiedName& tagName, Document& document, bool createdByParser)
+PassRefPtr<HTMLVideoElement> HTMLVideoElement::create(Document& document, bool createdByParser)
{
- RefPtr<HTMLVideoElement> videoElement(adoptRef(new HTMLVideoElement(tagName, document, createdByParser)));
+ RefPtr<HTMLVideoElement> videoElement(adoptRef(new HTMLVideoElement(document, createdByParser)));
videoElement->suspendIfNeeded();
return videoElement.release();
}
@@ -143,20 +142,6 @@ unsigned HTMLVideoElement::videoHeight() const
return player()->naturalSize().height();
}
-unsigned HTMLVideoElement::width() const
-{
- bool ok;
- unsigned w = getAttribute(widthAttr).string().toUInt(&ok);
- return ok ? w : 0;
-}
-
-unsigned HTMLVideoElement::height() const
-{
- bool ok;
- unsigned h = getAttribute(heightAttr).string().toUInt(&ok);
- return ok ? h : 0;
-}
-
bool HTMLVideoElement::isURLAttribute(const Attribute& attribute) const
{
return attribute.name() == posterAttr || HTMLMediaElement::isURLAttribute(attribute);
@@ -201,7 +186,7 @@ void HTMLVideoElement::paintCurrentFrameInContext(GraphicsContext* context, cons
MediaPlayer* player = HTMLMediaElement::player();
if (!player)
return;
- player->paintCurrentFrameInContext(context, destRect);
+ player->paint(context, destRect);
}
bool HTMLVideoElement::copyVideoTextureToPlatformTexture(GraphicsContext3D* context, Platform3DObject texture, GC3Dint level, GC3Denum type, GC3Denum internalFormat, bool premultiplyAlpha, bool flipY)
@@ -219,15 +204,19 @@ bool HTMLVideoElement::hasAvailableVideoFrame() const
return player()->hasVideo() && player()->readyState() >= MediaPlayer::HaveCurrentData;
}
-void HTMLVideoElement::webkitEnterFullscreen(ExceptionState& es)
+void HTMLVideoElement::webkitEnterFullscreen(ExceptionState& exceptionState)
{
if (isFullscreen())
return;
// Generate an exception if this isn't called in response to a user gesture, or if the
// element does not support fullscreen.
- if ((userGestureRequiredForFullscreen() && !ScriptController::processingUserGesture()) || !supportsFullscreen()) {
- es.throwDOMException(InvalidStateError);
+ if (userGestureRequiredForFullscreen() && !UserGestureIndicator::processingUserGesture()) {
+ exceptionState.throwDOMException(InvalidStateError, "This element may only enter fullscreen mode in response to a user gesture ('click', for example).");
+ return;
+ }
+ if (!supportsFullscreen()) {
+ exceptionState.throwDOMException(InvalidStateError, "This element does not support fullscreen mode.");
return;
}
@@ -250,7 +239,7 @@ bool HTMLVideoElement::webkitDisplayingFullscreen()
return isFullscreen();
}
-void HTMLVideoElement::didMoveToNewDocument(Document* oldDocument)
+void HTMLVideoElement::didMoveToNewDocument(Document& oldDocument)
{
if (m_imageLoader)
m_imageLoader->elementDidMoveToNewDocument();
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLVideoElement.h b/chromium/third_party/WebKit/Source/core/html/HTMLVideoElement.h
index c93933068d2..4d729f39fa5 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLVideoElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLVideoElement.h
@@ -35,11 +35,7 @@ class HTMLImageLoader;
class HTMLVideoElement FINAL : public HTMLMediaElement {
public:
- static PassRefPtr<HTMLVideoElement> create(Document& document) { return create(HTMLNames::videoTag, document, false); }
- static PassRefPtr<HTMLVideoElement> create(const QualifiedName&, Document&, bool);
-
- unsigned width() const;
- unsigned height() const;
+ static PassRefPtr<HTMLVideoElement> create(Document&, bool createdByParser = false);
unsigned videoWidth() const;
unsigned videoHeight() const;
@@ -50,11 +46,6 @@ public:
bool webkitSupportsFullscreen();
bool webkitDisplayingFullscreen();
- // FIXME: Maintain "FullScreen" capitalization scheme for backwards compatibility.
- // https://bugs.webkit.org/show_bug.cgi?id=36081
- void webkitEnterFullScreen(ExceptionState& es) { webkitEnterFullscreen(es); }
- void webkitExitFullScreen() { webkitExitFullscreen(); }
-
// Statistics
unsigned webkitDecodedFrameCount() const;
unsigned webkitDroppedFrameCount() const;
@@ -71,24 +62,24 @@ public:
KURL posterImageURL() const;
private:
- HTMLVideoElement(const QualifiedName&, Document&, bool);
+ HTMLVideoElement(Document&, bool);
- virtual bool rendererIsNeeded(const RenderStyle&);
- virtual RenderObject* createRenderer(RenderStyle*);
+ virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE;
+ virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
virtual void attach(const AttachContext& = AttachContext()) OVERRIDE;
virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
virtual void collectStyleForPresentationAttribute(const QualifiedName&, const AtomicString&, MutableStylePropertySet*) OVERRIDE;
- virtual bool isVideo() const { return true; }
- virtual bool hasVideo() const { return player() && player()->hasVideo(); }
- virtual bool supportsFullscreen() const;
+ virtual bool isVideo() const OVERRIDE { return true; }
+ virtual bool hasVideo() const OVERRIDE { return player() && player()->hasVideo(); }
+ virtual bool supportsFullscreen() const OVERRIDE;
virtual bool isURLAttribute(const Attribute&) const OVERRIDE;
virtual const AtomicString imageSourceURL() const OVERRIDE;
- virtual bool hasAvailableVideoFrame() const;
- virtual void updateDisplayState();
- virtual void didMoveToNewDocument(Document* oldDocument) OVERRIDE;
- virtual void setDisplayMode(DisplayMode);
+ bool hasAvailableVideoFrame() const;
+ virtual void updateDisplayState() OVERRIDE;
+ virtual void didMoveToNewDocument(Document& oldDocument) OVERRIDE;
+ virtual void setDisplayMode(DisplayMode) OVERRIDE;
OwnPtr<HTMLImageLoader> m_imageLoader;
@@ -105,11 +96,7 @@ inline bool isHTMLVideoElement(const Element* element)
return element->hasTagName(HTMLNames::videoTag);
}
-inline HTMLVideoElement* toHTMLVideoElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || isHTMLVideoElement(node));
- return static_cast<HTMLVideoElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(HTMLVideoElement, hasTagName(HTMLNames::videoTag));
} //namespace
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLVideoElement.idl b/chromium/third_party/WebKit/Source/core/html/HTMLVideoElement.idl
index 2b2ab0d2294..4448cd23542 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLVideoElement.idl
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLVideoElement.idl
@@ -24,29 +24,29 @@
*/
[
- EnabledAtRuntime=Media
+ RuntimeEnabled=Media
] interface HTMLVideoElement : HTMLMediaElement {
[Reflect] attribute unsigned long width;
[Reflect] attribute unsigned long height;
readonly attribute unsigned long videoWidth;
readonly attribute unsigned long videoHeight;
- [Reflect, URL] attribute DOMString poster;
+ [Reflect, URL, PerWorldBindings, ActivityLogging=SetterForIsolatedWorlds] attribute DOMString poster;
- readonly attribute boolean webkitSupportsFullscreen;
- readonly attribute boolean webkitDisplayingFullscreen;
+ [MeasureAs=PrefixedVideoSupportsFullscreen] readonly attribute boolean webkitSupportsFullscreen;
+ [MeasureAs=PrefixedVideoDisplayingFullscreen] readonly attribute boolean webkitDisplayingFullscreen;
- [RaisesException, PerWorldBindings, ActivityLog=Access] void webkitEnterFullscreen();
- void webkitExitFullscreen();
+ [MeasureAs=PrefixedVideoEnterFullscreen, RaisesException, PerWorldBindings, ActivityLogging=ForAllWorlds] void webkitEnterFullscreen();
+ [MeasureAs=PrefixedVideoExitFullscreen] void webkitExitFullscreen();
// Note the different capitalization of the "S" in FullScreen.
- [RaisesException, PerWorldBindings, ActivityLog=Access] void webkitEnterFullScreen();
- void webkitExitFullScreen();
+ [MeasureAs=PrefixedVideoEnterFullScreen, ImplementedAs=webkitEnterFullscreen, RaisesException, PerWorldBindings, ActivityLogging=ForAllWorlds] void webkitEnterFullScreen();
+ [MeasureAs=PrefixedVideoExitFullScreen, ImplementedAs=webkitExitFullscreen] void webkitExitFullScreen();
// The number of frames that have been decoded and made available for
// playback.
- readonly attribute unsigned long webkitDecodedFrameCount;
+ [MeasureAs=PrefixedVideoDecodedFrameCount] readonly attribute unsigned long webkitDecodedFrameCount;
// The number of decoded frames that have been dropped by the player
// for performance reasons during playback.
- readonly attribute unsigned long webkitDroppedFrameCount;
+ [MeasureAs=PrefixedVideoDroppedFrameCount] readonly attribute unsigned long webkitDroppedFrameCount;
};
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLViewSourceDocument.cpp b/chromium/third_party/WebKit/Source/core/html/HTMLViewSourceDocument.cpp
index e5dd879b1ba..4a55226d0b4 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLViewSourceDocument.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLViewSourceDocument.cpp
@@ -33,7 +33,9 @@
#include "core/html/HTMLBaseElement.h"
#include "core/html/HTMLBodyElement.h"
#include "core/html/HTMLDivElement.h"
+#include "core/html/HTMLHeadElement.h"
#include "core/html/HTMLHtmlElement.h"
+#include "core/html/HTMLSpanElement.h"
#include "core/html/HTMLTableCellElement.h"
#include "core/html/HTMLTableElement.h"
#include "core/html/HTMLTableRowElement.h"
@@ -65,7 +67,8 @@ void HTMLViewSourceDocument::createContainingTable()
{
RefPtr<HTMLHtmlElement> html = HTMLHtmlElement::create(*this);
parserAppendChild(html);
- html->lazyAttach();
+ RefPtr<HTMLHeadElement> head = HTMLHeadElement::create(*this);
+ html->parserAppendChild(head);
RefPtr<HTMLBodyElement> body = HTMLBodyElement::create(*this);
html->parserAppendChild(body);
@@ -96,8 +99,7 @@ void HTMLViewSourceDocument::addSource(const String& source, HTMLToken& token)
processDoctypeToken(source, token);
break;
case HTMLToken::EndOfFile:
- if (!m_tbody->hasChildNodes())
- addLine(String());
+ processEndOfFileToken(source, token);
break;
case HTMLToken::StartTag:
case HTMLToken::EndTag:
@@ -119,6 +121,13 @@ void HTMLViewSourceDocument::processDoctypeToken(const String& source, HTMLToken
m_current = m_td;
}
+void HTMLViewSourceDocument::processEndOfFileToken(const String& source, HTMLToken&)
+{
+ m_current = addSpanWithClassName("webkit-html-end-of-file");
+ addText(source, "webkit-html-end-of-file");
+ m_current = m_td;
+}
+
void HTMLViewSourceDocument::processTagToken(const String& source, HTMLToken& token)
{
m_current = addSpanWithClassName("webkit-html-tag");
@@ -142,7 +151,7 @@ void HTMLViewSourceDocument::processTagToken(const String& source, HTMLToken& to
index = addRange(source, index, iter->nameRange.end - token.startIndex(), "webkit-html-attribute-name");
if (tagName == baseTag && name == hrefAttr)
- m_current = addBase(value);
+ addBase(value);
index = addRange(source, index, iter->valueRange.start - token.startIndex(), "");
@@ -173,7 +182,7 @@ PassRefPtr<Element> HTMLViewSourceDocument::addSpanWithClassName(const AtomicStr
return m_current;
}
- RefPtr<HTMLElement> span = HTMLElement::create(spanTag, *this);
+ RefPtr<HTMLSpanElement> span = HTMLSpanElement::create(*this);
span->setAttribute(classAttr, className);
m_current->parserAppendChild(span);
return span.release();
@@ -188,7 +197,7 @@ void HTMLViewSourceDocument::addLine(const AtomicString& className)
// Create a cell that will hold the line number (it is generated in the stylesheet using counters).
RefPtr<HTMLTableCellElement> td = HTMLTableCellElement::create(tdTag, *this);
td->setAttribute(classAttr, "webkit-line-number");
- td->setAttribute(valueAttr, String::number(++m_lineNumber));
+ td->setIntegralAttribute(valueAttr, ++m_lineNumber);
trow->parserAppendChild(td);
// Create a second cell for the line contents
@@ -197,12 +206,6 @@ void HTMLViewSourceDocument::addLine(const AtomicString& className)
trow->parserAppendChild(td);
m_current = m_td = td;
-#ifdef DEBUG_LINE_NUMBERS
- RefPtr<Text> lineNumberText = Text::create(*this, String::number(parser()->lineNumber() + 1) + " ");
- td->addChild(lineNumberText);
- lineNumberText->lazyAttach();
-#endif
-
// Open up the needed spans.
if (!className.isEmpty()) {
if (className == "webkit-html-attribute-name" || className == "webkit-html-attribute-value")
@@ -267,7 +270,7 @@ int HTMLViewSourceDocument::addRange(const String& source, int start, int end, c
PassRefPtr<Element> HTMLViewSourceDocument::addBase(const AtomicString& href)
{
- RefPtr<HTMLBaseElement> base = HTMLBaseElement::create(baseTag, *this);
+ RefPtr<HTMLBaseElement> base = HTMLBaseElement::create(*this);
base->setAttribute(hrefAttr, href);
m_current->parserAppendChild(base);
return base.release();
diff --git a/chromium/third_party/WebKit/Source/core/html/HTMLViewSourceDocument.h b/chromium/third_party/WebKit/Source/core/html/HTMLViewSourceDocument.h
index d35cad2fea8..a1988cc7e2c 100644
--- a/chromium/third_party/WebKit/Source/core/html/HTMLViewSourceDocument.h
+++ b/chromium/third_party/WebKit/Source/core/html/HTMLViewSourceDocument.h
@@ -48,6 +48,7 @@ private:
virtual PassRefPtr<DocumentParser> createParser() OVERRIDE;
void processDoctypeToken(const String& source, HTMLToken&);
+ void processEndOfFileToken(const String& source, HTMLToken&);
void processTagToken(const String& source, HTMLToken&);
void processCommentToken(const String& source, HTMLToken&);
void processCharacterToken(const String& source, HTMLToken&);
diff --git a/chromium/third_party/WebKit/Source/core/html/ImageData.h b/chromium/third_party/WebKit/Source/core/html/ImageData.h
index 0032ebb1070..5015885998b 100644
--- a/chromium/third_party/WebKit/Source/core/html/ImageData.h
+++ b/chromium/third_party/WebKit/Source/core/html/ImageData.h
@@ -30,7 +30,7 @@
#define ImageData_h
#include "bindings/v8/ScriptWrappable.h"
-#include "core/platform/graphics/IntSize.h"
+#include "platform/geometry/IntSize.h"
#include "wtf/RefCounted.h"
#include "wtf/RefPtr.h"
#include "wtf/Uint8ClampedArray.h"
diff --git a/chromium/third_party/WebKit/Source/core/html/ImageData.idl b/chromium/third_party/WebKit/Source/core/html/ImageData.idl
index ca7d61c90ec..06847999097 100644
--- a/chromium/third_party/WebKit/Source/core/html/ImageData.idl
+++ b/chromium/third_party/WebKit/Source/core/html/ImageData.idl
@@ -27,7 +27,7 @@
*/
[
- CustomToV8
+ Custom=Wrap,
] interface ImageData {
readonly attribute long width;
readonly attribute long height;
diff --git a/chromium/third_party/WebKit/Source/core/html/ImageDocument.cpp b/chromium/third_party/WebKit/Source/core/html/ImageDocument.cpp
index 23b02c33498..aaeff99d644 100644
--- a/chromium/third_party/WebKit/Source/core/html/ImageDocument.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/ImageDocument.cpp
@@ -27,10 +27,10 @@
#include "HTMLNames.h"
#include "bindings/v8/ExceptionStatePlaceholder.h"
-#include "core/dom/EventListener.h"
-#include "core/dom/EventNames.h"
-#include "core/dom/MouseEvent.h"
#include "core/dom/RawDataDocumentParser.h"
+#include "core/events/EventListener.h"
+#include "core/events/MouseEvent.h"
+#include "core/events/ThreadLocalEventNames.h"
#include "core/fetch/ImageResource.h"
#include "core/html/HTMLBodyElement.h"
#include "core/html/HTMLHeadElement.h"
@@ -40,11 +40,10 @@
#include "core/loader/DocumentLoader.h"
#include "core/loader/FrameLoader.h"
#include "core/loader/FrameLoaderClient.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameView.h"
-#include "core/page/Page.h"
-#include "core/page/Settings.h"
-#include "core/platform/LocalizedStrings.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
+#include "core/frame/Settings.h"
+#include "wtf/text/StringBuilder.h"
using std::min;
@@ -71,7 +70,7 @@ private:
{
}
- virtual void handleEvent(ScriptExecutionContext*, Event*);
+ virtual void handleEvent(ExecutionContext*, Event*);
ImageDocument* m_doc;
};
@@ -94,7 +93,7 @@ private:
{
}
- virtual size_t appendBytes(const char*, size_t) OVERRIDE;
+ virtual void appendBytes(const char*, size_t) OVERRIDE;
virtual void finish();
};
@@ -106,19 +105,32 @@ static float pageZoomFactor(const Document* document)
return frame ? frame->pageZoomFactor() : 1;
}
-size_t ImageDocumentParser::appendBytes(const char* data, size_t length)
+static String imageTitle(const String& filename, const IntSize& size)
+{
+ StringBuilder result;
+ result.append(filename);
+ result.append(" (");
+ // FIXME: Localize numbers. Safari/OSX shows localized numbers with group
+ // separaters. For example, "1,920x1,080".
+ result.append(String::number(size.width()));
+ result.append(static_cast<UChar>(0xD7)); // U+00D7 (multiplication sign)
+ result.append(String::number(size.height()));
+ result.append(')');
+ return result.toString();
+}
+
+void ImageDocumentParser::appendBytes(const char* data, size_t length)
{
if (!length)
- return 0;
+ return;
Frame* frame = document()->frame();
Settings* settings = frame->settings();
- if (!frame->loader()->client()->allowImage(!settings || settings->areImagesEnabled(), document()->url()))
- return 0;
+ if (!frame->loader().client()->allowImage(!settings || settings->imagesEnabled(), document()->url()))
+ return;
document()->cachedImage()->appendData(data, length);
document()->imageUpdated();
- return 0;
}
void ImageDocumentParser::finish()
@@ -126,7 +138,7 @@ void ImageDocumentParser::finish()
if (!isStopped() && document()->imageElement()) {
ImageResource* cachedImage = document()->cachedImage();
cachedImage->finish();
- cachedImage->setResponse(document()->frame()->loader()->documentLoader()->response());
+ cachedImage->setResponse(document()->frame()->loader().documentLoader()->response());
// Report the natural image size in the page title, regardless of zoom level.
// At a zoom level of 1 the image is guaranteed to have an integer size.
@@ -170,8 +182,8 @@ void ImageDocument::createDocumentStructure()
appendChild(rootElement);
rootElement->insertedByParser();
- if (frame() && frame()->loader())
- frame()->loader()->dispatchDocumentElementAvailable();
+ if (frame())
+ frame()->loader().dispatchDocumentElementAvailable();
RefPtr<HTMLHeadElement> head = HTMLHeadElement::create(*this);
RefPtr<HTMLMetaElement> meta = HTMLMetaElement::create(*this);
@@ -202,7 +214,7 @@ void ImageDocument::createDocumentStructure()
float ImageDocument::scale() const
{
- if (!m_imageElement || &m_imageElement->document() != this)
+ if (!m_imageElement || m_imageElement->document() != this)
return 1.0f;
FrameView* view = frame()->view();
@@ -220,7 +232,7 @@ float ImageDocument::scale() const
void ImageDocument::resizeImageToFit()
{
- if (!m_imageElement || &m_imageElement->document() != this || pageZoomFactor(this) > 1)
+ if (!m_imageElement || m_imageElement->document() != this || pageZoomFactor(this) > 1)
return;
LayoutSize imageSize = m_imageElement->cachedImage()->imageSizeForRenderer(m_imageElement->renderer(), pageZoomFactor(this));
@@ -275,7 +287,7 @@ void ImageDocument::imageUpdated()
void ImageDocument::restoreImageSize()
{
- if (!m_imageElement || !m_imageSizeIsKnown || &m_imageElement->document() != this || pageZoomFactor(this) < 1)
+ if (!m_imageElement || !m_imageSizeIsKnown || m_imageElement->document() != this || pageZoomFactor(this) < 1)
return;
LayoutSize imageSize = m_imageElement->cachedImage()->imageSizeForRenderer(m_imageElement->renderer(), 1.0f);
@@ -292,7 +304,7 @@ void ImageDocument::restoreImageSize()
bool ImageDocument::imageFitsInWindow() const
{
- if (!m_imageElement || &m_imageElement->document() != this)
+ if (!m_imageElement || m_imageElement->document() != this)
return true;
FrameView* view = frame()->view();
@@ -307,7 +319,7 @@ bool ImageDocument::imageFitsInWindow() const
void ImageDocument::windowSizeChanged()
{
- if (!m_imageElement || !m_imageSizeIsKnown || &m_imageElement->document() != this)
+ if (!m_imageElement || !m_imageSizeIsKnown || m_imageElement->document() != this)
return;
bool fitsInWindow = imageFitsInWindow();
@@ -348,7 +360,7 @@ ImageResource* ImageDocument::cachedImage()
bool ImageDocument::shouldShrinkToFit() const
{
- return frame()->page()->settings().shrinksStandaloneImagesToFit() && frame()->page()->mainFrame() == frame();
+ return frame()->settings()->shrinksStandaloneImagesToFit() && frame()->isMainFrame();
}
void ImageDocument::dispose()
@@ -359,11 +371,11 @@ void ImageDocument::dispose()
// --------
-void ImageEventListener::handleEvent(ScriptExecutionContext*, Event* event)
+void ImageEventListener::handleEvent(ExecutionContext*, Event* event)
{
- if (event->type() == eventNames().resizeEvent)
+ if (event->type() == EventTypeNames::resize)
m_doc->windowSizeChanged();
- else if (event->type() == eventNames().clickEvent && event->isMouseEvent()) {
+ else if (event->type() == EventTypeNames::click && event->isMouseEvent()) {
MouseEvent* mouseEvent = toMouseEvent(event);
m_doc->imageClicked(mouseEvent->x(), mouseEvent->y());
}
diff --git a/chromium/third_party/WebKit/Source/core/html/ImageDocument.h b/chromium/third_party/WebKit/Source/core/html/ImageDocument.h
index 9400112ca68..896a46261da 100644
--- a/chromium/third_party/WebKit/Source/core/html/ImageDocument.h
+++ b/chromium/third_party/WebKit/Source/core/html/ImageDocument.h
@@ -72,20 +72,7 @@ private:
bool m_shouldShrinkImage;
};
-inline ImageDocument* toImageDocument(Document* document)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!document || document->isImageDocument());
- return static_cast<ImageDocument*>(document);
-}
-
-inline const ImageDocument* toImageDocument(const Document* document)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!document || document->isImageDocument());
- return static_cast<const ImageDocument*>(document);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toImageDocument(const ImageDocument*);
+DEFINE_DOCUMENT_TYPE_CASTS(ImageDocument);
}
diff --git a/chromium/third_party/WebKit/Source/core/html/LabelableElement.cpp b/chromium/third_party/WebKit/Source/core/html/LabelableElement.cpp
index 5eeab71514c..ad302516baf 100644
--- a/chromium/third_party/WebKit/Source/core/html/LabelableElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/LabelableElement.cpp
@@ -44,7 +44,7 @@ PassRefPtr<NodeList> LabelableElement::labels()
if (!supportLabels())
return 0;
- return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<LabelsNodeList>(this, LabelsNodeListType, starAtom);
+ return ensureRareData().ensureNodeLists().addCacheWithAtomicName<LabelsNodeList>(this, LabelsNodeListType, starAtom);
}
} // namespace Webcore
diff --git a/chromium/third_party/WebKit/Source/core/html/LabelableElement.h b/chromium/third_party/WebKit/Source/core/html/LabelableElement.h
index 259285c67c9..f3d2188dbfb 100644
--- a/chromium/third_party/WebKit/Source/core/html/LabelableElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/LabelableElement.h
@@ -50,12 +50,13 @@ private:
virtual bool isLabelable() const OVERRIDE FINAL { return true; }
};
-inline LabelableElement* toLabelableElement(Node* node)
+inline bool isLabelableElement(const Node& node)
{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || (node->isHTMLElement() && toHTMLElement(node)->isLabelable()));
- return static_cast<LabelableElement*>(node);
+ return node.isHTMLElement() && toHTMLElement(node).isLabelable();
}
+DEFINE_NODE_TYPE_CASTS_WITH_FUNCTION(LabelableElement);
+
} // namespace WebCore
#endif
diff --git a/chromium/third_party/WebKit/Source/core/html/LabelsNodeList.cpp b/chromium/third_party/WebKit/Source/core/html/LabelsNodeList.cpp
index a822c47ae6f..a3a6579370f 100644
--- a/chromium/third_party/WebKit/Source/core/html/LabelsNodeList.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/LabelsNodeList.cpp
@@ -33,8 +33,8 @@ namespace WebCore {
using namespace HTMLNames;
-LabelsNodeList::LabelsNodeList(Node* forNode)
- : LiveNodeList(forNode, LabelsNodeListType, InvalidateOnForAttrChange, NodeListIsRootedAtDocument)
+LabelsNodeList::LabelsNodeList(Node* ownerNode)
+ : LiveNodeList(ownerNode, LabelsNodeListType, InvalidateOnForAttrChange, NodeListIsRootedAtDocument)
{
}
diff --git a/chromium/third_party/WebKit/Source/core/html/LabelsNodeList.h b/chromium/third_party/WebKit/Source/core/html/LabelsNodeList.h
index 83339a406c5..0e5b125ca69 100644
--- a/chromium/third_party/WebKit/Source/core/html/LabelsNodeList.h
+++ b/chromium/third_party/WebKit/Source/core/html/LabelsNodeList.h
@@ -30,17 +30,18 @@
namespace WebCore {
-class LabelsNodeList : public LiveNodeList {
+class LabelsNodeList FINAL : public LiveNodeList {
public:
- static PassRefPtr<LabelsNodeList> create(Node* forNode, CollectionType type, const AtomicString&)
+ static PassRefPtr<LabelsNodeList> create(Node* ownerNode, CollectionType type, const AtomicString&)
{
ASSERT_UNUSED(type, type == LabelsNodeListType);
- return adoptRef(new LabelsNodeList(forNode));
+ return adoptRef(new LabelsNodeList(ownerNode));
}
- ~LabelsNodeList();
+
+ virtual ~LabelsNodeList();
protected:
- LabelsNodeList(Node* forNode);
+ explicit LabelsNodeList(Node*);
virtual bool nodeMatches(Element*) const;
};
diff --git a/chromium/third_party/WebKit/Source/core/html/LinkImport.cpp b/chromium/third_party/WebKit/Source/core/html/LinkImport.cpp
index 37945f83088..18e5d4a51a7 100644
--- a/chromium/third_party/WebKit/Source/core/html/LinkImport.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/LinkImport.cpp
@@ -33,20 +33,21 @@
#include "core/dom/Document.h"
#include "core/fetch/CrossOriginAccessControl.h"
-#include "core/html/HTMLImportLoader.h"
+#include "core/html/HTMLImportChild.h"
#include "core/html/HTMLImportsController.h"
#include "core/html/HTMLLinkElement.h"
namespace WebCore {
-PassRefPtr<LinkImport> LinkImport::create(HTMLLinkElement* owner)
+PassOwnPtr<LinkImport> LinkImport::create(HTMLLinkElement* owner)
{
- return adoptRef(new LinkImport(owner));
+ return adoptPtr(new LinkImport(owner));
}
LinkImport::LinkImport(HTMLLinkElement* owner)
: LinkResource(owner)
+ , m_loader(0)
{
}
@@ -68,7 +69,7 @@ void LinkImport::process()
return;
if (!m_owner)
return;
- if (!m_owner->document().frame() && !m_owner->document().import())
+ if (!shouldLoadResource())
return;
if (!m_owner->document().import()) {
@@ -84,22 +85,19 @@ void LinkImport::process()
HTMLImport* parent = m_owner->document().import();
HTMLImportsController* controller = parent->controller();
- m_loader = controller->createLoader(parent, builder.build(true));
+ m_loader = controller->load(parent, this, builder.build(true));
if (!m_loader) {
didFinish();
return;
}
-
- m_loader->addClient(this);
}
void LinkImport::clear()
{
m_owner = 0;
-
if (m_loader) {
- m_loader->removeClient(this);
- m_loader.clear();
+ m_loader->clearClient();
+ m_loader = 0;
}
}
@@ -115,6 +113,11 @@ void LinkImport::didFinish()
m_owner->scheduleEvent();
}
+void LinkImport::loaderWillBeDestroyed()
+{
+ clear();
+}
+
bool LinkImport::hasLoaded() const
{
return m_loader && m_loader->isLoaded();
diff --git a/chromium/third_party/WebKit/Source/core/html/LinkImport.h b/chromium/third_party/WebKit/Source/core/html/LinkImport.h
index 4003f88525e..bc2ec95bfb5 100644
--- a/chromium/third_party/WebKit/Source/core/html/LinkImport.h
+++ b/chromium/third_party/WebKit/Source/core/html/LinkImport.h
@@ -31,24 +31,25 @@
#ifndef LinkImport_h
#define LinkImport_h
-#include "core/html/HTMLImportLoaderClient.h"
+#include "core/html/HTMLImportChildClient.h"
#include "core/html/LinkResource.h"
#include "wtf/FastAllocBase.h"
+#include "wtf/PassOwnPtr.h"
#include "wtf/RefPtr.h"
namespace WebCore {
class Document;
-class HTMLImportLoader;
+class HTMLImportChild;
//
// A LinkResource subclasss used for @rel=import.
//
-class LinkImport : public LinkResource, public HTMLImportLoaderClient {
+class LinkImport : public LinkResource, public HTMLImportChildClient {
WTF_MAKE_FAST_ALLOCATED;
public:
- static PassRefPtr<LinkImport> create(HTMLLinkElement* owner);
+ static PassOwnPtr<LinkImport> create(HTMLLinkElement* owner);
explicit LinkImport(HTMLLinkElement* owner);
virtual ~LinkImport();
@@ -59,15 +60,16 @@ public:
virtual void ownerRemoved() OVERRIDE;
virtual bool hasLoaded() const OVERRIDE;
- // HTMLImportLoaderClient
+ // HTMLImportChildClient
virtual void didFinish() OVERRIDE;
+ virtual void loaderWillBeDestroyed() OVERRIDE;
Document* importedDocument() const;
private:
void clear();
- RefPtr<HTMLImportLoader> m_loader;
+ HTMLImportChild* m_loader;
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/html/LinkRelAttribute.cpp b/chromium/third_party/WebKit/Source/core/html/LinkRelAttribute.cpp
index 68b1c78e003..0c2f32be4ca 100644
--- a/chromium/third_party/WebKit/Source/core/html/LinkRelAttribute.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/LinkRelAttribute.cpp
@@ -32,6 +32,8 @@
#include "config.h"
#include "core/html/LinkRelAttribute.h"
+#include "wtf/text/WTFString.h"
+
namespace WebCore {
LinkRelAttribute::LinkRelAttribute()
diff --git a/chromium/third_party/WebKit/Source/core/html/LinkRelAttribute.h b/chromium/third_party/WebKit/Source/core/html/LinkRelAttribute.h
index 8dddfef3681..a124012055d 100644
--- a/chromium/third_party/WebKit/Source/core/html/LinkRelAttribute.h
+++ b/chromium/third_party/WebKit/Source/core/html/LinkRelAttribute.h
@@ -34,6 +34,10 @@
#include "core/dom/IconURL.h"
+namespace WTF {
+class String;
+}
+
namespace WebCore {
class LinkRelAttribute {
diff --git a/chromium/third_party/WebKit/Source/core/html/LinkRelAttributeTest.cpp b/chromium/third_party/WebKit/Source/core/html/LinkRelAttributeTest.cpp
new file mode 100644
index 00000000000..beac0e64066
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/html/LinkRelAttributeTest.cpp
@@ -0,0 +1,88 @@
+/*
+ * Copyright (c) 2013, Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/html/LinkRelAttribute.h"
+
+#include "wtf/text/CString.h"
+#include <gtest/gtest.h>
+
+using namespace WebCore;
+
+namespace {
+
+static inline void testLinkRelAttribute(String value, bool isStyleSheet, IconType iconType, bool isAlternate, bool isDNSPrefetch, bool isLinkSubresource, bool isLinkPrerender, bool isImport = false)
+{
+ LinkRelAttribute linkRelAttribute(value);
+ ASSERT_EQ(isStyleSheet, linkRelAttribute.isStyleSheet()) << value.utf8().data();
+ ASSERT_EQ(iconType, linkRelAttribute.iconType()) << value.utf8().data();
+ ASSERT_EQ(isAlternate, linkRelAttribute.isAlternate()) << value.utf8().data();
+ ASSERT_EQ(isDNSPrefetch, linkRelAttribute.isDNSPrefetch()) << value.utf8().data();
+ ASSERT_EQ(isLinkSubresource, linkRelAttribute.isLinkSubresource()) << value.utf8().data();
+ ASSERT_EQ(isLinkPrerender, linkRelAttribute.isLinkPrerender()) << value.utf8().data();
+ ASSERT_EQ(isImport, linkRelAttribute.isImport()) << value.utf8().data();
+}
+
+TEST(CoreLinkRelAttribute, Constructor)
+{
+ testLinkRelAttribute("stylesheet", true, InvalidIcon, false, false, false, false);
+ testLinkRelAttribute("sTyLeShEeT", true, InvalidIcon, false, false, false, false);
+
+ testLinkRelAttribute("icon", false, Favicon, false, false, false, false);
+ testLinkRelAttribute("iCoN", false, Favicon, false, false, false, false);
+ testLinkRelAttribute("shortcut icon", false, Favicon, false, false, false, false);
+ testLinkRelAttribute("sHoRtCuT iCoN", false, Favicon, false, false, false, false);
+
+#if ENABLE(TOUCH_ICON_LOADING)
+ testLinkRelAttribute("apple-touch-icon", false, TouchIcon, false, false, false, false);
+ testLinkRelAttribute("aPpLe-tOuCh-IcOn", false, TouchIcon, false, false, false, false);
+
+ testLinkRelAttribute("apple-touch-icon-precomposed", false, TouchPrecomposedIcon, false, false, false, false);
+ testLinkRelAttribute("aPpLe-tOuCh-IcOn-pReCoMpOsEd", false, TouchPrecomposedIcon, false, false, false, false);
+#endif
+
+ testLinkRelAttribute("dns-prefetch", false, InvalidIcon, false, true, false, false);
+ testLinkRelAttribute("dNs-pReFeTcH", false, InvalidIcon, false, true, false, false);
+
+ testLinkRelAttribute("alternate stylesheet", true, InvalidIcon, true, false, false, false);
+ testLinkRelAttribute("stylesheet alternate", true, InvalidIcon, true, false, false, false);
+ testLinkRelAttribute("aLtErNaTe sTyLeShEeT", true, InvalidIcon, true, false, false, false);
+ testLinkRelAttribute("sTyLeShEeT aLtErNaTe", true, InvalidIcon, true, false, false, false);
+
+ testLinkRelAttribute("stylesheet icon prerender aLtErNaTe", true, Favicon, true, false, false, true);
+ testLinkRelAttribute("alternate subresource", false, InvalidIcon, true, false, true, false);
+ testLinkRelAttribute("alternate icon stylesheet", true, Favicon, true, false, false, false);
+
+ testLinkRelAttribute("import", false, InvalidIcon, false, false, false, false, true);
+ // "import" is mutually exclusive and "stylesheet" wins when they conflict.
+ testLinkRelAttribute("stylesheet import", true, InvalidIcon, false, false, false, false, false);
+}
+
+} // namespace
diff --git a/chromium/third_party/WebKit/Source/core/html/LinkResource.cpp b/chromium/third_party/WebKit/Source/core/html/LinkResource.cpp
index 5e74a89c656..ef239527a14 100644
--- a/chromium/third_party/WebKit/Source/core/html/LinkResource.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/LinkResource.cpp
@@ -32,6 +32,7 @@
#include "core/html/LinkResource.h"
#include "HTMLNames.h"
+#include "core/html/HTMLImport.h"
#include "core/html/HTMLLinkElement.h"
namespace WebCore {
@@ -47,9 +48,22 @@ LinkResource::~LinkResource()
{
}
+bool LinkResource::shouldLoadResource() const
+{
+ return m_owner->document().frame() || m_owner->document().import();
+}
+
+Frame* LinkResource::loadingFrame() const
+{
+ HTMLImport* import = m_owner->document().import();
+ if (!import)
+ return m_owner->document().frame();
+ return import->master()->document().frame();
+}
+
LinkRequestBuilder::LinkRequestBuilder(HTMLLinkElement* owner)
: m_owner(owner)
- , m_url(m_owner->getNonEmptyURLAttribute(hrefAttr))
+ , m_url(owner->getNonEmptyURLAttribute(hrefAttr))
{
m_charset = m_owner->getAttribute(charsetAttr);
if (m_charset.isEmpty() && m_owner->document().frame())
diff --git a/chromium/third_party/WebKit/Source/core/html/LinkResource.h b/chromium/third_party/WebKit/Source/core/html/LinkResource.h
index b4eeb3d44ad..a922639d216 100644
--- a/chromium/third_party/WebKit/Source/core/html/LinkResource.h
+++ b/chromium/third_party/WebKit/Source/core/html/LinkResource.h
@@ -32,15 +32,15 @@
#define LinkResource_h
#include "core/fetch/FetchRequest.h"
-#include "weborigin/KURL.h"
-#include "wtf/RefCounted.h"
+#include "platform/weborigin/KURL.h"
#include "wtf/text/WTFString.h"
namespace WebCore {
class HTMLLinkElement;
-class LinkResource : public RefCounted<LinkResource> {
+class LinkResource {
+ WTF_MAKE_NONCOPYABLE(LinkResource); WTF_MAKE_FAST_ALLOCATED;
public:
enum Type {
Style,
@@ -50,6 +50,9 @@ public:
explicit LinkResource(HTMLLinkElement*);
virtual ~LinkResource();
+ bool shouldLoadResource() const;
+ Frame* loadingFrame() const;
+
virtual Type type() const = 0;
virtual void process() = 0;
virtual void ownerRemoved() = 0;
@@ -65,13 +68,13 @@ public:
bool isValid() const { return !m_url.isEmpty() && m_url.isValid(); }
const KURL& url() const { return m_url; }
- const String& charset() const { return m_charset; }
+ const AtomicString& charset() const { return m_charset; }
FetchRequest build(bool blocking) const;
private:
HTMLLinkElement* m_owner;
KURL m_url;
- String m_charset;
+ AtomicString m_charset;
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/html/MediaController.cpp b/chromium/third_party/WebKit/Source/core/html/MediaController.cpp
index afc7cc96efa..e93bbc1df30 100644
--- a/chromium/third_party/WebKit/Source/core/html/MediaController.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/MediaController.cpp
@@ -26,12 +26,13 @@
#include "config.h"
#include "core/html/MediaController.h"
+#include "bindings/v8/ExceptionMessages.h"
#include "bindings/v8/ExceptionState.h"
#include "bindings/v8/ExceptionStatePlaceholder.h"
#include "core/dom/ExceptionCode.h"
#include "core/html/HTMLMediaElement.h"
#include "core/html/TimeRanges.h"
-#include "core/platform/Clock.h"
+#include "platform/Clock.h"
#include "wtf/CurrentTime.h"
#include "wtf/StdLibExtras.h"
#include "wtf/text/AtomicString.h"
@@ -39,12 +40,12 @@
using namespace WebCore;
using namespace std;
-PassRefPtr<MediaController> MediaController::create(ScriptExecutionContext* context)
+PassRefPtr<MediaController> MediaController::create(ExecutionContext* context)
{
return adoptRef(new MediaController(context));
}
-MediaController::MediaController(ScriptExecutionContext* context)
+MediaController::MediaController(ExecutionContext* context)
: m_paused(false)
, m_defaultPlaybackRate(1)
, m_volume(1)
@@ -56,7 +57,7 @@ MediaController::MediaController(ScriptExecutionContext* context)
, m_clearPositionTimer(this, &MediaController::clearPositionTimerFired)
, m_closedCaptionsVisible(false)
, m_clock(Clock::create())
- , m_scriptExecutionContext(context)
+ , m_executionContext(context)
, m_timeupdateTimer(this, &MediaController::timeupdateTimerFired)
, m_previousTimeupdateTime(0)
{
@@ -158,7 +159,7 @@ double MediaController::currentTime() const
return m_position;
}
-void MediaController::setCurrentTime(double time, ExceptionState& es)
+void MediaController::setCurrentTime(double time, ExceptionState& exceptionState)
{
// When the user agent is to seek the media controller to a particular new playback position,
// it must follow these steps:
@@ -174,7 +175,7 @@ void MediaController::setCurrentTime(double time, ExceptionState& es)
// Seek each slaved media element to the new playback position relative to the media element timeline.
for (size_t index = 0; index < m_mediaElements.size(); ++index)
- m_mediaElements[index]->seek(time, es);
+ m_mediaElements[index]->seek(time, exceptionState);
scheduleTimeupdateEvent();
}
@@ -188,7 +189,7 @@ void MediaController::unpause()
// the user agent must change the MediaController into a playing media controller,
m_paused = false;
// queue a task to fire a simple event named play at the MediaController,
- scheduleEvent(eventNames().playEvent);
+ scheduleEvent(EventTypeNames::play);
// and then report the controller state of the MediaController.
reportControllerState();
}
@@ -213,7 +214,7 @@ void MediaController::pause()
// then the user agent must change the MediaController into a paused media controller,
m_paused = true;
// queue a task to fire a simple event named pause at the MediaController,
- scheduleEvent(eventNames().pauseEvent);
+ scheduleEvent(EventTypeNames::pause);
// and then report the controller state of the MediaController.
reportControllerState();
}
@@ -228,7 +229,7 @@ void MediaController::setDefaultPlaybackRate(double rate)
m_defaultPlaybackRate = rate;
// then queue a task to fire a simple event named ratechange at the MediaController.
- scheduleEvent(eventNames().ratechangeEvent);
+ scheduleEvent(EventTypeNames::ratechange);
}
double MediaController::playbackRate() const
@@ -249,10 +250,10 @@ void MediaController::setPlaybackRate(double rate)
m_mediaElements[index]->updatePlaybackRate();
// then queue a task to fire a simple event named ratechange at the MediaController.
- scheduleEvent(eventNames().ratechangeEvent);
+ scheduleEvent(EventTypeNames::ratechange);
}
-void MediaController::setVolume(double level, ExceptionState& es)
+void MediaController::setVolume(double level, ExceptionState& exceptionState)
{
if (m_volume == level)
return;
@@ -260,7 +261,7 @@ void MediaController::setVolume(double level, ExceptionState& es)
// If the new value is outside the range 0.0 to 1.0 inclusive, then, on setting, an
// IndexSizeError exception must be raised instead.
if (level < 0 || level > 1) {
- es.throwDOMException(IndexSizeError);
+ exceptionState.throwDOMException(IndexSizeError, ExceptionMessages::failedToSet("volume", "MediaController", "The value provided (" + String::number(level) + ") is not in the range [0.0, 1.0]."));
return;
}
@@ -269,7 +270,7 @@ void MediaController::setVolume(double level, ExceptionState& es)
m_volume = level;
// and queue a task to fire a simple event named volumechange at the MediaController.
- scheduleEvent(eventNames().volumechangeEvent);
+ scheduleEvent(EventTypeNames::volumechange);
for (size_t index = 0; index < m_mediaElements.size(); ++index)
m_mediaElements[index]->updateVolume();
@@ -285,7 +286,7 @@ void MediaController::setMuted(bool flag)
m_muted = flag;
// and queue a task to fire a simple event named volumechange at the MediaController.
- scheduleEvent(eventNames().volumechangeEvent);
+ scheduleEvent(EventTypeNames::volumechange);
for (size_t index = 0; index < m_mediaElements.size(); ++index)
m_mediaElements[index]->updateVolume();
@@ -334,15 +335,15 @@ static AtomicString eventNameForReadyState(MediaControllerInterface::ReadyState
{
switch (state) {
case MediaControllerInterface::HAVE_NOTHING:
- return eventNames().emptiedEvent;
+ return EventTypeNames::emptied;
case MediaControllerInterface::HAVE_METADATA:
- return eventNames().loadedmetadataEvent;
+ return EventTypeNames::loadedmetadata;
case MediaControllerInterface::HAVE_CURRENT_DATA:
- return eventNames().loadeddataEvent;
+ return EventTypeNames::loadeddata;
case MediaControllerInterface::HAVE_FUTURE_DATA:
- return eventNames().canplayEvent;
+ return EventTypeNames::canplay;
case MediaControllerInterface::HAVE_ENOUGH_DATA:
- return eventNames().canplaythroughEvent;
+ return EventTypeNames::canplaythrough;
default:
ASSERT_NOT_REACHED();
return nullAtom;
@@ -433,7 +434,7 @@ void MediaController::updatePlaybackState()
m_paused = true;
// and then fires a simple event named pause at the MediaController object.
- scheduleEvent(eventNames().pauseEvent);
+ scheduleEvent(EventTypeNames::pause);
}
}
@@ -443,17 +444,17 @@ void MediaController::updatePlaybackState()
AtomicString eventName;
switch (newPlaybackState) {
case WAITING:
- eventName = eventNames().waitingEvent;
+ eventName = EventTypeNames::waiting;
m_clock->stop();
m_timeupdateTimer.stop();
break;
case ENDED:
- eventName = eventNames().endedEvent;
+ eventName = EventTypeNames::ended;
m_clock->stop();
m_timeupdateTimer.stop();
break;
case PLAYING:
- eventName = eventNames().playingEvent;
+ eventName = EventTypeNames::playing;
m_clock->start();
startTimeupdateTimer();
break;
@@ -629,7 +630,7 @@ bool MediaController::hasCurrentSrc() const
const AtomicString& MediaController::interfaceName() const
{
- return eventNames().interfaceForMediaController;
+ return EventTargetNames::MediaController;
}
// The spec says to fire periodic timeupdate events (those sent while playing) every
@@ -657,6 +658,6 @@ void MediaController::scheduleTimeupdateEvent()
if (timedelta < maxTimeupdateEventFrequency)
return;
- scheduleEvent(eventNames().timeupdateEvent);
+ scheduleEvent(EventTypeNames::timeupdate);
m_previousTimeupdateTime = now;
}
diff --git a/chromium/third_party/WebKit/Source/core/html/MediaController.h b/chromium/third_party/WebKit/Source/core/html/MediaController.h
index 2a833de8ade..5b31cc24e18 100644
--- a/chromium/third_party/WebKit/Source/core/html/MediaController.h
+++ b/chromium/third_party/WebKit/Source/core/html/MediaController.h
@@ -27,10 +27,10 @@
#define MediaController_h
#include "bindings/v8/ScriptWrappable.h"
-#include "core/dom/Event.h"
-#include "core/dom/EventTarget.h"
+#include "core/events/Event.h"
+#include "core/events/EventTarget.h"
#include "core/html/MediaControllerInterface.h"
-#include "core/platform/Timer.h"
+#include "platform/Timer.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefCounted.h"
#include "wtf/Vector.h"
@@ -41,11 +41,12 @@ class Clock;
class Event;
class ExceptionState;
class HTMLMediaElement;
-class ScriptExecutionContext;
+class ExecutionContext;
-class MediaController : public RefCounted<MediaController>, public ScriptWrappable, public MediaControllerInterface, public EventTarget {
+class MediaController : public RefCounted<MediaController>, public ScriptWrappable, public MediaControllerInterface, public EventTargetWithInlineData {
+ REFCOUNTED_EVENT_TARGET(MediaController);
public:
- static PassRefPtr<MediaController> create(ScriptExecutionContext*);
+ static PassRefPtr<MediaController> create(ExecutionContext*);
virtual ~MediaController();
void addMediaElement(HTMLMediaElement*);
@@ -103,12 +104,10 @@ public:
bool isBlocked() const;
- // EventTarget
- using RefCounted<MediaController>::ref;
- using RefCounted<MediaController>::deref;
+ void clearExecutionContext() { m_executionContext = 0; }
private:
- MediaController(ScriptExecutionContext*);
+ MediaController(ExecutionContext*);
void reportControllerState();
void updateReadyState();
void updatePlaybackState();
@@ -123,13 +122,8 @@ private:
void startTimeupdateTimer();
// EventTarget
- virtual void refEventTarget() { ref(); }
- virtual void derefEventTarget() { deref(); }
- virtual const AtomicString& interfaceName() const;
- virtual ScriptExecutionContext* scriptExecutionContext() const { return m_scriptExecutionContext; };
- virtual EventTargetData* eventTargetData() { return &m_eventTargetData; }
- virtual EventTargetData* ensureEventTargetData() { return &m_eventTargetData; }
- EventTargetData m_eventTargetData;
+ virtual const AtomicString& interfaceName() const OVERRIDE;
+ virtual ExecutionContext* executionContext() const OVERRIDE { return m_executionContext; }
friend class HTMLMediaElement;
friend class MediaControllerEventListener;
@@ -146,8 +140,8 @@ private:
mutable Timer<MediaController> m_clearPositionTimer;
String m_mediaGroup;
bool m_closedCaptionsVisible;
- PassRefPtr<Clock> m_clock;
- ScriptExecutionContext* m_scriptExecutionContext;
+ OwnPtr<Clock> m_clock;
+ ExecutionContext* m_executionContext;
Timer<MediaController> m_timeupdateTimer;
double m_previousTimeupdateTime;
};
diff --git a/chromium/third_party/WebKit/Source/core/html/MediaController.idl b/chromium/third_party/WebKit/Source/core/html/MediaController.idl
index 81171ec6b77..ad46115d889 100644
--- a/chromium/third_party/WebKit/Source/core/html/MediaController.idl
+++ b/chromium/third_party/WebKit/Source/core/html/MediaController.idl
@@ -24,15 +24,15 @@
*/
[
- EnabledAtRuntime=Media,
Constructor,
- ConstructorCallWith=ScriptExecutionContext
+ ConstructorCallWith=ExecutionContext,
+ RuntimeEnabled=Media,
] interface MediaController : EventTarget {
readonly attribute TimeRanges buffered;
readonly attribute TimeRanges seekable;
readonly attribute double duration;
- [SetterRaisesException] attribute double currentTime;
+ [RaisesException=Setter] attribute double currentTime;
readonly attribute boolean paused;
readonly attribute TimeRanges played;
@@ -44,6 +44,6 @@
attribute double defaultPlaybackRate;
attribute double playbackRate;
- [SetterRaisesException] attribute double volume;
+ [RaisesException=Setter] attribute double volume;
attribute boolean muted;
};
diff --git a/chromium/third_party/WebKit/Source/core/html/MediaDocument.cpp b/chromium/third_party/WebKit/Source/core/html/MediaDocument.cpp
index 874a45e7779..ef6207470d6 100644
--- a/chromium/third_party/WebKit/Source/core/html/MediaDocument.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/MediaDocument.cpp
@@ -29,10 +29,10 @@
#include "HTMLNames.h"
#include "bindings/v8/ExceptionStatePlaceholder.h"
-#include "core/dom/EventNames.h"
-#include "core/dom/KeyboardEvent.h"
#include "core/dom/NodeTraversal.h"
#include "core/dom/RawDataDocumentParser.h"
+#include "core/events/KeyboardEvent.h"
+#include "core/events/ThreadLocalEventNames.h"
#include "core/html/HTMLBodyElement.h"
#include "core/html/HTMLHeadElement.h"
#include "core/html/HTMLHtmlElement.h"
@@ -41,8 +41,8 @@
#include "core/html/HTMLVideoElement.h"
#include "core/loader/DocumentLoader.h"
#include "core/loader/FrameLoader.h"
-#include "core/page/Frame.h"
-#include "core/platform/chromium/KeyboardCodes.h"
+#include "core/frame/Frame.h"
+#include "platform/KeyboardCodes.h"
namespace WebCore {
@@ -63,7 +63,7 @@ private:
{
}
- virtual size_t appendBytes(const char*, size_t) OVERRIDE;
+ virtual void appendBytes(const char*, size_t) OVERRIDE;
void createDocumentStructure();
@@ -78,7 +78,7 @@ void MediaDocumentParser::createDocumentStructure()
document()->appendChild(rootElement);
if (document()->frame())
- document()->frame()->loader()->dispatchDocumentElementAvailable();
+ document()->frame()->loader().dispatchDocumentElementAvailable();
RefPtr<HTMLHeadElement> head = HTMLHeadElement::create(*document());
RefPtr<HTMLMetaElement> meta = HTMLMetaElement::create(*document());
@@ -108,14 +108,13 @@ void MediaDocumentParser::createDocumentStructure()
m_didBuildDocumentStructure = true;
}
-size_t MediaDocumentParser::appendBytes(const char*, size_t)
+void MediaDocumentParser::appendBytes(const char*, size_t)
{
if (m_didBuildDocumentStructure)
- return 0;
+ return;
createDocumentStructure();
finish();
- return 0;
}
MediaDocument::MediaDocument(const DocumentInit& initializer)
@@ -134,7 +133,7 @@ static inline HTMLVideoElement* descendentVideoElement(Node* root)
{
ASSERT(root);
- for (Node* node = root; node; node = NodeTraversal::next(node, root)) {
+ for (Node* node = root; node; node = NodeTraversal::next(*node, root)) {
if (isHTMLVideoElement(node))
return toHTMLVideoElement(node);
}
@@ -148,7 +147,7 @@ void MediaDocument::defaultEventHandler(Event* event)
if (!targetNode)
return;
- if (event->type() == eventNames().keydownEvent && event->isKeyboardEvent()) {
+ if (event->type() == EventTypeNames::keydown && event->isKeyboardEvent()) {
HTMLVideoElement* video = descendentVideoElement(targetNode);
if (!video)
return;
diff --git a/chromium/third_party/WebKit/Source/core/html/MediaError.idl b/chromium/third_party/WebKit/Source/core/html/MediaError.idl
index 376159d6b7c..4cf13edcef5 100644
--- a/chromium/third_party/WebKit/Source/core/html/MediaError.idl
+++ b/chromium/third_party/WebKit/Source/core/html/MediaError.idl
@@ -24,12 +24,12 @@
*/
[
- EnabledAtRuntime=Media
+ RuntimeEnabled=Media
] interface MediaError {
- const unsigned short MEDIA_ERR_ABORTED = 1;
- const unsigned short MEDIA_ERR_NETWORK = 2;
- const unsigned short MEDIA_ERR_DECODE = 3;
- const unsigned short MEDIA_ERR_SRC_NOT_SUPPORTED = 4;
- const unsigned short MEDIA_ERR_ENCRYPTED = 5;
- readonly attribute unsigned short code;
+ const unsigned short MEDIA_ERR_ABORTED = 1;
+ const unsigned short MEDIA_ERR_NETWORK = 2;
+ const unsigned short MEDIA_ERR_DECODE = 3;
+ const unsigned short MEDIA_ERR_SRC_NOT_SUPPORTED = 4;
+ [RuntimeEnabled=EncryptedMediaAnyVersion] const unsigned short MEDIA_ERR_ENCRYPTED = 5;
+ readonly attribute unsigned short code;
};
diff --git a/chromium/third_party/WebKit/Source/core/html/MediaFragmentURIParser.cpp b/chromium/third_party/WebKit/Source/core/html/MediaFragmentURIParser.cpp
index c3775816328..f887a05f163 100644
--- a/chromium/third_party/WebKit/Source/core/html/MediaFragmentURIParser.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/MediaFragmentURIParser.cpp
@@ -26,7 +26,7 @@
#include "config.h"
#include "core/html/MediaFragmentURIParser.h"
-#include "core/platform/graphics/MediaPlayer.h"
+#include "platform/graphics/media/MediaPlayer.h"
#include "wtf/text/CString.h"
#include "wtf/text/StringBuilder.h"
#include "wtf/text/WTFString.h"
diff --git a/chromium/third_party/WebKit/Source/core/html/MediaFragmentURIParser.h b/chromium/third_party/WebKit/Source/core/html/MediaFragmentURIParser.h
index 9348be0d9fa..df43c07a71c 100644
--- a/chromium/third_party/WebKit/Source/core/html/MediaFragmentURIParser.h
+++ b/chromium/third_party/WebKit/Source/core/html/MediaFragmentURIParser.h
@@ -26,7 +26,7 @@
#ifndef MediaFragmentURIParser_h
#define MediaFragmentURIParser_h
-#include "weborigin/KURL.h"
+#include "platform/weborigin/KURL.h"
#include "wtf/Vector.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/html/MediaKeyError.idl b/chromium/third_party/WebKit/Source/core/html/MediaKeyError.idl
index ea442f8cfd9..d746c4c03fb 100644
--- a/chromium/third_party/WebKit/Source/core/html/MediaKeyError.idl
+++ b/chromium/third_party/WebKit/Source/core/html/MediaKeyError.idl
@@ -24,7 +24,7 @@
*/
[
- EnabledAtRuntime=EncryptedMediaAnyVersion
+ RuntimeEnabled=EncryptedMediaAnyVersion
] interface MediaKeyError {
const unsigned short MEDIA_KEYERR_UNKNOWN = 1;
const unsigned short MEDIA_KEYERR_CLIENT = 2;
@@ -33,5 +33,5 @@
const unsigned short MEDIA_KEYERR_HARDWARECHANGE = 5;
const unsigned short MEDIA_KEYERR_DOMAIN = 6;
readonly attribute unsigned short code;
- [Conditional=ENCRYPTED_MEDIA_V2, EnabledAtRuntime=EncryptedMedia] readonly attribute unsigned long systemCode;
+ [RuntimeEnabled=EncryptedMedia] readonly attribute unsigned long systemCode;
};
diff --git a/chromium/third_party/WebKit/Source/core/html/MediaKeyEvent.cpp b/chromium/third_party/WebKit/Source/core/html/MediaKeyEvent.cpp
index 3e9e27c56e3..38f02b701bd 100644
--- a/chromium/third_party/WebKit/Source/core/html/MediaKeyEvent.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/MediaKeyEvent.cpp
@@ -26,7 +26,7 @@
#include "config.h"
#include "core/html/MediaKeyEvent.h"
-#include "core/dom/EventNames.h"
+#include "core/events/ThreadLocalEventNames.h"
#include "wtf/Uint8Array.h"
namespace WebCore {
@@ -60,7 +60,7 @@ MediaKeyEvent::~MediaKeyEvent()
const AtomicString& MediaKeyEvent::interfaceName() const
{
- return eventNames().interfaceForMediaKeyEvent;
+ return EventNames::MediaKeyEvent;
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/html/MediaKeyEvent.h b/chromium/third_party/WebKit/Source/core/html/MediaKeyEvent.h
index 1261d233396..370abafce6b 100644
--- a/chromium/third_party/WebKit/Source/core/html/MediaKeyEvent.h
+++ b/chromium/third_party/WebKit/Source/core/html/MediaKeyEvent.h
@@ -26,7 +26,7 @@
#ifndef MediaKeyEvent_h
#define MediaKeyEvent_h
-#include "core/dom/Event.h"
+#include "core/events/Event.h"
#include "core/html/MediaKeyError.h"
namespace WebCore {
@@ -65,6 +65,7 @@ public:
Uint8Array* message() const { return m_message.get(); }
String defaultURL() const { return m_defaultURL; }
MediaKeyError* errorCode() const { return m_errorCode.get(); }
+ MediaKeyError* errorCode(bool& isNull) const { isNull = !m_errorCode; return m_errorCode.get(); }
unsigned short systemCode() const { return m_systemCode; }
private:
diff --git a/chromium/third_party/WebKit/Source/core/html/MediaKeyEvent.idl b/chromium/third_party/WebKit/Source/core/html/MediaKeyEvent.idl
index 297eabea0f2..ec80808d745 100644
--- a/chromium/third_party/WebKit/Source/core/html/MediaKeyEvent.idl
+++ b/chromium/third_party/WebKit/Source/core/html/MediaKeyEvent.idl
@@ -24,15 +24,15 @@
*/
[
- EnabledAtRuntime=LegacyEncryptedMedia,
- ConstructorTemplate=Event
+ EventConstructor,
+ RuntimeEnabled=PrefixedEncryptedMedia,
] interface MediaKeyEvent : Event {
[InitializedByEventConstructor] readonly attribute DOMString keySystem;
[InitializedByEventConstructor] readonly attribute DOMString sessionId;
[InitializedByEventConstructor] readonly attribute Uint8Array initData;
[InitializedByEventConstructor] readonly attribute Uint8Array message;
[InitializedByEventConstructor] readonly attribute DOMString defaultURL;
- [InitializedByEventConstructor] readonly attribute MediaKeyError errorCode;
+ [InitializedByEventConstructor] readonly attribute MediaKeyError? errorCode;
[InitializedByEventConstructor] readonly attribute unsigned short systemCode;
};
diff --git a/chromium/third_party/WebKit/Source/core/html/PluginDocument.cpp b/chromium/third_party/WebKit/Source/core/html/PluginDocument.cpp
index 2f8ae7e58c1..366ee643ba3 100644
--- a/chromium/third_party/WebKit/Source/core/html/PluginDocument.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/PluginDocument.cpp
@@ -34,8 +34,8 @@
#include "core/loader/DocumentLoader.h"
#include "core/loader/FrameLoader.h"
#include "core/loader/FrameLoaderClient.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameView.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
#include "core/plugins/PluginView.h"
#include "core/rendering/RenderEmbeddedObject.h"
@@ -58,7 +58,7 @@ private:
{
}
- virtual size_t appendBytes(const char*, size_t) OVERRIDE;
+ virtual void appendBytes(const char*, size_t) OVERRIDE;
virtual void finish() OVERRIDE;
@@ -81,13 +81,13 @@ void PluginDocumentParser::createDocumentStructure()
return;
// FIXME: Why does this check settings?
- if (!frame->settings() || !frame->loader()->allowPlugins(NotAboutToInstantiatePlugin))
+ if (!frame->settings() || !frame->loader().allowPlugins(NotAboutToInstantiatePlugin))
return;
RefPtr<HTMLHtmlElement> rootElement = HTMLHtmlElement::create(*document());
rootElement->insertedByParser();
document()->appendChild(rootElement);
- frame->loader()->dispatchDocumentElementAvailable();
+ frame->loader().dispatchDocumentElementAvailable();
RefPtr<HTMLBodyElement> body = HTMLBodyElement::create(*document());
body->setAttribute(marginwidthAttr, "0");
@@ -99,7 +99,7 @@ void PluginDocumentParser::createDocumentStructure()
m_embedElement->setAttribute(widthAttr, "100%");
m_embedElement->setAttribute(heightAttr, "100%");
m_embedElement->setAttribute(nameAttr, "plugin");
- m_embedElement->setAttribute(srcAttr, document()->url().string());
+ m_embedElement->setAttribute(srcAttr, AtomicString(document()->url().string()));
m_embedElement->setAttribute(typeAttr, document()->loader()->mimeType());
body->appendChild(m_embedElement);
@@ -115,17 +115,15 @@ void PluginDocumentParser::createDocumentStructure()
view->didReceiveResponse(document()->loader()->response());
}
-size_t PluginDocumentParser::appendBytes(const char* data, size_t length)
+void PluginDocumentParser::appendBytes(const char* data, size_t length)
{
if (!m_embedElement)
createDocumentStructure();
if (!length)
- return 0;
+ return;
if (PluginView* view = pluginView())
view->didReceiveData(data, length);
-
- return 0;
}
void PluginDocumentParser::finish()
@@ -191,7 +189,7 @@ void PluginDocument::cancelManualPluginLoad()
if (!shouldLoadPluginManually())
return;
- DocumentLoader* documentLoader = frame()->loader()->activeDocumentLoader();
+ DocumentLoader* documentLoader = frame()->loader().activeDocumentLoader();
documentLoader->cancelMainResourceLoad(ResourceError::cancelledError(documentLoader->request().url()));
setShouldLoadPluginManually(false);
}
diff --git a/chromium/third_party/WebKit/Source/core/html/PluginDocument.h b/chromium/third_party/WebKit/Source/core/html/PluginDocument.h
index 9764a9dbedf..590cb30303f 100644
--- a/chromium/third_party/WebKit/Source/core/html/PluginDocument.h
+++ b/chromium/third_party/WebKit/Source/core/html/PluginDocument.h
@@ -61,26 +61,7 @@ private:
RefPtr<Node> m_pluginNode;
};
-inline PluginDocument* toPluginDocument(Document* document)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!document || document->isPluginDocument());
- return static_cast<PluginDocument*>(document);
-}
-
-inline const PluginDocument* toPluginDocument(const Document* document)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!document || document->isPluginDocument());
- return static_cast<const PluginDocument*>(document);
-}
-
-inline PluginDocument& toPluginDocument(Document& document)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(document.isPluginDocument());
- return static_cast<PluginDocument&>(document);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toPluginDocument(const PluginDocument*);
+DEFINE_DOCUMENT_TYPE_CASTS(PluginDocument);
}
diff --git a/chromium/third_party/WebKit/Source/core/html/PublicURLManager.cpp b/chromium/third_party/WebKit/Source/core/html/PublicURLManager.cpp
index 013503898dd..09157de9df7 100644
--- a/chromium/third_party/WebKit/Source/core/html/PublicURLManager.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/PublicURLManager.cpp
@@ -28,19 +28,19 @@
#include "core/html/PublicURLManager.h"
#include "core/html/URLRegistry.h"
-#include "weborigin/KURL.h"
+#include "platform/weborigin/KURL.h"
#include "wtf/text/StringHash.h"
namespace WebCore {
-PassOwnPtr<PublicURLManager> PublicURLManager::create(ScriptExecutionContext* context)
+PassOwnPtr<PublicURLManager> PublicURLManager::create(ExecutionContext* context)
{
OwnPtr<PublicURLManager> publicURLManager(adoptPtr(new PublicURLManager(context)));
publicURLManager->suspendIfNeeded();
return publicURLManager.release();
}
-PublicURLManager::PublicURLManager(ScriptExecutionContext* context)
+PublicURLManager::PublicURLManager(ExecutionContext* context)
: ActiveDOMObject(context)
, m_isStopped(false)
{
diff --git a/chromium/third_party/WebKit/Source/core/html/PublicURLManager.h b/chromium/third_party/WebKit/Source/core/html/PublicURLManager.h
index 7b9f2f7208b..08848772701 100644
--- a/chromium/third_party/WebKit/Source/core/html/PublicURLManager.h
+++ b/chromium/third_party/WebKit/Source/core/html/PublicURLManager.h
@@ -35,7 +35,7 @@
namespace WebCore {
class KURL;
-class ScriptExecutionContext;
+class ExecutionContext;
class SecurityOrigin;
class URLRegistry;
class URLRegistrable;
@@ -43,7 +43,7 @@ class URLRegistrable;
class PublicURLManager : public ActiveDOMObject {
WTF_MAKE_FAST_ALLOCATED;
public:
- static PassOwnPtr<PublicURLManager> create(ScriptExecutionContext*);
+ static PassOwnPtr<PublicURLManager> create(ExecutionContext*);
void registerURL(SecurityOrigin*, const KURL&, URLRegistrable*);
void revoke(const KURL&);
@@ -52,7 +52,7 @@ public:
virtual void stop() OVERRIDE;
private:
- PublicURLManager(ScriptExecutionContext*);
+ PublicURLManager(ExecutionContext*);
typedef HashSet<String> URLSet;
typedef HashMap<URLRegistry*, URLSet > RegistryURLMap;
diff --git a/chromium/third_party/WebKit/Source/core/html/RadioNodeList.cpp b/chromium/third_party/WebKit/Source/core/html/RadioNodeList.cpp
index 0522f12ec50..f7cbfa982a2 100644
--- a/chromium/third_party/WebKit/Source/core/html/RadioNodeList.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/RadioNodeList.cpp
@@ -88,11 +88,7 @@ bool RadioNodeList::checkElementMatchesRadioNodeListFilter(Element* testElement)
{
ASSERT(testElement->hasTagName(objectTag) || testElement->isFormControlElement());
if (ownerNode()->hasTagName(formTag)) {
- HTMLFormElement* formElement = 0;
- if (testElement->hasTagName(objectTag))
- formElement = toHTMLObjectElement(testElement)->form();
- else
- formElement = toHTMLFormControlElement(testElement)->form();
+ HTMLFormElement* formElement = toHTMLElement(testElement)->formOwner();
if (!formElement || formElement != ownerNode())
return false;
}
diff --git a/chromium/third_party/WebKit/Source/core/html/RadioNodeList.h b/chromium/third_party/WebKit/Source/core/html/RadioNodeList.h
index d0bdbf304f1..b735b0c3377 100644
--- a/chromium/third_party/WebKit/Source/core/html/RadioNodeList.h
+++ b/chromium/third_party/WebKit/Source/core/html/RadioNodeList.h
@@ -32,26 +32,25 @@
namespace WebCore {
-class RadioNodeList : public LiveNodeList {
+class RadioNodeList FINAL : public LiveNodeList {
public:
- static PassRefPtr<RadioNodeList> create(Node* rootNode, CollectionType type, const AtomicString& name)
+ static PassRefPtr<RadioNodeList> create(Node* ownerNode, CollectionType type, const AtomicString& name)
{
ASSERT_UNUSED(type, type == RadioNodeListType);
- return adoptRef(new RadioNodeList(rootNode, name));
+ return adoptRef(new RadioNodeList(ownerNode, name));
}
- ~RadioNodeList();
+ virtual ~RadioNodeList();
String value() const;
void setValue(const String&);
-protected:
- virtual bool nodeMatches(Element*) const;
-
private:
RadioNodeList(Node*, const AtomicString& name);
bool checkElementMatchesRadioNodeListFilter(Element*) const;
+ virtual bool nodeMatches(Element*) const OVERRIDE;
+
AtomicString m_name;
};
diff --git a/chromium/third_party/WebKit/Source/core/html/TimeRanges.cpp b/chromium/third_party/WebKit/Source/core/html/TimeRanges.cpp
index 7d424255551..407ff32353b 100644
--- a/chromium/third_party/WebKit/Source/core/html/TimeRanges.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/TimeRanges.cpp
@@ -40,6 +40,17 @@ TimeRanges::TimeRanges(double start, double end)
add(start, end);
}
+PassRefPtr<TimeRanges> TimeRanges::create(const blink::WebTimeRanges& webRanges)
+{
+ RefPtr<TimeRanges> ranges = TimeRanges::create();
+
+ unsigned size = webRanges.size();
+ for (unsigned i = 0; i < size; ++i)
+ ranges->add(webRanges[i].start, webRanges[i].end);
+
+ return ranges.release();
+}
+
PassRefPtr<TimeRanges> TimeRanges::copy() const
{
RefPtr<TimeRanges> newSession = TimeRanges::create();
@@ -102,19 +113,19 @@ void TimeRanges::unionWith(const TimeRanges* other)
m_ranges.swap(unioned->m_ranges);
}
-double TimeRanges::start(unsigned index, ExceptionState& es) const
+double TimeRanges::start(unsigned index, ExceptionState& exceptionState) const
{
if (index >= length()) {
- es.throwDOMException(IndexSizeError);
+ exceptionState.throwDOMException(IndexSizeError, "The index provided (" + String::number(index) + ") is not less than the object's length (" + String::number(length()) + ").");
return 0;
}
return m_ranges[index].m_start;
}
-double TimeRanges::end(unsigned index, ExceptionState& es) const
+double TimeRanges::end(unsigned index, ExceptionState& exceptionState) const
{
if (index >= length()) {
- es.throwDOMException(IndexSizeError);
+ exceptionState.throwDOMException(IndexSizeError, "The index provided (" + String::number(index) + ") is not less than the object's length (" + String::number(length()) + ").");
return 0;
}
return m_ranges[index].m_end;
diff --git a/chromium/third_party/WebKit/Source/core/html/TimeRanges.h b/chromium/third_party/WebKit/Source/core/html/TimeRanges.h
index 39a16d36f6c..a3c82e53f87 100644
--- a/chromium/third_party/WebKit/Source/core/html/TimeRanges.h
+++ b/chromium/third_party/WebKit/Source/core/html/TimeRanges.h
@@ -27,6 +27,7 @@
#define TimeRanges_h
#include "bindings/v8/ScriptWrappable.h"
+#include "public/platform/WebTimeRange.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefCounted.h"
#include "wtf/Vector.h"
@@ -47,6 +48,7 @@ public:
{
return adoptRef(new TimeRanges(start, end));
}
+ static PassRefPtr<TimeRanges> create(const blink::WebTimeRanges&);
PassRefPtr<TimeRanges> copy() const;
void intersectWith(const TimeRanges*);
diff --git a/chromium/third_party/WebKit/Source/core/html/TimeRanges.idl b/chromium/third_party/WebKit/Source/core/html/TimeRanges.idl
index 3aa6b886a0b..e6e6e95cceb 100644
--- a/chromium/third_party/WebKit/Source/core/html/TimeRanges.idl
+++ b/chromium/third_party/WebKit/Source/core/html/TimeRanges.idl
@@ -24,7 +24,7 @@
*/
[
- EnabledAtRuntime=Media
+ RuntimeEnabled=Media
] interface TimeRanges {
readonly attribute unsigned long length;
[RaisesException] double start(unsigned long index);
diff --git a/chromium/third_party/WebKit/Source/core/html/TimeRangesTest.cpp b/chromium/third_party/WebKit/Source/core/html/TimeRangesTest.cpp
index 9c92149210d..584761c36ea 100644
--- a/chromium/third_party/WebKit/Source/core/html/TimeRangesTest.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/TimeRangesTest.cpp
@@ -61,6 +61,16 @@ TEST(TimeRanges, SingleRange)
ASSERT_RANGE("{ [1,2) }", TimeRanges::create(1, 2));
}
+TEST(TimeRanges, CreateFromWebTimeRanges)
+{
+ blink::WebTimeRanges webRanges(static_cast<size_t>(2));
+ webRanges[0].start = 0;
+ webRanges[0].end = 1;
+ webRanges[1].start = 2;
+ webRanges[1].end = 3;
+ ASSERT_RANGE("{ [0,1) [2,3) }", TimeRanges::create(webRanges));
+}
+
TEST(TimeRanges, AddOrder)
{
RefPtr<TimeRanges> rangeA = TimeRanges::create();
diff --git a/chromium/third_party/WebKit/Source/core/html/URL.idl b/chromium/third_party/WebKit/Source/core/html/URL.idl
deleted file mode 100644
index 265f371db82..00000000000
--- a/chromium/third_party/WebKit/Source/core/html/URL.idl
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- * Copyright (C) 2012 Motorola Mobility Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-[
- GlobalContext=Window&WorkerGlobalScope,
- Constructor,
- ImplementedAs=DOMURL
-] interface URL {
- [CallWith=ScriptExecutionContext,TreatReturnedNullStringAs=Null] static DOMString createObjectURL(Blob? blob);
- [CallWith=ScriptExecutionContext] static void revokeObjectURL(DOMString url);
-};
diff --git a/chromium/third_party/WebKit/Source/core/html/VoidCallback.h b/chromium/third_party/WebKit/Source/core/html/VoidCallback.h
index 0c3688097ee..8fdf709d5e0 100644
--- a/chromium/third_party/WebKit/Source/core/html/VoidCallback.h
+++ b/chromium/third_party/WebKit/Source/core/html/VoidCallback.h
@@ -26,14 +26,12 @@
#ifndef VoidCallback_h
#define VoidCallback_h
-#include "wtf/RefCounted.h"
-
namespace WebCore {
-class VoidCallback : public RefCounted<VoidCallback> {
+class VoidCallback {
public:
virtual ~VoidCallback() { }
- virtual bool handleEvent() = 0;
+ virtual void handleEvent() = 0;
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/html/VoidCallback.idl b/chromium/third_party/WebKit/Source/core/html/VoidCallback.idl
index d403ecc48c1..970113b0200 100644
--- a/chromium/third_party/WebKit/Source/core/html/VoidCallback.idl
+++ b/chromium/third_party/WebKit/Source/core/html/VoidCallback.idl
@@ -24,5 +24,5 @@
*/
callback interface VoidCallback {
- boolean handleEvent();
+ void handleEvent();
};
diff --git a/chromium/third_party/WebKit/Source/core/html/canvas/ANGLEInstancedArrays.cpp b/chromium/third_party/WebKit/Source/core/html/canvas/ANGLEInstancedArrays.cpp
index b2d047f558d..c7e5c9301b6 100644
--- a/chromium/third_party/WebKit/Source/core/html/canvas/ANGLEInstancedArrays.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/canvas/ANGLEInstancedArrays.cpp
@@ -33,7 +33,7 @@
#include "core/html/canvas/ANGLEInstancedArrays.h"
#include "core/html/canvas/WebGLRenderingContext.h"
-#include "core/platform/graphics/Extensions3D.h"
+#include "platform/graphics/Extensions3D.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/html/canvas/ANGLEInstancedArrays.h b/chromium/third_party/WebKit/Source/core/html/canvas/ANGLEInstancedArrays.h
index b7e11a58665..0b9f53119e0 100644
--- a/chromium/third_party/WebKit/Source/core/html/canvas/ANGLEInstancedArrays.h
+++ b/chromium/third_party/WebKit/Source/core/html/canvas/ANGLEInstancedArrays.h
@@ -32,7 +32,7 @@
#include "bindings/v8/ScriptWrappable.h"
#include "core/html/canvas/WebGLExtension.h"
-#include "core/platform/graphics/GraphicsTypes3D.h"
+#include "platform/graphics/GraphicsTypes3D.h"
#include "wtf/PassRefPtr.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/html/canvas/ArrayBufferView.idl b/chromium/third_party/WebKit/Source/core/html/canvas/ArrayBufferView.idl
index 55457319b92..478bf25d27b 100644
--- a/chromium/third_party/WebKit/Source/core/html/canvas/ArrayBufferView.idl
+++ b/chromium/third_party/WebKit/Source/core/html/canvas/ArrayBufferView.idl
@@ -24,8 +24,8 @@
*/
[
+ Custom=Wrap,
NoInterfaceObject,
- CustomToV8
] interface ArrayBufferView {
readonly attribute ArrayBuffer buffer;
readonly attribute unsigned long byteOffset;
diff --git a/chromium/third_party/WebKit/Source/core/html/canvas/Canvas2DContextAttributes.idl b/chromium/third_party/WebKit/Source/core/html/canvas/Canvas2DContextAttributes.idl
index f756bda2ff4..72e01914f14 100644
--- a/chromium/third_party/WebKit/Source/core/html/canvas/Canvas2DContextAttributes.idl
+++ b/chromium/third_party/WebKit/Source/core/html/canvas/Canvas2DContextAttributes.idl
@@ -25,8 +25,7 @@
*/
[
- NoInterfaceObject,
- EnabledAtRuntime=ExperimentalCanvasFeatures
+ NoInterfaceObject
] interface Canvas2DContextAttributes {
attribute boolean alpha;
};
diff --git a/chromium/third_party/WebKit/Source/core/html/canvas/CanvasGradient.cpp b/chromium/third_party/WebKit/Source/core/html/canvas/CanvasGradient.cpp
index 394ebf0f2a4..07e62a07e10 100644
--- a/chromium/third_party/WebKit/Source/core/html/canvas/CanvasGradient.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/canvas/CanvasGradient.cpp
@@ -46,16 +46,16 @@ CanvasGradient::CanvasGradient(const FloatPoint& p0, float r0, const FloatPoint&
ScriptWrappable::init(this);
}
-void CanvasGradient::addColorStop(float value, const String& color, ExceptionState& es)
+void CanvasGradient::addColorStop(float value, const String& color, ExceptionState& exceptionState)
{
if (!(value >= 0 && value <= 1.0f)) {
- es.throwDOMException(IndexSizeError);
+ exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
return;
}
RGBA32 rgba = 0;
if (!parseColorOrCurrentColor(rgba, color, 0 /*canvas*/)) {
- es.throwDOMException(SyntaxError);
+ exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
return;
}
diff --git a/chromium/third_party/WebKit/Source/core/html/canvas/CanvasGradient.h b/chromium/third_party/WebKit/Source/core/html/canvas/CanvasGradient.h
index 76d564b48ef..599534fb31a 100644
--- a/chromium/third_party/WebKit/Source/core/html/canvas/CanvasGradient.h
+++ b/chromium/third_party/WebKit/Source/core/html/canvas/CanvasGradient.h
@@ -28,7 +28,7 @@
#define CanvasGradient_h
#include "bindings/v8/ScriptWrappable.h"
-#include "core/platform/graphics/Gradient.h"
+#include "platform/graphics/Gradient.h"
#include "wtf/Forward.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefCounted.h"
diff --git a/chromium/third_party/WebKit/Source/core/html/canvas/CanvasPathMethods.cpp b/chromium/third_party/WebKit/Source/core/html/canvas/CanvasPathMethods.cpp
index 9104eac6c07..66a1ac99fa4 100644
--- a/chromium/third_party/WebKit/Source/core/html/canvas/CanvasPathMethods.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/canvas/CanvasPathMethods.cpp
@@ -37,8 +37,8 @@
#include "bindings/v8/ExceptionState.h"
#include "core/dom/ExceptionCode.h"
-#include "core/platform/graphics/FloatRect.h"
-#include "core/platform/graphics/transforms/AffineTransform.h"
+#include "platform/geometry/FloatRect.h"
+#include "platform/transforms/AffineTransform.h"
#include "wtf/MathExtras.h"
namespace WebCore {
@@ -107,13 +107,13 @@ void CanvasPathMethods::bezierCurveTo(float cp1x, float cp1y, float cp2x, float
m_path.addBezierCurveTo(cp1, cp2, p1);
}
-void CanvasPathMethods::arcTo(float x1, float y1, float x2, float y2, float r, ExceptionState& es)
+void CanvasPathMethods::arcTo(float x1, float y1, float x2, float y2, float r, ExceptionState& exceptionState)
{
if (!std::isfinite(x1) || !std::isfinite(y1) || !std::isfinite(x2) || !std::isfinite(y2) || !std::isfinite(r))
return;
if (r < 0) {
- es.throwDOMException(IndexSizeError);
+ exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
return;
}
@@ -140,12 +140,13 @@ float adjustEndAngle(float startAngle, float endAngle, bool anticlockwise)
/* http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#dom-context-2d-arc
* If the anticlockwise argument is false and endAngle-startAngle is equal to or greater than 2pi, or,
* if the anticlockwise argument is true and startAngle-endAngle is equal to or greater than 2pi,
- * then the arc is the whole circumference of this ellipse.
+ * then the arc is the whole circumference of this ellipse, and the point at startAngle along this circle's circumference,
+ * measured in radians clockwise from the ellipse's semi-major axis, acts as both the start point and the end point.
*/
if (!anticlockwise && endAngle - startAngle >= twoPi)
- newEndAngle = startAngle + twoPi + fmodf(endAngle - startAngle, twoPi);
+ newEndAngle = startAngle + twoPi;
else if (anticlockwise && startAngle - endAngle >= twoPi)
- newEndAngle = startAngle - twoPi - fmodf(startAngle - endAngle, twoPi);
+ newEndAngle = startAngle - twoPi;
/*
* Otherwise, the arc is the path along the circumference of this ellipse from the start point to the end point,
@@ -162,7 +163,7 @@ float adjustEndAngle(float startAngle, float endAngle, bool anticlockwise)
else if (anticlockwise && startAngle < endAngle)
newEndAngle = startAngle - (twoPi - fmodf(endAngle - startAngle, twoPi));
- ASSERT(std::abs(newEndAngle - startAngle) < 4 * piFloat);
+ ASSERT(ellipseIsRenderable(startAngle, newEndAngle));
return newEndAngle;
}
@@ -221,11 +222,11 @@ void canonicalizeAngle(float* startAngle, float* endAngle)
* Angles for P are 0 and Pi in the ellipse coordinates.
*
* To handle both cases, degenerateEllipse() lines to start angle, local maximum points(every 0.5Pi), and end angle.
- * NOTE: Before ellipse() calls this function, adjustEndAngle() is called, so endAngle - startAngle must be less than 4Pi.
+ * NOTE: Before ellipse() calls this function, adjustEndAngle() is called, so endAngle - startAngle must be equal to or less than 2Pi.
*/
void degenerateEllipse(CanvasPathMethods* path, float x, float y, float radiusX, float radiusY, float rotation, float startAngle, float endAngle, bool anticlockwise)
{
- ASSERT(std::abs(endAngle - startAngle) < 4 * piFloat);
+ ASSERT(ellipseIsRenderable(startAngle, endAngle));
ASSERT(startAngle >= 0 && startAngle < 2 * piFloat);
ASSERT((anticlockwise && (startAngle - endAngle) >= 0) || (!anticlockwise && (endAngle - startAngle) >= 0));
@@ -253,13 +254,13 @@ void degenerateEllipse(CanvasPathMethods* path, float x, float y, float radiusX,
} // namespace
-void CanvasPathMethods::arc(float x, float y, float radius, float startAngle, float endAngle, bool anticlockwise, ExceptionState& es)
+void CanvasPathMethods::arc(float x, float y, float radius, float startAngle, float endAngle, bool anticlockwise, ExceptionState& exceptionState)
{
if (!std::isfinite(x) || !std::isfinite(y) || !std::isfinite(radius) || !std::isfinite(startAngle) || !std::isfinite(endAngle))
return;
if (radius < 0) {
- es.throwDOMException(IndexSizeError);
+ exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
return;
}
@@ -277,13 +278,13 @@ void CanvasPathMethods::arc(float x, float y, float radius, float startAngle, fl
m_path.addArc(FloatPoint(x, y), radius, startAngle, adjustedEndAngle, anticlockwise);
}
-void CanvasPathMethods::ellipse(float x, float y, float radiusX, float radiusY, float rotation, float startAngle, float endAngle, bool anticlockwise, ExceptionState& es)
+void CanvasPathMethods::ellipse(float x, float y, float radiusX, float radiusY, float rotation, float startAngle, float endAngle, bool anticlockwise, ExceptionState& exceptionState)
{
if (!std::isfinite(x) || !std::isfinite(y) || !std::isfinite(radiusX) || !std::isfinite(radiusY) || !std::isfinite(rotation) || !std::isfinite(startAngle) || !std::isfinite(endAngle))
return;
if (radiusX < 0 || radiusY < 0) {
- es.throwDOMException(IndexSizeError);
+ exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
return;
}
diff --git a/chromium/third_party/WebKit/Source/core/html/canvas/CanvasPathMethods.h b/chromium/third_party/WebKit/Source/core/html/canvas/CanvasPathMethods.h
index 187bd2e103f..100f95cf055 100644
--- a/chromium/third_party/WebKit/Source/core/html/canvas/CanvasPathMethods.h
+++ b/chromium/third_party/WebKit/Source/core/html/canvas/CanvasPathMethods.h
@@ -29,7 +29,7 @@
#ifndef CanvasPathMethods_h
#define CanvasPathMethods_h
-#include "core/platform/graphics/Path.h"
+#include "platform/graphics/Path.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/html/canvas/CanvasPattern.cpp b/chromium/third_party/WebKit/Source/core/html/canvas/CanvasPattern.cpp
index 8e20d0cef83..f7ee0da4388 100644
--- a/chromium/third_party/WebKit/Source/core/html/canvas/CanvasPattern.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/canvas/CanvasPattern.cpp
@@ -32,7 +32,7 @@
namespace WebCore {
-void CanvasPattern::parseRepetitionType(const String& type, bool& repeatX, bool& repeatY, ExceptionState& es)
+void CanvasPattern::parseRepetitionType(const String& type, bool& repeatX, bool& repeatY, ExceptionState& exceptionState)
{
if (type.isEmpty() || type == "repeat") {
repeatX = true;
@@ -54,7 +54,7 @@ void CanvasPattern::parseRepetitionType(const String& type, bool& repeatX, bool&
repeatY = true;
return;
}
- es.throwDOMException(SyntaxError);
+ exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
}
CanvasPattern::CanvasPattern(PassRefPtr<Image> image, bool repeatX, bool repeatY, bool originClean)
diff --git a/chromium/third_party/WebKit/Source/core/html/canvas/CanvasPattern.h b/chromium/third_party/WebKit/Source/core/html/canvas/CanvasPattern.h
index f1095f24228..cc7bdb92735 100644
--- a/chromium/third_party/WebKit/Source/core/html/canvas/CanvasPattern.h
+++ b/chromium/third_party/WebKit/Source/core/html/canvas/CanvasPattern.h
@@ -27,7 +27,7 @@
#define CanvasPattern_h
#include "bindings/v8/ScriptWrappable.h"
-#include "core/platform/graphics/Pattern.h"
+#include "platform/graphics/Pattern.h"
#include "wtf/Forward.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefCounted.h"
diff --git a/chromium/third_party/WebKit/Source/core/html/canvas/CanvasRenderingContext.cpp b/chromium/third_party/WebKit/Source/core/html/canvas/CanvasRenderingContext.cpp
index 7d259a4efd0..47a0e616efb 100644
--- a/chromium/third_party/WebKit/Source/core/html/canvas/CanvasRenderingContext.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/canvas/CanvasRenderingContext.cpp
@@ -27,11 +27,10 @@
#include "core/html/canvas/CanvasRenderingContext.h"
#include "core/fetch/ImageResource.h"
-#include "core/html/HTMLCanvasElement.h"
#include "core/html/HTMLImageElement.h"
#include "core/html/HTMLVideoElement.h"
#include "core/html/canvas/CanvasPattern.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/weborigin/SecurityOrigin.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/html/canvas/CanvasRenderingContext.h b/chromium/third_party/WebKit/Source/core/html/canvas/CanvasRenderingContext.h
index a7cefa3c287..2f5cd637991 100644
--- a/chromium/third_party/WebKit/Source/core/html/canvas/CanvasRenderingContext.h
+++ b/chromium/third_party/WebKit/Source/core/html/canvas/CanvasRenderingContext.h
@@ -32,7 +32,7 @@
#include "wtf/Noncopyable.h"
#include "wtf/text/StringHash.h"
-namespace WebKit { class WebLayer; }
+namespace blink { class WebLayer; }
namespace WebCore {
@@ -59,7 +59,7 @@ public:
virtual void paintRenderingResultsToCanvas() {}
- virtual WebKit::WebLayer* platformLayer() const { return 0; }
+ virtual blink::WebLayer* platformLayer() const { return 0; }
protected:
CanvasRenderingContext(HTMLCanvasElement*);
diff --git a/chromium/third_party/WebKit/Source/core/html/canvas/CanvasRenderingContext.idl b/chromium/third_party/WebKit/Source/core/html/canvas/CanvasRenderingContext.idl
index 36a791169ba..ae89a5fcd56 100644
--- a/chromium/third_party/WebKit/Source/core/html/canvas/CanvasRenderingContext.idl
+++ b/chromium/third_party/WebKit/Source/core/html/canvas/CanvasRenderingContext.idl
@@ -24,8 +24,8 @@
*/
[
+ Custom=Wrap,
NoInterfaceObject,
- CustomToV8
] interface CanvasRenderingContext {
readonly attribute HTMLCanvasElement canvas;
};
diff --git a/chromium/third_party/WebKit/Source/core/html/canvas/CanvasRenderingContext2D.cpp b/chromium/third_party/WebKit/Source/core/html/canvas/CanvasRenderingContext2D.cpp
index a2cabf1f82a..68f213b18ae 100644
--- a/chromium/third_party/WebKit/Source/core/html/canvas/CanvasRenderingContext2D.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/canvas/CanvasRenderingContext2D.cpp
@@ -34,7 +34,6 @@
#include "core/html/canvas/CanvasRenderingContext2D.h"
#include "CSSPropertyNames.h"
-#include "bindings/v8/ExceptionMessages.h"
#include "bindings/v8/ExceptionState.h"
#include "bindings/v8/ExceptionStatePlaceholder.h"
#include "core/accessibility/AXObjectCache.h"
@@ -50,21 +49,20 @@
#include "core/html/HTMLVideoElement.h"
#include "core/html/ImageData.h"
#include "core/html/TextMetrics.h"
-#include "core/html/canvas/Canvas2DContextAttributes.h"
#include "core/html/canvas/CanvasGradient.h"
#include "core/html/canvas/CanvasPattern.h"
#include "core/html/canvas/CanvasStyle.h"
#include "core/html/canvas/DOMPath.h"
-#include "core/page/ImageBitmap.h"
-#include "core/platform/graphics/DrawLooper.h"
-#include "core/platform/graphics/FloatQuad.h"
-#include "core/platform/graphics/FontCache.h"
-#include "core/platform/graphics/GraphicsContextStateSaver.h"
-#include "core/platform/graphics/TextRun.h"
-#include "core/platform/graphics/transforms/AffineTransform.h"
+#include "core/frame/ImageBitmap.h"
+#include "core/rendering/RenderImage.h"
#include "core/rendering/RenderLayer.h"
#include "core/rendering/RenderTheme.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/fonts/FontCache.h"
+#include "platform/geometry/FloatQuad.h"
+#include "platform/graphics/GraphicsContextStateSaver.h"
+#include "platform/graphics/DrawLooper.h"
+#include "platform/text/TextRun.h"
+#include "platform/weborigin/SecurityOrigin.h"
#include "wtf/CheckedArithmetic.h"
#include "wtf/MathExtras.h"
#include "wtf/OwnPtr.h"
@@ -76,17 +74,8 @@ using namespace std;
namespace WebCore {
static const int defaultFontSize = 10;
-static const char* const defaultFontFamily = "sans-serif";
-static const char* const defaultFont = "10px sans-serif";
-
-static bool isOriginClean(ImageResource* cachedImage, SecurityOrigin* securityOrigin)
-{
- if (!cachedImage->image()->currentFrameHasSingleSecurityOrigin())
- return false;
- if (cachedImage->passesAccessControlCheck(securityOrigin))
- return true;
- return !securityOrigin->taintsCanvas(cachedImage->response().url());
-}
+static const char defaultFontFamily[] = "sans-serif";
+static const char defaultFont[] = "10px sans-serif";
CanvasRenderingContext2D::CanvasRenderingContext2D(HTMLCanvasElement* canvas, const Canvas2DContextAttributes* attrs, bool usesCSSCompatibilityParseMode)
: CanvasRenderingContext(canvas)
@@ -120,7 +109,7 @@ CanvasRenderingContext2D::~CanvasRenderingContext2D()
bool CanvasRenderingContext2D::isAccelerated() const
{
- if (!canvas()->hasCreatedImageBuffer())
+ if (!canvas()->hasImageBuffer())
return false;
GraphicsContext* context = drawingContext();
return context && context->isAccelerated();
@@ -150,7 +139,7 @@ CanvasRenderingContext2D::State::State()
, m_shadowColor(Color::transparent)
, m_globalAlpha(1)
, m_globalComposite(CompositeSourceOver)
- , m_globalBlend(BlendModeNormal)
+ , m_globalBlend(blink::WebBlendModeNormal)
, m_invertibleCTM(true)
, m_lineDashOffset(0)
, m_imageSmoothingEnabled(true)
@@ -582,7 +571,7 @@ String CanvasRenderingContext2D::globalCompositeOperation() const
void CanvasRenderingContext2D::setGlobalCompositeOperation(const String& operation)
{
CompositeOperator op = CompositeSourceOver;
- BlendMode blendMode = BlendModeNormal;
+ blink::WebBlendMode blendMode = blink::WebBlendModeNormal;
if (!parseCompositeAndBlendOperator(operation, op, blendMode))
return;
if ((state().m_globalComposite == op) && (state().m_globalBlend == blendMode))
@@ -596,6 +585,11 @@ void CanvasRenderingContext2D::setGlobalCompositeOperation(const String& operati
c->setCompositeOperation(op, blendMode);
}
+void CanvasRenderingContext2D::setCurrentTransform(const SVGMatrix& matrix)
+{
+ setTransform(matrix.a(), matrix.b(), matrix.c(), matrix.d(), matrix.e(), matrix.f());
+}
+
void CanvasRenderingContext2D::scale(float sx, float sy)
{
GraphicsContext* c = drawingContext();
@@ -698,12 +692,12 @@ void CanvasRenderingContext2D::transform(float m11, float m12, float m21, float
realizeSaves();
+ modifiableState().m_transform = newTransform;
if (!newTransform.isInvertible()) {
modifiableState().m_invertibleCTM = false;
return;
}
- modifiableState().m_transform = newTransform;
c->concatCTM(transform);
m_path.transform(transform.inverse());
}
@@ -728,7 +722,7 @@ void CanvasRenderingContext2D::resetTransform()
c->setCTM(canvas()->baseTransform());
if (invertibleCTM)
- m_path.transform(ctm.inverse());
+ m_path.transform(ctm);
// When else, do nothing because all transform methods didn't update m_path when CTM became non-invertible.
// It means that resetTransform() restores m_path just before CTM became non-invertible.
}
@@ -1207,11 +1201,22 @@ bool CanvasRenderingContext2D::shouldDrawShadows() const
return alphaChannel(state().m_shadowColor) && (state().m_shadowBlur || !state().m_shadowOffset.isZero());
}
-static LayoutSize sizeFor(HTMLImageElement* image)
+enum ImageSizeType {
+ ImageSizeAfterDevicePixelRatio,
+ ImageSizeBeforeDevicePixelRatio
+};
+
+static LayoutSize sizeFor(HTMLImageElement* image, ImageSizeType sizeType)
{
- if (ImageResource* cachedImage = image->cachedImage())
- return cachedImage->imageSizeForRenderer(image->renderer(), 1.0f); // FIXME: Not sure about this.
- return IntSize();
+ LayoutSize size;
+ ImageResource* cachedImage = image->cachedImage();
+ if (cachedImage) {
+ size = cachedImage->imageSizeForRenderer(image->renderer(), 1.0f); // FIXME: Not sure about this.
+
+ if (sizeType == ImageSizeAfterDevicePixelRatio && image->renderer() && image->renderer()->isRenderImage() && cachedImage->image() && !cachedImage->image()->hasRelativeWidth())
+ size.scale(toRenderImage(image->renderer())->imageDevicePixelRatio());
+ }
+ return size;
}
static IntSize sizeFor(HTMLVideoElement* video)
@@ -1248,7 +1253,7 @@ static inline void clipRectsToImageRect(const FloatRect& imageRect, FloatRect* s
dstRect->move(offset);
}
-void CanvasRenderingContext2D::drawImageInternal(Image* image, const FloatRect& srcRect, const FloatRect& dstRect, const CompositeOperator& op, const BlendMode& blendMode)
+void CanvasRenderingContext2D::drawImageInternal(Image* image, const FloatRect& srcRect, const FloatRect& dstRect, const CompositeOperator& op, const blink::WebBlendMode& blendMode)
{
if (!image)
return;
@@ -1281,34 +1286,34 @@ void CanvasRenderingContext2D::drawImageInternal(Image* image, const FloatRect&
}
}
-void CanvasRenderingContext2D::drawImage(ImageBitmap* bitmap, float x, float y, ExceptionState& es)
+void CanvasRenderingContext2D::drawImage(ImageBitmap* bitmap, float x, float y, ExceptionState& exceptionState)
{
if (!bitmap) {
- es.throwDOMException(TypeMismatchError);
+ exceptionState.throwUninformativeAndGenericDOMException(TypeMismatchError);
return;
}
- drawImage(bitmap, x, y, bitmap->width(), bitmap->height(), es);
+ drawImage(bitmap, x, y, bitmap->width(), bitmap->height(), exceptionState);
}
void CanvasRenderingContext2D::drawImage(ImageBitmap* bitmap,
- float x, float y, float width, float height, ExceptionState& es)
+ float x, float y, float width, float height, ExceptionState& exceptionState)
{
if (!bitmap) {
- es.throwDOMException(TypeMismatchError);
+ exceptionState.throwUninformativeAndGenericDOMException(TypeMismatchError);
return;
}
if (!bitmap->bitmapRect().width() || !bitmap->bitmapRect().height())
return;
- drawImage(bitmap, 0, 0, bitmap->width(), bitmap->height(), x, y, width, height, es);
+ drawImage(bitmap, 0, 0, bitmap->width(), bitmap->height(), x, y, width, height, exceptionState);
}
void CanvasRenderingContext2D::drawImage(ImageBitmap* bitmap,
float sx, float sy, float sw, float sh,
- float dx, float dy, float dw, float dh, ExceptionState& es)
+ float dx, float dy, float dw, float dh, ExceptionState& exceptionState)
{
if (!bitmap) {
- es.throwDOMException(TypeMismatchError);
+ exceptionState.throwUninformativeAndGenericDOMException(TypeMismatchError);
return;
}
@@ -1323,7 +1328,7 @@ void CanvasRenderingContext2D::drawImage(ImageBitmap* bitmap,
if (!dstRect.width() || !dstRect.height())
return;
if (!srcRect.width() || !srcRect.height()) {
- es.throwDOMException(IndexSizeError);
+ exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
return;
}
@@ -1356,43 +1361,43 @@ void CanvasRenderingContext2D::drawImage(ImageBitmap* bitmap,
drawImageInternal(imageForRendering.get(), actualSrcRect, actualDstRect, state().m_globalComposite, state().m_globalBlend);
}
-void CanvasRenderingContext2D::drawImage(HTMLImageElement* image, float x, float y, ExceptionState& es)
+void CanvasRenderingContext2D::drawImage(HTMLImageElement* image, float x, float y, ExceptionState& exceptionState)
{
if (!image) {
- es.throwDOMException(TypeMismatchError);
+ exceptionState.throwUninformativeAndGenericDOMException(TypeMismatchError);
return;
}
- LayoutSize size = sizeFor(image);
- drawImage(image, x, y, size.width(), size.height(), es);
+ LayoutSize destRectSize = sizeFor(image, ImageSizeAfterDevicePixelRatio);
+ drawImage(image, x, y, destRectSize.width(), destRectSize.height(), exceptionState);
}
void CanvasRenderingContext2D::drawImage(HTMLImageElement* image,
- float x, float y, float width, float height, ExceptionState& es)
+ float x, float y, float width, float height, ExceptionState& exceptionState)
{
if (!image) {
- es.throwDOMException(TypeMismatchError);
+ exceptionState.throwUninformativeAndGenericDOMException(TypeMismatchError);
return;
}
- LayoutSize size = sizeFor(image);
- drawImage(image, FloatRect(0, 0, size.width(), size.height()), FloatRect(x, y, width, height), es);
+ LayoutSize sourceRectSize = sizeFor(image, ImageSizeBeforeDevicePixelRatio);
+ drawImage(image, FloatRect(0, 0, sourceRectSize.width(), sourceRectSize.height()), FloatRect(x, y, width, height), exceptionState);
}
void CanvasRenderingContext2D::drawImage(HTMLImageElement* image,
float sx, float sy, float sw, float sh,
- float dx, float dy, float dw, float dh, ExceptionState& es)
+ float dx, float dy, float dw, float dh, ExceptionState& exceptionState)
{
- drawImage(image, FloatRect(sx, sy, sw, sh), FloatRect(dx, dy, dw, dh), es);
+ drawImage(image, FloatRect(sx, sy, sw, sh), FloatRect(dx, dy, dw, dh), exceptionState);
}
-void CanvasRenderingContext2D::drawImage(HTMLImageElement* image, const FloatRect& srcRect, const FloatRect& dstRect, ExceptionState& es)
+void CanvasRenderingContext2D::drawImage(HTMLImageElement* image, const FloatRect& srcRect, const FloatRect& dstRect, ExceptionState& exceptionState)
{
- drawImage(image, srcRect, dstRect, state().m_globalComposite, state().m_globalBlend, es);
+ drawImage(image, srcRect, dstRect, state().m_globalComposite, state().m_globalBlend, exceptionState);
}
-void CanvasRenderingContext2D::drawImage(HTMLImageElement* image, const FloatRect& srcRect, const FloatRect& dstRect, const CompositeOperator& op, const BlendMode& blendMode, ExceptionState& es)
+void CanvasRenderingContext2D::drawImage(HTMLImageElement* image, const FloatRect& srcRect, const FloatRect& dstRect, const CompositeOperator& op, const blink::WebBlendMode& blendMode, ExceptionState& exceptionState)
{
if (!image) {
- es.throwDOMException(TypeMismatchError);
+ exceptionState.throwUninformativeAndGenericDOMException(TypeMismatchError);
return;
}
@@ -1404,9 +1409,9 @@ void CanvasRenderingContext2D::drawImage(HTMLImageElement* image, const FloatRec
if (!cachedImage || !image->complete())
return;
- LayoutSize size = sizeFor(image);
+ LayoutSize size = sizeFor(image, ImageSizeBeforeDevicePixelRatio);
if (!size.width() || !size.height()) {
- es.throwDOMException(InvalidStateError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
return;
}
@@ -1418,7 +1423,7 @@ void CanvasRenderingContext2D::drawImage(HTMLImageElement* image, const FloatRec
FloatRect imageRect = FloatRect(FloatPoint(), size);
if (!srcRect.width() || !srcRect.height()) {
- es.throwDOMException(IndexSizeError);
+ exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
return;
}
if (!imageRect.intersects(normalizedSrcRect))
@@ -1439,41 +1444,41 @@ void CanvasRenderingContext2D::drawImage(HTMLImageElement* image, const FloatRec
drawImageInternal(imageForRendering, normalizedSrcRect, normalizedDstRect, op, blendMode);
}
-void CanvasRenderingContext2D::drawImage(HTMLCanvasElement* sourceCanvas, float x, float y, ExceptionState& es)
+void CanvasRenderingContext2D::drawImage(HTMLCanvasElement* sourceCanvas, float x, float y, ExceptionState& exceptionState)
{
- drawImage(sourceCanvas, 0, 0, sourceCanvas->width(), sourceCanvas->height(), x, y, sourceCanvas->width(), sourceCanvas->height(), es);
+ drawImage(sourceCanvas, 0, 0, sourceCanvas->width(), sourceCanvas->height(), x, y, sourceCanvas->width(), sourceCanvas->height(), exceptionState);
}
void CanvasRenderingContext2D::drawImage(HTMLCanvasElement* sourceCanvas,
- float x, float y, float width, float height, ExceptionState& es)
+ float x, float y, float width, float height, ExceptionState& exceptionState)
{
- drawImage(sourceCanvas, FloatRect(0, 0, sourceCanvas->width(), sourceCanvas->height()), FloatRect(x, y, width, height), es);
+ drawImage(sourceCanvas, FloatRect(0, 0, sourceCanvas->width(), sourceCanvas->height()), FloatRect(x, y, width, height), exceptionState);
}
void CanvasRenderingContext2D::drawImage(HTMLCanvasElement* sourceCanvas,
float sx, float sy, float sw, float sh,
- float dx, float dy, float dw, float dh, ExceptionState& es)
+ float dx, float dy, float dw, float dh, ExceptionState& exceptionState)
{
- drawImage(sourceCanvas, FloatRect(sx, sy, sw, sh), FloatRect(dx, dy, dw, dh), es);
+ drawImage(sourceCanvas, FloatRect(sx, sy, sw, sh), FloatRect(dx, dy, dw, dh), exceptionState);
}
void CanvasRenderingContext2D::drawImage(HTMLCanvasElement* sourceCanvas, const FloatRect& srcRect,
- const FloatRect& dstRect, ExceptionState& es)
+ const FloatRect& dstRect, ExceptionState& exceptionState)
{
if (!sourceCanvas) {
- es.throwDOMException(TypeMismatchError);
+ exceptionState.throwUninformativeAndGenericDOMException(TypeMismatchError);
return;
}
FloatRect srcCanvasRect = FloatRect(FloatPoint(), sourceCanvas->size());
if (!srcCanvasRect.width() || !srcCanvasRect.height()) {
- es.throwDOMException(InvalidStateError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
return;
}
if (!srcRect.width() || !srcRect.height()) {
- es.throwDOMException(IndexSizeError);
+ exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
return;
}
@@ -1526,40 +1531,44 @@ void CanvasRenderingContext2D::drawImage(HTMLCanvasElement* sourceCanvas, const
didDraw(dirtyRect);
}
}
+
+ // Flush canvas's ImageBuffer when drawImage from WebGL to HW accelerated 2d canvas
+ if (sourceContext && sourceContext->is3d() && is2d() && isAccelerated() && canvas()->buffer())
+ canvas()->buffer()->flush();
}
-void CanvasRenderingContext2D::drawImage(HTMLVideoElement* video, float x, float y, ExceptionState& es)
+void CanvasRenderingContext2D::drawImage(HTMLVideoElement* video, float x, float y, ExceptionState& exceptionState)
{
if (!video) {
- es.throwDOMException(TypeMismatchError);
+ exceptionState.throwUninformativeAndGenericDOMException(TypeMismatchError);
return;
}
IntSize size = sizeFor(video);
- drawImage(video, x, y, size.width(), size.height(), es);
+ drawImage(video, x, y, size.width(), size.height(), exceptionState);
}
void CanvasRenderingContext2D::drawImage(HTMLVideoElement* video,
- float x, float y, float width, float height, ExceptionState& es)
+ float x, float y, float width, float height, ExceptionState& exceptionState)
{
if (!video) {
- es.throwDOMException(TypeMismatchError);
+ exceptionState.throwUninformativeAndGenericDOMException(TypeMismatchError);
return;
}
IntSize size = sizeFor(video);
- drawImage(video, FloatRect(0, 0, size.width(), size.height()), FloatRect(x, y, width, height), es);
+ drawImage(video, FloatRect(0, 0, size.width(), size.height()), FloatRect(x, y, width, height), exceptionState);
}
void CanvasRenderingContext2D::drawImage(HTMLVideoElement* video,
float sx, float sy, float sw, float sh,
- float dx, float dy, float dw, float dh, ExceptionState& es)
+ float dx, float dy, float dw, float dh, ExceptionState& exceptionState)
{
- drawImage(video, FloatRect(sx, sy, sw, sh), FloatRect(dx, dy, dw, dh), es);
+ drawImage(video, FloatRect(sx, sy, sw, sh), FloatRect(dx, dy, dw, dh), exceptionState);
}
-void CanvasRenderingContext2D::drawImage(HTMLVideoElement* video, const FloatRect& srcRect, const FloatRect& dstRect, ExceptionState& es)
+void CanvasRenderingContext2D::drawImage(HTMLVideoElement* video, const FloatRect& srcRect, const FloatRect& dstRect, ExceptionState& exceptionState)
{
if (!video) {
- es.throwDOMException(TypeMismatchError);
+ exceptionState.throwUninformativeAndGenericDOMException(TypeMismatchError);
return;
}
@@ -1568,7 +1577,7 @@ void CanvasRenderingContext2D::drawImage(HTMLVideoElement* video, const FloatRec
FloatRect videoRect = FloatRect(FloatPoint(), sizeFor(video));
if (!srcRect.width() || !srcRect.height()) {
- es.throwDOMException(IndexSizeError);
+ exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
return;
}
@@ -1609,11 +1618,11 @@ void CanvasRenderingContext2D::drawImageFromRect(HTMLImageElement* image,
const String& compositeOperation)
{
CompositeOperator op;
- BlendMode blendOp = BlendModeNormal;
- if (!parseCompositeAndBlendOperator(compositeOperation, op, blendOp) || blendOp != BlendModeNormal)
+ blink::WebBlendMode blendOp = blink::WebBlendModeNormal;
+ if (!parseCompositeAndBlendOperator(compositeOperation, op, blendOp) || blendOp != blink::WebBlendModeNormal)
op = CompositeSourceOver;
- drawImage(image, FloatRect(sx, sy, sw, sh), FloatRect(dx, dy, dw, dh), op, BlendModeNormal, IGNORE_EXCEPTION);
+ drawImage(image, FloatRect(sx, sy, sw, sh), FloatRect(dx, dy, dw, dh), op, blink::WebBlendModeNormal, IGNORE_EXCEPTION);
}
void CanvasRenderingContext2D::setAlpha(float alpha)
@@ -1660,7 +1669,7 @@ template<class T> void CanvasRenderingContext2D::fullCanvasCompositedDrawImage(
{
ASSERT(isFullCanvasCompositeMode(op));
- drawingContext()->beginTransparencyLayer(1, op);
+ drawingContext()->beginLayer(1, op);
drawImageToContext(image, drawingContext(), dest, src, CompositeSourceOver);
drawingContext()->endLayer();
}
@@ -1681,7 +1690,7 @@ template<class T> void CanvasRenderingContext2D::fullCanvasCompositedFill(const
GraphicsContext* c = drawingContext();
ASSERT(c);
- c->beginTransparencyLayer(1, state().m_globalComposite);
+ c->beginLayer(1, state().m_globalComposite);
CompositeOperator previousOperator = c->compositeOperation();
c->setCompositeOperation(CompositeSourceOver);
fillPrimitive(area, c);
@@ -1689,10 +1698,10 @@ template<class T> void CanvasRenderingContext2D::fullCanvasCompositedFill(const
c->endLayer();
}
-PassRefPtr<CanvasGradient> CanvasRenderingContext2D::createLinearGradient(float x0, float y0, float x1, float y1, ExceptionState& es)
+PassRefPtr<CanvasGradient> CanvasRenderingContext2D::createLinearGradient(float x0, float y0, float x1, float y1, ExceptionState& exceptionState)
{
if (!std::isfinite(x0) || !std::isfinite(y0) || !std::isfinite(x1) || !std::isfinite(y1)) {
- es.throwDOMException(NotSupportedError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
return 0;
}
@@ -1700,15 +1709,15 @@ PassRefPtr<CanvasGradient> CanvasRenderingContext2D::createLinearGradient(float
return gradient.release();
}
-PassRefPtr<CanvasGradient> CanvasRenderingContext2D::createRadialGradient(float x0, float y0, float r0, float x1, float y1, float r1, ExceptionState& es)
+PassRefPtr<CanvasGradient> CanvasRenderingContext2D::createRadialGradient(float x0, float y0, float r0, float x1, float y1, float r1, ExceptionState& exceptionState)
{
if (!std::isfinite(x0) || !std::isfinite(y0) || !std::isfinite(r0) || !std::isfinite(x1) || !std::isfinite(y1) || !std::isfinite(r1)) {
- es.throwDOMException(NotSupportedError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
return 0;
}
if (r0 < 0 || r1 < 0) {
- es.throwDOMException(IndexSizeError);
+ exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
return 0;
}
@@ -1717,15 +1726,15 @@ PassRefPtr<CanvasGradient> CanvasRenderingContext2D::createRadialGradient(float
}
PassRefPtr<CanvasPattern> CanvasRenderingContext2D::createPattern(HTMLImageElement* image,
- const String& repetitionType, ExceptionState& es)
+ const String& repetitionType, ExceptionState& exceptionState)
{
if (!image) {
- es.throwDOMException(TypeMismatchError);
+ exceptionState.throwUninformativeAndGenericDOMException(TypeMismatchError);
return 0;
}
bool repeatX, repeatY;
- CanvasPattern::parseRepetitionType(repetitionType, repeatX, repeatY, es);
- if (es.hadException())
+ CanvasPattern::parseRepetitionType(repetitionType, repeatX, repeatY, exceptionState);
+ if (exceptionState.hadException())
return 0;
if (!image->complete())
@@ -1740,25 +1749,25 @@ PassRefPtr<CanvasPattern> CanvasRenderingContext2D::createPattern(HTMLImageEleme
if (!image->renderer() && imageForRendering->usesContainerSize())
imageForRendering->setContainerSize(imageForRendering->size());
- bool originClean = isOriginClean(cachedImage, canvas()->securityOrigin());
+ bool originClean = cachedImage->isAccessAllowed(canvas()->securityOrigin());
return CanvasPattern::create(imageForRendering, repeatX, repeatY, originClean);
}
PassRefPtr<CanvasPattern> CanvasRenderingContext2D::createPattern(HTMLCanvasElement* canvas,
- const String& repetitionType, ExceptionState& es)
+ const String& repetitionType, ExceptionState& exceptionState)
{
if (!canvas) {
- es.throwDOMException(TypeMismatchError);
+ exceptionState.throwUninformativeAndGenericDOMException(TypeMismatchError);
return 0;
}
if (!canvas->width() || !canvas->height()) {
- es.throwDOMException(InvalidStateError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
return 0;
}
bool repeatX, repeatY;
- CanvasPattern::parseRepetitionType(repetitionType, repeatX, repeatY, es);
- if (es.hadException())
+ CanvasPattern::parseRepetitionType(repetitionType, repeatX, repeatY, exceptionState);
+ if (exceptionState.hadException())
return 0;
return CanvasPattern::create(canvas->copiedImage(), repeatX, repeatY, canvas->originClean());
}
@@ -1829,24 +1838,24 @@ static PassRefPtr<ImageData> createEmptyImageData(const IntSize& size)
return data.release();
}
-PassRefPtr<ImageData> CanvasRenderingContext2D::createImageData(PassRefPtr<ImageData> imageData, ExceptionState& es) const
+PassRefPtr<ImageData> CanvasRenderingContext2D::createImageData(PassRefPtr<ImageData> imageData, ExceptionState& exceptionState) const
{
if (!imageData) {
- es.throwDOMException(NotSupportedError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
return 0;
}
return createEmptyImageData(imageData->size());
}
-PassRefPtr<ImageData> CanvasRenderingContext2D::createImageData(float sw, float sh, ExceptionState& es) const
+PassRefPtr<ImageData> CanvasRenderingContext2D::createImageData(float sw, float sh, ExceptionState& exceptionState) const
{
if (!sw || !sh) {
- es.throwDOMException(IndexSizeError);
+ exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
return 0;
}
if (!std::isfinite(sw) || !std::isfinite(sh)) {
- es.throwDOMException(NotSupportedError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
return 0;
}
@@ -1863,29 +1872,24 @@ PassRefPtr<ImageData> CanvasRenderingContext2D::createImageData(float sw, float
return createEmptyImageData(size);
}
-PassRefPtr<ImageData> CanvasRenderingContext2D::getImageData(float sx, float sy, float sw, float sh, ExceptionState& es) const
+PassRefPtr<ImageData> CanvasRenderingContext2D::webkitGetImageDataHD(float sx, float sy, float sw, float sh, ExceptionState& exceptionState) const
{
- return getImageData(ImageBuffer::LogicalCoordinateSystem, sx, sy, sw, sh, es);
+ return getImageData(sx, sy, sw, sh, exceptionState);
}
-PassRefPtr<ImageData> CanvasRenderingContext2D::webkitGetImageDataHD(float sx, float sy, float sw, float sh, ExceptionState& es) const
-{
- return getImageData(ImageBuffer::BackingStoreCoordinateSystem, sx, sy, sw, sh, es);
-}
-
-PassRefPtr<ImageData> CanvasRenderingContext2D::getImageData(ImageBuffer::CoordinateSystem coordinateSystem, float sx, float sy, float sw, float sh, ExceptionState& es) const
+PassRefPtr<ImageData> CanvasRenderingContext2D::getImageData(float sx, float sy, float sw, float sh, ExceptionState& exceptionState) const
{
if (!canvas()->originClean()) {
- es.throwSecurityError(ExceptionMessages::failedToExecute("getImageData", "CanvasRenderingContext2D", "the canvas has been tainted by cross-origin data."));
+ exceptionState.throwSecurityError("The canvas has been tainted by cross-origin data.");
return 0;
}
if (!sw || !sh) {
- es.throwDOMException(IndexSizeError);
+ exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
return 0;
}
if (!std::isfinite(sx) || !std::isfinite(sy) || !std::isfinite(sw) || !std::isfinite(sh)) {
- es.throwDOMException(NotSupportedError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
return 0;
}
@@ -1911,51 +1915,31 @@ PassRefPtr<ImageData> CanvasRenderingContext2D::getImageData(ImageBuffer::Coordi
if (!buffer)
return createEmptyImageData(imageDataRect.size());
- RefPtr<Uint8ClampedArray> byteArray = buffer->getUnmultipliedImageData(imageDataRect, coordinateSystem);
+ RefPtr<Uint8ClampedArray> byteArray = buffer->getUnmultipliedImageData(imageDataRect);
if (!byteArray)
return 0;
return ImageData::create(imageDataRect.size(), byteArray.release());
}
-void CanvasRenderingContext2D::putImageData(ImageData* data, float dx, float dy, ExceptionState& es)
-{
- if (!data) {
- es.throwDOMException(TypeMismatchError);
- return;
- }
- putImageData(data, dx, dy, 0, 0, data->width(), data->height(), es);
-}
-
-void CanvasRenderingContext2D::webkitPutImageDataHD(ImageData* data, float dx, float dy, ExceptionState& es)
+void CanvasRenderingContext2D::putImageData(ImageData* data, float dx, float dy, ExceptionState& exceptionState)
{
if (!data) {
- es.throwDOMException(TypeMismatchError);
+ exceptionState.throwUninformativeAndGenericDOMException(TypeMismatchError);
return;
}
- webkitPutImageDataHD(data, dx, dy, 0, 0, data->width(), data->height(), es);
+ putImageData(data, dx, dy, 0, 0, data->width(), data->height(), exceptionState);
}
void CanvasRenderingContext2D::putImageData(ImageData* data, float dx, float dy, float dirtyX, float dirtyY,
- float dirtyWidth, float dirtyHeight, ExceptionState& es)
-{
- putImageData(data, ImageBuffer::LogicalCoordinateSystem, dx, dy, dirtyX, dirtyY, dirtyWidth, dirtyHeight, es);
-}
-
-void CanvasRenderingContext2D::webkitPutImageDataHD(ImageData* data, float dx, float dy, float dirtyX, float dirtyY, float dirtyWidth, float dirtyHeight, ExceptionState& es)
-{
- putImageData(data, ImageBuffer::BackingStoreCoordinateSystem, dx, dy, dirtyX, dirtyY, dirtyWidth, dirtyHeight, es);
-}
-
-void CanvasRenderingContext2D::putImageData(ImageData* data, ImageBuffer::CoordinateSystem coordinateSystem, float dx, float dy, float dirtyX, float dirtyY,
- float dirtyWidth, float dirtyHeight, ExceptionState& es)
+ float dirtyWidth, float dirtyHeight, ExceptionState& exceptionState)
{
if (!data) {
- es.throwDOMException(TypeMismatchError);
+ exceptionState.throwUninformativeAndGenericDOMException(TypeMismatchError);
return;
}
if (!std::isfinite(dx) || !std::isfinite(dy) || !std::isfinite(dirtyX) || !std::isfinite(dirtyY) || !std::isfinite(dirtyWidth) || !std::isfinite(dirtyHeight)) {
- es.throwDOMException(NotSupportedError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
return;
}
@@ -1978,19 +1962,14 @@ void CanvasRenderingContext2D::putImageData(ImageData* data, ImageBuffer::Coordi
IntSize destOffset(static_cast<int>(dx), static_cast<int>(dy));
IntRect destRect = enclosingIntRect(clipRect);
destRect.move(destOffset);
- destRect.intersect(IntRect(IntPoint(), coordinateSystem == ImageBuffer::LogicalCoordinateSystem ? buffer->logicalSize() : buffer->internalSize()));
+ destRect.intersect(IntRect(IntPoint(), buffer->size()));
if (destRect.isEmpty())
return;
IntRect sourceRect(destRect);
sourceRect.move(-destOffset);
- buffer->putByteArray(Unmultiplied, data->data(), IntSize(data->width(), data->height()), sourceRect, IntPoint(destOffset), coordinateSystem);
+ buffer->putByteArray(Unmultiplied, data->data(), IntSize(data->width(), data->height()), sourceRect, IntPoint(destOffset));
- if (coordinateSystem == ImageBuffer::BackingStoreCoordinateSystem) {
- FloatRect dirtyRect = destRect;
- dirtyRect.scale(1 / canvas()->deviceScaleFactor());
- destRect = enclosingIntRect(dirtyRect);
- }
didDraw(destRect);
}
@@ -2038,7 +2017,8 @@ void CanvasRenderingContext2D::setFont(const String& newFont)
if (!parsedStyle) {
parsedStyle = MutableStylePropertySet::create();
- CSSParser::parseValue(parsedStyle.get(), CSSPropertyFont, newFont, true, strictToCSSParserMode(!m_usesCSSCompatibilityParseMode), 0);
+ CSSParserMode mode = m_usesCSSCompatibilityParseMode ? HTMLQuirksMode : HTMLStandardMode;
+ CSSParser::parseValue(parsedStyle.get(), CSSPropertyFont, newFont, true, mode, 0);
m_fetchedFonts.add(newFont, parsedStyle);
}
if (parsedStyle->isEmpty())
@@ -2085,15 +2065,15 @@ void CanvasRenderingContext2D::setFont(const String& newFont)
CSSPropertyValue(CSSPropertyLineHeight, *parsedStyle),
};
- StyleResolver* styleResolver = canvas()->styleResolver();
- styleResolver->applyPropertiesToStyle(properties, WTF_ARRAY_LENGTH(properties), newStyle.get());
+ StyleResolver& styleResolver = canvas()->document().ensureStyleResolver();
+ styleResolver.applyPropertiesToStyle(properties, WTF_ARRAY_LENGTH(properties), newStyle.get());
if (state().m_realizedFont)
state().m_font.fontSelector()->unregisterForInvalidationCallbacks(&modifiableState());
modifiableState().m_font = newStyle->font();
- modifiableState().m_font.update(styleResolver->fontSelector());
+ modifiableState().m_font.update(canvas()->document().styleEngine()->fontSelector());
modifiableState().m_realizedFont = true;
- styleResolver->fontSelector()->registerForInvalidationCallbacks(&modifiableState());
+ canvas()->document().styleEngine()->fontSelector()->registerForInvalidationCallbacks(&modifiableState());
}
String CanvasRenderingContext2D::textAlign() const
@@ -2301,7 +2281,7 @@ const Font& CanvasRenderingContext2D::accessFont()
return state().m_font;
}
-WebKit::WebLayer* CanvasRenderingContext2D::platformLayer() const
+blink::WebLayer* CanvasRenderingContext2D::platformLayer() const
{
return canvas()->buffer() ? canvas()->buffer()->platformLayer() : 0;
}
@@ -2377,7 +2357,7 @@ void CanvasRenderingContext2D::updateFocusRingAccessibility(const Path& path, El
// isn't focused because assistive technology might try to explore the object's
// location before it gets focus.
if (AXObjectCache* axObjectCache = element->document().existingAXObjectCache()) {
- if (AccessibilityObject* obj = axObjectCache->getOrCreate(element)) {
+ if (AXObject* obj = axObjectCache->getOrCreate(element)) {
// Get the bounding rect and apply transformations.
FloatRect bounds = m_path.boundingRect();
AffineTransform ctm = state().m_transform;
@@ -2413,7 +2393,7 @@ void CanvasRenderingContext2D::drawFocusRing(const Path& path)
c->save();
c->setAlpha(1.0);
c->clearShadow();
- c->setCompositeOperation(CompositeSourceOver, BlendModeNormal);
+ c->setCompositeOperation(CompositeSourceOver, blink::WebBlendModeNormal);
// These should match the style defined in html.css.
Color focusRingColor = RenderTheme::focusRingColor();
diff --git a/chromium/third_party/WebKit/Source/core/html/canvas/CanvasRenderingContext2D.h b/chromium/third_party/WebKit/Source/core/html/canvas/CanvasRenderingContext2D.h
index a3f8eb1cfa2..8493b10b149 100644
--- a/chromium/third_party/WebKit/Source/core/html/canvas/CanvasRenderingContext2D.h
+++ b/chromium/third_party/WebKit/Source/core/html/canvas/CanvasRenderingContext2D.h
@@ -29,18 +29,19 @@
#include "core/html/canvas/Canvas2DContextAttributes.h"
#include "core/html/canvas/CanvasPathMethods.h"
#include "core/html/canvas/CanvasRenderingContext.h"
-#include "core/platform/graphics/Color.h"
-#include "core/platform/graphics/FloatSize.h"
-#include "core/platform/graphics/Font.h"
-#include "core/platform/graphics/GraphicsTypes.h"
-#include "core/platform/graphics/ImageBuffer.h"
-#include "core/platform/graphics/Path.h"
-#include "core/platform/graphics/transforms/AffineTransform.h"
+#include "core/svg/SVGMatrix.h"
+#include "platform/fonts/Font.h"
+#include "platform/graphics/Color.h"
+#include "platform/geometry/FloatSize.h"
+#include "platform/graphics/GraphicsTypes.h"
+#include "platform/graphics/ImageBuffer.h"
+#include "platform/graphics/Path.h"
+#include "platform/transforms/AffineTransform.h"
#include "wtf/HashMap.h"
#include "wtf/Vector.h"
#include "wtf/text/WTFString.h"
-namespace WebKit { class WebLayer; }
+namespace blink { class WebLayer; }
namespace WebCore {
@@ -117,6 +118,12 @@ public:
void save() { ++m_unrealizedSaveCount; }
void restore();
+ SVGMatrix currentTransform() const
+ {
+ return SVGMatrix(state().m_transform);
+ }
+ void setCurrentTransform(const SVGMatrix&);
+
void scale(float sx, float sy);
void rotate(float angleInRadians);
void translate(float tx, float ty);
@@ -170,7 +177,7 @@ public:
void drawImage(HTMLImageElement*, float x, float y, float width, float height, ExceptionState&);
void drawImage(HTMLImageElement*, float sx, float sy, float sw, float sh, float dx, float dy, float dw, float dh, ExceptionState&);
void drawImage(HTMLImageElement*, const FloatRect& srcRect, const FloatRect& dstRect, ExceptionState&);
- void drawImage(HTMLImageElement*, const FloatRect& srcRect, const FloatRect& dstRect, const CompositeOperator&, const BlendMode&, ExceptionState&);
+ void drawImage(HTMLImageElement*, const FloatRect& srcRect, const FloatRect& dstRect, const CompositeOperator&, const blink::WebBlendMode&, ExceptionState&);
void drawImage(HTMLCanvasElement*, float x, float y, ExceptionState&);
void drawImage(HTMLCanvasElement*, float x, float y, float width, float height, ExceptionState&);
void drawImage(HTMLCanvasElement*, float sx, float sy, float sw, float sh, float dx, float dy, float dw, float dh, ExceptionState&);
@@ -195,13 +202,14 @@ public:
PassRefPtr<ImageData> createImageData(PassRefPtr<ImageData>, ExceptionState&) const;
PassRefPtr<ImageData> createImageData(float width, float height, ExceptionState&) const;
PassRefPtr<ImageData> getImageData(float sx, float sy, float sw, float sh, ExceptionState&) const;
- PassRefPtr<ImageData> webkitGetImageDataHD(float sx, float sy, float sw, float sh, ExceptionState&) const;
void putImageData(ImageData*, float dx, float dy, ExceptionState&);
void putImageData(ImageData*, float dx, float dy, float dirtyX, float dirtyY, float dirtyWidth, float dirtyHeight, ExceptionState&);
- void webkitPutImageDataHD(ImageData*, float dx, float dy, ExceptionState&);
- void webkitPutImageDataHD(ImageData*, float dx, float dy, float dirtyX, float dirtyY, float dirtyWidth, float dirtyHeight, ExceptionState&);
- float webkitBackingStorePixelRatio() const { return canvas()->deviceScaleFactor(); }
+ // Slated for deprecation:
+ void webkitPutImageDataHD(ImageData* image, float dx, float dy, ExceptionState& e) { putImageData(image, dx, dy, e); }
+ void webkitPutImageDataHD(ImageData* image, float dx, float dy, float dirtyX, float dirtyY, float dirtyWidth, float dirtyHeight, ExceptionState& e) { putImageData(image, dx, dy, dirtyX, dirtyY, dirtyWidth, dirtyHeight, e); }
+ PassRefPtr<ImageData> webkitGetImageDataHD(float sx, float sy, float sw, float sh, ExceptionState&) const;
+ float webkitBackingStorePixelRatio() const { return 1; }
void reset();
@@ -254,7 +262,7 @@ private:
RGBA32 m_shadowColor;
float m_globalAlpha;
CompositeOperator m_globalComposite;
- BlendMode m_globalBlend;
+ blink::WebBlendMode m_globalBlend;
AffineTransform m_transform;
bool m_invertibleCTM;
Vector<float> m_lineDash;
@@ -280,7 +288,7 @@ private:
void applyShadow();
bool shouldDrawShadows() const;
- void drawImageInternal(Image*, const FloatRect&, const FloatRect&, const CompositeOperator&, const BlendMode&);
+ void drawImageInternal(Image*, const FloatRect&, const FloatRect&, const CompositeOperator&, const blink::WebBlendMode&);
bool computeDirtyRect(const FloatRect& localBounds, FloatRect*);
bool computeDirtyRect(const FloatRect& localBounds, const FloatRect& transformedClipBounds, FloatRect*);
void didDraw(const FloatRect&);
@@ -310,9 +318,6 @@ private:
template<class T> void fullCanvasCompositedFill(const T&);
template<class T> void fullCanvasCompositedDrawImage(T*, const FloatRect&, const FloatRect&, CompositeOperator);
- PassRefPtr<ImageData> getImageData(ImageBuffer::CoordinateSystem, float sx, float sy, float sw, float sh, ExceptionState&) const;
- void putImageData(ImageData*, ImageBuffer::CoordinateSystem, float dx, float dy, float dirtyX, float dirtyY, float dirtyWidth, float dirtyHeight, ExceptionState&);
-
bool focusRingCallIsValid(const Path&, Element*);
void updateFocusRingAccessibility(const Path&, Element*);
void drawFocusRing(const Path&);
@@ -323,7 +328,7 @@ private:
virtual bool isTransformInvertible() const { return state().m_invertibleCTM; }
- virtual WebKit::WebLayer* platformLayer() const OVERRIDE;
+ virtual blink::WebLayer* platformLayer() const OVERRIDE;
Vector<State, 1> m_stateStack;
unsigned m_unrealizedSaveCount;
@@ -332,6 +337,8 @@ private:
MutableStylePropertyMap m_fetchedFonts;
};
+DEFINE_TYPE_CASTS(CanvasRenderingContext2D, CanvasRenderingContext, context, context->is2d(), context.is2d());
+
} // namespace WebCore
#endif
diff --git a/chromium/third_party/WebKit/Source/core/html/canvas/CanvasRenderingContext2D.idl b/chromium/third_party/WebKit/Source/core/html/canvas/CanvasRenderingContext2D.idl
index 69a3ffa2354..1c243a6b4a0 100644
--- a/chromium/third_party/WebKit/Source/core/html/canvas/CanvasRenderingContext2D.idl
+++ b/chromium/third_party/WebKit/Source/core/html/canvas/CanvasRenderingContext2D.idl
@@ -30,6 +30,7 @@ interface CanvasRenderingContext2D : CanvasRenderingContext {
void save();
void restore();
+ [RuntimeEnabled=ExperimentalCanvasFeatures, Immutable] attribute SVGMatrix currentTransform;
void scale(float sx, float sy);
void rotate(float angle);
void translate(float tx, float ty);
@@ -128,9 +129,9 @@ interface CanvasRenderingContext2D : CanvasRenderingContext {
[RaisesException] void drawImage(HTMLVideoElement? video, float x, float y);
[RaisesException] void drawImage(HTMLVideoElement? video, float x, float y, float width, float height);
[RaisesException] void drawImage(HTMLVideoElement? video, float sx, float sy, float sw, float sh, float dx, float dy, float dw, float dh);
- [EnabledAtRuntime=ExperimentalCanvasFeatures, RaisesException] void drawImage(ImageBitmap? imageBitmap, float x, float y);
- [EnabledAtRuntime=ExperimentalCanvasFeatures, RaisesException] void drawImage(ImageBitmap? imageBitmap, float x, float y, float width, float height);
- [EnabledAtRuntime=ExperimentalCanvasFeatures, RaisesException] void drawImage(ImageBitmap? imageBitmap, float sx, float sy, float sw, float sh, float dx, float dy, float dw, float dh);
+ [RuntimeEnabled=ExperimentalCanvasFeatures, RaisesException] void drawImage(ImageBitmap? imageBitmap, float x, float y);
+ [RuntimeEnabled=ExperimentalCanvasFeatures, RaisesException] void drawImage(ImageBitmap? imageBitmap, float x, float y, float width, float height);
+ [RuntimeEnabled=ExperimentalCanvasFeatures, RaisesException] void drawImage(ImageBitmap? imageBitmap, float sx, float sy, float sw, float sh, float dx, float dy, float dw, float dh);
void drawImageFromRect(HTMLImageElement image,
optional float sx, optional float sy, optional float sw, optional float sh,
@@ -153,8 +154,8 @@ interface CanvasRenderingContext2D : CanvasRenderingContext {
[RaisesException] ImageData createImageData(ImageData? imagedata);
[RaisesException] ImageData createImageData(float sw, float sh);
- [Custom] attribute custom strokeStyle;
- [Custom] attribute custom fillStyle;
+ [Custom] attribute object strokeStyle;
+ [Custom] attribute object fillStyle;
// pixel manipulation
[RaisesException] ImageData getImageData(float sx, float sy, float sw, float sh);
@@ -162,14 +163,14 @@ interface CanvasRenderingContext2D : CanvasRenderingContext {
[RaisesException] ImageData webkitGetImageDataHD(float sx, float sy, float sw, float sh);
// Focus rings
- [EnabledAtRuntime=ExperimentalCanvasFeatures] void drawSystemFocusRing(Element element);
- [EnabledAtRuntime=ExperimentalCanvasFeatures] boolean drawCustomFocusRing(Element element);
+ [RuntimeEnabled=ExperimentalCanvasFeatures] void drawSystemFocusRing(Element element);
+ [RuntimeEnabled=ExperimentalCanvasFeatures] boolean drawCustomFocusRing(Element element);
readonly attribute float webkitBackingStorePixelRatio;
[ImplementedAs=imageSmoothingEnabled] attribute boolean webkitImageSmoothingEnabled;
attribute boolean imageSmoothingEnabled;
- [EnabledAtRuntime=ExperimentalCanvasFeatures] Canvas2DContextAttributes getContextAttributes();
+ Canvas2DContextAttributes getContextAttributes();
};
diff --git a/chromium/third_party/WebKit/Source/core/html/canvas/CanvasStyle.cpp b/chromium/third_party/WebKit/Source/core/html/canvas/CanvasStyle.cpp
index 3e9e86947a5..b68421af1f6 100644
--- a/chromium/third_party/WebKit/Source/core/html/canvas/CanvasStyle.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/canvas/CanvasStyle.cpp
@@ -35,8 +35,7 @@
#include "core/html/HTMLCanvasElement.h"
#include "core/html/canvas/CanvasGradient.h"
#include "core/html/canvas/CanvasPattern.h"
-#include "core/platform/graphics/GraphicsContext.h"
-#include "wtf/Assertions.h"
+#include "platform/graphics/GraphicsContext.h"
#include "wtf/PassRefPtr.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/html/canvas/CanvasStyle.h b/chromium/third_party/WebKit/Source/core/html/canvas/CanvasStyle.h
index 0dbaf1bf14b..526ab716345 100644
--- a/chromium/third_party/WebKit/Source/core/html/canvas/CanvasStyle.h
+++ b/chromium/third_party/WebKit/Source/core/html/canvas/CanvasStyle.h
@@ -27,7 +27,7 @@
#ifndef CanvasStyle_h
#define CanvasStyle_h
-#include "core/platform/graphics/Color.h"
+#include "platform/graphics/Color.h"
#include "wtf/Assertions.h"
#include "wtf/RefCounted.h"
#include "wtf/text/WTFString.h"
diff --git a/chromium/third_party/WebKit/Source/core/html/canvas/CheckedInt.h b/chromium/third_party/WebKit/Source/core/html/canvas/CheckedInt.h
deleted file mode 100644
index 906107b0508..00000000000
--- a/chromium/third_party/WebKit/Source/core/html/canvas/CheckedInt.h
+++ /dev/null
@@ -1,819 +0,0 @@
-/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* This Source Code Form is subject to the terms of the Mozilla Public
- * License, v. 2.0. If a copy of the MPL was not distributed with this file,
- * You can obtain one at http://mozilla.org/MPL/2.0/. */
-
-/* Provides checked integers, detecting integer overflow and divide-by-0. */
-
-// Necessary modifications are made to the original CheckedInt.h file when
-// incorporating it into WebKit:
-// 1) Comment out #define MOZ_CHECKEDINT_ENABLE_MOZ_ASSERTS
-// 2) Comment out #include "mozilla/StandardInteger.h"
-// 3) Define MOZ_DELETE
-// 4) Change namespace mozilla to namespace WebCore
-
-#ifndef mozilla_CheckedInt_h_
-#define mozilla_CheckedInt_h_
-
-/*
- * Build options. Comment out these #defines to disable the corresponding
- * optional feature. Disabling features may be useful for code using
- * CheckedInt outside of Mozilla (e.g. WebKit)
- */
-
-// Enable usage of MOZ_STATIC_ASSERT to check for unsupported types.
-// If disabled, static asserts are replaced by regular assert().
-// #define MOZ_CHECKEDINT_ENABLE_MOZ_ASSERTS
-
-/*
- * End of build options
- */
-
-#ifdef MOZ_CHECKEDINT_ENABLE_MOZ_ASSERTS
-# include "mozilla/Assertions.h"
-#else
-# ifndef MOZ_STATIC_ASSERT
-# include <cassert>
-# define MOZ_STATIC_ASSERT(cond, reason) assert((cond) && reason)
-# define MOZ_ASSERT(cond, reason) assert((cond) && reason)
-# endif
-#endif
-
-// #include "mozilla/StandardInteger.h"
-
-#ifndef MOZ_DELETE
-#define MOZ_DELETE
-#endif
-
-#include <climits>
-#include <cstddef>
-
-namespace WebCore {
-
-namespace detail {
-
-/*
- * Step 1: manually record supported types
- *
- * What's nontrivial here is that there are different families of integer
- * types: basic integer types and stdint types. It is merrily undefined which
- * types from one family may be just typedefs for a type from another family.
- *
- * For example, on GCC 4.6, aside from the basic integer types, the only other
- * type that isn't just a typedef for some of them, is int8_t.
- */
-
-struct UnsupportedType {};
-
-template<typename IntegerType>
-struct IsSupportedPass2
-{
- static const bool value = false;
-};
-
-template<typename IntegerType>
-struct IsSupported
-{
- static const bool value = IsSupportedPass2<IntegerType>::value;
-};
-
-template<>
-struct IsSupported<int8_t>
-{ static const bool value = true; };
-
-template<>
-struct IsSupported<uint8_t>
-{ static const bool value = true; };
-
-template<>
-struct IsSupported<int16_t>
-{ static const bool value = true; };
-
-template<>
-struct IsSupported<uint16_t>
-{ static const bool value = true; };
-
-template<>
-struct IsSupported<int32_t>
-{ static const bool value = true; };
-
-template<>
-struct IsSupported<uint32_t>
-{ static const bool value = true; };
-
-template<>
-struct IsSupported<int64_t>
-{ static const bool value = true; };
-
-template<>
-struct IsSupported<uint64_t>
-{ static const bool value = true; };
-
-
-template<>
-struct IsSupportedPass2<char>
-{ static const bool value = true; };
-
-template<>
-struct IsSupportedPass2<unsigned char>
-{ static const bool value = true; };
-
-template<>
-struct IsSupportedPass2<short>
-{ static const bool value = true; };
-
-template<>
-struct IsSupportedPass2<unsigned short>
-{ static const bool value = true; };
-
-template<>
-struct IsSupportedPass2<int>
-{ static const bool value = true; };
-
-template<>
-struct IsSupportedPass2<unsigned int>
-{ static const bool value = true; };
-
-template<>
-struct IsSupportedPass2<long>
-{ static const bool value = true; };
-
-template<>
-struct IsSupportedPass2<unsigned long>
-{ static const bool value = true; };
-
-
-/*
- * Step 2: some integer-traits kind of stuff.
- */
-
-template<size_t Size, bool Signedness>
-struct StdintTypeForSizeAndSignedness
-{};
-
-template<>
-struct StdintTypeForSizeAndSignedness<1, true>
-{ typedef int8_t Type; };
-
-template<>
-struct StdintTypeForSizeAndSignedness<1, false>
-{ typedef uint8_t Type; };
-
-template<>
-struct StdintTypeForSizeAndSignedness<2, true>
-{ typedef int16_t Type; };
-
-template<>
-struct StdintTypeForSizeAndSignedness<2, false>
-{ typedef uint16_t Type; };
-
-template<>
-struct StdintTypeForSizeAndSignedness<4, true>
-{ typedef int32_t Type; };
-
-template<>
-struct StdintTypeForSizeAndSignedness<4, false>
-{ typedef uint32_t Type; };
-
-template<>
-struct StdintTypeForSizeAndSignedness<8, true>
-{ typedef int64_t Type; };
-
-template<>
-struct StdintTypeForSizeAndSignedness<8, false>
-{ typedef uint64_t Type; };
-
-template<typename IntegerType>
-struct UnsignedType
-{
- typedef typename StdintTypeForSizeAndSignedness<sizeof(IntegerType),
- false>::Type Type;
-};
-
-template<typename IntegerType>
-struct IsSigned
-{
- static const bool value = IntegerType(-1) <= IntegerType(0);
-};
-
-template<typename IntegerType, size_t Size = sizeof(IntegerType)>
-struct TwiceBiggerType
-{
- typedef typename StdintTypeForSizeAndSignedness<
- sizeof(IntegerType) * 2,
- IsSigned<IntegerType>::value
- >::Type Type;
-};
-
-template<typename IntegerType>
-struct TwiceBiggerType<IntegerType, 8>
-{
- typedef UnsupportedType Type;
-};
-
-template<typename IntegerType>
-struct PositionOfSignBit
-{
- static const size_t value = CHAR_BIT * sizeof(IntegerType) - 1;
-};
-
-template<typename IntegerType>
-struct MinValue
-{
- private:
- typedef typename UnsignedType<IntegerType>::Type UnsignedIntegerType;
- static const size_t PosOfSignBit = PositionOfSignBit<IntegerType>::value;
-
- public:
- // Bitwise ops may return a larger type, that's why we cast explicitly.
- // In C++, left bit shifts on signed values is undefined by the standard
- // unless the shifted value is representable.
- // Notice that signed-to-unsigned conversions are always well-defined in
- // the standard as the value congruent to 2**n, as expected. By contrast,
- // unsigned-to-signed is only well-defined if the value is representable.
- static const IntegerType value =
- IsSigned<IntegerType>::value
- ? IntegerType(UnsignedIntegerType(1) << PosOfSignBit)
- : IntegerType(0);
-};
-
-template<typename IntegerType>
-struct MaxValue
-{
- // Tricksy, but covered by the unit test.
- // Relies heavily on the type of MinValue<IntegerType>::value
- // being IntegerType.
- static const IntegerType value = ~MinValue<IntegerType>::value;
-};
-
-/*
- * Step 3: Implement the actual validity checks.
- *
- * Ideas taken from IntegerLib, code different.
- */
-
-template<typename T>
-inline bool
-HasSignBit(T x)
-{
- // In C++, right bit shifts on negative values is undefined by the standard.
- // Notice that signed-to-unsigned conversions are always well-defined in the
- // standard, as the value congruent modulo 2**n as expected. By contrast,
- // unsigned-to-signed is only well-defined if the value is representable.
- return bool(typename UnsignedType<T>::Type(x)
- >> PositionOfSignBit<T>::value);
-}
-
-// Bitwise ops may return a larger type, so it's good to use this inline
-// helper guaranteeing that the result is really of type T.
-template<typename T>
-inline T
-BinaryComplement(T x)
-{
- return ~x;
-}
-
-template<typename T,
- typename U,
- bool IsTSigned = IsSigned<T>::value,
- bool IsUSigned = IsSigned<U>::value>
-struct DoesRangeContainRange
-{
-};
-
-template<typename T, typename U, bool Signedness>
-struct DoesRangeContainRange<T, U, Signedness, Signedness>
-{
- static const bool value = sizeof(T) >= sizeof(U);
-};
-
-template<typename T, typename U>
-struct DoesRangeContainRange<T, U, true, false>
-{
- static const bool value = sizeof(T) > sizeof(U);
-};
-
-template<typename T, typename U>
-struct DoesRangeContainRange<T, U, false, true>
-{
- static const bool value = false;
-};
-
-template<typename T,
- typename U,
- bool IsTSigned = IsSigned<T>::value,
- bool IsUSigned = IsSigned<U>::value,
- bool DoesTRangeContainURange = DoesRangeContainRange<T, U>::value>
-struct IsInRangeImpl {};
-
-template<typename T, typename U, bool IsTSigned, bool IsUSigned>
-struct IsInRangeImpl<T, U, IsTSigned, IsUSigned, true>
-{
- static bool run(U)
- {
- return true;
- }
-};
-
-template<typename T, typename U>
-struct IsInRangeImpl<T, U, true, true, false>
-{
- static bool run(U x)
- {
- return x <= MaxValue<T>::value && x >= MinValue<T>::value;
- }
-};
-
-template<typename T, typename U>
-struct IsInRangeImpl<T, U, false, false, false>
-{
- static bool run(U x)
- {
- return x <= MaxValue<T>::value;
- }
-};
-
-template<typename T, typename U>
-struct IsInRangeImpl<T, U, true, false, false>
-{
- static bool run(U x)
- {
- return sizeof(T) > sizeof(U) || x <= U(MaxValue<T>::value);
- }
-};
-
-template<typename T, typename U>
-struct IsInRangeImpl<T, U, false, true, false>
-{
- static bool run(U x)
- {
- return sizeof(T) >= sizeof(U)
- ? x >= 0
- : x >= 0 && x <= U(MaxValue<T>::value);
- }
-};
-
-template<typename T, typename U>
-inline bool
-IsInRange(U x)
-{
- return IsInRangeImpl<T, U>::run(x);
-}
-
-template<typename T>
-inline bool
-IsAddValid(T x, T y)
-{
- // Addition is valid if the sign of x+y is equal to either that of x or that
- // of y. Since the value of x+y is undefined if we have a signed type, we
- // compute it using the unsigned type of the same size.
- // Beware! These bitwise operations can return a larger integer type,
- // if T was a small type like int8_t, so we explicitly cast to T.
-
- typename UnsignedType<T>::Type ux = x;
- typename UnsignedType<T>::Type uy = y;
- typename UnsignedType<T>::Type result = ux + uy;
- return IsSigned<T>::value
- ? HasSignBit(BinaryComplement(T((result ^ x) & (result ^ y))))
- : BinaryComplement(x) >= y;
-}
-
-template<typename T>
-inline bool
-IsSubValid(T x, T y)
-{
- // Subtraction is valid if either x and y have same sign, or x-y and x have
- // same sign. Since the value of x-y is undefined if we have a signed type,
- // we compute it using the unsigned type of the same size.
- typename UnsignedType<T>::Type ux = x;
- typename UnsignedType<T>::Type uy = y;
- typename UnsignedType<T>::Type result = ux - uy;
-
- return IsSigned<T>::value
- ? HasSignBit(BinaryComplement(T((result ^ x) & (x ^ y))))
- : x >= y;
-}
-
-template<typename T,
- bool IsSigned = IsSigned<T>::value,
- bool TwiceBiggerTypeIsSupported =
- IsSupported<typename TwiceBiggerType<T>::Type>::value>
-struct IsMulValidImpl {};
-
-template<typename T, bool IsSigned>
-struct IsMulValidImpl<T, IsSigned, true>
-{
- static bool run(T x, T y)
- {
- typedef typename TwiceBiggerType<T>::Type TwiceBiggerType;
- TwiceBiggerType product = TwiceBiggerType(x) * TwiceBiggerType(y);
- return IsInRange<T>(product);
- }
-};
-
-template<typename T>
-struct IsMulValidImpl<T, true, false>
-{
- static bool run(T x, T y)
- {
- const T max = MaxValue<T>::value;
- const T min = MinValue<T>::value;
-
- if (x == 0 || y == 0)
- return true;
-
- if (x > 0) {
- return y > 0
- ? x <= max / y
- : y >= min / x;
- }
-
- // If we reach this point, we know that x < 0.
- return y > 0
- ? x >= min / y
- : y >= max / x;
- }
-};
-
-template<typename T>
-struct IsMulValidImpl<T, false, false>
-{
- static bool run(T x, T y)
- {
- return y == 0 || x <= MaxValue<T>::value / y;
- }
-};
-
-template<typename T>
-inline bool
-IsMulValid(T x, T y)
-{
- return IsMulValidImpl<T>::run(x, y);
-}
-
-template<typename T>
-inline bool
-IsDivValid(T x, T y)
-{
- // Keep in mind that in the signed case, min/-1 is invalid because abs(min)>max.
- return y != 0 &&
- !(IsSigned<T>::value && x == MinValue<T>::value && y == T(-1));
-}
-
-// This is just to shut up msvc warnings about negating unsigned ints.
-template<typename T, bool IsSigned = IsSigned<T>::value>
-struct OppositeIfSignedImpl
-{
- static T run(T x) { return -x; }
-};
-template<typename T>
-struct OppositeIfSignedImpl<T, false>
-{
- static T run(T x) { return x; }
-};
-template<typename T>
-inline T
-OppositeIfSigned(T x)
-{
- return OppositeIfSignedImpl<T>::run(x);
-}
-
-} // namespace detail
-
-
-/*
- * Step 4: Now define the CheckedInt class.
- */
-
-/**
- * @class CheckedInt
- * @brief Integer wrapper class checking for integer overflow and other errors
- * @param T the integer type to wrap. Can be any type among the following:
- * - any basic integer type such as |int|
- * - any stdint type such as |int8_t|
- *
- * This class implements guarded integer arithmetic. Do a computation, check
- * that isValid() returns true, you then have a guarantee that no problem, such
- * as integer overflow, happened during this computation, and you can call
- * value() to get the plain integer value.
- *
- * The arithmetic operators in this class are guaranteed not to raise a signal
- * (e.g. in case of a division by zero).
- *
- * For example, suppose that you want to implement a function that computes
- * (x+y)/z, that doesn't crash if z==0, and that reports on error (divide by
- * zero or integer overflow). You could code it as follows:
- @code
- bool computeXPlusYOverZ(int x, int y, int z, int *result)
- {
- CheckedInt<int> checkedResult = (CheckedInt<int>(x) + y) / z;
- if (checkedResult.isValid()) {
- *result = checkedResult.value();
- return true;
- } else {
- return false;
- }
- }
- @endcode
- *
- * Implicit conversion from plain integers to checked integers is allowed. The
- * plain integer is checked to be in range before being casted to the
- * destination type. This means that the following lines all compile, and the
- * resulting CheckedInts are correctly detected as valid or invalid:
- * @code
- // 1 is of type int, is found to be in range for uint8_t, x is valid
- CheckedInt<uint8_t> x(1);
- // -1 is of type int, is found not to be in range for uint8_t, x is invalid
- CheckedInt<uint8_t> x(-1);
- // -1 is of type int, is found to be in range for int8_t, x is valid
- CheckedInt<int8_t> x(-1);
- // 1000 is of type int16_t, is found not to be in range for int8_t,
- // x is invalid
- CheckedInt<int8_t> x(int16_t(1000));
- // 3123456789 is of type uint32_t, is found not to be in range for int32_t,
- // x is invalid
- CheckedInt<int32_t> x(uint32_t(3123456789));
- * @endcode
- * Implicit conversion from
- * checked integers to plain integers is not allowed. As shown in the
- * above example, to get the value of a checked integer as a normal integer,
- * call value().
- *
- * Arithmetic operations between checked and plain integers is allowed; the
- * result type is the type of the checked integer.
- *
- * Checked integers of different types cannot be used in the same arithmetic
- * expression.
- *
- * There are convenience typedefs for all stdint types, of the following form
- * (these are just 2 examples):
- @code
- typedef CheckedInt<int32_t> CheckedInt32;
- typedef CheckedInt<uint16_t> CheckedUint16;
- @endcode
- */
-template<typename T>
-class CheckedInt
-{
- protected:
- T mValue;
- bool mIsValid;
-
- template<typename U>
- CheckedInt(U value, bool isValid) : mValue(value), mIsValid(isValid)
- {
- MOZ_STATIC_ASSERT(detail::IsSupported<T>::value,
- "This type is not supported by CheckedInt");
- }
-
- public:
- /**
- * Constructs a checked integer with given @a value. The checked integer is
- * initialized as valid or invalid depending on whether the @a value
- * is in range.
- *
- * This constructor is not explicit. Instead, the type of its argument is a
- * separate template parameter, ensuring that no conversion is performed
- * before this constructor is actually called. As explained in the above
- * documentation for class CheckedInt, this constructor checks that its
- * argument is valid.
- */
- template<typename U>
- CheckedInt(U value)
- : mValue(T(value)),
- mIsValid(detail::IsInRange<T>(value))
- {
- MOZ_STATIC_ASSERT(detail::IsSupported<T>::value,
- "This type is not supported by CheckedInt");
- }
-
- /** Constructs a valid checked integer with initial value 0 */
- CheckedInt() : mValue(0), mIsValid(true)
- {
- MOZ_STATIC_ASSERT(detail::IsSupported<T>::value,
- "This type is not supported by CheckedInt");
- }
-
- /** @returns the actual value */
- T value() const
- {
- MOZ_ASSERT(mIsValid, "Invalid checked integer (division by zero or integer overflow)");
- return mValue;
- }
-
- /**
- * @returns true if the checked integer is valid, i.e. is not the result
- * of an invalid operation or of an operation involving an invalid checked
- * integer
- */
- bool isValid() const
- {
- return mIsValid;
- }
-
- template<typename U>
- friend CheckedInt<U> operator +(const CheckedInt<U>& lhs,
- const CheckedInt<U>& rhs);
- template<typename U>
- CheckedInt& operator +=(U rhs);
- template<typename U>
- friend CheckedInt<U> operator -(const CheckedInt<U>& lhs,
- const CheckedInt<U> &rhs);
- template<typename U>
- CheckedInt& operator -=(U rhs);
- template<typename U>
- friend CheckedInt<U> operator *(const CheckedInt<U>& lhs,
- const CheckedInt<U> &rhs);
- template<typename U>
- CheckedInt& operator *=(U rhs);
- template<typename U>
- friend CheckedInt<U> operator /(const CheckedInt<U>& lhs,
- const CheckedInt<U> &rhs);
- template<typename U>
- CheckedInt& operator /=(U rhs);
-
- CheckedInt operator -() const
- {
- // Circumvent msvc warning about - applied to unsigned int.
- // if we're unsigned, the only valid case anyway is 0
- // in which case - is a no-op.
- T result = detail::OppositeIfSigned(mValue);
- /* Help the compiler perform RVO (return value optimization). */
- return CheckedInt(result,
- mIsValid && detail::IsSubValid(T(0),
- mValue));
- }
-
- /**
- * @returns true if the left and right hand sides are valid
- * and have the same value.
- *
- * Note that these semantics are the reason why we don't offer
- * a operator!=. Indeed, we'd want to have a!=b be equivalent to !(a==b)
- * but that would mean that whenever a or b is invalid, a!=b
- * is always true, which would be very confusing.
- *
- * For similar reasons, operators <, >, <=, >= would be very tricky to
- * specify, so we just avoid offering them.
- *
- * Notice that these == semantics are made more reasonable by these facts:
- * 1. a==b implies equality at the raw data level
- * (the converse is false, as a==b is never true among invalids)
- * 2. This is similar to the behavior of IEEE floats, where a==b
- * means that a and b have the same value *and* neither is NaN.
- */
- bool operator ==(const CheckedInt& other) const
- {
- return mIsValid && other.mIsValid && mValue == other.mValue;
- }
-
- /** prefix ++ */
- CheckedInt& operator++()
- {
- *this += 1;
- return *this;
- }
-
- /** postfix ++ */
- CheckedInt operator++(int)
- {
- CheckedInt tmp = *this;
- *this += 1;
- return tmp;
- }
-
- /** prefix -- */
- CheckedInt& operator--()
- {
- *this -= 1;
- return *this;
- }
-
- /** postfix -- */
- CheckedInt operator--(int)
- {
- CheckedInt tmp = *this;
- *this -= 1;
- return tmp;
- }
-
- private:
- /**
- * The !=, <, <=, >, >= operators are disabled:
- * see the comment on operator==.
- */
- template<typename U>
- bool operator !=(U other) const MOZ_DELETE;
- template<typename U>
- bool operator <(U other) const MOZ_DELETE;
- template<typename U>
- bool operator <=(U other) const MOZ_DELETE;
- template<typename U>
- bool operator >(U other) const MOZ_DELETE;
- template<typename U>
- bool operator >=(U other) const MOZ_DELETE;
-};
-
-#define MOZ_CHECKEDINT_BASIC_BINARY_OPERATOR(NAME, OP) \
-template<typename T> \
-inline CheckedInt<T> operator OP(const CheckedInt<T> &lhs, \
- const CheckedInt<T> &rhs) \
-{ \
- if (!detail::Is##NAME##Valid(lhs.mValue, rhs.mValue)) \
- return CheckedInt<T>(0, false); \
- \
- return CheckedInt<T>(lhs.mValue OP rhs.mValue, \
- lhs.mIsValid && rhs.mIsValid); \
-}
-
-MOZ_CHECKEDINT_BASIC_BINARY_OPERATOR(Add, +)
-MOZ_CHECKEDINT_BASIC_BINARY_OPERATOR(Sub, -)
-MOZ_CHECKEDINT_BASIC_BINARY_OPERATOR(Mul, *)
-MOZ_CHECKEDINT_BASIC_BINARY_OPERATOR(Div, /)
-
-#undef MOZ_CHECKEDINT_BASIC_BINARY_OPERATOR
-
-// Implement castToCheckedInt<T>(x), making sure that
-// - it allows x to be either a CheckedInt<T> or any integer type
-// that can be casted to T
-// - if x is already a CheckedInt<T>, we just return a reference to it,
-// instead of copying it (optimization)
-
-namespace detail {
-
-template<typename T, typename U>
-struct CastToCheckedIntImpl
-{
- typedef CheckedInt<T> ReturnType;
- static CheckedInt<T> run(U u) { return u; }
-};
-
-template<typename T>
-struct CastToCheckedIntImpl<T, CheckedInt<T> >
-{
- typedef const CheckedInt<T>& ReturnType;
- static const CheckedInt<T>& run(const CheckedInt<T>& u) { return u; }
-};
-
-} // namespace detail
-
-template<typename T, typename U>
-inline typename detail::CastToCheckedIntImpl<T, U>::ReturnType
-castToCheckedInt(U u)
-{
- return detail::CastToCheckedIntImpl<T, U>::run(u);
-}
-
-#define MOZ_CHECKEDINT_CONVENIENCE_BINARY_OPERATORS(OP, COMPOUND_OP) \
-template<typename T> \
-template<typename U> \
-CheckedInt<T>& CheckedInt<T>::operator COMPOUND_OP(U rhs) \
-{ \
- *this = *this OP castToCheckedInt<T>(rhs); \
- return *this; \
-} \
-template<typename T, typename U> \
-inline CheckedInt<T> operator OP(const CheckedInt<T> &lhs, U rhs) \
-{ \
- return lhs OP castToCheckedInt<T>(rhs); \
-} \
-template<typename T, typename U> \
-inline CheckedInt<T> operator OP(U lhs, const CheckedInt<T> &rhs) \
-{ \
- return castToCheckedInt<T>(lhs) OP rhs; \
-}
-
-MOZ_CHECKEDINT_CONVENIENCE_BINARY_OPERATORS(+, +=)
-MOZ_CHECKEDINT_CONVENIENCE_BINARY_OPERATORS(*, *=)
-MOZ_CHECKEDINT_CONVENIENCE_BINARY_OPERATORS(-, -=)
-MOZ_CHECKEDINT_CONVENIENCE_BINARY_OPERATORS(/, /=)
-
-#undef MOZ_CHECKEDINT_CONVENIENCE_BINARY_OPERATORS
-
-template<typename T, typename U>
-inline bool
-operator ==(const CheckedInt<T> &lhs, U rhs)
-{
- return lhs == castToCheckedInt<T>(rhs);
-}
-
-template<typename T, typename U>
-inline bool
-operator ==(U lhs, const CheckedInt<T> &rhs)
-{
- return castToCheckedInt<T>(lhs) == rhs;
-}
-
-// Convenience typedefs.
-typedef CheckedInt<int8_t> CheckedInt8;
-typedef CheckedInt<uint8_t> CheckedUint8;
-typedef CheckedInt<int16_t> CheckedInt16;
-typedef CheckedInt<uint16_t> CheckedUint16;
-typedef CheckedInt<int32_t> CheckedInt32;
-typedef CheckedInt<uint32_t> CheckedUint32;
-typedef CheckedInt<int64_t> CheckedInt64;
-typedef CheckedInt<uint64_t> CheckedUint64;
-
-} // namespace WebCore
-
-#endif /* mozilla_CheckedInt_h_ */
diff --git a/chromium/third_party/WebKit/Source/core/html/canvas/DataView.cpp b/chromium/third_party/WebKit/Source/core/html/canvas/DataView.cpp
index b35984dd43e..5a28161937c 100644
--- a/chromium/third_party/WebKit/Source/core/html/canvas/DataView.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/canvas/DataView.cpp
@@ -28,7 +28,7 @@
#include "bindings/v8/ExceptionState.h"
#include "core/dom/ExceptionCode.h"
-#include "core/html/canvas/CheckedInt.h"
+#include "platform/CheckedInt.h"
#include "wtf/CPU.h"
namespace {
@@ -130,10 +130,10 @@ static void flipBytesIfNeeded(char* value, size_t size, bool littleEndian)
}
template<typename T>
-T DataView::getData(unsigned byteOffset, bool littleEndian, ExceptionState& es) const
+T DataView::getData(unsigned byteOffset, bool littleEndian, ExceptionState& exceptionState) const
{
if (beyondRange<T>(byteOffset)) {
- es.throwDOMException(IndexSizeError);
+ exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
return 0;
}
@@ -145,10 +145,10 @@ T DataView::getData(unsigned byteOffset, bool littleEndian, ExceptionState& es)
}
template<typename T>
-void DataView::setData(unsigned byteOffset, T value, bool littleEndian, ExceptionState& es)
+void DataView::setData(unsigned byteOffset, T value, bool littleEndian, ExceptionState& exceptionState)
{
if (beyondRange<T>(byteOffset)) {
- es.throwDOMException(IndexSizeError);
+ exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
return;
}
@@ -159,84 +159,84 @@ void DataView::setData(unsigned byteOffset, T value, bool littleEndian, Exceptio
memcpy(static_cast<char*>(m_baseAddress) + byteOffset, tempValue.bytes, sizeof(T));
}
-int8_t DataView::getInt8(unsigned byteOffset, ExceptionState& es)
+int8_t DataView::getInt8(unsigned byteOffset, ExceptionState& exceptionState)
{
- return getData<int8_t>(byteOffset, false, es);
+ return getData<int8_t>(byteOffset, false, exceptionState);
}
-uint8_t DataView::getUint8(unsigned byteOffset, ExceptionState& es)
+uint8_t DataView::getUint8(unsigned byteOffset, ExceptionState& exceptionState)
{
- return getData<uint8_t>(byteOffset, false, es);
+ return getData<uint8_t>(byteOffset, false, exceptionState);
}
-int16_t DataView::getInt16(unsigned byteOffset, bool littleEndian, ExceptionState& es)
+int16_t DataView::getInt16(unsigned byteOffset, bool littleEndian, ExceptionState& exceptionState)
{
- return getData<int16_t>(byteOffset, littleEndian, es);
+ return getData<int16_t>(byteOffset, littleEndian, exceptionState);
}
-uint16_t DataView::getUint16(unsigned byteOffset, bool littleEndian, ExceptionState& es)
+uint16_t DataView::getUint16(unsigned byteOffset, bool littleEndian, ExceptionState& exceptionState)
{
- return getData<uint16_t>(byteOffset, littleEndian, es);
+ return getData<uint16_t>(byteOffset, littleEndian, exceptionState);
}
-int32_t DataView::getInt32(unsigned byteOffset, bool littleEndian, ExceptionState& es)
+int32_t DataView::getInt32(unsigned byteOffset, bool littleEndian, ExceptionState& exceptionState)
{
- return getData<int32_t>(byteOffset, littleEndian, es);
+ return getData<int32_t>(byteOffset, littleEndian, exceptionState);
}
-uint32_t DataView::getUint32(unsigned byteOffset, bool littleEndian, ExceptionState& es)
+uint32_t DataView::getUint32(unsigned byteOffset, bool littleEndian, ExceptionState& exceptionState)
{
- return getData<uint32_t>(byteOffset, littleEndian, es);
+ return getData<uint32_t>(byteOffset, littleEndian, exceptionState);
}
-float DataView::getFloat32(unsigned byteOffset, bool littleEndian, ExceptionState& es)
+float DataView::getFloat32(unsigned byteOffset, bool littleEndian, ExceptionState& exceptionState)
{
- return getData<float>(byteOffset, littleEndian, es);
+ return getData<float>(byteOffset, littleEndian, exceptionState);
}
-double DataView::getFloat64(unsigned byteOffset, bool littleEndian, ExceptionState& es)
+double DataView::getFloat64(unsigned byteOffset, bool littleEndian, ExceptionState& exceptionState)
{
- return getData<double>(byteOffset, littleEndian, es);
+ return getData<double>(byteOffset, littleEndian, exceptionState);
}
-void DataView::setInt8(unsigned byteOffset, int8_t value, ExceptionState& es)
+void DataView::setInt8(unsigned byteOffset, int8_t value, ExceptionState& exceptionState)
{
- setData<int8_t>(byteOffset, value, false, es);
+ setData<int8_t>(byteOffset, value, false, exceptionState);
}
-void DataView::setUint8(unsigned byteOffset, uint8_t value, ExceptionState& es)
+void DataView::setUint8(unsigned byteOffset, uint8_t value, ExceptionState& exceptionState)
{
- setData<uint8_t>(byteOffset, value, false, es);
+ setData<uint8_t>(byteOffset, value, false, exceptionState);
}
-void DataView::setInt16(unsigned byteOffset, short value, bool littleEndian, ExceptionState& es)
+void DataView::setInt16(unsigned byteOffset, short value, bool littleEndian, ExceptionState& exceptionState)
{
- setData<int16_t>(byteOffset, value, littleEndian, es);
+ setData<int16_t>(byteOffset, value, littleEndian, exceptionState);
}
-void DataView::setUint16(unsigned byteOffset, uint16_t value, bool littleEndian, ExceptionState& es)
+void DataView::setUint16(unsigned byteOffset, uint16_t value, bool littleEndian, ExceptionState& exceptionState)
{
- setData<uint16_t>(byteOffset, value, littleEndian, es);
+ setData<uint16_t>(byteOffset, value, littleEndian, exceptionState);
}
-void DataView::setInt32(unsigned byteOffset, int32_t value, bool littleEndian, ExceptionState& es)
+void DataView::setInt32(unsigned byteOffset, int32_t value, bool littleEndian, ExceptionState& exceptionState)
{
- setData<int32_t>(byteOffset, value, littleEndian, es);
+ setData<int32_t>(byteOffset, value, littleEndian, exceptionState);
}
-void DataView::setUint32(unsigned byteOffset, uint32_t value, bool littleEndian, ExceptionState& es)
+void DataView::setUint32(unsigned byteOffset, uint32_t value, bool littleEndian, ExceptionState& exceptionState)
{
- setData<uint32_t>(byteOffset, value, littleEndian, es);
+ setData<uint32_t>(byteOffset, value, littleEndian, exceptionState);
}
-void DataView::setFloat32(unsigned byteOffset, float value, bool littleEndian, ExceptionState& es)
+void DataView::setFloat32(unsigned byteOffset, float value, bool littleEndian, ExceptionState& exceptionState)
{
- setData<float>(byteOffset, value, littleEndian, es);
+ setData<float>(byteOffset, value, littleEndian, exceptionState);
}
-void DataView::setFloat64(unsigned byteOffset, double value, bool littleEndian, ExceptionState& es)
+void DataView::setFloat64(unsigned byteOffset, double value, bool littleEndian, ExceptionState& exceptionState)
{
- setData<double>(byteOffset, value, littleEndian, es);
+ setData<double>(byteOffset, value, littleEndian, exceptionState);
}
void DataView::neuter()
diff --git a/chromium/third_party/WebKit/Source/core/html/canvas/DataView.idl b/chromium/third_party/WebKit/Source/core/html/canvas/DataView.idl
index 5847f9c1d37..a9b9facac3e 100644
--- a/chromium/third_party/WebKit/Source/core/html/canvas/DataView.idl
+++ b/chromium/third_party/WebKit/Source/core/html/canvas/DataView.idl
@@ -24,9 +24,9 @@
*/
[
- GlobalContext=Window&WorkerGlobalScope,
+ Custom=Wrap,
CustomConstructor(ArrayBuffer buffer, optional unsigned long byteOffset, optional unsigned long byteLength),
- CustomToV8
+ GlobalContext=Window&WorkerGlobalScope,
] interface DataView : ArrayBufferView {
// All these methods raise an exception if they would read or write beyond the end of the view.
diff --git a/chromium/third_party/WebKit/Source/core/html/canvas/EXTFragDepth.cpp b/chromium/third_party/WebKit/Source/core/html/canvas/EXTFragDepth.cpp
index dbc55a41630..a2484d283d3 100644
--- a/chromium/third_party/WebKit/Source/core/html/canvas/EXTFragDepth.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/canvas/EXTFragDepth.cpp
@@ -27,7 +27,7 @@
#include "core/html/canvas/EXTFragDepth.h"
-#include "core/platform/graphics/Extensions3D.h"
+#include "platform/graphics/Extensions3D.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/html/canvas/EXTTextureFilterAnisotropic.cpp b/chromium/third_party/WebKit/Source/core/html/canvas/EXTTextureFilterAnisotropic.cpp
index 6f3f9440d7b..231c3c58662 100644
--- a/chromium/third_party/WebKit/Source/core/html/canvas/EXTTextureFilterAnisotropic.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/canvas/EXTTextureFilterAnisotropic.cpp
@@ -26,7 +26,7 @@
#include "config.h"
#include "core/html/canvas/EXTTextureFilterAnisotropic.h"
-#include "core/platform/graphics/Extensions3D.h"
+#include "platform/graphics/Extensions3D.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/html/canvas/OESElementIndexUint.cpp b/chromium/third_party/WebKit/Source/core/html/canvas/OESElementIndexUint.cpp
index af87a99a23f..a4b0e29c94d 100644
--- a/chromium/third_party/WebKit/Source/core/html/canvas/OESElementIndexUint.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/canvas/OESElementIndexUint.cpp
@@ -26,7 +26,7 @@
#include "config.h"
#include "core/html/canvas/OESElementIndexUint.h"
-#include "core/platform/graphics/Extensions3D.h"
+#include "platform/graphics/Extensions3D.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/html/canvas/OESStandardDerivatives.cpp b/chromium/third_party/WebKit/Source/core/html/canvas/OESStandardDerivatives.cpp
index 36bf2dcec81..aec473bc686 100644
--- a/chromium/third_party/WebKit/Source/core/html/canvas/OESStandardDerivatives.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/canvas/OESStandardDerivatives.cpp
@@ -26,7 +26,7 @@
#include "config.h"
#include "core/html/canvas/OESStandardDerivatives.h"
-#include "core/platform/graphics/Extensions3D.h"
+#include "platform/graphics/Extensions3D.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/html/canvas/OESTextureFloat.cpp b/chromium/third_party/WebKit/Source/core/html/canvas/OESTextureFloat.cpp
index 5b102089255..99d1387376c 100644
--- a/chromium/third_party/WebKit/Source/core/html/canvas/OESTextureFloat.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/canvas/OESTextureFloat.cpp
@@ -26,7 +26,7 @@
#include "config.h"
#include "core/html/canvas/OESTextureFloat.h"
-#include "core/platform/graphics/Extensions3D.h"
+#include "platform/graphics/Extensions3D.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/html/canvas/OESTextureFloatLinear.cpp b/chromium/third_party/WebKit/Source/core/html/canvas/OESTextureFloatLinear.cpp
index b7ddd053bcd..1e8518d95d6 100644
--- a/chromium/third_party/WebKit/Source/core/html/canvas/OESTextureFloatLinear.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/canvas/OESTextureFloatLinear.cpp
@@ -27,7 +27,7 @@
#include "core/html/canvas/OESTextureFloatLinear.h"
-#include "core/platform/graphics/Extensions3D.h"
+#include "platform/graphics/Extensions3D.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/html/canvas/OESTextureHalfFloat.cpp b/chromium/third_party/WebKit/Source/core/html/canvas/OESTextureHalfFloat.cpp
index f3b3bd6565f..7253837aa42 100644
--- a/chromium/third_party/WebKit/Source/core/html/canvas/OESTextureHalfFloat.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/canvas/OESTextureHalfFloat.cpp
@@ -26,7 +26,7 @@
#include "config.h"
#include "core/html/canvas/OESTextureHalfFloat.h"
-#include "core/platform/graphics/Extensions3D.h"
+#include "platform/graphics/Extensions3D.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/html/canvas/OESTextureHalfFloatLinear.cpp b/chromium/third_party/WebKit/Source/core/html/canvas/OESTextureHalfFloatLinear.cpp
index c8ba20c0ccc..c7da9bd745b 100644
--- a/chromium/third_party/WebKit/Source/core/html/canvas/OESTextureHalfFloatLinear.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/canvas/OESTextureHalfFloatLinear.cpp
@@ -27,7 +27,7 @@
#include "core/html/canvas/OESTextureHalfFloatLinear.h"
-#include "core/platform/graphics/Extensions3D.h"
+#include "platform/graphics/Extensions3D.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/html/canvas/OESVertexArrayObject.cpp b/chromium/third_party/WebKit/Source/core/html/canvas/OESVertexArrayObject.cpp
index 5ff1af87a92..848c85f5557 100644
--- a/chromium/third_party/WebKit/Source/core/html/canvas/OESVertexArrayObject.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/canvas/OESVertexArrayObject.cpp
@@ -30,7 +30,7 @@
#include "bindings/v8/ExceptionState.h"
#include "core/html/canvas/WebGLRenderingContext.h"
#include "core/html/canvas/WebGLVertexArrayObjectOES.h"
-#include "core/platform/graphics/Extensions3D.h"
+#include "platform/graphics/Extensions3D.h"
namespace WebCore {
@@ -94,7 +94,7 @@ void OESVertexArrayObject::bindVertexArrayOES(WebGLVertexArrayObjectOES* arrayOb
return;
if (arrayObject && (arrayObject->isDeleted() || !arrayObject->validate(0, context()))) {
- m_context->graphicsContext3D()->synthesizeGLError(GraphicsContext3D::INVALID_OPERATION);
+ m_context->graphicsContext3D()->synthesizeGLError(GL_INVALID_OPERATION);
return;
}
diff --git a/chromium/third_party/WebKit/Source/core/html/canvas/OESVertexArrayObject.h b/chromium/third_party/WebKit/Source/core/html/canvas/OESVertexArrayObject.h
index 1ac17259fe1..2fd0735f21a 100644
--- a/chromium/third_party/WebKit/Source/core/html/canvas/OESVertexArrayObject.h
+++ b/chromium/third_party/WebKit/Source/core/html/canvas/OESVertexArrayObject.h
@@ -28,7 +28,7 @@
#include "bindings/v8/ScriptWrappable.h"
#include "core/html/canvas/WebGLExtension.h"
-#include "core/platform/graphics/GraphicsTypes3D.h"
+#include "platform/graphics/GraphicsTypes3D.h"
#include "wtf/PassRefPtr.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/html/canvas/Path.idl b/chromium/third_party/WebKit/Source/core/html/canvas/Path.idl
index ce19874b973..66435a5da46 100644
--- a/chromium/third_party/WebKit/Source/core/html/canvas/Path.idl
+++ b/chromium/third_party/WebKit/Source/core/html/canvas/Path.idl
@@ -27,7 +27,7 @@
*/
[
- EnabledAtRuntime=ExperimentalCanvasFeatures,
+ RuntimeEnabled=ExperimentalCanvasFeatures,
Constructor,
Constructor(Path path),
Constructor(DOMString text),
diff --git a/chromium/third_party/WebKit/Source/core/html/canvas/WebGLActiveInfo.h b/chromium/third_party/WebKit/Source/core/html/canvas/WebGLActiveInfo.h
index 7b3f1516eb0..7571e3681ec 100644
--- a/chromium/third_party/WebKit/Source/core/html/canvas/WebGLActiveInfo.h
+++ b/chromium/third_party/WebKit/Source/core/html/canvas/WebGLActiveInfo.h
@@ -27,7 +27,7 @@
#define WebGLActiveInfo_h
#include "bindings/v8/ScriptWrappable.h"
-#include "core/platform/graphics/GraphicsContext3D.h"
+#include "platform/graphics/GraphicsContext3D.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefCounted.h"
#include "wtf/text/WTFString.h"
diff --git a/chromium/third_party/WebKit/Source/core/html/canvas/WebGLBuffer.cpp b/chromium/third_party/WebKit/Source/core/html/canvas/WebGLBuffer.cpp
index 34fb7bb787b..48bf88a1ab0 100644
--- a/chromium/third_party/WebKit/Source/core/html/canvas/WebGLBuffer.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/canvas/WebGLBuffer.cpp
@@ -59,7 +59,7 @@ void WebGLBuffer::setTarget(GC3Denum target)
// In WebGL, a buffer is bound to one target in its lifetime
if (m_target)
return;
- if (target == GraphicsContext3D::ARRAY_BUFFER || target == GraphicsContext3D::ELEMENT_ARRAY_BUFFER)
+ if (target == GL_ARRAY_BUFFER || target == GL_ELEMENT_ARRAY_BUFFER)
m_target = target;
}
diff --git a/chromium/third_party/WebKit/Source/core/html/canvas/WebGLCompressedTextureATC.cpp b/chromium/third_party/WebKit/Source/core/html/canvas/WebGLCompressedTextureATC.cpp
index 601ef85fad6..dad7ff49b05 100644
--- a/chromium/third_party/WebKit/Source/core/html/canvas/WebGLCompressedTextureATC.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/canvas/WebGLCompressedTextureATC.cpp
@@ -27,7 +27,7 @@
#include "core/html/canvas/WebGLCompressedTextureATC.h"
-#include "core/platform/graphics/Extensions3D.h"
+#include "platform/graphics/Extensions3D.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/html/canvas/WebGLCompressedTexturePVRTC.cpp b/chromium/third_party/WebKit/Source/core/html/canvas/WebGLCompressedTexturePVRTC.cpp
index 663dcc06e85..8ae4acd2689 100644
--- a/chromium/third_party/WebKit/Source/core/html/canvas/WebGLCompressedTexturePVRTC.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/canvas/WebGLCompressedTexturePVRTC.cpp
@@ -28,7 +28,7 @@
#include "core/html/canvas/WebGLCompressedTexturePVRTC.h"
#include "core/html/canvas/WebGLRenderingContext.h"
-#include "core/platform/graphics/Extensions3D.h"
+#include "platform/graphics/Extensions3D.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/html/canvas/WebGLCompressedTextureS3TC.cpp b/chromium/third_party/WebKit/Source/core/html/canvas/WebGLCompressedTextureS3TC.cpp
index 4b63f02315b..9d3f2543001 100644
--- a/chromium/third_party/WebKit/Source/core/html/canvas/WebGLCompressedTextureS3TC.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/canvas/WebGLCompressedTextureS3TC.cpp
@@ -28,7 +28,7 @@
#include "core/html/canvas/WebGLCompressedTextureS3TC.h"
#include "core/html/canvas/WebGLRenderingContext.h"
-#include "core/platform/graphics/Extensions3D.h"
+#include "platform/graphics/Extensions3D.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/html/canvas/WebGLContextAttributes.cpp b/chromium/third_party/WebKit/Source/core/html/canvas/WebGLContextAttributes.cpp
index a28e4cf20c2..cb26556a731 100644
--- a/chromium/third_party/WebKit/Source/core/html/canvas/WebGLContextAttributes.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/canvas/WebGLContextAttributes.cpp
@@ -117,6 +117,16 @@ void WebGLContextAttributes::setPreserveDrawingBuffer(bool preserveDrawingBuffer
m_attrs.preserveDrawingBuffer = preserveDrawingBuffer;
}
+bool WebGLContextAttributes::failIfMajorPerformanceCaveat() const
+{
+ return m_attrs.failIfMajorPerformanceCaveat;
+}
+
+void WebGLContextAttributes::setFailIfMajorPerformanceCaveat(bool failIfMajorPerformanceCaveat)
+{
+ m_attrs.failIfMajorPerformanceCaveat = failIfMajorPerformanceCaveat;
+}
+
GraphicsContext3D::Attributes WebGLContextAttributes::attributes() const
{
return m_attrs;
diff --git a/chromium/third_party/WebKit/Source/core/html/canvas/WebGLContextAttributes.h b/chromium/third_party/WebKit/Source/core/html/canvas/WebGLContextAttributes.h
index d609920e077..62a576ef736 100644
--- a/chromium/third_party/WebKit/Source/core/html/canvas/WebGLContextAttributes.h
+++ b/chromium/third_party/WebKit/Source/core/html/canvas/WebGLContextAttributes.h
@@ -29,7 +29,7 @@
#include "bindings/v8/ScriptWrappable.h"
#include "core/html/canvas/CanvasContextAttributes.h"
-#include "core/platform/graphics/GraphicsContext3D.h"
+#include "platform/graphics/GraphicsContext3D.h"
#include "wtf/PassRefPtr.h"
namespace WebCore {
@@ -71,6 +71,11 @@ public:
bool preserveDrawingBuffer() const;
void setPreserveDrawingBuffer(bool);
+ // Whether or not to fail context creation if performance will be
+ // significantly degraded compared to a native GL context; default=false
+ bool failIfMajorPerformanceCaveat() const;
+ void setFailIfMajorPerformanceCaveat(bool);
+
// Fetches a copy of the attributes stored in this object in a
// form that can be used to initialize a GraphicsContext3D.
GraphicsContext3D::Attributes attributes() const;
diff --git a/chromium/third_party/WebKit/Source/core/html/canvas/WebGLContextAttributes.idl b/chromium/third_party/WebKit/Source/core/html/canvas/WebGLContextAttributes.idl
index d97164405cc..0fe4662533a 100644
--- a/chromium/third_party/WebKit/Source/core/html/canvas/WebGLContextAttributes.idl
+++ b/chromium/third_party/WebKit/Source/core/html/canvas/WebGLContextAttributes.idl
@@ -33,4 +33,5 @@
attribute boolean antialias;
attribute boolean premultipliedAlpha;
attribute boolean preserveDrawingBuffer;
+ attribute boolean failIfMajorPerformanceCaveat;
};
diff --git a/chromium/third_party/WebKit/Source/core/html/canvas/WebGLContextEvent.cpp b/chromium/third_party/WebKit/Source/core/html/canvas/WebGLContextEvent.cpp
index 9d03537f894..7f4cf7c7576 100644
--- a/chromium/third_party/WebKit/Source/core/html/canvas/WebGLContextEvent.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/canvas/WebGLContextEvent.cpp
@@ -26,7 +26,7 @@
#include "config.h"
#include "core/html/canvas/WebGLContextEvent.h"
-#include "core/dom/EventNames.h"
+#include "core/events/ThreadLocalEventNames.h"
namespace WebCore {
@@ -59,7 +59,7 @@ WebGLContextEvent::~WebGLContextEvent()
const AtomicString& WebGLContextEvent::interfaceName() const
{
- return eventNames().interfaceForWebGLContextEvent;
+ return EventNames::WebGLContextEvent;
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/html/canvas/WebGLContextEvent.h b/chromium/third_party/WebKit/Source/core/html/canvas/WebGLContextEvent.h
index c5b0078fbb2..18f4a4812f9 100644
--- a/chromium/third_party/WebKit/Source/core/html/canvas/WebGLContextEvent.h
+++ b/chromium/third_party/WebKit/Source/core/html/canvas/WebGLContextEvent.h
@@ -26,7 +26,7 @@
#ifndef WebGLContextEvent_h
#define WebGLContextEvent_h
-#include "core/dom/Event.h"
+#include "core/events/Event.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/html/canvas/WebGLContextEvent.idl b/chromium/third_party/WebKit/Source/core/html/canvas/WebGLContextEvent.idl
index f6a30928933..18266e50817 100644
--- a/chromium/third_party/WebKit/Source/core/html/canvas/WebGLContextEvent.idl
+++ b/chromium/third_party/WebKit/Source/core/html/canvas/WebGLContextEvent.idl
@@ -24,7 +24,7 @@
*/
[
- ConstructorTemplate=Event
+ EventConstructor,
] interface WebGLContextEvent : Event {
[InitializedByEventConstructor] readonly attribute DOMString statusMessage;
};
diff --git a/chromium/third_party/WebKit/Source/core/html/canvas/WebGLContextGroup.cpp b/chromium/third_party/WebKit/Source/core/html/canvas/WebGLContextGroup.cpp
index 46650a6e292..93ff6f4f4f1 100644
--- a/chromium/third_party/WebKit/Source/core/html/canvas/WebGLContextGroup.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/canvas/WebGLContextGroup.cpp
@@ -27,7 +27,6 @@
#include "core/html/canvas/WebGLContextGroup.h"
-#include "core/html/canvas/WebGLRenderingContext.h"
#include "core/html/canvas/WebGLSharedObject.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/html/canvas/WebGLContextGroup.h b/chromium/third_party/WebKit/Source/core/html/canvas/WebGLContextGroup.h
index 3bd00563a7c..b1fece9111b 100644
--- a/chromium/third_party/WebKit/Source/core/html/canvas/WebGLContextGroup.h
+++ b/chromium/third_party/WebKit/Source/core/html/canvas/WebGLContextGroup.h
@@ -40,10 +40,10 @@ class WebGLRenderingContext;
typedef int ExceptionCode;
-class WebGLContextGroup : public RefCounted<WebGLContextGroup> {
+class WebGLContextGroup FINAL : public RefCounted<WebGLContextGroup> {
public:
static PassRefPtr<WebGLContextGroup> create();
- virtual ~WebGLContextGroup();
+ ~WebGLContextGroup();
void addContext(WebGLRenderingContext*);
void removeContext(WebGLRenderingContext*);
diff --git a/chromium/third_party/WebKit/Source/core/html/canvas/WebGLDebugShaders.cpp b/chromium/third_party/WebKit/Source/core/html/canvas/WebGLDebugShaders.cpp
index e373c2a0206..8ecb09379d2 100644
--- a/chromium/third_party/WebKit/Source/core/html/canvas/WebGLDebugShaders.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/canvas/WebGLDebugShaders.cpp
@@ -29,7 +29,7 @@
#include "bindings/v8/ExceptionState.h"
#include "core/html/canvas/WebGLRenderingContext.h"
#include "core/html/canvas/WebGLShader.h"
-#include "core/platform/graphics/Extensions3D.h"
+#include "platform/graphics/Extensions3D.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/html/canvas/WebGLDepthTexture.cpp b/chromium/third_party/WebKit/Source/core/html/canvas/WebGLDepthTexture.cpp
index 4c873ede4fc..d42019ff82f 100644
--- a/chromium/third_party/WebKit/Source/core/html/canvas/WebGLDepthTexture.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/canvas/WebGLDepthTexture.cpp
@@ -27,7 +27,7 @@
#include "core/html/canvas/WebGLDepthTexture.h"
-#include "core/platform/graphics/Extensions3D.h"
+#include "platform/graphics/Extensions3D.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/html/canvas/WebGLDrawBuffers.cpp b/chromium/third_party/WebKit/Source/core/html/canvas/WebGLDrawBuffers.cpp
index 756476b8fb3..20b21feb5fe 100644
--- a/chromium/third_party/WebKit/Source/core/html/canvas/WebGLDrawBuffers.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/canvas/WebGLDrawBuffers.cpp
@@ -27,7 +27,7 @@
#include "core/html/canvas/WebGLDrawBuffers.h"
-#include "core/platform/graphics/Extensions3D.h"
+#include "platform/graphics/Extensions3D.h"
namespace WebCore {
@@ -73,25 +73,25 @@ void WebGLDrawBuffers::drawBuffersWEBGL(const Vector<GC3Denum>& buffers)
const GC3Denum* bufs = buffers.data();
if (!m_context->m_framebufferBinding) {
if (n != 1) {
- m_context->synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "drawBuffersWEBGL", "more than one buffer");
+ m_context->synthesizeGLError(GL_INVALID_VALUE, "drawBuffersWEBGL", "more than one buffer");
return;
}
- if (bufs[0] != GraphicsContext3D::BACK && bufs[0] != GraphicsContext3D::NONE) {
- m_context->synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "drawBuffersWEBGL", "BACK or NONE");
+ if (bufs[0] != GL_BACK && bufs[0] != GL_NONE) {
+ m_context->synthesizeGLError(GL_INVALID_OPERATION, "drawBuffersWEBGL", "BACK or NONE");
return;
}
// Because the backbuffer is simulated on all current WebKit ports, we need to change BACK to COLOR_ATTACHMENT0.
- GC3Denum value = (bufs[0] == GraphicsContext3D::BACK) ? GraphicsContext3D::COLOR_ATTACHMENT0 : GraphicsContext3D::NONE;
+ GC3Denum value = (bufs[0] == GL_BACK) ? GL_COLOR_ATTACHMENT0 : GL_NONE;
m_context->graphicsContext3D()->extensions()->drawBuffersEXT(1, &value);
m_context->setBackDrawBuffer(bufs[0]);
} else {
if (n > m_context->maxDrawBuffers()) {
- m_context->synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "drawBuffersWEBGL", "more than max draw buffers");
+ m_context->synthesizeGLError(GL_INVALID_VALUE, "drawBuffersWEBGL", "more than max draw buffers");
return;
}
for (GC3Dsizei i = 0; i < n; ++i) {
- if (bufs[i] != GraphicsContext3D::NONE && bufs[i] != static_cast<GC3Denum>(Extensions3D::COLOR_ATTACHMENT0_EXT + i)) {
- m_context->synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "drawBuffersWEBGL", "COLOR_ATTACHMENTi_EXT or NONE");
+ if (bufs[i] != GL_NONE && bufs[i] != static_cast<GC3Denum>(Extensions3D::COLOR_ATTACHMENT0_EXT + i)) {
+ m_context->synthesizeGLError(GL_INVALID_OPERATION, "drawBuffersWEBGL", "COLOR_ATTACHMENTi_EXT or NONE");
return;
}
}
@@ -113,7 +113,7 @@ bool WebGLDrawBuffers::satisfiesWebGLRequirements(WebGLRenderingContext* webglCo
return false;
Platform3DObject fbo = context->createFramebuffer();
- context->bindFramebuffer(GraphicsContext3D::FRAMEBUFFER, fbo);
+ context->bindFramebuffer(GL_FRAMEBUFFER, fbo);
const unsigned char* buffer = 0; // Chromium doesn't allow init data for depth/stencil tetxures.
bool supportsDepth = (context->extensions()->supports("GL_CHROMIUM_depth_texture")
@@ -124,14 +124,14 @@ bool WebGLDrawBuffers::satisfiesWebGLRequirements(WebGLRenderingContext* webglCo
Platform3DObject depthStencil = 0;
if (supportsDepthStencil) {
depthStencil = context->createTexture();
- context->bindTexture(GraphicsContext3D::TEXTURE_2D, depthStencil);
- context->texImage2D(GraphicsContext3D::TEXTURE_2D, 0, GraphicsContext3D::DEPTH_STENCIL, 1, 1, 0, GraphicsContext3D::DEPTH_STENCIL, GraphicsContext3D::UNSIGNED_INT_24_8, buffer);
+ context->bindTexture(GL_TEXTURE_2D, depthStencil);
+ context->texImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_STENCIL_OES, 1, 1, 0, GL_DEPTH_STENCIL_OES, GL_UNSIGNED_INT_24_8_OES, buffer);
}
Platform3DObject depth = 0;
if (supportsDepth) {
depth = context->createTexture();
- context->bindTexture(GraphicsContext3D::TEXTURE_2D, depth);
- context->texImage2D(GraphicsContext3D::TEXTURE_2D, 0, GraphicsContext3D::DEPTH_COMPONENT, 1, 1, 0, GraphicsContext3D::DEPTH_COMPONENT, GraphicsContext3D::UNSIGNED_INT, buffer);
+ context->bindTexture(GL_TEXTURE_2D, depth);
+ context->texImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, 1, 1, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, buffer);
}
Vector<Platform3DObject> colors;
@@ -140,30 +140,30 @@ bool WebGLDrawBuffers::satisfiesWebGLRequirements(WebGLRenderingContext* webglCo
for (GC3Dint i = 0; i < maxAllowedBuffers; ++i) {
Platform3DObject color = context->createTexture();
colors.append(color);
- context->bindTexture(GraphicsContext3D::TEXTURE_2D, color);
- context->texImage2D(GraphicsContext3D::TEXTURE_2D, 0, GraphicsContext3D::RGBA, 1, 1, 0, GraphicsContext3D::RGBA, GraphicsContext3D::UNSIGNED_BYTE, buffer);
- context->framebufferTexture2D(GraphicsContext3D::FRAMEBUFFER, GraphicsContext3D::COLOR_ATTACHMENT0 + i, GraphicsContext3D::TEXTURE_2D, color, 0);
- if (context->checkFramebufferStatus(GraphicsContext3D::FRAMEBUFFER) != GraphicsContext3D::FRAMEBUFFER_COMPLETE) {
+ context->bindTexture(GL_TEXTURE_2D, color);
+ context->texImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer);
+ context->framebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, GL_TEXTURE_2D, color, 0);
+ if (context->checkFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
ok = false;
break;
}
if (supportsDepth) {
- context->framebufferTexture2D(GraphicsContext3D::FRAMEBUFFER, GraphicsContext3D::DEPTH_ATTACHMENT, GraphicsContext3D::TEXTURE_2D, depth, 0);
- if (context->checkFramebufferStatus(GraphicsContext3D::FRAMEBUFFER) != GraphicsContext3D::FRAMEBUFFER_COMPLETE) {
+ context->framebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depth, 0);
+ if (context->checkFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
ok = false;
break;
}
- context->framebufferTexture2D(GraphicsContext3D::FRAMEBUFFER, GraphicsContext3D::DEPTH_ATTACHMENT, GraphicsContext3D::TEXTURE_2D, 0, 0);
+ context->framebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
}
if (supportsDepthStencil) {
- context->framebufferTexture2D(GraphicsContext3D::FRAMEBUFFER, GraphicsContext3D::DEPTH_ATTACHMENT, GraphicsContext3D::TEXTURE_2D, depthStencil, 0);
- context->framebufferTexture2D(GraphicsContext3D::FRAMEBUFFER, GraphicsContext3D::STENCIL_ATTACHMENT, GraphicsContext3D::TEXTURE_2D, depthStencil, 0);
- if (context->checkFramebufferStatus(GraphicsContext3D::FRAMEBUFFER) != GraphicsContext3D::FRAMEBUFFER_COMPLETE) {
+ context->framebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depthStencil, 0);
+ context->framebufferTexture2D(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, depthStencil, 0);
+ if (context->checkFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
ok = false;
break;
}
- context->framebufferTexture2D(GraphicsContext3D::FRAMEBUFFER, GraphicsContext3D::DEPTH_ATTACHMENT, GraphicsContext3D::TEXTURE_2D, 0, 0);
- context->framebufferTexture2D(GraphicsContext3D::FRAMEBUFFER, GraphicsContext3D::STENCIL_ATTACHMENT, GraphicsContext3D::TEXTURE_2D, 0, 0);
+ context->framebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
+ context->framebufferTexture2D(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
}
}
diff --git a/chromium/third_party/WebKit/Source/core/html/canvas/WebGLFramebuffer.cpp b/chromium/third_party/WebKit/Source/core/html/canvas/WebGLFramebuffer.cpp
index 41f7d82b6a9..7ab97df91d1 100644
--- a/chromium/third_party/WebKit/Source/core/html/canvas/WebGLFramebuffer.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/canvas/WebGLFramebuffer.cpp
@@ -28,8 +28,8 @@
#include "core/html/canvas/WebGLFramebuffer.h"
#include "core/html/canvas/WebGLRenderingContext.h"
-#include "core/platform/NotImplemented.h"
-#include "core/platform/graphics/Extensions3D.h"
+#include "platform/NotImplemented.h"
+#include "platform/graphics/Extensions3D.h"
namespace WebCore {
@@ -87,9 +87,9 @@ namespace {
GC3Denum WebGLRenderbufferAttachment::format() const
{
GC3Denum format = m_renderbuffer->internalFormat();
- if (format == GraphicsContext3D::DEPTH_STENCIL
+ if (format == GL_DEPTH_STENCIL_OES
&& m_renderbuffer->emulatedStencilBuffer()
- && m_renderbuffer->emulatedStencilBuffer()->internalFormat() != GraphicsContext3D::STENCIL_INDEX8) {
+ && m_renderbuffer->emulatedStencilBuffer()->internalFormat() != GL_STENCIL_INDEX8) {
return 0;
}
return format;
@@ -129,21 +129,22 @@ namespace {
void WebGLRenderbufferAttachment::attach(GraphicsContext3D* context, GC3Denum attachment)
{
Platform3DObject object = objectOrZero(m_renderbuffer.get());
- if (attachment == GraphicsContext3D::DEPTH_STENCIL_ATTACHMENT && m_renderbuffer->emulatedStencilBuffer()) {
- context->framebufferRenderbuffer(GraphicsContext3D::FRAMEBUFFER, GraphicsContext3D::DEPTH_ATTACHMENT, GraphicsContext3D::RENDERBUFFER, object);
- context->framebufferRenderbuffer(GraphicsContext3D::FRAMEBUFFER, GraphicsContext3D::STENCIL_ATTACHMENT, GraphicsContext3D::RENDERBUFFER, objectOrZero(m_renderbuffer->emulatedStencilBuffer()));
+ if (attachment == GC3D_DEPTH_STENCIL_ATTACHMENT_WEBGL && m_renderbuffer->emulatedStencilBuffer()) {
+ context->framebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, object);
+ context->framebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, objectOrZero(m_renderbuffer->emulatedStencilBuffer()));
} else {
- context->framebufferRenderbuffer(GraphicsContext3D::FRAMEBUFFER, attachment, GraphicsContext3D::RENDERBUFFER, object);
+ context->framebufferRenderbuffer(GL_FRAMEBUFFER, attachment, GL_RENDERBUFFER, object);
}
}
void WebGLRenderbufferAttachment::unattach(GraphicsContext3D* context, GC3Denum attachment)
{
- if (attachment == GraphicsContext3D::DEPTH_STENCIL_ATTACHMENT) {
- context->framebufferRenderbuffer(GraphicsContext3D::FRAMEBUFFER, GraphicsContext3D::DEPTH_ATTACHMENT, GraphicsContext3D::RENDERBUFFER, 0);
- context->framebufferRenderbuffer(GraphicsContext3D::FRAMEBUFFER, GraphicsContext3D::STENCIL_ATTACHMENT, GraphicsContext3D::RENDERBUFFER, 0);
- } else
- context->framebufferRenderbuffer(GraphicsContext3D::FRAMEBUFFER, attachment, GraphicsContext3D::RENDERBUFFER, 0);
+ if (attachment == GC3D_DEPTH_STENCIL_ATTACHMENT_WEBGL) {
+ context->framebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, 0);
+ context->framebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, 0);
+ } else {
+ context->framebufferRenderbuffer(GL_FRAMEBUFFER, attachment, GL_RENDERBUFFER, 0);
+ }
}
GC3Denum WebGLRenderbufferAttachment::type() const
@@ -239,16 +240,17 @@ namespace {
void WebGLTextureAttachment::attach(GraphicsContext3D* context, GC3Denum attachment)
{
Platform3DObject object = objectOrZero(m_texture.get());
- context->framebufferTexture2D(GraphicsContext3D::FRAMEBUFFER, attachment, m_target, object, m_level);
+ context->framebufferTexture2D(GL_FRAMEBUFFER, attachment, m_target, object, m_level);
}
void WebGLTextureAttachment::unattach(GraphicsContext3D* context, GC3Denum attachment)
{
- if (attachment == GraphicsContext3D::DEPTH_STENCIL_ATTACHMENT) {
- context->framebufferTexture2D(GraphicsContext3D::FRAMEBUFFER, GraphicsContext3D::DEPTH_ATTACHMENT, m_target, 0, m_level);
- context->framebufferTexture2D(GraphicsContext3D::FRAMEBUFFER, GraphicsContext3D::STENCIL_ATTACHMENT, m_target, 0, m_level);
- } else
- context->framebufferTexture2D(GraphicsContext3D::FRAMEBUFFER, attachment, m_target, 0, m_level);
+ if (attachment == GC3D_DEPTH_STENCIL_ATTACHMENT_WEBGL) {
+ context->framebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, m_target, 0, m_level);
+ context->framebufferTexture2D(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, m_target, 0, m_level);
+ } else {
+ context->framebufferTexture2D(GL_FRAMEBUFFER, attachment, m_target, 0, m_level);
+ }
}
GC3Denum WebGLTextureAttachment::type() const
@@ -259,9 +261,9 @@ namespace {
bool isColorRenderable(GC3Denum internalformat)
{
switch (internalformat) {
- case GraphicsContext3D::RGBA4:
- case GraphicsContext3D::RGB5_A1:
- case GraphicsContext3D::RGB565:
+ case GL_RGBA4:
+ case GL_RGB5_A1:
+ case GL_RGB565:
return true;
default:
return false;
@@ -347,46 +349,46 @@ bool WebGLFramebuffer::isAttachmentComplete(WebGLAttachment* attachedObject, GC3
WebGLSharedObject* object = attachedObject->object();
ASSERT(object && (object->isTexture() || object->isRenderbuffer()));
- if (attachment == GraphicsContext3D::DEPTH_ATTACHMENT) {
+ if (attachment == GL_DEPTH_ATTACHMENT) {
if (object->isRenderbuffer()) {
- if (internalformat != GraphicsContext3D::DEPTH_COMPONENT16) {
+ if (internalformat != GL_DEPTH_COMPONENT16) {
*reason = "the internalformat of the attached renderbuffer is not DEPTH_COMPONENT16";
return false;
}
} else if (object->isTexture()) {
GC3Denum type = attachedObject->type();
- if (!(context()->m_webglDepthTexture && internalformat == GraphicsContext3D::DEPTH_COMPONENT
- && (type == GraphicsContext3D::UNSIGNED_SHORT || type == GraphicsContext3D::UNSIGNED_INT))) {
+ if (!(context()->m_webglDepthTexture && internalformat == GL_DEPTH_COMPONENT
+ && (type == GL_UNSIGNED_SHORT || type == GL_UNSIGNED_INT))) {
*reason = "the attached texture is not a depth texture";
return false;
}
}
- } else if (attachment == GraphicsContext3D::STENCIL_ATTACHMENT) {
+ } else if (attachment == GL_STENCIL_ATTACHMENT) {
// Depend on the underlying GL drivers to check stencil textures
// and check renderbuffer type here only.
if (object->isRenderbuffer()) {
- if (internalformat != GraphicsContext3D::STENCIL_INDEX8) {
+ if (internalformat != GL_STENCIL_INDEX8) {
*reason = "the internalformat of the attached renderbuffer is not STENCIL_INDEX8";
return false;
}
}
- } else if (attachment == GraphicsContext3D::DEPTH_STENCIL_ATTACHMENT) {
+ } else if (attachment == GC3D_DEPTH_STENCIL_ATTACHMENT_WEBGL) {
if (object->isRenderbuffer()) {
- if (internalformat != GraphicsContext3D::DEPTH_STENCIL) {
+ if (internalformat != GL_DEPTH_STENCIL_OES) {
*reason = "the internalformat of the attached renderbuffer is not DEPTH_STENCIL";
return false;
}
} else if (object->isTexture()) {
GC3Denum type = attachedObject->type();
- if (!(context()->m_webglDepthTexture && internalformat == GraphicsContext3D::DEPTH_STENCIL
- && type == GraphicsContext3D::UNSIGNED_INT_24_8)) {
+ if (!(context()->m_webglDepthTexture && internalformat == GL_DEPTH_STENCIL_OES
+ && type == GL_UNSIGNED_INT_24_8_OES)) {
*reason = "the attached texture is not a DEPTH_STENCIL texture";
return false;
}
}
- } else if (attachment == GraphicsContext3D::COLOR_ATTACHMENT0
- || (context()->m_webglDrawBuffers && attachment > GraphicsContext3D::COLOR_ATTACHMENT0
- && attachment < static_cast<GC3Denum>(GraphicsContext3D::COLOR_ATTACHMENT0 + context()->maxColorAttachments()))) {
+ } else if (attachment == GL_COLOR_ATTACHMENT0
+ || (context()->m_webglDrawBuffers && attachment > GL_COLOR_ATTACHMENT0
+ && attachment < static_cast<GC3Denum>(GL_COLOR_ATTACHMENT0 + context()->maxColorAttachments()))) {
if (object->isRenderbuffer()) {
if (!isColorRenderable(internalformat)) {
*reason = "the internalformat of the attached renderbuffer is not color-renderable";
@@ -394,7 +396,7 @@ bool WebGLFramebuffer::isAttachmentComplete(WebGLAttachment* attachedObject, GC3
}
} else if (object->isTexture()) {
GC3Denum type = attachedObject->type();
- if (internalformat != GraphicsContext3D::RGBA && internalformat != GraphicsContext3D::RGB) {
+ if (internalformat != GL_RGBA && internalformat != GL_RGB) {
*reason = "the internalformat of the attached texture is not color-renderable";
return false;
}
@@ -402,12 +404,12 @@ bool WebGLFramebuffer::isAttachmentComplete(WebGLAttachment* attachedObject, GC3
// WebGL yet. It would be better to depend on the underlying GL drivers to check on rendering to floating point textures
// and add the check back to WebGL when above two extensions are implemented.
// Assume UNSIGNED_BYTE is renderable here without the need to explicitly check if GL_OES_rgb8_rgba8 extension is supported.
- if (type != GraphicsContext3D::UNSIGNED_BYTE
- && type != GraphicsContext3D::UNSIGNED_SHORT_5_6_5
- && type != GraphicsContext3D::UNSIGNED_SHORT_4_4_4_4
- && type != GraphicsContext3D::UNSIGNED_SHORT_5_5_5_1
- && !(type == GraphicsContext3D::FLOAT && context()->m_oesTextureFloat)
- && !(type == GraphicsContext3D::HALF_FLOAT_OES && context()->m_oesTextureHalfFloat)) {
+ if (type != GL_UNSIGNED_BYTE
+ && type != GL_UNSIGNED_SHORT_5_6_5
+ && type != GL_UNSIGNED_SHORT_4_4_4_4
+ && type != GL_UNSIGNED_SHORT_5_5_5_1
+ && !(type == GL_FLOAT && context()->m_oesTextureFloat)
+ && !(type == GL_HALF_FLOAT_OES && context()->m_oesTextureHalfFloat)) {
*reason = "unsupported type: The attached texture is not supported to be rendered to";
return false;
}
@@ -442,15 +444,15 @@ void WebGLFramebuffer::removeAttachmentFromBoundFramebuffer(GC3Denum attachment)
m_attachments.remove(attachment);
drawBuffersIfNecessary(false);
switch (attachment) {
- case GraphicsContext3D::DEPTH_STENCIL_ATTACHMENT:
- attach(GraphicsContext3D::DEPTH_ATTACHMENT, GraphicsContext3D::DEPTH_ATTACHMENT);
- attach(GraphicsContext3D::STENCIL_ATTACHMENT, GraphicsContext3D::STENCIL_ATTACHMENT);
+ case GC3D_DEPTH_STENCIL_ATTACHMENT_WEBGL:
+ attach(GL_DEPTH_ATTACHMENT, GL_DEPTH_ATTACHMENT);
+ attach(GL_STENCIL_ATTACHMENT, GL_STENCIL_ATTACHMENT);
break;
- case GraphicsContext3D::DEPTH_ATTACHMENT:
- attach(GraphicsContext3D::DEPTH_STENCIL_ATTACHMENT, GraphicsContext3D::DEPTH_ATTACHMENT);
+ case GL_DEPTH_ATTACHMENT:
+ attach(GC3D_DEPTH_STENCIL_ATTACHMENT_WEBGL, GL_DEPTH_ATTACHMENT);
break;
- case GraphicsContext3D::STENCIL_ATTACHMENT:
- attach(GraphicsContext3D::DEPTH_STENCIL_ATTACHMENT, GraphicsContext3D::STENCIL_ATTACHMENT);
+ case GL_STENCIL_ATTACHMENT:
+ attach(GC3D_DEPTH_STENCIL_ATTACHMENT_WEBGL, GL_STENCIL_ATTACHMENT);
break;
}
}
@@ -484,7 +486,7 @@ GC3Dsizei WebGLFramebuffer::colorBufferWidth() const
{
if (!object())
return 0;
- WebGLAttachment* attachment = getAttachment(GraphicsContext3D::COLOR_ATTACHMENT0);
+ WebGLAttachment* attachment = getAttachment(GL_COLOR_ATTACHMENT0);
if (!attachment)
return 0;
@@ -495,7 +497,7 @@ GC3Dsizei WebGLFramebuffer::colorBufferHeight() const
{
if (!object())
return 0;
- WebGLAttachment* attachment = getAttachment(GraphicsContext3D::COLOR_ATTACHMENT0);
+ WebGLAttachment* attachment = getAttachment(GL_COLOR_ATTACHMENT0);
if (!attachment)
return 0;
@@ -506,7 +508,7 @@ GC3Denum WebGLFramebuffer::colorBufferFormat() const
{
if (!object())
return 0;
- WebGLAttachment* attachment = getAttachment(GraphicsContext3D::COLOR_ATTACHMENT0);
+ WebGLAttachment* attachment = getAttachment(GL_COLOR_ATTACHMENT0);
if (!attachment)
return 0;
return attachment->format();
@@ -522,23 +524,23 @@ GC3Denum WebGLFramebuffer::checkStatus(const char** reason) const
for (AttachmentMap::const_iterator it = m_attachments.begin(); it != m_attachments.end(); ++it) {
WebGLAttachment* attachment = it->value.get();
if (!isAttachmentComplete(attachment, it->key, reason))
- return GraphicsContext3D::FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
+ return GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
if (!attachment->valid()) {
*reason = "attachment is not valid";
- return GraphicsContext3D::FRAMEBUFFER_UNSUPPORTED;
+ return GL_FRAMEBUFFER_UNSUPPORTED;
}
if (!attachment->format()) {
*reason = "attachment is an unsupported format";
- return GraphicsContext3D::FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
+ return GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
}
switch (it->key) {
- case GraphicsContext3D::DEPTH_ATTACHMENT:
+ case GL_DEPTH_ATTACHMENT:
haveDepth = true;
break;
- case GraphicsContext3D::STENCIL_ATTACHMENT:
+ case GL_STENCIL_ATTACHMENT:
haveStencil = true;
break;
- case GraphicsContext3D::DEPTH_STENCIL_ATTACHMENT:
+ case GC3D_DEPTH_STENCIL_ATTACHMENT_WEBGL:
haveDepthStencil = true;
break;
}
@@ -548,39 +550,39 @@ GC3Denum WebGLFramebuffer::checkStatus(const char** reason) const
} else {
if (width != attachment->width() || height != attachment->height()) {
*reason = "attachments do not have the same dimensions";
- return GraphicsContext3D::FRAMEBUFFER_INCOMPLETE_DIMENSIONS;
+ return GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS;
}
}
++count;
}
if (!count) {
*reason = "no attachments";
- return GraphicsContext3D::FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT;
+ return GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT;
}
if (!width || !height) {
*reason = "framebuffer has a 0 dimension";
- return GraphicsContext3D::FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
+ return GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT;
}
// WebGL specific: no conflicting DEPTH/STENCIL/DEPTH_STENCIL attachments.
if ((haveDepthStencil && (haveDepth || haveStencil)) || (haveDepth && haveStencil)) {
*reason = "conflicting DEPTH/STENCIL/DEPTH_STENCIL attachments";
- return GraphicsContext3D::FRAMEBUFFER_UNSUPPORTED;
+ return GL_FRAMEBUFFER_UNSUPPORTED;
}
- return GraphicsContext3D::FRAMEBUFFER_COMPLETE;
+ return GL_FRAMEBUFFER_COMPLETE;
}
bool WebGLFramebuffer::onAccess(GraphicsContext3D* context3d, const char** reason)
{
- if (checkStatus(reason) != GraphicsContext3D::FRAMEBUFFER_COMPLETE)
+ if (checkStatus(reason) != GL_FRAMEBUFFER_COMPLETE)
return false;
return true;
}
bool WebGLFramebuffer::hasStencilBuffer() const
{
- WebGLAttachment* attachment = getAttachment(GraphicsContext3D::STENCIL_ATTACHMENT);
+ WebGLAttachment* attachment = getAttachment(GL_STENCIL_ATTACHMENT);
if (!attachment)
- attachment = getAttachment(GraphicsContext3D::DEPTH_STENCIL_ATTACHMENT);
+ attachment = getAttachment(GC3D_DEPTH_STENCIL_ATTACHMENT_WEBGL);
return attachment && attachment->valid();
}
@@ -602,7 +604,7 @@ void WebGLFramebuffer::drawBuffers(const Vector<GC3Denum>& bufs)
m_drawBuffers = bufs;
m_filteredDrawBuffers.resize(m_drawBuffers.size());
for (size_t i = 0; i < m_filteredDrawBuffers.size(); ++i)
- m_filteredDrawBuffers[i] = GraphicsContext3D::NONE;
+ m_filteredDrawBuffers[i] = GL_NONE;
drawBuffersIfNecessary(true);
}
@@ -613,14 +615,14 @@ void WebGLFramebuffer::drawBuffersIfNecessary(bool force)
bool reset = force;
// This filtering works around graphics driver bugs on Mac OS X.
for (size_t i = 0; i < m_drawBuffers.size(); ++i) {
- if (m_drawBuffers[i] != GraphicsContext3D::NONE && getAttachment(m_drawBuffers[i])) {
+ if (m_drawBuffers[i] != GL_NONE && getAttachment(m_drawBuffers[i])) {
if (m_filteredDrawBuffers[i] != m_drawBuffers[i]) {
m_filteredDrawBuffers[i] = m_drawBuffers[i];
reset = true;
}
} else {
- if (m_filteredDrawBuffers[i] != GraphicsContext3D::NONE) {
- m_filteredDrawBuffers[i] = GraphicsContext3D::NONE;
+ if (m_filteredDrawBuffers[i] != GL_NONE) {
+ m_filteredDrawBuffers[i] = GL_NONE;
reset = true;
}
}
@@ -638,8 +640,8 @@ GC3Denum WebGLFramebuffer::getDrawBuffer(GC3Denum drawBuffer)
if (index < static_cast<int>(m_drawBuffers.size()))
return m_drawBuffers[index];
if (drawBuffer == Extensions3D::DRAW_BUFFER0_EXT)
- return GraphicsContext3D::COLOR_ATTACHMENT0;
- return GraphicsContext3D::NONE;
+ return GL_COLOR_ATTACHMENT0;
+ return GL_NONE;
}
}
diff --git a/chromium/third_party/WebKit/Source/core/html/canvas/WebGLGetInfo.cpp b/chromium/third_party/WebKit/Source/core/html/canvas/WebGLGetInfo.cpp
index e8e71de4c6b..55cead3c16f 100644
--- a/chromium/third_party/WebKit/Source/core/html/canvas/WebGLGetInfo.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/canvas/WebGLGetInfo.cpp
@@ -27,16 +27,6 @@
#include "config.h"
#include "core/html/canvas/WebGLGetInfo.h"
-#include "core/html/canvas/WebGLBuffer.h"
-#include "core/html/canvas/WebGLFramebuffer.h"
-#include "core/html/canvas/WebGLProgram.h"
-#include "core/html/canvas/WebGLRenderbuffer.h"
-#include "core/html/canvas/WebGLTexture.h"
-#include "core/html/canvas/WebGLVertexArrayObjectOES.h"
-#include "wtf/Float32Array.h"
-#include "wtf/Int32Array.h"
-#include "wtf/Uint32Array.h"
-#include "wtf/Uint8Array.h"
namespace WebCore {
@@ -209,10 +199,6 @@ WebGLGetInfo::WebGLGetInfo(PassRefPtr<WebGLVertexArrayObjectOES> value)
{
}
-WebGLGetInfo::~WebGLGetInfo()
-{
-}
-
WebGLGetInfo::Type WebGLGetInfo::getType() const
{
return m_type;
diff --git a/chromium/third_party/WebKit/Source/core/html/canvas/WebGLGetInfo.h b/chromium/third_party/WebKit/Source/core/html/canvas/WebGLGetInfo.h
index 552cf47f515..d72e7f9c65a 100644
--- a/chromium/third_party/WebKit/Source/core/html/canvas/WebGLGetInfo.h
+++ b/chromium/third_party/WebKit/Source/core/html/canvas/WebGLGetInfo.h
@@ -48,7 +48,7 @@ namespace WebCore {
// similar variants. For reference counted types, increments and
// decrements the reference count of the target object.
-class WebGLGetInfo {
+class WebGLGetInfo FINAL {
public:
enum Type {
kTypeBool,
@@ -92,8 +92,6 @@ public:
explicit WebGLGetInfo(PassRefPtr<Uint32Array> value);
explicit WebGLGetInfo(PassRefPtr<WebGLVertexArrayObjectOES> value);
- virtual ~WebGLGetInfo();
-
Type getType() const;
bool getBool() const;
diff --git a/chromium/third_party/WebKit/Source/core/html/canvas/WebGLObject.h b/chromium/third_party/WebKit/Source/core/html/canvas/WebGLObject.h
index 70aeab731d7..55a7d51e2da 100644
--- a/chromium/third_party/WebKit/Source/core/html/canvas/WebGLObject.h
+++ b/chromium/third_party/WebKit/Source/core/html/canvas/WebGLObject.h
@@ -26,8 +26,7 @@
#ifndef WebGLObject_h
#define WebGLObject_h
-#include "core/platform/graphics/GraphicsContext3D.h"
-
+#include "platform/graphics/GraphicsContext3D.h"
#include "wtf/RefCounted.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/html/canvas/WebGLProgram.cpp b/chromium/third_party/WebKit/Source/core/html/canvas/WebGLProgram.cpp
index f3001c54782..6a1539331f9 100644
--- a/chromium/third_party/WebKit/Source/core/html/canvas/WebGLProgram.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/canvas/WebGLProgram.cpp
@@ -109,9 +109,9 @@ void WebGLProgram::increaseLinkCount()
WebGLShader* WebGLProgram::getAttachedShader(GC3Denum type)
{
switch (type) {
- case GraphicsContext3D::VERTEX_SHADER:
+ case GL_VERTEX_SHADER:
return m_vertexShader.get();
- case GraphicsContext3D::FRAGMENT_SHADER:
+ case GL_FRAGMENT_SHADER:
return m_fragmentShader.get();
default:
return 0;
@@ -123,12 +123,12 @@ bool WebGLProgram::attachShader(WebGLShader* shader)
if (!shader || !shader->object())
return false;
switch (shader->type()) {
- case GraphicsContext3D::VERTEX_SHADER:
+ case GL_VERTEX_SHADER:
if (m_vertexShader)
return false;
m_vertexShader = shader;
return true;
- case GraphicsContext3D::FRAGMENT_SHADER:
+ case GL_FRAGMENT_SHADER:
if (m_fragmentShader)
return false;
m_fragmentShader = shader;
@@ -143,12 +143,12 @@ bool WebGLProgram::detachShader(WebGLShader* shader)
if (!shader || !shader->object())
return false;
switch (shader->type()) {
- case GraphicsContext3D::VERTEX_SHADER:
+ case GL_VERTEX_SHADER:
if (m_vertexShader != shader)
return false;
m_vertexShader = 0;
return true;
- case GraphicsContext3D::FRAGMENT_SHADER:
+ case GL_FRAGMENT_SHADER:
if (m_fragmentShader != shader)
return false;
m_fragmentShader = 0;
@@ -163,7 +163,7 @@ void WebGLProgram::cacheActiveAttribLocations(GraphicsContext3D* context3d)
m_activeAttribLocations.clear();
GC3Dint numAttribs = 0;
- context3d->getProgramiv(object(), GraphicsContext3D::ACTIVE_ATTRIBUTES, &numAttribs);
+ context3d->getProgramiv(object(), GL_ACTIVE_ATTRIBUTES, &numAttribs);
m_activeAttribLocations.resize(static_cast<size_t>(numAttribs));
for (int i = 0; i < numAttribs; ++i) {
ActiveInfo info;
@@ -184,7 +184,7 @@ void WebGLProgram::cacheInfoIfNeeded()
if (!context)
return;
GC3Dint linkStatus = 0;
- context->getProgramiv(object(), GraphicsContext3D::LINK_STATUS, &linkStatus);
+ context->getProgramiv(object(), GL_LINK_STATUS, &linkStatus);
m_linkStatus = linkStatus;
if (m_linkStatus)
cacheActiveAttribLocations(context);
diff --git a/chromium/third_party/WebKit/Source/core/html/canvas/WebGLRenderbuffer.cpp b/chromium/third_party/WebKit/Source/core/html/canvas/WebGLRenderbuffer.cpp
index 68b3ae2b819..da27596f273 100644
--- a/chromium/third_party/WebKit/Source/core/html/canvas/WebGLRenderbuffer.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/canvas/WebGLRenderbuffer.cpp
@@ -43,7 +43,7 @@ WebGLRenderbuffer::~WebGLRenderbuffer()
WebGLRenderbuffer::WebGLRenderbuffer(WebGLRenderingContext* ctx)
: WebGLSharedObject(ctx)
- , m_internalFormat(GraphicsContext3D::RGBA4)
+ , m_internalFormat(GL_RGBA4)
, m_initialized(false)
, m_width(0)
, m_height(0)
diff --git a/chromium/third_party/WebKit/Source/core/html/canvas/WebGLRenderingContext.cpp b/chromium/third_party/WebKit/Source/core/html/canvas/WebGLRenderingContext.cpp
index 33440648594..ed0d58811ad 100644
--- a/chromium/third_party/WebKit/Source/core/html/canvas/WebGLRenderingContext.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/canvas/WebGLRenderingContext.cpp
@@ -68,18 +68,17 @@
#include "core/inspector/InspectorInstrumentation.h"
#include "core/loader/FrameLoader.h"
#include "core/loader/FrameLoaderClient.h"
-#include "core/page/Frame.h"
-#include "core/page/Page.h"
-#include "core/page/Settings.h"
-#include "core/platform/NotImplemented.h"
-#include "core/platform/graphics/Extensions3D.h"
-#include "core/platform/graphics/ImageBuffer.h"
-#include "core/platform/graphics/IntSize.h"
-#include "core/platform/graphics/gpu/DrawingBuffer.h"
+#include "core/frame/Frame.h"
+#include "core/frame/Settings.h"
#include "core/rendering/RenderBox.h"
-
-#include "wtf/OwnArrayPtr.h"
-#include "wtf/PassOwnArrayPtr.h"
+#include "platform/CheckedInt.h"
+#include "platform/NotImplemented.h"
+#include "platform/geometry/IntSize.h"
+#include "platform/graphics/Extensions3D.h"
+#include "platform/graphics/UnacceleratedImageBufferSurface.h"
+#include "platform/graphics/gpu/DrawingBuffer.h"
+
+#include "wtf/PassOwnPtr.h"
#include "wtf/Uint32Array.h"
#include "wtf/text/StringBuilder.h"
@@ -87,7 +86,7 @@ namespace WebCore {
const double secondsBetweenRestoreAttempts = 1.0;
const int maxGLErrorsAllowedToConsole = 256;
-const int maxGLActiveContexts = 16;
+const unsigned maxGLActiveContexts = 16;
Vector<WebGLRenderingContext*>& WebGLRenderingContext::activeContexts()
{
@@ -152,11 +151,14 @@ IntSize WebGLRenderingContext::oldestContextSize()
void WebGLRenderingContext::activateContext(WebGLRenderingContext* context)
{
+ unsigned removedContexts = 0;
+ while (activeContexts().size() >= maxGLActiveContexts && removedContexts < maxGLActiveContexts) {
+ forciblyLoseOldestContext("WARNING: Too many active WebGL contexts. Oldest context will be lost.");
+ removedContexts++;
+ }
+
if (!activeContexts().contains(context))
activeContexts().append(context);
-
- if (activeContexts().size() > maxGLActiveContexts)
- forciblyLoseOldestContext("WARNING: Too many active WebGL contexts. Oldest context will be lost.");
}
void WebGLRenderingContext::deactivateContext(WebGLRenderingContext* context, bool addToEvictedList)
@@ -237,31 +239,6 @@ namespace {
return object ? object->object() : 0;
}
- void clip1D(GC3Dint start, GC3Dsizei range, GC3Dsizei sourceRange, GC3Dint* clippedStart, GC3Dsizei* clippedRange)
- {
- ASSERT(clippedStart && clippedRange);
- if (start < 0) {
- range += start;
- start = 0;
- }
- GC3Dint end = start + range;
- if (end > sourceRange)
- range -= end - sourceRange;
- *clippedStart = start;
- *clippedRange = range;
- }
-
- // Returns false if no clipping is necessary, i.e., x, y, width, height stay the same.
- bool clip2D(GC3Dint x, GC3Dint y, GC3Dsizei width, GC3Dsizei height,
- GC3Dsizei sourceWidth, GC3Dsizei sourceHeight,
- GC3Dint* clippedX, GC3Dint* clippedY, GC3Dsizei* clippedWidth, GC3Dsizei*clippedHeight)
- {
- ASSERT(clippedX && clippedY && clippedWidth && clippedHeight);
- clip1D(x, width, sourceWidth, clippedX, clippedWidth);
- clip1D(y, height, sourceHeight, clippedY, clippedHeight);
- return (*clippedX != x || *clippedY != y || *clippedWidth != width || *clippedHeight != height);
- }
-
GC3Dint clamp(GC3Dint value, GC3Dint min, GC3Dint max)
{
if (value < min)
@@ -524,8 +501,8 @@ PassOwnPtr<WebGLRenderingContext> WebGLRenderingContext::create(HTMLCanvasElemen
// The FrameLoaderClient might block creation of a new WebGL context despite the page settings; in
// particular, if WebGL contexts were lost one or more times via the GL_ARB_robustness extension.
- if (!frame->loader()->client()->allowWebGL(settings && settings->webGLEnabled())) {
- canvas->dispatchEvent(WebGLContextEvent::create(eventNames().webglcontextcreationerrorEvent, false, true, "Web page was not allowed to create a WebGL context."));
+ if (!frame->loader().client()->allowWebGL(settings && settings->webGLEnabled())) {
+ canvas->dispatchEvent(WebGLContextEvent::create(EventTypeNames::webglcontextcreationerror, false, true, "Web page was not allowed to create a WebGL context."));
return nullptr;
}
@@ -540,7 +517,7 @@ PassOwnPtr<WebGLRenderingContext> WebGLRenderingContext::create(HTMLCanvasElemen
RefPtr<GraphicsContext3D> context(GraphicsContext3D::create(attributes));
if (!context || !context->makeContextCurrent()) {
- canvas->dispatchEvent(WebGLContextEvent::create(eventNames().webglcontextcreationerrorEvent, false, true, "Could not create a WebGL context."));
+ canvas->dispatchEvent(WebGLContextEvent::create(EventTypeNames::webglcontextcreationerror, false, true, "Could not create a WebGL context."));
return nullptr;
}
@@ -552,7 +529,7 @@ PassOwnPtr<WebGLRenderingContext> WebGLRenderingContext::create(HTMLCanvasElemen
renderingContext->suspendIfNeeded();
if (renderingContext->m_drawingBuffer->isZeroSized()) {
- canvas->dispatchEvent(WebGLContextEvent::create(eventNames().webglcontextcreationerrorEvent, false, true, "Could not create a WebGL context."));
+ canvas->dispatchEvent(WebGLContextEvent::create(EventTypeNames::webglcontextcreationerror, false, true, "Could not create a WebGL context."));
return nullptr;
}
@@ -567,7 +544,7 @@ WebGLRenderingContext::WebGLRenderingContext(HTMLCanvasElement* passedCanvas, Pa
, m_dispatchContextLostEventTimer(this, &WebGLRenderingContext::dispatchContextLostEvent)
, m_restoreAllowed(false)
, m_restoreTimer(this, &WebGLRenderingContext::maybeRestoreContext)
- , m_videoCache(4)
+ , m_generatedImageCache(4)
, m_contextLost(false)
, m_contextLostMode(SyntheticLostContext)
, m_attributes(attributes)
@@ -586,7 +563,7 @@ WebGLRenderingContext::WebGLRenderingContext(HTMLCanvasElement* passedCanvas, Pa
m_contextGroup->addContext(this);
m_maxViewportDims[0] = m_maxViewportDims[1] = 0;
- m_context->getIntegerv(GraphicsContext3D::MAX_VIEWPORT_DIMS, m_maxViewportDims);
+ m_context->getIntegerv(GL_MAX_VIEWPORT_DIMS, m_maxViewportDims);
RefPtr<WebGLRenderingContextEvictionManager> contextEvictionManager = adoptRef(new WebGLRenderingContextEvictionManager());
@@ -601,8 +578,8 @@ WebGLRenderingContext::WebGLRenderingContext(HTMLCanvasElement* passedCanvas, Pa
}
// Register extensions.
- static const char* webkitPrefix[] = { "WEBKIT_", 0, };
- static const char* bothPrefixes[] = { "", "WEBKIT_", 0, };
+ static const char* const webkitPrefix[] = { "WEBKIT_", 0, };
+ static const char* const bothPrefixes[] = { "", "WEBKIT_", 0, };
registerExtension<ANGLEInstancedArrays>(m_angleInstancedArrays);
registerExtension<EXTTextureFilterAnisotropic>(m_extTextureFilterAnisotropic, PrefixedExtension, webkitPrefix);
@@ -617,11 +594,11 @@ WebGLRenderingContext::WebGLRenderingContext(HTMLCanvasElement* passedCanvas, Pa
registerExtension<WebGLCompressedTexturePVRTC>(m_webglCompressedTexturePVRTC, PrefixedExtension, webkitPrefix);
registerExtension<WebGLCompressedTextureS3TC>(m_webglCompressedTextureS3TC, PrefixedExtension, bothPrefixes);
registerExtension<WebGLDepthTexture>(m_webglDepthTexture, PrefixedExtension, bothPrefixes);
+ registerExtension<WebGLDrawBuffers>(m_webglDrawBuffers);
registerExtension<WebGLLoseContext>(m_webglLoseContext, ApprovedExtension, bothPrefixes);
// Register draft extensions.
registerExtension<EXTFragDepth>(m_extFragDepth, DraftExtension);
- registerExtension<WebGLDrawBuffers>(m_webglDrawBuffers, DraftExtension);
// Register privileged extensions.
registerExtension<WebGLDebugRendererInfo>(m_webglDebugRendererInfo, WebGLDebugRendererInfoExtension);
@@ -638,7 +615,7 @@ void WebGLRenderingContext::initializeNewContext()
m_unpackAlignment = 4;
m_unpackFlipY = false;
m_unpackPremultiplyAlpha = false;
- m_unpackColorspaceConversion = GraphicsContext3D::BROWSER_DEFAULT_WEBGL;
+ m_unpackColorspaceConversion = GC3D_BROWSER_DEFAULT_WEBGL;
m_boundArrayBuffer = 0;
m_currentProgram = 0;
m_framebufferBinding = 0;
@@ -661,28 +638,28 @@ void WebGLRenderingContext::initializeNewContext()
m_colorMask[0] = m_colorMask[1] = m_colorMask[2] = m_colorMask[3] = true;
GC3Dint numCombinedTextureImageUnits = 0;
- m_context->getIntegerv(GraphicsContext3D::MAX_COMBINED_TEXTURE_IMAGE_UNITS, &numCombinedTextureImageUnits);
+ m_context->getIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &numCombinedTextureImageUnits);
m_textureUnits.clear();
m_textureUnits.resize(numCombinedTextureImageUnits);
GC3Dint numVertexAttribs = 0;
- m_context->getIntegerv(GraphicsContext3D::MAX_VERTEX_ATTRIBS, &numVertexAttribs);
+ m_context->getIntegerv(GL_MAX_VERTEX_ATTRIBS, &numVertexAttribs);
m_maxVertexAttribs = numVertexAttribs;
m_maxTextureSize = 0;
- m_context->getIntegerv(GraphicsContext3D::MAX_TEXTURE_SIZE, &m_maxTextureSize);
+ m_context->getIntegerv(GL_MAX_TEXTURE_SIZE, &m_maxTextureSize);
m_maxTextureLevel = WebGLTexture::computeLevelCount(m_maxTextureSize, m_maxTextureSize);
m_maxCubeMapTextureSize = 0;
- m_context->getIntegerv(GraphicsContext3D::MAX_CUBE_MAP_TEXTURE_SIZE, &m_maxCubeMapTextureSize);
+ m_context->getIntegerv(GL_MAX_CUBE_MAP_TEXTURE_SIZE, &m_maxCubeMapTextureSize);
m_maxCubeMapTextureLevel = WebGLTexture::computeLevelCount(m_maxCubeMapTextureSize, m_maxCubeMapTextureSize);
m_maxRenderbufferSize = 0;
- m_context->getIntegerv(GraphicsContext3D::MAX_RENDERBUFFER_SIZE, &m_maxRenderbufferSize);
+ m_context->getIntegerv(GL_MAX_RENDERBUFFER_SIZE, &m_maxRenderbufferSize);
// These two values from EXT_draw_buffers are lazily queried.
m_maxDrawBuffers = 0;
m_maxColorAttachments = 0;
- m_backDrawBuffer = GraphicsContext3D::BACK;
+ m_backDrawBuffer = GL_BACK;
m_defaultVertexArrayObject = WebGLVertexArrayObjectOES::create(this, WebGLVertexArrayObjectOES::VaoTypeDefault);
addContextObject(m_defaultVertexArrayObject.get());
@@ -701,6 +678,9 @@ void WebGLRenderingContext::initializeNewContext()
m_context->setContextLostCallback(adoptPtr(new WebGLRenderingContextLostCallback(this)));
m_context->setErrorMessageCallback(adoptPtr(new WebGLRenderingContextErrorMessageCallback(this)));
+ // This ensures that the context has a valid "lastFlushID" and won't be mistakenly identified as the "least recently used" context.
+ m_context->flush();
+
activateContext(this);
}
@@ -730,10 +710,7 @@ bool WebGLRenderingContext::allowPrivilegedExtensions() const
bool WebGLRenderingContext::allowWebGLDebugRendererInfo() const
{
- if (allowPrivilegedExtensions())
- return true;
- Frame* frame = canvas()->document().frame();
- return frame && frame->loader()->client()->allowWebGLDebugRendererInfo();
+ return true;
}
void WebGLRenderingContext::addCompressedTextureFormat(GC3Denum format)
@@ -839,8 +816,8 @@ bool WebGLRenderingContext::clearIfComposited(GC3Dbitfield mask)
// Determine if it's possible to combine the clear the user asked for and this clear.
bool combinedClear = mask && !m_scissorEnabled;
- m_context->disable(GraphicsContext3D::SCISSOR_TEST);
- if (combinedClear && (mask & GraphicsContext3D::COLOR_BUFFER_BIT))
+ m_context->disable(GL_SCISSOR_TEST);
+ if (combinedClear && (mask & GL_COLOR_BUFFER_BIT))
m_context->clearColor(m_colorMask[0] ? m_clearColor[0] : 0,
m_colorMask[1] ? m_clearColor[1] : 0,
m_colorMask[2] ? m_clearColor[2] : 0,
@@ -848,27 +825,27 @@ bool WebGLRenderingContext::clearIfComposited(GC3Dbitfield mask)
else
m_context->clearColor(0, 0, 0, 0);
m_context->colorMask(true, true, true, true);
- GC3Dbitfield clearMask = GraphicsContext3D::COLOR_BUFFER_BIT;
+ GC3Dbitfield clearMask = GL_COLOR_BUFFER_BIT;
if (contextAttributes->depth()) {
- if (!combinedClear || !m_depthMask || !(mask & GraphicsContext3D::DEPTH_BUFFER_BIT))
+ if (!combinedClear || !m_depthMask || !(mask & GL_DEPTH_BUFFER_BIT))
m_context->clearDepth(1.0f);
- clearMask |= GraphicsContext3D::DEPTH_BUFFER_BIT;
+ clearMask |= GL_DEPTH_BUFFER_BIT;
m_context->depthMask(true);
}
if (contextAttributes->stencil()) {
- if (combinedClear && (mask & GraphicsContext3D::STENCIL_BUFFER_BIT))
+ if (combinedClear && (mask & GL_STENCIL_BUFFER_BIT))
m_context->clearStencil(m_clearStencil & m_stencilMask);
else
m_context->clearStencil(0);
- clearMask |= GraphicsContext3D::STENCIL_BUFFER_BIT;
- m_context->stencilMaskSeparate(GraphicsContext3D::FRONT, 0xFFFFFFFF);
+ clearMask |= GL_STENCIL_BUFFER_BIT;
+ m_context->stencilMaskSeparate(GL_FRONT, 0xFFFFFFFF);
}
m_drawingBuffer->clearFramebuffers(clearMask);
restoreStateAfterClear();
if (m_framebufferBinding)
- m_context->bindFramebuffer(GraphicsContext3D::FRAMEBUFFER, objectOrZero(m_framebufferBinding.get()));
+ m_context->bindFramebuffer(GL_FRAMEBUFFER, objectOrZero(m_framebufferBinding.get()));
m_layerCleared = true;
return combinedClear;
@@ -881,14 +858,14 @@ void WebGLRenderingContext::restoreStateAfterClear()
// Restore the state that the context set.
if (m_scissorEnabled)
- m_context->enable(GraphicsContext3D::SCISSOR_TEST);
+ m_context->enable(GL_SCISSOR_TEST);
m_context->clearColor(m_clearColor[0], m_clearColor[1],
m_clearColor[2], m_clearColor[3]);
m_context->colorMask(m_colorMask[0], m_colorMask[1],
m_colorMask[2], m_colorMask[3]);
m_context->clearDepth(m_clearDepth);
m_context->clearStencil(m_clearStencil);
- m_context->stencilMaskSeparate(GraphicsContext3D::FRONT, m_stencilMask);
+ m_context->stencilMaskSeparate(GL_FRONT, m_stencilMask);
m_context->depthMask(m_depthMask);
}
@@ -925,10 +902,14 @@ void WebGLRenderingContext::paintRenderingResultsToCanvas()
m_markedCanvasDirty = false;
m_drawingBuffer->commit();
- m_context->paintRenderingResultsToCanvas(canvas()->buffer(), m_drawingBuffer.get());
+ if (!(canvas()->buffer())->copyRenderingResultsFromDrawingBuffer(m_drawingBuffer.get())) {
+ canvas()->ensureUnacceleratedImageBuffer();
+ if (canvas()->hasImageBuffer())
+ m_context->paintRenderingResultsToCanvas(canvas()->buffer(), m_drawingBuffer.get());
+ }
if (m_framebufferBinding)
- m_context->bindFramebuffer(GraphicsContext3D::FRAMEBUFFER, objectOrZero(m_framebufferBinding.get()));
+ m_context->bindFramebuffer(GL_FRAMEBUFFER, objectOrZero(m_framebufferBinding.get()));
else
m_drawingBuffer->bind();
}
@@ -940,14 +921,17 @@ PassRefPtr<ImageData> WebGLRenderingContext::paintRenderingResultsToImageData()
clearIfComposited();
m_drawingBuffer->commit();
- RefPtr<ImageData> imageData = m_context->paintRenderingResultsToImageData(m_drawingBuffer.get());
+ int width, height;
+ RefPtr<Uint8ClampedArray> imageDataPixels = m_context->paintRenderingResultsToImageData(m_drawingBuffer.get(), width, height);
+ if (!imageDataPixels)
+ return 0;
if (m_framebufferBinding)
- m_context->bindFramebuffer(GraphicsContext3D::FRAMEBUFFER, objectOrZero(m_framebufferBinding.get()));
+ m_context->bindFramebuffer(GL_FRAMEBUFFER, objectOrZero(m_framebufferBinding.get()));
else
m_drawingBuffer->bind();
- return imageData;
+ return ImageData::create(IntSize(width, height), imageDataPixels);
}
void WebGLRenderingContext::reshape(int width, int height)
@@ -978,10 +962,10 @@ void WebGLRenderingContext::reshape(int width, int height)
m_drawingBuffer->reset(IntSize(width, height));
restoreStateAfterClear();
- m_context->bindTexture(GraphicsContext3D::TEXTURE_2D, objectOrZero(m_textureUnits[m_activeTextureUnit].m_texture2DBinding.get()));
- m_context->bindRenderbuffer(GraphicsContext3D::RENDERBUFFER, objectOrZero(m_renderbufferBinding.get()));
+ m_context->bindTexture(GL_TEXTURE_2D, objectOrZero(m_textureUnits[m_activeTextureUnit].m_texture2DBinding.get()));
+ m_context->bindRenderbuffer(GL_RENDERBUFFER, objectOrZero(m_renderbufferBinding.get()));
if (m_framebufferBinding)
- m_context->bindFramebuffer(GraphicsContext3D::FRAMEBUFFER, objectOrZero(m_framebufferBinding.get()));
+ m_context->bindFramebuffer(GL_FRAMEBUFFER, objectOrZero(m_framebufferBinding.get()));
}
int WebGLRenderingContext::drawingBufferWidth() const
@@ -997,19 +981,19 @@ int WebGLRenderingContext::drawingBufferHeight() const
unsigned int WebGLRenderingContext::sizeInBytes(GC3Denum type)
{
switch (type) {
- case GraphicsContext3D::BYTE:
+ case GL_BYTE:
return sizeof(GC3Dbyte);
- case GraphicsContext3D::UNSIGNED_BYTE:
+ case GL_UNSIGNED_BYTE:
return sizeof(GC3Dubyte);
- case GraphicsContext3D::SHORT:
+ case GL_SHORT:
return sizeof(GC3Dshort);
- case GraphicsContext3D::UNSIGNED_SHORT:
+ case GL_UNSIGNED_SHORT:
return sizeof(GC3Dushort);
- case GraphicsContext3D::INT:
+ case GL_INT:
return sizeof(GC3Dint);
- case GraphicsContext3D::UNSIGNED_INT:
+ case GL_UNSIGNED_INT:
return sizeof(GC3Duint);
- case GraphicsContext3D::FLOAT:
+ case GL_FLOAT:
return sizeof(GC3Dfloat);
}
ASSERT_NOT_REACHED();
@@ -1020,11 +1004,11 @@ void WebGLRenderingContext::activeTexture(GC3Denum texture)
{
if (isContextLost())
return;
- if (texture - GraphicsContext3D::TEXTURE0 >= m_textureUnits.size()) {
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "activeTexture", "texture unit out of range");
+ if (texture - GL_TEXTURE0 >= m_textureUnits.size()) {
+ synthesizeGLError(GL_INVALID_ENUM, "activeTexture", "texture unit out of range");
return;
}
- m_activeTextureUnit = texture - GraphicsContext3D::TEXTURE0;
+ m_activeTextureUnit = texture - GL_TEXTURE0;
m_context->activeTexture(texture);
m_drawingBuffer->setActiveTextureUnit(texture);
@@ -1036,7 +1020,7 @@ void WebGLRenderingContext::attachShader(WebGLProgram* program, WebGLShader* sha
if (isContextLost() || !validateWebGLObject("attachShader", program) || !validateWebGLObject("attachShader", shader))
return;
if (!program->attachShader(shader)) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "attachShader", "shader attachment already has shader");
+ synthesizeGLError(GL_INVALID_OPERATION, "attachShader", "shader attachment already has shader");
return;
}
m_context->attachShader(objectOrZero(program), objectOrZero(shader));
@@ -1052,11 +1036,11 @@ void WebGLRenderingContext::bindAttribLocation(WebGLProgram* program, GC3Duint i
if (!validateString("bindAttribLocation", name))
return;
if (isPrefixReserved(name)) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "bindAttribLocation", "reserved prefix");
+ synthesizeGLError(GL_INVALID_OPERATION, "bindAttribLocation", "reserved prefix");
return;
}
if (index >= m_maxVertexAttribs) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "bindAttribLocation", "index out of range");
+ synthesizeGLError(GL_INVALID_VALUE, "bindAttribLocation", "index out of range");
return;
}
m_context->bindAttribLocation(objectOrZero(program), index, name);
@@ -1069,7 +1053,7 @@ bool WebGLRenderingContext::checkObjectToBeBound(const char* functionName, WebGL
return false;
if (object) {
if (!object->validate(contextGroup(), this)) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, functionName, "object not from this context");
+ synthesizeGLError(GL_INVALID_OPERATION, functionName, "object not from this context");
return false;
}
deleted = !object->object();
@@ -1085,15 +1069,15 @@ void WebGLRenderingContext::bindBuffer(GC3Denum target, WebGLBuffer* buffer)
if (deleted)
buffer = 0;
if (buffer && buffer->getTarget() && buffer->getTarget() != target) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "bindBuffer", "buffers can not be used with multiple targets");
+ synthesizeGLError(GL_INVALID_OPERATION, "bindBuffer", "buffers can not be used with multiple targets");
return;
}
- if (target == GraphicsContext3D::ARRAY_BUFFER)
+ if (target == GL_ARRAY_BUFFER)
m_boundArrayBuffer = buffer;
- else if (target == GraphicsContext3D::ELEMENT_ARRAY_BUFFER)
+ else if (target == GL_ELEMENT_ARRAY_BUFFER)
m_boundVertexArrayObject->setElementArrayBuffer(buffer);
else {
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "bindBuffer", "invalid target");
+ synthesizeGLError(GL_INVALID_ENUM, "bindBuffer", "invalid target");
return;
}
@@ -1109,8 +1093,8 @@ void WebGLRenderingContext::bindFramebuffer(GC3Denum target, WebGLFramebuffer* b
return;
if (deleted)
buffer = 0;
- if (target != GraphicsContext3D::FRAMEBUFFER) {
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "bindFramebuffer", "invalid target");
+ if (target != GL_FRAMEBUFFER) {
+ synthesizeGLError(GL_INVALID_ENUM, "bindFramebuffer", "invalid target");
return;
}
m_framebufferBinding = buffer;
@@ -1132,8 +1116,8 @@ void WebGLRenderingContext::bindRenderbuffer(GC3Denum target, WebGLRenderbuffer*
return;
if (deleted)
renderBuffer = 0;
- if (target != GraphicsContext3D::RENDERBUFFER) {
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "bindRenderbuffer", "invalid target");
+ if (target != GL_RENDERBUFFER) {
+ synthesizeGLError(GL_INVALID_ENUM, "bindRenderbuffer", "invalid target");
return;
}
m_renderbufferBinding = renderBuffer;
@@ -1150,22 +1134,22 @@ void WebGLRenderingContext::bindTexture(GC3Denum target, WebGLTexture* texture)
if (deleted)
texture = 0;
if (texture && texture->getTarget() && texture->getTarget() != target) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "bindTexture", "textures can not be used with multiple targets");
+ synthesizeGLError(GL_INVALID_OPERATION, "bindTexture", "textures can not be used with multiple targets");
return;
}
GC3Dint maxLevel = 0;
- if (target == GraphicsContext3D::TEXTURE_2D) {
+ if (target == GL_TEXTURE_2D) {
m_textureUnits[m_activeTextureUnit].m_texture2DBinding = texture;
maxLevel = m_maxTextureLevel;
if (!m_activeTextureUnit)
m_drawingBuffer->setTexture2DBinding(objectOrZero(texture));
- } else if (target == GraphicsContext3D::TEXTURE_CUBE_MAP) {
+ } else if (target == GL_TEXTURE_CUBE_MAP) {
m_textureUnits[m_activeTextureUnit].m_textureCubeMapBinding = texture;
maxLevel = m_maxCubeMapTextureLevel;
} else {
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "bindTexture", "invalid target");
+ synthesizeGLError(GL_INVALID_ENUM, "bindTexture", "invalid target");
return;
}
@@ -1236,11 +1220,11 @@ void WebGLRenderingContext::bufferData(GC3Denum target, long long size, GC3Denum
if (!buffer)
return;
if (size < 0) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "bufferData", "size < 0");
+ synthesizeGLError(GL_INVALID_VALUE, "bufferData", "size < 0");
return;
}
if (!size) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "bufferData", "size == 0");
+ synthesizeGLError(GL_INVALID_VALUE, "bufferData", "size == 0");
return;
}
@@ -1255,7 +1239,7 @@ void WebGLRenderingContext::bufferData(GC3Denum target, ArrayBuffer* data, GC3De
if (!buffer)
return;
if (!data) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "bufferData", "no data");
+ synthesizeGLError(GL_INVALID_VALUE, "bufferData", "no data");
return;
}
m_context->bufferData(target, data->byteLength(), data->data(), usage);
@@ -1269,7 +1253,7 @@ void WebGLRenderingContext::bufferData(GC3Denum target, ArrayBufferView* data, G
if (!buffer)
return;
if (!data) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "bufferData", "no data");
+ synthesizeGLError(GL_INVALID_VALUE, "bufferData", "no data");
return;
}
@@ -1280,11 +1264,11 @@ void WebGLRenderingContext::bufferSubData(GC3Denum target, long long offset, Arr
{
if (isContextLost())
return;
- WebGLBuffer* buffer = validateBufferDataParameters("bufferSubData", target, GraphicsContext3D::STATIC_DRAW);
+ WebGLBuffer* buffer = validateBufferDataParameters("bufferSubData", target, GL_STATIC_DRAW);
if (!buffer)
return;
if (offset < 0) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "bufferSubData", "offset < 0");
+ synthesizeGLError(GL_INVALID_VALUE, "bufferSubData", "offset < 0");
return;
}
if (!data)
@@ -1297,11 +1281,11 @@ void WebGLRenderingContext::bufferSubData(GC3Denum target, long long offset, Arr
{
if (isContextLost())
return;
- WebGLBuffer* buffer = validateBufferDataParameters("bufferSubData", target, GraphicsContext3D::STATIC_DRAW);
+ WebGLBuffer* buffer = validateBufferDataParameters("bufferSubData", target, GL_STATIC_DRAW);
if (!buffer)
return;
if (offset < 0) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "bufferSubData", "offset < 0");
+ synthesizeGLError(GL_INVALID_VALUE, "bufferSubData", "offset < 0");
return;
}
if (!data)
@@ -1313,16 +1297,16 @@ void WebGLRenderingContext::bufferSubData(GC3Denum target, long long offset, Arr
GC3Denum WebGLRenderingContext::checkFramebufferStatus(GC3Denum target)
{
if (isContextLost())
- return GraphicsContext3D::FRAMEBUFFER_UNSUPPORTED;
- if (target != GraphicsContext3D::FRAMEBUFFER) {
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "checkFramebufferStatus", "invalid target");
+ return GL_FRAMEBUFFER_UNSUPPORTED;
+ if (target != GL_FRAMEBUFFER) {
+ synthesizeGLError(GL_INVALID_ENUM, "checkFramebufferStatus", "invalid target");
return 0;
}
if (!m_framebufferBinding || !m_framebufferBinding->object())
- return GraphicsContext3D::FRAMEBUFFER_COMPLETE;
+ return GL_FRAMEBUFFER_COMPLETE;
const char* reason = "framebuffer incomplete";
GC3Denum result = m_framebufferBinding->checkStatus(&reason);
- if (result != GraphicsContext3D::FRAMEBUFFER_COMPLETE) {
+ if (result != GL_FRAMEBUFFER_COMPLETE) {
emitGLWarning("checkFramebufferStatus", reason);
return result;
}
@@ -1334,13 +1318,13 @@ void WebGLRenderingContext::clear(GC3Dbitfield mask)
{
if (isContextLost())
return;
- if (mask & ~(GraphicsContext3D::COLOR_BUFFER_BIT | GraphicsContext3D::DEPTH_BUFFER_BIT | GraphicsContext3D::STENCIL_BUFFER_BIT)) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "clear", "invalid mask");
+ if (mask & ~(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT)) {
+ synthesizeGLError(GL_INVALID_VALUE, "clear", "invalid mask");
return;
}
const char* reason = "framebuffer incomplete";
if (m_framebufferBinding && !m_framebufferBinding->onAccess(graphicsContext3D(), &reason)) {
- synthesizeGLError(GraphicsContext3D::INVALID_FRAMEBUFFER_OPERATION, "clear", reason);
+ synthesizeGLError(GL_INVALID_FRAMEBUFFER_OPERATION, "clear", reason);
return;
}
if (!clearIfComposited(mask))
@@ -1410,11 +1394,11 @@ void WebGLRenderingContext::compressedTexImage2D(GC3Denum target, GC3Dint level,
return;
if (!validateCompressedTexFormat(internalformat)) {
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "compressedTexImage2D", "invalid internalformat");
+ synthesizeGLError(GL_INVALID_ENUM, "compressedTexImage2D", "invalid internalformat");
return;
}
if (border) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "compressedTexImage2D", "border not 0");
+ synthesizeGLError(GL_INVALID_VALUE, "compressedTexImage2D", "border not 0");
return;
}
if (!validateCompressedTexDimensions("compressedTexImage2D", NotTexSubImage2D, target, level, width, height, internalformat))
@@ -1427,13 +1411,13 @@ void WebGLRenderingContext::compressedTexImage2D(GC3Denum target, GC3Dint level,
return;
if (!isGLES2NPOTStrict()) {
if (level && WebGLTexture::isNPOT(width, height)) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "compressedTexImage2D", "level > 0 not power of 2");
+ synthesizeGLError(GL_INVALID_VALUE, "compressedTexImage2D", "level > 0 not power of 2");
return;
}
}
graphicsContext3D()->compressedTexImage2D(target, level, internalformat, width, height,
border, data->byteLength(), data->baseAddress());
- tex->setLevelInfo(target, level, internalformat, width, height, GraphicsContext3D::UNSIGNED_BYTE);
+ tex->setLevelInfo(target, level, internalformat, width, height, GL_UNSIGNED_BYTE);
}
void WebGLRenderingContext::compressedTexSubImage2D(GC3Denum target, GC3Dint level, GC3Dint xoffset, GC3Dint yoffset,
@@ -1444,7 +1428,7 @@ void WebGLRenderingContext::compressedTexSubImage2D(GC3Denum target, GC3Dint lev
if (!validateTexFuncLevel("compressedTexSubImage2D", target, level))
return;
if (!validateCompressedTexFormat(format)) {
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "compressedTexSubImage2D", "invalid format");
+ synthesizeGLError(GL_INVALID_ENUM, "compressedTexSubImage2D", "invalid format");
return;
}
if (!validateCompressedTexFuncData("compressedTexSubImage2D", width, height, format, data))
@@ -1455,7 +1439,7 @@ void WebGLRenderingContext::compressedTexSubImage2D(GC3Denum target, GC3Dint lev
return;
if (format != tex->getInternalFormat(target, level)) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "compressedTexSubImage2D", "format does not match texture format");
+ synthesizeGLError(GL_INVALID_OPERATION, "compressedTexSubImage2D", "format does not match texture format");
return;
}
@@ -1468,8 +1452,8 @@ void WebGLRenderingContext::compressedTexSubImage2D(GC3Denum target, GC3Dint lev
bool WebGLRenderingContext::validateSettableTexFormat(const char* functionName, GC3Denum format)
{
- if (GraphicsContext3D::getClearBitsByFormat(format) & (GraphicsContext3D::DEPTH_BUFFER_BIT | GraphicsContext3D::STENCIL_BUFFER_BIT)) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, functionName, "format can not be set, only rendered to");
+ if (GraphicsContext3D::getClearBitsByFormat(format) & (GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT)) {
+ synthesizeGLError(GL_INVALID_OPERATION, functionName, "format can not be set, only rendered to");
return false;
}
return true;
@@ -1479,7 +1463,7 @@ void WebGLRenderingContext::copyTexImage2D(GC3Denum target, GC3Dint level, GC3De
{
if (isContextLost())
return;
- if (!validateTexFuncParameters("copyTexImage2D", NotTexSubImage2D, target, level, internalformat, width, height, border, internalformat, GraphicsContext3D::UNSIGNED_BYTE))
+ if (!validateTexFuncParameters("copyTexImage2D", NotTexSubImage2D, target, level, internalformat, width, height, border, internalformat, GL_UNSIGNED_BYTE))
return;
if (!validateSettableTexFormat("copyTexImage2D", internalformat))
return;
@@ -1487,23 +1471,23 @@ void WebGLRenderingContext::copyTexImage2D(GC3Denum target, GC3Dint level, GC3De
if (!tex)
return;
if (!isTexInternalFormatColorBufferCombinationValid(internalformat, boundFramebufferColorFormat())) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "copyTexImage2D", "framebuffer is incompatible format");
+ synthesizeGLError(GL_INVALID_OPERATION, "copyTexImage2D", "framebuffer is incompatible format");
return;
}
if (!isGLES2NPOTStrict() && level && WebGLTexture::isNPOT(width, height)) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "copyTexImage2D", "level > 0 not power of 2");
+ synthesizeGLError(GL_INVALID_VALUE, "copyTexImage2D", "level > 0 not power of 2");
return;
}
const char* reason = "framebuffer incomplete";
if (m_framebufferBinding && !m_framebufferBinding->onAccess(graphicsContext3D(), &reason)) {
- synthesizeGLError(GraphicsContext3D::INVALID_FRAMEBUFFER_OPERATION, "copyTexImage2D", reason);
+ synthesizeGLError(GL_INVALID_FRAMEBUFFER_OPERATION, "copyTexImage2D", reason);
return;
}
clearIfComposited();
ScopedDrawingBufferBinder binder(m_drawingBuffer.get(), m_framebufferBinding.get());
m_context->copyTexImage2D(target, level, internalformat, x, y, width, height, border);
// FIXME: if the framebuffer is not complete, none of the below should be executed.
- tex->setLevelInfo(target, level, internalformat, width, height, GraphicsContext3D::UNSIGNED_BYTE);
+ tex->setLevelInfo(target, level, internalformat, width, height, GL_UNSIGNED_BYTE);
}
void WebGLRenderingContext::copyTexSubImage2D(GC3Denum target, GC3Dint level, GC3Dint xoffset, GC3Dint yoffset, GC3Dint x, GC3Dint y, GC3Dsizei width, GC3Dsizei height)
@@ -1518,24 +1502,29 @@ void WebGLRenderingContext::copyTexSubImage2D(GC3Denum target, GC3Dint level, GC
if (!validateSize("copyTexSubImage2D", xoffset, yoffset) || !validateSize("copyTexSubImage2D", width, height))
return;
// Before checking if it is in the range, check if overflow happens first.
- if (xoffset + width < 0 || yoffset + height < 0) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "copyTexSubImage2D", "bad dimensions");
+ Checked<GC3Dint, RecordOverflow> maxX = xoffset;
+ maxX += width;
+ Checked<GC3Dint, RecordOverflow> maxY = yoffset;
+ maxY += height;
+
+ if (maxX.hasOverflowed() || maxY.hasOverflowed()) {
+ synthesizeGLError(GL_INVALID_VALUE, "copyTexSubImage2D", "bad dimensions");
return;
}
- if (xoffset + width > tex->getWidth(target, level) || yoffset + height > tex->getHeight(target, level)) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "copyTexSubImage2D", "rectangle out of range");
+ if (maxX.unsafeGet() > tex->getWidth(target, level) || maxY.unsafeGet() > tex->getHeight(target, level)) {
+ synthesizeGLError(GL_INVALID_VALUE, "copyTexSubImage2D", "rectangle out of range");
return;
}
GC3Denum internalformat = tex->getInternalFormat(target, level);
if (!validateSettableTexFormat("copyTexSubImage2D", internalformat))
return;
if (!isTexInternalFormatColorBufferCombinationValid(internalformat, boundFramebufferColorFormat())) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "copyTexSubImage2D", "framebuffer is incompatible format");
+ synthesizeGLError(GL_INVALID_OPERATION, "copyTexSubImage2D", "framebuffer is incompatible format");
return;
}
const char* reason = "framebuffer incomplete";
if (m_framebufferBinding && !m_framebufferBinding->onAccess(graphicsContext3D(), &reason)) {
- synthesizeGLError(GraphicsContext3D::INVALID_FRAMEBUFFER_OPERATION, "copyTexSubImage2D", reason);
+ synthesizeGLError(GL_INVALID_FRAMEBUFFER_OPERATION, "copyTexSubImage2D", reason);
return;
}
clearIfComposited();
@@ -1604,8 +1593,8 @@ PassRefPtr<WebGLShader> WebGLRenderingContext::createShader(GC3Denum type)
{
if (isContextLost())
return 0;
- if (type != GraphicsContext3D::VERTEX_SHADER && type != GraphicsContext3D::FRAGMENT_SHADER) {
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "createShader", "invalid shader type");
+ if (type != GL_VERTEX_SHADER && type != GL_FRAGMENT_SHADER) {
+ synthesizeGLError(GL_INVALID_ENUM, "createShader", "invalid shader type");
return 0;
}
@@ -1619,12 +1608,12 @@ void WebGLRenderingContext::cullFace(GC3Denum mode)
if (isContextLost())
return;
switch (mode) {
- case GraphicsContext3D::FRONT_AND_BACK:
- case GraphicsContext3D::FRONT:
- case GraphicsContext3D::BACK:
+ case GL_FRONT_AND_BACK:
+ case GL_FRONT:
+ case GL_BACK:
break;
default:
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "cullFace", "invalid mode");
+ synthesizeGLError(GL_INVALID_ENUM, "cullFace", "invalid mode");
return;
}
m_context->cullFace(mode);
@@ -1635,7 +1624,7 @@ bool WebGLRenderingContext::deleteObject(WebGLObject* object)
if (isContextLost() || !object)
return false;
if (!object->validate(contextGroup(), this)) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "delete", "object does not belong to this context");
+ synthesizeGLError(GL_INVALID_OPERATION, "delete", "object does not belong to this context");
return false;
}
if (object->object())
@@ -1711,7 +1700,7 @@ void WebGLRenderingContext::deleteTexture(WebGLTexture* texture)
m_framebufferBinding->removeAttachmentFromBoundFramebuffer(texture);
// If the deleted was bound to the the current maximum index, trace backwards to find the new max texture index
- if (m_onePlusMaxNonDefaultTextureUnit == maxBoundTextureIndex + 1) {
+ if (m_onePlusMaxNonDefaultTextureUnit == static_cast<unsigned long>(maxBoundTextureIndex + 1)) {
findNewMaxNonDefaultTextureUnit();
}
}
@@ -1738,7 +1727,7 @@ void WebGLRenderingContext::depthRange(GC3Dfloat zNear, GC3Dfloat zFar)
if (isContextLost())
return;
if (zNear > zFar) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "depthRange", "zNear > zFar");
+ synthesizeGLError(GL_INVALID_OPERATION, "depthRange", "zNear > zFar");
return;
}
m_context->depthRange(zNear, zFar);
@@ -1749,7 +1738,7 @@ void WebGLRenderingContext::detachShader(WebGLProgram* program, WebGLShader* sha
if (isContextLost() || !validateWebGLObject("detachShader", program) || !validateWebGLObject("detachShader", shader))
return;
if (!program->detachShader(shader)) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "detachShader", "shader not attached");
+ synthesizeGLError(GL_INVALID_OPERATION, "detachShader", "shader not attached");
return;
}
m_context->detachShader(objectOrZero(program), objectOrZero(shader));
@@ -1760,12 +1749,12 @@ void WebGLRenderingContext::disable(GC3Denum cap)
{
if (isContextLost() || !validateCapability("disable", cap))
return;
- if (cap == GraphicsContext3D::STENCIL_TEST) {
+ if (cap == GL_STENCIL_TEST) {
m_stencilEnabled = false;
applyStencilTest();
return;
}
- if (cap == GraphicsContext3D::SCISSOR_TEST) {
+ if (cap == GL_SCISSOR_TEST) {
m_scissorEnabled = false;
m_drawingBuffer->setScissorEnabled(m_scissorEnabled);
}
@@ -1777,7 +1766,7 @@ void WebGLRenderingContext::disableVertexAttribArray(GC3Duint index)
if (isContextLost())
return;
if (index >= m_maxVertexAttribs) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "disableVertexAttribArray", "index out of range");
+ synthesizeGLError(GL_INVALID_VALUE, "disableVertexAttribArray", "index out of range");
return;
}
@@ -1811,11 +1800,11 @@ bool WebGLRenderingContext::validateRenderingState()
bool WebGLRenderingContext::validateWebGLObject(const char* functionName, WebGLObject* object)
{
if (!object || !object->object()) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "no object or object deleted");
+ synthesizeGLError(GL_INVALID_VALUE, functionName, "no object or object deleted");
return false;
}
if (!object->validate(contextGroup(), this)) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, functionName, "object does not belong to this context");
+ synthesizeGLError(GL_INVALID_OPERATION, functionName, "object does not belong to this context");
return false;
}
return true;
@@ -1883,12 +1872,12 @@ void WebGLRenderingContext::enable(GC3Denum cap)
{
if (isContextLost() || !validateCapability("enable", cap))
return;
- if (cap == GraphicsContext3D::STENCIL_TEST) {
+ if (cap == GL_STENCIL_TEST) {
m_stencilEnabled = true;
applyStencilTest();
return;
}
- if (cap == GraphicsContext3D::SCISSOR_TEST) {
+ if (cap == GL_SCISSOR_TEST) {
m_scissorEnabled = true;
m_drawingBuffer->setScissorEnabled(m_scissorEnabled);
}
@@ -1900,7 +1889,7 @@ void WebGLRenderingContext::enableVertexAttribArray(GC3Duint index)
if (isContextLost())
return;
if (index >= m_maxVertexAttribs) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "enableVertexAttribArray", "index out of range");
+ synthesizeGLError(GL_INVALID_VALUE, "enableVertexAttribArray", "index out of range");
return;
}
@@ -1930,35 +1919,35 @@ void WebGLRenderingContext::framebufferRenderbuffer(GC3Denum target, GC3Denum at
{
if (isContextLost() || !validateFramebufferFuncParameters("framebufferRenderbuffer", target, attachment))
return;
- if (renderbuffertarget != GraphicsContext3D::RENDERBUFFER) {
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "framebufferRenderbuffer", "invalid target");
+ if (renderbuffertarget != GL_RENDERBUFFER) {
+ synthesizeGLError(GL_INVALID_ENUM, "framebufferRenderbuffer", "invalid target");
return;
}
if (buffer && !buffer->validate(contextGroup(), this)) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "framebufferRenderbuffer", "no buffer or buffer not from this context");
+ synthesizeGLError(GL_INVALID_OPERATION, "framebufferRenderbuffer", "no buffer or buffer not from this context");
return;
}
// Don't allow the default framebuffer to be mutated; all current
// implementations use an FBO internally in place of the default
// FBO.
if (!m_framebufferBinding || !m_framebufferBinding->object()) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "framebufferRenderbuffer", "no framebuffer bound");
+ synthesizeGLError(GL_INVALID_OPERATION, "framebufferRenderbuffer", "no framebuffer bound");
return;
}
Platform3DObject bufferObject = objectOrZero(buffer);
switch (attachment) {
- case GraphicsContext3D::DEPTH_STENCIL_ATTACHMENT:
+ case GC3D_DEPTH_STENCIL_ATTACHMENT_WEBGL:
if (isDepthStencilSupported() || !buffer) {
- m_context->framebufferRenderbuffer(target, GraphicsContext3D::DEPTH_ATTACHMENT, renderbuffertarget, bufferObject);
- m_context->framebufferRenderbuffer(target, GraphicsContext3D::STENCIL_ATTACHMENT, renderbuffertarget, bufferObject);
+ m_context->framebufferRenderbuffer(target, GL_DEPTH_ATTACHMENT, renderbuffertarget, bufferObject);
+ m_context->framebufferRenderbuffer(target, GL_STENCIL_ATTACHMENT, renderbuffertarget, bufferObject);
} else {
WebGLRenderbuffer* emulatedStencilBuffer = ensureEmulatedStencilBuffer(renderbuffertarget, buffer);
if (!emulatedStencilBuffer) {
- synthesizeGLError(GraphicsContext3D::OUT_OF_MEMORY, "framebufferRenderbuffer", "out of memory");
+ synthesizeGLError(GL_OUT_OF_MEMORY, "framebufferRenderbuffer", "out of memory");
return;
}
- m_context->framebufferRenderbuffer(target, GraphicsContext3D::DEPTH_ATTACHMENT, renderbuffertarget, bufferObject);
- m_context->framebufferRenderbuffer(target, GraphicsContext3D::STENCIL_ATTACHMENT, renderbuffertarget, objectOrZero(emulatedStencilBuffer));
+ m_context->framebufferRenderbuffer(target, GL_DEPTH_ATTACHMENT, renderbuffertarget, bufferObject);
+ m_context->framebufferRenderbuffer(target, GL_STENCIL_ATTACHMENT, renderbuffertarget, objectOrZero(emulatedStencilBuffer));
}
break;
default:
@@ -1973,30 +1962,30 @@ void WebGLRenderingContext::framebufferTexture2D(GC3Denum target, GC3Denum attac
if (isContextLost() || !validateFramebufferFuncParameters("framebufferTexture2D", target, attachment))
return;
if (level) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "framebufferTexture2D", "level not 0");
+ synthesizeGLError(GL_INVALID_VALUE, "framebufferTexture2D", "level not 0");
return;
}
if (texture && !texture->validate(contextGroup(), this)) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "framebufferTexture2D", "no texture or texture not from this context");
+ synthesizeGLError(GL_INVALID_OPERATION, "framebufferTexture2D", "no texture or texture not from this context");
return;
}
// Don't allow the default framebuffer to be mutated; all current
// implementations use an FBO internally in place of the default
// FBO.
if (!m_framebufferBinding || !m_framebufferBinding->object()) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "framebufferTexture2D", "no framebuffer bound");
+ synthesizeGLError(GL_INVALID_OPERATION, "framebufferTexture2D", "no framebuffer bound");
return;
}
Platform3DObject textureObject = objectOrZero(texture);
switch (attachment) {
- case GraphicsContext3D::DEPTH_STENCIL_ATTACHMENT:
- m_context->framebufferTexture2D(target, GraphicsContext3D::DEPTH_ATTACHMENT, textarget, textureObject, level);
- m_context->framebufferTexture2D(target, GraphicsContext3D::STENCIL_ATTACHMENT, textarget, textureObject, level);
+ case GC3D_DEPTH_STENCIL_ATTACHMENT_WEBGL:
+ m_context->framebufferTexture2D(target, GL_DEPTH_ATTACHMENT, textarget, textureObject, level);
+ m_context->framebufferTexture2D(target, GL_STENCIL_ATTACHMENT, textarget, textureObject, level);
break;
- case GraphicsContext3D::DEPTH_ATTACHMENT:
+ case GL_DEPTH_ATTACHMENT:
m_context->framebufferTexture2D(target, attachment, textarget, textureObject, level);
break;
- case GraphicsContext3D::STENCIL_ATTACHMENT:
+ case GL_STENCIL_ATTACHMENT:
m_context->framebufferTexture2D(target, attachment, textarget, textureObject, level);
break;
default:
@@ -2011,11 +2000,11 @@ void WebGLRenderingContext::frontFace(GC3Denum mode)
if (isContextLost())
return;
switch (mode) {
- case GraphicsContext3D::CW:
- case GraphicsContext3D::CCW:
+ case GL_CW:
+ case GL_CCW:
break;
default:
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "frontFace", "invalid mode");
+ synthesizeGLError(GL_INVALID_ENUM, "frontFace", "invalid mode");
return;
}
m_context->frontFace(mode);
@@ -2029,7 +2018,7 @@ void WebGLRenderingContext::generateMipmap(GC3Denum target)
if (!tex)
return;
if (!tex->canGenerateMipmaps()) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "generateMipmap", "level 0 not power of 2 or not all the same size");
+ synthesizeGLError(GL_INVALID_OPERATION, "generateMipmap", "level 0 not power of 2 or not all the same size");
return;
}
if (!validateSettableTexFormat("generateMipmap", tex->getInternalFormat(target, 0)))
@@ -2039,15 +2028,15 @@ void WebGLRenderingContext::generateMipmap(GC3Denum target)
// on Mac. Remove the hack once this driver bug is fixed.
#if OS(MACOSX)
bool needToResetMinFilter = false;
- if (tex->getMinFilter() != GraphicsContext3D::NEAREST_MIPMAP_LINEAR) {
- m_context->texParameteri(target, GraphicsContext3D::TEXTURE_MIN_FILTER, GraphicsContext3D::NEAREST_MIPMAP_LINEAR);
+ if (tex->getMinFilter() != GL_NEAREST_MIPMAP_LINEAR) {
+ m_context->texParameteri(target, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_LINEAR);
needToResetMinFilter = true;
}
#endif
m_context->generateMipmap(target);
#if OS(MACOSX)
if (needToResetMinFilter)
- m_context->texParameteri(target, GraphicsContext3D::TEXTURE_MIN_FILTER, tex->getMinFilter());
+ m_context->texParameteri(target, GL_TEXTURE_MIN_FILTER, tex->getMinFilter());
#endif
tex->generateMipmapLevelInfo();
}
@@ -2079,8 +2068,8 @@ bool WebGLRenderingContext::getAttachedShaders(WebGLProgram* program, Vector<Ref
return false;
const GC3Denum shaderType[] = {
- GraphicsContext3D::VERTEX_SHADER,
- GraphicsContext3D::FRAGMENT_SHADER
+ GL_VERTEX_SHADER,
+ GL_FRAGMENT_SHADER
};
for (unsigned i = 0; i < sizeof(shaderType) / sizeof(GC3Denum); ++i) {
WebGLShader* shader = program->getAttachedShader(shaderType[i]);
@@ -2101,7 +2090,7 @@ GC3Dint WebGLRenderingContext::getAttribLocation(WebGLProgram* program, const St
if (isPrefixReserved(name))
return -1;
if (!program->linkStatus()) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "getAttribLocation", "program not linked");
+ synthesizeGLError(GL_INVALID_OPERATION, "getAttribLocation", "program not linked");
return 0;
}
return m_context->getAttribLocation(objectOrZero(program), name);
@@ -2111,19 +2100,19 @@ WebGLGetInfo WebGLRenderingContext::getBufferParameter(GC3Denum target, GC3Denum
{
if (isContextLost())
return WebGLGetInfo();
- if (target != GraphicsContext3D::ARRAY_BUFFER && target != GraphicsContext3D::ELEMENT_ARRAY_BUFFER) {
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "getBufferParameter", "invalid target");
+ if (target != GL_ARRAY_BUFFER && target != GL_ELEMENT_ARRAY_BUFFER) {
+ synthesizeGLError(GL_INVALID_ENUM, "getBufferParameter", "invalid target");
return WebGLGetInfo();
}
- if (pname != GraphicsContext3D::BUFFER_SIZE && pname != GraphicsContext3D::BUFFER_USAGE) {
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "getBufferParameter", "invalid parameter name");
+ if (pname != GL_BUFFER_SIZE && pname != GL_BUFFER_USAGE) {
+ synthesizeGLError(GL_INVALID_ENUM, "getBufferParameter", "invalid parameter name");
return WebGLGetInfo();
}
GC3Dint value = 0;
m_context->getBufferParameteriv(target, pname, &value);
- if (pname == GraphicsContext3D::BUFFER_SIZE)
+ if (pname == GL_BUFFER_SIZE)
return WebGLGetInfo(value);
return WebGLGetInfo(static_cast<unsigned int>(value));
}
@@ -2158,16 +2147,16 @@ GC3Denum WebGLRenderingContext::getError()
}
if (isContextLost())
- return GraphicsContext3D::NO_ERROR;
+ return GL_NO_ERROR;
return m_context->getError();
}
bool WebGLRenderingContext::ExtensionTracker::matchesNameWithPrefixes(const String& name) const
{
- static const char* unprefixed[] = { "", 0, };
+ static const char* const unprefixed[] = { "", 0, };
- const char** prefixes = m_prefixes ? m_prefixes : unprefixed;
+ const char* const* prefixes = m_prefixes ? m_prefixes : unprefixed;
for (; *prefixes; ++prefixes) {
String prefixedName = String(*prefixes) + extensionName();
if (equalIgnoringCase(prefixedName, name)) {
@@ -2206,46 +2195,46 @@ WebGLGetInfo WebGLRenderingContext::getFramebufferAttachmentParameter(GC3Denum t
return WebGLGetInfo();
if (!m_framebufferBinding || !m_framebufferBinding->object()) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "getFramebufferAttachmentParameter", "no framebuffer bound");
+ synthesizeGLError(GL_INVALID_OPERATION, "getFramebufferAttachmentParameter", "no framebuffer bound");
return WebGLGetInfo();
}
WebGLSharedObject* object = m_framebufferBinding->getAttachmentObject(attachment);
if (!object) {
- if (pname == GraphicsContext3D::FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE)
- return WebGLGetInfo(GraphicsContext3D::NONE);
+ if (pname == GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE)
+ return WebGLGetInfo(GL_NONE);
// OpenGL ES 2.0 specifies INVALID_ENUM in this case, while desktop GL
// specifies INVALID_OPERATION.
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "getFramebufferAttachmentParameter", "invalid parameter name");
+ synthesizeGLError(GL_INVALID_ENUM, "getFramebufferAttachmentParameter", "invalid parameter name");
return WebGLGetInfo();
}
ASSERT(object->isTexture() || object->isRenderbuffer());
if (object->isTexture()) {
switch (pname) {
- case GraphicsContext3D::FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE:
- return WebGLGetInfo(GraphicsContext3D::TEXTURE);
- case GraphicsContext3D::FRAMEBUFFER_ATTACHMENT_OBJECT_NAME:
+ case GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE:
+ return WebGLGetInfo(GL_TEXTURE);
+ case GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME:
return WebGLGetInfo(PassRefPtr<WebGLTexture>(static_cast<WebGLTexture*>(object)));
- case GraphicsContext3D::FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL:
- case GraphicsContext3D::FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE:
+ case GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL:
+ case GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE:
{
GC3Dint value = 0;
m_context->getFramebufferAttachmentParameteriv(target, attachment, pname, &value);
return WebGLGetInfo(value);
}
default:
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "getFramebufferAttachmentParameter", "invalid parameter name for texture attachment");
+ synthesizeGLError(GL_INVALID_ENUM, "getFramebufferAttachmentParameter", "invalid parameter name for texture attachment");
return WebGLGetInfo();
}
} else {
switch (pname) {
- case GraphicsContext3D::FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE:
- return WebGLGetInfo(GraphicsContext3D::RENDERBUFFER);
- case GraphicsContext3D::FRAMEBUFFER_ATTACHMENT_OBJECT_NAME:
+ case GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE:
+ return WebGLGetInfo(GL_RENDERBUFFER);
+ case GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME:
return WebGLGetInfo(PassRefPtr<WebGLRenderbuffer>(static_cast<WebGLRenderbuffer*>(object)));
default:
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "getFramebufferAttachmentParameter", "invalid parameter name for renderbuffer attachment");
+ synthesizeGLError(GL_INVALID_ENUM, "getFramebufferAttachmentParameter", "invalid parameter name for renderbuffer attachment");
return WebGLGetInfo();
}
}
@@ -2257,197 +2246,197 @@ WebGLGetInfo WebGLRenderingContext::getParameter(GC3Denum pname)
return WebGLGetInfo();
const int intZero = 0;
switch (pname) {
- case GraphicsContext3D::ACTIVE_TEXTURE:
+ case GL_ACTIVE_TEXTURE:
return getUnsignedIntParameter(pname);
- case GraphicsContext3D::ALIASED_LINE_WIDTH_RANGE:
+ case GL_ALIASED_LINE_WIDTH_RANGE:
return getWebGLFloatArrayParameter(pname);
- case GraphicsContext3D::ALIASED_POINT_SIZE_RANGE:
+ case GL_ALIASED_POINT_SIZE_RANGE:
return getWebGLFloatArrayParameter(pname);
- case GraphicsContext3D::ALPHA_BITS:
+ case GL_ALPHA_BITS:
return getIntParameter(pname);
- case GraphicsContext3D::ARRAY_BUFFER_BINDING:
+ case GL_ARRAY_BUFFER_BINDING:
return WebGLGetInfo(PassRefPtr<WebGLBuffer>(m_boundArrayBuffer));
- case GraphicsContext3D::BLEND:
+ case GL_BLEND:
return getBooleanParameter(pname);
- case GraphicsContext3D::BLEND_COLOR:
+ case GL_BLEND_COLOR:
return getWebGLFloatArrayParameter(pname);
- case GraphicsContext3D::BLEND_DST_ALPHA:
+ case GL_BLEND_DST_ALPHA:
return getUnsignedIntParameter(pname);
- case GraphicsContext3D::BLEND_DST_RGB:
+ case GL_BLEND_DST_RGB:
return getUnsignedIntParameter(pname);
- case GraphicsContext3D::BLEND_EQUATION_ALPHA:
+ case GL_BLEND_EQUATION_ALPHA:
return getUnsignedIntParameter(pname);
- case GraphicsContext3D::BLEND_EQUATION_RGB:
+ case GL_BLEND_EQUATION_RGB:
return getUnsignedIntParameter(pname);
- case GraphicsContext3D::BLEND_SRC_ALPHA:
+ case GL_BLEND_SRC_ALPHA:
return getUnsignedIntParameter(pname);
- case GraphicsContext3D::BLEND_SRC_RGB:
+ case GL_BLEND_SRC_RGB:
return getUnsignedIntParameter(pname);
- case GraphicsContext3D::BLUE_BITS:
+ case GL_BLUE_BITS:
return getIntParameter(pname);
- case GraphicsContext3D::COLOR_CLEAR_VALUE:
+ case GL_COLOR_CLEAR_VALUE:
return getWebGLFloatArrayParameter(pname);
- case GraphicsContext3D::COLOR_WRITEMASK:
+ case GL_COLOR_WRITEMASK:
return getBooleanArrayParameter(pname);
- case GraphicsContext3D::COMPRESSED_TEXTURE_FORMATS:
+ case GL_COMPRESSED_TEXTURE_FORMATS:
return WebGLGetInfo(Uint32Array::create(m_compressedTextureFormats.data(), m_compressedTextureFormats.size()));
- case GraphicsContext3D::CULL_FACE:
+ case GL_CULL_FACE:
return getBooleanParameter(pname);
- case GraphicsContext3D::CULL_FACE_MODE:
+ case GL_CULL_FACE_MODE:
return getUnsignedIntParameter(pname);
- case GraphicsContext3D::CURRENT_PROGRAM:
+ case GL_CURRENT_PROGRAM:
return WebGLGetInfo(PassRefPtr<WebGLProgram>(m_currentProgram));
- case GraphicsContext3D::DEPTH_BITS:
+ case GL_DEPTH_BITS:
if (!m_framebufferBinding && !m_attributes.depth)
return WebGLGetInfo(intZero);
return getIntParameter(pname);
- case GraphicsContext3D::DEPTH_CLEAR_VALUE:
+ case GL_DEPTH_CLEAR_VALUE:
return getFloatParameter(pname);
- case GraphicsContext3D::DEPTH_FUNC:
+ case GL_DEPTH_FUNC:
return getUnsignedIntParameter(pname);
- case GraphicsContext3D::DEPTH_RANGE:
+ case GL_DEPTH_RANGE:
return getWebGLFloatArrayParameter(pname);
- case GraphicsContext3D::DEPTH_TEST:
+ case GL_DEPTH_TEST:
return getBooleanParameter(pname);
- case GraphicsContext3D::DEPTH_WRITEMASK:
+ case GL_DEPTH_WRITEMASK:
return getBooleanParameter(pname);
- case GraphicsContext3D::DITHER:
+ case GL_DITHER:
return getBooleanParameter(pname);
- case GraphicsContext3D::ELEMENT_ARRAY_BUFFER_BINDING:
+ case GL_ELEMENT_ARRAY_BUFFER_BINDING:
return WebGLGetInfo(PassRefPtr<WebGLBuffer>(m_boundVertexArrayObject->boundElementArrayBuffer()));
- case GraphicsContext3D::FRAMEBUFFER_BINDING:
+ case GL_FRAMEBUFFER_BINDING:
return WebGLGetInfo(PassRefPtr<WebGLFramebuffer>(m_framebufferBinding));
- case GraphicsContext3D::FRONT_FACE:
+ case GL_FRONT_FACE:
return getUnsignedIntParameter(pname);
- case GraphicsContext3D::GENERATE_MIPMAP_HINT:
+ case GL_GENERATE_MIPMAP_HINT:
return getUnsignedIntParameter(pname);
- case GraphicsContext3D::GREEN_BITS:
+ case GL_GREEN_BITS:
return getIntParameter(pname);
- case GraphicsContext3D::LINE_WIDTH:
+ case GL_LINE_WIDTH:
return getFloatParameter(pname);
- case GraphicsContext3D::MAX_COMBINED_TEXTURE_IMAGE_UNITS:
+ case GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS:
return getIntParameter(pname);
- case GraphicsContext3D::MAX_CUBE_MAP_TEXTURE_SIZE:
+ case GL_MAX_CUBE_MAP_TEXTURE_SIZE:
return getIntParameter(pname);
- case GraphicsContext3D::MAX_FRAGMENT_UNIFORM_VECTORS:
+ case GL_MAX_FRAGMENT_UNIFORM_VECTORS:
return getIntParameter(pname);
- case GraphicsContext3D::MAX_RENDERBUFFER_SIZE:
+ case GL_MAX_RENDERBUFFER_SIZE:
return getIntParameter(pname);
- case GraphicsContext3D::MAX_TEXTURE_IMAGE_UNITS:
+ case GL_MAX_TEXTURE_IMAGE_UNITS:
return getIntParameter(pname);
- case GraphicsContext3D::MAX_TEXTURE_SIZE:
+ case GL_MAX_TEXTURE_SIZE:
return getIntParameter(pname);
- case GraphicsContext3D::MAX_VARYING_VECTORS:
+ case GL_MAX_VARYING_VECTORS:
return getIntParameter(pname);
- case GraphicsContext3D::MAX_VERTEX_ATTRIBS:
+ case GL_MAX_VERTEX_ATTRIBS:
return getIntParameter(pname);
- case GraphicsContext3D::MAX_VERTEX_TEXTURE_IMAGE_UNITS:
+ case GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS:
return getIntParameter(pname);
- case GraphicsContext3D::MAX_VERTEX_UNIFORM_VECTORS:
+ case GL_MAX_VERTEX_UNIFORM_VECTORS:
return getIntParameter(pname);
- case GraphicsContext3D::MAX_VIEWPORT_DIMS:
+ case GL_MAX_VIEWPORT_DIMS:
return getWebGLIntArrayParameter(pname);
- case GraphicsContext3D::NUM_SHADER_BINARY_FORMATS:
+ case GL_NUM_SHADER_BINARY_FORMATS:
// FIXME: should we always return 0 for this?
return getIntParameter(pname);
- case GraphicsContext3D::PACK_ALIGNMENT:
+ case GL_PACK_ALIGNMENT:
return getIntParameter(pname);
- case GraphicsContext3D::POLYGON_OFFSET_FACTOR:
+ case GL_POLYGON_OFFSET_FACTOR:
return getFloatParameter(pname);
- case GraphicsContext3D::POLYGON_OFFSET_FILL:
+ case GL_POLYGON_OFFSET_FILL:
return getBooleanParameter(pname);
- case GraphicsContext3D::POLYGON_OFFSET_UNITS:
+ case GL_POLYGON_OFFSET_UNITS:
return getFloatParameter(pname);
- case GraphicsContext3D::RED_BITS:
+ case GL_RED_BITS:
return getIntParameter(pname);
- case GraphicsContext3D::RENDERBUFFER_BINDING:
+ case GL_RENDERBUFFER_BINDING:
return WebGLGetInfo(PassRefPtr<WebGLRenderbuffer>(m_renderbufferBinding));
- case GraphicsContext3D::RENDERER:
+ case GL_RENDERER:
return WebGLGetInfo(String("WebKit WebGL"));
- case GraphicsContext3D::SAMPLE_BUFFERS:
+ case GL_SAMPLE_BUFFERS:
return getIntParameter(pname);
- case GraphicsContext3D::SAMPLE_COVERAGE_INVERT:
+ case GL_SAMPLE_COVERAGE_INVERT:
return getBooleanParameter(pname);
- case GraphicsContext3D::SAMPLE_COVERAGE_VALUE:
+ case GL_SAMPLE_COVERAGE_VALUE:
return getFloatParameter(pname);
- case GraphicsContext3D::SAMPLES:
+ case GL_SAMPLES:
return getIntParameter(pname);
- case GraphicsContext3D::SCISSOR_BOX:
+ case GL_SCISSOR_BOX:
return getWebGLIntArrayParameter(pname);
- case GraphicsContext3D::SCISSOR_TEST:
+ case GL_SCISSOR_TEST:
return getBooleanParameter(pname);
- case GraphicsContext3D::SHADING_LANGUAGE_VERSION:
- return WebGLGetInfo("WebGL GLSL ES 1.0 (" + m_context->getString(GraphicsContext3D::SHADING_LANGUAGE_VERSION) + ")");
- case GraphicsContext3D::STENCIL_BACK_FAIL:
+ case GL_SHADING_LANGUAGE_VERSION:
+ return WebGLGetInfo("WebGL GLSL ES 1.0 (" + m_context->getString(GL_SHADING_LANGUAGE_VERSION) + ")");
+ case GL_STENCIL_BACK_FAIL:
return getUnsignedIntParameter(pname);
- case GraphicsContext3D::STENCIL_BACK_FUNC:
+ case GL_STENCIL_BACK_FUNC:
return getUnsignedIntParameter(pname);
- case GraphicsContext3D::STENCIL_BACK_PASS_DEPTH_FAIL:
+ case GL_STENCIL_BACK_PASS_DEPTH_FAIL:
return getUnsignedIntParameter(pname);
- case GraphicsContext3D::STENCIL_BACK_PASS_DEPTH_PASS:
+ case GL_STENCIL_BACK_PASS_DEPTH_PASS:
return getUnsignedIntParameter(pname);
- case GraphicsContext3D::STENCIL_BACK_REF:
+ case GL_STENCIL_BACK_REF:
return getIntParameter(pname);
- case GraphicsContext3D::STENCIL_BACK_VALUE_MASK:
+ case GL_STENCIL_BACK_VALUE_MASK:
return getUnsignedIntParameter(pname);
- case GraphicsContext3D::STENCIL_BACK_WRITEMASK:
+ case GL_STENCIL_BACK_WRITEMASK:
return getUnsignedIntParameter(pname);
- case GraphicsContext3D::STENCIL_BITS:
+ case GL_STENCIL_BITS:
if (!m_framebufferBinding && !m_attributes.stencil)
return WebGLGetInfo(intZero);
return getIntParameter(pname);
- case GraphicsContext3D::STENCIL_CLEAR_VALUE:
+ case GL_STENCIL_CLEAR_VALUE:
return getIntParameter(pname);
- case GraphicsContext3D::STENCIL_FAIL:
+ case GL_STENCIL_FAIL:
return getUnsignedIntParameter(pname);
- case GraphicsContext3D::STENCIL_FUNC:
+ case GL_STENCIL_FUNC:
return getUnsignedIntParameter(pname);
- case GraphicsContext3D::STENCIL_PASS_DEPTH_FAIL:
+ case GL_STENCIL_PASS_DEPTH_FAIL:
return getUnsignedIntParameter(pname);
- case GraphicsContext3D::STENCIL_PASS_DEPTH_PASS:
+ case GL_STENCIL_PASS_DEPTH_PASS:
return getUnsignedIntParameter(pname);
- case GraphicsContext3D::STENCIL_REF:
+ case GL_STENCIL_REF:
return getIntParameter(pname);
- case GraphicsContext3D::STENCIL_TEST:
+ case GL_STENCIL_TEST:
return getBooleanParameter(pname);
- case GraphicsContext3D::STENCIL_VALUE_MASK:
+ case GL_STENCIL_VALUE_MASK:
return getUnsignedIntParameter(pname);
- case GraphicsContext3D::STENCIL_WRITEMASK:
+ case GL_STENCIL_WRITEMASK:
return getUnsignedIntParameter(pname);
- case GraphicsContext3D::SUBPIXEL_BITS:
+ case GL_SUBPIXEL_BITS:
return getIntParameter(pname);
- case GraphicsContext3D::TEXTURE_BINDING_2D:
+ case GL_TEXTURE_BINDING_2D:
return WebGLGetInfo(PassRefPtr<WebGLTexture>(m_textureUnits[m_activeTextureUnit].m_texture2DBinding));
- case GraphicsContext3D::TEXTURE_BINDING_CUBE_MAP:
+ case GL_TEXTURE_BINDING_CUBE_MAP:
return WebGLGetInfo(PassRefPtr<WebGLTexture>(m_textureUnits[m_activeTextureUnit].m_textureCubeMapBinding));
- case GraphicsContext3D::UNPACK_ALIGNMENT:
+ case GL_UNPACK_ALIGNMENT:
return getIntParameter(pname);
- case GraphicsContext3D::UNPACK_FLIP_Y_WEBGL:
+ case GC3D_UNPACK_FLIP_Y_WEBGL:
return WebGLGetInfo(m_unpackFlipY);
- case GraphicsContext3D::UNPACK_PREMULTIPLY_ALPHA_WEBGL:
+ case GC3D_UNPACK_PREMULTIPLY_ALPHA_WEBGL:
return WebGLGetInfo(m_unpackPremultiplyAlpha);
- case GraphicsContext3D::UNPACK_COLORSPACE_CONVERSION_WEBGL:
+ case GC3D_UNPACK_COLORSPACE_CONVERSION_WEBGL:
return WebGLGetInfo(m_unpackColorspaceConversion);
- case GraphicsContext3D::VENDOR:
+ case GL_VENDOR:
return WebGLGetInfo(String("WebKit"));
- case GraphicsContext3D::VERSION:
- return WebGLGetInfo("WebGL 1.0 (" + m_context->getString(GraphicsContext3D::VERSION) + ")");
- case GraphicsContext3D::VIEWPORT:
+ case GL_VERSION:
+ return WebGLGetInfo("WebGL 1.0 (" + m_context->getString(GL_VERSION) + ")");
+ case GL_VIEWPORT:
return getWebGLIntArrayParameter(pname);
case Extensions3D::FRAGMENT_SHADER_DERIVATIVE_HINT_OES: // OES_standard_derivatives
if (m_oesStandardDerivatives)
return getUnsignedIntParameter(Extensions3D::FRAGMENT_SHADER_DERIVATIVE_HINT_OES);
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "getParameter", "invalid parameter name, OES_standard_derivatives not enabled");
+ synthesizeGLError(GL_INVALID_ENUM, "getParameter", "invalid parameter name, OES_standard_derivatives not enabled");
return WebGLGetInfo();
case WebGLDebugRendererInfo::UNMASKED_RENDERER_WEBGL:
if (m_webglDebugRendererInfo)
- return WebGLGetInfo(m_context->getString(GraphicsContext3D::RENDERER));
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "getParameter", "invalid parameter name, WEBGL_debug_renderer_info not enabled");
+ return WebGLGetInfo(m_context->getString(GL_RENDERER));
+ synthesizeGLError(GL_INVALID_ENUM, "getParameter", "invalid parameter name, WEBGL_debug_renderer_info not enabled");
return WebGLGetInfo();
case WebGLDebugRendererInfo::UNMASKED_VENDOR_WEBGL:
if (m_webglDebugRendererInfo)
- return WebGLGetInfo(m_context->getString(GraphicsContext3D::VENDOR));
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "getParameter", "invalid parameter name, WEBGL_debug_renderer_info not enabled");
+ return WebGLGetInfo(m_context->getString(GL_VENDOR));
+ synthesizeGLError(GL_INVALID_ENUM, "getParameter", "invalid parameter name, WEBGL_debug_renderer_info not enabled");
return WebGLGetInfo();
case Extensions3D::VERTEX_ARRAY_BINDING_OES: // OES_vertex_array_object
if (m_oesVertexArrayObject) {
@@ -2455,35 +2444,35 @@ WebGLGetInfo WebGLRenderingContext::getParameter(GC3Denum pname)
return WebGLGetInfo(PassRefPtr<WebGLVertexArrayObjectOES>(m_boundVertexArrayObject));
return WebGLGetInfo();
}
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "getParameter", "invalid parameter name, OES_vertex_array_object not enabled");
+ synthesizeGLError(GL_INVALID_ENUM, "getParameter", "invalid parameter name, OES_vertex_array_object not enabled");
return WebGLGetInfo();
case Extensions3D::MAX_TEXTURE_MAX_ANISOTROPY_EXT: // EXT_texture_filter_anisotropic
if (m_extTextureFilterAnisotropic)
return getUnsignedIntParameter(Extensions3D::MAX_TEXTURE_MAX_ANISOTROPY_EXT);
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "getParameter", "invalid parameter name, EXT_texture_filter_anisotropic not enabled");
+ synthesizeGLError(GL_INVALID_ENUM, "getParameter", "invalid parameter name, EXT_texture_filter_anisotropic not enabled");
return WebGLGetInfo();
case Extensions3D::MAX_COLOR_ATTACHMENTS_EXT: // EXT_draw_buffers BEGIN
if (m_webglDrawBuffers)
return WebGLGetInfo(maxColorAttachments());
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "getParameter", "invalid parameter name, WEBGL_draw_buffers not enabled");
+ synthesizeGLError(GL_INVALID_ENUM, "getParameter", "invalid parameter name, WEBGL_draw_buffers not enabled");
return WebGLGetInfo();
case Extensions3D::MAX_DRAW_BUFFERS_EXT:
if (m_webglDrawBuffers)
return WebGLGetInfo(maxDrawBuffers());
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "getParameter", "invalid parameter name, WEBGL_draw_buffers not enabled");
+ synthesizeGLError(GL_INVALID_ENUM, "getParameter", "invalid parameter name, WEBGL_draw_buffers not enabled");
return WebGLGetInfo();
default:
if (m_webglDrawBuffers
&& pname >= Extensions3D::DRAW_BUFFER0_EXT
&& pname < static_cast<GC3Denum>(Extensions3D::DRAW_BUFFER0_EXT + maxDrawBuffers())) {
- GC3Dint value = GraphicsContext3D::NONE;
+ GC3Dint value = GL_NONE;
if (m_framebufferBinding)
value = m_framebufferBinding->getDrawBuffer(pname);
else // emulated backbuffer
value = m_backDrawBuffer;
return WebGLGetInfo(value);
}
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "getParameter", "invalid parameter name");
+ synthesizeGLError(GL_INVALID_ENUM, "getParameter", "invalid parameter name");
return WebGLGetInfo();
}
}
@@ -2495,20 +2484,20 @@ WebGLGetInfo WebGLRenderingContext::getProgramParameter(WebGLProgram* program, G
GC3Dint value = 0;
switch (pname) {
- case GraphicsContext3D::DELETE_STATUS:
+ case GL_DELETE_STATUS:
return WebGLGetInfo(program->isDeleted());
- case GraphicsContext3D::VALIDATE_STATUS:
+ case GL_VALIDATE_STATUS:
m_context->getProgramiv(objectOrZero(program), pname, &value);
return WebGLGetInfo(static_cast<bool>(value));
- case GraphicsContext3D::LINK_STATUS:
+ case GL_LINK_STATUS:
return WebGLGetInfo(program->linkStatus());
- case GraphicsContext3D::ATTACHED_SHADERS:
- case GraphicsContext3D::ACTIVE_ATTRIBUTES:
- case GraphicsContext3D::ACTIVE_UNIFORMS:
+ case GL_ATTACHED_SHADERS:
+ case GL_ACTIVE_ATTRIBUTES:
+ case GL_ACTIVE_UNIFORMS:
m_context->getProgramiv(objectOrZero(program), pname, &value);
return WebGLGetInfo(value);
default:
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "getProgramParameter", "invalid parameter name");
+ synthesizeGLError(GL_INVALID_ENUM, "getProgramParameter", "invalid parameter name");
return WebGLGetInfo();
}
}
@@ -2526,27 +2515,27 @@ WebGLGetInfo WebGLRenderingContext::getRenderbufferParameter(GC3Denum target, GC
{
if (isContextLost())
return WebGLGetInfo();
- if (target != GraphicsContext3D::RENDERBUFFER) {
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "getRenderbufferParameter", "invalid target");
+ if (target != GL_RENDERBUFFER) {
+ synthesizeGLError(GL_INVALID_ENUM, "getRenderbufferParameter", "invalid target");
return WebGLGetInfo();
}
if (!m_renderbufferBinding || !m_renderbufferBinding->object()) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "getRenderbufferParameter", "no renderbuffer bound");
+ synthesizeGLError(GL_INVALID_OPERATION, "getRenderbufferParameter", "no renderbuffer bound");
return WebGLGetInfo();
}
GC3Dint value = 0;
switch (pname) {
- case GraphicsContext3D::RENDERBUFFER_WIDTH:
- case GraphicsContext3D::RENDERBUFFER_HEIGHT:
- case GraphicsContext3D::RENDERBUFFER_RED_SIZE:
- case GraphicsContext3D::RENDERBUFFER_GREEN_SIZE:
- case GraphicsContext3D::RENDERBUFFER_BLUE_SIZE:
- case GraphicsContext3D::RENDERBUFFER_ALPHA_SIZE:
- case GraphicsContext3D::RENDERBUFFER_DEPTH_SIZE:
+ case GL_RENDERBUFFER_WIDTH:
+ case GL_RENDERBUFFER_HEIGHT:
+ case GL_RENDERBUFFER_RED_SIZE:
+ case GL_RENDERBUFFER_GREEN_SIZE:
+ case GL_RENDERBUFFER_BLUE_SIZE:
+ case GL_RENDERBUFFER_ALPHA_SIZE:
+ case GL_RENDERBUFFER_DEPTH_SIZE:
m_context->getRenderbufferParameteriv(target, pname, &value);
return WebGLGetInfo(value);
- case GraphicsContext3D::RENDERBUFFER_STENCIL_SIZE:
+ case GL_RENDERBUFFER_STENCIL_SIZE:
if (m_renderbufferBinding->emulatedStencilBuffer()) {
m_context->bindRenderbuffer(target, objectOrZero(m_renderbufferBinding->emulatedStencilBuffer()));
m_context->getRenderbufferParameteriv(target, pname, &value);
@@ -2555,10 +2544,10 @@ WebGLGetInfo WebGLRenderingContext::getRenderbufferParameter(GC3Denum target, GC
m_context->getRenderbufferParameteriv(target, pname, &value);
}
return WebGLGetInfo(value);
- case GraphicsContext3D::RENDERBUFFER_INTERNAL_FORMAT:
+ case GL_RENDERBUFFER_INTERNAL_FORMAT:
return WebGLGetInfo(m_renderbufferBinding->internalFormat());
default:
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "getRenderbufferParameter", "invalid parameter name");
+ synthesizeGLError(GL_INVALID_ENUM, "getRenderbufferParameter", "invalid parameter name");
return WebGLGetInfo();
}
}
@@ -2569,16 +2558,16 @@ WebGLGetInfo WebGLRenderingContext::getShaderParameter(WebGLShader* shader, GC3D
return WebGLGetInfo();
GC3Dint value = 0;
switch (pname) {
- case GraphicsContext3D::DELETE_STATUS:
+ case GL_DELETE_STATUS:
return WebGLGetInfo(shader->isDeleted());
- case GraphicsContext3D::COMPILE_STATUS:
+ case GL_COMPILE_STATUS:
m_context->getShaderiv(objectOrZero(shader), pname, &value);
return WebGLGetInfo(static_cast<bool>(value));
- case GraphicsContext3D::SHADER_TYPE:
+ case GL_SHADER_TYPE:
m_context->getShaderiv(objectOrZero(shader), pname, &value);
return WebGLGetInfo(static_cast<unsigned int>(value));
default:
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "getShaderParameter", "invalid parameter name");
+ synthesizeGLError(GL_INVALID_ENUM, "getShaderParameter", "invalid parameter name");
return WebGLGetInfo();
}
}
@@ -2597,23 +2586,23 @@ PassRefPtr<WebGLShaderPrecisionFormat> WebGLRenderingContext::getShaderPrecision
if (isContextLost())
return 0;
switch (shaderType) {
- case GraphicsContext3D::VERTEX_SHADER:
- case GraphicsContext3D::FRAGMENT_SHADER:
+ case GL_VERTEX_SHADER:
+ case GL_FRAGMENT_SHADER:
break;
default:
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "getShaderPrecisionFormat", "invalid shader type");
+ synthesizeGLError(GL_INVALID_ENUM, "getShaderPrecisionFormat", "invalid shader type");
return 0;
}
switch (precisionType) {
- case GraphicsContext3D::LOW_FLOAT:
- case GraphicsContext3D::MEDIUM_FLOAT:
- case GraphicsContext3D::HIGH_FLOAT:
- case GraphicsContext3D::LOW_INT:
- case GraphicsContext3D::MEDIUM_INT:
- case GraphicsContext3D::HIGH_INT:
+ case GL_LOW_FLOAT:
+ case GL_MEDIUM_FLOAT:
+ case GL_HIGH_FLOAT:
+ case GL_LOW_INT:
+ case GL_MEDIUM_INT:
+ case GL_HIGH_INT:
break;
default:
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "getShaderPrecisionFormat", "invalid precision type");
+ synthesizeGLError(GL_INVALID_ENUM, "getShaderPrecisionFormat", "invalid precision type");
return 0;
}
@@ -2662,10 +2651,10 @@ WebGLGetInfo WebGLRenderingContext::getTexParameter(GC3Denum target, GC3Denum pn
return WebGLGetInfo();
GC3Dint value = 0;
switch (pname) {
- case GraphicsContext3D::TEXTURE_MAG_FILTER:
- case GraphicsContext3D::TEXTURE_MIN_FILTER:
- case GraphicsContext3D::TEXTURE_WRAP_S:
- case GraphicsContext3D::TEXTURE_WRAP_T:
+ case GL_TEXTURE_MAG_FILTER:
+ case GL_TEXTURE_MIN_FILTER:
+ case GL_TEXTURE_WRAP_S:
+ case GL_TEXTURE_WRAP_T:
m_context->getTexParameteriv(target, pname, &value);
return WebGLGetInfo(static_cast<unsigned int>(value));
case Extensions3D::TEXTURE_MAX_ANISOTROPY_EXT: // EXT_texture_filter_anisotropic
@@ -2673,10 +2662,10 @@ WebGLGetInfo WebGLRenderingContext::getTexParameter(GC3Denum target, GC3Denum pn
m_context->getTexParameteriv(target, pname, &value);
return WebGLGetInfo(static_cast<unsigned int>(value));
}
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "getTexParameter", "invalid parameter name, EXT_texture_filter_anisotropic not enabled");
+ synthesizeGLError(GL_INVALID_ENUM, "getTexParameter", "invalid parameter name, EXT_texture_filter_anisotropic not enabled");
return WebGLGetInfo();
default:
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "getTexParameter", "invalid parameter name");
+ synthesizeGLError(GL_INVALID_ENUM, "getTexParameter", "invalid parameter name");
return WebGLGetInfo();
}
}
@@ -2686,14 +2675,14 @@ WebGLGetInfo WebGLRenderingContext::getUniform(WebGLProgram* program, const WebG
if (isContextLost() || !validateWebGLObject("getUniform", program))
return WebGLGetInfo();
if (!uniformLocation || uniformLocation->program() != program) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "getUniform", "no uniformlocation or not valid for this program");
+ synthesizeGLError(GL_INVALID_OPERATION, "getUniform", "no uniformlocation or not valid for this program");
return WebGLGetInfo();
}
GC3Dint location = uniformLocation->location();
// FIXME: make this more efficient using WebGLUniformLocation and caching types in it
GC3Dint activeUniforms = 0;
- m_context->getProgramiv(objectOrZero(program), GraphicsContext3D::ACTIVE_UNIFORMS, &activeUniforms);
+ m_context->getProgramiv(objectOrZero(program), GL_ACTIVE_UNIFORMS, &activeUniforms);
for (GC3Dint i = 0; i < activeUniforms; i++) {
ActiveInfo info;
if (!m_context->getActiveUniform(objectOrZero(program), i, info))
@@ -2716,92 +2705,92 @@ WebGLGetInfo WebGLRenderingContext::getUniform(WebGLProgram* program, const WebG
GC3Denum baseType;
unsigned int length;
switch (info.type) {
- case GraphicsContext3D::BOOL:
- baseType = GraphicsContext3D::BOOL;
+ case GL_BOOL:
+ baseType = GL_BOOL;
length = 1;
break;
- case GraphicsContext3D::BOOL_VEC2:
- baseType = GraphicsContext3D::BOOL;
+ case GL_BOOL_VEC2:
+ baseType = GL_BOOL;
length = 2;
break;
- case GraphicsContext3D::BOOL_VEC3:
- baseType = GraphicsContext3D::BOOL;
+ case GL_BOOL_VEC3:
+ baseType = GL_BOOL;
length = 3;
break;
- case GraphicsContext3D::BOOL_VEC4:
- baseType = GraphicsContext3D::BOOL;
+ case GL_BOOL_VEC4:
+ baseType = GL_BOOL;
length = 4;
break;
- case GraphicsContext3D::INT:
- baseType = GraphicsContext3D::INT;
+ case GL_INT:
+ baseType = GL_INT;
length = 1;
break;
- case GraphicsContext3D::INT_VEC2:
- baseType = GraphicsContext3D::INT;
+ case GL_INT_VEC2:
+ baseType = GL_INT;
length = 2;
break;
- case GraphicsContext3D::INT_VEC3:
- baseType = GraphicsContext3D::INT;
+ case GL_INT_VEC3:
+ baseType = GL_INT;
length = 3;
break;
- case GraphicsContext3D::INT_VEC4:
- baseType = GraphicsContext3D::INT;
+ case GL_INT_VEC4:
+ baseType = GL_INT;
length = 4;
break;
- case GraphicsContext3D::FLOAT:
- baseType = GraphicsContext3D::FLOAT;
+ case GL_FLOAT:
+ baseType = GL_FLOAT;
length = 1;
break;
- case GraphicsContext3D::FLOAT_VEC2:
- baseType = GraphicsContext3D::FLOAT;
+ case GL_FLOAT_VEC2:
+ baseType = GL_FLOAT;
length = 2;
break;
- case GraphicsContext3D::FLOAT_VEC3:
- baseType = GraphicsContext3D::FLOAT;
+ case GL_FLOAT_VEC3:
+ baseType = GL_FLOAT;
length = 3;
break;
- case GraphicsContext3D::FLOAT_VEC4:
- baseType = GraphicsContext3D::FLOAT;
+ case GL_FLOAT_VEC4:
+ baseType = GL_FLOAT;
length = 4;
break;
- case GraphicsContext3D::FLOAT_MAT2:
- baseType = GraphicsContext3D::FLOAT;
+ case GL_FLOAT_MAT2:
+ baseType = GL_FLOAT;
length = 4;
break;
- case GraphicsContext3D::FLOAT_MAT3:
- baseType = GraphicsContext3D::FLOAT;
+ case GL_FLOAT_MAT3:
+ baseType = GL_FLOAT;
length = 9;
break;
- case GraphicsContext3D::FLOAT_MAT4:
- baseType = GraphicsContext3D::FLOAT;
+ case GL_FLOAT_MAT4:
+ baseType = GL_FLOAT;
length = 16;
break;
- case GraphicsContext3D::SAMPLER_2D:
- case GraphicsContext3D::SAMPLER_CUBE:
- baseType = GraphicsContext3D::INT;
+ case GL_SAMPLER_2D:
+ case GL_SAMPLER_CUBE:
+ baseType = GL_INT;
length = 1;
break;
default:
// Can't handle this type
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "getUniform", "unhandled type");
+ synthesizeGLError(GL_INVALID_VALUE, "getUniform", "unhandled type");
return WebGLGetInfo();
}
switch (baseType) {
- case GraphicsContext3D::FLOAT: {
+ case GL_FLOAT: {
GC3Dfloat value[16] = {0};
m_context->getUniformfv(objectOrZero(program), location, value);
if (length == 1)
return WebGLGetInfo(value[0]);
return WebGLGetInfo(Float32Array::create(value, length));
}
- case GraphicsContext3D::INT: {
+ case GL_INT: {
GC3Dint value[4] = {0};
m_context->getUniformiv(objectOrZero(program), location, value);
if (length == 1)
return WebGLGetInfo(value[0]);
return WebGLGetInfo(Int32Array::create(value, length));
}
- case GraphicsContext3D::BOOL: {
+ case GL_BOOL: {
GC3Dint value[4] = {0};
m_context->getUniformiv(objectOrZero(program), location, value);
if (length > 1) {
@@ -2819,7 +2808,7 @@ WebGLGetInfo WebGLRenderingContext::getUniform(WebGLProgram* program, const WebG
}
}
// If we get here, something went wrong in our unfortunately complex logic above
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "getUniform", "unknown error");
+ synthesizeGLError(GL_INVALID_VALUE, "getUniform", "unknown error");
return WebGLGetInfo();
}
@@ -2834,7 +2823,7 @@ PassRefPtr<WebGLUniformLocation> WebGLRenderingContext::getUniformLocation(WebGL
if (isPrefixReserved(name))
return 0;
if (!program->linkStatus()) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "getUniformLocation", "program not linked");
+ synthesizeGLError(GL_INVALID_OPERATION, "getUniformLocation", "program not linked");
return 0;
}
GC3Dint uniformLocation = m_context->getUniformLocation(objectOrZero(program), name);
@@ -2848,7 +2837,7 @@ WebGLGetInfo WebGLRenderingContext::getVertexAttrib(GC3Duint index, GC3Denum pna
if (isContextLost())
return WebGLGetInfo();
if (index >= m_maxVertexAttribs) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "getVertexAttrib", "index out of range");
+ synthesizeGLError(GL_INVALID_VALUE, "getVertexAttrib", "index out of range");
return WebGLGetInfo();
}
const WebGLVertexArrayObjectOES::VertexAttribState& state = m_boundVertexArrayObject->getVertexAttribState(index);
@@ -2857,24 +2846,24 @@ WebGLGetInfo WebGLRenderingContext::getVertexAttrib(GC3Duint index, GC3Denum pna
return WebGLGetInfo(state.divisor);
switch (pname) {
- case GraphicsContext3D::VERTEX_ATTRIB_ARRAY_BUFFER_BINDING:
+ case GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING:
if (!state.bufferBinding || !state.bufferBinding->object())
return WebGLGetInfo();
return WebGLGetInfo(PassRefPtr<WebGLBuffer>(state.bufferBinding));
- case GraphicsContext3D::VERTEX_ATTRIB_ARRAY_ENABLED:
+ case GL_VERTEX_ATTRIB_ARRAY_ENABLED:
return WebGLGetInfo(state.enabled);
- case GraphicsContext3D::VERTEX_ATTRIB_ARRAY_NORMALIZED:
+ case GL_VERTEX_ATTRIB_ARRAY_NORMALIZED:
return WebGLGetInfo(state.normalized);
- case GraphicsContext3D::VERTEX_ATTRIB_ARRAY_SIZE:
+ case GL_VERTEX_ATTRIB_ARRAY_SIZE:
return WebGLGetInfo(state.size);
- case GraphicsContext3D::VERTEX_ATTRIB_ARRAY_STRIDE:
+ case GL_VERTEX_ATTRIB_ARRAY_STRIDE:
return WebGLGetInfo(state.originalStride);
- case GraphicsContext3D::VERTEX_ATTRIB_ARRAY_TYPE:
+ case GL_VERTEX_ATTRIB_ARRAY_TYPE:
return WebGLGetInfo(state.type);
- case GraphicsContext3D::CURRENT_VERTEX_ATTRIB:
+ case GL_CURRENT_VERTEX_ATTRIB:
return WebGLGetInfo(Float32Array::create(m_vertexAttribValue[index].value, 4));
default:
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "getVertexAttrib", "invalid parameter name");
+ synthesizeGLError(GL_INVALID_ENUM, "getVertexAttrib", "invalid parameter name");
return WebGLGetInfo();
}
}
@@ -2883,8 +2872,8 @@ long long WebGLRenderingContext::getVertexAttribOffset(GC3Duint index, GC3Denum
{
if (isContextLost())
return 0;
- if (pname != GraphicsContext3D::VERTEX_ATTRIB_ARRAY_POINTER) {
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "getVertexAttribOffset", "invalid parameter name");
+ if (pname != GL_VERTEX_ATTRIB_ARRAY_POINTER) {
+ synthesizeGLError(GL_INVALID_ENUM, "getVertexAttribOffset", "invalid parameter name");
return 0;
}
GC3Dsizeiptr result = m_context->getVertexAttribOffset(index, pname);
@@ -2897,7 +2886,7 @@ void WebGLRenderingContext::hint(GC3Denum target, GC3Denum mode)
return;
bool isValid = false;
switch (target) {
- case GraphicsContext3D::GENERATE_MIPMAP_HINT:
+ case GL_GENERATE_MIPMAP_HINT:
isValid = true;
break;
case Extensions3D::FRAGMENT_SHADER_DERIVATIVE_HINT_OES: // OES_standard_derivatives
@@ -2906,7 +2895,7 @@ void WebGLRenderingContext::hint(GC3Denum target, GC3Denum mode)
break;
}
if (!isValid) {
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "hint", "invalid target");
+ synthesizeGLError(GL_INVALID_ENUM, "hint", "invalid target");
return;
}
m_context->hint(target, mode);
@@ -2932,7 +2921,7 @@ GC3Dboolean WebGLRenderingContext::isEnabled(GC3Denum cap)
{
if (isContextLost() || !validateCapability("isEnabled", cap))
return 0;
- if (cap == GraphicsContext3D::STENCIL_TEST)
+ if (cap == GL_STENCIL_TEST)
return m_stencilEnabled;
return m_context->isEnabled(cap);
}
@@ -3007,35 +2996,35 @@ void WebGLRenderingContext::pixelStorei(GC3Denum pname, GC3Dint param)
if (isContextLost())
return;
switch (pname) {
- case GraphicsContext3D::UNPACK_FLIP_Y_WEBGL:
+ case GC3D_UNPACK_FLIP_Y_WEBGL:
m_unpackFlipY = param;
break;
- case GraphicsContext3D::UNPACK_PREMULTIPLY_ALPHA_WEBGL:
+ case GC3D_UNPACK_PREMULTIPLY_ALPHA_WEBGL:
m_unpackPremultiplyAlpha = param;
break;
- case GraphicsContext3D::UNPACK_COLORSPACE_CONVERSION_WEBGL:
- if (param == GraphicsContext3D::BROWSER_DEFAULT_WEBGL || param == GraphicsContext3D::NONE)
+ case GC3D_UNPACK_COLORSPACE_CONVERSION_WEBGL:
+ if (static_cast<GC3Denum>(param) == GC3D_BROWSER_DEFAULT_WEBGL || param == GL_NONE)
m_unpackColorspaceConversion = static_cast<GC3Denum>(param);
else {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "pixelStorei", "invalid parameter for UNPACK_COLORSPACE_CONVERSION_WEBGL");
+ synthesizeGLError(GL_INVALID_VALUE, "pixelStorei", "invalid parameter for UNPACK_COLORSPACE_CONVERSION_WEBGL");
return;
}
break;
- case GraphicsContext3D::PACK_ALIGNMENT:
- case GraphicsContext3D::UNPACK_ALIGNMENT:
+ case GL_PACK_ALIGNMENT:
+ case GL_UNPACK_ALIGNMENT:
if (param == 1 || param == 2 || param == 4 || param == 8) {
- if (pname == GraphicsContext3D::PACK_ALIGNMENT)
+ if (pname == GL_PACK_ALIGNMENT)
m_packAlignment = param;
- else // GraphicsContext3D::UNPACK_ALIGNMENT:
+ else // GL_UNPACK_ALIGNMENT:
m_unpackAlignment = param;
m_context->pixelStorei(pname, param);
} else {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "pixelStorei", "invalid parameter for alignment");
+ synthesizeGLError(GL_INVALID_VALUE, "pixelStorei", "invalid parameter for alignment");
return;
}
break;
default:
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "pixelStorei", "invalid parameter name");
+ synthesizeGLError(GL_INVALID_ENUM, "pixelStorei", "invalid parameter name");
return;
}
}
@@ -3056,52 +3045,52 @@ void WebGLRenderingContext::readPixels(GC3Dint x, GC3Dint y, GC3Dsizei width, GC
ASSERT(canvas()->originClean());
// Validate input parameters.
if (!pixels) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "readPixels", "no destination ArrayBufferView");
+ synthesizeGLError(GL_INVALID_VALUE, "readPixels", "no destination ArrayBufferView");
return;
}
switch (format) {
- case GraphicsContext3D::ALPHA:
- case GraphicsContext3D::RGB:
- case GraphicsContext3D::RGBA:
+ case GL_ALPHA:
+ case GL_RGB:
+ case GL_RGBA:
break;
default:
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "readPixels", "invalid format");
+ synthesizeGLError(GL_INVALID_ENUM, "readPixels", "invalid format");
return;
}
switch (type) {
- case GraphicsContext3D::UNSIGNED_BYTE:
- case GraphicsContext3D::UNSIGNED_SHORT_5_6_5:
- case GraphicsContext3D::UNSIGNED_SHORT_4_4_4_4:
- case GraphicsContext3D::UNSIGNED_SHORT_5_5_5_1:
+ case GL_UNSIGNED_BYTE:
+ case GL_UNSIGNED_SHORT_5_6_5:
+ case GL_UNSIGNED_SHORT_4_4_4_4:
+ case GL_UNSIGNED_SHORT_5_5_5_1:
break;
default:
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "readPixels", "invalid type");
+ synthesizeGLError(GL_INVALID_ENUM, "readPixels", "invalid type");
return;
}
- if (format != GraphicsContext3D::RGBA || type != GraphicsContext3D::UNSIGNED_BYTE) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "readPixels", "format not RGBA or type not UNSIGNED_BYTE");
+ if (format != GL_RGBA || type != GL_UNSIGNED_BYTE) {
+ synthesizeGLError(GL_INVALID_OPERATION, "readPixels", "format not RGBA or type not UNSIGNED_BYTE");
return;
}
// Validate array type against pixel type.
if (pixels->getType() != ArrayBufferView::TypeUint8) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "readPixels", "ArrayBufferView not Uint8Array");
+ synthesizeGLError(GL_INVALID_OPERATION, "readPixels", "ArrayBufferView not Uint8Array");
return;
}
const char* reason = "framebuffer incomplete";
if (m_framebufferBinding && !m_framebufferBinding->onAccess(graphicsContext3D(), &reason)) {
- synthesizeGLError(GraphicsContext3D::INVALID_FRAMEBUFFER_OPERATION, "readPixels", reason);
+ synthesizeGLError(GL_INVALID_FRAMEBUFFER_OPERATION, "readPixels", reason);
return;
}
// Calculate array size, taking into consideration of PACK_ALIGNMENT.
unsigned int totalBytesRequired = 0;
unsigned int padding = 0;
GC3Denum error = m_context->computeImageSizeInBytes(format, type, width, height, m_packAlignment, &totalBytesRequired, &padding);
- if (error != GraphicsContext3D::NO_ERROR) {
+ if (error != GL_NO_ERROR) {
synthesizeGLError(error, "readPixels", "invalid dimensions");
return;
}
if (pixels->byteLength() < totalBytesRequired) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "readPixels", "ArrayBufferView not large enough for dimensions");
+ synthesizeGLError(GL_INVALID_OPERATION, "readPixels", "ArrayBufferView not large enough for dimensions");
return;
}
@@ -3133,48 +3122,48 @@ void WebGLRenderingContext::renderbufferStorage(GC3Denum target, GC3Denum intern
{
if (isContextLost())
return;
- if (target != GraphicsContext3D::RENDERBUFFER) {
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "renderbufferStorage", "invalid target");
+ if (target != GL_RENDERBUFFER) {
+ synthesizeGLError(GL_INVALID_ENUM, "renderbufferStorage", "invalid target");
return;
}
if (!m_renderbufferBinding || !m_renderbufferBinding->object()) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "renderbufferStorage", "no bound renderbuffer");
+ synthesizeGLError(GL_INVALID_OPERATION, "renderbufferStorage", "no bound renderbuffer");
return;
}
if (!validateSize("renderbufferStorage", width, height))
return;
switch (internalformat) {
- case GraphicsContext3D::DEPTH_COMPONENT16:
- case GraphicsContext3D::RGBA4:
- case GraphicsContext3D::RGB5_A1:
- case GraphicsContext3D::RGB565:
- case GraphicsContext3D::STENCIL_INDEX8:
+ case GL_DEPTH_COMPONENT16:
+ case GL_RGBA4:
+ case GL_RGB5_A1:
+ case GL_RGB565:
+ case GL_STENCIL_INDEX8:
m_context->renderbufferStorage(target, internalformat, width, height);
m_renderbufferBinding->setInternalFormat(internalformat);
m_renderbufferBinding->setSize(width, height);
m_renderbufferBinding->deleteEmulatedStencilBuffer(m_context.get());
break;
- case GraphicsContext3D::DEPTH_STENCIL:
+ case GL_DEPTH_STENCIL_OES:
if (isDepthStencilSupported()) {
m_context->renderbufferStorage(target, Extensions3D::DEPTH24_STENCIL8, width, height);
} else {
WebGLRenderbuffer* emulatedStencilBuffer = ensureEmulatedStencilBuffer(target, m_renderbufferBinding.get());
if (!emulatedStencilBuffer) {
- synthesizeGLError(GraphicsContext3D::OUT_OF_MEMORY, "renderbufferStorage", "out of memory");
+ synthesizeGLError(GL_OUT_OF_MEMORY, "renderbufferStorage", "out of memory");
return;
}
- m_context->renderbufferStorage(target, GraphicsContext3D::DEPTH_COMPONENT16, width, height);
+ m_context->renderbufferStorage(target, GL_DEPTH_COMPONENT16, width, height);
m_context->bindRenderbuffer(target, objectOrZero(emulatedStencilBuffer));
- m_context->renderbufferStorage(target, GraphicsContext3D::STENCIL_INDEX8, width, height);
+ m_context->renderbufferStorage(target, GL_STENCIL_INDEX8, width, height);
m_context->bindRenderbuffer(target, objectOrZero(m_renderbufferBinding.get()));
emulatedStencilBuffer->setSize(width, height);
- emulatedStencilBuffer->setInternalFormat(GraphicsContext3D::STENCIL_INDEX8);
+ emulatedStencilBuffer->setInternalFormat(GL_STENCIL_INDEX8);
}
m_renderbufferBinding->setSize(width, height);
m_renderbufferBinding->setInternalFormat(internalformat);
break;
default:
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "renderbufferStorage", "invalid internalformat");
+ synthesizeGLError(GL_INVALID_ENUM, "renderbufferStorage", "invalid internalformat");
return;
}
applyStencilTest();
@@ -3227,22 +3216,22 @@ void WebGLRenderingContext::stencilFuncSeparate(GC3Denum face, GC3Denum func, GC
if (!validateStencilOrDepthFunc("stencilFuncSeparate", func))
return;
switch (face) {
- case GraphicsContext3D::FRONT_AND_BACK:
+ case GL_FRONT_AND_BACK:
m_stencilFuncRef = ref;
m_stencilFuncRefBack = ref;
m_stencilFuncMask = mask;
m_stencilFuncMaskBack = mask;
break;
- case GraphicsContext3D::FRONT:
+ case GL_FRONT:
m_stencilFuncRef = ref;
m_stencilFuncMask = mask;
break;
- case GraphicsContext3D::BACK:
+ case GL_BACK:
m_stencilFuncRefBack = ref;
m_stencilFuncMaskBack = mask;
break;
default:
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "stencilFuncSeparate", "invalid face");
+ synthesizeGLError(GL_INVALID_ENUM, "stencilFuncSeparate", "invalid face");
return;
}
m_context->stencilFuncSeparate(face, func, ref, mask);
@@ -3262,18 +3251,18 @@ void WebGLRenderingContext::stencilMaskSeparate(GC3Denum face, GC3Duint mask)
if (isContextLost())
return;
switch (face) {
- case GraphicsContext3D::FRONT_AND_BACK:
+ case GL_FRONT_AND_BACK:
m_stencilMask = mask;
m_stencilMaskBack = mask;
break;
- case GraphicsContext3D::FRONT:
+ case GL_FRONT:
m_stencilMask = mask;
break;
- case GraphicsContext3D::BACK:
+ case GL_BACK:
m_stencilMaskBack = mask;
break;
default:
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "stencilMaskSeparate", "invalid face");
+ synthesizeGLError(GL_INVALID_ENUM, "stencilMaskSeparate", "invalid face");
return;
}
m_context->stencilMaskSeparate(face, mask);
@@ -3293,7 +3282,7 @@ void WebGLRenderingContext::stencilOpSeparate(GC3Denum face, GC3Denum fail, GC3D
m_context->stencilOpSeparate(face, fail, zfail, zpass);
}
-void WebGLRenderingContext::texImage2DBase(GC3Denum target, GC3Dint level, GC3Denum internalformat, GC3Dsizei width, GC3Dsizei height, GC3Dint border, GC3Denum format, GC3Denum type, const void* pixels, ExceptionState& es)
+void WebGLRenderingContext::texImage2DBase(GC3Denum target, GC3Dint level, GC3Denum internalformat, GC3Dsizei width, GC3Dsizei height, GC3Dint border, GC3Denum format, GC3Denum type, const void* pixels, ExceptionState& exceptionState)
{
// All calling functions check isContextLost, so a duplicate check is not needed here.
// FIXME: Handle errors.
@@ -3307,13 +3296,13 @@ void WebGLRenderingContext::texImage2DBase(GC3Denum target, GC3Dint level, GC3De
tex->setLevelInfo(target, level, internalformat, width, height, type);
}
-void WebGLRenderingContext::texImage2DImpl(GC3Denum target, GC3Dint level, GC3Denum internalformat, GC3Denum format, GC3Denum type, Image* image, GraphicsContext3D::ImageHtmlDomSource domSource, bool flipY, bool premultiplyAlpha, ExceptionState& es)
+void WebGLRenderingContext::texImage2DImpl(GC3Denum target, GC3Dint level, GC3Denum internalformat, GC3Denum format, GC3Denum type, Image* image, GraphicsContext3D::ImageHtmlDomSource domSource, bool flipY, bool premultiplyAlpha, ExceptionState& exceptionState)
{
// All calling functions check isContextLost, so a duplicate check is not needed here.
Vector<uint8_t> data;
- GraphicsContext3D::ImageExtractor imageExtractor(image, domSource, premultiplyAlpha, m_unpackColorspaceConversion == GraphicsContext3D::NONE);
+ GraphicsContext3D::ImageExtractor imageExtractor(image, domSource, premultiplyAlpha, m_unpackColorspaceConversion == GL_NONE);
if (!imageExtractor.extractSucceeded()) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "texImage2D", "bad image data");
+ synthesizeGLError(GL_INVALID_VALUE, "texImage2D", "bad image data");
return;
}
GraphicsContext3D::DataFormat sourceDataFormat = imageExtractor.imageSourceFormat();
@@ -3321,20 +3310,20 @@ void WebGLRenderingContext::texImage2DImpl(GC3Denum target, GC3Dint level, GC3De
const void* imagePixelData = imageExtractor.imagePixelData();
bool needConversion = true;
- if (type == GraphicsContext3D::UNSIGNED_BYTE && sourceDataFormat == GraphicsContext3D::DataFormatRGBA8 && format == GraphicsContext3D::RGBA && alphaOp == GraphicsContext3D::AlphaDoNothing && !flipY)
+ if (type == GL_UNSIGNED_BYTE && sourceDataFormat == GraphicsContext3D::DataFormatRGBA8 && format == GL_RGBA && alphaOp == GraphicsContext3D::AlphaDoNothing && !flipY)
needConversion = false;
else {
if (!m_context->packImageData(image, imagePixelData, format, type, flipY, alphaOp, sourceDataFormat, imageExtractor.imageWidth(), imageExtractor.imageHeight(), imageExtractor.imageSourceUnpackAlignment(), data)) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "texImage2D", "packImage error");
+ synthesizeGLError(GL_INVALID_VALUE, "texImage2D", "packImage error");
return;
}
}
if (m_unpackAlignment != 1)
- m_context->pixelStorei(GraphicsContext3D::UNPACK_ALIGNMENT, 1);
- texImage2DBase(target, level, internalformat, image->width(), image->height(), 0, format, type, needConversion ? data.data() : imagePixelData, es);
+ m_context->pixelStorei(GL_UNPACK_ALIGNMENT, 1);
+ texImage2DBase(target, level, internalformat, image->width(), image->height(), 0, format, type, needConversion ? data.data() : imagePixelData, exceptionState);
if (m_unpackAlignment != 1)
- m_context->pixelStorei(GraphicsContext3D::UNPACK_ALIGNMENT, m_unpackAlignment);
+ m_context->pixelStorei(GL_UNPACK_ALIGNMENT, m_unpackAlignment);
}
bool WebGLRenderingContext::validateTexFunc(const char* functionName, TexFuncValidationFunctionType functionType, TexFuncValidationSourceType sourceType, GC3Denum target, GC3Dint level, GC3Denum internalformat, GC3Dsizei width, GC3Dsizei height, GC3Dint border, GC3Denum format, GC3Denum type, GC3Dint xoffset, GC3Dint yoffset)
@@ -3348,7 +3337,7 @@ bool WebGLRenderingContext::validateTexFunc(const char* functionName, TexFuncVal
if (functionType == NotTexSubImage2D) {
if (level && WebGLTexture::isNPOT(width, height)) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "level > 0 not power of 2");
+ synthesizeGLError(GL_INVALID_VALUE, functionName, "level > 0 not power of 2");
return false;
}
// For SourceArrayBufferView, function validateTexFuncData() would handle whether to validate the SettableTexFormat
@@ -3364,15 +3353,15 @@ bool WebGLRenderingContext::validateTexFunc(const char* functionName, TexFuncVal
return false;
// Before checking if it is in the range, check if overflow happens first.
if (xoffset + width < 0 || yoffset + height < 0) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "bad dimensions");
+ synthesizeGLError(GL_INVALID_VALUE, functionName, "bad dimensions");
return false;
}
if (xoffset + width > texture->getWidth(target, level) || yoffset + height > texture->getHeight(target, level)) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "dimensions out of range");
+ synthesizeGLError(GL_INVALID_VALUE, functionName, "dimensions out of range");
return false;
}
if (texture->getInternalFormat(target, level) != format || texture->getType(target, level) != type) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, functionName, "type and format do not match texture");
+ synthesizeGLError(GL_INVALID_OPERATION, functionName, "type and format do not match texture");
return false;
}
}
@@ -3380,9 +3369,24 @@ bool WebGLRenderingContext::validateTexFunc(const char* functionName, TexFuncVal
return true;
}
+PassRefPtr<Image> WebGLRenderingContext::drawImageIntoBuffer(Image* image, int width, int height)
+{
+ IntSize size(width, height);
+ ImageBuffer* buf = m_generatedImageCache.imageBuffer(size);
+ if (!buf) {
+ synthesizeGLError(GL_OUT_OF_MEMORY, "texImage2D", "out of memory");
+ return 0;
+ }
+
+ IntRect srcRect(IntPoint(), image->size());
+ IntRect destRect(0, 0, size.width(), size.height());
+ buf->context()->drawImage(image, destRect, srcRect);
+ return buf->copyImage(ImageBuffer::fastCopyImageMode());
+}
+
void WebGLRenderingContext::texImage2D(GC3Denum target, GC3Dint level, GC3Denum internalformat,
GC3Dsizei width, GC3Dsizei height, GC3Dint border,
- GC3Denum format, GC3Denum type, ArrayBufferView* pixels, ExceptionState& es)
+ GC3Denum format, GC3Denum type, ArrayBufferView* pixels, ExceptionState& exceptionState)
{
if (isContextLost() || !validateTexFuncData("texImage2D", level, width, height, format, type, pixels, NullAllowed)
|| !validateTexFunc("texImage2D", NotTexSubImage2D, SourceArrayBufferView, target, level, internalformat, width, height, border, format, type, 0, 0))
@@ -3401,14 +3405,14 @@ void WebGLRenderingContext::texImage2D(GC3Denum target, GC3Dint level, GC3Denum
changeUnpackAlignment = true;
}
if (changeUnpackAlignment)
- m_context->pixelStorei(GraphicsContext3D::UNPACK_ALIGNMENT, 1);
- texImage2DBase(target, level, internalformat, width, height, border, format, type, data, es);
+ m_context->pixelStorei(GL_UNPACK_ALIGNMENT, 1);
+ texImage2DBase(target, level, internalformat, width, height, border, format, type, data, exceptionState);
if (changeUnpackAlignment)
- m_context->pixelStorei(GraphicsContext3D::UNPACK_ALIGNMENT, m_unpackAlignment);
+ m_context->pixelStorei(GL_UNPACK_ALIGNMENT, m_unpackAlignment);
}
void WebGLRenderingContext::texImage2D(GC3Denum target, GC3Dint level, GC3Denum internalformat,
- GC3Denum format, GC3Denum type, ImageData* pixels, ExceptionState& es)
+ GC3Denum format, GC3Denum type, ImageData* pixels, ExceptionState& exceptionState)
{
if (isContextLost() || !pixels || !validateTexFunc("texImage2D", NotTexSubImage2D, SourceImageData, target, level, internalformat, pixels->width(), pixels->height(), 0, format, type, 0, 0))
return;
@@ -3416,63 +3420,77 @@ void WebGLRenderingContext::texImage2D(GC3Denum target, GC3Dint level, GC3Denum
bool needConversion = true;
// The data from ImageData is always of format RGBA8.
// No conversion is needed if destination format is RGBA and type is USIGNED_BYTE and no Flip or Premultiply operation is required.
- if (!m_unpackFlipY && !m_unpackPremultiplyAlpha && format == GraphicsContext3D::RGBA && type == GraphicsContext3D::UNSIGNED_BYTE)
+ if (!m_unpackFlipY && !m_unpackPremultiplyAlpha && format == GL_RGBA && type == GL_UNSIGNED_BYTE)
needConversion = false;
else {
- if (!m_context->extractImageData(pixels, format, type, m_unpackFlipY, m_unpackPremultiplyAlpha, data)) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "texImage2D", "bad image data");
+ if (!m_context->extractImageData(pixels->data()->data(), pixels->size(), format, type, m_unpackFlipY, m_unpackPremultiplyAlpha, data)) {
+ synthesizeGLError(GL_INVALID_VALUE, "texImage2D", "bad image data");
return;
}
}
if (m_unpackAlignment != 1)
- m_context->pixelStorei(GraphicsContext3D::UNPACK_ALIGNMENT, 1);
- texImage2DBase(target, level, internalformat, pixels->width(), pixels->height(), 0, format, type, needConversion ? data.data() : pixels->data()->data(), es);
+ m_context->pixelStorei(GL_UNPACK_ALIGNMENT, 1);
+ texImage2DBase(target, level, internalformat, pixels->width(), pixels->height(), 0, format, type, needConversion ? data.data() : pixels->data()->data(), exceptionState);
if (m_unpackAlignment != 1)
- m_context->pixelStorei(GraphicsContext3D::UNPACK_ALIGNMENT, m_unpackAlignment);
+ m_context->pixelStorei(GL_UNPACK_ALIGNMENT, m_unpackAlignment);
}
void WebGLRenderingContext::texImage2D(GC3Denum target, GC3Dint level, GC3Denum internalformat,
- GC3Denum format, GC3Denum type, HTMLImageElement* image, ExceptionState& es)
+ GC3Denum format, GC3Denum type, HTMLImageElement* image, ExceptionState& exceptionState)
{
- if (isContextLost() || !validateHTMLImageElement("texImage2D", image, es))
+ if (isContextLost() || !validateHTMLImageElement("texImage2D", image, exceptionState))
return;
- Image* imageForRender = image->cachedImage()->imageForRenderer(image->renderer());
+
+ RefPtr<Image> imageForRender = image->cachedImage()->imageForRenderer(image->renderer());
+ if (imageForRender->isSVGImage())
+ imageForRender = drawImageIntoBuffer(imageForRender.get(), image->width(), image->height());
+
if (!imageForRender || !validateTexFunc("texImage2D", NotTexSubImage2D, SourceHTMLImageElement, target, level, internalformat, imageForRender->width(), imageForRender->height(), 0, format, type, 0, 0))
return;
- texImage2DImpl(target, level, internalformat, format, type, imageForRender, GraphicsContext3D::HtmlDomImage, m_unpackFlipY, m_unpackPremultiplyAlpha, es);
+ texImage2DImpl(target, level, internalformat, format, type, imageForRender.get(), GraphicsContext3D::HtmlDomImage, m_unpackFlipY, m_unpackPremultiplyAlpha, exceptionState);
}
void WebGLRenderingContext::texImage2D(GC3Denum target, GC3Dint level, GC3Denum internalformat,
- GC3Denum format, GC3Denum type, HTMLCanvasElement* canvas, ExceptionState& es)
+ GC3Denum format, GC3Denum type, HTMLCanvasElement* canvas, ExceptionState& exceptionState)
{
- if (isContextLost() || !validateHTMLCanvasElement("texImage2D", canvas, es) || !validateTexFunc("texImage2D", NotTexSubImage2D, SourceHTMLCanvasElement, target, level, internalformat, canvas->width(), canvas->height(), 0, format, type, 0, 0))
+ if (isContextLost() || !validateHTMLCanvasElement("texImage2D", canvas, exceptionState) || !validateTexFunc("texImage2D", NotTexSubImage2D, SourceHTMLCanvasElement, target, level, internalformat, canvas->width(), canvas->height(), 0, format, type, 0, 0))
return;
WebGLTexture* texture = validateTextureBinding("texImage2D", target, true);
// If possible, copy from the canvas element directly to the texture
// via the GPU, without a read-back to system memory.
- if (GraphicsContext3D::TEXTURE_2D == target && texture) {
- ImageBuffer* buffer = canvas->buffer();
- if (buffer && buffer->copyToPlatformTexture(*m_context.get(), texture->object(), internalformat, type, level, m_unpackPremultiplyAlpha, m_unpackFlipY)) {
- texture->setLevelInfo(target, level, internalformat, canvas->width(), canvas->height(), type);
- return;
+ if (GL_TEXTURE_2D == target && texture) {
+ if (!canvas->is3D()) {
+ ImageBuffer* buffer = canvas->buffer();
+ if (buffer && buffer->copyToPlatformTexture(*m_context.get(), texture->object(), internalformat, type,
+ level, m_unpackPremultiplyAlpha, m_unpackFlipY)) {
+ texture->setLevelInfo(target, level, internalformat, canvas->width(), canvas->height(), type);
+ return;
+ }
+ } else {
+ WebGLRenderingContext* gl = toWebGLRenderingContext(canvas->renderingContext());
+ if (gl && gl->m_drawingBuffer->copyToPlatformTexture(*m_context.get(), texture->object(), internalformat, type,
+ level, m_unpackPremultiplyAlpha, m_unpackFlipY)) {
+ texture->setLevelInfo(target, level, internalformat, canvas->width(), canvas->height(), type);
+ return;
+ }
}
}
RefPtr<ImageData> imageData = canvas->getImageData();
if (imageData)
- texImage2D(target, level, internalformat, format, type, imageData.get(), es);
+ texImage2D(target, level, internalformat, format, type, imageData.get(), exceptionState);
else
- texImage2DImpl(target, level, internalformat, format, type, canvas->copiedImage(), GraphicsContext3D::HtmlDomCanvas, m_unpackFlipY, m_unpackPremultiplyAlpha, es);
+ texImage2DImpl(target, level, internalformat, format, type, canvas->copiedImage(), GraphicsContext3D::HtmlDomCanvas, m_unpackFlipY, m_unpackPremultiplyAlpha, exceptionState);
}
PassRefPtr<Image> WebGLRenderingContext::videoFrameToImage(HTMLVideoElement* video, BackingStoreCopy backingStoreCopy)
{
IntSize size(video->videoWidth(), video->videoHeight());
- ImageBuffer* buf = m_videoCache.imageBuffer(size);
+ ImageBuffer* buf = m_generatedImageCache.imageBuffer(size);
if (!buf) {
- synthesizeGLError(GraphicsContext3D::OUT_OF_MEMORY, "texImage2D", "out of memory");
+ synthesizeGLError(GL_OUT_OF_MEMORY, "texImage2D", "out of memory");
return 0;
}
IntRect destRect(0, 0, size.width(), size.height());
@@ -3482,16 +3500,16 @@ PassRefPtr<Image> WebGLRenderingContext::videoFrameToImage(HTMLVideoElement* vid
}
void WebGLRenderingContext::texImage2D(GC3Denum target, GC3Dint level, GC3Denum internalformat,
- GC3Denum format, GC3Denum type, HTMLVideoElement* video, ExceptionState& es)
+ GC3Denum format, GC3Denum type, HTMLVideoElement* video, ExceptionState& exceptionState)
{
- if (isContextLost() || !validateHTMLVideoElement("texImage2D", video, es)
+ if (isContextLost() || !validateHTMLVideoElement("texImage2D", video, exceptionState)
|| !validateTexFunc("texImage2D", NotTexSubImage2D, SourceHTMLVideoElement, target, level, internalformat, video->videoWidth(), video->videoHeight(), 0, format, type, 0, 0))
return;
// Go through the fast path doing a GPU-GPU textures copy without a readback to system memory if possible.
// Otherwise, it will fall back to the normal SW path.
WebGLTexture* texture = validateTextureBinding("texImage2D", target, true);
- if (GraphicsContext3D::TEXTURE_2D == target && texture) {
+ if (GL_TEXTURE_2D == target && texture) {
if (video->copyVideoTextureToPlatformTexture(m_context.get(), texture->object(), level, type, internalformat, m_unpackPremultiplyAlpha, m_unpackFlipY)) {
texture->setLevelInfo(target, level, internalformat, video->videoWidth(), video->videoHeight(), type);
return;
@@ -3502,7 +3520,7 @@ void WebGLRenderingContext::texImage2D(GC3Denum target, GC3Dint level, GC3Denum
RefPtr<Image> image = videoFrameToImage(video, ImageBuffer::fastCopyImageMode());
if (!image)
return;
- texImage2DImpl(target, level, internalformat, format, type, image.get(), GraphicsContext3D::HtmlDomVideo, m_unpackFlipY, m_unpackPremultiplyAlpha, es);
+ texImage2DImpl(target, level, internalformat, format, type, image.get(), GraphicsContext3D::HtmlDomVideo, m_unpackFlipY, m_unpackPremultiplyAlpha, exceptionState);
}
void WebGLRenderingContext::texParameter(GC3Denum target, GC3Denum pname, GC3Dfloat paramf, GC3Dint parami, bool isFloat)
@@ -3513,25 +3531,25 @@ void WebGLRenderingContext::texParameter(GC3Denum target, GC3Denum pname, GC3Dfl
if (!tex)
return;
switch (pname) {
- case GraphicsContext3D::TEXTURE_MIN_FILTER:
- case GraphicsContext3D::TEXTURE_MAG_FILTER:
+ case GL_TEXTURE_MIN_FILTER:
+ case GL_TEXTURE_MAG_FILTER:
break;
- case GraphicsContext3D::TEXTURE_WRAP_S:
- case GraphicsContext3D::TEXTURE_WRAP_T:
- if ((isFloat && paramf != GraphicsContext3D::CLAMP_TO_EDGE && paramf != GraphicsContext3D::MIRRORED_REPEAT && paramf != GraphicsContext3D::REPEAT)
- || (!isFloat && parami != GraphicsContext3D::CLAMP_TO_EDGE && parami != GraphicsContext3D::MIRRORED_REPEAT && parami != GraphicsContext3D::REPEAT)) {
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "texParameter", "invalid parameter");
+ case GL_TEXTURE_WRAP_S:
+ case GL_TEXTURE_WRAP_T:
+ if ((isFloat && paramf != GL_CLAMP_TO_EDGE && paramf != GL_MIRRORED_REPEAT && paramf != GL_REPEAT)
+ || (!isFloat && parami != GL_CLAMP_TO_EDGE && parami != GL_MIRRORED_REPEAT && parami != GL_REPEAT)) {
+ synthesizeGLError(GL_INVALID_ENUM, "texParameter", "invalid parameter");
return;
}
break;
case Extensions3D::TEXTURE_MAX_ANISOTROPY_EXT: // EXT_texture_filter_anisotropic
if (!m_extTextureFilterAnisotropic) {
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "texParameter", "invalid parameter, EXT_texture_filter_anisotropic not enabled");
+ synthesizeGLError(GL_INVALID_ENUM, "texParameter", "invalid parameter, EXT_texture_filter_anisotropic not enabled");
return;
}
break;
default:
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "texParameter", "invalid parameter name");
+ synthesizeGLError(GL_INVALID_ENUM, "texParameter", "invalid parameter name");
return;
}
if (isFloat) {
@@ -3553,7 +3571,7 @@ void WebGLRenderingContext::texParameteri(GC3Denum target, GC3Denum pname, GC3Di
texParameter(target, pname, 0, param, false);
}
-void WebGLRenderingContext::texSubImage2DBase(GC3Denum target, GC3Dint level, GC3Dint xoffset, GC3Dint yoffset, GC3Dsizei width, GC3Dsizei height, GC3Denum format, GC3Denum type, const void* pixels, ExceptionState& es)
+void WebGLRenderingContext::texSubImage2DBase(GC3Denum target, GC3Dint level, GC3Dint xoffset, GC3Dint yoffset, GC3Dsizei width, GC3Dsizei height, GC3Denum format, GC3Denum type, const void* pixels, ExceptionState& exceptionState)
{
// FIXME: Handle errors.
ASSERT(!isContextLost());
@@ -3574,13 +3592,13 @@ void WebGLRenderingContext::texSubImage2DBase(GC3Denum target, GC3Dint level, GC
m_context->texSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels);
}
-void WebGLRenderingContext::texSubImage2DImpl(GC3Denum target, GC3Dint level, GC3Dint xoffset, GC3Dint yoffset, GC3Denum format, GC3Denum type, Image* image, GraphicsContext3D::ImageHtmlDomSource domSource, bool flipY, bool premultiplyAlpha, ExceptionState& es)
+void WebGLRenderingContext::texSubImage2DImpl(GC3Denum target, GC3Dint level, GC3Dint xoffset, GC3Dint yoffset, GC3Denum format, GC3Denum type, Image* image, GraphicsContext3D::ImageHtmlDomSource domSource, bool flipY, bool premultiplyAlpha, ExceptionState& exceptionState)
{
// All calling functions check isContextLost, so a duplicate check is not needed here.
Vector<uint8_t> data;
- GraphicsContext3D::ImageExtractor imageExtractor(image, domSource, premultiplyAlpha, m_unpackColorspaceConversion == GraphicsContext3D::NONE);
+ GraphicsContext3D::ImageExtractor imageExtractor(image, domSource, premultiplyAlpha, m_unpackColorspaceConversion == GL_NONE);
if (!imageExtractor.extractSucceeded()) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "texSubImage2D", "bad image");
+ synthesizeGLError(GL_INVALID_VALUE, "texSubImage2D", "bad image");
return;
}
GraphicsContext3D::DataFormat sourceDataFormat = imageExtractor.imageSourceFormat();
@@ -3588,25 +3606,25 @@ void WebGLRenderingContext::texSubImage2DImpl(GC3Denum target, GC3Dint level, GC
const void* imagePixelData = imageExtractor.imagePixelData();
bool needConversion = true;
- if (type == GraphicsContext3D::UNSIGNED_BYTE && sourceDataFormat == GraphicsContext3D::DataFormatRGBA8 && format == GraphicsContext3D::RGBA && alphaOp == GraphicsContext3D::AlphaDoNothing && !flipY)
+ if (type == GL_UNSIGNED_BYTE && sourceDataFormat == GraphicsContext3D::DataFormatRGBA8 && format == GL_RGBA && alphaOp == GraphicsContext3D::AlphaDoNothing && !flipY)
needConversion = false;
else {
if (!m_context->packImageData(image, imagePixelData, format, type, flipY, alphaOp, sourceDataFormat, imageExtractor.imageWidth(), imageExtractor.imageHeight(), imageExtractor.imageSourceUnpackAlignment(), data)) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "texImage2D", "bad image data");
+ synthesizeGLError(GL_INVALID_VALUE, "texImage2D", "bad image data");
return;
}
}
if (m_unpackAlignment != 1)
- m_context->pixelStorei(GraphicsContext3D::UNPACK_ALIGNMENT, 1);
- texSubImage2DBase(target, level, xoffset, yoffset, image->width(), image->height(), format, type, needConversion ? data.data() : imagePixelData, es);
+ m_context->pixelStorei(GL_UNPACK_ALIGNMENT, 1);
+ texSubImage2DBase(target, level, xoffset, yoffset, image->width(), image->height(), format, type, needConversion ? data.data() : imagePixelData, exceptionState);
if (m_unpackAlignment != 1)
- m_context->pixelStorei(GraphicsContext3D::UNPACK_ALIGNMENT, m_unpackAlignment);
+ m_context->pixelStorei(GL_UNPACK_ALIGNMENT, m_unpackAlignment);
}
void WebGLRenderingContext::texSubImage2D(GC3Denum target, GC3Dint level, GC3Dint xoffset, GC3Dint yoffset,
GC3Dsizei width, GC3Dsizei height,
- GC3Denum format, GC3Denum type, ArrayBufferView* pixels, ExceptionState& es)
+ GC3Denum format, GC3Denum type, ArrayBufferView* pixels, ExceptionState& exceptionState)
{
if (isContextLost() || !validateTexFuncData("texSubImage2D", level, width, height, format, type, pixels, NullNotAllowed)
|| !validateTexFunc("texSubImage2D", TexSubImage2D, SourceArrayBufferView, target, level, format, width, height, 0, format, type, xoffset, yoffset))
@@ -3625,14 +3643,14 @@ void WebGLRenderingContext::texSubImage2D(GC3Denum target, GC3Dint level, GC3Din
changeUnpackAlignment = true;
}
if (changeUnpackAlignment)
- m_context->pixelStorei(GraphicsContext3D::UNPACK_ALIGNMENT, 1);
- texSubImage2DBase(target, level, xoffset, yoffset, width, height, format, type, data, es);
+ m_context->pixelStorei(GL_UNPACK_ALIGNMENT, 1);
+ texSubImage2DBase(target, level, xoffset, yoffset, width, height, format, type, data, exceptionState);
if (changeUnpackAlignment)
- m_context->pixelStorei(GraphicsContext3D::UNPACK_ALIGNMENT, m_unpackAlignment);
+ m_context->pixelStorei(GL_UNPACK_ALIGNMENT, m_unpackAlignment);
}
void WebGLRenderingContext::texSubImage2D(GC3Denum target, GC3Dint level, GC3Dint xoffset, GC3Dint yoffset,
- GC3Denum format, GC3Denum type, ImageData* pixels, ExceptionState& es)
+ GC3Denum format, GC3Denum type, ImageData* pixels, ExceptionState& exceptionState)
{
if (isContextLost() || !pixels || !validateTexFunc("texSubImage2D", TexSubImage2D, SourceImageData, target, level, format, pixels->width(), pixels->height(), 0, format, type, xoffset, yoffset))
return;
@@ -3641,58 +3659,62 @@ void WebGLRenderingContext::texSubImage2D(GC3Denum target, GC3Dint level, GC3Din
bool needConversion = true;
// The data from ImageData is always of format RGBA8.
// No conversion is needed if destination format is RGBA and type is USIGNED_BYTE and no Flip or Premultiply operation is required.
- if (format == GraphicsContext3D::RGBA && type == GraphicsContext3D::UNSIGNED_BYTE && !m_unpackFlipY && !m_unpackPremultiplyAlpha)
+ if (format == GL_RGBA && type == GL_UNSIGNED_BYTE && !m_unpackFlipY && !m_unpackPremultiplyAlpha)
needConversion = false;
else {
- if (!m_context->extractImageData(pixels, format, type, m_unpackFlipY, m_unpackPremultiplyAlpha, data)) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "texSubImage2D", "bad image data");
+ if (!m_context->extractImageData(pixels->data()->data(), pixels->size(), format, type, m_unpackFlipY, m_unpackPremultiplyAlpha, data)) {
+ synthesizeGLError(GL_INVALID_VALUE, "texSubImage2D", "bad image data");
return;
}
}
if (m_unpackAlignment != 1)
- m_context->pixelStorei(GraphicsContext3D::UNPACK_ALIGNMENT, 1);
- texSubImage2DBase(target, level, xoffset, yoffset, pixels->width(), pixels->height(), format, type, needConversion ? data.data() : pixels->data()->data(), es);
+ m_context->pixelStorei(GL_UNPACK_ALIGNMENT, 1);
+ texSubImage2DBase(target, level, xoffset, yoffset, pixels->width(), pixels->height(), format, type, needConversion ? data.data() : pixels->data()->data(), exceptionState);
if (m_unpackAlignment != 1)
- m_context->pixelStorei(GraphicsContext3D::UNPACK_ALIGNMENT, m_unpackAlignment);
+ m_context->pixelStorei(GL_UNPACK_ALIGNMENT, m_unpackAlignment);
}
void WebGLRenderingContext::texSubImage2D(GC3Denum target, GC3Dint level, GC3Dint xoffset, GC3Dint yoffset,
- GC3Denum format, GC3Denum type, HTMLImageElement* image, ExceptionState& es)
+ GC3Denum format, GC3Denum type, HTMLImageElement* image, ExceptionState& exceptionState)
{
- if (isContextLost() || !validateHTMLImageElement("texSubImage2D", image, es))
+ if (isContextLost() || !validateHTMLImageElement("texSubImage2D", image, exceptionState))
return;
- Image* imageForRender = image->cachedImage()->imageForRenderer(image->renderer());
+
+ RefPtr<Image> imageForRender = image->cachedImage()->imageForRenderer(image->renderer());
+ if (imageForRender->isSVGImage())
+ imageForRender = drawImageIntoBuffer(imageForRender.get(), image->width(), image->height());
+
if (!imageForRender || !validateTexFunc("texSubImage2D", TexSubImage2D, SourceHTMLImageElement, target, level, format, imageForRender->width(), imageForRender->height(), 0, format, type, xoffset, yoffset))
return;
- texSubImage2DImpl(target, level, xoffset, yoffset, format, type, imageForRender, GraphicsContext3D::HtmlDomImage, m_unpackFlipY, m_unpackPremultiplyAlpha, es);
+ texSubImage2DImpl(target, level, xoffset, yoffset, format, type, imageForRender.get(), GraphicsContext3D::HtmlDomImage, m_unpackFlipY, m_unpackPremultiplyAlpha, exceptionState);
}
void WebGLRenderingContext::texSubImage2D(GC3Denum target, GC3Dint level, GC3Dint xoffset, GC3Dint yoffset,
- GC3Denum format, GC3Denum type, HTMLCanvasElement* canvas, ExceptionState& es)
+ GC3Denum format, GC3Denum type, HTMLCanvasElement* canvas, ExceptionState& exceptionState)
{
- if (isContextLost() || !validateHTMLCanvasElement("texSubImage2D", canvas, es)
+ if (isContextLost() || !validateHTMLCanvasElement("texSubImage2D", canvas, exceptionState)
|| !validateTexFunc("texSubImage2D", TexSubImage2D, SourceHTMLCanvasElement, target, level, format, canvas->width(), canvas->height(), 0, format, type, xoffset, yoffset))
return;
RefPtr<ImageData> imageData = canvas->getImageData();
if (imageData)
- texSubImage2D(target, level, xoffset, yoffset, format, type, imageData.get(), es);
+ texSubImage2D(target, level, xoffset, yoffset, format, type, imageData.get(), exceptionState);
else
- texSubImage2DImpl(target, level, xoffset, yoffset, format, type, canvas->copiedImage(), GraphicsContext3D::HtmlDomCanvas, m_unpackFlipY, m_unpackPremultiplyAlpha, es);
+ texSubImage2DImpl(target, level, xoffset, yoffset, format, type, canvas->copiedImage(), GraphicsContext3D::HtmlDomCanvas, m_unpackFlipY, m_unpackPremultiplyAlpha, exceptionState);
}
void WebGLRenderingContext::texSubImage2D(GC3Denum target, GC3Dint level, GC3Dint xoffset, GC3Dint yoffset,
- GC3Denum format, GC3Denum type, HTMLVideoElement* video, ExceptionState& es)
+ GC3Denum format, GC3Denum type, HTMLVideoElement* video, ExceptionState& exceptionState)
{
- if (isContextLost() || !validateHTMLVideoElement("texSubImage2D", video, es)
+ if (isContextLost() || !validateHTMLVideoElement("texSubImage2D", video, exceptionState)
|| !validateTexFunc("texSubImage2D", TexSubImage2D, SourceHTMLVideoElement, target, level, format, video->videoWidth(), video->videoHeight(), 0, format, type, xoffset, yoffset))
return;
RefPtr<Image> image = videoFrameToImage(video, ImageBuffer::fastCopyImageMode());
if (!image)
return;
- texSubImage2DImpl(target, level, xoffset, yoffset, format, type, image.get(), GraphicsContext3D::HtmlDomVideo, m_unpackFlipY, m_unpackPremultiplyAlpha, es);
+ texSubImage2DImpl(target, level, xoffset, yoffset, format, type, image.get(), GraphicsContext3D::HtmlDomVideo, m_unpackFlipY, m_unpackPremultiplyAlpha, exceptionState);
}
void WebGLRenderingContext::uniform1f(const WebGLUniformLocation* location, GC3Dfloat x)
@@ -3701,7 +3723,7 @@ void WebGLRenderingContext::uniform1f(const WebGLUniformLocation* location, GC3D
return;
if (location->program() != m_currentProgram) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "uniform1f", "location not for current program");
+ synthesizeGLError(GL_INVALID_OPERATION, "uniform1f", "location not for current program");
return;
}
@@ -3730,7 +3752,7 @@ void WebGLRenderingContext::uniform1i(const WebGLUniformLocation* location, GC3D
return;
if (location->program() != m_currentProgram) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "uniform1i", "location not for current program");
+ synthesizeGLError(GL_INVALID_OPERATION, "uniform1i", "location not for current program");
return;
}
@@ -3759,7 +3781,7 @@ void WebGLRenderingContext::uniform2f(const WebGLUniformLocation* location, GC3D
return;
if (location->program() != m_currentProgram) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "uniform2f", "location not for current program");
+ synthesizeGLError(GL_INVALID_OPERATION, "uniform2f", "location not for current program");
return;
}
@@ -3788,7 +3810,7 @@ void WebGLRenderingContext::uniform2i(const WebGLUniformLocation* location, GC3D
return;
if (location->program() != m_currentProgram) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "uniform2i", "location not for current program");
+ synthesizeGLError(GL_INVALID_OPERATION, "uniform2i", "location not for current program");
return;
}
@@ -3817,7 +3839,7 @@ void WebGLRenderingContext::uniform3f(const WebGLUniformLocation* location, GC3D
return;
if (location->program() != m_currentProgram) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "uniform3f", "location not for current program");
+ synthesizeGLError(GL_INVALID_OPERATION, "uniform3f", "location not for current program");
return;
}
@@ -3846,7 +3868,7 @@ void WebGLRenderingContext::uniform3i(const WebGLUniformLocation* location, GC3D
return;
if (location->program() != m_currentProgram) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "uniform3i", "location not for current program");
+ synthesizeGLError(GL_INVALID_OPERATION, "uniform3i", "location not for current program");
return;
}
@@ -3875,7 +3897,7 @@ void WebGLRenderingContext::uniform4f(const WebGLUniformLocation* location, GC3D
return;
if (location->program() != m_currentProgram) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "uniform4f", "location not for current program");
+ synthesizeGLError(GL_INVALID_OPERATION, "uniform4f", "location not for current program");
return;
}
@@ -3904,7 +3926,7 @@ void WebGLRenderingContext::uniform4i(const WebGLUniformLocation* location, GC3D
return;
if (location->program() != m_currentProgram) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "uniform4i", "location not for current program");
+ synthesizeGLError(GL_INVALID_OPERATION, "uniform4i", "location not for current program");
return;
}
@@ -3977,7 +3999,7 @@ void WebGLRenderingContext::useProgram(WebGLProgram* program)
if (deleted)
program = 0;
if (program && !program->linkStatus()) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "useProgram", "program not valid");
+ synthesizeGLError(GL_INVALID_OPERATION, "useProgram", "program not valid");
return;
}
if (m_currentProgram != program) {
@@ -4062,36 +4084,36 @@ void WebGLRenderingContext::vertexAttribPointer(GC3Duint index, GC3Dint size, GC
if (isContextLost())
return;
switch (type) {
- case GraphicsContext3D::BYTE:
- case GraphicsContext3D::UNSIGNED_BYTE:
- case GraphicsContext3D::SHORT:
- case GraphicsContext3D::UNSIGNED_SHORT:
- case GraphicsContext3D::FLOAT:
+ case GL_BYTE:
+ case GL_UNSIGNED_BYTE:
+ case GL_SHORT:
+ case GL_UNSIGNED_SHORT:
+ case GL_FLOAT:
break;
default:
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "vertexAttribPointer", "invalid type");
+ synthesizeGLError(GL_INVALID_ENUM, "vertexAttribPointer", "invalid type");
return;
}
if (index >= m_maxVertexAttribs) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "vertexAttribPointer", "index out of range");
+ synthesizeGLError(GL_INVALID_VALUE, "vertexAttribPointer", "index out of range");
return;
}
if (size < 1 || size > 4 || stride < 0 || stride > 255 || offset < 0) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "vertexAttribPointer", "bad size, stride or offset");
+ synthesizeGLError(GL_INVALID_VALUE, "vertexAttribPointer", "bad size, stride or offset");
return;
}
if (!m_boundArrayBuffer) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "vertexAttribPointer", "no bound ARRAY_BUFFER");
+ synthesizeGLError(GL_INVALID_OPERATION, "vertexAttribPointer", "no bound ARRAY_BUFFER");
return;
}
// Determine the number of elements the bound buffer can hold, given the offset, size, type and stride
unsigned int typeSize = sizeInBytes(type);
if (!typeSize) {
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "vertexAttribPointer", "invalid type");
+ synthesizeGLError(GL_INVALID_ENUM, "vertexAttribPointer", "invalid type");
return;
}
if ((stride % typeSize) || (static_cast<GC3Dintptr>(offset) % typeSize)) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "vertexAttribPointer", "stride or offset not valid for type");
+ synthesizeGLError(GL_INVALID_OPERATION, "vertexAttribPointer", "stride or offset not valid for type");
return;
}
GC3Dsizei bytesPerElement = size * typeSize;
@@ -4106,7 +4128,7 @@ void WebGLRenderingContext::vertexAttribDivisorANGLE(GC3Duint index, GC3Duint di
return;
if (index >= m_maxVertexAttribs) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "vertexAttribDivisorANGLE", "index out of range");
+ synthesizeGLError(GL_INVALID_VALUE, "vertexAttribDivisorANGLE", "index out of range");
return;
}
@@ -4126,7 +4148,7 @@ void WebGLRenderingContext::viewport(GC3Dint x, GC3Dint y, GC3Dsizei width, GC3D
void WebGLRenderingContext::forceLostContext(WebGLRenderingContext::LostContextMode mode)
{
if (isContextLost()) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "loseContext", "context already lost");
+ synthesizeGLError(GL_INVALID_OPERATION, "loseContext", "context already lost");
return;
}
@@ -4145,7 +4167,7 @@ void WebGLRenderingContext::loseContextImpl(WebGLRenderingContext::LostContextMo
// Inform the embedder that a lost context was received. In response, the embedder might
// decide to take action such as asking the user for permission to use WebGL again.
if (Frame* frame = canvas()->document().frame())
- frame->loader()->client()->didLoseWebGLContext(m_context->extensions()->getGraphicsResetStatusARB());
+ frame->loader().client()->didLoseWebGLContext(m_context->extensions()->getGraphicsResetStatusARB());
}
// Make absolutely sure we do not refer to an already-deleted texture or framebuffer.
@@ -4166,7 +4188,7 @@ void WebGLRenderingContext::loseContextImpl(WebGLRenderingContext::LostContextMo
destroyGraphicsContext3D();
ConsoleDisplayPreference display = (mode == RealLostContext) ? DisplayInConsole: DontDisplayInConsole;
- synthesizeGLError(GraphicsContext3D::CONTEXT_LOST_WEBGL, "loseContext", "context lost", display);
+ synthesizeGLError(GC3D_CONTEXT_LOST_WEBGL, "loseContext", "context lost", display);
// Don't allow restoration unless the context lost event has both been
// dispatched and its default behavior prevented.
@@ -4180,13 +4202,13 @@ void WebGLRenderingContext::loseContextImpl(WebGLRenderingContext::LostContextMo
void WebGLRenderingContext::forceRestoreContext()
{
if (!isContextLost()) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "restoreContext", "context not lost");
+ synthesizeGLError(GL_INVALID_OPERATION, "restoreContext", "context not lost");
return;
}
if (!m_restoreAllowed) {
if (m_contextLostMode == SyntheticLostContext)
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "restoreContext", "context restoration not allowed");
+ synthesizeGLError(GL_INVALID_OPERATION, "restoreContext", "context restoration not allowed");
return;
}
@@ -4194,7 +4216,7 @@ void WebGLRenderingContext::forceRestoreContext()
m_restoreTimer.startOneShot(0);
}
-WebKit::WebLayer* WebGLRenderingContext::platformLayer() const
+blink::WebLayer* WebGLRenderingContext::platformLayer() const
{
return m_drawingBuffer->platformLayer();
}
@@ -4252,7 +4274,7 @@ WebGLGetInfo WebGLRenderingContext::getBooleanParameter(GC3Denum pname)
WebGLGetInfo WebGLRenderingContext::getBooleanArrayParameter(GC3Denum pname)
{
- if (pname != GraphicsContext3D::COLOR_WRITEMASK) {
+ if (pname != GL_COLOR_WRITEMASK) {
notImplemented();
return WebGLGetInfo(0, 0);
}
@@ -4296,13 +4318,13 @@ WebGLGetInfo WebGLRenderingContext::getWebGLFloatArrayParameter(GC3Denum pname)
m_context->getFloatv(pname, value);
unsigned length = 0;
switch (pname) {
- case GraphicsContext3D::ALIASED_POINT_SIZE_RANGE:
- case GraphicsContext3D::ALIASED_LINE_WIDTH_RANGE:
- case GraphicsContext3D::DEPTH_RANGE:
+ case GL_ALIASED_POINT_SIZE_RANGE:
+ case GL_ALIASED_LINE_WIDTH_RANGE:
+ case GL_DEPTH_RANGE:
length = 2;
break;
- case GraphicsContext3D::BLEND_COLOR:
- case GraphicsContext3D::COLOR_CLEAR_VALUE:
+ case GL_BLEND_COLOR:
+ case GL_COLOR_CLEAR_VALUE:
length = 4;
break;
default:
@@ -4318,11 +4340,11 @@ WebGLGetInfo WebGLRenderingContext::getWebGLIntArrayParameter(GC3Denum pname)
m_context->getIntegerv(pname, value);
unsigned length = 0;
switch (pname) {
- case GraphicsContext3D::MAX_VIEWPORT_DIMS:
+ case GL_MAX_VIEWPORT_DIMS:
length = 2;
break;
- case GraphicsContext3D::SCISSOR_BOX:
- case GraphicsContext3D::VIEWPORT:
+ case GL_SCISSOR_BOX:
+ case GL_VIEWPORT:
length = 4;
break;
default:
@@ -4361,9 +4383,9 @@ void WebGLRenderingContext::handleTextureCompleteness(const char* functionName,
texCubeMap = m_textureUnits[ii].m_textureCubeMapBinding.get();
}
if (m_textureUnits[ii].m_texture2DBinding && m_textureUnits[ii].m_texture2DBinding->needToUseBlackTexture(flag))
- m_context->bindTexture(GraphicsContext3D::TEXTURE_2D, objectOrZero(tex2D));
+ m_context->bindTexture(GL_TEXTURE_2D, objectOrZero(tex2D));
if (m_textureUnits[ii].m_textureCubeMapBinding && m_textureUnits[ii].m_textureCubeMapBinding->needToUseBlackTexture(flag))
- m_context->bindTexture(GraphicsContext3D::TEXTURE_CUBE_MAP, objectOrZero(texCubeMap));
+ m_context->bindTexture(GL_TEXTURE_CUBE_MAP, objectOrZero(texCubeMap));
}
}
if (resetActiveUnit)
@@ -4375,25 +4397,25 @@ void WebGLRenderingContext::createFallbackBlackTextures1x1()
// All calling functions check isContextLost, so a duplicate check is not needed here.
unsigned char black[] = {0, 0, 0, 255};
m_blackTexture2D = createTexture();
- m_context->bindTexture(GraphicsContext3D::TEXTURE_2D, m_blackTexture2D->object());
- m_context->texImage2D(GraphicsContext3D::TEXTURE_2D, 0, GraphicsContext3D::RGBA, 1, 1,
- 0, GraphicsContext3D::RGBA, GraphicsContext3D::UNSIGNED_BYTE, black);
- m_context->bindTexture(GraphicsContext3D::TEXTURE_2D, 0);
+ m_context->bindTexture(GL_TEXTURE_2D, m_blackTexture2D->object());
+ m_context->texImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1, 1,
+ 0, GL_RGBA, GL_UNSIGNED_BYTE, black);
+ m_context->bindTexture(GL_TEXTURE_2D, 0);
m_blackTextureCubeMap = createTexture();
- m_context->bindTexture(GraphicsContext3D::TEXTURE_CUBE_MAP, m_blackTextureCubeMap->object());
- m_context->texImage2D(GraphicsContext3D::TEXTURE_CUBE_MAP_POSITIVE_X, 0, GraphicsContext3D::RGBA, 1, 1,
- 0, GraphicsContext3D::RGBA, GraphicsContext3D::UNSIGNED_BYTE, black);
- m_context->texImage2D(GraphicsContext3D::TEXTURE_CUBE_MAP_NEGATIVE_X, 0, GraphicsContext3D::RGBA, 1, 1,
- 0, GraphicsContext3D::RGBA, GraphicsContext3D::UNSIGNED_BYTE, black);
- m_context->texImage2D(GraphicsContext3D::TEXTURE_CUBE_MAP_POSITIVE_Y, 0, GraphicsContext3D::RGBA, 1, 1,
- 0, GraphicsContext3D::RGBA, GraphicsContext3D::UNSIGNED_BYTE, black);
- m_context->texImage2D(GraphicsContext3D::TEXTURE_CUBE_MAP_NEGATIVE_Y, 0, GraphicsContext3D::RGBA, 1, 1,
- 0, GraphicsContext3D::RGBA, GraphicsContext3D::UNSIGNED_BYTE, black);
- m_context->texImage2D(GraphicsContext3D::TEXTURE_CUBE_MAP_POSITIVE_Z, 0, GraphicsContext3D::RGBA, 1, 1,
- 0, GraphicsContext3D::RGBA, GraphicsContext3D::UNSIGNED_BYTE, black);
- m_context->texImage2D(GraphicsContext3D::TEXTURE_CUBE_MAP_NEGATIVE_Z, 0, GraphicsContext3D::RGBA, 1, 1,
- 0, GraphicsContext3D::RGBA, GraphicsContext3D::UNSIGNED_BYTE, black);
- m_context->bindTexture(GraphicsContext3D::TEXTURE_CUBE_MAP, 0);
+ m_context->bindTexture(GL_TEXTURE_CUBE_MAP, m_blackTextureCubeMap->object());
+ m_context->texImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X, 0, GL_RGBA, 1, 1,
+ 0, GL_RGBA, GL_UNSIGNED_BYTE, black);
+ m_context->texImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_X, 0, GL_RGBA, 1, 1,
+ 0, GL_RGBA, GL_UNSIGNED_BYTE, black);
+ m_context->texImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Y, 0, GL_RGBA, 1, 1,
+ 0, GL_RGBA, GL_UNSIGNED_BYTE, black);
+ m_context->texImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, 0, GL_RGBA, 1, 1,
+ 0, GL_RGBA, GL_UNSIGNED_BYTE, black);
+ m_context->texImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Z, 0, GL_RGBA, 1, 1,
+ 0, GL_RGBA, GL_UNSIGNED_BYTE, black);
+ m_context->texImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, 0, GL_RGBA, 1, 1,
+ 0, GL_RGBA, GL_UNSIGNED_BYTE, black);
+ m_context->bindTexture(GL_TEXTURE_CUBE_MAP, 0);
}
bool WebGLRenderingContext::isTexInternalFormatColorBufferCombinationValid(GC3Denum texInternalFormat,
@@ -4409,8 +4431,8 @@ GC3Denum WebGLRenderingContext::boundFramebufferColorFormat()
if (m_framebufferBinding && m_framebufferBinding->object())
return m_framebufferBinding->colorBufferFormat();
if (m_attributes.alpha)
- return GraphicsContext3D::RGBA;
- return GraphicsContext3D::RGB;
+ return GL_RGBA;
+ return GL_RGB;
}
int WebGLRenderingContext::boundFramebufferWidth()
@@ -4431,34 +4453,34 @@ WebGLTexture* WebGLRenderingContext::validateTextureBinding(const char* function
{
WebGLTexture* tex = 0;
switch (target) {
- case GraphicsContext3D::TEXTURE_2D:
+ case GL_TEXTURE_2D:
tex = m_textureUnits[m_activeTextureUnit].m_texture2DBinding.get();
break;
- case GraphicsContext3D::TEXTURE_CUBE_MAP_POSITIVE_X:
- case GraphicsContext3D::TEXTURE_CUBE_MAP_NEGATIVE_X:
- case GraphicsContext3D::TEXTURE_CUBE_MAP_POSITIVE_Y:
- case GraphicsContext3D::TEXTURE_CUBE_MAP_NEGATIVE_Y:
- case GraphicsContext3D::TEXTURE_CUBE_MAP_POSITIVE_Z:
- case GraphicsContext3D::TEXTURE_CUBE_MAP_NEGATIVE_Z:
+ case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
+ case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
+ case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
+ case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
+ case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
+ case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
if (!useSixEnumsForCubeMap) {
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, functionName, "invalid texture target");
+ synthesizeGLError(GL_INVALID_ENUM, functionName, "invalid texture target");
return 0;
}
tex = m_textureUnits[m_activeTextureUnit].m_textureCubeMapBinding.get();
break;
- case GraphicsContext3D::TEXTURE_CUBE_MAP:
+ case GL_TEXTURE_CUBE_MAP:
if (useSixEnumsForCubeMap) {
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, functionName, "invalid texture target");
+ synthesizeGLError(GL_INVALID_ENUM, functionName, "invalid texture target");
return 0;
}
tex = m_textureUnits[m_activeTextureUnit].m_textureCubeMapBinding.get();
break;
default:
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, functionName, "invalid texture target");
+ synthesizeGLError(GL_INVALID_ENUM, functionName, "invalid texture target");
return 0;
}
if (!tex)
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, functionName, "no texture");
+ synthesizeGLError(GL_INVALID_OPERATION, functionName, "no texture");
return tex;
}
@@ -4466,7 +4488,7 @@ bool WebGLRenderingContext::validateLocationLength(const char* functionName, con
{
const unsigned maxWebGLLocationLength = 256;
if (string.length() > maxWebGLLocationLength) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "location length > 256");
+ synthesizeGLError(GL_INVALID_VALUE, functionName, "location length > 256");
return false;
}
return true;
@@ -4475,7 +4497,7 @@ bool WebGLRenderingContext::validateLocationLength(const char* functionName, con
bool WebGLRenderingContext::validateSize(const char* functionName, GC3Dint x, GC3Dint y)
{
if (x < 0 || y < 0) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "size < 0");
+ synthesizeGLError(GL_INVALID_VALUE, functionName, "size < 0");
return false;
}
return true;
@@ -4485,7 +4507,7 @@ bool WebGLRenderingContext::validateString(const char* functionName, const Strin
{
for (size_t i = 0; i < string.length(); ++i) {
if (!validateCharacter(string[i])) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "string not ASCII");
+ synthesizeGLError(GL_INVALID_VALUE, functionName, "string not ASCII");
return false;
}
}
@@ -4495,109 +4517,109 @@ bool WebGLRenderingContext::validateString(const char* functionName, const Strin
bool WebGLRenderingContext::validateTexFuncFormatAndType(const char* functionName, GC3Denum format, GC3Denum type, GC3Dint level)
{
switch (format) {
- case GraphicsContext3D::ALPHA:
- case GraphicsContext3D::LUMINANCE:
- case GraphicsContext3D::LUMINANCE_ALPHA:
- case GraphicsContext3D::RGB:
- case GraphicsContext3D::RGBA:
+ case GL_ALPHA:
+ case GL_LUMINANCE:
+ case GL_LUMINANCE_ALPHA:
+ case GL_RGB:
+ case GL_RGBA:
break;
- case GraphicsContext3D::DEPTH_STENCIL:
- case GraphicsContext3D::DEPTH_COMPONENT:
+ case GL_DEPTH_STENCIL_OES:
+ case GL_DEPTH_COMPONENT:
if (m_webglDepthTexture)
break;
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, functionName, "depth texture formats not enabled");
+ synthesizeGLError(GL_INVALID_ENUM, functionName, "depth texture formats not enabled");
return false;
default:
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, functionName, "invalid texture format");
+ synthesizeGLError(GL_INVALID_ENUM, functionName, "invalid texture format");
return false;
}
switch (type) {
- case GraphicsContext3D::UNSIGNED_BYTE:
- case GraphicsContext3D::UNSIGNED_SHORT_5_6_5:
- case GraphicsContext3D::UNSIGNED_SHORT_4_4_4_4:
- case GraphicsContext3D::UNSIGNED_SHORT_5_5_5_1:
+ case GL_UNSIGNED_BYTE:
+ case GL_UNSIGNED_SHORT_5_6_5:
+ case GL_UNSIGNED_SHORT_4_4_4_4:
+ case GL_UNSIGNED_SHORT_5_5_5_1:
break;
- case GraphicsContext3D::FLOAT:
+ case GL_FLOAT:
if (m_oesTextureFloat)
break;
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, functionName, "invalid texture type");
+ synthesizeGLError(GL_INVALID_ENUM, functionName, "invalid texture type");
return false;
- case GraphicsContext3D::HALF_FLOAT_OES:
+ case GL_HALF_FLOAT_OES:
if (m_oesTextureHalfFloat)
break;
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, functionName, "invalid texture type");
+ synthesizeGLError(GL_INVALID_ENUM, functionName, "invalid texture type");
return false;
- case GraphicsContext3D::UNSIGNED_INT:
- case GraphicsContext3D::UNSIGNED_INT_24_8:
- case GraphicsContext3D::UNSIGNED_SHORT:
+ case GL_UNSIGNED_INT:
+ case GL_UNSIGNED_INT_24_8_OES:
+ case GL_UNSIGNED_SHORT:
if (m_webglDepthTexture)
break;
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, functionName, "invalid texture type");
+ synthesizeGLError(GL_INVALID_ENUM, functionName, "invalid texture type");
return false;
default:
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, functionName, "invalid texture type");
+ synthesizeGLError(GL_INVALID_ENUM, functionName, "invalid texture type");
return false;
}
// Verify that the combination of format and type is supported.
switch (format) {
- case GraphicsContext3D::ALPHA:
- case GraphicsContext3D::LUMINANCE:
- case GraphicsContext3D::LUMINANCE_ALPHA:
- if (type != GraphicsContext3D::UNSIGNED_BYTE
- && type != GraphicsContext3D::FLOAT
- && type != GraphicsContext3D::HALF_FLOAT_OES) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, functionName, "invalid type for format");
+ case GL_ALPHA:
+ case GL_LUMINANCE:
+ case GL_LUMINANCE_ALPHA:
+ if (type != GL_UNSIGNED_BYTE
+ && type != GL_FLOAT
+ && type != GL_HALF_FLOAT_OES) {
+ synthesizeGLError(GL_INVALID_OPERATION, functionName, "invalid type for format");
return false;
}
break;
- case GraphicsContext3D::RGB:
- if (type != GraphicsContext3D::UNSIGNED_BYTE
- && type != GraphicsContext3D::UNSIGNED_SHORT_5_6_5
- && type != GraphicsContext3D::FLOAT
- && type != GraphicsContext3D::HALF_FLOAT_OES) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, functionName, "invalid type for RGB format");
+ case GL_RGB:
+ if (type != GL_UNSIGNED_BYTE
+ && type != GL_UNSIGNED_SHORT_5_6_5
+ && type != GL_FLOAT
+ && type != GL_HALF_FLOAT_OES) {
+ synthesizeGLError(GL_INVALID_OPERATION, functionName, "invalid type for RGB format");
return false;
}
break;
- case GraphicsContext3D::RGBA:
- if (type != GraphicsContext3D::UNSIGNED_BYTE
- && type != GraphicsContext3D::UNSIGNED_SHORT_4_4_4_4
- && type != GraphicsContext3D::UNSIGNED_SHORT_5_5_5_1
- && type != GraphicsContext3D::FLOAT
- && type != GraphicsContext3D::HALF_FLOAT_OES) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, functionName, "invalid type for RGBA format");
+ case GL_RGBA:
+ if (type != GL_UNSIGNED_BYTE
+ && type != GL_UNSIGNED_SHORT_4_4_4_4
+ && type != GL_UNSIGNED_SHORT_5_5_5_1
+ && type != GL_FLOAT
+ && type != GL_HALF_FLOAT_OES) {
+ synthesizeGLError(GL_INVALID_OPERATION, functionName, "invalid type for RGBA format");
return false;
}
break;
- case GraphicsContext3D::DEPTH_COMPONENT:
+ case GL_DEPTH_COMPONENT:
if (!m_webglDepthTexture) {
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, functionName, "invalid format. DEPTH_COMPONENT not enabled");
+ synthesizeGLError(GL_INVALID_ENUM, functionName, "invalid format. DEPTH_COMPONENT not enabled");
return false;
}
- if (type != GraphicsContext3D::UNSIGNED_SHORT
- && type != GraphicsContext3D::UNSIGNED_INT) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, functionName, "invalid type for DEPTH_COMPONENT format");
+ if (type != GL_UNSIGNED_SHORT
+ && type != GL_UNSIGNED_INT) {
+ synthesizeGLError(GL_INVALID_OPERATION, functionName, "invalid type for DEPTH_COMPONENT format");
return false;
}
if (level > 0) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, functionName, "level must be 0 for DEPTH_COMPONENT format");
- return false;
+ synthesizeGLError(GL_INVALID_OPERATION, functionName, "level must be 0 for DEPTH_COMPONENT format");
+ return false;
}
break;
- case GraphicsContext3D::DEPTH_STENCIL:
+ case GL_DEPTH_STENCIL_OES:
if (!m_webglDepthTexture) {
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, functionName, "invalid format. DEPTH_STENCIL not enabled");
+ synthesizeGLError(GL_INVALID_ENUM, functionName, "invalid format. DEPTH_STENCIL not enabled");
return false;
}
- if (type != GraphicsContext3D::UNSIGNED_INT_24_8) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, functionName, "invalid type for DEPTH_STENCIL format");
+ if (type != GL_UNSIGNED_INT_24_8_OES) {
+ synthesizeGLError(GL_INVALID_OPERATION, functionName, "invalid type for DEPTH_STENCIL format");
return false;
}
if (level > 0) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, functionName, "level must be 0 for DEPTH_STENCIL format");
- return false;
+ synthesizeGLError(GL_INVALID_OPERATION, functionName, "level must be 0 for DEPTH_STENCIL format");
+ return false;
}
break;
default:
@@ -4610,24 +4632,24 @@ bool WebGLRenderingContext::validateTexFuncFormatAndType(const char* functionNam
bool WebGLRenderingContext::validateTexFuncLevel(const char* functionName, GC3Denum target, GC3Dint level)
{
if (level < 0) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "level < 0");
+ synthesizeGLError(GL_INVALID_VALUE, functionName, "level < 0");
return false;
}
switch (target) {
- case GraphicsContext3D::TEXTURE_2D:
+ case GL_TEXTURE_2D:
if (level >= m_maxTextureLevel) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "level out of range");
+ synthesizeGLError(GL_INVALID_VALUE, functionName, "level out of range");
return false;
}
break;
- case GraphicsContext3D::TEXTURE_CUBE_MAP_POSITIVE_X:
- case GraphicsContext3D::TEXTURE_CUBE_MAP_NEGATIVE_X:
- case GraphicsContext3D::TEXTURE_CUBE_MAP_POSITIVE_Y:
- case GraphicsContext3D::TEXTURE_CUBE_MAP_NEGATIVE_Y:
- case GraphicsContext3D::TEXTURE_CUBE_MAP_POSITIVE_Z:
- case GraphicsContext3D::TEXTURE_CUBE_MAP_NEGATIVE_Z:
+ case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
+ case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
+ case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
+ case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
+ case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
+ case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
if (level >= m_maxCubeMapTextureLevel) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "level out of range");
+ synthesizeGLError(GL_INVALID_VALUE, functionName, "level out of range");
return false;
}
break;
@@ -4641,36 +4663,36 @@ bool WebGLRenderingContext::validateTexFuncDimensions(const char* functionName,
GC3Denum target, GC3Dint level, GC3Dsizei width, GC3Dsizei height)
{
if (width < 0 || height < 0) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "width or height < 0");
+ synthesizeGLError(GL_INVALID_VALUE, functionName, "width or height < 0");
return false;
}
switch (target) {
- case GraphicsContext3D::TEXTURE_2D:
+ case GL_TEXTURE_2D:
if (width > (m_maxTextureSize >> level) || height > (m_maxTextureSize >> level)) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "width or height out of range");
+ synthesizeGLError(GL_INVALID_VALUE, functionName, "width or height out of range");
return false;
}
break;
- case GraphicsContext3D::TEXTURE_CUBE_MAP_POSITIVE_X:
- case GraphicsContext3D::TEXTURE_CUBE_MAP_NEGATIVE_X:
- case GraphicsContext3D::TEXTURE_CUBE_MAP_POSITIVE_Y:
- case GraphicsContext3D::TEXTURE_CUBE_MAP_NEGATIVE_Y:
- case GraphicsContext3D::TEXTURE_CUBE_MAP_POSITIVE_Z:
- case GraphicsContext3D::TEXTURE_CUBE_MAP_NEGATIVE_Z:
+ case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
+ case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
+ case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
+ case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
+ case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
+ case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
if (functionType != TexSubImage2D && width != height) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "width != height for cube map");
- return false;
+ synthesizeGLError(GL_INVALID_VALUE, functionName, "width != height for cube map");
+ return false;
}
// No need to check height here. For texImage width == height.
// For texSubImage that will be checked when checking yoffset + height is in range.
if (width > (m_maxCubeMapTextureSize >> level)) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "width or height out of range for cube map");
+ synthesizeGLError(GL_INVALID_VALUE, functionName, "width or height out of range for cube map");
return false;
}
break;
default:
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, functionName, "invalid target");
+ synthesizeGLError(GL_INVALID_ENUM, functionName, "invalid target");
return false;
}
return true;
@@ -4689,12 +4711,12 @@ bool WebGLRenderingContext::validateTexFuncParameters(const char* functionName,
return false;
if (format != internalformat) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, functionName, "format != internalformat");
+ synthesizeGLError(GL_INVALID_OPERATION, functionName, "format != internalformat");
return false;
}
if (border) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "border != 0");
+ synthesizeGLError(GL_INVALID_VALUE, functionName, "border != 0");
return false;
}
@@ -4711,7 +4733,7 @@ bool WebGLRenderingContext::validateTexFuncData(const char* functionName, GC3Din
if (!pixels) {
if (disposition == NullAllowed)
return true;
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "no pixels");
+ synthesizeGLError(GL_INVALID_VALUE, functionName, "no pixels");
return false;
}
@@ -4721,31 +4743,31 @@ bool WebGLRenderingContext::validateTexFuncData(const char* functionName, GC3Din
return false;
switch (type) {
- case GraphicsContext3D::UNSIGNED_BYTE:
+ case GL_UNSIGNED_BYTE:
if (pixels->getType() != ArrayBufferView::TypeUint8) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, functionName, "type UNSIGNED_BYTE but ArrayBufferView not Uint8Array");
+ synthesizeGLError(GL_INVALID_OPERATION, functionName, "type UNSIGNED_BYTE but ArrayBufferView not Uint8Array");
return false;
}
break;
- case GraphicsContext3D::UNSIGNED_SHORT_5_6_5:
- case GraphicsContext3D::UNSIGNED_SHORT_4_4_4_4:
- case GraphicsContext3D::UNSIGNED_SHORT_5_5_5_1:
+ case GL_UNSIGNED_SHORT_5_6_5:
+ case GL_UNSIGNED_SHORT_4_4_4_4:
+ case GL_UNSIGNED_SHORT_5_5_5_1:
if (pixels->getType() != ArrayBufferView::TypeUint16) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, functionName, "type UNSIGNED_SHORT but ArrayBufferView not Uint16Array");
+ synthesizeGLError(GL_INVALID_OPERATION, functionName, "type UNSIGNED_SHORT but ArrayBufferView not Uint16Array");
return false;
}
break;
- case GraphicsContext3D::FLOAT: // OES_texture_float
+ case GL_FLOAT: // OES_texture_float
if (pixels->getType() != ArrayBufferView::TypeFloat32) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, functionName, "type FLOAT but ArrayBufferView not Float32Array");
+ synthesizeGLError(GL_INVALID_OPERATION, functionName, "type FLOAT but ArrayBufferView not Float32Array");
return false;
}
break;
- case GraphicsContext3D::HALF_FLOAT_OES: // OES_texture_half_float
+ case GL_HALF_FLOAT_OES: // OES_texture_half_float
// As per the specification, ArrayBufferView should be null when
// OES_texture_half_float is enabled.
if (pixels) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, functionName, "type HALF_FLOAT_OES but ArrayBufferView is not NULL");
+ synthesizeGLError(GL_INVALID_OPERATION, functionName, "type HALF_FLOAT_OES but ArrayBufferView is not NULL");
return false;
}
break;
@@ -4755,7 +4777,7 @@ bool WebGLRenderingContext::validateTexFuncData(const char* functionName, GC3Din
unsigned int totalBytesRequired;
GC3Denum error = m_context->computeImageSizeInBytes(format, type, width, height, m_unpackAlignment, &totalBytesRequired, 0);
- if (error != GraphicsContext3D::NO_ERROR) {
+ if (error != GL_NO_ERROR) {
synthesizeGLError(error, functionName, "invalid texture dimensions");
return false;
}
@@ -4763,11 +4785,11 @@ bool WebGLRenderingContext::validateTexFuncData(const char* functionName, GC3Din
if (m_unpackAlignment != 1) {
error = m_context->computeImageSizeInBytes(format, type, width, height, 1, &totalBytesRequired, 0);
if (pixels->byteLength() == totalBytesRequired) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, functionName, "ArrayBufferView not big enough for request with UNPACK_ALIGNMENT > 1");
+ synthesizeGLError(GL_INVALID_OPERATION, functionName, "ArrayBufferView not big enough for request with UNPACK_ALIGNMENT > 1");
return false;
}
}
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, functionName, "ArrayBufferView not big enough for request");
+ synthesizeGLError(GL_INVALID_OPERATION, functionName, "ArrayBufferView not big enough for request");
return false;
}
return true;
@@ -4783,11 +4805,11 @@ bool WebGLRenderingContext::validateCompressedTexFuncData(const char* functionNa
GC3Denum format, ArrayBufferView* pixels)
{
if (!pixels) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "no pixels");
+ synthesizeGLError(GL_INVALID_VALUE, functionName, "no pixels");
return false;
}
if (width < 0 || height < 0) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "width or height < 0");
+ synthesizeGLError(GL_INVALID_VALUE, functionName, "width or height < 0");
return false;
}
@@ -4841,12 +4863,12 @@ bool WebGLRenderingContext::validateCompressedTexFuncData(const char* functionNa
}
break;
default:
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, functionName, "invalid format");
+ synthesizeGLError(GL_INVALID_ENUM, functionName, "invalid format");
return false;
}
if (pixels->byteLength() != bytesRequired) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "length of ArrayBufferView is not correct for dimensions");
+ synthesizeGLError(GL_INVALID_VALUE, functionName, "length of ArrayBufferView is not correct for dimensions");
return false;
}
@@ -4868,8 +4890,8 @@ bool WebGLRenderingContext::validateCompressedTexDimensions(const char* function
bool widthValid = (level && width == 1) || (level && width == 2) || !(width % kBlockWidth);
bool heightValid = (level && height == 1) || (level && height == 2) || !(height % kBlockHeight);
if (!widthValid || !heightValid) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, functionName, "width or height invalid for level");
- return false;
+ synthesizeGLError(GL_INVALID_OPERATION, functionName, "width or height invalid for level");
+ return false;
}
return true;
}
@@ -4882,8 +4904,8 @@ bool WebGLRenderingContext::validateCompressedTexSubDimensions(const char* funct
GC3Dsizei width, GC3Dsizei height, GC3Denum format, WebGLTexture* tex)
{
if (xoffset < 0 || yoffset < 0) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "xoffset or yoffset < 0");
- return false;
+ synthesizeGLError(GL_INVALID_VALUE, functionName, "xoffset or yoffset < 0");
+ return false;
}
switch (format) {
@@ -4894,12 +4916,12 @@ bool WebGLRenderingContext::validateCompressedTexSubDimensions(const char* funct
const int kBlockWidth = 4;
const int kBlockHeight = 4;
if ((xoffset % kBlockWidth) || (yoffset % kBlockHeight)) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, functionName, "xoffset or yoffset not multiple of 4");
+ synthesizeGLError(GL_INVALID_OPERATION, functionName, "xoffset or yoffset not multiple of 4");
return false;
}
if (width - xoffset > tex->getWidth(target, level)
|| height - yoffset > tex->getHeight(target, level)) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, functionName, "dimensions out of range");
+ synthesizeGLError(GL_INVALID_OPERATION, functionName, "dimensions out of range");
return false;
}
return validateCompressedTexDimensions(functionName, TexSubImage2D, target, level, width, height, format);
@@ -4912,16 +4934,16 @@ bool WebGLRenderingContext::validateCompressedTexSubDimensions(const char* funct
bool WebGLRenderingContext::validateDrawMode(const char* functionName, GC3Denum mode)
{
switch (mode) {
- case GraphicsContext3D::POINTS:
- case GraphicsContext3D::LINE_STRIP:
- case GraphicsContext3D::LINE_LOOP:
- case GraphicsContext3D::LINES:
- case GraphicsContext3D::TRIANGLE_STRIP:
- case GraphicsContext3D::TRIANGLE_FAN:
- case GraphicsContext3D::TRIANGLES:
+ case GL_POINTS:
+ case GL_LINE_STRIP:
+ case GL_LINE_LOOP:
+ case GL_LINES:
+ case GL_TRIANGLE_STRIP:
+ case GL_TRIANGLE_FAN:
+ case GL_TRIANGLES:
return true;
default:
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, functionName, "invalid draw mode");
+ synthesizeGLError(GL_INVALID_ENUM, functionName, "invalid draw mode");
return false;
}
}
@@ -4929,7 +4951,7 @@ bool WebGLRenderingContext::validateDrawMode(const char* functionName, GC3Denum
bool WebGLRenderingContext::validateStencilSettings(const char* functionName)
{
if (m_stencilMask != m_stencilMaskBack || m_stencilFuncRef != m_stencilFuncRefBack || m_stencilFuncMask != m_stencilFuncMaskBack) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, functionName, "front and back stencils settings do not match");
+ synthesizeGLError(GL_INVALID_OPERATION, functionName, "front and back stencils settings do not match");
return false;
}
return true;
@@ -4938,17 +4960,17 @@ bool WebGLRenderingContext::validateStencilSettings(const char* functionName)
bool WebGLRenderingContext::validateStencilOrDepthFunc(const char* functionName, GC3Denum func)
{
switch (func) {
- case GraphicsContext3D::NEVER:
- case GraphicsContext3D::LESS:
- case GraphicsContext3D::LEQUAL:
- case GraphicsContext3D::GREATER:
- case GraphicsContext3D::GEQUAL:
- case GraphicsContext3D::EQUAL:
- case GraphicsContext3D::NOTEQUAL:
- case GraphicsContext3D::ALWAYS:
+ case GL_NEVER:
+ case GL_LESS:
+ case GL_LEQUAL:
+ case GL_GREATER:
+ case GL_GEQUAL:
+ case GL_EQUAL:
+ case GL_NOTEQUAL:
+ case GL_ALWAYS:
return true;
default:
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, functionName, "invalid function");
+ synthesizeGLError(GL_INVALID_ENUM, functionName, "invalid function");
return false;
}
}
@@ -4976,22 +4998,22 @@ void WebGLRenderingContext::printWarningToConsole(const String& message)
bool WebGLRenderingContext::validateFramebufferFuncParameters(const char* functionName, GC3Denum target, GC3Denum attachment)
{
- if (target != GraphicsContext3D::FRAMEBUFFER) {
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, functionName, "invalid target");
+ if (target != GL_FRAMEBUFFER) {
+ synthesizeGLError(GL_INVALID_ENUM, functionName, "invalid target");
return false;
}
switch (attachment) {
- case GraphicsContext3D::COLOR_ATTACHMENT0:
- case GraphicsContext3D::DEPTH_ATTACHMENT:
- case GraphicsContext3D::STENCIL_ATTACHMENT:
- case GraphicsContext3D::DEPTH_STENCIL_ATTACHMENT:
+ case GL_COLOR_ATTACHMENT0:
+ case GL_DEPTH_ATTACHMENT:
+ case GL_STENCIL_ATTACHMENT:
+ case GC3D_DEPTH_STENCIL_ATTACHMENT_WEBGL:
break;
default:
if (m_webglDrawBuffers
- && attachment > GraphicsContext3D::COLOR_ATTACHMENT0
- && attachment < static_cast<GC3Denum>(GraphicsContext3D::COLOR_ATTACHMENT0 + maxColorAttachments()))
+ && attachment > GL_COLOR_ATTACHMENT0
+ && attachment < static_cast<GC3Denum>(GL_COLOR_ATTACHMENT0 + maxColorAttachments()))
break;
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, functionName, "invalid attachment");
+ synthesizeGLError(GL_INVALID_ENUM, functionName, "invalid attachment");
return false;
}
return true;
@@ -5000,23 +5022,23 @@ bool WebGLRenderingContext::validateFramebufferFuncParameters(const char* functi
bool WebGLRenderingContext::validateBlendEquation(const char* functionName, GC3Denum mode)
{
switch (mode) {
- case GraphicsContext3D::FUNC_ADD:
- case GraphicsContext3D::FUNC_SUBTRACT:
- case GraphicsContext3D::FUNC_REVERSE_SUBTRACT:
+ case GL_FUNC_ADD:
+ case GL_FUNC_SUBTRACT:
+ case GL_FUNC_REVERSE_SUBTRACT:
return true;
default:
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, functionName, "invalid mode");
+ synthesizeGLError(GL_INVALID_ENUM, functionName, "invalid mode");
return false;
}
}
bool WebGLRenderingContext::validateBlendFuncFactors(const char* functionName, GC3Denum src, GC3Denum dst)
{
- if (((src == GraphicsContext3D::CONSTANT_COLOR || src == GraphicsContext3D::ONE_MINUS_CONSTANT_COLOR)
- && (dst == GraphicsContext3D::CONSTANT_ALPHA || dst == GraphicsContext3D::ONE_MINUS_CONSTANT_ALPHA))
- || ((dst == GraphicsContext3D::CONSTANT_COLOR || dst == GraphicsContext3D::ONE_MINUS_CONSTANT_COLOR)
- && (src == GraphicsContext3D::CONSTANT_ALPHA || src == GraphicsContext3D::ONE_MINUS_CONSTANT_ALPHA))) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, functionName, "incompatible src and dst");
+ if (((src == GL_CONSTANT_COLOR || src == GL_ONE_MINUS_CONSTANT_COLOR)
+ && (dst == GL_CONSTANT_ALPHA || dst == GL_ONE_MINUS_CONSTANT_ALPHA))
+ || ((dst == GL_CONSTANT_COLOR || dst == GL_ONE_MINUS_CONSTANT_COLOR)
+ && (src == GL_CONSTANT_ALPHA || src == GL_ONE_MINUS_CONSTANT_ALPHA))) {
+ synthesizeGLError(GL_INVALID_OPERATION, functionName, "incompatible src and dst");
return false;
}
return true;
@@ -5025,18 +5047,18 @@ bool WebGLRenderingContext::validateBlendFuncFactors(const char* functionName, G
bool WebGLRenderingContext::validateCapability(const char* functionName, GC3Denum cap)
{
switch (cap) {
- case GraphicsContext3D::BLEND:
- case GraphicsContext3D::CULL_FACE:
- case GraphicsContext3D::DEPTH_TEST:
- case GraphicsContext3D::DITHER:
- case GraphicsContext3D::POLYGON_OFFSET_FILL:
- case GraphicsContext3D::SAMPLE_ALPHA_TO_COVERAGE:
- case GraphicsContext3D::SAMPLE_COVERAGE:
- case GraphicsContext3D::SCISSOR_TEST:
- case GraphicsContext3D::STENCIL_TEST:
+ case GL_BLEND:
+ case GL_CULL_FACE:
+ case GL_DEPTH_TEST:
+ case GL_DITHER:
+ case GL_POLYGON_OFFSET_FILL:
+ case GL_SAMPLE_ALPHA_TO_COVERAGE:
+ case GL_SAMPLE_COVERAGE:
+ case GL_SCISSOR_TEST:
+ case GL_STENCIL_TEST:
return true;
default:
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, functionName, "invalid capability");
+ synthesizeGLError(GL_INVALID_ENUM, functionName, "invalid capability");
return false;
}
}
@@ -5044,7 +5066,7 @@ bool WebGLRenderingContext::validateCapability(const char* functionName, GC3Denu
bool WebGLRenderingContext::validateUniformParameters(const char* functionName, const WebGLUniformLocation* location, Float32Array* v, GC3Dsizei requiredMinSize)
{
if (!v) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "no array");
+ synthesizeGLError(GL_INVALID_VALUE, functionName, "no array");
return false;
}
return validateUniformMatrixParameters(functionName, location, false, v->data(), v->length(), requiredMinSize);
@@ -5053,7 +5075,7 @@ bool WebGLRenderingContext::validateUniformParameters(const char* functionName,
bool WebGLRenderingContext::validateUniformParameters(const char* functionName, const WebGLUniformLocation* location, Int32Array* v, GC3Dsizei requiredMinSize)
{
if (!v) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "no array");
+ synthesizeGLError(GL_INVALID_VALUE, functionName, "no array");
return false;
}
return validateUniformMatrixParameters(functionName, location, false, v->data(), v->length(), requiredMinSize);
@@ -5067,7 +5089,7 @@ bool WebGLRenderingContext::validateUniformParameters(const char* functionName,
bool WebGLRenderingContext::validateUniformMatrixParameters(const char* functionName, const WebGLUniformLocation* location, GC3Dboolean transpose, Float32Array* v, GC3Dsizei requiredMinSize)
{
if (!v) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "no array");
+ synthesizeGLError(GL_INVALID_VALUE, functionName, "no array");
return false;
}
return validateUniformMatrixParameters(functionName, location, transpose, v->data(), v->length(), requiredMinSize);
@@ -5078,19 +5100,19 @@ bool WebGLRenderingContext::validateUniformMatrixParameters(const char* function
if (!location)
return false;
if (location->program() != m_currentProgram) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, functionName, "location is not from current program");
+ synthesizeGLError(GL_INVALID_OPERATION, functionName, "location is not from current program");
return false;
}
if (!v) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "no array");
+ synthesizeGLError(GL_INVALID_VALUE, functionName, "no array");
return false;
}
if (transpose) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "transpose not FALSE");
+ synthesizeGLError(GL_INVALID_VALUE, functionName, "transpose not FALSE");
return false;
}
if (size < requiredMinSize || (size % requiredMinSize)) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "invalid size");
+ synthesizeGLError(GL_INVALID_VALUE, functionName, "invalid size");
return false;
}
return true;
@@ -5100,69 +5122,69 @@ WebGLBuffer* WebGLRenderingContext::validateBufferDataParameters(const char* fun
{
WebGLBuffer* buffer = 0;
switch (target) {
- case GraphicsContext3D::ELEMENT_ARRAY_BUFFER:
+ case GL_ELEMENT_ARRAY_BUFFER:
buffer = m_boundVertexArrayObject->boundElementArrayBuffer().get();
break;
- case GraphicsContext3D::ARRAY_BUFFER:
+ case GL_ARRAY_BUFFER:
buffer = m_boundArrayBuffer.get();
break;
default:
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, functionName, "invalid target");
+ synthesizeGLError(GL_INVALID_ENUM, functionName, "invalid target");
return 0;
}
if (!buffer) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, functionName, "no buffer");
+ synthesizeGLError(GL_INVALID_OPERATION, functionName, "no buffer");
return 0;
}
switch (usage) {
- case GraphicsContext3D::STREAM_DRAW:
- case GraphicsContext3D::STATIC_DRAW:
- case GraphicsContext3D::DYNAMIC_DRAW:
+ case GL_STREAM_DRAW:
+ case GL_STATIC_DRAW:
+ case GL_DYNAMIC_DRAW:
return buffer;
}
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, functionName, "invalid usage");
+ synthesizeGLError(GL_INVALID_ENUM, functionName, "invalid usage");
return 0;
}
-bool WebGLRenderingContext::validateHTMLImageElement(const char* functionName, HTMLImageElement* image, ExceptionState& es)
+bool WebGLRenderingContext::validateHTMLImageElement(const char* functionName, HTMLImageElement* image, ExceptionState& exceptionState)
{
if (!image || !image->cachedImage()) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "no image");
+ synthesizeGLError(GL_INVALID_VALUE, functionName, "no image");
return false;
}
const KURL& url = image->cachedImage()->response().url();
if (url.isNull() || url.isEmpty() || !url.isValid()) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "invalid image");
+ synthesizeGLError(GL_INVALID_VALUE, functionName, "invalid image");
return false;
}
if (wouldTaintOrigin(image)) {
- es.throwSecurityError(ExceptionMessages::failedToExecute(functionName, "WebGLRenderingContext", "the cross-origin image at " + url.elidedString() + " may not be loaded."));
+ exceptionState.throwSecurityError("The cross-origin image at " + url.elidedString() + " may not be loaded.");
return false;
}
return true;
}
-bool WebGLRenderingContext::validateHTMLCanvasElement(const char* functionName, HTMLCanvasElement* canvas, ExceptionState& es)
+bool WebGLRenderingContext::validateHTMLCanvasElement(const char* functionName, HTMLCanvasElement* canvas, ExceptionState& exceptionState)
{
if (!canvas || !canvas->buffer()) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "no canvas");
+ synthesizeGLError(GL_INVALID_VALUE, functionName, "no canvas");
return false;
}
if (wouldTaintOrigin(canvas)) {
- es.throwSecurityError(ExceptionMessages::failedToExecute(functionName, "WebGLRenderingContext", "tainted canvases may not be loded."));
+ exceptionState.throwSecurityError("Tainted canvases may not be loaded.");
return false;
}
return true;
}
-bool WebGLRenderingContext::validateHTMLVideoElement(const char* functionName, HTMLVideoElement* video, ExceptionState& es)
+bool WebGLRenderingContext::validateHTMLVideoElement(const char* functionName, HTMLVideoElement* video, ExceptionState& exceptionState)
{
if (!video || !video->videoWidth() || !video->videoHeight()) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "no video");
+ synthesizeGLError(GL_INVALID_VALUE, functionName, "no video");
return false;
}
if (wouldTaintOrigin(video)) {
- es.throwSecurityError(ExceptionMessages::failedToExecute(functionName, "WebGLRenderingContext", "the video element contains cross-origin data, and may not be loaded."));
+ exceptionState.throwSecurityError("The video element contains cross-origin data, and may not be loaded.");
return false;
}
return true;
@@ -5177,7 +5199,7 @@ bool WebGLRenderingContext::validateDrawArrays(const char* functionName, GC3Denu
return false;
if (first < 0 || count < 0) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "first or count < 0");
+ synthesizeGLError(GL_INVALID_VALUE, functionName, "first or count < 0");
return false;
}
@@ -5187,13 +5209,13 @@ bool WebGLRenderingContext::validateDrawArrays(const char* functionName, GC3Denu
}
if (!validateRenderingState()) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, functionName, "attribs not setup correctly");
+ synthesizeGLError(GL_INVALID_OPERATION, functionName, "attribs not setup correctly");
return false;
}
const char* reason = "framebuffer incomplete";
if (m_framebufferBinding && !m_framebufferBinding->onAccess(graphicsContext3D(), &reason)) {
- synthesizeGLError(GraphicsContext3D::INVALID_FRAMEBUFFER_OPERATION, functionName, reason);
+ synthesizeGLError(GL_INVALID_FRAMEBUFFER_OPERATION, functionName, reason);
return false;
}
@@ -5209,21 +5231,21 @@ bool WebGLRenderingContext::validateDrawElements(const char* functionName, GC3De
return false;
switch (type) {
- case GraphicsContext3D::UNSIGNED_BYTE:
- case GraphicsContext3D::UNSIGNED_SHORT:
+ case GL_UNSIGNED_BYTE:
+ case GL_UNSIGNED_SHORT:
break;
- case GraphicsContext3D::UNSIGNED_INT:
+ case GL_UNSIGNED_INT:
if (m_oesElementIndexUint)
break;
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, functionName, "invalid type");
+ synthesizeGLError(GL_INVALID_ENUM, functionName, "invalid type");
return false;
default:
- synthesizeGLError(GraphicsContext3D::INVALID_ENUM, functionName, "invalid type");
+ synthesizeGLError(GL_INVALID_ENUM, functionName, "invalid type");
return false;
}
if (count < 0 || offset < 0) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "count or offset < 0");
+ synthesizeGLError(GL_INVALID_VALUE, functionName, "count or offset < 0");
return false;
}
@@ -5233,18 +5255,18 @@ bool WebGLRenderingContext::validateDrawElements(const char* functionName, GC3De
}
if (!m_boundVertexArrayObject->boundElementArrayBuffer()) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, functionName, "no ELEMENT_ARRAY_BUFFER bound");
+ synthesizeGLError(GL_INVALID_OPERATION, functionName, "no ELEMENT_ARRAY_BUFFER bound");
return false;
}
if (!validateRenderingState()) {
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, functionName, "attribs not setup correctly");
+ synthesizeGLError(GL_INVALID_OPERATION, functionName, "attribs not setup correctly");
return false;
}
const char* reason = "framebuffer incomplete";
if (m_framebufferBinding && !m_framebufferBinding->onAccess(graphicsContext3D(), &reason)) {
- synthesizeGLError(GraphicsContext3D::INVALID_FRAMEBUFFER_OPERATION, functionName, reason);
+ synthesizeGLError(GL_INVALID_FRAMEBUFFER_OPERATION, functionName, reason);
return false;
}
@@ -5255,7 +5277,7 @@ bool WebGLRenderingContext::validateDrawElements(const char* functionName, GC3De
bool WebGLRenderingContext::validateDrawInstanced(const char* functionName, GC3Dsizei primcount)
{
if (primcount < 0) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "primcount < 0");
+ synthesizeGLError(GL_INVALID_VALUE, functionName, "primcount < 0");
return false;
}
@@ -5266,7 +5288,7 @@ bool WebGLRenderingContext::validateDrawInstanced(const char* functionName, GC3D
return true;
}
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, functionName, "at least one enabled attribute must have a divisor of 0");
+ synthesizeGLError(GL_INVALID_OPERATION, functionName, "at least one enabled attribute must have a divisor of 0");
return false;
}
@@ -5275,7 +5297,7 @@ void WebGLRenderingContext::vertexAttribfImpl(const char* functionName, GC3Duint
if (isContextLost())
return;
if (index >= m_maxVertexAttribs) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "index out of range");
+ synthesizeGLError(GL_INVALID_VALUE, functionName, "index out of range");
return;
}
// In GL, we skip setting vertexAttrib0 values.
@@ -5305,7 +5327,7 @@ void WebGLRenderingContext::vertexAttribfvImpl(const char* functionName, GC3Duin
if (isContextLost())
return;
if (!v) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "no array");
+ synthesizeGLError(GL_INVALID_VALUE, functionName, "no array");
return;
}
vertexAttribfvImpl(functionName, index, v->data(), v->length(), expectedSize);
@@ -5316,15 +5338,15 @@ void WebGLRenderingContext::vertexAttribfvImpl(const char* functionName, GC3Duin
if (isContextLost())
return;
if (!v) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "no array");
+ synthesizeGLError(GL_INVALID_VALUE, functionName, "no array");
return;
}
if (size < expectedSize) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "invalid size");
+ synthesizeGLError(GL_INVALID_VALUE, functionName, "invalid size");
return;
}
if (index >= m_maxVertexAttribs) {
- synthesizeGLError(GraphicsContext3D::INVALID_VALUE, functionName, "index out of range");
+ synthesizeGLError(GL_INVALID_VALUE, functionName, "index out of range");
return;
}
// In GL, we skip setting vertexAttrib0 values.
@@ -5350,7 +5372,7 @@ void WebGLRenderingContext::vertexAttribfvImpl(const char* functionName, GC3Duin
void WebGLRenderingContext::dispatchContextLostEvent(Timer<WebGLRenderingContext>*)
{
- RefPtr<WebGLContextEvent> event = WebGLContextEvent::create(eventNames().webglcontextlostEvent, false, true, "");
+ RefPtr<WebGLContextEvent> event = WebGLContextEvent::create(EventTypeNames::webglcontextlost, false, true, "");
canvas()->dispatchEvent(event);
m_restoreAllowed = event->defaultPrevented();
deactivateContext(this, m_contextLostMode != RealLostContext && m_restoreAllowed);
@@ -5377,7 +5399,7 @@ void WebGLRenderingContext::maybeRestoreContext(Timer<WebGLRenderingContext>*)
Settings* settings = frame->settings();
- if (!frame->loader()->client()->allowWebGL(settings && settings->webGLEnabled()))
+ if (!frame->loader().client()->allowWebGL(settings && settings->webGLEnabled()))
return;
// Reset the context attributes back to the requested attributes and re-apply restrictions
@@ -5386,11 +5408,12 @@ void WebGLRenderingContext::maybeRestoreContext(Timer<WebGLRenderingContext>*)
RefPtr<GraphicsContext3D> context(GraphicsContext3D::create(m_attributes));
if (!context) {
- if (m_contextLostMode == RealLostContext)
+ if (m_contextLostMode == RealLostContext) {
m_restoreTimer.startOneShot(secondsBetweenRestoreAttempts);
- else
+ } else {
// This likely shouldn't happen but is the best way to report it to the WebGL app.
- synthesizeGLError(GraphicsContext3D::INVALID_OPERATION, "", "error restoring context");
+ synthesizeGLError(GL_INVALID_OPERATION, "", "error restoring context");
+ }
return;
}
@@ -5413,7 +5436,7 @@ void WebGLRenderingContext::maybeRestoreContext(Timer<WebGLRenderingContext>*)
setupFlags();
initializeNewContext();
- canvas()->dispatchEvent(WebGLContextEvent::create(eventNames().webglcontextrestoredEvent, false, true, ""));
+ canvas()->dispatchEvent(WebGLContextEvent::create(EventTypeNames::webglcontextrestored, false, true, ""));
}
String WebGLRenderingContext::ensureNotNull(const String& text) const
@@ -5436,13 +5459,13 @@ ImageBuffer* WebGLRenderingContext::LRUImageBufferCache::imageBuffer(const IntSi
ImageBuffer* buf = m_buffers[i].get();
if (!buf)
break;
- if (buf->logicalSize() != size)
+ if (buf->size() != size)
continue;
bubbleToFront(i);
return buf;
}
- OwnPtr<ImageBuffer> temp = ImageBuffer::create(size, 1);
+ OwnPtr<ImageBuffer> temp(ImageBuffer::create(size));
if (!temp)
return 0;
i = std::min(m_capacity - 1, i);
@@ -5464,17 +5487,17 @@ namespace {
String GetErrorString(GC3Denum error)
{
switch (error) {
- case GraphicsContext3D::INVALID_ENUM:
+ case GL_INVALID_ENUM:
return "INVALID_ENUM";
- case GraphicsContext3D::INVALID_VALUE:
+ case GL_INVALID_VALUE:
return "INVALID_VALUE";
- case GraphicsContext3D::INVALID_OPERATION:
+ case GL_INVALID_OPERATION:
return "INVALID_OPERATION";
- case GraphicsContext3D::OUT_OF_MEMORY:
+ case GL_OUT_OF_MEMORY:
return "OUT_OF_MEMORY";
- case GraphicsContext3D::INVALID_FRAMEBUFFER_OPERATION:
+ case GL_INVALID_FRAMEBUFFER_OPERATION:
return "INVALID_FRAMEBUFFER_OPERATION";
- case GraphicsContext3D::CONTEXT_LOST_WEBGL:
+ case GC3D_CONTEXT_LOST_WEBGL:
return "CONTEXT_LOST_WEBGL";
default:
return String::format("WebGL ERROR(0x%04X)", error);
@@ -5518,7 +5541,7 @@ void WebGLRenderingContext::applyStencilTest()
RefPtr<WebGLContextAttributes> attributes = getContextAttributes();
haveStencilBuffer = attributes->stencil();
}
- enableOrDisable(GraphicsContext3D::STENCIL_TEST,
+ enableOrDisable(GL_STENCIL_TEST,
m_stencilEnabled && haveStencilBuffer);
}
@@ -5566,12 +5589,12 @@ void WebGLRenderingContext::setBackDrawBuffer(GC3Denum buf)
void WebGLRenderingContext::restoreCurrentFramebuffer()
{
- bindFramebuffer(GraphicsContext3D::FRAMEBUFFER, m_framebufferBinding.get());
+ bindFramebuffer(GL_FRAMEBUFFER, m_framebufferBinding.get());
}
void WebGLRenderingContext::restoreCurrentTexture2D()
{
- bindTexture(GraphicsContext3D::TEXTURE_2D, m_textureUnits[m_activeTextureUnit].m_texture2DBinding.get());
+ bindTexture(GL_TEXTURE_2D, m_textureUnits[m_activeTextureUnit].m_texture2DBinding.get());
}
void WebGLRenderingContext::multisamplingChanged(bool enabled)
diff --git a/chromium/third_party/WebKit/Source/core/html/canvas/WebGLRenderingContext.h b/chromium/third_party/WebKit/Source/core/html/canvas/WebGLRenderingContext.h
index 5e53d1f6d0f..e1e3911e9f1 100644
--- a/chromium/third_party/WebKit/Source/core/html/canvas/WebGLRenderingContext.h
+++ b/chromium/third_party/WebKit/Source/core/html/canvas/WebGLRenderingContext.h
@@ -30,16 +30,16 @@
#include "core/html/canvas/CanvasRenderingContext.h"
#include "core/html/canvas/WebGLGetInfo.h"
#include "core/page/Page.h"
-#include "core/platform/Timer.h"
-#include "core/platform/graphics/GraphicsContext3D.h"
-#include "core/platform/graphics/ImageBuffer.h"
+#include "platform/Timer.h"
+#include "platform/graphics/GraphicsContext3D.h"
+#include "platform/graphics/ImageBuffer.h"
#include "wtf/Float32Array.h"
#include "wtf/Int32Array.h"
-#include "wtf/OwnArrayPtr.h"
+#include "wtf/OwnPtr.h"
#include "wtf/text/WTFString.h"
-namespace WebKit { class WebLayer; }
+namespace blink { class WebLayer; }
namespace WebCore {
@@ -315,7 +315,7 @@ public:
GraphicsContext3D* graphicsContext3D() const { return m_context.get(); }
WebGLContextGroup* contextGroup() const { return m_contextGroup.get(); }
- virtual WebKit::WebLayer* platformLayer() const;
+ virtual blink::WebLayer* platformLayer() const;
void reshape(int width, int height);
@@ -373,6 +373,8 @@ public:
void addCompressedTextureFormat(GC3Denum);
void removeAllCompressedTextureFormats();
+ PassRefPtr<Image> drawImageIntoBuffer(Image*, int width, int height);
+
PassRefPtr<Image> videoFrameToImage(HTMLVideoElement*, BackingStoreCopy);
WebGLRenderbuffer* ensureEmulatedStencilBuffer(GC3Denum target, WebGLRenderbuffer*);
@@ -459,10 +461,10 @@ public:
ImageBuffer* imageBuffer(const IntSize& size);
private:
void bubbleToFront(int idx);
- OwnArrayPtr<OwnPtr<ImageBuffer> > m_buffers;
+ OwnPtr<OwnPtr<ImageBuffer>[]> m_buffers;
int m_capacity;
};
- LRUImageBufferCache m_videoCache;
+ LRUImageBufferCache m_generatedImageCache;
GC3Dint m_maxTextureSize;
GC3Dint m_maxCubeMapTextureSize;
@@ -542,7 +544,7 @@ public:
class ExtensionTracker {
public:
- ExtensionTracker(ExtensionFlags flags, const char** prefixes)
+ ExtensionTracker(ExtensionFlags flags, const char* const* prefixes)
: m_privileged(flags & PrivilegedExtension)
, m_draft(flags & DraftExtension)
, m_prefixed(flags & PrefixedExtension)
@@ -587,13 +589,13 @@ public:
bool m_draft;
bool m_prefixed;
bool m_webglDebugRendererInfo;
- const char** m_prefixes;
+ const char* const* m_prefixes;
};
template <typename T>
class TypedExtensionTracker : public ExtensionTracker {
public:
- TypedExtensionTracker(RefPtr<T>& extensionField, ExtensionFlags flags, const char** prefixes)
+ TypedExtensionTracker(RefPtr<T>& extensionField, ExtensionFlags flags, const char* const* prefixes)
: ExtensionTracker(flags, prefixes)
, m_extensionField(extensionField)
{
@@ -641,7 +643,7 @@ public:
Vector<ExtensionTracker*> m_extensions;
template <typename T>
- void registerExtension(RefPtr<T>& extensionPtr, ExtensionFlags flags = ApprovedExtension, const char** prefixes = 0)
+ void registerExtension(RefPtr<T>& extensionPtr, ExtensionFlags flags = ApprovedExtension, const char* const* prefixes = 0)
{
m_extensions.append(new TypedExtensionTracker<T>(extensionPtr, flags, prefixes));
}
@@ -924,6 +926,8 @@ public:
static IntSize oldestContextSize();
};
+DEFINE_TYPE_CASTS(WebGLRenderingContext, CanvasRenderingContext, context, context->is3d(), context.is3d());
+
} // namespace WebCore
#endif
diff --git a/chromium/third_party/WebKit/Source/core/html/canvas/WebGLShaderPrecisionFormat.h b/chromium/third_party/WebKit/Source/core/html/canvas/WebGLShaderPrecisionFormat.h
index d20b412baf1..b59acc052a5 100644
--- a/chromium/third_party/WebKit/Source/core/html/canvas/WebGLShaderPrecisionFormat.h
+++ b/chromium/third_party/WebKit/Source/core/html/canvas/WebGLShaderPrecisionFormat.h
@@ -28,7 +28,7 @@
#define WebGLShaderPrecisionFormat_h
#include "bindings/v8/ScriptWrappable.h"
-#include "core/platform/graphics/GraphicsContext3D.h"
+#include "platform/graphics/GraphicsContext3D.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefCounted.h"
diff --git a/chromium/third_party/WebKit/Source/core/html/canvas/WebGLTexture.cpp b/chromium/third_party/WebKit/Source/core/html/canvas/WebGLTexture.cpp
index d01bf83a94b..804547e1b0e 100644
--- a/chromium/third_party/WebKit/Source/core/html/canvas/WebGLTexture.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/canvas/WebGLTexture.cpp
@@ -39,10 +39,10 @@ PassRefPtr<WebGLTexture> WebGLTexture::create(WebGLRenderingContext* ctx)
WebGLTexture::WebGLTexture(WebGLRenderingContext* ctx)
: WebGLSharedObject(ctx)
, m_target(0)
- , m_minFilter(GraphicsContext3D::NEAREST_MIPMAP_LINEAR)
- , m_magFilter(GraphicsContext3D::LINEAR)
- , m_wrapS(GraphicsContext3D::REPEAT)
- , m_wrapT(GraphicsContext3D::REPEAT)
+ , m_minFilter(GL_NEAREST_MIPMAP_LINEAR)
+ , m_magFilter(GL_LINEAR)
+ , m_wrapS(GL_REPEAT)
+ , m_wrapT(GL_REPEAT)
, m_isNPOT(false)
, m_isCubeComplete(false)
, m_isComplete(false)
@@ -67,12 +67,12 @@ void WebGLTexture::setTarget(GC3Denum target, GC3Dint maxLevel)
if (m_target)
return;
switch (target) {
- case GraphicsContext3D::TEXTURE_2D:
+ case GL_TEXTURE_2D:
m_target = target;
m_info.resize(1);
m_info[0].resize(maxLevel);
break;
- case GraphicsContext3D::TEXTURE_CUBE_MAP:
+ case GL_TEXTURE_CUBE_MAP:
m_target = target;
m_info.resize(6);
for (int ii = 0; ii < 6; ++ii)
@@ -86,40 +86,40 @@ void WebGLTexture::setParameteri(GC3Denum pname, GC3Dint param)
if (!object() || !m_target)
return;
switch (pname) {
- case GraphicsContext3D::TEXTURE_MIN_FILTER:
+ case GL_TEXTURE_MIN_FILTER:
switch (param) {
- case GraphicsContext3D::NEAREST:
- case GraphicsContext3D::LINEAR:
- case GraphicsContext3D::NEAREST_MIPMAP_NEAREST:
- case GraphicsContext3D::LINEAR_MIPMAP_NEAREST:
- case GraphicsContext3D::NEAREST_MIPMAP_LINEAR:
- case GraphicsContext3D::LINEAR_MIPMAP_LINEAR:
+ case GL_NEAREST:
+ case GL_LINEAR:
+ case GL_NEAREST_MIPMAP_NEAREST:
+ case GL_LINEAR_MIPMAP_NEAREST:
+ case GL_NEAREST_MIPMAP_LINEAR:
+ case GL_LINEAR_MIPMAP_LINEAR:
m_minFilter = param;
break;
}
break;
- case GraphicsContext3D::TEXTURE_MAG_FILTER:
+ case GL_TEXTURE_MAG_FILTER:
switch (param) {
- case GraphicsContext3D::NEAREST:
- case GraphicsContext3D::LINEAR:
+ case GL_NEAREST:
+ case GL_LINEAR:
m_magFilter = param;
break;
}
break;
- case GraphicsContext3D::TEXTURE_WRAP_S:
+ case GL_TEXTURE_WRAP_S:
switch (param) {
- case GraphicsContext3D::CLAMP_TO_EDGE:
- case GraphicsContext3D::MIRRORED_REPEAT:
- case GraphicsContext3D::REPEAT:
+ case GL_CLAMP_TO_EDGE:
+ case GL_MIRRORED_REPEAT:
+ case GL_REPEAT:
m_wrapS = param;
break;
}
break;
- case GraphicsContext3D::TEXTURE_WRAP_T:
+ case GL_TEXTURE_WRAP_T:
switch (param) {
- case GraphicsContext3D::CLAMP_TO_EDGE:
- case GraphicsContext3D::MIRRORED_REPEAT:
- case GraphicsContext3D::REPEAT:
+ case GL_CLAMP_TO_EDGE:
+ case GL_MIRRORED_REPEAT:
+ case GL_REPEAT:
m_wrapT = param;
break;
}
@@ -239,7 +239,7 @@ bool WebGLTexture::needToUseBlackTexture(TextureExtensionFlag flag) const
if (m_needToUseBlackTexture)
return true;
if ((m_isFloatType && !(flag & TextureFloatLinearExtensionEnabled)) || (m_isHalfFloatType && !(flag && TextureHalfFloatLinearExtensionEnabled))) {
- if (m_magFilter != GraphicsContext3D::NEAREST || (m_minFilter != GraphicsContext3D::NEAREST && m_minFilter != GraphicsContext3D::NEAREST_MIPMAP_NEAREST))
+ if (m_magFilter != GL_NEAREST || (m_minFilter != GL_NEAREST && m_minFilter != GL_NEAREST_MIPMAP_NEAREST))
return true;
}
return false;
@@ -252,22 +252,22 @@ void WebGLTexture::deleteObjectImpl(GraphicsContext3D* context3d, Platform3DObje
int WebGLTexture::mapTargetToIndex(GC3Denum target) const
{
- if (m_target == GraphicsContext3D::TEXTURE_2D) {
- if (target == GraphicsContext3D::TEXTURE_2D)
+ if (m_target == GL_TEXTURE_2D) {
+ if (target == GL_TEXTURE_2D)
return 0;
- } else if (m_target == GraphicsContext3D::TEXTURE_CUBE_MAP) {
+ } else if (m_target == GL_TEXTURE_CUBE_MAP) {
switch (target) {
- case GraphicsContext3D::TEXTURE_CUBE_MAP_POSITIVE_X:
+ case GL_TEXTURE_CUBE_MAP_POSITIVE_X:
return 0;
- case GraphicsContext3D::TEXTURE_CUBE_MAP_NEGATIVE_X:
+ case GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
return 1;
- case GraphicsContext3D::TEXTURE_CUBE_MAP_POSITIVE_Y:
+ case GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
return 2;
- case GraphicsContext3D::TEXTURE_CUBE_MAP_NEGATIVE_Y:
+ case GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
return 3;
- case GraphicsContext3D::TEXTURE_CUBE_MAP_POSITIVE_Z:
+ case GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
return 4;
- case GraphicsContext3D::TEXTURE_CUBE_MAP_NEGATIVE_Z:
+ case GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
return 5;
}
}
@@ -353,19 +353,19 @@ void WebGLTexture::update()
}
}
}
- m_isFloatType = m_info[0][0].type == GraphicsContext3D::FLOAT;
- m_isHalfFloatType = m_info[0][0].type == GraphicsContext3D::HALF_FLOAT_OES;
+ m_isFloatType = m_info[0][0].type == GL_FLOAT;
+ m_isHalfFloatType = m_info[0][0].type == GL_HALF_FLOAT_OES;
m_needToUseBlackTexture = false;
// NPOT
- if (m_isNPOT && ((m_minFilter != GraphicsContext3D::NEAREST && m_minFilter != GraphicsContext3D::LINEAR)
- || m_wrapS != GraphicsContext3D::CLAMP_TO_EDGE || m_wrapT != GraphicsContext3D::CLAMP_TO_EDGE))
+ if (m_isNPOT && ((m_minFilter != GL_NEAREST && m_minFilter != GL_LINEAR)
+ || m_wrapS != GL_CLAMP_TO_EDGE || m_wrapT != GL_CLAMP_TO_EDGE))
m_needToUseBlackTexture = true;
// If it is a Cube texture, check Cube Completeness first
if (m_info.size() > 1 && !m_isCubeComplete)
m_needToUseBlackTexture = true;
// Completeness
- if (!m_isComplete && m_minFilter != GraphicsContext3D::NEAREST && m_minFilter != GraphicsContext3D::LINEAR)
+ if (!m_isComplete && m_minFilter != GL_NEAREST && m_minFilter != GL_LINEAR)
m_needToUseBlackTexture = true;
}
diff --git a/chromium/third_party/WebKit/Source/core/html/canvas/WebGLUniformLocation.h b/chromium/third_party/WebKit/Source/core/html/canvas/WebGLUniformLocation.h
index 2a41d003767..34e0480c126 100644
--- a/chromium/third_party/WebKit/Source/core/html/canvas/WebGLUniformLocation.h
+++ b/chromium/third_party/WebKit/Source/core/html/canvas/WebGLUniformLocation.h
@@ -34,10 +34,8 @@
namespace WebCore {
-class WebGLUniformLocation : public RefCounted<WebGLUniformLocation>, public ScriptWrappable {
+class WebGLUniformLocation FINAL : public RefCounted<WebGLUniformLocation>, public ScriptWrappable {
public:
- virtual ~WebGLUniformLocation() { }
-
static PassRefPtr<WebGLUniformLocation> create(WebGLProgram*, GC3Dint location);
WebGLProgram* program() const;
diff --git a/chromium/third_party/WebKit/Source/core/html/canvas/WebGLVertexArrayObjectOES.cpp b/chromium/third_party/WebKit/Source/core/html/canvas/WebGLVertexArrayObjectOES.cpp
index 44dff92a83b..1d54886af8a 100644
--- a/chromium/third_party/WebKit/Source/core/html/canvas/WebGLVertexArrayObjectOES.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/canvas/WebGLVertexArrayObjectOES.cpp
@@ -28,7 +28,7 @@
#include "core/html/canvas/WebGLVertexArrayObjectOES.h"
#include "core/html/canvas/WebGLRenderingContext.h"
-#include "core/platform/graphics/Extensions3D.h"
+#include "platform/graphics/Extensions3D.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/html/canvas/WebGLVertexArrayObjectOES.h b/chromium/third_party/WebKit/Source/core/html/canvas/WebGLVertexArrayObjectOES.h
index 2d7fe0123fa..8b1fd6ee063 100644
--- a/chromium/third_party/WebKit/Source/core/html/canvas/WebGLVertexArrayObjectOES.h
+++ b/chromium/third_party/WebKit/Source/core/html/canvas/WebGLVertexArrayObjectOES.h
@@ -50,7 +50,7 @@ public:
: enabled(false)
, bytesPerElement(0)
, size(4)
- , type(GraphicsContext3D::FLOAT)
+ , type(GL_FLOAT)
, normalized(false)
, stride(16)
, originalStride(0)
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/BaseButtonInputType.cpp b/chromium/third_party/WebKit/Source/core/html/forms/BaseButtonInputType.cpp
index 3ea90b5398e..a41645c2428 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/BaseButtonInputType.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/forms/BaseButtonInputType.cpp
@@ -37,42 +37,20 @@
#include "core/dom/shadow/ShadowRoot.h"
#include "core/html/HTMLInputElement.h"
#include "core/rendering/RenderButton.h"
-#include "core/rendering/RenderTextFragment.h"
namespace WebCore {
using namespace HTMLNames;
-class NonSelectableText : public Text {
- inline NonSelectableText(Document& document, const String& data)
- : Text(document, data, CreateText)
- {
- }
-
- virtual RenderText* createTextRenderer(RenderStyle*) OVERRIDE
- {
- return new RenderTextFragment(this, dataImpl());
- }
-
-public:
- static inline PassRefPtr<NonSelectableText> create(Document& document, const String& data)
- {
- return adoptRef(new NonSelectableText(document, data));
- }
-};
-
-// ----------------------------
-
void BaseButtonInputType::createShadowSubtree()
{
- ASSERT(element()->userAgentShadowRoot());
- RefPtr<Text> text = NonSelectableText::create(element()->document(), element()->valueWithDefault());
- element()->userAgentShadowRoot()->appendChild(text);
+ ASSERT(element().userAgentShadowRoot());
+ element().userAgentShadowRoot()->appendChild(Text::create(element().document(), element().valueWithDefault()));
}
void BaseButtonInputType::valueAttributeChanged()
{
- toText(element()->userAgentShadowRoot()->firstChild())->setData(element()->valueWithDefault());
+ toText(element().userAgentShadowRoot()->firstChild())->setData(element().valueWithDefault());
}
bool BaseButtonInputType::shouldSaveAndRestoreFormControlState() const
@@ -88,7 +66,7 @@ bool BaseButtonInputType::appendFormData(FormDataList&, bool) const
RenderObject* BaseButtonInputType::createRenderer(RenderStyle*) const
{
- return new RenderButton(element());
+ return new RenderButton(&element());
}
bool BaseButtonInputType::storesValueSeparateFromAttribute()
@@ -98,7 +76,7 @@ bool BaseButtonInputType::storesValueSeparateFromAttribute()
void BaseButtonInputType::setValue(const String& sanitizedValue, bool, TextFieldEventBehavior)
{
- element()->setAttribute(valueAttr, sanitizedValue);
+ element().setAttribute(valueAttr, AtomicString(sanitizedValue));
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/BaseButtonInputType.h b/chromium/third_party/WebKit/Source/core/html/forms/BaseButtonInputType.h
index ee5cbf2c0ab..63f2a37cf12 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/BaseButtonInputType.h
+++ b/chromium/third_party/WebKit/Source/core/html/forms/BaseButtonInputType.h
@@ -38,7 +38,7 @@ namespace WebCore {
// Base of button, file, image, reset, and submit types.
class BaseButtonInputType : public BaseClickableWithKeyInputType {
protected:
- BaseButtonInputType(HTMLInputElement* element) : BaseClickableWithKeyInputType(element) { }
+ BaseButtonInputType(HTMLInputElement& element) : BaseClickableWithKeyInputType(element) { }
private:
virtual void createShadowSubtree() OVERRIDE;
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/BaseCheckableInputType.cpp b/chromium/third_party/WebKit/Source/core/html/forms/BaseCheckableInputType.cpp
index 1e04eba843c..7ffe40b29da 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/BaseCheckableInputType.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/forms/BaseCheckableInputType.cpp
@@ -33,7 +33,7 @@
#include "core/html/forms/BaseCheckableInputType.h"
#include "HTMLNames.h"
-#include "core/dom/KeyboardEvent.h"
+#include "core/events/KeyboardEvent.h"
#include "core/html/FormDataList.h"
#include "core/html/HTMLInputElement.h"
#include "core/html/forms/FormController.h"
@@ -44,19 +44,19 @@ using namespace HTMLNames;
FormControlState BaseCheckableInputType::saveFormControlState() const
{
- return FormControlState(element()->checked() ? "on" : "off");
+ return FormControlState(element().checked() ? "on" : "off");
}
void BaseCheckableInputType::restoreFormControlState(const FormControlState& state)
{
- element()->setChecked(state[0] == "on");
+ element().setChecked(state[0] == "on");
}
bool BaseCheckableInputType::appendFormData(FormDataList& encoding, bool) const
{
- if (!element()->checked())
+ if (!element().checked())
return false;
- encoding.appendData(element()->name(), element()->value());
+ encoding.appendData(element().name(), element().value());
return true;
}
@@ -64,7 +64,7 @@ void BaseCheckableInputType::handleKeydownEvent(KeyboardEvent* event)
{
const String& key = event->keyIdentifier();
if (key == "U+0020") {
- element()->setActive(true, true);
+ element().setActive(true);
// No setDefaultHandled(), because IE dispatches a keypress in this case
// and the caller will only dispatch a keypress if we don't call setDefaultHandled().
}
@@ -88,7 +88,7 @@ void BaseCheckableInputType::accessKeyAction(bool sendMouseEvents)
{
InputType::accessKeyAction(sendMouseEvents);
- element()->dispatchSimulatedClick(0, sendMouseEvents ? SendMouseUpDownEvents : SendNoEvents);
+ element().dispatchSimulatedClick(0, sendMouseEvents ? SendMouseUpDownEvents : SendNoEvents);
}
String BaseCheckableInputType::fallbackValue() const
@@ -103,7 +103,7 @@ bool BaseCheckableInputType::storesValueSeparateFromAttribute()
void BaseCheckableInputType::setValue(const String& sanitizedValue, bool, TextFieldEventBehavior)
{
- element()->setAttribute(valueAttr, sanitizedValue);
+ element().setAttribute(valueAttr, AtomicString(sanitizedValue));
}
bool BaseCheckableInputType::isCheckable()
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/BaseCheckableInputType.h b/chromium/third_party/WebKit/Source/core/html/forms/BaseCheckableInputType.h
index c4453ad3f7e..fdb2fa006ec 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/BaseCheckableInputType.h
+++ b/chromium/third_party/WebKit/Source/core/html/forms/BaseCheckableInputType.h
@@ -38,7 +38,7 @@ namespace WebCore {
// Base of checkbox and radio types.
class BaseCheckableInputType : public InputType {
protected:
- BaseCheckableInputType(HTMLInputElement* element) : InputType(element) { }
+ BaseCheckableInputType(HTMLInputElement& element) : InputType(element) { }
virtual void handleKeydownEvent(KeyboardEvent*);
private:
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/BaseChooserOnlyDateAndTimeInputType.cpp b/chromium/third_party/WebKit/Source/core/html/forms/BaseChooserOnlyDateAndTimeInputType.cpp
index 431d63238d1..3967a8ac871 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/BaseChooserOnlyDateAndTimeInputType.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/forms/BaseChooserOnlyDateAndTimeInputType.cpp
@@ -28,12 +28,12 @@
#include "core/html/forms/BaseChooserOnlyDateAndTimeInputType.h"
#include "bindings/v8/ExceptionStatePlaceholder.h"
-#include "bindings/v8/ScriptController.h"
#include "core/dom/shadow/ShadowRoot.h"
#include "core/html/HTMLDivElement.h"
#include "core/html/HTMLInputElement.h"
#include "core/page/Chrome.h"
#include "core/page/Page.h"
+#include "platform/UserGestureIndicator.h"
namespace WebCore {
@@ -44,32 +44,32 @@ BaseChooserOnlyDateAndTimeInputType::~BaseChooserOnlyDateAndTimeInputType()
void BaseChooserOnlyDateAndTimeInputType::handleDOMActivateEvent(Event*)
{
- if (element()->isDisabledOrReadOnly() || !element()->renderer() || !ScriptController::processingUserGesture() || element()->hasAuthorShadowRoot())
+ if (element().isDisabledOrReadOnly() || !element().renderer() || !UserGestureIndicator::processingUserGesture() || element().hasAuthorShadowRoot())
return;
if (m_dateTimeChooser)
return;
- if (!element()->document().page())
+ if (!element().document().isActive())
return;
DateTimeChooserParameters parameters;
- if (!element()->setupDateTimeChooserParameters(parameters))
+ if (!element().setupDateTimeChooserParameters(parameters))
return;
- m_dateTimeChooser = element()->document().page()->chrome().openDateTimeChooser(this, parameters);
+ m_dateTimeChooser = element().document().page()->chrome().openDateTimeChooser(this, parameters);
}
void BaseChooserOnlyDateAndTimeInputType::createShadowSubtree()
{
DEFINE_STATIC_LOCAL(AtomicString, valueContainerPseudo, ("-webkit-date-and-time-value", AtomicString::ConstructFromLiteral));
- RefPtr<HTMLDivElement> valueContainer = HTMLDivElement::create(element()->document());
- valueContainer->setPart(valueContainerPseudo);
- element()->userAgentShadowRoot()->appendChild(valueContainer.get());
+ RefPtr<HTMLDivElement> valueContainer = HTMLDivElement::create(element().document());
+ valueContainer->setPseudo(valueContainerPseudo);
+ element().userAgentShadowRoot()->appendChild(valueContainer.get());
updateAppearance();
}
void BaseChooserOnlyDateAndTimeInputType::updateAppearance()
{
- Node* node = element()->userAgentShadowRoot()->firstChild();
+ Node* node = element().userAgentShadowRoot()->firstChild();
if (!node || !node->isHTMLElement())
return;
String displayValue = visibleValue();
@@ -87,14 +87,23 @@ void BaseChooserOnlyDateAndTimeInputType::setValue(const String& value, bool val
updateAppearance();
}
-void BaseChooserOnlyDateAndTimeInputType::detach()
+void BaseChooserOnlyDateAndTimeInputType::closePopupView()
{
closeDateTimeChooser();
}
void BaseChooserOnlyDateAndTimeInputType::didChooseValue(const String& value)
{
- element()->setValue(value, DispatchInputAndChangeEvent);
+ element().setValue(value, DispatchInputAndChangeEvent);
+}
+
+void BaseChooserOnlyDateAndTimeInputType::didChooseValue(double value)
+{
+ ASSERT(std::isfinite(value) || std::isnan(value));
+ if (std::isnan(value))
+ element().setValue(emptyString(), DispatchInputAndChangeEvent);
+ else
+ element().setValueAsNumber(value, ASSERT_NO_EXCEPTION, DispatchInputAndChangeEvent);
}
void BaseChooserOnlyDateAndTimeInputType::didEndChooser()
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/BaseChooserOnlyDateAndTimeInputType.h b/chromium/third_party/WebKit/Source/core/html/forms/BaseChooserOnlyDateAndTimeInputType.h
index 001276fd162..4ba1f878ce5 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/BaseChooserOnlyDateAndTimeInputType.h
+++ b/chromium/third_party/WebKit/Source/core/html/forms/BaseChooserOnlyDateAndTimeInputType.h
@@ -29,14 +29,14 @@
#if !ENABLE(INPUT_MULTIPLE_FIELDS_UI)
#include "core/html/forms/BaseClickableWithKeyInputType.h"
#include "core/html/forms/BaseDateAndTimeInputType.h"
-#include "core/platform/DateTimeChooser.h"
-#include "core/platform/DateTimeChooserClient.h"
+#include "platform/DateTimeChooser.h"
+#include "platform/DateTimeChooserClient.h"
namespace WebCore {
class BaseChooserOnlyDateAndTimeInputType : public BaseDateAndTimeInputType, public DateTimeChooserClient {
protected:
- BaseChooserOnlyDateAndTimeInputType(HTMLInputElement* element) : BaseDateAndTimeInputType(element) { }
+ BaseChooserOnlyDateAndTimeInputType(HTMLInputElement& element) : BaseDateAndTimeInputType(element) { }
virtual ~BaseChooserOnlyDateAndTimeInputType();
private:
@@ -45,7 +45,7 @@ private:
// InputType functions:
virtual void createShadowSubtree() OVERRIDE;
- virtual void detach() OVERRIDE;
+ virtual void closePopupView() OVERRIDE;
virtual void setValue(const String&, bool valueChanged, TextFieldEventBehavior) OVERRIDE;
virtual void handleDOMActivateEvent(Event*) OVERRIDE;
virtual void handleKeydownEvent(KeyboardEvent*) OVERRIDE;
@@ -55,6 +55,7 @@ private:
// DateTimeChooserClient functions:
virtual void didChooseValue(const String&) OVERRIDE;
+ virtual void didChooseValue(double) OVERRIDE;
virtual void didEndChooser() OVERRIDE;
RefPtr<DateTimeChooser> m_dateTimeChooser;
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/BaseClickableWithKeyInputType.cpp b/chromium/third_party/WebKit/Source/core/html/forms/BaseClickableWithKeyInputType.cpp
index b58b722ed1c..98ab9b1d9c1 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/BaseClickableWithKeyInputType.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/forms/BaseClickableWithKeyInputType.cpp
@@ -32,28 +32,28 @@
#include "config.h"
#include "core/html/forms/BaseClickableWithKeyInputType.h"
-#include "core/dom/KeyboardEvent.h"
+#include "core/events/KeyboardEvent.h"
#include "core/html/HTMLInputElement.h"
namespace WebCore {
using namespace HTMLNames;
-void BaseClickableWithKeyInputType::handleKeydownEvent(HTMLInputElement* element, KeyboardEvent* event)
+void BaseClickableWithKeyInputType::handleKeydownEvent(HTMLInputElement& element, KeyboardEvent* event)
{
const String& key = event->keyIdentifier();
if (key == "U+0020") {
- element->setActive(true, true);
+ element.setActive(true);
// No setDefaultHandled(), because IE dispatches a keypress in this case
// and the caller will only dispatch a keypress if we don't call setDefaultHandled().
}
}
-void BaseClickableWithKeyInputType::handleKeypressEvent(HTMLInputElement* element, KeyboardEvent* event)
+void BaseClickableWithKeyInputType::handleKeypressEvent(HTMLInputElement& element, KeyboardEvent* event)
{
int charCode = event->charCode();
if (charCode == '\r') {
- element->dispatchSimulatedClick(event);
+ element.dispatchSimulatedClick(event);
event->setDefaultHandled();
return;
}
@@ -73,9 +73,9 @@ void BaseClickableWithKeyInputType::handleKeyupEvent(InputType& inputType, Keybo
}
// FIXME: Could share this with BaseCheckableInputType and RangeInputType if we had a common base class.
-void BaseClickableWithKeyInputType::accessKeyAction(HTMLInputElement* element, bool sendMouseEvents)
+void BaseClickableWithKeyInputType::accessKeyAction(HTMLInputElement& element, bool sendMouseEvents)
{
- element->dispatchSimulatedClick(0, sendMouseEvents ? SendMouseUpDownEvents : SendNoEvents);
+ element.dispatchSimulatedClick(0, sendMouseEvents ? SendMouseUpDownEvents : SendNoEvents);
}
void BaseClickableWithKeyInputType::handleKeydownEvent(KeyboardEvent* event)
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/BaseClickableWithKeyInputType.h b/chromium/third_party/WebKit/Source/core/html/forms/BaseClickableWithKeyInputType.h
index 23b2a2e63da..bd0161de3b1 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/BaseClickableWithKeyInputType.h
+++ b/chromium/third_party/WebKit/Source/core/html/forms/BaseClickableWithKeyInputType.h
@@ -38,13 +38,13 @@ namespace WebCore {
// Base of input types that dispatches a simulated click on space/return key.
class BaseClickableWithKeyInputType : public InputType {
public:
- static void handleKeydownEvent(HTMLInputElement*, KeyboardEvent*);
- static void handleKeypressEvent(HTMLInputElement*, KeyboardEvent*);
+ static void handleKeydownEvent(HTMLInputElement&, KeyboardEvent*);
+ static void handleKeypressEvent(HTMLInputElement&, KeyboardEvent*);
static void handleKeyupEvent(InputType&, KeyboardEvent*);
- static void accessKeyAction(HTMLInputElement*, bool sendMouseEvents);
+ static void accessKeyAction(HTMLInputElement&, bool sendMouseEvents);
protected:
- BaseClickableWithKeyInputType(HTMLInputElement* element) : InputType(element) { }
+ BaseClickableWithKeyInputType(HTMLInputElement& element) : InputType(element) { }
private:
virtual void handleKeydownEvent(KeyboardEvent*) OVERRIDE;
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/BaseDateAndTimeInputType.cpp b/chromium/third_party/WebKit/Source/core/html/forms/BaseDateAndTimeInputType.cpp
index d3c37c24eac..bf87e948cc0 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/BaseDateAndTimeInputType.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/forms/BaseDateAndTimeInputType.cpp
@@ -31,16 +31,17 @@
#include "config.h"
#include "core/html/forms/BaseDateAndTimeInputType.h"
+#include <limits>
#include "core/html/HTMLInputElement.h"
-#include "core/platform/text/PlatformLocale.h"
+#include "platform/text/PlatformLocale.h"
#include "wtf/CurrentTime.h"
#include "wtf/DateMath.h"
#include "wtf/MathExtras.h"
#include "wtf/text/WTFString.h"
-#include <limits>
namespace WebCore {
+using blink::WebLocalizedString;
using namespace HTMLNames;
using namespace std;
@@ -54,18 +55,18 @@ double BaseDateAndTimeInputType::valueAsDate() const
void BaseDateAndTimeInputType::setValueAsDate(double value, ExceptionState&) const
{
- element()->setValue(serializeWithMilliseconds(value));
+ element().setValue(serializeWithMilliseconds(value));
}
double BaseDateAndTimeInputType::valueAsDouble() const
{
- const Decimal value = parseToNumber(element()->value(), Decimal::nan());
+ const Decimal value = parseToNumber(element().value(), Decimal::nan());
return value.isFinite() ? value.toDouble() : DateComponents::invalidMilliseconds();
}
void BaseDateAndTimeInputType::setValueAsDecimal(const Decimal& newValue, TextFieldEventBehavior eventBehavior, ExceptionState&) const
{
- element()->setValue(serialize(newValue), eventBehavior);
+ element().setValue(serialize(newValue), eventBehavior);
}
bool BaseDateAndTimeInputType::typeMismatchFor(const String& value) const
@@ -75,7 +76,17 @@ bool BaseDateAndTimeInputType::typeMismatchFor(const String& value) const
bool BaseDateAndTimeInputType::typeMismatch() const
{
- return typeMismatchFor(element()->value());
+ return typeMismatchFor(element().value());
+}
+
+String BaseDateAndTimeInputType::rangeOverflowText(const Decimal& maximum) const
+{
+ return locale().queryString(WebLocalizedString::ValidationRangeOverflowDateTime, localizeValue(serialize(maximum)));
+}
+
+String BaseDateAndTimeInputType::rangeUnderflowText(const Decimal& minimum) const
+{
+ return locale().queryString(WebLocalizedString::ValidationRangeUnderflowDateTime, localizeValue(serialize(minimum)));
}
Decimal BaseDateAndTimeInputType::defaultValueForStepUp() const
@@ -125,7 +136,7 @@ String BaseDateAndTimeInputType::serialize(const Decimal& value) const
String BaseDateAndTimeInputType::serializeWithComponents(const DateComponents& date) const
{
Decimal step;
- if (!element()->getAllowedValueStep(&step))
+ if (!element().getAllowedValueStep(&step))
return date.toString();
if (step.remainder(msecPerMinute).isZero())
return date.toString(DateComponents::None);
@@ -145,13 +156,13 @@ String BaseDateAndTimeInputType::localizeValue(const String& proposedValue) cons
if (!parseToDateComponents(proposedValue, &date))
return proposedValue;
- String localized = element()->locale().formatDateTime(date);
+ String localized = element().locale().formatDateTime(date);
return localized.isEmpty() ? proposedValue : localized;
}
String BaseDateAndTimeInputType::visibleValue() const
{
- return localizeValue(element()->value());
+ return localizeValue(element().value());
}
String BaseDateAndTimeInputType::sanitizeValue(const String& proposedValue) const
@@ -171,7 +182,7 @@ bool BaseDateAndTimeInputType::shouldRespectListAttribute()
bool BaseDateAndTimeInputType::valueMissing(const String& value) const
{
- return element()->isRequired() && value.isEmpty();
+ return element().isRequired() && value.isEmpty();
}
bool BaseDateAndTimeInputType::shouldShowFocusRingOnMouseFocus() const
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/BaseDateAndTimeInputType.h b/chromium/third_party/WebKit/Source/core/html/forms/BaseDateAndTimeInputType.h
index 3ec0e74d8cf..0bdf559b0f2 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/BaseDateAndTimeInputType.h
+++ b/chromium/third_party/WebKit/Source/core/html/forms/BaseDateAndTimeInputType.h
@@ -32,7 +32,7 @@
#define BaseDateAndTimeInputType_h
#include "core/html/forms/InputType.h"
-#include "core/platform/DateComponents.h"
+#include "platform/DateComponents.h"
namespace WebCore {
@@ -41,7 +41,7 @@ class ExceptionState;
// A super class of date, datetime, datetime-local, month, time, and week types.
class BaseDateAndTimeInputType : public InputType {
protected:
- BaseDateAndTimeInputType(HTMLInputElement* element) : InputType(element) { }
+ BaseDateAndTimeInputType(HTMLInputElement& element) : InputType(element) { }
virtual Decimal parseToNumber(const String&, const Decimal&) const OVERRIDE;
virtual bool parseToDateComponents(const String&, DateComponents*) const OVERRIDE;
virtual String sanitizeValue(const String&) const OVERRIDE;
@@ -52,7 +52,6 @@ protected:
private:
virtual bool parseToDateComponentsInternal(const String&, DateComponents*) const = 0;
- virtual DateComponents::Type dateType() const = 0;
virtual double valueAsDate() const OVERRIDE;
virtual void setValueAsDate(double, ExceptionState&) const OVERRIDE;
virtual double valueAsDouble() const OVERRIDE;
@@ -60,6 +59,8 @@ private:
virtual bool typeMismatchFor(const String&) const OVERRIDE;
virtual bool typeMismatch() const OVERRIDE;
virtual bool valueMissing(const String&) const OVERRIDE;
+ virtual String rangeOverflowText(const Decimal& maximum) const OVERRIDE;
+ virtual String rangeUnderflowText(const Decimal& minimum) const OVERRIDE;
virtual Decimal defaultValueForStepUp() const OVERRIDE;
virtual bool isSteppable() const OVERRIDE;
virtual String serializeWithMilliseconds(double) const;
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/BaseMultipleFieldsDateAndTimeInputType.cpp b/chromium/third_party/WebKit/Source/core/html/forms/BaseMultipleFieldsDateAndTimeInputType.cpp
index 8044e9d5d12..3fbe6236e7b 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/BaseMultipleFieldsDateAndTimeInputType.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/forms/BaseMultipleFieldsDateAndTimeInputType.cpp
@@ -34,22 +34,20 @@
#include "CSSValueKeywords.h"
#include "RuntimeEnabledFeatures.h"
-#include "core/dom/KeyboardEvent.h"
#include "core/dom/shadow/ShadowRoot.h"
+#include "core/events/KeyboardEvent.h"
#include "core/html/HTMLDataListElement.h"
#include "core/html/HTMLInputElement.h"
#include "core/html/HTMLOptionElement.h"
#include "core/html/forms/DateTimeFieldsState.h"
#include "core/html/forms/FormController.h"
-#include "core/html/shadow/PickerIndicatorElement.h"
#include "core/html/shadow/ShadowElementNames.h"
#include "core/page/FocusController.h"
#include "core/page/Page.h"
-#include "core/platform/DateComponents.h"
-#include "core/platform/LocalizedStrings.h"
-#include "core/platform/text/DateTimeFormat.h"
-#include "core/platform/text/PlatformLocale.h"
#include "core/rendering/RenderTheme.h"
+#include "platform/DateComponents.h"
+#include "platform/text/DateTimeFormat.h"
+#include "platform/text/PlatformLocale.h"
#include "wtf/DateMath.h"
namespace WebCore {
@@ -130,27 +128,27 @@ bool DateTimeFormatValidator::validateFormat(const String& format, const BaseMul
DateTimeEditElement* BaseMultipleFieldsDateAndTimeInputType::dateTimeEditElement() const
{
- return toDateTimeEditElement(element()->userAgentShadowRoot()->getElementById(ShadowElementNames::dateTimeEdit()));
+ return toDateTimeEditElement(element().userAgentShadowRoot()->getElementById(ShadowElementNames::dateTimeEdit()));
}
SpinButtonElement* BaseMultipleFieldsDateAndTimeInputType::spinButtonElement() const
{
- return toSpinButtonElement(element()->userAgentShadowRoot()->getElementById(ShadowElementNames::spinButton()));
+ return toSpinButtonElement(element().userAgentShadowRoot()->getElementById(ShadowElementNames::spinButton()));
}
ClearButtonElement* BaseMultipleFieldsDateAndTimeInputType::clearButtonElement() const
{
- return toClearButtonElement(element()->userAgentShadowRoot()->getElementById(ShadowElementNames::clearButton()));
+ return toClearButtonElement(element().userAgentShadowRoot()->getElementById(ShadowElementNames::clearButton()));
}
PickerIndicatorElement* BaseMultipleFieldsDateAndTimeInputType::pickerIndicatorElement() const
{
- return toPickerIndicatorElement(element()->userAgentShadowRoot()->getElementById(ShadowElementNames::pickerIndicator()));
+ return toPickerIndicatorElement(element().userAgentShadowRoot()->getElementById(ShadowElementNames::pickerIndicator()));
}
inline bool BaseMultipleFieldsDateAndTimeInputType::containsFocusedShadowElement() const
{
- return element()->userAgentShadowRoot()->contains(element()->document().focusedElement());
+ return element().userAgentShadowRoot()->contains(element().document().focusedElement());
}
void BaseMultipleFieldsDateAndTimeInputType::didBlurFromControl()
@@ -162,7 +160,7 @@ void BaseMultipleFieldsDateAndTimeInputType::didBlurFromControl()
return;
RefPtr<HTMLInputElement> protector(element());
// Remove focus ring by CSS "focus" pseudo class.
- element()->setFocus(false);
+ element().setFocus(false);
}
void BaseMultipleFieldsDateAndTimeInputType::didFocusOnControl()
@@ -174,7 +172,7 @@ void BaseMultipleFieldsDateAndTimeInputType::didFocusOnControl()
return;
// Add focus ring by CSS "focus" pseudo class.
// FIXME: Setting the focus flag to non-focused element is too tricky.
- element()->setFocus(true);
+ element().setFocus(true);
}
void BaseMultipleFieldsDateAndTimeInputType::editControlValueChanged()
@@ -202,12 +200,12 @@ bool BaseMultipleFieldsDateAndTimeInputType::hasCustomFocusLogic() const
bool BaseMultipleFieldsDateAndTimeInputType::isEditControlOwnerDisabled() const
{
- return element()->isDisabledFormControl();
+ return element().isDisabledFormControl();
}
bool BaseMultipleFieldsDateAndTimeInputType::isEditControlOwnerReadOnly() const
{
- return element()->isReadOnly();
+ return element().isReadOnly();
}
void BaseMultipleFieldsDateAndTimeInputType::focusAndSelectSpinButtonOwner()
@@ -218,7 +216,7 @@ void BaseMultipleFieldsDateAndTimeInputType::focusAndSelectSpinButtonOwner()
bool BaseMultipleFieldsDateAndTimeInputType::shouldSpinButtonRespondToMouseEvents()
{
- return !element()->isDisabledOrReadOnly();
+ return !element().isDisabledOrReadOnly();
}
bool BaseMultipleFieldsDateAndTimeInputType::shouldSpinButtonRespondToWheelEvents()
@@ -244,13 +242,13 @@ void BaseMultipleFieldsDateAndTimeInputType::spinButtonStepUp()
bool BaseMultipleFieldsDateAndTimeInputType::isPickerIndicatorOwnerDisabledOrReadOnly() const
{
- return element()->isDisabledOrReadOnly();
+ return element().isDisabledOrReadOnly();
}
void BaseMultipleFieldsDateAndTimeInputType::pickerIndicatorChooseValue(const String& value)
{
- if (element()->isValidValue(value)) {
- element()->setValue(value, DispatchInputAndChangeEvent);
+ if (element().isValidValue(value)) {
+ element().setValue(value, DispatchInputAndChangeEvent);
return;
}
@@ -263,12 +261,21 @@ void BaseMultipleFieldsDateAndTimeInputType::pickerIndicatorChooseValue(const St
edit->setOnlyYearMonthDay(date);
}
+void BaseMultipleFieldsDateAndTimeInputType::pickerIndicatorChooseValue(double value)
+{
+ ASSERT(std::isfinite(value) || std::isnan(value));
+ if (std::isnan(value))
+ element().setValue(emptyString(), DispatchInputAndChangeEvent);
+ else
+ element().setValueAsNumber(value, ASSERT_NO_EXCEPTION, DispatchInputAndChangeEvent);
+}
+
bool BaseMultipleFieldsDateAndTimeInputType::setupDateTimeChooserParameters(DateTimeChooserParameters& parameters)
{
- return element()->setupDateTimeChooserParameters(parameters);
+ return element().setupDateTimeChooserParameters(parameters);
}
-BaseMultipleFieldsDateAndTimeInputType::BaseMultipleFieldsDateAndTimeInputType(HTMLInputElement* element)
+BaseMultipleFieldsDateAndTimeInputType::BaseMultipleFieldsDateAndTimeInputType(HTMLInputElement& element)
: BaseDateAndTimeInputType(element)
, m_isDestroyingShadowSubtree(false)
, m_pickerIndicatorIsVisible(false)
@@ -290,7 +297,7 @@ BaseMultipleFieldsDateAndTimeInputType::~BaseMultipleFieldsDateAndTimeInputType(
String BaseMultipleFieldsDateAndTimeInputType::badInputText() const
{
- return validationMessageBadInputForDateTimeText();
+ return locale().queryString(blink::WebLocalizedString::ValidationBadInputForDateTime);
}
void BaseMultipleFieldsDateAndTimeInputType::blur()
@@ -307,31 +314,32 @@ PassRefPtr<RenderStyle> BaseMultipleFieldsDateAndTimeInputType::customStyleForRe
newDisplay = INLINE_FLEX;
else if (originalDisplay == BLOCK)
newDisplay = FLEX;
- TextDirection contentDirection = element()->locale().isRTL() ? RTL : LTR;
+ TextDirection contentDirection = element().locale().isRTL() ? RTL : LTR;
if (originalStyle->direction() == contentDirection && originalDisplay == newDisplay)
return originalStyle;
RefPtr<RenderStyle> style = RenderStyle::clone(originalStyle.get());
style->setDirection(contentDirection);
style->setDisplay(newDisplay);
+ style->setUnique();
return style.release();
}
void BaseMultipleFieldsDateAndTimeInputType::createShadowSubtree()
{
- ASSERT(element()->shadow());
+ ASSERT(element().shadow());
// Element must not have a renderer here, because if it did
// DateTimeEditElement::customStyleForRenderer() is called in appendChild()
// before the field wrapper element is created.
// FIXME: This code should not depend on such craziness.
- ASSERT(!element()->renderer());
+ ASSERT(!element().renderer());
- Document& document = element()->document();
- ContainerNode* container = element()->userAgentShadowRoot();
+ Document& document = element().document();
+ ContainerNode* container = element().userAgentShadowRoot();
container->appendChild(DateTimeEditElement::create(document, *this));
- updateInnerTextValue();
+ updateView();
container->appendChild(ClearButtonElement::create(document, *this));
container->appendChild(SpinButtonElement::create(document, *this));
@@ -365,7 +373,7 @@ void BaseMultipleFieldsDateAndTimeInputType::destroyShadowSubtree()
// If a field element has focus, set focus back to the <input> itself before
// deleting the field. This prevents unnecessary focusout/blur events.
if (containsFocusedShadowElement())
- element()->focus();
+ element().focus();
BaseDateAndTimeInputType::destroyShadowSubtree();
m_isDestroyingShadowSubtree = false;
@@ -377,8 +385,8 @@ void BaseMultipleFieldsDateAndTimeInputType::handleFocusEvent(Element* oldFocuse
if (!edit || m_isDestroyingShadowSubtree)
return;
if (direction == FocusDirectionBackward) {
- if (element()->document().page())
- element()->document().page()->focusController().advanceFocus(direction);
+ if (element().document().page())
+ element().document().page()->focusController().advanceFocus(direction);
} else if (direction == FocusDirectionNone || direction == FocusDirectionMouse || direction == FocusDirectionPage) {
edit->focusByOwner(oldFocusedElement);
} else {
@@ -427,17 +435,17 @@ void BaseMultipleFieldsDateAndTimeInputType::handleKeydownEvent(KeyboardEvent* e
bool BaseMultipleFieldsDateAndTimeInputType::hasBadInput() const
{
DateTimeEditElement* edit = dateTimeEditElement();
- return element()->value().isEmpty() && edit && edit->anyEditableFieldsHaveValues();
+ return element().value().isEmpty() && edit && edit->anyEditableFieldsHaveValues();
}
AtomicString BaseMultipleFieldsDateAndTimeInputType::localeIdentifier() const
{
- return element()->computeInheritedLanguage();
+ return element().computeInheritedLanguage();
}
void BaseMultipleFieldsDateAndTimeInputType::minOrMaxAttributeChanged()
{
- updateInnerTextValue();
+ updateView();
}
void BaseMultipleFieldsDateAndTimeInputType::readonlyAttributeChanged()
@@ -455,7 +463,7 @@ void BaseMultipleFieldsDateAndTimeInputType::restoreFormControlState(const FormC
return;
DateTimeFieldsState dateTimeFieldsState = DateTimeFieldsState::restoreFormControlState(state);
edit->setValueAsDateTimeFieldsState(dateTimeFieldsState);
- element()->setValueInternal(sanitizeValue(edit->value()), DispatchNoEvent);
+ element().setValueInternal(sanitizeValue(edit->value()), DispatchNoEvent);
updateClearButtonVisibility();
}
@@ -471,8 +479,8 @@ void BaseMultipleFieldsDateAndTimeInputType::setValue(const String& sanitizedVal
InputType::setValue(sanitizedValue, valueChanged, eventBehavior);
DateTimeEditElement* edit = dateTimeEditElement();
if (valueChanged || (sanitizedValue.isEmpty() && edit && edit->anyEditableFieldsHaveValues())) {
- updateInnerTextValue();
- element()->setNeedsValidityCheck();
+ updateView();
+ element().setNeedsValidityCheck();
}
}
@@ -483,19 +491,19 @@ bool BaseMultipleFieldsDateAndTimeInputType::shouldUseInputMethod() const
void BaseMultipleFieldsDateAndTimeInputType::stepAttributeChanged()
{
- updateInnerTextValue();
+ updateView();
}
-void BaseMultipleFieldsDateAndTimeInputType::updateInnerTextValue()
+void BaseMultipleFieldsDateAndTimeInputType::updateView()
{
DateTimeEditElement* edit = dateTimeEditElement();
if (!edit)
return;
- DateTimeEditElement::LayoutParameters layoutParameters(element()->locale(), createStepRange(AnyIsDefaultStep));
+ DateTimeEditElement::LayoutParameters layoutParameters(element().locale(), createStepRange(AnyIsDefaultStep));
DateComponents date;
- const bool hasValue = parseToDateComponents(element()->value(), &date);
+ const bool hasValue = parseToDateComponents(element().value(), &date);
if (!hasValue)
setMillisecondToDateComponents(layoutParameters.stepRange.minimum().toDouble(), &date);
@@ -517,8 +525,8 @@ void BaseMultipleFieldsDateAndTimeInputType::updateInnerTextValue()
void BaseMultipleFieldsDateAndTimeInputType::valueAttributeChanged()
{
- if (!element()->hasDirtyValue())
- updateInnerTextValue();
+ if (!element().hasDirtyValue())
+ updateView();
}
void BaseMultipleFieldsDateAndTimeInputType::listAttributeTargetChanged()
@@ -533,16 +541,10 @@ void BaseMultipleFieldsDateAndTimeInputType::updatePickerIndicatorVisibility()
return;
}
if (RuntimeEnabledFeatures::dataListElementEnabled()) {
- if (HTMLDataListElement* dataList = element()->dataList()) {
- RefPtr<HTMLCollection> options = dataList->options();
- for (unsigned i = 0; HTMLOptionElement* option = toHTMLOptionElement(options->item(i)); ++i) {
- if (element()->isValidValue(option->value())) {
- showPickerIndicator();
- return;
- }
- }
- }
- hidePickerIndicator();
+ if (element().hasValidDataListOptions())
+ showPickerIndicator();
+ else
+ hidePickerIndicator();
}
}
@@ -574,12 +576,12 @@ bool BaseMultipleFieldsDateAndTimeInputType::shouldHaveSecondField(const DateCom
void BaseMultipleFieldsDateAndTimeInputType::focusAndSelectClearButtonOwner()
{
- element()->focus();
+ element().focus();
}
bool BaseMultipleFieldsDateAndTimeInputType::shouldClearButtonRespondToMouseEvents()
{
- return !element()->isDisabledOrReadOnly() && !element()->isRequired();
+ return !element().isDisabledOrReadOnly() && !element().isRequired();
}
void BaseMultipleFieldsDateAndTimeInputType::clearValue()
@@ -595,10 +597,13 @@ void BaseMultipleFieldsDateAndTimeInputType::updateClearButtonVisibility()
if (!clearButton)
return;
- if (element()->isRequired() || !dateTimeEditElement()->anyEditableFieldsHaveValues())
- clearButton->setInlineStyleProperty(CSSPropertyVisibility, CSSValueHidden);
- else
- clearButton->removeInlineStyleProperty(CSSPropertyVisibility);
+ if (element().isRequired() || !dateTimeEditElement()->anyEditableFieldsHaveValues()) {
+ clearButton->setInlineStyleProperty(CSSPropertyOpacity, 0.0, CSSPrimitiveValue::CSS_NUMBER);
+ clearButton->setInlineStyleProperty(CSSPropertyPointerEvents, CSSValueNone);
+ } else {
+ clearButton->removeInlineStyleProperty(CSSPropertyOpacity);
+ clearButton->removeInlineStyleProperty(CSSPropertyPointerEvents);
+ }
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/BaseMultipleFieldsDateAndTimeInputType.h b/chromium/third_party/WebKit/Source/core/html/forms/BaseMultipleFieldsDateAndTimeInputType.h
index 518ff725474..14a0a2c8171 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/BaseMultipleFieldsDateAndTimeInputType.h
+++ b/chromium/third_party/WebKit/Source/core/html/forms/BaseMultipleFieldsDateAndTimeInputType.h
@@ -53,7 +53,7 @@ public:
virtual bool isValidFormat(bool hasYear, bool hasMonth, bool hasWeek, bool hasDay, bool hasAMPM, bool hasHour, bool hasMinute, bool hasSecond) const = 0;
protected:
- BaseMultipleFieldsDateAndTimeInputType(HTMLInputElement*);
+ BaseMultipleFieldsDateAndTimeInputType(HTMLInputElement&);
virtual ~BaseMultipleFieldsDateAndTimeInputType();
virtual void setupLayoutParameters(DateTimeEditElement::LayoutParameters&, const DateComponents&) const = 0;
@@ -78,6 +78,7 @@ private:
// PickerIndicatorElement::PickerIndicatorOwner functions
virtual bool isPickerIndicatorOwnerDisabledOrReadOnly() const OVERRIDE FINAL;
virtual void pickerIndicatorChooseValue(const String&) OVERRIDE FINAL;
+ virtual void pickerIndicatorChooseValue(double) OVERRIDE FINAL;
virtual bool setupDateTimeChooserParameters(DateTimeChooserParameters&) OVERRIDE FINAL;
// ClearButtonElement::ClearButtonOwner functions.
@@ -105,7 +106,7 @@ private:
virtual void setValue(const String&, bool valueChanged, TextFieldEventBehavior) OVERRIDE FINAL;
virtual bool shouldUseInputMethod() const OVERRIDE FINAL;
virtual void stepAttributeChanged() OVERRIDE FINAL;
- virtual void updateInnerTextValue() OVERRIDE FINAL;
+ virtual void updateView() OVERRIDE FINAL;
virtual void valueAttributeChanged() OVERRIDE;
virtual void listAttributeTargetChanged() OVERRIDE FINAL;
virtual void updateClearButtonVisibility() OVERRIDE FINAL;
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/BaseTextInputType.cpp b/chromium/third_party/WebKit/Source/core/html/forms/BaseTextInputType.cpp
index 54c0e74e0aa..d00d21e98cb 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/BaseTextInputType.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/forms/BaseTextInputType.cpp
@@ -25,8 +25,8 @@
#include "core/html/forms/BaseTextInputType.h"
#include "HTMLNames.h"
+#include "bindings/v8/ScriptRegexp.h"
#include "core/html/HTMLInputElement.h"
-#include "core/platform/text/RegularExpression.h"
namespace WebCore {
@@ -39,14 +39,14 @@ bool BaseTextInputType::isTextType() const
bool BaseTextInputType::patternMismatch(const String& value) const
{
- const AtomicString& rawPattern = element()->fastGetAttribute(patternAttr);
+ const AtomicString& rawPattern = element().fastGetAttribute(patternAttr);
// Empty values can't be mismatched
- if (rawPattern.isNull() || value.isEmpty() || !RegularExpression(rawPattern, TextCaseSensitive).isValid())
+ if (rawPattern.isNull() || value.isEmpty() || !ScriptRegexp(rawPattern, TextCaseSensitive).isValid())
return false;
String pattern = "^(?:" + rawPattern + ")$";
int matchLength = 0;
int valueLength = value.length();
- int matchOffset = RegularExpression(pattern, TextCaseSensitive).match(value, 0, &matchLength);
+ int matchOffset = ScriptRegexp(pattern, TextCaseSensitive).match(value, 0, &matchLength);
return matchOffset || matchLength != valueLength;
}
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/BaseTextInputType.h b/chromium/third_party/WebKit/Source/core/html/forms/BaseTextInputType.h
index 05e2cd5f65a..8c917a0b616 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/BaseTextInputType.h
+++ b/chromium/third_party/WebKit/Source/core/html/forms/BaseTextInputType.h
@@ -39,7 +39,7 @@ namespace WebCore {
// They support maxlength, selection functions, and so on.
class BaseTextInputType : public TextFieldInputType {
protected:
- BaseTextInputType(HTMLInputElement* element) : TextFieldInputType(element) { }
+ BaseTextInputType(HTMLInputElement& element) : TextFieldInputType(element) { }
private:
virtual bool isTextType() const OVERRIDE;
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/ButtonInputType.cpp b/chromium/third_party/WebKit/Source/core/html/forms/ButtonInputType.cpp
index 6b6d0c7ab1c..39e112c03fe 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/ButtonInputType.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/forms/ButtonInputType.cpp
@@ -31,19 +31,19 @@
#include "config.h"
#include "core/html/forms/ButtonInputType.h"
-#include "core/html/forms/InputTypeNames.h"
+#include "InputTypeNames.h"
#include "wtf/PassOwnPtr.h"
namespace WebCore {
-PassRefPtr<InputType> ButtonInputType::create(HTMLInputElement* element)
+PassRefPtr<InputType> ButtonInputType::create(HTMLInputElement& element)
{
return adoptRef(new ButtonInputType(element));
}
const AtomicString& ButtonInputType::formControlType() const
{
- return InputTypeNames::button();
+ return InputTypeNames::button;
}
bool ButtonInputType::supportsValidation() const
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/ButtonInputType.h b/chromium/third_party/WebKit/Source/core/html/forms/ButtonInputType.h
index 8511b88b24a..aa31135602b 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/ButtonInputType.h
+++ b/chromium/third_party/WebKit/Source/core/html/forms/ButtonInputType.h
@@ -37,10 +37,10 @@ namespace WebCore {
class ButtonInputType : public BaseButtonInputType {
public:
- static PassRefPtr<InputType> create(HTMLInputElement*);
+ static PassRefPtr<InputType> create(HTMLInputElement&);
private:
- ButtonInputType(HTMLInputElement* element) : BaseButtonInputType(element) { }
+ ButtonInputType(HTMLInputElement& element) : BaseButtonInputType(element) { }
virtual const AtomicString& formControlType() const OVERRIDE;
virtual bool supportsValidation() const OVERRIDE;
virtual bool isTextButton() const OVERRIDE;
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/CheckboxInputType.cpp b/chromium/third_party/WebKit/Source/core/html/forms/CheckboxInputType.cpp
index 73d4dc3217f..738f9d58b9b 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/CheckboxInputType.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/forms/CheckboxInputType.cpp
@@ -32,32 +32,32 @@
#include "config.h"
#include "core/html/forms/CheckboxInputType.h"
-#include "core/dom/KeyboardEvent.h"
+#include "InputTypeNames.h"
+#include "core/events/KeyboardEvent.h"
#include "core/html/HTMLInputElement.h"
-#include "core/html/forms/InputTypeNames.h"
-#include "core/platform/LocalizedStrings.h"
+#include "platform/text/PlatformLocale.h"
#include "wtf/PassOwnPtr.h"
namespace WebCore {
-PassRefPtr<InputType> CheckboxInputType::create(HTMLInputElement* element)
+PassRefPtr<InputType> CheckboxInputType::create(HTMLInputElement& element)
{
return adoptRef(new CheckboxInputType(element));
}
const AtomicString& CheckboxInputType::formControlType() const
{
- return InputTypeNames::checkbox();
+ return InputTypeNames::checkbox;
}
bool CheckboxInputType::valueMissing(const String&) const
{
- return element()->isRequired() && !element()->checked();
+ return element().isRequired() && !element().checked();
}
String CheckboxInputType::valueMissingText() const
{
- return validationMessageValueMissingForCheckboxText();
+ return locale().queryString(blink::WebLocalizedString::ValidationValueMissingForCheckbox);
}
void CheckboxInputType::handleKeyupEvent(KeyboardEvent* event)
@@ -75,13 +75,13 @@ PassOwnPtr<ClickHandlingState> CheckboxInputType::willDispatchClick()
OwnPtr<ClickHandlingState> state = adoptPtr(new ClickHandlingState);
- state->checked = element()->checked();
- state->indeterminate = element()->indeterminate();
+ state->checked = element().checked();
+ state->indeterminate = element().indeterminate();
if (state->indeterminate)
- element()->setIndeterminate(false);
+ element().setIndeterminate(false);
- element()->setChecked(!state->checked, DispatchChangeEvent);
+ element().setChecked(!state->checked, DispatchChangeEvent);
return state.release();
}
@@ -89,8 +89,8 @@ PassOwnPtr<ClickHandlingState> CheckboxInputType::willDispatchClick()
void CheckboxInputType::didDispatchClick(Event* event, const ClickHandlingState& state)
{
if (event->defaultPrevented() || event->defaultHandled()) {
- element()->setIndeterminate(state.indeterminate);
- element()->setChecked(state.checked);
+ element().setIndeterminate(state.indeterminate);
+ element().setChecked(state.checked);
}
// The work we did in willDispatchClick was default handling.
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/CheckboxInputType.h b/chromium/third_party/WebKit/Source/core/html/forms/CheckboxInputType.h
index 3cef9b921cc..9299018f6b5 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/CheckboxInputType.h
+++ b/chromium/third_party/WebKit/Source/core/html/forms/CheckboxInputType.h
@@ -37,10 +37,10 @@ namespace WebCore {
class CheckboxInputType : public BaseCheckableInputType {
public:
- static PassRefPtr<InputType> create(HTMLInputElement*);
+ static PassRefPtr<InputType> create(HTMLInputElement&);
private:
- CheckboxInputType(HTMLInputElement* element) : BaseCheckableInputType(element) { }
+ CheckboxInputType(HTMLInputElement& element) : BaseCheckableInputType(element) { }
virtual const AtomicString& formControlType() const OVERRIDE;
virtual bool valueMissing(const String&) const OVERRIDE;
virtual String valueMissingText() const OVERRIDE;
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/ColorInputType.cpp b/chromium/third_party/WebKit/Source/core/html/forms/ColorInputType.cpp
index 5c340280644..304504bdfc3 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/ColorInputType.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/forms/ColorInputType.cpp
@@ -32,19 +32,20 @@
#include "core/html/forms/ColorInputType.h"
#include "CSSPropertyNames.h"
+#include "InputTypeNames.h"
#include "RuntimeEnabledFeatures.h"
#include "bindings/v8/ExceptionStatePlaceholder.h"
#include "bindings/v8/ScriptController.h"
-#include "core/dom/MouseEvent.h"
+#include "core/events/MouseEvent.h"
#include "core/dom/shadow/ShadowRoot.h"
#include "core/html/HTMLDataListElement.h"
#include "core/html/HTMLDivElement.h"
#include "core/html/HTMLInputElement.h"
#include "core/html/HTMLOptionElement.h"
-#include "core/html/forms/InputTypeNames.h"
#include "core/page/Chrome.h"
-#include "core/platform/graphics/Color.h"
#include "core/rendering/RenderView.h"
+#include "platform/UserGestureIndicator.h"
+#include "platform/graphics/Color.h"
#include "wtf/PassOwnPtr.h"
#include "wtf/text/WTFString.h"
@@ -52,6 +53,11 @@ namespace WebCore {
using namespace HTMLNames;
+// Upper limit of number of datalist suggestions shown.
+static const unsigned maxSuggestions = 1000;
+// Upper limit for the length of the labels for datalist suggestions.
+static const unsigned maxSuggestionLabelLength = 1000;
+
static bool isValidColorString(const String& value)
{
if (value.isEmpty())
@@ -66,7 +72,7 @@ static bool isValidColorString(const String& value)
return color.isValid() && !color.hasAlpha();
}
-PassRefPtr<InputType> ColorInputType::create(HTMLInputElement* element)
+PassRefPtr<InputType> ColorInputType::create(HTMLInputElement& element)
{
return adoptRef(new ColorInputType(element));
}
@@ -78,7 +84,7 @@ ColorInputType::~ColorInputType()
void ColorInputType::countUsage()
{
- observeFeatureIfVisible(UseCounter::InputTypeColor);
+ countUsageIfVisible(UseCounter::InputTypeColor);
}
bool ColorInputType::isColorControl() const
@@ -88,7 +94,7 @@ bool ColorInputType::isColorControl() const
const AtomicString& ColorInputType::formControlType() const
{
- return InputTypeNames::color();
+ return InputTypeNames::color;
}
bool ColorInputType::supportsRequired() const
@@ -111,20 +117,20 @@ String ColorInputType::sanitizeValue(const String& proposedValue) const
Color ColorInputType::valueAsColor() const
{
- return Color(element()->value());
+ return Color(element().value());
}
void ColorInputType::createShadowSubtree()
{
- ASSERT(element()->shadow());
+ ASSERT(element().shadow());
- Document& document = element()->document();
+ Document& document = element().document();
RefPtr<HTMLDivElement> wrapperElement = HTMLDivElement::create(document);
- wrapperElement->setPart(AtomicString("-webkit-color-swatch-wrapper", AtomicString::ConstructFromLiteral));
+ wrapperElement->setPseudo(AtomicString("-webkit-color-swatch-wrapper", AtomicString::ConstructFromLiteral));
RefPtr<HTMLDivElement> colorSwatch = HTMLDivElement::create(document);
- colorSwatch->setPart(AtomicString("-webkit-color-swatch", AtomicString::ConstructFromLiteral));
+ colorSwatch->setPseudo(AtomicString("-webkit-color-swatch", AtomicString::ConstructFromLiteral));
wrapperElement->appendChild(colorSwatch.release());
- element()->userAgentShadowRoot()->appendChild(wrapperElement.release());
+ element().userAgentShadowRoot()->appendChild(wrapperElement.release());
updateColorSwatch();
}
@@ -143,10 +149,10 @@ void ColorInputType::setValue(const String& value, bool valueChanged, TextFieldE
void ColorInputType::handleDOMActivateEvent(Event* event)
{
- if (element()->isDisabledFormControl() || !element()->renderer())
+ if (element().isDisabledFormControl() || !element().renderer())
return;
- if (!ScriptController::processingUserGesture())
+ if (!UserGestureIndicator::processingUserGesture())
return;
Chrome* chrome = this->chrome();
@@ -156,7 +162,7 @@ void ColorInputType::handleDOMActivateEvent(Event* event)
event->setDefaultHandled();
}
-void ColorInputType::detach()
+void ColorInputType::closePopupView()
{
endColorChooser();
}
@@ -173,11 +179,11 @@ bool ColorInputType::typeMismatchFor(const String& value) const
void ColorInputType::didChooseColor(const Color& color)
{
- if (element()->isDisabledFormControl() || color == valueAsColor())
+ if (element().isDisabledFormControl() || color == valueAsColor())
return;
- element()->setValueFromRenderer(color.serialized());
+ element().setValueFromRenderer(color.serialized());
updateColorSwatch();
- element()->dispatchFormControlChangeEvent();
+ element().dispatchFormControlChangeEvent();
}
void ColorInputType::didEndChooser()
@@ -197,18 +203,18 @@ void ColorInputType::updateColorSwatch()
if (!colorSwatch)
return;
- colorSwatch->setInlineStyleProperty(CSSPropertyBackgroundColor, element()->value());
+ colorSwatch->setInlineStyleProperty(CSSPropertyBackgroundColor, element().value());
}
HTMLElement* ColorInputType::shadowColorSwatch() const
{
- ShadowRoot* shadow = element()->userAgentShadowRoot();
+ ShadowRoot* shadow = element().userAgentShadowRoot();
return shadow ? toHTMLElement(shadow->firstChild()->firstChild()) : 0;
}
IntRect ColorInputType::elementRectRelativeToRootView() const
{
- return element()->document().view()->contentsToRootView(element()->pixelSnappedBoundingBox());
+ return element().document().view()->contentsToRootView(element().pixelSnappedBoundingBox());
}
Color ColorInputType::currentColor()
@@ -219,25 +225,28 @@ Color ColorInputType::currentColor()
bool ColorInputType::shouldShowSuggestions() const
{
if (RuntimeEnabledFeatures::dataListElementEnabled())
- return element()->fastHasAttribute(listAttr);
+ return element().fastHasAttribute(listAttr);
return false;
}
-Vector<Color> ColorInputType::suggestions() const
+Vector<ColorSuggestion> ColorInputType::suggestions() const
{
- Vector<Color> suggestions;
+ Vector<ColorSuggestion> suggestions;
if (RuntimeEnabledFeatures::dataListElementEnabled()) {
- HTMLDataListElement* dataList = element()->dataList();
+ HTMLDataListElement* dataList = element().dataList();
if (dataList) {
RefPtr<HTMLCollection> options = dataList->options();
for (unsigned i = 0; HTMLOptionElement* option = toHTMLOptionElement(options->item(i)); i++) {
- if (!element()->isValidValue(option->value()))
+ if (!element().isValidValue(option->value()))
continue;
Color color(option->value());
if (!color.isValid())
continue;
- suggestions.append(color);
+ ColorSuggestion suggestion(color, option->label().left(maxSuggestionLabelLength));
+ suggestions.append(suggestion);
+ if (suggestions.size() >= maxSuggestions)
+ break;
}
}
}
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/ColorInputType.h b/chromium/third_party/WebKit/Source/core/html/forms/ColorInputType.h
index 3d7340f37e1..b0f7ba3d02b 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/ColorInputType.h
+++ b/chromium/third_party/WebKit/Source/core/html/forms/ColorInputType.h
@@ -32,13 +32,13 @@
#define ColorInputType_h
#include "core/html/forms/BaseClickableWithKeyInputType.h"
-#include "core/platform/ColorChooserClient.h"
+#include "platform/ColorChooserClient.h"
namespace WebCore {
class ColorInputType : public BaseClickableWithKeyInputType, public ColorChooserClient {
public:
- static PassRefPtr<InputType> create(HTMLInputElement*);
+ static PassRefPtr<InputType> create(HTMLInputElement&);
virtual ~ColorInputType();
// ColorChooserClient implementation.
@@ -47,10 +47,10 @@ public:
virtual IntRect elementRectRelativeToRootView() const OVERRIDE;
virtual Color currentColor() OVERRIDE;
virtual bool shouldShowSuggestions() const OVERRIDE;
- virtual Vector<Color> suggestions() const OVERRIDE;
+ virtual Vector<ColorSuggestion> suggestions() const OVERRIDE;
private:
- ColorInputType(HTMLInputElement* element) : BaseClickableWithKeyInputType(element) { }
+ ColorInputType(HTMLInputElement& element) : BaseClickableWithKeyInputType(element) { }
virtual void countUsage() OVERRIDE;
virtual bool isColorControl() const OVERRIDE;
virtual const AtomicString& formControlType() const OVERRIDE;
@@ -60,7 +60,7 @@ private:
virtual void createShadowSubtree() OVERRIDE;
virtual void setValue(const String&, bool valueChanged, TextFieldEventBehavior) OVERRIDE;
virtual void handleDOMActivateEvent(Event*) OVERRIDE;
- virtual void detach() OVERRIDE;
+ virtual void closePopupView() OVERRIDE;
virtual bool shouldRespectListAttribute() OVERRIDE;
virtual bool typeMismatchFor(const String&) const OVERRIDE;
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/DateInputType.cpp b/chromium/third_party/WebKit/Source/core/html/forms/DateInputType.cpp
index 00ac554730d..a820bc8f97b 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/DateInputType.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/forms/DateInputType.cpp
@@ -32,56 +32,47 @@
#include "core/html/forms/DateInputType.h"
#include "HTMLNames.h"
+#include "InputTypeNames.h"
#include "core/html/HTMLInputElement.h"
#include "core/html/forms/DateTimeFieldsState.h"
-#include "core/html/forms/InputTypeNames.h"
-#include "core/platform/DateComponents.h"
-#include "core/platform/LocalizedStrings.h"
-#include "core/platform/text/PlatformLocale.h"
+#include "platform/DateComponents.h"
+#include "platform/text/PlatformLocale.h"
#include "wtf/PassOwnPtr.h"
namespace WebCore {
+using blink::WebLocalizedString;
using namespace HTMLNames;
static const int dateDefaultStep = 1;
static const int dateDefaultStepBase = 0;
static const int dateStepScaleFactor = 86400000;
-inline DateInputType::DateInputType(HTMLInputElement* element)
+inline DateInputType::DateInputType(HTMLInputElement& element)
: BaseDateInputType(element)
{
}
-PassRefPtr<InputType> DateInputType::create(HTMLInputElement* element)
+PassRefPtr<InputType> DateInputType::create(HTMLInputElement& element)
{
return adoptRef(new DateInputType(element));
}
void DateInputType::countUsage()
{
- observeFeatureIfVisible(UseCounter::InputTypeDate);
+ countUsageIfVisible(UseCounter::InputTypeDate);
}
const AtomicString& DateInputType::formControlType() const
{
- return InputTypeNames::date();
-}
-
-DateComponents::Type DateInputType::dateType() const
-{
- return DateComponents::Date;
+ return InputTypeNames::date;
}
StepRange DateInputType::createStepRange(AnyStepHandling anyStepHandling) const
{
DEFINE_STATIC_LOCAL(const StepRange::StepDescription, stepDescription, (dateDefaultStep, dateDefaultStepBase, dateStepScaleFactor, StepRange::ParsedStepValueShouldBeInteger));
- const Decimal stepBase = parseToNumber(element()->fastGetAttribute(minAttr), 0);
- const Decimal minimum = parseToNumber(element()->fastGetAttribute(minAttr), Decimal::fromDouble(DateComponents::minimumDate()));
- const Decimal maximum = parseToNumber(element()->fastGetAttribute(maxAttr), Decimal::fromDouble(DateComponents::maximumDate()));
- const Decimal step = StepRange::parseStep(anyStepHandling, stepDescription, element()->fastGetAttribute(stepAttr));
- return StepRange(stepBase, minimum, maximum, step, stepDescription);
+ return InputType::createStepRange(anyStepHandling, 0, Decimal::fromDouble(DateComponents::minimumDate()), Decimal::fromDouble(DateComponents::maximumDate()), stepDescription);
}
bool DateInputType::parseToDateComponentsInternal(const String& string, DateComponents* out) const
@@ -115,13 +106,13 @@ void DateInputType::setupLayoutParameters(DateTimeEditElement::LayoutParameters&
{
layoutParameters.dateTimeFormat = layoutParameters.locale.dateFormat();
layoutParameters.fallbackDateTimeFormat = "yyyy-MM-dd";
- if (!parseToDateComponents(element()->fastGetAttribute(minAttr), &layoutParameters.minimum))
+ if (!parseToDateComponents(element().fastGetAttribute(minAttr), &layoutParameters.minimum))
layoutParameters.minimum = DateComponents();
- if (!parseToDateComponents(element()->fastGetAttribute(maxAttr), &layoutParameters.maximum))
+ if (!parseToDateComponents(element().fastGetAttribute(maxAttr), &layoutParameters.maximum))
layoutParameters.maximum = DateComponents();
- layoutParameters.placeholderForDay = placeholderForDayOfMonthField();
- layoutParameters.placeholderForMonth = placeholderForMonthField();
- layoutParameters.placeholderForYear = placeholderForYearField();
+ layoutParameters.placeholderForDay = locale().queryString(WebLocalizedString::PlaceholderForDayOfMonthField);
+ layoutParameters.placeholderForMonth = locale().queryString(WebLocalizedString::PlaceholderForMonthField);
+ layoutParameters.placeholderForYear = locale().queryString(WebLocalizedString::PlaceholderForYearField);
}
bool DateInputType::isValidFormat(bool hasYear, bool hasMonth, bool hasWeek, bool hasDay, bool hasAMPM, bool hasHour, bool hasMinute, bool hasSecond) const
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/DateInputType.h b/chromium/third_party/WebKit/Source/core/html/forms/DateInputType.h
index 157278fb14b..2688adf1d93 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/DateInputType.h
+++ b/chromium/third_party/WebKit/Source/core/html/forms/DateInputType.h
@@ -46,13 +46,12 @@ typedef BaseChooserOnlyDateAndTimeInputType BaseDateInputType;
class DateInputType : public BaseDateInputType {
public:
- static PassRefPtr<InputType> create(HTMLInputElement*);
+ static PassRefPtr<InputType> create(HTMLInputElement&);
private:
- DateInputType(HTMLInputElement*);
+ DateInputType(HTMLInputElement&);
virtual void countUsage() OVERRIDE;
virtual const AtomicString& formControlType() const OVERRIDE;
- virtual DateComponents::Type dateType() const OVERRIDE;
virtual StepRange createStepRange(AnyStepHandling) const OVERRIDE;
virtual bool parseToDateComponentsInternal(const String&, DateComponents*) const OVERRIDE;
virtual bool setMillisecondToDateComponents(double, DateComponents*) const OVERRIDE;
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/DateTimeLocalInputType.cpp b/chromium/third_party/WebKit/Source/core/html/forms/DateTimeLocalInputType.cpp
index 420a9cfb6df..60c162dc247 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/DateTimeLocalInputType.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/forms/DateTimeLocalInputType.cpp
@@ -32,42 +32,37 @@
#include "core/html/forms/DateTimeLocalInputType.h"
#include "HTMLNames.h"
+#include "InputTypeNames.h"
#include "bindings/v8/ExceptionState.h"
#include "core/html/HTMLInputElement.h"
#include "core/html/forms/DateTimeFieldsState.h"
-#include "core/html/forms/InputTypeNames.h"
-#include "core/platform/DateComponents.h"
-#include "core/platform/LocalizedStrings.h"
-#include "core/platform/text/PlatformLocale.h"
+#include "platform/DateComponents.h"
+#include "platform/text/PlatformLocale.h"
#include "wtf/PassOwnPtr.h"
#include "wtf/text/WTFString.h"
namespace WebCore {
+using blink::WebLocalizedString;
using namespace HTMLNames;
static const int dateTimeLocalDefaultStep = 60;
static const int dateTimeLocalDefaultStepBase = 0;
static const int dateTimeLocalStepScaleFactor = 1000;
-PassRefPtr<InputType> DateTimeLocalInputType::create(HTMLInputElement* element)
+PassRefPtr<InputType> DateTimeLocalInputType::create(HTMLInputElement& element)
{
return adoptRef(new DateTimeLocalInputType(element));
}
void DateTimeLocalInputType::countUsage()
{
- observeFeatureIfVisible(UseCounter::InputTypeDateTimeLocal);
+ countUsageIfVisible(UseCounter::InputTypeDateTimeLocal);
}
const AtomicString& DateTimeLocalInputType::formControlType() const
{
- return InputTypeNames::datetimelocal();
-}
-
-DateComponents::Type DateTimeLocalInputType::dateType() const
-{
- return DateComponents::DateTimeLocal;
+ return InputTypeNames::datetime_local;
}
double DateTimeLocalInputType::valueAsDate() const
@@ -76,21 +71,17 @@ double DateTimeLocalInputType::valueAsDate() const
return DateComponents::invalidMilliseconds();
}
-void DateTimeLocalInputType::setValueAsDate(double value, ExceptionState& es) const
+void DateTimeLocalInputType::setValueAsDate(double value, ExceptionState& exceptionState) const
{
// valueAsDate doesn't work for the datetime-local type according to the standard.
- InputType::setValueAsDate(value, es);
+ InputType::setValueAsDate(value, exceptionState);
}
StepRange DateTimeLocalInputType::createStepRange(AnyStepHandling anyStepHandling) const
{
DEFINE_STATIC_LOCAL(const StepRange::StepDescription, stepDescription, (dateTimeLocalDefaultStep, dateTimeLocalDefaultStepBase, dateTimeLocalStepScaleFactor, StepRange::ScaledStepValueShouldBeInteger));
- const Decimal stepBase = parseToNumber(element()->fastGetAttribute(minAttr), 0);
- const Decimal minimum = parseToNumber(element()->fastGetAttribute(minAttr), Decimal::fromDouble(DateComponents::minimumDateTime()));
- const Decimal maximum = parseToNumber(element()->fastGetAttribute(maxAttr), Decimal::fromDouble(DateComponents::maximumDateTime()));
- const Decimal step = StepRange::parseStep(anyStepHandling, stepDescription, element()->fastGetAttribute(stepAttr));
- return StepRange(stepBase, minimum, maximum, step, stepDescription);
+ return InputType::createStepRange(anyStepHandling, 0, Decimal::fromDouble(DateComponents::minimumDateTime()), Decimal::fromDouble(DateComponents::maximumDateTime()), stepDescription);
}
bool DateTimeLocalInputType::parseToDateComponentsInternal(const String& string, DateComponents* out) const
@@ -158,13 +149,13 @@ void DateTimeLocalInputType::setupLayoutParameters(DateTimeEditElement::LayoutPa
layoutParameters.dateTimeFormat = layoutParameters.locale.dateTimeFormatWithoutSeconds();
layoutParameters.fallbackDateTimeFormat = "yyyy-MM-dd'T'HH:mm";
}
- if (!parseToDateComponents(element()->fastGetAttribute(minAttr), &layoutParameters.minimum))
+ if (!parseToDateComponents(element().fastGetAttribute(minAttr), &layoutParameters.minimum))
layoutParameters.minimum = DateComponents();
- if (!parseToDateComponents(element()->fastGetAttribute(maxAttr), &layoutParameters.maximum))
+ if (!parseToDateComponents(element().fastGetAttribute(maxAttr), &layoutParameters.maximum))
layoutParameters.maximum = DateComponents();
- layoutParameters.placeholderForDay = placeholderForDayOfMonthField();
- layoutParameters.placeholderForMonth = placeholderForMonthField();
- layoutParameters.placeholderForYear = placeholderForYearField();
+ layoutParameters.placeholderForDay = locale().queryString(WebLocalizedString::PlaceholderForDayOfMonthField);
+ layoutParameters.placeholderForMonth = locale().queryString(WebLocalizedString::PlaceholderForMonthField);
+ layoutParameters.placeholderForYear = locale().queryString(WebLocalizedString::PlaceholderForYearField);
}
bool DateTimeLocalInputType::isValidFormat(bool hasYear, bool hasMonth, bool hasWeek, bool hasDay, bool hasAMPM, bool hasHour, bool hasMinute, bool hasSecond) const
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/DateTimeLocalInputType.h b/chromium/third_party/WebKit/Source/core/html/forms/DateTimeLocalInputType.h
index 699ccdd4605..ade5ac0f8e4 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/DateTimeLocalInputType.h
+++ b/chromium/third_party/WebKit/Source/core/html/forms/DateTimeLocalInputType.h
@@ -46,13 +46,12 @@ typedef BaseChooserOnlyDateAndTimeInputType BaseDateTimeLocalInputType;
class DateTimeLocalInputType : public BaseDateTimeLocalInputType {
public:
- static PassRefPtr<InputType> create(HTMLInputElement*);
+ static PassRefPtr<InputType> create(HTMLInputElement&);
private:
- DateTimeLocalInputType(HTMLInputElement* element) : BaseDateTimeLocalInputType(element) { }
+ DateTimeLocalInputType(HTMLInputElement& element) : BaseDateTimeLocalInputType(element) { }
virtual void countUsage() OVERRIDE;
virtual const AtomicString& formControlType() const OVERRIDE;
- virtual DateComponents::Type dateType() const OVERRIDE;
virtual double valueAsDate() const OVERRIDE;
virtual void setValueAsDate(double, ExceptionState&) const OVERRIDE;
virtual StepRange createStepRange(AnyStepHandling) const;
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/EmailInputType.cpp b/chromium/third_party/WebKit/Source/core/html/forms/EmailInputType.cpp
index e9333963ac6..20db60bf5f2 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/EmailInputType.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/forms/EmailInputType.cpp
@@ -24,13 +24,13 @@
#include "config.h"
#include "core/html/forms/EmailInputType.h"
+#include "InputTypeNames.h"
+#include "bindings/v8/ScriptRegexp.h"
#include "core/html/HTMLInputElement.h"
-#include "core/html/forms/InputTypeNames.h"
#include "core/html/parser/HTMLParserIdioms.h"
#include "core/page/Chrome.h"
#include "core/page/ChromeClient.h"
-#include "core/platform/text/PlatformLocale.h"
-#include "core/platform/text/RegularExpression.h"
+#include "platform/text/PlatformLocale.h"
#include "public/platform/Platform.h"
#include "wtf/PassOwnPtr.h"
#include "wtf/text/StringBuilder.h"
@@ -38,7 +38,7 @@
namespace WebCore {
-using WebKit::WebLocalizedString;
+using blink::WebLocalizedString;
// http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#valid-e-mail-address
static const char localPartCharacters[] = "abcdefghijklmnopqrstuvwxyz0123456789!#$%&'*+/=?^_`{|}~.-";
@@ -88,7 +88,7 @@ String EmailInputType::convertEmailAddressToUnicode(const String& address) const
return address;
String languages = chrome()->client().acceptLanguages();
- String unicodeHost = WebKit::Platform::current()->convertIDNToUnicode(address.substring(atPosition + 1), languages);
+ String unicodeHost = blink::Platform::current()->convertIDNToUnicode(address.substring(atPosition + 1), languages);
StringBuilder builder;
builder.append(address, 0, atPosition + 1);
builder.append(unicodeHost);
@@ -125,7 +125,7 @@ static bool isValidEmailAddress(const String& address)
if (!addressLength)
return false;
- DEFINE_STATIC_LOCAL(const RegularExpression, regExp, (emailPattern, TextCaseInsensitive));
+ DEFINE_STATIC_LOCAL(const ScriptRegexp, regExp, (emailPattern, TextCaseInsensitive));
int matchLength;
int matchOffset = regExp.match(address, 0, &matchLength);
@@ -133,19 +133,27 @@ static bool isValidEmailAddress(const String& address)
return !matchOffset && matchLength == addressLength;
}
-PassRefPtr<InputType> EmailInputType::create(HTMLInputElement* element)
+PassRefPtr<InputType> EmailInputType::create(HTMLInputElement& element)
{
return adoptRef(new EmailInputType(element));
}
void EmailInputType::countUsage()
{
- observeFeatureIfVisible(UseCounter::InputTypeEmail);
+ countUsageIfVisible(UseCounter::InputTypeEmail);
+ bool hasMaxLength = element().fastHasAttribute(HTMLNames::maxlengthAttr);
+ if (hasMaxLength)
+ countUsageIfVisible(UseCounter::InputTypeEmailMaxLength);
+ if (element().multiple()) {
+ countUsageIfVisible(UseCounter::InputTypeEmailMultiple);
+ if (hasMaxLength)
+ countUsageIfVisible(UseCounter::InputTypeEmailMultipleMaxLength);
+ }
}
const AtomicString& EmailInputType::formControlType() const
{
- return InputTypeNames::email();
+ return InputTypeNames::email;
}
// The return value is an invalid email address string if the specified string
@@ -156,7 +164,7 @@ String EmailInputType::findInvalidAddress(const String& value) const
{
if (value.isEmpty())
return String();
- if (!element()->multiple())
+ if (!element().multiple())
return isValidEmailAddress(value) ? String() : value;
Vector<String> addresses;
value.split(',', true, addresses);
@@ -175,12 +183,12 @@ bool EmailInputType::typeMismatchFor(const String& value) const
bool EmailInputType::typeMismatch() const
{
- return typeMismatchFor(element()->value());
+ return typeMismatchFor(element().value());
}
String EmailInputType::typeMismatchText() const
{
- String invalidAddress = findInvalidAddress(element()->value());
+ String invalidAddress = findInvalidAddress(element().value());
ASSERT(!invalidAddress.isNull());
if (invalidAddress.isEmpty())
return locale().queryString(WebLocalizedString::ValidationTypeMismatchForEmailEmpty);
@@ -212,7 +220,7 @@ String EmailInputType::typeMismatchText() const
ASSERT(atIndexInUnicode != kNotFound);
return locale().queryString(WebLocalizedString::ValidationTypeMismatchForEmailInvalidDots, String("."), unicodeAddress.substring(atIndexInUnicode + 1));
}
- if (element()->multiple())
+ if (element().multiple())
return locale().queryString(WebLocalizedString::ValidationTypeMismatchForMultipleEmail);
return locale().queryString(WebLocalizedString::ValidationTypeMismatchForEmail);
}
@@ -230,7 +238,7 @@ bool EmailInputType::supportsSelectionAPI() const
String EmailInputType::sanitizeValue(const String& proposedValue) const
{
String noLineBreakValue = proposedValue.removeCharacters(isHTMLLineBreak);
- if (!element()->multiple())
+ if (!element().multiple())
return stripLeadingAndTrailingHTMLSpaces(noLineBreakValue);
Vector<String> addresses;
noLineBreakValue.split(',', true, addresses);
@@ -246,7 +254,7 @@ String EmailInputType::sanitizeValue(const String& proposedValue) const
String EmailInputType::convertFromVisibleValue(const String& visibleValue) const
{
String sanitizedValue = sanitizeValue(visibleValue);
- if (!element()->multiple())
+ if (!element().multiple())
return convertEmailAddressToASCII(sanitizedValue);
Vector<String> addresses;
sanitizedValue.split(',', true, addresses);
@@ -262,8 +270,8 @@ String EmailInputType::convertFromVisibleValue(const String& visibleValue) const
String EmailInputType::visibleValue() const
{
- String value = element()->value();
- if (!element()->multiple())
+ String value = element().value();
+ if (!element().multiple())
return convertEmailAddressToUnicode(value);
Vector<String> addresses;
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/EmailInputType.h b/chromium/third_party/WebKit/Source/core/html/forms/EmailInputType.h
index aea5fe4f2ec..82bd153a780 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/EmailInputType.h
+++ b/chromium/third_party/WebKit/Source/core/html/forms/EmailInputType.h
@@ -37,10 +37,10 @@ namespace WebCore {
class EmailInputType : public BaseTextInputType {
public:
- static PassRefPtr<InputType> create(HTMLInputElement*);
+ static PassRefPtr<InputType> create(HTMLInputElement&);
private:
- EmailInputType(HTMLInputElement* element) : BaseTextInputType(element) { }
+ EmailInputType(HTMLInputElement& element) : BaseTextInputType(element) { }
virtual void countUsage() OVERRIDE;
virtual const AtomicString& formControlType() const OVERRIDE;
virtual bool typeMismatchFor(const String&) const OVERRIDE;
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/FileInputType.cpp b/chromium/third_party/WebKit/Source/core/html/forms/FileInputType.cpp
index e6018cdf38f..64338a6849d 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/FileInputType.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/forms/FileInputType.cpp
@@ -23,37 +23,38 @@
#include "core/html/forms/FileInputType.h"
#include "HTMLNames.h"
+#include "InputTypeNames.h"
#include "RuntimeEnabledFeatures.h"
#include "bindings/v8/ExceptionStatePlaceholder.h"
-#include "bindings/v8/ScriptController.h"
-#include "core/dom/Event.h"
#include "core/dom/shadow/ShadowRoot.h"
+#include "core/events/Event.h"
#include "core/fileapi/File.h"
#include "core/fileapi/FileList.h"
#include "core/html/FormDataList.h"
#include "core/html/HTMLInputElement.h"
#include "core/html/forms/FormController.h"
-#include "core/html/forms/InputTypeNames.h"
#include "core/page/Chrome.h"
-#include "core/platform/DragData.h"
-#include "core/platform/FileSystem.h"
-#include "core/platform/LocalizedStrings.h"
+#include "core/page/DragData.h"
#include "core/rendering/RenderFileUploadControl.h"
+#include "platform/FileMetadata.h"
+#include "platform/UserGestureIndicator.h"
+#include "platform/text/PlatformLocale.h"
#include "wtf/PassOwnPtr.h"
#include "wtf/text/StringBuilder.h"
#include "wtf/text/WTFString.h"
namespace WebCore {
+using blink::WebLocalizedString;
using namespace HTMLNames;
-inline FileInputType::FileInputType(HTMLInputElement* element)
+inline FileInputType::FileInputType(HTMLInputElement& element)
: BaseClickableWithKeyInputType(element)
, m_fileList(FileList::create())
{
}
-PassRefPtr<InputType> FileInputType::create(HTMLInputElement* element)
+PassRefPtr<InputType> FileInputType::create(HTMLInputElement& element)
{
return adoptRef(new FileInputType(element));
}
@@ -72,7 +73,7 @@ Vector<FileChooserFileInfo> FileInputType::filesFromFormControlState(const FormC
const AtomicString& FileInputType::formControlType() const
{
- return InputTypeNames::file();
+ return InputTypeNames::file;
}
FormControlState FileInputType::saveFormControlState() const
@@ -97,7 +98,7 @@ void FileInputType::restoreFormControlState(const FormControlState& state)
bool FileInputType::appendFormData(FormDataList& encoding, bool multipart) const
{
- FileList* fileList = element()->files();
+ FileList* fileList = element().files();
unsigned numFiles = fileList->length();
if (!multipart) {
// Send only the basenames.
@@ -108,59 +109,59 @@ bool FileInputType::appendFormData(FormDataList& encoding, bool multipart) const
// submission of file inputs, and Firefox doesn't add "name=" query
// parameter.
for (unsigned i = 0; i < numFiles; ++i)
- encoding.appendData(element()->name(), fileList->item(i)->name());
+ encoding.appendData(element().name(), fileList->item(i)->name());
return true;
}
// If no filename at all is entered, return successful but empty.
// Null would be more logical, but Netscape posts an empty file. Argh.
if (!numFiles) {
- encoding.appendBlob(element()->name(), File::create(""));
+ encoding.appendBlob(element().name(), File::create(""));
return true;
}
for (unsigned i = 0; i < numFiles; ++i)
- encoding.appendBlob(element()->name(), fileList->item(i));
+ encoding.appendBlob(element().name(), fileList->item(i));
return true;
}
bool FileInputType::valueMissing(const String& value) const
{
- return element()->isRequired() && value.isEmpty();
+ return element().isRequired() && value.isEmpty();
}
String FileInputType::valueMissingText() const
{
- return element()->multiple() ? validationMessageValueMissingForMultipleFileText() : validationMessageValueMissingForFileText();
+ return locale().queryString(element().multiple() ? WebLocalizedString::ValidationValueMissingForMultipleFile : WebLocalizedString::ValidationValueMissingForFile);
}
void FileInputType::handleDOMActivateEvent(Event* event)
{
- if (element()->isDisabledFormControl())
+ if (element().isDisabledFormControl())
return;
- if (!ScriptController::processingUserGesture())
+ if (!UserGestureIndicator::processingUserGesture())
return;
if (Chrome* chrome = this->chrome()) {
FileChooserSettings settings;
- HTMLInputElement* input = element();
- settings.allowsDirectoryUpload = RuntimeEnabledFeatures::directoryUploadEnabled() && input->fastHasAttribute(webkitdirectoryAttr);
- settings.allowsMultipleFiles = settings.allowsDirectoryUpload || input->fastHasAttribute(multipleAttr);
- settings.acceptMIMETypes = input->acceptMIMETypes();
- settings.acceptFileExtensions = input->acceptFileExtensions();
+ HTMLInputElement& input = element();
+ settings.allowsDirectoryUpload = RuntimeEnabledFeatures::directoryUploadEnabled() && input.fastHasAttribute(webkitdirectoryAttr);
+ settings.allowsMultipleFiles = settings.allowsDirectoryUpload || input.fastHasAttribute(multipleAttr);
+ settings.acceptMIMETypes = input.acceptMIMETypes();
+ settings.acceptFileExtensions = input.acceptFileExtensions();
settings.selectedFiles = m_fileList->paths();
#if ENABLE(MEDIA_CAPTURE)
- settings.useMediaCapture = input->capture();
+ settings.useMediaCapture = input.capture();
#endif
- chrome->runOpenPanel(input->document().frame(), newFileChooser(settings));
+ chrome->runOpenPanel(input.document().frame(), newFileChooser(settings));
}
event->setDefaultHandled();
}
RenderObject* FileInputType::createRenderer(RenderStyle*) const
{
- return new RenderFileUploadControl(element());
+ return new RenderFileUploadControl(&element());
}
bool FileInputType::canSetStringValue() const
@@ -202,7 +203,7 @@ bool FileInputType::getTypeSpecificValue(String& value)
void FileInputType::setValue(const String&, bool, TextFieldEventBehavior)
{
m_fileList->clear();
- element()->setNeedsStyleRecalc();
+ element().setNeedsStyleRecalc();
}
PassRefPtr<FileList> FileInputType::createFileList(const Vector<FileChooserFileInfo>& files) const
@@ -213,7 +214,7 @@ PassRefPtr<FileList> FileInputType::createFileList(const Vector<FileChooserFileI
// If a directory is being selected, the UI allows a directory to be chosen
// and the paths provided here share a root directory somewhere up the tree;
// we want to store only the relative paths from that point.
- if (size && element()->fastHasAttribute(webkitdirectoryAttr) && RuntimeEnabledFeatures::directoryUploadEnabled()) {
+ if (size && element().fastHasAttribute(webkitdirectoryAttr) && RuntimeEnabledFeatures::directoryUploadEnabled()) {
// Find the common root path.
String rootPath = directoryName(files[0].path);
for (size_t i = 1; i < size; i++) {
@@ -245,26 +246,26 @@ bool FileInputType::isFileUpload() const
void FileInputType::createShadowSubtree()
{
- ASSERT(element()->shadow());
- RefPtr<HTMLInputElement> button = HTMLInputElement::create(inputTag, element()->document(), 0, false);
- button->setType(InputTypeNames::button());
- button->setAttribute(valueAttr, element()->multiple() ? fileButtonChooseMultipleFilesLabel() : fileButtonChooseFileLabel());
- button->setPart(AtomicString("-webkit-file-upload-button", AtomicString::ConstructFromLiteral));
- element()->userAgentShadowRoot()->appendChild(button.release());
+ ASSERT(element().shadow());
+ RefPtr<HTMLInputElement> button = HTMLInputElement::create(element().document(), 0, false);
+ button->setType(InputTypeNames::button);
+ button->setAttribute(valueAttr, locale().queryString(element().multiple() ? WebLocalizedString::FileButtonChooseMultipleFilesLabel : WebLocalizedString::FileButtonChooseFileLabel));
+ button->setPseudo(AtomicString("-webkit-file-upload-button", AtomicString::ConstructFromLiteral));
+ element().userAgentShadowRoot()->appendChild(button.release());
}
void FileInputType::disabledAttributeChanged()
{
- ASSERT(element()->shadow());
- if (Element* button = toElement(element()->userAgentShadowRoot()->firstChild()))
- button->setBooleanAttribute(disabledAttr, element()->isDisabledFormControl());
+ ASSERT(element().shadow());
+ if (Element* button = toElement(element().userAgentShadowRoot()->firstChild()))
+ button->setBooleanAttribute(disabledAttr, element().isDisabledFormControl());
}
void FileInputType::multipleAttributeChanged()
{
- ASSERT(element()->shadow());
- if (Element* button = toElement(element()->userAgentShadowRoot()->firstChild()))
- button->setAttribute(valueAttr, element()->multiple() ? fileButtonChooseMultipleFilesLabel() : fileButtonChooseFileLabel());
+ ASSERT(element().shadow());
+ if (Element* button = toElement(element().userAgentShadowRoot()->firstChild()))
+ button->setAttribute(valueAttr, locale().queryString(element().multiple() ? WebLocalizedString::FileButtonChooseMultipleFilesLabel : WebLocalizedString::FileButtonChooseFileLabel));
}
void FileInputType::setFiles(PassRefPtr<FileList> files)
@@ -272,7 +273,7 @@ void FileInputType::setFiles(PassRefPtr<FileList> files)
if (!files)
return;
- RefPtr<HTMLInputElement> input = element();
+ RefPtr<HTMLInputElement> input(element());
bool pathsChanged = false;
if (files->length() != m_fileList->length()) {
@@ -316,12 +317,12 @@ void FileInputType::receiveDropForDirectoryUpload(const Vector<String>& paths)
{
if (Chrome* chrome = this->chrome()) {
FileChooserSettings settings;
- HTMLInputElement* input = element();
+ HTMLInputElement& input = element();
settings.allowsDirectoryUpload = true;
settings.allowsMultipleFiles = true;
settings.selectedFiles.append(paths[0]);
- settings.acceptMIMETypes = input->acceptMIMETypes();
- settings.acceptFileExtensions = input->acceptFileExtensions();
+ settings.acceptMIMETypes = input.acceptMIMETypes();
+ settings.acceptFileExtensions = input.acceptFileExtensions();
chrome->enumerateChosenDirectory(newFileChooser(settings));
}
}
@@ -333,8 +334,8 @@ bool FileInputType::receiveDroppedFiles(const DragData* dragData)
if (paths.isEmpty())
return false;
- HTMLInputElement* input = element();
- if (input->fastHasAttribute(webkitdirectoryAttr) && RuntimeEnabledFeatures::directoryUploadEnabled()) {
+ HTMLInputElement& input = element();
+ if (input.fastHasAttribute(webkitdirectoryAttr) && RuntimeEnabledFeatures::directoryUploadEnabled()) {
receiveDropForDirectoryUpload(paths);
return true;
}
@@ -345,7 +346,7 @@ bool FileInputType::receiveDroppedFiles(const DragData* dragData)
for (unsigned i = 0; i < paths.size(); ++i)
files.append(FileChooserFileInfo(paths[i]));
- if (input->fastHasAttribute(multipleAttr)) {
+ if (input.fastHasAttribute(multipleAttr)) {
filesChosen(files);
} else {
Vector<FileChooserFileInfo> firstFileOnly;
@@ -365,9 +366,7 @@ String FileInputType::defaultToolTip() const
FileList* fileList = m_fileList.get();
unsigned listSize = fileList->length();
if (!listSize) {
- if (element()->multiple())
- return fileButtonNoFilesSelectedLabel();
- return fileButtonNoFileSelectedLabel();
+ return locale().queryString(WebLocalizedString::FileButtonNoFileSelectedLabel);
}
StringBuilder names;
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/FileInputType.h b/chromium/third_party/WebKit/Source/core/html/forms/FileInputType.h
index f96f5c4ef8a..a91ba75e2be 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/FileInputType.h
+++ b/chromium/third_party/WebKit/Source/core/html/forms/FileInputType.h
@@ -33,7 +33,7 @@
#define FileInputType_h
#include "core/html/forms/BaseClickableWithKeyInputType.h"
-#include "core/platform/FileChooser.h"
+#include "platform/FileChooser.h"
#include "wtf/RefPtr.h"
namespace WebCore {
@@ -43,11 +43,11 @@ class FileList;
class FileInputType : public BaseClickableWithKeyInputType, private FileChooserClient {
public:
- static PassRefPtr<InputType> create(HTMLInputElement*);
+ static PassRefPtr<InputType> create(HTMLInputElement&);
static Vector<FileChooserFileInfo> filesFromFormControlState(const FormControlState&);
private:
- FileInputType(HTMLInputElement*);
+ FileInputType(HTMLInputElement&);
virtual const AtomicString& formControlType() const OVERRIDE;
virtual FormControlState saveFormControlState() const OVERRIDE;
virtual void restoreFormControlState(const FormControlState&) OVERRIDE;
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/FormController.cpp b/chromium/third_party/WebKit/Source/core/html/forms/FormController.cpp
index bcf7b279331..a3cd9b02100 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/FormController.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/forms/FormController.cpp
@@ -24,7 +24,7 @@
#include "core/html/HTMLFormControlElementWithState.h"
#include "core/html/HTMLFormElement.h"
#include "core/html/HTMLInputElement.h"
-#include "core/platform/FileChooser.h"
+#include "platform/FileChooser.h"
#include "wtf/Deque.h"
#include "wtf/HashTableDeletedValueType.h"
#include "wtf/text/StringBuilder.h"
@@ -294,7 +294,7 @@ class FormKeyGenerator {
public:
static PassOwnPtr<FormKeyGenerator> create() { return adoptPtr(new FormKeyGenerator); }
- AtomicString formKey(const HTMLFormControlElementWithState&);
+ const AtomicString& formKey(const HTMLFormControlElementWithState&);
void willDeleteForm(HTMLFormElement*);
private:
@@ -342,11 +342,11 @@ static inline String formSignature(const HTMLFormElement& form)
return builder.toString();
}
-AtomicString FormKeyGenerator::formKey(const HTMLFormControlElementWithState& control)
+const AtomicString& FormKeyGenerator::formKey(const HTMLFormControlElementWithState& control)
{
HTMLFormElement* form = ownerFormForState(control);
if (!form) {
- DEFINE_STATIC_LOCAL(AtomicString, formKeyForNoOwner, ("No owner", AtomicString::ConstructFromLiteral));
+ DEFINE_STATIC_LOCAL(const AtomicString, formKeyForNoOwner, ("No owner", AtomicString::ConstructFromLiteral));
return formKeyForNoOwner;
}
FormToKeyMap::const_iterator it = m_formToKeyMap.find(form);
@@ -358,13 +358,12 @@ AtomicString FormKeyGenerator::formKey(const HTMLFormControlElementWithState& co
FormSignatureToNextIndexMap::AddResult result = m_formSignatureToNextIndexMap.add(signature, 0);
unsigned nextIndex = result.iterator->value++;
- StringBuilder builder;
- builder.append(signature);
- builder.appendLiteral(" #");
- builder.appendNumber(nextIndex);
- AtomicString formKey = builder.toAtomicString();
- m_formToKeyMap.add(form, formKey);
- return formKey;
+ StringBuilder formKeyBuilder;
+ formKeyBuilder.append(signature);
+ formKeyBuilder.appendLiteral(" #");
+ formKeyBuilder.appendNumber(nextIndex);
+ FormToKeyMap::AddResult addFormKeyresult = m_formToKeyMap.add(form, formKeyBuilder.toAtomicString());
+ return addFormKeyresult.iterator->value;
}
void FormKeyGenerator::willDeleteForm(HTMLFormElement* form)
@@ -401,7 +400,7 @@ PassOwnPtr<FormController::SavedFormStateMap> FormController::createSavedFormSta
ASSERT(control->inDocument());
if (!control->shouldSaveAndRestoreFormControlState())
continue;
- SavedFormStateMap::AddResult result = stateMap->add(keyGenerator->formKey(*control).impl(), nullptr);
+ SavedFormStateMap::AddResult result = stateMap->add(keyGenerator->formKey(*control), nullptr);
if (result.isNewEntry)
result.iterator->value = SavedFormState::create();
result.iterator->value->appendControlState(control->name(), control->type(), control->saveFormControlState());
@@ -436,7 +435,7 @@ FormControlState FormController::takeStateForFormElement(const HTMLFormControlEl
return FormControlState();
if (!m_formKeyGenerator)
m_formKeyGenerator = FormKeyGenerator::create();
- SavedFormStateMap::iterator it = m_savedFormStateMap.find(m_formKeyGenerator->formKey(control).impl());
+ SavedFormStateMap::iterator it = m_savedFormStateMap.find(m_formKeyGenerator->formKey(control));
if (it == m_savedFormStateMap.end())
return FormControlState();
FormControlState state = it->value->takeControlState(control.name(), control.type());
@@ -460,7 +459,7 @@ void FormController::formStatesFromStateVector(const Vector<String>& stateVector
i = 0;
break;
}
- map.add(formKey.impl(), state.release());
+ map.add(formKey, state.release());
}
if (i != stateVector.size())
map.clear();
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/HiddenInputType.cpp b/chromium/third_party/WebKit/Source/core/html/forms/HiddenInputType.cpp
index 512522e749e..7609742da68 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/HiddenInputType.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/forms/HiddenInputType.cpp
@@ -33,24 +33,24 @@
#include "core/html/forms/HiddenInputType.h"
#include "HTMLNames.h"
+#include "InputTypeNames.h"
#include "core/html/FormDataList.h"
#include "core/html/HTMLInputElement.h"
#include "core/html/forms/FormController.h"
-#include "core/html/forms/InputTypeNames.h"
#include "wtf/PassOwnPtr.h"
namespace WebCore {
using namespace HTMLNames;
-PassRefPtr<InputType> HiddenInputType::create(HTMLInputElement* element)
+PassRefPtr<InputType> HiddenInputType::create(HTMLInputElement& element)
{
return adoptRef(new HiddenInputType(element));
}
const AtomicString& HiddenInputType::formControlType() const
{
- return InputTypeNames::hidden();
+ return InputTypeNames::hidden;
}
FormControlState HiddenInputType::saveFormControlState() const
@@ -59,12 +59,12 @@ FormControlState HiddenInputType::saveFormControlState() const
// controls create by createElement() or cloneNode(). It's ok for
// now because we restore values only to form controls created by
// parsing.
- return element()->valueAttributeWasUpdatedAfterParsing() ? FormControlState(element()->value()) : FormControlState();
+ return element().valueAttributeWasUpdatedAfterParsing() ? FormControlState(element().value()) : FormControlState();
}
void HiddenInputType::restoreFormControlState(const FormControlState& state)
{
- element()->setAttribute(valueAttr, state[0]);
+ element().setAttribute(valueAttr, AtomicString(state[0]));
}
bool HiddenInputType::supportsValidation() const
@@ -94,7 +94,7 @@ bool HiddenInputType::storesValueSeparateFromAttribute()
void HiddenInputType::setValue(const String& sanitizedValue, bool, TextFieldEventBehavior)
{
- element()->setAttribute(valueAttr, sanitizedValue);
+ element().setAttribute(valueAttr, AtomicString(sanitizedValue));
}
bool HiddenInputType::isHiddenType() const
@@ -104,8 +104,8 @@ bool HiddenInputType::isHiddenType() const
bool HiddenInputType::appendFormData(FormDataList& encoding, bool isMultipartForm) const
{
- if (equalIgnoringCase(element()->name(), "_charset_")) {
- encoding.appendData(element()->name(), String(encoding.encoding().name()));
+ if (equalIgnoringCase(element().name(), "_charset_")) {
+ encoding.appendData(element().name(), String(encoding.encoding().name()));
return true;
}
return InputType::appendFormData(encoding, isMultipartForm);
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/HiddenInputType.h b/chromium/third_party/WebKit/Source/core/html/forms/HiddenInputType.h
index 9f20f749fd8..a93b5c34fa7 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/HiddenInputType.h
+++ b/chromium/third_party/WebKit/Source/core/html/forms/HiddenInputType.h
@@ -37,10 +37,10 @@ namespace WebCore {
class HiddenInputType : public InputType {
public:
- static PassRefPtr<InputType> create(HTMLInputElement*);
+ static PassRefPtr<InputType> create(HTMLInputElement&);
private:
- HiddenInputType(HTMLInputElement* element) : InputType(element) { }
+ HiddenInputType(HTMLInputElement& element) : InputType(element) { }
virtual const AtomicString& formControlType() const OVERRIDE;
virtual FormControlState saveFormControlState() const OVERRIDE;
virtual void restoreFormControlState(const FormControlState&) OVERRIDE;
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/ImageInputType.cpp b/chromium/third_party/WebKit/Source/core/html/forms/ImageInputType.cpp
index f0b17329913..a8a8d5143ca 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/ImageInputType.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/forms/ImageInputType.cpp
@@ -24,34 +24,35 @@
#include "core/html/forms/ImageInputType.h"
#include "HTMLNames.h"
-#include "core/dom/MouseEvent.h"
+#include "InputTypeNames.h"
+#include "core/events/MouseEvent.h"
#include "core/fetch/ImageResource.h"
#include "core/html/FormDataList.h"
#include "core/html/HTMLFormElement.h"
#include "core/html/HTMLImageLoader.h"
#include "core/html/HTMLInputElement.h"
-#include "core/html/forms/InputTypeNames.h"
#include "core/html/parser/HTMLParserIdioms.h"
#include "core/rendering/RenderImage.h"
#include "wtf/PassOwnPtr.h"
+#include "wtf/text/StringBuilder.h"
namespace WebCore {
using namespace HTMLNames;
-inline ImageInputType::ImageInputType(HTMLInputElement* element)
+inline ImageInputType::ImageInputType(HTMLInputElement& element)
: BaseButtonInputType(element)
{
}
-PassRefPtr<InputType> ImageInputType::create(HTMLInputElement* element)
+PassRefPtr<InputType> ImageInputType::create(HTMLInputElement& element)
{
return adoptRef(new ImageInputType(element));
}
const AtomicString& ImageInputType::formControlType() const
{
- return InputTypeNames::image();
+ return InputTypeNames::image;
}
bool ImageInputType::isFormDataAppendable() const
@@ -61,9 +62,9 @@ bool ImageInputType::isFormDataAppendable() const
bool ImageInputType::appendFormData(FormDataList& encoding, bool) const
{
- if (!element()->isActivatedSubmit())
+ if (!element().isActivatedSubmit())
return false;
- const AtomicString& name = element()->name();
+ const AtomicString& name = element().name();
if (name.isEmpty()) {
encoding.appendData("x", m_clickLocation.x());
encoding.appendData("y", m_clickLocation.y());
@@ -75,28 +76,42 @@ bool ImageInputType::appendFormData(FormDataList& encoding, bool) const
encoding.appendData(name + dotXString, m_clickLocation.x());
encoding.appendData(name + dotYString, m_clickLocation.y());
- if (!element()->value().isEmpty())
- encoding.appendData(name, element()->value());
+ if (!element().value().isEmpty())
+ encoding.appendData(name, element().value());
return true;
}
+String ImageInputType::resultForDialogSubmit() const
+{
+ StringBuilder result;
+ result.appendNumber(m_clickLocation.x());
+ result.append(",");
+ result.appendNumber(m_clickLocation.y());
+ return result.toString();
+}
+
bool ImageInputType::supportsValidation() const
{
return false;
}
+static IntPoint extractClickLocation(Event* event)
+{
+ if (!event->underlyingEvent() || !event->underlyingEvent()->isMouseEvent())
+ return IntPoint();
+ MouseEvent* mouseEvent = toMouseEvent(event->underlyingEvent());
+ if (mouseEvent->isSimulated())
+ return IntPoint();
+ return IntPoint(mouseEvent->offsetX(), mouseEvent->offsetY());
+}
+
void ImageInputType::handleDOMActivateEvent(Event* event)
{
- RefPtr<HTMLInputElement> element = this->element();
+ RefPtr<HTMLInputElement> element(this->element());
if (element->isDisabledFormControl() || !element->form())
return;
element->setActivatedSubmit(true);
- if (event->underlyingEvent() && event->underlyingEvent()->isMouseEvent()) {
- MouseEvent* mouseEvent = toMouseEvent(event->underlyingEvent());
- m_clickLocation = IntPoint(mouseEvent->offsetX(), mouseEvent->offsetY());
- } else {
- m_clickLocation = IntPoint();
- }
+ m_clickLocation = extractClickLocation(event);
element->form()->prepareForSubmission(event); // Event handlers can run.
element->setActivatedSubmit(false);
event->setDefaultHandled();
@@ -104,14 +119,14 @@ void ImageInputType::handleDOMActivateEvent(Event* event)
RenderObject* ImageInputType::createRenderer(RenderStyle*) const
{
- RenderImage* image = new RenderImage(element());
+ RenderImage* image = new RenderImage(&element());
image->setImageResource(RenderImageResource::create());
return image;
}
void ImageInputType::altAttributeChanged()
{
- RenderImage* image = toRenderImage(element()->renderer());
+ RenderImage* image = toRenderImage(element().renderer());
if (!image)
return;
image->updateAltText();
@@ -119,19 +134,19 @@ void ImageInputType::altAttributeChanged()
void ImageInputType::srcAttributeChanged()
{
- if (!element()->renderer())
+ if (!element().renderer())
return;
- element()->imageLoader()->updateFromElementIgnoringPreviousError();
+ element().imageLoader()->updateFromElementIgnoringPreviousError();
}
-void ImageInputType::attach()
+void ImageInputType::startResourceLoading()
{
- BaseButtonInputType::attach();
+ BaseButtonInputType::startResourceLoading();
- HTMLImageLoader* imageLoader = element()->imageLoader();
+ HTMLImageLoader* imageLoader = element().imageLoader();
imageLoader->updateFromElement();
- RenderImage* renderer = toRenderImage(element()->renderer());
+ RenderImage* renderer = toRenderImage(element().renderer());
if (!renderer)
return;
@@ -174,7 +189,7 @@ bool ImageInputType::shouldRespectHeightAndWidthAttributes()
unsigned ImageInputType::height() const
{
- RefPtr<HTMLInputElement> element = this->element();
+ RefPtr<HTMLInputElement> element(this->element());
if (!element->renderer()) {
// Check the attribute first for an explicit pixel value.
@@ -198,7 +213,7 @@ unsigned ImageInputType::height() const
unsigned ImageInputType::width() const
{
- RefPtr<HTMLInputElement> element = this->element();
+ RefPtr<HTMLInputElement> element(this->element());
if (!element->renderer()) {
// Check the attribute first for an explicit pixel value.
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/ImageInputType.h b/chromium/third_party/WebKit/Source/core/html/forms/ImageInputType.h
index c3a5d76929f..d033e2a61c2 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/ImageInputType.h
+++ b/chromium/third_party/WebKit/Source/core/html/forms/ImageInputType.h
@@ -34,25 +34,26 @@
#define ImageInputType_h
#include "core/html/forms/BaseButtonInputType.h"
-#include "core/platform/graphics/IntPoint.h"
+#include "platform/geometry/IntPoint.h"
namespace WebCore {
class ImageInputType : public BaseButtonInputType {
public:
- static PassRefPtr<InputType> create(HTMLInputElement*);
+ static PassRefPtr<InputType> create(HTMLInputElement&);
private:
- ImageInputType(HTMLInputElement*);
+ ImageInputType(HTMLInputElement&);
virtual const AtomicString& formControlType() const OVERRIDE;
virtual bool isFormDataAppendable() const OVERRIDE;
virtual bool appendFormData(FormDataList&, bool) const OVERRIDE;
+ virtual String resultForDialogSubmit() const OVERRIDE;
virtual bool supportsValidation() const OVERRIDE;
virtual RenderObject* createRenderer(RenderStyle*) const OVERRIDE;
virtual void handleDOMActivateEvent(Event*) OVERRIDE;
virtual void altAttributeChanged() OVERRIDE;
virtual void srcAttributeChanged() OVERRIDE;
- virtual void attach() OVERRIDE;
+ virtual void startResourceLoading() OVERRIDE;
virtual bool shouldRespectAlignAttribute() OVERRIDE;
virtual bool canBeSuccessfulSubmitButton() OVERRIDE;
virtual bool isImageButton() const OVERRIDE;
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/InputType.cpp b/chromium/third_party/WebKit/Source/core/html/forms/InputType.cpp
index 371097aae21..c443f6d2025 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/InputType.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/forms/InputType.cpp
@@ -28,12 +28,12 @@
#include "config.h"
#include "core/html/forms/InputType.h"
+#include "InputTypeNames.h"
#include "RuntimeEnabledFeatures.h"
#include "core/accessibility/AXObjectCache.h"
-#include "core/dom/KeyboardEvent.h"
#include "core/dom/NodeRenderStyle.h"
-#include "core/dom/ScopedEventQueue.h"
-#include "core/dom/shadow/ShadowRoot.h"
+#include "core/events/KeyboardEvent.h"
+#include "core/events/ScopedEventQueue.h"
#include "core/fileapi/FileList.h"
#include "core/html/FormDataList.h"
#include "core/html/HTMLInputElement.h"
@@ -47,7 +47,6 @@
#include "core/html/forms/FormController.h"
#include "core/html/forms/HiddenInputType.h"
#include "core/html/forms/ImageInputType.h"
-#include "core/html/forms/InputTypeNames.h"
#include "core/html/forms/MonthInputType.h"
#include "core/html/forms/NumberInputType.h"
#include "core/html/forms/PasswordInputType.h"
@@ -64,46 +63,45 @@
#include "core/html/parser/HTMLParserIdioms.h"
#include "core/html/shadow/HTMLShadowElement.h"
#include "core/page/Page.h"
-#include "core/platform/LocalizedStrings.h"
-#include "core/platform/text/PlatformLocale.h"
-#include "core/platform/text/TextBreakIterator.h"
#include "core/rendering/RenderTheme.h"
+#include "platform/text/PlatformLocale.h"
+#include "platform/text/TextBreakIterator.h"
namespace WebCore {
-using WebKit::WebLocalizedString;
+using blink::WebLocalizedString;
using namespace HTMLNames;
using namespace std;
-typedef PassRefPtr<InputType> (*InputTypeFactoryFunction)(HTMLInputElement*);
+typedef PassRefPtr<InputType> (*InputTypeFactoryFunction)(HTMLInputElement&);
typedef HashMap<AtomicString, InputTypeFactoryFunction, CaseFoldingHash> InputTypeFactoryMap;
static PassOwnPtr<InputTypeFactoryMap> createInputTypeFactoryMap()
{
OwnPtr<InputTypeFactoryMap> map = adoptPtr(new InputTypeFactoryMap);
- map->add(InputTypeNames::button(), ButtonInputType::create);
- map->add(InputTypeNames::checkbox(), CheckboxInputType::create);
+ map->add(InputTypeNames::button, ButtonInputType::create);
+ map->add(InputTypeNames::checkbox, CheckboxInputType::create);
if (RuntimeEnabledFeatures::inputTypeColorEnabled())
- map->add(InputTypeNames::color(), ColorInputType::create);
- map->add(InputTypeNames::date(), DateInputType::create);
- map->add(InputTypeNames::datetimelocal(), DateTimeLocalInputType::create);
- map->add(InputTypeNames::email(), EmailInputType::create);
- map->add(InputTypeNames::file(), FileInputType::create);
- map->add(InputTypeNames::hidden(), HiddenInputType::create);
- map->add(InputTypeNames::image(), ImageInputType::create);
- map->add(InputTypeNames::month(), MonthInputType::create);
- map->add(InputTypeNames::number(), NumberInputType::create);
- map->add(InputTypeNames::password(), PasswordInputType::create);
- map->add(InputTypeNames::radio(), RadioInputType::create);
- map->add(InputTypeNames::range(), RangeInputType::create);
- map->add(InputTypeNames::reset(), ResetInputType::create);
- map->add(InputTypeNames::search(), SearchInputType::create);
- map->add(InputTypeNames::submit(), SubmitInputType::create);
- map->add(InputTypeNames::telephone(), TelephoneInputType::create);
- map->add(InputTypeNames::time(), TimeInputType::create);
- map->add(InputTypeNames::url(), URLInputType::create);
+ map->add(InputTypeNames::color, ColorInputType::create);
+ map->add(InputTypeNames::date, DateInputType::create);
+ map->add(InputTypeNames::datetime_local, DateTimeLocalInputType::create);
+ map->add(InputTypeNames::email, EmailInputType::create);
+ map->add(InputTypeNames::file, FileInputType::create);
+ map->add(InputTypeNames::hidden, HiddenInputType::create);
+ map->add(InputTypeNames::image, ImageInputType::create);
+ map->add(InputTypeNames::month, MonthInputType::create);
+ map->add(InputTypeNames::number, NumberInputType::create);
+ map->add(InputTypeNames::password, PasswordInputType::create);
+ map->add(InputTypeNames::radio, RadioInputType::create);
+ map->add(InputTypeNames::range, RangeInputType::create);
+ map->add(InputTypeNames::reset, ResetInputType::create);
+ map->add(InputTypeNames::search, SearchInputType::create);
+ map->add(InputTypeNames::submit, SubmitInputType::create);
+ map->add(InputTypeNames::tel, TelephoneInputType::create);
+ map->add(InputTypeNames::time, TimeInputType::create);
+ map->add(InputTypeNames::url, URLInputType::create);
if (RuntimeEnabledFeatures::inputTypeWeekEnabled())
- map->add(InputTypeNames::week(), WeekInputType::create);
+ map->add(InputTypeNames::week, WeekInputType::create);
// No need to register "text" because it is the default type.
return map.release();
}
@@ -114,7 +112,7 @@ static const InputTypeFactoryMap* factoryMap()
return factoryMap;
}
-PassRefPtr<InputType> InputType::create(HTMLInputElement* element, const AtomicString& typeName)
+PassRefPtr<InputType> InputType::create(HTMLInputElement& element, const AtomicString& typeName)
{
InputTypeFactoryFunction factory = typeName.isEmpty() ? 0 : factoryMap()->get(typeName);
if (!factory)
@@ -122,7 +120,7 @@ PassRefPtr<InputType> InputType::create(HTMLInputElement* element, const AtomicS
return factory(element);
}
-PassRefPtr<InputType> InputType::createText(HTMLInputElement* element)
+PassRefPtr<InputType> InputType::createText(HTMLInputElement& element)
{
return TextInputType::create(element);
}
@@ -130,9 +128,9 @@ PassRefPtr<InputType> InputType::createText(HTMLInputElement* element)
const AtomicString& InputType::normalizeTypeName(const AtomicString& typeName)
{
if (typeName.isEmpty())
- return InputTypeNames::text();
+ return InputTypeNames::text;
InputTypeFactoryMap::const_iterator it = factoryMap()->find(typeName);
- return it == factoryMap()->end() ? InputTypeNames::text() : it->key;
+ return it == factoryMap()->end() ? InputTypeNames::text : it->key;
}
bool InputType::canChangeFromAnotherType(const AtomicString& normalizedTypeName)
@@ -142,7 +140,7 @@ bool InputType::canChangeFromAnotherType(const AtomicString& normalizedTypeName)
// field's value to something like /etc/passwd and then change it to a file
// input. I don't think this would actually occur in Blink, but this rule
// still may be important for compatibility.
- return normalizedTypeName != InputTypeNames::file();
+ return normalizedTypeName != InputTypeNames::file;
}
InputType::~InputType()
@@ -176,38 +174,43 @@ bool InputType::shouldSaveAndRestoreFormControlState() const
FormControlState InputType::saveFormControlState() const
{
- String currentValue = element()->value();
- if (currentValue == element()->defaultValue())
+ String currentValue = element().value();
+ if (currentValue == element().defaultValue())
return FormControlState();
return FormControlState(currentValue);
}
void InputType::restoreFormControlState(const FormControlState& state)
{
- element()->setValue(state[0]);
+ element().setValue(state[0]);
}
bool InputType::isFormDataAppendable() const
{
// There is no form data unless there's a name for non-image types.
- return !element()->name().isEmpty();
+ return !element().name().isEmpty();
}
bool InputType::appendFormData(FormDataList& encoding, bool) const
{
// Always successful.
- encoding.appendData(element()->name(), element()->value());
+ encoding.appendData(element().name(), element().value());
return true;
}
+String InputType::resultForDialogSubmit() const
+{
+ return element().fastGetAttribute(valueAttr);
+}
+
double InputType::valueAsDate() const
{
return DateComponents::invalidMilliseconds();
}
-void InputType::setValueAsDate(double, ExceptionState& es) const
+void InputType::setValueAsDate(double, ExceptionState& exceptionState) const
{
- es.throwDOMException(InvalidStateError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
}
double InputType::valueAsDouble() const
@@ -215,14 +218,14 @@ double InputType::valueAsDouble() const
return numeric_limits<double>::quiet_NaN();
}
-void InputType::setValueAsDouble(double doubleValue, TextFieldEventBehavior eventBehavior, ExceptionState& es) const
+void InputType::setValueAsDouble(double doubleValue, TextFieldEventBehavior eventBehavior, ExceptionState& exceptionState) const
{
- setValueAsDecimal(Decimal::fromDouble(doubleValue), eventBehavior, es);
+ setValueAsDecimal(Decimal::fromDouble(doubleValue), eventBehavior, exceptionState);
}
-void InputType::setValueAsDecimal(const Decimal&, TextFieldEventBehavior, ExceptionState& es) const
+void InputType::setValueAsDecimal(const Decimal&, TextFieldEventBehavior, ExceptionState& exceptionState) const
{
- es.throwDOMException(InvalidStateError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
}
bool InputType::supportsValidation() const
@@ -341,22 +344,34 @@ bool InputType::stepMismatch(const String& value) const
String InputType::badInputText() const
{
ASSERT_NOT_REACHED();
- return validationMessageTypeMismatchText();
+ return locale().queryString(WebLocalizedString::ValidationTypeMismatch);
+}
+
+String InputType::rangeOverflowText(const Decimal&) const
+{
+ ASSERT_NOT_REACHED();
+ return String();
+}
+
+String InputType::rangeUnderflowText(const Decimal&) const
+{
+ ASSERT_NOT_REACHED();
+ return String();
}
String InputType::typeMismatchText() const
{
- return validationMessageTypeMismatchText();
+ return locale().queryString(WebLocalizedString::ValidationTypeMismatch);
}
String InputType::valueMissingText() const
{
- return validationMessageValueMissingText();
+ return locale().queryString(WebLocalizedString::ValidationValueMissing);
}
String InputType::validationMessage() const
{
- const String value = element()->value();
+ const String value = element().value();
// The order of the following checks is meaningful. e.g. We'd like to show the
// badInput message even if the control has other validation errors.
@@ -370,10 +385,10 @@ String InputType::validationMessage() const
return typeMismatchText();
if (patternMismatch(value))
- return validationMessagePatternMismatchText();
+ return locale().queryString(WebLocalizedString::ValidationPatternMismatch);
- if (element()->tooLong())
- return locale().validationMessageTooLongText(value.length(), element()->maxLength());
+ if (element().tooLong())
+ return locale().validationMessageTooLongText(value.length(), element().maxLength());
if (!isSteppable())
return emptyString();
@@ -385,10 +400,10 @@ String InputType::validationMessage() const
StepRange stepRange(createStepRange(RejectAny));
if (numericValue < stepRange.minimum())
- return locale().queryString(WebLocalizedString::ValidationRangeUnderflow, localizeValue(serialize(stepRange.minimum())));
+ return rangeUnderflowText(stepRange.minimum());
if (numericValue > stepRange.maximum())
- return locale().queryString(WebLocalizedString::ValidationRangeOverflow, localizeValue(serialize(stepRange.maximum())));
+ return rangeOverflowText(stepRange.maximum());
if (stepRange.stepMismatch(numericValue)) {
ASSERT(stepRange.hasStep());
@@ -408,29 +423,7 @@ String InputType::validationMessage() const
bool InputType::shouldSubmitImplicitly(Event* event)
{
- return event->isKeyboardEvent() && event->type() == eventNames().keypressEvent && toKeyboardEvent(event)->charCode() == '\r';
-}
-
-void InputType::createShadowSubtree()
-{
-}
-
-void InputType::destroyShadowSubtree()
-{
- ShadowRoot* root = element()->userAgentShadowRoot();
- if (!root)
- return;
-
- root->removeChildren();
-
- // It's ok to clear contents of all other UA ShadowRoots because they must
- // have been created by InputFieldPasswordGeneratorButtonElement.
- // FIXME: Remove the PasswordGeneratorButtonElement's shadow root and then
- // remove this loop.
- while ((root = root->youngerShadowRoot()) && root->type() == ShadowRoot::UserAgentShadowRoot) {
- root->removeChildren();
- root->appendChild(HTMLShadowElement::create(shadowTag, element()->document()));
- }
+ return event->isKeyboardEvent() && event->type() == EventTypeNames::keypress && toKeyboardEvent(event)->charCode() == '\r';
}
Decimal InputType::parseToNumber(const String&, const Decimal& defaultValue) const
@@ -458,21 +451,21 @@ String InputType::serialize(const Decimal&) const
void InputType::dispatchSimulatedClickIfActive(KeyboardEvent* event) const
{
- if (element()->active())
- element()->dispatchSimulatedClick(event);
+ if (element().active())
+ element().dispatchSimulatedClick(event);
event->setDefaultHandled();
}
Chrome* InputType::chrome() const
{
- if (Page* page = element()->document().page())
+ if (Page* page = element().document().page())
return &page->chrome();
return 0;
}
Locale& InputType::locale() const
{
- return element()->locale();
+ return element().locale();
}
bool InputType::canSetStringValue() const
@@ -487,7 +480,7 @@ bool InputType::hasCustomFocusLogic() const
bool InputType::isKeyboardFocusable() const
{
- return element()->isFocusable();
+ return element().isFocusable();
}
bool InputType::shouldShowFocusRingOnMouseFocus() const
@@ -510,11 +503,7 @@ void InputType::disableSecureTextInput()
void InputType::accessKeyAction(bool)
{
- element()->focus(false);
-}
-
-void InputType::detach()
-{
+ element().focus(false);
}
void InputType::countUsage()
@@ -581,17 +570,17 @@ bool InputType::storesValueSeparateFromAttribute()
void InputType::setValue(const String& sanitizedValue, bool valueChanged, TextFieldEventBehavior eventBehavior)
{
- element()->setValueInternal(sanitizedValue, eventBehavior);
- element()->setNeedsStyleRecalc();
+ element().setValueInternal(sanitizedValue, eventBehavior);
+ element().setNeedsStyleRecalc();
if (!valueChanged)
return;
switch (eventBehavior) {
case DispatchChangeEvent:
- element()->dispatchFormControlChangeEvent();
+ element().dispatchFormControlChangeEvent();
break;
case DispatchInputAndChangeEvent:
- element()->dispatchFormControlInputEvent();
- element()->dispatchFormControlChangeEvent();
+ element().dispatchFormControlInputEvent();
+ element().dispatchFormControlChangeEvent();
break;
case DispatchNoEvent:
break;
@@ -610,7 +599,7 @@ String InputType::localizeValue(const String& proposedValue) const
String InputType::visibleValue() const
{
- return element()->value();
+ return element().value();
}
String InputType::sanitizeValue(const String& proposedValue) const
@@ -819,48 +808,48 @@ unsigned InputType::width() const
return 0;
}
-void InputType::applyStep(int count, AnyStepHandling anyStepHandling, TextFieldEventBehavior eventBehavior, ExceptionState& es)
+void InputType::applyStep(int count, AnyStepHandling anyStepHandling, TextFieldEventBehavior eventBehavior, ExceptionState& exceptionState)
{
StepRange stepRange(createStepRange(anyStepHandling));
if (!stepRange.hasStep()) {
- es.throwDOMException(InvalidStateError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
return;
}
- const Decimal current = parseToNumberOrNaN(element()->value());
+ const Decimal current = parseToNumberOrNaN(element().value());
if (!current.isFinite()) {
- es.throwDOMException(InvalidStateError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
return;
}
Decimal newValue = current + stepRange.step() * count;
if (!newValue.isFinite()) {
- es.throwDOMException(InvalidStateError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
return;
}
const Decimal acceptableErrorValue = stepRange.acceptableError();
if (newValue - stepRange.minimum() < -acceptableErrorValue) {
- es.throwDOMException(InvalidStateError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
return;
}
if (newValue < stepRange.minimum())
newValue = stepRange.minimum();
- const AtomicString& stepString = element()->fastGetAttribute(stepAttr);
+ const AtomicString& stepString = element().fastGetAttribute(stepAttr);
if (!equalIgnoringCase(stepString, "any"))
newValue = stepRange.alignValueForStep(current, newValue);
if (newValue - stepRange.maximum() > acceptableErrorValue) {
- es.throwDOMException(InvalidStateError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
return;
}
if (newValue > stepRange.maximum())
newValue = stepRange.maximum();
- setValueAsDecimal(newValue, eventBehavior, es);
+ setValueAsDecimal(newValue, eventBehavior, exceptionState);
- if (AXObjectCache* cache = element()->document().existingAXObjectCache())
- cache->postNotification(element(), AXObjectCache::AXValueChanged, true);
+ if (AXObjectCache* cache = element().document().existingAXObjectCache())
+ cache->postNotification(&element(), AXObjectCache::AXValueChanged, true);
}
bool InputType::getAllowedValueStep(Decimal* step) const
@@ -876,13 +865,13 @@ StepRange InputType::createStepRange(AnyStepHandling) const
return StepRange();
}
-void InputType::stepUp(int n, ExceptionState& es)
+void InputType::stepUp(int n, ExceptionState& exceptionState)
{
if (!isSteppable()) {
- es.throwDOMException(InvalidStateError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
return;
}
- applyStep(n, RejectAny, DispatchNoEvent, es);
+ applyStep(n, RejectAny, DispatchNoEvent, exceptionState);
}
void InputType::stepUpFromRenderer(int n)
@@ -947,7 +936,7 @@ void InputType::stepUpFromRenderer(int n)
else
sign = 0;
- String currentStringValue = element()->value();
+ String currentStringValue = element().value();
Decimal current = parseToNumberOrNaN(currentStringValue);
if (!current.isFinite()) {
current = defaultValueForStepUp();
@@ -961,7 +950,7 @@ void InputType::stepUpFromRenderer(int n)
if ((sign > 0 && current < stepRange.minimum()) || (sign < 0 && current > stepRange.maximum())) {
setValueAsDecimal(sign > 0 ? stepRange.minimum() : stepRange.maximum(), DispatchInputAndChangeEvent, IGNORE_EXCEPTION);
} else {
- if (stepMismatch(element()->value())) {
+ if (stepMismatch(element().value())) {
ASSERT(!step.isZero());
const Decimal base = stepRange.stepBase();
Decimal newValue;
@@ -988,12 +977,29 @@ void InputType::stepUpFromRenderer(int n)
}
}
-void InputType::observeFeatureIfVisible(UseCounter::Feature feature) const
+void InputType::countUsageIfVisible(UseCounter::Feature feature) const
{
- if (RenderStyle* style = element()->renderStyle()) {
+ if (RenderStyle* style = element().renderStyle()) {
if (style->visibility() != HIDDEN)
- UseCounter::count(&element()->document(), feature);
+ UseCounter::count(element().document(), feature);
}
}
+Decimal InputType::findStepBase(const Decimal& defaultValue) const
+{
+ Decimal stepBase = parseToNumber(element().fastGetAttribute(minAttr), Decimal::nan());
+ if (!stepBase.isFinite())
+ stepBase = parseToNumber(element().fastGetAttribute(valueAttr), defaultValue);
+ return stepBase;
+}
+
+StepRange InputType::createStepRange(AnyStepHandling anyStepHandling, const Decimal& stepBaseDefault, const Decimal& minimumDefault, const Decimal& maximumDefault, const StepRange::StepDescription& stepDescription) const
+{
+ const Decimal stepBase = findStepBase(stepBaseDefault);
+ const Decimal minimum = parseToNumber(element().fastGetAttribute(minAttr), minimumDefault);
+ const Decimal maximum = parseToNumber(element().fastGetAttribute(maxAttr), maximumDefault);
+ const Decimal step = StepRange::parseStep(anyStepHandling, stepDescription, element().fastGetAttribute(stepAttr));
+ return StepRange(stepBase, minimum, maximum, step, stepDescription);
+}
+
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/InputType.h b/chromium/third_party/WebKit/Source/core/html/forms/InputType.h
index 2a01fc91f56..207abd8f305 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/InputType.h
+++ b/chromium/third_party/WebKit/Source/core/html/forms/InputType.h
@@ -36,7 +36,7 @@
#include "core/html/HTMLTextFormControlElement.h"
#include "core/html/forms/InputTypeView.h"
#include "core/html/forms/StepRange.h"
-#include "core/page/UseCounter.h"
+#include "core/frame/UseCounter.h"
namespace WebCore {
@@ -58,8 +58,8 @@ class InputType : public InputTypeView {
WTF_MAKE_FAST_ALLOCATED;
public:
- static PassRefPtr<InputType> create(HTMLInputElement*, const AtomicString&);
- static PassRefPtr<InputType> createText(HTMLInputElement*);
+ static PassRefPtr<InputType> create(HTMLInputElement&, const AtomicString&);
+ static PassRefPtr<InputType> createText(HTMLInputElement&);
static const AtomicString& normalizeTypeName(const AtomicString&);
virtual ~InputType();
@@ -108,6 +108,7 @@ public:
virtual void restoreFormControlState(const FormControlState&);
virtual bool isFormDataAppendable() const;
virtual bool appendFormData(FormDataList&, bool multipart) const;
+ virtual String resultForDialogSubmit() const;
// DOM property functions
@@ -145,6 +146,8 @@ public:
virtual void stepUp(int, ExceptionState&);
virtual void stepUpFromRenderer(int);
virtual String badInputText() const;
+ virtual String rangeOverflowText(const Decimal& maximum) const;
+ virtual String rangeUnderflowText(const Decimal& minimum) const;
virtual String typeMismatchText() const;
virtual String valueMissingText() const;
virtual bool canSetStringValue() const;
@@ -162,19 +165,9 @@ public:
virtual void accessKeyAction(bool sendMouseEvents);
virtual bool canBeSuccessfulSubmitButton();
- // Shadow tree handling
-
- virtual void createShadowSubtree();
- virtual void destroyShadowSubtree();
-
- virtual HTMLElement* containerElement() const { return 0; }
- virtual HTMLElement* innerTextElement() const { return 0; }
- virtual HTMLElement* passwordGeneratorButtonElement() const { return 0; }
-
// Miscellaneous functions
virtual bool rendererIsNeeded();
- virtual void detach();
virtual void countUsage();
virtual void sanitizeValueInResponseToMinOrMaxAttributeChange();
virtual bool shouldRespectAlignAttribute();
@@ -238,11 +231,16 @@ public:
virtual bool hasCustomFocusLogic() const OVERRIDE;
protected:
- InputType(HTMLInputElement* element) : InputTypeView(element) { }
+ InputType(HTMLInputElement& element) : InputTypeView(element) { }
Chrome* chrome() const;
Locale& locale() const;
Decimal parseToNumberOrNaN(const String&) const;
- void observeFeatureIfVisible(UseCounter::Feature) const;
+ void countUsageIfVisible(UseCounter::Feature) const;
+
+ // Derive the step base, following the HTML algorithm steps.
+ Decimal findStepBase(const Decimal&) const;
+
+ StepRange createStepRange(AnyStepHandling, const Decimal& stepBaseDefault, const Decimal& minimumDefault, const Decimal& maximumDefault, const StepRange::StepDescription&) const;
private:
// Helper for stepUp()/stepDown(). Adds step value * count to the current value.
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/InputTypeNames.cpp b/chromium/third_party/WebKit/Source/core/html/forms/InputTypeNames.cpp
deleted file mode 100644
index e4fa55a314e..00000000000
--- a/chromium/third_party/WebKit/Source/core/html/forms/InputTypeNames.cpp
+++ /dev/null
@@ -1,172 +0,0 @@
-/*
- * Copyright (C) 2012 Apple Inc. All rights reserved.
- * Copyright (C) 2010, 2012 Google Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#include "config.h"
-#include "core/html/forms/InputTypeNames.h"
-
-namespace WebCore {
-
-namespace InputTypeNames {
-
-// The type names must be lowercased because they will be the return values of
-// input.type and input.type must be lowercase according to DOM Level 2.
-
-const AtomicString& button()
-{
- DEFINE_STATIC_LOCAL(AtomicString, name, ("button", AtomicString::ConstructFromLiteral));
- return name;
-}
-
-const AtomicString& checkbox()
-{
- DEFINE_STATIC_LOCAL(AtomicString, name, ("checkbox", AtomicString::ConstructFromLiteral));
- return name;
-}
-
-const AtomicString& color()
-{
- DEFINE_STATIC_LOCAL(AtomicString, name, ("color", AtomicString::ConstructFromLiteral));
- return name;
-}
-
-const AtomicString& date()
-{
- DEFINE_STATIC_LOCAL(AtomicString, name, ("date", AtomicString::ConstructFromLiteral));
- return name;
-}
-
-const AtomicString& datetime()
-{
- DEFINE_STATIC_LOCAL(AtomicString, name, ("datetime", AtomicString::ConstructFromLiteral));
- return name;
-}
-
-const AtomicString& datetimelocal()
-{
- DEFINE_STATIC_LOCAL(AtomicString, name, ("datetime-local", AtomicString::ConstructFromLiteral));
- return name;
-}
-
-const AtomicString& email()
-{
- DEFINE_STATIC_LOCAL(AtomicString, name, ("email", AtomicString::ConstructFromLiteral));
- return name;
-}
-
-const AtomicString& file()
-{
- DEFINE_STATIC_LOCAL(AtomicString, name, ("file", AtomicString::ConstructFromLiteral));
- return name;
-}
-
-const AtomicString& hidden()
-{
- DEFINE_STATIC_LOCAL(AtomicString, name, ("hidden", AtomicString::ConstructFromLiteral));
- return name;
-}
-
-const AtomicString& image()
-{
- DEFINE_STATIC_LOCAL(AtomicString, name, ("image", AtomicString::ConstructFromLiteral));
- return name;
-}
-
-const AtomicString& month()
-{
- DEFINE_STATIC_LOCAL(AtomicString, name, ("month", AtomicString::ConstructFromLiteral));
- return name;
-}
-
-const AtomicString& number()
-{
- DEFINE_STATIC_LOCAL(AtomicString, name, ("number", AtomicString::ConstructFromLiteral));
- return name;
-}
-
-const AtomicString& password()
-{
- DEFINE_STATIC_LOCAL(AtomicString, name, ("password", AtomicString::ConstructFromLiteral));
- return name;
-}
-
-const AtomicString& radio()
-{
- DEFINE_STATIC_LOCAL(AtomicString, name, ("radio", AtomicString::ConstructFromLiteral));
- return name;
-}
-
-const AtomicString& range()
-{
- DEFINE_STATIC_LOCAL(AtomicString, name, ("range", AtomicString::ConstructFromLiteral));
- return name;
-}
-
-const AtomicString& reset()
-{
- DEFINE_STATIC_LOCAL(AtomicString, name, ("reset", AtomicString::ConstructFromLiteral));
- return name;
-}
-
-const AtomicString& search()
-{
- DEFINE_STATIC_LOCAL(AtomicString, name, ("search", AtomicString::ConstructFromLiteral));
- return name;
-}
-
-const AtomicString& submit()
-{
- DEFINE_STATIC_LOCAL(AtomicString, name, ("submit", AtomicString::ConstructFromLiteral));
- return name;
-}
-
-const AtomicString& telephone()
-{
- DEFINE_STATIC_LOCAL(AtomicString, name, ("tel", AtomicString::ConstructFromLiteral));
- return name;
-}
-
-const AtomicString& text()
-{
- DEFINE_STATIC_LOCAL(AtomicString, name, ("text", AtomicString::ConstructFromLiteral));
- return name;
-}
-
-const AtomicString& time()
-{
- DEFINE_STATIC_LOCAL(AtomicString, name, ("time", AtomicString::ConstructFromLiteral));
- return name;
-}
-
-const AtomicString& url()
-{
- DEFINE_STATIC_LOCAL(AtomicString, name, ("url", AtomicString::ConstructFromLiteral));
- return name;
-}
-
-const AtomicString& week()
-{
- DEFINE_STATIC_LOCAL(AtomicString, name, ("week", AtomicString::ConstructFromLiteral));
- return name;
-}
-
-} // namespace WebCore::InputTypeNames
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/InputTypeNames.h b/chromium/third_party/WebKit/Source/core/html/forms/InputTypeNames.h
deleted file mode 100644
index bb84f3e828f..00000000000
--- a/chromium/third_party/WebKit/Source/core/html/forms/InputTypeNames.h
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Copyright (C) 2010, 2012 Google Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-
-#ifndef InputTypeNames_h
-#define InputTypeNames_h
-
-#include "wtf/text/AtomicString.h"
-
-namespace WebCore {
-
-namespace InputTypeNames {
-
-const AtomicString& button();
-const AtomicString& checkbox();
-const AtomicString& color();
-const AtomicString& date();
-const AtomicString& datetime();
-const AtomicString& datetimelocal();
-const AtomicString& email();
-const AtomicString& file();
-const AtomicString& hidden();
-const AtomicString& image();
-const AtomicString& month();
-const AtomicString& number();
-const AtomicString& password();
-const AtomicString& radio();
-const AtomicString& range();
-const AtomicString& reset();
-const AtomicString& search();
-const AtomicString& submit();
-const AtomicString& telephone();
-const AtomicString& text();
-const AtomicString& time();
-const AtomicString& url();
-const AtomicString& week();
-
-}
-
-} // namespace WebCore
-
-#endif // InputTypeNames_h
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/InputTypeNames.in b/chromium/third_party/WebKit/Source/core/html/forms/InputTypeNames.in
new file mode 100644
index 00000000000..57abbfea6ae
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/html/forms/InputTypeNames.in
@@ -0,0 +1,25 @@
+namespace="InputType"
+
+button
+checkbox
+color
+date
+datetime
+datetime-local
+email
+file
+hidden
+image
+month
+number
+password
+radio
+range
+reset
+search
+submit
+tel
+text
+time
+url
+week
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/InputTypeView.cpp b/chromium/third_party/WebKit/Source/core/html/forms/InputTypeView.cpp
index 99e778b6078..d8c49395104 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/InputTypeView.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/forms/InputTypeView.cpp
@@ -28,13 +28,14 @@
#include "config.h"
#include "core/html/forms/InputTypeView.h"
+#include "core/dom/shadow/ShadowRoot.h"
#include "core/html/HTMLFormElement.h"
#include "core/html/HTMLInputElement.h"
#include "core/rendering/RenderObject.h"
namespace WebCore {
-PassRefPtr<InputTypeView> InputTypeView::create(HTMLInputElement* input)
+PassRefPtr<InputTypeView> InputTypeView::create(HTMLInputElement& input)
{
return adoptRef(new InputTypeView(input));
}
@@ -45,7 +46,7 @@ InputTypeView::~InputTypeView()
bool InputTypeView::sizeShouldIncludeDecoration(int, int& preferredSize) const
{
- preferredSize = element()->size();
+ preferredSize = element().size();
return false;
}
@@ -88,12 +89,12 @@ bool InputTypeView::shouldSubmitImplicitly(Event* event)
PassRefPtr<HTMLFormElement> InputTypeView::formForSubmission() const
{
- return element()->form();
+ return element().form();
}
RenderObject* InputTypeView::createRenderer(RenderStyle* style) const
{
- return RenderObject::createObject(element(), style);
+ return RenderObject::createObject(&element(), style);
}
PassRefPtr<RenderStyle> InputTypeView::customStyleForRenderer(PassRefPtr<RenderStyle> originalStyle)
@@ -103,7 +104,7 @@ PassRefPtr<RenderStyle> InputTypeView::customStyleForRenderer(PassRefPtr<RenderS
void InputTypeView::blur()
{
- element()->defaultBlur();
+ element().defaultBlur();
}
bool InputTypeView::hasCustomFocusLogic() const
@@ -119,10 +120,24 @@ void InputTypeView::handleBlurEvent()
{
}
-void InputTypeView::attach()
+void InputTypeView::startResourceLoading()
{
}
+void InputTypeView::closePopupView()
+{
+}
+
+void InputTypeView::createShadowSubtree()
+{
+}
+
+void InputTypeView::destroyShadowSubtree()
+{
+ if (ShadowRoot* root = element().userAgentShadowRoot())
+ root->removeChildren();
+}
+
void InputTypeView::altAttributeChanged()
{
}
@@ -148,7 +163,7 @@ void InputTypeView::didDispatchClick(Event*, const ClickHandlingState&)
{
}
-void InputTypeView::updateInnerTextValue()
+void InputTypeView::updateView()
{
}
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/InputTypeView.h b/chromium/third_party/WebKit/Source/core/html/forms/InputTypeView.h
index 2b880d051a6..1e4aec4f20a 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/InputTypeView.h
+++ b/chromium/third_party/WebKit/Source/core/html/forms/InputTypeView.h
@@ -70,7 +70,7 @@ class InputTypeView : public RefCounted<InputTypeView> {
WTF_MAKE_FAST_ALLOCATED;
public:
- static PassRefPtr<InputTypeView> create(HTMLInputElement*);
+ static PassRefPtr<InputTypeView> create(HTMLInputElement&);
virtual ~InputTypeView();
virtual bool sizeShouldIncludeDecoration(int defaultSize, int& preferredSize) const;
@@ -94,12 +94,15 @@ public:
virtual void blur();
virtual RenderObject* createRenderer(RenderStyle*) const;
virtual PassRefPtr<RenderStyle> customStyleForRenderer(PassRefPtr<RenderStyle>);
- virtual void attach();
+ virtual void startResourceLoading();
+ virtual void closePopupView();
+ virtual void createShadowSubtree();
+ virtual void destroyShadowSubtree();
virtual void minOrMaxAttributeChanged();
virtual void stepAttributeChanged();
virtual void altAttributeChanged();
virtual void srcAttributeChanged();
- virtual void updateInnerTextValue();
+ virtual void updateView();
virtual void attributeChanged();
virtual void multipleAttributeChanged();
virtual void disabledAttributeChanged();
@@ -110,13 +113,13 @@ public:
virtual void updateClearButtonVisibility();
protected:
- InputTypeView(HTMLInputElement* element) : m_element(element) { }
- HTMLInputElement* element() const { return m_element; }
+ InputTypeView(HTMLInputElement& element) : m_element(element) { }
+ HTMLInputElement& element() const { return m_element; }
private:
- // Raw pointer because the HTMLInputElement object owns this InputTypeView
+ // Not a RefPtr because the HTMLInputElement object owns this InputTypeView
// object.
- HTMLInputElement* m_element;
+ HTMLInputElement& m_element;
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/MonthInputType.cpp b/chromium/third_party/WebKit/Source/core/html/forms/MonthInputType.cpp
index 390a94b1be7..647ac351770 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/MonthInputType.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/forms/MonthInputType.cpp
@@ -32,11 +32,11 @@
#include "core/html/forms/MonthInputType.h"
#include "HTMLNames.h"
+#include "InputTypeNames.h"
#include "core/html/HTMLInputElement.h"
#include "core/html/forms/DateTimeFieldsState.h"
-#include "core/html/forms/InputTypeNames.h"
-#include "core/platform/DateComponents.h"
-#include "core/platform/text/PlatformLocale.h"
+#include "platform/DateComponents.h"
+#include "platform/text/PlatformLocale.h"
#include "wtf/CurrentTime.h"
#include "wtf/DateMath.h"
#include "wtf/MathExtras.h"
@@ -51,30 +51,25 @@ static const int monthDefaultStep = 1;
static const int monthDefaultStepBase = 0;
static const int monthStepScaleFactor = 1;
-PassRefPtr<InputType> MonthInputType::create(HTMLInputElement* element)
+PassRefPtr<InputType> MonthInputType::create(HTMLInputElement& element)
{
return adoptRef(new MonthInputType(element));
}
void MonthInputType::countUsage()
{
- observeFeatureIfVisible(UseCounter::InputTypeMonth);
+ countUsageIfVisible(UseCounter::InputTypeMonth);
}
const AtomicString& MonthInputType::formControlType() const
{
- return InputTypeNames::month();
-}
-
-DateComponents::Type MonthInputType::dateType() const
-{
- return DateComponents::Month;
+ return InputTypeNames::month;
}
double MonthInputType::valueAsDate() const
{
DateComponents date;
- if (!parseToDateComponents(element()->value(), &date))
+ if (!parseToDateComponents(element().value(), &date))
return DateComponents::invalidMilliseconds();
double msec = date.millisecondsSinceEpoch();
ASSERT(std::isfinite(msec));
@@ -108,11 +103,7 @@ StepRange MonthInputType::createStepRange(AnyStepHandling anyStepHandling) const
{
DEFINE_STATIC_LOCAL(const StepRange::StepDescription, stepDescription, (monthDefaultStep, monthDefaultStepBase, monthStepScaleFactor, StepRange::ParsedStepValueShouldBeInteger));
- const Decimal stepBase = parseToNumber(element()->fastGetAttribute(minAttr), Decimal::fromDouble(monthDefaultStepBase));
- const Decimal minimum = parseToNumber(element()->fastGetAttribute(minAttr), Decimal::fromDouble(DateComponents::minimumMonth()));
- const Decimal maximum = parseToNumber(element()->fastGetAttribute(maxAttr), Decimal::fromDouble(DateComponents::maximumMonth()));
- const Decimal step = StepRange::parseStep(anyStepHandling, stepDescription, element()->fastGetAttribute(stepAttr));
- return StepRange(stepBase, minimum, maximum, step, stepDescription);
+ return InputType::createStepRange(anyStepHandling, Decimal::fromDouble(monthDefaultStepBase), Decimal::fromDouble(DateComponents::minimumMonth()), Decimal::fromDouble(DateComponents::maximumMonth()), stepDescription);
}
Decimal MonthInputType::parseToNumber(const String& src, const Decimal& defaultValue) const
@@ -155,9 +146,9 @@ void MonthInputType::setupLayoutParameters(DateTimeEditElement::LayoutParameters
{
layoutParameters.dateTimeFormat = layoutParameters.locale.monthFormat();
layoutParameters.fallbackDateTimeFormat = "yyyy-MM";
- if (!parseToDateComponents(element()->fastGetAttribute(minAttr), &layoutParameters.minimum))
+ if (!parseToDateComponents(element().fastGetAttribute(minAttr), &layoutParameters.minimum))
layoutParameters.minimum = DateComponents();
- if (!parseToDateComponents(element()->fastGetAttribute(maxAttr), &layoutParameters.maximum))
+ if (!parseToDateComponents(element().fastGetAttribute(maxAttr), &layoutParameters.maximum))
layoutParameters.maximum = DateComponents();
layoutParameters.placeholderForMonth = "--";
layoutParameters.placeholderForYear = "----";
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/MonthInputType.h b/chromium/third_party/WebKit/Source/core/html/forms/MonthInputType.h
index 73865bed6d9..ee2bbf2bf24 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/MonthInputType.h
+++ b/chromium/third_party/WebKit/Source/core/html/forms/MonthInputType.h
@@ -44,13 +44,12 @@ typedef BaseChooserOnlyDateAndTimeInputType BaseMonthInputType;
class MonthInputType : public BaseMonthInputType {
public:
- static PassRefPtr<InputType> create(HTMLInputElement*);
+ static PassRefPtr<InputType> create(HTMLInputElement&);
private:
- MonthInputType(HTMLInputElement* element) : BaseMonthInputType(element) { }
+ MonthInputType(HTMLInputElement& element) : BaseMonthInputType(element) { }
virtual void countUsage() OVERRIDE;
virtual const AtomicString& formControlType() const OVERRIDE;
- virtual DateComponents::Type dateType() const OVERRIDE;
virtual double valueAsDate() const OVERRIDE;
virtual String serializeWithMilliseconds(double) const OVERRIDE;
virtual Decimal parseToNumber(const String&, const Decimal&) const OVERRIDE;
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/NumberInputType.cpp b/chromium/third_party/WebKit/Source/core/html/forms/NumberInputType.cpp
index 630d25d6aa9..e2d90015378 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/NumberInputType.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/forms/NumberInputType.cpp
@@ -33,21 +33,21 @@
#include "core/html/forms/NumberInputType.h"
#include "HTMLNames.h"
+#include "InputTypeNames.h"
#include "bindings/v8/ExceptionState.h"
#include "core/dom/ExceptionCode.h"
-#include "core/dom/KeyboardEvent.h"
+#include "core/events/KeyboardEvent.h"
#include "core/html/HTMLInputElement.h"
-#include "core/html/forms/InputTypeNames.h"
#include "core/html/parser/HTMLParserIdioms.h"
-#include "core/platform/LocalizedStrings.h"
-#include "core/platform/text/PlatformLocale.h"
#include "core/rendering/RenderTextControl.h"
+#include "platform/text/PlatformLocale.h"
#include "wtf/MathExtras.h"
#include "wtf/PassOwnPtr.h"
#include <limits>
namespace WebCore {
+using blink::WebLocalizedString;
using namespace HTMLNames;
using namespace std;
@@ -94,61 +94,53 @@ static RealNumberRenderSize calculateRenderSize(const Decimal& value)
return RealNumberRenderSize(sizeOfSign + sizeOfZero , numberOfZeroAfterDecimalPoint + sizeOfDigits);
}
-PassRefPtr<InputType> NumberInputType::create(HTMLInputElement* element)
+PassRefPtr<InputType> NumberInputType::create(HTMLInputElement& element)
{
return adoptRef(new NumberInputType(element));
}
void NumberInputType::countUsage()
{
- observeFeatureIfVisible(UseCounter::InputTypeNumber);
+ countUsageIfVisible(UseCounter::InputTypeNumber);
}
const AtomicString& NumberInputType::formControlType() const
{
- return InputTypeNames::number();
+ return InputTypeNames::number;
}
void NumberInputType::setValue(const String& sanitizedValue, bool valueChanged, TextFieldEventBehavior eventBehavior)
{
- if (!valueChanged && sanitizedValue.isEmpty() && !element()->innerTextValue().isEmpty())
- updateInnerTextValue();
+ if (!valueChanged && sanitizedValue.isEmpty() && !element().innerTextValue().isEmpty())
+ updateView();
TextFieldInputType::setValue(sanitizedValue, valueChanged, eventBehavior);
}
double NumberInputType::valueAsDouble() const
{
- return parseToDoubleForNumberType(element()->value());
+ return parseToDoubleForNumberType(element().value());
}
-void NumberInputType::setValueAsDouble(double newValue, TextFieldEventBehavior eventBehavior, ExceptionState& es) const
+void NumberInputType::setValueAsDouble(double newValue, TextFieldEventBehavior eventBehavior, ExceptionState& exceptionState) const
{
// FIXME: We should use numeric_limits<double>::max for number input type.
const double floatMax = numeric_limits<float>::max();
- if (newValue < -floatMax) {
- es.throwDOMException(InvalidStateError);
+ if (newValue < -floatMax || newValue > floatMax) {
+ exceptionState.throwDOMException(InvalidStateError, "The value provided (" + String::number(newValue) + ") is outside the range (" + String::number(-floatMax) + ", " + String::number(floatMax) + ").");
return;
}
- if (newValue > floatMax) {
- es.throwDOMException(InvalidStateError);
- return;
- }
- element()->setValue(serializeForNumberType(newValue), eventBehavior);
+ element().setValue(serializeForNumberType(newValue), eventBehavior);
}
-void NumberInputType::setValueAsDecimal(const Decimal& newValue, TextFieldEventBehavior eventBehavior, ExceptionState& es) const
+void NumberInputType::setValueAsDecimal(const Decimal& newValue, TextFieldEventBehavior eventBehavior, ExceptionState& exceptionState) const
{
// FIXME: We should use numeric_limits<double>::max for number input type.
const Decimal floatMax = Decimal::fromDouble(numeric_limits<float>::max());
- if (newValue < -floatMax) {
- es.throwDOMException(InvalidStateError);
- return;
- }
- if (newValue > floatMax) {
- es.throwDOMException(InvalidStateError);
+ if (newValue < -floatMax || newValue > floatMax) {
+ exceptionState.throwDOMException(InvalidStateError, "The value provided (" + newValue.toString() + ") is outside the range (-" + floatMax.toString() + ", " + floatMax.toString() + ").");
return;
}
- element()->setValue(serializeForNumberType(newValue), eventBehavior);
+ element().setValue(serializeForNumberType(newValue), eventBehavior);
}
bool NumberInputType::typeMismatchFor(const String& value) const
@@ -158,35 +150,32 @@ bool NumberInputType::typeMismatchFor(const String& value) const
bool NumberInputType::typeMismatch() const
{
- ASSERT(!typeMismatchFor(element()->value()));
+ ASSERT(!typeMismatchFor(element().value()));
return false;
}
StepRange NumberInputType::createStepRange(AnyStepHandling anyStepHandling) const
{
DEFINE_STATIC_LOCAL(const StepRange::StepDescription, stepDescription, (numberDefaultStep, numberDefaultStepBase, numberStepScaleFactor));
- const Decimal stepBase = parseToDecimalForNumberType(element()->fastGetAttribute(minAttr), numberDefaultStepBase);
+
// FIXME: We should use numeric_limits<double>::max for number input type.
const Decimal floatMax = Decimal::fromDouble(numeric_limits<float>::max());
- const Decimal minimum = parseToNumber(element()->fastGetAttribute(minAttr), -floatMax);
- const Decimal maximum = parseToNumber(element()->fastGetAttribute(maxAttr), floatMax);
- const Decimal step = StepRange::parseStep(anyStepHandling, stepDescription, element()->fastGetAttribute(stepAttr));
- return StepRange(stepBase, minimum, maximum, step, stepDescription);
+ return InputType::createStepRange(anyStepHandling, numberDefaultStepBase, -floatMax, floatMax, stepDescription);
}
bool NumberInputType::sizeShouldIncludeDecoration(int defaultSize, int& preferredSize) const
{
preferredSize = defaultSize;
- const String stepString = element()->fastGetAttribute(stepAttr);
+ const String stepString = element().fastGetAttribute(stepAttr);
if (equalIgnoringCase(stepString, "any"))
return false;
- const Decimal minimum = parseToDecimalForNumberType(element()->fastGetAttribute(minAttr));
+ const Decimal minimum = parseToDecimalForNumberType(element().fastGetAttribute(minAttr));
if (!minimum.isFinite())
return false;
- const Decimal maximum = parseToDecimalForNumberType(element()->fastGetAttribute(maxAttr));
+ const Decimal maximum = parseToDecimalForNumberType(element().fastGetAttribute(maxAttr));
if (!maximum.isFinite())
return false;
@@ -236,12 +225,12 @@ String NumberInputType::localizeValue(const String& proposedValue) const
// We don't localize scientific notations.
if (proposedValue.find(isE) != kNotFound)
return proposedValue;
- return element()->locale().convertToLocalizedNumber(proposedValue);
+ return element().locale().convertToLocalizedNumber(proposedValue);
}
String NumberInputType::visibleValue() const
{
- return localizeValue(element()->value());
+ return localizeValue(element().value());
}
String NumberInputType::convertFromVisibleValue(const String& visibleValue) const
@@ -251,7 +240,7 @@ String NumberInputType::convertFromVisibleValue(const String& visibleValue) cons
// We don't localize scientific notations.
if (visibleValue.find(isE) != kNotFound)
return visibleValue;
- return element()->locale().convertFromLocalizedNumber(visibleValue);
+ return element().locale().convertFromLocalizedNumber(visibleValue);
}
String NumberInputType::sanitizeValue(const String& proposedValue) const
@@ -263,13 +252,23 @@ String NumberInputType::sanitizeValue(const String& proposedValue) const
bool NumberInputType::hasBadInput() const
{
- String standardValue = convertFromVisibleValue(element()->innerTextValue());
+ String standardValue = convertFromVisibleValue(element().innerTextValue());
return !standardValue.isEmpty() && !std::isfinite(parseToDoubleForNumberType(standardValue));
}
String NumberInputType::badInputText() const
{
- return validationMessageBadInputForNumberText();
+ return locale().queryString(WebLocalizedString::ValidationBadInputForNumber);
+}
+
+String NumberInputType::rangeOverflowText(const Decimal& maximum) const
+{
+ return locale().queryString(WebLocalizedString::ValidationRangeOverflow, localizeValue(serialize(maximum)));
+}
+
+String NumberInputType::rangeUnderflowText(const Decimal& minimum) const
+{
+ return locale().queryString(WebLocalizedString::ValidationRangeUnderflow, localizeValue(serialize(minimum)));
}
bool NumberInputType::shouldRespectSpeechAttribute()
@@ -291,16 +290,21 @@ void NumberInputType::minOrMaxAttributeChanged()
{
InputType::minOrMaxAttributeChanged();
- if (element()->renderer())
- element()->renderer()->setNeedsLayoutAndPrefWidthsRecalc();
+ if (element().renderer())
+ element().renderer()->setNeedsLayoutAndPrefWidthsRecalc();
}
void NumberInputType::stepAttributeChanged()
{
InputType::stepAttributeChanged();
- if (element()->renderer())
- element()->renderer()->setNeedsLayoutAndPrefWidthsRecalc();
+ if (element().renderer())
+ element().renderer()->setNeedsLayoutAndPrefWidthsRecalc();
+}
+
+bool NumberInputType::supportsSelectionAPI() const
+{
+ return false;
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/NumberInputType.h b/chromium/third_party/WebKit/Source/core/html/forms/NumberInputType.h
index 483ac101b3e..35711e3f9f6 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/NumberInputType.h
+++ b/chromium/third_party/WebKit/Source/core/html/forms/NumberInputType.h
@@ -39,10 +39,10 @@ class ExceptionState;
class NumberInputType : public TextFieldInputType {
public:
- static PassRefPtr<InputType> create(HTMLInputElement*);
+ static PassRefPtr<InputType> create(HTMLInputElement&);
private:
- NumberInputType(HTMLInputElement* element) : TextFieldInputType(element) { }
+ NumberInputType(HTMLInputElement& element) : TextFieldInputType(element) { }
virtual void countUsage() OVERRIDE;
virtual const AtomicString& formControlType() const OVERRIDE;
virtual void setValue(const String&, bool valueChanged, TextFieldEventBehavior) OVERRIDE;
@@ -63,11 +63,14 @@ private:
virtual String sanitizeValue(const String&) const OVERRIDE;
virtual bool hasBadInput() const OVERRIDE;
virtual String badInputText() const OVERRIDE;
+ virtual String rangeOverflowText(const Decimal& maxmum) const OVERRIDE;
+ virtual String rangeUnderflowText(const Decimal& minimum) const OVERRIDE;
virtual bool shouldRespectSpeechAttribute() OVERRIDE;
virtual bool supportsPlaceholder() const OVERRIDE;
virtual bool isNumberField() const OVERRIDE;
virtual void minOrMaxAttributeChanged() OVERRIDE;
virtual void stepAttributeChanged() OVERRIDE;
+ virtual bool supportsSelectionAPI() const OVERRIDE;
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/PasswordInputType.cpp b/chromium/third_party/WebKit/Source/core/html/forms/PasswordInputType.cpp
index f5b84a2829a..6da205be0cc 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/PasswordInputType.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/forms/PasswordInputType.cpp
@@ -32,34 +32,49 @@
#include "config.h"
#include "core/html/forms/PasswordInputType.h"
+#include "CSSPropertyNames.h"
+#include "CSSValueKeywords.h"
+#include "InputTypeNames.h"
+#include "core/dom/shadow/ShadowRoot.h"
#include "core/html/HTMLInputElement.h"
#include "core/html/forms/FormController.h"
-#include "core/html/forms/InputTypeNames.h"
#include "core/page/Chrome.h"
#include "core/page/ChromeClient.h"
#include "core/page/Page.h"
+#include "core/frame/Settings.h"
#include "wtf/Assertions.h"
#include "wtf/PassOwnPtr.h"
namespace WebCore {
-PassRefPtr<InputType> PasswordInputType::create(HTMLInputElement* element)
+PassRefPtr<InputType> PasswordInputType::create(HTMLInputElement& element)
{
return adoptRef(new PasswordInputType(element));
}
-HTMLElement* PasswordInputType::passwordGeneratorButtonElement() const
+void PasswordInputType::countUsage()
{
- return m_generatorButton.get();
+ countUsageIfVisible(UseCounter::InputTypePassword);
+ if (element().fastHasAttribute(HTMLNames::maxlengthAttr))
+ countUsageIfVisible(UseCounter::InputTypePasswordMaxLength);
}
bool PasswordInputType::isPasswordGenerationEnabled() const
{
- if (Page* page = element()->document().page())
+ if (isPasswordGenerationDecorationEnabled())
+ return true;
+ if (Page* page = element().document().page())
return page->chrome().client().isPasswordGenerationEnabled();
return false;
}
+bool PasswordInputType::isPasswordGenerationDecorationEnabled() const
+{
+ if (Page* page = element().document().page())
+ return page->settings().passwordGenerationDecorationEnabled();
+ return false;
+}
+
bool PasswordInputType::needsContainer() const
{
return BaseTextInputType::needsContainer() || isPasswordGenerationEnabled();
@@ -68,21 +83,17 @@ bool PasswordInputType::needsContainer() const
void PasswordInputType::createShadowSubtree()
{
BaseTextInputType::createShadowSubtree();
- if (isPasswordGenerationEnabled()) {
- m_generatorButton = PasswordGeneratorButtonElement::create(element()->document());
- m_generatorButton->decorate(element());
- }
-}
-
-void PasswordInputType::destroyShadowSubtree()
-{
- BaseTextInputType::destroyShadowSubtree();
- m_generatorButton = 0;
+ if (!isPasswordGenerationEnabled())
+ return;
+ RefPtr<PasswordGeneratorButtonElement> generatorButton = PasswordGeneratorButtonElement::create(element().document());
+ if (!isPasswordGenerationDecorationEnabled())
+ generatorButton->setInlineStyleProperty(CSSPropertyDisplay, CSSValueNone);
+ containerElement()->appendChild(generatorButton.release());
}
const AtomicString& PasswordInputType::formControlType() const
{
- return InputTypeNames::password();
+ return InputTypeNames::password;
}
bool PasswordInputType::shouldSaveAndRestoreFormControlState() const
@@ -132,14 +143,14 @@ bool PasswordInputType::isPasswordField() const
void PasswordInputType::enableSecureTextInput()
{
- if (element()->document().frame())
- element()->document().setUseSecureKeyboardEntryWhenActive(true);
+ if (element().document().frame())
+ element().document().setUseSecureKeyboardEntryWhenActive(true);
}
void PasswordInputType::disableSecureTextInput()
{
- if (element()->document().frame())
- element()->document().setUseSecureKeyboardEntryWhenActive(false);
+ if (element().document().frame())
+ element().document().setUseSecureKeyboardEntryWhenActive(false);
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/PasswordInputType.h b/chromium/third_party/WebKit/Source/core/html/forms/PasswordInputType.h
index b4cf2bf6552..50f36691e0d 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/PasswordInputType.h
+++ b/chromium/third_party/WebKit/Source/core/html/forms/PasswordInputType.h
@@ -38,14 +38,13 @@ namespace WebCore {
class PasswordInputType FINAL : public BaseTextInputType {
public:
- static PassRefPtr<InputType> create(HTMLInputElement*);
+ static PassRefPtr<InputType> create(HTMLInputElement&);
private:
- PasswordInputType(HTMLInputElement* element) : BaseTextInputType(element) { }
- virtual HTMLElement* passwordGeneratorButtonElement() const OVERRIDE;
+ PasswordInputType(HTMLInputElement& element) : BaseTextInputType(element) { }
virtual bool needsContainer() const OVERRIDE;
virtual void createShadowSubtree() OVERRIDE;
- virtual void destroyShadowSubtree() OVERRIDE;
+ virtual void countUsage() OVERRIDE;
virtual const AtomicString& formControlType() const OVERRIDE;
virtual bool shouldSaveAndRestoreFormControlState() const OVERRIDE;
virtual FormControlState saveFormControlState() const OVERRIDE;
@@ -59,8 +58,8 @@ private:
virtual void disableSecureTextInput() OVERRIDE;
bool isPasswordGenerationEnabled() const;
-
- RefPtr<PasswordGeneratorButtonElement> m_generatorButton;
+ // For testing.
+ bool isPasswordGenerationDecorationEnabled() const;
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/RadioInputType.cpp b/chromium/third_party/WebKit/Source/core/html/forms/RadioInputType.cpp
index d18e856d89a..fc6da4939fa 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/RadioInputType.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/forms/RadioInputType.cpp
@@ -23,37 +23,37 @@
#include "core/html/forms/RadioInputType.h"
#include "HTMLNames.h"
-#include "core/dom/KeyboardEvent.h"
-#include "core/dom/MouseEvent.h"
+#include "InputTypeNames.h"
#include "core/dom/NodeTraversal.h"
+#include "core/events/KeyboardEvent.h"
+#include "core/events/MouseEvent.h"
#include "core/html/HTMLInputElement.h"
-#include "core/html/forms/InputTypeNames.h"
#include "core/page/SpatialNavigation.h"
-#include "core/platform/LocalizedStrings.h"
+#include "platform/text/PlatformLocale.h"
#include "wtf/PassOwnPtr.h"
namespace WebCore {
using namespace HTMLNames;
-PassRefPtr<InputType> RadioInputType::create(HTMLInputElement* element)
+PassRefPtr<InputType> RadioInputType::create(HTMLInputElement& element)
{
return adoptRef(new RadioInputType(element));
}
const AtomicString& RadioInputType::formControlType() const
{
- return InputTypeNames::radio();
+ return InputTypeNames::radio;
}
bool RadioInputType::valueMissing(const String&) const
{
- return element()->isInRequiredRadioButtonGroup() && !element()->checkedRadioButtonForGroup();
+ return element().isInRequiredRadioButtonGroup() && !element().checkedRadioButtonForGroup();
}
String RadioInputType::valueMissingText() const
{
- return validationMessageValueMissingForRadioText();
+ return locale().queryString(blink::WebLocalizedString::ValidationValueMissingForRadio);
}
void RadioInputType::handleClickEvent(MouseEvent* event)
@@ -76,15 +76,15 @@ void RadioInputType::handleKeydownEvent(KeyboardEvent* event)
// (and so moves to the right). Seems strange, but we'll match it. However,
// when using Spatial Navigation, we need to be able to navigate without
// changing the selection.
- Document& document = element()->document();
+ Document& document = element().document();
if (isSpatialNavigationEnabled(document.frame()))
return;
bool forward = (key == "Down" || key == "Right");
// We can only stay within the form's children if the form hasn't been demoted to a leaf because
// of malformed HTML.
- Node* node = element();
- while ((node = (forward ? NodeTraversal::next(node) : NodeTraversal::previous(node)))) {
+ Node* node = &element();
+ while ((node = (forward ? NodeTraversal::next(*node) : NodeTraversal::previous(*node)))) {
// Once we encounter a form element, we know we're through.
if (node->hasTagName(formTag))
break;
@@ -92,12 +92,12 @@ void RadioInputType::handleKeydownEvent(KeyboardEvent* event)
if (!node->hasTagName(inputTag))
continue;
HTMLInputElement* inputElement = toHTMLInputElement(node);
- if (inputElement->form() != element()->form())
+ if (inputElement->form() != element().form())
break;
- if (inputElement->isRadioButton() && inputElement->name() == element()->name() && inputElement->isFocusable()) {
+ if (inputElement->isRadioButton() && inputElement->name() == element().name() && inputElement->isFocusable()) {
RefPtr<HTMLInputElement> protector(inputElement);
document.setFocusedElement(inputElement);
- inputElement->dispatchSimulatedClick(event, SendNoEvents, DoNotShowPressedLook);
+ inputElement->dispatchSimulatedClick(event, SendNoEvents);
event->setDefaultHandled();
return;
}
@@ -111,7 +111,7 @@ void RadioInputType::handleKeyupEvent(KeyboardEvent* event)
return;
// If an unselected radio is tabbed into (because the entire group has nothing
// checked, or because of some explicit .focus() call), then allow space to check it.
- if (element()->checked())
+ if (element().checked())
return;
dispatchSimulatedClickIfActive(event);
}
@@ -122,27 +122,27 @@ bool RadioInputType::isKeyboardFocusable() const
return false;
// When using Spatial Navigation, every radio button should be focusable.
- if (isSpatialNavigationEnabled(element()->document().frame()))
+ if (isSpatialNavigationEnabled(element().document().frame()))
return true;
// Never allow keyboard tabbing to leave you in the same radio group. Always
// skip any other elements in the group.
- Element* currentFocusedElement = element()->document().focusedElement();
+ Element* currentFocusedElement = element().document().focusedElement();
if (currentFocusedElement && currentFocusedElement->hasTagName(inputTag)) {
HTMLInputElement* focusedInput = toHTMLInputElement(currentFocusedElement);
- if (focusedInput->isRadioButton() && focusedInput->form() == element()->form() && focusedInput->name() == element()->name())
+ if (focusedInput->isRadioButton() && focusedInput->form() == element().form() && focusedInput->name() == element().name())
return false;
}
// Allow keyboard focus if we're checked or if nothing in the group is checked.
- return element()->checked() || !element()->checkedRadioButtonForGroup();
+ return element().checked() || !element().checkedRadioButtonForGroup();
}
bool RadioInputType::shouldSendChangeEventAfterCheckedChanged()
{
// Don't send a change event for a radio button that's getting unchecked.
// This was done to match the behavior of other browsers.
- return element()->checked();
+ return element().checked();
}
PassOwnPtr<ClickHandlingState> RadioInputType::willDispatchClick()
@@ -156,9 +156,9 @@ PassOwnPtr<ClickHandlingState> RadioInputType::willDispatchClick()
OwnPtr<ClickHandlingState> state = adoptPtr(new ClickHandlingState);
- state->checked = element()->checked();
- state->checkedRadioButton = element()->checkedRadioButtonForGroup();
- element()->setChecked(true, DispatchChangeEvent);
+ state->checked = element().checked();
+ state->checkedRadioButton = element().checkedRadioButtonForGroup();
+ element().setChecked(true, DispatchChangeEvent);
return state.release();
}
@@ -171,8 +171,8 @@ void RadioInputType::didDispatchClick(Event* event, const ClickHandlingState& st
HTMLInputElement* checkedRadioButton = state.checkedRadioButton.get();
if (checkedRadioButton
&& checkedRadioButton->isRadioButton()
- && checkedRadioButton->form() == element()->form()
- && checkedRadioButton->name() == element()->name()) {
+ && checkedRadioButton->form() == element().form()
+ && checkedRadioButton->name() == element().name()) {
checkedRadioButton->setChecked(true);
}
}
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/RadioInputType.h b/chromium/third_party/WebKit/Source/core/html/forms/RadioInputType.h
index 667b3f2f399..09788e2033a 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/RadioInputType.h
+++ b/chromium/third_party/WebKit/Source/core/html/forms/RadioInputType.h
@@ -37,10 +37,10 @@ namespace WebCore {
class RadioInputType : public BaseCheckableInputType {
public:
- static PassRefPtr<InputType> create(HTMLInputElement*);
+ static PassRefPtr<InputType> create(HTMLInputElement&);
private:
- RadioInputType(HTMLInputElement* element) : BaseCheckableInputType(element) { }
+ RadioInputType(HTMLInputElement& element) : BaseCheckableInputType(element) { }
virtual const AtomicString& formControlType() const OVERRIDE;
virtual bool valueMissing(const String&) const OVERRIDE;
virtual String valueMissingText() const OVERRIDE;
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/RangeInputType.cpp b/chromium/third_party/WebKit/Source/core/html/forms/RangeInputType.cpp
index 649bffd3745..561a6504777 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/RangeInputType.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/forms/RangeInputType.cpp
@@ -33,26 +33,26 @@
#include "core/html/forms/RangeInputType.h"
#include "HTMLNames.h"
+#include "InputTypeNames.h"
#include "bindings/v8/ExceptionStatePlaceholder.h"
#include "core/accessibility/AXObjectCache.h"
-#include "core/dom/KeyboardEvent.h"
-#include "core/dom/MouseEvent.h"
-#include "core/dom/ScopedEventQueue.h"
+#include "core/events/KeyboardEvent.h"
+#include "core/events/MouseEvent.h"
+#include "core/events/ScopedEventQueue.h"
#include "core/dom/Touch.h"
-#include "core/dom/TouchEvent.h"
+#include "core/events/TouchEvent.h"
#include "core/dom/TouchList.h"
#include "core/dom/shadow/ShadowRoot.h"
#include "core/html/HTMLDataListElement.h"
#include "core/html/HTMLDivElement.h"
#include "core/html/HTMLInputElement.h"
#include "core/html/HTMLOptionElement.h"
-#include "core/html/forms/InputTypeNames.h"
#include "core/html/forms/StepRange.h"
#include "core/html/parser/HTMLParserIdioms.h"
#include "core/html/shadow/ShadowElementNames.h"
#include "core/html/shadow/SliderThumbElement.h"
-#include "core/platform/PlatformMouseEvent.h"
#include "core/rendering/RenderSlider.h"
+#include "platform/PlatformMouseEvent.h"
#include "wtf/MathExtras.h"
#include "wtf/NonCopyingSort.h"
#include "wtf/PassOwnPtr.h"
@@ -74,12 +74,12 @@ static Decimal ensureMaximum(const Decimal& proposedValue, const Decimal& minimu
return proposedValue >= minimum ? proposedValue : std::max(minimum, fallbackValue);
}
-PassRefPtr<InputType> RangeInputType::create(HTMLInputElement* element)
+PassRefPtr<InputType> RangeInputType::create(HTMLInputElement& element)
{
return adoptRef(new RangeInputType(element));
}
-RangeInputType::RangeInputType(HTMLInputElement* element)
+RangeInputType::RangeInputType(HTMLInputElement& element)
: InputType(element)
, m_tickMarkValuesDirty(true)
{
@@ -87,7 +87,7 @@ RangeInputType::RangeInputType(HTMLInputElement* element)
void RangeInputType::countUsage()
{
- observeFeatureIfVisible(UseCounter::InputTypeRange);
+ countUsageIfVisible(UseCounter::InputTypeRange);
}
bool RangeInputType::isRangeControl() const
@@ -97,17 +97,17 @@ bool RangeInputType::isRangeControl() const
const AtomicString& RangeInputType::formControlType() const
{
- return InputTypeNames::range();
+ return InputTypeNames::range;
}
double RangeInputType::valueAsDouble() const
{
- return parseToDoubleForNumberType(element()->value());
+ return parseToDoubleForNumberType(element().value());
}
void RangeInputType::setValueAsDecimal(const Decimal& newValue, TextFieldEventBehavior eventBehavior, ExceptionState&) const
{
- element()->setValue(serialize(newValue), eventBehavior);
+ element().setValue(serialize(newValue), eventBehavior);
}
bool RangeInputType::typeMismatchFor(const String& value) const
@@ -124,16 +124,16 @@ StepRange RangeInputType::createStepRange(AnyStepHandling anyStepHandling) const
{
DEFINE_STATIC_LOCAL(const StepRange::StepDescription, stepDescription, (rangeDefaultStep, rangeDefaultStepBase, rangeStepScaleFactor));
- const Decimal minimum = parseToNumber(element()->fastGetAttribute(minAttr), rangeDefaultMinimum);
- const Decimal maximum = ensureMaximum(parseToNumber(element()->fastGetAttribute(maxAttr), rangeDefaultMaximum), minimum, rangeDefaultMaximum);
+ const Decimal minimum = parseToNumber(element().fastGetAttribute(minAttr), rangeDefaultMinimum);
+ const Decimal maximum = ensureMaximum(parseToNumber(element().fastGetAttribute(maxAttr), rangeDefaultMaximum), minimum, rangeDefaultMaximum);
- const AtomicString& precisionValue = element()->fastGetAttribute(precisionAttr);
+ const AtomicString& precisionValue = element().fastGetAttribute(precisionAttr);
if (!precisionValue.isNull()) {
const Decimal step = equalIgnoringCase(precisionValue, "float") ? Decimal::nan() : 1;
return StepRange(minimum, minimum, maximum, step, stepDescription);
}
- const Decimal step = StepRange::parseStep(anyStepHandling, stepDescription, element()->fastGetAttribute(stepAttr));
+ const Decimal step = StepRange::parseStep(anyStepHandling, stepDescription, element().fastGetAttribute(stepAttr));
return StepRange(minimum, minimum, maximum, step, stepDescription);
}
@@ -144,14 +144,14 @@ bool RangeInputType::isSteppable() const
void RangeInputType::handleMouseDownEvent(MouseEvent* event)
{
- if (element()->isDisabledOrReadOnly())
+ if (element().isDisabledOrReadOnly())
return;
Node* targetNode = event->target()->toNode();
if (event->button() != LeftButton || !targetNode)
return;
- ASSERT(element()->shadow());
- if (targetNode != element() && !targetNode->isDescendantOf(element()->userAgentShadowRoot()))
+ ASSERT(element().shadow());
+ if (targetNode != element() && !targetNode->isDescendantOf(element().userAgentShadowRoot()))
return;
SliderThumbElement* thumb = sliderThumbElement();
if (targetNode == thumb)
@@ -161,10 +161,10 @@ void RangeInputType::handleMouseDownEvent(MouseEvent* event)
void RangeInputType::handleTouchEvent(TouchEvent* event)
{
- if (element()->isDisabledOrReadOnly())
+ if (element().isDisabledOrReadOnly())
return;
- if (event->type() == eventNames().touchendEvent) {
+ if (event->type() == EventTypeNames::touchend) {
event->setDefaultHandled();
return;
}
@@ -183,12 +183,12 @@ bool RangeInputType::hasTouchEventHandler() const
void RangeInputType::handleKeydownEvent(KeyboardEvent* event)
{
- if (element()->isDisabledOrReadOnly())
+ if (element().isDisabledOrReadOnly())
return;
const String& key = event->keyIdentifier();
- const Decimal current = parseToNumberOrNaN(element()->value());
+ const Decimal current = parseToNumberOrNaN(element().value());
ASSERT(current.isFinite());
StepRange stepRange(createStepRange(RejectAny));
@@ -196,12 +196,12 @@ void RangeInputType::handleKeydownEvent(KeyboardEvent* event)
// FIXME: We can't use stepUp() for the step value "any". So, we increase
// or decrease the value by 1/100 of the value range. Is it reasonable?
- const Decimal step = equalIgnoringCase(element()->fastGetAttribute(stepAttr), "any") ? (stepRange.maximum() - stepRange.minimum()) / 100 : stepRange.step();
+ const Decimal step = equalIgnoringCase(element().fastGetAttribute(stepAttr), "any") ? (stepRange.maximum() - stepRange.minimum()) / 100 : stepRange.step();
const Decimal bigStep = max((stepRange.maximum() - stepRange.minimum()) / 10, step);
bool isVertical = false;
- if (element()->renderer()) {
- ControlPart part = element()->renderer()->style()->appearance();
+ if (element().renderer()) {
+ ControlPart part = element().renderer()->style()->appearance();
isVertical = part == SliderVerticalPart || part == MediaVolumeSliderPart;
}
@@ -232,9 +232,9 @@ void RangeInputType::handleKeydownEvent(KeyboardEvent* event)
TextFieldEventBehavior eventBehavior = DispatchChangeEvent;
setValueAsDecimal(newValue, eventBehavior, IGNORE_EXCEPTION);
- if (AXObjectCache* cache = element()->document().existingAXObjectCache())
- cache->postNotification(element(), AXObjectCache::AXValueChanged, true);
- element()->dispatchFormControlChangeEvent();
+ if (AXObjectCache* cache = element().document().existingAXObjectCache())
+ cache->postNotification(&element(), AXObjectCache::AXValueChanged, true);
+ element().dispatchFormControlChangeEvent();
}
event->setDefaultHandled();
@@ -242,21 +242,21 @@ void RangeInputType::handleKeydownEvent(KeyboardEvent* event)
void RangeInputType::createShadowSubtree()
{
- ASSERT(element()->shadow());
+ ASSERT(element().shadow());
- Document& document = element()->document();
+ Document& document = element().document();
RefPtr<HTMLDivElement> track = HTMLDivElement::create(document);
- track->setPart(AtomicString("-webkit-slider-runnable-track", AtomicString::ConstructFromLiteral));
+ track->setPseudo(AtomicString("-webkit-slider-runnable-track", AtomicString::ConstructFromLiteral));
track->setAttribute(idAttr, ShadowElementNames::sliderTrack());
track->appendChild(SliderThumbElement::create(document));
RefPtr<HTMLElement> container = SliderContainerElement::create(document);
container->appendChild(track.release());
- element()->userAgentShadowRoot()->appendChild(container.release());
+ element().userAgentShadowRoot()->appendChild(container.release());
}
RenderObject* RangeInputType::createRenderer(RenderStyle*) const
{
- return new RenderSlider(element());
+ return new RenderSlider(&element());
}
Decimal RangeInputType::parseToNumber(const String& src, const Decimal& defaultValue) const
@@ -276,13 +276,13 @@ void RangeInputType::accessKeyAction(bool sendMouseEvents)
{
InputType::accessKeyAction(sendMouseEvents);
- element()->dispatchSimulatedClick(0, sendMouseEvents ? SendMouseUpDownEvents : SendNoEvents);
+ element().dispatchSimulatedClick(0, sendMouseEvents ? SendMouseUpDownEvents : SendNoEvents);
}
void RangeInputType::sanitizeValueInResponseToMinOrMaxAttributeChange()
{
- if (element()->hasDirtyValue())
- element()->setValue(element()->value());
+ if (element().hasDirtyValue())
+ element().setValue(element().value());
sliderThumbElement()->setPositionFromValue();
}
@@ -309,6 +309,12 @@ String RangeInputType::sanitizeValue(const String& proposedValue) const
return serializeForNumberType(stepRange.clampValue(proposedNumericValue));
}
+void RangeInputType::disabledAttributeChanged()
+{
+ if (element().isDisabledFormControl())
+ sliderThumbElement()->stopDragging();
+}
+
bool RangeInputType::shouldRespectListAttribute()
{
return InputType::themeSupportsDataListUI(this);
@@ -316,12 +322,12 @@ bool RangeInputType::shouldRespectListAttribute()
inline SliderThumbElement* RangeInputType::sliderThumbElement() const
{
- return toSliderThumbElement(element()->userAgentShadowRoot()->getElementById(ShadowElementNames::sliderThumb()));
+ return toSliderThumbElement(element().userAgentShadowRoot()->getElementById(ShadowElementNames::sliderThumb()));
}
inline Element* RangeInputType::sliderTrackElement() const
{
- return element()->userAgentShadowRoot()->getElementById(ShadowElementNames::sliderTrack());
+ return element().userAgentShadowRoot()->getElementById(ShadowElementNames::sliderTrack());
}
void RangeInputType::listAttributeTargetChanged()
@@ -343,7 +349,7 @@ void RangeInputType::updateTickMarkValues()
return;
m_tickMarkValues.clear();
m_tickMarkValuesDirty = false;
- HTMLDataListElement* dataList = element()->dataList();
+ HTMLDataListElement* dataList = element().dataList();
if (!dataList)
return;
RefPtr<HTMLCollection> options = dataList->options();
@@ -352,7 +358,7 @@ void RangeInputType::updateTickMarkValues()
Node* node = options->item(i);
HTMLOptionElement* optionElement = toHTMLOptionElement(node);
String optionValue = optionElement->value();
- if (!element()->isValidValue(optionValue))
+ if (!element().isValidValue(optionValue))
continue;
m_tickMarkValues.append(parseToNumber(optionValue, Decimal::nan()));
}
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/RangeInputType.h b/chromium/third_party/WebKit/Source/core/html/forms/RangeInputType.h
index b9d20df1306..cb10f784e3e 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/RangeInputType.h
+++ b/chromium/third_party/WebKit/Source/core/html/forms/RangeInputType.h
@@ -40,10 +40,10 @@ class SliderThumbElement;
class RangeInputType : public InputType {
public:
- static PassRefPtr<InputType> create(HTMLInputElement*);
+ static PassRefPtr<InputType> create(HTMLInputElement&);
private:
- RangeInputType(HTMLInputElement*);
+ RangeInputType(HTMLInputElement&);
virtual void countUsage() OVERRIDE;
virtual bool isRangeControl() const OVERRIDE;
virtual const AtomicString& formControlType() const OVERRIDE;
@@ -69,6 +69,7 @@ private:
virtual bool shouldRespectListAttribute() OVERRIDE;
SliderThumbElement* sliderThumbElement() const;
Element* sliderTrackElement() const;
+ virtual void disabledAttributeChanged() OVERRIDE;
virtual void listAttributeTargetChanged() OVERRIDE;
void updateTickMarkValues();
virtual Decimal findClosestTickMarkValue(const Decimal&) OVERRIDE;
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/ResetInputType.cpp b/chromium/third_party/WebKit/Source/core/html/forms/ResetInputType.cpp
index a31864c2361..6175a6c95e9 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/ResetInputType.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/forms/ResetInputType.cpp
@@ -32,23 +32,23 @@
#include "config.h"
#include "core/html/forms/ResetInputType.h"
-#include "core/dom/Event.h"
+#include "InputTypeNames.h"
+#include "core/events/Event.h"
#include "core/html/HTMLFormElement.h"
#include "core/html/HTMLInputElement.h"
-#include "core/html/forms/InputTypeNames.h"
-#include "core/platform/LocalizedStrings.h"
+#include "platform/text/PlatformLocale.h"
#include "wtf/PassOwnPtr.h"
namespace WebCore {
-PassRefPtr<InputType> ResetInputType::create(HTMLInputElement* element)
+PassRefPtr<InputType> ResetInputType::create(HTMLInputElement& element)
{
return adoptRef(new ResetInputType(element));
}
const AtomicString& ResetInputType::formControlType() const
{
- return InputTypeNames::reset();
+ return InputTypeNames::reset;
}
bool ResetInputType::supportsValidation() const
@@ -58,15 +58,15 @@ bool ResetInputType::supportsValidation() const
void ResetInputType::handleDOMActivateEvent(Event* event)
{
- if (element()->isDisabledFormControl() || !element()->form())
+ if (element().isDisabledFormControl() || !element().form())
return;
- element()->form()->reset();
+ element().form()->reset();
event->setDefaultHandled();
}
String ResetInputType::defaultValue() const
{
- return resetButtonDefaultLabel();
+ return locale().queryString(blink::WebLocalizedString::ResetButtonDefaultLabel);
}
bool ResetInputType::isTextButton() const
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/ResetInputType.h b/chromium/third_party/WebKit/Source/core/html/forms/ResetInputType.h
index b467c82ccc2..8837400b86e 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/ResetInputType.h
+++ b/chromium/third_party/WebKit/Source/core/html/forms/ResetInputType.h
@@ -37,10 +37,10 @@ namespace WebCore {
class ResetInputType : public BaseButtonInputType {
public:
- static PassRefPtr<InputType> create(HTMLInputElement*);
+ static PassRefPtr<InputType> create(HTMLInputElement&);
private:
- ResetInputType(HTMLInputElement* element) : BaseButtonInputType(element) { }
+ ResetInputType(HTMLInputElement& element) : BaseButtonInputType(element) { }
virtual const AtomicString& formControlType() const OVERRIDE;
virtual bool supportsValidation() const OVERRIDE;
virtual void handleDOMActivateEvent(Event*) OVERRIDE;
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/SearchInputType.cpp b/chromium/third_party/WebKit/Source/core/html/forms/SearchInputType.cpp
index 9de12b8d5d8..ba6e85aab40 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/SearchInputType.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/forms/SearchInputType.cpp
@@ -32,11 +32,11 @@
#include "core/html/forms/SearchInputType.h"
#include "HTMLNames.h"
+#include "InputTypeNames.h"
#include "bindings/v8/ExceptionStatePlaceholder.h"
-#include "core/dom/KeyboardEvent.h"
+#include "core/events/KeyboardEvent.h"
#include "core/dom/shadow/ShadowRoot.h"
#include "core/html/HTMLInputElement.h"
-#include "core/html/forms/InputTypeNames.h"
#include "core/html/shadow/ShadowElementNames.h"
#include "core/html/shadow/TextControlInnerElements.h"
#include "core/rendering/RenderSearchField.h"
@@ -46,30 +46,30 @@ namespace WebCore {
using namespace HTMLNames;
-inline SearchInputType::SearchInputType(HTMLInputElement* element)
+inline SearchInputType::SearchInputType(HTMLInputElement& element)
: BaseTextInputType(element)
, m_searchEventTimer(this, &SearchInputType::searchEventTimerFired)
{
}
-PassRefPtr<InputType> SearchInputType::create(HTMLInputElement* element)
+PassRefPtr<InputType> SearchInputType::create(HTMLInputElement& element)
{
return adoptRef(new SearchInputType(element));
}
void SearchInputType::countUsage()
{
- observeFeatureIfVisible(UseCounter::InputTypeSearch);
+ countUsageIfVisible(UseCounter::InputTypeSearch);
}
RenderObject* SearchInputType::createRenderer(RenderStyle*) const
{
- return new RenderSearchField(element());
+ return new RenderSearchField(&element());
}
const AtomicString& SearchInputType::formControlType() const
{
- return InputTypeNames::search();
+ return InputTypeNames::search;
}
bool SearchInputType::shouldRespectSpeechAttribute()
@@ -90,25 +90,25 @@ bool SearchInputType::needsContainer() const
void SearchInputType::createShadowSubtree()
{
TextFieldInputType::createShadowSubtree();
- HTMLElement* container = containerElement();
- Element* viewPort = element()->userAgentShadowRoot()->getElementById(ShadowElementNames::editingViewPort());
+ Element* container = containerElement();
+ Element* viewPort = element().userAgentShadowRoot()->getElementById(ShadowElementNames::editingViewPort());
ASSERT(container);
ASSERT(viewPort);
- container->insertBefore(SearchFieldDecorationElement::create(element()->document()), viewPort);
- container->insertBefore(SearchFieldCancelButtonElement::create(element()->document()), viewPort->nextSibling());
+ container->insertBefore(SearchFieldDecorationElement::create(element().document()), viewPort);
+ container->insertBefore(SearchFieldCancelButtonElement::create(element().document()), viewPort->nextSibling());
}
void SearchInputType::handleKeydownEvent(KeyboardEvent* event)
{
- if (element()->isDisabledOrReadOnly()) {
+ if (element().isDisabledOrReadOnly()) {
TextFieldInputType::handleKeydownEvent(event);
return;
}
const String& key = event->keyIdentifier();
if (key == "U+001B") {
- RefPtr<HTMLInputElement> input = element();
+ RefPtr<HTMLInputElement> input(element());
input->setValueForUser("");
input->onSearch();
event->setDefaultHandled();
@@ -119,12 +119,12 @@ void SearchInputType::handleKeydownEvent(KeyboardEvent* event)
void SearchInputType::startSearchEventTimer()
{
- ASSERT(element()->renderer());
- unsigned length = element()->innerTextValue().length();
+ ASSERT(element().renderer());
+ unsigned length = element().innerTextValue().length();
if (!length) {
stopSearchEventTimer();
- element()->onSearch();
+ element().onSearch();
return;
}
@@ -140,12 +140,12 @@ void SearchInputType::stopSearchEventTimer()
void SearchInputType::searchEventTimerFired(Timer<SearchInputType>*)
{
- element()->onSearch();
+ element().onSearch();
}
bool SearchInputType::searchEventsShouldBeDispatched() const
{
- return element()->hasAttribute(incrementalAttr);
+ return element().hasAttribute(incrementalAttr);
}
void SearchInputType::didSetValueByUserEdit(ValueChangeState state)
@@ -159,21 +159,24 @@ void SearchInputType::didSetValueByUserEdit(ValueChangeState state)
TextFieldInputType::didSetValueByUserEdit(state);
}
-void SearchInputType::updateInnerTextValue()
+void SearchInputType::updateView()
{
- BaseTextInputType::updateInnerTextValue();
+ BaseTextInputType::updateView();
updateCancelButtonVisibility();
}
void SearchInputType::updateCancelButtonVisibility()
{
- Element* button = element()->userAgentShadowRoot()->getElementById(ShadowElementNames::clearButton());
+ Element* button = element().userAgentShadowRoot()->getElementById(ShadowElementNames::clearButton());
if (!button)
return;
- if (element()->value().isEmpty())
- button->setInlineStyleProperty(CSSPropertyVisibility, CSSValueHidden);
- else
- button->removeInlineStyleProperty(CSSPropertyVisibility);
+ if (element().value().isEmpty()) {
+ button->setInlineStyleProperty(CSSPropertyOpacity, 0.0, CSSPrimitiveValue::CSS_NUMBER);
+ button->setInlineStyleProperty(CSSPropertyPointerEvents, CSSValueNone);
+ } else {
+ button->removeInlineStyleProperty(CSSPropertyOpacity);
+ button->removeInlineStyleProperty(CSSPropertyPointerEvents);
+ }
}
bool SearchInputType::supportsInputModeAttribute() const
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/SearchInputType.h b/chromium/third_party/WebKit/Source/core/html/forms/SearchInputType.h
index f2aa7fd42bc..d13c0f94c42 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/SearchInputType.h
+++ b/chromium/third_party/WebKit/Source/core/html/forms/SearchInputType.h
@@ -32,7 +32,7 @@
#define SearchInputType_h
#include "core/html/forms/BaseTextInputType.h"
-#include "core/platform/Timer.h"
+#include "platform/Timer.h"
namespace WebCore {
@@ -41,12 +41,12 @@ class SearchFieldDecorationElement;
class SearchInputType : public BaseTextInputType {
public:
- static PassRefPtr<InputType> create(HTMLInputElement*);
+ static PassRefPtr<InputType> create(HTMLInputElement&);
void stopSearchEventTimer();
private:
- SearchInputType(HTMLInputElement*);
+ SearchInputType(HTMLInputElement&);
virtual void countUsage() OVERRIDE;
virtual RenderObject* createRenderer(RenderStyle*) const OVERRIDE;
virtual const AtomicString& formControlType() const OVERRIDE;
@@ -57,7 +57,7 @@ private:
virtual void handleKeydownEvent(KeyboardEvent*) OVERRIDE;
virtual void didSetValueByUserEdit(ValueChangeState) OVERRIDE;
virtual bool supportsInputModeAttribute() const OVERRIDE;
- virtual void updateInnerTextValue() OVERRIDE;
+ virtual void updateView() OVERRIDE;
void searchEventTimerFired(Timer<SearchInputType>*);
bool searchEventsShouldBeDispatched() const;
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/StepRange.h b/chromium/third_party/WebKit/Source/core/html/forms/StepRange.h
index 0b044442fd8..a31e264c281 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/StepRange.h
+++ b/chromium/third_party/WebKit/Source/core/html/forms/StepRange.h
@@ -21,7 +21,7 @@
#ifndef StepRange_h
#define StepRange_h
-#include "core/platform/Decimal.h"
+#include "platform/Decimal.h"
#include "wtf/Forward.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/SubmitInputType.cpp b/chromium/third_party/WebKit/Source/core/html/forms/SubmitInputType.cpp
index d10b659b8d2..3b25b468ec1 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/SubmitInputType.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/forms/SubmitInputType.cpp
@@ -32,31 +32,31 @@
#include "config.h"
#include "core/html/forms/SubmitInputType.h"
-#include "core/dom/Event.h"
+#include "InputTypeNames.h"
+#include "core/events/Event.h"
#include "core/html/FormDataList.h"
#include "core/html/HTMLFormElement.h"
#include "core/html/HTMLInputElement.h"
-#include "core/html/forms/InputTypeNames.h"
-#include "core/platform/LocalizedStrings.h"
+#include "platform/text/PlatformLocale.h"
#include "wtf/PassOwnPtr.h"
namespace WebCore {
-PassRefPtr<InputType> SubmitInputType::create(HTMLInputElement* element)
+PassRefPtr<InputType> SubmitInputType::create(HTMLInputElement& element)
{
return adoptRef(new SubmitInputType(element));
}
const AtomicString& SubmitInputType::formControlType() const
{
- return InputTypeNames::submit();
+ return InputTypeNames::submit;
}
bool SubmitInputType::appendFormData(FormDataList& encoding, bool) const
{
- if (!element()->isActivatedSubmit())
+ if (!element().isActivatedSubmit())
return false;
- encoding.appendData(element()->name(), element()->valueWithDefault());
+ encoding.appendData(element().name(), element().valueWithDefault());
return true;
}
@@ -67,7 +67,7 @@ bool SubmitInputType::supportsRequired() const
void SubmitInputType::handleDOMActivateEvent(Event* event)
{
- RefPtr<HTMLInputElement> element = this->element();
+ RefPtr<HTMLInputElement> element(this->element());
if (element->isDisabledFormControl() || !element->form())
return;
element->setActivatedSubmit(true);
@@ -83,7 +83,7 @@ bool SubmitInputType::canBeSuccessfulSubmitButton()
String SubmitInputType::defaultValue() const
{
- return submitButtonDefaultLabel();
+ return locale().queryString(blink::WebLocalizedString::SubmitButtonDefaultLabel);
}
bool SubmitInputType::isSubmitButton() const
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/SubmitInputType.h b/chromium/third_party/WebKit/Source/core/html/forms/SubmitInputType.h
index 4a9c58fa65c..ea88704fe9e 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/SubmitInputType.h
+++ b/chromium/third_party/WebKit/Source/core/html/forms/SubmitInputType.h
@@ -37,10 +37,10 @@ namespace WebCore {
class SubmitInputType : public BaseButtonInputType {
public:
- static PassRefPtr<InputType> create(HTMLInputElement*);
+ static PassRefPtr<InputType> create(HTMLInputElement&);
private:
- SubmitInputType(HTMLInputElement* element) : BaseButtonInputType(element) { }
+ SubmitInputType(HTMLInputElement& element) : BaseButtonInputType(element) { }
virtual const AtomicString& formControlType() const OVERRIDE;
virtual bool appendFormData(FormDataList&, bool) const OVERRIDE;
virtual bool supportsRequired() const OVERRIDE;
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/TelephoneInputType.cpp b/chromium/third_party/WebKit/Source/core/html/forms/TelephoneInputType.cpp
index 933e4aedb60..4b5e2edbd48 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/TelephoneInputType.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/forms/TelephoneInputType.cpp
@@ -31,24 +31,24 @@
#include "config.h"
#include "core/html/forms/TelephoneInputType.h"
-#include "core/html/forms/InputTypeNames.h"
+#include "InputTypeNames.h"
#include "wtf/PassOwnPtr.h"
namespace WebCore {
-PassRefPtr<InputType> TelephoneInputType::create(HTMLInputElement* element)
+PassRefPtr<InputType> TelephoneInputType::create(HTMLInputElement& element)
{
return adoptRef(new TelephoneInputType(element));
}
void TelephoneInputType::countUsage()
{
- observeFeatureIfVisible(UseCounter::InputTypeTel);
+ countUsageIfVisible(UseCounter::InputTypeTel);
}
const AtomicString& TelephoneInputType::formControlType() const
{
- return InputTypeNames::telephone();
+ return InputTypeNames::tel;
}
bool TelephoneInputType::shouldRespectSpeechAttribute()
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/TelephoneInputType.h b/chromium/third_party/WebKit/Source/core/html/forms/TelephoneInputType.h
index b49b0a235c5..d636ee2bff6 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/TelephoneInputType.h
+++ b/chromium/third_party/WebKit/Source/core/html/forms/TelephoneInputType.h
@@ -37,10 +37,10 @@ namespace WebCore {
class TelephoneInputType : public BaseTextInputType {
public:
- static PassRefPtr<InputType> create(HTMLInputElement*);
+ static PassRefPtr<InputType> create(HTMLInputElement&);
private:
- TelephoneInputType(HTMLInputElement* element) : BaseTextInputType(element) { }
+ TelephoneInputType(HTMLInputElement& element) : BaseTextInputType(element) { }
virtual void countUsage() OVERRIDE;
virtual const AtomicString& formControlType() const OVERRIDE;
virtual bool shouldRespectSpeechAttribute() OVERRIDE;
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/TextFieldInputType.cpp b/chromium/third_party/WebKit/Source/core/html/forms/TextFieldInputType.cpp
index 7d915cfb901..0114adab3e8 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/TextFieldInputType.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/forms/TextFieldInputType.cpp
@@ -34,21 +34,23 @@
#include "HTMLNames.h"
#include "bindings/v8/ExceptionStatePlaceholder.h"
-#include "core/dom/BeforeTextInsertedEvent.h"
-#include "core/dom/KeyboardEvent.h"
+#include "core/events/BeforeTextInsertedEvent.h"
+#include "core/events/KeyboardEvent.h"
#include "core/dom/NodeRenderStyle.h"
-#include "core/dom/TextEvent.h"
+#include "core/events/TextEvent.h"
#include "core/dom/shadow/ShadowRoot.h"
-#include "core/editing/Editor.h"
#include "core/editing/FrameSelection.h"
#include "core/editing/TextIterator.h"
#include "core/html/FormDataList.h"
#include "core/html/HTMLInputElement.h"
#include "core/html/shadow/ShadowElementNames.h"
#include "core/html/shadow/TextControlInnerElements.h"
-#include "core/page/Frame.h"
+#include "core/frame/Frame.h"
+#include "core/frame/Settings.h"
+#include "core/page/Chrome.h"
+#include "core/page/ChromeClient.h"
#include "core/page/Page.h"
-#include "core/page/Settings.h"
+#include "core/rendering/RenderDetailsMarker.h"
#include "core/rendering/RenderLayer.h"
#include "core/rendering/RenderTextControlSingleLine.h"
#include "core/rendering/RenderTheme.h"
@@ -58,7 +60,55 @@ namespace WebCore {
using namespace HTMLNames;
-TextFieldInputType::TextFieldInputType(HTMLInputElement* element)
+class DataListIndicatorElement FINAL : public HTMLDivElement {
+private:
+ inline DataListIndicatorElement(Document& document) : HTMLDivElement(document) { }
+ inline HTMLInputElement* hostInput() const { return toHTMLInputElement(shadowHost()); }
+
+ virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE
+ {
+ return new RenderDetailsMarker(this);
+ }
+
+ virtual void* preDispatchEventHandler(Event* event) OVERRIDE
+ {
+ // Chromium opens autofill popup in a mousedown event listener
+ // associated to the document. We don't want to open it in this case
+ // because we opens a datalist chooser later.
+ // FIXME: We should dispatch mousedown events even in such case.
+ if (event->type() == EventTypeNames::mousedown)
+ event->stopPropagation();
+ return 0;
+ }
+
+ virtual void defaultEventHandler(Event* event) OVERRIDE
+ {
+ if (event->type() != EventTypeNames::click)
+ return;
+ HTMLInputElement* host = hostInput();
+ if (host && !host->isDisabledOrReadOnly() && document().page()) {
+ document().page()->chrome().openTextDataListChooser(*host);
+ event->setDefaultHandled();
+ }
+ }
+
+ virtual bool willRespondToMouseClickEvents() OVERRIDE
+ {
+ return hostInput() && !hostInput()->isDisabledOrReadOnly() && document().page();
+ }
+
+public:
+ static PassRefPtr<DataListIndicatorElement> create(Document& document)
+ {
+ RefPtr<DataListIndicatorElement> element = adoptRef(new DataListIndicatorElement(document));
+ element->setPseudo(AtomicString("-webkit-calendar-picker-indicator", AtomicString::ConstructFromLiteral));
+ element->setAttribute(idAttr, ShadowElementNames::pickerIndicator());
+ return element.release();
+ }
+
+};
+
+TextFieldInputType::TextFieldInputType(HTMLInputElement& element)
: InputType(element)
{
}
@@ -71,7 +121,7 @@ TextFieldInputType::~TextFieldInputType()
SpinButtonElement* TextFieldInputType::spinButtonElement() const
{
- return toSpinButtonElement(element()->userAgentShadowRoot()->getElementById(ShadowElementNames::spinButton()));
+ return toSpinButtonElement(element().userAgentShadowRoot()->getElementById(ShadowElementNames::spinButton()));
}
bool TextFieldInputType::shouldShowFocusRingOnMouseFocus() const
@@ -95,7 +145,7 @@ static inline bool shouldIgnoreRequiredAttribute(const HTMLInputElement& input)
bool TextFieldInputType::valueMissing(const String& value) const
{
- return !shouldIgnoreRequiredAttribute(*element()) && element()->isRequired() && value.isEmpty();
+ return !shouldIgnoreRequiredAttribute(element()) && element().isRequired() && value.isEmpty();
}
bool TextFieldInputType::canSetSuggestedValue()
@@ -114,7 +164,7 @@ void TextFieldInputType::setValue(const String& sanitizedValue, bool valueChange
InputType::setValue(sanitizedValue, valueChanged, DispatchNoEvent);
if (valueChanged)
- updateInnerTextValue();
+ updateView();
unsigned max = visibleValue().length();
if (input->focused())
@@ -151,17 +201,18 @@ void TextFieldInputType::setValue(const String& sanitizedValue, bool valueChange
void TextFieldInputType::handleKeydownEvent(KeyboardEvent* event)
{
- if (!element()->focused())
+ if (!element().focused())
return;
- Frame* frame = element()->document().frame();
- if (!frame || !frame->editor().doTextFieldCommandFromEvent(element(), event))
+ if (Chrome* chrome = this->chrome()) {
+ chrome->client().handleKeyboardEventOnTextField(element(), *event);
return;
+ }
event->setDefaultHandled();
}
void TextFieldInputType::handleKeydownEventForSpinButton(KeyboardEvent* event)
{
- if (element()->isDisabledOrReadOnly())
+ if (element().isDisabledOrReadOnly())
return;
const String& key = event->keyIdentifier();
if (key == "Up")
@@ -181,51 +232,53 @@ void TextFieldInputType::forwardEvent(Event* event)
return;
}
- if (element()->renderer() && (event->isMouseEvent() || event->isDragEvent() || event->hasInterface(eventNames().interfaceForWheelEvent) || event->type() == eventNames().blurEvent || event->type() == eventNames().focusEvent)) {
- RenderTextControlSingleLine* renderTextControl = toRenderTextControlSingleLine(element()->renderer());
- if (event->type() == eventNames().blurEvent) {
- if (RenderBox* innerTextRenderer = innerTextElement()->renderBox()) {
+ if (element().renderer() && (event->isMouseEvent() || event->isDragEvent() || event->hasInterface(EventNames::WheelEvent) || event->type() == EventTypeNames::blur || event->type() == EventTypeNames::focus)) {
+ RenderTextControlSingleLine* renderTextControl = toRenderTextControlSingleLine(element().renderer());
+ if (event->type() == EventTypeNames::blur) {
+ if (RenderBox* innerTextRenderer = element().innerTextElement()->renderBox()) {
+ // FIXME: This class has no need to know about RenderLayer!
if (RenderLayer* innerLayer = innerTextRenderer->layer()) {
- IntSize scrollOffset(!renderTextControl->style()->isLeftToRightDirection() ? innerLayer->scrollWidth() : 0, 0);
- innerLayer->scrollToOffset(scrollOffset, ScrollOffsetClamped);
+ RenderLayerScrollableArea* innerScrollableArea = innerLayer->scrollableArea();
+ IntSize scrollOffset(!renderTextControl->style()->isLeftToRightDirection() ? innerScrollableArea->scrollWidth() : 0, 0);
+ innerScrollableArea->scrollToOffset(scrollOffset, ScrollOffsetClamped);
}
}
renderTextControl->capsLockStateMayHaveChanged();
- } else if (event->type() == eventNames().focusEvent) {
+ } else if (event->type() == EventTypeNames::focus) {
renderTextControl->capsLockStateMayHaveChanged();
}
- element()->forwardEvent(event);
+ element().forwardEvent(event);
}
}
void TextFieldInputType::handleFocusEvent(Element* oldFocusedNode, FocusDirection focusDirection)
{
InputType::handleFocusEvent(oldFocusedNode, focusDirection);
- element()->beginEditing();
+ element().beginEditing();
}
void TextFieldInputType::handleBlurEvent()
{
InputType::handleBlurEvent();
- element()->endEditing();
+ element().endEditing();
}
bool TextFieldInputType::shouldSubmitImplicitly(Event* event)
{
- return (event->type() == eventNames().textInputEvent && event->hasInterface(eventNames().interfaceForTextEvent) && toTextEvent(event)->data() == "\n") || InputType::shouldSubmitImplicitly(event);
+ return (event->type() == EventTypeNames::textInput && event->hasInterface(EventNames::TextEvent) && toTextEvent(event)->data() == "\n") || InputType::shouldSubmitImplicitly(event);
}
RenderObject* TextFieldInputType::createRenderer(RenderStyle*) const
{
- return new RenderTextControlSingleLine(element());
+ return new RenderTextControlSingleLine(&element());
}
bool TextFieldInputType::needsContainer() const
{
#if ENABLE(INPUT_SPEECH)
- return element()->isSpeechEnabled();
+ return element().isSpeechEnabled();
#else
return false;
#endif
@@ -233,67 +286,96 @@ bool TextFieldInputType::needsContainer() const
bool TextFieldInputType::shouldHaveSpinButton() const
{
- return RenderTheme::theme().shouldHaveSpinButton(element());
+ return RenderTheme::theme().shouldHaveSpinButton(&element());
}
void TextFieldInputType::createShadowSubtree()
{
- ASSERT(element()->shadow());
- ShadowRoot* shadowRoot = element()->userAgentShadowRoot();
+ ASSERT(element().shadow());
+ ShadowRoot* shadowRoot = element().userAgentShadowRoot();
ASSERT(!shadowRoot->hasChildNodes());
- Document& document = element()->document();
+ Document& document = element().document();
bool shouldHaveSpinButton = this->shouldHaveSpinButton();
- bool createsContainer = shouldHaveSpinButton || needsContainer();
+ bool shouldHaveDataListIndicator = element().hasValidDataListOptions();
+ bool createsContainer = shouldHaveSpinButton || shouldHaveDataListIndicator || needsContainer();
- m_innerText = TextControlInnerTextElement::create(document);
+ RefPtr<TextControlInnerTextElement> innerEditor = TextControlInnerTextElement::create(document);
if (!createsContainer) {
- shadowRoot->appendChild(m_innerText);
+ shadowRoot->appendChild(innerEditor.release());
return;
}
- m_container = TextControlInnerContainer::create(document);
- m_container->setPart(AtomicString("-webkit-textfield-decoration-container", AtomicString::ConstructFromLiteral));
- shadowRoot->appendChild(m_container);
+ RefPtr<TextControlInnerContainer> container = TextControlInnerContainer::create(document);
+ container->setPseudo(AtomicString("-webkit-textfield-decoration-container", AtomicString::ConstructFromLiteral));
+ shadowRoot->appendChild(container);
RefPtr<EditingViewPortElement> editingViewPort = EditingViewPortElement::create(document);
- editingViewPort->appendChild(m_innerText);
- m_container->appendChild(editingViewPort.release());
+ editingViewPort->appendChild(innerEditor.release());
+ container->appendChild(editingViewPort.release());
#if ENABLE(INPUT_SPEECH)
- if (element()->isSpeechEnabled())
- m_container->appendChild(InputFieldSpeechButtonElement::create(document));
+ if (element().isSpeechEnabled())
+ container->appendChild(InputFieldSpeechButtonElement::create(document));
#endif
+ if (shouldHaveDataListIndicator)
+ container->appendChild(DataListIndicatorElement::create(document));
+ // FIXME: Because of a special handling for a spin button in
+ // RenderTextControlSingleLine, we need to put it to the last position. It's
+ // inconsistent with multiple-fields date/time types.
if (shouldHaveSpinButton)
- m_container->appendChild(SpinButtonElement::create(document, *this));
-}
+ container->appendChild(SpinButtonElement::create(document, *this));
-HTMLElement* TextFieldInputType::containerElement() const
-{
- return m_container.get();
+ // See listAttributeTargetChanged too.
}
-HTMLElement* TextFieldInputType::innerTextElement() const
+Element* TextFieldInputType::containerElement() const
{
- ASSERT(m_innerText);
- return m_innerText.get();
+ return element().userAgentShadowRoot()->getElementById(ShadowElementNames::textFieldContainer());
}
void TextFieldInputType::destroyShadowSubtree()
{
InputType::destroyShadowSubtree();
- m_innerText.clear();
if (SpinButtonElement* spinButton = spinButtonElement())
spinButton->removeSpinButtonOwner();
- m_container.clear();
+}
+
+void TextFieldInputType::listAttributeTargetChanged()
+{
+ Element* picker = element().userAgentShadowRoot()->getElementById(ShadowElementNames::pickerIndicator());
+ bool didHavePickerIndicator = picker;
+ bool willHavePickerIndicator = element().hasValidDataListOptions();
+ if (didHavePickerIndicator == willHavePickerIndicator)
+ return;
+ if (willHavePickerIndicator) {
+ Document& document = element().document();
+ if (Element* container = containerElement()) {
+ container->insertBefore(DataListIndicatorElement::create(document), spinButtonElement());
+ } else {
+ // FIXME: The following code is similar to createShadowSubtree(),
+ // but they are different. We should simplify the code by making
+ // containerElement mandatory.
+ RefPtr<Element> rpContainer = TextControlInnerContainer::create(document);
+ rpContainer->setPseudo(AtomicString("-webkit-textfield-decoration-container", AtomicString::ConstructFromLiteral));
+ RefPtr<Element> innerEditor = element().innerTextElement();
+ innerEditor->parentNode()->replaceChild(rpContainer.get(), innerEditor.get());
+ RefPtr<Element> editingViewPort = EditingViewPortElement::create(document);
+ editingViewPort->appendChild(innerEditor.release());
+ rpContainer->appendChild(editingViewPort.release());
+ rpContainer->appendChild(DataListIndicatorElement::create(document));
+ }
+ } else {
+ picker->remove(ASSERT_NO_EXCEPTION);
+ }
}
void TextFieldInputType::attributeChanged()
{
- // FIXME: Updating the inner text on any attribute update should
- // be unnecessary. We should figure out what attributes affect.
- updateInnerTextValue();
+ // FIXME: Updating on any attribute update should be unnecessary. We should
+ // figure out what attributes affect.
+ updateView();
}
void TextFieldInputType::disabledAttributeChanged()
@@ -354,19 +436,19 @@ void TextFieldInputType::handleBeforeTextInsertedEvent(BeforeTextInsertedEvent*
// We use HTMLInputElement::innerTextValue() instead of
// HTMLInputElement::value() because they can be mismatched by
// sanitizeValue() in HTMLInputElement::subtreeHasChanged() in some cases.
- unsigned oldLength = element()->innerTextValue().length();
+ unsigned oldLength = element().innerTextValue().length();
// selectionLength represents the selection length of this text field to be
// removed by this insertion.
// If the text field has no focus, we don't need to take account of the
// selection length. The selection is the source of text drag-and-drop in
// that case, and nothing in the text field will be removed.
- unsigned selectionLength = element()->focused() ? plainText(element()->document().frame()->selection().selection().toNormalizedRange().get()).length() : 0;
+ unsigned selectionLength = element().focused() ? plainText(element().document().frame()->selection().selection().toNormalizedRange().get()).length() : 0;
ASSERT(oldLength >= selectionLength);
// Selected characters will be removed by the next text event.
unsigned baseLength = oldLength - selectionLength;
- unsigned maxLength = static_cast<unsigned>(isTextType() ? element()->maxLength() : HTMLInputElement::maximumLength); // maxLength can never be negative.
+ unsigned maxLength = static_cast<unsigned>(isTextType() ? element().maxLength() : HTMLInputElement::maximumLength); // maxLength can never be negative.
unsigned appendableLength = maxLength > baseLength ? maxLength - baseLength : 0;
// Truncate the inserted text to avoid violating the maxLength and other constraints.
@@ -391,29 +473,32 @@ void TextFieldInputType::updatePlaceholderText()
{
if (!supportsPlaceholder())
return;
- HTMLElement* placeholder = element()->placeholderElement();
- String placeholderText = element()->strippedPlaceholder();
+ HTMLElement* placeholder = element().placeholderElement();
+ String placeholderText = element().strippedPlaceholder();
if (placeholderText.isEmpty()) {
if (placeholder)
placeholder->remove(ASSERT_NO_EXCEPTION);
return;
}
if (!placeholder) {
- RefPtr<HTMLElement> newElement = HTMLDivElement::create(element()->document());
+ RefPtr<HTMLElement> newElement = HTMLDivElement::create(element().document());
placeholder = newElement.get();
- placeholder->setPart(AtomicString("-webkit-input-placeholder", AtomicString::ConstructFromLiteral));
+ placeholder->setPseudo(AtomicString("-webkit-input-placeholder", AtomicString::ConstructFromLiteral));
placeholder->setAttribute(idAttr, ShadowElementNames::placeholder());
- element()->userAgentShadowRoot()->insertBefore(placeholder, m_container ? m_container->nextSibling() : innerTextElement()->nextSibling());
+ Element* container = containerElement();
+ Node* previous = container ? container : element().innerTextElement();
+ previous->parentNode()->insertBefore(placeholder, previous->nextSibling());
+ ASSERT_WITH_SECURITY_IMPLICATION(placeholder->parentNode() == previous->parentNode());
}
- placeholder->setTextContent(placeholderText, ASSERT_NO_EXCEPTION);
+ placeholder->setTextContent(placeholderText);
}
bool TextFieldInputType::appendFormData(FormDataList& list, bool multipart) const
{
InputType::appendFormData(list, multipart);
- const AtomicString& dirnameAttrValue = element()->fastGetAttribute(dirnameAttr);
+ const AtomicString& dirnameAttrValue = element().fastGetAttribute(dirnameAttr);
if (!dirnameAttrValue.isNull())
- list.appendData(dirnameAttrValue, element()->directionForFormData());
+ list.appendData(dirnameAttrValue, element().directionForFormData());
return true;
}
@@ -424,29 +509,29 @@ String TextFieldInputType::convertFromVisibleValue(const String& visibleValue) c
void TextFieldInputType::subtreeHasChanged()
{
- ASSERT(element()->renderer());
+ ASSERT(element().renderer());
- bool wasChanged = element()->wasChangedSinceLastFormControlChangeEvent();
- element()->setChangedSinceLastFormControlChangeEvent(true);
+ bool wasChanged = element().wasChangedSinceLastFormControlChangeEvent();
+ element().setChangedSinceLastFormControlChangeEvent(true);
// We don't need to call sanitizeUserInputValue() function here because
// HTMLInputElement::handleBeforeTextInsertedEvent() has already called
// sanitizeUserInputValue().
// sanitizeValue() is needed because IME input doesn't dispatch BeforeTextInsertedEvent.
- element()->setValueFromRenderer(sanitizeValue(convertFromVisibleValue(element()->innerTextValue())));
- element()->updatePlaceholderVisibility(false);
+ element().setValueFromRenderer(sanitizeValue(convertFromVisibleValue(element().innerTextValue())));
+ element().updatePlaceholderVisibility(false);
// Recalc for :invalid change.
- element()->setNeedsStyleRecalc();
+ element().setNeedsStyleRecalc();
didSetValueByUserEdit(wasChanged ? ValueChangeStateChanged : ValueChangeStateNone);
}
void TextFieldInputType::didSetValueByUserEdit(ValueChangeState state)
{
- if (!element()->focused())
+ if (!element().focused())
return;
- if (Frame* frame = element()->document().frame())
- frame->editor().textDidChangeInTextField(element());
+ if (Chrome* chrome = this->chrome())
+ chrome->client().didChangeValueInTextField(element());
}
void TextFieldInputType::spinButtonStepDown()
@@ -459,16 +544,16 @@ void TextFieldInputType::spinButtonStepUp()
stepUpFromRenderer(1);
}
-void TextFieldInputType::updateInnerTextValue()
+void TextFieldInputType::updateView()
{
- if (!element()->suggestedValue().isNull()) {
- element()->setInnerTextValue(element()->suggestedValue());
- element()->updatePlaceholderVisibility(false);
- } else if (!element()->formControlValueMatchesRenderer()) {
+ if (!element().suggestedValue().isNull()) {
+ element().setInnerTextValue(element().suggestedValue());
+ element().updatePlaceholderVisibility(false);
+ } else if (!element().formControlValueMatchesRenderer()) {
// Update the renderer value if the formControlValueMatchesRenderer() flag is false.
// It protects an unacceptable renderer value from being overwritten with the DOM value.
- element()->setInnerTextValue(visibleValue());
- element()->updatePlaceholderVisibility(false);
+ element().setInnerTextValue(visibleValue());
+ element().updatePlaceholderVisibility(false);
}
}
@@ -481,12 +566,12 @@ void TextFieldInputType::focusAndSelectSpinButtonOwner()
bool TextFieldInputType::shouldSpinButtonRespondToMouseEvents()
{
- return !element()->isDisabledOrReadOnly();
+ return !element().isDisabledOrReadOnly();
}
bool TextFieldInputType::shouldSpinButtonRespondToWheelEvents()
{
- return shouldSpinButtonRespondToMouseEvents() && element()->focused();
+ return shouldSpinButtonRespondToMouseEvents() && element().focused();
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/TextFieldInputType.h b/chromium/third_party/WebKit/Source/core/html/forms/TextFieldInputType.h
index 360708e6a5f..38d5d9ed57f 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/TextFieldInputType.h
+++ b/chromium/third_party/WebKit/Source/core/html/forms/TextFieldInputType.h
@@ -42,15 +42,12 @@ class FormDataList;
// It supports not only the types for BaseTextInputType but also type=number.
class TextFieldInputType : public InputType, protected SpinButtonElement::SpinButtonOwner {
protected:
- TextFieldInputType(HTMLInputElement*);
+ TextFieldInputType(HTMLInputElement&);
virtual ~TextFieldInputType();
virtual bool canSetSuggestedValue() OVERRIDE;
virtual void handleKeydownEvent(KeyboardEvent*) OVERRIDE;
void handleKeydownEventForSpinButton(KeyboardEvent*);
- virtual HTMLElement* containerElement() const OVERRIDE;
- virtual HTMLElement* innerTextElement() const OVERRIDE;
-
protected:
virtual bool needsContainer() const;
virtual bool shouldHaveSpinButton() const;
@@ -63,7 +60,7 @@ protected:
virtual void handleFocusEvent(Element* oldFocusedNode, FocusDirection) OVERRIDE;
virtual void handleBlurEvent() OVERRIDE;
virtual void setValue(const String&, bool valueChanged, TextFieldEventBehavior) OVERRIDE;
- virtual void updateInnerTextValue() OVERRIDE;
+ virtual void updateView() OVERRIDE;
virtual String convertFromVisibleValue(const String&) const;
enum ValueChangeState {
@@ -72,6 +69,8 @@ protected:
};
virtual void didSetValueByUserEdit(ValueChangeState);
+ Element* containerElement() const;
+
private:
virtual bool shouldShowFocusRingOnMouseFocus() const OVERRIDE;
virtual bool isTextField() const OVERRIDE;
@@ -83,6 +82,7 @@ private:
virtual bool shouldUseInputMethod() const OVERRIDE;
virtual String sanitizeValue(const String&) const OVERRIDE;
virtual bool shouldRespectListAttribute() OVERRIDE;
+ virtual void listAttributeTargetChanged() OVERRIDE;
virtual void updatePlaceholderText() OVERRIDE;
virtual bool appendFormData(FormDataList&, bool multipart) const OVERRIDE;
virtual void subtreeHasChanged() OVERRIDE;
@@ -95,9 +95,6 @@ private:
virtual void spinButtonStepUp() OVERRIDE;
SpinButtonElement* spinButtonElement() const;
-
- RefPtr<HTMLElement> m_container;
- RefPtr<HTMLElement> m_innerText;
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/TextInputType.cpp b/chromium/third_party/WebKit/Source/core/html/forms/TextInputType.cpp
index 0b1d56dcdc7..a5e9db19398 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/TextInputType.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/forms/TextInputType.cpp
@@ -31,31 +31,34 @@
#include "config.h"
#include "core/html/forms/TextInputType.h"
+#include "InputTypeNames.h"
#include "core/html/HTMLInputElement.h"
-#include "core/html/forms/InputTypeNames.h"
#include "wtf/PassOwnPtr.h"
namespace WebCore {
using namespace HTMLNames;
-PassRefPtr<InputType> TextInputType::create(HTMLInputElement* element)
+PassRefPtr<InputType> TextInputType::create(HTMLInputElement& element)
{
return adoptRef(new TextInputType(element));
}
void TextInputType::countUsage()
{
- const AtomicString& type = element()->fastGetAttribute(typeAttr);
- if (equalIgnoringCase(type, InputTypeNames::datetime()))
- observeFeatureIfVisible(UseCounter::InputTypeDateTimeFallback);
- else if (equalIgnoringCase(type, InputTypeNames::week()))
- observeFeatureIfVisible(UseCounter::InputTypeWeekFallback);
+ countUsageIfVisible(UseCounter::InputTypeText);
+ if (element().fastHasAttribute(maxlengthAttr))
+ countUsageIfVisible(UseCounter::InputTypeTextMaxLength);
+ const AtomicString& type = element().fastGetAttribute(typeAttr);
+ if (equalIgnoringCase(type, InputTypeNames::datetime))
+ countUsageIfVisible(UseCounter::InputTypeDateTimeFallback);
+ else if (equalIgnoringCase(type, InputTypeNames::week))
+ countUsageIfVisible(UseCounter::InputTypeWeekFallback);
}
const AtomicString& TextInputType::formControlType() const
{
- return InputTypeNames::text();
+ return InputTypeNames::text;
}
bool TextInputType::shouldRespectSpeechAttribute()
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/TextInputType.h b/chromium/third_party/WebKit/Source/core/html/forms/TextInputType.h
index 378036a878b..8fb1e8c2447 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/TextInputType.h
+++ b/chromium/third_party/WebKit/Source/core/html/forms/TextInputType.h
@@ -37,10 +37,10 @@ namespace WebCore {
class TextInputType : public BaseTextInputType {
public:
- static PassRefPtr<InputType> create(HTMLInputElement*);
+ static PassRefPtr<InputType> create(HTMLInputElement&);
private:
- TextInputType(HTMLInputElement* element) : BaseTextInputType(element) { }
+ TextInputType(HTMLInputElement& element) : BaseTextInputType(element) { }
virtual void countUsage() OVERRIDE;
virtual const AtomicString& formControlType() const OVERRIDE;
virtual bool shouldRespectSpeechAttribute() OVERRIDE;
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/TimeInputType.cpp b/chromium/third_party/WebKit/Source/core/html/forms/TimeInputType.cpp
index 08ee92d234e..22d80ef7e1e 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/TimeInputType.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/forms/TimeInputType.cpp
@@ -32,11 +32,11 @@
#include "core/html/forms/TimeInputType.h"
#include "HTMLNames.h"
+#include "InputTypeNames.h"
#include "core/html/HTMLInputElement.h"
#include "core/html/forms/DateTimeFieldsState.h"
-#include "core/html/forms/InputTypeNames.h"
-#include "core/platform/DateComponents.h"
-#include "core/platform/text/PlatformLocale.h"
+#include "platform/DateComponents.h"
+#include "platform/text/PlatformLocale.h"
#include "wtf/CurrentTime.h"
#include "wtf/DateMath.h"
#include "wtf/MathExtras.h"
@@ -51,29 +51,24 @@ static const int timeDefaultStep = 60;
static const int timeDefaultStepBase = 0;
static const int timeStepScaleFactor = 1000;
-TimeInputType::TimeInputType(HTMLInputElement* element)
+TimeInputType::TimeInputType(HTMLInputElement& element)
: BaseTimeInputType(element)
{
}
-PassRefPtr<InputType> TimeInputType::create(HTMLInputElement* element)
+PassRefPtr<InputType> TimeInputType::create(HTMLInputElement& element)
{
return adoptRef(new TimeInputType(element));
}
void TimeInputType::countUsage()
{
- observeFeatureIfVisible(UseCounter::InputTypeTime);
+ countUsageIfVisible(UseCounter::InputTypeTime);
}
const AtomicString& TimeInputType::formControlType() const
{
- return InputTypeNames::time();
-}
-
-DateComponents::Type TimeInputType::dateType() const
-{
- return DateComponents::Time;
+ return InputTypeNames::time;
}
Decimal TimeInputType::defaultValueForStepUp() const
@@ -95,11 +90,7 @@ StepRange TimeInputType::createStepRange(AnyStepHandling anyStepHandling) const
{
DEFINE_STATIC_LOCAL(const StepRange::StepDescription, stepDescription, (timeDefaultStep, timeDefaultStepBase, timeStepScaleFactor, StepRange::ScaledStepValueShouldBeInteger));
- const Decimal stepBase = parseToNumber(element()->fastGetAttribute(minAttr), 0);
- const Decimal minimum = parseToNumber(element()->fastGetAttribute(minAttr), Decimal::fromDouble(DateComponents::minimumTime()));
- const Decimal maximum = parseToNumber(element()->fastGetAttribute(maxAttr), Decimal::fromDouble(DateComponents::maximumTime()));
- const Decimal step = StepRange::parseStep(anyStepHandling, stepDescription, element()->fastGetAttribute(stepAttr));
- return StepRange(stepBase, minimum, maximum, step, stepDescription);
+ return InputType::createStepRange(anyStepHandling, 0, Decimal::fromDouble(DateComponents::minimumTime()), Decimal::fromDouble(DateComponents::maximumTime()), stepDescription);
}
bool TimeInputType::parseToDateComponentsInternal(const String& string, DateComponents* out) const
@@ -130,7 +121,7 @@ String TimeInputType::localizeValue(const String& proposedValue) const
Locale::FormatType formatType = shouldHaveSecondField(date) ? Locale::FormatTypeMedium : Locale::FormatTypeShort;
- String localized = element()->locale().formatDateTime(date, formatType);
+ String localized = element().locale().formatDateTime(date, formatType);
return localized.isEmpty() ? proposedValue : localized;
}
@@ -163,9 +154,9 @@ void TimeInputType::setupLayoutParameters(DateTimeEditElement::LayoutParameters&
layoutParameters.dateTimeFormat = layoutParameters.locale.shortTimeFormat();
layoutParameters.fallbackDateTimeFormat = "HH:mm";
}
- if (!parseToDateComponents(element()->fastGetAttribute(minAttr), &layoutParameters.minimum))
+ if (!parseToDateComponents(element().fastGetAttribute(minAttr), &layoutParameters.minimum))
layoutParameters.minimum = DateComponents();
- if (!parseToDateComponents(element()->fastGetAttribute(maxAttr), &layoutParameters.maximum))
+ if (!parseToDateComponents(element().fastGetAttribute(maxAttr), &layoutParameters.maximum))
layoutParameters.maximum = DateComponents();
}
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/TimeInputType.h b/chromium/third_party/WebKit/Source/core/html/forms/TimeInputType.h
index dfccfa1d4de..82a540d52f6 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/TimeInputType.h
+++ b/chromium/third_party/WebKit/Source/core/html/forms/TimeInputType.h
@@ -44,13 +44,12 @@ typedef BaseChooserOnlyDateAndTimeInputType BaseTimeInputType;
class TimeInputType : public BaseTimeInputType {
public:
- static PassRefPtr<InputType> create(HTMLInputElement*);
+ static PassRefPtr<InputType> create(HTMLInputElement&);
private:
- TimeInputType(HTMLInputElement*);
+ TimeInputType(HTMLInputElement&);
virtual void countUsage() OVERRIDE;
virtual const AtomicString& formControlType() const OVERRIDE;
- virtual DateComponents::Type dateType() const OVERRIDE;
virtual Decimal defaultValueForStepUp() const OVERRIDE;
virtual StepRange createStepRange(AnyStepHandling) const OVERRIDE;
virtual bool parseToDateComponentsInternal(const String&, DateComponents*) const OVERRIDE;
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/TypeAhead.cpp b/chromium/third_party/WebKit/Source/core/html/forms/TypeAhead.cpp
index 739f742b691..e9a0052edad 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/TypeAhead.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/forms/TypeAhead.cpp
@@ -28,7 +28,7 @@
#include "config.h"
#include "core/html/forms/TypeAhead.h"
-#include "core/dom/KeyboardEvent.h"
+#include "core/events/KeyboardEvent.h"
#include "wtf/unicode/CharacterNames.h"
using namespace WTF::Unicode;
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/URLInputType.cpp b/chromium/third_party/WebKit/Source/core/html/forms/URLInputType.cpp
index 4b2ebfba892..33017eb34c7 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/URLInputType.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/forms/URLInputType.cpp
@@ -31,26 +31,26 @@
#include "config.h"
#include "core/html/forms/URLInputType.h"
+#include "InputTypeNames.h"
#include "core/html/HTMLInputElement.h"
-#include "core/html/forms/InputTypeNames.h"
-#include "core/platform/LocalizedStrings.h"
+#include "platform/text/PlatformLocale.h"
#include "wtf/PassOwnPtr.h"
namespace WebCore {
-PassRefPtr<InputType> URLInputType::create(HTMLInputElement* element)
+PassRefPtr<InputType> URLInputType::create(HTMLInputElement& element)
{
return adoptRef(new URLInputType(element));
}
void URLInputType::countUsage()
{
- observeFeatureIfVisible(UseCounter::InputTypeURL);
+ countUsageIfVisible(UseCounter::InputTypeURL);
}
const AtomicString& URLInputType::formControlType() const
{
- return InputTypeNames::url();
+ return InputTypeNames::url;
}
bool URLInputType::typeMismatchFor(const String& value) const
@@ -60,12 +60,12 @@ bool URLInputType::typeMismatchFor(const String& value) const
bool URLInputType::typeMismatch() const
{
- return typeMismatchFor(element()->value());
+ return typeMismatchFor(element().value());
}
String URLInputType::typeMismatchText() const
{
- return validationMessageTypeMismatchForURLText();
+ return locale().queryString(blink::WebLocalizedString::ValidationTypeMismatchForURL);
}
bool URLInputType::isURLField() const
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/URLInputType.h b/chromium/third_party/WebKit/Source/core/html/forms/URLInputType.h
index 7c310b52d7d..98f53f21b38 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/URLInputType.h
+++ b/chromium/third_party/WebKit/Source/core/html/forms/URLInputType.h
@@ -37,10 +37,10 @@ namespace WebCore {
class URLInputType : public BaseTextInputType {
public:
- static PassRefPtr<InputType> create(HTMLInputElement*);
+ static PassRefPtr<InputType> create(HTMLInputElement&);
private:
- URLInputType(HTMLInputElement* element) : BaseTextInputType(element) { }
+ URLInputType(HTMLInputElement& element) : BaseTextInputType(element) { }
virtual void countUsage() OVERRIDE;
virtual const AtomicString& formControlType() const OVERRIDE;
virtual bool typeMismatchFor(const String&) const OVERRIDE;
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/WeekInputType.cpp b/chromium/third_party/WebKit/Source/core/html/forms/WeekInputType.cpp
index dd1cc4dd543..419b1603ddc 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/WeekInputType.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/forms/WeekInputType.cpp
@@ -32,11 +32,11 @@
#include "core/html/forms/WeekInputType.h"
#include "HTMLNames.h"
+#include "InputTypeNames.h"
#include "core/html/HTMLInputElement.h"
#include "core/html/forms/DateTimeFieldsState.h"
-#include "core/html/forms/InputTypeNames.h"
-#include "core/platform/DateComponents.h"
-#include "core/platform/LocalizedStrings.h"
+#include "platform/DateComponents.h"
+#include "platform/text/PlatformLocale.h"
#include "wtf/PassOwnPtr.h"
#include "wtf/text/WTFString.h"
@@ -48,35 +48,26 @@ static const int weekDefaultStepBase = -259200000; // The first day of 1970-W01.
static const int weekDefaultStep = 1;
static const int weekStepScaleFactor = 604800000;
-PassRefPtr<InputType> WeekInputType::create(HTMLInputElement* element)
+PassRefPtr<InputType> WeekInputType::create(HTMLInputElement& element)
{
return adoptRef(new WeekInputType(element));
}
void WeekInputType::countUsage()
{
- observeFeatureIfVisible(UseCounter::InputTypeWeek);
+ countUsageIfVisible(UseCounter::InputTypeWeek);
}
const AtomicString& WeekInputType::formControlType() const
{
- return InputTypeNames::week();
-}
-
-DateComponents::Type WeekInputType::dateType() const
-{
- return DateComponents::Week;
+ return InputTypeNames::week;
}
StepRange WeekInputType::createStepRange(AnyStepHandling anyStepHandling) const
{
DEFINE_STATIC_LOCAL(const StepRange::StepDescription, stepDescription, (weekDefaultStep, weekDefaultStepBase, weekStepScaleFactor, StepRange::ParsedStepValueShouldBeInteger));
- const Decimal stepBase = parseToNumber(element()->fastGetAttribute(minAttr), weekDefaultStepBase);
- const Decimal minimum = parseToNumber(element()->fastGetAttribute(minAttr), Decimal::fromDouble(DateComponents::minimumWeek()));
- const Decimal maximum = parseToNumber(element()->fastGetAttribute(maxAttr), Decimal::fromDouble(DateComponents::maximumWeek()));
- const Decimal step = StepRange::parseStep(anyStepHandling, stepDescription, element()->fastGetAttribute(stepAttr));
- return StepRange(stepBase, minimum, maximum, step, stepDescription);
+ return InputType::createStepRange(anyStepHandling, weekDefaultStepBase, Decimal::fromDouble(DateComponents::minimumWeek()), Decimal::fromDouble(DateComponents::maximumWeek()), stepDescription);
}
bool WeekInputType::parseToDateComponentsInternal(const String& string, DateComponents* out) const
@@ -108,11 +99,11 @@ String WeekInputType::formatDateTimeFieldsState(const DateTimeFieldsState& dateT
void WeekInputType::setupLayoutParameters(DateTimeEditElement::LayoutParameters& layoutParameters, const DateComponents&) const
{
- layoutParameters.dateTimeFormat = weekFormatInLDML();
+ layoutParameters.dateTimeFormat = locale().weekFormatInLDML();
layoutParameters.fallbackDateTimeFormat = "yyyy-'W'ww";
- if (!parseToDateComponents(element()->fastGetAttribute(minAttr), &layoutParameters.minimum))
+ if (!parseToDateComponents(element().fastGetAttribute(minAttr), &layoutParameters.minimum))
layoutParameters.minimum = DateComponents();
- if (!parseToDateComponents(element()->fastGetAttribute(maxAttr), &layoutParameters.maximum))
+ if (!parseToDateComponents(element().fastGetAttribute(maxAttr), &layoutParameters.maximum))
layoutParameters.maximum = DateComponents();
layoutParameters.placeholderForYear = "----";
}
diff --git a/chromium/third_party/WebKit/Source/core/html/forms/WeekInputType.h b/chromium/third_party/WebKit/Source/core/html/forms/WeekInputType.h
index 0450eb10d8a..9455039c61a 100644
--- a/chromium/third_party/WebKit/Source/core/html/forms/WeekInputType.h
+++ b/chromium/third_party/WebKit/Source/core/html/forms/WeekInputType.h
@@ -44,13 +44,12 @@ typedef BaseChooserOnlyDateAndTimeInputType BaseWeekInputType;
class WeekInputType : public BaseWeekInputType {
public:
- static PassRefPtr<InputType> create(HTMLInputElement*);
+ static PassRefPtr<InputType> create(HTMLInputElement&);
private:
- WeekInputType(HTMLInputElement* element) : BaseWeekInputType(element) { }
+ WeekInputType(HTMLInputElement& element) : BaseWeekInputType(element) { }
virtual void countUsage() OVERRIDE;
virtual const AtomicString& formControlType() const OVERRIDE;
- virtual DateComponents::Type dateType() const OVERRIDE;
virtual StepRange createStepRange(AnyStepHandling) const OVERRIDE;
virtual bool parseToDateComponentsInternal(const String&, DateComponents*) const OVERRIDE;
virtual bool setMillisecondToDateComponents(double, DateComponents*) const OVERRIDE;
diff --git a/chromium/third_party/WebKit/Source/core/html/ime/Composition.cpp b/chromium/third_party/WebKit/Source/core/html/ime/Composition.cpp
index 9b40000a5b2..17250b38ba6 100644
--- a/chromium/third_party/WebKit/Source/core/html/ime/Composition.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/ime/Composition.cpp
@@ -31,27 +31,53 @@
#include "config.h"
#include "core/html/ime/Composition.h"
+#include "core/html/ime/InputMethodContext.h"
+
namespace WebCore {
Composition::~Composition()
{
}
-PassRefPtr<Composition> Composition::create()
+void Composition::ref()
+{
+ m_inputMethodContext->ref();
+}
+
+void Composition::deref()
{
- return adoptRef(new Composition());
+ m_inputMethodContext->deref();
}
-Composition::Composition()
- : m_selectionStart(0)
- , m_selectionEnd(0)
+PassOwnPtr<Composition> Composition::create(InputMethodContext* context)
+{
+ return adoptPtr(new Composition(context));
+}
+
+Composition::Composition(InputMethodContext* context)
+ : m_inputMethodContext(context)
{
ScriptWrappable::init(this);
}
+String Composition::text() const
+{
+ return m_inputMethodContext->compositionText();
+}
+
+int Composition::selectionStart() const
+{
+ return m_inputMethodContext->selectionStart();
+}
+
+int Composition::selectionEnd() const
+{
+ return m_inputMethodContext->selectionEnd();
+}
+
const Vector<unsigned>& Composition::getSegments() const
{
- return m_segments;
+ return m_inputMethodContext->segments();
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/html/ime/Composition.h b/chromium/third_party/WebKit/Source/core/html/ime/Composition.h
index a180c867ee0..43054668f0d 100644
--- a/chromium/third_party/WebKit/Source/core/html/ime/Composition.h
+++ b/chromium/third_party/WebKit/Source/core/html/ime/Composition.h
@@ -32,36 +32,30 @@
#define Composition_h
#include "bindings/v8/ScriptWrappable.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/RefPtr.h"
+#include "wtf/PassOwnPtr.h"
#include "wtf/text/WTFString.h"
namespace WebCore {
-class Composition : public RefCounted<Composition>, public ScriptWrappable {
+class InputMethodContext;
+
+class Composition : public ScriptWrappable {
public:
- static PassRefPtr<Composition> create();
+ static PassOwnPtr<Composition> create(InputMethodContext*);
~Composition();
- String text() const { return m_text; }
- void setText(const String& text) { m_text = text; }
-
- int selectionStart() const { return m_selectionStart; }
- void setSelectionStart(int selectionStart) { selectionStart = m_selectionStart; }
-
- int selectionEnd() const { return m_selectionEnd; }
- void setSelectionEnd(int selectionEnd) { selectionEnd = m_selectionEnd; }
+ void ref();
+ void deref();
+ String text() const;
+ int selectionStart() const;
+ int selectionEnd() const;
const Vector<unsigned>& getSegments() const;
private:
- Composition();
+ explicit Composition(InputMethodContext*);
- String m_text;
- int m_selectionStart;
- int m_selectionEnd;
- Vector<unsigned> m_segments;
+ InputMethodContext* m_inputMethodContext;
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/html/ime/InputMethodContext.cpp b/chromium/third_party/WebKit/Source/core/html/ime/InputMethodContext.cpp
index 87560063a51..74643ac6db0 100644
--- a/chromium/third_party/WebKit/Source/core/html/ime/InputMethodContext.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/ime/InputMethodContext.cpp
@@ -31,9 +31,10 @@
#include "config.h"
#include "core/html/ime/InputMethodContext.h"
+#include "core/dom/Text.h"
#include "core/editing/InputMethodController.h"
#include "core/html/ime/Composition.h"
-#include "core/page/Frame.h"
+#include "core/frame/Frame.h"
namespace WebCore {
@@ -43,8 +44,7 @@ PassOwnPtr<InputMethodContext> InputMethodContext::create(HTMLElement* element)
}
InputMethodContext::InputMethodContext(HTMLElement* element)
- : m_composition(0)
- , m_element(element)
+ : m_element(element)
{
ScriptWrappable::init(this);
}
@@ -53,10 +53,10 @@ InputMethodContext::~InputMethodContext()
{
}
-Composition* InputMethodContext::composition() const
+Composition* InputMethodContext::composition()
{
- // FIXME: Implement this. This should lazily update the composition object
- // here.
+ if (!m_composition)
+ m_composition = Composition::create(this);
return m_composition.get();
}
@@ -71,27 +71,126 @@ HTMLElement* InputMethodContext::target() const
return m_element;
}
+unsigned InputMethodContext::compositionStartOffset()
+{
+ if (hasFocus())
+ return inputMethodController().compositionStart();
+ return 0;
+}
+
+unsigned InputMethodContext::compositionEndOffset()
+{
+ if (hasFocus())
+ return inputMethodController().compositionEnd();
+ return 0;
+}
+
void InputMethodContext::confirmComposition()
{
+ if (hasFocus())
+ inputMethodController().confirmCompositionAndResetState();
+}
+
+bool InputMethodContext::hasFocus() const
+{
Frame* frame = m_element->document().frame();
if (!frame)
- return;
+ return false;
const Element* element = frame->document()->focusedElement();
- if (!element || !element->isHTMLElement() || m_element != toHTMLElement(element))
- return;
+ return element && element->isHTMLElement() && m_element == toHTMLElement(element);
+}
+
+String InputMethodContext::compositionText() const
+{
+ if (!hasFocus())
+ return emptyString();
- frame->inputMethodController().confirmCompositionAndResetState();
+ Text* text = inputMethodController().compositionNode();
+ return text ? text->wholeText() : emptyString();
}
-void InputMethodContext::setCaretRectangle(Node* anchor, int x, int y, int w, int h)
+CompositionUnderline InputMethodContext::selectedSegment() const
{
- // FIXME: Implement this.
+ CompositionUnderline underline;
+ if (!hasFocus())
+ return underline;
+
+ const InputMethodController& controller = inputMethodController();
+ if (!controller.hasComposition())
+ return underline;
+
+ Vector<CompositionUnderline> underlines = controller.customCompositionUnderlines();
+ for (size_t i = 0; i < underlines.size(); ++i) {
+ if (underlines[i].thick)
+ return underlines[i];
+ }
+
+ // When no underline information is available while composition exists,
+ // build a CompositionUnderline whose element is the whole composition.
+ underline.endOffset = controller.compositionEnd() - controller.compositionStart();
+ return underline;
+
}
-void InputMethodContext::setExclusionRectangle(Node* anchor, int x, int y, int w, int h)
+int InputMethodContext::selectionStart() const
{
- // FIXME: Implement this.
+ return selectedSegment().startOffset;
+}
+
+int InputMethodContext::selectionEnd() const
+{
+ return selectedSegment().endOffset;
+}
+
+const Vector<unsigned>& InputMethodContext::segments()
+{
+ m_segments.clear();
+ if (!hasFocus())
+ return m_segments;
+ const InputMethodController& controller = inputMethodController();
+ if (!controller.hasComposition())
+ return m_segments;
+
+ Vector<CompositionUnderline> underlines = controller.customCompositionUnderlines();
+ if (!underlines.size()) {
+ m_segments.append(0);
+ } else {
+ for (size_t i = 0; i < underlines.size(); ++i)
+ m_segments.append(underlines[i].startOffset);
+ }
+
+ return m_segments;
+}
+
+InputMethodController& InputMethodContext::inputMethodController() const
+{
+ return m_element->document().frame()->inputMethodController();
+}
+
+const AtomicString& InputMethodContext::interfaceName() const
+{
+ return EventTargetNames::InputMethodContext;
+}
+
+ExecutionContext* InputMethodContext::executionContext() const
+{
+ return &m_element->document();
+}
+
+void InputMethodContext::dispatchCandidateWindowShowEvent()
+{
+ dispatchEvent(Event::create(EventTypeNames::candidatewindowshow));
+}
+
+void InputMethodContext::dispatchCandidateWindowUpdateEvent()
+{
+ dispatchEvent(Event::create(EventTypeNames::candidatewindowupdate));
+}
+
+void InputMethodContext::dispatchCandidateWindowHideEvent()
+{
+ dispatchEvent(Event::create(EventTypeNames::candidatewindowhide));
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/html/ime/InputMethodContext.h b/chromium/third_party/WebKit/Source/core/html/ime/InputMethodContext.h
index e75be3905a9..16bb6ffe17a 100644
--- a/chromium/third_party/WebKit/Source/core/html/ime/InputMethodContext.h
+++ b/chromium/third_party/WebKit/Source/core/html/ime/InputMethodContext.h
@@ -32,17 +32,22 @@
#define InputMethodContext_h
#include "bindings/v8/ScriptWrappable.h"
+#include "core/editing/CompositionUnderline.h"
+#include "core/events/EventTarget.h"
#include "core/html/HTMLElement.h"
#include "wtf/PassOwnPtr.h"
#include "wtf/RefPtr.h"
+#include "wtf/text/AtomicString.h"
#include "wtf/text/WTFString.h"
namespace WebCore {
class Composition;
+class ExecutionContext;
+class InputMethodController;
class Node;
-class InputMethodContext : public ScriptWrappable {
+class InputMethodContext : public ScriptWrappable, public EventTargetWithInlineData {
public:
static PassOwnPtr<InputMethodContext> create(HTMLElement*);
~InputMethodContext();
@@ -50,17 +55,41 @@ public:
void ref() { m_element->ref(); }
void deref() { m_element->deref(); }
- Composition* composition() const;
+ Composition* composition();
String locale() const;
HTMLElement* target() const;
+ unsigned compositionStartOffset();
+ unsigned compositionEndOffset();
void confirmComposition();
- void setCaretRectangle(Node* anchor, int x, int y, int w, int h);
- void setExclusionRectangle(Node* anchor, int x, int y, int w, int h);
+
+ String compositionText() const;
+ int selectionStart() const;
+ int selectionEnd() const;
+ const Vector<unsigned>& segments();
+
+ virtual const AtomicString& interfaceName() const OVERRIDE;
+ virtual ExecutionContext* executionContext() const OVERRIDE;
+
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(candidatewindowshow);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(candidatewindowupdate);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(candidatewindowhide);
+
+ void dispatchCandidateWindowShowEvent();
+ void dispatchCandidateWindowUpdateEvent();
+ void dispatchCandidateWindowHideEvent();
private:
InputMethodContext(HTMLElement*);
- RefPtr<Composition> m_composition;
+ bool hasFocus() const;
+ CompositionUnderline selectedSegment() const;
+ InputMethodController& inputMethodController() const;
+
+ virtual void refEventTarget() OVERRIDE { ref(); }
+ virtual void derefEventTarget() OVERRIDE { deref(); }
+
HTMLElement* m_element;
+ OwnPtr<Composition> m_composition;
+ Vector<unsigned> m_segments;
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/html/ime/InputMethodContext.idl b/chromium/third_party/WebKit/Source/core/html/ime/InputMethodContext.idl
index 2ad97b95292..8ce8c4a43d6 100644
--- a/chromium/third_party/WebKit/Source/core/html/ime/InputMethodContext.idl
+++ b/chromium/third_party/WebKit/Source/core/html/ime/InputMethodContext.idl
@@ -29,12 +29,16 @@
*/
// http://www.w3.org/TR/ime-api/
-[
-] interface InputMethodContext {
+interface InputMethodContext : EventTarget {
readonly attribute Composition composition;
readonly attribute DOMString locale;
readonly attribute HTMLElement target;
+ readonly attribute unsigned long compositionStartOffset;
+ readonly attribute unsigned long compositionEndOffset;
+
void confirmComposition();
- void setCaretRectangle(Node anchor, long x, long y, long w, long h);
- void setExclusionRectangle(Node anchor, long x, long y, long w, long h);
+
+ attribute EventHandler oncandidatewindowshow;
+ attribute EventHandler oncandidatewindowupdate;
+ attribute EventHandler oncandidatewindowhide;
};
diff --git a/chromium/third_party/WebKit/Source/core/html/parser/AtomicHTMLToken.h b/chromium/third_party/WebKit/Source/core/html/parser/AtomicHTMLToken.h
index 2d74f8e1930..63e8c0c86dc 100644
--- a/chromium/third_party/WebKit/Source/core/html/parser/AtomicHTMLToken.h
+++ b/chromium/third_party/WebKit/Source/core/html/parser/AtomicHTMLToken.h
@@ -26,6 +26,7 @@
#ifndef AtomicHTMLToken_h
#define AtomicHTMLToken_h
+#include "HTMLElementLookupTrie.h"
#include "core/dom/Attribute.h"
#include "core/html/parser/CompactHTMLToken.h"
#include "core/html/parser/HTMLToken.h"
@@ -124,7 +125,10 @@ public:
case HTMLToken::StartTag:
case HTMLToken::EndTag: {
m_selfClosing = token.selfClosing();
- m_name = AtomicString(token.name());
+ if (StringImpl* tagName = lookupHTMLTag(token.name().data(), token.name().size()))
+ m_name = AtomicString(tagName);
+ else
+ m_name = AtomicString(token.name());
initializeAttributes(token.attributes());
break;
}
@@ -146,10 +150,10 @@ public:
ASSERT_NOT_REACHED();
break;
case HTMLToken::DOCTYPE:
- m_name = token.data().asString();
+ m_name = token.data();
m_doctypeData = adoptPtr(new DoctypeData());
m_doctypeData->m_hasPublicIdentifier = true;
- append(m_doctypeData->m_publicIdentifier, token.publicIdentifier().asString());
+ append(m_doctypeData->m_publicIdentifier, token.publicIdentifier());
m_doctypeData->m_hasSystemIdentifier = true;
append(m_doctypeData->m_systemIdentifier, token.systemIdentifier());
m_doctypeData->m_forceQuirks = token.doctypeForcesQuirks();
@@ -159,7 +163,7 @@ public:
case HTMLToken::StartTag:
m_attributes.reserveInitialCapacity(token.attributes().size());
for (Vector<CompactHTMLToken::Attribute>::const_iterator it = token.attributes().begin(); it != token.attributes().end(); ++it) {
- QualifiedName name(nullAtom, it->name.asString(), nullAtom);
+ QualifiedName name(nullAtom, it->name, nullAtom);
// FIXME: This is N^2 for the number of attributes.
if (!findAttributeInVector(m_attributes, name))
m_attributes.append(Attribute(name, it->value));
@@ -167,11 +171,11 @@ public:
// Fall through!
case HTMLToken::EndTag:
m_selfClosing = token.selfClosing();
- m_name = token.data().asString();
+ m_name = token.data();
break;
case HTMLToken::Character:
case HTMLToken::Comment:
- m_data = token.data().asString();
+ m_data = token.data();
break;
}
}
diff --git a/chromium/third_party/WebKit/Source/core/html/parser/BackgroundHTMLInputStream.cpp b/chromium/third_party/WebKit/Source/core/html/parser/BackgroundHTMLInputStream.cpp
index 6f536082c63..05ccea8e021 100644
--- a/chromium/third_party/WebKit/Source/core/html/parser/BackgroundHTMLInputStream.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/parser/BackgroundHTMLInputStream.cpp
@@ -31,6 +31,7 @@ namespace WebCore {
BackgroundHTMLInputStream::BackgroundHTMLInputStream()
: m_firstValidCheckpointIndex(0)
, m_firstValidSegmentIndex(0)
+ , m_totalCheckpointTokenCount(0)
{
}
@@ -45,10 +46,11 @@ void BackgroundHTMLInputStream::close()
m_current.close();
}
-HTMLInputCheckpoint BackgroundHTMLInputStream::createCheckpoint()
+HTMLInputCheckpoint BackgroundHTMLInputStream::createCheckpoint(size_t tokensExtractedSincePreviousCheckpoint)
{
HTMLInputCheckpoint checkpoint = m_checkpoints.size();
- m_checkpoints.append(Checkpoint(m_current, m_segments.size()));
+ m_checkpoints.append(Checkpoint(m_current, m_segments.size(), tokensExtractedSincePreviousCheckpoint));
+ m_totalCheckpointTokenCount += tokensExtractedSincePreviousCheckpoint;
return checkpoint;
}
@@ -70,6 +72,8 @@ void BackgroundHTMLInputStream::invalidateCheckpointsBefore(HTMLInputCheckpoint
for (size_t i = m_firstValidCheckpointIndex; i < newFirstValidCheckpointIndex; ++i)
m_checkpoints[i].clear();
m_firstValidCheckpointIndex = newFirstValidCheckpointIndex;
+
+ updateTotalCheckpointTokenCount();
}
void BackgroundHTMLInputStream::rewindTo(HTMLInputCheckpoint checkpointIndex, const String& unparsedInput)
@@ -99,6 +103,16 @@ void BackgroundHTMLInputStream::rewindTo(HTMLInputCheckpoint checkpointIndex, co
m_checkpoints.clear();
m_firstValidCheckpointIndex = 0;
m_firstValidSegmentIndex = 0;
+
+ updateTotalCheckpointTokenCount();
+}
+
+void BackgroundHTMLInputStream::updateTotalCheckpointTokenCount()
+{
+ m_totalCheckpointTokenCount = 0;
+ size_t lastCheckpointIndex = m_checkpoints.size();
+ for (size_t i = 0; i < lastCheckpointIndex; ++i)
+ m_totalCheckpointTokenCount += m_checkpoints[i].tokensExtractedSincePreviousCheckpoint;
}
}
diff --git a/chromium/third_party/WebKit/Source/core/html/parser/BackgroundHTMLInputStream.h b/chromium/third_party/WebKit/Source/core/html/parser/BackgroundHTMLInputStream.h
index 3ffc16cba94..ba12b63e070 100644
--- a/chromium/third_party/WebKit/Source/core/html/parser/BackgroundHTMLInputStream.h
+++ b/chromium/third_party/WebKit/Source/core/html/parser/BackgroundHTMLInputStream.h
@@ -26,7 +26,7 @@
#ifndef BackgroundHTMLInputStream_h
#define BackgroundHTMLInputStream_h
-#include "core/platform/text/SegmentedString.h"
+#include "platform/text/SegmentedString.h"
#include "wtf/Vector.h"
#include "wtf/text/WTFString.h"
@@ -46,23 +46,24 @@ public:
// An HTMLInputCheckpoint is valid until the next call to rewindTo, at which
// point all outstanding checkpoints are invalidated.
- HTMLInputCheckpoint createCheckpoint();
+ HTMLInputCheckpoint createCheckpoint(size_t tokensExtractedSincePreviousCheckpoint);
void rewindTo(HTMLInputCheckpoint, const String& unparsedInput);
void invalidateCheckpointsBefore(HTMLInputCheckpoint);
- size_t outstandingCheckpointCount() const { return m_checkpoints.size() - m_firstValidCheckpointIndex; }
+ size_t totalCheckpointTokenCount() const { return m_totalCheckpointTokenCount; }
private:
struct Checkpoint {
- Checkpoint(const SegmentedString& i, size_t n) : input(i), numberOfSegmentsAlreadyAppended(n) { }
+ Checkpoint(const SegmentedString& i, size_t n, size_t t) : input(i), numberOfSegmentsAlreadyAppended(n), tokensExtractedSincePreviousCheckpoint(t) { }
SegmentedString input;
size_t numberOfSegmentsAlreadyAppended;
+ size_t tokensExtractedSincePreviousCheckpoint;
#ifndef NDEBUG
bool isNull() const { return input.isEmpty() && !numberOfSegmentsAlreadyAppended; }
#endif
- void clear() { input.clear(); numberOfSegmentsAlreadyAppended = 0; }
+ void clear() { input.clear(); numberOfSegmentsAlreadyAppended = 0; tokensExtractedSincePreviousCheckpoint = 0;}
};
SegmentedString m_current;
@@ -72,6 +73,9 @@ private:
// Note: These indicies may === vector.size(), in which case there are no valid checkpoints/segments at this time.
size_t m_firstValidCheckpointIndex;
size_t m_firstValidSegmentIndex;
+ size_t m_totalCheckpointTokenCount;
+
+ void updateTotalCheckpointTokenCount();
};
}
diff --git a/chromium/third_party/WebKit/Source/core/html/parser/BackgroundHTMLParser.cpp b/chromium/third_party/WebKit/Source/core/html/parser/BackgroundHTMLParser.cpp
index 23747edd7eb..b91dafd40b9 100644
--- a/chromium/third_party/WebKit/Source/core/html/parser/BackgroundHTMLParser.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/parser/BackgroundHTMLParser.cpp
@@ -28,7 +28,6 @@
#include "core/html/parser/HTMLDocumentParser.h"
#include "core/html/parser/HTMLParserThread.h"
-#include "core/html/parser/HTMLTokenizer.h"
#include "core/html/parser/XSSAuditor.h"
#include "wtf/MainThread.h"
#include "wtf/text/TextPosition.h"
@@ -39,14 +38,14 @@ namespace WebCore {
// with a fast CPU, we could end up speculatively tokenizing
// the whole document, well ahead of when the main-thread actually needs it.
// This is a waste of memory (and potentially time if the speculation fails).
-// So we limit our outstanding speculations arbitrarily to 10.
+// So we limit our outstanding tokens arbitrarily to 10,000.
// Our maximal memory spent speculating will be approximately:
-// outstandingCheckpointLimit * pendingTokenLimit * sizeof(CompactToken)
+// (outstandingTokenLimit + pendingTokenLimit) * sizeof(CompactToken)
// We use a separate low and high water mark to avoid constantly topping
// off the main thread's token buffer.
-// At time of writing, this is 10 * 1000 * 28 bytes = appox 280kb of memory.
+// At time of writing, this is (10000 + 1000) * 28 bytes = ~308kb of memory.
// These numbers have not been tuned.
-static const size_t outstandingCheckpointLimit = 10;
+static const size_t outstandingTokenLimit = 10000;
// We limit our chucks to 1000 tokens, to make sure the main
// thread is never waiting on the parser thread for tokens.
@@ -69,6 +68,12 @@ static void checkThatPreloadsAreSafeToSendToAnotherThread(const PreloadRequestSt
ASSERT(preloads[i]->isSafeToSendToAnotherThread());
}
+static void checkThatXSSInfosAreSafeToSendToAnotherThread(const XSSInfoStream& infos)
+{
+ for (size_t i = 0; i < infos.size(); ++i)
+ ASSERT(infos[i]->isSafeToSendToAnotherThread());
+}
+
#endif
BackgroundHTMLParser::BackgroundHTMLParser(PassRefPtr<WeakReference<BackgroundHTMLParser> > reference, PassOwnPtr<Configuration> config)
@@ -139,7 +144,7 @@ void BackgroundHTMLParser::markEndOfFile()
void BackgroundHTMLParser::pumpTokenizer()
{
// No need to start speculating until the main thread has almost caught up.
- if (m_input.outstandingCheckpointCount() > outstandingCheckpointLimit)
+ if (m_input.totalCheckpointTokenCount() > outstandingTokenLimit)
return;
while (true) {
@@ -171,7 +176,7 @@ void BackgroundHTMLParser::pumpTokenizer()
if (!m_treeBuilderSimulator.simulate(m_pendingTokens->last(), m_tokenizer.get()) || m_pendingTokens->size() >= pendingTokenLimit) {
sendTokensToMainThread();
// If we're far ahead of the main thread, yield for a bit to avoid consuming too much memory.
- if (m_input.outstandingCheckpointCount() > outstandingCheckpointLimit)
+ if (m_input.totalCheckpointTokenCount() > outstandingTokenLimit)
break;
}
}
@@ -185,16 +190,17 @@ void BackgroundHTMLParser::sendTokensToMainThread()
#ifndef NDEBUG
checkThatTokensAreSafeToSendToAnotherThread(m_pendingTokens.get());
checkThatPreloadsAreSafeToSendToAnotherThread(m_pendingPreloads);
+ checkThatXSSInfosAreSafeToSendToAnotherThread(m_pendingXSSInfos);
#endif
OwnPtr<HTMLDocumentParser::ParsedChunk> chunk = adoptPtr(new HTMLDocumentParser::ParsedChunk);
- chunk->tokens = m_pendingTokens.release();
chunk->preloads.swap(m_pendingPreloads);
chunk->xssInfos.swap(m_pendingXSSInfos);
chunk->tokenizerState = m_tokenizer->state();
chunk->treeBuilderState = m_treeBuilderSimulator.state();
- chunk->inputCheckpoint = m_input.createCheckpoint();
+ chunk->inputCheckpoint = m_input.createCheckpoint(m_pendingTokens->size());
chunk->preloadScannerCheckpoint = m_preloadScanner->createCheckpoint();
+ chunk->tokens = m_pendingTokens.release();
callOnMainThread(bind(&HTMLDocumentParser::didReceiveParsedChunkFromBackgroundParser, m_parser, chunk.release()));
m_pendingTokens = adoptPtr(new CompactHTMLTokenStream);
diff --git a/chromium/third_party/WebKit/Source/core/html/parser/CSSPreloadScanner.cpp b/chromium/third_party/WebKit/Source/core/html/parser/CSSPreloadScanner.cpp
index af3ff09d9cc..b1eea275aaa 100644
--- a/chromium/third_party/WebKit/Source/core/html/parser/CSSPreloadScanner.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/parser/CSSPreloadScanner.cpp
@@ -29,9 +29,8 @@
#include "core/html/parser/CSSPreloadScanner.h"
#include "FetchInitiatorTypeNames.h"
-#include "core/html/parser/HTMLIdentifier.h"
#include "core/html/parser/HTMLParserIdioms.h"
-#include "core/platform/text/SegmentedString.h"
+#include "platform/text/SegmentedString.h"
namespace WebCore {
@@ -66,16 +65,15 @@ void CSSPreloadScanner::scan(const HTMLToken::DataVector& data, const SegmentedS
scanCommon(data.data(), data.data() + data.size(), source, requests);
}
-void CSSPreloadScanner::scan(const HTMLIdentifier& identifier, const SegmentedString& source, PreloadRequestStream& requests)
+void CSSPreloadScanner::scan(const String& tagName, const SegmentedString& source, PreloadRequestStream& requests)
{
- const StringImpl* data = identifier.asStringImpl();
- if (data->is8Bit()) {
- const LChar* begin = data->characters8();
- scanCommon(begin, begin + data->length(), source, requests);
+ if (tagName.is8Bit()) {
+ const LChar* begin = tagName.characters8();
+ scanCommon(begin, begin + tagName.length(), source, requests);
return;
}
- const UChar* begin = data->characters16();
- scanCommon(begin, begin + data->length(), source, requests);
+ const UChar* begin = tagName.characters16();
+ scanCommon(begin, begin + tagName.length(), source, requests);
}
inline void CSSPreloadScanner::tokenize(UChar c, const SegmentedString& source)
diff --git a/chromium/third_party/WebKit/Source/core/html/parser/CSSPreloadScanner.h b/chromium/third_party/WebKit/Source/core/html/parser/CSSPreloadScanner.h
index 07e3b175d0c..7161a27434e 100644
--- a/chromium/third_party/WebKit/Source/core/html/parser/CSSPreloadScanner.h
+++ b/chromium/third_party/WebKit/Source/core/html/parser/CSSPreloadScanner.h
@@ -45,7 +45,7 @@ public:
void reset();
void scan(const HTMLToken::DataVector&, const SegmentedString&, PreloadRequestStream&);
- void scan(const HTMLIdentifier&, const SegmentedString&, PreloadRequestStream&);
+ void scan(const String&, const SegmentedString&, PreloadRequestStream&);
private:
enum State {
diff --git a/chromium/third_party/WebKit/Source/core/html/parser/CompactHTMLToken.cpp b/chromium/third_party/WebKit/Source/core/html/parser/CompactHTMLToken.cpp
index 11c4f639e21..4a826e839b3 100644
--- a/chromium/third_party/WebKit/Source/core/html/parser/CompactHTMLToken.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/parser/CompactHTMLToken.cpp
@@ -28,13 +28,12 @@
#include "core/dom/QualifiedName.h"
#include "core/html/parser/HTMLParserIdioms.h"
-#include "core/html/parser/HTMLToken.h"
namespace WebCore {
struct SameSizeAsCompactHTMLToken {
unsigned bitfields;
- HTMLIdentifier data;
+ String data;
Vector<Attribute> vector;
TextPosition textPosition;
};
@@ -52,10 +51,11 @@ CompactHTMLToken::CompactHTMLToken(const HTMLToken* token, const TextPosition& t
ASSERT_NOT_REACHED();
break;
case HTMLToken::DOCTYPE: {
- m_data = HTMLIdentifier(token->name(), Likely8Bit);
+ m_data = attemptStaticStringCreation(token->name(), Likely8Bit);
+
// There is only 1 DOCTYPE token per document, so to avoid increasing the
// size of CompactHTMLToken, we just use the m_attributes vector.
- m_attributes.append(Attribute(HTMLIdentifier(token->publicIdentifier(), Likely8Bit), String(token->systemIdentifier())));
+ m_attributes.append(Attribute(attemptStaticStringCreation(token->publicIdentifier(), Likely8Bit), String(token->systemIdentifier())));
m_doctypeForcesQuirks = token->forceQuirks();
break;
}
@@ -64,7 +64,7 @@ CompactHTMLToken::CompactHTMLToken(const HTMLToken* token, const TextPosition& t
case HTMLToken::StartTag:
m_attributes.reserveInitialCapacity(token->attributes().size());
for (Vector<HTMLToken::Attribute>::const_iterator it = token->attributes().begin(); it != token->attributes().end(); ++it)
- m_attributes.append(Attribute(HTMLIdentifier(it->name, Likely8Bit), StringImpl::create8BitIfPossible(it->value)));
+ m_attributes.append(Attribute(attemptStaticStringCreation(it->name, Likely8Bit), StringImpl::create8BitIfPossible(it->value)));
// Fall through!
case HTMLToken::EndTag:
m_selfClosing = token->selfClosing();
@@ -72,7 +72,7 @@ CompactHTMLToken::CompactHTMLToken(const HTMLToken* token, const TextPosition& t
case HTMLToken::Comment:
case HTMLToken::Character: {
m_isAll8BitData = token->isAll8BitData();
- m_data = HTMLIdentifier(token->data(), token->isAll8BitData() ? Force8Bit : Force16Bit);
+ m_data = attemptStaticStringCreation(token->data(), token->isAll8BitData() ? Force8Bit : Force16Bit);
break;
}
default:
diff --git a/chromium/third_party/WebKit/Source/core/html/parser/CompactHTMLToken.h b/chromium/third_party/WebKit/Source/core/html/parser/CompactHTMLToken.h
index 89ef4ca6a02..3858e03a094 100644
--- a/chromium/third_party/WebKit/Source/core/html/parser/CompactHTMLToken.h
+++ b/chromium/third_party/WebKit/Source/core/html/parser/CompactHTMLToken.h
@@ -26,7 +26,6 @@
#ifndef CompactHTMLToken_h
#define CompactHTMLToken_h
-#include "core/html/parser/HTMLIdentifier.h"
#include "core/html/parser/HTMLToken.h"
#include "wtf/Vector.h"
#include "wtf/text/TextPosition.h"
@@ -39,13 +38,13 @@ class QualifiedName;
class CompactHTMLToken {
public:
struct Attribute {
- Attribute(const HTMLIdentifier& name, const String& value)
+ Attribute(const String& name, const String& value)
: name(name)
, value(value)
{
}
- HTMLIdentifier name;
+ String name;
String value;
};
@@ -54,7 +53,7 @@ public:
bool isSafeToSendToAnotherThread() const;
HTMLToken::Type type() const { return static_cast<HTMLToken::Type>(m_type); }
- const HTMLIdentifier& data() const { return m_data; }
+ const String& data() const { return m_data; }
bool selfClosing() const { return m_selfClosing; }
bool isAll8BitData() const { return m_isAll8BitData; }
const Vector<Attribute>& attributes() const { return m_attributes; }
@@ -63,7 +62,7 @@ public:
// There is only 1 DOCTYPE token per document, so to avoid increasing the
// size of CompactHTMLToken, we just use the m_attributes vector.
- const HTMLIdentifier& publicIdentifier() const { return m_attributes[0].name; }
+ const String& publicIdentifier() const { return m_attributes[0].name; }
const String& systemIdentifier() const { return m_attributes[0].value; }
bool doctypeForcesQuirks() const { return m_doctypeForcesQuirks; }
@@ -73,7 +72,7 @@ private:
unsigned m_isAll8BitData : 1;
unsigned m_doctypeForcesQuirks: 1;
- HTMLIdentifier m_data; // "name", "characters", or "data" depending on m_type
+ String m_data; // "name", "characters", or "data" depending on m_type
Vector<Attribute> m_attributes;
TextPosition m_textPosition;
};
diff --git a/chromium/third_party/WebKit/Source/core/html/parser/HTMLConstructionSite.cpp b/chromium/third_party/WebKit/Source/core/html/parser/HTMLConstructionSite.cpp
index 169f06711cc..96dc2484b4b 100644
--- a/chromium/third_party/WebKit/Source/core/html/parser/HTMLConstructionSite.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/parser/HTMLConstructionSite.cpp
@@ -46,8 +46,9 @@
#include "core/html/parser/HTMLToken.h"
#include "core/loader/FrameLoader.h"
#include "core/loader/FrameLoaderClient.h"
-#include "core/page/Frame.h"
-#include "core/platform/NotImplemented.h"
+#include "core/frame/Frame.h"
+#include "platform/NotImplemented.h"
+#include "platform/text/TextBreakIterator.h"
#include <limits>
namespace WebCore {
@@ -82,6 +83,11 @@ static bool shouldUseLengthLimit(const ContainerNode* node)
&& !node->hasTagName(SVGNames::scriptTag);
}
+static unsigned textLengthLimitForContainer(const ContainerNode* node)
+{
+ return shouldUseLengthLimit(node) ? Text::defaultLengthLimit : std::numeric_limits<unsigned>::max();
+}
+
static inline bool isAllWhitespace(const String& string)
{
return string.isAllSpecialCharacters<isHTMLSpace<UChar> >();
@@ -93,10 +99,10 @@ static inline void insert(HTMLConstructionSiteTask& task)
task.parent = toHTMLTemplateElement(task.parent.get())->content();
if (ContainerNode* parent = task.child->parentNode())
- parent->parserRemoveChild(task.child.get());
+ parent->parserRemoveChild(*task.child);
if (task.nextChild)
- task.parent->parserInsertBefore(task.child.get(), task.nextChild.get());
+ task.parent->parserInsertBefore(task.child.get(), *task.nextChild);
else
task.parent->parserAppendChild(task.child.get());
}
@@ -113,12 +119,33 @@ static inline void executeInsertTask(HTMLConstructionSiteTask& task)
task.child->finishParsingChildren();
}
+static inline void executeInsertTextTask(HTMLConstructionSiteTask& task)
+{
+ ASSERT(task.operation == HTMLConstructionSiteTask::InsertText);
+ ASSERT(task.child->isTextNode());
+
+ // Merge text nodes into previous ones if possible:
+ // http://www.whatwg.org/specs/web-apps/current-work/multipage/tree-construction.html#insert-a-character
+ Text* newText = toText(task.child.get());
+ Node* previousChild = task.nextChild ? task.nextChild->previousSibling() : task.parent->lastChild();
+ if (previousChild && previousChild->isTextNode()) {
+ Text* previousText = toText(previousChild);
+ unsigned lengthLimit = textLengthLimitForContainer(task.parent.get());
+ if (previousText->length() + newText->length() < lengthLimit) {
+ previousText->parserAppendData(newText->data());
+ return;
+ }
+ }
+
+ insert(task);
+}
+
static inline void executeReparentTask(HTMLConstructionSiteTask& task)
{
ASSERT(task.operation == HTMLConstructionSiteTask::Reparent);
if (ContainerNode* parent = task.child->parentNode())
- parent->parserRemoveChild(task.child.get());
+ parent->parserRemoveChild(*task.child);
task.parent->parserAppendChild(task.child);
}
@@ -134,16 +161,18 @@ static inline void executeTakeAllChildrenTask(HTMLConstructionSiteTask& task)
{
ASSERT(task.operation == HTMLConstructionSiteTask::TakeAllChildren);
- task.parent->takeAllChildrenFrom(task.oldParent());
- // Notice that we don't need to manually attach the moved children
- // because takeAllChildrenFrom does that work for us.
+ task.parent->parserTakeAllChildrenFrom(*task.oldParent());
}
-static inline void executeTask(HTMLConstructionSiteTask& task)
+void HTMLConstructionSite::executeTask(HTMLConstructionSiteTask& task)
{
+ ASSERT(m_taskQueue.isEmpty());
if (task.operation == HTMLConstructionSiteTask::Insert)
return executeInsertTask(task);
+ if (task.operation == HTMLConstructionSiteTask::InsertText)
+ return executeInsertTextTask(task);
+
// All the cases below this point are only used by the adoption agency.
if (task.operation == HTMLConstructionSiteTask::InsertAlreadyParsedChild)
@@ -158,6 +187,88 @@ static inline void executeTask(HTMLConstructionSiteTask& task)
ASSERT_NOT_REACHED();
}
+// This is only needed for TextDocuments where we might have text nodes
+// approaching the default length limit (~64k) and we don't want to
+// break a text node in the middle of a combining character.
+static unsigned findBreakIndexBetween(const StringBuilder& string, unsigned currentPosition, unsigned proposedBreakIndex)
+{
+ ASSERT(currentPosition < proposedBreakIndex);
+ ASSERT(proposedBreakIndex <= string.length());
+ // The end of the string is always a valid break.
+ if (proposedBreakIndex == string.length())
+ return proposedBreakIndex;
+
+ // Latin-1 does not have breakable boundaries. If we ever moved to a differnet 8-bit encoding this could be wrong.
+ if (string.is8Bit())
+ return proposedBreakIndex;
+
+ const UChar* breakSearchCharacters = string.characters16() + currentPosition;
+ // We need at least two characters look-ahead to account for UTF-16 surrogates, but can't search off the end of the buffer!
+ unsigned breakSearchLength = std::min(proposedBreakIndex - currentPosition + 2, string.length() - currentPosition);
+ NonSharedCharacterBreakIterator it(breakSearchCharacters, breakSearchLength);
+
+ if (it.isBreak(proposedBreakIndex - currentPosition))
+ return proposedBreakIndex;
+
+ int adjustedBreakIndexInSubstring = it.preceding(proposedBreakIndex - currentPosition);
+ if (adjustedBreakIndexInSubstring > 0)
+ return currentPosition + adjustedBreakIndexInSubstring;
+ // We failed to find a breakable point, let the caller figure out what to do.
+ return 0;
+}
+
+static String atomizeIfAllWhitespace(const String& string, WhitespaceMode whitespaceMode)
+{
+ // Strings composed entirely of whitespace are likely to be repeated.
+ // Turn them into AtomicString so we share a single string for each.
+ if (whitespaceMode == AllWhitespace || (whitespaceMode == WhitespaceUnknown && isAllWhitespace(string)))
+ return AtomicString(string).string();
+ return string;
+}
+
+void HTMLConstructionSite::flushPendingText()
+{
+ if (m_pendingText.isEmpty())
+ return;
+
+ PendingText pendingText;
+ // Hold onto the current pending text on the stack so that queueTask doesn't recurse infinitely.
+ m_pendingText.swap(pendingText);
+ ASSERT(m_pendingText.isEmpty());
+
+ // Splitting text nodes into smaller chunks contradicts HTML5 spec, but is necessary
+ // for performance, see: https://bugs.webkit.org/show_bug.cgi?id=55898
+ unsigned lengthLimit = textLengthLimitForContainer(pendingText.parent.get());
+
+ unsigned currentPosition = 0;
+ const StringBuilder& string = pendingText.stringBuilder;
+ while (currentPosition < string.length()) {
+ unsigned proposedBreakIndex = std::min(currentPosition + lengthLimit, string.length());
+ unsigned breakIndex = findBreakIndexBetween(string, currentPosition, proposedBreakIndex);
+ ASSERT(breakIndex <= string.length());
+ String substring = string.substring(currentPosition, breakIndex - currentPosition);
+ substring = atomizeIfAllWhitespace(substring, pendingText.whitespaceMode);
+
+ HTMLConstructionSiteTask task(HTMLConstructionSiteTask::InsertText);
+ task.parent = pendingText.parent;
+ task.nextChild = pendingText.nextChild;
+ task.child = Text::create(task.parent->document(), substring);
+ queueTask(task);
+
+ ASSERT(breakIndex > currentPosition);
+ ASSERT(breakIndex - currentPosition == substring.length());
+ ASSERT(toText(task.child.get())->length() == substring.length());
+ currentPosition = breakIndex;
+ }
+}
+
+void HTMLConstructionSite::queueTask(const HTMLConstructionSiteTask& task)
+{
+ flushPendingText();
+ ASSERT(m_pendingText.isEmpty());
+ m_taskQueue.append(task);
+}
+
void HTMLConstructionSite::attachLater(ContainerNode* parent, PassRefPtr<Node> prpChild, bool selfClosing)
{
ASSERT(scriptingContentIsAllowed(m_parserContentPolicy) || !prpChild.get()->isElementNode() || !toScriptLoaderIfPossible(toElement(prpChild.get())));
@@ -178,11 +289,13 @@ void HTMLConstructionSite::attachLater(ContainerNode* parent, PassRefPtr<Node> p
task.parent = task.parent->parentNode();
ASSERT(task.parent);
- m_taskQueue.append(task);
+ queueTask(task);
}
void HTMLConstructionSite::executeQueuedTasks()
{
+ // This has no affect on pendingText, and we may have pendingText
+ // remaining after executing all other queued tasks.
const size_t size = m_taskQueue.size();
if (!size)
return;
@@ -222,10 +335,20 @@ HTMLConstructionSite::HTMLConstructionSite(DocumentFragment* fragment, ParserCon
HTMLConstructionSite::~HTMLConstructionSite()
{
+ // Depending on why we're being destroyed it might be OK
+ // to forget queued tasks, but currently we don't expect to.
+ ASSERT(m_taskQueue.isEmpty());
+ // Currently we assume that text will never be the last token in the
+ // document and that we'll always queue some additional task to cause it to flush.
+ ASSERT(m_pendingText.isEmpty());
}
void HTMLConstructionSite::detach()
{
+ // FIXME: We'd like to ASSERT here that we're canceling and not just discarding
+ // text that really should have made it into the DOM earlier, but there
+ // doesn't seem to be a nice way to do that.
+ m_pendingText.discard();
m_document = 0;
m_attachmentRoot = 0;
}
@@ -246,7 +369,7 @@ void HTMLConstructionSite::dispatchDocumentElementAvailableIfNeeded()
{
ASSERT(m_document);
if (m_document->frame() && !m_isParsingFragment)
- m_document->frame()->loader()->dispatchDocumentElementAvailable();
+ m_document->frame()->loader().dispatchDocumentElementAvailable();
}
void HTMLConstructionSite::insertHTMLHtmlStartTagBeforeHTML(AtomicHTMLToken* token)
@@ -392,8 +515,18 @@ void HTMLConstructionSite::setCompatibilityModeFromDoctype(const String& name, c
setCompatibilityMode(Document::NoQuirksMode);
}
+void HTMLConstructionSite::processEndOfFile()
+{
+ ASSERT(currentNode());
+ flush();
+ openElements()->popAll();
+}
+
void HTMLConstructionSite::finishedParsing()
{
+ // We shouldn't have any queued tasks but we might have pending text which we need to promote to tasks and execute.
+ ASSERT(m_taskQueue.isEmpty());
+ flush();
m_document->finishedParsing();
}
@@ -457,7 +590,7 @@ void HTMLConstructionSite::insertHTMLBodyElement(AtomicHTMLToken* token)
attachLater(currentNode(), body);
m_openElements.pushHTMLBodyElement(HTMLStackItem::create(body.release(), token));
if (Frame* frame = m_document->frame())
- frame->loader()->client()->dispatchWillInsertBody();
+ frame->loader().client()->dispatchWillInsertBody();
}
void HTMLConstructionSite::insertHTMLFormElement(AtomicHTMLToken* token, bool isDemoted)
@@ -506,7 +639,7 @@ void HTMLConstructionSite::insertScriptElement(AtomicHTMLToken* token)
// those flags or effects thereof.
const bool parserInserted = m_parserContentPolicy != AllowScriptingContentAndDoNotMarkAlreadyStarted;
const bool alreadyStarted = m_isParsingFragment && parserInserted;
- RefPtr<HTMLScriptElement> element = HTMLScriptElement::create(scriptTag, ownerDocumentForCurrentNode(), parserInserted, alreadyStarted);
+ RefPtr<HTMLScriptElement> element = HTMLScriptElement::create(ownerDocumentForCurrentNode(), parserInserted, alreadyStarted);
setAttributes(element.get(), token, m_parserContentPolicy);
if (scriptingContentIsAllowed(m_parserContentPolicy))
attachLater(currentNode(), element);
@@ -525,49 +658,24 @@ void HTMLConstructionSite::insertForeignElement(AtomicHTMLToken* token, const At
m_openElements.push(HTMLStackItem::create(element.release(), token, namespaceURI));
}
-void HTMLConstructionSite::insertTextNode(const String& characters, WhitespaceMode whitespaceMode)
+void HTMLConstructionSite::insertTextNode(const String& string, WhitespaceMode whitespaceMode)
{
- HTMLConstructionSiteTask task(HTMLConstructionSiteTask::Insert);
- task.parent = currentNode();
+ HTMLConstructionSiteTask dummyTask(HTMLConstructionSiteTask::Insert);
+ dummyTask.parent = currentNode();
if (shouldFosterParent())
- findFosterSite(task);
-
- if (task.parent->hasTagName(templateTag))
- task.parent = toHTMLTemplateElement(task.parent.get())->content();
+ findFosterSite(dummyTask);
- // Strings composed entirely of whitespace are likely to be repeated.
- // Turn them into AtomicString so we share a single string for each.
- bool shouldUseAtomicString = whitespaceMode == AllWhitespace
- || (whitespaceMode == WhitespaceUnknown && isAllWhitespace(characters));
+ // FIXME: This probably doesn't need to be done both here and in insert(Task).
+ if (dummyTask.parent->hasTagName(templateTag))
+ dummyTask.parent = toHTMLTemplateElement(dummyTask.parent.get())->content();
- unsigned currentPosition = 0;
- unsigned lengthLimit = shouldUseLengthLimit(task.parent.get()) ? Text::defaultLengthLimit : std::numeric_limits<unsigned>::max();
-
- // FIXME: Splitting text nodes into smaller chunks contradicts HTML5 spec, but is currently necessary
- // for performance, see <https://bugs.webkit.org/show_bug.cgi?id=55898>.
-
- Node* previousChild = task.nextChild ? task.nextChild->previousSibling() : task.parent->lastChild();
- if (previousChild && previousChild->isTextNode()) {
- // FIXME: We're only supposed to append to this text node if it
- // was the last text node inserted by the parser.
- currentPosition = toCharacterData(previousChild)->parserAppendData(characters, 0, lengthLimit);
- }
-
- while (currentPosition < characters.length()) {
- RefPtr<Text> textNode = Text::createWithLengthLimit(task.parent->document(), shouldUseAtomicString ? AtomicString(characters).string() : characters, currentPosition, lengthLimit);
- // If we have a whole string of unbreakable characters the above could lead to an infinite loop. Exceeding the length limit is the lesser evil.
- if (!textNode->length()) {
- String substring = characters.substring(currentPosition);
- textNode = Text::create(task.parent->document(), shouldUseAtomicString ? AtomicString(substring).string() : substring);
- }
-
- currentPosition += textNode->length();
- ASSERT(currentPosition <= characters.length());
- task.child = textNode.release();
-
- executeTask(task);
- }
+ // Unclear when parent != case occurs. Somehow we insert text into two separate nodes while processing the same Token.
+ // The nextChild != dummy.nextChild case occurs whenever foster parenting happened and we hit a new text node "<table>a</table>b"
+ // In either case we have to flush the pending text into the task queue before making more.
+ if (!m_pendingText.isEmpty() && (m_pendingText.parent != dummyTask.parent || m_pendingText.nextChild != dummyTask.nextChild))
+ flushPendingText();
+ m_pendingText.append(dummyTask.parent, dummyTask.nextChild, string, whitespaceMode);
}
void HTMLConstructionSite::reparent(HTMLElementStack::ElementRecord* newParent, HTMLElementStack::ElementRecord* child)
@@ -575,7 +683,7 @@ void HTMLConstructionSite::reparent(HTMLElementStack::ElementRecord* newParent,
HTMLConstructionSiteTask task(HTMLConstructionSiteTask::Reparent);
task.parent = newParent->node();
task.child = child->node();
- m_taskQueue.append(task);
+ queueTask(task);
}
void HTMLConstructionSite::reparent(HTMLElementStack::ElementRecord* newParent, HTMLStackItem* child)
@@ -583,7 +691,7 @@ void HTMLConstructionSite::reparent(HTMLElementStack::ElementRecord* newParent,
HTMLConstructionSiteTask task(HTMLConstructionSiteTask::Reparent);
task.parent = newParent->node();
task.child = child->node();
- m_taskQueue.append(task);
+ queueTask(task);
}
void HTMLConstructionSite::insertAlreadyParsedChild(HTMLStackItem* newParent, HTMLElementStack::ElementRecord* child)
@@ -596,7 +704,7 @@ void HTMLConstructionSite::insertAlreadyParsedChild(HTMLStackItem* newParent, HT
HTMLConstructionSiteTask task(HTMLConstructionSiteTask::InsertAlreadyParsedChild);
task.parent = newParent->node();
task.child = child->node();
- m_taskQueue.append(task);
+ queueTask(task);
}
void HTMLConstructionSite::takeAllChildren(HTMLStackItem* newParent, HTMLElementStack::ElementRecord* oldParent)
@@ -604,7 +712,7 @@ void HTMLConstructionSite::takeAllChildren(HTMLStackItem* newParent, HTMLElement
HTMLConstructionSiteTask task(HTMLConstructionSiteTask::TakeAllChildren);
task.parent = newParent->node();
task.child = oldParent->node();
- m_taskQueue.append(task);
+ queueTask(task);
}
PassRefPtr<Element> HTMLConstructionSite::createElement(AtomicHTMLToken* token, const AtomicString& namespaceURI)
@@ -624,7 +732,6 @@ inline Document& HTMLConstructionSite::ownerDocumentForCurrentNode()
PassRefPtr<Element> HTMLConstructionSite::createHTMLElement(AtomicHTMLToken* token)
{
- QualifiedName tagName(nullAtom, token->name(), xhtmlNamespaceURI);
Document& document = ownerDocumentForCurrentNode();
// Only associate the element with the current form if we're creating the new element
// in a document with a browsing context (rather than in <template> contents).
@@ -632,7 +739,7 @@ PassRefPtr<Element> HTMLConstructionSite::createHTMLElement(AtomicHTMLToken* tok
// FIXME: This can't use HTMLConstructionSite::createElement because we
// have to pass the current form element. We should rework form association
// to occur after construction to allow better code sharing here.
- RefPtr<Element> element = HTMLElementFactory::createHTMLElement(tagName, &document, form, true);
+ RefPtr<Element> element = HTMLElementFactory::createHTMLElement(token->name(), document, form, true);
setAttributes(element.get(), token, m_parserContentPolicy);
ASSERT(element->isHTMLElement());
return element.release();
@@ -746,8 +853,7 @@ void HTMLConstructionSite::fosterParent(PassRefPtr<Node> node)
findFosterSite(task);
task.child = node;
ASSERT(task.parent);
-
- m_taskQueue.append(task);
+ queueTask(task);
}
}
diff --git a/chromium/third_party/WebKit/Source/core/html/parser/HTMLConstructionSite.h b/chromium/third_party/WebKit/Source/core/html/parser/HTMLConstructionSite.h
index ba03ce72d34..d4d812eb109 100644
--- a/chromium/third_party/WebKit/Source/core/html/parser/HTMLConstructionSite.h
+++ b/chromium/third_party/WebKit/Source/core/html/parser/HTMLConstructionSite.h
@@ -34,13 +34,15 @@
#include "wtf/PassRefPtr.h"
#include "wtf/RefPtr.h"
#include "wtf/Vector.h"
+#include "wtf/text/StringBuilder.h"
namespace WebCore {
struct HTMLConstructionSiteTask {
enum Operation {
Insert,
- InsertAlreadyParsedChild,
+ InsertText, // Handles possible merging of text nodes.
+ InsertAlreadyParsedChild, // Insert w/o calling begin/end parsing.
Reparent,
TakeAllChildren,
};
@@ -74,10 +76,12 @@ template<> struct VectorTraits<WebCore::HTMLConstructionSiteTask> : SimpleClassV
namespace WebCore {
+// Note: These are intentionally ordered so that when we concatonate
+// strings and whitespaces the resulting whitespace is ws = min(ws1, ws2).
enum WhitespaceMode {
- AllWhitespace,
+ WhitespaceUnknown,
NotAllWhitespace,
- WhitespaceUnknown
+ AllWhitespace,
};
class AtomicHTMLToken;
@@ -93,9 +97,31 @@ public:
~HTMLConstructionSite();
void detach();
+
+ // executeQueuedTasks empties the queue but does not flush pending text.
+ // NOTE: Possible reentrancy via JavaScript execution.
void executeQueuedTasks();
+ // flushPendingText turns pending text into queued Text insertions, but does not execute them.
+ void flushPendingText();
+
+ // Called before every token in HTMLTreeBuilder::processToken, thus inlined:
+ void flush()
+ {
+ if (!hasPendingTasks())
+ return;
+ flushPendingText();
+ executeQueuedTasks(); // NOTE: Possible reentrancy via JavaScript execution.
+ ASSERT(!hasPendingTasks());
+ }
+
+ bool hasPendingTasks()
+ {
+ return !m_pendingText.isEmpty() || !m_taskQueue.isEmpty();
+ }
+
void setDefaultCompatibilityMode();
+ void processEndOfFile();
void finishedParsing();
void insertDoctype(AtomicHTMLToken*);
@@ -195,6 +221,9 @@ private:
void mergeAttributesFromTokenIntoElement(AtomicHTMLToken*, Element*);
void dispatchDocumentElementAvailableIfNeeded();
+ void executeTask(HTMLConstructionSiteTask&);
+ void queueTask(const HTMLConstructionSiteTask&);
+
Document* m_document;
// This is the root ContainerNode to which the parser attaches all newly
@@ -209,6 +238,53 @@ private:
TaskQueue m_taskQueue;
+ struct PendingText {
+ PendingText()
+ : whitespaceMode(WhitespaceUnknown)
+ {
+ }
+
+ void append(PassRefPtr<ContainerNode> newParent, PassRefPtr<Node> newNextChild, const String& newString, WhitespaceMode newWhitespaceMode)
+ {
+ ASSERT(!parent || parent == newParent);
+ parent = newParent;
+ ASSERT(!nextChild || nextChild == newNextChild);
+ nextChild = newNextChild;
+ stringBuilder.append(newString);
+ whitespaceMode = std::min(whitespaceMode, newWhitespaceMode);
+ }
+
+ void swap(PendingText& other)
+ {
+ std::swap(whitespaceMode, other.whitespaceMode);
+ parent.swap(other.parent);
+ nextChild.swap(other.nextChild);
+ stringBuilder.swap(other.stringBuilder);
+ }
+
+ void discard()
+ {
+ PendingText discardedText;
+ swap(discardedText);
+ }
+
+ bool isEmpty()
+ {
+ // When the stringbuilder is empty, the parent and whitespace should also be "empty".
+ ASSERT(stringBuilder.isEmpty() == !parent);
+ ASSERT(!stringBuilder.isEmpty() || !nextChild);
+ ASSERT(!stringBuilder.isEmpty() || (whitespaceMode == WhitespaceUnknown));
+ return stringBuilder.isEmpty();
+ }
+
+ RefPtr<ContainerNode> parent;
+ RefPtr<Node> nextChild;
+ StringBuilder stringBuilder;
+ WhitespaceMode whitespaceMode;
+ };
+
+ PendingText m_pendingText;
+
ParserContentPolicy m_parserContentPolicy;
bool m_isParsingFragment;
diff --git a/chromium/third_party/WebKit/Source/core/html/parser/HTMLDocumentParser.cpp b/chromium/third_party/WebKit/Source/core/html/parser/HTMLDocumentParser.cpp
index e377ee67132..2008ae5f0e1 100644
--- a/chromium/third_party/WebKit/Source/core/html/parser/HTMLDocumentParser.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/parser/HTMLDocumentParser.cpp
@@ -32,17 +32,13 @@
#include "core/html/HTMLDocument.h"
#include "core/html/parser/AtomicHTMLToken.h"
#include "core/html/parser/BackgroundHTMLParser.h"
-#include "core/html/parser/CompactHTMLToken.h"
-#include "core/html/parser/HTMLIdentifier.h"
#include "core/html/parser/HTMLParserScheduler.h"
#include "core/html/parser/HTMLParserThread.h"
-#include "core/html/parser/HTMLPreloadScanner.h"
#include "core/html/parser/HTMLScriptRunner.h"
-#include "core/html/parser/HTMLTokenizer.h"
#include "core/html/parser/HTMLTreeBuilder.h"
#include "core/inspector/InspectorInstrumentation.h"
-#include "core/page/Frame.h"
-#include "core/platform/chromium/TraceEvent.h"
+#include "core/frame/Frame.h"
+#include "platform/TraceEvent.h"
#include "wtf/Functional.h"
namespace WebCore {
@@ -288,7 +284,7 @@ bool HTMLDocumentParser::canTakeNextToken(SynchronousMode mode, PumpSession& ses
// parser to stop parsing cleanly. The problem is we're not
// perpared to do that at every point where we run JavaScript.
if (!isParsingFragment()
- && document()->frame() && document()->frame()->navigationScheduler()->locationChangePending())
+ && document()->frame() && document()->frame()->navigationScheduler().locationChangePending())
return false;
if (mode == AllowYield)
@@ -299,6 +295,8 @@ bool HTMLDocumentParser::canTakeNextToken(SynchronousMode mode, PumpSession& ses
void HTMLDocumentParser::didReceiveParsedChunkFromBackgroundParser(PassOwnPtr<ParsedChunk> chunk)
{
+ TRACE_EVENT0("webkit", "HTMLDocumentParser::didReceiveParsedChunkFromBackgroundParser");
+
// alert(), runModalDialog, and the JavaScript Debugger all run nested event loops
// which can cause this method to be re-entered. We detect re-entry using
// hasActiveParser(), save the chunk as a speculation, and return.
@@ -378,6 +376,8 @@ void HTMLDocumentParser::discardSpeculationsAndResumeFrom(PassOwnPtr<ParsedChunk
void HTMLDocumentParser::processParsedChunkFromBackgroundParser(PassOwnPtr<ParsedChunk> popChunk)
{
+ TRACE_EVENT0("webkit", "HTMLDocumentParser::processParsedChunkFromBackgroundParser");
+
ASSERT_WITH_SECURITY_IMPLICATION(!document()->activeParserCount());
ASSERT(!isParsingFragment());
ASSERT(!isWaitingForScripts());
@@ -407,7 +407,7 @@ void HTMLDocumentParser::processParsedChunkFromBackgroundParser(PassOwnPtr<Parse
ASSERT(!isWaitingForScripts());
if (!isParsingFragment()
- && document()->frame() && document()->frame()->navigationScheduler()->locationChangePending()) {
+ && document()->frame() && document()->frame()->navigationScheduler().locationChangePending()) {
// To match main-thread parser behavior (which never checks locationChangePending on the EOF path)
// we peek to see if this chunk has an EOF and process it anyway.
@@ -553,6 +553,12 @@ void HTMLDocumentParser::pumpTokenizer(SynchronousMode mode)
if (isStopped())
return;
+ // There should only be PendingText left since the tree-builder always flushes
+ // the task queue before returning. In case that ever changes, crash.
+ if (mode == ForceSynchronous)
+ m_treeBuilder->flush();
+ RELEASE_ASSERT(!isStopped());
+
if (session.needsYield)
m_parserScheduler->scheduleForResume();
@@ -614,6 +620,8 @@ void HTMLDocumentParser::insert(const SegmentedString& source)
if (isStopped())
return;
+ TRACE_EVENT0("webkit", "HTMLDocumentParser::insert");
+
// pumpTokenizer can cause this parser to be detached from the Document,
// but we need to ensure it isn't deleted yet.
RefPtr<HTMLDocumentParser> protect(this);
@@ -649,8 +657,6 @@ void HTMLDocumentParser::startBackgroundParser()
ASSERT(!m_haveBackgroundParser);
m_haveBackgroundParser = true;
- HTMLIdentifier::init();
-
RefPtr<WeakReference<BackgroundHTMLParser> > reference = WeakReference<BackgroundHTMLParser>::createUnbound();
m_backgroundParser = WeakPtr<BackgroundHTMLParser>(reference);
diff --git a/chromium/third_party/WebKit/Source/core/html/parser/HTMLDocumentParser.h b/chromium/third_party/WebKit/Source/core/html/parser/HTMLDocumentParser.h
index 4b3be11a9a8..40779561ad3 100644
--- a/chromium/third_party/WebKit/Source/core/html/parser/HTMLDocumentParser.h
+++ b/chromium/third_party/WebKit/Source/core/html/parser/HTMLDocumentParser.h
@@ -29,6 +29,7 @@
#include "core/dom/ParserContentPolicy.h"
#include "core/dom/ScriptableDocumentParser.h"
#include "core/fetch/ResourceClient.h"
+#include "core/frame/UseCounter.h"
#include "core/html/parser/BackgroundHTMLInputStream.h"
#include "core/html/parser/CompactHTMLToken.h"
#include "core/html/parser/HTMLInputStream.h"
@@ -41,7 +42,7 @@
#include "core/html/parser/HTMLTreeBuilderSimulator.h"
#include "core/html/parser/XSSAuditor.h"
#include "core/html/parser/XSSAuditorDelegate.h"
-#include "core/platform/text/SegmentedString.h"
+#include "platform/text/SegmentedString.h"
#include "wtf/Deque.h"
#include "wtf/OwnPtr.h"
#include "wtf/WeakPtr.h"
@@ -96,6 +97,8 @@ public:
};
void didReceiveParsedChunkFromBackgroundParser(PassOwnPtr<ParsedChunk>);
+ UseCounter* useCounter() { return UseCounter::getFrom(contextForParsingSession()); }
+
protected:
virtual void insert(const SegmentedString&) OVERRIDE;
virtual void append(PassRefPtr<StringImpl>) OVERRIDE;
diff --git a/chromium/third_party/WebKit/Source/core/html/parser/HTMLElementStack.cpp b/chromium/third_party/WebKit/Source/core/html/parser/HTMLElementStack.cpp
index 1a8227c9fdc..9adfdf1612c 100644
--- a/chromium/third_party/WebKit/Source/core/html/parser/HTMLElementStack.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/parser/HTMLElementStack.cpp
@@ -34,7 +34,6 @@
#include "core/html/HTMLHtmlElement.h"
#include "core/html/HTMLOptGroupElement.h"
#include "core/html/HTMLTableElement.h"
-#include "wtf/PassOwnPtr.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/html/parser/HTMLEntityParser.h b/chromium/third_party/WebKit/Source/core/html/parser/HTMLEntityParser.h
index 12499c76c93..ed5d7e6652e 100644
--- a/chromium/third_party/WebKit/Source/core/html/parser/HTMLEntityParser.h
+++ b/chromium/third_party/WebKit/Source/core/html/parser/HTMLEntityParser.h
@@ -27,7 +27,7 @@
#ifndef HTMLEntityParser_h
#define HTMLEntityParser_h
-#include "core/platform/text/SegmentedString.h"
+#include "platform/text/SegmentedString.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/html/parser/HTMLIdentifier.cpp b/chromium/third_party/WebKit/Source/core/html/parser/HTMLIdentifier.cpp
deleted file mode 100644
index d12ea6a955c..00000000000
--- a/chromium/third_party/WebKit/Source/core/html/parser/HTMLIdentifier.cpp
+++ /dev/null
@@ -1,125 +0,0 @@
-/*
- * Copyright (C) 2013 Google, Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY GOOGLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GOOGLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/html/parser/HTMLIdentifier.h"
-
-#include "HTMLNames.h"
-#include "wtf/HashMap.h"
-#include "wtf/MainThread.h"
-#include "wtf/text/StringHash.h"
-
-namespace WebCore {
-
-using namespace HTMLNames;
-
-typedef HashMap<unsigned, StringImpl*, AlreadyHashed> IdentifierTable;
-
-unsigned HTMLIdentifier::maxNameLength = 0;
-
-static IdentifierTable& identifierTable()
-{
- DEFINE_STATIC_LOCAL(IdentifierTable, table, ());
- ASSERT(isMainThread() || !table.isEmpty());
- return table;
-}
-
-#ifndef NDEBUG
-bool HTMLIdentifier::isKnown(const StringImpl* string)
-{
- const IdentifierTable& table = identifierTable();
- return table.contains(string->hash());
-}
-#endif
-
-StringImpl* HTMLIdentifier::findIfKnown(const UChar* characters, unsigned length)
-{
- // We don't need to try hashing if we know the string is too long.
- if (length > maxNameLength)
- return 0;
- // computeHashAndMaskTop8Bits is the function StringImpl::hash() uses.
- unsigned hash = StringHasher::computeHashAndMaskTop8Bits(characters, length);
- const IdentifierTable& table = identifierTable();
- ASSERT(!table.isEmpty());
-
- IdentifierTable::const_iterator it = table.find(hash);
- if (it == table.end())
- return 0;
- // It's possible to have hash collisions between arbitrary strings and
- // known identifiers (e.g. "bvvfg" collides with "script").
- // However ASSERTs in addNames() guard against there ever being collisions
- // between known identifiers.
- if (!equal(it->value, characters, length))
- return 0;
- return it->value;
-}
-
-const unsigned kHTMLNamesIndexOffset = 0;
-const unsigned kHTMLAttrsIndexOffset = 1000;
-COMPILE_ASSERT(kHTMLAttrsIndexOffset > HTMLTagsCount, kHTMLAttrsIndexOffset_should_be_larger_than_HTMLTagsCount);
-
-const String& HTMLIdentifier::asString() const
-{
- ASSERT(isMainThread());
- return m_string;
-}
-
-const StringImpl* HTMLIdentifier::asStringImpl() const
-{
- return m_string.impl();
-}
-
-void HTMLIdentifier::addNames(QualifiedName** names, unsigned namesCount, unsigned indexOffset)
-{
- IdentifierTable& table = identifierTable();
- for (unsigned i = 0; i < namesCount; ++i) {
- StringImpl* name = names[i]->localName().impl();
- unsigned hash = name->hash();
- IdentifierTable::AddResult addResult = table.add(hash, name);
- maxNameLength = std::max(maxNameLength, name->length());
- // Ensure we're using the same hashing algorithm to get and set.
- ASSERT_UNUSED(addResult, !addResult.isNewEntry || HTMLIdentifier::findIfKnown(String(name).charactersWithNullTermination().data(), name->length()) == name);
- // We expect some hash collisions, but only for identical strings.
- // Since all of these names are AtomicStrings pointers should be equal.
- // Note: If you hit this ASSERT, then we had a hash collision among
- // HTMLNames strings, and we need to re-design how we use this hash!
- ASSERT_UNUSED(addResult, !addResult.isNewEntry || name == addResult.iterator->value);
- }
-}
-
-void HTMLIdentifier::init()
-{
- ASSERT(isMainThread()); // Not technically necessary, but this is our current expected usage.
- static bool isInitialized = false;
- if (isInitialized)
- return;
- isInitialized = true;
-
- // FIXME: We should atomize small whitespace (\n, \n\n, etc.)
- addNames(getHTMLTags(), HTMLTagsCount, kHTMLNamesIndexOffset);
- addNames(getHTMLAttrs(), HTMLAttrsCount, kHTMLAttrsIndexOffset);
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/html/parser/HTMLIdentifier.h b/chromium/third_party/WebKit/Source/core/html/parser/HTMLIdentifier.h
deleted file mode 100644
index 1aec5f7d7d7..00000000000
--- a/chromium/third_party/WebKit/Source/core/html/parser/HTMLIdentifier.h
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * Copyright (C) 2013 Google, Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY GOOGLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GOOGLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef HTMLIdentifier_h
-#define HTMLIdentifier_h
-
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class QualifiedName;
-
-enum CharacterWidth {
- Likely8Bit,
- Force8Bit,
- Force16Bit
-};
-
-class HTMLIdentifier {
-public:
- HTMLIdentifier() { }
-
- template<size_t inlineCapacity>
- HTMLIdentifier(const Vector<UChar, inlineCapacity>& vector, CharacterWidth width)
- : m_string(findIfKnown(vector.data(), vector.size()))
- {
- if (m_string.impl())
- return;
- if (width == Likely8Bit)
- m_string = StringImpl::create8BitIfPossible(vector);
- else if (width == Force8Bit)
- m_string = String::make8BitFrom16BitSource(vector);
- else
- m_string = String(vector);
- }
-
- // asString should only be used on the main thread.
- const String& asString() const;
- // asStringImpl() is safe to call from any thread.
- const StringImpl* asStringImpl() const;
-
- static void init();
-
- bool isSafeToSendToAnotherThread() const { return m_string.isSafeToSendToAnotherThread(); }
-
-#ifndef NDEBUG
- static bool isKnown(const StringImpl*);
-#endif
-
-private:
- static unsigned maxNameLength;
- static StringImpl* findIfKnown(const UChar* characters, unsigned length);
- static void addNames(QualifiedName** names, unsigned namesCount, unsigned indexOffset);
-
- String m_string;
-};
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/html/parser/HTMLInputStream.h b/chromium/third_party/WebKit/Source/core/html/parser/HTMLInputStream.h
index c7acd97d9ef..a121b131f12 100644
--- a/chromium/third_party/WebKit/Source/core/html/parser/HTMLInputStream.h
+++ b/chromium/third_party/WebKit/Source/core/html/parser/HTMLInputStream.h
@@ -27,7 +27,7 @@
#define HTMLInputStream_h
#include "core/html/parser/InputStreamPreprocessor.h"
-#include "core/platform/text/SegmentedString.h"
+#include "platform/text/SegmentedString.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/html/parser/HTMLMetaCharsetParser.cpp b/chromium/third_party/WebKit/Source/core/html/parser/HTMLMetaCharsetParser.cpp
index 7f3c34d8905..038c8a1e5fb 100644
--- a/chromium/third_party/WebKit/Source/core/html/parser/HTMLMetaCharsetParser.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/parser/HTMLMetaCharsetParser.cpp
@@ -30,7 +30,6 @@
#include "core/html/parser/HTMLParserIdioms.h"
#include "core/html/parser/HTMLParserOptions.h"
#include "core/html/parser/HTMLTokenizer.h"
-#include "wtf/text/TextCodec.h"
#include "wtf/text/TextEncodingRegistry.h"
#include "wtf/text/WTFString.h"
diff --git a/chromium/third_party/WebKit/Source/core/html/parser/HTMLMetaCharsetParser.h b/chromium/third_party/WebKit/Source/core/html/parser/HTMLMetaCharsetParser.h
index 5ee8862ccd9..3393fca40d2 100644
--- a/chromium/third_party/WebKit/Source/core/html/parser/HTMLMetaCharsetParser.h
+++ b/chromium/third_party/WebKit/Source/core/html/parser/HTMLMetaCharsetParser.h
@@ -27,7 +27,7 @@
#define HTMLMetaCharsetParser_h
#include "core/html/parser/HTMLToken.h"
-#include "core/platform/text/SegmentedString.h"
+#include "platform/text/SegmentedString.h"
#include "wtf/Noncopyable.h"
#include "wtf/text/TextCodec.h"
#include "wtf/text/TextEncoding.h"
diff --git a/chromium/third_party/WebKit/Source/core/html/parser/HTMLParserIdioms.cpp b/chromium/third_party/WebKit/Source/core/html/parser/HTMLParserIdioms.cpp
index 493627c1417..f538c54cc5b 100644
--- a/chromium/third_party/WebKit/Source/core/html/parser/HTMLParserIdioms.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/parser/HTMLParserIdioms.cpp
@@ -26,12 +26,10 @@
#include "core/html/parser/HTMLParserIdioms.h"
#include <limits>
-#include "core/dom/QualifiedName.h"
-#include "core/html/parser/HTMLIdentifier.h"
-#include "core/platform/Decimal.h"
#include "wtf/MathExtras.h"
#include "wtf/text/AtomicString.h"
#include "wtf/text/StringBuilder.h"
+#include "wtf/text/StringHash.h"
namespace WebCore {
@@ -115,11 +113,6 @@ Decimal parseToDecimalForNumberType(const String& string, const Decimal& fallbac
return value.isZero() ? Decimal(0) : value;
}
-Decimal parseToDecimalForNumberType(const String& string)
-{
- return parseToDecimalForNumberType(string, Decimal::nan());
-}
-
double parseToDoubleForNumberType(const String& string, double fallbackValue)
{
// See HTML5 2.5.4.3 `Real numbers.'
@@ -147,11 +140,6 @@ double parseToDoubleForNumberType(const String& string, double fallbackValue)
return value ? value : 0;
}
-double parseToDoubleForNumberType(const String& string)
-{
- return parseToDoubleForNumberType(string, std::numeric_limits<double>::quiet_NaN());
-}
-
template <typename CharacterType>
static bool parseHTMLIntegerInternal(const CharacterType* position, const CharacterType* end, int& value)
{
@@ -291,9 +279,31 @@ bool threadSafeMatch(const QualifiedName& a, const QualifiedName& b)
return threadSafeEqual(a.localName().impl(), b.localName().impl());
}
-bool threadSafeMatch(const HTMLIdentifier& localName, const QualifiedName& qName)
+bool threadSafeMatch(const String& localName, const QualifiedName& qName)
+{
+ return threadSafeEqual(localName.impl(), qName.localName().impl());
+}
+
+StringImpl* findStringIfStatic(const UChar* characters, unsigned length)
{
- return threadSafeEqual(localName.asStringImpl(), qName.localName().impl());
+ // We don't need to try hashing if we know the string is too long.
+ if (length > StringImpl::highestStaticStringLength())
+ return 0;
+ // computeHashAndMaskTop8Bits is the function StringImpl::hash() uses.
+ unsigned hash = StringHasher::computeHashAndMaskTop8Bits(characters, length);
+ const WTF::StaticStringsTable& table = StringImpl::allStaticStrings();
+ ASSERT(!table.isEmpty());
+
+ WTF::StaticStringsTable::const_iterator it = table.find(hash);
+ if (it == table.end())
+ return 0;
+ // It's possible to have hash collisions between arbitrary strings and
+ // known identifiers (e.g. "bvvfg" collides with "script").
+ // However ASSERTs in StringImpl::createStatic guard against there ever being collisions
+ // between static strings.
+ if (!equal(it->value, characters, length))
+ return 0;
+ return it->value;
}
}
diff --git a/chromium/third_party/WebKit/Source/core/html/parser/HTMLParserIdioms.h b/chromium/third_party/WebKit/Source/core/html/parser/HTMLParserIdioms.h
index 5c3e9df9e84..16fd3eebe3c 100644
--- a/chromium/third_party/WebKit/Source/core/html/parser/HTMLParserIdioms.h
+++ b/chromium/third_party/WebKit/Source/core/html/parser/HTMLParserIdioms.h
@@ -26,14 +26,12 @@
#define HTMLParserIdioms_h
#include "core/dom/QualifiedName.h"
-#include "core/html/parser/HTMLIdentifier.h"
+#include "platform/Decimal.h"
#include "wtf/Forward.h"
#include "wtf/text/WTFString.h"
namespace WebCore {
-class Decimal;
-
// Space characters as defined by the HTML specification.
bool isHTMLSpace(UChar);
bool isHTMLLineBreak(UChar);
@@ -54,10 +52,8 @@ String serializeForNumberType(double);
// Convert the specified string to a decimal/double. If the conversion fails, the return value is fallback value or NaN if not specified.
// Leading or trailing illegal characters cause failure, as does passing an empty string.
// The double* parameter may be 0 to check if the string can be parsed without getting the result.
-Decimal parseToDecimalForNumberType(const String&);
-Decimal parseToDecimalForNumberType(const String&, const Decimal& fallbackValue);
-double parseToDoubleForNumberType(const String&);
-double parseToDoubleForNumberType(const String&, double fallbackValue);
+Decimal parseToDecimalForNumberType(const String&, const Decimal& fallbackValue = Decimal::nan());
+double parseToDoubleForNumberType(const String&, double fallbackValue = std::numeric_limits<double>::quiet_NaN());
// http://www.whatwg.org/specs/web-apps/current-work/#rules-for-parsing-integers
bool parseHTMLInteger(const String&, int&);
@@ -101,15 +97,31 @@ inline bool isNotHTMLSpace(CharType character)
}
bool threadSafeMatch(const QualifiedName&, const QualifiedName&);
-bool threadSafeMatch(const HTMLIdentifier&, const QualifiedName&);
-inline bool threadSafeHTMLNamesMatch(const HTMLIdentifier& tagName, const QualifiedName& qName)
+bool threadSafeMatch(const String&, const QualifiedName&);
+
+StringImpl* findStringIfStatic(const UChar* characters, unsigned length);
+
+enum CharacterWidth {
+ Likely8Bit,
+ Force8Bit,
+ Force16Bit
+};
+
+template<size_t inlineCapacity>
+static String attemptStaticStringCreation(const Vector<UChar, inlineCapacity>& vector, CharacterWidth width)
{
- // When the QualifiedName is known to HTMLIdentifier,
- // all we have to do is a pointer compare.
- ASSERT(HTMLIdentifier::isKnown(qName.localName().impl()));
- return tagName.asStringImpl() == qName.localName().impl();
+ String string(findStringIfStatic(vector.data(), vector.size()));
+ if (string.impl())
+ return string;
+ if (width == Likely8Bit)
+ string = StringImpl::create8BitIfPossible(vector);
+ else if (width == Force8Bit)
+ string = String::make8BitFrom16BitSource(vector);
+ else
+ string = String(vector);
+
+ return string;
}
}
-
#endif
diff --git a/chromium/third_party/WebKit/Source/core/html/parser/HTMLParserOptions.cpp b/chromium/third_party/WebKit/Source/core/html/parser/HTMLParserOptions.cpp
index 3ed04906ffe..98ceb68461d 100644
--- a/chromium/third_party/WebKit/Source/core/html/parser/HTMLParserOptions.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/parser/HTMLParserOptions.cpp
@@ -29,16 +29,16 @@
#include "bindings/v8/ScriptController.h"
#include "core/dom/Document.h"
#include "core/loader/FrameLoader.h"
-#include "core/page/Frame.h"
-#include "core/page/Settings.h"
+#include "core/frame/Frame.h"
+#include "core/frame/Settings.h"
namespace WebCore {
HTMLParserOptions::HTMLParserOptions(Document* document)
{
Frame* frame = document ? document->frame() : 0;
- scriptEnabled = frame && frame->script()->canExecuteScripts(NotAboutToExecuteScript);
- pluginsEnabled = frame && frame->loader()->allowPlugins(NotAboutToInstantiatePlugin);
+ scriptEnabled = frame && frame->script().canExecuteScripts(NotAboutToExecuteScript);
+ pluginsEnabled = frame && frame->loader().allowPlugins(NotAboutToInstantiatePlugin);
Settings* settings = document ? document->settings() : 0;
// We force the main-thread parser for about:blank, javascript: and data: urls for compatibility
diff --git a/chromium/third_party/WebKit/Source/core/html/parser/HTMLParserScheduler.cpp b/chromium/third_party/WebKit/Source/core/html/parser/HTMLParserScheduler.cpp
index b5b38896df4..c74628479df 100644
--- a/chromium/third_party/WebKit/Source/core/html/parser/HTMLParserScheduler.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/parser/HTMLParserScheduler.cpp
@@ -28,7 +28,7 @@
#include "core/dom/Document.h"
#include "core/html/parser/HTMLDocumentParser.h"
-#include "core/page/FrameView.h"
+#include "core/frame/FrameView.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/html/parser/HTMLParserScheduler.h b/chromium/third_party/WebKit/Source/core/html/parser/HTMLParserScheduler.h
index 01624b7940f..e8bfe493085 100644
--- a/chromium/third_party/WebKit/Source/core/html/parser/HTMLParserScheduler.h
+++ b/chromium/third_party/WebKit/Source/core/html/parser/HTMLParserScheduler.h
@@ -27,7 +27,7 @@
#define HTMLParserScheduler_h
#include "core/html/parser/NestingLevelIncrementer.h"
-#include "core/platform/Timer.h"
+#include "platform/Timer.h"
#include "wtf/CurrentTime.h"
#include "wtf/PassOwnPtr.h"
#include "wtf/RefPtr.h"
diff --git a/chromium/third_party/WebKit/Source/core/html/parser/HTMLParserThread.cpp b/chromium/third_party/WebKit/Source/core/html/parser/HTMLParserThread.cpp
index 0ddc0587687..5a0e30c3e67 100644
--- a/chromium/third_party/WebKit/Source/core/html/parser/HTMLParserThread.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/parser/HTMLParserThread.cpp
@@ -31,14 +31,14 @@
#include "config.h"
#include "core/html/parser/HTMLParserThread.h"
-#include "core/platform/Task.h"
-#include "wtf/PassOwnPtr.h"
+#include "platform/Task.h"
#include "public/platform/Platform.h"
+#include "wtf/PassOwnPtr.h"
namespace WebCore {
HTMLParserThread::HTMLParserThread()
- : m_thread(adoptPtr(WebKit::Platform::current()->createThread("HTMLParserThread")))
+ : m_thread(adoptPtr(blink::Platform::current()->createThread("HTMLParserThread")))
{
}
diff --git a/chromium/third_party/WebKit/Source/core/html/parser/HTMLParserThread.h b/chromium/third_party/WebKit/Source/core/html/parser/HTMLParserThread.h
index 9e687de451a..e0b85f9399c 100644
--- a/chromium/third_party/WebKit/Source/core/html/parser/HTMLParserThread.h
+++ b/chromium/third_party/WebKit/Source/core/html/parser/HTMLParserThread.h
@@ -46,7 +46,7 @@ private:
HTMLParserThread();
~HTMLParserThread();
- OwnPtr<WebKit::WebThread> m_thread;
+ OwnPtr<blink::WebThread> m_thread;
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/html/parser/HTMLPreloadScanner.cpp b/chromium/third_party/WebKit/Source/core/html/parser/HTMLPreloadScanner.cpp
index e4a3abb3089..0d1e0645ad7 100644
--- a/chromium/third_party/WebKit/Source/core/html/parser/HTMLPreloadScanner.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/parser/HTMLPreloadScanner.cpp
@@ -29,13 +29,13 @@
#include "core/html/parser/HTMLPreloadScanner.h"
#include "HTMLNames.h"
+#include "InputTypeNames.h"
#include "RuntimeEnabledFeatures.h"
#include "core/html/LinkRelAttribute.h"
-#include "core/html/forms/InputTypeNames.h"
#include "core/html/parser/HTMLParserIdioms.h"
#include "core/html/parser/HTMLSrcsetParser.h"
#include "core/html/parser/HTMLTokenizer.h"
-#include "core/platform/chromium/TraceEvent.h"
+#include "platform/TraceEvent.h"
#include "wtf/MainThread.h"
namespace WebCore {
@@ -47,17 +47,17 @@ static bool match(const StringImpl* impl, const QualifiedName& qName)
return impl == qName.localName().impl();
}
-static bool match(const HTMLIdentifier& name, const QualifiedName& qName)
-{
- return match(name.asStringImpl(), qName);
-}
-
static bool match(const AtomicString& name, const QualifiedName& qName)
{
ASSERT(isMainThread());
return qName.localName() == name;
}
+static bool match(const String& name, const QualifiedName& qName)
+{
+ return threadSafeMatch(name, qName);
+}
+
static const StringImpl* tagImplFor(const HTMLToken::DataVector& data)
{
AtomicString tagName(data);
@@ -67,9 +67,9 @@ static const StringImpl* tagImplFor(const HTMLToken::DataVector& data)
return 0;
}
-static const StringImpl* tagImplFor(const HTMLIdentifier& tagName)
+static const StringImpl* tagImplFor(const String& tagName)
{
- const StringImpl* result = tagName.asStringImpl();
+ const StringImpl* result = tagName.impl();
if (result->isStatic())
return result;
return 0;
@@ -98,6 +98,8 @@ public:
, m_inputIsImage(false)
, m_deviceScaleFactor(deviceScaleFactor)
, m_encounteredImgSrc(false)
+ , m_isCORSEnabled(false)
+ , m_allowCredentials(DoNotAllowStoredCredentials)
{
if (!match(m_tagImpl, imgTag)
&& !match(m_tagImpl, inputTag)
@@ -139,7 +141,8 @@ public:
TRACE_EVENT_INSTANT1("net", "PreloadRequest", "url", m_urlToLoad.ascii());
TextPosition position = TextPosition(source.currentLine(), source.currentColumn());
OwnPtr<PreloadRequest> request = PreloadRequest::create(initiatorFor(m_tagImpl), position, m_urlToLoad, predictedBaseURL, resourceType(), m_mediaAttribute);
- request->setCrossOriginModeAllowsCookies(crossOriginModeAllowsCookies());
+ if (isCORSEnabled())
+ request->setCrossOriginEnabled(allowCredentials());
request->setCharset(charset());
return request.release();
}
@@ -154,14 +157,14 @@ private:
if (match(m_tagImpl, scriptTag)) {
if (match(attributeName, srcAttr))
setUrlToLoad(attributeValue, DisallowURLReplacement);
- else if (match(attributeName, crossoriginAttr) && !attributeValue.isNull())
- m_crossOriginMode = stripLeadingAndTrailingHTMLSpaces(attributeValue);
+ else if (match(attributeName, crossoriginAttr))
+ setCrossOriginAllowed(attributeValue);
} else if (match(m_tagImpl, imgTag)) {
if (match(attributeName, srcAttr) && !m_encounteredImgSrc) {
m_encounteredImgSrc = true;
setUrlToLoad(bestFitSourceForImageAttributes(m_deviceScaleFactor, attributeValue, m_srcsetImageCandidate), AllowURLReplacement);
- } else if (match(attributeName, crossoriginAttr) && !attributeValue.isNull()) {
- m_crossOriginMode = stripLeadingAndTrailingHTMLSpaces(attributeValue);
+ } else if (match(attributeName, crossoriginAttr)) {
+ setCrossOriginAllowed(attributeValue);
} else if (RuntimeEnabledFeatures::srcsetEnabled()
&& match(attributeName, srcsetAttr)
&& m_srcsetImageCandidate.isEmpty()) {
@@ -179,7 +182,7 @@ private:
if (match(attributeName, srcAttr))
setUrlToLoad(attributeValue, DisallowURLReplacement);
else if (match(attributeName, typeAttr))
- m_inputIsImage = equalIgnoringCase(attributeValue, InputTypeNames::image());
+ m_inputIsImage = equalIgnoringCase(attributeValue, InputTypeNames::image);
}
}
@@ -221,7 +224,7 @@ private:
return Resource::Raw;
}
- bool shouldPreload()
+ bool shouldPreload() const
{
if (m_urlToLoad.isEmpty())
return false;
@@ -232,21 +235,36 @@ private:
return true;
}
- bool crossOriginModeAllowsCookies()
+ bool isCORSEnabled() const
+ {
+ return m_isCORSEnabled;
+ }
+
+ StoredCredentials allowCredentials() const
+ {
+ return m_allowCredentials;
+ }
+
+ void setCrossOriginAllowed(const String& corsSetting)
{
- return m_crossOriginMode.isNull() || equalIgnoringCase(m_crossOriginMode, "use-credentials");
+ m_isCORSEnabled = true;
+ if (!corsSetting.isNull() && equalIgnoringCase(stripLeadingAndTrailingHTMLSpaces(corsSetting), "use-credentials"))
+ m_allowCredentials = AllowStoredCredentials;
+ else
+ m_allowCredentials = DoNotAllowStoredCredentials;
}
const StringImpl* m_tagImpl;
String m_urlToLoad;
ImageCandidate m_srcsetImageCandidate;
String m_charset;
- String m_crossOriginMode;
bool m_linkIsStyleSheet;
String m_mediaAttribute;
bool m_inputIsImage;
float m_deviceScaleFactor;
bool m_encounteredImgSrc;
+ bool m_isCORSEnabled;
+ StoredCredentials m_allowCredentials;
};
TokenPreloadScanner::TokenPreloadScanner(const KURL& documentURL, float deviceScaleFactor)
diff --git a/chromium/third_party/WebKit/Source/core/html/parser/HTMLPreloadScanner.h b/chromium/third_party/WebKit/Source/core/html/parser/HTMLPreloadScanner.h
index 50366d18f7f..956d30b3d28 100644
--- a/chromium/third_party/WebKit/Source/core/html/parser/HTMLPreloadScanner.h
+++ b/chromium/third_party/WebKit/Source/core/html/parser/HTMLPreloadScanner.h
@@ -30,7 +30,7 @@
#include "core/html/parser/CSSPreloadScanner.h"
#include "core/html/parser/CompactHTMLToken.h"
#include "core/html/parser/HTMLToken.h"
-#include "core/platform/text/SegmentedString.h"
+#include "platform/text/SegmentedString.h"
#include "wtf/Vector.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/html/parser/HTMLResourcePreloader.cpp b/chromium/third_party/WebKit/Source/core/html/parser/HTMLResourcePreloader.cpp
index 1d5317c4775..08e70a6a278 100644
--- a/chromium/third_party/WebKit/Source/core/html/parser/HTMLResourcePreloader.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/parser/HTMLResourcePreloader.cpp
@@ -32,8 +32,8 @@
#include "core/html/HTMLImport.h"
#include "core/css/MediaList.h"
#include "core/css/MediaQueryEvaluator.h"
-#include "core/platform/HistogramSupport.h"
#include "core/rendering/RenderObject.h"
+#include "public/platform/Platform.h"
namespace WebCore {
@@ -59,9 +59,8 @@ FetchRequest PreloadRequest::resourceRequest(Document* document)
initiatorInfo.position = m_initiatorPosition;
FetchRequest request(ResourceRequest(completeURL(document)), initiatorInfo);
- // FIXME: It's possible CORS should work for other request types?
- if (m_resourceType == Resource::Script)
- request.mutableResourceRequest().setAllowCookies(m_crossOriginModeAllowsCookies);
+ if (m_isCORSEnabled)
+ request.setCrossOriginAccessControl(document->securityOrigin(), m_allowCredentials);
return request;
}
@@ -93,7 +92,7 @@ void HTMLResourcePreloader::preload(PassOwnPtr<PreloadRequest> preload)
return;
FetchRequest request = preload->resourceRequest(m_document);
- HistogramSupport::histogramCustomCounts("WebCore.PreloadDelayMs", static_cast<int>(1000 * (monotonicallyIncreasingTime() - preload->discoveryTime())), 0, 2000, 20);
+ blink::Platform::current()->histogramCustomCounts("WebCore.PreloadDelayMs", static_cast<int>(1000 * (monotonicallyIncreasingTime() - preload->discoveryTime())), 0, 2000, 20);
loadingDocument->fetcher()->preload(preload->resourceType(), request, preload->charset());
}
diff --git a/chromium/third_party/WebKit/Source/core/html/parser/HTMLResourcePreloader.h b/chromium/third_party/WebKit/Source/core/html/parser/HTMLResourcePreloader.h
index 75c620d86a8..48686b6ca73 100644
--- a/chromium/third_party/WebKit/Source/core/html/parser/HTMLResourcePreloader.h
+++ b/chromium/third_party/WebKit/Source/core/html/parser/HTMLResourcePreloader.h
@@ -53,7 +53,12 @@ public:
const String& media() const { return m_mediaAttribute; }
double discoveryTime() const { return m_discoveryTime; }
void setCharset(const String& charset) { m_charset = charset.isolatedCopy(); }
- void setCrossOriginModeAllowsCookies(bool allowsCookies) { m_crossOriginModeAllowsCookies = allowsCookies; }
+ void setCrossOriginEnabled(StoredCredentials allowCredentials)
+ {
+ m_isCORSEnabled = true;
+ m_allowCredentials = allowCredentials;
+ }
+
Resource::Type resourceType() const { return m_resourceType; }
private:
@@ -64,7 +69,8 @@ private:
, m_baseURL(baseURL.copy())
, m_resourceType(resourceType)
, m_mediaAttribute(mediaAttribute.isolatedCopy())
- , m_crossOriginModeAllowsCookies(false)
+ , m_isCORSEnabled(false)
+ , m_allowCredentials(DoNotAllowStoredCredentials)
, m_discoveryTime(monotonicallyIncreasingTime())
{
}
@@ -78,7 +84,8 @@ private:
String m_charset;
Resource::Type m_resourceType;
String m_mediaAttribute;
- bool m_crossOriginModeAllowsCookies;
+ bool m_isCORSEnabled;
+ StoredCredentials m_allowCredentials;
double m_discoveryTime;
};
@@ -89,18 +96,14 @@ class HTMLResourcePreloader {
public:
explicit HTMLResourcePreloader(Document* document)
: m_document(document)
- , m_weakFactory(this)
{
}
void takeAndPreload(PreloadRequestStream&);
void preload(PassOwnPtr<PreloadRequest>);
- WeakPtr<HTMLResourcePreloader> createWeakPtr() { return m_weakFactory.createWeakPtr(); }
-
private:
Document* m_document;
- WeakPtrFactory<HTMLResourcePreloader> m_weakFactory;
};
}
diff --git a/chromium/third_party/WebKit/Source/core/html/parser/HTMLScriptRunner.cpp b/chromium/third_party/WebKit/Source/core/html/parser/HTMLScriptRunner.cpp
index f03d204314d..1cb6555c243 100644
--- a/chromium/third_party/WebKit/Source/core/html/parser/HTMLScriptRunner.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/parser/HTMLScriptRunner.cpp
@@ -28,7 +28,7 @@
#include "bindings/v8/ScriptSourceCode.h"
#include "core/dom/Element.h"
-#include "core/dom/Event.h"
+#include "core/events/Event.h"
#include "core/dom/IgnoreDestructiveWriteCountIncrementer.h"
#include "core/dom/Microtask.h"
#include "core/dom/ScriptLoader.h"
@@ -36,8 +36,8 @@
#include "core/html/parser/HTMLInputStream.h"
#include "core/html/parser/HTMLScriptRunnerHost.h"
#include "core/html/parser/NestingLevelIncrementer.h"
-#include "core/page/Frame.h"
-#include "core/platform/NotImplemented.h"
+#include "core/frame/Frame.h"
+#include "platform/NotImplemented.h"
namespace WebCore {
@@ -81,7 +81,7 @@ static KURL documentURLForScriptExecution(Document* document)
inline PassRefPtr<Event> createScriptLoadEvent()
{
- return Event::create(eventNames().loadEvent);
+ return Event::create(EventTypeNames::load);
}
ScriptSourceCode HTMLScriptRunner::sourceFromPendingScript(const PendingScript& script, bool& errorOccurred) const
@@ -137,8 +137,8 @@ void HTMLScriptRunner::executePendingScriptAndDispatchEvent(PendingScript& pendi
scriptLoader->dispatchErrorEvent();
else {
ASSERT(isExecutingScript());
- scriptLoader->executeScript(sourceCode);
- element->dispatchEvent(createScriptLoadEvent());
+ if (scriptLoader->executePotentiallyCrossOriginScript(sourceCode))
+ element->dispatchEvent(createScriptLoadEvent());
}
}
ASSERT(!isExecutingScript());
diff --git a/chromium/third_party/WebKit/Source/core/html/parser/HTMLSourceTracker.cpp b/chromium/third_party/WebKit/Source/core/html/parser/HTMLSourceTracker.cpp
index ef802ba4ee7..af729fa4dc8 100644
--- a/chromium/third_party/WebKit/Source/core/html/parser/HTMLSourceTracker.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/parser/HTMLSourceTracker.cpp
@@ -58,14 +58,17 @@ void HTMLSourceTracker::end(SegmentedString& currentInput, HTMLTokenizer* tokeni
String HTMLSourceTracker::sourceForToken(const HTMLToken& token)
{
- if (token.type() == HTMLToken::EndOfFile)
- return String(); // Hides the null character we use to mark the end of file.
-
if (!m_cachedSourceForToken.isEmpty())
return m_cachedSourceForToken;
- ASSERT(!token.startIndex());
- size_t length = static_cast<size_t>(token.endIndex() - token.startIndex());
+ size_t length;
+ if (token.type() == HTMLToken::EndOfFile) {
+ // Consume the remainder of the input, omitting the null character we use to mark the end of the file.
+ length = m_previousSource.length() + m_currentSource.length() - 1;
+ } else {
+ ASSERT(!token.startIndex());
+ length = static_cast<size_t>(token.endIndex() - token.startIndex());
+ }
StringBuilder source;
source.reserveCapacity(length);
diff --git a/chromium/third_party/WebKit/Source/core/html/parser/HTMLSourceTracker.h b/chromium/third_party/WebKit/Source/core/html/parser/HTMLSourceTracker.h
index 63fec2b1bb9..083e6a93bf4 100644
--- a/chromium/third_party/WebKit/Source/core/html/parser/HTMLSourceTracker.h
+++ b/chromium/third_party/WebKit/Source/core/html/parser/HTMLSourceTracker.h
@@ -27,7 +27,7 @@
#define HTMLSourceTracker_h
#include "core/html/parser/HTMLToken.h"
-#include "core/platform/text/SegmentedString.h"
+#include "platform/text/SegmentedString.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/html/parser/HTMLSrcsetParser.cpp b/chromium/third_party/WebKit/Source/core/html/parser/HTMLSrcsetParser.cpp
index 40c95a19643..7002dffab3b 100644
--- a/chromium/third_party/WebKit/Source/core/html/parser/HTMLSrcsetParser.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/parser/HTMLSrcsetParser.cpp
@@ -32,7 +32,7 @@
#include "core/html/parser/HTMLSrcsetParser.h"
#include "core/html/parser/HTMLParserIdioms.h"
-#include "core/platform/ParsingUtilities.h"
+#include "platform/ParsingUtilities.h"
namespace WebCore {
@@ -154,10 +154,13 @@ ImageCandidate bestFitSourceForSrcsetAttribute(float deviceScaleFactor, const St
return pickBestImageCandidate(deviceScaleFactor, imageCandidates);
}
-String bestFitSourceForImageAttributes(float deviceScaleFactor, const String& srcAttribute, const String& srcsetAttribute)
+ImageCandidate bestFitSourceForImageAttributes(float deviceScaleFactor, const String& srcAttribute, const String& srcsetAttribute)
{
- if (srcsetAttribute.isNull())
- return srcAttribute;
+ if (srcsetAttribute.isNull()) {
+ if (srcAttribute.isNull())
+ return ImageCandidate();
+ return ImageCandidate(srcAttribute, 0, srcAttribute.length(), 1);
+ }
Vector<ImageCandidate> imageCandidates;
@@ -166,7 +169,7 @@ String bestFitSourceForImageAttributes(float deviceScaleFactor, const String& sr
if (!srcAttribute.isEmpty())
imageCandidates.append(ImageCandidate(srcAttribute, 0, srcAttribute.length(), 1.0));
- return pickBestImageCandidate(deviceScaleFactor, imageCandidates).toString();
+ return pickBestImageCandidate(deviceScaleFactor, imageCandidates);
}
String bestFitSourceForImageAttributes(float deviceScaleFactor, const String& srcAttribute, ImageCandidate& srcsetImageCandidate)
diff --git a/chromium/third_party/WebKit/Source/core/html/parser/HTMLSrcsetParser.h b/chromium/third_party/WebKit/Source/core/html/parser/HTMLSrcsetParser.h
index bb53cb893c9..8964ffbcd5f 100644
--- a/chromium/third_party/WebKit/Source/core/html/parser/HTMLSrcsetParser.h
+++ b/chromium/third_party/WebKit/Source/core/html/parser/HTMLSrcsetParser.h
@@ -70,7 +70,7 @@ private:
ImageCandidate bestFitSourceForSrcsetAttribute(float deviceScaleFactor, const String& srcsetAttribute);
-String bestFitSourceForImageAttributes(float deviceScaleFactor, const String& srcAttribute, const String& srcsetAttribute);
+ImageCandidate bestFitSourceForImageAttributes(float deviceScaleFactor, const String& srcAttribute, const String& srcsetAttribute);
String bestFitSourceForImageAttributes(float deviceScaleFactor, const String& srcAttribute, ImageCandidate& srcsetImageCandidate);
diff --git a/chromium/third_party/WebKit/Source/core/html/parser/HTMLTokenizer.cpp b/chromium/third_party/WebKit/Source/core/html/parser/HTMLTokenizer.cpp
index c78cd592941..ed8c954a64b 100644
--- a/chromium/third_party/WebKit/Source/core/html/parser/HTMLTokenizer.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/parser/HTMLTokenizer.cpp
@@ -30,9 +30,8 @@
#include "HTMLNames.h"
#include "core/html/parser/HTMLEntityParser.h"
-#include "core/html/parser/HTMLToken.h"
#include "core/html/parser/HTMLTreeBuilder.h"
-#include "core/platform/NotImplemented.h"
+#include "platform/NotImplemented.h"
#include "core/xml/parser/MarkupTokenizerInlines.h"
#include "wtf/ASCIICType.h"
#include "wtf/text/AtomicString.h"
diff --git a/chromium/third_party/WebKit/Source/core/html/parser/HTMLTokenizer.h b/chromium/third_party/WebKit/Source/core/html/parser/HTMLTokenizer.h
index bbfa0f2f9b2..aa7c059bf78 100644
--- a/chromium/third_party/WebKit/Source/core/html/parser/HTMLTokenizer.h
+++ b/chromium/third_party/WebKit/Source/core/html/parser/HTMLTokenizer.h
@@ -30,7 +30,7 @@
#include "core/html/parser/HTMLParserOptions.h"
#include "core/html/parser/HTMLToken.h"
#include "core/html/parser/InputStreamPreprocessor.h"
-#include "core/platform/text/SegmentedString.h"
+#include "platform/text/SegmentedString.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/html/parser/HTMLTreeBuilder.cpp b/chromium/third_party/WebKit/Source/core/html/parser/HTMLTreeBuilder.cpp
index ac516a20d2e..4196cde09f0 100644
--- a/chromium/third_party/WebKit/Source/core/html/parser/HTMLTreeBuilder.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/parser/HTMLTreeBuilder.cpp
@@ -46,8 +46,8 @@
#include "core/html/parser/HTMLStackItem.h"
#include "core/html/parser/HTMLToken.h"
#include "core/html/parser/HTMLTokenizer.h"
-#include "core/platform/LocalizedStrings.h"
-#include "core/platform/NotImplemented.h"
+#include "platform/NotImplemented.h"
+#include "platform/text/PlatformLocale.h"
#include "wtf/MainThread.h"
#include "wtf/unicode/CharacterNames.h"
@@ -340,15 +340,14 @@ void HTMLTreeBuilder::detach()
HTMLTreeBuilder::FragmentParsingContext::FragmentParsingContext()
: m_fragment(0)
- , m_contextElement(0)
{
}
HTMLTreeBuilder::FragmentParsingContext::FragmentParsingContext(DocumentFragment* fragment, Element* contextElement)
: m_fragment(fragment)
- , m_contextElement(contextElement)
{
ASSERT(!fragment->hasChildNodes());
+ m_contextElementStackItem = HTMLStackItem::create(contextElement, HTMLStackItem::ItemForContextElement);
}
HTMLTreeBuilder::FragmentParsingContext::~FragmentParsingContext()
@@ -358,6 +357,7 @@ HTMLTreeBuilder::FragmentParsingContext::~FragmentParsingContext()
PassRefPtr<Element> HTMLTreeBuilder::takeScriptToProcess(TextPosition& scriptStartPosition)
{
ASSERT(m_scriptToProcess);
+ ASSERT(!m_tree.hasPendingTasks());
// Unpause ourselves, callers may pause us again when processing the script.
// The HTML5 spec is written as though scripts are executed inside the tree
// builder. We pause the parser to exit the tree builder, and then resume
@@ -375,10 +375,13 @@ void HTMLTreeBuilder::constructTree(AtomicHTMLToken* token)
processToken(token);
if (m_parser->tokenizer()) {
- bool inForeignContent = !m_tree.isEmpty()
- && !m_tree.currentStackItem()->isInHTMLNamespace()
- && !HTMLElementStack::isHTMLIntegrationPoint(m_tree.currentStackItem())
- && !HTMLElementStack::isMathMLTextIntegrationPoint(m_tree.currentStackItem());
+ bool inForeignContent = false;
+ if (!m_tree.isEmpty()) {
+ HTMLStackItem* adjustedCurrentNode = adjustedCurrentStackItem();
+ inForeignContent = !adjustedCurrentNode->isInHTMLNamespace()
+ && !HTMLElementStack::isHTMLIntegrationPoint(adjustedCurrentNode)
+ && !HTMLElementStack::isMathMLTextIntegrationPoint(adjustedCurrentNode);
+ }
m_parser->tokenizer()->setForceNullCharacterReplacement(m_insertionMode == TextMode || inForeignContent);
m_parser->tokenizer()->setShouldAllowCDATA(inForeignContent);
@@ -390,31 +393,34 @@ void HTMLTreeBuilder::constructTree(AtomicHTMLToken* token)
void HTMLTreeBuilder::processToken(AtomicHTMLToken* token)
{
+ if (token->type() == HTMLToken::Character) {
+ processCharacter(token);
+ return;
+ }
+
+ // Any non-character token needs to cause us to flush any pending text immediately.
+ // NOTE: flush() can cause any queued tasks to execute, possibly re-entering the parser.
+ m_tree.flush();
+ m_shouldSkipLeadingNewline = false;
+
switch (token->type()) {
case HTMLToken::Uninitialized:
+ case HTMLToken::Character:
ASSERT_NOT_REACHED();
break;
case HTMLToken::DOCTYPE:
- m_shouldSkipLeadingNewline = false;
processDoctypeToken(token);
break;
case HTMLToken::StartTag:
- m_shouldSkipLeadingNewline = false;
processStartTag(token);
break;
case HTMLToken::EndTag:
- m_shouldSkipLeadingNewline = false;
processEndTag(token);
break;
case HTMLToken::Comment:
- m_shouldSkipLeadingNewline = false;
processComment(token);
- return;
- case HTMLToken::Character:
- processCharacter(token);
break;
case HTMLToken::EndOfFile:
- m_shouldSkipLeadingNewline = false;
processEndOfFile(token);
break;
}
@@ -487,6 +493,10 @@ void HTMLTreeBuilder::processIsindexStartTagForInBody(AtomicHTMLToken* token)
{
ASSERT(token->type() == HTMLToken::StartTag);
ASSERT(token->name() == isindexTag);
+
+ if (m_parser->useCounter())
+ m_parser->useCounter()->count(UseCounter::IsIndexElement);
+
parseError(token);
if (m_tree.form())
return;
@@ -501,7 +511,7 @@ void HTMLTreeBuilder::processIsindexStartTagForInBody(AtomicHTMLToken* token)
if (promptAttribute)
processFakeCharacters(promptAttribute->value());
else
- processFakeCharacters(searchableIndexIntroduction());
+ processFakeCharacters(Locale::defaultLocale().queryString(blink::WebLocalizedString::SearchableIndexIntroduction));
processFakeStartTag(inputTag, attributesForIsindexInput(token));
notImplemented(); // This second set of characters may be needed by non-english locales.
processFakeEndTag(labelTag);
@@ -546,7 +556,7 @@ void HTMLTreeBuilder::processCloseWhenNestedTag(AtomicHTMLToken* token)
typedef HashMap<AtomicString, QualifiedName> PrefixedNameToQualifiedNameMap;
-static void mapLoweredLocalNameToName(PrefixedNameToQualifiedNameMap* map, QualifiedName** names, size_t length)
+static void mapLoweredLocalNameToName(PrefixedNameToQualifiedNameMap* map, const QualifiedName* const* names, size_t length)
{
for (size_t i = 0; i < length; ++i) {
const QualifiedName& name = *names[i];
@@ -562,7 +572,7 @@ static void adjustSVGTagNameCase(AtomicHTMLToken* token)
static PrefixedNameToQualifiedNameMap* caseMap = 0;
if (!caseMap) {
caseMap = new PrefixedNameToQualifiedNameMap;
- QualifiedName** svgTags = SVGNames::getSVGTags();
+ const QualifiedName* const* svgTags = SVGNames::getSVGTags();
mapLoweredLocalNameToName(caseMap, svgTags, SVGNames::SVGTagsCount);
}
@@ -572,13 +582,13 @@ static void adjustSVGTagNameCase(AtomicHTMLToken* token)
token->setName(casedName.localName());
}
-template<QualifiedName** getAttrs(), unsigned length>
+template<const QualifiedName* const* getAttrs(), unsigned length>
static void adjustAttributes(AtomicHTMLToken* token)
{
static PrefixedNameToQualifiedNameMap* caseMap = 0;
if (!caseMap) {
caseMap = new PrefixedNameToQualifiedNameMap;
- QualifiedName** attrs = getAttrs();
+ const QualifiedName* const* attrs = getAttrs();
mapLoweredLocalNameToName(caseMap, attrs, length);
}
@@ -600,10 +610,10 @@ static void adjustMathMLAttributes(AtomicHTMLToken* token)
adjustAttributes<MathMLNames::getMathMLAttrs, MathMLNames::MathMLAttrsCount>(token);
}
-static void addNamesWithPrefix(PrefixedNameToQualifiedNameMap* map, const AtomicString& prefix, QualifiedName** names, size_t length)
+static void addNamesWithPrefix(PrefixedNameToQualifiedNameMap* map, const AtomicString& prefix, const QualifiedName* const* names, size_t length)
{
for (size_t i = 0; i < length; ++i) {
- QualifiedName* name = names[i];
+ const QualifiedName* name = names[i];
const AtomicString& localName = name->localName();
AtomicString prefixColonLocalName = prefix + ':' + localName;
QualifiedName nameWithPrefix(prefix, localName, name->namespaceURI());
@@ -617,7 +627,7 @@ static void adjustForeignAttributes(AtomicHTMLToken* token)
if (!map) {
map = new PrefixedNameToQualifiedNameMap;
- QualifiedName** attrs = XLinkNames::getXLinkAttrs();
+ const QualifiedName* const* attrs = XLinkNames::getXLinkAttrs();
addNamesWithPrefix(map, xlinkAtom, attrs, XLinkNames::XLinkAttrsCount);
attrs = XMLNames::getXMLAttrs();
@@ -995,6 +1005,16 @@ bool HTMLTreeBuilder::processColgroupEndTagForInColumnGroup()
return true;
}
+// http://www.whatwg.org/specs/web-apps/current-work/#adjusted-current-node
+HTMLStackItem* HTMLTreeBuilder::adjustedCurrentStackItem() const
+{
+ ASSERT(!m_tree.isEmpty());
+ if (isParsingFragment() && m_tree.openElements()->hasOnlyOneElement())
+ return m_fragmentContext.contextElementStackItem();
+
+ return m_tree.currentStackItem();
+}
+
// http://www.whatwg.org/specs/web-apps/current-work/multipage/tokenization.html#close-the-cell
void HTMLTreeBuilder::closeTheCell()
{
@@ -1144,6 +1164,7 @@ void HTMLTreeBuilder::processStartTag(AtomicHTMLToken* token)
|| token->name() == noframesTag
|| token->name() == scriptTag
|| token->name() == styleTag
+ || token->name() == templateTag
|| token->name() == titleTag) {
parseError(token);
ASSERT(m_tree.head());
@@ -1604,13 +1625,21 @@ void HTMLTreeBuilder::resetInsertionModeAppropriately()
while (1) {
RefPtr<HTMLStackItem> item = nodeRecord->stackItem();
if (item->node() == m_tree.openElements()->rootNode()) {
- ASSERT(isParsingFragment());
last = true;
- item = HTMLStackItem::create(m_fragmentContext.contextElement(), HTMLStackItem::ItemForContextElement);
+ if (isParsingFragment())
+ item = m_fragmentContext.contextElementStackItem();
}
if (item->hasTagName(templateTag))
return setInsertionMode(m_templateInsertionModes.last());
if (item->hasTagName(selectTag)) {
+ if (!last) {
+ while (item->node() != m_tree.openElements()->rootNode() && !item->hasTagName(templateTag)) {
+ nodeRecord = nodeRecord->next();
+ item = nodeRecord->stackItem();
+ if (isHTMLTableElement(item->node()))
+ return setInsertionMode(InSelectInTableMode);
+ }
+ }
return setInsertionMode(InSelectMode);
}
if (item->hasTagName(tdTag) || item->hasTagName(thTag))
@@ -1637,6 +1666,9 @@ void HTMLTreeBuilder::resetInsertionModeAppropriately()
return setInsertionMode(InFramesetMode);
}
if (isHTMLHtmlElement(item->node())) {
+ if (m_tree.headStackItem())
+ return setInsertionMode(AfterHeadMode);
+
ASSERT(isParsingFragment());
return setInsertionMode(BeforeHeadMode);
}
@@ -2514,8 +2546,7 @@ void HTMLTreeBuilder::processEndOfFile(AtomicHTMLToken* token)
return;
break;
}
- ASSERT(m_tree.currentNode());
- m_tree.openElements()->popAll();
+ m_tree.processEndOfFile();
}
void HTMLTreeBuilder::defaultForInitial()
@@ -2664,10 +2695,11 @@ bool HTMLTreeBuilder::shouldProcessTokenInForeignContent(AtomicHTMLToken* token)
{
if (m_tree.isEmpty())
return false;
- HTMLStackItem* item = m_tree.currentStackItem();
- if (item->isInHTMLNamespace())
+ HTMLStackItem* adjustedCurrentNode = adjustedCurrentStackItem();
+
+ if (adjustedCurrentNode->isInHTMLNamespace())
return false;
- if (HTMLElementStack::isMathMLTextIntegrationPoint(item)) {
+ if (HTMLElementStack::isMathMLTextIntegrationPoint(adjustedCurrentNode)) {
if (token->type() == HTMLToken::StartTag
&& token->name() != MathMLNames::mglyphTag
&& token->name() != MathMLNames::malignmarkTag)
@@ -2675,11 +2707,11 @@ bool HTMLTreeBuilder::shouldProcessTokenInForeignContent(AtomicHTMLToken* token)
if (token->type() == HTMLToken::Character)
return false;
}
- if (item->hasTagName(MathMLNames::annotation_xmlTag)
+ if (adjustedCurrentNode->hasTagName(MathMLNames::annotation_xmlTag)
&& token->type() == HTMLToken::StartTag
&& token->name() == SVGNames::svgTag)
return false;
- if (HTMLElementStack::isHTMLIntegrationPoint(item)) {
+ if (HTMLElementStack::isHTMLIntegrationPoint(adjustedCurrentNode)) {
if (token->type() == HTMLToken::StartTag)
return false;
if (token->type() == HTMLToken::Character)
@@ -2692,6 +2724,17 @@ bool HTMLTreeBuilder::shouldProcessTokenInForeignContent(AtomicHTMLToken* token)
void HTMLTreeBuilder::processTokenInForeignContent(AtomicHTMLToken* token)
{
+ if (token->type() == HTMLToken::Character) {
+ const String& characters = token->characters();
+ m_tree.insertTextNode(characters);
+ if (m_framesetOk && !isAllWhitespaceOrReplacementCharacters(characters))
+ m_framesetOk = false;
+ return;
+ }
+
+ m_tree.flush();
+ HTMLStackItem* adjustedCurrentNode = adjustedCurrentStackItem();
+
switch (token->type()) {
case HTMLToken::Uninitialized:
ASSERT_NOT_REACHED();
@@ -2745,7 +2788,7 @@ void HTMLTreeBuilder::processTokenInForeignContent(AtomicHTMLToken* token)
processStartTag(token);
return;
}
- const AtomicString& currentNamespace = m_tree.currentStackItem()->namespaceURI();
+ const AtomicString& currentNamespace = adjustedCurrentNode->namespaceURI();
if (currentNamespace == MathMLNames::mathmlNamespaceURI)
adjustMathMLAttributes(token);
if (currentNamespace == SVGNames::svgNamespaceURI) {
@@ -2757,7 +2800,7 @@ void HTMLTreeBuilder::processTokenInForeignContent(AtomicHTMLToken* token)
break;
}
case HTMLToken::EndTag: {
- if (m_tree.currentStackItem()->namespaceURI() == SVGNames::svgNamespaceURI)
+ if (adjustedCurrentNode->namespaceURI() == SVGNames::svgNamespaceURI)
adjustSVGTagNameCase(token);
if (token->name() == SVGNames::scriptTag && m_tree.currentStackItem()->hasTagName(SVGNames::scriptTag)) {
@@ -2788,14 +2831,8 @@ void HTMLTreeBuilder::processTokenInForeignContent(AtomicHTMLToken* token)
}
case HTMLToken::Comment:
m_tree.insertComment(token);
- return;
- case HTMLToken::Character: {
- const String& characters = token->characters();
- m_tree.insertTextNode(characters);
- if (m_framesetOk && !isAllWhitespaceOrReplacementCharacters(characters))
- m_framesetOk = false;
break;
- }
+ case HTMLToken::Character:
case HTMLToken::EndOfFile:
ASSERT_NOT_REACHED();
break;
@@ -2817,4 +2854,4 @@ void HTMLTreeBuilder::parseError(AtomicHTMLToken*)
{
}
-}
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/html/parser/HTMLTreeBuilder.h b/chromium/third_party/WebKit/Source/core/html/parser/HTMLTreeBuilder.h
index c434d56220c..60ead95f286 100644
--- a/chromium/third_party/WebKit/Source/core/html/parser/HTMLTreeBuilder.h
+++ b/chromium/third_party/WebKit/Source/core/html/parser/HTMLTreeBuilder.h
@@ -80,6 +80,9 @@ public:
// Done, close any open tags, etc.
void finished();
+ // Synchronously empty any queues, possibly creating more DOM nodes.
+ void flush() { m_tree.flush(); }
+
void setShouldSkipLeadingNewline(bool shouldSkip) { m_shouldSkipLeadingNewline = shouldSkip; }
private:
@@ -166,6 +169,7 @@ private:
void defaultForAfterHead();
void defaultForInTableText();
+ inline HTMLStackItem* adjustedCurrentStackItem() const;
inline bool shouldProcessTokenInForeignContent(AtomicHTMLToken*);
void processTokenInForeignContent(AtomicHTMLToken*);
@@ -197,11 +201,12 @@ private:
~FragmentParsingContext();
DocumentFragment* fragment() const { return m_fragment; }
- Element* contextElement() const { ASSERT(m_fragment); return m_contextElement; }
+ Element* contextElement() const { ASSERT(m_fragment); return m_contextElementStackItem->element(); }
+ HTMLStackItem* contextElementStackItem() const { ASSERT(m_fragment); return m_contextElementStackItem.get(); }
private:
DocumentFragment* m_fragment;
- Element* m_contextElement;
+ RefPtr<HTMLStackItem> m_contextElementStackItem;
};
bool m_framesetOk;
diff --git a/chromium/third_party/WebKit/Source/core/html/parser/HTMLTreeBuilderSimulator.cpp b/chromium/third_party/WebKit/Source/core/html/parser/HTMLTreeBuilderSimulator.cpp
index 32ccaaf1ae9..37273cbaea0 100644
--- a/chromium/third_party/WebKit/Source/core/html/parser/HTMLTreeBuilderSimulator.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/parser/HTMLTreeBuilderSimulator.cpp
@@ -40,64 +40,64 @@ using namespace HTMLNames;
static bool tokenExitsForeignContent(const CompactHTMLToken& token)
{
// FIXME: This is copied from HTMLTreeBuilder::processTokenInForeignContent and changed to use threadSafeHTMLNamesMatch.
- const HTMLIdentifier& tagName = token.data();
- return threadSafeHTMLNamesMatch(tagName, bTag)
- || threadSafeHTMLNamesMatch(tagName, bigTag)
- || threadSafeHTMLNamesMatch(tagName, blockquoteTag)
- || threadSafeHTMLNamesMatch(tagName, bodyTag)
- || threadSafeHTMLNamesMatch(tagName, brTag)
- || threadSafeHTMLNamesMatch(tagName, centerTag)
- || threadSafeHTMLNamesMatch(tagName, codeTag)
- || threadSafeHTMLNamesMatch(tagName, ddTag)
- || threadSafeHTMLNamesMatch(tagName, divTag)
- || threadSafeHTMLNamesMatch(tagName, dlTag)
- || threadSafeHTMLNamesMatch(tagName, dtTag)
- || threadSafeHTMLNamesMatch(tagName, emTag)
- || threadSafeHTMLNamesMatch(tagName, embedTag)
- || threadSafeHTMLNamesMatch(tagName, h1Tag)
- || threadSafeHTMLNamesMatch(tagName, h2Tag)
- || threadSafeHTMLNamesMatch(tagName, h3Tag)
- || threadSafeHTMLNamesMatch(tagName, h4Tag)
- || threadSafeHTMLNamesMatch(tagName, h5Tag)
- || threadSafeHTMLNamesMatch(tagName, h6Tag)
- || threadSafeHTMLNamesMatch(tagName, headTag)
- || threadSafeHTMLNamesMatch(tagName, hrTag)
- || threadSafeHTMLNamesMatch(tagName, iTag)
- || threadSafeHTMLNamesMatch(tagName, imgTag)
- || threadSafeHTMLNamesMatch(tagName, liTag)
- || threadSafeHTMLNamesMatch(tagName, listingTag)
- || threadSafeHTMLNamesMatch(tagName, menuTag)
- || threadSafeHTMLNamesMatch(tagName, metaTag)
- || threadSafeHTMLNamesMatch(tagName, nobrTag)
- || threadSafeHTMLNamesMatch(tagName, olTag)
- || threadSafeHTMLNamesMatch(tagName, pTag)
- || threadSafeHTMLNamesMatch(tagName, preTag)
- || threadSafeHTMLNamesMatch(tagName, rubyTag)
- || threadSafeHTMLNamesMatch(tagName, sTag)
- || threadSafeHTMLNamesMatch(tagName, smallTag)
- || threadSafeHTMLNamesMatch(tagName, spanTag)
- || threadSafeHTMLNamesMatch(tagName, strongTag)
- || threadSafeHTMLNamesMatch(tagName, strikeTag)
- || threadSafeHTMLNamesMatch(tagName, subTag)
- || threadSafeHTMLNamesMatch(tagName, supTag)
- || threadSafeHTMLNamesMatch(tagName, tableTag)
- || threadSafeHTMLNamesMatch(tagName, ttTag)
- || threadSafeHTMLNamesMatch(tagName, uTag)
- || threadSafeHTMLNamesMatch(tagName, ulTag)
- || threadSafeHTMLNamesMatch(tagName, varTag)
- || (threadSafeHTMLNamesMatch(tagName, fontTag) && (token.getAttributeItem(colorAttr) || token.getAttributeItem(faceAttr) || token.getAttributeItem(sizeAttr)));
+ const String& tagName = token.data();
+ return threadSafeMatch(tagName, bTag)
+ || threadSafeMatch(tagName, bigTag)
+ || threadSafeMatch(tagName, blockquoteTag)
+ || threadSafeMatch(tagName, bodyTag)
+ || threadSafeMatch(tagName, brTag)
+ || threadSafeMatch(tagName, centerTag)
+ || threadSafeMatch(tagName, codeTag)
+ || threadSafeMatch(tagName, ddTag)
+ || threadSafeMatch(tagName, divTag)
+ || threadSafeMatch(tagName, dlTag)
+ || threadSafeMatch(tagName, dtTag)
+ || threadSafeMatch(tagName, emTag)
+ || threadSafeMatch(tagName, embedTag)
+ || threadSafeMatch(tagName, h1Tag)
+ || threadSafeMatch(tagName, h2Tag)
+ || threadSafeMatch(tagName, h3Tag)
+ || threadSafeMatch(tagName, h4Tag)
+ || threadSafeMatch(tagName, h5Tag)
+ || threadSafeMatch(tagName, h6Tag)
+ || threadSafeMatch(tagName, headTag)
+ || threadSafeMatch(tagName, hrTag)
+ || threadSafeMatch(tagName, iTag)
+ || threadSafeMatch(tagName, imgTag)
+ || threadSafeMatch(tagName, liTag)
+ || threadSafeMatch(tagName, listingTag)
+ || threadSafeMatch(tagName, menuTag)
+ || threadSafeMatch(tagName, metaTag)
+ || threadSafeMatch(tagName, nobrTag)
+ || threadSafeMatch(tagName, olTag)
+ || threadSafeMatch(tagName, pTag)
+ || threadSafeMatch(tagName, preTag)
+ || threadSafeMatch(tagName, rubyTag)
+ || threadSafeMatch(tagName, sTag)
+ || threadSafeMatch(tagName, smallTag)
+ || threadSafeMatch(tagName, spanTag)
+ || threadSafeMatch(tagName, strongTag)
+ || threadSafeMatch(tagName, strikeTag)
+ || threadSafeMatch(tagName, subTag)
+ || threadSafeMatch(tagName, supTag)
+ || threadSafeMatch(tagName, tableTag)
+ || threadSafeMatch(tagName, ttTag)
+ || threadSafeMatch(tagName, uTag)
+ || threadSafeMatch(tagName, ulTag)
+ || threadSafeMatch(tagName, varTag)
+ || (threadSafeMatch(tagName, fontTag) && (token.getAttributeItem(colorAttr) || token.getAttributeItem(faceAttr) || token.getAttributeItem(sizeAttr)));
}
static bool tokenExitsSVG(const CompactHTMLToken& token)
{
// FIXME: It's very fragile that we special case foreignObject here to be case-insensitive.
- return equalIgnoringCaseNonNull(token.data().asStringImpl(), SVGNames::foreignObjectTag.localName().impl());
+ return equalIgnoringCaseNonNull(token.data().impl(), SVGNames::foreignObjectTag.localName().impl());
}
static bool tokenExitsMath(const CompactHTMLToken& token)
{
// FIXME: This is copied from HTMLElementStack::isMathMLTextIntegrationPoint and changed to use threadSafeMatch.
- const HTMLIdentifier& tagName = token.data();
+ const String& tagName = token.data();
return threadSafeMatch(tagName, MathMLNames::miTag)
|| threadSafeMatch(tagName, MathMLNames::moTag)
|| threadSafeMatch(tagName, MathMLNames::mnTag)
@@ -132,7 +132,7 @@ HTMLTreeBuilderSimulator::State HTMLTreeBuilderSimulator::stateFor(HTMLTreeBuild
bool HTMLTreeBuilderSimulator::simulate(const CompactHTMLToken& token, HTMLTokenizer* tokenizer)
{
if (token.type() == HTMLToken::StartTag) {
- const HTMLIdentifier& tagName = token.data();
+ const String& tagName = token.data();
if (threadSafeMatch(tagName, SVGNames::svgTag))
m_namespaceStack.append(SVG);
if (threadSafeMatch(tagName, MathMLNames::mathTag))
@@ -144,30 +144,30 @@ bool HTMLTreeBuilderSimulator::simulate(const CompactHTMLToken& token, HTMLToken
m_namespaceStack.append(HTML);
if (!inForeignContent()) {
// FIXME: This is just a copy of Tokenizer::updateStateFor which uses threadSafeMatches.
- if (threadSafeHTMLNamesMatch(tagName, textareaTag) || threadSafeHTMLNamesMatch(tagName, titleTag))
+ if (threadSafeMatch(tagName, textareaTag) || threadSafeMatch(tagName, titleTag))
tokenizer->setState(HTMLTokenizer::RCDATAState);
- else if (threadSafeHTMLNamesMatch(tagName, plaintextTag))
+ else if (threadSafeMatch(tagName, plaintextTag))
tokenizer->setState(HTMLTokenizer::PLAINTEXTState);
- else if (threadSafeHTMLNamesMatch(tagName, scriptTag))
+ else if (threadSafeMatch(tagName, scriptTag))
tokenizer->setState(HTMLTokenizer::ScriptDataState);
- else if (threadSafeHTMLNamesMatch(tagName, styleTag)
- || threadSafeHTMLNamesMatch(tagName, iframeTag)
- || threadSafeHTMLNamesMatch(tagName, xmpTag)
- || (threadSafeHTMLNamesMatch(tagName, noembedTag) && m_options.pluginsEnabled)
- || threadSafeHTMLNamesMatch(tagName, noframesTag)
- || (threadSafeHTMLNamesMatch(tagName, noscriptTag) && m_options.scriptEnabled))
+ else if (threadSafeMatch(tagName, styleTag)
+ || threadSafeMatch(tagName, iframeTag)
+ || threadSafeMatch(tagName, xmpTag)
+ || (threadSafeMatch(tagName, noembedTag) && m_options.pluginsEnabled)
+ || threadSafeMatch(tagName, noframesTag)
+ || (threadSafeMatch(tagName, noscriptTag) && m_options.scriptEnabled))
tokenizer->setState(HTMLTokenizer::RAWTEXTState);
}
}
if (token.type() == HTMLToken::EndTag) {
- const HTMLIdentifier& tagName = token.data();
+ const String& tagName = token.data();
if ((m_namespaceStack.last() == SVG && threadSafeMatch(tagName, SVGNames::svgTag))
|| (m_namespaceStack.last() == MathML && threadSafeMatch(tagName, MathMLNames::mathTag))
|| (m_namespaceStack.contains(SVG) && m_namespaceStack.last() == HTML && tokenExitsSVG(token))
|| (m_namespaceStack.contains(MathML) && m_namespaceStack.last() == HTML && tokenExitsMath(token)))
m_namespaceStack.removeLast();
- if (threadSafeHTMLNamesMatch(tagName, scriptTag)) {
+ if (threadSafeMatch(tagName, scriptTag)) {
if (!inForeignContent())
tokenizer->setState(HTMLTokenizer::DataState);
return false;
diff --git a/chromium/third_party/WebKit/Source/core/html/parser/HTMLViewSourceParser.cpp b/chromium/third_party/WebKit/Source/core/html/parser/HTMLViewSourceParser.cpp
index de01ee274d1..b46ff5ad2e9 100644
--- a/chromium/third_party/WebKit/Source/core/html/parser/HTMLViewSourceParser.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/parser/HTMLViewSourceParser.cpp
@@ -27,7 +27,6 @@
#include "core/html/parser/HTMLViewSourceParser.h"
#include "core/dom/DOMImplementation.h"
-#include "core/html/HTMLViewSourceDocument.h"
#include "core/html/parser/HTMLParserOptions.h"
#include "core/html/parser/HTMLToken.h"
diff --git a/chromium/third_party/WebKit/Source/core/html/parser/InputStreamPreprocessor.h b/chromium/third_party/WebKit/Source/core/html/parser/InputStreamPreprocessor.h
index 842e948138b..a411d52d6a1 100644
--- a/chromium/third_party/WebKit/Source/core/html/parser/InputStreamPreprocessor.h
+++ b/chromium/third_party/WebKit/Source/core/html/parser/InputStreamPreprocessor.h
@@ -28,7 +28,7 @@
#ifndef InputStreamPreprocessor_h
#define InputStreamPreprocessor_h
-#include "core/platform/text/SegmentedString.h"
+#include "platform/text/SegmentedString.h"
#include "wtf/Noncopyable.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/mathml/mathattrs.in b/chromium/third_party/WebKit/Source/core/html/parser/MathMLAttributeNames.in
index 45a6e3af507..45a6e3af507 100644
--- a/chromium/third_party/WebKit/Source/core/mathml/mathattrs.in
+++ b/chromium/third_party/WebKit/Source/core/html/parser/MathMLAttributeNames.in
diff --git a/chromium/third_party/WebKit/Source/core/html/parser/MathMLTagNames.in b/chromium/third_party/WebKit/Source/core/html/parser/MathMLTagNames.in
new file mode 100644
index 00000000000..80d830f4750
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/html/parser/MathMLTagNames.in
@@ -0,0 +1,12 @@
+namespace="MathML"
+namespaceURI="http://www.w3.org/1998/Math/MathML"
+
+math
+mi
+mn
+mo
+mtext
+ms
+mglyph
+malignmark
+annotation-xml
diff --git a/chromium/third_party/WebKit/Source/core/html/parser/XSSAuditor.cpp b/chromium/third_party/WebKit/Source/core/html/parser/XSSAuditor.cpp
index bd70813edde..a43fca982b5 100644
--- a/chromium/third_party/WebKit/Source/core/html/parser/XSSAuditor.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/parser/XSSAuditor.cpp
@@ -32,20 +32,25 @@
#include "XLinkNames.h"
#include "core/dom/Document.h"
#include "core/fetch/TextResourceDecoder.h"
+#include "core/frame/ContentSecurityPolicy.h"
+#include "core/frame/Frame.h"
#include "core/html/HTMLParamElement.h"
#include "core/html/parser/HTMLDocumentParser.h"
#include "core/html/parser/HTMLParserIdioms.h"
#include "core/html/parser/XSSAuditorDelegate.h"
#include "core/loader/DocumentLoader.h"
-#include "core/page/ContentSecurityPolicy.h"
-#include "core/page/Frame.h"
-#include "core/page/Settings.h"
-#include "core/platform/JSONValues.h"
-#include "core/platform/network/FormData.h"
-#include "core/platform/text/DecodeEscapeSequences.h"
-#include "weborigin/KURL.h"
+#include "core/frame/Settings.h"
+#include "platform/JSONValues.h"
+#include "platform/network/FormData.h"
+#include "platform/text/DecodeEscapeSequences.h"
#include "wtf/MainThread.h"
-#include "wtf/text/TextEncoding.h"
+
+namespace {
+
+// SecurityOrigin::urlWithUniqueSecurityOrigin() can't be used cross-thread, or we'd use it instead.
+const char kURLWithUniqueOrigin[] = "data:,";
+
+} // namespace
namespace WebCore {
@@ -170,12 +175,12 @@ static String fullyDecodeString(const String& string, const WTF::TextEncoding& e
return workingString;
}
-static ContentSecurityPolicy::ReflectedXSSDisposition combineXSSProtectionHeaderAndCSP(ContentSecurityPolicy::ReflectedXSSDisposition xssProtection, ContentSecurityPolicy::ReflectedXSSDisposition reflectedXSS)
+static ReflectedXSSDisposition combineXSSProtectionHeaderAndCSP(ReflectedXSSDisposition xssProtection, ReflectedXSSDisposition reflectedXSS)
{
- ContentSecurityPolicy::ReflectedXSSDisposition result = std::max(xssProtection, reflectedXSS);
+ ReflectedXSSDisposition result = std::max(xssProtection, reflectedXSS);
- if (result == ContentSecurityPolicy::ReflectedXSSInvalid || result == ContentSecurityPolicy::FilterReflectedXSS || result == ContentSecurityPolicy::ReflectedXSSUnset)
- return ContentSecurityPolicy::FilterReflectedXSS;
+ if (result == ReflectedXSSInvalid || result == FilterReflectedXSS || result == ReflectedXSSUnset)
+ return FilterReflectedXSS;
return result;
}
@@ -198,7 +203,7 @@ static bool semicolonSeparatedValueContainsJavaScriptURL(const String& value)
XSSAuditor::XSSAuditor()
: m_isEnabled(false)
- , m_xssProtection(ContentSecurityPolicy::FilterReflectedXSS)
+ , m_xssProtection(FilterReflectedXSS)
, m_didSendValidCSPHeader(false)
, m_didSendValidXSSProtectionHeader(false)
, m_state(Uninitialized)
@@ -214,7 +219,7 @@ void XSSAuditor::initForFragment()
{
ASSERT(isMainThread());
ASSERT(m_state == Uninitialized);
- m_state = Initialized;
+ m_state = FilteringTokens;
// When parsing a fragment, we don't enable the XSS auditor because it's
// too much overhead.
ASSERT(!m_isEnabled);
@@ -226,10 +231,9 @@ void XSSAuditor::init(Document* document, XSSAuditorDelegate* auditorDelegate)
const int suffixTreeDepth = 5;
ASSERT(isMainThread());
- if (m_state == Initialized)
+ if (m_state != Uninitialized)
return;
- ASSERT(m_state == Uninitialized);
- m_state = Initialized;
+ m_state = FilteringTokens;
if (Settings* settings = document->settings())
m_isEnabled = settings->xssAuditorEnabled();
@@ -265,36 +269,36 @@ void XSSAuditor::init(Document* document, XSSAuditorDelegate* auditorDelegate)
m_decodedURL = String();
String httpBodyAsString;
- if (DocumentLoader* documentLoader = document->frame()->loader()->documentLoader()) {
- DEFINE_STATIC_LOCAL(String, XSSProtectionHeader, ("X-XSS-Protection"));
- String headerValue = documentLoader->response().httpHeaderField(XSSProtectionHeader);
+ if (DocumentLoader* documentLoader = document->frame()->loader().documentLoader()) {
+ DEFINE_STATIC_LOCAL(const AtomicString, XSSProtectionHeader, ("X-XSS-Protection", AtomicString::ConstructFromLiteral));
+ const AtomicString& headerValue = documentLoader->response().httpHeaderField(XSSProtectionHeader);
String errorDetails;
unsigned errorPosition = 0;
String reportURL;
KURL xssProtectionReportURL;
// Process the X-XSS-Protection header, then mix in the CSP header's value.
- ContentSecurityPolicy::ReflectedXSSDisposition xssProtectionHeader = parseXSSProtectionHeader(headerValue, errorDetails, errorPosition, reportURL);
- m_didSendValidXSSProtectionHeader = xssProtectionHeader != ContentSecurityPolicy::ReflectedXSSUnset && xssProtectionHeader != ContentSecurityPolicy::ReflectedXSSInvalid;
- if ((xssProtectionHeader == ContentSecurityPolicy::FilterReflectedXSS || xssProtectionHeader == ContentSecurityPolicy::BlockReflectedXSS) && !reportURL.isEmpty()) {
+ ReflectedXSSDisposition xssProtectionHeader = parseXSSProtectionHeader(headerValue, errorDetails, errorPosition, reportURL);
+ m_didSendValidXSSProtectionHeader = xssProtectionHeader != ReflectedXSSUnset && xssProtectionHeader != ReflectedXSSInvalid;
+ if ((xssProtectionHeader == FilterReflectedXSS || xssProtectionHeader == BlockReflectedXSS) && !reportURL.isEmpty()) {
xssProtectionReportURL = document->completeURL(reportURL);
if (MixedContentChecker::isMixedContent(document->securityOrigin(), xssProtectionReportURL)) {
errorDetails = "insecure reporting URL for secure page";
- xssProtectionHeader = ContentSecurityPolicy::ReflectedXSSInvalid;
+ xssProtectionHeader = ReflectedXSSInvalid;
xssProtectionReportURL = KURL();
}
}
- if (xssProtectionHeader == ContentSecurityPolicy::ReflectedXSSInvalid)
+ if (xssProtectionHeader == ReflectedXSSInvalid)
document->addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, "Error parsing header X-XSS-Protection: " + headerValue + ": " + errorDetails + " at character position " + String::format("%u", errorPosition) + ". The default protections will be applied.");
- ContentSecurityPolicy::ReflectedXSSDisposition cspHeader = document->contentSecurityPolicy()->reflectedXSSDisposition();
- m_didSendValidCSPHeader = cspHeader != ContentSecurityPolicy::ReflectedXSSUnset && cspHeader != ContentSecurityPolicy::ReflectedXSSInvalid;
+ ReflectedXSSDisposition cspHeader = document->contentSecurityPolicy()->reflectedXSSDisposition();
+ m_didSendValidCSPHeader = cspHeader != ReflectedXSSUnset && cspHeader != ReflectedXSSInvalid;
m_xssProtection = combineXSSProtectionHeaderAndCSP(xssProtectionHeader, cspHeader);
// FIXME: Combine the two report URLs in some reasonable way.
if (auditorDelegate)
auditorDelegate->setReportURL(xssProtectionReportURL.copy());
- FormData* httpBody = documentLoader->originalRequest().httpBody();
+ FormData* httpBody = documentLoader->request().httpBody();
if (httpBody && !httpBody->isEmpty()) {
httpBodyAsString = httpBody->flattenToString();
if (!httpBodyAsString.isEmpty()) {
@@ -315,8 +319,8 @@ void XSSAuditor::init(Document* document, XSSAuditorDelegate* auditorDelegate)
PassOwnPtr<XSSInfo> XSSAuditor::filterToken(const FilterTokenRequest& request)
{
- ASSERT(m_state == Initialized);
- if (!m_isEnabled || m_xssProtection == ContentSecurityPolicy::AllowReflectedXSS)
+ ASSERT(m_state != Uninitialized);
+ if (!m_isEnabled || m_xssProtection == AllowReflectedXSS)
return nullptr;
bool didBlockScript = false;
@@ -330,7 +334,7 @@ PassOwnPtr<XSSInfo> XSSAuditor::filterToken(const FilterTokenRequest& request)
}
if (didBlockScript) {
- bool didBlockEntirePage = (m_xssProtection == ContentSecurityPolicy::BlockReflectedXSS);
+ bool didBlockEntirePage = (m_xssProtection == BlockReflectedXSS);
OwnPtr<XSSInfo> xssInfo = XSSInfo::create(m_documentURL, didBlockEntirePage, m_didSendValidXSSProtectionHeader, m_didSendValidCSPHeader);
return xssInfo.release();
}
@@ -339,6 +343,7 @@ PassOwnPtr<XSSInfo> XSSAuditor::filterToken(const FilterTokenRequest& request)
bool XSSAuditor::filterStartToken(const FilterTokenRequest& request)
{
+ m_state = FilteringTokens;
bool didBlockScript = eraseDangerousAttributesIfInjected(request);
if (hasName(request.token, scriptTag)) {
@@ -372,6 +377,7 @@ bool XSSAuditor::filterStartToken(const FilterTokenRequest& request)
void XSSAuditor::filterEndToken(const FilterTokenRequest& request)
{
ASSERT(m_scriptTagNestingLevel);
+ m_state = FilteringTokens;
if (hasName(request.token, scriptTag)) {
m_scriptTagNestingLevel--;
ASSERT(request.shouldAllowCDATA || !m_scriptTagNestingLevel);
@@ -381,11 +387,19 @@ void XSSAuditor::filterEndToken(const FilterTokenRequest& request)
bool XSSAuditor::filterCharacterToken(const FilterTokenRequest& request)
{
ASSERT(m_scriptTagNestingLevel);
- if (m_scriptTagFoundInRequest && isContainedInRequest(decodedSnippetForJavaScript(request))) {
+ ASSERT(m_state != Uninitialized);
+ if (m_state == PermittingAdjacentCharacterTokens)
+ return false;
+
+ if ((m_state == SuppressingAdjacentCharacterTokens)
+ || (m_scriptTagFoundInRequest && isContainedInRequest(decodedSnippetForJavaScript(request)))) {
request.token.eraseCharacters();
request.token.appendToCharacter(' '); // Technically, character tokens can't be empty.
+ m_state = SuppressingAdjacentCharacterTokens;
return true;
}
+
+ m_state = PermittingAdjacentCharacterTokens;
return false;
}
@@ -465,11 +479,10 @@ bool XSSAuditor::filterFrameToken(const FilterTokenRequest& request)
ASSERT(request.token.type() == HTMLToken::StartTag);
ASSERT(hasName(request.token, iframeTag) || hasName(request.token, frameTag));
- bool didBlockScript = false;
- if (isContainedInRequest(decodedSnippetForName(request))) {
+ bool didBlockScript = eraseAttributeIfInjected(request, srcdocAttr, String(), ScriptLikeAttribute);
+ if (isContainedInRequest(decodedSnippetForName(request)))
didBlockScript |= eraseAttributeIfInjected(request, srcAttr, String(), SrcLikeAttribute);
- didBlockScript |= eraseAttributeIfInjected(request, srcdocAttr, String(), ScriptLikeAttribute);
- }
+
return didBlockScript;
}
@@ -494,7 +507,7 @@ bool XSSAuditor::filterFormToken(const FilterTokenRequest& request)
ASSERT(request.token.type() == HTMLToken::StartTag);
ASSERT(hasName(request.token, formTag));
- return eraseAttributeIfInjected(request, actionAttr, blankURL().string());
+ return eraseAttributeIfInjected(request, actionAttr, kURLWithUniqueOrigin);
}
bool XSSAuditor::filterInputToken(const FilterTokenRequest& request)
@@ -502,7 +515,7 @@ bool XSSAuditor::filterInputToken(const FilterTokenRequest& request)
ASSERT(request.token.type() == HTMLToken::StartTag);
ASSERT(hasName(request.token, inputTag));
- return eraseAttributeIfInjected(request, formactionAttr, blankURL().string(), SrcLikeAttribute);
+ return eraseAttributeIfInjected(request, formactionAttr, kURLWithUniqueOrigin, SrcLikeAttribute);
}
bool XSSAuditor::filterButtonToken(const FilterTokenRequest& request)
@@ -510,7 +523,7 @@ bool XSSAuditor::filterButtonToken(const FilterTokenRequest& request)
ASSERT(request.token.type() == HTMLToken::StartTag);
ASSERT(hasName(request.token, buttonTag));
- return eraseAttributeIfInjected(request, formactionAttr, blankURL().string(), SrcLikeAttribute);
+ return eraseAttributeIfInjected(request, formactionAttr, kURLWithUniqueOrigin, SrcLikeAttribute);
}
bool XSSAuditor::eraseDangerousAttributesIfInjected(const FilterTokenRequest& request)
diff --git a/chromium/third_party/WebKit/Source/core/html/parser/XSSAuditor.h b/chromium/third_party/WebKit/Source/core/html/parser/XSSAuditor.h
index 5249479c630..db2655f4a8a 100644
--- a/chromium/third_party/WebKit/Source/core/html/parser/XSSAuditor.h
+++ b/chromium/third_party/WebKit/Source/core/html/parser/XSSAuditor.h
@@ -27,9 +27,9 @@
#define XSSAuditor_h
#include "core/html/parser/HTMLToken.h"
-#include "core/platform/network/HTTPParsers.h"
-#include "core/platform/text/SuffixTree.h"
-#include "weborigin/KURL.h"
+#include "platform/network/HTTPParsers.h"
+#include "platform/text/SuffixTree.h"
+#include "platform/weborigin/KURL.h"
#include "wtf/PassOwnPtr.h"
#include "wtf/text/TextEncoding.h"
@@ -69,7 +69,9 @@ private:
enum State {
Uninitialized,
- Initialized
+ FilteringTokens,
+ PermittingAdjacentCharacterTokens,
+ SuppressingAdjacentCharacterTokens
};
enum AttributeKind {
@@ -107,7 +109,7 @@ private:
KURL m_documentURL;
bool m_isEnabled;
- ContentSecurityPolicy::ReflectedXSSDisposition m_xssProtection;
+ ReflectedXSSDisposition m_xssProtection;
bool m_didSendValidCSPHeader;
bool m_didSendValidXSSProtectionHeader;
diff --git a/chromium/third_party/WebKit/Source/core/html/parser/XSSAuditorDelegate.cpp b/chromium/third_party/WebKit/Source/core/html/parser/XSSAuditorDelegate.cpp
index a5a4f52b73f..5ea9b66ccf7 100644
--- a/chromium/third_party/WebKit/Source/core/html/parser/XSSAuditorDelegate.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/parser/XSSAuditorDelegate.cpp
@@ -27,40 +27,32 @@
#include "core/html/parser/XSSAuditorDelegate.h"
#include "core/dom/Document.h"
+#include "core/frame/Frame.h"
#include "core/loader/DocumentLoader.h"
#include "core/loader/FrameLoader.h"
#include "core/loader/FrameLoaderClient.h"
#include "core/loader/PingLoader.h"
-#include "core/page/Frame.h"
-#include "core/platform/JSONValues.h"
-#include "core/platform/network/FormData.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/JSONValues.h"
+#include "platform/network/FormData.h"
+#include "platform/weborigin/SecurityOrigin.h"
#include "wtf/text/StringBuilder.h"
namespace WebCore {
-XSSAuditorDelegate::XSSAuditorDelegate(Document* document)
- : m_document(document)
- , m_didSendNotifications(false)
-{
- ASSERT(isMainThread());
- ASSERT(m_document);
-}
-
-static inline String buildConsoleError(const XSSInfo& xssInfo)
+String XSSInfo::buildConsoleError() const
{
StringBuilder message;
message.append("The XSS Auditor ");
- message.append(xssInfo.m_didBlockEntirePage ? "blocked access to" : "refused to execute a script in");
+ message.append(m_didBlockEntirePage ? "blocked access to" : "refused to execute a script in");
message.append(" '");
- message.append(xssInfo.m_originalURL);
+ message.append(m_originalURL);
message.append("' because ");
- message.append(xssInfo.m_didBlockEntirePage ? "the source code of a script" : "its source code");
+ message.append(m_didBlockEntirePage ? "the source code of a script" : "its source code");
message.append(" was found within the request.");
- if (xssInfo.m_didSendCSPHeader)
+ if (m_didSendCSPHeader)
message.append(" The server sent a 'Content-Security-Policy' header requesting this behavior.");
- else if (xssInfo.m_didSendXSSProtectionHeader)
+ else if (m_didSendXSSProtectionHeader)
message.append(" The server sent an 'X-XSS-Protection' header requesting this behavior.");
else
message.append(" The auditor was enabled as the server sent neither an 'X-XSS-Protection' nor 'Content-Security-Policy' header.");
@@ -68,14 +60,27 @@ static inline String buildConsoleError(const XSSInfo& xssInfo)
return message.toString();
}
+bool XSSInfo::isSafeToSendToAnotherThread() const
+{
+ return m_originalURL.isSafeToSendToAnotherThread();
+}
+
+XSSAuditorDelegate::XSSAuditorDelegate(Document* document)
+ : m_document(document)
+ , m_didSendNotifications(false)
+{
+ ASSERT(isMainThread());
+ ASSERT(m_document);
+}
+
PassRefPtr<FormData> XSSAuditorDelegate::generateViolationReport(const XSSInfo& xssInfo)
{
ASSERT(isMainThread());
- FrameLoader* frameLoader = m_document->frame()->loader();
+ FrameLoader& frameLoader = m_document->frame()->loader();
String httpBody;
- if (frameLoader->documentLoader()) {
- if (FormData* formData = frameLoader->documentLoader()->originalRequest().httpBody())
+ if (frameLoader.documentLoader()) {
+ if (FormData* formData = frameLoader.documentLoader()->originalRequest().httpBody())
httpBody = formData->flattenToString();
}
@@ -93,25 +98,25 @@ void XSSAuditorDelegate::didBlockScript(const XSSInfo& xssInfo)
{
ASSERT(isMainThread());
- m_document->addConsoleMessage(JSMessageSource, ErrorMessageLevel, buildConsoleError(xssInfo));
+ m_document->addConsoleMessage(JSMessageSource, ErrorMessageLevel, xssInfo.buildConsoleError());
// stopAllLoaders can detach the Frame, so protect it.
RefPtr<Frame> protect(m_document->frame());
- FrameLoader* frameLoader = m_document->frame()->loader();
+ FrameLoader& frameLoader = m_document->frame()->loader();
if (xssInfo.m_didBlockEntirePage)
- frameLoader->stopAllLoaders();
+ frameLoader.stopAllLoaders();
if (!m_didSendNotifications) {
m_didSendNotifications = true;
- frameLoader->client()->didDetectXSS(m_document->url(), xssInfo.m_didBlockEntirePage);
+ frameLoader.client()->didDetectXSS(m_document->url(), xssInfo.m_didBlockEntirePage);
if (!m_reportURL.isEmpty())
PingLoader::sendViolationReport(m_document->frame(), m_reportURL, generateViolationReport(xssInfo), PingLoader::XSSAuditorViolationReport);
}
if (xssInfo.m_didBlockEntirePage)
- m_document->frame()->navigationScheduler()->scheduleLocationChange(m_document->securityOrigin(), SecurityOrigin::urlWithUniqueSecurityOrigin(), String());
+ m_document->frame()->navigationScheduler().scheduleLocationChange(m_document, SecurityOrigin::urlWithUniqueSecurityOrigin(), String());
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/html/parser/XSSAuditorDelegate.h b/chromium/third_party/WebKit/Source/core/html/parser/XSSAuditorDelegate.h
index 5dda5f5b5e2..1fbfb20b01c 100644
--- a/chromium/third_party/WebKit/Source/core/html/parser/XSSAuditorDelegate.h
+++ b/chromium/third_party/WebKit/Source/core/html/parser/XSSAuditorDelegate.h
@@ -26,7 +26,7 @@
#ifndef XSSAuditorDelegate_h
#define XSSAuditorDelegate_h
-#include "weborigin/KURL.h"
+#include "platform/weborigin/KURL.h"
#include "wtf/OwnPtr.h"
#include "wtf/PassOwnPtr.h"
#include "wtf/Vector.h"
@@ -45,6 +45,9 @@ public:
return adoptPtr(new XSSInfo(originalURL, didBlockEntirePage, didSendXSSProtectionHeader, didSendCSPHeader));
}
+ String buildConsoleError() const;
+ bool isSafeToSendToAnotherThread() const;
+
String m_originalURL;
bool m_didBlockEntirePage;
bool m_didSendXSSProtectionHeader;
diff --git a/chromium/third_party/WebKit/Source/core/html/shadow/ClearButtonElement.cpp b/chromium/third_party/WebKit/Source/core/html/shadow/ClearButtonElement.cpp
index fc91016c8ee..cb928e81dce 100644
--- a/chromium/third_party/WebKit/Source/core/html/shadow/ClearButtonElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/shadow/ClearButtonElement.cpp
@@ -26,10 +26,10 @@
#include "config.h"
#include "core/html/shadow/ClearButtonElement.h"
-#include "core/dom/MouseEvent.h"
+#include "core/events/MouseEvent.h"
#include "core/html/shadow/ShadowElementNames.h"
#include "core/page/EventHandler.h"
-#include "core/page/Frame.h"
+#include "core/frame/Frame.h"
#include "core/rendering/RenderView.h"
namespace WebCore {
@@ -37,7 +37,7 @@ namespace WebCore {
using namespace HTMLNames;
inline ClearButtonElement::ClearButtonElement(Document& document, ClearButtonOwner& clearButtonOwner)
- : HTMLDivElement(divTag, document)
+ : HTMLDivElement(document)
, m_clearButtonOwner(&clearButtonOwner)
, m_capturing(false)
{
@@ -46,7 +46,7 @@ inline ClearButtonElement::ClearButtonElement(Document& document, ClearButtonOwn
PassRefPtr<ClearButtonElement> ClearButtonElement::create(Document& document, ClearButtonOwner& clearButtonOwner)
{
RefPtr<ClearButtonElement> element = adoptRef(new ClearButtonElement(document, clearButtonOwner));
- element->setPart(AtomicString("-webkit-clear-button", AtomicString::ConstructFromLiteral));
+ element->setPseudo(AtomicString("-webkit-clear-button", AtomicString::ConstructFromLiteral));
element->setAttribute(idAttr, ShadowElementNames::clearButton());
return element.release();
}
@@ -55,7 +55,7 @@ void ClearButtonElement::detach(const AttachContext& context)
{
if (m_capturing) {
if (Frame* frame = document().frame())
- frame->eventHandler()->setCapturingMouseEventsNode(0);
+ frame->eventHandler().setCapturingMouseEventsNode(0);
}
HTMLDivElement::detach(context);
}
@@ -66,7 +66,7 @@ void ClearButtonElement::releaseCapture()
return;
if (Frame* frame = document().frame()) {
- frame->eventHandler()->setCapturingMouseEventsNode(0);
+ frame->eventHandler().setCapturingMouseEventsNode(0);
m_capturing = false;
}
}
@@ -85,20 +85,20 @@ void ClearButtonElement::defaultEventHandler(Event* event)
return;
}
- if (event->type() == eventNames().mousedownEvent && event->isMouseEvent() && toMouseEvent(event)->button() == LeftButton) {
+ if (event->type() == EventTypeNames::mousedown && event->isMouseEvent() && toMouseEvent(event)->button() == LeftButton) {
if (renderer() && renderer()->visibleToHitTesting()) {
if (Frame* frame = document().frame()) {
- frame->eventHandler()->setCapturingMouseEventsNode(this);
+ frame->eventHandler().setCapturingMouseEventsNode(this);
m_capturing = true;
}
}
m_clearButtonOwner->focusAndSelectClearButtonOwner();
event->setDefaultHandled();
}
- if (event->type() == eventNames().mouseupEvent && event->isMouseEvent() && toMouseEvent(event)->button() == LeftButton) {
+ if (event->type() == EventTypeNames::mouseup && event->isMouseEvent() && toMouseEvent(event)->button() == LeftButton) {
if (m_capturing) {
if (Frame* frame = document().frame()) {
- frame->eventHandler()->setCapturingMouseEventsNode(0);
+ frame->eventHandler().setCapturingMouseEventsNode(0);
m_capturing = false;
}
if (hovered()) {
diff --git a/chromium/third_party/WebKit/Source/core/html/shadow/ClearButtonElement.h b/chromium/third_party/WebKit/Source/core/html/shadow/ClearButtonElement.h
index 00bf5aa4a53..47c91115e31 100644
--- a/chromium/third_party/WebKit/Source/core/html/shadow/ClearButtonElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/shadow/ClearButtonElement.h
@@ -56,11 +56,7 @@ private:
bool m_capturing;
};
-inline ClearButtonElement* toClearButtonElement(Element* element)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!element || element->isClearButtonElement());
- return static_cast<ClearButtonElement*>(element);
-}
+DEFINE_TYPE_CASTS(ClearButtonElement, Element, element, element->isClearButtonElement(), element.isClearButtonElement());
} // namespace
diff --git a/chromium/third_party/WebKit/Source/core/html/shadow/DateTimeEditElement.cpp b/chromium/third_party/WebKit/Source/core/html/shadow/DateTimeEditElement.cpp
index 562525eda03..eb3508e9dc8 100644
--- a/chromium/third_party/WebKit/Source/core/html/shadow/DateTimeEditElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/shadow/DateTimeEditElement.cpp
@@ -29,17 +29,16 @@
#include "HTMLNames.h"
#include "bindings/v8/ExceptionStatePlaceholder.h"
-#include "core/dom/MouseEvent.h"
#include "core/dom/Text.h"
+#include "core/events/MouseEvent.h"
#include "core/html/forms/DateTimeFieldsState.h"
#include "core/html/shadow/DateTimeFieldElements.h"
#include "core/html/shadow/ShadowElementNames.h"
-#include "core/platform/DateComponents.h"
-#include "core/platform/graphics/FontCache.h"
-#include "core/platform/text/DateTimeFormat.h"
-#include "core/platform/text/PlatformLocale.h"
#include "core/rendering/style/RenderStyle.h"
#include "core/rendering/style/StyleInheritedData.h"
+#include "platform/fonts/FontCache.h"
+#include "platform/text/DateTimeFormat.h"
+#include "platform/text/PlatformLocale.h"
#include "wtf/DateMath.h"
namespace WebCore {
@@ -403,7 +402,7 @@ void DateTimeEditBuilder::visitLiteral(const String& text)
DEFINE_STATIC_LOCAL(AtomicString, textPseudoId, ("-webkit-datetime-edit-text", AtomicString::ConstructFromLiteral));
ASSERT(text.length());
RefPtr<HTMLDivElement> element = HTMLDivElement::create(m_editElement.document());
- element->setPart(textPseudoId);
+ element->setPseudo(textPseudoId);
if (m_parameters.locale.isRTL() && text.length()) {
Direction dir = direction(text[0]);
if (dir == SegmentSeparator || dir == WhiteSpaceNeutral || dir == OtherNeutral)
@@ -441,7 +440,7 @@ DateTimeEditElement::EditControlOwner::~EditControlOwner()
}
DateTimeEditElement::DateTimeEditElement(Document& document, EditControlOwner& editControlOwner)
- : HTMLDivElement(divTag, document)
+ : HTMLDivElement(document)
, m_editControlOwner(&editControlOwner)
{
setHasCustomStyleCallbacks();
@@ -485,7 +484,7 @@ void DateTimeEditElement::blurByOwner()
PassRefPtr<DateTimeEditElement> DateTimeEditElement::create(Document& document, EditControlOwner& editControlOwner)
{
RefPtr<DateTimeEditElement> container = adoptRef(new DateTimeEditElement(document, editControlOwner));
- container->setPart(AtomicString("-webkit-datetime-edit", AtomicString::ConstructFromLiteral));
+ container->setPseudo(AtomicString("-webkit-datetime-edit", AtomicString::ConstructFromLiteral));
container->setAttribute(idAttr, ShadowElementNames::dateTimeEdit());
return container.release();
}
@@ -512,6 +511,7 @@ PassRefPtr<RenderStyle> DateTimeEditElement::customStyleForRenderer()
}
}
style->setWidth(Length(ceilf(width), Fixed));
+ style->setUnique();
return style.release();
}
@@ -652,7 +652,7 @@ void DateTimeEditElement::layout(const LayoutParameters& layoutParameters, const
DEFINE_STATIC_LOCAL(AtomicString, fieldsWrapperPseudoId, ("-webkit-datetime-edit-fields-wrapper", AtomicString::ConstructFromLiteral));
if (!firstChild()) {
RefPtr<HTMLDivElement> element = HTMLDivElement::create(document());
- element->setPart(fieldsWrapperPseudoId);
+ element->setPseudo(fieldsWrapperPseudoId);
appendChild(element.get());
}
Element* fieldsWrapper = fieldsWrapperElement();
diff --git a/chromium/third_party/WebKit/Source/core/html/shadow/DateTimeEditElement.h b/chromium/third_party/WebKit/Source/core/html/shadow/DateTimeEditElement.h
index f6a54d71c91..87226cb136b 100644
--- a/chromium/third_party/WebKit/Source/core/html/shadow/DateTimeEditElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/shadow/DateTimeEditElement.h
@@ -29,7 +29,7 @@
#if ENABLE(INPUT_MULTIPLE_FIELDS_UI)
#include "core/html/forms/StepRange.h"
#include "core/html/shadow/DateTimeFieldElement.h"
-#include "core/platform/DateComponents.h"
+#include "platform/DateComponents.h"
namespace WebCore {
@@ -149,11 +149,7 @@ private:
EditControlOwner* m_editControlOwner;
};
-inline DateTimeEditElement* toDateTimeEditElement(Element* element)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!element || element->isDateTimeEditElement());
- return static_cast<DateTimeEditElement*>(element);
-}
+DEFINE_TYPE_CASTS(DateTimeEditElement, Element, element, element->isDateTimeEditElement(), element.isDateTimeEditElement());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/html/shadow/DateTimeFieldElement.cpp b/chromium/third_party/WebKit/Source/core/html/shadow/DateTimeFieldElement.cpp
index 76c20d45566..31cdb06f9c4 100644
--- a/chromium/third_party/WebKit/Source/core/html/shadow/DateTimeFieldElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/shadow/DateTimeFieldElement.cpp
@@ -28,32 +28,36 @@
#include "core/html/shadow/DateTimeFieldElement.h"
#include "HTMLNames.h"
-#include "core/dom/KeyboardEvent.h"
#include "core/dom/Text.h"
-#include "core/platform/LocalizedStrings.h"
-#include "core/platform/text/PlatformLocale.h"
+#include "core/events/KeyboardEvent.h"
+#include "platform/text/PlatformLocale.h"
#include "wtf/text/WTFString.h"
namespace WebCore {
using namespace HTMLNames;
+static String emptyValueAXText()
+{
+ return Locale::defaultLocale().queryString(blink::WebLocalizedString::AXDateTimeFieldEmptyValueText);
+}
+
DateTimeFieldElement::FieldOwner::~FieldOwner()
{
}
DateTimeFieldElement::DateTimeFieldElement(Document& document, FieldOwner& fieldOwner)
- : HTMLSpanElement(spanTag, document)
+ : HTMLSpanElement(document)
, m_fieldOwner(&fieldOwner)
{
}
void DateTimeFieldElement::defaultEventHandler(Event* event)
{
- if (event->type() == eventNames().blurEvent)
+ if (event->type() == EventTypeNames::blur)
didBlur();
- if (event->type() == eventNames().focusEvent)
+ if (event->type() == EventTypeNames::focus)
didFocus();
if (event->isKeyboardEvent()) {
@@ -73,7 +77,7 @@ void DateTimeFieldElement::defaultEventHandler(Event* event)
void DateTimeFieldElement::defaultKeyboardEventHandler(KeyboardEvent* keyboardEvent)
{
- if (keyboardEvent->type() != eventNames().keydownEvent)
+ if (keyboardEvent->type() != EventTypeNames::keydown)
return;
if (isDisabled() || isFieldOwnerDisabled())
@@ -148,12 +152,12 @@ void DateTimeFieldElement::initialize(const AtomicString& pseudo, const String&
{
// On accessibility, DateTimeFieldElement acts like spin button.
setAttribute(roleAttr, AtomicString("spinbutton", AtomicString::ConstructFromLiteral));
- setAttribute(aria_valuetextAttr, AXDateTimeFieldEmptyValueText());
+ setAttribute(aria_valuetextAttr, emptyValueAXText());
setAttribute(aria_valueminAttr, String::number(axMinimum));
setAttribute(aria_valuemaxAttr, String::number(axMaximum));
setAttribute(aria_helpAttr, axHelpText);
- setPart(pseudo);
+ setPseudo(pseudo);
appendChild(Text::create(document(), visibleValue()));
}
@@ -219,7 +223,7 @@ void DateTimeFieldElement::updateVisibleValue(EventBehavior eventBehavior)
setAttribute(aria_valuetextAttr, newVisibleValue);
setAttribute(aria_valuenowAttr, String::number(valueForARIAValueNow()));
} else {
- setAttribute(aria_valuetextAttr, AXDateTimeFieldEmptyValueText());
+ setAttribute(aria_valuetextAttr, emptyValueAXText());
removeAttribute(aria_valuenowAttr);
}
diff --git a/chromium/third_party/WebKit/Source/core/html/shadow/DateTimeFieldElements.cpp b/chromium/third_party/WebKit/Source/core/html/shadow/DateTimeFieldElements.cpp
index 4fc9f6e6263..5353c04ff2e 100644
--- a/chromium/third_party/WebKit/Source/core/html/shadow/DateTimeFieldElements.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/shadow/DateTimeFieldElements.cpp
@@ -28,13 +28,20 @@
#include "core/html/shadow/DateTimeFieldElements.h"
#include "core/html/forms/DateTimeFieldsState.h"
-#include "core/platform/DateComponents.h"
-#include "core/platform/LocalizedStrings.h"
+#include "platform/DateComponents.h"
+#include "platform/text/PlatformLocale.h"
#include "wtf/CurrentTime.h"
#include "wtf/DateMath.h"
namespace WebCore {
+using blink::WebLocalizedString;
+
+static String queryString(WebLocalizedString::Name name)
+{
+ return Locale::defaultLocale().queryString(name);
+}
+
DateTimeAMPMFieldElement::DateTimeAMPMFieldElement(Document& document, FieldOwner& fieldOwner, const Vector<String>& ampmLabels)
: DateTimeSymbolicFieldElement(document, fieldOwner, ampmLabels, 0, 1)
{
@@ -44,7 +51,7 @@ PassRefPtr<DateTimeAMPMFieldElement> DateTimeAMPMFieldElement::create(Document&
{
DEFINE_STATIC_LOCAL(AtomicString, ampmPsuedoId, ("-webkit-datetime-edit-ampm-field", AtomicString::ConstructFromLiteral));
RefPtr<DateTimeAMPMFieldElement> field = adoptRef(new DateTimeAMPMFieldElement(document, fieldOwner, ampmLabels));
- field->initialize(ampmPsuedoId, AXAMPMFieldText());
+ field->initialize(ampmPsuedoId, queryString(WebLocalizedString::AXAMPMFieldText));
return field.release();
}
@@ -80,7 +87,7 @@ PassRefPtr<DateTimeDayFieldElement> DateTimeDayFieldElement::create(Document& do
{
DEFINE_STATIC_LOCAL(AtomicString, dayPsuedoId, ("-webkit-datetime-edit-day-field", AtomicString::ConstructFromLiteral));
RefPtr<DateTimeDayFieldElement> field = adoptRef(new DateTimeDayFieldElement(document, fieldOwner, placeholder.isEmpty() ? "--" : placeholder, range));
- field->initialize(dayPsuedoId, AXDayOfMonthFieldText());
+ field->initialize(dayPsuedoId, queryString(WebLocalizedString::AXDayOfMonthFieldText));
return field.release();
}
@@ -120,7 +127,7 @@ DateTimeHourFieldElementBase::DateTimeHourFieldElementBase(Document& document, F
void DateTimeHourFieldElementBase::initialize()
{
DEFINE_STATIC_LOCAL(AtomicString, hourPsuedoId, ("-webkit-datetime-edit-hour-field", AtomicString::ConstructFromLiteral));
- DateTimeNumericFieldElement::initialize(hourPsuedoId, AXHourFieldText());
+ DateTimeNumericFieldElement::initialize(hourPsuedoId, queryString(WebLocalizedString::AXHourFieldText));
}
void DateTimeHourFieldElementBase::setValueAsDate(const DateComponents& date)
@@ -323,7 +330,7 @@ PassRefPtr<DateTimeMillisecondFieldElement> DateTimeMillisecondFieldElement::cre
{
DEFINE_STATIC_LOCAL(AtomicString, millisecondPsuedoId, ("-webkit-datetime-edit-millisecond-field", AtomicString::ConstructFromLiteral));
RefPtr<DateTimeMillisecondFieldElement> field = adoptRef(new DateTimeMillisecondFieldElement(document, fieldOwner, range, step));
- field->initialize(millisecondPsuedoId, AXMillisecondFieldText());
+ field->initialize(millisecondPsuedoId, queryString(WebLocalizedString::AXMillisecondFieldText));
return field.release();
}
@@ -364,7 +371,7 @@ PassRefPtr<DateTimeMinuteFieldElement> DateTimeMinuteFieldElement::create(Docume
{
DEFINE_STATIC_LOCAL(AtomicString, minutePsuedoId, ("-webkit-datetime-edit-minute-field", AtomicString::ConstructFromLiteral));
RefPtr<DateTimeMinuteFieldElement> field = adoptRef(new DateTimeMinuteFieldElement(document, fieldOwner, range, step));
- field->initialize(minutePsuedoId, AXMinuteFieldText());
+ field->initialize(minutePsuedoId, queryString(WebLocalizedString::AXMinuteFieldText));
return field.release();
}
@@ -405,7 +412,7 @@ PassRefPtr<DateTimeMonthFieldElement> DateTimeMonthFieldElement::create(Document
{
DEFINE_STATIC_LOCAL(AtomicString, monthPsuedoId, ("-webkit-datetime-edit-month-field", AtomicString::ConstructFromLiteral));
RefPtr<DateTimeMonthFieldElement> field = adoptRef(new DateTimeMonthFieldElement(document, fieldOwner, placeholder.isEmpty() ? "--" : placeholder, range));
- field->initialize(monthPsuedoId, AXMonthFieldText());
+ field->initialize(monthPsuedoId, queryString(WebLocalizedString::AXMonthFieldText));
return field.release();
}
@@ -446,7 +453,7 @@ PassRefPtr<DateTimeSecondFieldElement> DateTimeSecondFieldElement::create(Docume
{
DEFINE_STATIC_LOCAL(AtomicString, secondPsuedoId, ("-webkit-datetime-edit-second-field", AtomicString::ConstructFromLiteral));
RefPtr<DateTimeSecondFieldElement> field = adoptRef(new DateTimeSecondFieldElement(document, fieldOwner, range, step));
- field->initialize(secondPsuedoId, AXSecondFieldText());
+ field->initialize(secondPsuedoId, queryString(WebLocalizedString::AXSecondFieldText));
return field.release();
}
@@ -487,7 +494,7 @@ PassRefPtr<DateTimeSymbolicMonthFieldElement> DateTimeSymbolicMonthFieldElement:
{
DEFINE_STATIC_LOCAL(AtomicString, monthPsuedoId, ("-webkit-datetime-edit-month-field", AtomicString::ConstructFromLiteral));
RefPtr<DateTimeSymbolicMonthFieldElement> field = adoptRef(new DateTimeSymbolicMonthFieldElement(document, fieldOwner, labels, minimum, maximum));
- field->initialize(monthPsuedoId, AXMonthFieldText());
+ field->initialize(monthPsuedoId, queryString(WebLocalizedString::AXMonthFieldText));
return field.release();
}
@@ -531,7 +538,7 @@ PassRefPtr<DateTimeWeekFieldElement> DateTimeWeekFieldElement::create(Document&
{
DEFINE_STATIC_LOCAL(AtomicString, weekPsuedoId, ("-webkit-datetime-edit-week-field", AtomicString::ConstructFromLiteral));
RefPtr<DateTimeWeekFieldElement> field = adoptRef(new DateTimeWeekFieldElement(document, fieldOwner, range));
- field->initialize(weekPsuedoId, AXWeekOfYearFieldText());
+ field->initialize(weekPsuedoId, queryString(WebLocalizedString::AXWeekOfYearFieldText));
return field.release();
}
@@ -576,7 +583,7 @@ PassRefPtr<DateTimeYearFieldElement> DateTimeYearFieldElement::create(Document&
{
DEFINE_STATIC_LOCAL(AtomicString, yearPsuedoId, ("-webkit-datetime-edit-year-field", AtomicString::ConstructFromLiteral));
RefPtr<DateTimeYearFieldElement> field = adoptRef(new DateTimeYearFieldElement(document, fieldOwner, parameters));
- field->initialize(yearPsuedoId, AXYearFieldText());
+ field->initialize(yearPsuedoId, queryString(WebLocalizedString::AXYearFieldText));
return field.release();
}
diff --git a/chromium/third_party/WebKit/Source/core/html/shadow/DateTimeNumericFieldElement.cpp b/chromium/third_party/WebKit/Source/core/html/shadow/DateTimeNumericFieldElement.cpp
index 15703d531e8..537416f7402 100644
--- a/chromium/third_party/WebKit/Source/core/html/shadow/DateTimeNumericFieldElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/shadow/DateTimeNumericFieldElement.cpp
@@ -29,17 +29,14 @@
#include "CSSPropertyNames.h"
#include "CSSValueKeywords.h"
-#include "core/dom/KeyboardEvent.h"
-#include "core/platform/graphics/Font.h"
-#include "core/platform/text/PlatformLocale.h"
-#include "wtf/text/StringBuilder.h"
+#include "core/events/KeyboardEvent.h"
+#include "platform/fonts/Font.h"
+#include "platform/text/PlatformLocale.h"
using namespace WTF::Unicode;
namespace WebCore {
-static const DOMTimeStamp typeAheadTimeout = 1000;
-
int DateTimeNumericFieldElement::Range::clampValue(int value) const
{
return std::min(std::max(value, minimum), maximum);
@@ -54,7 +51,6 @@ bool DateTimeNumericFieldElement::Range::isInRange(int value) const
DateTimeNumericFieldElement::DateTimeNumericFieldElement(Document& document, FieldOwner& fieldOwner, const Range& range, const Range& hardLimits, const String& placeholder, const DateTimeNumericFieldElement::Step& step)
: DateTimeFieldElement(document, fieldOwner)
- , m_lastDigitCharTime(0)
, m_placeholder(placeholder)
, m_range(range)
, m_hardLimits(hardLimits)
@@ -117,7 +113,7 @@ String DateTimeNumericFieldElement::formatValue(int value) const
void DateTimeNumericFieldElement::handleKeyboardEvent(KeyboardEvent* keyboardEvent)
{
ASSERT(!isDisabled());
- if (keyboardEvent->type() != eventNames().keypressEvent)
+ if (keyboardEvent->type() != EventTypeNames::keypress)
return;
UChar charCode = static_cast<UChar>(keyboardEvent->charCode());
@@ -126,13 +122,7 @@ void DateTimeNumericFieldElement::handleKeyboardEvent(KeyboardEvent* keyboardEve
if (digit < 0 || digit > 9)
return;
- DOMTimeStamp delta = keyboardEvent->timeStamp() - m_lastDigitCharTime;
- m_lastDigitCharTime = keyboardEvent->timeStamp();
-
- if (delta > typeAheadTimeout)
- m_typeAheadBuffer.clear();
m_typeAheadBuffer.append(number);
-
int newValue = typeAheadValue();
if (newValue >= m_hardLimits.minimum)
setValueAsInteger(newValue, DispatchEvent);
diff --git a/chromium/third_party/WebKit/Source/core/html/shadow/DateTimeNumericFieldElement.h b/chromium/third_party/WebKit/Source/core/html/shadow/DateTimeNumericFieldElement.h
index e38e2103696..9b96fb54e3b 100644
--- a/chromium/third_party/WebKit/Source/core/html/shadow/DateTimeNumericFieldElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/shadow/DateTimeNumericFieldElement.h
@@ -92,7 +92,6 @@ private:
int roundDown(int) const;
int typeAheadValue() const;
- DOMTimeStamp m_lastDigitCharTime;
const String m_placeholder;
const Range m_range;
const Range m_hardLimits;
diff --git a/chromium/third_party/WebKit/Source/core/html/shadow/DateTimeSymbolicFieldElement.cpp b/chromium/third_party/WebKit/Source/core/html/shadow/DateTimeSymbolicFieldElement.cpp
index 16d62440430..bcda2753b2b 100644
--- a/chromium/third_party/WebKit/Source/core/html/shadow/DateTimeSymbolicFieldElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/shadow/DateTimeSymbolicFieldElement.cpp
@@ -27,9 +27,9 @@
#if ENABLE(INPUT_MULTIPLE_FIELDS_UI)
#include "core/html/shadow/DateTimeSymbolicFieldElement.h"
-#include "core/dom/KeyboardEvent.h"
-#include "core/platform/graphics/Font.h"
-#include "core/platform/text/TextBreakIterator.h"
+#include "core/events/KeyboardEvent.h"
+#include "platform/fonts/Font.h"
+#include "platform/text/TextBreakIterator.h"
#include "wtf/text/StringBuilder.h"
#include "wtf/unicode/Unicode.h"
@@ -72,7 +72,7 @@ float DateTimeSymbolicFieldElement::maximumWidth(const Font& font)
void DateTimeSymbolicFieldElement::handleKeyboardEvent(KeyboardEvent* keyboardEvent)
{
- if (keyboardEvent->type() != eventNames().keypressEvent)
+ if (keyboardEvent->type() != EventTypeNames::keypress)
return;
const UChar charCode = WTF::Unicode::toLower(keyboardEvent->charCode());
diff --git a/chromium/third_party/WebKit/Source/core/html/shadow/DetailsMarkerControl.cpp b/chromium/third_party/WebKit/Source/core/html/shadow/DetailsMarkerControl.cpp
index 2056e1a85d8..f3f2adb3b8e 100644
--- a/chromium/third_party/WebKit/Source/core/html/shadow/DetailsMarkerControl.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/shadow/DetailsMarkerControl.cpp
@@ -40,7 +40,7 @@ namespace WebCore {
using namespace HTMLNames;
DetailsMarkerControl::DetailsMarkerControl(Document& document)
- : HTMLDivElement(divTag, document)
+ : HTMLDivElement(document)
{
}
diff --git a/chromium/third_party/WebKit/Source/core/html/shadow/DetailsMarkerControl.h b/chromium/third_party/WebKit/Source/core/html/shadow/DetailsMarkerControl.h
index a86195fb00e..118063ef090 100644
--- a/chromium/third_party/WebKit/Source/core/html/shadow/DetailsMarkerControl.h
+++ b/chromium/third_party/WebKit/Source/core/html/shadow/DetailsMarkerControl.h
@@ -53,7 +53,7 @@ private:
inline PassRefPtr<DetailsMarkerControl> DetailsMarkerControl::create(Document& document)
{
RefPtr<DetailsMarkerControl> element = adoptRef(new DetailsMarkerControl(document));
- element->setPart(AtomicString("-webkit-details-marker", AtomicString::ConstructFromLiteral));
+ element->setPseudo(AtomicString("-webkit-details-marker", AtomicString::ConstructFromLiteral));
return element.release();
}
diff --git a/chromium/third_party/WebKit/Source/core/html/shadow/HTMLContentElement.cpp b/chromium/third_party/WebKit/Source/core/html/shadow/HTMLContentElement.cpp
index 004beb847c0..81691295e85 100644
--- a/chromium/third_party/WebKit/Source/core/html/shadow/HTMLContentElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/shadow/HTMLContentElement.cpp
@@ -29,7 +29,6 @@
#include "HTMLNames.h"
#include "core/css/CSSParser.h"
-#include "core/css/CSSSelectorList.h"
#include "core/css/SelectorChecker.h"
#include "core/css/SiblingTraversalStrategies.h"
#include "core/dom/QualifiedName.h"
@@ -42,20 +41,14 @@ using namespace HTMLNames;
PassRefPtr<HTMLContentElement> HTMLContentElement::create(Document& document)
{
- return adoptRef(new HTMLContentElement(contentTag, document));
+ return adoptRef(new HTMLContentElement(document));
}
-PassRefPtr<HTMLContentElement> HTMLContentElement::create(const QualifiedName& tagName, Document& document)
-{
- return adoptRef(new HTMLContentElement(tagName, document));
-}
-
-HTMLContentElement::HTMLContentElement(const QualifiedName& name, Document& document)
- : InsertionPoint(name, document)
+HTMLContentElement::HTMLContentElement(Document& document)
+ : InsertionPoint(contentTag, document)
, m_shouldParseSelect(false)
, m_isValidSelector(true)
{
- ASSERT(hasTagName(contentTag));
ScriptWrappable::init(this);
}
@@ -106,17 +99,16 @@ bool HTMLContentElement::validateSelect() const
return true;
}
-static inline bool checkOneSelector(const CSSSelector* selector, const Vector<Node*>& siblings, int nth)
+static inline bool checkOneSelector(const CSSSelector* selector, const Vector<Node*, 32>& siblings, int nth)
{
Element* element = toElement(siblings[nth]);
- SelectorChecker selectorChecker(element->document(), SelectorChecker::CollectingRules);
+ SelectorChecker selectorChecker(element->document(), SelectorChecker::CollectingCSSRules);
SelectorChecker::SelectorCheckingContext context(selector, element, SelectorChecker::VisitedMatchEnabled);
ShadowDOMSiblingTraversalStrategy strategy(siblings, nth);
- PseudoId ignoreDynamicPseudo = NOPSEUDO;
- return selectorChecker.match(context, ignoreDynamicPseudo, strategy) == SelectorChecker::SelectorMatches;
+ return selectorChecker.match(context, strategy) == SelectorChecker::SelectorMatches;
}
-bool HTMLContentElement::matchSelector(const Vector<Node*>& siblings, int nth) const
+bool HTMLContentElement::matchSelector(const Vector<Node*, 32>& siblings, int nth) const
{
for (const CSSSelector* selector = selectorList().first(); selector; selector = CSSSelectorList::next(selector)) {
if (checkOneSelector(selector, siblings, nth))
diff --git a/chromium/third_party/WebKit/Source/core/html/shadow/HTMLContentElement.h b/chromium/third_party/WebKit/Source/core/html/shadow/HTMLContentElement.h
index df52237d34f..b8f0f4fdd58 100644
--- a/chromium/third_party/WebKit/Source/core/html/shadow/HTMLContentElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/shadow/HTMLContentElement.h
@@ -38,27 +38,26 @@ namespace WebCore {
class HTMLContentElement FINAL : public InsertionPoint {
public:
- static PassRefPtr<HTMLContentElement> create(const QualifiedName&, Document&);
static PassRefPtr<HTMLContentElement> create(Document&);
virtual ~HTMLContentElement();
virtual bool canAffectSelector() const OVERRIDE { return true; }
- bool canSelectNode(const Vector<Node*>& siblings, int nth) const;
+ bool canSelectNode(const Vector<Node*, 32>& siblings, int nth) const;
const CSSSelectorList& selectorList() const;
bool isSelectValid() const;
private:
- HTMLContentElement(const QualifiedName&, Document&);
+ explicit HTMLContentElement(Document&);
virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
bool validateSelect() const;
void parseSelect();
- bool matchSelector(const Vector<Node*>& siblings, int nth) const;
+ bool matchSelector(const Vector<Node*, 32>& siblings, int nth) const;
bool m_shouldParseSelect;
bool m_isValidSelector;
@@ -80,7 +79,7 @@ inline bool HTMLContentElement::isSelectValid() const
return m_isValidSelector;
}
-inline bool HTMLContentElement::canSelectNode(const Vector<Node*>& siblings, int nth) const
+inline bool HTMLContentElement::canSelectNode(const Vector<Node*, 32>& siblings, int nth) const
{
if (m_select.isNull() || m_select.isEmpty())
return true;
@@ -101,11 +100,7 @@ inline bool isHTMLContentElement(const Element* element)
return element->hasTagName(HTMLNames::contentTag);
}
-inline HTMLContentElement* toHTMLContentElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || isHTMLContentElement(node));
- return static_cast<HTMLContentElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(HTMLContentElement, hasTagName(HTMLNames::contentTag));
}
diff --git a/chromium/third_party/WebKit/Source/core/html/shadow/HTMLContentElement.idl b/chromium/third_party/WebKit/Source/core/html/shadow/HTMLContentElement.idl
index 77095c2ca29..ab593425152 100644
--- a/chromium/third_party/WebKit/Source/core/html/shadow/HTMLContentElement.idl
+++ b/chromium/third_party/WebKit/Source/core/html/shadow/HTMLContentElement.idl
@@ -26,7 +26,7 @@
[
] interface HTMLContentElement : HTMLElement {
- [Reflect] attribute DOMString select;
+ [Reflect, TreatNullAs=NullString] attribute DOMString select;
attribute boolean resetStyleInheritance;
NodeList getDistributedNodes();
};
diff --git a/chromium/third_party/WebKit/Source/core/html/shadow/HTMLShadowElement.cpp b/chromium/third_party/WebKit/Source/core/html/shadow/HTMLShadowElement.cpp
index a6cf5298a69..edfba07e3e1 100644
--- a/chromium/third_party/WebKit/Source/core/html/shadow/HTMLShadowElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/shadow/HTMLShadowElement.cpp
@@ -38,16 +38,15 @@ namespace WebCore {
class Document;
-inline HTMLShadowElement::HTMLShadowElement(const QualifiedName& tagName, Document& document)
- : InsertionPoint(tagName, document)
+inline HTMLShadowElement::HTMLShadowElement(Document& document)
+ : InsertionPoint(HTMLNames::shadowTag, document)
{
- ASSERT(hasTagName(HTMLNames::shadowTag));
ScriptWrappable::init(this);
}
-PassRefPtr<HTMLShadowElement> HTMLShadowElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<HTMLShadowElement> HTMLShadowElement::create(Document& document)
{
- return adoptRef(new HTMLShadowElement(tagName, document));
+ return adoptRef(new HTMLShadowElement(document));
}
HTMLShadowElement::~HTMLShadowElement()
@@ -63,7 +62,7 @@ ShadowRoot* HTMLShadowElement::olderShadowRoot()
document().updateDistributionForNodeIfNeeded(this);
ShadowRoot* older = containingRoot->olderShadowRoot();
- if (!older || !older->shouldExposeToBindings() || older->insertionPoint() != this)
+ if (!older || !older->shouldExposeToBindings() || older->shadowInsertionPointOfYoungerShadowRoot() != this)
return 0;
ASSERT(older->shouldExposeToBindings());
diff --git a/chromium/third_party/WebKit/Source/core/html/shadow/HTMLShadowElement.h b/chromium/third_party/WebKit/Source/core/html/shadow/HTMLShadowElement.h
index b9943bd3364..77741ecc588 100644
--- a/chromium/third_party/WebKit/Source/core/html/shadow/HTMLShadowElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/shadow/HTMLShadowElement.h
@@ -38,14 +38,14 @@ namespace WebCore {
class HTMLShadowElement FINAL : public InsertionPoint {
public:
- static PassRefPtr<HTMLShadowElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<HTMLShadowElement> create(Document&);
virtual ~HTMLShadowElement();
ShadowRoot* olderShadowRoot();
private:
- HTMLShadowElement(const QualifiedName&, Document&);
+ explicit HTMLShadowElement(Document&);
virtual InsertionNotificationRequest insertedInto(ContainerNode* insertionPoint) OVERRIDE;
};
@@ -55,22 +55,7 @@ inline bool isHTMLShadowElement(const Node* node)
return node->hasTagName(HTMLNames::shadowTag);
}
-inline HTMLShadowElement* toHTMLShadowElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || isHTMLShadowElement(node));
- return static_cast<HTMLShadowElement*>(node);
-}
-
-inline const HTMLShadowElement* toHTMLShadowElement(const Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || isHTMLShadowElement(node));
- return static_cast<const HTMLShadowElement*>(node);
-}
-
-inline bool isActiveShadowInsertionPoint(const Node* node)
-{
- return isHTMLShadowElement(node) && toHTMLShadowElement(node)->isActive();
-}
+DEFINE_NODE_TYPE_CASTS(HTMLShadowElement, hasTagName(HTMLNames::shadowTag));
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/html/shadow/HTMLShadowElement.idl b/chromium/third_party/WebKit/Source/core/html/shadow/HTMLShadowElement.idl
index 3b6351bec7d..faceace1458 100644
--- a/chromium/third_party/WebKit/Source/core/html/shadow/HTMLShadowElement.idl
+++ b/chromium/third_party/WebKit/Source/core/html/shadow/HTMLShadowElement.idl
@@ -31,4 +31,5 @@
interface HTMLShadowElement : HTMLElement {
attribute boolean resetStyleInheritance;
[DeprecateAs=HTMLShadowElementOlderShadowRoot] readonly attribute ShadowRoot olderShadowRoot;
+ [RuntimeEnabled=ShadowDOM] NodeList getDistributedNodes();
};
diff --git a/chromium/third_party/WebKit/Source/core/html/shadow/MediaControlElementTypes.cpp b/chromium/third_party/WebKit/Source/core/html/shadow/MediaControlElementTypes.cpp
index 6065a8f4721..dc7f986e04e 100644
--- a/chromium/third_party/WebKit/Source/core/html/shadow/MediaControlElementTypes.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/shadow/MediaControlElementTypes.cpp
@@ -35,7 +35,7 @@
#include "HTMLNames.h"
#include "bindings/v8/ExceptionStatePlaceholder.h"
#include "core/css/StylePropertySet.h"
-#include "core/dom/MouseEvent.h"
+#include "core/events/MouseEvent.h"
namespace WebCore {
@@ -103,7 +103,7 @@ void MediaControlElement::setDisplayType(MediaControlElementType displayType)
// ----------------------------
MediaControlDivElement::MediaControlDivElement(Document& document, MediaControlElementType displayType)
- : HTMLDivElement(divTag, document)
+ : HTMLDivElement(document)
, MediaControlElement(displayType, this)
{
}
@@ -111,7 +111,7 @@ MediaControlDivElement::MediaControlDivElement(Document& document, MediaControlE
// ----------------------------
MediaControlInputElement::MediaControlInputElement(Document& document, MediaControlElementType displayType)
- : HTMLInputElement(inputTag, document, 0, false)
+ : HTMLInputElement(document, 0, false)
, MediaControlElement(displayType, this)
{
}
@@ -143,7 +143,7 @@ MediaControlMuteButtonElement::MediaControlMuteButtonElement(Document& document,
void MediaControlMuteButtonElement::defaultEventHandler(Event* event)
{
- if (event->type() == eventNames().clickEvent) {
+ if (event->type() == EventTypeNames::click) {
mediaController()->setMuted(!mediaController()->muted());
event->setDefaultHandled();
}
@@ -175,12 +175,12 @@ void MediaControlVolumeSliderElement::defaultEventHandler(Event* event)
if (event->isMouseEvent() && toMouseEvent(event)->button())
return;
- if (!attached())
+ if (!inDocument() || !document().isActive())
return;
MediaControlInputElement::defaultEventHandler(event);
- if (event->type() == eventNames().mouseoverEvent || event->type() == eventNames().mouseoutEvent || event->type() == eventNames().mousemoveEvent)
+ if (event->type() == EventTypeNames::mouseover || event->type() == EventTypeNames::mouseout || event->type() == EventTypeNames::mousemove)
return;
double volume = value().toDouble();
@@ -192,7 +192,7 @@ void MediaControlVolumeSliderElement::defaultEventHandler(Event* event)
bool MediaControlVolumeSliderElement::willRespondToMouseMoveEvents()
{
- if (!attached())
+ if (!inDocument() || !document().isActive())
return false;
return MediaControlInputElement::willRespondToMouseMoveEvents();
@@ -200,7 +200,7 @@ bool MediaControlVolumeSliderElement::willRespondToMouseMoveEvents()
bool MediaControlVolumeSliderElement::willRespondToMouseClickEvents()
{
- if (!attached())
+ if (!inDocument() || !document().isActive())
return false;
return MediaControlInputElement::willRespondToMouseClickEvents();
diff --git a/chromium/third_party/WebKit/Source/core/html/shadow/MediaControlElementTypes.h b/chromium/third_party/WebKit/Source/core/html/shadow/MediaControlElementTypes.h
index a2304fd43a1..6293e6dac09 100644
--- a/chromium/third_party/WebKit/Source/core/html/shadow/MediaControlElementTypes.h
+++ b/chromium/third_party/WebKit/Source/core/html/shadow/MediaControlElementTypes.h
@@ -84,7 +84,7 @@ public:
virtual bool isShowing() const;
virtual MediaControlElementType displayType() { return m_displayType; }
- virtual const AtomicString& part() const = 0;
+ virtual const AtomicString& pseudo() const = 0;
virtual void setMediaController(MediaControllerInterface* controller) { m_mediaController = controller; }
virtual MediaControllerInterface* mediaController() const { return m_mediaController; }
diff --git a/chromium/third_party/WebKit/Source/core/html/shadow/MediaControlElements.cpp b/chromium/third_party/WebKit/Source/core/html/shadow/MediaControlElements.cpp
index cf339da95ce..9c3aee249b1 100644
--- a/chromium/third_party/WebKit/Source/core/html/shadow/MediaControlElements.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/shadow/MediaControlElements.cpp
@@ -30,19 +30,20 @@
#include "config.h"
#include "core/html/shadow/MediaControlElements.h"
+#include "RuntimeEnabledFeatures.h"
#include "bindings/v8/ExceptionStatePlaceholder.h"
#include "core/dom/DOMTokenList.h"
-#include "core/dom/EventNames.h"
#include "core/dom/FullscreenElementStack.h"
-#include "core/dom/MouseEvent.h"
+#include "core/dom/shadow/ShadowRoot.h"
+#include "core/events/MouseEvent.h"
+#include "core/events/ThreadLocalEventNames.h"
#include "core/html/HTMLVideoElement.h"
#include "core/html/shadow/MediaControls.h"
#include "core/html/track/TextTrack.h"
-#include "core/html/track/TextTrackRegionList.h"
+#include "core/html/track/vtt/VTTRegionList.h"
#include "core/page/EventHandler.h"
-#include "core/page/Frame.h"
-#include "core/page/Page.h"
-#include "core/page/Settings.h"
+#include "core/frame/Frame.h"
+#include "core/frame/Settings.h"
#include "core/rendering/RenderMediaControlElements.h"
#include "core/rendering/RenderSlider.h"
#include "core/rendering/RenderTheme.h"
@@ -55,7 +56,8 @@ using namespace HTMLNames;
static const AtomicString& getMediaControlCurrentTimeDisplayElementShadowPseudoId();
static const AtomicString& getMediaControlTimeRemainingDisplayElementShadowPseudoId();
-static const char* textTracksOffAttrValue = "-1"; // This must match HTMLMediaElement::textTracksOffIndex()
+static const double fadeInDuration = 0.1;
+static const double fadeOutDuration = 0.3;
MediaControlPanelElement::MediaControlPanelElement(Document& document)
: MediaControlDivElement(document, MediaControlsPanel)
@@ -72,7 +74,7 @@ PassRefPtr<MediaControlPanelElement> MediaControlPanelElement::create(Document&
return adoptRef(new MediaControlPanelElement(document));
}
-const AtomicString& MediaControlPanelElement::part() const
+const AtomicString& MediaControlPanelElement::pseudo() const
{
DEFINE_STATIC_LOCAL(AtomicString, id, ("-webkit-media-controls-panel", AtomicString::ConstructFromLiteral));
return id;
@@ -96,7 +98,7 @@ void MediaControlPanelElement::startDrag(const LayoutPoint& eventLocation)
m_lastDragEventLocation = eventLocation;
- frame->eventHandler()->setCapturingMouseEventsNode(this);
+ frame->eventHandler().setCapturingMouseEventsNode(this);
m_isBeingDragged = true;
}
@@ -123,7 +125,7 @@ void MediaControlPanelElement::endDrag()
if (!frame)
return;
- frame->eventHandler()->setCapturingMouseEventsNode(0);
+ frame->eventHandler().setCapturingMouseEventsNode(0);
}
void MediaControlPanelElement::startTimer()
@@ -133,8 +135,8 @@ void MediaControlPanelElement::startTimer()
// The timer is required to set the property display:'none' on the panel,
// such that captions are correctly displayed at the bottom of the video
// at the end of the fadeout transition.
- double duration = RenderTheme::theme().mediaControlsFadeOutDuration();
- m_transitionTimer.startOneShot(duration);
+ // FIXME: Racing a transition with a setTimeout like this is wrong.
+ m_transitionTimer.startOneShot(fadeOutDuration);
}
void MediaControlPanelElement::stopTimer()
@@ -184,10 +186,8 @@ void MediaControlPanelElement::makeOpaque()
if (m_opaque)
return;
- double duration = RenderTheme::theme().mediaControlsFadeInDuration();
-
setInlineStyleProperty(CSSPropertyTransitionProperty, CSSPropertyOpacity);
- setInlineStyleProperty(CSSPropertyTransitionDuration, duration, CSSPrimitiveValue::CSS_S);
+ setInlineStyleProperty(CSSPropertyTransitionDuration, fadeInDuration, CSSPrimitiveValue::CSS_S);
setInlineStyleProperty(CSSPropertyOpacity, 1.0, CSSPrimitiveValue::CSS_NUMBER);
m_opaque = true;
@@ -201,10 +201,8 @@ void MediaControlPanelElement::makeTransparent()
if (!m_opaque)
return;
- double duration = RenderTheme::theme().mediaControlsFadeOutDuration();
-
setInlineStyleProperty(CSSPropertyTransitionProperty, CSSPropertyOpacity);
- setInlineStyleProperty(CSSPropertyTransitionDuration, duration, CSSPrimitiveValue::CSS_S);
+ setInlineStyleProperty(CSSPropertyTransitionDuration, fadeOutDuration, CSSPrimitiveValue::CSS_S);
setInlineStyleProperty(CSSPropertyOpacity, 0.0, CSSPrimitiveValue::CSS_NUMBER);
m_opaque = false;
@@ -217,12 +215,12 @@ void MediaControlPanelElement::defaultEventHandler(Event* event)
if (event->isMouseEvent()) {
LayoutPoint location = toMouseEvent(event)->absoluteLocation();
- if (event->type() == eventNames().mousedownEvent && event->target() == this) {
+ if (event->type() == EventTypeNames::mousedown && event->target() == this) {
startDrag(location);
event->setDefaultHandled();
- } else if (event->type() == eventNames().mousemoveEvent && m_isBeingDragged)
+ } else if (event->type() == EventTypeNames::mousemove && m_isBeingDragged)
continueDrag(location);
- else if (event->type() == eventNames().mouseupEvent && m_isBeingDragged) {
+ else if (event->type() == EventTypeNames::mouseup && m_isBeingDragged) {
continueDrag(location);
endDrag();
event->setDefaultHandled();
@@ -259,7 +257,7 @@ PassRefPtr<MediaControlPanelEnclosureElement> MediaControlPanelEnclosureElement:
return adoptRef(new MediaControlPanelEnclosureElement(document));
}
-const AtomicString& MediaControlPanelEnclosureElement::part() const
+const AtomicString& MediaControlPanelEnclosureElement::pseudo() const
{
DEFINE_STATIC_LOCAL(AtomicString, id, ("-webkit-media-controls-enclosure", AtomicString::ConstructFromLiteral));
return id;
@@ -278,7 +276,7 @@ PassRefPtr<MediaControlOverlayEnclosureElement> MediaControlOverlayEnclosureElem
return adoptRef(new MediaControlOverlayEnclosureElement(document));
}
-const AtomicString& MediaControlOverlayEnclosureElement::part() const
+const AtomicString& MediaControlOverlayEnclosureElement::pseudo() const
{
DEFINE_STATIC_LOCAL(AtomicString, id, ("-webkit-media-controls-overlay-enclosure", AtomicString::ConstructFromLiteral));
return id;
@@ -304,13 +302,13 @@ PassRefPtr<MediaControlPanelMuteButtonElement> MediaControlPanelMuteButtonElemen
void MediaControlPanelMuteButtonElement::defaultEventHandler(Event* event)
{
- if (event->type() == eventNames().mouseoverEvent)
+ if (event->type() == EventTypeNames::mouseover)
m_controls->showVolumeSlider();
MediaControlMuteButtonElement::defaultEventHandler(event);
}
-const AtomicString& MediaControlPanelMuteButtonElement::part() const
+const AtomicString& MediaControlPanelMuteButtonElement::pseudo() const
{
DEFINE_STATIC_LOCAL(AtomicString, id, ("-webkit-media-controls-mute-button", AtomicString::ConstructFromLiteral));
return id;
@@ -331,7 +329,7 @@ PassRefPtr<MediaControlVolumeSliderMuteButtonElement> MediaControlVolumeSliderMu
return button.release();
}
-const AtomicString& MediaControlVolumeSliderMuteButtonElement::part() const
+const AtomicString& MediaControlVolumeSliderMuteButtonElement::pseudo() const
{
DEFINE_STATIC_LOCAL(AtomicString, id, ("-webkit-media-controls-volume-slider-mute-button", AtomicString::ConstructFromLiteral));
return id;
@@ -354,7 +352,7 @@ PassRefPtr<MediaControlPlayButtonElement> MediaControlPlayButtonElement::create(
void MediaControlPlayButtonElement::defaultEventHandler(Event* event)
{
- if (event->type() == eventNames().clickEvent) {
+ if (event->type() == EventTypeNames::click) {
if (mediaController()->canPlay())
mediaController()->play();
else
@@ -370,7 +368,7 @@ void MediaControlPlayButtonElement::updateDisplayType()
setDisplayType(mediaController()->canPlay() ? MediaPlayButton : MediaPauseButton);
}
-const AtomicString& MediaControlPlayButtonElement::part() const
+const AtomicString& MediaControlPlayButtonElement::pseudo() const
{
DEFINE_STATIC_LOCAL(AtomicString, id, ("-webkit-media-controls-play-button", AtomicString::ConstructFromLiteral));
return id;
@@ -393,7 +391,7 @@ PassRefPtr<MediaControlOverlayPlayButtonElement> MediaControlOverlayPlayButtonEl
void MediaControlOverlayPlayButtonElement::defaultEventHandler(Event* event)
{
- if (event->type() == eventNames().clickEvent && mediaController()->canPlay()) {
+ if (event->type() == EventTypeNames::click && mediaController()->canPlay()) {
mediaController()->play();
updateDisplayType();
event->setDefaultHandled();
@@ -409,7 +407,7 @@ void MediaControlOverlayPlayButtonElement::updateDisplayType()
hide();
}
-const AtomicString& MediaControlOverlayPlayButtonElement::part() const
+const AtomicString& MediaControlOverlayPlayButtonElement::pseudo() const
{
DEFINE_STATIC_LOCAL(AtomicString, id, ("-webkit-media-controls-overlay-play-button", AtomicString::ConstructFromLiteral));
return id;
@@ -418,10 +416,9 @@ const AtomicString& MediaControlOverlayPlayButtonElement::part() const
// ----------------------------
-MediaControlToggleClosedCaptionsButtonElement::MediaControlToggleClosedCaptionsButtonElement(Document& document, MediaControls* controls)
+MediaControlToggleClosedCaptionsButtonElement::MediaControlToggleClosedCaptionsButtonElement(Document& document, MediaControls*)
: MediaControlInputElement(document, MediaShowClosedCaptionsButton)
{
- UNUSED_PARAM(controls);
}
PassRefPtr<MediaControlToggleClosedCaptionsButtonElement> MediaControlToggleClosedCaptionsButtonElement::create(Document& document, MediaControls* controls)
@@ -444,7 +441,7 @@ void MediaControlToggleClosedCaptionsButtonElement::updateDisplayType()
void MediaControlToggleClosedCaptionsButtonElement::defaultEventHandler(Event* event)
{
- if (event->type() == eventNames().clickEvent) {
+ if (event->type() == EventTypeNames::click) {
mediaController()->setClosedCaptionsVisible(!mediaController()->closedCaptionsVisible());
setChecked(mediaController()->closedCaptionsVisible());
updateDisplayType();
@@ -454,7 +451,7 @@ void MediaControlToggleClosedCaptionsButtonElement::defaultEventHandler(Event* e
HTMLInputElement::defaultEventHandler(event);
}
-const AtomicString& MediaControlToggleClosedCaptionsButtonElement::part() const
+const AtomicString& MediaControlToggleClosedCaptionsButtonElement::pseudo() const
{
DEFINE_STATIC_LOCAL(AtomicString, id, ("-webkit-media-controls-toggle-closed-captions-button", AtomicString::ConstructFromLiteral));
return id;
@@ -475,7 +472,7 @@ PassRefPtr<MediaControlTimelineElement> MediaControlTimelineElement::create(Docu
RefPtr<MediaControlTimelineElement> timeline = adoptRef(new MediaControlTimelineElement(document, controls));
timeline->ensureUserAgentShadowRoot();
timeline->setType("range");
- timeline->setAttribute(precisionAttr, "float");
+ timeline->setAttribute(stepAttr, "any");
return timeline.release();
}
@@ -485,22 +482,22 @@ void MediaControlTimelineElement::defaultEventHandler(Event* event)
if (event->isMouseEvent() && toMouseEvent(event)->button())
return;
- if (!attached())
+ if (!inDocument() || !document().isActive())
return;
- if (event->type() == eventNames().mousedownEvent)
+ if (event->type() == EventTypeNames::mousedown)
mediaController()->beginScrubbing();
- if (event->type() == eventNames().mouseupEvent)
+ if (event->type() == EventTypeNames::mouseup)
mediaController()->endScrubbing();
MediaControlInputElement::defaultEventHandler(event);
- if (event->type() == eventNames().mouseoverEvent || event->type() == eventNames().mouseoutEvent || event->type() == eventNames().mousemoveEvent)
+ if (event->type() == EventTypeNames::mouseover || event->type() == EventTypeNames::mouseout || event->type() == EventTypeNames::mousemove)
return;
double time = value().toDouble();
- if (event->type() == eventNames().inputEvent && time != mediaController()->currentTime())
+ if (event->type() == EventTypeNames::input && time != mediaController()->currentTime())
mediaController()->setCurrentTime(time, IGNORE_EXCEPTION);
RenderSlider* slider = toRenderSlider(renderer());
@@ -510,10 +507,7 @@ void MediaControlTimelineElement::defaultEventHandler(Event* event)
bool MediaControlTimelineElement::willRespondToMouseClickEvents()
{
- if (!attached())
- return false;
-
- return true;
+ return inDocument() && document().isActive();
}
void MediaControlTimelineElement::setPosition(double currentTime)
@@ -523,11 +517,11 @@ void MediaControlTimelineElement::setPosition(double currentTime)
void MediaControlTimelineElement::setDuration(double duration)
{
- setAttribute(maxAttr, String::number(std::isfinite(duration) ? duration : 0));
+ setFloatingPointAttribute(maxAttr, std::isfinite(duration) ? duration : 0);
}
-const AtomicString& MediaControlTimelineElement::part() const
+const AtomicString& MediaControlTimelineElement::pseudo() const
{
DEFINE_STATIC_LOCAL(AtomicString, id, ("-webkit-media-controls-timeline", AtomicString::ConstructFromLiteral));
return id;
@@ -545,12 +539,12 @@ PassRefPtr<MediaControlPanelVolumeSliderElement> MediaControlPanelVolumeSliderEl
RefPtr<MediaControlPanelVolumeSliderElement> slider = adoptRef(new MediaControlPanelVolumeSliderElement(document));
slider->ensureUserAgentShadowRoot();
slider->setType("range");
- slider->setAttribute(precisionAttr, "float");
+ slider->setAttribute(stepAttr, "any");
slider->setAttribute(maxAttr, "1");
return slider.release();
}
-const AtomicString& MediaControlPanelVolumeSliderElement::part() const
+const AtomicString& MediaControlPanelVolumeSliderElement::pseudo() const
{
DEFINE_STATIC_LOCAL(AtomicString, id, ("-webkit-media-controls-volume-slider", AtomicString::ConstructFromLiteral));
return id;
@@ -574,7 +568,7 @@ PassRefPtr<MediaControlFullscreenButtonElement> MediaControlFullscreenButtonElem
void MediaControlFullscreenButtonElement::defaultEventHandler(Event* event)
{
- if (event->type() == eventNames().clickEvent) {
+ if (event->type() == EventTypeNames::click) {
// Only use the new full screen API if the fullScreenEnabled setting has
// been explicitly enabled. Otherwise, use the old fullscreen API. This
// allows apps which embed a WebView to retain the existing full screen
@@ -592,7 +586,7 @@ void MediaControlFullscreenButtonElement::defaultEventHandler(Event* event)
HTMLInputElement::defaultEventHandler(event);
}
-const AtomicString& MediaControlFullscreenButtonElement::part() const
+const AtomicString& MediaControlFullscreenButtonElement::pseudo() const
{
DEFINE_STATIC_LOCAL(AtomicString, id, ("-webkit-media-controls-fullscreen-button", AtomicString::ConstructFromLiteral));
return id;
@@ -621,7 +615,7 @@ static const AtomicString& getMediaControlTimeRemainingDisplayElementShadowPseud
return id;
}
-const AtomicString& MediaControlTimeRemainingDisplayElement::part() const
+const AtomicString& MediaControlTimeRemainingDisplayElement::pseudo() const
{
return getMediaControlTimeRemainingDisplayElementShadowPseudoId();
}
@@ -644,7 +638,7 @@ static const AtomicString& getMediaControlCurrentTimeDisplayElementShadowPseudoI
return id;
}
-const AtomicString& MediaControlCurrentTimeDisplayElement::part() const
+const AtomicString& MediaControlCurrentTimeDisplayElement::pseudo() const
{
return getMediaControlCurrentTimeDisplayElementShadowPseudoId();
}
@@ -675,7 +669,7 @@ const AtomicString& MediaControlTextTrackContainerElement::textTrackContainerEle
return id;
}
-const AtomicString& MediaControlTextTrackContainerElement::part() const
+const AtomicString& MediaControlTextTrackContainerElement::pseudo() const
{
return textTrackContainerElementShadowPseudoId();
}
@@ -739,33 +733,7 @@ void MediaControlTextTrackContainerElement::updateDisplay()
if (!cue->track() || !cue->track()->isRendered() || !cue->isActive())
continue;
- RefPtr<TextTrackCueBox> displayBox = cue->getDisplayTree(m_videoDisplaySize.size());
-
-#if ENABLE(WEBVTT_REGIONS)
- String regionId = cue->regionId();
- TextTrackRegion* region = cue->track()->regions()->getRegionById(regionId);
- if (!region) {
- // If cue has an empty text track cue region identifier or there is no
- // WebVTT region whose region identifier is identical to cue's text
- // track cue region identifier, run the following substeps:
-#endif
- if (displayBox->hasChildNodes() && !contains(displayBox.get())) {
- // Note: the display tree of a cue is removed when the active flag of the cue is unset.
- appendChild(displayBox);
- }
-#if ENABLE(WEBVTT_REGIONS)
- } else {
- // Let region be the WebVTT region whose region identifier
- // matches the text track cue region identifier of cue.
- RefPtr<HTMLDivElement> regionNode = region->getDisplayTree();
-
- // Append the region to the viewport, if it was not already.
- if (!contains(regionNode.get()))
- appendChild(region->getDisplayTree());
-
- region->appendTextTrackCueBox(displayBox);
- }
-#endif
+ cue->updateDisplay(m_videoDisplaySize.size(), *this);
}
// 11. Return output.
@@ -781,7 +749,7 @@ void MediaControlTextTrackContainerElement::updateSizes(bool forceUpdate)
if (!mediaElement)
return;
- if (!document().page())
+ if (!document().isActive())
return;
IntRect videoBox;
@@ -801,12 +769,6 @@ void MediaControlTextTrackContainerElement::updateSizes(bool forceUpdate)
m_fontSize = fontSize;
setInlineStyleProperty(CSSPropertyFontSize, fontSize, CSSPrimitiveValue::CSS_PX);
}
-
- CueList activeCues = mediaElement->currentlyActiveCues();
- for (size_t i = 0; i < activeCues.size(); ++i) {
- TextTrackCue* cue = activeCues[i].data();
- cue->videoSizeDidChange(m_videoDisplaySize.size());
- }
}
// ----------------------------
diff --git a/chromium/third_party/WebKit/Source/core/html/shadow/MediaControlElements.h b/chromium/third_party/WebKit/Source/core/html/shadow/MediaControlElements.h
index e53002dcb97..3d631dbb9b9 100644
--- a/chromium/third_party/WebKit/Source/core/html/shadow/MediaControlElements.h
+++ b/chromium/third_party/WebKit/Source/core/html/shadow/MediaControlElements.h
@@ -53,7 +53,7 @@ public:
private:
explicit MediaControlPanelElement(Document&);
- virtual const AtomicString& part() const OVERRIDE;
+ virtual const AtomicString& pseudo() const OVERRIDE;
virtual void defaultEventHandler(Event*) OVERRIDE;
void startDrag(const LayoutPoint& eventLocation);
@@ -84,7 +84,7 @@ public:
private:
explicit MediaControlPanelEnclosureElement(Document&);
- virtual const AtomicString& part() const OVERRIDE;
+ virtual const AtomicString& pseudo() const OVERRIDE;
};
// ----------------------------
@@ -95,7 +95,7 @@ public:
private:
explicit MediaControlOverlayEnclosureElement(Document&);
- virtual const AtomicString& part() const OVERRIDE;
+ virtual const AtomicString& pseudo() const OVERRIDE;
};
// ----------------------------
@@ -109,7 +109,7 @@ public:
private:
explicit MediaControlPanelMuteButtonElement(Document&, MediaControls*);
- virtual const AtomicString& part() const OVERRIDE;
+ virtual const AtomicString& pseudo() const OVERRIDE;
virtual void defaultEventHandler(Event*) OVERRIDE;
MediaControls* m_controls;
@@ -123,7 +123,7 @@ public:
private:
explicit MediaControlVolumeSliderMuteButtonElement(Document&);
- virtual const AtomicString& part() const OVERRIDE;
+ virtual const AtomicString& pseudo() const OVERRIDE;
};
@@ -139,7 +139,7 @@ public:
private:
explicit MediaControlPlayButtonElement(Document&);
- virtual const AtomicString& part() const OVERRIDE;
+ virtual const AtomicString& pseudo() const OVERRIDE;
virtual void defaultEventHandler(Event*) OVERRIDE;
};
@@ -154,7 +154,7 @@ public:
private:
explicit MediaControlOverlayPlayButtonElement(Document&);
- virtual const AtomicString& part() const OVERRIDE;
+ virtual const AtomicString& pseudo() const OVERRIDE;
virtual void defaultEventHandler(Event*) OVERRIDE;
};
@@ -171,7 +171,7 @@ public:
private:
explicit MediaControlToggleClosedCaptionsButtonElement(Document&, MediaControls*);
- virtual const AtomicString& part() const OVERRIDE;
+ virtual const AtomicString& pseudo() const OVERRIDE;
virtual void defaultEventHandler(Event*) OVERRIDE;
};
@@ -189,7 +189,7 @@ public:
private:
explicit MediaControlTimelineElement(Document&, MediaControls*);
- virtual const AtomicString& part() const OVERRIDE;
+ virtual const AtomicString& pseudo() const OVERRIDE;
virtual void defaultEventHandler(Event*) OVERRIDE;
MediaControls* m_controls;
@@ -208,7 +208,7 @@ public:
private:
explicit MediaControlFullscreenButtonElement(Document&);
- virtual const AtomicString& part() const OVERRIDE;
+ virtual const AtomicString& pseudo() const OVERRIDE;
virtual void defaultEventHandler(Event*) OVERRIDE;
};
@@ -220,7 +220,7 @@ public:
private:
explicit MediaControlPanelVolumeSliderElement(Document&);
- virtual const AtomicString& part() const OVERRIDE;
+ virtual const AtomicString& pseudo() const OVERRIDE;
};
// ----------------------------
@@ -231,7 +231,7 @@ public:
private:
explicit MediaControlTimeRemainingDisplayElement(Document&);
- virtual const AtomicString& part() const OVERRIDE;
+ virtual const AtomicString& pseudo() const OVERRIDE;
};
// ----------------------------
@@ -242,7 +242,7 @@ public:
private:
explicit MediaControlCurrentTimeDisplayElement(Document&);
- virtual const AtomicString& part() const OVERRIDE;
+ virtual const AtomicString& pseudo() const OVERRIDE;
};
// ----------------------------
@@ -257,7 +257,7 @@ public:
private:
explicit MediaControlTextTrackContainerElement(Document&);
- virtual const AtomicString& part() const OVERRIDE;
+ virtual const AtomicString& pseudo() const OVERRIDE;
virtual RenderObject* createRenderer(RenderStyle*);
diff --git a/chromium/third_party/WebKit/Source/core/html/shadow/MediaControls.cpp b/chromium/third_party/WebKit/Source/core/html/shadow/MediaControls.cpp
index e86861edafa..0e2fa811fba 100644
--- a/chromium/third_party/WebKit/Source/core/html/shadow/MediaControls.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/shadow/MediaControls.cpp
@@ -34,7 +34,7 @@ namespace WebCore {
static const double timeWithoutMouseMovementBeforeHidingFullscreenControls = 3;
MediaControls::MediaControls(Document& document)
- : HTMLDivElement(HTMLNames::divTag, document)
+ : HTMLDivElement(document)
, m_mediaController(0)
, m_panel(0)
, m_textDisplayContainer(0)
@@ -268,7 +268,7 @@ void MediaControls::defaultEventHandler(Event* event)
{
HTMLDivElement::defaultEventHandler(event);
- if (event->type() == eventNames().mouseoverEvent) {
+ if (event->type() == EventTypeNames::mouseover) {
if (!containsRelatedTarget(event)) {
m_isMouseOverControls = true;
if (!m_mediaController->canPlay()) {
@@ -280,7 +280,7 @@ void MediaControls::defaultEventHandler(Event* event)
return;
}
- if (event->type() == eventNames().mouseoutEvent) {
+ if (event->type() == EventTypeNames::mouseout) {
if (!containsRelatedTarget(event)) {
m_isMouseOverControls = false;
stopHideFullscreenControlsTimer();
@@ -288,7 +288,7 @@ void MediaControls::defaultEventHandler(Event* event)
return;
}
- if (event->type() == eventNames().mousemoveEvent) {
+ if (event->type() == EventTypeNames::mousemove) {
if (m_isFullscreen) {
// When we get a mouse move in fullscreen mode, show the media controls, and start a timer
// that will hide the media controls after a 3 seconds without a mouse move.
@@ -331,7 +331,7 @@ void MediaControls::stopHideFullscreenControlsTimer()
m_hideFullscreenControlsTimer.stop();
}
-const AtomicString& MediaControls::part() const
+const AtomicString& MediaControls::pseudo() const
{
DEFINE_STATIC_LOCAL(AtomicString, id, ("-webkit-media-controls"));
return id;
diff --git a/chromium/third_party/WebKit/Source/core/html/shadow/MediaControls.h b/chromium/third_party/WebKit/Source/core/html/shadow/MediaControls.h
index 4342ac110d5..ea87254a8e2 100644
--- a/chromium/third_party/WebKit/Source/core/html/shadow/MediaControls.h
+++ b/chromium/third_party/WebKit/Source/core/html/shadow/MediaControls.h
@@ -27,17 +27,15 @@
#ifndef MediaControls_h
#define MediaControls_h
-#include "core/dom/MouseEvent.h"
+#include "core/events/MouseEvent.h"
#include "core/html/HTMLDivElement.h"
#include "core/html/shadow/MediaControlElements.h"
-#include "core/page/Page.h"
#include "core/rendering/RenderTheme.h"
namespace WebCore {
class Document;
class Event;
-class Page;
class MediaPlayer;
class RenderBox;
@@ -125,17 +123,10 @@ protected:
private:
virtual bool isMediaControls() const { return true; }
- virtual const AtomicString& part() const;
+ virtual const AtomicString& pseudo() const;
};
-inline MediaControls* toMediaControls(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->isMediaControls());
- return static_cast<MediaControls*>(node);
-}
-
-// This will catch anyone doing an unneccessary cast.
-void toMediaControls(const MediaControls*);
+DEFINE_NODE_TYPE_CASTS(MediaControls, isMediaControls());
}
diff --git a/chromium/third_party/WebKit/Source/core/html/shadow/MediaControlsChromium.cpp b/chromium/third_party/WebKit/Source/core/html/shadow/MediaControlsChromium.cpp
index d4fadf70193..d1d4ccbfd40 100644
--- a/chromium/third_party/WebKit/Source/core/html/shadow/MediaControlsChromium.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/shadow/MediaControlsChromium.cpp
@@ -69,68 +69,68 @@ bool MediaControlsChromium::initializeControls(Document& document)
RefPtr<MediaControlPanelElement> panel = MediaControlPanelElement::create(document);
- TrackExceptionState es;
+ TrackExceptionState exceptionState;
RefPtr<MediaControlPlayButtonElement> playButton = MediaControlPlayButtonElement::create(document);
m_playButton = playButton.get();
- panel->appendChild(playButton.release(), es);
- if (es.hadException())
+ panel->appendChild(playButton.release(), exceptionState);
+ if (exceptionState.hadException())
return false;
RefPtr<MediaControlTimelineElement> timeline = MediaControlTimelineElement::create(document, this);
m_timeline = timeline.get();
- panel->appendChild(timeline.release(), es);
- if (es.hadException())
+ panel->appendChild(timeline.release(), exceptionState);
+ if (exceptionState.hadException())
return false;
RefPtr<MediaControlCurrentTimeDisplayElement> currentTimeDisplay = MediaControlCurrentTimeDisplayElement::create(document);
m_currentTimeDisplay = currentTimeDisplay.get();
m_currentTimeDisplay->hide();
- panel->appendChild(currentTimeDisplay.release(), es);
- if (es.hadException())
+ panel->appendChild(currentTimeDisplay.release(), exceptionState);
+ if (exceptionState.hadException())
return false;
RefPtr<MediaControlTimeRemainingDisplayElement> durationDisplay = MediaControlTimeRemainingDisplayElement::create(document);
m_durationDisplay = durationDisplay.get();
- panel->appendChild(durationDisplay.release(), es);
- if (es.hadException())
+ panel->appendChild(durationDisplay.release(), exceptionState);
+ if (exceptionState.hadException())
return false;
RefPtr<MediaControlPanelMuteButtonElement> panelMuteButton = MediaControlPanelMuteButtonElement::create(document, this);
m_panelMuteButton = panelMuteButton.get();
- panel->appendChild(panelMuteButton.release(), es);
- if (es.hadException())
+ panel->appendChild(panelMuteButton.release(), exceptionState);
+ if (exceptionState.hadException())
return false;
RefPtr<MediaControlPanelVolumeSliderElement> slider = MediaControlPanelVolumeSliderElement::create(document);
m_volumeSlider = slider.get();
m_volumeSlider->setClearMutedOnUserInteraction(true);
- panel->appendChild(slider.release(), es);
- if (es.hadException())
+ panel->appendChild(slider.release(), exceptionState);
+ if (exceptionState.hadException())
return false;
if (RenderTheme::theme().supportsClosedCaptioning()) {
RefPtr<MediaControlToggleClosedCaptionsButtonElement> toggleClosedCaptionsButton = MediaControlToggleClosedCaptionsButtonElement::create(document, this);
m_toggleClosedCaptionsButton = toggleClosedCaptionsButton.get();
- panel->appendChild(toggleClosedCaptionsButton.release(), es);
- if (es.hadException())
+ panel->appendChild(toggleClosedCaptionsButton.release(), exceptionState);
+ if (exceptionState.hadException())
return false;
}
RefPtr<MediaControlFullscreenButtonElement> fullscreenButton = MediaControlFullscreenButtonElement::create(document);
m_fullScreenButton = fullscreenButton.get();
- panel->appendChild(fullscreenButton.release(), es);
- if (es.hadException())
+ panel->appendChild(fullscreenButton.release(), exceptionState);
+ if (exceptionState.hadException())
return false;
m_panel = panel.get();
- enclosure->appendChild(panel.release(), es);
- if (es.hadException())
+ enclosure->appendChild(panel.release(), exceptionState);
+ if (exceptionState.hadException())
return false;
m_enclosure = enclosure.get();
- appendChild(enclosure.release(), es);
- if (es.hadException())
+ appendChild(enclosure.release(), exceptionState);
+ if (exceptionState.hadException())
return false;
return true;
diff --git a/chromium/third_party/WebKit/Source/core/html/shadow/MediaControlsChromiumAndroid.cpp b/chromium/third_party/WebKit/Source/core/html/shadow/MediaControlsChromiumAndroid.cpp
index 1585d86f1ae..f81c9309b37 100644
--- a/chromium/third_party/WebKit/Source/core/html/shadow/MediaControlsChromiumAndroid.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/shadow/MediaControlsChromiumAndroid.cpp
@@ -50,18 +50,18 @@ PassRefPtr<MediaControlsChromiumAndroid> MediaControlsChromiumAndroid::createCon
RefPtr<MediaControlsChromiumAndroid> controls = adoptRef(new MediaControlsChromiumAndroid(document));
- TrackExceptionState es;
+ TrackExceptionState exceptionState;
RefPtr<MediaControlOverlayEnclosureElement> overlayEnclosure = MediaControlOverlayEnclosureElement::create(document);
RefPtr<MediaControlOverlayPlayButtonElement> overlayPlayButton = MediaControlOverlayPlayButtonElement::create(document);
controls->m_overlayPlayButton = overlayPlayButton.get();
- overlayEnclosure->appendChild(overlayPlayButton.release(), es);
- if (es.hadException())
+ overlayEnclosure->appendChild(overlayPlayButton.release(), exceptionState);
+ if (exceptionState.hadException())
return 0;
controls->m_overlayEnclosure = overlayEnclosure.get();
- controls->appendChild(overlayEnclosure.release(), es);
- if (es.hadException())
+ controls->appendChild(overlayEnclosure.release(), exceptionState);
+ if (exceptionState.hadException())
return 0;
if (controls->initializeControls(document))
diff --git a/chromium/third_party/WebKit/Source/core/html/shadow/MeterShadowElement.cpp b/chromium/third_party/WebKit/Source/core/html/shadow/MeterShadowElement.cpp
index 0462983f6b7..a39c29cdb71 100644
--- a/chromium/third_party/WebKit/Source/core/html/shadow/MeterShadowElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/shadow/MeterShadowElement.cpp
@@ -43,7 +43,7 @@ namespace WebCore {
using namespace HTMLNames;
inline MeterShadowElement::MeterShadowElement(Document& document)
- : HTMLDivElement(HTMLNames::divTag, document)
+ : HTMLDivElement(document)
{
}
@@ -66,7 +66,7 @@ inline MeterInnerElement::MeterInnerElement(Document& document)
PassRefPtr<MeterInnerElement> MeterInnerElement::create(Document& document)
{
RefPtr<MeterInnerElement> element = adoptRef(new MeterInnerElement(document));
- element->setPart(AtomicString("-webkit-meter-inner-element", AtomicString::ConstructFromLiteral));
+ element->setPseudo(AtomicString("-webkit-meter-inner-element", AtomicString::ConstructFromLiteral));
return element.release();
}
@@ -92,7 +92,7 @@ inline MeterBarElement::MeterBarElement(Document& document)
PassRefPtr<MeterBarElement> MeterBarElement::create(Document& document)
{
RefPtr<MeterBarElement> element = adoptRef(new MeterBarElement(document));
- element->setPart(AtomicString("-webkit-meter-bar", AtomicString::ConstructFromLiteral));
+ element->setPseudo(AtomicString("-webkit-meter-bar", AtomicString::ConstructFromLiteral));
return element.release();
}
diff --git a/chromium/third_party/WebKit/Source/core/html/shadow/MeterShadowElement.h b/chromium/third_party/WebKit/Source/core/html/shadow/MeterShadowElement.h
index 30bbd9c451c..c15bfdcbcb7 100644
--- a/chromium/third_party/WebKit/Source/core/html/shadow/MeterShadowElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/shadow/MeterShadowElement.h
@@ -70,7 +70,7 @@ class MeterValueElement FINAL : public MeterShadowElement {
public:
static PassRefPtr<MeterValueElement> create(Document&);
void setWidthPercentage(double);
- void updatePseudo() { setPart(valuePseudoId()); }
+ void updatePseudo() { setPseudo(valuePseudoId()); }
private:
MeterValueElement(Document&);
diff --git a/chromium/third_party/WebKit/Source/core/html/shadow/PasswordGeneratorButtonElement.cpp b/chromium/third_party/WebKit/Source/core/html/shadow/PasswordGeneratorButtonElement.cpp
index 33d442835d5..238c3f41aee 100644
--- a/chromium/third_party/WebKit/Source/core/html/shadow/PasswordGeneratorButtonElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/shadow/PasswordGeneratorButtonElement.cpp
@@ -31,73 +31,33 @@
#include "config.h"
#include "core/html/shadow/PasswordGeneratorButtonElement.h"
-#include "CSSPropertyNames.h"
-#include "CSSValueKeywords.h"
-#include "core/dom/Event.h"
+#include "core/events/Event.h"
#include "core/dom/NodeRenderStyle.h"
-#include "core/dom/shadow/ElementShadow.h"
-#include "core/dom/shadow/ShadowRoot.h"
#include "core/fetch/ImageResource.h"
#include "core/html/HTMLInputElement.h"
-#include "core/html/shadow/HTMLShadowElement.h"
+#include "core/html/shadow/ShadowElementNames.h"
#include "core/page/Chrome.h"
#include "core/page/ChromeClient.h"
#include "core/page/Page.h"
-#include "core/platform/graphics/Image.h"
#include "core/rendering/RenderImage.h"
+#include "platform/graphics/Image.h"
namespace WebCore {
using namespace HTMLNames;
-// FIXME: This class is only used in Chromium and has no layout tests.
-
PasswordGeneratorButtonElement::PasswordGeneratorButtonElement(Document& document)
- : HTMLDivElement(HTMLNames::divTag, document)
+ : HTMLDivElement(document)
, m_isInHoverState(false)
{
setHasCustomStyleCallbacks();
}
-static void getDecorationRootAndDecoratedRoot(HTMLInputElement* input, ShadowRoot*& decorationRoot, ShadowRoot*& decoratedRoot)
-{
- ShadowRoot* existingRoot = input->youngestShadowRoot();
- ShadowRoot* newRoot = 0;
- while (existingRoot->childNodeCount() == 1 && existingRoot->firstChild()->hasTagName(shadowTag)) {
- newRoot = existingRoot;
- existingRoot = existingRoot->olderShadowRoot();
- ASSERT(existingRoot);
- }
- if (newRoot) {
- newRoot->removeChild(newRoot->firstChild());
- } else {
- // FIXME: This interacts really badly with author shadow roots because now
- // we can interleave user agent and author shadow roots on the element meaning
- // input.shadowRoot may be inaccessible if the browser has decided to decorate
- // the input.
- newRoot = input->ensureShadow()->addShadowRoot(input, ShadowRoot::UserAgentShadowRoot);
- }
- decorationRoot = newRoot;
- decoratedRoot = existingRoot;
-}
-
-void PasswordGeneratorButtonElement::decorate(HTMLInputElement* input)
+PassRefPtr<PasswordGeneratorButtonElement> PasswordGeneratorButtonElement::create(Document& document)
{
- ASSERT(input);
- ShadowRoot* existingRoot;
- ShadowRoot* decorationRoot;
- getDecorationRootAndDecoratedRoot(input, decorationRoot, existingRoot);
- ASSERT(decorationRoot);
- ASSERT(existingRoot);
- RefPtr<HTMLDivElement> box = HTMLDivElement::create(input->document());
- decorationRoot->appendChild(box);
- box->setInlineStyleProperty(CSSPropertyDisplay, CSSValueFlex);
- box->setInlineStyleProperty(CSSPropertyAlignItems, CSSValueCenter);
- ASSERT(existingRoot->childNodeCount() == 1);
- toHTMLElement(existingRoot->firstChild())->setInlineStyleProperty(CSSPropertyFlexGrow, 1.0, CSSPrimitiveValue::CSS_NUMBER);
- box->appendChild(HTMLShadowElement::create(HTMLNames::shadowTag, input->document()));
- setInlineStyleProperty(CSSPropertyDisplay, CSSValueNone);
- box->appendChild(this);
+ RefPtr<PasswordGeneratorButtonElement> element = adoptRef(new PasswordGeneratorButtonElement(document));
+ element->setAttribute(idAttr, ShadowElementNames::passwordGenerator());
+ return element.release();
}
inline HTMLInputElement* PasswordGeneratorButtonElement::hostInput()
@@ -125,6 +85,7 @@ PassRefPtr<RenderStyle> PasswordGeneratorButtonElement::customStyleForRenderer()
ASSERT(inputStyle);
style->setWidth(Length(inputStyle->fontSize(), Fixed));
style->setHeight(Length(inputStyle->fontSize(), Fixed));
+ style->setUnique();
updateImage();
return style.release();
}
@@ -170,18 +131,18 @@ void PasswordGeneratorButtonElement::defaultEventHandler(Event* event)
}
RefPtr<PasswordGeneratorButtonElement> protector(this);
- if (event->type() == eventNames().clickEvent) {
+ if (event->type() == EventTypeNames::click) {
if (Page* page = document().page())
page->chrome().client().openPasswordGenerator(input.get());
event->setDefaultHandled();
}
- if (event->type() == eventNames().mouseoverEvent) {
+ if (event->type() == EventTypeNames::mouseover) {
m_isInHoverState = true;
updateImage();
}
- if (event->type() == eventNames().mouseoutEvent) {
+ if (event->type() == EventTypeNames::mouseout) {
m_isInHoverState = false;
updateImage();
}
diff --git a/chromium/third_party/WebKit/Source/core/html/shadow/PasswordGeneratorButtonElement.h b/chromium/third_party/WebKit/Source/core/html/shadow/PasswordGeneratorButtonElement.h
index e0853ead16c..0d220f9c6b1 100644
--- a/chromium/third_party/WebKit/Source/core/html/shadow/PasswordGeneratorButtonElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/shadow/PasswordGeneratorButtonElement.h
@@ -42,10 +42,7 @@ class ShadowRoot;
class PasswordGeneratorButtonElement FINAL : public HTMLDivElement {
public:
- static PassRefPtr<PasswordGeneratorButtonElement> create(Document& document)
- {
- return adoptRef(new PasswordGeneratorButtonElement(document));
- }
+ static PassRefPtr<PasswordGeneratorButtonElement> create(Document&);
void decorate(HTMLInputElement*);
diff --git a/chromium/third_party/WebKit/Source/core/html/shadow/PickerIndicatorElement.cpp b/chromium/third_party/WebKit/Source/core/html/shadow/PickerIndicatorElement.cpp
index 208475dc2ee..40aec28a852 100644
--- a/chromium/third_party/WebKit/Source/core/html/shadow/PickerIndicatorElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/shadow/PickerIndicatorElement.cpp
@@ -32,7 +32,7 @@
#if ENABLE(INPUT_MULTIPLE_FIELDS_UI)
#include "core/html/shadow/PickerIndicatorElement.h"
-#include "core/dom/Event.h"
+#include "core/events/Event.h"
#include "core/html/shadow/ShadowElementNames.h"
#include "core/page/Chrome.h"
#include "core/page/Page.h"
@@ -45,7 +45,7 @@ namespace WebCore {
using namespace HTMLNames;
inline PickerIndicatorElement::PickerIndicatorElement(Document& document, PickerIndicatorOwner& pickerIndicatorOwner)
- : HTMLDivElement(divTag, document)
+ : HTMLDivElement(document)
, m_pickerIndicatorOwner(&pickerIndicatorOwner)
{
}
@@ -53,7 +53,7 @@ inline PickerIndicatorElement::PickerIndicatorElement(Document& document, Picker
PassRefPtr<PickerIndicatorElement> PickerIndicatorElement::create(Document& document, PickerIndicatorOwner& pickerIndicatorOwner)
{
RefPtr<PickerIndicatorElement> element = adoptRef(new PickerIndicatorElement(document, pickerIndicatorOwner));
- element->setPart(AtomicString("-webkit-calendar-picker-indicator", AtomicString::ConstructFromLiteral));
+ element->setPseudo(AtomicString("-webkit-calendar-picker-indicator", AtomicString::ConstructFromLiteral));
element->setAttribute(idAttr, ShadowElementNames::pickerIndicator());
return element.release();
}
@@ -76,7 +76,7 @@ void PickerIndicatorElement::defaultEventHandler(Event* event)
if (!m_pickerIndicatorOwner || m_pickerIndicatorOwner->isPickerIndicatorOwnerDisabledOrReadOnly())
return;
- if (event->type() == eventNames().clickEvent) {
+ if (event->type() == EventTypeNames::click) {
openPopup();
event->setDefaultHandled();
}
@@ -100,6 +100,12 @@ void PickerIndicatorElement::didChooseValue(const String& value)
m_pickerIndicatorOwner->pickerIndicatorChooseValue(value);
}
+void PickerIndicatorElement::didChooseValue(double value)
+{
+ if (m_pickerIndicatorOwner)
+ m_pickerIndicatorOwner->pickerIndicatorChooseValue(value);
+}
+
void PickerIndicatorElement::didEndChooser()
{
m_chooser.clear();
diff --git a/chromium/third_party/WebKit/Source/core/html/shadow/PickerIndicatorElement.h b/chromium/third_party/WebKit/Source/core/html/shadow/PickerIndicatorElement.h
index 3e899fe4b85..8b7a5e3d740 100644
--- a/chromium/third_party/WebKit/Source/core/html/shadow/PickerIndicatorElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/shadow/PickerIndicatorElement.h
@@ -33,8 +33,8 @@
#if ENABLE(INPUT_MULTIPLE_FIELDS_UI)
#include "core/html/HTMLDivElement.h"
-#include "core/platform/DateTimeChooser.h"
-#include "core/platform/DateTimeChooserClient.h"
+#include "platform/DateTimeChooser.h"
+#include "platform/DateTimeChooserClient.h"
namespace WebCore {
@@ -49,7 +49,9 @@ public:
public:
virtual ~PickerIndicatorOwner() { }
virtual bool isPickerIndicatorOwnerDisabledOrReadOnly() const = 0;
+ // FIXME: Remove. Deprecated in favor of double version.
virtual void pickerIndicatorChooseValue(const String&) = 0;
+ virtual void pickerIndicatorChooseValue(double) = 0;
virtual bool setupDateTimeChooserParameters(DateTimeChooserParameters&) = 0;
};
@@ -62,6 +64,7 @@ public:
// DateTimeChooserClient implementation.
virtual void didChooseValue(const String&) OVERRIDE;
+ virtual void didChooseValue(double) OVERRIDE;
virtual void didEndChooser() OVERRIDE;
private:
@@ -77,11 +80,7 @@ private:
RefPtr<DateTimeChooser> m_chooser;
};
-inline PickerIndicatorElement* toPickerIndicatorElement(Element* element)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!element || element->isPickerIndicatorElement());
- return static_cast<PickerIndicatorElement*>(element);
-}
+DEFINE_TYPE_CASTS(PickerIndicatorElement, Element, element, element->isPickerIndicatorElement(), element.isPickerIndicatorElement());
}
#endif
diff --git a/chromium/third_party/WebKit/Source/core/html/shadow/ProgressShadowElement.cpp b/chromium/third_party/WebKit/Source/core/html/shadow/ProgressShadowElement.cpp
index 2de1161e95a..50c8d1dc9a4 100644
--- a/chromium/third_party/WebKit/Source/core/html/shadow/ProgressShadowElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/shadow/ProgressShadowElement.cpp
@@ -41,7 +41,7 @@ namespace WebCore {
using namespace HTMLNames;
ProgressShadowElement::ProgressShadowElement(Document& document)
- : HTMLDivElement(HTMLNames::divTag, document)
+ : HTMLDivElement(document)
{
}
diff --git a/chromium/third_party/WebKit/Source/core/html/shadow/ShadowElementNames.cpp b/chromium/third_party/WebKit/Source/core/html/shadow/ShadowElementNames.cpp
index d34bfddeee6..abe60e1d644 100644
--- a/chromium/third_party/WebKit/Source/core/html/shadow/ShadowElementNames.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/shadow/ShadowElementNames.cpp
@@ -59,6 +59,18 @@ const AtomicString& editingViewPort()
return name;
}
+const AtomicString& innerEditor()
+{
+ DEFINE_STATIC_LOCAL(AtomicString, name, ("inner-editor", AtomicString::ConstructFromLiteral));
+ return name;
+}
+
+const AtomicString& passwordGenerator()
+{
+ DEFINE_STATIC_LOCAL(AtomicString, name, ("password-generator", AtomicString::ConstructFromLiteral));
+ return name;
+}
+
const AtomicString& pickerIndicator()
{
DEFINE_STATIC_LOCAL(AtomicString, name, ("picker", AtomicString::ConstructFromLiteral));
@@ -95,6 +107,12 @@ const AtomicString& speechButton()
return name;
}
+const AtomicString& textFieldContainer()
+{
+ DEFINE_STATIC_LOCAL(AtomicString, name, ("text-field-container", AtomicString::ConstructFromLiteral));
+ return name;
+}
+
}
}
diff --git a/chromium/third_party/WebKit/Source/core/html/shadow/ShadowElementNames.h b/chromium/third_party/WebKit/Source/core/html/shadow/ShadowElementNames.h
index a5f8d3a3b78..46788a1cdfb 100644
--- a/chromium/third_party/WebKit/Source/core/html/shadow/ShadowElementNames.h
+++ b/chromium/third_party/WebKit/Source/core/html/shadow/ShadowElementNames.h
@@ -41,12 +41,15 @@ const AtomicString& dateTimeEdit();
const AtomicString& spinButton();
const AtomicString& clearButton();
const AtomicString& editingViewPort();
+const AtomicString& innerEditor();
+const AtomicString& passwordGenerator();
const AtomicString& pickerIndicator();
const AtomicString& placeholder();
const AtomicString& searchDecoration();
const AtomicString& sliderThumb();
const AtomicString& sliderTrack();
const AtomicString& speechButton();
+const AtomicString& textFieldContainer();
}
diff --git a/chromium/third_party/WebKit/Source/core/html/shadow/SliderThumbElement.cpp b/chromium/third_party/WebKit/Source/core/html/shadow/SliderThumbElement.cpp
index 29b3313891e..dc7d5080591 100644
--- a/chromium/third_party/WebKit/Source/core/html/shadow/SliderThumbElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/shadow/SliderThumbElement.cpp
@@ -33,15 +33,15 @@
#include "config.h"
#include "core/html/shadow/SliderThumbElement.h"
-#include "core/dom/Event.h"
-#include "core/dom/MouseEvent.h"
+#include "core/events/Event.h"
+#include "core/events/MouseEvent.h"
#include "core/dom/shadow/ShadowRoot.h"
#include "core/html/HTMLInputElement.h"
#include "core/html/forms/StepRange.h"
#include "core/html/parser/HTMLParserIdioms.h"
#include "core/html/shadow/ShadowElementNames.h"
#include "core/page/EventHandler.h"
-#include "core/page/Frame.h"
+#include "core/frame/Frame.h"
#include "core/rendering/RenderFlexibleBox.h"
#include "core/rendering/RenderSlider.h"
#include "core/rendering/RenderTheme.h"
@@ -196,7 +196,7 @@ void RenderSliderContainer::layout()
// --------------------------------
inline SliderThumbElement::SliderThumbElement(Document& document)
- : HTMLDivElement(HTMLNames::divTag, document)
+ : HTMLDivElement(document)
, m_inDragMode(false)
{
}
@@ -245,8 +245,8 @@ Node* SliderThumbElement::focusDelegate()
void SliderThumbElement::dragFrom(const LayoutPoint& point)
{
RefPtr<SliderThumbElement> protector(this);
- setPositionFromPoint(point);
startDragging();
+ setPositionFromPoint(point);
}
void SliderThumbElement::setPositionFromPoint(const LayoutPoint& point)
@@ -287,16 +287,14 @@ void SliderThumbElement::setPositionFromPoint(const LayoutPoint& point)
StepRange stepRange(input->createStepRange(RejectAny));
Decimal value = stepRange.clampValue(stepRange.valueFromProportion(fraction));
- const LayoutUnit snappingThreshold = RenderTheme::theme().sliderTickSnappingThreshold();
- if (snappingThreshold > 0) {
- Decimal closest = input->findClosestTickMarkValue(value);
- if (closest.isFinite()) {
- double closestFraction = stepRange.proportionFromValue(closest).toDouble();
- double closestRatio = isVertical || !isLeftToRightDirection ? 1.0 - closestFraction : closestFraction;
- LayoutUnit closestPosition = trackSize * closestRatio;
- if ((closestPosition - position).abs() <= snappingThreshold)
- value = closest;
- }
+ Decimal closest = input->findClosestTickMarkValue(value);
+ if (closest.isFinite()) {
+ double closestFraction = stepRange.proportionFromValue(closest).toDouble();
+ double closestRatio = isVertical || !isLeftToRightDirection ? 1.0 - closestFraction : closestFraction;
+ LayoutUnit closestPosition = trackSize * closestRatio;
+ const LayoutUnit snappingThreshold = 5;
+ if ((closestPosition - position).abs() <= snappingThreshold)
+ value = closest;
}
String valueString = serializeForNumberType(value);
@@ -313,7 +311,7 @@ void SliderThumbElement::setPositionFromPoint(const LayoutPoint& point)
void SliderThumbElement::startDragging()
{
if (Frame* frame = document().frame()) {
- frame->eventHandler()->setCapturingMouseEventsNode(this);
+ frame->eventHandler().setCapturingMouseEventsNode(this);
m_inDragMode = true;
}
}
@@ -324,7 +322,7 @@ void SliderThumbElement::stopDragging()
return;
if (Frame* frame = document().frame())
- frame->eventHandler()->setCapturingMouseEventsNode(0);
+ frame->eventHandler().setCapturingMouseEventsNode(0);
m_inDragMode = false;
if (renderer())
renderer()->setNeedsLayout();
@@ -353,13 +351,13 @@ void SliderThumbElement::defaultEventHandler(Event* event)
// We intentionally do not call event->setDefaultHandled() here because
// MediaControlTimelineElement::defaultEventHandler() wants to handle these
// mouse events.
- if (eventType == eventNames().mousedownEvent && isLeftButton) {
+ if (eventType == EventTypeNames::mousedown && isLeftButton) {
startDragging();
return;
- } else if (eventType == eventNames().mouseupEvent && isLeftButton) {
+ } else if (eventType == EventTypeNames::mouseup && isLeftButton) {
stopDragging();
return;
- } else if (eventType == eventNames().mousemoveEvent) {
+ } else if (eventType == EventTypeNames::mousemove) {
if (m_inDragMode)
setPositionFromPoint(mouseEvent->absoluteLocation());
return;
@@ -390,7 +388,7 @@ void SliderThumbElement::detach(const AttachContext& context)
{
if (m_inDragMode) {
if (Frame* frame = document().frame())
- frame->eventHandler()->setCapturingMouseEventsNode(0);
+ frame->eventHandler().setCapturingMouseEventsNode(0);
}
HTMLDivElement::detach(context);
}
@@ -414,7 +412,7 @@ static const AtomicString& mediaSliderThumbShadowPartId()
return mediaSliderThumb;
}
-const AtomicString& SliderThumbElement::part() const
+const AtomicString& SliderThumbElement::pseudo() const
{
HTMLInputElement* input = hostInput();
if (!input)
@@ -437,7 +435,7 @@ const AtomicString& SliderThumbElement::part() const
// --------------------------------
inline SliderContainerElement::SliderContainerElement(Document& document)
- : HTMLDivElement(HTMLNames::divTag, document)
+ : HTMLDivElement(document)
{
}
@@ -451,7 +449,7 @@ RenderObject* SliderContainerElement::createRenderer(RenderStyle*)
return new RenderSliderContainer(this);
}
-const AtomicString& SliderContainerElement::part() const
+const AtomicString& SliderContainerElement::pseudo() const
{
DEFINE_STATIC_LOCAL(const AtomicString, mediaSliderContainer, ("-webkit-media-slider-container", AtomicString::ConstructFromLiteral));
DEFINE_STATIC_LOCAL(const AtomicString, sliderContainer, ("-webkit-slider-container", AtomicString::ConstructFromLiteral));
diff --git a/chromium/third_party/WebKit/Source/core/html/shadow/SliderThumbElement.h b/chromium/third_party/WebKit/Source/core/html/shadow/SliderThumbElement.h
index 1c625dd02cd..a7af7771fbd 100644
--- a/chromium/third_party/WebKit/Source/core/html/shadow/SliderThumbElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/shadow/SliderThumbElement.h
@@ -55,9 +55,10 @@ public:
virtual bool willRespondToMouseMoveEvents() OVERRIDE;
virtual bool willRespondToMouseClickEvents() OVERRIDE;
virtual void detach(const AttachContext& = AttachContext()) OVERRIDE;
- virtual const AtomicString& part() const OVERRIDE;
+ virtual const AtomicString& pseudo() const OVERRIDE;
HTMLInputElement* hostInput() const;
void setPositionFromPoint(const LayoutPoint&);
+ void stopDragging();
private:
SliderThumbElement(Document&);
@@ -68,7 +69,6 @@ private:
virtual bool matchesReadWritePseudoClass() const OVERRIDE;
virtual Node* focusDelegate();
void startDragging();
- void stopDragging();
bool m_inDragMode;
};
@@ -105,7 +105,7 @@ public:
private:
SliderContainerElement(Document&);
virtual RenderObject* createRenderer(RenderStyle*);
- virtual const AtomicString& part() const;
+ virtual const AtomicString& pseudo() const;
};
}
diff --git a/chromium/third_party/WebKit/Source/core/html/shadow/SpinButtonElement.cpp b/chromium/third_party/WebKit/Source/core/html/shadow/SpinButtonElement.cpp
index 4521b32612b..38303b5aca5 100644
--- a/chromium/third_party/WebKit/Source/core/html/shadow/SpinButtonElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/shadow/SpinButtonElement.cpp
@@ -28,23 +28,23 @@
#include "core/html/shadow/SpinButtonElement.h"
#include "HTMLNames.h"
-#include "core/dom/EventNames.h"
-#include "core/dom/MouseEvent.h"
-#include "core/dom/WheelEvent.h"
+#include "core/events/MouseEvent.h"
+#include "core/events/ThreadLocalEventNames.h"
+#include "core/events/WheelEvent.h"
#include "core/html/shadow/ShadowElementNames.h"
#include "core/page/Chrome.h"
#include "core/page/EventHandler.h"
-#include "core/page/Frame.h"
+#include "core/frame/Frame.h"
#include "core/page/Page.h"
-#include "core/platform/ScrollbarTheme.h"
#include "core/rendering/RenderBox.h"
+#include "platform/scroll/ScrollbarTheme.h"
namespace WebCore {
using namespace HTMLNames;
inline SpinButtonElement::SpinButtonElement(Document& document, SpinButtonOwner& spinButtonOwner)
- : HTMLDivElement(divTag, document)
+ : HTMLDivElement(document)
, m_spinButtonOwner(&spinButtonOwner)
, m_capturing(false)
, m_upDownState(Indeterminate)
@@ -56,7 +56,7 @@ inline SpinButtonElement::SpinButtonElement(Document& document, SpinButtonOwner&
PassRefPtr<SpinButtonElement> SpinButtonElement::create(Document& document, SpinButtonOwner& spinButtonOwner)
{
RefPtr<SpinButtonElement> element = adoptRef(new SpinButtonElement(document, spinButtonOwner));
- element->setPart(AtomicString("-webkit-inner-spin-button", AtomicString::ConstructFromLiteral));
+ element->setPseudo(AtomicString("-webkit-inner-spin-button", AtomicString::ConstructFromLiteral));
element->setAttribute(idAttr, ShadowElementNames::spinButton());
return element.release();
}
@@ -90,7 +90,7 @@ void SpinButtonElement::defaultEventHandler(Event* event)
MouseEvent* mouseEvent = toMouseEvent(event);
IntPoint local = roundedIntPoint(box->absoluteToLocal(mouseEvent->absoluteLocation(), UseTransforms));
- if (mouseEvent->type() == eventNames().mousedownEvent && mouseEvent->button() == LeftButton) {
+ if (mouseEvent->type() == EventTypeNames::mousedown && mouseEvent->button() == LeftButton) {
if (box->pixelSnappedBorderBoxRect().contains(local)) {
// The following functions of HTMLInputElement may run JavaScript
// code which detaches this shadow node. We need to take a reference
@@ -111,13 +111,13 @@ void SpinButtonElement::defaultEventHandler(Event* event)
}
event->setDefaultHandled();
}
- } else if (mouseEvent->type() == eventNames().mouseupEvent && mouseEvent->button() == LeftButton)
+ } else if (mouseEvent->type() == EventTypeNames::mouseup && mouseEvent->button() == LeftButton)
stopRepeatingTimer();
- else if (event->type() == eventNames().mousemoveEvent) {
+ else if (event->type() == EventTypeNames::mousemove) {
if (box->pixelSnappedBorderBoxRect().contains(local)) {
if (!m_capturing) {
if (Frame* frame = document().frame()) {
- frame->eventHandler()->setCapturingMouseEventsNode(this);
+ frame->eventHandler().setCapturingMouseEventsNode(this);
m_capturing = true;
if (Page* page = document().page())
page->chrome().registerPopupOpeningObserver(this);
@@ -148,7 +148,7 @@ void SpinButtonElement::forwardEvent(Event* event)
if (!renderBox())
return;
- if (!event->hasInterface(eventNames().interfaceForWheelEvent))
+ if (!event->hasInterface(EventNames::WheelEvent))
return;
if (!m_spinButtonOwner)
@@ -157,7 +157,7 @@ void SpinButtonElement::forwardEvent(Event* event)
if (!m_spinButtonOwner->shouldSpinButtonRespondToWheelEvents())
return;
- doStepAction(static_cast<WheelEvent*>(event)->wheelDeltaY());
+ doStepAction(toWheelEvent(event)->wheelDeltaY());
event->setDefaultHandled();
}
@@ -193,7 +193,7 @@ void SpinButtonElement::releaseCapture()
stopRepeatingTimer();
if (m_capturing) {
if (Frame* frame = document().frame()) {
- frame->eventHandler()->setCapturingMouseEventsNode(0);
+ frame->eventHandler().setCapturingMouseEventsNode(0);
m_capturing = false;
if (Page* page = document().page())
page->chrome().unregisterPopupOpeningObserver(this);
diff --git a/chromium/third_party/WebKit/Source/core/html/shadow/SpinButtonElement.h b/chromium/third_party/WebKit/Source/core/html/shadow/SpinButtonElement.h
index a7490366545..41de8fcdaee 100644
--- a/chromium/third_party/WebKit/Source/core/html/shadow/SpinButtonElement.h
+++ b/chromium/third_party/WebKit/Source/core/html/shadow/SpinButtonElement.h
@@ -29,7 +29,7 @@
#include "core/html/HTMLDivElement.h"
#include "core/page/PopupOpeningObserver.h"
-#include "core/platform/Timer.h"
+#include "platform/Timer.h"
namespace WebCore {
@@ -91,25 +91,7 @@ private:
Timer<SpinButtonElement> m_repeatingTimer;
};
-inline SpinButtonElement* toSpinButtonElement(Element* element)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!element || element->isSpinButtonElement());
- return static_cast<SpinButtonElement*>(element);
-}
-
-inline SpinButtonElement* toSpinButtonElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || toElement(node)->isSpinButtonElement());
- return static_cast<SpinButtonElement*>(node);
-}
-
-inline const SpinButtonElement* toSpinButtonElement(const Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || toElement(node)->isSpinButtonElement());
- return static_cast<const SpinButtonElement*>(node);
-}
-
-void toSpinButtonElement(const SpinButtonElement*);
+DEFINE_TYPE_CASTS(SpinButtonElement, Node, node, toElement(node)->isSpinButtonElement(), toElement(node).isSpinButtonElement());
} // namespace
diff --git a/chromium/third_party/WebKit/Source/core/html/shadow/TextControlInnerElements.cpp b/chromium/third_party/WebKit/Source/core/html/shadow/TextControlInnerElements.cpp
index 47a3ade8796..a19fef2c9e9 100644
--- a/chromium/third_party/WebKit/Source/core/html/shadow/TextControlInnerElements.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/shadow/TextControlInnerElements.cpp
@@ -28,34 +28,36 @@
#include "core/html/shadow/TextControlInnerElements.h"
#include "HTMLNames.h"
-#include "bindings/v8/ScriptController.h"
#include "core/dom/Document.h"
-#include "core/dom/EventNames.h"
-#include "core/dom/MouseEvent.h"
#include "core/dom/NodeRenderStyle.h"
-#include "core/dom/TextEvent.h"
-#include "core/dom/TextEventInputType.h"
+#include "core/events/MouseEvent.h"
+#include "core/events/TextEvent.h"
+#include "core/events/TextEventInputType.h"
+#include "core/events/ThreadLocalEventNames.h"
#include "core/html/HTMLInputElement.h"
#include "core/html/shadow/ShadowElementNames.h"
#include "core/page/EventHandler.h"
-#include "core/page/Frame.h"
-#include "core/page/SpeechInput.h"
-#include "core/page/SpeechInputEvent.h"
+#include "core/frame/Frame.h"
#include "core/rendering/RenderTextControlSingleLine.h"
#include "core/rendering/RenderView.h"
+#include "core/speech/SpeechInput.h"
+#include "core/speech/SpeechInputEvent.h"
+#include "platform/UserGestureIndicator.h"
namespace WebCore {
using namespace HTMLNames;
TextControlInnerContainer::TextControlInnerContainer(Document& document)
- : HTMLDivElement(divTag, document)
+ : HTMLDivElement(document)
{
}
PassRefPtr<TextControlInnerContainer> TextControlInnerContainer::create(Document& document)
{
- return adoptRef(new TextControlInnerContainer(document));
+ RefPtr<TextControlInnerContainer> element = adoptRef(new TextControlInnerContainer(document));
+ element->setAttribute(idAttr, ShadowElementNames::textFieldContainer());
+ return element.release();
}
RenderObject* TextControlInnerContainer::createRenderer(RenderStyle*)
@@ -66,7 +68,7 @@ RenderObject* TextControlInnerContainer::createRenderer(RenderStyle*)
// ---------------------------
EditingViewPortElement::EditingViewPortElement(Document& document)
- : HTMLDivElement(divTag, document)
+ : HTMLDivElement(document)
{
setHasCustomStyleCallbacks();
}
@@ -95,6 +97,7 @@ PassRefPtr<RenderStyle> EditingViewPortElement::customStyleForRenderer()
// We don't want the shadow dom to be editable, so we set this block to
// read-only in case the input itself is editable.
style->setUserModify(READ_ONLY);
+ style->setUnique();
return style.release();
}
@@ -102,14 +105,16 @@ PassRefPtr<RenderStyle> EditingViewPortElement::customStyleForRenderer()
// ---------------------------
inline TextControlInnerTextElement::TextControlInnerTextElement(Document& document)
- : HTMLDivElement(divTag, document)
+ : HTMLDivElement(document)
{
setHasCustomStyleCallbacks();
}
PassRefPtr<TextControlInnerTextElement> TextControlInnerTextElement::create(Document& document)
{
- return adoptRef(new TextControlInnerTextElement(document));
+ RefPtr<TextControlInnerTextElement> element = adoptRef(new TextControlInnerTextElement(document));
+ element->setAttribute(idAttr, ShadowElementNames::innerEditor());
+ return element.release();
}
void TextControlInnerTextElement::defaultEventHandler(Event* event)
@@ -117,7 +122,7 @@ void TextControlInnerTextElement::defaultEventHandler(Event* event)
// FIXME: In the future, we should add a way to have default event listeners.
// Then we would add one to the text field's inner div, and we wouldn't need this subclass.
// Or possibly we could just use a normal event listener.
- if (event->isBeforeTextInsertedEvent() || event->type() == eventNames().webkitEditableContentChangedEvent) {
+ if (event->isBeforeTextInsertedEvent() || event->type() == EventTypeNames::webkitEditableContentChanged) {
Element* shadowAncestor = shadowHost();
// A TextControlInnerTextElement can have no host if its been detached,
// but kept alive by an EditCommand. In this case, an undo/redo can
@@ -148,7 +153,7 @@ PassRefPtr<RenderStyle> TextControlInnerTextElement::customStyleForRenderer()
// ----------------------------
inline SearchFieldDecorationElement::SearchFieldDecorationElement(Document& document)
- : HTMLDivElement(divTag, document)
+ : HTMLDivElement(document)
{
}
@@ -159,7 +164,7 @@ PassRefPtr<SearchFieldDecorationElement> SearchFieldDecorationElement::create(Do
return element.release();
}
-const AtomicString& SearchFieldDecorationElement::part() const
+const AtomicString& SearchFieldDecorationElement::pseudo() const
{
DEFINE_STATIC_LOCAL(AtomicString, resultsDecorationId, ("-webkit-search-results-decoration", AtomicString::ConstructFromLiteral));
DEFINE_STATIC_LOCAL(AtomicString, decorationId, ("-webkit-search-decoration", AtomicString::ConstructFromLiteral));
@@ -178,7 +183,7 @@ void SearchFieldDecorationElement::defaultEventHandler(Event* event)
{
// On mousedown, focus the search field
HTMLInputElement* input = toHTMLInputElement(shadowHost());
- if (input && event->type() == eventNames().mousedownEvent && event->isMouseEvent() && toMouseEvent(event)->button() == LeftButton) {
+ if (input && event->type() == EventTypeNames::mousedown && event->isMouseEvent() && toMouseEvent(event)->button() == LeftButton) {
input->focus();
input->select();
event->setDefaultHandled();
@@ -196,7 +201,7 @@ bool SearchFieldDecorationElement::willRespondToMouseClickEvents()
// ----------------------------
inline SearchFieldCancelButtonElement::SearchFieldCancelButtonElement(Document& document)
- : HTMLDivElement(divTag, document)
+ : HTMLDivElement(document)
, m_capturing(false)
{
}
@@ -204,7 +209,7 @@ inline SearchFieldCancelButtonElement::SearchFieldCancelButtonElement(Document&
PassRefPtr<SearchFieldCancelButtonElement> SearchFieldCancelButtonElement::create(Document& document)
{
RefPtr<SearchFieldCancelButtonElement> element = adoptRef(new SearchFieldCancelButtonElement(document));
- element->setPart(AtomicString("-webkit-search-cancel-button", AtomicString::ConstructFromLiteral));
+ element->setPseudo(AtomicString("-webkit-search-cancel-button", AtomicString::ConstructFromLiteral));
element->setAttribute(idAttr, ShadowElementNames::clearButton());
return element.release();
}
@@ -213,7 +218,7 @@ void SearchFieldCancelButtonElement::detach(const AttachContext& context)
{
if (m_capturing) {
if (Frame* frame = document().frame())
- frame->eventHandler()->setCapturingMouseEventsNode(0);
+ frame->eventHandler().setCapturingMouseEventsNode(0);
}
HTMLDivElement::detach(context);
}
@@ -229,10 +234,10 @@ void SearchFieldCancelButtonElement::defaultEventHandler(Event* event)
return;
}
- if (event->type() == eventNames().mousedownEvent && event->isMouseEvent() && toMouseEvent(event)->button() == LeftButton) {
+ if (event->type() == EventTypeNames::mousedown && event->isMouseEvent() && toMouseEvent(event)->button() == LeftButton) {
if (renderer() && renderer()->visibleToHitTesting()) {
if (Frame* frame = document().frame()) {
- frame->eventHandler()->setCapturingMouseEventsNode(this);
+ frame->eventHandler().setCapturingMouseEventsNode(this);
m_capturing = true;
}
}
@@ -240,10 +245,10 @@ void SearchFieldCancelButtonElement::defaultEventHandler(Event* event)
input->select();
event->setDefaultHandled();
}
- if (event->type() == eventNames().mouseupEvent && event->isMouseEvent() && toMouseEvent(event)->button() == LeftButton) {
+ if (event->type() == EventTypeNames::mouseup && event->isMouseEvent() && toMouseEvent(event)->button() == LeftButton) {
if (m_capturing) {
if (Frame* frame = document().frame()) {
- frame->eventHandler()->setCapturingMouseEventsNode(0);
+ frame->eventHandler().setCapturingMouseEventsNode(0);
m_capturing = false;
}
if (hovered()) {
@@ -273,7 +278,7 @@ bool SearchFieldCancelButtonElement::willRespondToMouseClickEvents()
#if ENABLE(INPUT_SPEECH)
inline InputFieldSpeechButtonElement::InputFieldSpeechButtonElement(Document& document)
- : HTMLDivElement(divTag, document)
+ : HTMLDivElement(document)
, m_capturing(false)
, m_state(Idle)
, m_listenerId(0)
@@ -293,7 +298,7 @@ InputFieldSpeechButtonElement::~InputFieldSpeechButtonElement()
PassRefPtr<InputFieldSpeechButtonElement> InputFieldSpeechButtonElement::create(Document& document)
{
RefPtr<InputFieldSpeechButtonElement> element = adoptRef(new InputFieldSpeechButtonElement(document));
- element->setPart(AtomicString("-webkit-input-speech-button", AtomicString::ConstructFromLiteral));
+ element->setPseudo(AtomicString("-webkit-input-speech-button", AtomicString::ConstructFromLiteral));
element->setAttribute(idAttr, ShadowElementNames::speechButton());
return element.release();
}
@@ -301,7 +306,7 @@ PassRefPtr<InputFieldSpeechButtonElement> InputFieldSpeechButtonElement::create(
void InputFieldSpeechButtonElement::defaultEventHandler(Event* event)
{
// For privacy reasons, only allow clicks directly coming from the user.
- if (!ScriptController::processingUserGesture()) {
+ if (!UserGestureIndicator::processingUserGesture()) {
HTMLDivElement::defaultEventHandler(event);
return;
}
@@ -318,10 +323,10 @@ void InputFieldSpeechButtonElement::defaultEventHandler(Event* event)
}
// On mouse down, select the text and set focus.
- if (event->type() == eventNames().mousedownEvent && event->isMouseEvent() && toMouseEvent(event)->button() == LeftButton) {
+ if (event->type() == EventTypeNames::mousedown && event->isMouseEvent() && toMouseEvent(event)->button() == LeftButton) {
if (renderer() && renderer()->visibleToHitTesting()) {
if (Frame* frame = document().frame()) {
- frame->eventHandler()->setCapturingMouseEventsNode(this);
+ frame->eventHandler().setCapturingMouseEventsNode(this);
m_capturing = true;
}
}
@@ -331,16 +336,16 @@ void InputFieldSpeechButtonElement::defaultEventHandler(Event* event)
event->setDefaultHandled();
}
// On mouse up, release capture cleanly.
- if (event->type() == eventNames().mouseupEvent && event->isMouseEvent() && toMouseEvent(event)->button() == LeftButton) {
+ if (event->type() == EventTypeNames::mouseup && event->isMouseEvent() && toMouseEvent(event)->button() == LeftButton) {
if (m_capturing && renderer() && renderer()->visibleToHitTesting()) {
if (Frame* frame = document().frame()) {
- frame->eventHandler()->setCapturingMouseEventsNode(0);
+ frame->eventHandler().setCapturingMouseEventsNode(0);
m_capturing = false;
}
}
}
- if (event->type() == eventNames().clickEvent && m_listenerId) {
+ if (event->type() == EventTypeNames::click && m_listenerId) {
switch (m_state) {
case Idle:
startSpeechInput();
@@ -413,7 +418,7 @@ void InputFieldSpeechButtonElement::setRecognitionResult(int, const SpeechInputR
// This event is sent after the text event so the website can perform actions using the input field content immediately.
// It provides alternative recognition hypotheses and notifies that the results come from speech input.
- input->dispatchEvent(SpeechInputEvent::create(eventNames().webkitspeechchangeEvent, results));
+ input->dispatchEvent(SpeechInputEvent::create(EventTypeNames::webkitspeechchange, results));
// Check before accessing the renderer as the above event could have potentially turned off
// speech in the input element, hence removing this button and renderer from the hierarchy.
@@ -433,7 +438,7 @@ void InputFieldSpeechButtonElement::detach(const AttachContext& context)
{
if (m_capturing) {
if (Frame* frame = document().frame())
- frame->eventHandler()->setCapturingMouseEventsNode(0);
+ frame->eventHandler().setCapturingMouseEventsNode(0);
}
if (m_listenerId) {
diff --git a/chromium/third_party/WebKit/Source/core/html/shadow/TextControlInnerElements.h b/chromium/third_party/WebKit/Source/core/html/shadow/TextControlInnerElements.h
index 5843c4d40dd..6b6fb0ff6f4 100644
--- a/chromium/third_party/WebKit/Source/core/html/shadow/TextControlInnerElements.h
+++ b/chromium/third_party/WebKit/Source/core/html/shadow/TextControlInnerElements.h
@@ -28,7 +28,7 @@
#define TextControlInnerElements_h
#include "core/html/HTMLDivElement.h"
-#include "core/page/SpeechInputListener.h"
+#include "core/speech/SpeechInputListener.h"
#include "wtf/Forward.h"
namespace WebCore {
@@ -77,7 +77,7 @@ public:
private:
SearchFieldDecorationElement(Document&);
- virtual const AtomicString& part() const OVERRIDE;
+ virtual const AtomicString& pseudo() const OVERRIDE;
virtual bool supportsFocus() const OVERRIDE { return false; }
};
@@ -137,11 +137,7 @@ private:
SpeechInputResultArray m_results;
};
-inline InputFieldSpeechButtonElement* toInputFieldSpeechButtonElement(Element* element)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!element || element->isInputFieldSpeechButtonElement());
- return static_cast<InputFieldSpeechButtonElement*>(element);
-}
+DEFINE_TYPE_CASTS(InputFieldSpeechButtonElement, Element, element, element->isInputFieldSpeechButtonElement(), element.isInputFieldSpeechButtonElement());
#endif // ENABLE(INPUT_SPEECH)
diff --git a/chromium/third_party/WebKit/Source/core/html/track/InbandTextTrack.cpp b/chromium/third_party/WebKit/Source/core/html/track/InbandTextTrack.cpp
index 95f629d74ef..925f84e7c9d 100644
--- a/chromium/third_party/WebKit/Source/core/html/track/InbandTextTrack.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/track/InbandTextTrack.cpp
@@ -27,42 +27,45 @@
#include "core/html/track/InbandTextTrack.h"
#include "bindings/v8/ExceptionStatePlaceholder.h"
-#include "core/html/track/TextTrackCueGeneric.h"
-#include "core/platform/Logging.h"
-#include "core/platform/graphics/InbandTextTrackPrivate.h"
-#include "wtf/UnusedParam.h"
+#include "core/html/track/vtt/VTTCue.h"
+#include "platform/Logging.h"
+#include "public/platform/WebInbandTextTrack.h"
+#include "public/platform/WebString.h"
#include <math.h>
+using blink::WebInbandTextTrack;
+using blink::WebString;
+
namespace WebCore {
-PassRefPtr<InbandTextTrack> InbandTextTrack::create(ScriptExecutionContext* context, TextTrackClient* client, PassRefPtr<InbandTextTrackPrivate> playerPrivate)
+PassRefPtr<InbandTextTrack> InbandTextTrack::create(Document& document, TextTrackClient* client, WebInbandTextTrack* webTrack)
{
- return adoptRef(new InbandTextTrack(context, client, playerPrivate));
+ return adoptRef(new InbandTextTrack(document, client, webTrack));
}
-InbandTextTrack::InbandTextTrack(ScriptExecutionContext* context, TextTrackClient* client, PassRefPtr<InbandTextTrackPrivate> tracksPrivate)
- : TextTrack(context, client, emptyString(), tracksPrivate->label(), tracksPrivate->language(), InBand)
- , m_private(tracksPrivate)
+InbandTextTrack::InbandTextTrack(Document& document, TextTrackClient* client, WebInbandTextTrack* webTrack)
+ : TextTrack(document, client, emptyAtom, webTrack->label(), webTrack->language(), webTrack->id(), InBand)
+ , m_webTrack(webTrack)
{
- m_private->setClient(this);
+ m_webTrack->setClient(this);
- switch (m_private->kind()) {
- case InbandTextTrackPrivate::Subtitles:
+ switch (m_webTrack->kind()) {
+ case WebInbandTextTrack::KindSubtitles:
setKind(TextTrack::subtitlesKeyword());
break;
- case InbandTextTrackPrivate::Captions:
+ case WebInbandTextTrack::KindCaptions:
setKind(TextTrack::captionsKeyword());
break;
- case InbandTextTrackPrivate::Descriptions:
+ case WebInbandTextTrack::KindDescriptions:
setKind(TextTrack::descriptionsKeyword());
break;
- case InbandTextTrackPrivate::Chapters:
+ case WebInbandTextTrack::KindChapters:
setKind(TextTrack::chaptersKeyword());
break;
- case InbandTextTrackPrivate::Metadata:
+ case WebInbandTextTrack::KindMetadata:
setKind(TextTrack::metadataKeyword());
break;
- case InbandTextTrackPrivate::None:
+ case WebInbandTextTrack::KindNone:
default:
ASSERT_NOT_REACHED();
break;
@@ -71,125 +74,29 @@ InbandTextTrack::InbandTextTrack(ScriptExecutionContext* context, TextTrackClien
InbandTextTrack::~InbandTextTrack()
{
- // Make sure m_private was cleared by trackRemoved() before destruction.
- ASSERT(!m_private);
-}
-
-void InbandTextTrack::setMode(const AtomicString& mode)
-{
- TextTrack::setMode(mode);
-
- if (!m_private)
- return;
-
- if (mode == TextTrack::disabledKeyword())
- m_private->setMode(InbandTextTrackPrivate::Disabled);
- else if (mode == TextTrack::hiddenKeyword())
- m_private->setMode(InbandTextTrackPrivate::Hidden);
- else if (mode == TextTrack::showingKeyword())
- m_private->setMode(InbandTextTrackPrivate::Showing);
- else
- ASSERT_NOT_REACHED();
-}
-
-bool InbandTextTrack::isClosedCaptions() const
-{
- if (!m_private)
- return false;
-
- return m_private->isClosedCaptions();
-}
-
-bool InbandTextTrack::containsOnlyForcedSubtitles() const
-{
- if (!m_private)
- return false;
-
- return m_private->containsOnlyForcedSubtitles();
-}
-
-bool InbandTextTrack::isMainProgramContent() const
-{
- if (!m_private)
- return false;
-
- return m_private->isMainProgramContent();
-}
-
-bool InbandTextTrack::isEasyToRead() const
-{
- if (!m_private)
- return false;
-
- return m_private->isEasyToRead();
+ // Make sure m_webTrack was cleared by trackRemoved() before destruction.
+ ASSERT(!m_webTrack);
}
size_t InbandTextTrack::inbandTrackIndex()
{
- ASSERT(m_private);
- return m_private->textTrackIndex();
+ ASSERT(m_webTrack);
+ return m_webTrack->textTrackIndex();
}
void InbandTextTrack::trackRemoved()
{
- ASSERT(m_private);
- m_private->setClient(0);
- m_private = 0;
+ ASSERT(m_webTrack);
+ m_webTrack->setClient(0);
+ m_webTrack = 0;
clearClient();
}
-void InbandTextTrack::addGenericCue(InbandTextTrackPrivate* trackPrivate, GenericCueData* cueData)
-{
- UNUSED_PARAM(trackPrivate);
- ASSERT(trackPrivate == m_private);
-
- RefPtr<TextTrackCueGeneric> cue = TextTrackCueGeneric::create(scriptExecutionContext(), cueData->startTime(), cueData->endTime(), cueData->content());
-
- cue->setId(cueData->id());
- cue->setBaseFontSizeRelativeToVideoHeight(cueData->baseFontSize());
- cue->setFontSizeMultiplier(cueData->relativeFontSize());
- cue->setFontName(cueData->fontName());
-
- if (cueData->position() > 0)
- cue->setPosition(lround(cueData->position()), IGNORE_EXCEPTION);
- if (cueData->line() > 0)
- cue->setLine(lround(cueData->line()), IGNORE_EXCEPTION);
- if (cueData->size() > 0)
- cue->setSize(lround(cueData->size()), IGNORE_EXCEPTION);
- if (cueData->backgroundColor().isValid())
- cue->setBackgroundColor(cueData->backgroundColor().rgb());
- if (cueData->foregroundColor().isValid())
- cue->setForegroundColor(cueData->foregroundColor().rgb());
-
- if (cueData->align() == GenericCueData::Start)
- cue->setAlign("start", IGNORE_EXCEPTION);
- else if (cueData->align() == GenericCueData::Middle)
- cue->setAlign("middle", IGNORE_EXCEPTION);
- else if (cueData->align() == GenericCueData::End)
- cue->setAlign("end", IGNORE_EXCEPTION);
- cue->setSnapToLines(false);
-
- if (hasCue(cue.get())) {
- LOG(Media, "InbandTextTrack::addGenericCue ignoring already added cue: start=%.2f, end=%.2f, content=\"%s\"\n",
- cueData->startTime(), cueData->endTime(), cueData->content().utf8().data());
- return;
- }
-
- addCue(cue);
-}
-
-void InbandTextTrack::addWebVTTCue(InbandTextTrackPrivate* trackPrivate, double start, double end, const String& id, const String& content, const String& settings)
+void InbandTextTrack::addWebVTTCue(double start, double end, const WebString& id, const WebString& content, const WebString& settings)
{
- UNUSED_PARAM(trackPrivate);
- ASSERT(trackPrivate == m_private);
-
- RefPtr<TextTrackCue> cue = TextTrackCue::create(scriptExecutionContext(), start, end, content);
+ RefPtr<VTTCue> cue = VTTCue::create(document(), start, end, content);
cue->setId(id);
- cue->setCueSettings(settings);
-
- if (hasCue(cue.get()))
- return;
-
+ cue->parseSettings(settings);
addCue(cue);
}
diff --git a/chromium/third_party/WebKit/Source/core/html/track/InbandTextTrack.h b/chromium/third_party/WebKit/Source/core/html/track/InbandTextTrack.h
index 5707249eb67..83948f0e77a 100644
--- a/chromium/third_party/WebKit/Source/core/html/track/InbandTextTrack.h
+++ b/chromium/third_party/WebKit/Source/core/html/track/InbandTextTrack.h
@@ -27,36 +27,34 @@
#define InbandTextTrack_h
#include "core/html/track/TextTrack.h"
-#include "core/platform/graphics/InbandTextTrackPrivateClient.h"
+#include "public/platform/WebInbandTextTrackClient.h"
#include "wtf/RefPtr.h"
+namespace blink {
+class WebInbandTextTrack;
+class WebString;
+}
+
namespace WebCore {
class Document;
-class InbandTextTrackPrivate;
class MediaPlayer;
class TextTrackCue;
-class InbandTextTrack : public TextTrack, public InbandTextTrackPrivateClient {
+class InbandTextTrack : public TextTrack, public blink::WebInbandTextTrackClient {
public:
- static PassRefPtr<InbandTextTrack> create(ScriptExecutionContext*, TextTrackClient*, PassRefPtr<InbandTextTrackPrivate>);
+ static PassRefPtr<InbandTextTrack> create(Document&, TextTrackClient*, blink::WebInbandTextTrack*);
virtual ~InbandTextTrack();
- virtual bool isClosedCaptions() const OVERRIDE;
- virtual bool containsOnlyForcedSubtitles() const OVERRIDE;
- virtual bool isMainProgramContent() const OVERRIDE;
- virtual bool isEasyToRead() const OVERRIDE;
- virtual void setMode(const AtomicString&) OVERRIDE;
size_t inbandTrackIndex();
void trackRemoved();
private:
- InbandTextTrack(ScriptExecutionContext*, TextTrackClient*, PassRefPtr<InbandTextTrackPrivate>);
+ InbandTextTrack(Document&, TextTrackClient*, blink::WebInbandTextTrack*);
- virtual void addGenericCue(InbandTextTrackPrivate*, GenericCueData*) OVERRIDE;
- virtual void addWebVTTCue(InbandTextTrackPrivate*, double, double, const String&, const String&, const String&) OVERRIDE;
+ virtual void addWebVTTCue(double, double, const blink::WebString&, const blink::WebString&, const blink::WebString&) OVERRIDE;
- RefPtr<InbandTextTrackPrivate> m_private;
+ blink::WebInbandTextTrack* m_webTrack;
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/html/track/LoadableTextTrack.cpp b/chromium/third_party/WebKit/Source/core/html/track/LoadableTextTrack.cpp
index 9ccb64b53af..588c06c79ff 100644
--- a/chromium/third_party/WebKit/Source/core/html/track/LoadableTextTrack.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/track/LoadableTextTrack.cpp
@@ -24,17 +24,16 @@
*/
#include "config.h"
-
#include "core/html/track/LoadableTextTrack.h"
#include "core/html/HTMLTrackElement.h"
#include "core/html/track/TextTrackCueList.h"
-#include "core/html/track/TextTrackRegionList.h"
+#include "core/html/track/vtt/VTTRegionList.h"
namespace WebCore {
-LoadableTextTrack::LoadableTextTrack(HTMLTrackElement* track, const String& kind, const String& label, const String& language)
- : TextTrack(&track->document(), track, kind, label, language, TrackElement)
+LoadableTextTrack::LoadableTextTrack(HTMLTrackElement* track)
+ : TextTrack(track->document(), track, emptyAtom, emptyAtom, emptyAtom, emptyAtom, TrackElement)
, m_trackElement(track)
, m_loadTimer(this, &LoadableTextTrack::loadTimerFired)
, m_isDefault(false)
@@ -89,16 +88,16 @@ void LoadableTextTrack::loadTimerFired(Timer<LoadableTextTrack>*)
// 4. Download: If URL is not the empty string, perform a potentially CORS-enabled fetch of URL, with the
// mode being the state of the media element's crossorigin content attribute, the origin being the
// origin of the media element's Document, and the default origin behaviour set to fail.
- m_loader = TextTrackLoader::create(this, static_cast<ScriptExecutionContext*>(&m_trackElement->document()));
+ m_loader = TextTrackLoader::create(*this, m_trackElement->document());
if (!m_loader->load(m_url, m_trackElement->mediaElementCrossOriginAttribute()))
- m_trackElement->didCompleteLoad(this, HTMLTrackElement::Failure);
+ m_trackElement->didCompleteLoad(HTMLTrackElement::Failure);
}
void LoadableTextTrack::newCuesAvailable(TextTrackLoader* loader)
{
ASSERT_UNUSED(loader, m_loader == loader);
- Vector<RefPtr<TextTrackCue> > newCues;
+ Vector<RefPtr<VTTCue> > newCues;
m_loader->getNewCues(newCues);
if (!m_cues)
@@ -113,11 +112,6 @@ void LoadableTextTrack::newCuesAvailable(TextTrackLoader* loader)
client()->textTrackAddCues(this, m_cues.get());
}
-void LoadableTextTrack::cueLoadingStarted(TextTrackLoader* loader)
-{
- ASSERT_UNUSED(loader, m_loader == loader);
-}
-
void LoadableTextTrack::cueLoadingCompleted(TextTrackLoader* loader, bool loadingFailed)
{
ASSERT_UNUSED(loader, m_loader == loader);
@@ -125,23 +119,21 @@ void LoadableTextTrack::cueLoadingCompleted(TextTrackLoader* loader, bool loadin
if (!m_trackElement)
return;
- m_trackElement->didCompleteLoad(this, loadingFailed ? HTMLTrackElement::Failure : HTMLTrackElement::Success);
+ m_trackElement->didCompleteLoad(loadingFailed ? HTMLTrackElement::Failure : HTMLTrackElement::Success);
}
-#if ENABLE(WEBVTT_REGIONS)
void LoadableTextTrack::newRegionsAvailable(TextTrackLoader* loader)
{
ASSERT_UNUSED(loader, m_loader == loader);
- Vector<RefPtr<TextTrackRegion> > newRegions;
+ Vector<RefPtr<VTTRegion> > newRegions;
m_loader->getNewRegions(newRegions);
for (size_t i = 0; i < newRegions.size(); ++i) {
newRegions[i]->setTrack(this);
- regionList()->add(newRegions[i]);
+ regions()->add(newRegions[i]);
}
}
-#endif
size_t LoadableTextTrack::trackElementIndex()
{
diff --git a/chromium/third_party/WebKit/Source/core/html/track/LoadableTextTrack.h b/chromium/third_party/WebKit/Source/core/html/track/LoadableTextTrack.h
index d28c1042632..487e7caab78 100644
--- a/chromium/third_party/WebKit/Source/core/html/track/LoadableTextTrack.h
+++ b/chromium/third_party/WebKit/Source/core/html/track/LoadableTextTrack.h
@@ -35,25 +35,18 @@ namespace WebCore {
class HTMLTrackElement;
class LoadableTextTrack;
-class LoadableTextTrackClient : public TextTrackClient {
-public:
- virtual ~LoadableTextTrackClient() { }
-
- virtual bool canLoadUrl(LoadableTextTrack*, const KURL&) { return false; }
- virtual void loadingCompleted(LoadableTextTrack*, bool /* loadingFailed */) { }
-};
-
class LoadableTextTrack : public TextTrack, private TextTrackLoaderClient {
public:
- static PassRefPtr<LoadableTextTrack> create(HTMLTrackElement* track, const String& kind, const String& label, const String& language)
+ static PassRefPtr<LoadableTextTrack> create(HTMLTrackElement* track)
{
- return adoptRef(new LoadableTextTrack(track, kind, label, language));
+ return adoptRef(new LoadableTextTrack(track));
}
virtual ~LoadableTextTrack();
void scheduleLoad(const KURL&);
- virtual void clearClient();
+ // This shadows TextTrack::clearClient, but need not be virtual.
+ void clearClient();
size_t trackElementIndex();
HTMLTrackElement* trackElement() { return m_trackElement; }
@@ -63,15 +56,11 @@ public:
private:
// TextTrackLoaderClient
- virtual bool shouldLoadCues(TextTrackLoader*) { return true; }
- virtual void newCuesAvailable(TextTrackLoader*);
- virtual void cueLoadingStarted(TextTrackLoader*);
- virtual void cueLoadingCompleted(TextTrackLoader*, bool loadingFailed);
-#if ENABLE(WEBVTT_REGIONS)
- virtual void newRegionsAvailable(TextTrackLoader*);
-#endif
+ virtual void newCuesAvailable(TextTrackLoader*) OVERRIDE;
+ virtual void cueLoadingCompleted(TextTrackLoader*, bool loadingFailed) OVERRIDE;
+ virtual void newRegionsAvailable(TextTrackLoader*) OVERRIDE;
- LoadableTextTrack(HTMLTrackElement*, const String& kind, const String& label, const String& language);
+ LoadableTextTrack(HTMLTrackElement*);
void loadTimerFired(Timer<LoadableTextTrack>*);
diff --git a/chromium/third_party/WebKit/Source/core/html/track/TextTrack.cpp b/chromium/third_party/WebKit/Source/core/html/track/TextTrack.cpp
index 6a392efa8f5..84dea3e44a3 100644
--- a/chromium/third_party/WebKit/Source/core/html/track/TextTrack.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/track/TextTrack.cpp
@@ -32,13 +32,16 @@
#include "config.h"
#include "core/html/track/TextTrack.h"
+#include "RuntimeEnabledFeatures.h"
+#include "bindings/v8/ExceptionState.h"
#include "bindings/v8/ExceptionStatePlaceholder.h"
+#include "core/dom/Document.h"
#include "core/dom/ExceptionCode.h"
#include "core/html/HTMLMediaElement.h"
#include "core/html/track/TextTrackCueList.h"
#include "core/html/track/TextTrackList.h"
-#include "core/html/track/TextTrackRegion.h"
-#include "core/html/track/TextTrackRegionList.h"
+#include "core/html/track/vtt/VTTRegion.h"
+#include "core/html/track/vtt/VTTRegionList.h"
namespace WebCore {
@@ -92,16 +95,16 @@ const AtomicString& TextTrack::showingKeyword()
return ended;
}
-TextTrack::TextTrack(ScriptExecutionContext* context, TextTrackClient* client, const AtomicString& kind, const AtomicString& label, const AtomicString& language, TextTrackType type)
- : TrackBase(context, TrackBase::TextTrack)
+TextTrack::TextTrack(Document& document, TextTrackClient* client, const AtomicString& kind, const AtomicString& label, const AtomicString& language, const AtomicString& id, TextTrackType type)
+ : TrackBase(TrackBase::TextTrack)
, m_cues(0)
-#if ENABLE(WEBVTT_REGIONS)
, m_regions(0)
-#endif
+ , m_document(&document)
, m_mediaElement(0)
, m_label(label)
, m_language(language)
- , m_mode(disabledKeyword().string())
+ , m_id(id)
+ , m_mode(disabledKeyword())
, m_client(client)
, m_trackType(type)
, m_readinessState(NotLoaded)
@@ -123,12 +126,10 @@ TextTrack::~TextTrack()
m_cues->item(i)->setTrack(0);
}
-#if ENABLE(WEBVTT_REGIONS)
if (m_regions) {
for (size_t i = 0; i < m_regions->length(); ++i)
m_regions->item(i)->setTrack(0);
}
-#endif
clearClient();
}
@@ -163,11 +164,10 @@ void TextTrack::setKind(const AtomicString& kind)
void TextTrack::setMode(const AtomicString& mode)
{
+ ASSERT(mode == disabledKeyword() || mode == hiddenKeyword() || mode == showingKeyword());
+
// On setting, if the new value isn't equal to what the attribute would currently
// return, the new value must be processed as follows ...
- if (mode != disabledKeyword() && mode != hiddenKeyword() && mode != showingKeyword())
- return;
-
if (m_mode == mode)
return;
@@ -254,7 +254,7 @@ void TextTrack::addCue(PassRefPtr<TextTrackCue> prpCue)
m_client->textTrackAddCue(this, cue.get());
}
-void TextTrack::removeCue(TextTrackCue* cue, ExceptionState& es)
+void TextTrack::removeCue(TextTrackCue* cue, ExceptionState& exceptionState)
{
if (!cue)
return;
@@ -266,13 +266,13 @@ void TextTrack::removeCue(TextTrackCue* cue, ExceptionState& es)
// 1. If the given cue is not currently listed in the method's TextTrack
// object's text track's text track list of cues, then throw a NotFoundError exception.
if (cue->track() != this) {
- es.throwDOMException(NotFoundError);
+ exceptionState.throwDOMException(NotFoundError, "The specified cue is not listed in the TextTrack's list of cues.");
return;
}
// 2. Remove cue from the method's TextTrack object's text track's text track list of cues.
if (!m_cues || !m_cues->remove(cue)) {
- es.throwDOMException(InvalidStateError);
+ exceptionState.throwDOMException(InvalidStateError, "Failed to remove the specified cue.");
return;
}
@@ -281,41 +281,34 @@ void TextTrack::removeCue(TextTrackCue* cue, ExceptionState& es)
m_client->textTrackRemoveCue(this, cue);
}
-#if ENABLE(WEBVTT_REGIONS)
-TextTrackRegionList* TextTrack::regionList()
-{
- return ensureTextTrackRegionList();
-}
-
-TextTrackRegionList* TextTrack::ensureTextTrackRegionList()
+VTTRegionList* TextTrack::ensureVTTRegionList()
{
if (!m_regions)
- m_regions = TextTrackRegionList::create();
+ m_regions = VTTRegionList::create();
return m_regions.get();
}
-TextTrackRegionList* TextTrack::regions()
+VTTRegionList* TextTrack::regions()
{
// If the text track mode of the text track that the TextTrack object
// represents is not the text track disabled mode, then the regions
- // attribute must return a live TextTrackRegionList object that represents
+ // attribute must return a live VTTRegionList object that represents
// the text track list of regions of the text track. Otherwise, it must
// return null. When an object is returned, the same object must be returned
// each time.
- if (m_mode != disabledKeyword())
- return ensureTextTrackRegionList();
-
+ if (RuntimeEnabledFeatures::webVTTRegionsEnabled() && m_mode != disabledKeyword())
+ return ensureVTTRegionList();
return 0;
}
-void TextTrack::addRegion(PassRefPtr<TextTrackRegion> prpRegion)
+void TextTrack::addRegion(PassRefPtr<VTTRegion> prpRegion)
{
if (!prpRegion)
return;
- RefPtr<TextTrackRegion> region = prpRegion;
- TextTrackRegionList* regionList = ensureTextTrackRegionList();
+ RefPtr<VTTRegion> region = prpRegion;
+ VTTRegionList* regionList = ensureVTTRegionList();
// 1. If the given region is in a text track list of regions, then remove
// region from that text track list of regions.
@@ -327,7 +320,7 @@ void TextTrack::addRegion(PassRefPtr<TextTrackRegion> prpRegion)
// a region with the same identifier as region replace the values of that
// region's width, height, anchor point, viewport anchor point and scroll
// attributes with those of region.
- TextTrackRegion* existingRegion = regionList->getRegionById(region->id());
+ VTTRegion* existingRegion = regionList->getRegionById(region->id());
if (existingRegion) {
existingRegion->updateParametersFromRegion(region.get());
return;
@@ -339,7 +332,7 @@ void TextTrack::addRegion(PassRefPtr<TextTrackRegion> prpRegion)
regionList->add(region);
}
-void TextTrack::removeRegion(TextTrackRegion* region, ExceptionState &es)
+void TextTrack::removeRegion(VTTRegion* region, ExceptionState &exceptionState)
{
if (!region)
return;
@@ -347,18 +340,17 @@ void TextTrack::removeRegion(TextTrackRegion* region, ExceptionState &es)
// 1. If the given region is not currently listed in the method's TextTrack
// object's text track list of regions, then throw a NotFoundError exception.
if (region->track() != this) {
- es.throwDOMException(NotFoundError);
+ exceptionState.throwDOMException(NotFoundError, "The specified region is not listed in the TextTrack's list of regions.");
return;
}
if (!m_regions || !m_regions->remove(region)) {
- es.throwDOMException(InvalidStateError);
+ exceptionState.throwDOMException(InvalidStateError, "Failed to remove the specified region.");
return;
}
region->setTrack(0);
}
-#endif
void TextTrack::cueWillChange(TextTrackCue* cue)
{
@@ -427,71 +419,14 @@ int TextTrack::trackIndexRelativeToRenderedTracks()
return m_renderedTrackIndex;
}
-bool TextTrack::hasCue(TextTrackCue* cue)
+const AtomicString& TextTrack::interfaceName() const
{
- if (cue->startTime() < 0 || cue->endTime() < 0)
- return false;
-
- if (!m_cues || !m_cues->length())
- return false;
-
- size_t searchStart = 0;
- size_t searchEnd = m_cues->length();
-
- while (1) {
- ASSERT(searchStart <= m_cues->length());
- ASSERT(searchEnd <= m_cues->length());
-
- TextTrackCue* existingCue;
-
- // Cues in the TextTrackCueList are maintained in start time order.
- if (searchStart == searchEnd) {
- if (!searchStart)
- return false;
-
- // If there is more than one cue with the same start time, back up to first one so we
- // consider all of them.
- while (searchStart >= 2 && cue->startTime() == m_cues->item(searchStart - 2)->startTime())
- --searchStart;
-
- bool firstCompare = true;
- while (1) {
- if (!firstCompare)
- ++searchStart;
- firstCompare = false;
- if (searchStart > m_cues->length())
- return false;
-
- existingCue = m_cues->item(searchStart - 1);
- if (!existingCue || cue->startTime() > existingCue->startTime())
- return false;
-
- if (*existingCue != *cue)
- continue;
-
- return true;
- }
- }
-
- size_t index = (searchStart + searchEnd) / 2;
- existingCue = m_cues->item(index);
- if (cue->startTime() < existingCue->startTime() || (cue->startTime() == existingCue->startTime() && cue->endTime() > existingCue->endTime()))
- searchEnd = index;
- else
- searchStart = index + 1;
- }
-
- ASSERT_NOT_REACHED();
- return false;
+ return EventTargetNames::TextTrack;
}
-bool TextTrack::isMainProgramContent() const
+ExecutionContext* TextTrack::executionContext() const
{
- // "Main program" content is intrinsic to the presentation of the media file, regardless of locale. Content such as
- // directors commentary is not "main program" because it is not essential for the presentation. HTML5 doesn't have
- // a way to express this in a machine-reable form, it is typically done with the track label, so we assume that caption
- // tracks are main content and all other track types are not.
- return m_kind == captionsKeyword();
+ return m_document;
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/html/track/TextTrack.h b/chromium/third_party/WebKit/Source/core/html/track/TextTrack.h
index c16b447273a..721c55566b0 100644
--- a/chromium/third_party/WebKit/Source/core/html/track/TextTrack.h
+++ b/chromium/third_party/WebKit/Source/core/html/track/TextTrack.h
@@ -33,15 +33,14 @@
namespace WebCore {
+class Document;
class ExceptionState;
class HTMLMediaElement;
class TextTrack;
class TextTrackCue;
class TextTrackCueList;
-#if ENABLE(WEBVTT_REGIONS)
-class TextTrackRegion;
-class TextTrackRegionList;
-#endif
+class VTTRegion;
+class VTTRegionList;
class TextTrackClient {
public:
@@ -56,16 +55,16 @@ public:
class TextTrack : public TrackBase, public ScriptWrappable {
public:
- static PassRefPtr<TextTrack> create(ScriptExecutionContext* context, TextTrackClient* client, const AtomicString& kind, const AtomicString& label, const AtomicString& language)
+ static PassRefPtr<TextTrack> create(Document& document, TextTrackClient* client, const AtomicString& kind, const AtomicString& label, const AtomicString& language)
{
- return adoptRef(new TextTrack(context, client, kind, label, language, AddTrack));
+ return adoptRef(new TextTrack(document, client, kind, label, language, emptyAtom, AddTrack));
}
virtual ~TextTrack();
void setMediaElement(HTMLMediaElement* element) { m_mediaElement = element; }
HTMLMediaElement* mediaElement() { return m_mediaElement; }
- AtomicString kind() const { return m_kind; }
+ const AtomicString& kind() const { return m_kind; }
void setKind(const AtomicString&);
static const AtomicString& subtitlesKeyword();
@@ -81,12 +80,15 @@ public:
AtomicString language() const { return m_language; }
void setLanguage(const AtomicString& language) { m_language = language; }
+ AtomicString id() const { return m_id; }
+ void setId(const AtomicString& id) { m_id = id; }
+
static const AtomicString& disabledKeyword();
static const AtomicString& hiddenKeyword();
static const AtomicString& showingKeyword();
AtomicString mode() const { return m_mode; }
- virtual void setMode(const AtomicString&);
+ void setMode(const AtomicString&);
enum ReadinessState { NotLoaded = 0, Loading = 1, Loaded = 2, FailedToLoad = 3 };
ReadinessState readinessState() const { return m_readinessState; }
@@ -100,13 +102,10 @@ public:
void addCue(PassRefPtr<TextTrackCue>);
void removeCue(TextTrackCue*, ExceptionState&);
- bool hasCue(TextTrackCue*);
-#if ENABLE(WEBVTT_REGIONS)
- TextTrackRegionList* regions();
- void addRegion(PassRefPtr<TextTrackRegion>);
- void removeRegion(TextTrackRegion*, ExceptionState&);
-#endif
+ VTTRegionList* regions();
+ void addRegion(PassRefPtr<VTTRegion>);
+ void removeRegion(VTTRegion*, ExceptionState&);
void cueWillChange(TextTrackCue*);
void cueDidChange(TextTrackCue*);
@@ -116,12 +115,6 @@ public:
enum TextTrackType { TrackElement, AddTrack, InBand };
TextTrackType trackType() const { return m_trackType; }
- virtual bool isClosedCaptions() const { return false; }
-
- virtual bool containsOnlyForcedSubtitles() const { return false; }
- virtual bool isMainProgramContent() const;
- virtual bool isEasyToRead() const { return false; }
-
int trackIndex();
void invalidateTrackIndex();
@@ -136,27 +129,31 @@ public:
void removeAllCues();
+ Document& document() const { return *m_document; }
+
+ // EventTarget methods
+ virtual const AtomicString& interfaceName() const OVERRIDE;
+ virtual ExecutionContext* executionContext() const OVERRIDE;
+
protected:
- TextTrack(ScriptExecutionContext*, TextTrackClient*, const AtomicString& kind, const AtomicString& label, const AtomicString& language, TextTrackType);
-#if ENABLE(WEBVTT_REGIONS)
- TextTrackRegionList* regionList();
-#endif
+ TextTrack(Document&, TextTrackClient*, const AtomicString& kind, const AtomicString& label, const AtomicString& language, const AtomicString& id, TextTrackType);
RefPtr<TextTrackCueList> m_cues;
private:
-
-#if ENABLE(WEBVTT_REGIONS)
- TextTrackRegionList* ensureTextTrackRegionList();
- RefPtr<TextTrackRegionList> m_regions;
-#endif
+ VTTRegionList* ensureVTTRegionList();
+ RefPtr<VTTRegionList> m_regions;
TextTrackCueList* ensureTextTrackCueList();
+ // FIXME: Remove this pointer and get the Document from m_client
+ Document* m_document;
+
HTMLMediaElement* m_mediaElement;
AtomicString m_kind;
AtomicString m_label;
AtomicString m_language;
+ AtomicString m_id;
AtomicString m_mode;
TextTrackClient* m_client;
TextTrackType m_trackType;
diff --git a/chromium/third_party/WebKit/Source/core/html/track/TextTrack.idl b/chromium/third_party/WebKit/Source/core/html/track/TextTrack.idl
index 10679016bb8..a64462d028f 100644
--- a/chromium/third_party/WebKit/Source/core/html/track/TextTrack.idl
+++ b/chromium/third_party/WebKit/Source/core/html/track/TextTrack.idl
@@ -23,23 +23,29 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
+enum TextTrackMode { "disabled", "hidden", "showing" };
+enum TextTrackKind { "subtitles", "captions", "descriptions", "chapters", "metadata" };
+
[
- EnabledAtRuntime=VideoTrack
+ RuntimeEnabled=VideoTrack
] interface TextTrack : EventTarget {
- readonly attribute DOMString kind;
+ readonly attribute TextTrackKind kind;
readonly attribute DOMString label;
readonly attribute DOMString language;
- attribute DOMString mode;
+ readonly attribute DOMString id;
+
+ attribute TextTrackMode mode;
readonly attribute TextTrackCueList cues;
readonly attribute TextTrackCueList activeCues;
- attribute EventHandler oncuechange;
void addCue(TextTrackCue cue);
[RaisesException] void removeCue(TextTrackCue cue);
- [Conditional=WEBVTT_REGIONS] readonly attribute TextTrackRegionList regions;
- [Conditional=WEBVTT_REGIONS] void addRegion(TextTrackRegion region);
- [RaisesException, Conditional=WEBVTT_REGIONS] void removeRegion(TextTrackRegion region);
+ attribute EventHandler oncuechange;
+
+ [RuntimeEnabled=WebVTTRegions] readonly attribute VTTRegionList regions;
+ [RuntimeEnabled=WebVTTRegions] void addRegion(VTTRegion region);
+ [RaisesException, RuntimeEnabled=WebVTTRegions] void removeRegion(VTTRegion region);
};
diff --git a/chromium/third_party/WebKit/Source/core/html/track/TextTrackCue.cpp b/chromium/third_party/WebKit/Source/core/html/track/TextTrackCue.cpp
index b4ddc64c93d..cfb2effe24b 100644
--- a/chromium/third_party/WebKit/Source/core/html/track/TextTrackCue.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/track/TextTrackCue.cpp
@@ -30,213 +30,35 @@
*/
#include "config.h"
-
#include "core/html/track/TextTrackCue.h"
-#include "CSSPropertyNames.h"
-#include "CSSValueKeywords.h"
+#include "bindings/v8/ExceptionMessages.h"
#include "bindings/v8/ExceptionStatePlaceholder.h"
-#include "core/dom/DocumentFragment.h"
-#include "core/dom/Event.h"
-#include "core/dom/NodeTraversal.h"
-#include "core/html/HTMLDivElement.h"
+#include "core/events/Event.h"
#include "core/html/track/TextTrack.h"
#include "core/html/track/TextTrackCueList.h"
-#include "core/html/track/TextTrackRegionList.h"
-#include "core/html/track/WebVTTElement.h"
-#include "core/html/track/WebVTTParser.h"
-#include "core/rendering/RenderTextTrackCue.h"
-#include "wtf/MathExtras.h"
-#include "wtf/text/StringBuilder.h"
namespace WebCore {
static const int invalidCueIndex = -1;
-static const int undefinedPosition = -1;
-static const int autoSize = 0;
-
-static const String& startKeyword()
-{
- DEFINE_STATIC_LOCAL(const String, start, ("start"));
- return start;
-}
-
-static const String& middleKeyword()
-{
- DEFINE_STATIC_LOCAL(const String, middle, ("middle"));
- return middle;
-}
-
-static const String& endKeyword()
-{
- DEFINE_STATIC_LOCAL(const String, end, ("end"));
- return end;
-}
-
-static const String& horizontalKeyword()
-{
- return emptyString();
-}
-
-static const String& verticalGrowingLeftKeyword()
-{
- DEFINE_STATIC_LOCAL(const String, verticalrl, ("rl"));
- return verticalrl;
-}
-
-static const String& verticalGrowingRightKeyword()
-{
- DEFINE_STATIC_LOCAL(const String, verticallr, ("lr"));
- return verticallr;
-}
-
-// ----------------------------
-TextTrackCueBox::TextTrackCueBox(Document& document, TextTrackCue* cue)
- : HTMLDivElement(divTag, document)
- , m_cue(cue)
+bool TextTrackCue::isInfiniteOrNonNumber(double value, ExceptionState& exceptionState)
{
- setPart(textTrackCueBoxShadowPseudoId());
-}
-
-TextTrackCue* TextTrackCueBox::getCue() const
-{
- return m_cue;
-}
-
-void TextTrackCueBox::applyCSSProperties(const IntSize&)
-{
- // FIXME: Apply all the initial CSS positioning properties. http://wkb.ug/79916
-#if ENABLE(WEBVTT_REGIONS)
- if (!m_cue->regionId().isEmpty()) {
- setInlineStyleProperty(CSSPropertyPosition, CSSValueRelative);
- return;
- }
-#endif
-
- // 3.5.1 On the (root) List of WebVTT Node Objects:
-
- // the 'position' property must be set to 'absolute'
- setInlineStyleProperty(CSSPropertyPosition, CSSValueAbsolute);
-
- // the 'unicode-bidi' property must be set to 'plaintext'
- setInlineStyleProperty(CSSPropertyUnicodeBidi, CSSValueWebkitPlaintext);
-
- // the 'direction' property must be set to direction
- setInlineStyleProperty(CSSPropertyDirection, m_cue->getCSSWritingDirection());
-
- // the 'writing-mode' property must be set to writing-mode
- setInlineStyleProperty(CSSPropertyWebkitWritingMode, m_cue->getCSSWritingMode());
-
- std::pair<float, float> position = m_cue->getCSSPosition();
-
- // the 'top' property must be set to top,
- setInlineStyleProperty(CSSPropertyTop, position.second, CSSPrimitiveValue::CSS_PERCENTAGE);
-
- // the 'left' property must be set to left
- setInlineStyleProperty(CSSPropertyLeft, position.first, CSSPrimitiveValue::CSS_PERCENTAGE);
-
- // the 'width' property must be set to width, and the 'height' property must be set to height
- if (m_cue->vertical() == horizontalKeyword()) {
- setInlineStyleProperty(CSSPropertyWidth, static_cast<double>(m_cue->getCSSSize()), CSSPrimitiveValue::CSS_PERCENTAGE);
- setInlineStyleProperty(CSSPropertyHeight, CSSValueAuto);
- } else {
- setInlineStyleProperty(CSSPropertyWidth, CSSValueAuto);
- setInlineStyleProperty(CSSPropertyHeight, static_cast<double>(m_cue->getCSSSize()), CSSPrimitiveValue::CSS_PERCENTAGE);
+ if (!std::isfinite(value)) {
+ exceptionState.throwTypeError(ExceptionMessages::notAFiniteNumber(value));
+ return true;
}
-
- // The 'text-align' property on the (root) List of WebVTT Node Objects must
- // be set to the value in the second cell of the row of the table below
- // whose first cell is the value of the corresponding cue's text track cue
- // alignment:
- if (m_cue->align() == startKeyword())
- setInlineStyleProperty(CSSPropertyTextAlign, CSSValueStart);
- else if (m_cue->align() == endKeyword())
- setInlineStyleProperty(CSSPropertyTextAlign, CSSValueEnd);
- else
- setInlineStyleProperty(CSSPropertyTextAlign, CSSValueCenter);
-
- if (!m_cue->snapToLines()) {
- // 10.13.1 Set up x and y:
- // Note: x and y are set through the CSS left and top above.
-
- // 10.13.2 Position the boxes in boxes such that the point x% along the
- // width of the bounding box of the boxes in boxes is x% of the way
- // across the width of the video's rendering area, and the point y%
- // along the height of the bounding box of the boxes in boxes is y%
- // of the way across the height of the video's rendering area, while
- // maintaining the relative positions of the boxes in boxes to each
- // other.
- setInlineStyleProperty(CSSPropertyWebkitTransform,
- String::format("translate(-%.2f%%, -%.2f%%)", position.first, position.second));
-
- setInlineStyleProperty(CSSPropertyWhiteSpace, CSSValuePre);
- }
-}
-
-const AtomicString& TextTrackCueBox::textTrackCueBoxShadowPseudoId()
-{
- DEFINE_STATIC_LOCAL(const AtomicString, trackDisplayBoxShadowPseudoId, ("-webkit-media-text-track-display", AtomicString::ConstructFromLiteral));
- return trackDisplayBoxShadowPseudoId;
+ return false;
}
-RenderObject* TextTrackCueBox::createRenderer(RenderStyle*)
-{
- return new RenderTextTrackCue(this);
-}
-
-// ----------------------------
-
-TextTrackCue::TextTrackCue(ScriptExecutionContext* context, double start, double end, const String& content)
+TextTrackCue::TextTrackCue(double start, double end)
: m_startTime(start)
, m_endTime(end)
- , m_content(content)
- , m_linePosition(undefinedPosition)
- , m_computedLinePosition(undefinedPosition)
- , m_textPosition(50)
- , m_cueSize(100)
, m_cueIndex(invalidCueIndex)
- , m_writingDirection(Horizontal)
- , m_cueAlignment(Middle)
- , m_webVTTNodeTree(0)
, m_track(0)
- , m_scriptExecutionContext(context)
, m_isActive(false)
, m_pauseOnExit(false)
- , m_snapToLines(true)
- , m_cueBackgroundBox(HTMLDivElement::create(*toDocument(context)))
- , m_displayTreeShouldChange(true)
- , m_displayDirection(CSSValueLtr)
-{
- ASSERT(m_scriptExecutionContext->isDocument());
- ScriptWrappable::init(this);
-
- // 4. If the text track cue writing direction is horizontal, then let
- // writing-mode be 'horizontal-tb'. Otherwise, if the text track cue writing
- // direction is vertical growing left, then let writing-mode be
- // 'vertical-rl'. Otherwise, the text track cue writing direction is
- // vertical growing right; let writing-mode be 'vertical-lr'.
- m_displayWritingModeMap[Horizontal] = CSSValueHorizontalTb;
- m_displayWritingModeMap[VerticalGrowingLeft] = CSSValueVerticalRl;
- m_displayWritingModeMap[VerticalGrowingRight] = CSSValueVerticalLr;
-}
-
-TextTrackCue::~TextTrackCue()
-{
- displayTreeInternal()->remove(ASSERT_NO_EXCEPTION);
-}
-
-PassRefPtr<TextTrackCueBox> TextTrackCue::createDisplayTree()
{
- ASSERT(ownerDocument());
- return TextTrackCueBox::create(*ownerDocument(), this);
-}
-
-PassRefPtr<TextTrackCueBox> TextTrackCue::displayTreeInternal()
-{
- if (!m_displayTree)
- m_displayTree = createDisplayTree();
- return m_displayTree;
}
void TextTrackCue::cueWillChange()
@@ -249,8 +71,6 @@ void TextTrackCue::cueDidChange()
{
if (m_track)
m_track->cueDidChange(this);
-
- m_displayTreeShouldChange = true;
}
TextTrack* TextTrackCue::track() const
@@ -273,13 +93,11 @@ void TextTrackCue::setId(const String& id)
cueDidChange();
}
-void TextTrackCue::setStartTime(double value, ExceptionState& es)
+void TextTrackCue::setStartTime(double value, ExceptionState& exceptionState)
{
// NaN, Infinity and -Infinity values should trigger a TypeError.
- if (std::isinf(value) || std::isnan(value)) {
- es.throwTypeError();
+ if (isInfiniteOrNonNumber(value, exceptionState))
return;
- }
// TODO(93143): Add spec-compliant behavior for negative time values.
if (m_startTime == value || value < 0)
@@ -290,13 +108,11 @@ void TextTrackCue::setStartTime(double value, ExceptionState& es)
cueDidChange();
}
-void TextTrackCue::setEndTime(double value, ExceptionState& es)
+void TextTrackCue::setEndTime(double value, ExceptionState& exceptionState)
{
// NaN, Infinity and -Infinity values should trigger a TypeError.
- if (std::isinf(value) || std::isnan(value)) {
- es.throwTypeError();
+ if (isInfiniteOrNonNumber(value, exceptionState))
return;
- }
// TODO(93143): Add spec-compliant behavior for negative time values.
if (m_endTime == value || value < 0)
@@ -317,169 +133,6 @@ void TextTrackCue::setPauseOnExit(bool value)
cueDidChange();
}
-const String& TextTrackCue::vertical() const
-{
- switch (m_writingDirection) {
- case Horizontal:
- return horizontalKeyword();
- case VerticalGrowingLeft:
- return verticalGrowingLeftKeyword();
- case VerticalGrowingRight:
- return verticalGrowingRightKeyword();
- default:
- ASSERT_NOT_REACHED();
- return emptyString();
- }
-}
-
-void TextTrackCue::setVertical(const String& value, ExceptionState& es)
-{
- // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#dom-texttrackcue-vertical
- // On setting, the text track cue writing direction must be set to the value given
- // in the first cell of the row in the table above whose second cell is a
- // case-sensitive match for the new value, if any. If none of the values match, then
- // the user agent must instead throw a SyntaxError exception.
-
- WritingDirection direction = m_writingDirection;
- if (value == horizontalKeyword())
- direction = Horizontal;
- else if (value == verticalGrowingLeftKeyword())
- direction = VerticalGrowingLeft;
- else if (value == verticalGrowingRightKeyword())
- direction = VerticalGrowingRight;
- else
- es.throwDOMException(SyntaxError);
-
- if (direction == m_writingDirection)
- return;
-
- cueWillChange();
- m_writingDirection = direction;
- cueDidChange();
-}
-
-void TextTrackCue::setSnapToLines(bool value)
-{
- if (m_snapToLines == value)
- return;
-
- cueWillChange();
- m_snapToLines = value;
- cueDidChange();
-}
-
-void TextTrackCue::setLine(int position, ExceptionState& es)
-{
- // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#dom-texttrackcue-line
- // On setting, if the text track cue snap-to-lines flag is not set, and the new
- // value is negative or greater than 100, then throw an IndexSizeError exception.
- if (!m_snapToLines && (position < 0 || position > 100)) {
- es.throwDOMException(IndexSizeError);
- return;
- }
-
- // Otherwise, set the text track cue line position to the new value.
- if (m_linePosition == position)
- return;
-
- cueWillChange();
- m_linePosition = position;
- m_computedLinePosition = calculateComputedLinePosition();
- cueDidChange();
-}
-
-void TextTrackCue::setPosition(int position, ExceptionState& es)
-{
- // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#dom-texttrackcue-position
- // On setting, if the new value is negative or greater than 100, then throw an IndexSizeError exception.
- // Otherwise, set the text track cue text position to the new value.
- if (position < 0 || position > 100) {
- es.throwDOMException(IndexSizeError);
- return;
- }
-
- // Otherwise, set the text track cue line position to the new value.
- if (m_textPosition == position)
- return;
-
- cueWillChange();
- m_textPosition = position;
- cueDidChange();
-}
-
-void TextTrackCue::setSize(int size, ExceptionState& es)
-{
- // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#dom-texttrackcue-size
- // On setting, if the new value is negative or greater than 100, then throw an IndexSizeError
- // exception. Otherwise, set the text track cue size to the new value.
- if (size < 0 || size > 100) {
- es.throwDOMException(IndexSizeError);
- return;
- }
-
- // Otherwise, set the text track cue line position to the new value.
- if (m_cueSize == size)
- return;
-
- cueWillChange();
- m_cueSize = size;
- cueDidChange();
-}
-
-const String& TextTrackCue::align() const
-{
- switch (m_cueAlignment) {
- case Start:
- return startKeyword();
- case Middle:
- return middleKeyword();
- case End:
- return endKeyword();
- default:
- ASSERT_NOT_REACHED();
- return emptyString();
- }
-}
-
-void TextTrackCue::setAlign(const String& value, ExceptionState& es)
-{
- // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#dom-texttrackcue-align
- // On setting, the text track cue alignment must be set to the value given in the
- // first cell of the row in the table above whose second cell is a case-sensitive
- // match for the new value, if any. If none of the values match, then the user
- // agent must instead throw a SyntaxError exception.
-
- CueAlignment alignment = m_cueAlignment;
- if (value == startKeyword())
- alignment = Start;
- else if (value == middleKeyword())
- alignment = Middle;
- else if (value == endKeyword())
- alignment = End;
- else
- es.throwDOMException(SyntaxError);
-
- if (alignment == m_cueAlignment)
- return;
-
- cueWillChange();
- m_cueAlignment = alignment;
- cueDidChange();
-}
-
-void TextTrackCue::setText(const String& text)
-{
- if (m_content == text)
- return;
-
- cueWillChange();
- // Clear the document fragment but don't bother to create it again just yet as we can do that
- // when it is requested.
- m_webVTTNodeTree = 0;
- m_content = text;
- cueDidChange();
-}
-
int TextTrackCue::cueIndex()
{
if (m_cueIndex == invalidCueIndex)
@@ -493,43 +146,6 @@ void TextTrackCue::invalidateCueIndex()
m_cueIndex = invalidCueIndex;
}
-void TextTrackCue::createWebVTTNodeTree()
-{
- if (!m_webVTTNodeTree)
- m_webVTTNodeTree = WebVTTParser::create(0, m_scriptExecutionContext)->createDocumentFragmentFromCueText(m_content);
-}
-
-void TextTrackCue::copyWebVTTNodeToDOMTree(ContainerNode* webVTTNode, ContainerNode* parent)
-{
- for (Node* node = webVTTNode->firstChild(); node; node = node->nextSibling()) {
- RefPtr<Node> clonedNode;
- if (node->isWebVTTElement())
- clonedNode = toWebVTTElement(node)->createEquivalentHTMLElement(ownerDocument());
- else
- clonedNode = node->cloneNode(false);
- parent->appendChild(clonedNode);
- if (node->isContainerNode())
- copyWebVTTNodeToDOMTree(toContainerNode(node), toContainerNode(clonedNode.get()));
- }
-}
-
-PassRefPtr<DocumentFragment> TextTrackCue::getCueAsHTML()
-{
- createWebVTTNodeTree();
- RefPtr<DocumentFragment> clonedFragment = DocumentFragment::create(*ownerDocument());
- copyWebVTTNodeToDOMTree(m_webVTTNodeTree.get(), clonedFragment.get());
- return clonedFragment.release();
-}
-
-PassRefPtr<DocumentFragment> TextTrackCue::createCueRenderingTree()
-{
- RefPtr<DocumentFragment> clonedFragment;
- createWebVTTNodeTree();
- clonedFragment = DocumentFragment::create(*ownerDocument());
- m_webVTTNodeTree->cloneChildNodes(clonedFragment.get());
- return clonedFragment.release();
-}
-
bool TextTrackCue::dispatchEvent(PassRefPtr<Event> event)
{
// When a TextTrack's mode is disabled: no cues are active, no events fired.
@@ -539,18 +155,6 @@ bool TextTrackCue::dispatchEvent(PassRefPtr<Event> event)
return EventTarget::dispatchEvent(event);
}
-#if ENABLE(WEBVTT_REGIONS)
-void TextTrackCue::setRegionId(const String& regionId)
-{
- if (m_regionId == regionId)
- return;
-
- cueWillChange();
- m_regionId = regionId;
- cueDidChange();
-}
-#endif
-
bool TextTrackCue::isActive()
{
return m_isActive && track() && track()->mode() != TextTrack::disabledKeyword();
@@ -565,629 +169,9 @@ void TextTrackCue::setIsActive(bool active)
removeDisplayTree();
}
-int TextTrackCue::calculateComputedLinePosition()
-{
- // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#text-track-cue-computed-line-position
-
- // If the text track cue line position is numeric, then that is the text
- // track cue computed line position.
- if (m_linePosition != undefinedPosition)
- return m_linePosition;
-
- // If the text track cue snap-to-lines flag of the text track cue is not
- // set, the text track cue computed line position is the value 100;
- if (!m_snapToLines)
- return 100;
-
- // Otherwise, it is the value returned by the following algorithm:
-
- // If cue is not associated with a text track, return -1 and abort these
- // steps.
- if (!track())
- return -1;
-
- // Let n be the number of text tracks whose text track mode is showing or
- // showing by default and that are in the media element's list of text
- // tracks before track.
- int n = track()->trackIndexRelativeToRenderedTracks();
-
- // Increment n by one.
- n++;
-
- // Negate n.
- n = -n;
-
- return n;
-}
-
-static bool isCueParagraphSeparator(UChar character)
-{
- // Within a cue, paragraph boundaries are only denoted by Type B characters,
- // such as U+000A LINE FEED (LF), U+0085 NEXT LINE (NEL), and U+2029 PARAGRAPH SEPARATOR.
- return WTF::Unicode::category(character) & WTF::Unicode::Separator_Paragraph;
-}
-
-void TextTrackCue::determineTextDirection()
-{
- DEFINE_STATIC_LOCAL(const String, rtTag, ("rt"));
- createWebVTTNodeTree();
-
- // Apply the Unicode Bidirectional Algorithm's Paragraph Level steps to the
- // concatenation of the values of each WebVTT Text Object in nodes, in a
- // pre-order, depth-first traversal, excluding WebVTT Ruby Text Objects and
- // their descendants.
- StringBuilder paragraphBuilder;
- for (Node* node = m_webVTTNodeTree->firstChild(); node; node = NodeTraversal::next(node, m_webVTTNodeTree.get())) {
- if (!node->isTextNode() || node->localName() == rtTag)
- continue;
-
- paragraphBuilder.append(node->nodeValue());
- }
-
- String paragraph = paragraphBuilder.toString();
- if (!paragraph.length())
- return;
-
- for (size_t i = 0; i < paragraph.length(); ++i) {
- UChar current = paragraph[i];
- if (!current || isCueParagraphSeparator(current))
- return;
-
- if (UChar current = paragraph[i]) {
- WTF::Unicode::Direction charDirection = WTF::Unicode::direction(current);
- if (charDirection == WTF::Unicode::LeftToRight) {
- m_displayDirection = CSSValueLtr;
- return;
- }
- if (charDirection == WTF::Unicode::RightToLeft
- || charDirection == WTF::Unicode::RightToLeftArabic) {
- m_displayDirection = CSSValueRtl;
- return;
- }
- }
- }
-}
-
-void TextTrackCue::calculateDisplayParameters()
-{
- // Steps 10.2, 10.3
- determineTextDirection();
-
- // 10.4 If the text track cue writing direction is horizontal, then let
- // block-flow be 'tb'. Otherwise, if the text track cue writing direction is
- // vertical growing left, then let block-flow be 'lr'. Otherwise, the text
- // track cue writing direction is vertical growing right; let block-flow be
- // 'rl'.
- m_displayWritingMode = m_displayWritingModeMap[m_writingDirection];
-
- // 10.5 Determine the value of maximum size for cue as per the appropriate
- // rules from the following list:
- int maximumSize = m_textPosition;
- if ((m_writingDirection == Horizontal && m_cueAlignment == Start && m_displayDirection == CSSValueLtr)
- || (m_writingDirection == Horizontal && m_cueAlignment == End && m_displayDirection == CSSValueRtl)
- || (m_writingDirection == VerticalGrowingLeft && m_cueAlignment == Start)
- || (m_writingDirection == VerticalGrowingRight && m_cueAlignment == Start)) {
- maximumSize = 100 - m_textPosition;
- } else if ((m_writingDirection == Horizontal && m_cueAlignment == End && m_displayDirection == CSSValueLtr)
- || (m_writingDirection == Horizontal && m_cueAlignment == Start && m_displayDirection == CSSValueRtl)
- || (m_writingDirection == VerticalGrowingLeft && m_cueAlignment == End)
- || (m_writingDirection == VerticalGrowingRight && m_cueAlignment == End)) {
- maximumSize = m_textPosition;
- } else if (m_cueAlignment == Middle) {
- maximumSize = m_textPosition <= 50 ? m_textPosition : (100 - m_textPosition);
- maximumSize = maximumSize * 2;
- }
-
- // 10.6 If the text track cue size is less than maximum size, then let size
- // be text track cue size. Otherwise, let size be maximum size.
- m_displaySize = std::min(m_cueSize, maximumSize);
-
- // 10.8 Determine the value of x-position or y-position for cue as per the
- // appropriate rules from the following list:
- if (m_writingDirection == Horizontal) {
- if (m_cueAlignment == Start) {
- if (m_displayDirection == CSSValueLtr)
- m_displayPosition.first = m_textPosition;
- else
- m_displayPosition.first = 100 - m_textPosition - m_displaySize;
- } else if (m_cueAlignment == End) {
- if (m_displayDirection == CSSValueRtl)
- m_displayPosition.first = 100 - m_textPosition;
- else
- m_displayPosition.first = m_textPosition - m_displaySize;
- }
- }
-
- if ((m_writingDirection == VerticalGrowingLeft && m_cueAlignment == Start)
- || (m_writingDirection == VerticalGrowingRight && m_cueAlignment == Start)) {
- m_displayPosition.second = m_textPosition;
- } else if ((m_writingDirection == VerticalGrowingLeft && m_cueAlignment == End)
- || (m_writingDirection == VerticalGrowingRight && m_cueAlignment == End)) {
- m_displayPosition.second = 100 - m_textPosition;
- }
-
- if (m_writingDirection == Horizontal && m_cueAlignment == Middle) {
- if (m_displayDirection == CSSValueLtr)
- m_displayPosition.first = m_textPosition - m_displaySize / 2;
- else
- m_displayPosition.first = 100 - m_textPosition - m_displaySize / 2;
- }
-
- if ((m_writingDirection == VerticalGrowingLeft && m_cueAlignment == Middle)
- || (m_writingDirection == VerticalGrowingRight && m_cueAlignment == Middle))
- m_displayPosition.second = m_textPosition - m_displaySize / 2;
-
- // 10.9 Determine the value of whichever of x-position or y-position is not
- // yet calculated for cue as per the appropriate rules from the following
- // list:
- if (m_snapToLines && m_displayPosition.second == undefinedPosition && m_writingDirection == Horizontal)
- m_displayPosition.second = 0;
-
- if (!m_snapToLines && m_displayPosition.second == undefinedPosition && m_writingDirection == Horizontal)
- m_displayPosition.second = m_computedLinePosition;
-
- if (m_snapToLines && m_displayPosition.first == undefinedPosition
- && (m_writingDirection == VerticalGrowingLeft || m_writingDirection == VerticalGrowingRight))
- m_displayPosition.first = 0;
-
- if (!m_snapToLines && (m_writingDirection == VerticalGrowingLeft || m_writingDirection == VerticalGrowingRight))
- m_displayPosition.first = m_computedLinePosition;
-
- // A text track cue has a text track cue computed line position whose value
- // is defined in terms of the other aspects of the cue.
- m_computedLinePosition = calculateComputedLinePosition();
-}
-
-void TextTrackCue::markFutureAndPastNodes(ContainerNode* root, double previousTimestamp, double movieTime)
-{
- DEFINE_STATIC_LOCAL(const String, timestampTag, ("timestamp"));
-
- bool isPastNode = true;
- double currentTimestamp = previousTimestamp;
- if (currentTimestamp > movieTime)
- isPastNode = false;
-
- for (Node* child = root->firstChild(); child; child = NodeTraversal::next(child, root)) {
- if (child->nodeName() == timestampTag) {
- unsigned position = 0;
- String timestamp = child->nodeValue();
- double currentTimestamp = WebVTTParser::create(0, m_scriptExecutionContext)->collectTimeStamp(timestamp, &position);
- ASSERT(currentTimestamp != -1);
-
- if (currentTimestamp > movieTime)
- isPastNode = false;
- }
-
- if (child->isWebVTTElement()) {
- toWebVTTElement(child)->setIsPastNode(isPastNode);
- // Make an elemenet id match a cue id for style matching purposes.
- if (!m_id.isEmpty())
- toElement(child)->setIdAttribute(m_id);
- }
- }
-}
-
-void TextTrackCue::updateDisplayTree(double movieTime)
-{
- // The display tree may contain WebVTT timestamp objects representing
- // timestamps (processing instructions), along with displayable nodes.
-
- if (!track()->isRendered())
- return;
-
- // Clear the contents of the set.
- m_cueBackgroundBox->removeChildren();
-
- // Update the two sets containing past and future WebVTT objects.
- RefPtr<DocumentFragment> referenceTree = createCueRenderingTree();
- markFutureAndPastNodes(referenceTree.get(), startTime(), movieTime);
- m_cueBackgroundBox->appendChild(referenceTree, ASSERT_NO_EXCEPTION);
-}
-
-PassRefPtr<TextTrackCueBox> TextTrackCue::getDisplayTree(const IntSize& videoSize)
-{
- RefPtr<TextTrackCueBox> displayTree = displayTreeInternal();
- if (!m_displayTreeShouldChange || !track()->isRendered())
- return displayTree;
-
- // 10.1 - 10.10
- calculateDisplayParameters();
-
- // 10.11. Apply the terms of the CSS specifications to nodes within the
- // following constraints, thus obtaining a set of CSS boxes positioned
- // relative to an initial containing block:
- displayTree->removeChildren();
-
- // The document tree is the tree of WebVTT Node Objects rooted at nodes.
-
- // The children of the nodes must be wrapped in an anonymous box whose
- // 'display' property has the value 'inline'. This is the WebVTT cue
- // background box.
-
- // Note: This is contained by default in m_cueBackgroundBox.
- m_cueBackgroundBox->setPart(cueShadowPseudoId());
- displayTree->appendChild(m_cueBackgroundBox);
-
- // FIXME(BUG 79916): Runs of children of WebVTT Ruby Objects that are not
- // WebVTT Ruby Text Objects must be wrapped in anonymous boxes whose
- // 'display' property has the value 'ruby-base'.
-
- // FIXME(BUG 79916): Text runs must be wrapped according to the CSS
- // line-wrapping rules, except that additionally, regardless of the value of
- // the 'white-space' property, lines must be wrapped at the edge of their
- // containing blocks, even if doing so requires splitting a word where there
- // is no line breaking opportunity. (Thus, normally text wraps as needed,
- // but if there is a particularly long word, it does not overflow as it
- // normally would in CSS, it is instead forcibly wrapped at the box's edge.)
- displayTree->applyCSSProperties(videoSize);
-
- m_displayTreeShouldChange = false;
-
- // 10.15. Let cue's text track cue display state have the CSS boxes in
- // boxes.
- return displayTree;
-}
-
-void TextTrackCue::removeDisplayTree()
-{
-#if ENABLE(WEBVTT_REGIONS)
- // The region needs to be informed about the cue removal.
- TextTrackRegion* region = m_track->regions()->getRegionById(m_regionId);
- if (region)
- region->willRemoveTextTrackCueBox(m_displayTree.get());
-#endif
-
- displayTreeInternal()->remove(ASSERT_NO_EXCEPTION);
-}
-
-std::pair<double, double> TextTrackCue::getPositionCoordinates() const
-{
- // This method is used for setting x and y when snap to lines is not set.
- std::pair<double, double> coordinates;
-
- if (m_writingDirection == Horizontal && m_displayDirection == CSSValueLtr) {
- coordinates.first = m_textPosition;
- coordinates.second = m_computedLinePosition;
-
- return coordinates;
- }
-
- if (m_writingDirection == Horizontal && m_displayDirection == CSSValueRtl) {
- coordinates.first = 100 - m_textPosition;
- coordinates.second = m_computedLinePosition;
-
- return coordinates;
- }
-
- if (m_writingDirection == VerticalGrowingLeft) {
- coordinates.first = 100 - m_computedLinePosition;
- coordinates.second = m_textPosition;
-
- return coordinates;
- }
-
- if (m_writingDirection == VerticalGrowingRight) {
- coordinates.first = m_computedLinePosition;
- coordinates.second = m_textPosition;
-
- return coordinates;
- }
-
- ASSERT_NOT_REACHED();
-
- return coordinates;
-}
-
-TextTrackCue::CueSetting TextTrackCue::settingName(const String& name)
-{
- DEFINE_STATIC_LOCAL(const String, verticalKeyword, ("vertical"));
- DEFINE_STATIC_LOCAL(const String, lineKeyword, ("line"));
- DEFINE_STATIC_LOCAL(const String, positionKeyword, ("position"));
- DEFINE_STATIC_LOCAL(const String, sizeKeyword, ("size"));
- DEFINE_STATIC_LOCAL(const String, alignKeyword, ("align"));
-#if ENABLE(WEBVTT_REGIONS)
- DEFINE_STATIC_LOCAL(const String, regionIdKeyword, ("region"));
-#endif
-
- if (name == verticalKeyword)
- return Vertical;
- else if (name == lineKeyword)
- return Line;
- else if (name == positionKeyword)
- return Position;
- else if (name == sizeKeyword)
- return Size;
- else if (name == alignKeyword)
- return Align;
-#if ENABLE(WEBVTT_REGIONS)
- else if (name == regionIdKeyword)
- return RegionId;
-#endif
-
- return None;
-}
-
-void TextTrackCue::setCueSettings(const String& input)
-{
- m_settings = input;
- unsigned position = 0;
-
- while (position < input.length()) {
-
- // The WebVTT cue settings part of a WebVTT cue consists of zero or more of the following components, in any order,
- // separated from each other by one or more U+0020 SPACE characters or U+0009 CHARACTER TABULATION (tab) characters.
- while (position < input.length() && WebVTTParser::isValidSettingDelimiter(input[position]))
- position++;
- if (position >= input.length())
- break;
-
- // When the user agent is to parse the WebVTT settings given by a string input for a text track cue cue,
- // the user agent must run the following steps:
- // 1. Let settings be the result of splitting input on spaces.
- // 2. For each token setting in the list settings, run the following substeps:
- // 1. If setting does not contain a U+003A COLON character (:), or if the first U+003A COLON character (:)
- // in setting is either the first or last character of setting, then jump to the step labeled next setting.
- unsigned endOfSetting = position;
- String setting = WebVTTParser::collectWord(input, &endOfSetting);
- CueSetting name;
- size_t colonOffset = setting.find(':', 1);
- if (colonOffset == kNotFound || !colonOffset || colonOffset == setting.length() - 1)
- goto NextSetting;
-
- // 2. Let name be the leading substring of setting up to and excluding the first U+003A COLON character (:) in that string.
- name = settingName(setting.substring(0, colonOffset));
-
- // 3. Let value be the trailing substring of setting starting from the character immediately after the first U+003A COLON character (:) in that string.
- position += colonOffset + 1;
- if (position >= input.length())
- break;
-
- // 4. Run the appropriate substeps that apply for the value of name, as follows:
- switch (name) {
- case Vertical:
- {
- // If name is a case-sensitive match for "vertical"
- // 1. If value is a case-sensitive match for the string "rl", then let cue's text track cue writing direction
- // be vertical growing left.
- String writingDirection = WebVTTParser::collectWord(input, &position);
- if (writingDirection == verticalGrowingLeftKeyword())
- m_writingDirection = VerticalGrowingLeft;
-
- // 2. Otherwise, if value is a case-sensitive match for the string "lr", then let cue's text track cue writing
- // direction be vertical growing right.
- else if (writingDirection == verticalGrowingRightKeyword())
- m_writingDirection = VerticalGrowingRight;
- }
- break;
- case Line:
- {
- // 1-2 - Collect chars that are either '-', '%', or a digit.
- // 1. If value contains any characters other than U+002D HYPHEN-MINUS characters (-), U+0025 PERCENT SIGN
- // characters (%), and characters in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9), then jump
- // to the step labeled next setting.
- StringBuilder linePositionBuilder;
- while (position < input.length() && (input[position] == '-' || input[position] == '%' || isASCIIDigit(input[position])))
- linePositionBuilder.append(input[position++]);
- if (position < input.length() && !WebVTTParser::isValidSettingDelimiter(input[position]))
- break;
-
- // 2. If value does not contain at least one character in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT
- // NINE (9), then jump to the step labeled next setting.
- // 3. If any character in value other than the first character is a U+002D HYPHEN-MINUS character (-), then
- // jump to the step labeled next setting.
- // 4. If any character in value other than the last character is a U+0025 PERCENT SIGN character (%), then
- // jump to the step labeled next setting.
- String linePosition = linePositionBuilder.toString();
- if (linePosition.find('-', 1) != kNotFound || linePosition.reverseFind("%", linePosition.length() - 2) != kNotFound)
- break;
-
- // 5. If the first character in value is a U+002D HYPHEN-MINUS character (-) and the last character in value is a
- // U+0025 PERCENT SIGN character (%), then jump to the step labeled next setting.
- if (linePosition[0] == '-' && linePosition[linePosition.length() - 1] == '%')
- break;
-
- // 6. Ignoring the trailing percent sign, if any, interpret value as a (potentially signed) integer, and
- // let number be that number.
- // NOTE: toInt ignores trailing non-digit characters, such as '%'.
- bool validNumber;
- int number = linePosition.toInt(&validNumber);
- if (!validNumber)
- break;
-
- // 7. If the last character in value is a U+0025 PERCENT SIGN character (%), but number is not in the range
- // 0 ≤ number ≤ 100, then jump to the step labeled next setting.
- // 8. Let cue's text track cue line position be number.
- // 9. If the last character in value is a U+0025 PERCENT SIGN character (%), then let cue's text track cue
- // snap-to-lines flag be false. Otherwise, let it be true.
- if (linePosition[linePosition.length() - 1] == '%') {
- if (number < 0 || number > 100)
- break;
-
- // 10 - If '%' then set snap-to-lines flag to false.
- m_snapToLines = false;
- }
-
- m_linePosition = number;
- }
- break;
- case Position:
- {
- // 1. If value contains any characters other than U+0025 PERCENT SIGN characters (%) and characters in the range
- // U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9), then jump to the step labeled next setting.
- // 2. If value does not contain at least one character in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9),
- // then jump to the step labeled next setting.
- String textPosition = WebVTTParser::collectDigits(input, &position);
- if (textPosition.isEmpty())
- break;
- if (position >= input.length())
- break;
-
- // 3. If any character in value other than the last character is a U+0025 PERCENT SIGN character (%), then jump
- // to the step labeled next setting.
- // 4. If the last character in value is not a U+0025 PERCENT SIGN character (%), then jump to the step labeled
- // next setting.
- if (input[position++] != '%')
- break;
- if (position < input.length() && !WebVTTParser::isValidSettingDelimiter(input[position]))
- break;
-
- // 5. Ignoring the trailing percent sign, interpret value as an integer, and let number be that number.
- // 6. If number is not in the range 0 ≤ number ≤ 100, then jump to the step labeled next setting.
- // NOTE: toInt ignores trailing non-digit characters, such as '%'.
- bool validNumber;
- int number = textPosition.toInt(&validNumber);
- if (!validNumber)
- break;
- if (number < 0 || number > 100)
- break;
-
- // 7. Let cue's text track cue text position be number.
- m_textPosition = number;
- }
- break;
- case Size:
- {
- // 1. If value contains any characters other than U+0025 PERCENT SIGN characters (%) and characters in the
- // range U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9), then jump to the step labeled next setting.
- // 2. If value does not contain at least one character in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT
- // NINE (9), then jump to the step labeled next setting.
- String cueSize = WebVTTParser::collectDigits(input, &position);
- if (cueSize.isEmpty())
- break;
- if (position >= input.length())
- break;
-
- // 3. If any character in value other than the last character is a U+0025 PERCENT SIGN character (%),
- // then jump to the step labeled next setting.
- // 4. If the last character in value is not a U+0025 PERCENT SIGN character (%), then jump to the step
- // labeled next setting.
- if (input[position++] != '%')
- break;
- if (position < input.length() && !WebVTTParser::isValidSettingDelimiter(input[position]))
- break;
-
- // 5. Ignoring the trailing percent sign, interpret value as an integer, and let number be that number.
- // 6. If number is not in the range 0 ≤ number ≤ 100, then jump to the step labeled next setting.
- bool validNumber;
- int number = cueSize.toInt(&validNumber);
- if (!validNumber)
- break;
- if (number < 0 || number > 100)
- break;
-
- // 7. Let cue's text track cue size be number.
- m_cueSize = number;
- }
- break;
- case Align:
- {
- String cueAlignment = WebVTTParser::collectWord(input, &position);
-
- // 1. If value is a case-sensitive match for the string "start", then let cue's text track cue alignment be start alignment.
- if (cueAlignment == startKeyword())
- m_cueAlignment = Start;
-
- // 2. If value is a case-sensitive match for the string "middle", then let cue's text track cue alignment be middle alignment.
- else if (cueAlignment == middleKeyword())
- m_cueAlignment = Middle;
-
- // 3. If value is a case-sensitive match for the string "end", then let cue's text track cue alignment be end alignment.
- else if (cueAlignment == endKeyword())
- m_cueAlignment = End;
- }
- break;
-#if ENABLE(WEBVTT_REGIONS)
- case RegionId:
- m_regionId = WebVTTParser::collectWord(input, &position);
- break;
-#endif
- case None:
- break;
- }
-
-NextSetting:
- position = endOfSetting;
- }
-#if ENABLE(WEBVTT_REGIONS)
- // If cue's line position is not auto or cue's size is not 100 or cue's
- // writing direction is not horizontal, but cue's region identifier is not
- // the empty string, let cue's region identifier be the empty string.
- if (m_regionId.isEmpty())
- return;
-
- if (m_linePosition != undefinedPosition || m_cueSize != 100 || m_writingDirection != Horizontal)
- m_regionId = emptyString();
-#endif
-}
-
-CSSValueID TextTrackCue::getCSSWritingDirection() const
-{
- return m_displayDirection;
-}
-
-CSSValueID TextTrackCue::getCSSWritingMode() const
-{
- return m_displayWritingMode;
-}
-
-int TextTrackCue::getCSSSize() const
-{
- return m_displaySize;
-}
-
-std::pair<double, double> TextTrackCue::getCSSPosition() const
-{
- if (!m_snapToLines)
- return getPositionCoordinates();
-
- return m_displayPosition;
-}
-
const AtomicString& TextTrackCue::interfaceName() const
{
- return eventNames().interfaceForTextTrackCue;
-}
-
-ScriptExecutionContext* TextTrackCue::scriptExecutionContext() const
-{
- return m_scriptExecutionContext;
-}
-
-EventTargetData* TextTrackCue::eventTargetData()
-{
- return &m_eventTargetData;
-}
-
-EventTargetData* TextTrackCue::ensureEventTargetData()
-{
- return &m_eventTargetData;
-}
-
-bool TextTrackCue::operator==(const TextTrackCue& cue) const
-{
- if (cueType() != cue.cueType())
- return false;
-
- if (m_endTime != cue.endTime())
- return false;
- if (m_startTime != cue.startTime())
- return false;
- if (m_content != cue.text())
- return false;
- if (m_settings != cue.cueSettings())
- return false;
- if (m_id != cue.id())
- return false;
- if (m_textPosition != cue.position())
- return false;
- if (m_linePosition != cue.line())
- return false;
- if (m_cueSize != cue.size())
- return false;
- if (align() != cue.align())
- return false;
-
- return true;
+ return EventTargetNames::TextTrackCue;
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/html/track/TextTrackCue.h b/chromium/third_party/WebKit/Source/core/html/track/TextTrackCue.h
index 61fd4500ce6..1779e37a7d1 100644
--- a/chromium/third_party/WebKit/Source/core/html/track/TextTrackCue.h
+++ b/chromium/third_party/WebKit/Source/core/html/track/TextTrackCue.h
@@ -32,49 +32,18 @@
#ifndef TextTrackCue_h
#define TextTrackCue_h
-#include "bindings/v8/ScriptWrappable.h"
-#include "core/dom/EventTarget.h"
+#include "core/events/EventTarget.h"
#include "core/html/HTMLDivElement.h"
#include "wtf/RefCounted.h"
namespace WebCore {
-class DocumentFragment;
class ExceptionState;
-class ScriptExecutionContext;
-class TextTrack;
-class TextTrackCue;
-// ----------------------------
-
-class TextTrackCueBox : public HTMLDivElement {
+class TextTrackCue : public RefCounted<TextTrackCue>, public EventTargetWithInlineData {
+ REFCOUNTED_EVENT_TARGET(TextTrackCue);
public:
- static PassRefPtr<TextTrackCueBox> create(Document& document, TextTrackCue* cue)
- {
- return adoptRef(new TextTrackCueBox(document, cue));
- }
-
- TextTrackCue* getCue() const;
- virtual void applyCSSProperties(const IntSize& videoSize);
-
- static const AtomicString& textTrackCueBoxShadowPseudoId();
-
-protected:
- TextTrackCueBox(Document&, TextTrackCue*);
-
- virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
-
- TextTrackCue* m_cue;
-};
-
-// ----------------------------
-
-class TextTrackCue : public RefCounted<TextTrackCue>, public ScriptWrappable, public EventTarget {
-public:
- static PassRefPtr<TextTrackCue> create(ScriptExecutionContext* context, double start, double end, const String& content)
- {
- return adoptRef(new TextTrackCue(context, start, end, content));
- }
+ static bool isInfiniteOrNonNumber(double value, ExceptionState&);
static const AtomicString& cueShadowPseudoId()
{
@@ -82,7 +51,7 @@ public:
return cue;
}
- virtual ~TextTrackCue();
+ virtual ~TextTrackCue() { }
TextTrack* track() const;
void setTrack(TextTrack*);
@@ -99,182 +68,48 @@ public:
bool pauseOnExit() const { return m_pauseOnExit; }
void setPauseOnExit(bool);
- const String& vertical() const;
- void setVertical(const String&, ExceptionState&);
-
- bool snapToLines() const { return m_snapToLines; }
- void setSnapToLines(bool);
-
- int line() const { return m_linePosition; }
- virtual void setLine(int, ExceptionState&);
-
- int position() const { return m_textPosition; }
- virtual void setPosition(int, ExceptionState&);
-
- int size() const { return m_cueSize; }
- virtual void setSize(int, ExceptionState&);
-
- const String& align() const;
- void setAlign(const String&, ExceptionState&);
-
- const String& text() const { return m_content; }
- void setText(const String&);
-
- const String& cueSettings() const { return m_settings; }
- void setCueSettings(const String&);
-
int cueIndex();
void invalidateCueIndex();
- PassRefPtr<DocumentFragment> getCueAsHTML();
- PassRefPtr<DocumentFragment> createCueRenderingTree();
-
using EventTarget::dispatchEvent;
virtual bool dispatchEvent(PassRefPtr<Event>) OVERRIDE;
-#if ENABLE(WEBVTT_REGIONS)
- const String& regionId() const { return m_regionId; }
- void setRegionId(const String&);
-#endif
-
bool isActive();
void setIsActive(bool);
- bool hasDisplayTree() const { return m_displayTree; }
- PassRefPtr<TextTrackCueBox> getDisplayTree(const IntSize& videoSize);
- PassRefPtr<HTMLDivElement> element() const { return m_cueBackgroundBox; }
-
- void updateDisplayTree(double);
- void removeDisplayTree();
- void markFutureAndPastNodes(ContainerNode*, double, double);
-
- int calculateComputedLinePosition();
-
- virtual const AtomicString& interfaceName() const;
- virtual ScriptExecutionContext* scriptExecutionContext() const;
+ virtual void updateDisplay(const IntSize& videoSize, HTMLDivElement& container) = 0;
- std::pair<double, double> getCSSPosition() const;
+ // FIXME: Consider refactoring to eliminate or merge the following three members.
+ // https://code.google.com/p/chromium/issues/detail?id=322434
+ virtual void updateDisplayTree(double movieTime) = 0;
+ virtual void removeDisplayTree() = 0;
+ virtual void notifyRegionWhenRemovingDisplayTree(bool notifyRegion) = 0;
- int getCSSSize() const;
- CSSValueID getCSSWritingDirection() const;
- CSSValueID getCSSWritingMode() const;
+ virtual const AtomicString& interfaceName() const OVERRIDE;
- enum WritingDirection {
- Horizontal,
- VerticalGrowingLeft,
- VerticalGrowingRight,
- NumberOfWritingDirections
- };
- WritingDirection getWritingDirection() const { return m_writingDirection; }
-
- enum CueAlignment {
- Start,
- Middle,
- End
- };
- CueAlignment getAlignment() const { return m_cueAlignment; }
-
- virtual void videoSizeDidChange(const IntSize&) { }
-
- virtual bool operator==(const TextTrackCue&) const;
- virtual bool operator!=(const TextTrackCue& cue) const
- {
- return !(*this == cue);
- }
-
- enum CueType {
- Generic,
- WebVTT
- };
- virtual CueType cueType() const { return WebVTT; }
+#ifndef NDEBUG
+ virtual String toString() const = 0;
+#endif
DEFINE_ATTRIBUTE_EVENT_LISTENER(enter);
DEFINE_ATTRIBUTE_EVENT_LISTENER(exit);
- using RefCounted<TextTrackCue>::ref;
- using RefCounted<TextTrackCue>::deref;
-
protected:
- virtual EventTargetData* eventTargetData();
- virtual EventTargetData* ensureEventTargetData();
-
- TextTrackCue(ScriptExecutionContext*, double start, double end, const String& content);
-
- Document* ownerDocument() { return toDocument(m_scriptExecutionContext); }
-
- virtual PassRefPtr<TextTrackCueBox> createDisplayTree();
- PassRefPtr<TextTrackCueBox> displayTreeInternal();
-
-private:
- void createWebVTTNodeTree();
- void copyWebVTTNodeToDOMTree(ContainerNode* WebVTTNode, ContainerNode* root);
-
- std::pair<double, double> getPositionCoordinates() const;
- void parseSettings(const String&);
-
- void determineTextDirection();
- void calculateDisplayParameters();
+ TextTrackCue(double start, double end);
void cueWillChange();
- void cueDidChange();
-
- virtual void refEventTarget() { ref(); }
- virtual void derefEventTarget() { deref(); }
-
- enum CueSetting {
- None,
- Vertical,
- Line,
- Position,
- Size,
- Align,
-#if ENABLE(WEBVTT_REGIONS)
- RegionId
-#endif
- };
- CueSetting settingName(const String&);
+ virtual void cueDidChange();
+private:
String m_id;
double m_startTime;
double m_endTime;
- String m_content;
- String m_settings;
- int m_linePosition;
- int m_computedLinePosition;
- int m_textPosition;
- int m_cueSize;
int m_cueIndex;
- WritingDirection m_writingDirection;
-
- CueAlignment m_cueAlignment;
-
- RefPtr<DocumentFragment> m_webVTTNodeTree;
TextTrack* m_track;
- EventTargetData m_eventTargetData;
- ScriptExecutionContext* m_scriptExecutionContext;
-
- bool m_isActive;
- bool m_pauseOnExit;
- bool m_snapToLines;
-
- RefPtr<HTMLDivElement> m_cueBackgroundBox;
-
- bool m_displayTreeShouldChange;
- RefPtr<TextTrackCueBox> m_displayTree;
-
- CSSValueID m_displayDirection;
-
- CSSValueID m_displayWritingModeMap[NumberOfWritingDirections];
- CSSValueID m_displayWritingMode;
-
- int m_displaySize;
-
- std::pair<float, float> m_displayPosition;
-#if ENABLE(WEBVTT_REGIONS)
- String m_regionId;
-#endif
+ bool m_isActive : 1;
+ bool m_pauseOnExit : 1;
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/html/track/TextTrackCue.idl b/chromium/third_party/WebKit/Source/core/html/track/TextTrackCue.idl
index e64d8a33dfd..efc18e3e60a 100644
--- a/chromium/third_party/WebKit/Source/core/html/track/TextTrackCue.idl
+++ b/chromium/third_party/WebKit/Source/core/html/track/TextTrackCue.idl
@@ -24,30 +24,17 @@
*/
[
- EnabledAtRuntime=VideoTrack,
- Constructor(double startTime, double endTime, DOMString text),
- ConstructorCallWith=ScriptExecutionContext
+ Custom=ToV8,
+ CustomConstructor(double startTime, double endTime, DOMString text),
+ RuntimeEnabled=VideoTrack,
] interface TextTrackCue : EventTarget {
readonly attribute TextTrack track;
attribute DOMString id;
- [SetterRaisesException] attribute double startTime;
- [SetterRaisesException] attribute double endTime;
+ [RaisesException=Setter] attribute double startTime;
+ [RaisesException=Setter] attribute double endTime;
attribute boolean pauseOnExit;
- [SetterRaisesException] attribute DOMString vertical;
- attribute boolean snapToLines;
- [SetterRaisesException] attribute long line;
- [SetterRaisesException] attribute long position;
- [SetterRaisesException] attribute long size;
- [SetterRaisesException] attribute DOMString align;
-
- attribute DOMString text;
- DocumentFragment getCueAsHTML();
-
attribute EventHandler onenter;
attribute EventHandler onexit;
-
- [Conditional=WEBVTT_REGIONS] attribute DOMString regionId;
};
-
diff --git a/chromium/third_party/WebKit/Source/core/html/track/TextTrackCueGeneric.cpp b/chromium/third_party/WebKit/Source/core/html/track/TextTrackCueGeneric.cpp
deleted file mode 100644
index b80e67b7d9b..00000000000
--- a/chromium/third_party/WebKit/Source/core/html/track/TextTrackCueGeneric.cpp
+++ /dev/null
@@ -1,168 +0,0 @@
-/*
- * Copyright (C) 2013 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/html/track/TextTrackCueGeneric.h"
-
-#include "CSSPropertyNames.h"
-#include "CSSValueKeywords.h"
-#include "bindings/v8/ExceptionStatePlaceholder.h"
-#include "core/html/HTMLDivElement.h"
-#include "core/html/track/TextTrackCue.h"
-
-namespace WebCore {
-
-class TextTrackCueGenericBoxElement FINAL : public TextTrackCueBox {
-public:
- static PassRefPtr<TextTrackCueGenericBoxElement> create(Document& document, TextTrackCueGeneric* cue)
- {
- return adoptRef(new TextTrackCueGenericBoxElement(document, cue));
- }
-
- virtual void applyCSSProperties(const IntSize&) OVERRIDE;
-
-private:
- TextTrackCueGenericBoxElement(Document&, TextTrackCue*);
-};
-
-TextTrackCueGenericBoxElement::TextTrackCueGenericBoxElement(Document& document, TextTrackCue* cue)
- : TextTrackCueBox(document, cue)
-{
-}
-
-void TextTrackCueGenericBoxElement::applyCSSProperties(const IntSize& videoSize)
-{
- setInlineStyleProperty(CSSPropertyPosition, CSSValueAbsolute);
- setInlineStyleProperty(CSSPropertyUnicodeBidi, CSSValueWebkitPlaintext);
-
- TextTrackCueGeneric* cue = static_cast<TextTrackCueGeneric*>(getCue());
-
- float size = static_cast<float>(cue->getCSSSize());
- if (cue->useDefaultPosition()) {
- setInlineStyleProperty(CSSPropertyBottom, 0.0, CSSPrimitiveValue::CSS_PX);
- setInlineStyleProperty(CSSPropertyMarginBottom, 1.0, CSSPrimitiveValue::CSS_PERCENTAGE);
- } else {
- setInlineStyleProperty(CSSPropertyLeft, static_cast<float>(cue->position()), CSSPrimitiveValue::CSS_PERCENTAGE);
- setInlineStyleProperty(CSSPropertyTop, static_cast<float>(cue->line()), CSSPrimitiveValue::CSS_PERCENTAGE);
-
- if (cue->getWritingDirection() == TextTrackCue::Horizontal)
- setInlineStyleProperty(CSSPropertyWidth, size, CSSPrimitiveValue::CSS_PERCENTAGE);
- else
- setInlineStyleProperty(CSSPropertyHeight, size, CSSPrimitiveValue::CSS_PERCENTAGE);
- }
-
- if (cue->foregroundColor().isValid())
- setInlineStyleProperty(CSSPropertyColor, cue->foregroundColor().serialized());
-
- if (cue->backgroundColor().isValid())
- cue->element()->setInlineStyleProperty(CSSPropertyBackgroundColor, cue->backgroundColor().serialized());
-
- if (cue->getWritingDirection() == TextTrackCue::Horizontal)
- setInlineStyleProperty(CSSPropertyHeight, CSSValueAuto);
- else
- setInlineStyleProperty(CSSPropertyWidth, CSSValueAuto);
-
- if (cue->baseFontSizeRelativeToVideoHeight()) {
- double fontSize = videoSize.height() * cue->baseFontSizeRelativeToVideoHeight() / 100;
- if (cue->fontSizeMultiplier())
- fontSize *= cue->fontSizeMultiplier() / 100;
- setInlineStyleProperty(CSSPropertyFontSize, fontSize, CSSPrimitiveValue::CSS_PX);
- }
-
- if (cue->getAlignment() == TextTrackCue::Middle)
- setInlineStyleProperty(CSSPropertyTextAlign, CSSValueCenter);
- else if (cue->getAlignment() == TextTrackCue::End)
- setInlineStyleProperty(CSSPropertyTextAlign, CSSValueEnd);
- else
- setInlineStyleProperty(CSSPropertyTextAlign, CSSValueStart);
-
- setInlineStyleProperty(CSSPropertyWebkitWritingMode, cue->getCSSWritingMode(), false);
- setInlineStyleProperty(CSSPropertyWhiteSpace, CSSValuePreWrap);
- setInlineStyleProperty(CSSPropertyWordBreak, CSSValueNormal);
-}
-
-TextTrackCueGeneric::TextTrackCueGeneric(ScriptExecutionContext* context, double start, double end, const String& content)
- : TextTrackCue(context, start, end, content)
- , m_baseFontSizeRelativeToVideoHeight(0)
- , m_fontSizeMultiplier(0)
- , m_defaultPosition(true)
-{
-}
-
-PassRefPtr<TextTrackCueBox> TextTrackCueGeneric::createDisplayTree()
-{
- ASSERT(ownerDocument());
- return TextTrackCueGenericBoxElement::create(*ownerDocument(), this);
-}
-
-void TextTrackCueGeneric::setLine(int line, ExceptionState& es)
-{
- m_defaultPosition = false;
- TextTrackCue::setLine(line, es);
-}
-
-void TextTrackCueGeneric::setPosition(int position, ExceptionState& es)
-{
- m_defaultPosition = false;
- TextTrackCue::setPosition(position, es);
-}
-
-void TextTrackCueGeneric::videoSizeDidChange(const IntSize& videoSize)
-{
- if (!hasDisplayTree())
- return;
-
- if (baseFontSizeRelativeToVideoHeight()) {
- double fontSize = videoSize.height() * baseFontSizeRelativeToVideoHeight() / 100;
- if (fontSizeMultiplier())
- fontSize *= fontSizeMultiplier() / 100;
- displayTreeInternal()->setInlineStyleProperty(CSSPropertyFontSize, fontSize, CSSPrimitiveValue::CSS_PX);
- }
-
-}
-
-bool TextTrackCueGeneric::operator==(const TextTrackCue& cue) const
-{
- if (cue.cueType() != TextTrackCue::Generic)
- return false;
-
- const TextTrackCueGeneric* other = static_cast<const TextTrackCueGeneric*>(&cue);
-
- if (m_baseFontSizeRelativeToVideoHeight != other->baseFontSizeRelativeToVideoHeight())
- return false;
- if (m_fontSizeMultiplier != other->fontSizeMultiplier())
- return false;
- if (m_fontName != other->fontName())
- return false;
- if (m_foregroundColor != other->foregroundColor())
- return false;
- if (m_backgroundColor != other->backgroundColor())
- return false;
-
- return TextTrackCue::operator==(cue);
-}
-
-} // namespace WebCore
-
diff --git a/chromium/third_party/WebKit/Source/core/html/track/TextTrackCueGeneric.h b/chromium/third_party/WebKit/Source/core/html/track/TextTrackCueGeneric.h
deleted file mode 100644
index a62611a07e5..00000000000
--- a/chromium/third_party/WebKit/Source/core/html/track/TextTrackCueGeneric.h
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
- * Copyright (C) 2013 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TextTrackCueGeneric_h
-#define TextTrackCueGeneric_h
-
-#include "core/html/track/TextTrackCue.h"
-#include "core/platform/graphics/Color.h"
-
-namespace WebCore {
-
-class ExceptionState;
-class GenericCueData;
-
-// A "generic" cue is a non-WebVTT cue, so it is not positioned/sized with the WebVTT logic.
-class TextTrackCueGeneric : public TextTrackCue {
-public:
- static PassRefPtr<TextTrackCueGeneric> create(ScriptExecutionContext* context, double start, double end, const String& content)
- {
- return adoptRef(new TextTrackCueGeneric(context, start, end, content));
- }
-
- virtual ~TextTrackCueGeneric() { }
-
- virtual PassRefPtr<TextTrackCueBox> createDisplayTree() OVERRIDE;
-
- virtual void setLine(int, ExceptionState&) OVERRIDE;
- virtual void setPosition(int, ExceptionState&) OVERRIDE;
-
- bool useDefaultPosition() const { return m_defaultPosition; }
-
- double baseFontSizeRelativeToVideoHeight() const { return m_baseFontSizeRelativeToVideoHeight; }
- void setBaseFontSizeRelativeToVideoHeight(double size) { m_baseFontSizeRelativeToVideoHeight = size; }
-
- double fontSizeMultiplier() const { return m_fontSizeMultiplier; }
- void setFontSizeMultiplier(double size) { m_fontSizeMultiplier = size; }
-
- String fontName() const { return m_fontName; }
- void setFontName(String name) { m_fontName = name; }
-
- Color foregroundColor() const { return m_foregroundColor; }
-
- void setForegroundColor(RGBA32 color) { m_foregroundColor.setRGB(color); }
-
- Color backgroundColor() const { return m_backgroundColor; }
- void setBackgroundColor(RGBA32 color) { m_backgroundColor.setRGB(color); }
-
- virtual void videoSizeDidChange(const IntSize&);
-
- virtual bool operator==(const TextTrackCue&) const OVERRIDE;
- virtual bool operator!=(const TextTrackCue& cue) const OVERRIDE
- {
- return !(*this == cue);
- }
-
- virtual TextTrackCue::CueType cueType() const OVERRIDE { return TextTrackCue::Generic; }
-
-private:
- TextTrackCueGeneric(ScriptExecutionContext*, double start, double end, const String&);
-
- Color m_foregroundColor;
- Color m_backgroundColor;
- double m_baseFontSizeRelativeToVideoHeight;
- double m_fontSizeMultiplier;
- String m_fontName;
- bool m_defaultPosition;
-};
-
-} // namespace WebCore
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/html/track/TextTrackCueList.idl b/chromium/third_party/WebKit/Source/core/html/track/TextTrackCueList.idl
index 4f289352682..a71d6875ddb 100644
--- a/chromium/third_party/WebKit/Source/core/html/track/TextTrackCueList.idl
+++ b/chromium/third_party/WebKit/Source/core/html/track/TextTrackCueList.idl
@@ -24,7 +24,7 @@
*/
[
- EnabledAtRuntime=VideoTrack
+ RuntimeEnabled=VideoTrack
] interface TextTrackCueList {
readonly attribute unsigned long length;
getter TextTrackCue item(unsigned long index);
diff --git a/chromium/third_party/WebKit/Source/core/html/track/TextTrackList.cpp b/chromium/third_party/WebKit/Source/core/html/track/TextTrackList.cpp
index 763707c7744..0d00ba33fee 100644
--- a/chromium/third_party/WebKit/Source/core/html/track/TextTrackList.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/track/TextTrackList.cpp
@@ -27,7 +27,8 @@
#include "core/html/track/TextTrackList.h"
#include "bindings/v8/ExceptionStatePlaceholder.h"
-#include "core/dom/EventNames.h"
+#include "core/events/GenericEventQueue.h"
+#include "core/events/ThreadLocalEventNames.h"
#include "core/html/HTMLMediaElement.h"
#include "core/html/track/InbandTextTrack.h"
#include "core/html/track/LoadableTextTrack.h"
@@ -36,18 +37,16 @@
using namespace WebCore;
-TextTrackList::TextTrackList(HTMLMediaElement* owner, ScriptExecutionContext* context)
- : m_context(context)
- , m_owner(owner)
- , m_pendingEventTimer(this, &TextTrackList::asyncEventTimerFired)
- , m_dispatchingEvents(0)
+TextTrackList::TextTrackList(HTMLMediaElement* owner)
+ : m_owner(owner)
+ , m_asyncEventQueue(GenericEventQueue::create(this))
{
- ASSERT(context->isDocument());
ScriptWrappable::init(this);
}
TextTrackList::~TextTrackList()
{
+ m_asyncEventQueue->close();
}
unsigned TextTrackList::length() const
@@ -131,6 +130,22 @@ TextTrack* TextTrackList::item(unsigned index)
return 0;
}
+TextTrack* TextTrackList::getTrackById(const AtomicString& id)
+{
+ // 4.8.10.12.5 Text track API
+ // The getTrackById(id) method must return the first TextTrack in the
+ // TextTrackList object whose id IDL attribute would return a value equal
+ // to the value of the id argument.
+ for (unsigned i = 0; i < length(); ++i) {
+ TextTrack* track = item(i);
+ if (track->id() == id)
+ return track;
+ }
+
+ // When no tracks match the given argument, the method must return null.
+ return 0;
+}
+
void TextTrackList::invalidateTrackIndexesAfterTrack(TextTrack* track)
{
Vector<RefPtr<TextTrack> >* tracks = 0;
@@ -212,6 +227,8 @@ void TextTrackList::remove(TextTrack* track)
if (inbandTrack)
inbandTrack->trackRemoved();
+
+ scheduleRemoveTrackEvent(track);
}
bool TextTrackList::contains(TextTrack* track) const
@@ -232,7 +249,23 @@ bool TextTrackList::contains(TextTrack* track) const
const AtomicString& TextTrackList::interfaceName() const
{
- return eventNames().interfaceForTextTrackList;
+ return EventTargetNames::TextTrackList;
+}
+
+ExecutionContext* TextTrackList::executionContext() const
+{
+ ASSERT(m_owner);
+ return m_owner->executionContext();
+}
+
+void TextTrackList::scheduleTrackEvent(const AtomicString& eventName, PassRefPtr<TextTrack> track)
+{
+ TrackEventInit initializer;
+ initializer.track = track;
+ initializer.bubbles = false;
+ initializer.cancelable = false;
+
+ m_asyncEventQueue->enqueueEvent(TrackEvent::create(eventName, initializer));
}
void TextTrackList::scheduleAddTrackEvent(PassRefPtr<TextTrack> track)
@@ -243,28 +276,38 @@ void TextTrackList::scheduleAddTrackEvent(PassRefPtr<TextTrack> track)
// bubble and is not cancelable, and that uses the TrackEvent interface, with
// the track attribute initialized to the text track's TextTrack object, at
// the media element's textTracks attribute's TextTrackList object.
+ scheduleTrackEvent(EventTypeNames::addtrack, track);
+}
- RefPtr<TextTrack> trackRef = track;
- TrackEventInit initializer;
- initializer.track = trackRef;
+void TextTrackList::scheduleChangeEvent()
+{
+ // 4.8.10.12.1 Text track model
+ // Whenever a text track that is in a media element's list of text tracks
+ // has its text track mode change value, the user agent must run the
+ // following steps for the media element:
+ // ...
+ // Fire a simple event named change at the media element's textTracks
+ // attribute's TextTrackList object.
+
+ EventInit initializer;
initializer.bubbles = false;
initializer.cancelable = false;
- m_pendingEvents.append(TrackEvent::create(eventNames().addtrackEvent, initializer));
- if (!m_pendingEventTimer.isActive())
- m_pendingEventTimer.startOneShot(0);
+ m_asyncEventQueue->enqueueEvent(Event::create(EventTypeNames::change, initializer));
}
-void TextTrackList::asyncEventTimerFired(Timer<TextTrackList>*)
+void TextTrackList::scheduleRemoveTrackEvent(PassRefPtr<TextTrack> track)
{
- Vector<RefPtr<Event> > pendingEvents;
-
- ++m_dispatchingEvents;
- m_pendingEvents.swap(pendingEvents);
- size_t count = pendingEvents.size();
- for (size_t index = 0; index < count; ++index)
- dispatchEvent(pendingEvents[index].release(), IGNORE_EXCEPTION);
- --m_dispatchingEvents;
+ // 4.8.10.12.3 Sourcing out-of-band text tracks
+ // When a track element's parent element changes and the old parent was a
+ // media element, then the user agent must remove the track element's
+ // corresponding text track from the media element's list of text tracks,
+ // and then queue a task to fire a trusted event with the name removetrack,
+ // that does not bubble and is not cancelable, and that uses the TrackEvent
+ // interface, with the track attribute initialized to the text track's
+ // TextTrack object, at the media element's textTracks attribute's
+ // TextTrackList object.
+ scheduleTrackEvent(EventTypeNames::removetrack, track);
}
Node* TextTrackList::owner() const
diff --git a/chromium/third_party/WebKit/Source/core/html/track/TextTrackList.h b/chromium/third_party/WebKit/Source/core/html/track/TextTrackList.h
index ac4621a2f13..7c150b2c931 100644
--- a/chromium/third_party/WebKit/Source/core/html/track/TextTrackList.h
+++ b/chromium/third_party/WebKit/Source/core/html/track/TextTrackList.h
@@ -27,24 +27,26 @@
#define TextTrackList_h
#include "bindings/v8/ScriptWrappable.h"
-#include "core/dom/EventListener.h"
-#include "core/dom/EventTarget.h"
-#include "core/platform/Timer.h"
+#include "core/events/EventListener.h"
+#include "core/events/EventTarget.h"
+#include "platform/Timer.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefCounted.h"
#include "wtf/Vector.h"
namespace WebCore {
+class GenericEventQueue;
class HTMLMediaElement;
class TextTrack;
class TextTrackList;
-class TextTrackList : public RefCounted<TextTrackList>, public ScriptWrappable, public EventTarget {
+class TextTrackList : public RefCounted<TextTrackList>, public ScriptWrappable, public EventTargetWithInlineData {
+ REFCOUNTED_EVENT_TARGET(TextTrackList);
public:
- static PassRefPtr<TextTrackList> create(HTMLMediaElement* owner, ScriptExecutionContext* context)
+ static PassRefPtr<TextTrackList> create(HTMLMediaElement* owner)
{
- return adoptRef(new TextTrackList(owner, context));
+ return adoptRef(new TextTrackList(owner));
}
~TextTrackList();
@@ -54,48 +56,40 @@ public:
bool contains(TextTrack*) const;
TextTrack* item(unsigned index);
+ TextTrack* getTrackById(const AtomicString& id);
void append(PassRefPtr<TextTrack>);
void remove(TextTrack*);
// EventTarget
- virtual const AtomicString& interfaceName() const;
- using RefCounted<TextTrackList>::ref;
- using RefCounted<TextTrackList>::deref;
- virtual ScriptExecutionContext* scriptExecutionContext() const { return m_context; }
+ virtual const AtomicString& interfaceName() const OVERRIDE;
+ virtual ExecutionContext* executionContext() const OVERRIDE;
DEFINE_ATTRIBUTE_EVENT_LISTENER(addtrack);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(change);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(removetrack);
void clearOwner() { m_owner = 0; }
Node* owner() const;
- bool isFiringEventListeners() { return m_dispatchingEvents; }
+ void scheduleChangeEvent();
private:
- TextTrackList(HTMLMediaElement*, ScriptExecutionContext*);
+ explicit TextTrackList(HTMLMediaElement*);
- // EventTarget
- virtual void refEventTarget() { ref(); }
- virtual void derefEventTarget() { deref(); }
- virtual EventTargetData* eventTargetData() { return &m_eventTargetData; }
- virtual EventTargetData* ensureEventTargetData() { return &m_eventTargetData; }
+ void scheduleTrackEvent(const AtomicString& eventName, PassRefPtr<TextTrack>);
void scheduleAddTrackEvent(PassRefPtr<TextTrack>);
- void asyncEventTimerFired(Timer<TextTrackList>*);
+ void scheduleRemoveTrackEvent(PassRefPtr<TextTrack>);
void invalidateTrackIndexesAfterTrack(TextTrack*);
- ScriptExecutionContext* m_context;
HTMLMediaElement* m_owner;
- Vector<RefPtr<Event> > m_pendingEvents;
- Timer<TextTrackList> m_pendingEventTimer;
+ OwnPtr<GenericEventQueue> m_asyncEventQueue;
- EventTargetData m_eventTargetData;
Vector<RefPtr<TextTrack> > m_addTrackTracks;
Vector<RefPtr<TextTrack> > m_elementTracks;
Vector<RefPtr<TextTrack> > m_inbandTracks;
-
- int m_dispatchingEvents;
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/html/track/TextTrackList.idl b/chromium/third_party/WebKit/Source/core/html/track/TextTrackList.idl
index bdfcc743432..bbcd2d96499 100644
--- a/chromium/third_party/WebKit/Source/core/html/track/TextTrackList.idl
+++ b/chromium/third_party/WebKit/Source/core/html/track/TextTrackList.idl
@@ -24,12 +24,15 @@
*/
[
- EnabledAtRuntime=VideoTrack,
- GenerateIsReachable=owner
+ GenerateVisitDOMWrapper=owner,
+ RuntimeEnabled=VideoTrack,
] interface TextTrackList : EventTarget {
readonly attribute unsigned long length;
getter TextTrack item(unsigned long index);
+ TextTrack getTrackById(DOMString id);
attribute EventHandler onaddtrack;
+ attribute EventHandler onchange;
+ attribute EventHandler onremovetrack;
};
diff --git a/chromium/third_party/WebKit/Source/core/html/track/TextTrackRegion.cpp b/chromium/third_party/WebKit/Source/core/html/track/TextTrackRegion.cpp
deleted file mode 100644
index ca3f3447a4c..00000000000
--- a/chromium/third_party/WebKit/Source/core/html/track/TextTrackRegion.cpp
+++ /dev/null
@@ -1,510 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#if ENABLE(WEBVTT_REGIONS)
-
-#include "core/html/track/TextTrackRegion.h"
-
-#include "bindings/v8/ExceptionState.h"
-#include "bindings/v8/ExceptionStatePlaceholder.h"
-#include "core/dom/ClientRect.h"
-#include "core/dom/DOMTokenList.h"
-#include "core/html/HTMLDivElement.h"
-#include "core/html/track/WebVTTParser.h"
-#include "core/platform/Logging.h"
-#include "core/rendering/RenderInline.h"
-#include "core/rendering/RenderObject.h"
-#include "wtf/MathExtras.h"
-#include "wtf/text/StringBuilder.h"
-
-namespace WebCore {
-
-// The following values default values are defined within the WebVTT Regions Spec.
-// https://dvcs.w3.org/hg/text-tracks/raw-file/default/608toVTT/region.html
-
-// The region occupies by default 100% of the width of the video viewport.
-static const float defaultWidth = 100;
-
-// The region has, by default, 3 lines of text.
-static const long defaultHeightInLines = 3;
-
-// The region and viewport are anchored in the bottom left corner.
-static const float defaultAnchorPointX = 0;
-static const float defaultAnchorPointY = 100;
-
-// The region doesn't have scrolling text, by default.
-static const bool defaultScroll = false;
-
-// Default region line-height (vh units)
-static const float lineHeight = 5.33;
-
-// Default scrolling animation time period (s).
-static const float scrollTime = 0.433;
-
-TextTrackRegion::TextTrackRegion(ScriptExecutionContext* context)
- : ContextLifecycleObserver(context)
- , m_id(emptyString())
- , m_width(defaultWidth)
- , m_heightInLines(defaultHeightInLines)
- , m_regionAnchor(FloatPoint(defaultAnchorPointX, defaultAnchorPointY))
- , m_viewportAnchor(FloatPoint(defaultAnchorPointX, defaultAnchorPointY))
- , m_scroll(defaultScroll)
- , m_regionDisplayTree(0)
- , m_cueContainer(0)
- , m_track(0)
- , m_currentTop(0)
- , m_scrollTimer(this, &TextTrackRegion::scrollTimerFired)
-{
-}
-
-TextTrackRegion::~TextTrackRegion()
-{
-}
-
-void TextTrackRegion::setTrack(TextTrack* track)
-{
- m_track = track;
-}
-
-void TextTrackRegion::setId(const String& id)
-{
- m_id = id;
-}
-
-void TextTrackRegion::setWidth(double value, ExceptionState& es)
-{
- if (std::isinf(value) || std::isnan(value)) {
- es.throwTypeError();
- return;
- }
-
- if (value < 0 || value > 100) {
- es.throwDOMException(IndexSizeError);
- return;
- }
-
- m_width = value;
-}
-
-void TextTrackRegion::setHeight(long value, ExceptionState& es)
-{
- if (value < 0) {
- es.throwDOMException(IndexSizeError);
- return;
- }
-
- m_heightInLines = value;
-}
-
-void TextTrackRegion::setRegionAnchorX(double value, ExceptionState& es)
-{
- if (std::isinf(value) || std::isnan(value)) {
- es.throwTypeError();
- return;
- }
-
- if (value < 0 || value > 100) {
- es.throwDOMException(IndexSizeError);
- return;
- }
-
- m_regionAnchor.setX(value);
-}
-
-void TextTrackRegion::setRegionAnchorY(double value, ExceptionState& es)
-{
- if (std::isinf(value) || std::isnan(value)) {
- es.throwTypeError();
- return;
- }
-
- if (value < 0 || value > 100) {
- es.throwDOMException(IndexSizeError);
- return;
- }
-
- m_regionAnchor.setY(value);
-}
-
-void TextTrackRegion::setViewportAnchorX(double value, ExceptionState& es)
-{
- if (std::isinf(value) || std::isnan(value)) {
- es.throwTypeError();
- return;
- }
-
- if (value < 0 || value > 100) {
- es.throwDOMException(IndexSizeError);
- return;
- }
-
- m_viewportAnchor.setX(value);
-}
-
-void TextTrackRegion::setViewportAnchorY(double value, ExceptionState& es)
-{
- if (std::isinf(value) || std::isnan(value)) {
- es.throwTypeError();
- return;
- }
-
- if (value < 0 || value > 100) {
- es.throwDOMException(IndexSizeError);
- return;
- }
-
- m_viewportAnchor.setY(value);
-}
-
-const AtomicString TextTrackRegion::scroll() const
-{
- DEFINE_STATIC_LOCAL(const AtomicString, upScrollValueKeyword, ("up", AtomicString::ConstructFromLiteral));
-
- if (m_scroll)
- return upScrollValueKeyword;
-
- return "";
-}
-
-void TextTrackRegion::setScroll(const AtomicString& value, ExceptionState& es)
-{
- DEFINE_STATIC_LOCAL(const AtomicString, upScrollValueKeyword, ("up", AtomicString::ConstructFromLiteral));
-
- if (value != emptyString() && value != upScrollValueKeyword) {
- es.throwDOMException(SyntaxError);
- return;
- }
-
- m_scroll = value == upScrollValueKeyword;
-}
-
-void TextTrackRegion::updateParametersFromRegion(TextTrackRegion* region)
-{
- m_heightInLines = region->height();
- m_width = region->width();
-
- m_regionAnchor = FloatPoint(region->regionAnchorX(), region->regionAnchorY());
- m_viewportAnchor = FloatPoint(region->viewportAnchorX(), region->viewportAnchorY());
-
- setScroll(region->scroll(), ASSERT_NO_EXCEPTION);
-}
-
-void TextTrackRegion::setRegionSettings(const String& input)
-{
- m_settings = input;
- unsigned position = 0;
-
- while (position < input.length()) {
- while (position < input.length() && WebVTTParser::isValidSettingDelimiter(input[position]))
- position++;
-
- if (position >= input.length())
- break;
-
- parseSetting(input, &position);
- }
-}
-
-TextTrackRegion::RegionSetting TextTrackRegion::getSettingFromString(const String& setting)
-{
- DEFINE_STATIC_LOCAL(const AtomicString, idKeyword, ("id", AtomicString::ConstructFromLiteral));
- DEFINE_STATIC_LOCAL(const AtomicString, heightKeyword, ("height", AtomicString::ConstructFromLiteral));
- DEFINE_STATIC_LOCAL(const AtomicString, widthKeyword, ("width", AtomicString::ConstructFromLiteral));
- DEFINE_STATIC_LOCAL(const AtomicString, regionAnchorKeyword, ("regionanchor", AtomicString::ConstructFromLiteral));
- DEFINE_STATIC_LOCAL(const AtomicString, viewportAnchorKeyword, ("viewportanchor", AtomicString::ConstructFromLiteral));
- DEFINE_STATIC_LOCAL(const AtomicString, scrollKeyword, ("scroll", AtomicString::ConstructFromLiteral));
-
- if (setting == idKeyword)
- return Id;
- if (setting == heightKeyword)
- return Height;
- if (setting == widthKeyword)
- return Width;
- if (setting == viewportAnchorKeyword)
- return ViewportAnchor;
- if (setting == regionAnchorKeyword)
- return RegionAnchor;
- if (setting == scrollKeyword)
- return Scroll;
-
- return None;
-}
-
-void TextTrackRegion::parseSettingValue(RegionSetting setting, const String& value)
-{
- DEFINE_STATIC_LOCAL(const AtomicString, scrollUpValueKeyword, ("up", AtomicString::ConstructFromLiteral));
-
- bool isValidSetting;
- String numberAsString;
- int number;
- unsigned position;
- FloatPoint anchorPosition;
-
- switch (setting) {
- case Id:
- if (value.find("-->") == kNotFound)
- m_id = value;
- break;
- case Width:
- number = WebVTTParser::parseFloatPercentageValue(value, isValidSetting);
- if (isValidSetting)
- m_width = number;
- else
- LOG(Media, "TextTrackRegion::parseSettingValue, invalid Width");
- break;
- case Height:
- position = 0;
-
- numberAsString = WebVTTParser::collectDigits(value, &position);
- number = value.toInt(&isValidSetting);
-
- if (isValidSetting && number >= 0)
- m_heightInLines = number;
- else
- LOG(Media, "TextTrackRegion::parseSettingValue, invalid Height");
- break;
- case RegionAnchor:
- anchorPosition = WebVTTParser::parseFloatPercentageValuePair(value, ',', isValidSetting);
- if (isValidSetting)
- m_regionAnchor = anchorPosition;
- else
- LOG(Media, "TextTrackRegion::parseSettingValue, invalid RegionAnchor");
- break;
- case ViewportAnchor:
- anchorPosition = WebVTTParser::parseFloatPercentageValuePair(value, ',', isValidSetting);
- if (isValidSetting)
- m_viewportAnchor = anchorPosition;
- else
- LOG(Media, "TextTrackRegion::parseSettingValue, invalid ViewportAnchor");
- break;
- case Scroll:
- if (value == scrollUpValueKeyword)
- m_scroll = true;
- else
- LOG(Media, "TextTrackRegion::parseSettingValue, invalid Scroll");
- break;
- case None:
- break;
- }
-}
-
-void TextTrackRegion::parseSetting(const String& input, unsigned* position)
-{
- String setting = WebVTTParser::collectWord(input, position);
-
- size_t equalOffset = setting.find('=', 1);
- if (equalOffset == kNotFound || !equalOffset || equalOffset == setting.length() - 1)
- return;
-
- RegionSetting name = getSettingFromString(setting.substring(0, equalOffset));
- String value = setting.substring(equalOffset + 1, setting.length() - 1);
-
- parseSettingValue(name, value);
-}
-
-const AtomicString& TextTrackRegion::textTrackCueContainerShadowPseudoId()
-{
- DEFINE_STATIC_LOCAL(const AtomicString, trackRegionCueContainerPseudoId,
- ("-webkit-media-text-track-region-container", AtomicString::ConstructFromLiteral));
-
- return trackRegionCueContainerPseudoId;
-}
-
-const AtomicString& TextTrackRegion::textTrackCueContainerScrollingClass()
-{
- DEFINE_STATIC_LOCAL(const AtomicString, trackRegionCueContainerScrollingClass,
- ("scrolling", AtomicString::ConstructFromLiteral));
-
- return trackRegionCueContainerScrollingClass;
-}
-
-const AtomicString& TextTrackRegion::textTrackRegionShadowPseudoId()
-{
- DEFINE_STATIC_LOCAL(const AtomicString, trackRegionShadowPseudoId,
- ("-webkit-media-text-track-region", AtomicString::ConstructFromLiteral));
-
- return trackRegionShadowPseudoId;
-}
-
-PassRefPtr<HTMLDivElement> TextTrackRegion::getDisplayTree()
-{
- if (!m_regionDisplayTree) {
- m_regionDisplayTree = HTMLDivElement::create(ownerDocument());
- prepareRegionDisplayTree();
- }
-
- return m_regionDisplayTree;
-}
-
-void TextTrackRegion::willRemoveTextTrackCueBox(TextTrackCueBox* box)
-{
- LOG(Media, "TextTrackRegion::willRemoveTextTrackCueBox");
- ASSERT(m_cueContainer->contains(box));
-
- double boxHeight = box->getBoundingClientRect()->bottom() - box->getBoundingClientRect()->top();
- float regionBottom = m_regionDisplayTree->getBoundingClientRect()->bottom();
-
- m_cueContainer->classList()->remove(textTrackCueContainerScrollingClass(), ASSERT_NO_EXCEPTION);
-
- m_currentTop += boxHeight;
- m_cueContainer->setInlineStyleProperty(CSSPropertyTop, m_currentTop, CSSPrimitiveValue::CSS_PX);
-}
-
-
-void TextTrackRegion::appendTextTrackCueBox(PassRefPtr<TextTrackCueBox> displayBox)
-{
- if (m_cueContainer->contains(displayBox.get()))
- return;
-
- m_cueContainer->appendChild(displayBox);
- displayLastTextTrackCueBox();
-}
-
-void TextTrackRegion::displayLastTextTrackCueBox()
-{
- LOG(Media, "TextTrackRegion::displayLastTextTrackCueBox");
- ASSERT(m_cueContainer);
-
- // FIXME: This should not be causing recalc styles in a loop to set the "top" css
- // property to move elements. We should just scroll the text track cues on the
- // compositor with an animation.
-
- if (!m_scrollTimer.isActive())
- return;
-
- // If it's a scrolling region, add the scrolling class.
- if (isScrollingRegion())
- m_cueContainer->classList()->add(textTrackCueContainerScrollingClass(), ASSERT_NO_EXCEPTION);
-
- float regionBottom = m_regionDisplayTree->getBoundingClientRect()->bottom();
-
- // Find first cue that is not entirely displayed and scroll it upwards.
- for (int i = 0; i < m_cueContainer->childNodeCount() && !m_scrollTimer.isActive(); ++i) {
- float childTop = toHTMLDivElement(m_cueContainer->childNode(i))->getBoundingClientRect()->top();
- float childBottom = toHTMLDivElement(m_cueContainer->childNode(i))->getBoundingClientRect()->bottom();
-
- if (regionBottom >= childBottom)
- continue;
-
- float height = childBottom - childTop;
-
- m_currentTop -= std::min(height, childBottom - regionBottom);
- m_cueContainer->setInlineStyleProperty(CSSPropertyTop, m_currentTop, CSSPrimitiveValue::CSS_PX);
-
- startTimer();
- }
-}
-
-void TextTrackRegion::prepareRegionDisplayTree()
-{
- ASSERT(m_regionDisplayTree);
-
- // 7.2 Prepare region CSS boxes
-
- // FIXME: Change the code below to use viewport units when
- // http://crbug/244618 is fixed.
-
- // Let regionWidth be the text track region width.
- // Let width be 'regionWidth vw' ('vw' is a CSS unit)
- m_regionDisplayTree->setInlineStyleProperty(CSSPropertyWidth,
- m_width, CSSPrimitiveValue::CSS_PERCENTAGE);
-
- // Let lineHeight be '0.0533vh' ('vh' is a CSS unit) and regionHeight be
- // the text track region height. Let height be 'lineHeight' multiplied
- // by regionHeight.
- double height = lineHeight * m_heightInLines;
- m_regionDisplayTree->setInlineStyleProperty(CSSPropertyHeight,
- height, CSSPrimitiveValue::CSS_VH);
-
- // Let viewportAnchorX be the x dimension of the text track region viewport
- // anchor and regionAnchorX be the x dimension of the text track region
- // anchor. Let leftOffset be regionAnchorX multiplied by width divided by
- // 100.0. Let left be leftOffset subtracted from 'viewportAnchorX vw'.
- double leftOffset = m_regionAnchor.x() * m_width / 100;
- m_regionDisplayTree->setInlineStyleProperty(CSSPropertyLeft,
- m_viewportAnchor.x() - leftOffset,
- CSSPrimitiveValue::CSS_PERCENTAGE);
-
- // Let viewportAnchorY be the y dimension of the text track region viewport
- // anchor and regionAnchorY be the y dimension of the text track region
- // anchor. Let topOffset be regionAnchorY multiplied by height divided by
- // 100.0. Let top be topOffset subtracted from 'viewportAnchorY vh'.
- double topOffset = m_regionAnchor.y() * height / 100;
- m_regionDisplayTree->setInlineStyleProperty(CSSPropertyTop,
- m_viewportAnchor.y() - topOffset,
- CSSPrimitiveValue::CSS_PERCENTAGE);
-
-
- // The cue container is used to wrap the cues and it is the object which is
- // gradually scrolled out as multiple cues are appended to the region.
- m_cueContainer = HTMLDivElement::create(ownerDocument());
- m_cueContainer->setInlineStyleProperty(CSSPropertyTop,
- 0.0,
- CSSPrimitiveValue::CSS_PX);
-
- m_cueContainer->setPart(textTrackCueContainerShadowPseudoId());
- m_regionDisplayTree->appendChild(m_cueContainer);
-
- // 7.5 Every WebVTT region object is initialised with the following CSS
- m_regionDisplayTree->setPart(textTrackRegionShadowPseudoId());
-}
-
-void TextTrackRegion::startTimer()
-{
- LOG(Media, "TextTrackRegion::startTimer");
-
- if (m_scrollTimer.isActive())
- return;
-
- double duration = isScrollingRegion() ? scrollTime : 0;
- m_scrollTimer.startOneShot(duration);
-}
-
-void TextTrackRegion::stopTimer()
-{
- LOG(Media, "TextTrackRegion::stopTimer");
-
- if (m_scrollTimer.isActive())
- m_scrollTimer.stop();
-}
-
-void TextTrackRegion::scrollTimerFired(Timer<TextTrackRegion>*)
-{
- LOG(Media, "TextTrackRegion::scrollTimerFired");
-
- stopTimer();
- displayLastTextTrackCueBox();
-}
-
-} // namespace WebCore
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/html/track/TextTrackRegion.h b/chromium/third_party/WebKit/Source/core/html/track/TextTrackRegion.h
deleted file mode 100644
index f0642fb5580..00000000000
--- a/chromium/third_party/WebKit/Source/core/html/track/TextTrackRegion.h
+++ /dev/null
@@ -1,165 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TextTrackRegion_h
-#define TextTrackRegion_h
-
-#if ENABLE(WEBVTT_REGIONS)
-
-#include "core/dom/ContextLifecycleObserver.h"
-#include "core/dom/Document.h"
-#include "core/html/track/TextTrack.h"
-#include "core/platform/graphics/FloatPoint.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/RefCounted.h"
-
-namespace WebCore {
-
-class ExceptionState;
-class HTMLDivElement;
-class TextTrackCueBox;
-
-class TextTrackRegion : public RefCounted<TextTrackRegion>, public ContextLifecycleObserver {
-public:
- static PassRefPtr<TextTrackRegion> create(ScriptExecutionContext* context)
- {
- return adoptRef(new TextTrackRegion(context));
- }
-
- virtual ~TextTrackRegion();
-
- TextTrack* track() const { return m_track; }
- void setTrack(TextTrack*);
-
- const String& id() const { return m_id; }
- void setId(const String&);
-
- double width() const { return m_width; }
- void setWidth(double, ExceptionState&);
-
- long height() const { return m_heightInLines; }
- void setHeight(long, ExceptionState&);
-
- double regionAnchorX() const { return m_regionAnchor.x(); }
- void setRegionAnchorX(double, ExceptionState&);
-
- double regionAnchorY() const { return m_regionAnchor.y(); }
- void setRegionAnchorY(double, ExceptionState&);
-
- double viewportAnchorX() const { return m_viewportAnchor.x(); }
- void setViewportAnchorX(double, ExceptionState&);
-
- double viewportAnchorY() const { return m_viewportAnchor.y(); }
- void setViewportAnchorY(double, ExceptionState&);
-
- const AtomicString scroll() const;
- void setScroll(const AtomicString&, ExceptionState&);
-
- void updateParametersFromRegion(TextTrackRegion*);
-
- const String& regionSettings() const { return m_settings; }
- void setRegionSettings(const String&);
-
- bool isScrollingRegion() { return m_scroll; }
-
- PassRefPtr<HTMLDivElement> getDisplayTree();
-
- void appendTextTrackCueBox(PassRefPtr<TextTrackCueBox>);
- void displayLastTextTrackCueBox();
- void willRemoveTextTrackCueBox(TextTrackCueBox*);
-
-private:
- TextTrackRegion(ScriptExecutionContext*);
- Document* ownerDocument() { return toDocument(m_scriptExecutionContext); }
-
- void prepareRegionDisplayTree();
-
- // The timer is needed to continue processing when cue scrolling ended.
- void startTimer();
- void stopTimer();
- void scrollTimerFired(Timer<TextTrackRegion>*);
-
- enum RegionSetting {
- None,
- Id,
- Width,
- Height,
- RegionAnchor,
- ViewportAnchor,
- Scroll
- };
-
- RegionSetting getSettingFromString(const String&);
-
- void parseSettingValue(RegionSetting, const String&);
- void parseSetting(const String&, unsigned*);
-
- static const AtomicString& textTrackCueContainerShadowPseudoId();
- static const AtomicString& textTrackCueContainerScrollingClass();
- static const AtomicString& textTrackRegionShadowPseudoId();
-
- String m_id;
- String m_settings;
-
- double m_width;
- unsigned m_heightInLines;
-
- FloatPoint m_regionAnchor;
- FloatPoint m_viewportAnchor;
-
- bool m_scroll;
-
- RefPtr<HTMLDivElement> m_regionDisplayTree;
-
- // The cue container is the container that is scrolled up to obtain the
- // effect of scrolling cues when this is enabled for the regions.
- RefPtr<HTMLDivElement> m_cueContainer;
-
- // The member variable track can be a raw pointer as it will never
- // reference a destroyed TextTrack, as this member variable
- // is cleared in the TextTrack destructor and it is generally
- // set/reset within the addRegion and removeRegion methods.
- TextTrack* m_track;
-
- // Keep track of the current numeric value of the css "top" property.
- double m_currentTop;
-
- // The timer is used to display the next cue line after the current one has
- // been displayed. It's main use is for scrolling regions and it triggers as
- // soon as the animation for rolling out one line has finished, but
- // currently it is used also for non-scrolling regions to use a single
- // code path.
- Timer<TextTrackRegion> m_scrollTimer;
-};
-
-} // namespace WebCore
-
-#endif
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/html/track/TextTrackRegion.idl b/chromium/third_party/WebKit/Source/core/html/track/TextTrackRegion.idl
deleted file mode 100644
index 62ca08e9a94..00000000000
--- a/chromium/third_party/WebKit/Source/core/html/track/TextTrackRegion.idl
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-[
- Conditional=WEBVTT_REGIONS,
- Constructor(),
- EnabledAtRuntime=VideoTrack,
- ConstructorCallWith=ScriptExecutionContext
-] interface TextTrackRegion {
- readonly attribute TextTrack track;
-
- attribute DOMString id;
- [SetterRaisesException] attribute double width;
- [SetterRaisesException] attribute long height;
- [SetterRaisesException] attribute double regionAnchorX;
- [SetterRaisesException] attribute double regionAnchorY;
- [SetterRaisesException] attribute double viewportAnchorX;
- [SetterRaisesException] attribute double viewportAnchorY;
- [SetterRaisesException] attribute DOMString scroll;
-};
-
diff --git a/chromium/third_party/WebKit/Source/core/html/track/TextTrackRegionList.cpp b/chromium/third_party/WebKit/Source/core/html/track/TextTrackRegionList.cpp
deleted file mode 100644
index 8004a9c76a0..00000000000
--- a/chromium/third_party/WebKit/Source/core/html/track/TextTrackRegionList.cpp
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#if ENABLE(WEBVTT_REGIONS)
-
-#include "core/html/track/TextTrackRegionList.h"
-
-namespace WebCore {
-
-TextTrackRegionList::TextTrackRegionList()
-{
-}
-
-unsigned long TextTrackRegionList::length() const
-{
- return m_list.size();
-}
-
-TextTrackRegion* TextTrackRegionList::item(unsigned index) const
-{
- if (index < m_list.size())
- return m_list[index].get();
-
- return 0;
-}
-
-TextTrackRegion* TextTrackRegionList::getRegionById(const String& id) const
-{
- if (id.isEmpty())
- return 0;
-
- for (size_t i = 0; i < m_list.size(); ++i) {
- if (m_list[i]->id() == id)
- return m_list[i].get();
- }
-
- return 0;
-}
-
-void TextTrackRegionList::add(PassRefPtr<TextTrackRegion> region)
-{
- m_list.append(region);
-}
-
-bool TextTrackRegionList::remove(TextTrackRegion* region)
-{
- size_t index = m_list.find(region);
- if (index == kNotFound)
- return false;
-
- m_list.remove(index);
- return true;
-}
-
-void TextTrackRegionList::clear()
-{
- m_list.clear();
-}
-
-} // namespace WebCore
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/html/track/TextTrackRegionList.h b/chromium/third_party/WebKit/Source/core/html/track/TextTrackRegionList.h
deleted file mode 100644
index dd8a64ebc6b..00000000000
--- a/chromium/third_party/WebKit/Source/core/html/track/TextTrackRegionList.h
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TextTrackRegionList_h
-#define TextTrackRegionList_h
-
-#if ENABLE(WEBVTT_REGIONS)
-
-#include "core/html/track/TextTrackRegion.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-class TextTrackRegionList : public RefCounted<TextTrackRegionList> {
-public:
- static PassRefPtr<TextTrackRegionList> create()
- {
- return adoptRef(new TextTrackRegionList());
- }
-
- ~TextTrackRegionList() { }
-
- unsigned long length() const;
-
- TextTrackRegion* item(unsigned index) const;
- TextTrackRegion* getRegionById(const String&) const;
-
- void add(PassRefPtr<TextTrackRegion>);
- bool remove(TextTrackRegion*);
-
-private:
- TextTrackRegionList();
- void clear();
-
- Vector<RefPtr<TextTrackRegion> > m_list;
-};
-
-} // namespace WebCore
-
-#endif
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/html/track/TextTrackRegionList.idl b/chromium/third_party/WebKit/Source/core/html/track/TextTrackRegionList.idl
deleted file mode 100644
index 844cd9d1a6e..00000000000
--- a/chromium/third_party/WebKit/Source/core/html/track/TextTrackRegionList.idl
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-[
- NoInterfaceObject,
- Conditional=WEBVTT_REGIONS,
- EnabledAtRuntime=VideoTrack
-] interface TextTrackRegionList {
- readonly attribute unsigned long length;
- getter TextTrackRegion item(unsigned long index);
- TextTrackRegion getRegionById(DOMString id);
-};
-
diff --git a/chromium/third_party/WebKit/Source/core/html/track/TrackBase.cpp b/chromium/third_party/WebKit/Source/core/html/track/TrackBase.cpp
deleted file mode 100644
index e76de1740b8..00000000000
--- a/chromium/third_party/WebKit/Source/core/html/track/TrackBase.cpp
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Copyright (C) 2011 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/html/track/TrackBase.h"
-
-namespace WebCore {
-
-TrackBase::TrackBase(ScriptExecutionContext* context, Type type)
- : m_scriptExecutionContext(context)
-{
- ASSERT(type != BaseTrack);
- m_type = type;
-}
-
-TrackBase::~TrackBase()
-{
-}
-
-const AtomicString& TrackBase::interfaceName() const
-{
- return eventNames().interfaceForTextTrack;
-}
-
-ScriptExecutionContext* TrackBase::scriptExecutionContext() const
-{
- return m_scriptExecutionContext;
-}
-
-EventTargetData* TrackBase::eventTargetData()
-{
- return &m_eventTargetData;
-}
-
-EventTargetData* TrackBase::ensureEventTargetData()
-{
- return &m_eventTargetData;
-}
-
-} // namespace WebCore
-
diff --git a/chromium/third_party/WebKit/Source/core/html/track/TrackBase.h b/chromium/third_party/WebKit/Source/core/html/track/TrackBase.h
index c8b592765a0..38ead6489f0 100644
--- a/chromium/third_party/WebKit/Source/core/html/track/TrackBase.h
+++ b/chromium/third_party/WebKit/Source/core/html/track/TrackBase.h
@@ -26,40 +26,24 @@
#ifndef TrackBase_h
#define TrackBase_h
-#include "core/dom/EventTarget.h"
+#include "core/events/EventTarget.h"
#include "wtf/RefCounted.h"
namespace WebCore {
-class ScriptExecutionContext;
-
-class TrackBase : public RefCounted<TrackBase>, public EventTarget {
+class TrackBase : public RefCounted<TrackBase>, public EventTargetWithInlineData {
+ REFCOUNTED_EVENT_TARGET(TrackBase);
public:
- virtual ~TrackBase();
+ virtual ~TrackBase() { }
- enum Type { BaseTrack, TextTrack, AudioTrack, VideoTrack };
+ enum Type { TextTrack, AudioTrack, VideoTrack };
Type type() const { return m_type; }
- virtual const AtomicString& interfaceName() const;
- virtual ScriptExecutionContext* scriptExecutionContext() const;
-
- using RefCounted<TrackBase>::ref;
- using RefCounted<TrackBase>::deref;
-
protected:
- TrackBase(ScriptExecutionContext*, Type);
-
- virtual EventTargetData* eventTargetData();
- virtual EventTargetData* ensureEventTargetData();
+ explicit TrackBase(Type type) : m_type(type) { }
private:
Type m_type;
-
- virtual void refEventTarget() { ref(); }
- virtual void derefEventTarget() { deref(); }
-
- ScriptExecutionContext* m_scriptExecutionContext;
- EventTargetData m_eventTargetData;
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/html/track/TrackEvent.cpp b/chromium/third_party/WebKit/Source/core/html/track/TrackEvent.cpp
index 7e20843d39f..39d70bd1961 100644
--- a/chromium/third_party/WebKit/Source/core/html/track/TrackEvent.cpp
+++ b/chromium/third_party/WebKit/Source/core/html/track/TrackEvent.cpp
@@ -27,7 +27,7 @@
#include "core/html/track/TrackEvent.h"
-#include "core/dom/EventNames.h"
+#include "core/events/ThreadLocalEventNames.h"
namespace WebCore {
@@ -54,7 +54,7 @@ TrackEvent::~TrackEvent()
const AtomicString& TrackEvent::interfaceName() const
{
- return eventNames().interfaceForTrackEvent;
+ return EventNames::TrackEvent;
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/html/track/TrackEvent.h b/chromium/third_party/WebKit/Source/core/html/track/TrackEvent.h
index 8df7bb70490..606bc1488cc 100644
--- a/chromium/third_party/WebKit/Source/core/html/track/TrackEvent.h
+++ b/chromium/third_party/WebKit/Source/core/html/track/TrackEvent.h
@@ -26,7 +26,7 @@
#ifndef TrackEvent_h
#define TrackEvent_h
-#include "core/dom/Event.h"
+#include "core/events/Event.h"
#include "core/html/track/TrackBase.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/html/track/TrackEvent.idl b/chromium/third_party/WebKit/Source/core/html/track/TrackEvent.idl
index c1dc03ecbc2..eed92389f38 100644
--- a/chromium/third_party/WebKit/Source/core/html/track/TrackEvent.idl
+++ b/chromium/third_party/WebKit/Source/core/html/track/TrackEvent.idl
@@ -24,9 +24,9 @@
*/
[
- EnabledAtRuntime=VideoTrack,
- ConstructorTemplate=Event
+ RuntimeEnabled=VideoTrack,
+ EventConstructor,
] interface TrackEvent : Event {
- [InitializedByEventConstructor, CustomGetter] readonly attribute object track;
+ [InitializedByEventConstructor, Custom=Getter] readonly attribute object track;
};
diff --git a/chromium/third_party/WebKit/Source/core/html/track/WebVTTElement.cpp b/chromium/third_party/WebKit/Source/core/html/track/WebVTTElement.cpp
deleted file mode 100644
index c988de0ab6e..00000000000
--- a/chromium/third_party/WebKit/Source/core/html/track/WebVTTElement.cpp
+++ /dev/null
@@ -1,121 +0,0 @@
-/*
- * Copyright (C) 2013 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/html/track/WebVTTElement.h"
-
-#include "HTMLElementFactory.h"
-
-namespace WebCore {
-
-static const QualifiedName& nodeTypeToTagName(WebVTTNodeType nodeType)
-{
- DEFINE_STATIC_LOCAL(QualifiedName, cTag, (nullAtom, "c", nullAtom));
- DEFINE_STATIC_LOCAL(QualifiedName, vTag, (nullAtom, "v", nullAtom));
- DEFINE_STATIC_LOCAL(QualifiedName, langTag, (nullAtom, "lang", nullAtom));
- DEFINE_STATIC_LOCAL(QualifiedName, bTag, (nullAtom, "b", nullAtom));
- DEFINE_STATIC_LOCAL(QualifiedName, uTag, (nullAtom, "u", nullAtom));
- DEFINE_STATIC_LOCAL(QualifiedName, iTag, (nullAtom, "i", nullAtom));
- DEFINE_STATIC_LOCAL(QualifiedName, rubyTag, (nullAtom, "ruby", nullAtom));
- DEFINE_STATIC_LOCAL(QualifiedName, rtTag, (nullAtom, "rt", nullAtom));
- switch (nodeType) {
- case WebVTTNodeTypeClass:
- return cTag;
- case WebVTTNodeTypeItalic:
- return iTag;
- case WebVTTNodeTypeLanguage:
- return langTag;
- case WebVTTNodeTypeBold:
- return bTag;
- case WebVTTNodeTypeUnderline:
- return uTag;
- case WebVTTNodeTypeRuby:
- return rubyTag;
- case WebVTTNodeTypeRubyText:
- return rtTag;
- case WebVTTNodeTypeVoice:
- return vTag;
- case WebVTTNodeTypeNone:
- default:
- ASSERT_NOT_REACHED();
- return cTag; // Make the compiler happy.
- }
-}
-
-WebVTTElement::WebVTTElement(WebVTTNodeType nodeType, Document* document)
- : Element(nodeTypeToTagName(nodeType), document, CreateElement)
- , m_isPastNode(0)
- , m_webVTTNodeType(nodeType)
-{
-}
-
-PassRefPtr<WebVTTElement> WebVTTElement::create(WebVTTNodeType nodeType, Document* document)
-{
- return adoptRef(new WebVTTElement(nodeType, document));
-}
-
-PassRefPtr<Element> WebVTTElement::cloneElementWithoutAttributesAndChildren()
-{
- RefPtr<WebVTTElement> clone = create(static_cast<WebVTTNodeType>(m_webVTTNodeType), &document());
- clone->setLanguage(m_language);
- return clone;
-}
-
-PassRefPtr<HTMLElement> WebVTTElement::createEquivalentHTMLElement(Document* document)
-{
- RefPtr<HTMLElement> htmlElement;
- switch (m_webVTTNodeType) {
- case WebVTTNodeTypeClass:
- case WebVTTNodeTypeLanguage:
- case WebVTTNodeTypeVoice:
- htmlElement = HTMLElementFactory::createHTMLElement(HTMLNames::spanTag, document);
- htmlElement.get()->setAttribute(HTMLNames::titleAttr, getAttribute(voiceAttributeName()));
- htmlElement.get()->setAttribute(HTMLNames::langAttr, getAttribute(langAttributeName()));
- break;
- case WebVTTNodeTypeItalic:
- htmlElement = HTMLElementFactory::createHTMLElement(HTMLNames::iTag, document);
- break;
- case WebVTTNodeTypeBold:
- htmlElement = HTMLElementFactory::createHTMLElement(HTMLNames::bTag, document);
- break;
- case WebVTTNodeTypeUnderline:
- htmlElement = HTMLElementFactory::createHTMLElement(HTMLNames::uTag, document);
- break;
- case WebVTTNodeTypeRuby:
- htmlElement = HTMLElementFactory::createHTMLElement(HTMLNames::rubyTag, document);
- break;
- case WebVTTNodeTypeRubyText:
- htmlElement = HTMLElementFactory::createHTMLElement(HTMLNames::rtTag, document);
- break;
- default:
- ASSERT_NOT_REACHED();
- }
-
- htmlElement.get()->setAttribute(HTMLNames::classAttr, getAttribute(HTMLNames::classAttr));
- return htmlElement;
-}
-
-} // namespace WebCore
-
diff --git a/chromium/third_party/WebKit/Source/core/html/track/WebVTTElement.h b/chromium/third_party/WebKit/Source/core/html/track/WebVTTElement.h
deleted file mode 100644
index 6eb1b8de8db..00000000000
--- a/chromium/third_party/WebKit/Source/core/html/track/WebVTTElement.h
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
- * Copyright (C) 2013 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "core/html/HTMLElement.h"
-
-namespace WebCore {
-
-enum WebVTTNodeType {
- WebVTTNodeTypeNone = 0,
- WebVTTNodeTypeClass,
- WebVTTNodeTypeItalic,
- WebVTTNodeTypeLanguage,
- WebVTTNodeTypeBold,
- WebVTTNodeTypeUnderline,
- WebVTTNodeTypeRuby,
- WebVTTNodeTypeRubyText,
- WebVTTNodeTypeVoice
-};
-
-class WebVTTElement FINAL : public Element {
-public:
- static PassRefPtr<WebVTTElement> create(const WebVTTNodeType, Document*);
- static PassRefPtr<WebVTTElement> create(const QualifiedName&, Document*);
- PassRefPtr<HTMLElement> createEquivalentHTMLElement(Document*);
-
- virtual PassRefPtr<Element> cloneElementWithoutAttributesAndChildren() OVERRIDE;
-
- void setWebVTTNodeType(WebVTTNodeType type) { m_webVTTNodeType = static_cast<unsigned>(type); }
- WebVTTNodeType webVTTNodeType() const { return static_cast<WebVTTNodeType>(m_webVTTNodeType); }
-
- bool isPastNode() const { return m_isPastNode; }
- void setIsPastNode(bool value) { m_isPastNode = value; }
-
- virtual bool isWebVTTElement() const OVERRIDE { return true; }
- AtomicString language() const { return m_language; }
- void setLanguage(AtomicString value) { m_language = value; }
-
- static const QualifiedName& voiceAttributeName()
- {
- DEFINE_STATIC_LOCAL(QualifiedName, voiceAttr, (nullAtom, "voice", nullAtom));
- return voiceAttr;
- }
-
- static const QualifiedName& langAttributeName()
- {
- DEFINE_STATIC_LOCAL(QualifiedName, voiceAttr, (nullAtom, "lang", nullAtom));
- return voiceAttr;
- }
-
-private:
- WebVTTElement(const QualifiedName&, Document*);
- WebVTTElement(WebVTTNodeType, Document*);
-
- unsigned m_isPastNode : 1;
- unsigned m_webVTTNodeType : 4;
-
- AtomicString m_language;
-};
-
-inline WebVTTElement* toWebVTTElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->isWebVTTElement());
- return static_cast<WebVTTElement*>(node);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toWebVTTElement(const WebVTTElement*);
-
-
-} // namespace WebCore
-
diff --git a/chromium/third_party/WebKit/Source/core/html/track/WebVTTParser.cpp b/chromium/third_party/WebKit/Source/core/html/track/WebVTTParser.cpp
deleted file mode 100644
index e249da4cfd6..00000000000
--- a/chromium/third_party/WebKit/Source/core/html/track/WebVTTParser.cpp
+++ /dev/null
@@ -1,575 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/html/track/WebVTTParser.h"
-
-#include "core/dom/ProcessingInstruction.h"
-#include "core/dom/Text.h"
-#include "core/html/track/WebVTTElement.h"
-#include "core/platform/text/SegmentedString.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-const double secondsPerHour = 3600;
-const double secondsPerMinute = 60;
-const double secondsPerMillisecond = 0.001;
-const double malformedTime = -1;
-const unsigned bomLength = 3;
-const unsigned fileIdentifierLength = 6;
-
-String WebVTTParser::collectDigits(const String& input, unsigned* position)
-{
- StringBuilder digits;
- while (*position < input.length() && isASCIIDigit(input[*position]))
- digits.append(input[(*position)++]);
- return digits.toString();
-}
-
-String WebVTTParser::collectWord(const String& input, unsigned* position)
-{
- StringBuilder string;
- while (*position < input.length() && !isASpace(input[*position]))
- string.append(input[(*position)++]);
- return string.toString();
-}
-
-#if ENABLE(WEBVTT_REGIONS)
-float WebVTTParser::parseFloatPercentageValue(const String& value, bool& isValidSetting)
-{
- // '%' must be present and at the end of the setting value.
- if (value.find('%', 1) != value.length() - 1) {
- isValidSetting = false;
- return 0;
- }
-
- unsigned position = 0;
-
- StringBuilder floatNumberAsString;
- floatNumberAsString.append(WebVTTParser::collectDigits(value, &position));
-
- if (value[position] == '.') {
- floatNumberAsString.append(".");
- position++;
-
- floatNumberAsString.append(WebVTTParser::collectDigits(value, &position));
- }
- float number = floatNumberAsString.toString().toFloat(&isValidSetting);
-
- if (isValidSetting && (number <= 0 || number >= 100))
- isValidSetting = false;
-
- return number;
-}
-
-FloatPoint WebVTTParser::parseFloatPercentageValuePair(const String& value, char delimiter, bool& isValidSetting)
-{
- // The delimiter can't be the first or second value because a pair of
- // percentages (x%,y%) implies that at least the first two characters
- // are the first percentage value.
- size_t delimiterOffset = value.find(delimiter, 2);
- if (delimiterOffset == kNotFound || delimiterOffset == value.length() - 1) {
- isValidSetting = false;
- return FloatPoint(0, 0);
- }
-
- bool isFirstValueValid;
- float firstCoord = parseFloatPercentageValue(value.substring(0, delimiterOffset), isFirstValueValid);
-
- bool isSecondValueValid;
- float secondCoord = parseFloatPercentageValue(value.substring(delimiterOffset + 1, value.length() - 1), isSecondValueValid);
-
- isValidSetting = isFirstValueValid && isSecondValueValid;
- return FloatPoint(firstCoord, secondCoord);
-}
-#endif
-
-WebVTTParser::WebVTTParser(WebVTTParserClient* client, ScriptExecutionContext* context)
- : m_scriptExecutionContext(context)
- , m_state(Initial)
- , m_currentStartTime(0)
- , m_currentEndTime(0)
- , m_tokenizer(WebVTTTokenizer::create())
- , m_client(client)
-{
-}
-
-void WebVTTParser::getNewCues(Vector<RefPtr<TextTrackCue> >& outputCues)
-{
- outputCues = m_cuelist;
- m_cuelist.clear();
-}
-
-#if ENABLE(WEBVTT_REGIONS)
-void WebVTTParser::getNewRegions(Vector<RefPtr<TextTrackRegion> >& outputRegions)
-{
- outputRegions = m_regionList;
- m_regionList.clear();
-}
-#endif
-
-void WebVTTParser::parseBytes(const char* data, unsigned length)
-{
- // 4.8.10.13.3 WHATWG WebVTT Parser algorithm.
- // 1-3 - Initial setup.
- unsigned position = 0;
-
- while (position < length) {
- String line = collectNextLine(data, length, &position);
-
- switch (m_state) {
- case Initial:
- // Buffer up at least 9 bytes before proceeding with checking for the file identifier.
- m_identifierData.append(data, length);
- if (m_identifierData.size() < bomLength + fileIdentifierLength)
- return;
-
- // 4-12 - Collect the first line and check for "WEBVTT".
- if (!hasRequiredFileIdentifier()) {
- if (m_client)
- m_client->fileFailedToParse();
- return;
- }
-
- m_state = Header;
- m_identifierData.clear();
- break;
-
- case Header:
- // 13-18 - Allow a header (comment area) under the WEBVTT line.
-#if ENABLE(WEBVTT_REGIONS)
- if (line.isEmpty()) {
- if (m_client && m_regionList.size())
- m_client->newRegionsParsed();
-
- m_state = Id;
- break;
- }
- collectHeader(line);
-
- break;
-
- case Metadata:
-#endif
- if (line.isEmpty())
- m_state = Id;
- break;
-
- case Id:
- // 19-29 - Allow any number of line terminators, then initialize new cue values.
- if (line.isEmpty())
- break;
- resetCueValues();
-
- // 30-39 - Check if this line contains an optional identifier or timing data.
- m_state = collectCueId(line);
- break;
-
- case TimingsAndSettings:
- // 40 - Collect cue timings and settings.
- m_state = collectTimingsAndSettings(line);
- break;
-
- case CueText:
- // 41-53 - Collect the cue text, create a cue, and add it to the output.
- m_state = collectCueText(line, length, position);
- break;
-
- case BadCue:
- // 54-62 - Collect and discard the remaining cue.
- m_state = ignoreBadCue(line);
- break;
- }
- }
-}
-
-bool WebVTTParser::hasRequiredFileIdentifier()
-{
- // A WebVTT file identifier consists of an optional BOM character,
- // the string "WEBVTT" followed by an optional space or tab character,
- // and any number of characters that are not line terminators ...
- unsigned position = 0;
- if (m_identifierData.size() >= bomLength && m_identifierData[0] == '\xEF' && m_identifierData[1] == '\xBB' && m_identifierData[2] == '\xBF')
- position += bomLength;
- String line = collectNextLine(m_identifierData.data(), m_identifierData.size(), &position);
-
- if (line.length() < fileIdentifierLength)
- return false;
- if (line.substring(0, fileIdentifierLength) != "WEBVTT")
- return false;
- if (line.length() > fileIdentifierLength && line[fileIdentifierLength] != ' ' && line[fileIdentifierLength] != '\t')
- return false;
-
- return true;
-}
-
-#if ENABLE(WEBVTT_REGIONS)
-void WebVTTParser::collectHeader(const String& line)
-{
- // 4.1 Extension of WebVTT header parsing (11 - 15)
- DEFINE_STATIC_LOCAL(const AtomicString, regionHeaderName, ("Region", AtomicString::ConstructFromLiteral));
-
- // 15.4 If line contains the character ":" (A U+003A COLON), then set metadata's
- // name to the substring of line before the first ":" character and
- // metadata's value to the substring after this character.
- if (!line.contains(":"))
- return;
-
- unsigned colonPosition = line.find(":");
- m_currentHeaderName = line.substring(0, colonPosition);
-
- // 15.5 If metadata's name equals "Region":
- if (m_currentHeaderName == regionHeaderName) {
- m_currentHeaderValue = line.substring(colonPosition + 1, line.length() - 1);
- // 15.5.1 - 15.5.8 Region creation: Let region be a new text track region [...]
- createNewRegion();
- }
-}
-#endif
-
-WebVTTParser::ParseState WebVTTParser::collectCueId(const String& line)
-{
- if (line.contains("-->"))
- return collectTimingsAndSettings(line);
- m_currentId = line;
- return TimingsAndSettings;
-}
-
-WebVTTParser::ParseState WebVTTParser::collectTimingsAndSettings(const String& line)
-{
- // 4.8.10.13.3 Collect WebVTT cue timings and settings.
- // 1-3 - Let input be the string being parsed and position be a pointer into input
- unsigned position = 0;
- skipWhiteSpace(line, &position);
-
- // 4-5 - Collect a WebVTT timestamp. If that fails, then abort and return failure. Otherwise, let cue's text track cue start time be the collected time.
- m_currentStartTime = collectTimeStamp(line, &position);
- if (m_currentStartTime == malformedTime)
- return BadCue;
- if (position >= line.length())
- return BadCue;
-
- skipWhiteSpace(line, &position);
-
- // 6-9 - If the next three characters are not "-->", abort and return failure.
- if (line.find("-->", position) == kNotFound)
- return BadCue;
- position += 3;
- if (position >= line.length())
- return BadCue;
-
- skipWhiteSpace(line, &position);
-
- // 10-11 - Collect a WebVTT timestamp. If that fails, then abort and return failure. Otherwise, let cue's text track cue end time be the collected time.
- m_currentEndTime = collectTimeStamp(line, &position);
- if (m_currentEndTime == malformedTime)
- return BadCue;
- skipWhiteSpace(line, &position);
-
- // 12 - Parse the WebVTT settings for the cue (conducted in TextTrackCue).
- m_currentSettings = line.substring(position, line.length()-1);
- return CueText;
-}
-
-WebVTTParser::ParseState WebVTTParser::collectCueText(const String& line, unsigned length, unsigned position)
-{
- if (line.isEmpty()) {
- createNewCue();
- return Id;
- }
- if (!m_currentContent.isEmpty())
- m_currentContent.append("\n");
- m_currentContent.append(line);
-
- if (position >= length)
- createNewCue();
-
- return CueText;
-}
-
-WebVTTParser::ParseState WebVTTParser::ignoreBadCue(const String& line)
-{
- if (!line.isEmpty())
- return BadCue;
- return Id;
-}
-
-PassRefPtr<DocumentFragment> WebVTTParser::createDocumentFragmentFromCueText(const String& text)
-{
- // Cue text processing based on
- // 4.8.10.13.4 WebVTT cue text parsing rules and
- // 4.8.10.13.5 WebVTT cue text DOM construction rules.
-
- ASSERT(m_scriptExecutionContext->isDocument());
- Document* document = toDocument(m_scriptExecutionContext);
- ASSERT(document);
-
- RefPtr<DocumentFragment> fragment = DocumentFragment::create(*document);
-
- if (!text.length()) {
- fragment->parserAppendChild(Text::create(*document, ""));
- return fragment;
- }
-
- m_currentNode = fragment;
- m_tokenizer->reset();
- m_token.clear();
-
- m_languageStack.clear();
- SegmentedString content(text);
- while (m_tokenizer->nextToken(content, m_token))
- constructTreeFromToken(*document);
-
- return fragment.release();
-}
-
-void WebVTTParser::createNewCue()
-{
- if (!m_currentContent.length())
- return;
-
- RefPtr<TextTrackCue> cue = TextTrackCue::create(m_scriptExecutionContext, m_currentStartTime, m_currentEndTime, m_currentContent.toString());
- cue->setId(m_currentId);
- cue->setCueSettings(m_currentSettings);
-
- m_cuelist.append(cue);
- if (m_client)
- m_client->newCuesParsed();
-}
-
-void WebVTTParser::resetCueValues()
-{
- m_currentId = emptyString();
- m_currentSettings = emptyString();
- m_currentStartTime = 0;
- m_currentEndTime = 0;
- m_currentContent.clear();
-}
-
-#if ENABLE(WEBVTT_REGIONS)
-void WebVTTParser::createNewRegion()
-{
- if (!m_currentHeaderValue.length())
- return;
-
- RefPtr<TextTrackRegion> region = TextTrackRegion::create(m_scriptExecutionContext);
- region->setRegionSettings(m_currentHeaderValue);
-
- // 15.5.10 If the text track list of regions regions contains a region
- // with the same region identifier value as region, remove that region.
- for (size_t i = 0; i < m_regionList.size(); ++i)
- if (m_regionList[i]->id() == region->id()) {
- m_regionList.remove(i);
- break;
- }
-
- m_regionList.append(region);
-}
-#endif
-
-double WebVTTParser::collectTimeStamp(const String& line, unsigned* position)
-{
- // 4.8.10.13.3 Collect a WebVTT timestamp.
- // 1-4 - Initial checks, let most significant units be minutes.
- enum Mode { minutes, hours };
- Mode mode = minutes;
- if (*position >= line.length() || !isASCIIDigit(line[*position]))
- return malformedTime;
-
- // 5-6 - Collect a sequence of characters that are 0-9.
- String digits1 = collectDigits(line, position);
- int value1 = digits1.toInt();
-
- // 7 - If not 2 characters or value is greater than 59, interpret as hours.
- if (digits1.length() != 2 || value1 > 59)
- mode = hours;
-
- // 8-12 - Collect the next sequence of 0-9 after ':' (must be 2 chars).
- if (*position >= line.length() || line[(*position)++] != ':')
- return malformedTime;
- if (*position >= line.length() || !isASCIIDigit(line[(*position)]))
- return malformedTime;
- String digits2 = collectDigits(line, position);
- int value2 = digits2.toInt();
- if (digits2.length() != 2)
- return malformedTime;
-
- // 13 - Detect whether this timestamp includes hours.
- int value3;
- if (mode == hours || (*position < line.length() && line[*position] == ':')) {
- if (*position >= line.length() || line[(*position)++] != ':')
- return malformedTime;
- if (*position >= line.length() || !isASCIIDigit(line[*position]))
- return malformedTime;
- String digits3 = collectDigits(line, position);
- if (digits3.length() != 2)
- return malformedTime;
- value3 = digits3.toInt();
- } else {
- value3 = value2;
- value2 = value1;
- value1 = 0;
- }
-
- // 14-19 - Collect next sequence of 0-9 after '.' (must be 3 chars).
- if (*position >= line.length() || line[(*position)++] != '.')
- return malformedTime;
- if (*position >= line.length() || !isASCIIDigit(line[*position]))
- return malformedTime;
- String digits4 = collectDigits(line, position);
- if (digits4.length() != 3)
- return malformedTime;
- int value4 = digits4.toInt();
- if (value2 > 59 || value3 > 59)
- return malformedTime;
-
- // 20-21 - Calculate result.
- return (value1 * secondsPerHour) + (value2 * secondsPerMinute) + value3 + (value4 * secondsPerMillisecond);
-}
-
-static WebVTTNodeType tokenToNodeType(WebVTTToken& token)
-{
- switch (token.name().size()) {
- case 1:
- if (token.name()[0] == 'c')
- return WebVTTNodeTypeClass;
- if (token.name()[0] == 'v')
- return WebVTTNodeTypeVoice;
- if (token.name()[0] == 'b')
- return WebVTTNodeTypeBold;
- if (token.name()[0] == 'i')
- return WebVTTNodeTypeItalic;
- if (token.name()[0] == 'u')
- return WebVTTNodeTypeUnderline;
- break;
- case 2:
- if (token.name()[0] == 'r' && token.name()[1] == 't')
- return WebVTTNodeTypeRubyText;
- break;
- case 4:
- if (token.name()[0] == 'r' && token.name()[1] == 'u' && token.name()[2] == 'b' && token.name()[3] == 'y')
- return WebVTTNodeTypeRuby;
- if (token.name()[0] == 'l' && token.name()[1] == 'a' && token.name()[2] == 'n' && token.name()[3] == 'g')
- return WebVTTNodeTypeLanguage;
- break;
- }
- return WebVTTNodeTypeNone;
-}
-
-void WebVTTParser::constructTreeFromToken(Document& document)
-{
- QualifiedName tagName(nullAtom, AtomicString(m_token.name()), xhtmlNamespaceURI);
-
- // http://dev.w3.org/html5/webvtt/#webvtt-cue-text-dom-construction-rules
-
- switch (m_token.type()) {
- case WebVTTTokenTypes::Character: {
- String content(m_token.characters()); // FIXME: This should be 8bit if possible.
- RefPtr<Text> child = Text::create(document, content);
- m_currentNode->parserAppendChild(child);
- break;
- }
- case WebVTTTokenTypes::StartTag: {
- RefPtr<WebVTTElement> child;
- WebVTTNodeType nodeType = tokenToNodeType(m_token);
- if (nodeType != WebVTTNodeTypeNone)
- child = WebVTTElement::create(nodeType, &document);
- if (child) {
- if (m_token.classes().size() > 0)
- child->setAttribute(classAttr, AtomicString(m_token.classes()));
-
- if (child->webVTTNodeType() == WebVTTNodeTypeVoice)
- child->setAttribute(WebVTTElement::voiceAttributeName(), AtomicString(m_token.annotation()));
- else if (child->webVTTNodeType() == WebVTTNodeTypeLanguage) {
- m_languageStack.append(AtomicString(m_token.annotation()));
- child->setAttribute(WebVTTElement::langAttributeName(), m_languageStack.last());
- }
- if (!m_languageStack.isEmpty())
- child->setLanguage(m_languageStack.last());
- m_currentNode->parserAppendChild(child);
- m_currentNode = child;
- }
- break;
- }
- case WebVTTTokenTypes::EndTag: {
- WebVTTNodeType nodeType = tokenToNodeType(m_token);
- if (nodeType != WebVTTNodeTypeNone) {
- if (nodeType == WebVTTNodeTypeLanguage && m_currentNode->isWebVTTElement() && toWebVTTElement(m_currentNode.get())->webVTTNodeType() == WebVTTNodeTypeLanguage)
- m_languageStack.removeLast();
- if (m_currentNode->parentNode())
- m_currentNode = m_currentNode->parentNode();
- }
- break;
- }
- case WebVTTTokenTypes::TimestampTag: {
- unsigned position = 0;
- String charactersString(StringImpl::create8BitIfPossible(m_token.characters()));
- double time = collectTimeStamp(charactersString, &position);
- if (time != malformedTime)
- m_currentNode->parserAppendChild(ProcessingInstruction::create(document, "timestamp", charactersString));
- break;
- }
- default:
- break;
- }
- m_token.clear();
-}
-
-void WebVTTParser::skipWhiteSpace(const String& line, unsigned* position)
-{
- while (*position < line.length() && isASpace(line[*position]))
- (*position)++;
-}
-
-void WebVTTParser::skipLineTerminator(const char* data, unsigned length, unsigned* position)
-{
- if (*position >= length)
- return;
- if (data[*position] == '\r')
- (*position)++;
- if (*position >= length)
- return;
- if (data[*position] == '\n')
- (*position)++;
-}
-
-String WebVTTParser::collectNextLine(const char* data, unsigned length, unsigned* position)
-{
- unsigned oldPosition = *position;
- while (*position < length && data[*position] != '\r' && data[*position] != '\n')
- (*position)++;
- String line = String::fromUTF8(data + oldPosition, *position - oldPosition);
- skipLineTerminator(data, length, position);
- return line;
-}
-
-}
-
diff --git a/chromium/third_party/WebKit/Source/core/html/track/WebVTTParser.h b/chromium/third_party/WebKit/Source/core/html/track/WebVTTParser.h
deleted file mode 100644
index c717e57e597..00000000000
--- a/chromium/third_party/WebKit/Source/core/html/track/WebVTTParser.h
+++ /dev/null
@@ -1,175 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef WebVTTParser_h
-#define WebVTTParser_h
-
-#include "HTMLNames.h"
-#include "core/dom/DocumentFragment.h"
-#include "core/html/track/TextTrackCue.h"
-#include "core/html/track/TextTrackRegion.h"
-#include "core/html/track/WebVTTTokenizer.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/text/StringBuilder.h"
-
-namespace WebCore {
-
-using namespace HTMLNames;
-
-class Document;
-
-class WebVTTParserClient {
-public:
- virtual ~WebVTTParserClient() { }
-
- virtual void newCuesParsed() = 0;
-#if ENABLE(WEBVTT_REGIONS)
- virtual void newRegionsParsed() = 0;
-#endif
- virtual void fileFailedToParse() = 0;
-};
-
-class WebVTTParser {
-public:
- virtual ~WebVTTParser() { }
-
- enum ParseState {
- Initial,
- Header,
-#if ENABLE(WEBVTT_REGIONS)
- Metadata,
-#endif
- Id,
- TimingsAndSettings,
- CueText,
- BadCue
- };
-
- static PassOwnPtr<WebVTTParser> create(WebVTTParserClient* client, ScriptExecutionContext* context)
- {
- return adoptPtr(new WebVTTParser(client, context));
- }
-
- static inline bool isRecognizedTag(const AtomicString& tagName)
- {
- return tagName == iTag
- || tagName == bTag
- || tagName == uTag
- || tagName == rubyTag
- || tagName == rtTag;
- }
-
- static inline bool isASpace(char c)
- {
- // WebVTT space characters are U+0020 SPACE, U+0009 CHARACTER TABULATION (tab), U+000A LINE FEED (LF), U+000C FORM FEED (FF), and U+000D CARRIAGE RETURN (CR).
- return c == ' ' || c == '\t' || c == '\n' || c == '\f' || c == '\r';
- }
- static inline bool isValidSettingDelimiter(char c)
- {
- // ... a WebVTT cue consists of zero or more of the following components, in any order, separated from each other by one or more
- // U+0020 SPACE characters or U+0009 CHARACTER TABULATION (tab) characters.
- return c == ' ' || c == '\t';
- }
- static String collectDigits(const String&, unsigned*);
- static String collectWord(const String&, unsigned*);
-
-#if ENABLE(WEBVTT_REGIONS)
- // Useful functions for parsing percentage settings.
- static float parseFloatPercentageValue(const String&, bool&);
- static FloatPoint parseFloatPercentageValuePair(const String&, char, bool&);
-#endif
-
- // Input data to the parser to parse.
- void parseBytes(const char* data, unsigned length);
-
- // Transfers ownership of last parsed cues to caller.
- void getNewCues(Vector<RefPtr<TextTrackCue> >&);
-#if ENABLE(WEBVTT_REGIONS)
- void getNewRegions(Vector<RefPtr<TextTrackRegion> >&);
-#endif
-
- PassRefPtr<DocumentFragment> createDocumentFragmentFromCueText(const String&);
- double collectTimeStamp(const String&, unsigned*);
-
-protected:
- WebVTTParser(WebVTTParserClient*, ScriptExecutionContext*);
-
- ScriptExecutionContext* m_scriptExecutionContext;
- ParseState m_state;
-
-private:
- bool hasRequiredFileIdentifier();
- ParseState collectCueId(const String&);
- ParseState collectTimingsAndSettings(const String&);
- ParseState collectCueText(const String&, unsigned length, unsigned);
- ParseState ignoreBadCue(const String&);
-
- void createNewCue();
- void resetCueValues();
-
-#if ENABLE(WEBVTT_REGIONS)
- void collectHeader(const String&);
- void createNewRegion();
-#endif
-
- void skipWhiteSpace(const String&, unsigned*);
- static void skipLineTerminator(const char* data, unsigned length, unsigned*);
- static String collectNextLine(const char* data, unsigned length, unsigned*);
-
- void constructTreeFromToken(Document&);
-
- String m_currentHeaderName;
- String m_currentHeaderValue;
-
- Vector<char> m_identifierData;
- String m_currentId;
- double m_currentStartTime;
- double m_currentEndTime;
- StringBuilder m_currentContent;
- String m_currentSettings;
-
- WebVTTToken m_token;
- OwnPtr<WebVTTTokenizer> m_tokenizer;
-
- RefPtr<ContainerNode> m_currentNode;
-
- WebVTTParserClient* m_client;
-
- Vector<AtomicString> m_languageStack;
- Vector<RefPtr<TextTrackCue> > m_cuelist;
-
-#if ENABLE(WEBVTT_REGIONS)
- Vector<RefPtr<TextTrackRegion> > m_regionList;
-#endif
-};
-
-} // namespace WebCore
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/html/track/WebVTTToken.h b/chromium/third_party/WebKit/Source/core/html/track/WebVTTToken.h
deleted file mode 100644
index 0111eb8661b..00000000000
--- a/chromium/third_party/WebKit/Source/core/html/track/WebVTTToken.h
+++ /dev/null
@@ -1,209 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef WebVTTToken_h
-#define WebVTTToken_h
-
-namespace WebCore {
-
-class WebVTTTokenTypes {
-public:
- enum Type {
- Uninitialized,
- Character,
- StartTag,
- EndTag,
- TimestampTag,
- EndOfFile,
- };
-};
-
-class WebVTTToken {
- WTF_MAKE_NONCOPYABLE(WebVTTToken);
- WTF_MAKE_FAST_ALLOCATED;
-public:
- typedef WebVTTTokenTypes Type;
- typedef WTF::Vector<UChar, 1024> DataVector; // FIXME: Is this too large for WebVTT?
-
- WebVTTToken() { clear(); }
-
- void appendToName(UChar character)
- {
- ASSERT(m_type == WebVTTTokenTypes::StartTag || m_type == WebVTTTokenTypes::EndTag);
- ASSERT(character);
- m_data.append(character);
- }
-
- Type::Type type() const { return m_type; }
-
- const DataVector& name() const
- {
- return m_data;
- }
-
- const DataVector& characters() const
- {
- ASSERT(m_type == Type::Character || m_type == Type::TimestampTag);
- return m_data;
- }
-
- // Starting a character token works slightly differently than starting
- // other types of tokens because we want to save a per-character branch.
- void ensureIsCharacterToken()
- {
- ASSERT(m_type == Type::Uninitialized || m_type == Type::Character);
- m_type = Type::Character;
- }
-
- void appendToCharacter(char character)
- {
- ASSERT(m_type == Type::Character);
- m_data.append(character);
- }
-
- void appendToCharacter(UChar character)
- {
- ASSERT(m_type == Type::Character);
- m_data.append(character);
- }
-
- void appendToCharacter(const Vector<LChar, 32>& characters)
- {
- ASSERT(m_type == Type::Character);
- m_data.appendVector(characters);
- }
-
- void beginEmptyStartTag()
- {
- ASSERT(m_type == Type::Uninitialized);
- m_type = Type::StartTag;
- m_data.clear();
- }
-
- void beginStartTag(UChar character)
- {
- ASSERT(character);
- ASSERT(m_type == Type::Uninitialized);
- m_type = Type::StartTag;
- m_data.append(character);
- }
-
- void beginEndTag(LChar character)
- {
- ASSERT(m_type == Type::Uninitialized);
- m_type = Type::EndTag;
- m_data.append(character);
- }
-
- void beginTimestampTag(UChar character)
- {
- ASSERT(character);
- ASSERT(m_type == Type::Uninitialized);
- m_type = Type::TimestampTag;
- m_data.append(character);
- }
-
- void appendToTimestamp(UChar character)
- {
- ASSERT(character);
- ASSERT(m_type == Type::TimestampTag);
- m_data.append(character);
- }
-
- void appendToClass(UChar character)
- {
- appendToStartType(character);
- }
-
- void addNewClass()
- {
- ASSERT(m_type == Type::StartTag);
- if (!m_classes.isEmpty())
- m_classes.append(' ');
- m_classes.append(m_currentBuffer);
- m_currentBuffer.clear();
- }
-
- const DataVector& classes() const
- {
- return m_classes;
- }
-
- void appendToAnnotation(UChar character)
- {
- appendToStartType(character);
- }
-
- void addNewAnnotation()
- {
- ASSERT(m_type == Type::StartTag);
- m_annotation.clear();
- m_annotation.append(m_currentBuffer);
- m_currentBuffer.clear();
- }
-
- const DataVector& annotation() const
- {
- return m_annotation;
- }
-
- void makeEndOfFile()
- {
- ASSERT(m_type == Type::Uninitialized);
- m_type = Type::EndOfFile;
- }
-
- void clear()
- {
- m_type = Type::Uninitialized;
- m_data.clear();
- m_annotation.clear();
- m_classes.clear();
- m_currentBuffer.clear();
- }
-
-private:
- void appendToStartType(UChar character)
- {
- ASSERT(character);
- ASSERT(m_type == Type::StartTag);
- m_currentBuffer.append(character);
- }
-
- Type::Type m_type;
- DataVector m_data;
- DataVector m_annotation;
- DataVector m_classes;
- DataVector m_currentBuffer;
-};
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/html/track/WebVTTTokenizer.cpp b/chromium/third_party/WebKit/Source/core/html/track/WebVTTTokenizer.cpp
deleted file mode 100644
index f290cb67e27..00000000000
--- a/chromium/third_party/WebKit/Source/core/html/track/WebVTTTokenizer.cpp
+++ /dev/null
@@ -1,228 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/html/track/WebVTTTokenizer.h"
-
-#include "core/xml/parser/MarkupTokenizerInlines.h"
-
-namespace WebCore {
-
-#define WEBVTT_BEGIN_STATE(stateName) BEGIN_STATE(WebVTTTokenizerState, stateName)
-#define WEBVTT_ADVANCE_TO(stateName) ADVANCE_TO(WebVTTTokenizerState, stateName)
-
-WebVTTTokenizer::WebVTTTokenizer()
- : m_inputStreamPreprocessor(this)
-{
- reset();
-}
-
-template <typename CharacterType>
-inline bool vectorEqualsString(const Vector<CharacterType, 32>& vector, const String& string)
-{
- if (vector.size() != string.length())
- return false;
-
- if (!string.length())
- return true;
-
- return equal(string.impl(), vector.data(), vector.size());
-}
-
-void WebVTTTokenizer::reset()
-{
- m_state = WebVTTTokenizerState::DataState;
- m_token = 0;
- m_buffer.clear();
-}
-
-bool WebVTTTokenizer::nextToken(SegmentedString& source, WebVTTToken& token)
-{
- // If we have a token in progress, then we're supposed to be called back
- // with the same token so we can finish it.
- ASSERT(!m_token || m_token == &token || token.type() == WebVTTTokenTypes::Uninitialized);
- m_token = &token;
-
- if (source.isEmpty() || !m_inputStreamPreprocessor.peek(source))
- return haveBufferedCharacterToken();
-
- UChar cc = m_inputStreamPreprocessor.nextInputCharacter();
-
- // 4.8.10.13.4 WebVTT cue text tokenizer
- switch (m_state) {
- WEBVTT_BEGIN_STATE(DataState) {
- if (cc == '&') {
- m_buffer.append(static_cast<LChar>(cc));
- WEBVTT_ADVANCE_TO(EscapeState);
- } else if (cc == '<') {
- // FIXME: the explicit Vector conversion copies into a temporary
- // and is wasteful.
- if (m_token->type() == WebVTTTokenTypes::Uninitialized
- || vectorEqualsString<UChar>(Vector<UChar, 32>(m_token->characters()), emptyString()))
- WEBVTT_ADVANCE_TO(TagState);
- else
- return emitAndResumeIn(source, WebVTTTokenizerState::TagState);
- } else if (cc == kEndOfFileMarker)
- return emitEndOfFile(source);
- else {
- bufferCharacter(cc);
- WEBVTT_ADVANCE_TO(DataState);
- }
- }
- END_STATE()
-
- WEBVTT_BEGIN_STATE(EscapeState) {
- if (cc == ';') {
- if (vectorEqualsString(m_buffer, "&amp"))
- bufferCharacter('&');
- else if (vectorEqualsString(m_buffer, "&lt"))
- bufferCharacter('<');
- else if (vectorEqualsString(m_buffer, "&gt"))
- bufferCharacter('>');
- else {
- m_buffer.append(static_cast<LChar>(cc));
- m_token->appendToCharacter(m_buffer);
- }
- m_buffer.clear();
- WEBVTT_ADVANCE_TO(DataState);
- } else if (isASCIIAlphanumeric(cc)) {
- m_buffer.append(static_cast<LChar>(cc));
- WEBVTT_ADVANCE_TO(EscapeState);
- } else if (cc == kEndOfFileMarker) {
- m_token->appendToCharacter(m_buffer);
- return emitEndOfFile(source);
- } else {
- if (!vectorEqualsString(m_buffer, "&"))
- m_token->appendToCharacter(m_buffer);
- m_buffer.clear();
- WEBVTT_ADVANCE_TO(DataState);
- }
- }
- END_STATE()
-
- WEBVTT_BEGIN_STATE(TagState) {
- if (isTokenizerWhitespace(cc)) {
- m_token->beginEmptyStartTag();
- WEBVTT_ADVANCE_TO(StartTagAnnotationState);
- } else if (cc == '.') {
- m_token->beginEmptyStartTag();
- WEBVTT_ADVANCE_TO(StartTagClassState);
- } else if (cc == '/') {
- WEBVTT_ADVANCE_TO(EndTagOpenState);
- } else if (WTF::isASCIIDigit(cc)) {
- m_token->beginTimestampTag(cc);
- WEBVTT_ADVANCE_TO(TimestampTagState);
- } else if (cc == '>' || cc == kEndOfFileMarker) {
- m_token->beginEmptyStartTag();
- return emitAndResumeIn(source, WebVTTTokenizerState::DataState);
- } else {
- m_token->beginStartTag(cc);
- WEBVTT_ADVANCE_TO(StartTagState);
- }
- }
- END_STATE()
-
- WEBVTT_BEGIN_STATE(StartTagState) {
- if (isTokenizerWhitespace(cc))
- WEBVTT_ADVANCE_TO(StartTagAnnotationState);
- else if (cc == '.')
- WEBVTT_ADVANCE_TO(StartTagClassState);
- else if (cc == '>' || cc == kEndOfFileMarker)
- return emitAndResumeIn(source, WebVTTTokenizerState::DataState);
- else {
- m_token->appendToName(cc);
- WEBVTT_ADVANCE_TO(StartTagState);
- }
- }
- END_STATE()
-
- WEBVTT_BEGIN_STATE(StartTagClassState) {
- if (isTokenizerWhitespace(cc)) {
- m_token->addNewClass();
- WEBVTT_ADVANCE_TO(StartTagAnnotationState);
- } else if (cc == '.') {
- m_token->addNewClass();
- WEBVTT_ADVANCE_TO(StartTagClassState);
- } else if (cc == '>' || cc == kEndOfFileMarker) {
- m_token->addNewClass();
- return emitAndResumeIn(source, WebVTTTokenizerState::DataState);
- } else {
- m_token->appendToClass(cc);
- WEBVTT_ADVANCE_TO(StartTagClassState);
- }
-
- }
- END_STATE()
-
- WEBVTT_BEGIN_STATE(StartTagAnnotationState) {
- if (cc == '>' || cc == kEndOfFileMarker) {
- m_token->addNewAnnotation();
- return emitAndResumeIn(source, WebVTTTokenizerState::DataState);
- }
- m_token->appendToAnnotation(cc);
- WEBVTT_ADVANCE_TO(StartTagAnnotationState);
- }
- END_STATE()
-
- WEBVTT_BEGIN_STATE(EndTagOpenState) {
- if (cc == '>' || cc == kEndOfFileMarker) {
- m_token->beginEndTag('\0');
- return emitAndResumeIn(source, WebVTTTokenizerState::DataState);
- }
- m_token->beginEndTag(cc);
- WEBVTT_ADVANCE_TO(EndTagState);
- }
- END_STATE()
-
- WEBVTT_BEGIN_STATE(EndTagState) {
- if (cc == '>' || cc == kEndOfFileMarker)
- return emitAndResumeIn(source, WebVTTTokenizerState::DataState);
- m_token->appendToName(cc);
- WEBVTT_ADVANCE_TO(EndTagState);
- }
- END_STATE()
-
- WEBVTT_BEGIN_STATE(TimestampTagState) {
- if (cc == '>' || cc == kEndOfFileMarker)
- return emitAndResumeIn(source, WebVTTTokenizerState::DataState);
- m_token->appendToTimestamp(cc);
- WEBVTT_ADVANCE_TO(TimestampTagState);
- }
- END_STATE()
-
- }
-
- ASSERT_NOT_REACHED();
- return false;
-}
-
-}
-
diff --git a/chromium/third_party/WebKit/Source/core/html/track/WebVTTTokenizer.h b/chromium/third_party/WebKit/Source/core/html/track/WebVTTTokenizer.h
deleted file mode 100644
index 097f5089bd7..00000000000
--- a/chromium/third_party/WebKit/Source/core/html/track/WebVTTTokenizer.h
+++ /dev/null
@@ -1,115 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef WebVTTTokenizer_h
-#define WebVTTTokenizer_h
-
-#include "core/html/parser/InputStreamPreprocessor.h"
-#include "core/html/track/WebVTTToken.h"
-#include "wtf/PassOwnPtr.h"
-
-namespace WebCore {
-
-class WebVTTTokenizerState {
-public:
- enum State {
- DataState,
- EscapeState,
- TagState,
- StartTagState,
- StartTagClassState,
- StartTagAnnotationState,
- EndTagState,
- EndTagOpenState,
- TimestampTagState,
- };
-};
-
-class WebVTTTokenizer {
- WTF_MAKE_NONCOPYABLE(WebVTTTokenizer);
- WTF_MAKE_FAST_ALLOCATED;
-public:
- static PassOwnPtr<WebVTTTokenizer> create() { return adoptPtr(new WebVTTTokenizer); }
-
- typedef WebVTTTokenizerState State;
-
- void reset();
-
- bool nextToken(SegmentedString&, WebVTTToken&);
-
- inline bool haveBufferedCharacterToken()
- {
- return m_token->type() == WebVTTToken::Type::Character;
- }
-
- inline void bufferCharacter(UChar character)
- {
- ASSERT(character != kEndOfFileMarker);
- m_token->ensureIsCharacterToken();
- m_token->appendToCharacter(character);
- }
-
- inline bool emitAndResumeIn(SegmentedString& source, State::State state)
- {
- m_state = state;
- source.advanceAndUpdateLineNumber();
- return true;
- }
-
- inline bool emitEndOfFile(SegmentedString& source)
- {
- if (haveBufferedCharacterToken())
- return true;
- m_state = State::DataState;
- source.advanceAndUpdateLineNumber();
- m_token->clear();
- m_token->makeEndOfFile();
- return true;
- }
-
- bool shouldSkipNullCharacters() const { return true; }
-
-private:
- WebVTTTokenizer();
-
- // m_token is owned by the caller. If nextToken is not on the stack,
- // this member might be pointing to unallocated memory.
- WebVTTToken* m_token;
- WebVTTTokenizerState::State m_state;
-
- Vector<LChar, 32> m_buffer;
-
- // ://www.whatwg.org/specs/web-apps/current-work/#preprocessing-the-input-stream
- InputStreamPreprocessor<WebVTTTokenizer> m_inputStreamPreprocessor;
-};
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/html/track/vtt/BufferedLineReader.cpp b/chromium/third_party/WebKit/Source/core/html/track/vtt/BufferedLineReader.cpp
new file mode 100644
index 00000000000..3a4aab74416
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/html/track/vtt/BufferedLineReader.cpp
@@ -0,0 +1,104 @@
+/*
+ * Copyright (C) 2013, Opera Software ASA. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "BufferedLineReader.h"
+
+#include "wtf/unicode/CharacterNames.h"
+
+namespace WebCore {
+
+bool BufferedLineReader::getLine(String& line)
+{
+ if (m_maybeSkipLF) {
+ // We ran out of data after a CR (U+000D), which means that we may be
+ // in the middle of a CRLF pair. If the next character is a LF (U+000A)
+ // then skip it, and then (unconditionally) return the buffered line.
+ if (!m_buffer.isEmpty()) {
+ scanCharacter(newlineCharacter);
+ m_maybeSkipLF = false;
+ }
+ // If there was no (new) data available, then keep m_maybeSkipLF set,
+ // and fall through all the way down to the EOS check at the end of
+ // the method.
+ }
+
+ bool shouldReturnLine = false;
+ bool checkForLF = false;
+ while (!m_buffer.isEmpty()) {
+ UChar c = m_buffer.currentChar();
+ m_buffer.advance();
+
+ if (c == newlineCharacter || c == carriageReturn) {
+ // We found a line ending. Return the accumulated line.
+ shouldReturnLine = true;
+ checkForLF = (c == carriageReturn);
+ break;
+ }
+
+ // NULs are transformed into U+FFFD (REPLACEMENT CHAR.) in step 1 of
+ // the WebVTT parser algorithm.
+ if (c == '\0')
+ c = replacementCharacter;
+
+ m_lineBuffer.append(c);
+ }
+
+ if (checkForLF) {
+ // May be in the middle of a CRLF pair.
+ if (!m_buffer.isEmpty()) {
+ // Scan a potential newline character.
+ scanCharacter(newlineCharacter);
+ } else {
+ // Check for the LF on the next call (unless we reached EOS, in
+ // which case we'll return the contents of the line buffer, and
+ // reset state for the next line.)
+ m_maybeSkipLF = true;
+ }
+ }
+
+ if (isAtEndOfStream()) {
+ // We've reached the end of the stream proper. Emit a line if the
+ // current line buffer is non-empty. (Note that if shouldReturnLine is
+ // set already, we want to return a line nonetheless.)
+ shouldReturnLine |= !m_lineBuffer.isEmpty();
+ }
+
+ if (shouldReturnLine) {
+ line = m_lineBuffer.toString();
+ m_lineBuffer.clear();
+ return true;
+ }
+
+ ASSERT(m_buffer.isEmpty());
+ return false;
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/html/track/vtt/BufferedLineReader.h b/chromium/third_party/WebKit/Source/core/html/track/vtt/BufferedLineReader.h
new file mode 100644
index 00000000000..489eb53bbdd
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/html/track/vtt/BufferedLineReader.h
@@ -0,0 +1,88 @@
+/*
+ * Copyright (C) 2013, Opera Software ASA. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef BufferedLineReader_h
+#define BufferedLineReader_h
+
+#include "platform/text/SegmentedString.h"
+#include "wtf/text/StringBuilder.h"
+
+namespace WebCore {
+
+// Line collection helper for the WebVTT Parser.
+//
+// Converts a stream of data (== a sequence of Strings) into a set of
+// lines. CR, LR or CRLF are considered linebreaks. Normalizes NULs (U+0000)
+// to 'REPLACEMENT CHARACTER' (U+FFFD) and does not return the linebreaks as
+// part of the result.
+class BufferedLineReader {
+ WTF_MAKE_NONCOPYABLE(BufferedLineReader);
+public:
+ BufferedLineReader()
+ : m_endOfStream(false)
+ , m_maybeSkipLF(false) { }
+
+ // Append data to the internal buffer.
+ void append(const String& data)
+ {
+ ASSERT(!m_endOfStream);
+ m_buffer.append(SegmentedString(data));
+ }
+
+ // Indicate that no more data will be appended. This will cause any
+ // potentially "unterminated" line to be returned from getLine.
+ void setEndOfStream() { m_endOfStream = true; }
+
+ // Attempt to read a line from the internal buffer (fed via append).
+ // If successful, true is returned and |line| is set to the line that was
+ // read. If no line could be read false is returned.
+ bool getLine(String& line);
+
+ // Returns true if EOS has been reached proper.
+ bool isAtEndOfStream() const { return m_endOfStream && m_buffer.isEmpty(); }
+
+private:
+ // Consume the next character the buffer if it is the character |c|.
+ void scanCharacter(UChar c)
+ {
+ ASSERT(!m_buffer.isEmpty());
+ if (m_buffer.currentChar() == c)
+ m_buffer.advance();
+ }
+
+ SegmentedString m_buffer;
+ StringBuilder m_lineBuffer;
+ bool m_endOfStream;
+ bool m_maybeSkipLF;
+};
+
+} // namespace WebCore
+
+#endif
diff --git a/chromium/third_party/WebKit/Source/core/html/track/vtt/BufferedLineReaderTest.cpp b/chromium/third_party/WebKit/Source/core/html/track/vtt/BufferedLineReaderTest.cpp
new file mode 100644
index 00000000000..7bfcd49abae
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/html/track/vtt/BufferedLineReaderTest.cpp
@@ -0,0 +1,292 @@
+/*
+ * Copyright (C) 2013, Opera Software ASA. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/html/track/vtt/BufferedLineReader.h"
+
+#include "wtf/text/CString.h"
+#include "wtf/text/WTFString.h"
+#include "wtf/unicode/CharacterNames.h"
+
+#include <gtest/gtest.h>
+
+using WebCore::BufferedLineReader;
+
+namespace {
+
+TEST(BufferedLineReader, Constructor)
+{
+ BufferedLineReader reader;
+ ASSERT_FALSE(reader.isAtEndOfStream());
+ String line;
+ ASSERT_FALSE(reader.getLine(line));
+}
+
+TEST(BufferedLineReader, EOSNoInput)
+{
+ BufferedLineReader reader;
+ String line;
+ ASSERT_FALSE(reader.getLine(line));
+ reader.setEndOfStream();
+ // No input observed, so still no line.
+ ASSERT_FALSE(reader.getLine(line));
+}
+
+TEST(BufferedLineReader, EOSInput)
+{
+ BufferedLineReader reader;
+ reader.append("A");
+ reader.setEndOfStream();
+ String line;
+ ASSERT_TRUE(reader.getLine(line));
+ ASSERT_EQ(line, "A");
+}
+
+TEST(BufferedLineReader, EOSMultipleReads_1)
+{
+ BufferedLineReader reader;
+ reader.append("A");
+ reader.setEndOfStream();
+ String line;
+ ASSERT_TRUE(reader.getLine(line));
+ ASSERT_EQ(line, "A");
+ // No more lines returned.
+ ASSERT_FALSE(reader.getLine(line));
+ ASSERT_FALSE(reader.getLine(line));
+}
+
+TEST(BufferedLineReader, EOSMultipleReads_2)
+{
+ BufferedLineReader reader;
+ reader.append("A\n");
+ reader.setEndOfStream();
+ String line;
+ ASSERT_TRUE(reader.getLine(line));
+ ASSERT_EQ(line, "A");
+ // No more lines returned.
+ ASSERT_FALSE(reader.getLine(line));
+ ASSERT_FALSE(reader.getLine(line));
+}
+
+TEST(BufferedLineReader, LineEndingCR)
+{
+ BufferedLineReader reader;
+ reader.append("X\rY");
+ reader.setEndOfStream();
+ String line;
+ ASSERT_TRUE(reader.getLine(line));
+ ASSERT_EQ(line, "X");
+ ASSERT_TRUE(reader.getLine(line));
+ ASSERT_EQ(line, "Y");
+}
+
+TEST(BufferedLineReader, LineEndingCR_EOS)
+{
+ BufferedLineReader reader;
+ reader.append("X\r");
+ reader.setEndOfStream();
+ String line;
+ ASSERT_TRUE(reader.getLine(line));
+ ASSERT_EQ(line, "X");
+ ASSERT_FALSE(reader.getLine(line));
+}
+
+TEST(BufferedLineReader, LineEndingLF)
+{
+ BufferedLineReader reader;
+ reader.append("X\nY");
+ reader.setEndOfStream();
+ String line;
+ ASSERT_TRUE(reader.getLine(line));
+ ASSERT_EQ(line, "X");
+ ASSERT_TRUE(reader.getLine(line));
+ ASSERT_EQ(line, "Y");
+}
+
+TEST(BufferedLineReader, LineEndingLF_EOS)
+{
+ BufferedLineReader reader;
+ reader.append("X\n");
+ reader.setEndOfStream();
+ String line;
+ ASSERT_TRUE(reader.getLine(line));
+ ASSERT_EQ(line, "X");
+ ASSERT_FALSE(reader.getLine(line));
+}
+
+TEST(BufferedLineReader, LineEndingCRLF)
+{
+ BufferedLineReader reader;
+ reader.append("X\r\nY");
+ reader.setEndOfStream();
+ String line;
+ ASSERT_TRUE(reader.getLine(line));
+ ASSERT_EQ(line, "X");
+ ASSERT_TRUE(reader.getLine(line));
+ ASSERT_EQ(line, "Y");
+}
+
+TEST(BufferedLineReader, LineEndingCRLF_EOS)
+{
+ BufferedLineReader reader;
+ reader.append("X\r\n");
+ reader.setEndOfStream();
+ String line;
+ ASSERT_TRUE(reader.getLine(line));
+ ASSERT_EQ(line, "X");
+ ASSERT_FALSE(reader.getLine(line));
+}
+
+enum LineBreakType {
+ Cr,
+ Lf,
+ CrLf
+};
+
+String LineBreakString(LineBreakType type)
+{
+ static const char breakStrings[] = "\r\n";
+ return String(type == Lf ? breakStrings + 1 : breakStrings, type == CrLf ? 2 : 1);
+}
+
+String MakeTestData(const char** lines, const LineBreakType* breaks, int count)
+{
+ StringBuilder builder;
+ for (int i = 0; i < count; ++i) {
+ builder.append(lines[i]);
+ builder.append(LineBreakString(breaks[i]));
+ }
+ return builder.toString();
+}
+
+const size_t blockSizes[] = { 64, 32, 16, 8, 4, 2, 1, 3, 5, 7, 9, 11, 13, 17, 19, 23 };
+
+TEST(BufferedLineReader, BufferSizes)
+{
+ const char* lines[] = {
+ "aaaaaaaaaaaaaaaa",
+ "bbbbbbbbbb",
+ "ccccccccccccc",
+ "",
+ "dddddd",
+ "",
+ "eeeeeeeeee"
+ };
+ const LineBreakType breaks[] = { Lf, Lf, Lf, Lf, Lf, Lf, Lf };
+ const size_t numTestLines = WTF_ARRAY_LENGTH(lines);
+ COMPILE_ASSERT(numTestLines == WTF_ARRAY_LENGTH(breaks), DifferentLengths_lines_and_breaks);
+ String data = MakeTestData(lines, breaks, numTestLines);
+
+ for (size_t k = 0; k < WTF_ARRAY_LENGTH(blockSizes); ++k) {
+ size_t lineCount = 0;
+ BufferedLineReader reader;
+ size_t blockSize = blockSizes[k];
+ for (size_t i = 0; i < data.length(); i += blockSize) {
+ reader.append(data.substring(i, blockSize));
+
+ String line;
+ while (reader.getLine(line)) {
+ ASSERT_LT(lineCount, numTestLines);
+ ASSERT_EQ(line, lines[lineCount++]);
+ }
+ }
+ ASSERT_EQ(lineCount, numTestLines);
+ }
+}
+
+TEST(BufferedLineReader, BufferSizesMixedEndings)
+{
+ const char* lines[] = {
+ "aaaaaaaaaaaaaaaa",
+ "bbbbbbbbbb",
+ "ccccccccccccc",
+ "",
+ "dddddd",
+ "eeeeeeeeee",
+ "fffffffffffffffffff"
+ };
+ const LineBreakType breaks[] = { Cr, Lf, CrLf, Cr, Lf, CrLf, Lf };
+ const size_t numTestLines = WTF_ARRAY_LENGTH(lines);
+ COMPILE_ASSERT(numTestLines == WTF_ARRAY_LENGTH(breaks), DifferentLengths_lines_and_breaks);
+ String data = MakeTestData(lines, breaks, numTestLines);
+
+ for (size_t k = 0; k < WTF_ARRAY_LENGTH(blockSizes); ++k) {
+ size_t lineCount = 0;
+ BufferedLineReader reader;
+ size_t blockSize = blockSizes[k];
+ for (size_t i = 0; i < data.length(); i += blockSize) {
+ reader.append(data.substring(i, blockSize));
+
+ String line;
+ while (reader.getLine(line)) {
+ ASSERT_LT(lineCount, numTestLines);
+ ASSERT_EQ(line, lines[lineCount++]);
+ }
+ }
+ ASSERT_EQ(lineCount, numTestLines);
+ }
+}
+
+TEST(BufferedLineReader, BufferBoundaryInCRLF_1)
+{
+ BufferedLineReader reader;
+ reader.append("X\r");
+ String line;
+ ASSERT_TRUE(reader.getLine(line));
+ ASSERT_EQ(line, "X");
+ reader.append("\n");
+ ASSERT_FALSE(reader.getLine(line));
+}
+
+TEST(BufferedLineReader, BufferBoundaryInCRLF_2)
+{
+ BufferedLineReader reader;
+ reader.append("X\r");
+ String line;
+ ASSERT_TRUE(reader.getLine(line));
+ ASSERT_EQ(line, "X");
+ ASSERT_FALSE(reader.getLine(line));
+ reader.append("\n");
+ ASSERT_FALSE(reader.getLine(line));
+ reader.append("Y\n");
+ ASSERT_TRUE(reader.getLine(line));
+ ASSERT_EQ(line, "Y");
+}
+
+TEST(BufferedLineReader, NormalizedNUL)
+{
+ BufferedLineReader reader;
+ reader.append(String("X\0Y\n", 4));
+ String line;
+ ASSERT_TRUE(reader.getLine(line));
+ ASSERT_EQ(line[1], WTF::Unicode::replacementCharacter);
+}
+
+} // namespace
diff --git a/chromium/third_party/WebKit/Source/core/html/track/vtt/VTTCue.cpp b/chromium/third_party/WebKit/Source/core/html/track/vtt/VTTCue.cpp
new file mode 100644
index 00000000000..ab185dc3d67
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/html/track/vtt/VTTCue.cpp
@@ -0,0 +1,1110 @@
+/*
+ * Copyright (c) 2013, Opera Software ASA. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Opera Software ASA nor the names of its
+ * contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/html/track/vtt/VTTCue.h"
+
+#include "CSSPropertyNames.h"
+#include "CSSValueKeywords.h"
+#include "RuntimeEnabledFeatures.h"
+#include "bindings/v8/ExceptionMessages.h"
+#include "bindings/v8/ExceptionStatePlaceholder.h"
+#include "core/dom/DocumentFragment.h"
+#include "core/dom/NodeTraversal.h"
+#include "core/events/Event.h"
+#include "core/html/HTMLDivElement.h"
+#include "core/html/track/TextTrack.h"
+#include "core/html/track/TextTrackCueList.h"
+#include "core/html/track/vtt/VTTElement.h"
+#include "core/html/track/vtt/VTTParser.h"
+#include "core/html/track/vtt/VTTRegionList.h"
+#include "core/rendering/RenderVTTCue.h"
+#include "platform/text/BidiResolver.h"
+#include "platform/text/TextRunIterator.h"
+#include "wtf/MathExtras.h"
+#include "wtf/text/StringBuilder.h"
+
+namespace WebCore {
+
+static const int undefinedPosition = -1;
+
+static const CSSValueID displayWritingModeMap[] = {
+ CSSValueHorizontalTb, CSSValueVerticalRl, CSSValueVerticalLr
+};
+COMPILE_ASSERT(WTF_ARRAY_LENGTH(displayWritingModeMap) == VTTCue::NumberOfWritingDirections,
+ displayWritingModeMap_has_wrong_size);
+
+static const CSSValueID displayAlignmentMap[] = {
+ CSSValueStart, CSSValueCenter, CSSValueEnd, CSSValueLeft, CSSValueRight
+};
+COMPILE_ASSERT(WTF_ARRAY_LENGTH(displayAlignmentMap) == VTTCue::NumberOfAlignments,
+ displayAlignmentMap_has_wrong_size);
+
+static const String& startKeyword()
+{
+ DEFINE_STATIC_LOCAL(const String, start, ("start"));
+ return start;
+}
+
+static const String& middleKeyword()
+{
+ DEFINE_STATIC_LOCAL(const String, middle, ("middle"));
+ return middle;
+}
+
+static const String& endKeyword()
+{
+ DEFINE_STATIC_LOCAL(const String, end, ("end"));
+ return end;
+}
+
+static const String& leftKeyword()
+{
+ DEFINE_STATIC_LOCAL(const String, left, ("left"));
+ return left;
+}
+
+static const String& rightKeyword()
+{
+ DEFINE_STATIC_LOCAL(const String, right, ("right"));
+ return right;
+}
+
+static const String& horizontalKeyword()
+{
+ return emptyString();
+}
+
+static const String& verticalGrowingLeftKeyword()
+{
+ DEFINE_STATIC_LOCAL(const String, verticalrl, ("rl"));
+ return verticalrl;
+}
+
+static const String& verticalGrowingRightKeyword()
+{
+ DEFINE_STATIC_LOCAL(const String, verticallr, ("lr"));
+ return verticallr;
+}
+
+static bool isInvalidPercentage(double value, ExceptionState& exceptionState)
+{
+ if (TextTrackCue::isInfiniteOrNonNumber(value, exceptionState))
+ return true;
+ if (value < 0 || value > 100) {
+ exceptionState.throwDOMException(IndexSizeError, "The value provided (" + String::number(value) + ") is not between 0 and 100.");
+ return true;
+ }
+ return false;
+}
+
+VTTCueBox::VTTCueBox(Document& document, VTTCue* cue)
+ : HTMLDivElement(document)
+ , m_cue(cue)
+{
+ setPseudo(AtomicString("-webkit-media-text-track-display", AtomicString::ConstructFromLiteral));
+}
+
+void VTTCueBox::applyCSSProperties(const IntSize&)
+{
+ // FIXME: Apply all the initial CSS positioning properties. http://wkb.ug/79916
+ if (!m_cue->regionId().isEmpty()) {
+ setInlineStyleProperty(CSSPropertyPosition, CSSValueRelative);
+ return;
+ }
+
+ // 3.5.1 On the (root) List of WebVTT Node Objects:
+
+ // the 'position' property must be set to 'absolute'
+ setInlineStyleProperty(CSSPropertyPosition, CSSValueAbsolute);
+
+ // the 'unicode-bidi' property must be set to 'plaintext'
+ setInlineStyleProperty(CSSPropertyUnicodeBidi, CSSValueWebkitPlaintext);
+
+ // the 'direction' property must be set to direction
+ setInlineStyleProperty(CSSPropertyDirection, m_cue->getCSSWritingDirection());
+
+ // the 'writing-mode' property must be set to writing-mode
+ setInlineStyleProperty(CSSPropertyWebkitWritingMode, m_cue->getCSSWritingMode());
+
+ std::pair<float, float> position = m_cue->getCSSPosition();
+
+ // the 'top' property must be set to top,
+ setInlineStyleProperty(CSSPropertyTop, position.second, CSSPrimitiveValue::CSS_PERCENTAGE);
+
+ // the 'left' property must be set to left
+ setInlineStyleProperty(CSSPropertyLeft, position.first, CSSPrimitiveValue::CSS_PERCENTAGE);
+
+ // the 'width' property must be set to width, and the 'height' property must be set to height
+ if (m_cue->vertical() == horizontalKeyword()) {
+ setInlineStyleProperty(CSSPropertyWidth, static_cast<double>(m_cue->getCSSSize()), CSSPrimitiveValue::CSS_PERCENTAGE);
+ setInlineStyleProperty(CSSPropertyHeight, CSSValueAuto);
+ } else {
+ setInlineStyleProperty(CSSPropertyWidth, CSSValueAuto);
+ setInlineStyleProperty(CSSPropertyHeight, static_cast<double>(m_cue->getCSSSize()), CSSPrimitiveValue::CSS_PERCENTAGE);
+ }
+
+ // The 'text-align' property on the (root) List of WebVTT Node Objects must
+ // be set to the value in the second cell of the row of the table below
+ // whose first cell is the value of the corresponding cue's text track cue
+ // alignment:
+ setInlineStyleProperty(CSSPropertyTextAlign, m_cue->getCSSAlignment());
+
+ if (!m_cue->snapToLines()) {
+ // 10.13.1 Set up x and y:
+ // Note: x and y are set through the CSS left and top above.
+
+ // 10.13.2 Position the boxes in boxes such that the point x% along the
+ // width of the bounding box of the boxes in boxes is x% of the way
+ // across the width of the video's rendering area, and the point y%
+ // along the height of the bounding box of the boxes in boxes is y%
+ // of the way across the height of the video's rendering area, while
+ // maintaining the relative positions of the boxes in boxes to each
+ // other.
+ setInlineStyleProperty(CSSPropertyWebkitTransform,
+ String::format("translate(-%.2f%%, -%.2f%%)", position.first, position.second));
+
+ setInlineStyleProperty(CSSPropertyWhiteSpace, CSSValuePre);
+ }
+}
+
+RenderObject* VTTCueBox::createRenderer(RenderStyle*)
+{
+ return new RenderVTTCue(this);
+}
+
+VTTCue::VTTCue(Document& document, double startTime, double endTime, const String& text)
+ : TextTrackCue(startTime, endTime)
+ , m_text(text)
+ , m_linePosition(undefinedPosition)
+ , m_computedLinePosition(undefinedPosition)
+ , m_textPosition(50)
+ , m_cueSize(100)
+ , m_writingDirection(Horizontal)
+ , m_cueAlignment(Middle)
+ , m_vttNodeTree(0)
+ , m_cueBackgroundBox(HTMLDivElement::create(document))
+ , m_displayDirection(CSSValueLtr)
+ , m_snapToLines(true)
+ , m_displayTreeShouldChange(true)
+ , m_notifyRegion(true)
+{
+ ScriptWrappable::init(this);
+}
+
+VTTCue::~VTTCue()
+{
+ displayTreeInternal()->remove(ASSERT_NO_EXCEPTION);
+}
+
+#ifndef NDEBUG
+String VTTCue::toString() const
+{
+ return String::format("%p id=%s interval=%f-->%f cue=%s)", this, id().utf8().data(), startTime(), endTime(), text().utf8().data());
+}
+#endif
+
+PassRefPtr<VTTCueBox> VTTCue::displayTreeInternal()
+{
+ if (!m_displayTree)
+ m_displayTree = VTTCueBox::create(document(), this);
+ return m_displayTree;
+}
+
+void VTTCue::cueDidChange()
+{
+ TextTrackCue::cueDidChange();
+ m_displayTreeShouldChange = true;
+}
+
+const String& VTTCue::vertical() const
+{
+ switch (m_writingDirection) {
+ case Horizontal:
+ return horizontalKeyword();
+ case VerticalGrowingLeft:
+ return verticalGrowingLeftKeyword();
+ case VerticalGrowingRight:
+ return verticalGrowingRightKeyword();
+ default:
+ ASSERT_NOT_REACHED();
+ return emptyString();
+ }
+}
+
+void VTTCue::setVertical(const String& value, ExceptionState& exceptionState)
+{
+ // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#dom-texttrackcue-vertical
+ // On setting, the text track cue writing direction must be set to the value given
+ // in the first cell of the row in the table above whose second cell is a
+ // case-sensitive match for the new value, if any. If none of the values match, then
+ // the user agent must instead throw a SyntaxError exception.
+
+ WritingDirection direction = m_writingDirection;
+ if (value == horizontalKeyword())
+ direction = Horizontal;
+ else if (value == verticalGrowingLeftKeyword())
+ direction = VerticalGrowingLeft;
+ else if (value == verticalGrowingRightKeyword())
+ direction = VerticalGrowingRight;
+ else
+ exceptionState.throwDOMException(SyntaxError, ExceptionMessages::failedToSet("vertical", "TextTrackCue", "The value provided ('" + value + "') is invalid. Only 'rl', 'lr', and the empty string are accepted."));
+
+ if (direction == m_writingDirection)
+ return;
+
+ cueWillChange();
+ m_writingDirection = direction;
+ cueDidChange();
+}
+
+void VTTCue::setSnapToLines(bool value)
+{
+ if (m_snapToLines == value)
+ return;
+
+ cueWillChange();
+ m_snapToLines = value;
+ cueDidChange();
+}
+
+void VTTCue::setLine(int position, ExceptionState& exceptionState)
+{
+ // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#dom-texttrackcue-line
+ // On setting, if the text track cue snap-to-lines flag is not set, and the new
+ // value is negative or greater than 100, then throw an IndexSizeError exception.
+ if (!m_snapToLines && (position < 0 || position > 100)) {
+ exceptionState.throwDOMException(IndexSizeError, ExceptionMessages::failedToSet("line", "TextTrackCue", "The snap-to-lines flag is not set, and the value provided (" + String::number(position) + ") is not between 0 and 100."));
+ return;
+ }
+
+ // Otherwise, set the text track cue line position to the new value.
+ if (m_linePosition == position)
+ return;
+
+ cueWillChange();
+ m_linePosition = position;
+ m_computedLinePosition = calculateComputedLinePosition();
+ cueDidChange();
+}
+
+void VTTCue::setPosition(int position, ExceptionState& exceptionState)
+{
+ // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#dom-texttrackcue-position
+ // On setting, if the new value is negative or greater than 100, then throw an IndexSizeError exception.
+ // Otherwise, set the text track cue text position to the new value.
+ if (isInvalidPercentage(position, exceptionState))
+ return;
+
+ // Otherwise, set the text track cue line position to the new value.
+ if (m_textPosition == position)
+ return;
+
+ cueWillChange();
+ m_textPosition = position;
+ cueDidChange();
+}
+
+void VTTCue::setSize(int size, ExceptionState& exceptionState)
+{
+ // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#dom-texttrackcue-size
+ // On setting, if the new value is negative or greater than 100, then throw an IndexSizeError
+ // exception. Otherwise, set the text track cue size to the new value.
+ if (isInvalidPercentage(size, exceptionState))
+ return;
+
+ // Otherwise, set the text track cue line position to the new value.
+ if (m_cueSize == size)
+ return;
+
+ cueWillChange();
+ m_cueSize = size;
+ cueDidChange();
+}
+
+const String& VTTCue::align() const
+{
+ switch (m_cueAlignment) {
+ case Start:
+ return startKeyword();
+ case Middle:
+ return middleKeyword();
+ case End:
+ return endKeyword();
+ case Left:
+ return leftKeyword();
+ case Right:
+ return rightKeyword();
+ default:
+ ASSERT_NOT_REACHED();
+ return emptyString();
+ }
+}
+
+void VTTCue::setAlign(const String& value, ExceptionState& exceptionState)
+{
+ // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#dom-texttrackcue-align
+ // On setting, the text track cue alignment must be set to the value given in the
+ // first cell of the row in the table above whose second cell is a case-sensitive
+ // match for the new value, if any. If none of the values match, then the user
+ // agent must instead throw a SyntaxError exception.
+
+ CueAlignment alignment = m_cueAlignment;
+ if (value == startKeyword())
+ alignment = Start;
+ else if (value == middleKeyword())
+ alignment = Middle;
+ else if (value == endKeyword())
+ alignment = End;
+ else if (value == leftKeyword())
+ alignment = Left;
+ else if (value == rightKeyword())
+ alignment = Right;
+ else
+ exceptionState.throwDOMException(SyntaxError, ExceptionMessages::failedToSet("align", "TextTrackCue", "The value provided ('" + value + "') is invalid. Only 'start', 'middle', 'end', 'left', and 'right' are accepted."));
+
+ if (alignment == m_cueAlignment)
+ return;
+
+ cueWillChange();
+ m_cueAlignment = alignment;
+ cueDidChange();
+}
+
+void VTTCue::setText(const String& text)
+{
+ if (m_text == text)
+ return;
+
+ cueWillChange();
+ // Clear the document fragment but don't bother to create it again just yet as we can do that
+ // when it is requested.
+ m_vttNodeTree = 0;
+ m_text = text;
+ cueDidChange();
+}
+
+void VTTCue::createVTTNodeTree()
+{
+ if (!m_vttNodeTree)
+ m_vttNodeTree = VTTParser::createDocumentFragmentFromCueText(document(), m_text);
+}
+
+void VTTCue::copyVTTNodeToDOMTree(ContainerNode* vttNode, ContainerNode* parent)
+{
+ for (Node* node = vttNode->firstChild(); node; node = node->nextSibling()) {
+ RefPtr<Node> clonedNode;
+ if (node->isVTTElement())
+ clonedNode = toVTTElement(node)->createEquivalentHTMLElement(document());
+ else
+ clonedNode = node->cloneNode(false);
+ parent->appendChild(clonedNode);
+ if (node->isContainerNode())
+ copyVTTNodeToDOMTree(toContainerNode(node), toContainerNode(clonedNode));
+ }
+}
+
+PassRefPtr<DocumentFragment> VTTCue::getCueAsHTML()
+{
+ createVTTNodeTree();
+ RefPtr<DocumentFragment> clonedFragment = DocumentFragment::create(document());
+ copyVTTNodeToDOMTree(m_vttNodeTree.get(), clonedFragment.get());
+ return clonedFragment.release();
+}
+
+PassRefPtr<DocumentFragment> VTTCue::createCueRenderingTree()
+{
+ RefPtr<DocumentFragment> clonedFragment;
+ createVTTNodeTree();
+ clonedFragment = DocumentFragment::create(document());
+ m_vttNodeTree->cloneChildNodes(clonedFragment.get());
+ return clonedFragment.release();
+}
+
+void VTTCue::setRegionId(const String& regionId)
+{
+ if (m_regionId == regionId)
+ return;
+
+ cueWillChange();
+ m_regionId = regionId;
+ cueDidChange();
+}
+
+void VTTCue::notifyRegionWhenRemovingDisplayTree(bool notifyRegion)
+{
+ m_notifyRegion = notifyRegion;
+}
+
+int VTTCue::calculateComputedLinePosition()
+{
+ // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#text-track-cue-computed-line-position
+
+ // If the text track cue line position is numeric, then that is the text
+ // track cue computed line position.
+ if (m_linePosition != undefinedPosition)
+ return m_linePosition;
+
+ // If the text track cue snap-to-lines flag of the text track cue is not
+ // set, the text track cue computed line position is the value 100;
+ if (!m_snapToLines)
+ return 100;
+
+ // Otherwise, it is the value returned by the following algorithm:
+
+ // If cue is not associated with a text track, return -1 and abort these
+ // steps.
+ if (!track())
+ return -1;
+
+ // Let n be the number of text tracks whose text track mode is showing or
+ // showing by default and that are in the media element's list of text
+ // tracks before track.
+ int n = track()->trackIndexRelativeToRenderedTracks();
+
+ // Increment n by one.
+ n++;
+
+ // Negate n.
+ n = -n;
+
+ return n;
+}
+
+class VTTTextRunIterator : public TextRunIterator {
+public:
+ VTTTextRunIterator() { }
+ VTTTextRunIterator(const TextRun* textRun, unsigned offset) : TextRunIterator(textRun, offset) { }
+
+ bool atParagraphSeparator() const
+ {
+ // Within a cue, paragraph boundaries are only denoted by Type B characters,
+ // such as U+000A LINE FEED (LF), U+0085 NEXT LINE (NEL), and U+2029 PARAGRAPH SEPARATOR.
+ return WTF::Unicode::category(current()) & WTF::Unicode::Separator_Paragraph;
+ }
+};
+
+// Almost the same as determineDirectionality in core/html/HTMLElement.cpp, but
+// that one uses a "plain" TextRunIterator (which only checks for '\n').
+static TextDirection determineDirectionality(const String& value, bool& hasStrongDirectionality)
+{
+ TextRun run(value);
+ BidiResolver<VTTTextRunIterator, BidiCharacterRun> bidiResolver;
+ bidiResolver.setStatus(BidiStatus(LTR, false));
+ bidiResolver.setPositionIgnoringNestedIsolates(VTTTextRunIterator(&run, 0));
+ return bidiResolver.determineParagraphDirectionality(&hasStrongDirectionality);
+}
+
+static CSSValueID determineTextDirection(DocumentFragment* vttRoot)
+{
+ DEFINE_STATIC_LOCAL(const String, rtTag, ("rt"));
+ ASSERT(vttRoot);
+
+ // Apply the Unicode Bidirectional Algorithm's Paragraph Level steps to the
+ // concatenation of the values of each WebVTT Text Object in nodes, in a
+ // pre-order, depth-first traversal, excluding WebVTT Ruby Text Objects and
+ // their descendants.
+ TextDirection textDirection = LTR;
+ for (Node* node = vttRoot->firstChild(); node; node = NodeTraversal::next(*node, vttRoot)) {
+ if (!node->isTextNode() || node->localName() == rtTag)
+ continue;
+
+ bool hasStrongDirectionality;
+ textDirection = determineDirectionality(node->nodeValue(), hasStrongDirectionality);
+ if (hasStrongDirectionality)
+ break;
+ }
+ return isLeftToRightDirection(textDirection) ? CSSValueLtr : CSSValueRtl;
+}
+
+void VTTCue::calculateDisplayParameters()
+{
+ createVTTNodeTree();
+
+ // Steps 10.2, 10.3
+ m_displayDirection = determineTextDirection(m_vttNodeTree.get());
+
+ // 10.4 If the text track cue writing direction is horizontal, then let
+ // block-flow be 'tb'. Otherwise, if the text track cue writing direction is
+ // vertical growing left, then let block-flow be 'lr'. Otherwise, the text
+ // track cue writing direction is vertical growing right; let block-flow be
+ // 'rl'.
+
+ // The above step is done through the writing direction static map.
+
+ // 10.5 Determine the value of maximum size for cue as per the appropriate
+ // rules from the following list:
+ int maximumSize = m_textPosition;
+ if ((m_writingDirection == Horizontal && m_cueAlignment == Start && m_displayDirection == CSSValueLtr)
+ || (m_writingDirection == Horizontal && m_cueAlignment == End && m_displayDirection == CSSValueRtl)
+ || (m_writingDirection == Horizontal && m_cueAlignment == Left)
+ || (m_writingDirection == VerticalGrowingLeft && (m_cueAlignment == Start || m_cueAlignment == Left))
+ || (m_writingDirection == VerticalGrowingRight && (m_cueAlignment == Start || m_cueAlignment == Left))) {
+ maximumSize = 100 - m_textPosition;
+ } else if ((m_writingDirection == Horizontal && m_cueAlignment == End && m_displayDirection == CSSValueLtr)
+ || (m_writingDirection == Horizontal && m_cueAlignment == Start && m_displayDirection == CSSValueRtl)
+ || (m_writingDirection == Horizontal && m_cueAlignment == Right)
+ || (m_writingDirection == VerticalGrowingLeft && (m_cueAlignment == End || m_cueAlignment == Right))
+ || (m_writingDirection == VerticalGrowingRight && (m_cueAlignment == End || m_cueAlignment == Right))) {
+ maximumSize = m_textPosition;
+ } else if (m_cueAlignment == Middle) {
+ maximumSize = m_textPosition <= 50 ? m_textPosition : (100 - m_textPosition);
+ maximumSize = maximumSize * 2;
+ } else {
+ ASSERT_NOT_REACHED();
+ }
+
+ // 10.6 If the text track cue size is less than maximum size, then let size
+ // be text track cue size. Otherwise, let size be maximum size.
+ m_displaySize = std::min(m_cueSize, maximumSize);
+
+ // FIXME: Understand why step 10.7 is missing (just a copy/paste error?)
+ // Could be done within a spec implementation check - http://crbug.com/301580
+
+ // 10.8 Determine the value of x-position or y-position for cue as per the
+ // appropriate rules from the following list:
+ if (m_writingDirection == Horizontal) {
+ switch (m_cueAlignment) {
+ case Start:
+ if (m_displayDirection == CSSValueLtr)
+ m_displayPosition.first = m_textPosition;
+ else
+ m_displayPosition.first = 100 - m_textPosition - m_displaySize;
+ break;
+ case End:
+ if (m_displayDirection == CSSValueRtl)
+ m_displayPosition.first = 100 - m_textPosition;
+ else
+ m_displayPosition.first = m_textPosition - m_displaySize;
+ break;
+ case Left:
+ if (m_displayDirection == CSSValueLtr)
+ m_displayPosition.first = m_textPosition;
+ else
+ m_displayPosition.first = 100 - m_textPosition;
+ break;
+ case Right:
+ if (m_displayDirection == CSSValueLtr)
+ m_displayPosition.first = m_textPosition - m_displaySize;
+ else
+ m_displayPosition.first = 100 - m_textPosition - m_displaySize;
+ break;
+ case Middle:
+ if (m_displayDirection == CSSValueLtr)
+ m_displayPosition.first = m_textPosition - m_displaySize / 2;
+ else
+ m_displayPosition.first = 100 - m_textPosition - m_displaySize / 2;
+ break;
+ case NumberOfAlignments:
+ ASSERT_NOT_REACHED();
+ }
+ } else {
+ // Cases for m_writingDirection being VerticalGrowing{Left|Right}
+ switch (m_cueAlignment) {
+ case Start:
+ case Left:
+ m_displayPosition.second = m_textPosition;
+ break;
+ case End:
+ case Right:
+ m_displayPosition.second = m_textPosition - m_displaySize;
+ break;
+ case Middle:
+ m_displayPosition.second = m_textPosition - m_displaySize / 2;
+ break;
+ case NumberOfAlignments:
+ ASSERT_NOT_REACHED();
+ }
+ }
+
+ // A text track cue has a text track cue computed line position whose value
+ // is defined in terms of the other aspects of the cue.
+ m_computedLinePosition = calculateComputedLinePosition();
+
+ // 10.9 Determine the value of whichever of x-position or y-position is not
+ // yet calculated for cue as per the appropriate rules from the following
+ // list:
+ if (m_snapToLines && m_displayPosition.second == undefinedPosition && m_writingDirection == Horizontal)
+ m_displayPosition.second = 0;
+
+ if (!m_snapToLines && m_displayPosition.second == undefinedPosition && m_writingDirection == Horizontal)
+ m_displayPosition.second = m_computedLinePosition;
+
+ if (m_snapToLines && m_displayPosition.first == undefinedPosition
+ && (m_writingDirection == VerticalGrowingLeft || m_writingDirection == VerticalGrowingRight))
+ m_displayPosition.first = 0;
+
+ if (!m_snapToLines && (m_writingDirection == VerticalGrowingLeft || m_writingDirection == VerticalGrowingRight))
+ m_displayPosition.first = m_computedLinePosition;
+}
+
+void VTTCue::markFutureAndPastNodes(ContainerNode* root, double previousTimestamp, double movieTime)
+{
+ DEFINE_STATIC_LOCAL(const String, timestampTag, ("timestamp"));
+
+ bool isPastNode = true;
+ double currentTimestamp = previousTimestamp;
+ if (currentTimestamp > movieTime)
+ isPastNode = false;
+
+ for (Node* child = root->firstChild(); child; child = NodeTraversal::next(*child, root)) {
+ if (child->nodeName() == timestampTag) {
+ unsigned position = 0;
+ String timestamp = child->nodeValue();
+ double currentTimestamp;
+ bool check = VTTParser::collectTimeStamp(timestamp, &position, currentTimestamp);
+ ASSERT_UNUSED(check, check);
+
+ if (currentTimestamp > movieTime)
+ isPastNode = false;
+ }
+
+ if (child->isVTTElement()) {
+ toVTTElement(child)->setIsPastNode(isPastNode);
+ // Make an elemenet id match a cue id for style matching purposes.
+ if (!id().isEmpty())
+ toElement(child)->setIdAttribute(id());
+ }
+ }
+}
+
+void VTTCue::updateDisplayTree(double movieTime)
+{
+ // The display tree may contain WebVTT timestamp objects representing
+ // timestamps (processing instructions), along with displayable nodes.
+
+ if (!track()->isRendered())
+ return;
+
+ // Clear the contents of the set.
+ m_cueBackgroundBox->removeChildren();
+
+ // Update the two sets containing past and future WebVTT objects.
+ RefPtr<DocumentFragment> referenceTree = createCueRenderingTree();
+ markFutureAndPastNodes(referenceTree.get(), startTime(), movieTime);
+ m_cueBackgroundBox->appendChild(referenceTree, ASSERT_NO_EXCEPTION);
+}
+
+PassRefPtr<VTTCueBox> VTTCue::getDisplayTree(const IntSize& videoSize)
+{
+ RefPtr<VTTCueBox> displayTree = displayTreeInternal();
+ if (!m_displayTreeShouldChange || !track()->isRendered())
+ return displayTree;
+
+ // 10.1 - 10.10
+ calculateDisplayParameters();
+
+ // 10.11. Apply the terms of the CSS specifications to nodes within the
+ // following constraints, thus obtaining a set of CSS boxes positioned
+ // relative to an initial containing block:
+ displayTree->removeChildren();
+
+ // The document tree is the tree of WebVTT Node Objects rooted at nodes.
+
+ // The children of the nodes must be wrapped in an anonymous box whose
+ // 'display' property has the value 'inline'. This is the WebVTT cue
+ // background box.
+
+ // Note: This is contained by default in m_cueBackgroundBox.
+ m_cueBackgroundBox->setPseudo(cueShadowPseudoId());
+ displayTree->appendChild(m_cueBackgroundBox);
+
+ // FIXME(BUG 79916): Runs of children of WebVTT Ruby Objects that are not
+ // WebVTT Ruby Text Objects must be wrapped in anonymous boxes whose
+ // 'display' property has the value 'ruby-base'.
+
+ // FIXME(BUG 79916): Text runs must be wrapped according to the CSS
+ // line-wrapping rules, except that additionally, regardless of the value of
+ // the 'white-space' property, lines must be wrapped at the edge of their
+ // containing blocks, even if doing so requires splitting a word where there
+ // is no line breaking opportunity. (Thus, normally text wraps as needed,
+ // but if there is a particularly long word, it does not overflow as it
+ // normally would in CSS, it is instead forcibly wrapped at the box's edge.)
+ displayTree->applyCSSProperties(videoSize);
+
+ m_displayTreeShouldChange = false;
+
+ // 10.15. Let cue's text track cue display state have the CSS boxes in
+ // boxes.
+ return displayTree;
+}
+
+void VTTCue::removeDisplayTree()
+{
+ if (m_notifyRegion && track()->regions()) {
+ // The region needs to be informed about the cue removal.
+ VTTRegion* region = track()->regions()->getRegionById(m_regionId);
+ if (region)
+ region->willRemoveVTTCueBox(m_displayTree.get());
+ }
+
+ displayTreeInternal()->remove(ASSERT_NO_EXCEPTION);
+}
+
+void VTTCue::updateDisplay(const IntSize& videoSize, HTMLDivElement& container)
+{
+ RefPtr<VTTCueBox> displayBox = getDisplayTree(videoSize);
+ VTTRegion* region = 0;
+ if (track()->regions())
+ region = track()->regions()->getRegionById(regionId());
+
+ if (!region) {
+ // If cue has an empty text track cue region identifier or there is no
+ // WebVTT region whose region identifier is identical to cue's text
+ // track cue region identifier, run the following substeps:
+ if (displayBox->hasChildNodes() && !container.contains(displayBox.get())) {
+ // Note: the display tree of a cue is removed when the active flag of the cue is unset.
+ container.appendChild(displayBox);
+ }
+ } else {
+ // Let region be the WebVTT region whose region identifier
+ // matches the text track cue region identifier of cue.
+ RefPtr<HTMLDivElement> regionNode = region->getDisplayTree(document());
+
+ // Append the region to the viewport, if it was not already.
+ if (!container.contains(regionNode.get()))
+ container.appendChild(regionNode);
+
+ region->appendVTTCueBox(displayBox);
+ }
+}
+
+std::pair<double, double> VTTCue::getPositionCoordinates() const
+{
+ // This method is used for setting x and y when snap to lines is not set.
+ std::pair<double, double> coordinates;
+
+ if (m_writingDirection == Horizontal && m_displayDirection == CSSValueLtr) {
+ coordinates.first = m_textPosition;
+ coordinates.second = m_computedLinePosition;
+
+ return coordinates;
+ }
+
+ if (m_writingDirection == Horizontal && m_displayDirection == CSSValueRtl) {
+ coordinates.first = 100 - m_textPosition;
+ coordinates.second = m_computedLinePosition;
+
+ return coordinates;
+ }
+
+ if (m_writingDirection == VerticalGrowingLeft) {
+ coordinates.first = 100 - m_computedLinePosition;
+ coordinates.second = m_textPosition;
+
+ return coordinates;
+ }
+
+ if (m_writingDirection == VerticalGrowingRight) {
+ coordinates.first = m_computedLinePosition;
+ coordinates.second = m_textPosition;
+
+ return coordinates;
+ }
+
+ ASSERT_NOT_REACHED();
+
+ return coordinates;
+}
+
+VTTCue::CueSetting VTTCue::settingName(const String& name)
+{
+ DEFINE_STATIC_LOCAL(const String, verticalKeyword, ("vertical"));
+ DEFINE_STATIC_LOCAL(const String, lineKeyword, ("line"));
+ DEFINE_STATIC_LOCAL(const String, positionKeyword, ("position"));
+ DEFINE_STATIC_LOCAL(const String, sizeKeyword, ("size"));
+ DEFINE_STATIC_LOCAL(const String, alignKeyword, ("align"));
+ DEFINE_STATIC_LOCAL(const String, regionIdKeyword, ("region"));
+
+ if (name == verticalKeyword)
+ return Vertical;
+ if (name == lineKeyword)
+ return Line;
+ if (name == positionKeyword)
+ return Position;
+ if (name == sizeKeyword)
+ return Size;
+ if (name == alignKeyword)
+ return Align;
+ if (RuntimeEnabledFeatures::webVTTRegionsEnabled() && name == regionIdKeyword)
+ return RegionId;
+
+ return None;
+}
+
+void VTTCue::parseSettings(const String& input)
+{
+ unsigned position = 0;
+
+ while (position < input.length()) {
+
+ // The WebVTT cue settings part of a WebVTT cue consists of zero or more of the following components, in any order,
+ // separated from each other by one or more U+0020 SPACE characters or U+0009 CHARACTER TABULATION (tab) characters.
+ while (position < input.length() && VTTParser::isValidSettingDelimiter(input[position]))
+ position++;
+ if (position >= input.length())
+ break;
+
+ // When the user agent is to parse the WebVTT settings given by a string input for a text track cue cue,
+ // the user agent must run the following steps:
+ // 1. Let settings be the result of splitting input on spaces.
+ // 2. For each token setting in the list settings, run the following substeps:
+ // 1. If setting does not contain a U+003A COLON character (:), or if the first U+003A COLON character (:)
+ // in setting is either the first or last character of setting, then jump to the step labeled next setting.
+ unsigned endOfSetting = position;
+ String setting = VTTParser::collectWord(input, &endOfSetting);
+ CueSetting name;
+ size_t colonOffset = setting.find(':', 1);
+ if (colonOffset == kNotFound || !colonOffset || colonOffset == setting.length() - 1)
+ goto NextSetting;
+
+ // 2. Let name be the leading substring of setting up to and excluding the first U+003A COLON character (:) in that string.
+ name = settingName(setting.substring(0, colonOffset));
+
+ // 3. Let value be the trailing substring of setting starting from the character immediately after the first U+003A COLON character (:) in that string.
+ position += colonOffset + 1;
+ if (position >= input.length())
+ break;
+
+ // 4. Run the appropriate substeps that apply for the value of name, as follows:
+ switch (name) {
+ case Vertical:
+ {
+ // If name is a case-sensitive match for "vertical"
+ // 1. If value is a case-sensitive match for the string "rl", then let cue's text track cue writing direction
+ // be vertical growing left.
+ String writingDirection = VTTParser::collectWord(input, &position);
+ if (writingDirection == verticalGrowingLeftKeyword())
+ m_writingDirection = VerticalGrowingLeft;
+
+ // 2. Otherwise, if value is a case-sensitive match for the string "lr", then let cue's text track cue writing
+ // direction be vertical growing right.
+ else if (writingDirection == verticalGrowingRightKeyword())
+ m_writingDirection = VerticalGrowingRight;
+ }
+ break;
+ case Line:
+ {
+ // 1-2 - Collect chars that are either '-', '%', or a digit.
+ // 1. If value contains any characters other than U+002D HYPHEN-MINUS characters (-), U+0025 PERCENT SIGN
+ // characters (%), and characters in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9), then jump
+ // to the step labeled next setting.
+ StringBuilder linePositionBuilder;
+ while (position < input.length() && (input[position] == '-' || input[position] == '%' || isASCIIDigit(input[position])))
+ linePositionBuilder.append(input[position++]);
+ if (position < input.length() && !VTTParser::isValidSettingDelimiter(input[position]))
+ break;
+
+ // 2. If value does not contain at least one character in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT
+ // NINE (9), then jump to the step labeled next setting.
+ // 3. If any character in value other than the first character is a U+002D HYPHEN-MINUS character (-), then
+ // jump to the step labeled next setting.
+ // 4. If any character in value other than the last character is a U+0025 PERCENT SIGN character (%), then
+ // jump to the step labeled next setting.
+ String linePosition = linePositionBuilder.toString();
+ if (linePosition.find('-', 1) != kNotFound || linePosition.reverseFind("%", linePosition.length() - 2) != kNotFound)
+ break;
+
+ // 5. If the first character in value is a U+002D HYPHEN-MINUS character (-) and the last character in value is a
+ // U+0025 PERCENT SIGN character (%), then jump to the step labeled next setting.
+ if (linePosition[0] == '-' && linePosition[linePosition.length() - 1] == '%')
+ break;
+
+ // 6. Ignoring the trailing percent sign, if any, interpret value as a (potentially signed) integer, and
+ // let number be that number.
+ // NOTE: toInt ignores trailing non-digit characters, such as '%'.
+ bool validNumber;
+ int number = linePosition.toInt(&validNumber);
+ if (!validNumber)
+ break;
+
+ // 7. If the last character in value is a U+0025 PERCENT SIGN character (%), but number is not in the range
+ // 0 ≤ number ≤ 100, then jump to the step labeled next setting.
+ // 8. Let cue's text track cue line position be number.
+ // 9. If the last character in value is a U+0025 PERCENT SIGN character (%), then let cue's text track cue
+ // snap-to-lines flag be false. Otherwise, let it be true.
+ if (linePosition[linePosition.length() - 1] == '%') {
+ if (number < 0 || number > 100)
+ break;
+
+ // 10 - If '%' then set snap-to-lines flag to false.
+ m_snapToLines = false;
+ }
+
+ m_linePosition = number;
+ }
+ break;
+ case Position:
+ {
+ // 1. If value contains any characters other than U+0025 PERCENT SIGN characters (%) and characters in the range
+ // U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9), then jump to the step labeled next setting.
+ // 2. If value does not contain at least one character in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9),
+ // then jump to the step labeled next setting.
+ int number;
+ if (!VTTParser::collectDigitsToInt(input, &position, number))
+ break;
+ if (position >= input.length())
+ break;
+
+ // 3. If any character in value other than the last character is a U+0025 PERCENT SIGN character (%), then jump
+ // to the step labeled next setting.
+ // 4. If the last character in value is not a U+0025 PERCENT SIGN character (%), then jump to the step labeled
+ // next setting.
+ if (input[position++] != '%')
+ break;
+ if (position < input.length() && !VTTParser::isValidSettingDelimiter(input[position]))
+ break;
+
+ // 5. Ignoring the trailing percent sign, interpret value as an integer, and let number be that number.
+ // 6. If number is not in the range 0 ≤ number ≤ 100, then jump to the step labeled next setting.
+ // NOTE: toInt ignores trailing non-digit characters, such as '%'.
+ if (number < 0 || number > 100)
+ break;
+
+ // 7. Let cue's text track cue text position be number.
+ m_textPosition = number;
+ }
+ break;
+ case Size:
+ {
+ // 1. If value contains any characters other than U+0025 PERCENT SIGN characters (%) and characters in the
+ // range U+0030 DIGIT ZERO (0) to U+0039 DIGIT NINE (9), then jump to the step labeled next setting.
+ // 2. If value does not contain at least one character in the range U+0030 DIGIT ZERO (0) to U+0039 DIGIT
+ // NINE (9), then jump to the step labeled next setting.
+ int number;
+ if (!VTTParser::collectDigitsToInt(input, &position, number))
+ break;
+ if (position >= input.length())
+ break;
+
+ // 3. If any character in value other than the last character is a U+0025 PERCENT SIGN character (%),
+ // then jump to the step labeled next setting.
+ // 4. If the last character in value is not a U+0025 PERCENT SIGN character (%), then jump to the step
+ // labeled next setting.
+ if (input[position++] != '%')
+ break;
+ if (position < input.length() && !VTTParser::isValidSettingDelimiter(input[position]))
+ break;
+
+ // 5. Ignoring the trailing percent sign, interpret value as an integer, and let number be that number.
+ // 6. If number is not in the range 0 ≤ number ≤ 100, then jump to the step labeled next setting.
+ if (number < 0 || number > 100)
+ break;
+
+ // 7. Let cue's text track cue size be number.
+ m_cueSize = number;
+ }
+ break;
+ case Align:
+ {
+ String cueAlignment = VTTParser::collectWord(input, &position);
+
+ // 1. If value is a case-sensitive match for the string "start", then let cue's text track cue alignment be start alignment.
+ if (cueAlignment == startKeyword())
+ m_cueAlignment = Start;
+
+ // 2. If value is a case-sensitive match for the string "middle", then let cue's text track cue alignment be middle alignment.
+ else if (cueAlignment == middleKeyword())
+ m_cueAlignment = Middle;
+
+ // 3. If value is a case-sensitive match for the string "end", then let cue's text track cue alignment be end alignment.
+ else if (cueAlignment == endKeyword())
+ m_cueAlignment = End;
+
+ // 4. If value is a case-sensitive match for the string "left", then let cue's text track cue alignment be left alignment.
+ else if (cueAlignment == leftKeyword())
+ m_cueAlignment = Left;
+
+ // 5. If value is a case-sensitive match for the string "right", then let cue's text track cue alignment be right alignment.
+ else if (cueAlignment == rightKeyword())
+ m_cueAlignment = Right;
+ }
+ break;
+ case RegionId:
+ m_regionId = VTTParser::collectWord(input, &position);
+ break;
+ case None:
+ break;
+ }
+
+NextSetting:
+ position = endOfSetting;
+ }
+
+ // If cue's line position is not auto or cue's size is not 100 or cue's
+ // writing direction is not horizontal, but cue's region identifier is not
+ // the empty string, let cue's region identifier be the empty string.
+ if (m_regionId.isEmpty())
+ return;
+
+ if (m_linePosition != undefinedPosition || m_cueSize != 100 || m_writingDirection != Horizontal)
+ m_regionId = emptyString();
+}
+
+CSSValueID VTTCue::getCSSAlignment() const
+{
+ return displayAlignmentMap[m_cueAlignment];
+}
+
+CSSValueID VTTCue::getCSSWritingDirection() const
+{
+ return m_displayDirection;
+}
+
+CSSValueID VTTCue::getCSSWritingMode() const
+{
+ return displayWritingModeMap[m_writingDirection];
+}
+
+int VTTCue::getCSSSize() const
+{
+ return m_displaySize;
+}
+
+std::pair<double, double> VTTCue::getCSSPosition() const
+{
+ if (!m_snapToLines)
+ return getPositionCoordinates();
+
+ return m_displayPosition;
+}
+
+ExecutionContext* VTTCue::executionContext() const
+{
+ ASSERT(m_cueBackgroundBox);
+ return m_cueBackgroundBox->executionContext();
+}
+
+Document& VTTCue::document() const
+{
+ ASSERT(m_cueBackgroundBox);
+ return m_cueBackgroundBox->document();
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/html/track/vtt/VTTCue.h b/chromium/third_party/WebKit/Source/core/html/track/vtt/VTTCue.h
new file mode 100644
index 00000000000..05e6f8ecf1b
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/html/track/vtt/VTTCue.h
@@ -0,0 +1,197 @@
+/*
+ * Copyright (c) 2013, Opera Software ASA. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Opera Software ASA nor the names of its
+ * contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef VTTCue_h
+#define VTTCue_h
+
+#include "bindings/v8/ScriptWrappable.h"
+#include "core/html/track/TextTrackCue.h"
+
+namespace WebCore {
+
+class Document;
+class ExecutionContext;
+class VTTCue;
+
+class VTTCueBox FINAL : public HTMLDivElement {
+public:
+ static PassRefPtr<VTTCueBox> create(Document& document, VTTCue* cue)
+ {
+ return adoptRef(new VTTCueBox(document, cue));
+ }
+
+ VTTCue* getCue() const { return m_cue; }
+ void applyCSSProperties(const IntSize& videoSize);
+
+private:
+ VTTCueBox(Document&, VTTCue*);
+
+ virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
+
+ VTTCue* m_cue;
+};
+
+class VTTCue FINAL : public TextTrackCue, public ScriptWrappable {
+public:
+ static PassRefPtr<VTTCue> create(Document& document, double startTime, double endTime, const String& text)
+ {
+ return adoptRef(new VTTCue(document, startTime, endTime, text));
+ }
+
+ virtual ~VTTCue();
+
+ const String& vertical() const;
+ void setVertical(const String&, ExceptionState&);
+
+ bool snapToLines() const { return m_snapToLines; }
+ void setSnapToLines(bool);
+
+ int line() const { return m_linePosition; }
+ void setLine(int, ExceptionState&);
+
+ int position() const { return m_textPosition; }
+ void setPosition(int, ExceptionState&);
+
+ int size() const { return m_cueSize; }
+ void setSize(int, ExceptionState&);
+
+ const String& align() const;
+ void setAlign(const String&, ExceptionState&);
+
+ const String& text() const { return m_text; }
+ void setText(const String&);
+
+ void parseSettings(const String&);
+
+ PassRefPtr<DocumentFragment> getCueAsHTML();
+ PassRefPtr<DocumentFragment> createCueRenderingTree();
+
+ const String& regionId() const { return m_regionId; }
+ void setRegionId(const String&);
+
+ virtual void updateDisplay(const IntSize& videoSize, HTMLDivElement& container) OVERRIDE;
+
+ virtual void updateDisplayTree(double movieTime) OVERRIDE;
+ virtual void removeDisplayTree() OVERRIDE;
+ virtual void notifyRegionWhenRemovingDisplayTree(bool notifyRegion) OVERRIDE;
+
+ void markFutureAndPastNodes(ContainerNode*, double previousTimestamp, double movieTime);
+
+ int calculateComputedLinePosition();
+
+ std::pair<double, double> getCSSPosition() const;
+
+ CSSValueID getCSSAlignment() const;
+ int getCSSSize() const;
+ CSSValueID getCSSWritingDirection() const;
+ CSSValueID getCSSWritingMode() const;
+
+ enum WritingDirection {
+ Horizontal = 0,
+ VerticalGrowingLeft,
+ VerticalGrowingRight,
+ NumberOfWritingDirections
+ };
+ WritingDirection getWritingDirection() const { return m_writingDirection; }
+
+ enum CueAlignment {
+ Start = 0,
+ Middle,
+ End,
+ Left,
+ Right,
+ NumberOfAlignments
+ };
+ CueAlignment getAlignment() const { return m_cueAlignment; }
+
+ virtual ExecutionContext* executionContext() const OVERRIDE;
+
+#ifndef NDEBUG
+ virtual String toString() const OVERRIDE;
+#endif
+
+private:
+ VTTCue(Document&, double startTime, double endTime, const String& text);
+
+ Document& document() const;
+
+ PassRefPtr<VTTCueBox> displayTreeInternal();
+ PassRefPtr<VTTCueBox> getDisplayTree(const IntSize& videoSize);
+
+ virtual void cueDidChange() OVERRIDE;
+
+ void createVTTNodeTree();
+ void copyVTTNodeToDOMTree(ContainerNode* vttNode, ContainerNode* root);
+
+ std::pair<double, double> getPositionCoordinates() const;
+
+ void calculateDisplayParameters();
+
+ enum CueSetting {
+ None,
+ Vertical,
+ Line,
+ Position,
+ Size,
+ Align,
+ RegionId
+ };
+ CueSetting settingName(const String&);
+
+ String m_text;
+ int m_linePosition;
+ int m_computedLinePosition;
+ int m_textPosition;
+ int m_cueSize;
+ WritingDirection m_writingDirection;
+ CueAlignment m_cueAlignment;
+ String m_regionId;
+
+ RefPtr<DocumentFragment> m_vttNodeTree;
+ RefPtr<HTMLDivElement> m_cueBackgroundBox;
+ RefPtr<VTTCueBox> m_displayTree;
+
+ CSSValueID m_displayDirection;
+ int m_displaySize;
+ std::pair<float, float> m_displayPosition;
+
+ bool m_snapToLines : 1;
+ bool m_displayTreeShouldChange : 1;
+ bool m_notifyRegion : 1;
+};
+
+inline VTTCue* toVTTCue(TextTrackCue* cue)
+{
+ // VTTCue is currently the only TextTrackCue subclass.
+ return static_cast<VTTCue*>(cue);
+}
+
+} // namespace WebCore
+
+#endif
diff --git a/chromium/third_party/WebKit/Source/core/html/track/vtt/VTTCue.idl b/chromium/third_party/WebKit/Source/core/html/track/vtt/VTTCue.idl
new file mode 100644
index 00000000000..8b958174353
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/html/track/vtt/VTTCue.idl
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) 2013, Opera Software ASA. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Opera Software ASA nor the names of its
+ * contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+[
+ Constructor(double startTime, double endTime, DOMString text),
+ ConstructorCallWith=Document,
+ RuntimeEnabled=VideoTrack,
+] interface VTTCue : TextTrackCue {
+ [RuntimeEnabled=WebVTTRegions] attribute DOMString regionId;
+ [RaisesException=Setter] attribute DOMString vertical;
+ attribute boolean snapToLines;
+ [RaisesException=Setter] attribute long line;
+ [RaisesException=Setter] attribute long position;
+ [RaisesException=Setter] attribute long size;
+ [RaisesException=Setter] attribute DOMString align;
+ attribute DOMString text;
+ DocumentFragment getCueAsHTML();
+};
diff --git a/chromium/third_party/WebKit/Source/core/html/track/vtt/VTTElement.cpp b/chromium/third_party/WebKit/Source/core/html/track/vtt/VTTElement.cpp
new file mode 100644
index 00000000000..e9b350a1304
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/html/track/vtt/VTTElement.cpp
@@ -0,0 +1,121 @@
+/*
+ * Copyright (C) 2013 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/html/track/vtt/VTTElement.h"
+
+#include "HTMLElementFactory.h"
+
+namespace WebCore {
+
+static const QualifiedName& nodeTypeToTagName(VTTNodeType nodeType)
+{
+ DEFINE_STATIC_LOCAL(QualifiedName, cTag, (nullAtom, "c", nullAtom));
+ DEFINE_STATIC_LOCAL(QualifiedName, vTag, (nullAtom, "v", nullAtom));
+ DEFINE_STATIC_LOCAL(QualifiedName, langTag, (nullAtom, "lang", nullAtom));
+ DEFINE_STATIC_LOCAL(QualifiedName, bTag, (nullAtom, "b", nullAtom));
+ DEFINE_STATIC_LOCAL(QualifiedName, uTag, (nullAtom, "u", nullAtom));
+ DEFINE_STATIC_LOCAL(QualifiedName, iTag, (nullAtom, "i", nullAtom));
+ DEFINE_STATIC_LOCAL(QualifiedName, rubyTag, (nullAtom, "ruby", nullAtom));
+ DEFINE_STATIC_LOCAL(QualifiedName, rtTag, (nullAtom, "rt", nullAtom));
+ switch (nodeType) {
+ case VTTNodeTypeClass:
+ return cTag;
+ case VTTNodeTypeItalic:
+ return iTag;
+ case VTTNodeTypeLanguage:
+ return langTag;
+ case VTTNodeTypeBold:
+ return bTag;
+ case VTTNodeTypeUnderline:
+ return uTag;
+ case VTTNodeTypeRuby:
+ return rubyTag;
+ case VTTNodeTypeRubyText:
+ return rtTag;
+ case VTTNodeTypeVoice:
+ return vTag;
+ case VTTNodeTypeNone:
+ default:
+ ASSERT_NOT_REACHED();
+ return cTag; // Make the compiler happy.
+ }
+}
+
+VTTElement::VTTElement(VTTNodeType nodeType, Document* document)
+ : Element(nodeTypeToTagName(nodeType), document, CreateElement)
+ , m_isPastNode(0)
+ , m_webVTTNodeType(nodeType)
+{
+}
+
+PassRefPtr<VTTElement> VTTElement::create(VTTNodeType nodeType, Document* document)
+{
+ return adoptRef(new VTTElement(nodeType, document));
+}
+
+PassRefPtr<Element> VTTElement::cloneElementWithoutAttributesAndChildren()
+{
+ RefPtr<VTTElement> clone = create(static_cast<VTTNodeType>(m_webVTTNodeType), &document());
+ clone->setLanguage(m_language);
+ return clone;
+}
+
+PassRefPtr<HTMLElement> VTTElement::createEquivalentHTMLElement(Document& document)
+{
+ RefPtr<HTMLElement> htmlElement;
+ switch (m_webVTTNodeType) {
+ case VTTNodeTypeClass:
+ case VTTNodeTypeLanguage:
+ case VTTNodeTypeVoice:
+ htmlElement = HTMLElementFactory::createHTMLElement(HTMLNames::spanTag.localName(), document);
+ htmlElement.get()->setAttribute(HTMLNames::titleAttr, getAttribute(voiceAttributeName()));
+ htmlElement.get()->setAttribute(HTMLNames::langAttr, getAttribute(langAttributeName()));
+ break;
+ case VTTNodeTypeItalic:
+ htmlElement = HTMLElementFactory::createHTMLElement(HTMLNames::iTag.localName(), document);
+ break;
+ case VTTNodeTypeBold:
+ htmlElement = HTMLElementFactory::createHTMLElement(HTMLNames::bTag.localName(), document);
+ break;
+ case VTTNodeTypeUnderline:
+ htmlElement = HTMLElementFactory::createHTMLElement(HTMLNames::uTag.localName(), document);
+ break;
+ case VTTNodeTypeRuby:
+ htmlElement = HTMLElementFactory::createHTMLElement(HTMLNames::rubyTag.localName(), document);
+ break;
+ case VTTNodeTypeRubyText:
+ htmlElement = HTMLElementFactory::createHTMLElement(HTMLNames::rtTag.localName(), document);
+ break;
+ default:
+ ASSERT_NOT_REACHED();
+ }
+
+ htmlElement.get()->setAttribute(HTMLNames::classAttr, getAttribute(HTMLNames::classAttr));
+ return htmlElement;
+}
+
+} // namespace WebCore
+
diff --git a/chromium/third_party/WebKit/Source/core/html/track/vtt/VTTElement.h b/chromium/third_party/WebKit/Source/core/html/track/vtt/VTTElement.h
new file mode 100644
index 00000000000..2fe08c79abe
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/html/track/vtt/VTTElement.h
@@ -0,0 +1,85 @@
+/*
+ * Copyright (C) 2013 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "core/html/HTMLElement.h"
+
+namespace WebCore {
+
+enum VTTNodeType {
+ VTTNodeTypeNone = 0,
+ VTTNodeTypeClass,
+ VTTNodeTypeItalic,
+ VTTNodeTypeLanguage,
+ VTTNodeTypeBold,
+ VTTNodeTypeUnderline,
+ VTTNodeTypeRuby,
+ VTTNodeTypeRubyText,
+ VTTNodeTypeVoice
+};
+
+class VTTElement FINAL : public Element {
+public:
+ static PassRefPtr<VTTElement> create(const VTTNodeType, Document*);
+ static PassRefPtr<VTTElement> create(const QualifiedName&, Document*);
+ PassRefPtr<HTMLElement> createEquivalentHTMLElement(Document&);
+
+ virtual PassRefPtr<Element> cloneElementWithoutAttributesAndChildren() OVERRIDE;
+
+ void setVTTNodeType(VTTNodeType type) { m_webVTTNodeType = static_cast<unsigned>(type); }
+ VTTNodeType webVTTNodeType() const { return static_cast<VTTNodeType>(m_webVTTNodeType); }
+
+ bool isPastNode() const { return m_isPastNode; }
+ void setIsPastNode(bool value) { m_isPastNode = value; }
+
+ virtual bool isVTTElement() const OVERRIDE { return true; }
+ AtomicString language() const { return m_language; }
+ void setLanguage(AtomicString value) { m_language = value; }
+
+ static const QualifiedName& voiceAttributeName()
+ {
+ DEFINE_STATIC_LOCAL(QualifiedName, voiceAttr, (nullAtom, "voice", nullAtom));
+ return voiceAttr;
+ }
+
+ static const QualifiedName& langAttributeName()
+ {
+ DEFINE_STATIC_LOCAL(QualifiedName, voiceAttr, (nullAtom, "lang", nullAtom));
+ return voiceAttr;
+ }
+
+private:
+ VTTElement(const QualifiedName&, Document*);
+ VTTElement(VTTNodeType, Document*);
+
+ unsigned m_isPastNode : 1;
+ unsigned m_webVTTNodeType : 4;
+
+ AtomicString m_language;
+};
+
+DEFINE_NODE_TYPE_CASTS(VTTElement, isVTTElement());
+
+} // namespace WebCore
+
diff --git a/chromium/third_party/WebKit/Source/core/html/track/vtt/VTTParser.cpp b/chromium/third_party/WebKit/Source/core/html/track/vtt/VTTParser.cpp
new file mode 100644
index 00000000000..e1b4b2a372d
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/html/track/vtt/VTTParser.cpp
@@ -0,0 +1,627 @@
+/*
+ * Copyright (C) 2011 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/html/track/vtt/VTTParser.h"
+
+#include "core/dom/Document.h"
+#include "core/dom/ProcessingInstruction.h"
+#include "core/dom/Text.h"
+#include "core/html/track/vtt/VTTElement.h"
+#include "platform/text/SegmentedString.h"
+#include "wtf/text/WTFString.h"
+
+namespace WebCore {
+
+const double secondsPerHour = 3600;
+const double secondsPerMinute = 60;
+const double secondsPerMillisecond = 0.001;
+const unsigned fileIdentifierLength = 6;
+
+static unsigned scanDigits(const String& input, unsigned* position)
+{
+ unsigned startPosition = *position;
+ while (*position < input.length() && isASCIIDigit(input[*position]))
+ (*position)++;
+ return *position - startPosition;
+}
+
+unsigned VTTParser::collectDigitsToInt(const String& input, unsigned* position, int& number)
+{
+ unsigned startPosition = *position;
+ unsigned numDigits = scanDigits(input, position);
+ if (!numDigits) {
+ number = 0;
+ return 0;
+ }
+ bool validNumber;
+ if (input.is8Bit())
+ number = charactersToInt(input.characters8() + startPosition, numDigits, &validNumber);
+ else
+ number = charactersToInt(input.characters16() + startPosition, numDigits, &validNumber);
+
+ // Since we know that scanDigits only scanned valid (ASCII) digits (and
+ // hence that's what got passed to charactersToInt()), the remaining
+ // failure mode for charactersToInt() is overflow, so if |validNumber| is
+ // not true, then set |number| to the maximum int value.
+ if (!validNumber)
+ number = std::numeric_limits<int>::max();
+ return numDigits;
+}
+
+String VTTParser::collectWord(const String& input, unsigned* position)
+{
+ StringBuilder string;
+ while (*position < input.length() && !isASpace(input[*position]))
+ string.append(input[(*position)++]);
+ return string.toString();
+}
+
+void VTTParser::skipWhiteSpace(const String& line, unsigned* position)
+{
+ while (*position < line.length() && isASpace(line[*position]))
+ (*position)++;
+}
+
+bool VTTParser::parseFloatPercentageValue(const String& value, float& percentage)
+{
+ // '%' must be present and at the end of the setting value.
+ if (value.isEmpty() || value[value.length() - 1] != '%')
+ return false;
+
+ unsigned position = 0;
+ unsigned digitsBeforeDot = scanDigits(value, &position);
+ unsigned digitsAfterDot = 0;
+ if (value[position] == '.') {
+ position++;
+
+ digitsAfterDot = scanDigits(value, &position);
+ }
+
+ // At least one digit required.
+ if (!digitsBeforeDot && !digitsAfterDot)
+ return false;
+
+ float number = value.toFloat();
+ if (number < 0 || number > 100)
+ return false;
+
+ percentage = number;
+ return true;
+}
+
+bool VTTParser::parseFloatPercentageValuePair(const String& value, char delimiter, FloatPoint& valuePair)
+{
+ // The delimiter can't be the first or second value because a pair of
+ // percentages (x%,y%) implies that at least the first two characters
+ // are the first percentage value.
+ size_t delimiterOffset = value.find(delimiter, 2);
+ if (delimiterOffset == kNotFound || delimiterOffset == value.length() - 1)
+ return false;
+
+ float firstCoord;
+ if (!parseFloatPercentageValue(value.substring(0, delimiterOffset), firstCoord))
+ return false;
+
+ float secondCoord;
+ if (!parseFloatPercentageValue(value.substring(delimiterOffset + 1, value.length() - 1), secondCoord))
+ return false;
+
+ valuePair = FloatPoint(firstCoord, secondCoord);
+ return true;
+}
+
+VTTParser::VTTParser(VTTParserClient* client, Document& document)
+ : m_document(&document)
+ , m_state(Initial)
+ , m_decoder(TextResourceDecoder::create("text/plain", UTF8Encoding()))
+ , m_currentStartTime(0)
+ , m_currentEndTime(0)
+ , m_client(client)
+{
+}
+
+void VTTParser::getNewCues(Vector<RefPtr<VTTCue> >& outputCues)
+{
+ outputCues = m_cuelist;
+ m_cuelist.clear();
+}
+
+void VTTParser::getNewRegions(Vector<RefPtr<VTTRegion> >& outputRegions)
+{
+ outputRegions = m_regionList;
+ m_regionList.clear();
+}
+
+void VTTParser::parseBytes(const char* data, unsigned length)
+{
+ String textData = m_decoder->decode(data, length);
+ m_lineReader.append(textData);
+ parse();
+}
+
+void VTTParser::flush()
+{
+ String textData = m_decoder->flush();
+ m_lineReader.append(textData);
+ m_lineReader.setEndOfStream();
+ parse();
+ flushPendingCue();
+}
+
+void VTTParser::parse()
+{
+ // WebVTT parser algorithm. (5.1 WebVTT file parsing.)
+ // Steps 1 - 3 - Initial setup.
+
+ String line;
+ while (m_lineReader.getLine(line)) {
+ switch (m_state) {
+ case Initial:
+ // Steps 4 - 9 - Check for a valid WebVTT signature.
+ if (!hasRequiredFileIdentifier(line)) {
+ if (m_client)
+ m_client->fileFailedToParse();
+ return;
+ }
+
+ m_state = Header;
+ break;
+
+ case Header:
+ // Steps 10 - 14 - Allow a header (comment area) under the WEBVTT line.
+ collectMetadataHeader(line);
+
+ if (line.isEmpty()) {
+ if (m_client && m_regionList.size())
+ m_client->newRegionsParsed();
+
+ m_state = Id;
+ break;
+ }
+
+ // Step 15 - Break out of header loop if the line could be a timestamp line.
+ if (line.contains("-->"))
+ m_state = recoverCue(line);
+
+ // Step 16 - Line is not the empty string and does not contain "-->".
+ break;
+
+ case Id:
+ // Steps 17 - 20 - Allow any number of line terminators, then initialize new cue values.
+ if (line.isEmpty())
+ break;
+
+ // Step 21 - Cue creation (start a new cue).
+ resetCueValues();
+
+ // Steps 22 - 25 - Check if this line contains an optional identifier or timing data.
+ m_state = collectCueId(line);
+ break;
+
+ case TimingsAndSettings:
+ // Steps 26 - 27 - Discard current cue if the line is empty.
+ if (line.isEmpty()) {
+ m_state = Id;
+ break;
+ }
+
+ // Steps 28 - 29 - Collect cue timings and settings.
+ m_state = collectTimingsAndSettings(line);
+ break;
+
+ case CueText:
+ // Steps 31 - 41 - Collect the cue text, create a cue, and add it to the output.
+ m_state = collectCueText(line);
+ break;
+
+ case BadCue:
+ // Steps 42 - 48 - Discard lines until an empty line or a potential timing line is seen.
+ m_state = ignoreBadCue(line);
+ break;
+ }
+ }
+}
+
+void VTTParser::flushPendingCue()
+{
+ ASSERT(m_lineReader.isAtEndOfStream());
+ // If we're in the CueText state when we run out of data, we emit the pending cue.
+ if (m_state == CueText)
+ createNewCue();
+}
+
+bool VTTParser::hasRequiredFileIdentifier(const String& line)
+{
+ // A WebVTT file identifier consists of an optional BOM character,
+ // the string "WEBVTT" followed by an optional space or tab character,
+ // and any number of characters that are not line terminators ...
+ if (!line.startsWith("WEBVTT", fileIdentifierLength))
+ return false;
+ if (line.length() > fileIdentifierLength && !isASpace(line[fileIdentifierLength]))
+ return false;
+
+ return true;
+}
+
+void VTTParser::collectMetadataHeader(const String& line)
+{
+ // WebVTT header parsing (WebVTT parser algorithm step 12)
+ DEFINE_STATIC_LOCAL(const AtomicString, regionHeaderName, ("Region", AtomicString::ConstructFromLiteral));
+
+ // The only currently supported header is the "Region" header.
+ if (!RuntimeEnabledFeatures::webVTTRegionsEnabled())
+ return;
+
+ // Step 12.4 If line contains the character ":" (A U+003A COLON), then set metadata's
+ // name to the substring of line before the first ":" character and
+ // metadata's value to the substring after this character.
+ size_t colonPosition = line.find(':');
+ if (colonPosition == kNotFound)
+ return;
+
+ String headerName = line.substring(0, colonPosition);
+
+ // Steps 12.5 If metadata's name equals "Region":
+ if (headerName == regionHeaderName) {
+ String headerValue = line.substring(colonPosition + 1);
+ // Steps 12.5.1 - 12.5.11 Region creation: Let region be a new text track region [...]
+ createNewRegion(headerValue);
+ }
+}
+
+VTTParser::ParseState VTTParser::collectCueId(const String& line)
+{
+ if (line.contains("-->"))
+ return collectTimingsAndSettings(line);
+ m_currentId = line;
+ return TimingsAndSettings;
+}
+
+VTTParser::ParseState VTTParser::collectTimingsAndSettings(const String& line)
+{
+ // Collect WebVTT cue timings and settings. (5.3 WebVTT cue timings and settings parsing.)
+ // Steps 1 - 3 - Let input be the string being parsed and position be a pointer into input.
+ unsigned position = 0;
+ skipWhiteSpace(line, &position);
+
+ // Steps 4 - 5 - Collect a WebVTT timestamp. If that fails, then abort and return failure. Otherwise, let cue's text track cue start time be the collected time.
+ if (!collectTimeStamp(line, &position, m_currentStartTime))
+ return BadCue;
+ if (position >= line.length())
+ return BadCue;
+
+ skipWhiteSpace(line, &position);
+
+ // Steps 6 - 9 - If the next three characters are not "-->", abort and return failure.
+ if (line.find("-->", position) == kNotFound)
+ return BadCue;
+ position += 3;
+ if (position >= line.length())
+ return BadCue;
+
+ skipWhiteSpace(line, &position);
+
+ // Steps 10 - 11 - Collect a WebVTT timestamp. If that fails, then abort and return failure. Otherwise, let cue's text track cue end time be the collected time.
+ if (!collectTimeStamp(line, &position, m_currentEndTime))
+ return BadCue;
+ skipWhiteSpace(line, &position);
+
+ // Step 12 - Parse the WebVTT settings for the cue (conducted in TextTrackCue).
+ m_currentSettings = line.substring(position, line.length()-1);
+ return CueText;
+}
+
+VTTParser::ParseState VTTParser::collectCueText(const String& line)
+{
+ // Step 34.
+ if (line.isEmpty()) {
+ createNewCue();
+ return Id;
+ }
+ // Step 35.
+ if (line.contains("-->")) {
+ // Step 39-40.
+ createNewCue();
+
+ // Step 41 - New iteration of the cue loop.
+ return recoverCue(line);
+ }
+ if (!m_currentContent.isEmpty())
+ m_currentContent.append("\n");
+ m_currentContent.append(line);
+
+ return CueText;
+}
+
+VTTParser::ParseState VTTParser::recoverCue(const String& line)
+{
+ // Step 17 and 21.
+ resetCueValues();
+
+ // Step 22.
+ return collectTimingsAndSettings(line);
+}
+
+VTTParser::ParseState VTTParser::ignoreBadCue(const String& line)
+{
+ if (line.isEmpty())
+ return Id;
+ if (line.contains("-->"))
+ return recoverCue(line);
+ return BadCue;
+}
+
+// A helper class for the construction of a "cue fragment" from the cue text.
+class VTTTreeBuilder {
+public:
+ VTTTreeBuilder(Document& document)
+ : m_document(document) { }
+
+ PassRefPtr<DocumentFragment> buildFromString(const String& cueText);
+
+private:
+ void constructTreeFromToken(Document&);
+
+ VTTToken m_token;
+ RefPtr<ContainerNode> m_currentNode;
+ Vector<AtomicString> m_languageStack;
+ Document& m_document;
+};
+
+PassRefPtr<DocumentFragment> VTTTreeBuilder::buildFromString(const String& cueText)
+{
+ // Cue text processing based on
+ // 5.4 WebVTT cue text parsing rules, and
+ // 5.5 WebVTT cue text DOM construction rules
+
+ RefPtr<DocumentFragment> fragment = DocumentFragment::create(m_document);
+
+ if (cueText.isEmpty()) {
+ fragment->parserAppendChild(Text::create(m_document, ""));
+ return fragment;
+ }
+
+ m_currentNode = fragment;
+
+ VTTTokenizer tokenizer(cueText);
+ m_languageStack.clear();
+
+ while (tokenizer.nextToken(m_token))
+ constructTreeFromToken(m_document);
+
+ return fragment.release();
+}
+
+PassRefPtr<DocumentFragment> VTTParser::createDocumentFragmentFromCueText(Document& document, const String& cueText)
+{
+ VTTTreeBuilder treeBuilder(document);
+ return treeBuilder.buildFromString(cueText);
+}
+
+void VTTParser::createNewCue()
+{
+ RefPtr<VTTCue> cue = VTTCue::create(*m_document, m_currentStartTime, m_currentEndTime, m_currentContent.toString());
+ cue->setId(m_currentId);
+ cue->parseSettings(m_currentSettings);
+
+ m_cuelist.append(cue);
+ if (m_client)
+ m_client->newCuesParsed();
+}
+
+void VTTParser::resetCueValues()
+{
+ m_currentId = emptyString();
+ m_currentSettings = emptyString();
+ m_currentStartTime = 0;
+ m_currentEndTime = 0;
+ m_currentContent.clear();
+}
+
+void VTTParser::createNewRegion(const String& headerValue)
+{
+ if (headerValue.isEmpty())
+ return;
+
+ // Steps 12.5.1 - 12.5.9 - Construct and initialize a WebVTT Region object.
+ RefPtr<VTTRegion> region = VTTRegion::create();
+ region->setRegionSettings(headerValue);
+
+ // Step 12.5.10 If the text track list of regions regions contains a region
+ // with the same region identifier value as region, remove that region.
+ for (size_t i = 0; i < m_regionList.size(); ++i) {
+ if (m_regionList[i]->id() == region->id()) {
+ m_regionList.remove(i);
+ break;
+ }
+ }
+
+ // Step 12.5.11
+ m_regionList.append(region);
+}
+
+bool VTTParser::collectTimeStamp(const String& line, unsigned* position, double& timeStamp)
+{
+ // Collect a WebVTT timestamp (5.3 WebVTT cue timings and settings parsing.)
+ // Steps 1 - 4 - Initial checks, let most significant units be minutes.
+ enum Mode { Minutes, Hours };
+ Mode mode = Minutes;
+
+ // Steps 5 - 7 - Collect a sequence of characters that are 0-9.
+ // If not 2 characters or value is greater than 59, interpret as hours.
+ int value1;
+ unsigned value1Digits = collectDigitsToInt(line, position, value1);
+ if (!value1Digits)
+ return false;
+ if (value1Digits != 2 || value1 > 59)
+ mode = Hours;
+
+ // Steps 8 - 11 - Collect the next sequence of 0-9 after ':' (must be 2 chars).
+ if (*position >= line.length() || line[(*position)++] != ':')
+ return false;
+ int value2;
+ if (collectDigitsToInt(line, position, value2) != 2)
+ return false;
+
+ // Step 12 - Detect whether this timestamp includes hours.
+ int value3;
+ if (mode == Hours || (*position < line.length() && line[*position] == ':')) {
+ if (*position >= line.length() || line[(*position)++] != ':')
+ return false;
+ if (collectDigitsToInt(line, position, value3) != 2)
+ return false;
+ } else {
+ value3 = value2;
+ value2 = value1;
+ value1 = 0;
+ }
+
+ // Steps 13 - 17 - Collect next sequence of 0-9 after '.' (must be 3 chars).
+ if (*position >= line.length() || line[(*position)++] != '.')
+ return false;
+ int value4;
+ if (collectDigitsToInt(line, position, value4) != 3)
+ return false;
+ if (value2 > 59 || value3 > 59)
+ return false;
+
+ // Steps 18 - 19 - Calculate result.
+ timeStamp = (value1 * secondsPerHour) + (value2 * secondsPerMinute) + value3 + (value4 * secondsPerMillisecond);
+ return true;
+}
+
+static VTTNodeType tokenToNodeType(VTTToken& token)
+{
+ switch (token.name().length()) {
+ case 1:
+ if (token.name()[0] == 'c')
+ return VTTNodeTypeClass;
+ if (token.name()[0] == 'v')
+ return VTTNodeTypeVoice;
+ if (token.name()[0] == 'b')
+ return VTTNodeTypeBold;
+ if (token.name()[0] == 'i')
+ return VTTNodeTypeItalic;
+ if (token.name()[0] == 'u')
+ return VTTNodeTypeUnderline;
+ break;
+ case 2:
+ if (token.name()[0] == 'r' && token.name()[1] == 't')
+ return VTTNodeTypeRubyText;
+ break;
+ case 4:
+ if (token.name()[0] == 'r' && token.name()[1] == 'u' && token.name()[2] == 'b' && token.name()[3] == 'y')
+ return VTTNodeTypeRuby;
+ if (token.name()[0] == 'l' && token.name()[1] == 'a' && token.name()[2] == 'n' && token.name()[3] == 'g')
+ return VTTNodeTypeLanguage;
+ break;
+ }
+ return VTTNodeTypeNone;
+}
+
+void VTTTreeBuilder::constructTreeFromToken(Document& document)
+{
+ // http://dev.w3.org/html5/webvtt/#webvtt-cue-text-dom-construction-rules
+
+ switch (m_token.type()) {
+ case VTTTokenTypes::Character: {
+ RefPtr<Text> child = Text::create(document, m_token.characters());
+ m_currentNode->parserAppendChild(child);
+ break;
+ }
+ case VTTTokenTypes::StartTag: {
+ VTTNodeType nodeType = tokenToNodeType(m_token);
+ if (nodeType == VTTNodeTypeNone)
+ break;
+
+ VTTNodeType currentType = m_currentNode->isVTTElement() ? toVTTElement(m_currentNode.get())->webVTTNodeType() : VTTNodeTypeNone;
+ // <rt> is only allowed if the current node is <ruby>.
+ if (nodeType == VTTNodeTypeRubyText && currentType != VTTNodeTypeRuby)
+ break;
+
+ RefPtr<VTTElement> child = VTTElement::create(nodeType, &document);
+ if (!m_token.classes().isEmpty())
+ child->setAttribute(classAttr, m_token.classes());
+
+ if (nodeType == VTTNodeTypeVoice) {
+ child->setAttribute(VTTElement::voiceAttributeName(), m_token.annotation());
+ } else if (nodeType == VTTNodeTypeLanguage) {
+ m_languageStack.append(m_token.annotation());
+ child->setAttribute(VTTElement::langAttributeName(), m_languageStack.last());
+ }
+ if (!m_languageStack.isEmpty())
+ child->setLanguage(m_languageStack.last());
+ m_currentNode->parserAppendChild(child);
+ m_currentNode = child;
+ break;
+ }
+ case VTTTokenTypes::EndTag: {
+ VTTNodeType nodeType = tokenToNodeType(m_token);
+ if (nodeType == VTTNodeTypeNone)
+ break;
+
+ // The only non-VTTElement would be the DocumentFragment root. (Text
+ // nodes and PIs will never appear as m_currentNode.)
+ if (!m_currentNode->isVTTElement())
+ break;
+
+ VTTNodeType currentType = toVTTElement(m_currentNode.get())->webVTTNodeType();
+ bool matchesCurrent = nodeType == currentType;
+ if (!matchesCurrent) {
+ // </ruby> auto-closes <rt>.
+ if (currentType == VTTNodeTypeRubyText && nodeType == VTTNodeTypeRuby) {
+ if (m_currentNode->parentNode())
+ m_currentNode = m_currentNode->parentNode();
+ } else {
+ break;
+ }
+ }
+ if (nodeType == VTTNodeTypeLanguage)
+ m_languageStack.removeLast();
+ if (m_currentNode->parentNode())
+ m_currentNode = m_currentNode->parentNode();
+ break;
+ }
+ case VTTTokenTypes::TimestampTag: {
+ unsigned position = 0;
+ String charactersString = m_token.characters();
+ double parsedTimeStamp;
+ if (VTTParser::collectTimeStamp(charactersString, &position, parsedTimeStamp))
+ m_currentNode->parserAppendChild(ProcessingInstruction::create(document, "timestamp", charactersString));
+ break;
+ }
+ default:
+ break;
+ }
+}
+
+}
+
diff --git a/chromium/third_party/WebKit/Source/core/html/track/vtt/VTTParser.h b/chromium/third_party/WebKit/Source/core/html/track/vtt/VTTParser.h
new file mode 100644
index 00000000000..df4e584cae9
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/html/track/vtt/VTTParser.h
@@ -0,0 +1,155 @@
+/*
+ * Copyright (C) 2011 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef VTTParser_h
+#define VTTParser_h
+
+#include "HTMLNames.h"
+#include "RuntimeEnabledFeatures.h"
+#include "core/dom/DocumentFragment.h"
+#include "core/fetch/TextResourceDecoder.h"
+#include "core/html/track/vtt/BufferedLineReader.h"
+#include "core/html/track/vtt/VTTCue.h"
+#include "core/html/track/vtt/VTTRegion.h"
+#include "core/html/track/vtt/VTTTokenizer.h"
+#include "wtf/PassOwnPtr.h"
+#include "wtf/text/StringBuilder.h"
+
+namespace WebCore {
+
+using namespace HTMLNames;
+
+class Document;
+
+class VTTParserClient {
+public:
+ virtual ~VTTParserClient() { }
+
+ virtual void newCuesParsed() = 0;
+ virtual void newRegionsParsed() = 0;
+ virtual void fileFailedToParse() = 0;
+};
+
+class VTTParser FINAL {
+public:
+ enum ParseState {
+ Initial,
+ Header,
+ Id,
+ TimingsAndSettings,
+ CueText,
+ BadCue
+ };
+
+ static PassOwnPtr<VTTParser> create(VTTParserClient* client, Document& document)
+ {
+ return adoptPtr(new VTTParser(client, document));
+ }
+
+ static inline bool isRecognizedTag(const AtomicString& tagName)
+ {
+ return tagName == iTag
+ || tagName == bTag
+ || tagName == uTag
+ || tagName == rubyTag
+ || tagName == rtTag;
+ }
+
+ static inline bool isASpace(char c)
+ {
+ // WebVTT space characters are U+0020 SPACE, U+0009 CHARACTER TABULATION (tab), U+000A LINE FEED (LF), U+000C FORM FEED (FF), and U+000D CARRIAGE RETURN (CR).
+ return c == ' ' || c == '\t' || c == '\n' || c == '\f' || c == '\r';
+ }
+ static inline bool isValidSettingDelimiter(char c)
+ {
+ // ... a WebVTT cue consists of zero or more of the following components, in any order, separated from each other by one or more
+ // U+0020 SPACE characters or U+0009 CHARACTER TABULATION (tab) characters.
+ return c == ' ' || c == '\t';
+ }
+ static unsigned collectDigitsToInt(const String& input, unsigned* position, int& number);
+ static String collectWord(const String&, unsigned*);
+ static bool collectTimeStamp(const String&, unsigned*, double& timeStamp);
+
+ // Useful functions for parsing percentage settings.
+ static bool parseFloatPercentageValue(const String&, float&);
+ static bool parseFloatPercentageValuePair(const String&, char, FloatPoint&);
+
+ // Create the DocumentFragment representation of the WebVTT cue text.
+ static PassRefPtr<DocumentFragment> createDocumentFragmentFromCueText(Document&, const String&);
+
+ // Input data to the parser to parse.
+ void parseBytes(const char* data, unsigned length);
+ void flush();
+
+ // Transfers ownership of last parsed cues to caller.
+ void getNewCues(Vector<RefPtr<VTTCue> >&);
+ void getNewRegions(Vector<RefPtr<VTTRegion> >&);
+
+private:
+ VTTParser(VTTParserClient*, Document&);
+
+ Document* m_document;
+ ParseState m_state;
+
+ void parse();
+ void flushPendingCue();
+ bool hasRequiredFileIdentifier(const String& line);
+ ParseState collectCueId(const String&);
+ ParseState collectTimingsAndSettings(const String&);
+ ParseState collectCueText(const String&);
+ ParseState recoverCue(const String&);
+ ParseState ignoreBadCue(const String&);
+
+ void createNewCue();
+ void resetCueValues();
+
+ void collectMetadataHeader(const String&);
+ void createNewRegion(const String& headerValue);
+
+ static void skipWhiteSpace(const String&, unsigned*);
+
+ BufferedLineReader m_lineReader;
+ OwnPtr<TextResourceDecoder> m_decoder;
+ String m_currentId;
+ double m_currentStartTime;
+ double m_currentEndTime;
+ StringBuilder m_currentContent;
+ String m_currentSettings;
+
+ VTTParserClient* m_client;
+
+ Vector<RefPtr<VTTCue> > m_cuelist;
+
+ Vector<RefPtr<VTTRegion> > m_regionList;
+};
+
+} // namespace WebCore
+
+#endif
diff --git a/chromium/third_party/WebKit/Source/core/html/track/vtt/VTTRegion.cpp b/chromium/third_party/WebKit/Source/core/html/track/vtt/VTTRegion.cpp
new file mode 100644
index 00000000000..4f39fb51cc9
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/html/track/vtt/VTTRegion.cpp
@@ -0,0 +1,466 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/html/track/vtt/VTTRegion.h"
+
+#include "bindings/v8/ExceptionMessages.h"
+#include "bindings/v8/ExceptionState.h"
+#include "core/dom/ClientRect.h"
+#include "core/dom/DOMTokenList.h"
+#include "core/html/HTMLDivElement.h"
+#include "core/html/track/vtt/VTTParser.h"
+#include "core/rendering/RenderInline.h"
+#include "core/rendering/RenderObject.h"
+#include "platform/Logging.h"
+#include "wtf/MathExtras.h"
+#include "wtf/text/StringBuilder.h"
+
+namespace WebCore {
+
+// The following values default values are defined within the WebVTT Regions Spec.
+// https://dvcs.w3.org/hg/text-tracks/raw-file/default/608toVTT/region.html
+
+// The region occupies by default 100% of the width of the video viewport.
+static const float defaultWidth = 100;
+
+// The region has, by default, 3 lines of text.
+static const long defaultHeightInLines = 3;
+
+// The region and viewport are anchored in the bottom left corner.
+static const float defaultAnchorPointX = 0;
+static const float defaultAnchorPointY = 100;
+
+// The region doesn't have scrolling text, by default.
+static const bool defaultScroll = false;
+
+// Default region line-height (vh units)
+static const float lineHeight = 5.33;
+
+// Default scrolling animation time period (s).
+static const float scrollTime = 0.433;
+
+static bool isInfiniteOrNonNumberOrNonPercentage(double value, const char* method, ExceptionState& exceptionState)
+{
+ if (!std::isfinite(value)) {
+ exceptionState.throwTypeError(ExceptionMessages::notAFiniteNumber(value));
+ return true;
+ }
+ if (value < 0 || value > 100) {
+ exceptionState.throwDOMException(IndexSizeError, "The value provided (" + String::number(value) + ") is not between 0 and 100.");
+ return true;
+ }
+ return false;
+}
+
+VTTRegion::VTTRegion()
+ : m_id(emptyString())
+ , m_width(defaultWidth)
+ , m_heightInLines(defaultHeightInLines)
+ , m_regionAnchor(FloatPoint(defaultAnchorPointX, defaultAnchorPointY))
+ , m_viewportAnchor(FloatPoint(defaultAnchorPointX, defaultAnchorPointY))
+ , m_scroll(defaultScroll)
+ , m_track(0)
+ , m_currentTop(0)
+ , m_scrollTimer(this, &VTTRegion::scrollTimerFired)
+{
+}
+
+VTTRegion::~VTTRegion()
+{
+}
+
+void VTTRegion::setTrack(TextTrack* track)
+{
+ m_track = track;
+}
+
+void VTTRegion::setId(const String& id)
+{
+ m_id = id;
+}
+
+void VTTRegion::setWidth(double value, ExceptionState& exceptionState)
+{
+ if (isInfiniteOrNonNumberOrNonPercentage(value, "width", exceptionState))
+ return;
+
+ m_width = value;
+}
+
+void VTTRegion::setHeight(long value, ExceptionState& exceptionState)
+{
+ if (value < 0) {
+ exceptionState.throwDOMException(IndexSizeError, "The height provided (" + String::number(value) + ") is negative.");
+ return;
+ }
+
+ m_heightInLines = value;
+}
+
+void VTTRegion::setRegionAnchorX(double value, ExceptionState& exceptionState)
+{
+ if (isInfiniteOrNonNumberOrNonPercentage(value, "regionAnchorX", exceptionState))
+ return;
+
+ m_regionAnchor.setX(value);
+}
+
+void VTTRegion::setRegionAnchorY(double value, ExceptionState& exceptionState)
+{
+ if (isInfiniteOrNonNumberOrNonPercentage(value, "regionAnchorY", exceptionState))
+ return;
+
+ m_regionAnchor.setY(value);
+}
+
+void VTTRegion::setViewportAnchorX(double value, ExceptionState& exceptionState)
+{
+ if (isInfiniteOrNonNumberOrNonPercentage(value, "viewportAnchorX", exceptionState))
+ return;
+
+ m_viewportAnchor.setX(value);
+}
+
+void VTTRegion::setViewportAnchorY(double value, ExceptionState& exceptionState)
+{
+ if (isInfiniteOrNonNumberOrNonPercentage(value, "viewportAnchorY", exceptionState))
+ return;
+
+ m_viewportAnchor.setY(value);
+}
+
+const AtomicString VTTRegion::scroll() const
+{
+ DEFINE_STATIC_LOCAL(const AtomicString, upScrollValueKeyword, ("up", AtomicString::ConstructFromLiteral));
+
+ if (m_scroll)
+ return upScrollValueKeyword;
+
+ return "";
+}
+
+void VTTRegion::setScroll(const AtomicString& value, ExceptionState& exceptionState)
+{
+ DEFINE_STATIC_LOCAL(const AtomicString, upScrollValueKeyword, ("up", AtomicString::ConstructFromLiteral));
+
+ if (value != emptyString() && value != upScrollValueKeyword) {
+ exceptionState.throwDOMException(SyntaxError, "The value provided ('" + value + "') is invalid. The 'scroll' property must be either the empty string, or 'up'.");
+ return;
+ }
+
+ m_scroll = value == upScrollValueKeyword;
+}
+
+void VTTRegion::updateParametersFromRegion(VTTRegion* region)
+{
+ m_heightInLines = region->height();
+ m_width = region->width();
+
+ m_regionAnchor = FloatPoint(region->regionAnchorX(), region->regionAnchorY());
+ m_viewportAnchor = FloatPoint(region->viewportAnchorX(), region->viewportAnchorY());
+
+ setScroll(region->scroll(), ASSERT_NO_EXCEPTION);
+}
+
+void VTTRegion::setRegionSettings(const String& input)
+{
+ m_settings = input;
+ unsigned position = 0;
+
+ while (position < input.length()) {
+ while (position < input.length() && VTTParser::isValidSettingDelimiter(input[position]))
+ position++;
+
+ if (position >= input.length())
+ break;
+
+ parseSetting(input, &position);
+ }
+}
+
+VTTRegion::RegionSetting VTTRegion::getSettingFromString(const String& setting)
+{
+ DEFINE_STATIC_LOCAL(const AtomicString, idKeyword, ("id", AtomicString::ConstructFromLiteral));
+ DEFINE_STATIC_LOCAL(const AtomicString, heightKeyword, ("height", AtomicString::ConstructFromLiteral));
+ DEFINE_STATIC_LOCAL(const AtomicString, widthKeyword, ("width", AtomicString::ConstructFromLiteral));
+ DEFINE_STATIC_LOCAL(const AtomicString, regionAnchorKeyword, ("regionanchor", AtomicString::ConstructFromLiteral));
+ DEFINE_STATIC_LOCAL(const AtomicString, viewportAnchorKeyword, ("viewportanchor", AtomicString::ConstructFromLiteral));
+ DEFINE_STATIC_LOCAL(const AtomicString, scrollKeyword, ("scroll", AtomicString::ConstructFromLiteral));
+
+ if (setting == idKeyword)
+ return Id;
+ if (setting == heightKeyword)
+ return Height;
+ if (setting == widthKeyword)
+ return Width;
+ if (setting == viewportAnchorKeyword)
+ return ViewportAnchor;
+ if (setting == regionAnchorKeyword)
+ return RegionAnchor;
+ if (setting == scrollKeyword)
+ return Scroll;
+
+ return None;
+}
+
+void VTTRegion::parseSettingValue(RegionSetting setting, const String& value)
+{
+ DEFINE_STATIC_LOCAL(const AtomicString, scrollUpValueKeyword, ("up", AtomicString::ConstructFromLiteral));
+
+ switch (setting) {
+ case Id:
+ if (value.find("-->") == kNotFound)
+ m_id = value;
+ break;
+ case Width: {
+ float floatWidth;
+ if (VTTParser::parseFloatPercentageValue(value, floatWidth))
+ m_width = floatWidth;
+ else
+ WTF_LOG(Media, "VTTRegion::parseSettingValue, invalid Width");
+ break;
+ }
+ case Height: {
+ unsigned position = 0;
+ int number;
+ if (VTTParser::collectDigitsToInt(value, &position, number) && position == value.length())
+ m_heightInLines = number;
+ else
+ WTF_LOG(Media, "VTTRegion::parseSettingValue, invalid Height");
+ break;
+ }
+ case RegionAnchor:
+ if (!VTTParser::parseFloatPercentageValuePair(value, ',', m_regionAnchor))
+ WTF_LOG(Media, "VTTRegion::parseSettingValue, invalid RegionAnchor");
+ break;
+ case ViewportAnchor:
+ if (!VTTParser::parseFloatPercentageValuePair(value, ',', m_viewportAnchor))
+ WTF_LOG(Media, "VTTRegion::parseSettingValue, invalid ViewportAnchor");
+ break;
+ case Scroll:
+ if (value == scrollUpValueKeyword)
+ m_scroll = true;
+ else
+ WTF_LOG(Media, "VTTRegion::parseSettingValue, invalid Scroll");
+ break;
+ case None:
+ break;
+ }
+}
+
+void VTTRegion::parseSetting(const String& input, unsigned* position)
+{
+ String setting = VTTParser::collectWord(input, position);
+
+ size_t equalOffset = setting.find('=', 1);
+ if (equalOffset == kNotFound || !equalOffset || equalOffset == setting.length() - 1)
+ return;
+
+ RegionSetting name = getSettingFromString(setting.substring(0, equalOffset));
+ String value = setting.substring(equalOffset + 1, setting.length() - 1);
+
+ parseSettingValue(name, value);
+}
+
+const AtomicString& VTTRegion::textTrackCueContainerShadowPseudoId()
+{
+ DEFINE_STATIC_LOCAL(const AtomicString, trackRegionCueContainerPseudoId,
+ ("-webkit-media-text-track-region-container", AtomicString::ConstructFromLiteral));
+
+ return trackRegionCueContainerPseudoId;
+}
+
+const AtomicString& VTTRegion::textTrackCueContainerScrollingClass()
+{
+ DEFINE_STATIC_LOCAL(const AtomicString, trackRegionCueContainerScrollingClass,
+ ("scrolling", AtomicString::ConstructFromLiteral));
+
+ return trackRegionCueContainerScrollingClass;
+}
+
+const AtomicString& VTTRegion::textTrackRegionShadowPseudoId()
+{
+ DEFINE_STATIC_LOCAL(const AtomicString, trackRegionShadowPseudoId,
+ ("-webkit-media-text-track-region", AtomicString::ConstructFromLiteral));
+
+ return trackRegionShadowPseudoId;
+}
+
+PassRefPtr<HTMLDivElement> VTTRegion::getDisplayTree(Document& document)
+{
+ if (!m_regionDisplayTree) {
+ m_regionDisplayTree = HTMLDivElement::create(document);
+ prepareRegionDisplayTree();
+ }
+
+ return m_regionDisplayTree;
+}
+
+void VTTRegion::willRemoveVTTCueBox(VTTCueBox* box)
+{
+ WTF_LOG(Media, "VTTRegion::willRemoveVTTCueBox");
+ ASSERT(m_cueContainer->contains(box));
+
+ double boxHeight = box->getBoundingClientRect()->bottom() - box->getBoundingClientRect()->top();
+
+ m_cueContainer->classList()->remove(textTrackCueContainerScrollingClass(), ASSERT_NO_EXCEPTION);
+
+ m_currentTop += boxHeight;
+ m_cueContainer->setInlineStyleProperty(CSSPropertyTop, m_currentTop, CSSPrimitiveValue::CSS_PX);
+}
+
+void VTTRegion::appendVTTCueBox(PassRefPtr<VTTCueBox> displayBox)
+{
+ ASSERT(m_cueContainer);
+
+ if (m_cueContainer->contains(displayBox.get()))
+ return;
+
+ m_cueContainer->appendChild(displayBox);
+ displayLastVTTCueBox();
+}
+
+void VTTRegion::displayLastVTTCueBox()
+{
+ WTF_LOG(Media, "VTTRegion::displayLastVTTCueBox");
+ ASSERT(m_cueContainer);
+
+ // FIXME: This should not be causing recalc styles in a loop to set the "top" css
+ // property to move elements. We should just scroll the text track cues on the
+ // compositor with an animation.
+
+ if (m_scrollTimer.isActive())
+ return;
+
+ // If it's a scrolling region, add the scrolling class.
+ if (isScrollingRegion())
+ m_cueContainer->classList()->add(textTrackCueContainerScrollingClass(), ASSERT_NO_EXCEPTION);
+
+ float regionBottom = m_regionDisplayTree->getBoundingClientRect()->bottom();
+
+ // Find first cue that is not entirely displayed and scroll it upwards.
+ for (size_t i = 0; i < m_cueContainer->childNodeCount() && !m_scrollTimer.isActive(); ++i) {
+ float childTop = toHTMLDivElement(m_cueContainer->childNode(i))->getBoundingClientRect()->top();
+ float childBottom = toHTMLDivElement(m_cueContainer->childNode(i))->getBoundingClientRect()->bottom();
+
+ if (regionBottom >= childBottom)
+ continue;
+
+ float height = childBottom - childTop;
+
+ m_currentTop -= std::min(height, childBottom - regionBottom);
+ m_cueContainer->setInlineStyleProperty(CSSPropertyTop, m_currentTop, CSSPrimitiveValue::CSS_PX);
+
+ startTimer();
+ }
+}
+
+void VTTRegion::prepareRegionDisplayTree()
+{
+ ASSERT(m_regionDisplayTree);
+
+ // 7.2 Prepare region CSS boxes
+
+ // FIXME: Change the code below to use viewport units when
+ // http://crbug/244618 is fixed.
+
+ // Let regionWidth be the text track region width.
+ // Let width be 'regionWidth vw' ('vw' is a CSS unit)
+ m_regionDisplayTree->setInlineStyleProperty(CSSPropertyWidth,
+ m_width, CSSPrimitiveValue::CSS_PERCENTAGE);
+
+ // Let lineHeight be '0.0533vh' ('vh' is a CSS unit) and regionHeight be
+ // the text track region height. Let height be 'lineHeight' multiplied
+ // by regionHeight.
+ double height = lineHeight * m_heightInLines;
+ m_regionDisplayTree->setInlineStyleProperty(CSSPropertyHeight,
+ height, CSSPrimitiveValue::CSS_VH);
+
+ // Let viewportAnchorX be the x dimension of the text track region viewport
+ // anchor and regionAnchorX be the x dimension of the text track region
+ // anchor. Let leftOffset be regionAnchorX multiplied by width divided by
+ // 100.0. Let left be leftOffset subtracted from 'viewportAnchorX vw'.
+ double leftOffset = m_regionAnchor.x() * m_width / 100;
+ m_regionDisplayTree->setInlineStyleProperty(CSSPropertyLeft,
+ m_viewportAnchor.x() - leftOffset,
+ CSSPrimitiveValue::CSS_PERCENTAGE);
+
+ // Let viewportAnchorY be the y dimension of the text track region viewport
+ // anchor and regionAnchorY be the y dimension of the text track region
+ // anchor. Let topOffset be regionAnchorY multiplied by height divided by
+ // 100.0. Let top be topOffset subtracted from 'viewportAnchorY vh'.
+ double topOffset = m_regionAnchor.y() * height / 100;
+ m_regionDisplayTree->setInlineStyleProperty(CSSPropertyTop,
+ m_viewportAnchor.y() - topOffset,
+ CSSPrimitiveValue::CSS_PERCENTAGE);
+
+ // The cue container is used to wrap the cues and it is the object which is
+ // gradually scrolled out as multiple cues are appended to the region.
+ m_cueContainer = HTMLDivElement::create(m_regionDisplayTree->document());
+ m_cueContainer->setInlineStyleProperty(CSSPropertyTop,
+ 0.0,
+ CSSPrimitiveValue::CSS_PX);
+
+ m_cueContainer->setPseudo(textTrackCueContainerShadowPseudoId());
+ m_regionDisplayTree->appendChild(m_cueContainer);
+
+ // 7.5 Every WebVTT region object is initialised with the following CSS
+ m_regionDisplayTree->setPseudo(textTrackRegionShadowPseudoId());
+}
+
+void VTTRegion::startTimer()
+{
+ WTF_LOG(Media, "VTTRegion::startTimer");
+
+ if (m_scrollTimer.isActive())
+ return;
+
+ double duration = isScrollingRegion() ? scrollTime : 0;
+ m_scrollTimer.startOneShot(duration);
+}
+
+void VTTRegion::stopTimer()
+{
+ WTF_LOG(Media, "VTTRegion::stopTimer");
+
+ if (m_scrollTimer.isActive())
+ m_scrollTimer.stop();
+}
+
+void VTTRegion::scrollTimerFired(Timer<VTTRegion>*)
+{
+ WTF_LOG(Media, "VTTRegion::scrollTimerFired");
+
+ stopTimer();
+ displayLastVTTCueBox();
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/html/track/vtt/VTTRegion.h b/chromium/third_party/WebKit/Source/core/html/track/vtt/VTTRegion.h
new file mode 100644
index 00000000000..f9452c22498
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/html/track/vtt/VTTRegion.h
@@ -0,0 +1,154 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef VTTRegion_h
+#define VTTRegion_h
+
+#include "core/dom/ContextLifecycleObserver.h"
+#include "core/html/track/TextTrack.h"
+#include "platform/Timer.h"
+#include "platform/geometry/FloatPoint.h"
+#include "wtf/PassOwnPtr.h"
+#include "wtf/RefCounted.h"
+
+namespace WebCore {
+
+class ExceptionState;
+class HTMLDivElement;
+class VTTCueBox;
+
+class VTTRegion : public RefCounted<VTTRegion> {
+public:
+ static PassRefPtr<VTTRegion> create()
+ {
+ return adoptRef(new VTTRegion());
+ }
+
+ virtual ~VTTRegion();
+
+ TextTrack* track() const { return m_track; }
+ void setTrack(TextTrack*);
+
+ const String& id() const { return m_id; }
+ void setId(const String&);
+
+ double width() const { return m_width; }
+ void setWidth(double, ExceptionState&);
+
+ long height() const { return m_heightInLines; }
+ void setHeight(long, ExceptionState&);
+
+ double regionAnchorX() const { return m_regionAnchor.x(); }
+ void setRegionAnchorX(double, ExceptionState&);
+
+ double regionAnchorY() const { return m_regionAnchor.y(); }
+ void setRegionAnchorY(double, ExceptionState&);
+
+ double viewportAnchorX() const { return m_viewportAnchor.x(); }
+ void setViewportAnchorX(double, ExceptionState&);
+
+ double viewportAnchorY() const { return m_viewportAnchor.y(); }
+ void setViewportAnchorY(double, ExceptionState&);
+
+ const AtomicString scroll() const;
+ void setScroll(const AtomicString&, ExceptionState&);
+
+ void updateParametersFromRegion(VTTRegion*);
+
+ const String& regionSettings() const { return m_settings; }
+ void setRegionSettings(const String&);
+
+ bool isScrollingRegion() { return m_scroll; }
+
+ PassRefPtr<HTMLDivElement> getDisplayTree(Document&);
+
+ void appendVTTCueBox(PassRefPtr<VTTCueBox>);
+ void displayLastVTTCueBox();
+ void willRemoveVTTCueBox(VTTCueBox*);
+
+private:
+ VTTRegion();
+
+ void prepareRegionDisplayTree();
+
+ // The timer is needed to continue processing when cue scrolling ended.
+ void startTimer();
+ void stopTimer();
+ void scrollTimerFired(Timer<VTTRegion>*);
+
+ enum RegionSetting {
+ None,
+ Id,
+ Width,
+ Height,
+ RegionAnchor,
+ ViewportAnchor,
+ Scroll
+ };
+ RegionSetting getSettingFromString(const String&);
+ void parseSettingValue(RegionSetting, const String&);
+ void parseSetting(const String&, unsigned*);
+
+ static const AtomicString& textTrackCueContainerShadowPseudoId();
+ static const AtomicString& textTrackCueContainerScrollingClass();
+ static const AtomicString& textTrackRegionShadowPseudoId();
+
+ String m_id;
+ String m_settings;
+ double m_width;
+ unsigned m_heightInLines;
+ FloatPoint m_regionAnchor;
+ FloatPoint m_viewportAnchor;
+ bool m_scroll;
+
+ // The cue container is the container that is scrolled up to obtain the
+ // effect of scrolling cues when this is enabled for the regions.
+ RefPtr<HTMLDivElement> m_cueContainer;
+ RefPtr<HTMLDivElement> m_regionDisplayTree;
+
+ // The member variable track can be a raw pointer as it will never
+ // reference a destroyed TextTrack, as this member variable
+ // is cleared in the TextTrack destructor and it is generally
+ // set/reset within the addRegion and removeRegion methods.
+ TextTrack* m_track;
+
+ // Keep track of the current numeric value of the css "top" property.
+ double m_currentTop;
+
+ // The timer is used to display the next cue line after the current one has
+ // been displayed. It's main use is for scrolling regions and it triggers as
+ // soon as the animation for rolling out one line has finished, but
+ // currently it is used also for non-scrolling regions to use a single
+ // code path.
+ Timer<VTTRegion> m_scrollTimer;
+};
+
+} // namespace WebCore
+#endif
diff --git a/chromium/third_party/WebKit/Source/core/html/track/vtt/VTTRegion.idl b/chromium/third_party/WebKit/Source/core/html/track/vtt/VTTRegion.idl
new file mode 100644
index 00000000000..398f7404b97
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/html/track/vtt/VTTRegion.idl
@@ -0,0 +1,41 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+[
+ Constructor,
+ RuntimeEnabled=WebVTTRegions
+] interface VTTRegion {
+ readonly attribute TextTrack track;
+
+ attribute DOMString id;
+ [RaisesException=Setter] attribute double width;
+ [RaisesException=Setter] attribute long height;
+ [RaisesException=Setter] attribute double regionAnchorX;
+ [RaisesException=Setter] attribute double regionAnchorY;
+ [RaisesException=Setter] attribute double viewportAnchorX;
+ [RaisesException=Setter] attribute double viewportAnchorY;
+ [RaisesException=Setter] attribute DOMString scroll;
+};
+
diff --git a/chromium/third_party/WebKit/Source/core/html/track/vtt/VTTRegionList.cpp b/chromium/third_party/WebKit/Source/core/html/track/vtt/VTTRegionList.cpp
new file mode 100644
index 00000000000..914da521ae7
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/html/track/vtt/VTTRegionList.cpp
@@ -0,0 +1,81 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/html/track/vtt/VTTRegionList.h"
+
+namespace WebCore {
+
+VTTRegionList::VTTRegionList()
+{
+}
+
+unsigned long VTTRegionList::length() const
+{
+ return m_list.size();
+}
+
+VTTRegion* VTTRegionList::item(unsigned index) const
+{
+ if (index < m_list.size())
+ return m_list[index].get();
+
+ return 0;
+}
+
+VTTRegion* VTTRegionList::getRegionById(const String& id) const
+{
+ if (id.isEmpty())
+ return 0;
+
+ for (size_t i = 0; i < m_list.size(); ++i) {
+ if (m_list[i]->id() == id)
+ return m_list[i].get();
+ }
+
+ return 0;
+}
+
+void VTTRegionList::add(PassRefPtr<VTTRegion> region)
+{
+ m_list.append(region);
+}
+
+bool VTTRegionList::remove(VTTRegion* region)
+{
+ size_t index = m_list.find(region);
+ if (index == kNotFound)
+ return false;
+
+ m_list.remove(index);
+ return true;
+}
+
+void VTTRegionList::clear()
+{
+ m_list.clear();
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/html/track/vtt/VTTRegionList.h b/chromium/third_party/WebKit/Source/core/html/track/vtt/VTTRegionList.h
new file mode 100644
index 00000000000..35e1b8e8d47
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/html/track/vtt/VTTRegionList.h
@@ -0,0 +1,62 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef VTTRegionList_h
+#define VTTRegionList_h
+
+#include "core/html/track/vtt/VTTRegion.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefCounted.h"
+#include "wtf/Vector.h"
+
+namespace WebCore {
+
+class VTTRegionList : public RefCounted<VTTRegionList> {
+public:
+ static PassRefPtr<VTTRegionList> create()
+ {
+ return adoptRef(new VTTRegionList());
+ }
+
+ ~VTTRegionList() { }
+
+ unsigned long length() const;
+
+ VTTRegion* item(unsigned index) const;
+ VTTRegion* getRegionById(const String&) const;
+
+ void add(PassRefPtr<VTTRegion>);
+ bool remove(VTTRegion*);
+
+private:
+ VTTRegionList();
+ void clear();
+
+ Vector<RefPtr<VTTRegion> > m_list;
+};
+
+} // namespace WebCore
+
+#endif
diff --git a/chromium/third_party/WebKit/Source/core/html/track/vtt/VTTRegionList.idl b/chromium/third_party/WebKit/Source/core/html/track/vtt/VTTRegionList.idl
new file mode 100644
index 00000000000..4a06653bba0
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/html/track/vtt/VTTRegionList.idl
@@ -0,0 +1,33 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+[
+ RuntimeEnabled=WebVTTRegions
+] interface VTTRegionList {
+ readonly attribute unsigned long length;
+ getter VTTRegion item(unsigned long index);
+ VTTRegion getRegionById(DOMString id);
+};
+
diff --git a/chromium/third_party/WebKit/Source/core/html/track/vtt/VTTToken.h b/chromium/third_party/WebKit/Source/core/html/track/vtt/VTTToken.h
new file mode 100644
index 00000000000..c95134f08c4
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/html/track/vtt/VTTToken.h
@@ -0,0 +1,92 @@
+/*
+ * Copyright (C) 2011 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef VTTToken_h
+#define VTTToken_h
+
+namespace WebCore {
+
+class VTTTokenTypes {
+public:
+ enum Type {
+ Uninitialized,
+ Character,
+ StartTag,
+ EndTag,
+ TimestampTag,
+ };
+};
+
+class VTTToken {
+public:
+ typedef VTTTokenTypes Type;
+
+ VTTToken() : m_type(Type::Uninitialized) { }
+
+ static VTTToken StringToken(const String& characterData)
+ {
+ return VTTToken(Type::Character, characterData);
+ }
+ static VTTToken StartTag(const String& tagName, const AtomicString& classes = emptyAtom, const AtomicString& annotation = emptyAtom)
+ {
+ VTTToken token(Type::StartTag, tagName);
+ token.m_classes = classes;
+ token.m_annotation = annotation;
+ return token;
+ }
+ static VTTToken EndTag(const String& tagName)
+ {
+ return VTTToken(Type::EndTag, tagName);
+ }
+ static VTTToken TimestampTag(const String& timestampData)
+ {
+ return VTTToken(Type::TimestampTag, timestampData);
+ }
+
+ Type::Type type() const { return m_type; }
+ const String& name() const { return m_data; }
+ const String& characters() const { return m_data; }
+ const AtomicString& classes() const { return m_classes; }
+ const AtomicString& annotation() const { return m_annotation; }
+
+private:
+ VTTToken(Type::Type type, const String& data)
+ : m_type(type)
+ , m_data(data) { }
+
+ Type::Type m_type;
+ String m_data;
+ AtomicString m_annotation;
+ AtomicString m_classes;
+};
+
+}
+
+#endif
diff --git a/chromium/third_party/WebKit/Source/core/html/track/vtt/VTTTokenizer.cpp b/chromium/third_party/WebKit/Source/core/html/track/vtt/VTTTokenizer.cpp
new file mode 100644
index 00000000000..0d84269f9a0
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/html/track/vtt/VTTTokenizer.cpp
@@ -0,0 +1,265 @@
+/*
+ * Copyright (C) 2011 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+
+#include "core/html/track/vtt/VTTTokenizer.h"
+
+#include "core/xml/parser/MarkupTokenizerInlines.h"
+#include "wtf/text/StringBuilder.h"
+#include "wtf/unicode/CharacterNames.h"
+
+namespace WebCore {
+
+#define WEBVTT_BEGIN_STATE(stateName) case stateName: stateName:
+#define WEBVTT_ADVANCE_TO(stateName) \
+ do { \
+ state = stateName; \
+ ASSERT(!m_input.isEmpty()); \
+ m_inputStreamPreprocessor.advance(m_input); \
+ cc = m_inputStreamPreprocessor.nextInputCharacter(); \
+ goto stateName; \
+ } while (false)
+
+template<unsigned charactersCount>
+ALWAYS_INLINE bool equalLiteral(const StringBuilder& s, const char (&characters)[charactersCount])
+{
+ return WTF::equal(s, reinterpret_cast<const LChar*>(characters), charactersCount - 1);
+}
+
+static void addNewClass(StringBuilder& classes, const StringBuilder& newClass)
+{
+ if (!classes.isEmpty())
+ classes.append(' ');
+ classes.append(newClass);
+}
+
+inline bool emitToken(VTTToken& resultToken, const VTTToken& token)
+{
+ resultToken = token;
+ return true;
+}
+
+inline bool advanceAndEmitToken(SegmentedString& source, VTTToken& resultToken, const VTTToken& token)
+{
+ source.advanceAndUpdateLineNumber();
+ return emitToken(resultToken, token);
+}
+
+VTTTokenizer::VTTTokenizer(const String& input)
+ : m_input(input)
+ , m_inputStreamPreprocessor(this)
+{
+ // Append a EOF marker and close the input "stream".
+ ASSERT(!m_input.isClosed());
+ m_input.append(SegmentedString(String(&kEndOfFileMarker, 1)));
+ m_input.close();
+}
+
+bool VTTTokenizer::nextToken(VTTToken& token)
+{
+ if (m_input.isEmpty() || !m_inputStreamPreprocessor.peek(m_input))
+ return false;
+
+ UChar cc = m_inputStreamPreprocessor.nextInputCharacter();
+ if (cc == kEndOfFileMarker) {
+ m_inputStreamPreprocessor.advance(m_input);
+ return false;
+ }
+
+ StringBuilder buffer;
+ StringBuilder result;
+ StringBuilder classes;
+ enum {
+ DataState,
+ EscapeState,
+ TagState,
+ StartTagState,
+ StartTagClassState,
+ StartTagAnnotationState,
+ EndTagState,
+ TimestampTagState,
+ } state = DataState;
+
+ // 4.8.10.13.4 WebVTT cue text tokenizer
+ switch (state) {
+ WEBVTT_BEGIN_STATE(DataState) {
+ if (cc == '&') {
+ buffer.append(static_cast<LChar>(cc));
+ WEBVTT_ADVANCE_TO(EscapeState);
+ } else if (cc == '<') {
+ if (result.isEmpty()) {
+ WEBVTT_ADVANCE_TO(TagState);
+ } else {
+ // We don't want to advance input or perform a state transition - just return a (new) token.
+ // (On the next call to nextToken we will see '<' again, but take the other branch in this if instead.)
+ return emitToken(token, VTTToken::StringToken(result.toString()));
+ }
+ } else if (cc == kEndOfFileMarker) {
+ return advanceAndEmitToken(m_input, token, VTTToken::StringToken(result.toString()));
+ } else {
+ result.append(cc);
+ WEBVTT_ADVANCE_TO(DataState);
+ }
+ }
+ END_STATE()
+
+ WEBVTT_BEGIN_STATE(EscapeState) {
+ if (cc == ';') {
+ if (equalLiteral(buffer, "&amp")) {
+ result.append('&');
+ } else if (equalLiteral(buffer, "&lt")) {
+ result.append('<');
+ } else if (equalLiteral(buffer, "&gt")) {
+ result.append('>');
+ } else if (equalLiteral(buffer, "&lrm")) {
+ result.append(leftToRightMark);
+ } else if (equalLiteral(buffer, "&rlm")) {
+ result.append(rightToLeftMark);
+ } else if (equalLiteral(buffer, "&nbsp")) {
+ result.append(noBreakSpace);
+ } else {
+ buffer.append(static_cast<LChar>(cc));
+ result.append(buffer);
+ }
+ buffer.clear();
+ WEBVTT_ADVANCE_TO(DataState);
+ } else if (isASCIIAlphanumeric(cc)) {
+ buffer.append(static_cast<LChar>(cc));
+ WEBVTT_ADVANCE_TO(EscapeState);
+ } else if (cc == '<') {
+ result.append(buffer);
+ return emitToken(token, VTTToken::StringToken(result.toString()));
+ } else if (cc == kEndOfFileMarker) {
+ result.append(buffer);
+ return advanceAndEmitToken(m_input, token, VTTToken::StringToken(result.toString()));
+ } else {
+ result.append(buffer);
+ buffer.clear();
+
+ if (cc == '&') {
+ buffer.append(static_cast<LChar>(cc));
+ WEBVTT_ADVANCE_TO(EscapeState);
+ }
+ result.append(cc);
+ WEBVTT_ADVANCE_TO(DataState);
+ }
+ }
+ END_STATE()
+
+ WEBVTT_BEGIN_STATE(TagState) {
+ if (isTokenizerWhitespace(cc)) {
+ ASSERT(result.isEmpty());
+ WEBVTT_ADVANCE_TO(StartTagAnnotationState);
+ } else if (cc == '.') {
+ ASSERT(result.isEmpty());
+ WEBVTT_ADVANCE_TO(StartTagClassState);
+ } else if (cc == '/') {
+ WEBVTT_ADVANCE_TO(EndTagState);
+ } else if (WTF::isASCIIDigit(cc)) {
+ result.append(cc);
+ WEBVTT_ADVANCE_TO(TimestampTagState);
+ } else if (cc == '>' || cc == kEndOfFileMarker) {
+ ASSERT(result.isEmpty());
+ return advanceAndEmitToken(m_input, token, VTTToken::StartTag(result.toString()));
+ } else {
+ result.append(cc);
+ WEBVTT_ADVANCE_TO(StartTagState);
+ }
+ }
+ END_STATE()
+
+ WEBVTT_BEGIN_STATE(StartTagState) {
+ if (isTokenizerWhitespace(cc)) {
+ WEBVTT_ADVANCE_TO(StartTagAnnotationState);
+ } else if (cc == '.') {
+ WEBVTT_ADVANCE_TO(StartTagClassState);
+ } else if (cc == '>' || cc == kEndOfFileMarker) {
+ return advanceAndEmitToken(m_input, token, VTTToken::StartTag(result.toString()));
+ } else {
+ result.append(cc);
+ WEBVTT_ADVANCE_TO(StartTagState);
+ }
+ }
+ END_STATE()
+
+ WEBVTT_BEGIN_STATE(StartTagClassState) {
+ if (isTokenizerWhitespace(cc)) {
+ addNewClass(classes, buffer);
+ buffer.clear();
+ WEBVTT_ADVANCE_TO(StartTagAnnotationState);
+ } else if (cc == '.') {
+ addNewClass(classes, buffer);
+ buffer.clear();
+ WEBVTT_ADVANCE_TO(StartTagClassState);
+ } else if (cc == '>' || cc == kEndOfFileMarker) {
+ addNewClass(classes, buffer);
+ buffer.clear();
+ return advanceAndEmitToken(m_input, token, VTTToken::StartTag(result.toString(), classes.toAtomicString()));
+ } else {
+ buffer.append(cc);
+ WEBVTT_ADVANCE_TO(StartTagClassState);
+ }
+ }
+ END_STATE()
+
+ WEBVTT_BEGIN_STATE(StartTagAnnotationState) {
+ if (cc == '>' || cc == kEndOfFileMarker) {
+ return advanceAndEmitToken(m_input, token, VTTToken::StartTag(result.toString(), classes.toAtomicString(), buffer.toAtomicString()));
+ }
+ buffer.append(cc);
+ WEBVTT_ADVANCE_TO(StartTagAnnotationState);
+ }
+ END_STATE()
+
+ WEBVTT_BEGIN_STATE(EndTagState) {
+ if (cc == '>' || cc == kEndOfFileMarker)
+ return advanceAndEmitToken(m_input, token, VTTToken::EndTag(result.toString()));
+ result.append(cc);
+ WEBVTT_ADVANCE_TO(EndTagState);
+ }
+ END_STATE()
+
+ WEBVTT_BEGIN_STATE(TimestampTagState) {
+ if (cc == '>' || cc == kEndOfFileMarker)
+ return advanceAndEmitToken(m_input, token, VTTToken::TimestampTag(result.toString()));
+ result.append(cc);
+ WEBVTT_ADVANCE_TO(TimestampTagState);
+ }
+ END_STATE()
+
+ }
+
+ ASSERT_NOT_REACHED();
+ return false;
+}
+
+}
+
diff --git a/chromium/third_party/WebKit/Source/core/html/track/vtt/VTTTokenizer.h b/chromium/third_party/WebKit/Source/core/html/track/vtt/VTTTokenizer.h
new file mode 100644
index 00000000000..abc05e2ae0b
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/html/track/vtt/VTTTokenizer.h
@@ -0,0 +1,57 @@
+/*
+ * Copyright (C) 2011 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef VTTTokenizer_h
+#define VTTTokenizer_h
+
+#include "core/html/parser/InputStreamPreprocessor.h"
+#include "core/html/track/vtt/VTTToken.h"
+
+namespace WebCore {
+
+class VTTTokenizer {
+ WTF_MAKE_NONCOPYABLE(VTTTokenizer);
+public:
+ explicit VTTTokenizer(const String& input);
+
+ bool nextToken(VTTToken&);
+
+ inline bool shouldSkipNullCharacters() const { return true; }
+
+private:
+ SegmentedString m_input;
+
+ // ://www.whatwg.org/specs/web-apps/current-work/#preprocessing-the-input-stream
+ InputStreamPreprocessor<VTTTokenizer> m_inputStreamPreprocessor;
+};
+
+}
+
+#endif
diff --git a/chromium/third_party/WebKit/Source/core/inspector/AsyncCallStackTracker.cpp b/chromium/third_party/WebKit/Source/core/inspector/AsyncCallStackTracker.cpp
new file mode 100644
index 00000000000..d3a1982af2b
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/inspector/AsyncCallStackTracker.cpp
@@ -0,0 +1,223 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/inspector/AsyncCallStackTracker.h"
+
+#include "core/dom/ContextLifecycleObserver.h"
+#include "core/dom/ExecutionContext.h"
+
+namespace WebCore {
+
+class AsyncCallStackTracker::ExecutionContextData : public ContextLifecycleObserver {
+ WTF_MAKE_FAST_ALLOCATED;
+public:
+ ExecutionContextData(AsyncCallStackTracker* tracker, ExecutionContext* executionContext)
+ : ContextLifecycleObserver(executionContext)
+ , m_tracker(tracker)
+ {
+ }
+
+ virtual void contextDestroyed() OVERRIDE
+ {
+ m_tracker->contextDestroyed(executionContext());
+ ContextLifecycleObserver::contextDestroyed();
+ }
+
+private:
+ friend class AsyncCallStackTracker;
+ AsyncCallStackTracker* m_tracker;
+ HashSet<int> m_intervalTimerIds;
+ HashMap<int, RefPtr<AsyncCallChain> > m_timerCallChains;
+ HashMap<int, RefPtr<AsyncCallChain> > m_animationFrameCallChains;
+};
+
+AsyncCallStackTracker::AsyncCallStack::AsyncCallStack(const String& description, const ScriptValue& callFrames)
+ : m_description(description)
+ , m_callFrames(callFrames)
+{
+}
+
+AsyncCallStackTracker::AsyncCallStack::~AsyncCallStack()
+{
+}
+
+AsyncCallStackTracker::AsyncCallStackTracker()
+ : m_maxAsyncCallStackDepth(0)
+{
+}
+
+void AsyncCallStackTracker::setAsyncCallStackDepth(int depth)
+{
+ if (depth <= 0) {
+ m_maxAsyncCallStackDepth = 0;
+ clear();
+ } else {
+ m_maxAsyncCallStackDepth = depth;
+ }
+}
+
+const AsyncCallStackTracker::AsyncCallChain* AsyncCallStackTracker::currentAsyncCallChain() const
+{
+ if (m_currentAsyncCallChain)
+ ensureMaxAsyncCallChainDepth(m_currentAsyncCallChain.get(), m_maxAsyncCallStackDepth);
+ return m_currentAsyncCallChain.get();
+}
+
+void AsyncCallStackTracker::didInstallTimer(ExecutionContext* context, int timerId, bool singleShot, const ScriptValue& callFrames)
+{
+ DEFINE_STATIC_LOCAL(String, setTimeoutName, ("setTimeout"));
+ DEFINE_STATIC_LOCAL(String, setIntervalName, ("setInterval"));
+
+ ASSERT(context);
+ ASSERT(isEnabled());
+ if (!validateCallFrames(callFrames))
+ return;
+ ASSERT(timerId > 0);
+ ExecutionContextData* data = createContextDataIfNeeded(context);
+ data->m_timerCallChains.set(timerId, createAsyncCallChain(singleShot ? setTimeoutName : setIntervalName, callFrames));
+ if (!singleShot)
+ data->m_intervalTimerIds.add(timerId);
+}
+
+void AsyncCallStackTracker::didRemoveTimer(ExecutionContext* context, int timerId)
+{
+ ASSERT(context);
+ if (!isEnabled() || timerId <= 0)
+ return;
+ ExecutionContextData* data = m_executionContextDataMap.get(context);
+ if (!data)
+ return;
+ data->m_intervalTimerIds.remove(timerId);
+ data->m_timerCallChains.remove(timerId);
+}
+
+void AsyncCallStackTracker::willFireTimer(ExecutionContext* context, int timerId)
+{
+ ASSERT(context);
+ if (!isEnabled())
+ return;
+ ASSERT(timerId > 0);
+ ASSERT(!m_currentAsyncCallChain);
+ ExecutionContextData* data = m_executionContextDataMap.get(context);
+ if (!data)
+ return;
+ if (data->m_intervalTimerIds.contains(timerId))
+ m_currentAsyncCallChain = data->m_timerCallChains.get(timerId);
+ else
+ m_currentAsyncCallChain = data->m_timerCallChains.take(timerId);
+}
+
+void AsyncCallStackTracker::didRequestAnimationFrame(ExecutionContext* context, int callbackId, const ScriptValue& callFrames)
+{
+ DEFINE_STATIC_LOCAL(String, requestAnimationFrameName, ("requestAnimationFrame"));
+
+ ASSERT(context);
+ ASSERT(isEnabled());
+ if (!validateCallFrames(callFrames))
+ return;
+ ASSERT(callbackId > 0);
+ ExecutionContextData* data = createContextDataIfNeeded(context);
+ data->m_animationFrameCallChains.set(callbackId, createAsyncCallChain(requestAnimationFrameName, callFrames));
+}
+
+void AsyncCallStackTracker::didCancelAnimationFrame(ExecutionContext* context, int callbackId)
+{
+ ASSERT(context);
+ if (!isEnabled() || callbackId <= 0)
+ return;
+ if (ExecutionContextData* data = m_executionContextDataMap.get(context))
+ data->m_animationFrameCallChains.remove(callbackId);
+}
+
+void AsyncCallStackTracker::willFireAnimationFrame(ExecutionContext* context, int callbackId)
+{
+ ASSERT(context);
+ if (!isEnabled())
+ return;
+ ASSERT(callbackId > 0);
+ ASSERT(!m_currentAsyncCallChain);
+ if (ExecutionContextData* data = m_executionContextDataMap.get(context))
+ m_currentAsyncCallChain = data->m_animationFrameCallChains.take(callbackId);
+}
+
+void AsyncCallStackTracker::didFireAsyncCall()
+{
+ m_currentAsyncCallChain = 0;
+}
+
+PassRefPtr<AsyncCallStackTracker::AsyncCallChain> AsyncCallStackTracker::createAsyncCallChain(const String& description, const ScriptValue& callFrames)
+{
+ ASSERT(isEnabled());
+ RefPtr<AsyncCallChain> chain = adoptRef(m_currentAsyncCallChain ? new AsyncCallStackTracker::AsyncCallChain(*m_currentAsyncCallChain) : new AsyncCallStackTracker::AsyncCallChain());
+ ensureMaxAsyncCallChainDepth(chain.get(), m_maxAsyncCallStackDepth - 1);
+ chain->m_callStacks.prepend(adoptRef(new AsyncCallStackTracker::AsyncCallStack(description, callFrames)));
+ return chain.release();
+}
+
+void AsyncCallStackTracker::ensureMaxAsyncCallChainDepth(AsyncCallChain* chain, unsigned maxDepth)
+{
+ while (chain->m_callStacks.size() > maxDepth)
+ chain->m_callStacks.removeLast();
+}
+
+bool AsyncCallStackTracker::validateCallFrames(const ScriptValue& callFrames)
+{
+ return !callFrames.hasNoValue();
+}
+
+void AsyncCallStackTracker::contextDestroyed(ExecutionContext* context)
+{
+ ASSERT(context);
+ if (ExecutionContextData* data = m_executionContextDataMap.take(context))
+ delete data;
+}
+
+AsyncCallStackTracker::ExecutionContextData* AsyncCallStackTracker::createContextDataIfNeeded(ExecutionContext* context)
+{
+ ExecutionContextData* data = m_executionContextDataMap.get(context);
+ if (!data) {
+ data = new AsyncCallStackTracker::ExecutionContextData(this, context);
+ m_executionContextDataMap.set(context, data);
+ }
+ return data;
+}
+
+void AsyncCallStackTracker::clear()
+{
+ m_currentAsyncCallChain = 0;
+ Vector<ExecutionContextData*> contextsData;
+ copyValuesToVector(m_executionContextDataMap, contextsData);
+ m_executionContextDataMap.clear();
+ for (Vector<ExecutionContextData*>::const_iterator it = contextsData.begin(); it != contextsData.end(); ++it)
+ delete *it;
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/inspector/AsyncCallStackTracker.h b/chromium/third_party/WebKit/Source/core/inspector/AsyncCallStackTracker.h
new file mode 100644
index 00000000000..e032134eeda
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/inspector/AsyncCallStackTracker.h
@@ -0,0 +1,105 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef AsyncCallStackTracker_h
+#define AsyncCallStackTracker_h
+
+#include "bindings/v8/ScriptValue.h"
+#include "wtf/Deque.h"
+#include "wtf/HashMap.h"
+#include "wtf/HashSet.h"
+#include "wtf/Noncopyable.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefPtr.h"
+
+namespace WebCore {
+
+class ExecutionContext;
+
+class AsyncCallStackTracker {
+ WTF_MAKE_NONCOPYABLE(AsyncCallStackTracker);
+public:
+ class AsyncCallStack : public RefCounted<AsyncCallStack> {
+ public:
+ AsyncCallStack(const String&, const ScriptValue&);
+ ~AsyncCallStack();
+ String description() const { return m_description; }
+ ScriptValue callFrames() const { return m_callFrames; }
+ private:
+ String m_description;
+ ScriptValue m_callFrames;
+ };
+
+ typedef Deque<RefPtr<AsyncCallStack>, 4> AsyncCallStackVector;
+
+ class AsyncCallChain : public RefCounted<AsyncCallChain> {
+ public:
+ AsyncCallChain() { }
+ AsyncCallChain(const AsyncCallChain& t) : m_callStacks(t.m_callStacks) { }
+ AsyncCallStackVector callStacks() const { return m_callStacks; }
+ private:
+ friend class AsyncCallStackTracker;
+ AsyncCallStackVector m_callStacks;
+ };
+
+ AsyncCallStackTracker();
+
+ bool isEnabled() const { return m_maxAsyncCallStackDepth; }
+ void setAsyncCallStackDepth(int);
+ const AsyncCallChain* currentAsyncCallChain() const;
+
+ void didInstallTimer(ExecutionContext*, int timerId, bool singleShot, const ScriptValue& callFrames);
+ void didRemoveTimer(ExecutionContext*, int timerId);
+ void willFireTimer(ExecutionContext*, int timerId);
+
+ void didRequestAnimationFrame(ExecutionContext*, int callbackId, const ScriptValue& callFrames);
+ void didCancelAnimationFrame(ExecutionContext*, int callbackId);
+ void willFireAnimationFrame(ExecutionContext*, int callbackId);
+
+ void didFireAsyncCall();
+ void clear();
+
+private:
+ PassRefPtr<AsyncCallChain> createAsyncCallChain(const String& description, const ScriptValue& callFrames);
+ static void ensureMaxAsyncCallChainDepth(AsyncCallChain*, unsigned);
+ static bool validateCallFrames(const ScriptValue& callFrames);
+
+ class ExecutionContextData;
+ void contextDestroyed(ExecutionContext*);
+ ExecutionContextData* createContextDataIfNeeded(ExecutionContext*);
+
+ unsigned m_maxAsyncCallStackDepth;
+ RefPtr<AsyncCallChain> m_currentAsyncCallChain;
+ HashMap<ExecutionContext*, ExecutionContextData*> m_executionContextDataMap;
+};
+
+} // namespace WebCore
+
+#endif // !defined(AsyncCallStackTracker_h)
diff --git a/chromium/third_party/WebKit/Source/core/inspector/CodeGeneratorInspector.py b/chromium/third_party/WebKit/Source/core/inspector/CodeGeneratorInspector.py
index 20122e6a7f9..163ce99c1f9 100755
--- a/chromium/third_party/WebKit/Source/core/inspector/CodeGeneratorInspector.py
+++ b/chromium/third_party/WebKit/Source/core/inspector/CodeGeneratorInspector.py
@@ -1281,8 +1281,8 @@ class TypeBindings:
for prop_data in resolve_data.main_properties + resolve_data.optional_properties:
prop_name = prop_data.p["name"]
prop_field_name = Capitalizer.lower_camel_case_to_upper(prop_name)
- writer.newline(" static const char* %s;\n" % (prop_field_name))
- cpp_writer.newline("const char* %s%s::%s = \"%s\";\n" % (helper.full_name_prefix_for_impl, class_name, prop_field_name, prop_name))
+ writer.newline(" static const char %s[];\n" % (prop_field_name))
+ cpp_writer.newline("const char %s%s::%s[] = \"%s\";\n" % (helper.full_name_prefix_for_impl, class_name, prop_field_name, prop_name))
writer.newline("};\n\n")
@@ -1773,6 +1773,8 @@ class Generator:
backend_method_declaration_list = []
backend_method_implementation_list = []
backend_method_name_declaration_list = []
+ backend_method_name_declaration_index_list = []
+ backend_method_name_declaration_current_index = 0
method_handler_list = []
frontend_method_list = []
@@ -1796,6 +1798,7 @@ class Generator:
Generator.backend_method_declaration_list,
Generator.backend_method_implementation_list,
Generator.backend_method_name_declaration_list,
+ Generator.backend_method_name_declaration_index_list,
Generator.backend_agent_interface_list,
Generator.frontend_class_field_lines,
Generator.frontend_constructor_init_list,
@@ -1921,9 +1924,11 @@ class Generator:
if "parameters" in json_command:
json_params = json_command["parameters"]
- method_in_code += Templates.param_container_access_code
request_message_param = " requestMessageObject"
+ if json_params:
+ method_in_code += Templates.param_container_access_code
+
for json_parameter in json_params:
json_param_name = json_parameter["name"]
param_raw_type = resolve_param_raw_type(json_parameter, domain_name)
@@ -2063,7 +2068,10 @@ class Generator:
responseCook=normal_response_cook_text,
errorCook=error_response_cook_text,
commandNameIndex=cmd_enum_name))
- Generator.backend_method_name_declaration_list.append(" \"%s.%s\"," % (domain_name, json_command_name))
+ declaration_command_name = "%s.%s\\0" % (domain_name, json_command_name)
+ Generator.backend_method_name_declaration_list.append(" \"%s\"" % declaration_command_name)
+ Generator.backend_method_name_declaration_index_list.append(" %d," % Generator.backend_method_name_declaration_current_index)
+ Generator.backend_method_name_declaration_current_index += len(declaration_command_name) - 1
Generator.backend_agent_interface_list.append(") = 0;\n")
@@ -2307,6 +2315,7 @@ backend_cpp_file.write(Templates.backend_cpp.substitute(None,
setters="\n".join(Generator.backend_setters_list),
fieldDeclarations="\n".join(Generator.backend_field_list),
methodNameDeclarations="\n".join(Generator.backend_method_name_declaration_list),
+ methodNameDeclarationsIndex="\n".join(Generator.backend_method_name_declaration_index_list),
methods="\n".join(Generator.backend_method_implementation_list),
methodDeclarations="\n".join(Generator.backend_method_declaration_list),
messageHandlers="\n".join(Generator.method_handler_list)))
diff --git a/chromium/third_party/WebKit/Source/core/inspector/CodeGeneratorInspectorStrings.py b/chromium/third_party/WebKit/Source/core/inspector/CodeGeneratorInspectorStrings.py
index b7e74221464..bc3bb739e19 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/CodeGeneratorInspectorStrings.py
+++ b/chromium/third_party/WebKit/Source/core/inspector/CodeGeneratorInspectorStrings.py
@@ -60,7 +60,7 @@ $methodInCode
$errorCook${responseCook}
}
- sendResponse(callId, result, commandNames[$commandNameIndex], protocolErrors, error, resultErrorData);
+ sendResponse(callId, result, commandName($commandNameIndex), protocolErrors, error, resultErrorData);
}
""")
@@ -101,7 +101,7 @@ frontend_h = (
#define InspectorFrontend_h
#include "InspectorTypeBuilder.h"
-#include "core/platform/JSONValues.h"
+#include "platform/JSONValues.h"
#include "wtf/PassRefPtr.h"
#include "wtf/text/WTFString.h"
@@ -196,7 +196,11 @@ $methodNamesEnumContent
kMethodNamesEnumSize
};
- static const char* commandNames[];
+ static const char* commandName(MethodNames);
+
+private:
+ static const char commandNames[];
+ static const size_t commandNamesIndex[];
};
} // namespace WebCore
@@ -214,16 +218,24 @@ backend_cpp = (
#include "core/inspector/InspectorAgent.h"
#include "core/inspector/InspectorFrontendChannel.h"
#include "core/inspector/JSONParser.h"
-#include "core/platform/JSONValues.h"
+#include "platform/JSONValues.h"
#include "wtf/text/CString.h"
#include "wtf/text/WTFString.h"
namespace WebCore {
-const char* InspectorBackendDispatcher::commandNames[] = {
+const char InspectorBackendDispatcher::commandNames[] = {
$methodNameDeclarations
};
+const size_t InspectorBackendDispatcher::commandNamesIndex[] = {
+$methodNameDeclarationsIndex
+};
+
+const char* InspectorBackendDispatcher::commandName(MethodNames index) {
+ COMPILE_ASSERT(static_cast<int>(kMethodNamesEnumSize) == WTF_ARRAY_LENGTH(commandNamesIndex), command_name_array_problem);
+ return commandNames + commandNamesIndex[index];
+}
class InspectorBackendDispatcherImpl : public InspectorBackendDispatcher {
public:
@@ -281,9 +293,8 @@ void InspectorBackendDispatcherImpl::dispatch(const String& message)
static CallHandler handlers[] = {
$messageHandlers
};
- size_t length = WTF_ARRAY_LENGTH(commandNames);
- for (size_t i = 0; i < length; ++i)
- dispatchMap.add(commandNames[i], handlers[i]);
+ for (size_t i = 0; i < kMethodNamesEnumSize; ++i)
+ dispatchMap.add(commandName(static_cast<MethodNames>(i)), handlers[i]);
}
RefPtr<JSONValue> parsedMessage = parseJSON(message);
@@ -503,8 +514,6 @@ void InspectorBackendDispatcher::CallbackBase::sendIfActive(PassRefPtr<JSONObjec
m_alreadySent = true;
}
-COMPILE_ASSERT(static_cast<int>(InspectorBackendDispatcher::kMethodNamesEnumSize) == WTF_ARRAY_LENGTH(InspectorBackendDispatcher::commandNames), command_name_array_problem);
-
} // namespace WebCore
""")
@@ -516,7 +525,7 @@ frontend_cpp = (
#include "InspectorFrontend.h"
#include "core/inspector/InspectorFrontendChannel.h"
-#include "core/platform/JSONValues.h"
+#include "platform/JSONValues.h"
#include "wtf/text/CString.h"
#include "wtf/text/WTFString.h"
@@ -537,7 +546,7 @@ typebuilder_h = (
#ifndef InspectorTypeBuilder_h
#define InspectorTypeBuilder_h
-#include "core/platform/JSONValues.h"
+#include "platform/JSONValues.h"
#include "wtf/Assertions.h"
#include "wtf/PassRefPtr.h"
diff --git a/chromium/third_party/WebKit/Source/core/inspector/ConsoleAPITypes.h b/chromium/third_party/WebKit/Source/core/inspector/ConsoleAPITypes.h
index b36cdfed9ed..01a9fe9d833 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/ConsoleAPITypes.h
+++ b/chromium/third_party/WebKit/Source/core/inspector/ConsoleAPITypes.h
@@ -37,9 +37,7 @@ enum MessageType {
StartGroupCollapsedMessageType,
EndGroupMessageType,
ClearMessageType,
- AssertMessageType,
- ProfileMessageType,
- ProfileEndMessageType
+ AssertMessageType
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/inspector/ConsoleMessage.cpp b/chromium/third_party/WebKit/Source/core/inspector/ConsoleMessage.cpp
index 0de574d1703..4e1dabc4619 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/ConsoleMessage.cpp
+++ b/chromium/third_party/WebKit/Source/core/inspector/ConsoleMessage.cpp
@@ -33,7 +33,6 @@
#include "core/inspector/ConsoleMessage.h"
-#include "InspectorFrontend.h"
#include "bindings/v8/ScriptCallStackFactory.h"
#include "bindings/v8/ScriptValue.h"
#include "core/inspector/IdentifiersFactory.h"
@@ -123,7 +122,7 @@ void ConsoleMessage::autogenerateMetadata(bool canGenerateCallStack, ScriptState
return;
if (state)
- m_callStack = createScriptCallStackForConsole(state);
+ m_callStack = createScriptCallStackForConsole();
else if (canGenerateCallStack)
m_callStack = createScriptCallStack(ScriptCallStack::maxCallStackSizeToCapture, true);
else
@@ -171,8 +170,6 @@ static TypeBuilder::Console::ConsoleMessage::Type::Enum messageTypeValue(Message
case StartGroupCollapsedMessageType: return TypeBuilder::Console::ConsoleMessage::Type::StartGroupCollapsed;
case EndGroupMessageType: return TypeBuilder::Console::ConsoleMessage::Type::EndGroup;
case AssertMessageType: return TypeBuilder::Console::ConsoleMessage::Type::Assert;
- case ProfileMessageType: return TypeBuilder::Console::ConsoleMessage::Type::Profile;
- case ProfileEndMessageType: return TypeBuilder::Console::ConsoleMessage::Type::ProfileEnd;
}
return TypeBuilder::Console::ConsoleMessage::Type::Log;
}
@@ -184,6 +181,7 @@ static TypeBuilder::Console::ConsoleMessage::Level::Enum messageLevelValue(Messa
case LogMessageLevel: return TypeBuilder::Console::ConsoleMessage::Level::Log;
case WarningMessageLevel: return TypeBuilder::Console::ConsoleMessage::Level::Warning;
case ErrorMessageLevel: return TypeBuilder::Console::ConsoleMessage::Level::Error;
+ case InfoMessageLevel: return TypeBuilder::Console::ConsoleMessage::Level::Info;
}
return TypeBuilder::Console::ConsoleMessage::Level::Log;
}
diff --git a/chromium/third_party/WebKit/Source/core/inspector/ConsoleMessage.h b/chromium/third_party/WebKit/Source/core/inspector/ConsoleMessage.h
index 78f4f9f0fed..f487f74bd95 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/ConsoleMessage.h
+++ b/chromium/third_party/WebKit/Source/core/inspector/ConsoleMessage.h
@@ -34,7 +34,7 @@
#include "InspectorFrontend.h"
#include "bindings/v8/ScriptState.h"
#include "core/inspector/ConsoleAPITypes.h"
-#include "core/page/ConsoleTypes.h"
+#include "core/frame/ConsoleTypes.h"
#include "wtf/Forward.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/inspector/ContentSearchUtils.cpp b/chromium/third_party/WebKit/Source/core/inspector/ContentSearchUtils.cpp
index 7797e402b72..9ed8568644c 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/ContentSearchUtils.cpp
+++ b/chromium/third_party/WebKit/Source/core/inspector/ContentSearchUtils.cpp
@@ -30,7 +30,7 @@
#include "core/inspector/ContentSearchUtils.h"
-#include "core/platform/text/RegularExpression.h"
+#include "bindings/v8/ScriptRegexp.h"
#include "wtf/text/StringBuilder.h"
using namespace std;
@@ -57,7 +57,7 @@ static String createSearchRegexSource(const String& text)
return result.toString();
}
-static Vector<pair<int, String> > getRegularExpressionMatchesByLines(const RegularExpression* regex, const String& text)
+static Vector<pair<int, String> > getScriptRegexpMatchesByLines(const ScriptRegexp* regex, const String& text)
{
Vector<pair<int, String> > result;
if (text.isEmpty())
@@ -89,13 +89,13 @@ static PassRefPtr<TypeBuilder::Page::SearchMatch> buildObjectForSearchMatch(int
.release();
}
-PassOwnPtr<RegularExpression> createSearchRegex(const String& query, bool caseSensitive, bool isRegex)
+PassOwnPtr<ScriptRegexp> createSearchRegex(const String& query, bool caseSensitive, bool isRegex)
{
String regexSource = isRegex ? query : createSearchRegexSource(query);
- return adoptPtr(new RegularExpression(regexSource, caseSensitive ? TextCaseSensitive : TextCaseInsensitive));
+ return adoptPtr(new ScriptRegexp(regexSource, caseSensitive ? TextCaseSensitive : TextCaseInsensitive));
}
-int countRegularExpressionMatches(const RegularExpression* regex, const String& content)
+int countScriptRegexpMatches(const ScriptRegexp* regex, const String& content)
{
if (content.isEmpty())
return 0;
@@ -118,8 +118,8 @@ PassRefPtr<TypeBuilder::Array<TypeBuilder::Page::SearchMatch> > searchInTextByLi
{
RefPtr<TypeBuilder::Array<TypeBuilder::Page::SearchMatch> > result = TypeBuilder::Array<TypeBuilder::Page::SearchMatch>::create();
- OwnPtr<RegularExpression> regex = ContentSearchUtils::createSearchRegex(query, caseSensitive, isRegex);
- Vector<pair<int, String> > matches = getRegularExpressionMatchesByLines(regex.get(), text);
+ OwnPtr<ScriptRegexp> regex = ContentSearchUtils::createSearchRegex(query, caseSensitive, isRegex);
+ Vector<pair<int, String> > matches = getScriptRegexpMatchesByLines(regex.get(), text);
for (Vector<pair<int, String> >::const_iterator it = matches.begin(); it != matches.end(); ++it)
result->addItem(buildObjectForSearchMatch(it->first, it->second));
@@ -147,8 +147,8 @@ static String findMagicComment(const String& content, const String& name, MagicC
ASSERT_NOT_REACHED();
return String();
}
- RegularExpression regex(pattern, TextCaseSensitive, MultilineEnabled);
- RegularExpression deprecatedRegex(deprecatedPattern, TextCaseSensitive, MultilineEnabled);
+ ScriptRegexp regex(pattern, TextCaseSensitive, MultilineEnabled);
+ ScriptRegexp deprecatedRegex(deprecatedPattern, TextCaseSensitive, MultilineEnabled);
int matchLength;
int offset = regex.match(content, 0, &matchLength);
diff --git a/chromium/third_party/WebKit/Source/core/inspector/ContentSearchUtils.h b/chromium/third_party/WebKit/Source/core/inspector/ContentSearchUtils.h
index 7900e34205d..4ede1afb61a 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/ContentSearchUtils.h
+++ b/chromium/third_party/WebKit/Source/core/inspector/ContentSearchUtils.h
@@ -37,7 +37,7 @@
namespace WebCore {
-class RegularExpression;
+class ScriptRegexp;
namespace ContentSearchUtils {
@@ -46,8 +46,8 @@ enum MagicCommentType {
CSSMagicComment
};
-PassOwnPtr<RegularExpression> createSearchRegex(const String& query, bool caseSensitive, bool isRegex);
-int countRegularExpressionMatches(const RegularExpression*, const String&);
+PassOwnPtr<ScriptRegexp> createSearchRegex(const String& query, bool caseSensitive, bool isRegex);
+int countScriptRegexpMatches(const ScriptRegexp*, const String&);
PassRefPtr<TypeBuilder::Array<TypeBuilder::Page::SearchMatch> > searchInTextByLines(const String& text, const String& query, const bool caseSensitive, const bool isRegex);
String findSourceURL(const String& content, MagicCommentType, bool* deprecated);
diff --git a/chromium/third_party/WebKit/Source/core/inspector/DEPS b/chromium/third_party/WebKit/Source/core/inspector/DEPS
new file mode 100644
index 00000000000..e17e3a39a77
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/inspector/DEPS
@@ -0,0 +1,6 @@
+include_rules = [
+ # In order to link modules as a separate dylib, we'll need to sort out
+ # how to deal with the inspector's dependencies. Perhaps we'll want to
+ # move the inspector code out of blink_core.so?
+ "+modules",
+]
diff --git a/chromium/third_party/WebKit/Source/core/inspector/DOMEditor.cpp b/chromium/third_party/WebKit/Source/core/inspector/DOMEditor.cpp
index 152d47ff97c..cd3a1f5981d 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/DOMEditor.cpp
+++ b/chromium/third_party/WebKit/Source/core/inspector/DOMEditor.cpp
@@ -56,22 +56,22 @@ public:
{
}
- virtual bool perform(ExceptionState& es)
+ virtual bool perform(ExceptionState& exceptionState)
{
m_anchorNode = m_node->nextSibling();
- return redo(es);
+ return redo(exceptionState);
}
- virtual bool undo(ExceptionState& es)
+ virtual bool undo(ExceptionState& exceptionState)
{
- m_parentNode->insertBefore(m_node.get(), m_anchorNode.get(), es);
- return !es.hadException();
+ m_parentNode->insertBefore(m_node.get(), m_anchorNode.get(), exceptionState);
+ return !exceptionState.hadException();
}
- virtual bool redo(ExceptionState& es)
+ virtual bool redo(ExceptionState& exceptionState)
{
- m_parentNode->removeChild(m_node.get(), es);
- return !es.hadException();
+ m_parentNode->removeChild(m_node.get(), exceptionState);
+ return !exceptionState.hadException();
}
private:
@@ -91,33 +91,33 @@ public:
{
}
- virtual bool perform(ExceptionState& es)
+ virtual bool perform(ExceptionState& exceptionState)
{
if (m_node->parentNode()) {
m_removeChildAction = adoptPtr(new RemoveChildAction(m_node->parentNode(), m_node.get()));
- if (!m_removeChildAction->perform(es))
+ if (!m_removeChildAction->perform(exceptionState))
return false;
}
- m_parentNode->insertBefore(m_node.get(), m_anchorNode.get(), es);
- return !es.hadException();
+ m_parentNode->insertBefore(m_node.get(), m_anchorNode.get(), exceptionState);
+ return !exceptionState.hadException();
}
- virtual bool undo(ExceptionState& es)
+ virtual bool undo(ExceptionState& exceptionState)
{
- m_parentNode->removeChild(m_node.get(), es);
- if (es.hadException())
+ m_parentNode->removeChild(m_node.get(), exceptionState);
+ if (exceptionState.hadException())
return false;
if (m_removeChildAction)
- return m_removeChildAction->undo(es);
+ return m_removeChildAction->undo(exceptionState);
return true;
}
- virtual bool redo(ExceptionState& es)
+ virtual bool redo(ExceptionState& exceptionState)
{
- if (m_removeChildAction && !m_removeChildAction->redo(es))
+ if (m_removeChildAction && !m_removeChildAction->redo(exceptionState))
return false;
- m_parentNode->insertBefore(m_node.get(), m_anchorNode.get(), es);
- return !es.hadException();
+ m_parentNode->insertBefore(m_node.get(), m_anchorNode.get(), exceptionState);
+ return !exceptionState.hadException();
}
private:
@@ -130,22 +130,22 @@ private:
class DOMEditor::RemoveAttributeAction : public InspectorHistory::Action {
WTF_MAKE_NONCOPYABLE(RemoveAttributeAction);
public:
- RemoveAttributeAction(Element* element, const String& name)
+ RemoveAttributeAction(Element* element, const AtomicString& name)
: InspectorHistory::Action("RemoveAttribute")
, m_element(element)
, m_name(name)
{
}
- virtual bool perform(ExceptionState& es)
+ virtual bool perform(ExceptionState& exceptionState)
{
m_value = m_element->getAttribute(m_name);
- return redo(es);
+ return redo(exceptionState);
}
- virtual bool undo(ExceptionState& es)
+ virtual bool undo(ExceptionState& exceptionState)
{
- m_element->setAttribute(m_name, m_value, es);
+ m_element->setAttribute(m_name, m_value, exceptionState);
return true;
}
@@ -157,14 +157,14 @@ public:
private:
RefPtr<Element> m_element;
- String m_name;
- String m_value;
+ AtomicString m_name;
+ AtomicString m_value;
};
class DOMEditor::SetAttributeAction : public InspectorHistory::Action {
WTF_MAKE_NONCOPYABLE(SetAttributeAction);
public:
- SetAttributeAction(Element* element, const String& name, const String& value)
+ SetAttributeAction(Element* element, const AtomicString& name, const AtomicString& value)
: InspectorHistory::Action("SetAttribute")
, m_element(element)
, m_name(name)
@@ -173,35 +173,35 @@ public:
{
}
- virtual bool perform(ExceptionState& es)
+ virtual bool perform(ExceptionState& exceptionState)
{
m_hadAttribute = m_element->hasAttribute(m_name);
if (m_hadAttribute)
m_oldValue = m_element->getAttribute(m_name);
- return redo(es);
+ return redo(exceptionState);
}
- virtual bool undo(ExceptionState& es)
+ virtual bool undo(ExceptionState& exceptionState)
{
if (m_hadAttribute)
- m_element->setAttribute(m_name, m_oldValue, es);
+ m_element->setAttribute(m_name, m_oldValue, exceptionState);
else
m_element->removeAttribute(m_name);
return true;
}
- virtual bool redo(ExceptionState& es)
+ virtual bool redo(ExceptionState& exceptionState)
{
- m_element->setAttribute(m_name, m_value, es);
+ m_element->setAttribute(m_name, m_value, exceptionState);
return true;
}
private:
RefPtr<Element> m_element;
- String m_name;
- String m_value;
+ AtomicString m_name;
+ AtomicString m_value;
bool m_hadAttribute;
- String m_oldValue;
+ AtomicString m_oldValue;
};
class DOMEditor::SetOuterHTMLAction : public InspectorHistory::Action {
@@ -218,23 +218,23 @@ public:
{
}
- virtual bool perform(ExceptionState& es)
+ virtual bool perform(ExceptionState& exceptionState)
{
m_oldHTML = createMarkup(m_node.get());
ASSERT(m_node->ownerDocument());
DOMPatchSupport domPatchSupport(m_domEditor.get(), *m_node->ownerDocument());
- m_newNode = domPatchSupport.patchNode(m_node.get(), m_html, es);
- return !es.hadException();
+ m_newNode = domPatchSupport.patchNode(m_node.get(), m_html, exceptionState);
+ return !exceptionState.hadException();
}
- virtual bool undo(ExceptionState& es)
+ virtual bool undo(ExceptionState& exceptionState)
{
- return m_history->undo(es);
+ return m_history->undo(exceptionState);
}
- virtual bool redo(ExceptionState& es)
+ virtual bool redo(ExceptionState& exceptionState)
{
- return m_history->redo(es);
+ return m_history->redo(exceptionState);
}
Node* newNode()
@@ -262,10 +262,10 @@ public:
{
}
- virtual bool perform(ExceptionState& es)
+ virtual bool perform(ExceptionState& exceptionState)
{
m_oldText = m_textNode->wholeText();
- return redo(es);
+ return redo(exceptionState);
}
virtual bool undo(ExceptionState&)
@@ -297,21 +297,21 @@ public:
{
}
- virtual bool perform(ExceptionState& es)
+ virtual bool perform(ExceptionState& exceptionState)
{
- return redo(es);
+ return redo(exceptionState);
}
- virtual bool undo(ExceptionState& es)
+ virtual bool undo(ExceptionState& exceptionState)
{
- m_parentNode->replaceChild(m_oldNode, m_newNode.get(), es);
- return !es.hadException();
+ m_parentNode->replaceChild(m_oldNode, m_newNode.get(), exceptionState);
+ return !exceptionState.hadException();
}
- virtual bool redo(ExceptionState& es)
+ virtual bool redo(ExceptionState& exceptionState)
{
- m_parentNode->replaceChild(m_newNode, m_oldNode.get(), es);
- return !es.hadException();
+ m_parentNode->replaceChild(m_newNode, m_oldNode.get(), exceptionState);
+ return !exceptionState.hadException();
}
private:
@@ -358,102 +358,102 @@ DOMEditor::DOMEditor(InspectorHistory* history) : m_history(history) { }
DOMEditor::~DOMEditor() { }
-bool DOMEditor::insertBefore(Node* parentNode, PassRefPtr<Node> node, Node* anchorNode, ExceptionState& es)
+bool DOMEditor::insertBefore(Node* parentNode, PassRefPtr<Node> node, Node* anchorNode, ExceptionState& exceptionState)
{
- return m_history->perform(adoptPtr(new InsertBeforeAction(parentNode, node, anchorNode)), es);
+ return m_history->perform(adoptPtr(new InsertBeforeAction(parentNode, node, anchorNode)), exceptionState);
}
-bool DOMEditor::removeChild(Node* parentNode, Node* node, ExceptionState& es)
+bool DOMEditor::removeChild(Node* parentNode, Node* node, ExceptionState& exceptionState)
{
- return m_history->perform(adoptPtr(new RemoveChildAction(parentNode, node)), es);
+ return m_history->perform(adoptPtr(new RemoveChildAction(parentNode, node)), exceptionState);
}
-bool DOMEditor::setAttribute(Element* element, const String& name, const String& value, ExceptionState& es)
+bool DOMEditor::setAttribute(Element* element, const String& name, const String& value, ExceptionState& exceptionState)
{
- return m_history->perform(adoptPtr(new SetAttributeAction(element, name, value)), es);
+ return m_history->perform(adoptPtr(new SetAttributeAction(element, name, value)), exceptionState);
}
-bool DOMEditor::removeAttribute(Element* element, const String& name, ExceptionState& es)
+bool DOMEditor::removeAttribute(Element* element, const String& name, ExceptionState& exceptionState)
{
- return m_history->perform(adoptPtr(new RemoveAttributeAction(element, name)), es);
+ return m_history->perform(adoptPtr(new RemoveAttributeAction(element, name)), exceptionState);
}
-bool DOMEditor::setOuterHTML(Node* node, const String& html, Node** newNode, ExceptionState& es)
+bool DOMEditor::setOuterHTML(Node* node, const String& html, Node** newNode, ExceptionState& exceptionState)
{
OwnPtr<SetOuterHTMLAction> action = adoptPtr(new SetOuterHTMLAction(node, html));
SetOuterHTMLAction* rawAction = action.get();
- bool result = m_history->perform(action.release(), es);
+ bool result = m_history->perform(action.release(), exceptionState);
if (result)
*newNode = rawAction->newNode();
return result;
}
-bool DOMEditor::replaceWholeText(Text* textNode, const String& text, ExceptionState& es)
+bool DOMEditor::replaceWholeText(Text* textNode, const String& text, ExceptionState& exceptionState)
{
- return m_history->perform(adoptPtr(new ReplaceWholeTextAction(textNode, text)), es);
+ return m_history->perform(adoptPtr(new ReplaceWholeTextAction(textNode, text)), exceptionState);
}
-bool DOMEditor::replaceChild(Node* parentNode, PassRefPtr<Node> newNode, Node* oldNode, ExceptionState& es)
+bool DOMEditor::replaceChild(Node* parentNode, PassRefPtr<Node> newNode, Node* oldNode, ExceptionState& exceptionState)
{
- return m_history->perform(adoptPtr(new ReplaceChildNodeAction(parentNode, newNode, oldNode)), es);
+ return m_history->perform(adoptPtr(new ReplaceChildNodeAction(parentNode, newNode, oldNode)), exceptionState);
}
-bool DOMEditor::setNodeValue(Node* node, const String& value, ExceptionState& es)
+bool DOMEditor::setNodeValue(Node* node, const String& value, ExceptionState& exceptionState)
{
- return m_history->perform(adoptPtr(new SetNodeValueAction(node, value)), es);
+ return m_history->perform(adoptPtr(new SetNodeValueAction(node, value)), exceptionState);
}
-static void populateErrorString(ExceptionState& es, ErrorString* errorString)
+static void populateErrorString(ExceptionState& exceptionState, ErrorString* errorString)
{
- if (es.hadException())
- *errorString = DOMException::getErrorName(es.code());
+ if (exceptionState.hadException())
+ *errorString = DOMException::getErrorName(exceptionState.code());
}
bool DOMEditor::insertBefore(Node* parentNode, PassRefPtr<Node> node, Node* anchorNode, ErrorString* errorString)
{
- TrackExceptionState es;
- bool result = insertBefore(parentNode, node, anchorNode, es);
- populateErrorString(es, errorString);
+ TrackExceptionState exceptionState;
+ bool result = insertBefore(parentNode, node, anchorNode, exceptionState);
+ populateErrorString(exceptionState, errorString);
return result;
}
bool DOMEditor::removeChild(Node* parentNode, Node* node, ErrorString* errorString)
{
- TrackExceptionState es;
- bool result = removeChild(parentNode, node, es);
- populateErrorString(es, errorString);
+ TrackExceptionState exceptionState;
+ bool result = removeChild(parentNode, node, exceptionState);
+ populateErrorString(exceptionState, errorString);
return result;
}
bool DOMEditor::setAttribute(Element* element, const String& name, const String& value, ErrorString* errorString)
{
- TrackExceptionState es;
- bool result = setAttribute(element, name, value, es);
- populateErrorString(es, errorString);
+ TrackExceptionState exceptionState;
+ bool result = setAttribute(element, name, value, exceptionState);
+ populateErrorString(exceptionState, errorString);
return result;
}
bool DOMEditor::removeAttribute(Element* element, const String& name, ErrorString* errorString)
{
- TrackExceptionState es;
- bool result = removeAttribute(element, name, es);
- populateErrorString(es, errorString);
+ TrackExceptionState exceptionState;
+ bool result = removeAttribute(element, name, exceptionState);
+ populateErrorString(exceptionState, errorString);
return result;
}
bool DOMEditor::setOuterHTML(Node* node, const String& html, Node** newNode, ErrorString* errorString)
{
- TrackExceptionState es;
- bool result = setOuterHTML(node, html, newNode, es);
- populateErrorString(es, errorString);
+ TrackExceptionState exceptionState;
+ bool result = setOuterHTML(node, html, newNode, exceptionState);
+ populateErrorString(exceptionState, errorString);
return result;
}
bool DOMEditor::replaceWholeText(Text* textNode, const String& text, ErrorString* errorString)
{
- TrackExceptionState es;
- bool result = replaceWholeText(textNode, text, es);
- populateErrorString(es, errorString);
+ TrackExceptionState exceptionState;
+ bool result = replaceWholeText(textNode, text, exceptionState);
+ populateErrorString(exceptionState, errorString);
return result;
}
diff --git a/chromium/third_party/WebKit/Source/core/inspector/DOMPatchSupport.cpp b/chromium/third_party/WebKit/Source/core/inspector/DOMPatchSupport.cpp
index 5fed80547ac..d5c7cd5dccf 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/DOMPatchSupport.cpp
+++ b/chromium/third_party/WebKit/Source/core/inspector/DOMPatchSupport.cpp
@@ -82,8 +82,6 @@ DOMPatchSupport::DOMPatchSupport(DOMEditor* domEditor, Document& document)
{
}
-DOMPatchSupport::~DOMPatchSupport() { }
-
void DOMPatchSupport::patchDocument(const String& markup)
{
RefPtr<Document> newDocument;
@@ -115,7 +113,7 @@ void DOMPatchSupport::patchDocument(const String& markup)
}
}
-Node* DOMPatchSupport::patchNode(Node* node, const String& markup, ExceptionState& es)
+Node* DOMPatchSupport::patchNode(Node* node, const String& markup, ExceptionState& exceptionState)
{
// Don't parse <html> as a fragment.
if (node->isDocumentNode() || (node->parentNode() && node->parentNode()->isDocumentNode())) {
@@ -138,8 +136,7 @@ Node* DOMPatchSupport::patchNode(Node* node, const String& markup, ExceptionStat
oldList.append(createDigest(child, 0));
// Compose the new list.
- String markupCopy = markup;
- markupCopy.makeLower();
+ String markupCopy = markup.lower();
Vector<OwnPtr<Digest> > newList;
for (Node* child = parentNode->firstChild(); child != node; child = child->nextSibling())
newList.append(createDigest(child, 0));
@@ -153,15 +150,15 @@ Node* DOMPatchSupport::patchNode(Node* node, const String& markup, ExceptionStat
for (Node* child = node->nextSibling(); child; child = child->nextSibling())
newList.append(createDigest(child, 0));
- if (!innerPatchChildren(parentNode, oldList, newList, es)) {
+ if (!innerPatchChildren(parentNode, oldList, newList, exceptionState)) {
// Fall back to total replace.
- if (!m_domEditor->replaceChild(parentNode, fragment.release(), node, es))
+ if (!m_domEditor->replaceChild(parentNode, fragment.release(), node, exceptionState))
return 0;
}
return previousSibling ? previousSibling->nextSibling() : parentNode->firstChild();
}
-bool DOMPatchSupport::innerPatchNode(Digest* oldDigest, Digest* newDigest, ExceptionState& es)
+bool DOMPatchSupport::innerPatchNode(Digest* oldDigest, Digest* newDigest, ExceptionState& exceptionState)
{
if (oldDigest->m_sha1 == newDigest->m_sha1)
return true;
@@ -170,10 +167,10 @@ bool DOMPatchSupport::innerPatchNode(Digest* oldDigest, Digest* newDigest, Excep
Node* newNode = newDigest->m_node;
if (newNode->nodeType() != oldNode->nodeType() || newNode->nodeName() != oldNode->nodeName())
- return m_domEditor->replaceChild(oldNode->parentNode(), newNode, oldNode, es);
+ return m_domEditor->replaceChild(oldNode->parentNode(), newNode, oldNode, exceptionState);
if (oldNode->nodeValue() != newNode->nodeValue()) {
- if (!m_domEditor->setNodeValue(oldNode, newNode->nodeValue(), es))
+ if (!m_domEditor->setNodeValue(oldNode, newNode->nodeValue(), exceptionState))
return false;
}
@@ -188,7 +185,7 @@ bool DOMPatchSupport::innerPatchNode(Digest* oldDigest, Digest* newDigest, Excep
if (oldElement->hasAttributesWithoutUpdate()) {
while (oldElement->attributeCount()) {
const Attribute* attribute = oldElement->attributeItem(0);
- if (!m_domEditor->removeAttribute(oldElement, attribute->localName(), es))
+ if (!m_domEditor->removeAttribute(oldElement, attribute->localName(), exceptionState))
return false;
}
}
@@ -198,13 +195,13 @@ bool DOMPatchSupport::innerPatchNode(Digest* oldDigest, Digest* newDigest, Excep
size_t numAttrs = newElement->attributeCount();
for (size_t i = 0; i < numAttrs; ++i) {
const Attribute* attribute = newElement->attributeItem(i);
- if (!m_domEditor->setAttribute(oldElement, attribute->name().localName(), attribute->value(), es))
+ if (!m_domEditor->setAttribute(oldElement, attribute->name().localName(), attribute->value(), exceptionState))
return false;
}
}
}
- bool result = innerPatchChildren(oldElement, oldDigest->m_children, newDigest->m_children, es);
+ bool result = innerPatchChildren(oldElement, oldDigest->m_children, newDigest->m_children, exceptionState);
m_unusedNodesMap.remove(newDigest->m_sha1);
return result;
}
@@ -297,7 +294,7 @@ DOMPatchSupport::diff(const Vector<OwnPtr<Digest> >& oldList, const Vector<OwnPt
return make_pair(oldMap, newMap);
}
-bool DOMPatchSupport::innerPatchChildren(ContainerNode* parentNode, const Vector<OwnPtr<Digest> >& oldList, const Vector<OwnPtr<Digest> >& newList, ExceptionState& es)
+bool DOMPatchSupport::innerPatchChildren(ContainerNode* parentNode, const Vector<OwnPtr<Digest> >& oldList, const Vector<OwnPtr<Digest> >& newList, ExceptionState& exceptionState)
{
pair<ResultMap, ResultMap> resultMaps = diff(oldList, newList);
ResultMap& oldMap = resultMaps.first;
@@ -335,11 +332,11 @@ bool DOMPatchSupport::innerPatchChildren(ContainerNode* parentNode, const Vector
if (anchorAfter - anchorCandidate == 1 && anchorCandidate < newList.size())
merges.set(newList[anchorCandidate].get(), oldList[i].get());
else {
- if (!removeChildAndMoveToNew(oldList[i].get(), es))
+ if (!removeChildAndMoveToNew(oldList[i].get(), exceptionState))
return false;
}
} else {
- if (!removeChildAndMoveToNew(oldList[i].get(), es))
+ if (!removeChildAndMoveToNew(oldList[i].get(), exceptionState))
return false;
}
}
@@ -372,7 +369,7 @@ bool DOMPatchSupport::innerPatchChildren(ContainerNode* parentNode, const Vector
// 2. Patch nodes marked for merge.
for (HashMap<Digest*, Digest*>::iterator it = merges.begin(); it != merges.end(); ++it) {
- if (!innerPatchNode(it->value, it->key, es))
+ if (!innerPatchNode(it->value, it->key, exceptionState))
return false;
}
@@ -380,7 +377,7 @@ bool DOMPatchSupport::innerPatchChildren(ContainerNode* parentNode, const Vector
for (size_t i = 0; i < newMap.size(); ++i) {
if (newMap[i].first || merges.contains(newList[i].get()))
continue;
- if (!insertBeforeAndMarkAsUsed(parentNode, newList[i].get(), parentNode->childNode(i), es))
+ if (!insertBeforeAndMarkAsUsed(parentNode, newList[i].get(), parentNode->childNode(i), exceptionState))
return false;
}
@@ -395,7 +392,7 @@ bool DOMPatchSupport::innerPatchChildren(ContainerNode* parentNode, const Vector
if (node->hasTagName(bodyTag) || node->hasTagName(headTag))
continue; // Never move head or body, move the rest of the nodes around them.
- if (!m_domEditor->insertBefore(parentNode, node.release(), anchorNode, es))
+ if (!m_domEditor->insertBefore(parentNode, node.release(), anchorNode, exceptionState))
return false;
}
return true;
@@ -451,17 +448,17 @@ PassOwnPtr<DOMPatchSupport::Digest> DOMPatchSupport::createDigest(Node* node, Un
return adoptPtr(digest);
}
-bool DOMPatchSupport::insertBeforeAndMarkAsUsed(ContainerNode* parentNode, Digest* digest, Node* anchor, ExceptionState& es)
+bool DOMPatchSupport::insertBeforeAndMarkAsUsed(ContainerNode* parentNode, Digest* digest, Node* anchor, ExceptionState& exceptionState)
{
- bool result = m_domEditor->insertBefore(parentNode, digest->m_node, anchor, es);
+ bool result = m_domEditor->insertBefore(parentNode, digest->m_node, anchor, exceptionState);
markNodeAsUsed(digest);
return result;
}
-bool DOMPatchSupport::removeChildAndMoveToNew(Digest* oldDigest, ExceptionState& es)
+bool DOMPatchSupport::removeChildAndMoveToNew(Digest* oldDigest, ExceptionState& exceptionState)
{
RefPtr<Node> oldNode = oldDigest->m_node;
- if (!m_domEditor->removeChild(oldNode->parentNode(), oldNode.get(), es))
+ if (!m_domEditor->removeChild(oldNode->parentNode(), oldNode.get(), exceptionState))
return false;
// Diff works within levels. In order not to lose the node identity when user
@@ -473,7 +470,7 @@ bool DOMPatchSupport::removeChildAndMoveToNew(Digest* oldDigest, ExceptionState&
if (it != m_unusedNodesMap.end()) {
Digest* newDigest = it->value;
Node* newNode = newDigest->m_node;
- if (!m_domEditor->replaceChild(newNode->parentNode(), oldNode, newNode, es))
+ if (!m_domEditor->replaceChild(newNode->parentNode(), oldNode, newNode, exceptionState))
return false;
newDigest->m_node = oldNode.get();
markNodeAsUsed(newDigest);
@@ -481,7 +478,7 @@ bool DOMPatchSupport::removeChildAndMoveToNew(Digest* oldDigest, ExceptionState&
}
for (size_t i = 0; i < oldDigest->m_children.size(); ++i) {
- if (!removeChildAndMoveToNew(oldDigest->m_children[i].get(), es))
+ if (!removeChildAndMoveToNew(oldDigest->m_children[i].get(), exceptionState))
return false;
}
return true;
diff --git a/chromium/third_party/WebKit/Source/core/inspector/DOMPatchSupport.h b/chromium/third_party/WebKit/Source/core/inspector/DOMPatchSupport.h
index 4462fb58f5d..3aa775135b7 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/DOMPatchSupport.h
+++ b/chromium/third_party/WebKit/Source/core/inspector/DOMPatchSupport.h
@@ -45,13 +45,12 @@ class Document;
class ExceptionState;
class Node;
-class DOMPatchSupport {
+class DOMPatchSupport FINAL {
WTF_MAKE_NONCOPYABLE(DOMPatchSupport);
public:
static void patchDocument(Document&, const String& markup);
DOMPatchSupport(DOMEditor*, Document&);
- virtual ~DOMPatchSupport();
void patchDocument(const String& markup);
Node* patchNode(Node*, const String& markup, ExceptionState&);
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InjectedScript.cpp b/chromium/third_party/WebKit/Source/core/inspector/InjectedScript.cpp
index 52f3e09f9da..9d46e69bdf5 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InjectedScript.cpp
+++ b/chromium/third_party/WebKit/Source/core/inspector/InjectedScript.cpp
@@ -35,7 +35,7 @@
#include "bindings/v8/ScriptFunctionCall.h"
#include "core/inspector/InjectedScriptHost.h"
-#include "core/platform/JSONValues.h"
+#include "platform/JSONValues.h"
#include "wtf/text/WTFString.h"
using WebCore::TypeBuilder::Array;
@@ -296,6 +296,21 @@ ScriptValue InjectedScript::findObjectById(const String& objectId) const
return resultValue;
}
+ScriptValue InjectedScript::findCallFrameById(ErrorString* errorString, const ScriptValue& topCallFrame, const String& callFrameId)
+{
+ ScriptFunctionCall function(injectedScriptObject(), "callFrameForId");
+ function.appendArgument(topCallFrame);
+ function.appendArgument(callFrameId);
+ bool hadException = false;
+ ScriptValue resultValue = callFunctionWithEvalEnabled(function, hadException);
+ ASSERT(!hadException);
+ if (hadException || resultValue.hasNoValue() || !resultValue.isObject()) {
+ *errorString = "Internal error";
+ return ScriptValue();
+ }
+ return resultValue;
+}
+
void InjectedScript::inspectNode(Node* node)
{
ASSERT(!hasNoValue());
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InjectedScript.h b/chromium/third_party/WebKit/Source/core/inspector/InjectedScript.h
index 207f5aea425..05cfcf320fb 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InjectedScript.h
+++ b/chromium/third_party/WebKit/Source/core/inspector/InjectedScript.h
@@ -91,6 +91,7 @@ public:
PassRefPtr<TypeBuilder::Runtime::RemoteObject> wrapTable(const ScriptValue& table, const ScriptValue& columns) const;
PassRefPtr<TypeBuilder::Runtime::RemoteObject> wrapNode(Node*, const String& groupName);
ScriptValue findObjectById(const String& objectId) const;
+ ScriptValue findCallFrameById(ErrorString*, const ScriptValue& topCallFrame, const String& callFrameId);
void inspectNode(Node*);
void releaseObjectGroup(const String&);
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InjectedScriptBase.cpp b/chromium/third_party/WebKit/Source/core/inspector/InjectedScriptBase.cpp
index 2f246a829d9..574ce40ec6e 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InjectedScriptBase.cpp
+++ b/chromium/third_party/WebKit/Source/core/inspector/InjectedScriptBase.cpp
@@ -34,8 +34,9 @@
#include "core/inspector/InjectedScriptBase.h"
#include "bindings/v8/ScriptFunctionCall.h"
+#include "bindings/v8/ScriptState.h"
#include "core/inspector/InspectorInstrumentation.h"
-#include "core/platform/JSONValues.h"
+#include "platform/JSONValues.h"
#include "wtf/text/WTFString.h"
using WebCore::TypeBuilder::Runtime::RemoteObject;
@@ -73,8 +74,8 @@ const ScriptObject& InjectedScriptBase::injectedScriptObject() const
ScriptValue InjectedScriptBase::callFunctionWithEvalEnabled(ScriptFunctionCall& function, bool& hadException) const
{
- ScriptExecutionContext* scriptExecutionContext = m_injectedScriptObject.scriptState()->scriptExecutionContext();
- InspectorInstrumentationCookie cookie = InspectorInstrumentation::willCallFunction(scriptExecutionContext, name(), 1);
+ ExecutionContext* executionContext = m_injectedScriptObject.scriptState()->executionContext();
+ InspectorInstrumentationCookie cookie = InspectorInstrumentation::willCallFunction(executionContext, name(), 1);
ScriptState* scriptState = m_injectedScriptObject.scriptState();
bool evalIsDisabled = false;
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InjectedScriptCanvasModuleSource.js b/chromium/third_party/WebKit/Source/core/inspector/InjectedScriptCanvasModuleSource.js
index 00d50cf82c8..c82ab2352ec 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InjectedScriptCanvasModuleSource.js
+++ b/chromium/third_party/WebKit/Source/core/inspector/InjectedScriptCanvasModuleSource.js
@@ -118,6 +118,14 @@ var TypeUtils = {
return result;
}
+ // Try to convert to a primitive value via valueOf().
+ if (typeof obj.valueOf === "function") {
+ var value = obj.valueOf();
+ var valueType = typeof value;
+ if (valueType !== "object" && valueType !== "function")
+ return value;
+ }
+
console.error("ASSERT_NOT_REACHED: failed to clone object: ", obj);
return obj;
},
@@ -260,8 +268,8 @@ function StackTraceV8(stackTraceLimit, topMostFunctionToIgnore)
/**
* @param {Object} error
- * @param {Array.<CallSite>} structuredStackTrace
- * @return {Array.<{sourceURL: string, lineNumber: number, columnNumber: number}>}
+ * @param {!Array.<CallSite>} structuredStackTrace
+ * @return {!Array.<{sourceURL: string, lineNumber: number, columnNumber: number}>}
*/
Error.prepareStackTrace = function(error, structuredStackTrace)
{
@@ -274,7 +282,7 @@ function StackTraceV8(stackTraceLimit, topMostFunctionToIgnore)
});
}
- var holder = /** @type {{stack: Array.<{sourceURL: string, lineNumber: number, columnNumber: number}>}} */ ({});
+ var holder = /** @type {{stack: !Array.<{sourceURL: string, lineNumber: number, columnNumber: number}>}} */ ({});
Error.captureStackTrace(holder, topMostFunctionToIgnore || arguments.callee);
this._stackTrace = holder.stack;
@@ -356,7 +364,7 @@ Cache.prototype = {
* @constructor
* @param {Resource|Object} thisObject
* @param {string} functionName
- * @param {Array|Arguments} args
+ * @param {!Array|Arguments} args
* @param {Resource|*=} result
* @param {StackTrace=} stackTrace
*/
@@ -531,11 +539,6 @@ Call.prototype = {
var attachments = replayableCall.attachments();
if (attachments)
this._attachments = TypeUtils.cloneObject(attachments);
-
- var thisResource = Resource.forObject(replayObject);
- if (thisResource)
- thisResource.onCallReplayed(this);
-
return this;
}
}
@@ -544,7 +547,7 @@ Call.prototype = {
* @constructor
* @param {ReplayableResource} thisObject
* @param {string} functionName
- * @param {Array.<ReplayableResource|*>} args
+ * @param {!Array.<ReplayableResource|*>} args
* @param {ReplayableResource|*} result
* @param {StackTrace} stackTrace
* @param {Object.<string, Object>} attachments
@@ -604,7 +607,7 @@ ReplayableCall.prototype = {
},
/**
- * @return {Array.<ReplayableResource|*>}
+ * @return {!Array.<ReplayableResource|*>}
*/
args: function()
{
@@ -979,7 +982,7 @@ Resource.prototype = {
var proxy = Object.create(wrappedObject.__proto__); // In order to emulate "instanceof".
var customWrapFunctions = this._customWrapFunctions();
- /** @type {Array.<string>} */
+ /** @type {!Array.<string>} */
this._proxyStatePropertyNames = [];
/**
@@ -1112,7 +1115,7 @@ Resource.prototype = {
* @param {Object} originalObject
* @param {Function} originalFunction
* @param {string} functionName
- * @param {Array|Arguments} args
+ * @param {!Array|Arguments} args
*/
Resource.WrapFunction = function(originalObject, originalFunction, functionName, args)
{
@@ -2750,6 +2753,7 @@ WebGLRenderingContextResource.prototype = {
var gl = this.wrappedObject();
var bindingParameter;
var bindMethodName;
+ target = +target; // Explicitly convert to a number.
var bindMethodTarget = target;
switch (target) {
case gl.ARRAY_BUFFER:
@@ -2835,36 +2839,6 @@ WebGLRenderingContextResource.prototype = {
wrapFunctions["createRenderbuffer"] = Resource.WrapFunction.resourceFactoryMethod(WebGLRenderbufferResource, "WebGLRenderbuffer");
wrapFunctions["getUniformLocation"] = Resource.WrapFunction.resourceFactoryMethod(WebGLUniformLocationResource, "WebGLUniformLocation");
- /**
- * @param {string} methodName
- * @param {function(this:Resource, !Call)=} pushCallFunc
- */
- function stateModifyingWrapFunction(methodName, pushCallFunc)
- {
- if (pushCallFunc) {
- /**
- * @param {Object|number} target
- * @this Resource.WrapFunction
- */
- wrapFunctions[methodName] = function(target)
- {
- var resource = this._resource.currentBinding(target);
- if (resource)
- pushCallFunc.call(resource, this.call());
- }
- } else {
- /**
- * @param {Object|number} target
- * @this Resource.WrapFunction
- */
- wrapFunctions[methodName] = function(target)
- {
- var resource = this._resource.currentBinding(target);
- if (resource)
- resource.pushCall(this.call());
- }
- }
- }
stateModifyingWrapFunction("bindAttribLocation");
stateModifyingWrapFunction("compileShader");
stateModifyingWrapFunction("detachShader");
@@ -2984,6 +2958,38 @@ WebGLRenderingContextResource.prototype = {
WebGLRenderingContextResource._wrapFunctions = wrapFunctions;
}
+
+ /**
+ * @param {string} methodName
+ * @param {function(this:Resource, !Call)=} pushCallFunc
+ */
+ function stateModifyingWrapFunction(methodName, pushCallFunc)
+ {
+ if (pushCallFunc) {
+ /**
+ * @param {Object|number} target
+ * @this Resource.WrapFunction
+ */
+ wrapFunctions[methodName] = function(target)
+ {
+ var resource = this._resource.currentBinding(target);
+ if (resource)
+ pushCallFunc.call(resource, this.call());
+ }
+ } else {
+ /**
+ * @param {Object|number} target
+ * @this Resource.WrapFunction
+ */
+ wrapFunctions[methodName] = function(target)
+ {
+ var resource = this._resource.currentBinding(target);
+ if (resource)
+ resource.pushCall(this.call());
+ }
+ }
+ }
+
return wrapFunctions;
},
@@ -3378,27 +3384,6 @@ CanvasRenderingContext2DResource.prototype = {
wrapFunctions["createRadialGradient"] = Resource.WrapFunction.resourceFactoryMethod(LogEverythingResource, "CanvasGradient");
wrapFunctions["createPattern"] = Resource.WrapFunction.resourceFactoryMethod(LogEverythingResource, "CanvasPattern");
- /**
- * @param {string} methodName
- * @param {function(this:Resource, !Call)=} func
- */
- function stateModifyingWrapFunction(methodName, func)
- {
- if (func) {
- /** @this Resource.WrapFunction */
- wrapFunctions[methodName] = function()
- {
- func.call(this._resource, this.call());
- }
- } else {
- /** @this Resource.WrapFunction */
- wrapFunctions[methodName] = function()
- {
- this._resource.pushCall(this.call());
- }
- }
- }
-
for (var i = 0, methodName; methodName = CanvasRenderingContext2DResource.TransformationMatrixMethods[i]; ++i)
stateModifyingWrapFunction(methodName, methodName === "setTransform" ? this.pushCall_setTransform : undefined);
for (var i = 0, methodName; methodName = CanvasRenderingContext2DResource.PathMethods[i]; ++i)
@@ -3410,6 +3395,28 @@ CanvasRenderingContext2DResource.prototype = {
CanvasRenderingContext2DResource._wrapFunctions = wrapFunctions;
}
+
+ /**
+ * @param {string} methodName
+ * @param {function(this:Resource, !Call)=} func
+ */
+ function stateModifyingWrapFunction(methodName, func)
+ {
+ if (func) {
+ /** @this Resource.WrapFunction */
+ wrapFunctions[methodName] = function()
+ {
+ func.call(this._resource, this.call());
+ }
+ } else {
+ /** @this Resource.WrapFunction */
+ wrapFunctions[methodName] = function()
+ {
+ this._resource.pushCall(this.call());
+ }
+ }
+ }
+
return wrapFunctions;
},
@@ -3897,12 +3904,14 @@ CallFormatter.register("WebGLRenderingContext", new WebGLCallFormatter(WebGLRend
*/
function TraceLog()
{
- /** @type {!Array.<ReplayableCall>} */
+ /** @type {!Array.<!ReplayableCall>} */
this._replayableCalls = [];
/** @type {!Cache.<ReplayableResource>} */
this._replayablesCache = new Cache();
/** @type {!Object.<number, boolean>} */
this._frameEndCallIndexes = {};
+ /** @type {!Object.<number, boolean>} */
+ this._resourcesCreatedInThisTraceLog = {};
}
TraceLog.prototype = {
@@ -3915,7 +3924,7 @@ TraceLog.prototype = {
},
/**
- * @return {!Array.<ReplayableCall>}
+ * @return {!Array.<!ReplayableCall>}
*/
replayableCalls: function()
{
@@ -3932,6 +3941,15 @@ TraceLog.prototype = {
},
/**
+ * @param {number} resourceId
+ * @return {boolean}
+ */
+ createdInThisTraceLog: function(resourceId)
+ {
+ return !!this._resourcesCreatedInThisTraceLog[resourceId];
+ },
+
+ /**
* @param {!Resource} resource
*/
captureResource: function(resource)
@@ -3944,6 +3962,9 @@ TraceLog.prototype = {
*/
addCall: function(call)
{
+ var resource = Resource.forObject(call.result());
+ if (resource && !this._replayablesCache.has(resource.id()))
+ this._resourcesCreatedInThisTraceLog[resource.id()] = true;
this._replayableCalls.push(call.toReplayable(this._replayablesCache));
},
@@ -4011,16 +4032,8 @@ TraceLogPlayer.prototype = {
},
/**
- * @return {Call}
- */
- step: function()
- {
- return this.stepTo(this._nextReplayStep);
- },
-
- /**
* @param {number} stepNum
- * @return {Call}
+ * @return {{replayTime:number, lastCall:(!Call)}}
*/
stepTo: function(stepNum)
{
@@ -4028,20 +4041,50 @@ TraceLogPlayer.prototype = {
console.assert(stepNum >= 0);
if (this._nextReplayStep > stepNum)
this.reset();
- // FIXME: Replay all the cached resources first to warm-up.
- var lastCall = null;
+
+ // Replay the calls' arguments first to warm-up, before measuring the actual replay time.
+ this._replayCallArguments(stepNum);
+
var replayableCalls = this._traceLog.replayableCalls();
- while (this._nextReplayStep <= stepNum)
- lastCall = replayableCalls[this._nextReplayStep++].replay(this._replayWorldCache);
- return lastCall;
+ var replayedCalls = [];
+ replayedCalls.length = stepNum - this._nextReplayStep + 1;
+
+ var beforeTime = TypeUtils.now();
+ for (var i = 0; this._nextReplayStep <= stepNum; ++this._nextReplayStep, ++i)
+ replayedCalls[i] = replayableCalls[this._nextReplayStep].replay(this._replayWorldCache);
+ var replayTime = Math.max(0, TypeUtils.now() - beforeTime);
+
+ for (var i = 0, call; call = replayedCalls[i]; ++i)
+ call.resource().onCallReplayed(call);
+
+ return {
+ replayTime: replayTime,
+ lastCall: replayedCalls[replayedCalls.length - 1]
+ };
},
/**
- * @return {Call}
+ * @param {number} stepNum
*/
- replay: function()
+ _replayCallArguments: function(stepNum)
{
- return this.stepTo(this._traceLog.size() - 1);
+ /**
+ * @param {*} obj
+ */
+ function replayIfNotCreatedInThisTraceLog(obj)
+ {
+ if (!(obj instanceof ReplayableResource))
+ return;
+ var replayableResource = /** @type {!ReplayableResource} */ (obj);
+ if (!this._traceLog.createdInThisTraceLog(replayableResource.id()))
+ replayableResource.replay(this._replayWorldCache)
+ }
+ var replayableCalls = this._traceLog.replayableCalls();
+ for (var i = this._nextReplayStep; i <= stepNum; ++i) {
+ replayIfNotCreatedInThisTraceLog.call(this, replayableCalls[i].replayableResource());
+ replayIfNotCreatedInThisTraceLog.call(this, replayableCalls[i].result());
+ replayableCalls[i].args().forEach(replayIfNotCreatedInThisTraceLog.bind(this));
+ }
}
}
@@ -4283,9 +4326,9 @@ InjectedCanvasModule.prototype = {
var alive = this._manager.capturing() && this._manager.lastTraceLog() === traceLog;
var result = {
id: id,
- /** @type {Array.<CanvasAgent.Call>} */
+ /** @type {!Array.<!CanvasAgent.Call>} */
calls: [],
- /** @type {Array.<CanvasAgent.CallArgument>} */
+ /** @type {!Array.<!CanvasAgent.CallArgument>} */
contexts: [],
alive: alive,
startOffset: fromIndex,
@@ -4325,14 +4368,10 @@ InjectedCanvasModule.prototype = {
if (!traceLog)
return "Error: Trace log with the given ID not found.";
this._traceLogPlayers[traceLogId] = this._traceLogPlayers[traceLogId] || new TraceLogPlayer(traceLog);
-
injectedScript.releaseObjectGroup(traceLogId);
- var beforeTime = TypeUtils.now();
- var lastCall = this._traceLogPlayers[traceLogId].stepTo(stepNo);
- var replayTime = Math.max(0, TypeUtils.now() - beforeTime);
-
- var resource = lastCall.resource();
+ var replayResult = this._traceLogPlayers[traceLogId].stepTo(stepNo);
+ var resource = replayResult.lastCall.resource();
var dataURL = resource.toDataURL();
if (!dataURL) {
resource = resource.contextResource();
@@ -4340,7 +4379,7 @@ InjectedCanvasModule.prototype = {
}
return {
resourceState: this._makeResourceState(resource.id(), traceLogId, resource, dataURL),
- replayTime: replayTime
+ replayTime: replayResult.replayTime
};
},
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InjectedScriptExterns.js b/chromium/third_party/WebKit/Source/core/inspector/InjectedScriptExterns.js
index 513bff45f81..b7d83a2a2d2 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InjectedScriptExterns.js
+++ b/chromium/third_party/WebKit/Source/core/inspector/InjectedScriptExterns.js
@@ -28,13 +28,6 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-// WebKit Web Facing API
-var console = { }
-/** @param {...*} vararg */
-console.log = function(vararg) { }
-/** @param {...*} vararg */
-console.table = function(vararg) { }
-
/**
* @constructor
*/
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InjectedScriptHost.cpp b/chromium/third_party/WebKit/Source/core/inspector/InjectedScriptHost.cpp
index 5f06de17992..8354958f1ce 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InjectedScriptHost.cpp
+++ b/chromium/third_party/WebKit/Source/core/inspector/InjectedScriptHost.cpp
@@ -38,7 +38,7 @@
#include "core/inspector/InspectorDatabaseAgent.h"
#include "core/inspector/InspectorDebuggerAgent.h"
#include "core/inspector/InstrumentingAgents.h"
-#include "core/platform/JSONValues.h"
+#include "platform/JSONValues.h"
#include "wtf/RefPtr.h"
#include "wtf/text/StringBuilder.h"
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InjectedScriptManager.cpp b/chromium/third_party/WebKit/Source/core/inspector/InjectedScriptManager.cpp
index d7cec010cf9..e425ee1b4f4 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InjectedScriptManager.cpp
+++ b/chromium/third_party/WebKit/Source/core/inspector/InjectedScriptManager.cpp
@@ -36,7 +36,7 @@
#include "core/inspector/InjectedScript.h"
#include "core/inspector/InjectedScriptHost.h"
#include "core/inspector/JSONParser.h"
-#include "core/platform/JSONValues.h"
+#include "platform/JSONValues.h"
#include "wtf/PassOwnPtr.h"
namespace WebCore {
@@ -149,8 +149,13 @@ bool InjectedScriptManager::canAccessInspectedWorkerGlobalScope(ScriptState*)
void InjectedScriptManager::releaseObjectGroup(const String& objectGroup)
{
- for (IdToInjectedScriptMap::iterator it = m_idToInjectedScript.begin(); it != m_idToInjectedScript.end(); ++it)
- it->value.releaseObjectGroup(objectGroup);
+ Vector<int> keys;
+ keys.appendRange(m_idToInjectedScript.keys().begin(), m_idToInjectedScript.keys().end());
+ for (Vector<int>::iterator k = keys.begin(); k != keys.end(); ++k) {
+ IdToInjectedScriptMap::iterator s = m_idToInjectedScript.find(*k);
+ if (s != m_idToInjectedScript.end())
+ s->value.releaseObjectGroup(objectGroup); // m_idToInjectedScript may change here.
+ }
}
String InjectedScriptManager::injectedScriptSource()
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InjectedScriptManager.h b/chromium/third_party/WebKit/Source/core/inspector/InjectedScriptManager.h
index e513651d8f6..83c5d2fb45f 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InjectedScriptManager.h
+++ b/chromium/third_party/WebKit/Source/core/inspector/InjectedScriptManager.h
@@ -64,7 +64,8 @@ public:
typedef bool (*InspectedStateAccessCheck)(ScriptState*);
InspectedStateAccessCheck inspectedStateAccessCheck() const { return m_inspectedStateAccessCheck; }
- static void makeWeakCallback(v8::Isolate*, v8::Persistent<v8::Object>*, InjectedScriptHost*);
+ struct CallbackData;
+ static void setWeakCallback(const v8::WeakCallbackData<v8::Object, CallbackData>&);
private:
explicit InjectedScriptManager(InspectedStateAccessCheck);
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InjectedScriptSource.js b/chromium/third_party/WebKit/Source/core/inspector/InjectedScriptSource.js
index 59eac83218d..64c39f7c558 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InjectedScriptSource.js
+++ b/chromium/third_party/WebKit/Source/core/inspector/InjectedScriptSource.js
@@ -54,6 +54,27 @@ function slice(array, index)
}
/**
+ * @param {*} obj
+ * @return {string}
+ */
+function toString(obj)
+{
+ // We don't use String(obj) because it could be overriden.
+ return "" + obj;
+}
+
+/**
+ * @param {*} obj
+ * @return {string}
+ */
+function toStringDescription(obj)
+{
+ if (typeof obj === "number" && obj === 0 && 1 / obj < 0)
+ return "-0"; // Negative zero.
+ return "" + obj;
+}
+
+/**
* Please use this bind, not the one from Function.prototype
* @param {function(...)} func
* @param {Object} thisObject
@@ -140,7 +161,7 @@ InjectedScript.prototype = {
if (this.isPrimitiveValue(object))
result.value = object;
else
- result.description = this._toString(object);
+ result.description = toString(object);
return /** @type {!RuntimeAgent.RemoteObject} */ (result);
},
@@ -160,7 +181,7 @@ InjectedScript.prototype = {
if (InjectedScriptHost.type(columns) == "array") {
columnNames = [];
for (var i = 0; i < columns.length; ++i)
- columnNames.push(String(columns[i]));
+ columnNames.push(toString(columns[i]));
}
return this._wrapObject(table, "console", false, true, columnNames, true);
},
@@ -340,7 +361,7 @@ InjectedScript.prototype = {
value: this._wrapObject(property.value, objectGroupName)
};
descriptors.push(descriptor);
- }
+ }
}
return descriptors;
},
@@ -388,17 +409,21 @@ InjectedScript.prototype = {
/**
* @param {Object} object
- * @param {boolean} ownProperties
- * @param {boolean} accessorPropertiesOnly
+ * @param {boolean=} ownProperties
+ * @param {boolean=} accessorPropertiesOnly
* @return {Array.<Object>}
*/
_propertyDescriptors: function(object, ownProperties, accessorPropertiesOnly)
{
var descriptors = [];
- var nameProcessed = {};
- nameProcessed["__proto__"] = null;
- for (var o = object; this._isDefined(o); o = o.__proto__) {
- var names = Object.getOwnPropertyNames(/** @type {!Object} */ (o));
+ var nameProcessed = { __proto__: null };
+
+ /**
+ * @param {Object} o
+ * @param {Array.<string>} names
+ */
+ function process(o, names)
+ {
for (var i = 0; i < names.length; ++i) {
var name = names[i];
if (nameProcessed[name])
@@ -416,7 +441,7 @@ InjectedScript.prototype = {
continue;
try {
descriptor = { name: name, value: o[name], writable: false, configurable: false, enumerable: false};
- if (o === object)
+ if (o === object)
descriptor.isOwn = true;
descriptors.push(descriptor);
} catch (e) {
@@ -433,16 +458,24 @@ InjectedScript.prototype = {
}
descriptor.name = name;
- if (o === object)
+ if (o === object)
descriptor.isOwn = true;
descriptors.push(descriptor);
}
+ }
+
+ for (var o = object; this._isDefined(o); o = o.__proto__) {
+ // First call Object.keys() to enforce ordering of the property descriptors.
+ process(o, Object.keys(/** @type {!Object} */ (o)));
+ process(o, Object.getOwnPropertyNames(/** @type {!Object} */ (o)));
+
if (ownProperties) {
if (object.__proto__ && !accessorPropertiesOnly)
descriptors.push({ name: "__proto__", value: object.__proto__, writable: true, configurable: true, enumerable: false, isOwn: true});
break;
}
}
+
return descriptors;
},
@@ -480,7 +513,7 @@ InjectedScript.prototype = {
try {
resolvedCallArgument = this._resolveCallArgument(args[i]);
} catch (e) {
- return String(e);
+ return toString(e);
}
resolvedArgs.push(resolvedCallArgument)
}
@@ -498,7 +531,7 @@ InjectedScript.prototype = {
return this._createThrownValue(e, objectGroup);
}
},
-
+
/**
* Resolves a value from CallArgument description.
* @param {RuntimeAgent.CallArgument} callArgumentJson
@@ -517,10 +550,10 @@ InjectedScript.prototype = {
throw "Could not find object with given id";
return resolvedArg;
- } else if ("value" in callArgumentJson)
+ } else if ("value" in callArgumentJson) {
return callArgumentJson.value;
- else
- return undefined;
+ }
+ return undefined;
},
/**
@@ -552,10 +585,9 @@ InjectedScript.prototype = {
{
var remoteObject = this._wrapObject(value, objectGroup);
try {
- remoteObject.description = this._toString(value);
+ remoteObject.description = toStringDescription(value);
} catch (e) {}
- return { wasThrown: true,
- result: remoteObject };
+ return { wasThrown: true, result: remoteObject };
},
/**
@@ -590,7 +622,7 @@ InjectedScript.prototype = {
/**
* @param {Object} callFrame
- * @return {Array.<InjectedScript.CallFrameProxy>|boolean}
+ * @return {!Array.<InjectedScript.CallFrameProxy>|boolean}
*/
wrapCallFrames: function(callFrame)
{
@@ -618,7 +650,7 @@ InjectedScript.prototype = {
*/
evaluateOnCallFrame: function(topCallFrame, callFrameId, expression, objectGroup, injectCommandLineAPI, returnByValue, generatePreview)
{
- var callFrame = this._callFrameForId(topCallFrame, callFrameId);
+ var callFrame = this.callFrameForId(topCallFrame, callFrameId);
if (!callFrame)
return "Could not find call frame with given id";
return this._evaluateAndWrap(callFrame.evaluate, callFrame, expression, objectGroup, true, injectCommandLineAPI, returnByValue, generatePreview);
@@ -631,12 +663,12 @@ InjectedScript.prototype = {
*/
restartFrame: function(topCallFrame, callFrameId)
{
- var callFrame = this._callFrameForId(topCallFrame, callFrameId);
+ var callFrame = this.callFrameForId(topCallFrame, callFrameId);
if (!callFrame)
return "Could not find call frame with given id";
var result = callFrame.restart();
if (result === false)
- result = "Restart frame is not supported";
+ result = "Restart frame is not supported";
return result;
},
@@ -647,7 +679,7 @@ InjectedScript.prototype = {
*/
getStepInPositions: function(topCallFrame, callFrameId)
{
- var callFrame = this._callFrameForId(topCallFrame, callFrameId);
+ var callFrame = this.callFrameForId(topCallFrame, callFrameId);
if (!callFrame)
return "Could not find call frame with given id";
var stepInPositionsUnpacked = JSON.parse(callFrame.stepInPositions);
@@ -663,23 +695,23 @@ InjectedScript.prototype = {
* @param {string|boolean} functionObjectId or false
* @param {number} scopeNumber
* @param {string} variableName
- * @param {string} newValueJsonString RuntimeAgent.CallArgument structure serialized as string
- * @return {string|undefined} undefined if success or an error message
+ * @param {string} newValueJsonString RuntimeAgent.CallArgument structure serialized as string
+ * @return {string|undefined} undefined if success or an error message
*/
setVariableValue: function(topCallFrame, callFrameId, functionObjectId, scopeNumber, variableName, newValueJsonString)
- {
+ {
var setter;
if (typeof callFrameId === "string") {
- var callFrame = this._callFrameForId(topCallFrame, callFrameId);
+ var callFrame = this.callFrameForId(topCallFrame, callFrameId);
if (!callFrame)
return "Could not find call frame with given id";
- setter = callFrame.setVariableValue.bind(callFrame);
+ setter = callFrame.setVariableValue.bind(callFrame);
} else {
var parsedFunctionId = this._parseObjectId(/** @type {string} */ (functionObjectId));
var func = this._objectForId(parsedFunctionId);
if (typeof func !== "function")
return "Cannot resolve function by id.";
- setter = InjectedScriptHost.setFunctionVariableValue.bind(InjectedScriptHost, func);
+ setter = InjectedScriptHost.setFunctionVariableValue.bind(InjectedScriptHost, func);
}
var newValueJson;
try {
@@ -691,7 +723,7 @@ InjectedScript.prototype = {
try {
resolvedValue = this._resolveCallArgument(newValueJson);
} catch (e) {
- return String(e);
+ return toString(e);
}
try {
setter(scopeNumber, variableName, resolvedValue);
@@ -706,7 +738,7 @@ InjectedScript.prototype = {
* @param {string} callFrameId
* @return {Object}
*/
- _callFrameForId: function(topCallFrame, callFrameId)
+ callFrameForId: function(topCallFrame, callFrameId)
{
var parsedCallFrameId = InjectedScriptHost.evaluate("(" + callFrameId + ")");
var ordinal = parsedCallFrameId["ordinal"];
@@ -750,7 +782,7 @@ InjectedScript.prototype = {
/**
* @param {string} name
* @return {Object}
- */
+ */
module: function(name)
{
return this._modules[name];
@@ -760,7 +792,7 @@ InjectedScript.prototype = {
* @param {string} name
* @param {string} source
* @return {Object}
- */
+ */
injectModule: function(name, source)
{
delete this._modules[name];
@@ -838,10 +870,10 @@ InjectedScript.prototype = {
var subtype = this._subtype(obj);
if (subtype === "regexp")
- return this._toString(obj);
+ return toString(obj);
if (subtype === "date")
- return this._toString(obj);
+ return toString(obj);
if (subtype === "node") {
var description = obj.nodeName.toLowerCase();
@@ -867,7 +899,7 @@ InjectedScript.prototype = {
// NodeList in JSC is a function, check for array prior to this.
if (typeof obj === "function")
- return this._toString(obj);
+ return toString(obj);
if (className === "Object") {
// In Chromium DOM wrapper prototypes will have Object as their constructor name,
@@ -877,16 +909,6 @@ InjectedScript.prototype = {
return constructorName;
}
return className;
- },
-
- /**
- * @param {*} obj
- * @return {string}
- */
- _toString: function(obj)
- {
- // We don't use String(obj) because inspectedWindow.String is undefined if owning frame navigated to another page.
- return "" + obj;
}
}
@@ -919,7 +941,7 @@ InjectedScript.RemoteObject = function(object, objectGroupName, forceValueType,
// Provide user-friendly number values.
if (this.type === "number")
- this.description = object + "";
+ this.description = toStringDescription(object);
return;
}
@@ -958,36 +980,43 @@ InjectedScript.RemoteObject.prototype = {
properties: (isTable || isTableRow) ? 1000 : Math.max(5, firstLevelKeysCount),
indexes: (isTable || isTableRow) ? 1000 : Math.max(100, firstLevelKeysCount)
};
- for (var o = object; injectedScript._isDefined(o); o = o.__proto__)
- this._generateProtoPreview(/** @type {!Object} */ (o), preview, propertiesThreshold, firstLevelKeys, secondLevelKeys, isTable);
- return preview;
- },
- /**
- * @param {!Object} object
- * @param {!RuntimeAgent.ObjectPreview} preview
- * @param {!Object} propertiesThreshold
- * @param {Array.<string>=} firstLevelKeys
- * @param {Array.<string>=} secondLevelKeys
- * @param {boolean=} isTable
- */
- _generateProtoPreview: function(object, preview, propertiesThreshold, firstLevelKeys, secondLevelKeys, isTable)
- {
- var propertyNames = firstLevelKeys ? firstLevelKeys : Object.keys(object);
try {
- for (var i = 0; i < propertyNames.length; ++i) {
- if (!propertiesThreshold.properties || !propertiesThreshold.indexes) {
- preview.overflow = true;
- preview.lossless = false;
+ var descriptors = injectedScript._propertyDescriptors(object);
+
+ if (firstLevelKeys) {
+ var nameToDescriptors = {};
+ for (var i = 0; i < descriptors.length; ++i) {
+ var descriptor = descriptors[i];
+ nameToDescriptors["#" + descriptor.name] = descriptor;
+ }
+ descriptors = [];
+ for (var i = 0; i < firstLevelKeys.length; ++i)
+ descriptors.push(nameToDescriptors["#" + firstLevelKeys[i]]);
+ }
+
+ for (var i = 0; i < descriptors.length; ++i) {
+ if (propertiesThreshold.indexes < 0 || propertiesThreshold.properties < 0)
break;
+
+ var descriptor = descriptors[i];
+ if (!descriptor)
+ continue;
+ if (descriptor.wasThrown) {
+ preview.lossless = false;
+ continue;
}
- var name = propertyNames[i];
+ if (!descriptor.enumerable && !descriptor.isOwn)
+ continue;
+
+ var name = descriptor.name;
+ if (name === "__proto__")
+ continue;
if (this.subtype === "array" && name === "length")
continue;
- var descriptor = Object.getOwnPropertyDescriptor(object, name);
- if (!("value" in descriptor) || !descriptor.enumerable) {
- preview.lossless = false;
+ if (!("value" in descriptor)) {
+ this._appendPropertyPreview(preview, { name: name, type: "accessor" }, propertiesThreshold);
continue;
}
@@ -996,19 +1025,20 @@ InjectedScript.RemoteObject.prototype = {
this._appendPropertyPreview(preview, { name: name, type: "object", value: "null" }, propertiesThreshold);
continue;
}
-
+
const maxLength = 100;
var type = typeof value;
+ if (!descriptor.enumerable && type === "function")
+ continue;
+ if (type === "undefined" && injectedScript._isHTMLAllCollection(value))
+ type = "object";
if (InjectedScript.primitiveTypes[type]) {
- if (type === "string") {
- if (value.length > maxLength) {
- value = this._abbreviateString(value, maxLength, true);
- preview.lossless = false;
- }
- value = value.replace(/\n/g, "\u21B5");
+ if (type === "string" && value.length > maxLength) {
+ value = this._abbreviateString(value, maxLength, true);
+ preview.lossless = false;
}
- this._appendPropertyPreview(preview, { name: name, type: type, value: value + "" }, propertiesThreshold);
+ this._appendPropertyPreview(preview, { name: name, type: type, value: toStringDescription(value) }, propertiesThreshold);
continue;
}
@@ -1036,7 +1066,10 @@ InjectedScript.RemoteObject.prototype = {
this._appendPropertyPreview(preview, property, propertiesThreshold);
}
} catch (e) {
+ preview.lossless = false;
}
+
+ return preview;
},
/**
@@ -1046,11 +1079,16 @@ InjectedScript.RemoteObject.prototype = {
*/
_appendPropertyPreview: function(preview, property, propertiesThreshold)
{
- if (isNaN(property.name))
- propertiesThreshold.properties--;
- else
+ if (toString(property.name >>> 0) === property.name)
propertiesThreshold.indexes--;
- preview.properties.push(property);
+ else
+ propertiesThreshold.properties--;
+ if (propertiesThreshold.indexes < 0 || propertiesThreshold.properties < 0) {
+ preview.overflow = true;
+ preview.lossless = false;
+ } else {
+ preview.properties.push(property);
+ }
},
/**
@@ -1074,15 +1112,17 @@ InjectedScript.RemoteObject.prototype = {
/**
* @constructor
* @param {number} ordinal
- * @param {Object} callFrame
+ * @param {!Object} callFrame
*/
InjectedScript.CallFrameProxy = function(ordinal, callFrame)
{
this.callFrameId = "{\"ordinal\":" + ordinal + ",\"injectedScriptId\":" + injectedScriptId + "}";
this.functionName = (callFrame.type === "function" ? callFrame.functionName : "");
- this.location = { scriptId: String(callFrame.sourceID), lineNumber: callFrame.line, columnNumber: callFrame.column };
+ this.location = { scriptId: toString(callFrame.sourceID), lineNumber: callFrame.line, columnNumber: callFrame.column };
this.scopeChain = this._wrapScopeChain(callFrame);
this.this = injectedScript._wrapObject(callFrame.thisObject, "backtrace");
+ if (callFrame.isAtReturn)
+ this.returnValue = injectedScript._wrapObject(callFrame.returnValue, "backtrace");
}
InjectedScript.CallFrameProxy.prototype = {
@@ -1159,7 +1199,20 @@ function CommandLineAPI(commandLineAPIImpl, callFrame)
*/
function customToStringMethod(name)
{
- return function () { return "function " + name + "() { [Command Line API] }"; };
+ return function()
+ {
+ var funcArgsSyntax = "";
+ try {
+ var funcSyntax = "" + commandLineAPIImpl[name];
+ funcSyntax = funcSyntax.replace(/\n/g, " ");
+ funcSyntax = funcSyntax.replace(/^function[^\(]*\(([^\)]*)\).*$/, "$1");
+ funcSyntax = funcSyntax.replace(/\s*,\s*/g, ", ");
+ funcSyntax = funcSyntax.replace(/\bopt_(\w+)\b/g, "[$1]");
+ funcArgsSyntax = funcSyntax.trim();
+ } catch (e) {
+ }
+ return "function " + name + "(" + funcArgsSyntax + ") { [Command Line API] }";
+ };
}
for (var i = 0; i < CommandLineAPI.members_.length; ++i) {
@@ -1183,6 +1236,7 @@ function CommandLineAPI(commandLineAPIImpl, callFrame)
}
// NOTE: Please keep the list of API methods below snchronized to that in WebInspector.RuntimeModel!
+// NOTE: Argument names of these methods will be printed in the console, so use pretty names!
/**
* @type {Array.<string>}
* @const
@@ -1203,24 +1257,24 @@ function CommandLineAPIImpl()
CommandLineAPIImpl.prototype = {
/**
* @param {string} selector
- * @param {Node=} start
+ * @param {Node=} opt_startNode
*/
- $: function (selector, start)
+ $: function (selector, opt_startNode)
{
- if (this._canQuerySelectorOnNode(start))
- return start.querySelector(selector);
+ if (this._canQuerySelectorOnNode(opt_startNode))
+ return opt_startNode.querySelector(selector);
return inspectedWindow.document.querySelector(selector);
},
/**
* @param {string} selector
- * @param {Node=} start
+ * @param {Node=} opt_startNode
*/
- $$: function (selector, start)
+ $$: function (selector, opt_startNode)
{
- if (this._canQuerySelectorOnNode(start))
- return start.querySelectorAll(selector);
+ if (this._canQuerySelectorOnNode(opt_startNode))
+ return opt_startNode.querySelectorAll(selector);
return inspectedWindow.document.querySelectorAll(selector);
},
@@ -1235,12 +1289,12 @@ CommandLineAPIImpl.prototype = {
/**
* @param {string} xpath
- * @param {Node=} context
+ * @param {Node=} opt_startNode
*/
- $x: function(xpath, context)
+ $x: function(xpath, opt_startNode)
{
- var doc = (context && context.ownerDocument) || inspectedWindow.document;
- var result = doc.evaluate(xpath, context || doc, null, XPathResult.ANY_TYPE, null);
+ var doc = (opt_startNode && opt_startNode.ownerDocument) || inspectedWindow.document;
+ var result = doc.evaluate(xpath, opt_startNode || doc, null, XPathResult.ANY_TYPE, null);
switch (result.resultType) {
case XPathResult.NUMBER_TYPE:
return result.numberValue;
@@ -1257,12 +1311,12 @@ CommandLineAPIImpl.prototype = {
}
},
- dir: function()
+ dir: function(var_args)
{
return inspectedWindow.console.dir.apply(inspectedWindow.console, arguments)
},
- dirxml: function()
+ dirxml: function(var_args)
{
return inspectedWindow.console.dirxml.apply(inspectedWindow.console, arguments)
},
@@ -1280,25 +1334,25 @@ CommandLineAPIImpl.prototype = {
return result;
},
- profile: function()
+ profile: function(opt_title)
{
return inspectedWindow.console.profile.apply(inspectedWindow.console, arguments)
},
- profileEnd: function()
+ profileEnd: function(opt_title)
{
return inspectedWindow.console.profileEnd.apply(inspectedWindow.console, arguments)
},
/**
* @param {Object} object
- * @param {Array.<string>|string=} types
+ * @param {Array.<string>|string=} opt_types
*/
- monitorEvents: function(object, types)
+ monitorEvents: function(object, opt_types)
{
if (!object || !object.addEventListener || !object.removeEventListener)
return;
- types = this._normalizeEventTypes(types);
+ var types = this._normalizeEventTypes(opt_types);
for (var i = 0; i < types.length; ++i) {
object.removeEventListener(types[i], this._logEvent, false);
object.addEventListener(types[i], this._logEvent, false);
@@ -1307,13 +1361,13 @@ CommandLineAPIImpl.prototype = {
/**
* @param {Object} object
- * @param {Array.<string>|string=} types
+ * @param {Array.<string>|string=} opt_types
*/
- unmonitorEvents: function(object, types)
+ unmonitorEvents: function(object, opt_types)
{
if (!object || !object.addEventListener || !object.removeEventListener)
return;
- types = this._normalizeEventTypes(types);
+ var types = this._normalizeEventTypes(opt_types);
for (var i = 0; i < types.length; ++i)
object.removeEventListener(types[i], this._logEvent, false);
},
@@ -1329,9 +1383,19 @@ CommandLineAPIImpl.prototype = {
copy: function(object)
{
- if (injectedScript._subtype(object) === "node")
- object = object.outerHTML;
- var string = object + "";
+ var string;
+ if (injectedScript._subtype(object) === "node") {
+ string = object.outerHTML;
+ } else if (injectedScript.isPrimitiveValue(object)) {
+ string = toString(object);
+ } else {
+ try {
+ string = JSON.stringify(object, null, " ");
+ } catch (e) {
+ string = toString(object);
+ }
+ }
+
var hints = { copyToClipboard: true };
var remoteObject = injectedScript._wrapObject(string, "")
InjectedScriptHost.inspect(remoteObject, hints);
@@ -1344,10 +1408,26 @@ CommandLineAPIImpl.prototype = {
/**
* @param {Node} node
+ * @return {{type: string, listener: function(), useCapture: boolean, remove: function()}|undefined}
*/
getEventListeners: function(node)
{
- return InjectedScriptHost.getEventListeners(node);
+ var result = InjectedScriptHost.getEventListeners(node);
+ if (!result)
+ return result;
+ /** @this {{type: string, listener: function(), useCapture: boolean}} */
+ var removeFunc = function()
+ {
+ node.removeEventListener(this.type, this.listener, this.useCapture);
+ }
+ for (var type in result) {
+ var listeners = result[type];
+ for (var i = 0, listener; listener = listeners[i]; ++i) {
+ listener["type"] = type;
+ listener["remove"] = removeFunc;
+ }
+ }
+ return result;
},
debug: function(fn)
@@ -1369,7 +1449,7 @@ CommandLineAPIImpl.prototype = {
InjectedScriptHost.unmonitorFunction(fn);
},
- table: function()
+ table: function(data, opt_columns)
{
inspectedWindow.console.table.apply(inspectedWindow.console, arguments);
},
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InspectorAgent.cpp b/chromium/third_party/WebKit/Source/core/inspector/InspectorAgent.cpp
index e988353093e..4ae9a6680e7 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InspectorAgent.cpp
+++ b/chromium/third_party/WebKit/Source/core/inspector/InspectorAgent.cpp
@@ -41,10 +41,9 @@
#include "core/inspector/InspectorState.h"
#include "core/inspector/InstrumentingAgents.h"
#include "core/loader/DocumentLoader.h"
-#include "core/page/Frame.h"
+#include "core/frame/Frame.h"
#include "core/page/Page.h"
-#include "core/platform/JSONValues.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/weborigin/SecurityOrigin.h"
#include "wtf/text/StringBuilder.h"
namespace WebCore {
@@ -86,7 +85,7 @@ void InspectorAgent::didClearWindowObjectInWorld(Frame* frame, DOMWrapperWorld*
scriptSource.append("(");
scriptSource.appendNumber(injectedScriptId);
scriptSource.append(")");
- frame->script()->executeScript(scriptSource.toString());
+ frame->script().executeScriptInMainWorld(scriptSource.toString());
}
void InspectorAgent::setFrontend(InspectorFrontend* inspectorFrontend)
@@ -141,11 +140,6 @@ void InspectorAgent::domContentLoadedEventFired(Frame* frame)
m_injectedScriptManager->injectedScriptHost()->clearInspectedObjects();
}
-bool InspectorAgent::isMainResourceLoader(DocumentLoader* loader, const KURL& requestUrl)
-{
- return loader->frame() == m_inspectedPage->mainFrame() && requestUrl == loader->requestURL();
-}
-
void InspectorAgent::evaluateForTestInFrontend(long callId, const String& script)
{
if (m_state->getBoolean(InspectorAgentState::inspectorAgentEnabled))
@@ -171,17 +165,5 @@ void InspectorAgent::inspect(PassRefPtr<TypeBuilder::Runtime::RemoteObject> obje
m_pendingInspectData.second = hints;
}
-KURL InspectorAgent::inspectedURL() const
-{
- return m_inspectedPage->mainFrame()->document()->url();
-}
-
-KURL InspectorAgent::inspectedURLWithoutFragment() const
-{
- KURL url = inspectedURL();
- url.removeFragmentIdentifier();
- return url;
-}
-
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InspectorAgent.h b/chromium/third_party/WebKit/Source/core/inspector/InspectorAgent.h
index 5b07482900e..789e00220ea 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InspectorAgent.h
+++ b/chromium/third_party/WebKit/Source/core/inspector/InspectorAgent.h
@@ -31,11 +31,9 @@
#define InspectorAgent_h
#include "core/inspector/InspectorBaseAgent.h"
-#include "wtf/Forward.h"
#include "wtf/HashMap.h"
#include "wtf/PassOwnPtr.h"
#include "wtf/Vector.h"
-#include "wtf/text/WTFString.h"
namespace WebCore {
@@ -46,7 +44,6 @@ class InjectedScriptManager;
class InspectorFrontend;
class InstrumentingAgents;
class JSONObject;
-class KURL;
class Page;
typedef String ErrorString;
@@ -66,11 +63,6 @@ public:
void disable(ErrorString*);
void reset(ErrorString*);
- KURL inspectedURL() const;
- KURL inspectedURLWithoutFragment() const;
-
- InspectorFrontend* frontend() const { return m_frontend; }
-
virtual void setFrontend(InspectorFrontend*);
virtual void clearFrontend();
@@ -91,12 +83,6 @@ public:
private:
InspectorAgent(Page*, InjectedScriptManager*, InstrumentingAgents*, InspectorCompositeState*);
- void unbindAllResources();
-
- void toggleRecordButton(bool);
-
- bool isMainResourceLoader(DocumentLoader*, const KURL& requestUrl);
-
Page* m_inspectedPage;
InspectorFrontend* m_frontend;
InjectedScriptManager* m_injectedScriptManager;
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InspectorApplicationCacheAgent.cpp b/chromium/third_party/WebKit/Source/core/inspector/InspectorApplicationCacheAgent.cpp
index c68e9799dbb..954c28a71ac 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InspectorApplicationCacheAgent.cpp
+++ b/chromium/third_party/WebKit/Source/core/inspector/InspectorApplicationCacheAgent.cpp
@@ -26,15 +26,13 @@
#include "config.h"
#include "core/inspector/InspectorApplicationCacheAgent.h"
-#include "InspectorFrontend.h"
#include "core/inspector/InspectorPageAgent.h"
#include "core/inspector/InspectorState.h"
#include "core/inspector/InstrumentingAgents.h"
#include "core/loader/DocumentLoader.h"
#include "core/loader/FrameLoader.h"
-#include "core/loader/appcache/ApplicationCacheHost.h"
-#include "core/page/Frame.h"
-#include "core/platform/network/NetworkStateNotifier.h"
+#include "core/frame/Frame.h"
+#include "core/page/NetworkStateNotifier.h"
#include "wtf/text/StringBuilder.h"
namespace WebCore {
@@ -75,12 +73,12 @@ void InspectorApplicationCacheAgent::enable(ErrorString*)
m_instrumentingAgents->setInspectorApplicationCacheAgent(this);
// We need to pass initial navigator.onOnline.
- networkStateChanged();
+ networkStateChanged(networkStateNotifier().onLine());
}
void InspectorApplicationCacheAgent::updateApplicationCacheStatus(Frame* frame)
{
- DocumentLoader* documentLoader = frame->loader()->documentLoader();
+ DocumentLoader* documentLoader = frame->loader().documentLoader();
if (!documentLoader)
return;
@@ -92,10 +90,9 @@ void InspectorApplicationCacheAgent::updateApplicationCacheStatus(Frame* frame)
m_frontend->applicationCacheStatusUpdated(m_pageAgent->frameId(frame), manifestURL, static_cast<int>(status));
}
-void InspectorApplicationCacheAgent::networkStateChanged()
+void InspectorApplicationCacheAgent::networkStateChanged(bool online)
{
- bool isNowOnline = networkStateNotifier().onLine();
- m_frontend->networkStateUpdated(isNowOnline);
+ m_frontend->networkStateUpdated(online);
}
void InspectorApplicationCacheAgent::getFramesWithManifests(ErrorString*, RefPtr<TypeBuilder::Array<TypeBuilder::ApplicationCache::FrameWithManifest> >& result)
@@ -103,8 +100,8 @@ void InspectorApplicationCacheAgent::getFramesWithManifests(ErrorString*, RefPtr
result = TypeBuilder::Array<TypeBuilder::ApplicationCache::FrameWithManifest>::create();
Frame* mainFrame = m_pageAgent->mainFrame();
- for (Frame* frame = mainFrame; frame; frame = frame->tree()->traverseNext(mainFrame)) {
- DocumentLoader* documentLoader = frame->loader()->documentLoader();
+ for (Frame* frame = mainFrame; frame; frame = frame->tree().traverseNext(mainFrame)) {
+ DocumentLoader* documentLoader = frame->loader().documentLoader();
if (!documentLoader)
continue;
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InspectorApplicationCacheAgent.h b/chromium/third_party/WebKit/Source/core/inspector/InspectorApplicationCacheAgent.h
index cba2125cf1f..8b9b9d5051d 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InspectorApplicationCacheAgent.h
+++ b/chromium/third_party/WebKit/Source/core/inspector/InspectorApplicationCacheAgent.h
@@ -56,7 +56,7 @@ public:
// InspectorInstrumentation API
void updateApplicationCacheStatus(Frame*);
- void networkStateChanged();
+ void networkStateChanged(bool online);
// ApplicationCache API for InspectorFrontend
virtual void enable(ErrorString*);
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InspectorCSSAgent.cpp b/chromium/third_party/WebKit/Source/core/inspector/InspectorCSSAgent.cpp
index ee326aa3206..d4bafdf24e2 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InspectorCSSAgent.cpp
+++ b/chromium/third_party/WebKit/Source/core/inspector/InspectorCSSAgent.cpp
@@ -55,27 +55,24 @@
#include "core/fetch/ResourceFetcher.h"
#include "core/fetch/StyleSheetResourceClient.h"
#include "core/html/HTMLHeadElement.h"
-#include "core/inspector/InspectorDOMAgent.h"
#include "core/inspector/InspectorHistory.h"
#include "core/inspector/InspectorPageAgent.h"
#include "core/inspector/InspectorResourceAgent.h"
#include "core/inspector/InspectorState.h"
#include "core/inspector/InstrumentingAgents.h"
#include "core/loader/DocumentLoader.h"
-#include "core/page/ContentSecurityPolicy.h"
-#include "core/platform/JSONValues.h"
-#include "core/platform/graphics/Font.h"
-#include "core/platform/graphics/GlyphBuffer.h"
-#include "core/platform/graphics/TextRun.h"
-#include "core/platform/graphics/WidthIterator.h"
+#include "core/frame/Frame.h"
+#include "core/page/Page.h"
#include "core/rendering/InlineTextBox.h"
#include "core/rendering/RenderObject.h"
#include "core/rendering/RenderRegion.h"
#include "core/rendering/RenderText.h"
#include "core/rendering/RenderTextFragment.h"
+#include "platform/fonts/Font.h"
+#include "platform/fonts/GlyphBuffer.h"
+#include "platform/fonts/WidthIterator.h"
+#include "platform/text/TextRun.h"
#include "wtf/CurrentTime.h"
-#include "wtf/HashSet.h"
-#include "wtf/Vector.h"
#include "wtf/text/CString.h"
#include "wtf/text/StringConcatenate.h"
@@ -97,18 +94,11 @@ enum ForcePseudoClassFlags {
class StyleSheetAppender {
public:
- StyleSheetAppender(CSSStyleSheetToInspectorStyleSheet& cssStyleSheetToInspectorStyleSheet, Vector<CSSStyleSheet*>& result)
- : m_cssStyleSheetToInspectorStyleSheet(cssStyleSheetToInspectorStyleSheet)
- , m_result(result) { }
+ StyleSheetAppender(Vector<CSSStyleSheet*>& result)
+ : m_result(result) { }
void run(CSSStyleSheet* styleSheet)
{
- RefPtr<InspectorStyleSheet> inspectorStyleSheet = m_cssStyleSheetToInspectorStyleSheet.get(styleSheet);
- // Avoid creating m_childRuleCSSOMWrappers in the stylesheet if it is in the process of re-parsing.
- // Otherwise m_childRuleCSSOMWrappers size will be initialized only for a part of rules, resulting in an ASSERT failure in CSSStyleSheet::item().
- // Instead, wait for the RuleMutationScope destruction and handle the complete CSSStyleSheet.
- if (inspectorStyleSheet && inspectorStyleSheet->isReparsing())
- return;
m_result.append(styleSheet);
for (unsigned i = 0, size = styleSheet->length(); i < size; ++i) {
CSSRule* rule = styleSheet->item(i);
@@ -121,7 +111,6 @@ public:
}
private:
- CSSStyleSheetToInspectorStyleSheet& m_cssStyleSheetToInspectorStyleSheet;
Vector<CSSStyleSheet*>& m_result;
};
@@ -298,7 +287,7 @@ InspectorCSSAgent::EnableResourceClient::EnableResourceClient(InspectorCSSAgent*
for (size_t i = 0; i < styleSheets.size(); ++i) {
InspectorStyleSheet* styleSheet = styleSheets.at(i);
Document* document = styleSheet->ownerDocument();
- FetchRequest request(ResourceRequest(styleSheet->finalURL()), FetchInitiatorTypeNames::inspector);
+ FetchRequest request(ResourceRequest(styleSheet->finalURL()), FetchInitiatorTypeNames::internal);
ResourcePtr<Resource> resource = document->fetcher()->fetchCSSStyleSheet(request);
resource->addClient(this);
}
@@ -326,25 +315,25 @@ public:
{
}
- virtual bool perform(ExceptionState& es)
+ virtual bool perform(ExceptionState& exceptionState)
{
if (!m_styleSheet->getText(&m_oldText))
return false;
- return redo(es);
+ return redo(exceptionState);
}
- virtual bool undo(ExceptionState& es)
+ virtual bool undo(ExceptionState& exceptionState)
{
- if (m_styleSheet->setText(m_oldText, es)) {
+ if (m_styleSheet->setText(m_oldText, exceptionState)) {
m_styleSheet->reparseStyleSheet(m_oldText);
return true;
}
return false;
}
- virtual bool redo(ExceptionState& es)
+ virtual bool redo(ExceptionState& exceptionState)
{
- if (m_styleSheet->setText(m_text, es)) {
+ if (m_styleSheet->setText(m_text, exceptionState)) {
m_styleSheet->reparseStyleSheet(m_text);
return true;
}
@@ -384,20 +373,20 @@ public:
return mergeId() + ": " + m_oldText + " -> " + m_text;
}
- virtual bool perform(ExceptionState& es)
+ virtual bool perform(ExceptionState& exceptionState)
{
- return redo(es);
+ return redo(exceptionState);
}
- virtual bool undo(ExceptionState& es)
+ virtual bool undo(ExceptionState& exceptionState)
{
String placeholder;
- return m_styleSheet->setStyleText(m_cssId, m_oldText, &placeholder, es);
+ return m_styleSheet->setStyleText(m_cssId, m_oldText, &placeholder, exceptionState);
}
- virtual bool redo(ExceptionState& es)
+ virtual bool redo(ExceptionState& exceptionState)
{
- return m_styleSheet->setStyleText(m_cssId, m_text, &m_oldText, es);
+ return m_styleSheet->setStyleText(m_cssId, m_text, &m_oldText, exceptionState);
}
virtual String mergeId()
@@ -436,21 +425,21 @@ public:
return mergeId() + ": " + m_oldText + " -> " + m_text;
}
- virtual bool perform(ExceptionState& es)
+ virtual bool perform(ExceptionState& exceptionState)
{
- return redo(es);
+ return redo(exceptionState);
}
- virtual bool undo(ExceptionState& es)
+ virtual bool undo(ExceptionState& exceptionState)
{
String placeholder;
- return m_styleSheet->setPropertyText(m_cssId, m_propertyIndex, m_overwrite ? m_oldText : "", true, &placeholder, es);
+ return m_styleSheet->setPropertyText(m_cssId, m_propertyIndex, m_overwrite ? m_oldText : "", true, &placeholder, exceptionState);
}
- virtual bool redo(ExceptionState& es)
+ virtual bool redo(ExceptionState& exceptionState)
{
String oldText;
- bool result = m_styleSheet->setPropertyText(m_cssId, m_propertyIndex, m_text, m_overwrite, &oldText, es);
+ bool result = m_styleSheet->setPropertyText(m_cssId, m_propertyIndex, m_text, m_overwrite, &oldText, exceptionState);
m_oldText = oldText.stripWhiteSpace();
// FIXME: remove this once the model handles this case.
if (!m_oldText.endsWith(';'))
@@ -490,19 +479,19 @@ public:
{
}
- virtual bool perform(ExceptionState& es)
+ virtual bool perform(ExceptionState& exceptionState)
{
- return redo(es);
+ return redo(exceptionState);
}
- virtual bool undo(ExceptionState& es)
+ virtual bool undo(ExceptionState& exceptionState)
{
- return m_styleSheet->toggleProperty(m_cssId, m_propertyIndex, !m_disable, es);
+ return m_styleSheet->toggleProperty(m_cssId, m_propertyIndex, !m_disable, exceptionState);
}
- virtual bool redo(ExceptionState& es)
+ virtual bool redo(ExceptionState& exceptionState)
{
- return m_styleSheet->toggleProperty(m_cssId, m_propertyIndex, m_disable, es);
+ return m_styleSheet->toggleProperty(m_cssId, m_propertyIndex, m_disable, exceptionState);
}
private:
@@ -521,22 +510,22 @@ public:
{
}
- virtual bool perform(ExceptionState& es)
+ virtual bool perform(ExceptionState& exceptionState)
{
- m_oldSelector = m_styleSheet->ruleSelector(m_cssId, es);
- if (es.hadException())
+ m_oldSelector = m_styleSheet->ruleSelector(m_cssId, exceptionState);
+ if (exceptionState.hadException())
return false;
- return redo(es);
+ return redo(exceptionState);
}
- virtual bool undo(ExceptionState& es)
+ virtual bool undo(ExceptionState& exceptionState)
{
- return m_styleSheet->setRuleSelector(m_cssId, m_oldSelector, es);
+ return m_styleSheet->setRuleSelector(m_cssId, m_oldSelector, exceptionState);
}
- virtual bool redo(ExceptionState& es)
+ virtual bool redo(ExceptionState& exceptionState)
{
- return m_styleSheet->setRuleSelector(m_cssId, m_selector, es);
+ return m_styleSheet->setRuleSelector(m_cssId, m_selector, exceptionState);
}
private:
@@ -554,20 +543,20 @@ public:
{
}
- virtual bool perform(ExceptionState& es)
+ virtual bool perform(ExceptionState& exceptionState)
{
- return redo(es);
+ return redo(exceptionState);
}
- virtual bool undo(ExceptionState& es)
+ virtual bool undo(ExceptionState& exceptionState)
{
- return m_styleSheet->deleteRule(m_newId, es);
+ return m_styleSheet->deleteRule(m_newId, exceptionState);
}
- virtual bool redo(ExceptionState& es)
+ virtual bool redo(ExceptionState& exceptionState)
{
- CSSStyleRule* cssStyleRule = m_styleSheet->addRule(m_selector, es);
- if (es.hadException())
+ CSSStyleRule* cssStyleRule = m_styleSheet->addRule(m_selector, exceptionState);
+ if (exceptionState.hadException())
return false;
m_newId = m_styleSheet->ruleId(cssStyleRule);
return true;
@@ -615,164 +604,6 @@ static size_t vendorPrefixLowerCase(const CharType* string, size_t stringLength,
return 0;
}
-template <size_t patternLength>
-static bool equals(const char* prefix, size_t prefixLength, const char (&pattern)[patternLength])
-{
- if (prefixLength != patternLength - 1)
- return false;
- for (size_t i = 0; i < patternLength - 1; i++) {
- if (prefix[i] != pattern[i])
- return false;
- }
- return true;
-}
-
-static bool hasNonWebkitVendorSpecificPrefix(const CSSParserString& string)
-{
- // Known prefixes: http://wiki.csswg.org/spec/vendor-prefixes
- const size_t stringLength = string.length();
- if (stringLength < 4)
- return false;
-
- char buffer[6];
- size_t prefixLength = string.is8Bit() ?
- vendorPrefixLowerCase(string.characters8(), stringLength, buffer) :
- vendorPrefixLowerCase(string.characters16(), stringLength, buffer);
-
- if (!prefixLength || prefixLength == stringLength - 2)
- return false;
-
- switch (buffer[0]) {
- case 'a':
- return (prefixLength == 2 && buffer[1] == 'h') || equals(buffer + 1, prefixLength - 1, "tsc");
- case 'e':
- return equals(buffer + 1, prefixLength - 1, "pub");
- case 'h':
- return prefixLength == 2 && buffer[1] == 'p';
- case 'i':
- return equals(buffer + 1, prefixLength - 1, "books");
- case 'k':
- return equals(buffer + 1, prefixLength - 1, "html");
- case 'm':
- if (prefixLength == 2)
- return buffer[1] == 's';
- if (prefixLength == 3)
- return (buffer[1] == 'o' && buffer[2] == 'z') || (buffer[1] == 's' || buffer[2] == 'o');
- break;
- case 'o':
- return prefixLength == 1;
- case 'p':
- return equals(buffer + 1, prefixLength - 1, "rince");
- case 'r':
- return (prefixLength == 2 && buffer[1] == 'o') || equals(buffer + 1, prefixLength - 1, "im");
- case 't':
- return prefixLength == 2 && buffer[1] == 'c';
- case 'w':
- return (prefixLength == 3 && buffer[1] == 'a' && buffer[2] == 'p') || equals(buffer + 1, prefixLength - 1, "easy");
- case 'x':
- return prefixLength == 2 && buffer[1] == 'v';
- }
- return false;
-}
-
-static bool isValidPropertyName(const CSSParserString& content)
-{
- if (content.equalIgnoringCase("animation")
- || content.equalIgnoringCase("font-size-adjust")
- || content.equalIgnoringCase("transform")
- || content.equalIgnoringCase("user-select")
- || content.equalIgnoringCase("-webkit-flex-pack")
- || content.equalIgnoringCase("-webkit-text-size-adjust"))
- return true;
-
- return false;
-}
-
-// static
-bool InspectorCSSAgent::cssErrorFilter(const CSSParserString& content, int propertyId, int errorType)
-{
- const size_t contentLength = content.length();
-
- switch (errorType) {
- case CSSParser::PropertyDeclarationError:
- // Ignore errors like "*property: value". This trick is used for IE7: http://stackoverflow.com/questions/4563651/what-does-an-asterisk-do-in-a-css-property-name
- if (contentLength && content[0] == '*')
- return false;
-
- // The "filter" property is commonly used instead of "opacity" for IE9.
- if (propertyId == CSSPropertyFilter)
- return false;
-
- break;
-
- case CSSParser::InvalidPropertyValueError:
- // The "filter" property is commonly used instead of "opacity" for IE9.
- if (propertyId == CSSPropertyFilter)
- return false;
-
- // Value might be a vendor-specific function.
- if (hasNonWebkitVendorSpecificPrefix(content))
- return false;
-
- // IE-only "cursor: hand".
- if (propertyId == CSSPropertyCursor && content.equalIgnoringCase("hand"))
- return false;
-
- // Ignore properties like "property: value \9" (common IE hack) or "property: value \0" (IE 8 hack).
- if (contentLength > 2 && content[contentLength - 2] == '\\' && (content[contentLength - 1] == '9' || content[contentLength - 1] == '0'))
- return false;
-
- if (contentLength > 3) {
-
- // property: value\0/;
- if (content[contentLength - 3] == '\\' && content[contentLength - 2] == '0' && content[contentLength - 1] == '/')
- return false;
-
- // property: value !ie;
- if (content[contentLength - 3] == '!' && content[contentLength - 2] == 'i' && content[contentLength - 1] == 'e')
- return false;
- }
-
- // Popular value prefixes valid in other browsers.
- if (content.startsWithIgnoringCase("linear-gradient"))
- return false;
- if (content.startsWithIgnoringCase("-webkit-flexbox"))
- return false;
- if (propertyId == CSSPropertyUnicodeBidi && content.startsWithIgnoringCase("isolate"))
- return false;
-
- break;
-
- case CSSParser::InvalidPropertyError:
- if (hasNonWebkitVendorSpecificPrefix(content))
- return false;
-
- // Another hack to make IE-only property.
- if (contentLength && content[0] == '_')
- return false;
-
- // IE-only set of properties.
- if (content.startsWithIgnoringCase("scrollbar-"))
- return false;
-
- if (isValidPropertyName(content))
- return false;
-
- break;
-
- case CSSParser::InvalidRuleError:
- // Block error reporting for @-rules for now to avoid noise.
- if (contentLength > 4 && content[0] == '@')
- return false;
- return true;
-
- case CSSParser::InvalidSelectorPseudoError:
- if (hasNonWebkitVendorSpecificPrefix(content))
- return false;
- }
- return true;
-}
-
InspectorCSSAgent::InspectorCSSAgent(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* state, InspectorDOMAgent* domAgent, InspectorPageAgent* pageAgent, InspectorResourceAgent* resourceAgent)
: InspectorBaseAgent<InspectorCSSAgent>("CSS", instrumentingAgents, state)
, m_frontend(0)
@@ -780,6 +611,8 @@ InspectorCSSAgent::InspectorCSSAgent(InstrumentingAgents* instrumentingAgents, I
, m_pageAgent(pageAgent)
, m_resourceAgent(resourceAgent)
, m_lastStyleSheetId(1)
+ , m_styleSheetsPendingMutation(0)
+ , m_styleDeclarationPendingMutation(false)
, m_creatingViaInspectorStyleSheet(false)
, m_isSettingStyleSheetText(false)
{
@@ -878,15 +711,19 @@ void InspectorCSSAgent::wasEnabled(PassRefPtr<EnableCallback> callback)
return;
}
- // Re-read stylesheets, we know for sure we have content for all of them.
Vector<InspectorStyleSheet*> styleSheets;
collectAllStyleSheets(styleSheets);
for (size_t i = 0; i < styleSheets.size(); ++i)
m_frontend->styleSheetAdded(styleSheets.at(i)->buildObjectForStyleSheetInfo());
- if (callback)
- callback->sendSuccess();
+ // More styleSheetAdded events will be generated below.
m_instrumentingAgents->setInspectorCSSAgent(this);
+ Vector<Document*> documents = m_domAgent->documents();
+ for (Vector<Document*>::iterator it = documents.begin(); it != documents.end(); ++it)
+ (*it)->styleEngine()->updateActiveStyleSheets(FullStyleUpdate);
+
+ if (callback)
+ callback->sendSuccess();
}
void InspectorCSSAgent::disable(ErrorString*)
@@ -931,6 +768,40 @@ void InspectorCSSAgent::willRemoveNamedFlow(Document* document, NamedFlow* named
m_frontend->namedFlowRemoved(documentNodeId, namedFlow->name().string());
}
+void InspectorCSSAgent::willMutateRules()
+{
+ ++m_styleSheetsPendingMutation;
+}
+
+void InspectorCSSAgent::didMutateRules(CSSStyleSheet* styleSheet)
+{
+ --m_styleSheetsPendingMutation;
+ ASSERT(m_styleSheetsPendingMutation >= 0);
+
+ if (!styleSheetEditInProgress()) {
+ Document* owner = styleSheet->ownerDocument();
+ if (owner)
+ owner->modifiedStyleSheet(styleSheet, RecalcStyleDeferred, FullStyleUpdate);
+ }
+}
+
+void InspectorCSSAgent::willMutateStyle()
+{
+ m_styleDeclarationPendingMutation = true;
+}
+
+void InspectorCSSAgent::didMutateStyle(CSSStyleDeclaration* style, bool isInlineStyle)
+{
+ ASSERT(m_styleDeclarationPendingMutation);
+ m_styleDeclarationPendingMutation = false;
+ if (!styleSheetEditInProgress() && !isInlineStyle) {
+ CSSStyleSheet* parentSheet = style->parentStyleSheet();
+ Document* owner = parentSheet ? parentSheet->ownerDocument() : 0;
+ if (owner)
+ owner->modifiedStyleSheet(parentSheet, RecalcStyleDeferred, FullStyleUpdate);
+ }
+}
+
void InspectorCSSAgent::didUpdateRegionLayout(Document* document, NamedFlow* namedFlow)
{
int documentNodeId = documentNodeWithRequestedFlowsId(document);
@@ -977,8 +848,9 @@ void InspectorCSSAgent::regionOversetChanged(NamedFlow* namedFlow, int documentN
void InspectorCSSAgent::activeStyleSheetsUpdated(Document* document, const StyleSheetVector& newSheets)
{
- if (m_isSettingStyleSheetText)
+ if (styleSheetEditInProgress())
return;
+
HashSet<CSSStyleSheet*> removedSheets;
for (CSSStyleSheetToInspectorStyleSheet::iterator it = m_cssStyleSheetToInspectorStyleSheet.begin(); it != m_cssStyleSheetToInspectorStyleSheet.end(); ++it) {
if (it->value->canBind() && (!it->key->ownerDocument() || it->key->ownerDocument() == document))
@@ -989,8 +861,8 @@ void InspectorCSSAgent::activeStyleSheetsUpdated(Document* document, const Style
for (size_t i = 0, size = newSheets.size(); i < size; ++i) {
StyleSheet* newSheet = newSheets.at(i).get();
if (newSheet->isCSSStyleSheet()) {
- StyleSheetAppender appender(m_cssStyleSheetToInspectorStyleSheet, newSheetsVector);
- appender.run(static_cast<CSSStyleSheet*>(newSheet));
+ StyleSheetAppender appender(newSheetsVector);
+ appender.run(toCSSStyleSheet(newSheet));
}
}
@@ -1015,7 +887,7 @@ void InspectorCSSAgent::activeStyleSheetsUpdated(Document* document, const Style
for (HashSet<CSSStyleSheet*>::iterator it = addedSheets.begin(); it != addedSheets.end(); ++it) {
if (!m_cssStyleSheetToInspectorStyleSheet.contains(*it)) {
- InspectorStyleSheet* newStyleSheet = bindStyleSheet(static_cast<CSSStyleSheet*>(*it));
+ InspectorStyleSheet* newStyleSheet = bindStyleSheet(*it);
if (m_frontend)
m_frontend->styleSheetAdded(newStyleSheet->buildObjectForStyleSheetInfo());
}
@@ -1070,16 +942,26 @@ void InspectorCSSAgent::getMatchedStylesForNode(ErrorString* errorString, int no
if (elementPseudoId)
element = element->parentOrShadowHostElement();
+ Document* ownerDocument = element->ownerDocument();
+ // A non-active document has no styles.
+ if (!ownerDocument->isActive())
+ return;
+
+ // FIXME: It's really gross for the inspector to reach in and access StyleResolver
+ // directly here. We need to provide the Inspector better APIs to get this information
+ // without grabbing at internal style classes!
+
// Matched rules.
- StyleResolver* styleResolver = element->ownerDocument()->styleResolver();
- RefPtr<CSSRuleList> matchedRules = styleResolver->pseudoStyleRulesForElement(element, elementPseudoId, StyleResolver::AllCSSRules);
+ StyleResolver& styleResolver = ownerDocument->ensureStyleResolver();
+ // FIXME: This code should not pass DoNotIncludeStyleSheetInCSSOMWrapper. All CSSOMWrappers should always have a parent sheet or rule.
+ RefPtr<CSSRuleList> matchedRules = styleResolver.pseudoCSSRulesForElement(element, elementPseudoId, StyleResolver::AllCSSRules, DoNotIncludeStyleSheetInCSSOMWrapper);
matchedCSSRules = buildArrayForMatchedRuleList(matchedRules.get(), styleResolver, originalElement);
// Pseudo elements.
if (!elementPseudoId && (!includePseudo || *includePseudo)) {
RefPtr<TypeBuilder::Array<TypeBuilder::CSS::PseudoIdMatches> > pseudoElements = TypeBuilder::Array<TypeBuilder::CSS::PseudoIdMatches>::create();
for (PseudoId pseudoId = FIRST_PUBLIC_PSEUDOID; pseudoId < AFTER_LAST_INTERNAL_PSEUDOID; pseudoId = static_cast<PseudoId>(pseudoId + 1)) {
- RefPtr<CSSRuleList> matchedRules = styleResolver->pseudoStyleRulesForElement(element, pseudoId, StyleResolver::AllCSSRules);
+ RefPtr<CSSRuleList> matchedRules = styleResolver.pseudoCSSRulesForElement(element, pseudoId, StyleResolver::AllCSSRules, DoNotIncludeStyleSheetInCSSOMWrapper);
if (matchedRules && matchedRules->length()) {
RefPtr<TypeBuilder::CSS::PseudoIdMatches> matches = TypeBuilder::CSS::PseudoIdMatches::create()
.setPseudoId(static_cast<int>(pseudoId))
@@ -1096,8 +978,8 @@ void InspectorCSSAgent::getMatchedStylesForNode(ErrorString* errorString, int no
RefPtr<TypeBuilder::Array<TypeBuilder::CSS::InheritedStyleEntry> > entries = TypeBuilder::Array<TypeBuilder::CSS::InheritedStyleEntry>::create();
Element* parentElement = element->parentElement();
while (parentElement) {
- StyleResolver* parentStyleResolver = parentElement->ownerDocument()->styleResolver();
- RefPtr<CSSRuleList> parentMatchedRules = parentStyleResolver->styleRulesForElement(parentElement, StyleResolver::AllCSSRules);
+ StyleResolver& parentStyleResolver = parentElement->ownerDocument()->ensureStyleResolver();
+ RefPtr<CSSRuleList> parentMatchedRules = parentStyleResolver.cssRulesForElement(parentElement, StyleResolver::AllCSSRules, DoNotIncludeStyleSheetInCSSOMWrapper);
RefPtr<TypeBuilder::CSS::InheritedStyleEntry> entry = TypeBuilder::CSS::InheritedStyleEntry::create()
.setMatchedCSSRules(buildArrayForMatchedRuleList(parentMatchedRules.get(), styleResolver, parentElement));
if (parentElement->style() && parentElement->style()->length()) {
@@ -1140,7 +1022,7 @@ void InspectorCSSAgent::getComputedStyleForNode(ErrorString* errorString, int no
style = inspectorStyle->buildArrayForComputedStyle();
}
-void InspectorCSSAgent::collectPlatformFontsForRenderer(RenderText* renderer, HashMap<String, int>* fontStats)
+void InspectorCSSAgent::collectPlatformFontsForRenderer(RenderText* renderer, HashCountedSet<String>* fontStats)
{
for (InlineTextBox* box = renderer->firstTextBox(); box; box = box->nextTextBox()) {
RenderStyle* style = renderer->style(box->isFirstLineStyle());
@@ -1149,10 +1031,11 @@ void InspectorCSSAgent::collectPlatformFontsForRenderer(RenderText* renderer, Ha
WidthIterator it(&font, run, 0, false);
GlyphBuffer glyphBuffer;
it.advance(run.length(), &glyphBuffer);
- for (int i = 0; i < glyphBuffer.size(); ++i) {
+ for (unsigned i = 0; i < glyphBuffer.size(); ++i) {
String familyName = glyphBuffer.fontDataAt(i)->platformData().fontFamilyName();
- int value = fontStats->contains(familyName) ? fontStats->get(familyName) : 0;
- fontStats->set(familyName, value + 1);
+ if (familyName.isNull())
+ familyName = "";
+ fontStats->add(familyName);
}
}
}
@@ -1178,7 +1061,7 @@ void InspectorCSSAgent::getPlatformFontsForNode(ErrorString* errorString, int no
}
}
- HashMap<String, int> fontStats;
+ HashCountedSet<String> fontStats;
for (size_t i = 0; i < textNodes.size(); ++i) {
RenderText* renderer = toRenderText(textNodes[i]->renderer());
collectPlatformFontsForRenderer(renderer, &fontStats);
@@ -1195,7 +1078,7 @@ void InspectorCSSAgent::getPlatformFontsForNode(ErrorString* errorString, int no
}
platformFonts = TypeBuilder::Array<TypeBuilder::CSS::PlatformFontUsage>::create();
- for (HashMap<String, int>::iterator it = fontStats.begin(), end = fontStats.end(); it != end; ++it) {
+ for (HashCountedSet<String>::iterator it = fontStats.begin(), end = fontStats.end(); it != end; ++it) {
RefPtr<TypeBuilder::CSS::PlatformFontUsage> platformFont = TypeBuilder::CSS::PlatformFontUsage::create()
.setFamilyName(it->key)
.setGlyphCount(it->value);
@@ -1219,12 +1102,12 @@ void InspectorCSSAgent::getStyleSheet(ErrorString* errorString, const String& st
return;
Document* doc = inspectorStyleSheet->pageStyleSheet() ? inspectorStyleSheet->pageStyleSheet()->ownerDocument() : 0;
- if (!doc || !doc->styleResolver())
+ if (!doc)
return;
RefPtr<TypeBuilder::CSS::CSSStyleSheetBody> result = TypeBuilder::CSS::CSSStyleSheetBody::create()
.setStyleSheetId(styleSheetId)
- .setRules(buildArrayForRuleList(inspectorStyleSheet->pageStyleSheet()->rules().get(), doc->styleResolver()));
+ .setRules(buildArrayForRuleList(inspectorStyleSheet->pageStyleSheet()->rules().get(), doc->ensureStyleResolver()));
bool success = inspectorStyleSheet->fillObjectForStyleSheet(result);
if (success)
@@ -1246,9 +1129,9 @@ void InspectorCSSAgent::setStyleSheetText(ErrorString* errorString, const String
if (!inspectorStyleSheet)
return;
- TrackExceptionState es;
- m_domAgent->history()->perform(adoptPtr(new SetStyleSheetTextAction(inspectorStyleSheet, text)), es);
- *errorString = InspectorDOMAgent::toErrorString(es);
+ TrackExceptionState exceptionState;
+ m_domAgent->history()->perform(adoptPtr(new SetStyleSheetTextAction(inspectorStyleSheet, text)), exceptionState);
+ *errorString = InspectorDOMAgent::toErrorString(exceptionState);
}
void InspectorCSSAgent::setStyleText(ErrorString* errorString, const RefPtr<JSONObject>& fullStyleId, const String& text, RefPtr<TypeBuilder::CSS::CSSStyle>& result)
@@ -1260,11 +1143,11 @@ void InspectorCSSAgent::setStyleText(ErrorString* errorString, const RefPtr<JSON
if (!inspectorStyleSheet)
return;
- TrackExceptionState es;
- m_domAgent->history()->perform(adoptPtr(new SetStyleTextAction(inspectorStyleSheet, compoundId, text)), es);
- if (!es.hadException())
+ TrackExceptionState exceptionState;
+ m_domAgent->history()->perform(adoptPtr(new SetStyleTextAction(inspectorStyleSheet, compoundId, text)), exceptionState);
+ if (!exceptionState.hadException())
result = inspectorStyleSheet->buildObjectForStyle(inspectorStyleSheet->styleForId(compoundId));
- *errorString = InspectorDOMAgent::toErrorString(es);
+ *errorString = InspectorDOMAgent::toErrorString(exceptionState);
}
void InspectorCSSAgent::setPropertyText(ErrorString* errorString, const RefPtr<JSONObject>& fullStyleId, int propertyIndex, const String& text, bool overwrite, RefPtr<TypeBuilder::CSS::CSSStyle>& result)
@@ -1276,11 +1159,11 @@ void InspectorCSSAgent::setPropertyText(ErrorString* errorString, const RefPtr<J
if (!inspectorStyleSheet)
return;
- TrackExceptionState es;
- bool success = m_domAgent->history()->perform(adoptPtr(new SetPropertyTextAction(inspectorStyleSheet, compoundId, propertyIndex, text, overwrite)), es);
+ TrackExceptionState exceptionState;
+ bool success = m_domAgent->history()->perform(adoptPtr(new SetPropertyTextAction(inspectorStyleSheet, compoundId, propertyIndex, text, overwrite)), exceptionState);
if (success)
result = inspectorStyleSheet->buildObjectForStyle(inspectorStyleSheet->styleForId(compoundId));
- *errorString = InspectorDOMAgent::toErrorString(es);
+ *errorString = InspectorDOMAgent::toErrorString(exceptionState);
}
void InspectorCSSAgent::toggleProperty(ErrorString* errorString, const RefPtr<JSONObject>& fullStyleId, int propertyIndex, bool disable, RefPtr<TypeBuilder::CSS::CSSStyle>& result)
@@ -1292,11 +1175,11 @@ void InspectorCSSAgent::toggleProperty(ErrorString* errorString, const RefPtr<JS
if (!inspectorStyleSheet)
return;
- TrackExceptionState es;
- bool success = m_domAgent->history()->perform(adoptPtr(new TogglePropertyAction(inspectorStyleSheet, compoundId, propertyIndex, disable)), es);
+ TrackExceptionState exceptionState;
+ bool success = m_domAgent->history()->perform(adoptPtr(new TogglePropertyAction(inspectorStyleSheet, compoundId, propertyIndex, disable)), exceptionState);
if (success)
result = inspectorStyleSheet->buildObjectForStyle(inspectorStyleSheet->styleForId(compoundId));
- *errorString = InspectorDOMAgent::toErrorString(es);
+ *errorString = InspectorDOMAgent::toErrorString(exceptionState);
}
void InspectorCSSAgent::setRuleSelector(ErrorString* errorString, const RefPtr<JSONObject>& fullRuleId, const String& selector, RefPtr<TypeBuilder::CSS::CSSRule>& result)
@@ -1308,14 +1191,14 @@ void InspectorCSSAgent::setRuleSelector(ErrorString* errorString, const RefPtr<J
if (!inspectorStyleSheet)
return;
- TrackExceptionState es;
- bool success = m_domAgent->history()->perform(adoptPtr(new SetRuleSelectorAction(inspectorStyleSheet, compoundId, selector)), es);
+ TrackExceptionState exceptionState;
+ bool success = m_domAgent->history()->perform(adoptPtr(new SetRuleSelectorAction(inspectorStyleSheet, compoundId, selector)), exceptionState);
if (success) {
CSSStyleRule* rule = inspectorStyleSheet->ruleForId(compoundId);
result = inspectorStyleSheet->buildObjectForRule(rule, buildMediaListChain(rule));
}
- *errorString = InspectorDOMAgent::toErrorString(es);
+ *errorString = InspectorDOMAgent::toErrorString(exceptionState);
}
void InspectorCSSAgent::addRule(ErrorString* errorString, const int contextNodeId, const String& selector, RefPtr<TypeBuilder::CSS::CSSRule>& result)
@@ -1330,12 +1213,12 @@ void InspectorCSSAgent::addRule(ErrorString* errorString, const int contextNodeI
return;
}
- TrackExceptionState es;
+ TrackExceptionState exceptionState;
OwnPtr<AddRuleAction> action = adoptPtr(new AddRuleAction(inspectorStyleSheet, selector));
AddRuleAction* rawAction = action.get();
- bool success = m_domAgent->history()->perform(action.release(), es);
+ bool success = m_domAgent->history()->perform(action.release(), exceptionState);
if (!success) {
- *errorString = InspectorDOMAgent::toErrorString(es);
+ *errorString = InspectorDOMAgent::toErrorString(exceptionState);
return;
}
@@ -1459,7 +1342,7 @@ PassRefPtr<TypeBuilder::Array<TypeBuilder::CSS::CSSMedia> > InspectorCSSAgent::b
CSSStyleSheet* parentStyleSheet = 0;
bool isMediaRule = true;
if (parentRule->type() == CSSRule::MEDIA_RULE) {
- CSSMediaRule* mediaRule = static_cast<CSSMediaRule*>(parentRule);
+ CSSMediaRule* mediaRule = toCSSMediaRule(parentRule);
mediaList = mediaRule->media();
parentStyleSheet = mediaRule->parentStyleSheet();
} else if (parentRule->type() == CSSRule::IMPORT_RULE) {
@@ -1559,14 +1442,14 @@ void InspectorCSSAgent::collectAllStyleSheets(Vector<InspectorStyleSheet*>& resu
for (unsigned i = 0; i < list->length(); ++i) {
StyleSheet* styleSheet = list->item(i);
if (styleSheet->isCSSStyleSheet())
- collectStyleSheets(static_cast<CSSStyleSheet*>(styleSheet), result);
+ collectStyleSheets(toCSSStyleSheet(styleSheet), result);
}
}
}
void InspectorCSSAgent::collectStyleSheets(CSSStyleSheet* styleSheet, Vector<InspectorStyleSheet*>& result)
{
- InspectorStyleSheet* inspectorStyleSheet = bindStyleSheet(static_cast<CSSStyleSheet*>(styleSheet));
+ InspectorStyleSheet* inspectorStyleSheet = bindStyleSheet(styleSheet);
result.append(inspectorStyleSheet);
for (unsigned i = 0, size = styleSheet->length(); i < size; ++i) {
CSSRule* rule = styleSheet->item(i);
@@ -1616,11 +1499,11 @@ InspectorStyleSheet* InspectorCSSAgent::viaInspectorStyleSheet(Document* documen
if (inspectorStyleSheet || !createIfAbsent)
return inspectorStyleSheet.get();
- TrackExceptionState es;
- RefPtr<Element> styleElement = document->createElement("style", es);
- if (!es.hadException())
- styleElement->setAttribute("type", "text/css", es);
- if (!es.hadException()) {
+ TrackExceptionState exceptionState;
+ RefPtr<Element> styleElement = document->createElement("style", exceptionState);
+ if (!exceptionState.hadException())
+ styleElement->setAttribute("type", "text/css", exceptionState);
+ if (!exceptionState.hadException()) {
ContainerNode* targetNode;
// HEAD is absent in ImageDocuments, for example.
if (document->head())
@@ -1632,12 +1515,12 @@ InspectorStyleSheet* InspectorCSSAgent::viaInspectorStyleSheet(Document* documen
InlineStyleOverrideScope overrideScope(document);
m_creatingViaInspectorStyleSheet = true;
- targetNode->appendChild(styleElement, es);
+ targetNode->appendChild(styleElement, exceptionState);
// At this point the added stylesheet will get bound through the updateActiveStyleSheets() invocation.
// We just need to pick the respective InspectorStyleSheet from m_documentToInspectorStyleSheet.
m_creatingViaInspectorStyleSheet = false;
}
- if (es.hadException())
+ if (exceptionState.hadException())
return 0;
return m_documentToInspectorStyleSheet.get(document);
@@ -1671,23 +1554,23 @@ TypeBuilder::CSS::StyleSheetOrigin::Enum InspectorCSSAgent::detectOrigin(CSSStyl
return origin;
}
-PassRefPtr<TypeBuilder::CSS::CSSRule> InspectorCSSAgent::buildObjectForRule(CSSStyleRule* rule, StyleResolver* styleResolver)
+PassRefPtr<TypeBuilder::CSS::CSSRule> InspectorCSSAgent::buildObjectForRule(CSSStyleRule* rule, StyleResolver& styleResolver)
{
if (!rule)
return 0;
- // CSSRules returned by StyleResolver::styleRulesForElement lack parent pointers since that infomation is not cheaply available.
+ // CSSRules returned by StyleResolver::cssRulesForElement lack parent pointers since that infomation is not cheaply available.
// Since the inspector wants to walk the parent chain, we construct the full wrappers here.
- // FIXME: This could be factored better. StyleResolver::styleRulesForElement should return a StyleRule vector, not a CSSRuleList.
+ // FIXME: This could be factored better. StyleResolver::cssRulesForElement should return a StyleRule vector, not a CSSRuleList.
if (!rule->parentStyleSheet()) {
- rule = styleResolver->inspectorCSSOMWrappers().getWrapperForRuleInSheets(rule->styleRule(), styleResolver->document().styleEngine());
+ rule = styleResolver.inspectorCSSOMWrappers().getWrapperForRuleInSheets(rule->styleRule(), styleResolver.document().styleEngine());
if (!rule)
return 0;
}
return bindStyleSheet(rule->parentStyleSheet())->buildObjectForRule(rule, buildMediaListChain(rule));
}
-PassRefPtr<TypeBuilder::Array<TypeBuilder::CSS::CSSRule> > InspectorCSSAgent::buildArrayForRuleList(CSSRuleList* ruleList, StyleResolver* styleResolver)
+PassRefPtr<TypeBuilder::Array<TypeBuilder::CSS::CSSRule> > InspectorCSSAgent::buildArrayForRuleList(CSSRuleList* ruleList, StyleResolver& styleResolver)
{
RefPtr<TypeBuilder::Array<TypeBuilder::CSS::CSSRule> > result = TypeBuilder::Array<TypeBuilder::CSS::CSSRule>::create();
if (!ruleList)
@@ -1719,7 +1602,7 @@ static inline bool matchesPseudoElement(const CSSSelector* selector, PseudoId el
return selectorPseudoId == elementPseudoId;
}
-PassRefPtr<TypeBuilder::Array<TypeBuilder::CSS::RuleMatch> > InspectorCSSAgent::buildArrayForMatchedRuleList(CSSRuleList* ruleList, StyleResolver* styleResolver, Element* element)
+PassRefPtr<TypeBuilder::Array<TypeBuilder::CSS::RuleMatch> > InspectorCSSAgent::buildArrayForMatchedRuleList(CSSRuleList* ruleList, StyleResolver& styleResolver, Element* element)
{
RefPtr<TypeBuilder::Array<TypeBuilder::CSS::RuleMatch> > result = TypeBuilder::Array<TypeBuilder::CSS::RuleMatch>::create();
if (!ruleList)
@@ -1763,8 +1646,7 @@ PassRefPtr<TypeBuilder::CSS::CSSStyle> InspectorCSSAgent::buildObjectForAttribut
if (!attributeStyle)
return 0;
- ASSERT(attributeStyle->isMutable());
- MutableStylePropertySet* mutableAttributeStyle = static_cast<MutableStylePropertySet*>(attributeStyle);
+ MutableStylePropertySet* mutableAttributeStyle = toMutableStylePropertySet(attributeStyle);
RefPtr<InspectorStyle> inspectorStyle = InspectorStyle::create(InspectorCSSId(), mutableAttributeStyle->ensureCSSStyleDeclaration(), 0);
return inspectorStyle->buildObjectForStyle();
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InspectorCSSAgent.h b/chromium/third_party/WebKit/Source/core/inspector/InspectorCSSAgent.h
index 207c7875365..aab88549865 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InspectorCSSAgent.h
+++ b/chromium/third_party/WebKit/Source/core/inspector/InspectorCSSAgent.h
@@ -30,8 +30,9 @@
#include "core/inspector/InspectorBaseAgent.h"
#include "core/inspector/InspectorDOMAgent.h"
#include "core/inspector/InspectorStyleSheet.h"
-#include "core/page/ContentSecurityPolicy.h"
-#include "core/platform/JSONValues.h"
+#include "core/frame/ContentSecurityPolicy.h"
+#include "platform/JSONValues.h"
+#include "wtf/HashCountedSet.h"
#include "wtf/HashMap.h"
#include "wtf/HashSet.h"
#include "wtf/PassRefPtr.h"
@@ -56,6 +57,7 @@ class MediaList;
class Node;
class NodeList;
class PlatformFontUsage;
+class RenderText;
class StyleResolver;
class UpdateRegionLayoutTask;
@@ -94,7 +96,6 @@ public:
};
static CSSStyleRule* asCSSStyleRule(CSSRule*);
- static bool cssErrorFilter(const CSSParserString& content, int propertyId, int errorType);
static PassOwnPtr<InspectorCSSAgent> create(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* state, InspectorDOMAgent* domAgent, InspectorPageAgent* pageAgent, InspectorResourceAgent* resourceAgent)
{
@@ -114,6 +115,10 @@ public:
void mediaQueryResultChanged();
void didCreateNamedFlow(Document*, NamedFlow*);
void willRemoveNamedFlow(Document*, NamedFlow*);
+ void willMutateRules();
+ void didMutateRules(CSSStyleSheet*);
+ void willMutateStyle();
+ void didMutateStyle(CSSStyleDeclaration*, bool);
private:
void regionLayoutUpdated(NamedFlow*, int documentNodeId);
@@ -171,17 +176,18 @@ private:
void collectAllStyleSheets(Vector<InspectorStyleSheet*>&);
void collectStyleSheets(CSSStyleSheet*, Vector<InspectorStyleSheet*>&);
- void collectPlatformFontsForRenderer(RenderText*, HashMap<String, int>*);
+ void collectPlatformFontsForRenderer(RenderText*, HashCountedSet<String>*);
InspectorStyleSheet* bindStyleSheet(CSSStyleSheet*);
String unbindStyleSheet(InspectorStyleSheet*);
InspectorStyleSheet* viaInspectorStyleSheet(Document*, bool createIfAbsent);
InspectorStyleSheet* assertStyleSheetForId(ErrorString*, const String&);
TypeBuilder::CSS::StyleSheetOrigin::Enum detectOrigin(CSSStyleSheet* pageStyleSheet, Document* ownerDocument);
+ bool styleSheetEditInProgress() const { return m_styleSheetsPendingMutation || m_styleDeclarationPendingMutation || m_isSettingStyleSheetText; }
- PassRefPtr<TypeBuilder::CSS::CSSRule> buildObjectForRule(CSSStyleRule*, StyleResolver*);
- PassRefPtr<TypeBuilder::Array<TypeBuilder::CSS::CSSRule> > buildArrayForRuleList(CSSRuleList*, StyleResolver*);
- PassRefPtr<TypeBuilder::Array<TypeBuilder::CSS::RuleMatch> > buildArrayForMatchedRuleList(CSSRuleList*, StyleResolver*, Element*);
+ PassRefPtr<TypeBuilder::CSS::CSSRule> buildObjectForRule(CSSStyleRule*, StyleResolver&);
+ PassRefPtr<TypeBuilder::Array<TypeBuilder::CSS::CSSRule> > buildArrayForRuleList(CSSRuleList*, StyleResolver&);
+ PassRefPtr<TypeBuilder::Array<TypeBuilder::CSS::RuleMatch> > buildArrayForMatchedRuleList(CSSRuleList*, StyleResolver&, Element*);
PassRefPtr<TypeBuilder::CSS::CSSStyle> buildObjectForAttributesStyle(Element*);
PassRefPtr<TypeBuilder::Array<TypeBuilder::CSS::Region> > buildArrayForRegions(ErrorString*, PassRefPtr<NodeList>, int documentNodeId);
PassRefPtr<TypeBuilder::CSS::NamedFlow> buildObjectForNamedFlow(ErrorString*, NamedFlow*, int documentNodeId);
@@ -191,7 +197,7 @@ private:
virtual void didRemoveDOMNode(Node*);
virtual void didModifyDOMAttr(Element*);
- // InspectorCSSAgent::Listener implementation
+ // InspectorStyleSheet::Listener implementation
virtual void styleSheetChanged(InspectorStyleSheet*) OVERRIDE;
virtual void willReparseStyleSheet() OVERRIDE;
virtual void didReparseStyleSheet() OVERRIDE;
@@ -213,6 +219,8 @@ private:
OwnPtr<ChangeRegionOversetTask> m_changeRegionOversetTask;
int m_lastStyleSheetId;
+ int m_styleSheetsPendingMutation;
+ bool m_styleDeclarationPendingMutation;
bool m_creatingViaInspectorStyleSheet;
bool m_isSettingStyleSheetText;
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InspectorCanvasAgent.cpp b/chromium/third_party/WebKit/Source/core/inspector/InspectorCanvasAgent.cpp
index 294770e0099..5a03d88a17a 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InspectorCanvasAgent.cpp
+++ b/chromium/third_party/WebKit/Source/core/inspector/InspectorCanvasAgent.cpp
@@ -32,10 +32,8 @@
#include "core/inspector/InspectorCanvasAgent.h"
#include "HTMLNames.h"
-#include "InspectorFrontend.h"
#include "bindings/v8/ScriptObject.h"
#include "bindings/v8/ScriptProfiler.h"
-#include "bindings/v8/ScriptState.h"
#include "core/html/HTMLCanvasElement.h"
#include "core/inspector/BindingVisitors.h"
#include "core/inspector/InjectedScript.h"
@@ -45,8 +43,8 @@
#include "core/inspector/InspectorState.h"
#include "core/inspector/InstrumentingAgents.h"
#include "core/loader/DocumentLoader.h"
-#include "core/page/DOMWindow.h"
-#include "core/page/Frame.h"
+#include "core/frame/DOMWindow.h"
+#include "core/frame/Frame.h"
using WebCore::TypeBuilder::Array;
using WebCore::TypeBuilder::Canvas::ResourceId;
@@ -325,7 +323,7 @@ void InspectorCanvasAgent::didCommitLoad(Frame*, DocumentLoader* loader)
String frameId = m_pageAgent->frameId(frame);
m_frontend->traceLogsRemoved(&frameId, 0);
}
- frame = frame->tree()->traverseNext();
+ frame = frame->tree().traverseNext();
}
}
}
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InspectorClient.cpp b/chromium/third_party/WebKit/Source/core/inspector/InspectorClient.cpp
index 1e4c29d289d..bc0bcd7ef00 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InspectorClient.cpp
+++ b/chromium/third_party/WebKit/Source/core/inspector/InspectorClient.cpp
@@ -33,7 +33,7 @@
#include "bindings/v8/ScriptController.h"
#include "bindings/v8/ScriptSourceCode.h"
-#include "core/page/Frame.h"
+#include "core/frame/Frame.h"
#include "core/page/Page.h"
namespace WebCore {
@@ -47,14 +47,7 @@ bool InspectorClient::doDispatchMessageOnFrontendPage(Page* frontendPage, const
if (!frame)
return false;
- ScriptController* scriptController = frame->script();
- if (!scriptController)
- return false;
-
- String dispatchToFrontend = "InspectorFrontendAPI.dispatchMessageAsync(" + message + ");";
-
- // FIXME: This should execute the script in the appropriate world.
- scriptController->executeScriptInMainWorld(ScriptSourceCode(dispatchToFrontend));
+ frame->script().executeScriptInMainWorld("InspectorFrontendAPI.dispatchMessageAsync(" + message + ");", ScriptController::ExecuteScriptWhenScriptsDisabled);
return true;
}
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InspectorClient.h b/chromium/third_party/WebKit/Source/core/inspector/InspectorClient.h
index da449a3552e..4a69725f62f 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InspectorClient.h
+++ b/chromium/third_party/WebKit/Source/core/inspector/InspectorClient.h
@@ -34,6 +34,7 @@
namespace WebCore {
+class IntPoint;
class Page;
class PlatformKeyboardEvent;
class PlatformMouseEvent;
@@ -48,11 +49,13 @@ public:
typedef void (*TraceEventCallback)(char phase, const unsigned char*, const char* name, unsigned long long id,
int numArgs, const char* const* argNames, const unsigned char* argTypes, const unsigned long long* argValues,
- unsigned char flags);
+ unsigned char flags, double timestamp);
virtual void setTraceEventCallback(TraceEventCallback) { }
- virtual void overrideDeviceMetrics(int /*width*/, int /*height*/, float /*fontScaleFactor*/, bool /*fitWindow*/) { }
- virtual void autoZoomPageToFitWidth() { }
+ virtual void startGPUEventsRecording() { }
+ virtual void stopGPUEventsRecording() { }
+
+ virtual void overrideDeviceMetrics(int /*width*/, int /*height*/, float /*deviceScaleFactor*/, bool /*emulateViewport*/, bool /*fitWindow*/) { }
virtual bool overridesShowPaintRects() { return false; }
virtual void setShowPaintRects(bool) { }
@@ -61,6 +64,7 @@ public:
virtual void setContinuousPaintingEnabled(bool) { }
virtual void setShowScrollBottleneckRects(bool) { }
+ virtual void requestPageScaleFactor(float scale, const IntPoint& origin) { }
virtual void getAllocatedObjects(HashSet<const void*>&) { }
virtual void dumpUncountedAllocatedObjects(const HashMap<const void*, size_t>&) { }
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InspectorConsoleAgent.cpp b/chromium/third_party/WebKit/Source/core/inspector/InspectorConsoleAgent.cpp
index 8ad03e4df3f..06f9e6a05c9 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InspectorConsoleAgent.cpp
+++ b/chromium/third_party/WebKit/Source/core/inspector/InspectorConsoleAgent.cpp
@@ -26,11 +26,11 @@
#include "config.h"
#include "core/inspector/InspectorConsoleAgent.h"
-#include "InspectorFrontend.h"
#include "bindings/v8/ScriptCallStackFactory.h"
#include "bindings/v8/ScriptController.h"
#include "bindings/v8/ScriptObject.h"
#include "bindings/v8/ScriptProfiler.h"
+#include "core/frame/Frame.h"
#include "core/inspector/ConsoleMessage.h"
#include "core/inspector/InjectedScriptHost.h"
#include "core/inspector/InjectedScriptManager.h"
@@ -41,10 +41,9 @@
#include "core/inspector/ScriptCallFrame.h"
#include "core/inspector/ScriptCallStack.h"
#include "core/loader/DocumentLoader.h"
-#include "core/page/Frame.h"
#include "core/page/Page.h"
-#include "core/platform/network/ResourceError.h"
-#include "core/platform/network/ResourceResponse.h"
+#include "platform/network/ResourceError.h"
+#include "platform/network/ResourceResponse.h"
#include "wtf/CurrentTime.h"
#include "wtf/OwnPtr.h"
#include "wtf/PassOwnPtr.h"
@@ -193,7 +192,7 @@ Vector<unsigned> InspectorConsoleAgent::consoleMessageArgumentCounts()
return result;
}
-void InspectorConsoleAgent::consoleTime(ScriptExecutionContext*, const String& title)
+void InspectorConsoleAgent::consoleTime(ExecutionContext*, const String& title)
{
// Follow Firebug's behavior of requiring a title that is not null or
// undefined for timing functions
@@ -203,7 +202,7 @@ void InspectorConsoleAgent::consoleTime(ScriptExecutionContext*, const String& t
m_times.add(title, monotonicallyIncreasingTime());
}
-void InspectorConsoleAgent::consoleTimeEnd(ScriptExecutionContext*, const String& title, ScriptState* state)
+void InspectorConsoleAgent::consoleTimeEnd(ExecutionContext*, const String& title, ScriptState* state)
{
// Follow Firebug's behavior of requiring a title that is not null or
// undefined for timing functions
@@ -222,19 +221,19 @@ void InspectorConsoleAgent::consoleTimeEnd(ScriptExecutionContext*, const String
addMessageToConsole(ConsoleAPIMessageSource, LogMessageType, DebugMessageLevel, message, String(), 0, 0, state);
}
-void InspectorConsoleAgent::consoleTimeline(ScriptExecutionContext* context, const String& title, ScriptState* state)
+void InspectorConsoleAgent::consoleTimeline(ExecutionContext* context, const String& title, ScriptState* state)
{
m_timelineAgent->consoleTimeline(context, title, state);
}
-void InspectorConsoleAgent::consoleTimelineEnd(ScriptExecutionContext* context, const String& title, ScriptState* state)
+void InspectorConsoleAgent::consoleTimelineEnd(ExecutionContext* context, const String& title, ScriptState* state)
{
m_timelineAgent->consoleTimelineEnd(context, title, state);
}
void InspectorConsoleAgent::consoleCount(ScriptState* state, PassRefPtr<ScriptArguments> arguments)
{
- RefPtr<ScriptCallStack> callStack(createScriptCallStackForConsole(state));
+ RefPtr<ScriptCallStack> callStack(createScriptCallStackForConsole());
const ScriptCallFrame& lastCaller = callStack->at(0);
// Follow Firebug's behavior of counting with null and undefined title in
// the same bucket as no argument
@@ -243,18 +242,8 @@ void InspectorConsoleAgent::consoleCount(ScriptState* state, PassRefPtr<ScriptAr
String identifier = title.isEmpty() ? String(lastCaller.sourceURL() + ':' + String::number(lastCaller.lineNumber()))
: String(title + '@');
- HashMap<String, unsigned>::iterator it = m_counts.find(identifier);
- int count;
- if (it == m_counts.end())
- count = 1;
- else {
- count = it->value + 1;
- m_counts.remove(it);
- }
-
- m_counts.add(identifier, count);
-
- String message = title + ": " + String::number(count);
+ HashCountedSet<String>::AddResult result = m_counts.add(identifier);
+ String message = title + ": " + String::number(result.iterator->value);
addMessageToConsole(ConsoleAPIMessageSource, LogMessageType, DebugMessageLevel, message, callStack);
}
@@ -273,7 +262,7 @@ void InspectorConsoleAgent::didCommitLoad(Frame* frame, DocumentLoader* loader)
reset();
}
-void InspectorConsoleAgent::didFinishXHRLoading(ThreadableLoaderClient*, unsigned long requestIdentifier, ScriptString, const String& url, const String& sendURL, unsigned sendLineNumber)
+void InspectorConsoleAgent::didFinishXHRLoading(XMLHttpRequest*, ThreadableLoaderClient*, unsigned long requestIdentifier, ScriptString, const String& url, const String& sendURL, unsigned sendLineNumber)
{
if (m_frontend && m_state->getBoolean(ConsoleAgentState::monitoringXHR)) {
String message = "XHR finished loading: \"" + url + "\".";
@@ -281,7 +270,7 @@ void InspectorConsoleAgent::didFinishXHRLoading(ThreadableLoaderClient*, unsigne
}
}
-void InspectorConsoleAgent::didReceiveResourceResponse(unsigned long requestIdentifier, DocumentLoader* loader, const ResourceResponse& response, ResourceLoader* resourceLoader)
+void InspectorConsoleAgent::didReceiveResourceResponse(Frame*, unsigned long requestIdentifier, DocumentLoader* loader, const ResourceResponse& response, ResourceLoader* resourceLoader)
{
if (!loader)
return;
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InspectorConsoleAgent.h b/chromium/third_party/WebKit/Source/core/inspector/InspectorConsoleAgent.h
index a76b1b624cc..142728f5744 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InspectorConsoleAgent.h
+++ b/chromium/third_party/WebKit/Source/core/inspector/InspectorConsoleAgent.h
@@ -30,8 +30,9 @@
#include "bindings/v8/ScriptString.h"
#include "core/inspector/ConsoleAPITypes.h"
#include "core/inspector/InspectorBaseAgent.h"
-#include "core/page/ConsoleTypes.h"
+#include "core/frame/ConsoleTypes.h"
#include "wtf/Forward.h"
+#include "wtf/HashCountedSet.h"
#include "wtf/HashMap.h"
#include "wtf/Noncopyable.h"
#include "wtf/Vector.h"
@@ -54,6 +55,7 @@ class ScriptArguments;
class ScriptCallStack;
class ScriptProfile;
class ThreadableLoaderClient;
+class XMLHttpRequest;
typedef String ErrorString;
@@ -81,18 +83,18 @@ public:
Vector<unsigned> consoleMessageArgumentCounts();
- void consoleTime(ScriptExecutionContext*, const String& title);
- void consoleTimeEnd(ScriptExecutionContext*, const String& title, ScriptState*);
- void consoleTimeline(ScriptExecutionContext*, const String& title, ScriptState*);
- void consoleTimelineEnd(ScriptExecutionContext*, const String& title, ScriptState*);
+ void consoleTime(ExecutionContext*, const String& title);
+ void consoleTimeEnd(ExecutionContext*, const String& title, ScriptState*);
+ void consoleTimeline(ExecutionContext*, const String& title, ScriptState*);
+ void consoleTimelineEnd(ExecutionContext*, const String& title, ScriptState*);
void consoleCount(ScriptState*, PassRefPtr<ScriptArguments>);
void frameWindowDiscarded(DOMWindow*);
void didCommitLoad(Frame*, DocumentLoader*);
- void didFinishXHRLoading(ThreadableLoaderClient*, unsigned long requestIdentifier, ScriptString, const String& url, const String& sendURL, unsigned sendLineNumber);
- void didReceiveResourceResponse(unsigned long requestIdentifier, DocumentLoader*, const ResourceResponse& response, ResourceLoader*);
+ void didFinishXHRLoading(XMLHttpRequest*, ThreadableLoaderClient*, unsigned long requestIdentifier, ScriptString, const String& url, const String& sendURL, unsigned sendLineNumber);
+ void didReceiveResourceResponse(Frame*, unsigned long requestIdentifier, DocumentLoader*, const ResourceResponse&, ResourceLoader*);
void didFailLoading(unsigned long requestIdentifier, DocumentLoader*, const ResourceError&);
void addProfileFinishedMessageToConsole(PassRefPtr<ScriptProfile>, unsigned lineNumber, const String& sourceURL);
void addStartProfilingMessageToConsole(const String& title, unsigned lineNumber, const String& sourceURL);
@@ -111,7 +113,7 @@ protected:
ConsoleMessage* m_previousMessage;
Vector<OwnPtr<ConsoleMessage> > m_consoleMessages;
int m_expiredConsoleMessageCount;
- HashMap<String, unsigned> m_counts;
+ HashCountedSet<String> m_counts;
HashMap<String, double> m_times;
bool m_enabled;
private:
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InspectorController.cpp b/chromium/third_party/WebKit/Source/core/inspector/InspectorController.cpp
index 963282e2ef4..0e3f017eb8c 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InspectorController.cpp
+++ b/chromium/third_party/WebKit/Source/core/inspector/InspectorController.cpp
@@ -39,7 +39,6 @@
#include "core/inspector/InjectedScriptManager.h"
#include "core/inspector/InspectorAgent.h"
#include "core/inspector/InspectorApplicationCacheAgent.h"
-#include "core/inspector/InspectorBaseAgent.h"
#include "core/inspector/InspectorCSSAgent.h"
#include "core/inspector/InspectorCanvasAgent.h"
#include "core/inspector/InspectorClient.h"
@@ -68,7 +67,7 @@
#include "core/inspector/PageDebuggerAgent.h"
#include "core/inspector/PageRuntimeAgent.h"
#include "core/page/Page.h"
-#include "core/platform/PlatformMouseEvent.h"
+#include "platform/PlatformMouseEvent.h"
namespace WebCore {
@@ -91,7 +90,7 @@ InspectorController::InspectorController(Page* page, InspectorClient* inspectorC
InspectorDOMAgent* domAgent = domAgentPtr.get();
m_agents.append(domAgentPtr.release());
- OwnPtr<InspectorResourceAgent> resourceAgentPtr(InspectorResourceAgent::create(m_instrumentingAgents.get(), pageAgent, inspectorClient, m_state.get(), m_overlay.get()));
+ OwnPtr<InspectorResourceAgent> resourceAgentPtr(InspectorResourceAgent::create(m_instrumentingAgents.get(), pageAgent, inspectorClient, m_state.get()));
InspectorResourceAgent* resourceAgent = resourceAgentPtr.get();
m_agents.append(resourceAgentPtr.release());
@@ -109,7 +108,7 @@ InspectorController::InspectorController(Page* page, InspectorClient* inspectorC
m_memoryAgent = memoryAgentPtr.get();
m_agents.append(memoryAgentPtr.release());
- OwnPtr<InspectorTimelineAgent> timelineAgentPtr(InspectorTimelineAgent::create(m_instrumentingAgents.get(), pageAgent, m_memoryAgent, domAgent, m_state.get(),
+ OwnPtr<InspectorTimelineAgent> timelineAgentPtr(InspectorTimelineAgent::create(m_instrumentingAgents.get(), pageAgent, m_memoryAgent, domAgent, m_overlay.get(), m_state.get(),
InspectorTimelineAgent::PageInspector, inspectorClient));
m_timelineAgent = timelineAgentPtr.get();
m_agents.append(timelineAgentPtr.release());
@@ -120,9 +119,7 @@ InspectorController::InspectorController(Page* page, InspectorClient* inspectorC
m_agents.append(PageRuntimeAgent::create(m_instrumentingAgents.get(), m_state.get(), m_injectedScriptManager.get(), pageScriptDebugServer, page, pageAgent));
- OwnPtr<InspectorConsoleAgent> consoleAgentPtr(PageConsoleAgent::create(m_instrumentingAgents.get(), m_state.get(), m_injectedScriptManager.get(), domAgent, m_timelineAgent));
- InspectorConsoleAgent* consoleAgent = consoleAgentPtr.get();
- m_agents.append(consoleAgentPtr.release());
+ m_agents.append(PageConsoleAgent::create(m_instrumentingAgents.get(), m_state.get(), m_injectedScriptManager.get(), domAgent, m_timelineAgent));
OwnPtr<InspectorDebuggerAgent> debuggerAgentPtr(PageDebuggerAgent::create(m_instrumentingAgents.get(), m_state.get(), pageScriptDebugServer, pageAgent, m_injectedScriptManager.get(), m_overlay.get()));
InspectorDebuggerAgent* debuggerAgent = debuggerAgentPtr.get();
@@ -130,7 +127,7 @@ InspectorController::InspectorController(Page* page, InspectorClient* inspectorC
m_agents.append(InspectorDOMDebuggerAgent::create(m_instrumentingAgents.get(), m_state.get(), domAgent, debuggerAgent));
- m_agents.append(InspectorProfilerAgent::create(m_instrumentingAgents.get(), consoleAgent, m_state.get(), m_injectedScriptManager.get()));
+ m_agents.append(InspectorProfilerAgent::create(m_instrumentingAgents.get(), m_state.get(), m_injectedScriptManager.get(), m_overlay.get()));
m_agents.append(InspectorHeapProfilerAgent::create(m_instrumentingAgents.get(), m_state.get(), m_injectedScriptManager.get()));
@@ -298,11 +295,6 @@ void InspectorController::inspect(Node* node)
injectedScript.inspectNode(node);
}
-Page* InspectorController::inspectedPage() const
-{
- return m_page;
-}
-
void InspectorController::setInjectedScriptForOrigin(const String& origin, const String& source)
{
if (InspectorAgent* inspectorAgent = m_instrumentingAgents->inspectorAgent())
@@ -360,6 +352,25 @@ bool InspectorController::handleTouchEvent(Frame* frame, const PlatformTouchEven
return false;
}
+bool InspectorController::handleKeyboardEvent(Frame* frame, const PlatformKeyboardEvent& event)
+{
+ // Overlay should not consume events.
+ m_overlay->handleKeyboardEvent(event);
+ return false;
+}
+
+void InspectorController::requestPageScaleFactor(float scale, const IntPoint& origin)
+{
+ m_inspectorClient->requestPageScaleFactor(scale, origin);
+}
+
+bool InspectorController::deviceEmulationEnabled()
+{
+ if (InspectorPageAgent* pageAgent = m_instrumentingAgents->inspectorPageAgent())
+ return pageAgent->deviceMetricsOverrideEnabled();
+ return false;
+}
+
void InspectorController::resume()
{
if (InspectorDebuggerAgent* debuggerAgent = m_instrumentingAgents->inspectorDebuggerAgent()) {
@@ -392,10 +403,10 @@ void InspectorController::didProcessTask()
domDebuggerAgent->didProcessTask();
}
-void InspectorController::didBeginFrame()
+void InspectorController::didBeginFrame(int frameId)
{
if (InspectorTimelineAgent* timelineAgent = m_instrumentingAgents->inspectorTimelineAgent())
- timelineAgent->didBeginFrame();
+ timelineAgent->didBeginFrame(frameId);
if (InspectorCanvasAgent* canvasAgent = m_instrumentingAgents->inspectorCanvasAgent())
canvasAgent->didBeginFrame();
}
@@ -418,4 +429,10 @@ void InspectorController::didComposite()
timelineAgent->didComposite();
}
+void InspectorController::processGPUEvent(double timestamp, int phase, bool foreign, size_t usedGPUMemoryBytes)
+{
+ if (InspectorTimelineAgent* timelineAgent = m_instrumentingAgents->inspectorTimelineAgent())
+ timelineAgent->processGPUEvent(InspectorTimelineAgent::GPUEvent(timestamp, phase, foreign, usedGPUMemoryBytes));
+}
+
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InspectorController.h b/chromium/third_party/WebKit/Source/core/inspector/InspectorController.h
index 95f036886a2..f8e9af7a29a 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InspectorController.h
+++ b/chromium/third_party/WebKit/Source/core/inspector/InspectorController.h
@@ -53,9 +53,11 @@ class InspectorTimelineAgent;
class InspectorOverlay;
class InspectorState;
class InstrumentingAgents;
+class IntPoint;
class IntSize;
class Page;
class PlatformGestureEvent;
+class PlatformKeyboardEvent;
class PlatformMouseEvent;
class PlatformTouchEvent;
class PostWorkerNotificationToFrontendTask;
@@ -72,15 +74,12 @@ public:
static PassOwnPtr<InspectorController> create(Page*, InspectorClient*);
void inspectedPageDestroyed();
- Page* inspectedPage() const;
-
void setInspectorFrontendClient(PassOwnPtr<InspectorFrontendClient>);
void didClearWindowObjectInWorld(Frame*, DOMWrapperWorld*);
void setInjectedScriptForOrigin(const String& origin, const String& source);
void dispatchMessageFromFrontend(const String& message);
- bool hasFrontend() const { return m_inspectorFrontend; }
void connectFrontend(InspectorFrontendChannel*);
void disconnectFrontend();
void reconnectFrontend();
@@ -98,6 +97,10 @@ public:
bool handleGestureEvent(Frame*, const PlatformGestureEvent&);
bool handleMouseEvent(Frame*, const PlatformMouseEvent&);
bool handleTouchEvent(Frame*, const PlatformTouchEvent&);
+ bool handleKeyboardEvent(Frame*, const PlatformKeyboardEvent&);
+
+ void requestPageScaleFactor(float scale, const IntPoint& origin);
+ bool deviceEmulationEnabled();
bool isUnderTest();
void evaluateForTestInFrontend(long callId, const String& script);
@@ -106,16 +109,16 @@ public:
void setResourcesDataSizeLimitsFromInternals(int maximumResourcesContentSize, int maximumSingleResourceContentSize);
- InspectorClient* inspectorClient() const { return m_inspectorClient; }
-
void willProcessTask();
void didProcessTask();
- void didBeginFrame();
+ void didBeginFrame(int frameId);
void didCancelFrame();
void willComposite();
void didComposite();
+ void processGPUEvent(double timestamp, int phase, bool foreign, size_t usedGPUMemoryBytes);
+
private:
InspectorController(Page*, InspectorClient*);
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InspectorCounters.cpp b/chromium/third_party/WebKit/Source/core/inspector/InspectorCounters.cpp
index 5082e09b20d..2e81a9848ec 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InspectorCounters.cpp
+++ b/chromium/third_party/WebKit/Source/core/inspector/InspectorCounters.cpp
@@ -31,8 +31,6 @@
#include "config.h"
#include "core/inspector/InspectorCounters.h"
-#include "core/platform/ThreadGlobalData.h"
-
namespace WebCore {
int InspectorCounters::s_counters[CounterTypeLength];
@@ -42,21 +40,5 @@ int InspectorCounters::counterValue(CounterType type)
return s_counters[type];
}
-ThreadLocalInspectorCounters::ThreadLocalInspectorCounters()
-{
- for (size_t i = 0; i < CounterTypeLength; i++)
- m_counters[i] = 0;
-}
-
-int ThreadLocalInspectorCounters::counterValue(CounterType type)
-{
- return m_counters[type];
-}
-
-ThreadLocalInspectorCounters& ThreadLocalInspectorCounters::current()
-{
- return threadGlobalData().inspectorCounters();
-}
-
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InspectorCounters.h b/chromium/third_party/WebKit/Source/core/inspector/InspectorCounters.h
index 893f941e9c7..93e8284ef1a 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InspectorCounters.h
+++ b/chromium/third_party/WebKit/Source/core/inspector/InspectorCounters.h
@@ -68,34 +68,6 @@ private:
static int s_counters[CounterTypeLength];
};
-
-class ThreadLocalInspectorCounters {
- WTF_MAKE_FAST_ALLOCATED;
-public:
- enum CounterType {
- JSEventListenerCounter,
- CounterTypeLength
- };
- ThreadLocalInspectorCounters();
-
- inline void incrementCounter(CounterType type)
- {
- ++m_counters[type];
- }
-
- inline void decrementCounter(CounterType type)
- {
- --m_counters[type];
- }
-
- int counterValue(CounterType);
-
- static ThreadLocalInspectorCounters& current();
-
-private:
- int m_counters[CounterTypeLength];
-};
-
} // namespace WebCore
#endif // !defined(InspectorCounters_h)
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InspectorDOMAgent.cpp b/chromium/third_party/WebKit/Source/core/inspector/InspectorDOMAgent.cpp
index 1270a5e92e0..a8f12bb7446 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InspectorDOMAgent.cpp
+++ b/chromium/third_party/WebKit/Source/core/inspector/InspectorDOMAgent.cpp
@@ -32,7 +32,6 @@
#include "core/inspector/InspectorDOMAgent.h"
#include "HTMLNames.h"
-#include "InspectorFrontend.h"
#include "bindings/v8/ExceptionState.h"
#include "bindings/v8/ScriptEventListener.h"
#include "core/dom/Attr.h"
@@ -43,8 +42,8 @@
#include "core/dom/DocumentFragment.h"
#include "core/dom/DocumentType.h"
#include "core/dom/Element.h"
-#include "core/dom/EventListener.h"
-#include "core/dom/EventTarget.h"
+#include "core/events/EventListener.h"
+#include "core/events/EventTarget.h"
#include "core/dom/Node.h"
#include "core/dom/NodeList.h"
#include "core/dom/NodeTraversal.h"
@@ -61,27 +60,23 @@
#include "core/inspector/DOMEditor.h"
#include "core/inspector/DOMPatchSupport.h"
#include "core/inspector/IdentifiersFactory.h"
-#include "core/inspector/InjectedScriptManager.h"
#include "core/inspector/InspectorHistory.h"
#include "core/inspector/InspectorOverlay.h"
#include "core/inspector/InspectorPageAgent.h"
#include "core/inspector/InspectorState.h"
#include "core/inspector/InstrumentingAgents.h"
#include "core/loader/DocumentLoader.h"
-#include "core/page/Frame.h"
+#include "core/frame/Frame.h"
#include "core/page/FrameTree.h"
#include "core/page/Page.h"
-#include "core/platform/PlatformGestureEvent.h"
-#include "core/platform/PlatformMouseEvent.h"
-#include "core/platform/PlatformTouchEvent.h"
#include "core/rendering/HitTestResult.h"
#include "core/rendering/RenderView.h"
#include "core/xml/DocumentXPathEvaluator.h"
#include "core/xml/XPathResult.h"
-#include "wtf/HashSet.h"
+#include "platform/PlatformGestureEvent.h"
+#include "platform/PlatformMouseEvent.h"
+#include "platform/PlatformTouchEvent.h"
#include "wtf/ListHashSet.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/Vector.h"
#include "wtf/text/CString.h"
#include "wtf/text/WTFString.h"
@@ -158,7 +153,7 @@ static Node* hoveredNodeForPoint(Frame* frame, const IntPoint& point, bool ignor
HitTestRequest request(hitType);
HitTestResult result(frame->view()->windowToContents(point));
frame->contentRenderer()->hitTest(request, result);
- Node* node = result.innerNode();
+ Node* node = result.innerPossiblyPseudoNode();
while (node && node->nodeType() == Node::TEXT_NODE)
node = node->parentNode();
return node;
@@ -220,10 +215,10 @@ void RevalidateStyleAttributeTask::onTimer(Timer<RevalidateStyleAttributeTask>*)
m_elements.clear();
}
-String InspectorDOMAgent::toErrorString(ExceptionState& es)
+String InspectorDOMAgent::toErrorString(ExceptionState& exceptionState)
{
- if (es.hadException())
- return DOMException::getErrorName(es.code());
+ if (exceptionState.hadException())
+ return DOMException::getErrorName(exceptionState.code());
return "";
}
@@ -286,7 +281,7 @@ void InspectorDOMAgent::restore()
Vector<Document*> InspectorDOMAgent::documents()
{
Vector<Document*> result;
- for (Frame* frame = m_document->frame(); frame; frame = frame->tree()->traverseNext()) {
+ for (Frame* frame = m_document->frame(); frame; frame = frame->tree().traverseNext()) {
Document* document = frame->document();
if (!document)
continue;
@@ -523,7 +518,7 @@ int InspectorDOMAgent::pushNodeToFrontend(ErrorString* errorString, int document
Document* document = assertDocument(errorString, documentNodeId);
if (!document)
return 0;
- if (&nodeToPush->document() != document) {
+ if (nodeToPush->document() != document) {
*errorString = "Node is not part of the document with given id";
return 0;
}
@@ -567,9 +562,9 @@ void InspectorDOMAgent::querySelector(ErrorString* errorString, int nodeId, cons
if (!node)
return;
- TrackExceptionState es;
- RefPtr<Element> element = node->querySelector(selectors, es);
- if (es.hadException()) {
+ TrackExceptionState exceptionState;
+ RefPtr<Element> element = node->querySelector(selectors, exceptionState);
+ if (exceptionState.hadException()) {
*errorString = "DOM Error while querying";
return;
}
@@ -584,9 +579,9 @@ void InspectorDOMAgent::querySelectorAll(ErrorString* errorString, int nodeId, c
if (!node)
return;
- TrackExceptionState es;
- RefPtr<NodeList> nodes = node->querySelectorAll(selectors, es);
- if (es.hadException()) {
+ TrackExceptionState exceptionState;
+ RefPtr<NodeList> nodes = node->querySelectorAll(selectors, exceptionState);
+ if (exceptionState.hadException()) {
*errorString = "DOM Error while querying";
return;
}
@@ -767,9 +762,9 @@ void InspectorDOMAgent::setNodeName(ErrorString* errorString, int nodeId, const
if (!oldNode || !oldNode->isElementNode())
return;
- TrackExceptionState es;
- RefPtr<Element> newElem = oldNode->document().createElement(tagName, es);
- if (es.hadException())
+ TrackExceptionState exceptionState;
+ RefPtr<Element> newElem = oldNode->document().createElement(tagName, exceptionState);
+ if (exceptionState.hadException())
return;
// Copy over the original node's attributes.
@@ -954,7 +949,7 @@ void InspectorDOMAgent::performSearch(ErrorString*, const String& whitespaceTrim
continue;
// Manual plain text search.
- while ((node = NodeTraversal::next(node, document->documentElement()))) {
+ while ((node = NodeTraversal::next(*node, document->documentElement()))) {
switch (node->nodeType()) {
case Node::TEXT_NODE:
case Node::COMMENT_NODE:
@@ -981,11 +976,11 @@ void InspectorDOMAgent::performSearch(ErrorString*, const String& whitespaceTrim
for (unsigned i = 0; i < numAttrs; ++i) {
// Add attribute pair
const Attribute* attribute = element->attributeItem(i);
- if (attribute->localName().find(whitespaceTrimmedQuery) != kNotFound) {
+ if (attribute->localName().find(whitespaceTrimmedQuery, 0, false) != kNotFound) {
resultCollector.add(node);
break;
}
- size_t foundPosition = attribute->value().find(attributeQuery);
+ size_t foundPosition = attribute->value().find(attributeQuery, 0, false);
if (foundPosition != kNotFound) {
if (!exactAttributeMatch || (!foundPosition && attribute->value().length() == attributeQuery.length())) {
resultCollector.add(node);
@@ -1003,15 +998,15 @@ void InspectorDOMAgent::performSearch(ErrorString*, const String& whitespaceTrim
// XPath evaluation
for (Vector<Document*>::iterator it = docs.begin(); it != docs.end(); ++it) {
Document* document = *it;
- TrackExceptionState es;
- RefPtr<XPathResult> result = DocumentXPathEvaluator::evaluate(document, whitespaceTrimmedQuery, document, 0, XPathResult::ORDERED_NODE_SNAPSHOT_TYPE, 0, es);
- if (es.hadException() || !result)
+ TrackExceptionState exceptionState;
+ RefPtr<XPathResult> result = DocumentXPathEvaluator::evaluate(document, whitespaceTrimmedQuery, document, 0, XPathResult::ORDERED_NODE_SNAPSHOT_TYPE, 0, exceptionState);
+ if (exceptionState.hadException() || !result)
continue;
- unsigned long size = result->snapshotLength(es);
- for (unsigned long i = 0; !es.hadException() && i < size; ++i) {
- Node* node = result->snapshotItem(i, es);
- if (es.hadException())
+ unsigned long size = result->snapshotLength(exceptionState);
+ for (unsigned long i = 0; !exceptionState.hadException() && i < size; ++i) {
+ Node* node = result->snapshotItem(i, exceptionState);
+ if (exceptionState.hadException())
break;
if (node->nodeType() == Node::ATTRIBUTE_NODE)
@@ -1023,9 +1018,9 @@ void InspectorDOMAgent::performSearch(ErrorString*, const String& whitespaceTrim
// Selector evaluation
for (Vector<Document*>::iterator it = docs.begin(); it != docs.end(); ++it) {
Document* document = *it;
- TrackExceptionState es;
- RefPtr<NodeList> nodeList = document->querySelectorAll(whitespaceTrimmedQuery, es);
- if (es.hadException() || !nodeList)
+ TrackExceptionState exceptionState;
+ RefPtr<NodeList> nodeList = document->querySelectorAll(whitespaceTrimmedQuery, exceptionState);
+ if (exceptionState.hadException() || !nodeList)
continue;
unsigned size = nodeList->length();
@@ -1143,6 +1138,7 @@ void InspectorDOMAgent::setSearchingForNode(ErrorString* errorString, SearchMode
{
if (m_searchingForNode == searchMode)
return;
+
m_searchingForNode = searchMode;
m_overlay->setInspectModeEnabled(searchMode != NotSearching);
if (searchMode != NotSearching) {
@@ -1178,6 +1174,8 @@ PassOwnPtr<HighlightConfig> InspectorDOMAgent::highlightConfigFromInspectorObjec
void InspectorDOMAgent::setInspectModeEnabled(ErrorString* errorString, bool enabled, const bool* inspectShadowDOM, const RefPtr<JSONObject>* highlightConfig)
{
+ if (enabled && !pushDocumentUponHandlelessOperation(errorString))
+ return;
SearchMode searchMode = enabled ? (inspectShadowDOM && *inspectShadowDOM ? SearchingForShadow : SearchingForNormal) : NotSearching;
setSearchingForNode(errorString, searchMode, highlightConfig ? highlightConfig->get() : 0);
}
@@ -1279,16 +1277,16 @@ void InspectorDOMAgent::moveTo(ErrorString* errorString, int nodeId, int targetE
void InspectorDOMAgent::undo(ErrorString* errorString)
{
- TrackExceptionState es;
- m_history->undo(es);
- *errorString = InspectorDOMAgent::toErrorString(es);
+ TrackExceptionState exceptionState;
+ m_history->undo(exceptionState);
+ *errorString = InspectorDOMAgent::toErrorString(exceptionState);
}
void InspectorDOMAgent::redo(ErrorString* errorString)
{
- TrackExceptionState es;
- m_history->redo(es);
- *errorString = InspectorDOMAgent::toErrorString(es);
+ TrackExceptionState exceptionState;
+ m_history->redo(exceptionState);
+ *errorString = InspectorDOMAgent::toErrorString(exceptionState);
}
void InspectorDOMAgent::markUndoableState(ErrorString*)
@@ -1375,13 +1373,8 @@ void InspectorDOMAgent::getBoxModel(ErrorString* errorString, int nodeId, RefPtr
void InspectorDOMAgent::getNodeForLocation(ErrorString* errorString, int x, int y, int* nodeId)
{
- // This call operates no handles, it could emerge before getDocument.
- if (!m_documentNodeToIdMap.contains(m_document)) {
- RefPtr<TypeBuilder::DOM::Node> root;
- getDocument(errorString, root);
- if (!errorString->isEmpty())
- return;
- }
+ if (!pushDocumentUponHandlelessOperation(errorString))
+ return;
Node* node = hoveredNodeForPoint(m_document->frame(), IntPoint(x, y), false);
if (!node) {
@@ -1439,6 +1432,18 @@ static String documentBaseURLString(Document* document)
return document->completeURL("").string();
}
+static TypeBuilder::DOM::ShadowRootType::Enum shadowRootType(ShadowRoot* shadowRoot)
+{
+ switch (shadowRoot->type()) {
+ case ShadowRoot::UserAgentShadowRoot:
+ return TypeBuilder::DOM::ShadowRootType::User_agent;
+ case ShadowRoot::AuthorShadowRoot:
+ return TypeBuilder::DOM::ShadowRootType::Author;
+ }
+ ASSERT_NOT_REACHED();
+ return TypeBuilder::DOM::ShadowRootType::User_agent;
+}
+
PassRefPtr<TypeBuilder::DOM::Node> InspectorDOMAgent::buildObjectForNode(Node* node, int depth, NodeToIdMap* nodesMap)
{
int id = bind(node, nodesMap);
@@ -1531,6 +1536,8 @@ PassRefPtr<TypeBuilder::DOM::Node> InspectorDOMAgent::buildObjectForNode(Node* n
Attr* attribute = toAttr(node);
value->setName(attribute->name());
value->setValue(attribute->value());
+ } else if (node->isShadowRoot()) {
+ value->setShadowRootType(shadowRootType(toShadowRoot(node)));
}
if (node->isContainerNode()) {
@@ -1691,7 +1698,7 @@ bool InspectorDOMAgent::isWhitespace(Node* node)
void InspectorDOMAgent::domContentLoadedEventFired(Frame* frame)
{
- if (frame->page()->mainFrame() != frame)
+ if (!frame->isMainFrame())
return;
// Re-push document once it is loaded.
@@ -1700,7 +1707,7 @@ void InspectorDOMAgent::domContentLoadedEventFired(Frame* frame)
m_frontend->documentUpdated();
}
-void InspectorDOMAgent::loadEventFired(Frame* frame)
+void InspectorDOMAgent::invalidateFrameOwnerElement(Frame* frame)
{
Element* frameOwner = frame->document()->ownerElement();
if (!frameOwner)
@@ -1723,9 +1730,14 @@ void InspectorDOMAgent::loadEventFired(Frame* frame)
void InspectorDOMAgent::didCommitLoad(Frame* frame, DocumentLoader* loader)
{
+ // FIXME: If "frame" is always guarenteed to be in the same Page as loader->frame()
+ // then all we need to check here is loader->frame()->isMainFrame()
+ // and we don't need "frame" at all.
Frame* mainFrame = frame->page()->mainFrame();
- if (loader->frame() != mainFrame)
+ if (loader->frame() != mainFrame) {
+ invalidateFrameOwnerElement(loader->frame());
return;
+ }
setDocument(mainFrame->document());
}
@@ -1893,7 +1905,7 @@ void InspectorDOMAgent::frameDocumentUpdated(Frame* frame)
return;
// Only update the main frame document, nested frame document updates are not required
- // (will be handled by loadEventFired()).
+ // (will be handled by invalidateFrameOwnerElement()).
setDocument(document);
}
@@ -1982,6 +1994,22 @@ void InspectorDOMAgent::pushNodeByBackendIdToFrontend(ErrorString* errorString,
}
}
+void InspectorDOMAgent::getRelayoutBoundary(ErrorString* errorString, int nodeId, int* relayoutBoundaryNodeId)
+{
+ Node* node = assertNode(errorString, nodeId);
+ if (!node)
+ return;
+ RenderObject* renderer = node->renderer();
+ if (!renderer) {
+ *errorString = "No renderer for node, perhaps orphan or hidden node";
+ return;
+ }
+ while (renderer && !renderer->isRoot() && !renderer->isRelayoutBoundaryForInspector())
+ renderer = renderer->container();
+ Node* resultNode = renderer ? renderer->generatingNode() : node->ownerDocument();
+ *relayoutBoundaryNodeId = pushNodePathToFrontend(resultNode);
+}
+
PassRefPtr<TypeBuilder::Runtime::RemoteObject> InspectorDOMAgent::resolveNode(Node* node, const String& objectGroup)
{
Document* document = node->isDocumentNode() ? &node->document() : node->ownerDocument();
@@ -1996,5 +2024,15 @@ PassRefPtr<TypeBuilder::Runtime::RemoteObject> InspectorDOMAgent::resolveNode(No
return injectedScript.wrapNode(node, objectGroup);
}
+bool InspectorDOMAgent::pushDocumentUponHandlelessOperation(ErrorString* errorString)
+{
+ if (!m_documentNodeToIdMap.contains(m_document)) {
+ RefPtr<TypeBuilder::DOM::Node> root;
+ getDocument(errorString, root);
+ return errorString->isEmpty();
+ }
+ return true;
+}
+
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InspectorDOMAgent.h b/chromium/third_party/WebKit/Source/core/inspector/InspectorDOMAgent.h
index b70b4b062b2..c1042f57b2e 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InspectorDOMAgent.h
+++ b/chromium/third_party/WebKit/Source/core/inspector/InspectorDOMAgent.h
@@ -34,8 +34,8 @@
#include "core/inspector/InjectedScript.h"
#include "core/inspector/InjectedScriptManager.h"
#include "core/inspector/InspectorBaseAgent.h"
-#include "core/platform/JSONValues.h"
#include "core/rendering/RenderLayer.h"
+#include "platform/JSONValues.h"
#include "wtf/HashMap.h"
#include "wtf/HashSet.h"
@@ -150,6 +150,7 @@ public:
virtual void setFileInputFiles(ErrorString*, int nodeId, const RefPtr<JSONArray>& files);
virtual void getBoxModel(ErrorString*, int nodeId, RefPtr<TypeBuilder::DOM::BoxModel>&);
virtual void getNodeForLocation(ErrorString*, int x, int y, int* nodeId);
+ virtual void getRelayoutBoundary(ErrorString*, int nodeId, int* relayoutBoundaryNodeId);
static void getEventListeners(Node*, Vector<EventListenerInfo>& listenersArray, bool includeAncestors);
@@ -158,7 +159,6 @@ public:
void releaseDanglingNodes();
void domContentLoadedEventFired(Frame*);
- void loadEventFired(Frame*);
void didCommitLoad(Frame*, DocumentLoader*);
void didInsertDOMNode(Node*);
@@ -204,9 +204,6 @@ public:
Element* assertElement(ErrorString*, int nodeId);
Document* assertDocument(ErrorString*, int nodeId);
- // Methods called from other agents.
- InspectorPageAgent* pageAgent() { return m_pageAgent; }
-
private:
enum SearchMode { NotSearching, SearchingForNormal, SearchingForShadow };
@@ -228,6 +225,8 @@ private:
int pushNodePathToFrontend(Node*);
void pushChildNodesToFrontend(int nodeId, int depth = 1);
+ void invalidateFrameOwnerElement(Frame*);
+
bool hasBreakpoint(Node*, int type);
void updateSubtreeBreakpoints(Node* root, uint32_t rootMask, bool value);
void descriptionForDOMEvent(Node* target, int breakpointType, bool insertion, PassRefPtr<JSONObject> description);
@@ -245,6 +244,8 @@ private:
void innerHighlightQuad(PassOwnPtr<FloatQuad>, const RefPtr<JSONObject>* color, const RefPtr<JSONObject>* outlineColor);
+ bool pushDocumentUponHandlelessOperation(ErrorString*);
+
InspectorPageAgent* m_pageAgent;
InjectedScriptManager* m_injectedScriptManager;
InspectorOverlay* m_overlay;
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InspectorDOMDebuggerAgent.cpp b/chromium/third_party/WebKit/Source/core/inspector/InspectorDOMDebuggerAgent.cpp
index 4e65d498026..1fe691875ab 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InspectorDOMDebuggerAgent.cpp
+++ b/chromium/third_party/WebKit/Source/core/inspector/InspectorDOMDebuggerAgent.cpp
@@ -32,13 +32,11 @@
#include "core/inspector/InspectorDOMDebuggerAgent.h"
#include "InspectorFrontend.h"
-#include "core/dom/Event.h"
+#include "core/events/Event.h"
#include "core/inspector/InspectorDOMAgent.h"
-#include "core/inspector/InspectorDebuggerAgent.h"
#include "core/inspector/InspectorState.h"
#include "core/inspector/InstrumentingAgents.h"
-#include "core/platform/JSONValues.h"
-#include "wtf/text/WTFString.h"
+#include "platform/JSONValues.h"
namespace {
@@ -49,8 +47,8 @@ enum DOMBreakpointType {
DOMBreakpointTypesCount
};
-static const char* const listenerEventCategoryType = "listener:";
-static const char* const instrumentationEventCategoryType = "instrumentation:";
+static const char listenerEventCategoryType[] = "listener:";
+static const char instrumentationEventCategoryType[] = "instrumentation:";
const uint32_t inheritableDOMBreakpointTypesMask = (1 << SubtreeModified);
const int domBreakpointDerivedTypeShift = 16;
@@ -59,15 +57,15 @@ const int domBreakpointDerivedTypeShift = 16;
namespace WebCore {
-static const char* const requestAnimationFrameEventName = "requestAnimationFrame";
-static const char* const cancelAnimationFrameEventName = "cancelAnimationFrame";
-static const char* const animationFrameFiredEventName = "animationFrameFired";
-static const char* const setTimerEventName = "setTimer";
-static const char* const clearTimerEventName = "clearTimer";
-static const char* const timerFiredEventName = "timerFired";
-static const char* const webglErrorFiredEventName = "webglErrorFired";
-static const char* const webglWarningFiredEventName = "webglWarningFired";
-static const char* const webglErrorNameProperty = "webglErrorName";
+static const char requestAnimationFrameEventName[] = "requestAnimationFrame";
+static const char cancelAnimationFrameEventName[] = "cancelAnimationFrame";
+static const char animationFrameFiredEventName[] = "animationFrameFired";
+static const char setTimerEventName[] = "setTimer";
+static const char clearTimerEventName[] = "clearTimer";
+static const char timerFiredEventName[] = "timerFired";
+static const char webglErrorFiredEventName[] = "webglErrorFired";
+static const char webglWarningFiredEventName[] = "webglWarningFired";
+static const char webglErrorNameProperty[] = "webglErrorName";
namespace DOMDebuggerAgentState {
static const char eventListenerBreakpoints[] = "eventListenerBreakpoints";
@@ -407,17 +405,17 @@ PassRefPtr<JSONObject> InspectorDOMDebuggerAgent::preparePauseOnNativeEventData(
return eventData.release();
}
-void InspectorDOMDebuggerAgent::didInstallTimer(ScriptExecutionContext* context, int timerId, int timeout, bool singleShot)
+void InspectorDOMDebuggerAgent::didInstallTimer(ExecutionContext* context, int timerId, int timeout, bool singleShot)
{
pauseOnNativeEventIfNeeded(preparePauseOnNativeEventData(false, setTimerEventName), true);
}
-void InspectorDOMDebuggerAgent::didRemoveTimer(ScriptExecutionContext* context, int timerId)
+void InspectorDOMDebuggerAgent::didRemoveTimer(ExecutionContext* context, int timerId)
{
pauseOnNativeEventIfNeeded(preparePauseOnNativeEventData(false, clearTimerEventName), true);
}
-void InspectorDOMDebuggerAgent::willFireTimer(ScriptExecutionContext* context, int timerId)
+void InspectorDOMDebuggerAgent::willFireTimer(ExecutionContext* context, int timerId)
{
pauseOnNativeEventIfNeeded(preparePauseOnNativeEventData(false, timerFiredEventName), false);
}
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InspectorDOMDebuggerAgent.h b/chromium/third_party/WebKit/Source/core/inspector/InspectorDOMDebuggerAgent.h
index b1b9171d6c8..2b0b87bfc94 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InspectorDOMDebuggerAgent.h
+++ b/chromium/third_party/WebKit/Source/core/inspector/InspectorDOMDebuggerAgent.h
@@ -77,9 +77,9 @@ public:
void didRemoveDOMNode(Node*);
void willModifyDOMAttr(Element*, const AtomicString&, const AtomicString&);
void willSendXMLHttpRequest(const String& url);
- void didInstallTimer(ScriptExecutionContext*, int timerId, int timeout, bool singleShot);
- void didRemoveTimer(ScriptExecutionContext*, int timerId);
- void willFireTimer(ScriptExecutionContext*, int timerId);
+ void didInstallTimer(ExecutionContext*, int timerId, int timeout, bool singleShot);
+ void didRemoveTimer(ExecutionContext*, int timerId);
+ void willFireTimer(ExecutionContext*, int timerId);
void didRequestAnimationFrame(Document*, int callbackId);
void didCancelAnimationFrame(Document*, int callbackId);
void willFireAnimationFrame(Document*, int callbackId);
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InspectorDOMStorageAgent.cpp b/chromium/third_party/WebKit/Source/core/inspector/InspectorDOMStorageAgent.cpp
index 4420d1b9016..19e11e86701 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InspectorDOMStorageAgent.cpp
+++ b/chromium/third_party/WebKit/Source/core/inspector/InspectorDOMStorageAgent.cpp
@@ -38,15 +38,14 @@
#include "core/inspector/InspectorPageAgent.h"
#include "core/inspector/InspectorState.h"
#include "core/inspector/InstrumentingAgents.h"
-#include "core/page/DOMWindow.h"
-#include "core/page/Frame.h"
+#include "core/frame/DOMWindow.h"
+#include "core/frame/Frame.h"
#include "core/page/Page.h"
#include "core/page/PageGroup.h"
-#include "core/platform/JSONValues.h"
#include "core/storage/Storage.h"
-#include "core/storage/StorageArea.h"
#include "core/storage/StorageNamespace.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/JSONValues.h"
+#include "platform/weborigin/SecurityOrigin.h"
namespace WebCore {
@@ -54,12 +53,12 @@ namespace DOMStorageAgentState {
static const char domStorageAgentEnabled[] = "domStorageAgentEnabled";
};
-static bool hadException(ExceptionState& es, ErrorString* errorString)
+static bool hadException(ExceptionState& exceptionState, ErrorString* errorString)
{
- if (!es.hadException())
+ if (!exceptionState.hadException())
return false;
- switch (es.code()) {
+ switch (exceptionState.code()) {
case SecurityError:
*errorString = "Security error";
return true;
@@ -117,13 +116,13 @@ void InspectorDOMStorageAgent::getDOMStorageItems(ErrorString* errorString, cons
RefPtr<TypeBuilder::Array<TypeBuilder::Array<String> > > storageItems = TypeBuilder::Array<TypeBuilder::Array<String> >::create();
- TrackExceptionState es;
- for (unsigned i = 0; i < storageArea->length(es, frame); ++i) {
- String name(storageArea->key(i, es, frame));
- if (hadException(es, errorString))
+ TrackExceptionState exceptionState;
+ for (unsigned i = 0; i < storageArea->length(exceptionState, frame); ++i) {
+ String name(storageArea->key(i, exceptionState, frame));
+ if (hadException(exceptionState, errorString))
return;
- String value(storageArea->getItem(name, es, frame));
- if (hadException(es, errorString))
+ String value(storageArea->getItem(name, exceptionState, frame));
+ if (hadException(exceptionState, errorString))
return;
RefPtr<TypeBuilder::Array<String> > entry = TypeBuilder::Array<String>::create();
entry->addItem(name);
@@ -133,10 +132,10 @@ void InspectorDOMStorageAgent::getDOMStorageItems(ErrorString* errorString, cons
items = storageItems.release();
}
-static String toErrorString(ExceptionState& es)
+static String toErrorString(ExceptionState& exceptionState)
{
- if (es.hadException())
- return DOMException::getErrorName(es.code());
+ if (exceptionState.hadException())
+ return DOMException::getErrorName(exceptionState.code());
return "";
}
@@ -149,9 +148,9 @@ void InspectorDOMStorageAgent::setDOMStorageItem(ErrorString* errorString, const
return;
}
- TrackExceptionState es;
- storageArea->setItem(key, value, es, frame);
- *errorString = toErrorString(es);
+ TrackExceptionState exceptionState;
+ storageArea->setItem(key, value, exceptionState, frame);
+ *errorString = toErrorString(exceptionState);
}
void InspectorDOMStorageAgent::removeDOMStorageItem(ErrorString* errorString, const RefPtr<JSONObject>& storageId, const String& key)
@@ -163,9 +162,9 @@ void InspectorDOMStorageAgent::removeDOMStorageItem(ErrorString* errorString, co
return;
}
- TrackExceptionState es;
- storageArea->removeItem(key, es, frame);
- *errorString = toErrorString(es);
+ TrackExceptionState exceptionState;
+ storageArea->removeItem(key, exceptionState, frame);
+ *errorString = toErrorString(exceptionState);
}
String InspectorDOMStorageAgent::storageId(Storage* storage)
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InspectorDatabaseAgent.cpp b/chromium/third_party/WebKit/Source/core/inspector/InspectorDatabaseAgent.cpp
index 22ead3ea5b9..11960dfe0cf 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InspectorDatabaseAgent.cpp
+++ b/chromium/third_party/WebKit/Source/core/inspector/InspectorDatabaseAgent.cpp
@@ -29,17 +29,14 @@
#include "config.h"
#include "core/inspector/InspectorDatabaseAgent.h"
-#include "InspectorFrontend.h"
#include "bindings/v8/ExceptionStatePlaceholder.h"
-#include "core/html/VoidCallback.h"
#include "core/inspector/InspectorDatabaseResource.h"
#include "core/inspector/InspectorState.h"
#include "core/inspector/InstrumentingAgents.h"
#include "core/loader/DocumentLoader.h"
-#include "core/page/Frame.h"
+#include "core/frame/Frame.h"
+#include "core/html/VoidCallback.h"
#include "core/page/Page.h"
-#include "core/platform/JSONValues.h"
-#include "core/platform/sql/SQLValue.h"
#include "modules/webdatabase/Database.h"
#include "modules/webdatabase/SQLError.h"
#include "modules/webdatabase/SQLResultSet.h"
@@ -49,6 +46,8 @@
#include "modules/webdatabase/SQLTransaction.h"
#include "modules/webdatabase/SQLTransactionCallback.h"
#include "modules/webdatabase/SQLTransactionErrorCallback.h"
+#include "modules/webdatabase/sqlite/SQLValue.h"
+#include "platform/JSONValues.h"
#include "wtf/Vector.h"
typedef WebCore::InspectorBackendDispatcher::DatabaseCommandHandler::ExecuteSQLCallback ExecuteSQLCallback;
@@ -71,9 +70,9 @@ void reportTransactionFailed(ExecuteSQLCallback* requestCallback, SQLError* erro
class StatementCallback : public SQLStatementCallback {
public:
- static PassRefPtr<StatementCallback> create(PassRefPtr<ExecuteSQLCallback> requestCallback)
+ static PassOwnPtr<StatementCallback> create(PassRefPtr<ExecuteSQLCallback> requestCallback)
{
- return adoptRef(new StatementCallback(requestCallback));
+ return adoptPtr(new StatementCallback(requestCallback));
}
virtual ~StatementCallback() { }
@@ -109,9 +108,9 @@ private:
class StatementErrorCallback : public SQLStatementErrorCallback {
public:
- static PassRefPtr<StatementErrorCallback> create(PassRefPtr<ExecuteSQLCallback> requestCallback)
+ static PassOwnPtr<StatementErrorCallback> create(PassRefPtr<ExecuteSQLCallback> requestCallback)
{
- return adoptRef(new StatementErrorCallback(requestCallback));
+ return adoptPtr(new StatementErrorCallback(requestCallback));
}
virtual ~StatementErrorCallback() { }
@@ -130,9 +129,9 @@ private:
class TransactionCallback : public SQLTransactionCallback {
public:
- static PassRefPtr<TransactionCallback> create(const String& sqlStatement, PassRefPtr<ExecuteSQLCallback> requestCallback)
+ static PassOwnPtr<TransactionCallback> create(const String& sqlStatement, PassRefPtr<ExecuteSQLCallback> requestCallback)
{
- return adoptRef(new TransactionCallback(sqlStatement, requestCallback));
+ return adoptPtr(new TransactionCallback(sqlStatement, requestCallback));
}
virtual ~TransactionCallback() { }
@@ -143,8 +142,8 @@ public:
return true;
Vector<SQLValue> sqlValues;
- RefPtr<SQLStatementCallback> callback(StatementCallback::create(m_requestCallback.get()));
- RefPtr<SQLStatementErrorCallback> errorCallback(StatementErrorCallback::create(m_requestCallback.get()));
+ OwnPtr<SQLStatementCallback> callback(StatementCallback::create(m_requestCallback.get()));
+ OwnPtr<SQLStatementErrorCallback> errorCallback(StatementErrorCallback::create(m_requestCallback.get()));
transaction->executeSQL(m_sqlStatement, sqlValues, callback.release(), errorCallback.release(), IGNORE_EXCEPTION);
return true;
}
@@ -158,9 +157,9 @@ private:
class TransactionErrorCallback : public SQLTransactionErrorCallback {
public:
- static PassRefPtr<TransactionErrorCallback> create(PassRefPtr<ExecuteSQLCallback> requestCallback)
+ static PassOwnPtr<TransactionErrorCallback> create(PassRefPtr<ExecuteSQLCallback> requestCallback)
{
- return adoptRef(new TransactionErrorCallback(requestCallback));
+ return adoptPtr(new TransactionErrorCallback(requestCallback));
}
virtual ~TransactionErrorCallback() { }
@@ -178,14 +177,14 @@ private:
class TransactionSuccessCallback : public VoidCallback {
public:
- static PassRefPtr<TransactionSuccessCallback> create()
+ static PassOwnPtr<TransactionSuccessCallback> create()
{
- return adoptRef(new TransactionSuccessCallback());
+ return adoptPtr(new TransactionSuccessCallback());
}
virtual ~TransactionSuccessCallback() { }
- virtual bool handleEvent() { return false; }
+ virtual void handleEvent() { }
private:
TransactionSuccessCallback() { }
@@ -209,6 +208,9 @@ void InspectorDatabaseAgent::didOpenDatabase(PassRefPtr<Database> database, cons
void InspectorDatabaseAgent::didCommitLoad(Frame* frame, DocumentLoader* loader)
{
+ // FIXME: If "frame" is always guarenteed to be in the same Page as loader->frame()
+ // then all we need to check here is loader->frame()->isMainFrame()
+ // and we don't need "frame" at all.
if (loader->frame() != frame->page()->mainFrame())
return;
@@ -297,9 +299,9 @@ void InspectorDatabaseAgent::executeSQL(ErrorString*, const String& databaseId,
return;
}
- RefPtr<SQLTransactionCallback> callback(TransactionCallback::create(query, requestCallback.get()));
- RefPtr<SQLTransactionErrorCallback> errorCallback(TransactionErrorCallback::create(requestCallback.get()));
- RefPtr<VoidCallback> successCallback(TransactionSuccessCallback::create());
+ OwnPtr<SQLTransactionCallback> callback(TransactionCallback::create(query, requestCallback.get()));
+ OwnPtr<SQLTransactionErrorCallback> errorCallback(TransactionErrorCallback::create(requestCallback.get()));
+ OwnPtr<VoidCallback> successCallback(TransactionSuccessCallback::create());
database->transaction(callback.release(), errorCallback.release(), successCallback.release());
}
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InspectorDatabaseResource.cpp b/chromium/third_party/WebKit/Source/core/inspector/InspectorDatabaseResource.cpp
index 23367de68c0..d2196a062ab 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InspectorDatabaseResource.cpp
+++ b/chromium/third_party/WebKit/Source/core/inspector/InspectorDatabaseResource.cpp
@@ -32,7 +32,6 @@
#include "core/inspector/InspectorDatabaseResource.h"
-#include "InspectorFrontend.h"
#include "modules/webdatabase/Database.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InspectorDebuggerAgent.cpp b/chromium/third_party/WebKit/Source/core/inspector/InspectorDebuggerAgent.cpp
index db63572ec5b..aceaae4e39a 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InspectorDebuggerAgent.cpp
+++ b/chromium/third_party/WebKit/Source/core/inspector/InspectorDebuggerAgent.cpp
@@ -31,26 +31,28 @@
#include "core/inspector/InspectorDebuggerAgent.h"
#include "core/inspector/JavaScriptCallFrame.h"
-#include "InspectorFrontend.h"
#include "bindings/v8/ScriptDebugServer.h"
#include "bindings/v8/ScriptObject.h"
+#include "bindings/v8/ScriptRegexp.h"
#include "bindings/v8/ScriptSourceCode.h"
+#include "core/dom/Document.h"
#include "core/fetch/Resource.h"
#include "core/inspector/ContentSearchUtils.h"
-#include "core/inspector/InjectedScript.h"
#include "core/inspector/InjectedScriptManager.h"
#include "core/inspector/InspectorPageAgent.h"
#include "core/inspector/InspectorState.h"
#include "core/inspector/InstrumentingAgents.h"
#include "core/inspector/ScriptArguments.h"
#include "core/inspector/ScriptCallStack.h"
-#include "core/platform/JSONValues.h"
-#include "core/platform/text/RegularExpression.h"
+#include "platform/JSONValues.h"
#include "wtf/text/WTFString.h"
using WebCore::TypeBuilder::Array;
+using WebCore::TypeBuilder::Debugger::BreakpointId;
+using WebCore::TypeBuilder::Debugger::CallFrame;
using WebCore::TypeBuilder::Debugger::FunctionDetails;
using WebCore::TypeBuilder::Debugger::ScriptId;
+using WebCore::TypeBuilder::Debugger::StackTrace;
using WebCore::TypeBuilder::Runtime::RemoteObject;
namespace WebCore {
@@ -59,6 +61,7 @@ namespace DebuggerAgentState {
static const char debuggerEnabled[] = "debuggerEnabled";
static const char javaScriptBreakpoints[] = "javaScriptBreakopints";
static const char pauseOnExceptionsState[] = "pauseOnExceptionsState";
+static const char asyncCallStackDepth[] = "asyncCallStackDepth";
// Breakpoint properties.
static const char url[] = "url";
@@ -75,7 +78,7 @@ static const char skipAllPausesExpiresOnReload[] = "skipAllPausesExpiresOnReload
static const int numberOfStepsBeforeStepOut = 10;
-const char* InspectorDebuggerAgent::backtraceObjectGroup = "backtrace";
+const char InspectorDebuggerAgent::backtraceObjectGroup[] = "backtrace";
static String breakpointIdSuffix(InspectorDebuggerAgent::BreakpointSource source)
{
@@ -132,6 +135,7 @@ void InspectorDebuggerAgent::disable()
m_state->setObject(DebuggerAgentState::javaScriptBreakpoints, JSONObject::create());
m_state->setLong(DebuggerAgentState::pauseOnExceptionsState, ScriptDebugServer::DontPauseOnExceptions);
m_state->setString(DebuggerAgentState::skipStackPattern, "");
+ m_state->setLong(DebuggerAgentState::asyncCallStackDepth, 0);
m_instrumentingAgents->setInspectorDebuggerAgent(0);
stopListeningScriptDebugServer();
@@ -170,11 +174,11 @@ void InspectorDebuggerAgent::disable(ErrorString*)
m_state->setBoolean(DebuggerAgentState::debuggerEnabled, false);
}
-static PassOwnPtr<RegularExpression> compileSkipCallFramePattern(String patternText)
+static PassOwnPtr<ScriptRegexp> compileSkipCallFramePattern(String patternText)
{
if (patternText.isEmpty())
return nullptr;
- OwnPtr<RegularExpression> result = adoptPtr(new RegularExpression(patternText, TextCaseSensitive));
+ OwnPtr<ScriptRegexp> result = adoptPtr(new ScriptRegexp(patternText, TextCaseSensitive));
if (!result->isValid())
result.clear();
return result.release();
@@ -194,6 +198,7 @@ void InspectorDebuggerAgent::restore()
m_skipAllPauses = false;
m_state->setBoolean(DebuggerAgentState::skipAllPauses, false);
}
+ m_asyncCallStackTracker.setAsyncCallStackDepth(m_state->getLong(DebuggerAgentState::asyncCallStackDepth));
}
}
@@ -289,13 +294,13 @@ static PassRefPtr<JSONObject> buildObjectForBreakpointCookie(const String& url,
static bool matches(const String& url, const String& pattern, bool isRegex)
{
if (isRegex) {
- RegularExpression regex(pattern, TextCaseSensitive);
+ ScriptRegexp regex(pattern, TextCaseSensitive);
return regex.match(url) != -1;
}
return url == pattern;
}
-void InspectorDebuggerAgent::setBreakpointByUrl(ErrorString* errorString, int lineNumber, const String* const optionalURL, const String* const optionalURLRegex, const int* const optionalColumnNumber, const String* const optionalCondition, const bool* isAntiBreakpoint, TypeBuilder::Debugger::BreakpointId* outBreakpointId, RefPtr<TypeBuilder::Array<TypeBuilder::Debugger::Location> >& locations)
+void InspectorDebuggerAgent::setBreakpointByUrl(ErrorString* errorString, int lineNumber, const String* const optionalURL, const String* const optionalURLRegex, const int* const optionalColumnNumber, const String* const optionalCondition, const bool* isAntiBreakpoint, BreakpointId* outBreakpointId, RefPtr<Array<TypeBuilder::Debugger::Location> >& locations)
{
locations = Array<TypeBuilder::Debugger::Location>::create();
if (!optionalURL == !optionalURLRegex) {
@@ -354,7 +359,7 @@ static bool parseLocation(ErrorString* errorString, PassRefPtr<JSONObject> locat
return true;
}
-void InspectorDebuggerAgent::setBreakpoint(ErrorString* errorString, const RefPtr<JSONObject>& location, const String* const optionalCondition, TypeBuilder::Debugger::BreakpointId* outBreakpointId, RefPtr<TypeBuilder::Debugger::Location>& actualLocation)
+void InspectorDebuggerAgent::setBreakpoint(ErrorString* errorString, const RefPtr<JSONObject>& location, const String* const optionalCondition, BreakpointId* outBreakpointId, RefPtr<TypeBuilder::Debugger::Location>& actualLocation)
{
String scriptId;
int lineNumber;
@@ -429,7 +434,7 @@ void InspectorDebuggerAgent::continueToLocation(ErrorString* errorString, const
void InspectorDebuggerAgent::getStepInPositions(ErrorString* errorString, const String& callFrameId, RefPtr<Array<TypeBuilder::Debugger::Location> >& positions)
{
- if (!isPaused() || m_currentCallStack.isNull()) {
+ if (!isPaused() || m_currentCallStack.hasNoValue()) {
*errorString = "Attempt to access callframe when debugger is not on pause";
return;
}
@@ -442,12 +447,13 @@ void InspectorDebuggerAgent::getStepInPositions(ErrorString* errorString, const
injectedScript.getStepInPositions(errorString, m_currentCallStack, callFrameId, positions);
}
-void InspectorDebuggerAgent::getBacktrace(ErrorString* errorString, RefPtr<Array<TypeBuilder::Debugger::CallFrame> >& callFrames)
+void InspectorDebuggerAgent::getBacktrace(ErrorString* errorString, RefPtr<Array<CallFrame> >& callFrames, RefPtr<StackTrace>& asyncStackTrace)
{
if (!assertPaused(errorString))
return;
- scriptDebugServer().updateCallStack(&m_currentCallStack);
+ m_currentCallStack = scriptDebugServer().currentCallFrames();
callFrames = currentCallFrames();
+ asyncStackTrace = currentAsyncStackTrace();
}
String InspectorDebuggerAgent::scriptURL(JavaScriptCallFrame* frame)
@@ -463,19 +469,21 @@ ScriptDebugListener::SkipPauseRequest InspectorDebuggerAgent::shouldSkipExceptio
{
if (m_skipAllPauses)
return ScriptDebugListener::Continue;
+ if (!topFrame)
+ return ScriptDebugListener::NoSkip;
String topFrameScriptUrl = scriptURL(topFrame.get());
if (m_cachedSkipStackRegExp && !topFrameScriptUrl.isEmpty() && m_cachedSkipStackRegExp->match(topFrameScriptUrl) != -1)
return ScriptDebugListener::Continue;
- // Prepare top frame parameters;
- int topFrameLineNumber = topFrame->line();
- int topFrameColumnNumber = topFrame->column();
-
// Match against breakpoints.
if (topFrameScriptUrl.isEmpty())
return ScriptDebugListener::NoSkip;
+ // Prepare top frame parameters.
+ int topFrameLineNumber = topFrame->line();
+ int topFrameColumnNumber = topFrame->column();
+
RefPtr<JSONObject> breakpointsCookie = m_state->getObject(DebuggerAgentState::javaScriptBreakpoints);
for (JSONObject::iterator it = breakpointsCookie->begin(); it != breakpointsCookie->end(); ++it) {
RefPtr<JSONObject> breakpointObject = it->value->asObject();
@@ -512,6 +520,8 @@ ScriptDebugListener::SkipPauseRequest InspectorDebuggerAgent::shouldSkipBreakpoi
{
if (m_skipAllPauses)
return ScriptDebugListener::Continue;
+ if (!topFrame)
+ return ScriptDebugListener::NoSkip;
return ScriptDebugListener::NoSkip;
}
@@ -519,6 +529,8 @@ ScriptDebugListener::SkipPauseRequest InspectorDebuggerAgent::shouldSkipStepPaus
{
if (m_skipAllPauses)
return ScriptDebugListener::Continue;
+ if (!topFrame)
+ return ScriptDebugListener::NoSkip;
if (m_cachedSkipStackRegExp) {
String scriptUrl = scriptURL(topFrame.get());
@@ -584,20 +596,22 @@ void InspectorDebuggerAgent::searchInContent(ErrorString* error, const String& s
*error = "No script for id: " + scriptId;
}
-void InspectorDebuggerAgent::setScriptSource(ErrorString* error, RefPtr<TypeBuilder::Debugger::SetScriptSourceError>& errorData, const String& scriptId, const String& newContent, const bool* const preview, RefPtr<Array<TypeBuilder::Debugger::CallFrame> >& newCallFrames, RefPtr<JSONObject>& result)
+void InspectorDebuggerAgent::setScriptSource(ErrorString* error, RefPtr<TypeBuilder::Debugger::SetScriptSourceError>& errorData, const String& scriptId, const String& newContent, const bool* const preview, RefPtr<Array<CallFrame> >& newCallFrames, RefPtr<JSONObject>& result, RefPtr<StackTrace>& asyncStackTrace)
{
bool previewOnly = preview && *preview;
ScriptObject resultObject;
if (!scriptDebugServer().setScriptSource(scriptId, newContent, previewOnly, error, errorData, &m_currentCallStack, &resultObject))
return;
newCallFrames = currentCallFrames();
+ asyncStackTrace = currentAsyncStackTrace();
RefPtr<JSONObject> object = scriptToInspectorObject(resultObject);
if (object)
result = object;
}
-void InspectorDebuggerAgent::restartFrame(ErrorString* errorString, const String& callFrameId, RefPtr<Array<TypeBuilder::Debugger::CallFrame> >& newCallFrames, RefPtr<JSONObject>& result)
+
+void InspectorDebuggerAgent::restartFrame(ErrorString* errorString, const String& callFrameId, RefPtr<Array<CallFrame> >& newCallFrames, RefPtr<JSONObject>& result, RefPtr<StackTrace>& asyncStackTrace)
{
- if (!isPaused() || m_currentCallStack.isNull()) {
+ if (!isPaused() || m_currentCallStack.hasNoValue()) {
*errorString = "Attempt to access callframe when debugger is not on pause";
return;
}
@@ -608,8 +622,9 @@ void InspectorDebuggerAgent::restartFrame(ErrorString* errorString, const String
}
injectedScript.restartFrame(errorString, m_currentCallStack, callFrameId, &result);
- scriptDebugServer().updateCallStack(&m_currentCallStack);
+ m_currentCallStack = scriptDebugServer().currentCallFrames();
newCallFrames = currentCallFrames();
+ asyncStackTrace = currentAsyncStackTrace();
}
void InspectorDebuggerAgent::getScriptSource(ErrorString* error, const String& scriptId, String* scriptSource)
@@ -621,7 +636,7 @@ void InspectorDebuggerAgent::getScriptSource(ErrorString* error, const String& s
*error = "No script for id: " + scriptId;
}
-void InspectorDebuggerAgent::getFunctionDetails(ErrorString* errorString, const String& functionId, RefPtr<TypeBuilder::Debugger::FunctionDetails>& details)
+void InspectorDebuggerAgent::getFunctionDetails(ErrorString* errorString, const String& functionId, RefPtr<FunctionDetails>& details)
{
InjectedScript injectedScript = m_injectedScriptManager->injectedScriptForObjectId(functionId);
if (injectedScript.hasNoValue()) {
@@ -648,11 +663,51 @@ void InspectorDebuggerAgent::cancelPauseOnNextStatement()
scriptDebugServer().setPauseOnNextStatement(false);
}
+void InspectorDebuggerAgent::didInstallTimer(ExecutionContext* context, int timerId, int timeout, bool singleShot)
+{
+ if (m_asyncCallStackTracker.isEnabled())
+ m_asyncCallStackTracker.didInstallTimer(context, timerId, singleShot, scriptDebugServer().currentCallFrames());
+}
+
+void InspectorDebuggerAgent::didRemoveTimer(ExecutionContext* context, int timerId)
+{
+ m_asyncCallStackTracker.didRemoveTimer(context, timerId);
+}
+
+bool InspectorDebuggerAgent::willFireTimer(ExecutionContext* context, int timerId)
+{
+ m_asyncCallStackTracker.willFireTimer(context, timerId);
+ return true;
+}
+
void InspectorDebuggerAgent::didFireTimer()
{
+ m_asyncCallStackTracker.didFireAsyncCall();
cancelPauseOnNextStatement();
}
+void InspectorDebuggerAgent::didRequestAnimationFrame(Document* document, int callbackId)
+{
+ if (m_asyncCallStackTracker.isEnabled())
+ m_asyncCallStackTracker.didRequestAnimationFrame(document, callbackId, scriptDebugServer().currentCallFrames());
+}
+
+void InspectorDebuggerAgent::didCancelAnimationFrame(Document* document, int callbackId)
+{
+ m_asyncCallStackTracker.didCancelAnimationFrame(document, callbackId);
+}
+
+bool InspectorDebuggerAgent::willFireAnimationFrame(Document* document, int callbackId)
+{
+ m_asyncCallStackTracker.willFireAnimationFrame(document, callbackId);
+ return true;
+}
+
+void InspectorDebuggerAgent::didFireAnimationFrame()
+{
+ m_asyncCallStackTracker.didFireAsyncCall();
+}
+
void InspectorDebuggerAgent::didHandleEvent()
{
cancelPauseOnNextStatement();
@@ -675,12 +730,31 @@ void InspectorDebuggerAgent::resume(ErrorString* errorString)
scriptDebugServer().continueProgram();
}
-void InspectorDebuggerAgent::stepOver(ErrorString* errorString)
+ScriptValue InspectorDebuggerAgent::resolveCallFrame(ErrorString* errorString, const String* callFrameId)
+{
+ if (!callFrameId)
+ return ScriptValue();
+ if (!isPaused() || m_currentCallStack.hasNoValue()) {
+ *errorString = "Attempt to access callframe when debugger is not on pause";
+ return ScriptValue();
+ }
+ InjectedScript injectedScript = m_injectedScriptManager->injectedScriptForObjectId(*callFrameId);
+ if (injectedScript.hasNoValue()) {
+ *errorString = "Inspected frame has gone";
+ return ScriptValue();
+ }
+ return injectedScript.findCallFrameById(errorString, m_currentCallStack, *callFrameId);
+}
+
+void InspectorDebuggerAgent::stepOver(ErrorString* errorString, const String* callFrameId)
{
if (!assertPaused(errorString))
return;
+ ScriptValue frame = resolveCallFrame(errorString, callFrameId);
+ if (!errorString->isEmpty())
+ return;
m_injectedScriptManager->releaseObjectGroup(InspectorDebuggerAgent::backtraceObjectGroup);
- scriptDebugServer().stepOverStatement();
+ scriptDebugServer().stepOverStatement(frame);
}
void InspectorDebuggerAgent::stepInto(ErrorString* errorString)
@@ -693,12 +767,15 @@ void InspectorDebuggerAgent::stepInto(ErrorString* errorString)
m_listener->stepInto();
}
-void InspectorDebuggerAgent::stepOut(ErrorString* errorString)
+void InspectorDebuggerAgent::stepOut(ErrorString* errorString, const String* callFrameId)
{
if (!assertPaused(errorString))
return;
+ ScriptValue frame = resolveCallFrame(errorString, callFrameId);
+ if (!errorString->isEmpty())
+ return;
m_injectedScriptManager->releaseObjectGroup(InspectorDebuggerAgent::backtraceObjectGroup);
- scriptDebugServer().stepOutOfFunction();
+ scriptDebugServer().stepOutOfFunction(frame);
}
void InspectorDebuggerAgent::setPauseOnExceptions(ErrorString* errorString, const String& stringPauseState)
@@ -726,9 +803,9 @@ void InspectorDebuggerAgent::setPauseOnExceptionsImpl(ErrorString* errorString,
m_state->setLong(DebuggerAgentState::pauseOnExceptionsState, pauseState);
}
-void InspectorDebuggerAgent::evaluateOnCallFrame(ErrorString* errorString, const String& callFrameId, const String& expression, const String* const objectGroup, const bool* const includeCommandLineAPI, const bool* const doNotPauseOnExceptionsAndMuteConsole, const bool* const returnByValue, const bool* generatePreview, RefPtr<TypeBuilder::Runtime::RemoteObject>& result, TypeBuilder::OptOutput<bool>* wasThrown)
+void InspectorDebuggerAgent::evaluateOnCallFrame(ErrorString* errorString, const String& callFrameId, const String& expression, const String* const objectGroup, const bool* const includeCommandLineAPI, const bool* const doNotPauseOnExceptionsAndMuteConsole, const bool* const returnByValue, const bool* generatePreview, RefPtr<RemoteObject>& result, TypeBuilder::OptOutput<bool>* wasThrown)
{
- if (!isPaused() || m_currentCallStack.isNull()) {
+ if (!isPaused() || m_currentCallStack.hasNoValue()) {
*errorString = "Attempt to access callframe when debugger is not on pause";
return;
}
@@ -773,7 +850,7 @@ void InspectorDebuggerAgent::compileScript(ErrorString* errorString, const Strin
*scriptId = scriptIdValue;
}
-void InspectorDebuggerAgent::runScript(ErrorString* errorString, const ScriptId& scriptId, const int* executionContextId, const String* const objectGroup, const bool* const doNotPauseOnExceptionsAndMuteConsole, RefPtr<TypeBuilder::Runtime::RemoteObject>& result, TypeBuilder::OptOutput<bool>* wasThrown)
+void InspectorDebuggerAgent::runScript(ErrorString* errorString, const ScriptId& scriptId, const int* executionContextId, const String* const objectGroup, const bool* const doNotPauseOnExceptionsAndMuteConsole, RefPtr<RemoteObject>& result, TypeBuilder::OptOutput<bool>* wasThrown)
{
InjectedScript injectedScript = injectedScriptForEval(errorString, executionContextId);
if (injectedScript.hasNoValue()) {
@@ -816,7 +893,7 @@ void InspectorDebuggerAgent::setVariableValue(ErrorString* errorString, int scop
{
InjectedScript injectedScript;
if (callFrameId) {
- if (!isPaused() || m_currentCallStack.isNull()) {
+ if (!isPaused() || m_currentCallStack.hasNoValue()) {
*errorString = "Attempt to access callframe when debugger is not on pause";
return;
}
@@ -842,7 +919,7 @@ void InspectorDebuggerAgent::setVariableValue(ErrorString* errorString, int scop
void InspectorDebuggerAgent::skipStackFrames(ErrorString* errorString, const String* pattern)
{
- OwnPtr<RegularExpression> compiled;
+ OwnPtr<ScriptRegexp> compiled;
String patternValue = pattern ? *pattern : "";
if (!patternValue.isEmpty()) {
compiled = compileSkipCallFramePattern(patternValue);
@@ -855,6 +932,12 @@ void InspectorDebuggerAgent::skipStackFrames(ErrorString* errorString, const Str
m_cachedSkipStackRegExp = compiled.release();
}
+void InspectorDebuggerAgent::setAsyncCallStackDepth(ErrorString*, int depth)
+{
+ m_state->setLong(DebuggerAgentState::asyncCallStackDepth, depth);
+ m_asyncCallStackTracker.setAsyncCallStackDepth(depth);
+}
+
void InspectorDebuggerAgent::scriptExecutionBlockedByCSP(const String& directiveText)
{
if (scriptDebugServer().pauseOnExceptionsState() != ScriptDebugServer::DontPauseOnExceptions) {
@@ -864,18 +947,46 @@ void InspectorDebuggerAgent::scriptExecutionBlockedByCSP(const String& directive
}
}
-PassRefPtr<Array<TypeBuilder::Debugger::CallFrame> > InspectorDebuggerAgent::currentCallFrames()
+PassRefPtr<Array<CallFrame> > InspectorDebuggerAgent::currentCallFrames()
{
- if (!m_pausedScriptState)
- return Array<TypeBuilder::Debugger::CallFrame>::create();
+ if (!m_pausedScriptState || m_currentCallStack.hasNoValue())
+ return Array<CallFrame>::create();
InjectedScript injectedScript = m_injectedScriptManager->injectedScriptFor(m_pausedScriptState);
if (injectedScript.hasNoValue()) {
ASSERT_NOT_REACHED();
- return Array<TypeBuilder::Debugger::CallFrame>::create();
+ return Array<CallFrame>::create();
}
return injectedScript.wrapCallFrames(m_currentCallStack);
}
+PassRefPtr<StackTrace> InspectorDebuggerAgent::currentAsyncStackTrace()
+{
+ if (!m_pausedScriptState || !m_asyncCallStackTracker.isEnabled())
+ return 0;
+ InjectedScript injectedScript = m_injectedScriptManager->injectedScriptFor(m_pausedScriptState);
+ if (injectedScript.hasNoValue()) {
+ ASSERT_NOT_REACHED();
+ return 0;
+ }
+ const AsyncCallStackTracker::AsyncCallChain* chain = m_asyncCallStackTracker.currentAsyncCallChain();
+ if (!chain)
+ return 0;
+ const AsyncCallStackTracker::AsyncCallStackVector& callStacks = chain->callStacks();
+ if (callStacks.isEmpty())
+ return 0;
+ RefPtr<StackTrace> result;
+ for (AsyncCallStackTracker::AsyncCallStackVector::const_reverse_iterator it = callStacks.rbegin(); it != callStacks.rend(); ++it) {
+ RefPtr<StackTrace> next = StackTrace::create()
+ .setCallFrames(injectedScript.wrapCallFrames((*it)->callFrames()))
+ .release();
+ next->setDescription((*it)->description());
+ if (result)
+ next->setAsyncStackTrace(result.release());
+ result.swap(next);
+ }
+ return result.release();
+}
+
String InspectorDebuggerAgent::sourceMapURLForScript(const Script& script)
{
bool deprecated;
@@ -958,7 +1069,7 @@ void InspectorDebuggerAgent::didPause(ScriptState* scriptState, const ScriptValu
InjectedScript injectedScript = m_injectedScriptManager->injectedScriptFor(scriptState);
if (!injectedScript.hasNoValue()) {
m_breakReason = InspectorFrontend::Debugger::Reason::Exception;
- m_breakAuxData = injectedScript.wrapObject(exception, "backtrace")->openAccessors();
+ m_breakAuxData = injectedScript.wrapObject(exception, InspectorDebuggerAgent::backtraceObjectGroup)->openAccessors();
// m_breakAuxData might be null after this.
}
}
@@ -977,7 +1088,7 @@ void InspectorDebuggerAgent::didPause(ScriptState* scriptState, const ScriptValu
}
}
- m_frontend->paused(currentCallFrames(), m_breakReason, m_breakAuxData, hitBreakpointIds);
+ m_frontend->paused(currentCallFrames(), m_breakReason, m_breakAuxData, hitBreakpointIds, currentAsyncStackTrace());
m_javaScriptPauseScheduled = false;
if (!m_continueToLocationBreakpointId.isEmpty()) {
@@ -1003,6 +1114,8 @@ bool InspectorDebuggerAgent::canBreakProgram()
void InspectorDebuggerAgent::breakProgram(InspectorFrontend::Debugger::Reason::Enum breakReason, PassRefPtr<JSONObject> data)
{
+ if (m_skipAllPauses)
+ return;
m_breakReason = breakReason;
m_breakAuxData = data;
scriptDebugServer().breakProgram();
@@ -1014,6 +1127,7 @@ void InspectorDebuggerAgent::clear()
m_currentCallStack = ScriptValue();
m_scripts.clear();
m_breakpointIdToDebugServerBreakpointIds.clear();
+ m_asyncCallStackTracker.clear();
m_continueToLocationBreakpointId = String();
clearBreakDetails();
m_javaScriptPauseScheduled = false;
@@ -1052,6 +1166,7 @@ void InspectorDebuggerAgent::reset()
{
m_scripts.clear();
m_breakpointIdToDebugServerBreakpointIds.clear();
+ m_asyncCallStackTracker.clear();
if (m_frontend)
m_frontend->globalObjectCleared();
}
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InspectorDebuggerAgent.h b/chromium/third_party/WebKit/Source/core/inspector/InspectorDebuggerAgent.h
index b4b281eb784..718a0c24e93 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InspectorDebuggerAgent.h
+++ b/chromium/third_party/WebKit/Source/core/inspector/InspectorDebuggerAgent.h
@@ -32,12 +32,13 @@
#include "InspectorFrontend.h"
#include "bindings/v8/ScriptState.h"
+#include "core/inspector/AsyncCallStackTracker.h"
#include "core/inspector/ConsoleAPITypes.h"
#include "core/inspector/InjectedScript.h"
#include "core/inspector/InspectorBaseAgent.h"
#include "core/inspector/ScriptBreakpoint.h"
#include "core/inspector/ScriptDebugListener.h"
-#include "core/page/ConsoleTypes.h"
+#include "core/frame/ConsoleTypes.h"
#include "wtf/Forward.h"
#include "wtf/HashMap.h"
#include "wtf/PassRefPtr.h"
@@ -46,6 +47,7 @@
namespace WebCore {
+class Document;
class InjectedScriptManager;
class InspectorFrontend;
class InstrumentingAgents;
@@ -55,7 +57,7 @@ class ScriptCallStack;
class ScriptDebugServer;
class ScriptSourceCode;
class ScriptValue;
-class RegularExpression;
+class ScriptRegexp;
typedef String ErrorString;
@@ -68,7 +70,7 @@ public:
MonitorCommandBreakpointSource
};
- static const char* backtraceObjectGroup;
+ static const char backtraceObjectGroup[];
virtual ~InspectorDebuggerAgent();
@@ -97,18 +99,18 @@ public:
virtual void removeBreakpoint(ErrorString*, const String& breakpointId);
virtual void continueToLocation(ErrorString*, const RefPtr<JSONObject>& location, const bool* interstateLocationOpt);
virtual void getStepInPositions(ErrorString*, const String& callFrameId, RefPtr<TypeBuilder::Array<TypeBuilder::Debugger::Location> >& positions);
- virtual void getBacktrace(ErrorString*, RefPtr<TypeBuilder::Array<TypeBuilder::Debugger::CallFrame> >&);
+ virtual void getBacktrace(ErrorString*, RefPtr<TypeBuilder::Array<TypeBuilder::Debugger::CallFrame> >&, RefPtr<TypeBuilder::Debugger::StackTrace>&);
virtual void searchInContent(ErrorString*, const String& scriptId, const String& query, const bool* optionalCaseSensitive, const bool* optionalIsRegex, RefPtr<TypeBuilder::Array<TypeBuilder::Page::SearchMatch> >&);
- virtual void setScriptSource(ErrorString*, RefPtr<TypeBuilder::Debugger::SetScriptSourceError>&, const String& scriptId, const String& newContent, const bool* preview, RefPtr<TypeBuilder::Array<TypeBuilder::Debugger::CallFrame> >& newCallFrames, RefPtr<JSONObject>& result);
- virtual void restartFrame(ErrorString*, const String& callFrameId, RefPtr<TypeBuilder::Array<TypeBuilder::Debugger::CallFrame> >& newCallFrames, RefPtr<JSONObject>& result);
+ virtual void setScriptSource(ErrorString*, RefPtr<TypeBuilder::Debugger::SetScriptSourceError>&, const String& scriptId, const String& newContent, const bool* preview, RefPtr<TypeBuilder::Array<TypeBuilder::Debugger::CallFrame> >& newCallFrames, RefPtr<JSONObject>& result, RefPtr<TypeBuilder::Debugger::StackTrace>& asyncStackTrace);
+ virtual void restartFrame(ErrorString*, const String& callFrameId, RefPtr<TypeBuilder::Array<TypeBuilder::Debugger::CallFrame> >& newCallFrames, RefPtr<JSONObject>& result, RefPtr<TypeBuilder::Debugger::StackTrace>& asyncStackTrace);
virtual void getScriptSource(ErrorString*, const String& scriptId, String* scriptSource);
virtual void getFunctionDetails(ErrorString*, const String& functionId, RefPtr<TypeBuilder::Debugger::FunctionDetails>&);
virtual void pause(ErrorString*);
virtual void resume(ErrorString*);
- virtual void stepOver(ErrorString*);
+ virtual void stepOver(ErrorString*, const String* callFrameId);
virtual void stepInto(ErrorString*);
- virtual void stepOut(ErrorString*);
+ virtual void stepOut(ErrorString*, const String* callFrameId);
virtual void setPauseOnExceptions(ErrorString*, const String& pauseState);
virtual void evaluateOnCallFrame(ErrorString*,
const String& callFrameId,
@@ -125,9 +127,17 @@ public:
virtual void setOverlayMessage(ErrorString*, const String*);
virtual void setVariableValue(ErrorString*, int in_scopeNumber, const String& in_variableName, const RefPtr<JSONObject>& in_newValue, const String* in_callFrame, const String* in_functionObjectId);
virtual void skipStackFrames(ErrorString*, const String* pattern);
+ virtual void setAsyncCallStackDepth(ErrorString*, int depth);
void schedulePauseOnNextStatement(InspectorFrontend::Debugger::Reason::Enum breakReason, PassRefPtr<JSONObject> data);
+ void didInstallTimer(ExecutionContext*, int timerId, int timeout, bool singleShot);
+ void didRemoveTimer(ExecutionContext*, int timerId);
+ bool willFireTimer(ExecutionContext*, int timerId);
void didFireTimer();
+ void didRequestAnimationFrame(Document*, int callbackId);
+ void didCancelAnimationFrame(Document*, int callbackId);
+ bool willFireAnimationFrame(Document*, int callbackId);
+ void didFireAnimationFrame();
void didHandleEvent();
bool canBreakProgram();
void breakProgram(InspectorFrontend::Debugger::Reason::Enum breakReason, PassRefPtr<JSONObject> data);
@@ -176,6 +186,7 @@ private:
bool enabled();
PassRefPtr<TypeBuilder::Array<TypeBuilder::Debugger::CallFrame> > currentCallFrames();
+ PassRefPtr<TypeBuilder::Debugger::StackTrace> currentAsyncStackTrace();
virtual void didParseSource(const String& scriptId, const Script&);
virtual void failedToParseSource(const String& url, const String& data, int firstLine, int errorLine, const String& errorMessage);
@@ -192,6 +203,8 @@ private:
String scriptURL(JavaScriptCallFrame*);
+ ScriptValue resolveCallFrame(ErrorString*, const String* callFrameId);
+
typedef HashMap<String, Script> ScriptsMap;
typedef HashMap<String, Vector<String> > BreakpointIdToDebugServerBreakpointIdsMap;
typedef HashMap<String, std::pair<String, BreakpointSource> > DebugServerBreakpointToBreakpointIdAndSourceMap;
@@ -211,7 +224,8 @@ private:
int m_skipStepInCount;
bool m_skipAllPauses;
- OwnPtr<RegularExpression> m_cachedSkipStackRegExp;
+ OwnPtr<ScriptRegexp> m_cachedSkipStackRegExp;
+ AsyncCallStackTracker m_asyncCallStackTracker;
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InspectorFileSystemAgent.cpp b/chromium/third_party/WebKit/Source/core/inspector/InspectorFileSystemAgent.cpp
index b16d96614ca..e406a22b8ee 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InspectorFileSystemAgent.cpp
+++ b/chromium/third_party/WebKit/Source/core/inspector/InspectorFileSystemAgent.cpp
@@ -34,16 +34,15 @@
#include "bindings/v8/ExceptionStatePlaceholder.h"
#include "core/dom/DOMImplementation.h"
#include "core/dom/Document.h"
-#include "core/dom/Event.h"
+#include "core/events/Event.h"
#include "core/fetch/TextResourceDecoder.h"
#include "core/fileapi/File.h"
#include "core/fileapi/FileError.h"
#include "core/fileapi/FileReader.h"
+#include "core/frame/Frame.h"
#include "core/html/VoidCallback.h"
#include "core/inspector/InspectorPageAgent.h"
#include "core/inspector/InspectorState.h"
-#include "core/page/Frame.h"
-#include "core/platform/MIMETypeRegistry.h"
#include "modules/filesystem/DOMFileSystem.h"
#include "modules/filesystem/DirectoryEntry.h"
#include "modules/filesystem/DirectoryReader.h"
@@ -57,8 +56,9 @@
#include "modules/filesystem/LocalFileSystem.h"
#include "modules/filesystem/Metadata.h"
#include "modules/filesystem/MetadataCallback.h"
-#include "weborigin/KURL.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/MIMETypeRegistry.h"
+#include "platform/weborigin/KURL.h"
+#include "platform/weborigin/SecurityOrigin.h"
#include "wtf/ArrayBuffer.h"
#include "wtf/text/Base64.h"
#include "wtf/text/TextEncoding.h"
@@ -84,14 +84,14 @@ class CallbackDispatcher : public BaseCallback {
public:
typedef bool (Handler::*HandlingMethod)(Argument);
- static PassRefPtr<CallbackDispatcher> create(PassRefPtr<Handler> handler, HandlingMethod handlingMethod)
+ static PassOwnPtr<CallbackDispatcher> create(PassRefPtr<Handler> handler, HandlingMethod handlingMethod)
{
- return adoptRef(new CallbackDispatcher(handler, handlingMethod));
+ return adoptPtr(new CallbackDispatcher(handler, handlingMethod));
}
- virtual bool handleEvent(Argument argument) OVERRIDE
+ virtual void handleEvent(Argument argument) OVERRIDE
{
- return (m_handler.get()->*m_handlingMethod)(argument);
+ (m_handler.get()->*m_handlingMethod)(argument);
}
private:
@@ -107,7 +107,7 @@ template<typename BaseCallback>
class CallbackDispatcherFactory {
public:
template<typename Handler, typename Argument>
- static PassRefPtr<CallbackDispatcher<BaseCallback, Handler, Argument> > create(Handler* handler, bool (Handler::*handlingMethod)(Argument))
+ static PassOwnPtr<CallbackDispatcher<BaseCallback, Handler, Argument> > create(Handler* handler, bool (Handler::*handlingMethod)(Argument))
{
return CallbackDispatcher<BaseCallback, Handler, Argument>::create(PassRefPtr<Handler>(handler), handlingMethod);
}
@@ -121,7 +121,7 @@ public:
return adoptRef(new FileSystemRootRequest(requestCallback, type));
}
- void start(ScriptExecutionContext*);
+ void start(ExecutionContext*);
private:
bool didHitError(FileError* error)
@@ -145,25 +145,27 @@ private:
String m_type;
};
-void FileSystemRootRequest::start(ScriptExecutionContext* scriptExecutionContext)
+void FileSystemRootRequest::start(ExecutionContext* executionContext)
{
- ASSERT(scriptExecutionContext);
+ ASSERT(executionContext);
+
+ OwnPtr<ErrorCallback> errorCallback = CallbackDispatcherFactory<ErrorCallback>::create(this, &FileSystemRootRequest::didHitError);
- RefPtr<ErrorCallback> errorCallback = CallbackDispatcherFactory<ErrorCallback>::create(this, &FileSystemRootRequest::didHitError);
FileSystemType type;
- if (m_type == DOMFileSystemBase::persistentPathPrefix)
- type = FileSystemTypePersistent;
- else if (m_type == DOMFileSystemBase::temporaryPathPrefix)
- type = FileSystemTypeTemporary;
- else {
+ if (!DOMFileSystemBase::pathPrefixToFileSystemType(m_type, type)) {
errorCallback->handleEvent(FileError::create(FileError::SYNTAX_ERR).get());
return;
}
- RefPtr<EntryCallback> successCallback = CallbackDispatcherFactory<EntryCallback>::create(this, &FileSystemRootRequest::didGetEntry);
- OwnPtr<AsyncFileSystemCallbacks> fileSystemCallbacks = ResolveURICallbacks::create(successCallback, errorCallback, scriptExecutionContext, type, "/");
+ KURL rootURL = DOMFileSystemBase::createFileSystemRootURL(executionContext->securityOrigin()->toString(), type);
+ if (!rootURL.isValid()) {
+ errorCallback->handleEvent(FileError::create(FileError::SYNTAX_ERR).get());
+ return;
+ }
- LocalFileSystem::from(scriptExecutionContext)->readFileSystem(scriptExecutionContext, type, fileSystemCallbacks.release());
+ OwnPtr<EntryCallback> successCallback = CallbackDispatcherFactory<EntryCallback>::create(this, &FileSystemRootRequest::didGetEntry);
+ OwnPtr<AsyncFileSystemCallbacks> fileSystemCallbacks = ResolveURICallbacks::create(successCallback.release(), errorCallback.release(), executionContext);
+ LocalFileSystem::from(executionContext)->resolveURL(executionContext, rootURL, fileSystemCallbacks.release());
}
bool FileSystemRootRequest::didGetEntry(Entry* entry)
@@ -189,7 +191,7 @@ public:
reportResult(FileError::ABORT_ERR);
}
- void start(ScriptExecutionContext*);
+ void start(ExecutionContext*);
private:
bool didHitError(FileError* error)
@@ -218,22 +220,16 @@ private:
RefPtr<DirectoryReader> m_directoryReader;
};
-void DirectoryContentRequest::start(ScriptExecutionContext* scriptExecutionContext)
+void DirectoryContentRequest::start(ExecutionContext* executionContext)
{
- ASSERT(scriptExecutionContext);
+ ASSERT(executionContext);
- RefPtr<ErrorCallback> errorCallback = CallbackDispatcherFactory<ErrorCallback>::create(this, &DirectoryContentRequest::didHitError);
- FileSystemType type;
- String path;
- if (!DOMFileSystemBase::crackFileSystemURL(m_url, type, path)) {
- errorCallback->handleEvent(FileError::create(FileError::SYNTAX_ERR).get());
- return;
- }
+ OwnPtr<ErrorCallback> errorCallback = CallbackDispatcherFactory<ErrorCallback>::create(this, &DirectoryContentRequest::didHitError);
+ OwnPtr<EntryCallback> successCallback = CallbackDispatcherFactory<EntryCallback>::create(this, &DirectoryContentRequest::didGetEntry);
- RefPtr<EntryCallback> successCallback = CallbackDispatcherFactory<EntryCallback>::create(this, &DirectoryContentRequest::didGetEntry);
- OwnPtr<AsyncFileSystemCallbacks> fileSystemCallbacks = ResolveURICallbacks::create(successCallback, errorCallback, scriptExecutionContext, type, path);
+ OwnPtr<AsyncFileSystemCallbacks> fileSystemCallbacks = ResolveURICallbacks::create(successCallback.release(), errorCallback.release(), executionContext);
- LocalFileSystem::from(scriptExecutionContext)->readFileSystem(scriptExecutionContext, type, fileSystemCallbacks.release());
+ LocalFileSystem::from(executionContext)->resolveURL(executionContext, m_url, fileSystemCallbacks.release());
}
bool DirectoryContentRequest::didGetEntry(Entry* entry)
@@ -243,7 +239,7 @@ bool DirectoryContentRequest::didGetEntry(Entry* entry)
return true;
}
- m_directoryReader = static_cast<DirectoryEntry*>(entry)->createReader();
+ m_directoryReader = toDirectoryEntry(entry)->createReader();
m_entries = Array<TypeBuilder::FileSystem::Entry>::create();
readDirectoryEntries();
return true;
@@ -251,14 +247,14 @@ bool DirectoryContentRequest::didGetEntry(Entry* entry)
void DirectoryContentRequest::readDirectoryEntries()
{
- if (!m_directoryReader->filesystem()->scriptExecutionContext()) {
+ if (!m_directoryReader->filesystem()->executionContext()) {
reportResult(FileError::ABORT_ERR);
return;
}
- RefPtr<EntriesCallback> successCallback = CallbackDispatcherFactory<EntriesCallback>::create(this, &DirectoryContentRequest::didReadDirectoryEntries);
- RefPtr<ErrorCallback> errorCallback = CallbackDispatcherFactory<ErrorCallback>::create(this, &DirectoryContentRequest::didHitError);
- m_directoryReader->readEntries(successCallback, errorCallback);
+ OwnPtr<EntriesCallback> successCallback = CallbackDispatcherFactory<EntriesCallback>::create(this, &DirectoryContentRequest::didReadDirectoryEntries);
+ OwnPtr<ErrorCallback> errorCallback = CallbackDispatcherFactory<ErrorCallback>::create(this, &DirectoryContentRequest::didHitError);
+ m_directoryReader->readEntries(successCallback.release(), errorCallback.release());
}
bool DirectoryContentRequest::didReadDirectoryEntries(const EntryVector& entries)
@@ -316,7 +312,7 @@ public:
reportResult(FileError::ABORT_ERR);
}
- void start(ScriptExecutionContext*);
+ void start(ExecutionContext*);
private:
bool didHitError(FileError* error)
@@ -339,37 +335,29 @@ private:
RefPtr<RequestMetadataCallback> m_requestCallback;
KURL m_url;
- String m_path;
bool m_isDirectory;
};
-void MetadataRequest::start(ScriptExecutionContext* scriptExecutionContext)
+void MetadataRequest::start(ExecutionContext* executionContext)
{
- ASSERT(scriptExecutionContext);
-
- RefPtr<ErrorCallback> errorCallback = CallbackDispatcherFactory<ErrorCallback>::create(this, &MetadataRequest::didHitError);
-
- FileSystemType type;
- if (!DOMFileSystemBase::crackFileSystemURL(m_url, type, m_path)) {
- errorCallback->handleEvent(FileError::create(FileError::SYNTAX_ERR).get());
- return;
- }
+ ASSERT(executionContext);
- RefPtr<EntryCallback> successCallback = CallbackDispatcherFactory<EntryCallback>::create(this, &MetadataRequest::didGetEntry);
- OwnPtr<AsyncFileSystemCallbacks> fileSystemCallbacks = ResolveURICallbacks::create(successCallback, errorCallback, scriptExecutionContext, type, m_path);
- LocalFileSystem::from(scriptExecutionContext)->readFileSystem(scriptExecutionContext, type, fileSystemCallbacks.release());
+ OwnPtr<ErrorCallback> errorCallback = CallbackDispatcherFactory<ErrorCallback>::create(this, &MetadataRequest::didHitError);
+ OwnPtr<EntryCallback> successCallback = CallbackDispatcherFactory<EntryCallback>::create(this, &MetadataRequest::didGetEntry);
+ OwnPtr<AsyncFileSystemCallbacks> fileSystemCallbacks = ResolveURICallbacks::create(successCallback.release(), errorCallback.release(), executionContext);
+ LocalFileSystem::from(executionContext)->resolveURL(executionContext, m_url, fileSystemCallbacks.release());
}
bool MetadataRequest::didGetEntry(Entry* entry)
{
- if (!entry->filesystem()->scriptExecutionContext()) {
+ if (!entry->filesystem()->executionContext()) {
reportResult(FileError::ABORT_ERR);
return true;
}
- RefPtr<MetadataCallback> successCallback = CallbackDispatcherFactory<MetadataCallback>::create(this, &MetadataRequest::didGetMetadata);
- RefPtr<ErrorCallback> errorCallback = CallbackDispatcherFactory<ErrorCallback>::create(this, &MetadataRequest::didHitError);
- entry->getMetadata(successCallback, errorCallback);
+ OwnPtr<MetadataCallback> successCallback = CallbackDispatcherFactory<MetadataCallback>::create(this, &MetadataRequest::didGetMetadata);
+ OwnPtr<ErrorCallback> errorCallback = CallbackDispatcherFactory<ErrorCallback>::create(this, &MetadataRequest::didHitError);
+ entry->getMetadata(successCallback.release(), errorCallback.release());
m_isDirectory = entry->isDirectory();
return true;
}
@@ -397,18 +385,18 @@ public:
reportResult(FileError::ABORT_ERR);
}
- void start(ScriptExecutionContext*);
+ void start(ExecutionContext*);
virtual bool operator==(const EventListener& other) OVERRIDE
{
return this == &other;
}
- virtual void handleEvent(ScriptExecutionContext*, Event* event) OVERRIDE
+ virtual void handleEvent(ExecutionContext*, Event* event) OVERRIDE
{
- if (event->type() == eventNames().loadEvent)
+ if (event->type() == EventTypeNames::load)
didRead();
- else if (event->type() == eventNames().errorEvent)
+ else if (event->type() == EventTypeNames::error)
didHitError(m_reader->error().get());
}
@@ -448,23 +436,15 @@ private:
RefPtr<FileReader> m_reader;
};
-void FileContentRequest::start(ScriptExecutionContext* scriptExecutionContext)
+void FileContentRequest::start(ExecutionContext* executionContext)
{
- ASSERT(scriptExecutionContext);
-
- RefPtr<ErrorCallback> errorCallback = CallbackDispatcherFactory<ErrorCallback>::create(this, &FileContentRequest::didHitError);
+ ASSERT(executionContext);
- FileSystemType type;
- String path;
- if (!DOMFileSystemBase::crackFileSystemURL(m_url, type, path)) {
- errorCallback->handleEvent(FileError::create(FileError::SYNTAX_ERR).get());
- return;
- }
-
- RefPtr<EntryCallback> successCallback = CallbackDispatcherFactory<EntryCallback>::create(this, &FileContentRequest::didGetEntry);
- OwnPtr<AsyncFileSystemCallbacks> fileSystemCallbacks = ResolveURICallbacks::create(successCallback, errorCallback, scriptExecutionContext, type, path);
+ OwnPtr<ErrorCallback> errorCallback = CallbackDispatcherFactory<ErrorCallback>::create(this, &FileContentRequest::didHitError);
+ OwnPtr<EntryCallback> successCallback = CallbackDispatcherFactory<EntryCallback>::create(this, &FileContentRequest::didGetEntry);
- LocalFileSystem::from(scriptExecutionContext)->readFileSystem(scriptExecutionContext, type, fileSystemCallbacks.release());
+ OwnPtr<AsyncFileSystemCallbacks> fileSystemCallbacks = ResolveURICallbacks::create(successCallback.release(), errorCallback.release(), executionContext);
+ LocalFileSystem::from(executionContext)->resolveURL(executionContext, m_url, fileSystemCallbacks.release());
}
bool FileContentRequest::didGetEntry(Entry* entry)
@@ -474,16 +454,16 @@ bool FileContentRequest::didGetEntry(Entry* entry)
return true;
}
- if (!entry->filesystem()->scriptExecutionContext()) {
+ if (!entry->filesystem()->executionContext()) {
reportResult(FileError::ABORT_ERR);
return true;
}
- RefPtr<FileCallback> successCallback = CallbackDispatcherFactory<FileCallback>::create(this, &FileContentRequest::didGetFile);
- RefPtr<ErrorCallback> errorCallback = CallbackDispatcherFactory<ErrorCallback>::create(this, &FileContentRequest::didHitError);
- static_cast<FileEntry*>(entry)->file(successCallback, errorCallback);
+ OwnPtr<FileCallback> successCallback = CallbackDispatcherFactory<FileCallback>::create(this, &FileContentRequest::didGetFile);
+ OwnPtr<ErrorCallback> errorCallback = CallbackDispatcherFactory<ErrorCallback>::create(this, &FileContentRequest::didHitError);
+ toFileEntry(entry)->file(successCallback.release(), errorCallback.release());
- m_reader = FileReader::create(entry->filesystem()->scriptExecutionContext());
+ m_reader = FileReader::create(entry->filesystem()->executionContext());
m_mimeType = MIMETypeRegistry::getMIMETypeForPath(entry->name());
return true;
@@ -509,14 +489,14 @@ void FileContentRequest::didRead()
return;
}
- RefPtr<TextResourceDecoder> decoder = TextResourceDecoder::create(m_mimeType, m_charset, true);
+ OwnPtr<TextResourceDecoder> decoder = TextResourceDecoder::create(m_mimeType, m_charset, true);
String result = decoder->decode(static_cast<char*>(buffer->data()), buffer->byteLength());
result.append(decoder->flush());
- m_charset = decoder->encoding().domName();
+ m_charset = decoder->encoding().name();
reportResult(static_cast<FileError::ErrorCode>(0), &result, &m_charset);
}
-class DeleteEntryRequest : public VoidCallback {
+class DeleteEntryRequest : public RefCounted<DeleteEntryRequest> {
public:
static PassRefPtr<DeleteEntryRequest> create(PassRefPtr<DeleteEntryCallback> requestCallback, const KURL& url)
{
@@ -528,14 +508,26 @@ public:
reportResult(FileError::ABORT_ERR);
}
- virtual bool handleEvent() OVERRIDE
- {
- return didDeleteEntry();
- }
-
- void start(ScriptExecutionContext*);
+ void start(ExecutionContext*);
private:
+ // CallbackDispatcherFactory doesn't handle 0-arg handleEvent methods
+ class VoidCallbackImpl : public VoidCallback {
+ public:
+ explicit VoidCallbackImpl(PassRefPtr<DeleteEntryRequest> handler)
+ : m_handler(handler)
+ {
+ }
+
+ virtual void handleEvent() OVERRIDE
+ {
+ m_handler->didDeleteEntry();
+ }
+
+ private:
+ RefPtr<DeleteEntryRequest> m_handler;
+ };
+
bool didHitError(FileError* error)
{
reportResult(error->code());
@@ -558,11 +550,11 @@ private:
KURL m_url;
};
-void DeleteEntryRequest::start(ScriptExecutionContext* scriptExecutionContext)
+void DeleteEntryRequest::start(ExecutionContext* executionContext)
{
- ASSERT(scriptExecutionContext);
+ ASSERT(executionContext);
- RefPtr<ErrorCallback> errorCallback = CallbackDispatcherFactory<ErrorCallback>::create(this, &DeleteEntryRequest::didHitError);
+ OwnPtr<ErrorCallback> errorCallback = CallbackDispatcherFactory<ErrorCallback>::create(this, &DeleteEntryRequest::didHitError);
FileSystemType type;
String path;
@@ -572,23 +564,26 @@ void DeleteEntryRequest::start(ScriptExecutionContext* scriptExecutionContext)
}
if (path == "/") {
- OwnPtr<AsyncFileSystemCallbacks> fileSystemCallbacks = VoidCallbacks::create(this, errorCallback, 0);
- LocalFileSystem::from(scriptExecutionContext)->deleteFileSystem(scriptExecutionContext, type, fileSystemCallbacks.release());
+ OwnPtr<VoidCallback> successCallback = adoptPtr(new VoidCallbackImpl(this));
+ OwnPtr<AsyncFileSystemCallbacks> fileSystemCallbacks = VoidCallbacks::create(successCallback.release(), errorCallback.release(), 0);
+ LocalFileSystem::from(executionContext)->deleteFileSystem(executionContext, type, fileSystemCallbacks.release());
} else {
- RefPtr<EntryCallback> successCallback = CallbackDispatcherFactory<EntryCallback>::create(this, &DeleteEntryRequest::didGetEntry);
- OwnPtr<AsyncFileSystemCallbacks> fileSystemCallbacks = ResolveURICallbacks::create(successCallback, errorCallback, scriptExecutionContext, type, path);
- LocalFileSystem::from(scriptExecutionContext)->readFileSystem(scriptExecutionContext, type, fileSystemCallbacks.release());
+ OwnPtr<EntryCallback> successCallback = CallbackDispatcherFactory<EntryCallback>::create(this, &DeleteEntryRequest::didGetEntry);
+ OwnPtr<AsyncFileSystemCallbacks> fileSystemCallbacks = ResolveURICallbacks::create(successCallback.release(), errorCallback.release(), executionContext);
+ LocalFileSystem::from(executionContext)->resolveURL(executionContext, m_url, fileSystemCallbacks.release());
}
}
bool DeleteEntryRequest::didGetEntry(Entry* entry)
{
- RefPtr<ErrorCallback> errorCallback = CallbackDispatcherFactory<ErrorCallback>::create(this, &DeleteEntryRequest::didHitError);
+ OwnPtr<VoidCallback> successCallback = adoptPtr(new VoidCallbackImpl(this));
+ OwnPtr<ErrorCallback> errorCallback = CallbackDispatcherFactory<ErrorCallback>::create(this, &DeleteEntryRequest::didHitError);
if (entry->isDirectory()) {
- DirectoryEntry* directoryEntry = static_cast<DirectoryEntry*>(entry);
- directoryEntry->removeRecursively(this, errorCallback);
- } else
- entry->remove(this, errorCallback);
+ DirectoryEntry* directoryEntry = toDirectoryEntry(entry);
+ directoryEntry->removeRecursively(successCallback.release(), errorCallback.release());
+ } else {
+ entry->remove(successCallback.release(), errorCallback.release());
+ }
return true;
}
@@ -631,11 +626,11 @@ void InspectorFileSystemAgent::requestFileSystemRoot(ErrorString* error, const S
if (!assertEnabled(error))
return;
- ScriptExecutionContext* scriptExecutionContext = assertScriptExecutionContextForOrigin(error, SecurityOrigin::createFromString(origin).get());
- if (!scriptExecutionContext)
+ ExecutionContext* executionContext = assertExecutionContextForOrigin(error, SecurityOrigin::createFromString(origin).get());
+ if (!executionContext)
return;
- FileSystemRootRequest::create(requestCallback, type)->start(scriptExecutionContext);
+ FileSystemRootRequest::create(requestCallback, type)->start(executionContext);
}
void InspectorFileSystemAgent::requestDirectoryContent(ErrorString* error, const String& url, PassRefPtr<RequestDirectoryContentCallback> requestCallback)
@@ -643,11 +638,11 @@ void InspectorFileSystemAgent::requestDirectoryContent(ErrorString* error, const
if (!assertEnabled(error))
return;
- ScriptExecutionContext* scriptExecutionContext = assertScriptExecutionContextForOrigin(error, SecurityOrigin::createFromString(url).get());
- if (!scriptExecutionContext)
+ ExecutionContext* executionContext = assertExecutionContextForOrigin(error, SecurityOrigin::createFromString(url).get());
+ if (!executionContext)
return;
- DirectoryContentRequest::create(requestCallback, url)->start(scriptExecutionContext);
+ DirectoryContentRequest::create(requestCallback, url)->start(executionContext);
}
void InspectorFileSystemAgent::requestMetadata(ErrorString* error, const String& url, PassRefPtr<RequestMetadataCallback> requestCallback)
@@ -655,11 +650,11 @@ void InspectorFileSystemAgent::requestMetadata(ErrorString* error, const String&
if (!assertEnabled(error))
return;
- ScriptExecutionContext* scriptExecutionContext = assertScriptExecutionContextForOrigin(error, SecurityOrigin::createFromString(url).get());
- if (!scriptExecutionContext)
+ ExecutionContext* executionContext = assertExecutionContextForOrigin(error, SecurityOrigin::createFromString(url).get());
+ if (!executionContext)
return;
- MetadataRequest::create(requestCallback, url)->start(scriptExecutionContext);
+ MetadataRequest::create(requestCallback, url)->start(executionContext);
}
void InspectorFileSystemAgent::requestFileContent(ErrorString* error, const String& url, bool readAsText, const int* start, const int* end, const String* charset, PassRefPtr<RequestFileContentCallback> requestCallback)
@@ -667,13 +662,13 @@ void InspectorFileSystemAgent::requestFileContent(ErrorString* error, const Stri
if (!assertEnabled(error))
return;
- ScriptExecutionContext* scriptExecutionContext = assertScriptExecutionContextForOrigin(error, SecurityOrigin::createFromString(url).get());
- if (!scriptExecutionContext)
+ ExecutionContext* executionContext = assertExecutionContextForOrigin(error, SecurityOrigin::createFromString(url).get());
+ if (!executionContext)
return;
long long startPosition = start ? *start : 0;
long long endPosition = end ? *end : std::numeric_limits<long long>::max();
- FileContentRequest::create(requestCallback, url, readAsText, startPosition, endPosition, charset ? *charset : "")->start(scriptExecutionContext);
+ FileContentRequest::create(requestCallback, url, readAsText, startPosition, endPosition, charset ? *charset : "")->start(executionContext);
}
void InspectorFileSystemAgent::deleteEntry(ErrorString* error, const String& urlString, PassRefPtr<DeleteEntryCallback> requestCallback)
@@ -683,11 +678,11 @@ void InspectorFileSystemAgent::deleteEntry(ErrorString* error, const String& url
KURL url(ParsedURLString, urlString);
- ScriptExecutionContext* scriptExecutionContext = assertScriptExecutionContextForOrigin(error, SecurityOrigin::create(url).get());
- if (!scriptExecutionContext)
+ ExecutionContext* executionContext = assertExecutionContextForOrigin(error, SecurityOrigin::create(url).get());
+ if (!executionContext)
return;
- DeleteEntryRequest::create(requestCallback, url)->start(scriptExecutionContext);
+ DeleteEntryRequest::create(requestCallback, url)->start(executionContext);
}
void InspectorFileSystemAgent::clearFrontend()
@@ -720,9 +715,9 @@ bool InspectorFileSystemAgent::assertEnabled(ErrorString* error)
return true;
}
-ScriptExecutionContext* InspectorFileSystemAgent::assertScriptExecutionContextForOrigin(ErrorString* error, SecurityOrigin* origin)
+ExecutionContext* InspectorFileSystemAgent::assertExecutionContextForOrigin(ErrorString* error, SecurityOrigin* origin)
{
- for (Frame* frame = m_pageAgent->mainFrame(); frame; frame = frame->tree()->traverseNext()) {
+ for (Frame* frame = m_pageAgent->mainFrame(); frame; frame = frame->tree().traverseNext()) {
if (frame->document() && frame->document()->securityOrigin()->isSameSchemeHostPort(origin))
return frame->document();
}
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InspectorFileSystemAgent.h b/chromium/third_party/WebKit/Source/core/inspector/InspectorFileSystemAgent.h
index e6bd23cbbd0..24e68ab0e33 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InspectorFileSystemAgent.h
+++ b/chromium/third_party/WebKit/Source/core/inspector/InspectorFileSystemAgent.h
@@ -38,7 +38,7 @@
namespace WebCore {
class InspectorPageAgent;
-class ScriptExecutionContext;
+class ExecutionContext;
class SecurityOrigin;
class InspectorFileSystemAgent : public InspectorBaseAgent<InspectorFileSystemAgent>, public InspectorBackendDispatcher::FileSystemCommandHandler {
@@ -61,7 +61,7 @@ public:
private:
InspectorFileSystemAgent(InstrumentingAgents*, InspectorPageAgent*, InspectorCompositeState*);
bool assertEnabled(ErrorString*);
- ScriptExecutionContext* assertScriptExecutionContextForOrigin(ErrorString*, SecurityOrigin*);
+ ExecutionContext* assertExecutionContextForOrigin(ErrorString*, SecurityOrigin*);
InspectorPageAgent* m_pageAgent;
bool m_enabled;
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InspectorFrontendHost.cpp b/chromium/third_party/WebKit/Source/core/inspector/InspectorFrontendHost.cpp
index a8e0d6b269d..20f2160f56f 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InspectorFrontendHost.cpp
+++ b/chromium/third_party/WebKit/Source/core/inspector/InspectorFrontendHost.cpp
@@ -31,26 +31,27 @@
#include "core/inspector/InspectorFrontendHost.h"
#include "bindings/v8/ScriptFunctionCall.h"
-#include "core/dom/UserGestureIndicator.h"
+#include "bindings/v8/ScriptState.h"
#include "core/fetch/ResourceFetcher.h"
#include "core/fetch/TextResourceDecoder.h"
+#include "core/frame/Frame.h"
#include "core/inspector/InspectorController.h"
#include "core/inspector/InspectorFrontendClient.h"
#include "core/loader/FrameLoader.h"
#include "core/page/ContextMenuController.h"
#include "core/page/ContextMenuProvider.h"
-#include "core/page/Frame.h"
#include "core/page/Page.h"
-#include "core/platform/ContextMenu.h"
-#include "core/platform/ContextMenuItem.h"
-#include "core/platform/JSONValues.h"
#include "core/platform/Pasteboard.h"
-#include "core/platform/SharedBuffer.h"
-#include "core/platform/network/ResourceError.h"
-#include "core/platform/network/ResourceRequest.h"
-#include "core/platform/network/ResourceResponse.h"
#include "core/rendering/RenderTheme.h"
#include "modules/filesystem/DOMFileSystem.h"
+#include "platform/ContextMenu.h"
+#include "platform/ContextMenuItem.h"
+#include "platform/JSONValues.h"
+#include "platform/SharedBuffer.h"
+#include "platform/UserGestureIndicator.h"
+#include "platform/network/ResourceError.h"
+#include "platform/network/ResourceRequest.h"
+#include "platform/network/ResourceResponse.h"
namespace WebCore {
@@ -135,20 +136,6 @@ void InspectorFrontendHost::disconnectClient()
m_frontendPage = 0;
}
-void InspectorFrontendHost::loaded()
-{
-}
-
-void InspectorFrontendHost::closeWindow()
-{
- if (m_client) {
- RefPtr<JSONObject> message = JSONObject::create();
- message->setString("method", "closeWindow");
- sendMessageToEmbedder(message->toJSONString());
- disconnectClient(); // Disconnect from client.
- }
-}
-
void InspectorFrontendHost::setZoomFactor(float zoom)
{
m_frontendPage->mainFrame()->setPageAndTextZoomFactors(zoom, 1);
@@ -160,34 +147,16 @@ void InspectorFrontendHost::inspectedURLChanged(const String& newURL)
m_client->inspectedURLChanged(newURL);
}
-void InspectorFrontendHost::setAttachedWindowHeight(unsigned height)
-{
-}
-
void InspectorFrontendHost::setInjectedScriptForOrigin(const String& origin, const String& script)
{
m_frontendPage->inspectorController().setInjectedScriptForOrigin(origin, script);
}
-String InspectorFrontendHost::localizedStringsURL()
-{
- return "";
-}
-
void InspectorFrontendHost::copyText(const String& text)
{
Pasteboard::generalPasteboard()->writePlainText(text, Pasteboard::CannotSmartReplace);
}
-bool InspectorFrontendHost::canSave()
-{
- return true;
-}
-
-void InspectorFrontendHost::close(const String&)
-{
-}
-
void InspectorFrontendHost::sendMessageToBackend(const String& message)
{
if (m_client)
@@ -217,23 +186,6 @@ void InspectorFrontendHost::showContextMenu(Event* event, const Vector<ContextMe
m_menuProvider = menuProvider.get();
}
-String InspectorFrontendHost::loadResourceSynchronously(const String& url)
-{
- FetchRequest request(url, FetchInitiatorInfo());
- ResourcePtr<Resource> resource = m_frontendPage->mainFrame()->document()->fetcher()->fetchSynchronously(request);
- if (!resource)
- return emptyString();
- WTF::TextEncoding textEncoding(resource->response().textEncodingName());
- bool useDetector = false;
- if (!textEncoding.isValid()) {
- textEncoding = UTF8Encoding();
- useDetector = true;
- }
- RefPtr<TextResourceDecoder> decoder = TextResourceDecoder::create("text/plain", textEncoding, useDetector);
- SharedBuffer* data = resource->resourceBuffer();
- return decoder->decode(data->data(), data->size()) + decoder->flush();
-}
-
String InspectorFrontendHost::getSelectionBackgroundColor()
{
Color color = RenderTheme::theme().activeSelectionBackgroundColor();
@@ -246,35 +198,28 @@ String InspectorFrontendHost::getSelectionForegroundColor()
return color.isValid() ? color.serialized() : "";
}
-bool InspectorFrontendHost::supportsFileSystems()
-{
- return true;
-}
-
PassRefPtr<DOMFileSystem> InspectorFrontendHost::isolatedFileSystem(const String& fileSystemName, const String& rootURL)
{
- ScriptExecutionContext* context = m_frontendPage->mainFrame()->document();
+ ExecutionContext* context = m_frontendPage->mainFrame()->document();
return DOMFileSystem::create(context, fileSystemName, FileSystemTypeIsolated, KURL(ParsedURLString, rootURL));
}
-bool InspectorFrontendHost::isUnderTest()
-{
- return m_client && m_client->isUnderTest();
-}
-
-bool InspectorFrontendHost::canSaveAs()
+void InspectorFrontendHost::upgradeDraggedFileSystemPermissions(DOMFileSystem* domFileSystem)
{
- return false;
-}
-
-bool InspectorFrontendHost::canInspectWorkers()
-{
- return false;
+ if (!m_client)
+ return;
+ RefPtr<JSONObject> message = JSONObject::create();
+ message->setNumber("id", 0);
+ message->setString("method", "upgradeDraggedFileSystemPermissions");
+ RefPtr<JSONArray> params = JSONArray::create();
+ message->setArray("params", params);
+ params->pushString(domFileSystem->rootURL().string());
+ sendMessageToEmbedder(message->toJSONString());
}
-String InspectorFrontendHost::hiddenPanels()
+bool InspectorFrontendHost::isUnderTest()
{
- return "";
+ return m_client && m_client->isUnderTest();
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InspectorFrontendHost.h b/chromium/third_party/WebKit/Source/core/inspector/InspectorFrontendHost.h
index 4c955c35b4c..1bccdca379f 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InspectorFrontendHost.h
+++ b/chromium/third_party/WebKit/Source/core/inspector/InspectorFrontendHost.h
@@ -30,7 +30,6 @@
#define InspectorFrontendHost_h
#include "bindings/v8/ScriptWrappable.h"
-#include "core/platform/ContextMenu.h"
#include "wtf/RefCounted.h"
#include "wtf/Vector.h"
#include "wtf/text/WTFString.h"
@@ -54,38 +53,26 @@ public:
~InspectorFrontendHost();
void disconnectClient();
- void closeWindow();
void setZoomFactor(float);
void inspectedURLChanged(const String&);
- void setAttachedWindowHeight(unsigned);
void setInjectedScriptForOrigin(const String& origin, const String& script);
void copyText(const String& text);
- void close(const String& url);
// Called from [Custom] implementations.
void showContextMenu(Event*, const Vector<ContextMenuItem>& items);
void sendMessageToBackend(const String& message);
void sendMessageToEmbedder(const String& message);
- String loadResourceSynchronously(const String& url);
String getSelectionBackgroundColor();
String getSelectionForegroundColor();
PassRefPtr<DOMFileSystem> isolatedFileSystem(const String& fileSystemName, const String& rootURL);
+ void upgradeDraggedFileSystemPermissions(DOMFileSystem*);
bool isUnderTest();
- // Deprecated but should stay around for a while as old front-ends may use them.
- bool canInspectWorkers();
- bool canSaveAs();
- bool canSave();
- bool supportsFileSystems();
- void loaded();
- String hiddenPanels();
- String localizedStringsURL();
-
private:
friend class FrontendMenuProvider;
InspectorFrontendHost(InspectorFrontendClient* client, Page* frontendPage);
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InspectorFrontendHost.idl b/chromium/third_party/WebKit/Source/core/inspector/InspectorFrontendHost.idl
index 678a36cb89a..467e7aa563e 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InspectorFrontendHost.idl
+++ b/chromium/third_party/WebKit/Source/core/inspector/InspectorFrontendHost.idl
@@ -33,15 +33,12 @@
[
NoInterfaceObject
] interface InspectorFrontendHost {
- void closeWindow();
void setZoomFactor(float zoom);
void inspectedURLChanged(DOMString newURL);
- void setAttachedWindowHeight(unsigned long height);
void setInjectedScriptForOrigin(DOMString origin, DOMString script);
void copyText(DOMString text);
- void close(DOMString url);
[Custom] DOMString platform();
[Custom] DOMString port();
@@ -53,20 +50,11 @@
[Custom] void recordPanelShown(unsigned long panelCode);
[Custom] void recordSettingChanged(unsigned long settingChanged);
- DOMString loadResourceSynchronously(DOMString url);
DOMString getSelectionBackgroundColor();
DOMString getSelectionForegroundColor();
DOMFileSystem isolatedFileSystem(DOMString fileSystemId, DOMString registeredName);
+ void upgradeDraggedFileSystemPermissions(DOMFileSystem domFileSystem);
boolean isUnderTest();
-
- // Deprecated
- boolean canInspectWorkers();
- boolean canSaveAs();
- boolean canSave();
- boolean supportsFileSystems();
- void loaded();
- DOMString hiddenPanels();
- DOMString localizedStringsURL();
};
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InspectorHeapProfilerAgent.cpp b/chromium/third_party/WebKit/Source/core/inspector/InspectorHeapProfilerAgent.cpp
index d85ed881113..fd67c240bc1 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InspectorHeapProfilerAgent.cpp
+++ b/chromium/third_party/WebKit/Source/core/inspector/InspectorHeapProfilerAgent.cpp
@@ -32,20 +32,19 @@
#include "core/inspector/InspectorHeapProfilerAgent.h"
#include "bindings/v8/ScriptProfiler.h"
+#include "bindings/v8/ScriptScope.h"
#include "core/inspector/InjectedScript.h"
#include "core/inspector/InjectedScriptHost.h"
#include "core/inspector/InspectorState.h"
-#include "core/platform/Timer.h"
+#include "platform/Timer.h"
#include "wtf/CurrentTime.h"
namespace WebCore {
namespace HeapProfilerAgentState {
-static const char profileHeadersRequested[] = "profileHeadersRequested";
+static const char heapProfilerEnabled[] = "heapProfilerEnabled";
}
-static const char* const userInitiatedProfileNameHeap = "org.webkit.profiles.user-initiated";
-
class InspectorHeapProfilerAgent::HeapStatsUpdateTask {
public:
HeapStatsUpdateTask(InspectorHeapProfilerAgent*);
@@ -79,16 +78,16 @@ void InspectorHeapProfilerAgent::clearProfiles(ErrorString*)
{
m_snapshots.clear();
m_nextUserInitiatedHeapSnapshotNumber = 1;
+ stopTrackingHeapObjectsInternal();
resetFrontendProfiles();
m_injectedScriptManager->injectedScriptHost()->clearInspectedObjects();
}
void InspectorHeapProfilerAgent::resetFrontendProfiles()
{
- stopTrackingHeapObjects(0);
if (!m_frontend)
return;
- if (!m_state->getBoolean(HeapProfilerAgentState::profileHeadersRequested))
+ if (!m_state->getBoolean(HeapProfilerAgentState::heapProfilerEnabled))
return;
if (m_snapshots.isEmpty())
m_frontend->resetProfiles();
@@ -101,9 +100,10 @@ void InspectorHeapProfilerAgent::setFrontend(InspectorFrontend* frontend)
void InspectorHeapProfilerAgent::clearFrontend()
{
- stopTrackingHeapObjects(0);
- m_state->setBoolean(HeapProfilerAgentState::profileHeadersRequested, false);
m_frontend = 0;
+ ErrorString error;
+ clearProfiles(&error);
+ disable(&error);
}
void InspectorHeapProfilerAgent::restore()
@@ -189,7 +189,18 @@ void InspectorHeapProfilerAgent::pushHeapStatsUpdate(const uint32_t* const data,
m_frontend->heapStatsUpdate(statsDiff.release());
}
-void InspectorHeapProfilerAgent::stopTrackingHeapObjects(ErrorString*)
+void InspectorHeapProfilerAgent::stopTrackingHeapObjects(ErrorString* error, const bool* reportProgress)
+{
+ if (!m_heapStatsUpdateTask) {
+ *error = "Heap object tracking is not started.";
+ return;
+ }
+ requestHeapStatsUpdate();
+ takeHeapSnapshot(error, reportProgress);
+ stopTrackingHeapObjectsInternal();
+}
+
+void InspectorHeapProfilerAgent::stopTrackingHeapObjectsInternal()
{
if (!m_heapStatsUpdateTask)
return;
@@ -198,14 +209,15 @@ void InspectorHeapProfilerAgent::stopTrackingHeapObjects(ErrorString*)
m_heapStatsUpdateTask.clear();
}
-void InspectorHeapProfilerAgent::getProfileHeaders(ErrorString*, RefPtr<TypeBuilder::Array<TypeBuilder::HeapProfiler::ProfileHeader> >& headers)
+void InspectorHeapProfilerAgent::enable(ErrorString*)
{
- m_state->setBoolean(HeapProfilerAgentState::profileHeadersRequested, true);
- headers = TypeBuilder::Array<TypeBuilder::HeapProfiler::ProfileHeader>::create();
+ m_state->setBoolean(HeapProfilerAgentState::heapProfilerEnabled, true);
+}
- IdToHeapSnapshotMap::iterator snapshotsEnd = m_snapshots.end();
- for (IdToHeapSnapshotMap::iterator it = m_snapshots.begin(); it != snapshotsEnd; ++it)
- headers->addItem(createSnapshotHeader(*it->value));
+void InspectorHeapProfilerAgent::disable(ErrorString* error)
+{
+ stopTrackingHeapObjectsInternal();
+ m_state->setBoolean(HeapProfilerAgentState::heapProfilerEnabled, false);
}
void InspectorHeapProfilerAgent::getHeapSnapshot(ErrorString* errorString, int rawUid)
@@ -215,7 +227,7 @@ void InspectorHeapProfilerAgent::getHeapSnapshot(ErrorString* errorString, int r
OutputStream(InspectorFrontend::HeapProfiler* frontend, unsigned uid)
: m_frontend(frontend), m_uid(uid) { }
void Write(const String& chunk) { m_frontend->addHeapSnapshotChunk(m_uid, chunk); }
- void Close() { m_frontend->finishHeapSnapshot(m_uid); }
+ void Close() { }
private:
InspectorFrontend::HeapProfiler* m_frontend;
int m_uid;
@@ -263,9 +275,7 @@ void InspectorHeapProfilerAgent::takeHeapSnapshot(ErrorString*, const bool* repo
int m_totalWork;
};
- String title = String(userInitiatedProfileNameHeap) + "." + String::number(m_nextUserInitiatedHeapSnapshotNumber);
- ++m_nextUserInitiatedHeapSnapshotNumber;
-
+ String title = "Snapshot " + String::number(m_nextUserInitiatedHeapSnapshotNumber++);
HeapSnapshotProgress progress(reportProgress && *reportProgress ? m_frontend : 0);
RefPtr<ScriptHeapSnapshot> snapshot = ScriptProfiler::takeHeapSnapshot(title, &progress);
if (snapshot) {
@@ -306,6 +316,7 @@ void InspectorHeapProfilerAgent::getHeapObjectId(ErrorString* errorString, const
return;
}
ScriptValue value = injectedScript.findObjectById(objectId);
+ ScriptScope scope(injectedScript.scriptState());
if (value.hasNoValue() || value.isUndefined()) {
*errorString = "Object with given id not found";
return;
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InspectorHeapProfilerAgent.h b/chromium/third_party/WebKit/Source/core/inspector/InspectorHeapProfilerAgent.h
index f4c19ed279d..65ea5266587 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InspectorHeapProfilerAgent.h
+++ b/chromium/third_party/WebKit/Source/core/inspector/InspectorHeapProfilerAgent.h
@@ -57,11 +57,12 @@ public:
virtual void collectGarbage(ErrorString*);
virtual void clearProfiles(ErrorString*);
- virtual void getProfileHeaders(ErrorString*, RefPtr<TypeBuilder::Array<TypeBuilder::HeapProfiler::ProfileHeader> >&);
+ virtual void enable(ErrorString*);
+ virtual void disable(ErrorString*);
virtual void getHeapSnapshot(ErrorString*, int uid);
virtual void removeProfile(ErrorString*, int uid);
virtual void startTrackingHeapObjects(ErrorString*);
- virtual void stopTrackingHeapObjects(ErrorString*);
+ virtual void stopTrackingHeapObjects(ErrorString*, const bool* reportProgress);
virtual void setFrontend(InspectorFrontend*);
virtual void clearFrontend();
@@ -85,6 +86,7 @@ private:
void pushHeapStatsUpdate(const uint32_t* const data, const int size);
PassRefPtr<TypeBuilder::HeapProfiler::ProfileHeader> createSnapshotHeader(const ScriptHeapSnapshot&);
+ void stopTrackingHeapObjectsInternal();
InjectedScriptManager* m_injectedScriptManager;
InspectorFrontend::HeapProfiler* m_frontend;
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InspectorHistory.cpp b/chromium/third_party/WebKit/Source/core/inspector/InspectorHistory.cpp
index 9282e0f1b67..e882744b084 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InspectorHistory.cpp
+++ b/chromium/third_party/WebKit/Source/core/inspector/InspectorHistory.cpp
@@ -83,11 +83,9 @@ void InspectorHistory::Action::merge(PassOwnPtr<Action>)
InspectorHistory::InspectorHistory() : m_afterLastActionIndex(0) { }
-InspectorHistory::~InspectorHistory() { }
-
-bool InspectorHistory::perform(PassOwnPtr<Action> action, ExceptionState& es)
+bool InspectorHistory::perform(PassOwnPtr<Action> action, ExceptionState& exceptionState)
{
- if (!action->perform(es))
+ if (!action->perform(exceptionState))
return false;
if (!action->mergeId().isEmpty() && m_afterLastActionIndex > 0 && action->mergeId() == m_history[m_afterLastActionIndex - 1]->mergeId())
@@ -105,14 +103,14 @@ void InspectorHistory::markUndoableState()
perform(adoptPtr(new UndoableStateMark()), IGNORE_EXCEPTION);
}
-bool InspectorHistory::undo(ExceptionState& es)
+bool InspectorHistory::undo(ExceptionState& exceptionState)
{
while (m_afterLastActionIndex > 0 && m_history[m_afterLastActionIndex - 1]->isUndoableStateMark())
--m_afterLastActionIndex;
while (m_afterLastActionIndex > 0) {
Action* action = m_history[m_afterLastActionIndex - 1].get();
- if (!action->undo(es)) {
+ if (!action->undo(exceptionState)) {
reset();
return false;
}
@@ -124,14 +122,14 @@ bool InspectorHistory::undo(ExceptionState& es)
return true;
}
-bool InspectorHistory::redo(ExceptionState& es)
+bool InspectorHistory::redo(ExceptionState& exceptionState)
{
while (m_afterLastActionIndex < m_history.size() && m_history[m_afterLastActionIndex]->isUndoableStateMark())
++m_afterLastActionIndex;
while (m_afterLastActionIndex < m_history.size()) {
Action* action = m_history[m_afterLastActionIndex].get();
- if (!action->redo(es)) {
+ if (!action->redo(exceptionState)) {
reset();
return false;
}
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InspectorHistory.h b/chromium/third_party/WebKit/Source/core/inspector/InspectorHistory.h
index 8fb4a6df518..049684efcca 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InspectorHistory.h
+++ b/chromium/third_party/WebKit/Source/core/inspector/InspectorHistory.h
@@ -39,7 +39,7 @@ namespace WebCore {
class ExceptionState;
-class InspectorHistory {
+class InspectorHistory FINAL {
WTF_MAKE_NONCOPYABLE(InspectorHistory); WTF_MAKE_FAST_ALLOCATED;
public:
class Action {
@@ -63,7 +63,6 @@ public:
};
InspectorHistory();
- virtual ~InspectorHistory();
bool perform(PassOwnPtr<Action>, ExceptionState&);
void markUndoableState();
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InspectorIndexedDBAgent.cpp b/chromium/third_party/WebKit/Source/core/inspector/InspectorIndexedDBAgent.cpp
index b6c1bde3c16..9ef572c68c3 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InspectorIndexedDBAgent.cpp
+++ b/chromium/third_party/WebKit/Source/core/inspector/InspectorIndexedDBAgent.cpp
@@ -36,13 +36,12 @@
#include "bindings/v8/ScriptController.h"
#include "core/dom/DOMStringList.h"
#include "core/dom/Document.h"
-#include "core/dom/Event.h"
-#include "core/dom/EventListener.h"
+#include "core/events/Event.h"
+#include "core/events/EventListener.h"
#include "core/inspector/InjectedScript.h"
#include "core/inspector/InspectorPageAgent.h"
#include "core/inspector/InspectorState.h"
-#include "core/page/Frame.h"
-#include "core/platform/JSONValues.h"
+#include "core/frame/Frame.h"
#include "modules/indexeddb/DOMWindowIndexedDatabase.h"
#include "modules/indexeddb/IDBCursor.h"
#include "modules/indexeddb/IDBCursorWithValue.h"
@@ -58,7 +57,8 @@
#include "modules/indexeddb/IDBPendingTransactionMonitor.h"
#include "modules/indexeddb/IDBRequest.h"
#include "modules/indexeddb/IDBTransaction.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/JSONValues.h"
+#include "platform/weborigin/SecurityOrigin.h"
#include "wtf/Vector.h"
using WebCore::TypeBuilder::Array;
@@ -99,22 +99,17 @@ public:
return this == &other;
}
- virtual void handleEvent(ScriptExecutionContext*, Event* event) OVERRIDE
+ virtual void handleEvent(ExecutionContext*, Event* event) OVERRIDE
{
if (!m_requestCallback->isActive())
return;
- if (event->type() != eventNames().successEvent) {
+ if (event->type() != EventTypeNames::success) {
m_requestCallback->sendFailure("Unexpected event type.");
return;
}
IDBRequest* idbRequest = static_cast<IDBRequest*>(event->target());
- TrackExceptionState es;
- RefPtr<IDBAny> requestResult = idbRequest->result(es);
- if (es.hadException()) {
- m_requestCallback->sendFailure("Could not get result in callback.");
- return;
- }
+ RefPtr<IDBAny> requestResult = idbRequest->resultAsAny();
if (requestResult->type() != IDBAny::DOMStringListType) {
m_requestCallback->sendFailure("Unexpected result type.");
return;
@@ -138,15 +133,15 @@ private:
class ExecutableWithDatabase : public RefCounted<ExecutableWithDatabase> {
public:
- ExecutableWithDatabase(ScriptExecutionContext* context)
+ ExecutableWithDatabase(ExecutionContext* context)
: m_context(context) { }
virtual ~ExecutableWithDatabase() { };
void start(IDBFactory*, SecurityOrigin*, const String& databaseName);
virtual void execute(PassRefPtr<IDBDatabase>) = 0;
virtual RequestCallback* requestCallback() = 0;
- ScriptExecutionContext* context() { return m_context; };
+ ExecutionContext* context() { return m_context; };
private:
- ScriptExecutionContext* m_context;
+ ExecutionContext* m_context;
};
class OpenDatabaseCallback : public EventListener {
@@ -163,20 +158,15 @@ public:
return this == &other;
}
- virtual void handleEvent(ScriptExecutionContext*, Event* event) OVERRIDE
+ virtual void handleEvent(ExecutionContext*, Event* event) OVERRIDE
{
- if (event->type() != eventNames().successEvent) {
+ if (event->type() != EventTypeNames::success) {
m_executableWithDatabase->requestCallback()->sendFailure("Unexpected event type.");
return;
}
IDBOpenDBRequest* idbOpenDBRequest = static_cast<IDBOpenDBRequest*>(event->target());
- TrackExceptionState es;
- RefPtr<IDBAny> requestResult = idbOpenDBRequest->result(es);
- if (es.hadException()) {
- m_executableWithDatabase->requestCallback()->sendFailure("Could not get result in callback.");
- return;
- }
+ RefPtr<IDBAny> requestResult = idbOpenDBRequest->resultAsAny();
if (requestResult->type() != IDBAny::IDBDatabaseType) {
m_executableWithDatabase->requestCallback()->sendFailure("Unexpected result type.");
return;
@@ -198,38 +188,38 @@ private:
void ExecutableWithDatabase::start(IDBFactory* idbFactory, SecurityOrigin*, const String& databaseName)
{
RefPtr<OpenDatabaseCallback> callback = OpenDatabaseCallback::create(this);
- TrackExceptionState es;
- RefPtr<IDBOpenDBRequest> idbOpenDBRequest = idbFactory->open(context(), databaseName, es);
- if (es.hadException()) {
+ TrackExceptionState exceptionState;
+ RefPtr<IDBOpenDBRequest> idbOpenDBRequest = idbFactory->open(context(), databaseName, exceptionState);
+ if (exceptionState.hadException()) {
requestCallback()->sendFailure("Could not open database.");
return;
}
- idbOpenDBRequest->addEventListener(eventNames().successEvent, callback, false);
+ idbOpenDBRequest->addEventListener(EventTypeNames::success, callback, false);
}
-static PassRefPtr<IDBTransaction> transactionForDatabase(ScriptExecutionContext* scriptExecutionContext, IDBDatabase* idbDatabase, const String& objectStoreName, const String& mode = IDBTransaction::modeReadOnly())
+static PassRefPtr<IDBTransaction> transactionForDatabase(ExecutionContext* executionContext, IDBDatabase* idbDatabase, const String& objectStoreName, const String& mode = IDBTransaction::modeReadOnly())
{
- TrackExceptionState es;
- RefPtr<IDBTransaction> idbTransaction = idbDatabase->transaction(scriptExecutionContext, objectStoreName, mode, es);
- if (es.hadException())
+ TrackExceptionState exceptionState;
+ RefPtr<IDBTransaction> idbTransaction = idbDatabase->transaction(executionContext, objectStoreName, mode, exceptionState);
+ if (exceptionState.hadException())
return 0;
return idbTransaction;
}
static PassRefPtr<IDBObjectStore> objectStoreForTransaction(IDBTransaction* idbTransaction, const String& objectStoreName)
{
- TrackExceptionState es;
- RefPtr<IDBObjectStore> idbObjectStore = idbTransaction->objectStore(objectStoreName, es);
- if (es.hadException())
+ TrackExceptionState exceptionState;
+ RefPtr<IDBObjectStore> idbObjectStore = idbTransaction->objectStore(objectStoreName, exceptionState);
+ if (exceptionState.hadException())
return 0;
return idbObjectStore;
}
static PassRefPtr<IDBIndex> indexForObjectStore(IDBObjectStore* idbObjectStore, const String& indexName)
{
- TrackExceptionState es;
- RefPtr<IDBIndex> idbIndex = idbObjectStore->index(indexName, es);
- if (es.hadException())
+ TrackExceptionState exceptionState;
+ RefPtr<IDBIndex> idbIndex = idbObjectStore->index(indexName, exceptionState);
+ if (exceptionState.hadException())
return 0;
return idbIndex;
}
@@ -263,7 +253,7 @@ static PassRefPtr<KeyPath> keyPathFromIDBKeyPath(const IDBKeyPath& idbKeyPath)
class DatabaseLoader : public ExecutableWithDatabase {
public:
- static PassRefPtr<DatabaseLoader> create(ScriptExecutionContext* context, PassRefPtr<RequestDatabaseCallback> requestCallback)
+ static PassRefPtr<DatabaseLoader> create(ExecutionContext* context, PassRefPtr<RequestDatabaseCallback> requestCallback)
{
return adoptRef(new DatabaseLoader(context, requestCallback));
}
@@ -314,7 +304,7 @@ public:
virtual RequestCallback* requestCallback() { return m_requestCallback.get(); }
private:
- DatabaseLoader(ScriptExecutionContext* context, PassRefPtr<RequestDatabaseCallback> requestCallback)
+ DatabaseLoader(ExecutionContext* context, PassRefPtr<RequestDatabaseCallback> requestCallback)
: ExecutableWithDatabase(context)
, m_requestCallback(requestCallback) { }
RefPtr<RequestDatabaseCallback> m_requestCallback;
@@ -407,21 +397,16 @@ public:
return this == &other;
}
- virtual void handleEvent(ScriptExecutionContext* context, Event* event) OVERRIDE
+ virtual void handleEvent(ExecutionContext* context, Event* event) OVERRIDE
{
- if (event->type() != eventNames().successEvent) {
+ if (event->type() != EventTypeNames::success) {
m_requestCallback->sendFailure("Unexpected event type.");
return;
}
IDBRequest* idbRequest = static_cast<IDBRequest*>(event->target());
- TrackExceptionState es;
- RefPtr<IDBAny> requestResult = idbRequest->result(es);
- if (es.hadException()) {
- m_requestCallback->sendFailure("Could not get result in callback.");
- return;
- }
- if (requestResult->type() == IDBAny::ScriptValueType) {
+ RefPtr<IDBAny> requestResult = idbRequest->resultAsAny();
+ if (requestResult->type() == IDBAny::BufferType) {
end(false);
return;
}
@@ -433,9 +418,9 @@ public:
RefPtr<IDBCursorWithValue> idbCursor = requestResult->idbCursorWithValue();
if (m_skipCount) {
- TrackExceptionState es;
- idbCursor->advance(m_skipCount, es);
- if (es.hadException())
+ TrackExceptionState exceptionState;
+ idbCursor->advance(m_skipCount, exceptionState);
+ if (exceptionState.hadException())
m_requestCallback->sendFailure("Could not advance cursor.");
m_skipCount = 0;
return;
@@ -447,8 +432,9 @@ public:
}
// Continue cursor before making injected script calls, otherwise transaction might be finished.
- idbCursor->continueFunction(0, es);
- if (es.hadException()) {
+ TrackExceptionState exceptionState;
+ idbCursor->continueFunction(0, 0, exceptionState);
+ if (exceptionState.hadException()) {
m_requestCallback->sendFailure("Could not continue cursor.");
return;
}
@@ -487,7 +473,7 @@ private:
class DataLoader : public ExecutableWithDatabase {
public:
- static PassRefPtr<DataLoader> create(ScriptExecutionContext* context, PassRefPtr<RequestDataCallback> requestCallback, const InjectedScript& injectedScript, const String& objectStoreName, const String& indexName, PassRefPtr<IDBKeyRange> idbKeyRange, int skipCount, unsigned pageSize)
+ static PassRefPtr<DataLoader> create(ExecutionContext* context, PassRefPtr<RequestDataCallback> requestCallback, const InjectedScript& injectedScript, const String& objectStoreName, const String& indexName, PassRefPtr<IDBKeyRange> idbKeyRange, int skipCount, unsigned pageSize)
{
return adoptRef(new DataLoader(context, requestCallback, injectedScript, objectStoreName, indexName, idbKeyRange, skipCount, pageSize));
}
@@ -524,12 +510,12 @@ public:
} else {
idbRequest = idbObjectStore->openCursor(context(), PassRefPtr<IDBKeyRange>(m_idbKeyRange), IndexedDB::CursorNext);
}
- idbRequest->addEventListener(eventNames().successEvent, openCursorCallback, false);
+ idbRequest->addEventListener(EventTypeNames::success, openCursorCallback, false);
}
virtual RequestCallback* requestCallback() { return m_requestCallback.get(); }
- DataLoader(ScriptExecutionContext* scriptExecutionContext, PassRefPtr<RequestDataCallback> requestCallback, const InjectedScript& injectedScript, const String& objectStoreName, const String& indexName, PassRefPtr<IDBKeyRange> idbKeyRange, int skipCount, unsigned pageSize)
- : ExecutableWithDatabase(scriptExecutionContext)
+ DataLoader(ExecutionContext* executionContext, PassRefPtr<RequestDataCallback> requestCallback, const InjectedScript& injectedScript, const String& objectStoreName, const String& indexName, PassRefPtr<IDBKeyRange> idbKeyRange, int skipCount, unsigned pageSize)
+ : ExecutableWithDatabase(executionContext)
, m_requestCallback(requestCallback)
, m_injectedScript(injectedScript)
, m_objectStoreName(objectStoreName)
@@ -619,17 +605,17 @@ void InspectorIndexedDBAgent::requestDatabaseNames(ErrorString* errorString, con
// FIXME: This should probably use ScriptState/ScriptScope instead of V8 API
v8::HandleScope handleScope(toIsolate(frame));
- v8::Handle<v8::Context> context = document->frame()->script()->mainWorldContext();
+ v8::Handle<v8::Context> context = document->frame()->script().mainWorldContext();
ASSERT(!context.IsEmpty());
v8::Context::Scope contextScope(context);
- TrackExceptionState es;
- RefPtr<IDBRequest> idbRequest = idbFactory->getDatabaseNames(document, es);
- if (es.hadException()) {
+ TrackExceptionState exceptionState;
+ RefPtr<IDBRequest> idbRequest = idbFactory->getDatabaseNames(document, exceptionState);
+ if (exceptionState.hadException()) {
requestCallback->sendFailure("Could not obtain database names.");
return;
}
- idbRequest->addEventListener(eventNames().successEvent, GetDatabaseNamesCallback::create(requestCallback, document->securityOrigin()->toRawString()), false);
+ idbRequest->addEventListener(EventTypeNames::success, GetDatabaseNamesCallback::create(requestCallback, document->securityOrigin()->toRawString()), false);
}
void InspectorIndexedDBAgent::requestDatabase(ErrorString* errorString, const String& securityOrigin, const String& databaseName, PassRefPtr<RequestDatabaseCallback> requestCallback)
@@ -644,7 +630,7 @@ void InspectorIndexedDBAgent::requestDatabase(ErrorString* errorString, const St
// FIXME: This should probably use ScriptState/ScriptScope instead of V8 API
v8::HandleScope handleScope(toIsolate(frame));
- v8::Handle<v8::Context> context = document->frame()->script()->mainWorldContext();
+ v8::Handle<v8::Context> context = document->frame()->script().mainWorldContext();
ASSERT(!context.IsEmpty());
v8::Context::Scope contextScope(context);
@@ -672,7 +658,7 @@ void InspectorIndexedDBAgent::requestData(ErrorString* errorString, const String
// FIXME: This should probably use ScriptState/ScriptScope instead of V8 API
v8::HandleScope handleScope(toIsolate(frame));
- v8::Handle<v8::Context> context = document->frame()->script()->mainWorldContext();
+ v8::Handle<v8::Context> context = document->frame()->script().mainWorldContext();
ASSERT(!context.IsEmpty());
v8::Context::Scope contextScope(context);
@@ -695,11 +681,11 @@ public:
return this == &other;
}
- virtual void handleEvent(ScriptExecutionContext*, Event* event) OVERRIDE
+ virtual void handleEvent(ExecutionContext*, Event* event) OVERRIDE
{
if (!m_requestCallback->isActive())
return;
- if (event->type() != eventNames().completeEvent) {
+ if (event->type() != EventTypeNames::complete) {
m_requestCallback->sendFailure("Unexpected event type.");
return;
}
@@ -719,12 +705,12 @@ private:
class ClearObjectStore : public ExecutableWithDatabase {
public:
- static PassRefPtr<ClearObjectStore> create(ScriptExecutionContext* context, const String& objectStoreName, PassRefPtr<ClearObjectStoreCallback> requestCallback)
+ static PassRefPtr<ClearObjectStore> create(ExecutionContext* context, const String& objectStoreName, PassRefPtr<ClearObjectStoreCallback> requestCallback)
{
return adoptRef(new ClearObjectStore(context, objectStoreName, requestCallback));
}
- ClearObjectStore(ScriptExecutionContext* context, const String& objectStoreName, PassRefPtr<ClearObjectStoreCallback> requestCallback)
+ ClearObjectStore(ExecutionContext* context, const String& objectStoreName, PassRefPtr<ClearObjectStoreCallback> requestCallback)
: ExecutableWithDatabase(context)
, m_objectStoreName(objectStoreName)
, m_requestCallback(requestCallback)
@@ -747,15 +733,15 @@ public:
return;
}
- TrackExceptionState es;
- RefPtr<IDBRequest> idbRequest = idbObjectStore->clear(context(), es);
- ASSERT(!es.hadException());
- if (es.hadException()) {
- ExceptionCode ec = es.code();
+ TrackExceptionState exceptionState;
+ RefPtr<IDBRequest> idbRequest = idbObjectStore->clear(context(), exceptionState);
+ ASSERT(!exceptionState.hadException());
+ if (exceptionState.hadException()) {
+ ExceptionCode ec = exceptionState.code();
m_requestCallback->sendFailure(String::format("Could not clear object store '%s': %d", m_objectStoreName.utf8().data(), ec));
return;
}
- idbTransaction->addEventListener(eventNames().completeEvent, ClearObjectStoreListener::create(m_requestCallback), false);
+ idbTransaction->addEventListener(EventTypeNames::complete, ClearObjectStoreListener::create(m_requestCallback), false);
}
virtual RequestCallback* requestCallback() { return m_requestCallback.get(); }
@@ -776,7 +762,7 @@ void InspectorIndexedDBAgent::clearObjectStore(ErrorString* errorString, const S
// FIXME: This should probably use ScriptState/ScriptScope instead of V8 API
v8::HandleScope handleScope(toIsolate(frame));
- v8::Handle<v8::Context> context = document->frame()->script()->mainWorldContext();
+ v8::Handle<v8::Context> context = document->frame()->script().mainWorldContext();
ASSERT(!context.IsEmpty());
v8::Context::Scope contextScope(context);
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InspectorInputAgent.cpp b/chromium/third_party/WebKit/Source/core/inspector/InspectorInputAgent.cpp
index 4af918756dd..342f9adedb0 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InspectorInputAgent.cpp
+++ b/chromium/third_party/WebKit/Source/core/inspector/InspectorInputAgent.cpp
@@ -34,20 +34,18 @@
#include "core/inspector/InspectorClient.h"
#include "core/page/Chrome.h"
#include "core/page/EventHandler.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameView.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
#include "core/page/Page.h"
-#include "core/platform/JSONValues.h"
-#include "core/platform/PlatformEvent.h"
-#include "core/platform/PlatformKeyboardEvent.h"
-#include "core/platform/PlatformMouseEvent.h"
-#include "core/platform/PlatformTouchEvent.h"
-#include "core/platform/PlatformTouchPoint.h"
-#include "core/platform/graphics/IntPoint.h"
-#include "core/platform/graphics/IntRect.h"
-#include "core/platform/graphics/IntSize.h"
+#include "platform/JSONValues.h"
+#include "platform/PlatformKeyboardEvent.h"
+#include "platform/PlatformMouseEvent.h"
+#include "platform/PlatformTouchEvent.h"
+#include "platform/PlatformTouchPoint.h"
+#include "platform/geometry/IntPoint.h"
+#include "platform/geometry/IntRect.h"
+#include "platform/geometry/IntSize.h"
#include "wtf/CurrentTime.h"
-#include "wtf/text/WTFString.h"
namespace {
@@ -270,8 +268,7 @@ void InspectorInputAgent::dispatchTouchEvent(ErrorString* error, const String& t
event.append(point);
}
- EventHandler* handler = m_page->mainFrame()->eventHandler();
- handler->handleTouchEvent(event);
+ m_page->mainFrame()->eventHandler().handleTouchEvent(event);
}
void InspectorInputAgent::dispatchGestureEvent(ErrorString*, const String& type, int x, int y, const double* timestamp, const int* deltaX, const int* deltaY, const double* scale)
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InspectorInstrumentation.cpp b/chromium/third_party/WebKit/Source/core/inspector/InspectorInstrumentation.cpp
index 4788d699e96..bc982c73036 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InspectorInstrumentation.cpp
+++ b/chromium/third_party/WebKit/Source/core/inspector/InspectorInstrumentation.cpp
@@ -101,8 +101,7 @@ void continueAfterPingLoaderImpl(InstrumentingAgents* instrumentingAgents, unsig
void didReceiveResourceResponseButCanceledImpl(Frame* frame, DocumentLoader* loader, unsigned long identifier, const ResourceResponse& r)
{
- InspectorInstrumentationCookie cookie = willReceiveResourceResponse(frame, identifier, r);
- didReceiveResourceResponse(cookie, identifier, loader, r, 0);
+ didReceiveResourceResponse(frame, identifier, loader, r, 0);
}
void continueAfterXFrameOptionsDeniedImpl(Frame* frame, DocumentLoader* loader, unsigned long identifier, const ResourceResponse& r)
@@ -132,13 +131,6 @@ void willDestroyResourceImpl(Resource* cachedResource)
}
}
-bool profilerEnabledImpl(InstrumentingAgents* instrumentingAgents)
-{
- if (InspectorProfilerAgent* profilerAgent = instrumentingAgents->inspectorProfilerAgent())
- return profilerAgent->enabled();
- return false;
-}
-
bool collectingHTMLParseErrorsImpl(InstrumentingAgents* instrumentingAgents)
{
if (InspectorAgent* inspectorAgent = instrumentingAgents->inspectorAgent())
@@ -160,22 +152,22 @@ String preprocessEventListenerImpl(InstrumentingAgents* instrumentingAgents, Fra
return source;
}
-bool canvasAgentEnabled(ScriptExecutionContext* scriptExecutionContext)
+bool canvasAgentEnabled(ExecutionContext* executionContext)
{
- InstrumentingAgents* instrumentingAgents = instrumentingAgentsFor(scriptExecutionContext);
+ InstrumentingAgents* instrumentingAgents = instrumentingAgentsFor(executionContext);
return instrumentingAgents && instrumentingAgents->inspectorCanvasAgent();
}
-bool consoleAgentEnabled(ScriptExecutionContext* scriptExecutionContext)
+bool consoleAgentEnabled(ExecutionContext* executionContext)
{
- InstrumentingAgents* instrumentingAgents = instrumentingAgentsFor(scriptExecutionContext);
+ InstrumentingAgents* instrumentingAgents = instrumentingAgentsFor(executionContext);
InspectorConsoleAgent* consoleAgent = instrumentingAgents ? instrumentingAgents->inspectorConsoleAgent() : 0;
return consoleAgent && consoleAgent->enabled();
}
-bool timelineAgentEnabled(ScriptExecutionContext* scriptExecutionContext)
+bool timelineAgentEnabled(ExecutionContext* executionContext)
{
- InstrumentingAgents* instrumentingAgents = instrumentingAgentsFor(scriptExecutionContext);
+ InstrumentingAgents* instrumentingAgents = instrumentingAgentsFor(executionContext);
return instrumentingAgents && instrumentingAgents->inspectorTimelineAgent();
}
@@ -226,35 +218,28 @@ InstrumentingAgents* instrumentingAgentsFor(WorkerGlobalScope* workerGlobalScope
return instrumentationForWorkerGlobalScope(workerGlobalScope);
}
-InstrumentingAgents* instrumentingAgentsForNonDocumentContext(ScriptExecutionContext* context)
+InstrumentingAgents* instrumentingAgentsForNonDocumentContext(ExecutionContext* context)
{
if (context->isWorkerGlobalScope())
return instrumentationForWorkerGlobalScope(toWorkerGlobalScope(context));
return 0;
}
-bool cssErrorFilter(const CSSParserString& content, int propertyId, int errorType)
-{
- return InspectorCSSAgent::cssErrorFilter(content, propertyId, errorType);
-}
-
} // namespace InspectorInstrumentation
namespace InstrumentationEvents {
const char PaintSetup[] = "PaintSetup";
-const char PaintLayer[] = "PaintLayer";
const char RasterTask[] = "RasterTask";
-const char ImageDecodeTask[] = "ImageDecodeTask";
const char Paint[] = "Paint";
const char Layer[] = "Layer";
const char BeginFrame[] = "BeginFrame";
-const char UpdateLayer[] = "UpdateLayer";
+const char ActivateLayerTree[] = "ActivateLayerTree";
};
namespace InstrumentationEventArguments {
+const char FrameId[] = "frameId";
const char LayerId[] = "layerId";
const char LayerTreeId[] = "layerTreeId";
-const char NodeId[] = "nodeId";
const char PageId[] = "pageId";
};
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InspectorInstrumentation.h b/chromium/third_party/WebKit/Source/core/inspector/InspectorInstrumentation.h
index 3e4f9e258b7..53fb8064411 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InspectorInstrumentation.h
+++ b/chromium/third_party/WebKit/Source/core/inspector/InspectorInstrumentation.h
@@ -33,20 +33,22 @@
#include "bindings/v8/ScriptString.h"
#include "core/css/CSSSelector.h"
+#include "core/css/CSSStyleDeclaration.h"
#include "core/css/CSSStyleSheet.h"
+#include "core/dom/CharacterData.h"
#include "core/dom/Element.h"
-#include "core/dom/EventContext.h"
-#include "core/dom/ScriptExecutionContext.h"
+#include "core/dom/ExecutionContext.h"
+#include "core/events/EventContext.h"
+#include "core/frame/Frame.h"
#include "core/inspector/ConsoleAPITypes.h"
-#include "core/page/Frame.h"
#include "core/page/Page.h"
-#include "core/platform/network/FormData.h"
#include "core/rendering/HitTestResult.h"
#include "core/rendering/RenderImage.h"
#include "core/storage/StorageArea.h"
#include "modules/websockets/WebSocketFrame.h"
-#include "modules/websockets/WebSocketHandshakeRequest.h"
-#include "modules/websockets/WebSocketHandshakeResponse.h"
+#include "platform/network/FormData.h"
+#include "platform/network/WebSocketHandshakeRequest.h"
+#include "platform/network/WebSocketHandshakeResponse.h"
#include "wtf/RefPtr.h"
namespace WebCore {
@@ -57,10 +59,11 @@ class Element;
class DeviceOrientationData;
class GeolocationPosition;
class GraphicsContext;
+class GraphicsLayer;
class InspectorTimelineAgent;
class InstrumentingAgents;
class RenderLayer;
-class ScriptExecutionContext;
+class ExecutionContext;
class ThreadableLoaderClient;
class WorkerGlobalScope;
class WorkerGlobalScopeProxy;
@@ -106,42 +109,41 @@ InspectorTimelineAgent* retrieveTimelineAgent(const InspectorInstrumentationCook
// Called from generated instrumentation code.
InstrumentingAgents* instrumentingAgentsFor(Page*);
InstrumentingAgents* instrumentingAgentsFor(Frame*);
-InstrumentingAgents* instrumentingAgentsFor(ScriptExecutionContext*);
+InstrumentingAgents* instrumentingAgentsFor(ExecutionContext*);
+InstrumentingAgents* instrumentingAgentsFor(Document&);
InstrumentingAgents* instrumentingAgentsFor(Document*);
InstrumentingAgents* instrumentingAgentsFor(RenderObject*);
-InstrumentingAgents* instrumentingAgentsFor(Element*);
+InstrumentingAgents* instrumentingAgentsFor(Node*);
InstrumentingAgents* instrumentingAgentsFor(WorkerGlobalScope*);
// Helper for the one above.
-InstrumentingAgents* instrumentingAgentsForNonDocumentContext(ScriptExecutionContext*);
+InstrumentingAgents* instrumentingAgentsForNonDocumentContext(ExecutionContext*);
} // namespace InspectorInstrumentation
namespace InstrumentationEvents {
extern const char PaintSetup[];
-extern const char PaintLayer[];
extern const char RasterTask[];
-extern const char ImageDecodeTask[];
extern const char Paint[];
extern const char Layer[];
extern const char BeginFrame[];
-extern const char UpdateLayer[];
+extern const char ActivateLayerTree[];
};
namespace InstrumentationEventArguments {
+extern const char FrameId[];
extern const char LayerId[];
extern const char LayerTreeId[];
-extern const char NodeId[];
extern const char PageId[];
};
namespace InspectorInstrumentation {
-inline InstrumentingAgents* instrumentingAgentsFor(ScriptExecutionContext* context)
+inline InstrumentingAgents* instrumentingAgentsFor(ExecutionContext* context)
{
if (!context)
return 0;
- return context->isDocument() ? instrumentingAgentsFor(toDocument(context)) : instrumentingAgentsForNonDocumentContext(context);
+ return context->isDocument() ? instrumentingAgentsFor(*toDocument(context)) : instrumentingAgentsForNonDocumentContext(context);
}
inline InstrumentingAgents* instrumentingAgentsFor(Frame* frame)
@@ -149,23 +151,33 @@ inline InstrumentingAgents* instrumentingAgentsFor(Frame* frame)
return frame ? instrumentingAgentsFor(frame->page()) : 0;
}
+inline InstrumentingAgents* instrumentingAgentsFor(Document& document)
+{
+ Page* page = document.page();
+ if (!page && document.templateDocumentHost())
+ page = document.templateDocumentHost()->page();
+ return instrumentingAgentsFor(page);
+}
+
inline InstrumentingAgents* instrumentingAgentsFor(Document* document)
{
- if (document) {
- Page* page = document->page();
- if (!page && document->templateDocumentHost())
- page = document->templateDocumentHost()->page();
- return instrumentingAgentsFor(page);
- }
- return 0;
+ return document ? instrumentingAgentsFor(*document) : 0;
+}
+
+inline InstrumentingAgents* instrumentingAgentsFor(CSSStyleSheet* styleSheet)
+{
+ return styleSheet ? instrumentingAgentsFor(styleSheet->ownerDocument()) : 0;
}
-inline InstrumentingAgents* instrumentingAgentsFor(Element* element)
+inline InstrumentingAgents* instrumentingAgentsFor(Node* node)
{
- return element ? instrumentingAgentsFor(&element->document()) : 0;
+ return node ? instrumentingAgentsFor(node->document()) : 0;
}
-bool cssErrorFilter(const CSSParserString& content, int propertyId, int errorType);
+inline InstrumentingAgents* instrumentingAgentsFor(CSSStyleDeclaration* declaration)
+{
+ return declaration ? instrumentingAgentsFor(declaration->parentStyleSheet()) : 0;
+}
} // namespace InspectorInstrumentation
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InspectorInstrumentation.idl b/chromium/third_party/WebKit/Source/core/inspector/InspectorInstrumentation.idl
index 578c8572e0a..548af1f7977 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InspectorInstrumentation.idl
+++ b/chromium/third_party/WebKit/Source/core/inspector/InspectorInstrumentation.idl
@@ -68,28 +68,40 @@ interface InspectorInstrumentation {
void didClearWindowObjectInWorld([Keep] Frame*, DOMWrapperWorld*);
[DOMDebugger, Inline=FastReturn]
- void willInsertDOMNode(Document*, Node* parent);
+ void willInsertDOMNode([Keep] Node* parent);
[DOM, DOMDebugger, Inline=FastReturn]
- void didInsertDOMNode(Document*, Node*);
+ void didInsertDOMNode([Keep] Node*);
[DOMDebugger, DOM, Inline=FastReturn]
- void willRemoveDOMNode(Document* document, Node*);
+ void willRemoveDOMNode([Keep] Node*);
[DOMDebugger, DOM, Inline=FastReturn]
- void willModifyDOMAttr(Document*, Element*, const AtomicString& oldValue, const AtomicString& newValue);
+ void willModifyDOMAttr([Keep] Element*, const AtomicString& oldValue, const AtomicString& newValue);
[DOM, Inline=FastReturn]
- void didModifyDOMAttr(Document*, Element*, const AtomicString& name, const AtomicString& value);
+ void didModifyDOMAttr([Keep] Element*, const AtomicString& name, const AtomicString& value);
[DOM, Inline=FastReturn]
- void didRemoveDOMAttr(Document*, Element*, const AtomicString& name);
+ void didRemoveDOMAttr([Keep] Element*, const AtomicString& name);
[DOM, Inline=FastReturn]
- void characterDataModified(Document*, CharacterData*);
+ void characterDataModified([Keep] CharacterData*);
[DOM, DOMDebugger, Inline=FastReturn]
- void didInvalidateStyleAttr(Document*, Node*);
+ void didInvalidateStyleAttr([Keep] Node*);
+
+ [CSS, Inline=FastReturn]
+ void willMutateRules(CSSStyleSheet*);
+
+ [CSS, Inline=FastReturn]
+ void didMutateRules([Keep] CSSStyleSheet*);
+
+ [CSS, Inline=FastReturn]
+ void willMutateStyle(CSSStyleDeclaration*);
+
+ [CSS, Inline=FastReturn]
+ void didMutateStyle([Keep] CSSStyleDeclaration*, bool);
[CSS, Inline=FastReturn]
void activeStyleSheetsUpdated([Keep] Document*, const Vector<RefPtr<StyleSheet> >& newSheets);
@@ -119,7 +131,7 @@ interface InspectorInstrumentation {
void didChangeRegionOverset([Keep] Document*, NamedFlow*);
[DOMDebugger, Inline=FastReturn]
- void willSendXMLHttpRequest(ScriptExecutionContext*, const String& url);
+ void willSendXMLHttpRequest(ExecutionContext*, const String& url);
[DOMDebugger, Inline=FastReturn]
void didFireWebGLError(Element*, const String& errorName);
@@ -133,20 +145,20 @@ interface InspectorInstrumentation {
[Timeline, Inline=FastReturn]
void didScheduleResourceRequest([Keep] Document*, const String& url);
- [DOMDebugger, Timeline, Inline=FastReturn]
- void didInstallTimer([Keep] ScriptExecutionContext*, int timerId, int timeout, bool singleShot);
+ [DOMDebugger, Debugger, Timeline, Inline=FastReturn]
+ void didInstallTimer([Keep] ExecutionContext*, int timerId, int timeout, bool singleShot);
- [DOMDebugger, Timeline, Inline=FastReturn]
- void didRemoveTimer([Keep] ScriptExecutionContext*, int timerId);
+ [DOMDebugger, Debugger, Timeline, Inline=FastReturn]
+ void didRemoveTimer([Keep] ExecutionContext*, int timerId);
[Timeline, Inline=FastReturn]
- InspectorInstrumentationCookie willCallFunction([Keep] ScriptExecutionContext*, const String& scriptName, int scriptLine);
+ InspectorInstrumentationCookie willCallFunction([Keep] ExecutionContext*, const String& scriptName, int scriptLine);
[Timeline, Inline=FastReturn]
void didCallFunction(const InspectorInstrumentationCookie&);
[Timeline, Inline=FastReturn]
- InspectorInstrumentationCookie willDispatchXHRReadyStateChangeEvent([Keep] ScriptExecutionContext*, XMLHttpRequest*);
+ InspectorInstrumentationCookie willDispatchXHRReadyStateChangeEvent([Keep] ExecutionContext*, XMLHttpRequest*);
[Timeline, Inline=FastReturn]
void didDispatchXHRReadyStateChangeEvent(const InspectorInstrumentationCookie&);
@@ -158,7 +170,7 @@ interface InspectorInstrumentation {
void didDispatchEvent(const InspectorInstrumentationCookie&);
[DOMDebugger, Inline=FastReturn]
- InspectorInstrumentationCookie willHandleEvent(ScriptExecutionContext*, Event*);
+ InspectorInstrumentationCookie willHandleEvent(ExecutionContext*, Event*);
[Debugger, Inline=FastReturn]
void didHandleEvent(const InspectorInstrumentationCookie&);
@@ -181,8 +193,8 @@ interface InspectorInstrumentation {
[PageRuntime, Inline=FastReturn]
void didCreateIsolatedContext([Keep] Frame*, ScriptState*, SecurityOrigin*);
- [DOMDebugger, Timeline, Inline=FastReturn]
- InspectorInstrumentationCookie willFireTimer([Keep] ScriptExecutionContext*, int timerId);
+ [DOMDebugger, Debugger, Timeline, Inline=FastReturn]
+ InspectorInstrumentationCookie willFireTimer([Keep] ExecutionContext*, int timerId);
[Debugger, Timeline, Inline=FastReturn]
void didFireTimer(const InspectorInstrumentationCookie&);
@@ -196,6 +208,12 @@ interface InspectorInstrumentation {
[Timeline, Page, Inline=FastReturn]
void didLayout(const InspectorInstrumentationCookie&, RenderObject* root);
+ [Timeline, Inline=FastReturn]
+ void willAutosizeText([Keep] RenderObject* root);
+
+ [Timeline, Inline=FastReturn]
+ void didAutosizeText([Keep] RenderObject* root);
+
[Page, Inline=FastReturn]
void didScroll(Page*);
@@ -203,7 +221,7 @@ interface InspectorInstrumentation {
void didResizeMainFrame(Page*);
[Timeline, Inline=FastReturn]
- InspectorInstrumentationCookie willDispatchXHRLoadEvent([Keep] ScriptExecutionContext*, XMLHttpRequest*);
+ InspectorInstrumentationCookie willDispatchXHRLoadEvent([Keep] ExecutionContext*, XMLHttpRequest*);
[Timeline, Inline=FastReturn]
void didDispatchXHRLoadEvent(const InspectorInstrumentationCookie&);
@@ -215,10 +233,10 @@ interface InspectorInstrumentation {
void didScrollLayer(RenderObject*);
[Timeline, Inline=FastReturn]
- void willPaint([Keep] RenderObject*);
+ void willPaint([Keep] RenderObject*, const GraphicsLayer*);
- [Timeline, Page, Inline=FastReturn]
- void didPaint([Keep] RenderObject*, GraphicsContext*, const LayoutRect&);
+ [Timeline, Page, LayerTree, Inline=FastReturn]
+ void didPaint([Keep] RenderObject*, const GraphicsLayer*, GraphicsContext*, const LayoutRect&);
[Timeline, Inline=FastReturn]
void willPaintImage([Keep] RenderImage*);
@@ -242,10 +260,7 @@ interface InspectorInstrumentation {
void applyUserAgentOverride(Frame*, String* userAgent);
[Page, Inline=FastReturn]
- void applyScreenWidthOverride(Frame*, long* width);
-
- [Page, Inline=FastReturn]
- void applyScreenHeightOverride(Frame*, long* height);
+ bool applyViewportStyleOverride(Document*, StyleResolver*);
[Page, Inline=FastReturn]
void applyEmulatedMedia(Frame*, String* media);
@@ -264,11 +279,8 @@ interface InspectorInstrumentation {
[Timeline, Inline=FastReturn]
void didReceiveResourceData(const InspectorInstrumentationCookie&);
- [Timeline]
- InspectorInstrumentationCookie willReceiveResourceResponse([Keep] Frame*, unsigned long identifier, const ResourceResponse&);
-
[Timeline, Resource, Console] // Console should come AFTER Resource notification, front-end relies on this.
- void didReceiveResourceResponse(const InspectorInstrumentationCookie&, unsigned long identifier, DocumentLoader*, const ResourceResponse&, ResourceLoader*);
+ void didReceiveResourceResponse([Keep] Frame*, unsigned long identifier, DocumentLoader*, const ResourceResponse&, ResourceLoader*);
[Inline=Forward]
void continueAfterXFrameOptionsDenied(Frame* frame, DocumentLoader* loader, unsigned long identifier, const ResourceResponse& r);
@@ -286,39 +298,36 @@ interface InspectorInstrumentation {
void didFinishLoading(Frame* frame, unsigned long identifier, DocumentLoader*, double finishTime);
[Resource]
- void didReceiveCORSRedirectResponse(Frame*, unsigned long identifier, DocumentLoader*, const ResourceResponse&, ResourceLoader*);
+ void didReceiveCORSRedirectResponse([Keep] Frame*, unsigned long identifier, DocumentLoader*, const ResourceResponse&, ResourceLoader*);
[Timeline, Resource, Console] // Console should come AFTER Resource notification, front-end relies on this.
void didFailLoading(Frame* frame, unsigned long identifier, DocumentLoader*, const ResourceError&);
[Resource]
- void documentThreadableLoaderStartedLoadingForClient(ScriptExecutionContext*, unsigned long identifier, ThreadableLoaderClient* client);
+ void documentThreadableLoaderStartedLoadingForClient(ExecutionContext*, unsigned long identifier, ThreadableLoaderClient* client);
[Resource]
- void willLoadXHR(ScriptExecutionContext*, ThreadableLoaderClient* client, const String& method, const KURL& url, bool async, PassRefPtr<FormData>, const HTTPHeaderMap& headers, bool includeCredentials);
+ void willLoadXHR(ExecutionContext*, XMLHttpRequest* xhr, ThreadableLoaderClient* client, const AtomicString& method, const KURL& url, bool async, PassRefPtr<FormData>, const HTTPHeaderMap& headers, bool includeCredentials);
[Resource]
- void didFailXHRLoading(ScriptExecutionContext*, ThreadableLoaderClient* client);
+ void didFailXHRLoading(ExecutionContext*, XMLHttpRequest* xhr, ThreadableLoaderClient* client);
[Console, Resource]
- void didFinishXHRLoading(ScriptExecutionContext*, ThreadableLoaderClient* client, unsigned long identifier, ScriptString sourceString, const String& url, const String& sendURL, unsigned sendLineNumber);
-
- [Resource]
- void didReceiveXHRResponse(ScriptExecutionContext*, unsigned long identifier);
+ void didFinishXHRLoading(ExecutionContext*, XMLHttpRequest* xhr, ThreadableLoaderClient* client, unsigned long identifier, ScriptString sourceString, const String& url, const String& sendURL, unsigned sendLineNumber);
[Resource]
- void scriptImported(ScriptExecutionContext*, unsigned long identifier, const String& sourceString);
+ void scriptImported(ExecutionContext*, unsigned long identifier, const String& sourceString);
[Debugger]
- void scriptExecutionBlockedByCSP(ScriptExecutionContext*, const String& directiveText);
+ void scriptExecutionBlockedByCSP(ExecutionContext*, const String& directiveText);
[Resource]
- void didReceiveScriptResponse(ScriptExecutionContext*, unsigned long identifier);
+ void didReceiveScriptResponse(ExecutionContext*, unsigned long identifier);
[Timeline, Inspector, DOM, Page]
void domContentLoadedEventFired([Keep] Frame*);
- [DOM, Timeline, Page]
+ [Timeline, Page]
void loadEventFired([Keep] Frame*);
[Page]
@@ -327,9 +336,6 @@ interface InspectorInstrumentation {
[Canvas, Page, CSS]
void frameDetachedFromParent([Keep] Frame*);
- [Page, Inline=FastReturn]
- void childDocumentOpened([Keep] Document*);
-
[Console, Resource, CSS, Database, DOM, Inspector, Canvas, Page, PageDebugger]
void didCommitLoad([Keep] Frame*, DocumentLoader*);
@@ -366,29 +372,29 @@ interface InspectorInstrumentation {
[Timeline, Inline=FastReturn]
void didWriteHTML(const InspectorInstrumentationCookie&, unsigned endLine);
- [DOMDebugger, Timeline]
+ [DOMDebugger, Debugger, Timeline]
void didRequestAnimationFrame([Keep] Document*, int callbackId);
- [DOMDebugger, Timeline]
+ [DOMDebugger, Debugger, Timeline]
void didCancelAnimationFrame([Keep] Document*, int callbackId);
- [DOMDebugger, Timeline]
+ [DOMDebugger, Debugger, Timeline]
InspectorInstrumentationCookie willFireAnimationFrame([Keep] Document*, int callbackId);
- [Timeline, Inline=FastReturn]
+ [Timeline, Debugger, Inline=FastReturn]
void didFireAnimationFrame(const InspectorInstrumentationCookie&);
[DOMStorage, Inline=FastReturn]
void didDispatchDOMStorageEvent(Page* page, const String& key, const String& oldValue, const String& newValue, StorageType storageType, SecurityOrigin* securityOrigin);
[Worker]
- void didStartWorkerGlobalScope(ScriptExecutionContext*, WorkerGlobalScopeProxy* proxy, const KURL& url);
+ void didStartWorkerGlobalScope(ExecutionContext*, WorkerGlobalScopeProxy* proxy, const KURL& url);
[WorkerRuntime]
void willEvaluateWorkerScript([Keep] WorkerGlobalScope* context, int workerThreadStartMode);
[Worker]
- void workerGlobalScopeTerminated(ScriptExecutionContext*, WorkerGlobalScopeProxy* proxy);
+ void workerGlobalScopeTerminated(ExecutionContext*, WorkerGlobalScopeProxy* proxy);
[Profiler, Timeline]
void willProcessTask(WorkerGlobalScope* context);
@@ -424,7 +430,7 @@ interface InspectorInstrumentation {
void didReceiveWebSocketFrameError(Document*, unsigned long identifier, const String& errorMessage);
[ApplicationCache, Inline=FastReturn]
- void networkStateChanged(Page*);
+ void networkStateChanged(Page*, bool online);
[ApplicationCache, Inline=FastReturn]
void updateApplicationCacheStatus([Keep] Frame*);
@@ -443,40 +449,42 @@ interface InspectorConsoleInstrumentation {
#include "core/inspector/ScriptArguments.h"
#include "core/inspector/ScriptCallStack.h"
-#include "core/inspector/ScriptProfile.h"
// FIXME: Convert to ScriptArguments to match non-worker context.
// Use the same implementation as above as a similar method dispatched on Page.
[Console]
- void addMessageToConsole(ScriptExecutionContext* context, MessageSource source, MessageType type, MessageLevel level, const String& message, PassRefPtr<ScriptCallStack> callStack, unsigned long requestIdentifier = 0);
+ void addMessageToConsole(ExecutionContext* context, MessageSource source, MessageType type, MessageLevel level, const String& message, PassRefPtr<ScriptCallStack> callStack, unsigned long requestIdentifier = 0);
// Use the same implementation as above as a similar method dispatched on Page.
[Console]
- void addMessageToConsole(ScriptExecutionContext* context, MessageSource source, MessageType type, MessageLevel level, const String& message, const String& scriptId, unsigned lineNumber, unsigned columnNumber, ScriptState* state, unsigned long requestIdentifier = 0);
+ void addMessageToConsole(ExecutionContext* context, MessageSource source, MessageType type, MessageLevel level, const String& message, const String& scriptId, unsigned lineNumber, unsigned columnNumber, ScriptState* state, unsigned long requestIdentifier = 0);
[Console, Debugger]
- void addMessageToConsole(ScriptExecutionContext* context, MessageSource source, MessageType type, MessageLevel level, const String& message, ScriptState* state, PassRefPtr<ScriptArguments> arguments, unsigned long requestIdentifier = 0);
+ void addMessageToConsole(ExecutionContext* context, MessageSource source, MessageType type, MessageLevel level, const String& message, ScriptState* state, PassRefPtr<ScriptArguments> arguments, unsigned long requestIdentifier = 0);
[Console]
- void consoleCount(ScriptExecutionContext* context, ScriptState* state, PassRefPtr<ScriptArguments> arguments);
+ void consoleCount(ExecutionContext* context, ScriptState* state, PassRefPtr<ScriptArguments> arguments);
[Timeline, Console]
- void consoleTime([Keep] ScriptExecutionContext* context, const String& title);
+ void consoleTime([Keep] ExecutionContext* context, const String& title);
[Console, Timeline]
- void consoleTimeEnd([Keep] ScriptExecutionContext* context, const String& title, ScriptState* state);
+ void consoleTimeEnd([Keep] ExecutionContext* context, const String& title, ScriptState* state);
[Timeline, Inline=FastReturn]
- void consoleTimeStamp([Keep] ScriptExecutionContext* context, const String& title);
+ void consoleTimeStamp([Keep] ExecutionContext* context, const String& title);
[Console, Inline=FastReturn]
- void consoleTimeline([Keep] ScriptExecutionContext* context, const String& title, ScriptState* state);
+ void consoleTimeline([Keep] ExecutionContext* context, const String& title, ScriptState* state);
[Console, Inline=FastReturn]
- void consoleTimelineEnd([Keep] ScriptExecutionContext* context, const String& title, ScriptState* state);
+ void consoleTimelineEnd([Keep] ExecutionContext* context, const String& title, ScriptState* state);
- [Profiler]
- void addProfile(ScriptExecutionContext* context, PassRefPtr<ScriptProfile> profile, PassRefPtr<ScriptCallStack> callStack);
+ [Profiler, Inline=FastReturn]
+ void consoleProfile(ExecutionContext* context, const String& title, ScriptState* state);
+
+ [Profiler, Inline=FastReturn]
+ void consoleProfileEnd(ExecutionContext* context, const String& title);
}
interface InspectorDatabaseInstrumentation {
@@ -484,30 +492,24 @@ interface InspectorDatabaseInstrumentation {
#include "modules/webdatabase/Database.h"
[Database]
- void didOpenDatabase(ScriptExecutionContext* context, PassRefPtr<Database> database, const String& domain, const String& name, const String& version);
+ void didOpenDatabase(ExecutionContext* context, PassRefPtr<Database> database, const String& domain, const String& name, const String& version);
}
interface InspectorOverrides {
[CSS, Inline=FastReturn]
bool forcePseudoState([Keep] Element* element, CSSSelector::PseudoType pseudoState);
- [Page, Inline=FastReturn]
- bool shouldApplyScreenWidthOverride(Frame* frame);
-
- [Page, Inline=FastReturn]
- bool shouldApplyScreenHeightOverride(Frame* frame);
-
[Worker, Inline=FastReturn]
- bool shouldPauseDedicatedWorkerOnStart(ScriptExecutionContext* context);
+ bool shouldPauseDedicatedWorkerOnStart(ExecutionContext* context);
[Page, Inline=FastReturn]
GeolocationPosition* overrideGeolocationPosition(Page* page, [DefaultReturn] GeolocationPosition* position);
[Page, Inline=FastReturn]
- DeviceOrientationData* overrideDeviceOrientation(Page* page, [DefaultReturn] DeviceOrientationData* deviceOrientation);
+ float overrideFontScaleFactor(Page* page, [DefaultReturn] float fontScaleFactor);
- [Profiler]
- String getCurrentUserInitiatedProfileName(ScriptExecutionContext* context, bool incrementProfileNumber);
+ [Page, Inline=FastReturn]
+ bool overrideTextAutosizing(Page* page, [DefaultReturn] bool textAutosizing);
}
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InspectorInstrumentationCustomInl.h b/chromium/third_party/WebKit/Source/core/inspector/InspectorInstrumentationCustomInl.h
index 49dcdb70d06..2ff178d3d2a 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InspectorInstrumentationCustomInl.h
+++ b/chromium/third_party/WebKit/Source/core/inspector/InspectorInstrumentationCustomInl.h
@@ -35,29 +35,14 @@ namespace WebCore {
namespace InspectorInstrumentation {
-bool profilerEnabledImpl(InstrumentingAgents*);
bool isDebuggerPausedImpl(InstrumentingAgents*);
bool collectingHTMLParseErrorsImpl(InstrumentingAgents*);
PassOwnPtr<ScriptSourceCode> preprocessImpl(InstrumentingAgents*, Frame*, const ScriptSourceCode&);
String preprocessEventListenerImpl(InstrumentingAgents*, Frame*, const String& source, const String& url, const String& functionName);
-bool canvasAgentEnabled(ScriptExecutionContext*);
-bool consoleAgentEnabled(ScriptExecutionContext*);
-bool timelineAgentEnabled(ScriptExecutionContext*);
-
-inline bool profilerEnabled(WorkerGlobalScope* scope)
-{
- if (InstrumentingAgents* instrumentingAgents = instrumentingAgentsFor(scope))
- return profilerEnabledImpl(instrumentingAgents);
- return false;
-}
-
-inline bool profilerEnabled(Page* page)
-{
- if (InstrumentingAgents* instrumentingAgents = instrumentingAgentsFor(page))
- return profilerEnabledImpl(instrumentingAgents);
- return false;
-}
+bool canvasAgentEnabled(ExecutionContext*);
+bool consoleAgentEnabled(ExecutionContext*);
+bool timelineAgentEnabled(ExecutionContext*);
inline bool isDebuggerPaused(Frame* frame)
{
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InspectorLayerTreeAgent.cpp b/chromium/third_party/WebKit/Source/core/inspector/InspectorLayerTreeAgent.cpp
index 5f92bb00c0a..0c138c15774 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InspectorLayerTreeAgent.cpp
+++ b/chromium/third_party/WebKit/Source/core/inspector/InspectorLayerTreeAgent.cpp
@@ -33,33 +33,49 @@
#include "core/inspector/InspectorLayerTreeAgent.h"
-#include "InspectorFrontend.h"
#include "core/inspector/IdentifiersFactory.h"
#include "core/inspector/InspectorDOMAgent.h"
#include "core/inspector/InspectorState.h"
#include "core/inspector/InstrumentingAgents.h"
#include "core/loader/DocumentLoader.h"
-#include "core/page/Frame.h"
+#include "core/frame/Frame.h"
#include "core/page/Page.h"
-#include "core/platform/graphics/IntRect.h"
-#include "core/platform/graphics/transforms/TransformationMatrix.h"
-#include "core/rendering/RenderLayer.h"
-#include "core/rendering/RenderLayerBacking.h"
+#include "core/rendering/CompositedLayerMapping.h"
#include "core/rendering/RenderLayerCompositor.h"
#include "core/rendering/RenderView.h"
+#include "platform/geometry/IntRect.h"
+#include "platform/graphics/GraphicsContextRecorder.h"
+#include "platform/transforms/TransformationMatrix.h"
#include "public/platform/WebCompositingReasons.h"
#include "public/platform/WebLayer.h"
namespace WebCore {
-namespace LayerTreeAgentState {
-static const char layerTreeAgentEnabled[] = "layerTreeAgentEnabled";
+unsigned InspectorLayerTreeAgent::s_lastSnapshotId;
+
+struct LayerSnapshot {
+ LayerSnapshot()
+ : layerId(0)
+ {
+ }
+ LayerSnapshot(int layerId, PassRefPtr<GraphicsContextSnapshot> graphicsSnapshot)
+ : layerId(layerId)
+ , graphicsSnapshot(graphicsSnapshot)
+ {
+ }
+ int layerId;
+ RefPtr<GraphicsContextSnapshot> graphicsSnapshot;
};
+inline String idForLayer(const GraphicsLayer* graphicsLayer)
+{
+ return String::number(graphicsLayer->platformLayer()->id());
+}
+
static PassRefPtr<TypeBuilder::LayerTree::Layer> buildObjectForLayer(GraphicsLayer* graphicsLayer, int nodeId)
{
RefPtr<TypeBuilder::LayerTree::Layer> layerObject = TypeBuilder::LayerTree::Layer::create()
- .setLayerId(String::number(graphicsLayer->platformLayer()->id()))
+ .setLayerId(idForLayer(graphicsLayer))
.setOffsetX(graphicsLayer->position().x())
.setOffsetY(graphicsLayer->position().y())
.setWidth(graphicsLayer->size().width())
@@ -73,7 +89,7 @@ static PassRefPtr<TypeBuilder::LayerTree::Layer> buildObjectForLayer(GraphicsLay
if (!parent)
parent = graphicsLayer->replicatedLayer();
if (parent)
- layerObject->setParentLayerId(String::number(parent->platformLayer()->id()));
+ layerObject->setParentLayerId(idForLayer(parent));
if (!graphicsLayer->contentsAreVisible())
layerObject->setInvisible(true);
const TransformationMatrix& transform = graphicsLayer->transform();
@@ -127,87 +143,80 @@ void InspectorLayerTreeAgent::clearFrontend()
void InspectorLayerTreeAgent::restore()
{
- if (m_state->getBoolean(LayerTreeAgentState::layerTreeAgentEnabled))
- enable(0);
+ // We do not re-enable layer agent automatically after navigation. This is because
+ // it depends on DOMAgent and node ids in particular, so we let front-end request document
+ // and re-enable the agent manually after this.
}
void InspectorLayerTreeAgent::enable(ErrorString*)
{
- m_state->setBoolean(LayerTreeAgentState::layerTreeAgentEnabled, true);
m_instrumentingAgents->setInspectorLayerTreeAgent(this);
+ layerTreeDidChange();
}
void InspectorLayerTreeAgent::disable(ErrorString*)
{
- if (!m_state->getBoolean(LayerTreeAgentState::layerTreeAgentEnabled))
- return;
- m_state->setBoolean(LayerTreeAgentState::layerTreeAgentEnabled, false);
m_instrumentingAgents->setInspectorLayerTreeAgent(0);
+ m_snapshotById.clear();
}
void InspectorLayerTreeAgent::layerTreeDidChange()
{
- m_frontend->layerTreeDidChange();
+ m_frontend->layerTreeDidChange(buildLayerTree());
}
-void InspectorLayerTreeAgent::getLayers(ErrorString* errorString, const int* nodeId, RefPtr<TypeBuilder::Array<TypeBuilder::LayerTree::Layer> >& layers)
+void InspectorLayerTreeAgent::didPaint(RenderObject*, const GraphicsLayer* graphicsLayer, GraphicsContext*, const LayoutRect& rect)
{
- LayerIdToNodeIdMap layerIdToNodeIdMap;
- layers = TypeBuilder::Array<TypeBuilder::LayerTree::Layer>::create();
+ // Should only happen for FrameView paints when compositing is off. Consider different instrumentation method for that.
+ if (!graphicsLayer)
+ return;
+ RefPtr<TypeBuilder::DOM::Rect> domRect = TypeBuilder::DOM::Rect::create()
+ .setX(rect.x())
+ .setY(rect.y())
+ .setWidth(rect.width())
+ .setHeight(rect.height());
+ m_frontend->layerPainted(idForLayer(graphicsLayer), domRect.release());
+}
+
+PassRefPtr<TypeBuilder::Array<TypeBuilder::LayerTree::Layer> > InspectorLayerTreeAgent::buildLayerTree()
+{
RenderLayerCompositor* compositor = renderLayerCompositor();
- if (!compositor || !compositor->inCompositingMode()) {
- *errorString = "Not in the compositing mode";
- return;
- }
- if (!nodeId) {
- buildLayerIdToNodeIdMap(errorString, compositor->rootRenderLayer(), layerIdToNodeIdMap);
- gatherGraphicsLayers(compositor->rootGraphicsLayer(), layerIdToNodeIdMap, layers);
- return;
- }
- Node* node = m_instrumentingAgents->inspectorDOMAgent()->nodeForId(*nodeId);
- if (!node) {
- *errorString = "Provided node id doesn't match any known node";
- return;
- }
- RenderObject* renderer = node->renderer();
- if (!renderer) {
- *errorString = "Node for provided node id doesn't have a renderer";
- return;
- }
- RenderLayer* enclosingLayer = renderer->enclosingLayer();
- GraphicsLayer* enclosingGraphicsLayer = enclosingLayer->enclosingCompositingLayer()->backing()->childForSuperlayers();
- buildLayerIdToNodeIdMap(errorString, enclosingLayer, layerIdToNodeIdMap);
- gatherGraphicsLayers(enclosingGraphicsLayer, layerIdToNodeIdMap, layers);
+ if (!compositor || !compositor->inCompositingMode())
+ return 0;
+ LayerIdToNodeIdMap layerIdToNodeIdMap;
+ RefPtr<TypeBuilder::Array<TypeBuilder::LayerTree::Layer> > layers = TypeBuilder::Array<TypeBuilder::LayerTree::Layer>::create();
+ buildLayerIdToNodeIdMap(compositor->rootRenderLayer(), layerIdToNodeIdMap);
+ gatherGraphicsLayers(compositor->rootGraphicsLayer(), layerIdToNodeIdMap, layers);
+ return layers.release();
}
-void InspectorLayerTreeAgent::buildLayerIdToNodeIdMap(ErrorString* errorString, RenderLayer* root, LayerIdToNodeIdMap& layerIdToNodeIdMap)
+void InspectorLayerTreeAgent::buildLayerIdToNodeIdMap(RenderLayer* root, LayerIdToNodeIdMap& layerIdToNodeIdMap)
{
- if (root->isComposited()) {
+ if (root->hasCompositedLayerMapping()) {
if (Node* node = root->renderer()->generatingNode()) {
- GraphicsLayer* graphicsLayer = root->backing()->childForSuperlayers();
- layerIdToNodeIdMap.set(graphicsLayer->platformLayer()->id(), idForNode(errorString, node));
+ GraphicsLayer* graphicsLayer = root->compositedLayerMapping()->childForSuperlayers();
+ layerIdToNodeIdMap.set(graphicsLayer->platformLayer()->id(), idForNode(node));
}
}
for (RenderLayer* child = root->firstChild(); child; child = child->nextSibling())
- buildLayerIdToNodeIdMap(errorString, child, layerIdToNodeIdMap);
+ buildLayerIdToNodeIdMap(child, layerIdToNodeIdMap);
if (!root->renderer()->isRenderIFrame())
return;
FrameView* childFrameView = toFrameView(toRenderWidget(root->renderer())->widget());
if (RenderView* childRenderView = childFrameView->renderView()) {
if (RenderLayerCompositor* childCompositor = childRenderView->compositor())
- buildLayerIdToNodeIdMap(errorString, childCompositor->rootRenderLayer(), layerIdToNodeIdMap);
+ buildLayerIdToNodeIdMap(childCompositor->rootRenderLayer(), layerIdToNodeIdMap);
}
}
-int InspectorLayerTreeAgent::idForNode(ErrorString* errorString, Node* node)
+int InspectorLayerTreeAgent::idForNode(Node* node)
{
- InspectorDOMAgent* domAgent = m_instrumentingAgents->inspectorDOMAgent();
-
- int nodeId = domAgent->boundNodeId(node);
- if (!nodeId)
- nodeId = domAgent->pushNodeToFrontend(errorString, domAgent->boundNodeId(&node->document()), node);
-
+ int nodeId = m_domAgent->boundNodeId(node);
+ if (!nodeId) {
+ ErrorString ignoredError;
+ nodeId = m_domAgent->pushNodeToFrontend(&ignoredError, m_domAgent->boundNodeId(&node->document()), node);
+ }
return nodeId;
}
@@ -242,8 +251,10 @@ GraphicsLayer* InspectorLayerTreeAgent::layerById(ErrorString* errorString, cons
return 0;
}
RenderLayerCompositor* compositor = renderLayerCompositor();
- if (!compositor)
+ if (!compositor) {
+ *errorString = "Not in compositing mode";
return 0;
+ }
GraphicsLayer* result = findLayerById(compositor->rootGraphicsLayer(), id);
if (!result)
@@ -290,13 +301,14 @@ void InspectorLayerTreeAgent::compositingReasons(ErrorString* errorString, const
{ CompositingReasonLayerForForeground, "layerForForeground" },
{ CompositingReasonLayerForBackground, "layerForBackground" },
{ CompositingReasonLayerForMask, "layerForMask" },
- { CompositingReasonLayerForVideoOverlay, "layerForVideoOverlay" }
+ { CompositingReasonLayerForVideoOverlay, "layerForVideoOverlay" },
+ { CompositingReasonIsolateCompositedDescendants, "isolateCompositedDescendants" }
};
const GraphicsLayer* graphicsLayer = layerById(errorString, layerId);
if (!graphicsLayer)
return;
- WebKit::WebCompositingReasons reasonsBitmask = graphicsLayer->compositingReasons();
+ blink::WebCompositingReasons reasonsBitmask = graphicsLayer->compositingReasons();
reasonStrings = TypeBuilder::Array<String>::create();
for (size_t i = 0; i < WTF_ARRAY_LENGTH(compositingReasonNames); ++i) {
if (!(reasonsBitmask & compositingReasonNames[i].mask))
@@ -309,4 +321,65 @@ void InspectorLayerTreeAgent::compositingReasons(ErrorString* errorString, const
ASSERT(!reasonsBitmask);
}
+void InspectorLayerTreeAgent::makeSnapshot(ErrorString* errorString, const String& layerId, String* snapshotId)
+{
+ GraphicsLayer* layer = layerById(errorString, layerId);
+ if (!layer)
+ return;
+
+ GraphicsContextRecorder recorder;
+ IntSize size = expandedIntSize(layer->size());
+ GraphicsContext* context = recorder.record(size, layer->contentsOpaque());
+ layer->paint(*context, IntRect(IntPoint(0, 0), size));
+ RefPtr<GraphicsContextSnapshot> snapshot = recorder.stop();
+ *snapshotId = String::number(++s_lastSnapshotId);
+ bool newEntry = m_snapshotById.add(*snapshotId, LayerSnapshot(layer->platformLayer()->id(), snapshot)).isNewEntry;
+ ASSERT_UNUSED(newEntry, newEntry);
+}
+
+void InspectorLayerTreeAgent::releaseSnapshot(ErrorString* errorString, const String& snapshotId)
+{
+ SnapshotById::iterator it = m_snapshotById.find(snapshotId);
+ if (it == m_snapshotById.end()) {
+ *errorString = "Snapshot not found";
+ return;
+ }
+ m_snapshotById.remove(it);
+}
+
+const LayerSnapshot* InspectorLayerTreeAgent::snapshotById(ErrorString* errorString, const String& snapshotId)
+{
+ SnapshotById::iterator it = m_snapshotById.find(snapshotId);
+ if (it == m_snapshotById.end()) {
+ *errorString = "Snapshot not found";
+ return 0;
+ }
+ return &it->value;
+}
+
+void InspectorLayerTreeAgent::replaySnapshot(ErrorString* errorString, const String& snapshotId, const int* fromStep, const int* toStep, String* dataURL)
+{
+ const LayerSnapshot* snapshot = snapshotById(errorString, snapshotId);
+ if (!snapshot)
+ return;
+ OwnPtr<ImageBuffer> imageBuffer = snapshot->graphicsSnapshot->replay(fromStep ? *fromStep : 0, toStep ? *toStep : 0);
+ *dataURL = imageBuffer->toDataURL("image/png");
+}
+
+void InspectorLayerTreeAgent::profileSnapshot(ErrorString* errorString, const String& snapshotId, const int* minRepeatCount, const double* minDuration, RefPtr<TypeBuilder::Array<TypeBuilder::Array<double> > >& outTimings)
+{
+ const LayerSnapshot* snapshot = snapshotById(errorString, snapshotId);
+ if (!snapshot)
+ return;
+ OwnPtr<GraphicsContextSnapshot::Timings> timings = snapshot->graphicsSnapshot->profile(minRepeatCount ? *minRepeatCount : 1, minDuration ? *minDuration : 0);
+ outTimings = TypeBuilder::Array<TypeBuilder::Array<double> >::create();
+ for (size_t i = 0; i < timings->size(); ++i) {
+ const Vector<double>& row = (*timings)[i];
+ RefPtr<TypeBuilder::Array<double> > outRow = TypeBuilder::Array<double>::create();
+ for (size_t j = 1; j < row.size(); ++j)
+ outRow->addItem(row[j] - row[j - 1]);
+ outTimings->addItem(outRow.release());
+ }
+}
+
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InspectorLayerTreeAgent.h b/chromium/third_party/WebKit/Source/core/inspector/InspectorLayerTreeAgent.h
index 9db42fd9539..ffaeb481a53 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InspectorLayerTreeAgent.h
+++ b/chromium/third_party/WebKit/Source/core/inspector/InspectorLayerTreeAgent.h
@@ -35,6 +35,7 @@
#include "InspectorTypeBuilder.h"
#include "core/inspector/InspectorBaseAgent.h"
#include "core/rendering/RenderLayer.h"
+#include "platform/Timer.h"
#include "wtf/PassOwnPtr.h"
#include "wtf/PassRefPtr.h"
#include "wtf/text/WTFString.h"
@@ -46,6 +47,8 @@ class InstrumentingAgents;
class Page;
class RenderLayerCompositor;
+struct LayerSnapshot;
+
typedef String ErrorString;
class InspectorLayerTreeAgent : public InspectorBaseAgent<InspectorLayerTreeAgent>, public InspectorBackendDispatcher::LayerTreeCommandHandler {
@@ -60,30 +63,39 @@ public:
virtual void clearFrontend();
virtual void restore();
+ // Called from InspectorInstrumentation
void layerTreeDidChange();
+ void didPaint(RenderObject*, const GraphicsLayer*, GraphicsContext*, const LayoutRect&);
// Called from the front-end.
virtual void enable(ErrorString*);
virtual void disable(ErrorString*);
- virtual void getLayers(ErrorString*, const int* nodeId, RefPtr<TypeBuilder::Array<TypeBuilder::LayerTree::Layer> >&);
virtual void compositingReasons(ErrorString*, const String& layerId, RefPtr<TypeBuilder::Array<String> >&);
+ virtual void makeSnapshot(ErrorString*, const String& layerId, String* snapshotId);
+ virtual void releaseSnapshot(ErrorString*, const String& snapshotId);
+ virtual void replaySnapshot(ErrorString*, const String& snapshotId, const int* fromStep, const int* toStep, String* dataURL);
+ virtual void profileSnapshot(ErrorString*, const String& snapshotId, const int* minRepeatCount, const double* minDuration, RefPtr<TypeBuilder::Array<TypeBuilder::Array<double> > >&);
private:
- typedef HashMap<int, int> LayerIdToNodeIdMap;
+ static unsigned s_lastSnapshotId;
InspectorLayerTreeAgent(InstrumentingAgents*, InspectorCompositeState*, InspectorDOMAgent*, Page*);
RenderLayerCompositor* renderLayerCompositor();
GraphicsLayer* layerById(ErrorString*, const String& layerId);
- int idForNode(ErrorString*, Node*);
+ const LayerSnapshot* snapshotById(ErrorString*, const String& snapshotId);
+ PassRefPtr<TypeBuilder::Array<TypeBuilder::LayerTree::Layer> > buildLayerTree();
- void buildLayerIdToNodeIdMap(ErrorString*, RenderLayer*, LayerIdToNodeIdMap&);
+ typedef HashMap<int, int> LayerIdToNodeIdMap;
+ void buildLayerIdToNodeIdMap(RenderLayer*, LayerIdToNodeIdMap&);
+ int idForNode(Node*);
InspectorFrontend::LayerTree* m_frontend;
Page* m_page;
InspectorDOMAgent* m_domAgent;
- HashMap<const RenderLayer*, String> m_documentLayerToIdMap;
+ typedef HashMap<String, LayerSnapshot> SnapshotById;
+ SnapshotById m_snapshotById;
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InspectorMemoryAgent.cpp b/chromium/third_party/WebKit/Source/core/inspector/InspectorMemoryAgent.cpp
index 33fc481243b..c754aa09195 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InspectorMemoryAgent.cpp
+++ b/chromium/third_party/WebKit/Source/core/inspector/InspectorMemoryAgent.cpp
@@ -31,10 +31,8 @@
#include "config.h"
#include "core/inspector/InspectorMemoryAgent.h"
-#include "InspectorFrontend.h"
#include "core/inspector/InspectorCounters.h"
#include "wtf/OwnPtr.h"
-#include "wtf/PassOwnPtr.h"
namespace WebCore {
@@ -46,7 +44,7 @@ void InspectorMemoryAgent::getDOMCounters(ErrorString*, int* documents, int* nod
{
*documents = InspectorCounters::counterValue(InspectorCounters::DocumentCounter);
*nodes = InspectorCounters::counterValue(InspectorCounters::NodeCounter);
- *jsEventListeners = ThreadLocalInspectorCounters::current().counterValue(ThreadLocalInspectorCounters::JSEventListenerCounter);
+ *jsEventListeners = InspectorCounters::counterValue(InspectorCounters::JSEventListenerCounter);
}
InspectorMemoryAgent::InspectorMemoryAgent(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* state)
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InspectorMemoryAgent.h b/chromium/third_party/WebKit/Source/core/inspector/InspectorMemoryAgent.h
index 1aa511f7fd5..6b202a86d24 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InspectorMemoryAgent.h
+++ b/chromium/third_party/WebKit/Source/core/inspector/InspectorMemoryAgent.h
@@ -44,8 +44,6 @@ typedef String ErrorString;
class InspectorMemoryAgent : public InspectorBaseAgent<InspectorMemoryAgent>, public InspectorBackendDispatcher::MemoryCommandHandler {
WTF_MAKE_NONCOPYABLE(InspectorMemoryAgent);
public:
- typedef Vector<OwnPtr<InspectorBaseAgentInterface> > InspectorAgents;
-
static PassOwnPtr<InspectorMemoryAgent> create(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* state)
{
return adoptPtr(new InspectorMemoryAgent(instrumentingAgents, state));
@@ -60,8 +58,6 @@ public:
private:
InspectorMemoryAgent(InstrumentingAgents*, InspectorCompositeState*);
- PassRefPtr<JSONObject> getProcessMemoryDistributionImpl(bool reportGraph, HashMap<String, size_t>* memoryInfo);
-
InspectorFrontend::Memory* m_frontend;
};
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InspectorOverlay.cpp b/chromium/third_party/WebKit/Source/core/inspector/InspectorOverlay.cpp
index 6811ffde724..c2b10d66da0 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InspectorOverlay.cpp
+++ b/chromium/third_party/WebKit/Source/core/inspector/InspectorOverlay.cpp
@@ -42,17 +42,17 @@
#include "core/loader/EmptyClients.h"
#include "core/page/Chrome.h"
#include "core/page/EventHandler.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameView.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
#include "core/page/Page.h"
-#include "core/page/Settings.h"
-#include "core/platform/JSONValues.h"
-#include "core/platform/PlatformMouseEvent.h"
-#include "core/platform/graphics/GraphicsContextStateSaver.h"
+#include "core/frame/Settings.h"
#include "core/rendering/RenderBoxModelObject.h"
#include "core/rendering/RenderInline.h"
#include "core/rendering/RenderObject.h"
#include "core/rendering/style/RenderStyleConstants.h"
+#include "platform/JSONValues.h"
+#include "platform/PlatformMouseEvent.h"
+#include "platform/graphics/GraphicsContextStateSaver.h"
#include "wtf/text/StringBuilder.h"
namespace WebCore {
@@ -248,12 +248,11 @@ InspectorOverlay::InspectorOverlay(Page* page, InspectorClient* client)
: m_page(page)
, m_client(client)
, m_inspectModeEnabled(false)
+ , m_overlayHost(InspectorOverlayHost::create())
, m_drawViewSize(false)
, m_drawViewSizeWithGrid(false)
, m_timer(this, &InspectorOverlay::onTimer)
- , m_overlayHost(InspectorOverlayHost::create())
- , m_overrides(0)
- , m_overridesTopOffset(0)
+ , m_activeProfilerCount(0)
{
}
@@ -281,7 +280,7 @@ bool InspectorOverlay::handleGestureEvent(const PlatformGestureEvent& event)
if (isEmpty())
return false;
- return overlayPage()->mainFrame()->eventHandler()->handleGestureEvent(event);
+ return overlayPage()->mainFrame()->eventHandler().handleGestureEvent(event);
}
bool InspectorOverlay::handleMouseEvent(const PlatformMouseEvent& event)
@@ -289,17 +288,17 @@ bool InspectorOverlay::handleMouseEvent(const PlatformMouseEvent& event)
if (isEmpty())
return false;
- EventHandler* eventHandler = overlayPage()->mainFrame()->eventHandler();
+ EventHandler& eventHandler = overlayPage()->mainFrame()->eventHandler();
bool result;
switch (event.type()) {
case PlatformEvent::MouseMoved:
- result = eventHandler->handleMouseMoveEvent(event);
+ result = eventHandler.handleMouseMoveEvent(event);
break;
case PlatformEvent::MousePressed:
- result = eventHandler->handleMousePressEvent(event);
+ result = eventHandler.handleMousePressEvent(event);
break;
case PlatformEvent::MouseReleased:
- result = eventHandler->handleMouseReleaseEvent(event);
+ result = eventHandler.handleMouseReleaseEvent(event);
break;
default:
return false;
@@ -314,7 +313,15 @@ bool InspectorOverlay::handleTouchEvent(const PlatformTouchEvent& event)
if (isEmpty())
return false;
- return overlayPage()->mainFrame()->eventHandler()->handleTouchEvent(event);
+ return overlayPage()->mainFrame()->eventHandler().handleTouchEvent(event);
+}
+
+bool InspectorOverlay::handleKeyboardEvent(const PlatformKeyboardEvent& event)
+{
+ if (isEmpty())
+ return false;
+
+ return overlayPage()->mainFrame()->eventHandler().keyEvent(event);
}
void InspectorOverlay::drawOutline(GraphicsContext* context, const LayoutRect& rect, const Color& color)
@@ -353,25 +360,6 @@ void InspectorOverlay::setInspectModeEnabled(bool enabled)
update();
}
-void InspectorOverlay::setOverride(OverrideType type, bool enabled)
-{
- bool currentEnabled = m_overrides & type;
- if (currentEnabled == enabled)
- return;
- if (enabled)
- m_overrides |= type;
- else
- m_overrides &= ~type;
- update();
-}
-
-void InspectorOverlay::setOverridesTopOffset(int offset)
-{
- m_overridesTopOffset = offset;
- if (m_overrides)
- update();
-}
-
void InspectorOverlay::hideHighlight()
{
m_highlightNode.clear();
@@ -410,7 +398,9 @@ Node* InspectorOverlay::highlightedNode() const
bool InspectorOverlay::isEmpty()
{
- bool hasAlwaysVisibleElements = m_highlightNode || m_eventTargetNode || m_highlightQuad || m_overrides || !m_size.isEmpty() || m_drawViewSize;
+ if (m_activeProfilerCount)
+ return true;
+ bool hasAlwaysVisibleElements = m_highlightNode || m_eventTargetNode || m_highlightQuad || !m_size.isEmpty() || m_drawViewSize;
bool hasInvisibleInInspectModeElements = !m_pausedInDebuggerMessage.isNull();
return !(hasAlwaysVisibleElements || (hasInvisibleInInspectModeElements && !m_inspectModeEnabled));
}
@@ -427,6 +417,8 @@ void InspectorOverlay::update()
return;
IntRect viewRect = view->visibleContentRect();
FrameView* overlayView = overlayPage()->mainFrame()->view();
+
+ // Include scrollbars to avoid masking them by the gutter.
IntSize frameViewFullSize = view->visibleContentRect(ScrollableArea::IncludeScrollbars).size();
IntSize size = m_size.isEmpty() ? frameViewFullSize : m_size;
size.scale(m_page->pageScaleFactor());
@@ -435,14 +427,11 @@ void InspectorOverlay::update()
// Clear canvas and paint things.
reset(size, m_size.isEmpty() ? IntSize() : frameViewFullSize, viewRect.x(), viewRect.y());
- // Include scrollbars to avoid masking them by the gutter.
- drawGutter();
drawNodeHighlight();
drawQuadHighlight();
if (!m_inspectModeEnabled)
drawPausedInDebuggerMessage();
drawViewSize();
- drawOverridesMessage();
// Position DOM elements.
overlayPage()->mainFrame()->document()->recalcStyle(Force);
@@ -463,8 +452,6 @@ void InspectorOverlay::hide()
m_size = IntSize();
m_drawViewSize = false;
m_drawViewSizeWithGrid = false;
- m_overrides = 0;
- m_overridesTopOffset = 0;
update();
}
@@ -511,11 +498,6 @@ static PassRefPtr<JSONObject> buildObjectForSize(const IntSize& size)
return result.release();
}
-void InspectorOverlay::drawGutter()
-{
- evaluateInOverlay("drawGutter", "");
-}
-
void InspectorOverlay::drawNodeHighlight()
{
if (!m_highlightNode)
@@ -558,9 +540,9 @@ void InspectorOverlay::drawNodeHighlight()
}
if (pseudoElement) {
if (pseudoElement->pseudoId() == BEFORE)
- classNames.append(":before");
+ classNames.append("::before");
else if (pseudoElement->pseudoId() == AFTER)
- classNames.append(":after");
+ classNames.append("::after");
}
if (!classNames.isEmpty())
elementInfo->setString("className", classNames.toString());
@@ -599,15 +581,6 @@ void InspectorOverlay::drawViewSize()
evaluateInOverlay("drawViewSize", m_drawViewSizeWithGrid ? "true" : "false");
}
-void InspectorOverlay::drawOverridesMessage()
-{
- RefPtr<JSONObject> data = JSONObject::create();
- if (!m_drawViewSize)
- data->setNumber("overrides", m_overrides);
- data->setNumber("topOffset", m_overridesTopOffset);
- evaluateInOverlay("drawOverridesMessage", data.release());
-}
-
Page* InspectorOverlay::overlayPage()
{
if (m_overlayPage)
@@ -620,17 +593,16 @@ Page* InspectorOverlay::overlayPage()
m_overlayChromeClient = adoptPtr(new InspectorOverlayChromeClient(m_page->chrome().client(), this));
pageClients.chromeClient = m_overlayChromeClient.get();
m_overlayPage = adoptPtr(new Page(pageClients));
- m_overlayPage->setGroupType(Page::InspectorPageGroup);
Settings& settings = m_page->settings();
Settings& overlaySettings = m_overlayPage->settings();
- overlaySettings.setStandardFontFamily(settings.standardFontFamily());
- overlaySettings.setSerifFontFamily(settings.serifFontFamily());
- overlaySettings.setSansSerifFontFamily(settings.sansSerifFontFamily());
- overlaySettings.setCursiveFontFamily(settings.cursiveFontFamily());
- overlaySettings.setFantasyFontFamily(settings.fantasyFontFamily());
- overlaySettings.setPictographFontFamily(settings.pictographFontFamily());
+ overlaySettings.genericFontFamilySettings().setStandard(settings.genericFontFamilySettings().standard());
+ overlaySettings.genericFontFamilySettings().setSerif(settings.genericFontFamilySettings().serif());
+ overlaySettings.genericFontFamilySettings().setSansSerif(settings.genericFontFamilySettings().sansSerif());
+ overlaySettings.genericFontFamilySettings().setCursive(settings.genericFontFamilySettings().cursive());
+ overlaySettings.genericFontFamilySettings().setFantasy(settings.genericFontFamilySettings().fantasy());
+ overlaySettings.genericFontFamilySettings().setPictograph(settings.genericFontFamilySettings().pictograph());
overlaySettings.setMinimumFontSize(settings.minimumFontSize());
overlaySettings.setMinimumLogicalFontSize(settings.minimumLogicalFontSize());
overlaySettings.setMediaEnabled(false);
@@ -638,23 +610,23 @@ Page* InspectorOverlay::overlayPage()
overlaySettings.setPluginsEnabled(false);
overlaySettings.setLoadsImagesAutomatically(true);
- RefPtr<Frame> frame = Frame::create(m_overlayPage.get(), 0, dummyFrameLoaderClient);
+ RefPtr<Frame> frame = Frame::create(FrameInit::create(0, m_overlayPage.get(), dummyFrameLoaderClient));
frame->setView(FrameView::create(frame.get()));
frame->init();
- FrameLoader* loader = frame->loader();
+ FrameLoader& loader = frame->loader();
frame->view()->setCanHaveScrollbars(false);
frame->view()->setTransparent(true);
- ASSERT(loader->activeDocumentLoader());
- DocumentWriter* writer = loader->activeDocumentLoader()->beginWriting("text/html", "UTF-8");
+ ASSERT(loader.activeDocumentLoader());
+ DocumentWriter* writer = loader.activeDocumentLoader()->beginWriting("text/html", "UTF-8");
writer->addData(reinterpret_cast<const char*>(InspectorOverlayPage_html), sizeof(InspectorOverlayPage_html));
- loader->activeDocumentLoader()->endWriting(writer);
+ loader.activeDocumentLoader()->endWriting(writer);
v8::Isolate* isolate = toIsolate(frame.get());
v8::HandleScope handleScope(isolate);
- v8::Handle<v8::Context> frameContext = frame->script()->currentWorldContext();
+ v8::Handle<v8::Context> frameContext = frame->script().currentWorldContext();
v8::Context::Scope contextScope(frameContext);
v8::Handle<v8::Value> overlayHostObj = toV8(m_overlayHost.get(), v8::Handle<v8::Object>(), isolate);
v8::Handle<v8::Object> global = frameContext->Global();
- global->Set(v8::String::New("InspectorOverlayHost"), overlayHostObj);
+ global->Set(v8::String::NewFromUtf8(isolate, "InspectorOverlayHost"), overlayHostObj);
#if OS(WIN)
evaluateInOverlay("setPlatform", "windows");
@@ -685,7 +657,7 @@ void InspectorOverlay::evaluateInOverlay(const String& method, const String& arg
RefPtr<JSONArray> command = JSONArray::create();
command->pushString(method);
command->pushString(argument);
- overlayPage()->mainFrame()->script()->executeScriptInMainWorld(ScriptSourceCode("dispatch(" + command->toJSONString() + ")"));
+ overlayPage()->mainFrame()->script().executeScriptInMainWorld("dispatch(" + command->toJSONString() + ")", ScriptController::ExecuteScriptWhenScriptsDisabled);
}
void InspectorOverlay::evaluateInOverlay(const String& method, PassRefPtr<JSONValue> argument)
@@ -693,7 +665,7 @@ void InspectorOverlay::evaluateInOverlay(const String& method, PassRefPtr<JSONVa
RefPtr<JSONArray> command = JSONArray::create();
command->pushString(method);
command->pushValue(argument);
- overlayPage()->mainFrame()->script()->executeScriptInMainWorld(ScriptSourceCode("dispatch(" + command->toJSONString() + ")"));
+ overlayPage()->mainFrame()->script().executeScriptInMainWorld("dispatch(" + command->toJSONString() + ")", ScriptController::ExecuteScriptWhenScriptsDisabled);
}
void InspectorOverlay::onTimer(Timer<InspectorOverlay>*)
@@ -714,4 +686,10 @@ void InspectorOverlay::freePage()
m_timer.stop();
}
+void InspectorOverlay::startedRecordingProfile()
+{
+ if (!m_activeProfilerCount++)
+ freePage();
+}
+
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InspectorOverlay.h b/chromium/third_party/WebKit/Source/core/inspector/InspectorOverlay.h
index 1517c450fb2..609cf52cf8c 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InspectorOverlay.h
+++ b/chromium/third_party/WebKit/Source/core/inspector/InspectorOverlay.h
@@ -29,10 +29,10 @@
#ifndef InspectorOverlay_h
#define InspectorOverlay_h
-#include "core/platform/graphics/Color.h"
-#include "core/platform/graphics/FloatQuad.h"
-#include "core/platform/graphics/LayoutRect.h"
-#include "core/platform/Timer.h"
+#include "platform/Timer.h"
+#include "platform/geometry/FloatQuad.h"
+#include "platform/geometry/LayoutRect.h"
+#include "platform/graphics/Color.h"
#include "wtf/OwnPtr.h"
#include "wtf/PassOwnPtr.h"
#include "wtf/RefPtr.h"
@@ -50,6 +50,7 @@ class JSONValue;
class Node;
class Page;
class PlatformGestureEvent;
+class PlatformKeyboardEvent;
class PlatformMouseEvent;
class PlatformTouchEvent;
@@ -106,15 +107,6 @@ struct Highlight {
class InspectorOverlay {
WTF_MAKE_FAST_ALLOCATED;
public:
- // This must be kept in sync with the overrideEntries array in InspectorOverlayPage.html.
- enum OverrideType {
- UserAgentOverride = 1,
- DeviceMetricsOverride = 1 << 1,
- GeolocationOverride = 1 << 2,
- DeviceOrientationOverride = 1 << 3,
- TouchOverride = 1 << 4,
- CSSMediaOverride = 1 << 5
- };
static PassOwnPtr<InspectorOverlay> create(Page* page, InspectorClient* client)
{
return adoptPtr(new InspectorOverlay(page, client));
@@ -131,11 +123,10 @@ public:
bool handleGestureEvent(const PlatformGestureEvent&);
bool handleMouseEvent(const PlatformMouseEvent&);
bool handleTouchEvent(const PlatformTouchEvent&);
+ bool handleKeyboardEvent(const PlatformKeyboardEvent&);
void setPausedInDebuggerMessage(const String*);
void setInspectModeEnabled(bool);
- void setOverride(OverrideType, bool);
- void setOverridesTopOffset(int);
void hideHighlight();
void highlightNode(Node*, Node* eventTarget, const HighlightConfig&);
@@ -149,6 +140,9 @@ public:
InspectorOverlayHost* overlayHost() const { return m_overlayHost.get(); }
+ void startedRecordingProfile();
+ void finishedRecordingProfile() { m_activeProfilerCount--; }
+
// Methods supporting underlying overlay page.
void invalidate();
private:
@@ -156,12 +150,10 @@ private:
bool isEmpty();
- void drawGutter();
void drawNodeHighlight();
void drawQuadHighlight();
void drawPausedInDebuggerMessage();
void drawViewSize();
- void drawOverridesMessage();
Page* overlayPage();
void reset(const IntSize& viewportSize, const IntSize& frameViewFullSize, int scrollX, int scrollY);
@@ -185,8 +177,7 @@ private:
bool m_drawViewSize;
bool m_drawViewSizeWithGrid;
Timer<InspectorOverlay> m_timer;
- unsigned m_overrides;
- int m_overridesTopOffset;
+ int m_activeProfilerCount;
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InspectorOverlayPage.html b/chromium/third_party/WebKit/Source/core/inspector/InspectorOverlayPage.html
index fc150af8731..c10cac7f9e5 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InspectorOverlayPage.html
+++ b/chromium/third_party/WebKit/Source/core/inspector/InspectorOverlayPage.html
@@ -149,48 +149,6 @@ body.platform-linux {
color: rgb(153, 69, 0);
}
-#right-gutter {
- display: none;
- right: 0;
- top: 0;
- bottom: 0;
- position: absolute;
- background-color: darkgray;
-}
-
-#bottom-gutter {
- display: none;
- left: 0;
- right: 0;
- bottom: 0;
- position: absolute;
- background-color: darkgray;
-}
-
-#overrides-container {
- display: inline-block;
- padding: 0 0 10px 10px;
- position: absolute;
- top: 0;
- right: 0;
-}
-
-#overrides-message > div:not(:first-child) {
- text-indent: 8px;
-}
-
-#overrides-message {
- display: inline-block;
- font-size: 14px;
- padding: 4px 6px;
- color: red;
- background-color: rgba(17, 17, 17, 0.843); /* Same as DebugColors::HUDBackgroundColor() */
-}
-
-#overrides-container:hover #overrides-message,
-#overrides-container.hidden #overrides-message {
- visibility: hidden;
-}
</style>
<script>
const lightGridColor = "rgba(0,0,0,0.2)";
@@ -198,15 +156,9 @@ const darkGridColor = "rgba(0,0,0,0.7)";
const transparentColor = "rgba(0, 0, 0, 0)";
const gridBackgroundColor = "rgba(255, 255, 255, 0.8)";
-// The order must correspond to that in InspectorOverlay::OverrideType.
-const overrideEntries = ["User-Agent", "Device Metrics", "Geolocation", "Device Orientation", "Touch", "Media"];
-const overrideTouchBit = 1 << 4;
-
-var overridesContainer;
-var overridesMessageElement;
-
function drawPausedInDebuggerMessage(message)
{
+ window._controlsVisible = true;
document.querySelector(".controls-line").style.visibility = "visible";
document.getElementById("paused-in-debugger").textContent = message;
document.body.classList.add("dimmed");
@@ -401,26 +353,6 @@ function quadEquals(quad1, quad2)
quad1[3].x === quad2[3].x && quad1[3].y === quad2[3].y;
}
-function drawGutter()
-{
- var frameWidth = frameViewFullSize.width;
- var frameHeight = frameViewFullSize.height;
-
- if (!frameWidth || document.body.offsetWidth <= frameWidth)
- rightGutter.style.removeProperty("display");
- else {
- rightGutter.style.display = "block";
- rightGutter.style.left = frameWidth + "px";
- }
-
- if (!frameHeight || document.body.offsetHeight <= frameHeight)
- bottomGutter.style.removeProperty("display");
- else {
- bottomGutter.style.display = "block";
- bottomGutter.style.top = frameHeight + "px";
- }
-}
-
function drawViewSize(drawViewSizeWithGrid)
{
var drawGridBoolean = drawViewSizeWithGrid === "true";
@@ -444,39 +376,6 @@ function drawViewSize(drawViewSizeWithGrid)
_drawGrid();
}
-function drawOverridesMessage(data)
-{
- overridesContainer.style.top = data.topOffset + "px";
- var overrides = data.overrides;
- overridesMessageElement.textContent = "";
- if (!overrides) {
- overridesContainer.classList.add("hidden");
- document.body.classList.remove("touch");
- return;
- }
-
- var header = document.createElement("div");
- header.id = "overrides-header";
- header.textContent = "Overrides:";
- overridesMessageElement.appendChild(header);
-
- var maskBit = 1;
- for (var i = 0; i < overrideEntries.length; ++i, maskBit <<= 1) {
- if (!(overrides & maskBit))
- continue;
- var item = document.createElement("div");
- item.textContent = overrideEntries[i];
- overridesMessageElement.appendChild(item);
- }
-
- overridesContainer.classList.remove("hidden");
- var hasTouch = overrides & overrideTouchBit;
- if (hasTouch)
- document.body.classList.add("touch");
- else
- document.body.classList.remove("touch");
-}
-
function reset(resetData)
{
window.viewportSize = resetData.viewportSize;
@@ -489,8 +388,6 @@ function reset(resetData)
window.canvas = document.getElementById("canvas");
window.context = canvas.getContext("2d");
- window.rightGutter = document.getElementById("right-gutter");
- window.bottomGutter = document.getElementById("bottom-gutter");
canvas.width = deviceScaleFactor * viewportSize.width;
canvas.height = deviceScaleFactor * viewportSize.height;
@@ -500,6 +397,7 @@ function reset(resetData)
window.canvasWidth = viewportSize.width;
window.canvasHeight = viewportSize.height;
+ window._controlsVisible = false;
document.querySelector(".controls-line").style.visibility = "hidden";
document.getElementById("element-title").style.visibility = "hidden";
document.body.classList.remove("dimmed");
@@ -756,42 +654,37 @@ function onStepOverClick()
InspectorOverlayHost.stepOver();
}
-function onMouseMotion(isOverElement)
+function onLoaded()
{
- if (!overridesMessageElement.textContent.length)
- return;
- if (isOverElement)
- overridesContainer.classList.add("hidden");
- else
- overridesContainer.classList.remove("hidden");
+ document.getElementById("resume-button").addEventListener("click", onResumeClick);
+ document.getElementById("step-over-button").addEventListener("click", onStepOverClick);
}
-function onFocus()
+function eventHasCtrlOrMeta(event)
{
- if (overridesMessageElement.textContent.length)
- overridesContainer.classList.remove("hidden");
+ return window.platform == "mac" ? (event.metaKey && !event.ctrlKey) : (event.ctrlKey && !event.metaKey);
}
-function onLoaded()
+function onDocumentKeyDown(event)
{
- overridesContainer = document.getElementById("overrides-container");
- overridesMessageElement = document.getElementById("overrides-message");
- document.getElementById("resume-button").addEventListener("click", onResumeClick);
- document.getElementById("step-over-button").addEventListener("click", onStepOverClick);
- overridesContainer.addEventListener("mousemove", onMouseMotion.bind(this, true));
- overridesContainer.addEventListener("mouseout", onMouseMotion.bind(this, false));
- window.addEventListener("focus", onFocus);
+ if (!window._controlsVisible)
+ return;
+ if (event.keyIdentifier == "F8" || eventHasCtrlOrMeta(event) && event.keyCode == 220 /* backslash */)
+ InspectorOverlayHost.resume();
+ else if (event.keyIdentifier == "F10" || eventHasCtrlOrMeta(event) && event.keyCode == 222 /* single quote */)
+ InspectorOverlayHost.stepOver();
}
window.addEventListener("DOMContentLoaded", onLoaded);
+document.addEventListener("keydown", onDocumentKeyDown);
</script>
</head>
<body class="fill">
<div class="controls-line">
<div class="message-box"><div id="paused-in-debugger"></div></div>
- <button id="resume-button" title="Resume script execution"><div class="glyph"></div></button>
- <button id="step-over-button" title="Step over next function call"><div class="glyph"></div></button>
+ <button id="resume-button" title="Resume script execution (F8)."><div class="glyph"></div></button>
+ <button id="step-over-button" title="Step over next function call (F10)."><div class="glyph"></div></button>
</div>
</body>
<canvas id="canvas" class="fill"></canvas>
@@ -799,10 +692,5 @@ window.addEventListener("DOMContentLoaded", onLoaded);
<span id="tag-name"></span><span id="node-id"></span><span id="class-name"></span>
<span id="node-width"></span><span class="px">px</span><span class="px"> &#xD7; </span><span id="node-height"></span><span class="px">px</span>
</div>
-<div id="right-gutter"></div>
-<div id="bottom-gutter"></div>
-<div id="overrides-container">
- <div id="overrides-message"></div>
-</div>
<div id="log"></div>
</html>
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InspectorPageAgent.cpp b/chromium/third_party/WebKit/Source/core/inspector/InspectorPageAgent.cpp
index 00bef931dd8..077d556cf77 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InspectorPageAgent.cpp
+++ b/chromium/third_party/WebKit/Source/core/inspector/InspectorPageAgent.cpp
@@ -32,13 +32,14 @@
#include "core/inspector/InspectorPageAgent.h"
#include "HTMLNames.h"
-#include "InspectorFrontend.h"
+#include "UserAgentStyleSheets.h"
#include "bindings/v8/DOMWrapperWorld.h"
#include "bindings/v8/ScriptController.h"
+#include "bindings/v8/ScriptRegexp.h"
+#include "core/css/StyleSheetContents.h"
+#include "core/css/resolver/ViewportStyleResolver.h"
#include "core/dom/DOMImplementation.h"
-#include "core/dom/DeviceOrientationController.h"
#include "core/dom/Document.h"
-#include "core/dom/UserGestureIndicator.h"
#include "core/fetch/CSSStyleSheetResource.h"
#include "core/fetch/FontResource.h"
#include "core/fetch/ImageResource.h"
@@ -61,16 +62,18 @@
#include "core/loader/DocumentLoader.h"
#include "core/loader/FrameLoadRequest.h"
#include "core/loader/FrameLoader.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameView.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
#include "core/page/Page.h"
#include "core/page/PageConsole.h"
-#include "core/page/Settings.h"
-#include "core/platform/Cookie.h"
-#include "core/platform/JSONValues.h"
-#include "core/platform/text/RegularExpression.h"
+#include "core/frame/Settings.h"
+#include "modules/device_orientation/DeviceOrientationController.h"
+#include "modules/device_orientation/DeviceOrientationData.h"
#include "modules/geolocation/GeolocationController.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/Cookie.h"
+#include "platform/JSONValues.h"
+#include "platform/UserGestureIndicator.h"
+#include "platform/weborigin/SecurityOrigin.h"
#include "wtf/CurrentTime.h"
#include "wtf/ListHashSet.h"
#include "wtf/Vector.h"
@@ -85,9 +88,12 @@ static const char pageAgentScriptExecutionDisabled[] = "pageAgentScriptExecution
static const char pageAgentScriptsToEvaluateOnLoad[] = "pageAgentScriptsToEvaluateOnLoad";
static const char pageAgentScreenWidthOverride[] = "pageAgentScreenWidthOverride";
static const char pageAgentScreenHeightOverride[] = "pageAgentScreenHeightOverride";
-static const char pageAgentFontScaleFactorOverride[] = "pageAgentFontScaleFactorOverride";
+static const char pageAgentDeviceScaleFactorOverride[] = "pageAgentDeviceScaleFactorOverride";
+static const char pageAgentEmulateViewport[] = "pageAgentEmulateViewport";
static const char pageAgentFitWindow[] = "pageAgentFitWindow";
+static const char fontScaleFactor[] = "fontScaleFactor";
static const char pageAgentShowFPSCounter[] = "pageAgentShowFPSCounter";
+static const char pageAgentTextAutosizingOverride[] = "pageAgentTextAutosizingOverride";
static const char pageAgentContinuousPaintingEnabled[] = "pageAgentContinuousPaintingEnabled";
static const char pageAgentShowPaintRects[] = "pageAgentShowPaintRects";
static const char pageAgentShowDebugBorders[] = "pageAgentShowDebugBorders";
@@ -96,7 +102,6 @@ static const char touchEventEmulationEnabled[] = "touchEventEmulationEnabled";
static const char pageAgentEmulatedMedia[] = "pageAgentEmulatedMedia";
static const char showSizeOnResize[] = "showSizeOnResize";
static const char showGridOnResize[] = "showGridOnResize";
-static const char forceCompositingMode[] = "forceCompositingMode";
}
namespace {
@@ -128,6 +133,9 @@ static bool prepareResourceBuffer(Resource* cachedResource, bool* hasZeroSize)
if (!cachedResource)
return false;
+ if (cachedResource->dataBufferingPolicy() == DoNotBufferData)
+ return false;
+
// Zero-sized resources don't have data at all -- so fake the empty buffer, instead of indicating error by returning 0.
if (!cachedResource->encodedSize()) {
*hasZeroSize = true;
@@ -154,14 +162,14 @@ static bool hasTextContent(Resource* cachedResource)
return type == InspectorPageAgent::DocumentResource || type == InspectorPageAgent::StylesheetResource || type == InspectorPageAgent::ScriptResource || type == InspectorPageAgent::XHRResource;
}
-static PassRefPtr<TextResourceDecoder> createXHRTextDecoder(const String& mimeType, const String& textEncodingName)
+static PassOwnPtr<TextResourceDecoder> createXHRTextDecoder(const String& mimeType, const String& textEncodingName)
{
if (!textEncodingName.isEmpty())
return TextResourceDecoder::create("text/plain", textEncodingName);
if (DOMImplementation::isXMLMIMEType(mimeType.lower())) {
- RefPtr<TextResourceDecoder> decoder = TextResourceDecoder::create("application/xml");
+ OwnPtr<TextResourceDecoder> decoder = TextResourceDecoder::create("application/xml");
decoder->useLenientXMLDecoding();
- return decoder;
+ return decoder.release();
}
if (equalIgnoringCase(mimeType, "text/html"))
return TextResourceDecoder::create("text/html", "UTF-8");
@@ -194,10 +202,10 @@ bool InspectorPageAgent::cachedResourceContent(Resource* cachedResource, String*
if (cachedResource) {
switch (cachedResource->type()) {
case Resource::CSSStyleSheet:
- *result = static_cast<CSSStyleSheetResource*>(cachedResource)->sheetText(false);
+ *result = toCSSStyleSheetResource(cachedResource)->sheetText(false);
return true;
case Resource::Script:
- *result = static_cast<WebCore::ScriptResource*>(cachedResource)->script();
+ *result = toScriptResource(cachedResource)->script();
return true;
case Resource::MainResource:
return false;
@@ -205,7 +213,7 @@ bool InspectorPageAgent::cachedResourceContent(Resource* cachedResource, String*
SharedBuffer* buffer = cachedResource->resourceBuffer();
if (!buffer)
return false;
- RefPtr<TextResourceDecoder> decoder = createXHRTextDecoder(cachedResource->response().mimeType(), cachedResource->response().textEncodingName());
+ OwnPtr<TextResourceDecoder> decoder = createXHRTextDecoder(cachedResource->response().mimeType(), cachedResource->response().textEncodingName());
String content = decoder->decode(buffer->data(), buffer->size());
*result = content + decoder->flush();
return true;
@@ -317,10 +325,10 @@ InspectorPageAgent::InspectorPageAgent(InstrumentingAgents* instrumentingAgents,
, m_overlay(overlay)
, m_lastScriptIdentifier(0)
, m_enabled(false)
- , m_isFirstLayoutAfterOnLoad(false)
, m_geolocationOverridden(false)
, m_ignoreScriptsEnabledNotification(false)
- , m_didForceCompositingMode(false)
+ , m_deviceMetricsOverridden(false)
+ , m_emulateViewportEnabled(false)
{
}
@@ -344,8 +352,6 @@ void InspectorPageAgent::restore()
enable(&error);
bool scriptExecutionDisabled = m_state->getBoolean(PageAgentState::pageAgentScriptExecutionDisabled);
setScriptExecutionDisabled(0, scriptExecutionDisabled);
- if (m_state->getBoolean(PageAgentState::forceCompositingMode))
- setForceCompositingMode(0, true);
bool showPaintRects = m_state->getBoolean(PageAgentState::pageAgentShowPaintRects);
setShowPaintRects(0, showPaintRects);
bool showDebugBorders = m_state->getBoolean(PageAgentState::pageAgentShowDebugBorders);
@@ -361,9 +367,10 @@ void InspectorPageAgent::restore()
int currentWidth = static_cast<int>(m_state->getLong(PageAgentState::pageAgentScreenWidthOverride));
int currentHeight = static_cast<int>(m_state->getLong(PageAgentState::pageAgentScreenHeightOverride));
- double currentFontScaleFactor = m_state->getDouble(PageAgentState::pageAgentFontScaleFactorOverride);
+ double currentDeviceScaleFactor = m_state->getDouble(PageAgentState::pageAgentDeviceScaleFactorOverride);
+ bool currentEmulateViewport = m_state->getBoolean(PageAgentState::pageAgentEmulateViewport);
bool currentFitWindow = m_state->getBoolean(PageAgentState::pageAgentFitWindow);
- updateViewMetrics(currentWidth, currentHeight, currentFontScaleFactor, currentFitWindow);
+ updateViewMetrics(currentWidth, currentHeight, currentDeviceScaleFactor, currentEmulateViewport, currentFitWindow);
updateTouchEventEmulationInPage(m_state->getBoolean(PageAgentState::touchEventEmulationEnabled));
}
}
@@ -388,6 +395,7 @@ void InspectorPageAgent::disable(ErrorString*)
m_state->remove(PageAgentState::pageAgentScriptsToEvaluateOnLoad);
m_overlay->hide();
m_instrumentingAgents->setInspectorPageAgent(0);
+ m_deviceMetricsOverridden = false;
setShowPaintRects(0, false);
setShowDebugBorders(0, false);
@@ -396,18 +404,19 @@ void InspectorPageAgent::disable(ErrorString*)
setContinuousPaintingEnabled(0, false);
setShowScrollBottleneckRects(0, false);
setShowViewportSizeOnResize(0, false, 0);
- if (m_didForceCompositingMode)
- setForceCompositingMode(0, false);
- if (!deviceMetricsChanged(0, 0, 1, false))
+ if (!deviceMetricsChanged(0, 0, 1, false, false, 1, false))
return;
// When disabling the agent, reset the override values if necessary.
- updateViewMetrics(0, 0, 1, false);
+ updateViewMetrics(0, 0, 1, false, false);
m_state->setLong(PageAgentState::pageAgentScreenWidthOverride, 0);
m_state->setLong(PageAgentState::pageAgentScreenHeightOverride, 0);
- m_state->setDouble(PageAgentState::pageAgentFontScaleFactorOverride, 1);
+ m_state->setDouble(PageAgentState::pageAgentDeviceScaleFactorOverride, 1);
+ m_state->setBoolean(PageAgentState::pageAgentEmulateViewport, false);
m_state->setBoolean(PageAgentState::pageAgentFitWindow, false);
+ m_state->setDouble(PageAgentState::fontScaleFactor, 1);
+ m_state->setBoolean(PageAgentState::pageAgentTextAutosizingOverride, false);
}
void InspectorPageAgent::addScriptToEvaluateOnLoad(ErrorString*, const String& source, String* identifier)
@@ -442,15 +451,15 @@ void InspectorPageAgent::reload(ErrorString*, const bool* const optionalIgnoreCa
{
m_pendingScriptToEvaluateOnLoadOnce = optionalScriptToEvaluateOnLoad ? *optionalScriptToEvaluateOnLoad : "";
m_pendingScriptPreprocessor = optionalScriptPreprocessor ? *optionalScriptPreprocessor : "";
- m_page->mainFrame()->loader()->reload(optionalIgnoreCache && *optionalIgnoreCache ? EndToEndReload : NormalReload);
+ m_page->mainFrame()->loader().reload(optionalIgnoreCache && *optionalIgnoreCache ? EndToEndReload : NormalReload);
}
void InspectorPageAgent::navigate(ErrorString*, const String& url)
{
UserGestureIndicator indicator(DefinitelyProcessingNewUserGesture);
Frame* frame = m_page->mainFrame();
- FrameLoadRequest request(frame->document()->securityOrigin(), ResourceRequest(frame->document()->completeURL(url)));
- frame->loader()->load(request);
+ FrameLoadRequest request(frame->document(), ResourceRequest(frame->document()->completeURL(url)));
+ frame->loader().load(request);
}
void InspectorPageAgent::getNavigationHistory(ErrorString*, int*, RefPtr<TypeBuilder::Array<TypeBuilder::Page::NavigationEntry> >&)
@@ -498,12 +507,12 @@ static Vector<Resource*> cachedResourcesForFrame(Frame* frame)
switch (cachedResource->type()) {
case Resource::Image:
// Skip images that were not auto loaded (images disabled in the user agent).
- if (static_cast<ImageResource*>(cachedResource)->stillNeedsLoad())
+ if (toImageResource(cachedResource)->stillNeedsLoad())
continue;
break;
case Resource::Font:
// Skip fonts that were referenced in CSS but never used/downloaded.
- if (static_cast<FontResource*>(cachedResource)->stillNeedsLoad())
+ if (toFontResource(cachedResource)->stillNeedsLoad())
continue;
break;
default:
@@ -521,7 +530,7 @@ static Vector<KURL> allResourcesURLsForFrame(Frame* frame)
{
Vector<KURL> result;
- result.append(urlWithoutFragment(frame->loader()->documentLoader()->url()));
+ result.append(urlWithoutFragment(frame->loader().documentLoader()->url()));
Vector<Resource*> allResources = cachedResourcesForFrame(frame);
for (Vector<Resource*>::const_iterator it = allResources.begin(); it != allResources.end(); ++it)
@@ -530,11 +539,11 @@ static Vector<KURL> allResourcesURLsForFrame(Frame* frame)
return result;
}
-void InspectorPageAgent::getCookies(ErrorString*, RefPtr<TypeBuilder::Array<TypeBuilder::Page::Cookie> >& cookies, WTF::String* cookiesString)
+void InspectorPageAgent::getCookies(ErrorString*, RefPtr<TypeBuilder::Array<TypeBuilder::Page::Cookie> >& cookies)
{
ListHashSet<Cookie> rawCookiesList;
- for (Frame* frame = mainFrame(); frame; frame = frame->tree()->traverseNext(mainFrame())) {
+ for (Frame* frame = mainFrame(); frame; frame = frame->tree().traverseNext(mainFrame())) {
Document* document = frame->document();
Vector<KURL> allURLs = allResourcesURLsForFrame(frame);
for (Vector<KURL>::const_iterator it = allURLs.begin(); it != allURLs.end(); ++it) {
@@ -548,15 +557,13 @@ void InspectorPageAgent::getCookies(ErrorString*, RefPtr<TypeBuilder::Array<Type
}
}
- // FIXME: Remove "cookiesString" output.
cookies = buildArrayForCookies(rawCookiesList);
- *cookiesString = "";
}
void InspectorPageAgent::deleteCookie(ErrorString*, const String& cookieName, const String& url)
{
KURL parsedURL(ParsedURLString, url);
- for (Frame* frame = m_page->mainFrame(); frame; frame = frame->tree()->traverseNext(m_page->mainFrame()))
+ for (Frame* frame = m_page->mainFrame(); frame; frame = frame->tree().traverseNext(m_page->mainFrame()))
WebCore::deleteCookie(frame->document(), parsedURL, cookieName);
}
@@ -596,7 +603,7 @@ void InspectorPageAgent::searchInResource(ErrorString*, const String& frameId, c
Frame* frame = frameForId(frameId);
KURL kurl(ParsedURLString, url);
- FrameLoader* frameLoader = frame ? frame->loader() : 0;
+ FrameLoader* frameLoader = frame ? &frame->loader() : 0;
DocumentLoader* loader = frameLoader ? frameLoader->documentLoader() : 0;
if (!loader)
return;
@@ -613,39 +620,6 @@ void InspectorPageAgent::searchInResource(ErrorString*, const String& frameId, c
results = ContentSearchUtils::searchInTextByLines(content, query, caseSensitive, isRegex);
}
-static PassRefPtr<TypeBuilder::Page::SearchResult> buildObjectForSearchResult(const String& frameId, const String& url, int matchesCount)
-{
- return TypeBuilder::Page::SearchResult::create()
- .setUrl(url)
- .setFrameId(frameId)
- .setMatchesCount(matchesCount)
- .release();
-}
-
-void InspectorPageAgent::searchInResources(ErrorString*, const String& text, const bool* const optionalCaseSensitive, const bool* const optionalIsRegex, RefPtr<TypeBuilder::Array<TypeBuilder::Page::SearchResult> >& results)
-{
- RefPtr<TypeBuilder::Array<TypeBuilder::Page::SearchResult> > searchResults = TypeBuilder::Array<TypeBuilder::Page::SearchResult>::create();
-
- bool isRegex = optionalIsRegex ? *optionalIsRegex : false;
- bool caseSensitive = optionalCaseSensitive ? *optionalCaseSensitive : false;
- OwnPtr<RegularExpression> regex = ContentSearchUtils::createSearchRegex(text, caseSensitive, isRegex);
-
- for (Frame* frame = m_page->mainFrame(); frame; frame = frame->tree()->traverseNext(m_page->mainFrame())) {
- String content;
- Vector<Resource*> allResources = cachedResourcesForFrame(frame);
- for (Vector<Resource*>::const_iterator it = allResources.begin(); it != allResources.end(); ++it) {
- Resource* cachedResource = *it;
- if (textContentForResource(cachedResource, &content)) {
- int matchesCount = ContentSearchUtils::countRegularExpressionMatches(regex.get(), content);
- if (matchesCount)
- searchResults->addItem(buildObjectForSearchResult(frameId(frame), urlWithoutFragment(cachedResource->url()).string(), matchesCount));
- }
- }
- }
-
- results = searchResults;
-}
-
void InspectorPageAgent::setDocumentContent(ErrorString* errorString, const String& frameId, const String& html)
{
Frame* frame = assertFrame(errorString, frameId);
@@ -660,10 +634,13 @@ void InspectorPageAgent::setDocumentContent(ErrorString* errorString, const Stri
DOMPatchSupport::patchDocument(*document, html);
}
-void InspectorPageAgent::setDeviceMetricsOverride(ErrorString* errorString, int width, int height, double fontScaleFactor, bool fitWindow)
+void InspectorPageAgent::setDeviceMetricsOverride(ErrorString* errorString, int width, int height, double deviceScaleFactor, bool emulateViewport, bool fitWindow, const bool* optionalTextAutosizing, const double* optionalFontScaleFactor)
{
const static long maxDimension = 10000000;
+ bool textAutosizing = optionalTextAutosizing ? *optionalTextAutosizing : false;
+ double fontScaleFactor = optionalFontScaleFactor ? *optionalFontScaleFactor : 1;
+
if (width < 0 || height < 0 || width > maxDimension || height > maxDimension) {
*errorString = "Width and height values must be positive, not greater than " + String::number(maxDimension);
return;
@@ -674,31 +651,50 @@ void InspectorPageAgent::setDeviceMetricsOverride(ErrorString* errorString, int
return;
}
+ if (deviceScaleFactor <= 0) {
+ *errorString = "deviceScaleFactor must be positive";
+ return;
+ }
+
if (fontScaleFactor <= 0) {
*errorString = "fontScaleFactor must be positive";
return;
}
- if (!deviceMetricsChanged(width, height, fontScaleFactor, fitWindow))
+ Settings& settings = m_page->settings();
+ if (width && height && !settings.acceleratedCompositingEnabled()) {
+ if (errorString)
+ *errorString = "Compositing mode is not supported";
+ return;
+ }
+
+ if (!deviceMetricsChanged(width, height, deviceScaleFactor, emulateViewport, fitWindow, fontScaleFactor, textAutosizing))
return;
+
m_state->setLong(PageAgentState::pageAgentScreenWidthOverride, width);
m_state->setLong(PageAgentState::pageAgentScreenHeightOverride, height);
- m_state->setDouble(PageAgentState::pageAgentFontScaleFactorOverride, fontScaleFactor);
+ m_state->setDouble(PageAgentState::pageAgentDeviceScaleFactorOverride, deviceScaleFactor);
+ m_state->setBoolean(PageAgentState::pageAgentEmulateViewport, emulateViewport);
m_state->setBoolean(PageAgentState::pageAgentFitWindow, fitWindow);
+ m_state->setDouble(PageAgentState::fontScaleFactor, fontScaleFactor);
+ m_state->setBoolean(PageAgentState::pageAgentTextAutosizingOverride, textAutosizing);
- updateViewMetrics(width, height, fontScaleFactor, fitWindow);
+ updateViewMetrics(width, height, deviceScaleFactor, emulateViewport, fitWindow);
}
-bool InspectorPageAgent::deviceMetricsChanged(int width, int height, double fontScaleFactor, bool fitWindow)
+bool InspectorPageAgent::deviceMetricsChanged(int width, int height, double deviceScaleFactor, bool emulateViewport, bool fitWindow, double fontScaleFactor, bool textAutosizing)
{
// These two always fit an int.
int currentWidth = static_cast<int>(m_state->getLong(PageAgentState::pageAgentScreenWidthOverride));
int currentHeight = static_cast<int>(m_state->getLong(PageAgentState::pageAgentScreenHeightOverride));
- double currentFontScaleFactor = m_state->getDouble(PageAgentState::pageAgentFontScaleFactorOverride, 1);
+ double currentDeviceScaleFactor = m_state->getDouble(PageAgentState::pageAgentDeviceScaleFactorOverride, 1);
+ bool currentEmulateViewport = m_state->getBoolean(PageAgentState::pageAgentEmulateViewport);
bool currentFitWindow = m_state->getBoolean(PageAgentState::pageAgentFitWindow);
+ double currentFontScaleFactor = m_state->getDouble(PageAgentState::fontScaleFactor, 1);
+ bool currentTextAutosizing = m_state->getBoolean(PageAgentState::pageAgentTextAutosizingOverride);
- return width != currentWidth || height != currentHeight || fontScaleFactor != currentFontScaleFactor || fitWindow != currentFitWindow;
+ return width != currentWidth || height != currentHeight || deviceScaleFactor != currentDeviceScaleFactor || emulateViewport != currentEmulateViewport || fitWindow != currentFitWindow || fontScaleFactor != currentFontScaleFactor || textAutosizing != currentTextAutosizing;
}
void InspectorPageAgent::setShowPaintRects(ErrorString*, bool show)
@@ -710,31 +706,36 @@ void InspectorPageAgent::setShowPaintRects(ErrorString*, bool show)
mainFrame()->view()->invalidate();
}
-void InspectorPageAgent::setShowDebugBorders(ErrorString*, bool show)
+void InspectorPageAgent::setShowDebugBorders(ErrorString* errorString, bool show)
{
m_state->setBoolean(PageAgentState::pageAgentShowDebugBorders, show);
+ if (show && !forceCompositingMode(errorString))
+ return;
m_client->setShowDebugBorders(show);
}
-void InspectorPageAgent::setShowFPSCounter(ErrorString*, bool show)
+void InspectorPageAgent::setShowFPSCounter(ErrorString* errorString, bool show)
{
+ // FIXME: allow metrics override, fps counter and continuous painting at the same time: crbug.com/299837.
m_state->setBoolean(PageAgentState::pageAgentShowFPSCounter, show);
- m_client->setShowFPSCounter(show);
-
- updateOverridesTopOffset();
+ if (show && !forceCompositingMode(errorString))
+ return;
+ m_client->setShowFPSCounter(show && !m_deviceMetricsOverridden);
}
-void InspectorPageAgent::setContinuousPaintingEnabled(ErrorString*, bool enabled)
+void InspectorPageAgent::setContinuousPaintingEnabled(ErrorString* errorString, bool enabled)
{
m_state->setBoolean(PageAgentState::pageAgentContinuousPaintingEnabled, enabled);
- m_client->setContinuousPaintingEnabled(enabled);
-
- updateOverridesTopOffset();
+ if (enabled && !forceCompositingMode(errorString))
+ return;
+ m_client->setContinuousPaintingEnabled(enabled && !m_deviceMetricsOverridden);
}
-void InspectorPageAgent::setShowScrollBottleneckRects(ErrorString*, bool show)
+void InspectorPageAgent::setShowScrollBottleneckRects(ErrorString* errorString, bool show)
{
m_state->setBoolean(PageAgentState::pageAgentShowScrollBottleneckRects, show);
+ if (show && !forceCompositingMode(errorString))
+ return;
m_client->setShowScrollBottleneckRects(show);
}
@@ -744,7 +745,7 @@ void InspectorPageAgent::getScriptExecutionStatus(ErrorString*, PageCommandHandl
bool disabledInSettings = false;
Frame* frame = mainFrame();
if (frame) {
- disabledByScriptController = !frame->script()->canExecuteScripts(NotAboutToExecuteScript);
+ disabledByScriptController = !frame->script().canExecuteScripts(NotAboutToExecuteScript);
if (frame->settings())
disabledInSettings = !frame->settings()->isScriptEnabled();
}
@@ -791,38 +792,32 @@ void InspectorPageAgent::didClearWindowObjectInWorld(Frame* frame, DOMWrapperWor
for (JSONObject::const_iterator it = scripts->begin(); it != end; ++it) {
String scriptText;
if (it->value->asString(&scriptText))
- frame->script()->executeScript(scriptText);
+ frame->script().executeScriptInMainWorld(scriptText);
}
}
if (!m_scriptToEvaluateOnLoadOnce.isEmpty())
- frame->script()->executeScript(m_scriptToEvaluateOnLoadOnce);
+ frame->script().executeScriptInMainWorld(m_scriptToEvaluateOnLoadOnce);
}
void InspectorPageAgent::domContentLoadedEventFired(Frame* frame)
{
- if (frame->page()->mainFrame() != frame)
+ if (!frame->isMainFrame())
return;
-
- m_isFirstLayoutAfterOnLoad = true;
m_frontend->domContentEventFired(currentTime());
- if (m_state->getBoolean(PageAgentState::forceCompositingMode))
- setForceCompositingMode(0, true);
}
void InspectorPageAgent::loadEventFired(Frame* frame)
{
- if (frame->page()->mainFrame() != frame)
+ if (!frame->isMainFrame())
return;
m_frontend->loadEventFired(currentTime());
}
-void InspectorPageAgent::childDocumentOpened(Document* document)
-{
- m_frontend->frameNavigated(buildObjectForFrame(document->frame()));
-}
-
void InspectorPageAgent::didCommitLoad(Frame*, DocumentLoader* loader)
{
+ // FIXME: If "frame" is always guarenteed to be in the same Page as loader->frame()
+ // then all we need to check here is loader->frame()->isMainFrame()
+ // and we don't need "frame" at all.
if (loader->frame() == m_page->mainFrame()) {
m_scriptToEvaluateOnLoadOnce = m_pendingScriptToEvaluateOnLoadOnce;
m_scriptPreprocessorSource = m_pendingScriptPreprocessor;
@@ -834,7 +829,7 @@ void InspectorPageAgent::didCommitLoad(Frame*, DocumentLoader* loader)
void InspectorPageAgent::frameAttachedToParent(Frame* frame)
{
- m_frontend->frameAttached(frameId(frame));
+ m_frontend->frameAttached(frameId(frame), frameId(frame->tree().parent()));
}
void InspectorPageAgent::frameDetachedFromParent(Frame* frame)
@@ -889,7 +884,7 @@ String InspectorPageAgent::loaderId(DocumentLoader* loader)
Frame* InspectorPageAgent::findFrameWithSecurityOrigin(const String& originRawString)
{
- for (Frame* frame = m_page->mainFrame(); frame; frame = frame->tree()->traverseNext()) {
+ for (Frame* frame = m_page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
RefPtr<SecurityOrigin> documentOrigin = frame->document()->securityOrigin();
if (documentOrigin->toRawString() == originRawString)
return frame;
@@ -905,19 +900,19 @@ Frame* InspectorPageAgent::assertFrame(ErrorString* errorString, const String& f
return frame;
}
-String InspectorPageAgent::resourceSourceMapURL(const String& url)
+const AtomicString& InspectorPageAgent::resourceSourceMapURL(const String& url)
{
- DEFINE_STATIC_LOCAL(String, sourceMapHttpHeader, ("SourceMap"));
- DEFINE_STATIC_LOCAL(String, deprecatedSourceMapHttpHeader, ("X-SourceMap"));
+ DEFINE_STATIC_LOCAL(const AtomicString, sourceMapHttpHeader, ("SourceMap", AtomicString::ConstructFromLiteral));
+ DEFINE_STATIC_LOCAL(const AtomicString, deprecatedSourceMapHttpHeader, ("X-SourceMap", AtomicString::ConstructFromLiteral));
if (url.isEmpty())
- return String();
+ return nullAtom;
Frame* frame = mainFrame();
if (!frame)
- return String();
+ return nullAtom;
Resource* resource = cachedResource(frame, KURL(ParsedURLString, url));
if (!resource)
- return String();
- String deprecatedHeaderSourceMapURL = resource->response().httpHeaderField(deprecatedSourceMapHttpHeader);
+ return nullAtom;
+ const AtomicString& deprecatedHeaderSourceMapURL = resource->response().httpHeaderField(deprecatedSourceMapHttpHeader);
if (!deprecatedHeaderSourceMapURL.isEmpty()) {
// FIXME: add deprecated console message here.
return deprecatedHeaderSourceMapURL;
@@ -925,11 +920,15 @@ String InspectorPageAgent::resourceSourceMapURL(const String& url)
return resource->response().httpHeaderField(sourceMapHttpHeader);
}
+bool InspectorPageAgent::deviceMetricsOverrideEnabled()
+{
+ return m_enabled && m_deviceMetricsOverridden;
+}
+
// static
DocumentLoader* InspectorPageAgent::assertDocumentLoader(ErrorString* errorString, Frame* frame)
{
- FrameLoader* frameLoader = frame->loader();
- DocumentLoader* documentLoader = frameLoader ? frameLoader->documentLoader() : 0;
+ DocumentLoader* documentLoader = frame->loader().documentLoader();
if (!documentLoader)
*errorString = "No documentLoader for given frame found";
return documentLoader;
@@ -972,35 +971,7 @@ void InspectorPageAgent::didRunJavaScriptDialog()
m_frontend->javascriptDialogClosed();
}
-void InspectorPageAgent::applyScreenWidthOverride(long* width)
-{
- long widthOverride = m_state->getLong(PageAgentState::pageAgentScreenWidthOverride);
- if (widthOverride)
- *width = widthOverride;
-}
-
-bool InspectorPageAgent::shouldApplyScreenWidthOverride()
-{
- long width = 0;
- applyScreenWidthOverride(&width);
- return !!width;
-}
-
-void InspectorPageAgent::applyScreenHeightOverride(long* height)
-{
- long heightOverride = m_state->getLong(PageAgentState::pageAgentScreenHeightOverride);
- if (heightOverride)
- *height = heightOverride;
-}
-
-bool InspectorPageAgent::shouldApplyScreenHeightOverride()
-{
- long height = 0;
- applyScreenHeightOverride(&height);
- return !!height;
-}
-
-void InspectorPageAgent::didPaint(RenderObject*, GraphicsContext* context, const LayoutRect& rect)
+void InspectorPageAgent::didPaint(RenderObject*, const GraphicsLayer*, GraphicsContext* context, const LayoutRect& rect)
{
if (!m_enabled || m_client->overridesShowPaintRects() || !m_state->getBoolean(PageAgentState::pageAgentShowPaintRects))
return;
@@ -1019,20 +990,8 @@ void InspectorPageAgent::didPaint(RenderObject*, GraphicsContext* context, const
void InspectorPageAgent::didLayout(RenderObject*)
{
- bool isFirstLayout = m_isFirstLayoutAfterOnLoad;
- if (isFirstLayout)
- m_isFirstLayoutAfterOnLoad = false;
-
if (!m_enabled)
return;
-
- if (isFirstLayout) {
- int currentWidth = static_cast<int>(m_state->getLong(PageAgentState::pageAgentScreenWidthOverride));
- int currentHeight = static_cast<int>(m_state->getLong(PageAgentState::pageAgentScreenHeightOverride));
-
- if (currentWidth && currentHeight)
- m_client->autoZoomPageToFitWidth();
- }
m_overlay->update();
}
@@ -1046,6 +1005,7 @@ void InspectorPageAgent::didResizeMainFrame()
{
if (m_enabled && m_state->getBoolean(PageAgentState::showSizeOnResize))
m_overlay->showAndHideViewSize(m_state->getBoolean(PageAgentState::showGridOnResize));
+ m_frontend->frameResized();
}
void InspectorPageAgent::didRecalculateStyle()
@@ -1066,14 +1026,14 @@ PassRefPtr<TypeBuilder::Page::Frame> InspectorPageAgent::buildObjectForFrame(Fra
{
RefPtr<TypeBuilder::Page::Frame> frameObject = TypeBuilder::Page::Frame::create()
.setId(frameId(frame))
- .setLoaderId(loaderId(frame->loader()->documentLoader()))
+ .setLoaderId(loaderId(frame->loader().documentLoader()))
.setUrl(urlWithoutFragment(frame->document()->url()).string())
- .setMimeType(frame->loader()->documentLoader()->responseMIMEType())
+ .setMimeType(frame->loader().documentLoader()->responseMIMEType())
.setSecurityOrigin(frame->document()->securityOrigin()->toRawString());
- if (frame->tree()->parent())
- frameObject->setParentId(frameId(frame->tree()->parent()));
+ if (frame->tree().parent())
+ frameObject->setParentId(frameId(frame->tree().parent()));
if (frame->ownerElement()) {
- String name = frame->ownerElement()->getNameAttribute();
+ AtomicString name = frame->ownerElement()->getNameAttribute();
if (name.isEmpty())
name = frame->ownerElement()->getAttribute(HTMLNames::idAttr);
frameObject->setName(name);
@@ -1106,7 +1066,7 @@ PassRefPtr<TypeBuilder::Page::FrameResourceTree> InspectorPageAgent::buildObject
}
RefPtr<TypeBuilder::Array<TypeBuilder::Page::FrameResourceTree> > childrenArray;
- for (Frame* child = frame->tree()->firstChild(); child; child = child->tree()->nextSibling()) {
+ for (Frame* child = frame->tree().firstChild(); child; child = child->tree().nextSibling()) {
if (!childrenArray) {
childrenArray = TypeBuilder::Array<TypeBuilder::Page::FrameResourceTree>::create();
result->setChildFrames(childrenArray);
@@ -1116,15 +1076,25 @@ PassRefPtr<TypeBuilder::Page::FrameResourceTree> InspectorPageAgent::buildObject
return result;
}
-void InspectorPageAgent::updateViewMetrics(int width, int height, double fontScaleFactor, bool fitWindow)
+void InspectorPageAgent::updateViewMetrics(int width, int height, double deviceScaleFactor, bool emulateViewport, bool fitWindow)
{
- m_client->overrideDeviceMetrics(width, height, static_cast<float>(fontScaleFactor), fitWindow);
+ if (width && height && !m_page->settings().acceleratedCompositingEnabled())
+ return;
+
+ m_deviceMetricsOverridden = width && height;
+ m_emulateViewportEnabled = emulateViewport;
+ m_client->overrideDeviceMetrics(width, height, static_cast<float>(deviceScaleFactor), emulateViewport, fitWindow);
Document* document = mainFrame()->document();
- if (document)
+ if (document) {
document->styleResolverChanged(RecalcStyleImmediately);
+ document->mediaQueryAffectingValueChanged();
+ }
InspectorInstrumentation::mediaQueryResultChanged(document);
- m_overlay->setOverride(InspectorOverlay::DeviceMetricsOverride, width && height);
+
+ // FIXME: allow metrics override, fps counter and continuous painting at the same time: crbug.com/299837.
+ m_client->setShowFPSCounter(m_state->getBoolean(PageAgentState::pageAgentShowFPSCounter) && !m_deviceMetricsOverridden);
+ m_client->setContinuousPaintingEnabled(m_state->getBoolean(PageAgentState::pageAgentContinuousPaintingEnabled) && !m_deviceMetricsOverridden);
}
void InspectorPageAgent::updateTouchEventEmulationInPage(bool enabled)
@@ -1132,19 +1102,6 @@ void InspectorPageAgent::updateTouchEventEmulationInPage(bool enabled)
m_state->setBoolean(PageAgentState::touchEventEmulationEnabled, enabled);
if (mainFrame() && mainFrame()->settings())
mainFrame()->settings()->setTouchEventEmulationEnabled(enabled);
- m_overlay->setOverride(InspectorOverlay::TouchOverride, enabled);
-}
-
-void InspectorPageAgent::updateOverridesTopOffset()
-{
- static const int continousPaintingGraphHeight = 92;
- static const int fpsGraphHeight = 73;
- int topOffset = 0;
- if (m_state->getBoolean(PageAgentState::pageAgentContinuousPaintingEnabled))
- topOffset = continousPaintingGraphHeight;
- else if (m_state->getBoolean(PageAgentState::pageAgentShowFPSCounter))
- topOffset = fpsGraphHeight;
- m_overlay->setOverridesTopOffset(topOffset);
}
void InspectorPageAgent::setGeolocationOverride(ErrorString* error, const double* latitude, const double* longitude, const double* accuracy)
@@ -1166,7 +1123,6 @@ void InspectorPageAgent::setGeolocationOverride(ErrorString* error, const double
m_geolocationPosition.clear();
controller->positionChanged(0); // Kick location update.
- m_overlay->setOverride(InspectorOverlay::GeolocationOverride, true);
}
void InspectorPageAgent::clearGeolocationOverride(ErrorString*)
@@ -1179,7 +1135,6 @@ void InspectorPageAgent::clearGeolocationOverride(ErrorString*)
GeolocationController* controller = GeolocationController::from(m_page);
if (controller && m_platformGeolocationPosition.get())
controller->positionChanged(m_platformGeolocationPosition.get());
- m_overlay->setOverride(InspectorOverlay::GeolocationOverride, false);
}
GeolocationPosition* InspectorPageAgent::overrideGeolocationPosition(GeolocationPosition* position)
@@ -1194,31 +1149,32 @@ GeolocationPosition* InspectorPageAgent::overrideGeolocationPosition(Geolocation
void InspectorPageAgent::setDeviceOrientationOverride(ErrorString* error, double alpha, double beta, double gamma)
{
- DeviceOrientationController* controller = DeviceOrientationController::from(m_page);
+ DeviceOrientationController* controller = DeviceOrientationController::from(mainFrame()->document());
if (!controller) {
*error = "Internal error: unable to override device orientation";
return;
}
- ErrorString clearError;
- clearDeviceOrientationOverride(&clearError);
+ controller->didChangeDeviceOrientation(DeviceOrientationData::create(true, alpha, true, beta, true, gamma).get());
+}
- m_deviceOrientation = DeviceOrientationData::create(true, alpha, true, beta, true, gamma);
- controller->didChangeDeviceOrientation(m_deviceOrientation.get());
- m_overlay->setOverride(InspectorOverlay::DeviceOrientationOverride, true);
+void InspectorPageAgent::clearDeviceOrientationOverride(ErrorString* error)
+{
+ setDeviceOrientationOverride(error, 0, 0, 0);
}
-void InspectorPageAgent::clearDeviceOrientationOverride(ErrorString*)
+bool InspectorPageAgent::overrideTextAutosizing(bool textAutosizing)
{
- m_deviceOrientation.clear();
- m_overlay->setOverride(InspectorOverlay::DeviceOrientationOverride, false);
+ if (!m_deviceMetricsOverridden)
+ return textAutosizing;
+ return m_state->getBoolean(PageAgentState::pageAgentTextAutosizingOverride);
}
-DeviceOrientationData* InspectorPageAgent::overrideDeviceOrientation(DeviceOrientationData* deviceOrientation)
+float InspectorPageAgent::overrideFontScaleFactor(float fontScaleFactor)
{
- if (m_deviceOrientation)
- deviceOrientation = m_deviceOrientation.get();
- return deviceOrientation;
+ if (!m_deviceMetricsOverridden)
+ return fontScaleFactor;
+ return static_cast<float>(m_state->getDouble(PageAgentState::fontScaleFactor));
}
void InspectorPageAgent::setTouchEmulationEnabled(ErrorString*, bool enabled)
@@ -1239,10 +1195,23 @@ void InspectorPageAgent::setEmulatedMedia(ErrorString*, const String& media)
if (m_page->mainFrame())
document = m_page->mainFrame()->document();
if (document) {
+ document->mediaQueryAffectingValueChanged();
document->styleResolverChanged(RecalcStyleImmediately);
document->updateLayout();
}
- m_overlay->setOverride(InspectorOverlay::CSSMediaOverride, !media.isEmpty());
+}
+
+bool InspectorPageAgent::applyViewportStyleOverride(StyleResolver* resolver)
+{
+ if (!m_deviceMetricsOverridden || !m_emulateViewportEnabled)
+ return false;
+
+ RefPtr<StyleSheetContents> styleSheet = StyleSheetContents::create(CSSParserContext(UASheetMode));
+ styleSheet->parseString(String(viewportAndroidUserAgentStyleSheet, sizeof(viewportAndroidUserAgentStyleSheet)));
+ OwnPtr<RuleSet> ruleSet = RuleSet::create();
+ ruleSet->addRulesFromSheet(styleSheet.get(), MediaQueryEvaluator("screen"));
+ resolver->viewportStyleResolver()->collectViewportRules(ruleSet.get(), ViewportStyleResolver::UserAgentOrigin);
+ return true;
}
void InspectorPageAgent::applyEmulatedMedia(String* media)
@@ -1252,26 +1221,29 @@ void InspectorPageAgent::applyEmulatedMedia(String* media)
*media = emulatedMedia;
}
-void InspectorPageAgent::setForceCompositingMode(ErrorString* errorString, bool force)
+bool InspectorPageAgent::forceCompositingMode(ErrorString* errorString)
{
Settings& settings = m_page->settings();
- if (force && !settings.acceleratedCompositingEnabled()) {
+ if (!settings.acceleratedCompositingEnabled()) {
if (errorString)
*errorString = "Compositing mode is not supported";
- return;
+ return false;
}
- m_state->setBoolean(PageAgentState::forceCompositingMode, force);
- if (settings.forceCompositingMode() == force)
- return;
- m_didForceCompositingMode = force;
- settings.setForceCompositingMode(force);
+ if (settings.forceCompositingMode())
+ return true;
+ settings.setForceCompositingMode(true);
Frame* mainFrame = m_page->mainFrame();
- if (!mainFrame)
- return;
- mainFrame->view()->updateCompositingLayersAfterStyleChange();
+ if (mainFrame)
+ mainFrame->view()->updateCompositingLayersAfterStyleChange();
+ return true;
}
-void InspectorPageAgent::captureScreenshot(ErrorString*, const String*, const int*, const int*, const int*, String*, double*, double*, RefPtr<TypeBuilder::DOM::Rect>&)
+void InspectorPageAgent::captureScreenshot(ErrorString*, const String*, const int*, const int*, const int*, String*, RefPtr<TypeBuilder::Page::ScreencastFrameMetadata>&)
+{
+ // Handled on the browser level.
+}
+
+void InspectorPageAgent::canScreencast(ErrorString*, bool*)
{
// Handled on the browser level.
}
@@ -1291,6 +1263,11 @@ void InspectorPageAgent::handleJavaScriptDialog(ErrorString* errorString, bool a
// Handled on the browser level.
}
+void InspectorPageAgent::queryUsageAndQuota(WebCore::ErrorString*, const WTF::String&, WTF::RefPtr<WebCore::TypeBuilder::Page::Quota>&, WTF::RefPtr<WebCore::TypeBuilder::Page::Usage>&)
+{
+ // Handled on the browser level.
+}
+
void InspectorPageAgent::setShowViewportSizeOnResize(ErrorString*, bool show, const bool* showGrid)
{
m_state->setBoolean(PageAgentState::showSizeOnResize, show);
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InspectorPageAgent.h b/chromium/third_party/WebKit/Source/core/inspector/InspectorPageAgent.h
index b1dd8aceb0e..8a0dc8d52b2 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InspectorPageAgent.h
+++ b/chromium/third_party/WebKit/Source/core/inspector/InspectorPageAgent.h
@@ -34,7 +34,6 @@
#include "InspectorFrontend.h"
#include "core/inspector/InspectorBaseAgent.h"
-#include "modules/device_orientation/DeviceOrientationData.h"
#include "modules/geolocation/GeolocationPosition.h"
#include "wtf/HashMap.h"
#include "wtf/text/WTFString.h"
@@ -47,6 +46,7 @@ class Document;
class DocumentLoader;
class Frame;
class GraphicsContext;
+class GraphicsLayer;
class InjectedScriptManager;
class InspectorClient;
class InspectorOverlay;
@@ -57,6 +57,7 @@ class LayoutRect;
class Page;
class RenderObject;
class SharedBuffer;
+class StyleResolver;
typedef String ErrorString;
@@ -94,14 +95,13 @@ public:
virtual void navigate(ErrorString*, const String& url);
virtual void getNavigationHistory(ErrorString*, int*, RefPtr<TypeBuilder::Array<TypeBuilder::Page::NavigationEntry> >&);
virtual void navigateToHistoryEntry(ErrorString*, int);
- virtual void getCookies(ErrorString*, RefPtr<TypeBuilder::Array<TypeBuilder::Page::Cookie> >& cookies, WTF::String* cookiesString);
+ virtual void getCookies(ErrorString*, RefPtr<TypeBuilder::Array<TypeBuilder::Page::Cookie> >& cookies);
virtual void deleteCookie(ErrorString*, const String& cookieName, const String& url);
virtual void getResourceTree(ErrorString*, RefPtr<TypeBuilder::Page::FrameResourceTree>&);
virtual void getResourceContent(ErrorString*, const String& frameId, const String& url, String* content, bool* base64Encoded);
virtual void searchInResource(ErrorString*, const String& frameId, const String& url, const String& query, const bool* optionalCaseSensitive, const bool* optionalIsRegex, RefPtr<TypeBuilder::Array<TypeBuilder::Page::SearchMatch> >&);
- virtual void searchInResources(ErrorString*, const String&, const bool* caseSensitive, const bool* isRegex, RefPtr<TypeBuilder::Array<TypeBuilder::Page::SearchResult> >&);
virtual void setDocumentContent(ErrorString*, const String& frameId, const String& html);
- virtual void setDeviceMetricsOverride(ErrorString*, int width, int height, double fontScaleFactor, bool fitWindow);
+ virtual void setDeviceMetricsOverride(ErrorString*, int width, int height, double deviceScaleFactor, bool emulateViewport, bool fitWindow, const bool* optionalTextAutosizing, const double* optionalFontScaleFactor);
virtual void setShowPaintRects(ErrorString*, bool show);
virtual void setShowDebugBorders(ErrorString*, bool show);
virtual void setShowFPSCounter(ErrorString*, bool show);
@@ -115,24 +115,26 @@ public:
virtual void clearDeviceOrientationOverride(ErrorString*);
virtual void setTouchEmulationEnabled(ErrorString*, bool);
virtual void setEmulatedMedia(ErrorString*, const String&);
- virtual void setForceCompositingMode(ErrorString*, bool force);
- virtual void captureScreenshot(ErrorString*, const String* format, const int* quality, const int* maxWidth, const int* maxHeight, String* data, double* deviceScaleFactor, double* pageScaleFactor, RefPtr<TypeBuilder::DOM::Rect>&);
+ virtual void captureScreenshot(ErrorString*, const String* format, const int* quality, const int* maxWidth, const int* maxHeight, String* data, RefPtr<TypeBuilder::Page::ScreencastFrameMetadata>& out_metadata);
+ virtual void canScreencast(ErrorString*, bool*);
virtual void startScreencast(ErrorString*, const String* format, const int* quality, const int* maxWidth, const int* maxHeight);
virtual void stopScreencast(ErrorString*);
virtual void handleJavaScriptDialog(ErrorString*, bool accept, const String* promptText);
+ virtual void queryUsageAndQuota(WebCore::ErrorString*, const WTF::String&, WTF::RefPtr<WebCore::TypeBuilder::Page::Quota>&, WTF::RefPtr<WebCore::TypeBuilder::Page::Usage>&);
virtual void setShowViewportSizeOnResize(ErrorString*, bool show, const bool* showGrid);
- // Geolocation override helpers.
+ // Geolocation override helper.
GeolocationPosition* overrideGeolocationPosition(GeolocationPosition*);
- // DeviceOrientation helper
- DeviceOrientationData* overrideDeviceOrientation(DeviceOrientationData*);
+ // Text autosizing override helpers.
+ bool overrideTextAutosizing(bool);
+ // Note: This is used by Settings::deviceScaleAdjustment to calculate the overridden device scale adjustment.
+ float overrideFontScaleFactor(float);
// InspectorInstrumentation API
void didClearWindowObjectInWorld(Frame*, DOMWrapperWorld*);
void domContentLoadedEventFired(Frame*);
void loadEventFired(Frame*);
- void childDocumentOpened(Document*);
void didCommitLoad(Frame*, DocumentLoader*);
void frameAttachedToParent(Frame*);
void frameDetachedFromParent(Frame*);
@@ -143,12 +145,9 @@ public:
void frameClearedScheduledNavigation(Frame*);
void willRunJavaScriptDialog(const String& message);
void didRunJavaScriptDialog();
- void applyScreenWidthOverride(long*);
- bool shouldApplyScreenWidthOverride();
- void applyScreenHeightOverride(long*);
- bool shouldApplyScreenHeightOverride();
+ bool applyViewportStyleOverride(StyleResolver*);
void applyEmulatedMedia(String*);
- void didPaint(RenderObject*, GraphicsContext*, const LayoutRect&);
+ void didPaint(RenderObject*, const GraphicsLayer*, GraphicsContext*, const LayoutRect&);
void didLayout(RenderObject*);
void didScroll();
void didResizeMainFrame();
@@ -173,17 +172,18 @@ public:
Frame* findFrameWithSecurityOrigin(const String& originRawString);
Frame* assertFrame(ErrorString*, const String& frameId);
String scriptPreprocessorSource() { return m_scriptPreprocessorSource; }
- String resourceSourceMapURL(const String& url);
+ const AtomicString& resourceSourceMapURL(const String& url);
+ bool deviceMetricsOverrideEnabled();
static DocumentLoader* assertDocumentLoader(ErrorString*, Frame*);
private:
static void resourceContent(ErrorString*, Frame*, const KURL&, String* result, bool* base64Encoded);
InspectorPageAgent(InstrumentingAgents*, Page*, InspectorCompositeState*, InjectedScriptManager*, InspectorClient*, InspectorOverlay*);
- bool deviceMetricsChanged(int width, int height, double fontScaleFactor, bool fitWindow);
- void updateViewMetrics(int, int, double, bool);
+ bool deviceMetricsChanged(int width, int height, double deviceScaleFactor, bool emulateViewport, bool fitWindow, double fontScaleFactor, bool textAutosizing);
+ void updateViewMetrics(int width, int height, double deviceScaleFactor, bool emulateViewport, bool fitWindow);
void updateTouchEventEmulationInPage(bool);
- void updateOverridesTopOffset();
+ bool forceCompositingMode(ErrorString*);
static bool dataContent(const char* data, unsigned size, const String& textEncodingName, bool withBase64Encode, String* result);
@@ -203,13 +203,12 @@ private:
HashMap<String, Frame*> m_identifierToFrame;
HashMap<DocumentLoader*, String> m_loaderToIdentifier;
bool m_enabled;
- bool m_isFirstLayoutAfterOnLoad;
bool m_geolocationOverridden;
bool m_ignoreScriptsEnabledNotification;
- bool m_didForceCompositingMode;
+ bool m_deviceMetricsOverridden;
+ bool m_emulateViewportEnabled;
RefPtr<GeolocationPosition> m_geolocationPosition;
RefPtr<GeolocationPosition> m_platformGeolocationPosition;
- RefPtr<DeviceOrientationData> m_deviceOrientation;
};
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InspectorProfilerAgent.cpp b/chromium/third_party/WebKit/Source/core/inspector/InspectorProfilerAgent.cpp
index 6db81c8bb8d..f7083a9cbf5 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InspectorProfilerAgent.cpp
+++ b/chromium/third_party/WebKit/Source/core/inspector/InspectorProfilerAgent.cpp
@@ -30,17 +30,16 @@
#include "config.h"
#include "core/inspector/InspectorProfilerAgent.h"
-#include "InspectorFrontend.h"
+#include "bindings/v8/ScriptCallStackFactory.h"
#include "bindings/v8/ScriptProfiler.h"
-#include "core/inspector/ConsoleAPITypes.h"
#include "core/inspector/InjectedScript.h"
#include "core/inspector/InjectedScriptHost.h"
-#include "core/inspector/InspectorConsoleAgent.h"
+#include "core/inspector/InspectorOverlay.h"
#include "core/inspector/InspectorState.h"
#include "core/inspector/InstrumentingAgents.h"
#include "core/inspector/ScriptCallStack.h"
#include "core/inspector/ScriptProfile.h"
-#include "core/page/ConsoleTypes.h"
+#include "core/frame/ConsoleTypes.h"
#include "wtf/CurrentTime.h"
#include "wtf/text/StringConcatenate.h"
@@ -50,27 +49,52 @@ namespace ProfilerAgentState {
static const char samplingInterval[] = "samplingInterval";
static const char userInitiatedProfiling[] = "userInitiatedProfiling";
static const char profilerEnabled[] = "profilerEnabled";
-static const char profileHeadersRequested[] = "profileHeadersRequested";
}
-static const char* const userInitiatedProfileName = "org.webkit.profiles.user-initiated";
-static const char* const CPUProfileType = "CPU";
+static PassRefPtr<TypeBuilder::Profiler::CPUProfile> createCPUProfile(const ScriptProfile& scriptProfile)
+{
+ RefPtr<TypeBuilder::Profiler::CPUProfile> profile = TypeBuilder::Profiler::CPUProfile::create()
+ .setHead(scriptProfile.buildInspectorObjectForHead())
+ .setStartTime(scriptProfile.startTime())
+ .setEndTime(scriptProfile.endTime());
+ profile->setSamples(scriptProfile.buildInspectorObjectForSamples());
+ return profile.release();
+}
+
+static PassRefPtr<TypeBuilder::Debugger::Location> currentDebugLocation()
+{
+ RefPtr<ScriptCallStack> callStack(createScriptCallStackForConsole(1));
+ const ScriptCallFrame& lastCaller = callStack->at(0);
+ RefPtr<TypeBuilder::Debugger::Location> location = TypeBuilder::Debugger::Location::create()
+ .setScriptId(lastCaller.scriptId())
+ .setLineNumber(lastCaller.lineNumber());
+ location->setColumnNumber(lastCaller.columnNumber());
+ return location.release();
+}
+
+class InspectorProfilerAgent::ProfileDescriptor {
+public:
+ ProfileDescriptor(const String& id, const String& title)
+ : m_id(id)
+ , m_title(title) { }
+ String m_id;
+ String m_title;
+};
-PassOwnPtr<InspectorProfilerAgent> InspectorProfilerAgent::create(InstrumentingAgents* instrumentingAgents, InspectorConsoleAgent* consoleAgent, InspectorCompositeState* inspectorState, InjectedScriptManager* injectedScriptManager)
+PassOwnPtr<InspectorProfilerAgent> InspectorProfilerAgent::create(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* inspectorState, InjectedScriptManager* injectedScriptManager, InspectorOverlay* overlay)
{
- return adoptPtr(new InspectorProfilerAgent(instrumentingAgents, consoleAgent, inspectorState, injectedScriptManager));
+ return adoptPtr(new InspectorProfilerAgent(instrumentingAgents, inspectorState, injectedScriptManager, overlay));
}
-InspectorProfilerAgent::InspectorProfilerAgent(InstrumentingAgents* instrumentingAgents, InspectorConsoleAgent* consoleAgent, InspectorCompositeState* inspectorState, InjectedScriptManager* injectedScriptManager)
+InspectorProfilerAgent::InspectorProfilerAgent(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* inspectorState, InjectedScriptManager* injectedScriptManager, InspectorOverlay* overlay)
: InspectorBaseAgent<InspectorProfilerAgent>("Profiler", instrumentingAgents, inspectorState)
- , m_consoleAgent(consoleAgent)
, m_injectedScriptManager(injectedScriptManager)
, m_frontend(0)
, m_recordingCPUProfile(false)
- , m_currentUserInitiatedProfileNumber(-1)
- , m_nextUserInitiatedProfileNumber(1)
+ , m_nextProfileId(1)
, m_profileNameIdleTimeMap(ScriptProfiler::currentProfileNameIdleTimeMap())
, m_idleStartTime(0.0)
+ , m_overlay(overlay)
{
}
@@ -78,49 +102,64 @@ InspectorProfilerAgent::~InspectorProfilerAgent()
{
}
-void InspectorProfilerAgent::addProfile(PassRefPtr<ScriptProfile> prpProfile, unsigned lineNumber, const String& sourceURL)
+void InspectorProfilerAgent::consoleProfile(const String& title, ScriptState* state)
{
- RefPtr<ScriptProfile> profile = prpProfile;
- m_profiles.add(profile->uid(), profile);
- if (m_frontend && m_state->getBoolean(ProfilerAgentState::profileHeadersRequested))
- m_frontend->addProfileHeader(createProfileHeader(*profile));
- addProfileFinishedMessageToConsole(profile, lineNumber, sourceURL);
+ ASSERT(m_frontend && enabled());
+ String id = String::number(m_nextProfileId++);
+ m_startedProfiles.append(ProfileDescriptor(id, title));
+ ScriptProfiler::start(id);
+ m_frontend->consoleProfile(id, currentDebugLocation(), title.isNull() ? 0 : &title);
}
-void InspectorProfilerAgent::addProfile(PassRefPtr<ScriptProfile> prpProfile, PassRefPtr<ScriptCallStack> callStack)
+void InspectorProfilerAgent::consoleProfileEnd(const String& title)
{
- const ScriptCallFrame& lastCaller = callStack->at(0);
- addProfile(prpProfile, lastCaller.lineNumber(), lastCaller.sourceURL());
-}
-
-void InspectorProfilerAgent::addProfileFinishedMessageToConsole(PassRefPtr<ScriptProfile> prpProfile, unsigned lineNumber, const String& sourceURL)
-{
- if (!m_frontend)
+ ASSERT(m_frontend && enabled());
+ String id;
+ String resolvedTitle;
+ // Take last started profile if no title was passed.
+ if (title.isNull()) {
+ if (m_startedProfiles.isEmpty())
+ return;
+ id = m_startedProfiles.last().m_id;
+ resolvedTitle = m_startedProfiles.last().m_title;
+ m_startedProfiles.removeLast();
+ } else {
+ for (size_t i = 0; i < m_startedProfiles.size(); i++) {
+ if (m_startedProfiles[i].m_title == title) {
+ resolvedTitle = title;
+ id = m_startedProfiles[i].m_id;
+ m_startedProfiles.remove(i);
+ break;
+ }
+ }
+ if (id.isEmpty())
+ return;
+ }
+ RefPtr<ScriptProfile> profile = ScriptProfiler::stop(id);
+ if (!profile)
return;
- RefPtr<ScriptProfile> profile = prpProfile;
- String message = profile->title() + "#" + String::number(profile->uid());
- m_consoleAgent->addMessageToConsole(ConsoleAPIMessageSource, ProfileEndMessageType, DebugMessageLevel, message, sourceURL, lineNumber);
+ RefPtr<TypeBuilder::Debugger::Location> location = currentDebugLocation();
+ if (!m_keepAliveProfile)
+ m_keepAliveProfile = profile;
+ m_frontend->addProfileHeader(id, location, createCPUProfile(*profile), resolvedTitle.isNull() ? 0 : &resolvedTitle);
}
-PassRefPtr<TypeBuilder::Profiler::ProfileHeader> InspectorProfilerAgent::createProfileHeader(const ScriptProfile& profile)
+void InspectorProfilerAgent::enable(ErrorString*)
{
- return TypeBuilder::Profiler::ProfileHeader::create()
- .setUid(profile.uid())
- .setTitle(profile.title())
- .release();
+ m_state->setBoolean(ProfilerAgentState::profilerEnabled, true);
+ doEnable();
}
-void InspectorProfilerAgent::enable(ErrorString*)
+void InspectorProfilerAgent::doEnable()
{
- m_state->setBoolean(ProfilerAgentState::profilerEnabled, true);
m_instrumentingAgents->setInspectorProfilerAgent(this);
}
void InspectorProfilerAgent::disable(ErrorString*)
{
+ m_keepAliveProfile.clear();
m_instrumentingAgents->setInspectorProfilerAgent(0);
m_state->setBoolean(ProfilerAgentState::profilerEnabled, false);
- m_state->setBoolean(ProfilerAgentState::profileHeadersRequested, false);
}
bool InspectorProfilerAgent::enabled()
@@ -138,68 +177,6 @@ void InspectorProfilerAgent::setSamplingInterval(ErrorString* error, int interva
ScriptProfiler::setSamplingInterval(interval);
}
-String InspectorProfilerAgent::getCurrentUserInitiatedProfileName(bool incrementProfileNumber)
-{
- if (incrementProfileNumber)
- m_currentUserInitiatedProfileNumber = m_nextUserInitiatedProfileNumber++;
-
- return String(userInitiatedProfileName) + "." + String::number(m_currentUserInitiatedProfileNumber);
-}
-
-void InspectorProfilerAgent::getProfileHeaders(ErrorString*, RefPtr<TypeBuilder::Array<TypeBuilder::Profiler::ProfileHeader> >& headers)
-{
- m_state->setBoolean(ProfilerAgentState::profileHeadersRequested, true);
- headers = TypeBuilder::Array<TypeBuilder::Profiler::ProfileHeader>::create();
-
- ProfilesMap::iterator profilesEnd = m_profiles.end();
- for (ProfilesMap::iterator it = m_profiles.begin(); it != profilesEnd; ++it)
- headers->addItem(createProfileHeader(*it->value));
-}
-
-void InspectorProfilerAgent::getCPUProfile(ErrorString* errorString, int rawUid, RefPtr<TypeBuilder::Profiler::CPUProfile>& profileObject)
-{
- unsigned uid = static_cast<unsigned>(rawUid);
- ProfilesMap::iterator it = m_profiles.find(uid);
- if (it == m_profiles.end()) {
- *errorString = "Profile wasn't found";
- return;
- }
- profileObject = TypeBuilder::Profiler::CPUProfile::create()
- .setHead(it->value->buildInspectorObjectForHead())
- .setStartTime(it->value->startTime())
- .setEndTime(it->value->endTime());
- profileObject->setSamples(it->value->buildInspectorObjectForSamples());
-}
-
-void InspectorProfilerAgent::removeProfile(ErrorString*, const String& type, int rawUid)
-{
- unsigned uid = static_cast<unsigned>(rawUid);
- if (type == CPUProfileType) {
- if (m_profiles.contains(uid))
- m_profiles.remove(uid);
- }
-}
-
-void InspectorProfilerAgent::clearProfiles(ErrorString*)
-{
- stop();
- m_profiles.clear();
- m_currentUserInitiatedProfileNumber = 1;
- m_nextUserInitiatedProfileNumber = 1;
- resetFrontendProfiles();
- m_injectedScriptManager->injectedScriptHost()->clearInspectedObjects();
-}
-
-void InspectorProfilerAgent::resetFrontendProfiles()
-{
- if (!m_frontend)
- return;
- if (!m_state->getBoolean(ProfilerAgentState::profileHeadersRequested))
- return;
- if (m_profiles.isEmpty())
- m_frontend->resetProfiles();
-}
-
void InspectorProfilerAgent::setFrontend(InspectorFrontend* frontend)
{
m_frontend = frontend->profiler();
@@ -208,21 +185,25 @@ void InspectorProfilerAgent::setFrontend(InspectorFrontend* frontend)
void InspectorProfilerAgent::clearFrontend()
{
m_frontend = 0;
- stop();
+ stop(0, 0);
+ m_injectedScriptManager->injectedScriptHost()->clearInspectedObjects();
ErrorString error;
disable(&error);
}
void InspectorProfilerAgent::restore()
{
- resetFrontendProfiles();
+ if (m_state->getBoolean(ProfilerAgentState::profilerEnabled)) {
+ doEnable();
+ m_frontend->resetProfiles();
+ }
if (long interval = m_state->getLong(ProfilerAgentState::samplingInterval, 0))
ScriptProfiler::setSamplingInterval(interval);
if (m_state->getBoolean(ProfilerAgentState::userInitiatedProfiling))
start();
}
-void InspectorProfilerAgent::start(ErrorString*)
+void InspectorProfilerAgent::start(ErrorString* error)
{
if (m_recordingCPUProfile)
return;
@@ -231,42 +212,38 @@ void InspectorProfilerAgent::start(ErrorString*)
enable(&error);
}
m_recordingCPUProfile = true;
- String title = getCurrentUserInitiatedProfileName(true);
- ScriptProfiler::start(title);
- toggleRecordButton(true);
+ if (m_overlay)
+ m_overlay->startedRecordingProfile();
+ m_frontendInitiatedProfileId = String::number(m_nextProfileId++);
+ ScriptProfiler::start(m_frontendInitiatedProfileId);
m_state->setBoolean(ProfilerAgentState::userInitiatedProfiling, true);
}
-void InspectorProfilerAgent::stop(ErrorString* errorString, RefPtr<TypeBuilder::Profiler::ProfileHeader>& header)
+void InspectorProfilerAgent::stop(ErrorString* errorString, RefPtr<TypeBuilder::Profiler::CPUProfile>& profile)
{
- header = stop(errorString);
+ stop(errorString, &profile);
}
-PassRefPtr<TypeBuilder::Profiler::ProfileHeader> InspectorProfilerAgent::stop(ErrorString* errorString)
+void InspectorProfilerAgent::stop(ErrorString* errorString, RefPtr<TypeBuilder::Profiler::CPUProfile>* profile)
{
if (!m_recordingCPUProfile) {
if (errorString)
*errorString = "No recording profiles found";
- return 0;
+ return;
}
m_recordingCPUProfile = false;
- String title = getCurrentUserInitiatedProfileName();
- RefPtr<ScriptProfile> profile = ScriptProfiler::stop(title);
- RefPtr<TypeBuilder::Profiler::ProfileHeader> profileHeader;
- if (profile) {
- addProfile(profile, 0, String());
- profileHeader = createProfileHeader(*profile);
- } else if (errorString)
+ if (m_overlay)
+ m_overlay->finishedRecordingProfile();
+ RefPtr<ScriptProfile> scriptProfile = ScriptProfiler::stop(m_frontendInitiatedProfileId);
+ m_frontendInitiatedProfileId = String();
+ if (scriptProfile && profile) {
+ *profile = createCPUProfile(*scriptProfile);
+ if (!m_keepAliveProfile)
+ m_keepAliveProfile = scriptProfile;
+ } else if (errorString) {
*errorString = "Profile wasn't found";
- toggleRecordButton(false);
+ }
m_state->setBoolean(ProfilerAgentState::userInitiatedProfiling, false);
- return profileHeader;
-}
-
-void InspectorProfilerAgent::toggleRecordButton(bool isProfiling)
-{
- if (m_frontend)
- m_frontend->setRecordingProfile(isProfiling);
}
void InspectorProfilerAgent::idleFinished()
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InspectorProfilerAgent.h b/chromium/third_party/WebKit/Source/core/inspector/InspectorProfilerAgent.h
index a77d95ca83e..feefe2fdc9e 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InspectorProfilerAgent.h
+++ b/chromium/third_party/WebKit/Source/core/inspector/InspectorProfilerAgent.h
@@ -41,69 +41,60 @@
namespace WebCore {
class InjectedScriptManager;
-class InspectorConsoleAgent;
class InspectorFrontend;
+class InspectorOverlay;
class InstrumentingAgents;
class ScriptCallStack;
class ScriptProfile;
+class ScriptState;
typedef String ErrorString;
class InspectorProfilerAgent : public InspectorBaseAgent<InspectorProfilerAgent>, public InspectorBackendDispatcher::ProfilerCommandHandler {
WTF_MAKE_NONCOPYABLE(InspectorProfilerAgent); WTF_MAKE_FAST_ALLOCATED;
public:
- static PassOwnPtr<InspectorProfilerAgent> create(InstrumentingAgents*, InspectorConsoleAgent*, InspectorCompositeState*, InjectedScriptManager*);
+ static PassOwnPtr<InspectorProfilerAgent> create(InstrumentingAgents*, InspectorCompositeState*, InjectedScriptManager*, InspectorOverlay*);
virtual ~InspectorProfilerAgent();
- void addProfile(PassRefPtr<ScriptProfile> prpProfile, PassRefPtr<ScriptCallStack>);
- void addProfileFinishedMessageToConsole(PassRefPtr<ScriptProfile>, unsigned lineNumber, const String& sourceURL);
- virtual void clearProfiles(ErrorString*);
+ void consoleProfile(const String& title, ScriptState*);
+ void consoleProfileEnd(const String& title);
virtual void enable(ErrorString*);
virtual void disable(ErrorString*);
virtual void setSamplingInterval(ErrorString*, int);
virtual void start(ErrorString* = 0);
- virtual void stop(ErrorString*, RefPtr<TypeBuilder::Profiler::ProfileHeader>& header);
-
- bool enabled();
- String getCurrentUserInitiatedProfileName(bool incrementProfileNumber = false);
- virtual void getProfileHeaders(ErrorString*, RefPtr<TypeBuilder::Array<TypeBuilder::Profiler::ProfileHeader> >&);
- virtual void getCPUProfile(ErrorString*, int uid, RefPtr<TypeBuilder::Profiler::CPUProfile>&);
- virtual void removeProfile(ErrorString*, const String& type, int uid);
+ virtual void stop(ErrorString*, RefPtr<TypeBuilder::Profiler::CPUProfile>&);
virtual void setFrontend(InspectorFrontend*);
virtual void clearFrontend();
virtual void restore();
- void toggleRecordButton(bool isProfiling);
-
void willProcessTask();
void didProcessTask();
void willEnterNestedRunLoop();
void didLeaveNestedRunLoop();
private:
- InspectorProfilerAgent(InstrumentingAgents*, InspectorConsoleAgent*, InspectorCompositeState*, InjectedScriptManager*);
-
- void addProfile(PassRefPtr<ScriptProfile> prpProfile, unsigned lineNumber, const String& sourceURL);
-
- void resetFrontendProfiles();
- PassRefPtr<TypeBuilder::Profiler::ProfileHeader> stop(ErrorString* = 0);
-
- PassRefPtr<TypeBuilder::Profiler::ProfileHeader> createProfileHeader(const ScriptProfile&);
+ InspectorProfilerAgent(InstrumentingAgents*, InspectorCompositeState*, InjectedScriptManager*, InspectorOverlay*);
+ bool enabled();
+ void doEnable();
+ void stop(ErrorString*, RefPtr<TypeBuilder::Profiler::CPUProfile>*);
- InspectorConsoleAgent* m_consoleAgent;
InjectedScriptManager* m_injectedScriptManager;
InspectorFrontend::Profiler* m_frontend;
+ // This is a temporary workaround to make sure v8 doesn't stop profiling when
+ // last finished profile is deleted (we keep at least one finished profile alive).
+ RefPtr<ScriptProfile> m_keepAliveProfile;
bool m_recordingCPUProfile;
- int m_currentUserInitiatedProfileNumber;
- unsigned m_nextUserInitiatedProfileNumber;
- typedef HashMap<unsigned, RefPtr<ScriptProfile> > ProfilesMap;
- ProfilesMap m_profiles;
+ int m_nextProfileId;
+ class ProfileDescriptor;
+ Vector<ProfileDescriptor> m_startedProfiles;
+ String m_frontendInitiatedProfileId;
typedef HashMap<String, double> ProfileNameIdleTimeMap;
ProfileNameIdleTimeMap* m_profileNameIdleTimeMap;
double m_idleStartTime;
+ InspectorOverlay* m_overlay;
void idleStarted();
void idleFinished();
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InspectorResourceAgent.cpp b/chromium/third_party/WebKit/Source/core/inspector/InspectorResourceAgent.cpp
index 643b99c81bf..d0e29e993d0 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InspectorResourceAgent.cpp
+++ b/chromium/third_party/WebKit/Source/core/inspector/InspectorResourceAgent.cpp
@@ -32,7 +32,6 @@
#include "core/inspector/InspectorResourceAgent.h"
#include "FetchInitiatorTypeNames.h"
-#include "InspectorFrontend.h"
#include "bindings/v8/ExceptionStatePlaceholder.h"
#include "bindings/v8/ScriptCallStackFactory.h"
#include "core/dom/Document.h"
@@ -42,6 +41,7 @@
#include "core/fetch/Resource.h"
#include "core/fetch/ResourceFetcher.h"
#include "core/fetch/ResourceLoader.h"
+#include "core/frame/Frame.h"
#include "core/inspector/IdentifiersFactory.h"
#include "core/inspector/InspectorClient.h"
#include "core/inspector/InspectorOverlay.h"
@@ -55,18 +55,17 @@
#include "core/loader/FrameLoader.h"
#include "core/loader/ThreadableLoader.h"
#include "core/loader/ThreadableLoaderClient.h"
-#include "core/page/Frame.h"
#include "core/page/Page.h"
-#include "core/platform/JSONValues.h"
-#include "core/platform/network/HTTPHeaderMap.h"
-#include "core/platform/network/ResourceError.h"
-#include "core/platform/network/ResourceRequest.h"
-#include "core/platform/network/ResourceResponse.h"
#include "core/xml/XMLHttpRequest.h"
#include "modules/websockets/WebSocketFrame.h"
-#include "modules/websockets/WebSocketHandshakeRequest.h"
-#include "modules/websockets/WebSocketHandshakeResponse.h"
-#include "weborigin/KURL.h"
+#include "platform/JSONValues.h"
+#include "platform/network/HTTPHeaderMap.h"
+#include "platform/network/ResourceError.h"
+#include "platform/network/ResourceRequest.h"
+#include "platform/network/ResourceResponse.h"
+#include "platform/network/WebSocketHandshakeRequest.h"
+#include "platform/network/WebSocketHandshakeResponse.h"
+#include "platform/weborigin/KURL.h"
#include "wtf/CurrentTime.h"
#include "wtf/RefPtr.h"
@@ -165,7 +164,7 @@ private:
RefPtr<LoadResourceForFrontendCallback> m_callback;
RefPtr<ThreadableLoader> m_loader;
- RefPtr<TextResourceDecoder> m_decoder;
+ OwnPtr<TextResourceDecoder> m_decoder;
ScriptString m_responseText;
int m_statusCode;
HTTPHeaderMap m_responseHeaders;
@@ -287,7 +286,8 @@ InspectorResourceAgent::~InspectorResourceAgent()
void InspectorResourceAgent::willSendRequest(unsigned long identifier, DocumentLoader* loader, ResourceRequest& request, const ResourceResponse& redirectResponse, const FetchInitiatorInfo& initiatorInfo)
{
- if (initiatorInfo.name == FetchInitiatorTypeNames::inspector)
+ // Ignore the request initiated internally.
+ if (initiatorInfo.name == FetchInitiatorTypeNames::internal)
return;
String requestId = IdentifiersFactory::requestId(identifier);
m_resourcesData->resourceCreated(requestId, m_pageAgent->loaderId(loader));
@@ -329,7 +329,7 @@ void InspectorResourceAgent::markResourceAsCached(unsigned long identifier)
m_frontend->requestServedFromCache(IdentifiersFactory::requestId(identifier));
}
-void InspectorResourceAgent::didReceiveResourceResponse(unsigned long identifier, DocumentLoader* loader, const ResourceResponse& response, ResourceLoader* resourceLoader)
+void InspectorResourceAgent::didReceiveResourceResponse(Frame*, unsigned long identifier, DocumentLoader* loader, const ResourceResponse& response, ResourceLoader* resourceLoader)
{
if (!loader)
return;
@@ -353,11 +353,11 @@ void InspectorResourceAgent::didReceiveResourceResponse(unsigned long identifier
}
InspectorPageAgent::ResourceType type = cachedResource ? InspectorPageAgent::cachedResourceType(*cachedResource) : InspectorPageAgent::OtherResource;
- if (m_resourcesData->resourceType(requestId) == InspectorPageAgent::XHRResource)
- type = InspectorPageAgent::XHRResource;
- else if (m_resourcesData->resourceType(requestId) == InspectorPageAgent::ScriptResource)
+ // Workaround for worker scripts that use RawResources for loading.
+ if (m_resourcesData->resourceType(requestId) == InspectorPageAgent::ScriptResource)
type = InspectorPageAgent::ScriptResource;
- else if (equalIgnoringFragmentIdentifier(response.url(), loader->url()) && !loader->isCommitted())
+ // Workaround for background: url() in inline style.
+ if (equalIgnoringFragmentIdentifier(response.url(), loader->url()) && !loader->isCommitted())
type = InspectorPageAgent::DocumentResource;
m_resourcesData->responseReceived(requestId, m_pageAgent->frameId(loader->frame()), response);
@@ -401,10 +401,10 @@ void InspectorResourceAgent::didFinishLoading(unsigned long identifier, Document
m_frontend->loadingFinished(requestId, finishTime);
}
-void InspectorResourceAgent::didReceiveCORSRedirectResponse(unsigned long identifier, DocumentLoader* loader, const ResourceResponse& response, ResourceLoader* resourceLoader)
+void InspectorResourceAgent::didReceiveCORSRedirectResponse(Frame* frame, unsigned long identifier, DocumentLoader* loader, const ResourceResponse& response, ResourceLoader* resourceLoader)
{
// Update the response and finish loading
- didReceiveResourceResponse(identifier, loader, response, resourceLoader);
+ didReceiveResourceResponse(frame, identifier, loader, response, resourceLoader);
didFinishLoading(identifier, loader, 0);
}
@@ -439,7 +439,7 @@ void InspectorResourceAgent::documentThreadableLoaderStartedLoadingForClient(uns
m_resourcesData->setXHRReplayData(requestId, xhrReplayData);
}
-void InspectorResourceAgent::willLoadXHR(ThreadableLoaderClient* client, const String& method, const KURL& url, bool async, PassRefPtr<FormData> formData, const HTTPHeaderMap& headers, bool includeCredentials)
+void InspectorResourceAgent::willLoadXHR(XMLHttpRequest*, ThreadableLoaderClient* client, const AtomicString& method, const KURL& url, bool async, PassRefPtr<FormData> formData, const HTTPHeaderMap& headers, bool includeCredentials)
{
RefPtr<XHRReplayData> xhrReplayData = XHRReplayData::create(method, urlWithoutFragment(url), async, formData, includeCredentials);
HTTPHeaderMap::const_iterator end = headers.end();
@@ -448,21 +448,16 @@ void InspectorResourceAgent::willLoadXHR(ThreadableLoaderClient* client, const S
m_pendingXHRReplayData.set(client, xhrReplayData);
}
-void InspectorResourceAgent::didFailXHRLoading(ThreadableLoaderClient* client)
+void InspectorResourceAgent::didFailXHRLoading(XMLHttpRequest*, ThreadableLoaderClient* client)
{
m_pendingXHRReplayData.remove(client);
}
-void InspectorResourceAgent::didFinishXHRLoading(ThreadableLoaderClient* client, unsigned long identifier, ScriptString sourceString, const String&, const String&, unsigned)
+void InspectorResourceAgent::didFinishXHRLoading(XMLHttpRequest*, ThreadableLoaderClient* client, unsigned long identifier, ScriptString sourceString, const String&, const String&, unsigned)
{
m_pendingXHRReplayData.remove(client);
}
-void InspectorResourceAgent::didReceiveXHRResponse(unsigned long identifier)
-{
- m_resourcesData->setResourceType(IdentifiersFactory::requestId(identifier), InspectorPageAgent::XHRResource);
-}
-
void InspectorResourceAgent::willDestroyResource(Resource* cachedResource)
{
Vector<String> requestIds = m_resourcesData->removeResource(cachedResource);
@@ -610,7 +605,6 @@ void InspectorResourceAgent::disable(ErrorString*)
void InspectorResourceAgent::setUserAgentOverride(ErrorString*, const String& userAgent)
{
m_state->setString(ResourceAgentState::userAgentOverride, userAgent);
- m_overlay->setOverride(InspectorOverlay::UserAgentOverride, !userAgent.isEmpty());
}
void InspectorResourceAgent::setExtraHTTPHeaders(ErrorString*, const RefPtr<JSONObject>& headers)
@@ -786,11 +780,10 @@ bool InspectorResourceAgent::fetchResourceContent(Frame* frame, const KURL& url,
return false;
}
-InspectorResourceAgent::InspectorResourceAgent(InstrumentingAgents* instrumentingAgents, InspectorPageAgent* pageAgent, InspectorClient* client, InspectorCompositeState* state, InspectorOverlay* overlay)
+InspectorResourceAgent::InspectorResourceAgent(InstrumentingAgents* instrumentingAgents, InspectorPageAgent* pageAgent, InspectorClient* client, InspectorCompositeState* state)
: InspectorBaseAgent<InspectorResourceAgent>("Network", instrumentingAgents, state)
, m_pageAgent(pageAgent)
, m_client(client)
- , m_overlay(overlay)
, m_frontend(0)
, m_resourcesData(adoptPtr(new NetworkResourcesData()))
, m_isRecalculatingStyle(false)
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InspectorResourceAgent.h b/chromium/third_party/WebKit/Source/core/inspector/InspectorResourceAgent.h
index 5d5e15cc9c1..e5eb8be79ec 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InspectorResourceAgent.h
+++ b/chromium/third_party/WebKit/Source/core/inspector/InspectorResourceAgent.h
@@ -53,7 +53,6 @@ class Frame;
class HTTPHeaderMap;
class InspectorClient;
class InspectorFrontend;
-class InspectorOverlay;
class InspectorPageAgent;
class InstrumentingAgents;
class JSONObject;
@@ -66,6 +65,7 @@ class ResourceRequest;
class ResourceResponse;
class ThreadableLoaderClient;
class XHRReplayData;
+class XMLHttpRequest;
struct WebSocketFrame;
class WebSocketHandshakeRequest;
@@ -75,9 +75,9 @@ typedef String ErrorString;
class InspectorResourceAgent : public InspectorBaseAgent<InspectorResourceAgent>, public InspectorBackendDispatcher::NetworkCommandHandler {
public:
- static PassOwnPtr<InspectorResourceAgent> create(InstrumentingAgents* instrumentingAgents, InspectorPageAgent* pageAgent, InspectorClient* client, InspectorCompositeState* state, InspectorOverlay* overlay)
+ static PassOwnPtr<InspectorResourceAgent> create(InstrumentingAgents* instrumentingAgents, InspectorPageAgent* pageAgent, InspectorClient* client, InspectorCompositeState* state)
{
- return adoptPtr(new InspectorResourceAgent(instrumentingAgents, pageAgent, client, state, overlay));
+ return adoptPtr(new InspectorResourceAgent(instrumentingAgents, pageAgent, client, state));
}
virtual void setFrontend(InspectorFrontend*);
@@ -91,20 +91,19 @@ public:
// Called from instrumentation.
void willSendRequest(unsigned long identifier, DocumentLoader*, ResourceRequest&, const ResourceResponse& redirectResponse, const FetchInitiatorInfo&);
void markResourceAsCached(unsigned long identifier);
- void didReceiveResourceResponse(unsigned long identifier, DocumentLoader*, const ResourceResponse&, ResourceLoader*);
+ void didReceiveResourceResponse(Frame*, unsigned long identifier, DocumentLoader*, const ResourceResponse&, ResourceLoader*);
void didReceiveData(unsigned long identifier, const char* data, int dataLength, int encodedDataLength);
void didFinishLoading(unsigned long identifier, DocumentLoader*, double monotonicFinishTime);
- void didReceiveCORSRedirectResponse(unsigned long identifier, DocumentLoader*, const ResourceResponse&, ResourceLoader*);
+ void didReceiveCORSRedirectResponse(Frame*, unsigned long identifier, DocumentLoader*, const ResourceResponse&, ResourceLoader*);
void didFailLoading(unsigned long identifier, DocumentLoader*, const ResourceError&);
void didCommitLoad(Frame*, DocumentLoader*);
void scriptImported(unsigned long identifier, const String& sourceString);
void didReceiveScriptResponse(unsigned long identifier);
void documentThreadableLoaderStartedLoadingForClient(unsigned long identifier, ThreadableLoaderClient*);
- void willLoadXHR(ThreadableLoaderClient*, const String& method, const KURL&, bool async, PassRefPtr<FormData> body, const HTTPHeaderMap& headers, bool includeCrendentials);
- void didFailXHRLoading(ThreadableLoaderClient*);
- void didFinishXHRLoading(ThreadableLoaderClient*, unsigned long identifier, ScriptString sourceString, const String&, const String&, unsigned);
- void didReceiveXHRResponse(unsigned long identifier);
+ void willLoadXHR(XMLHttpRequest*, ThreadableLoaderClient*, const AtomicString& method, const KURL&, bool async, PassRefPtr<FormData> body, const HTTPHeaderMap& headers, bool includeCrendentials);
+ void didFailXHRLoading(XMLHttpRequest*, ThreadableLoaderClient*);
+ void didFinishXHRLoading(XMLHttpRequest*, ThreadableLoaderClient*, unsigned long identifier, ScriptString sourceString, const String&, const String&, unsigned);
void willDestroyResource(Resource*);
@@ -152,13 +151,12 @@ public:
bool fetchResourceContent(Frame*, const KURL&, String* content, bool* base64Encoded);
private:
- InspectorResourceAgent(InstrumentingAgents*, InspectorPageAgent*, InspectorClient*, InspectorCompositeState*, InspectorOverlay*);
+ InspectorResourceAgent(InstrumentingAgents*, InspectorPageAgent*, InspectorClient*, InspectorCompositeState*);
void enable();
InspectorPageAgent* m_pageAgent;
InspectorClient* m_client;
- InspectorOverlay* m_overlay;
InspectorFrontend::Network* m_frontend;
String m_userAgentOverride;
OwnPtr<NetworkResourcesData> m_resourcesData;
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InspectorRuntimeAgent.cpp b/chromium/third_party/WebKit/Source/core/inspector/InspectorRuntimeAgent.cpp
index 2568d13057b..fcb3a274f56 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InspectorRuntimeAgent.cpp
+++ b/chromium/third_party/WebKit/Source/core/inspector/InspectorRuntimeAgent.cpp
@@ -33,7 +33,7 @@
#include "core/inspector/InjectedScript.h"
#include "core/inspector/InjectedScriptManager.h"
-#include "core/platform/JSONValues.h"
+#include "platform/JSONValues.h"
#include "bindings/v8/ScriptDebugServer.h"
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InspectorRuntimeAgent.h b/chromium/third_party/WebKit/Source/core/inspector/InspectorRuntimeAgent.h
index 13049062442..f719291b89f 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InspectorRuntimeAgent.h
+++ b/chromium/third_party/WebKit/Source/core/inspector/InspectorRuntimeAgent.h
@@ -51,7 +51,6 @@ class InspectorRuntimeAgent : public InspectorBaseAgent<InspectorRuntimeAgent>,
public:
virtual ~InspectorRuntimeAgent();
- bool enabled() { return m_enabled; }
// Part of the protocol.
virtual void enable(ErrorString*) { m_enabled = true; }
virtual void disable(ErrorString*) { m_enabled = false; }
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InspectorState.h b/chromium/third_party/WebKit/Source/core/inspector/InspectorState.h
index 0679736b33d..d9faea7bdfe 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InspectorState.h
+++ b/chromium/third_party/WebKit/Source/core/inspector/InspectorState.h
@@ -32,7 +32,7 @@
#define InspectorState_h
-#include "core/platform/JSONValues.h"
+#include "platform/JSONValues.h"
#include "wtf/HashMap.h"
#include "wtf/text/WTFString.h"
@@ -46,11 +46,10 @@ public:
virtual void inspectorStateUpdated() = 0;
};
-class InspectorState {
+class InspectorState FINAL {
WTF_MAKE_FAST_ALLOCATED;
public:
InspectorState(InspectorStateUpdateListener*, PassRefPtr<JSONObject>);
- virtual ~InspectorState() {}
void loadFromCookie(const String& inspectorStateCookie);
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InspectorStyleSheet.cpp b/chromium/third_party/WebKit/Source/core/inspector/InspectorStyleSheet.cpp
index 22ceb8d277c..01f60ef60b1 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InspectorStyleSheet.cpp
+++ b/chromium/third_party/WebKit/Source/core/inspector/InspectorStyleSheet.cpp
@@ -30,11 +30,10 @@
#include "SVGNames.h"
#include "bindings/v8/ExceptionState.h"
#include "bindings/v8/ExceptionStatePlaceholder.h"
-#include "core/css/CSSHostRule.h"
+#include "bindings/v8/ScriptRegexp.h"
#include "core/css/CSSKeyframesRule.h"
#include "core/css/CSSMediaRule.h"
#include "core/css/CSSParser.h"
-#include "core/css/CSSPropertySourceData.h"
#include "core/css/CSSRule.h"
#include "core/css/CSSRuleList.h"
#include "core/css/CSSStyleRule.h"
@@ -53,11 +52,8 @@
#include "core/inspector/InspectorResourceAgent.h"
#include "core/page/Page.h"
#include "core/page/PageConsole.h"
-#include "core/platform/JSONValues.h"
-#include "core/platform/text/RegularExpression.h"
#include "wtf/OwnPtr.h"
#include "wtf/PassOwnPtr.h"
-#include "wtf/Vector.h"
#include "wtf/text/StringBuilder.h"
#include "wtf/text/TextPosition.h"
@@ -108,8 +104,6 @@ void ParsedStyleSheet::flattenSourceData(RuleSourceDataList* dataList)
} else if (data->type == CSSRuleSourceData::MEDIA_RULE) {
m_sourceData->append(data);
flattenSourceData(&data->childRules);
- } else if (data->type == CSSRuleSourceData::HOST_RULE) {
- flattenSourceData(&data->childRules);
} else if (data->type == CSSRuleSourceData::SUPPORTS_RULE) {
flattenSourceData(&data->childRules);
}
@@ -216,6 +210,8 @@ inline void StyleSheetHandler::setRuleHeaderEnd(const CharacterType* dataStart,
}
m_currentRuleDataStack.last()->ruleHeaderRange.end = listEndOffset;
+ if (!m_currentRuleDataStack.last()->selectorRanges.isEmpty())
+ m_currentRuleDataStack.last()->selectorRanges.last().end = listEndOffset;
}
void StyleSheetHandler::endRuleHeader(unsigned offset)
@@ -478,16 +474,13 @@ static PassRefPtr<CSSRuleList> asCSSRuleList(CSSRule* rule)
return 0;
if (rule->type() == CSSRule::MEDIA_RULE)
- return static_cast<CSSMediaRule*>(rule)->cssRules();
+ return toCSSMediaRule(rule)->cssRules();
if (rule->type() == CSSRule::KEYFRAMES_RULE)
- return static_cast<CSSKeyframesRule*>(rule)->cssRules();
-
- if (rule->type() == CSSRule::HOST_RULE)
- return static_cast<CSSHostRule*>(rule)->cssRules();
+ return toCSSKeyframesRule(rule)->cssRules();
if (rule->type() == CSSRule::SUPPORTS_RULE)
- return static_cast<CSSSupportsRule*>(rule)->cssRules();
+ return toCSSSupportsRule(rule)->cssRules();
return 0;
}
@@ -506,10 +499,6 @@ InspectorStyle::InspectorStyle(const InspectorCSSId& styleId, PassRefPtr<CSSStyl
ASSERT(m_style);
}
-InspectorStyle::~InspectorStyle()
-{
-}
-
PassRefPtr<TypeBuilder::CSS::CSSStyle> InspectorStyle::buildObjectForStyle() const
{
RefPtr<TypeBuilder::CSS::CSSStyle> result = styleWithProperties();
@@ -549,13 +538,13 @@ PassRefPtr<TypeBuilder::Array<TypeBuilder::CSS::CSSComputedStyleProperty> > Insp
//
// The propertyText (if not empty) is checked to be a valid style declaration (containing at least one property). If not,
// the method returns false (denoting an error).
-bool InspectorStyle::setPropertyText(unsigned index, const String& propertyText, bool overwrite, String* oldText, ExceptionState& es)
+bool InspectorStyle::setPropertyText(unsigned index, const String& propertyText, bool overwrite, String* oldText, ExceptionState& exceptionState)
{
ASSERT(m_parentStyleSheet);
DEFINE_STATIC_LOCAL(String, bogusPropertyName, ("-webkit-boguz-propertee"));
if (!m_parentStyleSheet->ensureParsedDataReady()) {
- es.throwDOMException(NotFoundError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
return false;
}
@@ -570,27 +559,27 @@ bool InspectorStyle::setPropertyText(unsigned index, const String& propertyText,
// At least one property + the bogus property added just above should be present.
if (propertyCount < 2) {
- es.throwDOMException(SyntaxError);
+ exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
return false;
}
// Check for the proper propertyText termination (the parser could at least restore to the PROPERTY_NAME state).
if (propertyData.at(propertyCount - 1).name != bogusPropertyName) {
- es.throwDOMException(SyntaxError);
+ exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
return false;
}
}
RefPtr<CSSRuleSourceData> sourceData = extractSourceData();
if (!sourceData) {
- es.throwDOMException(NotFoundError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
return false;
}
String text;
bool success = styleText(&text);
if (!success) {
- es.throwDOMException(NotFoundError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
return false;
}
@@ -600,7 +589,7 @@ bool InspectorStyle::setPropertyText(unsigned index, const String& propertyText,
InspectorStyleTextEditor editor(&allProperties, text, newLineAndWhitespaceDelimiters());
if (overwrite) {
if (index >= allProperties.size()) {
- es.throwDOMException(IndexSizeError);
+ exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
return false;
}
*oldText = allProperties.at(index).rawText;
@@ -611,31 +600,31 @@ bool InspectorStyle::setPropertyText(unsigned index, const String& propertyText,
return applyStyleText(editor.styleText());
}
-bool InspectorStyle::toggleProperty(unsigned index, bool disable, ExceptionState& es)
+bool InspectorStyle::toggleProperty(unsigned index, bool disable, ExceptionState& exceptionState)
{
ASSERT(m_parentStyleSheet);
if (!m_parentStyleSheet->ensureParsedDataReady()) {
- es.throwDOMException(NoModificationAllowedError);
+ exceptionState.throwUninformativeAndGenericDOMException(NoModificationAllowedError);
return false;
}
RefPtr<CSSRuleSourceData> sourceData = extractSourceData();
if (!sourceData) {
- es.throwDOMException(NotFoundError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
return false;
}
String text;
bool success = styleText(&text);
if (!success) {
- es.throwDOMException(NotFoundError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
return false;
}
Vector<InspectorStyleProperty> allProperties;
populateAllProperties(allProperties);
if (index >= allProperties.size()) {
- es.throwDOMException(IndexSizeError);
+ exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
return false;
}
@@ -992,7 +981,6 @@ InspectorStyleSheet::InspectorStyleSheet(InspectorPageAgent* pageAgent, Inspecto
, m_origin(origin)
, m_documentURL(documentURL)
, m_isRevalidating(false)
- , m_isReparsing(false)
, m_listener(listener)
{
m_parsedStyleSheet = new ParsedStyleSheet();
@@ -1021,10 +1009,8 @@ void InspectorStyleSheet::reparseStyleSheet(const String& text)
m_pageStyleSheet->clearChildRuleCSSOMWrappers();
}
{
- m_isReparsing = true;
CSSStyleSheet::RuleMutationScope mutationScope(m_pageStyleSheet.get());
m_pageStyleSheet->contents()->parseString(text);
- m_isReparsing = false;
}
if (m_listener)
@@ -1033,9 +1019,9 @@ void InspectorStyleSheet::reparseStyleSheet(const String& text)
m_pageStyleSheet->ownerDocument()->styleResolverChanged(RecalcStyleImmediately, FullStyleUpdate);
}
-bool InspectorStyleSheet::setText(const String& text, ExceptionState& es)
+bool InspectorStyleSheet::setText(const String& text, ExceptionState& exceptionState)
{
- if (!checkPageStyleSheet(es))
+ if (!checkPageStyleSheet(exceptionState))
return false;
if (!m_parsedStyleSheet)
return false;
@@ -1046,35 +1032,35 @@ bool InspectorStyleSheet::setText(const String& text, ExceptionState& es)
return true;
}
-String InspectorStyleSheet::ruleSelector(const InspectorCSSId& id, ExceptionState& es)
+String InspectorStyleSheet::ruleSelector(const InspectorCSSId& id, ExceptionState& exceptionState)
{
CSSStyleRule* rule = ruleForId(id);
if (!rule) {
- es.throwDOMException(NotFoundError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
return "";
}
return rule->selectorText();
}
-bool InspectorStyleSheet::setRuleSelector(const InspectorCSSId& id, const String& selector, ExceptionState& es)
+bool InspectorStyleSheet::setRuleSelector(const InspectorCSSId& id, const String& selector, ExceptionState& exceptionState)
{
- if (!checkPageStyleSheet(es))
+ if (!checkPageStyleSheet(exceptionState))
return false;
CSSStyleRule* rule = ruleForId(id);
if (!rule) {
- es.throwDOMException(NotFoundError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
return false;
}
CSSStyleSheet* styleSheet = rule->parentStyleSheet();
if (!styleSheet || !ensureParsedDataReady()) {
- es.throwDOMException(NotFoundError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
return false;
}
rule->setSelectorText(selector);
RefPtr<CSSRuleSourceData> sourceData = ruleSourceDataFor(rule->style());
if (!sourceData) {
- es.throwDOMException(NotFoundError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
return false;
}
@@ -1092,26 +1078,26 @@ static bool checkStyleRuleSelector(Document* document, const String& selector)
return selectorList.isValid();
}
-CSSStyleRule* InspectorStyleSheet::addRule(const String& selector, ExceptionState& es)
+CSSStyleRule* InspectorStyleSheet::addRule(const String& selector, ExceptionState& exceptionState)
{
- if (!checkPageStyleSheet(es))
+ if (!checkPageStyleSheet(exceptionState))
return 0;
if (!checkStyleRuleSelector(m_pageStyleSheet->ownerDocument(), selector)) {
- es.throwDOMException(SyntaxError);
+ exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
return 0;
}
String text;
bool success = getText(&text);
if (!success) {
- es.throwDOMException(NotFoundError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
return 0;
}
StringBuilder styleSheetText;
styleSheetText.append(text);
- m_pageStyleSheet->addRule(selector, "", es);
- if (es.hadException())
+ m_pageStyleSheet->addRule(selector, "", exceptionState);
+ if (exceptionState.hadException())
return 0;
ASSERT(m_pageStyleSheet->length());
unsigned lastRuleIndex = m_pageStyleSheet->length() - 1;
@@ -1123,7 +1109,7 @@ CSSStyleRule* InspectorStyleSheet::addRule(const String& selector, ExceptionStat
// What we just added has to be a CSSStyleRule - we cannot handle other types of rules yet.
// If it is not a style rule, pretend we never touched the stylesheet.
m_pageStyleSheet->deleteRule(lastRuleIndex, ASSERT_NO_EXCEPTION);
- es.throwDOMException(SyntaxError);
+ exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
return 0;
}
@@ -1140,31 +1126,31 @@ CSSStyleRule* InspectorStyleSheet::addRule(const String& selector, ExceptionStat
return styleRule;
}
-bool InspectorStyleSheet::deleteRule(const InspectorCSSId& id, ExceptionState& es)
+bool InspectorStyleSheet::deleteRule(const InspectorCSSId& id, ExceptionState& exceptionState)
{
- if (!checkPageStyleSheet(es))
+ if (!checkPageStyleSheet(exceptionState))
return false;
RefPtr<CSSStyleRule> rule = ruleForId(id);
if (!rule) {
- es.throwDOMException(NotFoundError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
return false;
}
CSSStyleSheet* styleSheet = rule->parentStyleSheet();
if (!styleSheet || !ensureParsedDataReady()) {
- es.throwDOMException(NotFoundError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
return false;
}
RefPtr<CSSRuleSourceData> sourceData = ruleSourceDataFor(rule->style());
if (!sourceData) {
- es.throwDOMException(NotFoundError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
return false;
}
- styleSheet->deleteRule(id.ordinal(), es);
+ styleSheet->deleteRule(id.ordinal(), exceptionState);
// |rule| MAY NOT be addressed after this line!
- if (es.hadException())
+ if (exceptionState.hadException())
return false;
String sheetText = m_parsedStyleSheet->text();
@@ -1228,10 +1214,10 @@ PassRefPtr<TypeBuilder::CSS::CSSStyleSheetHeader> InspectorStyleSheet::buildObje
return result.release();
}
-static PassRefPtr<TypeBuilder::Array<String> > selectorsFromSource(const CSSRuleSourceData* sourceData, const String& sheetText)
+PassRefPtr<TypeBuilder::Array<TypeBuilder::CSS::Selector> > InspectorStyleSheet::selectorsFromSource(const CSSRuleSourceData* sourceData, const String& sheetText) const
{
- RegularExpression comment("/\\*[^]*?\\*/", TextCaseSensitive, MultilineEnabled);
- RefPtr<TypeBuilder::Array<String> > result = TypeBuilder::Array<String>::create();
+ ScriptRegexp comment("/\\*[^]*?\\*/", TextCaseSensitive, MultilineEnabled);
+ RefPtr<TypeBuilder::Array<TypeBuilder::CSS::Selector> > result = TypeBuilder::Array<TypeBuilder::CSS::Selector>::create();
const SelectorRangeList& ranges = sourceData->selectorRanges;
for (size_t i = 0, size = ranges.size(); i < size; ++i) {
const SourceRange& range = ranges.at(i);
@@ -1243,7 +1229,10 @@ static PassRefPtr<TypeBuilder::Array<String> > selectorsFromSource(const CSSRule
while ((offset = comment.match(selector, offset, &matchLength)) >= 0)
selector.replace(offset, matchLength, "");
- result->addItem(selector.stripWhiteSpace());
+ RefPtr<TypeBuilder::CSS::Selector> simpleSelector = TypeBuilder::CSS::Selector::create()
+ .setValue(selector.stripWhiteSpace());
+ simpleSelector->setRange(buildSourceRangeObject(range, lineEndings().get()));
+ result->addItem(simpleSelector.release());
}
return result.release();
}
@@ -1253,7 +1242,7 @@ PassRefPtr<TypeBuilder::CSS::SelectorList> InspectorStyleSheet::buildObjectForSe
RefPtr<CSSRuleSourceData> sourceData;
if (ensureParsedDataReady())
sourceData = ruleSourceDataFor(rule->style());
- RefPtr<TypeBuilder::Array<String> > selectors;
+ RefPtr<TypeBuilder::Array<TypeBuilder::CSS::Selector> > selectors;
// This intentionally does not rely on the source data to avoid catching the trailing comments (before the declaration starting '{').
String selectorText = rule->selectorText();
@@ -1261,17 +1250,15 @@ PassRefPtr<TypeBuilder::CSS::SelectorList> InspectorStyleSheet::buildObjectForSe
if (sourceData)
selectors = selectorsFromSource(sourceData.get(), m_parsedStyleSheet->text());
else {
- selectors = TypeBuilder::Array<String>::create();
+ selectors = TypeBuilder::Array<TypeBuilder::CSS::Selector>::create();
const CSSSelectorList& selectorList = rule->styleRule()->selectorList();
for (const CSSSelector* selector = selectorList.first(); selector; selector = CSSSelectorList::next(selector))
- selectors->addItem(selector->selectorText());
+ selectors->addItem(TypeBuilder::CSS::Selector::create().setValue(selector->selectorText()).release());
}
RefPtr<TypeBuilder::CSS::SelectorList> result = TypeBuilder::CSS::SelectorList::create()
.setSelectors(selectors)
.setText(selectorText)
.release();
- if (sourceData)
- result->setRange(buildSourceRangeObject(sourceData->ruleHeaderRange, lineEndings().get()));
return result.release();
}
@@ -1333,17 +1320,17 @@ PassRefPtr<TypeBuilder::CSS::CSSStyle> InspectorStyleSheet::buildObjectForStyle(
return result.release();
}
-bool InspectorStyleSheet::setStyleText(const InspectorCSSId& id, const String& text, String* oldText, ExceptionState& es)
+bool InspectorStyleSheet::setStyleText(const InspectorCSSId& id, const String& text, String* oldText, ExceptionState& exceptionState)
{
RefPtr<InspectorStyle> inspectorStyle = inspectorStyleForId(id);
if (!inspectorStyle || !inspectorStyle->cssStyle()) {
- es.throwDOMException(NotFoundError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
return false;
}
bool success = inspectorStyle->styleText(oldText);
if (!success) {
- es.throwDOMException(NotFoundError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
return false;
}
@@ -1351,33 +1338,33 @@ bool InspectorStyleSheet::setStyleText(const InspectorCSSId& id, const String& t
if (success)
fireStyleSheetChanged();
else
- es.throwDOMException(SyntaxError);
+ exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
return success;
}
-bool InspectorStyleSheet::setPropertyText(const InspectorCSSId& id, unsigned propertyIndex, const String& text, bool overwrite, String* oldText, ExceptionState& es)
+bool InspectorStyleSheet::setPropertyText(const InspectorCSSId& id, unsigned propertyIndex, const String& text, bool overwrite, String* oldText, ExceptionState& exceptionState)
{
RefPtr<InspectorStyle> inspectorStyle = inspectorStyleForId(id);
if (!inspectorStyle) {
- es.throwDOMException(NotFoundError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
return false;
}
- bool success = inspectorStyle->setPropertyText(propertyIndex, text, overwrite, oldText, es);
+ bool success = inspectorStyle->setPropertyText(propertyIndex, text, overwrite, oldText, exceptionState);
if (success)
fireStyleSheetChanged();
return success;
}
-bool InspectorStyleSheet::toggleProperty(const InspectorCSSId& id, unsigned propertyIndex, bool disable, ExceptionState& es)
+bool InspectorStyleSheet::toggleProperty(const InspectorCSSId& id, unsigned propertyIndex, bool disable, ExceptionState& exceptionState)
{
RefPtr<InspectorStyle> inspectorStyle = inspectorStyleForId(id);
if (!inspectorStyle) {
- es.throwDOMException(NotFoundError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotFoundError);
return false;
}
- bool success = inspectorStyle->toggleProperty(propertyIndex, disable, es);
+ bool success = inspectorStyle->toggleProperty(propertyIndex, disable, exceptionState);
if (success)
fireStyleSheetChanged();
return success;
@@ -1544,10 +1531,10 @@ unsigned InspectorStyleSheet::ruleIndexByRule(const CSSRule* rule) const
return index == kNotFound ? UINT_MAX : static_cast<unsigned>(index);
}
-bool InspectorStyleSheet::checkPageStyleSheet(ExceptionState& es) const
+bool InspectorStyleSheet::checkPageStyleSheet(ExceptionState& exceptionState) const
{
if (!m_pageStyleSheet) {
- es.throwDOMException(NotSupportedError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
return false;
}
return true;
@@ -1613,12 +1600,12 @@ bool InspectorStyleSheet::setStyleText(CSSStyleDeclaration* style, const String&
if (id.isEmpty())
return false;
- TrackExceptionState es;
- style->setCssText(text, es);
- if (!es.hadException())
+ TrackExceptionState exceptionState;
+ style->setCSSText(text, exceptionState);
+ if (!exceptionState.hadException())
m_parsedStyleSheet->setText(patchedStyleSheetText);
- return !es.hadException();
+ return !exceptionState.hadException();
}
bool InspectorStyleSheet::styleSheetTextWithChangedStyle(CSSStyleDeclaration* style, const String& newStyleText, String* result)
@@ -1739,17 +1726,17 @@ bool InspectorStyleSheetForInlineStyle::getText(String* result) const
bool InspectorStyleSheetForInlineStyle::setStyleText(CSSStyleDeclaration* style, const String& text)
{
ASSERT_UNUSED(style, style == inlineStyle());
- TrackExceptionState es;
+ TrackExceptionState exceptionState;
{
InspectorCSSAgent::InlineStyleOverrideScope overrideScope(m_element->ownerDocument());
- m_element->setAttribute("style", text, es);
+ m_element->setAttribute("style", AtomicString(text), exceptionState);
}
m_styleText = text;
m_isStyleTextValid = true;
m_ruleSourceData.clear();
- return !es.hadException();
+ return !exceptionState.hadException();
}
PassOwnPtr<Vector<unsigned> > InspectorStyleSheetForInlineStyle::lineEndings() const
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InspectorStyleSheet.h b/chromium/third_party/WebKit/Source/core/inspector/InspectorStyleSheet.h
index 69d43a9c930..56a0ccafc32 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InspectorStyleSheet.h
+++ b/chromium/third_party/WebKit/Source/core/inspector/InspectorStyleSheet.h
@@ -29,7 +29,7 @@
#include "core/css/CSSPropertySourceData.h"
#include "core/css/CSSStyleDeclaration.h"
#include "core/inspector/InspectorStyleTextEditor.h"
-#include "core/platform/JSONValues.h"
+#include "platform/JSONValues.h"
#include "wtf/HashMap.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefPtr.h"
@@ -129,10 +129,9 @@ struct InspectorStyleProperty {
String rawText;
};
-class InspectorStyle : public RefCounted<InspectorStyle> {
+class InspectorStyle FINAL : public RefCounted<InspectorStyle> {
public:
static PassRefPtr<InspectorStyle> create(const InspectorCSSId& styleId, PassRefPtr<CSSStyleDeclaration> style, InspectorStyleSheet* parentStyleSheet);
- virtual ~InspectorStyle();
CSSStyleDeclaration* cssStyle() const { return m_style.get(); }
PassRefPtr<TypeBuilder::CSS::CSSStyle> buildObjectForStyle() const;
@@ -184,7 +183,6 @@ public:
virtual Document* ownerDocument() const;
bool canBind() const { return m_origin != TypeBuilder::CSS::StyleSheetOrigin::User_agent && m_origin != TypeBuilder::CSS::StyleSheetOrigin::User; }
CSSStyleSheet* pageStyleSheet() const { return m_pageStyleSheet.get(); }
- bool isReparsing() const { return m_isReparsing; }
void reparseStyleSheet(const String&);
bool setText(const String&, ExceptionState&);
String ruleSelector(const InspectorCSSId&, ExceptionState&);
@@ -237,6 +235,7 @@ private:
bool originalStyleSheetText(String* result) const;
bool resourceStyleSheetText(String* result) const;
bool inlineStyleSheetText(String* result) const;
+ PassRefPtr<TypeBuilder::Array<TypeBuilder::CSS::Selector> > selectorsFromSource(const CSSRuleSourceData*, const String&) const;
PassRefPtr<TypeBuilder::CSS::SelectorList> buildObjectForSelectorList(CSSStyleRule*);
String url() const;
bool hasSourceURL() const;
@@ -249,7 +248,6 @@ private:
TypeBuilder::CSS::StyleSheetOrigin::Enum m_origin;
String m_documentURL;
bool m_isRevalidating;
- bool m_isReparsing;
ParsedStyleSheet* m_parsedStyleSheet;
mutable CSSRuleVector m_flatRules;
Listener* m_listener;
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InspectorTimelineAgent.cpp b/chromium/third_party/WebKit/Source/core/inspector/InspectorTimelineAgent.cpp
index c2e19b0ff67..2e73ed1e3c3 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InspectorTimelineAgent.cpp
+++ b/chromium/third_party/WebKit/Source/core/inspector/InspectorTimelineAgent.cpp
@@ -31,30 +31,32 @@
#include "config.h"
#include "core/inspector/InspectorTimelineAgent.h"
-#include "InspectorFrontend.h"
-#include "core/dom/Event.h"
+#include "core/events/Event.h"
+#include "core/frame/DOMWindow.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
#include "core/inspector/IdentifiersFactory.h"
+#include "core/inspector/InspectorClient.h"
#include "core/inspector/InspectorCounters.h"
#include "core/inspector/InspectorDOMAgent.h"
#include "core/inspector/InspectorInstrumentation.h"
#include "core/inspector/InspectorMemoryAgent.h"
+#include "core/inspector/InspectorOverlay.h"
#include "core/inspector/InspectorPageAgent.h"
#include "core/inspector/InspectorState.h"
#include "core/inspector/InstrumentingAgents.h"
#include "core/inspector/ScriptCallStack.h"
#include "core/inspector/TimelineRecordFactory.h"
-#include "core/inspector/TimelineTraceEventProcessor.h"
+#include "core/inspector/TraceEventDispatcher.h"
#include "core/loader/DocumentLoader.h"
-#include "core/page/DOMWindow.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameView.h"
#include "core/page/PageConsole.h"
-#include "core/platform/MemoryUsageSupport.h"
-#include "core/platform/chromium/TraceEvent.h"
-#include "core/platform/network/ResourceRequest.h"
#include "core/rendering/RenderObject.h"
#include "core/rendering/RenderView.h"
#include "core/xml/XMLHttpRequest.h"
+#include "platform/TraceEvent.h"
+#include "platform/graphics/DeferredImageDecoder.h"
+#include "platform/graphics/GraphicsLayer.h"
+#include "platform/network/ResourceRequest.h"
#include "wtf/CurrentTime.h"
@@ -66,7 +68,7 @@ static const char started[] = "started";
static const char startedFromProtocol[] = "startedFromProtocol";
static const char timelineMaxCallStackDepth[] = "timelineMaxCallStackDepth";
static const char includeDomCounters[] = "includeDomCounters";
-static const char includeNativeMemoryStatistics[] = "includeNativeMemoryStatistics";
+static const char includeGPUEvents[] = "includeGPUEvents";
static const char bufferEvents[] = "bufferEvents";
}
@@ -75,11 +77,11 @@ namespace TimelineRecordType {
static const char Program[] = "Program";
static const char EventDispatch[] = "EventDispatch";
-static const char BeginFrame[] = "BeginFrame";
static const char ScheduleStyleRecalculation[] = "ScheduleStyleRecalculation";
static const char RecalculateStyles[] = "RecalculateStyles";
static const char InvalidateLayout[] = "InvalidateLayout";
static const char Layout[] = "Layout";
+static const char AutosizeText[] = "AutosizeText";
static const char Paint[] = "Paint";
static const char ScrollLayer[] = "ScrollLayer";
static const char ResizeImage[] = "ResizeImage";
@@ -95,6 +97,7 @@ static const char EvaluateScript[] = "EvaluateScript";
static const char MarkLoad[] = "MarkLoad";
static const char MarkDOMContent[] = "MarkDOMContent";
+static const char MarkFirstPaint[] = "MarkFirstPaint";
static const char TimeStamp[] = "TimeStamp";
static const char Time[] = "Time";
@@ -122,7 +125,10 @@ static const char WebSocketReceiveHandshakeResponse[] = "WebSocketReceiveHandsha
static const char WebSocketDestroy[] = "WebSocketDestroy";
// Event names visible to other modules.
+const char ActivateLayerTree[] = "ActivateLayerTree";
+const char BeginFrame[] = "BeginFrame";
const char DecodeImage[] = "DecodeImage";
+const char GPUTask[] = "GPUTask";
const char Rasterize[] = "Rasterize";
const char PaintSetup[] = "PaintSetup";
}
@@ -131,7 +137,84 @@ namespace {
const char BackendNodeIdGroup[] = "timeline";
}
-static Frame* frameForScriptExecutionContext(ScriptExecutionContext* context)
+struct TimelineRecordEntry {
+ TimelineRecordEntry(PassRefPtr<JSONObject> record, PassRefPtr<JSONObject> data, PassRefPtr<JSONArray> children, const String& type, size_t usedHeapSizeAtStart)
+ : record(record), data(data), children(children), type(type), usedHeapSizeAtStart(usedHeapSizeAtStart)
+ {
+ }
+ RefPtr<JSONObject> record;
+ RefPtr<JSONObject> data;
+ RefPtr<JSONArray> children;
+ String type;
+ size_t usedHeapSizeAtStart;
+};
+
+class TimelineRecordStack {
+private:
+ struct Entry {
+ Entry(PassRefPtr<JSONObject> record)
+ : record(record)
+ , children(JSONArray::create())
+ {
+ }
+
+ RefPtr<JSONObject> record;
+ RefPtr<JSONArray> children;
+ };
+
+public:
+ TimelineRecordStack() : m_timelineAgent(0) { }
+ TimelineRecordStack(InspectorTimelineAgent*);
+
+ void addScopedRecord(PassRefPtr<JSONObject> record);
+ void closeScopedRecord(double endTime);
+ void addInstantRecord(PassRefPtr<JSONObject> record);
+
+#ifndef NDEBUG
+ bool isOpenRecordOfType(const String& type);
+#endif
+
+private:
+ void send(PassRefPtr<JSONObject>);
+
+ InspectorTimelineAgent* m_timelineAgent;
+ Vector<Entry> m_stack;
+};
+
+struct TimelineThreadState {
+ TimelineThreadState() { }
+
+ TimelineThreadState(InspectorTimelineAgent* timelineAgent)
+ : recordStack(timelineAgent)
+ , inKnownLayerTask(false)
+ , decodedPixelRefId(0)
+ {
+ }
+
+ TimelineRecordStack recordStack;
+ bool inKnownLayerTask;
+ unsigned long long decodedPixelRefId;
+};
+
+struct TimelineGCEvent {
+ TimelineGCEvent(double startTime, double endTime, size_t collectedBytes)
+ : startTime(startTime), endTime(endTime), collectedBytes(collectedBytes)
+ {
+ }
+ double startTime;
+ double endTime;
+ size_t collectedBytes;
+};
+
+struct TimelineImageInfo {
+ int backendNodeId;
+ String url;
+
+ TimelineImageInfo() : backendNodeId(0) { }
+ TimelineImageInfo(int backendNodeId, String url) : backendNodeId(backendNodeId), url(url) { }
+};
+
+static Frame* frameForExecutionContext(ExecutionContext* context)
{
Frame* frame = 0;
if (context->isDocument())
@@ -148,7 +231,7 @@ static bool eventHasListeners(const AtomicString& eventType, DOMWindow* window,
return true;
for (size_t i = 0; i < eventPath.size(); i++) {
- if (eventPath[i]->node()->hasEventListeners(eventType))
+ if (eventPath[i].node()->hasEventListeners(eventType))
return true;
}
@@ -177,7 +260,7 @@ void InspectorTimelineAgent::pushGCEventRecords()
void InspectorTimelineAgent::didGC(double startTime, double endTime, size_t collectedBytesCount)
{
- m_gcEvents.append(GCEvent(startTime, endTime, collectedBytesCount));
+ m_gcEvents.append(TimelineGCEvent(startTime, endTime, collectedBytesCount));
}
InspectorTimelineAgent::~InspectorTimelineAgent()
@@ -224,7 +307,7 @@ void InspectorTimelineAgent::disable(ErrorString*)
m_state->setBoolean(TimelineAgentState::enabled, false);
}
-void InspectorTimelineAgent::start(ErrorString* errorString, const int* maxCallStackDepth, const bool* bufferEvents, const bool* includeDomCounters, const bool* includeNativeMemoryStatistics)
+void InspectorTimelineAgent::start(ErrorString* errorString, const int* maxCallStackDepth, const bool* bufferEvents, const bool* includeDomCounters, const bool* includeGPUEvents)
{
if (!m_frontend)
return;
@@ -246,7 +329,7 @@ void InspectorTimelineAgent::start(ErrorString* errorString, const int* maxCallS
m_state->setLong(TimelineAgentState::timelineMaxCallStackDepth, m_maxCallStackDepth);
m_state->setBoolean(TimelineAgentState::includeDomCounters, includeDomCounters && *includeDomCounters);
- m_state->setBoolean(TimelineAgentState::includeNativeMemoryStatistics, includeNativeMemoryStatistics && *includeNativeMemoryStatistics);
+ m_state->setBoolean(TimelineAgentState::includeGPUEvents, includeGPUEvents && *includeGPUEvents);
m_state->setBoolean(TimelineAgentState::bufferEvents, bufferEvents && *bufferEvents);
innerStart();
@@ -261,12 +344,33 @@ bool InspectorTimelineAgent::isStarted()
void InspectorTimelineAgent::innerStart()
{
+ if (m_overlay)
+ m_overlay->startedRecordingProfile();
m_state->setBoolean(TimelineAgentState::started, true);
m_timeConverter.reset();
m_instrumentingAgents->setInspectorTimelineAgent(this);
ScriptGCEvent::addEventListener(this);
- if (m_client && m_pageAgent)
- m_traceEventProcessor = adoptRef(new TimelineTraceEventProcessor(m_weakFactory.createWeakPtr(), m_client));
+ if (m_client) {
+ TraceEventDispatcher* dispatcher = TraceEventDispatcher::instance();
+ dispatcher->addListener(InstrumentationEvents::BeginFrame, TRACE_EVENT_PHASE_INSTANT, this, &InspectorTimelineAgent::onBeginImplSideFrame, m_client);
+ dispatcher->addListener(InstrumentationEvents::PaintSetup, TRACE_EVENT_PHASE_BEGIN, this, &InspectorTimelineAgent::onPaintSetupBegin, m_client);
+ dispatcher->addListener(InstrumentationEvents::PaintSetup, TRACE_EVENT_PHASE_END, this, &InspectorTimelineAgent::onPaintSetupEnd, m_client);
+ dispatcher->addListener(InstrumentationEvents::RasterTask, TRACE_EVENT_PHASE_BEGIN, this, &InspectorTimelineAgent::onRasterTaskBegin, m_client);
+ dispatcher->addListener(InstrumentationEvents::RasterTask, TRACE_EVENT_PHASE_END, this, &InspectorTimelineAgent::onRasterTaskEnd, m_client);
+ dispatcher->addListener(InstrumentationEvents::Layer, TRACE_EVENT_PHASE_DELETE_OBJECT, this, &InspectorTimelineAgent::onLayerDeleted, m_client);
+ dispatcher->addListener(InstrumentationEvents::ActivateLayerTree, TRACE_EVENT_PHASE_INSTANT, this, &InspectorTimelineAgent::onActivateLayerTree, m_client);
+ dispatcher->addListener(PlatformInstrumentation::ImageDecodeEvent, TRACE_EVENT_PHASE_BEGIN, this, &InspectorTimelineAgent::onImageDecodeBegin, m_client);
+ dispatcher->addListener(PlatformInstrumentation::ImageDecodeEvent, TRACE_EVENT_PHASE_END, this, &InspectorTimelineAgent::onImageDecodeEnd, m_client);
+ dispatcher->addListener(PlatformInstrumentation::DrawLazyPixelRefEvent, TRACE_EVENT_PHASE_INSTANT, this, &InspectorTimelineAgent::onDrawLazyPixelRef, m_client);
+ dispatcher->addListener(PlatformInstrumentation::DecodeLazyPixelRefEvent, TRACE_EVENT_PHASE_BEGIN, this, &InspectorTimelineAgent::onDecodeLazyPixelRefBegin, m_client);
+ dispatcher->addListener(PlatformInstrumentation::DecodeLazyPixelRefEvent, TRACE_EVENT_PHASE_END, this, &InspectorTimelineAgent::onDecodeLazyPixelRefEnd, m_client);
+ dispatcher->addListener(PlatformInstrumentation::LazyPixelRef, TRACE_EVENT_PHASE_DELETE_OBJECT, this, &InspectorTimelineAgent::onLazyPixelRefDeleted, m_client);
+
+ if (m_state->getBoolean(TimelineAgentState::includeGPUEvents)) {
+ m_pendingGPURecord.clear();
+ m_client->startGPUEventsRecording();
+ }
+ }
}
void InspectorTimelineAgent::stop(ErrorString* errorString, RefPtr<TypeBuilder::Array<TypeBuilder::Timeline::TimelineEvent> >& events)
@@ -287,16 +391,23 @@ void InspectorTimelineAgent::innerStop(bool fromConsole)
{
m_state->setBoolean(TimelineAgentState::started, false);
- if (m_traceEventProcessor) {
- m_traceEventProcessor->shutdown();
- m_traceEventProcessor.clear();
+ if (m_client) {
+ TraceEventDispatcher::instance()->removeAllListeners(this, m_client);
+ if (m_state->getBoolean(TimelineAgentState::includeGPUEvents))
+ m_client->stopGPUEventsRecording();
}
- m_weakFactory.revokeAll();
m_instrumentingAgents->setInspectorTimelineAgent(0);
ScriptGCEvent::removeEventListener(this);
clearRecordStack();
+ m_threadStates.clear();
m_gcEvents.clear();
+ m_gpuTask.clear();
+ m_layerToNodeMap.clear();
+ m_pixelRefToImageInfo.clear();
+ m_imageBeingPainted = 0;
+ m_paintSetupStart = 0;
+ m_mayEmitFirstPaint = false;
for (size_t i = 0; i < m_consoleTimelines.size(); ++i) {
String message = String::format("Timeline '%s' terminated.", m_consoleTimelines[i].utf8().data());
@@ -305,12 +416,15 @@ void InspectorTimelineAgent::innerStop(bool fromConsole)
m_consoleTimelines.clear();
m_frontend->stopped(&fromConsole);
+ if (m_overlay)
+ m_overlay->finishedRecordingProfile();
}
-void InspectorTimelineAgent::didBeginFrame()
+void InspectorTimelineAgent::didBeginFrame(int frameId)
{
- TRACE_EVENT_INSTANT0("webkit", InstrumentationEvents::BeginFrame);
+ TraceEventDispatcher::instance()->processBackgroundEvents();
m_pendingFrameRecord = TimelineRecordFactory::createGenericRecord(timestamp(), 0, TimelineRecordType::BeginFrame);
+ m_pendingFrameRecord->setObject("data", TimelineRecordFactory::createFrameData(frameId));
}
void InspectorTimelineAgent::didCancelFrame()
@@ -318,9 +432,9 @@ void InspectorTimelineAgent::didCancelFrame()
m_pendingFrameRecord.clear();
}
-bool InspectorTimelineAgent::willCallFunction(ScriptExecutionContext* context, const String& scriptName, int scriptLine)
+bool InspectorTimelineAgent::willCallFunction(ExecutionContext* context, const String& scriptName, int scriptLine)
{
- pushCurrentRecord(TimelineRecordFactory::createFunctionCallData(scriptName, scriptLine), TimelineRecordType::FunctionCall, true, frameForScriptExecutionContext(context));
+ pushCurrentRecord(TimelineRecordFactory::createFunctionCallData(scriptName, scriptLine), TimelineRecordType::FunctionCall, true, frameForExecutionContext(context));
return true;
}
@@ -389,12 +503,27 @@ void InspectorTimelineAgent::didLayout(RenderObject* root)
Vector<FloatQuad> quads;
root->absoluteQuads(quads);
if (quads.size() >= 1)
- TimelineRecordFactory::appendLayoutRoot(entry.data.get(), quads[0], idForNode(root->generatingNode()));
+ TimelineRecordFactory::appendLayoutRoot(entry.data.get(), quads[0], nodeId(root));
else
ASSERT_NOT_REACHED();
didCompleteCurrentRecord(TimelineRecordType::Layout);
}
+void InspectorTimelineAgent::willAutosizeText(RenderObject* renderer)
+{
+ pushCurrentRecord(TimelineRecordFactory::createNodeData(nodeId(renderer)), TimelineRecordType::AutosizeText, false, renderer->frame());
+}
+
+void InspectorTimelineAgent::didAutosizeText(RenderObject* renderer)
+{
+ if (renderer->needsLayout()) {
+ TimelineRecordEntry& entry = m_recordStack.last();
+ ASSERT(entry.type == TimelineRecordType::AutosizeText);
+ entry.data->setBoolean("needsRelayout", true);
+ }
+ didCompleteCurrentRecord(TimelineRecordType::AutosizeText);
+}
+
void InspectorTimelineAgent::didScheduleStyleRecalculation(Document* document)
{
appendRecord(JSONObject::create(), TimelineRecordType::ScheduleStyleRecalculation, true, document->frame());
@@ -423,24 +552,41 @@ void InspectorTimelineAgent::didRecalculateStyleForElement()
++m_styleRecalcElementCounter;
}
-void InspectorTimelineAgent::willPaint(RenderObject* renderer)
+void InspectorTimelineAgent::willPaint(RenderObject* renderer, const GraphicsLayer* graphicsLayer)
{
Frame* frame = renderer->frame();
- TRACE_EVENT_INSTANT2("instrumentation", InstrumentationEvents::Paint,
- InstrumentationEventArguments::PageId, reinterpret_cast<unsigned long long>(frame->page()),
- InstrumentationEventArguments::NodeId, idForNode(renderer->generatingNode()));
+ TraceEventDispatcher::instance()->processBackgroundEvents();
+ double paintSetupStart = m_paintSetupStart;
+ m_paintSetupStart = 0;
+ if (graphicsLayer) {
+ int layerIdentifier = graphicsLayer->platformLayer()->id();
+ int nodeIdentifier = nodeId(renderer);
+ ASSERT(layerIdentifier && nodeIdentifier);
+ m_layerToNodeMap.set(layerIdentifier, nodeIdentifier);
+ if (paintSetupStart) {
+ RefPtr<JSONObject> paintSetupRecord = TimelineRecordFactory::createGenericRecord(paintSetupStart, 0, TimelineRecordType::PaintSetup);
+ paintSetupRecord->setNumber("endTime", m_paintSetupEnd);
+ paintSetupRecord->setObject("data", TimelineRecordFactory::createLayerData(nodeIdentifier));
+ addRecordToTimeline(paintSetupRecord);
+ }
+ }
pushCurrentRecord(JSONObject::create(), TimelineRecordType::Paint, true, frame, true);
}
-void InspectorTimelineAgent::didPaint(RenderObject* renderer, GraphicsContext*, const LayoutRect& clipRect)
+void InspectorTimelineAgent::didPaint(RenderObject* renderer, const GraphicsLayer* graphicsLayer, GraphicsContext*, const LayoutRect& clipRect)
{
TimelineRecordEntry& entry = m_recordStack.last();
ASSERT(entry.type == TimelineRecordType::Paint);
FloatQuad quad;
localToPageQuad(*renderer, clipRect, &quad);
- entry.data = TimelineRecordFactory::createPaintData(quad, idForNode(renderer->generatingNode()));
+ int graphicsLayerId = graphicsLayer ? graphicsLayer->platformLayer()->id() : 0;
+ entry.data = TimelineRecordFactory::createPaintData(quad, nodeId(renderer), graphicsLayerId);
didCompleteCurrentRecord(TimelineRecordType::Paint);
+ if (m_mayEmitFirstPaint && !graphicsLayer) {
+ m_mayEmitFirstPaint = false;
+ appendRecord(JSONObject::create(), TimelineRecordType::MarkFirstPaint, false, 0);
+ }
}
void InspectorTimelineAgent::willPaintImage(RenderImage* renderImage)
@@ -456,7 +602,7 @@ void InspectorTimelineAgent::didPaintImage()
void InspectorTimelineAgent::willScrollLayer(RenderObject* renderer)
{
- pushCurrentRecord(TimelineRecordFactory::createLayerData(idForNode(renderer->generatingNode())), TimelineRecordType::ScrollLayer, false, renderer->frame());
+ pushCurrentRecord(TimelineRecordFactory::createLayerData(nodeId(renderer)), TimelineRecordType::ScrollLayer, false, renderer->frame());
}
void InspectorTimelineAgent::didScrollLayer()
@@ -498,6 +644,10 @@ void InspectorTimelineAgent::willComposite()
void InspectorTimelineAgent::didComposite()
{
didCompleteCurrentRecord(TimelineRecordType::CompositeLayers);
+ if (m_mayEmitFirstPaint) {
+ m_mayEmitFirstPaint = false;
+ appendRecord(JSONObject::create(), TimelineRecordType::MarkFirstPaint, false, 0);
+ }
}
bool InspectorTimelineAgent::willWriteHTML(Document* document, unsigned startLine)
@@ -515,19 +665,19 @@ void InspectorTimelineAgent::didWriteHTML(unsigned endLine)
}
}
-void InspectorTimelineAgent::didInstallTimer(ScriptExecutionContext* context, int timerId, int timeout, bool singleShot)
+void InspectorTimelineAgent::didInstallTimer(ExecutionContext* context, int timerId, int timeout, bool singleShot)
{
- appendRecord(TimelineRecordFactory::createTimerInstallData(timerId, timeout, singleShot), TimelineRecordType::TimerInstall, true, frameForScriptExecutionContext(context));
+ appendRecord(TimelineRecordFactory::createTimerInstallData(timerId, timeout, singleShot), TimelineRecordType::TimerInstall, true, frameForExecutionContext(context));
}
-void InspectorTimelineAgent::didRemoveTimer(ScriptExecutionContext* context, int timerId)
+void InspectorTimelineAgent::didRemoveTimer(ExecutionContext* context, int timerId)
{
- appendRecord(TimelineRecordFactory::createGenericTimerData(timerId), TimelineRecordType::TimerRemove, true, frameForScriptExecutionContext(context));
+ appendRecord(TimelineRecordFactory::createGenericTimerData(timerId), TimelineRecordType::TimerRemove, true, frameForExecutionContext(context));
}
-bool InspectorTimelineAgent::willFireTimer(ScriptExecutionContext* context, int timerId)
+bool InspectorTimelineAgent::willFireTimer(ExecutionContext* context, int timerId)
{
- pushCurrentRecord(TimelineRecordFactory::createGenericTimerData(timerId), TimelineRecordType::TimerFire, false, frameForScriptExecutionContext(context));
+ pushCurrentRecord(TimelineRecordFactory::createGenericTimerData(timerId), TimelineRecordType::TimerFire, false, frameForExecutionContext(context));
return true;
}
@@ -536,11 +686,11 @@ void InspectorTimelineAgent::didFireTimer()
didCompleteCurrentRecord(TimelineRecordType::TimerFire);
}
-bool InspectorTimelineAgent::willDispatchXHRReadyStateChangeEvent(ScriptExecutionContext* context, XMLHttpRequest* request)
+bool InspectorTimelineAgent::willDispatchXHRReadyStateChangeEvent(ExecutionContext* context, XMLHttpRequest* request)
{
- if (!request->hasEventListeners(eventNames().readystatechangeEvent))
+ if (!request->hasEventListeners(EventTypeNames::readystatechange))
return false;
- pushCurrentRecord(TimelineRecordFactory::createXHRReadyStateChangeData(request->url().string(), request->readyState()), TimelineRecordType::XHRReadyStateChange, false, frameForScriptExecutionContext(context));
+ pushCurrentRecord(TimelineRecordFactory::createXHRReadyStateChangeData(request->url().string(), request->readyState()), TimelineRecordType::XHRReadyStateChange, false, frameForExecutionContext(context));
return true;
}
@@ -549,11 +699,11 @@ void InspectorTimelineAgent::didDispatchXHRReadyStateChangeEvent()
didCompleteCurrentRecord(TimelineRecordType::XHRReadyStateChange);
}
-bool InspectorTimelineAgent::willDispatchXHRLoadEvent(ScriptExecutionContext* context, XMLHttpRequest* request)
+bool InspectorTimelineAgent::willDispatchXHRLoadEvent(ExecutionContext* context, XMLHttpRequest* request)
{
- if (!request->hasEventListeners(eventNames().loadEvent))
+ if (!request->hasEventListeners(EventTypeNames::load))
return false;
- pushCurrentRecord(TimelineRecordFactory::createXHRLoadData(request->url().string()), TimelineRecordType::XHRLoad, true, frameForScriptExecutionContext(context));
+ pushCurrentRecord(TimelineRecordFactory::createXHRLoadData(request->url().string()), TimelineRecordType::XHRLoad, true, frameForExecutionContext(context));
return true;
}
@@ -596,16 +746,10 @@ void InspectorTimelineAgent::didReceiveResourceData()
didCompleteCurrentRecord(TimelineRecordType::ResourceReceivedData);
}
-bool InspectorTimelineAgent::willReceiveResourceResponse(Frame* frame, unsigned long identifier, const ResourceResponse& response)
+void InspectorTimelineAgent::didReceiveResourceResponse(Frame* frame, unsigned long identifier, DocumentLoader* loader, const ResourceResponse& response, ResourceLoader* resourceLoader)
{
String requestId = IdentifiersFactory::requestId(identifier);
- pushCurrentRecord(TimelineRecordFactory::createResourceReceiveResponseData(requestId, response), TimelineRecordType::ResourceReceiveResponse, false, frame);
- return true;
-}
-
-void InspectorTimelineAgent::didReceiveResourceResponse(unsigned long identifier, DocumentLoader* loader, const ResourceResponse& response, ResourceLoader* resourceLoader)
-{
- didCompleteCurrentRecord(TimelineRecordType::ResourceReceiveResponse);
+ appendRecord(TimelineRecordFactory::createResourceReceiveResponseData(requestId, response), TimelineRecordType::ResourceReceiveResponse, false, frame);
}
void InspectorTimelineAgent::didFinishLoadingResource(unsigned long identifier, bool didFail, double finishTime, Frame* frame)
@@ -628,22 +772,22 @@ void InspectorTimelineAgent::didFailLoading(unsigned long identifier, DocumentLo
didFinishLoadingResource(identifier, true, 0, loader->frame());
}
-void InspectorTimelineAgent::consoleTimeStamp(ScriptExecutionContext* context, const String& title)
+void InspectorTimelineAgent::consoleTimeStamp(ExecutionContext* context, const String& title)
{
- appendRecord(TimelineRecordFactory::createTimeStampData(title), TimelineRecordType::TimeStamp, true, frameForScriptExecutionContext(context));
+ appendRecord(TimelineRecordFactory::createTimeStampData(title), TimelineRecordType::TimeStamp, true, frameForExecutionContext(context));
}
-void InspectorTimelineAgent::consoleTime(ScriptExecutionContext* context, const String& message)
+void InspectorTimelineAgent::consoleTime(ExecutionContext* context, const String& message)
{
- appendRecord(TimelineRecordFactory::createTimeStampData(message), TimelineRecordType::Time, true, frameForScriptExecutionContext(context));
+ appendRecord(TimelineRecordFactory::createTimeStampData(message), TimelineRecordType::Time, true, frameForExecutionContext(context));
}
-void InspectorTimelineAgent::consoleTimeEnd(ScriptExecutionContext* context, const String& message, ScriptState*)
+void InspectorTimelineAgent::consoleTimeEnd(ExecutionContext* context, const String& message, ScriptState*)
{
- appendRecord(TimelineRecordFactory::createTimeStampData(message), TimelineRecordType::TimeEnd, true, frameForScriptExecutionContext(context));
+ appendRecord(TimelineRecordFactory::createTimeStampData(message), TimelineRecordType::TimeEnd, true, frameForExecutionContext(context));
}
-void InspectorTimelineAgent::consoleTimeline(ScriptExecutionContext* context, const String& title, ScriptState* state)
+void InspectorTimelineAgent::consoleTimeline(ExecutionContext* context, const String& title, ScriptState* state)
{
if (!m_state->getBoolean(TimelineAgentState::enabled))
return;
@@ -656,10 +800,10 @@ void InspectorTimelineAgent::consoleTimeline(ScriptExecutionContext* context, co
bool fromConsole = true;
m_frontend->started(&fromConsole);
}
- appendRecord(TimelineRecordFactory::createTimeStampData(message), TimelineRecordType::TimeStamp, true, frameForScriptExecutionContext(context));
+ appendRecord(TimelineRecordFactory::createTimeStampData(message), TimelineRecordType::TimeStamp, true, frameForExecutionContext(context));
}
-void InspectorTimelineAgent::consoleTimelineEnd(ScriptExecutionContext* context, const String& title, ScriptState* state)
+void InspectorTimelineAgent::consoleTimelineEnd(ExecutionContext* context, const String& title, ScriptState* state)
{
if (!m_state->getBoolean(TimelineAgentState::enabled))
return;
@@ -672,10 +816,12 @@ void InspectorTimelineAgent::consoleTimelineEnd(ScriptExecutionContext* context,
}
String message = String::format("Timeline '%s' finished.", title.utf8().data());
- appendRecord(TimelineRecordFactory::createTimeStampData(message), TimelineRecordType::TimeStamp, true, frameForScriptExecutionContext(context));
+ appendRecord(TimelineRecordFactory::createTimeStampData(message), TimelineRecordType::TimeStamp, true, frameForExecutionContext(context));
m_consoleTimelines.remove(index);
- if (!m_consoleTimelines.size() && isStarted() && !m_state->getBoolean(TimelineAgentState::startedFromProtocol))
+ if (!m_consoleTimelines.size() && isStarted() && !m_state->getBoolean(TimelineAgentState::startedFromProtocol)) {
+ unwindRecordStack();
innerStop(true);
+ }
page()->console().addMessage(ConsoleAPIMessageSource, DebugMessageLevel, message, String(), 0, 0, 0, state);
}
@@ -683,6 +829,8 @@ void InspectorTimelineAgent::domContentLoadedEventFired(Frame* frame)
{
bool isMainFrame = frame && m_pageAgent && (frame == m_pageAgent->mainFrame());
appendRecord(TimelineRecordFactory::createMarkData(isMainFrame), TimelineRecordType::MarkDOMContent, false, frame);
+ if (isMainFrame)
+ m_mayEmitFirstPaint = true;
}
void InspectorTimelineAgent::loadEventFired(Frame* frame)
@@ -747,6 +895,140 @@ void InspectorTimelineAgent::didCloseWebSocket(Document* document, unsigned long
appendRecord(TimelineRecordFactory::createGenericWebSocketData(identifier), TimelineRecordType::WebSocketDestroy, true, document->frame());
}
+void InspectorTimelineAgent::onBeginImplSideFrame(const TraceEventDispatcher::TraceEvent& event)
+{
+ unsigned long long layerTreeId = event.asUInt(InstrumentationEventArguments::LayerTreeId);
+ if (layerTreeId != m_layerTreeId)
+ return;
+ TimelineThreadState& state = threadState(event.threadIdentifier());
+ state.recordStack.addInstantRecord(createRecordForEvent(event, TimelineRecordType::BeginFrame));
+}
+
+void InspectorTimelineAgent::onPaintSetupBegin(const TraceEventDispatcher::TraceEvent& event)
+{
+ ASSERT(!m_paintSetupStart);
+ m_paintSetupStart = m_timeConverter.fromMonotonicallyIncreasingTime(event.timestamp());
+}
+
+void InspectorTimelineAgent::onPaintSetupEnd(const TraceEventDispatcher::TraceEvent& event)
+{
+ ASSERT(m_paintSetupStart);
+ m_paintSetupEnd = m_timeConverter.fromMonotonicallyIncreasingTime(event.timestamp());
+}
+
+void InspectorTimelineAgent::onRasterTaskBegin(const TraceEventDispatcher::TraceEvent& event)
+{
+ TimelineThreadState& state = threadState(event.threadIdentifier());
+ unsigned long long layerId = event.asUInt(InstrumentationEventArguments::LayerId);
+ ASSERT(layerId);
+ if (!m_layerToNodeMap.contains(layerId))
+ return;
+ ASSERT(!state.inKnownLayerTask);
+ state.inKnownLayerTask = true;
+ double timeestamp = m_timeConverter.fromMonotonicallyIncreasingTime(event.timestamp());
+ RefPtr<JSONObject> data = TimelineRecordFactory::createLayerData(m_layerToNodeMap.get(layerId));
+ RefPtr<JSONObject> record = TimelineRecordFactory::createBackgroundRecord(timeestamp, String::number(event.threadIdentifier()), TimelineRecordType::Rasterize, data);
+ state.recordStack.addScopedRecord(record);
+}
+
+void InspectorTimelineAgent::onRasterTaskEnd(const TraceEventDispatcher::TraceEvent& event)
+{
+ TimelineThreadState& state = threadState(event.threadIdentifier());
+ if (!state.inKnownLayerTask)
+ return;
+ ASSERT(state.recordStack.isOpenRecordOfType(TimelineRecordType::Rasterize));
+ state.recordStack.closeScopedRecord(m_timeConverter.fromMonotonicallyIncreasingTime(event.timestamp()));
+ state.inKnownLayerTask = false;
+}
+
+void InspectorTimelineAgent::onImageDecodeBegin(const TraceEventDispatcher::TraceEvent& event)
+{
+ TimelineThreadState& state = threadState(event.threadIdentifier());
+ if (!state.decodedPixelRefId && !state.inKnownLayerTask)
+ return;
+ TimelineImageInfo imageInfo;
+ if (state.decodedPixelRefId) {
+ PixelRefToImageInfoMap::const_iterator it = m_pixelRefToImageInfo.find(state.decodedPixelRefId);
+ if (it != m_pixelRefToImageInfo.end())
+ imageInfo = it->value;
+ else
+ ASSERT_NOT_REACHED();
+ }
+ RefPtr<JSONObject> data = JSONObject::create();
+ TimelineRecordFactory::appendImageDetails(data.get(), imageInfo.backendNodeId, imageInfo.url);
+ double timeestamp = m_timeConverter.fromMonotonicallyIncreasingTime(event.timestamp());
+ state.recordStack.addScopedRecord(TimelineRecordFactory::createBackgroundRecord(timeestamp, String::number(event.threadIdentifier()), TimelineRecordType::DecodeImage, data));
+}
+
+void InspectorTimelineAgent::onImageDecodeEnd(const TraceEventDispatcher::TraceEvent& event)
+{
+ TimelineThreadState& state = threadState(event.threadIdentifier());
+ if (!state.decodedPixelRefId)
+ return;
+ ASSERT(state.recordStack.isOpenRecordOfType(TimelineRecordType::DecodeImage));
+ state.recordStack.closeScopedRecord(m_timeConverter.fromMonotonicallyIncreasingTime(event.timestamp()));
+}
+
+void InspectorTimelineAgent::onActivateLayerTree(const TraceEventDispatcher::TraceEvent& event)
+{
+ unsigned long long layerTreeId = event.asUInt(InstrumentationEventArguments::LayerTreeId);
+ if (layerTreeId != m_layerTreeId)
+ return;
+ unsigned long long frameId = event.asUInt(InstrumentationEventArguments::FrameId);
+ TimelineThreadState& state = threadState(event.threadIdentifier());
+ state.recordStack.addInstantRecord(createRecordForEvent(event, TimelineRecordType::ActivateLayerTree, TimelineRecordFactory::createFrameData(frameId)));
+}
+
+void InspectorTimelineAgent::onLayerDeleted(const TraceEventDispatcher::TraceEvent& event)
+{
+ unsigned long long id = event.id();
+ ASSERT(id);
+ m_layerToNodeMap.remove(id);
+}
+
+void InspectorTimelineAgent::onDecodeLazyPixelRefBegin(const TraceEventDispatcher::TraceEvent& event)
+{
+ TimelineThreadState& state = threadState(event.threadIdentifier());
+ ASSERT(!state.decodedPixelRefId);
+ unsigned long long pixelRefId = event.asUInt(PlatformInstrumentation::LazyPixelRef);
+ ASSERT(pixelRefId);
+ if (m_pixelRefToImageInfo.contains(pixelRefId))
+ state.decodedPixelRefId = pixelRefId;
+}
+
+void InspectorTimelineAgent::onDecodeLazyPixelRefEnd(const TraceEventDispatcher::TraceEvent& event)
+{
+ threadState(event.threadIdentifier()).decodedPixelRefId = 0;
+}
+
+void InspectorTimelineAgent::onDrawLazyPixelRef(const TraceEventDispatcher::TraceEvent& event)
+{
+ unsigned long long pixelRefId = event.asUInt(PlatformInstrumentation::LazyPixelRef);
+ ASSERT(pixelRefId);
+ if (!m_imageBeingPainted)
+ return;
+ String url;
+ if (const ImageResource* resource = m_imageBeingPainted->cachedImage())
+ url = resource->url().string();
+ m_pixelRefToImageInfo.set(pixelRefId, TimelineImageInfo(nodeId(m_imageBeingPainted->generatingNode()), url));
+}
+
+void InspectorTimelineAgent::onLazyPixelRefDeleted(const TraceEventDispatcher::TraceEvent& event)
+{
+ m_pixelRefToImageInfo.remove(event.id());
+}
+
+void InspectorTimelineAgent::processGPUEvent(const GPUEvent& event)
+{
+ double timelineTimestamp = m_timeConverter.fromMonotonicallyIncreasingTime(event.timestamp);
+ if (event.phase == GPUEvent::PhaseBegin) {
+ m_pendingGPURecord = TimelineRecordFactory::createBackgroundRecord(timelineTimestamp, "gpu", TimelineRecordType::GPUTask, TimelineRecordFactory::createGPUTaskData(event.foreign, event.usedGPUMemoryBytes));
+ } else if (m_pendingGPURecord) {
+ m_pendingGPURecord->setNumber("endTime", timelineTimestamp);
+ sendEvent(m_pendingGPURecord.release());
+ }
+}
+
void InspectorTimelineAgent::addRecordToTimeline(PassRefPtr<JSONObject> record)
{
commitFrameRecord();
@@ -756,7 +1038,6 @@ void InspectorTimelineAgent::addRecordToTimeline(PassRefPtr<JSONObject> record)
void InspectorTimelineAgent::innerAddRecordToTimeline(PassRefPtr<JSONObject> prpRecord)
{
RefPtr<TypeBuilder::Timeline::TimelineEvent> record = TypeBuilder::Timeline::TimelineEvent::runtimeCast(prpRecord);
-
if (m_recordStack.isEmpty()) {
sendEvent(record.release());
} else {
@@ -780,11 +1061,12 @@ void InspectorTimelineAgent::setDOMCounters(TypeBuilder::Timeline::TimelineEvent
if (m_state->getBoolean(TimelineAgentState::includeDomCounters)) {
int documentCount = 0;
int nodeCount = 0;
+ int listenerCount = 0;
if (m_inspectorType == PageInspector) {
documentCount = InspectorCounters::counterValue(InspectorCounters::DocumentCounter);
nodeCount = InspectorCounters::counterValue(InspectorCounters::NodeCounter);
+ listenerCount = InspectorCounters::counterValue(InspectorCounters::JSEventListenerCounter);
}
- int listenerCount = ThreadLocalInspectorCounters::current().counterValue(ThreadLocalInspectorCounters::JSEventListenerCounter);
RefPtr<TypeBuilder::Timeline::DOMCounters> counters = TypeBuilder::Timeline::DOMCounters::create()
.setDocuments(documentCount)
.setNodes(nodeCount)
@@ -806,7 +1088,7 @@ void InspectorTimelineAgent::setFrameIdentifier(JSONObject* record, Frame* frame
void InspectorTimelineAgent::populateImageDetails(JSONObject* data, const RenderImage& renderImage)
{
const ImageResource* resource = renderImage.cachedImage();
- TimelineRecordFactory::appendImageDetails(data, idForNode(renderImage.generatingNode()), resource ? resource->url().string() : "");
+ TimelineRecordFactory::appendImageDetails(data, nodeId(renderImage.generatingNode()), resource ? resource->url().string() : "");
}
void InspectorTimelineAgent::didCompleteCurrentRecord(const String& type)
@@ -833,21 +1115,31 @@ void InspectorTimelineAgent::didCompleteCurrentRecord(const String& type)
}
}
-InspectorTimelineAgent::InspectorTimelineAgent(InstrumentingAgents* instrumentingAgents, InspectorPageAgent* pageAgent, InspectorMemoryAgent* memoryAgent, InspectorDOMAgent* domAgent, InspectorCompositeState* state, InspectorType type, InspectorClient* client)
+void InspectorTimelineAgent::unwindRecordStack()
+{
+ while (!m_recordStack.isEmpty()) {
+ TimelineRecordEntry& entry = m_recordStack.last();
+ didCompleteCurrentRecord(entry.type);
+ }
+}
+
+InspectorTimelineAgent::InspectorTimelineAgent(InstrumentingAgents* instrumentingAgents, InspectorPageAgent* pageAgent, InspectorMemoryAgent* memoryAgent, InspectorDOMAgent* domAgent, InspectorOverlay* overlay, InspectorCompositeState* state, InspectorType type, InspectorClient* client)
: InspectorBaseAgent<InspectorTimelineAgent>("Timeline", instrumentingAgents, state)
, m_pageAgent(pageAgent)
, m_memoryAgent(memoryAgent)
, m_domAgent(domAgent)
, m_frontend(0)
+ , m_client(client)
+ , m_overlay(overlay)
+ , m_inspectorType(type)
, m_id(1)
+ , m_layerTreeId(0)
, m_maxCallStackDepth(5)
, m_platformInstrumentationClientInstalledAtStackDepth(0)
- , m_inspectorType(type)
- , m_client(client)
- , m_weakFactory(this)
- , m_styleRecalcElementCounter(0)
- , m_layerTreeId(0)
, m_imageBeingPainted(0)
+ , m_paintSetupStart(0)
+ , m_styleRecalcElementCounter(0)
+ , m_mayEmitFirstPaint(false)
{
}
@@ -884,12 +1176,18 @@ void InspectorTimelineAgent::pushCurrentRecord(PassRefPtr<JSONObject> data, cons
}
}
+TimelineThreadState& InspectorTimelineAgent::threadState(ThreadIdentifier thread)
+{
+ ThreadStateMap::iterator it = m_threadStates.find(thread);
+ if (it != m_threadStates.end())
+ return it->value;
+ return m_threadStates.add(thread, TimelineThreadState(this)).iterator->value;
+}
+
void InspectorTimelineAgent::commitFrameRecord()
{
if (!m_pendingFrameRecord)
return;
-
- m_pendingFrameRecord->setObject("data", JSONObject::create());
innerAddRecordToTimeline(m_pendingFrameRecord.release());
}
@@ -915,11 +1213,16 @@ void InspectorTimelineAgent::localToPageQuad(const RenderObject& renderer, const
quad->setP4(view->contentsToRootView(roundedIntPoint(absolute.p4())));
}
-long long InspectorTimelineAgent::idForNode(Node* node)
+long long InspectorTimelineAgent::nodeId(Node* node)
{
return m_domAgent && node ? m_domAgent->backendNodeIdForNode(node, BackendNodeIdGroup) : 0;
}
+long long InspectorTimelineAgent::nodeId(RenderObject* renderer)
+{
+ return nodeId(renderer->generatingNode());
+}
+
void InspectorTimelineAgent::releaseNodeIds()
{
ErrorString unused;
@@ -937,5 +1240,49 @@ Page* InspectorTimelineAgent::page()
return m_pageAgent ? m_pageAgent->page() : 0;
}
+PassRefPtr<JSONObject> InspectorTimelineAgent::createRecordForEvent(const TraceEventDispatcher::TraceEvent& event, const String& type, PassRefPtr<JSONObject> data)
+{
+ double timeestamp = m_timeConverter.fromMonotonicallyIncreasingTime(event.timestamp());
+ return TimelineRecordFactory::createBackgroundRecord(timeestamp, String::number(event.threadIdentifier()), type, data);
+}
+
+TimelineRecordStack::TimelineRecordStack(InspectorTimelineAgent* timelineAgent)
+ : m_timelineAgent(timelineAgent)
+{
+}
+
+void TimelineRecordStack::addScopedRecord(PassRefPtr<JSONObject> record)
+{
+ m_stack.append(Entry(record));
+}
+
+void TimelineRecordStack::closeScopedRecord(double endTime)
+{
+ if (m_stack.isEmpty())
+ return;
+ Entry last = m_stack.last();
+ m_stack.removeLast();
+ last.record->setNumber("endTime", endTime);
+ if (last.children->length())
+ last.record->setArray("children", last.children);
+ addInstantRecord(last.record);
+}
+
+void TimelineRecordStack::addInstantRecord(PassRefPtr<JSONObject> record)
+{
+ if (m_stack.isEmpty())
+ m_timelineAgent->sendEvent(record);
+ else
+ m_stack.last().children->pushObject(record);
+}
+
+#ifndef NDEBUG
+bool TimelineRecordStack::isOpenRecordOfType(const String& type)
+{
+ String lastRecordType;
+ return m_stack.isEmpty() || (m_stack.last().record->getString("type", &lastRecordType) && type == lastRecordType);
+}
+#endif
+
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InspectorTimelineAgent.h b/chromium/third_party/WebKit/Source/core/inspector/InspectorTimelineAgent.h
index c148c7bf9ba..10b1d948bfc 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InspectorTimelineAgent.h
+++ b/chromium/third_party/WebKit/Source/core/inspector/InspectorTimelineAgent.h
@@ -34,18 +34,24 @@
#include "InspectorFrontend.h"
#include "bindings/v8/ScriptGCEvent.h"
-#include "core/dom/EventContext.h"
+#include "core/events/EventPath.h"
#include "core/inspector/InspectorBaseAgent.h"
#include "core/inspector/ScriptGCEventListener.h"
-#include "core/platform/JSONValues.h"
-#include "core/platform/PlatformInstrumentation.h"
-#include "core/platform/graphics/LayoutRect.h"
+#include "core/inspector/TraceEventDispatcher.h"
+#include "platform/JSONValues.h"
+#include "platform/PlatformInstrumentation.h"
+#include "platform/geometry/LayoutRect.h"
#include "wtf/PassOwnPtr.h"
#include "wtf/Vector.h"
#include "wtf/WeakPtr.h"
namespace WebCore {
struct FetchInitiatorInfo;
+struct TimelineGCEvent;
+struct TimelineImageInfo;
+struct TimelineThreadState;
+struct TimelineRecordEntry;
+
class DOMWindow;
class Document;
class DocumentLoader;
@@ -53,10 +59,12 @@ class Event;
class FloatQuad;
class Frame;
class GraphicsContext;
+class GraphicsLayer;
class InspectorClient;
class InspectorDOMAgent;
class InspectorFrontend;
class InspectorMemoryAgent;
+class InspectorOverlay;
class InspectorPageAgent;
class InstrumentingAgents;
class KURL;
@@ -70,9 +78,9 @@ class ResourceRequest;
class ResourceResponse;
class ScriptArguments;
class ScriptCallStack;
-class ScriptExecutionContext;
+class TimelineRecordStack;
+class ExecutionContext;
class ScriptState;
-class TimelineTraceEventProcessor;
class WebSocketHandshakeRequest;
class WebSocketHandshakeResponse;
class XMLHttpRequest;
@@ -80,9 +88,12 @@ class XMLHttpRequest;
typedef String ErrorString;
namespace TimelineRecordType {
+extern const char ActivateLayerTree[];
+extern const char BeginFrame[];
extern const char DecodeImage[];
-extern const char Rasterize[];
+extern const char GPUTask[];
extern const char PaintSetup[];
+extern const char Rasterize[];
};
class TimelineTimeConverter {
@@ -99,17 +110,32 @@ private:
};
class InspectorTimelineAgent
- : public InspectorBaseAgent<InspectorTimelineAgent>,
- public ScriptGCEventListener,
- public InspectorBackendDispatcher::TimelineCommandHandler,
- public PlatformInstrumentationClient {
+ : public TraceEventTarget<InspectorTimelineAgent>
+ , public InspectorBaseAgent<InspectorTimelineAgent>
+ , public ScriptGCEventListener
+ , public InspectorBackendDispatcher::TimelineCommandHandler
+ , public PlatformInstrumentationClient {
WTF_MAKE_NONCOPYABLE(InspectorTimelineAgent);
public:
enum InspectorType { PageInspector, WorkerInspector };
- static PassOwnPtr<InspectorTimelineAgent> create(InstrumentingAgents* instrumentingAgents, InspectorPageAgent* pageAgent, InspectorMemoryAgent* memoryAgent, InspectorDOMAgent* domAgent, InspectorCompositeState* state, InspectorType type, InspectorClient* client)
+ class GPUEvent {
+ public:
+ enum Phase { PhaseBegin, PhaseEnd };
+ GPUEvent(double timestamp, int phase, bool foreign, size_t usedGPUMemoryBytes) :
+ timestamp(timestamp),
+ phase(static_cast<Phase>(phase)),
+ foreign(foreign),
+ usedGPUMemoryBytes(usedGPUMemoryBytes) { }
+ double timestamp;
+ Phase phase;
+ bool foreign;
+ size_t usedGPUMemoryBytes;
+ };
+
+ static PassOwnPtr<InspectorTimelineAgent> create(InstrumentingAgents* instrumentingAgents, InspectorPageAgent* pageAgent, InspectorMemoryAgent* memoryAgent, InspectorDOMAgent* domAgent, InspectorOverlay* overlay, InspectorCompositeState* state, InspectorType type, InspectorClient* client)
{
- return adoptPtr(new InspectorTimelineAgent(instrumentingAgents, pageAgent, memoryAgent, domAgent, state, type, client));
+ return adoptPtr(new InspectorTimelineAgent(instrumentingAgents, pageAgent, memoryAgent, domAgent, overlay, state, type, client));
}
~InspectorTimelineAgent();
@@ -120,17 +146,16 @@ public:
virtual void enable(ErrorString*);
virtual void disable(ErrorString*);
- virtual void start(ErrorString*, const int* maxCallStackDepth, const bool* bufferEvents, const bool* includeDomCounters, const bool* includeNativeMemoryStatistics);
+ virtual void start(ErrorString*, const int* maxCallStackDepth, const bool* bufferEvents, const bool* includeDomCounters, const bool* includeGPUEvents);
virtual void stop(ErrorString*, RefPtr<TypeBuilder::Array<TypeBuilder::Timeline::TimelineEvent> >& events);
void setLayerTreeId(int layerTreeId) { m_layerTreeId = layerTreeId; }
- int layerTreeId() const { return m_layerTreeId; }
int id() const { return m_id; }
void didCommitLoad();
// Methods called from WebCore.
- bool willCallFunction(ScriptExecutionContext* context, const String& scriptName, int scriptLine);
+ bool willCallFunction(ExecutionContext*, const String& scriptName, int scriptLine);
void didCallFunction();
bool willDispatchEvent(Document* document, const Event& event, DOMWindow* window, Node* node, const EventPath& eventPath);
@@ -138,20 +163,23 @@ public:
void didDispatchEvent();
void didDispatchEventOnWindow();
- void didBeginFrame();
+ void didBeginFrame(int frameId);
void didCancelFrame();
void didInvalidateLayout(Frame*);
bool willLayout(Frame*);
void didLayout(RenderObject*);
+ void willAutosizeText(RenderObject*);
+ void didAutosizeText(RenderObject*);
+
void didScheduleStyleRecalculation(Document*);
bool willRecalculateStyle(Document*);
void didRecalculateStyle();
void didRecalculateStyleForElement();
- void willPaint(RenderObject*);
- void didPaint(RenderObject*, GraphicsContext*, const LayoutRect&);
+ void willPaint(RenderObject*, const GraphicsLayer*);
+ void didPaint(RenderObject*, const GraphicsLayer*, GraphicsContext*, const LayoutRect&);
void willPaintImage(RenderImage*);
void didPaintImage();
@@ -165,32 +193,31 @@ public:
bool willWriteHTML(Document*, unsigned startLine);
void didWriteHTML(unsigned endLine);
- void didInstallTimer(ScriptExecutionContext* context, int timerId, int timeout, bool singleShot);
- void didRemoveTimer(ScriptExecutionContext* context, int timerId);
- bool willFireTimer(ScriptExecutionContext* context, int timerId);
+ void didInstallTimer(ExecutionContext*, int timerId, int timeout, bool singleShot);
+ void didRemoveTimer(ExecutionContext*, int timerId);
+ bool willFireTimer(ExecutionContext*, int timerId);
void didFireTimer();
- bool willDispatchXHRReadyStateChangeEvent(ScriptExecutionContext* context, XMLHttpRequest* request);
+ bool willDispatchXHRReadyStateChangeEvent(ExecutionContext*, XMLHttpRequest*);
void didDispatchXHRReadyStateChangeEvent();
- bool willDispatchXHRLoadEvent(ScriptExecutionContext* context, XMLHttpRequest* request);
+ bool willDispatchXHRLoadEvent(ExecutionContext*, XMLHttpRequest*);
void didDispatchXHRLoadEvent();
bool willEvaluateScript(Frame*, const String&, int);
void didEvaluateScript();
- void consoleTimeStamp(ScriptExecutionContext*, const String& title);
+ void consoleTimeStamp(ExecutionContext*, const String& title);
void domContentLoadedEventFired(Frame*);
void loadEventFired(Frame*);
- void consoleTime(ScriptExecutionContext*, const String&);
- void consoleTimeEnd(ScriptExecutionContext*, const String&, ScriptState*);
- void consoleTimeline(ScriptExecutionContext*, const String& title, ScriptState*);
- void consoleTimelineEnd(ScriptExecutionContext*, const String& title, ScriptState*);
+ void consoleTime(ExecutionContext*, const String&);
+ void consoleTimeEnd(ExecutionContext*, const String&, ScriptState*);
+ void consoleTimeline(ExecutionContext*, const String& title, ScriptState*);
+ void consoleTimelineEnd(ExecutionContext*, const String& title, ScriptState*);
void didScheduleResourceRequest(Document*, const String& url);
void willSendRequest(unsigned long, DocumentLoader*, const ResourceRequest&, const ResourceResponse&, const FetchInitiatorInfo&);
- bool willReceiveResourceResponse(Frame*, unsigned long, const ResourceResponse&);
- void didReceiveResourceResponse(unsigned long, DocumentLoader*, const ResourceResponse&, ResourceLoader*);
+ void didReceiveResourceResponse(Frame*, unsigned long, DocumentLoader*, const ResourceResponse&, ResourceLoader*);
void didFinishLoading(unsigned long, DocumentLoader*, double monotonicFinishTime);
void didFailLoading(unsigned long identifier, DocumentLoader* loader, const ResourceError& error);
bool willReceiveResourceData(Frame*, unsigned long identifier, int length);
@@ -209,6 +236,8 @@ public:
void didReceiveWebSocketHandshakeResponse(Document*, unsigned long identifier, const WebSocketHandshakeResponse&);
void didCloseWebSocket(Document*, unsigned long identifier);
+ void processGPUEvent(const GPUEvent&);
+
// ScriptGCEventListener methods.
virtual void didGC(double, double, size_t);
@@ -219,28 +248,32 @@ public:
virtual void didResizeImage() OVERRIDE;
private:
+
friend class TimelineRecordStack;
- friend class TimelineTraceEventProcessor;
-
- struct TimelineRecordEntry {
- TimelineRecordEntry(PassRefPtr<JSONObject> record, PassRefPtr<JSONObject> data, PassRefPtr<JSONArray> children, const String& type, size_t usedHeapSizeAtStart)
- : record(record), data(data), children(children), type(type), usedHeapSizeAtStart(usedHeapSizeAtStart)
- {
- }
- RefPtr<JSONObject> record;
- RefPtr<JSONObject> data;
- RefPtr<JSONArray> children;
- String type;
- size_t usedHeapSizeAtStart;
- };
- InspectorTimelineAgent(InstrumentingAgents*, InspectorPageAgent*, InspectorMemoryAgent*, InspectorDOMAgent*, InspectorCompositeState*, InspectorType, InspectorClient*);
+ InspectorTimelineAgent(InstrumentingAgents*, InspectorPageAgent*, InspectorMemoryAgent*, InspectorDOMAgent*, InspectorOverlay*, InspectorCompositeState*, InspectorType, InspectorClient*);
+
+ // Trace event handlers
+ void onBeginImplSideFrame(const TraceEventDispatcher::TraceEvent&);
+ void onPaintSetupBegin(const TraceEventDispatcher::TraceEvent&);
+ void onPaintSetupEnd(const TraceEventDispatcher::TraceEvent&);
+ void onRasterTaskBegin(const TraceEventDispatcher::TraceEvent&);
+ void onRasterTaskEnd(const TraceEventDispatcher::TraceEvent&);
+ void onImageDecodeBegin(const TraceEventDispatcher::TraceEvent&);
+ void onImageDecodeEnd(const TraceEventDispatcher::TraceEvent&);
+ void onLayerDeleted(const TraceEventDispatcher::TraceEvent&);
+ void onDrawLazyPixelRef(const TraceEventDispatcher::TraceEvent&);
+ void onDecodeLazyPixelRefBegin(const TraceEventDispatcher::TraceEvent&);
+ void onDecodeLazyPixelRefEnd(const TraceEventDispatcher::TraceEvent&);
+ void onActivateLayerTree(const TraceEventDispatcher::TraceEvent&);
+ void onLazyPixelRefDeleted(const TraceEventDispatcher::TraceEvent&);
void didFinishLoadingResource(unsigned long, bool didFail, double finishTime, Frame*);
void sendEvent(PassRefPtr<JSONObject>);
void appendRecord(PassRefPtr<JSONObject> data, const String& type, bool captureCallStack, Frame*);
void pushCurrentRecord(PassRefPtr<JSONObject>, const String& type, bool captureCallStack, Frame*, bool hasLowLevelDetails = false);
+ TimelineThreadState& threadState(ThreadIdentifier);
void setDOMCounters(TypeBuilder::Timeline::TimelineEvent*);
void setFrameIdentifier(JSONObject* record, Frame*);
@@ -249,16 +282,18 @@ private:
void pushGCEventRecords();
void didCompleteCurrentRecord(const String& type);
+ void unwindRecordStack();
void commitFrameRecord();
void addRecordToTimeline(PassRefPtr<JSONObject>);
void innerAddRecordToTimeline(PassRefPtr<JSONObject>);
void clearRecordStack();
+ PassRefPtr<JSONObject> createRecordForEvent(const TraceEventDispatcher::TraceEvent&, const String& type, PassRefPtr<JSONObject> data = 0);
void localToPageQuad(const RenderObject& renderer, const LayoutRect&, FloatQuad*);
- const TimelineTimeConverter& timeConverter() const { return m_timeConverter; }
- long long idForNode(Node*);
+ long long nodeId(Node*);
+ long long nodeId(RenderObject*);
void releaseNodeIds();
double timestamp();
@@ -271,37 +306,37 @@ private:
InspectorPageAgent* m_pageAgent;
InspectorMemoryAgent* m_memoryAgent;
InspectorDOMAgent* m_domAgent;
- TimelineTimeConverter m_timeConverter;
-
InspectorFrontend::Timeline* m_frontend;
- double m_timestampOffset;
+ InspectorClient* m_client;
+ InspectorOverlay* m_overlay;
+ InspectorType m_inspectorType;
+
+ int m_id;
+ unsigned long long m_layerTreeId;
+
+ TimelineTimeConverter m_timeConverter;
+ int m_maxCallStackDepth;
Vector<TimelineRecordEntry> m_recordStack;
+ RefPtr<TypeBuilder::Array<TypeBuilder::Timeline::TimelineEvent> > m_bufferedEvents;
+ Vector<String> m_consoleTimelines;
- int m_id;
- struct GCEvent {
- GCEvent(double startTime, double endTime, size_t collectedBytes)
- : startTime(startTime), endTime(endTime), collectedBytes(collectedBytes)
- {
- }
- double startTime;
- double endTime;
- size_t collectedBytes;
- };
- typedef Vector<GCEvent> GCEvents;
+ typedef Vector<TimelineGCEvent> GCEvents;
GCEvents m_gcEvents;
- int m_maxCallStackDepth;
unsigned m_platformInstrumentationClientInstalledAtStackDepth;
RefPtr<JSONObject> m_pendingFrameRecord;
- InspectorType m_inspectorType;
- InspectorClient* m_client;
- WeakPtrFactory<InspectorTimelineAgent> m_weakFactory;
- RefPtr<TimelineTraceEventProcessor> m_traceEventProcessor;
- unsigned m_styleRecalcElementCounter;
- int m_layerTreeId;
+ RefPtr<JSONObject> m_pendingGPURecord;
+ typedef HashMap<unsigned long long, TimelineImageInfo> PixelRefToImageInfoMap;
+ PixelRefToImageInfoMap m_pixelRefToImageInfo;
RenderImage* m_imageBeingPainted;
- Vector<String> m_consoleTimelines;
- RefPtr<TypeBuilder::Array<TypeBuilder::Timeline::TimelineEvent> > m_bufferedEvents;
+ HashMap<unsigned long long, long long> m_layerToNodeMap;
+ double m_paintSetupStart;
+ double m_paintSetupEnd;
+ RefPtr<JSONObject> m_gpuTask;
+ unsigned m_styleRecalcElementCounter;
+ typedef HashMap<ThreadIdentifier, TimelineThreadState> ThreadStateMap;
+ ThreadStateMap m_threadStates;
+ bool m_mayEmitFirstPaint;
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/inspector/InspectorWorkerAgent.cpp b/chromium/third_party/WebKit/Source/core/inspector/InspectorWorkerAgent.cpp
index 4665d47f1df..c4b91911458 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/InspectorWorkerAgent.cpp
+++ b/chromium/third_party/WebKit/Source/core/inspector/InspectorWorkerAgent.cpp
@@ -36,9 +36,9 @@
#include "core/inspector/InspectorState.h"
#include "core/inspector/InstrumentingAgents.h"
#include "core/inspector/JSONParser.h"
-#include "core/platform/JSONValues.h"
#include "core/workers/WorkerGlobalScopeProxy.h"
-#include "weborigin/KURL.h"
+#include "platform/JSONValues.h"
+#include "platform/weborigin/KURL.h"
#include "wtf/PassOwnPtr.h"
#include "wtf/RefPtr.h"
diff --git a/chromium/third_party/WebKit/Source/core/inspector/JSONParser.cpp b/chromium/third_party/WebKit/Source/core/inspector/JSONParser.cpp
index 115a5760bb5..58adb022e13 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/JSONParser.cpp
+++ b/chromium/third_party/WebKit/Source/core/inspector/JSONParser.cpp
@@ -31,7 +31,7 @@
#include "config.h"
#include "core/inspector/JSONParser.h"
-#include "core/platform/JSONValues.h"
+#include "platform/JSONValues.h"
#include "wtf/text/StringBuilder.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/inspector/JavaScriptCallFrame.cpp b/chromium/third_party/WebKit/Source/core/inspector/JavaScriptCallFrame.cpp
index abc5d83f2ad..6a669582b2d 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/JavaScriptCallFrame.cpp
+++ b/chromium/third_party/WebKit/Source/core/inspector/JavaScriptCallFrame.cpp
@@ -31,6 +31,7 @@
#include "config.h"
#include "core/inspector/JavaScriptCallFrame.h"
+#include "bindings/v8/ScriptValue.h"
#include "bindings/v8/V8Binding.h"
namespace WebCore {
@@ -53,7 +54,7 @@ JavaScriptCallFrame* JavaScriptCallFrame::caller()
v8::HandleScope handleScope(m_isolate);
v8::Handle<v8::Context> debuggerContext = m_debuggerContext.newLocal(m_isolate);
v8::Context::Scope contextScope(debuggerContext);
- v8::Handle<v8::Value> callerFrame = m_callFrame.newLocal(m_isolate)->Get(v8::String::NewSymbol("caller"));
+ v8::Handle<v8::Value> callerFrame = m_callFrame.newLocal(m_isolate)->Get(v8AtomicString(m_isolate, "caller"));
if (!callerFrame->IsObject())
return 0;
m_caller = JavaScriptCallFrame::create(debuggerContext, v8::Handle<v8::Object>::Cast(callerFrame));
@@ -65,7 +66,7 @@ int JavaScriptCallFrame::sourceID() const
{
v8::HandleScope handleScope(m_isolate);
v8::Context::Scope contextScope(m_debuggerContext.newLocal(m_isolate));
- v8::Handle<v8::Value> result = m_callFrame.newLocal(m_isolate)->Get(v8::String::NewSymbol("sourceID"));
+ v8::Handle<v8::Value> result = m_callFrame.newLocal(m_isolate)->Get(v8AtomicString(m_isolate, "sourceID"));
if (result->IsInt32())
return result->Int32Value();
return 0;
@@ -75,7 +76,7 @@ int JavaScriptCallFrame::line() const
{
v8::HandleScope handleScope(m_isolate);
v8::Context::Scope contextScope(m_debuggerContext.newLocal(m_isolate));
- v8::Handle<v8::Value> result = m_callFrame.newLocal(m_isolate)->Get(v8::String::NewSymbol("line"));
+ v8::Handle<v8::Value> result = m_callFrame.newLocal(m_isolate)->Get(v8AtomicString(m_isolate, "line"));
if (result->IsInt32())
return result->Int32Value();
return 0;
@@ -85,7 +86,7 @@ int JavaScriptCallFrame::column() const
{
v8::HandleScope handleScope(m_isolate);
v8::Context::Scope contextScope(m_debuggerContext.newLocal(m_isolate));
- v8::Handle<v8::Value> result = m_callFrame.newLocal(m_isolate)->Get(v8::String::NewSymbol("column"));
+ v8::Handle<v8::Value> result = m_callFrame.newLocal(m_isolate)->Get(v8AtomicString(m_isolate, "column"));
if (result->IsInt32())
return result->Int32Value();
return 0;
@@ -95,14 +96,14 @@ String JavaScriptCallFrame::functionName() const
{
v8::HandleScope handleScope(m_isolate);
v8::Context::Scope contextScope(m_debuggerContext.newLocal(m_isolate));
- v8::Handle<v8::Value> result = m_callFrame.newLocal(m_isolate)->Get(v8::String::NewSymbol("functionName"));
- return toWebCoreStringWithUndefinedOrNullCheck(result);
+ v8::Handle<v8::Value> result = m_callFrame.newLocal(m_isolate)->Get(v8AtomicString(m_isolate, "functionName"));
+ return toCoreStringWithUndefinedOrNullCheck(result);
}
v8::Handle<v8::Value> JavaScriptCallFrame::scopeChain() const
{
- v8::Handle<v8::Array> scopeChain = v8::Handle<v8::Array>::Cast(m_callFrame.newLocal(m_isolate)->Get(v8::String::NewSymbol("scopeChain")));
- v8::Handle<v8::Array> result = v8::Array::New(scopeChain->Length());
+ v8::Handle<v8::Array> scopeChain = v8::Handle<v8::Array>::Cast(m_callFrame.newLocal(m_isolate)->Get(v8AtomicString(m_isolate, "scopeChain")));
+ v8::Handle<v8::Array> result = v8::Array::New(m_isolate, scopeChain->Length());
for (uint32_t i = 0; i < scopeChain->Length(); i++)
result->Set(i, scopeChain->Get(i));
return result;
@@ -110,51 +111,71 @@ v8::Handle<v8::Value> JavaScriptCallFrame::scopeChain() const
int JavaScriptCallFrame::scopeType(int scopeIndex) const
{
- v8::Handle<v8::Array> scopeType = v8::Handle<v8::Array>::Cast(m_callFrame.newLocal(m_isolate)->Get(v8::String::NewSymbol("scopeType")));
+ v8::Handle<v8::Array> scopeType = v8::Handle<v8::Array>::Cast(m_callFrame.newLocal(m_isolate)->Get(v8AtomicString(m_isolate, "scopeType")));
return scopeType->Get(scopeIndex)->Int32Value();
}
v8::Handle<v8::Value> JavaScriptCallFrame::thisObject() const
{
- return m_callFrame.newLocal(m_isolate)->Get(v8::String::NewSymbol("thisObject"));
+ return m_callFrame.newLocal(m_isolate)->Get(v8AtomicString(m_isolate, "thisObject"));
}
String JavaScriptCallFrame::stepInPositions() const
{
v8::Handle<v8::Object> callFrame = m_callFrame.newLocal(m_isolate);
- v8::Handle<v8::Function> stepInPositions = v8::Handle<v8::Function>::Cast(callFrame->Get(v8::String::NewSymbol("stepInPositions")));
+ v8::Handle<v8::Function> stepInPositions = v8::Handle<v8::Function>::Cast(callFrame->Get(v8AtomicString(m_isolate, "stepInPositions")));
v8::Handle<v8::Value> result = stepInPositions->Call(callFrame, 0, 0);
- return toWebCoreStringWithUndefinedOrNullCheck(result);
+ return toCoreStringWithUndefinedOrNullCheck(result);
+}
+
+bool JavaScriptCallFrame::isAtReturn() const
+{
+ v8::HandleScope handleScope(m_isolate);
+ v8::Context::Scope contextScope(m_debuggerContext.newLocal(m_isolate));
+ v8::Handle<v8::Value> result = m_callFrame.newLocal(m_isolate)->Get(v8AtomicString(m_isolate, "isAtReturn"));
+ if (result->IsBoolean())
+ return result->BooleanValue();
+ return false;
+}
+
+v8::Handle<v8::Value> JavaScriptCallFrame::returnValue() const
+{
+ return m_callFrame.newLocal(m_isolate)->Get(v8AtomicString(m_isolate, "returnValue"));
}
v8::Handle<v8::Value> JavaScriptCallFrame::evaluate(const String& expression)
{
v8::Handle<v8::Object> callFrame = m_callFrame.newLocal(m_isolate);
- v8::Handle<v8::Function> evalFunction = v8::Handle<v8::Function>::Cast(callFrame->Get(v8::String::NewSymbol("evaluate")));
- v8::Handle<v8::Value> argv[] = { v8String(expression, m_debuggerContext.newLocal(m_isolate)->GetIsolate()) };
+ v8::Handle<v8::Function> evalFunction = v8::Handle<v8::Function>::Cast(callFrame->Get(v8AtomicString(m_isolate, "evaluate")));
+ v8::Handle<v8::Value> argv[] = { v8String(m_debuggerContext.newLocal(m_isolate)->GetIsolate(), expression) };
return evalFunction->Call(callFrame, 1, argv);
}
v8::Handle<v8::Value> JavaScriptCallFrame::restart()
{
v8::Handle<v8::Object> callFrame = m_callFrame.newLocal(m_isolate);
- v8::Handle<v8::Function> restartFunction = v8::Handle<v8::Function>::Cast(callFrame->Get(v8::String::NewSymbol("restart")));
+ v8::Handle<v8::Function> restartFunction = v8::Handle<v8::Function>::Cast(callFrame->Get(v8AtomicString(m_isolate, "restart")));
v8::Debug::SetLiveEditEnabled(true);
v8::Handle<v8::Value> result = restartFunction->Call(callFrame, 0, 0);
v8::Debug::SetLiveEditEnabled(false);
return result;
}
-v8::Handle<v8::Value> JavaScriptCallFrame::setVariableValue(int scopeNumber, const String& variableName, v8::Handle<v8::Value> newValue)
+v8::Handle<v8::Object> JavaScriptCallFrame::innerCallFrame()
+{
+ return m_callFrame.newLocal(m_isolate);
+}
+
+ScriptValue JavaScriptCallFrame::setVariableValue(int scopeNumber, const String& variableName, const ScriptValue& newValue)
{
v8::Handle<v8::Object> callFrame = m_callFrame.newLocal(m_isolate);
- v8::Handle<v8::Function> setVariableValueFunction = v8::Handle<v8::Function>::Cast(callFrame->Get(v8::String::NewSymbol("setVariableValue")));
+ v8::Handle<v8::Function> setVariableValueFunction = v8::Handle<v8::Function>::Cast(callFrame->Get(v8AtomicString(m_isolate, "setVariableValue")));
v8::Handle<v8::Value> argv[] = {
v8::Handle<v8::Value>(v8::Integer::New(scopeNumber, m_isolate)),
- v8String(variableName, m_isolate),
- newValue
+ v8String(m_isolate, variableName),
+ newValue.v8Value()
};
- return setVariableValueFunction->Call(callFrame, 3, argv);
+ return ScriptValue(setVariableValueFunction->Call(callFrame, 3, argv), m_isolate);
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/inspector/JavaScriptCallFrame.h b/chromium/third_party/WebKit/Source/core/inspector/JavaScriptCallFrame.h
index 62aec90c9f1..ac0c0350b61 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/JavaScriptCallFrame.h
+++ b/chromium/third_party/WebKit/Source/core/inspector/JavaScriptCallFrame.h
@@ -40,6 +40,8 @@
namespace WebCore {
+class ScriptValue;
+
class JavaScriptCallFrame : public RefCounted<JavaScriptCallFrame>, public ScriptWrappable {
public:
static PassRefPtr<JavaScriptCallFrame> create(v8::Handle<v8::Context> debuggerContext, v8::Handle<v8::Object> callFrame)
@@ -59,10 +61,13 @@ public:
int scopeType(int scopeIndex) const;
v8::Handle<v8::Value> thisObject() const;
String stepInPositions() const;
+ bool isAtReturn() const;
+ v8::Handle<v8::Value> returnValue() const;
v8::Handle<v8::Value> evaluate(const String& expression);
v8::Handle<v8::Value> restart();
- v8::Handle<v8::Value> setVariableValue(int scopeNumber, const String& variableName, v8::Handle<v8::Value> newValue);
+ ScriptValue setVariableValue(int scopeNumber, const String& variableName, const ScriptValue& newValue);
+ v8::Handle<v8::Object> innerCallFrame();
private:
JavaScriptCallFrame(v8::Handle<v8::Context> debuggerContext, v8::Handle<v8::Object> callFrame);
diff --git a/chromium/third_party/WebKit/Source/core/inspector/JavaScriptCallFrame.idl b/chromium/third_party/WebKit/Source/core/inspector/JavaScriptCallFrame.idl
index fa31924cfc5..1afad5a6d61 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/JavaScriptCallFrame.idl
+++ b/chromium/third_party/WebKit/Source/core/inspector/JavaScriptCallFrame.idl
@@ -39,17 +39,18 @@
[Custom] any restart();
// Only declarative scope (local, with and catch) is accepted. Returns undefined.
- [Custom] any setVariableValue(long scopeIndex, DOMString variableName, any newValue);
+ any setVariableValue([Default=Undefined] optional long scopeIndex, [TreatNullAs=NullString, TreatUndefinedAs=NullString, Default=Undefined] optional DOMString variableName, [Default=Undefined] optional any newValue);
readonly attribute JavaScriptCallFrame caller;
readonly attribute long sourceID;
readonly attribute long line;
readonly attribute long column;
- [CustomGetter] readonly attribute Array scopeChain;
+ [Custom=Getter] readonly attribute object scopeChain;
[Custom] unsigned short scopeType(long scopeIndex);
- [CustomGetter] readonly attribute Object thisObject;
+ [Custom=Getter] readonly attribute object thisObject;
readonly attribute DOMString stepInPositions;
readonly attribute DOMString functionName;
- [CustomGetter] readonly attribute DOMString type;
+ [Custom=Getter] readonly attribute DOMString type;
+ readonly attribute boolean isAtReturn;
+ [Custom=Getter] readonly attribute any returnValue;
};
-
diff --git a/chromium/third_party/WebKit/Source/core/inspector/NetworkResourcesData.cpp b/chromium/third_party/WebKit/Source/core/inspector/NetworkResourcesData.cpp
index 7ba8df630e3..3427421e4ac 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/NetworkResourcesData.cpp
+++ b/chromium/third_party/WebKit/Source/core/inspector/NetworkResourcesData.cpp
@@ -31,9 +31,8 @@
#include "core/dom/DOMImplementation.h"
#include "core/fetch/Resource.h"
-#include "core/fetch/TextResourceDecoder.h"
-#include "core/platform/SharedBuffer.h"
-#include "core/platform/network/ResourceResponse.h"
+#include "platform/SharedBuffer.h"
+#include "platform/network/ResourceResponse.h"
namespace {
// 100MB
@@ -46,17 +45,17 @@ static size_t maximumSingleResourceContentSize = 10 * 1000 * 1000;
namespace WebCore {
-PassRefPtr<XHRReplayData> XHRReplayData::create(const String &method, const KURL& url, bool async, PassRefPtr<FormData> formData, bool includeCredentials)
+PassRefPtr<XHRReplayData> XHRReplayData::create(const AtomicString& method, const KURL& url, bool async, PassRefPtr<FormData> formData, bool includeCredentials)
{
return adoptRef(new XHRReplayData(method, url, async, formData, includeCredentials));
}
-void XHRReplayData::addHeader(const AtomicString& key, const String& value)
+void XHRReplayData::addHeader(const AtomicString& key, const AtomicString& value)
{
m_headers.set(key, value);
}
-XHRReplayData::XHRReplayData(const String &method, const KURL& url, bool async, PassRefPtr<FormData> formData, bool includeCredentials)
+XHRReplayData::XHRReplayData(const AtomicString& method, const KURL& url, bool async, PassRefPtr<FormData> formData, bool includeCredentials)
: m_method(method)
, m_url(url)
, m_async(async)
@@ -155,9 +154,9 @@ void NetworkResourcesData::resourceCreated(const String& requestId, const String
m_requestIdToResourceDataMap.set(requestId, new ResourceData(requestId, loaderId));
}
-static PassRefPtr<TextResourceDecoder> createOtherResourceTextDecoder(const String& mimeType, const String& textEncodingName)
+static PassOwnPtr<TextResourceDecoder> createOtherResourceTextDecoder(const String& mimeType, const String& textEncodingName)
{
- RefPtr<TextResourceDecoder> decoder;
+ OwnPtr<TextResourceDecoder> decoder;
if (!textEncodingName.isEmpty())
decoder = TextResourceDecoder::create("text/plain", textEncodingName);
else if (DOMImplementation::isXMLMIMEType(mimeType.lower())) {
@@ -167,7 +166,7 @@ static PassRefPtr<TextResourceDecoder> createOtherResourceTextDecoder(const Stri
decoder = TextResourceDecoder::create("text/html", "UTF-8");
else if (mimeType == "text/plain")
decoder = TextResourceDecoder::create("text/plain", "ISO-8859-1");
- return decoder;
+ return decoder.release();
}
void NetworkResourcesData::responseReceived(const String& requestId, const String& frameId, const ResourceResponse& response)
diff --git a/chromium/third_party/WebKit/Source/core/inspector/NetworkResourcesData.h b/chromium/third_party/WebKit/Source/core/inspector/NetworkResourcesData.h
index 52b1cfa49cc..672f588a081 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/NetworkResourcesData.h
+++ b/chromium/third_party/WebKit/Source/core/inspector/NetworkResourcesData.h
@@ -31,8 +31,8 @@
#include "core/fetch/TextResourceDecoder.h"
#include "core/inspector/InspectorPageAgent.h"
-#include "core/platform/network/HTTPHeaderMap.h"
-#include "weborigin/KURL.h"
+#include "platform/network/HTTPHeaderMap.h"
+#include "platform/weborigin/KURL.h"
#include "wtf/Deque.h"
#include "wtf/HashMap.h"
#include "wtf/RefCounted.h"
@@ -49,10 +49,10 @@ class TextResourceDecoder;
class XHRReplayData : public RefCounted<XHRReplayData> {
public:
- static PassRefPtr<XHRReplayData> create(const String &method, const KURL&, bool async, PassRefPtr<FormData>, bool includeCredentials);
+ static PassRefPtr<XHRReplayData> create(const AtomicString& method, const KURL&, bool async, PassRefPtr<FormData>, bool includeCredentials);
- void addHeader(const AtomicString& key, const String& value);
- const String& method() const { return m_method; }
+ void addHeader(const AtomicString& key, const AtomicString& value);
+ const AtomicString& method() const { return m_method; }
const KURL& url() const { return m_url; }
bool async() const { return m_async; }
PassRefPtr<FormData> formData() const { return m_formData; }
@@ -60,9 +60,9 @@ public:
bool includeCredentials() const { return m_includeCredentials; }
private:
- XHRReplayData(const String &method, const KURL&, bool async, PassRefPtr<FormData>, bool includeCredentials);
+ XHRReplayData(const AtomicString& method, const KURL&, bool async, PassRefPtr<FormData>, bool includeCredentials);
- String m_method;
+ AtomicString m_method;
KURL m_url;
bool m_async;
RefPtr<FormData> m_formData;
@@ -107,8 +107,8 @@ public:
String textEncodingName() const { return m_textEncodingName; }
void setTextEncodingName(const String& textEncodingName) { m_textEncodingName = textEncodingName; }
- PassRefPtr<TextResourceDecoder> decoder() const { return m_decoder; }
- void setDecoder(PassRefPtr<TextResourceDecoder> decoder) { m_decoder = decoder; }
+ TextResourceDecoder* decoder() const { return m_decoder.get(); }
+ void setDecoder(PassOwnPtr<TextResourceDecoder> decoder) { m_decoder = decoder; }
PassRefPtr<SharedBuffer> buffer() const { return m_buffer; }
void setBuffer(PassRefPtr<SharedBuffer> buffer) { m_buffer = buffer; }
@@ -138,7 +138,7 @@ public:
int m_httpStatusCode;
String m_textEncodingName;
- RefPtr<TextResourceDecoder> m_decoder;
+ OwnPtr<TextResourceDecoder> m_decoder;
RefPtr<SharedBuffer> m_buffer;
Resource* m_cachedResource;
diff --git a/chromium/third_party/WebKit/Source/core/inspector/PageDebuggerAgent.cpp b/chromium/third_party/WebKit/Source/core/inspector/PageDebuggerAgent.cpp
index b3069869c07..5e9323bfb91 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/PageDebuggerAgent.cpp
+++ b/chromium/third_party/WebKit/Source/core/inspector/PageDebuggerAgent.cpp
@@ -32,14 +32,13 @@
#include "core/inspector/PageDebuggerAgent.h"
#include "bindings/v8/DOMWrapperWorld.h"
-#include "bindings/v8/PageScriptDebugServer.h"
#include "bindings/v8/ScriptController.h"
#include "bindings/v8/ScriptSourceCode.h"
#include "core/inspector/InspectorOverlay.h"
#include "core/inspector/InspectorPageAgent.h"
#include "core/inspector/InstrumentingAgents.h"
#include "core/loader/DocumentLoader.h"
-#include "core/page/Frame.h"
+#include "core/frame/Frame.h"
#include "core/page/Page.h"
#include "core/page/PageConsole.h"
@@ -109,7 +108,7 @@ void PageDebuggerAgent::overlayResumed()
void PageDebuggerAgent::overlaySteppedOver()
{
ErrorString error;
- stepOver(&error);
+ stepOver(&error, 0);
}
InjectedScript PageDebuggerAgent::injectedScriptForEval(ErrorString* errorString, const int* executionContextId)
diff --git a/chromium/third_party/WebKit/Source/core/inspector/PageRuntimeAgent.cpp b/chromium/third_party/WebKit/Source/core/inspector/PageRuntimeAgent.cpp
index c6e81e5e446..78d2bbc58b8 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/PageRuntimeAgent.cpp
+++ b/chromium/third_party/WebKit/Source/core/inspector/PageRuntimeAgent.cpp
@@ -38,10 +38,10 @@
#include "core/inspector/InspectorPageAgent.h"
#include "core/inspector/InspectorState.h"
#include "core/inspector/InstrumentingAgents.h"
-#include "core/page/Frame.h"
+#include "core/frame/Frame.h"
#include "core/page/Page.h"
#include "core/page/PageConsole.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/weborigin/SecurityOrigin.h"
using WebCore::TypeBuilder::Runtime::ExecutionContextDescription;
@@ -161,14 +161,14 @@ void PageRuntimeAgent::unmuteConsole()
void PageRuntimeAgent::reportExecutionContextCreation()
{
Vector<std::pair<ScriptState*, SecurityOrigin*> > isolatedContexts;
- for (Frame* frame = m_inspectedPage->mainFrame(); frame; frame = frame->tree()->traverseNext()) {
- if (!frame->script()->canExecuteScripts(NotAboutToExecuteScript))
+ for (Frame* frame = m_inspectedPage->mainFrame(); frame; frame = frame->tree().traverseNext()) {
+ if (!frame->script().canExecuteScripts(NotAboutToExecuteScript))
continue;
String frameId = m_pageAgent->frameId(frame);
ScriptState* scriptState = mainWorldScriptState(frame);
notifyContextCreated(frameId, scriptState, 0, true);
- frame->script()->collectIsolatedContexts(isolatedContexts);
+ frame->script().collectIsolatedContexts(isolatedContexts);
if (isolatedContexts.isEmpty())
continue;
for (size_t i = 0; i< isolatedContexts.size(); i++)
diff --git a/chromium/third_party/WebKit/Source/core/inspector/ScriptCallStack.cpp b/chromium/third_party/WebKit/Source/core/inspector/ScriptCallStack.cpp
index 4486b910fc5..0a23bb4fae5 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/ScriptCallStack.cpp
+++ b/chromium/third_party/WebKit/Source/core/inspector/ScriptCallStack.cpp
@@ -31,7 +31,6 @@
#include "config.h"
#include "core/inspector/ScriptCallStack.h"
-#include "InspectorTypeBuilder.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/inspector/ScriptProfile.cpp b/chromium/third_party/WebKit/Source/core/inspector/ScriptProfile.cpp
index 7894f80c60e..8eef1ea15ac 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/ScriptProfile.cpp
+++ b/chromium/third_party/WebKit/Source/core/inspector/ScriptProfile.cpp
@@ -46,7 +46,7 @@ ScriptProfile::~ScriptProfile()
String ScriptProfile::title() const
{
v8::HandleScope scope(v8::Isolate::GetCurrent());
- return toWebCoreString(m_profile->GetTitle());
+ return toCoreString(m_profile->GetTitle());
}
unsigned int ScriptProfile::uid() const
@@ -81,10 +81,11 @@ static PassRefPtr<TypeBuilder::Profiler::CPUProfileNode> buildInspectorObjectFor
}
RefPtr<TypeBuilder::Profiler::CPUProfileNode> result = TypeBuilder::Profiler::CPUProfileNode::create()
- .setFunctionName(toWebCoreString(node->GetFunctionName()))
+ .setFunctionName(toCoreString(node->GetFunctionName()))
.setScriptId(String::number(node->GetScriptId()))
- .setUrl(toWebCoreString(node->GetScriptResourceName()))
+ .setUrl(toCoreString(node->GetScriptResourceName()))
.setLineNumber(node->GetLineNumber())
+ .setColumnNumber(node->GetColumnNumber())
.setHitCount(node->GetHitCount())
.setCallUID(node->GetCallUid())
.setChildren(children.release())
diff --git a/chromium/third_party/WebKit/Source/core/inspector/ScriptProfile.h b/chromium/third_party/WebKit/Source/core/inspector/ScriptProfile.h
index ba14b981d50..0a99d899854 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/ScriptProfile.h
+++ b/chromium/third_party/WebKit/Source/core/inspector/ScriptProfile.h
@@ -41,13 +41,13 @@ class CpuProfile;
namespace WebCore {
-class ScriptProfile : public RefCounted<ScriptProfile> {
+class ScriptProfile FINAL : public RefCounted<ScriptProfile> {
public:
static PassRefPtr<ScriptProfile> create(const v8::CpuProfile* profile, double idleTime)
{
return adoptRef(new ScriptProfile(profile, idleTime));
}
- virtual ~ScriptProfile();
+ ~ScriptProfile();
String title() const;
unsigned int uid() const;
diff --git a/chromium/third_party/WebKit/Source/core/inspector/TimelineRecordFactory.cpp b/chromium/third_party/WebKit/Source/core/inspector/TimelineRecordFactory.cpp
index 75badf89741..b0fd28a3b66 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/TimelineRecordFactory.cpp
+++ b/chromium/third_party/WebKit/Source/core/inspector/TimelineRecordFactory.cpp
@@ -32,13 +32,12 @@
#include "core/inspector/TimelineRecordFactory.h"
#include "bindings/v8/ScriptCallStackFactory.h"
-#include "core/dom/Event.h"
+#include "core/events/Event.h"
#include "core/inspector/ScriptCallStack.h"
-#include "core/platform/JSONValues.h"
-#include "core/platform/graphics/FloatQuad.h"
-#include "core/platform/graphics/LayoutRect.h"
-#include "core/platform/network/ResourceRequest.h"
-#include "core/platform/network/ResourceResponse.h"
+#include "platform/geometry/FloatQuad.h"
+#include "platform/geometry/LayoutRect.h"
+#include "platform/network/ResourceRequest.h"
+#include "platform/network/ResourceResponse.h"
#include "wtf/CurrentTime.h"
namespace WebCore {
@@ -57,15 +56,17 @@ PassRefPtr<JSONObject> TimelineRecordFactory::createGenericRecord(double startTi
return record.release();
}
-PassRefPtr<JSONObject> TimelineRecordFactory::createBackgroundRecord(double startTime, const String& threadName)
+PassRefPtr<JSONObject> TimelineRecordFactory::createBackgroundRecord(double startTime, const String& threadName, const String& type, PassRefPtr<JSONObject> data)
{
RefPtr<JSONObject> record = JSONObject::create();
record->setNumber("startTime", startTime);
record->setString("thread", threadName);
+ record->setString("type", type);
+ record->setObject("data", data ? data : JSONObject::create());
return record.release();
}
-PassRefPtr<JSONObject> TimelineRecordFactory::createGCEventData(const size_t usedHeapSizeDelta)
+PassRefPtr<JSONObject> TimelineRecordFactory::createGCEventData(size_t usedHeapSizeDelta)
{
RefPtr<JSONObject> data = JSONObject::create();
data->setNumber("usedHeapSizeDelta", usedHeapSizeDelta);
@@ -220,6 +221,15 @@ PassRefPtr<JSONObject> TimelineRecordFactory::createAnimationFrameData(int callb
return data.release();
}
+PassRefPtr<JSONObject> TimelineRecordFactory::createGPUTaskData(bool foreign, size_t usedGPUMemoryBytes)
+{
+ RefPtr<JSONObject> data = JSONObject::create();
+ data->setBoolean("foreign", foreign);
+ if (!foreign)
+ data->setNumber("usedGPUMemoryBytes", usedGPUMemoryBytes);
+ return data.release();
+}
+
static PassRefPtr<JSONArray> createQuad(const FloatQuad& quad)
{
RefPtr<JSONArray> array = JSONArray::create();
@@ -234,18 +244,31 @@ static PassRefPtr<JSONArray> createQuad(const FloatQuad& quad)
return array.release();
}
-PassRefPtr<JSONObject> TimelineRecordFactory::createLayerData(long long layerRootNodeId)
+PassRefPtr<JSONObject> TimelineRecordFactory::createNodeData(long long nodeId)
{
RefPtr<JSONObject> data = JSONObject::create();
- if (layerRootNodeId)
- data->setNumber("layerRootNode", layerRootNodeId);
+ if (nodeId)
+ data->setNumber("rootNode", nodeId);
return data.release();
}
-PassRefPtr<JSONObject> TimelineRecordFactory::createPaintData(const FloatQuad& quad, long long layerRootNodeId)
+PassRefPtr<JSONObject> TimelineRecordFactory::createLayerData(long long rootNodeId)
+{
+ return createNodeData(rootNodeId);
+}
+
+PassRefPtr<JSONObject> TimelineRecordFactory::createPaintData(const FloatQuad& quad, long long layerRootNodeId, int graphicsLayerId)
{
RefPtr<JSONObject> data = TimelineRecordFactory::createLayerData(layerRootNodeId);
data->setArray("clip", createQuad(quad));
+ data->setNumber("layerId", graphicsLayerId);
+ return data.release();
+}
+
+PassRefPtr<JSONObject> TimelineRecordFactory::createFrameData(int frameId)
+{
+ RefPtr<JSONObject> data = JSONObject::create();
+ data->setNumber("id", frameId);
return data.release();
}
diff --git a/chromium/third_party/WebKit/Source/core/inspector/TimelineRecordFactory.h b/chromium/third_party/WebKit/Source/core/inspector/TimelineRecordFactory.h
index bb2df6ac074..67ac43f1993 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/TimelineRecordFactory.h
+++ b/chromium/third_party/WebKit/Source/core/inspector/TimelineRecordFactory.h
@@ -31,8 +31,8 @@
#ifndef TimelineRecordFactory_h
#define TimelineRecordFactory_h
-#include "core/platform/JSONValues.h"
-#include "weborigin/KURL.h"
+#include "platform/JSONValues.h"
+#include "platform/weborigin/KURL.h"
#include "wtf/Forward.h"
#include "wtf/text/WTFString.h"
@@ -48,9 +48,9 @@ namespace WebCore {
class TimelineRecordFactory {
public:
static PassRefPtr<JSONObject> createGenericRecord(double startTime, int maxCallStackDepth, const String& type);
- static PassRefPtr<JSONObject> createBackgroundRecord(double startTime, const String& thread);
+ static PassRefPtr<JSONObject> createBackgroundRecord(double startTime, const String& thread, const String& type, PassRefPtr<JSONObject> data = 0);
- static PassRefPtr<JSONObject> createGCEventData(const size_t usedHeapSizeDelta);
+ static PassRefPtr<JSONObject> createGCEventData(size_t usedHeapSizeDelta);
static PassRefPtr<JSONObject> createFunctionCallData(const String& scriptName, int scriptLine);
@@ -90,9 +90,15 @@ namespace WebCore {
static PassRefPtr<JSONObject> createAnimationFrameData(int callbackId);
+ static PassRefPtr<JSONObject> createNodeData(long long nodeId);
+
static PassRefPtr<JSONObject> createLayerData(long long layerRootNodeId);
- static PassRefPtr<JSONObject> createPaintData(const FloatQuad&, long long layerRootNodeId);
+ static PassRefPtr<JSONObject> createPaintData(const FloatQuad&, long long layerRootNodeId, int graphicsLayerId);
+
+ static PassRefPtr<JSONObject> createFrameData(int frameId);
+
+ static PassRefPtr<JSONObject> createGPUTaskData(bool foreign, size_t usedGPUMemoryBytes);
static void appendLayoutRoot(JSONObject* data, const FloatQuad&, long long rootNodeId);
diff --git a/chromium/third_party/WebKit/Source/core/inspector/TimelineTraceEventProcessor.cpp b/chromium/third_party/WebKit/Source/core/inspector/TimelineTraceEventProcessor.cpp
deleted file mode 100644
index 9145e07d758..00000000000
--- a/chromium/third_party/WebKit/Source/core/inspector/TimelineTraceEventProcessor.cpp
+++ /dev/null
@@ -1,398 +0,0 @@
-/*
-* Copyright (C) 2013 Google Inc. All rights reserved.
-*
-* Redistribution and use in source and binary forms, with or without
-* modification, are permitted provided that the following conditions are
-* met:
-*
-* * Redistributions of source code must retain the above copyright
-* notice, this list of conditions and the following disclaimer.
-* * Redistributions in binary form must reproduce the above
-* copyright notice, this list of conditions and the following disclaimer
-* in the documentation and/or other materials provided with the
-* distribution.
-* * Neither the name of Google Inc. nor the names of its
-* contributors may be used to endorse or promote products derived from
-* this software without specific prior written permission.
-*
-* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-*/
-
-#include "config.h"
-#include "core/inspector/TimelineTraceEventProcessor.h"
-
-#include "core/inspector/InspectorClient.h"
-#include "core/inspector/InspectorInstrumentation.h"
-#include "core/inspector/TimelineRecordFactory.h"
-
-#include "wtf/CurrentTime.h"
-#include "wtf/MainThread.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-namespace {
-
-class TraceEventDispatcher {
- WTF_MAKE_NONCOPYABLE(TraceEventDispatcher);
-public:
- static TraceEventDispatcher* instance()
- {
- DEFINE_STATIC_LOCAL(TraceEventDispatcher, instance, ());
- return &instance;
- }
-
- void addProcessor(TimelineTraceEventProcessor* processor, InspectorClient* client)
- {
- MutexLocker locker(m_mutex);
-
- m_processors.append(processor);
- if (m_processors.size() == 1)
- client->setTraceEventCallback(dispatchEventOnAnyThread);
- }
-
- void removeProcessor(TimelineTraceEventProcessor* processor, InspectorClient* client)
- {
- MutexLocker locker(m_mutex);
-
- size_t index = m_processors.find(processor);
- if (index == kNotFound) {
- ASSERT_NOT_REACHED();
- return;
- }
- m_processors.remove(index);
- if (m_processors.isEmpty())
- client->setTraceEventCallback(0);
- }
-
-private:
- TraceEventDispatcher() { }
-
- static void dispatchEventOnAnyThread(char phase, const unsigned char*, const char* name, unsigned long long id,
- int numArgs, const char* const* argNames, const unsigned char* argTypes, const unsigned long long* argValues,
- unsigned char flags)
- {
- TraceEventDispatcher* self = instance();
- Vector<RefPtr<TimelineTraceEventProcessor> > processors;
- {
- MutexLocker locker(self->m_mutex);
- processors = self->m_processors;
- }
- for (int i = 0, size = processors.size(); i < size; ++i) {
- processors[i]->processEventOnAnyThread(static_cast<TimelineTraceEventProcessor::TraceEventPhase>(phase),
- name, id, numArgs, argNames, argTypes, argValues, flags);
- }
- }
-
- Mutex m_mutex;
- Vector<RefPtr<TimelineTraceEventProcessor> > m_processors;
-};
-
-} // namespce
-
-
-TimelineRecordStack::TimelineRecordStack(WeakPtr<InspectorTimelineAgent> timelineAgent)
- : m_timelineAgent(timelineAgent)
-{
-}
-
-void TimelineRecordStack::addScopedRecord(PassRefPtr<JSONObject> record)
-{
- m_stack.append(Entry(record));
-}
-
-void TimelineRecordStack::closeScopedRecord(double endTime)
-{
- if (m_stack.isEmpty())
- return;
- Entry last = m_stack.last();
- m_stack.removeLast();
- last.record->setNumber("endTime", endTime);
- if (last.children->length())
- last.record->setArray("children", last.children);
- addInstantRecord(last.record);
-}
-
-void TimelineRecordStack::addInstantRecord(PassRefPtr<JSONObject> record)
-{
- if (m_stack.isEmpty())
- send(record);
- else
- m_stack.last().children->pushObject(record);
-}
-
-#ifndef NDEBUG
-bool TimelineRecordStack::isOpenRecordOfType(const String& type)
-{
- String lastRecordType;
- return m_stack.isEmpty() || (m_stack.last().record->getString("type", &lastRecordType) && type == lastRecordType);
-}
-#endif
-
-void TimelineRecordStack::send(PassRefPtr<JSONObject> record)
-{
- InspectorTimelineAgent* timelineAgent = m_timelineAgent.get();
- if (!timelineAgent)
- return;
- timelineAgent->sendEvent(record);
-}
-
-TimelineTraceEventProcessor::TimelineTraceEventProcessor(WeakPtr<InspectorTimelineAgent> timelineAgent, InspectorClient *client)
- : m_timelineAgent(timelineAgent)
- , m_timeConverter(timelineAgent.get()->timeConverter())
- , m_inspectorClient(client)
- , m_pageId(reinterpret_cast<unsigned long long>(m_timelineAgent.get()->page()))
- , m_layerTreeId(m_timelineAgent.get()->layerTreeId())
- , m_layerId(0)
- , m_paintSetupStart(0)
- , m_paintSetupEnd(0)
-{
- registerHandler(InstrumentationEvents::BeginFrame, TracePhaseInstant, &TimelineTraceEventProcessor::onBeginFrame);
- registerHandler(InstrumentationEvents::UpdateLayer, TracePhaseBegin, &TimelineTraceEventProcessor::onUpdateLayerBegin);
- registerHandler(InstrumentationEvents::UpdateLayer, TracePhaseEnd, &TimelineTraceEventProcessor::onUpdateLayerEnd);
- registerHandler(InstrumentationEvents::PaintLayer, TracePhaseBegin, &TimelineTraceEventProcessor::onPaintLayerBegin);
- registerHandler(InstrumentationEvents::PaintLayer, TracePhaseEnd, &TimelineTraceEventProcessor::onPaintLayerEnd);
- registerHandler(InstrumentationEvents::PaintSetup, TracePhaseBegin, &TimelineTraceEventProcessor::onPaintSetupBegin);
- registerHandler(InstrumentationEvents::PaintSetup, TracePhaseEnd, &TimelineTraceEventProcessor::onPaintSetupEnd);
- registerHandler(InstrumentationEvents::RasterTask, TracePhaseBegin, &TimelineTraceEventProcessor::onRasterTaskBegin);
- registerHandler(InstrumentationEvents::RasterTask, TracePhaseEnd, &TimelineTraceEventProcessor::onRasterTaskEnd);
- registerHandler(InstrumentationEvents::ImageDecodeTask, TracePhaseBegin, &TimelineTraceEventProcessor::onImageDecodeTaskBegin);
- registerHandler(InstrumentationEvents::ImageDecodeTask, TracePhaseEnd, &TimelineTraceEventProcessor::onImageDecodeTaskEnd);
- registerHandler(InstrumentationEvents::Layer, TracePhaseDeleteObject, &TimelineTraceEventProcessor::onLayerDeleted);
- registerHandler(InstrumentationEvents::Paint, TracePhaseInstant, &TimelineTraceEventProcessor::onPaint);
- registerHandler(PlatformInstrumentation::ImageDecodeEvent, TracePhaseBegin, &TimelineTraceEventProcessor::onImageDecodeBegin);
- registerHandler(PlatformInstrumentation::ImageDecodeEvent, TracePhaseEnd, &TimelineTraceEventProcessor::onImageDecodeEnd);
-
- TraceEventDispatcher::instance()->addProcessor(this, m_inspectorClient);
-}
-
-TimelineTraceEventProcessor::~TimelineTraceEventProcessor()
-{
-}
-
-void TimelineTraceEventProcessor::registerHandler(const char* name, TraceEventPhase phase, TraceEventHandler handler)
-{
- m_handlersByType.set(std::make_pair(name, phase), handler);
-}
-
-void TimelineTraceEventProcessor::shutdown()
-{
- TraceEventDispatcher::instance()->removeProcessor(this, m_inspectorClient);
-}
-
-size_t TimelineTraceEventProcessor::TraceEvent::findParameter(const char* name) const
-{
- for (int i = 0; i < m_argumentCount; ++i) {
- if (!strcmp(name, m_argumentNames[i]))
- return i;
- }
- return kNotFound;
-}
-
-const TimelineTraceEventProcessor::TraceValueUnion& TimelineTraceEventProcessor::TraceEvent::parameter(const char* name, TraceValueTypes expectedType) const
-{
- static TraceValueUnion missingValue;
- size_t index = findParameter(name);
- if (index == kNotFound || m_argumentTypes[index] != expectedType) {
- ASSERT_NOT_REACHED();
- return missingValue;
- }
- return *reinterpret_cast<const TraceValueUnion*>(m_argumentValues + index);
-}
-
-void TimelineTraceEventProcessor::processEventOnAnyThread(TraceEventPhase phase, const char* name, unsigned long long id,
- int numArgs, const char* const* argNames, const unsigned char* argTypes, const unsigned long long* argValues,
- unsigned char)
-{
- HandlersMap::iterator it = m_handlersByType.find(std::make_pair(name, phase));
- if (it == m_handlersByType.end())
- return;
-
- TraceEvent event(WTF::monotonicallyIncreasingTime(), phase, name, id, currentThread(), numArgs, argNames, argTypes, argValues);
-
- if (!isMainThread()) {
- MutexLocker locker(m_backgroundEventsMutex);
- m_backgroundEvents.append(event);
- return;
- }
- (this->*(it->value))(event);
-}
-
-void TimelineTraceEventProcessor::onBeginFrame(const TraceEvent&)
-{
- processBackgroundEvents();
-}
-
-void TimelineTraceEventProcessor::onUpdateLayerBegin(const TraceEvent& event)
-{
- unsigned long long layerTreeId = event.asUInt(InstrumentationEventArguments::LayerTreeId);
- if (layerTreeId != m_layerTreeId)
- return;
- m_layerId = event.asUInt(InstrumentationEventArguments::LayerId);
- // We don't know the node yet. For content layers, the node will be updated
- // by paint. For others, let it remain 0 -- we just need the fact that
- // the layer belongs to the page (see cookie check).
- m_layerToNodeMap.add(m_layerId, 0);
-}
-
-void TimelineTraceEventProcessor::onUpdateLayerEnd(const TraceEvent& event)
-{
- m_layerId = 0;
-}
-
-void TimelineTraceEventProcessor::onPaintLayerBegin(const TraceEvent& event)
-{
- m_layerId = event.asUInt(InstrumentationEventArguments::LayerId);
- ASSERT(m_layerId);
- ASSERT(!m_paintSetupStart);
-}
-
-void TimelineTraceEventProcessor::onPaintLayerEnd(const TraceEvent& event)
-{
- m_layerId = 0;
- ASSERT(m_paintSetupStart);
-}
-
-void TimelineTraceEventProcessor::onPaintSetupBegin(const TraceEvent& event)
-{
- ASSERT(!m_paintSetupStart);
- m_paintSetupStart = m_timeConverter.fromMonotonicallyIncreasingTime(event.timestamp());
-}
-
-void TimelineTraceEventProcessor::onPaintSetupEnd(const TraceEvent& event)
-{
- ASSERT(m_paintSetupStart);
- m_paintSetupEnd = m_timeConverter.fromMonotonicallyIncreasingTime(event.timestamp());
-}
-
-void TimelineTraceEventProcessor::onRasterTaskBegin(const TraceEvent& event)
-{
- TimelineThreadState& state = threadState(event.threadIdentifier());
- if (!maybeEnterLayerTask(event, state))
- return;
- unsigned long long layerId = event.asUInt(InstrumentationEventArguments::LayerId);
- ASSERT(layerId);
- RefPtr<JSONObject> record = createRecord(event, TimelineRecordType::Rasterize);
- record->setObject("data", TimelineRecordFactory::createLayerData(m_layerToNodeMap.get(layerId)));
- state.recordStack.addScopedRecord(record.release());
-}
-
-void TimelineTraceEventProcessor::onRasterTaskEnd(const TraceEvent& event)
-{
- TimelineThreadState& state = threadState(event.threadIdentifier());
- if (!state.inKnownLayerTask)
- return;
- ASSERT(state.recordStack.isOpenRecordOfType(TimelineRecordType::Rasterize));
- state.recordStack.closeScopedRecord(m_timeConverter.fromMonotonicallyIncreasingTime(event.timestamp()));
- leaveLayerTask(state);
-}
-
-void TimelineTraceEventProcessor::onImageDecodeTaskBegin(const TraceEvent& event)
-{
- maybeEnterLayerTask(event, threadState(event.threadIdentifier()));
-}
-
-void TimelineTraceEventProcessor::onImageDecodeTaskEnd(const TraceEvent& event)
-{
- leaveLayerTask(threadState(event.threadIdentifier()));
-}
-
-bool TimelineTraceEventProcessor::maybeEnterLayerTask(const TraceEvent& event, TimelineThreadState& threadState)
-{
- unsigned long long layerId = event.asUInt(InstrumentationEventArguments::LayerId);
- if (!m_layerToNodeMap.contains(layerId))
- return false;
- ASSERT(!threadState.inKnownLayerTask);
- threadState.inKnownLayerTask = true;
- return true;
-}
-
-void TimelineTraceEventProcessor::leaveLayerTask(TimelineThreadState& threadState)
-{
- threadState.inKnownLayerTask = false;
-}
-
-void TimelineTraceEventProcessor::onImageDecodeBegin(const TraceEvent& event)
-{
- TimelineThreadState& state = threadState(event.threadIdentifier());
- if (!state.inKnownLayerTask)
- return;
- state.recordStack.addScopedRecord(createRecord(event, TimelineRecordType::DecodeImage));
-}
-
-void TimelineTraceEventProcessor::onImageDecodeEnd(const TraceEvent& event)
-{
- TimelineThreadState& state = threadState(event.threadIdentifier());
- if (!state.inKnownLayerTask)
- return;
- ASSERT(state.recordStack.isOpenRecordOfType(TimelineRecordType::DecodeImage));
- state.recordStack.closeScopedRecord(m_timeConverter.fromMonotonicallyIncreasingTime(event.timestamp()));
-}
-
-void TimelineTraceEventProcessor::onLayerDeleted(const TraceEvent& event)
-{
- unsigned long long id = event.id();
- ASSERT(id);
- processBackgroundEvents();
- m_layerToNodeMap.remove(id);
-}
-
-void TimelineTraceEventProcessor::onPaint(const TraceEvent& event)
-{
- double paintSetupStart = m_paintSetupStart;
- m_paintSetupStart = 0;
- if (!m_layerId)
- return;
- unsigned long long pageId = event.asUInt(InstrumentationEventArguments::PageId);
- if (pageId != m_pageId)
- return;
- long long nodeId = event.asInt(InstrumentationEventArguments::NodeId);
- ASSERT(nodeId);
- m_layerToNodeMap.set(m_layerId, nodeId);
- InspectorTimelineAgent* timelineAgent = m_timelineAgent.get();
- if (timelineAgent && paintSetupStart) {
- RefPtr<JSONObject> paintSetupRecord = TimelineRecordFactory::createGenericRecord(paintSetupStart, 0, TimelineRecordType::PaintSetup);
- paintSetupRecord->setNumber("endTime", m_paintSetupEnd);
- paintSetupRecord->setObject("data", TimelineRecordFactory::createLayerData(nodeId));
- timelineAgent->addRecordToTimeline(paintSetupRecord);
- }
-}
-
-PassRefPtr<JSONObject> TimelineTraceEventProcessor::createRecord(const TraceEvent& event, const String& recordType, PassRefPtr<JSONObject> data)
-{
- double startTime = m_timeConverter.fromMonotonicallyIncreasingTime(event.timestamp());
- RefPtr<JSONObject> record = TimelineRecordFactory::createBackgroundRecord(startTime, String::number(event.threadIdentifier()));
- record->setString("type", recordType);
- record->setObject("data", data ? data : JSONObject::create());
- return record.release();
-}
-
-void TimelineTraceEventProcessor::processBackgroundEvents()
-{
- ASSERT(isMainThread());
- Vector<TraceEvent> events;
- {
- MutexLocker locker(m_backgroundEventsMutex);
- events.reserveCapacity(m_backgroundEvents.capacity());
- m_backgroundEvents.swap(events);
- }
- for (size_t i = 0, size = events.size(); i < size; ++i) {
- const TraceEvent& event = events[i];
- HandlersMap::iterator it = m_handlersByType.find(std::make_pair(event.name(), event.phase()));
- ASSERT(it != m_handlersByType.end() && it->value);
- (this->*(it->value))(event);
- }
-}
-
-} // namespace WebCore
-
diff --git a/chromium/third_party/WebKit/Source/core/inspector/TimelineTraceEventProcessor.h b/chromium/third_party/WebKit/Source/core/inspector/TimelineTraceEventProcessor.h
deleted file mode 100644
index e9b386ec05d..00000000000
--- a/chromium/third_party/WebKit/Source/core/inspector/TimelineTraceEventProcessor.h
+++ /dev/null
@@ -1,269 +0,0 @@
-/*
-* Copyright (C) 2013 Google Inc. All rights reserved.
-*
-* Redistribution and use in source and binary forms, with or without
-* modification, are permitted provided that the following conditions are
-* met:
-*
-* * Redistributions of source code must retain the above copyright
-* notice, this list of conditions and the following disclaimer.
-* * Redistributions in binary form must reproduce the above
-* copyright notice, this list of conditions and the following disclaimer
-* in the documentation and/or other materials provided with the
-* distribution.
-* * Neither the name of Google Inc. nor the names of its
-* contributors may be used to endorse or promote products derived from
-* this software without specific prior written permission.
-*
-* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-*/
-
-#ifndef TimelineTraceEventProcessor_h
-#define TimelineTraceEventProcessor_h
-
-
-#include "core/inspector/InspectorTimelineAgent.h"
-#include "core/platform/JSONValues.h"
-#include "wtf/HashMap.h"
-#include "wtf/Threading.h"
-#include "wtf/ThreadingPrimitives.h"
-#include "wtf/Vector.h"
-#include "wtf/WeakPtr.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class InspectorClient;
-class InspectorTimelineAgent;
-class Page;
-
-class TimelineRecordStack {
-private:
- struct Entry {
- Entry(PassRefPtr<JSONObject> record)
- : record(record)
- , children(JSONArray::create())
- {
- }
-
- RefPtr<JSONObject> record;
- RefPtr<JSONArray> children;
- };
-
-public:
- TimelineRecordStack() { }
- TimelineRecordStack(WeakPtr<InspectorTimelineAgent>);
-
- void addScopedRecord(PassRefPtr<JSONObject> record);
- void closeScopedRecord(double endTime);
- void addInstantRecord(PassRefPtr<JSONObject> record);
-
-#ifndef NDEBUG
- bool isOpenRecordOfType(const String& type);
-#endif
-
-private:
- void send(PassRefPtr<JSONObject>);
-
- WeakPtr<InspectorTimelineAgent> m_timelineAgent;
- Vector<Entry> m_stack;
-};
-
-class TimelineTraceEventProcessor : public ThreadSafeRefCounted<TimelineTraceEventProcessor> {
-public:
- // FIXME: re-use definitions in TraceEvent.h once it's promoted to all platforms.
- enum TraceEventPhase {
- TracePhaseBegin = 'B',
- TracePhaseEnd = 'E',
- TracePhaseInstant = 'I',
- TracePhaseCreateObject = 'N',
- TracePhaseDeleteObject = 'D'
- };
-
- TimelineTraceEventProcessor(WeakPtr<InspectorTimelineAgent>, InspectorClient*);
- ~TimelineTraceEventProcessor();
-
- void shutdown();
- void processEventOnAnyThread(TraceEventPhase, const char* name, unsigned long long id,
- int numArgs, const char* const* argNames, const unsigned char* argTypes, const unsigned long long* argValues,
- unsigned char flags);
-
-private:
- // FIXME: use the definition in TraceEvent.h once we expose the latter to all plaforms.
- union TraceValueUnion {
- bool m_bool;
- unsigned long long m_uint;
- long long m_int;
- double m_double;
- const void* m_pointer;
- const char* m_string;
- };
-
- enum TraceValueTypes {
- TypeBool = 1,
- TypeUInt = 2,
- TypeInt = 3,
- TypeDouble = 4,
- TypePointer = 5,
- TypeString = 6,
- TypeCopyString = 7
- };
-
- struct TimelineThreadState {
- TimelineThreadState() { }
-
- TimelineThreadState(WeakPtr<InspectorTimelineAgent> timelineAgent)
- : recordStack(timelineAgent)
- , inKnownLayerTask(false)
- {
- }
-
- TimelineRecordStack recordStack;
- bool inKnownLayerTask;
- };
-
- class TraceEvent {
- public:
- TraceEvent()
- : m_name(0)
- , m_argumentCount(0)
- {
- }
-
- TraceEvent(double timestamp, TraceEventPhase phase, const char* name, unsigned long long id, ThreadIdentifier threadIdentifier,
- int argumentCount, const char* const* argumentNames, const unsigned char* argumentTypes, const unsigned long long* argumentValues)
- : m_timestamp(timestamp)
- , m_phase(phase)
- , m_name(name)
- , m_id(id)
- , m_threadIdentifier(threadIdentifier)
- , m_argumentCount(argumentCount)
- {
- if (m_argumentCount > MaxArguments) {
- ASSERT_NOT_REACHED();
- m_argumentCount = MaxArguments;
- }
- for (int i = 0; i < m_argumentCount; ++i) {
- m_argumentNames[i] = argumentNames[i];
- m_argumentTypes[i] = argumentTypes[i];
- m_argumentValues[i] = argumentValues[i];
- }
- }
-
- double timestamp() const { return m_timestamp; }
- TraceEventPhase phase() const { return m_phase; }
- const char* name() const { return m_name; }
- unsigned long long id() const { return m_id; }
- ThreadIdentifier threadIdentifier() const { return m_threadIdentifier; }
- int argumentCount() const { return m_argumentCount; }
- bool isNull() const { return !m_name; }
-
- bool asBool(const char* name) const
- {
- return parameter(name, TypeBool).m_bool;
- }
- long long asInt(const char* name) const
- {
- size_t index = findParameter(name);
- if (index == kNotFound || (m_argumentTypes[index] != TypeInt && m_argumentTypes[index] != TypeUInt)) {
- ASSERT_NOT_REACHED();
- return 0;
- }
- return reinterpret_cast<const TraceValueUnion*>(m_argumentValues + index)->m_int;
- }
- unsigned long long asUInt(const char* name) const
- {
- return asInt(name);
- }
- double asDouble(const char* name) const
- {
- return parameter(name, TypeDouble).m_double;
- }
- const char* asString(const char* name) const
- {
- return parameter(name, TypeString).m_string;
- }
-
- private:
- enum { MaxArguments = 2 };
-
- size_t findParameter(const char*) const;
- const TraceValueUnion& parameter(const char* name, TraceValueTypes expectedType) const;
-
- double m_timestamp;
- TraceEventPhase m_phase;
- const char* m_name;
- unsigned long long m_id;
- ThreadIdentifier m_threadIdentifier;
- int m_argumentCount;
- const char* m_argumentNames[MaxArguments];
- unsigned char m_argumentTypes[MaxArguments];
- unsigned long long m_argumentValues[MaxArguments];
- };
-
- typedef void (TimelineTraceEventProcessor::*TraceEventHandler)(const TraceEvent&);
-
- TimelineThreadState& threadState(ThreadIdentifier thread)
- {
- ThreadStateMap::iterator it = m_threadStates.find(thread);
- if (it != m_threadStates.end())
- return it->value;
- return m_threadStates.add(thread, TimelineThreadState(m_timelineAgent)).iterator->value;
- }
- bool maybeEnterLayerTask(const TraceEvent&, TimelineThreadState&);
- void leaveLayerTask(TimelineThreadState&);
-
- void processBackgroundEvents();
- PassRefPtr<JSONObject> createRecord(const TraceEvent&, const String& recordType, PassRefPtr<JSONObject> data = 0);
-
- void registerHandler(const char* name, TraceEventPhase, TraceEventHandler);
-
- void onBeginFrame(const TraceEvent&);
- void onUpdateLayerBegin(const TraceEvent&);
- void onUpdateLayerEnd(const TraceEvent&);
- void onPaintLayerBegin(const TraceEvent&);
- void onPaintLayerEnd(const TraceEvent&);
- void onPaintSetupBegin(const TraceEvent&);
- void onPaintSetupEnd(const TraceEvent&);
- void onRasterTaskBegin(const TraceEvent&);
- void onRasterTaskEnd(const TraceEvent&);
- void onPaint(const TraceEvent&);
- void onImageDecodeTaskBegin(const TraceEvent&);
- void onImageDecodeTaskEnd(const TraceEvent&);
- void onImageDecodeBegin(const TraceEvent&);
- void onImageDecodeEnd(const TraceEvent&);
- void onLayerDeleted(const TraceEvent&);
-
- WeakPtr<InspectorTimelineAgent> m_timelineAgent;
- TimelineTimeConverter m_timeConverter;
- InspectorClient* m_inspectorClient;
- unsigned long long m_pageId;
- int m_layerTreeId;
-
- typedef HashMap<std::pair<String, int>, TraceEventHandler> HandlersMap;
- HandlersMap m_handlersByType;
- Mutex m_backgroundEventsMutex;
- Vector<TraceEvent> m_backgroundEvents;
-
- typedef HashMap<ThreadIdentifier, TimelineThreadState> ThreadStateMap;
- ThreadStateMap m_threadStates;
-
- HashMap<unsigned long long, long long> m_layerToNodeMap;
- unsigned long long m_layerId;
- double m_paintSetupStart;
- double m_paintSetupEnd;
-};
-
-} // namespace WebCore
-
-#endif // !defined(TimelineTraceEventProcessor_h)
diff --git a/chromium/third_party/WebKit/Source/core/inspector/TraceEventDispatcher.cpp b/chromium/third_party/WebKit/Source/core/inspector/TraceEventDispatcher.cpp
new file mode 100644
index 00000000000..bdfbea6fe58
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/inspector/TraceEventDispatcher.cpp
@@ -0,0 +1,159 @@
+/*
+* Copyright (C) 2013 Google Inc. All rights reserved.
+*
+* Redistribution and use in source and binary forms, with or without
+* modification, are permitted provided that the following conditions are
+* met:
+*
+* * Redistributions of source code must retain the above copyright
+* notice, this list of conditions and the following disclaimer.
+* * Redistributions in binary form must reproduce the above
+* copyright notice, this list of conditions and the following disclaimer
+* in the documentation and/or other materials provided with the
+* distribution.
+* * Neither the name of Google Inc. nor the names of its
+* contributors may be used to endorse or promote products derived from
+* this software without specific prior written permission.
+*
+* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+#include "config.h"
+#include "core/inspector/TraceEventDispatcher.h"
+
+#include "core/inspector/InspectorClient.h"
+#include "wtf/CurrentTime.h"
+#include "wtf/Functional.h"
+#include "wtf/MainThread.h"
+#include "wtf/text/StringHash.h"
+
+namespace WebCore {
+
+void TraceEventDispatcher::dispatchEventOnAnyThread(char phase, const unsigned char*, const char* name, unsigned long long id,
+ int numArgs, const char* const* argNames, const unsigned char* argTypes, const unsigned long long* argValues,
+ unsigned char flags, double timestamp)
+{
+ if (phase == TRACE_EVENT_PHASE_INSTANT_WITH_SCOPE)
+ phase = TRACE_EVENT_PHASE_INSTANT;
+ TraceEventDispatcher* self = instance();
+ {
+ MutexLocker locker(self->m_mutex);
+ if (self->m_handlers.find(std::make_pair(name, phase)) == self->m_handlers.end())
+ return;
+ }
+ self->enqueueEvent(TraceEvent(timestamp, phase, name, id, currentThread(), numArgs, argNames, argTypes, argValues));
+ if (isMainThread())
+ self->processBackgroundEvents();
+}
+
+void TraceEventDispatcher::enqueueEvent(const TraceEvent& event)
+{
+ const float eventProcessingThresholdInSeconds = 0.1;
+ {
+ MutexLocker locker(m_mutex);
+ m_backgroundEvents.append(event);
+ if (m_processEventsTaskInFlight || event.timestamp() - m_lastEventProcessingTime <= eventProcessingThresholdInSeconds)
+ return;
+ }
+ m_processEventsTaskInFlight = true;
+ callOnMainThread(bind(&TraceEventDispatcher::processBackgroundEventsTask, this));
+}
+
+void TraceEventDispatcher::processBackgroundEventsTask()
+{
+ m_processEventsTaskInFlight = false;
+ processBackgroundEvents();
+}
+
+void TraceEventDispatcher::processBackgroundEvents()
+{
+ ASSERT(isMainThread());
+ Vector<TraceEvent> events;
+ {
+ MutexLocker locker(m_mutex);
+ m_lastEventProcessingTime = WTF::monotonicallyIncreasingTime();
+ if (m_backgroundEvents.isEmpty())
+ return;
+ events.reserveCapacity(m_backgroundEvents.capacity());
+ m_backgroundEvents.swap(events);
+ }
+ for (size_t eventIndex = 0, size = events.size(); eventIndex < size; ++eventIndex) {
+ const TraceEvent& event = events[eventIndex];
+ HandlersMap::iterator it = m_handlers.find(std::make_pair(event.name(), event.phase()));
+ if (it == m_handlers.end())
+ continue;
+ Vector<BoundTraceEventHandler>& handlers = it->value;
+ for (size_t handlerIndex = 0; handlerIndex < handlers.size(); ++handlerIndex)
+ (handlers[handlerIndex].instance->*(handlers[handlerIndex].method))(event);
+ }
+}
+
+void TraceEventDispatcher::innerAddListener(const char* name, char phase, TraceEventTargetBase* instance, TraceEventHandlerMethod method, InspectorClient* client)
+{
+ ASSERT(isMainThread());
+ MutexLocker locker(m_mutex);
+ if (m_handlers.isEmpty())
+ client->setTraceEventCallback(dispatchEventOnAnyThread);
+ HandlersMap::iterator it = m_handlers.find(std::make_pair(name, phase));
+ if (it == m_handlers.end())
+ it = m_handlers.add(std::make_pair(name, phase), Vector<BoundTraceEventHandler>()).iterator;
+ it->value.append(BoundTraceEventHandler(instance, method));
+}
+
+void TraceEventDispatcher::removeAllListeners(TraceEventTargetBase* instance, InspectorClient* client)
+{
+ ASSERT(isMainThread());
+ processBackgroundEvents();
+ {
+ MutexLocker locker(m_mutex);
+
+ HandlersMap remainingHandlers;
+ for (HandlersMap::iterator it = m_handlers.begin(); it != m_handlers.end(); ++it) {
+ Vector<BoundTraceEventHandler>& handlers = it->value;
+ for (size_t j = 0; j < handlers.size();) {
+ if (handlers[j].instance == instance)
+ handlers.remove(j);
+ else
+ ++j;
+ }
+ if (!handlers.isEmpty())
+ remainingHandlers.add(it->key, it->value);
+ }
+ m_handlers.swap(remainingHandlers);
+ }
+ if (m_handlers.isEmpty())
+ client->setTraceEventCallback(0);
+}
+
+size_t TraceEventDispatcher::TraceEvent::findParameter(const char* name) const
+{
+ for (int i = 0; i < m_argumentCount; ++i) {
+ if (!strcmp(name, m_argumentNames[i]))
+ return i;
+ }
+ return kNotFound;
+}
+
+const TraceEvent::TraceValueUnion& TraceEventDispatcher::TraceEvent::parameter(const char* name, unsigned char expectedType) const
+{
+ static WebCore::TraceEvent::TraceValueUnion missingValue;
+ size_t index = findParameter(name);
+ if (index == kNotFound || m_argumentTypes[index] != expectedType) {
+ ASSERT_NOT_REACHED();
+ return missingValue;
+ }
+ return *reinterpret_cast<const WebCore::TraceEvent::TraceValueUnion*>(m_argumentValues + index);
+}
+
+} // namespace WebCore
+
diff --git a/chromium/third_party/WebKit/Source/core/inspector/TraceEventDispatcher.h b/chromium/third_party/WebKit/Source/core/inspector/TraceEventDispatcher.h
new file mode 100644
index 00000000000..22e14e750ee
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/inspector/TraceEventDispatcher.h
@@ -0,0 +1,192 @@
+/*
+* Copyright (C) 2013 Google Inc. All rights reserved.
+*
+* Redistribution and use in source and binary forms, with or without
+* modification, are permitted provided that the following conditions are
+* met:
+*
+* * Redistributions of source code must retain the above copyright
+* notice, this list of conditions and the following disclaimer.
+* * Redistributions in binary form must reproduce the above
+* copyright notice, this list of conditions and the following disclaimer
+* in the documentation and/or other materials provided with the
+* distribution.
+* * Neither the name of Google Inc. nor the names of its
+* contributors may be used to endorse or promote products derived from
+* this software without specific prior written permission.
+*
+* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+#ifndef TraceEventDispatcher_h
+#define TraceEventDispatcher_h
+
+#include "platform/TraceEvent.h"
+#include "wtf/HashMap.h"
+#include "wtf/Threading.h"
+#include "wtf/ThreadingPrimitives.h"
+#include "wtf/Vector.h"
+#include "wtf/text/WTFString.h"
+
+namespace WebCore {
+
+class InspectorClient;
+
+struct TraceEventTargetBase {
+ virtual ~TraceEventTargetBase() { }
+};
+
+template<typename C> struct TraceEventTarget;
+
+class TraceEventDispatcher {
+ WTF_MAKE_NONCOPYABLE(TraceEventDispatcher);
+public:
+ class TraceEvent {
+ public:
+ TraceEvent()
+ : m_name(0)
+ , m_argumentCount(0)
+ {
+ }
+
+ TraceEvent(double timestamp, char phase, const char* name, unsigned long long id, ThreadIdentifier threadIdentifier,
+ int argumentCount, const char* const* argumentNames, const unsigned char* argumentTypes, const unsigned long long* argumentValues)
+ : m_timestamp(timestamp)
+ , m_phase(phase)
+ , m_name(name)
+ , m_id(id)
+ , m_threadIdentifier(threadIdentifier)
+ , m_argumentCount(argumentCount)
+ {
+ if (m_argumentCount > MaxArguments) {
+ ASSERT_NOT_REACHED();
+ m_argumentCount = MaxArguments;
+ }
+ for (int i = 0; i < m_argumentCount; ++i) {
+ m_argumentNames[i] = argumentNames[i];
+ m_argumentTypes[i] = argumentTypes[i];
+ m_argumentValues[i] = argumentValues[i];
+ }
+ }
+
+ double timestamp() const { return m_timestamp; }
+ char phase() const { return m_phase; }
+ const char* name() const { return m_name; }
+ unsigned long long id() const { return m_id; }
+ ThreadIdentifier threadIdentifier() const { return m_threadIdentifier; }
+ int argumentCount() const { return m_argumentCount; }
+ bool isNull() const { return !m_name; }
+
+ bool asBool(const char* name) const
+ {
+ return parameter(name, TRACE_VALUE_TYPE_BOOL).m_bool;
+ }
+ long long asInt(const char* name) const
+ {
+ size_t index = findParameter(name);
+ if (index == kNotFound || (m_argumentTypes[index] != TRACE_VALUE_TYPE_INT && m_argumentTypes[index] != TRACE_VALUE_TYPE_UINT)) {
+ ASSERT_NOT_REACHED();
+ return 0;
+ }
+ return reinterpret_cast<const WebCore::TraceEvent::TraceValueUnion*>(m_argumentValues + index)->m_int;
+ }
+ unsigned long long asUInt(const char* name) const
+ {
+ return asInt(name);
+ }
+ double asDouble(const char* name) const
+ {
+ return parameter(name, TRACE_VALUE_TYPE_DOUBLE).m_double;
+ }
+ const char* asString(const char* name) const
+ {
+ return parameter(name, TRACE_VALUE_TYPE_STRING).m_string;
+ }
+
+ private:
+ enum { MaxArguments = 2 };
+
+ size_t findParameter(const char*) const;
+ const WebCore::TraceEvent::TraceValueUnion& parameter(const char* name, unsigned char expectedType) const;
+
+ double m_timestamp;
+ char m_phase;
+ const char* m_name;
+ unsigned long long m_id;
+ ThreadIdentifier m_threadIdentifier;
+ int m_argumentCount;
+ const char* m_argumentNames[MaxArguments];
+ unsigned char m_argumentTypes[MaxArguments];
+ unsigned long long m_argumentValues[MaxArguments];
+ };
+
+ typedef void (TraceEventTargetBase::*TraceEventHandlerMethod)(const TraceEvent&);
+
+ static TraceEventDispatcher* instance()
+ {
+ DEFINE_STATIC_LOCAL(TraceEventDispatcher, instance, ());
+ return &instance;
+ }
+
+ template<typename ListenerClass>
+ void addListener(const char* name, char phase, ListenerClass* instance, typename TraceEventTarget<ListenerClass>::TraceEventHandler handler, InspectorClient* client)
+ {
+ innerAddListener(name, phase, instance, static_cast<TraceEventHandlerMethod>(handler), client);
+ }
+
+ void removeAllListeners(TraceEventTargetBase*, InspectorClient*);
+ void processBackgroundEvents();
+
+private:
+ struct BoundTraceEventHandler {
+ TraceEventTargetBase* instance;
+ TraceEventHandlerMethod method;
+
+ BoundTraceEventHandler() : instance(0), method(0) { }
+ BoundTraceEventHandler(TraceEventTargetBase* instance, TraceEventHandlerMethod method)
+ : instance(instance)
+ , method(method)
+ {
+ }
+ };
+ typedef std::pair<String, int> EventSelector;
+ typedef HashMap<EventSelector, Vector<BoundTraceEventHandler> > HandlersMap;
+
+ TraceEventDispatcher()
+ : m_processEventsTaskInFlight(false)
+ , m_lastEventProcessingTime(0)
+ {
+ }
+
+ static void dispatchEventOnAnyThread(char phase, const unsigned char*, const char* name, unsigned long long id,
+ int numArgs, const char* const* argNames, const unsigned char* argTypes, const unsigned long long* argValues,
+ unsigned char flags, double timestamp);
+
+ void enqueueEvent(const TraceEvent&);
+ void innerAddListener(const char* name, char phase, TraceEventTargetBase*, TraceEventHandlerMethod, InspectorClient*);
+ void processBackgroundEventsTask();
+
+ Mutex m_mutex;
+ HandlersMap m_handlers;
+ Vector<TraceEvent> m_backgroundEvents;
+ bool m_processEventsTaskInFlight;
+ double m_lastEventProcessingTime;
+};
+
+template<typename C> struct TraceEventTarget : public TraceEventTargetBase {
+ typedef void (C::*TraceEventHandler)(const TraceEventDispatcher::TraceEvent&);
+};
+
+} // namespace WebCore
+
+#endif // TraceEventDispatcher_h
diff --git a/chromium/third_party/WebKit/Source/core/inspector/WorkerDebuggerAgent.cpp b/chromium/third_party/WebKit/Source/core/inspector/WorkerDebuggerAgent.cpp
index 0af72efb770..271c306e156 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/WorkerDebuggerAgent.cpp
+++ b/chromium/third_party/WebKit/Source/core/inspector/WorkerDebuggerAgent.cpp
@@ -76,7 +76,7 @@ private:
} // namespace
-const char* WorkerDebuggerAgent::debuggerTaskMode = "debugger";
+const char WorkerDebuggerAgent::debuggerTaskMode[] = "debugger";
PassOwnPtr<WorkerDebuggerAgent> WorkerDebuggerAgent::create(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* inspectorState, WorkerScriptDebugServer* scriptDebugServer, WorkerGlobalScope* inspectedWorkerGlobalScope, InjectedScriptManager* injectedScriptManager)
{
diff --git a/chromium/third_party/WebKit/Source/core/inspector/WorkerDebuggerAgent.h b/chromium/third_party/WebKit/Source/core/inspector/WorkerDebuggerAgent.h
index 3974ade57f9..dee9dbf8e24 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/WorkerDebuggerAgent.h
+++ b/chromium/third_party/WebKit/Source/core/inspector/WorkerDebuggerAgent.h
@@ -46,7 +46,7 @@ public:
static PassOwnPtr<WorkerDebuggerAgent> create(InstrumentingAgents*, InspectorCompositeState*, WorkerScriptDebugServer*, WorkerGlobalScope*, InjectedScriptManager*);
virtual ~WorkerDebuggerAgent();
- static const char* debuggerTaskMode;
+ static const char debuggerTaskMode[];
static void interruptAndDispatchInspectorCommands(WorkerThread*);
private:
diff --git a/chromium/third_party/WebKit/Source/core/inspector/WorkerInspectorController.cpp b/chromium/third_party/WebKit/Source/core/inspector/WorkerInspectorController.cpp
index 6761fd77db9..3fac1b3c6e2 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/WorkerInspectorController.cpp
+++ b/chromium/third_party/WebKit/Source/core/inspector/WorkerInspectorController.cpp
@@ -97,14 +97,13 @@ WorkerInspectorController::WorkerInspectorController(WorkerGlobalScope* workerGl
{
m_agents.append(WorkerRuntimeAgent::create(m_instrumentingAgents.get(), m_state.get(), m_injectedScriptManager.get(), m_debugServer.get(), workerGlobalScope));
- OwnPtr<InspectorTimelineAgent> timelineAgent = InspectorTimelineAgent::create(m_instrumentingAgents.get(), 0, 0, 0, m_state.get(), InspectorTimelineAgent::WorkerInspector, 0);
- OwnPtr<InspectorConsoleAgent> consoleAgent = WorkerConsoleAgent::create(m_instrumentingAgents.get(), timelineAgent.get(), m_state.get(), m_injectedScriptManager.get());
+ OwnPtr<InspectorTimelineAgent> timelineAgent = InspectorTimelineAgent::create(m_instrumentingAgents.get(), 0, 0, 0, 0, m_state.get(), InspectorTimelineAgent::WorkerInspector, 0);
m_agents.append(WorkerDebuggerAgent::create(m_instrumentingAgents.get(), m_state.get(), m_debugServer.get(), workerGlobalScope, m_injectedScriptManager.get()));
- m_agents.append(InspectorProfilerAgent::create(m_instrumentingAgents.get(), consoleAgent.get(), m_state.get(), m_injectedScriptManager.get()));
+ m_agents.append(InspectorProfilerAgent::create(m_instrumentingAgents.get(), m_state.get(), m_injectedScriptManager.get(), 0));
m_agents.append(InspectorHeapProfilerAgent::create(m_instrumentingAgents.get(), m_state.get(), m_injectedScriptManager.get()));
+ m_agents.append(WorkerConsoleAgent::create(m_instrumentingAgents.get(), timelineAgent.get(), m_state.get(), m_injectedScriptManager.get()));
m_agents.append(timelineAgent.release());
- m_agents.append(consoleAgent.release());
m_injectedScriptManager->injectedScriptHost()->init(m_instrumentingAgents.get(), m_debugServer.get());
}
diff --git a/chromium/third_party/WebKit/Source/core/inspector/WorkerInspectorController.h b/chromium/third_party/WebKit/Source/core/inspector/WorkerInspectorController.h
index cc639e932e1..3e06e99ef7e 100644
--- a/chromium/third_party/WebKit/Source/core/inspector/WorkerInspectorController.h
+++ b/chromium/third_party/WebKit/Source/core/inspector/WorkerInspectorController.h
@@ -57,7 +57,6 @@ public:
WorkerInspectorController(WorkerGlobalScope*);
~WorkerInspectorController();
- bool hasFrontend() const { return m_frontend; }
void connectFrontend();
void disconnectFrontend();
void restoreInspectorStateFromCookie(const String& inspectorCookie);
diff --git a/chromium/third_party/WebKit/Source/core/loader/CookieJar.cpp b/chromium/third_party/WebKit/Source/core/loader/CookieJar.cpp
index 9d6821adf77..4ba0ca173d5 100644
--- a/chromium/third_party/WebKit/Source/core/loader/CookieJar.cpp
+++ b/chromium/third_party/WebKit/Source/core/loader/CookieJar.cpp
@@ -33,8 +33,8 @@
#include "core/dom/Document.h"
#include "core/loader/FrameLoaderClient.h"
-#include "core/page/Frame.h"
-#include "core/platform/Cookie.h"
+#include "core/frame/Frame.h"
+#include "platform/Cookie.h"
#include "public/platform/Platform.h"
#include "public/platform/WebCookie.h"
#include "public/platform/WebCookieJar.h"
@@ -43,21 +43,21 @@
namespace WebCore {
-static WebKit::WebCookieJar* toCookieJar(const Document* document)
+static blink::WebCookieJar* toCookieJar(const Document* document)
{
if (!document || !document->frame())
return 0;
- WebKit::WebCookieJar* cookieJar = document->frame()->loader()->client()->cookieJar();
+ blink::WebCookieJar* cookieJar = document->frame()->loader().client()->cookieJar();
// FIXME: DRT depends on being able to get a cookie jar from Platform rather than
// FrameLoaderClient. Delete this when DRT is deleted.
if (!cookieJar)
- cookieJar = WebKit::Platform::current()->cookieJar();
+ cookieJar = blink::Platform::current()->cookieJar();
return cookieJar;
}
String cookies(const Document* document, const KURL& url)
{
- WebKit::WebCookieJar* cookieJar = toCookieJar(document);
+ blink::WebCookieJar* cookieJar = toCookieJar(document);
if (!cookieJar)
return String();
return cookieJar->cookies(url, document->firstPartyForCookies());
@@ -65,7 +65,7 @@ String cookies(const Document* document, const KURL& url)
void setCookies(Document* document, const KURL& url, const String& cookieString)
{
- WebKit::WebCookieJar* cookieJar = toCookieJar(document);
+ blink::WebCookieJar* cookieJar = toCookieJar(document);
if (!cookieJar)
return;
cookieJar->setCookie(url, document->firstPartyForCookies(), cookieString);
@@ -73,7 +73,7 @@ void setCookies(Document* document, const KURL& url, const String& cookieString)
bool cookiesEnabled(const Document* document)
{
- WebKit::WebCookieJar* cookieJar = toCookieJar(document);
+ blink::WebCookieJar* cookieJar = toCookieJar(document);
if (!cookieJar)
return false;
return cookieJar->cookiesEnabled(document->cookieURL(), document->firstPartyForCookies());
@@ -81,7 +81,7 @@ bool cookiesEnabled(const Document* document)
String cookieRequestHeaderFieldValue(const Document* document, const KURL& url)
{
- WebKit::WebCookieJar* cookieJar = toCookieJar(document);
+ blink::WebCookieJar* cookieJar = toCookieJar(document);
if (!cookieJar)
return String();
return cookieJar->cookieRequestHeaderFieldValue(url, document->firstPartyForCookies());
@@ -90,13 +90,13 @@ String cookieRequestHeaderFieldValue(const Document* document, const KURL& url)
bool getRawCookies(const Document* document, const KURL& url, Vector<Cookie>& cookies)
{
cookies.clear();
- WebKit::WebCookieJar* cookieJar = toCookieJar(document);
+ blink::WebCookieJar* cookieJar = toCookieJar(document);
if (!cookieJar)
return false;
- WebKit::WebVector<WebKit::WebCookie> webCookies;
+ blink::WebVector<blink::WebCookie> webCookies;
cookieJar->rawCookies(url, document->firstPartyForCookies(), webCookies);
for (unsigned i = 0; i < webCookies.size(); ++i) {
- const WebKit::WebCookie& webCookie = webCookies[i];
+ const blink::WebCookie& webCookie = webCookies[i];
cookies.append(Cookie(webCookie.name, webCookie.value, webCookie.domain, webCookie.path,
webCookie.expires, webCookie.httpOnly, webCookie.secure, webCookie.session));
}
@@ -105,7 +105,7 @@ bool getRawCookies(const Document* document, const KURL& url, Vector<Cookie>& co
void deleteCookie(const Document* document, const KURL& url, const String& cookieName)
{
- WebKit::WebCookieJar* cookieJar = toCookieJar(document);
+ blink::WebCookieJar* cookieJar = toCookieJar(document);
if (!cookieJar)
return;
cookieJar->deleteCookie(url, cookieName);
diff --git a/chromium/third_party/WebKit/Source/core/loader/CrossOriginPreflightResultCache.cpp b/chromium/third_party/WebKit/Source/core/loader/CrossOriginPreflightResultCache.cpp
index c3f82abc12e..460e2e9f826 100644
--- a/chromium/third_party/WebKit/Source/core/loader/CrossOriginPreflightResultCache.cpp
+++ b/chromium/third_party/WebKit/Source/core/loader/CrossOriginPreflightResultCache.cpp
@@ -28,7 +28,7 @@
#include "core/loader/CrossOriginPreflightResultCache.h"
#include "core/fetch/CrossOriginAccessControl.h"
-#include "core/platform/network/ResourceResponse.h"
+#include "platform/network/ResourceResponse.h"
#include "wtf/CurrentTime.h"
#include "wtf/MainThread.h"
#include "wtf/StdLibExtras.h"
diff --git a/chromium/third_party/WebKit/Source/core/loader/CrossOriginPreflightResultCache.h b/chromium/third_party/WebKit/Source/core/loader/CrossOriginPreflightResultCache.h
index 3911a2c1373..1c65c968c22 100644
--- a/chromium/third_party/WebKit/Source/core/loader/CrossOriginPreflightResultCache.h
+++ b/chromium/third_party/WebKit/Source/core/loader/CrossOriginPreflightResultCache.h
@@ -28,7 +28,7 @@
#define CrossOriginPreflightResultCache_h
#include "core/fetch/ResourceLoaderOptions.h"
-#include "weborigin/KURLHash.h"
+#include "platform/weborigin/KURLHash.h"
#include "wtf/HashMap.h"
#include "wtf/HashSet.h"
#include "wtf/PassOwnPtr.h"
diff --git a/chromium/third_party/WebKit/Source/core/loader/DocumentLoadTiming.cpp b/chromium/third_party/WebKit/Source/core/loader/DocumentLoadTiming.cpp
index a9115f00291..6204ca61357 100644
--- a/chromium/third_party/WebKit/Source/core/loader/DocumentLoadTiming.cpp
+++ b/chromium/third_party/WebKit/Source/core/loader/DocumentLoadTiming.cpp
@@ -26,8 +26,7 @@
#include "config.h"
#include "core/loader/DocumentLoadTiming.h"
-#include "weborigin/SecurityOrigin.h"
-#include "wtf/CurrentTime.h"
+#include "platform/weborigin/SecurityOrigin.h"
#include "wtf/RefPtr.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/loader/DocumentLoader.cpp b/chromium/third_party/WebKit/Source/core/loader/DocumentLoader.cpp
index 11f05e28e92..79122f88347 100644
--- a/chromium/third_party/WebKit/Source/core/loader/DocumentLoader.cpp
+++ b/chromium/third_party/WebKit/Source/core/loader/DocumentLoader.cpp
@@ -31,11 +31,9 @@
#include "core/loader/DocumentLoader.h"
#include "FetchInitiatorTypeNames.h"
-#include "bindings/v8/ScriptController.h"
-#include "core/dom/DOMImplementation.h"
#include "core/dom/Document.h"
#include "core/dom/DocumentParser.h"
-#include "core/dom/Event.h"
+#include "core/events/Event.h"
#include "core/fetch/FetchContext.h"
#include "core/fetch/MemoryCache.h"
#include "core/fetch/ResourceFetcher.h"
@@ -43,25 +41,25 @@
#include "core/fetch/TextResourceDecoder.h"
#include "core/html/HTMLFrameOwnerElement.h"
#include "core/inspector/InspectorInstrumentation.h"
-#include "core/loader/DocumentWriter.h"
#include "core/loader/FrameLoader.h"
#include "core/loader/FrameLoaderClient.h"
-#include "core/loader/SinkDocument.h"
#include "core/loader/UniqueIdentifier.h"
#include "core/loader/appcache/ApplicationCacheHost.h"
-#include "core/loader/archive/ArchiveResourceCollection.h"
-#include "core/loader/archive/MHTMLArchive.h"
-#include "core/page/DOMWindow.h"
-#include "core/page/Frame.h"
+#include "core/frame/ContentSecurityPolicy.h"
+#include "core/frame/DOMWindow.h"
+#include "core/frame/Frame.h"
#include "core/page/FrameTree.h"
#include "core/page/Page.h"
-#include "core/page/Settings.h"
-#include "core/platform/Logging.h"
-#include "core/plugins/PluginData.h"
+#include "core/frame/Settings.h"
+#include "platform/Logging.h"
+#include "platform/UserGestureIndicator.h"
+#include "platform/mhtml/ArchiveResourceCollection.h"
+#include "platform/mhtml/MHTMLArchive.h"
+#include "platform/plugins/PluginData.h"
+#include "platform/weborigin/SchemeRegistry.h"
+#include "platform/weborigin/SecurityPolicy.h"
#include "public/platform/Platform.h"
#include "public/platform/WebMimeRegistry.h"
-#include "weborigin/SchemeRegistry.h"
-#include "weborigin/SecurityPolicy.h"
#include "wtf/Assertions.h"
#include "wtf/text/WTFString.h"
@@ -95,7 +93,7 @@ FrameLoader* DocumentLoader::frameLoader() const
{
if (!m_frame)
return 0;
- return m_frame->loader();
+ return &m_frame->loader();
}
ResourceLoader* DocumentLoader::mainResourceLoader() const
@@ -127,7 +125,7 @@ unsigned long DocumentLoader::mainResourceIdentifier() const
Document* DocumentLoader::document() const
{
- if (m_frame && m_frame->loader()->documentLoader() == this)
+ if (m_frame && m_frame->loader().documentLoader() == this)
return m_frame->document();
return 0;
}
@@ -157,10 +155,20 @@ const KURL& DocumentLoader::url() const
return request().url();
}
-void DocumentLoader::replaceRequestURLForSameDocumentNavigation(const KURL& url)
+void DocumentLoader::updateForSameDocumentNavigation(const KURL& newURL)
{
- m_originalRequestCopy.setURL(url);
- m_request.setURL(url);
+ KURL oldURL = m_request.url();
+ m_originalRequestCopy.setURL(newURL);
+ m_request.setURL(newURL);
+ clearRedirectChain();
+ if (m_isClientRedirect)
+ appendRedirect(oldURL);
+ appendRedirect(newURL);
+}
+
+bool DocumentLoader::isURLValidForNewHistoryEntry() const
+{
+ return !originalRequest().url().isEmpty() || !unreachableURL().isEmpty();
}
void DocumentLoader::setRequest(const ResourceRequest& req)
@@ -190,7 +198,7 @@ void DocumentLoader::setMainDocumentError(const ResourceError& error)
void DocumentLoader::mainReceivedError(const ResourceError& error)
{
ASSERT(!error.isNull());
- ASSERT(!mainResourceLoader() || !mainResourceLoader()->defersLoading());
+ ASSERT(!mainResourceLoader() || !mainResourceLoader()->defersLoading() || InspectorInstrumentation::isDebuggerPaused(m_frame));
m_applicationCacheHost->failedLoadingMainResource();
if (!frameLoader())
return;
@@ -220,7 +228,7 @@ void DocumentLoader::stopLoading()
Document* doc = m_frame->document();
if (loading || doc->parsing())
- m_frame->loader()->stopLoading();
+ m_frame->loader().stopLoading();
}
clearArchiveResources();
@@ -337,7 +345,7 @@ bool DocumentLoader::isRedirectAfterPost(const ResourceRequest& newRequest, cons
void DocumentLoader::handleSubstituteDataLoadNow(DocumentLoaderTimer*)
{
RefPtr<DocumentLoader> protect(this);
- ResourceResponse response(m_request.url(), m_substituteData.mimeType(), m_substituteData.content()->size(), m_substituteData.textEncoding(), "");
+ ResourceResponse response(m_request.url(), m_substituteData.mimeType(), m_substituteData.content()->size(), m_substituteData.textEncoding(), emptyString());
responseReceived(0, response);
if (m_substituteData.content()->size())
dataReceived(0, m_substituteData.content()->data(), m_substituteData.content()->size());
@@ -373,15 +381,14 @@ bool DocumentLoader::shouldContinueForNavigationPolicy(const ResourceRequest& re
if (m_frame->ownerElement() && !m_frame->ownerElement()->document().contentSecurityPolicy()->allowChildFrameFromSource(request.url()))
return false;
- NavigationPolicy policy = NavigationPolicyCurrentTab;
- m_triggeringAction.specifiesNavigationPolicy(&policy);
+ NavigationPolicy policy = m_triggeringAction.policy();
if (policyCheckLoadType != PolicyCheckFragment)
policy = frameLoader()->client()->decidePolicyForNavigation(request, this, policy);
if (policy == NavigationPolicyCurrentTab)
return true;
if (policy == NavigationPolicyIgnore)
return false;
- if (!DOMWindow::allowPopUp(m_frame) && !ScriptController::processingUserGesture())
+ if (!DOMWindow::allowPopUp(m_frame) && !UserGestureIndicator::processingUserGesture())
return false;
frameLoader()->client()->loadURLExternally(request, policy);
return false;
@@ -434,9 +441,9 @@ void DocumentLoader::willSendRequest(ResourceRequest& newRequest, const Resource
if (newRequest.cachePolicy() == UseProtocolCachePolicy && isRedirectAfterPost(newRequest, redirectResponse))
newRequest.setCachePolicy(ReloadIgnoringCacheData);
- Frame* parent = m_frame->tree()->parent();
+ Frame* parent = m_frame->tree().parent();
if (parent) {
- if (!parent->loader()->mixedContentChecker()->canRunInsecureContent(parent->document()->securityOrigin(), newRequest.url())) {
+ if (!parent->loader().mixedContentChecker()->canRunInsecureContent(parent->document()->securityOrigin(), newRequest.url())) {
cancelMainResourceLoad(ResourceError::cancelledError(newRequest.url()));
return;
}
@@ -455,7 +462,7 @@ void DocumentLoader::willSendRequest(ResourceRequest& newRequest, const Resource
static bool canShowMIMEType(const String& mimeType, Page* page)
{
- if (WebKit::Platform::current()->mimeRegistry()->supportsMIMEType(mimeType) == WebKit::WebMimeRegistry::IsSupported)
+ if (blink::Platform::current()->mimeRegistry()->supportsMIMEType(mimeType) == blink::WebMimeRegistry::IsSupported)
return true;
PluginData* pluginData = page->pluginData();
return !mimeType.isEmpty() && pluginData && pluginData->supportsMimeType(mimeType);
@@ -515,7 +522,7 @@ void DocumentLoader::responseReceived(Resource* resource, const ResourceResponse
frame()->document()->addConsoleMessageWithRequestIdentifier(SecurityMessageSource, ErrorMessageLevel, message, identifier);
frame()->document()->enforceSandboxFlags(SandboxOrigin);
if (HTMLFrameOwnerElement* ownerElement = frame()->ownerElement())
- ownerElement->dispatchEvent(Event::create(eventNames().loadEvent));
+ ownerElement->dispatchEvent(Event::create(EventTypeNames::load));
// The load event might have detached this frame. In that case, the load will already have been cancelled during detach.
if (frameLoader())
@@ -556,13 +563,12 @@ void DocumentLoader::ensureWriter()
ensureWriter(m_response.mimeType());
}
-void DocumentLoader::ensureWriter(const String& mimeType, const KURL& overridingURL)
+void DocumentLoader::ensureWriter(const AtomicString& mimeType, const KURL& overridingURL)
{
if (m_writer)
return;
- String encoding = overrideEncoding().isNull() ? response().textEncodingName().impl() : overrideEncoding();
- bool userChosen = !overrideEncoding().isNull();
+ const AtomicString& encoding = overrideEncoding().isNull() ? response().textEncodingName() : overrideEncoding();
m_writer = createWriterFor(m_frame, 0, requestURL(), mimeType, encoding, false, false);
m_writer->setDocumentWasLoadedAsPartOfNavigation();
// This should be set before receivedFirstData().
@@ -682,6 +688,8 @@ bool DocumentLoader::isLoadingInAPISense() const
return true;
if (m_fetcher->requestCount())
return true;
+ if (doc->isDelayingLoadEvent() && !doc->loadEventFinished())
+ return true;
if (doc->processingLoadEvent())
return true;
if (doc->hasActiveParser())
@@ -715,14 +723,14 @@ void DocumentLoader::addAllArchiveResources(MHTMLArchive* archive)
void DocumentLoader::prepareSubframeArchiveLoadIfNeeded()
{
- if (!m_frame->tree()->parent())
+ if (!m_frame->tree().parent())
return;
- ArchiveResourceCollection* parentCollection = m_frame->tree()->parent()->loader()->documentLoader()->m_archiveResourceCollection.get();
+ ArchiveResourceCollection* parentCollection = m_frame->tree().parent()->loader().documentLoader()->m_archiveResourceCollection.get();
if (!parentCollection)
return;
- m_archive = parentCollection->popSubframeArchive(m_frame->tree()->uniqueName(), m_request.url());
+ m_archive = parentCollection->popSubframeArchive(m_frame->tree().uniqueName(), m_request.url());
if (!m_archive)
return;
@@ -758,17 +766,6 @@ bool DocumentLoader::scheduleArchiveLoad(Resource* cachedResource, const Resourc
return true;
}
-KURL DocumentLoader::urlForHistory() const
-{
- // Return the URL to be used for history and B/F list.
- // Returns nil for WebDataProtocol URLs that aren't alternates
- // for unreachable URLs, because these can't be stored in history.
- if (m_substituteData.isValid())
- return unreachableURL();
-
- return m_originalRequestCopy.url();
-}
-
const KURL& DocumentLoader::originalURL() const
{
return m_originalRequestCopy.url();
@@ -779,7 +776,7 @@ const KURL& DocumentLoader::requestURL() const
return request().url();
}
-const String& DocumentLoader::responseMIMEType() const
+const AtomicString& DocumentLoader::responseMIMEType() const
{
return m_response.mimeType();
}
@@ -808,7 +805,7 @@ bool DocumentLoader::maybeLoadEmpty()
if (m_request.url().isEmpty() && !frameLoader()->stateMachine()->creatingInitialEmptyDocument())
m_request.setURL(blankURL());
- m_response = ResourceResponse(m_request.url(), "text/html", 0, String(), String());
+ m_response = ResourceResponse(m_request.url(), "text/html", 0, nullAtom, String());
finishedLoading(monotonicallyIncreasingTime());
return true;
}
@@ -846,7 +843,7 @@ void DocumentLoader::startLoadingMainResource()
ResourceRequest request(m_request);
DEFINE_STATIC_LOCAL(ResourceLoaderOptions, mainResourceLoadOptions,
- (SendCallbacks, SniffContent, DoNotBufferData, AllowStoredCredentials, ClientRequestedCredentials, AskClientForCrossOriginCredentials, SkipSecurityCheck, CheckContentSecurityPolicy, UseDefaultOriginRestrictionsForType, DocumentContext));
+ (SendCallbacks, SniffContent, DoNotBufferData, AllowStoredCredentials, ClientRequestedCredentials, AskClientForCrossOriginCredentials, SkipSecurityCheck, CheckContentSecurityPolicy, DocumentContext));
FetchRequest cachedResourceRequest(request, FetchInitiatorTypeNames::document, mainResourceLoadOptions);
m_mainResource = m_fetcher->fetchMainResource(cachedResourceRequest);
if (!m_mainResource) {
@@ -882,7 +879,7 @@ void DocumentLoader::cancelMainResourceLoad(const ResourceError& resourceError)
mainReceivedError(error);
}
-DocumentWriter* DocumentLoader::beginWriting(const String& mimeType, const String& encoding, const KURL& url)
+DocumentWriter* DocumentLoader::beginWriting(const AtomicString& mimeType, const AtomicString& encoding, const KURL& url)
{
m_writer = createWriterFor(m_frame, 0, url, mimeType, encoding, false, true);
return m_writer.get();
@@ -895,53 +892,63 @@ void DocumentLoader::endWriting(DocumentWriter* writer)
m_writer.clear();
}
-PassRefPtr<DocumentWriter> DocumentLoader::createWriterFor(Frame* frame, const Document* ownerDocument, const KURL& url, const String& mimeType, const String& encoding, bool userChosen, bool dispatch)
+PassRefPtr<DocumentWriter> DocumentLoader::createWriterFor(Frame* frame, const Document* ownerDocument, const KURL& url, const AtomicString& mimeType, const AtomicString& encoding, bool userChosen, bool dispatch)
{
// Create a new document before clearing the frame, because it may need to
// inherit an aliased security context.
- RefPtr<Document> document = DOMImplementation::createDocument(mimeType, frame, url, frame->inViewSourceMode());
- if (document->isPluginDocument() && document->isSandboxed(SandboxPlugins))
- document = SinkDocument::create(DocumentInit(url, frame));
- bool shouldReuseDefaultView = frame->loader()->stateMachine()->isDisplayingInitialEmptyDocument() && frame->document()->isSecureTransitionTo(url);
+ DocumentInit init(url, frame);
+
+ // In some rare cases, we'll re-used a DOMWindow for a new Document. For example,
+ // when a script calls window.open("..."), the browser gives JavaScript a window
+ // synchronously but kicks off the load in the window asynchronously. Web sites
+ // expect that modifications that they make to the window object synchronously
+ // won't be blown away when the network load commits. To make that happen, we
+ // "securely transition" the existing DOMWindow to the Document that results from
+ // the network load. See also SecurityContext::isSecureTransitionTo.
+ bool shouldReuseDefaultView = frame->loader().stateMachine()->isDisplayingInitialEmptyDocument() && frame->document()->isSecureTransitionTo(url);
ClearOptions options = 0;
if (!shouldReuseDefaultView)
options = ClearWindowProperties | ClearScriptObjects;
- frame->loader()->clear(options);
+ frame->loader().clear(options);
- if (frame->document() && frame->document()->attached())
+ if (frame->document())
frame->document()->prepareForDestruction();
if (!shouldReuseDefaultView)
frame->setDOMWindow(DOMWindow::create(frame));
- frame->loader()->setOutgoingReferrer(url);
- frame->domWindow()->setDocument(document);
-
+ RefPtr<Document> document = frame->domWindow()->installNewDocument(mimeType, init);
if (ownerDocument) {
document->setCookieURL(ownerDocument->cookieURL());
document->setSecurityOrigin(ownerDocument->securityOrigin());
}
- frame->loader()->didBeginDocument(dispatch);
+ frame->loader().didBeginDocument(dispatch);
return DocumentWriter::create(document.get(), mimeType, encoding, userChosen);
}
-String DocumentLoader::mimeType() const
+const AtomicString& DocumentLoader::mimeType() const
{
if (m_writer)
return m_writer->mimeType();
return m_response.mimeType();
}
+void DocumentLoader::setUserChosenEncoding(const String& charset)
+{
+ if (m_writer)
+ m_writer->setUserChosenEncoding(charset);
+}
+
// This is only called by ScriptController::executeScriptIfJavaScriptURL
// and always contains the result of evaluating a javascript: url.
// This is the <iframe src="javascript:'html'"> case.
void DocumentLoader::replaceDocument(const String& source, Document* ownerDocument)
{
- m_frame->loader()->stopAllLoaders();
- m_writer = createWriterFor(m_frame, ownerDocument, m_frame->document()->url(), mimeType(), m_writer ? m_writer->encoding() : "", m_writer ? m_writer->encodingWasChosenByUser() : false, true);
+ m_frame->loader().stopAllLoaders();
+ m_writer = createWriterFor(m_frame, ownerDocument, m_frame->document()->url(), mimeType(), m_writer ? m_writer->encoding() : emptyAtom, m_writer ? m_writer->encodingWasChosenByUser() : false, true);
if (!source.isNull())
m_writer->appendReplacingData(source);
endWriting(m_writer.get());
diff --git a/chromium/third_party/WebKit/Source/core/loader/DocumentLoader.h b/chromium/third_party/WebKit/Source/core/loader/DocumentLoader.h
index 7fe971f89c8..d9b30f80232 100644
--- a/chromium/third_party/WebKit/Source/core/loader/DocumentLoader.h
+++ b/chromium/third_party/WebKit/Source/core/loader/DocumentLoader.h
@@ -37,10 +37,10 @@
#include "core/loader/DocumentWriter.h"
#include "core/loader/NavigationAction.h"
#include "core/loader/SubstituteData.h"
-#include "core/platform/Timer.h"
-#include "core/platform/network/ResourceError.h"
-#include "core/platform/network/ResourceRequest.h"
-#include "core/platform/network/ResourceResponse.h"
+#include "platform/Timer.h"
+#include "platform/network/ResourceError.h"
+#include "platform/network/ResourceRequest.h"
+#include "platform/network/ResourceResponse.h"
#include "wtf/HashSet.h"
#include "wtf/RefPtr.h"
@@ -81,10 +81,12 @@ namespace WebCore {
unsigned long mainResourceIdentifier() const;
void replaceDocument(const String& source, Document*);
- DocumentWriter* beginWriting(const String& mimeType, const String& encoding, const KURL& = KURL());
+ DocumentWriter* beginWriting(const AtomicString& mimeType, const AtomicString& encoding, const KURL& = KURL());
void endWriting(DocumentWriter*);
- String mimeType() const;
+ const AtomicString& mimeType() const;
+
+ void setUserChosenEncoding(const String& charset);
const ResourceRequest& originalRequest() const;
const ResourceRequest& originalRequestCopy() const;
@@ -99,12 +101,13 @@ namespace WebCore {
// FIXME: This is the same as requestURL(). We should remove one of them.
const KURL& url() const;
const KURL& unreachableURL() const;
+ bool isURLValidForNewHistoryEntry() const;
const KURL& originalURL() const;
const KURL& requestURL() const;
- const String& responseMIMEType() const;
+ const AtomicString& responseMIMEType() const;
- void replaceRequestURLForSameDocumentNavigation(const KURL&);
+ void updateForSameDocumentNavigation(const KURL&);
void stopLoading();
void setCommitted(bool committed) { m_committed = committed; }
bool isCommitted() const { return m_committed; }
@@ -116,7 +119,7 @@ namespace WebCore {
bool replacesCurrentHistoryItem() const { return m_replacesCurrentHistoryItem; }
void setReplacesCurrentHistoryItem(bool replacesCurrentHistoryItem) { m_replacesCurrentHistoryItem = replacesCurrentHistoryItem; }
bool isLoadingInAPISense() const;
- const String& overrideEncoding() const { return m_overrideEncoding; }
+ const AtomicString& overrideEncoding() const { return m_overrideEncoding; }
bool scheduleArchiveLoad(Resource*, const ResourceRequest&);
void cancelPendingSubstituteLoad(ResourceLoader*);
@@ -129,9 +132,7 @@ namespace WebCore {
const NavigationAction& triggeringAction() const { return m_triggeringAction; }
void setTriggeringAction(const NavigationAction& action) { m_triggeringAction = action; }
- void setOverrideEncoding(const String& encoding) { m_overrideEncoding = encoding; }
-
- KURL urlForHistory() const;
+ void setOverrideEncoding(const AtomicString& encoding) { m_overrideEncoding = encoding; }
void setDefersLoading(bool);
@@ -164,10 +165,10 @@ namespace WebCore {
Vector<KURL> m_redirectChain;
private:
- static PassRefPtr<DocumentWriter> createWriterFor(Frame*, const Document* ownerDocument, const KURL&, const String& mimeType, const String& encoding, bool userChosen, bool dispatch);
+ static PassRefPtr<DocumentWriter> createWriterFor(Frame*, const Document* ownerDocument, const KURL&, const AtomicString& mimeType, const AtomicString& encoding, bool userChosen, bool dispatch);
void ensureWriter();
- void ensureWriter(const String& mimeType, const KURL& overridingURL = KURL());
+ void ensureWriter(const AtomicString& mimeType, const KURL& overridingURL = KURL());
Document* document() const;
@@ -239,7 +240,7 @@ namespace WebCore {
bool m_isClientRedirect;
bool m_replacesCurrentHistoryItem;
- String m_overrideEncoding;
+ AtomicString m_overrideEncoding;
// The action that triggered loading - we keep this around for the
// benefit of the various policy handlers.
diff --git a/chromium/third_party/WebKit/Source/core/loader/DocumentThreadableLoader.cpp b/chromium/third_party/WebKit/Source/core/loader/DocumentThreadableLoader.cpp
index c12ac96fafe..f34ee2e5b9e 100644
--- a/chromium/third_party/WebKit/Source/core/loader/DocumentThreadableLoader.cpp
+++ b/chromium/third_party/WebKit/Source/core/loader/DocumentThreadableLoader.cpp
@@ -35,21 +35,19 @@
#include "core/dom/Document.h"
#include "core/fetch/CrossOriginAccessControl.h"
#include "core/fetch/FetchRequest.h"
-#include "core/fetch/RawResource.h"
#include "core/fetch/Resource.h"
#include "core/fetch/ResourceFetcher.h"
+#include "core/frame/ContentSecurityPolicy.h"
+#include "core/frame/Frame.h"
#include "core/inspector/InspectorInstrumentation.h"
#include "core/loader/CrossOriginPreflightResultCache.h"
#include "core/loader/DocumentThreadableLoaderClient.h"
#include "core/loader/FrameLoader.h"
#include "core/loader/ThreadableLoaderClient.h"
-#include "core/page/ContentSecurityPolicy.h"
-#include "core/page/Frame.h"
-#include "core/platform/SharedBuffer.h"
-#include "core/platform/network/ResourceError.h"
-#include "core/platform/network/ResourceRequest.h"
-#include "weborigin/SchemeRegistry.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/SharedBuffer.h"
+#include "platform/network/ResourceRequest.h"
+#include "platform/weborigin/SchemeRegistry.h"
+#include "platform/weborigin/SecurityOrigin.h"
#include "wtf/Assertions.h"
namespace WebCore {
@@ -64,7 +62,7 @@ void DocumentThreadableLoader::loadResourceSynchronously(Document* document, con
PassRefPtr<DocumentThreadableLoader> DocumentThreadableLoader::create(Document* document, ThreadableLoaderClient* client, const ResourceRequest& request, const ThreadableLoaderOptions& options)
{
RefPtr<DocumentThreadableLoader> loader = adoptRef(new DocumentThreadableLoader(document, client, LoadAsynchronously, request, options));
- if (!loader->m_resource)
+ if (!loader->resource())
loader = 0;
return loader.release();
}
@@ -89,7 +87,7 @@ DocumentThreadableLoader::DocumentThreadableLoader(Document* document, Threadabl
}
if (m_options.crossOriginRequestPolicy == DenyCrossOriginRequests) {
- m_client->didFail(ResourceError(errorDomainWebKitInternal, 0, request.url().string(), "Cross origin requests are not supported."));
+ m_client->didFail(ResourceError(errorDomainBlinkInternal, 0, request.url().string(), "Cross origin requests are not supported."));
return;
}
@@ -125,7 +123,7 @@ void DocumentThreadableLoader::makeSimpleCrossOriginAccessRequest(const Resource
// Cross-origin requests are only allowed for HTTP and registered schemes. We would catch this when checking response headers later, but there is no reason to send a request that's guaranteed to be denied.
if (!SchemeRegistry::shouldTreatURLSchemeAsCORSEnabled(request.url().protocol())) {
- m_client->didFailAccessControlCheck(ResourceError(errorDomainWebKitInternal, 0, request.url().string(), "Cross origin requests are only supported for HTTP."));
+ m_client->didFailAccessControlCheck(ResourceError(errorDomainBlinkInternal, 0, request.url().string(), "Cross origin requests are only supported for HTTP."));
return;
}
@@ -140,8 +138,6 @@ void DocumentThreadableLoader::makeCrossOriginAccessRequestWithPreflight(const R
DocumentThreadableLoader::~DocumentThreadableLoader()
{
- if (m_resource)
- m_resource->removeClient(this);
}
void DocumentThreadableLoader::cancel()
@@ -154,14 +150,14 @@ void DocumentThreadableLoader::cancelWithError(const ResourceError& error)
RefPtr<DocumentThreadableLoader> protect(this);
// Cancel can re-enter and m_resource might be null here as a result.
- if (m_client && m_resource) {
+ if (m_client && resource()) {
ResourceError errorForCallback = error;
if (errorForCallback.isNull()) {
// FIXME: This error is sent to the client in didFail(), so it should not be an internal one. Use FrameLoaderClient::cancelledError() instead.
- errorForCallback = ResourceError(errorDomainWebKitInternal, 0, m_resource->url().string(), "Load cancelled");
+ errorForCallback = ResourceError(errorDomainBlinkInternal, 0, resource()->url().string(), "Load cancelled");
errorForCallback.setIsCancellation(true);
}
- didFail(m_resource->identifier(), errorForCallback);
+ didFail(resource()->identifier(), errorForCallback);
}
clearResource();
m_client = 0;
@@ -169,26 +165,14 @@ void DocumentThreadableLoader::cancelWithError(const ResourceError& error)
void DocumentThreadableLoader::setDefersLoading(bool value)
{
- if (m_resource)
- m_resource->setDefersLoading(value);
-}
-
-void DocumentThreadableLoader::clearResource()
-{
- // Script can cancel and restart a request reentrantly within removeClient(),
- // which could lead to calling Resource::removeClient() multiple times for
- // this DocumentThreadableLoader. Save off a copy of m_resource and clear it to
- // prevent the reentrancy.
- if (ResourcePtr<RawResource> resource = m_resource) {
- m_resource = 0;
- resource->removeClient(this);
- }
+ if (resource())
+ resource()->setDefersLoading(value);
}
void DocumentThreadableLoader::redirectReceived(Resource* resource, ResourceRequest& request, const ResourceResponse& redirectResponse)
{
ASSERT(m_client);
- ASSERT_UNUSED(resource, resource == m_resource);
+ ASSERT_UNUSED(resource, resource == this->resource());
RefPtr<DocumentThreadableLoader> protect(this);
if (!isAllowedByPolicy(request.url())) {
@@ -209,7 +193,7 @@ void DocumentThreadableLoader::redirectReceived(Resource* resource, ResourceRequ
// original request was not same-origin.
if (m_options.crossOriginRequestPolicy == UseAccessControl) {
- InspectorInstrumentation::didReceiveCORSRedirectResponse(m_document->frame(), resource->identifier(), m_document->frame()->loader()->documentLoader(), redirectResponse, 0);
+ InspectorInstrumentation::didReceiveCORSRedirectResponse(m_document->frame(), resource->identifier(), m_document->frame()->loader().documentLoader(), redirectResponse, 0);
bool allowRedirect = false;
String accessControlErrorDescription;
@@ -222,8 +206,7 @@ void DocumentThreadableLoader::redirectReceived(Resource* resource, ResourceRequ
}
if (allowRedirect) {
- if (m_resource)
- clearResource();
+ clearResource();
RefPtr<SecurityOrigin> originalOrigin = SecurityOrigin::create(redirectResponse.url());
RefPtr<SecurityOrigin> requestOrigin = SecurityOrigin::create(request.url());
@@ -250,7 +233,7 @@ void DocumentThreadableLoader::redirectReceived(Resource* resource, ResourceRequ
return;
}
- ResourceError error(errorDomainWebKitInternal, 0, redirectResponse.url().string(), accessControlErrorDescription);
+ ResourceError error(errorDomainBlinkInternal, 0, redirectResponse.url().string(), accessControlErrorDescription);
m_client->didFailAccessControlCheck(error);
} else {
m_client->didFailRedirectCheck();
@@ -261,14 +244,14 @@ void DocumentThreadableLoader::redirectReceived(Resource* resource, ResourceRequ
void DocumentThreadableLoader::dataSent(Resource* resource, unsigned long long bytesSent, unsigned long long totalBytesToBeSent)
{
ASSERT(m_client);
- ASSERT_UNUSED(resource, resource == m_resource);
+ ASSERT_UNUSED(resource, resource == this->resource());
m_client->didSendData(bytesSent, totalBytesToBeSent);
}
void DocumentThreadableLoader::dataDownloaded(Resource* resource, int dataLength)
{
ASSERT(m_client);
- ASSERT_UNUSED(resource, resource == m_resource);
+ ASSERT_UNUSED(resource, resource == this->resource());
ASSERT(!m_actualRequest);
m_client->didDownloadData(dataLength);
@@ -276,8 +259,8 @@ void DocumentThreadableLoader::dataDownloaded(Resource* resource, int dataLength
void DocumentThreadableLoader::responseReceived(Resource* resource, const ResourceResponse& response)
{
- ASSERT_UNUSED(resource, resource == m_resource);
- didReceiveResponse(m_resource->identifier(), response);
+ ASSERT_UNUSED(resource, resource == this->resource());
+ didReceiveResponse(resource->identifier(), response);
}
void DocumentThreadableLoader::didReceiveResponse(unsigned long identifier, const ResourceResponse& response)
@@ -286,9 +269,8 @@ void DocumentThreadableLoader::didReceiveResponse(unsigned long identifier, cons
String accessControlErrorDescription;
if (m_actualRequest) {
- DocumentLoader* loader = m_document->frame()->loader()->documentLoader();
- InspectorInstrumentationCookie cookie = InspectorInstrumentation::willReceiveResourceResponse(m_document->frame(), identifier, response);
- InspectorInstrumentation::didReceiveResourceResponse(cookie, identifier, loader, response, m_resource ? m_resource->loader() : 0);
+ DocumentLoader* loader = m_document->frame()->loader().documentLoader();
+ InspectorInstrumentation::didReceiveResourceResponse(m_document->frame(), identifier, loader, response, resource() ? resource()->loader() : 0);
if (!passesAccessControlCheck(response, m_options.allowCredentials, securityOrigin(), accessControlErrorDescription)) {
preflightFailure(identifier, response.url().string(), accessControlErrorDescription);
@@ -312,7 +294,7 @@ void DocumentThreadableLoader::didReceiveResponse(unsigned long identifier, cons
} else {
if (!m_sameOriginRequest && m_options.crossOriginRequestPolicy == UseAccessControl) {
if (!passesAccessControlCheck(response, m_options.allowCredentials, securityOrigin(), accessControlErrorDescription)) {
- m_client->didFailAccessControlCheck(ResourceError(errorDomainWebKitInternal, 0, response.url().string(), accessControlErrorDescription));
+ m_client->didFailAccessControlCheck(ResourceError(errorDomainBlinkInternal, 0, response.url().string(), accessControlErrorDescription));
return;
}
}
@@ -323,8 +305,8 @@ void DocumentThreadableLoader::didReceiveResponse(unsigned long identifier, cons
void DocumentThreadableLoader::dataReceived(Resource* resource, const char* data, int dataLength)
{
- ASSERT_UNUSED(resource, resource == m_resource);
- didReceiveData(m_resource->identifier(), data, dataLength);
+ ASSERT(resource == this->resource());
+ didReceiveData(resource->identifier(), data, dataLength);
}
void DocumentThreadableLoader::didReceiveData(unsigned long identifier, const char* data, int dataLength)
@@ -343,20 +325,20 @@ void DocumentThreadableLoader::didReceiveData(unsigned long identifier, const ch
void DocumentThreadableLoader::notifyFinished(Resource* resource)
{
ASSERT(m_client);
- ASSERT_UNUSED(resource, resource == m_resource);
+ ASSERT(resource == this->resource());
m_timeoutTimer.stop();
- if (m_resource->errorOccurred())
- didFail(m_resource->identifier(), m_resource->resourceError());
+ if (resource->errorOccurred())
+ didFail(resource->identifier(), resource->resourceError());
else
- didFinishLoading(m_resource->identifier(), m_resource->loadFinishTime());
+ didFinishLoading(resource->identifier(), resource->loadFinishTime());
}
void DocumentThreadableLoader::didFinishLoading(unsigned long identifier, double finishTime)
{
if (m_actualRequest) {
- InspectorInstrumentation::didFinishLoading(m_document->frame(), identifier, m_document->frame()->loader()->documentLoader(), finishTime);
+ InspectorInstrumentation::didFinishLoading(m_document->frame(), identifier, m_document->frame()->loader().documentLoader(), finishTime);
ASSERT(!m_sameOriginRequest);
ASSERT(m_options.crossOriginRequestPolicy == UseAccessControl);
preflightSuccess();
@@ -367,7 +349,7 @@ void DocumentThreadableLoader::didFinishLoading(unsigned long identifier, double
void DocumentThreadableLoader::didFail(unsigned long identifier, const ResourceError& error)
{
if (m_actualRequest)
- InspectorInstrumentation::didFailLoading(m_document->frame(), identifier, m_document->frame()->loader()->documentLoader(), error);
+ InspectorInstrumentation::didFailLoading(m_document->frame(), identifier, m_document->frame()->loader().documentLoader(), error);
m_client->didFail(error);
}
@@ -379,7 +361,7 @@ void DocumentThreadableLoader::didTimeout(Timer<DocumentThreadableLoader>* timer
// Using values from net/base/net_error_list.h ERR_TIMED_OUT,
// Same as existing FIXME above - this error should be coming from FrameLoaderClient to be identifiable.
static const int timeoutError = -7;
- ResourceError error("net", timeoutError, m_resource->url(), String());
+ ResourceError error("net", timeoutError, resource()->url(), String());
error.setIsTimeout(true);
cancelWithError(error);
}
@@ -399,9 +381,9 @@ void DocumentThreadableLoader::preflightSuccess()
void DocumentThreadableLoader::preflightFailure(unsigned long identifier, const String& url, const String& errorDescription)
{
- ResourceError error(errorDomainWebKitInternal, 0, url, errorDescription);
+ ResourceError error(errorDomainBlinkInternal, 0, url, errorDescription);
if (m_actualRequest)
- InspectorInstrumentation::didFailLoading(m_document->frame(), identifier, m_document->frame()->loader()->documentLoader(), error);
+ InspectorInstrumentation::didFailLoading(m_document->frame(), identifier, m_document->frame()->loader().documentLoader(), error);
m_actualRequest = nullptr; // Prevent didFinishLoading() from bypassing access check.
m_client->didFailAccessControlCheck(error);
}
@@ -429,14 +411,11 @@ void DocumentThreadableLoader::loadRequest(const ResourceRequest& request, Secur
m_timeoutTimer.startOneShot(m_options.timeoutMilliseconds / 1000.0);
FetchRequest newRequest(request, m_options.initiator, options);
- ASSERT(!m_resource);
- m_resource = m_document->fetcher()->fetchRawResource(newRequest);
- if (m_resource) {
- if (m_resource->loader()) {
- unsigned long identifier = m_resource->identifier();
- InspectorInstrumentation::documentThreadableLoaderStartedLoadingForClient(m_document, identifier, m_client);
- }
- m_resource->addClient(this);
+ ASSERT(!resource());
+ setResource(m_document->fetcher()->fetchRawResource(newRequest));
+ if (resource() && resource()->loader()) {
+ unsigned long identifier = resource()->identifier();
+ InspectorInstrumentation::documentThreadableLoaderStartedLoadingForClient(m_document, identifier, m_client);
}
return;
}
diff --git a/chromium/third_party/WebKit/Source/core/loader/DocumentThreadableLoader.h b/chromium/third_party/WebKit/Source/core/loader/DocumentThreadableLoader.h
index df0e851f5aa..3eadc624f31 100644
--- a/chromium/third_party/WebKit/Source/core/loader/DocumentThreadableLoader.h
+++ b/chromium/third_party/WebKit/Source/core/loader/DocumentThreadableLoader.h
@@ -33,10 +33,10 @@
#define DocumentThreadableLoader_h
#include "core/fetch/RawResource.h"
-#include "core/fetch/ResourcePtr.h"
+#include "core/fetch/ResourceOwner.h"
#include "core/loader/ThreadableLoader.h"
-#include "core/platform/Timer.h"
-#include "core/platform/network/ResourceError.h"
+#include "platform/Timer.h"
+#include "platform/network/ResourceError.h"
#include "wtf/Forward.h"
#include "wtf/OwnPtr.h"
#include "wtf/PassRefPtr.h"
@@ -51,7 +51,7 @@ class ResourceRequest;
class SecurityOrigin;
class ThreadableLoaderClient;
-class DocumentThreadableLoader : public RefCounted<DocumentThreadableLoader>, public ThreadableLoader, private RawResourceClient {
+class DocumentThreadableLoader : public RefCounted<DocumentThreadableLoader>, public ThreadableLoader, private ResourceOwner<RawResource> {
WTF_MAKE_FAST_ALLOCATED;
public:
static void loadResourceSynchronously(Document*, const ResourceRequest&, ThreadableLoaderClient&, const ThreadableLoaderOptions&);
@@ -76,8 +76,6 @@ class DocumentThreadableLoader : public RefCounted<DocumentThreadableLoader>, pu
DocumentThreadableLoader(Document*, ThreadableLoaderClient*, BlockingBehavior, const ResourceRequest&, const ThreadableLoaderOptions&);
- void clearResource();
-
// RawResourceClient
virtual void dataSent(Resource*, unsigned long long bytesSent, unsigned long long totalBytesToBeSent);
virtual void responseReceived(Resource*, const ResourceResponse&);
@@ -105,7 +103,6 @@ class DocumentThreadableLoader : public RefCounted<DocumentThreadableLoader>, pu
SecurityOrigin* securityOrigin() const;
bool checkCrossOriginAccessRedirectionUrl(const KURL&, String& errorDescription);
- ResourcePtr<RawResource> m_resource;
ThreadableLoaderClient* m_client;
Document* m_document;
ThreadableLoaderOptions m_options;
diff --git a/chromium/third_party/WebKit/Source/core/loader/DocumentWriter.cpp b/chromium/third_party/WebKit/Source/core/loader/DocumentWriter.cpp
index 61e19f1f1ff..349da64347d 100644
--- a/chromium/third_party/WebKit/Source/core/loader/DocumentWriter.cpp
+++ b/chromium/third_party/WebKit/Source/core/loader/DocumentWriter.cpp
@@ -34,24 +34,23 @@
#include "core/fetch/TextResourceDecoder.h"
#include "core/loader/FrameLoader.h"
#include "core/loader/FrameLoaderStateMachine.h"
-#include "core/page/DOMWindow.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameView.h"
-#include "core/page/Settings.h"
-#include "weborigin/KURL.h"
-#include "weborigin/SecurityOrigin.h"
+#include "core/frame/DOMWindow.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
+#include "core/frame/Settings.h"
+#include "platform/weborigin/KURL.h"
+#include "platform/weborigin/SecurityOrigin.h"
#include "wtf/PassOwnPtr.h"
namespace WebCore {
-PassRefPtr<DocumentWriter> DocumentWriter::create(Document* document, const String& mimeType, const String& encoding, bool encodingUserChoosen)
+PassRefPtr<DocumentWriter> DocumentWriter::create(Document* document, const AtomicString& mimeType, const AtomicString& encoding, bool encodingUserChoosen)
{
return adoptRef(new DocumentWriter(document, mimeType, encoding, encodingUserChoosen));
}
-DocumentWriter::DocumentWriter(Document* document, const String& mimeType, const String& encoding, bool encodingUserChoosen)
+DocumentWriter::DocumentWriter(Document* document, const AtomicString& mimeType, const AtomicString& encoding, bool encodingUserChoosen)
: m_document(document)
- , m_hasReceivedSomeData(false)
, m_decoderBuilder(mimeType, encoding, encodingUserChoosen)
// We grab a reference to the parser so that we'll always send data to the
// original parser, even if the document acquires a new parser (e.g., via
@@ -70,8 +69,6 @@ DocumentWriter::~DocumentWriter()
void DocumentWriter::appendReplacingData(const String& source)
{
- ASSERT(!m_hasReceivedSomeData);
- m_hasReceivedSomeData = true;
m_document->setCompatibilityMode(Document::NoQuirksMode);
// FIXME: This should call DocumentParser::appendBytes instead of append
@@ -81,29 +78,20 @@ void DocumentWriter::appendReplacingData(const String& source)
// Because we're pinned to the main thread we don't need to worry about
// passing ownership of the source string.
parser->append(source.impl());
+ parser->setHasAppendedData();
}
}
-void DocumentWriter::reportDataReceived()
-{
- ASSERT(m_decoder);
- if (m_hasReceivedSomeData)
- return;
- m_hasReceivedSomeData = true;
- if (m_decoder->encoding().usesVisualOrdering())
- m_document->setVisuallyOrdered();
-}
-
void DocumentWriter::addData(const char* bytes, size_t length)
{
ASSERT(m_parser);
- if (!m_decoder && m_parser->needsDecoder() && 0 < length)
- m_decoder = m_decoderBuilder.buildFor(m_document);
+ if (m_parser->needsDecoder() && 0 < length) {
+ OwnPtr<TextResourceDecoder> decoder = m_decoderBuilder.buildFor(m_document);
+ m_parser->setDecoder(decoder.release());
+ }
// appendBytes() can result replacing DocumentLoader::m_writer.
RefPtr<DocumentWriter> protectingThis(this);
- size_t consumedChars = m_parser->appendBytes(bytes, length);
- if (consumedChars)
- reportDataReceived();
+ m_parser->appendBytes(bytes, length);
}
void DocumentWriter::end()
@@ -118,13 +106,14 @@ void DocumentWriter::end()
if (!m_parser)
return;
- if (!m_decoder && m_parser->needsDecoder())
- m_decoder = m_decoderBuilder.buildFor(m_document);
+ if (m_parser->needsDecoder()) {
+ OwnPtr<TextResourceDecoder> decoder = m_decoderBuilder.buildFor(m_document);
+ m_parser->setDecoder(decoder.release());
+ }
// flush() can result replacing DocumentLoader::m_writer.
RefPtr<DocumentWriter> protectingThis(this);
- size_t consumedChars = m_parser->flush();
- if (consumedChars)
- reportDataReceived();
+ m_parser->flush();
+
if (!m_parser)
return;
@@ -133,6 +122,13 @@ void DocumentWriter::end()
m_document = 0;
}
+void DocumentWriter::setUserChosenEncoding(const String& charset)
+{
+ TextResourceDecoder* decoder = m_parser->decoder();
+ if (decoder)
+ decoder->setEncoding(charset, TextResourceDecoder::UserChosenEncoding);
+}
+
void DocumentWriter::setDocumentWasLoadedAsPartOfNavigation()
{
ASSERT(m_parser && !m_parser->isStopped());
diff --git a/chromium/third_party/WebKit/Source/core/loader/DocumentWriter.h b/chromium/third_party/WebKit/Source/core/loader/DocumentWriter.h
index f3da31f112b..4e79045a1e9 100644
--- a/chromium/third_party/WebKit/Source/core/loader/DocumentWriter.h
+++ b/chromium/third_party/WebKit/Source/core/loader/DocumentWriter.h
@@ -45,7 +45,7 @@ class TextResourceDecoder;
class DocumentWriter : public RefCounted<DocumentWriter> {
WTF_MAKE_NONCOPYABLE(DocumentWriter);
public:
- static PassRefPtr<DocumentWriter> create(Document*, const String& mimeType = "", const String& encoding = "", bool encodingUserChoosen = false);
+ static PassRefPtr<DocumentWriter> create(Document*, const AtomicString& mimeType = emptyAtom, const AtomicString& encoding = emptyAtom, bool encodingUserChoosen = false);
~DocumentWriter();
@@ -57,27 +57,25 @@ public:
void addData(const char* bytes, size_t length);
- const String& mimeType() const { return m_decoderBuilder.mimeType(); }
- const String& encoding() const { return m_decoderBuilder.encoding(); }
+ const AtomicString& mimeType() const { return m_decoderBuilder.mimeType(); }
+ const AtomicString& encoding() const { return m_decoderBuilder.encoding(); }
bool encodingWasChosenByUser() const { return m_decoderBuilder.encodingWasChosenByUser(); }
- // Exposed for DocumentParser::appendBytes.
- void reportDataReceived();
// Exposed for DocumentLoader::replaceDocument.
void appendReplacingData(const String&);
+ void setUserChosenEncoding(const String& charset);
+
void setDocumentWasLoadedAsPartOfNavigation();
private:
- DocumentWriter(Document*, const String& mimeType, const String& encoding, bool encodingUserChoosen);
+ DocumentWriter(Document*, const AtomicString& mimeType, const AtomicString& encoding, bool encodingUserChoosen);
PassRefPtr<Document> createDocument(const KURL&);
Document* m_document;
- bool m_hasReceivedSomeData;
TextResourceDecoderBuilder m_decoderBuilder;
- RefPtr<TextResourceDecoder> m_decoder;
RefPtr<DocumentParser> m_parser;
};
diff --git a/chromium/third_party/WebKit/Source/core/loader/EmptyClients.cpp b/chromium/third_party/WebKit/Source/core/loader/EmptyClients.cpp
index cacba5b8f1a..78fbce00c1d 100644
--- a/chromium/third_party/WebKit/Source/core/loader/EmptyClients.cpp
+++ b/chromium/third_party/WebKit/Source/core/loader/EmptyClients.cpp
@@ -31,10 +31,12 @@
#include "core/html/HTMLFormElement.h"
#include "core/loader/DocumentLoader.h"
#include "core/loader/FormState.h"
-#include "core/page/Frame.h"
-#include "core/platform/ColorChooser.h"
-#include "core/platform/DateTimeChooser.h"
-#include "core/platform/FileChooser.h"
+#include "core/frame/Frame.h"
+#include "platform/ColorChooser.h"
+#include "platform/DateTimeChooser.h"
+#include "platform/FileChooser.h"
+#include "public/platform/WebServiceWorkerProvider.h"
+#include "public/platform/WebServiceWorkerProviderClient.h"
namespace WebCore {
@@ -57,6 +59,9 @@ void fillWithEmptyClients(Page::PageClients& pageClients)
static BackForwardClient* dummyBackForwardClient = adoptPtr(new EmptyBackForwardClient).leakPtr();
pageClients.backForwardClient = dummyBackForwardClient;
+
+ static SpellCheckerClient* dummySpellCheckerClient = adoptPtr(new EmptySpellCheckerClient).leakPtr();
+ pageClients.spellCheckerClient = dummySpellCheckerClient;
}
class EmptyPopupMenu : public PopupMenu {
@@ -82,6 +87,10 @@ PassRefPtr<DateTimeChooser> EmptyChromeClient::openDateTimeChooser(DateTimeChoos
return PassRefPtr<DateTimeChooser>();
}
+void EmptyChromeClient::openTextDataListChooser(HTMLInputElement&)
+{
+}
+
void EmptyChromeClient::runOpenPanel(Frame*, PassRefPtr<FileChooser>)
{
}
@@ -128,16 +137,13 @@ void EmptyTextCheckerClient::requestCheckingOfString(PassRefPtr<TextCheckingRequ
{
}
-void EmptyEditorClient::registerUndoStep(PassRefPtr<UndoStep>)
-{
-}
-
-void EmptyEditorClient::registerRedoStep(PassRefPtr<UndoStep>)
+void EmptyFrameLoaderClient::didRequestAutocomplete(PassRefPtr<FormState>)
{
}
-void EmptyFrameLoaderClient::didRequestAutocomplete(PassRefPtr<FormState>)
+PassOwnPtr<blink::WebServiceWorkerProvider> EmptyFrameLoaderClient::createServiceWorkerProvider(PassOwnPtr<blink::WebServiceWorkerProviderClient>)
{
+ return nullptr;
}
}
diff --git a/chromium/third_party/WebKit/Source/core/loader/EmptyClients.h b/chromium/third_party/WebKit/Source/core/loader/EmptyClients.h
index ed1cb5a3e18..ce31e022eaa 100644
--- a/chromium/third_party/WebKit/Source/core/loader/EmptyClients.h
+++ b/chromium/third_party/WebKit/Source/core/loader/EmptyClients.h
@@ -29,20 +29,21 @@
#ifndef EmptyClients_h
#define EmptyClients_h
-#include "core/dom/DeviceOrientationClient.h"
-#include "core/history/BackForwardClient.h"
+#include "core/editing/UndoStep.h"
#include "core/inspector/InspectorClient.h"
#include "core/loader/FrameLoaderClient.h"
+#include "core/page/BackForwardClient.h"
#include "core/page/ChromeClient.h"
#include "core/page/ContextMenuClient.h"
#include "core/page/DragClient.h"
#include "core/page/EditorClient.h"
#include "core/page/FocusDirection.h"
#include "core/page/Page.h"
+#include "core/page/SpellCheckerClient.h"
#include "core/platform/DragImage.h"
-#include "core/platform/graphics/FloatRect.h"
-#include "core/platform/network/ResourceError.h"
-#include "core/platform/text/TextCheckerClient.h"
+#include "platform/geometry/FloatRect.h"
+#include "platform/network/ResourceError.h"
+#include "platform/text/TextCheckerClient.h"
#include "public/platform/WebScreenInfo.h"
#include "wtf/Forward.h"
@@ -84,7 +85,7 @@ public:
virtual void takeFocus(FocusDirection) OVERRIDE { }
virtual void focusedNodeChanged(Node*) OVERRIDE { }
- virtual Page* createWindow(Frame*, const FrameLoadRequest&, const WindowFeatures&, NavigationPolicy) OVERRIDE { return 0; }
+ virtual Page* createWindow(Frame*, const FrameLoadRequest&, const WindowFeatures&, NavigationPolicy, ShouldSendReferrer) OVERRIDE { return 0; }
virtual void show(NavigationPolicy) OVERRIDE { }
virtual bool canRunModal() OVERRIDE { return false; }
@@ -134,9 +135,11 @@ public:
virtual void scroll(const IntSize&, const IntRect&, const IntRect&) OVERRIDE { }
virtual void scheduleAnimation() OVERRIDE { }
+ virtual bool isCompositorFramePending() const OVERRIDE { return false; }
+
virtual IntPoint screenToRootView(const IntPoint& p) const OVERRIDE { return p; }
virtual IntRect rootViewToScreen(const IntRect& r) const OVERRIDE { return r; }
- virtual WebKit::WebScreenInfo screenInfo() const OVERRIDE { return WebKit::WebScreenInfo(); }
+ virtual blink::WebScreenInfo screenInfo() const OVERRIDE { return blink::WebScreenInfo(); }
virtual void contentsSizeChanged(Frame*, const IntSize&) const OVERRIDE { }
virtual void mouseDidMoveOverElement(const HitTestResult&, unsigned) OVERRIDE { }
@@ -148,8 +151,8 @@ public:
virtual void enumerateChosenDirectory(FileChooser*) OVERRIDE { }
virtual PassOwnPtr<ColorChooser> createColorChooser(ColorChooserClient*, const Color&) OVERRIDE;
-
virtual PassRefPtr<DateTimeChooser> openDateTimeChooser(DateTimeChooserClient*, const DateTimeChooserParameters&) OVERRIDE;
+ virtual void openTextDataListChooser(HTMLInputElement&) OVERRIDE;
virtual void runOpenPanel(Frame*, PassRefPtr<FileChooser>) OVERRIDE;
@@ -161,6 +164,7 @@ public:
virtual void scheduleCompositingLayerFlush() OVERRIDE { }
virtual void needTouchEvents(bool) OVERRIDE { }
+ virtual void setTouchAction(TouchAction touchAction) OVERRIDE { };
virtual void numWheelEventHandlersChanged(unsigned) OVERRIDE { }
@@ -201,12 +205,12 @@ public:
virtual void dispatchDidStartProvisionalLoad() OVERRIDE { }
virtual void dispatchDidReceiveTitle(const String&) OVERRIDE { }
virtual void dispatchDidChangeIcons(IconType) OVERRIDE { }
- virtual void dispatchDidCommitLoad() OVERRIDE { }
+ virtual void dispatchDidCommitLoad(Frame*, HistoryItem*, NavigationHistoryPolicy) OVERRIDE { }
virtual void dispatchDidFailProvisionalLoad(const ResourceError&) OVERRIDE { }
virtual void dispatchDidFailLoad(const ResourceError&) OVERRIDE { }
virtual void dispatchDidFinishDocumentLoad() OVERRIDE { }
virtual void dispatchDidFinishLoad() OVERRIDE { }
- virtual void dispatchDidLayout(LayoutMilestones) OVERRIDE { }
+ virtual void dispatchDidFirstVisuallyNonEmptyLayout() OVERRIDE { }
virtual NavigationPolicy decidePolicyForNavigation(const ResourceRequest&, DocumentLoader*, NavigationPolicy) OVERRIDE;
@@ -227,11 +231,12 @@ public:
virtual void transitionToCommittedForNewPage() OVERRIDE { }
- virtual void navigateBackForward(int offset) const OVERRIDE { }
+ virtual bool navigateBackForward(int offset) const OVERRIDE { return false; }
virtual void didDisplayInsecureContent() OVERRIDE { }
virtual void didRunInsecureContent(SecurityOrigin*, const KURL&) OVERRIDE { }
virtual void didDetectXSS(const KURL&, bool) OVERRIDE { }
virtual void didDispatchPingLoader(const KURL&) OVERRIDE { }
+ virtual void selectorMatchChanged(const Vector<String>&, const Vector<String>&) OVERRIDE { }
virtual PassRefPtr<Frame> createFrame(const KURL&, const String&, const String&, HTMLFrameOwnerElement*) OVERRIDE;
virtual PassRefPtr<Widget> createPlugin(const IntSize&, HTMLPlugInElement*, const KURL&, const Vector<String>&, const Vector<String>&, const String&, bool) OVERRIDE;
virtual PassRefPtr<Widget> createJavaAppletWidget(const IntSize&, HTMLAppletElement*, const KURL&, const Vector<String>&, const Vector<String>&) OVERRIDE;
@@ -245,10 +250,10 @@ public:
virtual void willReleaseScriptContext(v8::Handle<v8::Context>, int worldId) OVERRIDE { }
virtual bool allowScriptExtension(const String& extensionName, int extensionGroup, int worldId) OVERRIDE { return false; }
- virtual WebKit::WebCookieJar* cookieJar() const { return 0; }
+ virtual blink::WebCookieJar* cookieJar() const { return 0; }
virtual void didRequestAutocomplete(PassRefPtr<FormState>) OVERRIDE;
- virtual WebKit::WebServiceWorkerRegistry* serviceWorkerRegistry() OVERRIDE { return 0; }
+ virtual PassOwnPtr<blink::WebServiceWorkerProvider> createServiceWorkerProvider(PassOwnPtr<blink::WebServiceWorkerProviderClient>) OVERRIDE;
};
class EmptyTextCheckerClient : public TextCheckerClient {
@@ -260,63 +265,42 @@ public:
virtual void requestCheckingOfString(PassRefPtr<TextCheckingRequest>) OVERRIDE;
};
-class EmptyEditorClient : public EditorClient {
- WTF_MAKE_NONCOPYABLE(EmptyEditorClient); WTF_MAKE_FAST_ALLOCATED;
+class EmptySpellCheckerClient : public SpellCheckerClient {
+ WTF_MAKE_NONCOPYABLE(EmptySpellCheckerClient); WTF_MAKE_FAST_ALLOCATED;
public:
- EmptyEditorClient() { }
- virtual ~EmptyEditorClient() { }
+ EmptySpellCheckerClient() { }
+ virtual ~EmptySpellCheckerClient() { }
- virtual bool shouldDeleteRange(Range*) OVERRIDE { return false; }
- virtual bool smartInsertDeleteEnabled() OVERRIDE { return false; }
- virtual bool isSelectTrailingWhitespaceEnabled() OVERRIDE { return false; }
virtual bool isContinuousSpellCheckingEnabled() OVERRIDE { return false; }
virtual void toggleContinuousSpellChecking() OVERRIDE { }
virtual bool isGrammarCheckingEnabled() OVERRIDE { return false; }
- virtual bool shouldBeginEditing(Range*) OVERRIDE { return false; }
- virtual bool shouldEndEditing(Range*) OVERRIDE { return false; }
- virtual bool shouldInsertNode(Node*, Range*, EditorInsertAction) OVERRIDE { return false; }
- virtual bool shouldInsertText(const String&, Range*, EditorInsertAction) OVERRIDE { return false; }
- virtual bool shouldChangeSelectedRange(Range*, Range*, EAffinity, bool) OVERRIDE { return false; }
-
- virtual bool shouldApplyStyle(StylePropertySet*, Range*) OVERRIDE { return false; }
-
- virtual void didBeginEditing() OVERRIDE { }
- virtual void respondToChangedContents() OVERRIDE { }
- virtual void respondToChangedSelection(Frame*) OVERRIDE { }
- virtual void didEndEditing() OVERRIDE { }
- virtual void didCancelCompositionOnSelectionChange() OVERRIDE { }
-
- virtual void registerUndoStep(PassRefPtr<UndoStep>) OVERRIDE;
- virtual void registerRedoStep(PassRefPtr<UndoStep>) OVERRIDE;
- virtual void clearUndoRedoOperations() OVERRIDE { }
-
- virtual bool canCopyCut(Frame*, bool defaultValue) const OVERRIDE { return defaultValue; }
- virtual bool canPaste(Frame*, bool defaultValue) const OVERRIDE { return defaultValue; }
- virtual bool canUndo() const OVERRIDE { return false; }
- virtual bool canRedo() const OVERRIDE { return false; }
-
- virtual void undo() OVERRIDE { }
- virtual void redo() OVERRIDE { }
-
- virtual void handleKeyboardEvent(KeyboardEvent*) OVERRIDE { }
-
- virtual void textFieldDidEndEditing(Element*) OVERRIDE { }
- virtual void textDidChangeInTextField(Element*) OVERRIDE { }
- virtual bool doTextFieldCommandFromEvent(Element*, KeyboardEvent*) OVERRIDE { return false; }
-
TextCheckerClient& textChecker() { return m_textCheckerClient; }
virtual void updateSpellingUIWithMisspelledWord(const String&) OVERRIDE { }
virtual void showSpellingUI(bool) OVERRIDE { }
virtual bool spellingUIIsShowing() OVERRIDE { return false; }
- virtual void willSetInputMethodState() OVERRIDE { }
-
private:
EmptyTextCheckerClient m_textCheckerClient;
};
+class EmptyEditorClient : public EditorClient {
+ WTF_MAKE_NONCOPYABLE(EmptyEditorClient); WTF_MAKE_FAST_ALLOCATED;
+public:
+ EmptyEditorClient() { }
+ virtual ~EmptyEditorClient() { }
+
+ virtual void respondToChangedContents() OVERRIDE { }
+ virtual void respondToChangedSelection(SelectionType) OVERRIDE { }
+
+ virtual bool canCopyCut(Frame*, bool defaultValue) const OVERRIDE { return defaultValue; }
+ virtual bool canPaste(Frame*, bool defaultValue) const OVERRIDE { return defaultValue; }
+
+ virtual void didExecuteCommand(String) OVERRIDE { }
+ virtual bool handleKeyboardEvent() OVERRIDE { return false; }
+};
+
class EmptyContextMenuClient : public ContextMenuClient {
WTF_MAKE_NONCOPYABLE(EmptyContextMenuClient); WTF_MAKE_FAST_ALLOCATED;
public:
@@ -345,24 +329,11 @@ public:
virtual void hideHighlight() OVERRIDE { }
};
-class EmptyDeviceClient : public DeviceClient {
-public:
- virtual void startUpdating() OVERRIDE { }
- virtual void stopUpdating() OVERRIDE { }
-};
-
-class EmptyDeviceOrientationClient : public DeviceOrientationClient {
-public:
- virtual void setController(DeviceOrientationController*) OVERRIDE { }
- virtual DeviceOrientationData* lastOrientation() const OVERRIDE { return 0; }
- virtual void deviceOrientationControllerDestroyed() OVERRIDE { }
-};
-
class EmptyBackForwardClient : public BackForwardClient {
public:
- virtual void didAddItem() OVERRIDE { }
virtual int backListCount() OVERRIDE { return 0; }
virtual int forwardListCount() OVERRIDE { return 0; }
+ virtual int backForwardListCount() OVERRIDE { return 0; }
};
void fillWithEmptyClients(Page::PageClients&);
diff --git a/chromium/third_party/WebKit/Source/core/loader/FormSubmission.cpp b/chromium/third_party/WebKit/Source/core/loader/FormSubmission.cpp
index d427f0b1da6..178a996bc76 100644
--- a/chromium/third_party/WebKit/Source/core/loader/FormSubmission.cpp
+++ b/chromium/third_party/WebKit/Source/core/loader/FormSubmission.cpp
@@ -32,18 +32,18 @@
#include "core/loader/FormSubmission.h"
#include "HTMLNames.h"
+#include "RuntimeEnabledFeatures.h"
#include "core/dom/Document.h"
-#include "core/dom/Event.h"
+#include "core/events/Event.h"
#include "core/html/DOMFormData.h"
#include "core/html/HTMLFormControlElement.h"
#include "core/html/HTMLFormElement.h"
#include "core/html/HTMLInputElement.h"
#include "core/html/parser/HTMLParserIdioms.h"
-#include "core/loader/FormState.h"
#include "core/loader/FrameLoadRequest.h"
#include "core/loader/FrameLoader.h"
-#include "core/platform/network/FormData.h"
-#include "core/platform/network/FormDataBuilder.h"
+#include "platform/network/FormData.h"
+#include "platform/network/FormDataBuilder.h"
#include "wtf/CurrentTime.h"
#include "wtf/text/TextEncoding.h"
@@ -103,7 +103,11 @@ void FormSubmission::Attributes::updateEncodingType(const String& type)
FormSubmission::Method FormSubmission::Attributes::parseMethodType(const String& type)
{
- return equalIgnoringCase(type, "post") ? FormSubmission::PostMethod : FormSubmission::GetMethod;
+ if (equalIgnoringCase(type, "post"))
+ return FormSubmission::PostMethod;
+ if (RuntimeEnabledFeatures::dialogElementEnabled() && equalIgnoringCase(type, "dialog"))
+ return FormSubmission::DialogMethod;
+ return FormSubmission::GetMethod;
}
void FormSubmission::Attributes::updateMethodType(const String& type)
@@ -111,6 +115,20 @@ void FormSubmission::Attributes::updateMethodType(const String& type)
m_method = parseMethodType(type);
}
+String FormSubmission::Attributes::methodString(Method method)
+{
+ switch (method) {
+ case GetMethod:
+ return "get";
+ case PostMethod:
+ return "post";
+ case DialogMethod:
+ return "dialog";
+ }
+ ASSERT_NOT_REACHED();
+ return emptyString();
+}
+
void FormSubmission::Attributes::copyFrom(const Attributes& other)
{
m_method = other.m_method;
@@ -134,6 +152,12 @@ inline FormSubmission::FormSubmission(Method method, const KURL& action, const S
{
}
+inline FormSubmission::FormSubmission(const String& result)
+ : m_method(DialogMethod)
+ , m_result(result)
+{
+}
+
PassRefPtr<FormSubmission> FormSubmission::create(HTMLFormElement* form, const Attributes& attributes, PassRefPtr<Event> event, FormSubmissionTrigger trigger)
{
ASSERT(form);
@@ -152,16 +176,19 @@ PassRefPtr<FormSubmission> FormSubmission::create(HTMLFormElement* form, const A
copiedAttributes.copyFrom(attributes);
if (submitButton) {
String attributeValue;
- if (!(attributeValue = submitButton->getAttribute(formactionAttr)).isNull())
+ if (!(attributeValue = submitButton->fastGetAttribute(formactionAttr)).isNull())
copiedAttributes.parseAction(attributeValue);
- if (!(attributeValue = submitButton->getAttribute(formenctypeAttr)).isNull())
+ if (!(attributeValue = submitButton->fastGetAttribute(formenctypeAttr)).isNull())
copiedAttributes.updateEncodingType(attributeValue);
- if (!(attributeValue = submitButton->getAttribute(formmethodAttr)).isNull())
+ if (!(attributeValue = submitButton->fastGetAttribute(formmethodAttr)).isNull())
copiedAttributes.updateMethodType(attributeValue);
- if (!(attributeValue = submitButton->getAttribute(formtargetAttr)).isNull())
+ if (!(attributeValue = submitButton->fastGetAttribute(formtargetAttr)).isNull())
copiedAttributes.setTarget(attributeValue);
}
+ if (copiedAttributes.method() == DialogMethod)
+ return adoptRef(new FormSubmission(submitButton->resultForDialogSubmit()));
+
Document& document = form->document();
KURL actionURL = document.completeURL(copiedAttributes.action().isEmpty() ? document.url().string() : copiedAttributes.action());
bool isMailtoForm = actionURL.protocolIs("mailto");
@@ -175,8 +202,7 @@ PassRefPtr<FormSubmission> FormSubmission::create(HTMLFormElement* form, const A
isMultiPartForm = false;
}
}
-
- WTF::TextEncoding dataEncoding = isMailtoForm ? UTF8Encoding() : FormDataBuilder::encodingFromAcceptCharset(copiedAttributes.acceptCharset(), &document);
+ WTF::TextEncoding dataEncoding = isMailtoForm ? UTF8Encoding() : FormDataBuilder::encodingFromAcceptCharset(copiedAttributes.acceptCharset(), document.inputEncoding(), document.defaultCharset());
RefPtr<DOMFormData> domFormData = DOMFormData::create(dataEncoding.encodingForFormSubmission());
Vector<pair<String, String> > formValues;
@@ -199,10 +225,10 @@ PassRefPtr<FormSubmission> FormSubmission::create(HTMLFormElement* form, const A
String boundary;
if (isMultiPartForm) {
- formData = FormData::createMultiPart(*(static_cast<FormDataList*>(domFormData.get())), domFormData->encoding(), &document);
+ formData = domFormData->createMultiPartFormData(domFormData->encoding());
boundary = formData->boundary().data();
} else {
- formData = FormData::create(*(static_cast<FormDataList*>(domFormData.get())), domFormData->encoding(), attributes.method() == GetMethod ? FormData::FormURLEncoded : FormData::parseEncodingType(encodingType));
+ formData = domFormData->createFormData(domFormData->encoding(), attributes.method() == GetMethod ? FormData::FormURLEncoded : FormData::parseEncodingType(encodingType));
if (copiedAttributes.method() == PostMethod && isMailtoForm) {
// Convert the form data into a string that we put into the URL.
appendMailtoPostFormDataToURL(actionURL, *formData, encodingType);
diff --git a/chromium/third_party/WebKit/Source/core/loader/FormSubmission.h b/chromium/third_party/WebKit/Source/core/loader/FormSubmission.h
index 8731bac3ecb..d53b2e686ec 100644
--- a/chromium/third_party/WebKit/Source/core/loader/FormSubmission.h
+++ b/chromium/third_party/WebKit/Source/core/loader/FormSubmission.h
@@ -32,7 +32,7 @@
#define FormSubmission_h
#include "core/loader/FormState.h"
-#include "weborigin/KURL.h"
+#include "platform/weborigin/KURL.h"
namespace WTF{
class TextEncoding;
@@ -48,7 +48,7 @@ class HTMLFormElement;
class FormSubmission : public RefCounted<FormSubmission> {
public:
- enum Method { GetMethod, PostMethod };
+ enum Method { GetMethod, PostMethod, DialogMethod };
class Attributes {
WTF_MAKE_NONCOPYABLE(Attributes);
@@ -63,7 +63,7 @@ public:
Method method() const { return m_method; }
static Method parseMethodType(const String&);
void updateMethodType(const String&);
- static String methodString(Method method) { return method == PostMethod ? "post" : "get"; }
+ static String methodString(Method);
const String& action() const { return m_action; }
void parseAction(const String&);
@@ -112,8 +112,12 @@ public:
const String& origin() const { return m_origin; }
void setOrigin(const String& origin) { m_origin = origin; }
+ const String& result() const { return m_result; }
+
private:
FormSubmission(Method, const KURL& action, const String& target, const String& contentType, PassRefPtr<FormState>, PassRefPtr<FormData>, const String& boundary, PassRefPtr<Event>);
+ // FormSubmission for DialogMethod
+ FormSubmission(const String& result);
// FIXME: Hold an instance of Attributes instead of individual members.
Method m_method;
@@ -126,6 +130,7 @@ private:
RefPtr<Event> m_event;
String m_referrer;
String m_origin;
+ String m_result;
};
}
diff --git a/chromium/third_party/WebKit/Source/core/loader/FrameFetchContext.cpp b/chromium/third_party/WebKit/Source/core/loader/FrameFetchContext.cpp
index 387f13a8a25..a74ad9be373 100644
--- a/chromium/third_party/WebKit/Source/core/loader/FrameFetchContext.cpp
+++ b/chromium/third_party/WebKit/Source/core/loader/FrameFetchContext.cpp
@@ -31,15 +31,16 @@
#include "config.h"
#include "core/loader/FrameFetchContext.h"
+#include "core/dom/Document.h"
#include "core/inspector/InspectorInstrumentation.h"
#include "core/loader/DocumentLoader.h"
#include "core/loader/FrameLoader.h"
#include "core/loader/FrameLoaderClient.h"
#include "core/loader/ProgressTracker.h"
-#include "core/page/Frame.h"
+#include "core/frame/Frame.h"
#include "core/page/Page.h"
-#include "core/page/Settings.h"
-#include "weborigin/SecurityPolicy.h"
+#include "core/frame/Settings.h"
+#include "platform/weborigin/SecurityPolicy.h"
namespace WebCore {
@@ -55,16 +56,12 @@ void FrameFetchContext::reportLocalLoadFailed(const KURL& url)
void FrameFetchContext::addAdditionalRequestHeaders(Document& document, ResourceRequest& request, Resource::Type type)
{
- bool isMainResource = type == Resource::MainResource;
-
- FrameLoader* frameLoader = m_frame->loader();
-
- if (!isMainResource) {
+ if (type != Resource::MainResource) {
String outgoingReferrer;
String outgoingOrigin;
if (request.httpReferrer().isNull()) {
- outgoingReferrer = frameLoader->outgoingReferrer();
- outgoingOrigin = frameLoader->outgoingOrigin();
+ outgoingReferrer = document.outgoingReferrer();
+ outgoingOrigin = document.outgoingOrigin();
} else {
outgoingReferrer = request.httpReferrer();
outgoingOrigin = SecurityOrigin::createFromString(outgoingReferrer)->toString();
@@ -79,16 +76,30 @@ void FrameFetchContext::addAdditionalRequestHeaders(Document& document, Resource
FrameLoader::addHTTPOriginIfNeeded(request, outgoingOrigin);
}
- frameLoader->addExtraFieldsToRequest(request);
+ m_frame->loader().addExtraFieldsToRequest(request);
}
-CachePolicy FrameFetchContext::cachePolicy(Resource::Type type) const
+CachePolicy FrameFetchContext::cachePolicy(Document* document) const
{
- if (type != Resource::MainResource)
- return m_frame->loader()->subresourceCachePolicy();
+ if (document && document->loadEventFinished())
+ return CachePolicyVerify;
- if (m_frame->loader()->loadType() == FrameLoadTypeReloadFromOrigin || m_frame->loader()->loadType() == FrameLoadTypeReload)
+ FrameLoadType loadType = m_frame->loader().loadType();
+ if (loadType == FrameLoadTypeReloadFromOrigin)
return CachePolicyReload;
+
+ if (Frame* parentFrame = m_frame->tree().parent()) {
+ CachePolicy parentCachePolicy = parentFrame->loader().fetchContext().cachePolicy(parentFrame->document());
+ if (parentCachePolicy != CachePolicyVerify)
+ return parentCachePolicy;
+ }
+
+ if (loadType == FrameLoadTypeReload)
+ return CachePolicyRevalidate;
+
+ DocumentLoader* loader = document ? document->loader() : 0;
+ if (loader && loader->request().cachePolicy() == ReturnCacheDataElseLoad)
+ return CachePolicyHistoryBuffer;
return CachePolicyVerify;
}
@@ -99,33 +110,32 @@ CachePolicy FrameFetchContext::cachePolicy(Resource::Type type) const
// cannot see imported documents.
inline DocumentLoader* FrameFetchContext::ensureLoader(DocumentLoader* loader)
{
- return loader ? loader : m_frame->loader()->activeDocumentLoader();
+ return loader ? loader : m_frame->loader().activeDocumentLoader();
}
void FrameFetchContext::dispatchDidChangeResourcePriority(unsigned long identifier, ResourceLoadPriority loadPriority)
{
- m_frame->loader()->client()->dispatchDidChangeResourcePriority(identifier, loadPriority);
+ m_frame->loader().client()->dispatchDidChangeResourcePriority(identifier, loadPriority);
}
void FrameFetchContext::dispatchWillSendRequest(DocumentLoader* loader, unsigned long identifier, ResourceRequest& request, const ResourceResponse& redirectResponse, const FetchInitiatorInfo& initiatorInfo)
{
- m_frame->loader()->applyUserAgent(request);
- m_frame->loader()->client()->dispatchWillSendRequest(loader, identifier, request, redirectResponse);
+ m_frame->loader().applyUserAgent(request);
+ m_frame->loader().client()->dispatchWillSendRequest(loader, identifier, request, redirectResponse);
InspectorInstrumentation::willSendRequest(m_frame, identifier, ensureLoader(loader), request, redirectResponse, initiatorInfo);
}
void FrameFetchContext::dispatchDidLoadResourceFromMemoryCache(const ResourceRequest& request, const ResourceResponse& response)
{
- m_frame->loader()->client()->dispatchDidLoadResourceFromMemoryCache(request, response);
+ m_frame->loader().client()->dispatchDidLoadResourceFromMemoryCache(request, response);
}
void FrameFetchContext::dispatchDidReceiveResponse(DocumentLoader* loader, unsigned long identifier, const ResourceResponse& r, ResourceLoader* resourceLoader)
{
if (Page* page = m_frame->page())
page->progress().incrementProgress(identifier, r);
- InspectorInstrumentationCookie cookie = InspectorInstrumentation::willReceiveResourceResponse(m_frame, identifier, r);
- m_frame->loader()->client()->dispatchDidReceiveResponse(loader, identifier, r);
- InspectorInstrumentation::didReceiveResourceResponse(cookie, identifier, ensureLoader(loader), r, resourceLoader);
+ m_frame->loader().client()->dispatchDidReceiveResponse(loader, identifier, r);
+ InspectorInstrumentation::didReceiveResourceResponse(m_frame, identifier, ensureLoader(loader), r, resourceLoader);
}
void FrameFetchContext::dispatchDidReceiveData(DocumentLoader*, unsigned long identifier, const char* data, int dataLength, int encodedDataLength)
@@ -135,11 +145,18 @@ void FrameFetchContext::dispatchDidReceiveData(DocumentLoader*, unsigned long id
InspectorInstrumentation::didReceiveData(m_frame, identifier, data, dataLength, encodedDataLength);
}
+void FrameFetchContext::dispatchDidDownloadData(DocumentLoader*, unsigned long identifier, int dataLength, int encodedDataLength)
+{
+ if (Page* page = m_frame->page())
+ page->progress().incrementProgress(identifier, 0, dataLength);
+ InspectorInstrumentation::didReceiveData(m_frame, identifier, 0, dataLength, encodedDataLength);
+}
+
void FrameFetchContext::dispatchDidFinishLoading(DocumentLoader* loader, unsigned long identifier, double finishTime)
{
if (Page* page = m_frame->page())
page->progress().completeProgress(identifier);
- m_frame->loader()->client()->dispatchDidFinishLoading(loader, identifier);
+ m_frame->loader().client()->dispatchDidFinishLoading(loader, identifier);
InspectorInstrumentation::didFinishLoading(m_frame, identifier, ensureLoader(loader), finishTime);
}
@@ -151,18 +168,15 @@ void FrameFetchContext::dispatchDidFail(DocumentLoader* loader, unsigned long id
InspectorInstrumentation::didFailLoading(m_frame, identifier, ensureLoader(loader), error);
}
-void FrameFetchContext::sendRemainingDelegateMessages(DocumentLoader* loader, unsigned long identifier, const ResourceResponse& response, const char* data, int dataLength, int encodedDataLength, const ResourceError& error)
+void FrameFetchContext::sendRemainingDelegateMessages(DocumentLoader* loader, unsigned long identifier, const ResourceResponse& response, int dataLength)
{
if (!response.isNull())
dispatchDidReceiveResponse(ensureLoader(loader), identifier, response);
if (dataLength > 0)
- dispatchDidReceiveData(ensureLoader(loader), identifier, data, dataLength, encodedDataLength);
+ dispatchDidReceiveData(ensureLoader(loader), identifier, 0, dataLength, 0);
- if (error.isNull())
- dispatchDidFinishLoading(ensureLoader(loader), identifier, 0);
- else
- dispatchDidFail(ensureLoader(loader), identifier, error);
+ dispatchDidFinishLoading(ensureLoader(loader), identifier, 0);
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/loader/FrameFetchContext.h b/chromium/third_party/WebKit/Source/core/loader/FrameFetchContext.h
index 77a92afb05a..f8a2050fd8d 100644
--- a/chromium/third_party/WebKit/Source/core/loader/FrameFetchContext.h
+++ b/chromium/third_party/WebKit/Source/core/loader/FrameFetchContext.h
@@ -32,11 +32,12 @@
#define FrameFetchContext_h
#include "core/fetch/FetchContext.h"
-#include "core/platform/network/ResourceRequest.h"
+#include "platform/network/ResourceRequest.h"
#include "wtf/PassOwnPtr.h"
namespace WebCore {
+class Document;
class DocumentLoader;
class Frame;
class Page;
@@ -51,15 +52,16 @@ public:
virtual void reportLocalLoadFailed(const KURL&) OVERRIDE;
virtual void addAdditionalRequestHeaders(Document&, ResourceRequest&, Resource::Type) OVERRIDE;
- virtual CachePolicy cachePolicy(Resource::Type) const OVERRIDE;
+ virtual CachePolicy cachePolicy(Document*) const OVERRIDE;
virtual void dispatchDidChangeResourcePriority(unsigned long identifier, ResourceLoadPriority);
virtual void dispatchWillSendRequest(DocumentLoader*, unsigned long identifier, ResourceRequest&, const ResourceResponse& redirectResponse, const FetchInitiatorInfo& = FetchInitiatorInfo()) OVERRIDE;
virtual void dispatchDidLoadResourceFromMemoryCache(const ResourceRequest&, const ResourceResponse&) OVERRIDE;
virtual void dispatchDidReceiveResponse(DocumentLoader*, unsigned long identifier, const ResourceResponse&, ResourceLoader* = 0) OVERRIDE;
- virtual void dispatchDidReceiveData(DocumentLoader*, unsigned long identifier, const char* data, int dataLength, int encodedDataLength) OVERRIDE;
+ virtual void dispatchDidReceiveData(DocumentLoader*, unsigned long identifier, const char* data, int dataLength, int encodedDataLength) OVERRIDE;
+ virtual void dispatchDidDownloadData(DocumentLoader*, unsigned long identifier, int dataLength, int encodedDataLength) OVERRIDE;
virtual void dispatchDidFinishLoading(DocumentLoader*, unsigned long identifier, double finishTime) OVERRIDE;
virtual void dispatchDidFail(DocumentLoader*, unsigned long identifier, const ResourceError&) OVERRIDE;
- virtual void sendRemainingDelegateMessages(DocumentLoader*, unsigned long identifier, const ResourceResponse&, const char* data, int dataLength, int encodedDataLength, const ResourceError&) OVERRIDE;
+ virtual void sendRemainingDelegateMessages(DocumentLoader*, unsigned long identifier, const ResourceResponse&, int dataLength) OVERRIDE;
private:
explicit FrameFetchContext(Frame*);
diff --git a/chromium/third_party/WebKit/Source/core/loader/FrameLoadRequest.h b/chromium/third_party/WebKit/Source/core/loader/FrameLoadRequest.h
index 7d3e4daaf79..5f854f83f6a 100644
--- a/chromium/third_party/WebKit/Source/core/loader/FrameLoadRequest.h
+++ b/chromium/third_party/WebKit/Source/core/loader/FrameLoadRequest.h
@@ -26,56 +26,56 @@
#ifndef FrameLoadRequest_h
#define FrameLoadRequest_h
-#include "core/dom/Event.h"
+#include "core/dom/Document.h"
+#include "core/events/Event.h"
#include "core/html/HTMLFormElement.h"
#include "core/loader/FrameLoaderTypes.h"
#include "core/loader/SubstituteData.h"
-#include "weborigin/SecurityOrigin.h"
-#include "core/platform/network/ResourceRequest.h"
+#include "platform/network/ResourceRequest.h"
namespace WebCore {
class Frame;
struct FrameLoadRequest {
public:
- explicit FrameLoadRequest(SecurityOrigin* requester)
- : m_requester(requester)
+ explicit FrameLoadRequest(Document* originDocument)
+ : m_originDocument(originDocument)
, m_lockBackForwardList(false)
- , m_clientRedirect(false)
+ , m_clientRedirect(NotClientRedirect)
, m_shouldSendReferrer(MaybeSendReferrer)
{
}
- FrameLoadRequest(SecurityOrigin* requester, const ResourceRequest& resourceRequest)
- : m_requester(requester)
+ FrameLoadRequest(Document* originDocument, const ResourceRequest& resourceRequest)
+ : m_originDocument(originDocument)
, m_resourceRequest(resourceRequest)
, m_lockBackForwardList(false)
- , m_clientRedirect(false)
+ , m_clientRedirect(NotClientRedirect)
, m_shouldSendReferrer(MaybeSendReferrer)
{
}
- FrameLoadRequest(SecurityOrigin* requester, const ResourceRequest& resourceRequest, const String& frameName)
- : m_requester(requester)
+ FrameLoadRequest(Document* originDocument, const ResourceRequest& resourceRequest, const String& frameName)
+ : m_originDocument(originDocument)
, m_resourceRequest(resourceRequest)
, m_frameName(frameName)
, m_lockBackForwardList(false)
- , m_clientRedirect(false)
+ , m_clientRedirect(NotClientRedirect)
, m_shouldSendReferrer(MaybeSendReferrer)
{
}
- FrameLoadRequest(SecurityOrigin* requester, const ResourceRequest& resourceRequest, const SubstituteData& substituteData)
- : m_requester(requester)
+ FrameLoadRequest(Document* originDocument, const ResourceRequest& resourceRequest, const SubstituteData& substituteData)
+ : m_originDocument(originDocument)
, m_resourceRequest(resourceRequest)
, m_substituteData(substituteData)
, m_lockBackForwardList(false)
- , m_clientRedirect(false)
+ , m_clientRedirect(NotClientRedirect)
, m_shouldSendReferrer(MaybeSendReferrer)
{
}
- const SecurityOrigin* requester() const { return m_requester.get(); }
+ Document* originDocument() const { return m_originDocument.get(); }
ResourceRequest& resourceRequest() { return m_resourceRequest; }
const ResourceRequest& resourceRequest() const { return m_resourceRequest; }
@@ -88,8 +88,8 @@ public:
bool lockBackForwardList() const { return m_lockBackForwardList; }
void setLockBackForwardList(bool lockBackForwardList) { m_lockBackForwardList = lockBackForwardList; }
- bool clientRedirect() const { return m_clientRedirect; }
- void setClientRedirect(bool clientRedirect) { m_clientRedirect = clientRedirect; }
+ ClientRedirectPolicy clientRedirect() const { return m_clientRedirect; }
+ void setClientRedirect(ClientRedirectPolicy clientRedirect) { m_clientRedirect = clientRedirect; }
Event* triggeringEvent() const { return m_triggeringEvent.get(); }
void setTriggeringEvent(PassRefPtr<Event> triggeringEvent) { m_triggeringEvent = triggeringEvent; }
@@ -101,12 +101,12 @@ public:
void setShouldSendReferrer(ShouldSendReferrer shouldSendReferrer) { m_shouldSendReferrer = shouldSendReferrer; }
private:
- RefPtr<SecurityOrigin> m_requester;
+ RefPtr<Document> m_originDocument;
ResourceRequest m_resourceRequest;
String m_frameName;
SubstituteData m_substituteData;
bool m_lockBackForwardList;
- bool m_clientRedirect;
+ ClientRedirectPolicy m_clientRedirect;
RefPtr<Event> m_triggeringEvent;
RefPtr<FormState> m_formState;
ShouldSendReferrer m_shouldSendReferrer;
diff --git a/chromium/third_party/WebKit/Source/core/loader/FrameLoader.cpp b/chromium/third_party/WebKit/Source/core/loader/FrameLoader.cpp
index 511588a8102..b32c0c08e3a 100644
--- a/chromium/third_party/WebKit/Source/core/loader/FrameLoader.cpp
+++ b/chromium/third_party/WebKit/Source/core/loader/FrameLoader.cpp
@@ -41,15 +41,19 @@
#include "bindings/v8/SerializedScriptValue.h"
#include "core/dom/Document.h"
#include "core/dom/Element.h"
-#include "core/dom/Event.h"
-#include "core/dom/EventNames.h"
-#include "core/dom/PageTransitionEvent.h"
#include "core/editing/Editor.h"
+#include "core/editing/UndoStack.h"
+#include "core/events/Event.h"
+#include "core/events/PageTransitionEvent.h"
+#include "core/events/ThreadLocalEventNames.h"
#include "core/fetch/FetchContext.h"
#include "core/fetch/ResourceFetcher.h"
#include "core/fetch/ResourceLoader.h"
-#include "core/history/BackForwardController.h"
-#include "core/history/HistoryItem.h"
+#include "core/frame/ContentSecurityPolicy.h"
+#include "core/frame/ContentSecurityPolicyResponseHeaders.h"
+#include "core/frame/DOMWindow.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
#include "core/html/HTMLFormElement.h"
#include "core/html/HTMLFrameOwnerElement.h"
#include "core/html/parser/HTMLParserIdioms.h"
@@ -62,31 +66,29 @@
#include "core/loader/FrameFetchContext.h"
#include "core/loader/FrameLoadRequest.h"
#include "core/loader/FrameLoaderClient.h"
-#include "core/loader/IconController.h"
#include "core/loader/ProgressTracker.h"
#include "core/loader/UniqueIdentifier.h"
#include "core/loader/appcache/ApplicationCacheHost.h"
+#include "core/page/BackForwardClient.h"
#include "core/page/Chrome.h"
#include "core/page/ChromeClient.h"
-#include "core/page/ContentSecurityPolicy.h"
-#include "core/page/ContentSecurityPolicyResponseHeaders.h"
-#include "core/page/DOMWindow.h"
+#include "core/page/CreateWindow.h"
#include "core/page/EventHandler.h"
-#include "core/page/Frame.h"
#include "core/page/FrameTree.h"
-#include "core/page/FrameView.h"
#include "core/page/Page.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
#include "core/page/WindowFeatures.h"
-#include "core/platform/Logging.h"
-#include "core/platform/ScrollAnimator.h"
-#include "core/platform/graphics/FloatRect.h"
-#include "core/platform/network/HTTPParsers.h"
-#include "core/platform/network/ResourceRequest.h"
+#include "core/page/scrolling/ScrollingCoordinator.h"
#include "core/xml/parser/XMLDocumentParser.h"
#include "modules/webdatabase/DatabaseManager.h"
-#include "weborigin/SecurityOrigin.h"
-#include "weborigin/SecurityPolicy.h"
+#include "platform/Logging.h"
+#include "platform/UserGestureIndicator.h"
+#include "platform/geometry/FloatRect.h"
+#include "platform/network/HTTPParsers.h"
+#include "platform/network/ResourceRequest.h"
+#include "platform/scroll/ScrollAnimator.h"
+#include "platform/weborigin/SecurityOrigin.h"
+#include "platform/weborigin/SecurityPolicy.h"
#include "wtf/TemporaryChange.h"
#include "wtf/text/CString.h"
#include "wtf/text/WTFString.h"
@@ -102,17 +104,6 @@ bool isBackForwardLoadType(FrameLoadType type)
return type == FrameLoadTypeBackForward;
}
-// This is not in the FrameLoader class to emphasize that it does not depend on
-// private FrameLoader data, and to avoid increasing the number of public functions
-// with access to private data. Since only this .cpp file needs it, making it
-// non-member lets us exclude it from the header file, thus keeping core/loader/FrameLoader.h's
-// API simpler.
-//
-static bool isDocumentSandboxed(Frame* frame, SandboxFlags mask)
-{
- return frame->document() && frame->document()->isSandboxed(mask);
-}
-
class FrameLoader::FrameProgressTracker {
public:
static PassOwnPtr<FrameProgressTracker> create(Frame* frame) { return adoptPtr(new FrameProgressTracker(frame)); }
@@ -153,22 +144,17 @@ private:
FrameLoader::FrameLoader(Frame* frame, FrameLoaderClient* client)
: m_frame(frame)
, m_client(client)
- , m_history(frame)
- , m_icon(adoptPtr(new IconController(frame)))
- , m_fetchContext(FrameFetchContext::create(frame))
, m_mixedContentChecker(frame)
, m_state(FrameStateProvisional)
, m_loadType(FrameLoadTypeStandard)
+ , m_fetchContext(FrameFetchContext::create(frame))
, m_inStopAllLoaders(false)
, m_isComplete(false)
- , m_containsPlugins(false)
, m_checkTimer(this, &FrameLoader::checkTimerFired)
, m_shouldCallCheckCompleted(false)
, m_opener(0)
, m_didAccessInitialDocument(false)
, m_didAccessInitialDocumentTimer(this, &FrameLoader::didAccessInitialDocumentTimerFired)
- , m_suppressOpenerInNewFrame(false)
- , m_startingClientRedirect(false)
, m_forcedSandboxFlags(SandboxNone)
{
}
@@ -179,7 +165,7 @@ FrameLoader::~FrameLoader()
HashSet<Frame*>::iterator end = m_openedFrames.end();
for (HashSet<Frame*>::iterator it = m_openedFrames.begin(); it != end; ++it)
- (*it)->loader()->m_opener = 0;
+ (*it)->loader().m_opener = 0;
m_client->frameLoaderDestroyed();
}
@@ -203,10 +189,9 @@ void FrameLoader::setDefersLoading(bool defers)
m_provisionalDocumentLoader->setDefersLoading(defers);
if (m_policyDocumentLoader)
m_policyDocumentLoader->setDefersLoading(defers);
- history()->setDefersLoading(defers);
if (!defers) {
- m_frame->navigationScheduler()->startTimer();
+ m_frame->navigationScheduler().startTimer();
startCheckCompleteTimer();
}
}
@@ -230,19 +215,50 @@ void FrameLoader::stopLoading()
}
// FIXME: This will cancel redirection timer, which really needs to be restarted when restoring the frame from b/f cache.
- m_frame->navigationScheduler()->cancel();
+ m_frame->navigationScheduler().cancel();
+}
+
+void FrameLoader::saveDocumentAndScrollState()
+{
+ if (!m_currentItem)
+ return;
+
+ Document* document = m_frame->document();
+ if (m_currentItem->isCurrentDocument(document) && document->isActive())
+ m_currentItem->setDocumentState(document->formElementsState());
+
+ if (!m_frame->view())
+ return;
+
+ m_currentItem->setScrollPoint(m_frame->view()->scrollPosition());
+ if (m_frame->isMainFrame() && !m_frame->page()->inspectorController().deviceEmulationEnabled())
+ m_currentItem->setPageScaleFactor(m_frame->page()->pageScaleFactor());
+}
+
+void FrameLoader::clearScrollPositionAndViewState()
+{
+ ASSERT(m_frame->isMainFrame());
+ if (!m_currentItem)
+ return;
+ m_currentItem->clearScrollPoint();
+ m_currentItem->setPageScaleFactor(0);
}
bool FrameLoader::closeURL()
{
- history()->saveDocumentState();
+ // This is done when a back/forward navigation begins (and the current item
+ // changes) in loadHistoryItem(). Saving now will save the state will save
+ // to the wrong item if the navigation is back/forward.
+ if (m_loadType != FrameLoadTypeBackForward)
+ saveDocumentAndScrollState();
// Should only send the pagehide event here if the current document exists.
if (m_frame->document())
m_frame->document()->dispatchUnloadEvents();
stopLoading();
- m_frame->editor().clearUndoRedoOperations();
+ if (Page* page = m_frame->page())
+ page->undoStack().didUnloadFrame(*m_frame);
return true;
}
@@ -258,7 +274,7 @@ void FrameLoader::didExplicitOpen()
// from a subsequent window.document.open / window.document.write call.
// Canceling redirection here works for all cases because document.open
// implicitly precedes document.write.
- m_frame->navigationScheduler()->cancel();
+ m_frame->navigationScheduler().cancel();
}
void FrameLoader::clear(ClearOptions options)
@@ -268,21 +284,18 @@ void FrameLoader::clear(ClearOptions options)
m_frame->editor().clear();
m_frame->document()->cancelParsing();
- m_frame->document()->stopActiveDOMObjects();
- if (m_frame->document()->attached()) {
- m_frame->document()->prepareForDestruction();
- m_frame->document()->removeFocusedElementOfSubtree(m_frame->document());
- }
+ m_frame->document()->prepareForDestruction();
+ m_frame->document()->removeFocusedElementOfSubtree(m_frame->document());
// Do this after detaching the document so that the unload event works.
if (options & ClearWindowProperties) {
InspectorInstrumentation::frameWindowDiscarded(m_frame, m_frame->domWindow());
m_frame->domWindow()->reset();
- m_frame->script()->clearWindowShell();
+ m_frame->script().clearWindowShell();
}
m_frame->selection().prepareForDestruction();
- m_frame->eventHandler()->clear();
+ m_frame->eventHandler().clear();
if (m_frame->view())
m_frame->view()->clear();
@@ -292,14 +305,12 @@ void FrameLoader::clear(ClearOptions options)
m_frame->setDOMWindow(0);
}
- m_containsPlugins = false;
-
if (options & ClearScriptObjects)
- m_frame->script()->clearScriptObjects();
+ m_frame->script().clearScriptObjects();
- m_frame->script()->enableEval();
+ m_frame->script().enableEval();
- m_frame->navigationScheduler()->clear();
+ m_frame->navigationScheduler().clear();
m_checkTimer.stop();
m_shouldCallCheckCompleted = false;
@@ -308,28 +319,53 @@ void FrameLoader::clear(ClearOptions options)
m_stateMachine.advanceTo(FrameLoaderStateMachine::CommittedFirstRealLoad);
}
+void FrameLoader::setHistoryItemStateForCommit(HistoryItemPolicy historyItemPolicy)
+{
+ if (!m_currentItem || historyItemPolicy == CreateNewHistoryItem || m_currentItem->url() != m_documentLoader->url()) {
+ if (!m_currentItem || historyItemPolicy == CreateNewHistoryItem)
+ m_currentItem = HistoryItem::create();
+ else
+ m_currentItem->reset();
+ const KURL& unreachableURL = m_documentLoader->unreachableURL();
+ const KURL& url = unreachableURL.isEmpty() ? m_documentLoader->requestURL() : unreachableURL;
+ const KURL& originalURL = unreachableURL.isEmpty() ? m_documentLoader->originalURL() : unreachableURL;
+ m_currentItem->setURL(url);
+ m_currentItem->setTarget(m_frame->tree().uniqueName());
+ m_currentItem->setTargetFrameID(m_frame->frameID());
+ m_currentItem->setOriginalURLString(originalURL.string());
+ }
+ m_currentItem->setFormInfoFromRequest(m_documentLoader->request());
+}
+
void FrameLoader::receivedFirstData()
{
if (m_stateMachine.creatingInitialEmptyDocument())
return;
- m_client->dispatchDidCommitLoad();
+ NavigationHistoryPolicy navigationHistoryPolicy = NavigationReusedHistoryEntry;
+ if (m_loadType == FrameLoadTypeStandard && m_documentLoader->isURLValidForNewHistoryEntry())
+ navigationHistoryPolicy = NavigationCreatedHistoryEntry;
+ HistoryItemPolicy historyItemPolicy = DoNotCreateNewHistoryItem;
+ if (m_loadType == FrameLoadTypeInitialInChildFrame || navigationHistoryPolicy == NavigationCreatedHistoryEntry)
+ historyItemPolicy = CreateNewHistoryItem;
+ setHistoryItemStateForCommit(historyItemPolicy);
+
+ if (!m_stateMachine.committedMultipleRealLoads() && navigationHistoryPolicy == NavigationCreatedHistoryEntry)
+ m_stateMachine.advanceTo(FrameLoaderStateMachine::CommittedMultipleRealLoads);
+
+ m_client->dispatchDidCommitLoad(m_frame, m_currentItem.get(), navigationHistoryPolicy);
+
InspectorInstrumentation::didCommitLoad(m_frame, m_documentLoader.get());
m_frame->page()->didCommitLoad(m_frame);
dispatchDidClearWindowObjectsInAllWorlds();
}
-void FrameLoader::setOutgoingReferrer(const KURL& url)
-{
- m_outgoingReferrer = url.strippedForUseAsReferrer();
-}
-
void FrameLoader::didBeginDocument(bool dispatch)
{
m_isComplete = false;
m_frame->document()->setReadyState(Document::Loading);
- if (history()->currentItem() && m_loadType == FrameLoadTypeBackForward)
- m_frame->document()->statePopped(history()->currentItem()->stateObject());
+ if (m_currentItem && m_loadType == FrameLoadTypeBackForward)
+ m_frame->domWindow()->statePopped(m_currentItem->stateObject());
if (dispatch)
dispatchDidClearWindowObjectsInAllWorlds();
@@ -338,12 +374,12 @@ void FrameLoader::didBeginDocument(bool dispatch)
Settings* settings = m_frame->document()->settings();
if (settings) {
- m_frame->document()->fetcher()->setImagesEnabled(settings->areImagesEnabled());
+ m_frame->document()->fetcher()->setImagesEnabled(settings->imagesEnabled());
m_frame->document()->fetcher()->setAutoLoadImages(settings->loadsImagesAutomatically());
}
if (m_documentLoader) {
- String dnsPrefetchControl = m_documentLoader->response().httpHeaderField("X-DNS-Prefetch-Control");
+ const AtomicString& dnsPrefetchControl = m_documentLoader->response().httpHeaderField("X-DNS-Prefetch-Control");
if (!dnsPrefetchControl.isEmpty())
m_frame->document()->parseDNSPrefetchControlHeader(dnsPrefetchControl);
@@ -353,11 +389,12 @@ void FrameLoader::didBeginDocument(bool dispatch)
headerContentLanguage.truncate(commaIndex); // kNotFound == -1 == don't truncate
headerContentLanguage = headerContentLanguage.stripWhiteSpace(isHTMLSpace<UChar>);
if (!headerContentLanguage.isEmpty())
- m_frame->document()->setContentLanguage(headerContentLanguage);
+ m_frame->document()->setContentLanguage(AtomicString(headerContentLanguage));
}
}
- history()->restoreDocumentState();
+ if (m_currentItem && m_loadType == FrameLoadTypeBackForward)
+ m_frame->document()->setStateForNewFormElements(m_currentItem->documentState());
}
void FrameLoader::finishedParsing()
@@ -390,8 +427,8 @@ void FrameLoader::loadDone()
bool FrameLoader::allChildrenAreComplete() const
{
- for (Frame* child = m_frame->tree()->firstChild(); child; child = child->tree()->nextSibling()) {
- if (!child->loader()->m_isComplete)
+ for (Frame* child = m_frame->tree().firstChild(); child; child = child->tree().nextSibling()) {
+ if (!child->loader().m_isComplete)
return false;
}
return true;
@@ -399,7 +436,7 @@ bool FrameLoader::allChildrenAreComplete() const
bool FrameLoader::allAncestorsAreComplete() const
{
- for (Frame* ancestor = m_frame; ancestor; ancestor = ancestor->tree()->parent()) {
+ for (Frame* ancestor = m_frame; ancestor; ancestor = ancestor->tree().parent()) {
if (!ancestor->document()->loadEventFinished())
return false;
}
@@ -436,12 +473,11 @@ void FrameLoader::checkCompleted()
// OK, completed.
m_isComplete = true;
- m_requestedHistoryItem = 0;
m_frame->document()->setReadyState(Document::Complete);
if (m_frame->document()->loadEventStillNeeded())
m_frame->document()->implicitClose();
- m_frame->navigationScheduler()->startTimer();
+ m_frame->navigationScheduler().startTimer();
completed();
if (m_frame->page())
@@ -478,25 +514,6 @@ void FrameLoader::scheduleCheckCompleted()
startCheckCompleteTimer();
}
-String FrameLoader::outgoingReferrer() const
-{
- // See http://www.whatwg.org/specs/web-apps/current-work/#fetching-resources
- // for why we walk the parent chain for srcdoc documents.
- Frame* frame = m_frame;
- while (frame->document()->isSrcdocDocument()) {
- frame = frame->tree()->parent();
- // Srcdoc documents cannot be top-level documents, by definition,
- // because they need to be contained in iframes with the srcdoc.
- ASSERT(frame);
- }
- return frame->loader()->m_outgoingReferrer;
-}
-
-String FrameLoader::outgoingOrigin() const
-{
- return m_frame->document()->securityOrigin()->toString();
-}
-
Frame* FrameLoader::opener()
{
return m_opener;
@@ -508,9 +525,9 @@ void FrameLoader::setOpener(Frame* opener)
m_client->didDisownOpener();
if (m_opener)
- m_opener->loader()->m_openedFrames.remove(m_frame);
+ m_opener->loader().m_openedFrames.remove(m_frame);
if (opener)
- opener->loader()->m_openedFrames.add(m_frame);
+ opener->loader().m_openedFrames.add(m_frame);
m_opener = opener;
if (m_frame->document())
@@ -520,34 +537,17 @@ void FrameLoader::setOpener(Frame* opener)
bool FrameLoader::allowPlugins(ReasonForCallingAllowPlugins reason)
{
Settings* settings = m_frame->settings();
- bool allowed = m_client->allowPlugins(settings && settings->arePluginsEnabled());
+ bool allowed = m_client->allowPlugins(settings && settings->pluginsEnabled());
if (!allowed && reason == AboutToInstantiatePlugin)
m_client->didNotAllowPlugins();
return allowed;
}
-void FrameLoader::updateForSameDocumentNavigation(const KURL& newURL, SameDocumentNavigationSource sameDocumentNavigationSource, PassRefPtr<SerializedScriptValue> data, const String& title, UpdateBackForwardListPolicy updateBackForwardList)
+void FrameLoader::updateForSameDocumentNavigation(const KURL& newURL, SameDocumentNavigationSource sameDocumentNavigationSource, PassRefPtr<SerializedScriptValue> data, UpdateBackForwardListPolicy updateBackForwardList)
{
// Update the data source's request with the new URL to fake the URL change
- KURL oldURL = m_frame->document()->url();
m_frame->document()->setURL(newURL);
- setOutgoingReferrer(newURL);
- documentLoader()->replaceRequestURLForSameDocumentNavigation(newURL);
-
- // updateBackForwardListForFragmentScroll() must happen after
- // replaceRequestURLForSameDocumentNavigation(), since we add based on
- // the current request.
- if (updateBackForwardList == UpdateBackForwardList)
- history()->updateBackForwardListForFragmentScroll();
-
- if (sameDocumentNavigationSource == SameDocumentNavigationDefault)
- history()->updateForSameDocumentNavigation();
- else if (sameDocumentNavigationSource == SameDocumentNavigationPushState)
- history()->pushState(data, title, newURL.string());
- else if (sameDocumentNavigationSource == SameDocumentNavigationReplaceState)
- history()->replaceState(data, title, newURL.string());
- else
- ASSERT_NOT_REACHED();
+ documentLoader()->updateForSameDocumentNavigation(newURL);
// Generate start and stop notifications only when loader is completed so that we
// don't fire them for fragment redirection that happens in window.onload handler.
@@ -555,19 +555,28 @@ void FrameLoader::updateForSameDocumentNavigation(const KURL& newURL, SameDocume
if (m_frame->document()->loadEventFinished())
m_client->postProgressStartedNotification();
- m_documentLoader->clearRedirectChain();
- if (m_documentLoader->isClientRedirect())
- m_documentLoader->appendRedirect(oldURL);
- m_documentLoader->appendRedirect(newURL);
-
- m_client->dispatchDidNavigateWithinPage();
+ NavigationHistoryPolicy navigationHistoryPolicy = NavigationReusedHistoryEntry;
+ if (updateBackForwardList == UpdateBackForwardList || (sameDocumentNavigationSource == SameDocumentNavigationPushState && m_currentItem)) {
+ navigationHistoryPolicy = NavigationCreatedHistoryEntry;
+ setHistoryItemStateForCommit(CreateNewHistoryItem);
+ }
+ m_client->dispatchDidNavigateWithinPage(navigationHistoryPolicy, m_currentItem.get());
m_client->dispatchDidReceiveTitle(m_frame->document()->title());
+ if (m_currentItem) {
+ m_currentItem->setURL(newURL);
+ if (sameDocumentNavigationSource != SameDocumentNavigationDefault) {
+ m_currentItem->setStateObject(data);
+ m_currentItem->setFormData(0);
+ m_currentItem->setFormContentType(nullAtom);
+ }
+ }
+
if (m_frame->document()->loadEventFinished())
m_client->postProgressFinishedNotification();
}
-void FrameLoader::loadInSameDocument(const KURL& url, PassRefPtr<SerializedScriptValue> stateObject, bool isNewNavigation)
+void FrameLoader::loadInSameDocument(const KURL& url, PassRefPtr<SerializedScriptValue> stateObject, bool isNewNavigation, ClientRedirectPolicy clientRedirect)
{
// If we have a state object, we cannot also be a new navigation.
ASSERT(!stateObject || (stateObject && !isNewNavigation));
@@ -576,13 +585,13 @@ void FrameLoader::loadInSameDocument(const KURL& url, PassRefPtr<SerializedScrip
// If we were in the autoscroll/panScroll mode we want to stop it before following the link to the anchor
bool hashChange = equalIgnoringFragmentIdentifier(url, oldURL) && url.fragmentIdentifier() != oldURL.fragmentIdentifier();
if (hashChange) {
- m_frame->eventHandler()->stopAutoscrollTimer();
- m_frame->document()->enqueueHashchangeEvent(oldURL, url);
+ m_frame->eventHandler().stopAutoscroll();
+ m_frame->domWindow()->enqueueHashchangeEvent(oldURL, url);
}
- m_documentLoader->setIsClientRedirect((m_startingClientRedirect && !isNewNavigation) || !UserGestureIndicator::processingUserGesture());
+ m_documentLoader->setIsClientRedirect((clientRedirect == ClientRedirect && !isNewNavigation) || !UserGestureIndicator::processingUserGesture());
m_documentLoader->setReplacesCurrentHistoryItem(!isNewNavigation);
UpdateBackForwardListPolicy updateBackForwardList = isNewNavigation && !shouldTreatURLAsSameAsCurrent(url) && !stateObject ? UpdateBackForwardList : DoNotUpdateBackForwardList;
- updateForSameDocumentNavigation(url, SameDocumentNavigationDefault, 0, String(), updateBackForwardList);
+ updateForSameDocumentNavigation(url, SameDocumentNavigationDefault, 0, updateBackForwardList);
// It's important to model this as a load that starts and immediately finishes.
// Otherwise, the parent frame may think we never finished loading.
@@ -595,18 +604,18 @@ void FrameLoader::loadInSameDocument(const KURL& url, PassRefPtr<SerializedScrip
m_isComplete = false;
checkCompleted();
- m_frame->document()->statePopped(stateObject ? stateObject : SerializedScriptValue::nullValue());
+ m_frame->domWindow()->statePopped(stateObject ? stateObject : SerializedScriptValue::nullValue());
}
void FrameLoader::completed()
{
RefPtr<Frame> protect(m_frame);
- for (Frame* descendant = m_frame->tree()->traverseNext(m_frame); descendant; descendant = descendant->tree()->traverseNext(m_frame))
- descendant->navigationScheduler()->startTimer();
+ for (Frame* descendant = m_frame->tree().traverseNext(m_frame); descendant; descendant = descendant->tree().traverseNext(m_frame))
+ descendant->navigationScheduler().startTimer();
- if (Frame* parent = m_frame->tree()->parent())
- parent->loader()->checkCompleted();
+ if (Frame* parent = m_frame->tree().parent())
+ parent->loader().checkCompleted();
if (m_frame->view())
m_frame->view()->maintainScrollPositionAtAnchor(0);
@@ -614,35 +623,24 @@ void FrameLoader::completed()
void FrameLoader::started()
{
- for (Frame* frame = m_frame; frame; frame = frame->tree()->parent())
- frame->loader()->m_isComplete = false;
+ for (Frame* frame = m_frame; frame; frame = frame->tree().parent())
+ frame->loader().m_isComplete = false;
}
-void FrameLoader::prepareForHistoryNavigation()
-{
- // If there is no currentItem, but we still want to engage in
- // history navigation we need to manufacture one, and update
- // the state machine of this frame to impersonate having
- // loaded it.
- RefPtr<HistoryItem> currentItem = history()->currentItem();
- if (!currentItem) {
- insertDummyHistoryItem();
- ASSERT(stateMachine()->isDisplayingInitialEmptyDocument());
- stateMachine()->advanceTo(FrameLoaderStateMachine::CommittedFirstRealLoad);
- }
-}
-
-void FrameLoader::setReferrerForFrameRequest(ResourceRequest& request, ShouldSendReferrer shouldSendReferrer)
+void FrameLoader::setReferrerForFrameRequest(ResourceRequest& request, ShouldSendReferrer shouldSendReferrer, Document* originDocument)
{
if (shouldSendReferrer == NeverSendReferrer) {
request.clearHTTPReferrer();
return;
}
+ // Always use the initiating document to generate the referrer.
+ // We need to generateReferrerHeader(), because we might not have enforced ReferrerPolicy or https->http
+ // referrer suppression yet.
String argsReferrer(request.httpReferrer());
if (argsReferrer.isEmpty())
- argsReferrer = outgoingReferrer();
- String referrer = SecurityPolicy::generateReferrerHeader(m_frame->document()->referrerPolicy(), request.url(), argsReferrer);
+ argsReferrer = originDocument->outgoingReferrer();
+ String referrer = SecurityPolicy::generateReferrerHeader(originDocument->referrerPolicy(), request.url(), argsReferrer);
request.setHTTPReferrer(referrer);
RefPtr<SecurityOrigin> referrerOrigin = SecurityOrigin::createFromString(referrer);
@@ -654,20 +652,22 @@ bool FrameLoader::isScriptTriggeredFormSubmissionInChildFrame(const FrameLoadReq
// If this is a child frame and the form submission was triggered by a script, lock the back/forward list
// to match IE and Opera.
// See https://bugs.webkit.org/show_bug.cgi?id=32383 for the original motivation for this.
- if (!m_frame->tree()->parent() || ScriptController::processingUserGesture())
+ if (!m_frame->tree().parent() || UserGestureIndicator::processingUserGesture())
return false;
return request.formState() && request.formState()->formSubmissionTrigger() == SubmittedByJavaScript;
}
FrameLoadType FrameLoader::determineFrameLoadType(const FrameLoadRequest& request)
{
- if (m_frame->tree()->parent() && !m_stateMachine.startedFirstRealLoad())
+ if (m_frame->tree().parent() && !m_stateMachine.startedFirstRealLoad())
return FrameLoadTypeInitialInChildFrame;
+ if (!m_frame->tree().parent() && !m_frame->page()->backForward().backForwardListCount())
+ return FrameLoadTypeStandard;
if (request.resourceRequest().cachePolicy() == ReloadIgnoringCacheData)
return FrameLoadTypeReload;
if (request.lockBackForwardList() || isScriptTriggeredFormSubmissionInChildFrame(request))
return FrameLoadTypeRedirectWithLockedBackForwardList;
- if (!request.requester() && shouldTreatURLAsSameAsCurrent(request.resourceRequest().url()))
+ if (!request.originDocument() && shouldTreatURLAsSameAsCurrent(request.resourceRequest().url()))
return FrameLoadTypeSame;
if (shouldTreatURLAsSameAsCurrent(request.substituteData().failingURL()) && m_loadType == FrameLoadTypeReload)
return FrameLoadTypeReload;
@@ -676,44 +676,28 @@ FrameLoadType FrameLoader::determineFrameLoadType(const FrameLoadRequest& reques
bool FrameLoader::prepareRequestForThisFrame(FrameLoadRequest& request)
{
- // If no SecurityOrigin was specified, skip security checks and assume the caller has fully initialized the FrameLoadRequest.
- if (!request.requester())
+ // If no origin Document* was specified, skip security checks and assume the caller has fully initialized the FrameLoadRequest.
+ if (!request.originDocument())
return true;
KURL url = request.resourceRequest().url();
- if (m_frame->script()->executeScriptIfJavaScriptURL(url))
+ if (m_frame->script().executeScriptIfJavaScriptURL(url))
return false;
- if (!request.requester()->canDisplay(url)) {
+ if (!request.originDocument()->securityOrigin()->canDisplay(url)) {
reportLocalLoadFailed(m_frame, url.elidedString());
return false;
}
- if (request.requester() && !request.formState() && request.frameName().isEmpty())
+ if (!request.formState() && request.frameName().isEmpty())
request.setFrameName(m_frame->document()->baseTarget());
- // If the requesting SecurityOrigin is not this Frame's SecurityOrigin, the request was initiated by a different frame that should
- // have already set the referrer.
- if (request.requester() == m_frame->document()->securityOrigin())
- setReferrerForFrameRequest(request.resourceRequest(), request.shouldSendReferrer());
+ setReferrerForFrameRequest(request.resourceRequest(), request.shouldSendReferrer(), request.originDocument());
return true;
}
-static bool shouldOpenInNewWindow(Frame* targetFrame, const FrameLoadRequest& request, const NavigationAction& action)
-{
- if (!targetFrame && !request.frameName().isEmpty())
- return true;
- if (!request.formState())
- return false;
- NavigationPolicy navigationPolicy = NavigationPolicyCurrentTab;
- if (!action.specifiesNavigationPolicy(&navigationPolicy))
- return false;
- return navigationPolicy != NavigationPolicyCurrentTab;
-}
-
void FrameLoader::load(const FrameLoadRequest& passedRequest)
{
- ASSERT(!m_suppressOpenerInNewFrame);
ASSERT(m_frame->document());
// Protect frame from getting blown away inside dispatchBeforeLoadEvent in loadWithDocumentLoader.
@@ -726,10 +710,10 @@ void FrameLoader::load(const FrameLoadRequest& passedRequest)
if (!prepareRequestForThisFrame(request))
return;
- RefPtr<Frame> targetFrame = findFrameForNavigation(request.frameName(), request.formState() ? request.formState()->sourceDocument() : m_frame->document());
+ RefPtr<Frame> targetFrame = request.formState() ? 0 : findFrameForNavigation(request.frameName(), request.formState() ? request.formState()->sourceDocument() : m_frame->document());
if (targetFrame && targetFrame != m_frame) {
request.setFrameName("_self");
- targetFrame->loader()->load(request);
+ targetFrame->loader().load(request);
if (Page* page = targetFrame->page())
page->chrome().focus();
return;
@@ -737,19 +721,20 @@ void FrameLoader::load(const FrameLoadRequest& passedRequest)
FrameLoadType newLoadType = determineFrameLoadType(request);
NavigationAction action(request.resourceRequest(), newLoadType, request.formState(), request.triggeringEvent());
- if (shouldOpenInNewWindow(targetFrame.get(), request, action)) {
- TemporaryChange<bool> changeOpener(m_suppressOpenerInNewFrame, request.shouldSendReferrer() == NeverSendReferrer);
- checkNewWindowPolicyAndContinue(request.formState(), request.frameName(), action);
+ if ((!targetFrame && !request.frameName().isEmpty()) || action.shouldOpenInNewWindow()) {
+ if (action.policy() == NavigationPolicyDownload)
+ m_client->loadURLExternally(action.resourceRequest(), NavigationPolicyDownload);
+ else
+ createWindowForRequest(request, m_frame, action.policy(), request.shouldSendReferrer());
return;
}
- TemporaryChange<bool> changeClientRedirect(m_startingClientRedirect, request.clientRedirect());
if (shouldPerformFragmentNavigation(request.formState(), request.resourceRequest().httpMethod(), newLoadType, request.resourceRequest().url())) {
- checkNavigationPolicyAndContinueFragmentScroll(action, newLoadType != FrameLoadTypeRedirectWithLockedBackForwardList);
+ checkNavigationPolicyAndContinueFragmentScroll(action, newLoadType != FrameLoadTypeRedirectWithLockedBackForwardList, request.clientRedirect());
return;
}
bool sameURL = shouldTreatURLAsSameAsCurrent(request.resourceRequest().url());
- loadWithNavigationAction(request.resourceRequest(), action, newLoadType, request.formState(), request.substituteData());
+ loadWithNavigationAction(action, newLoadType, request.formState(), request.substituteData(), request.clientRedirect());
// Example of this case are sites that reload the same URL with a different cookie
// driving the generated content, or a master frame with links that drive a target
// frame, where the user has clicked on the same link repeatedly.
@@ -776,16 +761,12 @@ void FrameLoader::reportLocalLoadFailed(Frame* frame, const String& url)
frame->document()->addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, "Not allowed to load local resource: " + url);
}
-void FrameLoader::reload(ReloadPolicy reloadPolicy, const KURL& overrideURL, const String& overrideEncoding)
+void FrameLoader::reload(ReloadPolicy reloadPolicy, const KURL& overrideURL, const AtomicString& overrideEncoding)
{
DocumentLoader* documentLoader = activeDocumentLoader();
if (!documentLoader)
return;
- if (m_state == FrameStateProvisional)
- insertDummyHistoryItem();
- frame()->loader()->history()->saveDocumentAndScrollState();
-
ResourceRequest request = documentLoader->request();
// FIXME: We need to reset cache policy to prevent it from being incorrectly propagted to the reload.
// Do we need to propagate anything other than the url?
@@ -797,10 +778,10 @@ void FrameLoader::reload(ReloadPolicy reloadPolicy, const KURL& overrideURL, con
FrameLoadType type = reloadPolicy == EndToEndReload ? FrameLoadTypeReloadFromOrigin : FrameLoadTypeReload;
NavigationAction action(request, type, request.httpMethod() == "POST");
- loadWithNavigationAction(request, action, type, 0, SubstituteData(), overrideEncoding);
+ loadWithNavigationAction(action, type, 0, SubstituteData(), NotClientRedirect, overrideEncoding);
}
-void FrameLoader::stopAllLoaders(ClearProvisionalItemPolicy clearProvisionalItemPolicy)
+void FrameLoader::stopAllLoaders()
{
if (m_frame->document()->pageDismissalEventBeingDispatched() != Document::NoDismissal)
return;
@@ -815,13 +796,8 @@ void FrameLoader::stopAllLoaders(ClearProvisionalItemPolicy clearProvisionalItem
m_inStopAllLoaders = true;
- // If no new load is in progress, we should clear the provisional item from history
- // before we call stopLoading.
- if (clearProvisionalItemPolicy == ShouldClearProvisionalItem)
- history()->setProvisionalItem(0);
-
- for (RefPtr<Frame> child = m_frame->tree()->firstChild(); child; child = child->tree()->nextSibling())
- child->loader()->stopAllLoaders(clearProvisionalItemPolicy);
+ for (RefPtr<Frame> child = m_frame->tree().firstChild(); child; child = child->tree().nextSibling())
+ child->loader().stopAllLoaders();
if (m_provisionalDocumentLoader)
m_provisionalDocumentLoader->stopLoading();
if (m_documentLoader)
@@ -834,6 +810,8 @@ void FrameLoader::stopAllLoaders(ClearProvisionalItemPolicy clearProvisionalItem
m_checkTimer.stop();
m_inStopAllLoaders = false;
+
+ m_client->didStopAllLoaders();
}
DocumentLoader* FrameLoader::activeDocumentLoader() const
@@ -906,10 +884,8 @@ void FrameLoader::commitProvisionalLoad()
if (isLoadingMainFrame())
m_frame->page()->chrome().client().needTouchEvents(false);
- history()->updateForCommit();
m_client->transitionToCommittedForNewPage();
-
- m_frame->navigationScheduler()->cancel();
+ m_frame->navigationScheduler().cancel();
m_frame->editor().clearLastEditCommand();
// If we are still in the process of initializing an empty document then
@@ -928,8 +904,8 @@ void FrameLoader::closeOldDataSources()
// FIXME: Is it important for this traversal to be postorder instead of preorder?
// If so, add helpers for postorder traversal, and use them. If not, then lets not
// use a recursive algorithm here.
- for (Frame* child = m_frame->tree()->firstChild(); child; child = child->tree()->nextSibling())
- child->loader()->closeOldDataSources();
+ for (Frame* child = m_frame->tree().firstChild(); child; child = child->tree().nextSibling())
+ child->loader().closeOldDataSources();
if (m_documentLoader)
m_client->dispatchWillClose();
@@ -937,22 +913,21 @@ void FrameLoader::closeOldDataSources()
bool FrameLoader::isLoadingMainFrame() const
{
- Page* page = m_frame->page();
- return page && m_frame == page->mainFrame();
+ return m_frame->isMainFrame();
}
bool FrameLoader::subframeIsLoading() const
{
// It's most likely that the last added frame is the last to load so we walk backwards.
- for (Frame* child = m_frame->tree()->lastChild(); child; child = child->tree()->previousSibling()) {
- FrameLoader* childLoader = child->loader();
- DocumentLoader* documentLoader = childLoader->documentLoader();
+ for (Frame* child = m_frame->tree().lastChild(); child; child = child->tree().previousSibling()) {
+ const FrameLoader& childLoader = child->loader();
+ DocumentLoader* documentLoader = childLoader.documentLoader();
if (documentLoader && documentLoader->isLoadingInAPISense())
return true;
- documentLoader = childLoader->provisionalDocumentLoader();
+ documentLoader = childLoader.provisionalDocumentLoader();
if (documentLoader && documentLoader->isLoadingInAPISense())
return true;
- documentLoader = childLoader->policyDocumentLoader();
+ documentLoader = childLoader.policyDocumentLoader();
if (documentLoader)
return true;
}
@@ -964,31 +939,6 @@ FrameLoadType FrameLoader::loadType() const
return m_loadType;
}
-CachePolicy FrameLoader::subresourceCachePolicy() const
-{
- if (m_frame->document()->loadEventFinished())
- return CachePolicyVerify;
-
- if (m_loadType == FrameLoadTypeReloadFromOrigin)
- return CachePolicyReload;
-
- if (Frame* parentFrame = m_frame->tree()->parent()) {
- CachePolicy parentCachePolicy = parentFrame->loader()->subresourceCachePolicy();
- if (parentCachePolicy != CachePolicyVerify)
- return parentCachePolicy;
- }
-
- if (m_loadType == FrameLoadTypeReload)
- return CachePolicyRevalidate;
-
- const ResourceRequest& request(documentLoader()->request());
-
- if (request.cachePolicy() == ReturnCacheDataElseLoad)
- return CachePolicyHistoryBuffer;
-
- return CachePolicyVerify;
-}
-
void FrameLoader::checkLoadCompleteForThisFrame()
{
ASSERT(m_client->hasWebView());
@@ -1005,11 +955,6 @@ void FrameLoader::checkLoadCompleteForThisFrame()
m_provisionalDocumentLoader = 0;
m_progressTracker->progressCompleted();
m_state = FrameStateComplete;
-
- // Reset the back forward list to the last committed history item at the top level.
- RefPtr<HistoryItem> item = m_frame->page()->mainFrame()->loader()->history()->currentItem();
- if (isBackForwardLoadType(loadType()) && !history()->provisionalItem() && item)
- m_frame->page()->backForward().setCurrentItem(item.get());
}
if (m_state != FrameStateCommittedPage)
@@ -1025,19 +970,12 @@ void FrameLoader::checkLoadCompleteForThisFrame()
// the new page is ready.
// If the user had a scroll point, scroll to it, overriding the anchor point if any.
- if (m_frame->page()) {
- if (isBackForwardLoadType(m_loadType) || m_loadType == FrameLoadTypeReload || m_loadType == FrameLoadTypeReloadFromOrigin)
- history()->restoreScrollPositionAndViewState();
- }
+ restoreScrollPositionAndViewState();
if (!m_stateMachine.committedFirstRealDocumentLoad())
return;
m_progressTracker->progressCompleted();
- if (Page* page = m_frame->page()) {
- if (m_frame == page->mainFrame())
- page->resetRelevantPaintedObjectCounter();
- }
const ResourceError& error = m_documentLoader->mainDocumentError();
if (!error.isNull())
@@ -1047,32 +985,56 @@ void FrameLoader::checkLoadCompleteForThisFrame()
m_loadType = FrameLoadTypeStandard;
}
-void FrameLoader::didLayout(LayoutMilestones milestones)
+// There is a race condition between the layout and load completion that affects restoring the scroll position.
+// We try to restore the scroll position at both the first layout and upon load completion.
+// 1) If first layout happens before the load completes, we want to restore the scroll position then so that the
+// first time we draw the page is already scrolled to the right place, instead of starting at the top and later
+// jumping down. It is possible that the old scroll position is past the part of the doc laid out so far, in
+// which case the restore silent fails and we will fix it in when we try to restore on doc completion.
+// 2) If the layout happens after the load completes, the attempt to restore at load completion time silently
+// fails. We then successfully restore it when the layout happens.
+void FrameLoader::restoreScrollPositionAndViewState(RestorePolicy restorePolicy)
{
- m_client->dispatchDidLayout(milestones);
+ if (!isBackForwardLoadType(m_loadType) && m_loadType != FrameLoadTypeReload && m_loadType != FrameLoadTypeReloadFromOrigin && restorePolicy != ForcedRestoreForSameDocumentHistoryNavigation)
+ return;
+ if (!m_frame->page() || !m_currentItem || !m_stateMachine.committedFirstRealDocumentLoad())
+ return;
+
+ if (FrameView* view = m_frame->view()) {
+ if (m_frame->isMainFrame()) {
+ if (ScrollingCoordinator* scrollingCoordinator = m_frame->page()->scrollingCoordinator())
+ scrollingCoordinator->frameViewRootLayerDidChange(view);
+ }
+
+ if (!view->wasScrolledByUser() || restorePolicy == ForcedRestoreForSameDocumentHistoryNavigation) {
+ if (m_frame->isMainFrame() && m_currentItem->pageScaleFactor())
+ m_frame->page()->setPageScaleFactor(m_currentItem->pageScaleFactor(), m_currentItem->scrollPoint());
+ else
+ view->setScrollPositionNonProgrammatically(m_currentItem->scrollPoint());
+ }
+ }
}
void FrameLoader::didFirstLayout()
{
- if (m_frame->page() && isBackForwardLoadType(m_loadType))
- history()->restoreScrollPositionAndViewState();
+ restoreScrollPositionAndViewState();
}
void FrameLoader::detachChildren()
{
typedef Vector<RefPtr<Frame> > FrameVector;
FrameVector childrenToDetach;
- childrenToDetach.reserveCapacity(m_frame->tree()->childCount());
- for (Frame* child = m_frame->tree()->lastChild(); child; child = child->tree()->previousSibling())
+ childrenToDetach.reserveCapacity(m_frame->tree().childCount());
+ for (Frame* child = m_frame->tree().lastChild(); child; child = child->tree().previousSibling())
childrenToDetach.append(child);
FrameVector::iterator end = childrenToDetach.end();
for (FrameVector::iterator it = childrenToDetach.begin(); it != end; it++)
- (*it)->loader()->detachFromParent();
+ (*it)->loader().detachFromParent();
}
void FrameLoader::closeAndRemoveChild(Frame* child)
{
- child->tree()->detachFromParent();
+ child->tree().detachFromParent();
child->setView(0);
if (child->ownerElement() && child->page())
@@ -1080,7 +1042,7 @@ void FrameLoader::closeAndRemoveChild(Frame* child)
child->willDetachPage();
child->detachFromPage();
- m_frame->tree()->removeChild(child);
+ m_frame->tree().removeChild(child);
}
// Called every time a resource is completely loaded or an error is received.
@@ -1092,11 +1054,11 @@ void FrameLoader::checkLoadComplete()
// is currently needed in order to null out the previous history item for all frames.
if (Page* page = m_frame->page()) {
Vector<RefPtr<Frame>, 10> frames;
- for (RefPtr<Frame> frame = page->mainFrame(); frame; frame = frame->tree()->traverseNext())
+ for (RefPtr<Frame> frame = page->mainFrame(); frame; frame = frame->tree().traverseNext())
frames.append(frame);
// To process children before their parents, iterate the vector backwards.
for (size_t i = frames.size(); i; --i)
- frames[i - 1]->loader()->checkLoadCompleteForThisFrame();
+ frames[i - 1]->loader().checkLoadCompleteForThisFrame();
}
}
@@ -1113,7 +1075,7 @@ int FrameLoader::numPendingOrLoadingRequests(bool recurse) const
return m_frame->document()->fetcher()->requestCount();
int count = 0;
- for (Frame* frame = m_frame; frame; frame = frame->tree()->traverseNext(m_frame))
+ for (Frame* frame = m_frame; frame; frame = frame->tree().traverseNext(m_frame))
count += frame->document()->fetcher()->requestCount();
return count;
}
@@ -1130,7 +1092,6 @@ void FrameLoader::frameDetached()
// stopAllLoaders can detach the Frame, so protect it.
RefPtr<Frame> protect(m_frame);
stopAllLoaders();
- m_frame->document()->stopActiveDOMObjects();
detachFromParent();
}
@@ -1140,7 +1101,6 @@ void FrameLoader::detachFromParent()
RefPtr<Frame> protect(m_frame);
closeURL();
- history()->saveScrollPositionAndViewStateToItem(history()->currentItem());
detachChildren();
// stopAllLoaders() needs to be called after detachChildren(), because detachedChildren()
// will trigger the unload event handlers of any child frames, and those event
@@ -1156,9 +1116,9 @@ void FrameLoader::detachFromParent()
m_progressTracker.clear();
- if (Frame* parent = m_frame->tree()->parent()) {
- parent->loader()->closeAndRemoveChild(m_frame);
- parent->loader()->scheduleCheckCompleted();
+ if (Frame* parent = m_frame->tree().parent()) {
+ parent->loader().closeAndRemoveChild(m_frame);
+ parent->loader().scheduleCheckCompleted();
} else {
m_frame->setView(0);
m_frame->willDetachPage();
@@ -1194,10 +1154,10 @@ void FrameLoader::addExtraFieldsToRequest(ResourceRequest& request)
request.setHTTPAccept(defaultAcceptHeader);
// Make sure we send the Origin header.
- addHTTPOriginIfNeeded(request, String());
+ addHTTPOriginIfNeeded(request, nullAtom);
}
-void FrameLoader::addHTTPOriginIfNeeded(ResourceRequest& request, const String& origin)
+void FrameLoader::addHTTPOriginIfNeeded(ResourceRequest& request, const AtomicString& origin)
{
if (!request.httpOrigin().isEmpty())
return; // Request already has an Origin header.
@@ -1249,7 +1209,7 @@ void FrameLoader::receivedMainResourceError(const ResourceError& error)
checkLoadComplete();
}
-void FrameLoader::checkNavigationPolicyAndContinueFragmentScroll(const NavigationAction& action, bool isNewNavigation)
+void FrameLoader::checkNavigationPolicyAndContinueFragmentScroll(const NavigationAction& action, bool isNewNavigation, ClientRedirectPolicy clientRedirect)
{
m_documentLoader->setTriggeringAction(action);
@@ -1264,7 +1224,8 @@ void FrameLoader::checkNavigationPolicyAndContinueFragmentScroll(const Navigatio
m_provisionalDocumentLoader->detachFromFrame();
m_provisionalDocumentLoader = 0;
}
- loadInSameDocument(request.url(), 0, isNewNavigation);
+ saveDocumentAndScrollState();
+ loadInSameDocument(request.url(), 0, isNewNavigation, clientRedirect);
}
bool FrameLoader::shouldPerformFragmentNavigation(bool isFormSubmission, const String& httpMethod, FrameLoadType loadType, const KURL& url)
@@ -1310,7 +1271,7 @@ bool FrameLoader::shouldClose()
// Store all references to each subframe in advance since beforeunload's event handler may modify frame
Vector<RefPtr<Frame> > targetFrames;
targetFrames.append(m_frame);
- for (Frame* child = m_frame->tree()->firstChild(); child; child = child->tree()->traverseNext(m_frame))
+ for (Frame* child = m_frame->tree().firstChild(); child; child = child->tree().traverseNext(m_frame))
targetFrames.append(child);
bool shouldClose = false;
@@ -1320,7 +1281,7 @@ bool FrameLoader::shouldClose()
bool didAllowNavigation = false;
for (i = 0; i < targetFrames.size(); i++) {
- if (!targetFrames[i]->tree()->isDescendantOf(m_frame))
+ if (!targetFrames[i]->tree().isDescendantOf(m_frame))
continue;
if (!targetFrames[i]->document()->dispatchBeforeUnloadEvent(page->chrome(), didAllowNavigation))
break;
@@ -1332,7 +1293,7 @@ bool FrameLoader::shouldClose()
return shouldClose;
}
-void FrameLoader::loadWithNavigationAction(const ResourceRequest& request, const NavigationAction& action, FrameLoadType type, PassRefPtr<FormState> formState, const SubstituteData& substituteData, const String& overrideEncoding)
+void FrameLoader::loadWithNavigationAction(const NavigationAction& action, FrameLoadType type, PassRefPtr<FormState> formState, const SubstituteData& substituteData, ClientRedirectPolicy clientRedirect, const AtomicString& overrideEncoding)
{
ASSERT(m_client->hasWebView());
if (m_frame->document()->pageDismissalEventBeingDispatched() != Document::NoDismissal)
@@ -1342,20 +1303,29 @@ void FrameLoader::loadWithNavigationAction(const ResourceRequest& request, const
// document load because the event would leak subsequent activity by the frame which the parent
// frame isn't supposed to learn. For example, if the child frame navigated to a new URL, the
// parent frame shouldn't learn the URL.
+ const ResourceRequest& request = action.resourceRequest();
if (!m_stateMachine.committedFirstRealDocumentLoad() && m_frame->ownerElement() && !m_frame->ownerElement()->dispatchBeforeLoadEvent(request.url().string()))
return;
if (!m_stateMachine.startedFirstRealLoad())
m_stateMachine.advanceTo(FrameLoaderStateMachine::StartedFirstRealLoad);
+ // The current load should replace the history item if it is the first real
+ // load of the frame.
+ bool replacesCurrentHistoryItem = false;
+ if (type == FrameLoadTypeRedirectWithLockedBackForwardList
+ || !m_stateMachine.committedFirstRealDocumentLoad()) {
+ replacesCurrentHistoryItem = true;
+ }
+
m_policyDocumentLoader = m_client->createDocumentLoader(request, substituteData.isValid() ? substituteData : defaultSubstituteDataForURL(request.url()));
m_policyDocumentLoader->setFrame(m_frame);
m_policyDocumentLoader->setTriggeringAction(action);
- m_policyDocumentLoader->setReplacesCurrentHistoryItem(type == FrameLoadTypeRedirectWithLockedBackForwardList);
- m_policyDocumentLoader->setIsClientRedirect(m_startingClientRedirect);
+ m_policyDocumentLoader->setReplacesCurrentHistoryItem(replacesCurrentHistoryItem);
+ m_policyDocumentLoader->setIsClientRedirect(clientRedirect == ClientRedirect);
- if (Frame* parent = m_frame->tree()->parent())
- m_policyDocumentLoader->setOverrideEncoding(parent->loader()->documentLoader()->overrideEncoding());
+ if (Frame* parent = m_frame->tree().parent())
+ m_policyDocumentLoader->setOverrideEncoding(parent->loader().documentLoader()->overrideEncoding());
else if (!overrideEncoding.isEmpty())
m_policyDocumentLoader->setOverrideEncoding(overrideEncoding);
else if (m_documentLoader)
@@ -1370,7 +1340,7 @@ void FrameLoader::loadWithNavigationAction(const ResourceRequest& request, const
}
// A new navigation is in progress, so don't clear the history's provisional item.
- stopAllLoaders(ShouldNotClearProvisionalItem);
+ stopAllLoaders();
// <rdar://problem/6250856> - In certain circumstances on pages with multiple frames, stopAllLoaders()
// might detach the current FrameLoader, in which case we should bail on this newly defunct load.
@@ -1379,7 +1349,7 @@ void FrameLoader::loadWithNavigationAction(const ResourceRequest& request, const
if (isLoadingMainFrame())
m_frame->page()->inspectorController().resume();
- m_frame->navigationScheduler()->cancel();
+ m_frame->navigationScheduler().cancel();
m_provisionalDocumentLoader = m_policyDocumentLoader.release();
m_loadType = type;
@@ -1397,54 +1367,6 @@ void FrameLoader::loadWithNavigationAction(const ResourceRequest& request, const
m_provisionalDocumentLoader->startLoadingMainResource();
}
-void FrameLoader::checkNewWindowPolicyAndContinue(PassRefPtr<FormState> formState, const String& frameName, const NavigationAction& action)
-{
- if (m_frame->document()->pageDismissalEventBeingDispatched() != Document::NoDismissal)
- return;
-
- if (m_frame->document() && m_frame->document()->isSandboxed(SandboxPopups))
- return;
-
- if (!DOMWindow::allowPopUp(m_frame))
- return;
-
- NavigationPolicy navigationPolicy = NavigationPolicyNewForegroundTab;
- action.specifiesNavigationPolicy(&navigationPolicy);
-
- if (navigationPolicy == NavigationPolicyDownload) {
- m_client->loadURLExternally(action.resourceRequest(), navigationPolicy);
- return;
- }
-
- RefPtr<Frame> frame = m_frame;
- RefPtr<Frame> mainFrame = m_frame;
-
- if (!m_frame->settings() || m_frame->settings()->supportsMultipleWindows()) {
- struct WindowFeatures features;
- Page* newPage = m_frame->page()->chrome().client().createWindow(m_frame, FrameLoadRequest(m_frame->document()->securityOrigin(), action.resourceRequest()),
- features, navigationPolicy);
-
- // createWindow can return null (e.g., popup blocker denies the window).
- if (!newPage)
- return;
- mainFrame = newPage->mainFrame();
- }
-
- if (frameName != "_blank")
- mainFrame->tree()->setName(frameName);
-
- mainFrame->page()->setOpenedByDOM();
- mainFrame->page()->chrome().show(navigationPolicy);
- if (!m_suppressOpenerInNewFrame) {
- mainFrame->loader()->setOpener(frame.get());
- mainFrame->document()->setReferrerPolicy(frame->document()->referrerPolicy());
- }
-
- // FIXME: We can't just send our NavigationAction to the new FrameLoader's loadWithNavigationAction(), we need to
- // create a new one with a default NavigationType and no triggering event. We should figure out why.
- mainFrame->loader()->loadWithNavigationAction(action.resourceRequest(), NavigationAction(action.resourceRequest()), FrameLoadTypeStandard, formState, SubstituteData());
-}
-
void FrameLoader::applyUserAgent(ResourceRequest& request)
{
String userAgent = this->userAgent(request.url());
@@ -1454,9 +1376,9 @@ void FrameLoader::applyUserAgent(ResourceRequest& request)
bool FrameLoader::shouldInterruptLoadForXFrameOptions(const String& content, const KURL& url, unsigned long requestIdentifier)
{
- UseCounter::count(m_frame->document(), UseCounter::XFrameOptions);
+ UseCounter::count(m_frame->domWindow(), UseCounter::XFrameOptions);
- Frame* topFrame = m_frame->tree()->top();
+ Frame* topFrame = m_frame->tree().top();
if (m_frame == topFrame)
return false;
@@ -1464,13 +1386,13 @@ bool FrameLoader::shouldInterruptLoadForXFrameOptions(const String& content, con
switch (disposition) {
case XFrameOptionsSameOrigin: {
- UseCounter::count(m_frame->document(), UseCounter::XFrameOptionsSameOrigin);
+ UseCounter::count(m_frame->domWindow(), UseCounter::XFrameOptionsSameOrigin);
RefPtr<SecurityOrigin> origin = SecurityOrigin::create(url);
if (!origin->isSameSchemeHostPort(topFrame->document()->securityOrigin()))
return true;
- for (Frame* frame = m_frame->tree()->parent(); frame; frame = frame->tree()->parent()) {
+ for (Frame* frame = m_frame->tree().parent(); frame; frame = frame->tree().parent()) {
if (!origin->isSameSchemeHostPort(frame->document()->securityOrigin())) {
- UseCounter::count(m_frame->document(), UseCounter::XFrameOptionsSameOriginWithBadAncestorChain);
+ UseCounter::count(m_frame->domWindow(), UseCounter::XFrameOptionsSameOriginWithBadAncestorChain);
break;
}
}
@@ -1494,9 +1416,9 @@ bool FrameLoader::shouldInterruptLoadForXFrameOptions(const String& content, con
bool FrameLoader::shouldTreatURLAsSameAsCurrent(const KURL& url) const
{
- if (!history()->currentItem())
+ if (!m_currentItem)
return false;
- return url == history()->currentItem()->url() || url == history()->currentItem()->originalURL();
+ return url == m_currentItem->url() || url == m_currentItem->originalURL();
}
bool FrameLoader::shouldTreatURLAsSrcdocDocument(const KURL& url) const
@@ -1514,7 +1436,7 @@ bool FrameLoader::shouldTreatURLAsSrcdocDocument(const KURL& url) const
Frame* FrameLoader::findFrameForNavigation(const AtomicString& name, Document* activeDocument)
{
ASSERT(activeDocument);
- Frame* frame = m_frame->tree()->find(name);
+ Frame* frame = m_frame->tree().find(name);
// From http://www.whatwg.org/specs/web-apps/current-work/#seamlessLinks:
//
@@ -1526,7 +1448,7 @@ Frame* FrameLoader::findFrameForNavigation(const AtomicString& name, Document* a
// browsing context flag set, and continue these steps as if that
// browsing context was the one that was going to be navigated instead.
if (frame == m_frame && name != "_self" && m_frame->document()->shouldDisplaySeamlesslyWithParent()) {
- for (Frame* ancestor = m_frame; ancestor; ancestor = ancestor->tree()->parent()) {
+ for (Frame* ancestor = m_frame; ancestor; ancestor = ancestor->tree().parent()) {
if (!ancestor->document()->shouldDisplaySeamlesslyWithParent()) {
frame = ancestor;
break;
@@ -1540,20 +1462,16 @@ Frame* FrameLoader::findFrameForNavigation(const AtomicString& name, Document* a
return frame;
}
-void FrameLoader::loadHistoryItem(HistoryItem* item)
+void FrameLoader::loadHistoryItem(HistoryItem* item, HistoryLoadType historyLoadType)
{
- m_requestedHistoryItem = item;
- HistoryItem* currentItem = history()->currentItem();
-
- if (currentItem && item->shouldDoSameDocumentNavigationTo(currentItem)) {
- history()->setCurrentItem(item);
- loadInSameDocument(item->url(), item->stateObject(), false);
+ saveDocumentAndScrollState();
+ m_currentItem = item;
+ if (historyLoadType == HistorySameDocumentLoad) {
+ loadInSameDocument(item->url(), item->stateObject(), false, NotClientRedirect);
+ restoreScrollPositionAndViewState(ForcedRestoreForSameDocumentHistoryNavigation);
return;
}
- // Remember this item so we can traverse any child items as child frames load
- history()->setProvisionalItem(item);
-
RefPtr<FormData> formData = item->formData();
ResourceRequest request(item->url());
request.setHTTPReferrer(item->referrer());
@@ -1565,14 +1483,7 @@ void FrameLoader::loadHistoryItem(HistoryItem* item)
addHTTPOriginIfNeeded(request, securityOrigin->toString());
}
- loadWithNavigationAction(request, NavigationAction(request, FrameLoadTypeBackForward, formData), FrameLoadTypeBackForward, 0, SubstituteData());
-}
-
-void FrameLoader::insertDummyHistoryItem()
-{
- RefPtr<HistoryItem> currentItem = HistoryItem::create();
- history()->setCurrentItem(currentItem.get());
- frame()->page()->backForward().setCurrentItem(currentItem.get());
+ loadWithNavigationAction(NavigationAction(request, FrameLoadTypeBackForward, formData), FrameLoadTypeBackForward, 0, SubstituteData());
}
void FrameLoader::dispatchDocumentElementAvailable()
@@ -1582,7 +1493,7 @@ void FrameLoader::dispatchDocumentElementAvailable()
void FrameLoader::dispatchDidClearWindowObjectsInAllWorlds()
{
- if (!m_frame->script()->canExecuteScripts(NotAboutToExecuteScript))
+ if (!m_frame->script().canExecuteScripts(NotAboutToExecuteScript))
return;
Vector<RefPtr<DOMWrapperWorld> > worlds;
@@ -1593,7 +1504,7 @@ void FrameLoader::dispatchDidClearWindowObjectsInAllWorlds()
void FrameLoader::dispatchDidClearWindowObjectInWorld(DOMWrapperWorld* world)
{
- if (!m_frame->script()->canExecuteScripts(NotAboutToExecuteScript) || !m_frame->script()->existingWindowShell(world))
+ if (!m_frame->script().canExecuteScripts(NotAboutToExecuteScript) || !m_frame->script().existingWindowShell(world))
return;
m_client->dispatchDidClearWindowObjectInWorld(world);
@@ -1607,7 +1518,7 @@ void FrameLoader::dispatchDidClearWindowObjectInWorld(DOMWrapperWorld* world)
SandboxFlags FrameLoader::effectiveSandboxFlags() const
{
SandboxFlags flags = m_forcedSandboxFlags;
- if (Frame* parentFrame = m_frame->tree()->parent())
+ if (Frame* parentFrame = m_frame->tree().parent())
flags |= parentFrame->document()->sandboxFlags();
if (HTMLFrameOwnerElement* ownerElement = m_frame->ownerElement())
flags |= ownerElement->sandboxFlags();
diff --git a/chromium/third_party/WebKit/Source/core/loader/FrameLoader.h b/chromium/third_party/WebKit/Source/core/loader/FrameLoader.h
index 98879429e78..7bdedd6c85e 100644
--- a/chromium/third_party/WebKit/Source/core/loader/FrameLoader.h
+++ b/chromium/third_party/WebKit/Source/core/loader/FrameLoader.h
@@ -33,15 +33,14 @@
#define FrameLoader_h
#include "core/dom/IconURL.h"
+#include "core/dom/SandboxFlags.h"
#include "core/dom/SecurityContext.h"
-#include "core/fetch/CachePolicy.h"
#include "core/fetch/ResourceLoaderOptions.h"
+#include "core/history/HistoryItem.h"
#include "core/loader/FrameLoaderStateMachine.h"
#include "core/loader/FrameLoaderTypes.h"
-#include "core/loader/HistoryController.h"
#include "core/loader/MixedContentChecker.h"
-#include "core/page/LayoutMilestones.h"
-#include "core/platform/Timer.h"
+#include "platform/Timer.h"
#include "wtf/Forward.h"
#include "wtf/HashSet.h"
#include "wtf/OwnPtr.h"
@@ -82,26 +81,19 @@ public:
Frame* frame() const { return m_frame; }
- HistoryController* history() const { return &m_history; }
-
- IconController* icon() const { return m_icon.get(); }
MixedContentChecker* mixedContentChecker() const { return &m_mixedContentChecker; }
- void prepareForHistoryNavigation();
-
// These functions start a load. All eventually call into loadWithNavigationAction() or loadInSameDocument().
void load(const FrameLoadRequest&); // The entry point for non-reload, non-history loads.
- void reload(ReloadPolicy = NormalReload, const KURL& overrideURL = KURL(), const String& overrideEncoding = String());
- void loadHistoryItem(HistoryItem*); // The entry point for all back/forward loads
-
- HistoryItem* requestedHistoryItem() const { return m_requestedHistoryItem.get(); }
+ void reload(ReloadPolicy = NormalReload, const KURL& overrideURL = KURL(), const AtomicString& overrideEncoding = nullAtom);
+ void loadHistoryItem(HistoryItem*, HistoryLoadType = HistoryDifferentDocumentLoad); // The entry point for all back/forward loads
static void reportLocalLoadFailed(Frame*, const String& url);
// FIXME: These are all functions which stop loads. We have too many.
// Warning: stopAllLoaders can and will detach the Frame out from under you. All callers need to either protect the Frame
// or guarantee they won't in any way access the Frame after stopAllLoaders returns.
- void stopAllLoaders(ClearProvisionalItemPolicy = ShouldClearProvisionalItem);
+ void stopAllLoaders();
void stopLoading();
bool closeURL();
// FIXME: clear() is trying to do too many things. We should break it down into smaller functions.
@@ -120,8 +112,6 @@ public:
bool isLoading() const;
int numPendingOrLoadingRequests(bool recurse) const;
- String outgoingReferrer() const;
- String outgoingOrigin() const;
DocumentLoader* activeDocumentLoader() const;
DocumentLoader* documentLoader() const { return m_documentLoader.get(); }
@@ -137,14 +127,12 @@ public:
bool subframeIsLoading() const;
+ bool shouldTreatURLAsSameAsCurrent(const KURL&) const;
bool shouldTreatURLAsSrcdocDocument(const KURL&) const;
FrameLoadType loadType() const;
void setLoadType(FrameLoadType loadType) { m_loadType = loadType; }
- CachePolicy subresourceCachePolicy() const;
-
- void didLayout(LayoutMilestones);
void didFirstLayout();
void checkLoadComplete(DocumentLoader*);
@@ -153,7 +141,7 @@ public:
void addExtraFieldsToRequest(ResourceRequest&);
- static void addHTTPOriginIfNeeded(ResourceRequest&, const String& origin);
+ static void addHTTPOriginIfNeeded(ResourceRequest&, const AtomicString& origin);
FrameLoaderClient* client() const { return m_client; }
@@ -182,8 +170,6 @@ public:
void frameDetached();
- void setOutgoingReferrer(const KURL&);
-
void loadDone();
void finishedParsing();
void checkCompleted();
@@ -200,21 +186,27 @@ public:
bool allAncestorsAreComplete() const; // including this
- bool suppressOpenerInNewFrame() const { return m_suppressOpenerInNewFrame; }
-
bool shouldClose();
void started();
- void setContainsPlugins() { m_containsPlugins = true; }
- bool containsPlugins() const { return m_containsPlugins; }
bool allowPlugins(ReasonForCallingAllowPlugins);
enum UpdateBackForwardListPolicy {
UpdateBackForwardList,
DoNotUpdateBackForwardList
};
- void updateForSameDocumentNavigation(const KURL&, SameDocumentNavigationSource, PassRefPtr<SerializedScriptValue>, const String& title, UpdateBackForwardListPolicy);
+ void updateForSameDocumentNavigation(const KURL&, SameDocumentNavigationSource, PassRefPtr<SerializedScriptValue>, UpdateBackForwardListPolicy);
+
+ HistoryItem* currentItem() const { return m_currentItem.get(); }
+ void saveDocumentAndScrollState();
+ void clearScrollPositionAndViewState();
+
+ enum RestorePolicy {
+ StandardRestore,
+ ForcedRestoreForSameDocumentHistoryNavigation
+ };
+ void restoreScrollPositionAndViewState(RestorePolicy = StandardRestore);
private:
bool allChildrenAreComplete() const; // immediate children, not all descendants
@@ -224,17 +216,14 @@ private:
void checkTimerFired(Timer<FrameLoader>*);
void didAccessInitialDocumentTimerFired(Timer<FrameLoader>*);
- void insertDummyHistoryItem();
-
bool prepareRequestForThisFrame(FrameLoadRequest&);
- void setReferrerForFrameRequest(ResourceRequest&, ShouldSendReferrer);
+ void setReferrerForFrameRequest(ResourceRequest&, ShouldSendReferrer, Document*);
FrameLoadType determineFrameLoadType(const FrameLoadRequest&);
bool isScriptTriggeredFormSubmissionInChildFrame(const FrameLoadRequest&) const;
SubstituteData defaultSubstituteDataForURL(const KURL&);
- void checkNavigationPolicyAndContinueFragmentScroll(const NavigationAction&, bool isNewNavigation);
- void checkNewWindowPolicyAndContinue(PassRefPtr<FormState>, const String& frameName, const NavigationAction&);
+ void checkNavigationPolicyAndContinueFragmentScroll(const NavigationAction&, bool isNewNavigation, ClientRedirectPolicy);
bool shouldPerformFragmentNavigation(bool isFormSubmission, const String& httpMethod, FrameLoadType, const KURL&);
void scrollToFragmentWithParentBoundary(const KURL&);
@@ -244,28 +233,30 @@ private:
void closeOldDataSources();
// Calls continueLoadAfterNavigationPolicy
- void loadWithNavigationAction(const ResourceRequest&, const NavigationAction&,
- FrameLoadType, PassRefPtr<FormState>, const SubstituteData&, const String& overrideEncoding = String());
+ void loadWithNavigationAction(const NavigationAction&, FrameLoadType, PassRefPtr<FormState>,
+ const SubstituteData&, ClientRedirectPolicy = NotClientRedirect, const AtomicString& overrideEncoding = nullAtom);
void detachChildren();
void closeAndRemoveChild(Frame*);
- void loadInSameDocument(const KURL&, PassRefPtr<SerializedScriptValue> stateObject, bool isNewNavigation);
+ enum HistoryItemPolicy {
+ CreateNewHistoryItem,
+ DoNotCreateNewHistoryItem
+ };
+ void setHistoryItemStateForCommit(HistoryItemPolicy);
+
+ void loadInSameDocument(const KURL&, PassRefPtr<SerializedScriptValue> stateObject, bool isNewNavigation, ClientRedirectPolicy);
void scheduleCheckCompleted();
void startCheckCompleteTimer();
- bool shouldTreatURLAsSameAsCurrent(const KURL&) const;
-
Frame* m_frame;
FrameLoaderClient* m_client;
// FIXME: These should be OwnPtr<T> to reduce build times and simplify
// header dependencies unless performance testing proves otherwise.
// Some of these could be lazily created for memory savings on devices.
- mutable HistoryController m_history;
mutable FrameLoaderStateMachine m_stateMachine;
- OwnPtr<IconController> m_icon;
mutable MixedContentChecker m_mixedContentChecker;
class FrameProgressTracker;
@@ -283,15 +274,13 @@ private:
RefPtr<DocumentLoader> m_policyDocumentLoader;
OwnPtr<FetchContext> m_fetchContext;
- bool m_inStopAllLoaders;
+ RefPtr<HistoryItem> m_currentItem;
- String m_outgoingReferrer;
+ bool m_inStopAllLoaders;
// FIXME: This is only used in checkCompleted(). Figure out a way to disentangle it.
bool m_isComplete;
- bool m_containsPlugins;
-
Timer<FrameLoader> m_checkTimer;
bool m_shouldCallCheckCompleted;
@@ -300,12 +289,8 @@ private:
bool m_didAccessInitialDocument;
Timer<FrameLoader> m_didAccessInitialDocumentTimer;
- bool m_suppressOpenerInNewFrame;
- bool m_startingClientRedirect;
SandboxFlags m_forcedSandboxFlags;
-
- RefPtr<HistoryItem> m_requestedHistoryItem;
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/loader/FrameLoaderClient.h b/chromium/third_party/WebKit/Source/core/loader/FrameLoaderClient.h
index bb75b830aa1..ec3ca3ccfc5 100644
--- a/chromium/third_party/WebKit/Source/core/loader/FrameLoaderClient.h
+++ b/chromium/third_party/WebKit/Source/core/loader/FrameLoaderClient.h
@@ -33,8 +33,7 @@
#include "core/dom/IconURL.h"
#include "core/loader/FrameLoaderTypes.h"
#include "core/loader/NavigationPolicy.h"
-#include "core/page/LayoutMilestones.h"
-#include "core/platform/network/ResourceLoadPriority.h"
+#include "platform/network/ResourceLoadPriority.h"
#include "wtf/Forward.h"
#include "wtf/Vector.h"
@@ -45,9 +44,10 @@ class Context;
template<class T> class Handle;
}
-namespace WebKit {
+namespace blink {
class WebCookieJar;
-class WebServiceWorkerRegistry;
+class WebServiceWorkerProvider;
+class WebServiceWorkerProviderClient;
}
namespace WebCore {
@@ -83,6 +83,11 @@ class FetchRequest;
class SubstituteData;
class Widget;
+ enum NavigationHistoryPolicy {
+ NavigationCreatedHistoryEntry,
+ NavigationReusedHistoryEntry
+ };
+
class FrameLoaderClient {
public:
virtual ~FrameLoaderClient() { }
@@ -101,18 +106,17 @@ class FetchRequest;
virtual void dispatchDidHandleOnloadEvents() = 0;
virtual void dispatchDidReceiveServerRedirectForProvisionalLoad() = 0;
- virtual void dispatchDidNavigateWithinPage() { }
+ virtual void dispatchDidNavigateWithinPage(NavigationHistoryPolicy, HistoryItem*) { }
virtual void dispatchWillClose() = 0;
virtual void dispatchDidStartProvisionalLoad() = 0;
virtual void dispatchDidReceiveTitle(const String&) = 0;
virtual void dispatchDidChangeIcons(IconType) = 0;
- virtual void dispatchDidCommitLoad() = 0;
+ virtual void dispatchDidCommitLoad(Frame*, HistoryItem*, NavigationHistoryPolicy) = 0;
virtual void dispatchDidFailProvisionalLoad(const ResourceError&) = 0;
virtual void dispatchDidFailLoad(const ResourceError&) = 0;
virtual void dispatchDidFinishDocumentLoad() = 0;
virtual void dispatchDidFinishLoad() = 0;
-
- virtual void dispatchDidLayout(LayoutMilestones) { }
+ virtual void dispatchDidFirstVisuallyNonEmptyLayout() = 0;
virtual NavigationPolicy decidePolicyForNavigation(const ResourceRequest&, DocumentLoader*, NavigationPolicy) = 0;
@@ -128,7 +132,7 @@ class FetchRequest;
virtual void loadURLExternally(const ResourceRequest&, NavigationPolicy, const String& suggestedName = String()) = 0;
- virtual void navigateBackForward(int offset) const = 0;
+ virtual bool navigateBackForward(int offset) const = 0;
// Another page has accessed the initial empty document of this frame.
// It is no longer safe to display a provisional URL, since a URL spoof
@@ -151,6 +155,10 @@ class FetchRequest;
virtual void didDetectXSS(const KURL&, bool didBlockEntirePage) = 0;
virtual void didDispatchPingLoader(const KURL&) = 0;
+ // Transmits the change in the set of watched CSS selectors property
+ // that match any element on the frame.
+ virtual void selectorMatchChanged(const Vector<String>& addedSelectors, const Vector<String>& removedSelectors) = 0;
+
virtual PassRefPtr<DocumentLoader> createDocumentLoader(const ResourceRequest&, const SubstituteData&) = 0;
virtual String userAgent(const KURL&) = 0;
@@ -193,7 +201,7 @@ class FetchRequest;
// This callback is similar, but for plugins.
virtual void didNotAllowPlugins() { }
- virtual WebKit::WebCookieJar* cookieJar() const = 0;
+ virtual blink::WebCookieJar* cookieJar() const = 0;
// Returns true if the embedder intercepted the postMessage call
virtual bool willCheckAndDispatchMessageEvent(SecurityOrigin* /*target*/, MessageEvent*) const { return false; }
@@ -219,7 +227,11 @@ class FetchRequest;
virtual void dispatchDidChangeResourcePriority(unsigned long /*identifier*/, ResourceLoadPriority) { }
- virtual WebKit::WebServiceWorkerRegistry* serviceWorkerRegistry() = 0;
+ virtual PassOwnPtr<blink::WebServiceWorkerProvider> createServiceWorkerProvider(PassOwnPtr<blink::WebServiceWorkerProviderClient>) = 0;
+
+ virtual void didStopAllLoaders() { }
+
+ virtual bool isFrameLoaderClientImpl() const { return false; }
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/loader/FrameLoaderStateMachine.cpp b/chromium/third_party/WebKit/Source/core/loader/FrameLoaderStateMachine.cpp
index 2ad0e231cb7..61db0ef4cce 100644
--- a/chromium/third_party/WebKit/Source/core/loader/FrameLoaderStateMachine.cpp
+++ b/chromium/third_party/WebKit/Source/core/loader/FrameLoaderStateMachine.cpp
@@ -46,7 +46,7 @@ bool FrameLoaderStateMachine::startedFirstRealLoad() const
bool FrameLoaderStateMachine::committedFirstRealDocumentLoad() const
{
- return m_state == CommittedFirstRealLoad;
+ return m_state >= CommittedFirstRealLoad;
}
bool FrameLoaderStateMachine::creatingInitialEmptyDocument() const
@@ -54,6 +54,11 @@ bool FrameLoaderStateMachine::creatingInitialEmptyDocument() const
return m_state == CreatingInitialEmptyDocument;
}
+bool FrameLoaderStateMachine::committedMultipleRealLoads() const
+{
+ return m_state == CommittedMultipleRealLoads;
+}
+
bool FrameLoaderStateMachine::isDisplayingInitialEmptyDocument() const
{
return m_state >= DisplayingInitialEmptyDocument && m_state < CommittedFirstRealLoad;
diff --git a/chromium/third_party/WebKit/Source/core/loader/FrameLoaderStateMachine.h b/chromium/third_party/WebKit/Source/core/loader/FrameLoaderStateMachine.h
index e8d1a2aaddf..aa349a5d660 100644
--- a/chromium/third_party/WebKit/Source/core/loader/FrameLoaderStateMachine.h
+++ b/chromium/third_party/WebKit/Source/core/loader/FrameLoaderStateMachine.h
@@ -47,13 +47,15 @@ public:
CreatingInitialEmptyDocument,
DisplayingInitialEmptyDocument,
StartedFirstRealLoad,
- CommittedFirstRealLoad
+ CommittedFirstRealLoad,
+ CommittedMultipleRealLoads
};
bool startedFirstRealLoad() const;
bool committedFirstRealDocumentLoad() const;
bool creatingInitialEmptyDocument() const;
bool isDisplayingInitialEmptyDocument() const;
+ bool committedMultipleRealLoads() const;
void advanceTo(State);
private:
diff --git a/chromium/third_party/WebKit/Source/core/loader/FrameLoaderTypes.h b/chromium/third_party/WebKit/Source/core/loader/FrameLoaderTypes.h
index 53c6f0d8a2d..5fe5d36da4f 100644
--- a/chromium/third_party/WebKit/Source/core/loader/FrameLoaderTypes.h
+++ b/chromium/third_party/WebKit/Source/core/loader/FrameLoaderTypes.h
@@ -31,73 +31,79 @@
namespace WebCore {
- enum FrameState {
- FrameStateProvisional,
- // This state indicates we are ready to commit to a page,
- // which means the view will transition to use the new data source.
- FrameStateCommittedPage,
- FrameStateComplete
- };
+enum FrameState {
+ FrameStateProvisional,
+ // This state indicates we are ready to commit to a page,
+ // which means the view will transition to use the new data source.
+ FrameStateCommittedPage,
+ FrameStateComplete
+};
- enum FrameLoadType {
- FrameLoadTypeStandard,
- FrameLoadTypeBackForward,
- FrameLoadTypeReload,
- FrameLoadTypeSame, // user loads same URL again (but not reload button)
- FrameLoadTypeRedirectWithLockedBackForwardList,
- FrameLoadTypeInitialInChildFrame,
- FrameLoadTypeReloadFromOrigin,
- };
+enum FrameLoadType {
+ FrameLoadTypeStandard,
+ FrameLoadTypeBackForward,
+ FrameLoadTypeReload,
+ FrameLoadTypeSame, // user loads same URL again (but not reload button)
+ FrameLoadTypeRedirectWithLockedBackForwardList,
+ FrameLoadTypeInitialInChildFrame,
+ FrameLoadTypeReloadFromOrigin,
+};
- enum NavigationType {
- NavigationTypeLinkClicked,
- NavigationTypeFormSubmitted,
- NavigationTypeBackForward,
- NavigationTypeReload,
- NavigationTypeFormResubmitted,
- NavigationTypeOther
- };
+enum NavigationType {
+ NavigationTypeLinkClicked,
+ NavigationTypeFormSubmitted,
+ NavigationTypeBackForward,
+ NavigationTypeReload,
+ NavigationTypeFormResubmitted,
+ NavigationTypeOther
+};
- enum ClearProvisionalItemPolicy {
- ShouldClearProvisionalItem,
- ShouldNotClearProvisionalItem
- };
+enum ObjectContentType {
+ ObjectContentNone,
+ ObjectContentImage,
+ ObjectContentFrame,
+ ObjectContentNetscapePlugin,
+ ObjectContentOtherPlugin
+};
- enum ObjectContentType {
- ObjectContentNone,
- ObjectContentImage,
- ObjectContentFrame,
- ObjectContentNetscapePlugin,
- ObjectContentOtherPlugin
- };
+enum ClearOption {
+ ClearWindowProperties = 1 << 0,
+ ClearScriptObjects = 1 << 1,
+ ClearWindowObject = 1 << 2,
+};
+typedef int ClearOptions;
- enum ClearOption {
- ClearWindowProperties = 1 << 0,
- ClearScriptObjects = 1 << 1,
- ClearWindowObject = 1 << 2,
- };
- typedef int ClearOptions;
+enum ShouldSendReferrer {
+ MaybeSendReferrer,
+ NeverSendReferrer
+};
- enum ShouldSendReferrer {
- MaybeSendReferrer,
- NeverSendReferrer
- };
+enum ReasonForCallingAllowPlugins {
+ AboutToInstantiatePlugin,
+ NotAboutToInstantiatePlugin
+};
- enum ReasonForCallingAllowPlugins {
- AboutToInstantiatePlugin,
- NotAboutToInstantiatePlugin
- };
+enum ReloadPolicy {
+ NormalReload,
+ EndToEndReload
+};
- enum ReloadPolicy {
- NormalReload,
- EndToEndReload
- };
+enum SameDocumentNavigationSource {
+ SameDocumentNavigationDefault,
+ SameDocumentNavigationPushState,
+ SameDocumentNavigationReplaceState
+};
+
+enum ClientRedirectPolicy {
+ NotClientRedirect,
+ ClientRedirect
+};
+
+enum HistoryLoadType {
+ HistorySameDocumentLoad,
+ HistoryDifferentDocumentLoad
+};
- enum SameDocumentNavigationSource {
- SameDocumentNavigationDefault,
- SameDocumentNavigationPushState,
- SameDocumentNavigationReplaceState
- };
}
#endif
diff --git a/chromium/third_party/WebKit/Source/core/loader/HistoryController.cpp b/chromium/third_party/WebKit/Source/core/loader/HistoryController.cpp
index be314f56128..033c7348ec0 100644
--- a/chromium/third_party/WebKit/Source/core/loader/HistoryController.cpp
+++ b/chromium/third_party/WebKit/Source/core/loader/HistoryController.cpp
@@ -31,686 +31,317 @@
#include "config.h"
#include "core/loader/HistoryController.h"
-#include "core/dom/Document.h"
-#include "core/history/BackForwardController.h"
-#include "core/history/HistoryItem.h"
-#include "core/html/HTMLFrameOwnerElement.h"
-#include "core/loader/DocumentLoader.h"
#include "core/loader/FrameLoader.h"
-#include "core/loader/FrameLoaderClient.h"
-#include "core/loader/FrameLoaderStateMachine.h"
-#include "core/page/Frame.h"
+#include "core/frame/Frame.h"
#include "core/page/FrameTree.h"
-#include "core/page/FrameView.h"
#include "core/page/Page.h"
-#include "core/page/scrolling/ScrollingCoordinator.h"
-#include "core/platform/Logging.h"
-#include "wtf/text/CString.h"
+#include "wtf/Deque.h"
+#include "wtf/text/StringHash.h"
namespace WebCore {
-HistoryController::HistoryController(Frame* frame)
- : m_frame(frame)
- , m_defersLoading(false)
+PassOwnPtr<HistoryNode> HistoryNode::create(HistoryEntry* entry, HistoryItem* value)
{
+ return adoptPtr(new HistoryNode(entry, value));
}
-HistoryController::~HistoryController()
+HistoryNode* HistoryNode::addChild(PassRefPtr<HistoryItem> item)
{
+ m_children.append(HistoryNode::create(m_entry, item.get()));
+ return m_children.last().get();
}
-void HistoryController::saveScrollPositionAndViewStateToItem(HistoryItem* item)
+PassOwnPtr<HistoryNode> HistoryNode::cloneAndReplace(HistoryEntry* newEntry, HistoryItem* newItem, bool clipAtTarget, Frame* targetFrame, Frame* currentFrame)
{
- if (!item || !m_frame->view())
- return;
+ bool isNodeBeingNavigated = targetFrame == currentFrame;
+ HistoryItem* itemForCreate = isNodeBeingNavigated ? newItem : m_value.get();
+ OwnPtr<HistoryNode> newHistoryNode = create(newEntry, itemForCreate);
- item->setScrollPoint(m_frame->view()->scrollPosition());
-
- Page* page = m_frame->page();
- if (page && page->mainFrame() == m_frame)
- item->setPageScaleFactor(page->pageScaleFactor());
+ if (!clipAtTarget || !isNodeBeingNavigated) {
+ for (Frame* child = currentFrame->tree().firstChild(); child; child = child->tree().nextSibling()) {
+ HistoryNode* childHistoryNode = m_entry->historyNodeForFrame(child);
+ if (!childHistoryNode)
+ continue;
+ newHistoryNode->m_children.append(childHistoryNode->cloneAndReplace(newEntry, newItem, clipAtTarget, targetFrame, child));
+ }
+ }
+ return newHistoryNode.release();
}
-void HistoryController::clearScrollPositionAndViewState()
+HistoryNode::HistoryNode(HistoryEntry* entry, HistoryItem* value)
+ : m_entry(entry)
+ , m_value(value)
{
- if (!m_currentItem)
- return;
-
- m_currentItem->clearScrollPoint();
- m_currentItem->setPageScaleFactor(0);
+ m_entry->m_framesToItems.add(value->targetFrameID(), this);
+ String target = value->target();
+ if (target.isNull())
+ target = emptyString();
+ m_entry->m_uniqueNamesToItems.add(target, this);
}
-/*
- There is a race condition between the layout and load completion that affects restoring the scroll position.
- We try to restore the scroll position at both the first layout and upon load completion.
-
- 1) If first layout happens before the load completes, we want to restore the scroll position then so that the
- first time we draw the page is already scrolled to the right place, instead of starting at the top and later
- jumping down. It is possible that the old scroll position is past the part of the doc laid out so far, in
- which case the restore silent fails and we will fix it in when we try to restore on doc completion.
- 2) If the layout happens after the load completes, the attempt to restore at load completion time silently
- fails. We then successfully restore it when the layout happens.
-*/
-void HistoryController::restoreScrollPositionAndViewState()
+void HistoryNode::removeChildren()
{
- if (!m_frame->loader()->stateMachine()->committedFirstRealDocumentLoad())
- return;
-
- ASSERT(m_currentItem);
+ // FIXME: This is inefficient. Figure out a cleaner way to ensure this HistoryNode isn't cached anywhere.
+ for (unsigned i = 0; i < m_children.size(); i++) {
+ m_children[i]->removeChildren();
- // FIXME: As the ASSERT attests, it seems we should always have a currentItem here.
- // One counterexample is <rdar://problem/4917290>
- // For now, to cover this issue in release builds, there is no technical harm to returning
- // early and from a user standpoint - as in the above radar - the previous page load failed
- // so there *is* no scroll or view state to restore!
- if (!m_currentItem)
- return;
-
- if (FrameView* view = m_frame->view()) {
- Page* page = m_frame->page();
- if (page && page->mainFrame() == m_frame) {
- if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
- scrollingCoordinator->frameViewRootLayerDidChange(view);
+ HashMap<uint64_t, HistoryNode*>::iterator framesEnd = m_entry->m_framesToItems.end();
+ HashMap<String, HistoryNode*>::iterator uniqueNamesEnd = m_entry->m_uniqueNamesToItems.end();
+ for (HashMap<uint64_t, HistoryNode*>::iterator it = m_entry->m_framesToItems.begin(); it != framesEnd; ++it) {
+ if (it->value == m_children[i])
+ m_entry->m_framesToItems.remove(it);
}
-
- if (!view->wasScrolledByUser()) {
- if (page && page->mainFrame() == m_frame && m_currentItem->pageScaleFactor())
- page->setPageScaleFactor(m_currentItem->pageScaleFactor(), m_currentItem->scrollPoint());
- else
- view->setScrollPositionNonProgrammatically(m_currentItem->scrollPoint());
+ for (HashMap<String, HistoryNode*>::iterator it = m_entry->m_uniqueNamesToItems.begin(); it != uniqueNamesEnd; ++it) {
+ if (it->value == m_children[i])
+ m_entry->m_uniqueNamesToItems.remove(it);
}
}
+ m_children.clear();
}
-void HistoryController::updateBackForwardListForFragmentScroll()
+HistoryEntry::HistoryEntry(HistoryItem* root)
{
- updateBackForwardListClippedAtTarget(false);
+ m_root = HistoryNode::create(this, root);
}
-void HistoryController::saveDocumentState()
+PassOwnPtr<HistoryEntry> HistoryEntry::create(HistoryItem* root)
{
- if (!m_currentItem)
- return;
-
- Document* document = m_frame->document();
- ASSERT(document);
-
- if (m_currentItem->isCurrentDocument(document) && document->attached()) {
- LOG(Loading, "WebCoreLoading %s: saving form state to %p", m_frame->tree()->uniqueName().string().utf8().data(), m_currentItem.get());
- m_currentItem->setDocumentState(document->formElementsState());
- }
+ return adoptPtr(new HistoryEntry(root));
}
-// Walk the frame tree, telling all frames to save their form state into their current
-// history item.
-void HistoryController::saveDocumentAndScrollState()
+PassOwnPtr<HistoryEntry> HistoryEntry::cloneAndReplace(HistoryItem* newItem, bool clipAtTarget, Frame* targetFrame, Page* page)
{
- for (Frame* frame = m_frame; frame; frame = frame->tree()->traverseNext(m_frame)) {
- frame->loader()->history()->saveDocumentState();
- frame->loader()->history()->saveScrollPositionAndViewStateToItem(frame->loader()->history()->currentItem());
- }
+ OwnPtr<HistoryEntry> newEntry = adoptPtr(new HistoryEntry());
+ newEntry->m_root = m_root->cloneAndReplace(newEntry.get(), newItem, clipAtTarget, targetFrame, page->mainFrame());
+ return newEntry.release();
}
-static inline bool isAssociatedToRequestedHistoryItem(const HistoryItem* current, Frame* frame, const HistoryItem* requested)
+HistoryNode* HistoryEntry::historyNodeForFrame(Frame* frame)
{
- if (requested == current)
- return true;
- if (requested)
- return false;
- while ((frame = frame->tree()->parent())) {
- requested = frame->loader()->requestedHistoryItem();
- if (!requested)
- continue;
- if (requested->isAncestorOf(current))
- return true;
- }
- return false;
+ if (HistoryNode* historyNode = m_framesToItems.get(frame->frameID()))
+ return historyNode;
+ String target = frame->tree().uniqueName();
+ if (target.isNull())
+ target = emptyString();
+ return m_uniqueNamesToItems.get(target);
}
-void HistoryController::restoreDocumentState()
+HistoryItem* HistoryEntry::itemForFrame(Frame* frame)
{
- Document* doc = m_frame->document();
-
- HistoryItem* itemToRestore = 0;
-
- switch (m_frame->loader()->loadType()) {
- case FrameLoadTypeReload:
- case FrameLoadTypeReloadFromOrigin:
- case FrameLoadTypeSame:
- break;
- case FrameLoadTypeBackForward:
- case FrameLoadTypeRedirectWithLockedBackForwardList:
- case FrameLoadTypeInitialInChildFrame:
- case FrameLoadTypeStandard:
- itemToRestore = m_currentItem.get();
- }
-
- if (!itemToRestore)
- return;
- if (isAssociatedToRequestedHistoryItem(itemToRestore, m_frame, m_frame->loader()->requestedHistoryItem()) && !m_frame->loader()->documentLoader()->isClientRedirect()) {
- LOG(Loading, "WebCoreLoading %s: restoring form state from %p", m_frame->tree()->uniqueName().string().utf8().data(), itemToRestore);
- doc->setStateForNewFormElements(itemToRestore->documentState());
- }
-}
-
-bool HistoryController::shouldStopLoadingForHistoryItem(HistoryItem* targetItem) const
-{
- if (!m_currentItem)
- return false;
- // Don't abort the current load if we're navigating within the current document.
- return !m_currentItem->shouldDoSameDocumentNavigationTo(targetItem);
+ if (HistoryNode* historyNode = historyNodeForFrame(frame))
+ return historyNode->value();
+ return 0;
}
-// Main funnel for navigating to a previous location (back/forward, non-search snap-back)
-// This includes recursion to handle loading into framesets properly
-void HistoryController::goToItem(HistoryItem* targetItem)
+HistoryController::HistoryController(Page* page)
+ : m_page(page)
+ , m_defersLoading(false)
{
- ASSERT(!m_frame->tree()->parent());
-
- // shouldGoToHistoryItem is a private delegate method. This is needed to fix:
- // <rdar://problem/3951283> can view pages from the back/forward cache that should be disallowed by Parental Controls
- // Ultimately, history item navigations should go through the policy delegate. That's covered in:
- // <rdar://problem/3979539> back/forward cache navigations should consult policy delegate
- Page* page = m_frame->page();
- if (!page)
- return;
- if (m_defersLoading) {
- m_deferredItem = targetItem;
- return;
- }
-
- // Set the BF cursor before commit, which lets the user quickly click back/forward again.
- // - plus, it only makes sense for the top level of the operation through the frametree,
- // as opposed to happening for some/one of the page commits that might happen soon
- RefPtr<HistoryItem> currentItem = page->backForward().currentItem();
- page->backForward().setCurrentItem(targetItem);
-
- // First set the provisional item of any frames that are not actually navigating.
- // This must be done before trying to navigate the desired frame, because some
- // navigations can commit immediately (such as about:blank). We must be sure that
- // all frames have provisional items set before the commit.
- recursiveSetProvisionalItem(targetItem, currentItem.get());
- // Now that all other frames have provisional items, do the actual navigation.
- recursiveGoToItem(targetItem, currentItem.get());
}
-void HistoryController::setDefersLoading(bool defer)
-{
- m_defersLoading = defer;
- if (!defer && m_deferredItem) {
- goToItem(m_deferredItem.get());
- m_deferredItem = 0;
- }
-}
-
-void HistoryController::updateForBackForwardNavigation()
+HistoryController::~HistoryController()
{
-#if !LOG_DISABLED
- LOG(History, "WebCoreHistory: Updating History for back/forward navigation in frame %s", m_frame->document()->title().utf8().data());
-#endif
-
- saveScrollPositionAndViewStateToItem(m_previousItem.get());
-
- // When traversing history, we may end up redirecting to a different URL
- // this time (e.g., due to cookies). See http://webkit.org/b/49654.
- updateCurrentItem();
}
-void HistoryController::updateForReload()
+void HistoryController::updateBackForwardListForFragmentScroll(Frame* frame, HistoryItem* item)
{
-#if !LOG_DISABLED
- LOG(History, "WebCoreHistory: Updating History for reload in frame %s", m_frame->document()->title().utf8().data());
-#endif
-
- if (m_currentItem) {
- if (m_frame->loader()->loadType() == FrameLoadTypeReload || m_frame->loader()->loadType() == FrameLoadTypeReloadFromOrigin)
- saveScrollPositionAndViewStateToItem(m_currentItem.get());
- }
-
- // When reloading the page, we may end up redirecting to a different URL
- // this time (e.g., due to cookies). See http://webkit.org/b/4072.
- updateCurrentItem();
+ m_provisionalEntry.clear();
+ createNewBackForwardItem(frame, item, false);
}
-// There are 2 things you might think of as "history", all of which are handled by these functions.
-//
-// 1) Back/forward: The m_currentItem is part of this mechanism.
-// 2) Global history: Handled by the client.
-//
-void HistoryController::updateForStandardLoad()
+void HistoryController::goToEntry(PassOwnPtr<HistoryEntry> targetEntry)
{
- LOG(History, "WebCoreHistory: Updating History for Standard Load in frame %s", m_frame->loader()->documentLoader()->url().string().ascii().data());
+ ASSERT(m_sameDocumentLoadsInProgress.isEmpty());
+ ASSERT(m_differentDocumentLoadsInProgress.isEmpty());
- if (!m_frame->loader()->documentLoader()->urlForHistory().isEmpty())
- updateBackForwardListClippedAtTarget(true);
-}
+ m_provisionalEntry = targetEntry;
+ if (m_currentEntry)
+ recursiveGoToEntry(m_page->mainFrame());
+ else
+ m_differentDocumentLoadsInProgress.set(m_page->mainFrame(), m_provisionalEntry->root());
-void HistoryController::updateForRedirectWithLockedBackForwardList()
-{
-#if !LOG_DISABLED
- LOG(History, "WebCoreHistory: Updating History for redirect load in frame %s", m_frame->document()->title().utf8().data());
-#endif
+ if (m_sameDocumentLoadsInProgress.isEmpty() && m_differentDocumentLoadsInProgress.isEmpty())
+ m_sameDocumentLoadsInProgress.set(m_page->mainFrame(), m_provisionalEntry->root());
- if (!m_currentItem && !m_frame->tree()->parent()) {
- if (!m_frame->loader()->documentLoader()->urlForHistory().isEmpty())
- updateBackForwardListClippedAtTarget(true);
+ if (m_differentDocumentLoadsInProgress.isEmpty()) {
+ m_previousEntry = m_currentEntry.release();
+ m_currentEntry = m_provisionalEntry.release();
+ } else {
+ m_page->mainFrame()->loader().stopAllLoaders();
}
- // The client redirect replaces the current history item.
- updateCurrentItem();
-}
-void HistoryController::updateForInitialLoadInChildFrame()
-{
- Frame* parentFrame = m_frame->tree()->parent();
- if (parentFrame && parentFrame->loader()->history()->m_currentItem)
- parentFrame->loader()->history()->m_currentItem->setChildItem(createItem());
+ for (HistoryFrameLoadSet::iterator it = m_sameDocumentLoadsInProgress.begin(); it != m_sameDocumentLoadsInProgress.end(); ++it)
+ it->key->loader().loadHistoryItem(it->value.get(), HistorySameDocumentLoad);
+ for (HistoryFrameLoadSet::iterator it = m_differentDocumentLoadsInProgress.begin(); it != m_differentDocumentLoadsInProgress.end(); ++it)
+ it->key->loader().loadHistoryItem(it->value.get(), HistoryDifferentDocumentLoad);
+ m_sameDocumentLoadsInProgress.clear();
+ m_differentDocumentLoadsInProgress.clear();
}
-void HistoryController::updateForCommit()
+void HistoryController::recursiveGoToEntry(Frame* frame)
{
- FrameLoader* frameLoader = m_frame->loader();
-#if !LOG_DISABLED
- if (m_frame->document())
- LOG(History, "WebCoreHistory: Updating History for commit in frame %s", m_frame->document()->title().utf8().data());
-#endif
- FrameLoadType type = frameLoader->loadType();
- if (isBackForwardLoadType(type) || (isReloadTypeWithProvisionalItem(type) && !frameLoader->documentLoader()->unreachableURL().isEmpty())) {
- // Once committed, we want to use current item for saving DocState, and
- // the provisional item for restoring state.
- // Note previousItem must be set before we close the URL, which will
- // happen when the data source is made non-provisional below
- m_previousItem = m_currentItem;
- ASSERT(m_provisionalItem);
- m_currentItem = m_provisionalItem;
- m_provisionalItem = 0;
-
- // Tell all other frames in the tree to commit their provisional items and
- // restore their scroll position. We'll avoid this frame (which has already
- // committed) and its children (which will be replaced).
- Page* page = m_frame->page();
- ASSERT(page);
- page->mainFrame()->loader()->history()->recursiveUpdateForCommit();
- }
-
- switch (type) {
- case FrameLoadTypeBackForward:
- updateForBackForwardNavigation();
+ ASSERT(m_provisionalEntry);
+ ASSERT(m_currentEntry);
+ HistoryItem* newItem = m_provisionalEntry->itemForFrame(frame);
+ HistoryItem* oldItem = m_currentEntry->itemForFrame(frame);
+ if (!newItem)
return;
- case FrameLoadTypeReload:
- case FrameLoadTypeReloadFromOrigin:
- case FrameLoadTypeSame:
- updateForReload();
- return;
- case FrameLoadTypeStandard:
- updateForStandardLoad();
- return;
- case FrameLoadTypeRedirectWithLockedBackForwardList:
- updateForRedirectWithLockedBackForwardList();
- return;
- case FrameLoadTypeInitialInChildFrame:
- updateForInitialLoadInChildFrame();
+
+ if (!oldItem || (newItem != oldItem && newItem->itemSequenceNumber() != oldItem->itemSequenceNumber())) {
+ if (oldItem && newItem->documentSequenceNumber() == oldItem->documentSequenceNumber())
+ m_sameDocumentLoadsInProgress.set(frame, newItem);
+ else
+ m_differentDocumentLoadsInProgress.set(frame, newItem);
return;
- default:
- ASSERT_NOT_REACHED();
}
-}
-bool HistoryController::isReloadTypeWithProvisionalItem(FrameLoadType type)
-{
- return (type == FrameLoadTypeReload || type == FrameLoadTypeReloadFromOrigin) && m_provisionalItem;
+ for (Frame* child = frame->tree().firstChild(); child; child = child->tree().nextSibling())
+ recursiveGoToEntry(child);
}
-void HistoryController::recursiveUpdateForCommit()
+void HistoryController::goToItem(HistoryItem* targetItem)
{
- // The frame that navigated will now have a null provisional item.
- // Ignore it and its children.
- if (!m_provisionalItem)
+ if (m_defersLoading) {
+ m_deferredItem = targetItem;
return;
-
- // For each frame that already had the content the item requested (based on
- // (a matching URL and frame tree snapshot), just restore the scroll position.
- // Save form state
- if (m_currentItem && itemsAreClones(m_currentItem.get(), m_provisionalItem.get())) {
- saveDocumentState();
- saveScrollPositionAndViewStateToItem(m_currentItem.get());
-
- if (FrameView* view = m_frame->view())
- view->setWasScrolledByUser(false);
-
- // Now commit the provisional item
- m_previousItem = m_currentItem;
- m_currentItem = m_provisionalItem;
- m_provisionalItem = 0;
-
- // Restore form state (works from currentItem)
- restoreDocumentState();
-
- // Restore the scroll position (we choose to do this rather than going back to the anchor point)
- restoreScrollPositionAndViewState();
}
- // Iterate over the rest of the tree
- for (Frame* child = m_frame->tree()->firstChild(); child; child = child->tree()->nextSibling())
- child->loader()->history()->recursiveUpdateForCommit();
+ OwnPtr<HistoryEntry> newEntry = HistoryEntry::create(targetItem);
+ Deque<HistoryNode*> historyNodes;
+ historyNodes.append(newEntry->rootHistoryNode());
+ while (!historyNodes.isEmpty()) {
+ // For each item, read the children (if any) off the HistoryItem,
+ // create a new HistoryNode for each child and attach it,
+ // then clear the children on the HistoryItem.
+ HistoryNode* historyNode = historyNodes.takeFirst();
+ const HistoryItemVector& children = historyNode->value()->children();
+ for (size_t i = 0; i < children.size(); i++) {
+ HistoryNode* childHistoryNode = historyNode->addChild(children[i].get());
+ historyNodes.append(childHistoryNode);
+ }
+ historyNode->value()->clearChildren();
+ }
+ goToEntry(newEntry.release());
}
-void HistoryController::updateForSameDocumentNavigation()
+void HistoryController::setDefersLoading(bool defer)
{
- if (m_frame->document()->url().isEmpty())
- return;
-
- Page* page = m_frame->page();
- if (!page)
- return;
-
- page->mainFrame()->loader()->history()->recursiveUpdateForSameDocumentNavigation();
-
- if (m_currentItem)
- m_currentItem->setURL(m_frame->document()->url());
+ m_defersLoading = defer;
+ if (!defer && m_deferredItem) {
+ goToItem(m_deferredItem.get());
+ m_deferredItem = 0;
+ }
}
-void HistoryController::recursiveUpdateForSameDocumentNavigation()
+void HistoryController::updateForInitialLoadInChildFrame(Frame* frame, HistoryItem* item)
{
- // The frame that navigated will now have a null provisional item.
- // Ignore it and its children.
- if (!m_provisionalItem)
- return;
-
- // The provisional item may represent a different pending navigation.
- // Don't commit it if it isn't a same document navigation.
- if (m_currentItem && !m_currentItem->shouldDoSameDocumentNavigationTo(m_provisionalItem.get()))
+ ASSERT(frame->tree().parent());
+ if (!m_currentEntry)
return;
-
- // Commit the provisional item.
- m_previousItem = m_currentItem;
- m_currentItem = m_provisionalItem;
- m_provisionalItem = 0;
-
- // Iterate over the rest of the tree.
- for (Frame* child = m_frame->tree()->firstChild(); child; child = child->tree()->nextSibling())
- child->loader()->history()->recursiveUpdateForSameDocumentNavigation();
-}
-
-void HistoryController::setCurrentItem(HistoryItem* item)
-{
- m_previousItem = m_currentItem;
- m_currentItem = item;
-}
-
-void HistoryController::setCurrentItemTitle(const String& title)
-{
- if (m_currentItem)
- m_currentItem->setTitle(title);
-}
-
-bool HistoryController::currentItemShouldBeReplaced() const
-{
- // From the HTML5 spec for location.assign():
- // "If the browsing context's session history contains only one Document,
- // and that was the about:blank Document created when the browsing context
- // was created, then the navigation must be done with replacement enabled."
- return m_currentItem && !m_previousItem && equalIgnoringCase(m_currentItem->urlString(), blankURL());
-}
-
-void HistoryController::setProvisionalItem(HistoryItem* item)
-{
- m_provisionalItem = item;
+ if (HistoryNode* existingChildHistoryNode = m_currentEntry->historyNodeForFrame(frame))
+ existingChildHistoryNode->updateValue(item);
+ else if (HistoryNode* parentHistoryNode = m_currentEntry->historyNodeForFrame(frame->tree().parent()))
+ parentHistoryNode->addChild(item);
+}
+
+// FIXME: This is a temporary hack designed to be mergeable to the 1750 branch.
+// As trunk stands currently, we should never clear the provisional entry, since it's
+// possible to clear based on a commit in an irrelevant frame. On trunk, the provisional entry is
+// an implementation detail of HistoryController and only used when we know that we're in
+// a back/forward navigation. Also, it is clobbered when a new history navigation begins,
+// so we can be sure that a stale provisional entry won't be confused with a new one.
+// On the branch, however, the provisional entry is observable because
+// WebFrameImpl::currentHistoryItem() will return data based on the provisional entry preferentially
+// over the current entry, so we can't leave a stale provisional entry around indefinitely.
+// Therefore, search the frame tree for any back/forward navigations in progress, and only clear
+// the provisional entry if none are found.
+// Once the fix is merged to the branch, this can be removed, along with all places that we clear
+// m_provisionalEntry.
+static bool shouldClearProvisionalEntry(Page* page)
+{
+ for (Frame* frame = page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
+ if (frame->loader().loadType() == FrameLoadTypeBackForward)
+ return false;
+ }
+ return true;
}
-void HistoryController::initializeItem(HistoryItem* item)
+void HistoryController::updateForCommit(Frame* frame, HistoryItem* item)
{
- DocumentLoader* documentLoader = m_frame->loader()->documentLoader();
- ASSERT(documentLoader);
-
- KURL unreachableURL = documentLoader->unreachableURL();
-
- KURL url;
- KURL originalURL;
-
- if (!unreachableURL.isEmpty()) {
- url = unreachableURL;
- originalURL = unreachableURL;
- } else {
- url = documentLoader->url();
- originalURL = documentLoader->originalURL();
+ FrameLoadType type = frame->loader().loadType();
+ if (isBackForwardLoadType(type) && m_provisionalEntry) {
+ // Once committed, we want to use current item for saving DocState, and
+ // the provisional item for restoring state.
+ // Note previousItem must be set before we close the URL, which will
+ // happen when the data source is made non-provisional below
+ m_previousEntry = m_currentEntry.release();
+ ASSERT(m_provisionalEntry);
+ m_currentEntry = m_provisionalEntry.release();
+ } else if (type != FrameLoadTypeRedirectWithLockedBackForwardList && shouldClearProvisionalEntry(m_page)) {
+ m_provisionalEntry.clear();
}
- // Frames that have never successfully loaded any content
- // may have no URL at all. Currently our history code can't
- // deal with such things, so we nip that in the bud here.
- // Later we may want to learn to live with nil for URL.
- // See bug 3368236 and related bugs for more information.
- if (url.isEmpty())
- url = blankURL();
- if (originalURL.isEmpty())
- originalURL = blankURL();
-
- Frame* parentFrame = m_frame->tree()->parent();
- String parent = parentFrame ? parentFrame->tree()->uniqueName() : "";
-
- item->setURL(url);
- item->setTarget(m_frame->tree()->uniqueName());
- item->setParent(parent);
- // FIXME: should store title directionality in history as well.
- item->setTitle(m_frame->document()->title());
- item->setOriginalURLString(originalURL.string());
-
- // Save form state if this is a POST
- item->setFormInfoFromRequest(documentLoader->request());
+ if (type == FrameLoadTypeStandard)
+ createNewBackForwardItem(frame, item, true);
+ else if (type == FrameLoadTypeInitialInChildFrame)
+ updateForInitialLoadInChildFrame(frame, item);
}
-PassRefPtr<HistoryItem> HistoryController::createItem()
+static PassRefPtr<HistoryItem> itemForExport(HistoryNode* historyNode)
{
- RefPtr<HistoryItem> item = HistoryItem::create();
- initializeItem(item.get());
-
- // Set the item for which we will save document state
- m_previousItem = m_currentItem;
- m_currentItem = item;
-
- return item.release();
+ RefPtr<HistoryItem> item = historyNode->value()->copy();
+ const Vector<OwnPtr<HistoryNode> >& childEntries = historyNode->children();
+ for (size_t i = 0; i < childEntries.size(); i++)
+ item->addChildItem(itemForExport(childEntries[i].get()));
+ return item;
}
-PassRefPtr<HistoryItem> HistoryController::createItemTree(Frame* targetFrame, bool clipAtTarget)
+PassRefPtr<HistoryItem> HistoryController::currentItemForExport()
{
- RefPtr<HistoryItem> bfItem = createItem();
- saveScrollPositionAndViewStateToItem(m_previousItem.get());
-
- if (!clipAtTarget || m_frame != targetFrame) {
- // save frame state for items that aren't loading (khtml doesn't save those)
- saveDocumentState();
-
- // clipAtTarget is false for navigations within the same document, so
- // we should copy the documentSequenceNumber over to the newly create
- // item. Non-target items are just clones, and they should therefore
- // preserve the same itemSequenceNumber.
- if (m_previousItem) {
- if (m_frame != targetFrame)
- bfItem->setItemSequenceNumber(m_previousItem->itemSequenceNumber());
- bfItem->setDocumentSequenceNumber(m_previousItem->documentSequenceNumber());
- }
-
- for (Frame* child = m_frame->tree()->firstChild(); child; child = child->tree()->nextSibling()) {
- // If the child is a frame corresponding to an <object> element that never loaded,
- // we don't want to create a history item, because that causes fallback content
- // to be ignored on reload.
- FrameLoader* childLoader = child->loader();
- if (childLoader->stateMachine()->startedFirstRealLoad() || !child->ownerElement()->isObjectElement())
- bfItem->addChildItem(childLoader->history()->createItemTree(targetFrame, clipAtTarget));
- }
- }
- // FIXME: Eliminate the isTargetItem flag in favor of itemSequenceNumber.
- if (m_frame == targetFrame)
- bfItem->setIsTargetItem(true);
- return bfItem;
+ if (!m_currentEntry)
+ return 0;
+ return itemForExport(m_currentEntry->rootHistoryNode());
}
-// The general idea here is to traverse the frame tree and the item tree in parallel,
-// tracking whether each frame already has the content the item requests. If there is
-// a match, we set the provisional item and recurse. Otherwise we will reload that
-// frame and all its kids in recursiveGoToItem.
-void HistoryController::recursiveSetProvisionalItem(HistoryItem* item, HistoryItem* fromItem)
+PassRefPtr<HistoryItem> HistoryController::previousItemForExport()
{
- ASSERT(item);
-
- if (itemsAreClones(item, fromItem)) {
- // Set provisional item, which will be committed in recursiveUpdateForCommit.
- m_provisionalItem = item;
-
- const HistoryItemVector& childItems = item->children();
-
- int size = childItems.size();
-
- for (int i = 0; i < size; ++i) {
- String childFrameName = childItems[i]->target();
- HistoryItem* fromChildItem = fromItem->childItemWithTarget(childFrameName);
- ASSERT(fromChildItem);
- Frame* childFrame = m_frame->tree()->child(childFrameName);
- ASSERT(childFrame);
- childFrame->loader()->history()->recursiveSetProvisionalItem(childItems[i].get(), fromChildItem);
- }
- }
-}
-
-// We now traverse the frame tree and item tree a second time, loading frames that
-// do have the content the item requests.
-void HistoryController::recursiveGoToItem(HistoryItem* item, HistoryItem* fromItem)
-{
- ASSERT(item);
-
- if (itemsAreClones(item, fromItem)) {
- // Just iterate over the rest, looking for frames to navigate.
- const HistoryItemVector& childItems = item->children();
-
- int size = childItems.size();
- for (int i = 0; i < size; ++i) {
- String childFrameName = childItems[i]->target();
- HistoryItem* fromChildItem = fromItem->childItemWithTarget(childFrameName);
- ASSERT(fromChildItem);
- Frame* childFrame = m_frame->tree()->child(childFrameName);
- ASSERT(childFrame);
- childFrame->loader()->history()->recursiveGoToItem(childItems[i].get(), fromChildItem);
- }
- } else {
- m_frame->loader()->loadHistoryItem(item);
- }
+ if (!m_previousEntry)
+ return 0;
+ return itemForExport(m_previousEntry->rootHistoryNode());
}
-bool HistoryController::itemsAreClones(HistoryItem* item1, HistoryItem* item2) const
+PassRefPtr<HistoryItem> HistoryController::provisionalItemForExport()
{
- // If the item we're going to is a clone of the item we're at, then we do
- // not need to load it again. The current frame tree and the frame tree
- // snapshot in the item have to match.
- // Note: Some clients treat a navigation to the current history item as
- // a reload. Thus, if item1 and item2 are the same, we need to create a
- // new document and should not consider them clones.
- // (See http://webkit.org/b/35532 for details.)
- return item1
- && item2
- && item1 != item2
- && item1->itemSequenceNumber() == item2->itemSequenceNumber()
- && currentFramesMatchItem(item1)
- && item2->hasSameFrames(item1);
+ if (!m_provisionalEntry)
+ return 0;
+ return itemForExport(m_provisionalEntry->rootHistoryNode());
}
-// Helper method that determines whether the current frame tree matches given history item's.
-bool HistoryController::currentFramesMatchItem(HistoryItem* item) const
+HistoryItem* HistoryController::itemForNewChildFrame(Frame* frame) const
{
- if ((!m_frame->tree()->uniqueName().isEmpty() || !item->target().isEmpty()) && m_frame->tree()->uniqueName() != item->target())
- return false;
-
- const HistoryItemVector& childItems = item->children();
- if (childItems.size() != m_frame->tree()->childCount())
- return false;
-
- unsigned size = childItems.size();
- for (unsigned i = 0; i < size; ++i) {
- if (!m_frame->tree()->child(childItems[i]->target()))
- return false;
- }
-
- return true;
+ return m_currentEntry ? m_currentEntry->itemForFrame(frame) : 0;
}
-void HistoryController::updateBackForwardListClippedAtTarget(bool doClip)
+void HistoryController::removeChildrenForRedirect(Frame* frame)
{
- // In the case of saving state about a page with frames, we store a tree of items that mirrors the frame tree.
- // The item that was the target of the user's navigation is designated as the "targetItem".
- // When this function is called with doClip=true we're able to create the whole tree except for the target's children,
- // which will be loaded in the future. That part of the tree will be filled out as the child loads are committed.
-
- Page* page = m_frame->page();
- if (!page)
- return;
-
- if (m_frame->loader()->documentLoader()->urlForHistory().isEmpty())
+ if (!m_provisionalEntry)
return;
-
- Frame* mainFrame = page->mainFrame();
- ASSERT(mainFrame);
-
- RefPtr<HistoryItem> topItem = mainFrame->loader()->history()->createItemTree(m_frame, doClip);
- LOG(BackForward, "WebCoreBackForward - Adding backforward item %p for frame %s", topItem.get(), m_frame->loader()->documentLoader()->url().string().ascii().data());
- page->backForward().addItem(topItem.release());
+ if (HistoryNode* node = m_provisionalEntry->historyNodeForFrame(frame))
+ node->removeChildren();
}
-void HistoryController::updateCurrentItem()
+void HistoryController::createNewBackForwardItem(Frame* targetFrame, HistoryItem* item, bool clipAtTarget)
{
- if (!m_currentItem)
- return;
-
- DocumentLoader* documentLoader = m_frame->loader()->documentLoader();
-
- if (!documentLoader->unreachableURL().isEmpty())
- return;
-
- if (m_currentItem->url() != documentLoader->url()) {
- // We ended up on a completely different URL this time, so the HistoryItem
- // needs to be re-initialized. Preserve the isTargetItem flag as it is a
- // property of how this HistoryItem was originally created and is not
- // dependent on the document.
- bool isTargetItem = m_currentItem->isTargetItem();
- m_currentItem->reset();
- initializeItem(m_currentItem.get());
- m_currentItem->setIsTargetItem(isTargetItem);
+ RefPtr<HistoryItem> newItem = item;
+ if (!m_currentEntry) {
+ m_currentEntry = HistoryEntry::create(newItem.get());
} else {
- // Even if the final URL didn't change, the form data may have changed.
- m_currentItem->setFormInfoFromRequest(documentLoader->request());
+ HistoryItem* oldItem = m_currentEntry->itemForFrame(targetFrame);
+ if (!clipAtTarget && oldItem)
+ newItem->setDocumentSequenceNumber(oldItem->documentSequenceNumber());
+ m_previousEntry = m_currentEntry.release();
+ m_currentEntry = m_previousEntry->cloneAndReplace(newItem.get(), clipAtTarget, targetFrame, m_page);
}
}
-void HistoryController::pushState(PassRefPtr<SerializedScriptValue> stateObject, const String& title, const String& urlString)
-{
- if (!m_currentItem)
- return;
-
- Page* page = m_frame->page();
- ASSERT(page);
-
- // Get a HistoryItem tree for the current frame tree.
- RefPtr<HistoryItem> topItem = page->mainFrame()->loader()->history()->createItemTree(m_frame, false);
-
- // Override data in the current item (created by createItemTree) to reflect
- // the pushState() arguments.
- m_currentItem->setTitle(title);
- m_currentItem->setStateObject(stateObject);
- m_currentItem->setURLString(urlString);
- page->backForward().addItem(topItem.release());
-}
-
-void HistoryController::replaceState(PassRefPtr<SerializedScriptValue> stateObject, const String& title, const String& urlString)
-{
- if (!m_currentItem)
- return;
-
- if (!urlString.isEmpty())
- m_currentItem->setURLString(urlString);
- m_currentItem->setTitle(title);
- m_currentItem->setStateObject(stateObject);
- m_currentItem->setFormData(0);
- m_currentItem->setFormContentType(String());
-
- ASSERT(m_frame->page());
-}
-
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/loader/HistoryController.h b/chromium/third_party/WebKit/Source/core/loader/HistoryController.h
index a5f85b85547..d9478c37554 100644
--- a/chromium/third_party/WebKit/Source/core/loader/HistoryController.h
+++ b/chromium/third_party/WebKit/Source/core/loader/HistoryController.h
@@ -32,6 +32,7 @@
#include "core/history/HistoryItem.h"
#include "core/loader/FrameLoaderTypes.h"
+#include "wtf/HashMap.h"
#include "wtf/Noncopyable.h"
#include "wtf/RefPtr.h"
#include "wtf/text/WTFString.h"
@@ -39,72 +40,136 @@
namespace WebCore {
class Frame;
-class SerializedScriptValue;
+class HistoryEntry;
+class Page;
+
+
+// A guide to history state in Blink:
+//
+// HistoryController: Owned by Page, is the entry point for interacting with history.
+// Handles most of the operations to modify history state, navigate to an existing
+// back/forward entry, etc.
+// HistoryEntry: Represents a single entry in the back/forward list, encapsulating
+// all frames in the page it represents. It provides access to each frame's
+// state via lookups by frame id or frame name.
+// HistoryNode: Represents a single frame in a HistoryEntry. Owned by a HistoryEntry. HistoryNodes
+// form a tree that mirrors the FrameTree in the corresponding page. HistoryNodes represent
+// the structure of the page, but don't hold any per-frame state except a list of child frames.
+// HistoryItem (lives in a separate file): The state for a given frame. Can persist across
+// navigations. HistoryItem is reference counted, and each HistoryNode holds a reference
+// to its single corresponding HistoryItem. Can be referenced by multiple HistoryNodes and
+// can therefore exist in multiple HistoryEntry instances.
+//
+// Suppose we have the following page, foo.com, which embeds foo.com/a in an iframe:
+//
+// HistoryEntry 0:
+// HistoryNode 0_0 (HistoryItem A (url: foo.com))
+// HistoryNode 0_1: (HistoryItem B (url: foo.com/a))
+//
+// Now we navigation the top frame to bar.com, which embeds bar.com/b and bar.com/c in iframes,
+// and bar.com/b in turn embeds bar.com/d. We will create a new HistoryEntry with a tree
+// containing 4 new HistoryNodes. The state will be:
+//
+// HistoryEntry 1:
+// HistoryNode 1_0 (HistoryItem C (url: bar.com))
+// HistoryNode 1_1: (HistoryItem D (url: bar.com/b))
+// HistoryNode 1_3: (HistoryItem F (url: bar.com/d))
+// HistoryNode 1_2: (HistoryItem E (url: bar.com/c))
+//
+//
+// Finally, we navigate the first subframe from bar.com/b to bar.com/e, which embeds bar.com/f.
+// We will create a new HistoryEntry and new HistoryNode for each frame. Any frame that
+// navigates (bar.com/e and its child, bar.com/f) will receive a new HistoryItem. However,
+// 2 frames were not navigated (bar.com and bar.com/c), so those two frames will reuse the
+// existing HistoryItem:
+//
+// HistoryEntry 2:
+// HistoryNode 2_0 (HistoryItem C (url: bar.com)) *REUSED*
+// HistoryNode 2_1: (HistoryItem G (url: bar.com/e))
+// HistoryNode 2_3: (HistoryItem H (url: bar.com/f))
+// HistoryNode 2_2: (HistoryItem E (url: bar.com/c)) *REUSED*
+//
+
+class HistoryNode {
+public:
+ static PassOwnPtr<HistoryNode> create(HistoryEntry*, HistoryItem*);
+ ~HistoryNode() { }
-class HistoryController {
- WTF_MAKE_NONCOPYABLE(HistoryController);
+ HistoryNode* addChild(PassRefPtr<HistoryItem>);
+ PassOwnPtr<HistoryNode> cloneAndReplace(HistoryEntry*, HistoryItem* newItem, bool clipAtTarget, Frame* targetFrame, Frame* currentFrame);
+ HistoryItem* value() { return m_value.get(); }
+ void updateValue(PassRefPtr<HistoryItem> item) { m_value = item; }
+ const Vector<OwnPtr<HistoryNode> >& children() const { return m_children; }
+ void removeChildren();
+
+private:
+ HistoryNode(HistoryEntry*, HistoryItem*);
+
+ HistoryEntry* m_entry;
+ Vector<OwnPtr<HistoryNode> > m_children;
+ RefPtr<HistoryItem> m_value;
+};
+
+class HistoryEntry {
public:
- explicit HistoryController(Frame*);
- ~HistoryController();
+ static PassOwnPtr<HistoryEntry> create(HistoryItem* root);
+ PassOwnPtr<HistoryEntry> cloneAndReplace(HistoryItem* newItem, bool clipAtTarget, Frame* targetFrame, Page*);
- void saveScrollPositionAndViewStateToItem(HistoryItem*);
- void clearScrollPositionAndViewState();
- void restoreScrollPositionAndViewState();
+ HistoryNode* historyNodeForFrame(Frame*);
+ HistoryItem* itemForFrame(Frame*);
+ HistoryItem* root() const { return m_root->value(); }
+ HistoryNode* rootHistoryNode() const { return m_root.get(); }
- void updateBackForwardListForFragmentScroll();
+private:
+ friend class HistoryNode;
- void saveDocumentState();
- void saveDocumentAndScrollState();
- void restoreDocumentState();
+ HistoryEntry() { }
+ explicit HistoryEntry(HistoryItem* root);
- void updateForCommit();
- void updateForSameDocumentNavigation();
+ OwnPtr<HistoryNode> m_root;
+ HashMap<uint64_t, HistoryNode*> m_framesToItems;
+ HashMap<String, HistoryNode*> m_uniqueNamesToItems;
+};
- HistoryItem* currentItem() const { return m_currentItem.get(); }
- void setCurrentItem(HistoryItem*);
- void setCurrentItemTitle(const String&);
- bool currentItemShouldBeReplaced() const;
+class HistoryController {
+ WTF_MAKE_NONCOPYABLE(HistoryController);
+public:
+ explicit HistoryController(Page*);
+ ~HistoryController();
+
+ // Should only be called by embedder. To request a back/forward
+ // navigation, call FrameLoaderClient::navigateBackForward().
+ void goToItem(HistoryItem*);
- HistoryItem* previousItem() const { return m_previousItem.get(); }
+ void updateBackForwardListForFragmentScroll(Frame*, HistoryItem*);
+ void updateForCommit(Frame*, HistoryItem*);
- HistoryItem* provisionalItem() const { return m_provisionalItem.get(); }
- void setProvisionalItem(HistoryItem*);
+ PassRefPtr<HistoryItem> currentItemForExport();
+ PassRefPtr<HistoryItem> previousItemForExport();
+ PassRefPtr<HistoryItem> provisionalItemForExport();
+ HistoryItem* itemForNewChildFrame(Frame*) const;
+ void removeChildrenForRedirect(Frame*);
- void pushState(PassRefPtr<SerializedScriptValue>, const String& title, const String& url);
- void replaceState(PassRefPtr<SerializedScriptValue>, const String& title, const String& url);
+ bool inSameDocumentLoad() const { return !m_sameDocumentLoadsInProgress.isEmpty() && m_differentDocumentLoadsInProgress.isEmpty(); }
void setDefersLoading(bool);
private:
- friend class Page;
- bool shouldStopLoadingForHistoryItem(HistoryItem*) const;
- void goToItem(HistoryItem*);
+ void goToEntry(PassOwnPtr<HistoryEntry>);
+ void recursiveGoToEntry(Frame*);
+
+ void updateForInitialLoadInChildFrame(Frame*, HistoryItem*);
+ void createNewBackForwardItem(Frame*, HistoryItem*, bool doClip);
+
+ Page* m_page;
+
+ OwnPtr<HistoryEntry> m_currentEntry;
+ OwnPtr<HistoryEntry> m_previousEntry;
+ OwnPtr<HistoryEntry> m_provisionalEntry;
- void initializeItem(HistoryItem*);
- PassRefPtr<HistoryItem> createItem();
- PassRefPtr<HistoryItem> createItemTree(Frame* targetFrame, bool clipAtTarget);
-
- void updateForBackForwardNavigation();
- void updateForReload();
- void updateForStandardLoad();
- void updateForRedirectWithLockedBackForwardList();
- void updateForInitialLoadInChildFrame();
-
- void recursiveSetProvisionalItem(HistoryItem*, HistoryItem*);
- void recursiveGoToItem(HistoryItem*, HistoryItem*);
- bool isReloadTypeWithProvisionalItem(FrameLoadType);
- void recursiveUpdateForCommit();
- void recursiveUpdateForSameDocumentNavigation();
- bool itemsAreClones(HistoryItem*, HistoryItem*) const;
- bool currentFramesMatchItem(HistoryItem*) const;
- void updateBackForwardListClippedAtTarget(bool doClip);
- void updateCurrentItem();
-
- Frame* m_frame;
-
- RefPtr<HistoryItem> m_currentItem;
- RefPtr<HistoryItem> m_previousItem;
- RefPtr<HistoryItem> m_provisionalItem;
+ typedef HashMap<Frame*, RefPtr<HistoryItem> > HistoryFrameLoadSet;
+ HistoryFrameLoadSet m_sameDocumentLoadsInProgress;
+ HistoryFrameLoadSet m_differentDocumentLoadsInProgress;
bool m_defersLoading;
RefPtr<HistoryItem> m_deferredItem;
diff --git a/chromium/third_party/WebKit/Source/core/loader/IconController.cpp b/chromium/third_party/WebKit/Source/core/loader/IconController.cpp
deleted file mode 100644
index b112bc4cabb..00000000000
--- a/chromium/third_party/WebKit/Source/core/loader/IconController.cpp
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
- * Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
- * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
- * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
- * Copyright (C) 2008 Alp Toker <alp@atoker.com>
- * Copyright (C) Research In Motion Limited 2009. All rights reserved.
- * Copyright (C) 2011 Kris Jordan <krisjordan@gmail.com>
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/loader/IconController.h"
-
-#include "core/dom/Document.h"
-#include "core/dom/IconURL.h"
-#include "core/page/Frame.h"
-
-namespace WebCore {
-
-IconController::IconController(Frame* frame)
- : m_frame(frame)
-{
-}
-
-IconController::~IconController()
-{
-}
-
-KURL IconController::url()
-{
- IconURLs iconURLs = urlsForTypes(Favicon);
- return iconURLs.isEmpty() ? KURL() : iconURLs[0].m_iconURL;
-}
-
-IconURL IconController::iconURL(IconType iconType) const
-{
- IconURL result;
- const Vector<IconURL>& iconURLs = m_frame->document()->iconURLs(iconType);
- Vector<IconURL>::const_iterator iter(iconURLs.begin());
- for (; iter != iconURLs.end(); ++iter) {
- if (result.m_iconURL.isEmpty() || !iter->m_mimeType.isEmpty())
- result = *iter;
- }
-
- return result;
-}
-
-IconURLs IconController::urlsForTypes(int iconTypesMask)
-{
- IconURLs iconURLs;
- if (m_frame->tree() && m_frame->tree()->parent())
- return iconURLs;
-
- if (iconTypesMask & Favicon && !appendToIconURLs(Favicon, &iconURLs))
- iconURLs.append(defaultURL(Favicon));
-
-#if ENABLE(TOUCH_ICON_LOADING)
- appendToIconURLs(TouchPrecomposedIcon, &iconURLs);
- appendToIconURLs(TouchIcon, &iconURLs);
-#endif
-
- // Finally, append all remaining icons of this type.
- const Vector<IconURL>& allIconURLs = m_frame->document()->iconURLs(iconTypesMask);
- for (Vector<IconURL>::const_iterator iter = allIconURLs.begin(); iter != allIconURLs.end(); ++iter) {
- int i;
- int iconCount = iconURLs.size();
- for (i = 0; i < iconCount; ++i) {
- if (*iter == iconURLs.at(i))
- break;
- }
- if (i == iconCount)
- iconURLs.append(*iter);
- }
-
- return iconURLs;
-}
-
-bool IconController::appendToIconURLs(IconType iconType, IconURLs* iconURLs)
-{
- IconURL faviconURL = iconURL(iconType);
- if (faviconURL.m_iconURL.isEmpty())
- return false;
-
- iconURLs->append(faviconURL);
- return true;
-}
-
-IconURL IconController::defaultURL(IconType iconType)
-{
- // Don't return a favicon iconURL unless we're http or https
- KURL documentURL = m_frame->document()->url();
- if (!documentURL.protocolIsInHTTPFamily())
- return IconURL();
-
- KURL url;
- bool couldSetProtocol = url.setProtocol(documentURL.protocol());
- ASSERT_UNUSED(couldSetProtocol, couldSetProtocol);
- url.setHost(documentURL.host());
- if (documentURL.hasPort())
- url.setPort(documentURL.port());
-
- if (iconType == Favicon) {
- url.setPath("/favicon.ico");
- return IconURL::defaultIconURL(url, Favicon);
- }
- return IconURL();
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/loader/IconController.h b/chromium/third_party/WebKit/Source/core/loader/IconController.h
deleted file mode 100644
index 87aa799dcda..00000000000
--- a/chromium/third_party/WebKit/Source/core/loader/IconController.h
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Copyright (C) 2006, 2007, 2008, 2009, 2011 Apple Inc. All rights reserved.
- * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
- * Copyright (C) Research In Motion Limited 2009. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef IconController_h
-#define IconController_h
-
-#include "core/dom/IconURL.h"
-
-namespace WebCore {
-
-class Frame;
-class KURL;
-
-class IconController {
- WTF_MAKE_NONCOPYABLE(IconController);
- WTF_MAKE_FAST_ALLOCATED;
-public:
- explicit IconController(Frame*);
- ~IconController();
-
- KURL url();
- IconURLs urlsForTypes(int iconTypesMask);
- IconURL iconURL(IconType) const;
-
-private:
- bool appendToIconURLs(IconType, IconURLs*);
- IconURL defaultURL(IconType);
-
- Frame* m_frame;
-};
-
-} // namespace WebCore
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/loader/ImageLoader.cpp b/chromium/third_party/WebKit/Source/core/loader/ImageLoader.cpp
index 06482124c0c..a8177ba48d5 100644
--- a/chromium/third_party/WebKit/Source/core/loader/ImageLoader.cpp
+++ b/chromium/third_party/WebKit/Source/core/loader/ImageLoader.cpp
@@ -25,36 +25,35 @@
#include "HTMLNames.h"
#include "core/dom/Document.h"
#include "core/dom/Element.h"
-#include "core/dom/Event.h"
-#include "core/dom/EventSender.h"
+#include "core/events/Event.h"
+#include "core/events/EventSender.h"
#include "core/fetch/CrossOriginAccessControl.h"
#include "core/fetch/FetchRequest.h"
-#include "core/fetch/ImageResource.h"
#include "core/fetch/ResourceFetcher.h"
#include "core/html/HTMLObjectElement.h"
#include "core/html/parser/HTMLParserIdioms.h"
#include "core/rendering/RenderImage.h"
#include "core/rendering/RenderVideo.h"
#include "core/rendering/svg/RenderSVGImage.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/weborigin/SecurityOrigin.h"
namespace WebCore {
static ImageEventSender& beforeLoadEventSender()
{
- DEFINE_STATIC_LOCAL(ImageEventSender, sender, (eventNames().beforeloadEvent));
+ DEFINE_STATIC_LOCAL(ImageEventSender, sender, (EventTypeNames::beforeload));
return sender;
}
static ImageEventSender& loadEventSender()
{
- DEFINE_STATIC_LOCAL(ImageEventSender, sender, (eventNames().loadEvent));
+ DEFINE_STATIC_LOCAL(ImageEventSender, sender, (EventTypeNames::load));
return sender;
}
static ImageEventSender& errorEventSender()
{
- DEFINE_STATIC_LOCAL(ImageEventSender, sender, (eventNames().errorEvent));
+ DEFINE_STATIC_LOCAL(ImageEventSender, sender, (EventTypeNames::error));
return sender;
}
@@ -141,10 +140,10 @@ void ImageLoader::setImageWithoutConsideringPendingLoadEvent(ImageResource* newI
void ImageLoader::updateFromElement()
{
- // If we're not making renderers for the page, then don't load images. We don't want to slow
- // down the raw HTML parsing case by loading images we don't intend to display.
+ // Don't load images for inactive documents. We don't want to slow down the
+ // raw HTML parsing case by loading images we don't intend to display.
Document& document = m_element->document();
- if (!document.renderer())
+ if (!document.isActive())
return;
AtomicString attr = m_element->imageSourceURL();
@@ -158,7 +157,7 @@ void ImageLoader::updateFromElement()
if (!attr.isNull() && !stripLeadingAndTrailingHTMLSpaces(attr).isEmpty()) {
FetchRequest request(ResourceRequest(document.completeURL(sourceURI(attr))), element()->localName());
- String crossOriginMode = m_element->fastGetAttribute(HTMLNames::crossoriginAttr);
+ AtomicString crossOriginMode = m_element->fastGetAttribute(HTMLNames::crossoriginAttr);
if (!crossOriginMode.isNull()) {
StoredCredentials allowCredentials = equalIgnoringCase(crossOriginMode, "use-credentials") ? AllowStoredCredentials : DoNotAllowStoredCredentials;
updateRequestForAccessControl(request.mutableResourceRequest(), document.securityOrigin(), allowCredentials);
@@ -363,11 +362,11 @@ void ImageLoader::dispatchPendingEvent(ImageEventSender* eventSender)
{
ASSERT(eventSender == &beforeLoadEventSender() || eventSender == &loadEventSender() || eventSender == &errorEventSender());
const AtomicString& eventType = eventSender->eventType();
- if (eventType == eventNames().beforeloadEvent)
+ if (eventType == EventTypeNames::beforeload)
dispatchPendingBeforeLoadEvent();
- if (eventType == eventNames().loadEvent)
+ if (eventType == EventTypeNames::load)
dispatchPendingLoadEvent();
- if (eventType == eventNames().errorEvent)
+ if (eventType == EventTypeNames::error)
dispatchPendingErrorEvent();
}
@@ -377,7 +376,7 @@ void ImageLoader::dispatchPendingBeforeLoadEvent()
return;
if (!m_image)
return;
- if (!m_element->document().attached())
+ if (!m_element->document().frame())
return;
m_hasPendingBeforeLoadEvent = false;
if (m_element->dispatchBeforeLoadEvent(m_image->url().string())) {
@@ -407,7 +406,7 @@ void ImageLoader::dispatchPendingLoadEvent()
if (!m_image)
return;
m_hasPendingLoadEvent = false;
- if (element()->document().attached())
+ if (element()->document().frame())
dispatchLoadEvent();
// Only consider updating the protection ref-count of the Element immediately before returning
@@ -420,8 +419,8 @@ void ImageLoader::dispatchPendingErrorEvent()
if (!m_hasPendingErrorEvent)
return;
m_hasPendingErrorEvent = false;
- if (element()->document().attached())
- element()->dispatchEvent(Event::create(eventNames().errorEvent));
+ if (element()->document().frame())
+ element()->dispatchEvent(Event::create(EventTypeNames::error));
// Only consider updating the protection ref-count of the Element immediately before returning
// from this function as doing so might result in the destruction of this ImageLoader.
diff --git a/chromium/third_party/WebKit/Source/core/loader/LinkLoader.cpp b/chromium/third_party/WebKit/Source/core/loader/LinkLoader.cpp
index 2e49672fdfd..25c23488f04 100644
--- a/chromium/third_party/WebKit/Source/core/loader/LinkLoader.cpp
+++ b/chromium/third_party/WebKit/Source/core/loader/LinkLoader.cpp
@@ -37,10 +37,9 @@
#include "core/fetch/FetchRequest.h"
#include "core/fetch/ResourceFetcher.h"
#include "core/html/LinkRelAttribute.h"
-#include "core/loader/Prerenderer.h"
-#include "core/page/Settings.h"
-#include "core/platform/PrerenderHandle.h"
-#include "core/platform/network/DNS.h"
+#include "core/loader/PrerenderHandle.h"
+#include "core/frame/Settings.h"
+#include "platform/network/DNS.h"
namespace WebCore {
@@ -53,10 +52,6 @@ LinkLoader::LinkLoader(LinkLoaderClient* client)
LinkLoader::~LinkLoader()
{
- if (m_cachedLinkResource)
- m_cachedLinkResource->removeClient(this);
- if (m_prerenderHandle)
- m_prerenderHandle->removeClient();
}
void LinkLoader::linkLoadTimerFired(Timer<LinkLoader>* timer)
@@ -73,15 +68,14 @@ void LinkLoader::linkLoadingErrorTimerFired(Timer<LinkLoader>* timer)
void LinkLoader::notifyFinished(Resource* resource)
{
- ASSERT_UNUSED(resource, m_cachedLinkResource.get() == resource);
+ ASSERT(this->resource() == resource);
- if (m_cachedLinkResource->errorOccurred())
+ if (resource->errorOccurred())
m_linkLoadingErrorTimer.startOneShot(0);
else
m_linkLoadTimer.startOneShot(0);
- m_cachedLinkResource->removeClient(this);
- m_cachedLinkResource = 0;
+ clearResource();
}
void LinkLoader::didStartPrerender()
@@ -114,30 +108,25 @@ bool LinkLoader::loadLink(const LinkRelAttribute& relAttribute, const String& ty
prefetchDNS(href.host());
}
+ // FIXME(crbug.com/323096): Should take care of import.
if ((relAttribute.isLinkPrefetch() || relAttribute.isLinkSubresource()) && href.isValid() && document.frame()) {
if (!m_client->shouldLoadLink())
return false;
Resource::Type type = relAttribute.isLinkSubresource() ? Resource::LinkSubresource : Resource::LinkPrefetch;
FetchRequest linkRequest(ResourceRequest(document.completeURL(href)), FetchInitiatorTypeNames::link);
- if (m_cachedLinkResource) {
- m_cachedLinkResource->removeClient(this);
- m_cachedLinkResource = 0;
- }
- m_cachedLinkResource = document.fetcher()->fetchLinkResource(type, linkRequest);
- if (m_cachedLinkResource)
- m_cachedLinkResource->addClient(this);
+ setResource(document.fetcher()->fetchLinkResource(type, linkRequest));
}
if (relAttribute.isLinkPrerender()) {
- if (!m_prerenderHandle) {
- m_prerenderHandle = document.prerenderer()->render(this, href);
- } else if (m_prerenderHandle->url() != href) {
- m_prerenderHandle->cancel();
- m_prerenderHandle = document.prerenderer()->render(this, href);
+ if (!m_prerender) {
+ m_prerender = PrerenderHandle::create(document, this, href);
+ } else if (m_prerender->url() != href) {
+ m_prerender->cancel();
+ m_prerender = PrerenderHandle::create(document, this, href);
}
- } else if (m_prerenderHandle) {
- m_prerenderHandle->cancel();
- m_prerenderHandle = 0;
+ } else if (m_prerender) {
+ m_prerender->cancel();
+ m_prerender.clear();
}
return true;
}
@@ -146,10 +135,9 @@ void LinkLoader::released()
{
// Only prerenders need treatment here; other links either use the Resource interface, or are notionally
// atomic (dns prefetch).
- if (m_prerenderHandle) {
- m_prerenderHandle->cancel();
- m_prerenderHandle->removeClient();
- m_prerenderHandle.clear();
+ if (m_prerender) {
+ m_prerender->cancel();
+ m_prerender.clear();
}
}
diff --git a/chromium/third_party/WebKit/Source/core/loader/LinkLoader.h b/chromium/third_party/WebKit/Source/core/loader/LinkLoader.h
index b0208609a20..4d1f72d7c95 100644
--- a/chromium/third_party/WebKit/Source/core/loader/LinkLoader.h
+++ b/chromium/third_party/WebKit/Source/core/loader/LinkLoader.h
@@ -33,19 +33,20 @@
#define LinkLoader_h
#include "core/fetch/ResourceClient.h"
-#include "core/fetch/ResourcePtr.h"
+#include "core/fetch/ResourceOwner.h"
#include "core/loader/LinkLoaderClient.h"
-#include "core/platform/PrerenderClient.h"
-#include "core/platform/Timer.h"
-#include "wtf/RefPtr.h"
+#include "platform/PrerenderClient.h"
+#include "platform/Timer.h"
+#include "wtf/OwnPtr.h"
namespace WebCore {
+class Document;
class LinkRelAttribute;
class PrerenderHandle;
// The LinkLoader can load link rel types icon, dns-prefetch, subresource, prefetch and prerender.
-class LinkLoader : public ResourceClient, public PrerenderClient {
+class LinkLoader : public ResourceOwner<Resource, ResourceClient>, public PrerenderClient {
public:
explicit LinkLoader(LinkLoaderClient*);
@@ -69,11 +70,10 @@ private:
LinkLoaderClient* m_client;
- ResourcePtr<Resource> m_cachedLinkResource;
Timer<LinkLoader> m_linkLoadTimer;
Timer<LinkLoader> m_linkLoadingErrorTimer;
- RefPtr<PrerenderHandle> m_prerenderHandle;
+ OwnPtr<PrerenderHandle> m_prerender;
};
}
diff --git a/chromium/third_party/WebKit/Source/core/loader/MixedContentChecker.cpp b/chromium/third_party/WebKit/Source/core/loader/MixedContentChecker.cpp
index ac812e0edf8..750f1308afc 100644
--- a/chromium/third_party/WebKit/Source/core/loader/MixedContentChecker.cpp
+++ b/chromium/third_party/WebKit/Source/core/loader/MixedContentChecker.cpp
@@ -32,10 +32,9 @@
#include "core/dom/Document.h"
#include "core/loader/FrameLoader.h"
#include "core/loader/FrameLoaderClient.h"
-#include "core/page/Frame.h"
-#include "core/page/Settings.h"
-#include "weborigin/SecurityOrigin.h"
-#include "wtf/text/WTFString.h"
+#include "core/frame/Frame.h"
+#include "core/frame/Settings.h"
+#include "platform/weborigin/SecurityOrigin.h"
namespace WebCore {
@@ -46,7 +45,7 @@ MixedContentChecker::MixedContentChecker(Frame* frame)
FrameLoaderClient* MixedContentChecker::client() const
{
- return m_frame->loader()->client();
+ return m_frame->loader().client();
}
// static
@@ -92,7 +91,8 @@ bool MixedContentChecker::canRunInsecureContent(SecurityOrigin* securityOrigin,
void MixedContentChecker::logWarning(bool allowed, const String& action, const KURL& target) const
{
String message = String(allowed ? "" : "[blocked] ") + "The page at '" + m_frame->document()->url().elidedString() + "' was loaded over HTTPS, but " + action + " insecure content from '" + target.elidedString() + "': this content should also be loaded over HTTPS.\n";
- m_frame->document()->addConsoleMessage(SecurityMessageSource, WarningMessageLevel, message);
+ MessageLevel messageLevel = allowed ? WarningMessageLevel : ErrorMessageLevel;
+ m_frame->document()->addConsoleMessage(SecurityMessageSource, messageLevel, message);
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/loader/NavigationAction.cpp b/chromium/third_party/WebKit/Source/core/loader/NavigationAction.cpp
index ffabc57d84a..b0cffda86eb 100644
--- a/chromium/third_party/WebKit/Source/core/loader/NavigationAction.cpp
+++ b/chromium/third_party/WebKit/Source/core/loader/NavigationAction.cpp
@@ -29,7 +29,7 @@
#include "config.h"
#include "core/loader/NavigationAction.h"
-#include "core/dom/MouseEvent.h"
+#include "core/events/MouseEvent.h"
#include "core/loader/FrameLoader.h"
namespace WebCore {
@@ -60,19 +60,14 @@ NavigationAction::NavigationAction(const ResourceRequest& resourceRequest, Frame
, m_type(navigationType(frameLoadType, isFormSubmission, event))
, m_event(event)
{
-}
-
-bool NavigationAction::specifiesNavigationPolicy(NavigationPolicy* policy) const
-{
- const MouseEvent* event = 0;
+ const MouseEvent* mouseEvent = 0;
if (m_type == NavigationTypeLinkClicked && m_event->isMouseEvent())
- event = toMouseEvent(m_event.get());
+ mouseEvent = toMouseEvent(m_event.get());
else if (m_type == NavigationTypeFormSubmitted && m_event && m_event->underlyingEvent() && m_event->underlyingEvent()->isMouseEvent())
- event = toMouseEvent(m_event->underlyingEvent());
+ mouseEvent = toMouseEvent(m_event->underlyingEvent());
- if (!event)
- return false;
- return navigationPolicyFromMouseEvent(event->button(), event->ctrlKey(), event->shiftKey(), event->altKey(), event->metaKey(), policy);
+ if (!mouseEvent || !navigationPolicyFromMouseEvent(mouseEvent->button(), mouseEvent->ctrlKey(), mouseEvent->shiftKey(), mouseEvent->altKey(), mouseEvent->metaKey(), &m_policy))
+ m_policy = NavigationPolicyCurrentTab;
}
}
diff --git a/chromium/third_party/WebKit/Source/core/loader/NavigationAction.h b/chromium/third_party/WebKit/Source/core/loader/NavigationAction.h
index 5ba25f33219..e50716bfe9c 100644
--- a/chromium/third_party/WebKit/Source/core/loader/NavigationAction.h
+++ b/chromium/third_party/WebKit/Source/core/loader/NavigationAction.h
@@ -29,11 +29,11 @@
#ifndef NavigationAction_h
#define NavigationAction_h
-#include "core/dom/Event.h"
+#include "core/events/Event.h"
#include "core/loader/FrameLoaderTypes.h"
#include "core/loader/NavigationPolicy.h"
-#include "core/platform/network/ResourceRequest.h"
-#include "weborigin/KURL.h"
+#include "platform/network/ResourceRequest.h"
+#include "platform/weborigin/KURL.h"
#include "wtf/Forward.h"
namespace WebCore {
@@ -46,13 +46,14 @@ namespace WebCore {
const ResourceRequest& resourceRequest() const { return m_resourceRequest; }
NavigationType type() const { return m_type; }
Event* event() const { return m_event.get(); }
-
- bool specifiesNavigationPolicy(NavigationPolicy*) const;
+ NavigationPolicy policy() const { return m_policy; }
+ bool shouldOpenInNewWindow() const { return m_policy != NavigationPolicyCurrentTab; }
private:
ResourceRequest m_resourceRequest;
NavigationType m_type;
RefPtr<Event> m_event;
+ NavigationPolicy m_policy;
};
}
diff --git a/chromium/third_party/WebKit/Source/core/loader/NavigationScheduler.cpp b/chromium/third_party/WebKit/Source/core/loader/NavigationScheduler.cpp
index 594667a6a91..e47437cc842 100644
--- a/chromium/third_party/WebKit/Source/core/loader/NavigationScheduler.cpp
+++ b/chromium/third_party/WebKit/Source/core/loader/NavigationScheduler.cpp
@@ -33,9 +33,7 @@
#include "core/loader/NavigationScheduler.h"
#include "bindings/v8/ScriptController.h"
-#include "core/dom/Event.h"
-#include "core/dom/UserGestureIndicator.h"
-#include "core/history/BackForwardController.h"
+#include "core/events/Event.h"
#include "core/html/HTMLFormElement.h"
#include "core/inspector/InspectorInstrumentation.h"
#include "core/loader/DocumentLoader.h"
@@ -43,9 +41,12 @@
#include "core/loader/FormSubmission.h"
#include "core/loader/FrameLoadRequest.h"
#include "core/loader/FrameLoader.h"
+#include "core/loader/FrameLoaderClient.h"
#include "core/loader/FrameLoaderStateMachine.h"
-#include "core/page/Frame.h"
+#include "core/frame/Frame.h"
+#include "core/page/BackForwardClient.h"
#include "core/page/Page.h"
+#include "platform/UserGestureIndicator.h"
#include "wtf/CurrentTime.h"
namespace WebCore {
@@ -59,7 +60,7 @@ public:
: m_delay(delay)
, m_lockBackForwardList(lockBackForwardList)
, m_isLocationChange(isLocationChange)
- , m_wasUserGesture(ScriptController::processingUserGesture())
+ , m_wasUserGesture(UserGestureIndicator::processingUserGesture())
{
if (m_wasUserGesture)
m_userGestureToken = UserGestureIndicator::currentToken();
@@ -69,11 +70,9 @@ public:
virtual void fire(Frame*) = 0;
virtual bool shouldStartTimer(Frame*) { return true; }
- virtual void didStartTimer(Frame*, Timer<NavigationScheduler>*) { }
double delay() const { return m_delay; }
bool lockBackForwardList() const { return m_lockBackForwardList; }
- void setLockBackForwardList(bool lockBackForwardList) { m_lockBackForwardList = lockBackForwardList; }
bool isLocationChange() const { return m_isLocationChange; }
PassOwnPtr<UserGestureIndicator> createUserGestureIndicator()
{
@@ -97,88 +96,75 @@ private:
class ScheduledURLNavigation : public ScheduledNavigation {
protected:
- ScheduledURLNavigation(double delay, SecurityOrigin* securityOrigin, const String& url, const String& referrer, bool lockBackForwardList, bool isLocationChange)
+ ScheduledURLNavigation(double delay, Document* originDocument, const String& url, const String& referrer, bool lockBackForwardList, bool isLocationChange)
: ScheduledNavigation(delay, lockBackForwardList, isLocationChange)
- , m_securityOrigin(securityOrigin)
+ , m_originDocument(originDocument)
, m_url(url)
, m_referrer(referrer)
- , m_haveToldClient(false)
{
}
virtual void fire(Frame* frame)
{
OwnPtr<UserGestureIndicator> gestureIndicator = createUserGestureIndicator();
- FrameLoadRequest request(m_securityOrigin.get(), ResourceRequest(KURL(ParsedURLString, m_url), m_referrer), "_self");
+ FrameLoadRequest request(m_originDocument.get(), ResourceRequest(KURL(ParsedURLString, m_url), m_referrer), "_self");
request.setLockBackForwardList(lockBackForwardList());
- request.setClientRedirect(true);
- frame->loader()->load(request);
+ request.setClientRedirect(ClientRedirect);
+ frame->loader().load(request);
}
- virtual void didStartTimer(Frame* frame, Timer<NavigationScheduler>* timer)
- {
- if (m_haveToldClient)
- return;
- m_haveToldClient = true;
-
- OwnPtr<UserGestureIndicator> gestureIndicator = createUserGestureIndicator();
- if (frame->loader()->history()->currentItemShouldBeReplaced())
- setLockBackForwardList(true);
- }
-
- SecurityOrigin* securityOrigin() const { return m_securityOrigin.get(); }
+ Document* originDocument() const { return m_originDocument.get(); }
String url() const { return m_url; }
String referrer() const { return m_referrer; }
private:
- RefPtr<SecurityOrigin> m_securityOrigin;
+ RefPtr<Document> m_originDocument;
String m_url;
String m_referrer;
- bool m_haveToldClient;
};
class ScheduledRedirect : public ScheduledURLNavigation {
public:
- ScheduledRedirect(double delay, SecurityOrigin* securityOrigin, const String& url, bool lockBackForwardList)
- : ScheduledURLNavigation(delay, securityOrigin, url, String(), lockBackForwardList, false)
+ ScheduledRedirect(double delay, Document* originDocument, const String& url, bool lockBackForwardList)
+ : ScheduledURLNavigation(delay, originDocument, url, String(), lockBackForwardList, false)
{
clearUserGesture();
}
- virtual bool shouldStartTimer(Frame* frame) { return frame->loader()->allAncestorsAreComplete(); }
+ virtual bool shouldStartTimer(Frame* frame) { return frame->loader().allAncestorsAreComplete(); }
virtual void fire(Frame* frame)
{
OwnPtr<UserGestureIndicator> gestureIndicator = createUserGestureIndicator();
- FrameLoadRequest request(securityOrigin(), ResourceRequest(KURL(ParsedURLString, url()), referrer()), "_self");
+ FrameLoadRequest request(originDocument(), ResourceRequest(KURL(ParsedURLString, url()), referrer()), "_self");
request.setLockBackForwardList(lockBackForwardList());
if (equalIgnoringFragmentIdentifier(frame->document()->url(), request.resourceRequest().url()))
request.resourceRequest().setCachePolicy(ReloadIgnoringCacheData);
- request.setClientRedirect(true);
- frame->loader()->load(request);
+ request.setClientRedirect(ClientRedirect);
+ frame->loader().load(request);
}
};
class ScheduledLocationChange : public ScheduledURLNavigation {
public:
- ScheduledLocationChange(SecurityOrigin* securityOrigin, const String& url, const String& referrer, bool lockBackForwardList)
- : ScheduledURLNavigation(0.0, securityOrigin, url, referrer, lockBackForwardList, true) { }
+ ScheduledLocationChange(Document* originDocument, const String& url, const String& referrer, bool lockBackForwardList)
+ : ScheduledURLNavigation(0.0, originDocument, url, referrer, lockBackForwardList, true) { }
};
class ScheduledRefresh : public ScheduledURLNavigation {
public:
- ScheduledRefresh(SecurityOrigin* securityOrigin, const String& url, const String& referrer)
- : ScheduledURLNavigation(0.0, securityOrigin, url, referrer, true, true)
+ ScheduledRefresh(Document* originDocument, const String& url, const String& referrer)
+ : ScheduledURLNavigation(0.0, originDocument, url, referrer, true, true)
{
}
virtual void fire(Frame* frame)
{
OwnPtr<UserGestureIndicator> gestureIndicator = createUserGestureIndicator();
- FrameLoadRequest request(securityOrigin(), ResourceRequest(KURL(ParsedURLString, url()), referrer(), ReloadIgnoringCacheData), "_self");
+ FrameLoadRequest request(originDocument(), ResourceRequest(KURL(ParsedURLString, url()), referrer(), ReloadIgnoringCacheData), "_self");
request.setLockBackForwardList(lockBackForwardList());
- request.setClientRedirect(true);
- frame->loader()->load(request);
+ request.setClientRedirect(ClientRedirect);
+ frame->loader().load(request);
}
};
@@ -195,16 +181,16 @@ public:
OwnPtr<UserGestureIndicator> gestureIndicator = createUserGestureIndicator();
if (!m_historySteps) {
- FrameLoadRequest frameRequest(frame->document()->securityOrigin(), ResourceRequest(frame->document()->url()));
+ FrameLoadRequest frameRequest(frame->document(), ResourceRequest(frame->document()->url()));
frameRequest.setLockBackForwardList(lockBackForwardList());
// Special case for go(0) from a frame -> reload only the frame
// To follow Firefox and IE's behavior, history reload can only navigate the self frame.
- frame->loader()->load(frameRequest);
+ frame->loader().load(frameRequest);
return;
}
// go(i!=0) from a frame navigates into the history of the frame only,
// in both IE and NS (but not in Mozilla). We can't easily do that.
- frame->page()->backForward().goBackOrForward(m_historySteps);
+ frame->page()->mainFrame()->loader().client()->navigateBackForward(m_historySteps);
}
private:
@@ -214,9 +200,8 @@ private:
class ScheduledFormSubmission : public ScheduledNavigation {
public:
ScheduledFormSubmission(PassRefPtr<FormSubmission> submission, bool lockBackForwardList)
- : ScheduledNavigation(0, lockBackForwardList, submission->target().isNull())
+ : ScheduledNavigation(0, lockBackForwardList, true)
, m_submission(submission)
- , m_haveToldClient(false)
{
ASSERT(m_submission->state());
}
@@ -224,23 +209,12 @@ public:
virtual void fire(Frame* frame)
{
OwnPtr<UserGestureIndicator> gestureIndicator = createUserGestureIndicator();
- FrameLoadRequest frameRequest(m_submission->state()->sourceDocument()->securityOrigin());
+ FrameLoadRequest frameRequest(m_submission->state()->sourceDocument());
m_submission->populateFrameLoadRequest(frameRequest);
frameRequest.setLockBackForwardList(lockBackForwardList());
frameRequest.setTriggeringEvent(m_submission->event());
frameRequest.setFormState(m_submission->state());
- frame->loader()->load(frameRequest);
- }
-
- virtual void didStartTimer(Frame* frame, Timer<NavigationScheduler>* timer)
- {
- if (m_haveToldClient)
- return;
- m_haveToldClient = true;
-
- OwnPtr<UserGestureIndicator> gestureIndicator = createUserGestureIndicator();
- if (frame->loader()->history()->currentItemShouldBeReplaced())
- setLockBackForwardList(true);
+ frame->loader().load(frameRequest);
}
virtual bool isForm() const { return true; }
@@ -248,7 +222,6 @@ public:
private:
RefPtr<FormSubmission> m_submission;
- bool m_haveToldClient;
};
NavigationScheduler::NavigationScheduler(Frame* frame)
@@ -272,7 +245,6 @@ void NavigationScheduler::clear()
InspectorInstrumentation::frameClearedScheduledNavigation(m_frame);
m_timer.stop();
m_redirect.clear();
- m_additionalFormSubmissions.clear();
}
inline bool NavigationScheduler::shouldScheduleNavigation() const
@@ -296,23 +268,31 @@ void NavigationScheduler::scheduleRedirect(double delay, const String& url)
// We want a new back/forward list item if the refresh timeout is > 1 second.
if (!m_redirect || delay <= m_redirect->delay())
- schedule(adoptPtr(new ScheduledRedirect(delay, m_frame->document()->securityOrigin(), url, delay <= 1)));
+ schedule(adoptPtr(new ScheduledRedirect(delay, m_frame->document(), url, delay <= 1)));
}
bool NavigationScheduler::mustLockBackForwardList(Frame* targetFrame)
{
// Non-user navigation before the page has finished firing onload should not create a new back/forward item.
// See https://webkit.org/b/42861 for the original motivation for this.
- if (!ScriptController::processingUserGesture() && !targetFrame->document()->loadEventFinished())
+ if (!UserGestureIndicator::processingUserGesture() && !targetFrame->document()->loadEventFinished())
+ return true;
+
+ // From the HTML5 spec for location.assign():
+ // "If the browsing context's session history contains only one Document,
+ // and that was the about:blank Document created when the browsing context
+ // was created, then the navigation must be done with replacement enabled."
+ if (!targetFrame->loader().stateMachine()->committedMultipleRealLoads()
+ && equalIgnoringCase(targetFrame->document()->url(), blankURL()))
return true;
// Navigation of a subframe during loading of an ancestor frame does not create a new back/forward item.
// The definition of "during load" is any time before all handlers for the load event have been run.
// See https://bugs.webkit.org/show_bug.cgi?id=14957 for the original motivation for this.
- return targetFrame->tree()->parent() && !targetFrame->tree()->parent()->loader()->allAncestorsAreComplete();
+ return targetFrame->tree().parent() && !targetFrame->tree().parent()->loader().allAncestorsAreComplete();
}
-void NavigationScheduler::scheduleLocationChange(SecurityOrigin* securityOrigin, const String& url, const String& referrer, bool lockBackForwardList)
+void NavigationScheduler::scheduleLocationChange(Document* originDocument, const String& url, const String& referrer, bool lockBackForwardList)
{
if (!shouldScheduleNavigation(url))
return;
@@ -321,36 +301,27 @@ void NavigationScheduler::scheduleLocationChange(SecurityOrigin* securityOrigin,
lockBackForwardList = lockBackForwardList || mustLockBackForwardList(m_frame);
- FrameLoader* loader = m_frame->loader();
-
// If the URL we're going to navigate to is the same as the current one, except for the
// fragment part, we don't need to schedule the location change. We'll skip this
// optimization for cross-origin navigations to minimize the navigator's ability to
// execute timing attacks.
- if (securityOrigin->canAccess(m_frame->document()->securityOrigin())) {
+ if (originDocument->securityOrigin()->canAccess(m_frame->document()->securityOrigin())) {
KURL parsedURL(ParsedURLString, url);
if (parsedURL.hasFragmentIdentifier() && equalIgnoringFragmentIdentifier(m_frame->document()->url(), parsedURL)) {
- FrameLoadRequest request(securityOrigin, ResourceRequest(m_frame->document()->completeURL(url), referrer), "_self");
+ FrameLoadRequest request(originDocument, ResourceRequest(m_frame->document()->completeURL(url), referrer), "_self");
request.setLockBackForwardList(lockBackForwardList);
- request.setClientRedirect(true);
- loader->load(request);
+ request.setClientRedirect(ClientRedirect);
+ m_frame->loader().load(request);
return;
}
}
- schedule(adoptPtr(new ScheduledLocationChange(securityOrigin, url, referrer, lockBackForwardList)));
+ schedule(adoptPtr(new ScheduledLocationChange(originDocument, url, referrer, lockBackForwardList)));
}
void NavigationScheduler::scheduleFormSubmission(PassRefPtr<FormSubmission> submission)
{
ASSERT(m_frame->page());
- if (m_redirect && m_redirect->isForm()) {
- if (submission->target() != static_cast<ScheduledFormSubmission*>(m_redirect.get())->submission()->target()) {
- const String& target = submission->target().isNull() ? "" : submission->target();
- m_additionalFormSubmissions.add(target, adoptPtr(new ScheduledFormSubmission(submission, mustLockBackForwardList(m_frame))));
- return;
- }
- }
schedule(adoptPtr(new ScheduledFormSubmission(submission, mustLockBackForwardList(m_frame))));
}
@@ -362,7 +333,7 @@ void NavigationScheduler::scheduleRefresh()
if (url.isEmpty())
return;
- schedule(adoptPtr(new ScheduledRefresh(m_frame->document()->securityOrigin(), url.string(), m_frame->loader()->outgoingReferrer())));
+ schedule(adoptPtr(new ScheduledRefresh(m_frame->document(), url.string(), m_frame->document()->outgoingReferrer())));
}
void NavigationScheduler::scheduleHistoryNavigation(int steps)
@@ -372,8 +343,8 @@ void NavigationScheduler::scheduleHistoryNavigation(int steps)
// Invalid history navigations (such as history.forward() during a new load) have the side effect of cancelling any scheduled
// redirects. We also avoid the possibility of cancelling the current load by avoiding the scheduled redirection altogether.
- BackForwardController& backForward = m_frame->page()->backForward();
- if (steps > backForward.forwardCount() || -steps > backForward.backCount()) {
+ BackForwardClient& backForward = m_frame->page()->backForward();
+ if (steps > backForward.forwardListCount() || -steps > backForward.backListCount()) {
cancel();
return;
}
@@ -394,15 +365,7 @@ void NavigationScheduler::timerFired(Timer<NavigationScheduler>*)
RefPtr<Frame> protect(m_frame);
OwnPtr<ScheduledNavigation> redirect(m_redirect.release());
- HashMap<String, OwnPtr<ScheduledNavigation> > additionalFormSubmissions;
- additionalFormSubmissions.swap(m_additionalFormSubmissions);
redirect->fire(m_frame);
- while (!additionalFormSubmissions.isEmpty()) {
- HashMap<String, OwnPtr<ScheduledNavigation> >::iterator it = additionalFormSubmissions.begin();
- OwnPtr<ScheduledNavigation> formSubmission = it->value.release();
- additionalFormSubmissions.remove(it);
- formSubmission->fire(m_frame);
- }
InspectorInstrumentation::frameClearedScheduledNavigation(m_frame);
}
@@ -426,7 +389,6 @@ void NavigationScheduler::startTimer()
return;
m_timer.startOneShot(m_redirect->delay());
- m_redirect->didStartTimer(m_frame, &m_timer);
InspectorInstrumentation::frameScheduledNavigation(m_frame, m_redirect->delay());
}
@@ -436,7 +398,6 @@ void NavigationScheduler::cancel()
InspectorInstrumentation::frameClearedScheduledNavigation(m_frame);
m_timer.stop();
m_redirect.clear();
- m_additionalFormSubmissions.clear();
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/loader/NavigationScheduler.h b/chromium/third_party/WebKit/Source/core/loader/NavigationScheduler.h
index 07b610d0a7b..b10031e427c 100644
--- a/chromium/third_party/WebKit/Source/core/loader/NavigationScheduler.h
+++ b/chromium/third_party/WebKit/Source/core/loader/NavigationScheduler.h
@@ -31,7 +31,7 @@
#ifndef NavigationScheduler_h
#define NavigationScheduler_h
-#include "core/platform/Timer.h"
+#include "platform/Timer.h"
#include "wtf/Forward.h"
#include "wtf/HashMap.h"
#include "wtf/Noncopyable.h"
@@ -42,10 +42,10 @@
namespace WebCore {
+class Document;
class FormSubmission;
class Frame;
class ScheduledNavigation;
-class SecurityOrigin;
class NavigationDisablerForBeforeUnload {
WTF_MAKE_NONCOPYABLE(NavigationDisablerForBeforeUnload);
@@ -76,7 +76,7 @@ public:
bool locationChangePending();
void scheduleRedirect(double delay, const String& url);
- void scheduleLocationChange(SecurityOrigin*, const String& url, const String& referrer, bool lockBackForwardList = true);
+ void scheduleLocationChange(Document*, const String& url, const String& referrer, bool lockBackForwardList = true);
void scheduleFormSubmission(PassRefPtr<FormSubmission>);
void scheduleRefresh();
void scheduleHistoryNavigation(int steps);
@@ -98,7 +98,6 @@ private:
Frame* m_frame;
Timer<NavigationScheduler> m_timer;
OwnPtr<ScheduledNavigation> m_redirect;
- HashMap<String, OwnPtr<ScheduledNavigation> > m_additionalFormSubmissions;
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/loader/PingLoader.cpp b/chromium/third_party/WebKit/Source/core/loader/PingLoader.cpp
index b9253d1a197..410143d86a4 100644
--- a/chromium/third_party/WebKit/Source/core/loader/PingLoader.cpp
+++ b/chromium/third_party/WebKit/Source/core/loader/PingLoader.cpp
@@ -33,21 +33,20 @@
#include "core/loader/PingLoader.h"
#include "core/dom/Document.h"
+#include "core/frame/Frame.h"
#include "core/inspector/InspectorInstrumentation.h"
#include "core/loader/FrameLoader.h"
#include "core/loader/FrameLoaderClient.h"
#include "core/loader/UniqueIdentifier.h"
-#include "core/page/Frame.h"
-#include "core/platform/chromium/support/WrappedResourceRequest.h"
-#include "core/platform/network/FormData.h"
-#include "core/platform/network/ResourceRequest.h"
-#include "core/platform/network/ResourceResponse.h"
+#include "platform/exported/WrappedResourceRequest.h"
+#include "platform/network/FormData.h"
+#include "platform/network/ResourceRequest.h"
+#include "platform/network/ResourceResponse.h"
+#include "platform/weborigin/SecurityOrigin.h"
+#include "platform/weborigin/SecurityPolicy.h"
#include "public/platform/Platform.h"
#include "public/platform/WebURLLoader.h"
-#include "weborigin/SecurityOrigin.h"
-#include "weborigin/SecurityPolicy.h"
#include "wtf/OwnPtr.h"
-#include "wtf/UnusedParam.h"
namespace WebCore {
@@ -59,38 +58,37 @@ void PingLoader::loadImage(Frame* frame, const KURL& url)
}
ResourceRequest request(url);
- request.setTargetType(ResourceRequest::TargetIsImage);
+ request.setTargetType(ResourceRequest::TargetIsPing);
request.setHTTPHeaderField("Cache-Control", "max-age=0");
- String referrer = SecurityPolicy::generateReferrerHeader(frame->document()->referrerPolicy(), request.url(), frame->loader()->outgoingReferrer());
+ String referrer = SecurityPolicy::generateReferrerHeader(frame->document()->referrerPolicy(), request.url(), frame->document()->outgoingReferrer());
if (!referrer.isEmpty())
request.setHTTPReferrer(referrer);
- frame->loader()->addExtraFieldsToRequest(request);
+ frame->loader().addExtraFieldsToRequest(request);
OwnPtr<PingLoader> pingLoader = adoptPtr(new PingLoader(frame, request));
// Leak the ping loader, since it will kill itself as soon as it receives a response.
- PingLoader* leakedPingLoader = pingLoader.leakPtr();
- UNUSED_PARAM(leakedPingLoader);
+ PingLoader* ALLOW_UNUSED leakedPingLoader = pingLoader.leakPtr();
}
// http://www.whatwg.org/specs/web-apps/current-work/multipage/links.html#hyperlink-auditing
void PingLoader::sendPing(Frame* frame, const KURL& pingURL, const KURL& destinationURL)
{
ResourceRequest request(pingURL);
- request.setTargetType(ResourceRequest::TargetIsSubresource);
+ request.setTargetType(ResourceRequest::TargetIsPing);
request.setHTTPMethod("POST");
request.setHTTPContentType("text/ping");
request.setHTTPBody(FormData::create("PING"));
request.setHTTPHeaderField("Cache-Control", "max-age=0");
- frame->loader()->addExtraFieldsToRequest(request);
+ frame->loader().addExtraFieldsToRequest(request);
SecurityOrigin* sourceOrigin = frame->document()->securityOrigin();
RefPtr<SecurityOrigin> pingOrigin = SecurityOrigin::create(pingURL);
FrameLoader::addHTTPOriginIfNeeded(request, sourceOrigin->toString());
request.setHTTPHeaderField("Ping-To", destinationURL.string());
- if (!SecurityPolicy::shouldHideReferrer(pingURL, frame->loader()->outgoingReferrer())) {
+ if (!SecurityPolicy::shouldHideReferrer(pingURL, frame->document()->outgoingReferrer())) {
request.setHTTPHeaderField("Ping-From", frame->document()->url().string());
if (!sourceOrigin->isSameSchemeHostPort(pingOrigin.get())) {
- String referrer = SecurityPolicy::generateReferrerHeader(frame->document()->referrerPolicy(), pingURL, frame->loader()->outgoingReferrer());
+ String referrer = SecurityPolicy::generateReferrerHeader(frame->document()->referrerPolicy(), pingURL, frame->document()->outgoingReferrer());
if (!referrer.isEmpty())
request.setHTTPReferrer(referrer);
}
@@ -98,8 +96,7 @@ void PingLoader::sendPing(Frame* frame, const KURL& pingURL, const KURL& destina
OwnPtr<PingLoader> pingLoader = adoptPtr(new PingLoader(frame, request));
// Leak the ping loader, since it will kill itself as soon as it receives a response.
- PingLoader* leakedPingLoader = pingLoader.leakPtr();
- UNUSED_PARAM(leakedPingLoader);
+ PingLoader* ALLOW_UNUSED leakedPingLoader = pingLoader.leakPtr();
}
void PingLoader::sendViolationReport(Frame* frame, const KURL& reportURL, PassRefPtr<FormData> report, ViolationReportType type)
@@ -109,31 +106,30 @@ void PingLoader::sendViolationReport(Frame* frame, const KURL& reportURL, PassRe
request.setHTTPMethod("POST");
request.setHTTPContentType(type == ContentSecurityPolicyViolationReport ? "application/csp-report" : "application/json");
request.setHTTPBody(report);
- frame->loader()->addExtraFieldsToRequest(request);
+ frame->loader().addExtraFieldsToRequest(request);
- String referrer = SecurityPolicy::generateReferrerHeader(frame->document()->referrerPolicy(), reportURL, frame->loader()->outgoingReferrer());
+ String referrer = SecurityPolicy::generateReferrerHeader(frame->document()->referrerPolicy(), reportURL, frame->document()->outgoingReferrer());
if (!referrer.isEmpty())
request.setHTTPReferrer(referrer);
OwnPtr<PingLoader> pingLoader = adoptPtr(new PingLoader(frame, request, SecurityOrigin::create(reportURL)->isSameSchemeHostPort(frame->document()->securityOrigin()) ? AllowStoredCredentials : DoNotAllowStoredCredentials));
// Leak the ping loader, since it will kill itself as soon as it receives a response.
- PingLoader* leakedPingLoader = pingLoader.leakPtr();
- UNUSED_PARAM(leakedPingLoader);
+ PingLoader* ALLOW_UNUSED leakedPingLoader = pingLoader.leakPtr();
}
PingLoader::PingLoader(Frame* frame, ResourceRequest& request, StoredCredentials credentialsAllowed)
: m_timeout(this, &PingLoader::timeout)
{
- frame->loader()->client()->didDispatchPingLoader(request.url());
+ frame->loader().client()->didDispatchPingLoader(request.url());
unsigned long identifier = createUniqueIdentifier();
- m_loader = adoptPtr(WebKit::Platform::current()->createURLLoader());
+ m_loader = adoptPtr(blink::Platform::current()->createURLLoader());
ASSERT(m_loader);
- WebKit::WrappedResourceRequest wrappedRequest(request);
+ blink::WrappedResourceRequest wrappedRequest(request);
wrappedRequest.setAllowStoredCredentials(credentialsAllowed == AllowStoredCredentials);
m_loader->loadAsynchronously(wrappedRequest, this);
- InspectorInstrumentation::continueAfterPingLoader(frame, identifier, frame->loader()->activeDocumentLoader(), request, ResourceResponse());
+ InspectorInstrumentation::continueAfterPingLoader(frame, identifier, frame->loader().activeDocumentLoader(), request, ResourceResponse());
// If the server never responds, FrameLoader won't be able to cancel this load and
// we'll sit here waiting forever. Set a very generous timeout, just in case.
diff --git a/chromium/third_party/WebKit/Source/core/loader/PingLoader.h b/chromium/third_party/WebKit/Source/core/loader/PingLoader.h
index 80f7070aef7..e22f84caaf4 100644
--- a/chromium/third_party/WebKit/Source/core/loader/PingLoader.h
+++ b/chromium/third_party/WebKit/Source/core/loader/PingLoader.h
@@ -33,7 +33,7 @@
#define PingLoader_h
#include "core/fetch/ResourceLoaderOptions.h"
-#include "core/platform/Timer.h"
+#include "platform/Timer.h"
#include "public/platform/WebURLLoaderClient.h"
#include "wtf/Noncopyable.h"
#include "wtf/RefPtr.h"
@@ -53,7 +53,7 @@ class ResourceResponse;
// to allow the load to live long enough to ensure the message was actually sent.
// Therefore, as soon as a callback is received from the ResourceHandle, this class
// will cancel the load and delete itself.
-class PingLoader : private WebKit::WebURLLoaderClient {
+class PingLoader : private blink::WebURLLoaderClient {
WTF_MAKE_NONCOPYABLE(PingLoader); WTF_MAKE_FAST_ALLOCATED;
public:
enum ViolationReportType {
@@ -70,13 +70,13 @@ public:
private:
PingLoader(Frame*, ResourceRequest&, StoredCredentials = AllowStoredCredentials);
- virtual void didReceiveResponse(WebKit::WebURLLoader*, const WebKit::WebURLResponse&) OVERRIDE { delete this; }
- virtual void didReceiveData(WebKit::WebURLLoader*, const char*, int, int) OVERRIDE { delete this; }
- virtual void didFinishLoading(WebKit::WebURLLoader*, double) OVERRIDE { delete this; }
- virtual void didFail(WebKit::WebURLLoader*, const WebKit::WebURLError&) OVERRIDE { delete this; }
+ virtual void didReceiveResponse(blink::WebURLLoader*, const blink::WebURLResponse&) OVERRIDE { delete this; }
+ virtual void didReceiveData(blink::WebURLLoader*, const char*, int, int) OVERRIDE { delete this; }
+ virtual void didFinishLoading(blink::WebURLLoader*, double) OVERRIDE { delete this; }
+ virtual void didFail(blink::WebURLLoader*, const blink::WebURLError&) OVERRIDE { delete this; }
void timeout(Timer<PingLoader>*) { delete this; }
- OwnPtr<WebKit::WebURLLoader> m_loader;
+ OwnPtr<blink::WebURLLoader> m_loader;
Timer<PingLoader> m_timeout;
};
diff --git a/chromium/third_party/WebKit/Source/core/loader/PrerenderHandle.cpp b/chromium/third_party/WebKit/Source/core/loader/PrerenderHandle.cpp
new file mode 100644
index 00000000000..763506ab77a
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/loader/PrerenderHandle.cpp
@@ -0,0 +1,108 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/loader/PrerenderHandle.h"
+
+#include "core/dom/Document.h"
+#include "core/frame/Frame.h"
+#include "core/loader/FrameLoader.h"
+#include "core/loader/PrerendererClient.h"
+#include "platform/Prerender.h"
+#include "platform/weborigin/ReferrerPolicy.h"
+#include "platform/weborigin/SecurityPolicy.h"
+
+namespace WebCore {
+
+// static
+PassOwnPtr<PrerenderHandle> PrerenderHandle::create(Document& document, PrerenderClient* client, const KURL& url)
+{
+ // Prerenders are unlike requests in most ways (for instance, they pass down fragments, and they don't return data),
+ // but they do have referrers.
+ const ReferrerPolicy referrerPolicy = document.referrerPolicy();
+
+ if (!document.frame())
+ return PassOwnPtr<PrerenderHandle>();
+
+ const String referrer = SecurityPolicy::generateReferrerHeader(referrerPolicy, url, document.outgoingReferrer());
+
+ RefPtr<Prerender> prerender = Prerender::create(client, url, referrer, referrerPolicy);
+
+ PrerendererClient* prerendererClient = PrerendererClient::from(document.page());
+ if (prerendererClient)
+ prerendererClient->willAddPrerender(prerender.get());
+ prerender->add();
+
+ return adoptPtr(new PrerenderHandle(document, prerender.release()));
+}
+
+PrerenderHandle::PrerenderHandle(Document& document, PassRefPtr<Prerender> prerender)
+ : DocumentLifecycleObserver(&document)
+ , m_prerender(prerender)
+{
+}
+
+PrerenderHandle::~PrerenderHandle()
+{
+ if (m_prerender)
+ detach();
+}
+
+void PrerenderHandle::cancel()
+{
+ // Avoid both abandoning and canceling the same prerender. In the abandon case, the LinkLoader cancels the
+ // PrerenderHandle as the Document is destroyed, even through the DocumentLifecycleObserver has already abandoned
+ // it.
+ if (!m_prerender)
+ return;
+ m_prerender->cancel();
+ detach();
+}
+
+const KURL& PrerenderHandle::url() const
+{
+ return m_prerender->url();
+}
+
+void PrerenderHandle::documentWasDetached()
+{
+ ASSERT(m_prerender);
+ m_prerender->abandon();
+ detach();
+}
+
+
+void PrerenderHandle::detach()
+{
+ m_prerender->removeClient();
+ m_prerender.clear();
+}
+
+}
diff --git a/chromium/third_party/WebKit/Source/core/loader/PrerenderHandle.h b/chromium/third_party/WebKit/Source/core/loader/PrerenderHandle.h
new file mode 100644
index 00000000000..2adc058b85b
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/loader/PrerenderHandle.h
@@ -0,0 +1,68 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef PrerenderHandle_h
+#define PrerenderHandle_h
+
+#include "core/dom/DocumentLifecycleObserver.h"
+#include "platform/weborigin/KURL.h"
+#include "wtf/Noncopyable.h"
+#include "wtf/PassOwnPtr.h"
+#include "wtf/PassRefPtr.h"
+
+namespace WebCore {
+
+class Document;
+class Prerender;
+class PrerenderClient;
+
+class PrerenderHandle : public DocumentLifecycleObserver {
+ WTF_MAKE_NONCOPYABLE(PrerenderHandle);
+public:
+ static PassOwnPtr<PrerenderHandle> create(Document&, PrerenderClient*, const KURL&);
+
+ virtual ~PrerenderHandle();
+
+ void cancel();
+ const KURL& url() const;
+
+ // From DocumentLifecycleObserver:
+ virtual void documentWasDetached() OVERRIDE;
+private:
+ PrerenderHandle(Document&, PassRefPtr<Prerender>);
+
+ void detach();
+
+ RefPtr<Prerender> m_prerender;
+};
+
+}
+
+#endif // PrerenderHandle_h
diff --git a/chromium/third_party/WebKit/Source/core/loader/Prerenderer.cpp b/chromium/third_party/WebKit/Source/core/loader/Prerenderer.cpp
deleted file mode 100644
index 75f454d2319..00000000000
--- a/chromium/third_party/WebKit/Source/core/loader/Prerenderer.cpp
+++ /dev/null
@@ -1,144 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-#include "config.h"
-#include "core/loader/Prerenderer.h"
-
-#include "core/dom/Document.h"
-#include "core/loader/FrameLoader.h"
-#include "core/loader/PrerendererClient.h"
-#include "core/page/Frame.h"
-#include "core/platform/PrerenderHandle.h"
-#include "weborigin/ReferrerPolicy.h"
-#include "weborigin/SecurityPolicy.h"
-
-#include "wtf/PassOwnPtr.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefPtr.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-// static
-PassOwnPtr<Prerenderer> Prerenderer::create(Document* document)
-{
- Prerenderer* prerenderer = new Prerenderer(document);
- prerenderer->suspendIfNeeded();
- return adoptPtr(prerenderer);
-}
-
-Prerenderer::Prerenderer(Document* document)
- : ActiveDOMObject(document)
- , m_initializedClient(false)
- , m_client(0)
-{
-}
-
-Prerenderer::~Prerenderer()
-{
-}
-
-PassRefPtr<PrerenderHandle> Prerenderer::render(PrerenderClient* prerenderClient, const KURL& url)
-{
- // Prerenders are unlike requests in most ways (for instance, they pass down fragments, and they don't return data),
- // but they do have referrers.
- const ReferrerPolicy referrerPolicy = document()->referrerPolicy();
-
- if (!document()->frame())
- return 0;
-
- const String referrer = SecurityPolicy::generateReferrerHeader(referrerPolicy, url, document()->frame()->loader()->outgoingReferrer());
-
- RefPtr<PrerenderHandle> prerenderHandle = PrerenderHandle::create(prerenderClient, url, referrer, referrerPolicy);
-
- if (client())
- client()->willAddPrerender(prerenderHandle.get());
- prerenderHandle->add();
-
- // FIXME: This handle isn't released until page unload, but it may be canceled before then. It should be released in that case.
- m_activeHandles.append(prerenderHandle);
- return prerenderHandle;
-}
-
-void Prerenderer::stop()
-{
- while (!m_activeHandles.isEmpty()) {
- RefPtr<PrerenderHandle> handle = m_activeHandles[0].release();
- m_activeHandles.remove(0);
- handle->abandon();
- }
- while (!m_suspendedHandles.isEmpty()) {
- RefPtr<PrerenderHandle> handle = m_suspendedHandles[0].release();
- m_suspendedHandles.remove(0);
- handle->abandon();
- }
-}
-
-void Prerenderer::suspend(ReasonForSuspension reason)
-{
- if (reason == DocumentWillBecomeInactive) {
- while (!m_activeHandles.isEmpty()) {
- RefPtr<PrerenderHandle> handle = m_activeHandles[0].release();
- m_activeHandles.remove(0);
- handle->suspend();
- m_suspendedHandles.append(handle);
- }
- }
-}
-
-void Prerenderer::resume()
-{
- while (!m_suspendedHandles.isEmpty()) {
- RefPtr<PrerenderHandle> handle = m_suspendedHandles[0].release();
- m_suspendedHandles.remove(0);
- handle->resume();
- m_activeHandles.append(handle);
- }
-}
-
-Document* Prerenderer::document()
-{
- ASSERT(scriptExecutionContext()->isDocument());
- return toDocument(scriptExecutionContext());
-}
-
-PrerendererClient* Prerenderer::client()
-{
- if (!m_initializedClient) {
- // We can't initialize the client in our contructor, because the platform might not have
- // provided our supplement by then.
- m_initializedClient = true;
- m_client = PrerendererClient::from(document()->page());
- }
- return m_client;
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/loader/Prerenderer.h b/chromium/third_party/WebKit/Source/core/loader/Prerenderer.h
deleted file mode 100644
index a7545652f2a..00000000000
--- a/chromium/third_party/WebKit/Source/core/loader/Prerenderer.h
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-#ifndef Prerenderer_h
-#define Prerenderer_h
-
-#include "core/dom/ActiveDOMObject.h"
-#include "weborigin/KURL.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefPtr.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-class Document;
-class PrerenderClient;
-class PrerenderHandle;
-class PrerendererClient;
-class Page;
-
-class Prerenderer : public ActiveDOMObject {
- WTF_MAKE_NONCOPYABLE(Prerenderer);
-public:
- virtual ~Prerenderer();
-
- PassRefPtr<PrerenderHandle> render(PrerenderClient*, const KURL&);
-
- static PassOwnPtr<Prerenderer> create(Document*);
-
- // From ActiveDOMObject:
- virtual bool canSuspend() const OVERRIDE { return true; }
- virtual void stop() OVERRIDE;
- virtual void suspend(ReasonForSuspension) OVERRIDE;
- virtual void resume() OVERRIDE;
-
-private:
- typedef Vector<RefPtr<PrerenderHandle> > HandleVector;
- typedef Vector<KURL> KURLVector;
-
- explicit Prerenderer(Document*);
-
- Document* document();
- PrerendererClient* client();
-
- bool m_initializedClient;
- PrerendererClient* m_client;
- HandleVector m_activeHandles;
- HandleVector m_suspendedHandles;
-};
-
-}
-
-#endif // Prerenderer_h
diff --git a/chromium/third_party/WebKit/Source/core/loader/PrerendererClient.cpp b/chromium/third_party/WebKit/Source/core/loader/PrerendererClient.cpp
index e7149fbfab7..3db482676ec 100644
--- a/chromium/third_party/WebKit/Source/core/loader/PrerendererClient.cpp
+++ b/chromium/third_party/WebKit/Source/core/loader/PrerendererClient.cpp
@@ -33,7 +33,6 @@
#include "core/loader/PrerendererClient.h"
#include "core/page/Page.h"
-#include "core/platform/Supplementable.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/loader/PrerendererClient.h b/chromium/third_party/WebKit/Source/core/loader/PrerendererClient.h
index 4a9eafeca2f..4c6a1952cc7 100644
--- a/chromium/third_party/WebKit/Source/core/loader/PrerendererClient.h
+++ b/chromium/third_party/WebKit/Source/core/loader/PrerendererClient.h
@@ -32,19 +32,19 @@
#ifndef PrerendererClient_h
#define PrerendererClient_h
-#include "core/platform/Supplementable.h"
+#include "platform/Supplementable.h"
namespace WebCore {
class Document;
class Page;
-class PrerenderHandle;
+class Prerender;
class PrerendererClient : public Supplement<Page> {
public:
virtual ~PrerendererClient() { }
- virtual void willAddPrerender(PrerenderHandle*) = 0;
+ virtual void willAddPrerender(Prerender*) = 0;
static const char* supplementName();
static PrerendererClient* from(Page*);
diff --git a/chromium/third_party/WebKit/Source/core/loader/ProgressTracker.cpp b/chromium/third_party/WebKit/Source/core/loader/ProgressTracker.cpp
index 2daa653e1b7..df7477cb71f 100644
--- a/chromium/third_party/WebKit/Source/core/loader/ProgressTracker.cpp
+++ b/chromium/third_party/WebKit/Source/core/loader/ProgressTracker.cpp
@@ -26,13 +26,13 @@
#include "config.h"
#include "core/loader/ProgressTracker.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
#include "core/inspector/InspectorInstrumentation.h"
#include "core/loader/FrameLoader.h"
#include "core/loader/FrameLoaderClient.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameView.h"
-#include "core/platform/Logging.h"
-#include "core/platform/network/ResourceResponse.h"
+#include "platform/Logging.h"
+#include "platform/network/ResourceResponse.h"
#include "wtf/CurrentTime.h"
#include "wtf/text/CString.h"
@@ -104,14 +104,14 @@ void ProgressTracker::reset()
void ProgressTracker::progressStarted(Frame* frame)
{
- LOG(Progress, "Progress started (%p) - frame %p(\"%s\"), value %f, tracked frames %d, originating frame %p", this, frame, frame->tree()->uniqueName().string().utf8().data(), m_progressValue, m_numProgressTrackedFrames, m_originatingProgressFrame.get());
+ WTF_LOG(Progress, "Progress started (%p) - frame %p(\"%s\"), value %f, tracked frames %d, originating frame %p", this, frame, frame->tree().uniqueName().string().utf8().data(), m_progressValue, m_numProgressTrackedFrames, m_originatingProgressFrame.get());
if (m_numProgressTrackedFrames == 0 || m_originatingProgressFrame == frame) {
reset();
m_progressValue = initialProgressValue;
m_originatingProgressFrame = frame;
- m_originatingProgressFrame->loader()->client()->postProgressStartedNotification();
+ m_originatingProgressFrame->loader().client()->postProgressStartedNotification();
}
m_numProgressTrackedFrames++;
InspectorInstrumentation::frameStartedLoading(frame);
@@ -119,7 +119,7 @@ void ProgressTracker::progressStarted(Frame* frame)
void ProgressTracker::progressCompleted(Frame* frame)
{
- LOG(Progress, "Progress completed (%p) - frame %p(\"%s\"), value %f, tracked frames %d, originating frame %p", this, frame, frame->tree()->uniqueName().string().utf8().data(), m_progressValue, m_numProgressTrackedFrames, m_originatingProgressFrame.get());
+ WTF_LOG(Progress, "Progress completed (%p) - frame %p(\"%s\"), value %f, tracked frames %d, originating frame %p", this, frame, frame->tree().uniqueName().string().utf8().data(), m_progressValue, m_numProgressTrackedFrames, m_originatingProgressFrame.get());
if (m_numProgressTrackedFrames <= 0)
return;
@@ -130,7 +130,7 @@ void ProgressTracker::progressCompleted(Frame* frame)
void ProgressTracker::finalProgressComplete()
{
- LOG(Progress, "Final progress complete (%p)", this);
+ WTF_LOG(Progress, "Final progress complete (%p)", this);
RefPtr<Frame> frame = m_originatingProgressFrame.release();
@@ -138,17 +138,17 @@ void ProgressTracker::finalProgressComplete()
// with final progress value.
if (!m_finalProgressChangedSent) {
m_progressValue = 1;
- frame->loader()->client()->postProgressEstimateChangedNotification();
+ frame->loader().client()->postProgressEstimateChangedNotification();
}
reset();
- frame->loader()->client()->postProgressFinishedNotification();
+ frame->loader().client()->postProgressFinishedNotification();
InspectorInstrumentation::frameStoppedLoading(frame.get());
}
void ProgressTracker::incrementProgress(unsigned long identifier, const ResourceResponse& response)
{
- LOG(Progress, "Progress incremented (%p) - value %f, tracked frames %d, originating frame %p", this, m_progressValue, m_numProgressTrackedFrames, m_originatingProgressFrame.get());
+ WTF_LOG(Progress, "Progress incremented (%p) - value %f, tracked frames %d, originating frame %p", this, m_progressValue, m_numProgressTrackedFrames, m_originatingProgressFrame.get());
if (m_numProgressTrackedFrames <= 0)
return;
@@ -186,7 +186,7 @@ void ProgressTracker::incrementProgress(unsigned long identifier, const char*, i
item->estimatedLength = item->bytesReceived * 2;
}
- int numPendingOrLoadingRequests = frame->loader()->numPendingOrLoadingRequests(true);
+ int numPendingOrLoadingRequests = frame->loader().numPendingOrLoadingRequests(true);
estimatedBytesForPendingRequests = progressItemDefaultEstimatedLength * numPendingOrLoadingRequests;
remainingBytes = ((m_totalPageAndResourceBytesToLoad + estimatedBytesForPendingRequests) - m_totalBytesReceived);
if (remainingBytes > 0) // Prevent divide by 0.
@@ -207,7 +207,7 @@ void ProgressTracker::incrementProgress(unsigned long identifier, const char*, i
double now = currentTime();
double notifiedProgressTimeDelta = now - m_lastNotifiedProgressTime;
- LOG(Progress, "Progress incremented (%p) - value %f, tracked frames %d", this, m_progressValue, m_numProgressTrackedFrames);
+ WTF_LOG(Progress, "Progress incremented (%p) - value %f, tracked frames %d", this, m_progressValue, m_numProgressTrackedFrames);
double notificationProgressDelta = m_progressValue - m_lastNotifiedProgressValue;
if ((notificationProgressDelta >= m_progressNotificationInterval ||
notifiedProgressTimeDelta >= m_progressNotificationTimeInterval) &&
@@ -216,7 +216,7 @@ void ProgressTracker::incrementProgress(unsigned long identifier, const char*, i
if (m_progressValue == 1)
m_finalProgressChangedSent = true;
- frame->loader()->client()->postProgressEstimateChangedNotification();
+ frame->loader().client()->postProgressEstimateChangedNotification();
m_lastNotifiedProgressValue = m_progressValue;
m_lastNotifiedProgressTime = now;
diff --git a/chromium/third_party/WebKit/Source/core/loader/ProgressTracker.h b/chromium/third_party/WebKit/Source/core/loader/ProgressTracker.h
index f7516c70e74..fa7612f9dab 100644
--- a/chromium/third_party/WebKit/Source/core/loader/ProgressTracker.h
+++ b/chromium/third_party/WebKit/Source/core/loader/ProgressTracker.h
@@ -38,6 +38,9 @@ class Frame;
class ResourceResponse;
struct ProgressItem;
+// FIXME: This is only used on Android. Android is the only Chrome
+// browser which shows a progress bar during loading.
+// We should find a better way for Android to get this data and remove this!
class ProgressTracker {
WTF_MAKE_NONCOPYABLE(ProgressTracker); WTF_MAKE_FAST_ALLOCATED;
public:
diff --git a/chromium/third_party/WebKit/Source/core/loader/SinkDocument.cpp b/chromium/third_party/WebKit/Source/core/loader/SinkDocument.cpp
index 11839f7318b..990b71af0f4 100644
--- a/chromium/third_party/WebKit/Source/core/loader/SinkDocument.cpp
+++ b/chromium/third_party/WebKit/Source/core/loader/SinkDocument.cpp
@@ -44,7 +44,7 @@ private:
}
// Ignore all data.
- virtual size_t appendBytes(const char*, size_t) OVERRIDE { return 0; }
+ virtual void appendBytes(const char*, size_t) OVERRIDE { }
};
SinkDocument::SinkDocument(const DocumentInit& initializer)
diff --git a/chromium/third_party/WebKit/Source/core/loader/SubstituteData.h b/chromium/third_party/WebKit/Source/core/loader/SubstituteData.h
index ad6f2b7bab6..48f19283a24 100644
--- a/chromium/third_party/WebKit/Source/core/loader/SubstituteData.h
+++ b/chromium/third_party/WebKit/Source/core/loader/SubstituteData.h
@@ -26,8 +26,8 @@
#ifndef SubstituteData_h
#define SubstituteData_h
-#include "core/platform/SharedBuffer.h"
-#include "weborigin/KURL.h"
+#include "platform/SharedBuffer.h"
+#include "platform/weborigin/KURL.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefPtr.h"
@@ -37,7 +37,7 @@ namespace WebCore {
public:
SubstituteData() { }
- SubstituteData(PassRefPtr<SharedBuffer> content, const String& mimeType, const String& textEncoding, const KURL& failingURL)
+ SubstituteData(PassRefPtr<SharedBuffer> content, const AtomicString& mimeType, const AtomicString& textEncoding, const KURL& failingURL)
: m_content(content)
, m_mimeType(mimeType)
, m_textEncoding(textEncoding)
@@ -48,14 +48,14 @@ namespace WebCore {
bool isValid() const { return m_content != 0; }
const SharedBuffer* content() const { return m_content.get(); }
- const String& mimeType() const { return m_mimeType; }
- const String& textEncoding() const { return m_textEncoding; }
+ const AtomicString& mimeType() const { return m_mimeType; }
+ const AtomicString& textEncoding() const { return m_textEncoding; }
const KURL& failingURL() const { return m_failingURL; }
private:
RefPtr<SharedBuffer> m_content;
- String m_mimeType;
- String m_textEncoding;
+ AtomicString m_mimeType;
+ AtomicString m_textEncoding;
KURL m_failingURL;
KURL m_responseURL;
};
diff --git a/chromium/third_party/WebKit/Source/core/loader/TextResourceDecoderBuilder.cpp b/chromium/third_party/WebKit/Source/core/loader/TextResourceDecoderBuilder.cpp
index 1ad37828d03..ff4002adb3a 100644
--- a/chromium/third_party/WebKit/Source/core/loader/TextResourceDecoderBuilder.cpp
+++ b/chromium/third_party/WebKit/Source/core/loader/TextResourceDecoderBuilder.cpp
@@ -32,9 +32,9 @@
#include "core/loader/TextResourceDecoderBuilder.h"
#include "core/dom/Document.h"
-#include "core/page/Frame.h"
-#include "core/page/Settings.h"
-#include "weborigin/SecurityOrigin.h"
+#include "core/frame/Frame.h"
+#include "core/frame/Settings.h"
+#include "platform/weborigin/SecurityOrigin.h"
namespace WebCore {
@@ -44,7 +44,7 @@ static inline bool canReferToParentFrameEncoding(const Frame* frame, const Frame
}
-TextResourceDecoderBuilder::TextResourceDecoderBuilder(const String& mimeType, const String& encoding, bool encodingUserChoosen)
+TextResourceDecoderBuilder::TextResourceDecoderBuilder(const AtomicString& mimeType, const AtomicString& encoding, bool encodingUserChoosen)
: m_mimeType(mimeType)
, m_encoding(encoding)
, m_encodingWasChosenByUser(encodingUserChoosen)
@@ -56,7 +56,7 @@ TextResourceDecoderBuilder::~TextResourceDecoderBuilder()
}
-inline PassRefPtr<TextResourceDecoder> TextResourceDecoderBuilder::createDecoderInstance(Document* document)
+inline PassOwnPtr<TextResourceDecoder> TextResourceDecoderBuilder::createDecoderInstance(Document* document)
{
if (Frame* frame = document->frame()) {
if (Settings* settings = frame->settings())
@@ -69,10 +69,10 @@ inline PassRefPtr<TextResourceDecoder> TextResourceDecoderBuilder::createDecoder
inline void TextResourceDecoderBuilder::setupEncoding(TextResourceDecoder* decoder, Document* document)
{
Frame* frame = document->frame();
- Frame* parentFrame = frame ? frame->tree()->parent() : 0;
+ Frame* parentFrame = frame ? frame->tree().parent() : 0;
if (!m_encoding.isEmpty())
- decoder->setEncoding(m_encoding, m_encodingWasChosenByUser ? TextResourceDecoder::UserChosenEncoding : TextResourceDecoder::EncodingFromHTTPHeader);
+ decoder->setEncoding(m_encoding.string(), m_encodingWasChosenByUser ? TextResourceDecoder::UserChosenEncoding : TextResourceDecoder::EncodingFromHTTPHeader);
// Set the hint encoding to the parent frame encoding only if
// the parent and the current frames share the security origin.
@@ -84,24 +84,25 @@ inline void TextResourceDecoderBuilder::setupEncoding(TextResourceDecoder* decod
// FIXME: This might be too cautious for non-7bit-encodings and
// we may consider relaxing this later after testing.
if (frame && canReferToParentFrameEncoding(frame, parentFrame)) {
- decoder->setHintEncoding(parentFrame->document()->decoder());
+ if (parentFrame->document()->encodingWasDetectedHeuristically())
+ decoder->setHintEncoding(parentFrame->document()->encoding());
+
if (m_encoding.isEmpty())
- decoder->setEncoding(parentFrame->document()->inputEncoding(), TextResourceDecoder::EncodingFromParentFrame);
+ decoder->setEncoding(parentFrame->document()->inputEncoding().string(), TextResourceDecoder::EncodingFromParentFrame);
}
}
-PassRefPtr<TextResourceDecoder> TextResourceDecoderBuilder::buildFor(Document* document)
+PassOwnPtr<TextResourceDecoder> TextResourceDecoderBuilder::buildFor(Document* document)
{
- RefPtr<TextResourceDecoder> decoder = createDecoderInstance(document);
+ OwnPtr<TextResourceDecoder> decoder = createDecoderInstance(document);
setupEncoding(decoder.get(), document);
- document->setDecoder(decoder);
return decoder.release();
}
void TextResourceDecoderBuilder::clear()
{
if (!m_encodingWasChosenByUser)
- m_encoding = String();
+ m_encoding = nullAtom;
}
}
diff --git a/chromium/third_party/WebKit/Source/core/loader/TextResourceDecoderBuilder.h b/chromium/third_party/WebKit/Source/core/loader/TextResourceDecoderBuilder.h
index c2a57b9f4da..b6c27c77464 100644
--- a/chromium/third_party/WebKit/Source/core/loader/TextResourceDecoderBuilder.h
+++ b/chromium/third_party/WebKit/Source/core/loader/TextResourceDecoderBuilder.h
@@ -42,23 +42,23 @@ class TextResourceDecoder;
class TextResourceDecoderBuilder {
public:
- TextResourceDecoderBuilder(const String& mimeType, const String& encoding, bool encodingUserChoosen);
+ TextResourceDecoderBuilder(const AtomicString& mimeType, const AtomicString& encoding, bool encodingUserChoosen);
~TextResourceDecoderBuilder();
- PassRefPtr<TextResourceDecoder> buildFor(Document*);
+ PassOwnPtr<TextResourceDecoder> buildFor(Document*);
- const String& mimeType() const { return m_mimeType; }
- const String& encoding() const { return m_encoding; }
+ const AtomicString& mimeType() const { return m_mimeType; }
+ const AtomicString& encoding() const { return m_encoding; }
bool encodingWasChosenByUser() const { return m_encodingWasChosenByUser; }
void clear();
private:
- PassRefPtr<TextResourceDecoder> createDecoderInstance(Document*);
+ PassOwnPtr<TextResourceDecoder> createDecoderInstance(Document*);
void setupEncoding(TextResourceDecoder*, Document*);
- String m_mimeType;
- String m_encoding;
+ AtomicString m_mimeType;
+ AtomicString m_encoding;
bool m_encodingWasChosenByUser;
};
diff --git a/chromium/third_party/WebKit/Source/core/loader/TextTrackLoader.cpp b/chromium/third_party/WebKit/Source/core/loader/TextTrackLoader.cpp
index 7e6fd8612a5..121a2b5c163 100644
--- a/chromium/third_party/WebKit/Source/core/loader/TextTrackLoader.cpp
+++ b/chromium/third_party/WebKit/Source/core/loader/TextTrackLoader.cpp
@@ -32,28 +32,23 @@
#include "core/fetch/CrossOriginAccessControl.h"
#include "core/fetch/FetchRequest.h"
#include "core/fetch/ResourceFetcher.h"
-#include "core/fetch/TextTrackResource.h"
-#include "core/html/track/WebVTTParser.h"
-#include "core/platform/Logging.h"
-#include "core/platform/SharedBuffer.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/Logging.h"
+#include "platform/SharedBuffer.h"
+#include "platform/weborigin/SecurityOrigin.h"
namespace WebCore {
-TextTrackLoader::TextTrackLoader(TextTrackLoaderClient* client, ScriptExecutionContext* context)
+TextTrackLoader::TextTrackLoader(TextTrackLoaderClient& client, Document& document)
: m_client(client)
- , m_scriptExecutionContext(context)
+ , m_document(document)
, m_cueLoadTimer(this, &TextTrackLoader::cueLoadTimerFired)
, m_state(Idle)
- , m_parseOffset(0)
, m_newCuesAvailable(false)
{
}
TextTrackLoader::~TextTrackLoader()
{
- if (m_cachedCueData)
- m_cachedCueData->removeClient(this);
}
void TextTrackLoader::cueLoadTimerFired(Timer<TextTrackLoader>* timer)
@@ -62,80 +57,54 @@ void TextTrackLoader::cueLoadTimerFired(Timer<TextTrackLoader>* timer)
if (m_newCuesAvailable) {
m_newCuesAvailable = false;
- m_client->newCuesAvailable(this);
+ m_client.newCuesAvailable(this);
}
if (m_state >= Finished)
- m_client->cueLoadingCompleted(this, m_state == Failed);
+ m_client.cueLoadingCompleted(this, m_state == Failed);
}
void TextTrackLoader::cancelLoad()
{
- if (m_cachedCueData) {
- m_cachedCueData->removeClient(this);
- m_cachedCueData = 0;
- }
+ clearResource();
}
-void TextTrackLoader::processNewCueData(Resource* resource)
+void TextTrackLoader::dataReceived(Resource* resource, const char* data, int length)
{
- ASSERT(m_cachedCueData == resource);
-
- if (m_state == Failed || !resource->resourceBuffer())
- return;
+ ASSERT(this->resource() == resource);
- SharedBuffer* buffer = resource->resourceBuffer();
- if (m_parseOffset == buffer->size())
+ if (m_state == Failed)
return;
if (!m_cueParser)
- m_cueParser = WebVTTParser::create(this, m_scriptExecutionContext);
-
- const char* data;
- unsigned length;
-
- while ((length = buffer->getSomeData(data, m_parseOffset))) {
- m_cueParser->parseBytes(data, length);
- m_parseOffset += length;
- }
-}
-
-// FIXME: This is a very unusual pattern, no other ResourceClient does this. Refactor to use notifyFinished() instead.
-void TextTrackLoader::deprecatedDidReceiveResource(Resource* resource)
-{
- ASSERT(m_cachedCueData == resource);
+ m_cueParser = VTTParser::create(this, m_document);
- if (!resource->resourceBuffer())
- return;
-
- processNewCueData(resource);
+ m_cueParser->parseBytes(data, length);
}
void TextTrackLoader::corsPolicyPreventedLoad()
{
DEFINE_STATIC_LOCAL(String, consoleMessage, ("Cross-origin text track load denied by Cross-Origin Resource Sharing policy."));
- Document* document = toDocument(m_scriptExecutionContext);
- document->addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, consoleMessage);
+ m_document.addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, consoleMessage);
m_state = Failed;
}
void TextTrackLoader::notifyFinished(Resource* resource)
{
- ASSERT(m_cachedCueData == resource);
+ ASSERT(this->resource() == resource);
- Document* document = toDocument(m_scriptExecutionContext);
if (!m_crossOriginMode.isNull()
- && !document->securityOrigin()->canRequest(resource->response().url())
- && !resource->passesAccessControlCheck(document->securityOrigin())) {
+ && !m_document.securityOrigin()->canRequest(resource->response().url())
+ && !resource->passesAccessControlCheck(m_document.securityOrigin())) {
corsPolicyPreventedLoad();
}
- if (m_state != Failed) {
- processNewCueData(resource);
- if (m_state != Failed)
- m_state = resource->errorOccurred() ? Failed : Finished;
- }
+ if (m_state != Failed)
+ m_state = resource->errorOccurred() ? Failed : Finished;
+
+ if (m_state == Finished && m_cueParser)
+ m_cueParser->flush();
if (!m_cueLoadTimer.isActive())
m_cueLoadTimer.startOneShot(0);
@@ -147,33 +116,23 @@ bool TextTrackLoader::load(const KURL& url, const String& crossOriginMode)
{
cancelLoad();
- if (!m_client->shouldLoadCues(this))
- return false;
-
- ASSERT(m_scriptExecutionContext->isDocument());
- Document* document = toDocument(m_scriptExecutionContext);
- FetchRequest cueRequest(ResourceRequest(document->completeURL(url)), FetchInitiatorTypeNames::texttrack);
+ FetchRequest cueRequest(ResourceRequest(m_document.completeURL(url)), FetchInitiatorTypeNames::texttrack);
if (!crossOriginMode.isNull()) {
m_crossOriginMode = crossOriginMode;
StoredCredentials allowCredentials = equalIgnoringCase(crossOriginMode, "use-credentials") ? AllowStoredCredentials : DoNotAllowStoredCredentials;
- updateRequestForAccessControl(cueRequest.mutableResourceRequest(), document->securityOrigin(), allowCredentials);
+ updateRequestForAccessControl(cueRequest.mutableResourceRequest(), m_document.securityOrigin(), allowCredentials);
} else {
// Cross-origin resources that are not suitably CORS-enabled may not load.
- if (!document->securityOrigin()->canRequest(url)) {
+ if (!m_document.securityOrigin()->canRequest(url)) {
corsPolicyPreventedLoad();
return false;
}
}
- ResourceFetcher* fetcher = document->fetcher();
- m_cachedCueData = fetcher->fetchTextTrack(cueRequest);
- if (m_cachedCueData)
- m_cachedCueData->addClient(this);
-
- m_client->cueLoadingStarted(this);
-
- return true;
+ ResourceFetcher* fetcher = m_document.fetcher();
+ setResource(fetcher->fetchRawResource(cueRequest));
+ return resource();
}
void TextTrackLoader::newCuesParsed()
@@ -185,16 +144,14 @@ void TextTrackLoader::newCuesParsed()
m_cueLoadTimer.startOneShot(0);
}
-#if ENABLE(WEBVTT_REGIONS)
void TextTrackLoader::newRegionsParsed()
{
- m_client->newRegionsAvailable(this);
+ m_client.newRegionsAvailable(this);
}
-#endif
void TextTrackLoader::fileFailedToParse()
{
- LOG(Media, "TextTrackLoader::fileFailedToParse");
+ WTF_LOG(Media, "TextTrackLoader::fileFailedToParse");
m_state = Failed;
@@ -204,20 +161,18 @@ void TextTrackLoader::fileFailedToParse()
cancelLoad();
}
-void TextTrackLoader::getNewCues(Vector<RefPtr<TextTrackCue> >& outputCues)
+void TextTrackLoader::getNewCues(Vector<RefPtr<VTTCue> >& outputCues)
{
ASSERT(m_cueParser);
if (m_cueParser)
m_cueParser->getNewCues(outputCues);
}
-#if ENABLE(WEBVTT_REGIONS)
-void TextTrackLoader::getNewRegions(Vector<RefPtr<TextTrackRegion> >& outputRegions)
+void TextTrackLoader::getNewRegions(Vector<RefPtr<VTTRegion> >& outputRegions)
{
ASSERT(m_cueParser);
if (m_cueParser)
m_cueParser->getNewRegions(outputRegions);
}
-#endif
-}
+}
diff --git a/chromium/third_party/WebKit/Source/core/loader/TextTrackLoader.h b/chromium/third_party/WebKit/Source/core/loader/TextTrackLoader.h
index 4eb68a81aa6..4ab8e95fd38 100644
--- a/chromium/third_party/WebKit/Source/core/loader/TextTrackLoader.h
+++ b/chromium/third_party/WebKit/Source/core/loader/TextTrackLoader.h
@@ -26,39 +26,33 @@
#ifndef TextTrackLoader_h
#define TextTrackLoader_h
-#include "core/fetch/ResourceClient.h"
-#include "core/fetch/ResourcePtr.h"
-#include "core/fetch/TextTrackResource.h"
-#include "core/html/track/WebVTTParser.h"
-#include "core/platform/Timer.h"
+#include "core/fetch/RawResource.h"
+#include "core/fetch/ResourceOwner.h"
+#include "core/html/track/vtt/VTTParser.h"
+#include "platform/Timer.h"
#include "wtf/OwnPtr.h"
namespace WebCore {
class Document;
class TextTrackLoader;
-class ScriptExecutionContext;
-class TextTrackLoaderClient {
+class TextTrackLoaderClient : public ResourceOwner<RawResource> {
public:
virtual ~TextTrackLoaderClient() { }
- virtual bool shouldLoadCues(TextTrackLoader*) = 0;
virtual void newCuesAvailable(TextTrackLoader*) = 0;
- virtual void cueLoadingStarted(TextTrackLoader*) = 0;
virtual void cueLoadingCompleted(TextTrackLoader*, bool loadingFailed) = 0;
-#if ENABLE(WEBVTT_REGIONS)
virtual void newRegionsAvailable(TextTrackLoader*) = 0;
-#endif
};
-class TextTrackLoader : public ResourceClient, private WebVTTParserClient {
+class TextTrackLoader : public ResourceOwner<RawResource>, private VTTParserClient {
WTF_MAKE_NONCOPYABLE(TextTrackLoader);
WTF_MAKE_FAST_ALLOCATED;
public:
- static PassOwnPtr<TextTrackLoader> create(TextTrackLoaderClient* client, ScriptExecutionContext* context)
+ static PassOwnPtr<TextTrackLoader> create(TextTrackLoaderClient& client, Document& document)
{
- return adoptPtr(new TextTrackLoader(client, context));
+ return adoptPtr(new TextTrackLoader(client, document));
}
virtual ~TextTrackLoader();
@@ -68,37 +62,31 @@ public:
enum State { Idle, Loading, Finished, Failed };
State loadState() { return m_state; }
- void getNewCues(Vector<RefPtr<TextTrackCue> >& outputCues);
-#if ENABLE(WEBVTT_REGIONS)
- void getNewRegions(Vector<RefPtr<TextTrackRegion> >& outputRegions);
-#endif
+ void getNewCues(Vector<RefPtr<VTTCue> >& outputCues);
+ void getNewRegions(Vector<RefPtr<VTTRegion> >& outputRegions);
private:
- // ResourceClient
- virtual void notifyFinished(Resource*);
- virtual void deprecatedDidReceiveResource(Resource*);
+ // RawResourceClient
+ virtual void dataReceived(Resource*, const char* data, int length) OVERRIDE;
+ virtual void notifyFinished(Resource*) OVERRIDE;
- // WebVTTParserClient
- virtual void newCuesParsed();
-#if ENABLE(WEBVTT_REGIONS)
- virtual void newRegionsParsed();
-#endif
- virtual void fileFailedToParse();
+ // VTTParserClient
+ virtual void newCuesParsed() OVERRIDE;
+ virtual void newRegionsParsed() OVERRIDE;
+ virtual void fileFailedToParse() OVERRIDE;
- TextTrackLoader(TextTrackLoaderClient*, ScriptExecutionContext*);
+ TextTrackLoader(TextTrackLoaderClient&, Document&);
- void processNewCueData(Resource*);
void cueLoadTimerFired(Timer<TextTrackLoader>*);
void corsPolicyPreventedLoad();
- TextTrackLoaderClient* m_client;
- OwnPtr<WebVTTParser> m_cueParser;
- ResourcePtr<TextTrackResource> m_cachedCueData;
- ScriptExecutionContext* m_scriptExecutionContext;
+ TextTrackLoaderClient& m_client;
+ OwnPtr<VTTParser> m_cueParser;
+ // FIXME: Remove this pointer and get the Document from m_client.
+ Document& m_document;
Timer<TextTrackLoader> m_cueLoadTimer;
String m_crossOriginMode;
State m_state;
- unsigned m_parseOffset;
bool m_newCuesAvailable;
};
diff --git a/chromium/third_party/WebKit/Source/core/loader/ThreadableLoader.cpp b/chromium/third_party/WebKit/Source/core/loader/ThreadableLoader.cpp
index 50279cb2ae7..476f915fe9e 100644
--- a/chromium/third_party/WebKit/Source/core/loader/ThreadableLoader.cpp
+++ b/chromium/third_party/WebKit/Source/core/loader/ThreadableLoader.cpp
@@ -32,7 +32,7 @@
#include "core/loader/ThreadableLoader.h"
#include "core/dom/Document.h"
-#include "core/dom/ScriptExecutionContext.h"
+#include "core/dom/ExecutionContext.h"
#include "core/loader/DocumentThreadableLoader.h"
#include "core/loader/WorkerThreadableLoader.h"
#include "core/workers/WorkerGlobalScope.h"
@@ -40,7 +40,7 @@
namespace WebCore {
-PassRefPtr<ThreadableLoader> ThreadableLoader::create(ScriptExecutionContext* context, ThreadableLoaderClient* client, const ResourceRequest& request, const ThreadableLoaderOptions& options)
+PassRefPtr<ThreadableLoader> ThreadableLoader::create(ExecutionContext* context, ThreadableLoaderClient* client, const ResourceRequest& request, const ThreadableLoaderOptions& options)
{
ASSERT(client);
ASSERT(context);
@@ -51,7 +51,7 @@ PassRefPtr<ThreadableLoader> ThreadableLoader::create(ScriptExecutionContext* co
return DocumentThreadableLoader::create(toDocument(context), client, request, options);
}
-void ThreadableLoader::loadResourceSynchronously(ScriptExecutionContext* context, const ResourceRequest& request, ThreadableLoaderClient& client, const ThreadableLoaderOptions& options)
+void ThreadableLoader::loadResourceSynchronously(ExecutionContext* context, const ResourceRequest& request, ThreadableLoaderClient& client, const ThreadableLoaderOptions& options)
{
ASSERT(context);
diff --git a/chromium/third_party/WebKit/Source/core/loader/ThreadableLoader.h b/chromium/third_party/WebKit/Source/core/loader/ThreadableLoader.h
index a2afdd11b6b..a1092d24400 100644
--- a/chromium/third_party/WebKit/Source/core/loader/ThreadableLoader.h
+++ b/chromium/third_party/WebKit/Source/core/loader/ThreadableLoader.h
@@ -32,7 +32,6 @@
#define ThreadableLoader_h
#include "core/fetch/ResourceLoaderOptions.h"
-#include "weborigin/SecurityOrigin.h"
#include "wtf/Noncopyable.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefPtr.h"
@@ -42,7 +41,7 @@ namespace WebCore {
class ResourceError;
class ResourceRequest;
class ResourceResponse;
- class ScriptExecutionContext;
+ class ExecutionContext;
class ThreadableLoaderClient;
enum CrossOriginRequestPolicy {
@@ -71,7 +70,6 @@ namespace WebCore {
PreflightPolicy preflightPolicy; // If AccessControl is used, how to determine if a preflight is needed.
CrossOriginRequestPolicy crossOriginRequestPolicy;
- RefPtr<SecurityOrigin> securityOrigin;
AtomicString initiator;
ContentSecurityPolicyEnforcement contentSecurityPolicyEnforcement;
unsigned long timeoutMilliseconds;
@@ -82,8 +80,8 @@ namespace WebCore {
class ThreadableLoader {
WTF_MAKE_NONCOPYABLE(ThreadableLoader);
public:
- static void loadResourceSynchronously(ScriptExecutionContext*, const ResourceRequest&, ThreadableLoaderClient&, const ThreadableLoaderOptions&);
- static PassRefPtr<ThreadableLoader> create(ScriptExecutionContext*, ThreadableLoaderClient*, const ResourceRequest&, const ThreadableLoaderOptions&);
+ static void loadResourceSynchronously(ExecutionContext*, const ResourceRequest&, ThreadableLoaderClient&, const ThreadableLoaderOptions&);
+ static PassRefPtr<ThreadableLoader> create(ExecutionContext*, ThreadableLoaderClient*, const ResourceRequest&, const ThreadableLoaderOptions&);
virtual void cancel() = 0;
void ref() { refThreadableLoader(); }
diff --git a/chromium/third_party/WebKit/Source/core/loader/WorkerThreadableLoader.cpp b/chromium/third_party/WebKit/Source/core/loader/WorkerThreadableLoader.cpp
index d76b7244e99..ad16a0f36d0 100644
--- a/chromium/third_party/WebKit/Source/core/loader/WorkerThreadableLoader.cpp
+++ b/chromium/third_party/WebKit/Source/core/loader/WorkerThreadableLoader.cpp
@@ -35,13 +35,12 @@
#include "core/dom/CrossThreadTask.h"
#include "core/dom/Document.h"
#include "core/loader/DocumentThreadableLoader.h"
-#include "core/loader/ThreadableLoader.h"
-#include "core/platform/network/ResourceError.h"
-#include "core/platform/network/ResourceRequest.h"
-#include "core/platform/network/ResourceResponse.h"
#include "core/workers/WorkerGlobalScope.h"
#include "core/workers/WorkerLoaderProxy.h"
#include "core/workers/WorkerThread.h"
+#include "platform/network/ResourceError.h"
+#include "platform/network/ResourceRequest.h"
+#include "platform/network/ResourceResponse.h"
#include "wtf/MainThread.h"
#include "wtf/OwnPtr.h"
#include "wtf/Vector.h"
@@ -102,7 +101,7 @@ WorkerThreadableLoader::MainThreadBridge::~MainThreadBridge()
{
}
-void WorkerThreadableLoader::MainThreadBridge::mainThreadCreateLoader(ScriptExecutionContext* context, MainThreadBridge* thisPtr, PassOwnPtr<CrossThreadResourceRequestData> requestData, ThreadableLoaderOptions options, const String& outgoingReferrer)
+void WorkerThreadableLoader::MainThreadBridge::mainThreadCreateLoader(ExecutionContext* context, MainThreadBridge* thisPtr, PassOwnPtr<CrossThreadResourceRequestData> requestData, ThreadableLoaderOptions options, const String& outgoingReferrer)
{
ASSERT(isMainThread());
Document* document = toDocument(context);
@@ -110,14 +109,14 @@ void WorkerThreadableLoader::MainThreadBridge::mainThreadCreateLoader(ScriptExec
OwnPtr<ResourceRequest> request(ResourceRequest::adopt(requestData));
request->setHTTPReferrer(outgoingReferrer);
options.requestInitiatorContext = WorkerContext;
- // FIXME: If the a site requests a local resource, then this will return a non-zero value but the sync path
- // will return a 0 value. Either this should return 0 or the other code path should do a callback with
- // a failure.
thisPtr->m_mainThreadLoader = DocumentThreadableLoader::create(document, thisPtr, *request, options);
- ASSERT(thisPtr->m_mainThreadLoader);
+ if (!thisPtr->m_mainThreadLoader) {
+ // DocumentThreadableLoader::create may return 0 when the document loader has been already changed.
+ thisPtr->didFail(ResourceError(errorDomainBlinkInternal, 0, request->url().string(), "Can't create DocumentThreadableLoader"));
+ }
}
-void WorkerThreadableLoader::MainThreadBridge::mainThreadDestroy(ScriptExecutionContext* context, MainThreadBridge* thisPtr)
+void WorkerThreadableLoader::MainThreadBridge::mainThreadDestroy(ExecutionContext* context, MainThreadBridge* thisPtr)
{
ASSERT(isMainThread());
ASSERT_UNUSED(context, context->isDocument());
@@ -134,7 +133,7 @@ void WorkerThreadableLoader::MainThreadBridge::destroy()
createCallbackTask(&MainThreadBridge::mainThreadDestroy, AllowCrossThreadAccess(this)));
}
-void WorkerThreadableLoader::MainThreadBridge::mainThreadCancel(ScriptExecutionContext* context, MainThreadBridge* thisPtr)
+void WorkerThreadableLoader::MainThreadBridge::mainThreadCancel(ExecutionContext* context, MainThreadBridge* thisPtr)
{
ASSERT(isMainThread());
ASSERT_UNUSED(context, context->isDocument());
@@ -165,7 +164,7 @@ void WorkerThreadableLoader::MainThreadBridge::clearClientWrapper()
m_workerClientWrapper->clearClient();
}
-static void workerGlobalScopeDidSendData(ScriptExecutionContext* context, RefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, unsigned long long bytesSent, unsigned long long totalBytesToBeSent)
+static void workerGlobalScopeDidSendData(ExecutionContext* context, PassRefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, unsigned long long bytesSent, unsigned long long totalBytesToBeSent)
{
ASSERT_UNUSED(context, context->isWorkerGlobalScope());
workerClientWrapper->didSendData(bytesSent, totalBytesToBeSent);
@@ -176,7 +175,7 @@ void WorkerThreadableLoader::MainThreadBridge::didSendData(unsigned long long by
m_loaderProxy.postTaskForModeToWorkerGlobalScope(createCallbackTask(&workerGlobalScopeDidSendData, m_workerClientWrapper, bytesSent, totalBytesToBeSent), m_taskMode);
}
-static void workerGlobalScopeDidReceiveResponse(ScriptExecutionContext* context, RefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, unsigned long identifier, PassOwnPtr<CrossThreadResourceResponseData> responseData)
+static void workerGlobalScopeDidReceiveResponse(ExecutionContext* context, PassRefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, unsigned long identifier, PassOwnPtr<CrossThreadResourceResponseData> responseData)
{
ASSERT_UNUSED(context, context->isWorkerGlobalScope());
OwnPtr<ResourceResponse> response(ResourceResponse::adopt(responseData));
@@ -188,7 +187,7 @@ void WorkerThreadableLoader::MainThreadBridge::didReceiveResponse(unsigned long
m_loaderProxy.postTaskForModeToWorkerGlobalScope(createCallbackTask(&workerGlobalScopeDidReceiveResponse, m_workerClientWrapper, identifier, response), m_taskMode);
}
-static void workerGlobalScopeDidReceiveData(ScriptExecutionContext* context, RefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, PassOwnPtr<Vector<char> > vectorData)
+static void workerGlobalScopeDidReceiveData(ExecutionContext* context, PassRefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, PassOwnPtr<Vector<char> > vectorData)
{
ASSERT_UNUSED(context, context->isWorkerGlobalScope());
workerClientWrapper->didReceiveData(vectorData->data(), vectorData->size());
@@ -201,7 +200,18 @@ void WorkerThreadableLoader::MainThreadBridge::didReceiveData(const char* data,
m_loaderProxy.postTaskForModeToWorkerGlobalScope(createCallbackTask(&workerGlobalScopeDidReceiveData, m_workerClientWrapper, vector.release()), m_taskMode);
}
-static void workerGlobalScopeDidReceiveCachedMetadata(ScriptExecutionContext* context, RefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, PassOwnPtr<Vector<char> > vectorData)
+static void workerGlobalScopeDidDownloadData(ExecutionContext* context, PassRefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, int dataLength)
+{
+ ASSERT_UNUSED(context, context->isWorkerGlobalScope());
+ workerClientWrapper->didDownloadData(dataLength);
+}
+
+void WorkerThreadableLoader::MainThreadBridge::didDownloadData(int dataLength)
+{
+ m_loaderProxy.postTaskForModeToWorkerGlobalScope(createCallbackTask(&workerGlobalScopeDidDownloadData, m_workerClientWrapper, dataLength), m_taskMode);
+}
+
+static void workerGlobalScopeDidReceiveCachedMetadata(ExecutionContext* context, PassRefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, PassOwnPtr<Vector<char> > vectorData)
{
ASSERT_UNUSED(context, context->isWorkerGlobalScope());
workerClientWrapper->didReceiveCachedMetadata(vectorData->data(), vectorData->size());
@@ -214,7 +224,7 @@ void WorkerThreadableLoader::MainThreadBridge::didReceiveCachedMetadata(const ch
m_loaderProxy.postTaskForModeToWorkerGlobalScope(createCallbackTask(&workerGlobalScopeDidReceiveCachedMetadata, m_workerClientWrapper, vector.release()), m_taskMode);
}
-static void workerGlobalScopeDidFinishLoading(ScriptExecutionContext* context, RefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, unsigned long identifier, double finishTime)
+static void workerGlobalScopeDidFinishLoading(ExecutionContext* context, PassRefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, unsigned long identifier, double finishTime)
{
ASSERT_UNUSED(context, context->isWorkerGlobalScope());
workerClientWrapper->didFinishLoading(identifier, finishTime);
@@ -225,7 +235,7 @@ void WorkerThreadableLoader::MainThreadBridge::didFinishLoading(unsigned long id
m_loaderProxy.postTaskForModeToWorkerGlobalScope(createCallbackTask(&workerGlobalScopeDidFinishLoading, m_workerClientWrapper, identifier, finishTime), m_taskMode);
}
-static void workerGlobalScopeDidFail(ScriptExecutionContext* context, RefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, const ResourceError& error)
+static void workerGlobalScopeDidFail(ExecutionContext* context, PassRefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, const ResourceError& error)
{
ASSERT_UNUSED(context, context->isWorkerGlobalScope());
workerClientWrapper->didFail(error);
@@ -236,7 +246,7 @@ void WorkerThreadableLoader::MainThreadBridge::didFail(const ResourceError& erro
m_loaderProxy.postTaskForModeToWorkerGlobalScope(createCallbackTask(&workerGlobalScopeDidFail, m_workerClientWrapper, error), m_taskMode);
}
-static void workerGlobalScopeDidFailAccessControlCheck(ScriptExecutionContext* context, PassRefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, const ResourceError& error)
+static void workerGlobalScopeDidFailAccessControlCheck(ExecutionContext* context, PassRefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, const ResourceError& error)
{
ASSERT_UNUSED(context, context->isWorkerGlobalScope());
workerClientWrapper->didFailAccessControlCheck(error);
@@ -247,7 +257,7 @@ void WorkerThreadableLoader::MainThreadBridge::didFailAccessControlCheck(const R
m_loaderProxy.postTaskForModeToWorkerGlobalScope(createCallbackTask(&workerGlobalScopeDidFailAccessControlCheck, m_workerClientWrapper, error), m_taskMode);
}
-static void workerGlobalScopeDidFailRedirectCheck(ScriptExecutionContext* context, RefPtr<ThreadableLoaderClientWrapper> workerClientWrapper)
+static void workerGlobalScopeDidFailRedirectCheck(ExecutionContext* context, PassRefPtr<ThreadableLoaderClientWrapper> workerClientWrapper)
{
ASSERT_UNUSED(context, context->isWorkerGlobalScope());
workerClientWrapper->didFailRedirectCheck();
diff --git a/chromium/third_party/WebKit/Source/core/loader/WorkerThreadableLoader.h b/chromium/third_party/WebKit/Source/core/loader/WorkerThreadableLoader.h
index 911bf6ea786..369babe30cc 100644
--- a/chromium/third_party/WebKit/Source/core/loader/WorkerThreadableLoader.h
+++ b/chromium/third_party/WebKit/Source/core/loader/WorkerThreadableLoader.h
@@ -104,14 +104,15 @@ namespace WebCore {
void clearClientWrapper();
// All executed on the main thread.
- static void mainThreadDestroy(ScriptExecutionContext*, MainThreadBridge*);
+ static void mainThreadDestroy(ExecutionContext*, MainThreadBridge*);
~MainThreadBridge();
- static void mainThreadCreateLoader(ScriptExecutionContext*, MainThreadBridge*, PassOwnPtr<CrossThreadResourceRequestData>, ThreadableLoaderOptions, const String& outgoingReferrer);
- static void mainThreadCancel(ScriptExecutionContext*, MainThreadBridge*);
+ static void mainThreadCreateLoader(ExecutionContext*, MainThreadBridge*, PassOwnPtr<CrossThreadResourceRequestData>, ThreadableLoaderOptions, const String& outgoingReferrer);
+ static void mainThreadCancel(ExecutionContext*, MainThreadBridge*);
virtual void didSendData(unsigned long long bytesSent, unsigned long long totalBytesToBeSent) OVERRIDE;
virtual void didReceiveResponse(unsigned long identifier, const ResourceResponse&) OVERRIDE;
virtual void didReceiveData(const char*, int dataLength) OVERRIDE;
+ virtual void didDownloadData(int dataLength) OVERRIDE;
virtual void didReceiveCachedMetadata(const char*, int dataLength) OVERRIDE;
virtual void didFinishLoading(unsigned long identifier, double finishTime) OVERRIDE;
virtual void didFail(const ResourceError&) OVERRIDE;
diff --git a/chromium/third_party/WebKit/Source/core/loader/appcache/ApplicationCache.cpp b/chromium/third_party/WebKit/Source/core/loader/appcache/ApplicationCache.cpp
index 786c8fdd3b9..862f37a668e 100644
--- a/chromium/third_party/WebKit/Source/core/loader/appcache/ApplicationCache.cpp
+++ b/chromium/third_party/WebKit/Source/core/loader/appcache/ApplicationCache.cpp
@@ -26,16 +26,13 @@
#include "config.h"
#include "core/loader/appcache/ApplicationCache.h"
-#include "bindings/v8/ExceptionMessages.h"
#include "bindings/v8/ExceptionState.h"
#include "core/dom/Document.h"
-#include "core/dom/EventListener.h"
-#include "core/dom/EventNames.h"
#include "core/dom/ExceptionCode.h"
+#include "core/events/EventListener.h"
#include "core/loader/DocumentLoader.h"
#include "core/loader/FrameLoader.h"
-#include "core/loader/appcache/ApplicationCacheHost.h"
-#include "core/page/Frame.h"
+#include "core/frame/Frame.h"
namespace WebCore {
@@ -57,9 +54,9 @@ void ApplicationCache::willDestroyGlobalObjectInFrame()
ApplicationCacheHost* ApplicationCache::applicationCacheHost() const
{
- if (!m_frame || !m_frame->loader()->documentLoader())
+ if (!m_frame || !m_frame->loader().documentLoader())
return 0;
- return m_frame->loader()->documentLoader()->applicationCacheHost();
+ return m_frame->loader().documentLoader()->applicationCacheHost();
}
unsigned short ApplicationCache::status() const
@@ -70,18 +67,18 @@ unsigned short ApplicationCache::status() const
return cacheHost->status();
}
-void ApplicationCache::update(ExceptionState& es)
+void ApplicationCache::update(ExceptionState& exceptionState)
{
ApplicationCacheHost* cacheHost = applicationCacheHost();
if (!cacheHost || !cacheHost->update())
- es.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("update", "ApplicationCache", "there is no application cache to update."));
+ exceptionState.throwDOMException(InvalidStateError, "there is no application cache to update.");
}
-void ApplicationCache::swapCache(ExceptionState& es)
+void ApplicationCache::swapCache(ExceptionState& exceptionState)
{
ApplicationCacheHost* cacheHost = applicationCacheHost();
if (!cacheHost || !cacheHost->swapCache())
- es.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("swapCache", "ApplicationCache", "there is no newer application cache to swap to."));
+ exceptionState.throwDOMException(InvalidStateError, "there is no newer application cache to swap to.");
}
void ApplicationCache::abort()
@@ -93,10 +90,10 @@ void ApplicationCache::abort()
const AtomicString& ApplicationCache::interfaceName() const
{
- return eventNames().interfaceForApplicationCache;
+ return EventTargetNames::ApplicationCache;
}
-ScriptExecutionContext* ApplicationCache::scriptExecutionContext() const
+ExecutionContext* ApplicationCache::executionContext() const
{
if (m_frame)
return m_frame->document();
@@ -107,34 +104,24 @@ const AtomicString& ApplicationCache::toEventType(ApplicationCacheHost::EventID
{
switch (id) {
case ApplicationCacheHost::CHECKING_EVENT:
- return eventNames().checkingEvent;
+ return EventTypeNames::checking;
case ApplicationCacheHost::ERROR_EVENT:
- return eventNames().errorEvent;
+ return EventTypeNames::error;
case ApplicationCacheHost::NOUPDATE_EVENT:
- return eventNames().noupdateEvent;
+ return EventTypeNames::noupdate;
case ApplicationCacheHost::DOWNLOADING_EVENT:
- return eventNames().downloadingEvent;
+ return EventTypeNames::downloading;
case ApplicationCacheHost::PROGRESS_EVENT:
- return eventNames().progressEvent;
+ return EventTypeNames::progress;
case ApplicationCacheHost::UPDATEREADY_EVENT:
- return eventNames().updatereadyEvent;
+ return EventTypeNames::updateready;
case ApplicationCacheHost::CACHED_EVENT:
- return eventNames().cachedEvent;
+ return EventTypeNames::cached;
case ApplicationCacheHost::OBSOLETE_EVENT:
- return eventNames().obsoleteEvent;
+ return EventTypeNames::obsolete;
}
ASSERT_NOT_REACHED();
- return eventNames().errorEvent;
-}
-
-EventTargetData* ApplicationCache::eventTargetData()
-{
- return &m_eventTargetData;
-}
-
-EventTargetData* ApplicationCache::ensureEventTargetData()
-{
- return &m_eventTargetData;
+ return EventTypeNames::error;
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/loader/appcache/ApplicationCache.h b/chromium/third_party/WebKit/Source/core/loader/appcache/ApplicationCache.h
index 680f9c4145d..405ad35b75e 100644
--- a/chromium/third_party/WebKit/Source/core/loader/appcache/ApplicationCache.h
+++ b/chromium/third_party/WebKit/Source/core/loader/appcache/ApplicationCache.h
@@ -27,10 +27,10 @@
#define ApplicationCache_h
#include "bindings/v8/ScriptWrappable.h"
-#include "core/dom/EventNames.h"
-#include "core/dom/EventTarget.h"
+#include "core/events/EventTarget.h"
+#include "core/events/ThreadLocalEventNames.h"
#include "core/loader/appcache/ApplicationCacheHost.h"
-#include "core/page/DOMWindowProperty.h"
+#include "core/frame/DOMWindowProperty.h"
#include "wtf/Forward.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefCounted.h"
@@ -41,7 +41,8 @@ class ExceptionState;
class Frame;
class KURL;
-class ApplicationCache : public ScriptWrappable, public RefCounted<ApplicationCache>, public EventTarget, public DOMWindowProperty {
+class ApplicationCache : public ScriptWrappable, public RefCounted<ApplicationCache>, public EventTargetWithInlineData, public DOMWindowProperty {
+ REFCOUNTED_EVENT_TARGET(ApplicationCache);
public:
static PassRefPtr<ApplicationCache> create(Frame* frame) { return adoptRef(new ApplicationCache(frame)); }
~ApplicationCache() { ASSERT(!m_frame); }
@@ -53,11 +54,6 @@ public:
void swapCache(ExceptionState&);
void abort();
- // EventTarget impl
-
- using RefCounted<ApplicationCache>::ref;
- using RefCounted<ApplicationCache>::deref;
-
// Explicitly named attribute event listener helpers
DEFINE_ATTRIBUTE_EVENT_LISTENER(checking);
@@ -69,22 +65,15 @@ public:
DEFINE_ATTRIBUTE_EVENT_LISTENER(cached);
DEFINE_ATTRIBUTE_EVENT_LISTENER(obsolete);
- virtual const AtomicString& interfaceName() const;
- virtual ScriptExecutionContext* scriptExecutionContext() const;
+ virtual const AtomicString& interfaceName() const OVERRIDE;
+ virtual ExecutionContext* executionContext() const OVERRIDE;
static const AtomicString& toEventType(ApplicationCacheHost::EventID);
private:
explicit ApplicationCache(Frame*);
- virtual void refEventTarget() { ref(); }
- virtual void derefEventTarget() { deref(); }
- virtual EventTargetData* eventTargetData();
- virtual EventTargetData* ensureEventTargetData();
-
ApplicationCacheHost* applicationCacheHost() const;
-
- EventTargetData m_eventTargetData;
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/loader/appcache/ApplicationCacheHost.h b/chromium/third_party/WebKit/Source/core/loader/appcache/ApplicationCacheHost.h
index 8530fc15721..140558900e3 100644
--- a/chromium/third_party/WebKit/Source/core/loader/appcache/ApplicationCacheHost.h
+++ b/chromium/third_party/WebKit/Source/core/loader/appcache/ApplicationCacheHost.h
@@ -31,7 +31,7 @@
#ifndef ApplicationCacheHost_h
#define ApplicationCacheHost_h
-#include "weborigin/KURL.h"
+#include "platform/weborigin/KURL.h"
#include "wtf/Deque.h"
#include "wtf/OwnPtr.h"
#include "wtf/PassRefPtr.h"
diff --git a/chromium/third_party/WebKit/Source/core/loader/archive/ArchiveResource.cpp b/chromium/third_party/WebKit/Source/core/loader/archive/ArchiveResource.cpp
deleted file mode 100644
index ebcbadca24b..00000000000
--- a/chromium/third_party/WebKit/Source/core/loader/archive/ArchiveResource.cpp
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Copyright (C) 2008, 2010 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/loader/archive/ArchiveResource.h"
-
-#include "core/platform/SharedBuffer.h"
-
-namespace WebCore {
-
-inline ArchiveResource::ArchiveResource(PassRefPtr<SharedBuffer> data, const KURL& url, const String& mimeType, const String& textEncoding, const String& frameName, const ResourceResponse& response)
- : m_url(url)
- , m_response(response)
- , m_data(data)
- , m_mimeType(mimeType)
- , m_textEncoding(textEncoding)
- , m_frameName(frameName)
-{
- ASSERT(m_data);
-}
-
-PassRefPtr<ArchiveResource> ArchiveResource::create(PassRefPtr<SharedBuffer> data, const KURL& url, const String& mimeType, const String& textEncoding, const String& frameName, const ResourceResponse& response)
-{
- if (!data)
- return 0;
- if (response.isNull()) {
- unsigned dataSize = data->size();
- return adoptRef(new ArchiveResource(data, url, mimeType, textEncoding, frameName,
- ResourceResponse(url, mimeType, dataSize, textEncoding, String())));
- }
- return adoptRef(new ArchiveResource(data, url, mimeType, textEncoding, frameName, response));
-}
-
-PassRefPtr<ArchiveResource> ArchiveResource::create(PassRefPtr<SharedBuffer> data, const KURL& url, const ResourceResponse& response)
-{
- return create(data, url, response.mimeType(), response.textEncodingName(), String(), response);
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/loader/archive/ArchiveResource.h b/chromium/third_party/WebKit/Source/core/loader/archive/ArchiveResource.h
deleted file mode 100644
index df6a949b0af..00000000000
--- a/chromium/third_party/WebKit/Source/core/loader/archive/ArchiveResource.h
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Copyright (C) 2008, 2010 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ArchiveResource_h
-#define ArchiveResource_h
-
-#include "core/platform/SharedBuffer.h"
-#include "core/platform/network/ResourceResponse.h"
-#include "weborigin/KURL.h"
-#include "wtf/RefCounted.h"
-#include "wtf/RefPtr.h"
-
-namespace WebCore {
-
-class ArchiveResource : public RefCounted<ArchiveResource> {
-public:
- static PassRefPtr<ArchiveResource> create(PassRefPtr<SharedBuffer>, const KURL&, const ResourceResponse&);
- static PassRefPtr<ArchiveResource> create(PassRefPtr<SharedBuffer>, const KURL&,
- const String& mimeType, const String& textEncoding, const String& frameName,
- const ResourceResponse& = ResourceResponse());
-
- const KURL& url() const { return m_url; }
- const ResourceResponse& response() const { return m_response; }
- SharedBuffer* data() const { return m_data.get(); }
- const String& mimeType() const { return m_mimeType; }
- const String& textEncoding() const { return m_textEncoding; }
- const String& frameName() const { return m_frameName; }
-
-private:
- ArchiveResource(PassRefPtr<SharedBuffer>, const KURL&, const String& mimeType, const String& textEncoding, const String& frameName, const ResourceResponse&);
-
- KURL m_url;
- ResourceResponse m_response;
- RefPtr<SharedBuffer> m_data;
- String m_mimeType;
- String m_textEncoding;
- String m_frameName;
-};
-
-}
-
-#endif // ArchiveResource_h
diff --git a/chromium/third_party/WebKit/Source/core/loader/archive/ArchiveResourceCollection.cpp b/chromium/third_party/WebKit/Source/core/loader/archive/ArchiveResourceCollection.cpp
deleted file mode 100644
index 06b24301ef4..00000000000
--- a/chromium/third_party/WebKit/Source/core/loader/archive/ArchiveResourceCollection.cpp
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * Copyright (C) 2008 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/loader/archive/ArchiveResourceCollection.h"
-
-#include "weborigin/KURL.h"
-
-namespace WebCore {
-
-ArchiveResourceCollection::ArchiveResourceCollection()
-{
-}
-
-void ArchiveResourceCollection::addAllResources(MHTMLArchive* archive)
-{
- ASSERT(archive);
- if (!archive)
- return;
-
- const Vector<RefPtr<ArchiveResource> >& subresources = archive->subresources();
- for (Vector<RefPtr<ArchiveResource> >::const_iterator iterator = subresources.begin(); iterator != subresources.end(); ++iterator)
- m_subresources.set((*iterator)->url(), iterator->get());
-
- const Vector<RefPtr<MHTMLArchive> >& subframes = archive->subframeArchives();
- for (Vector<RefPtr<MHTMLArchive> >::const_iterator iterator = subframes.begin(); iterator != subframes.end(); ++iterator) {
- RefPtr<MHTMLArchive> archive = *iterator;
- ASSERT(archive->mainResource());
-
- const String& frameName = archive->mainResource()->frameName();
- if (!frameName.isNull())
- m_subframes.set(frameName, archive.get());
- else {
- // In the MHTML case, frames don't have a name so we use the URL instead.
- m_subframes.set(archive->mainResource()->url().string(), archive.get());
- }
- }
-}
-
-// FIXME: Adding a resource directly to a DocumentLoader/ArchiveResourceCollection seems like bad design, but is API some apps rely on.
-// Can we change the design in a manner that will let us deprecate that API without reducing functionality of those apps?
-void ArchiveResourceCollection::addResource(PassRefPtr<ArchiveResource> resource)
-{
- ASSERT(resource);
- if (!resource)
- return;
-
- const KURL& url = resource->url(); // get before passing PassRefPtr (which sets it to 0)
- m_subresources.set(url, resource);
-}
-
-ArchiveResource* ArchiveResourceCollection::archiveResourceForURL(const KURL& url)
-{
- ArchiveResource* resource = m_subresources.get(url);
- if (!resource)
- return 0;
-
- return resource;
-}
-
-PassRefPtr<MHTMLArchive> ArchiveResourceCollection::popSubframeArchive(const String& frameName, const KURL& url)
-{
- RefPtr<MHTMLArchive> archive = m_subframes.take(frameName);
- if (archive)
- return archive.release();
-
- return m_subframes.take(url.string());
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/loader/archive/ArchiveResourceCollection.h b/chromium/third_party/WebKit/Source/core/loader/archive/ArchiveResourceCollection.h
deleted file mode 100644
index 4b66573f69e..00000000000
--- a/chromium/third_party/WebKit/Source/core/loader/archive/ArchiveResourceCollection.h
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Copyright (C) 2008 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ArchiveResourceCollection_h
-#define ArchiveResourceCollection_h
-
-#include "core/loader/archive/ArchiveResource.h"
-#include "core/loader/archive/MHTMLArchive.h"
-#include "wtf/HashMap.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class KURL;
-
-class ArchiveResourceCollection {
- WTF_MAKE_NONCOPYABLE(ArchiveResourceCollection); WTF_MAKE_FAST_ALLOCATED;
-public:
- ArchiveResourceCollection();
-
- void addResource(PassRefPtr<ArchiveResource>);
- void addAllResources(MHTMLArchive*);
-
- ArchiveResource* archiveResourceForURL(const KURL&);
- PassRefPtr<MHTMLArchive> popSubframeArchive(const String& frameName, const KURL&);
-
-private:
- HashMap<String, RefPtr<ArchiveResource> > m_subresources;
- HashMap<String, RefPtr<MHTMLArchive> > m_subframes;
-};
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/loader/archive/DEPS b/chromium/third_party/WebKit/Source/core/loader/archive/DEPS
deleted file mode 100644
index f91aaec8510..00000000000
--- a/chromium/third_party/WebKit/Source/core/loader/archive/DEPS
+++ /dev/null
@@ -1,9 +0,0 @@
-# Please run Tools/Scripts/check-blink-deps after modifying this file.
-
-include_rules = [
- # core/loader/archive should not depend on anything in core,
- # except for itself and core/platform.
- "-core",
- "+core/loader/archive",
- "+core/platform",
-]
diff --git a/chromium/third_party/WebKit/Source/core/loader/archive/MHTMLArchive.cpp b/chromium/third_party/WebKit/Source/core/loader/archive/MHTMLArchive.cpp
deleted file mode 100644
index 90cdb2cebcd..00000000000
--- a/chromium/third_party/WebKit/Source/core/loader/archive/MHTMLArchive.cpp
+++ /dev/null
@@ -1,235 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/loader/archive/MHTMLArchive.h"
-
-#include "core/loader/archive/MHTMLParser.h"
-#include "core/platform/MIMETypeRegistry.h"
-#include "core/platform/SerializedResource.h"
-#include "core/platform/SharedBuffer.h"
-#include "core/platform/text/QuotedPrintable.h"
-#include "weborigin/SchemeRegistry.h"
-#include "wtf/CryptographicallyRandomNumber.h"
-#include "wtf/DateMath.h"
-#include "wtf/GregorianDateTime.h"
-#include "wtf/text/Base64.h"
-#include "wtf/text/StringBuilder.h"
-
-namespace WebCore {
-
-const char* const quotedPrintable = "quoted-printable";
-const char* const base64 = "base64";
-const char* const binary = "binary";
-
-static String generateRandomBoundary()
-{
- // Trying to generate random boundaries similar to IE/UnMHT (ex: ----=_NextPart_000_001B_01CC157B.96F808A0).
- const size_t randomValuesLength = 10;
- char randomValues[randomValuesLength];
- cryptographicallyRandomValues(&randomValues, randomValuesLength);
- StringBuilder stringBuilder;
- stringBuilder.append("----=_NextPart_000_");
- for (size_t i = 0; i < randomValuesLength; ++i) {
- if (i == 2)
- stringBuilder.append('_');
- else if (i == 6)
- stringBuilder.append('.');
- stringBuilder.append(lowerNibbleToASCIIHexDigit(randomValues[i]));
- stringBuilder.append(upperNibbleToASCIIHexDigit(randomValues[i]));
- }
- return stringBuilder.toString();
-}
-
-static String replaceNonPrintableCharacters(const String& text)
-{
- StringBuilder stringBuilder;
- for (size_t i = 0; i < text.length(); ++i) {
- if (isASCIIPrintable(text[i]))
- stringBuilder.append(text[i]);
- else
- stringBuilder.append('?');
- }
- return stringBuilder.toString();
-}
-
-MHTMLArchive::MHTMLArchive()
-{
-}
-
-MHTMLArchive::~MHTMLArchive()
-{
- // Because all frames know about each other we need to perform a deep clearing of the archives graph.
- clearAllSubframeArchives();
-}
-
-PassRefPtr<MHTMLArchive> MHTMLArchive::create()
-{
- return adoptRef(new MHTMLArchive);
-}
-
-PassRefPtr<MHTMLArchive> MHTMLArchive::create(const KURL& url, SharedBuffer* data)
-{
- // For security reasons we only load MHTML pages from local URLs.
- if (!SchemeRegistry::shouldTreatURLSchemeAsLocal(url.protocol()))
- return 0;
-
- MHTMLParser parser(data);
- RefPtr<MHTMLArchive> mainArchive = parser.parseArchive();
- if (!mainArchive)
- return 0; // Invalid MHTML file.
-
- // Since MHTML is a flat format, we need to make all frames aware of all resources.
- for (size_t i = 0; i < parser.frameCount(); ++i) {
- RefPtr<MHTMLArchive> archive = parser.frameAt(i);
- for (size_t j = 1; j < parser.frameCount(); ++j) {
- if (i != j)
- archive->addSubframeArchive(parser.frameAt(j));
- }
- for (size_t j = 0; j < parser.subResourceCount(); ++j)
- archive->addSubresource(parser.subResourceAt(j));
- }
- return mainArchive.release();
-}
-
-PassRefPtr<SharedBuffer> MHTMLArchive::generateMHTMLData(const Vector<SerializedResource>& resources, EncodingPolicy encodingPolicy, const String& title, const String& mimeType)
-{
- String boundary = generateRandomBoundary();
- String endOfResourceBoundary = "--" + boundary + "\r\n";
-
- GregorianDateTime now;
- now.setToCurrentLocalTime();
- String dateString = makeRFC2822DateString(now.weekDay(), now.monthDay(), now.month(), now.year(), now.hour(), now.minute(), now.second(), now.utcOffset() / 60);
-
- StringBuilder stringBuilder;
- stringBuilder.append("From: <Saved by WebKit>\r\n");
- stringBuilder.append("Subject: ");
- // We replace non ASCII characters with '?' characters to match IE's behavior.
- stringBuilder.append(replaceNonPrintableCharacters(title));
- stringBuilder.append("\r\nDate: ");
- stringBuilder.append(dateString);
- stringBuilder.append("\r\nMIME-Version: 1.0\r\n");
- stringBuilder.append("Content-Type: multipart/related;\r\n");
- stringBuilder.append("\ttype=\"");
- stringBuilder.append(mimeType);
- stringBuilder.append("\";\r\n");
- stringBuilder.append("\tboundary=\"");
- stringBuilder.append(boundary);
- stringBuilder.append("\"\r\n\r\n");
-
- // We use utf8() below instead of ascii() as ascii() replaces CRLFs with ?? (we still only have put ASCII characters in it).
- ASSERT(stringBuilder.toString().containsOnlyASCII());
- CString asciiString = stringBuilder.toString().utf8();
- RefPtr<SharedBuffer> mhtmlData = SharedBuffer::create();
- mhtmlData->append(asciiString.data(), asciiString.length());
-
- for (size_t i = 0; i < resources.size(); ++i) {
- const SerializedResource& resource = resources[i];
-
- stringBuilder.clear();
- stringBuilder.append(endOfResourceBoundary);
- stringBuilder.append("Content-Type: ");
- stringBuilder.append(resource.mimeType);
-
- const char* contentEncoding = 0;
- if (encodingPolicy == UseBinaryEncoding)
- contentEncoding = binary;
- else if (MIMETypeRegistry::isSupportedJavaScriptMIMEType(resource.mimeType) || MIMETypeRegistry::isSupportedNonImageMIMEType(resource.mimeType))
- contentEncoding = quotedPrintable;
- else
- contentEncoding = base64;
-
- stringBuilder.append("\r\nContent-Transfer-Encoding: ");
- stringBuilder.append(contentEncoding);
- stringBuilder.append("\r\nContent-Location: ");
- stringBuilder.append(resource.url);
- stringBuilder.append("\r\n\r\n");
-
- asciiString = stringBuilder.toString().utf8();
- mhtmlData->append(asciiString.data(), asciiString.length());
-
- if (!strcmp(contentEncoding, binary)) {
- const char* data;
- size_t position = 0;
- while (size_t length = resource.data->getSomeData(data, position)) {
- mhtmlData->append(data, length);
- position += length;
- }
- } else {
- // FIXME: ideally we would encode the content as a stream without having to fetch it all.
- const char* data = resource.data->data();
- size_t dataLength = resource.data->size();
- Vector<char> encodedData;
- if (!strcmp(contentEncoding, quotedPrintable)) {
- quotedPrintableEncode(data, dataLength, encodedData);
- mhtmlData->append(encodedData.data(), encodedData.size());
- mhtmlData->append("\r\n", 2);
- } else {
- ASSERT(!strcmp(contentEncoding, base64));
- // We are not specifying insertLFs = true below as it would cut the lines with LFs and MHTML requires CRLFs.
- base64Encode(data, dataLength, encodedData);
- const size_t maximumLineLength = 76;
- size_t index = 0;
- size_t encodedDataLength = encodedData.size();
- do {
- size_t lineLength = std::min(encodedDataLength - index, maximumLineLength);
- mhtmlData->append(encodedData.data() + index, lineLength);
- mhtmlData->append("\r\n", 2);
- index += maximumLineLength;
- } while (index < encodedDataLength);
- }
- }
- }
-
- asciiString = String("--" + boundary + "--\r\n").utf8();
- mhtmlData->append(asciiString.data(), asciiString.length());
-
- return mhtmlData.release();
-}
-
-void MHTMLArchive::clearAllSubframeArchives()
-{
- Vector<RefPtr<MHTMLArchive> > clearedArchives;
- clearAllSubframeArchivesImpl(&clearedArchives);
-}
-
-void MHTMLArchive::clearAllSubframeArchivesImpl(Vector<RefPtr<MHTMLArchive> >* clearedArchives)
-{
- for (Vector<RefPtr<MHTMLArchive> >::iterator it = m_subframeArchives.begin(); it != m_subframeArchives.end(); ++it) {
- if (!clearedArchives->contains(*it)) {
- clearedArchives->append(*it);
- (*it)->clearAllSubframeArchivesImpl(clearedArchives);
- }
- }
- m_subframeArchives.clear();
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/loader/archive/MHTMLArchive.h b/chromium/third_party/WebKit/Source/core/loader/archive/MHTMLArchive.h
deleted file mode 100644
index d102afdb81f..00000000000
--- a/chromium/third_party/WebKit/Source/core/loader/archive/MHTMLArchive.h
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef MHTMLArchive_h
-#define MHTMLArchive_h
-
-#include "core/loader/archive/ArchiveResource.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/RefPtr.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-class KURL;
-class MHTMLParser;
-class SharedBuffer;
-
-struct SerializedResource;
-
-class MHTMLArchive : public RefCounted<MHTMLArchive> {
-public:
- static PassRefPtr<MHTMLArchive> create();
- static PassRefPtr<MHTMLArchive> create(const KURL&, SharedBuffer*);
-
- enum EncodingPolicy {
- UseDefaultEncoding,
- UseBinaryEncoding
- };
-
- // Binary encoding results in smaller MHTML files but they might not work in other browsers.
- static PassRefPtr<SharedBuffer> generateMHTMLData(const Vector<SerializedResource>&, EncodingPolicy, const String& title, const String& mimeType);
-
- virtual ~MHTMLArchive();
- ArchiveResource* mainResource() { return m_mainResource.get(); }
- const Vector<RefPtr<ArchiveResource> >& subresources() const { return m_subresources; }
- const Vector<RefPtr<MHTMLArchive> >& subframeArchives() const { return m_subframeArchives; }
-
-private:
- friend class MHTMLParser;
- MHTMLArchive();
-
- void setMainResource(PassRefPtr<ArchiveResource> mainResource) { m_mainResource = mainResource; }
- void addSubresource(PassRefPtr<ArchiveResource> subResource) { m_subresources.append(subResource); }
- void addSubframeArchive(PassRefPtr<MHTMLArchive> subframeArchive) { m_subframeArchives.append(subframeArchive); }
-
- void clearAllSubframeArchives();
- void clearAllSubframeArchivesImpl(Vector<RefPtr<MHTMLArchive> >* clearedArchives);
-
- RefPtr<ArchiveResource> m_mainResource;
- Vector<RefPtr<ArchiveResource> > m_subresources;
- Vector<RefPtr<MHTMLArchive> > m_subframeArchives;
-};
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/loader/archive/MHTMLParser.cpp b/chromium/third_party/WebKit/Source/core/loader/archive/MHTMLParser.cpp
deleted file mode 100644
index 6bab361df34..00000000000
--- a/chromium/third_party/WebKit/Source/core/loader/archive/MHTMLParser.cpp
+++ /dev/null
@@ -1,247 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/loader/archive/MHTMLParser.h"
-
-#include "core/loader/archive/MHTMLArchive.h"
-#include "core/platform/MIMETypeRegistry.h"
-#include "core/platform/network/MIMEHeader.h"
-#include "core/platform/text/QuotedPrintable.h"
-#include "wtf/text/Base64.h"
-
-namespace WebCore {
-
-static bool skipLinesUntilBoundaryFound(SharedBufferChunkReader& lineReader, const String& boundary)
-{
- String line;
- while (!(line = lineReader.nextChunkAsUTF8StringWithLatin1Fallback()).isNull()) {
- if (line == boundary)
- return true;
- }
- return false;
-}
-
-MHTMLParser::MHTMLParser(SharedBuffer* data)
- : m_lineReader(data, "\r\n")
-{
-}
-
-PassRefPtr<MHTMLArchive> MHTMLParser::parseArchive()
-{
- RefPtr<MIMEHeader> header = MIMEHeader::parseHeader(&m_lineReader);
- return parseArchiveWithHeader(header.get());
-}
-
-PassRefPtr<MHTMLArchive> MHTMLParser::parseArchiveWithHeader(MIMEHeader* header)
-{
- if (!header) {
- LOG_ERROR("Failed to parse MHTML part: no header.");
- return 0;
- }
-
- RefPtr<MHTMLArchive> archive = MHTMLArchive::create();
- if (!header->isMultipart()) {
- // With IE a page with no resource is not multi-part.
- bool endOfArchiveReached = false;
- RefPtr<ArchiveResource> resource = parseNextPart(*header, String(), String(), endOfArchiveReached);
- if (!resource)
- return 0;
- archive->setMainResource(resource);
- return archive;
- }
-
- // Skip the message content (it's a generic browser specific message).
- skipLinesUntilBoundaryFound(m_lineReader, header->endOfPartBoundary());
-
- bool endOfArchive = false;
- while (!endOfArchive) {
- RefPtr<MIMEHeader> resourceHeader = MIMEHeader::parseHeader(&m_lineReader);
- if (!resourceHeader) {
- LOG_ERROR("Failed to parse MHTML, invalid MIME header.");
- return 0;
- }
- if (resourceHeader->contentType() == "multipart/alternative") {
- // Ignore IE nesting which makes little sense (IE seems to nest only some of the frames).
- RefPtr<MHTMLArchive> subframeArchive = parseArchiveWithHeader(resourceHeader.get());
- if (!subframeArchive) {
- LOG_ERROR("Failed to parse MHTML subframe.");
- return 0;
- }
- bool endOfPartReached = skipLinesUntilBoundaryFound(m_lineReader, header->endOfPartBoundary());
- ASSERT_UNUSED(endOfPartReached, endOfPartReached);
- // The top-frame is the first frame found, regardless of the nesting level.
- if (subframeArchive->mainResource())
- addResourceToArchive(subframeArchive->mainResource(), archive.get());
- archive->addSubframeArchive(subframeArchive);
- continue;
- }
-
- RefPtr<ArchiveResource> resource = parseNextPart(*resourceHeader, header->endOfPartBoundary(), header->endOfDocumentBoundary(), endOfArchive);
- if (!resource) {
- LOG_ERROR("Failed to parse MHTML part.");
- return 0;
- }
- addResourceToArchive(resource.get(), archive.get());
- }
-
- return archive.release();
-}
-
-void MHTMLParser::addResourceToArchive(ArchiveResource* resource, MHTMLArchive* archive)
-{
- const String& mimeType = resource->mimeType();
- if (!MIMETypeRegistry::isSupportedNonImageMIMEType(mimeType) || MIMETypeRegistry::isSupportedJavaScriptMIMEType(mimeType) || mimeType == "text/css") {
- m_resources.append(resource);
- return;
- }
-
- // The first document suitable resource is the main frame.
- if (!archive->mainResource()) {
- archive->setMainResource(resource);
- m_frames.append(archive);
- return;
- }
-
- RefPtr<MHTMLArchive> subframe = MHTMLArchive::create();
- subframe->setMainResource(resource);
- m_frames.append(subframe);
-}
-
-PassRefPtr<ArchiveResource> MHTMLParser::parseNextPart(const MIMEHeader& mimeHeader, const String& endOfPartBoundary, const String& endOfDocumentBoundary, bool& endOfArchiveReached)
-{
- ASSERT(endOfPartBoundary.isEmpty() == endOfDocumentBoundary.isEmpty());
-
- // If no content transfer encoding is specified, default to binary encoding.
- MIMEHeader::Encoding contentTransferEncoding = mimeHeader.contentTransferEncoding();
- if (contentTransferEncoding == MIMEHeader::Unknown)
- contentTransferEncoding = MIMEHeader::Binary;
-
- RefPtr<SharedBuffer> content = SharedBuffer::create();
- const bool checkBoundary = !endOfPartBoundary.isEmpty();
- bool endOfPartReached = false;
- if (contentTransferEncoding == MIMEHeader::Binary) {
- if (!checkBoundary) {
- LOG_ERROR("Binary contents requires end of part");
- return 0;
- }
- m_lineReader.setSeparator(endOfPartBoundary.utf8().data());
- Vector<char> part;
- if (!m_lineReader.nextChunk(part)) {
- LOG_ERROR("Binary contents requires end of part");
- return 0;
- }
- content->append(part);
- m_lineReader.setSeparator("\r\n");
- Vector<char> nextChars;
- if (m_lineReader.peek(nextChars, 2) != 2) {
- LOG_ERROR("Invalid seperator.");
- return 0;
- }
- endOfPartReached = true;
- ASSERT(nextChars.size() == 2);
- endOfArchiveReached = (nextChars[0] == '-' && nextChars[1] == '-');
- if (!endOfArchiveReached) {
- String line = m_lineReader.nextChunkAsUTF8StringWithLatin1Fallback();
- if (!line.isEmpty()) {
- LOG_ERROR("No CRLF at end of binary section.");
- return 0;
- }
- }
- } else {
- String line;
- while (!(line = m_lineReader.nextChunkAsUTF8StringWithLatin1Fallback()).isNull()) {
- endOfArchiveReached = (line == endOfDocumentBoundary);
- if (checkBoundary && (line == endOfPartBoundary || endOfArchiveReached)) {
- endOfPartReached = true;
- break;
- }
- // Note that we use line.utf8() and not line.ascii() as ascii turns special characters (such as tab, line-feed...) into '?'.
- content->append(line.utf8().data(), line.length());
- if (contentTransferEncoding == MIMEHeader::QuotedPrintable) {
- // The line reader removes the \r\n, but we need them for the content in this case as the QuotedPrintable decoder expects CR-LF terminated lines.
- content->append("\r\n", 2);
- }
- }
- }
- if (!endOfPartReached && checkBoundary) {
- LOG_ERROR("No bounday found for MHTML part.");
- return 0;
- }
-
- Vector<char> data;
- switch (contentTransferEncoding) {
- case MIMEHeader::Base64:
- if (!base64Decode(content->data(), content->size(), data)) {
- LOG_ERROR("Invalid base64 content for MHTML part.");
- return 0;
- }
- break;
- case MIMEHeader::QuotedPrintable:
- quotedPrintableDecode(content->data(), content->size(), data);
- break;
- case MIMEHeader::EightBit:
- case MIMEHeader::SevenBit:
- case MIMEHeader::Binary:
- data.append(content->data(), content->size());
- break;
- default:
- LOG_ERROR("Invalid encoding for MHTML part.");
- return 0;
- }
- RefPtr<SharedBuffer> contentBuffer = SharedBuffer::adoptVector(data);
- // FIXME: the URL in the MIME header could be relative, we should resolve it if it is.
- // The specs mentions 5 ways to resolve a URL: http://tools.ietf.org/html/rfc2557#section-5
- // IE and Firefox (UNMht) seem to generate only absolute URLs.
- KURL location = KURL(KURL(), mimeHeader.contentLocation());
- return ArchiveResource::create(contentBuffer, location, mimeHeader.contentType(), mimeHeader.charset(), String());
-}
-
-size_t MHTMLParser::frameCount() const
-{
- return m_frames.size();
-}
-
-MHTMLArchive* MHTMLParser::frameAt(size_t index) const
-{
- return m_frames[index].get();
-}
-
-size_t MHTMLParser::subResourceCount() const
-{
- return m_resources.size();
-}
-
-ArchiveResource* MHTMLParser::subResourceAt(size_t index) const
-{
- return m_resources[index].get();
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/loader/archive/MHTMLParser.h b/chromium/third_party/WebKit/Source/core/loader/archive/MHTMLParser.h
deleted file mode 100644
index dda8bd34018..00000000000
--- a/chromium/third_party/WebKit/Source/core/loader/archive/MHTMLParser.h
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef MHTMLParser_h
-#define MHTMLParser_h
-
-#include "core/platform/SharedBufferChunkReader.h"
-#include "wtf/RefPtr.h"
-#include "wtf/Vector.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class ArchiveResource;
-class MHTMLArchive;
-class MIMEHeader;
-class SharedBuffer;
-
-class MHTMLParser {
-public:
- explicit MHTMLParser(SharedBuffer*);
-
- PassRefPtr<MHTMLArchive> parseArchive();
-
- size_t frameCount() const;
- MHTMLArchive* frameAt(size_t) const;
-
- size_t subResourceCount() const;
- ArchiveResource* subResourceAt(size_t) const;
-
-private:
- PassRefPtr<MHTMLArchive> parseArchiveWithHeader(MIMEHeader*);
- PassRefPtr<ArchiveResource> parseNextPart(const MIMEHeader&, const String& endOfPartBoundary, const String& endOfDocumentBoundary, bool& endOfArchiveReached);
-
- void addResourceToArchive(ArchiveResource*, MHTMLArchive*);
-
- SharedBufferChunkReader m_lineReader;
- Vector<RefPtr<ArchiveResource> > m_resources;
- Vector<RefPtr<MHTMLArchive> > m_frames;
-};
-
-}
-
-#endif
-
diff --git a/chromium/third_party/WebKit/Source/core/make_core_derived_sources.xml b/chromium/third_party/WebKit/Source/core/make_core_derived_sources.xml
new file mode 100644
index 00000000000..c69aaa610bf
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/make_core_derived_sources.xml
@@ -0,0 +1,68 @@
+<?xml version="1.0" encoding="utf-8"?>
+<ProjectSchemaDefinitions xmlns="clr-namespace:Microsoft.Build.Framework.XamlTypes;assembly=Microsoft.Build.Framework" xmlns:sys="clr-namespace:System;assembly=mscorlib" xmlns:transformCallback="Microsoft.Cpp.Dev10.ConvertPropertyCallback" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
+ <Rule DisplayName="bison" Name="bison" Order="200" PageTemplate="tool">
+ <Rule.DataSource>
+ <DataSource ItemType="bison" Persistence="ProjectFile"/>
+ </Rule.DataSource>
+ <Rule.Categories>
+ <Category Name="General">
+ <Category.DisplayName>
+ <sys:String>General</sys:String>
+ </Category.DisplayName>
+ </Category>
+ <Category Name="Command Line" Subtype="CommandLine">
+ <Category.DisplayName>
+ <sys:String>Command Line</sys:String>
+ </Category.DisplayName>
+ </Category>
+ </Rule.Categories>
+ <StringListProperty Category="Command Line" IsRequired="true" Name="Inputs" Switch=" ">
+ <StringListProperty.DataSource>
+ <DataSource ItemType="bison" Persistence="ProjectFile" SourceType="Item"/>
+ </StringListProperty.DataSource>
+ </StringListProperty>
+ <StringProperty DisplayName="Command Line" IncludeInCommandLine="False" Name="CommandLineTemplate" Visible="False"/>
+ <DynamicEnumProperty Category="General" EnumProvider="Targets" IncludeInCommandLine="False" Name="bisonBeforeTargets">
+ <DynamicEnumProperty.DisplayName>
+ <sys:String>Execute Before</sys:String>
+ </DynamicEnumProperty.DisplayName>
+ <DynamicEnumProperty.Description>
+ <sys:String>Specifies the targets for the build customization to run before.</sys:String>
+ </DynamicEnumProperty.Description>
+ <DynamicEnumProperty.ProviderSettings>
+ <NameValuePair Name="Exclude" Value="^bisonBeforeTargets|^Compute"/>
+ </DynamicEnumProperty.ProviderSettings>
+ <DynamicEnumProperty.DataSource>
+ <DataSource HasConfigurationCondition="true" Persistence="ProjectFile"/>
+ </DynamicEnumProperty.DataSource>
+ </DynamicEnumProperty>
+ <DynamicEnumProperty Category="General" EnumProvider="Targets" IncludeInCommandLine="False" Name="bisonAfterTargets">
+ <DynamicEnumProperty.DisplayName>
+ <sys:String>Execute After</sys:String>
+ </DynamicEnumProperty.DisplayName>
+ <DynamicEnumProperty.Description>
+ <sys:String>Specifies the targets for the build customization to run after.</sys:String>
+ </DynamicEnumProperty.Description>
+ <DynamicEnumProperty.ProviderSettings>
+ <NameValuePair Name="Exclude" Value="^bisonAfterTargets|^Compute"/>
+ </DynamicEnumProperty.ProviderSettings>
+ <DynamicEnumProperty.DataSource>
+ <DataSource HasConfigurationCondition="true" ItemType="" Persistence="ProjectFile"/>
+ </DynamicEnumProperty.DataSource>
+ </DynamicEnumProperty>
+ <StringListProperty DisplayName="Outputs" IncludeInCommandLine="False" Name="Outputs" Visible="False"/>
+ <StringProperty DisplayName="Execution Description" IncludeInCommandLine="False" Name="ExecutionDescription" Visible="False"/>
+ <StringListProperty DisplayName="Additional Dependencies" IncludeInCommandLine="False" Name="AdditionalDependencies" Visible="false"/>
+ <StringProperty Category="Command Line" Name="AdditionalOptions" Subtype="AdditionalOptions">
+ <StringProperty.DisplayName>
+ <sys:String>Additional Options</sys:String>
+ </StringProperty.DisplayName>
+ <StringProperty.Description>
+ <sys:String>Additional Options</sys:String>
+ </StringProperty.Description>
+ </StringProperty>
+ </Rule>
+ <ItemType DisplayName="bison" Name="bison"/>
+ <FileExtension ContentType="bison" Name="*.y"/>
+ <ContentType DisplayName="" ItemType="bison" Name="bison"/>
+</ProjectSchemaDefinitions>
diff --git a/chromium/third_party/WebKit/Source/core/mathml/mathtags.in b/chromium/third_party/WebKit/Source/core/mathml/mathtags.in
deleted file mode 100644
index 95688e1a6b2..00000000000
--- a/chromium/third_party/WebKit/Source/core/mathml/mathtags.in
+++ /dev/null
@@ -1,15 +0,0 @@
-namespace="MathML"
-namespaceURI="http://www.w3.org/1998/Math/MathML"
-
-math
-mi
-mn
-mo
-mtext
-
-#if 0 // Curently only for MathMLNames used by HTMLTreeBuilder.
-ms
-mglyph
-malignmark
-annotation-xml
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/page/AbstractView.idl b/chromium/third_party/WebKit/Source/core/page/AbstractView.idl
deleted file mode 100644
index 60c537f5550..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/AbstractView.idl
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Copyright (C) 2006 Apple Computer, Inc. All rights reserved.
- * Copyright (C) 2006 Samuel Weinig <sam.weinig@gmail.com>
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-// Introduced in DOM Level 2:
-[
-
-] interface AbstractView {
- readonly attribute Document document;
- readonly attribute StyleMedia styleMedia;
-};
-
diff --git a/chromium/third_party/WebKit/Source/core/page/AutoscrollController.cpp b/chromium/third_party/WebKit/Source/core/page/AutoscrollController.cpp
index 257bb7dbc76..6c460280b17 100644
--- a/chromium/third_party/WebKit/Source/core/page/AutoscrollController.cpp
+++ b/chromium/third_party/WebKit/Source/core/page/AutoscrollController.cpp
@@ -1,4 +1,5 @@
/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
* Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
* Copyright (C) 2006 Alexey Proskuryakov (ap@webkit.org)
* Copyright (C) 2012 Digia Plc. and/or its subsidiary(-ies)
@@ -29,8 +30,9 @@
#include "core/page/AutoscrollController.h"
#include "core/page/EventHandler.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameView.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
+#include "core/page/Chrome.h"
#include "core/page/Page.h"
#include "core/rendering/HitTestResult.h"
#include "core/rendering/RenderBox.h"
@@ -41,16 +43,13 @@ namespace WebCore {
// Delay time in second for start autoscroll if pointer is in border edge of scrollable element.
static double autoscrollDelay = 0.2;
-// When the autoscroll or the panScroll is triggered when do the scroll every 0.05s to make it smooth
-static const double autoscrollInterval = 0.05;
-
-PassOwnPtr<AutoscrollController> AutoscrollController::create()
+PassOwnPtr<AutoscrollController> AutoscrollController::create(Page& page)
{
- return adoptPtr(new AutoscrollController());
+ return adoptPtr(new AutoscrollController(page));
}
-AutoscrollController::AutoscrollController()
- : m_autoscrollTimer(this, &AutoscrollController::autoscrollTimerFired)
+AutoscrollController::AutoscrollController(Page& page)
+ : m_page(page)
, m_autoscrollRenderer(0)
, m_autoscrollType(NoAutoscroll)
, m_dragAndDropAutoscrollStartTime(0)
@@ -70,20 +69,19 @@ bool AutoscrollController::autoscrollInProgress(const RenderBox* renderer) const
void AutoscrollController::startAutoscrollForSelection(RenderObject* renderer)
{
// We don't want to trigger the autoscroll or the panScroll if it's already active
- if (m_autoscrollTimer.isActive())
+ if (m_autoscrollType != NoAutoscroll)
return;
RenderBox* scrollable = RenderBox::findAutoscrollable(renderer);
if (!scrollable)
return;
m_autoscrollType = AutoscrollForSelection;
m_autoscrollRenderer = scrollable;
- startAutoscrollTimer();
+ startAutoscroll();
}
-void AutoscrollController::stopAutoscrollTimer()
+void AutoscrollController::stopAutoscroll()
{
RenderBox* scrollable = m_autoscrollRenderer;
- m_autoscrollTimer.stop();
m_autoscrollRenderer = 0;
if (!scrollable)
@@ -108,7 +106,6 @@ void AutoscrollController::stopAutoscrollIfNeeded(RenderObject* renderer)
return;
m_autoscrollRenderer = 0;
m_autoscrollType = NoAutoscroll;
- m_autoscrollTimer.stop();
}
void AutoscrollController::updateAutoscrollRenderer()
@@ -119,7 +116,7 @@ void AutoscrollController::updateAutoscrollRenderer()
RenderObject* renderer = m_autoscrollRenderer;
#if OS(WIN)
- HitTestResult hitTest = renderer->frame()->eventHandler()->hitTestResultAtPoint(m_panScrollStartPos, HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::DisallowShadowContent);
+ HitTestResult hitTest = renderer->frame()->eventHandler().hitTestResultAtPoint(m_panScrollStartPos, HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent);
if (Node* nodeAtPoint = hitTest.innerNode())
renderer = nodeAtPoint->renderer();
@@ -133,7 +130,7 @@ void AutoscrollController::updateAutoscrollRenderer()
void AutoscrollController::updateDragAndDrop(Node* dropTargetNode, const IntPoint& eventPosition, double eventTime)
{
if (!dropTargetNode || !dropTargetNode->renderer()) {
- stopAutoscrollTimer();
+ stopAutoscroll();
return;
}
@@ -142,19 +139,19 @@ void AutoscrollController::updateDragAndDrop(Node* dropTargetNode, const IntPoin
RenderBox* scrollable = RenderBox::findAutoscrollable(dropTargetNode->renderer());
if (!scrollable) {
- stopAutoscrollTimer();
+ stopAutoscroll();
return;
}
Page* page = scrollable->frame() ? scrollable->frame()->page() : 0;
if (!page) {
- stopAutoscrollTimer();
+ stopAutoscroll();
return;
}
IntSize offset = scrollable->calculateAutoscrollDirection(eventPosition);
if (offset.isZero()) {
- stopAutoscrollTimer();
+ stopAutoscroll();
return;
}
@@ -164,7 +161,7 @@ void AutoscrollController::updateDragAndDrop(Node* dropTargetNode, const IntPoin
m_autoscrollType = AutoscrollForDragAndDrop;
m_autoscrollRenderer = scrollable;
m_dragAndDropAutoscrollStartTime = eventTime;
- startAutoscrollTimer();
+ startAutoscroll();
} else if (m_autoscrollRenderer != scrollable) {
m_dragAndDropAutoscrollStartTime = eventTime;
m_autoscrollRenderer = scrollable;
@@ -174,8 +171,7 @@ void AutoscrollController::updateDragAndDrop(Node* dropTargetNode, const IntPoin
#if OS(WIN)
void AutoscrollController::handleMouseReleaseForPanScrolling(Frame* frame, const PlatformMouseEvent& mouseEvent)
{
- Page* page = frame->page();
- if (!page || page->mainFrame() != frame)
+ if (!frame->isMainFrame())
return;
switch (m_autoscrollType) {
case AutoscrollForPan:
@@ -183,7 +179,7 @@ void AutoscrollController::handleMouseReleaseForPanScrolling(Frame* frame, const
m_autoscrollType = AutoscrollForPanCanStop;
break;
case AutoscrollForPanCanStop:
- stopAutoscrollTimer();
+ stopAutoscroll();
break;
}
}
@@ -196,7 +192,7 @@ bool AutoscrollController::panScrollInProgress() const
void AutoscrollController::startPanScrolling(RenderBox* scrollable, const IntPoint& lastKnownMousePosition)
{
// We don't want to trigger the autoscroll or the panScroll if it's already active
- if (m_autoscrollTimer.isActive())
+ if (m_autoscrollType != NoAutoscroll)
return;
m_autoscrollType = AutoscrollForPan;
@@ -205,7 +201,7 @@ void AutoscrollController::startPanScrolling(RenderBox* scrollable, const IntPoi
if (FrameView* view = scrollable->frame()->view())
view->addPanScrollIcon(lastKnownMousePosition);
- startAutoscrollTimer();
+ startAutoscroll();
}
#else
bool AutoscrollController::panScrollInProgress() const
@@ -214,26 +210,28 @@ bool AutoscrollController::panScrollInProgress() const
}
#endif
-void AutoscrollController::autoscrollTimerFired(Timer<AutoscrollController>*)
+// FIXME: This would get get better animation fidelity if it used the monotonicFrameBeginTime instead
+// of WTF::currentTime().
+void AutoscrollController::animate(double)
{
if (!m_autoscrollRenderer) {
- stopAutoscrollTimer();
+ stopAutoscroll();
return;
}
- EventHandler* eventHandler = m_autoscrollRenderer->frame()->eventHandler();
+ EventHandler& eventHandler = m_autoscrollRenderer->frame()->eventHandler();
switch (m_autoscrollType) {
case AutoscrollForDragAndDrop:
if (WTF::currentTime() - m_dragAndDropAutoscrollStartTime > autoscrollDelay)
m_autoscrollRenderer->autoscroll(m_dragAndDropAutoscrollReferencePosition);
break;
case AutoscrollForSelection:
- if (!eventHandler->mousePressed()) {
- stopAutoscrollTimer();
+ if (!eventHandler.mousePressed()) {
+ stopAutoscroll();
return;
}
- eventHandler->updateSelectionForMouseDrag();
- m_autoscrollRenderer->autoscroll(eventHandler->lastKnownMousePosition());
+ eventHandler.updateSelectionForMouseDrag();
+ m_autoscrollRenderer->autoscroll(eventHandler.lastKnownMousePosition());
break;
case NoAutoscroll:
break;
@@ -241,20 +239,22 @@ void AutoscrollController::autoscrollTimerFired(Timer<AutoscrollController>*)
case AutoscrollForPanCanStop:
case AutoscrollForPan:
if (!panScrollInProgress()) {
- stopAutoscrollTimer();
+ stopAutoscroll();
return;
}
if (FrameView* view = m_autoscrollRenderer->frame()->view())
- updatePanScrollState(view, eventHandler->lastKnownMousePosition());
+ updatePanScrollState(view, eventHandler.lastKnownMousePosition());
m_autoscrollRenderer->panScroll(m_panScrollStartPos);
break;
#endif
}
+ if (m_autoscrollType != NoAutoscroll)
+ m_page.chrome().scheduleAnimation();
}
-void AutoscrollController::startAutoscrollTimer()
+void AutoscrollController::startAutoscroll()
{
- m_autoscrollTimer.startRepeating(autoscrollInterval);
+ m_page.chrome().scheduleAnimation();
}
#if OS(WIN)
diff --git a/chromium/third_party/WebKit/Source/core/page/AutoscrollController.h b/chromium/third_party/WebKit/Source/core/page/AutoscrollController.h
index 88ed10f2593..c66b3a06bc1 100644
--- a/chromium/third_party/WebKit/Source/core/page/AutoscrollController.h
+++ b/chromium/third_party/WebKit/Source/core/page/AutoscrollController.h
@@ -26,8 +26,7 @@
#ifndef AutoscrollController_h
#define AutoscrollController_h
-#include "core/platform/Timer.h"
-#include "core/platform/graphics/IntPoint.h"
+#include "platform/geometry/IntPoint.h"
#include "wtf/PassOwnPtr.h"
namespace WebCore {
@@ -36,6 +35,7 @@ class EventHandler;
class Frame;
class FrameView;
class Node;
+class Page;
class PlatformMouseEvent;
class RenderBox;
class RenderObject;
@@ -53,12 +53,14 @@ enum AutoscrollType {
// AutscrollController handels autoscroll and pan scroll for EventHandler.
class AutoscrollController {
public:
+ static PassOwnPtr<AutoscrollController> create(Page&);
+
+ void animate(double monotonicFrameBeginTime);
bool autoscrollInProgress() const;
bool autoscrollInProgress(const RenderBox*) const;
- static PassOwnPtr<AutoscrollController> create();
bool panScrollInProgress() const;
void startAutoscrollForSelection(RenderObject*);
- void stopAutoscrollTimer();
+ void stopAutoscroll();
void stopAutoscrollIfNeeded(RenderObject*);
void updateAutoscrollRenderer();
void updateDragAndDrop(Node* targetNode, const IntPoint& eventPosition, double eventTime);
@@ -68,14 +70,15 @@ public:
#endif
private:
- AutoscrollController();
- void autoscrollTimerFired(Timer<AutoscrollController>*);
- void startAutoscrollTimer();
+ explicit AutoscrollController(Page&);
+
+ void startAutoscroll();
+
#if OS(WIN)
- void updatePanScrollState(FrameView*, const IntPoint&);
+ void updatePanScrollState(FrameView*, const IntPoint& lastKnownMousePosition);
#endif
- Timer<AutoscrollController> m_autoscrollTimer;
+ Page& m_page;
RenderBox* m_autoscrollRenderer;
AutoscrollType m_autoscrollType;
IntPoint m_dragAndDropAutoscrollReferencePosition;
diff --git a/chromium/third_party/WebKit/Source/core/page/BackForwardClient.h b/chromium/third_party/WebKit/Source/core/page/BackForwardClient.h
new file mode 100644
index 00000000000..4ff88ea85f8
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/page/BackForwardClient.h
@@ -0,0 +1,48 @@
+/*
+ * Copyright (C) 2006, 2010 Apple Inc. All rights reserved.
+ * Copyright (C) 2008 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
+ * Copyright (C) 2009 Google, Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef BackForwardClient_h
+#define BackForwardClient_h
+
+#include "wtf/PassRefPtr.h"
+
+namespace WebCore {
+
+class HistoryItem;
+
+class BackForwardClient {
+public:
+ virtual ~BackForwardClient() { }
+
+ virtual int backListCount() = 0;
+ virtual int forwardListCount() = 0;
+ virtual int backForwardListCount() = 0;
+};
+
+} // namespace WebCore
+
+#endif // BackForwardClient_h
diff --git a/chromium/third_party/WebKit/Source/core/page/BarProp.cpp b/chromium/third_party/WebKit/Source/core/page/BarProp.cpp
deleted file mode 100644
index 169d65a846a..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/BarProp.cpp
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * Copyright (C) 2007, 2010 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/page/BarProp.h"
-
-#include "core/page/Chrome.h"
-#include "core/page/Frame.h"
-#include "core/page/Page.h"
-
-namespace WebCore {
-
-BarProp::BarProp(Frame* frame, Type type)
- : DOMWindowProperty(frame)
- , m_type(type)
-{
- ScriptWrappable::init(this);
-}
-
-BarProp::Type BarProp::type() const
-{
- return m_type;
-}
-
-bool BarProp::visible() const
-{
- if (!m_frame)
- return false;
- Page* page = m_frame->page();
- if (!page)
- return false;
-
- switch (m_type) {
- case Locationbar:
- case Personalbar:
- case Toolbar:
- return page->chrome().toolbarsVisible();
- case Menubar:
- return page->chrome().menubarVisible();
- case Scrollbars:
- return page->chrome().scrollbarsVisible();
- case Statusbar:
- return page->chrome().statusbarVisible();
- }
-
- ASSERT_NOT_REACHED();
- return false;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/page/BarProp.h b/chromium/third_party/WebKit/Source/core/page/BarProp.h
deleted file mode 100644
index 9c6b7241710..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/BarProp.h
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Copyright (C) 2007 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef BarProp_h
-#define BarProp_h
-
-#include "bindings/v8/ScriptWrappable.h"
-#include "core/page/DOMWindowProperty.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-
-namespace WebCore {
-
- class Frame;
-
- class BarProp : public ScriptWrappable, public RefCounted<BarProp>, public DOMWindowProperty {
- public:
- enum Type { Locationbar, Menubar, Personalbar, Scrollbars, Statusbar, Toolbar };
-
- static PassRefPtr<BarProp> create(Frame* frame, Type type) { return adoptRef(new BarProp(frame, type)); }
-
- Type type() const;
- bool visible() const;
-
- private:
- BarProp(Frame*, Type);
- Type m_type;
- };
-
-} // namespace WebCore
-
-#endif // BarProp_h
diff --git a/chromium/third_party/WebKit/Source/core/page/Chrome.cpp b/chromium/third_party/WebKit/Source/core/page/Chrome.cpp
index 57c5838baa0..15a47637eb9 100644
--- a/chromium/third_party/WebKit/Source/core/page/Chrome.cpp
+++ b/chromium/third_party/WebKit/Source/core/page/Chrome.cpp
@@ -28,18 +28,18 @@
#include "core/html/HTMLInputElement.h"
#include "core/inspector/InspectorInstrumentation.h"
#include "core/page/ChromeClient.h"
-#include "core/page/Frame.h"
+#include "core/frame/Frame.h"
#include "core/page/FrameTree.h"
#include "core/page/Page.h"
#include "core/page/PageGroupLoadDeferrer.h"
#include "core/page/PopupOpeningObserver.h"
#include "core/page/WindowFeatures.h"
-#include "core/platform/ColorChooser.h"
-#include "core/platform/DateTimeChooser.h"
-#include "core/platform/FileChooser.h"
-#include "core/platform/graphics/FloatRect.h"
-#include "core/platform/network/DNS.h"
#include "core/rendering/HitTestResult.h"
+#include "platform/ColorChooser.h"
+#include "platform/DateTimeChooser.h"
+#include "platform/FileChooser.h"
+#include "platform/geometry/FloatRect.h"
+#include "platform/network/DNS.h"
#include "wtf/PassRefPtr.h"
#include "wtf/Vector.h"
@@ -91,7 +91,7 @@ IntRect Chrome::rootViewToScreen(const IntRect& rect) const
return m_client->rootViewToScreen(rect);
}
-WebKit::WebScreenInfo Chrome::screenInfo() const
+blink::WebScreenInfo Chrome::screenInfo() const
{
return m_client->screenInfo();
}
@@ -158,7 +158,7 @@ bool Chrome::canRunModal() const
static bool canRunModalIfDuringPageDismissal(Page* page, ChromeClient::DialogType dialog, const String& message)
{
- for (Frame* frame = page->mainFrame(); frame; frame = frame->tree()->traverseNext()) {
+ for (Frame* frame = page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
Document::PageDismissalType dismissal = frame->document()->pageDismissalEventBeingDispatched();
if (dismissal != Document::NoDismissal)
return page->chrome().client().shouldRunModalDialogDuringPageDismissal(dialog, message, dismissal);
@@ -243,10 +243,9 @@ void Chrome::runJavaScriptAlert(Frame* frame, const String& message)
ASSERT(frame);
notifyPopupOpeningObservers();
- String displayMessage = frame->displayStringModifiedByEncoding(message);
- InspectorInstrumentationCookie cookie = InspectorInstrumentation::willRunJavaScriptDialog(m_page, displayMessage);
- m_client->runJavaScriptAlert(frame, displayMessage);
+ InspectorInstrumentationCookie cookie = InspectorInstrumentation::willRunJavaScriptDialog(m_page, message);
+ m_client->runJavaScriptAlert(frame, message);
InspectorInstrumentation::didRunJavaScriptDialog(cookie);
}
@@ -261,10 +260,9 @@ bool Chrome::runJavaScriptConfirm(Frame* frame, const String& message)
ASSERT(frame);
notifyPopupOpeningObservers();
- String displayMessage = frame->displayStringModifiedByEncoding(message);
- InspectorInstrumentationCookie cookie = InspectorInstrumentation::willRunJavaScriptDialog(m_page, displayMessage);
- bool ok = m_client->runJavaScriptConfirm(frame, displayMessage);
+ InspectorInstrumentationCookie cookie = InspectorInstrumentation::willRunJavaScriptDialog(m_page, message);
+ bool ok = m_client->runJavaScriptConfirm(frame, message);
InspectorInstrumentation::didRunJavaScriptDialog(cookie);
return ok;
}
@@ -280,22 +278,18 @@ bool Chrome::runJavaScriptPrompt(Frame* frame, const String& prompt, const Strin
ASSERT(frame);
notifyPopupOpeningObservers();
- String displayPrompt = frame->displayStringModifiedByEncoding(prompt);
- InspectorInstrumentationCookie cookie = InspectorInstrumentation::willRunJavaScriptDialog(m_page, displayPrompt);
- bool ok = m_client->runJavaScriptPrompt(frame, displayPrompt, frame->displayStringModifiedByEncoding(defaultValue), result);
+ InspectorInstrumentationCookie cookie = InspectorInstrumentation::willRunJavaScriptDialog(m_page, prompt);
+ bool ok = m_client->runJavaScriptPrompt(frame, prompt, defaultValue, result);
InspectorInstrumentation::didRunJavaScriptDialog(cookie);
- if (ok)
- result = frame->displayStringModifiedByEncoding(result);
-
return ok;
}
void Chrome::setStatusbarText(Frame* frame, const String& status)
{
ASSERT(frame);
- m_client->setStatusbarText(frame->displayStringModifiedByEncoding(status));
+ m_client->setStatusbarText(status);
}
IntRect Chrome::windowResizerRect() const
@@ -365,15 +359,21 @@ PassRefPtr<DateTimeChooser> Chrome::openDateTimeChooser(DateTimeChooserClient* c
return m_client->openDateTimeChooser(client, parameters);
}
+void Chrome::openTextDataListChooser(HTMLInputElement& input)
+{
+ notifyPopupOpeningObservers();
+ m_client->openTextDataListChooser(input);
+}
+
void Chrome::runOpenPanel(Frame* frame, PassRefPtr<FileChooser> fileChooser)
{
notifyPopupOpeningObservers();
m_client->runOpenPanel(frame, fileChooser);
}
-void Chrome::dispatchViewportPropertiesDidChange(const ViewportArguments& arguments) const
+void Chrome::dispatchViewportPropertiesDidChange(const ViewportDescription& description) const
{
- m_client->dispatchViewportPropertiesDidChange(arguments);
+ m_client->dispatchViewportPropertiesDidChange(description);
}
void Chrome::setCursor(const Cursor& cursor)
diff --git a/chromium/third_party/WebKit/Source/core/page/Chrome.h b/chromium/third_party/WebKit/Source/core/page/Chrome.h
index f9171c2ae95..1c021f062d4 100644
--- a/chromium/third_party/WebKit/Source/core/page/Chrome.h
+++ b/chromium/third_party/WebKit/Source/core/page/Chrome.h
@@ -24,8 +24,8 @@
#include "core/loader/NavigationPolicy.h"
#include "core/page/FocusDirection.h"
-#include "core/platform/Cursor.h"
-#include "core/platform/HostWindow.h"
+#include "platform/Cursor.h"
+#include "platform/HostWindow.h"
#include "wtf/Forward.h"
namespace WebCore {
@@ -39,6 +39,7 @@ class FileChooser;
class FloatRect;
class Frame;
class Geolocation;
+class HTMLInputElement;
class HitTestResult;
class IntRect;
class Node;
@@ -49,7 +50,7 @@ class PopupOpeningObserver;
class SearchPopupMenu;
struct DateTimeChooserParameters;
-struct ViewportArguments;
+struct ViewportDescription;
struct WindowFeatures;
class Chrome : public HostWindow {
@@ -66,14 +67,15 @@ public:
virtual void scroll(const IntSize&, const IntRect&, const IntRect&) OVERRIDE;
virtual IntPoint screenToRootView(const IntPoint&) const OVERRIDE;
virtual IntRect rootViewToScreen(const IntRect&) const OVERRIDE;
- virtual WebKit::WebScreenInfo screenInfo() const OVERRIDE;
- virtual void setCursor(const Cursor&) OVERRIDE;
+ virtual blink::WebScreenInfo screenInfo() const OVERRIDE;
virtual void scheduleAnimation() OVERRIDE;
void contentsSizeChanged(Frame*, const IntSize&) const;
void layoutUpdated(Frame*) const;
+ void setCursor(const Cursor&);
+
void setWindowRect(const FloatRect&) const;
FloatRect windowRect() const;
@@ -120,11 +122,12 @@ public:
PassOwnPtr<ColorChooser> createColorChooser(ColorChooserClient*, const Color& initialColor);
PassRefPtr<DateTimeChooser> openDateTimeChooser(DateTimeChooserClient*, const DateTimeChooserParameters&);
+ void openTextDataListChooser(HTMLInputElement&);
void runOpenPanel(Frame*, PassRefPtr<FileChooser>);
void enumerateChosenDirectory(FileChooser*);
- void dispatchViewportPropertiesDidChange(const ViewportArguments&) const;
+ void dispatchViewportPropertiesDidChange(const ViewportDescription&) const;
bool hasOpenedPopup() const;
PassRefPtr<PopupMenu> createPopupMenu(Frame&, PopupMenuClient*) const;
diff --git a/chromium/third_party/WebKit/Source/core/page/ChromeClient.h b/chromium/third_party/WebKit/Source/core/page/ChromeClient.h
index 9eab17faada..13929c23fa4 100644
--- a/chromium/third_party/WebKit/Source/core/page/ChromeClient.h
+++ b/chromium/third_party/WebKit/Source/core/page/ChromeClient.h
@@ -26,19 +26,18 @@
#include "core/inspector/ConsoleAPITypes.h"
#include "core/loader/FrameLoader.h"
#include "core/loader/NavigationPolicy.h"
-#include "core/page/ConsoleTypes.h"
+#include "core/frame/ConsoleTypes.h"
#include "core/page/FocusDirection.h"
-#include "core/platform/Cursor.h"
-#include "core/platform/HostWindow.h"
-#include "core/platform/PopupMenu.h"
-#include "core/platform/PopupMenuClient.h"
-#include "core/platform/ScrollTypes.h"
-#include "core/platform/graphics/GraphicsContext.h"
#include "core/rendering/RenderEmbeddedObject.h"
-#include "modules/webdatabase/DatabaseDetails.h"
+#include "core/rendering/style/RenderStyleConstants.h"
+#include "platform/Cursor.h"
+#include "platform/HostWindow.h"
+#include "platform/PopupMenu.h"
+#include "platform/PopupMenuClient.h"
+#include "platform/graphics/GraphicsContext.h"
+#include "platform/scroll/ScrollTypes.h"
#include "wtf/Forward.h"
#include "wtf/PassOwnPtr.h"
-#include "wtf/UnusedParam.h"
#include "wtf/Vector.h"
@@ -49,7 +48,7 @@ class NSResponder;
namespace WebCore {
-class AccessibilityObject;
+class AXObject;
class ColorChooser;
class ColorChooserClient;
class DateTimeChooser;
@@ -78,7 +77,7 @@ class Widget;
struct DateTimeChooserParameters;
struct FrameLoadRequest;
struct GraphicsDeviceAdapter;
-struct ViewportArguments;
+struct ViewportDescription;
struct WindowFeatures;
class ChromeClient {
@@ -104,7 +103,7 @@ public:
// created Page has its show method called.
// The FrameLoadRequest parameter is only for ChromeClient to check if the
// request could be fulfilled. The ChromeClient should not load the request.
- virtual Page* createWindow(Frame*, const FrameLoadRequest&, const WindowFeatures&, NavigationPolicy = NavigationPolicyIgnore) = 0;
+ virtual Page* createWindow(Frame*, const FrameLoadRequest&, const WindowFeatures&, NavigationPolicy, ShouldSendReferrer) = 0;
virtual void show(NavigationPolicy) = 0;
virtual bool canRunModal() = 0;
@@ -148,20 +147,19 @@ public:
virtual void scroll(const IntSize&, const IntRect&, const IntRect&) = 0;
virtual IntPoint screenToRootView(const IntPoint&) const = 0;
virtual IntRect rootViewToScreen(const IntRect&) const = 0;
- virtual WebKit::WebScreenInfo screenInfo() const = 0;
+ virtual blink::WebScreenInfo screenInfo() const = 0;
virtual void setCursor(const Cursor&) = 0;
virtual void scheduleAnimation() = 0;
// End methods used by HostWindow.
- virtual void dispatchViewportPropertiesDidChange(const ViewportArguments&) const { }
+ virtual bool isCompositorFramePending() const = 0;
+
+ virtual void dispatchViewportPropertiesDidChange(const ViewportDescription&) const { }
virtual void contentsSizeChanged(Frame*, const IntSize&) const = 0;
virtual void deviceOrPageScaleFactorChanged() const { }
virtual void layoutUpdated(Frame*) const { }
- // didProgrammaticallyScroll should be called whenever a Frame is programmatically scrolled.
- virtual void didProgrammaticallyScroll(Frame*, const IntPoint& newScrollPosition) const { }
-
virtual void mouseDidMoveOverElement(const HitTestResult&, unsigned modifierFlags) = 0;
virtual void setToolTip(const String&, TextDirection) = 0;
@@ -183,6 +181,8 @@ public:
// ENABLE(INPUT_MULTIPLE_FIELDS_UI)
virtual PassRefPtr<DateTimeChooser> openDateTimeChooser(DateTimeChooserClient*, const DateTimeChooserParameters&) = 0;
+ virtual void openTextDataListChooser(HTMLInputElement&) = 0;
+
virtual void runOpenPanel(Frame*, PassRefPtr<FileChooser>) = 0;
// Asychronous request to enumerate all files in a directory chosen by the user.
@@ -224,6 +224,8 @@ public:
virtual void needTouchEvents(bool) = 0;
+ virtual void setTouchAction(TouchAction) = 0;
+
// Checks if there is an opened popup, called by RenderMenuList::showPopup().
virtual bool hasOpenedPopup() const = 0;
virtual PassRefPtr<PopupMenu> createPopupMenu(Frame&, PopupMenuClient*) const = 0;
@@ -239,7 +241,7 @@ public:
virtual bool isPasswordGenerationEnabled() const { return false; }
virtual void openPasswordGenerator(HTMLInputElement*) { }
- virtual void postAccessibilityNotification(AccessibilityObject*, AXObjectCache::AXNotification) { }
+ virtual void postAccessibilityNotification(AXObject*, AXObjectCache::AXNotification) { }
virtual String acceptLanguages() = 0;
enum DialogType {
@@ -248,7 +250,7 @@ public:
PromptDialog = 2,
HTMLDialog = 3
};
- virtual bool shouldRunModalDialogDuringPageDismissal(const DialogType&, const String& dialogMessage, Document::PageDismissalType) const { UNUSED_PARAM(dialogMessage); return true; }
+ virtual bool shouldRunModalDialogDuringPageDismissal(const DialogType&, const String&, Document::PageDismissalType) const { return true; }
virtual void numWheelEventHandlersChanged(unsigned) = 0;
@@ -261,8 +263,16 @@ public:
virtual FloatSize minimumWindowSize() const { return FloatSize(100, 100); };
virtual bool isEmptyChromeClient() const { return false; }
+ virtual bool isChromeClientImpl() const { return false; }
virtual void didAssociateFormControls(const Vector<RefPtr<Element> >&) { };
+ virtual void didChangeValueInTextField(HTMLInputElement&) { }
+ virtual void didEndEditingOnTextField(HTMLInputElement&) { }
+ virtual void handleKeyboardEventOnTextField(HTMLInputElement&, KeyboardEvent&) { }
+
+ // Input mehtod editor related functions.
+ virtual void didCancelCompositionOnSelectionChange() { }
+ virtual void willSetInputMethodState() { }
// Notifies the client of a new popup widget. The client should place
// and size the widget with the given bounds, relative to the screen.
diff --git a/chromium/third_party/WebKit/Source/core/page/Console.cpp b/chromium/third_party/WebKit/Source/core/page/Console.cpp
deleted file mode 100644
index 006028c6cbb..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/Console.cpp
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
- * Copyright (C) 2007 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/page/Console.h"
-
-#include "bindings/v8/ScriptCallStackFactory.h"
-#include "bindings/v8/ScriptProfiler.h"
-#include "core/inspector/ConsoleAPITypes.h"
-#include "core/inspector/InspectorConsoleInstrumentation.h"
-#include "core/inspector/ScriptArguments.h"
-#include "core/inspector/ScriptCallStack.h"
-#include "core/inspector/ScriptProfile.h"
-#include "core/page/Chrome.h"
-#include "core/page/ChromeClient.h"
-#include "core/page/ConsoleBase.h"
-#include "core/page/ConsoleTypes.h"
-#include "core/page/Frame.h"
-#include "core/page/MemoryInfo.h"
-#include "core/page/Page.h"
-#include "core/page/PageConsole.h"
-#include "wtf/text/CString.h"
-#include "wtf/text/WTFString.h"
-
-#include "core/platform/chromium/TraceEvent.h"
-
-namespace WebCore {
-
-Console::Console(Frame* frame)
- : DOMWindowProperty(frame)
-{
- ScriptWrappable::init(this);
-}
-
-Console::~Console()
-{
-}
-
-ScriptExecutionContext* Console::context()
-{
- if (!m_frame)
- return 0;
- return m_frame->document();
-}
-
-void Console::reportMessageToClient(MessageLevel level, const String& message, PassRefPtr<ScriptCallStack> callStack)
-{
- String stackTrace;
- if (m_frame->page()->chrome().client().shouldReportDetailedMessageForSource(callStack->at(0).sourceURL())) {
- RefPtr<ScriptCallStack> fullStack = createScriptCallStack(ScriptCallStack::maxCallStackSizeToCapture);
- stackTrace = PageConsole::formatStackTraceString(message, fullStack);
- }
- m_frame->page()->chrome().client().addMessageToConsole(ConsoleAPIMessageSource, level, message, callStack->at(0).lineNumber(), callStack->at(0).sourceURL(), stackTrace);
-}
-
-bool Console::profilerEnabled()
-{
- return InspectorInstrumentation::profilerEnabled(m_frame->page());
-}
-
-PassRefPtr<MemoryInfo> Console::memory() const
-{
- // FIXME: Because we create a new object here each time,
- // console.memory !== console.memory, which seems wrong.
- return MemoryInfo::create(m_frame);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/page/Console.h b/chromium/third_party/WebKit/Source/core/page/Console.h
deleted file mode 100644
index abf4e71a0ed..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/Console.h
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Copyright (C) 2007 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef Console_h
-#define Console_h
-
-#include "bindings/v8/ScriptState.h"
-#include "bindings/v8/ScriptWrappable.h"
-#include "core/page/ConsoleBase.h"
-#include "core/page/DOMWindowProperty.h"
-#include "wtf/Forward.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-
-namespace WebCore {
-
-class Frame;
-class MemoryInfo;
-class Page;
-class ScriptArguments;
-
-class Console : public RefCounted<Console>, public ConsoleBase, public ScriptWrappable, public DOMWindowProperty {
-public:
- using RefCounted<Console>::ref;
- using RefCounted<Console>::deref;
-
- static PassRefPtr<Console> create(Frame* frame) { return adoptRef(new Console(frame)); }
- virtual ~Console();
-
- PassRefPtr<MemoryInfo> memory() const;
-
-protected:
- virtual ScriptExecutionContext* context();
- virtual void reportMessageToClient(MessageLevel, const String& message, PassRefPtr<ScriptCallStack>) OVERRIDE;
- virtual bool profilerEnabled();
-
-private:
- explicit Console(Frame*);
- inline Page* page() const;
-
- virtual void refConsole() { ref(); }
- virtual void derefConsole() { deref(); }
-};
-
-} // namespace WebCore
-
-#endif // Console_h
diff --git a/chromium/third_party/WebKit/Source/core/page/ConsoleBase.cpp b/chromium/third_party/WebKit/Source/core/page/ConsoleBase.cpp
deleted file mode 100644
index a889446b555..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/ConsoleBase.cpp
+++ /dev/null
@@ -1,216 +0,0 @@
-/*
- * Copyright (C) 2007 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/page/Console.h"
-
-#include "bindings/v8/ScriptCallStackFactory.h"
-#include "bindings/v8/ScriptProfiler.h"
-#include "core/dom/Document.h"
-#include "core/inspector/ConsoleAPITypes.h"
-#include "core/inspector/InspectorConsoleInstrumentation.h"
-#include "core/inspector/ScriptArguments.h"
-#include "core/inspector/ScriptCallStack.h"
-#include "core/inspector/ScriptProfile.h"
-#include "core/page/ConsoleTypes.h"
-#include "core/platform/chromium/TraceEvent.h"
-#include "wtf/text/CString.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-ConsoleBase::~ConsoleBase()
-{
-}
-
-void ConsoleBase::debug(ScriptState* state, PassRefPtr<ScriptArguments> arguments)
-{
- internalAddMessage(LogMessageType, DebugMessageLevel, state, arguments);
-}
-
-void ConsoleBase::error(ScriptState* state, PassRefPtr<ScriptArguments> arguments)
-{
- internalAddMessage(LogMessageType, ErrorMessageLevel, state, arguments);
-}
-
-void ConsoleBase::info(ScriptState* state, PassRefPtr<ScriptArguments> arguments)
-{
- log(state, arguments);
-}
-
-void ConsoleBase::log(ScriptState* state, PassRefPtr<ScriptArguments> arguments)
-{
- internalAddMessage(LogMessageType, LogMessageLevel, state, arguments);
-}
-
-void ConsoleBase::warn(ScriptState* state, PassRefPtr<ScriptArguments> arguments)
-{
- internalAddMessage(LogMessageType, WarningMessageLevel, state, arguments);
-}
-
-void ConsoleBase::dir(ScriptState* state, PassRefPtr<ScriptArguments> arguments)
-{
- internalAddMessage(DirMessageType, LogMessageLevel, state, arguments);
-}
-
-void ConsoleBase::dirxml(ScriptState* state, PassRefPtr<ScriptArguments> arguments)
-{
- internalAddMessage(DirXMLMessageType, LogMessageLevel, state, arguments);
-}
-
-void ConsoleBase::table(ScriptState* state, PassRefPtr<ScriptArguments> arguments)
-{
- internalAddMessage(TableMessageType, LogMessageLevel, state, arguments);
-}
-
-void ConsoleBase::clear(ScriptState* state, PassRefPtr<ScriptArguments> arguments)
-{
- InspectorInstrumentation::addMessageToConsole(context(), ConsoleAPIMessageSource, ClearMessageType, LogMessageLevel, String(), state, arguments);
-}
-
-void ConsoleBase::trace(ScriptState* state, PassRefPtr<ScriptArguments> arguments)
-{
- internalAddMessage(TraceMessageType, LogMessageLevel, state, arguments, true, true);
-}
-
-void ConsoleBase::assertCondition(ScriptState* state, PassRefPtr<ScriptArguments> arguments, bool condition)
-{
- if (condition)
- return;
-
- internalAddMessage(AssertMessageType, ErrorMessageLevel, state, arguments, true);
-}
-
-void ConsoleBase::count(ScriptState* state, PassRefPtr<ScriptArguments> arguments)
-{
- InspectorInstrumentation::consoleCount(context(), state, arguments);
-}
-
-void ConsoleBase::markTimeline(const String& title)
-{
- InspectorInstrumentation::consoleTimeStamp(context(), title);
-}
-
-void ConsoleBase::profile(ScriptState* state, const String& title)
-{
- ScriptExecutionContext* context = this->context();
- if (!context)
- return;
-
- // FIXME: log a console message when profiling is disabled.
- if (!profilerEnabled())
- return;
-
- String resolvedTitle = title;
- if (title.isNull()) // no title so give it the next user initiated profile title.
- resolvedTitle = InspectorInstrumentation::getCurrentUserInitiatedProfileName(context, true);
-
- ScriptProfiler::start(resolvedTitle);
- InspectorInstrumentation::addMessageToConsole(context, ConsoleAPIMessageSource, ProfileMessageType, DebugMessageLevel, resolvedTitle, String(), 0, 0, state);
-}
-
-void ConsoleBase::profileEnd(ScriptState* state, const String& title)
-{
- ScriptExecutionContext* context = this->context();
- if (!context)
- return;
-
- if (!profilerEnabled())
- return;
-
- RefPtr<ScriptProfile> profile = ScriptProfiler::stop(title);
- if (!profile)
- return;
-
- RefPtr<ScriptCallStack> callStack(createScriptCallStack(state, 1));
- InspectorInstrumentation::addProfile(context, profile, callStack);
-}
-
-void ConsoleBase::time(const String& title)
-{
- InspectorInstrumentation::consoleTime(context(), title);
- TRACE_EVENT_COPY_ASYNC_BEGIN0("webkit.console", title.utf8().data(), this);
-}
-
-void ConsoleBase::timeEnd(ScriptState* state, const String& title)
-{
- TRACE_EVENT_COPY_ASYNC_END0("webkit.console", title.utf8().data(), this);
- InspectorInstrumentation::consoleTimeEnd(context(), title, state);
-}
-
-void ConsoleBase::timeStamp(const String& title)
-{
- InspectorInstrumentation::consoleTimeStamp(context(), title);
-}
-
-void ConsoleBase::timeline(ScriptState* state, const String& title)
-{
- InspectorInstrumentation::consoleTimeline(context(), title, state);
-}
-
-void ConsoleBase::timelineEnd(ScriptState* state, const String& title)
-{
- InspectorInstrumentation::consoleTimelineEnd(context(), title, state);
-}
-
-void ConsoleBase::group(ScriptState* state, PassRefPtr<ScriptArguments> arguments)
-{
- InspectorInstrumentation::addMessageToConsole(context(), ConsoleAPIMessageSource, StartGroupMessageType, LogMessageLevel, String(), state, arguments);
-}
-
-void ConsoleBase::groupCollapsed(ScriptState* state, PassRefPtr<ScriptArguments> arguments)
-{
- InspectorInstrumentation::addMessageToConsole(context(), ConsoleAPIMessageSource, StartGroupCollapsedMessageType, LogMessageLevel, String(), state, arguments);
-}
-
-void ConsoleBase::groupEnd()
-{
- InspectorInstrumentation::addMessageToConsole(context(), ConsoleAPIMessageSource, EndGroupMessageType, LogMessageLevel, String(), 0);
-}
-
-void ConsoleBase::internalAddMessage(MessageType type, MessageLevel level, ScriptState* state, PassRefPtr<ScriptArguments> scriptArguments, bool acceptNoArguments, bool printTrace)
-{
- if (!context())
- return;
-
- RefPtr<ScriptArguments> arguments = scriptArguments;
- if (!acceptNoArguments && !arguments->argumentCount())
- return;
-
- size_t stackSize = printTrace ? ScriptCallStack::maxCallStackSizeToCapture : 1;
- RefPtr<ScriptCallStack> callStack(createScriptCallStack(state, stackSize));
- const ScriptCallFrame& lastCaller = callStack->at(0);
-
- String message;
- bool gotStringMessage = arguments->getFirstArgumentAsString(message);
- InspectorInstrumentation::addMessageToConsole(context(), ConsoleAPIMessageSource, type, level, message, state, arguments);
- if (gotStringMessage)
- reportMessageToClient(level, message, callStack);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/page/ConsoleBase.h b/chromium/third_party/WebKit/Source/core/page/ConsoleBase.h
deleted file mode 100644
index 4fcd9715796..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/ConsoleBase.h
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
- * Copyright (C) 2007 Apple Inc. All rights reserved.
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ConsoleBase_h
-#define ConsoleBase_h
-
-#include "bindings/v8/ScriptState.h"
-#include "bindings/v8/ScriptWrappable.h"
-#include "core/inspector/ConsoleAPITypes.h"
-#include "core/inspector/ScriptCallStack.h"
-#include "core/page/ConsoleTypes.h"
-#include "core/page/DOMWindowProperty.h"
-#include "wtf/Forward.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-
-namespace WebCore {
-
-class ScriptArguments;
-
-class ConsoleBase {
-public:
- void ref() { refConsole(); }
- void deref() { derefConsole(); }
-
- void debug(ScriptState*, PassRefPtr<ScriptArguments>);
- void error(ScriptState*, PassRefPtr<ScriptArguments>);
- void info(ScriptState*, PassRefPtr<ScriptArguments>);
- void log(ScriptState*, PassRefPtr<ScriptArguments>);
- void clear(ScriptState*, PassRefPtr<ScriptArguments>);
- void warn(ScriptState*, PassRefPtr<ScriptArguments>);
- void dir(ScriptState*, PassRefPtr<ScriptArguments>);
- void dirxml(ScriptState*, PassRefPtr<ScriptArguments>);
- void table(ScriptState*, PassRefPtr<ScriptArguments>);
- void trace(ScriptState*, PassRefPtr<ScriptArguments>);
- void assertCondition(ScriptState*, PassRefPtr<ScriptArguments>, bool condition);
- void count(ScriptState*, PassRefPtr<ScriptArguments>);
- void markTimeline(const String&);
- void profile(ScriptState*, const String&);
- void profileEnd(ScriptState*, const String&);
- void time(const String&);
- void timeEnd(ScriptState*, const String&);
- void timeStamp(const String&);
- void timeline(ScriptState*, const String&);
- void timelineEnd(ScriptState*, const String&);
- void group(ScriptState*, PassRefPtr<ScriptArguments>);
- void groupCollapsed(ScriptState*, PassRefPtr<ScriptArguments>);
- void groupEnd();
-
-protected:
- virtual ~ConsoleBase();
- virtual ScriptExecutionContext* context() = 0;
- virtual void reportMessageToClient(MessageLevel, const String& message, PassRefPtr<ScriptCallStack>) = 0;
- virtual bool profilerEnabled() = 0;
-
-private:
- virtual void refConsole() = 0;
- virtual void derefConsole() = 0;
-
- void internalAddMessage(MessageType, MessageLevel, ScriptState*, PassRefPtr<ScriptArguments>, bool acceptNoArguments = false, bool printTrace = false);
-};
-
-} // namespace WebCore
-
-#endif // ConsoleBase_h
diff --git a/chromium/third_party/WebKit/Source/core/page/ConsoleBase.idl b/chromium/third_party/WebKit/Source/core/page/ConsoleBase.idl
deleted file mode 100644
index 542610fd162..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/ConsoleBase.idl
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * Copyright (C) 2007, 2008 Apple Inc. All rights reserved.
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-[
- CustomToV8,
- DoNotGenerateWrap,
- NoInterfaceObject
-] interface ConsoleBase {
- [CallWith=ScriptArguments&ScriptState] void debug();
- [CallWith=ScriptArguments&ScriptState] void error();
- [CallWith=ScriptArguments&ScriptState] void info();
- [CallWith=ScriptArguments&ScriptState] void log();
- [CallWith=ScriptArguments&ScriptState] void warn();
- [CallWith=ScriptArguments&ScriptState] void dir();
- [CallWith=ScriptArguments&ScriptState] void dirxml();
- [CallWith=ScriptArguments&ScriptState] void table();
- [CallWith=ScriptArguments&ScriptState] void trace();
- [CallWith=ScriptArguments&ScriptState, ImplementedAs=assertCondition] void assert([Default=Undefined] optional boolean condition);
- [CallWith=ScriptArguments&ScriptState] void count();
- [DeprecateAs=ConsoleMarkTimeline] void markTimeline([Default=NullString] optional DOMString title);
-
- [CallWith=ScriptState] void profile([Default=NullString] optional DOMString title);
- [CallWith=ScriptState] void profileEnd([Default=NullString] optional DOMString title);
-
- void time([Default=NullString] optional DOMString title);
- [CallWith=ScriptState] void timeEnd([Default=NullString] optional DOMString title);
- void timeStamp([Default=NullString] optional DOMString title);
-
- [CallWith=ScriptState] void timeline([Default=NullString] optional DOMString title);
- [CallWith=ScriptState] void timelineEnd([Default=NullString] optional DOMString title);
-
- [CallWith=ScriptArguments&ScriptState] void group();
- [CallWith=ScriptArguments&ScriptState] void groupCollapsed();
- void groupEnd();
- [CallWith=ScriptArguments&ScriptState] void clear();
-};
diff --git a/chromium/third_party/WebKit/Source/core/page/ConsoleTypes.h b/chromium/third_party/WebKit/Source/core/page/ConsoleTypes.h
deleted file mode 100644
index 6a1a4b3bad6..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/ConsoleTypes.h
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright (C) 2011 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ConsoleTypes_h
-#define ConsoleTypes_h
-
-namespace WebCore {
-
-enum MessageSource {
- XMLMessageSource,
- JSMessageSource,
- NetworkMessageSource,
- ConsoleAPIMessageSource,
- StorageMessageSource,
- AppCacheMessageSource,
- RenderingMessageSource,
- CSSMessageSource,
- SecurityMessageSource,
- OtherMessageSource,
- DeprecationMessageSource,
-};
-
-enum MessageLevel {
- DebugMessageLevel = 4,
- LogMessageLevel = 1,
- WarningMessageLevel = 2,
- ErrorMessageLevel = 3
-};
-
-} // namespace WebCore
-
-#endif // ConsoleTypes_h
diff --git a/chromium/third_party/WebKit/Source/core/page/ContentSecurityPolicy.cpp b/chromium/third_party/WebKit/Source/core/page/ContentSecurityPolicy.cpp
deleted file mode 100644
index 3b3899606ec..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/ContentSecurityPolicy.cpp
+++ /dev/null
@@ -1,1898 +0,0 @@
-/*
- * Copyright (C) 2011 Google, Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY GOOGLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/page/ContentSecurityPolicy.h"
-
-#include "RuntimeEnabledFeatures.h"
-#include "bindings/v8/ScriptCallStackFactory.h"
-#include "bindings/v8/ScriptController.h"
-#include "bindings/v8/ScriptState.h"
-#include "core/dom/DOMStringList.h"
-#include "core/dom/Document.h"
-#include "core/dom/SecurityPolicyViolationEvent.h"
-#include "core/inspector/InspectorInstrumentation.h"
-#include "core/inspector/ScriptCallStack.h"
-#include "core/loader/DocumentLoader.h"
-#include "core/loader/PingLoader.h"
-#include "core/page/ContentSecurityPolicyResponseHeaders.h"
-#include "core/page/Frame.h"
-#include "core/page/UseCounter.h"
-#include "core/platform/JSONValues.h"
-#include "core/platform/ParsingUtilities.h"
-#include "core/platform/network/FormData.h"
-#include "core/platform/network/ResourceResponse.h"
-#include "weborigin/KURL.h"
-#include "weborigin/KnownPorts.h"
-#include "weborigin/SchemeRegistry.h"
-#include "weborigin/SecurityOrigin.h"
-#include "wtf/HashSet.h"
-#include "wtf/text/TextPosition.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-// Normally WebKit uses "static" for internal linkage, but using "static" for
-// these functions causes a compile error because these functions are used as
-// template parameters.
-namespace {
-
-bool isDirectiveNameCharacter(UChar c)
-{
- return isASCIIAlphanumeric(c) || c == '-';
-}
-
-bool isDirectiveValueCharacter(UChar c)
-{
- return isASCIISpace(c) || (c >= 0x21 && c <= 0x7e); // Whitespace + VCHAR
-}
-
-bool isNonceCharacter(UChar c)
-{
- return isASCIIAlphanumeric(c) || c == '+' || c == '/';
-}
-
-bool isSourceCharacter(UChar c)
-{
- return !isASCIISpace(c);
-}
-
-bool isPathComponentCharacter(UChar c)
-{
- return c != '?' && c != '#';
-}
-
-bool isHostCharacter(UChar c)
-{
- return isASCIIAlphanumeric(c) || c == '-';
-}
-
-bool isSchemeContinuationCharacter(UChar c)
-{
- return isASCIIAlphanumeric(c) || c == '+' || c == '-' || c == '.';
-}
-
-bool isNotASCIISpace(UChar c)
-{
- return !isASCIISpace(c);
-}
-
-bool isNotColonOrSlash(UChar c)
-{
- return c != ':' && c != '/';
-}
-
-bool isMediaTypeCharacter(UChar c)
-{
- return !isASCIISpace(c) && c != '/';
-}
-
-// CSP 1.0 Directives
-static const char connectSrc[] = "connect-src";
-static const char defaultSrc[] = "default-src";
-static const char fontSrc[] = "font-src";
-static const char frameSrc[] = "frame-src";
-static const char imgSrc[] = "img-src";
-static const char mediaSrc[] = "media-src";
-static const char objectSrc[] = "object-src";
-static const char reportURI[] = "report-uri";
-static const char sandbox[] = "sandbox";
-static const char scriptSrc[] = "script-src";
-static const char styleSrc[] = "style-src";
-
-// CSP 1.1 Directives
-static const char baseURI[] = "base-uri";
-static const char formAction[] = "form-action";
-static const char pluginTypes[] = "plugin-types";
-static const char reflectedXSS[] = "reflected-xss";
-
-bool isDirectiveName(const String& name)
-{
- return (equalIgnoringCase(name, connectSrc)
- || equalIgnoringCase(name, defaultSrc)
- || equalIgnoringCase(name, fontSrc)
- || equalIgnoringCase(name, frameSrc)
- || equalIgnoringCase(name, imgSrc)
- || equalIgnoringCase(name, mediaSrc)
- || equalIgnoringCase(name, objectSrc)
- || equalIgnoringCase(name, reportURI)
- || equalIgnoringCase(name, sandbox)
- || equalIgnoringCase(name, scriptSrc)
- || equalIgnoringCase(name, styleSrc)
- || equalIgnoringCase(name, baseURI)
- || equalIgnoringCase(name, formAction)
- || equalIgnoringCase(name, pluginTypes)
- || equalIgnoringCase(name, reflectedXSS)
- );
-}
-
-UseCounter::Feature getUseCounterType(ContentSecurityPolicy::HeaderType type)
-{
- switch (type) {
- case ContentSecurityPolicy::PrefixedEnforce:
- return UseCounter::PrefixedContentSecurityPolicy;
- case ContentSecurityPolicy::Enforce:
- return UseCounter::ContentSecurityPolicy;
- case ContentSecurityPolicy::PrefixedReport:
- return UseCounter::PrefixedContentSecurityPolicyReportOnly;
- case ContentSecurityPolicy::Report:
- return UseCounter::ContentSecurityPolicyReportOnly;
- }
- ASSERT_NOT_REACHED();
- return UseCounter::NumberOfFeatures;
-}
-
-} // namespace
-
-static bool isSourceListNone(const UChar* begin, const UChar* end)
-{
- skipWhile<UChar, isASCIISpace>(begin, end);
-
- const UChar* position = begin;
- skipWhile<UChar, isSourceCharacter>(position, end);
- if (!equalIgnoringCase("'none'", begin, position - begin))
- return false;
-
- skipWhile<UChar, isASCIISpace>(position, end);
- if (position != end)
- return false;
-
- return true;
-}
-
-class CSPSource {
-public:
- CSPSource(ContentSecurityPolicy* policy, const String& scheme, const String& host, int port, const String& path, bool hostHasWildcard, bool portHasWildcard)
- : m_policy(policy)
- , m_scheme(scheme)
- , m_host(host)
- , m_port(port)
- , m_path(path)
- , m_hostHasWildcard(hostHasWildcard)
- , m_portHasWildcard(portHasWildcard)
- {
- }
-
- bool matches(const KURL& url) const
- {
- if (!schemeMatches(url))
- return false;
- if (isSchemeOnly())
- return true;
- return hostMatches(url) && portMatches(url) && pathMatches(url);
- }
-
-private:
- bool schemeMatches(const KURL& url) const
- {
- if (m_scheme.isEmpty()) {
- String protectedResourceScheme(m_policy->securityOrigin()->protocol());
- if (equalIgnoringCase("http", protectedResourceScheme))
- return url.protocolIs("http") || url.protocolIs("https");
- return equalIgnoringCase(url.protocol(), protectedResourceScheme);
- }
- return equalIgnoringCase(url.protocol(), m_scheme);
- }
-
- bool hostMatches(const KURL& url) const
- {
- const String& host = url.host();
- if (equalIgnoringCase(host, m_host))
- return true;
- return m_hostHasWildcard && host.endsWith("." + m_host, false);
-
- }
-
- bool pathMatches(const KURL& url) const
- {
- if (m_path.isEmpty())
- return true;
-
- String path = decodeURLEscapeSequences(url.path());
-
- if (m_path.endsWith("/"))
- return path.startsWith(m_path, false);
-
- return path == m_path;
- }
-
- bool portMatches(const KURL& url) const
- {
- if (m_portHasWildcard)
- return true;
-
- int port = url.port();
-
- if (port == m_port)
- return true;
-
- if (!port)
- return isDefaultPortForProtocol(m_port, url.protocol());
-
- if (!m_port)
- return isDefaultPortForProtocol(port, url.protocol());
-
- return false;
- }
-
- bool isSchemeOnly() const { return m_host.isEmpty(); }
-
- ContentSecurityPolicy* m_policy;
- String m_scheme;
- String m_host;
- int m_port;
- String m_path;
-
- bool m_hostHasWildcard;
- bool m_portHasWildcard;
-};
-
-class CSPSourceList {
-public:
- CSPSourceList(ContentSecurityPolicy*, const String& directiveName);
-
- void parse(const UChar* begin, const UChar* end);
-
- bool matches(const KURL&);
- bool allowInline() const { return m_allowInline; }
- bool allowEval() const { return m_allowEval; }
- bool allowNonce(const String& nonce) const { return !nonce.isNull() && m_nonces.contains(nonce); }
-
-private:
- bool parseSource(const UChar* begin, const UChar* end, String& scheme, String& host, int& port, String& path, bool& hostHasWildcard, bool& portHasWildcard);
- bool parseScheme(const UChar* begin, const UChar* end, String& scheme);
- bool parseHost(const UChar* begin, const UChar* end, String& host, bool& hostHasWildcard);
- bool parsePort(const UChar* begin, const UChar* end, int& port, bool& portHasWildcard);
- bool parsePath(const UChar* begin, const UChar* end, String& path);
- bool parseNonce(const UChar* begin, const UChar* end, String& nonce);
-
- void addSourceSelf();
- void addSourceStar();
- void addSourceUnsafeInline();
- void addSourceUnsafeEval();
- void addSourceNonce(const String& nonce);
-
- ContentSecurityPolicy* m_policy;
- Vector<CSPSource> m_list;
- String m_directiveName;
- bool m_allowStar;
- bool m_allowInline;
- bool m_allowEval;
- HashSet<String> m_nonces;
-};
-
-CSPSourceList::CSPSourceList(ContentSecurityPolicy* policy, const String& directiveName)
- : m_policy(policy)
- , m_directiveName(directiveName)
- , m_allowStar(false)
- , m_allowInline(false)
- , m_allowEval(false)
-{
-}
-
-bool CSPSourceList::matches(const KURL& url)
-{
- if (m_allowStar)
- return true;
-
- KURL effectiveURL = SecurityOrigin::shouldUseInnerURL(url) ? SecurityOrigin::extractInnerURL(url) : url;
-
- for (size_t i = 0; i < m_list.size(); ++i) {
- if (m_list[i].matches(effectiveURL))
- return true;
- }
-
- return false;
-}
-
-// source-list = *WSP [ source *( 1*WSP source ) *WSP ]
-// / *WSP "'none'" *WSP
-//
-void CSPSourceList::parse(const UChar* begin, const UChar* end)
-{
- // We represent 'none' as an empty m_list.
- if (isSourceListNone(begin, end))
- return;
-
- const UChar* position = begin;
- while (position < end) {
- skipWhile<UChar, isASCIISpace>(position, end);
- if (position == end)
- return;
-
- const UChar* beginSource = position;
- skipWhile<UChar, isSourceCharacter>(position, end);
-
- String scheme, host, path;
- int port = 0;
- bool hostHasWildcard = false;
- bool portHasWildcard = false;
-
- if (parseSource(beginSource, position, scheme, host, port, path, hostHasWildcard, portHasWildcard)) {
- // Wildcard hosts and keyword sources ('self', 'unsafe-inline',
- // etc.) aren't stored in m_list, but as attributes on the source
- // list itself.
- if (scheme.isEmpty() && host.isEmpty())
- continue;
- if (isDirectiveName(host))
- m_policy->reportDirectiveAsSourceExpression(m_directiveName, host);
- m_list.append(CSPSource(m_policy, scheme, host, port, path, hostHasWildcard, portHasWildcard));
- } else
- m_policy->reportInvalidSourceExpression(m_directiveName, String(beginSource, position - beginSource));
-
- ASSERT(position == end || isASCIISpace(*position));
- }
-}
-
-// source = scheme ":"
-// / ( [ scheme "://" ] host [ port ] [ path ] )
-// / "'self'"
-//
-bool CSPSourceList::parseSource(const UChar* begin, const UChar* end,
- String& scheme, String& host, int& port, String& path,
- bool& hostHasWildcard, bool& portHasWildcard)
-{
- if (begin == end)
- return false;
-
- if (equalIgnoringCase("'none'", begin, end - begin))
- return false;
-
- if (end - begin == 1 && *begin == '*') {
- addSourceStar();
- return true;
- }
-
- if (equalIgnoringCase("'self'", begin, end - begin)) {
- addSourceSelf();
- return true;
- }
-
- if (equalIgnoringCase("'unsafe-inline'", begin, end - begin)) {
- addSourceUnsafeInline();
- return true;
- }
-
- if (equalIgnoringCase("'unsafe-eval'", begin, end - begin)) {
- addSourceUnsafeEval();
- return true;
- }
-
- if (m_policy->experimentalFeaturesEnabled()) {
- String nonce;
- if (!parseNonce(begin, end, nonce))
- return false;
-
- if (!nonce.isNull()) {
- addSourceNonce(nonce);
- return true;
- }
- }
-
- const UChar* position = begin;
- const UChar* beginHost = begin;
- const UChar* beginPath = end;
- const UChar* beginPort = 0;
-
- skipWhile<UChar, isNotColonOrSlash>(position, end);
-
- if (position == end) {
- // host
- // ^
- return parseHost(beginHost, position, host, hostHasWildcard);
- }
-
- if (position < end && *position == '/') {
- // host/path || host/ || /
- // ^ ^ ^
- return parseHost(beginHost, position, host, hostHasWildcard) && parsePath(position, end, path);
- }
-
- if (position < end && *position == ':') {
- if (end - position == 1) {
- // scheme:
- // ^
- return parseScheme(begin, position, scheme);
- }
-
- if (position[1] == '/') {
- // scheme://host || scheme://
- // ^ ^
- if (!parseScheme(begin, position, scheme)
- || !skipExactly<UChar>(position, end, ':')
- || !skipExactly<UChar>(position, end, '/')
- || !skipExactly<UChar>(position, end, '/'))
- return false;
- if (position == end)
- return true;
- beginHost = position;
- skipWhile<UChar, isNotColonOrSlash>(position, end);
- }
-
- if (position < end && *position == ':') {
- // host:port || scheme://host:port
- // ^ ^
- beginPort = position;
- skipUntil<UChar>(position, end, '/');
- }
- }
-
- if (position < end && *position == '/') {
- // scheme://host/path || scheme://host:port/path
- // ^ ^
- if (position == beginHost)
- return false;
- beginPath = position;
- }
-
- if (!parseHost(beginHost, beginPort ? beginPort : beginPath, host, hostHasWildcard))
- return false;
-
- if (beginPort) {
- if (!parsePort(beginPort, beginPath, port, portHasWildcard))
- return false;
- } else {
- port = 0;
- }
-
- if (beginPath != end) {
- if (!parsePath(beginPath, end, path))
- return false;
- }
-
- return true;
-}
-
-// nonce-source = "'nonce-" nonce-value "'"
-// nonce-value = 1*( ALPHA / DIGIT / "+" / "/" )
-//
-bool CSPSourceList::parseNonce(const UChar* begin, const UChar* end, String& nonce)
-{
- DEFINE_STATIC_LOCAL(const String, noncePrefix, ("'nonce-"));
-
- if (!equalIgnoringCase(noncePrefix.characters8(), begin, noncePrefix.length()))
- return true;
-
- const UChar* position = begin + noncePrefix.length();
- const UChar* nonceBegin = position;
-
- skipWhile<UChar, isNonceCharacter>(position, end);
- ASSERT(nonceBegin <= position);
-
- if (((position + 1) != end && *position != '\'') || !(position - nonceBegin))
- return false;
-
- nonce = String(nonceBegin, position - nonceBegin);
- return true;
-}
-
-// ; <scheme> production from RFC 3986
-// scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
-//
-bool CSPSourceList::parseScheme(const UChar* begin, const UChar* end, String& scheme)
-{
- ASSERT(begin <= end);
- ASSERT(scheme.isEmpty());
-
- if (begin == end)
- return false;
-
- const UChar* position = begin;
-
- if (!skipExactly<UChar, isASCIIAlpha>(position, end))
- return false;
-
- skipWhile<UChar, isSchemeContinuationCharacter>(position, end);
-
- if (position != end)
- return false;
-
- scheme = String(begin, end - begin);
- return true;
-}
-
-// host = [ "*." ] 1*host-char *( "." 1*host-char )
-// / "*"
-// host-char = ALPHA / DIGIT / "-"
-//
-bool CSPSourceList::parseHost(const UChar* begin, const UChar* end, String& host, bool& hostHasWildcard)
-{
- ASSERT(begin <= end);
- ASSERT(host.isEmpty());
- ASSERT(!hostHasWildcard);
-
- if (begin == end)
- return false;
-
- const UChar* position = begin;
-
- if (skipExactly<UChar>(position, end, '*')) {
- hostHasWildcard = true;
-
- if (position == end)
- return true;
-
- if (!skipExactly<UChar>(position, end, '.'))
- return false;
- }
-
- const UChar* hostBegin = position;
-
- while (position < end) {
- if (!skipExactly<UChar, isHostCharacter>(position, end))
- return false;
-
- skipWhile<UChar, isHostCharacter>(position, end);
-
- if (position < end && !skipExactly<UChar>(position, end, '.'))
- return false;
- }
-
- ASSERT(position == end);
- host = String(hostBegin, end - hostBegin);
- return true;
-}
-
-bool CSPSourceList::parsePath(const UChar* begin, const UChar* end, String& path)
-{
- ASSERT(begin <= end);
- ASSERT(path.isEmpty());
-
- const UChar* position = begin;
- skipWhile<UChar, isPathComponentCharacter>(position, end);
- // path/to/file.js?query=string || path/to/file.js#anchor
- // ^ ^
- if (position < end)
- m_policy->reportInvalidPathCharacter(m_directiveName, String(begin, end - begin), *position);
-
- path = decodeURLEscapeSequences(String(begin, position - begin));
-
- ASSERT(position <= end);
- ASSERT(position == end || (*position == '#' || *position == '?'));
- return true;
-}
-
-// port = ":" ( 1*DIGIT / "*" )
-//
-bool CSPSourceList::parsePort(const UChar* begin, const UChar* end, int& port, bool& portHasWildcard)
-{
- ASSERT(begin <= end);
- ASSERT(!port);
- ASSERT(!portHasWildcard);
-
- if (!skipExactly<UChar>(begin, end, ':'))
- ASSERT_NOT_REACHED();
-
- if (begin == end)
- return false;
-
- if (end - begin == 1 && *begin == '*') {
- port = 0;
- portHasWildcard = true;
- return true;
- }
-
- const UChar* position = begin;
- skipWhile<UChar, isASCIIDigit>(position, end);
-
- if (position != end)
- return false;
-
- bool ok;
- port = charactersToIntStrict(begin, end - begin, &ok);
- return ok;
-}
-
-void CSPSourceList::addSourceSelf()
-{
- m_list.append(CSPSource(m_policy, m_policy->securityOrigin()->protocol(), m_policy->securityOrigin()->host(), m_policy->securityOrigin()->port(), String(), false, false));
-}
-
-void CSPSourceList::addSourceStar()
-{
- m_allowStar = true;
-}
-
-void CSPSourceList::addSourceUnsafeInline()
-{
- m_allowInline = true;
-}
-
-void CSPSourceList::addSourceUnsafeEval()
-{
- m_allowEval = true;
-}
-
-void CSPSourceList::addSourceNonce(const String& nonce)
-{
- m_nonces.add(nonce);
-}
-
-class CSPDirective {
-public:
- CSPDirective(const String& name, const String& value, ContentSecurityPolicy* policy)
- : m_name(name)
- , m_text(name + ' ' + value)
- , m_policy(policy)
- {
- }
-
- const String& text() const { return m_text; }
-
-protected:
- const ContentSecurityPolicy* policy() const { return m_policy; }
-
-private:
- String m_name;
- String m_text;
- ContentSecurityPolicy* m_policy;
-};
-
-class MediaListDirective : public CSPDirective {
-public:
- MediaListDirective(const String& name, const String& value, ContentSecurityPolicy* policy)
- : CSPDirective(name, value, policy)
- {
- Vector<UChar> characters;
- value.appendTo(characters);
- parse(characters.data(), characters.data() + characters.size());
- }
-
- bool allows(const String& type)
- {
- return m_pluginTypes.contains(type);
- }
-
-private:
- void parse(const UChar* begin, const UChar* end)
- {
- const UChar* position = begin;
-
- // 'plugin-types ____;' OR 'plugin-types;'
- if (position == end) {
- policy()->reportInvalidPluginTypes(String());
- return;
- }
-
- while (position < end) {
- // _____ OR _____mime1/mime1
- // ^ ^
- skipWhile<UChar, isASCIISpace>(position, end);
- if (position == end)
- return;
-
- // mime1/mime1 mime2/mime2
- // ^
- begin = position;
- if (!skipExactly<UChar, isMediaTypeCharacter>(position, end)) {
- skipWhile<UChar, isNotASCIISpace>(position, end);
- policy()->reportInvalidPluginTypes(String(begin, position - begin));
- continue;
- }
- skipWhile<UChar, isMediaTypeCharacter>(position, end);
-
- // mime1/mime1 mime2/mime2
- // ^
- if (!skipExactly<UChar>(position, end, '/')) {
- skipWhile<UChar, isNotASCIISpace>(position, end);
- policy()->reportInvalidPluginTypes(String(begin, position - begin));
- continue;
- }
-
- // mime1/mime1 mime2/mime2
- // ^
- if (!skipExactly<UChar, isMediaTypeCharacter>(position, end)) {
- skipWhile<UChar, isNotASCIISpace>(position, end);
- policy()->reportInvalidPluginTypes(String(begin, position - begin));
- continue;
- }
- skipWhile<UChar, isMediaTypeCharacter>(position, end);
-
- // mime1/mime1 mime2/mime2 OR mime1/mime1 OR mime1/mime1/error
- // ^ ^ ^
- if (position < end && isNotASCIISpace(*position)) {
- skipWhile<UChar, isNotASCIISpace>(position, end);
- policy()->reportInvalidPluginTypes(String(begin, position - begin));
- continue;
- }
- m_pluginTypes.add(String(begin, position - begin));
-
- ASSERT(position == end || isASCIISpace(*position));
- }
- }
-
- HashSet<String> m_pluginTypes;
-};
-
-class SourceListDirective : public CSPDirective {
-public:
- SourceListDirective(const String& name, const String& value, ContentSecurityPolicy* policy)
- : CSPDirective(name, value, policy)
- , m_sourceList(policy, name)
- {
- Vector<UChar> characters;
- value.appendTo(characters);
-
- m_sourceList.parse(characters.data(), characters.data() + characters.size());
- }
-
- bool allows(const KURL& url)
- {
- return m_sourceList.matches(url.isEmpty() ? policy()->url() : url);
- }
-
- bool allowInline() const { return m_sourceList.allowInline(); }
- bool allowEval() const { return m_sourceList.allowEval(); }
- bool allowNonce(const String& nonce) const { return m_sourceList.allowNonce(nonce.stripWhiteSpace()); }
-
-private:
- CSPSourceList m_sourceList;
-};
-
-class CSPDirectiveList {
- WTF_MAKE_FAST_ALLOCATED;
-public:
- static PassOwnPtr<CSPDirectiveList> create(ContentSecurityPolicy*, const UChar* begin, const UChar* end, ContentSecurityPolicy::HeaderType);
-
- void parse(const UChar* begin, const UChar* end);
-
- const String& header() const { return m_header; }
- ContentSecurityPolicy::HeaderType headerType() const { return m_headerType; }
-
- bool allowJavaScriptURLs(const String& contextURL, const WTF::OrdinalNumber& contextLine, ContentSecurityPolicy::ReportingStatus) const;
- bool allowInlineEventHandlers(const String& contextURL, const WTF::OrdinalNumber& contextLine, ContentSecurityPolicy::ReportingStatus) const;
- bool allowInlineScript(const String& contextURL, const WTF::OrdinalNumber& contextLine, ContentSecurityPolicy::ReportingStatus) const;
- bool allowInlineStyle(const String& contextURL, const WTF::OrdinalNumber& contextLine, ContentSecurityPolicy::ReportingStatus) const;
- bool allowEval(ScriptState*, ContentSecurityPolicy::ReportingStatus) const;
- bool allowPluginType(const String& type, const String& typeAttribute, const KURL&, ContentSecurityPolicy::ReportingStatus) const;
-
- bool allowScriptFromSource(const KURL&, ContentSecurityPolicy::ReportingStatus) const;
- bool allowObjectFromSource(const KURL&, ContentSecurityPolicy::ReportingStatus) const;
- bool allowChildFrameFromSource(const KURL&, ContentSecurityPolicy::ReportingStatus) const;
- bool allowImageFromSource(const KURL&, ContentSecurityPolicy::ReportingStatus) const;
- bool allowStyleFromSource(const KURL&, ContentSecurityPolicy::ReportingStatus) const;
- bool allowFontFromSource(const KURL&, ContentSecurityPolicy::ReportingStatus) const;
- bool allowMediaFromSource(const KURL&, ContentSecurityPolicy::ReportingStatus) const;
- bool allowConnectToSource(const KURL&, ContentSecurityPolicy::ReportingStatus) const;
- bool allowFormAction(const KURL&, ContentSecurityPolicy::ReportingStatus) const;
- bool allowBaseURI(const KURL&, ContentSecurityPolicy::ReportingStatus) const;
- bool allowScriptNonce(const String&) const;
-
- void gatherReportURIs(DOMStringList&) const;
- const String& evalDisabledErrorMessage() const { return m_evalDisabledErrorMessage; }
- ContentSecurityPolicy::ReflectedXSSDisposition reflectedXSSDisposition() const { return m_reflectedXSSDisposition; }
- bool isReportOnly() const { return m_reportOnly; }
- const Vector<KURL>& reportURIs() const { return m_reportURIs; }
-
-private:
- CSPDirectiveList(ContentSecurityPolicy*, ContentSecurityPolicy::HeaderType);
-
- bool parseDirective(const UChar* begin, const UChar* end, String& name, String& value);
- void parseReportURI(const String& name, const String& value);
- void parsePluginTypes(const String& name, const String& value);
- void parseReflectedXSS(const String& name, const String& value);
- void addDirective(const String& name, const String& value);
- void applySandboxPolicy(const String& name, const String& sandboxPolicy);
-
- template <class CSPDirectiveType>
- void setCSPDirective(const String& name, const String& value, OwnPtr<CSPDirectiveType>&);
-
- SourceListDirective* operativeDirective(SourceListDirective*) const;
- void reportViolation(const String& directiveText, const String& effectiveDirective, const String& consoleMessage, const KURL& blockedURL) const;
- void reportViolationWithLocation(const String& directiveText, const String& effectiveDirective, const String& consoleMessage, const KURL& blockedURL, const String& contextURL, const WTF::OrdinalNumber& contextLine) const;
- void reportViolationWithState(const String& directiveText, const String& effectiveDirective, const String& consoleMessage, const KURL& blockedURL, ScriptState*) const;
-
- bool checkEval(SourceListDirective*) const;
- bool checkInline(SourceListDirective*) const;
- bool checkNonce(SourceListDirective*, const String&) const;
- bool checkSource(SourceListDirective*, const KURL&) const;
- bool checkMediaType(MediaListDirective*, const String& type, const String& typeAttribute) const;
-
- void setEvalDisabledErrorMessage(const String& errorMessage) { m_evalDisabledErrorMessage = errorMessage; }
-
- bool checkEvalAndReportViolation(SourceListDirective*, const String& consoleMessage, ScriptState*) const;
- bool checkInlineAndReportViolation(SourceListDirective*, const String& consoleMessage, const String& contextURL, const WTF::OrdinalNumber& contextLine, bool isScript) const;
-
- bool checkSourceAndReportViolation(SourceListDirective*, const KURL&, const String& effectiveDirective) const;
- bool checkMediaTypeAndReportViolation(MediaListDirective*, const String& type, const String& typeAttribute, const String& consoleMessage) const;
-
- bool denyIfEnforcingPolicy() const { return m_reportOnly; }
-
- ContentSecurityPolicy* m_policy;
-
- String m_header;
- ContentSecurityPolicy::HeaderType m_headerType;
-
- bool m_reportOnly;
- bool m_haveSandboxPolicy;
- ContentSecurityPolicy::ReflectedXSSDisposition m_reflectedXSSDisposition;
-
- OwnPtr<MediaListDirective> m_pluginTypes;
- OwnPtr<SourceListDirective> m_baseURI;
- OwnPtr<SourceListDirective> m_connectSrc;
- OwnPtr<SourceListDirective> m_defaultSrc;
- OwnPtr<SourceListDirective> m_fontSrc;
- OwnPtr<SourceListDirective> m_formAction;
- OwnPtr<SourceListDirective> m_frameSrc;
- OwnPtr<SourceListDirective> m_imgSrc;
- OwnPtr<SourceListDirective> m_mediaSrc;
- OwnPtr<SourceListDirective> m_objectSrc;
- OwnPtr<SourceListDirective> m_scriptSrc;
- OwnPtr<SourceListDirective> m_styleSrc;
-
- Vector<KURL> m_reportURIs;
-
- String m_evalDisabledErrorMessage;
-};
-
-CSPDirectiveList::CSPDirectiveList(ContentSecurityPolicy* policy, ContentSecurityPolicy::HeaderType type)
- : m_policy(policy)
- , m_headerType(type)
- , m_reportOnly(false)
- , m_haveSandboxPolicy(false)
- , m_reflectedXSSDisposition(ContentSecurityPolicy::ReflectedXSSUnset)
-{
- m_reportOnly = (type == ContentSecurityPolicy::Report || type == ContentSecurityPolicy::PrefixedReport);
-}
-
-PassOwnPtr<CSPDirectiveList> CSPDirectiveList::create(ContentSecurityPolicy* policy, const UChar* begin, const UChar* end, ContentSecurityPolicy::HeaderType type)
-{
- OwnPtr<CSPDirectiveList> directives = adoptPtr(new CSPDirectiveList(policy, type));
- directives->parse(begin, end);
-
- if (!directives->checkEval(directives->operativeDirective(directives->m_scriptSrc.get()))) {
- String message = "Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: \"" + directives->operativeDirective(directives->m_scriptSrc.get())->text() + "\".\n";
- directives->setEvalDisabledErrorMessage(message);
- }
-
- if (directives->isReportOnly() && directives->reportURIs().isEmpty())
- policy->reportMissingReportURI(String(begin, end - begin));
-
- return directives.release();
-}
-
-void CSPDirectiveList::reportViolation(const String& directiveText, const String& effectiveDirective, const String& consoleMessage, const KURL& blockedURL) const
-{
- String message = m_reportOnly ? "[Report Only] " + consoleMessage : consoleMessage;
- m_policy->scriptExecutionContext()->addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, message);
- m_policy->reportViolation(directiveText, effectiveDirective, message, blockedURL, m_reportURIs, m_header);
-}
-
-void CSPDirectiveList::reportViolationWithLocation(const String& directiveText, const String& effectiveDirective, const String& consoleMessage, const KURL& blockedURL, const String& contextURL, const WTF::OrdinalNumber& contextLine) const
-{
- String message = m_reportOnly ? "[Report Only] " + consoleMessage : consoleMessage;
- m_policy->scriptExecutionContext()->addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, message, contextURL, contextLine.oneBasedInt());
- m_policy->reportViolation(directiveText, effectiveDirective, message, blockedURL, m_reportURIs, m_header);
-}
-
-void CSPDirectiveList::reportViolationWithState(const String& directiveText, const String& effectiveDirective, const String& consoleMessage, const KURL& blockedURL, ScriptState* state) const
-{
- String message = m_reportOnly ? "[Report Only] " + consoleMessage : consoleMessage;
- m_policy->scriptExecutionContext()->addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, message, state);
- m_policy->reportViolation(directiveText, effectiveDirective, message, blockedURL, m_reportURIs, m_header);
-}
-
-bool CSPDirectiveList::checkEval(SourceListDirective* directive) const
-{
- return !directive || directive->allowEval();
-}
-
-bool CSPDirectiveList::checkInline(SourceListDirective* directive) const
-{
- return !directive || directive->allowInline();
-}
-
-bool CSPDirectiveList::checkNonce(SourceListDirective* directive, const String& nonce) const
-{
- return !directive || directive->allowNonce(nonce);
-}
-
-bool CSPDirectiveList::checkSource(SourceListDirective* directive, const KURL& url) const
-{
- return !directive || directive->allows(url);
-}
-
-bool CSPDirectiveList::checkMediaType(MediaListDirective* directive, const String& type, const String& typeAttribute) const
-{
- if (!directive)
- return true;
- if (typeAttribute.isEmpty() || typeAttribute.stripWhiteSpace() != type)
- return false;
- return directive->allows(type);
-}
-
-SourceListDirective* CSPDirectiveList::operativeDirective(SourceListDirective* directive) const
-{
- return directive ? directive : m_defaultSrc.get();
-}
-
-bool CSPDirectiveList::checkEvalAndReportViolation(SourceListDirective* directive, const String& consoleMessage, ScriptState* state) const
-{
- if (checkEval(directive))
- return true;
-
- String suffix = String();
- if (directive == m_defaultSrc)
- suffix = " Note that 'script-src' was not explicitly set, so 'default-src' is used as a fallback.";
-
- reportViolationWithState(directive->text(), scriptSrc, consoleMessage + "\"" + directive->text() + "\"." + suffix + "\n", KURL(), state);
- if (!m_reportOnly) {
- m_policy->reportBlockedScriptExecutionToInspector(directive->text());
- return false;
- }
- return true;
-}
-
-bool CSPDirectiveList::checkMediaTypeAndReportViolation(MediaListDirective* directive, const String& type, const String& typeAttribute, const String& consoleMessage) const
-{
- if (checkMediaType(directive, type, typeAttribute))
- return true;
-
- String message = consoleMessage + "\'" + directive->text() + "\'.";
- if (typeAttribute.isEmpty())
- message = message + " When enforcing the 'plugin-types' directive, the plugin's media type must be explicitly declared with a 'type' attribute on the containing element (e.g. '<object type=\"[TYPE GOES HERE]\" ...>').";
-
- reportViolation(directive->text(), pluginTypes, message + "\n", KURL());
- return denyIfEnforcingPolicy();
-}
-
-bool CSPDirectiveList::checkInlineAndReportViolation(SourceListDirective* directive, const String& consoleMessage, const String& contextURL, const WTF::OrdinalNumber& contextLine, bool isScript) const
-{
- if (checkInline(directive))
- return true;
-
- String suffix = String();
- if (directive == m_defaultSrc)
- suffix = " Note that '" + String(isScript ? "script" : "style") + "-src' was not explicitly set, so 'default-src' is used as a fallback.";
-
- reportViolationWithLocation(directive->text(), isScript ? scriptSrc : styleSrc, consoleMessage + "\"" + directive->text() + "\"." + suffix + "\n", KURL(), contextURL, contextLine);
-
- if (!m_reportOnly) {
- if (isScript)
- m_policy->reportBlockedScriptExecutionToInspector(directive->text());
- return false;
- }
- return true;
-}
-
-bool CSPDirectiveList::checkSourceAndReportViolation(SourceListDirective* directive, const KURL& url, const String& effectiveDirective) const
-{
- if (checkSource(directive, url))
- return true;
-
- String prefix;
- if (baseURI == effectiveDirective)
- prefix = "Refused to set the document's base URI to '";
- else if (connectSrc == effectiveDirective)
- prefix = "Refused to connect to '";
- else if (fontSrc == effectiveDirective)
- prefix = "Refused to load the font '";
- else if (formAction == effectiveDirective)
- prefix = "Refused to send form data to '";
- else if (frameSrc == effectiveDirective)
- prefix = "Refused to frame '";
- else if (imgSrc == effectiveDirective)
- prefix = "Refused to load the image '";
- else if (mediaSrc == effectiveDirective)
- prefix = "Refused to load media from '";
- else if (objectSrc == effectiveDirective)
- prefix = "Refused to load plugin data from '";
- else if (scriptSrc == effectiveDirective)
- prefix = "Refused to load the script '";
- else if (styleSrc == effectiveDirective)
- prefix = "Refused to load the stylesheet '";
-
- String suffix = String();
- if (directive == m_defaultSrc)
- suffix = " Note that '" + effectiveDirective + "' was not explicitly set, so 'default-src' is used as a fallback.";
-
- reportViolation(directive->text(), effectiveDirective, prefix + url.elidedString() + "' because it violates the following Content Security Policy directive: \"" + directive->text() + "\"." + suffix + "\n", url);
- return denyIfEnforcingPolicy();
-}
-
-bool CSPDirectiveList::allowJavaScriptURLs(const String& contextURL, const WTF::OrdinalNumber& contextLine, ContentSecurityPolicy::ReportingStatus reportingStatus) const
-{
- DEFINE_STATIC_LOCAL(String, consoleMessage, ("Refused to execute JavaScript URL because it violates the following Content Security Policy directive: "));
- if (reportingStatus == ContentSecurityPolicy::SendReport) {
- return checkInlineAndReportViolation(operativeDirective(m_scriptSrc.get()), consoleMessage, contextURL, contextLine, true);
- } else {
- return checkInline(operativeDirective(m_scriptSrc.get()));
- }
-}
-
-bool CSPDirectiveList::allowInlineEventHandlers(const String& contextURL, const WTF::OrdinalNumber& contextLine, ContentSecurityPolicy::ReportingStatus reportingStatus) const
-{
- DEFINE_STATIC_LOCAL(String, consoleMessage, ("Refused to execute inline event handler because it violates the following Content Security Policy directive: "));
- if (reportingStatus == ContentSecurityPolicy::SendReport) {
- return checkInlineAndReportViolation(operativeDirective(m_scriptSrc.get()), consoleMessage, contextURL, contextLine, true);
- } else {
- return checkInline(operativeDirective(m_scriptSrc.get()));
- }
-}
-
-bool CSPDirectiveList::allowInlineScript(const String& contextURL, const WTF::OrdinalNumber& contextLine, ContentSecurityPolicy::ReportingStatus reportingStatus) const
-{
- DEFINE_STATIC_LOCAL(String, consoleMessage, ("Refused to execute inline script because it violates the following Content Security Policy directive: "));
- return reportingStatus == ContentSecurityPolicy::SendReport ?
- checkInlineAndReportViolation(operativeDirective(m_scriptSrc.get()), consoleMessage, contextURL, contextLine, true) :
- checkInline(operativeDirective(m_scriptSrc.get()));
-}
-
-bool CSPDirectiveList::allowInlineStyle(const String& contextURL, const WTF::OrdinalNumber& contextLine, ContentSecurityPolicy::ReportingStatus reportingStatus) const
-{
- DEFINE_STATIC_LOCAL(String, consoleMessage, ("Refused to apply inline style because it violates the following Content Security Policy directive: "));
- return reportingStatus == ContentSecurityPolicy::SendReport ?
- checkInlineAndReportViolation(operativeDirective(m_styleSrc.get()), consoleMessage, contextURL, contextLine, false) :
- checkInline(operativeDirective(m_styleSrc.get()));
-}
-
-bool CSPDirectiveList::allowEval(ScriptState* state, ContentSecurityPolicy::ReportingStatus reportingStatus) const
-{
- DEFINE_STATIC_LOCAL(String, consoleMessage, ("Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "));
-
- return reportingStatus == ContentSecurityPolicy::SendReport ?
- checkEvalAndReportViolation(operativeDirective(m_scriptSrc.get()), consoleMessage, state) :
- checkEval(operativeDirective(m_scriptSrc.get()));
-}
-
-bool CSPDirectiveList::allowPluginType(const String& type, const String& typeAttribute, const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
-{
- return reportingStatus == ContentSecurityPolicy::SendReport ?
- checkMediaTypeAndReportViolation(m_pluginTypes.get(), type, typeAttribute, "Refused to load '" + url.elidedString() + "' (MIME type '" + typeAttribute + "') because it violates the following Content Security Policy Directive: ") :
- checkMediaType(m_pluginTypes.get(), type, typeAttribute);
-}
-
-bool CSPDirectiveList::allowScriptFromSource(const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
-{
- return reportingStatus == ContentSecurityPolicy::SendReport ?
- checkSourceAndReportViolation(operativeDirective(m_scriptSrc.get()), url, scriptSrc) :
- checkSource(operativeDirective(m_scriptSrc.get()), url);
-}
-
-bool CSPDirectiveList::allowObjectFromSource(const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
-{
- if (url.isBlankURL())
- return true;
- return reportingStatus == ContentSecurityPolicy::SendReport ?
- checkSourceAndReportViolation(operativeDirective(m_objectSrc.get()), url, objectSrc) :
- checkSource(operativeDirective(m_objectSrc.get()), url);
-}
-
-bool CSPDirectiveList::allowChildFrameFromSource(const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
-{
- if (url.isBlankURL())
- return true;
- return reportingStatus == ContentSecurityPolicy::SendReport ?
- checkSourceAndReportViolation(operativeDirective(m_frameSrc.get()), url, frameSrc) :
- checkSource(operativeDirective(m_frameSrc.get()), url);
-}
-
-bool CSPDirectiveList::allowImageFromSource(const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
-{
- return reportingStatus == ContentSecurityPolicy::SendReport ?
- checkSourceAndReportViolation(operativeDirective(m_imgSrc.get()), url, imgSrc) :
- checkSource(operativeDirective(m_imgSrc.get()), url);
-}
-
-bool CSPDirectiveList::allowStyleFromSource(const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
-{
- return reportingStatus == ContentSecurityPolicy::SendReport ?
- checkSourceAndReportViolation(operativeDirective(m_styleSrc.get()), url, styleSrc) :
- checkSource(operativeDirective(m_styleSrc.get()), url);
-}
-
-bool CSPDirectiveList::allowFontFromSource(const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
-{
- return reportingStatus == ContentSecurityPolicy::SendReport ?
- checkSourceAndReportViolation(operativeDirective(m_fontSrc.get()), url, fontSrc) :
- checkSource(operativeDirective(m_fontSrc.get()), url);
-}
-
-bool CSPDirectiveList::allowMediaFromSource(const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
-{
- return reportingStatus == ContentSecurityPolicy::SendReport ?
- checkSourceAndReportViolation(operativeDirective(m_mediaSrc.get()), url, mediaSrc) :
- checkSource(operativeDirective(m_mediaSrc.get()), url);
-}
-
-bool CSPDirectiveList::allowConnectToSource(const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
-{
- return reportingStatus == ContentSecurityPolicy::SendReport ?
- checkSourceAndReportViolation(operativeDirective(m_connectSrc.get()), url, connectSrc) :
- checkSource(operativeDirective(m_connectSrc.get()), url);
-}
-
-void CSPDirectiveList::gatherReportURIs(DOMStringList& list) const
-{
- for (size_t i = 0; i < m_reportURIs.size(); ++i)
- list.append(m_reportURIs[i].string());
-}
-
-bool CSPDirectiveList::allowFormAction(const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
-{
- return reportingStatus == ContentSecurityPolicy::SendReport ?
- checkSourceAndReportViolation(m_formAction.get(), url, formAction) :
- checkSource(m_formAction.get(), url);
-}
-
-bool CSPDirectiveList::allowBaseURI(const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
-{
- return reportingStatus == ContentSecurityPolicy::SendReport ?
- checkSourceAndReportViolation(m_baseURI.get(), url, baseURI) :
- checkSource(m_baseURI.get(), url);
-}
-
-bool CSPDirectiveList::allowScriptNonce(const String& nonce) const
-{
- return checkNonce(operativeDirective(m_scriptSrc.get()), nonce);
-}
-
-// policy = directive-list
-// directive-list = [ directive *( ";" [ directive ] ) ]
-//
-void CSPDirectiveList::parse(const UChar* begin, const UChar* end)
-{
- m_header = String(begin, end - begin);
-
- if (begin == end)
- return;
-
- const UChar* position = begin;
- while (position < end) {
- const UChar* directiveBegin = position;
- skipUntil<UChar>(position, end, ';');
-
- String name, value;
- if (parseDirective(directiveBegin, position, name, value)) {
- ASSERT(!name.isEmpty());
- addDirective(name, value);
- }
-
- ASSERT(position == end || *position == ';');
- skipExactly<UChar>(position, end, ';');
- }
-}
-
-// directive = *WSP [ directive-name [ WSP directive-value ] ]
-// directive-name = 1*( ALPHA / DIGIT / "-" )
-// directive-value = *( WSP / <VCHAR except ";"> )
-//
-bool CSPDirectiveList::parseDirective(const UChar* begin, const UChar* end, String& name, String& value)
-{
- ASSERT(name.isEmpty());
- ASSERT(value.isEmpty());
-
- const UChar* position = begin;
- skipWhile<UChar, isASCIISpace>(position, end);
-
- // Empty directive (e.g. ";;;"). Exit early.
- if (position == end)
- return false;
-
- const UChar* nameBegin = position;
- skipWhile<UChar, isDirectiveNameCharacter>(position, end);
-
- // The directive-name must be non-empty.
- if (nameBegin == position) {
- skipWhile<UChar, isNotASCIISpace>(position, end);
- m_policy->reportUnsupportedDirective(String(nameBegin, position - nameBegin));
- return false;
- }
-
- name = String(nameBegin, position - nameBegin);
-
- if (position == end)
- return true;
-
- if (!skipExactly<UChar, isASCIISpace>(position, end)) {
- skipWhile<UChar, isNotASCIISpace>(position, end);
- m_policy->reportUnsupportedDirective(String(nameBegin, position - nameBegin));
- return false;
- }
-
- skipWhile<UChar, isASCIISpace>(position, end);
-
- const UChar* valueBegin = position;
- skipWhile<UChar, isDirectiveValueCharacter>(position, end);
-
- if (position != end) {
- m_policy->reportInvalidDirectiveValueCharacter(name, String(valueBegin, end - valueBegin));
- return false;
- }
-
- // The directive-value may be empty.
- if (valueBegin == position)
- return true;
-
- value = String(valueBegin, position - valueBegin);
- return true;
-}
-
-void CSPDirectiveList::parseReportURI(const String& name, const String& value)
-{
- if (!m_reportURIs.isEmpty()) {
- m_policy->reportDuplicateDirective(name);
- return;
- }
-
- Vector<UChar> characters;
- value.appendTo(characters);
-
- const UChar* position = characters.data();
- const UChar* end = position + characters.size();
-
- while (position < end) {
- skipWhile<UChar, isASCIISpace>(position, end);
-
- const UChar* urlBegin = position;
- skipWhile<UChar, isNotASCIISpace>(position, end);
-
- if (urlBegin < position) {
- String url = String(urlBegin, position - urlBegin);
- m_reportURIs.append(m_policy->completeURL(url));
- }
- }
-}
-
-
-template<class CSPDirectiveType>
-void CSPDirectiveList::setCSPDirective(const String& name, const String& value, OwnPtr<CSPDirectiveType>& directive)
-{
- if (directive) {
- m_policy->reportDuplicateDirective(name);
- return;
- }
- directive = adoptPtr(new CSPDirectiveType(name, value, m_policy));
-}
-
-void CSPDirectiveList::applySandboxPolicy(const String& name, const String& sandboxPolicy)
-{
- if (m_haveSandboxPolicy) {
- m_policy->reportDuplicateDirective(name);
- return;
- }
- m_haveSandboxPolicy = true;
- String invalidTokens;
- m_policy->enforceSandboxFlags(SecurityContext::parseSandboxPolicy(sandboxPolicy, invalidTokens));
- if (!invalidTokens.isNull())
- m_policy->reportInvalidSandboxFlags(invalidTokens);
-}
-
-void CSPDirectiveList::parseReflectedXSS(const String& name, const String& value)
-{
- if (m_reflectedXSSDisposition != ContentSecurityPolicy::ReflectedXSSUnset) {
- m_policy->reportDuplicateDirective(name);
- m_reflectedXSSDisposition = ContentSecurityPolicy::ReflectedXSSInvalid;
- return;
- }
-
- if (value.isEmpty()) {
- m_reflectedXSSDisposition = ContentSecurityPolicy::ReflectedXSSInvalid;
- m_policy->reportInvalidReflectedXSS(value);
- return;
- }
-
- Vector<UChar> characters;
- value.appendTo(characters);
-
- const UChar* position = characters.data();
- const UChar* end = position + characters.size();
-
- skipWhile<UChar, isASCIISpace>(position, end);
- const UChar* begin = position;
- skipWhile<UChar, isNotASCIISpace>(position, end);
-
- // value1
- // ^
- if (equalIgnoringCase("allow", begin, position - begin))
- m_reflectedXSSDisposition = ContentSecurityPolicy::AllowReflectedXSS;
- else if (equalIgnoringCase("filter", begin, position - begin))
- m_reflectedXSSDisposition = ContentSecurityPolicy::FilterReflectedXSS;
- else if (equalIgnoringCase("block", begin, position - begin))
- m_reflectedXSSDisposition = ContentSecurityPolicy::BlockReflectedXSS;
- else {
- m_reflectedXSSDisposition = ContentSecurityPolicy::ReflectedXSSInvalid;
- m_policy->reportInvalidReflectedXSS(value);
- return;
- }
-
- skipWhile<UChar, isASCIISpace>(position, end);
- if (position == end && m_reflectedXSSDisposition != ContentSecurityPolicy::ReflectedXSSUnset)
- return;
-
- // value1 value2
- // ^
- m_reflectedXSSDisposition = ContentSecurityPolicy::ReflectedXSSInvalid;
- m_policy->reportInvalidReflectedXSS(value);
-}
-
-void CSPDirectiveList::addDirective(const String& name, const String& value)
-{
- ASSERT(!name.isEmpty());
-
- if (equalIgnoringCase(name, defaultSrc))
- setCSPDirective<SourceListDirective>(name, value, m_defaultSrc);
- else if (equalIgnoringCase(name, scriptSrc))
- setCSPDirective<SourceListDirective>(name, value, m_scriptSrc);
- else if (equalIgnoringCase(name, objectSrc))
- setCSPDirective<SourceListDirective>(name, value, m_objectSrc);
- else if (equalIgnoringCase(name, frameSrc))
- setCSPDirective<SourceListDirective>(name, value, m_frameSrc);
- else if (equalIgnoringCase(name, imgSrc))
- setCSPDirective<SourceListDirective>(name, value, m_imgSrc);
- else if (equalIgnoringCase(name, styleSrc))
- setCSPDirective<SourceListDirective>(name, value, m_styleSrc);
- else if (equalIgnoringCase(name, fontSrc))
- setCSPDirective<SourceListDirective>(name, value, m_fontSrc);
- else if (equalIgnoringCase(name, mediaSrc))
- setCSPDirective<SourceListDirective>(name, value, m_mediaSrc);
- else if (equalIgnoringCase(name, connectSrc))
- setCSPDirective<SourceListDirective>(name, value, m_connectSrc);
- else if (equalIgnoringCase(name, sandbox))
- applySandboxPolicy(name, value);
- else if (equalIgnoringCase(name, reportURI))
- parseReportURI(name, value);
- else if (m_policy->experimentalFeaturesEnabled()) {
- if (equalIgnoringCase(name, baseURI))
- setCSPDirective<SourceListDirective>(name, value, m_baseURI);
- else if (equalIgnoringCase(name, formAction))
- setCSPDirective<SourceListDirective>(name, value, m_formAction);
- else if (equalIgnoringCase(name, pluginTypes))
- setCSPDirective<MediaListDirective>(name, value, m_pluginTypes);
- else if (equalIgnoringCase(name, reflectedXSS))
- parseReflectedXSS(name, value);
- else
- m_policy->reportUnsupportedDirective(name);
- }
- else
- m_policy->reportUnsupportedDirective(name);
-}
-
-ContentSecurityPolicy::ContentSecurityPolicy(ScriptExecutionContext* scriptExecutionContext)
- : m_scriptExecutionContext(scriptExecutionContext)
- , m_overrideInlineStyleAllowed(false)
-{
-}
-
-ContentSecurityPolicy::~ContentSecurityPolicy()
-{
-}
-
-void ContentSecurityPolicy::copyStateFrom(const ContentSecurityPolicy* other)
-{
- ASSERT(m_policies.isEmpty());
- for (CSPDirectiveListVector::const_iterator iter = other->m_policies.begin(); iter != other->m_policies.end(); ++iter)
- addPolicyFromHeaderValue((*iter)->header(), (*iter)->headerType());
-}
-
-void ContentSecurityPolicy::didReceiveHeaders(const ContentSecurityPolicyResponseHeaders& headers)
-{
- if (!headers.contentSecurityPolicy().isEmpty())
- didReceiveHeader(headers.contentSecurityPolicy(), ContentSecurityPolicy::Enforce);
- if (!headers.contentSecurityPolicyReportOnly().isEmpty())
- didReceiveHeader(headers.contentSecurityPolicyReportOnly(), ContentSecurityPolicy::Report);
- if (!headers.xWebKitCSP().isEmpty())
- didReceiveHeader(headers.xWebKitCSP(), ContentSecurityPolicy::PrefixedEnforce);
- if (!headers.xWebKitCSPReportOnly().isEmpty())
- didReceiveHeader(headers.xWebKitCSPReportOnly(), ContentSecurityPolicy::PrefixedReport);
-}
-
-void ContentSecurityPolicy::didReceiveHeader(const String& header, HeaderType type)
-{
- addPolicyFromHeaderValue(header, type);
-}
-
-void ContentSecurityPolicy::addPolicyFromHeaderValue(const String& header, HeaderType type)
-{
- if (m_scriptExecutionContext->isDocument()) {
- Document* document = toDocument(m_scriptExecutionContext);
- if (type == PrefixedReport || type == PrefixedEnforce)
- UseCounter::countDeprecation(document, getUseCounterType(type));
- else
- UseCounter::count(document, getUseCounterType(type));
- }
-
- Vector<UChar> characters;
- header.appendTo(characters);
-
- const UChar* begin = characters.data();
- const UChar* end = begin + characters.size();
-
- // RFC2616, section 4.2 specifies that headers appearing multiple times can
- // be combined with a comma. Walk the header string, and parse each comma
- // separated chunk as a separate header.
- const UChar* position = begin;
- while (position < end) {
- skipUntil<UChar>(position, end, ',');
-
- // header1,header2 OR header1
- // ^ ^
- OwnPtr<CSPDirectiveList> policy = CSPDirectiveList::create(this, begin, position, type);
-
- // We disable 'eval()' even in the case of report-only policies, and rely on the check in the V8Initializer::codeGenerationCheckCallbackInMainThread callback to determine whether the call should execute or not.
- if (!policy->allowEval(0, SuppressReport))
- m_scriptExecutionContext->disableEval(policy->evalDisabledErrorMessage());
-
- m_policies.append(policy.release());
-
- // Skip the comma, and begin the next header from the current position.
- ASSERT(position == end || *position == ',');
- skipExactly<UChar>(position, end, ',');
- begin = position;
- }
-}
-
-void ContentSecurityPolicy::setOverrideAllowInlineStyle(bool value)
-{
- m_overrideInlineStyleAllowed = value;
-}
-
-const String& ContentSecurityPolicy::deprecatedHeader() const
-{
- return m_policies.isEmpty() ? emptyString() : m_policies[0]->header();
-}
-
-ContentSecurityPolicy::HeaderType ContentSecurityPolicy::deprecatedHeaderType() const
-{
- return m_policies.isEmpty() ? Enforce : m_policies[0]->headerType();
-}
-
-template<bool (CSPDirectiveList::*allowed)(ContentSecurityPolicy::ReportingStatus) const>
-bool isAllowedByAll(const CSPDirectiveListVector& policies, ContentSecurityPolicy::ReportingStatus reportingStatus)
-{
- for (size_t i = 0; i < policies.size(); ++i) {
- if (!(policies[i].get()->*allowed)(reportingStatus))
- return false;
- }
- return true;
-}
-
-template<bool (CSPDirectiveList::*allowed)(ScriptState* state, ContentSecurityPolicy::ReportingStatus) const>
-bool isAllowedByAllWithState(const CSPDirectiveListVector& policies, ScriptState* state, ContentSecurityPolicy::ReportingStatus reportingStatus)
-{
- for (size_t i = 0; i < policies.size(); ++i) {
- if (!(policies[i].get()->*allowed)(state, reportingStatus))
- return false;
- }
- return true;
-}
-
-template<bool (CSPDirectiveList::*allowed)(const String&, const WTF::OrdinalNumber&, ContentSecurityPolicy::ReportingStatus) const>
-bool isAllowedByAllWithContext(const CSPDirectiveListVector& policies, const String& contextURL, const WTF::OrdinalNumber& contextLine, ContentSecurityPolicy::ReportingStatus reportingStatus)
-{
- for (size_t i = 0; i < policies.size(); ++i) {
- if (!(policies[i].get()->*allowed)(contextURL, contextLine, reportingStatus))
- return false;
- }
- return true;
-}
-
-template<bool (CSPDirectiveList::*allowed)(const String&) const>
-bool isAllowedByAllWithNonce(const CSPDirectiveListVector& policies, const String& nonce)
-{
- for (size_t i = 0; i < policies.size(); ++i) {
- if (!(policies[i].get()->*allowed)(nonce))
- return false;
- }
- return true;
-}
-template<bool (CSPDirectiveList::*allowFromURL)(const KURL&, ContentSecurityPolicy::ReportingStatus) const>
-bool isAllowedByAllWithURL(const CSPDirectiveListVector& policies, const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus)
-{
- if (SchemeRegistry::schemeShouldBypassContentSecurityPolicy(url.protocol()))
- return true;
-
- for (size_t i = 0; i < policies.size(); ++i) {
- if (!(policies[i].get()->*allowFromURL)(url, reportingStatus))
- return false;
- }
- return true;
-}
-
-bool ContentSecurityPolicy::allowJavaScriptURLs(const String& contextURL, const WTF::OrdinalNumber& contextLine, ContentSecurityPolicy::ReportingStatus reportingStatus) const
-{
- return isAllowedByAllWithContext<&CSPDirectiveList::allowJavaScriptURLs>(m_policies, contextURL, contextLine, reportingStatus);
-}
-
-bool ContentSecurityPolicy::allowInlineEventHandlers(const String& contextURL, const WTF::OrdinalNumber& contextLine, ContentSecurityPolicy::ReportingStatus reportingStatus) const
-{
- return isAllowedByAllWithContext<&CSPDirectiveList::allowInlineEventHandlers>(m_policies, contextURL, contextLine, reportingStatus);
-}
-
-bool ContentSecurityPolicy::allowInlineScript(const String& contextURL, const WTF::OrdinalNumber& contextLine, ContentSecurityPolicy::ReportingStatus reportingStatus) const
-{
- return isAllowedByAllWithContext<&CSPDirectiveList::allowInlineScript>(m_policies, contextURL, contextLine, reportingStatus);
-}
-
-bool ContentSecurityPolicy::allowInlineStyle(const String& contextURL, const WTF::OrdinalNumber& contextLine, ContentSecurityPolicy::ReportingStatus reportingStatus) const
-{
- if (m_overrideInlineStyleAllowed)
- return true;
- return isAllowedByAllWithContext<&CSPDirectiveList::allowInlineStyle>(m_policies, contextURL, contextLine, reportingStatus);
-}
-
-bool ContentSecurityPolicy::allowEval(ScriptState* state, ContentSecurityPolicy::ReportingStatus reportingStatus) const
-{
- return isAllowedByAllWithState<&CSPDirectiveList::allowEval>(m_policies, state, reportingStatus);
-}
-
-String ContentSecurityPolicy::evalDisabledErrorMessage() const
-{
- for (size_t i = 0; i < m_policies.size(); ++i) {
- if (!m_policies[i]->allowEval(0, SuppressReport))
- return m_policies[i]->evalDisabledErrorMessage();
- }
- return String();
-}
-
-bool ContentSecurityPolicy::allowPluginType(const String& type, const String& typeAttribute, const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
-{
- for (size_t i = 0; i < m_policies.size(); ++i) {
- if (!m_policies[i]->allowPluginType(type, typeAttribute, url, reportingStatus))
- return false;
- }
- return true;
-}
-
-bool ContentSecurityPolicy::allowScriptFromSource(const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
-{
- return isAllowedByAllWithURL<&CSPDirectiveList::allowScriptFromSource>(m_policies, url, reportingStatus);
-}
-
-bool ContentSecurityPolicy::allowScriptNonce(const String& nonce) const
-{
- return isAllowedByAllWithNonce<&CSPDirectiveList::allowScriptNonce>(m_policies, nonce);
-}
-
-bool ContentSecurityPolicy::allowObjectFromSource(const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
-{
- return isAllowedByAllWithURL<&CSPDirectiveList::allowObjectFromSource>(m_policies, url, reportingStatus);
-}
-
-bool ContentSecurityPolicy::allowChildFrameFromSource(const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
-{
- return isAllowedByAllWithURL<&CSPDirectiveList::allowChildFrameFromSource>(m_policies, url, reportingStatus);
-}
-
-bool ContentSecurityPolicy::allowImageFromSource(const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
-{
- return isAllowedByAllWithURL<&CSPDirectiveList::allowImageFromSource>(m_policies, url, reportingStatus);
-}
-
-bool ContentSecurityPolicy::allowStyleFromSource(const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
-{
- return isAllowedByAllWithURL<&CSPDirectiveList::allowStyleFromSource>(m_policies, url, reportingStatus);
-}
-
-bool ContentSecurityPolicy::allowFontFromSource(const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
-{
- return isAllowedByAllWithURL<&CSPDirectiveList::allowFontFromSource>(m_policies, url, reportingStatus);
-}
-
-bool ContentSecurityPolicy::allowMediaFromSource(const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
-{
- return isAllowedByAllWithURL<&CSPDirectiveList::allowMediaFromSource>(m_policies, url, reportingStatus);
-}
-
-bool ContentSecurityPolicy::allowConnectToSource(const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
-{
- return isAllowedByAllWithURL<&CSPDirectiveList::allowConnectToSource>(m_policies, url, reportingStatus);
-}
-
-bool ContentSecurityPolicy::allowFormAction(const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
-{
- return isAllowedByAllWithURL<&CSPDirectiveList::allowFormAction>(m_policies, url, reportingStatus);
-}
-
-bool ContentSecurityPolicy::allowBaseURI(const KURL& url, ContentSecurityPolicy::ReportingStatus reportingStatus) const
-{
- return isAllowedByAllWithURL<&CSPDirectiveList::allowBaseURI>(m_policies, url, reportingStatus);
-}
-
-bool ContentSecurityPolicy::isActive() const
-{
- return !m_policies.isEmpty();
-}
-
-ContentSecurityPolicy::ReflectedXSSDisposition ContentSecurityPolicy::reflectedXSSDisposition() const
-{
- ReflectedXSSDisposition disposition = ReflectedXSSUnset;
- for (size_t i = 0; i < m_policies.size(); ++i) {
- if (m_policies[i]->reflectedXSSDisposition() > disposition)
- disposition = std::max(disposition, m_policies[i]->reflectedXSSDisposition());
- }
- return disposition;
-}
-
-void ContentSecurityPolicy::gatherReportURIs(DOMStringList& list) const
-{
- for (size_t i = 0; i < m_policies.size(); ++i)
- m_policies[i]->gatherReportURIs(list);
-}
-
-SecurityOrigin* ContentSecurityPolicy::securityOrigin() const
-{
- return m_scriptExecutionContext->securityOrigin();
-}
-
-const KURL& ContentSecurityPolicy::url() const
-{
- return m_scriptExecutionContext->url();
-}
-
-KURL ContentSecurityPolicy::completeURL(const String& url) const
-{
- return m_scriptExecutionContext->completeURL(url);
-}
-
-void ContentSecurityPolicy::enforceSandboxFlags(SandboxFlags mask) const
-{
- m_scriptExecutionContext->enforceSandboxFlags(mask);
-}
-
-static String stripURLForUseInReport(Document* document, const KURL& url)
-{
- if (!url.isValid())
- return String();
- if (!url.isHierarchical() || url.protocolIs("file"))
- return url.protocol();
- return document->securityOrigin()->canRequest(url) ? url.strippedForUseAsReferrer() : SecurityOrigin::create(url)->toString();
-}
-
-static void gatherSecurityPolicyViolationEventData(SecurityPolicyViolationEventInit& init, Document* document, const String& directiveText, const String& effectiveDirective, const KURL& blockedURL, const String& header)
-{
- init.documentURI = document->url().string();
- init.referrer = document->referrer();
- init.blockedURI = stripURLForUseInReport(document, blockedURL);
- init.violatedDirective = directiveText;
- init.effectiveDirective = effectiveDirective;
- init.originalPolicy = header;
- init.sourceFile = String();
- init.lineNumber = 0;
- init.columnNumber = 0;
- init.statusCode = 0;
-
- if (!SecurityOrigin::isSecure(document->url()) && document->loader())
- init.statusCode = document->loader()->response().httpStatusCode();
-
- RefPtr<ScriptCallStack> stack = createScriptCallStack(1, false);
- if (!stack)
- return;
-
- const ScriptCallFrame& callFrame = stack->at(0);
-
- if (callFrame.lineNumber()) {
- KURL source = KURL(ParsedURLString, callFrame.sourceURL());
- init.sourceFile = stripURLForUseInReport(document, source);
- init.lineNumber = callFrame.lineNumber();
- init.columnNumber = callFrame.columnNumber();
- }
-}
-
-void ContentSecurityPolicy::reportViolation(const String& directiveText, const String& effectiveDirective, const String& consoleMessage, const KURL& blockedURL, const Vector<KURL>& reportURIs, const String& header)
-{
- // FIXME: Support sending reports from worker.
- if (!m_scriptExecutionContext->isDocument())
- return;
-
- Document* document = toDocument(m_scriptExecutionContext);
- Frame* frame = document->frame();
- if (!frame)
- return;
-
- SecurityPolicyViolationEventInit violationData;
- gatherSecurityPolicyViolationEventData(violationData, document, directiveText, effectiveDirective, blockedURL, header);
-
- if (experimentalFeaturesEnabled())
- document->enqueueDocumentEvent(SecurityPolicyViolationEvent::create(eventNames().securitypolicyviolationEvent, violationData));
-
- if (reportURIs.isEmpty())
- return;
-
- // We need to be careful here when deciding what information to send to the
- // report-uri. Currently, we send only the current document's URL and the
- // directive that was violated. The document's URL is safe to send because
- // it's the document itself that's requesting that it be sent. You could
- // make an argument that we shouldn't send HTTPS document URLs to HTTP
- // report-uris (for the same reasons that we supress the Referer in that
- // case), but the Referer is sent implicitly whereas this request is only
- // sent explicitly. As for which directive was violated, that's pretty
- // harmless information.
-
- RefPtr<JSONObject> cspReport = JSONObject::create();
- cspReport->setString("document-uri", violationData.documentURI);
- cspReport->setString("referrer", violationData.referrer);
- cspReport->setString("violated-directive", violationData.violatedDirective);
- if (experimentalFeaturesEnabled())
- cspReport->setString("effective-directive", violationData.effectiveDirective);
- cspReport->setString("original-policy", violationData.originalPolicy);
- cspReport->setString("blocked-uri", violationData.blockedURI);
- if (!violationData.sourceFile.isEmpty() && violationData.lineNumber) {
- cspReport->setString("source-file", violationData.sourceFile);
- cspReport->setNumber("line-number", violationData.lineNumber);
- cspReport->setNumber("column-number", violationData.columnNumber);
- }
- cspReport->setNumber("status-code", violationData.statusCode);
-
- RefPtr<JSONObject> reportObject = JSONObject::create();
- reportObject->setObject("csp-report", cspReport.release());
- String stringifiedReport = reportObject->toJSONString();
-
- if (!shouldSendViolationReport(stringifiedReport))
- return;
-
- RefPtr<FormData> report = FormData::create(stringifiedReport.utf8());
-
- for (size_t i = 0; i < reportURIs.size(); ++i)
- PingLoader::sendViolationReport(frame, reportURIs[i], report, PingLoader::ContentSecurityPolicyViolationReport);
-
- didSendViolationReport(stringifiedReport);
-}
-
-void ContentSecurityPolicy::reportUnsupportedDirective(const String& name) const
-{
- DEFINE_STATIC_LOCAL(String, allow, ("allow"));
- DEFINE_STATIC_LOCAL(String, options, ("options"));
- DEFINE_STATIC_LOCAL(String, policyURI, ("policy-uri"));
- DEFINE_STATIC_LOCAL(String, allowMessage, ("The 'allow' directive has been replaced with 'default-src'. Please use that directive instead, as 'allow' has no effect."));
- DEFINE_STATIC_LOCAL(String, optionsMessage, ("The 'options' directive has been replaced with 'unsafe-inline' and 'unsafe-eval' source expressions for the 'script-src' and 'style-src' directives. Please use those directives instead, as 'options' has no effect."));
- DEFINE_STATIC_LOCAL(String, policyURIMessage, ("The 'policy-uri' directive has been removed from the specification. Please specify a complete policy via the Content-Security-Policy header."));
-
- String message = "Unrecognized Content-Security-Policy directive '" + name + "'.\n";
- if (equalIgnoringCase(name, allow))
- message = allowMessage;
- else if (equalIgnoringCase(name, options))
- message = optionsMessage;
- else if (equalIgnoringCase(name, policyURI))
- message = policyURIMessage;
-
- logToConsole(message);
-}
-
-void ContentSecurityPolicy::reportDirectiveAsSourceExpression(const String& directiveName, const String& sourceExpression) const
-{
- String message = "The Content Security Policy directive '" + directiveName + "' contains '" + sourceExpression + "' as a source expression. Did you mean '" + directiveName + " ...; " + sourceExpression + "...' (note the semicolon)?";
- logToConsole(message);
-}
-
-void ContentSecurityPolicy::reportDuplicateDirective(const String& name) const
-{
- String message = "Ignoring duplicate Content-Security-Policy directive '" + name + "'.\n";
- logToConsole(message);
-}
-
-void ContentSecurityPolicy::reportInvalidPluginTypes(const String& pluginType) const
-{
- String message;
- if (pluginType.isNull())
- message = "'plugin-types' Content Security Policy directive is empty; all plugins will be blocked.\n";
- else
- message = "Invalid plugin type in 'plugin-types' Content Security Policy directive: '" + pluginType + "'.\n";
- logToConsole(message);
-}
-
-void ContentSecurityPolicy::reportInvalidSandboxFlags(const String& invalidFlags) const
-{
- logToConsole("Error while parsing the 'sandbox' Content Security Policy directive: " + invalidFlags);
-}
-
-void ContentSecurityPolicy::reportInvalidReflectedXSS(const String& invalidValue) const
-{
- logToConsole("The 'reflected-xss' Content Security Policy directive has the invalid value \"" + invalidValue + "\". Valid values are \"allow\", \"filter\", and \"block\".");
-}
-
-void ContentSecurityPolicy::reportInvalidDirectiveValueCharacter(const String& directiveName, const String& value) const
-{
- String message = "The value for Content Security Policy directive '" + directiveName + "' contains an invalid character: '" + value + "'. Non-whitespace characters outside ASCII 0x21-0x7E must be percent-encoded, as described in RFC 3986, section 2.1: http://tools.ietf.org/html/rfc3986#section-2.1.";
- logToConsole(message);
-}
-
-void ContentSecurityPolicy::reportInvalidPathCharacter(const String& directiveName, const String& value, const char invalidChar) const
-{
- ASSERT(invalidChar == '#' || invalidChar == '?');
-
- String ignoring = "The fragment identifier, including the '#', will be ignored.";
- if (invalidChar == '?')
- ignoring = "The query component, including the '?', will be ignored.";
- String message = "The source list for Content Security Policy directive '" + directiveName + "' contains a source with an invalid path: '" + value + "'. " + ignoring;
- logToConsole(message);
-}
-
-void ContentSecurityPolicy::reportInvalidNonce(const String& nonce) const
-{
- String message = "Ignoring invalid Content Security Policy script nonce: '" + nonce + "'.\n";
- logToConsole(message);
-}
-
-void ContentSecurityPolicy::reportInvalidSourceExpression(const String& directiveName, const String& source) const
-{
- String message = "The source list for Content Security Policy directive '" + directiveName + "' contains an invalid source: '" + source + "'. It will be ignored.";
- if (equalIgnoringCase(source, "'none'"))
- message = message + " Note that 'none' has no effect unless it is the only expression in the source list.";
- logToConsole(message);
-}
-
-void ContentSecurityPolicy::reportMissingReportURI(const String& policy) const
-{
- logToConsole("The Content Security Policy '" + policy + "' was delivered in report-only mode, but does not specify a 'report-uri'; the policy will have no effect. Please either add a 'report-uri' directive, or deliver the policy via the 'Content-Security-Policy' header.");
-}
-
-void ContentSecurityPolicy::logToConsole(const String& message) const
-{
- m_scriptExecutionContext->addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, message);
-}
-
-void ContentSecurityPolicy::reportBlockedScriptExecutionToInspector(const String& directiveText) const
-{
- InspectorInstrumentation::scriptExecutionBlockedByCSP(m_scriptExecutionContext, directiveText);
-}
-
-bool ContentSecurityPolicy::experimentalFeaturesEnabled() const
-{
- return RuntimeEnabledFeatures::experimentalContentSecurityPolicyFeaturesEnabled();
-}
-
-bool ContentSecurityPolicy::shouldBypassMainWorld(ScriptExecutionContext* context)
-{
- if (context && context->isDocument()) {
- Document* document = toDocument(context);
- if (document->frame())
- return document->frame()->script()->shouldBypassMainWorldContentSecurityPolicy();
- }
- return false;
-}
-
-bool ContentSecurityPolicy::shouldSendViolationReport(const String& report) const
-{
- // Collisions have no security impact, so we can save space by storing only the string's hash rather than the whole report.
- return !m_violationReportsSent.contains(report.impl()->hash());
-}
-
-void ContentSecurityPolicy::didSendViolationReport(const String& report)
-{
- m_violationReportsSent.add(report.impl()->hash());
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/page/ContentSecurityPolicy.h b/chromium/third_party/WebKit/Source/core/page/ContentSecurityPolicy.h
deleted file mode 100644
index ad5c6b08872..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/ContentSecurityPolicy.h
+++ /dev/null
@@ -1,165 +0,0 @@
-/*
- * Copyright (C) 2011 Google, Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY GOOGLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ContentSecurityPolicy_h
-#define ContentSecurityPolicy_h
-
-#include "bindings/v8/ScriptState.h"
-#include "wtf/HashSet.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/Vector.h"
-#include "wtf/text/StringHash.h"
-#include "wtf/text/TextPosition.h"
-#include "wtf/text/WTFString.h"
-
-namespace WTF {
-class OrdinalNumber;
-}
-
-namespace WebCore {
-
-class ContentSecurityPolicyResponseHeaders;
-class CSPDirectiveList;
-class DOMStringList;
-class JSONObject;
-class KURL;
-class ScriptExecutionContext;
-class SecurityOrigin;
-
-typedef int SandboxFlags;
-typedef Vector<OwnPtr<CSPDirectiveList> > CSPDirectiveListVector;
-
-class ContentSecurityPolicy {
- WTF_MAKE_FAST_ALLOCATED;
-public:
- static PassOwnPtr<ContentSecurityPolicy> create(ScriptExecutionContext* scriptExecutionContext)
- {
- return adoptPtr(new ContentSecurityPolicy(scriptExecutionContext));
- }
- ~ContentSecurityPolicy();
-
- void copyStateFrom(const ContentSecurityPolicy*);
-
- enum HeaderType {
- Report,
- Enforce,
- PrefixedReport,
- PrefixedEnforce
- };
-
- enum ReportingStatus {
- SendReport,
- SuppressReport
- };
-
- // Be sure to update the behavior of XSSAuditor::combineXSSProtectionHeaderAndCSP whenever you change this enum's content or ordering.
- enum ReflectedXSSDisposition {
- ReflectedXSSUnset = 0,
- AllowReflectedXSS,
- ReflectedXSSInvalid,
- FilterReflectedXSS,
- BlockReflectedXSS
- };
-
- void didReceiveHeaders(const ContentSecurityPolicyResponseHeaders&);
- void didReceiveHeader(const String&, HeaderType);
-
- // These functions are wrong because they assume that there is only one header.
- // FIXME: Replace them with functions that return vectors.
- const String& deprecatedHeader() const;
- HeaderType deprecatedHeaderType() const;
-
- bool allowJavaScriptURLs(const String& contextURL, const WTF::OrdinalNumber& contextLine, ReportingStatus = SendReport) const;
- bool allowInlineEventHandlers(const String& contextURL, const WTF::OrdinalNumber& contextLine, ReportingStatus = SendReport) const;
- bool allowInlineScript(const String& contextURL, const WTF::OrdinalNumber& contextLine, ReportingStatus = SendReport) const;
- bool allowInlineStyle(const String& contextURL, const WTF::OrdinalNumber& contextLine, ReportingStatus = SendReport) const;
- bool allowEval(ScriptState* = 0, ReportingStatus = SendReport) const;
- bool allowPluginType(const String& type, const String& typeAttribute, const KURL&, ReportingStatus = SendReport) const;
-
- bool allowScriptFromSource(const KURL&, ReportingStatus = SendReport) const;
- bool allowObjectFromSource(const KURL&, ReportingStatus = SendReport) const;
- bool allowChildFrameFromSource(const KURL&, ReportingStatus = SendReport) const;
- bool allowImageFromSource(const KURL&, ReportingStatus = SendReport) const;
- bool allowStyleFromSource(const KURL&, ReportingStatus = SendReport) const;
- bool allowFontFromSource(const KURL&, ReportingStatus = SendReport) const;
- bool allowMediaFromSource(const KURL&, ReportingStatus = SendReport) const;
- bool allowConnectToSource(const KURL&, ReportingStatus = SendReport) const;
- bool allowFormAction(const KURL&, ReportingStatus = SendReport) const;
- bool allowBaseURI(const KURL&, ReportingStatus = SendReport) const;
- bool allowScriptNonce(const String& nonce) const;
-
- ReflectedXSSDisposition reflectedXSSDisposition() const;
-
- void setOverrideAllowInlineStyle(bool);
-
- bool isActive() const;
- void gatherReportURIs(DOMStringList&) const;
-
- void reportDirectiveAsSourceExpression(const String& directiveName, const String& sourceExpression) const;
- void reportDuplicateDirective(const String&) const;
- void reportInvalidDirectiveValueCharacter(const String& directiveName, const String& value) const;
- void reportInvalidPathCharacter(const String& directiveName, const String& value, const char) const;
- void reportInvalidNonce(const String&) const;
- void reportInvalidPluginTypes(const String&) const;
- void reportInvalidSandboxFlags(const String&) const;
- void reportInvalidSourceExpression(const String& directiveName, const String& source) const;
- void reportInvalidReflectedXSS(const String&) const;
- void reportMissingReportURI(const String&) const;
- void reportUnsupportedDirective(const String&) const;
- void reportViolation(const String& directiveText, const String& effectiveDirective, const String& consoleMessage, const KURL& blockedURL, const Vector<KURL>& reportURIs, const String& header);
-
- void reportBlockedScriptExecutionToInspector(const String& directiveText) const;
-
- const KURL& url() const;
- KURL completeURL(const String&) const;
- SecurityOrigin* securityOrigin() const;
- void enforceSandboxFlags(SandboxFlags) const;
- String evalDisabledErrorMessage() const;
-
- bool experimentalFeaturesEnabled() const;
-
- static bool shouldBypassMainWorld(ScriptExecutionContext*);
-
- ScriptExecutionContext* scriptExecutionContext() { return m_scriptExecutionContext; }
-
-private:
- explicit ContentSecurityPolicy(ScriptExecutionContext*);
-
- void logToConsole(const String& message) const;
- void addPolicyFromHeaderValue(const String&, HeaderType);
-
- bool shouldSendViolationReport(const String&) const;
- void didSendViolationReport(const String&);
-
- ScriptExecutionContext* m_scriptExecutionContext;
- bool m_overrideInlineStyleAllowed;
- CSPDirectiveListVector m_policies;
-
- HashSet<unsigned, AlreadyHashed> m_violationReportsSent;
-};
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/page/ContentSecurityPolicyResponseHeaders.cpp b/chromium/third_party/WebKit/Source/core/page/ContentSecurityPolicyResponseHeaders.cpp
deleted file mode 100644
index f51d7621696..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/ContentSecurityPolicyResponseHeaders.cpp
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright (C) 2013 Google, Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY GOOGLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/page/ContentSecurityPolicyResponseHeaders.h"
-
-#include "core/platform/network/ResourceResponse.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-ContentSecurityPolicyResponseHeaders::ContentSecurityPolicyResponseHeaders(const ResourceResponse& response)
- : m_contentSecurityPolicy(response.httpHeaderField("Content-Security-Policy"))
- , m_contentSecurityPolicyReportOnly(response.httpHeaderField("Content-Security-Policy-Report-Only"))
- , m_xWebKitCSP(response.httpHeaderField("X-WebKit-CSP"))
- , m_xWebKitCSPReportOnly(response.httpHeaderField("X-WebKit-CSP-Report-Only"))
-{
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/page/ContextMenuController.cpp b/chromium/third_party/WebKit/Source/core/page/ContextMenuController.cpp
index 226e2108b2f..cf5b8ba4e65 100644
--- a/chromium/third_party/WebKit/Source/core/page/ContextMenuController.cpp
+++ b/chromium/third_party/WebKit/Source/core/page/ContextMenuController.cpp
@@ -28,24 +28,21 @@
#include "core/page/ContextMenuController.h"
#include "core/dom/Document.h"
-#include "core/dom/Event.h"
-#include "core/dom/MouseEvent.h"
+#include "core/events/Event.h"
+#include "core/events/MouseEvent.h"
#include "core/dom/Node.h"
#include "core/page/ContextMenuClient.h"
#include "core/page/ContextMenuProvider.h"
#include "core/page/EventHandler.h"
-#include "core/page/Frame.h"
-#include "core/platform/ContextMenu.h"
-#include "core/platform/ContextMenuItem.h"
-#include "core/rendering/HitTestResult.h"
+#include "core/frame/Frame.h"
+#include "platform/ContextMenu.h"
+#include "platform/ContextMenuItem.h"
namespace WebCore {
-ContextMenuController::ContextMenuController(Page* page, ContextMenuClient* client)
- : m_page(page)
- , m_client(client)
+ContextMenuController::ContextMenuController(Page*, ContextMenuClient* client)
+ : m_client(client)
{
- ASSERT_ARG(page, page);
ASSERT_ARG(client, client);
}
@@ -72,7 +69,7 @@ void ContextMenuController::documentDetached(Document* document)
{
if (Node* innerNode = m_hitTestResult.innerNode()) {
// Invalidate the context menu info if its target document is detached.
- if (&innerNode->document() == document)
+ if (innerNode->document() == document)
clearContextMenu();
}
}
@@ -111,7 +108,7 @@ PassOwnPtr<ContextMenu> ContextMenuController::createContextMenu(Event* event)
HitTestResult result(mouseEvent->absoluteLocation());
if (Frame* frame = event->target()->toNode()->document().frame())
- result = frame->eventHandler()->hitTestResultAtPoint(mouseEvent->absoluteLocation(), HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::DisallowShadowContent);
+ result = frame->eventHandler().hitTestResultAtPoint(mouseEvent->absoluteLocation(), HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent);
if (!result.innerNonSharedNode())
return nullptr;
diff --git a/chromium/third_party/WebKit/Source/core/page/ContextMenuController.h b/chromium/third_party/WebKit/Source/core/page/ContextMenuController.h
index e36bedbd666..025638efe77 100644
--- a/chromium/third_party/WebKit/Source/core/page/ContextMenuController.h
+++ b/chromium/third_party/WebKit/Source/core/page/ContextMenuController.h
@@ -67,7 +67,6 @@ namespace WebCore {
PassOwnPtr<ContextMenu> createContextMenu(Event*);
void showContextMenu(Event*);
- Page* m_page;
ContextMenuClient* m_client;
OwnPtr<ContextMenu> m_contextMenu;
RefPtr<ContextMenuProvider> m_menuProvider;
diff --git a/chromium/third_party/WebKit/Source/core/page/CreateWindow.cpp b/chromium/third_party/WebKit/Source/core/page/CreateWindow.cpp
index d2b4fbeb4d5..6f588fa4430 100644
--- a/chromium/third_party/WebKit/Source/core/page/CreateWindow.cpp
+++ b/chromium/third_party/WebKit/Source/core/page/CreateWindow.cpp
@@ -28,30 +28,29 @@
#include "core/page/CreateWindow.h"
#include "core/dom/Document.h"
+#include "core/frame/Frame.h"
#include "core/loader/FrameLoadRequest.h"
#include "core/page/Chrome.h"
#include "core/page/ChromeClient.h"
-#include "core/page/Frame.h"
+#include "core/page/FocusController.h"
#include "core/page/Page.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
#include "core/page/WindowFeatures.h"
-#include "core/platform/network/ResourceRequest.h"
-#include "weborigin/KURL.h"
-#include "weborigin/SecurityOrigin.h"
-#include "weborigin/SecurityPolicy.h"
+#include "platform/network/ResourceRequest.h"
+#include "platform/weborigin/KURL.h"
+#include "platform/weborigin/SecurityOrigin.h"
+#include "platform/weborigin/SecurityPolicy.h"
namespace WebCore {
-static Frame* createWindow(Frame* openerFrame, Frame* lookupFrame, const FrameLoadRequest& request, const WindowFeatures& features, bool& created)
+static Frame* createWindow(Frame* openerFrame, Frame* lookupFrame, const FrameLoadRequest& request, const WindowFeatures& features, NavigationPolicy policy, ShouldSendReferrer shouldSendReferrer, bool& created)
{
ASSERT(!features.dialog || request.frameName().isEmpty());
- if (!request.frameName().isEmpty() && request.frameName() != "_blank") {
- if (Frame* frame = lookupFrame->loader()->findFrameForNavigation(request.frameName(), openerFrame->document())) {
- if (request.frameName() != "_self") {
- if (Page* page = frame->page())
- page->chrome().focus();
- }
+ if (!request.frameName().isEmpty() && request.frameName() != "_blank" && policy == NavigationPolicyIgnore) {
+ if (Frame* frame = lookupFrame->loader().findFrameForNavigation(request.frameName(), openerFrame->document())) {
+ if (request.frameName() != "_self")
+ frame->page()->focusController().setFocusedFrame(frame);
created = false;
return frame;
}
@@ -66,23 +65,23 @@ static Frame* createWindow(Frame* openerFrame, Frame* lookupFrame, const FrameLo
if (openerFrame->settings() && !openerFrame->settings()->supportsMultipleWindows()) {
created = false;
- return openerFrame->tree()->top();
+ return openerFrame->tree().top();
}
Page* oldPage = openerFrame->page();
if (!oldPage)
return 0;
- Page* page = oldPage->chrome().client().createWindow(openerFrame, request, features);
+ Page* page = oldPage->chrome().client().createWindow(openerFrame, request, features, policy, shouldSendReferrer);
if (!page)
return 0;
Frame* frame = page->mainFrame();
- frame->loader()->forceSandboxFlags(openerFrame->document()->sandboxFlags());
+ frame->loader().forceSandboxFlags(openerFrame->document()->sandboxFlags());
if (request.frameName() != "_blank")
- frame->tree()->setName(request.frameName());
+ frame->tree().setName(request.frameName());
page->chrome().setWindowFeatures(features);
@@ -106,7 +105,7 @@ static Frame* createWindow(Frame* openerFrame, Frame* lookupFrame, const FrameLo
FloatRect newWindowRect = DOMWindow::adjustWindowRect(page, windowRect);
page->chrome().setWindowRect(newWindowRect);
- page->chrome().show();
+ page->chrome().show(policy);
created = true;
return frame;
@@ -125,20 +124,20 @@ Frame* createWindow(const String& urlString, const AtomicString& frameName, cons
}
// For whatever reason, Firefox uses the first frame to determine the outgoingReferrer. We replicate that behavior here.
- String referrer = SecurityPolicy::generateReferrerHeader(firstFrame->document()->referrerPolicy(), completedURL, firstFrame->loader()->outgoingReferrer());
+ String referrer = SecurityPolicy::generateReferrerHeader(firstFrame->document()->referrerPolicy(), completedURL, firstFrame->document()->outgoingReferrer());
ResourceRequest request(completedURL, referrer);
- FrameLoader::addHTTPOriginIfNeeded(request, firstFrame->loader()->outgoingOrigin());
- FrameLoadRequest frameRequest(activeWindow->document()->securityOrigin(), request, frameName);
+ FrameLoader::addHTTPOriginIfNeeded(request, firstFrame->document()->outgoingOrigin());
+ FrameLoadRequest frameRequest(activeWindow->document(), request, frameName);
// We pass the opener frame for the lookupFrame in case the active frame is different from
// the opener frame, and the name references a frame relative to the opener frame.
bool created;
- Frame* newFrame = createWindow(activeFrame, openerFrame, frameRequest, windowFeatures, created);
+ Frame* newFrame = createWindow(activeFrame, openerFrame, frameRequest, windowFeatures, NavigationPolicyIgnore, MaybeSendReferrer, created);
if (!newFrame)
return 0;
- newFrame->loader()->setOpener(openerFrame);
+ newFrame->loader().setOpener(openerFrame);
newFrame->page()->setOpenedByDOM();
if (newFrame->domWindow()->isInsecureScriptAccess(activeWindow, completedURL))
@@ -148,12 +147,41 @@ Frame* createWindow(const String& urlString, const AtomicString& frameName, cons
function(newFrame->domWindow(), functionContext);
if (created) {
- FrameLoadRequest request(activeWindow->document()->securityOrigin(), ResourceRequest(completedURL, referrer));
- newFrame->loader()->load(request);
+ FrameLoadRequest request(activeWindow->document(), ResourceRequest(completedURL, referrer));
+ newFrame->loader().load(request);
} else if (!urlString.isEmpty()) {
- newFrame->navigationScheduler()->scheduleLocationChange(activeWindow->document()->securityOrigin(), completedURL.string(), referrer, false);
+ newFrame->navigationScheduler().scheduleLocationChange(activeWindow->document(), completedURL.string(), referrer, false);
}
return newFrame;
}
+void createWindowForRequest(const FrameLoadRequest& request, Frame* openerFrame, NavigationPolicy policy, ShouldSendReferrer shouldSendReferrer)
+{
+ if (openerFrame->document()->pageDismissalEventBeingDispatched() != Document::NoDismissal)
+ return;
+
+ if (openerFrame->document() && openerFrame->document()->isSandboxed(SandboxPopups))
+ return;
+
+ if (!DOMWindow::allowPopUp(openerFrame))
+ return;
+
+ if (policy == NavigationPolicyCurrentTab)
+ policy = NavigationPolicyNewForegroundTab;
+
+ WindowFeatures features;
+ bool created;
+ Frame* newFrame = createWindow(openerFrame, openerFrame, request, features, policy, shouldSendReferrer, created);
+ if (!newFrame)
+ return;
+ newFrame->page()->setOpenedByDOM();
+ if (shouldSendReferrer == MaybeSendReferrer) {
+ newFrame->loader().setOpener(openerFrame);
+ newFrame->document()->setReferrerPolicy(openerFrame->document()->referrerPolicy());
+ }
+ FrameLoadRequest newRequest(0, request.resourceRequest());
+ newRequest.setFormState(request.formState());
+ newFrame->loader().load(newRequest);
+}
+
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/page/CreateWindow.h b/chromium/third_party/WebKit/Source/core/page/CreateWindow.h
index 41603445797..1c2f3537a70 100644
--- a/chromium/third_party/WebKit/Source/core/page/CreateWindow.h
+++ b/chromium/third_party/WebKit/Source/core/page/CreateWindow.h
@@ -27,16 +27,21 @@
#ifndef CreateWindow_h
#define CreateWindow_h
-#include "core/page/DOMWindow.h"
+#include "core/frame/DOMWindow.h"
+#include "core/loader/FrameLoaderTypes.h"
+#include "core/loader/NavigationPolicy.h"
#include "wtf/text/WTFString.h"
namespace WebCore {
class Frame;
-class WindowFeatures;
+struct FrameLoadRequest;
+struct WindowFeatures;
Frame* createWindow(const String& urlString, const AtomicString& frameName, const WindowFeatures&,
DOMWindow* activeWindow, Frame* firstFrame, Frame* openerFrame, DOMWindow::PrepareDialogFunction = 0, void* functionContext = 0);
+void createWindowForRequest(const FrameLoadRequest&, Frame* openerFrame, NavigationPolicy, ShouldSendReferrer);
+
} // namespace WebCore
#endif // CreateWindow_h
diff --git a/chromium/third_party/WebKit/Source/core/page/DOMPoint.h b/chromium/third_party/WebKit/Source/core/page/DOMPoint.h
deleted file mode 100644
index 060e19a767d..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/DOMPoint.h
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright (C) 2009 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef DOMPoint_h
-#define DOMPoint_h
-
-#include "bindings/v8/ScriptWrappable.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-
-namespace WebCore {
-
-class DOMPoint : public RefCounted<DOMPoint>, public ScriptWrappable {
-public:
- static PassRefPtr<DOMPoint> create()
- {
- return adoptRef(new DOMPoint());
- }
- static PassRefPtr<DOMPoint> create(float x, float y)
- {
- return adoptRef(new DOMPoint(x, y));
- }
-
- float x() const { return m_x; }
- float y() const { return m_y; }
-
- void setX(float x) { m_x = x; }
- void setY(float y) { m_y = y; }
-
-private:
- DOMPoint(float x=0, float y=0)
- : m_x(x)
- , m_y(y)
- {
- ScriptWrappable::init(this);
- }
-
- float m_x;
- float m_y;
-};
-
-} // namespace WebCore
-
-#endif // DOMPoint_h
diff --git a/chromium/third_party/WebKit/Source/core/page/DOMSecurityPolicy.cpp b/chromium/third_party/WebKit/Source/core/page/DOMSecurityPolicy.cpp
deleted file mode 100644
index 1c62083a4ad..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/DOMSecurityPolicy.cpp
+++ /dev/null
@@ -1,176 +0,0 @@
-/*
- * Copyright (C) 2012 Google, Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY GOOGLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/page/DOMSecurityPolicy.h"
-
-#include "core/dom/ContextLifecycleObserver.h"
-#include "core/dom/DOMStringList.h"
-#include "core/dom/ScriptExecutionContext.h"
-#include "core/page/ContentSecurityPolicy.h"
-#include "wtf/text/TextPosition.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-namespace {
-
-bool isPolicyActiveInContext(ScriptExecutionContext* context)
-{
- // If the ScriptExecutionContext has been destroyed, there's no active policy.
- if (!context)
- return false;
-
- return context->contentSecurityPolicy()->isActive();
-}
-
-template<bool (ContentSecurityPolicy::*allowWithType)(const String&, const String&, const KURL&, ContentSecurityPolicy::ReportingStatus) const>
-bool isAllowedWithType(ScriptExecutionContext* context, const String& type)
-{
- if (!isPolicyActiveInContext(context))
- return true;
-
- return (context->contentSecurityPolicy()->*allowWithType)(type, type, KURL(), ContentSecurityPolicy::SuppressReport);
-}
-
-template<bool (ContentSecurityPolicy::*allowWithURL)(const KURL&, ContentSecurityPolicy::ReportingStatus) const>
-bool isAllowedWithURL(ScriptExecutionContext* context, const String& url)
-{
- if (!isPolicyActiveInContext(context))
- return true;
-
- KURL parsedURL = context->completeURL(url);
- if (!parsedURL.isValid())
- return false; // FIXME: Figure out how to throw a JavaScript error.
-
- return (context->contentSecurityPolicy()->*allowWithURL)(parsedURL, ContentSecurityPolicy::SuppressReport);
-}
-
-template<bool (ContentSecurityPolicy::*allowWithContext)(const String&, const WTF::OrdinalNumber&, ContentSecurityPolicy::ReportingStatus) const>
-bool isAllowed(ScriptExecutionContext* context)
-{
- if (!isPolicyActiveInContext(context))
- return true;
-
- return (context->contentSecurityPolicy()->*allowWithContext)(String(), WTF::OrdinalNumber::beforeFirst(), ContentSecurityPolicy::SuppressReport);
-}
-
-} // namespace
-
-DOMSecurityPolicy::DOMSecurityPolicy(ScriptExecutionContext* context)
- : ContextLifecycleObserver(context)
-{
- ScriptWrappable::init(this);
-}
-
-DOMSecurityPolicy::~DOMSecurityPolicy()
-{
-}
-
-bool DOMSecurityPolicy::isActive() const
-{
- return isPolicyActiveInContext(scriptExecutionContext());
-}
-
-PassRefPtr<DOMStringList> DOMSecurityPolicy::reportURIs() const
-{
- RefPtr<DOMStringList> result = DOMStringList::create();
-
- if (isActive())
- scriptExecutionContext()->contentSecurityPolicy()->gatherReportURIs(*result.get());
-
- return result.release();
-}
-
-bool DOMSecurityPolicy::allowsInlineScript() const
-{
- return isAllowed<&ContentSecurityPolicy::allowInlineScript>(scriptExecutionContext());
-}
-
-bool DOMSecurityPolicy::allowsInlineStyle() const
-{
- return isAllowed<&ContentSecurityPolicy::allowInlineStyle>(scriptExecutionContext());
-}
-
-bool DOMSecurityPolicy::allowsEval() const
-{
- if (!isActive())
- return true;
-
- return scriptExecutionContext()->contentSecurityPolicy()->allowEval(0, ContentSecurityPolicy::SuppressReport);
-}
-
-
-bool DOMSecurityPolicy::allowsConnectionTo(const String& url) const
-{
- return isAllowedWithURL<&ContentSecurityPolicy::allowConnectToSource>(scriptExecutionContext(), url);
-}
-
-bool DOMSecurityPolicy::allowsFontFrom(const String& url) const
-{
- return isAllowedWithURL<&ContentSecurityPolicy::allowFontFromSource>(scriptExecutionContext(), url);
-}
-
-bool DOMSecurityPolicy::allowsFormAction(const String& url) const
-{
- return isAllowedWithURL<&ContentSecurityPolicy::allowFormAction>(scriptExecutionContext(), url);
-}
-
-bool DOMSecurityPolicy::allowsFrameFrom(const String& url) const
-{
- return isAllowedWithURL<&ContentSecurityPolicy::allowChildFrameFromSource>(scriptExecutionContext(), url);
-}
-
-bool DOMSecurityPolicy::allowsImageFrom(const String& url) const
-{
- return isAllowedWithURL<&ContentSecurityPolicy::allowImageFromSource>(scriptExecutionContext(), url);
-}
-
-bool DOMSecurityPolicy::allowsMediaFrom(const String& url) const
-{
- return isAllowedWithURL<&ContentSecurityPolicy::allowMediaFromSource>(scriptExecutionContext(), url);
-}
-
-bool DOMSecurityPolicy::allowsObjectFrom(const String& url) const
-{
- return isAllowedWithURL<&ContentSecurityPolicy::allowObjectFromSource>(scriptExecutionContext(), url);
-}
-
-bool DOMSecurityPolicy::allowsPluginType(const String& type) const
-{
- return isAllowedWithType<&ContentSecurityPolicy::allowPluginType>(scriptExecutionContext(), type);
-}
-
-bool DOMSecurityPolicy::allowsScriptFrom(const String& url) const
-{
- return isAllowedWithURL<&ContentSecurityPolicy::allowScriptFromSource>(scriptExecutionContext(), url);
-}
-
-bool DOMSecurityPolicy::allowsStyleFrom(const String& url) const
-{
- return isAllowedWithURL<&ContentSecurityPolicy::allowStyleFromSource>(scriptExecutionContext(), url);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/page/DOMSecurityPolicy.h b/chromium/third_party/WebKit/Source/core/page/DOMSecurityPolicy.h
deleted file mode 100644
index 6cb8a804389..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/DOMSecurityPolicy.h
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Copyright (C) 2011 Google, Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY GOOGLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef DOMSecurityPolicy_h
-#define DOMSecurityPolicy_h
-
-#include "bindings/v8/ScriptWrappable.h"
-#include "core/dom/ContextLifecycleObserver.h"
-#include "wtf/RefCounted.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class ContentSecurityPolicy;
-class DOMStringList;
-class Frame;
-
-class DOMSecurityPolicy : public RefCounted<DOMSecurityPolicy>, public ScriptWrappable, public ContextLifecycleObserver {
-public:
- static PassRefPtr<DOMSecurityPolicy> create(ScriptExecutionContext* context)
- {
- return adoptRef(new DOMSecurityPolicy(context));
- }
- ~DOMSecurityPolicy();
-
- bool isActive() const;
- PassRefPtr<DOMStringList> reportURIs() const;
-
- bool allowsInlineScript() const;
- bool allowsInlineStyle() const;
- bool allowsEval() const;
-
- bool allowsConnectionTo(const String& url) const;
- bool allowsFontFrom(const String& url) const;
- bool allowsFormAction(const String& url) const;
- bool allowsFrameFrom(const String& url) const;
- bool allowsImageFrom(const String& url) const;
- bool allowsMediaFrom(const String& url) const;
- bool allowsObjectFrom(const String& url) const;
- bool allowsPluginType(const String& type) const;
- bool allowsScriptFrom(const String& url) const;
- bool allowsStyleFrom(const String& url) const;
-
-private:
- explicit DOMSecurityPolicy(ScriptExecutionContext*);
-};
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/page/DOMSelection.cpp b/chromium/third_party/WebKit/Source/core/page/DOMSelection.cpp
index a9fd1ad0d5f..4de89dec388 100644
--- a/chromium/third_party/WebKit/Source/core/page/DOMSelection.cpp
+++ b/chromium/third_party/WebKit/Source/core/page/DOMSelection.cpp
@@ -31,7 +31,6 @@
#include "config.h"
#include "core/page/DOMSelection.h"
-#include "bindings/v8/ExceptionMessages.h"
#include "bindings/v8/ExceptionState.h"
#include "bindings/v8/ExceptionStatePlaceholder.h"
#include "core/dom/Document.h"
@@ -42,7 +41,7 @@
#include "core/editing/FrameSelection.h"
#include "core/editing/TextIterator.h"
#include "core/editing/htmlediting.h"
-#include "core/page/Frame.h"
+#include "core/frame/Frame.h"
#include "wtf/text/WTFString.h"
namespace WebCore {
@@ -194,13 +193,13 @@ int DOMSelection::rangeCount() const
return m_frame->selection().isNone() ? 0 : 1;
}
-void DOMSelection::collapse(Node* node, int offset, ExceptionState& es)
+void DOMSelection::collapse(Node* node, int offset, ExceptionState& exceptionState)
{
if (!m_frame)
return;
if (offset < 0) {
- es.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("collapse", "Selection", String::number(offset) + " is not a valid offset."));
+ exceptionState.throwDOMException(IndexSizeError, String::number(offset) + " is not a valid offset.");
return;
}
@@ -211,7 +210,7 @@ void DOMSelection::collapse(Node* node, int offset, ExceptionState& es)
m_frame->selection().moveTo(VisiblePosition(createLegacyEditingPosition(node, offset), DOWNSTREAM));
}
-void DOMSelection::collapseToEnd(ExceptionState& es)
+void DOMSelection::collapseToEnd(ExceptionState& exceptionState)
{
if (!m_frame)
return;
@@ -219,14 +218,14 @@ void DOMSelection::collapseToEnd(ExceptionState& es)
const VisibleSelection& selection = m_frame->selection().selection();
if (selection.isNone()) {
- es.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("collapseToEnd", "Selection", "there is no selection."));
+ exceptionState.throwDOMException(InvalidStateError, "there is no selection.");
return;
}
m_frame->selection().moveTo(VisiblePosition(selection.end(), DOWNSTREAM));
}
-void DOMSelection::collapseToStart(ExceptionState& es)
+void DOMSelection::collapseToStart(ExceptionState& exceptionState)
{
if (!m_frame)
return;
@@ -234,7 +233,7 @@ void DOMSelection::collapseToStart(ExceptionState& es)
const VisibleSelection& selection = m_frame->selection().selection();
if (selection.isNone()) {
- es.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("collapseToStart", "Selection", "there is no selection."));
+ exceptionState.throwDOMException(InvalidStateError, "there is no selection.");
return;
}
@@ -248,18 +247,18 @@ void DOMSelection::empty()
m_frame->selection().clear();
}
-void DOMSelection::setBaseAndExtent(Node* baseNode, int baseOffset, Node* extentNode, int extentOffset, ExceptionState& es)
+void DOMSelection::setBaseAndExtent(Node* baseNode, int baseOffset, Node* extentNode, int extentOffset, ExceptionState& exceptionState)
{
if (!m_frame)
return;
if (baseOffset < 0) {
- es.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("setBaseAndExtent", "Selection", String::number(baseOffset) + " is not a valid base offset."));
+ exceptionState.throwDOMException(IndexSizeError, String::number(baseOffset) + " is not a valid base offset.");
return;
}
if (extentOffset < 0) {
- es.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("setBaseAndExtent", "Selection", String::number(extentOffset) + " is not a valid extent offset."));
+ exceptionState.throwDOMException(IndexSizeError, String::number(extentOffset) + " is not a valid extent offset.");
return;
}
@@ -273,12 +272,12 @@ void DOMSelection::setBaseAndExtent(Node* baseNode, int baseOffset, Node* extent
m_frame->selection().moveTo(visibleBase, visibleExtent);
}
-void DOMSelection::setPosition(Node* node, int offset, ExceptionState& es)
+void DOMSelection::setPosition(Node* node, int offset, ExceptionState& exceptionState)
{
if (!m_frame)
return;
if (offset < 0) {
- es.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("setPosition", "Selection", String::number(offset) + " is not a valid offset."));
+ exceptionState.throwDOMException(IndexSizeError, String::number(offset) + " is not a valid offset.");
return;
}
@@ -339,22 +338,22 @@ void DOMSelection::modify(const String& alterString, const String& directionStri
m_frame->selection().modify(alter, direction, granularity);
}
-void DOMSelection::extend(Node* node, int offset, ExceptionState& es)
+void DOMSelection::extend(Node* node, int offset, ExceptionState& exceptionState)
{
if (!m_frame)
return;
if (!node) {
- es.throwDOMException(TypeMismatchError, ExceptionMessages::failedToExecute("extend", "Selection", "The node provided is invalid."));
+ exceptionState.throwDOMException(TypeMismatchError, "The node provided is invalid.");
return;
}
if (offset < 0) {
- es.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("extend", "Selection", String::number(offset) + " is not a valid offset."));
+ exceptionState.throwDOMException(IndexSizeError, String::number(offset) + " is not a valid offset.");
return;
}
if (offset > (node->offsetInCharacters() ? caretMaxOffset(node) : (int)node->childNodeCount())) {
- es.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("extend", "Selection", String::number(offset) + " is larger than the given node's length."));
+ exceptionState.throwDOMException(IndexSizeError, String::number(offset) + " is larger than the given node's length.");
return;
}
@@ -365,13 +364,13 @@ void DOMSelection::extend(Node* node, int offset, ExceptionState& es)
m_frame->selection().setExtent(VisiblePosition(createLegacyEditingPosition(node, offset), DOWNSTREAM));
}
-PassRefPtr<Range> DOMSelection::getRangeAt(int index, ExceptionState& es)
+PassRefPtr<Range> DOMSelection::getRangeAt(int index, ExceptionState& exceptionState)
{
if (!m_frame)
return 0;
if (index < 0 || index >= rangeCount()) {
- es.throwDOMException(IndexSizeError, ExceptionMessages::failedToExecute("getRangeAt", "Selection", String::number(index) + " is not a valid index."));
+ exceptionState.throwDOMException(IndexSizeError, String::number(index) + " is not a valid index.");
return 0;
}
@@ -379,7 +378,8 @@ PassRefPtr<Range> DOMSelection::getRangeAt(int index, ExceptionState& es)
ASSERT(rangeCount() == 1);
if (Node* shadowAncestor = selectionShadowAncestor(m_frame)) {
- ContainerNode* container = shadowAncestor->parentNodeGuaranteedHostFree();
+ ASSERT(!shadowAncestor->isShadowRoot());
+ ContainerNode* container = shadowAncestor->parentOrShadowHostNode();
int offset = shadowAncestor->nodeIndex();
return Range::create(shadowAncestor->document(), container, offset, container, offset);
}
@@ -423,8 +423,8 @@ void DOMSelection::addRange(Range* r)
}
} else {
// We don't support discontiguous selection. We don't do anything if r and range don't intersect.
- TrackExceptionState es;
- if (r->compareBoundaryPoints(Range::END_TO_START, range.get(), es) < 1 && !es.hadException()) {
+ TrackExceptionState exceptionState;
+ if (r->compareBoundaryPoints(Range::END_TO_START, range.get(), exceptionState) < 1 && !exceptionState.hadException()) {
if (r->compareBoundaryPoints(Range::END_TO_END, range.get(), IGNORE_EXCEPTION) == -1) {
// The original range contains r.
selection.setSelection(VisibleSelection(range.get()));
@@ -465,7 +465,7 @@ bool DOMSelection::containsNode(const Node* n, bool allowPartial) const
FrameSelection& selection = m_frame->selection();
- if (!n || m_frame->document() != &n->document() || selection.isNone())
+ if (!n || m_frame->document() != n->document() || selection.isNone())
return false;
unsigned nodeIndex = n->nodeIndex();
@@ -475,29 +475,29 @@ bool DOMSelection::containsNode(const Node* n, bool allowPartial) const
if (!parentNode)
return false;
- TrackExceptionState es;
- bool nodeFullySelected = Range::compareBoundaryPoints(parentNode, nodeIndex, selectedRange->startContainer(), selectedRange->startOffset(), es) >= 0 && !es.hadException()
- && Range::compareBoundaryPoints(parentNode, nodeIndex + 1, selectedRange->endContainer(), selectedRange->endOffset(), es) <= 0 && !es.hadException();
- ASSERT(!es.hadException());
+ TrackExceptionState exceptionState;
+ bool nodeFullySelected = Range::compareBoundaryPoints(parentNode, nodeIndex, selectedRange->startContainer(), selectedRange->startOffset(), exceptionState) >= 0 && !exceptionState.hadException()
+ && Range::compareBoundaryPoints(parentNode, nodeIndex + 1, selectedRange->endContainer(), selectedRange->endOffset(), exceptionState) <= 0 && !exceptionState.hadException();
+ ASSERT(!exceptionState.hadException());
if (nodeFullySelected)
return true;
- bool nodeFullyUnselected = (Range::compareBoundaryPoints(parentNode, nodeIndex, selectedRange->endContainer(), selectedRange->endOffset(), es) > 0 && !es.hadException())
- || (Range::compareBoundaryPoints(parentNode, nodeIndex + 1, selectedRange->startContainer(), selectedRange->startOffset(), es) < 0 && !es.hadException());
- ASSERT(!es.hadException());
+ bool nodeFullyUnselected = (Range::compareBoundaryPoints(parentNode, nodeIndex, selectedRange->endContainer(), selectedRange->endOffset(), exceptionState) > 0 && !exceptionState.hadException())
+ || (Range::compareBoundaryPoints(parentNode, nodeIndex + 1, selectedRange->startContainer(), selectedRange->startOffset(), exceptionState) < 0 && !exceptionState.hadException());
+ ASSERT(!exceptionState.hadException());
if (nodeFullyUnselected)
return false;
return allowPartial || n->isTextNode();
}
-void DOMSelection::selectAllChildren(Node* n, ExceptionState& es)
+void DOMSelection::selectAllChildren(Node* n, ExceptionState& exceptionState)
{
if (!n)
return;
// This doesn't (and shouldn't) select text node characters.
- setBaseAndExtent(n, 0, n, n->childNodeCount(), es);
+ setBaseAndExtent(n, 0, n, n->childNodeCount(), exceptionState);
}
String DOMSelection::toString()
@@ -522,7 +522,8 @@ Node* DOMSelection::shadowAdjustedNode(const Position& position) const
if (containerNode == adjustedNode)
return containerNode;
- return adjustedNode->parentNodeGuaranteedHostFree();
+ ASSERT(!adjustedNode->isShadowRoot());
+ return adjustedNode->parentOrShadowHostNode();
}
int DOMSelection::shadowAdjustedOffset(const Position& position) const
@@ -547,7 +548,7 @@ bool DOMSelection::isValidForPosition(Node* node) const
ASSERT(m_frame);
if (!node)
return true;
- return &node->document() == m_frame->document();
+ return node->document() == m_frame->document();
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/page/DOMSelection.h b/chromium/third_party/WebKit/Source/core/page/DOMSelection.h
index 16d48f1f89a..0b4adfe0f98 100644
--- a/chromium/third_party/WebKit/Source/core/page/DOMSelection.h
+++ b/chromium/third_party/WebKit/Source/core/page/DOMSelection.h
@@ -32,7 +32,7 @@
#define DOMSelection_h
#include "bindings/v8/ScriptWrappable.h"
-#include "core/page/DOMWindowProperty.h"
+#include "core/frame/DOMWindowProperty.h"
#include "wtf/Forward.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefCounted.h"
diff --git a/chromium/third_party/WebKit/Source/core/page/DOMTimer.cpp b/chromium/third_party/WebKit/Source/core/page/DOMTimer.cpp
deleted file mode 100644
index 16210e59aad..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/DOMTimer.cpp
+++ /dev/null
@@ -1,201 +0,0 @@
-/*
- * Copyright (C) 2008 Apple Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-#include "config.h"
-#include "core/page/DOMTimer.h"
-
-#include "bindings/v8/ScheduledAction.h"
-#include "core/dom/ScriptExecutionContext.h"
-#include "core/inspector/InspectorInstrumentation.h"
-#include "wtf/CurrentTime.h"
-
-using namespace std;
-
-namespace WebCore {
-
-static const int maxIntervalForUserGestureForwarding = 1000; // One second matches Gecko.
-static const int maxTimerNestingLevel = 5;
-static const double oneMillisecond = 0.001;
-// Chromium uses a minimum timer interval of 4ms. We'd like to go
-// lower; however, there are poorly coded websites out there which do
-// create CPU-spinning loops. Using 4ms prevents the CPU from
-// spinning too busily and provides a balance between CPU spinning and
-// the smallest possible interval timer.
-static const double minimumInterval = 0.004;
-
-static int timerNestingLevel = 0;
-
-static inline bool shouldForwardUserGesture(int interval, int nestingLevel)
-{
- return UserGestureIndicator::processingUserGesture()
- && interval <= maxIntervalForUserGestureForwarding
- && nestingLevel == 1; // Gestures should not be forwarded to nested timers.
-}
-
-double DOMTimer::hiddenPageAlignmentInterval()
-{
- // Timers on hidden pages are aligned so that they fire once per
- // second at most.
- return 1.0;
-}
-
-double DOMTimer::visiblePageAlignmentInterval()
-{
- // Alignment does not apply to timers on visible pages.
- return 0;
-}
-
-int DOMTimer::install(ScriptExecutionContext* context, PassOwnPtr<ScheduledAction> action, int timeout, bool singleShot)
-{
- int timeoutID = context->installNewTimeout(action, timeout, singleShot);
- InspectorInstrumentation::didInstallTimer(context, timeoutID, timeout, singleShot);
- return timeoutID;
-}
-
-void DOMTimer::removeByID(ScriptExecutionContext* context, int timeoutID)
-{
- context->removeTimeoutByID(timeoutID);
- InspectorInstrumentation::didRemoveTimer(context, timeoutID);
-}
-
-DOMTimer::DOMTimer(ScriptExecutionContext* context, PassOwnPtr<ScheduledAction> action, int interval, bool singleShot, int timeoutID)
- : SuspendableTimer(context)
- , m_timeoutID(timeoutID)
- , m_nestingLevel(timerNestingLevel + 1)
- , m_action(action)
-{
- ASSERT(timeoutID > 0);
- if (shouldForwardUserGesture(interval, m_nestingLevel))
- m_userGestureToken = UserGestureIndicator::currentToken();
-
- double intervalMilliseconds = max(oneMillisecond, interval * oneMillisecond);
- if (intervalMilliseconds < minimumInterval && m_nestingLevel >= maxTimerNestingLevel)
- intervalMilliseconds = minimumInterval;
- if (singleShot)
- startOneShot(intervalMilliseconds);
- else
- startRepeating(intervalMilliseconds);
-}
-
-DOMTimer::~DOMTimer()
-{
-}
-
-int DOMTimer::timeoutID() const
-{
- return m_timeoutID;
-}
-
-void DOMTimer::fired()
-{
- ScriptExecutionContext* context = scriptExecutionContext();
- timerNestingLevel = m_nestingLevel;
- ASSERT(!context->activeDOMObjectsAreSuspended());
- // Only the first execution of a multi-shot timer should get an affirmative user gesture indicator.
- UserGestureIndicator gestureIndicator(m_userGestureToken.release());
-
- InspectorInstrumentationCookie cookie = InspectorInstrumentation::willFireTimer(context, m_timeoutID);
-
- // Simple case for non-one-shot timers.
- if (isActive()) {
- if (repeatInterval() && repeatInterval() < minimumInterval) {
- m_nestingLevel++;
- if (m_nestingLevel >= maxTimerNestingLevel)
- augmentRepeatInterval(minimumInterval - repeatInterval());
- }
-
- // No access to member variables after this point, it can delete the timer.
- m_action->execute(context);
-
- InspectorInstrumentation::didFireTimer(cookie);
-
- return;
- }
-
- // Delete timer before executing the action for one-shot timers.
- OwnPtr<ScheduledAction> action = m_action.release();
-
- // This timer is being deleted; no access to member variables allowed after this point.
- context->removeTimeoutByID(m_timeoutID);
-
- action->execute(context);
-
- InspectorInstrumentation::didFireTimer(cookie);
-
- timerNestingLevel = 0;
-}
-
-void DOMTimer::contextDestroyed()
-{
- SuspendableTimer::contextDestroyed();
-}
-
-void DOMTimer::stop()
-{
- SuspendableTimer::stop();
- // Need to release JS objects potentially protected by ScheduledAction
- // because they can form circular references back to the ScriptExecutionContext
- // which will cause a memory leak.
- m_action.clear();
-}
-
-double DOMTimer::alignedFireTime(double fireTime) const
-{
- double alignmentInterval = scriptExecutionContext()->timerAlignmentInterval();
- if (alignmentInterval) {
- double currentTime = monotonicallyIncreasingTime();
- if (fireTime <= currentTime)
- return fireTime;
-
- // When a repeating timer is scheduled for exactly the
- // background page alignment interval, because it's impossible
- // for the timer to be rescheduled instantaneously, it misses
- // every other fire time. Avoid this by looking at the next
- // fire time rounded both down and up.
-
- double alignedTimeRoundedDown = floor(fireTime / alignmentInterval) * alignmentInterval;
- double alignedTimeRoundedUp = ceil(fireTime / alignmentInterval) * alignmentInterval;
-
- // If the version rounded down is in the past, discard it
- // immediately.
-
- if (alignedTimeRoundedDown <= currentTime)
- return alignedTimeRoundedUp;
-
- // Only use the rounded-down time if it's within a certain
- // tolerance of the fire time. This avoids speeding up timers
- // on background pages in the common case.
-
- if (fireTime - alignedTimeRoundedDown < minimumInterval)
- return alignedTimeRoundedDown;
-
- return alignedTimeRoundedUp;
- }
-
- return fireTime;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/page/DOMTimer.h b/chromium/third_party/WebKit/Source/core/page/DOMTimer.h
deleted file mode 100644
index 9324899960a..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/DOMTimer.h
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * Copyright (C) 2008 Apple Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-#ifndef DOMTimer_h
-#define DOMTimer_h
-
-#include "bindings/v8/ScheduledAction.h"
-#include "core/dom/UserGestureIndicator.h"
-#include "core/page/SuspendableTimer.h"
-#include "wtf/Compiler.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/PassOwnPtr.h"
-
-namespace WebCore {
-
-class ScriptExecutionContext;
-
-class DOMTimer : public SuspendableTimer {
-public:
- // Creates a new timer owned by the ScriptExecutionContext, starts it and returns its ID.
- static int install(ScriptExecutionContext*, PassOwnPtr<ScheduledAction>, int timeout, bool singleShot);
- static void removeByID(ScriptExecutionContext*, int timeoutID);
-
- virtual ~DOMTimer();
-
- int timeoutID() const;
-
- // ActiveDOMObject
- virtual void contextDestroyed() OVERRIDE;
- virtual void stop() OVERRIDE;
-
- // The following are essentially constants. All intervals are in seconds.
- static double hiddenPageAlignmentInterval();
- static double visiblePageAlignmentInterval();
-
-private:
- friend class ScriptExecutionContext; // For create().
-
- // Should only be used by ScriptExecutionContext.
- static PassOwnPtr<DOMTimer> create(ScriptExecutionContext* context, PassOwnPtr<ScheduledAction> action, int timeout, bool singleShot, int timeoutID)
- {
- return adoptPtr(new DOMTimer(context, action, timeout, singleShot, timeoutID));
- }
-
- DOMTimer(ScriptExecutionContext*, PassOwnPtr<ScheduledAction>, int interval, bool singleShot, int timeoutID);
- virtual void fired();
-
- // Retuns timer fire time rounded to the next multiple of timer alignment interval.
- virtual double alignedFireTime(double) const;
-
- int m_timeoutID;
- int m_nestingLevel;
- OwnPtr<ScheduledAction> m_action;
- RefPtr<UserGestureToken> m_userGestureToken;
-};
-
-} // namespace WebCore
-
-#endif // DOMTimer_h
diff --git a/chromium/third_party/WebKit/Source/core/page/DOMWindow.cpp b/chromium/third_party/WebKit/Source/core/page/DOMWindow.cpp
deleted file mode 100644
index 1e59d664f73..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/DOMWindow.cpp
+++ /dev/null
@@ -1,1769 +0,0 @@
-/*
- * Copyright (C) 2006, 2007, 2008, 2010 Apple Inc. All rights reserved.
- * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/page/DOMWindow.h"
-
-#include "wtf/MainThread.h"
-#include "wtf/MathExtras.h"
-#include "wtf/text/WTFString.h"
-#include <algorithm>
-#include "RuntimeEnabledFeatures.h"
-#include "bindings/v8/ExceptionState.h"
-#include "bindings/v8/ExceptionStatePlaceholder.h"
-#include "bindings/v8/ScriptCallStackFactory.h"
-#include "bindings/v8/ScriptController.h"
-#include "bindings/v8/SerializedScriptValue.h"
-#include "core/css/CSSComputedStyleDeclaration.h"
-#include "core/css/CSSRuleList.h"
-#include "core/css/DOMWindowCSS.h"
-#include "core/css/MediaQueryList.h"
-#include "core/css/MediaQueryMatcher.h"
-#include "core/css/StyleMedia.h"
-#include "core/css/resolver/StyleResolver.h"
-#include "core/dom/DeviceOrientationController.h"
-#include "core/dom/Document.h"
-#include "core/dom/Element.h"
-#include "core/dom/EventListener.h"
-#include "core/dom/EventNames.h"
-#include "core/dom/ExceptionCode.h"
-#include "core/dom/MessageEvent.h"
-#include "core/dom/PageTransitionEvent.h"
-#include "core/dom/RequestAnimationFrameCallback.h"
-#include "core/dom/ScriptExecutionContext.h"
-#include "core/editing/Editor.h"
-#include "core/history/BackForwardController.h"
-#include "core/html/HTMLFrameOwnerElement.h"
-#include "core/inspector/InspectorInstrumentation.h"
-#include "core/inspector/ScriptCallStack.h"
-#include "core/loader/DocumentLoader.h"
-#include "core/loader/FrameLoadRequest.h"
-#include "core/loader/FrameLoader.h"
-#include "core/loader/FrameLoaderClient.h"
-#include "core/loader/appcache/ApplicationCache.h"
-#include "core/page/BarProp.h"
-#include "core/page/Chrome.h"
-#include "core/page/ChromeClient.h"
-#include "core/page/Console.h"
-#include "core/page/CreateWindow.h"
-#include "core/page/DOMPoint.h"
-#include "core/page/DOMWindowLifecycleNotifier.h"
-#include "core/page/EventHandler.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameTree.h"
-#include "core/page/FrameView.h"
-#include "core/page/History.h"
-#include "core/page/Location.h"
-#include "core/page/Navigator.h"
-#include "core/page/Page.h"
-#include "core/page/PageConsole.h"
-#include "core/page/PageGroup.h"
-#include "core/page/Performance.h"
-#include "core/page/Screen.h"
-#include "core/page/Settings.h"
-#include "core/page/WindowFeatures.h"
-#include "core/page/WindowFocusAllowedIndicator.h"
-#include "core/page/scrolling/ScrollingCoordinator.h"
-#include "core/platform/PlatformScreen.h"
-#include "core/platform/SuddenTermination.h"
-#include "core/platform/graphics/FloatRect.h"
-#include "core/platform/graphics/MediaPlayer.h"
-#include "core/storage/Storage.h"
-#include "core/storage/StorageArea.h"
-#include "core/storage/StorageNamespace.h"
-#include "weborigin/KURL.h"
-#include "weborigin/SecurityOrigin.h"
-#include "weborigin/SecurityPolicy.h"
-
-using std::min;
-using std::max;
-
-namespace WebCore {
-
-class PostMessageTimer : public TimerBase {
-public:
- PostMessageTimer(DOMWindow* window, PassRefPtr<SerializedScriptValue> message, const String& sourceOrigin, PassRefPtr<DOMWindow> source, PassOwnPtr<MessagePortChannelArray> channels, SecurityOrigin* targetOrigin, PassRefPtr<ScriptCallStack> stackTrace)
- : m_window(window)
- , m_message(message)
- , m_origin(sourceOrigin)
- , m_source(source)
- , m_channels(channels)
- , m_targetOrigin(targetOrigin)
- , m_stackTrace(stackTrace)
- {
- }
-
- PassRefPtr<MessageEvent> event(ScriptExecutionContext* context)
- {
- OwnPtr<MessagePortArray> messagePorts = MessagePort::entanglePorts(*context, m_channels.release());
- return MessageEvent::create(messagePorts.release(), m_message, m_origin, String(), m_source);
- }
- SecurityOrigin* targetOrigin() const { return m_targetOrigin.get(); }
- ScriptCallStack* stackTrace() const { return m_stackTrace.get(); }
-
-private:
- virtual void fired()
- {
- m_window->postMessageTimerFired(adoptPtr(this));
- // This object is deleted now.
- }
-
- RefPtr<DOMWindow> m_window;
- RefPtr<SerializedScriptValue> m_message;
- String m_origin;
- RefPtr<DOMWindow> m_source;
- OwnPtr<MessagePortChannelArray> m_channels;
- RefPtr<SecurityOrigin> m_targetOrigin;
- RefPtr<ScriptCallStack> m_stackTrace;
-};
-
-typedef HashCountedSet<DOMWindow*> DOMWindowSet;
-
-static DOMWindowSet& windowsWithUnloadEventListeners()
-{
- DEFINE_STATIC_LOCAL(DOMWindowSet, windowsWithUnloadEventListeners, ());
- return windowsWithUnloadEventListeners;
-}
-
-static DOMWindowSet& windowsWithBeforeUnloadEventListeners()
-{
- DEFINE_STATIC_LOCAL(DOMWindowSet, windowsWithBeforeUnloadEventListeners, ());
- return windowsWithBeforeUnloadEventListeners;
-}
-
-static void addUnloadEventListener(DOMWindow* domWindow)
-{
- DOMWindowSet& set = windowsWithUnloadEventListeners();
- if (set.isEmpty())
- disableSuddenTermination();
- set.add(domWindow);
-}
-
-static void removeUnloadEventListener(DOMWindow* domWindow)
-{
- DOMWindowSet& set = windowsWithUnloadEventListeners();
- DOMWindowSet::iterator it = set.find(domWindow);
- if (it == set.end())
- return;
- set.remove(it);
- if (set.isEmpty())
- enableSuddenTermination();
-}
-
-static void removeAllUnloadEventListeners(DOMWindow* domWindow)
-{
- DOMWindowSet& set = windowsWithUnloadEventListeners();
- DOMWindowSet::iterator it = set.find(domWindow);
- if (it == set.end())
- return;
- set.removeAll(it);
- if (set.isEmpty())
- enableSuddenTermination();
-}
-
-static void addBeforeUnloadEventListener(DOMWindow* domWindow)
-{
- DOMWindowSet& set = windowsWithBeforeUnloadEventListeners();
- if (set.isEmpty())
- disableSuddenTermination();
- set.add(domWindow);
-}
-
-static void removeBeforeUnloadEventListener(DOMWindow* domWindow)
-{
- DOMWindowSet& set = windowsWithBeforeUnloadEventListeners();
- DOMWindowSet::iterator it = set.find(domWindow);
- if (it == set.end())
- return;
- set.remove(it);
- if (set.isEmpty())
- enableSuddenTermination();
-}
-
-static void removeAllBeforeUnloadEventListeners(DOMWindow* domWindow)
-{
- DOMWindowSet& set = windowsWithBeforeUnloadEventListeners();
- DOMWindowSet::iterator it = set.find(domWindow);
- if (it == set.end())
- return;
- set.removeAll(it);
- if (set.isEmpty())
- enableSuddenTermination();
-}
-
-static bool allowsBeforeUnloadListeners(DOMWindow* window)
-{
- ASSERT_ARG(window, window);
- Frame* frame = window->frame();
- if (!frame)
- return false;
- Page* page = frame->page();
- if (!page)
- return false;
- return frame == page->mainFrame();
-}
-
-unsigned DOMWindow::pendingUnloadEventListeners() const
-{
- return windowsWithUnloadEventListeners().count(const_cast<DOMWindow*>(this));
-}
-
-// This function:
-// 1) Validates the pending changes are not changing any value to NaN; in that case keep original value.
-// 2) Constrains the window rect to the minimum window size and no bigger than the float rect's dimensions.
-// 3) Constrains the window rect to within the top and left boundaries of the available screen rect.
-// 4) Constrains the window rect to within the bottom and right boundaries of the available screen rect.
-// 5) Translate the window rect coordinates to be within the coordinate space of the screen.
-FloatRect DOMWindow::adjustWindowRect(Page* page, const FloatRect& pendingChanges)
-{
- ASSERT(page);
-
- FloatRect screen = screenAvailableRect(page->mainFrame()->view());
- FloatRect window = page->chrome().windowRect();
-
- // Make sure we're in a valid state before adjusting dimensions.
- ASSERT(std::isfinite(screen.x()));
- ASSERT(std::isfinite(screen.y()));
- ASSERT(std::isfinite(screen.width()));
- ASSERT(std::isfinite(screen.height()));
- ASSERT(std::isfinite(window.x()));
- ASSERT(std::isfinite(window.y()));
- ASSERT(std::isfinite(window.width()));
- ASSERT(std::isfinite(window.height()));
-
- // Update window values if new requested values are not NaN.
- if (!std::isnan(pendingChanges.x()))
- window.setX(pendingChanges.x());
- if (!std::isnan(pendingChanges.y()))
- window.setY(pendingChanges.y());
- if (!std::isnan(pendingChanges.width()))
- window.setWidth(pendingChanges.width());
- if (!std::isnan(pendingChanges.height()))
- window.setHeight(pendingChanges.height());
-
- FloatSize minimumSize = page->chrome().client().minimumWindowSize();
- // Let size 0 pass through, since that indicates default size, not minimum size.
- if (window.width())
- window.setWidth(min(max(minimumSize.width(), window.width()), screen.width()));
- if (window.height())
- window.setHeight(min(max(minimumSize.height(), window.height()), screen.height()));
-
- // Constrain the window position within the valid screen area.
- window.setX(max(screen.x(), min(window.x(), screen.maxX() - window.width())));
- window.setY(max(screen.y(), min(window.y(), screen.maxY() - window.height())));
-
- return window;
-}
-
-bool DOMWindow::allowPopUp(Frame* firstFrame)
-{
- ASSERT(firstFrame);
-
- if (ScriptController::processingUserGesture())
- return true;
-
- Settings* settings = firstFrame->settings();
- return settings && settings->javaScriptCanOpenWindowsAutomatically();
-}
-
-bool DOMWindow::allowPopUp()
-{
- return m_frame && allowPopUp(m_frame);
-}
-
-bool DOMWindow::canShowModalDialog(const Frame* frame)
-{
- if (!frame)
- return false;
- Page* page = frame->page();
- if (!page)
- return false;
- return page->chrome().canRunModal();
-}
-
-bool DOMWindow::canShowModalDialogNow(const Frame* frame)
-{
- if (!frame)
- return false;
- Page* page = frame->page();
- if (!page)
- return false;
- return page->chrome().canRunModalNow();
-}
-
-DOMWindow::DOMWindow(Frame* frame)
- : FrameDestructionObserver(frame)
- , m_shouldPrintWhenFinishedLoading(false)
-{
- ASSERT(frame);
- ScriptWrappable::init(this);
-}
-
-void DOMWindow::setDocument(PassRefPtr<Document> document)
-{
- ASSERT(!document || document->frame() == m_frame);
- if (m_document) {
- if (m_document->attached()) {
- // FIXME: We don't call willRemove here. Why is that OK?
- // This detach() call is also mostly redundant. Most of the calls to
- // this function come via DocumentLoader::createWriterFor, which
- // always detaches the previous Document first. Only XSLTProcessor
- // depends on this detach() call, so it seems like there's some room
- // for cleanup.
- m_document->detach();
- }
- m_document->setDOMWindow(0);
- }
-
- m_document = document;
-
- if (!m_document)
- return;
-
- m_document->setDOMWindow(this);
- if (!m_document->attached())
- m_document->attach();
-
- if (!m_frame)
- return;
-
- m_frame->script()->updateDocument();
- m_document->updateViewportArguments();
-
- if (m_frame->page() && m_frame->view()) {
- if (ScrollingCoordinator* scrollingCoordinator = m_frame->page()->scrollingCoordinator()) {
- scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(m_frame->view(), HorizontalScrollbar);
- scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(m_frame->view(), VerticalScrollbar);
- scrollingCoordinator->scrollableAreaScrollLayerDidChange(m_frame->view());
- }
- }
-
- m_frame->selection().updateSecureKeyboardEntryIfActive();
-
- if (m_frame->page() && m_frame->page()->mainFrame() == m_frame) {
- m_frame->page()->mainFrame()->notifyChromeClientWheelEventHandlerCountChanged();
- if (m_document->hasTouchEventHandlers())
- m_frame->page()->chrome().client().needTouchEvents(true);
- }
-}
-
-DOMWindow::~DOMWindow()
-{
- ASSERT(!m_screen);
- ASSERT(!m_history);
- ASSERT(!m_locationbar);
- ASSERT(!m_menubar);
- ASSERT(!m_personalbar);
- ASSERT(!m_scrollbars);
- ASSERT(!m_statusbar);
- ASSERT(!m_toolbar);
- ASSERT(!m_console);
- ASSERT(!m_navigator);
- ASSERT(!m_performance);
- ASSERT(!m_location);
- ASSERT(!m_media);
- ASSERT(!m_sessionStorage);
- ASSERT(!m_localStorage);
- ASSERT(!m_applicationCache);
-
- reset();
-
- removeAllEventListeners();
-
- ASSERT(!m_document->attached());
- setDocument(0);
-}
-
-const AtomicString& DOMWindow::interfaceName() const
-{
- return eventNames().interfaceForDOMWindow;
-}
-
-ScriptExecutionContext* DOMWindow::scriptExecutionContext() const
-{
- return m_document.get();
-}
-
-DOMWindow* DOMWindow::toDOMWindow()
-{
- return this;
-}
-
-PassRefPtr<MediaQueryList> DOMWindow::matchMedia(const String& media)
-{
- return document() ? document()->mediaQueryMatcher()->matchMedia(media) : 0;
-}
-
-Page* DOMWindow::page()
-{
- return frame() ? frame()->page() : 0;
-}
-
-void DOMWindow::frameDestroyed()
-{
- FrameDestructionObserver::frameDestroyed();
- reset();
-}
-
-void DOMWindow::willDetachPage()
-{
- InspectorInstrumentation::frameWindowDiscarded(m_frame, this);
- // FIXME: Once DeviceOrientationController is a ScriptExecutionContext
- // Supplement, this will no longer be needed.
- if (DeviceOrientationController* controller = DeviceOrientationController::from(page()))
- controller->removeAllDeviceEventListeners(this);
-}
-
-void DOMWindow::willDestroyDocumentInFrame()
-{
- // It is necessary to copy m_properties to a separate vector because the DOMWindowProperties may
- // unregister themselves from the DOMWindow as a result of the call to willDestroyGlobalObjectInFrame.
- Vector<DOMWindowProperty*> properties;
- copyToVector(m_properties, properties);
- for (size_t i = 0; i < properties.size(); ++i)
- properties[i]->willDestroyGlobalObjectInFrame();
-}
-
-void DOMWindow::willDetachDocumentFromFrame()
-{
- // It is necessary to copy m_properties to a separate vector because the DOMWindowProperties may
- // unregister themselves from the DOMWindow as a result of the call to willDetachGlobalObjectFromFrame.
- Vector<DOMWindowProperty*> properties;
- copyToVector(m_properties, properties);
- for (size_t i = 0; i < properties.size(); ++i)
- properties[i]->willDetachGlobalObjectFromFrame();
-}
-
-void DOMWindow::registerProperty(DOMWindowProperty* property)
-{
- m_properties.add(property);
-}
-
-void DOMWindow::unregisterProperty(DOMWindowProperty* property)
-{
- m_properties.remove(property);
-}
-
-void DOMWindow::reset()
-{
- willDestroyDocumentInFrame();
- resetDOMWindowProperties();
-}
-
-void DOMWindow::resetDOMWindowProperties()
-{
- m_properties.clear();
-
- m_screen = 0;
- m_history = 0;
- m_locationbar = 0;
- m_menubar = 0;
- m_personalbar = 0;
- m_scrollbars = 0;
- m_statusbar = 0;
- m_toolbar = 0;
- m_console = 0;
- m_navigator = 0;
- m_performance = 0;
- m_location = 0;
- m_media = 0;
- m_sessionStorage = 0;
- m_localStorage = 0;
- m_applicationCache = 0;
-}
-
-bool DOMWindow::isCurrentlyDisplayedInFrame() const
-{
- return m_frame && m_frame->domWindow() == this;
-}
-
-#if ENABLE(ORIENTATION_EVENTS)
-int DOMWindow::orientation() const
-{
- if (!m_frame)
- return 0;
-
- return m_frame->orientation();
-}
-#endif
-
-Screen* DOMWindow::screen() const
-{
- if (!isCurrentlyDisplayedInFrame())
- return 0;
- if (!m_screen)
- m_screen = Screen::create(m_frame);
- return m_screen.get();
-}
-
-History* DOMWindow::history() const
-{
- if (!isCurrentlyDisplayedInFrame())
- return 0;
- if (!m_history)
- m_history = History::create(m_frame);
- return m_history.get();
-}
-
-BarProp* DOMWindow::locationbar() const
-{
- if (!isCurrentlyDisplayedInFrame())
- return 0;
- if (!m_locationbar)
- m_locationbar = BarProp::create(m_frame, BarProp::Locationbar);
- return m_locationbar.get();
-}
-
-BarProp* DOMWindow::menubar() const
-{
- if (!isCurrentlyDisplayedInFrame())
- return 0;
- if (!m_menubar)
- m_menubar = BarProp::create(m_frame, BarProp::Menubar);
- return m_menubar.get();
-}
-
-BarProp* DOMWindow::personalbar() const
-{
- if (!isCurrentlyDisplayedInFrame())
- return 0;
- if (!m_personalbar)
- m_personalbar = BarProp::create(m_frame, BarProp::Personalbar);
- return m_personalbar.get();
-}
-
-BarProp* DOMWindow::scrollbars() const
-{
- if (!isCurrentlyDisplayedInFrame())
- return 0;
- if (!m_scrollbars)
- m_scrollbars = BarProp::create(m_frame, BarProp::Scrollbars);
- return m_scrollbars.get();
-}
-
-BarProp* DOMWindow::statusbar() const
-{
- if (!isCurrentlyDisplayedInFrame())
- return 0;
- if (!m_statusbar)
- m_statusbar = BarProp::create(m_frame, BarProp::Statusbar);
- return m_statusbar.get();
-}
-
-BarProp* DOMWindow::toolbar() const
-{
- if (!isCurrentlyDisplayedInFrame())
- return 0;
- if (!m_toolbar)
- m_toolbar = BarProp::create(m_frame, BarProp::Toolbar);
- return m_toolbar.get();
-}
-
-Console* DOMWindow::console() const
-{
- if (!isCurrentlyDisplayedInFrame())
- return 0;
- if (!m_console)
- m_console = Console::create(m_frame);
- return m_console.get();
-}
-
-PageConsole* DOMWindow::pageConsole() const
-{
- if (!isCurrentlyDisplayedInFrame())
- return 0;
- return m_frame->page() ? &m_frame->page()->console() : 0;
-}
-
-ApplicationCache* DOMWindow::applicationCache() const
-{
- if (!isCurrentlyDisplayedInFrame())
- return 0;
- if (!m_applicationCache)
- m_applicationCache = ApplicationCache::create(m_frame);
- return m_applicationCache.get();
-}
-
-Navigator* DOMWindow::navigator() const
-{
- if (!isCurrentlyDisplayedInFrame())
- return 0;
- if (!m_navigator)
- m_navigator = Navigator::create(m_frame);
- return m_navigator.get();
-}
-
-Performance* DOMWindow::performance() const
-{
- if (!isCurrentlyDisplayedInFrame())
- return 0;
- if (!m_performance)
- m_performance = Performance::create(m_frame);
- return m_performance.get();
-}
-
-Location* DOMWindow::location() const
-{
- if (!isCurrentlyDisplayedInFrame())
- return 0;
- if (!m_location)
- m_location = Location::create(m_frame);
- return m_location.get();
-}
-
-Storage* DOMWindow::sessionStorage(ExceptionState& es) const
-{
- if (!isCurrentlyDisplayedInFrame())
- return 0;
-
- Document* document = this->document();
- if (!document)
- return 0;
-
- String accessDeniedMessage = "Access to 'sessionStorage' is denied for this document.";
- if (!document->securityOrigin()->canAccessLocalStorage()) {
- if (document->isSandboxed(SandboxOrigin))
- es.throwSecurityError(accessDeniedMessage + " The document is sandboxed and lacks the 'allow-same-origin' flag.");
- else if (document->url().protocolIs("data"))
- es.throwSecurityError(accessDeniedMessage + " Storage is disabled inside 'data:' URLs.");
- else
- es.throwSecurityError(accessDeniedMessage);
- return 0;
- }
-
- if (m_sessionStorage) {
- if (!m_sessionStorage->area()->canAccessStorage(m_frame)) {
- es.throwSecurityError(accessDeniedMessage);
- return 0;
- }
- return m_sessionStorage.get();
- }
-
- Page* page = document->page();
- if (!page)
- return 0;
-
- OwnPtr<StorageArea> storageArea = page->sessionStorage()->storageArea(document->securityOrigin());
- if (!storageArea->canAccessStorage(m_frame)) {
- es.throwSecurityError(accessDeniedMessage);
- return 0;
- }
-
- m_sessionStorage = Storage::create(m_frame, storageArea.release());
- return m_sessionStorage.get();
-}
-
-Storage* DOMWindow::localStorage(ExceptionState& es) const
-{
- if (!isCurrentlyDisplayedInFrame())
- return 0;
-
- Document* document = this->document();
- if (!document)
- return 0;
-
- String accessDeniedMessage = "Access to 'localStorage' is denied for this document.";
- if (!document->securityOrigin()->canAccessLocalStorage()) {
- if (document->isSandboxed(SandboxOrigin))
- es.throwSecurityError(accessDeniedMessage + " The document is sandboxed and lacks the 'allow-same-origin' flag.");
- else if (document->url().protocolIs("data"))
- es.throwSecurityError(accessDeniedMessage + " Storage is disabled inside 'data:' URLs.");
- else
- es.throwSecurityError(accessDeniedMessage);
- return 0;
- }
-
- if (m_localStorage) {
- if (!m_localStorage->area()->canAccessStorage(m_frame)) {
- es.throwSecurityError(accessDeniedMessage);
- return 0;
- }
- return m_localStorage.get();
- }
-
- Page* page = document->page();
- if (!page)
- return 0;
-
- if (!page->settings().localStorageEnabled())
- return 0;
-
- OwnPtr<StorageArea> storageArea = StorageNamespace::localStorageArea(document->securityOrigin());
- if (!storageArea->canAccessStorage(m_frame)) {
- es.throwSecurityError(accessDeniedMessage);
- return 0;
- }
-
- m_localStorage = Storage::create(m_frame, storageArea.release());
- return m_localStorage.get();
-}
-
-void DOMWindow::postMessage(PassRefPtr<SerializedScriptValue> message, const MessagePortArray* ports, const String& targetOrigin, DOMWindow* source, ExceptionState& es)
-{
- if (!isCurrentlyDisplayedInFrame())
- return;
-
- Document* sourceDocument = source->document();
-
- // Compute the target origin. We need to do this synchronously in order
- // to generate the SyntaxError exception correctly.
- RefPtr<SecurityOrigin> target;
- if (targetOrigin == "/") {
- if (!sourceDocument)
- return;
- target = sourceDocument->securityOrigin();
- } else if (targetOrigin != "*") {
- target = SecurityOrigin::createFromString(targetOrigin);
- // It doesn't make sense target a postMessage at a unique origin
- // because there's no way to represent a unique origin in a string.
- if (target->isUnique()) {
- es.throwDOMException(SyntaxError, "Invalid target origin '" + targetOrigin + "' in a call to 'postMessage'.");
- return;
- }
- }
-
- OwnPtr<MessagePortChannelArray> channels = MessagePort::disentanglePorts(ports, es);
- if (es.hadException())
- return;
-
- // Capture the source of the message. We need to do this synchronously
- // in order to capture the source of the message correctly.
- if (!sourceDocument)
- return;
- String sourceOrigin = sourceDocument->securityOrigin()->toString();
-
- // Capture stack trace only when inspector front-end is loaded as it may be time consuming.
- RefPtr<ScriptCallStack> stackTrace;
- if (InspectorInstrumentation::consoleAgentEnabled(sourceDocument))
- stackTrace = createScriptCallStack(ScriptCallStack::maxCallStackSizeToCapture, true);
-
- // Schedule the message.
- PostMessageTimer* timer = new PostMessageTimer(this, message, sourceOrigin, source, channels.release(), target.get(), stackTrace.release());
- timer->startOneShot(0);
-}
-
-void DOMWindow::postMessageTimerFired(PassOwnPtr<PostMessageTimer> t)
-{
- OwnPtr<PostMessageTimer> timer(t);
-
- if (!document() || !isCurrentlyDisplayedInFrame())
- return;
-
- RefPtr<MessageEvent> event = timer->event(document());
-
- // Give the embedder a chance to intercept this postMessage because this
- // DOMWindow might be a proxy for another in browsers that support
- // postMessage calls across WebKit instances.
- if (m_frame->loader()->client()->willCheckAndDispatchMessageEvent(timer->targetOrigin(), event.get()))
- return;
-
- dispatchMessageEventWithOriginCheck(timer->targetOrigin(), event, timer->stackTrace());
-}
-
-void DOMWindow::dispatchMessageEventWithOriginCheck(SecurityOrigin* intendedTargetOrigin, PassRefPtr<Event> event, PassRefPtr<ScriptCallStack> stackTrace)
-{
- if (intendedTargetOrigin) {
- // Check target origin now since the target document may have changed since the timer was scheduled.
- if (!intendedTargetOrigin->isSameSchemeHostPort(document()->securityOrigin())) {
- String message = "Unable to post message to " + intendedTargetOrigin->toString() +
- ". Recipient has origin " + document()->securityOrigin()->toString() + ".\n";
- pageConsole()->addMessage(SecurityMessageSource, ErrorMessageLevel, message, stackTrace);
- return;
- }
- }
-
- dispatchEvent(event);
-}
-
-DOMSelection* DOMWindow::getSelection()
-{
- if (!isCurrentlyDisplayedInFrame() || !m_frame)
- return 0;
-
- return m_frame->document()->getSelection();
-}
-
-Element* DOMWindow::frameElement() const
-{
- if (!m_frame)
- return 0;
-
- return m_frame->ownerElement();
-}
-
-void DOMWindow::focus(ScriptExecutionContext* context)
-{
- if (!m_frame)
- return;
-
- Page* page = m_frame->page();
- if (!page)
- return;
-
- bool allowFocus = WindowFocusAllowedIndicator::windowFocusAllowed();
- if (context) {
- ASSERT(isMainThread());
- Document* activeDocument = toDocument(context);
- if (opener() && opener() != this && activeDocument->domWindow() == opener())
- allowFocus = true;
- }
-
- // If we're a top level window, bring the window to the front.
- if (m_frame == page->mainFrame() && allowFocus)
- page->chrome().focus();
-
- if (!m_frame)
- return;
-
- m_frame->eventHandler()->focusDocumentView();
-}
-
-void DOMWindow::blur()
-{
-}
-
-void DOMWindow::close(ScriptExecutionContext* context)
-{
- if (!m_frame)
- return;
-
- Page* page = m_frame->page();
- if (!page)
- return;
-
- if (m_frame != page->mainFrame())
- return;
-
- if (context) {
- ASSERT(isMainThread());
- Document* activeDocument = toDocument(context);
- if (!activeDocument)
- return;
-
- if (!activeDocument->canNavigate(m_frame))
- return;
- }
-
- Settings* settings = m_frame->settings();
- bool allowScriptsToCloseWindows = settings && settings->allowScriptsToCloseWindows();
-
- if (!(page->openedByDOM() || page->backForward().count() <= 1 || allowScriptsToCloseWindows))
- return;
-
- if (!m_frame->loader()->shouldClose())
- return;
-
- page->chrome().closeWindowSoon();
-}
-
-void DOMWindow::print()
-{
- if (!m_frame)
- return;
-
- Page* page = m_frame->page();
- if (!page)
- return;
-
- if (m_frame->loader()->activeDocumentLoader()->isLoading()) {
- m_shouldPrintWhenFinishedLoading = true;
- return;
- }
- m_shouldPrintWhenFinishedLoading = false;
- page->chrome().print(m_frame);
-}
-
-void DOMWindow::stop()
-{
- if (!m_frame)
- return;
- m_frame->loader()->stopAllLoaders();
-}
-
-void DOMWindow::alert(const String& message)
-{
- if (!m_frame)
- return;
-
- m_frame->document()->updateStyleIfNeeded();
-
- Page* page = m_frame->page();
- if (!page)
- return;
-
- page->chrome().runJavaScriptAlert(m_frame, message);
-}
-
-bool DOMWindow::confirm(const String& message)
-{
- if (!m_frame)
- return false;
-
- m_frame->document()->updateStyleIfNeeded();
-
- Page* page = m_frame->page();
- if (!page)
- return false;
-
- return page->chrome().runJavaScriptConfirm(m_frame, message);
-}
-
-String DOMWindow::prompt(const String& message, const String& defaultValue)
-{
- if (!m_frame)
- return String();
-
- m_frame->document()->updateStyleIfNeeded();
-
- Page* page = m_frame->page();
- if (!page)
- return String();
-
- String returnValue;
- if (page->chrome().runJavaScriptPrompt(m_frame, message, defaultValue, returnValue))
- return returnValue;
-
- return String();
-}
-
-bool DOMWindow::find(const String& string, bool caseSensitive, bool backwards, bool wrap, bool /*wholeWord*/, bool /*searchInFrames*/, bool /*showDialog*/) const
-{
- if (!isCurrentlyDisplayedInFrame())
- return false;
-
- // FIXME (13016): Support wholeWord, searchInFrames and showDialog
- return m_frame->editor().findString(string, !backwards, caseSensitive, wrap, false);
-}
-
-bool DOMWindow::offscreenBuffering() const
-{
- return true;
-}
-
-int DOMWindow::outerHeight() const
-{
- if (!m_frame)
- return 0;
-
- Page* page = m_frame->page();
- if (!page)
- return 0;
-
- return static_cast<int>(page->chrome().windowRect().height());
-}
-
-int DOMWindow::outerWidth() const
-{
- if (!m_frame)
- return 0;
-
- Page* page = m_frame->page();
- if (!page)
- return 0;
-
- return static_cast<int>(page->chrome().windowRect().width());
-}
-
-int DOMWindow::innerHeight() const
-{
- if (!m_frame)
- return 0;
-
- FrameView* view = m_frame->view();
- if (!view)
- return 0;
-
- // FIXME: This is potentially too much work. We really only need to know the dimensions of the parent frame's renderer.
- if (Frame* parent = m_frame->tree()->parent())
- parent->document()->updateLayoutIgnorePendingStylesheets();
-
- // If the device height is overridden, do not include the horizontal scrollbar into the innerHeight (since it is absent on the real device).
- bool includeScrollbars = !InspectorInstrumentation::shouldApplyScreenHeightOverride(m_frame);
- return view->mapFromLayoutToCSSUnits(static_cast<int>(view->visibleContentRect(includeScrollbars ? ScrollableArea::IncludeScrollbars : ScrollableArea::ExcludeScrollbars).height()));
-}
-
-int DOMWindow::innerWidth() const
-{
- if (!m_frame)
- return 0;
-
- FrameView* view = m_frame->view();
- if (!view)
- return 0;
-
- // FIXME: This is potentially too much work. We really only need to know the dimensions of the parent frame's renderer.
- if (Frame* parent = m_frame->tree()->parent())
- parent->document()->updateLayoutIgnorePendingStylesheets();
-
- // If the device width is overridden, do not include the vertical scrollbar into the innerWidth (since it is absent on the real device).
- bool includeScrollbars = !InspectorInstrumentation::shouldApplyScreenWidthOverride(m_frame);
- return view->mapFromLayoutToCSSUnits(static_cast<int>(view->visibleContentRect(includeScrollbars ? ScrollableArea::IncludeScrollbars : ScrollableArea::ExcludeScrollbars).width()));
-}
-
-int DOMWindow::screenX() const
-{
- if (!m_frame)
- return 0;
-
- Page* page = m_frame->page();
- if (!page)
- return 0;
-
- return static_cast<int>(page->chrome().windowRect().x());
-}
-
-int DOMWindow::screenY() const
-{
- if (!m_frame)
- return 0;
-
- Page* page = m_frame->page();
- if (!page)
- return 0;
-
- return static_cast<int>(page->chrome().windowRect().y());
-}
-
-int DOMWindow::scrollX() const
-{
- if (!m_frame)
- return 0;
-
- FrameView* view = m_frame->view();
- if (!view)
- return 0;
-
- m_frame->document()->updateLayoutIgnorePendingStylesheets();
-
- return view->mapFromLayoutToCSSUnits(view->scrollX());
-}
-
-int DOMWindow::scrollY() const
-{
- if (!m_frame)
- return 0;
-
- FrameView* view = m_frame->view();
- if (!view)
- return 0;
-
- m_frame->document()->updateLayoutIgnorePendingStylesheets();
-
- return view->mapFromLayoutToCSSUnits(view->scrollY());
-}
-
-bool DOMWindow::closed() const
-{
- return !m_frame;
-}
-
-unsigned DOMWindow::length() const
-{
- if (!isCurrentlyDisplayedInFrame())
- return 0;
-
- return m_frame->tree()->scopedChildCount();
-}
-
-String DOMWindow::name() const
-{
- if (!m_frame)
- return String();
-
- return m_frame->tree()->name();
-}
-
-void DOMWindow::setName(const String& string)
-{
- if (!m_frame)
- return;
-
- m_frame->tree()->setName(string);
- m_frame->loader()->client()->didChangeName(string);
-}
-
-void DOMWindow::setStatus(const String& string)
-{
- m_status = string;
-
- if (!m_frame)
- return;
-
- Page* page = m_frame->page();
- if (!page)
- return;
-
- ASSERT(m_frame->document()); // Client calls shouldn't be made when the frame is in inconsistent state.
- page->chrome().setStatusbarText(m_frame, m_status);
-}
-
-void DOMWindow::setDefaultStatus(const String& string)
-{
- m_defaultStatus = string;
-
- if (!m_frame)
- return;
-
- Page* page = m_frame->page();
- if (!page)
- return;
-
- ASSERT(m_frame->document()); // Client calls shouldn't be made when the frame is in inconsistent state.
- page->chrome().setStatusbarText(m_frame, m_defaultStatus);
-}
-
-DOMWindow* DOMWindow::self() const
-{
- if (!m_frame)
- return 0;
-
- return m_frame->domWindow();
-}
-
-DOMWindow* DOMWindow::opener() const
-{
- if (!m_frame)
- return 0;
-
- Frame* opener = m_frame->loader()->opener();
- if (!opener)
- return 0;
-
- return opener->domWindow();
-}
-
-DOMWindow* DOMWindow::parent() const
-{
- if (!m_frame)
- return 0;
-
- Frame* parent = m_frame->tree()->parent();
- if (parent)
- return parent->domWindow();
-
- return m_frame->domWindow();
-}
-
-DOMWindow* DOMWindow::top() const
-{
- if (!m_frame)
- return 0;
-
- Page* page = m_frame->page();
- if (!page)
- return 0;
-
- return m_frame->tree()->top()->domWindow();
-}
-
-Document* DOMWindow::document() const
-{
- return m_document.get();
-}
-
-PassRefPtr<StyleMedia> DOMWindow::styleMedia() const
-{
- if (!isCurrentlyDisplayedInFrame())
- return 0;
- if (!m_media)
- m_media = StyleMedia::create(m_frame);
- return m_media.get();
-}
-
-PassRefPtr<CSSStyleDeclaration> DOMWindow::getComputedStyle(Element* elt, const String& pseudoElt) const
-{
- if (!elt)
- return 0;
-
- return CSSComputedStyleDeclaration::create(elt, false, pseudoElt);
-}
-
-PassRefPtr<CSSRuleList> DOMWindow::getMatchedCSSRules(Element* element, const String& pseudoElement, bool authorOnly) const
-{
- if (!isCurrentlyDisplayedInFrame())
- return 0;
-
- unsigned colonStart = pseudoElement[0] == ':' ? (pseudoElement[1] == ':' ? 2 : 1) : 0;
- CSSSelector::PseudoType pseudoType = CSSSelector::parsePseudoType(AtomicString(pseudoElement.substring(colonStart)));
- if (pseudoType == CSSSelector::PseudoUnknown && !pseudoElement.isEmpty())
- return 0;
-
- unsigned rulesToInclude = StyleResolver::AuthorCSSRules;
- if (!authorOnly)
- rulesToInclude |= StyleResolver::UAAndUserCSSRules;
-
- PseudoId pseudoId = CSSSelector::pseudoId(pseudoType);
-
- return m_frame->document()->styleResolver()->pseudoStyleRulesForElement(element, pseudoId, rulesToInclude);
-}
-
-PassRefPtr<DOMPoint> DOMWindow::webkitConvertPointFromNodeToPage(Node* node, const DOMPoint* p) const
-{
- if (!node || !p)
- return 0;
-
- if (!document())
- return 0;
-
- document()->updateLayoutIgnorePendingStylesheets();
-
- FloatPoint pagePoint(p->x(), p->y());
- pagePoint = node->convertToPage(pagePoint);
- return DOMPoint::create(pagePoint.x(), pagePoint.y());
-}
-
-PassRefPtr<DOMPoint> DOMWindow::webkitConvertPointFromPageToNode(Node* node, const DOMPoint* p) const
-{
- if (!node || !p)
- return 0;
-
- if (!document())
- return 0;
-
- document()->updateLayoutIgnorePendingStylesheets();
-
- FloatPoint nodePoint(p->x(), p->y());
- nodePoint = node->convertFromPage(nodePoint);
- return DOMPoint::create(nodePoint.x(), nodePoint.y());
-}
-
-double DOMWindow::devicePixelRatio() const
-{
- if (!m_frame)
- return 0.0;
-
- return m_frame->devicePixelRatio();
-}
-
-void DOMWindow::scrollBy(int x, int y) const
-{
- if (!isCurrentlyDisplayedInFrame())
- return;
-
- document()->updateLayoutIgnorePendingStylesheets();
-
- FrameView* view = m_frame->view();
- if (!view)
- return;
-
- IntSize scaledOffset(view->mapFromCSSToLayoutUnits(x), view->mapFromCSSToLayoutUnits(y));
- view->scrollBy(scaledOffset);
-}
-
-void DOMWindow::scrollTo(int x, int y) const
-{
- if (!isCurrentlyDisplayedInFrame())
- return;
-
- document()->updateLayoutIgnorePendingStylesheets();
-
- RefPtr<FrameView> view = m_frame->view();
- if (!view)
- return;
-
- IntPoint layoutPos(view->mapFromCSSToLayoutUnits(x), view->mapFromCSSToLayoutUnits(y));
- view->setScrollPosition(layoutPos);
-}
-
-void DOMWindow::moveBy(float x, float y) const
-{
- if (!m_frame)
- return;
-
- Page* page = m_frame->page();
- if (!page)
- return;
-
- if (m_frame != page->mainFrame())
- return;
-
- FloatRect fr = page->chrome().windowRect();
- FloatRect update = fr;
- update.move(x, y);
- // Security check (the spec talks about UniversalBrowserWrite to disable this check...)
- page->chrome().setWindowRect(adjustWindowRect(page, update));
-}
-
-void DOMWindow::moveTo(float x, float y) const
-{
- if (!m_frame)
- return;
-
- Page* page = m_frame->page();
- if (!page)
- return;
-
- if (m_frame != page->mainFrame())
- return;
-
- FloatRect fr = page->chrome().windowRect();
- FloatRect sr = screenAvailableRect(page->mainFrame()->view());
- fr.setLocation(sr.location());
- FloatRect update = fr;
- update.move(x, y);
- // Security check (the spec talks about UniversalBrowserWrite to disable this check...)
- page->chrome().setWindowRect(adjustWindowRect(page, update));
-}
-
-void DOMWindow::resizeBy(float x, float y) const
-{
- if (!m_frame)
- return;
-
- Page* page = m_frame->page();
- if (!page)
- return;
-
- if (m_frame != page->mainFrame())
- return;
-
- FloatRect fr = page->chrome().windowRect();
- FloatSize dest = fr.size() + FloatSize(x, y);
- FloatRect update(fr.location(), dest);
- page->chrome().setWindowRect(adjustWindowRect(page, update));
-}
-
-void DOMWindow::resizeTo(float width, float height) const
-{
- if (!m_frame)
- return;
-
- Page* page = m_frame->page();
- if (!page)
- return;
-
- if (m_frame != page->mainFrame())
- return;
-
- FloatRect fr = page->chrome().windowRect();
- FloatSize dest = FloatSize(width, height);
- FloatRect update(fr.location(), dest);
- page->chrome().setWindowRect(adjustWindowRect(page, update));
-}
-
-int DOMWindow::requestAnimationFrame(PassRefPtr<RequestAnimationFrameCallback> callback)
-{
- callback->m_useLegacyTimeBase = false;
- if (Document* d = document())
- return d->requestAnimationFrame(callback);
- return 0;
-}
-
-int DOMWindow::webkitRequestAnimationFrame(PassRefPtr<RequestAnimationFrameCallback> callback)
-{
- callback->m_useLegacyTimeBase = true;
- if (Document* d = document())
- return d->requestAnimationFrame(callback);
- return 0;
-}
-
-void DOMWindow::cancelAnimationFrame(int id)
-{
- if (Document* d = document())
- d->cancelAnimationFrame(id);
-}
-
-DOMWindowCSS* DOMWindow::css()
-{
- if (!m_css)
- m_css = DOMWindowCSS::create();
- return m_css.get();
-}
-
-static void didAddStorageEventListener(DOMWindow* window)
-{
- // Creating these WebCore::Storage objects informs the system that we'd like to receive
- // notifications about storage events that might be triggered in other processes. Rather
- // than subscribe to these notifications explicitly, we subscribe to them implicitly to
- // simplify the work done by the system.
- window->localStorage(IGNORE_EXCEPTION);
- window->sessionStorage(IGNORE_EXCEPTION);
-}
-
-bool DOMWindow::addEventListener(const AtomicString& eventType, PassRefPtr<EventListener> listener, bool useCapture)
-{
- if (!EventTarget::addEventListener(eventType, listener, useCapture))
- return false;
-
- if (Document* document = this->document()) {
- document->addListenerTypeIfNeeded(eventType);
- if (eventNames().isTouchEventType(eventType))
- document->didAddTouchEventHandler(document);
- else if (eventType == eventNames().storageEvent)
- didAddStorageEventListener(this);
- }
-
- lifecycleNotifier()->notifyAddEventListener(this, eventType);
-
- if (eventType == eventNames().unloadEvent) {
- addUnloadEventListener(this);
- } else if (eventType == eventNames().beforeunloadEvent) {
- if (allowsBeforeUnloadListeners(this)) {
- // This is confusingly named. It doesn't actually add the listener. It just increments a count
- // so that we know we have listeners registered for the purposes of determining if we can
- // fast terminate the renderer process.
- addBeforeUnloadEventListener(this);
- } else {
- // Subframes return false from allowsBeforeUnloadListeners.
- UseCounter::count(this, UseCounter::SubFrameBeforeUnloadRegistered);
- }
- } else if (eventType == eventNames().deviceorientationEvent && RuntimeEnabledFeatures::deviceOrientationEnabled()) {
- if (DeviceOrientationController* controller = DeviceOrientationController::from(page()))
- controller->addDeviceEventListener(this);
- }
-
- return true;
-}
-
-bool DOMWindow::removeEventListener(const AtomicString& eventType, EventListener* listener, bool useCapture)
-{
- if (!EventTarget::removeEventListener(eventType, listener, useCapture))
- return false;
-
- if (Document* document = this->document()) {
- if (eventNames().isTouchEventType(eventType))
- document->didRemoveTouchEventHandler(document);
- }
-
- lifecycleNotifier()->notifyRemoveEventListener(this, eventType);
-
- if (eventType == eventNames().unloadEvent) {
- removeUnloadEventListener(this);
- } else if (eventType == eventNames().beforeunloadEvent && allowsBeforeUnloadListeners(this)) {
- removeBeforeUnloadEventListener(this);
- } else if (eventType == eventNames().deviceorientationEvent) {
- if (DeviceOrientationController* controller = DeviceOrientationController::from(page()))
- controller->removeDeviceEventListener(this);
- }
-
- return true;
-}
-
-void DOMWindow::dispatchLoadEvent()
-{
- RefPtr<Event> loadEvent(Event::create(eventNames().loadEvent));
- if (m_frame && m_frame->loader()->documentLoader() && !m_frame->loader()->documentLoader()->timing()->loadEventStart()) {
- // The DocumentLoader (and thus its DocumentLoadTiming) might get destroyed while dispatching
- // the event, so protect it to prevent writing the end time into freed memory.
- RefPtr<DocumentLoader> documentLoader = m_frame->loader()->documentLoader();
- DocumentLoadTiming* timing = documentLoader->timing();
- timing->markLoadEventStart();
- dispatchEvent(loadEvent, document());
- timing->markLoadEventEnd();
- } else
- dispatchEvent(loadEvent, document());
-
- // For load events, send a separate load event to the enclosing frame only.
- // This is a DOM extension and is independent of bubbling/capturing rules of
- // the DOM.
- Element* ownerElement = m_frame ? m_frame->ownerElement() : 0;
- if (ownerElement)
- ownerElement->dispatchEvent(Event::create(eventNames().loadEvent));
-
- InspectorInstrumentation::loadEventFired(frame());
-}
-
-bool DOMWindow::dispatchEvent(PassRefPtr<Event> prpEvent, PassRefPtr<EventTarget> prpTarget)
-{
- RefPtr<EventTarget> protect = this;
- RefPtr<Event> event = prpEvent;
-
- event->setTarget(prpTarget ? prpTarget : this);
- event->setCurrentTarget(this);
- event->setEventPhase(Event::AT_TARGET);
-
- InspectorInstrumentationCookie cookie = InspectorInstrumentation::willDispatchEventOnWindow(frame(), *event, this);
-
- bool result = fireEventListeners(event.get());
-
- InspectorInstrumentation::didDispatchEventOnWindow(cookie);
-
- return result;
-}
-
-void DOMWindow::removeAllEventListeners()
-{
- EventTarget::removeAllEventListeners();
-
- lifecycleNotifier()->notifyRemoveAllEventListeners(this);
-
- if (DeviceOrientationController* controller = DeviceOrientationController::from(page()))
- controller->removeAllDeviceEventListeners(this);
- if (Document* document = this->document())
- document->didRemoveEventTargetNode(document);
-
- removeAllUnloadEventListeners(this);
- removeAllBeforeUnloadEventListeners(this);
-}
-
-void DOMWindow::finishedLoading()
-{
- if (m_shouldPrintWhenFinishedLoading) {
- m_shouldPrintWhenFinishedLoading = false;
- print();
- }
-}
-
-EventTargetData* DOMWindow::eventTargetData()
-{
- return &m_eventTargetData;
-}
-
-EventTargetData* DOMWindow::ensureEventTargetData()
-{
- return &m_eventTargetData;
-}
-
-void DOMWindow::setLocation(const String& urlString, DOMWindow* activeWindow, DOMWindow* firstWindow, SetLocationLocking locking)
-{
- if (!isCurrentlyDisplayedInFrame())
- return;
-
- Document* activeDocument = activeWindow->document();
- if (!activeDocument)
- return;
-
- if (!activeDocument->canNavigate(m_frame))
- return;
-
- Frame* firstFrame = firstWindow->frame();
- if (!firstFrame)
- return;
-
- KURL completedURL = firstFrame->document()->completeURL(urlString);
- if (completedURL.isNull())
- return;
-
- if (isInsecureScriptAccess(activeWindow, completedURL))
- return;
-
- // We want a new history item if we are processing a user gesture.
- m_frame->navigationScheduler()->scheduleLocationChange(activeDocument->securityOrigin(),
- // FIXME: What if activeDocument()->frame() is 0?
- completedURL, activeDocument->frame()->loader()->outgoingReferrer(),
- locking != LockHistoryBasedOnGestureState);
-}
-
-void DOMWindow::printErrorMessage(const String& message)
-{
- if (message.isEmpty())
- return;
-
- pageConsole()->addMessage(JSMessageSource, ErrorMessageLevel, message);
-}
-
-// FIXME: Once we're throwing exceptions for cross-origin access violations, we will always sanitize the target
-// frame details, so we can safely combine 'crossDomainAccessErrorMessage' with this method after considering
-// exactly which details may be exposed to JavaScript.
-//
-// http://crbug.com/17325
-String DOMWindow::sanitizedCrossDomainAccessErrorMessage(DOMWindow* activeWindow)
-{
- const KURL& activeWindowURL = activeWindow->document()->url();
- if (activeWindowURL.isNull())
- return String();
-
- ASSERT(!activeWindow->document()->securityOrigin()->canAccess(document()->securityOrigin()));
-
- SecurityOrigin* activeOrigin = activeWindow->document()->securityOrigin();
- String message = "Blocked a frame with origin \"" + activeOrigin->toString() + "\" from accessing a cross-origin frame.";
-
- // FIXME: Evaluate which details from 'crossDomainAccessErrorMessage' may safely be reported to JavaScript.
-
- return message;
-}
-
-String DOMWindow::crossDomainAccessErrorMessage(DOMWindow* activeWindow)
-{
- const KURL& activeWindowURL = activeWindow->document()->url();
- if (activeWindowURL.isNull())
- return String();
-
- ASSERT(!activeWindow->document()->securityOrigin()->canAccess(document()->securityOrigin()));
-
- // FIXME: This message, and other console messages, have extra newlines. Should remove them.
- SecurityOrigin* activeOrigin = activeWindow->document()->securityOrigin();
- SecurityOrigin* targetOrigin = document()->securityOrigin();
- String message = "Blocked a frame with origin \"" + activeOrigin->toString() + "\" from accessing a frame with origin \"" + targetOrigin->toString() + "\". ";
-
- // Sandbox errors: Use the origin of the frames' location, rather than their actual origin (since we know that at least one will be "null").
- KURL activeURL = activeWindow->document()->url();
- KURL targetURL = document()->url();
- if (document()->isSandboxed(SandboxOrigin) || activeWindow->document()->isSandboxed(SandboxOrigin)) {
- message = "Blocked a frame at \"" + SecurityOrigin::create(activeURL)->toString() + "\" from accessing a frame at \"" + SecurityOrigin::create(targetURL)->toString() + "\". ";
- if (document()->isSandboxed(SandboxOrigin) && activeWindow->document()->isSandboxed(SandboxOrigin))
- return "Sandbox access violation: " + message + " Both frames are sandboxed and lack the \"allow-same-origin\" flag.";
- if (document()->isSandboxed(SandboxOrigin))
- return "Sandbox access violation: " + message + " The frame being accessed is sandboxed and lacks the \"allow-same-origin\" flag.";
- return "Sandbox access violation: " + message + " The frame requesting access is sandboxed and lacks the \"allow-same-origin\" flag.";
- }
-
- // Protocol errors: Use the URL's protocol rather than the origin's protocol so that we get a useful message for non-heirarchal URLs like 'data:'.
- if (targetOrigin->protocol() != activeOrigin->protocol())
- return message + " The frame requesting access has a protocol of \"" + activeURL.protocol() + "\", the frame being accessed has a protocol of \"" + targetURL.protocol() + "\". Protocols must match.\n";
-
- // 'document.domain' errors.
- if (targetOrigin->domainWasSetInDOM() && activeOrigin->domainWasSetInDOM())
- return message + "The frame requesting access set \"document.domain\" to \"" + activeOrigin->domain() + "\", the frame being accessed set it to \"" + targetOrigin->domain() + "\". Both must set \"document.domain\" to the same value to allow access.";
- if (activeOrigin->domainWasSetInDOM())
- return message + "The frame requesting access set \"document.domain\" to \"" + activeOrigin->domain() + "\", but the frame being accessed did not. Both must set \"document.domain\" to the same value to allow access.";
- if (targetOrigin->domainWasSetInDOM())
- return message + "The frame being accessed set \"document.domain\" to \"" + targetOrigin->domain() + "\", but the frame requesting access did not. Both must set \"document.domain\" to the same value to allow access.";
-
- // Default.
- return message + "Protocols, domains, and ports must match.";
-}
-
-bool DOMWindow::isInsecureScriptAccess(DOMWindow* activeWindow, const String& urlString)
-{
- if (!protocolIsJavaScript(urlString))
- return false;
-
- // If this DOMWindow isn't currently active in the Frame, then there's no
- // way we should allow the access.
- // FIXME: Remove this check if we're able to disconnect DOMWindow from
- // Frame on navigation: https://bugs.webkit.org/show_bug.cgi?id=62054
- if (isCurrentlyDisplayedInFrame()) {
- // FIXME: Is there some way to eliminate the need for a separate "activeWindow == this" check?
- if (activeWindow == this)
- return false;
-
- // FIXME: The name canAccess seems to be a roundabout way to ask "can execute script".
- // Can we name the SecurityOrigin function better to make this more clear?
- if (activeWindow->document()->securityOrigin()->canAccess(document()->securityOrigin()))
- return false;
- }
-
- printErrorMessage(crossDomainAccessErrorMessage(activeWindow));
- return true;
-}
-
-PassRefPtr<DOMWindow> DOMWindow::open(const String& urlString, const AtomicString& frameName, const String& windowFeaturesString,
- DOMWindow* activeWindow, DOMWindow* firstWindow)
-{
- if (!isCurrentlyDisplayedInFrame())
- return 0;
- Document* activeDocument = activeWindow->document();
- if (!activeDocument)
- return 0;
- Frame* firstFrame = firstWindow->frame();
- if (!firstFrame)
- return 0;
-
- if (!firstWindow->allowPopUp()) {
- // Because FrameTree::find() returns true for empty strings, we must check for empty frame names.
- // Otherwise, illegitimate window.open() calls with no name will pass right through the popup blocker.
- if (frameName.isEmpty() || !m_frame->tree()->find(frameName))
- return 0;
- }
-
- // Get the target frame for the special cases of _top and _parent.
- // In those cases, we schedule a location change right now and return early.
- Frame* targetFrame = 0;
- if (frameName == "_top")
- targetFrame = m_frame->tree()->top();
- else if (frameName == "_parent") {
- if (Frame* parent = m_frame->tree()->parent())
- targetFrame = parent;
- else
- targetFrame = m_frame;
- }
- if (targetFrame) {
- if (!activeDocument->canNavigate(targetFrame))
- return 0;
-
- KURL completedURL = firstFrame->document()->completeURL(urlString);
-
- if (targetFrame->domWindow()->isInsecureScriptAccess(activeWindow, completedURL))
- return targetFrame->domWindow();
-
- if (urlString.isEmpty())
- return targetFrame->domWindow();
-
- // For whatever reason, Firefox uses the first window rather than the active window to
- // determine the outgoing referrer. We replicate that behavior here.
- targetFrame->navigationScheduler()->scheduleLocationChange(
- activeDocument->securityOrigin(),
- completedURL,
- firstFrame->loader()->outgoingReferrer(),
- false);
- return targetFrame->domWindow();
- }
-
- WindowFeatures windowFeatures(windowFeaturesString);
- Frame* result = createWindow(urlString, frameName, windowFeatures, activeWindow, firstFrame, m_frame);
- return result ? result->domWindow() : 0;
-}
-
-void DOMWindow::showModalDialog(const String& urlString, const String& dialogFeaturesString,
- DOMWindow* activeWindow, DOMWindow* firstWindow, PrepareDialogFunction function, void* functionContext)
-{
- if (!isCurrentlyDisplayedInFrame())
- return;
- Frame* activeFrame = activeWindow->frame();
- if (!activeFrame)
- return;
- Frame* firstFrame = firstWindow->frame();
- if (!firstFrame)
- return;
-
- if (!canShowModalDialogNow(m_frame) || !firstWindow->allowPopUp())
- return;
-
- WindowFeatures windowFeatures(dialogFeaturesString, screenAvailableRect(m_frame->view()));
- Frame* dialogFrame = createWindow(urlString, emptyAtom, windowFeatures,
- activeWindow, firstFrame, m_frame, function, functionContext);
- if (!dialogFrame)
- return;
- UserGestureIndicatorDisabler disabler;
- dialogFrame->page()->chrome().runModal();
-}
-
-DOMWindow* DOMWindow::anonymousIndexedGetter(uint32_t index)
-{
- Frame* frame = this->frame();
- if (!frame)
- return 0;
-
- Frame* child = frame->tree()->scopedChild(index);
- if (child)
- return child->domWindow();
-
- return 0;
-}
-
-DOMWindowLifecycleNotifier* DOMWindow::lifecycleNotifier()
-{
- return static_cast<DOMWindowLifecycleNotifier*>(LifecycleContext::lifecycleNotifier());
-}
-
-PassOwnPtr<LifecycleNotifier> DOMWindow::createLifecycleNotifier()
-{
- return DOMWindowLifecycleNotifier::create(this);
-}
-
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/page/DOMWindow.h b/chromium/third_party/WebKit/Source/core/page/DOMWindow.h
deleted file mode 100644
index cdda703c712..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/DOMWindow.h
+++ /dev/null
@@ -1,448 +0,0 @@
-/*
- * Copyright (C) 2006, 2007, 2009, 2010 Apple Inc. All rights reserved.
- * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef DOMWindow_h
-#define DOMWindow_h
-
-#include "bindings/v8/ScriptWrappable.h"
-#include "core/dom/EventTarget.h"
-#include "core/page/FrameDestructionObserver.h"
-#include "core/platform/LifecycleContext.h"
-#include "core/platform/Supplementable.h"
-
-#include "wtf/Forward.h"
-
-namespace WebCore {
- class ApplicationCache;
- class BarProp;
- class CSSRuleList;
- class CSSStyleDeclaration;
- class Console;
- class DOMPoint;
- class DOMSelection;
- class DOMURL;
- class DOMWindowProperty;
- class Database;
- class DatabaseCallback;
- class Document;
- class DOMWindowLifecycleNotifier;
- class Element;
- class EventListener;
- class ExceptionState;
- class FloatRect;
- class Frame;
- class History;
- class IDBFactory;
- class Location;
- class MediaQueryList;
- class MessageEvent;
- class Navigator;
- class Node;
- class Page;
- class PageConsole;
- class Performance;
- class PostMessageTimer;
- class RequestAnimationFrameCallback;
- class ScheduledAction;
- class Screen;
- class ScriptCallStack;
- class SecurityOrigin;
- class SerializedScriptValue;
- class Storage;
- class StyleMedia;
- class DOMWindowCSS;
-
- struct WindowFeatures;
-
- typedef Vector<RefPtr<MessagePort>, 1> MessagePortArray;
-
- enum SetLocationLocking { LockHistoryBasedOnGestureState, LockHistoryAndBackForwardList };
-
- class DOMWindow : public RefCounted<DOMWindow>, public ScriptWrappable, public EventTarget, public FrameDestructionObserver, public Supplementable<DOMWindow>, public LifecycleContext {
- public:
- static PassRefPtr<DOMWindow> create(Frame* frame) { return adoptRef(new DOMWindow(frame)); }
- virtual ~DOMWindow();
-
- // In some rare cases, we'll re-used a DOMWindow for a new Document. For example,
- // when a script calls window.open("..."), the browser gives JavaScript a window
- // synchronously but kicks off the load in the window asynchronously. Web sites
- // expect that modifications that they make to the window object synchronously
- // won't be blown away when the network load commits. To make that happen, we
- // "securely transition" the existing DOMWindow to the Document that results from
- // the network load. See also SecurityContext::isSecureTransitionTo.
- void setDocument(PassRefPtr<Document>);
-
- virtual const AtomicString& interfaceName() const;
- virtual ScriptExecutionContext* scriptExecutionContext() const;
-
- virtual DOMWindow* toDOMWindow();
-
- void registerProperty(DOMWindowProperty*);
- void unregisterProperty(DOMWindowProperty*);
-
- void reset();
-
- PassRefPtr<MediaQueryList> matchMedia(const String&);
-
- unsigned pendingUnloadEventListeners() const;
-
- static FloatRect adjustWindowRect(Page*, const FloatRect& pendingChanges);
-
- bool allowPopUp(); // Call on first window, not target window.
- static bool allowPopUp(Frame* firstFrame);
- static bool canShowModalDialog(const Frame*);
- static bool canShowModalDialogNow(const Frame*);
-
- // DOM Level 0
-
- Screen* screen() const;
- History* history() const;
- BarProp* locationbar() const;
- BarProp* menubar() const;
- BarProp* personalbar() const;
- BarProp* scrollbars() const;
- BarProp* statusbar() const;
- BarProp* toolbar() const;
- Navigator* navigator() const;
- Navigator* clientInformation() const { return navigator(); }
-
- Location* location() const;
- void setLocation(const String& location, DOMWindow* activeWindow, DOMWindow* firstWindow,
- SetLocationLocking = LockHistoryBasedOnGestureState);
-
- DOMSelection* getSelection();
-
- Element* frameElement() const;
-
- void focus(ScriptExecutionContext* = 0);
- void blur();
- void close(ScriptExecutionContext* = 0);
- void print();
- void stop();
-
- PassRefPtr<DOMWindow> open(const String& urlString, const AtomicString& frameName, const String& windowFeaturesString,
- DOMWindow* activeWindow, DOMWindow* firstWindow);
-
- typedef void (*PrepareDialogFunction)(DOMWindow*, void* context);
- void showModalDialog(const String& urlString, const String& dialogFeaturesString,
- DOMWindow* activeWindow, DOMWindow* firstWindow, PrepareDialogFunction, void* functionContext);
-
- void alert(const String& message);
- bool confirm(const String& message);
- String prompt(const String& message, const String& defaultValue);
-
- bool find(const String&, bool caseSensitive, bool backwards, bool wrap, bool wholeWord, bool searchInFrames, bool showDialog) const;
-
- bool offscreenBuffering() const;
-
- int outerHeight() const;
- int outerWidth() const;
- int innerHeight() const;
- int innerWidth() const;
- int screenX() const;
- int screenY() const;
- int screenLeft() const { return screenX(); }
- int screenTop() const { return screenY(); }
- int scrollX() const;
- int scrollY() const;
- int pageXOffset() const { return scrollX(); }
- int pageYOffset() const { return scrollY(); }
-
- bool closed() const;
-
- unsigned length() const;
-
- String name() const;
- void setName(const String&);
-
- String status() const;
- void setStatus(const String&);
- String defaultStatus() const;
- void setDefaultStatus(const String&);
-
- // This attribute is an alias of defaultStatus and is necessary for legacy uses.
- String defaultstatus() const { return defaultStatus(); }
- void setDefaultstatus(const String& status) { setDefaultStatus(status); }
-
- // Self-referential attributes
-
- DOMWindow* self() const;
- DOMWindow* window() const { return self(); }
- DOMWindow* frames() const { return self(); }
-
- DOMWindow* opener() const;
- DOMWindow* parent() const;
- DOMWindow* top() const;
-
- // DOM Level 2 AbstractView Interface
-
- Document* document() const;
-
- // CSSOM View Module
-
- PassRefPtr<StyleMedia> styleMedia() const;
-
- // DOM Level 2 Style Interface
-
- PassRefPtr<CSSStyleDeclaration> getComputedStyle(Element*, const String& pseudoElt) const;
-
- // WebKit extensions
-
- PassRefPtr<CSSRuleList> getMatchedCSSRules(Element*, const String& pseudoElt, bool authorOnly = true) const;
- double devicePixelRatio() const;
-
- PassRefPtr<DOMPoint> webkitConvertPointFromPageToNode(Node*, const DOMPoint*) const;
- PassRefPtr<DOMPoint> webkitConvertPointFromNodeToPage(Node*, const DOMPoint*) const;
-
- Console* console() const;
- PageConsole* pageConsole() const;
-
- void printErrorMessage(const String&);
- String crossDomainAccessErrorMessage(DOMWindow* activeWindow);
- String sanitizedCrossDomainAccessErrorMessage(DOMWindow* activeWindow);
-
- void postMessage(PassRefPtr<SerializedScriptValue> message, const MessagePortArray*, const String& targetOrigin, DOMWindow* source, ExceptionState&);
- void postMessageTimerFired(PassOwnPtr<PostMessageTimer>);
- void dispatchMessageEventWithOriginCheck(SecurityOrigin* intendedTargetOrigin, PassRefPtr<Event>, PassRefPtr<ScriptCallStack>);
-
- void scrollBy(int x, int y) const;
- void scrollTo(int x, int y) const;
- void scroll(int x, int y) const { scrollTo(x, y); }
-
- void moveBy(float x, float y) const;
- void moveTo(float x, float y) const;
-
- void resizeBy(float x, float y) const;
- void resizeTo(float width, float height) const;
-
- // WebKit animation extensions
- int requestAnimationFrame(PassRefPtr<RequestAnimationFrameCallback>);
- int webkitRequestAnimationFrame(PassRefPtr<RequestAnimationFrameCallback>);
- void cancelAnimationFrame(int id);
-
- DOMWindowCSS* css();
-
- // Events
- // EventTarget API
- virtual bool addEventListener(const AtomicString& eventType, PassRefPtr<EventListener>, bool useCapture);
- virtual bool removeEventListener(const AtomicString& eventType, EventListener*, bool useCapture);
- virtual void removeAllEventListeners();
-
- using EventTarget::dispatchEvent;
- bool dispatchEvent(PassRefPtr<Event> prpEvent, PassRefPtr<EventTarget> prpTarget);
-
- void dispatchLoadEvent();
-
- DEFINE_ATTRIBUTE_EVENT_LISTENER(abort);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(animationend);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(animationiteration);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(animationstart);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(beforeunload);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(blur);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(canplay);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(canplaythrough);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(change);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(click);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(contextmenu);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(dblclick);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(drag);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(dragend);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(dragenter);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(dragleave);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(dragover);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(dragstart);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(drop);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(durationchange);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(emptied);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(ended);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(error);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(focus);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(hashchange);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(input);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(invalid);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(keydown);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(keypress);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(keyup);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(load);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(loadeddata);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(loadedmetadata);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(loadstart);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(message);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(mousedown);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(mouseenter);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(mouseleave);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(mousemove);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(mouseout);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(mouseover);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(mouseup);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(mousewheel);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(offline);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(online);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(pagehide);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(pageshow);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(pause);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(play);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(playing);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(popstate);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(progress);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(ratechange);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(reset);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(resize);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(scroll);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(search);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(seeked);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(seeking);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(select);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(stalled);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(storage);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(submit);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(suspend);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(timeupdate);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(transitionend);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(unload);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(volumechange);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(waiting);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(wheel);
-
- DEFINE_MAPPED_ATTRIBUTE_EVENT_LISTENER(webkitanimationstart, webkitAnimationStart);
- DEFINE_MAPPED_ATTRIBUTE_EVENT_LISTENER(webkitanimationiteration, webkitAnimationIteration);
- DEFINE_MAPPED_ATTRIBUTE_EVENT_LISTENER(webkitanimationend, webkitAnimationEnd);
- DEFINE_MAPPED_ATTRIBUTE_EVENT_LISTENER(webkittransitionend, webkitTransitionEnd);
-
- void captureEvents() { }
- void releaseEvents() { }
-
- void finishedLoading();
-
- using RefCounted<DOMWindow>::ref;
- using RefCounted<DOMWindow>::deref;
-
- DEFINE_ATTRIBUTE_EVENT_LISTENER(devicemotion);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(deviceorientation);
-
- // HTML 5 key/value storage
- Storage* sessionStorage(ExceptionState&) const;
- Storage* localStorage(ExceptionState&) const;
- Storage* optionalSessionStorage() const { return m_sessionStorage.get(); }
- Storage* optionalLocalStorage() const { return m_localStorage.get(); }
-
- ApplicationCache* applicationCache() const;
- ApplicationCache* optionalApplicationCache() const { return m_applicationCache.get(); }
-
-#if ENABLE(ORIENTATION_EVENTS)
- // This is the interface orientation in degrees. Some examples are:
- // 0 is straight up; -90 is when the device is rotated 90 clockwise;
- // 90 is when rotated counter clockwise.
- int orientation() const;
-
- DEFINE_ATTRIBUTE_EVENT_LISTENER(orientationchange);
-#endif
-
- DEFINE_ATTRIBUTE_EVENT_LISTENER(touchstart);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(touchmove);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(touchend);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(touchcancel);
-
- Performance* performance() const;
-
- // FIXME: When this DOMWindow is no longer the active DOMWindow (i.e.,
- // when its document is no longer the document that is displayed in its
- // frame), we would like to zero out m_frame to avoid being confused
- // by the document that is currently active in m_frame.
- bool isCurrentlyDisplayedInFrame() const;
-
- void willDetachDocumentFromFrame();
- DOMWindow* anonymousIndexedGetter(uint32_t);
-
- bool isInsecureScriptAccess(DOMWindow* activeWindow, const String& urlString);
-
- protected:
- DOMWindowLifecycleNotifier* lifecycleNotifier();
-
- private:
- explicit DOMWindow(Frame*);
-
- Page* page();
-
- virtual PassOwnPtr<LifecycleNotifier> createLifecycleNotifier() OVERRIDE;
-
- virtual void frameDestroyed() OVERRIDE;
- virtual void willDetachPage() OVERRIDE;
-
- virtual void refEventTarget() { ref(); }
- virtual void derefEventTarget() { deref(); }
- virtual EventTargetData* eventTargetData();
- virtual EventTargetData* ensureEventTargetData();
-
- void resetDOMWindowProperties();
- void willDestroyDocumentInFrame();
-
- RefPtr<Document> m_document;
-
- bool m_shouldPrintWhenFinishedLoading;
-
- HashSet<DOMWindowProperty*> m_properties;
-
- mutable RefPtr<Screen> m_screen;
- mutable RefPtr<History> m_history;
- mutable RefPtr<BarProp> m_locationbar;
- mutable RefPtr<BarProp> m_menubar;
- mutable RefPtr<BarProp> m_personalbar;
- mutable RefPtr<BarProp> m_scrollbars;
- mutable RefPtr<BarProp> m_statusbar;
- mutable RefPtr<BarProp> m_toolbar;
- mutable RefPtr<Console> m_console;
- mutable RefPtr<Navigator> m_navigator;
- mutable RefPtr<Location> m_location;
- mutable RefPtr<StyleMedia> m_media;
-
- EventTargetData m_eventTargetData;
-
- String m_status;
- String m_defaultStatus;
-
- mutable RefPtr<Storage> m_sessionStorage;
- mutable RefPtr<Storage> m_localStorage;
- mutable RefPtr<ApplicationCache> m_applicationCache;
-
- mutable RefPtr<Performance> m_performance;
-
- mutable RefPtr<DOMWindowCSS> m_css;
- };
-
- inline String DOMWindow::status() const
- {
- return m_status;
- }
-
- inline String DOMWindow::defaultStatus() const
- {
- return m_defaultStatus;
- }
-
-} // namespace WebCore
-
-#endif // DOMWindow_h
diff --git a/chromium/third_party/WebKit/Source/core/page/DOMWindowBase64.cpp b/chromium/third_party/WebKit/Source/core/page/DOMWindowBase64.cpp
deleted file mode 100644
index 6411d142135..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/DOMWindowBase64.cpp
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * Copyright (C) 2006, 2007, 2008, 2010 Apple Inc. All rights reserved.
- * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
- * Copyright (C) 2013 Samsung Electronics. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/page/DOMWindowBase64.h"
-
-#include "bindings/v8/ExceptionState.h"
-#include "core/dom/ExceptionCode.h"
-#include "wtf/text/Base64.h"
-
-namespace WebCore {
-
-namespace DOMWindowBase64 {
-
-String btoa(void*, const String& stringToEncode, ExceptionState& es)
-{
- if (stringToEncode.isNull())
- return String();
-
- if (!stringToEncode.containsOnlyLatin1()) {
- es.throwDOMException(InvalidCharacterError, "'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");
- return String();
- }
-
- return base64Encode(stringToEncode.latin1());
-}
-
-String atob(void*, const String& encodedString, ExceptionState& es)
-{
- if (encodedString.isNull())
- return String();
-
- if (!encodedString.containsOnlyLatin1()) {
- es.throwDOMException(InvalidCharacterError, "'atob' failed: The string to be decoded contains characters outside of the Latin1 range.");
- return String();
- }
-
- Vector<char> out;
- if (!base64Decode(encodedString, out, Base64FailOnInvalidCharacterOrExcessPadding)) {
- es.throwDOMException(InvalidCharacterError, "'atob' failed: The string to be decoded is not correctly encoded.");
- return String();
- }
-
- return String(out.data(), out.size());
-}
-
-} // namespace DOMWindowBase64
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/page/DOMWindowLifecycleNotifier.cpp b/chromium/third_party/WebKit/Source/core/page/DOMWindowLifecycleNotifier.cpp
deleted file mode 100644
index 189b18a62fe..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/DOMWindowLifecycleNotifier.cpp
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-
-#include "config.h"
-#include "core/page/DOMWindowLifecycleNotifier.h"
-
-namespace WebCore {
-
-DOMWindowLifecycleNotifier::DOMWindowLifecycleNotifier(LifecycleContext* context)
- : LifecycleNotifier(context)
-{
-}
-
-void DOMWindowLifecycleNotifier::addObserver(LifecycleObserver* observer)
-{
- if (observer->observerType() == LifecycleObserver::DOMWindowLifecycleObserverType) {
- RELEASE_ASSERT(m_iterating != IteratingOverDOMWindowObservers);
- m_windowObservers.add(static_cast<DOMWindowLifecycleObserver*>(observer));
- }
-
- LifecycleNotifier::addObserver(observer);
-}
-
-void DOMWindowLifecycleNotifier::removeObserver(LifecycleObserver* observer)
-{
- if (observer->observerType() == LifecycleObserver::DOMWindowLifecycleObserverType) {
- RELEASE_ASSERT(m_iterating != IteratingOverDOMWindowObservers);
- m_windowObservers.remove(static_cast<DOMWindowLifecycleObserver*>(observer));
- }
-
- LifecycleNotifier::removeObserver(observer);
-}
-
-PassOwnPtr<DOMWindowLifecycleNotifier> DOMWindowLifecycleNotifier::create(LifecycleContext* context)
-{
- return adoptPtr(new DOMWindowLifecycleNotifier(context));
-}
-
-void DOMWindowLifecycleNotifier::notifyAddEventListener(DOMWindow* window, const AtomicString& eventType)
-{
- TemporaryChange<IterationType> scope(this->m_iterating, IteratingOverDOMWindowObservers);
- for (DOMWindowObserverSet::iterator it = m_windowObservers.begin(); it != m_windowObservers.end(); ++it)
- (*it)->didAddEventListener(window, eventType);
-}
-
-void DOMWindowLifecycleNotifier::notifyRemoveEventListener(DOMWindow* window, const AtomicString& eventType)
-{
- TemporaryChange<IterationType> scope(this->m_iterating, IteratingOverDOMWindowObservers);
- for (DOMWindowObserverSet::iterator it = m_windowObservers.begin(); it != m_windowObservers.end(); ++it)
- (*it)->didRemoveEventListener(window, eventType);
-}
-
-void DOMWindowLifecycleNotifier::notifyRemoveAllEventListeners(DOMWindow* window)
-{
- TemporaryChange<IterationType> scope(this->m_iterating, IteratingOverDOMWindowObservers);
- for (DOMWindowObserverSet::iterator it = m_windowObservers.begin(); it != m_windowObservers.end(); ++it)
- (*it)->didRemoveAllEventListeners(window);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/page/DOMWindowLifecycleNotifier.h b/chromium/third_party/WebKit/Source/core/page/DOMWindowLifecycleNotifier.h
deleted file mode 100644
index e56f9ac7eab..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/DOMWindowLifecycleNotifier.h
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef DOMWindowLifecycleNotifier_h
-#define DOMWindowLifecycleNotifier_h
-
-#include "core/page/DOMWindowLifecycleObserver.h"
-#include "core/platform/LifecycleNotifier.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/TemporaryChange.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class DOMWindow;
-
-class DOMWindowLifecycleNotifier : public LifecycleNotifier {
-public:
- static PassOwnPtr<DOMWindowLifecycleNotifier> create(LifecycleContext*);
-
- void notifyAddEventListener(DOMWindow*, const AtomicString& eventType);
- void notifyRemoveEventListener(DOMWindow*, const AtomicString& eventType);
- void notifyRemoveAllEventListeners(DOMWindow*);
-
- virtual void addObserver(LifecycleObserver*) OVERRIDE;
- virtual void removeObserver(LifecycleObserver*) OVERRIDE;
-
-private:
- explicit DOMWindowLifecycleNotifier(LifecycleContext*);
-
- typedef HashSet<DOMWindowLifecycleObserver*> DOMWindowObserverSet;
- DOMWindowObserverSet m_windowObservers;
-};
-
-} // namespace WebCore
-
-#endif // DOMWindowLifecycleNotifier_h
diff --git a/chromium/third_party/WebKit/Source/core/page/DOMWindowLifecycleObserver.cpp b/chromium/third_party/WebKit/Source/core/page/DOMWindowLifecycleObserver.cpp
deleted file mode 100644
index 5c88b45e412..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/DOMWindowLifecycleObserver.cpp
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-
-#include "config.h"
-#include "core/page/DOMWindowLifecycleObserver.h"
-
-#include "core/page/DOMWindow.h"
-
-namespace WebCore {
-
-DOMWindowLifecycleObserver::DOMWindowLifecycleObserver(DOMWindow* window)
- : LifecycleObserver(window, DOMWindowLifecycleObserverType)
-{
-}
-
-DOMWindowLifecycleObserver::~DOMWindowLifecycleObserver()
-{
-}
-
-DOMWindow* DOMWindowLifecycleObserver::window() const
-{
- return static_cast<DOMWindow*>(lifecycleContext());
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/page/DOMWindowLifecycleObserver.h b/chromium/third_party/WebKit/Source/core/page/DOMWindowLifecycleObserver.h
deleted file mode 100644
index 46b17d5783c..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/DOMWindowLifecycleObserver.h
+++ /dev/null
@@ -1,51 +0,0 @@
-
-/*
- * Copyright (C) 2013 Google Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef DOMWindowLifecycleObserver_h
-#define DOMWindowLifecycleObserver_h
-
-#include "core/platform/LifecycleObserver.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class DOMWindow;
-
-class DOMWindowLifecycleObserver : public LifecycleObserver {
-public:
- explicit DOMWindowLifecycleObserver(DOMWindow*);
- virtual ~DOMWindowLifecycleObserver();
-
- DOMWindow* window() const;
-
- virtual void didAddEventListener(DOMWindow*, const AtomicString&) { }
- virtual void didRemoveEventListener(DOMWindow*, const AtomicString&) { }
- virtual void didRemoveAllEventListeners(DOMWindow*) { }
-};
-
-} // namespace WebCore
-
-#endif // DOMWindowLifecycleObserver_h
diff --git a/chromium/third_party/WebKit/Source/core/page/DOMWindowPagePopup.cpp b/chromium/third_party/WebKit/Source/core/page/DOMWindowPagePopup.cpp
index a5c803c0d28..348c5895ea6 100644
--- a/chromium/third_party/WebKit/Source/core/page/DOMWindowPagePopup.cpp
+++ b/chromium/third_party/WebKit/Source/core/page/DOMWindowPagePopup.cpp
@@ -31,7 +31,7 @@
#include "config.h"
#include "core/page/DOMWindowPagePopup.h"
-#include "core/page/DOMWindow.h"
+#include "core/frame/DOMWindow.h"
#include "core/page/PagePopupController.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/page/DOMWindowPagePopup.h b/chromium/third_party/WebKit/Source/core/page/DOMWindowPagePopup.h
index d39555e83fe..aa401a47100 100644
--- a/chromium/third_party/WebKit/Source/core/page/DOMWindowPagePopup.h
+++ b/chromium/third_party/WebKit/Source/core/page/DOMWindowPagePopup.h
@@ -31,7 +31,7 @@
#ifndef DOMWindowPagePopup_h
#define DOMWindowPagePopup_h
-#include "core/platform/Supplementable.h"
+#include "platform/Supplementable.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/page/DOMWindowProperty.cpp b/chromium/third_party/WebKit/Source/core/page/DOMWindowProperty.cpp
deleted file mode 100644
index 14df8aceace..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/DOMWindowProperty.cpp
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * Copyright (C) 2011 Google, Inc. All Rights Reserved.
- * Copyright (C) 2012 Apple Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY GOOGLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/page/DOMWindowProperty.h"
-
-#include "core/dom/Document.h"
-#include "core/page/DOMWindow.h"
-#include "core/page/Frame.h"
-
-namespace WebCore {
-
-DOMWindowProperty::DOMWindowProperty(Frame* frame)
- : m_frame(frame)
- , m_associatedDOMWindow(0)
-{
- // FIXME: For now it *is* acceptable for a DOMWindowProperty to be created with a null frame.
- // See fast/dom/navigator-detached-no-crash.html for the recipe.
- // We should fix that. <rdar://problem/11567132>
- if (m_frame) {
- m_associatedDOMWindow = m_frame->domWindow();
- m_associatedDOMWindow->registerProperty(this);
- }
-}
-
-DOMWindowProperty::~DOMWindowProperty()
-{
- if (m_associatedDOMWindow)
- m_associatedDOMWindow->unregisterProperty(this);
-
- m_associatedDOMWindow = 0;
- m_frame = 0;
-}
-
-void DOMWindowProperty::willDestroyGlobalObjectInFrame()
-{
- // If the property is getting this callback it must have been created with a Frame/DOMWindow and it should still have them.
- ASSERT(m_frame);
- ASSERT(m_associatedDOMWindow);
-
- // DOMWindowProperty lifetime isn't tied directly to the DOMWindow itself so it is important that it unregister
- // itself from any DOMWindow it is associated with if that DOMWindow is going away.
- if (m_associatedDOMWindow)
- m_associatedDOMWindow->unregisterProperty(this);
- m_associatedDOMWindow = 0;
- m_frame = 0;
-}
-
-void DOMWindowProperty::willDetachGlobalObjectFromFrame()
-{
- // If the property is getting this callback it must have been created with a Frame/DOMWindow and it should still have them.
- ASSERT(m_frame);
- ASSERT(m_associatedDOMWindow);
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/page/DOMWindowTimers.cpp b/chromium/third_party/WebKit/Source/core/page/DOMWindowTimers.cpp
deleted file mode 100644
index 499a7981588..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/DOMWindowTimers.cpp
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Copyright (C) 2006, 2007, 2008, 2010 Apple Inc. All rights reserved.
- * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
- * Copyright (C) 2013 Samsung Electronics. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/page/DOMWindowTimers.h"
-
-#include "core/dom/EventTarget.h"
-#include "core/page/DOMTimer.h"
-
-namespace WebCore {
-
-namespace DOMWindowTimers {
-
-int setTimeout(EventTarget* eventTarget, PassOwnPtr<ScheduledAction> action, int timeout)
-{
- return DOMTimer::install(eventTarget->scriptExecutionContext(), action, timeout, true);
-}
-
-int setInterval(EventTarget* eventTarget, PassOwnPtr<ScheduledAction> action, int timeout)
-{
- return DOMTimer::install(eventTarget->scriptExecutionContext(), action, timeout, false);
-}
-
-void clearTimeout(EventTarget* eventTarget, int timeoutID)
-{
- if (ScriptExecutionContext* context = eventTarget->scriptExecutionContext())
- DOMTimer::removeByID(context, timeoutID);
-}
-
-void clearInterval(EventTarget* eventTarget, int timeoutID)
-{
- if (ScriptExecutionContext* context = eventTarget->scriptExecutionContext())
- DOMTimer::removeByID(context, timeoutID);
-}
-
-} // namespace DOMWindowTimers
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/page/DeviceClient.h b/chromium/third_party/WebKit/Source/core/page/DeviceClient.h
deleted file mode 100644
index d5160b7177f..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/DeviceClient.h
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright 2010, The Android Open Source Project
- * Copyright (C) 2012 Samsung Electronics. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef DeviceClient_h
-#define DeviceClient_h
-
-namespace WebCore {
-
-class DeviceClient {
-public:
- virtual ~DeviceClient() { }
-
- virtual void startUpdating() = 0;
- virtual void stopUpdating() = 0;
-};
-
-} // namespace WebCore
-
-#endif // DeviceClient_h
diff --git a/chromium/third_party/WebKit/Source/core/page/DeviceController.cpp b/chromium/third_party/WebKit/Source/core/page/DeviceController.cpp
deleted file mode 100644
index 4376fd3d7eb..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/DeviceController.cpp
+++ /dev/null
@@ -1,114 +0,0 @@
-/*
- * Copyright 2010, The Android Open Source Project
- * Copyright (C) 2012 Samsung Electronics. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/page/DeviceController.h"
-
-#include "core/dom/Document.h"
-#include "core/page/DeviceClient.h"
-
-namespace WebCore {
-
-// FIXME: Another alternative is to update copyToVector in HashCountedSet to allow the source
-// and destination types to differ it the source type is convertible to the destination type.
-Vector<RefPtr<DOMWindow> > copyKeysToReferencingVector(const HashCountedSet<DOMWindow*>& set)
-{
- Vector<RefPtr<DOMWindow> > vector;
- vector.reserveCapacity(set.size());
-
- HashCountedSet<DOMWindow*>::const_iterator end= set.end();
- for (HashCountedSet<DOMWindow*>::const_iterator it = set.begin(); it != end; ++it)
- vector.append((*it).key);
- return vector;
-}
-
-DeviceController::DeviceController(DeviceClient* client)
- : m_client(client)
- , m_timer(this, &DeviceController::fireDeviceEvent)
-{
- ASSERT(m_client);
-}
-
-void DeviceController::addDeviceEventListener(DOMWindow* window)
-{
- bool wasEmpty = m_listeners.isEmpty();
- m_listeners.add(window);
-
- if (hasLastData()) {
- m_lastEventListeners.add(window);
- if (!m_timer.isActive())
- m_timer.startOneShot(0);
- }
-
- if (wasEmpty)
- m_client->startUpdating();
-}
-
-void DeviceController::removeDeviceEventListener(DOMWindow* window)
-{
- m_listeners.remove(window);
- m_lastEventListeners.remove(window);
- if (m_listeners.isEmpty())
- m_client->stopUpdating();
-}
-
-void DeviceController::removeAllDeviceEventListeners(DOMWindow* window)
-{
- m_listeners.removeAll(window);
- m_lastEventListeners.removeAll(window);
- if (m_listeners.isEmpty())
- m_client->stopUpdating();
-}
-
-void DeviceController::dispatchDeviceEvent(PassRefPtr<Event> prpEvent)
-{
- RefPtr<Event> event = prpEvent;
- Vector<RefPtr<DOMWindow> > listenerVector = copyKeysToReferencingVector(m_listeners);
- for (size_t i = 0; i < listenerVector.size(); ++i) {
- if (listenerVector[i]->document()
- && !listenerVector[i]->document()->activeDOMObjectsAreSuspended()
- && !listenerVector[i]->document()->activeDOMObjectsAreStopped())
- listenerVector[i]->dispatchEvent(event);
- }
-}
-
-void DeviceController::fireDeviceEvent(Timer<DeviceController>* timer)
-{
- ASSERT_UNUSED(timer, timer == &m_timer);
- ASSERT(hasLastData());
-
- m_timer.stop();
- Vector<RefPtr<DOMWindow> > listenerVector = copyKeysToReferencingVector(m_lastEventListeners);
- m_lastEventListeners.clear();
- for (size_t i = 0; i < listenerVector.size(); ++i) {
- if (listenerVector[i]->document()
- && !listenerVector[i]->document()->activeDOMObjectsAreSuspended()
- && !listenerVector[i]->document()->activeDOMObjectsAreStopped())
- listenerVector[i]->dispatchEvent(getLastEvent());
- }
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/page/DeviceController.h b/chromium/third_party/WebKit/Source/core/page/DeviceController.h
deleted file mode 100644
index b9fcbc1bbb2..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/DeviceController.h
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Copyright 2010, The Android Open Source Project
- * Copyright (C) 2012 Samsung Electronics. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef DeviceController_h
-#define DeviceController_h
-
-#include "core/dom/Event.h"
-#include "core/page/DOMWindow.h"
-#include "core/platform/Supplementable.h"
-#include "core/platform/Timer.h"
-#include "wtf/HashCountedSet.h"
-
-namespace WebCore {
-
-class DeviceClient;
-class Page;
-
-class DeviceController : public Supplement<Page> {
-public:
- explicit DeviceController(DeviceClient*);
- ~DeviceController() { }
-
- void addDeviceEventListener(DOMWindow*);
- void removeDeviceEventListener(DOMWindow*);
- void removeAllDeviceEventListeners(DOMWindow*);
-
- void dispatchDeviceEvent(PassRefPtr<Event>);
- bool isActive() { return !m_listeners.isEmpty(); }
- DeviceClient* client() { return m_client; }
-
- virtual bool hasLastData() { return false; }
- virtual PassRefPtr<Event> getLastEvent() { return 0; }
-
-protected:
- void fireDeviceEvent(Timer<DeviceController>*);
-
- HashCountedSet<DOMWindow*> m_listeners;
- HashCountedSet<DOMWindow*> m_lastEventListeners;
- DeviceClient* m_client;
- Timer<DeviceController> m_timer;
-};
-
-} // namespace WebCore
-
-#endif // DeviceController_h
diff --git a/chromium/third_party/WebKit/Source/core/page/DiagnosticLoggingKeys.cpp b/chromium/third_party/WebKit/Source/core/page/DiagnosticLoggingKeys.cpp
deleted file mode 100644
index 690ddc64597..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/DiagnosticLoggingKeys.cpp
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- * Copyright (C) 2012 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/page/DiagnosticLoggingKeys.h"
-
-namespace WebCore {
-
-const String& DiagnosticLoggingKeys::mediaLoadedKey()
-{
- DEFINE_STATIC_LOCAL(const String, key, ("mediaLoaded"));
- return key;
-}
-
-const String& DiagnosticLoggingKeys::mediaLoadingFailedKey()
-{
- DEFINE_STATIC_LOCAL(const String, key, ("mediaFailedLoading"));
- return key;
-}
-
-const String& DiagnosticLoggingKeys::pluginLoadedKey()
-{
- DEFINE_STATIC_LOCAL(const String, key, ("pluginLoaded"));
- return key;
-}
-
-const String& DiagnosticLoggingKeys::pluginLoadingFailedKey()
-{
- DEFINE_STATIC_LOCAL(const String, key, ("pluginFailedLoading"));
- return key;
-}
-
-const String& DiagnosticLoggingKeys::pageContainsPluginKey()
-{
- DEFINE_STATIC_LOCAL(const String, key, ("pageContainsPlugin"));
- return key;
-}
-
-const String& DiagnosticLoggingKeys::pageContainsAtLeastOnePluginKey()
-{
- DEFINE_STATIC_LOCAL(const String, key, ("pageContainsAtLeastOnePlugin"));
- return key;
-}
-
-const String& DiagnosticLoggingKeys::pageContainsMediaEngineKey()
-{
- DEFINE_STATIC_LOCAL(const String, key, ("pageContainsMediaEngine"));
- return key;
-}
-
-const String& DiagnosticLoggingKeys::pageContainsAtLeastOneMediaEngineKey()
-{
- DEFINE_STATIC_LOCAL(const String, key, ("pageContainsAtLeastOneMediaEngine"));
- return key;
-}
-
-const String& DiagnosticLoggingKeys::passKey()
-{
- DEFINE_STATIC_LOCAL(const String, key, ("pass"));
- return key;
-}
-
-const String& DiagnosticLoggingKeys::failKey()
-{
- DEFINE_STATIC_LOCAL(const String, key, ("fail"));
- return key;
-}
-
-const String& DiagnosticLoggingKeys::noopKey()
-{
- DEFINE_STATIC_LOCAL(const String, key, ("noop"));
- return key;
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/page/DiagnosticLoggingKeys.h b/chromium/third_party/WebKit/Source/core/page/DiagnosticLoggingKeys.h
deleted file mode 100644
index 50f03626f0f..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/DiagnosticLoggingKeys.h
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright (C) 2012 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef DiagnosticLoggingKeys_h
-#define DiagnosticLoggingKeys_h
-
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class DiagnosticLoggingKeys {
-public:
- // Message keys
- static const String& mediaLoadedKey();
- static const String& mediaLoadingFailedKey();
- static const String& pluginLoadedKey();
- static const String& pluginLoadingFailedKey();
- static const String& pageContainsPluginKey();
- static const String& pageContainsAtLeastOnePluginKey();
- static const String& pageContainsMediaEngineKey();
- static const String& pageContainsAtLeastOneMediaEngineKey();
-
- // Success keys
- static const String& passKey();
- static const String& failKey();
- static const String& noopKey();
-};
-
-}
-
-#endif // DiagnosticLoggingKeys_h
diff --git a/chromium/third_party/WebKit/Source/core/page/DragActions.h b/chromium/third_party/WebKit/Source/core/page/DragActions.h
index d98c9c40e2a..ce42ab777d9 100644
--- a/chromium/third_party/WebKit/Source/core/page/DragActions.h
+++ b/chromium/third_party/WebKit/Source/core/page/DragActions.h
@@ -39,13 +39,12 @@ namespace WebCore {
DragDestinationActionAny = UINT_MAX
} DragDestinationAction;
- // WebCoreDragSourceAction should be kept in sync with WebDragSourceAction
typedef enum {
- DragSourceActionNone = 0,
- DragSourceActionDHTML = 1,
- DragSourceActionImage = 2,
- DragSourceActionLink = 4,
- DragSourceActionSelection = 8,
+ DragSourceActionNone,
+ DragSourceActionDHTML,
+ DragSourceActionImage,
+ DragSourceActionLink,
+ DragSourceActionSelection,
} DragSourceAction;
//matches NSDragOperation
diff --git a/chromium/third_party/WebKit/Source/core/page/DragController.cpp b/chromium/third_party/WebKit/Source/core/page/DragController.cpp
index 166fc1c5725..b53c4ea6dc0 100644
--- a/chromium/third_party/WebKit/Source/core/page/DragController.cpp
+++ b/chromium/third_party/WebKit/Source/core/page/DragController.cpp
@@ -36,7 +36,6 @@
#include "core/dom/Element.h"
#include "core/dom/Node.h"
#include "core/dom/Text.h"
-#include "core/dom/TextEvent.h"
#include "core/dom/shadow/ShadowRoot.h"
#include "core/editing/Editor.h"
#include "core/editing/FrameSelection.h"
@@ -44,35 +43,36 @@
#include "core/editing/ReplaceSelectionCommand.h"
#include "core/editing/htmlediting.h"
#include "core/editing/markup.h"
+#include "core/events/TextEvent.h"
#include "core/fetch/ImageResource.h"
#include "core/fetch/ResourceFetcher.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
#include "core/html/HTMLAnchorElement.h"
#include "core/html/HTMLFormElement.h"
#include "core/html/HTMLInputElement.h"
#include "core/html/HTMLPlugInElement.h"
#include "core/loader/FrameLoadRequest.h"
#include "core/loader/FrameLoader.h"
-#include "core/page/DragActions.h"
#include "core/page/DragClient.h"
+#include "core/page/DragData.h"
#include "core/page/DragSession.h"
#include "core/page/DragState.h"
#include "core/page/EventHandler.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameView.h"
#include "core/page/Page.h"
-#include "core/page/Settings.h"
-#include "core/platform/DragData.h"
+#include "core/frame/Settings.h"
#include "core/platform/DragImage.h"
-#include "core/platform/graphics/FloatRect.h"
-#include "core/platform/graphics/Image.h"
-#include "core/platform/graphics/ImageOrientation.h"
-#include "core/platform/network/ResourceRequest.h"
+#include "core/platform/chromium/ChromiumDataObject.h"
#include "core/rendering/HitTestRequest.h"
#include "core/rendering/HitTestResult.h"
#include "core/rendering/RenderImage.h"
#include "core/rendering/RenderTheme.h"
#include "core/rendering/RenderView.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/geometry/FloatRect.h"
+#include "platform/graphics/Image.h"
+#include "platform/graphics/ImageOrientation.h"
+#include "platform/network/ResourceRequest.h"
+#include "platform/weborigin/SecurityOrigin.h"
#include "wtf/CurrentTime.h"
#include "wtf/OwnPtr.h"
#include "wtf/PassOwnPtr.h"
@@ -91,6 +91,7 @@ static const int MaxOriginalImageArea = 1500 * 1500;
static const int LinkDragBorderInset = 2;
static const float DragImageAlpha = 0.75f;
+#if !ASSERT_DISABLED
static bool dragTypeIsValid(DragSourceAction action)
{
switch (action) {
@@ -105,6 +106,7 @@ static bool dragTypeIsValid(DragSourceAction action)
// Make sure MSVC doesn't complain that not all control paths return a value.
return false;
}
+#endif
static PlatformMouseEvent createMouseEvent(DragData* dragData)
{
@@ -121,6 +123,11 @@ static PlatformMouseEvent createMouseEvent(DragData* dragData)
metaKey, currentTime());
}
+static PassRefPtr<Clipboard> createDraggingClipboard(ClipboardAccessPolicy policy, DragData* dragData)
+{
+ return Clipboard::create(Clipboard::DragAndDrop, policy, dragData->platformData());
+}
+
DragController::DragController(Page* page, DragClient* client)
: m_page(page)
, m_client(client)
@@ -154,16 +161,16 @@ static PassRefPtr<DocumentFragment> documentFragmentFromDragData(DragData* dragD
if (PassRefPtr<DocumentFragment> fragment = dragData->asFragment(frame, context, allowPlainText, chosePlainText))
return fragment;
- if (dragData->containsURL(frame, DragData::DoNotConvertFilenames)) {
+ if (dragData->containsURL(DragData::DoNotConvertFilenames)) {
String title;
- String url = dragData->asURL(frame, DragData::DoNotConvertFilenames, &title);
+ String url = dragData->asURL(DragData::DoNotConvertFilenames, &title);
if (!url.isEmpty()) {
RefPtr<HTMLAnchorElement> anchor = HTMLAnchorElement::create(document);
anchor->setHref(url);
if (title.isEmpty()) {
// Try the plain text first because the url might be normalized or escaped.
if (dragData->containsPlainText())
- title = dragData->asPlainText(frame);
+ title = dragData->asPlainText();
if (title.isEmpty())
title = url;
}
@@ -177,7 +184,7 @@ static PassRefPtr<DocumentFragment> documentFragmentFromDragData(DragData* dragD
}
if (allowPlainText && dragData->containsPlainText()) {
chosePlainText = true;
- return createFragmentFromText(context.get(), dragData->asPlainText(frame)).get();
+ return createFragmentFromText(context.get(), dragData->asPlainText()).get();
}
return 0;
@@ -213,9 +220,9 @@ void DragController::dragExited(DragData* dragData)
if (RefPtr<FrameView> v = mainFrame->view()) {
ClipboardAccessPolicy policy = (!m_documentUnderMouse || m_documentUnderMouse->securityOrigin()->isLocal()) ? ClipboardReadable : ClipboardTypesReadable;
- RefPtr<Clipboard> clipboard = Clipboard::create(policy, dragData, mainFrame);
+ RefPtr<Clipboard> clipboard = createDraggingClipboard(policy, dragData);
clipboard->setSourceOperation(dragData->draggingSourceOperationMask());
- mainFrame->eventHandler()->cancelDragAndDrop(createMouseEvent(dragData), clipboard.get());
+ mainFrame->eventHandler().cancelDragAndDrop(createMouseEvent(dragData), clipboard.get());
clipboard->setAccessPolicy(ClipboardNumb); // invalidate clipboard here for security
}
mouseMovedIntoDocument(0);
@@ -238,9 +245,9 @@ bool DragController::performDrag(DragData* dragData)
bool preventedDefault = false;
if (mainFrame->view()) {
// Sending an event can result in the destruction of the view and part.
- RefPtr<Clipboard> clipboard = Clipboard::create(ClipboardReadable, dragData, mainFrame.get());
+ RefPtr<Clipboard> clipboard = createDraggingClipboard(ClipboardReadable, dragData);
clipboard->setSourceOperation(dragData->draggingSourceOperationMask());
- preventedDefault = mainFrame->eventHandler()->performDragAndDrop(createMouseEvent(dragData), clipboard.get());
+ preventedDefault = mainFrame->eventHandler().performDragAndDrop(createMouseEvent(dragData), clipboard.get());
clipboard->setAccessPolicy(ClipboardNumb); // Invalidate clipboard here for security
}
if (preventedDefault) {
@@ -259,7 +266,7 @@ bool DragController::performDrag(DragData* dragData)
if (operationForLoad(dragData) == DragOperationNone)
return false;
- m_page->mainFrame()->loader()->load(FrameLoadRequest(0, ResourceRequest(dragData->asURL(m_page->mainFrame()))));
+ m_page->mainFrame()->loader().load(FrameLoadRequest(0, ResourceRequest(dragData->asURL())));
return true;
}
@@ -310,7 +317,7 @@ static Element* elementUnderMouse(Document* documentUnderMouse, const IntPoint&
float zoomFactor = frame ? frame->pageZoomFactor() : 1;
LayoutPoint point = roundedLayoutPoint(FloatPoint(p.x() * zoomFactor, p.y() * zoomFactor));
- HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::DisallowShadowContent);
+ HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent);
HitTestResult result(point);
documentUnderMouse->renderView()->hitTest(request, result);
@@ -432,7 +439,7 @@ static bool setSelectionToDragCaret(Frame* frame, VisibleSelection& dragCaret, R
bool DragController::dispatchTextInputEventFor(Frame* innerFrame, DragData* dragData)
{
ASSERT(m_page->dragCaretController().hasCaret());
- String text = m_page->dragCaretController().isContentRichlyEditable() ? "" : dragData->asPlainText(innerFrame);
+ String text = m_page->dragCaretController().isContentRichlyEditable() ? "" : dragData->asPlainText();
Node* target = innerFrame->editor().findEventTargetFrom(m_page->dragCaretController().caretPosition());
return target->dispatchEvent(TextEvent::createForDrop(innerFrame->domWindow(), text), IGNORE_EXCEPTION);
}
@@ -489,9 +496,8 @@ bool DragController::concludeEditDrag(DragData* dragData)
if (dragIsMove(innerFrame->selection(), dragData) || dragCaret.isContentRichlyEditable()) {
bool chosePlainText = false;
RefPtr<DocumentFragment> fragment = documentFragmentFromDragData(dragData, innerFrame.get(), range, true, chosePlainText);
- if (!fragment || !innerFrame->editor().shouldInsertFragment(fragment, range, EditorInsertActionDropped)) {
+ if (!fragment)
return false;
- }
if (dragIsMove(innerFrame->selection(), dragData)) {
// NSTextView behavior is to always smart delete on moving a selection,
@@ -511,10 +517,9 @@ bool DragController::concludeEditDrag(DragData* dragData)
}
}
} else {
- String text = dragData->asPlainText(innerFrame.get());
- if (text.isEmpty() || !innerFrame->editor().shouldInsertText(text, range.get(), EditorInsertActionDropped)) {
+ String text = dragData->asPlainText();
+ if (text.isEmpty())
return false;
- }
if (setSelectionToDragCaret(innerFrame.get(), dragCaret, range, point)) {
ASSERT(m_documentUnderMouse);
@@ -524,7 +529,7 @@ bool DragController::concludeEditDrag(DragData* dragData)
if (rootEditableElement) {
if (Frame* frame = rootEditableElement->document().frame())
- frame->eventHandler()->updateDragStateAfterEditDragIfNeeded(rootEditableElement.get());
+ frame->eventHandler().updateDragStateAfterEditDragIfNeeded(rootEditableElement.get());
}
return true;
@@ -542,7 +547,7 @@ bool DragController::canProcessDrag(DragData* dragData)
if (!m_page->mainFrame()->contentRenderer())
return false;
- result = m_page->mainFrame()->eventHandler()->hitTestResultAtPoint(point);
+ result = m_page->mainFrame()->eventHandler().hitTestResultAtPoint(point);
if (!result.innerNonSharedNode())
return false;
@@ -592,12 +597,12 @@ bool DragController::tryDHTMLDrag(DragData* dragData, DragOperation& operation)
return false;
ClipboardAccessPolicy policy = m_documentUnderMouse->securityOrigin()->isLocal() ? ClipboardReadable : ClipboardTypesReadable;
- RefPtr<Clipboard> clipboard = Clipboard::create(policy, dragData, mainFrame.get());
+ RefPtr<Clipboard> clipboard = createDraggingClipboard(policy, dragData);
DragOperation srcOpMask = dragData->draggingSourceOperationMask();
clipboard->setSourceOperation(srcOpMask);
PlatformMouseEvent event = createMouseEvent(dragData);
- if (!mainFrame->eventHandler()->updateDragAndDrop(event, clipboard.get())) {
+ if (!mainFrame->eventHandler().updateDragAndDrop(event, clipboard.get())) {
clipboard->setAccessPolicy(ClipboardNumb); // invalidate clipboard here for security
return false;
}
@@ -614,45 +619,77 @@ bool DragController::tryDHTMLDrag(DragData* dragData, DragOperation& operation)
return true;
}
-Node* DragController::draggableNode(const Frame* src, Node* startNode, const IntPoint& dragOrigin, DragState& state) const
+Node* DragController::draggableNode(const Frame* src, Node* startNode, const IntPoint& dragOrigin, SelectionDragPolicy selectionDragPolicy, DragSourceAction& dragType) const
{
- state.m_dragType = (src->selection().contains(dragOrigin)) ? DragSourceActionSelection : DragSourceActionNone;
+ if (src->selection().contains(dragOrigin)) {
+ dragType = DragSourceActionSelection;
+ if (selectionDragPolicy == ImmediateSelectionDragResolution)
+ return startNode;
+ } else {
+ dragType = DragSourceActionNone;
+ }
+ Node* node = 0;
+ DragSourceAction candidateDragType = DragSourceActionNone;
for (const RenderObject* renderer = startNode->renderer(); renderer; renderer = renderer->parent()) {
- Node* node = renderer->nonPseudoNode();
- if (!node)
+ node = renderer->nonPseudoNode();
+ if (!node) {
// Anonymous render blocks don't correspond to actual DOM nodes, so we skip over them
// for the purposes of finding a draggable node.
continue;
- if (!(state.m_dragType & DragSourceActionSelection) && node->isTextNode() && node->canStartSelection())
+ }
+ if (dragType != DragSourceActionSelection && node->isTextNode() && node->canStartSelection()) {
// In this case we have a click in the unselected portion of text. If this text is
// selectable, we want to start the selection process instead of looking for a parent
// to try to drag.
return 0;
+ }
if (node->isElementNode()) {
EUserDrag dragMode = renderer->style()->userDrag();
if (dragMode == DRAG_NONE)
continue;
+ // Even if the image is part of a selection, we always only drag the image in this case.
if (renderer->isImage()
&& src->settings()
&& src->settings()->loadsImagesAutomatically()) {
- state.m_dragType = static_cast<DragSourceAction>(state.m_dragType | DragSourceActionImage);
+ dragType = DragSourceActionImage;
return node;
}
+ // Other draggable elements are considered unselectable.
if (isHTMLAnchorElement(node)
&& toHTMLAnchorElement(node)->isLiveLink()) {
- state.m_dragType = static_cast<DragSourceAction>(state.m_dragType | DragSourceActionLink);
- return node;
+ candidateDragType = DragSourceActionLink;
+ break;
}
if (dragMode == DRAG_ELEMENT) {
- state.m_dragType = static_cast<DragSourceAction>(state.m_dragType | DragSourceActionDHTML);
- return node;
+ candidateDragType = DragSourceActionDHTML;
+ break;
}
}
}
- // We either have nothing to drag or we have a selection and we're not over a draggable element.
- return (state.m_dragType & DragSourceActionSelection) ? startNode : 0;
+ if (candidateDragType == DragSourceActionNone) {
+ // Either:
+ // 1) Nothing under the cursor is considered draggable, so we bail out.
+ // 2) There was a selection under the cursor but selectionDragPolicy is set to
+ // DelayedSelectionDragResolution and no other draggable element could be found, so bail
+ // out and allow text selection to start at the cursor instead.
+ return 0;
+ }
+
+ ASSERT(node);
+ if (dragType == DragSourceActionSelection) {
+ // Dragging unselectable elements in a selection has special behavior if selectionDragPolicy
+ // is DelayedSelectionDragResolution and this drag was flagged as a potential selection
+ // drag. In that case, don't allow selection and just drag the entire selection instead.
+ ASSERT(selectionDragPolicy == DelayedSelectionDragResolution);
+ node = startNode;
+ } else {
+ // If the cursor isn't over a selection, then just drag the node we found earlier.
+ ASSERT(dragType == DragSourceActionNone);
+ dragType = candidateDragType;
+ }
+ return node;
}
static ImageResource* getImageResource(Element* element)
@@ -683,7 +720,7 @@ static void prepareClipboardForImageDrag(Frame* source, Clipboard* clipboard, El
range->selectNode(node, ASSERT_NO_EXCEPTION);
source->selection().setSelection(VisibleSelection(range.get(), DOWNSTREAM));
}
- clipboard->declareAndWriteDragImage(node, !linkURL.isEmpty() ? linkURL : imageURL, label, source);
+ clipboard->declareAndWriteDragImage(node, !linkURL.isEmpty() ? linkURL : imageURL, label);
}
bool DragController::populateDragClipboard(Frame* src, const DragState& state, const IntPoint& dragOrigin)
@@ -693,7 +730,7 @@ bool DragController::populateDragClipboard(Frame* src, const DragState& state, c
if (!src->view() || !src->contentRenderer())
return false;
- HitTestResult hitTestResult = src->eventHandler()->hitTestResultAtPoint(dragOrigin, HitTestRequest::ReadOnly | HitTestRequest::Active);
+ HitTestResult hitTestResult = src->eventHandler().hitTestResultAtPoint(dragOrigin);
// FIXME: Can this even happen? I guess it's possible, but should verify
// with a layout test.
if (!state.m_dragSrc->contains(hitTestResult.innerNode())) {
@@ -727,7 +764,7 @@ bool DragController::populateDragClipboard(Frame* src, const DragState& state, c
return false;
// Simplify whitespace so the title put on the clipboard resembles what the user sees
// on the web page. This includes replacing newlines with spaces.
- clipboard->writeURL(linkURL, hitTestResult.textContent().simplifyWhiteSpace(), src);
+ clipboard->writeURL(linkURL, hitTestResult.textContent().simplifyWhiteSpace());
}
// FIXME: For DHTML/draggable element drags, write element markup to clipboard.
return true;
@@ -813,12 +850,13 @@ bool DragController::startDrag(Frame* src, const DragState& state, const Platfor
if (!src->view() || !src->contentRenderer())
return false;
- HitTestResult hitTestResult = src->eventHandler()->hitTestResultAtPoint(dragOrigin);
- if (!state.m_dragSrc->contains(hitTestResult.innerNode()))
+ HitTestResult hitTestResult = src->eventHandler().hitTestResultAtPoint(dragOrigin);
+ if (!state.m_dragSrc->contains(hitTestResult.innerNode())) {
// The original node being dragged isn't under the drag origin anymore... maybe it was
// hidden or moved out from under the cursor. Regardless, we don't want to start a drag on
// something that's not actually under the drag origin.
return false;
+ }
const KURL& linkURL = hitTestResult.absoluteLinkURL();
const KURL& imageURL = hitTestResult.absoluteImageURL();
@@ -830,7 +868,7 @@ bool DragController::startDrag(Frame* src, const DragState& state, const Platfor
Clipboard* clipboard = state.m_dragClipboard.get();
// We allow DHTML/JS to set the drag image, even if its a link, image or text we're dragging.
// This is in the spirit of the IE API, which allows overriding of pasteboard data and DragOp.
- OwnPtr<DragImage> dragImage = clipboard->createDragImage(dragOffset);
+ OwnPtr<DragImage> dragImage = clipboard->createDragImage(dragOffset, src);
if (dragImage) {
dragLocation = dragLocationForDHTMLDrag(mouseDraggedPoint, dragOrigin, dragOffset, !linkURL.isEmpty());
}
@@ -910,7 +948,7 @@ DragOperation DragController::dragOperation(DragData* dragData)
// attached sheet If this can be determined from within WebCore
// operationForDrag can be pulled into WebCore itself
ASSERT(dragData);
- return dragData->containsURL(0) && !m_didInitiateDrag ? DragOperationCopy : DragOperationNone;
+ return dragData->containsURL() && !m_didInitiateDrag ? DragOperationCopy : DragOperationNone;
}
bool DragController::isCopyKeyDown(DragData*)
diff --git a/chromium/third_party/WebKit/Source/core/page/DragController.h b/chromium/third_party/WebKit/Source/core/page/DragController.h
index 23293e53f53..f109837df9b 100644
--- a/chromium/third_party/WebKit/Source/core/page/DragController.h
+++ b/chromium/third_party/WebKit/Source/core/page/DragController.h
@@ -27,8 +27,8 @@
#define DragController_h
#include "core/page/DragActions.h"
-#include "core/platform/graphics/IntPoint.h"
-#include "weborigin/KURL.h"
+#include "platform/geometry/IntPoint.h"
+#include "platform/weborigin/KURL.h"
#include "wtf/Forward.h"
namespace WebCore {
@@ -63,7 +63,11 @@ namespace WebCore {
DragSession dragUpdated(DragData*);
bool performDrag(DragData*);
- Node* draggableNode(const Frame*, Node*, const IntPoint&, DragState&) const;
+ enum SelectionDragPolicy {
+ ImmediateSelectionDragResolution,
+ DelayedSelectionDragResolution,
+ };
+ Node* draggableNode(const Frame*, Node*, const IntPoint&, SelectionDragPolicy, DragSourceAction&) const;
void dragEnded();
bool populateDragClipboard(Frame* src, const DragState&, const IntPoint& dragOrigin);
diff --git a/chromium/third_party/WebKit/Source/core/page/DragData.cpp b/chromium/third_party/WebKit/Source/core/page/DragData.cpp
new file mode 100644
index 00000000000..79a22571264
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/page/DragData.cpp
@@ -0,0 +1,172 @@
+/*
+ * Copyright (C) 2007 Apple Inc. All rights reserved.
+ * Copyright (C) 2013 Google Inc.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/page/DragData.h"
+
+#include "core/dom/Document.h"
+#include "core/dom/DocumentFragment.h"
+#include "core/dom/Range.h"
+#include "core/editing/markup.h"
+#include "core/frame/Frame.h"
+#include "core/platform/chromium/ChromiumDataObject.h"
+#include "modules/filesystem/DraggedIsolatedFileSystem.h"
+#include "platform/FileMetadata.h"
+#include "platform/clipboard/ClipboardMimeTypes.h"
+#include "platform/weborigin/KURL.h"
+#include "wtf/text/WTFString.h"
+
+namespace WebCore {
+
+DragData::DragData(ChromiumDataObject* data, const IntPoint& clientPosition, const IntPoint& globalPosition,
+ DragOperation sourceOperationMask, DragApplicationFlags flags)
+ : m_clientPosition(clientPosition)
+ , m_globalPosition(globalPosition)
+ , m_platformDragData(data)
+ , m_draggingSourceOperationMask(sourceOperationMask)
+ , m_applicationFlags(flags)
+{
+}
+
+DragData::DragData(const String&, const IntPoint& clientPosition, const IntPoint& globalPosition,
+ DragOperation sourceOperationMask, DragApplicationFlags flags)
+ : m_clientPosition(clientPosition)
+ , m_globalPosition(globalPosition)
+ , m_platformDragData(0)
+ , m_draggingSourceOperationMask(sourceOperationMask)
+ , m_applicationFlags(flags)
+{
+}
+
+static bool containsHTML(const ChromiumDataObject* dropData)
+{
+ return dropData->types().contains(mimeTypeTextHTML);
+}
+
+bool DragData::containsURL(FilenameConversionPolicy filenamePolicy) const
+{
+ return m_platformDragData->types().contains(mimeTypeTextURIList)
+ || (filenamePolicy == ConvertFilenames && m_platformDragData->containsFilenames());
+}
+
+String DragData::asURL(FilenameConversionPolicy filenamePolicy, String* title) const
+{
+ String url;
+ if (m_platformDragData->types().contains(mimeTypeTextURIList))
+ m_platformDragData->urlAndTitle(url, title);
+ else if (filenamePolicy == ConvertFilenames && containsFiles())
+ url = filePathToURL(m_platformDragData->filenames()[0]);
+ return url;
+}
+
+bool DragData::containsFiles() const
+{
+ return m_platformDragData->containsFilenames();
+}
+
+unsigned DragData::numberOfFiles() const
+{
+ return m_platformDragData->filenames().size();
+}
+
+int DragData::modifierKeyState() const
+{
+ return m_platformDragData->modifierKeyState();
+}
+
+void DragData::asFilenames(Vector<String>& result) const
+{
+ const Vector<String>& filenames = m_platformDragData->filenames();
+ for (size_t i = 0; i < filenames.size(); ++i)
+ result.append(filenames[i]);
+}
+
+bool DragData::containsPlainText() const
+{
+ return m_platformDragData->types().contains(mimeTypeTextPlain);
+}
+
+String DragData::asPlainText() const
+{
+ return m_platformDragData->getData(mimeTypeTextPlain);
+}
+
+bool DragData::canSmartReplace() const
+{
+ // Mimic the situations in which mac allows drag&drop to do a smart replace.
+ // This is allowed whenever the drag data contains a 'range' (ie.,
+ // ClipboardWin::writeRange is called). For example, dragging a link
+ // should not result in a space being added.
+ return m_platformDragData->types().contains(mimeTypeTextPlain)
+ && !m_platformDragData->types().contains(mimeTypeTextURIList);
+}
+
+bool DragData::containsCompatibleContent() const
+{
+ return containsPlainText()
+ || containsURL()
+ || containsHTML(m_platformDragData)
+ || containsFiles();
+}
+
+PassRefPtr<DocumentFragment> DragData::asFragment(Frame* frame, PassRefPtr<Range>, bool, bool&) const
+{
+ /*
+ * Order is richest format first. On OSX this is:
+ * * Web Archive
+ * * Filenames
+ * * HTML
+ * * RTF
+ * * TIFF
+ * * PICT
+ */
+
+ if (containsFiles()) {
+ // FIXME: Implement this. Should be pretty simple to make some HTML
+ // and call createFragmentFromMarkup.
+ }
+
+ if (m_platformDragData->types().contains(mimeTypeTextHTML)) {
+ String html;
+ KURL baseURL;
+ m_platformDragData->htmlAndBaseURL(html, baseURL);
+ ASSERT(frame->document());
+ if (RefPtr<DocumentFragment> fragment = createFragmentFromMarkup(*frame->document(), html, baseURL, DisallowScriptingAndPluginContent))
+ return fragment.release();
+ }
+
+ return 0;
+}
+
+String DragData::droppedFileSystemId() const
+{
+ DraggedIsolatedFileSystem* filesystem = DraggedIsolatedFileSystem::from(m_platformDragData);
+ if (!filesystem)
+ return String();
+ return filesystem->filesystemId();
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/page/DragData.h b/chromium/third_party/WebKit/Source/core/page/DragData.h
new file mode 100644
index 00000000000..33c108c5fe2
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/page/DragData.h
@@ -0,0 +1,88 @@
+/*
+ * Copyright (C) 2007 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef DragData_h
+#define DragData_h
+
+#include "core/page/DragActions.h"
+#include "platform/geometry/IntPoint.h"
+
+#include "wtf/Forward.h"
+#include "wtf/HashMap.h"
+#include "wtf/Vector.h"
+
+namespace WebCore {
+
+class ChromiumDataObject;
+class DocumentFragment;
+class Frame;
+class KURL;
+class Range;
+
+enum DragApplicationFlags {
+ DragApplicationNone = 0,
+ DragApplicationIsModal = 1,
+ DragApplicationIsSource = 2,
+ DragApplicationHasAttachedSheet = 4,
+ DragApplicationIsCopyKeyDown = 8
+};
+
+class DragData {
+public:
+ enum FilenameConversionPolicy { DoNotConvertFilenames, ConvertFilenames };
+
+ // clientPosition is taken to be the position of the drag event within the target window, with (0,0) at the top left
+ DragData(ChromiumDataObject*, const IntPoint& clientPosition, const IntPoint& globalPosition, DragOperation, DragApplicationFlags = DragApplicationNone);
+ DragData(const String& dragStorageName, const IntPoint& clientPosition, const IntPoint& globalPosition, DragOperation, DragApplicationFlags = DragApplicationNone);
+ const IntPoint& clientPosition() const { return m_clientPosition; }
+ const IntPoint& globalPosition() const { return m_globalPosition; }
+ DragApplicationFlags flags() const { return m_applicationFlags; }
+ ChromiumDataObject* platformData() const { return m_platformDragData; }
+ DragOperation draggingSourceOperationMask() const { return m_draggingSourceOperationMask; }
+ bool containsURL(FilenameConversionPolicy filenamePolicy = ConvertFilenames) const;
+ bool containsPlainText() const;
+ bool containsCompatibleContent() const;
+ String asURL(FilenameConversionPolicy filenamePolicy = ConvertFilenames, String* title = 0) const;
+ String asPlainText() const;
+ void asFilenames(Vector<String>&) const;
+ PassRefPtr<DocumentFragment> asFragment(Frame*, PassRefPtr<Range> context, bool allowPlainText, bool& chosePlainText) const;
+ bool canSmartReplace() const;
+ bool containsFiles() const;
+ unsigned numberOfFiles() const;
+ int modifierKeyState() const;
+
+ String droppedFileSystemId() const;
+
+private:
+ IntPoint m_clientPosition;
+ IntPoint m_globalPosition;
+ ChromiumDataObject* m_platformDragData;
+ DragOperation m_draggingSourceOperationMask;
+ DragApplicationFlags m_applicationFlags;
+};
+
+}
+
+#endif // !DragData_h
diff --git a/chromium/third_party/WebKit/Source/core/page/DragState.h b/chromium/third_party/WebKit/Source/core/page/DragState.h
index 5b8780ca30d..6b866577170 100644
--- a/chromium/third_party/WebKit/Source/core/page/DragState.h
+++ b/chromium/third_party/WebKit/Source/core/page/DragState.h
@@ -26,10 +26,7 @@
#ifndef DragState_h
#define DragState_h
-#include "core/dom/Clipboard.h"
-#include "core/dom/Node.h"
#include "core/page/DragActions.h"
-#include "wtf/Forward.h"
#include "wtf/Noncopyable.h"
#include "wtf/RefPtr.h"
diff --git a/chromium/third_party/WebKit/Source/core/page/EditorClient.h b/chromium/third_party/WebKit/Source/core/page/EditorClient.h
index 5b866af7b66..f7664b6ba73 100644
--- a/chromium/third_party/WebKit/Source/core/page/EditorClient.h
+++ b/chromium/third_party/WebKit/Source/core/page/EditorClient.h
@@ -27,86 +27,27 @@
#ifndef EditorClient_h
#define EditorClient_h
-#include "core/editing/EditorInsertAction.h"
-#include "core/editing/TextAffinity.h"
-#include "core/editing/UndoStep.h"
-#include "core/platform/graphics/FloatRect.h"
-#include "core/platform/text/TextChecking.h"
+#include "core/editing/SelectionType.h"
#include "wtf/Forward.h"
-#include "wtf/Vector.h"
namespace WebCore {
-class ArchiveResource;
-class DocumentFragment;
-class Editor;
class Element;
class Frame;
-class HTMLElement;
-class KeyboardEvent;
-class Node;
-class Range;
-class SharedBuffer;
-class StylePropertySet;
-class TextCheckerClient;
-class VisibleSelection;
-class VisiblePosition;
-
-struct GrammarDetail;
+class UndoStep;
class EditorClient {
public:
- virtual ~EditorClient() { }
-
- virtual bool shouldDeleteRange(Range*) = 0;
- virtual bool smartInsertDeleteEnabled() = 0;
- virtual bool isSelectTrailingWhitespaceEnabled() = 0;
- virtual bool isContinuousSpellCheckingEnabled() = 0;
- virtual void toggleContinuousSpellChecking() = 0;
- virtual bool isGrammarCheckingEnabled() = 0;
-
- virtual bool shouldBeginEditing(Range*) = 0;
- virtual bool shouldEndEditing(Range*) = 0;
- virtual bool shouldInsertNode(Node*, Range*, EditorInsertAction) = 0;
- virtual bool shouldInsertText(const String&, Range*, EditorInsertAction) = 0;
- virtual bool shouldChangeSelectedRange(Range* fromRange, Range* toRange, EAffinity, bool stillSelecting) = 0;
+ virtual ~EditorClient() { }
- virtual bool shouldApplyStyle(StylePropertySet*, Range*) = 0;
-
- virtual void didBeginEditing() = 0;
virtual void respondToChangedContents() = 0;
- virtual void respondToChangedSelection(Frame*) = 0;
- virtual void didEndEditing() = 0;
- virtual void didCancelCompositionOnSelectionChange() = 0;
-
- virtual void registerUndoStep(PassRefPtr<UndoStep>) = 0;
- virtual void registerRedoStep(PassRefPtr<UndoStep>) = 0;
- virtual void clearUndoRedoOperations() = 0;
+ virtual void respondToChangedSelection(SelectionType) = 0;
virtual bool canCopyCut(Frame*, bool defaultValue) const = 0;
virtual bool canPaste(Frame*, bool defaultValue) const = 0;
- virtual bool canUndo() const = 0;
- virtual bool canRedo() const = 0;
-
- virtual void undo() = 0;
- virtual void redo() = 0;
-
- virtual void handleKeyboardEvent(KeyboardEvent*) = 0;
-
- virtual void textFieldDidEndEditing(Element*) = 0;
- virtual void textDidChangeInTextField(Element*) = 0;
- virtual bool doTextFieldCommandFromEvent(Element*, KeyboardEvent*) = 0;
-
- virtual TextCheckerClient& textChecker() = 0;
-
- virtual void updateSpellingUIWithMisspelledWord(const String&) = 0;
- virtual void showSpellingUI(bool show) = 0;
- virtual bool spellingUIIsShowing() = 0;
- virtual void willSetInputMethodState() = 0;
- // Support for global selections, used on platforms like the X Window System that treat
- // selection as a type of clipboard.
- virtual bool supportsGlobalSelection() { return false; }
+ virtual void didExecuteCommand(String) = 0;
+ virtual bool handleKeyboardEvent() = 0;
};
}
diff --git a/chromium/third_party/WebKit/Source/core/page/EventHandler.cpp b/chromium/third_party/WebKit/Source/core/page/EventHandler.cpp
index d99e5c12559..40b59aa8a56 100644
--- a/chromium/third_party/WebKit/Source/core/page/EventHandler.cpp
+++ b/chromium/third_party/WebKit/Source/core/page/EventHandler.cpp
@@ -32,67 +32,72 @@
#include "RuntimeEnabledFeatures.h"
#include "SVGNames.h"
#include "bindings/v8/ExceptionStatePlaceholder.h"
+#include "core/dom/Clipboard.h"
#include "core/dom/Document.h"
-#include "core/dom/DocumentEventQueue.h"
#include "core/dom/DocumentMarkerController.h"
-#include "core/dom/EventNames.h"
-#include "core/dom/EventPathWalker.h"
#include "core/dom/FullscreenElementStack.h"
-#include "core/dom/KeyboardEvent.h"
-#include "core/dom/MouseEvent.h"
-#include "core/dom/TextEvent.h"
-#include "core/dom/TouchEvent.h"
+#include "core/dom/NodeRenderingTraversal.h"
#include "core/dom/TouchList.h"
-#include "core/dom/UserTypingGestureIndicator.h"
-#include "core/dom/WheelEvent.h"
#include "core/dom/shadow/ShadowRoot.h"
#include "core/editing/Editor.h"
#include "core/editing/FrameSelection.h"
#include "core/editing/TextIterator.h"
#include "core/editing/htmlediting.h"
+#include "core/events/DOMWindowEventQueue.h"
+#include "core/events/EventPath.h"
+#include "core/events/KeyboardEvent.h"
+#include "core/events/MouseEvent.h"
+#include "core/events/TextEvent.h"
+#include "core/events/ThreadLocalEventNames.h"
+#include "core/events/TouchEvent.h"
+#include "core/events/WheelEvent.h"
#include "core/fetch/ImageResource.h"
-#include "core/history/BackForwardController.h"
#include "core/html/HTMLDialogElement.h"
#include "core/html/HTMLFrameElementBase.h"
#include "core/html/HTMLFrameSetElement.h"
#include "core/html/HTMLInputElement.h"
#include "core/loader/FrameLoader.h"
+#include "core/loader/FrameLoaderClient.h"
+#include "core/page/AutoscrollController.h"
+#include "core/page/BackForwardClient.h"
#include "core/page/Chrome.h"
+#include "core/page/ChromeClient.h"
#include "core/page/DragController.h"
#include "core/page/DragState.h"
#include "core/page/EditorClient.h"
#include "core/page/FocusController.h"
-#include "core/page/Frame.h"
+#include "core/frame/Frame.h"
#include "core/page/FrameTree.h"
-#include "core/page/FrameView.h"
+#include "core/frame/FrameView.h"
+#include "core/inspector/InspectorController.h"
#include "core/page/MouseEventWithHitTestResults.h"
#include "core/page/Page.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
#include "core/page/SpatialNavigation.h"
#include "core/page/TouchAdjustment.h"
-#include "core/platform/Cursor.h"
-#include "core/platform/PlatformEvent.h"
-#include "core/platform/PlatformGestureEvent.h"
-#include "core/platform/PlatformKeyboardEvent.h"
-#include "core/platform/PlatformTouchEvent.h"
-#include "core/platform/PlatformWheelEvent.h"
-#include "core/platform/ScrollAnimator.h"
-#include "core/platform/Scrollbar.h"
-#include "core/platform/WindowsKeyboardCodes.h"
#include "core/platform/chromium/ChromiumDataObject.h"
-#include "core/platform/chromium/ClipboardChromium.h"
-#include "core/platform/graphics/FloatPoint.h"
-#include "core/platform/graphics/Image.h"
#include "core/rendering/HitTestRequest.h"
#include "core/rendering/HitTestResult.h"
+#include "core/rendering/RenderFlowThread.h"
#include "core/rendering/RenderLayer.h"
+#include "core/rendering/RenderRegion.h"
#include "core/rendering/RenderTextControlSingleLine.h"
#include "core/rendering/RenderView.h"
#include "core/rendering/RenderWidget.h"
#include "core/rendering/style/CursorList.h"
+#include "core/rendering/style/RenderStyle.h"
#include "core/svg/SVGDocument.h"
#include "core/svg/SVGElementInstance.h"
#include "core/svg/SVGUseElement.h"
+#include "platform/PlatformGestureEvent.h"
+#include "platform/PlatformKeyboardEvent.h"
+#include "platform/PlatformTouchEvent.h"
+#include "platform/PlatformWheelEvent.h"
+#include "platform/WindowsKeyboardCodes.h"
+#include "platform/geometry/FloatPoint.h"
+#include "platform/graphics/Image.h"
+#include "platform/scroll/ScrollAnimator.h"
+#include "platform/scroll/Scrollbar.h"
#include "wtf/Assertions.h"
#include "wtf/CurrentTime.h"
#include "wtf/StdLibExtras.h"
@@ -101,41 +106,43 @@
namespace WebCore {
using namespace HTMLNames;
+using namespace SVGNames;
// The link drag hysteresis is much larger than the others because there
// needs to be enough space to cancel the link press without starting a link drag,
// and because dragging links is rare.
-const int LinkDragHysteresis = 40;
-const int ImageDragHysteresis = 5;
-const int TextDragHysteresis = 3;
-const int GeneralDragHysteresis = 3;
-
-// Match key code of composition keydown event on windows.
-// IE sends VK_PROCESSKEY which has value 229;
-const int CompositionEventKeyCode = 229;
-
-using namespace SVGNames;
+static const int LinkDragHysteresis = 40;
+static const int ImageDragHysteresis = 5;
+static const int TextDragHysteresis = 3;
+static const int GeneralDragHysteresis = 3;
// The amount of time to wait before sending a fake mouse event, triggered
// during a scroll. The short interval is used if the content responds to the mouse events quickly enough,
// otherwise the long interval is used.
-const double fakeMouseMoveShortInterval = 0.1;
-const double fakeMouseMoveLongInterval = 0.250;
+static const double fakeMouseMoveShortInterval = 0.1;
+static const double fakeMouseMoveLongInterval = 0.250;
+
+// The amount of time to wait for a cursor update on style and layout changes
+// Set to 50Hz, no need to be faster than common screen refresh rate
+static const double cursorUpdateInterval = 0.02;
-const int maximumCursorSize = 128;
+static const int maximumCursorSize = 128;
// It's pretty unlikely that a scale of less than one would ever be used. But all we really
// need to ensure here is that the scale isn't so small that integer overflow can occur when
// dividing cursor sizes (limited above) by the scale.
-const double minimumCursorScale = 0.001;
+static const double minimumCursorScale = 0.001;
+
+// The minimum amount of time an element stays active after a ShowPress
+// This is roughly 2 frames, which should be long enough to be noticeable.
+static const double minimumActiveInterval = 0.032;
#if OS(MACOSX)
-const double EventHandler::TextDragDelay = 0.15;
+static const double TextDragDelay = 0.15;
#else
-const double EventHandler::TextDragDelay = 0.0;
+static const double TextDragDelay = 0.0;
#endif
-
enum NoCursorChangeType { NoCursorChange };
class OptionalCursor {
@@ -248,23 +255,41 @@ static inline ScrollGranularity wheelGranularityToScrollGranularity(unsigned del
}
}
-static inline bool scrollNode(float delta, ScrollGranularity granularity, ScrollDirection positiveDirection, ScrollDirection negativeDirection, Node* node, Node** stopNode)
+static inline bool scrollNode(float delta, ScrollGranularity granularity, ScrollDirection direction, Node* node, Node** stopNode, IntPoint absolutePoint = IntPoint())
{
if (!delta)
return false;
if (!node->renderer())
return false;
- RenderBox* enclosingBox = node->renderer()->enclosingBox();
- float absDelta = delta > 0 ? delta : -delta;
- return enclosingBox->scroll(delta < 0 ? negativeDirection : positiveDirection, granularity, absDelta, stopNode);
-}
-static inline bool shouldGesturesTriggerActive()
-{
- // If the platform we're on supports GestureTapDown and GestureTapCancel then we'll
- // rely on them to set the active state. Unfortunately there's no generic way to
- // know in advance what event types are supported.
- return true;
+ RenderBox* curBox = node->renderer()->enclosingBox();
+
+ while (curBox && !curBox->isRenderView()) {
+ ScrollDirection physicalDirection = toPhysicalDirection(
+ direction, curBox->isHorizontalWritingMode(), curBox->style()->isFlippedBlocksWritingMode());
+
+ if (curBox->scroll(physicalDirection, granularity, delta)) {
+ if (stopNode)
+ *stopNode = curBox->node();
+ return true;
+ }
+
+ if (stopNode && *stopNode && curBox->node() == *stopNode)
+ return true;
+
+ // FIXME: This should probably move to a virtual method on RenderBox, something like RenderBox::scrollAncestor, and specialized for RenderFlowThread
+ curBox = curBox->containingBlock();
+ if (curBox && curBox->isRenderNamedFlowThread()) {
+ RenderBox* flowedBox = curBox;
+
+ if (RenderBox* startBox = node->renderBox())
+ flowedBox = startBox;
+
+ curBox = toRenderFlowThread(curBox)->regionFromAbsolutePointAndBox(absolutePoint, flowedBox);
+ }
+ }
+
+ return false;
}
// Refetch the event target node if it is removed or currently is the shadow node inside an <input> element.
@@ -274,8 +299,7 @@ static inline bool shouldGesturesTriggerActive()
static inline bool shouldRefetchEventTarget(const MouseEventWithHitTestResults& mev)
{
Node* targetNode = mev.targetNode();
- ASSERT(targetNode);
- if (!targetNode->parentNode())
+ if (!targetNode || !targetNode->parentNode())
return true;
return targetNode->isShadowRoot() && toShadowRoot(targetNode)->host()->hasTagName(inputTag);
}
@@ -286,17 +310,19 @@ EventHandler::EventHandler(Frame* frame)
, m_capturesDragging(false)
, m_mouseDownMayStartSelect(false)
, m_mouseDownMayStartDrag(false)
- , m_dragMayStartSelectionInstead(false)
, m_mouseDownWasSingleClickInSelection(false)
, m_selectionInitiationState(HaveNotStartedSelection)
+ , m_panScrollButtonPressed(false)
, m_hoverTimer(this, &EventHandler::hoverTimerFired)
+ , m_cursorUpdateTimer(this, &EventHandler::cursorUpdateTimerFired)
, m_mouseDownMayStartAutoscroll(false)
, m_mouseDownWasInSubframe(false)
, m_fakeMouseMoveEventTimer(this, &EventHandler::fakeMouseMoveEventTimerFired)
, m_svgPan(false)
- , m_resizeLayer(0)
+ , m_resizeScrollableArea(0)
, m_eventHandlerWillResetCapturingMouseEventsNode(0)
, m_clickCount(0)
+ , m_shouldOnlyFireDragOverEvent(false)
, m_mousePositionIsUnknown(true)
, m_mouseDownTimestamp(0)
, m_widgetIsLatched(false)
@@ -308,6 +334,9 @@ EventHandler::EventHandler(Frame* frame)
, m_baseEventType(PlatformEvent::NoType)
, m_didStartDrag(false)
, m_longTapShouldInvokeContextMenu(false)
+ , m_syntheticPageScaleFactor(0)
+ , m_activeIntervalTimer(this, &EventHandler::activeIntervalTimerFired)
+ , m_lastShowPressTimestamp(0)
{
}
@@ -325,8 +354,10 @@ DragState& EventHandler::dragState()
void EventHandler::clear()
{
m_hoverTimer.stop();
+ m_cursorUpdateTimer.stop();
m_fakeMouseMoveEventTimer.stop();
- m_resizeLayer = 0;
+ m_activeIntervalTimer.stop();
+ m_resizeScrollableArea = 0;
m_nodeUnderMouse = 0;
m_lastNodeUnderMouse = 0;
m_instanceUnderMouse = 0;
@@ -359,17 +390,28 @@ void EventHandler::clear()
m_baseEventType = PlatformEvent::NoType;
m_didStartDrag = false;
m_touchPressed = false;
+ m_mouseDownMayStartSelect = false;
+ m_mouseDownMayStartDrag = false;
+ m_lastShowPressTimestamp = 0;
+ m_lastDeferredTapElement = 0;
}
-void EventHandler::nodeWillBeRemoved(Node* nodeToBeRemoved)
+void EventHandler::nodeWillBeRemoved(Node& nodeToBeRemoved)
{
- if (nodeToBeRemoved->contains(m_clickNode.get()))
+ if (!nodeToBeRemoved.containsIncludingShadowDOM(m_clickNode.get()))
+ return;
+ if (nodeToBeRemoved.isInShadowTree()) {
+ m_clickNode = nodeToBeRemoved.parentOrShadowHostNode();
+ } else {
+ // We don't dispatch click events if the mousedown node is removed
+ // before a mouseup event. It is compatible with IE and Firefox.
m_clickNode = 0;
+ }
}
static void setSelectionIfNeeded(FrameSelection& selection, const VisibleSelection& newSelection)
{
- if (selection.selection() != newSelection && selection.shouldChangeSelection(newSelection))
+ if (selection.selection() != newSelection)
selection.setSelection(newSelection);
}
@@ -378,7 +420,7 @@ static inline bool dispatchSelectStart(Node* node)
if (!node || !node->renderer())
return true;
- return node->dispatchEvent(Event::createCancelableBubble(eventNames().selectstartEvent));
+ return node->dispatchEvent(Event::createCancelableBubble(EventTypeNames::selectstart));
}
static VisibleSelection expandSelectionToRespectUserSelectAll(Node* targetNode, const VisibleSelection& selection)
@@ -687,7 +729,7 @@ bool EventHandler::handleMouseDraggedEvent(const MouseEventWithHitTestResults& e
RenderObject* renderer = targetNode->renderer();
if (!renderer) {
- Node* parent = EventPathWalker::parent(targetNode);
+ Node* parent = EventPath::parent(targetNode);
if (!parent)
return false;
@@ -699,14 +741,14 @@ bool EventHandler::handleMouseDraggedEvent(const MouseEventWithHitTestResults& e
m_mouseDownMayStartDrag = false;
if (m_mouseDownMayStartAutoscroll && !panScrollInProgress()) {
- if (Page* page = m_frame->page()) {
- page->startAutoscrollForSelection(renderer);
+ if (AutoscrollController* controller = autoscrollController()) {
+ controller->startAutoscrollForSelection(renderer);
m_mouseDownMayStartAutoscroll = false;
}
}
if (m_selectionInitiationState != ExtendedSelection) {
- HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::DisallowShadowContent);
+ HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent);
HitTestResult result(m_mouseDownPos);
m_frame->document()->renderView()->hitTest(request, result);
@@ -725,7 +767,7 @@ void EventHandler::updateSelectionForMouseDrag()
if (!renderer)
return;
- HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::Move | HitTestRequest::DisallowShadowContent);
+ HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::Move | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent);
HitTestResult result(view->windowToContents(m_lastKnownMousePosition));
renderer->hitTest(request, result);
updateSelectionForMouseDrag(result);
@@ -795,16 +837,11 @@ void EventHandler::updateSelectionForMouseDrag(const HitTestResult& hitTestResul
FrameSelection::AdjustEndpointsAtBidiBoundary);
}
-void EventHandler::lostMouseCapture()
-{
- m_frame->selection().setCaretBlinkingSuspended(false);
-}
-
bool EventHandler::handleMouseReleaseEvent(const MouseEventWithHitTestResults& event)
{
- Page* page = m_frame->page();
- if (page && page->autoscrollInProgress())
- stopAutoscrollTimer();
+ AutoscrollController* controller = autoscrollController();
+ if (controller && controller->autoscrollInProgress())
+ stopAutoscroll();
// Used to prevent mouseMoveEvent from initiating a drag before
// the mouse is pressed again.
@@ -828,7 +865,7 @@ bool EventHandler::handleMouseReleaseEvent(const MouseEventWithHitTestResults& e
VisibleSelection newSelection;
Node* node = event.targetNode();
bool caretBrowsing = m_frame->settings() && m_frame->settings()->caretBrowsingEnabled();
- if (node && (caretBrowsing || node->rendererIsEditable()) && node->renderer()) {
+ if (node && node->renderer() && (caretBrowsing || node->rendererIsEditable())) {
VisiblePosition pos = VisiblePosition(node->renderer()->positionForPoint(event.localPoint()));
newSelection = VisibleSelection(pos);
}
@@ -856,19 +893,25 @@ void EventHandler::startPanScrolling(RenderObject* renderer)
{
if (!renderer->isBox())
return;
- Page* page = m_frame->page();
- if (!page)
+ AutoscrollController* controller = autoscrollController();
+ if (!controller)
return;
- page->startPanScrolling(toRenderBox(renderer), lastKnownMousePosition());
+ controller->startPanScrolling(toRenderBox(renderer), lastKnownMousePosition());
invalidateClick();
}
#endif // OS(WIN)
+AutoscrollController* EventHandler::autoscrollController() const
+{
+ if (Page* page = m_frame->page())
+ return &page->autoscrollController();
+ return 0;
+}
+
bool EventHandler::panScrollInProgress() const
{
- Page* page = m_frame->page();
- return page && page->panScrollInProgress();
+ return autoscrollController() && autoscrollController()->panScrollInProgress();
}
HitTestResult EventHandler::hitTestResultAtPoint(const LayoutPoint& point, HitTestRequest::HitTestRequestType hitType, const LayoutSize& padding)
@@ -882,7 +925,7 @@ HitTestResult EventHandler::hitTestResultAtPoint(const LayoutPoint& point, HitTe
FrameView* mainView = mainFrame->view();
if (frameView && mainView) {
IntPoint mainFramePoint = mainView->rootViewToContents(frameView->contentsToRootView(roundedIntPoint(point)));
- return mainFrame->eventHandler()->hitTestResultAtPoint(mainFramePoint, hitType, padding);
+ return mainFrame->eventHandler().hitTestResultAtPoint(mainFramePoint, hitType, padding);
}
}
}
@@ -910,12 +953,10 @@ HitTestResult EventHandler::hitTestResultAtPoint(const LayoutPoint& point, HitTe
return result;
}
-void EventHandler::stopAutoscrollTimer()
+void EventHandler::stopAutoscroll()
{
- Page* page = m_frame->page();
- if (!page)
- return;
- page->stopAutoscrollTimer();
+ if (AutoscrollController* controller = autoscrollController())
+ controller->stopAutoscroll();
}
Node* EventHandler::mousePressNode() const
@@ -923,11 +964,6 @@ Node* EventHandler::mousePressNode() const
return m_mousePressNode.get();
}
-void EventHandler::setMousePressNode(PassRefPtr<Node> node)
-{
- m_mousePressNode = node;
-}
-
bool EventHandler::scrollOverflow(ScrollDirection direction, ScrollGranularity granularity, Node* startingNode)
{
Node* node = startingNode;
@@ -940,28 +976,7 @@ bool EventHandler::scrollOverflow(ScrollDirection direction, ScrollGranularity g
if (node) {
RenderObject* r = node->renderer();
- if (r && !r->isListBox() && r->enclosingBox()->scroll(direction, granularity)) {
- setFrameWasScrolledByUser();
- return true;
- }
- }
-
- return false;
-}
-
-bool EventHandler::logicalScrollOverflow(ScrollLogicalDirection direction, ScrollGranularity granularity, Node* startingNode)
-{
- Node* node = startingNode;
-
- if (!node)
- node = m_frame->document()->focusedElement();
-
- if (!node)
- node = m_mousePressNode.get();
-
- if (node) {
- RenderObject* r = node->renderer();
- if (r && !r->isListBox() && r->enclosingBox()->logicalScroll(direction, granularity)) {
+ if (r && !r->isListBox() && scrollNode(1.0f, granularity, direction, node, 0)) {
setFrameWasScrolledByUser();
return true;
}
@@ -981,34 +996,10 @@ bool EventHandler::scrollRecursively(ScrollDirection direction, ScrollGranularit
FrameView* view = frame->view();
if (view && view->scroll(direction, granularity))
return true;
- frame = frame->tree()->parent();
- if (!frame)
- return false;
- return frame->eventHandler()->scrollRecursively(direction, granularity, m_frame->ownerElement());
-}
-
-bool EventHandler::logicalScrollRecursively(ScrollLogicalDirection direction, ScrollGranularity granularity, Node* startingNode)
-{
- // The layout needs to be up to date to determine if we can scroll. We may be
- // here because of an onLoad event, in which case the final layout hasn't been performed yet.
- m_frame->document()->updateLayoutIgnorePendingStylesheets();
- if (logicalScrollOverflow(direction, granularity, startingNode))
- return true;
- Frame* frame = m_frame;
- FrameView* view = frame->view();
-
- bool scrolled = false;
- if (view && view->logicalScroll(direction, granularity))
- scrolled = true;
-
- if (scrolled)
- return true;
-
- frame = frame->tree()->parent();
+ frame = frame->tree().parent();
if (!frame)
return false;
-
- return frame->eventHandler()->logicalScrollRecursively(direction, granularity, m_frame->ownerElement());
+ return frame->eventHandler().scrollRecursively(direction, granularity, m_frame->ownerElement());
}
IntPoint EventHandler::lastKnownMousePosition() const
@@ -1016,14 +1007,7 @@ IntPoint EventHandler::lastKnownMousePosition() const
return m_lastKnownMousePosition;
}
-Frame* EventHandler::subframeForHitTestResult(const MouseEventWithHitTestResults& hitTestResult)
-{
- if (!hitTestResult.isOverWidget())
- return 0;
- return subframeForTargetNode(hitTestResult.targetNode());
-}
-
-Frame* EventHandler::subframeForTargetNode(Node* node)
+static Frame* subframeForTargetNode(Node* node)
{
if (!node)
return 0;
@@ -1039,6 +1023,13 @@ Frame* EventHandler::subframeForTargetNode(Node* node)
return &toFrameView(widget)->frame();
}
+static Frame* subframeForHitTestResult(const MouseEventWithHitTestResults& hitTestResult)
+{
+ if (!hitTestResult.isOverWidget())
+ return 0;
+ return subframeForTargetNode(hitTestResult.targetNode());
+}
+
static bool isSubmitImage(Node* node)
{
return node && node->hasTagName(inputTag) && toHTMLInputElement(node)->isImageButton();
@@ -1085,9 +1076,49 @@ bool EventHandler::useHandCursor(Node* node, bool isOverLink, bool shiftKey)
return ((isOverLink || isSubmitImage(node)) && (!editable || editableLinkEnabled));
}
-OptionalCursor EventHandler::selectCursor(const MouseEventWithHitTestResults& event, Scrollbar* scrollbar)
+void EventHandler::cursorUpdateTimerFired(Timer<EventHandler>*)
+{
+ ASSERT(m_frame);
+ ASSERT(m_frame->document());
+
+ updateCursor();
+}
+
+void EventHandler::updateCursor()
{
- if (m_resizeLayer && m_resizeLayer->inResizeMode())
+ if (m_mousePositionIsUnknown)
+ return;
+
+ FrameView* view = m_frame->view();
+ if (!view || !view->shouldSetCursor())
+ return;
+
+ RenderView* renderView = view->renderView();
+ if (!renderView)
+ return;
+
+ bool shiftKey;
+ bool ctrlKey;
+ bool altKey;
+ bool metaKey;
+ PlatformKeyboardEvent::getCurrentModifierState(shiftKey, ctrlKey, altKey, metaKey);
+
+ m_frame->document()->updateLayout();
+
+ HitTestRequest request(HitTestRequest::ReadOnly);
+ HitTestResult result(view->windowToContents(m_lastKnownMousePosition));
+ renderView->hitTest(request, result);
+
+ OptionalCursor optionalCursor = selectCursor(result, shiftKey);
+ if (optionalCursor.isCursorChange()) {
+ m_currentMouseCursor = optionalCursor.cursor();
+ view->setCursor(m_currentMouseCursor);
+ }
+}
+
+OptionalCursor EventHandler::selectCursor(const HitTestResult& result, bool shiftKey)
+{
+ if (m_resizeScrollableArea && m_resizeScrollableArea->inResizeMode())
return NoCursorChange;
Page* page = m_frame->page();
@@ -1098,15 +1129,16 @@ OptionalCursor EventHandler::selectCursor(const MouseEventWithHitTestResults& ev
return NoCursorChange;
#endif
- Node* node = event.targetNode();
- RenderObject* renderer = node ? node->renderer() : 0;
+ Node* node = result.targetNode();
+ if (!node)
+ return selectAutoCursor(result, node, iBeamCursor(), shiftKey);
+
+ RenderObject* renderer = node->renderer();
RenderStyle* style = renderer ? renderer->style() : 0;
- bool horizontalText = !style || style->isHorizontalWritingMode();
- const Cursor& iBeam = horizontalText ? iBeamCursor() : verticalTextCursor();
if (renderer) {
Cursor overrideCursor;
- switch (renderer->getCursor(roundedIntPoint(event.localPoint()), overrideCursor)) {
+ switch (renderer->getCursor(roundedIntPoint(result.localPoint()), overrideCursor)) {
case SetCursorBasedOnStyle:
break;
case SetCursor:
@@ -1148,31 +1180,9 @@ OptionalCursor EventHandler::selectCursor(const MouseEventWithHitTestResults& ev
switch (style ? style->cursor() : CURSOR_AUTO) {
case CURSOR_AUTO: {
- bool editable = (node && node->rendererIsEditable());
-
- if (useHandCursor(node, event.isOverLink(), event.event().shiftKey()))
- return handCursor();
-
- bool inResizer = false;
- if (renderer) {
- if (RenderLayer* layer = renderer->enclosingLayer()) {
- if (FrameView* view = m_frame->view())
- inResizer = layer->isPointInResizeControl(view->windowToContents(event.event().position()), ResizerForPointer);
- }
- }
-
- // During selection, use an I-beam no matter what we're over.
- // If a drag may be starting or we're capturing mouse events for a particular node, don't treat this as a selection.
- if (m_mousePressed && m_mouseDownMayStartSelect
- && !m_mouseDownMayStartDrag
- && m_frame->selection().isCaretOrRange()
- && !m_capturingMouseEventsNode) {
- return iBeam;
- }
-
- if ((editable || (renderer && renderer->isText() && node->canStartSelection())) && !inResizer && !scrollbar)
- return iBeam;
- return pointerCursor();
+ bool horizontalText = !style || style->isHorizontalWritingMode();
+ const Cursor& iBeam = horizontalText ? iBeamCursor() : verticalTextCursor();
+ return selectAutoCursor(result, node, iBeam, shiftKey);
}
case CURSOR_CROSS:
return crossCursor();
@@ -1248,6 +1258,36 @@ OptionalCursor EventHandler::selectCursor(const MouseEventWithHitTestResults& ev
return pointerCursor();
}
+OptionalCursor EventHandler::selectAutoCursor(const HitTestResult& result, Node* node, const Cursor& iBeam, bool shiftKey)
+{
+ bool editable = (node && node->rendererIsEditable());
+
+ if (useHandCursor(node, result.isOverLink(), shiftKey))
+ return handCursor();
+
+ bool inResizer = false;
+ RenderObject* renderer = node ? node->renderer() : 0;
+ if (renderer) {
+ if (RenderLayer* layer = renderer->enclosingLayer()) {
+ if (m_frame->view())
+ inResizer = layer->scrollableArea() && layer->scrollableArea()->isPointInResizeControl(result.roundedPointInMainFrame(), ResizerForPointer);
+ }
+ }
+
+ // During selection, use an I-beam no matter what we're over.
+ // If a drag may be starting or we're capturing mouse events for a particular node, don't treat this as a selection.
+ if (m_mousePressed && m_mouseDownMayStartSelect
+ && !m_mouseDownMayStartDrag
+ && m_frame->selection().isCaretOrRange()
+ && !m_capturingMouseEventsNode) {
+ return iBeam;
+ }
+
+ if ((editable || (renderer && renderer->isText() && node->canStartSelection())) && !inResizer && !result.scrollbar())
+ return iBeam;
+ return pointerCursor();
+}
+
static LayoutPoint documentPointForWindowPoint(Frame* frame, const IntPoint& windowPoint)
{
FrameView* view = frame->view();
@@ -1265,7 +1305,7 @@ bool EventHandler::handleMousePressEvent(const PlatformMouseEvent& mouseEvent)
return true;
UserGestureIndicator gestureIndicator(DefinitelyProcessingUserGesture);
- m_frame->tree()->top()->eventHandler()->m_lastMouseDownUserGestureToken = gestureIndicator.currentToken();
+ m_frame->tree().top()->eventHandler().m_lastMouseDownUserGestureToken = gestureIndicator.currentToken();
cancelFakeMouseMoveEvent();
if (m_eventHandlerWillResetCapturingMouseEventsNode)
@@ -1285,7 +1325,10 @@ bool EventHandler::handleMousePressEvent(const PlatformMouseEvent& mouseEvent)
}
m_mouseDownWasInSubframe = false;
- HitTestRequest request(HitTestRequest::Active | HitTestRequest::DisallowShadowContent);
+ HitTestRequest::HitTestRequestType hitType = HitTestRequest::Active | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent;
+ if (mouseEvent.fromTouch())
+ hitType |= HitTestRequest::ReadOnly;
+ HitTestRequest request(hitType);
// Save the document point we generate in case the window coordinate is invalidated by what happens
// when we dispatch the event.
LayoutPoint documentPoint = documentPointForWindowPoint(m_frame, mouseEvent.position());
@@ -1302,7 +1345,7 @@ bool EventHandler::handleMousePressEvent(const PlatformMouseEvent& mouseEvent)
if (subframe && passMousePressEventToSubframe(mev, subframe.get())) {
// Start capturing future events for this frame. We only do this if we didn't clear
// the m_mousePressed flag, which may happen if an AppKit widget entered a modal event loop.
- m_capturesDragging = subframe->eventHandler()->capturesDragging();
+ m_capturesDragging = subframe->eventHandler().capturesDragging();
if (m_mousePressed && m_capturesDragging) {
m_capturingMouseEventsNode = mev.targetNode();
m_eventHandlerWillResetCapturingMouseEventsNode = true;
@@ -1312,10 +1355,10 @@ bool EventHandler::handleMousePressEvent(const PlatformMouseEvent& mouseEvent)
}
#if OS(WIN)
- // We store whether pan scrolling is in progress before calling stopAutoscrollTimer()
+ // We store whether pan scrolling is in progress before calling stopAutoscroll()
// because it will set m_autoscrollType to NoAutoscroll on return.
bool isPanScrollInProgress = panScrollInProgress();
- stopAutoscrollTimer();
+ stopAutoscroll();
if (isPanScrollInProgress) {
// We invalidate the click when exiting pan scrolling so that we don't inadvertently navigate
// away from the current page (e.g. the click was on a hyperlink). See <rdar://problem/6095023>.
@@ -1325,15 +1368,15 @@ bool EventHandler::handleMousePressEvent(const PlatformMouseEvent& mouseEvent)
#endif
m_clickCount = mouseEvent.clickCount();
- m_clickNode = mev.targetNode();
+ m_clickNode = mev.targetNode()->isTextNode() ? mev.targetNode()->parentOrShadowHostNode() : mev.targetNode();
if (FrameView* view = m_frame->view()) {
- RenderLayer* layer = m_clickNode->renderer() ? m_clickNode->renderer()->enclosingLayer() : 0;
+ RenderLayer* layer = mev.targetNode()->renderer() ? mev.targetNode()->renderer()->enclosingLayer() : 0;
IntPoint p = view->windowToContents(mouseEvent.position());
- if (layer && layer->isPointInResizeControl(p, ResizerForPointer)) {
- layer->setInResizeMode(true);
- m_resizeLayer = layer;
- m_offsetFromResizeCorner = layer->offsetFromResizeCorner(p);
+ if (layer && layer->scrollableArea() && layer->scrollableArea()->isPointInResizeControl(p, ResizerForPointer)) {
+ m_resizeScrollableArea = layer->scrollableArea();
+ m_resizeScrollableArea->setInResizeMode(true);
+ m_offsetFromResizeCorner = m_resizeScrollableArea->offsetFromResizeCorner(p);
invalidateClick();
return true;
}
@@ -1341,14 +1384,14 @@ bool EventHandler::handleMousePressEvent(const PlatformMouseEvent& mouseEvent)
m_frame->selection().setCaretBlinkingSuspended(true);
- bool swallowEvent = !dispatchMouseEvent(eventNames().mousedownEvent, mev.targetNode(), true, m_clickCount, mouseEvent, true);
+ bool swallowEvent = !dispatchMouseEvent(EventTypeNames::mousedown, mev.targetNode(), true, m_clickCount, mouseEvent, true);
m_capturesDragging = !swallowEvent || mev.scrollbar();
// If the hit testing originally determined the event was in a scrollbar, refetch the MouseEventWithHitTestResults
// in case the scrollbar widget was destroyed when the mouse event was handled.
if (mev.scrollbar()) {
const bool wasLastScrollBar = mev.scrollbar() == m_lastScrollbarUnderMouse.get();
- HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::DisallowShadowContent);
+ HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent);
mev = m_frame->document()->prepareMouseEvent(request, documentPoint, mouseEvent);
if (wasLastScrollBar && mev.scrollbar() != m_lastScrollbarUnderMouse.get())
m_lastScrollbarUnderMouse = 0;
@@ -1364,7 +1407,7 @@ bool EventHandler::handleMousePressEvent(const PlatformMouseEvent& mouseEvent)
passMousePressEventToScrollbar(mev, scrollbar);
} else {
if (shouldRefetchEventTarget(mev)) {
- HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::DisallowShadowContent);
+ HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent);
mev = m_frame->document()->prepareMouseEvent(request, documentPoint, mouseEvent);
}
@@ -1469,6 +1512,8 @@ bool EventHandler::handleMouseMoveOrLeaveEvent(const PlatformMouseEvent& mouseEv
if (m_hoverTimer.isActive())
m_hoverTimer.stop();
+ m_cursorUpdateTimer.stop();
+
cancelFakeMouseMoveEvent();
if (m_svgPan) {
@@ -1477,7 +1522,7 @@ bool EventHandler::handleMouseMoveOrLeaveEvent(const PlatformMouseEvent& mouseEv
}
if (m_frameSetBeingResized)
- return !dispatchMouseEvent(eventNames().mousemoveEvent, m_frameSetBeingResized.get(), false, 0, mouseEvent, false);
+ return !dispatchMouseEvent(EventTypeNames::mousemove, m_frameSetBeingResized.get(), false, 0, mouseEvent, false);
// Send events right to a scrollbar if the mouse is pressed.
if (m_lastScrollbarUnderMouse && m_mousePressed) {
@@ -1485,7 +1530,10 @@ bool EventHandler::handleMouseMoveOrLeaveEvent(const PlatformMouseEvent& mouseEv
return true;
}
- HitTestRequest::HitTestRequestType hitType = HitTestRequest::Move | HitTestRequest::DisallowShadowContent;
+ HitTestRequest::HitTestRequestType hitType = HitTestRequest::Move | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent;
+ if (mouseEvent.fromTouch())
+ hitType |= HitTestRequest::ReadOnly;
+
if (m_mousePressed)
hitType |= HitTestRequest::Active;
else if (onlyUpdateScrollbars) {
@@ -1506,8 +1554,8 @@ bool EventHandler::handleMouseMoveOrLeaveEvent(const PlatformMouseEvent& mouseEv
Scrollbar* scrollbar = 0;
- if (m_resizeLayer && m_resizeLayer->inResizeMode())
- m_resizeLayer->resize(mouseEvent, m_offsetFromResizeCorner);
+ if (m_resizeScrollableArea && m_resizeScrollableArea->inResizeMode())
+ m_resizeScrollableArea->resize(mouseEvent, m_offsetFromResizeCorner);
else {
if (FrameView* view = m_frame->view())
scrollbar = view->scrollbarAtPoint(mouseEvent.position());
@@ -1524,7 +1572,7 @@ bool EventHandler::handleMouseMoveOrLeaveEvent(const PlatformMouseEvent& mouseEv
RefPtr<Frame> newSubframe = m_capturingMouseEventsNode.get() ? subframeForTargetNode(m_capturingMouseEventsNode.get()) : subframeForHitTestResult(mev);
// We want mouseouts to happen first, from the inside out. First send a move event to the last subframe so that it will fire mouseouts.
- if (m_lastMouseMoveEventSubframe && m_lastMouseMoveEventSubframe->tree()->isDescendantOf(m_frame) && m_lastMouseMoveEventSubframe != newSubframe)
+ if (m_lastMouseMoveEventSubframe && m_lastMouseMoveEventSubframe->tree().isDescendantOf(m_frame) && m_lastMouseMoveEventSubframe != newSubframe)
passMouseMoveEventToSubframe(mev, m_lastMouseMoveEventSubframe.get());
if (newSubframe) {
@@ -1539,7 +1587,7 @@ bool EventHandler::handleMouseMoveOrLeaveEvent(const PlatformMouseEvent& mouseEv
if (scrollbar && !m_mousePressed)
scrollbar->mouseMoved(mouseEvent); // Handle hover effects on platforms that support visual feedback on scrollbar hovering.
if (FrameView* view = m_frame->view()) {
- OptionalCursor optionalCursor = selectCursor(mev, scrollbar);
+ OptionalCursor optionalCursor = selectCursor(mev.hitTestResult(), mouseEvent.shiftKey());
if (optionalCursor.isCursorChange()) {
m_currentMouseCursor = optionalCursor.cursor();
view->setCursor(m_currentMouseCursor);
@@ -1552,7 +1600,7 @@ bool EventHandler::handleMouseMoveOrLeaveEvent(const PlatformMouseEvent& mouseEv
if (swallowEvent)
return true;
- swallowEvent = !dispatchMouseEvent(eventNames().mousemoveEvent, mev.targetNode(), false, 0, mouseEvent, true);
+ swallowEvent = !dispatchMouseEvent(EventTypeNames::mousemove, mev.targetNode(), false, 0, mouseEvent, true);
if (!swallowEvent)
swallowEvent = handleMouseDraggedEvent(mev);
@@ -1565,28 +1613,13 @@ void EventHandler::invalidateClick()
m_clickNode = 0;
}
-inline static bool mouseIsReleasedOnPressedElement(Node* targetNode, Node* clickNode)
+static Node* parentForClickEvent(const Node& node)
{
- if (targetNode == clickNode)
- return true;
-
- if (!targetNode)
- return false;
-
- ShadowRoot* containingShadowRoot = targetNode->containingShadowRoot();
- if (!containingShadowRoot)
- return false;
-
- // FIXME: When an element in UA ShadowDOM (e.g. inner element in <input>) is clicked,
- // we assume that the host element is clicked. This is necessary for implementing <input type="range"> etc.
- // However, we should not check ShadowRoot type basically.
- // https://bugs.webkit.org/show_bug.cgi?id=108047
- if (containingShadowRoot->type() != ShadowRoot::UserAgentShadowRoot)
- return false;
-
- Node* adjustedTargetNode = targetNode->shadowHost();
- Node* adjustedClickNode = clickNode ? clickNode->shadowHost() : 0;
- return adjustedTargetNode == adjustedClickNode;
+ // IE doesn't dispatch click events for mousedown/mouseup events across form
+ // controls.
+ if (node.isHTMLElement() && toHTMLElement(node).isInteractiveContent())
+ return 0;
+ return node.parentOrShadowHostNode();
}
bool EventHandler::handleMouseReleaseEvent(const PlatformMouseEvent& mouseEvent)
@@ -1601,14 +1634,14 @@ bool EventHandler::handleMouseReleaseEvent(const PlatformMouseEvent& mouseEvent)
OwnPtr<UserGestureIndicator> gestureIndicator;
- if (m_frame->tree()->top()->eventHandler()->m_lastMouseDownUserGestureToken)
- gestureIndicator = adoptPtr(new UserGestureIndicator(m_frame->tree()->top()->eventHandler()->m_lastMouseDownUserGestureToken.release()));
+ if (m_frame->tree().top()->eventHandler().m_lastMouseDownUserGestureToken)
+ gestureIndicator = adoptPtr(new UserGestureIndicator(m_frame->tree().top()->eventHandler().m_lastMouseDownUserGestureToken.release()));
else
gestureIndicator = adoptPtr(new UserGestureIndicator(DefinitelyProcessingUserGesture));
#if OS(WIN)
if (Page* page = m_frame->page())
- page->handleMouseReleaseForPanScrolling(m_frame, mouseEvent);
+ page->autoscrollController().handleMouseReleaseForPanScrolling(m_frame, mouseEvent);
#endif
m_mousePressed = false;
@@ -1621,17 +1654,20 @@ bool EventHandler::handleMouseReleaseEvent(const PlatformMouseEvent& mouseEvent)
}
if (m_frameSetBeingResized)
- return !dispatchMouseEvent(eventNames().mouseupEvent, m_frameSetBeingResized.get(), true, m_clickCount, mouseEvent, false);
+ return !dispatchMouseEvent(EventTypeNames::mouseup, m_frameSetBeingResized.get(), true, m_clickCount, mouseEvent, false);
if (m_lastScrollbarUnderMouse) {
invalidateClick();
m_lastScrollbarUnderMouse->mouseUp(mouseEvent);
bool cancelable = true;
bool setUnder = false;
- return !dispatchMouseEvent(eventNames().mouseupEvent, m_lastNodeUnderMouse.get(), cancelable, m_clickCount, mouseEvent, setUnder);
+ return !dispatchMouseEvent(EventTypeNames::mouseup, m_lastNodeUnderMouse.get(), cancelable, m_clickCount, mouseEvent, setUnder);
}
- HitTestRequest request(HitTestRequest::Release | HitTestRequest::DisallowShadowContent);
+ HitTestRequest::HitTestRequestType hitType = HitTestRequest::Release | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent;
+ if (mouseEvent.fromTouch())
+ hitType |= HitTestRequest::ReadOnly;
+ HitTestRequest request(hitType);
MouseEventWithHitTestResults mev = prepareMouseEvent(request, mouseEvent);
Frame* subframe = m_capturingMouseEventsNode.get() ? subframeForTargetNode(m_capturingMouseEventsNode.get()) : subframeForHitTestResult(mev);
if (m_eventHandlerWillResetCapturingMouseEventsNode)
@@ -1639,7 +1675,7 @@ bool EventHandler::handleMouseReleaseEvent(const PlatformMouseEvent& mouseEvent)
if (subframe && passMouseReleaseEventToSubframe(mev, subframe))
return true;
- bool swallowMouseUpEvent = !dispatchMouseEvent(eventNames().mouseupEvent, mev.targetNode(), true, m_clickCount, mouseEvent, false);
+ bool swallowMouseUpEvent = !dispatchMouseEvent(EventTypeNames::mouseup, mev.targetNode(), true, m_clickCount, mouseEvent, false);
bool contextMenuEvent = mouseEvent.button() == RightButton;
#if OS(MACOSX)
@@ -1648,11 +1684,15 @@ bool EventHandler::handleMouseReleaseEvent(const PlatformMouseEvent& mouseEvent)
contextMenuEvent = true;
#endif
- bool swallowClickEvent = m_clickCount > 0 && !contextMenuEvent && mouseIsReleasedOnPressedElement(mev.targetNode(), m_clickNode.get()) && !dispatchMouseEvent(eventNames().clickEvent, mev.targetNode(), true, m_clickCount, mouseEvent, true);
+ bool swallowClickEvent = false;
+ if (m_clickCount > 0 && !contextMenuEvent && mev.targetNode() && m_clickNode) {
+ if (Node* clickTargetNode = mev.targetNode()->commonAncestor(*m_clickNode, parentForClickEvent))
+ swallowClickEvent = !dispatchMouseEvent(EventTypeNames::click, clickTargetNode, true, m_clickCount, mouseEvent, true);
+ }
- if (m_resizeLayer) {
- m_resizeLayer->setInResizeMode(false);
- m_resizeLayer = 0;
+ if (m_resizeScrollableArea) {
+ m_resizeScrollableArea->setInResizeMode(false);
+ m_resizeScrollableArea = 0;
}
bool swallowMouseReleaseEvent = false;
@@ -1689,7 +1729,7 @@ bool EventHandler::handlePasteGlobalSelection(const PlatformMouseEvent& mouseEve
return false;
Frame* focusFrame = m_frame->page()->focusController().focusedOrMainFrame();
// Do not paste here if the focus was moved somewhere else.
- if (m_frame == focusFrame && m_frame->editor().client().supportsGlobalSelection())
+ if (m_frame == focusFrame && m_frame->editor().behavior().supportsGlobalSelection())
return m_frame->editor().command("PasteGlobalSelection").execute();
return false;
@@ -1706,7 +1746,7 @@ bool EventHandler::dispatchDragEvent(const AtomicString& eventType, Node* dragTa
view->resetDeferredRepaintDelay();
RefPtr<MouseEvent> me = MouseEvent::create(eventType,
- true, true, m_frame->document()->defaultView(),
+ true, true, m_frame->document()->domWindow(),
0, event.globalPosition().x(), event.globalPosition().y(), event.position().x(), event.position().y(),
event.movementDelta().x(), event.movementDelta().y(),
event.ctrlKey(), event.altKey(), event.shiftKey(), event.metaKey(),
@@ -1733,12 +1773,12 @@ static bool findDropZone(Node* target, Clipboard* clipboard)
Element* element = target->isElementNode() ? toElement(target) : target->parentElement();
for (; element; element = element->parentElement()) {
bool matched = false;
- String dropZoneStr = element->fastGetAttribute(webkitdropzoneAttr);
+ AtomicString dropZoneStr = element->fastGetAttribute(webkitdropzoneAttr);
if (dropZoneStr.isEmpty())
continue;
- dropZoneStr.makeLower();
+ dropZoneStr = dropZoneStr.lower();
SpaceSplitString keywords(dropZoneStr, false);
if (keywords.isNull())
@@ -1771,16 +1811,16 @@ bool EventHandler::updateDragAndDrop(const PlatformMouseEvent& event, Clipboard*
if (!m_frame->view())
return false;
- HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::DisallowShadowContent);
+ HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent);
MouseEventWithHitTestResults mev = prepareMouseEvent(request, event);
// Drag events should never go to text nodes (following IE, and proper mouseover/out dispatch)
RefPtr<Node> newTarget = mev.targetNode();
if (newTarget && newTarget->isTextNode())
- newTarget = EventPathWalker::parent(newTarget.get());
+ newTarget = EventPath::parent(newTarget.get());
- if (Page* page = m_frame->page())
- page->updateDragAndDrop(newTarget.get(), event.position(), event.timestamp());
+ if (AutoscrollController* controller = autoscrollController())
+ controller->updateDragAndDrop(newTarget.get(), event.position(), event.timestamp());
if (m_dragTarget != newTarget) {
// FIXME: this ordering was explicitly chosen to match WinIE. However,
@@ -1791,23 +1831,23 @@ bool EventHandler::updateDragAndDrop(const PlatformMouseEvent& event, Clipboard*
Frame* targetFrame;
if (targetIsFrame(newTarget.get(), targetFrame)) {
if (targetFrame)
- accept = targetFrame->eventHandler()->updateDragAndDrop(event, clipboard);
+ accept = targetFrame->eventHandler().updateDragAndDrop(event, clipboard);
} else if (newTarget) {
// As per section 7.9.4 of the HTML 5 spec., we must always fire a drag event before firing a dragenter, dragleave, or dragover event.
if (dragState().m_dragSrc) {
// for now we don't care if event handler cancels default behavior, since there is none
- dispatchDragSrcEvent(eventNames().dragEvent, event);
+ dispatchDragSrcEvent(EventTypeNames::drag, event);
}
- accept = dispatchDragEvent(eventNames().dragenterEvent, newTarget.get(), event, clipboard);
+ accept = dispatchDragEvent(EventTypeNames::dragenter, newTarget.get(), event, clipboard);
if (!accept)
accept = findDropZone(newTarget.get(), clipboard);
}
if (targetIsFrame(m_dragTarget.get(), targetFrame)) {
if (targetFrame)
- accept = targetFrame->eventHandler()->updateDragAndDrop(event, clipboard);
+ accept = targetFrame->eventHandler().updateDragAndDrop(event, clipboard);
} else if (m_dragTarget)
- dispatchDragEvent(eventNames().dragleaveEvent, m_dragTarget.get(), event, clipboard);
+ dispatchDragEvent(EventTypeNames::dragleave, m_dragTarget.get(), event, clipboard);
if (newTarget) {
// We do not explicitly call dispatchDragEvent here because it could ultimately result in the appearance that
@@ -1818,14 +1858,14 @@ bool EventHandler::updateDragAndDrop(const PlatformMouseEvent& event, Clipboard*
Frame* targetFrame;
if (targetIsFrame(newTarget.get(), targetFrame)) {
if (targetFrame)
- accept = targetFrame->eventHandler()->updateDragAndDrop(event, clipboard);
+ accept = targetFrame->eventHandler().updateDragAndDrop(event, clipboard);
} else if (newTarget) {
// Note, when dealing with sub-frames, we may need to fire only a dragover event as a drag event may have been fired earlier.
if (!m_shouldOnlyFireDragOverEvent && dragState().m_dragSrc) {
// for now we don't care if event handler cancels default behavior, since there is none
- dispatchDragSrcEvent(eventNames().dragEvent, event);
+ dispatchDragSrcEvent(EventTypeNames::drag, event);
}
- accept = dispatchDragEvent(eventNames().dragoverEvent, newTarget.get(), event, clipboard);
+ accept = dispatchDragEvent(EventTypeNames::dragover, newTarget.get(), event, clipboard);
if (!accept)
accept = findDropZone(newTarget.get(), clipboard);
m_shouldOnlyFireDragOverEvent = false;
@@ -1841,11 +1881,11 @@ void EventHandler::cancelDragAndDrop(const PlatformMouseEvent& event, Clipboard*
Frame* targetFrame;
if (targetIsFrame(m_dragTarget.get(), targetFrame)) {
if (targetFrame)
- targetFrame->eventHandler()->cancelDragAndDrop(event, clipboard);
+ targetFrame->eventHandler().cancelDragAndDrop(event, clipboard);
} else if (m_dragTarget.get()) {
if (dragState().m_dragSrc)
- dispatchDragSrcEvent(eventNames().dragEvent, event);
- dispatchDragEvent(eventNames().dragleaveEvent, m_dragTarget.get(), event, clipboard);
+ dispatchDragSrcEvent(EventTypeNames::drag, event);
+ dispatchDragEvent(EventTypeNames::dragleave, m_dragTarget.get(), event, clipboard);
}
clearDragState();
}
@@ -1856,16 +1896,16 @@ bool EventHandler::performDragAndDrop(const PlatformMouseEvent& event, Clipboard
bool preventedDefault = false;
if (targetIsFrame(m_dragTarget.get(), targetFrame)) {
if (targetFrame)
- preventedDefault = targetFrame->eventHandler()->performDragAndDrop(event, clipboard);
+ preventedDefault = targetFrame->eventHandler().performDragAndDrop(event, clipboard);
} else if (m_dragTarget.get())
- preventedDefault = dispatchDragEvent(eventNames().dropEvent, m_dragTarget.get(), event, clipboard);
+ preventedDefault = dispatchDragEvent(EventTypeNames::drop, m_dragTarget.get(), event, clipboard);
clearDragState();
return preventedDefault;
}
void EventHandler::clearDragState()
{
- stopAutoscrollTimer();
+ stopAutoscroll();
m_dragTarget = 0;
m_capturingMouseEventsNode = 0;
m_shouldOnlyFireDragOverEvent = false;
@@ -1911,7 +1951,7 @@ void EventHandler::updateMouseEventTargetNode(Node* targetNode, const PlatformMo
else {
// If the target node is a text node, dispatch on the parent node - rdar://4196646
if (result && result->isTextNode())
- result = EventPathWalker::parent(result);
+ result = EventPath::parent(result);
}
m_nodeUnderMouse = result;
m_instanceUnderMouse = instanceAssociatedWithShadowTreeElement(result);
@@ -1953,7 +1993,7 @@ void EventHandler::updateMouseEventTargetNode(Node* targetNode, const PlatformMo
RenderLayer* layerForNodeUnderMouse = layerForNode(m_nodeUnderMouse.get());
Page* page = m_frame->page();
- if (m_lastNodeUnderMouse && (!m_nodeUnderMouse || &m_nodeUnderMouse->document() != m_frame->document())) {
+ if (m_lastNodeUnderMouse && (!m_nodeUnderMouse || m_nodeUnderMouse->document() != m_frame->document())) {
// The mouse has moved between frames.
if (Frame* frame = m_lastNodeUnderMouse->document().frame()) {
if (FrameView* frameView = frame->view())
@@ -1965,7 +2005,7 @@ void EventHandler::updateMouseEventTargetNode(Node* targetNode, const PlatformMo
scrollableAreaForLastNode->mouseExitedContentArea();
}
- if (m_nodeUnderMouse && (!m_lastNodeUnderMouse || &m_lastNodeUnderMouse->document() != m_frame->document())) {
+ if (m_nodeUnderMouse && (!m_lastNodeUnderMouse || m_lastNodeUnderMouse->document() != m_frame->document())) {
// The mouse has moved between frames.
if (Frame* frame = m_nodeUnderMouse->document().frame()) {
if (FrameView* frameView = frame->view())
@@ -1977,7 +2017,7 @@ void EventHandler::updateMouseEventTargetNode(Node* targetNode, const PlatformMo
scrollableAreaForNodeUnderMouse->mouseEnteredContentArea();
}
- if (m_lastNodeUnderMouse && &m_lastNodeUnderMouse->document() != m_frame->document()) {
+ if (m_lastNodeUnderMouse && m_lastNodeUnderMouse->document() != m_frame->document()) {
m_lastNodeUnderMouse = 0;
m_lastScrollbarUnderMouse = 0;
m_lastInstanceUnderMouse = 0;
@@ -1986,10 +2026,10 @@ void EventHandler::updateMouseEventTargetNode(Node* targetNode, const PlatformMo
if (m_lastNodeUnderMouse != m_nodeUnderMouse) {
// send mouseout event to the old node
if (m_lastNodeUnderMouse)
- m_lastNodeUnderMouse->dispatchMouseEvent(mouseEvent, eventNames().mouseoutEvent, 0, m_nodeUnderMouse.get());
+ m_lastNodeUnderMouse->dispatchMouseEvent(mouseEvent, EventTypeNames::mouseout, 0, m_nodeUnderMouse.get());
// send mouseover event to the new node
if (m_nodeUnderMouse)
- m_nodeUnderMouse->dispatchMouseEvent(mouseEvent, eventNames().mouseoverEvent, 0, m_lastNodeUnderMouse.get());
+ m_nodeUnderMouse->dispatchMouseEvent(mouseEvent, EventTypeNames::mouseover, 0, m_lastNodeUnderMouse.get());
}
m_lastNodeUnderMouse = m_nodeUnderMouse;
m_lastInstanceUnderMouse = instanceAssociatedWithShadowTreeElement(m_nodeUnderMouse.get());
@@ -2008,7 +2048,7 @@ bool EventHandler::dispatchMouseEvent(const AtomicString& eventType, Node* targe
if (m_nodeUnderMouse)
swallowEvent = !(m_nodeUnderMouse->dispatchMouseEvent(mouseEvent, eventType, clickCount));
- if (swallowEvent || eventType != eventNames().mousedownEvent)
+ if (swallowEvent || eventType != EventTypeNames::mousedown)
return !swallowEvent;
// If clicking on a frame scrollbar, do not mess up with content focus.
@@ -2022,7 +2062,7 @@ bool EventHandler::dispatchMouseEvent(const AtomicString& eventType, Node* targe
Element* element = 0;
if (m_nodeUnderMouse)
- element = m_nodeUnderMouse->isElementNode() ? toElement(m_nodeUnderMouse.get()) : m_nodeUnderMouse->parentOrShadowHostElement();
+ element = m_nodeUnderMouse->isElementNode() ? toElement(m_nodeUnderMouse) : m_nodeUnderMouse->parentOrShadowHostElement();
for (; element; element = element->parentOrShadowHostElement()) {
if (element->isFocusable() && element->focused())
return !swallowEvent;
@@ -2070,7 +2110,7 @@ bool EventHandler::dispatchMouseEvent(const AtomicString& eventType, Node* targe
bool EventHandler::isInsideScrollbar(const IntPoint& windowPoint) const
{
if (RenderView* renderView = m_frame->contentRenderer()) {
- HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::DisallowShadowContent);
+ HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent);
HitTestResult result(windowPoint);
renderView->hitTest(request, result);
return result.scrollbar();
@@ -2082,8 +2122,6 @@ bool EventHandler::isInsideScrollbar(const IntPoint& windowPoint) const
bool EventHandler::shouldTurnVerticalTicksIntoHorizontal(const HitTestResult& result, const PlatformWheelEvent& event) const
{
#if OS(ANDROID) || OS(MACOSX) || OS(WIN)
- UNUSED_PARAM(result);
- UNUSED_PARAM(event);
return false;
#else
// GTK+ must scroll horizontally if the mouse pointer is on top of the
@@ -2112,16 +2150,19 @@ bool EventHandler::handleWheelEvent(const PlatformWheelEvent& e)
if (!view)
return false;
+ if (handleWheelEventAsEmulatedGesture(e))
+ return true;
+
LayoutPoint vPoint = view->windowToContents(e.position());
- HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::DisallowShadowContent);
+ HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent);
HitTestResult result(vPoint);
doc->renderView()->hitTest(request, result);
Node* node = result.innerNode();
// Wheel events should not dispatch to text nodes.
if (node && node->isTextNode())
- node = EventPathWalker::parent(node);
+ node = EventPath::parent(node);
bool isOverWidget;
if (e.useLatchedEventNode()) {
@@ -2183,18 +2224,20 @@ void EventHandler::defaultWheelEventHandler(Node* startNode, WheelEvent* wheelEv
// Break up into two scrolls if we need to. Diagonal movement on
// a MacBook pro is an example of a 2-dimensional mouse wheel event (where both deltaX and deltaY can be set).
- if (scrollNode(wheelEvent->deltaX(), granularity, ScrollRight, ScrollLeft, startNode, &stopNode))
+ if (scrollNode(wheelEvent->deltaX(), granularity, ScrollRight, startNode, &stopNode, roundedIntPoint(wheelEvent->absoluteLocation())))
wheelEvent->setDefaultHandled();
- if (scrollNode(wheelEvent->deltaY(), granularity, ScrollDown, ScrollUp, startNode, &stopNode))
+ if (scrollNode(wheelEvent->deltaY(), granularity, ScrollDown, startNode, &stopNode, roundedIntPoint(wheelEvent->absoluteLocation())))
wheelEvent->setDefaultHandled();
if (!m_latchedWheelEventNode)
m_previousWheelScrolledNode = stopNode;
}
-bool EventHandler::handleGestureTapDown()
+bool EventHandler::handleGestureShowPress()
{
+ m_lastShowPressTimestamp = WTF::currentTime();
+
FrameView* view = m_frame->view();
if (!view)
return false;
@@ -2214,37 +2257,80 @@ bool EventHandler::handleGestureTapDown()
bool EventHandler::handleGestureEvent(const PlatformGestureEvent& gestureEvent)
{
+ IntPoint adjustedPoint = gestureEvent.position();
+ RefPtr<Frame> subframe = 0;
+ switch (gestureEvent.type()) {
+ case PlatformEvent::GestureScrollBegin:
+ case PlatformEvent::GestureScrollUpdate:
+ case PlatformEvent::GestureScrollUpdateWithoutPropagation:
+ case PlatformEvent::GestureScrollEnd:
+ case PlatformEvent::GestureFlingStart:
+ // Handle directly in main frame
+ break;
+
+ case PlatformEvent::GestureTap:
+ case PlatformEvent::GestureTapUnconfirmed:
+ case PlatformEvent::GestureTapDown:
+ case PlatformEvent::GestureShowPress:
+ case PlatformEvent::GestureTapDownCancel:
+ case PlatformEvent::GestureTwoFingerTap:
+ case PlatformEvent::GestureLongPress:
+ case PlatformEvent::GestureLongTap:
+ case PlatformEvent::GesturePinchBegin:
+ case PlatformEvent::GesturePinchEnd:
+ case PlatformEvent::GesturePinchUpdate:
+ adjustGesturePosition(gestureEvent, adjustedPoint);
+ subframe = getSubFrameForGestureEvent(adjustedPoint, gestureEvent);
+ if (subframe)
+ return subframe->eventHandler().handleGestureEvent(gestureEvent);
+ break;
+
+ default:
+ ASSERT_NOT_REACHED();
+ }
+
Node* eventTarget = 0;
Scrollbar* scrollbar = 0;
if (gestureEvent.type() == PlatformEvent::GestureScrollEnd
|| gestureEvent.type() == PlatformEvent::GestureScrollUpdate
- || gestureEvent.type() == PlatformEvent::GestureScrollUpdateWithoutPropagation) {
+ || gestureEvent.type() == PlatformEvent::GestureScrollUpdateWithoutPropagation
+ || gestureEvent.type() == PlatformEvent::GestureFlingStart) {
scrollbar = m_scrollbarHandlingScrollGesture.get();
eventTarget = m_scrollGestureHandlingNode.get();
}
- IntPoint adjustedPoint = gestureEvent.position();
HitTestRequest::HitTestRequestType hitType = HitTestRequest::TouchEvent;
- if (gestureEvent.type() == PlatformEvent::GestureTapDown ||
- gestureEvent.type() == PlatformEvent::GestureTapUnconfirmed) {
- adjustGesturePosition(gestureEvent, adjustedPoint);
+ double activeInterval = 0;
+ bool shouldKeepActiveForMinInterval = false;
+ if (gestureEvent.type() == PlatformEvent::GestureShowPress
+ || gestureEvent.type() == PlatformEvent::GestureTapUnconfirmed) {
hitType |= HitTestRequest::Active;
- } else if (gestureEvent.type() == PlatformEvent::GestureTapDownCancel)
+ } else if (gestureEvent.type() == PlatformEvent::GestureTapDownCancel) {
hitType |= HitTestRequest::Release;
- else if (gestureEvent.type() == PlatformEvent::GestureTap) {
- // The mouseup event synthesized for this gesture will clear the active state of the
- // targeted node, so performing a ReadOnly hit test here is fine.
- hitType |= HitTestRequest::ReadOnly;
+ // A TapDownCancel received when no element is active shouldn't really be changing hover state.
+ if (!m_frame->document()->activeElement())
+ hitType |= HitTestRequest::ReadOnly;
+ } else if (gestureEvent.type() == PlatformEvent::GestureTap) {
+ hitType |= HitTestRequest::Release;
+ // If the Tap is received very shortly after ShowPress, we want to delay clearing
+ // of the active state so that it's visible to the user for at least one frame.
+ activeInterval = WTF::currentTime() - m_lastShowPressTimestamp;
+ shouldKeepActiveForMinInterval = m_lastShowPressTimestamp && activeInterval < minimumActiveInterval;
+ if (shouldKeepActiveForMinInterval)
+ hitType |= HitTestRequest::ReadOnly;
}
else
hitType |= HitTestRequest::Active | HitTestRequest::ReadOnly;
- if (!shouldGesturesTriggerActive())
- hitType |= HitTestRequest::ReadOnly;
-
if ((!scrollbar && !eventTarget) || !(hitType & HitTestRequest::ReadOnly)) {
IntPoint hitTestPoint = m_frame->view()->windowToContents(adjustedPoint);
HitTestResult result = hitTestResultAtPoint(hitTestPoint, hitType | HitTestRequest::AllowFrameScrollbars);
+
+ if (shouldKeepActiveForMinInterval) {
+ m_lastDeferredTapElement = result.innerElement();
+ m_activeIntervalTimer.startOneShot(minimumActiveInterval - activeInterval);
+ }
+
eventTarget = result.targetNode();
if (!scrollbar) {
FrameView* view = m_frame->view();
@@ -2256,10 +2342,13 @@ bool EventHandler::handleGestureEvent(const PlatformGestureEvent& gestureEvent)
if (scrollbar) {
bool eventSwallowed = scrollbar->gestureEvent(gestureEvent);
- if (gestureEvent.type() == PlatformEvent::GestureScrollBegin && eventSwallowed)
+ if (gestureEvent.type() == PlatformEvent::GestureTapDown && eventSwallowed) {
m_scrollbarHandlingScrollGesture = scrollbar;
- else if (gestureEvent.type() == PlatformEvent::GestureScrollEnd || !eventSwallowed)
+ } else if (gestureEvent.type() == PlatformEvent::GestureScrollEnd
+ || gestureEvent.type() == PlatformEvent::GestureFlingStart
+ || !eventSwallowed) {
m_scrollbarHandlingScrollGesture = 0;
+ }
if (eventSwallowed)
return true;
@@ -2293,20 +2382,22 @@ bool EventHandler::handleGestureEvent(const PlatformGestureEvent& gestureEvent)
case PlatformEvent::GestureScrollEnd:
return handleGestureScrollEnd(gestureEvent);
case PlatformEvent::GestureTap:
- return handleGestureTap(gestureEvent);
- case PlatformEvent::GestureTapDown:
- return handleGestureTapDown();
+ return handleGestureTap(gestureEvent, adjustedPoint);
+ case PlatformEvent::GestureShowPress:
+ return handleGestureShowPress();
case PlatformEvent::GestureLongPress:
- return handleGestureLongPress(gestureEvent);
+ return handleGestureLongPress(gestureEvent, adjustedPoint);
case PlatformEvent::GestureLongTap:
- return handleGestureLongTap(gestureEvent);
+ return handleGestureLongTap(gestureEvent, adjustedPoint);
case PlatformEvent::GestureTwoFingerTap:
- return handleGestureTwoFingerTap(gestureEvent);
+ return handleGestureTwoFingerTap(gestureEvent, adjustedPoint);
+ case PlatformEvent::GestureTapDown:
case PlatformEvent::GesturePinchBegin:
case PlatformEvent::GesturePinchEnd:
case PlatformEvent::GesturePinchUpdate:
case PlatformEvent::GestureTapDownCancel:
case PlatformEvent::GestureTapUnconfirmed:
+ case PlatformEvent::GestureFlingStart:
break;
default:
ASSERT_NOT_REACHED();
@@ -2315,45 +2406,42 @@ bool EventHandler::handleGestureEvent(const PlatformGestureEvent& gestureEvent)
return false;
}
-bool EventHandler::handleGestureTap(const PlatformGestureEvent& gestureEvent)
+bool EventHandler::handleGestureTap(const PlatformGestureEvent& gestureEvent, const IntPoint& adjustedPoint)
{
// FIXME: Refactor this code to not hit test multiple times. We use the adjusted position to ensure that the correct node is targeted by the later redundant hit tests.
- IntPoint adjustedPoint = gestureEvent.position();
- adjustGesturePosition(gestureEvent, adjustedPoint);
+
+ unsigned modifierFlags = 0;
+ if (gestureEvent.altKey())
+ modifierFlags |= PlatformEvent::AltKey;
+ if (gestureEvent.ctrlKey())
+ modifierFlags |= PlatformEvent::CtrlKey;
+ if (gestureEvent.metaKey())
+ modifierFlags |= PlatformEvent::MetaKey;
+ if (gestureEvent.shiftKey())
+ modifierFlags |= PlatformEvent::ShiftKey;
+ PlatformEvent::Modifiers modifiers = static_cast<PlatformEvent::Modifiers>(modifierFlags);
PlatformMouseEvent fakeMouseMove(adjustedPoint, gestureEvent.globalPosition(),
NoButton, PlatformEvent::MouseMoved, /* clickCount */ 0,
- gestureEvent.shiftKey(), gestureEvent.ctrlKey(), gestureEvent.altKey(), gestureEvent.metaKey(), gestureEvent.timestamp());
+ modifiers, PlatformMouseEvent::FromTouch, gestureEvent.timestamp());
handleMouseMoveEvent(fakeMouseMove);
- int tapCount = 1;
- // FIXME: deletaX is overloaded to mean different things for different gestures.
- // http://wkb.ug/93123
- if (gestureEvent.deltaX() > 0)
- tapCount = static_cast<int>(gestureEvent.deltaX());
-
bool defaultPrevented = false;
PlatformMouseEvent fakeMouseDown(adjustedPoint, gestureEvent.globalPosition(),
- LeftButton, PlatformEvent::MousePressed, tapCount,
- gestureEvent.shiftKey(), gestureEvent.ctrlKey(), gestureEvent.altKey(), gestureEvent.metaKey(), gestureEvent.timestamp());
+ LeftButton, PlatformEvent::MousePressed, gestureEvent.tapCount(),
+ modifiers, PlatformMouseEvent::FromTouch, gestureEvent.timestamp());
defaultPrevented |= handleMousePressEvent(fakeMouseDown);
PlatformMouseEvent fakeMouseUp(adjustedPoint, gestureEvent.globalPosition(),
- LeftButton, PlatformEvent::MouseReleased, tapCount,
- gestureEvent.shiftKey(), gestureEvent.ctrlKey(), gestureEvent.altKey(), gestureEvent.metaKey(), gestureEvent.timestamp());
+ LeftButton, PlatformEvent::MouseReleased, gestureEvent.tapCount(),
+ modifiers, PlatformMouseEvent::FromTouch, gestureEvent.timestamp());
defaultPrevented |= handleMouseReleaseEvent(fakeMouseUp);
return defaultPrevented;
}
-bool EventHandler::handleGestureLongPress(const PlatformGestureEvent& gestureEvent)
+bool EventHandler::handleGestureLongPress(const PlatformGestureEvent& gestureEvent, const IntPoint& adjustedPoint)
{
- IntPoint adjustedPoint = gestureEvent.position();
- adjustGesturePosition(gestureEvent, adjustedPoint);
- RefPtr<Frame> subframe = getSubFrameForGestureEvent(adjustedPoint, gestureEvent);
- if (subframe && subframe->eventHandler()->handleGestureLongPress(gestureEvent))
- return true;
-
m_longTapShouldInvokeContextMenu = false;
if (m_frame->settings() && m_frame->settings()->touchDragDropEnabled() && m_frame->view()) {
PlatformMouseEvent mouseDownEvent(adjustedPoint, gestureEvent.globalPosition(), LeftButton, PlatformEvent::MousePressed, 1,
@@ -2362,7 +2450,7 @@ bool EventHandler::handleGestureLongPress(const PlatformGestureEvent& gestureEve
PlatformMouseEvent mouseDragEvent(adjustedPoint, gestureEvent.globalPosition(), LeftButton, PlatformEvent::MouseMoved, 1,
gestureEvent.shiftKey(), gestureEvent.ctrlKey(), gestureEvent.altKey(), gestureEvent.metaKey(), WTF::currentTime());
- HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::DisallowShadowContent);
+ HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent);
MouseEventWithHitTestResults mev = prepareMouseEvent(request, mouseDragEvent);
m_didStartDrag = false;
m_mouseDownMayStartDrag = true;
@@ -2395,13 +2483,8 @@ bool EventHandler::handleGestureLongPress(const PlatformGestureEvent& gestureEve
return sendContextMenuEventForGesture(gestureEvent);
}
-bool EventHandler::handleGestureLongTap(const PlatformGestureEvent& gestureEvent)
+bool EventHandler::handleGestureLongTap(const PlatformGestureEvent& gestureEvent, const IntPoint& adjustedPoint)
{
- IntPoint adjustedPoint = gestureEvent.position();
- adjustGesturePosition(gestureEvent, adjustedPoint);
- RefPtr<Frame> subframe = getSubFrameForGestureEvent(adjustedPoint, gestureEvent);
- if (subframe && subframe->eventHandler()->handleGestureLongTap(gestureEvent))
- return true;
#if !OS(ANDROID)
if (m_longTapShouldInvokeContextMenu) {
m_longTapShouldInvokeContextMenu = false;
@@ -2415,22 +2498,22 @@ bool EventHandler::handleScrollGestureOnResizer(Node* eventTarget, const Platfor
if (gestureEvent.type() == PlatformEvent::GestureScrollBegin) {
RenderLayer* layer = eventTarget->renderer() ? eventTarget->renderer()->enclosingLayer() : 0;
IntPoint p = m_frame->view()->windowToContents(gestureEvent.position());
- if (layer && layer->isPointInResizeControl(p, ResizerForTouch)) {
- layer->setInResizeMode(true);
- m_resizeLayer = layer;
- m_offsetFromResizeCorner = layer->offsetFromResizeCorner(p);
+ if (layer && layer->scrollableArea() && layer->scrollableArea()->isPointInResizeControl(p, ResizerForTouch)) {
+ m_resizeScrollableArea = layer->scrollableArea();
+ m_resizeScrollableArea->setInResizeMode(true);
+ m_offsetFromResizeCorner = m_resizeScrollableArea->offsetFromResizeCorner(p);
return true;
}
} else if (gestureEvent.type() == PlatformEvent::GestureScrollUpdate ||
gestureEvent.type() == PlatformEvent::GestureScrollUpdateWithoutPropagation) {
- if (m_resizeLayer && m_resizeLayer->inResizeMode()) {
- m_resizeLayer->resize(gestureEvent, m_offsetFromResizeCorner);
+ if (m_resizeScrollableArea && m_resizeScrollableArea->inResizeMode()) {
+ m_resizeScrollableArea->resize(gestureEvent, m_offsetFromResizeCorner);
return true;
}
} else if (gestureEvent.type() == PlatformEvent::GestureScrollEnd) {
- if (m_resizeLayer && m_resizeLayer->inResizeMode()) {
- m_resizeLayer->setInResizeMode(false);
- m_resizeLayer = 0;
+ if (m_resizeScrollableArea && m_resizeScrollableArea->inResizeMode()) {
+ m_resizeScrollableArea->setInResizeMode(false);
+ m_resizeScrollableArea = 0;
return false;
}
}
@@ -2438,7 +2521,7 @@ bool EventHandler::handleScrollGestureOnResizer(Node* eventTarget, const Platfor
return false;
}
-bool EventHandler::handleGestureTwoFingerTap(const PlatformGestureEvent& gestureEvent)
+bool EventHandler::handleGestureTwoFingerTap(const PlatformGestureEvent& gestureEvent, const IntPoint& adjustedPoint)
{
return sendContextMenuEventForGesture(gestureEvent);
}
@@ -2451,7 +2534,7 @@ bool EventHandler::passGestureEventToWidget(const PlatformGestureEvent& gestureE
if (!widget->isFrameView())
return false;
- return toFrameView(widget)->frame().eventHandler()->handleGestureEvent(gestureEvent);
+ return toFrameView(widget)->frame().eventHandler().handleGestureEvent(gestureEvent);
}
bool EventHandler::passGestureEventToWidgetIfPossible(const PlatformGestureEvent& gestureEvent, RenderObject* renderer)
@@ -2464,11 +2547,13 @@ bool EventHandler::passGestureEventToWidgetIfPossible(const PlatformGestureEvent
}
bool EventHandler::handleGestureScrollEnd(const PlatformGestureEvent& gestureEvent) {
- Node* node = m_scrollGestureHandlingNode.get();
+ RefPtr<Node> node = m_scrollGestureHandlingNode;
clearGestureScrollNodes();
- if (node)
+ if (node) {
+ ASSERT(node->refCount() > 0);
passGestureEventToWidgetIfPossible(gestureEvent, node->renderer());
+ }
return false;
}
@@ -2476,8 +2561,7 @@ bool EventHandler::handleGestureScrollEnd(const PlatformGestureEvent& gestureEve
bool EventHandler::handleGestureScrollBegin(const PlatformGestureEvent& gestureEvent)
{
Document* document = m_frame->document();
- RenderObject* documentRenderer = document->renderer();
- if (!documentRenderer)
+ if (!document->renderView())
return false;
FrameView* view = m_frame->view();
@@ -2485,7 +2569,7 @@ bool EventHandler::handleGestureScrollBegin(const PlatformGestureEvent& gestureE
return false;
LayoutPoint viewPoint = view->windowToContents(gestureEvent.position());
- HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::DisallowShadowContent);
+ HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent);
HitTestResult result(viewPoint);
document->renderView()->hitTest(request, result);
@@ -2542,8 +2626,8 @@ bool EventHandler::handleGestureScrollUpdate(const PlatformGestureEvent& gesture
// First try to scroll the closest scrollable RenderBox ancestor of |node|.
ScrollGranularity granularity = ScrollByPixel;
- bool horizontalScroll = scrollNode(delta.width(), granularity, ScrollLeft, ScrollRight, node, &stopNode);
- bool verticalScroll = scrollNode(delta.height(), granularity, ScrollUp, ScrollDown, node, &stopNode);
+ bool horizontalScroll = scrollNode(delta.width(), granularity, ScrollLeft, node, &stopNode);
+ bool verticalScroll = scrollNode(delta.height(), granularity, ScrollUp, node, &stopNode);
if (scrollShouldNotPropagate)
m_previousGestureScrolledNode = stopNode;
@@ -2586,7 +2670,7 @@ Frame* EventHandler::getSubFrameForGestureEvent(const IntPoint& touchAdjustedPoi
gestureEvent.shiftKey(), gestureEvent.ctrlKey(), gestureEvent.altKey(), gestureEvent.metaKey(), gestureEvent.timestamp());
HitTestRequest request(HitTestRequest::ReadOnly);
MouseEventWithHitTestResults mev = prepareMouseEvent(request, mouseDown);
- return EventHandler::subframeForHitTestResult(mev);
+ return subframeForHitTestResult(mev);
}
void EventHandler::clearGestureScrollNodes()
@@ -2613,6 +2697,12 @@ bool EventHandler::bestClickableNodeForTouchPoint(const IntPoint& touchCenter, c
IntPoint hitTestPoint = m_frame->view()->windowToContents(touchCenter);
HitTestResult result = hitTestResultAtPoint(hitTestPoint, HitTestRequest::ReadOnly | HitTestRequest::Active, touchRadius);
+ // If the touch is over a scrollbar, don't adjust the touch point since touch adjustment only takes into account
+ // DOM nodes so a touch over a scrollbar will be adjusted towards nearby nodes. This leads to things like textarea
+ // scrollbars being untouchable.
+ if (result.scrollbar())
+ return false;
+
IntRect touchRect(touchCenter - touchRadius, touchRadius + touchRadius);
Vector<RefPtr<Node>, 11> nodes;
copyToVector(result.rectBasedTestResult(), nodes);
@@ -2647,7 +2737,7 @@ bool EventHandler::bestContextMenuNodeForTouchPoint(const IntPoint& touchCenter,
bool EventHandler::bestZoomableAreaForTouchPoint(const IntPoint& touchCenter, const IntSize& touchRadius, IntRect& targetArea, Node*& targetNode)
{
IntPoint hitTestPoint = m_frame->view()->windowToContents(touchCenter);
- HitTestResult result = hitTestResultAtPoint(hitTestPoint, HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::DisallowShadowContent, touchRadius);
+ HitTestResult result = hitTestResultAtPoint(hitTestPoint, HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent, touchRadius);
IntRect touchRect(touchCenter - touchRadius, touchRadius + touchRadius);
Vector<RefPtr<Node>, 11> nodes;
@@ -2668,6 +2758,7 @@ bool EventHandler::adjustGesturePosition(const PlatformGestureEvent& gestureEven
case PlatformEvent::GestureTap:
case PlatformEvent::GestureTapUnconfirmed:
case PlatformEvent::GestureTapDown:
+ case PlatformEvent::GestureShowPress:
bestClickableNodeForTouchPoint(gestureEvent.position(), IntSize(gestureEvent.area().width() / 2, gestureEvent.area().height() / 2), adjustedPoint, targetNode);
break;
case PlatformEvent::GestureLongPress:
@@ -2693,7 +2784,7 @@ bool EventHandler::sendContextMenuEvent(const PlatformMouseEvent& event)
m_mousePressed = false;
bool swallowEvent;
LayoutPoint viewportPos = v->windowToContents(event.position());
- HitTestRequest request(HitTestRequest::Active | HitTestRequest::DisallowShadowContent);
+ HitTestRequest request(HitTestRequest::Active | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent);
MouseEventWithHitTestResults mev = doc->prepareMouseEvent(request, viewportPos, event);
if (!m_frame->selection().contains(viewportPos)
@@ -2710,7 +2801,7 @@ bool EventHandler::sendContextMenuEvent(const PlatformMouseEvent& event)
selectClosestWordOrLinkFromMouseEvent(mev);
}
- swallowEvent = !dispatchMouseEvent(eventNames().contextmenuEvent, mev.targetNode(), true, 0, event, false);
+ swallowEvent = !dispatchMouseEvent(EventTypeNames::contextmenu, mev.targetNode(), true, 0, event, false);
return swallowEvent;
}
@@ -2773,7 +2864,7 @@ bool EventHandler::sendContextMenuEventForKey()
// Use the focused node as the target for hover and active.
HitTestResult result(position);
result.setInnerNode(targetNode);
- doc->updateHoverActiveState(HitTestRequest::Active | HitTestRequest::DisallowShadowContent, result.innerElement());
+ doc->updateHoverActiveState(HitTestRequest::Active | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent, result.innerElement());
// The contextmenu event is a mouse event even when invoked using the keyboard.
// This is required for web compatibility.
@@ -2786,7 +2877,7 @@ bool EventHandler::sendContextMenuEventForKey()
PlatformMouseEvent mouseEvent(position, globalPosition, RightButton, eventType, 1, false, false, false, false, WTF::currentTime());
- return !dispatchMouseEvent(eventNames().contextmenuEvent, targetNode, true, 0, mouseEvent, false);
+ return !dispatchMouseEvent(EventTypeNames::contextmenu, targetNode, true, 0, mouseEvent, false);
}
bool EventHandler::sendContextMenuEventForGesture(const PlatformGestureEvent& event)
@@ -2814,6 +2905,12 @@ void EventHandler::scheduleHoverStateUpdate()
m_hoverTimer.startOneShot(0);
}
+void EventHandler::scheduleCursorUpdate()
+{
+ if (!m_cursorUpdateTimer.isActive())
+ m_cursorUpdateTimer.startOneShot(cursorUpdateInterval);
+}
+
void EventHandler::dispatchFakeMouseMoveEventSoon()
{
if (m_mousePressed)
@@ -2896,10 +2993,10 @@ void EventHandler::setResizingFrameSet(HTMLFrameSetElement* frameSet)
m_frameSetBeingResized = frameSet;
}
-void EventHandler::resizeLayerDestroyed()
+void EventHandler::resizeScrollableAreaDestroyed()
{
- ASSERT(m_resizeLayer);
- m_resizeLayer = 0;
+ ASSERT(m_resizeScrollableArea);
+ m_resizeScrollableArea = 0;
}
void EventHandler::hoverTimerFired(Timer<EventHandler>*)
@@ -2911,7 +3008,7 @@ void EventHandler::hoverTimerFired(Timer<EventHandler>*)
if (RenderView* renderer = m_frame->contentRenderer()) {
if (FrameView* view = m_frame->view()) {
- HitTestRequest request(HitTestRequest::Move | HitTestRequest::DisallowShadowContent);
+ HitTestRequest request(HitTestRequest::Move | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent);
HitTestResult result(view->windowToContents(m_lastKnownMousePosition));
renderer->hitTest(request, result);
m_frame->document()->updateHoverActiveState(request, result.innerElement());
@@ -2919,6 +3016,29 @@ void EventHandler::hoverTimerFired(Timer<EventHandler>*)
}
}
+void EventHandler::activeIntervalTimerFired(Timer<EventHandler>*)
+{
+ m_activeIntervalTimer.stop();
+
+ if (m_frame
+ && m_frame->document()
+ && m_lastDeferredTapElement) {
+ // FIXME: Enable condition when http://crbug.com/226842 lands
+ // m_lastDeferredTapElement.get() == m_frame->document()->activeElement()
+ HitTestRequest request(HitTestRequest::TouchEvent | HitTestRequest::Release);
+ m_frame->document()->updateHoverActiveState(request, m_lastDeferredTapElement.get());
+ }
+ m_lastDeferredTapElement = 0;
+}
+
+void EventHandler::notifyElementActivated()
+{
+ // Since another element has been set to active, stop current timer and clear reference.
+ if (m_activeIntervalTimer.isActive())
+ m_activeIntervalTimer.stop();
+ m_lastDeferredTapElement = 0;
+}
+
bool EventHandler::handleAccessKey(const PlatformKeyboardEvent& evt)
{
// FIXME: Ignoring the state of Shift key is what neither IE nor Firefox do.
@@ -2971,7 +3091,7 @@ bool EventHandler::keyEvent(const PlatformKeyboardEvent& initialKeyEvent)
if (panScrollInProgress()) {
// If a key is pressed while the panScroll is in progress then we want to stop
if (initialKeyEvent.type() == PlatformEvent::KeyDown || initialKeyEvent.type() == PlatformEvent::RawKeyDown)
- stopAutoscrollTimer();
+ stopAutoscroll();
// If we were in panscroll mode, we swallow the key event
return true;
@@ -2985,7 +3105,6 @@ bool EventHandler::keyEvent(const PlatformKeyboardEvent& initialKeyEvent)
return false;
UserGestureIndicator gestureIndicator(DefinitelyProcessingUserGesture);
- UserTypingGestureIndicator typingGestureIndicator(m_frame);
if (FrameView* view = m_frame->view())
view->resetDeferredRepaintDelay();
@@ -3006,7 +3125,7 @@ bool EventHandler::keyEvent(const PlatformKeyboardEvent& initialKeyEvent)
PlatformKeyboardEvent keyDownEvent = initialKeyEvent;
if (keyDownEvent.type() != PlatformEvent::RawKeyDown)
keyDownEvent.disambiguateKeyDownEvent(PlatformEvent::RawKeyDown);
- RefPtr<KeyboardEvent> keydown = KeyboardEvent::create(keyDownEvent, m_frame->document()->defaultView());
+ RefPtr<KeyboardEvent> keydown = KeyboardEvent::create(keyDownEvent, m_frame->document()->domWindow());
if (matchedAnAccessKey)
keydown->setDefaultPrevented(true);
keydown->setTarget(node);
@@ -3035,7 +3154,7 @@ bool EventHandler::keyEvent(const PlatformKeyboardEvent& initialKeyEvent)
keyPressEvent.disambiguateKeyDownEvent(PlatformEvent::Char);
if (keyPressEvent.text().isEmpty())
return keydownResult;
- RefPtr<KeyboardEvent> keypress = KeyboardEvent::create(keyPressEvent, m_frame->document()->defaultView());
+ RefPtr<KeyboardEvent> keypress = KeyboardEvent::create(keyPressEvent, m_frame->document()->domWindow());
keypress->setTarget(node);
if (keydownResult)
keypress->setDefaultPrevented(true);
@@ -3067,7 +3186,7 @@ static FocusDirection focusDirectionForKey(const AtomicString& keyIdentifier)
void EventHandler::defaultKeyboardEventHandler(KeyboardEvent* event)
{
- if (event->type() == eventNames().keydownEvent) {
+ if (event->type() == EventTypeNames::keydown) {
m_frame->editor().handleKeyboardEvent(event);
if (event->defaultHandled())
return;
@@ -3083,7 +3202,7 @@ void EventHandler::defaultKeyboardEventHandler(KeyboardEvent* event)
defaultArrowEventHandler(direction, event);
}
}
- if (event->type() == eventNames().keypressEvent) {
+ if (event->type() == EventTypeNames::keypress) {
m_frame->editor().handleKeyboardEvent(event);
if (event->defaultHandled())
return;
@@ -3135,13 +3254,13 @@ void EventHandler::freeClipboard()
void EventHandler::dragSourceEndedAt(const PlatformMouseEvent& event, DragOperation operation)
{
// Send a hit test request so that RenderLayer gets a chance to update the :hover and :active pseudoclasses.
- HitTestRequest request(HitTestRequest::Release | HitTestRequest::DisallowShadowContent);
+ HitTestRequest request(HitTestRequest::Release | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent);
prepareMouseEvent(request, event);
if (dragState().m_dragSrc) {
dragState().m_dragClipboard->setDestinationOperation(operation);
// for now we don't care if event handler cancels default behavior, since there is none
- dispatchDragSrcEvent(eventNames().dragendEvent, event);
+ dispatchDragSrcEvent(EventTypeNames::dragend, event);
}
freeClipboard();
dragState().m_dragSrc = 0;
@@ -3163,15 +3282,11 @@ bool EventHandler::dispatchDragSrcEvent(const AtomicString& eventType, const Pla
return !dispatchDragEvent(eventType, dragState().m_dragSrc.get(), event, dragState().m_dragClipboard.get());
}
-static bool exactlyOneBitSet(DragSourceAction n)
-{
- return n && !(n & (n - 1));
-}
-
bool EventHandler::handleDrag(const MouseEventWithHitTestResults& event, CheckDragHysteresis checkDragHysteresis)
{
+ ASSERT(event.event().type() == PlatformEvent::MouseMoved);
// Callers must protect the reference to FrameView, since this function may dispatch DOM
- // events, causing Frame/FrameView to go away.
+ // events, causing page/FrameView to go away.
ASSERT(m_frame);
ASSERT(m_frame->view());
if (!m_frame->page())
@@ -3186,58 +3301,27 @@ bool EventHandler::handleDrag(const MouseEventWithHitTestResults& event, CheckDr
return false;
}
- if (m_mouseDownMayStartDrag && !dragState().m_dragSrc) {
- // try to find an element that wants to be dragged
- HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::DisallowShadowContent);
+ if (m_mouseDownMayStartDrag) {
+ HitTestRequest request(HitTestRequest::ReadOnly);
HitTestResult result(m_mouseDownPos);
m_frame->contentRenderer()->hitTest(request, result);
Node* node = result.innerNode();
- if (node)
- dragState().m_dragSrc = m_frame->page()->dragController().draggableNode(m_frame, node, m_mouseDownPos, dragState());
- else
+ if (node) {
+ DragController::SelectionDragPolicy selectionDragPolicy = event.event().timestamp() - m_mouseDownTimestamp < TextDragDelay
+ ? DragController::DelayedSelectionDragResolution
+ : DragController::ImmediateSelectionDragResolution;
+ dragState().m_dragSrc = m_frame->page()->dragController().draggableNode(m_frame, node, m_mouseDownPos, selectionDragPolicy, dragState().m_dragType);
+ } else {
dragState().m_dragSrc = 0;
+ }
if (!dragState().m_dragSrc)
m_mouseDownMayStartDrag = false; // no element is draggable
- else
- m_dragMayStartSelectionInstead = (dragState().m_dragType & DragSourceActionSelection);
- }
-
- // For drags starting in the selection, the user must wait between the mousedown and mousedrag,
- // or else we bail on the dragging stuff and allow selection to occur
- if (m_mouseDownMayStartDrag && m_dragMayStartSelectionInstead && (dragState().m_dragType & DragSourceActionSelection) && event.event().timestamp() - m_mouseDownTimestamp < TextDragDelay) {
- ASSERT(event.event().type() == PlatformEvent::MouseMoved);
- if ((dragState().m_dragType & DragSourceActionImage)) {
- // ... unless the mouse is over an image, then we start dragging just the image
- dragState().m_dragType = DragSourceActionImage;
- } else if (!(dragState().m_dragType & (DragSourceActionDHTML | DragSourceActionLink))) {
- // ... but only bail if we're not over an unselectable element.
- m_mouseDownMayStartDrag = false;
- dragState().m_dragSrc = 0;
- } else {
- // Prevent the following case from occuring:
- // 1. User starts a drag immediately after mouse down over an unselectable element.
- // 2. We enter this block and decided that since we're over an unselectable element,
- // don't cancel the drag.
- // 3. The drag gets resolved as a potential selection drag below /but/ we haven't
- // exceeded the drag hysteresis yet.
- // 4. We enter this block again, and since it's now marked as a selection drag, we
- // cancel the drag.
- m_dragMayStartSelectionInstead = false;
- }
}
if (!m_mouseDownMayStartDrag)
return !mouseDownMayStartSelect() && !m_mouseDownMayStartAutoscroll;
- if (!exactlyOneBitSet(dragState().m_dragType)) {
- ASSERT((dragState().m_dragType & DragSourceActionSelection));
- ASSERT((dragState().m_dragType & ~DragSourceActionSelection) == DragSourceActionDHTML
- || (dragState().m_dragType & ~DragSourceActionSelection) == DragSourceActionImage
- || (dragState().m_dragType & ~DragSourceActionSelection) == DragSourceActionLink);
- dragState().m_dragType = DragSourceActionSelection;
- }
-
// We are starting a text/image/url drag, so the cursor should be an arrow
// FIXME <rdar://7577595>: Custom cursors aren't supported during drag and drop (default to pointer).
m_frame->view()->setCursor(pointerCursor());
@@ -3283,7 +3367,7 @@ bool EventHandler::tryStartDrag(const MouseEventWithHitTestResults& event)
DragController& dragController = m_frame->page()->dragController();
if (!dragController.populateDragClipboard(m_frame, dragState(), m_mouseDownPos))
return false;
- m_mouseDownMayStartDrag = dispatchDragSrcEvent(eventNames().dragstartEvent, m_mouseDown)
+ m_mouseDownMayStartDrag = dispatchDragSrcEvent(EventTypeNames::dragstart, m_mouseDown)
&& !m_frame->selection().isInPasswordField();
// Invalidate clipboard here against anymore pasteboard writing for security. The drag
@@ -3291,12 +3375,6 @@ bool EventHandler::tryStartDrag(const MouseEventWithHitTestResults& event)
dragState().m_dragClipboard->setAccessPolicy(ClipboardImageWritable);
if (m_mouseDownMayStartDrag) {
- // Yuck, a draggedImage:moveTo: message can be fired as a result of kicking off the
- // drag with dragImage! Because of that dumb reentrancy, we may think we've not
- // started the drag when that happens. So we have to assume it's started before we
- // kick it off.
- dragState().m_dragClipboard->setDragHasStarted();
-
// Dispatching the event could cause Page to go away. Make sure it's still valid before trying to use DragController.
m_didStartDrag = m_frame->page() && dragController.startDrag(m_frame, dragState(), event.event(), m_mouseDownPos);
// FIXME: This seems pretty useless now. The gesture code uses this as a signal for
@@ -3305,7 +3383,7 @@ bool EventHandler::tryStartDrag(const MouseEventWithHitTestResults& event)
if (m_didStartDrag)
return true;
// Drag was canned at the last minute - we owe m_dragSrc a DRAGEND event
- dispatchDragSrcEvent(eventNames().dragendEvent, event.event());
+ dispatchDragSrcEvent(EventTypeNames::dragend, event.event());
}
return false;
@@ -3315,7 +3393,7 @@ bool EventHandler::handleTextInputEvent(const String& text, Event* underlyingEve
{
// Platforms should differentiate real commands like selectAll from text input in disguise (like insertNewline),
// and avoid dispatching text input events from keydown default handlers.
- ASSERT(!underlyingEvent || !underlyingEvent->isKeyboardEvent() || toKeyboardEvent(underlyingEvent)->type() == eventNames().keypressEvent);
+ ASSERT(!underlyingEvent || !underlyingEvent->isKeyboardEvent() || toKeyboardEvent(underlyingEvent)->type() == EventTypeNames::keypress);
if (!m_frame)
return false;
@@ -3338,14 +3416,6 @@ bool EventHandler::handleTextInputEvent(const String& text, Event* underlyingEve
return event->defaultHandled();
}
-bool EventHandler::isKeyboardOptionTab(KeyboardEvent* event)
-{
- return event
- && (event->type() == eventNames().keydownEvent || event->type() == eventNames().keypressEvent)
- && event->altKey()
- && event->keyIdentifier() == "U+0009";
-}
-
void EventHandler::defaultTextInputEventHandler(TextEvent* event)
{
if (m_frame->editor().handleTextEvent(event))
@@ -3354,13 +3424,13 @@ void EventHandler::defaultTextInputEventHandler(TextEvent* event)
void EventHandler::defaultSpaceEventHandler(KeyboardEvent* event)
{
- ASSERT(event->type() == eventNames().keypressEvent);
+ ASSERT(event->type() == EventTypeNames::keypress);
if (event->ctrlKey() || event->metaKey() || event->altKey() || event->altGraphKey())
return;
- ScrollLogicalDirection direction = event->shiftKey() ? ScrollBlockDirectionBackward : ScrollBlockDirectionForward;
- if (logicalScrollOverflow(direction, ScrollByPage)) {
+ ScrollDirection direction = event->shiftKey() ? ScrollBlockDirectionBackward : ScrollBlockDirectionForward;
+ if (scrollOverflow(direction, ScrollByPage)) {
event->setDefaultHandled();
return;
}
@@ -3369,13 +3439,13 @@ void EventHandler::defaultSpaceEventHandler(KeyboardEvent* event)
if (!view)
return;
- if (view->logicalScroll(direction, ScrollByPage))
+ if (view->scroll(direction, ScrollByPage))
event->setDefaultHandled();
}
void EventHandler::defaultBackspaceEventHandler(KeyboardEvent* event)
{
- ASSERT(event->type() == eventNames().keydownEvent);
+ ASSERT(event->type() == EventTypeNames::keydown);
if (event->ctrlKey() || event->metaKey() || event->altKey() || event->altGraphKey())
return;
@@ -3386,21 +3456,14 @@ void EventHandler::defaultBackspaceEventHandler(KeyboardEvent* event)
Page* page = m_frame->page();
if (!page)
return;
-
- bool handledEvent = false;
-
- if (event->shiftKey())
- handledEvent = page->backForward().goForward();
- else
- handledEvent = page->backForward().goBack();
-
+ bool handledEvent = page->mainFrame()->loader().client()->navigateBackForward(event->shiftKey() ? 1 : -1);
if (handledEvent)
event->setDefaultHandled();
}
void EventHandler::defaultArrowEventHandler(FocusDirection focusDirection, KeyboardEvent* event)
{
- ASSERT(event->type() == eventNames().keydownEvent);
+ ASSERT(event->type() == EventTypeNames::keydown);
if (event->ctrlKey() || event->metaKey() || event->altGraphKey() || event->shiftKey())
return;
@@ -3423,7 +3486,7 @@ void EventHandler::defaultArrowEventHandler(FocusDirection focusDirection, Keybo
void EventHandler::defaultTabEventHandler(KeyboardEvent* event)
{
- ASSERT(event->type() == eventNames().keydownEvent);
+ ASSERT(event->type() == EventTypeNames::keydown);
// We should only advance focus on tabs if no special modifier keys are held down.
if (event->ctrlKey() || event->metaKey() || event->altGraphKey())
@@ -3448,7 +3511,7 @@ void EventHandler::defaultTabEventHandler(KeyboardEvent* event)
void EventHandler::defaultEscapeEventHandler(KeyboardEvent* event)
{
if (HTMLDialogElement* dialog = m_frame->document()->activeModalDialog())
- dialog->dispatchEvent(Event::createCancelable(eventNames().cancelEvent));
+ dialog->dispatchEvent(Event::createCancelable(EventTypeNames::cancel));
}
void EventHandler::capsLockStateMayHaveChanged()
@@ -3461,23 +3524,10 @@ void EventHandler::capsLockStateMayHaveChanged()
}
}
-void EventHandler::sendResizeEvent()
-{
- m_frame->document()->enqueueWindowEvent(Event::create(eventNames().resizeEvent));
-}
-
-void EventHandler::sendScrollEvent()
-{
- setFrameWasScrolledByUser();
- if (m_frame->view() && m_frame->document())
- m_frame->document()->eventQueue()->enqueueOrDispatchScrollEvent(m_frame->document(), DocumentEventQueue::ScrollEventDocumentTarget);
-}
-
void EventHandler::setFrameWasScrolledByUser()
{
- FrameView* v = m_frame->view();
- if (v)
- v->setWasScrolledByUser(true);
+ if (FrameView* view = m_frame->view())
+ view->setWasScrolledByUser(true);
}
bool EventHandler::passMousePressEventToScrollbar(MouseEventWithHitTestResults& mev, Scrollbar* scrollbar)
@@ -3510,13 +3560,13 @@ static const AtomicString& eventNameForTouchPointState(PlatformTouchPoint::State
{
switch (state) {
case PlatformTouchPoint::TouchReleased:
- return eventNames().touchendEvent;
+ return EventTypeNames::touchend;
case PlatformTouchPoint::TouchCancelled:
- return eventNames().touchcancelEvent;
+ return EventTypeNames::touchcancel;
case PlatformTouchPoint::TouchPressed:
- return eventNames().touchstartEvent;
+ return EventTypeNames::touchstart;
case PlatformTouchPoint::TouchMoved:
- return eventNames().touchmoveEvent;
+ return EventTypeNames::touchmove;
case PlatformTouchPoint::TouchStationary:
// TouchStationary state is not converted to touch events, so fall through to assert.
default:
@@ -3583,7 +3633,9 @@ bool EventHandler::handleTouchEvent(const PlatformTouchEvent& event)
PlatformTouchPoint::State pointState = point.state();
LayoutPoint pagePoint = documentPointForWindowPoint(m_frame, point.pos());
- HitTestRequest::HitTestRequestType hitType = HitTestRequest::TouchEvent;
+ // Gesture events trigger the active state, not touch events,
+ // so touch event hit tests can always be read only.
+ HitTestRequest::HitTestRequestType hitType = HitTestRequest::TouchEvent | HitTestRequest::ReadOnly;
// The HitTestRequest types used for mouse events map quite adequately
// to touch events. Note that in addition to meaning that the hit test
// should affect the active state of the current node if necessary,
@@ -3594,23 +3646,20 @@ bool EventHandler::handleTouchEvent(const PlatformTouchEvent& event)
hitType |= HitTestRequest::Active;
break;
case PlatformTouchPoint::TouchMoved:
- hitType |= HitTestRequest::Active | HitTestRequest::Move | HitTestRequest::ReadOnly;
+ hitType |= HitTestRequest::Active | HitTestRequest::Move;
break;
case PlatformTouchPoint::TouchReleased:
case PlatformTouchPoint::TouchCancelled:
hitType |= HitTestRequest::Release;
break;
case PlatformTouchPoint::TouchStationary:
- hitType |= HitTestRequest::Active | HitTestRequest::ReadOnly;
+ hitType |= HitTestRequest::Active;
break;
default:
ASSERT_NOT_REACHED();
break;
}
- if (shouldGesturesTriggerActive())
- hitType |= HitTestRequest::ReadOnly;
-
// Increment the platform touch id by 1 to avoid storing a key of 0 in the hashmap.
unsigned touchPointTargetKey = point.id() + 1;
RefPtr<EventTarget> touchTarget;
@@ -3631,7 +3680,7 @@ bool EventHandler::handleTouchEvent(const PlatformTouchEvent& event)
// Touch events should not go to text nodes
if (node->isTextNode())
- node = EventPathWalker::parent(node);
+ node = EventPath::parent(node);
Document& doc = node->document();
// Record the originating touch document even if it does not have a touch listener.
@@ -3643,15 +3692,13 @@ bool EventHandler::handleTouchEvent(const PlatformTouchEvent& event)
continue;
m_originatingTouchPointTargets.set(touchPointTargetKey, node);
touchTarget = node;
+
+ // FIXME(rbyers): Should really be doing a second hit test that ignores inline elements - crbug.com/319479.
+ TouchAction effectiveTouchAction = computeEffectiveTouchAction(*node);
+ if (effectiveTouchAction != TouchActionAuto)
+ m_frame->page()->chrome().client().setTouchAction(effectiveTouchAction);
+
} else if (pointState == PlatformTouchPoint::TouchReleased || pointState == PlatformTouchPoint::TouchCancelled) {
- // We only perform a hittest on release or cancel to unset :active or :hover state.
- if (touchPointTargetKey == m_originatingTouchPointTargetKey) {
- hitTestResultAtPoint(pagePoint, hitType);
- m_originatingTouchPointTargetKey = 0;
- } else if (m_originatingTouchPointDocument.get() && m_originatingTouchPointDocument->frame()) {
- LayoutPoint pagePointInOriginatingDocument = documentPointForWindowPoint(m_originatingTouchPointDocument->frame(), point.pos());
- hitTestResultInFrame(m_originatingTouchPointDocument->frame(), pagePointInOriginatingDocument, hitType);
- }
// The target should be the original target for this touch, so get it from the hashmap. As it's a release or cancel
// we also remove it from the map.
touchTarget = m_originatingTouchPointTargets.take(touchPointTargetKey);
@@ -3677,11 +3724,14 @@ bool EventHandler::handleTouchEvent(const PlatformTouchEvent& event)
int adjustedPageX = lroundf(pagePoint.x() / scaleFactor);
int adjustedPageY = lroundf(pagePoint.y() / scaleFactor);
+ int adjustedRadiusX = lroundf(point.radiusX() / scaleFactor);
+ int adjustedRadiusY = lroundf(point.radiusY() / scaleFactor);
RefPtr<Touch> touch = Touch::create(targetFrame, touchTarget.get(), point.id(),
point.screenPos().x(), point.screenPos().y(),
adjustedPageX, adjustedPageY,
- point.radiusX(), point.radiusY(), point.rotationAngle(), point.force());
+ adjustedRadiusX, adjustedRadiusY,
+ point.rotationAngle(), point.force());
// Ensure this target's touch list exists, even if it ends up empty, so it can always be passed to TouchEvent::Create below.
TargetTouchesMap::iterator targetTouchesIterator = touchesByTarget.find(touchTarget.get());
@@ -3733,8 +3783,8 @@ bool EventHandler::handleTouchEvent(const PlatformTouchEvent& event)
RefPtr<TouchEvent> touchEvent =
TouchEvent::create(effectiveTouches.get(), targetTouches.get(), changedTouches[state].m_touches.get(),
- stateName, touchEventTarget->toNode()->document().defaultView(),
- 0, 0, 0, 0, event.ctrlKey(), event.altKey(), event.shiftKey(), event.metaKey());
+ stateName, touchEventTarget->toNode()->document().domWindow(),
+ 0, 0, 0, 0, event.ctrlKey(), event.altKey(), event.shiftKey(), event.metaKey());
touchEventTarget->toNode()->dispatchTouchEvent(touchEvent.get());
swallowedEvent = swallowedEvent || touchEvent->defaultPrevented() || touchEvent->defaultHandled();
}
@@ -3745,24 +3795,149 @@ bool EventHandler::handleTouchEvent(const PlatformTouchEvent& event)
bool EventHandler::dispatchSyntheticTouchEventIfEnabled(const PlatformMouseEvent& event)
{
- if (!m_frame || !m_frame->settings() || !m_frame->settings()->isTouchEventEmulationEnabled())
+ if (!m_frame || !m_frame->settings() || !m_frame->settings()->touchEventEmulationEnabled())
return false;
PlatformEvent::Type eventType = event.type();
if (eventType != PlatformEvent::MouseMoved && eventType != PlatformEvent::MousePressed && eventType != PlatformEvent::MouseReleased)
return false;
- HitTestRequest request(HitTestRequest::Active | HitTestRequest::DisallowShadowContent);
+ HitTestRequest request(HitTestRequest::Active | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent);
MouseEventWithHitTestResults mev = prepareMouseEvent(request, event);
if (mev.scrollbar() || subframeForHitTestResult(mev))
return false;
// The order is important. This check should follow the subframe test: http://webkit.org/b/111292.
- if (eventType == PlatformEvent::MouseMoved && !m_touchPressed)
+ if (eventType == PlatformEvent::MouseMoved && event.button() == NoButton)
return true;
SyntheticSingleTouchEvent touchEvent(event);
- return handleTouchEvent(touchEvent);
+ if (handleTouchEvent(touchEvent))
+ return true;
+
+ return handleMouseEventAsEmulatedGesture(event);
+}
+
+bool EventHandler::handleMouseEventAsEmulatedGesture(const PlatformMouseEvent& event)
+{
+ PlatformEvent::Type eventType = event.type();
+ if (event.button() != LeftButton || !m_frame->isMainFrame())
+ return false;
+
+ // Simulate pinch / scroll gesture.
+ const IntPoint& position = event.position();
+ bool swallowEvent = false;
+
+ FrameView* view = m_frame->view();
+ if (event.shiftKey()) {
+ // Shift pressed - consider it gesture.
+ swallowEvent = true;
+ Page* page = m_frame->page();
+ float pageScaleFactor = page->pageScaleFactor();
+ switch (eventType) {
+ case PlatformEvent::MousePressed:
+ m_lastSyntheticPinchAnchorCss = adoptPtr(new IntPoint(view->scrollPosition() + position));
+ m_lastSyntheticPinchAnchorDip = adoptPtr(new IntPoint(position));
+ m_lastSyntheticPinchAnchorDip->scale(pageScaleFactor, pageScaleFactor);
+ m_syntheticPageScaleFactor = pageScaleFactor;
+ break;
+ case PlatformEvent::MouseMoved:
+ {
+ if (!m_lastSyntheticPinchAnchorCss)
+ break;
+
+ float dy = m_lastSyntheticPinchAnchorDip->y() - position.y() * pageScaleFactor;
+ float magnifyDelta = exp(dy * 0.002f);
+ float newPageScaleFactor = m_syntheticPageScaleFactor * magnifyDelta;
+
+ IntPoint anchorCss(*m_lastSyntheticPinchAnchorDip.get());
+ anchorCss.scale(1.f / newPageScaleFactor, 1.f / newPageScaleFactor);
+ page->inspectorController().requestPageScaleFactor(newPageScaleFactor, *m_lastSyntheticPinchAnchorCss.get() - toIntSize(anchorCss));
+ break;
+ }
+ case PlatformEvent::MouseReleased:
+ m_lastSyntheticPinchAnchorCss.clear();
+ m_lastSyntheticPinchAnchorDip.clear();
+ default:
+ break;
+ }
+ } else {
+ switch (eventType) {
+ case PlatformEvent::MouseMoved:
+ {
+ // Always consume move events.
+ swallowEvent = true;
+ int dx = m_lastSyntheticPanLocation ? position.x() - m_lastSyntheticPanLocation->x() : 0;
+ int dy = m_lastSyntheticPanLocation ? position.y() - m_lastSyntheticPanLocation->y() : 0;
+ if (dx || dy)
+ view->scrollBy(IntSize(-dx, -dy));
+ // Mouse dragged - consider it gesture.
+ m_lastSyntheticPanLocation = adoptPtr(new IntPoint(position));
+ break;
+ }
+ case PlatformEvent::MouseReleased:
+ // There was a drag -> gesture.
+ swallowEvent = !!m_lastSyntheticPanLocation;
+ m_lastSyntheticPanLocation.clear();
+ default:
+ break;
+ }
+ }
+
+ return swallowEvent;
+}
+
+bool EventHandler::handleWheelEventAsEmulatedGesture(const PlatformWheelEvent& event)
+{
+ if (!m_frame || !m_frame->settings() || !m_frame->settings()->touchEventEmulationEnabled())
+ return false;
+
+ // Only convert vertical wheel w/ shift into pinch for touch-enabled device convenience.
+ if (!event.shiftKey() || !event.deltaY())
+ return false;
+
+ Page* page = m_frame->page();
+ FrameView* view = m_frame->view();
+ float pageScaleFactor = page->pageScaleFactor();
+ IntPoint anchorBeforeCss(view->scrollPosition() + event.position());
+ IntPoint anchorBeforeDip(event.position());
+ anchorBeforeDip.scale(pageScaleFactor, pageScaleFactor);
+
+ float magnifyDelta = exp(event.deltaY() * 0.002f);
+ float newPageScaleFactor = pageScaleFactor * magnifyDelta;
+
+ IntPoint anchorAfterCss(anchorBeforeDip);
+ anchorAfterCss.scale(1.f / newPageScaleFactor, 1.f / newPageScaleFactor);
+ page->inspectorController().requestPageScaleFactor(newPageScaleFactor, anchorBeforeCss - toIntSize(anchorAfterCss));
+ return true;
+}
+
+TouchAction EventHandler::computeEffectiveTouchAction(const Node& node)
+{
+ // Optimization to minimize risk of this new feature (behavior should be identical
+ // since there's no way to get non-default touch-action values).
+ if (!RuntimeEnabledFeatures::cssTouchActionEnabled())
+ return TouchActionAuto;
+
+ // Start by permitting all actions, then walk the block level elements from
+ // the target node up to the nearest scrollable ancestor and exclude any
+ // prohibited actions. For now this is trivial, but when we add more types
+ // of actions it'll get a little more complex.
+ for (const Node* curNode = &node; curNode; curNode = NodeRenderingTraversal::parent(curNode)) {
+ // The spec says only block and SVG elements get touch-action.
+ // FIXME(rbyers): Add correct support for SVG, crbug.com/247396.
+ if (RenderObject* renderer = curNode->renderer()) {
+ if (renderer->isRenderBlockFlow()) {
+ if (renderer->style()->touchAction() == TouchActionNone)
+ return TouchActionNone;
+ }
+
+ // If we've reached an ancestor that supports a touch action, search no further.
+ if (renderer->isBox() && toRenderBox(renderer)->scrollsOverflow())
+ break;
+ }
+ }
+ return TouchActionAuto;
}
void EventHandler::setLastKnownMousePosition(const PlatformMouseEvent& event)
@@ -3783,11 +3958,10 @@ bool EventHandler::passMousePressEventToSubframe(MouseEventWithHitTestResults& m
VisiblePosition visiblePos(
mev.targetNode()->renderer()->positionForPoint(mev.localPoint()));
VisibleSelection newSelection(visiblePos);
- if (m_frame->selection().shouldChangeSelection(newSelection))
- m_frame->selection().setSelection(newSelection);
+ m_frame->selection().setSelection(newSelection);
}
- subframe->eventHandler()->handleMousePressEvent(mev.event());
+ subframe->eventHandler().handleMousePressEvent(mev.event());
return true;
}
@@ -3795,13 +3969,13 @@ bool EventHandler::passMouseMoveEventToSubframe(MouseEventWithHitTestResults& me
{
if (m_mouseDownMayStartDrag && !m_mouseDownWasInSubframe)
return false;
- subframe->eventHandler()->handleMouseMoveOrLeaveEvent(mev.event(), hoveredNode);
+ subframe->eventHandler().handleMouseMoveOrLeaveEvent(mev.event(), hoveredNode);
return true;
}
bool EventHandler::passMouseReleaseEventToSubframe(MouseEventWithHitTestResults& mev, Frame* subframe)
{
- subframe->eventHandler()->handleMouseReleaseEvent(mev.event());
+ subframe->eventHandler().handleMouseReleaseEvent(mev.event());
return true;
}
@@ -3817,7 +3991,7 @@ bool EventHandler::passWheelEventToWidget(const PlatformWheelEvent& wheelEvent,
if (!widget->isFrameView())
return false;
- return toFrameView(widget)->frame().eventHandler()->handleWheelEvent(wheelEvent);
+ return toFrameView(widget)->frame().eventHandler().handleWheelEvent(wheelEvent);
}
bool EventHandler::passWidgetMouseDownEventToWidget(const MouseEventWithHitTestResults& event)
@@ -3830,8 +4004,7 @@ bool EventHandler::passWidgetMouseDownEventToWidget(const MouseEventWithHitTestR
PassRefPtr<Clipboard> EventHandler::createDraggingClipboard() const
{
- RefPtr<ChromiumDataObject> dataObject = ChromiumDataObject::create();
- return ClipboardChromium::create(Clipboard::DragAndDrop, dataObject.get(), ClipboardWritable, m_frame);
+ return Clipboard::create(Clipboard::DragAndDrop, ClipboardWritable, ChromiumDataObject::create());
}
void EventHandler::focusDocumentView()
diff --git a/chromium/third_party/WebKit/Source/core/page/EventHandler.h b/chromium/third_party/WebKit/Source/core/page/EventHandler.h
index 5c5c4b906a4..183a4acb46c 100644
--- a/chromium/third_party/WebKit/Source/core/page/EventHandler.h
+++ b/chromium/third_party/WebKit/Source/core/page/EventHandler.h
@@ -26,23 +26,25 @@
#ifndef EventHandler_h
#define EventHandler_h
-#include "core/dom/TextEventInputType.h"
-#include "core/dom/UserGestureIndicator.h"
#include "core/editing/TextGranularity.h"
+#include "core/events/TextEventInputType.h"
#include "core/page/DragActions.h"
#include "core/page/FocusDirection.h"
-#include "core/platform/Cursor.h"
-#include "core/platform/PlatformMouseEvent.h"
-#include "core/platform/ScrollTypes.h"
-#include "core/platform/Timer.h"
-#include "core/platform/graphics/LayoutPoint.h"
#include "core/rendering/HitTestRequest.h"
+#include "core/rendering/style/RenderStyleConstants.h"
+#include "platform/Cursor.h"
+#include "platform/PlatformMouseEvent.h"
+#include "platform/Timer.h"
+#include "platform/UserGestureIndicator.h"
+#include "platform/geometry/LayoutPoint.h"
+#include "platform/scroll/ScrollTypes.h"
#include "wtf/Forward.h"
#include "wtf/HashMap.h"
#include "wtf/RefPtr.h"
namespace WebCore {
+class AutoscrollController;
class Clipboard;
class Document;
class Element;
@@ -64,6 +66,7 @@ class PlatformKeyboardEvent;
class PlatformTouchEvent;
class PlatformWheelEvent;
class RenderLayer;
+class RenderLayerScrollableArea;
class RenderObject;
class RenderWidget;
class SVGElementInstance;
@@ -77,11 +80,6 @@ class Widget;
struct DragState;
-extern const int LinkDragHysteresis;
-extern const int ImageDragHysteresis;
-extern const int TextDragHysteresis;
-extern const int GeneralDragHysteresis;
-
enum AppendTrailingWhitespace { ShouldAppendTrailingWhitespace, DontAppendTrailingWhitespace };
enum CheckDragHysteresis { ShouldCheckDragHysteresis, DontCheckDragHysteresis };
@@ -92,19 +90,17 @@ public:
~EventHandler();
void clear();
- void nodeWillBeRemoved(Node*);
+ void nodeWillBeRemoved(Node&);
void updateSelectionForMouseDrag();
Node* mousePressNode() const;
- void setMousePressNode(PassRefPtr<Node>);
#if OS(WIN)
void startPanScrolling(RenderObject*);
#endif
- void stopAutoscrollTimer();
- bool mouseDownWasInSubframe() const { return m_mouseDownWasInSubframe; }
+ void stopAutoscroll();
void dispatchFakeMouseMoveEventSoon();
void dispatchFakeMouseMoveEventSoonInQuad(const FloatQuad&);
@@ -124,45 +120,30 @@ public:
void updateDragStateAfterEditDragIfNeeded(Element* rootEditableElement);
void scheduleHoverStateUpdate();
+ void scheduleCursorUpdate();
void setResizingFrameSet(HTMLFrameSetElement*);
- void resizeLayerDestroyed();
+ void resizeScrollableAreaDestroyed();
IntPoint lastKnownMousePosition() const;
Cursor currentMouseCursor() const { return m_currentMouseCursor; }
- static Frame* subframeForTargetNode(Node*);
- static Frame* subframeForHitTestResult(const MouseEventWithHitTestResults&);
-
bool scrollOverflow(ScrollDirection, ScrollGranularity, Node* startingNode = 0);
bool scrollRecursively(ScrollDirection, ScrollGranularity, Node* startingNode = 0);
- bool logicalScrollRecursively(ScrollLogicalDirection, ScrollGranularity, Node* startingNode = 0);
bool handleMouseMoveEvent(const PlatformMouseEvent&);
void handleMouseLeaveEvent(const PlatformMouseEvent&);
- void lostMouseCapture();
-
bool handleMousePressEvent(const PlatformMouseEvent&);
bool handleMouseReleaseEvent(const PlatformMouseEvent&);
bool handleWheelEvent(const PlatformWheelEvent&);
void defaultWheelEventHandler(Node*, WheelEvent*);
- bool handlePasteGlobalSelection(const PlatformMouseEvent&);
bool handleGestureEvent(const PlatformGestureEvent&);
- bool handleGestureTap(const PlatformGestureEvent&);
- bool handleGestureLongPress(const PlatformGestureEvent&);
- bool handleGestureLongTap(const PlatformGestureEvent&);
- bool handleGestureTwoFingerTap(const PlatformGestureEvent&);
- bool handleGestureScrollUpdate(const PlatformGestureEvent&);
- bool handleGestureScrollBegin(const PlatformGestureEvent&);
bool handleGestureScrollEnd(const PlatformGestureEvent&);
- void clearGestureScrollNodes();
bool isScrollbarHandlingGestures() const;
- bool shouldApplyTouchAdjustment(const PlatformGestureEvent&) const;
-
bool bestClickableNodeForTouchPoint(const IntPoint& touchCenter, const IntSize& touchRadius, IntPoint& targetPoint, Node*& targetNode);
bool bestContextMenuNodeForTouchPoint(const IntPoint& touchCenter, const IntSize& touchRadius, IntPoint& targetPoint, Node*& targetNode);
bool bestZoomableAreaForTouchPoint(const IntPoint& touchCenter, const IntSize& touchRadius, IntRect& targetArea, Node*& targetNode);
@@ -189,16 +170,14 @@ public:
void capsLockStateMayHaveChanged(); // Only called by FrameSelection
- void sendResizeEvent(); // Only called in FrameView
- void sendScrollEvent(); // Ditto
-
bool handleTouchEvent(const PlatformTouchEvent&);
bool useHandCursor(Node*, bool isOverLink, bool shiftKey);
+ void notifyElementActivated();
+
private:
static DragState& dragState();
- static const double TextDragDelay;
PassRefPtr<Clipboard> createDraggingClipboard() const;
@@ -217,33 +196,49 @@ private:
bool handleMouseDraggedEvent(const MouseEventWithHitTestResults&);
bool handleMouseReleaseEvent(const MouseEventWithHitTestResults&);
- OptionalCursor selectCursor(const MouseEventWithHitTestResults&, Scrollbar*);
- void hoverTimerFired(Timer<EventHandler>*);
+ bool handlePasteGlobalSelection(const PlatformMouseEvent&);
- bool logicalScrollOverflow(ScrollLogicalDirection, ScrollGranularity, Node* startingNode = 0);
+ bool handleGestureTap(const PlatformGestureEvent&, const IntPoint& adjustedPoint);
+ bool handleGestureLongPress(const PlatformGestureEvent&, const IntPoint& adjustedPoint);
+ bool handleGestureLongTap(const PlatformGestureEvent&, const IntPoint& adjustedPoint);
+ bool handleGestureTwoFingerTap(const PlatformGestureEvent&, const IntPoint& adjustedPoint);
+ bool handleGestureScrollUpdate(const PlatformGestureEvent&);
+ bool handleGestureScrollBegin(const PlatformGestureEvent&);
+ void clearGestureScrollNodes();
+
+ bool shouldApplyTouchAdjustment(const PlatformGestureEvent&) const;
+
+ OptionalCursor selectCursor(const HitTestResult&, bool shiftKey);
+ OptionalCursor selectAutoCursor(const HitTestResult&, Node*, const Cursor& iBeam, bool shiftKey);
+
+ void hoverTimerFired(Timer<EventHandler>*);
+ void cursorUpdateTimerFired(Timer<EventHandler>*);
+ void activeIntervalTimerFired(Timer<EventHandler>*);
bool shouldTurnVerticalTicksIntoHorizontal(const HitTestResult&, const PlatformWheelEvent&) const;
bool mouseDownMayStartSelect() const { return m_mouseDownMayStartSelect; }
- static bool isKeyboardOptionTab(KeyboardEvent*);
-
void fakeMouseMoveEventTimerFired(Timer<EventHandler>*);
void cancelFakeMouseMoveEvent();
bool isCursorVisible() const;
+ void updateCursor();
bool isInsideScrollbar(const IntPoint&) const;
ScrollableArea* associatedScrollableArea(const RenderLayer*) const;
bool dispatchSyntheticTouchEventIfEnabled(const PlatformMouseEvent&);
- HitTestResult hitTestResultInFrame(Frame*, const LayoutPoint&, HitTestRequest::HitTestRequestType hitType = HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::DisallowShadowContent);
+ TouchAction computeEffectiveTouchAction(const Node&);
+
+ bool handleMouseEventAsEmulatedGesture(const PlatformMouseEvent&);
+ bool handleWheelEventAsEmulatedGesture(const PlatformWheelEvent&);
+ HitTestResult hitTestResultInFrame(Frame*, const LayoutPoint&, HitTestRequest::HitTestRequestType hitType = HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent);
void invalidateClick();
Node* nodeUnderMouse() const;
void updateMouseEventTargetNode(Node*, const PlatformMouseEvent&, bool fireMouseOverOut);
- void fireMouseOverOut(bool fireMouseOver = true, bool fireMouseOut = true, bool updateLastNodeUnderMouse = true);
MouseEventWithHitTestResults prepareMouseEvent(const HitTestRequest&, const PlatformMouseEvent&);
@@ -265,8 +260,6 @@ private:
bool passMouseMoveEventToSubframe(MouseEventWithHitTestResults&, Frame* subframe, HitTestResult* hoveredNode = 0);
bool passMouseReleaseEventToSubframe(MouseEventWithHitTestResults&, Frame* subframe);
- bool passSubframeEventToSubframe(MouseEventWithHitTestResults&, Frame* subframe, HitTestResult* hoveredNode = 0);
-
bool passMousePressEventToScrollbar(MouseEventWithHitTestResults&, Scrollbar*);
bool passWidgetMouseDownEventToWidget(const MouseEventWithHitTestResults&);
@@ -279,8 +272,6 @@ private:
void defaultEscapeEventHandler(KeyboardEvent*);
void defaultArrowEventHandler(FocusDirection, KeyboardEvent*);
- DragSourceAction updateDragSourceActionsAllowed() const;
-
void updateSelectionForMouseDrag(const HitTestResult&);
void updateLastScrollbarUnderMouse(Scrollbar*, bool);
@@ -291,7 +282,7 @@ private:
bool isKeyEventAllowedInFullScreen(FullscreenElementStack*, const PlatformKeyboardEvent&) const;
- bool handleGestureTapDown();
+ bool handleGestureShowPress();
bool handleScrollGestureOnResizer(Node*, const PlatformGestureEvent&);
@@ -300,6 +291,7 @@ private:
bool sendScrollEventToView(const PlatformGestureEvent&, const FloatSize&);
Frame* getSubFrameForGestureEvent(const IntPoint& touchAdjustedPoint, const PlatformGestureEvent&);
+ AutoscrollController* autoscrollController() const;
bool panScrollInProgress() const;
void setLastKnownMousePosition(const PlatformMouseEvent&);
@@ -311,7 +303,6 @@ private:
bool m_mouseDownMayStartSelect;
bool m_mouseDownMayStartDrag;
- bool m_dragMayStartSelectionInstead;
bool m_mouseDownWasSingleClickInSelection;
enum SelectionInitiationState { HaveNotStartedSelection, PlacedCaret, ExtendedSelection };
SelectionInitiationState m_selectionInitiationState;
@@ -321,6 +312,7 @@ private:
bool m_panScrollButtonPressed;
Timer<EventHandler> m_hoverTimer;
+ Timer<EventHandler> m_cursorUpdateTimer;
bool m_mouseDownMayStartAutoscroll;
bool m_mouseDownWasInSubframe;
@@ -331,7 +323,7 @@ private:
RefPtr<SVGElementInstance> m_instanceUnderMouse;
RefPtr<SVGElementInstance> m_lastInstanceUnderMouse;
- RenderLayer* m_resizeLayer;
+ RenderLayerScrollableArea* m_resizeScrollableArea;
RefPtr<Node> m_capturingMouseEventsNode;
bool m_eventHandlerWillResetCapturingMouseEventsNode;
@@ -350,7 +342,7 @@ private:
RefPtr<HTMLFrameSetElement> m_frameSetBeingResized;
- LayoutSize m_offsetFromResizeCorner; // In the coords of m_resizeLayer.
+ LayoutSize m_offsetFromResizeCorner; // In the coords of m_resizeScrollableArea.
bool m_mousePositionIsUnknown;
IntPoint m_lastKnownMousePosition;
@@ -381,6 +373,14 @@ private:
bool m_didStartDrag;
bool m_longTapShouldInvokeContextMenu;
+ OwnPtr<IntPoint> m_lastSyntheticPinchAnchorCss;
+ OwnPtr<IntPoint> m_lastSyntheticPinchAnchorDip;
+ OwnPtr<IntPoint> m_lastSyntheticPanLocation;
+ float m_syntheticPageScaleFactor;
+
+ Timer<EventHandler> m_activeIntervalTimer;
+ double m_lastShowPressTimestamp;
+ RefPtr<Element> m_lastDeferredTapElement;
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/page/EventSource.cpp b/chromium/third_party/WebKit/Source/core/page/EventSource.cpp
index d9cedc52c28..6a9600c5660 100644
--- a/chromium/third_party/WebKit/Source/core/page/EventSource.cpp
+++ b/chromium/third_party/WebKit/Source/core/page/EventSource.cpp
@@ -38,32 +38,32 @@
#include "bindings/v8/ScriptController.h"
#include "bindings/v8/SerializedScriptValue.h"
#include "core/dom/Document.h"
-#include "core/dom/Event.h"
#include "core/dom/ExceptionCode.h"
-#include "core/dom/MessageEvent.h"
-#include "core/dom/ScriptExecutionContext.h"
+#include "core/dom/ExecutionContext.h"
+#include "core/events/Event.h"
+#include "core/events/MessageEvent.h"
#include "core/fetch/TextResourceDecoder.h"
+#include "core/frame/ContentSecurityPolicy.h"
+#include "core/frame/DOMWindow.h"
+#include "core/frame/Frame.h"
#include "core/loader/ThreadableLoader.h"
-#include "core/page/ContentSecurityPolicy.h"
-#include "core/page/DOMWindow.h"
-#include "core/page/Frame.h"
-#include "core/platform/network/ResourceError.h"
-#include "core/platform/network/ResourceRequest.h"
-#include "core/platform/network/ResourceResponse.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/network/ResourceError.h"
+#include "platform/network/ResourceRequest.h"
+#include "platform/network/ResourceResponse.h"
+#include "platform/weborigin/SecurityOrigin.h"
#include "wtf/text/StringBuilder.h"
namespace WebCore {
const unsigned long long EventSource::defaultReconnectDelay = 3000;
-inline EventSource::EventSource(ScriptExecutionContext* context, const KURL& url, const Dictionary& eventSourceInit)
+inline EventSource::EventSource(ExecutionContext* context, const KURL& url, const Dictionary& eventSourceInit)
: ActiveDOMObject(context)
, m_url(url)
, m_withCredentials(false)
, m_state(CONNECTING)
, m_decoder(TextResourceDecoder::create("text/plain", "UTF-8"))
- , m_reconnectTimer(this, &EventSource::reconnectTimerFired)
+ , m_connectTimer(this, &EventSource::connectTimerFired)
, m_discardTrailingNewline(false)
, m_requestInFlight(false)
, m_reconnectDelay(defaultReconnectDelay)
@@ -72,16 +72,16 @@ inline EventSource::EventSource(ScriptExecutionContext* context, const KURL& url
eventSourceInit.get("withCredentials", m_withCredentials);
}
-PassRefPtr<EventSource> EventSource::create(ScriptExecutionContext* context, const String& url, const Dictionary& eventSourceInit, ExceptionState& es)
+PassRefPtr<EventSource> EventSource::create(ExecutionContext* context, const String& url, const Dictionary& eventSourceInit, ExceptionState& exceptionState)
{
if (url.isEmpty()) {
- es.throwDOMException(SyntaxError, "Cannot open an EventSource to an empty URL.");
+ exceptionState.throwDOMException(SyntaxError, "Cannot open an EventSource to an empty URL.");
return 0;
}
KURL fullURL = context->completeURL(url);
if (!fullURL.isValid()) {
- es.throwDOMException(SyntaxError, "Cannot open an EventSource to '" + url + "'. The URL is invalid.");
+ exceptionState.throwDOMException(SyntaxError, "Cannot open an EventSource to '" + url + "'. The URL is invalid.");
return 0;
}
@@ -89,18 +89,18 @@ PassRefPtr<EventSource> EventSource::create(ScriptExecutionContext* context, con
bool shouldBypassMainWorldContentSecurityPolicy = false;
if (context->isDocument()) {
Document* document = toDocument(context);
- shouldBypassMainWorldContentSecurityPolicy = document->frame()->script()->shouldBypassMainWorldContentSecurityPolicy();
+ shouldBypassMainWorldContentSecurityPolicy = document->frame()->script().shouldBypassMainWorldContentSecurityPolicy();
}
if (!shouldBypassMainWorldContentSecurityPolicy && !context->contentSecurityPolicy()->allowConnectToSource(fullURL)) {
// We can safely expose the URL to JavaScript, as this exception is generate synchronously before any redirects take place.
- es.throwSecurityError("Refused to connect to '" + fullURL.elidedString() + "' because it violates the document's Content Security Policy.");
+ exceptionState.throwSecurityError("Refused to connect to '" + fullURL.elidedString() + "' because it violates the document's Content Security Policy.");
return 0;
}
RefPtr<EventSource> source = adoptRef(new EventSource(context, fullURL, eventSourceInit));
source->setPendingActivity(source.get());
- source->connect();
+ source->scheduleInitialConnect();
source->suspendIfNeeded();
return source.release();
@@ -112,6 +112,14 @@ EventSource::~EventSource()
ASSERT(!m_requestInFlight);
}
+void EventSource::scheduleInitialConnect()
+{
+ ASSERT(m_state == CONNECTING);
+ ASSERT(!m_requestInFlight);
+
+ m_connectTimer.startOneShot(0);
+}
+
void EventSource::connect()
{
ASSERT(m_state == CONNECTING);
@@ -124,7 +132,7 @@ void EventSource::connect()
if (!m_lastEventId.isEmpty())
request.setHTTPHeaderField("Last-Event-ID", m_lastEventId);
- SecurityOrigin* origin = scriptExecutionContext()->securityOrigin();
+ SecurityOrigin* origin = executionContext()->securityOrigin();
ThreadableLoaderOptions options;
options.sendLoadCallbacks = SendCallbacks;
@@ -135,9 +143,9 @@ void EventSource::connect()
options.crossOriginRequestPolicy = UseAccessControl;
options.dataBufferingPolicy = DoNotBufferData;
options.securityOrigin = origin;
- options.contentSecurityPolicyEnforcement = ContentSecurityPolicy::shouldBypassMainWorld(scriptExecutionContext()) ? DoNotEnforceContentSecurityPolicy : EnforceConnectSrcDirective;
+ options.contentSecurityPolicyEnforcement = ContentSecurityPolicy::shouldBypassMainWorld(executionContext()) ? DoNotEnforceContentSecurityPolicy : EnforceConnectSrcDirective;
- m_loader = ThreadableLoader::create(scriptExecutionContext(), this, request, options);
+ m_loader = ThreadableLoader::create(executionContext(), this, request, options);
if (m_loader)
m_requestInFlight = true;
@@ -159,11 +167,11 @@ void EventSource::networkRequestEnded()
void EventSource::scheduleReconnect()
{
m_state = CONNECTING;
- m_reconnectTimer.startOneShot(m_reconnectDelay / 1000.0);
- dispatchEvent(Event::create(eventNames().errorEvent));
+ m_connectTimer.startOneShot(m_reconnectDelay / 1000.0);
+ dispatchEvent(Event::create(EventTypeNames::error));
}
-void EventSource::reconnectTimerFired(Timer<EventSource>*)
+void EventSource::connectTimerFired(Timer<EventSource>*)
{
connect();
}
@@ -191,8 +199,8 @@ void EventSource::close()
}
// Stop trying to reconnect if EventSource was explicitly closed or if ActiveDOMObject::stop() was called.
- if (m_reconnectTimer.isActive()) {
- m_reconnectTimer.stop();
+ if (m_connectTimer.isActive()) {
+ m_connectTimer.stop();
unsetPendingActivity(this);
}
@@ -204,12 +212,12 @@ void EventSource::close()
const AtomicString& EventSource::interfaceName() const
{
- return eventNames().interfaceForEventSource;
+ return EventTargetNames::EventSource;
}
-ScriptExecutionContext* EventSource::scriptExecutionContext() const
+ExecutionContext* EventSource::executionContext() const
{
- return ActiveDOMObject::scriptExecutionContext();
+ return ActiveDOMObject::executionContext();
}
void EventSource::didReceiveResponse(unsigned long, const ResourceResponse& response)
@@ -231,7 +239,7 @@ void EventSource::didReceiveResponse(unsigned long, const ResourceResponse& resp
message.append(charset);
message.appendLiteral("\") that is not UTF-8. Aborting the connection.");
// FIXME: We are missing the source line.
- scriptExecutionContext()->addConsoleMessage(JSMessageSource, ErrorMessageLevel, message.toString());
+ executionContext()->addConsoleMessage(JSMessageSource, ErrorMessageLevel, message.toString());
}
} else {
// To keep the signal-to-noise ratio low, we only log 200-response with an invalid MIME type.
@@ -241,16 +249,16 @@ void EventSource::didReceiveResponse(unsigned long, const ResourceResponse& resp
message.append(response.mimeType());
message.appendLiteral("\") that is not \"text/event-stream\". Aborting the connection.");
// FIXME: We are missing the source line.
- scriptExecutionContext()->addConsoleMessage(JSMessageSource, ErrorMessageLevel, message.toString());
+ executionContext()->addConsoleMessage(JSMessageSource, ErrorMessageLevel, message.toString());
}
}
if (responseIsValid) {
m_state = OPEN;
- dispatchEvent(Event::create(eventNames().openEvent));
+ dispatchEvent(Event::create(EventTypeNames::open));
} else {
m_loader->cancel();
- dispatchEvent(Event::create(eventNames().errorEvent));
+ dispatchEvent(Event::create(EventTypeNames::error));
}
}
@@ -293,7 +301,7 @@ void EventSource::didFail(const ResourceError& error)
void EventSource::didFailAccessControlCheck(const ResourceError& error)
{
String message = "EventSource cannot load " + error.failingURL() + ". " + error.localizedDescription();
- scriptExecutionContext()->addConsoleMessage(JSMessageSource, ErrorMessageLevel, message);
+ executionContext()->addConsoleMessage(JSMessageSource, ErrorMessageLevel, message);
abortConnectionAttempt();
}
@@ -306,12 +314,16 @@ void EventSource::didFailRedirectCheck()
void EventSource::abortConnectionAttempt()
{
ASSERT(m_state == CONNECTING);
- ASSERT(m_requestInFlight);
- m_loader->cancel();
+ if (m_requestInFlight) {
+ m_loader->cancel();
+ } else {
+ m_state = CLOSED;
+ unsetPendingActivity(this);
+ }
ASSERT(m_state == CLOSED);
- dispatchEvent(Event::create(eventNames().errorEvent));
+ dispatchEvent(Event::create(EventTypeNames::error));
}
void EventSource::parseEventStream()
@@ -416,19 +428,9 @@ void EventSource::stop()
PassRefPtr<MessageEvent> EventSource::createMessageEvent()
{
RefPtr<MessageEvent> event = MessageEvent::create();
- event->initMessageEvent(m_eventName.isEmpty() ? eventNames().messageEvent : AtomicString(m_eventName), false, false, SerializedScriptValue::create(String(m_data)), m_eventStreamOrigin, m_lastEventId, 0, nullptr);
+ event->initMessageEvent(m_eventName.isEmpty() ? EventTypeNames::message : AtomicString(m_eventName), false, false, SerializedScriptValue::create(String(m_data)), m_eventStreamOrigin, m_lastEventId, 0, nullptr);
m_data.clear();
return event.release();
}
-EventTargetData* EventSource::eventTargetData()
-{
- return &m_eventTargetData;
-}
-
-EventTargetData* EventSource::ensureEventTargetData()
-{
- return &m_eventTargetData;
-}
-
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/page/EventSource.h b/chromium/third_party/WebKit/Source/core/page/EventSource.h
index c407e09b962..66ea83aa1b8 100644
--- a/chromium/third_party/WebKit/Source/core/page/EventSource.h
+++ b/chromium/third_party/WebKit/Source/core/page/EventSource.h
@@ -34,10 +34,10 @@
#include "bindings/v8/ScriptWrappable.h"
#include "core/dom/ActiveDOMObject.h"
-#include "core/dom/EventTarget.h"
+#include "core/events/EventTarget.h"
#include "core/loader/ThreadableLoaderClient.h"
-#include "core/platform/Timer.h"
-#include "weborigin/KURL.h"
+#include "platform/Timer.h"
+#include "platform/weborigin/KURL.h"
#include "wtf/RefPtr.h"
#include "wtf/Vector.h"
@@ -50,10 +50,11 @@ class ResourceResponse;
class TextResourceDecoder;
class ThreadableLoader;
-class EventSource : public RefCounted<EventSource>, public ScriptWrappable, public EventTarget, private ThreadableLoaderClient, public ActiveDOMObject {
+class EventSource : public RefCounted<EventSource>, public ScriptWrappable, public EventTargetWithInlineData, private ThreadableLoaderClient, public ActiveDOMObject {
WTF_MAKE_FAST_ALLOCATED;
+ REFCOUNTED_EVENT_TARGET(EventSource);
public:
- static PassRefPtr<EventSource> create(ScriptExecutionContext*, const String& url, const Dictionary&, ExceptionState&);
+ static PassRefPtr<EventSource> create(ExecutionContext*, const String& url, const Dictionary&, ExceptionState&);
virtual ~EventSource();
static const unsigned long long defaultReconnectDelay;
@@ -74,21 +75,19 @@ public:
void close();
- using RefCounted<EventSource>::ref;
- using RefCounted<EventSource>::deref;
+ virtual const AtomicString& interfaceName() const OVERRIDE;
+ virtual ExecutionContext* executionContext() const OVERRIDE;
- virtual const AtomicString& interfaceName() const;
- virtual ScriptExecutionContext* scriptExecutionContext() const;
-
- virtual void stop();
+ // ActiveDOMObject
+ //
+ // Note: suspend() is noop since PageGroupLoadDeferrer calls
+ // Page::setDefersLoading() and it defers delivery of events from the
+ // loader, and therefore the methods of this class for receiving
+ // asynchronous events from the loader won't be invoked.
+ virtual void stop() OVERRIDE;
private:
- EventSource(ScriptExecutionContext*, const KURL&, const Dictionary&);
-
- virtual void refEventTarget() { ref(); }
- virtual void derefEventTarget() { deref(); }
- virtual EventTargetData* eventTargetData();
- virtual EventTargetData* ensureEventTargetData();
+ EventSource(ExecutionContext*, const KURL&, const Dictionary&);
virtual void didReceiveResponse(unsigned long, const ResourceResponse&);
virtual void didReceiveData(const char*, int);
@@ -97,10 +96,11 @@ private:
virtual void didFailAccessControlCheck(const ResourceError&);
virtual void didFailRedirectCheck();
+ void scheduleInitialConnect();
void connect();
void networkRequestEnded();
void scheduleReconnect();
- void reconnectTimerFired(Timer<EventSource>*);
+ void connectTimerFired(Timer<EventSource>*);
void abortConnectionAttempt();
void parseEventStream();
void parseEventStreamLine(unsigned pos, int fieldLength, int lineLength);
@@ -110,9 +110,9 @@ private:
bool m_withCredentials;
State m_state;
- RefPtr<TextResourceDecoder> m_decoder;
+ OwnPtr<TextResourceDecoder> m_decoder;
RefPtr<ThreadableLoader> m_loader;
- Timer<EventSource> m_reconnectTimer;
+ Timer<EventSource> m_connectTimer;
Vector<UChar> m_receiveBuf;
bool m_discardTrailingNewline;
bool m_requestInFlight;
@@ -123,8 +123,6 @@ private:
String m_lastEventId;
unsigned long long m_reconnectDelay;
String m_eventStreamOrigin;
-
- EventTargetData m_eventTargetData;
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/page/EventSource.idl b/chromium/third_party/WebKit/Source/core/page/EventSource.idl
index 6aeade10232..3562791dd24 100644
--- a/chromium/third_party/WebKit/Source/core/page/EventSource.idl
+++ b/chromium/third_party/WebKit/Source/core/page/EventSource.idl
@@ -30,11 +30,11 @@
*/
[
- GlobalContext=Window&WorkerGlobalScope,
ActiveDOMObject,
Constructor(DOMString url, optional Dictionary eventSourceInit),
- ConstructorCallWith=ScriptExecutionContext,
- ConstructorRaisesException
+ ConstructorCallWith=ExecutionContext,
+ GlobalContext=Window&WorkerGlobalScope,
+ RaisesException=Constructor,
] interface EventSource : EventTarget {
readonly attribute DOMString URL; // Lowercased .url is the one in the spec, but leaving .URL for compatibility reasons.
diff --git a/chromium/third_party/WebKit/Source/core/page/FocusController.cpp b/chromium/third_party/WebKit/Source/core/page/FocusController.cpp
index 81c41299e3a..686e013aa82 100644
--- a/chromium/third_party/WebKit/Source/core/page/FocusController.cpp
+++ b/chromium/third_party/WebKit/Source/core/page/FocusController.cpp
@@ -33,8 +33,6 @@
#include "core/dom/Document.h"
#include "core/dom/Element.h"
#include "core/dom/ElementTraversal.h"
-#include "core/dom/Event.h"
-#include "core/dom/EventNames.h"
#include "core/dom/NodeTraversal.h"
#include "core/dom/Range.h"
#include "core/dom/shadow/ElementShadow.h"
@@ -42,18 +40,21 @@
#include "core/editing/Editor.h"
#include "core/editing/FrameSelection.h"
#include "core/editing/htmlediting.h" // For firstPositionInOrBeforeNode
+#include "core/events/Event.h"
+#include "core/events/ThreadLocalEventNames.h"
+#include "core/frame/DOMWindow.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
#include "core/html/HTMLAreaElement.h"
#include "core/html/HTMLImageElement.h"
#include "core/html/HTMLTextAreaElement.h"
#include "core/html/shadow/HTMLShadowElement.h"
#include "core/page/Chrome.h"
-#include "core/page/EditorClient.h"
+#include "core/page/ChromeClient.h"
#include "core/page/EventHandler.h"
-#include "core/page/Frame.h"
#include "core/page/FrameTree.h"
-#include "core/page/FrameView.h"
#include "core/page/Page.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
#include "core/page/SpatialNavigation.h"
#include "core/rendering/HitTestResult.h"
@@ -79,7 +80,7 @@ Element* FocusNavigationScope::owner() const
Node* root = rootNode();
if (root->isShadowRoot()) {
ShadowRoot* shadowRoot = toShadowRoot(root);
- return shadowRoot->isYoungest() ? shadowRoot->host() : shadowRoot->insertionPoint();
+ return shadowRoot->isYoungest() ? shadowRoot->host() : shadowRoot->shadowInsertionPointOfYoungerShadowRoot();
}
if (Frame* frame = root->document().frame())
return frame->ownerElement();
@@ -99,9 +100,10 @@ FocusNavigationScope FocusNavigationScope::focusNavigationScopeOf(Node* node)
FocusNavigationScope FocusNavigationScope::ownedByNonFocusableFocusScopeOwner(Node* node)
{
+ ASSERT(node);
if (isShadowHost(node))
return FocusNavigationScope::ownedByShadowHost(node);
- ASSERT(isActiveShadowInsertionPoint(node));
+ ASSERT(isActiveShadowInsertionPoint(*node));
return FocusNavigationScope::ownedByShadowInsertionPoint(toHTMLShadowElement(node));
}
@@ -135,11 +137,27 @@ static inline void dispatchEventsOnWindowAndFocusedNode(Document* document, bool
return;
}
- if (!focused && document->focusedElement())
- document->focusedElement()->dispatchBlurEvent(0);
- document->dispatchWindowEvent(Event::create(focused ? eventNames().focusEvent : eventNames().blurEvent));
- if (focused && document->focusedElement())
- document->focusedElement()->dispatchFocusEvent(0, FocusDirectionPage);
+ if (!focused && document->focusedElement()) {
+ RefPtr<Element> focusedElement(document->focusedElement());
+ focusedElement->dispatchBlurEvent(0);
+ if (focusedElement == document->focusedElement()) {
+ focusedElement->dispatchFocusOutEvent(EventTypeNames::focusout, 0);
+ if (focusedElement == document->focusedElement())
+ focusedElement->dispatchFocusOutEvent(EventTypeNames::DOMFocusOut, 0);
+ }
+ }
+
+ if (DOMWindow* window = document->domWindow())
+ window->dispatchEvent(Event::create(focused ? EventTypeNames::focus : EventTypeNames::blur));
+ if (focused && document->focusedElement()) {
+ RefPtr<Element> focusedElement(document->focusedElement());
+ focusedElement->dispatchFocusEvent(0, FocusDirectionPage);
+ if (focusedElement == document->focusedElement()) {
+ document->focusedElement()->dispatchFocusInEvent(EventTypeNames::focusin, 0);
+ if (focusedElement == document->focusedElement())
+ document->focusedElement()->dispatchFocusInEvent(EventTypeNames::DOMFocusIn, 0);
+ }
+ }
}
static inline bool hasCustomFocusLogic(Element* element)
@@ -147,6 +165,7 @@ static inline bool hasCustomFocusLogic(Element* element)
return element->isHTMLElement() && toHTMLElement(element)->hasCustomFocusLogic();
}
+#if !ASSERT_DISABLED
static inline bool isNonFocusableShadowHost(Node* node)
{
ASSERT(node);
@@ -155,6 +174,7 @@ static inline bool isNonFocusableShadowHost(Node* node)
Element* element = toElement(node);
return !element->isFocusable() && isShadowHost(element) && !hasCustomFocusLogic(element);
}
+#endif
static inline bool isNonKeyboardFocusableShadowHost(Node* node)
{
@@ -177,7 +197,7 @@ static inline bool isKeyboardFocusableShadowHost(Node* node)
static inline bool isNonFocusableFocusScopeOwner(Node* node)
{
ASSERT(node);
- return isNonKeyboardFocusableShadowHost(node) || isActiveShadowInsertionPoint(node);
+ return isNonKeyboardFocusableShadowHost(node) || isActiveShadowInsertionPoint(*node);
}
static inline int adjustedTabIndex(Node* node)
@@ -222,12 +242,12 @@ void FocusController::setFocusedFrame(PassRefPtr<Frame> frame)
// Now that the frame is updated, fire events and update the selection focused states of both frames.
if (oldFrame && oldFrame->view()) {
oldFrame->selection().setFocused(false);
- oldFrame->document()->dispatchWindowEvent(Event::create(eventNames().blurEvent));
+ oldFrame->domWindow()->dispatchEvent(Event::create(EventTypeNames::blur));
}
if (newFrame && newFrame->view() && isFocused()) {
newFrame->selection().setFocused(true);
- newFrame->document()->dispatchWindowEvent(Event::create(eventNames().focusEvent));
+ newFrame->domWindow()->dispatchEvent(Event::create(EventTypeNames::focus));
}
m_isChangingFocusedFrame = false;
@@ -248,7 +268,7 @@ void FocusController::setFocused(bool focused)
m_isFocused = focused;
if (!m_isFocused)
- focusedOrMainFrame()->eventHandler()->stopAutoscrollTimer();
+ focusedOrMainFrame()->eventHandler().stopAutoscroll();
if (!m_focusedFrame)
setFocusedFrame(m_page->mainFrame());
@@ -352,7 +372,7 @@ bool FocusController::advanceFocusInDocumentOrder(FocusDirection direction, bool
// FIXME: May need a way to focus a document here.
return false;
- Element* element = toElement(node.get());
+ Element* element = toElement(node);
if (element->isFrameOwnerElement() && (!element->isPluginElement() || !element->isKeyboardFocusable())) {
// We focus frames rather than frame owners.
// FIXME: We should not focus frames that have no scrollbars, as focusing them isn't useful to the user.
@@ -380,8 +400,7 @@ bool FocusController::advanceFocusInDocumentOrder(FocusDirection direction, bool
if (caretBrowsing) {
Position position = firstPositionInOrBeforeNode(element);
VisibleSelection newSelection(position, position, DOWNSTREAM);
- if (frame->selection().shouldChangeSelection(newSelection))
- frame->selection().setSelection(newSelection);
+ frame->selection().setSelection(newSelection);
}
element->focus(false, direction);
@@ -449,7 +468,7 @@ Node* FocusController::findFocusableNode(FocusDirection direction, FocusNavigati
Node* FocusController::findNodeWithExactTabIndex(Node* start, int tabIndex, FocusDirection direction)
{
// Search is inclusive of start
- for (Node* node = start; node; node = direction == FocusDirectionForward ? NodeTraversal::next(node) : NodeTraversal::previous(node)) {
+ for (Node* node = start; node; node = direction == FocusDirectionForward ? NodeTraversal::next(*node) : NodeTraversal::previous(*node)) {
if (shouldVisit(node) && adjustedTabIndex(node) == tabIndex)
return node;
}
@@ -461,7 +480,7 @@ static Node* nextNodeWithGreaterTabIndex(Node* start, int tabIndex)
// Search is inclusive of start
int winningTabIndex = std::numeric_limits<short>::max() + 1;
Node* winner = 0;
- for (Node* node = start; node; node = NodeTraversal::next(node)) {
+ for (Node* node = start; node; node = NodeTraversal::next(*node)) {
if (shouldVisit(node) && node->tabIndex() > tabIndex && node->tabIndex() < winningTabIndex) {
winner = node;
winningTabIndex = node->tabIndex();
@@ -476,7 +495,7 @@ static Node* previousNodeWithLowerTabIndex(Node* start, int tabIndex)
// Search is inclusive of start
int winningTabIndex = 0;
Node* winner = 0;
- for (Node* node = start; node; node = NodeTraversal::previous(node)) {
+ for (Node* node = start; node; node = NodeTraversal::previous(*node)) {
int currentTabIndex = adjustedTabIndex(node);
if ((shouldVisit(node) || isNonKeyboardFocusableShadowHost(node)) && currentTabIndex < tabIndex && currentTabIndex > winningTabIndex) {
winner = node;
@@ -492,14 +511,14 @@ Node* FocusController::nextFocusableNode(FocusNavigationScope scope, Node* start
int tabIndex = adjustedTabIndex(start);
// If a node is excluded from the normal tabbing cycle, the next focusable node is determined by tree order
if (tabIndex < 0) {
- for (Node* node = NodeTraversal::next(start); node; node = NodeTraversal::next(node)) {
+ for (Node* node = NodeTraversal::next(*start); node; node = NodeTraversal::next(*node)) {
if (shouldVisit(node) && adjustedTabIndex(node) >= 0)
return node;
}
}
// First try to find a node with the same tabindex as start that comes after start in the scope.
- if (Node* winner = findNodeWithExactTabIndex(NodeTraversal::next(start), tabIndex, FocusDirectionForward))
+ if (Node* winner = findNodeWithExactTabIndex(NodeTraversal::next(*start), tabIndex, FocusDirectionForward))
return winner;
if (!tabIndex)
@@ -530,7 +549,7 @@ Node* FocusController::previousFocusableNode(FocusNavigationScope scope, Node* s
Node* startingNode;
int startingTabIndex;
if (start) {
- startingNode = NodeTraversal::previous(start);
+ startingNode = NodeTraversal::previous(*start);
startingTabIndex = adjustedTabIndex(start);
} else {
startingNode = last;
@@ -539,7 +558,7 @@ Node* FocusController::previousFocusableNode(FocusNavigationScope scope, Node* s
// However, if a node is excluded from the normal tabbing cycle, the previous focusable node is determined by tree order
if (startingTabIndex < 0) {
- for (Node* node = startingNode; node; node = NodeTraversal::previous(node)) {
+ for (Node* node = startingNode; node; node = NodeTraversal::previous(*node)) {
if (shouldVisit(node) && adjustedTabIndex(node) >= 0)
return node;
}
@@ -559,13 +578,7 @@ static bool relinquishesEditingFocus(Node *node)
{
ASSERT(node);
ASSERT(node->rendererIsEditable());
-
- Node* root = node->rootEditableElement();
- Frame* frame = node->document().frame();
- if (!frame || !root)
- return false;
-
- return frame->editor().shouldEndEditing(rangeOfContents(root).get());
+ return node->document().frame() && node->rootEditableElement();
}
static void clearSelectionIfNeeded(Frame* oldFocusedFrame, Frame* newFocusedFrame, Node* newFocusedNode)
@@ -588,7 +601,7 @@ static void clearSelectionIfNeeded(Frame* oldFocusedFrame, Frame* newFocusedFram
if (selectionStartNode == newFocusedNode || selectionStartNode->isDescendantOf(newFocusedNode) || selectionStartNode->deprecatedShadowAncestorNode() == newFocusedNode)
return;
- if (Node* mousePressNode = newFocusedFrame->eventHandler()->mousePressNode()) {
+ if (Node* mousePressNode = newFocusedFrame->eventHandler().mousePressNode()) {
if (mousePressNode->renderer() && !mousePressNode->canStartSelection()) {
// Don't clear the selection for contentEditable elements, but do clear it for input and textarea. See bug 38696.
Node* root = selection.rootEditableElement();
@@ -611,27 +624,25 @@ bool FocusController::setFocusedElement(Element* element, PassRefPtr<Frame> newF
RefPtr<Document> oldDocument = oldFocusedFrame ? oldFocusedFrame->document() : 0;
Element* oldFocusedElement = oldDocument ? oldDocument->focusedElement() : 0;
- if (oldFocusedElement == element)
+ if (element && oldFocusedElement == element)
return true;
// FIXME: Might want to disable this check for caretBrowsing
if (oldFocusedElement && oldFocusedElement->isRootEditableElement() && !relinquishesEditingFocus(oldFocusedElement))
return false;
- m_page->editorClient().willSetInputMethodState();
+ m_page->chrome().client().willSetInputMethodState();
- clearSelectionIfNeeded(oldFocusedFrame.get(), newFocusedFrame.get(), element);
+ RefPtr<Document> newDocument;
+ if (element)
+ newDocument = &element->document();
+ else if (newFocusedFrame)
+ newDocument = newFocusedFrame->document();
- if (!element) {
- if (oldDocument)
- oldDocument->setFocusedElement(0);
+ if (newDocument && oldDocument == newDocument && newDocument->focusedElement() == element)
return true;
- }
- RefPtr<Document> newDocument = &element->document();
-
- if (newDocument && newDocument->focusedElement() == element)
- return true;
+ clearSelectionIfNeeded(oldFocusedFrame.get(), newFocusedFrame.get(), element);
if (oldDocument && oldDocument != newDocument)
oldDocument->setFocusedElement(0);
@@ -689,7 +700,7 @@ void FocusController::setContainingWindowIsVisible(bool containingWindowIsVisibl
contentAreaDidShowOrHide(view, containingWindowIsVisible);
- for (Frame* frame = m_page->mainFrame(); frame; frame = frame->tree()->traverseNext()) {
+ for (Frame* frame = m_page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
FrameView* frameView = frame->view();
if (!frameView)
continue;
@@ -737,7 +748,7 @@ static void updateFocusCandidateIfNeeded(FocusDirection direction, const FocusCa
// If 2 nodes are intersecting, do hit test to find which node in on top.
LayoutUnit x = intersectionRect.x() + intersectionRect.width() / 2;
LayoutUnit y = intersectionRect.y() + intersectionRect.height() / 2;
- HitTestResult result = candidate.visibleNode->document().page()->mainFrame()->eventHandler()->hitTestResultAtPoint(IntPoint(x, y), HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::IgnoreClipping | HitTestRequest::DisallowShadowContent);
+ HitTestResult result = candidate.visibleNode->document().page()->mainFrame()->eventHandler().hitTestResultAtPoint(IntPoint(x, y), HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::IgnoreClipping | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent);
if (candidate.visibleNode->contains(result.innerNode())) {
closest = candidate;
return;
@@ -756,9 +767,8 @@ static void updateFocusCandidateIfNeeded(FocusDirection direction, const FocusCa
closest = candidate;
}
-void FocusController::findFocusCandidateInContainer(Node* container, const LayoutRect& startingRect, FocusDirection direction, FocusCandidate& closest)
+void FocusController::findFocusCandidateInContainer(Node& container, const LayoutRect& startingRect, FocusDirection direction, FocusCandidate& closest)
{
- ASSERT(container);
Element* focusedElement = (focusedFrame() && focusedFrame()->document()) ? focusedFrame()->document()->focusedElement() : 0;
Element* element = ElementTraversal::firstWithin(container);
@@ -768,8 +778,8 @@ void FocusController::findFocusCandidateInContainer(Node* container, const Layou
current.visibleNode = focusedElement;
for (; element; element = (element->isFrameOwnerElement() || canScrollInDirection(element, direction))
- ? ElementTraversal::nextSkippingChildren(element, container)
- : ElementTraversal::next(element, container)) {
+ ? ElementTraversal::nextSkippingChildren(*element, &container)
+ : ElementTraversal::next(*element, &container)) {
if (element == focusedElement)
continue;
@@ -780,7 +790,7 @@ void FocusController::findFocusCandidateInContainer(Node* container, const Layou
if (candidate.isNull())
continue;
- candidate.enclosingScrollableBox = container;
+ candidate.enclosingScrollableBox = &container;
updateFocusCandidateIfNeeded(direction, current, candidate, closest);
}
}
@@ -797,7 +807,7 @@ bool FocusController::advanceFocusDirectionallyInContainer(Node* container, cons
// Find the closest node within current container in the direction of the navigation.
FocusCandidate focusCandidate;
- findFocusCandidateInContainer(container, newStartingRect, direction, focusCandidate);
+ findFocusCandidateInContainer(*container, newStartingRect, direction, focusCandidate);
if (focusCandidate.isNull()) {
// Nothing to focus, scroll if possible.
diff --git a/chromium/third_party/WebKit/Source/core/page/FocusController.h b/chromium/third_party/WebKit/Source/core/page/FocusController.h
index ff245c6fb84..38069eb4919 100644
--- a/chromium/third_party/WebKit/Source/core/page/FocusController.h
+++ b/chromium/third_party/WebKit/Source/core/page/FocusController.h
@@ -27,7 +27,7 @@
#define FocusController_h
#include "core/page/FocusDirection.h"
-#include "core/platform/graphics/LayoutRect.h"
+#include "platform/geometry/LayoutRect.h"
#include "wtf/Forward.h"
#include "wtf/Noncopyable.h"
#include "wtf/RefPtr.h"
@@ -112,7 +112,7 @@ private:
Node* findNodeWithExactTabIndex(Node* start, int tabIndex, FocusDirection);
bool advanceFocusDirectionallyInContainer(Node* container, const LayoutRect& startingRect, FocusDirection);
- void findFocusCandidateInContainer(Node* container, const LayoutRect& startingRect, FocusDirection, FocusCandidate& closest);
+ void findFocusCandidateInContainer(Node& container, const LayoutRect& startingRect, FocusDirection, FocusCandidate& closest);
Page* m_page;
RefPtr<Frame> m_focusedFrame;
diff --git a/chromium/third_party/WebKit/Source/core/page/Frame.cpp b/chromium/third_party/WebKit/Source/core/page/Frame.cpp
deleted file mode 100644
index c9ed2a30b6d..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/Frame.cpp
+++ /dev/null
@@ -1,720 +0,0 @@
-/*
- * Copyright (C) 1998, 1999 Torben Weis <weis@kde.org>
- * 1999 Lars Knoll <knoll@kde.org>
- * 1999 Antti Koivisto <koivisto@kde.org>
- * 2000 Simon Hausmann <hausmann@kde.org>
- * 2000 Stefan Schimanski <1Stein@gmx.de>
- * 2001 George Staikos <staikos@kde.org>
- * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
- * Copyright (C) 2005 Alexey Proskuryakov <ap@nypop.com>
- * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
- * Copyright (C) 2008 Eric Seidel <eric@webkit.org>
- * Copyright (C) 2008 Google Inc.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-#include "core/page/Frame.h"
-
-#include "RuntimeEnabledFeatures.h"
-#include "bindings/v8/ScriptController.h"
-#include "core/dom/DocumentType.h"
-#include "core/dom/Event.h"
-#include "core/dom/WheelController.h"
-#include "core/editing/Editor.h"
-#include "core/editing/FrameSelection.h"
-#include "core/editing/InputMethodController.h"
-#include "core/editing/htmlediting.h"
-#include "core/editing/markup.h"
-#include "core/fetch/ResourceFetcher.h"
-#include "core/html/HTMLFrameElementBase.h"
-#include "core/inspector/InspectorInstrumentation.h"
-#include "core/loader/FrameLoader.h"
-#include "core/loader/FrameLoaderClient.h"
-#include "core/page/Chrome.h"
-#include "core/page/ChromeClient.h"
-#include "core/page/DOMWindow.h"
-#include "core/page/EventHandler.h"
-#include "core/page/FocusController.h"
-#include "core/page/FrameDestructionObserver.h"
-#include "core/page/FrameView.h"
-#include "core/page/Page.h"
-#include "core/page/Settings.h"
-#include "core/page/animation/AnimationController.h"
-#include "core/page/scrolling/ScrollingCoordinator.h"
-#include "core/platform/DragImage.h"
-#include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/graphics/ImageBuffer.h"
-#include "core/rendering/HitTestResult.h"
-#include "core/rendering/RenderLayerCompositor.h"
-#include "core/rendering/RenderPart.h"
-#include "core/rendering/RenderView.h"
-#include "core/svg/SVGDocument.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/RefCountedLeakCounter.h"
-#include "wtf/StdLibExtras.h"
-
-using namespace std;
-
-namespace WebCore {
-
-using namespace HTMLNames;
-
-DEFINE_DEBUG_ONLY_GLOBAL(WTF::RefCountedLeakCounter, frameCounter, ("Frame"));
-
-static inline Frame* parentFromOwnerElement(HTMLFrameOwnerElement* ownerElement)
-{
- if (!ownerElement)
- return 0;
- return ownerElement->document().frame();
-}
-
-static inline float parentPageZoomFactor(Frame* frame)
-{
- Frame* parent = frame->tree()->parent();
- if (!parent)
- return 1;
- return parent->pageZoomFactor();
-}
-
-static inline float parentTextZoomFactor(Frame* frame)
-{
- Frame* parent = frame->tree()->parent();
- if (!parent)
- return 1;
- return parent->textZoomFactor();
-}
-
-inline Frame::Frame(Page* page, HTMLFrameOwnerElement* ownerElement, FrameLoaderClient* frameLoaderClient)
- : m_page(page)
- , m_treeNode(this, parentFromOwnerElement(ownerElement))
- , m_loader(this, frameLoaderClient)
- , m_navigationScheduler(this)
- , m_ownerElement(ownerElement)
- , m_script(adoptPtr(new ScriptController(this)))
- , m_editor(adoptPtr(new Editor(*this)))
- , m_selection(adoptPtr(new FrameSelection(this)))
- , m_eventHandler(adoptPtr(new EventHandler(this)))
- , m_animationController(adoptPtr(new AnimationController(this)))
- , m_inputMethodController(InputMethodController::create(this))
- , m_pageZoomFactor(parentPageZoomFactor(this))
- , m_textZoomFactor(parentTextZoomFactor(this))
-#if ENABLE(ORIENTATION_EVENTS)
- , m_orientation(0)
-#endif
- , m_inViewSourceMode(false)
-{
- ASSERT(page);
-
- if (ownerElement) {
- page->incrementSubframeCount();
- ownerElement->setContentFrame(this);
- }
-
-#ifndef NDEBUG
- frameCounter.increment();
-#endif
-}
-
-PassRefPtr<Frame> Frame::create(Page* page, HTMLFrameOwnerElement* ownerElement, FrameLoaderClient* client)
-{
- RefPtr<Frame> frame = adoptRef(new Frame(page, ownerElement, client));
- if (!ownerElement)
- page->setMainFrame(frame);
- InspectorInstrumentation::frameAttachedToParent(frame.get());
- return frame.release();
-}
-
-Frame::~Frame()
-{
- setView(0);
- loader()->clear(ClearScriptObjects | ClearWindowObject);
-
- // FIXME: We should not be doing all this work inside the destructor
-
-#ifndef NDEBUG
- frameCounter.decrement();
-#endif
-
- disconnectOwnerElement();
-
- HashSet<FrameDestructionObserver*>::iterator stop = m_destructionObservers.end();
- for (HashSet<FrameDestructionObserver*>::iterator it = m_destructionObservers.begin(); it != stop; ++it)
- (*it)->frameDestroyed();
-}
-
-bool Frame::inScope(TreeScope* scope) const
-{
- ASSERT(scope);
- Document* doc = document();
- if (!doc)
- return false;
- HTMLFrameOwnerElement* owner = doc->ownerElement();
- if (!owner)
- return false;
- return &owner->treeScope() == scope;
-}
-
-void Frame::addDestructionObserver(FrameDestructionObserver* observer)
-{
- m_destructionObservers.add(observer);
-}
-
-void Frame::removeDestructionObserver(FrameDestructionObserver* observer)
-{
- m_destructionObservers.remove(observer);
-}
-
-void Frame::setView(PassRefPtr<FrameView> view)
-{
- // We the custom scroll bars as early as possible to prevent m_doc->detach()
- // from messing with the view such that its scroll bars won't be torn down.
- // FIXME: We should revisit this.
- if (m_view)
- m_view->prepareForDetach();
-
- // Prepare for destruction now, so any unload event handlers get run and the DOMWindow is
- // notified. If we wait until the view is destroyed, then things won't be hooked up enough for
- // these calls to work.
- if (!view && document() && document()->attached()) {
- // FIXME: We don't call willRemove here. Why is that OK?
- document()->prepareForDestruction();
- }
-
- if (m_view)
- m_view->unscheduleRelayout();
-
- eventHandler()->clear();
-
- m_view = view;
-
- if (m_view && m_page && m_page->mainFrame() == this)
- m_view->setVisibleContentScaleFactor(m_page->pageScaleFactor());
-}
-
-#if ENABLE(ORIENTATION_EVENTS)
-void Frame::sendOrientationChangeEvent(int orientation)
-{
- m_orientation = orientation;
- if (Document* doc = document())
- doc->dispatchWindowEvent(Event::create(eventNames().orientationchangeEvent));
-}
-#endif // ENABLE(ORIENTATION_EVENTS)
-
-Settings* Frame::settings() const
-{
- return m_page ? &m_page->settings() : 0;
-}
-
-void Frame::setPrinting(bool printing, const FloatSize& pageSize, const FloatSize& originalPageSize, float maximumShrinkRatio, AdjustViewSizeOrNot shouldAdjustViewSize)
-{
- // In setting printing, we should not validate resources already cached for the document.
- // See https://bugs.webkit.org/show_bug.cgi?id=43704
- ResourceCacheValidationSuppressor validationSuppressor(document()->fetcher());
-
- document()->setPrinting(printing);
- view()->adjustMediaTypeForPrinting(printing);
-
- document()->styleResolverChanged(RecalcStyleImmediately);
- if (shouldUsePrintingLayout()) {
- view()->forceLayoutForPagination(pageSize, originalPageSize, maximumShrinkRatio, shouldAdjustViewSize);
- } else {
- view()->forceLayout();
- if (shouldAdjustViewSize == AdjustViewSize)
- view()->adjustViewSize();
- }
-
- // Subframes of the one we're printing don't lay out to the page size.
- for (RefPtr<Frame> child = tree()->firstChild(); child; child = child->tree()->nextSibling())
- child->setPrinting(printing, FloatSize(), FloatSize(), 0, shouldAdjustViewSize);
-}
-
-bool Frame::shouldUsePrintingLayout() const
-{
- // Only top frame being printed should be fit to page size.
- // Subframes should be constrained by parents only.
- return document()->printing() && (!tree()->parent() || !tree()->parent()->document()->printing());
-}
-
-FloatSize Frame::resizePageRectsKeepingRatio(const FloatSize& originalSize, const FloatSize& expectedSize)
-{
- FloatSize resultSize;
- if (!contentRenderer())
- return FloatSize();
-
- if (contentRenderer()->style()->isHorizontalWritingMode()) {
- ASSERT(fabs(originalSize.width()) > numeric_limits<float>::epsilon());
- float ratio = originalSize.height() / originalSize.width();
- resultSize.setWidth(floorf(expectedSize.width()));
- resultSize.setHeight(floorf(resultSize.width() * ratio));
- } else {
- ASSERT(fabs(originalSize.height()) > numeric_limits<float>::epsilon());
- float ratio = originalSize.width() / originalSize.height();
- resultSize.setHeight(floorf(expectedSize.height()));
- resultSize.setWidth(floorf(resultSize.height() * ratio));
- }
- return resultSize;
-}
-
-void Frame::setDOMWindow(PassRefPtr<DOMWindow> domWindow)
-{
- m_domWindow = domWindow;
-}
-
-Document* Frame::document() const
-{
- return m_domWindow ? m_domWindow->document() : 0;
-}
-
-RenderView* Frame::contentRenderer() const
-{
- return document() ? document()->renderView() : 0;
-}
-
-RenderPart* Frame::ownerRenderer() const
-{
- HTMLFrameOwnerElement* ownerElement = m_ownerElement;
- if (!ownerElement)
- return 0;
- RenderObject* object = ownerElement->renderer();
- if (!object)
- return 0;
- // FIXME: If <object> is ever fixed to disassociate itself from frames
- // that it has started but canceled, then this can turn into an ASSERT
- // since m_ownerElement would be 0 when the load is canceled.
- // https://bugs.webkit.org/show_bug.cgi?id=18585
- if (!object->isRenderPart())
- return 0;
- return toRenderPart(object);
-}
-
-Frame* Frame::frameForWidget(const Widget* widget)
-{
- ASSERT_ARG(widget, widget);
-
- if (RenderWidget* renderer = RenderWidget::find(widget)) {
- if (Node* node = renderer->node())
- return node->document().frame();
- }
-
- // Assume all widgets are either a FrameView or owned by a RenderWidget.
- // FIXME: That assumption is not right for scroll bars!
- ASSERT_WITH_SECURITY_IMPLICATION(widget->isFrameView());
- return &toFrameView(widget)->frame();
-}
-
-void Frame::clearTimers(FrameView *view, Document *document)
-{
- if (view) {
- view->unscheduleRelayout();
- if (!RuntimeEnabledFeatures::webAnimationsCSSEnabled())
- view->frame().animation()->suspendAnimationsForDocument(document);
- view->frame().eventHandler()->stopAutoscrollTimer();
- }
-}
-
-void Frame::clearTimers()
-{
- clearTimers(m_view.get(), document());
-}
-
-void Frame::dispatchVisibilityStateChangeEvent()
-{
- if (document())
- document()->dispatchVisibilityStateChangeEvent();
-
- Vector<RefPtr<Frame> > childFrames;
- for (Frame* child = tree()->firstChild(); child; child = child->tree()->nextSibling())
- childFrames.append(child);
-
- for (size_t i = 0; i < childFrames.size(); ++i)
- childFrames[i]->dispatchVisibilityStateChangeEvent();
-}
-
-void Frame::willDetachPage()
-{
- // We should never be detatching the page during a Layout.
- RELEASE_ASSERT(!m_view || !m_view->isInLayout());
-
- if (Frame* parent = tree()->parent())
- parent->loader()->checkLoadComplete();
-
- HashSet<FrameDestructionObserver*>::iterator stop = m_destructionObservers.end();
- for (HashSet<FrameDestructionObserver*>::iterator it = m_destructionObservers.begin(); it != stop; ++it)
- (*it)->willDetachPage();
-
- // FIXME: It's unclear as to why this is called more than once, but it is,
- // so page() could be NULL.
- if (page() && page()->focusController().focusedFrame() == this)
- page()->focusController().setFocusedFrame(0);
-
- if (page() && page()->scrollingCoordinator() && m_view)
- page()->scrollingCoordinator()->willDestroyScrollableArea(m_view.get());
-
- script()->clearScriptObjects();
-}
-
-void Frame::detachFromPage()
-{
- // We should never be detatching the page during a Layout.
- RELEASE_ASSERT(!m_view || !m_view->isInLayout());
- m_page = 0;
-}
-
-void Frame::disconnectOwnerElement()
-{
- if (m_ownerElement) {
- if (Document* doc = document())
- doc->topDocument()->clearAXObjectCache();
- m_ownerElement->clearContentFrame();
- if (m_page)
- m_page->decrementSubframeCount();
- }
- m_ownerElement = 0;
-}
-
-String Frame::documentTypeString() const
-{
- if (DocumentType* doctype = document()->doctype())
- return createMarkup(doctype);
-
- return String();
-}
-
-String Frame::displayStringModifiedByEncoding(const String& str) const
-{
- return document() ? document()->displayStringModifiedByEncoding(str) : str;
-}
-
-String Frame::selectedText() const
-{
- return selection().selectedText();
-}
-
-String Frame::selectedTextForClipboard() const
-{
- return selection().selectedTextForClipboard();
-}
-
-VisiblePosition Frame::visiblePositionForPoint(const IntPoint& framePoint)
-{
- HitTestResult result = eventHandler()->hitTestResultAtPoint(framePoint);
- Node* node = result.innerNonSharedNode();
- if (!node)
- return VisiblePosition();
- RenderObject* renderer = node->renderer();
- if (!renderer)
- return VisiblePosition();
- VisiblePosition visiblePos = VisiblePosition(renderer->positionForPoint(result.localPoint()));
- if (visiblePos.isNull())
- visiblePos = firstPositionInOrBeforeNode(node);
- return visiblePos;
-}
-
-Document* Frame::documentAtPoint(const IntPoint& point)
-{
- if (!view())
- return 0;
-
- IntPoint pt = view()->windowToContents(point);
- HitTestResult result = HitTestResult(pt);
-
- if (contentRenderer())
- result = eventHandler()->hitTestResultAtPoint(pt, HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::DisallowShadowContent);
- return result.innerNode() ? &result.innerNode()->document() : 0;
-}
-
-PassRefPtr<Range> Frame::rangeForPoint(const IntPoint& framePoint)
-{
- VisiblePosition position = visiblePositionForPoint(framePoint);
- if (position.isNull())
- return 0;
-
- VisiblePosition previous = position.previous();
- if (previous.isNotNull()) {
- RefPtr<Range> previousCharacterRange = makeRange(previous, position);
- LayoutRect rect = editor().firstRectForRange(previousCharacterRange.get());
- if (rect.contains(framePoint))
- return previousCharacterRange.release();
- }
-
- VisiblePosition next = position.next();
- if (RefPtr<Range> nextCharacterRange = makeRange(position, next)) {
- LayoutRect rect = editor().firstRectForRange(nextCharacterRange.get());
- if (rect.contains(framePoint))
- return nextCharacterRange.release();
- }
-
- return 0;
-}
-
-void Frame::createView(const IntSize& viewportSize, const Color& backgroundColor, bool transparent,
- const IntSize& fixedLayoutSize, bool useFixedLayout, ScrollbarMode horizontalScrollbarMode, bool horizontalLock,
- ScrollbarMode verticalScrollbarMode, bool verticalLock)
-{
- ASSERT(this);
- ASSERT(m_page);
-
- bool isMainFrame = this == m_page->mainFrame();
-
- if (isMainFrame && view())
- view()->setParentVisible(false);
-
- setView(0);
-
- RefPtr<FrameView> frameView;
- if (isMainFrame) {
- frameView = FrameView::create(this, viewportSize);
- frameView->setFixedLayoutSize(fixedLayoutSize);
- frameView->setUseFixedLayout(useFixedLayout);
- } else
- frameView = FrameView::create(this);
-
- frameView->setScrollbarModes(horizontalScrollbarMode, verticalScrollbarMode, horizontalLock, verticalLock);
-
- setView(frameView);
-
- if (backgroundColor.isValid())
- frameView->updateBackgroundRecursively(backgroundColor, transparent);
-
- if (isMainFrame)
- frameView->setParentVisible(true);
-
- if (ownerRenderer())
- ownerRenderer()->setWidget(frameView);
-
- if (HTMLFrameOwnerElement* owner = ownerElement())
- view()->setCanHaveScrollbars(owner->scrollingMode() != ScrollbarAlwaysOff);
-}
-
-String Frame::layerTreeAsText(unsigned flags) const
-{
- document()->updateLayout();
-
- if (!contentRenderer())
- return String();
-
- return contentRenderer()->compositor()->layerTreeAsText(static_cast<LayerTreeFlags>(flags));
-}
-
-String Frame::trackedRepaintRectsAsText() const
-{
- if (!m_view)
- return String();
- return m_view->trackedRepaintRectsAsText();
-}
-
-void Frame::setPageZoomFactor(float factor)
-{
- setPageAndTextZoomFactors(factor, m_textZoomFactor);
-}
-
-void Frame::setTextZoomFactor(float factor)
-{
- setPageAndTextZoomFactors(m_pageZoomFactor, factor);
-}
-
-void Frame::setPageAndTextZoomFactors(float pageZoomFactor, float textZoomFactor)
-{
- if (m_pageZoomFactor == pageZoomFactor && m_textZoomFactor == textZoomFactor)
- return;
-
- Page* page = this->page();
- if (!page)
- return;
-
- Document* document = this->document();
- if (!document)
- return;
-
- // Respect SVGs zoomAndPan="disabled" property in standalone SVG documents.
- // FIXME: How to handle compound documents + zoomAndPan="disabled"? Needs SVG WG clarification.
- if (document->isSVGDocument()) {
- if (!toSVGDocument(document)->zoomAndPanEnabled())
- return;
- }
-
- if (m_pageZoomFactor != pageZoomFactor) {
- if (FrameView* view = this->view()) {
- // Update the scroll position when doing a full page zoom, so the content stays in relatively the same position.
- LayoutPoint scrollPosition = view->scrollPosition();
- float percentDifference = (pageZoomFactor / m_pageZoomFactor);
- view->setScrollPosition(IntPoint(scrollPosition.x() * percentDifference, scrollPosition.y() * percentDifference));
- }
- }
-
- m_pageZoomFactor = pageZoomFactor;
- m_textZoomFactor = textZoomFactor;
-
- document->recalcStyle(Force);
-
- for (RefPtr<Frame> child = tree()->firstChild(); child; child = child->tree()->nextSibling())
- child->setPageAndTextZoomFactors(m_pageZoomFactor, m_textZoomFactor);
-
- if (FrameView* view = this->view()) {
- if (document->renderer() && document->renderer()->needsLayout() && view->didFirstLayout())
- view->layout();
- }
-}
-
-void Frame::deviceOrPageScaleFactorChanged()
-{
- for (RefPtr<Frame> child = tree()->firstChild(); child; child = child->tree()->nextSibling())
- child->deviceOrPageScaleFactorChanged();
-
- m_page->chrome().client().deviceOrPageScaleFactorChanged();
-}
-
-void Frame::notifyChromeClientWheelEventHandlerCountChanged() const
-{
- // Ensure that this method is being called on the main frame of the page.
- ASSERT(m_page && m_page->mainFrame() == this);
-
- unsigned count = 0;
- for (const Frame* frame = this; frame; frame = frame->tree()->traverseNext()) {
- if (frame->document())
- count += WheelController::from(frame->document())->wheelEventHandlerCount();
- }
-
- m_page->chrome().client().numWheelEventHandlersChanged(count);
-}
-
-bool Frame::isURLAllowed(const KURL& url) const
-{
- // We allow one level of self-reference because some sites depend on that,
- // but we don't allow more than one.
- if (m_page->subframeCount() >= Page::maxNumberOfFrames)
- return false;
- bool foundSelfReference = false;
- for (const Frame* frame = this; frame; frame = frame->tree()->parent()) {
- if (equalIgnoringFragmentIdentifier(frame->document()->url(), url)) {
- if (foundSelfReference)
- return false;
- foundSelfReference = true;
- }
- }
- return true;
-}
-
-struct ScopedFramePaintingState {
- ScopedFramePaintingState(Frame* frame, Node* node)
- : frame(frame)
- , node(node)
- , paintBehavior(frame->view()->paintBehavior())
- , backgroundColor(frame->view()->baseBackgroundColor())
- {
- ASSERT(!node || node->renderer());
- if (node)
- node->renderer()->updateDragState(true);
- }
-
- ~ScopedFramePaintingState()
- {
- if (node && node->renderer())
- node->renderer()->updateDragState(false);
- frame->view()->setPaintBehavior(paintBehavior);
- frame->view()->setBaseBackgroundColor(backgroundColor);
- frame->view()->setNodeToDraw(0);
- }
-
- Frame* frame;
- Node* node;
- PaintBehavior paintBehavior;
- Color backgroundColor;
-};
-
-PassOwnPtr<DragImage> Frame::nodeImage(Node* node)
-{
- if (!node->renderer())
- return nullptr;
-
- const ScopedFramePaintingState state(this, node);
-
- m_view->setPaintBehavior(state.paintBehavior | PaintBehaviorFlattenCompositingLayers);
-
- // When generating the drag image for an element, ignore the document background.
- m_view->setBaseBackgroundColor(Color::transparent);
- document()->updateLayout();
- m_view->setNodeToDraw(node); // Enable special sub-tree drawing mode.
-
- // Document::updateLayout may have blown away the original RenderObject.
- RenderObject* renderer = node->renderer();
- if (!renderer)
- return nullptr;
-
- LayoutRect topLevelRect;
- IntRect paintingRect = pixelSnappedIntRect(renderer->paintingRootRect(topLevelRect));
-
- float deviceScaleFactor = 1;
- if (m_page)
- deviceScaleFactor = m_page->deviceScaleFactor();
- paintingRect.setWidth(paintingRect.width() * deviceScaleFactor);
- paintingRect.setHeight(paintingRect.height() * deviceScaleFactor);
-
- OwnPtr<ImageBuffer> buffer(ImageBuffer::create(paintingRect.size(), deviceScaleFactor));
- if (!buffer)
- return nullptr;
- buffer->context()->translate(-paintingRect.x(), -paintingRect.y());
- buffer->context()->clip(FloatRect(0, 0, paintingRect.maxX(), paintingRect.maxY()));
-
- m_view->paintContents(buffer->context(), paintingRect);
-
- RefPtr<Image> image = buffer->copyImage();
- return DragImage::create(image.get(), renderer->shouldRespectImageOrientation());
-}
-
-PassOwnPtr<DragImage> Frame::dragImageForSelection()
-{
- if (!selection().isRange())
- return nullptr;
-
- const ScopedFramePaintingState state(this, 0);
- m_view->setPaintBehavior(PaintBehaviorSelectionOnly | PaintBehaviorFlattenCompositingLayers);
- document()->updateLayout();
-
- IntRect paintingRect = enclosingIntRect(selection().bounds());
-
- float deviceScaleFactor = 1;
- if (m_page)
- deviceScaleFactor = m_page->deviceScaleFactor();
- paintingRect.setWidth(paintingRect.width() * deviceScaleFactor);
- paintingRect.setHeight(paintingRect.height() * deviceScaleFactor);
-
- OwnPtr<ImageBuffer> buffer(ImageBuffer::create(paintingRect.size(), deviceScaleFactor));
- if (!buffer)
- return nullptr;
- buffer->context()->translate(-paintingRect.x(), -paintingRect.y());
- buffer->context()->clip(FloatRect(0, 0, paintingRect.maxX(), paintingRect.maxY()));
-
- m_view->paintContents(buffer->context(), paintingRect);
-
- RefPtr<Image> image = buffer->copyImage();
- return DragImage::create(image.get());
-}
-
-double Frame::devicePixelRatio() const
-{
- if (!m_page)
- return 0;
-
- double ratio = m_page->deviceScaleFactor();
- if (RuntimeEnabledFeatures::devicePixelRatioIncludesZoomEnabled())
- ratio *= pageZoomFactor();
- return ratio;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/page/Frame.h b/chromium/third_party/WebKit/Source/core/page/Frame.h
deleted file mode 100644
index 1a912eb6c1f..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/Frame.h
+++ /dev/null
@@ -1,286 +0,0 @@
-/*
- * Copyright (C) 1998, 1999 Torben Weis <weis@kde.org>
- * 1999-2001 Lars Knoll <knoll@kde.org>
- * 1999-2001 Antti Koivisto <koivisto@kde.org>
- * 2000-2001 Simon Hausmann <hausmann@kde.org>
- * 2000-2001 Dirk Mueller <mueller@kde.org>
- * 2000 Stefan Schimanski <1Stein@gmx.de>
- * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010 Apple Inc. All rights reserved.
- * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
- * Copyright (C) 2008 Eric Seidel <eric@webkit.org>
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#ifndef Frame_h
-#define Frame_h
-
-#include "core/loader/FrameLoader.h"
-#include "core/loader/NavigationScheduler.h"
-#include "core/page/AdjustViewSizeOrNot.h"
-#include "core/page/FrameTree.h"
-#include "core/platform/ScrollTypes.h"
-#include "core/platform/graphics/IntSize.h"
-#include "wtf/Forward.h"
-#include "wtf/RefCounted.h"
-
-namespace WebCore {
-
- class AnimationController;
- class Color;
- class DOMWindow;
- class Document;
- class DragImage;
- class Editor;
- class Element;
- class EventHandler;
- class FetchContext;
- class FloatSize;
- class FrameDestructionObserver;
- class FrameSelection;
- class FrameView;
- class HTMLFrameOwnerElement;
- class HTMLTableCellElement;
- class InputMethodController;
- class IntPoint;
- class Node;
- class Range;
- class RenderPart;
- class RenderView;
- class TreeScope;
- class ScriptController;
- class Settings;
- class TreeScope;
- class VisiblePosition;
- class Widget;
-
- class Frame : public RefCounted<Frame> {
- public:
- static PassRefPtr<Frame> create(Page*, HTMLFrameOwnerElement*, FrameLoaderClient*);
-
- void init();
- void setView(PassRefPtr<FrameView>);
- void createView(const IntSize&, const Color&, bool,
- const IntSize& fixedLayoutSize = IntSize(), bool useFixedLayout = false, ScrollbarMode = ScrollbarAuto, bool horizontalLock = false,
- ScrollbarMode = ScrollbarAuto, bool verticalLock = false);
-
- ~Frame();
-
- void addDestructionObserver(FrameDestructionObserver*);
- void removeDestructionObserver(FrameDestructionObserver*);
-
- void willDetachPage();
- void detachFromPage();
- void disconnectOwnerElement();
-
- Page* page() const;
- HTMLFrameOwnerElement* ownerElement() const;
-
- void setDOMWindow(PassRefPtr<DOMWindow>);
- DOMWindow* domWindow() const;
- Document* document() const;
- FrameView* view() const;
-
- Editor& editor() const;
- EventHandler* eventHandler() const;
- FrameLoader* loader() const;
- NavigationScheduler* navigationScheduler() const;
- FrameSelection& selection() const;
- FrameTree* tree() const;
- AnimationController* animation() const;
- InputMethodController& inputMethodController() const;
- FetchContext& fetchContext() const { return loader()->fetchContext(); }
- ScriptController* script();
-
- RenderView* contentRenderer() const; // Root of the render tree for the document contained in this frame.
- RenderPart* ownerRenderer() const; // Renderer for the element that contains this frame.
-
- void dispatchVisibilityStateChangeEvent();
-
- // ======== All public functions below this point are candidates to move out of Frame into another class. ========
-
- bool inScope(TreeScope*) const;
-
- // See GraphicsLayerClient.h for accepted flags.
- String layerTreeAsText(unsigned flags = 0) const;
- String trackedRepaintRectsAsText() const;
-
- static Frame* frameForWidget(const Widget*);
-
- Settings* settings() const; // can be NULL
-
- void setPrinting(bool printing, const FloatSize& pageSize, const FloatSize& originalPageSize, float maximumShrinkRatio, AdjustViewSizeOrNot);
- bool shouldUsePrintingLayout() const;
- FloatSize resizePageRectsKeepingRatio(const FloatSize& originalSize, const FloatSize& expectedSize);
-
- bool inViewSourceMode() const;
- void setInViewSourceMode(bool = true);
-
- void setPageZoomFactor(float factor);
- float pageZoomFactor() const { return m_pageZoomFactor; }
- void setTextZoomFactor(float factor);
- float textZoomFactor() const { return m_textZoomFactor; }
- void setPageAndTextZoomFactors(float pageZoomFactor, float textZoomFactor);
-
- void deviceOrPageScaleFactorChanged();
- double devicePixelRatio() const;
-
-#if ENABLE(ORIENTATION_EVENTS)
- // Orientation is the interface orientation in degrees. Some examples are:
- // 0 is straight up; -90 is when the device is rotated 90 clockwise;
- // 90 is when rotated counter clockwise.
- void sendOrientationChangeEvent(int orientation);
- int orientation() const { return m_orientation; }
-#endif
-
- void clearTimers();
- static void clearTimers(FrameView*, Document*);
-
- String documentTypeString() const;
-
- String displayStringModifiedByEncoding(const String&) const;
-
- PassOwnPtr<DragImage> nodeImage(Node*);
- PassOwnPtr<DragImage> dragImageForSelection();
-
- String selectedText() const;
- String selectedTextForClipboard() const;
-
- VisiblePosition visiblePositionForPoint(const IntPoint& framePoint);
- Document* documentAtPoint(const IntPoint& windowPoint);
- PassRefPtr<Range> rangeForPoint(const IntPoint& framePoint);
-
- // Should only be called on the main frame of a page.
- void notifyChromeClientWheelEventHandlerCountChanged() const;
-
- bool isURLAllowed(const KURL&) const;
-
- // ========
-
- private:
- Frame(Page*, HTMLFrameOwnerElement*, FrameLoaderClient*);
-
- HashSet<FrameDestructionObserver*> m_destructionObservers;
-
- Page* m_page;
- mutable FrameTree m_treeNode;
- mutable FrameLoader m_loader;
- mutable NavigationScheduler m_navigationScheduler;
-
- HTMLFrameOwnerElement* m_ownerElement;
- RefPtr<FrameView> m_view;
- RefPtr<DOMWindow> m_domWindow;
-
- OwnPtr<ScriptController> m_script;
- const OwnPtr<Editor> m_editor;
- const OwnPtr<FrameSelection> m_selection;
- OwnPtr<EventHandler> m_eventHandler;
- OwnPtr<AnimationController> m_animationController;
- OwnPtr<InputMethodController> m_inputMethodController;
-
- float m_pageZoomFactor;
- float m_textZoomFactor;
-
-#if ENABLE(ORIENTATION_EVENTS)
- int m_orientation;
-#endif
-
- bool m_inViewSourceMode;
- };
-
- inline void Frame::init()
- {
- m_loader.init();
- }
-
- inline FrameLoader* Frame::loader() const
- {
- return &m_loader;
- }
-
- inline NavigationScheduler* Frame::navigationScheduler() const
- {
- return &m_navigationScheduler;
- }
-
- inline FrameView* Frame::view() const
- {
- return m_view.get();
- }
-
- inline ScriptController* Frame::script()
- {
- return m_script.get();
- }
-
- inline DOMWindow* Frame::domWindow() const
- {
- return m_domWindow.get();
- }
-
- inline FrameSelection& Frame::selection() const
- {
- return *m_selection;
- }
-
- inline Editor& Frame::editor() const
- {
- return *m_editor;
- }
-
- inline AnimationController* Frame::animation() const
- {
- return m_animationController.get();
- }
-
- inline InputMethodController& Frame::inputMethodController() const
- {
- return *m_inputMethodController;
- }
-
- inline HTMLFrameOwnerElement* Frame::ownerElement() const
- {
- return m_ownerElement;
- }
-
- inline bool Frame::inViewSourceMode() const
- {
- return m_inViewSourceMode;
- }
-
- inline void Frame::setInViewSourceMode(bool mode)
- {
- m_inViewSourceMode = mode;
- }
-
- inline FrameTree* Frame::tree() const
- {
- return &m_treeNode;
- }
-
- inline Page* Frame::page() const
- {
- return m_page;
- }
-
- inline EventHandler* Frame::eventHandler() const
- {
- return m_eventHandler.get();
- }
-
-} // namespace WebCore
-
-#endif // Frame_h
diff --git a/chromium/third_party/WebKit/Source/core/page/FrameActionScheduler.cpp b/chromium/third_party/WebKit/Source/core/page/FrameActionScheduler.cpp
deleted file mode 100644
index d1638fd83b3..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/FrameActionScheduler.cpp
+++ /dev/null
@@ -1,111 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/page/FrameActionScheduler.h"
-
-#include "bindings/v8/ExceptionStatePlaceholder.h"
-#include "core/dom/Event.h"
-#include "core/dom/Node.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-class EventFrameAction : public FrameAction {
-public:
- EventFrameAction(PassRefPtr<Event> event, PassRefPtr<Node> target)
- : m_event(event)
- , m_eventTarget(target)
- {
- }
-
- virtual void fire()
- {
- // Only dispatch events to nodes that are in the document
- if (m_eventTarget->inDocument())
- m_eventTarget->dispatchEvent(m_event, IGNORE_EXCEPTION);
- }
-
-private:
- RefPtr<Event> m_event;
- RefPtr<Node> m_eventTarget;
-};
-
-FrameActionScheduler::FrameActionScheduler()
- : m_enqueueActions(0)
-{
-}
-
-FrameActionScheduler::~FrameActionScheduler()
-{
- clear();
-}
-
-bool FrameActionScheduler::isEmpty() const
-{
- return m_scheduledActions.isEmpty();
-}
-
-void FrameActionScheduler::clear()
-{
- m_scheduledActions.clear();
- m_enqueueActions = 0;
-}
-
-void FrameActionScheduler::pause()
-{
- ASSERT(isEmpty() || m_enqueueActions);
- m_enqueueActions++;
-}
-
-void FrameActionScheduler::resume()
-{
- m_enqueueActions--;
- if (!m_enqueueActions)
- dispatch();
- ASSERT(isEmpty() || m_enqueueActions);
-}
-
-void FrameActionScheduler::dispatch()
-{
- Vector< OwnPtr<FrameAction> > snapshot;
- m_scheduledActions.swap(snapshot);
-
- for (Vector< OwnPtr<FrameAction> >::iterator i = snapshot.begin(); i != snapshot.end(); ++i)
- (*i)->fire();
-}
-
-void FrameActionScheduler::scheduleAction(PassOwnPtr<FrameAction> action)
-{
- m_scheduledActions.append(action);
-}
-
-void FrameActionScheduler::scheduleEvent(PassRefPtr<Event> event, PassRefPtr<Node> eventTarget)
-{
- scheduleAction(adoptPtr(new EventFrameAction(event, eventTarget)));
-}
-
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/page/FrameActionScheduler.h b/chromium/third_party/WebKit/Source/core/page/FrameActionScheduler.h
deleted file mode 100644
index a4143bed4b8..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/FrameActionScheduler.h
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef FrameActionScheduler_h
-#define FrameActionScheduler_h
-
-#include "wtf/FastAllocBase.h"
-#include "wtf/Noncopyable.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-class Node;
-class Event;
-
-class FrameAction {
- WTF_MAKE_FAST_ALLOCATED;
- WTF_MAKE_NONCOPYABLE(FrameAction);
-public:
- FrameAction() {}
- virtual ~FrameAction() {}
- virtual void fire() = 0;
-};
-
-class FrameActionScheduler {
- WTF_MAKE_FAST_ALLOCATED;
-public:
- FrameActionScheduler();
- ~FrameActionScheduler();
-
- bool isEmpty() const;
- // FIXME: Why is this < m_enqueueActions, does this
- // mean that the steady state of m_enqueueActions should be -1?
- bool isScheduled() const { return 0 < m_enqueueActions; }
- void clear();
- void pause();
- void resume();
-
- void scheduleAction(PassOwnPtr<FrameAction>);
- void scheduleEvent(PassRefPtr<Event>, PassRefPtr<Node>);
-
-private:
- void dispatch();
-
- unsigned m_enqueueActions;
- Vector< OwnPtr<FrameAction> > m_scheduledActions;
-};
-
-} // namespace WebCore
-
-#endif // FrameActionScheduler_h
diff --git a/chromium/third_party/WebKit/Source/core/page/FrameDestructionObserver.cpp b/chromium/third_party/WebKit/Source/core/page/FrameDestructionObserver.cpp
deleted file mode 100644
index 528c45f3405..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/FrameDestructionObserver.cpp
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright (C) 2011 Google, Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY GOOGLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/page/FrameDestructionObserver.h"
-
-#include "core/page/Frame.h"
-
-namespace WebCore {
-
-FrameDestructionObserver::FrameDestructionObserver(Frame* frame)
- : m_frame(0)
-{
- observeFrame(frame);
-}
-
-FrameDestructionObserver::~FrameDestructionObserver()
-{
- observeFrame(0);
-
-}
-
-void FrameDestructionObserver::observeFrame(Frame* frame)
-{
- if (m_frame)
- m_frame->removeDestructionObserver(this);
-
- m_frame = frame;
-
- if (m_frame)
- m_frame->addDestructionObserver(this);
-}
-
-void FrameDestructionObserver::frameDestroyed()
-{
- m_frame = 0;
-}
-
-void FrameDestructionObserver::willDetachPage()
-{
- // Subclasses should override this function to handle this notification.
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/page/FrameTree.cpp b/chromium/third_party/WebKit/Source/core/page/FrameTree.cpp
index 47e59adcf74..b7e7dc1cc10 100644
--- a/chromium/third_party/WebKit/Source/core/page/FrameTree.cpp
+++ b/chromium/third_party/WebKit/Source/core/page/FrameTree.cpp
@@ -22,8 +22,8 @@
#include "core/page/FrameTree.h"
#include "core/dom/Document.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameView.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
#include "core/page/Page.h"
#include "core/page/PageGroup.h"
#include "wtf/Vector.h"
@@ -36,7 +36,7 @@ namespace WebCore {
FrameTree::~FrameTree()
{
- for (Frame* child = firstChild(); child; child = child->tree()->nextSibling())
+ for (Frame* child = firstChild(); child; child = child->tree().nextSibling())
child->setView(0);
}
@@ -48,7 +48,7 @@ void FrameTree::setName(const AtomicString& name)
return;
}
m_uniqueName = AtomicString(); // Remove our old frame name so it's not considered in uniqueChildName.
- m_uniqueName = parent()->tree()->uniqueChildName(name);
+ m_uniqueName = parent()->tree().uniqueChildName(name);
}
Frame* FrameTree::parent() const
@@ -59,37 +59,37 @@ Frame* FrameTree::parent() const
void FrameTree::appendChild(PassRefPtr<Frame> child)
{
ASSERT(child->page() == m_thisFrame->page());
- child->tree()->m_parent = m_thisFrame;
+ child->tree().m_parent = m_thisFrame;
Frame* oldLast = m_lastChild;
m_lastChild = child.get();
if (oldLast) {
- child->tree()->m_previousSibling = oldLast;
- oldLast->tree()->m_nextSibling = child;
+ child->tree().m_previousSibling = oldLast;
+ oldLast->tree().m_nextSibling = child;
} else
m_firstChild = child;
m_scopedChildCount = invalidCount;
- ASSERT(!m_lastChild->tree()->m_nextSibling);
+ ASSERT(!m_lastChild->tree().m_nextSibling);
}
void FrameTree::removeChild(Frame* child)
{
- child->tree()->m_parent = 0;
+ child->tree().m_parent = 0;
// Slightly tricky way to prevent deleting the child until we are done with it, w/o
// extra refs. These swaps leave the child in a circular list by itself. Clearing its
// previous and next will then finally deref it.
- RefPtr<Frame>& newLocationForNext = m_firstChild == child ? m_firstChild : child->tree()->m_previousSibling->tree()->m_nextSibling;
- Frame*& newLocationForPrevious = m_lastChild == child ? m_lastChild : child->tree()->m_nextSibling->tree()->m_previousSibling;
- swap(newLocationForNext, child->tree()->m_nextSibling);
+ RefPtr<Frame>& newLocationForNext = m_firstChild == child ? m_firstChild : child->tree().m_previousSibling->tree().m_nextSibling;
+ Frame*& newLocationForPrevious = m_lastChild == child ? m_lastChild : child->tree().m_nextSibling->tree().m_previousSibling;
+ swap(newLocationForNext, child->tree().m_nextSibling);
// For some inexplicable reason, the following line does not compile without the explicit std:: namespace
- std::swap(newLocationForPrevious, child->tree()->m_previousSibling);
+ std::swap(newLocationForPrevious, child->tree().m_previousSibling);
- child->tree()->m_previousSibling = 0;
- child->tree()->m_nextSibling = 0;
+ child->tree().m_previousSibling = 0;
+ child->tree().m_nextSibling = 0;
m_scopedChildCount = invalidCount;
}
@@ -113,21 +113,21 @@ AtomicString FrameTree::uniqueChildName(const AtomicString& requestedName) const
// Find the nearest parent that has a frame with a path in it.
Vector<Frame*, 16> chain;
Frame* frame;
- for (frame = m_thisFrame; frame; frame = frame->tree()->parent()) {
- if (frame->tree()->uniqueName().startsWith(framePathPrefix))
+ for (frame = m_thisFrame; frame; frame = frame->tree().parent()) {
+ if (frame->tree().uniqueName().startsWith(framePathPrefix))
break;
chain.append(frame);
}
StringBuilder name;
name.append(framePathPrefix);
if (frame) {
- name.append(frame->tree()->uniqueName().string().substring(framePathPrefixLength,
- frame->tree()->uniqueName().length() - framePathPrefixLength - framePathSuffixLength));
+ name.append(frame->tree().uniqueName().string().substring(framePathPrefixLength,
+ frame->tree().uniqueName().length() - framePathPrefixLength - framePathSuffixLength));
}
for (int i = chain.size() - 1; i >= 0; --i) {
frame = chain[i];
name.append('/');
- name.append(frame->tree()->uniqueName());
+ name.append(frame->tree().uniqueName());
}
name.appendLiteral("/<!--frame");
@@ -144,7 +144,7 @@ Frame* FrameTree::scopedChild(unsigned index) const
return 0;
unsigned scopedIndex = 0;
- for (Frame* result = firstChild(); result; result = result->tree()->nextSibling()) {
+ for (Frame* result = firstChild(); result; result = result->tree().nextSibling()) {
if (result->inScope(scope)) {
if (scopedIndex == index)
return result;
@@ -161,8 +161,8 @@ Frame* FrameTree::scopedChild(const AtomicString& name) const
if (!scope)
return 0;
- for (Frame* child = firstChild(); child; child = child->tree()->nextSibling())
- if (child->tree()->uniqueName() == name && child->inScope(scope))
+ for (Frame* child = firstChild(); child; child = child->tree().nextSibling())
+ if (child->tree().uniqueName() == name && child->inScope(scope))
return child;
return 0;
}
@@ -173,7 +173,7 @@ inline unsigned FrameTree::scopedChildCount(TreeScope* scope) const
return 0;
unsigned scopedCount = 0;
- for (Frame* result = firstChild(); result; result = result->tree()->nextSibling()) {
+ for (Frame* result = firstChild(); result; result = result->tree().nextSibling()) {
if (result->inScope(scope))
scopedCount++;
}
@@ -191,15 +191,15 @@ unsigned FrameTree::scopedChildCount() const
unsigned FrameTree::childCount() const
{
unsigned count = 0;
- for (Frame* result = firstChild(); result; result = result->tree()->nextSibling())
+ for (Frame* result = firstChild(); result; result = result->tree().nextSibling())
++count;
return count;
}
Frame* FrameTree::child(const AtomicString& name) const
{
- for (Frame* child = firstChild(); child; child = child->tree()->nextSibling())
- if (child->tree()->uniqueName() == name)
+ for (Frame* child = firstChild(); child; child = child->tree().nextSibling())
+ if (child->tree().uniqueName() == name)
return child;
return 0;
}
@@ -220,8 +220,8 @@ Frame* FrameTree::find(const AtomicString& name) const
return 0;
// Search subtree starting with this frame first.
- for (Frame* frame = m_thisFrame; frame; frame = frame->tree()->traverseNext(m_thisFrame))
- if (frame->tree()->uniqueName() == name)
+ for (Frame* frame = m_thisFrame; frame; frame = frame->tree().traverseNext(m_thisFrame))
+ if (frame->tree().uniqueName() == name)
return frame;
// Search the entire tree for this page next.
@@ -231,8 +231,8 @@ Frame* FrameTree::find(const AtomicString& name) const
if (!page)
return 0;
- for (Frame* frame = page->mainFrame(); frame; frame = frame->tree()->traverseNext())
- if (frame->tree()->uniqueName() == name)
+ for (Frame* frame = page->mainFrame(); frame; frame = frame->tree().traverseNext())
+ if (frame->tree().uniqueName() == name)
return frame;
// Search the entire tree of each of the other pages in this namespace.
@@ -242,8 +242,8 @@ Frame* FrameTree::find(const AtomicString& name) const
for (HashSet<Page*>::const_iterator it = pages.begin(); it != end; ++it) {
Page* otherPage = *it;
if (otherPage != page) {
- for (Frame* frame = otherPage->mainFrame(); frame; frame = frame->tree()->traverseNext()) {
- if (frame->tree()->uniqueName() == name)
+ for (Frame* frame = otherPage->mainFrame(); frame; frame = frame->tree().traverseNext()) {
+ if (frame->tree().uniqueName() == name)
return frame;
}
}
@@ -260,7 +260,7 @@ bool FrameTree::isDescendantOf(const Frame* ancestor) const
if (m_thisFrame->page() != ancestor->page())
return false;
- for (Frame* frame = m_thisFrame; frame; frame = frame->tree()->parent())
+ for (Frame* frame = m_thisFrame; frame; frame = frame->tree().parent())
if (frame == ancestor)
return true;
return false;
@@ -270,7 +270,7 @@ Frame* FrameTree::traverseNext(const Frame* stayWithin) const
{
Frame* child = firstChild();
if (child) {
- ASSERT(!stayWithin || child->tree()->isDescendantOf(stayWithin));
+ ASSERT(!stayWithin || child->tree().isDescendantOf(stayWithin));
return child;
}
@@ -279,20 +279,20 @@ Frame* FrameTree::traverseNext(const Frame* stayWithin) const
Frame* sibling = nextSibling();
if (sibling) {
- ASSERT(!stayWithin || sibling->tree()->isDescendantOf(stayWithin));
+ ASSERT(!stayWithin || sibling->tree().isDescendantOf(stayWithin));
return sibling;
}
Frame* frame = m_thisFrame;
- while (!sibling && (!stayWithin || frame->tree()->parent() != stayWithin)) {
- frame = frame->tree()->parent();
+ while (!sibling && (!stayWithin || frame->tree().parent() != stayWithin)) {
+ frame = frame->tree().parent();
if (!frame)
return 0;
- sibling = frame->tree()->nextSibling();
+ sibling = frame->tree().nextSibling();
}
if (frame) {
- ASSERT(!stayWithin || !sibling || sibling->tree()->isDescendantOf(stayWithin));
+ ASSERT(!stayWithin || !sibling || sibling->tree().isDescendantOf(stayWithin));
return sibling;
}
@@ -315,7 +315,7 @@ Frame* FrameTree::traversePreviousWithWrap(bool wrap) const
// FIXME: besides the wrap feature, this is just the traversePreviousNode algorithm
if (Frame* prevSibling = previousSibling())
- return prevSibling->tree()->deepLastChild();
+ return prevSibling->tree().deepLastChild();
if (Frame* parentFrame = parent())
return parentFrame;
@@ -330,7 +330,7 @@ Frame* FrameTree::traversePreviousWithWrap(bool wrap) const
Frame* FrameTree::deepLastChild() const
{
Frame* result = m_thisFrame;
- for (Frame* last = lastChild(); last; last = last->tree()->lastChild())
+ for (Frame* last = lastChild(); last; last = last->tree().lastChild())
result = last;
return result;
@@ -339,7 +339,7 @@ Frame* FrameTree::deepLastChild() const
Frame* FrameTree::top() const
{
Frame* frame = m_thisFrame;
- for (Frame* parent = m_thisFrame; parent; parent = parent->tree()->parent())
+ for (Frame* parent = m_thisFrame; parent; parent = parent->tree().parent())
frame = parent;
return frame;
}
@@ -373,7 +373,7 @@ static void printFrames(const WebCore::Frame* frame, const WebCore::Frame* targe
printIndent(indent);
printf(" uri=%s\n\n", frame->document()->documentURI().utf8().data());
- for (WebCore::Frame* child = frame->tree()->firstChild(); child; child = child->tree()->nextSibling())
+ for (WebCore::Frame* child = frame->tree().firstChild(); child; child = child->tree().nextSibling())
printFrames(child, targetFrame, indent + 1);
}
@@ -384,7 +384,7 @@ void showFrameTree(const WebCore::Frame* frame)
return;
}
- printFrames(frame->tree()->top(), frame, 0);
+ printFrames(frame->tree().top(), frame, 0);
}
#endif
diff --git a/chromium/third_party/WebKit/Source/core/page/FrameView.cpp b/chromium/third_party/WebKit/Source/core/page/FrameView.cpp
deleted file mode 100644
index 1339426905c..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/FrameView.cpp
+++ /dev/null
@@ -1,3420 +0,0 @@
-/*
- * Copyright (C) 1998, 1999 Torben Weis <weis@kde.org>
- * 1999 Lars Knoll <knoll@kde.org>
- * 1999 Antti Koivisto <koivisto@kde.org>
- * 2000 Dirk Mueller <mueller@kde.org>
- * Copyright (C) 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
- * (C) 2006 Graham Dennis (graham.dennis@gmail.com)
- * (C) 2006 Alexey Proskuryakov (ap@nypop.com)
- * Copyright (C) 2009 Google Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-#include "core/page/FrameView.h"
-
-#include "HTMLNames.h"
-#include "RuntimeEnabledFeatures.h"
-#include "core/accessibility/AXObjectCache.h"
-#include "core/animation/DocumentTimeline.h"
-#include "core/css/FontFaceSet.h"
-#include "core/css/resolver/StyleResolver.h"
-#include "core/dom/DocumentMarkerController.h"
-#include "core/dom/OverflowEvent.h"
-#include "core/editing/FrameSelection.h"
-#include "core/fetch/ResourceFetcher.h"
-#include "core/fetch/TextResourceDecoder.h"
-#include "core/html/HTMLFrameElement.h"
-#include "core/html/HTMLHtmlElement.h"
-#include "core/html/HTMLPlugInImageElement.h"
-#include "core/inspector/InspectorInstrumentation.h"
-#include "core/loader/FrameLoader.h"
-#include "core/loader/FrameLoaderClient.h"
-#include "core/page/Chrome.h"
-#include "core/page/ChromeClient.h"
-#include "core/page/EventHandler.h"
-#include "core/page/FocusController.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameActionScheduler.h"
-#include "core/page/FrameTree.h"
-#include "core/page/Settings.h"
-#include "core/page/animation/AnimationController.h"
-#include "core/page/scrolling/ScrollingCoordinator.h"
-#include "core/platform/ScrollAnimator.h"
-#include "core/platform/graphics/FloatRect.h"
-#include "core/platform/graphics/FontCache.h"
-#include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/text/TextStream.h"
-#include "core/rendering/LayoutIndicator.h"
-#include "core/rendering/RenderCounter.h"
-#include "core/rendering/RenderEmbeddedObject.h"
-#include "core/rendering/RenderLayer.h"
-#include "core/rendering/RenderLayerBacking.h"
-#include "core/rendering/RenderLayerCompositor.h"
-#include "core/rendering/RenderPart.h"
-#include "core/rendering/RenderScrollbar.h"
-#include "core/rendering/RenderScrollbarPart.h"
-#include "core/rendering/RenderTheme.h"
-#include "core/rendering/RenderView.h"
-#include "core/rendering/TextAutosizer.h"
-#include "core/rendering/style/RenderStyle.h"
-#include "core/rendering/svg/RenderSVGRoot.h"
-#include "core/svg/SVGDocument.h"
-#include "core/svg/SVGSVGElement.h"
-
-#include "wtf/CurrentTime.h"
-#include "wtf/TemporaryChange.h"
-
-#include "core/platform/chromium/TraceEvent.h"
-
-namespace WebCore {
-
-using namespace HTMLNames;
-
-double FrameView::s_currentFrameTimeStamp = 0.0;
-bool FrameView::s_inPaintContents = false;
-
-
-// REPAINT_THROTTLING now chooses default values for throttling parameters.
-// Should be removed when applications start using runtime configuration.
-#if ENABLE(REPAINT_THROTTLING)
-// Normal delay
-double FrameView::s_normalDeferredRepaintDelay = 0.016;
-// Negative value would mean that first few repaints happen without a delay
-double FrameView::s_initialDeferredRepaintDelayDuringLoading = 0;
-// The delay grows on each repaint to this maximum value
-double FrameView::s_maxDeferredRepaintDelayDuringLoading = 2.5;
-// On each repaint the delay increses by this amount
-double FrameView::s_deferredRepaintDelayIncrementDuringLoading = 0.5;
-#else
-// FIXME: Repaint throttling could be good to have on all platform.
-// The balance between CPU use and repaint frequency will need some tuning for desktop.
-// More hooks may be needed to reset the delay on things like GIF and CSS animations.
-double FrameView::s_normalDeferredRepaintDelay = 0;
-double FrameView::s_initialDeferredRepaintDelayDuringLoading = 0;
-double FrameView::s_maxDeferredRepaintDelayDuringLoading = 0;
-double FrameView::s_deferredRepaintDelayIncrementDuringLoading = 0;
-#endif
-
-// The maximum number of updateWidgets iterations that should be done before returning.
-static const unsigned maxUpdateWidgetsIterations = 2;
-
-static RenderLayer::UpdateLayerPositionsFlags updateLayerPositionFlags(RenderLayer* layer, bool isRelayoutingSubtree, bool didFullRepaint)
-{
- RenderLayer::UpdateLayerPositionsFlags flags = RenderLayer::defaultFlags;
- if (didFullRepaint) {
- flags &= ~RenderLayer::CheckForRepaint;
- flags |= RenderLayer::NeedsFullRepaintInBacking;
- }
- if (isRelayoutingSubtree && layer->isPaginated())
- flags |= RenderLayer::UpdatePagination;
- return flags;
-}
-
-Pagination::Mode paginationModeForRenderStyle(RenderStyle* style)
-{
- EOverflow overflow = style->overflowY();
- if (overflow != OPAGEDX && overflow != OPAGEDY)
- return Pagination::Unpaginated;
-
- bool isHorizontalWritingMode = style->isHorizontalWritingMode();
- TextDirection textDirection = style->direction();
- WritingMode writingMode = style->writingMode();
-
- // paged-x always corresponds to LeftToRightPaginated or RightToLeftPaginated. If the WritingMode
- // is horizontal, then we use TextDirection to choose between those options. If the WritingMode
- // is vertical, then the direction of the verticality dictates the choice.
- if (overflow == OPAGEDX) {
- if ((isHorizontalWritingMode && textDirection == LTR) || writingMode == LeftToRightWritingMode)
- return Pagination::LeftToRightPaginated;
- return Pagination::RightToLeftPaginated;
- }
-
- // paged-y always corresponds to TopToBottomPaginated or BottomToTopPaginated. If the WritingMode
- // is horizontal, then the direction of the horizontality dictates the choice. If the WritingMode
- // is vertical, then we use TextDirection to choose between those options.
- if (writingMode == TopToBottomWritingMode || (!isHorizontalWritingMode && textDirection == RTL))
- return Pagination::TopToBottomPaginated;
- return Pagination::BottomToTopPaginated;
-}
-
-FrameView::FrameView(Frame* frame)
- : m_frame(frame)
- , m_canHaveScrollbars(true)
- , m_slowRepaintObjectCount(0)
- , m_layoutTimer(this, &FrameView::layoutTimerFired)
- , m_layoutRoot(0)
- , m_inSynchronousPostLayout(false)
- , m_postLayoutTasksTimer(this, &FrameView::postLayoutTimerFired)
- , m_isTransparent(false)
- , m_baseBackgroundColor(Color::white)
- , m_mediaType("screen")
- , m_actionScheduler(adoptPtr(new FrameActionScheduler))
- , m_overflowStatusDirty(true)
- , m_viewportRenderer(0)
- , m_wasScrolledByUser(false)
- , m_inProgrammaticScroll(false)
- , m_safeToPropagateScrollToParent(true)
- , m_deferredRepaintTimer(this, &FrameView::deferredRepaintTimerFired)
- , m_disableRepaints(0)
- , m_isTrackingRepaints(false)
- , m_shouldUpdateWhileOffscreen(true)
- , m_deferSetNeedsLayouts(0)
- , m_setNeedsLayoutWasDeferred(false)
- , m_scrollCorner(0)
- , m_shouldAutoSize(false)
- , m_inAutoSize(false)
- , m_didRunAutosize(false)
- , m_hasSoftwareFilters(false)
- , m_visibleContentScaleFactor(1)
- , m_partialLayout()
-{
- ASSERT(m_frame);
- init();
-
- if (!isMainFrame())
- return;
-
- ScrollableArea::setVerticalScrollElasticity(ScrollElasticityAllowed);
- ScrollableArea::setHorizontalScrollElasticity(ScrollElasticityAllowed);
-}
-
-PassRefPtr<FrameView> FrameView::create(Frame* frame)
-{
- RefPtr<FrameView> view = adoptRef(new FrameView(frame));
- view->show();
- return view.release();
-}
-
-PassRefPtr<FrameView> FrameView::create(Frame* frame, const IntSize& initialSize)
-{
- RefPtr<FrameView> view = adoptRef(new FrameView(frame));
- view->Widget::setFrameRect(IntRect(view->location(), initialSize));
- view->show();
- return view.release();
-}
-
-FrameView::~FrameView()
-{
- if (m_postLayoutTasksTimer.isActive()) {
- m_postLayoutTasksTimer.stop();
- m_actionScheduler->clear();
- }
-
- removeFromAXObjectCache();
- resetScrollbars();
-
- // Custom scrollbars should already be destroyed at this point
- ASSERT(!horizontalScrollbar() || !horizontalScrollbar()->isCustomScrollbar());
- ASSERT(!verticalScrollbar() || !verticalScrollbar()->isCustomScrollbar());
-
- setHasHorizontalScrollbar(false); // Remove native scrollbars now before we lose the connection to the HostWindow.
- setHasVerticalScrollbar(false);
-
- ASSERT(!m_scrollCorner);
- ASSERT(m_actionScheduler->isEmpty());
-
- ASSERT(m_frame);
- ASSERT(m_frame->view() != this || !m_frame->contentRenderer());
- RenderPart* renderer = m_frame->ownerRenderer();
- if (renderer && renderer->widget() == this)
- renderer->setWidget(0);
-}
-
-void FrameView::reset()
-{
- m_cannotBlitToWindow = false;
- m_isOverlapped = false;
- m_contentIsOpaque = false;
- m_borderX = 30;
- m_borderY = 30;
- m_layoutTimer.stop();
- m_layoutRoot = 0;
- m_delayedLayout = false;
- m_doFullRepaint = true;
- m_layoutSchedulingEnabled = true;
- m_inLayout = false;
- m_doingPreLayoutStyleUpdate = false;
- m_inSynchronousPostLayout = false;
- m_layoutCount = 0;
- m_nestedLayoutCount = 0;
- m_postLayoutTasksTimer.stop();
- m_firstLayout = true;
- m_firstLayoutCallbackPending = false;
- m_wasScrolledByUser = false;
- m_safeToPropagateScrollToParent = true;
- m_lastViewportSize = IntSize();
- m_lastZoomFactor = 1.0f;
- m_deferringRepaints = 0;
- m_repaintCount = 0;
- m_repaintRects.clear();
- m_deferredRepaintDelay = s_initialDeferredRepaintDelayDuringLoading;
- m_deferredRepaintTimer.stop();
- m_isTrackingRepaints = false;
- m_trackedRepaintRects.clear();
- m_lastPaintTime = 0;
- m_paintBehavior = PaintBehaviorNormal;
- m_isPainting = false;
- m_visuallyNonEmptyCharacterCount = 0;
- m_visuallyNonEmptyPixelCount = 0;
- m_isVisuallyNonEmpty = false;
- m_firstVisuallyNonEmptyLayoutCallbackPending = true;
- m_maintainScrollPositionAnchor = 0;
- m_disableRepaints = 0;
- m_partialLayout.reset();
-}
-
-void FrameView::removeFromAXObjectCache()
-{
- if (AXObjectCache* cache = axObjectCache())
- cache->remove(this);
-}
-
-void FrameView::resetScrollbars()
-{
- // Reset the document's scrollbars back to our defaults before we yield the floor.
- m_firstLayout = true;
- setScrollbarsSuppressed(true);
- if (m_canHaveScrollbars)
- setScrollbarModes(ScrollbarAuto, ScrollbarAuto);
- else
- setScrollbarModes(ScrollbarAlwaysOff, ScrollbarAlwaysOff);
- setScrollbarsSuppressed(false);
-}
-
-void FrameView::init()
-{
- reset();
-
- m_margins = LayoutSize(-1, -1); // undefined
- m_size = LayoutSize();
-
- // Propagate the marginwidth/height and scrolling modes to the view.
- Element* ownerElement = m_frame->ownerElement();
- if (ownerElement && (ownerElement->hasTagName(frameTag) || ownerElement->hasTagName(iframeTag))) {
- HTMLFrameElementBase* frameElt = toHTMLFrameElementBase(ownerElement);
- if (frameElt->scrollingMode() == ScrollbarAlwaysOff)
- setCanHaveScrollbars(false);
- LayoutUnit marginWidth = frameElt->marginWidth();
- LayoutUnit marginHeight = frameElt->marginHeight();
- if (marginWidth != -1)
- setMarginWidth(marginWidth);
- if (marginHeight != -1)
- setMarginHeight(marginHeight);
- }
-}
-
-void FrameView::prepareForDetach()
-{
- RELEASE_ASSERT(!isInLayout());
-
- if (ScrollAnimator* scrollAnimator = existingScrollAnimator())
- scrollAnimator->cancelAnimations();
-
- detachCustomScrollbars();
- // When the view is no longer associated with a frame, it needs to be removed from the ax object cache
- // right now, otherwise it won't be able to reach the topDocument()'s axObject cache later.
- removeFromAXObjectCache();
-
- if (m_frame->page()) {
- if (ScrollingCoordinator* scrollingCoordinator = m_frame->page()->scrollingCoordinator())
- scrollingCoordinator->willDestroyScrollableArea(this);
- }
-}
-
-void FrameView::detachCustomScrollbars()
-{
- Scrollbar* horizontalBar = horizontalScrollbar();
- if (horizontalBar && horizontalBar->isCustomScrollbar())
- setHasHorizontalScrollbar(false);
-
- Scrollbar* verticalBar = verticalScrollbar();
- if (verticalBar && verticalBar->isCustomScrollbar())
- setHasVerticalScrollbar(false);
-
- if (m_scrollCorner) {
- m_scrollCorner->destroy();
- m_scrollCorner = 0;
- }
-}
-
-void FrameView::recalculateScrollbarOverlayStyle()
-{
- ScrollbarOverlayStyle oldOverlayStyle = scrollbarOverlayStyle();
- ScrollbarOverlayStyle overlayStyle = ScrollbarOverlayStyleDefault;
-
- Color backgroundColor = documentBackgroundColor();
- if (backgroundColor.isValid()) {
- // Reduce the background color from RGB to a lightness value
- // and determine which scrollbar style to use based on a lightness
- // heuristic.
- double hue, saturation, lightness;
- backgroundColor.getHSL(hue, saturation, lightness);
- if (lightness <= .5)
- overlayStyle = ScrollbarOverlayStyleLight;
- }
-
- if (oldOverlayStyle != overlayStyle)
- setScrollbarOverlayStyle(overlayStyle);
-}
-
-void FrameView::clear()
-{
- setCanBlitOnScroll(true);
-
- reset();
-
- if (RenderPart* renderer = m_frame->ownerRenderer())
- renderer->viewCleared();
-
- setScrollbarsSuppressed(true);
-}
-
-bool FrameView::didFirstLayout() const
-{
- return !m_firstLayout;
-}
-
-void FrameView::invalidateRect(const IntRect& rect)
-{
- if (!parent()) {
- if (HostWindow* window = hostWindow())
- window->invalidateContentsAndRootView(rect);
- return;
- }
-
- RenderPart* renderer = m_frame->ownerRenderer();
- if (!renderer)
- return;
-
- IntRect repaintRect = rect;
- repaintRect.move(renderer->borderLeft() + renderer->paddingLeft(),
- renderer->borderTop() + renderer->paddingTop());
- renderer->repaintRectangle(repaintRect);
-}
-
-void FrameView::setFrameRect(const IntRect& newRect)
-{
- IntRect oldRect = frameRect();
- if (newRect == oldRect)
- return;
-
- // Autosized font sizes depend on the width of the viewing area.
- if (newRect.width() != oldRect.width()) {
- Page* page = m_frame->page();
- if (isMainFrame() && page->settings().textAutosizingEnabled()) {
- for (Frame* frame = page->mainFrame(); frame; frame = frame->tree()->traverseNext())
- m_frame->document()->textAutosizer()->recalculateMultipliers();
- }
- }
-
- ScrollView::setFrameRect(newRect);
-
- updateScrollableAreaSet();
-
- if (RenderView* renderView = this->renderView()) {
- if (renderView->usesCompositing())
- renderView->compositor()->frameViewDidChangeSize();
- }
-
- sendResizeEventIfNeeded();
-}
-
-bool FrameView::scheduleAnimation()
-{
- if (HostWindow* window = hostWindow()) {
- window->scheduleAnimation();
- return true;
- }
- return false;
-}
-
-RenderView* FrameView::renderView() const
-{
- return frame().contentRenderer();
-}
-
-int FrameView::mapFromLayoutToCSSUnits(LayoutUnit value) const
-{
- return value / frame().pageZoomFactor();
-}
-
-LayoutUnit FrameView::mapFromCSSToLayoutUnits(int value) const
-{
- return value * frame().pageZoomFactor();
-}
-
-void FrameView::setMarginWidth(LayoutUnit w)
-{
- // make it update the rendering area when set
- m_margins.setWidth(w);
-}
-
-void FrameView::setMarginHeight(LayoutUnit h)
-{
- // make it update the rendering area when set
- m_margins.setHeight(h);
-}
-
-void FrameView::setCanHaveScrollbars(bool canHaveScrollbars)
-{
- m_canHaveScrollbars = canHaveScrollbars;
- ScrollView::setCanHaveScrollbars(canHaveScrollbars);
-}
-
-void FrameView::updateCanHaveScrollbars()
-{
- ScrollbarMode hMode;
- ScrollbarMode vMode;
- scrollbarModes(hMode, vMode);
- if (hMode == ScrollbarAlwaysOff && vMode == ScrollbarAlwaysOff)
- setCanHaveScrollbars(false);
- else
- setCanHaveScrollbars(true);
-}
-
-PassRefPtr<Scrollbar> FrameView::createScrollbar(ScrollbarOrientation orientation)
-{
- if (Settings* settings = m_frame->settings()) {
- if (!settings->allowCustomScrollbarInMainFrame() && isMainFrame())
- return ScrollView::createScrollbar(orientation);
- }
-
- // FIXME: We need to update the scrollbar dynamically as documents change (or as doc elements and bodies get discovered that have custom styles).
- Document* doc = m_frame->document();
-
- // Try the <body> element first as a scrollbar source.
- Element* body = doc ? doc->body() : 0;
- if (body && body->renderer() && body->renderer()->style()->hasPseudoStyle(SCROLLBAR))
- return RenderScrollbar::createCustomScrollbar(this, orientation, body);
-
- // If the <body> didn't have a custom style, then the root element might.
- Element* docElement = doc ? doc->documentElement() : 0;
- if (docElement && docElement->renderer() && docElement->renderer()->style()->hasPseudoStyle(SCROLLBAR))
- return RenderScrollbar::createCustomScrollbar(this, orientation, docElement);
-
- // If we have an owning iframe/frame element, then it can set the custom scrollbar also.
- RenderPart* frameRenderer = m_frame->ownerRenderer();
- if (frameRenderer && frameRenderer->style()->hasPseudoStyle(SCROLLBAR))
- return RenderScrollbar::createCustomScrollbar(this, orientation, 0, m_frame.get());
-
- // Nobody set a custom style, so we just use a native scrollbar.
- return ScrollView::createScrollbar(orientation);
-}
-
-void FrameView::setContentsSize(const IntSize& size)
-{
- if (size == contentsSize())
- return;
-
- m_deferSetNeedsLayouts++;
-
- ScrollView::setContentsSize(size);
- ScrollView::contentsResized();
-
- Page* page = frame().page();
- if (!page)
- return;
-
- updateScrollableAreaSet();
-
- page->chrome().contentsSizeChanged(m_frame.get(), size); // Notify only.
-
- m_deferSetNeedsLayouts--;
-
- if (!m_deferSetNeedsLayouts)
- m_setNeedsLayoutWasDeferred = false; // FIXME: Find a way to make the deferred layout actually happen.
-}
-
-void FrameView::adjustViewSize()
-{
- RenderView* renderView = this->renderView();
- if (!renderView)
- return;
-
- ASSERT(m_frame->view() == this);
-
- const IntRect rect = renderView->documentRect();
- const IntSize& size = rect.size();
- ScrollView::setScrollOrigin(IntPoint(-rect.x(), -rect.y()), !m_frame->document()->printing(), size == contentsSize());
-
- setContentsSize(size);
-}
-
-void FrameView::applyOverflowToViewport(RenderObject* o, ScrollbarMode& hMode, ScrollbarMode& vMode)
-{
- // Handle the overflow:hidden/scroll case for the body/html elements. WinIE treats
- // overflow:hidden and overflow:scroll on <body> as applying to the document's
- // scrollbars. The CSS2.1 draft states that HTML UAs should use the <html> or <body> element and XML/XHTML UAs should
- // use the root element.
-
- EOverflow overflowX = o->style()->overflowX();
- EOverflow overflowY = o->style()->overflowY();
-
- if (o->isSVGRoot()) {
- // overflow is ignored in stand-alone SVG documents.
- if (!toRenderSVGRoot(o)->isEmbeddedThroughFrameContainingSVGDocument())
- return;
- overflowX = OHIDDEN;
- overflowY = OHIDDEN;
- }
-
- bool ignoreOverflowHidden = false;
- if (m_frame->page()->settings().ignoreMainFrameOverflowHiddenQuirk() && m_frame->page()->mainFrame() == m_frame)
- ignoreOverflowHidden = true;
-
- switch (overflowX) {
- case OHIDDEN:
- if (!ignoreOverflowHidden)
- hMode = ScrollbarAlwaysOff;
- break;
- case OSCROLL:
- hMode = ScrollbarAlwaysOn;
- break;
- case OAUTO:
- hMode = ScrollbarAuto;
- break;
- default:
- // Don't set it at all.
- ;
- }
-
- switch (overflowY) {
- case OHIDDEN:
- if (!ignoreOverflowHidden)
- vMode = ScrollbarAlwaysOff;
- break;
- case OSCROLL:
- vMode = ScrollbarAlwaysOn;
- break;
- case OAUTO:
- vMode = ScrollbarAuto;
- break;
- default:
- // Don't set it at all. Values of OPAGEDX and OPAGEDY are handled by applyPaginationToViewPort().
- ;
- }
-
- m_viewportRenderer = o;
-}
-
-void FrameView::applyPaginationToViewport()
-{
- Document* document = m_frame->document();
- Node* documentElement = document->documentElement();
- RenderObject* documentRenderer = documentElement ? documentElement->renderer() : 0;
- RenderObject* documentOrBodyRenderer = documentRenderer;
- Node* body = document->body();
- if (body && body->renderer()) {
- if (body->hasTagName(bodyTag))
- documentOrBodyRenderer = documentRenderer->style()->overflowX() == OVISIBLE && isHTMLHtmlElement(documentElement) ? body->renderer() : documentRenderer;
- }
-
- Pagination pagination;
-
- if (!documentOrBodyRenderer) {
- setPagination(pagination);
- return;
- }
-
- EOverflow overflowY = documentOrBodyRenderer->style()->overflowY();
- if (overflowY == OPAGEDX || overflowY == OPAGEDY) {
- pagination.mode = WebCore::paginationModeForRenderStyle(documentOrBodyRenderer->style());
- pagination.gap = static_cast<unsigned>(documentOrBodyRenderer->style()->columnGap());
- }
-
- setPagination(pagination);
-}
-
-void FrameView::calculateScrollbarModesForLayout(ScrollbarMode& hMode, ScrollbarMode& vMode, ScrollbarModesCalculationStrategy strategy)
-{
- m_viewportRenderer = 0;
-
- const HTMLFrameOwnerElement* owner = m_frame->ownerElement();
- if (owner && (owner->scrollingMode() == ScrollbarAlwaysOff)) {
- hMode = ScrollbarAlwaysOff;
- vMode = ScrollbarAlwaysOff;
- return;
- }
-
- if (m_canHaveScrollbars || strategy == RulesFromWebContentOnly) {
- hMode = ScrollbarAuto;
- // Seamless documents begin with heights of 0; we special case that here
- // to correctly render documents that don't need scrollbars.
- IntSize fullVisibleSize = visibleContentRect(IncludeScrollbars).size();
- bool isSeamlessDocument = frame().document() && frame().document()->shouldDisplaySeamlesslyWithParent();
- vMode = (isSeamlessDocument && !fullVisibleSize.height()) ? ScrollbarAlwaysOff : ScrollbarAuto;
- } else {
- hMode = ScrollbarAlwaysOff;
- vMode = ScrollbarAlwaysOff;
- }
-
- if (!m_layoutRoot) {
- Document* document = m_frame->document();
- Node* documentElement = document->documentElement();
- RenderObject* rootRenderer = documentElement ? documentElement->renderer() : 0;
- Node* body = document->body();
- if (body && body->renderer()) {
- if (body->hasTagName(framesetTag)) {
- vMode = ScrollbarAlwaysOff;
- hMode = ScrollbarAlwaysOff;
- } else if (body->hasTagName(bodyTag)) {
- // It's sufficient to just check the X overflow,
- // since it's illegal to have visible in only one direction.
- RenderObject* o = rootRenderer->style()->overflowX() == OVISIBLE && isHTMLHtmlElement(document->documentElement()) ? body->renderer() : rootRenderer;
- if (o->style())
- applyOverflowToViewport(o, hMode, vMode);
- }
- } else if (rootRenderer)
- applyOverflowToViewport(rootRenderer, hMode, vMode);
- }
-}
-
-void FrameView::updateCompositingLayersAfterStyleChange()
-{
- TRACE_EVENT0("webkit", "FrameView::updateCompositingLayersAfterStyleChange");
- RenderView* renderView = this->renderView();
- if (!renderView)
- return;
-
- // If we expect to update compositing after an incipient layout, don't do so here.
- if (m_doingPreLayoutStyleUpdate || layoutPending() || renderView->needsLayout())
- return;
-
- // This call will make sure the cached hasAcceleratedCompositing is updated from the pref
- renderView->compositor()->cacheAcceleratedCompositingFlags();
-
- // Sometimes we will change a property (for example, z-index) that will not
- // cause a layout, but will require us to update compositing state. We only
- // need to do this if a layout is not already scheduled.
- if (!needsLayout())
- renderView->compositor()->updateCompositingRequirementsState();
-
- renderView->compositor()->updateCompositingLayers(CompositingUpdateAfterStyleChange);
-}
-
-void FrameView::updateCompositingLayersAfterLayout()
-{
- TRACE_EVENT0("webkit", "FrameView::updateCompositingLayersAfterLayout");
- RenderView* renderView = this->renderView();
- if (!renderView)
- return;
-
- // This call will make sure the cached hasAcceleratedCompositing is updated from the pref
- renderView->compositor()->cacheAcceleratedCompositingFlags();
- renderView->compositor()->updateCompositingRequirementsState();
- renderView->compositor()->updateCompositingLayers(CompositingUpdateAfterLayout);
-}
-
-bool FrameView::usesCompositedScrolling() const
-{
- RenderView* renderView = this->renderView();
- if (!renderView)
- return false;
- if (m_frame->settings() && m_frame->settings()->compositedScrollingForFramesEnabled())
- return renderView->compositor()->inForcedCompositingMode();
- return false;
-}
-
-GraphicsLayer* FrameView::layerForScrolling() const
-{
- RenderView* renderView = this->renderView();
- if (!renderView)
- return 0;
- return renderView->compositor()->scrollLayer();
-}
-
-GraphicsLayer* FrameView::layerForHorizontalScrollbar() const
-{
- RenderView* renderView = this->renderView();
- if (!renderView)
- return 0;
- return renderView->compositor()->layerForHorizontalScrollbar();
-}
-
-GraphicsLayer* FrameView::layerForVerticalScrollbar() const
-{
- RenderView* renderView = this->renderView();
- if (!renderView)
- return 0;
- return renderView->compositor()->layerForVerticalScrollbar();
-}
-
-GraphicsLayer* FrameView::layerForScrollCorner() const
-{
- RenderView* renderView = this->renderView();
- if (!renderView)
- return 0;
- return renderView->compositor()->layerForScrollCorner();
-}
-
-#if USE(RUBBER_BANDING)
-GraphicsLayer* FrameView::layerForOverhangAreas() const
-{
- RenderView* renderView = this->renderView();
- if (!renderView)
- return 0;
- return renderView->compositor()->layerForOverhangAreas();
-}
-#endif // USE(RUBBER_BANDING)
-
-bool FrameView::hasCompositedContent() const
-{
- if (RenderView* renderView = this->renderView())
- return renderView->compositor()->inCompositingMode();
- return false;
-}
-
-bool FrameView::isEnclosedInCompositingLayer() const
-{
- RenderObject* frameOwnerRenderer = m_frame->ownerRenderer();
- if (frameOwnerRenderer && frameOwnerRenderer->containerForRepaint())
- return true;
-
- if (FrameView* parentView = parentFrameView())
- return parentView->isEnclosedInCompositingLayer();
-
- return false;
-}
-
-bool FrameView::isSoftwareRenderable() const
-{
- RenderView* renderView = this->renderView();
- return !renderView || !renderView->compositor()->has3DContent();
-}
-
-RenderObject* FrameView::layoutRoot(bool onlyDuringLayout) const
-{
- return onlyDuringLayout && layoutPending() ? 0 : m_layoutRoot;
-}
-
-static inline void collectFrameViewChildren(FrameView* frameView, Vector<RefPtr<FrameView> >& frameViews)
-{
- const HashSet<RefPtr<Widget> >* viewChildren = frameView->children();
- ASSERT(viewChildren);
-
- const HashSet<RefPtr<Widget> >::iterator end = viewChildren->end();
- for (HashSet<RefPtr<Widget> >::iterator current = viewChildren->begin(); current != end; ++current) {
- Widget* widget = (*current).get();
- if (widget->isFrameView())
- frameViews.append(toFrameView(widget));
- }
-}
-
-inline void FrameView::forceLayoutParentViewIfNeeded()
-{
- RenderPart* ownerRenderer = m_frame->ownerRenderer();
- if (!ownerRenderer || !ownerRenderer->frame())
- return;
-
- RenderBox* contentBox = embeddedContentBox();
- if (!contentBox)
- return;
-
- RenderSVGRoot* svgRoot = toRenderSVGRoot(contentBox);
- if (svgRoot->everHadLayout() && !svgRoot->needsLayout())
- return;
-
- // If the embedded SVG document appears the first time, the ownerRenderer has already finished
- // layout without knowing about the existence of the embedded SVG document, because RenderReplaced
- // embeddedContentBox() returns 0, as long as the embedded document isn't loaded yet. Before
- // bothering to lay out the SVG document, mark the ownerRenderer needing layout and ask its
- // FrameView for a layout. After that the RenderEmbeddedObject (ownerRenderer) carries the
- // correct size, which RenderSVGRoot::computeReplacedLogicalWidth/Height rely on, when laying
- // out for the first time, or when the RenderSVGRoot size has changed dynamically (eg. via <script>).
- RefPtr<FrameView> frameView = ownerRenderer->frame()->view();
-
- // Mark the owner renderer as needing layout.
- ownerRenderer->setNeedsLayoutAndPrefWidthsRecalc();
-
- // Synchronously enter layout, to layout the view containing the host object/embed/iframe.
- ASSERT(frameView);
- frameView->layout();
-}
-
-void FrameView::performPreLayoutTasks()
-{
- // Don't schedule more layouts, we're in one.
- TemporaryChange<bool> changeSchedulingEnabled(m_layoutSchedulingEnabled, false);
-
- if (!m_nestedLayoutCount && !m_inSynchronousPostLayout && m_postLayoutTasksTimer.isActive() && !frame().document()->shouldDisplaySeamlesslyWithParent()) {
- // This is a new top-level layout. If there are any remaining tasks from the previous layout, finish them now.
- m_inSynchronousPostLayout = true;
- performPostLayoutTasks();
- m_inSynchronousPostLayout = false;
- }
-
- // Viewport-dependent media queries may cause us to need completely different style information.
- Document* document = m_frame->document();
- if (!document->styleResolverIfExists() || document->styleResolverIfExists()->affectedByViewportChange()) {
- document->styleResolverChanged(RecalcStyleDeferred);
- // FIXME: This instrumentation event is not strictly accurate since cached media query results
- // do not persist across StyleResolver rebuilds.
- InspectorInstrumentation::mediaQueryResultChanged(document);
- } else {
- document->evaluateMediaQueryList();
- }
-
- // If there is any pagination to apply, it will affect the RenderView's style, so we should
- // take care of that now.
- applyPaginationToViewport();
-
- // Always ensure our style info is up-to-date. This can happen in situations where
- // the layout beats any sort of style recalc update that needs to occur.
- TemporaryChange<bool> changeDoingPreLayoutStyleUpdate(m_doingPreLayoutStyleUpdate, true);
- document->updateStyleIfNeeded();
-}
-
-void FrameView::performLayout(RenderObject* rootForThisLayout, bool inSubtreeLayout)
-{
- // performLayout is the actual guts of layout().
- // FIXME: The 300 other lines in layout() probably belong in other helper functions
- // so that a single human could understand what layout() is actually doing.
- {
- bool disableLayoutState = false;
- if (inSubtreeLayout) {
- RenderView* view = rootForThisLayout->view();
- disableLayoutState = view->shouldDisableLayoutStateForSubtree(rootForThisLayout);
- view->pushLayoutState(rootForThisLayout);
- }
- LayoutStateDisabler layoutStateDisabler(disableLayoutState ? rootForThisLayout->view() : 0);
-
- m_inLayout = true;
-
- beginDeferredRepaints();
- forceLayoutParentViewIfNeeded();
- renderView()->updateConfiguration();
-
- // Text Autosizing requires two-pass layout which is incompatible with partial layout.
- // If enabled, only do partial layout for the second layout.
- // FIXME (crbug.com/256657): Do not do two layouts for text autosizing.
- PartialLayoutDisabler partialLayoutDisabler(partialLayout(), m_frame->settings() && m_frame->settings()->textAutosizingEnabled());
-
- LayoutIndicator layoutIndicator;
- rootForThisLayout->layout();
- }
-
- bool autosized = frame().document()->textAutosizer()->processSubtree(rootForThisLayout);
- if (autosized && rootForThisLayout->needsLayout()) {
- TRACE_EVENT0("webkit", "2nd layout due to Text Autosizing");
- LayoutIndicator layoutIndicator;
- rootForThisLayout->layout();
- }
-
- endDeferredRepaints();
- m_inLayout = false;
-
- if (inSubtreeLayout)
- rootForThisLayout->view()->popLayoutState(rootForThisLayout);
-}
-
-void FrameView::scheduleOrPerformPostLayoutTasks()
-{
- if (m_postLayoutTasksTimer.isActive()) {
- m_actionScheduler->resume();
- return;
- }
-
- // Partial layouts should not happen with synchronous post layouts.
- ASSERT(!(m_inSynchronousPostLayout && partialLayout().isStopping()));
-
- if (!m_inSynchronousPostLayout) {
- if (frame().document()->shouldDisplaySeamlesslyWithParent()) {
- if (RenderView* renderView = this->renderView())
- renderView->updateWidgetPositions();
- } else {
- m_inSynchronousPostLayout = true;
- // Calls resumeScheduledEvents()
- performPostLayoutTasks();
- m_inSynchronousPostLayout = false;
- }
- }
-
- if (!m_postLayoutTasksTimer.isActive() && (needsLayout() || m_inSynchronousPostLayout || frame().document()->shouldDisplaySeamlesslyWithParent())) {
- // If we need layout or are already in a synchronous call to postLayoutTasks(),
- // defer widget updates and event dispatch until after we return. postLayoutTasks()
- // can make us need to update again, and we can get stuck in a nasty cycle unless
- // we call it through the timer here.
- m_postLayoutTasksTimer.startOneShot(0);
- if (!partialLayout().isStopping() && needsLayout()) {
- m_actionScheduler->pause();
- layout();
- }
- }
-}
-
-void FrameView::layout(bool allowSubtree)
-{
- // We should never layout a Document which is not in a Frame.
- ASSERT(m_frame);
- ASSERT(m_frame->view() == this);
- ASSERT(m_frame->page());
-
- if (m_inLayout)
- return;
-
- ASSERT(!partialLayout().isStopping());
-
- TRACE_EVENT0("webkit", "FrameView::layout");
- TRACE_EVENT_SCOPED_SAMPLING_STATE("Blink", "Layout");
-
- // Protect the view from being deleted during layout (in recalcStyle)
- RefPtr<FrameView> protector(this);
-
- // Every scroll that happens during layout is programmatic.
- TemporaryChange<bool> changeInProgrammaticScroll(m_inProgrammaticScroll, true);
-
- m_layoutTimer.stop();
- m_delayedLayout = false;
- m_setNeedsLayoutWasDeferred = false;
-
- // we shouldn't enter layout() while painting
- ASSERT(!isPainting());
- if (isPainting())
- return;
-
- InspectorInstrumentationCookie cookie = InspectorInstrumentation::willLayout(m_frame.get());
-
- if (!allowSubtree && m_layoutRoot) {
- m_layoutRoot->markContainingBlocksForLayout(false);
- m_layoutRoot = 0;
- }
-
- performPreLayoutTasks();
-
- // If there is only one ref to this view left, then its going to be destroyed as soon as we exit,
- // so there's no point to continuing to layout
- if (protector->hasOneRef())
- return;
-
- Document* document = m_frame->document();
- bool inSubtreeLayout = m_layoutRoot;
- RenderObject* rootForThisLayout = inSubtreeLayout ? m_layoutRoot : document->renderer();
- if (!rootForThisLayout) {
- // FIXME: Do we need to set m_size here?
- ASSERT_NOT_REACHED();
- return;
- }
-
- bool isPartialLayout = partialLayout().isPartialLayout();
-
- FontCachePurgePreventer fontCachePurgePreventer;
- RenderLayer* layer;
- {
- TemporaryChange<bool> changeSchedulingEnabled(m_layoutSchedulingEnabled, false);
-
- m_nestedLayoutCount++;
-
- updateCounters();
- autoSizeIfEnabled();
-
- ScrollbarMode hMode;
- ScrollbarMode vMode;
- calculateScrollbarModesForLayout(hMode, vMode);
-
- m_doFullRepaint = !inSubtreeLayout && !isPartialLayout && (m_firstLayout || toRenderView(rootForThisLayout)->document().printing());
-
- if (!inSubtreeLayout && !isPartialLayout) {
- // Now set our scrollbar state for the layout.
- ScrollbarMode currentHMode = horizontalScrollbarMode();
- ScrollbarMode currentVMode = verticalScrollbarMode();
-
- if (m_firstLayout || (hMode != currentHMode || vMode != currentVMode)) {
- if (m_firstLayout) {
- setScrollbarsSuppressed(true);
-
- m_firstLayout = false;
- m_firstLayoutCallbackPending = true;
- m_lastViewportSize = layoutSize(IncludeScrollbars);
- m_lastZoomFactor = rootForThisLayout->style()->zoom();
-
- // Set the initial vMode to AlwaysOn if we're auto.
- if (vMode == ScrollbarAuto)
- setVerticalScrollbarMode(ScrollbarAlwaysOn); // This causes a vertical scrollbar to appear.
- // Set the initial hMode to AlwaysOff if we're auto.
- if (hMode == ScrollbarAuto)
- setHorizontalScrollbarMode(ScrollbarAlwaysOff); // This causes a horizontal scrollbar to disappear.
-
- setScrollbarModes(hMode, vMode);
- setScrollbarsSuppressed(false, true);
- } else
- setScrollbarModes(hMode, vMode);
- }
-
- LayoutSize oldSize = m_size;
-
- m_size = LayoutSize(layoutWidth(), layoutHeight());
-
- if (oldSize != m_size) {
- m_doFullRepaint = true;
- if (!m_firstLayout) {
- RenderBox* rootRenderer = document->documentElement() ? document->documentElement()->renderBox() : 0;
- RenderBox* bodyRenderer = rootRenderer && document->body() ? document->body()->renderBox() : 0;
- if (bodyRenderer && bodyRenderer->stretchesToViewport())
- bodyRenderer->setChildNeedsLayout();
- else if (rootRenderer && rootRenderer->stretchesToViewport())
- rootRenderer->setChildNeedsLayout();
- }
- }
- }
-
- layer = rootForThisLayout->enclosingLayer();
-
- m_actionScheduler->pause();
-
- performLayout(rootForThisLayout, inSubtreeLayout);
- m_layoutRoot = 0;
- } // Reset m_layoutSchedulingEnabled to its previous value.
-
- bool neededFullRepaint = m_doFullRepaint;
-
- if (!inSubtreeLayout && !isPartialLayout && !toRenderView(rootForThisLayout)->document().printing())
- adjustViewSize();
-
- m_doFullRepaint = neededFullRepaint;
-
- // Now update the positions of all layers.
- beginDeferredRepaints();
- if (m_doFullRepaint) {
- // FIXME: This isn't really right, since the RenderView doesn't fully encompass
- // the visibleContentRect(). It just happens to work out most of the time,
- // since first layouts and printing don't have you scrolled anywhere.
- rootForThisLayout->view()->repaint();
- }
-
- layer->updateLayerPositionsAfterLayout(renderView()->layer(), updateLayerPositionFlags(layer, inSubtreeLayout, m_doFullRepaint));
-
- endDeferredRepaints();
-
- updateCompositingLayersAfterLayout();
-
- m_layoutCount++;
-
- if (AXObjectCache* cache = rootForThisLayout->document().existingAXObjectCache())
- cache->postNotification(rootForThisLayout, AXObjectCache::AXLayoutComplete, true);
- updateAnnotatedRegions();
-
- ASSERT(partialLayout().isStopping() || !rootForThisLayout->needsLayout());
-
- updateCanBlitOnScrollRecursively();
-
- if (document->hasListenerType(Document::OVERFLOWCHANGED_LISTENER))
- updateOverflowStatus(layoutWidth() < contentsWidth(), layoutHeight() < contentsHeight());
-
- // Resume scheduled events (FrameActionScheduler m_actionScheduler)
- // and ensure post layout tasks are executed or scheduled to be.
- scheduleOrPerformPostLayoutTasks();
-
- InspectorInstrumentation::didLayout(cookie, rootForThisLayout);
-
- m_nestedLayoutCount--;
- if (m_nestedLayoutCount)
- return;
-
- if (partialLayout().isStopping())
- return;
-
-#ifndef NDEBUG
- // Post-layout assert that nobody was re-marked as needing layout during layout.
- document->renderer()->assertSubtreeIsLaidOut();
-#endif
-
- // FIXME: It should be not possible to remove the FrameView from the frame/page during layout
- // however m_inLayout is not set for most of this function, so none of our RELEASE_ASSERTS
- // in Frame/Page will fire. One of the post-layout tasks is disconnecting the Frame from
- // the page in fast/frames/crash-remove-iframe-during-object-beforeload-2.html
- // necessitating this check here.
- // ASSERT(frame()->page());
- if (frame().page())
- frame().page()->chrome().client().layoutUpdated(m_frame.get());
-}
-
-RenderBox* FrameView::embeddedContentBox() const
-{
- RenderView* renderView = this->renderView();
- if (!renderView)
- return 0;
-
- RenderObject* firstChild = renderView->firstChild();
- if (!firstChild || !firstChild->isBox())
- return 0;
-
- // Curently only embedded SVG documents participate in the size-negotiation logic.
- if (firstChild->isSVGRoot())
- return toRenderBox(firstChild);
-
- return 0;
-}
-
-void FrameView::addWidgetToUpdate(RenderObject* object)
-{
- if (!m_widgetUpdateSet)
- m_widgetUpdateSet = adoptPtr(new RenderObjectSet);
-
- // Tell the DOM element that it needs a widget update.
- Node* node = object->node();
- if (node->hasTagName(objectTag) || node->hasTagName(embedTag)) {
- HTMLPlugInImageElement* pluginElement = toHTMLPlugInImageElement(node);
- pluginElement->setNeedsWidgetUpdate(true);
- }
-
- m_widgetUpdateSet->add(object);
-}
-
-void FrameView::removeWidgetToUpdate(RenderObject* object)
-{
- if (!m_widgetUpdateSet)
- return;
-
- m_widgetUpdateSet->remove(object);
-}
-
-void FrameView::setMediaType(const AtomicString& mediaType)
-{
- m_mediaType = mediaType;
-}
-
-AtomicString FrameView::mediaType() const
-{
- // See if we have an override type.
- String overrideType;
- InspectorInstrumentation::applyEmulatedMedia(m_frame.get(), &overrideType);
- if (!overrideType.isNull())
- return overrideType;
- return m_mediaType;
-}
-
-void FrameView::adjustMediaTypeForPrinting(bool printing)
-{
- if (printing) {
- if (m_mediaTypeWhenNotPrinting.isNull())
- m_mediaTypeWhenNotPrinting = mediaType();
- setMediaType("print");
- } else {
- if (!m_mediaTypeWhenNotPrinting.isNull())
- setMediaType(m_mediaTypeWhenNotPrinting);
- m_mediaTypeWhenNotPrinting = nullAtom;
- }
-}
-
-bool FrameView::useSlowRepaints(bool considerOverlap) const
-{
- bool mustBeSlow = m_slowRepaintObjectCount > 0;
-
- if (contentsInCompositedLayer())
- return mustBeSlow;
-
- // The chromium compositor does not support scrolling a non-composited frame within a composited page through
- // the fast scrolling path, so force slow scrolling in that case.
- if (m_frame->ownerElement() && !hasCompositedContent() && m_frame->page() && m_frame->page()->mainFrame()->view()->hasCompositedContent())
- return true;
-
- bool isOverlapped = m_isOverlapped && considerOverlap;
-
- if (mustBeSlow || m_cannotBlitToWindow || isOverlapped || !m_contentIsOpaque)
- return true;
-
- if (FrameView* parentView = parentFrameView())
- return parentView->useSlowRepaints(considerOverlap);
-
- return false;
-}
-
-bool FrameView::useSlowRepaintsIfNotOverlapped() const
-{
- return useSlowRepaints(false);
-}
-
-void FrameView::updateCanBlitOnScrollRecursively()
-{
- for (Frame* frame = m_frame.get(); frame; frame = frame->tree()->traverseNext(m_frame.get())) {
- if (FrameView* view = frame->view())
- view->setCanBlitOnScroll(!view->useSlowRepaints());
- }
-}
-
-bool FrameView::contentsInCompositedLayer() const
-{
- RenderView* renderView = this->renderView();
- if (renderView && renderView->isComposited()) {
- GraphicsLayer* layer = renderView->layer()->backing()->graphicsLayer();
- if (layer && layer->drawsContent())
- return true;
- }
-
- return false;
-}
-
-void FrameView::setCannotBlitToWindow()
-{
- m_cannotBlitToWindow = true;
- updateCanBlitOnScrollRecursively();
-}
-
-void FrameView::addSlowRepaintObject()
-{
- if (!m_slowRepaintObjectCount++) {
- updateCanBlitOnScrollRecursively();
-
- if (Page* page = m_frame->page()) {
- if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
- scrollingCoordinator->frameViewHasSlowRepaintObjectsDidChange(this);
- }
- }
-}
-
-void FrameView::removeSlowRepaintObject()
-{
- ASSERT(m_slowRepaintObjectCount > 0);
- m_slowRepaintObjectCount--;
- if (!m_slowRepaintObjectCount) {
- updateCanBlitOnScrollRecursively();
-
- if (Page* page = m_frame->page()) {
- if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
- scrollingCoordinator->frameViewHasSlowRepaintObjectsDidChange(this);
- }
- }
-}
-
-void FrameView::addViewportConstrainedObject(RenderObject* object)
-{
- if (!m_viewportConstrainedObjects)
- m_viewportConstrainedObjects = adoptPtr(new ViewportConstrainedObjectSet);
-
- if (!m_viewportConstrainedObjects->contains(object)) {
- m_viewportConstrainedObjects->add(object);
-
- if (Page* page = m_frame->page()) {
- if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
- scrollingCoordinator->frameViewFixedObjectsDidChange(this);
- }
- }
-}
-
-void FrameView::removeViewportConstrainedObject(RenderObject* object)
-{
- if (m_viewportConstrainedObjects && m_viewportConstrainedObjects->contains(object)) {
- m_viewportConstrainedObjects->remove(object);
- if (Page* page = m_frame->page()) {
- if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
- scrollingCoordinator->frameViewFixedObjectsDidChange(this);
- }
-
- // FIXME: In addFixedObject() we only call this if there's a platform widget,
- // why isn't the same check being made here?
- updateCanBlitOnScrollRecursively();
- }
-}
-
-LayoutRect FrameView::viewportConstrainedVisibleContentRect() const
-{
- LayoutRect viewportRect = visibleContentRect();
- // Ignore overhang. No-op when not using rubber banding.
- viewportRect.setLocation(clampScrollPosition(scrollPosition()));
- return viewportRect;
-}
-
-
-IntSize FrameView::scrollOffsetForFixedPosition() const
-{
- return toIntSize(clampScrollPosition(scrollPosition()));
-}
-
-IntPoint FrameView::lastKnownMousePosition() const
-{
- return m_frame->eventHandler()->lastKnownMousePosition();
-}
-
-bool FrameView::scrollContentsFastPath(const IntSize& scrollDelta, const IntRect& rectToScroll, const IntRect& clipRect)
-{
- if (!m_viewportConstrainedObjects || m_viewportConstrainedObjects->isEmpty()) {
- hostWindow()->scroll(scrollDelta, rectToScroll, clipRect);
- return true;
- }
-
- const bool isCompositedContentLayer = contentsInCompositedLayer();
-
- // Get the rects of the fixed objects visible in the rectToScroll
- Region regionToUpdate;
- ViewportConstrainedObjectSet::const_iterator end = m_viewportConstrainedObjects->end();
- for (ViewportConstrainedObjectSet::const_iterator it = m_viewportConstrainedObjects->begin(); it != end; ++it) {
- RenderObject* renderer = *it;
- if (!renderer->style()->hasViewportConstrainedPosition())
- continue;
-
- // Fixed items should always have layers.
- ASSERT(renderer->hasLayer());
- RenderLayer* layer = toRenderBoxModelObject(renderer)->layer();
-
- // Composited layers may still actually paint into their ancestor.
- // If that happens, the viewport constrained object needs to be
- // repainted on scroll.
- if (layer->isComposited() && !layer->backing()->paintsIntoCompositedAncestor())
- continue;
-
- if (layer->viewportConstrainedNotCompositedReason() == RenderLayer::NotCompositedForBoundsOutOfView
- || layer->viewportConstrainedNotCompositedReason() == RenderLayer::NotCompositedForNoVisibleContent) {
- // Don't invalidate for invisible fixed layers.
- continue;
- }
-
- if (layer->hasAncestorWithFilterOutsets()) {
- // If the fixed layer has a blur/drop-shadow filter applied on at least one of its parents, we cannot
- // scroll using the fast path, otherwise the outsets of the filter will be moved around the page.
- return false;
- }
-
- IntRect updateRect = pixelSnappedIntRect(layer->repaintRectIncludingNonCompositingDescendants());
-
- RenderLayer* enclosingCompositingLayer = layer->enclosingCompositingLayer(false);
- if (enclosingCompositingLayer && !enclosingCompositingLayer->renderer()->isRenderView()) {
- // If the fixed-position layer is contained by a composited layer that is not its containing block,
- // then we have to invlidate that enclosing layer, not the RenderView.
- updateRect.moveBy(scrollPosition());
- IntRect previousRect = updateRect;
- previousRect.move(scrollDelta);
- updateRect.unite(previousRect);
- enclosingCompositingLayer->setBackingNeedsRepaintInRect(updateRect);
- } else {
- // Coalesce the repaints that will be issued to the renderView.
- updateRect = contentsToRootView(updateRect);
- if (!isCompositedContentLayer && clipsRepaints())
- updateRect.intersect(rectToScroll);
- if (!updateRect.isEmpty())
- regionToUpdate.unite(updateRect);
- }
- }
-
- // 1) scroll
- hostWindow()->scroll(scrollDelta, rectToScroll, clipRect);
-
- // 2) update the area of fixed objects that has been invalidated
- Vector<IntRect> subRectsToUpdate = regionToUpdate.rects();
- size_t viewportConstrainedObjectsCount = subRectsToUpdate.size();
- for (size_t i = 0; i < viewportConstrainedObjectsCount; ++i) {
- IntRect updateRect = subRectsToUpdate[i];
- IntRect scrolledRect = updateRect;
- scrolledRect.move(scrollDelta);
- updateRect.unite(scrolledRect);
- if (isCompositedContentLayer) {
- updateRect = rootViewToContents(updateRect);
- ASSERT(renderView());
- renderView()->layer()->setBackingNeedsRepaintInRect(updateRect);
- continue;
- }
- if (clipsRepaints())
- updateRect.intersect(rectToScroll);
- hostWindow()->invalidateContentsAndRootView(updateRect);
- }
-
- return true;
-}
-
-void FrameView::scrollContentsSlowPath(const IntRect& updateRect)
-{
- if (contentsInCompositedLayer()) {
- IntRect updateRect = visibleContentRect();
- ASSERT(renderView());
- renderView()->layer()->setBackingNeedsRepaintInRect(updateRect);
- }
- if (RenderPart* frameRenderer = m_frame->ownerRenderer()) {
- if (isEnclosedInCompositingLayer()) {
- LayoutRect rect(frameRenderer->borderLeft() + frameRenderer->paddingLeft(),
- frameRenderer->borderTop() + frameRenderer->paddingTop(),
- visibleWidth(), visibleHeight());
- frameRenderer->repaintRectangle(rect);
- return;
- }
- }
-
- ScrollView::scrollContentsSlowPath(updateRect);
-}
-
-// Note that this gets called at painting time.
-void FrameView::setIsOverlapped(bool isOverlapped)
-{
- if (isOverlapped == m_isOverlapped)
- return;
-
- m_isOverlapped = isOverlapped;
- updateCanBlitOnScrollRecursively();
-}
-
-bool FrameView::isOverlappedIncludingAncestors() const
-{
- if (isOverlapped())
- return true;
-
- if (FrameView* parentView = parentFrameView()) {
- if (parentView->isOverlapped())
- return true;
- }
-
- return false;
-}
-
-void FrameView::setContentIsOpaque(bool contentIsOpaque)
-{
- if (contentIsOpaque == m_contentIsOpaque)
- return;
-
- m_contentIsOpaque = contentIsOpaque;
- updateCanBlitOnScrollRecursively();
-}
-
-void FrameView::restoreScrollbar()
-{
- setScrollbarsSuppressed(false);
-}
-
-bool FrameView::scrollToFragment(const KURL& url)
-{
- // If our URL has no ref, then we have no place we need to jump to.
- // OTOH If CSS target was set previously, we want to set it to 0, recalc
- // and possibly repaint because :target pseudo class may have been
- // set (see bug 11321).
- if (!url.hasFragmentIdentifier() && !m_frame->document()->cssTarget())
- return false;
-
- String fragmentIdentifier = url.fragmentIdentifier();
- if (scrollToAnchor(fragmentIdentifier))
- return true;
-
- // Try again after decoding the ref, based on the document's encoding.
- if (m_frame->document()->encoding().isValid())
- return scrollToAnchor(decodeURLEscapeSequences(fragmentIdentifier, m_frame->document()->encoding()));
-
- return false;
-}
-
-bool FrameView::scrollToAnchor(const String& name)
-{
- ASSERT(m_frame->document());
-
- if (!m_frame->document()->haveStylesheetsLoaded()) {
- m_frame->document()->setGotoAnchorNeededAfterStylesheetsLoad(true);
- return false;
- }
-
- m_frame->document()->setGotoAnchorNeededAfterStylesheetsLoad(false);
-
- Element* anchorNode = m_frame->document()->findAnchor(name);
-
- // Setting to null will clear the current target.
- m_frame->document()->setCSSTarget(anchorNode);
-
- if (m_frame->document()->isSVGDocument()) {
- if (SVGSVGElement* svg = toSVGDocument(m_frame->document())->rootElement()) {
- svg->setupInitialView(name, anchorNode);
- if (!anchorNode)
- return true;
- }
- }
-
- // Implement the rule that "" and "top" both mean top of page as in other browsers.
- if (!anchorNode && !(name.isEmpty() || equalIgnoringCase(name, "top")))
- return false;
-
- maintainScrollPositionAtAnchor(anchorNode ? static_cast<Node*>(anchorNode) : m_frame->document());
-
- // If the anchor accepts keyboard focus, move focus there to aid users relying on keyboard navigation.
- if (anchorNode && anchorNode->isFocusable())
- m_frame->document()->setFocusedElement(anchorNode);
-
- return true;
-}
-
-void FrameView::maintainScrollPositionAtAnchor(Node* anchorNode)
-{
- m_maintainScrollPositionAnchor = anchorNode;
- if (!m_maintainScrollPositionAnchor)
- return;
-
- // We need to update the layout before scrolling, otherwise we could
- // really mess things up if an anchor scroll comes at a bad moment.
- m_frame->document()->updateStyleIfNeeded();
- // Only do a layout if changes have occurred that make it necessary.
- RenderView* renderView = this->renderView();
- if (renderView && renderView->needsLayout())
- layout();
- else
- scrollToAnchor();
-}
-
-void FrameView::scrollElementToRect(Element* element, const IntRect& rect)
-{
- m_frame->document()->updateLayoutIgnorePendingStylesheets();
-
- LayoutRect bounds = element->boundingBox();
- int centeringOffsetX = (rect.width() - bounds.width()) / 2;
- int centeringOffsetY = (rect.height() - bounds.height()) / 2;
- setScrollPosition(IntPoint(bounds.x() - centeringOffsetX - rect.x(), bounds.y() - centeringOffsetY - rect.y()));
-}
-
-void FrameView::setScrollPosition(const IntPoint& scrollPoint)
-{
- TemporaryChange<bool> changeInProgrammaticScroll(m_inProgrammaticScroll, true);
- m_maintainScrollPositionAnchor = 0;
-
- IntPoint newScrollPosition = adjustScrollPositionWithinRange(scrollPoint);
-
- if (newScrollPosition == scrollPosition())
- return;
-
- Page* page = m_frame->page();
- if (page && RuntimeEnabledFeatures::programmaticScrollNotificationsEnabled())
- page->chrome().client().didProgrammaticallyScroll(m_frame.get(), newScrollPosition);
-
- if (requestScrollPositionUpdate(newScrollPosition))
- return;
-
- ScrollView::setScrollPosition(newScrollPosition);
-}
-
-void FrameView::setScrollPositionNonProgrammatically(const IntPoint& scrollPoint)
-{
- IntPoint newScrollPosition = adjustScrollPositionWithinRange(scrollPoint);
-
- if (newScrollPosition == scrollPosition())
- return;
-
- TemporaryChange<bool> changeInProgrammaticScroll(m_inProgrammaticScroll, false);
- notifyScrollPositionChanged(newScrollPosition);
-}
-
-void FrameView::setViewportConstrainedObjectsNeedLayout()
-{
- if (!hasViewportConstrainedObjects())
- return;
-
- ViewportConstrainedObjectSet::const_iterator end = m_viewportConstrainedObjects->end();
- for (ViewportConstrainedObjectSet::const_iterator it = m_viewportConstrainedObjects->begin(); it != end; ++it) {
- RenderObject* renderer = *it;
- renderer->setNeedsLayout();
- }
-}
-
-
-void FrameView::scrollPositionChanged()
-{
- m_frame->eventHandler()->sendScrollEvent();
- m_frame->eventHandler()->dispatchFakeMouseMoveEventSoon();
-
- if (RenderView* renderView = this->renderView()) {
- if (renderView->usesCompositing())
- renderView->compositor()->frameViewDidScroll();
- }
-}
-
-void FrameView::repaintFixedElementsAfterScrolling()
-{
- // For fixed position elements, update widget positions and compositing layers after scrolling,
- // but only if we're not inside of layout.
- if (!m_nestedLayoutCount && hasViewportConstrainedObjects()) {
- if (RenderView* renderView = this->renderView()) {
- renderView->updateWidgetPositions();
- renderView->layer()->updateLayerPositionsAfterDocumentScroll();
- }
- }
-}
-
-void FrameView::updateFixedElementsAfterScrolling()
-{
- if (m_nestedLayoutCount <= 1 && hasViewportConstrainedObjects()) {
- if (RenderView* renderView = this->renderView())
- renderView->compositor()->updateCompositingLayers(CompositingUpdateOnScroll);
- }
-}
-
-bool FrameView::shouldRubberBandInDirection(ScrollDirection direction) const
-{
- Page* page = frame().page();
- if (!page)
- return ScrollView::shouldRubberBandInDirection(direction);
- return page->chrome().client().shouldRubberBandInDirection(direction);
-}
-
-bool FrameView::isRubberBandInProgress() const
-{
- if (scrollbarsSuppressed())
- return false;
-
- // If the main thread updates the scroll position for this FrameView, we should return
- // ScrollAnimator::isRubberBandInProgress().
- if (ScrollAnimator* scrollAnimator = existingScrollAnimator())
- return scrollAnimator->isRubberBandInProgress();
-
- return false;
-}
-
-bool FrameView::requestScrollPositionUpdate(const IntPoint& position)
-{
- return false;
-}
-
-HostWindow* FrameView::hostWindow() const
-{
- Page* page = frame().page();
- if (!page)
- return 0;
- return &page->chrome();
-}
-
-const unsigned cRepaintRectUnionThreshold = 25;
-
-void FrameView::repaintContentRectangle(const IntRect& r)
-{
- ASSERT(!m_frame->ownerElement());
-
- if (m_isTrackingRepaints) {
- IntRect repaintRect = r;
- repaintRect.move(-scrollOffset());
- m_trackedRepaintRects.append(repaintRect);
- }
-
- double delay = m_deferringRepaints ? 0 : adjustedDeferredRepaintDelay();
- if (m_deferringRepaints || m_deferredRepaintTimer.isActive() || delay) {
- IntRect paintRect = r;
- if (clipsRepaints() && !paintsEntireContents())
- paintRect.intersect(visibleContentRect());
- if (paintRect.isEmpty())
- return;
- if (m_repaintCount == cRepaintRectUnionThreshold) {
- IntRect unionedRect;
- for (unsigned i = 0; i < cRepaintRectUnionThreshold; ++i)
- unionedRect.unite(pixelSnappedIntRect(m_repaintRects[i]));
- m_repaintRects.clear();
- m_repaintRects.append(unionedRect);
- }
- if (m_repaintCount < cRepaintRectUnionThreshold)
- m_repaintRects.append(paintRect);
- else
- m_repaintRects[0].unite(paintRect);
- m_repaintCount++;
-
- if (!m_deferringRepaints)
- startDeferredRepaintTimer(delay);
-
- return;
- }
-
- if (!shouldUpdate())
- return;
-
- ScrollView::repaintContentRectangle(r);
-}
-
-void FrameView::contentsResized()
-{
- ScrollView::contentsResized();
- setNeedsLayout();
-}
-
-void FrameView::visibleContentsResized()
-{
- // We check to make sure the view is attached to a frame() as this method can
- // be triggered before the view is attached by Frame::createView(...) setting
- // various values such as setScrollBarModes(...) for example. An ASSERT is
- // triggered when a view is layout before being attached to a frame().
- if (!frame().view())
- return;
-
- if (!useFixedLayout() && needsLayout())
- layout();
-
- if (RenderView* renderView = this->renderView()) {
- if (renderView->usesCompositing())
- renderView->compositor()->frameViewDidChangeSize();
- }
-}
-
-void FrameView::beginDeferredRepaints()
-{
- Page* page = m_frame->page();
- ASSERT(page);
-
- if (!isMainFrame()) {
- page->mainFrame()->view()->beginDeferredRepaints();
- return;
- }
-
- m_deferringRepaints++;
-}
-
-void FrameView::endDeferredRepaints()
-{
- Page* page = m_frame->page();
- ASSERT(page);
-
- if (!isMainFrame()) {
- page->mainFrame()->view()->endDeferredRepaints();
- return;
- }
-
- ASSERT(m_deferringRepaints > 0);
-
- if (--m_deferringRepaints)
- return;
-
- if (m_deferredRepaintTimer.isActive())
- return;
-
- if (double delay = adjustedDeferredRepaintDelay()) {
- startDeferredRepaintTimer(delay);
- return;
- }
-
- doDeferredRepaints();
-}
-
-void FrameView::startDeferredRepaintTimer(double delay)
-{
- if (m_deferredRepaintTimer.isActive())
- return;
-
- if (m_disableRepaints)
- return;
-
- m_deferredRepaintTimer.startOneShot(delay);
-}
-
-void FrameView::handleLoadCompleted()
-{
- // Once loading has completed, allow autoSize one last opportunity to
- // reduce the size of the frame.
- autoSizeIfEnabled();
- if (shouldUseLoadTimeDeferredRepaintDelay())
- return;
- m_deferredRepaintDelay = s_normalDeferredRepaintDelay;
- flushDeferredRepaints();
-}
-
-void FrameView::flushDeferredRepaints()
-{
- if (!m_deferredRepaintTimer.isActive())
- return;
- m_deferredRepaintTimer.stop();
- doDeferredRepaints();
-}
-
-void FrameView::doDeferredRepaints()
-{
- if (m_disableRepaints)
- return;
-
- ASSERT(!m_deferringRepaints);
- if (!shouldUpdate()) {
- m_repaintRects.clear();
- m_repaintCount = 0;
- return;
- }
- unsigned size = m_repaintRects.size();
- for (unsigned i = 0; i < size; i++) {
- ScrollView::repaintContentRectangle(pixelSnappedIntRect(m_repaintRects[i]));
- }
- m_repaintRects.clear();
- m_repaintCount = 0;
-
- updateDeferredRepaintDelayAfterRepaint();
-}
-
-bool FrameView::shouldUseLoadTimeDeferredRepaintDelay() const
-{
- // Don't defer after the initial load of the page has been completed.
- if (m_frame->tree()->top()->document()->loadEventFinished())
- return false;
- Document* document = m_frame->document();
- if (!document)
- return false;
- if (document->parsing())
- return true;
- if (document->fetcher()->requestCount())
- return true;
- return false;
-}
-
-void FrameView::updateDeferredRepaintDelayAfterRepaint()
-{
- if (!shouldUseLoadTimeDeferredRepaintDelay()) {
- m_deferredRepaintDelay = s_normalDeferredRepaintDelay;
- return;
- }
- double incrementedRepaintDelay = m_deferredRepaintDelay + s_deferredRepaintDelayIncrementDuringLoading;
- m_deferredRepaintDelay = std::min(incrementedRepaintDelay, s_maxDeferredRepaintDelayDuringLoading);
-}
-
-void FrameView::resetDeferredRepaintDelay()
-{
- m_deferredRepaintDelay = 0;
- if (m_deferredRepaintTimer.isActive()) {
- m_deferredRepaintTimer.stop();
- if (!m_deferringRepaints)
- doDeferredRepaints();
- }
-}
-
-double FrameView::adjustedDeferredRepaintDelay() const
-{
- ASSERT(!m_deferringRepaints);
- if (!m_deferredRepaintDelay)
- return 0;
- double timeSinceLastPaint = currentTime() - m_lastPaintTime;
- return max(0., m_deferredRepaintDelay - timeSinceLastPaint);
-}
-
-void FrameView::deferredRepaintTimerFired(Timer<FrameView>*)
-{
- doDeferredRepaints();
-}
-
-void FrameView::beginDisableRepaints()
-{
- m_disableRepaints++;
-}
-
-void FrameView::endDisableRepaints()
-{
- ASSERT(m_disableRepaints > 0);
- m_disableRepaints--;
-}
-
-void FrameView::layoutTimerFired(Timer<FrameView>*)
-{
- layout();
-}
-
-void FrameView::scheduleRelayout()
-{
- ASSERT(m_frame->view() == this);
-
- if (m_layoutRoot) {
- m_layoutRoot->markContainingBlocksForLayout(false);
- m_layoutRoot = 0;
- }
- if (!m_layoutSchedulingEnabled)
- return;
- if (!needsLayout())
- return;
- if (!m_frame->document()->shouldScheduleLayout())
- return;
- InspectorInstrumentation::didInvalidateLayout(m_frame.get());
-
- // When frame seamless is enabled, the contents of the frame could affect the layout of the parent frames.
- // Also invalidate parent frame starting from the owner element of this frame.
- if (m_frame->ownerRenderer() && m_frame->document()->shouldDisplaySeamlesslyWithParent())
- m_frame->ownerRenderer()->setNeedsLayout();
-
- int delay = m_frame->document()->minimumLayoutDelay();
- if (m_layoutTimer.isActive() && m_delayedLayout && !delay)
- unscheduleRelayout();
- if (m_layoutTimer.isActive())
- return;
-
- m_delayedLayout = delay != 0;
- m_layoutTimer.startOneShot(delay * 0.001);
-}
-
-static bool isObjectAncestorContainerOf(RenderObject* ancestor, RenderObject* descendant)
-{
- for (RenderObject* r = descendant; r; r = r->container()) {
- if (r == ancestor)
- return true;
- }
- return false;
-}
-
-void FrameView::scheduleRelayoutOfSubtree(RenderObject* relayoutRoot)
-{
- ASSERT(m_frame->view() == this);
-
- RenderView* renderView = this->renderView();
- if (renderView && renderView->needsLayout()) {
- if (relayoutRoot)
- relayoutRoot->markContainingBlocksForLayout(false);
- return;
- }
-
- if (layoutPending() || !m_layoutSchedulingEnabled) {
- if (m_layoutRoot != relayoutRoot) {
- if (isObjectAncestorContainerOf(m_layoutRoot, relayoutRoot)) {
- // Keep the current root
- relayoutRoot->markContainingBlocksForLayout(false, m_layoutRoot);
- ASSERT(!m_layoutRoot->container() || !m_layoutRoot->container()->needsLayout());
- } else if (m_layoutRoot && isObjectAncestorContainerOf(relayoutRoot, m_layoutRoot)) {
- // Re-root at relayoutRoot
- m_layoutRoot->markContainingBlocksForLayout(false, relayoutRoot);
- m_layoutRoot = relayoutRoot;
- ASSERT(!m_layoutRoot->container() || !m_layoutRoot->container()->needsLayout());
- InspectorInstrumentation::didInvalidateLayout(m_frame.get());
- } else {
- // Just do a full relayout
- if (m_layoutRoot)
- m_layoutRoot->markContainingBlocksForLayout(false);
- m_layoutRoot = 0;
- relayoutRoot->markContainingBlocksForLayout(false);
- InspectorInstrumentation::didInvalidateLayout(m_frame.get());
- }
- }
- } else if (m_layoutSchedulingEnabled) {
- int delay = m_frame->document()->minimumLayoutDelay();
- m_layoutRoot = relayoutRoot;
- ASSERT(!m_layoutRoot->container() || !m_layoutRoot->container()->needsLayout());
- InspectorInstrumentation::didInvalidateLayout(m_frame.get());
- m_delayedLayout = delay != 0;
- m_layoutTimer.startOneShot(delay * 0.001);
- }
-}
-
-bool FrameView::layoutPending() const
-{
- return m_layoutTimer.isActive();
-}
-
-bool FrameView::needsLayout() const
-{
- // This can return true in cases where the document does not have a body yet.
- // Document::shouldScheduleLayout takes care of preventing us from scheduling
- // layout in that case.
-
- RenderView* renderView = this->renderView();
- return layoutPending()
- || (renderView && renderView->needsLayout())
- || m_layoutRoot
- || (m_deferSetNeedsLayouts && m_setNeedsLayoutWasDeferred);
-}
-
-void FrameView::setNeedsLayout()
-{
- if (m_deferSetNeedsLayouts) {
- m_setNeedsLayoutWasDeferred = true;
- return;
- }
-
- if (RenderView* renderView = this->renderView())
- renderView->setNeedsLayout();
-}
-
-void FrameView::unscheduleRelayout()
-{
- if (!m_layoutTimer.isActive())
- return;
-
- m_layoutTimer.stop();
- m_delayedLayout = false;
-}
-
-void FrameView::serviceScriptedAnimations(double monotonicAnimationStartTime)
-{
- for (RefPtr<Frame> frame = m_frame; frame; frame = frame->tree()->traverseNext()) {
- frame->view()->serviceScrollAnimations();
- if (!RuntimeEnabledFeatures::webAnimationsCSSEnabled())
- frame->animation()->serviceAnimations();
- if (RuntimeEnabledFeatures::webAnimationsEnabled())
- frame->document()->timeline()->serviceAnimations(monotonicAnimationStartTime);
- }
-
- Vector<RefPtr<Document> > documents;
- for (Frame* frame = m_frame.get(); frame; frame = frame->tree()->traverseNext())
- documents.append(frame->document());
-
- for (size_t i = 0; i < documents.size(); ++i)
- documents[i]->serviceScriptedAnimations(monotonicAnimationStartTime);
-}
-
-bool FrameView::isTransparent() const
-{
- return m_isTransparent;
-}
-
-void FrameView::setTransparent(bool isTransparent)
-{
- m_isTransparent = isTransparent;
- if (renderView() && renderView()->layer()->backing())
- renderView()->layer()->backing()->updateContentsOpaque();
-}
-
-bool FrameView::hasOpaqueBackground() const
-{
- return !m_isTransparent && !m_baseBackgroundColor.hasAlpha();
-}
-
-Color FrameView::baseBackgroundColor() const
-{
- return m_baseBackgroundColor;
-}
-
-void FrameView::setBaseBackgroundColor(const Color& backgroundColor)
-{
- if (!backgroundColor.isValid())
- m_baseBackgroundColor = Color::white;
- else
- m_baseBackgroundColor = backgroundColor;
-
- if (RenderLayerBacking* backing = renderView() ? renderView()->layer()->backing() : 0) {
- backing->updateContentsOpaque();
- if (backing->graphicsLayer())
- backing->graphicsLayer()->setNeedsDisplay();
- }
- recalculateScrollbarOverlayStyle();
-}
-
-void FrameView::updateBackgroundRecursively(const Color& backgroundColor, bool transparent)
-{
- for (Frame* frame = m_frame.get(); frame; frame = frame->tree()->traverseNext(m_frame.get())) {
- if (FrameView* view = frame->view()) {
- view->setTransparent(transparent);
- view->setBaseBackgroundColor(backgroundColor);
- }
- }
-}
-
-bool FrameView::shouldUpdateWhileOffscreen() const
-{
- return m_shouldUpdateWhileOffscreen;
-}
-
-void FrameView::setShouldUpdateWhileOffscreen(bool shouldUpdateWhileOffscreen)
-{
- m_shouldUpdateWhileOffscreen = shouldUpdateWhileOffscreen;
-}
-
-bool FrameView::shouldUpdate() const
-{
- if (isOffscreen() && !shouldUpdateWhileOffscreen())
- return false;
- return true;
-}
-
-void FrameView::scheduleEvent(PassRefPtr<Event> event, PassRefPtr<Node> eventTarget)
-{
- m_actionScheduler->scheduleEvent(event, eventTarget);
-}
-
-void FrameView::pauseScheduledEvents()
-{
- m_actionScheduler->pause();
-}
-
-void FrameView::resumeScheduledEvents()
-{
- m_actionScheduler->resume();
-}
-
-void FrameView::scrollToAnchor()
-{
- RefPtr<Node> anchorNode = m_maintainScrollPositionAnchor;
- if (!anchorNode)
- return;
-
- if (!anchorNode->renderer())
- return;
-
- LayoutRect rect;
- if (anchorNode != m_frame->document())
- rect = anchorNode->boundingBox();
-
- // Scroll nested layers and frames to reveal the anchor.
- // Align to the top and to the closest side (this matches other browsers).
- anchorNode->renderer()->scrollRectToVisible(rect, ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignTopAlways);
-
- if (AXObjectCache* cache = m_frame->document()->existingAXObjectCache())
- cache->handleScrolledToAnchor(anchorNode.get());
-
- // scrollRectToVisible can call into setScrollPosition(), which resets m_maintainScrollPositionAnchor.
- m_maintainScrollPositionAnchor = anchorNode;
-}
-
-void FrameView::updateWidget(RenderObject* object)
-{
- ASSERT(!object->node() || object->node()->isElementNode());
- Element* ownerElement = toElement(object->node());
- // The object may have already been destroyed (thus node cleared),
- // but FrameView holds a manual ref, so it won't have been deleted.
- ASSERT(m_widgetUpdateSet->contains(object));
- if (!ownerElement)
- return;
-
- if (object->isEmbeddedObject()) {
- RenderEmbeddedObject* embeddedObject = static_cast<RenderEmbeddedObject*>(object);
- // No need to update if it's already crashed or known to be missing.
- if (embeddedObject->showsUnavailablePluginIndicator())
- return;
-
- // FIXME: This could turn into a real virtual dispatch if we defined
- // updateWidget(PluginCreationOption) on HTMLElement.
- if (ownerElement->hasTagName(objectTag) || ownerElement->hasTagName(embedTag) || ownerElement->hasTagName(appletTag)) {
- HTMLPlugInImageElement* pluginElement = toHTMLPlugInImageElement(ownerElement);
- if (pluginElement->needsWidgetUpdate())
- pluginElement->updateWidget(CreateAnyWidgetType);
- } else
- ASSERT_NOT_REACHED();
-
- // Caution: it's possible the object was destroyed again, since loading a
- // plugin may run any arbitrary JavaScript.
- embeddedObject->updateWidgetPosition();
- }
-}
-
-bool FrameView::updateWidgets()
-{
- if (m_nestedLayoutCount > 1 || !m_widgetUpdateSet || m_widgetUpdateSet->isEmpty())
- return true;
-
- size_t size = m_widgetUpdateSet->size();
-
- Vector<RenderObject*> objects;
- objects.reserveInitialCapacity(size);
-
- RenderObjectSet::const_iterator end = m_widgetUpdateSet->end();
- for (RenderObjectSet::const_iterator it = m_widgetUpdateSet->begin(); it != end; ++it) {
- RenderObject* object = *it;
- objects.uncheckedAppend(object);
- if (object->isEmbeddedObject()) {
- RenderEmbeddedObject* embeddedObject = static_cast<RenderEmbeddedObject*>(object);
- embeddedObject->ref();
- }
- }
-
- for (size_t i = 0; i < size; ++i) {
- RenderObject* object = objects[i];
- updateWidget(object);
- m_widgetUpdateSet->remove(object);
- }
-
- for (size_t i = 0; i < size; ++i) {
- RenderObject* object = objects[i];
- if (object->isEmbeddedObject()) {
- RenderEmbeddedObject* embeddedObject = static_cast<RenderEmbeddedObject*>(object);
- embeddedObject->deref();
- }
- }
-
- return m_widgetUpdateSet->isEmpty();
-}
-
-void FrameView::flushAnyPendingPostLayoutTasks()
-{
- if (!m_postLayoutTasksTimer.isActive())
- return;
-
- performPostLayoutTasks();
-}
-
-void FrameView::performPostLayoutTasks()
-{
- TRACE_EVENT0("webkit", "FrameView::performPostLayoutTasks");
- // updateWidgets() call below can blow us away from underneath.
- RefPtr<FrameView> protect(this);
-
- m_postLayoutTasksTimer.stop();
-
- m_frame->selection().setCaretRectNeedsUpdate();
- m_frame->selection().updateAppearance();
-
- LayoutMilestones milestonesOfInterest = 0;
- LayoutMilestones milestonesAchieved = 0;
- Page* page = m_frame->page();
- if (page)
- milestonesOfInterest = page->layoutMilestones();
-
- if (m_nestedLayoutCount <= 1) {
- if (m_firstLayoutCallbackPending) {
- m_firstLayoutCallbackPending = false;
- m_frame->loader()->didFirstLayout();
- if (milestonesOfInterest & DidFirstLayout)
- milestonesAchieved |= DidFirstLayout;
- if (isMainFrame())
- page->startCountingRelevantRepaintedObjects();
- }
-
- // Ensure that we always send this eventually.
- if (!m_frame->document()->parsing() && m_frame->loader()->stateMachine()->committedFirstRealDocumentLoad())
- m_isVisuallyNonEmpty = true;
-
- // If the layout was done with pending sheets, we are not in fact visually non-empty yet.
- if (m_isVisuallyNonEmpty && !m_frame->document()->didLayoutWithPendingStylesheets() && m_firstVisuallyNonEmptyLayoutCallbackPending) {
- m_firstVisuallyNonEmptyLayoutCallbackPending = false;
- if (milestonesOfInterest & DidFirstVisuallyNonEmptyLayout)
- milestonesAchieved |= DidFirstVisuallyNonEmptyLayout;
- }
- }
-
- m_frame->loader()->didLayout(milestonesAchieved);
- m_frame->document()->fonts()->didLayout();
-
- RenderView* renderView = this->renderView();
- if (renderView)
- renderView->updateWidgetPositions();
-
- for (unsigned i = 0; i < maxUpdateWidgetsIterations; i++) {
- if (updateWidgets())
- break;
- }
-
- if (page) {
- if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
- scrollingCoordinator->frameViewLayoutUpdated(this);
- }
-
- scrollToAnchor();
-
- m_actionScheduler->resume();
-
- sendResizeEventIfNeeded();
-}
-
-void FrameView::sendResizeEventIfNeeded()
-{
- ASSERT(m_frame);
-
- RenderView* renderView = this->renderView();
- if (!renderView || renderView->document().printing())
- return;
-
- IntSize currentSize = layoutSize(IncludeScrollbars);
- float currentZoomFactor = renderView->style()->zoom();
-
- bool shouldSendResizeEvent = currentSize != m_lastViewportSize || currentZoomFactor != m_lastZoomFactor;
-
- m_lastViewportSize = currentSize;
- m_lastZoomFactor = currentZoomFactor;
-
- if (!shouldSendResizeEvent)
- return;
-
- m_frame->eventHandler()->sendResizeEvent();
-
- Page* page = m_frame->page();
- if (isMainFrame())
- InspectorInstrumentation::didResizeMainFrame(page);
-}
-
-void FrameView::postLayoutTimerFired(Timer<FrameView>*)
-{
- performPostLayoutTasks();
-}
-
-void FrameView::updateCounters()
-{
- RenderView* view = renderView();
- if (!view->hasRenderCounters())
- return;
-
- for (RenderObject* renderer = view; renderer; renderer = renderer->nextInPreOrder()) {
- if (!renderer->isCounter())
- continue;
-
- toRenderCounter(renderer)->updateCounter();
- }
-}
-
-void FrameView::autoSizeIfEnabled()
-{
- if (!m_shouldAutoSize)
- return;
-
- if (m_inAutoSize)
- return;
-
- TemporaryChange<bool> changeInAutoSize(m_inAutoSize, true);
-
- Document* document = frame().document();
- if (!document)
- return;
-
- RenderView* documentView = document->renderView();
- Element* documentElement = document->documentElement();
- if (!documentView || !documentElement)
- return;
-
- RenderBox* documentRenderBox = documentElement->renderBox();
- if (!documentRenderBox)
- return;
-
- // If this is the first time we run autosize, start from small height and
- // allow it to grow.
- if (!m_didRunAutosize)
- resize(frameRect().width(), m_minAutoSize.height());
-
- IntSize size = frameRect().size();
-
- // Do the resizing twice. The first time is basically a rough calculation using the preferred width
- // which may result in a height change during the second iteration.
- for (int i = 0; i < 2; i++) {
- // Update various sizes including contentsSize, scrollHeight, etc.
- document->updateLayoutIgnorePendingStylesheets();
- int width = documentView->minPreferredLogicalWidth();
- int height = documentRenderBox->scrollHeight();
- IntSize newSize(width, height);
-
- // Check to see if a scrollbar is needed for a given dimension and
- // if so, increase the other dimension to account for the scrollbar.
- // Since the dimensions are only for the view rectangle, once a
- // dimension exceeds the maximum, there is no need to increase it further.
- if (newSize.width() > m_maxAutoSize.width()) {
- RefPtr<Scrollbar> localHorizontalScrollbar = horizontalScrollbar();
- if (!localHorizontalScrollbar)
- localHorizontalScrollbar = createScrollbar(HorizontalScrollbar);
- if (!localHorizontalScrollbar->isOverlayScrollbar())
- newSize.setHeight(newSize.height() + localHorizontalScrollbar->height());
-
- // Don't bother checking for a vertical scrollbar because the width is at
- // already greater the maximum.
- } else if (newSize.height() > m_maxAutoSize.height()) {
- RefPtr<Scrollbar> localVerticalScrollbar = verticalScrollbar();
- if (!localVerticalScrollbar)
- localVerticalScrollbar = createScrollbar(VerticalScrollbar);
- if (!localVerticalScrollbar->isOverlayScrollbar())
- newSize.setWidth(newSize.width() + localVerticalScrollbar->width());
-
- // Don't bother checking for a horizontal scrollbar because the height is
- // already greater the maximum.
- }
-
- // Ensure the size is at least the min bounds.
- newSize = newSize.expandedTo(m_minAutoSize);
-
- // Bound the dimensions by the max bounds and determine what scrollbars to show.
- ScrollbarMode horizonalScrollbarMode = ScrollbarAlwaysOff;
- if (newSize.width() > m_maxAutoSize.width()) {
- newSize.setWidth(m_maxAutoSize.width());
- horizonalScrollbarMode = ScrollbarAlwaysOn;
- }
- ScrollbarMode verticalScrollbarMode = ScrollbarAlwaysOff;
- if (newSize.height() > m_maxAutoSize.height()) {
- newSize.setHeight(m_maxAutoSize.height());
- verticalScrollbarMode = ScrollbarAlwaysOn;
- }
-
- if (newSize == size)
- continue;
-
- // While loading only allow the size to increase (to avoid twitching during intermediate smaller states)
- // unless autoresize has just been turned on or the maximum size is smaller than the current size.
- if (m_didRunAutosize && size.height() <= m_maxAutoSize.height() && size.width() <= m_maxAutoSize.width()
- && !m_frame->document()->loadEventFinished() && (newSize.height() < size.height() || newSize.width() < size.width()))
- break;
-
- resize(newSize.width(), newSize.height());
- // Force the scrollbar state to avoid the scrollbar code adding them and causing them to be needed. For example,
- // a vertical scrollbar may cause text to wrap and thus increase the height (which is the only reason the scollbar is needed).
- setVerticalScrollbarLock(false);
- setHorizontalScrollbarLock(false);
- setScrollbarModes(horizonalScrollbarMode, verticalScrollbarMode, true, true);
- }
- m_didRunAutosize = true;
-}
-
-void FrameView::updateOverflowStatus(bool horizontalOverflow, bool verticalOverflow)
-{
- if (!m_viewportRenderer)
- return;
-
- if (m_overflowStatusDirty) {
- m_horizontalOverflow = horizontalOverflow;
- m_verticalOverflow = verticalOverflow;
- m_overflowStatusDirty = false;
- return;
- }
-
- bool horizontalOverflowChanged = (m_horizontalOverflow != horizontalOverflow);
- bool verticalOverflowChanged = (m_verticalOverflow != verticalOverflow);
-
- if (horizontalOverflowChanged || verticalOverflowChanged) {
- m_horizontalOverflow = horizontalOverflow;
- m_verticalOverflow = verticalOverflow;
-
- m_actionScheduler->scheduleEvent(OverflowEvent::create(horizontalOverflowChanged, horizontalOverflow,
- verticalOverflowChanged, verticalOverflow),
- m_viewportRenderer->node());
- }
-
-}
-
-const Pagination& FrameView::pagination() const
-{
- if (m_pagination != Pagination())
- return m_pagination;
-
- if (isMainFrame())
- return m_frame->page()->pagination();
-
- return m_pagination;
-}
-
-void FrameView::setPagination(const Pagination& pagination)
-{
- if (m_pagination == pagination)
- return;
-
- m_pagination = pagination;
-
- m_frame->document()->styleResolverChanged(RecalcStyleDeferred);
-}
-
-IntRect FrameView::windowClipRect(bool clipToContents) const
-{
- ASSERT(m_frame->view() == this);
-
- if (paintsEntireContents())
- return IntRect(IntPoint(), contentsSize());
-
- // Set our clip rect to be our contents.
- IntRect clipRect = contentsToWindow(visibleContentRect(clipToContents ? ExcludeScrollbars : IncludeScrollbars));
- if (!m_frame->ownerElement())
- return clipRect;
-
- // Take our owner element and get its clip rect.
- HTMLFrameOwnerElement* ownerElement = m_frame->ownerElement();
- FrameView* parentView = ownerElement->document().view();
- if (parentView)
- clipRect.intersect(parentView->windowClipRectForFrameOwner(ownerElement, true));
- return clipRect;
-}
-
-IntRect FrameView::windowClipRectForFrameOwner(const HTMLFrameOwnerElement* ownerElement, bool clipToLayerContents) const
-{
- // The renderer can sometimes be null when style="display:none" interacts
- // with external content and plugins.
- if (!ownerElement->renderer())
- return windowClipRect();
-
- // If we have no layer, just return our window clip rect.
- const RenderLayer* enclosingLayer = ownerElement->renderer()->enclosingLayer();
- if (!enclosingLayer)
- return windowClipRect();
-
- // Apply the clip from the layer.
- IntRect clipRect;
- if (clipToLayerContents)
- clipRect = pixelSnappedIntRect(enclosingLayer->childrenClipRect());
- else
- clipRect = pixelSnappedIntRect(enclosingLayer->selfClipRect());
- clipRect = contentsToWindow(clipRect);
- return intersection(clipRect, windowClipRect());
-}
-
-bool FrameView::isActive() const
-{
- Page* page = frame().page();
- return page && page->focusController().isActive();
-}
-
-void FrameView::scrollTo(const IntSize& newOffset)
-{
- LayoutSize offset = scrollOffset();
- ScrollView::scrollTo(newOffset);
- if (offset != scrollOffset())
- scrollPositionChanged();
- frame().loader()->client()->didChangeScrollOffset();
-}
-
-void FrameView::invalidateScrollbarRect(Scrollbar* scrollbar, const IntRect& rect)
-{
- // Add in our offset within the FrameView.
- IntRect dirtyRect = rect;
- dirtyRect.moveBy(scrollbar->location());
- invalidateRect(dirtyRect);
-}
-
-void FrameView::getTickmarks(Vector<IntRect>& tickmarks) const
-{
- tickmarks = frame().document()->markers()->renderedRectsForMarkers(DocumentMarker::TextMatch);
-}
-
-IntRect FrameView::windowResizerRect() const
-{
- Page* page = frame().page();
- if (!page)
- return IntRect();
- return page->chrome().windowResizerRect();
-}
-
-void FrameView::setVisibleContentScaleFactor(float visibleContentScaleFactor)
-{
- if (m_visibleContentScaleFactor == visibleContentScaleFactor)
- return;
-
- m_visibleContentScaleFactor = visibleContentScaleFactor;
- updateScrollbars(scrollOffset());
-}
-
-bool FrameView::scrollbarsCanBeActive() const
-{
- if (m_frame->view() != this)
- return false;
-
- return !!m_frame->document();
-}
-
-ScrollableArea* FrameView::enclosingScrollableArea() const
-{
- // FIXME: Walk up the frame tree and look for a scrollable parent frame or RenderLayer.
- return 0;
-}
-
-IntRect FrameView::scrollableAreaBoundingBox() const
-{
- RenderPart* ownerRenderer = frame().ownerRenderer();
- if (!ownerRenderer)
- return frameRect();
-
- return ownerRenderer->absoluteContentQuad().enclosingBoundingBox();
-}
-
-bool FrameView::isScrollable()
-{
- // Check for:
- // 1) If there an actual overflow.
- // 2) display:none or visibility:hidden set to self or inherited.
- // 3) overflow{-x,-y}: hidden;
- // 4) scrolling: no;
-
- // Covers #1
- IntSize contentsSize = this->contentsSize();
- IntSize visibleContentSize = visibleContentRect().size();
- if ((contentsSize.height() <= visibleContentSize.height() && contentsSize.width() <= visibleContentSize.width()))
- return false;
-
- // Covers #2.
- HTMLFrameOwnerElement* owner = m_frame->ownerElement();
- if (owner && (!owner->renderer() || !owner->renderer()->visibleToHitTesting()))
- return false;
-
- // Cover #3 and #4.
- ScrollbarMode horizontalMode;
- ScrollbarMode verticalMode;
- calculateScrollbarModesForLayout(horizontalMode, verticalMode, RulesFromWebContentOnly);
- if (horizontalMode == ScrollbarAlwaysOff && verticalMode == ScrollbarAlwaysOff)
- return false;
-
- return true;
-}
-
-void FrameView::updateScrollableAreaSet()
-{
- // That ensures that only inner frames are cached.
- FrameView* parentFrameView = this->parentFrameView();
- if (!parentFrameView)
- return;
-
- if (!isScrollable()) {
- parentFrameView->removeScrollableArea(this);
- return;
- }
-
- parentFrameView->addScrollableArea(this);
-}
-
-bool FrameView::shouldSuspendScrollAnimations() const
-{
- return m_frame->loader()->state() != FrameStateComplete;
-}
-
-void FrameView::scrollbarStyleChanged(int newStyle, bool forceUpdate)
-{
- if (!isMainFrame())
- return;
-
- if (forceUpdate)
- ScrollView::scrollbarStyleChanged(newStyle, forceUpdate);
-}
-
-void FrameView::setAnimatorsAreActive()
-{
- Page* page = m_frame->page();
- if (!page)
- return;
-
- if (ScrollAnimator* scrollAnimator = existingScrollAnimator())
- scrollAnimator->setIsActive();
-
- if (!m_scrollableAreas)
- return;
-
- for (HashSet<ScrollableArea*>::const_iterator it = m_scrollableAreas->begin(), end = m_scrollableAreas->end(); it != end; ++it) {
- ScrollableArea* scrollableArea = *it;
-
- ASSERT(scrollableArea->scrollbarsCanBeActive());
- scrollableArea->scrollAnimator()->setIsActive();
- }
-}
-
-void FrameView::notifyPageThatContentAreaWillPaint() const
-{
- Page* page = m_frame->page();
- if (!page)
- return;
-
- contentAreaWillPaint();
-
- if (!m_scrollableAreas)
- return;
-
- for (HashSet<ScrollableArea*>::const_iterator it = m_scrollableAreas->begin(), end = m_scrollableAreas->end(); it != end; ++it) {
- ScrollableArea* scrollableArea = *it;
-
- if (!scrollableArea->scrollbarsCanBeActive())
- continue;
-
- scrollableArea->contentAreaWillPaint();
- }
-}
-
-bool FrameView::scrollAnimatorEnabled() const
-{
- if (Page* page = m_frame->page())
- return page->settings().scrollAnimatorEnabled();
- return false;
-}
-
-void FrameView::updateAnnotatedRegions()
-{
- Document* document = m_frame->document();
- if (!document->hasAnnotatedRegions())
- return;
- Vector<AnnotatedRegionValue> newRegions;
- document->renderBox()->collectAnnotatedRegions(newRegions);
- if (newRegions == document->annotatedRegions())
- return;
- document->setAnnotatedRegions(newRegions);
- if (Page* page = m_frame->page())
- page->chrome().client().annotatedRegionsChanged();
-}
-
-void FrameView::updateScrollCorner()
-{
- RefPtr<RenderStyle> cornerStyle;
- IntRect cornerRect = scrollCornerRect();
- Document* doc = m_frame->document();
-
- if (doc && !cornerRect.isEmpty()) {
- // Try the <body> element first as a scroll corner source.
- if (Element* body = doc->body()) {
- if (RenderObject* renderer = body->renderer())
- cornerStyle = renderer->getUncachedPseudoStyle(PseudoStyleRequest(SCROLLBAR_CORNER), renderer->style());
- }
-
- if (!cornerStyle) {
- // If the <body> didn't have a custom style, then the root element might.
- if (Element* docElement = doc->documentElement()) {
- if (RenderObject* renderer = docElement->renderer())
- cornerStyle = renderer->getUncachedPseudoStyle(PseudoStyleRequest(SCROLLBAR_CORNER), renderer->style());
- }
- }
-
- if (!cornerStyle) {
- // If we have an owning iframe/frame element, then it can set the custom scrollbar also.
- if (RenderPart* renderer = m_frame->ownerRenderer())
- cornerStyle = renderer->getUncachedPseudoStyle(PseudoStyleRequest(SCROLLBAR_CORNER), renderer->style());
- }
- }
-
- if (cornerStyle) {
- if (!m_scrollCorner)
- m_scrollCorner = RenderScrollbarPart::createAnonymous(doc);
- m_scrollCorner->setStyle(cornerStyle.release());
- invalidateScrollCorner(cornerRect);
- } else if (m_scrollCorner) {
- m_scrollCorner->destroy();
- m_scrollCorner = 0;
- }
-
- ScrollView::updateScrollCorner();
-}
-
-void FrameView::paintScrollCorner(GraphicsContext* context, const IntRect& cornerRect)
-{
- if (context->updatingControlTints()) {
- updateScrollCorner();
- return;
- }
-
- if (m_scrollCorner) {
- bool needsBackgorund = isMainFrame();
- if (needsBackgorund)
- context->fillRect(cornerRect, baseBackgroundColor());
- m_scrollCorner->paintIntoRect(context, cornerRect.location(), cornerRect);
- return;
- }
-
- ScrollView::paintScrollCorner(context, cornerRect);
-}
-
-void FrameView::paintScrollbar(GraphicsContext* context, Scrollbar* bar, const IntRect& rect)
-{
- bool needsBackgorund = bar->isCustomScrollbar() && isMainFrame();
- if (needsBackgorund) {
- IntRect toFill = bar->frameRect();
- toFill.intersect(rect);
- context->fillRect(toFill, baseBackgroundColor());
- }
-
- ScrollView::paintScrollbar(context, bar, rect);
-}
-
-Color FrameView::documentBackgroundColor() const
-{
- // <https://bugs.webkit.org/show_bug.cgi?id=59540> We blend the background color of
- // the document and the body against the base background color of the frame view.
- // Background images are unfortunately impractical to include.
-
- // Return invalid Color objects whenever there is insufficient information.
- if (!frame().document())
- return Color();
-
- Element* htmlElement = frame().document()->documentElement();
- Element* bodyElement = frame().document()->body();
-
- // Start with invalid colors.
- Color htmlBackgroundColor;
- Color bodyBackgroundColor;
- if (htmlElement && htmlElement->renderer())
- htmlBackgroundColor = htmlElement->renderer()->style()->visitedDependentColor(CSSPropertyBackgroundColor);
- if (bodyElement && bodyElement->renderer())
- bodyBackgroundColor = bodyElement->renderer()->style()->visitedDependentColor(CSSPropertyBackgroundColor);
-
- if (!bodyBackgroundColor.isValid()) {
- if (!htmlBackgroundColor.isValid())
- return Color();
- return baseBackgroundColor().blend(htmlBackgroundColor);
- }
-
- if (!htmlBackgroundColor.isValid())
- return baseBackgroundColor().blend(bodyBackgroundColor);
-
- // We take the aggregate of the base background color
- // the <html> background color, and the <body>
- // background color to find the document color. The
- // addition of the base background color is not
- // technically part of the document background, but it
- // otherwise poses problems when the aggregate is not
- // fully opaque.
- return baseBackgroundColor().blend(htmlBackgroundColor).blend(bodyBackgroundColor);
-}
-
-bool FrameView::hasCustomScrollbars() const
-{
- const HashSet<RefPtr<Widget> >* viewChildren = children();
- HashSet<RefPtr<Widget> >::const_iterator end = viewChildren->end();
- for (HashSet<RefPtr<Widget> >::const_iterator current = viewChildren->begin(); current != end; ++current) {
- Widget* widget = current->get();
- if (widget->isFrameView()) {
- if (toFrameView(widget)->hasCustomScrollbars())
- return true;
- } else if (widget->isScrollbar()) {
- Scrollbar* scrollbar = static_cast<Scrollbar*>(widget);
- if (scrollbar->isCustomScrollbar())
- return true;
- }
- }
-
- return false;
-}
-
-FrameView* FrameView::parentFrameView() const
-{
- if (!parent())
- return 0;
-
- if (Frame* parentFrame = m_frame->tree()->parent())
- return parentFrame->view();
-
- return 0;
-}
-
-void FrameView::updateControlTints()
-{
- // This is called when control tints are changed from aqua/graphite to clear and vice versa.
- // We do a "fake" paint, and when the theme gets a paint call, it can then do an invalidate.
- // This is only done if the theme supports control tinting. It's up to the theme and platform
- // to define when controls get the tint and to call this function when that changes.
-
- // Optimize the common case where we bring a window to the front while it's still empty.
- if (m_frame->document()->url().isEmpty())
- return;
-
- if (RenderTheme::theme().supportsControlTints() || hasCustomScrollbars())
- paintControlTints();
-}
-
-void FrameView::paintControlTints()
-{
- if (needsLayout())
- layout();
- // FIXME: The use of paint seems like overkill: crbug.com/236892
- GraphicsContext context(0); // NULL canvas to get a non-painting context.
- context.setUpdatingControlTints(true);
- paint(&context, frameRect());
-}
-
-bool FrameView::wasScrolledByUser() const
-{
- return m_wasScrolledByUser;
-}
-
-void FrameView::setWasScrolledByUser(bool wasScrolledByUser)
-{
- if (m_inProgrammaticScroll)
- return;
- m_maintainScrollPositionAnchor = 0;
- m_wasScrolledByUser = wasScrolledByUser;
-}
-
-void FrameView::paintContents(GraphicsContext* p, const IntRect& rect)
-{
- Document* document = m_frame->document();
-
-#ifndef NDEBUG
- bool fillWithRed;
- if (document->printing())
- fillWithRed = false; // Printing, don't fill with red (can't remember why).
- else if (m_frame->ownerElement())
- fillWithRed = false; // Subframe, don't fill with red.
- else if (isTransparent())
- fillWithRed = false; // Transparent, don't fill with red.
- else if (m_paintBehavior & PaintBehaviorSelectionOnly)
- fillWithRed = false; // Selections are transparent, don't fill with red.
- else if (m_nodeToDraw)
- fillWithRed = false; // Element images are transparent, don't fill with red.
- else
- fillWithRed = true;
-
- if (fillWithRed)
- p->fillRect(rect, Color(0xFF, 0, 0));
-#endif
-
- RenderView* renderView = this->renderView();
- if (!renderView) {
- LOG_ERROR("called FrameView::paint with nil renderer");
- return;
- }
-
- ASSERT(!needsLayout());
- if (needsLayout())
- return;
-
- InspectorInstrumentation::willPaint(renderView);
-
- bool isTopLevelPainter = !s_inPaintContents;
- s_inPaintContents = true;
-
- FontCachePurgePreventer fontCachePurgePreventer;
-
- PaintBehavior oldPaintBehavior = m_paintBehavior;
-
- if (FrameView* parentView = parentFrameView()) {
- if (parentView->paintBehavior() & PaintBehaviorFlattenCompositingLayers)
- m_paintBehavior |= PaintBehaviorFlattenCompositingLayers;
- }
-
- if (m_paintBehavior == PaintBehaviorNormal)
- document->markers()->invalidateRenderedRectsForMarkersInRect(rect);
-
- if (document->printing())
- m_paintBehavior |= PaintBehaviorFlattenCompositingLayers;
-
- ASSERT(!m_isPainting);
- m_isPainting = true;
-
- // m_nodeToDraw is used to draw only one element (and its descendants)
- RenderObject* eltRenderer = m_nodeToDraw ? m_nodeToDraw->renderer() : 0;
- RenderLayer* rootLayer = renderView->layer();
-
-#ifndef NDEBUG
- renderView->assertSubtreeIsLaidOut();
- RenderObject::SetLayoutNeededForbiddenScope forbidSetNeedsLayout(rootLayer->renderer());
-#endif
-
- RenderObject* enclosingLayerRenderer = eltRenderer->enclosingLayer() ? eltRenderer->enclosingLayer()->renderer() : eltRenderer;
- rootLayer->paint(p, rect, m_paintBehavior, enclosingLayerRenderer);
-
- if (rootLayer->containsDirtyOverlayScrollbars())
- rootLayer->paintOverlayScrollbars(p, rect, m_paintBehavior, eltRenderer);
-
- m_isPainting = false;
-
- m_paintBehavior = oldPaintBehavior;
- m_lastPaintTime = currentTime();
-
- // Regions may have changed as a result of the visibility/z-index of element changing.
- if (document->annotatedRegionsDirty())
- updateAnnotatedRegions();
-
- if (isTopLevelPainter) {
- // Everythin that happens after paintContents completions is considered
- // to be part of the next frame.
- s_currentFrameTimeStamp = currentTime();
- s_inPaintContents = false;
- }
-
- InspectorInstrumentation::didPaint(renderView, p, rect);
-}
-
-void FrameView::setPaintBehavior(PaintBehavior behavior)
-{
- m_paintBehavior = behavior;
-}
-
-PaintBehavior FrameView::paintBehavior() const
-{
- return m_paintBehavior;
-}
-
-bool FrameView::isPainting() const
-{
- return m_isPainting;
-}
-
-void FrameView::setNodeToDraw(Node* node)
-{
- m_nodeToDraw = node;
-}
-
-void FrameView::paintOverhangAreas(GraphicsContext* context, const IntRect& horizontalOverhangArea, const IntRect& verticalOverhangArea, const IntRect& dirtyRect)
-{
- if (context->paintingDisabled())
- return;
-
- if (m_frame->document()->printing())
- return;
-
- if (isMainFrame()) {
- if (m_frame->page()->chrome().client().paintCustomOverhangArea(context, horizontalOverhangArea, verticalOverhangArea, dirtyRect))
- return;
- }
-
- ScrollView::paintOverhangAreas(context, horizontalOverhangArea, verticalOverhangArea, dirtyRect);
-}
-
-void FrameView::updateLayoutAndStyleIfNeededRecursive()
-{
- // We have to crawl our entire tree looking for any FrameViews that need
- // layout and make sure they are up to date.
- // Mac actually tests for intersection with the dirty region and tries not to
- // update layout for frames that are outside the dirty region. Not only does this seem
- // pointless (since those frames will have set a zero timer to layout anyway), but
- // it is also incorrect, since if two frames overlap, the first could be excluded from the dirty
- // region but then become included later by the second frame adding rects to the dirty region
- // when it lays out.
-
- m_frame->document()->updateStyleIfNeeded();
-
- if (needsLayout())
- layout();
-
- // Grab a copy of the children() set, as it may be mutated by the following updateLayoutAndStyleIfNeededRecursive
- // calls, as they can potentially re-enter a layout of the parent frame view, which may add/remove scrollbars
- // and thus mutates the children() set.
- Vector<RefPtr<FrameView> > frameViews;
- collectFrameViewChildren(this, frameViews);
-
- const Vector<RefPtr<FrameView> >::iterator end = frameViews.end();
- for (Vector<RefPtr<FrameView> >::iterator it = frameViews.begin(); it != end; ++it)
- (*it)->updateLayoutAndStyleIfNeededRecursive();
-
- // updateLayoutAndStyleIfNeededRecursive is called when we need to make sure style and layout are up-to-date before
- // painting, so we need to flush out any deferred repaints too.
- flushDeferredRepaints();
-
- // When seamless is on, child frame can mark parent frame dirty. In such case, child frame
- // needs to call layout on parent frame recursively.
- // This assert ensures that parent frames are clean, when child frames finished updating layout and style.
- ASSERT(!needsLayout());
-}
-
-void FrameView::enableAutoSizeMode(bool enable, const IntSize& minSize, const IntSize& maxSize)
-{
- ASSERT(!enable || !minSize.isEmpty());
- ASSERT(minSize.width() <= maxSize.width());
- ASSERT(minSize.height() <= maxSize.height());
-
- if (m_shouldAutoSize == enable && m_minAutoSize == minSize && m_maxAutoSize == maxSize)
- return;
-
- m_shouldAutoSize = enable;
- m_minAutoSize = minSize;
- m_maxAutoSize = maxSize;
- m_didRunAutosize = false;
-
- setNeedsLayout();
- scheduleRelayout();
- if (m_shouldAutoSize)
- return;
-
- // Since autosize mode forces the scrollbar mode, change them to being auto.
- setVerticalScrollbarLock(false);
- setHorizontalScrollbarLock(false);
- setScrollbarModes(ScrollbarAuto, ScrollbarAuto);
-}
-
-void FrameView::forceLayout(bool allowSubtree)
-{
- layout(allowSubtree);
-}
-
-void FrameView::forceLayoutForPagination(const FloatSize& pageSize, const FloatSize& originalPageSize, float maximumShrinkFactor, AdjustViewSizeOrNot shouldAdjustViewSize)
-{
- // Dumping externalRepresentation(m_frame->renderer()).ascii() is a good trick to see
- // the state of things before and after the layout
- if (RenderView* renderView = this->renderView()) {
- float pageLogicalWidth = renderView->style()->isHorizontalWritingMode() ? pageSize.width() : pageSize.height();
- float pageLogicalHeight = renderView->style()->isHorizontalWritingMode() ? pageSize.height() : pageSize.width();
-
- LayoutUnit flooredPageLogicalWidth = static_cast<LayoutUnit>(pageLogicalWidth);
- LayoutUnit flooredPageLogicalHeight = static_cast<LayoutUnit>(pageLogicalHeight);
- renderView->setLogicalWidth(flooredPageLogicalWidth);
- renderView->setPageLogicalHeight(flooredPageLogicalHeight);
- renderView->setNeedsLayoutAndPrefWidthsRecalc();
- forceLayout();
-
- // If we don't fit in the given page width, we'll lay out again. If we don't fit in the
- // page width when shrunk, we will lay out at maximum shrink and clip extra content.
- // FIXME: We are assuming a shrink-to-fit printing implementation. A cropping
- // implementation should not do this!
- bool horizontalWritingMode = renderView->style()->isHorizontalWritingMode();
- const LayoutRect& documentRect = renderView->documentRect();
- LayoutUnit docLogicalWidth = horizontalWritingMode ? documentRect.width() : documentRect.height();
- if (docLogicalWidth > pageLogicalWidth) {
- int expectedPageWidth = std::min<float>(documentRect.width(), pageSize.width() * maximumShrinkFactor);
- int expectedPageHeight = std::min<float>(documentRect.height(), pageSize.height() * maximumShrinkFactor);
- FloatSize maxPageSize = m_frame->resizePageRectsKeepingRatio(FloatSize(originalPageSize.width(), originalPageSize.height()), FloatSize(expectedPageWidth, expectedPageHeight));
- pageLogicalWidth = horizontalWritingMode ? maxPageSize.width() : maxPageSize.height();
- pageLogicalHeight = horizontalWritingMode ? maxPageSize.height() : maxPageSize.width();
-
- flooredPageLogicalWidth = static_cast<LayoutUnit>(pageLogicalWidth);
- flooredPageLogicalHeight = static_cast<LayoutUnit>(pageLogicalHeight);
- renderView->setLogicalWidth(flooredPageLogicalWidth);
- renderView->setPageLogicalHeight(flooredPageLogicalHeight);
- renderView->setNeedsLayoutAndPrefWidthsRecalc();
- forceLayout();
-
- const LayoutRect& updatedDocumentRect = renderView->documentRect();
- LayoutUnit docLogicalHeight = horizontalWritingMode ? updatedDocumentRect.height() : updatedDocumentRect.width();
- LayoutUnit docLogicalTop = horizontalWritingMode ? updatedDocumentRect.y() : updatedDocumentRect.x();
- LayoutUnit docLogicalRight = horizontalWritingMode ? updatedDocumentRect.maxX() : updatedDocumentRect.maxY();
- LayoutUnit clippedLogicalLeft = 0;
- if (!renderView->style()->isLeftToRightDirection())
- clippedLogicalLeft = docLogicalRight - pageLogicalWidth;
- LayoutRect overflow(clippedLogicalLeft, docLogicalTop, pageLogicalWidth, docLogicalHeight);
-
- if (!horizontalWritingMode)
- overflow = overflow.transposedRect();
- renderView->clearLayoutOverflow();
- renderView->addLayoutOverflow(overflow); // This is how we clip in case we overflow again.
- }
- }
-
- if (shouldAdjustViewSize)
- adjustViewSize();
-}
-
-IntRect FrameView::convertFromRenderer(const RenderObject* renderer, const IntRect& rendererRect) const
-{
- IntRect rect = pixelSnappedIntRect(enclosingLayoutRect(renderer->localToAbsoluteQuad(FloatRect(rendererRect)).boundingBox()));
-
- // Convert from page ("absolute") to FrameView coordinates.
- rect.moveBy(-scrollPosition());
-
- return rect;
-}
-
-IntRect FrameView::convertToRenderer(const RenderObject* renderer, const IntRect& viewRect) const
-{
- IntRect rect = viewRect;
-
- // Convert from FrameView coords into page ("absolute") coordinates.
- rect.moveBy(scrollPosition());
-
- // FIXME: we don't have a way to map an absolute rect down to a local quad, so just
- // move the rect for now.
- rect.setLocation(roundedIntPoint(renderer->absoluteToLocal(rect.location(), UseTransforms)));
- return rect;
-}
-
-IntPoint FrameView::convertFromRenderer(const RenderObject* renderer, const IntPoint& rendererPoint) const
-{
- IntPoint point = roundedIntPoint(renderer->localToAbsolute(rendererPoint, UseTransforms));
-
- // Convert from page ("absolute") to FrameView coordinates.
- point.moveBy(-scrollPosition());
- return point;
-}
-
-IntPoint FrameView::convertToRenderer(const RenderObject* renderer, const IntPoint& viewPoint) const
-{
- IntPoint point = viewPoint;
-
- // Convert from FrameView coords into page ("absolute") coordinates.
- point += IntSize(scrollX(), scrollY());
-
- return roundedIntPoint(renderer->absoluteToLocal(point, UseTransforms));
-}
-
-IntRect FrameView::convertToContainingView(const IntRect& localRect) const
-{
- if (const ScrollView* parentScrollView = parent()) {
- if (parentScrollView->isFrameView()) {
- const FrameView* parentView = toFrameView(parentScrollView);
- // Get our renderer in the parent view
- RenderPart* renderer = m_frame->ownerRenderer();
- if (!renderer)
- return localRect;
-
- IntRect rect(localRect);
- // Add borders and padding??
- rect.move(renderer->borderLeft() + renderer->paddingLeft(),
- renderer->borderTop() + renderer->paddingTop());
- return parentView->convertFromRenderer(renderer, rect);
- }
-
- return Widget::convertToContainingView(localRect);
- }
-
- return localRect;
-}
-
-IntRect FrameView::convertFromContainingView(const IntRect& parentRect) const
-{
- if (const ScrollView* parentScrollView = parent()) {
- if (parentScrollView->isFrameView()) {
- const FrameView* parentView = toFrameView(parentScrollView);
-
- // Get our renderer in the parent view
- RenderPart* renderer = m_frame->ownerRenderer();
- if (!renderer)
- return parentRect;
-
- IntRect rect = parentView->convertToRenderer(renderer, parentRect);
- // Subtract borders and padding
- rect.move(-renderer->borderLeft() - renderer->paddingLeft(),
- -renderer->borderTop() - renderer->paddingTop());
- return rect;
- }
-
- return Widget::convertFromContainingView(parentRect);
- }
-
- return parentRect;
-}
-
-IntPoint FrameView::convertToContainingView(const IntPoint& localPoint) const
-{
- if (const ScrollView* parentScrollView = parent()) {
- if (parentScrollView->isFrameView()) {
- const FrameView* parentView = toFrameView(parentScrollView);
-
- // Get our renderer in the parent view
- RenderPart* renderer = m_frame->ownerRenderer();
- if (!renderer)
- return localPoint;
-
- IntPoint point(localPoint);
-
- // Add borders and padding
- point.move(renderer->borderLeft() + renderer->paddingLeft(),
- renderer->borderTop() + renderer->paddingTop());
- return parentView->convertFromRenderer(renderer, point);
- }
-
- return Widget::convertToContainingView(localPoint);
- }
-
- return localPoint;
-}
-
-IntPoint FrameView::convertFromContainingView(const IntPoint& parentPoint) const
-{
- if (const ScrollView* parentScrollView = parent()) {
- if (parentScrollView->isFrameView()) {
- const FrameView* parentView = toFrameView(parentScrollView);
-
- // Get our renderer in the parent view
- RenderPart* renderer = m_frame->ownerRenderer();
- if (!renderer)
- return parentPoint;
-
- IntPoint point = parentView->convertToRenderer(renderer, parentPoint);
- // Subtract borders and padding
- point.move(-renderer->borderLeft() - renderer->paddingLeft(),
- -renderer->borderTop() - renderer->paddingTop());
- return point;
- }
-
- return Widget::convertFromContainingView(parentPoint);
- }
-
- return parentPoint;
-}
-
-// Normal delay
-void FrameView::setRepaintThrottlingDeferredRepaintDelay(double p)
-{
- s_normalDeferredRepaintDelay = p;
-}
-
-// Negative value would mean that first few repaints happen without a delay
-void FrameView::setRepaintThrottlingnInitialDeferredRepaintDelayDuringLoading(double p)
-{
- s_initialDeferredRepaintDelayDuringLoading = p;
-}
-
-// The delay grows on each repaint to this maximum value
-void FrameView::setRepaintThrottlingMaxDeferredRepaintDelayDuringLoading(double p)
-{
- s_maxDeferredRepaintDelayDuringLoading = p;
-}
-
-// On each repaint the delay increases by this amount
-void FrameView::setRepaintThrottlingDeferredRepaintDelayIncrementDuringLoading(double p)
-{
- s_deferredRepaintDelayIncrementDuringLoading = p;
-}
-
-void FrameView::setTracksRepaints(bool trackRepaints)
-{
- if (trackRepaints == m_isTrackingRepaints)
- return;
-
- for (Frame* frame = m_frame->tree()->top(); frame; frame = frame->tree()->traverseNext()) {
- if (RenderView* renderView = frame->contentRenderer())
- renderView->compositor()->setTracksRepaints(trackRepaints);
- }
-
- resetTrackedRepaints();
- m_isTrackingRepaints = trackRepaints;
-}
-
-void FrameView::resetTrackedRepaints()
-{
- m_trackedRepaintRects.clear();
- if (RenderView* renderView = this->renderView())
- renderView->compositor()->resetTrackedRepaintRects();
-}
-
-String FrameView::trackedRepaintRectsAsText() const
-{
- TextStream ts;
- if (!m_trackedRepaintRects.isEmpty()) {
- ts << "(repaint rects\n";
- for (size_t i = 0; i < m_trackedRepaintRects.size(); ++i)
- ts << " (rect " << m_trackedRepaintRects[i].x() << " " << m_trackedRepaintRects[i].y() << " " << m_trackedRepaintRects[i].width() << " " << m_trackedRepaintRects[i].height() << ")\n";
- ts << ")\n";
- }
- return ts.release();
-}
-
-void FrameView::addResizerArea(RenderLayer* resizerLayer)
-{
- if (!m_resizerAreas)
- m_resizerAreas = adoptPtr(new ResizerAreaSet);
- m_resizerAreas->add(resizerLayer);
-}
-
-void FrameView::removeResizerArea(RenderLayer* resizerLayer)
-{
- if (!m_resizerAreas)
- return;
-
- ResizerAreaSet::iterator it = m_resizerAreas->find(resizerLayer);
- if (it != m_resizerAreas->end())
- m_resizerAreas->remove(it);
-}
-
-bool FrameView::addScrollableArea(ScrollableArea* scrollableArea)
-{
- if (!m_scrollableAreas)
- m_scrollableAreas = adoptPtr(new ScrollableAreaSet);
- return m_scrollableAreas->add(scrollableArea).isNewEntry;
-}
-
-bool FrameView::removeScrollableArea(ScrollableArea* scrollableArea)
-{
- if (!m_scrollableAreas)
- return false;
-
- ScrollableAreaSet::iterator it = m_scrollableAreas->find(scrollableArea);
- if (it == m_scrollableAreas->end())
- return false;
-
- m_scrollableAreas->remove(it);
- return true;
-}
-
-bool FrameView::containsScrollableArea(const ScrollableArea* scrollableArea) const
-{
- if (!m_scrollableAreas)
- return false;
- return m_scrollableAreas->contains(const_cast<ScrollableArea*>(scrollableArea));
-}
-
-void FrameView::removeChild(Widget* widget)
-{
- if (widget->isFrameView())
- removeScrollableArea(toFrameView(widget));
-
- ScrollView::removeChild(widget);
-}
-
-bool FrameView::wheelEvent(const PlatformWheelEvent& wheelEvent)
-{
- // Note that to allow for rubber-band over-scroll behavior, even non-scrollable views
- // should handle wheel events.
-#if !USE(RUBBER_BANDING)
- if (!isScrollable())
- return false;
-#endif
-
- // We don't allow mouse wheeling to happen in a ScrollView that has had its scrollbars explicitly disabled.
- if (!canHaveScrollbars())
- return false;
-
- return ScrollableArea::handleWheelEvent(wheelEvent);
-}
-
-bool FrameView::isVerticalDocument() const
-{
- RenderView* renderView = this->renderView();
- if (!renderView)
- return true;
-
- return renderView->style()->isHorizontalWritingMode();
-}
-
-bool FrameView::isFlippedDocument() const
-{
- RenderView* renderView = this->renderView();
- if (!renderView)
- return false;
-
- return renderView->style()->isFlippedBlocksWritingMode();
-}
-
-AXObjectCache* FrameView::axObjectCache() const
-{
- if (frame().document())
- return frame().document()->existingAXObjectCache();
- return 0;
-}
-
-bool FrameView::isMainFrame() const
-{
- return m_frame->page() && m_frame->page()->mainFrame() == m_frame;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/page/FrameView.h b/chromium/third_party/WebKit/Source/core/page/FrameView.h
deleted file mode 100644
index 81c9895520b..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/FrameView.h
+++ /dev/null
@@ -1,583 +0,0 @@
-/*
- Copyright (C) 1997 Martin Jones (mjones@kde.org)
- (C) 1998 Waldo Bastian (bastian@kde.org)
- (C) 1998, 1999 Torben Weis (weis@kde.org)
- (C) 1999 Lars Knoll (knoll@kde.org)
- (C) 1999 Antti Koivisto (koivisto@kde.org)
- Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#ifndef FrameView_h
-#define FrameView_h
-
-#include "core/page/AdjustViewSizeOrNot.h"
-#include "core/platform/ScrollView.h"
-#include "core/platform/graphics/Color.h"
-#include "core/platform/graphics/LayoutRect.h"
-#include "core/rendering/Pagination.h"
-#include "core/rendering/PaintPhase.h"
-#include "core/rendering/PartialLayoutState.h"
-#include "wtf/Forward.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class Element;
-class Event;
-class FloatSize;
-class Frame;
-class FrameActionScheduler;
-class KURL;
-class Node;
-class Page;
-class RenderBox;
-class RenderEmbeddedObject;
-class RenderLayer;
-class RenderObject;
-class RenderScrollbarPart;
-class RenderStyle;
-
-Pagination::Mode paginationModeForRenderStyle(RenderStyle*);
-
-typedef unsigned long long DOMTimeStamp;
-
-class FrameView : public ScrollView {
-public:
- friend class RenderView;
- friend class Internals;
-
- static PassRefPtr<FrameView> create(Frame*);
- static PassRefPtr<FrameView> create(Frame*, const IntSize& initialSize);
-
- virtual ~FrameView();
-
- virtual HostWindow* hostWindow() const;
-
- virtual void invalidateRect(const IntRect&);
- virtual void setFrameRect(const IntRect&);
-
- virtual bool scheduleAnimation();
-
- Frame& frame() const { return *m_frame; }
-
- RenderView* renderView() const;
-
- int mapFromLayoutToCSSUnits(LayoutUnit) const;
- LayoutUnit mapFromCSSToLayoutUnits(int) const;
-
- LayoutUnit marginWidth() const { return m_margins.width(); } // -1 means default
- LayoutUnit marginHeight() const { return m_margins.height(); } // -1 means default
- void setMarginWidth(LayoutUnit);
- void setMarginHeight(LayoutUnit);
-
- virtual void setCanHaveScrollbars(bool);
- void updateCanHaveScrollbars();
-
- virtual PassRefPtr<Scrollbar> createScrollbar(ScrollbarOrientation);
-
- virtual void setContentsSize(const IntSize&);
-
- void layout(bool allowSubtree = true);
- bool didFirstLayout() const;
- void layoutTimerFired(Timer<FrameView>*);
- void scheduleRelayout();
- void scheduleRelayoutOfSubtree(RenderObject*);
- void unscheduleRelayout();
- bool layoutPending() const;
- bool isInLayout() const { return m_inLayout; }
-
- RenderObject* layoutRoot(bool onlyDuringLayout = false) const;
- void clearLayoutRoot() { m_layoutRoot = 0; }
- int layoutCount() const { return m_layoutCount; }
-
- bool needsLayout() const;
- void setNeedsLayout();
- void setViewportConstrainedObjectsNeedLayout();
-
- bool needsFullRepaint() const { return m_doFullRepaint; }
-
- void serviceScriptedAnimations(double monotonicAnimationStartTime);
-
- void updateCompositingLayersAfterStyleChange();
- void updateCompositingLayersAfterLayout();
-
- bool hasCompositedContent() const;
- bool isEnclosedInCompositingLayer() const;
-
- // Returns true when a paint with the PaintBehaviorFlattenCompositingLayers flag set gives
- // a faithful representation of the content.
- bool isSoftwareRenderable() const;
-
- void resetScrollbars();
- void prepareForDetach();
- void detachCustomScrollbars();
- virtual void recalculateScrollbarOverlayStyle();
-
- void clear();
-
- bool isTransparent() const;
- void setTransparent(bool isTransparent);
-
- // True if the FrameView is not transparent, and the base background color is opaque.
- bool hasOpaqueBackground() const;
-
- Color baseBackgroundColor() const;
- void setBaseBackgroundColor(const Color&);
- void updateBackgroundRecursively(const Color&, bool);
-
- bool shouldUpdateWhileOffscreen() const;
- void setShouldUpdateWhileOffscreen(bool);
- bool shouldUpdate() const;
-
- void adjustViewSize();
-
- virtual IntRect windowClipRect(bool clipToContents = true) const;
- IntRect windowClipRectForFrameOwner(const HTMLFrameOwnerElement*, bool clipToLayerContents) const;
-
- virtual IntRect windowResizerRect() const;
-
- virtual float visibleContentScaleFactor() const OVERRIDE { return m_visibleContentScaleFactor; }
- void setVisibleContentScaleFactor(float);
-
- virtual void setScrollPosition(const IntPoint&) OVERRIDE;
- virtual void repaintFixedElementsAfterScrolling();
- virtual void updateFixedElementsAfterScrolling();
- virtual bool shouldRubberBandInDirection(ScrollDirection) const;
- virtual bool requestScrollPositionUpdate(const IntPoint&) OVERRIDE;
- virtual bool isRubberBandInProgress() const OVERRIDE;
- void setScrollPositionNonProgrammatically(const IntPoint&);
-
- // This is different than visibleContentRect() in that it ignores negative (or overly positive)
- // offsets from rubber-banding, and it takes zooming into account.
- LayoutRect viewportConstrainedVisibleContentRect() const;
-
- AtomicString mediaType() const;
- void setMediaType(const AtomicString&);
- void adjustMediaTypeForPrinting(bool printing);
-
- void setCannotBlitToWindow();
- void setIsOverlapped(bool);
- bool isOverlapped() const { return m_isOverlapped; }
- bool isOverlappedIncludingAncestors() const;
- void setContentIsOpaque(bool);
-
- void addSlowRepaintObject();
- void removeSlowRepaintObject();
- bool hasSlowRepaintObjects() const { return m_slowRepaintObjectCount; }
-
- // Includes fixed- and sticky-position objects.
- typedef HashSet<RenderObject*> ViewportConstrainedObjectSet;
- void addViewportConstrainedObject(RenderObject*);
- void removeViewportConstrainedObject(RenderObject*);
- const ViewportConstrainedObjectSet* viewportConstrainedObjects() const { return m_viewportConstrainedObjects.get(); }
- bool hasViewportConstrainedObjects() const { return m_viewportConstrainedObjects && m_viewportConstrainedObjects->size() > 0; }
-
- void beginDeferredRepaints();
- void endDeferredRepaints();
- void handleLoadCompleted();
- void flushDeferredRepaints();
- void startDeferredRepaintTimer(double delay);
- void resetDeferredRepaintDelay();
-
- void beginDisableRepaints();
- void endDisableRepaints();
- bool repaintsDisabled() { return m_disableRepaints > 0; }
-
- void updateAnnotatedRegions();
- void updateControlTints();
-
- void restoreScrollbar();
-
- void scheduleEvent(PassRefPtr<Event>, PassRefPtr<Node>);
- void pauseScheduledEvents();
- void resumeScheduledEvents();
- void postLayoutTimerFired(Timer<FrameView>*);
-
- bool wasScrolledByUser() const;
- void setWasScrolledByUser(bool);
-
- bool safeToPropagateScrollToParent() const { return m_safeToPropagateScrollToParent; }
- void setSafeToPropagateScrollToParent(bool isSafe) { m_safeToPropagateScrollToParent = isSafe; }
-
- void addWidgetToUpdate(RenderObject*);
- void removeWidgetToUpdate(RenderObject*);
-
- virtual void paintContents(GraphicsContext*, const IntRect& damageRect);
- void setPaintBehavior(PaintBehavior);
- PaintBehavior paintBehavior() const;
- bool isPainting() const;
- bool hasEverPainted() const { return m_lastPaintTime; }
- void setLastPaintTime(double lastPaintTime) { m_lastPaintTime = lastPaintTime; }
- void setNodeToDraw(Node*);
-
- virtual void paintOverhangAreas(GraphicsContext*, const IntRect& horizontalOverhangArea, const IntRect& verticalOverhangArea, const IntRect& dirtyRect);
- virtual void paintScrollCorner(GraphicsContext*, const IntRect& cornerRect);
- virtual void paintScrollbar(GraphicsContext*, Scrollbar*, const IntRect&) OVERRIDE;
-
- Color documentBackgroundColor() const;
-
- static double currentFrameTimeStamp() { return s_currentFrameTimeStamp; }
-
- void updateLayoutAndStyleIfNeededRecursive();
-
- void incrementVisuallyNonEmptyCharacterCount(unsigned);
- void incrementVisuallyNonEmptyPixelCount(const IntSize&);
- void setIsVisuallyNonEmpty() { m_isVisuallyNonEmpty = true; }
- bool isVisuallyNonEmpty() const { return m_isVisuallyNonEmpty; }
- void enableAutoSizeMode(bool enable, const IntSize& minSize, const IntSize& maxSize);
-
- void forceLayout(bool allowSubtree = false);
- void forceLayoutForPagination(const FloatSize& pageSize, const FloatSize& originalPageSize, float maximumShrinkFactor, AdjustViewSizeOrNot);
-
- bool scrollToFragment(const KURL&);
- bool scrollToAnchor(const String&);
- void maintainScrollPositionAtAnchor(Node*);
- void scrollElementToRect(Element*, const IntRect&);
-
- // Methods to convert points and rects between the coordinate space of the renderer, and this view.
- virtual IntRect convertFromRenderer(const RenderObject*, const IntRect&) const;
- virtual IntRect convertToRenderer(const RenderObject*, const IntRect&) const;
- virtual IntPoint convertFromRenderer(const RenderObject*, const IntPoint&) const;
- virtual IntPoint convertToRenderer(const RenderObject*, const IntPoint&) const;
-
- bool isFrameViewScrollCorner(RenderScrollbarPart* scrollCorner) const { return m_scrollCorner == scrollCorner; }
-
- bool isScrollable();
-
- enum ScrollbarModesCalculationStrategy { RulesFromWebContentOnly, AnyRule };
- void calculateScrollbarModesForLayout(ScrollbarMode& hMode, ScrollbarMode& vMode, ScrollbarModesCalculationStrategy = AnyRule);
-
- // Normal delay
- static void setRepaintThrottlingDeferredRepaintDelay(double p);
- // Negative value would mean that first few repaints happen without a delay
- static void setRepaintThrottlingnInitialDeferredRepaintDelayDuringLoading(double p);
- // The delay grows on each repaint to this maximum value
- static void setRepaintThrottlingMaxDeferredRepaintDelayDuringLoading(double p);
- // On each repaint the delay increses by this amount
- static void setRepaintThrottlingDeferredRepaintDelayIncrementDuringLoading(double p);
-
- virtual IntPoint lastKnownMousePosition() const;
-
- virtual bool scrollbarsCanBeActive() const OVERRIDE;
-
- // FIXME: Remove this method once plugin loading is decoupled from layout.
- void flushAnyPendingPostLayoutTasks();
-
- virtual bool shouldSuspendScrollAnimations() const;
- virtual void scrollbarStyleChanged(int newStyle, bool forceUpdate);
-
- void setAnimatorsAreActive();
-
- RenderBox* embeddedContentBox() const;
-
- void setTracksRepaints(bool);
- bool isTrackingRepaints() const { return m_isTrackingRepaints; }
- void resetTrackedRepaints();
- const Vector<IntRect>& trackedRepaintRects() const { return m_trackedRepaintRects; }
- String trackedRepaintRectsAsText() const;
-
- typedef HashSet<ScrollableArea*> ScrollableAreaSet;
- // Returns whether the scrollable area has just been newly added.
- bool addScrollableArea(ScrollableArea*);
- // Returns whether the scrollable area has just been removed.
- bool removeScrollableArea(ScrollableArea*);
- bool containsScrollableArea(const ScrollableArea*) const;
- const ScrollableAreaSet* scrollableAreas() const { return m_scrollableAreas.get(); }
-
- // With CSS style "resize:" enabled, a little resizer handle will appear at the bottom
- // right of the object. We keep track of these resizer areas for checking if touches
- // (implemented using Scroll gesture) are targeting the resizer.
- typedef HashSet<RenderLayer*> ResizerAreaSet;
- void addResizerArea(RenderLayer*);
- void removeResizerArea(RenderLayer*);
- const ResizerAreaSet* resizerAreas() const { return m_resizerAreas.get(); }
-
- virtual void removeChild(Widget*) OVERRIDE;
-
- // This function exists for ports that need to handle wheel events manually.
- // On Mac WebKit1 the underlying NSScrollView just does the scrolling, but on most other platforms
- // we need this function in order to do the scroll ourselves.
- bool wheelEvent(const PlatformWheelEvent&);
-
- // Page and FrameView both store a Pagination value. Page::pagination() is set only by API,
- // and FrameView::pagination() is set only by CSS. Page::pagination() will affect all
- // FrameViews in the page cache, but FrameView::pagination() only affects the current
- // FrameView. FrameView::pagination() will return m_pagination if it has been set. Otherwise,
- // it will return Page::pagination() since currently there are no callers that need to
- // distinguish between the two.
- const Pagination& pagination() const;
- void setPagination(const Pagination&);
-
- bool inProgrammaticScroll() const { return m_inProgrammaticScroll; }
- void setInProgrammaticScroll(bool programmaticScroll) { m_inProgrammaticScroll = programmaticScroll; }
-
- void setHasSoftwareFilters(bool hasSoftwareFilters) { m_hasSoftwareFilters = hasSoftwareFilters; }
- bool hasSoftwareFilters() const { return m_hasSoftwareFilters; }
-
- virtual bool isActive() const OVERRIDE;
-
- // DEPRECATED: Use viewportConstrainedVisibleContentRect() instead.
- IntSize scrollOffsetForFixedPosition() const;
-
- PartialLayoutState& partialLayout() { return m_partialLayout; }
-
-protected:
- virtual bool scrollContentsFastPath(const IntSize& scrollDelta, const IntRect& rectToScroll, const IntRect& clipRect);
- virtual void scrollContentsSlowPath(const IntRect& updateRect);
-
- virtual bool isVerticalDocument() const;
- virtual bool isFlippedDocument() const;
-
-private:
- explicit FrameView(Frame*);
-
- void reset();
- void init();
-
- virtual bool isFrameView() const OVERRIDE { return true; }
-
- friend class RenderWidget;
- bool useSlowRepaints(bool considerOverlap = true) const;
- bool useSlowRepaintsIfNotOverlapped() const;
- void updateCanBlitOnScrollRecursively();
- bool contentsInCompositedLayer() const;
-
- void applyOverflowToViewport(RenderObject*, ScrollbarMode& hMode, ScrollbarMode& vMode);
- void applyPaginationToViewport();
-
- void updateOverflowStatus(bool horizontalOverflow, bool verticalOverflow);
-
- void paintControlTints();
-
- void updateCounters();
- void autoSizeIfEnabled();
- void forceLayoutParentViewIfNeeded();
- void performPreLayoutTasks();
- void performLayout(RenderObject* rootForThisLayout, bool inSubtreeLayout);
- void scheduleOrPerformPostLayoutTasks();
- void performPostLayoutTasks();
-
- virtual void repaintContentRectangle(const IntRect&);
- virtual void contentsResized() OVERRIDE;
- virtual void visibleContentsResized();
-
- // Override ScrollView methods to do point conversion via renderers, in order to
- // take transforms into account.
- virtual IntRect convertToContainingView(const IntRect&) const OVERRIDE;
- virtual IntRect convertFromContainingView(const IntRect&) const OVERRIDE;
- virtual IntPoint convertToContainingView(const IntPoint&) const OVERRIDE;
- virtual IntPoint convertFromContainingView(const IntPoint&) const OVERRIDE;
-
- // ScrollableArea interface
- virtual void invalidateScrollbarRect(Scrollbar*, const IntRect&) OVERRIDE;
- virtual void getTickmarks(Vector<IntRect>&) const OVERRIDE;
- virtual void scrollTo(const IntSize&) OVERRIDE;
- virtual ScrollableArea* enclosingScrollableArea() const OVERRIDE;
- virtual IntRect scrollableAreaBoundingBox() const OVERRIDE;
- virtual bool scrollAnimatorEnabled() const OVERRIDE;
- virtual bool usesCompositedScrolling() const OVERRIDE;
- virtual GraphicsLayer* layerForScrolling() const OVERRIDE;
- virtual GraphicsLayer* layerForHorizontalScrollbar() const OVERRIDE;
- virtual GraphicsLayer* layerForVerticalScrollbar() const OVERRIDE;
- virtual GraphicsLayer* layerForScrollCorner() const OVERRIDE;
-#if USE(RUBBER_BANDING)
- virtual GraphicsLayer* layerForOverhangAreas() const OVERRIDE;
-#endif
-
- void sendResizeEventIfNeeded();
-
- void updateScrollableAreaSet();
-
- virtual void notifyPageThatContentAreaWillPaint() const;
-
- bool shouldUseLoadTimeDeferredRepaintDelay() const;
- void deferredRepaintTimerFired(Timer<FrameView>*);
- void doDeferredRepaints();
- void updateDeferredRepaintDelayAfterRepaint();
- double adjustedDeferredRepaintDelay() const;
-
- bool updateWidgets();
- void updateWidget(RenderObject*);
- void scrollToAnchor();
- void scrollPositionChanged();
-
- bool hasCustomScrollbars() const;
-
- virtual void updateScrollCorner();
-
- FrameView* parentFrameView() const;
-
- virtual AXObjectCache* axObjectCache() const;
- void removeFromAXObjectCache();
-
- bool isMainFrame() const;
-
- static double s_currentFrameTimeStamp; // used for detecting decoded resource thrash in the cache
- static bool s_inPaintContents;
-
- LayoutSize m_size;
- LayoutSize m_margins;
-
- typedef HashSet<RenderObject*> RenderObjectSet;
- OwnPtr<RenderObjectSet> m_widgetUpdateSet;
- RefPtr<Frame> m_frame;
-
- bool m_doFullRepaint;
-
- bool m_canHaveScrollbars;
- bool m_cannotBlitToWindow;
- bool m_isOverlapped;
- bool m_contentIsOpaque;
- unsigned m_slowRepaintObjectCount;
- int m_borderX;
- int m_borderY;
-
- Timer<FrameView> m_layoutTimer;
- bool m_delayedLayout;
- RenderObject* m_layoutRoot;
-
- bool m_layoutSchedulingEnabled;
- bool m_inLayout;
- bool m_doingPreLayoutStyleUpdate;
- bool m_inSynchronousPostLayout;
- int m_layoutCount;
- unsigned m_nestedLayoutCount;
- Timer<FrameView> m_postLayoutTasksTimer;
- bool m_firstLayoutCallbackPending;
-
- bool m_firstLayout;
- bool m_isTransparent;
- Color m_baseBackgroundColor;
- IntSize m_lastViewportSize;
- float m_lastZoomFactor;
-
- AtomicString m_mediaType;
- AtomicString m_mediaTypeWhenNotPrinting;
-
- OwnPtr<FrameActionScheduler> m_actionScheduler;
-
- bool m_overflowStatusDirty;
- bool m_horizontalOverflow;
- bool m_verticalOverflow;
- RenderObject* m_viewportRenderer;
-
- Pagination m_pagination;
-
- bool m_wasScrolledByUser;
- bool m_inProgrammaticScroll;
- bool m_safeToPropagateScrollToParent;
-
- unsigned m_deferringRepaints;
- unsigned m_repaintCount;
- Vector<LayoutRect> m_repaintRects;
- Timer<FrameView> m_deferredRepaintTimer;
- double m_deferredRepaintDelay;
- double m_lastPaintTime;
-
- unsigned m_disableRepaints;
-
- bool m_isTrackingRepaints; // Used for testing.
- Vector<IntRect> m_trackedRepaintRects;
-
- bool m_shouldUpdateWhileOffscreen;
-
- unsigned m_deferSetNeedsLayouts;
- bool m_setNeedsLayoutWasDeferred;
-
- RefPtr<Node> m_nodeToDraw;
- PaintBehavior m_paintBehavior;
- bool m_isPainting;
-
- unsigned m_visuallyNonEmptyCharacterCount;
- unsigned m_visuallyNonEmptyPixelCount;
- bool m_isVisuallyNonEmpty;
- bool m_firstVisuallyNonEmptyLayoutCallbackPending;
-
- RefPtr<Node> m_maintainScrollPositionAnchor;
-
- // Renderer to hold our custom scroll corner.
- RenderScrollbarPart* m_scrollCorner;
-
- // If true, automatically resize the frame view around its content.
- bool m_shouldAutoSize;
- bool m_inAutoSize;
- // True if autosize has been run since m_shouldAutoSize was set.
- bool m_didRunAutosize;
- // The lower bound on the size when autosizing.
- IntSize m_minAutoSize;
- // The upper bound on the size when autosizing.
- IntSize m_maxAutoSize;
-
- OwnPtr<ScrollableAreaSet> m_scrollableAreas;
- OwnPtr<ResizerAreaSet> m_resizerAreas;
- OwnPtr<ViewportConstrainedObjectSet> m_viewportConstrainedObjects;
-
- static double s_normalDeferredRepaintDelay;
- static double s_initialDeferredRepaintDelayDuringLoading;
- static double s_maxDeferredRepaintDelayDuringLoading;
- static double s_deferredRepaintDelayIncrementDuringLoading;
-
- bool m_hasSoftwareFilters;
-
- float m_visibleContentScaleFactor;
-
- PartialLayoutState m_partialLayout;
-};
-
-inline void FrameView::incrementVisuallyNonEmptyCharacterCount(unsigned count)
-{
- if (m_isVisuallyNonEmpty)
- return;
- m_visuallyNonEmptyCharacterCount += count;
- // Use a threshold value to prevent very small amounts of visible content from triggering didFirstVisuallyNonEmptyLayout.
- // The first few hundred characters rarely contain the interesting content of the page.
- static const unsigned visualCharacterThreshold = 200;
- if (m_visuallyNonEmptyCharacterCount > visualCharacterThreshold)
- setIsVisuallyNonEmpty();
-}
-
-inline void FrameView::incrementVisuallyNonEmptyPixelCount(const IntSize& size)
-{
- if (m_isVisuallyNonEmpty)
- return;
- m_visuallyNonEmptyPixelCount += size.width() * size.height();
- // Use a threshold value to prevent very small amounts of visible content from triggering didFirstVisuallyNonEmptyLayout
- static const unsigned visualPixelThreshold = 32 * 32;
- if (m_visuallyNonEmptyPixelCount > visualPixelThreshold)
- setIsVisuallyNonEmpty();
-}
-
-inline FrameView* toFrameView(Widget* widget)
-{
- ASSERT(!widget || widget->isFrameView());
- return static_cast<FrameView*>(widget);
-}
-
-inline const FrameView* toFrameView(const Widget* widget)
-{
- ASSERT(!widget || widget->isFrameView());
- return static_cast<const FrameView*>(widget);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toFrameView(const FrameView*);
-
-} // namespace WebCore
-
-#endif // FrameView_h
diff --git a/chromium/third_party/WebKit/Source/core/page/History.cpp b/chromium/third_party/WebKit/Source/core/page/History.cpp
deleted file mode 100644
index 3e4f2427674..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/History.cpp
+++ /dev/null
@@ -1,156 +0,0 @@
-/*
- * Copyright (C) 2007 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/page/History.h"
-
-#include "bindings/v8/ExceptionState.h"
-#include "bindings/v8/SerializedScriptValue.h"
-#include "core/dom/Document.h"
-#include "core/dom/ExceptionCode.h"
-#include "core/history/BackForwardController.h"
-#include "core/history/HistoryItem.h"
-#include "core/loader/DocumentLoader.h"
-#include "core/loader/FrameLoader.h"
-#include "core/loader/FrameLoaderClient.h"
-#include "core/page/Frame.h"
-#include "core/page/Page.h"
-#include "weborigin/KURL.h"
-#include "weborigin/SecurityOrigin.h"
-#include "wtf/MainThread.h"
-
-namespace WebCore {
-
-History::History(Frame* frame)
- : DOMWindowProperty(frame)
- , m_lastStateObjectRequested(0)
-{
- ScriptWrappable::init(this);
-}
-
-unsigned History::length() const
-{
- if (!m_frame)
- return 0;
- if (!m_frame->page())
- return 0;
- return m_frame->page()->backForward().count();
-}
-
-SerializedScriptValue* History::state()
-{
- m_lastStateObjectRequested = stateInternal();
- return m_lastStateObjectRequested.get();
-}
-
-SerializedScriptValue* History::stateInternal() const
-{
- if (!m_frame)
- return 0;
-
- if (HistoryItem* historyItem = m_frame->loader()->history()->currentItem())
- return historyItem->stateObject();
-
- return 0;
-}
-
-bool History::stateChanged() const
-{
- return m_lastStateObjectRequested != stateInternal();
-}
-
-bool History::isSameAsCurrentState(SerializedScriptValue* state) const
-{
- return state == stateInternal();
-}
-
-void History::back()
-{
- go(-1);
-}
-
-void History::back(ScriptExecutionContext* context)
-{
- go(context, -1);
-}
-
-void History::forward()
-{
- go(1);
-}
-
-void History::forward(ScriptExecutionContext* context)
-{
- go(context, 1);
-}
-
-void History::go(int distance)
-{
- if (!m_frame)
- return;
-
- m_frame->navigationScheduler()->scheduleHistoryNavigation(distance);
-}
-
-void History::go(ScriptExecutionContext* context, int distance)
-{
- if (!m_frame)
- return;
-
- ASSERT(isMainThread());
- Document* activeDocument = toDocument(context);
- if (!activeDocument)
- return;
-
- if (!activeDocument->canNavigate(m_frame))
- return;
-
- m_frame->navigationScheduler()->scheduleHistoryNavigation(distance);
-}
-
-KURL History::urlForState(const String& urlString)
-{
- KURL baseURL = m_frame->document()->baseURL();
- if (urlString.isEmpty())
- return baseURL;
-
- return KURL(baseURL, urlString);
-}
-
-void History::stateObjectAdded(PassRefPtr<SerializedScriptValue> data, const String& title, const String& urlString, SameDocumentNavigationSource sameDocumentNavigationSource, ExceptionState& es)
-{
- if (!m_frame || !m_frame->page())
- return;
-
- KURL fullURL = urlForState(urlString);
- if (!fullURL.isValid() || !m_frame->document()->securityOrigin()->canRequest(fullURL)) {
- // We can safely expose the URL to JavaScript, as a) no redirection takes place: JavaScript already had this URL, b) JavaScript can only access a same-origin History object.
- es.throwSecurityError("A history state object with URL '" + fullURL.elidedString() + "' cannot be created in a document with origin '" + m_frame->document()->securityOrigin()->toString() + "'.");
- return;
- }
- m_frame->loader()->updateForSameDocumentNavigation(fullURL, sameDocumentNavigationSource, data, title, FrameLoader::DoNotUpdateBackForwardList);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/page/History.h b/chromium/third_party/WebKit/Source/core/page/History.h
deleted file mode 100644
index 6bd9da79f47..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/History.h
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * Copyright (C) 2007 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef History_h
-#define History_h
-
-#include "bindings/v8/ScriptWrappable.h"
-#include "bindings/v8/SerializedScriptValue.h"
-#include "core/loader/FrameLoaderTypes.h"
-#include "core/page/DOMWindowProperty.h"
-#include "wtf/Forward.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-
-namespace WebCore {
-
-class Frame;
-class KURL;
-class ScriptExecutionContext;
-class ExceptionState;
-
-class History : public ScriptWrappable, public RefCounted<History>, public DOMWindowProperty {
-public:
- static PassRefPtr<History> create(Frame* frame) { return adoptRef(new History(frame)); }
-
- unsigned length() const;
- SerializedScriptValue* state();
- void back();
- void forward();
- void go(int distance);
-
- void back(ScriptExecutionContext*);
- void forward(ScriptExecutionContext*);
- void go(ScriptExecutionContext*, int distance);
-
- bool stateChanged() const;
- bool isSameAsCurrentState(SerializedScriptValue*) const;
-
- void stateObjectAdded(PassRefPtr<SerializedScriptValue>, const String& title, const String& url, SameDocumentNavigationSource, ExceptionState&);
-
-private:
- explicit History(Frame*);
-
- KURL urlForState(const String& url);
-
- SerializedScriptValue* stateInternal() const;
-
- RefPtr<SerializedScriptValue> m_lastStateObjectRequested;
-};
-
-} // namespace WebCore
-
-#endif // History_h
diff --git a/chromium/third_party/WebKit/Source/core/page/History.idl b/chromium/third_party/WebKit/Source/core/page/History.idl
deleted file mode 100644
index d20cc890f1d..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/History.idl
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Copyright (C) 2007, 2008 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-interface History {
- readonly attribute unsigned long length;
- [Custom] readonly attribute SerializedScriptValue state;
-
- [CallWith=ScriptExecutionContext] void back();
- [CallWith=ScriptExecutionContext] void forward();
- [CallWith=ScriptExecutionContext] void go([Default=Undefined] optional long distance);
-
- [Custom, EnabledPerContext=pushState, RaisesException] void pushState(any data, DOMString title, optional DOMString url);
- [Custom, EnabledPerContext=pushState, RaisesException] void replaceState(any data, DOMString title, optional DOMString url);
-};
diff --git a/chromium/third_party/WebKit/Source/core/page/ImageBitmap.cpp b/chromium/third_party/WebKit/Source/core/page/ImageBitmap.cpp
deleted file mode 100644
index a64ea0d4aec..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/ImageBitmap.cpp
+++ /dev/null
@@ -1,200 +0,0 @@
-// Copyright 2013 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "config.h"
-#include "core/page/ImageBitmap.h"
-
-#include "core/html/HTMLCanvasElement.h"
-#include "core/html/HTMLImageElement.h"
-#include "core/html/HTMLVideoElement.h"
-#include "core/html/ImageData.h"
-#include "core/html/canvas/CanvasRenderingContext.h"
-#include "core/platform/graphics/BitmapImage.h"
-#include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/graphics/ImageBuffer.h"
-#include "wtf/RefPtr.h"
-
-using namespace std;
-
-namespace WebCore {
-
-static inline IntRect normalizeRect(const IntRect& rect)
-{
- return IntRect(min(rect.x(), rect.maxX()),
- min(rect.y(), rect.maxY()),
- max(rect.width(), -rect.width()),
- max(rect.height(), -rect.height()));
-}
-
-static inline PassRefPtr<Image> cropImage(Image* image, const IntRect& cropRect)
-{
- IntRect intersectRect = intersection(IntRect(IntPoint(), image->size()), cropRect);
- if (!intersectRect.width() || !intersectRect.height())
- return 0;
-
- SkBitmap cropped;
- image->nativeImageForCurrentFrame()->bitmap().extractSubset(&cropped, intersectRect);
- return BitmapImage::create(NativeImageSkia::create(cropped));
-}
-
-ImageBitmap::ImageBitmap(HTMLImageElement* image, const IntRect& cropRect)
- : m_cropRect(cropRect)
- , m_bitmap(0)
- , m_imageElement(image)
-{
- IntRect srcRect = intersection(cropRect, IntRect(0, 0, image->width(), image->height()));
- m_bitmapRect = IntRect(IntPoint(max(0, -cropRect.x()), max(0, -cropRect.y())), srcRect.size());
- m_bitmapOffset = srcRect.location();
-
- if (!srcRect.width() || !srcRect.height())
- m_imageElement = 0;
- else
- m_imageElement->addClient(this);
-
- ScriptWrappable::init(this);
-}
-
-ImageBitmap::ImageBitmap(HTMLVideoElement* video, const IntRect& cropRect)
- : m_cropRect(cropRect)
- , m_imageElement(0)
- , m_bitmapOffset(IntPoint())
-{
- IntRect videoRect = IntRect(IntPoint(), video->player()->naturalSize());
- IntRect srcRect = intersection(cropRect, videoRect);
- IntRect dstRect(IntPoint(), srcRect.size());
-
- OwnPtr<ImageBuffer> buf = ImageBuffer::create(videoRect.size(), 1, UnacceleratedNonPlatformBuffer);
- GraphicsContext* c = buf->context();
- c->clip(dstRect);
- c->translate(-srcRect.x(), -srcRect.y());
- video->paintCurrentFrameInContext(c, videoRect);
- m_bitmap = buf->copyImage(DontCopyBackingStore);
- m_bitmapRect = IntRect(IntPoint(max(0, -cropRect.x()), max(0, -cropRect.y())), srcRect.size());
-
- ScriptWrappable::init(this);
-}
-
-ImageBitmap::ImageBitmap(HTMLCanvasElement* canvas, const IntRect& cropRect)
- : m_cropRect(cropRect)
- , m_imageElement(0)
- , m_bitmapOffset(IntPoint())
-{
- CanvasRenderingContext* sourceContext = canvas->renderingContext();
- if (sourceContext && sourceContext->is3d())
- sourceContext->paintRenderingResultsToCanvas();
-
- IntRect srcRect = intersection(cropRect, IntRect(IntPoint(), canvas->size()));
- m_bitmapRect = IntRect(IntPoint(max(0, -cropRect.x()), max(0, -cropRect.y())), srcRect.size());
- m_bitmap = cropImage(canvas->buffer()->copyImage(CopyBackingStore).get(), cropRect);
-
- ScriptWrappable::init(this);
-}
-
-ImageBitmap::ImageBitmap(ImageData* data, const IntRect& cropRect)
- : m_cropRect(cropRect)
- , m_imageElement(0)
- , m_bitmapOffset(IntPoint())
-{
- IntRect srcRect = intersection(cropRect, IntRect(IntPoint(), data->size()));
-
- OwnPtr<ImageBuffer> buf = ImageBuffer::create(data->size(), 1, UnacceleratedNonPlatformBuffer);
- if (srcRect.width() > 0 && srcRect.height() > 0)
- buf->putByteArray(Premultiplied, data->data(), data->size(), srcRect, IntPoint(min(0, -cropRect.x()), min(0, -cropRect.y())));
-
- m_bitmap = buf->copyImage(DontCopyBackingStore);
- m_bitmapRect = IntRect(IntPoint(max(0, -cropRect.x()), max(0, -cropRect.y())), srcRect.size());
-
- ScriptWrappable::init(this);
-}
-
-ImageBitmap::ImageBitmap(ImageBitmap* bitmap, const IntRect& cropRect)
- : m_cropRect(cropRect)
- , m_bitmap(0)
- , m_imageElement(bitmap->imageElement())
- , m_bitmapOffset(IntPoint())
-{
- IntRect oldBitmapRect = bitmap->bitmapRect();
- IntRect srcRect = intersection(cropRect, oldBitmapRect);
- m_bitmapRect = IntRect(IntPoint(max(0, oldBitmapRect.x() - cropRect.x()), max(0, oldBitmapRect.y() - cropRect.y())), srcRect.size());
-
- if (m_imageElement) {
- m_imageElement->addClient(this);
- m_bitmapOffset = srcRect.location();
- } else if (bitmap->bitmapImage()) {
- IntRect adjustedCropRect(IntPoint(cropRect.x() -oldBitmapRect.x(), cropRect.y() - oldBitmapRect.y()), cropRect.size());
- m_bitmap = cropImage(bitmap->bitmapImage().get(), adjustedCropRect);
- }
-
- ScriptWrappable::init(this);
-}
-
-ImageBitmap::ImageBitmap(Image* image, const IntRect& cropRect)
- : m_cropRect(cropRect)
- , m_imageElement(0)
-{
- IntRect srcRect = intersection(cropRect, IntRect(IntPoint(), image->size()));
- m_bitmap = cropImage(image, cropRect);
- m_bitmapRect = IntRect(IntPoint(max(0, -cropRect.x()), max(0, -cropRect.y())), srcRect.size());
-
- ScriptWrappable::init(this);
-}
-
-ImageBitmap::~ImageBitmap()
-{
- if (m_imageElement)
- m_imageElement->removeClient(this);
-}
-
-PassRefPtr<ImageBitmap> ImageBitmap::create(HTMLImageElement* image, const IntRect& cropRect)
-{
- IntRect normalizedCropRect = normalizeRect(cropRect);
- return adoptRef(new ImageBitmap(image, normalizedCropRect));
-}
-
-PassRefPtr<ImageBitmap> ImageBitmap::create(HTMLVideoElement* video, const IntRect& cropRect)
-{
- IntRect normalizedCropRect = normalizeRect(cropRect);
- return adoptRef(new ImageBitmap(video, normalizedCropRect));
-}
-
-PassRefPtr<ImageBitmap> ImageBitmap::create(HTMLCanvasElement* canvas, const IntRect& cropRect)
-{
- IntRect normalizedCropRect = normalizeRect(cropRect);
- return adoptRef(new ImageBitmap(canvas, normalizedCropRect));
-}
-
-PassRefPtr<ImageBitmap> ImageBitmap::create(ImageData* data, const IntRect& cropRect)
-{
- IntRect normalizedCropRect = normalizeRect(cropRect);
- return adoptRef(new ImageBitmap(data, normalizedCropRect));
-}
-
-PassRefPtr<ImageBitmap> ImageBitmap::create(ImageBitmap* bitmap, const IntRect& cropRect)
-{
- IntRect normalizedCropRect = normalizeRect(cropRect);
- return adoptRef(new ImageBitmap(bitmap, normalizedCropRect));
-}
-
-PassRefPtr<ImageBitmap> ImageBitmap::create(Image* image, const IntRect& cropRect)
-{
- IntRect normalizedCropRect = normalizeRect(cropRect);
- return adoptRef(new ImageBitmap(image, normalizedCropRect));
-}
-
-void ImageBitmap::notifyImageSourceChanged()
-{
- m_bitmap = cropImage(m_imageElement->cachedImage()->image(), m_cropRect);
- m_bitmapOffset = IntPoint();
- m_imageElement = 0;
-}
-
-PassRefPtr<Image> ImageBitmap::bitmapImage() const
-{
- ASSERT((m_imageElement || m_bitmap || !m_bitmapRect.width() || !m_bitmapRect.height()) && (!m_imageElement || !m_bitmap));
- if (m_imageElement)
- return m_imageElement->cachedImage()->image();
- return m_bitmap;
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/page/ImageBitmap.h b/chromium/third_party/WebKit/Source/core/page/ImageBitmap.h
deleted file mode 100644
index 604d87c6cc6..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/ImageBitmap.h
+++ /dev/null
@@ -1,72 +0,0 @@
-// Copyright 2013 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef ImageBitmap_h
-#define ImageBitmap_h
-
-#include "bindings/v8/ScriptWrappable.h"
-#include "core/html/HTMLImageElement.h"
-#include "core/platform/graphics/Image.h"
-#include "core/platform/graphics/IntRect.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-
-namespace WebCore {
-
-class HTMLCanvasElement;
-class HTMLVideoElement;
-class ImageData;
-
-class ImageBitmap : public RefCounted<ImageBitmap>, public ScriptWrappable, public ImageLoaderClient {
-
-public:
- static PassRefPtr<ImageBitmap> create(HTMLImageElement*, const IntRect&);
- static PassRefPtr<ImageBitmap> create(HTMLVideoElement*, const IntRect&);
- static PassRefPtr<ImageBitmap> create(HTMLCanvasElement*, const IntRect&);
- static PassRefPtr<ImageBitmap> create(ImageData*, const IntRect&);
- static PassRefPtr<ImageBitmap> create(ImageBitmap*, const IntRect&);
- static PassRefPtr<ImageBitmap> create(Image*, const IntRect&);
-
- PassRefPtr<Image> bitmapImage() const;
- PassRefPtr<HTMLImageElement> imageElement() const { return m_imageElement; }
-
- IntRect bitmapRect() const { return m_bitmapRect; }
- IntPoint bitmapOffset() const { return m_bitmapOffset; }
-
- int width() const { return m_cropRect.width(); }
- int height() const { return m_cropRect.height(); }
- IntSize size() const { return m_cropRect.size(); }
-
- virtual ~ImageBitmap();
-
-private:
- ImageBitmap(HTMLImageElement*, const IntRect&);
- ImageBitmap(HTMLVideoElement*, const IntRect&);
- ImageBitmap(HTMLCanvasElement*, const IntRect&);
- ImageBitmap(ImageData*, const IntRect&);
- ImageBitmap(ImageBitmap*, const IntRect&);
- ImageBitmap(Image*, const IntRect&);
-
- // ImageLoaderClient
- virtual void notifyImageSourceChanged();
- virtual bool requestsHighLiveResourceCachePriority() { return true; }
-
- // ImageBitmaps constructed from HTMLImageElements hold a reference to the HTMLImageElement until
- // the image source changes.
- RefPtr<HTMLImageElement> m_imageElement;
- RefPtr<Image> m_bitmap;
-
- IntRect m_bitmapRect; // The rect where the underlying Image should be placed in reference to the ImageBitmap.
- IntRect m_cropRect;
-
- // The offset by which the desired Image is stored internally.
- // ImageBitmaps constructed from HTMLImageElements reference the entire ImageResource and may have a non-zero bitmap offset.
- // ImageBitmaps not constructed from HTMLImageElements always pre-crop and store the image at (0, 0).
- IntPoint m_bitmapOffset;
-
-};
-
-} // namespace WebCore
-
-#endif // ImageBitmap_h
diff --git a/chromium/third_party/WebKit/Source/core/page/ImageBitmap.idl b/chromium/third_party/WebKit/Source/core/page/ImageBitmap.idl
deleted file mode 100644
index b7eec857663..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/ImageBitmap.idl
+++ /dev/null
@@ -1,9 +0,0 @@
-// Copyright 2013 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-[
-] interface ImageBitmap {
- readonly attribute long width;
- readonly attribute long height;
-}; \ No newline at end of file
diff --git a/chromium/third_party/WebKit/Source/core/page/ImageBitmapTest.cpp b/chromium/third_party/WebKit/Source/core/page/ImageBitmapTest.cpp
deleted file mode 100644
index 7d3d1b00dc0..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/ImageBitmapTest.cpp
+++ /dev/null
@@ -1,209 +0,0 @@
-/*
- * Copyright (c) 2013, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/page/ImageBitmap.h"
-
-#include "core/dom/Document.h"
-#include "core/fetch/ImageResource.h"
-#include "core/fetch/MemoryCache.h"
-#include "core/fetch/MockImageResourceClient.h"
-#include "core/fetch/ResourcePtr.h"
-#include "core/html/HTMLCanvasElement.h"
-#include "core/html/HTMLImageElement.h"
-#include "core/html/canvas/CanvasRenderingContext2D.h"
-#include "core/platform/graphics/BitmapImage.h"
-#include "core/platform/graphics/skia/NativeImageSkia.h"
-#include "core/platform/network/ResourceRequest.h"
-#include "third_party/skia/include/core/SkPixelRef.h"
-#include "wtf/OwnPtr.h"
-
-#include <gtest/gtest.h>
-
-namespace WebCore {
-
-class ImageBitmapTest : public ::testing::Test {
-protected:
- virtual void SetUp()
- {
- m_bitmap.setConfig(SkBitmap::kARGB_8888_Config, 10, 10);
- m_bitmap.allocPixels();
- m_bitmap.eraseColor(0xFFFFFFFF);
-
- m_bitmap2.setConfig(SkBitmap::kARGB_8888_Config, 5, 5);
- m_bitmap2.allocPixels();
- m_bitmap2.eraseColor(0xAAAAAAAA);
-
- // Save the global memory cache to restore it upon teardown.
- m_globalMemoryCache = adoptPtr(memoryCache());
- // Create the test memory cache instance and hook it in.
- m_testingMemoryCache = adoptPtr(new MemoryCache());
- setMemoryCacheForTesting(m_testingMemoryCache.leakPtr());
- }
- virtual void TearDown()
- {
- // Regain the ownership of testing memory cache, so that it will be
- // destroyed.
- m_testingMemoryCache = adoptPtr(memoryCache());
- // Yield the ownership of the global memory cache back.
- setMemoryCacheForTesting(m_globalMemoryCache.leakPtr());
- }
-
- SkBitmap m_bitmap, m_bitmap2;
- OwnPtr<MemoryCache> m_testingMemoryCache;
- OwnPtr<MemoryCache> m_globalMemoryCache;
-};
-
-// Verifies that the image resource held by an ImageBitmap is the same as the
-// one held by the HTMLImageElement.
-TEST_F(ImageBitmapTest, ImageResourceConsistency)
-{
- RefPtr<HTMLImageElement> imageElement = HTMLImageElement::create(*Document::create().get());
- imageElement->setImageResource(new ImageResource(BitmapImage::create(NativeImageSkia::create(m_bitmap)).get()));
-
- RefPtr<ImageBitmap> imageBitmapNoCrop = ImageBitmap::create(imageElement.get(), IntRect(0, 0, m_bitmap.width(), m_bitmap.height()));
- RefPtr<ImageBitmap> imageBitmapInteriorCrop = ImageBitmap::create(imageElement.get(), IntRect(m_bitmap.width() / 2, m_bitmap.height() / 2, m_bitmap.width() / 2, m_bitmap.height() / 2));
- RefPtr<ImageBitmap> imageBitmapExteriorCrop = ImageBitmap::create(imageElement.get(), IntRect(-m_bitmap.width() / 2, -m_bitmap.height() / 2, m_bitmap.width(), m_bitmap.height()));
- RefPtr<ImageBitmap> imageBitmapOutsideCrop = ImageBitmap::create(imageElement.get(), IntRect(-m_bitmap.width(), -m_bitmap.height(), m_bitmap.width(), m_bitmap.height()));
-
- ASSERT_EQ(imageBitmapNoCrop->bitmapImage().get(), imageElement->cachedImage()->image());
- ASSERT_EQ(imageBitmapInteriorCrop->bitmapImage().get(), imageElement->cachedImage()->image());
- ASSERT_EQ(imageBitmapExteriorCrop->bitmapImage().get(), imageElement->cachedImage()->image());
-
- RefPtr<Image> emptyImage = imageBitmapOutsideCrop->bitmapImage();
- ASSERT_NE(emptyImage.get(), imageElement->cachedImage()->image());
-}
-
-// Verifies that HTMLImageElements are given an elevated CacheLiveResourcePriority when used to construct an ImageBitmap.
-// ImageBitmaps that have crop rects outside of the bounds of the HTMLImageElement do not have elevated CacheLiveResourcePriority.
-TEST_F(ImageBitmapTest, ImageBitmapLiveResourcePriority)
-{
- RefPtr<HTMLImageElement> imageNoCrop = HTMLImageElement::create(*Document::create().get());
- ResourcePtr<ImageResource> cachedImageNoCrop = new ImageResource(BitmapImage::create(NativeImageSkia::create(m_bitmap)).get());
- imageNoCrop->setImageResource(cachedImageNoCrop.get());
-
- RefPtr<HTMLImageElement> imageInteriorCrop = HTMLImageElement::create(*Document::create().get());
- ResourcePtr<ImageResource> cachedImageInteriorCrop = new ImageResource(BitmapImage::create(NativeImageSkia::create(m_bitmap)).get());
- imageInteriorCrop->setImageResource(cachedImageInteriorCrop.get());
-
- RefPtr<HTMLImageElement> imageExteriorCrop = HTMLImageElement::create(*Document::create().get());
- ResourcePtr<ImageResource> cachedImageExteriorCrop = new ImageResource(BitmapImage::create(NativeImageSkia::create(m_bitmap)).get());
- imageExteriorCrop->setImageResource(cachedImageExteriorCrop.get());
-
- RefPtr<HTMLImageElement> imageOutsideCrop = HTMLImageElement::create(*Document::create().get());
- ResourcePtr<ImageResource> cachedImageOutsideCrop = new ImageResource(BitmapImage::create(NativeImageSkia::create(m_bitmap)).get());
- imageOutsideCrop->setImageResource(cachedImageOutsideCrop.get());
-
- MockImageResourceClient mockClient1, mockClient2, mockClient3, mockClient4;
- cachedImageNoCrop->addClient(&mockClient1);
- cachedImageInteriorCrop->addClient(&mockClient2);
- cachedImageExteriorCrop->addClient(&mockClient3);
- cachedImageOutsideCrop->addClient(&mockClient4);
-
- memoryCache()->add(cachedImageNoCrop.get());
- memoryCache()->add(cachedImageInteriorCrop.get());
- memoryCache()->add(cachedImageExteriorCrop.get());
- memoryCache()->add(cachedImageOutsideCrop.get());
- memoryCache()->insertInLiveDecodedResourcesList(cachedImageNoCrop.get());
- memoryCache()->insertInLiveDecodedResourcesList(cachedImageInteriorCrop.get());
- memoryCache()->insertInLiveDecodedResourcesList(cachedImageExteriorCrop.get());
- memoryCache()->insertInLiveDecodedResourcesList(cachedImageOutsideCrop.get());
-
- // HTMLImageElements should default to CacheLiveResourcePriorityLow.
- ASSERT_EQ(imageNoCrop->cachedImage()->cacheLiveResourcePriority(), Resource::CacheLiveResourcePriorityLow);
- ASSERT_EQ(imageInteriorCrop->cachedImage()->cacheLiveResourcePriority(), Resource::CacheLiveResourcePriorityLow);
- ASSERT_EQ(imageExteriorCrop->cachedImage()->cacheLiveResourcePriority(), Resource::CacheLiveResourcePriorityLow);
- ASSERT_EQ(imageOutsideCrop->cachedImage()->cacheLiveResourcePriority(), Resource::CacheLiveResourcePriorityLow);
-
- RefPtr<ImageBitmap> imageBitmapInteriorCrop = ImageBitmap::create(imageInteriorCrop.get(), IntRect(m_bitmap.width() / 2, m_bitmap.height() / 2, m_bitmap.width(), m_bitmap.height()));
- {
- RefPtr<ImageBitmap> imageBitmapNoCrop = ImageBitmap::create(imageNoCrop.get(), IntRect(0, 0, m_bitmap.width(), m_bitmap.height()));
- RefPtr<ImageBitmap> imageBitmapInteriorCrop2 = ImageBitmap::create(imageInteriorCrop.get(), IntRect(m_bitmap.width() / 2, m_bitmap.height() / 2, m_bitmap.width(), m_bitmap.height()));
- RefPtr<ImageBitmap> imageBitmapExteriorCrop = ImageBitmap::create(imageExteriorCrop.get(), IntRect(-m_bitmap.width() / 2, -m_bitmap.height() / 2, m_bitmap.width(), m_bitmap.height()));
- RefPtr<ImageBitmap> imageBitmapOutsideCrop = ImageBitmap::create(imageOutsideCrop.get(), IntRect(-m_bitmap.width(), -m_bitmap.height(), m_bitmap.width(), m_bitmap.height()));
-
- // Images that are referenced by ImageBitmaps have CacheLiveResourcePriorityHigh.
- ASSERT_EQ(imageNoCrop->cachedImage()->cacheLiveResourcePriority(), Resource::CacheLiveResourcePriorityHigh);
- ASSERT_EQ(imageInteriorCrop->cachedImage()->cacheLiveResourcePriority(), Resource::CacheLiveResourcePriorityHigh);
- ASSERT_EQ(imageExteriorCrop->cachedImage()->cacheLiveResourcePriority(), Resource::CacheLiveResourcePriorityHigh);
-
- // ImageBitmaps that do not contain any of the source image do not elevate CacheLiveResourcePriority.
- ASSERT_EQ(imageOutsideCrop->cachedImage()->cacheLiveResourcePriority(), Resource::CacheLiveResourcePriorityLow);
- }
-
- // CacheLiveResourcePriroity should return to CacheLiveResourcePriorityLow when no ImageBitmaps reference the image.
- ASSERT_EQ(imageNoCrop->cachedImage()->cacheLiveResourcePriority(), Resource::CacheLiveResourcePriorityLow);
- ASSERT_EQ(imageExteriorCrop->cachedImage()->cacheLiveResourcePriority(), Resource::CacheLiveResourcePriorityLow);
- ASSERT_EQ(imageOutsideCrop->cachedImage()->cacheLiveResourcePriority(), Resource::CacheLiveResourcePriorityLow);
-
- // There is still an ImageBitmap that references this image.
- ASSERT_EQ(imageInteriorCrop->cachedImage()->cacheLiveResourcePriority(), Resource::CacheLiveResourcePriorityHigh);
-}
-
-// Verifies that ImageBitmaps constructed from HTMLImageElements hold a reference to the original Image if the HTMLImageElement src is changed.
-TEST_F(ImageBitmapTest, ImageBitmapSourceChanged)
-{
- RefPtr<HTMLImageElement> image = HTMLImageElement::create(*Document::create().get());
- ResourcePtr<ImageResource> originalImageResource = new ImageResource(BitmapImage::create(NativeImageSkia::create(m_bitmap)).get());
- image->setImageResource(originalImageResource.get());
-
- RefPtr<ImageBitmap> imageBitmap = ImageBitmap::create(image.get(), IntRect(0, 0, m_bitmap.width(), m_bitmap.height()));
- ASSERT_EQ(imageBitmap->bitmapImage().get(), originalImageResource->image());
-
- ResourcePtr<ImageResource> newImageResource = new ImageResource(BitmapImage::create(NativeImageSkia::create(m_bitmap2)).get());
- image->setImageResource(newImageResource.get());
-
- // The ImageBitmap should contain the same data as the original cached image but should no longer hold a reference.
- ASSERT_NE(imageBitmap->bitmapImage().get(), originalImageResource->image());
- ASSERT_EQ(imageBitmap->bitmapImage()->nativeImageForCurrentFrame()->bitmap().pixelRef()->pixels(),
- originalImageResource->image()->nativeImageForCurrentFrame()->bitmap().pixelRef()->pixels());
-
- ASSERT_NE(imageBitmap->bitmapImage().get(), newImageResource->image());
- ASSERT_NE(imageBitmap->bitmapImage()->nativeImageForCurrentFrame()->bitmap().pixelRef()->pixels(),
- newImageResource->image()->nativeImageForCurrentFrame()->bitmap().pixelRef()->pixels());
-}
-
-// Verifies that ImageBitmaps constructed from ImageBitmaps hold onto their own Image.
-TEST_F(ImageBitmapTest, ImageResourceLifetime)
-{
- RefPtr<HTMLCanvasElement> canvasElement = HTMLCanvasElement::create(*Document::create().get());
- canvasElement->setHeight(40);
- canvasElement->setWidth(40);
- RefPtr<ImageBitmap> imageBitmapDerived;
- {
- RefPtr<ImageBitmap> imageBitmapFromCanvas = ImageBitmap::create(canvasElement.get(), IntRect(0, 0, canvasElement->width(), canvasElement->height()));
- imageBitmapDerived = ImageBitmap::create(imageBitmapFromCanvas.get(), IntRect(0, 0, 20, 20));
- }
- CanvasRenderingContext* context = canvasElement->getContext("2d");
- TrackExceptionState es;
- static_cast<CanvasRenderingContext2D*>(context)->drawImage(imageBitmapDerived.get(), 0, 0, es);
-}
-
-} // namespace
diff --git a/chromium/third_party/WebKit/Source/core/page/InjectedStyleSheet.h b/chromium/third_party/WebKit/Source/core/page/InjectedStyleSheet.h
new file mode 100644
index 00000000000..cdee055660e
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/page/InjectedStyleSheet.h
@@ -0,0 +1,60 @@
+/*
+ * Copyright (C) 2009 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef InjectedStyleSheet_h
+#define InjectedStyleSheet_h
+
+#include "wtf/Vector.h"
+#include "wtf/text/WTFString.h"
+
+namespace WebCore {
+
+enum StyleInjectionTarget { InjectStyleInAllFrames, InjectStyleInTopFrameOnly };
+
+class InjectedStyleSheet {
+ WTF_MAKE_FAST_ALLOCATED;
+public:
+ InjectedStyleSheet(const String& source, const Vector<String>& whitelist, StyleInjectionTarget injectedFrames)
+ : m_source(source)
+ , m_whitelist(whitelist)
+ , m_injectedFrames(injectedFrames)
+ {
+ }
+
+ const String& source() const { return m_source; }
+ const Vector<String>& whitelist() const { return m_whitelist; }
+ StyleInjectionTarget injectedFrames() const { return m_injectedFrames; }
+
+private:
+ String m_source;
+ Vector<String> m_whitelist;
+ StyleInjectionTarget m_injectedFrames;
+};
+
+typedef Vector<OwnPtr<InjectedStyleSheet> > InjectedStyleSheetVector;
+
+} // namespace WebCore
+
+#endif // InjectedStyleSheet_h
diff --git a/chromium/third_party/WebKit/Source/core/page/LayoutMilestones.h b/chromium/third_party/WebKit/Source/core/page/LayoutMilestones.h
deleted file mode 100644
index dbfcf143bb8..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/LayoutMilestones.h
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright (C) 2012 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef LayoutMilestones_h
-#define LayoutMilestones_h
-
-namespace WebCore {
-
-enum LayoutMilestoneFlag {
- DidFirstLayout = 1 << 0,
- DidFirstVisuallyNonEmptyLayout = 1 << 1,
- DidHitRelevantRepaintedObjectsAreaThreshold = 1 << 2
-};
-
-typedef unsigned LayoutMilestones;
-
-} // namespace WebCore
-
-#endif // LayoutMilestones_h
diff --git a/chromium/third_party/WebKit/Source/core/page/Location.cpp b/chromium/third_party/WebKit/Source/core/page/Location.cpp
deleted file mode 100644
index 493775652c1..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/Location.cpp
+++ /dev/null
@@ -1,269 +0,0 @@
-/*
- * Copyright (C) 2008, 2010 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/page/Location.h"
-
-#include "bindings/v8/ExceptionMessages.h"
-#include "bindings/v8/ExceptionState.h"
-#include "core/dom/Document.h"
-#include "core/dom/ExceptionCode.h"
-#include "core/loader/FrameLoader.h"
-#include "core/page/DOMWindow.h"
-#include "core/page/Frame.h"
-#include "weborigin/KURL.h"
-#include "weborigin/SecurityOrigin.h"
-
-namespace WebCore {
-
-Location::Location(Frame* frame)
- : DOMWindowProperty(frame)
-{
- ScriptWrappable::init(this);
-}
-
-inline const KURL& Location::url() const
-{
- ASSERT(m_frame);
-
- const KURL& url = m_frame->document()->url();
- if (!url.isValid())
- return blankURL(); // Use "about:blank" while the page is still loading (before we have a frame).
-
- return url;
-}
-
-String Location::href() const
-{
- if (!m_frame)
- return String();
-
- return url().string();
-}
-
-String Location::protocol() const
-{
- if (!m_frame)
- return String();
-
- return url().protocol() + ":";
-}
-
-String Location::host() const
-{
- if (!m_frame)
- return String();
-
- // Note: this is the IE spec. The NS spec swaps the two, it says
- // "The hostname property is the concatenation of the host and port properties, separated by a colon."
- const KURL& url = this->url();
- return url.hasPort() ? url.host() + ":" + String::number(url.port()) : url.host();
-}
-
-String Location::hostname() const
-{
- if (!m_frame)
- return String();
-
- return url().host();
-}
-
-String Location::port() const
-{
- if (!m_frame)
- return String();
-
- const KURL& url = this->url();
- return url.hasPort() ? String::number(url.port()) : "";
-}
-
-String Location::pathname() const
-{
- if (!m_frame)
- return String();
-
- const KURL& url = this->url();
- return url.path().isEmpty() ? "/" : url.path();
-}
-
-String Location::search() const
-{
- if (!m_frame)
- return String();
-
- const KURL& url = this->url();
- return url.query().isEmpty() ? emptyString() : "?" + url.query();
-}
-
-String Location::origin() const
-{
- if (!m_frame)
- return String();
- return SecurityOrigin::create(url())->toString();
-}
-
-PassRefPtr<DOMStringList> Location::ancestorOrigins() const
-{
- RefPtr<DOMStringList> origins = DOMStringList::create();
- if (!m_frame)
- return origins.release();
- for (Frame* frame = m_frame->tree()->parent(); frame; frame = frame->tree()->parent())
- origins->append(frame->document()->securityOrigin()->toString());
- return origins.release();
-}
-
-String Location::hash() const
-{
- if (!m_frame)
- return String();
-
- const String& fragmentIdentifier = url().fragmentIdentifier();
- return fragmentIdentifier.isEmpty() ? emptyString() : "#" + fragmentIdentifier;
-}
-
-void Location::setHref(DOMWindow* activeWindow, DOMWindow* firstWindow, const String& url)
-{
- if (!m_frame)
- return;
- setLocation(url, activeWindow, firstWindow);
-}
-
-void Location::setProtocol(DOMWindow* activeWindow, DOMWindow* firstWindow, const String& protocol, ExceptionState& es)
-{
- if (!m_frame)
- return;
- KURL url = m_frame->document()->url();
- if (!url.setProtocol(protocol)) {
- es.throwDOMException(SyntaxError, ExceptionMessages::failedToSet("protocol", "Location", "'" + protocol + "' is an invalid protocol."));
- return;
- }
- setLocation(url.string(), activeWindow, firstWindow);
-}
-
-void Location::setHost(DOMWindow* activeWindow, DOMWindow* firstWindow, const String& host)
-{
- if (!m_frame)
- return;
- KURL url = m_frame->document()->url();
- url.setHostAndPort(host);
- setLocation(url.string(), activeWindow, firstWindow);
-}
-
-void Location::setHostname(DOMWindow* activeWindow, DOMWindow* firstWindow, const String& hostname)
-{
- if (!m_frame)
- return;
- KURL url = m_frame->document()->url();
- url.setHost(hostname);
- setLocation(url.string(), activeWindow, firstWindow);
-}
-
-void Location::setPort(DOMWindow* activeWindow, DOMWindow* firstWindow, const String& portString)
-{
- if (!m_frame)
- return;
- KURL url = m_frame->document()->url();
- int port = portString.toInt();
- if (port < 0 || port > 0xFFFF || portString.isEmpty())
- url.removePort();
- else
- url.setPort(port);
- setLocation(url.string(), activeWindow, firstWindow);
-}
-
-void Location::setPathname(DOMWindow* activeWindow, DOMWindow* firstWindow, const String& pathname)
-{
- if (!m_frame)
- return;
- KURL url = m_frame->document()->url();
- url.setPath(pathname);
- setLocation(url.string(), activeWindow, firstWindow);
-}
-
-void Location::setSearch(DOMWindow* activeWindow, DOMWindow* firstWindow, const String& search)
-{
- if (!m_frame)
- return;
- KURL url = m_frame->document()->url();
- url.setQuery(search);
- setLocation(url.string(), activeWindow, firstWindow);
-}
-
-void Location::setHash(DOMWindow* activeWindow, DOMWindow* firstWindow, const String& hash)
-{
- if (!m_frame)
- return;
- KURL url = m_frame->document()->url();
- String oldFragmentIdentifier = url.fragmentIdentifier();
- String newFragmentIdentifier = hash;
- if (hash[0] == '#')
- newFragmentIdentifier = hash.substring(1);
- url.setFragmentIdentifier(newFragmentIdentifier);
- // Note that by parsing the URL and *then* comparing fragments, we are
- // comparing fragments post-canonicalization, and so this handles the
- // cases where fragment identifiers are ignored or invalid.
- if (equalIgnoringNullity(oldFragmentIdentifier, url.fragmentIdentifier()))
- return;
- setLocation(url.string(), activeWindow, firstWindow);
-}
-
-void Location::assign(DOMWindow* activeWindow, DOMWindow* firstWindow, const String& url)
-{
- if (!m_frame)
- return;
- setLocation(url, activeWindow, firstWindow);
-}
-
-void Location::replace(DOMWindow* activeWindow, DOMWindow* firstWindow, const String& url)
-{
- if (!m_frame)
- return;
- // Note: We call DOMWindow::setLocation directly here because replace() always operates on the current frame.
- m_frame->domWindow()->setLocation(url, activeWindow, firstWindow, LockHistoryAndBackForwardList);
-}
-
-void Location::reload(DOMWindow* activeWindow)
-{
- if (!m_frame)
- return;
- if (protocolIsJavaScript(m_frame->document()->url()))
- return;
- m_frame->navigationScheduler()->scheduleRefresh();
-}
-
-void Location::setLocation(const String& url, DOMWindow* activeWindow, DOMWindow* firstWindow)
-{
- ASSERT(m_frame);
- // We call findFrameForNavigation to handle the case of a seamless iframe correctly.
- Frame* frame = m_frame->loader()->findFrameForNavigation(String(), activeWindow->document());
- if (!frame)
- return;
- frame->domWindow()->setLocation(url, activeWindow, firstWindow);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/page/Location.h b/chromium/third_party/WebKit/Source/core/page/Location.h
deleted file mode 100644
index 63c5b3c30b0..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/Location.h
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * Copyright (C) 2008, 2010 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef Location_h
-#define Location_h
-
-#include "bindings/v8/ScriptWrappable.h"
-#include "core/dom/DOMStringList.h"
-#include "core/page/DOMWindowProperty.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class DOMWindow;
-class ExceptionState;
-class Frame;
-class KURL;
-
-class Location : public ScriptWrappable, public RefCounted<Location>, public DOMWindowProperty {
-public:
- static PassRefPtr<Location> create(Frame* frame) { return adoptRef(new Location(frame)); }
-
- void setHref(DOMWindow* activeWindow, DOMWindow* firstWindow, const String&);
- String href() const;
-
- void assign(DOMWindow* activeWindow, DOMWindow* firstWindow, const String&);
- void replace(DOMWindow* activeWindow, DOMWindow* firstWindow, const String&);
- void reload(DOMWindow* activeWindow);
-
- void setProtocol(DOMWindow* activeWindow, DOMWindow* firstWindow, const String&, ExceptionState&);
- String protocol() const;
- void setHost(DOMWindow* activeWindow, DOMWindow* firstWindow, const String&);
- String host() const;
- void setHostname(DOMWindow* activeWindow, DOMWindow* firstWindow, const String&);
- String hostname() const;
- void setPort(DOMWindow* activeWindow, DOMWindow* firstWindow, const String&);
- String port() const;
- void setPathname(DOMWindow* activeWindow, DOMWindow* firstWindow, const String&);
- String pathname() const;
- void setSearch(DOMWindow* activeWindow, DOMWindow* firstWindow, const String&);
- String search() const;
- void setHash(DOMWindow* activeWindow, DOMWindow* firstWindow, const String&);
- String hash() const;
- String origin() const;
-
- String toString() const { return href(); }
-
- PassRefPtr<DOMStringList> ancestorOrigins() const;
-
-private:
- explicit Location(Frame*);
-
- void setLocation(const String&, DOMWindow* activeWindow, DOMWindow* firstWindow);
-
- const KURL& url() const;
-};
-
-} // namespace WebCore
-
-#endif // Location_h
diff --git a/chromium/third_party/WebKit/Source/core/page/Location.idl b/chromium/third_party/WebKit/Source/core/page/Location.idl
deleted file mode 100644
index 77778e17025..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/Location.idl
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright (C) 2008 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-[
- CheckSecurity
-] interface Location {
- [SetterCallWith=ActiveWindow&FirstWindow, DoNotCheckSecurityOnSetter, Unforgeable] attribute DOMString href;
-
- [CallWith=ActiveWindow&FirstWindow, DoNotCheckSecurity, Unforgeable, ReadOnly, PerWorldBindings, ActivityLog=AccessForIsolatedWorlds] void assign([Default=Undefined] optional DOMString url);
- [CallWith=ActiveWindow&FirstWindow, DoNotCheckSecurity, Unforgeable, ReadOnly, PerWorldBindings, ActivityLog=AccessForIsolatedWorlds] void replace([Default=Undefined] optional DOMString url);
- [CallWith=ActiveWindow, Unforgeable, ReadOnly] void reload();
-
- // URI decomposition attributes
- [SetterCallWith=ActiveWindow&FirstWindow, SetterRaisesException] attribute DOMString protocol;
- [SetterCallWith=ActiveWindow&FirstWindow] attribute DOMString host;
- [SetterCallWith=ActiveWindow&FirstWindow] attribute DOMString hostname;
- [SetterCallWith=ActiveWindow&FirstWindow] attribute DOMString port;
- [SetterCallWith=ActiveWindow&FirstWindow] attribute DOMString pathname;
- [SetterCallWith=ActiveWindow&FirstWindow] attribute DOMString search;
- [SetterCallWith=ActiveWindow&FirstWindow] attribute DOMString hash;
-
- readonly attribute DOMString origin;
-
- readonly attribute DOMStringList ancestorOrigins;
-
- [NotEnumerable, Unforgeable, ReadOnly, ImplementedAs=href] DOMString toString();
- [NotEnumerable, Custom, Unforgeable, ReadOnly] any valueOf();
-};
-
diff --git a/chromium/third_party/WebKit/Source/core/page/MemoryInfo.cpp b/chromium/third_party/WebKit/Source/core/page/MemoryInfo.cpp
deleted file mode 100644
index b3ec36ad538..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/MemoryInfo.cpp
+++ /dev/null
@@ -1,150 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/page/MemoryInfo.h"
-
-#include <limits>
-#include "bindings/v8/ScriptGCEvent.h"
-#include "core/page/Frame.h"
-#include "core/page/Settings.h"
-#include "wtf/CurrentTime.h"
-#include "wtf/MainThread.h"
-#include "wtf/MathExtras.h"
-
-namespace WebCore {
-
-
-class HeapSizeCache {
- WTF_MAKE_NONCOPYABLE(HeapSizeCache); WTF_MAKE_FAST_ALLOCATED;
-public:
- HeapSizeCache()
- : m_lastUpdateTime(0)
- {
- }
-
- void getCachedHeapSize(HeapInfo& info)
- {
- maybeUpdate();
- info = m_info;
- }
-
-private:
- void maybeUpdate()
- {
- // We rate-limit queries to once every twenty minutes to make it more difficult
- // for attackers to compare memory usage before and after some event.
- const double TwentyMinutesInSeconds = 20 * 60;
-
- double now = monotonicallyIncreasingTime();
- if (now - m_lastUpdateTime >= TwentyMinutesInSeconds) {
- update();
- m_lastUpdateTime = now;
- }
- }
-
- void update()
- {
- ScriptGCEvent::getHeapSize(m_info);
- m_info.usedJSHeapSize = quantizeMemorySize(m_info.usedJSHeapSize);
- m_info.totalJSHeapSize = quantizeMemorySize(m_info.totalJSHeapSize);
- m_info.jsHeapSizeLimit = quantizeMemorySize(m_info.jsHeapSizeLimit);
- }
-
- double m_lastUpdateTime;
-
- HeapInfo m_info;
-};
-
-// We quantize the sizes to make it more difficult for an attacker to see precise
-// impact of operations on memory. The values are used for performance tuning,
-// and hence don't need to be as refined when the value is large, so we threshold
-// at a list of exponentially separated buckets.
-size_t quantizeMemorySize(size_t size)
-{
- const int numberOfBuckets = 100;
- DEFINE_STATIC_LOCAL(Vector<size_t>, bucketSizeList, ());
-
- ASSERT(isMainThread());
- if (bucketSizeList.isEmpty()) {
- bucketSizeList.resize(numberOfBuckets);
-
- float sizeOfNextBucket = 10000000.0; // First bucket size is roughly 10M.
- const float largestBucketSize = 4000000000.0; // Roughly 4GB.
- // We scale with the Nth root of the ratio, so that we use all the bucktes.
- const float scalingFactor = exp(log(largestBucketSize / sizeOfNextBucket) / numberOfBuckets);
-
- size_t nextPowerOfTen = static_cast<size_t>(pow(10, floor(log10(sizeOfNextBucket)) + 1) + 0.5);
- size_t granularity = nextPowerOfTen / 1000; // We want 3 signficant digits.
-
- for (int i = 0; i < numberOfBuckets; ++i) {
- size_t currentBucketSize = static_cast<size_t>(sizeOfNextBucket);
- bucketSizeList[i] = currentBucketSize - (currentBucketSize % granularity);
-
- sizeOfNextBucket *= scalingFactor;
- if (sizeOfNextBucket >= nextPowerOfTen) {
- if (std::numeric_limits<size_t>::max() / 10 <= nextPowerOfTen)
- nextPowerOfTen = std::numeric_limits<size_t>::max();
- else {
- nextPowerOfTen *= 10;
- granularity *= 10;
- }
- }
-
- // Watch out for overflow, if the range is too large for size_t.
- if (i > 0 && bucketSizeList[i] < bucketSizeList[i - 1])
- bucketSizeList[i] = std::numeric_limits<size_t>::max();
- }
- }
-
- for (int i = 0; i < numberOfBuckets; ++i) {
- if (size <= bucketSizeList[i])
- return bucketSizeList[i];
- }
-
- return bucketSizeList[numberOfBuckets - 1];
-}
-
-
-MemoryInfo::MemoryInfo(Frame* frame)
-{
- ScriptWrappable::init(this);
- if (!frame || !frame->settings())
- return;
-
- if (frame->settings()->memoryInfoEnabled())
- ScriptGCEvent::getHeapSize(m_info);
- else {
- DEFINE_STATIC_LOCAL(HeapSizeCache, heapSizeCache, ());
- heapSizeCache.getCachedHeapSize(m_info);
- }
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/page/MouseEventWithHitTestResults.cpp b/chromium/third_party/WebKit/Source/core/page/MouseEventWithHitTestResults.cpp
index d0402cfe9d6..2b6a70c2c29 100644
--- a/chromium/third_party/WebKit/Source/core/page/MouseEventWithHitTestResults.cpp
+++ b/chromium/third_party/WebKit/Source/core/page/MouseEventWithHitTestResults.cpp
@@ -34,7 +34,7 @@ MouseEventWithHitTestResults::MouseEventWithHitTestResults(const PlatformMouseEv
bool MouseEventWithHitTestResults::isOverLink() const
{
- return m_hitTestResult.URLElement() && m_hitTestResult.URLElement()->isLink();
+ return m_hitTestResult.isOverLink();
}
}
diff --git a/chromium/third_party/WebKit/Source/core/page/MouseEventWithHitTestResults.h b/chromium/third_party/WebKit/Source/core/page/MouseEventWithHitTestResults.h
index 650936afac8..4ad317d0dc8 100644
--- a/chromium/third_party/WebKit/Source/core/page/MouseEventWithHitTestResults.h
+++ b/chromium/third_party/WebKit/Source/core/page/MouseEventWithHitTestResults.h
@@ -21,8 +21,8 @@
#ifndef MouseEventWithHitTestResults_h
#define MouseEventWithHitTestResults_h
-#include "core/platform/PlatformMouseEvent.h"
#include "core/rendering/HitTestResult.h"
+#include "platform/PlatformMouseEvent.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/page/Navigator.cpp b/chromium/third_party/WebKit/Source/core/page/Navigator.cpp
deleted file mode 100644
index b93cb626e02..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/Navigator.cpp
+++ /dev/null
@@ -1,163 +0,0 @@
-/*
- * Copyright (C) 2000 Harri Porten (porten@kde.org)
- * Copyright (c) 2000 Daniel Molkentin (molkentin@kde.org)
- * Copyright (c) 2000 Stefan Schimanski (schimmi@kde.org)
- * Copyright (C) 2003, 2004, 2005, 2006 Apple Computer, Inc.
- * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-
-#include "config.h"
-#include "core/page/Navigator.h"
-
-#include "bindings/v8/ScriptController.h"
-#include "core/dom/Document.h"
-#include "core/loader/CookieJar.h"
-#include "core/loader/FrameLoader.h"
-#include "core/page/Frame.h"
-#include "core/page/NavigatorID.h"
-#include "core/page/Page.h"
-#include "core/page/Settings.h"
-#include "core/platform/Language.h"
-#include "core/plugins/DOMMimeTypeArray.h"
-#include "core/plugins/DOMPluginArray.h"
-
-#ifndef WEBCORE_NAVIGATOR_PRODUCT_SUB
-#define WEBCORE_NAVIGATOR_PRODUCT_SUB "20030107"
-#endif // ifndef WEBCORE_NAVIGATOR_PRODUCT_SUB
-
-#ifndef WEBCORE_NAVIGATOR_VENDOR
-#define WEBCORE_NAVIGATOR_VENDOR "Google Inc."
-#endif // ifndef WEBCORE_NAVIGATOR_VENDOR
-
-#ifndef WEBCORE_NAVIGATOR_VENDOR_SUB
-#define WEBCORE_NAVIGATOR_VENDOR_SUB ""
-#endif // ifndef WEBCORE_NAVIGATOR_VENDOR_SUB
-
-namespace WebCore {
-
-Navigator::Navigator(Frame* frame)
- : DOMWindowProperty(frame)
-{
- ScriptWrappable::init(this);
-}
-
-Navigator::~Navigator()
-{
-}
-
-// If this function returns true, we need to hide the substring "4." that would otherwise
-// appear in the appVersion string. This is to avoid problems with old versions of a
-// library called OpenCube QuickMenu, which as of this writing is still being used on
-// sites such as nwa.com -- the library thinks Safari is Netscape 4 if we don't do this!
-static bool shouldHideFourDot(Frame* frame)
-{
- const String* sourceURL = frame->script()->sourceURL();
- if (!sourceURL)
- return false;
- if (!(sourceURL->endsWith("/dqm_script.js") || sourceURL->endsWith("/dqm_loader.js") || sourceURL->endsWith("/tdqm_loader.js")))
- return false;
- Settings* settings = frame->settings();
- if (!settings)
- return false;
- return settings->needsSiteSpecificQuirks();
-}
-
-String Navigator::appVersion() const
-{
- if (!m_frame)
- return String();
- String appVersion = NavigatorID::appVersion(this);
- if (shouldHideFourDot(m_frame))
- appVersion.replace("4.", "4_");
- return appVersion;
-}
-
-String Navigator::language() const
-{
- return defaultLanguage();
-}
-
-String Navigator::productSub() const
-{
- return WEBCORE_NAVIGATOR_PRODUCT_SUB;
-}
-
-String Navigator::vendor() const
-{
- return WEBCORE_NAVIGATOR_VENDOR;
-}
-
-String Navigator::vendorSub() const
-{
- return WEBCORE_NAVIGATOR_VENDOR_SUB;
-}
-
-String Navigator::userAgent() const
-{
- if (!m_frame)
- return String();
-
- // If the frame is already detached, FrameLoader::userAgent may malfunction, because it calls a client method
- // that uses frame's WebView (at least, in Mac WebKit).
- if (!m_frame->page())
- return String();
-
- return m_frame->loader()->userAgent(m_frame->document()->url());
-}
-
-DOMPluginArray* Navigator::plugins() const
-{
- if (!m_plugins)
- m_plugins = DOMPluginArray::create(m_frame);
- return m_plugins.get();
-}
-
-DOMMimeTypeArray* Navigator::mimeTypes() const
-{
- if (!m_mimeTypes)
- m_mimeTypes = DOMMimeTypeArray::create(m_frame);
- return m_mimeTypes.get();
-}
-
-bool Navigator::cookieEnabled() const
-{
- if (!m_frame)
- return false;
-
- if (m_frame->page() && !m_frame->page()->settings().cookieEnabled())
- return false;
-
- return cookiesEnabled(m_frame->document());
-}
-
-bool Navigator::javaEnabled() const
-{
- if (!m_frame || !m_frame->settings())
- return false;
-
- if (!m_frame->settings()->isJavaEnabled())
- return false;
-
- return true;
-}
-
-void Navigator::getStorageUpdates()
-{
- // FIXME: Remove this method or rename to yieldForStorageUpdates.
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/page/Navigator.h b/chromium/third_party/WebKit/Source/core/page/Navigator.h
deleted file mode 100644
index 3f417d7b09d..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/Navigator.h
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#ifndef Navigator_h
-#define Navigator_h
-
-#include "bindings/v8/ScriptWrappable.h"
-#include "core/page/DOMWindowProperty.h"
-#include "core/page/NavigatorBase.h"
-#include "core/platform/Supplementable.h"
-#include "wtf/Forward.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/RefPtr.h"
-
-namespace WebCore {
-
-class DOMMimeTypeArray;
-class DOMPluginArray;
-class Frame;
-class PluginData;
-
-typedef int ExceptionCode;
-
-class Navigator : public NavigatorBase, public ScriptWrappable, public RefCounted<Navigator>, public DOMWindowProperty, public Supplementable<Navigator> {
-public:
- static PassRefPtr<Navigator> create(Frame* frame) { return adoptRef(new Navigator(frame)); }
- virtual ~Navigator();
-
- String appVersion() const;
- String language() const;
- DOMPluginArray* plugins() const;
- DOMMimeTypeArray* mimeTypes() const;
- bool cookieEnabled() const;
- bool javaEnabled() const;
-
- String productSub() const;
- String vendor() const;
- String vendorSub() const;
-
- virtual String userAgent() const OVERRIDE;
-
- // Relinquishes the storage lock, if one exists.
- void getStorageUpdates();
-
-private:
- explicit Navigator(Frame*);
-
- mutable RefPtr<DOMPluginArray> m_plugins;
- mutable RefPtr<DOMMimeTypeArray> m_mimeTypes;
-};
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/page/NavigatorID.cpp b/chromium/third_party/WebKit/Source/core/page/NavigatorID.cpp
deleted file mode 100644
index f76f57f6e04..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/NavigatorID.cpp
+++ /dev/null
@@ -1,92 +0,0 @@
-/*
- * Copyright (C) 2008 Apple Inc. All Rights Reserved.
- * Copyright (C) 2013 Samsung Electronics. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "NavigatorID.h"
-
-#include "core/page/NavigatorBase.h"
-
-#if !defined(WEBCORE_NAVIGATOR_PLATFORM) && OS(POSIX) && !OS(MACOSX)
-#include "wtf/StdLibExtras.h"
-#include <sys/utsname.h>
-#endif
-
-#ifndef WEBCORE_NAVIGATOR_PRODUCT
-#define WEBCORE_NAVIGATOR_PRODUCT "Gecko"
-#endif // ifndef WEBCORE_NAVIGATOR_PRODUCT
-
-namespace WebCore {
-
-String NavigatorID::appName(const NavigatorBase*)
-{
- return "Netscape";
-}
-
-String NavigatorID::appVersion(const NavigatorBase* navigator)
-{
- // Version is everything in the user agent string past the "Mozilla/" prefix.
- const String& agent = navigator->userAgent();
- return agent.substring(agent.find('/') + 1);
-}
-
-String NavigatorID::userAgent(const NavigatorBase* navigator)
-{
- return navigator->userAgent();
-}
-
-String NavigatorID::platform(const NavigatorBase*)
-{
-#if defined(WEBCORE_NAVIGATOR_PLATFORM)
- return WEBCORE_NAVIGATOR_PLATFORM;
-#elif OS(MACOSX)
- // Match Safari and Mozilla on Mac x86.
- return "MacIntel";
-#elif OS(WIN)
- // Match Safari and Mozilla on Windows.
- return "Win32";
-#else // Unix-like systems
- struct utsname osname;
- DEFINE_STATIC_LOCAL(String, platformName, (uname(&osname) >= 0 ? String(osname.sysname) + String(" ") + String(osname.machine) : emptyString()));
- return platformName;
-#endif
-}
-
-String NavigatorID::appCodeName(const NavigatorBase*)
-{
- return "Mozilla";
-}
-
-String NavigatorID::product(const NavigatorBase*)
-{
- return WEBCORE_NAVIGATOR_PRODUCT;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/page/NavigatorOnLine.h b/chromium/third_party/WebKit/Source/core/page/NavigatorOnLine.h
deleted file mode 100644
index 934cecbed1a..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/NavigatorOnLine.h
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Copyright (C) 2013 Samsung Electronics. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef NavigatorOnLine_h
-#define NavigatorOnLine_h
-
-#include "core/platform/network/NetworkStateNotifier.h"
-
-namespace WebCore {
-
-class NavigatorOnLine {
-public:
- static bool onLine(void*)
- {
- return networkStateNotifier().onLine();
- }
-};
-
-}
-
-#endif // NavigatorOnLine_h
diff --git a/chromium/third_party/WebKit/Source/core/page/NetworkStateNotifier.cpp b/chromium/third_party/WebKit/Source/core/page/NetworkStateNotifier.cpp
new file mode 100644
index 00000000000..02cc4615c96
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/page/NetworkStateNotifier.cpp
@@ -0,0 +1,58 @@
+/*
+ * Copyright (C) 2008 Apple Inc. All Rights Reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/page/NetworkStateNotifier.h"
+
+#include "core/page/Page.h"
+#include "wtf/Assertions.h"
+#include "wtf/MainThread.h"
+#include "wtf/StdLibExtras.h"
+#include "wtf/Threading.h"
+
+namespace WebCore {
+
+NetworkStateNotifier& networkStateNotifier()
+{
+ AtomicallyInitializedStatic(NetworkStateNotifier*, networkStateNotifier = new NetworkStateNotifier);
+ return *networkStateNotifier;
+}
+
+void NetworkStateNotifier::setOnLine(bool onLine)
+{
+ ASSERT(isMainThread());
+
+ {
+ MutexLocker locker(m_mutex);
+ if (m_isOnLine == onLine)
+ return;
+
+ m_isOnLine = onLine;
+ }
+
+ Page::networkStateChanged(onLine);
+}
+
+}
diff --git a/chromium/third_party/WebKit/Source/core/page/NetworkStateNotifier.h b/chromium/third_party/WebKit/Source/core/page/NetworkStateNotifier.h
new file mode 100644
index 00000000000..7e5fb725d6e
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/page/NetworkStateNotifier.h
@@ -0,0 +1,58 @@
+/*
+ * Copyright (C) 2008 Apple Inc. All Rights Reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef NetworkStateNotifier_h
+#define NetworkStateNotifier_h
+
+#include "wtf/FastAllocBase.h"
+#include "wtf/Noncopyable.h"
+#include "wtf/ThreadingPrimitives.h"
+
+namespace WebCore {
+
+class NetworkStateNotifier {
+ WTF_MAKE_NONCOPYABLE(NetworkStateNotifier); WTF_MAKE_FAST_ALLOCATED;
+public:
+ NetworkStateNotifier()
+ : m_isOnLine(true) { }
+
+ bool onLine() const
+ {
+ MutexLocker locker(m_mutex);
+ return m_isOnLine;
+ }
+
+ void setOnLine(bool);
+
+private:
+ mutable Mutex m_mutex;
+ bool m_isOnLine;
+};
+
+NetworkStateNotifier& networkStateNotifier();
+
+};
+
+#endif // NetworkStateNotifier_h
diff --git a/chromium/third_party/WebKit/Source/core/page/Page.cpp b/chromium/third_party/WebKit/Source/core/page/Page.cpp
index d1b954d47f6..4f2de052953 100644
--- a/chromium/third_party/WebKit/Source/core/page/Page.cpp
+++ b/chromium/third_party/WebKit/Source/core/page/Page.cpp
@@ -22,12 +22,17 @@
#include "core/dom/ClientRectList.h"
#include "core/dom/DocumentMarkerController.h"
-#include "core/dom/Event.h"
-#include "core/dom/EventNames.h"
#include "core/dom/StyleEngine.h"
#include "core/dom/VisitedLinkState.h"
#include "core/editing/Caret.h"
-#include "core/history/BackForwardController.h"
+#include "core/editing/UndoStack.h"
+#include "core/events/Event.h"
+#include "core/events/ThreadLocalEventNames.h"
+#include "core/fetch/ResourceFetcher.h"
+#include "core/frame/DOMTimer.h"
+#include "core/frame/DOMWindow.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
#include "core/history/HistoryItem.h"
#include "core/inspector/InspectorController.h"
#include "core/inspector/InspectorInstrumentation.h"
@@ -35,24 +40,23 @@
#include "core/loader/ProgressTracker.h"
#include "core/page/AutoscrollController.h"
#include "core/page/Chrome.h"
+#include "core/page/ChromeClient.h"
#include "core/page/ContextMenuController.h"
-#include "core/page/DOMTimer.h"
#include "core/page/DragController.h"
#include "core/page/FocusController.h"
-#include "core/page/Frame.h"
#include "core/page/FrameTree.h"
-#include "core/page/FrameView.h"
#include "core/page/PageConsole.h"
#include "core/page/PageGroup.h"
#include "core/page/PageLifecycleNotifier.h"
#include "core/page/PointerLockController.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
#include "core/page/ValidationMessageClient.h"
#include "core/page/scrolling/ScrollingCoordinator.h"
-#include "core/platform/network/NetworkStateNotifier.h"
-#include "core/plugins/PluginData.h"
#include "core/rendering/RenderView.h"
+#include "core/rendering/TextAutosizer.h"
#include "core/storage/StorageNamespace.h"
+#include "core/workers/SharedWorkerRepositoryClient.h"
+#include "platform/plugins/PluginData.h"
#include "wtf/HashMap.h"
#include "wtf/RefCountedLeakCounter.h"
#include "wtf/StdLibExtras.h"
@@ -64,21 +68,24 @@ static HashSet<Page*>* allPages;
DEFINE_DEBUG_ONLY_GLOBAL(WTF::RefCountedLeakCounter, pageCounter, ("Page"));
-static void networkStateChanged()
+void Page::networkStateChanged(bool online)
{
+ if (!allPages)
+ return;
+
Vector<RefPtr<Frame> > frames;
// Get all the frames of all the pages in all the page groups
HashSet<Page*>::iterator end = allPages->end();
for (HashSet<Page*>::iterator it = allPages->begin(); it != end; ++it) {
- for (Frame* frame = (*it)->mainFrame(); frame; frame = frame->tree()->traverseNext())
+ for (Frame* frame = (*it)->mainFrame(); frame; frame = frame->tree().traverseNext())
frames.append(frame);
- InspectorInstrumentation::networkStateChanged(*it);
+ InspectorInstrumentation::networkStateChanged(*it, online);
}
- AtomicString eventName = networkStateNotifier().onLine() ? eventNames().onlineEvent : eventNames().offlineEvent;
+ AtomicString eventName = online ? EventTypeNames::online : EventTypeNames::offline;
for (unsigned i = 0; i < frames.size(); i++)
- frames[i]->document()->dispatchWindowEvent(Event::create(eventName));
+ frames[i]->domWindow()->dispatchEvent(Event::create(eventName));
}
float deviceScaleFactor(Frame* frame)
@@ -92,7 +99,8 @@ float deviceScaleFactor(Frame* frame)
}
Page::Page(PageClients& pageClients)
- : m_autoscrollController(AutoscrollController::create())
+ : SettingsDelegate(Settings::create())
+ , m_autoscrollController(AutoscrollController::create(*this))
, m_chrome(Chrome::create(this, pageClients.chromeClient))
, m_dragCaretController(DragCaretController::create())
, m_dragController(DragController::create(this, pageClients.dragClient))
@@ -100,24 +108,24 @@ Page::Page(PageClients& pageClients)
, m_contextMenuController(ContextMenuController::create(this, pageClients.contextMenuClient))
, m_inspectorController(InspectorController::create(this, pageClients.inspectorClient))
, m_pointerLockController(PointerLockController::create(this))
- , m_settings(Settings::create(this))
+ , m_historyController(adoptPtr(new HistoryController(this)))
, m_progress(ProgressTracker::create())
- , m_backForwardController(BackForwardController::create(this, pageClients.backForwardClient))
+ , m_undoStack(UndoStack::create())
+ , m_backForwardClient(pageClients.backForwardClient)
, m_editorClient(pageClients.editorClient)
, m_validationMessageClient(0)
+ , m_sharedWorkerRepositoryClient(0)
+ , m_spellCheckerClient(pageClients.spellCheckerClient)
, m_subframeCount(0)
, m_openedByDOM(false)
, m_tabKeyCyclesThroughElements(true)
, m_defersLoading(false)
, m_pageScaleFactor(1)
, m_deviceScaleFactor(1)
- , m_didLoadUserStyleSheet(false)
, m_group(0)
, m_timerAlignmentInterval(DOMTimer::visiblePageAlignmentInterval())
, m_visibilityState(PageVisibilityStateVisible)
, m_isCursorVisible(true)
- , m_layoutMilestones(0)
- , m_isCountingRelevantRepaintedObjects(false)
#ifndef NDEBUG
, m_isPainting(false)
#endif
@@ -125,12 +133,9 @@ Page::Page(PageClients& pageClients)
{
ASSERT(m_editorClient);
- if (!allPages) {
+ if (!allPages)
allPages = new HashSet<Page*>;
- networkStateNotifier().setNetworkStateChangedFunction(networkStateChanged);
- }
-
ASSERT(!allPages->contains(this));
allPages->add(this);
@@ -145,7 +150,7 @@ Page::~Page()
clearPageGroup();
allPages->remove(this);
- for (Frame* frame = mainFrame(); frame; frame = frame->tree()->traverseNext()) {
+ for (Frame* frame = mainFrame(); frame; frame = frame->tree().traverseNext()) {
frame->willDetachPage();
frame->detachFromPage();
}
@@ -160,65 +165,11 @@ Page::~Page()
#endif
}
-ViewportArguments Page::viewportArguments() const
-{
- return mainFrame() && mainFrame()->document() ? mainFrame()->document()->viewportArguments() : ViewportArguments();
-}
-
-bool Page::autoscrollInProgress() const
-{
- return m_autoscrollController->autoscrollInProgress();
-}
-
-bool Page::autoscrollInProgress(const RenderBox* renderer) const
-{
- return m_autoscrollController->autoscrollInProgress(renderer);
-}
-
-bool Page::panScrollInProgress() const
-{
- return m_autoscrollController->panScrollInProgress();
-}
-
-void Page::startAutoscrollForSelection(RenderObject* renderer)
-{
- return m_autoscrollController->startAutoscrollForSelection(renderer);
-}
-
-void Page::stopAutoscrollIfNeeded(RenderObject* renderer)
-{
- m_autoscrollController->stopAutoscrollIfNeeded(renderer);
-}
-
-
-void Page::stopAutoscrollTimer()
-{
- m_autoscrollController->stopAutoscrollTimer();
-}
-
-void Page::updateAutoscrollRenderer()
-{
- m_autoscrollController->updateAutoscrollRenderer();
-}
-
-void Page::updateDragAndDrop(Node* dropTargetNode, const IntPoint& eventPosition, double eventTime)
-{
- m_autoscrollController->updateDragAndDrop(dropTargetNode, eventPosition, eventTime);
-}
-
-#if OS(WIN)
-void Page::handleMouseReleaseForPanScrolling(Frame* frame, const PlatformMouseEvent& point)
+ViewportDescription Page::viewportDescription() const
{
- m_autoscrollController->handleMouseReleaseForPanScrolling(frame, point);
+ return mainFrame() && mainFrame()->document() ? mainFrame()->document()->viewportDescription() : ViewportDescription();
}
-void Page::startPanScrolling(RenderBox* renderer, const IntPoint& point)
-{
- m_autoscrollController->startPanScrolling(renderer, point);
-}
-#endif
-
-
ScrollingCoordinator* Page::scrollingCoordinator()
{
if (!m_scrollingCoordinator && m_settings->scrollingCoordinatorEnabled())
@@ -229,9 +180,6 @@ ScrollingCoordinator* Page::scrollingCoordinator()
String Page::mainThreadScrollingReasonsAsText()
{
- if (Document* document = m_mainFrame->document())
- document->updateLayout();
-
if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
return scrollingCoordinator->mainThreadScrollingReasonsAsText();
@@ -265,6 +213,8 @@ void Page::documentDetached(Document* document)
m_contextMenuController->documentDetached(document);
if (m_validationMessageClient)
m_validationMessageClient->documentDetached(*document);
+ if (m_sharedWorkerRepositoryClient)
+ m_sharedWorkerRepositoryClient->documentDetached(document);
}
bool Page::openedByDOM() const
@@ -277,18 +227,6 @@ void Page::setOpenedByDOM()
m_openedByDOM = true;
}
-void Page::goToItem(HistoryItem* item)
-{
- // stopAllLoaders may end up running onload handlers, which could cause further history traversals that may lead to the passed in HistoryItem
- // being deref()-ed. Make sure we can still use it with HistoryController::goToItem later.
- RefPtr<HistoryItem> protector(item);
-
- if (m_mainFrame->loader()->history()->shouldStopLoadingForHistoryItem(item))
- m_mainFrame->loader()->stopAllLoaders();
-
- m_mainFrame->loader()->history()->goToItem(item);
-}
-
void Page::clearPageGroup()
{
if (!m_group)
@@ -302,9 +240,6 @@ void Page::setGroupType(PageGroupType type)
clearPageGroup();
switch (type) {
- case InspectorPageGroup:
- m_group = PageGroup::inspectorGroup();
- break;
case PrivatePageGroup:
m_group = PageGroup::create();
break;
@@ -322,13 +257,13 @@ void Page::scheduleForcedStyleRecalcForAllPages()
return;
HashSet<Page*>::iterator end = allPages->end();
for (HashSet<Page*>::iterator it = allPages->begin(); it != end; ++it)
- for (Frame* frame = (*it)->mainFrame(); frame; frame = frame->tree()->traverseNext())
+ for (Frame* frame = (*it)->mainFrame(); frame; frame = frame->tree().traverseNext())
frame->document()->setNeedsStyleRecalc();
}
void Page::setNeedsRecalcStyleInAllFrames()
{
- for (Frame* frame = mainFrame(); frame; frame = frame->tree()->traverseNext())
+ for (Frame* frame = mainFrame(); frame; frame = frame->tree().traverseNext())
frame->document()->styleResolverChanged(RecalcStyleDeferred);
}
@@ -352,19 +287,19 @@ void Page::refreshPlugins(bool reload)
if (!reload)
continue;
- for (Frame* frame = (*it)->mainFrame(); frame; frame = frame->tree()->traverseNext()) {
- if (frame->loader()->containsPlugins())
+ for (Frame* frame = (*it)->mainFrame(); frame; frame = frame->tree().traverseNext()) {
+ if (frame->document()->containsPlugins())
framesNeedingReload.append(frame);
}
}
for (size_t i = 0; i < framesNeedingReload.size(); ++i)
- framesNeedingReload[i]->loader()->reload();
+ framesNeedingReload[i]->loader().reload();
}
PluginData* Page::pluginData() const
{
- if (!mainFrame()->loader()->allowPlugins(NotAboutToInstantiatePlugin))
+ if (!mainFrame()->loader().allowPlugins(NotAboutToInstantiatePlugin))
return 0;
if (!m_pluginData)
m_pluginData = PluginData::create(this);
@@ -374,8 +309,8 @@ PluginData* Page::pluginData() const
static Frame* incrementFrame(Frame* curr, bool forward, bool wrapFlag)
{
return forward
- ? curr->tree()->traverseNextWithWrap(wrapFlag)
- : curr->tree()->traversePreviousWithWrap(wrapFlag);
+ ? curr->tree().traverseNextWithWrap(wrapFlag)
+ : curr->tree().traversePreviousWithWrap(wrapFlag);
}
void Page::unmarkAllTextMatches()
@@ -396,8 +331,9 @@ void Page::setDefersLoading(bool defers)
return;
m_defersLoading = defers;
- for (Frame* frame = mainFrame(); frame; frame = frame->tree()->traverseNext())
- frame->loader()->setDefersLoading(defers);
+ m_historyController->setDefersLoading(defers);
+ for (Frame* frame = mainFrame(); frame; frame = frame->tree().traverseNext())
+ frame->loader().setDefersLoading(defers);
}
void Page::setPageScaleFactor(float scale, const IntPoint& origin)
@@ -411,6 +347,7 @@ void Page::setPageScaleFactor(float scale, const IntPoint& origin)
view->setVisibleContentScaleFactor(scale);
mainFrame()->deviceOrPageScaleFactorChanged();
+ m_chrome->client().deviceOrPageScaleFactorChanged();
if (view)
view->setViewportConstrainedObjectsNeedLayout();
@@ -428,8 +365,10 @@ void Page::setDeviceScaleFactor(float scaleFactor)
m_deviceScaleFactor = scaleFactor;
setNeedsRecalcStyleInAllFrames();
- if (mainFrame())
+ if (mainFrame()) {
mainFrame()->deviceOrPageScaleFactorChanged();
+ m_chrome->client().deviceOrPageScaleFactorChanged();
+ }
}
void Page::setPagination(const Pagination& pagination)
@@ -442,36 +381,6 @@ void Page::setPagination(const Pagination& pagination)
setNeedsRecalcStyleInAllFrames();
}
-void Page::userStyleSheetLocationChanged()
-{
- // FIXME: Eventually we will move to a model of just being handed the sheet
- // text instead of loading the URL ourselves.
- KURL url = m_settings->userStyleSheetLocation();
-
- m_didLoadUserStyleSheet = false;
- m_userStyleSheet = String();
-
- // Data URLs with base64-encoded UTF-8 style sheets are common. We can process them
- // synchronously and avoid using a loader.
- if (url.protocolIsData() && url.string().startsWith("data:text/css;charset=utf-8;base64,")) {
- m_didLoadUserStyleSheet = true;
-
- Vector<char> styleSheetAsUTF8;
- if (base64Decode(decodeURLEscapeSequences(url.string().substring(35)), styleSheetAsUTF8, Base64IgnoreWhitespace))
- m_userStyleSheet = String::fromUTF8(styleSheetAsUTF8.data(), styleSheetAsUTF8.size());
- }
-
- for (Frame* frame = mainFrame(); frame; frame = frame->tree()->traverseNext()) {
- if (frame->document())
- frame->document()->styleEngine()->updatePageUserSheet();
- }
-}
-
-const String& Page::userStyleSheet() const
-{
- return m_userStyleSheet;
-}
-
void Page::allVisitedStateChanged(PageGroup* group)
{
ASSERT(group);
@@ -483,8 +392,8 @@ void Page::allVisitedStateChanged(PageGroup* group)
Page* page = *it;
if (page->m_group != group)
continue;
- for (Frame* frame = page->m_mainFrame.get(); frame; frame = frame->tree()->traverseNext())
- frame->document()->visitedLinkState()->invalidateStyleForAllLinks();
+ for (Frame* frame = page->m_mainFrame.get(); frame; frame = frame->tree().traverseNext())
+ frame->document()->visitedLinkState().invalidateStyleForAllLinks();
}
}
@@ -499,8 +408,8 @@ void Page::visitedStateChanged(PageGroup* group, LinkHash linkHash)
Page* page = *it;
if (page->m_group != group)
continue;
- for (Frame* frame = page->m_mainFrame.get(); frame; frame = frame->tree()->traverseNext())
- frame->document()->visitedLinkState()->invalidateStyleForLink(linkHash);
+ for (Frame* frame = page->m_mainFrame.get(); frame; frame = frame->tree().traverseNext())
+ frame->document()->visitedLinkState().invalidateStyleForLink(linkHash);
}
}
@@ -517,7 +426,7 @@ void Page::setTimerAlignmentInterval(double interval)
return;
m_timerAlignmentInterval = interval;
- for (Frame* frame = mainFrame(); frame; frame = frame->tree()->traverseNextWithWrap(false)) {
+ for (Frame* frame = mainFrame(); frame; frame = frame->tree().traverseNextWithWrap(false)) {
if (frame->document())
frame->document()->didChangeTimerAlignmentInterval();
}
@@ -528,19 +437,13 @@ double Page::timerAlignmentInterval() const
return m_timerAlignmentInterval;
}
-void Page::dnsPrefetchingStateChanged()
-{
- for (Frame* frame = mainFrame(); frame; frame = frame->tree()->traverseNext())
- frame->document()->initDNSPrefetch();
-}
-
#if !ASSERT_DISABLED
void Page::checkSubframeCountConsistency() const
{
ASSERT(m_subframeCount >= 0);
int subframeCount = 0;
- for (Frame* frame = mainFrame(); frame; frame = frame->tree()->traverseNext())
+ for (Frame* frame = mainFrame(); frame; frame = frame->tree().traverseNext())
++subframeCount;
ASSERT(m_subframeCount + 1 == subframeCount);
@@ -559,7 +462,7 @@ void Page::setVisibilityState(PageVisibilityState visibilityState, bool isInitia
setTimerAlignmentInterval(DOMTimer::visiblePageAlignmentInterval());
if (!isInitialState)
- lifecycleNotifier()->notifyPageVisibilityChanged();
+ lifecycleNotifier().notifyPageVisibilityChanged();
if (!isInitialState && m_mainFrame)
m_mainFrame->dispatchVisibilityStateChangeEvent();
@@ -570,138 +473,6 @@ PageVisibilityState Page::visibilityState() const
return m_visibilityState;
}
-void Page::addLayoutMilestones(LayoutMilestones milestones)
-{
- // In the future, we may want a function that replaces m_layoutMilestones instead of just adding to it.
- m_layoutMilestones |= milestones;
-}
-
-// These are magical constants that might be tweaked over time.
-static double gMinimumPaintedAreaRatio = 0.1;
-static double gMaximumUnpaintedAreaRatio = 0.04;
-
-bool Page::isCountingRelevantRepaintedObjects() const
-{
- return m_isCountingRelevantRepaintedObjects && (m_layoutMilestones & DidHitRelevantRepaintedObjectsAreaThreshold);
-}
-
-void Page::startCountingRelevantRepaintedObjects()
-{
- // Reset everything in case we didn't hit the threshold last time.
- resetRelevantPaintedObjectCounter();
-
- m_isCountingRelevantRepaintedObjects = true;
-}
-
-void Page::resetRelevantPaintedObjectCounter()
-{
- m_isCountingRelevantRepaintedObjects = false;
- m_relevantUnpaintedRenderObjects.clear();
- m_topRelevantPaintedRegion = Region();
- m_bottomRelevantPaintedRegion = Region();
- m_relevantUnpaintedRegion = Region();
-}
-
-static LayoutRect relevantViewRect(RenderView* view)
-{
- // DidHitRelevantRepaintedObjectsAreaThreshold is a LayoutMilestone intended to indicate that
- // a certain relevant amount of content has been drawn to the screen. This is the rect that
- // has been determined to be relevant in the context of this goal. We may choose to tweak
- // the rect over time, much like we may choose to tweak gMinimumPaintedAreaRatio and
- // gMaximumUnpaintedAreaRatio. But this seems to work well right now.
- LayoutRect relevantViewRect = LayoutRect(0, 0, 980, 1300);
-
- LayoutRect viewRect = view->viewRect();
- // If the viewRect is wider than the relevantViewRect, center the relevantViewRect.
- if (viewRect.width() > relevantViewRect.width())
- relevantViewRect.setX((viewRect.width() - relevantViewRect.width()) / 2);
-
- return relevantViewRect;
-}
-
-void Page::addRelevantRepaintedObject(RenderObject* object, const LayoutRect& objectPaintRect)
-{
- if (!isCountingRelevantRepaintedObjects())
- return;
-
- // Objects inside sub-frames are not considered to be relevant.
- if (object->document().frame() != mainFrame())
- return;
-
- RenderView* view = object->view();
- if (!view)
- return;
-
- LayoutRect relevantRect = relevantViewRect(view);
-
- // The objects are only relevant if they are being painted within the viewRect().
- if (!objectPaintRect.intersects(pixelSnappedIntRect(relevantRect)))
- return;
-
- IntRect snappedPaintRect = pixelSnappedIntRect(objectPaintRect);
-
- // If this object was previously counted as an unpainted object, remove it from that HashSet
- // and corresponding Region. FIXME: This doesn't do the right thing if the objects overlap.
- HashSet<RenderObject*>::iterator it = m_relevantUnpaintedRenderObjects.find(object);
- if (it != m_relevantUnpaintedRenderObjects.end()) {
- m_relevantUnpaintedRenderObjects.remove(it);
- m_relevantUnpaintedRegion.subtract(snappedPaintRect);
- }
-
- // Split the relevantRect into a top half and a bottom half. Making sure we have coverage in
- // both halves helps to prevent cases where we have a fully loaded menu bar or masthead with
- // no content beneath that.
- LayoutRect topRelevantRect = relevantRect;
- topRelevantRect.contract(LayoutSize(0, relevantRect.height() / 2));
- LayoutRect bottomRelevantRect = topRelevantRect;
- bottomRelevantRect.setY(relevantRect.height() / 2);
-
- // If the rect straddles both Regions, split it appropriately.
- if (topRelevantRect.intersects(snappedPaintRect) && bottomRelevantRect.intersects(snappedPaintRect)) {
- IntRect topIntersection = snappedPaintRect;
- topIntersection.intersect(pixelSnappedIntRect(topRelevantRect));
- m_topRelevantPaintedRegion.unite(topIntersection);
-
- IntRect bottomIntersection = snappedPaintRect;
- bottomIntersection.intersect(pixelSnappedIntRect(bottomRelevantRect));
- m_bottomRelevantPaintedRegion.unite(bottomIntersection);
- } else if (topRelevantRect.intersects(snappedPaintRect))
- m_topRelevantPaintedRegion.unite(snappedPaintRect);
- else
- m_bottomRelevantPaintedRegion.unite(snappedPaintRect);
-
- float topPaintedArea = m_topRelevantPaintedRegion.totalArea();
- float bottomPaintedArea = m_bottomRelevantPaintedRegion.totalArea();
- float viewArea = relevantRect.width() * relevantRect.height();
-
- float ratioThatIsPaintedOnTop = topPaintedArea / viewArea;
- float ratioThatIsPaintedOnBottom = bottomPaintedArea / viewArea;
- float ratioOfViewThatIsUnpainted = m_relevantUnpaintedRegion.totalArea() / viewArea;
-
- if (ratioThatIsPaintedOnTop > (gMinimumPaintedAreaRatio / 2) && ratioThatIsPaintedOnBottom > (gMinimumPaintedAreaRatio / 2)
- && ratioOfViewThatIsUnpainted < gMaximumUnpaintedAreaRatio) {
- m_isCountingRelevantRepaintedObjects = false;
- resetRelevantPaintedObjectCounter();
- if (Frame* frame = mainFrame())
- frame->loader()->didLayout(DidHitRelevantRepaintedObjectsAreaThreshold);
- }
-}
-
-void Page::addRelevantUnpaintedObject(RenderObject* object, const LayoutRect& objectPaintRect)
-{
- if (!isCountingRelevantRepaintedObjects())
- return;
-
- // The objects are only relevant if they are being painted within the relevantViewRect().
- if (RenderView* view = object->view()) {
- if (!objectPaintRect.intersects(pixelSnappedIntRect(relevantViewRect(view))))
- return;
- }
-
- m_relevantUnpaintedRenderObjects.add(object);
- m_relevantUnpaintedRegion.unite(pixelSnappedIntRect(objectPaintRect));
-}
-
void Page::addMultisamplingChangedObserver(MultisamplingChangedObserver* observer)
{
m_multisamplingChangedObservers.add(observer);
@@ -712,26 +483,61 @@ void Page::removeMultisamplingChangedObserver(MultisamplingChangedObserver* obse
m_multisamplingChangedObservers.remove(observer);
}
-void Page::multisamplingChanged()
+void Page::settingsChanged(SettingsDelegate::ChangeType changeType)
{
- HashSet<MultisamplingChangedObserver*>::iterator stop = m_multisamplingChangedObservers.end();
- for (HashSet<MultisamplingChangedObserver*>::iterator it = m_multisamplingChangedObservers.begin(); it != stop; ++it)
- (*it)->multisamplingChanged(m_settings->openGLMultisamplingEnabled());
+ switch (changeType) {
+ case SettingsDelegate::StyleChange:
+ setNeedsRecalcStyleInAllFrames();
+ break;
+ case SettingsDelegate::ViewportDescriptionChange:
+ if (mainFrame())
+ mainFrame()->document()->updateViewportDescription();
+ break;
+ case SettingsDelegate::MediaTypeChange:
+ m_mainFrame->view()->setMediaType(settings().mediaTypeOverride());
+ setNeedsRecalcStyleInAllFrames();
+ break;
+ case SettingsDelegate::DNSPrefetchingChange:
+ for (Frame* frame = mainFrame(); frame; frame = frame->tree().traverseNext())
+ frame->document()->initDNSPrefetch();
+ break;
+ case SettingsDelegate::MultisamplingChange: {
+ HashSet<MultisamplingChangedObserver*>::iterator stop = m_multisamplingChangedObservers.end();
+ for (HashSet<MultisamplingChangedObserver*>::iterator it = m_multisamplingChangedObservers.begin(); it != stop; ++it)
+ (*it)->multisamplingChanged(m_settings->openGLMultisamplingEnabled());
+ break;
+ }
+ case SettingsDelegate::ImageLoadingChange:
+ for (Frame* frame = mainFrame(); frame; frame = frame->tree().traverseNext()) {
+ frame->document()->fetcher()->setImagesEnabled(settings().imagesEnabled());
+ frame->document()->fetcher()->setAutoLoadImages(settings().loadsImagesAutomatically());
+ }
+ break;
+ case SettingsDelegate::TextAutosizingChange:
+ // FIXME: I wonder if this needs to traverse frames like in WebViewImpl::resize, or whether there is only one document per Settings instance?
+ for (Frame* frame = mainFrame(); frame; frame = frame->tree().traverseNext()) {
+ TextAutosizer* textAutosizer = frame->document()->textAutosizer();
+ if (textAutosizer)
+ textAutosizer->recalculateMultipliers();
+ }
+ setNeedsRecalcStyleInAllFrames();
+ break;
+ }
}
void Page::didCommitLoad(Frame* frame)
{
- lifecycleNotifier()->notifyDidCommitLoad(frame);
+ lifecycleNotifier().notifyDidCommitLoad(frame);
if (m_mainFrame == frame)
useCounter().didCommitLoad();
}
-PageLifecycleNotifier* Page::lifecycleNotifier()
+PageLifecycleNotifier& Page::lifecycleNotifier()
{
- return static_cast<PageLifecycleNotifier*>(LifecycleContext::lifecycleNotifier());
+ return static_cast<PageLifecycleNotifier&>(LifecycleContext<Page>::lifecycleNotifier());
}
-PassOwnPtr<LifecycleNotifier> Page::createLifecycleNotifier()
+PassOwnPtr<LifecycleNotifier<Page> > Page::createLifecycleNotifier()
{
return PageLifecycleNotifier::create(this);
}
@@ -742,6 +548,8 @@ Page::PageClients::PageClients()
, editorClient(0)
, dragClient(0)
, inspectorClient(0)
+ , backForwardClient(0)
+ , spellCheckerClient(0)
{
}
diff --git a/chromium/third_party/WebKit/Source/core/page/Page.h b/chromium/third_party/WebKit/Source/core/page/Page.h
index 1323bfffbf1..1104d156851 100644
--- a/chromium/third_party/WebKit/Source/core/page/Page.h
+++ b/chromium/third_party/WebKit/Source/core/page/Page.h
@@ -21,15 +21,16 @@
#ifndef Page_h
#define Page_h
-#include "core/dom/ViewportArguments.h"
-#include "core/page/LayoutMilestones.h"
+#include "core/dom/ViewportDescription.h"
+#include "core/frame/SettingsDelegate.h"
+#include "core/frame/UseCounter.h"
+#include "core/loader/HistoryController.h"
#include "core/page/PageVisibilityState.h"
-#include "core/page/UseCounter.h"
-#include "core/platform/LifecycleContext.h"
-#include "core/platform/Supplementable.h"
-#include "core/platform/graphics/LayoutRect.h"
-#include "core/platform/graphics/Region.h"
#include "core/rendering/Pagination.h"
+#include "platform/LifecycleContext.h"
+#include "platform/Supplementable.h"
+#include "platform/geometry/LayoutRect.h"
+#include "platform/geometry/Region.h"
#include "wtf/Forward.h"
#include "wtf/HashSet.h"
#include "wtf/Noncopyable.h"
@@ -39,7 +40,6 @@ namespace WebCore {
class AutoscrollController;
class BackForwardClient;
-class BackForwardController;
class Chrome;
class ChromeClient;
class ClientRectList;
@@ -73,14 +73,17 @@ class VisibleSelection;
class ScrollableArea;
class ScrollingCoordinator;
class Settings;
+class SharedWorkerRepositoryClient;
+class SpellCheckerClient;
class StorageNamespace;
+class UndoStack;
class ValidationMessageClient;
typedef uint64_t LinkHash;
float deviceScaleFactor(Frame*);
-class Page : public Supplementable<Page>, public LifecycleContext {
+class Page : public Supplementable<Page>, public LifecycleContext<Page>, public SettingsDelegate {
WTF_MAKE_NONCOPYABLE(Page);
friend class Settings;
public:
@@ -99,6 +102,7 @@ public:
DragClient* dragClient;
InspectorClient* inspectorClient;
BackForwardClient* backForwardClient;
+ SpellCheckerClient* spellCheckerClient;
};
explicit Page(PageClients&);
@@ -106,12 +110,16 @@ public:
void setNeedsRecalcStyleInAllFrames();
- ViewportArguments viewportArguments() const;
+ ViewportDescription viewportDescription() const;
static void refreshPlugins(bool reload);
PluginData* pluginData() const;
EditorClient& editorClient() const { return *m_editorClient; }
+ SpellCheckerClient& spellCheckerClient() const { return *m_spellCheckerClient; }
+ UndoStack& undoStack() const { return *m_undoStack; }
+
+ HistoryController& historyController() const { return *m_historyController; }
void setMainFrame(PassRefPtr<Frame>);
Frame* mainFrame() const { return m_mainFrame.get(); }
@@ -121,11 +129,7 @@ public:
bool openedByDOM() const;
void setOpenedByDOM();
- // DEPRECATED. Use backForward() instead of the following function.
- void goToItem(HistoryItem*);
-
- // FIXME: InspectorPageGroup is only needed to support single process debugger layout tests, it should be removed when DumpRenderTree is gone.
- enum PageGroupType { InspectorPageGroup, PrivatePageGroup, SharedPageGroup };
+ enum PageGroupType { PrivatePageGroup, SharedPageGroup };
void setGroupType(PageGroupType);
void clearPageGroup();
PageGroup& group()
@@ -140,6 +144,7 @@ public:
int subframeCount() const { checkSubframeCountConsistency(); return m_subframeCount; }
Chrome& chrome() const { return *m_chrome; }
+ AutoscrollController& autoscrollController() const { return *m_autoscrollController; }
DragCaretController& dragCaretController() const { return *m_dragCaretController; }
DragController& dragController() const { return *m_dragController; }
FocusController& focusController() const { return *m_focusController; }
@@ -148,19 +153,8 @@ public:
PointerLockController& pointerLockController() const { return *m_pointerLockController; }
ValidationMessageClient* validationMessageClient() const { return m_validationMessageClient; }
void setValidationMessageClient(ValidationMessageClient* client) { m_validationMessageClient = client; }
-
- bool autoscrollInProgress() const;
- bool autoscrollInProgress(const RenderBox*) const;
- bool panScrollInProgress() const;
- void startAutoscrollForSelection(RenderObject*);
- void stopAutoscrollIfNeeded(RenderObject*);
- void stopAutoscrollTimer();
- void updateAutoscrollRenderer();
- void updateDragAndDrop(Node* targetNode, const IntPoint& eventPosition, double eventTime);
-#if OS(WIN)
- void handleMouseReleaseForPanScrolling(Frame*, const PlatformMouseEvent&);
- void startPanScrolling(RenderBox*, const IntPoint&);
-#endif
+ SharedWorkerRepositoryClient* sharedWorkerRepositoryClient() { return m_sharedWorkerRepositoryClient; }
+ void setSharedWorkerRepositoryClient(SharedWorkerRepositoryClient* client) { m_sharedWorkerRepositoryClient = client; }
ScrollingCoordinator* scrollingCoordinator();
@@ -169,7 +163,7 @@ public:
Settings& settings() const { return *m_settings; }
ProgressTracker& progress() const { return *m_progress; }
- BackForwardController& backForward() const { return *m_backForwardController; }
+ BackForwardClient& backForward() const { return *m_backForwardClient; }
UseCounter& useCounter() { return m_useCounter; }
@@ -178,6 +172,9 @@ public:
void unmarkAllTextMatches();
+ // DefersLoading is used to delay loads during modal dialogs.
+ // Modal dialogs are supposed to freeze all background processes
+ // in the page, including prevent additional loads from staring/continuing.
void setDefersLoading(bool);
bool defersLoading() const { return m_defersLoading; }
@@ -194,11 +191,6 @@ public:
const Pagination& pagination() const { return m_pagination; }
void setPagination(const Pagination&);
- void userStyleSheetLocationChanged();
- const String& userStyleSheet() const;
-
- void dnsPrefetchingStateChanged();
-
static void allVisitedStateChanged(PageGroup*);
static void visitedStateChanged(PageGroup*, LinkHash visitedHash);
@@ -216,15 +208,6 @@ public:
bool isCursorVisible() const { return m_isCursorVisible; }
void setIsCursorVisible(bool isVisible) { m_isCursorVisible = isVisible; }
- void addLayoutMilestones(LayoutMilestones);
- LayoutMilestones layoutMilestones() const { return m_layoutMilestones; }
-
- bool isCountingRelevantRepaintedObjects() const;
- void startCountingRelevantRepaintedObjects();
- void resetRelevantPaintedObjectCounter();
- void addRelevantRepaintedObject(RenderObject*, const LayoutRect& objectPaintRect);
- void addRelevantUnpaintedObject(RenderObject*, const LayoutRect& objectPaintRect);
-
#ifndef NDEBUG
void setIsPainting(bool painting) { m_isPainting = painting; }
bool isPainting() const { return m_isPainting; }
@@ -241,12 +224,14 @@ public:
void addMultisamplingChangedObserver(MultisamplingChangedObserver*);
void removeMultisamplingChangedObserver(MultisamplingChangedObserver*);
- void multisamplingChanged();
void didCommitLoad(Frame*);
+ static void networkStateChanged(bool online);
+ PassOwnPtr<LifecycleNotifier<Page> > createLifecycleNotifier();
+
protected:
- PageLifecycleNotifier* lifecycleNotifier();
+ PageLifecycleNotifier& lifecycleNotifier();
private:
void initGroup();
@@ -259,7 +244,9 @@ private:
void setTimerAlignmentInterval(double);
- virtual PassOwnPtr<LifecycleNotifier> createLifecycleNotifier() OVERRIDE;
+ // SettingsDelegate overrides.
+ virtual Page* page() OVERRIDE { return this; }
+ virtual void settingsChanged(SettingsDelegate::ChangeType) OVERRIDE;
const OwnPtr<AutoscrollController> m_autoscrollController;
const OwnPtr<Chrome> m_chrome;
@@ -271,16 +258,19 @@ private:
const OwnPtr<PointerLockController> m_pointerLockController;
RefPtr<ScrollingCoordinator> m_scrollingCoordinator;
- const OwnPtr<Settings> m_settings;
+ const OwnPtr<HistoryController> m_historyController;
const OwnPtr<ProgressTracker> m_progress;
+ const OwnPtr<UndoStack> m_undoStack;
- const OwnPtr<BackForwardController> m_backForwardController;
RefPtr<Frame> m_mainFrame;
mutable RefPtr<PluginData> m_pluginData;
+ BackForwardClient* m_backForwardClient;
EditorClient* const m_editorClient;
ValidationMessageClient* m_validationMessageClient;
+ SharedWorkerRepositoryClient* m_sharedWorkerRepositoryClient;
+ SpellCheckerClient* const m_spellCheckerClient;
UseCounter m_useCounter;
@@ -295,9 +285,6 @@ private:
Pagination m_pagination;
- mutable String m_userStyleSheet;
- mutable bool m_didLoadUserStyleSheet;
-
RefPtr<PageGroup> m_group;
OwnPtr<StorageNamespace> m_sessionStorage;
@@ -308,13 +295,6 @@ private:
bool m_isCursorVisible;
- LayoutMilestones m_layoutMilestones;
-
- HashSet<RenderObject*> m_relevantUnpaintedRenderObjects;
- Region m_topRelevantPaintedRegion;
- Region m_bottomRelevantPaintedRegion;
- Region m_relevantUnpaintedRegion;
- bool m_isCountingRelevantRepaintedObjects;
#ifndef NDEBUG
bool m_isPainting;
#endif
diff --git a/chromium/third_party/WebKit/Source/core/page/PageConsole.cpp b/chromium/third_party/WebKit/Source/core/page/PageConsole.cpp
index 81cbc4ca0f9..763910a162c 100644
--- a/chromium/third_party/WebKit/Source/core/page/PageConsole.cpp
+++ b/chromium/third_party/WebKit/Source/core/page/PageConsole.cpp
@@ -33,11 +33,9 @@
#include "core/dom/ScriptableDocumentParser.h"
#include "core/inspector/ConsoleAPITypes.h"
#include "core/inspector/InspectorConsoleInstrumentation.h"
-#include "core/inspector/ScriptCallStack.h"
#include "core/page/Chrome.h"
#include "core/page/ChromeClient.h"
-#include "core/page/ConsoleBase.h"
-#include "core/page/ConsoleTypes.h"
+#include "core/frame/ConsoleBase.h"
#include "core/page/Page.h"
#include "wtf/text/StringBuilder.h"
#include "wtf/text/WTFString.h"
@@ -55,8 +53,6 @@ PageConsole::PageConsole(Page* page)
{
}
-PageConsole::~PageConsole() { }
-
void PageConsole::addMessage(MessageSource source, MessageLevel level, const String& message)
{
addMessage(source, level, message, String(), 0, 0, 0, 0, 0);
@@ -72,7 +68,7 @@ void PageConsole::addMessage(MessageSource source, MessageLevel level, const Str
if (muteCount && source != ConsoleAPIMessageSource)
return;
- ScriptExecutionContext* context = m_page->mainFrame()->document();
+ ExecutionContext* context = m_page->mainFrame()->document();
if (!context)
return;
diff --git a/chromium/third_party/WebKit/Source/core/page/PageConsole.h b/chromium/third_party/WebKit/Source/core/page/PageConsole.h
index 20cd0864bbe..b62d1922ed1 100644
--- a/chromium/third_party/WebKit/Source/core/page/PageConsole.h
+++ b/chromium/third_party/WebKit/Source/core/page/PageConsole.h
@@ -31,7 +31,7 @@
#include "bindings/v8/ScriptState.h"
#include "core/inspector/ScriptCallStack.h"
-#include "core/page/ConsoleTypes.h"
+#include "core/frame/ConsoleTypes.h"
#include "wtf/Forward.h"
#include "wtf/PassOwnPtr.h"
@@ -39,10 +39,9 @@ namespace WebCore {
class Page;
-class PageConsole {
+class PageConsole FINAL {
public:
static PassOwnPtr<PageConsole> create(Page* page) { return adoptPtr(new PageConsole(page)); }
- virtual ~PageConsole();
void addMessage(MessageSource, MessageLevel, const String& message);
void addMessage(MessageSource, MessageLevel, const String& message, const String& sourceURL, unsigned lineNumber, unsigned columnNumber = 0, PassRefPtr<ScriptCallStack> = 0, ScriptState* = 0, unsigned long requestIdentifier = 0);
diff --git a/chromium/third_party/WebKit/Source/core/page/PageGroup.cpp b/chromium/third_party/WebKit/Source/core/page/PageGroup.cpp
index 29b1937fac1..b4a72714323 100644
--- a/chromium/third_party/WebKit/Source/core/page/PageGroup.cpp
+++ b/chromium/third_party/WebKit/Source/core/page/PageGroup.cpp
@@ -28,8 +28,9 @@
#include "core/dom/Document.h"
#include "core/dom/StyleEngine.h"
-#include "core/page/Frame.h"
+#include "core/frame/Frame.h"
#include "core/page/Page.h"
+#include "wtf/StdLibExtras.h"
namespace WebCore {
@@ -39,21 +40,15 @@ PageGroup::PageGroup()
PageGroup::~PageGroup()
{
- removeAllUserContent();
+ removeInjectedStyleSheets();
}
PageGroup* PageGroup::sharedGroup()
{
- static PageGroup* staticSharedGroup = create().leakRef();
+ DEFINE_STATIC_REF(PageGroup, staticSharedGroup, (create()));
return staticSharedGroup;
}
-PageGroup* PageGroup::inspectorGroup()
-{
- static PageGroup* staticInspectorGroup = create().leakRef();
- return staticInspectorGroup;
-}
-
void PageGroup::addPage(Page* page)
{
ASSERT(page);
@@ -68,21 +63,15 @@ void PageGroup::removePage(Page* page)
m_pages.remove(page);
}
-void PageGroup::addUserStyleSheet(const String& source, const KURL& url,
- const Vector<String>& whitelist, const Vector<String>& blacklist,
- UserContentInjectedFrames injectedFrames,
- UserStyleLevel level,
- UserStyleInjectionTime injectionTime)
+void PageGroup::injectStyleSheet(const String& source, const Vector<String>& whitelist, StyleInjectionTarget injectIn)
{
- m_userStyleSheets.append(adoptPtr(new UserStyleSheet(source, url, whitelist, blacklist, injectedFrames, level)));
-
- if (injectionTime == InjectInExistingDocuments)
- invalidatedInjectedStyleSheetCacheInAllFrames();
+ m_injectedStyleSheets.append(adoptPtr(new InjectedStyleSheet(source, whitelist, injectIn)));
+ invalidatedInjectedStyleSheetCacheInAllFrames();
}
-void PageGroup::removeAllUserContent()
+void PageGroup::removeInjectedStyleSheets()
{
- m_userStyleSheets.clear();
+ m_injectedStyleSheets.clear();
invalidatedInjectedStyleSheetCacheInAllFrames();
}
@@ -91,7 +80,7 @@ void PageGroup::invalidatedInjectedStyleSheetCacheInAllFrames()
// Clear our cached sheets and have them just reparse.
HashSet<Page*>::const_iterator end = m_pages.end();
for (HashSet<Page*>::const_iterator it = m_pages.begin(); it != end; ++it) {
- for (Frame* frame = (*it)->mainFrame(); frame; frame = frame->tree()->traverseNext())
+ for (Frame* frame = (*it)->mainFrame(); frame; frame = frame->tree().traverseNext())
frame->document()->styleEngine()->invalidateInjectedStyleSheetCache();
}
}
diff --git a/chromium/third_party/WebKit/Source/core/page/PageGroup.h b/chromium/third_party/WebKit/Source/core/page/PageGroup.h
index c10f83a4b4b..5293bde39bc 100644
--- a/chromium/third_party/WebKit/Source/core/page/PageGroup.h
+++ b/chromium/third_party/WebKit/Source/core/page/PageGroup.h
@@ -26,8 +26,8 @@
#ifndef PageGroup_h
#define PageGroup_h
-#include "core/page/UserStyleSheet.h"
-#include "core/platform/Supplementable.h"
+#include "core/page/InjectedStyleSheet.h"
+#include "platform/Supplementable.h"
#include "wtf/HashSet.h"
#include "wtf/Noncopyable.h"
#include "wtf/PassRefPtr.h"
@@ -35,10 +35,17 @@
namespace WebCore {
- class KURL;
class Page;
- class SecurityOrigin;
+ // FIXME: This is really more of a "Settings Group" than a Page Group.
+ // It has nothing to do with Page. There is one shared PageGroup
+ // in the renderer process, which all normal Pages belong to. There are also
+ // additional private PageGroups for SVGImage, Inspector Overlay, etc.
+
+ // This really only exists to service InjectedStyleSheets at this point.
+ // InjectedStyleSheets could instead just use a global, and StyleEngine
+ // could be taught to look for InjectedStyleSheets when resolving style
+ // for normal frames.
class PageGroup : public Supplementable<PageGroup>, public RefCounted<PageGroup> {
WTF_MAKE_NONCOPYABLE(PageGroup); WTF_MAKE_FAST_ALLOCATED;
public:
@@ -46,22 +53,16 @@ namespace WebCore {
static PassRefPtr<PageGroup> create() { return adoptRef(new PageGroup()); }
static PageGroup* sharedGroup();
- static PageGroup* inspectorGroup();
const HashSet<Page*>& pages() const { return m_pages; }
void addPage(Page*);
void removePage(Page*);
- void addUserStyleSheet(const String& source, const KURL&,
- const Vector<String>& whitelist, const Vector<String>& blacklist,
- UserContentInjectedFrames,
- UserStyleLevel level = UserStyleUserLevel,
- UserStyleInjectionTime injectionTime = InjectInExistingDocuments);
-
- void removeAllUserContent();
+ void injectStyleSheet(const String& source, const Vector<String>& whitelist, StyleInjectionTarget);
+ void removeInjectedStyleSheets();
- const UserStyleSheetVector& userStyleSheets() const { return m_userStyleSheets; }
+ const InjectedStyleSheetVector& injectedStyleSheets() const { return m_injectedStyleSheets; }
private:
PageGroup();
@@ -69,7 +70,7 @@ namespace WebCore {
void invalidatedInjectedStyleSheetCacheInAllFrames();
HashSet<Page*> m_pages;
- UserStyleSheetVector m_userStyleSheets;
+ InjectedStyleSheetVector m_injectedStyleSheets;
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/page/PageGroupLoadDeferrer.cpp b/chromium/third_party/WebKit/Source/core/page/PageGroupLoadDeferrer.cpp
index fec74c1d9de..be7e7c24508 100644
--- a/chromium/third_party/WebKit/Source/core/page/PageGroupLoadDeferrer.cpp
+++ b/chromium/third_party/WebKit/Source/core/page/PageGroupLoadDeferrer.cpp
@@ -23,7 +23,7 @@
#include "core/dom/Document.h"
#include "core/loader/FrameLoader.h"
-#include "core/page/Frame.h"
+#include "core/frame/Frame.h"
#include "core/page/Page.h"
#include "core/page/PageGroup.h"
#include "wtf/HashSet.h"
@@ -45,12 +45,12 @@ PageGroupLoadDeferrer::PageGroupLoadDeferrer(Page* page, bool deferSelf)
// Ensure that we notify the client if the initial empty document is accessed before showing anything
// modal, to prevent spoofs while the modal window or sheet is visible.
- otherPage->mainFrame()->loader()->notifyIfInitialDocumentAccessed();
+ otherPage->mainFrame()->loader().notifyIfInitialDocumentAccessed();
// This code is not logically part of load deferring, but we do not want JS code executed beneath modal
// windows or sheets, which is exactly when PageGroupLoadDeferrer is used.
- for (Frame* frame = otherPage->mainFrame(); frame; frame = frame->tree()->traverseNext())
- frame->document()->suspendScheduledTasks(ActiveDOMObject::WillDeferLoading);
+ for (Frame* frame = otherPage->mainFrame(); frame; frame = frame->tree().traverseNext())
+ frame->document()->suspendScheduledTasks();
}
}
}
@@ -67,7 +67,7 @@ PageGroupLoadDeferrer::~PageGroupLoadDeferrer()
if (Page* page = m_deferredFrames[i]->page()) {
page->setDefersLoading(false);
- for (Frame* frame = page->mainFrame(); frame; frame = frame->tree()->traverseNext())
+ for (Frame* frame = page->mainFrame(); frame; frame = frame->tree().traverseNext())
frame->document()->resumeScheduledTasks();
}
}
diff --git a/chromium/third_party/WebKit/Source/core/page/PageLifecycleNotifier.cpp b/chromium/third_party/WebKit/Source/core/page/PageLifecycleNotifier.cpp
index e786ba0a66c..d57333426a0 100644
--- a/chromium/third_party/WebKit/Source/core/page/PageLifecycleNotifier.cpp
+++ b/chromium/third_party/WebKit/Source/core/page/PageLifecycleNotifier.cpp
@@ -29,29 +29,29 @@
namespace WebCore {
-PageLifecycleNotifier::PageLifecycleNotifier(LifecycleContext* context)
- : LifecycleNotifier(context)
+PageLifecycleNotifier::PageLifecycleNotifier(Page* context)
+ : LifecycleNotifier<Page>(context)
{
}
-void PageLifecycleNotifier::addObserver(LifecycleObserver* observer)
+void PageLifecycleNotifier::addObserver(PageLifecycleNotifier::Observer* observer)
{
- if (observer->observerType() == LifecycleObserver::PageLifecycleObserverType) {
+ if (observer->observerType() == Observer::PageLifecycleObserverType) {
RELEASE_ASSERT(m_iterating != IteratingOverPageObservers);
m_pageObservers.add(static_cast<PageLifecycleObserver*>(observer));
}
- LifecycleNotifier::addObserver(observer);
+ LifecycleNotifier<Page>::addObserver(observer);
}
-void PageLifecycleNotifier::removeObserver(LifecycleObserver* observer)
+void PageLifecycleNotifier::removeObserver(PageLifecycleNotifier::Observer* observer)
{
- if (observer->observerType() == LifecycleObserver::PageLifecycleObserverType) {
+ if (observer->observerType() == Observer::PageLifecycleObserverType) {
RELEASE_ASSERT(m_iterating != IteratingOverPageObservers);
m_pageObservers.remove(static_cast<PageLifecycleObserver*>(observer));
}
- LifecycleNotifier::removeObserver(observer);
+ LifecycleNotifier<Page>::removeObserver(observer);
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/page/PageLifecycleNotifier.h b/chromium/third_party/WebKit/Source/core/page/PageLifecycleNotifier.h
index 504cd682584..5514101ac70 100644
--- a/chromium/third_party/WebKit/Source/core/page/PageLifecycleNotifier.h
+++ b/chromium/third_party/WebKit/Source/core/page/PageLifecycleNotifier.h
@@ -27,7 +27,7 @@
#define PageLifecycleNotifier_h
#include "core/page/PageLifecycleObserver.h"
-#include "core/platform/LifecycleNotifier.h"
+#include "platform/LifecycleNotifier.h"
#include "wtf/PassOwnPtr.h"
#include "wtf/TemporaryChange.h"
@@ -36,24 +36,24 @@ namespace WebCore {
class Page;
class Frame;
-class PageLifecycleNotifier : public LifecycleNotifier {
+class PageLifecycleNotifier : public LifecycleNotifier<Page> {
public:
- static PassOwnPtr<PageLifecycleNotifier> create(LifecycleContext*);
+ static PassOwnPtr<PageLifecycleNotifier> create(Page*);
void notifyPageVisibilityChanged();
void notifyDidCommitLoad(Frame*);
- virtual void addObserver(LifecycleObserver*) OVERRIDE;
- virtual void removeObserver(LifecycleObserver*) OVERRIDE;
+ virtual void addObserver(Observer*) OVERRIDE;
+ virtual void removeObserver(Observer*) OVERRIDE;
private:
- explicit PageLifecycleNotifier(LifecycleContext*);
+ explicit PageLifecycleNotifier(Page*);
typedef HashSet<PageLifecycleObserver*> PageObserverSet;
PageObserverSet m_pageObservers;
};
-inline PassOwnPtr<PageLifecycleNotifier> PageLifecycleNotifier::create(LifecycleContext* context)
+inline PassOwnPtr<PageLifecycleNotifier> PageLifecycleNotifier::create(Page* context)
{
return adoptPtr(new PageLifecycleNotifier(context));
}
diff --git a/chromium/third_party/WebKit/Source/core/page/PageLifecycleObserver.cpp b/chromium/third_party/WebKit/Source/core/page/PageLifecycleObserver.cpp
index 175aca63daa..ce6c81966ed 100644
--- a/chromium/third_party/WebKit/Source/core/page/PageLifecycleObserver.cpp
+++ b/chromium/third_party/WebKit/Source/core/page/PageLifecycleObserver.cpp
@@ -31,8 +31,18 @@
namespace WebCore {
+template<> void observerContext(Page* context, LifecycleObserver<Page>* observer)
+{
+ context->wasObservedBy(observer);
+}
+
+template<> void unobserverContext(Page* context, LifecycleObserver<Page>* observer)
+{
+ context->wasUnobservedBy(observer);
+}
+
PageLifecycleObserver::PageLifecycleObserver(Page* page)
- : LifecycleObserver(page, PageLifecycleObserverType)
+ : LifecycleObserver<Page>(page, PageLifecycleObserverType)
{
}
diff --git a/chromium/third_party/WebKit/Source/core/page/PageLifecycleObserver.h b/chromium/third_party/WebKit/Source/core/page/PageLifecycleObserver.h
index 62626958b37..86c0eb0ff20 100644
--- a/chromium/third_party/WebKit/Source/core/page/PageLifecycleObserver.h
+++ b/chromium/third_party/WebKit/Source/core/page/PageLifecycleObserver.h
@@ -27,14 +27,17 @@
#ifndef PageLifecycleObserver_h
#define PageLifecycleObserver_h
-#include "core/platform/LifecycleObserver.h"
+#include "platform/LifecycleObserver.h"
namespace WebCore {
class Frame;
class Page;
-class PageLifecycleObserver : public LifecycleObserver {
+template<> void observerContext(Page*, LifecycleObserver<Page>*);
+template<> void unobserverContext(Page*, LifecycleObserver<Page>*);
+
+class PageLifecycleObserver : public LifecycleObserver<Page> {
public:
explicit PageLifecycleObserver(Page*);
virtual ~PageLifecycleObserver();
diff --git a/chromium/third_party/WebKit/Source/core/page/PagePopupClient.h b/chromium/third_party/WebKit/Source/core/page/PagePopupClient.h
index 0d2ff6fc58e..812e973a5de 100644
--- a/chromium/third_party/WebKit/Source/core/page/PagePopupClient.h
+++ b/chromium/third_party/WebKit/Source/core/page/PagePopupClient.h
@@ -32,7 +32,7 @@
#define PagePopupClient_h
#include "core/loader/DocumentWriter.h"
-#include "core/platform/graphics/IntRect.h"
+#include "platform/geometry/IntRect.h"
#include "wtf/text/CString.h"
#include "wtf/text/WTFString.h"
diff --git a/chromium/third_party/WebKit/Source/core/page/PagePopupController.cpp b/chromium/third_party/WebKit/Source/core/page/PagePopupController.cpp
index 144682fe282..961d96eee2d 100644
--- a/chromium/third_party/WebKit/Source/core/page/PagePopupController.cpp
+++ b/chromium/third_party/WebKit/Source/core/page/PagePopupController.cpp
@@ -32,8 +32,8 @@
#include "core/page/PagePopupController.h"
#include "core/page/PagePopupClient.h"
-#include "core/platform/HistogramSupport.h"
-#include "core/platform/text/PlatformLocale.h"
+#include "platform/text/PlatformLocale.h"
+#include "public/platform/Platform.h"
namespace WebCore {
@@ -74,7 +74,6 @@ String PagePopupController::localizeNumberString(const String& numberString)
return numberString;
}
-#if ENABLE(CALENDAR_PICKER)
String PagePopupController::formatMonth(int year, int zeroBaseMonth)
{
if (!m_popupClient)
@@ -92,7 +91,6 @@ String PagePopupController::formatShortMonth(int year, int zeroBaseMonth)
date.setMonthsSinceEpoch((year - 1970) * 12.0 + zeroBaseMonth);
return m_popupClient->locale().formatDateTime(date, Locale::FormatTypeShort);
}
-#endif
void PagePopupController::clearPagePopupClient()
{
@@ -101,7 +99,7 @@ void PagePopupController::clearPagePopupClient()
void PagePopupController::histogramEnumeration(const String& name, int sample, int boundaryValue)
{
- HistogramSupport::histogramEnumeration(name.utf8().data(), sample, boundaryValue);
+ blink::Platform::current()->histogramEnumeration(name.utf8().data(), sample, boundaryValue);
}
}
diff --git a/chromium/third_party/WebKit/Source/core/page/PagePopupController.h b/chromium/third_party/WebKit/Source/core/page/PagePopupController.h
index 398fa4edd80..7a4846fb0aa 100644
--- a/chromium/third_party/WebKit/Source/core/page/PagePopupController.h
+++ b/chromium/third_party/WebKit/Source/core/page/PagePopupController.h
@@ -46,10 +46,8 @@ public:
void setValue(const String&);
void closePopup();
String localizeNumberString(const String&);
-#if ENABLE(CALENDAR_PICKER)
String formatMonth(int year, int zeroBaseMonth);
String formatShortMonth(int year, int zeroBaseMonth);
-#endif
void clearPagePopupClient();
void histogramEnumeration(const String& name, int sample, int boundaryValue);
diff --git a/chromium/third_party/WebKit/Source/core/page/PagePopupController.idl b/chromium/third_party/WebKit/Source/core/page/PagePopupController.idl
index 453850dd39f..0a4fbd4f637 100644
--- a/chromium/third_party/WebKit/Source/core/page/PagePopupController.idl
+++ b/chromium/third_party/WebKit/Source/core/page/PagePopupController.idl
@@ -30,13 +30,13 @@
[
NoInterfaceObject,
- EnabledAtRuntime=PagePopup
+ RuntimeEnabled=PagePopup
] interface PagePopupController {
void setValueAndClosePopup(long numberValue, DOMString stringValue);
void setValue(DOMString value);
void closePopup();
DOMString localizeNumberString(DOMString numberString);
- [Conditional=CALENDAR_PICKER] DOMString formatMonth(long year, long zeroBaseMonth);
- [Conditional=CALENDAR_PICKER] DOMString formatShortMonth(long year, long zeroBaseMonth);
+ DOMString formatMonth(long year, long zeroBaseMonth);
+ DOMString formatShortMonth(long year, long zeroBaseMonth);
void histogramEnumeration(DOMString name, long sample, long boundaryValue);
};
diff --git a/chromium/third_party/WebKit/Source/core/page/PageScaleConstraints.h b/chromium/third_party/WebKit/Source/core/page/PageScaleConstraints.h
index 92688aadd2a..dc390e245cf 100644
--- a/chromium/third_party/WebKit/Source/core/page/PageScaleConstraints.h
+++ b/chromium/third_party/WebKit/Source/core/page/PageScaleConstraints.h
@@ -31,7 +31,7 @@
#ifndef PageScaleConstraints_h
#define PageScaleConstraints_h
-#include "core/platform/graphics/FloatSize.h"
+#include "platform/geometry/FloatSize.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/page/PageScaleConstraintsSet.cpp b/chromium/third_party/WebKit/Source/core/page/PageScaleConstraintsSet.cpp
deleted file mode 100644
index 6eacede5ab4..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/PageScaleConstraintsSet.cpp
+++ /dev/null
@@ -1,169 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/page/PageScaleConstraintsSet.h"
-
-#include "wtf/Assertions.h"
-
-namespace WebCore {
-
-static const float defaultMinimumScale = 0.25f;
-static const float defaultMaximumScale = 5.0f;
-
-PageScaleConstraintsSet::PageScaleConstraintsSet()
- : m_lastContentsWidth(0)
- , m_needsReset(false)
- , m_constraintsDirty(false)
-{
- m_finalConstraints = defaultConstraints();
-}
-
-PageScaleConstraints PageScaleConstraintsSet::defaultConstraints() const
-{
- return PageScaleConstraints(-1, defaultMinimumScale, defaultMaximumScale);
-}
-
-void PageScaleConstraintsSet::updatePageDefinedConstraints(const ViewportArguments& arguments, IntSize viewSize)
-{
- m_pageDefinedConstraints = arguments.resolve(viewSize);
-
- m_constraintsDirty = true;
-}
-
-void PageScaleConstraintsSet::setUserAgentConstraints(const PageScaleConstraints& userAgentConstraints)
-{
- m_userAgentConstraints = userAgentConstraints;
- m_constraintsDirty = true;
-}
-
-void PageScaleConstraintsSet::computeFinalConstraints()
-{
- m_finalConstraints = defaultConstraints();
- m_finalConstraints.overrideWith(m_pageDefinedConstraints);
- m_finalConstraints.overrideWith(m_userAgentConstraints);
-
- m_constraintsDirty = false;
-}
-
-void PageScaleConstraintsSet::adjustFinalConstraintsToContentsSize(IntSize viewSize, IntSize contentsSize, int nonOverlayScrollbarWidth)
-{
- m_finalConstraints.fitToContentsWidth(contentsSize.width(), viewSize.width() - nonOverlayScrollbarWidth);
-}
-
-void PageScaleConstraintsSet::setNeedsReset(bool needsReset)
-{
- m_needsReset = needsReset;
- if (needsReset)
- m_constraintsDirty = true;
-}
-
-void PageScaleConstraintsSet::didChangeContentsSize(IntSize contentsSize, float pageScaleFactor)
-{
- // If a large fixed-width element expanded the size of the document
- // late in loading and our initial scale is not constrained, reset the
- // page scale factor to the new minimum scale.
- if (contentsSize.width() > m_lastContentsWidth
- && pageScaleFactor == finalConstraints().minimumScale
- && userAgentConstraints().initialScale == -1 && pageDefinedConstraints().initialScale == -1)
- setNeedsReset(true);
-
- m_constraintsDirty = true;
- m_lastContentsWidth = contentsSize.width();
-}
-
-static float computeDeprecatedTargetDensityDPIFactor(const ViewportArguments& arguments, float deviceScaleFactor)
-{
- if (arguments.deprecatedTargetDensityDPI == ViewportArguments::ValueDeviceDPI)
- return 1.0f / deviceScaleFactor;
-
- float targetDPI = -1.0f;
- if (arguments.deprecatedTargetDensityDPI == ViewportArguments::ValueLowDPI)
- targetDPI = 120.0f;
- else if (arguments.deprecatedTargetDensityDPI == ViewportArguments::ValueMediumDPI)
- targetDPI = 160.0f;
- else if (arguments.deprecatedTargetDensityDPI == ViewportArguments::ValueHighDPI)
- targetDPI = 240.0f;
- else if (arguments.deprecatedTargetDensityDPI != ViewportArguments::ValueAuto)
- targetDPI = arguments.deprecatedTargetDensityDPI;
- return targetDPI > 0 ? 160.0f / targetDPI : 1.0f;
-}
-
-static float getLayoutWidthForNonWideViewport(const FloatSize& deviceSize, float initialScale)
-{
- return initialScale == -1 ? deviceSize.width() : deviceSize.width() / initialScale;
-}
-
-void PageScaleConstraintsSet::adjustForAndroidWebViewQuirks(const ViewportArguments& arguments, IntSize viewSize, int layoutFallbackWidth, float deviceScaleFactor, bool supportTargetDensityDPI, bool wideViewportQuirkEnabled, bool useWideViewport, bool loadWithOverviewMode)
-{
- if (!supportTargetDensityDPI && !wideViewportQuirkEnabled && loadWithOverviewMode)
- return;
-
- float initialScale = m_pageDefinedConstraints.initialScale;
- if (!loadWithOverviewMode) {
- bool resetInitialScale = false;
- if (arguments.zoom == -1) {
- if (arguments.maxWidth.isAuto())
- resetInitialScale = true;
- if (useWideViewport && arguments.maxWidth.isFixed())
- resetInitialScale = true;
- }
- if (resetInitialScale)
- m_pageDefinedConstraints.initialScale = 1.0f;
- }
-
- float adjustedLayoutSizeWidth = m_pageDefinedConstraints.layoutSize.width();
- float targetDensityDPIFactor = 1.0f;
-
- if (supportTargetDensityDPI) {
- targetDensityDPIFactor = computeDeprecatedTargetDensityDPIFactor(arguments, deviceScaleFactor);
- if (m_pageDefinedConstraints.initialScale != -1)
- m_pageDefinedConstraints.initialScale *= targetDensityDPIFactor;
- m_pageDefinedConstraints.minimumScale *= targetDensityDPIFactor;
- m_pageDefinedConstraints.maximumScale *= targetDensityDPIFactor;
- adjustedLayoutSizeWidth /= targetDensityDPIFactor;
- }
-
- if (wideViewportQuirkEnabled) {
- if (useWideViewport && (arguments.maxWidth.isAuto() || arguments.maxWidth.type() == ExtendToZoom) && arguments.zoom != 1.0f)
- adjustedLayoutSizeWidth = layoutFallbackWidth;
- else if (!useWideViewport)
- adjustedLayoutSizeWidth = getLayoutWidthForNonWideViewport(viewSize, initialScale) / targetDensityDPIFactor;
- }
-
- if (adjustedLayoutSizeWidth != m_pageDefinedConstraints.layoutSize.width()) {
- ASSERT(m_pageDefinedConstraints.layoutSize.width() > 0);
- float adjustedLayoutSizeHeight = (adjustedLayoutSizeWidth * m_pageDefinedConstraints.layoutSize.height()) / m_pageDefinedConstraints.layoutSize.width();
- m_pageDefinedConstraints.layoutSize.setWidth(adjustedLayoutSizeWidth);
- m_pageDefinedConstraints.layoutSize.setHeight(adjustedLayoutSizeHeight);
- }
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/page/PageScaleConstraintsSet.h b/chromium/third_party/WebKit/Source/core/page/PageScaleConstraintsSet.h
deleted file mode 100644
index 2e281cb21ca..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/PageScaleConstraintsSet.h
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef PageScaleConstraintsSet_h
-#define PageScaleConstraintsSet_h
-
-#include "PageScaleConstraints.h"
-#include "core/dom/ViewportArguments.h"
-#include "core/platform/graphics/IntSize.h"
-
-namespace WebCore {
-
-// This class harmonizes the viewport (particularly page scale) constraints from
-// the meta viewport tag and other sources.
-class PageScaleConstraintsSet {
-public:
- PageScaleConstraintsSet();
-
- PageScaleConstraints defaultConstraints() const;
-
- // Settings defined in the website's viewport tag, if viewport tag support
- // is enabled.
- const PageScaleConstraints& pageDefinedConstraints() const { return m_pageDefinedConstraints; }
- void updatePageDefinedConstraints(const ViewportArguments&, IntSize viewSize);
- void adjustForAndroidWebViewQuirks(const ViewportArguments&, IntSize viewSize, int layoutFallbackWidth, float deviceScaleFactor, bool supportTargetDensityDPI, bool wideViewportQuirkEnabled, bool useWideViewport, bool loadWithOverviewMode);
-
- // Constraints may also be set from Chromium -- this overrides any
- // page-defined values.
- const PageScaleConstraints& userAgentConstraints() const { return m_userAgentConstraints; }
- void setUserAgentConstraints(const PageScaleConstraints&);
-
- // Actual computed values, taking into account the above plus the current
- // viewport size and document width.
- const PageScaleConstraints& finalConstraints() const { return m_finalConstraints; }
- void computeFinalConstraints();
- void adjustFinalConstraintsToContentsSize(IntSize viewSize, IntSize contentsSize, int nonOverlayScrollbarWidth);
-
- void didChangeContentsSize(IntSize contentsSize, float pageScaleFactor);
-
- // This should be set to true on each page load to note that the page scale
- // factor needs to be reset to its initial value.
- void setNeedsReset(bool);
- bool needsReset() const { return m_needsReset; }
-
- // This is set when one of the inputs to finalConstraints changes.
- bool constraintsDirty() const { return m_constraintsDirty; }
-
-private:
- PageScaleConstraints m_pageDefinedConstraints;
- PageScaleConstraints m_userAgentConstraints;
- PageScaleConstraints m_finalConstraints;
-
- int m_lastContentsWidth;
-
- bool m_needsReset;
- bool m_constraintsDirty;
-};
-
-} // namespace WebCore
-
-#endif // PageScaleConstraintsSet_h
diff --git a/chromium/third_party/WebKit/Source/core/page/PageSerializer.cpp b/chromium/third_party/WebKit/Source/core/page/PageSerializer.cpp
index e22b0d444c5..d41f8719763 100644
--- a/chromium/third_party/WebKit/Source/core/page/PageSerializer.cpp
+++ b/chromium/third_party/WebKit/Source/core/page/PageSerializer.cpp
@@ -54,13 +54,13 @@
#include "core/html/HTMLLinkElement.h"
#include "core/html/HTMLStyleElement.h"
#include "core/html/parser/HTMLMetaCharsetParser.h"
-#include "core/page/Frame.h"
+#include "core/frame/Frame.h"
#include "core/page/Page.h"
-#include "core/platform/SerializedResource.h"
-#include "core/platform/graphics/Image.h"
#include "core/rendering/RenderImage.h"
#include "core/rendering/style/StyleFetchedImage.h"
#include "core/rendering/style/StyleImage.h"
+#include "platform/SerializedResource.h"
+#include "platform/graphics/Image.h"
#include "wtf/text/CString.h"
#include "wtf/text/StringBuilder.h"
#include "wtf/text/TextEncoding.h"
@@ -248,7 +248,7 @@ void PageSerializer::serializeFrame(Frame* frame)
}
}
- for (Frame* childFrame = frame->tree()->firstChild(); childFrame; childFrame = childFrame->tree()->nextSibling())
+ for (Frame* childFrame = frame->tree().firstChild(); childFrame; childFrame = childFrame->tree().nextSibling())
serializeFrame(childFrame);
}
@@ -297,7 +297,7 @@ bool PageSerializer::shouldAddURL(const KURL& url)
void PageSerializer::addToResources(Resource* resource, PassRefPtr<SharedBuffer> data, const KURL& url)
{
if (!data) {
- LOG_ERROR("No data for resource %s", url.string().utf8().data());
+ WTF_LOG_ERROR("No data for resource %s", url.string().utf8().data());
return;
}
diff --git a/chromium/third_party/WebKit/Source/core/page/PageSerializer.h b/chromium/third_party/WebKit/Source/core/page/PageSerializer.h
index 93a4dc10677..745af7e72d2 100644
--- a/chromium/third_party/WebKit/Source/core/page/PageSerializer.h
+++ b/chromium/third_party/WebKit/Source/core/page/PageSerializer.h
@@ -31,8 +31,8 @@
#ifndef PageSerializer_h
#define PageSerializer_h
-#include "weborigin/KURL.h"
-#include "weborigin/KURLHash.h"
+#include "platform/weborigin/KURL.h"
+#include "platform/weborigin/KURLHash.h"
#include "wtf/HashMap.h"
#include "wtf/ListHashSet.h"
#include "wtf/Vector.h"
diff --git a/chromium/third_party/WebKit/Source/core/page/PageVisibilityState.cpp b/chromium/third_party/WebKit/Source/core/page/PageVisibilityState.cpp
index 630b0dbe05d..4b015df5f5c 100644
--- a/chromium/third_party/WebKit/Source/core/page/PageVisibilityState.cpp
+++ b/chromium/third_party/WebKit/Source/core/page/PageVisibilityState.cpp
@@ -38,7 +38,6 @@ String pageVisibilityStateString(PageVisibilityState state)
DEFINE_STATIC_LOCAL(const String, visible, ("visible"));
DEFINE_STATIC_LOCAL(const String, hidden, ("hidden"));
DEFINE_STATIC_LOCAL(const String, prerender, ("prerender"));
- DEFINE_STATIC_LOCAL(const String, preview, ("preview"));
switch (state) {
case PageVisibilityStateVisible:
@@ -47,8 +46,6 @@ String pageVisibilityStateString(PageVisibilityState state)
return hidden;
case PageVisibilityStatePrerender:
return prerender;
- case PageVisibilityStatePreview:
- return preview;
}
ASSERT_NOT_REACHED();
diff --git a/chromium/third_party/WebKit/Source/core/page/PageVisibilityState.h b/chromium/third_party/WebKit/Source/core/page/PageVisibilityState.h
index 229b22f1fb7..cd09a2a4483 100644
--- a/chromium/third_party/WebKit/Source/core/page/PageVisibilityState.h
+++ b/chromium/third_party/WebKit/Source/core/page/PageVisibilityState.h
@@ -41,7 +41,6 @@ enum PageVisibilityState {
PageVisibilityStateVisible,
PageVisibilityStateHidden,
PageVisibilityStatePrerender,
- PageVisibilityStatePreview
};
String pageVisibilityStateString(PageVisibilityState);
diff --git a/chromium/third_party/WebKit/Source/core/page/Performance.cpp b/chromium/third_party/WebKit/Source/core/page/Performance.cpp
deleted file mode 100644
index 483bb7336ff..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/Performance.cpp
+++ /dev/null
@@ -1,294 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- * Copyright (C) 2012 Intel Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/page/Performance.h"
-
-#include "core/dom/Document.h"
-#include "core/loader/DocumentLoader.h"
-#include "core/page/MemoryInfo.h"
-#include "core/page/PerformanceEntry.h"
-#include "core/page/PerformanceNavigation.h"
-#include "core/page/PerformanceResourceTiming.h"
-#include "core/page/PerformanceTiming.h"
-#include "core/page/PerformanceUserTiming.h"
-#include "core/page/ResourceTimingInfo.h"
-#include "weborigin/SecurityOrigin.h"
-#include "wtf/CurrentTime.h"
-
-#include "core/page/Frame.h"
-
-namespace WebCore {
-
-static const size_t defaultResourceTimingBufferSize = 150;
-
-Performance::Performance(Frame* frame)
- : DOMWindowProperty(frame)
- , m_resourceTimingBufferSize(defaultResourceTimingBufferSize)
- , m_userTiming(0)
- , m_referenceTime(frame->document()->loader()->timing()->referenceMonotonicTime())
-{
- ASSERT(m_referenceTime);
- ScriptWrappable::init(this);
-}
-
-Performance::~Performance()
-{
-}
-
-const AtomicString& Performance::interfaceName() const
-{
- return eventNames().interfaceForPerformance;
-}
-
-ScriptExecutionContext* Performance::scriptExecutionContext() const
-{
- if (!frame())
- return 0;
- return frame()->document();
-}
-
-PassRefPtr<MemoryInfo> Performance::memory() const
-{
- return MemoryInfo::create(m_frame);
-}
-
-PerformanceNavigation* Performance::navigation() const
-{
- if (!m_navigation)
- m_navigation = PerformanceNavigation::create(m_frame);
-
- return m_navigation.get();
-}
-
-PerformanceTiming* Performance::timing() const
-{
- if (!m_timing)
- m_timing = PerformanceTiming::create(m_frame);
-
- return m_timing.get();
-}
-
-Vector<RefPtr<PerformanceEntry> > Performance::getEntries() const
-{
- Vector<RefPtr<PerformanceEntry> > entries;
-
- entries.append(m_resourceTimingBuffer);
-
- if (m_userTiming) {
- entries.append(m_userTiming->getMarks());
- entries.append(m_userTiming->getMeasures());
- }
-
- std::sort(entries.begin(), entries.end(), PerformanceEntry::startTimeCompareLessThan);
- return entries;
-}
-
-Vector<RefPtr<PerformanceEntry> > Performance::getEntriesByType(const String& entryType)
-{
- Vector<RefPtr<PerformanceEntry> > entries;
-
- if (equalIgnoringCase(entryType, "resource"))
- for (Vector<RefPtr<PerformanceEntry> >::const_iterator resource = m_resourceTimingBuffer.begin(); resource != m_resourceTimingBuffer.end(); ++resource)
- entries.append(*resource);
-
- if (m_userTiming) {
- if (equalIgnoringCase(entryType, "mark"))
- entries.append(m_userTiming->getMarks());
- else if (equalIgnoringCase(entryType, "measure"))
- entries.append(m_userTiming->getMeasures());
- }
-
- std::sort(entries.begin(), entries.end(), PerformanceEntry::startTimeCompareLessThan);
- return entries;
-}
-
-Vector<RefPtr<PerformanceEntry> > Performance::getEntriesByName(const String& name, const String& entryType)
-{
- Vector<RefPtr<PerformanceEntry> > entries;
-
- if (entryType.isNull() || equalIgnoringCase(entryType, "resource"))
- for (Vector<RefPtr<PerformanceEntry> >::const_iterator resource = m_resourceTimingBuffer.begin(); resource != m_resourceTimingBuffer.end(); ++resource)
- if ((*resource)->name() == name)
- entries.append(*resource);
-
- if (m_userTiming) {
- if (entryType.isNull() || equalIgnoringCase(entryType, "mark"))
- entries.append(m_userTiming->getMarks(name));
- if (entryType.isNull() || equalIgnoringCase(entryType, "measure"))
- entries.append(m_userTiming->getMeasures(name));
- }
-
- std::sort(entries.begin(), entries.end(), PerformanceEntry::startTimeCompareLessThan);
- return entries;
-}
-
-void Performance::webkitClearResourceTimings()
-{
- m_resourceTimingBuffer.clear();
-}
-
-void Performance::webkitSetResourceTimingBufferSize(unsigned size)
-{
- m_resourceTimingBufferSize = size;
- if (isResourceTimingBufferFull())
- dispatchEvent(Event::create(eventNames().webkitresourcetimingbufferfullEvent));
-}
-
-static bool passesTimingAllowCheck(const ResourceResponse& response, Document* requestingDocument)
-{
- AtomicallyInitializedStatic(AtomicString&, timingAllowOrigin = *new AtomicString("timing-allow-origin"));
-
- RefPtr<SecurityOrigin> resourceOrigin = SecurityOrigin::create(response.url());
- if (resourceOrigin->isSameSchemeHostPort(requestingDocument->securityOrigin()))
- return true;
-
- const String& timingAllowOriginString = response.httpHeaderField(timingAllowOrigin);
- if (timingAllowOriginString.isEmpty() || equalIgnoringCase(timingAllowOriginString, "null"))
- return false;
-
- if (timingAllowOriginString == "*")
- return true;
-
- const String& securityOrigin = requestingDocument->securityOrigin()->toString();
- Vector<String> timingAllowOrigins;
- timingAllowOriginString.split(" ", timingAllowOrigins);
- for (size_t i = 0; i < timingAllowOrigins.size(); ++i) {
- if (timingAllowOrigins[i] == securityOrigin)
- return true;
- }
-
- return false;
-}
-
-static bool allowsTimingRedirect(const Vector<ResourceResponse>& redirectChain, const ResourceResponse& finalResponse, Document* initiatorDocument)
-{
- if (!passesTimingAllowCheck(finalResponse, initiatorDocument))
- return false;
-
- for (size_t i = 0; i < redirectChain.size(); i++) {
- if (!passesTimingAllowCheck(redirectChain[i], initiatorDocument))
- return false;
- }
-
- return true;
-}
-
-void Performance::addResourceTiming(const ResourceTimingInfo& info, Document* initiatorDocument)
-{
- if (isResourceTimingBufferFull())
- return;
-
- const ResourceResponse& finalResponse = info.finalResponse();
- bool allowTimingDetails = passesTimingAllowCheck(finalResponse, initiatorDocument);
- double startTime = info.initialTime();
-
- if (info.redirectChain().isEmpty()) {
- RefPtr<PerformanceEntry> entry = PerformanceResourceTiming::create(info, initiatorDocument, startTime, allowTimingDetails);
- addResourceTimingBuffer(entry);
- return;
- }
-
- const Vector<ResourceResponse>& redirectChain = info.redirectChain();
- bool allowRedirectDetails = allowsTimingRedirect(redirectChain, finalResponse, initiatorDocument);
-
- if (!allowRedirectDetails) {
- ResourceLoadTiming* finalTiming = finalResponse.resourceLoadTiming();
- ASSERT(finalTiming);
- if (finalTiming)
- startTime = finalTiming->requestTime;
- }
-
- ResourceLoadTiming* lastRedirectTiming = redirectChain.last().resourceLoadTiming();
- ASSERT(lastRedirectTiming);
- double lastRedirectEndTime = lastRedirectTiming->receiveHeadersEnd;
-
- RefPtr<PerformanceEntry> entry = PerformanceResourceTiming::create(info, initiatorDocument, startTime, lastRedirectEndTime, allowTimingDetails, allowRedirectDetails);
- addResourceTimingBuffer(entry);
-}
-
-void Performance::addResourceTimingBuffer(PassRefPtr<PerformanceEntry> entry)
-{
- m_resourceTimingBuffer.append(entry);
-
- if (isResourceTimingBufferFull())
- dispatchEvent(Event::create(eventNames().webkitresourcetimingbufferfullEvent));
-}
-
-bool Performance::isResourceTimingBufferFull()
-{
- return m_resourceTimingBuffer.size() >= m_resourceTimingBufferSize;
-}
-
-EventTargetData* Performance::eventTargetData()
-{
- return &m_eventTargetData;
-}
-
-EventTargetData* Performance::ensureEventTargetData()
-{
- return &m_eventTargetData;
-}
-
-void Performance::mark(const String& markName, ExceptionState& es)
-{
- if (!m_userTiming)
- m_userTiming = UserTiming::create(this);
- m_userTiming->mark(markName, es);
-}
-
-void Performance::clearMarks(const String& markName)
-{
- if (!m_userTiming)
- m_userTiming = UserTiming::create(this);
- m_userTiming->clearMarks(markName);
-}
-
-void Performance::measure(const String& measureName, const String& startMark, const String& endMark, ExceptionState& es)
-{
- if (!m_userTiming)
- m_userTiming = UserTiming::create(this);
- m_userTiming->measure(measureName, startMark, endMark, es);
-}
-
-void Performance::clearMeasures(const String& measureName)
-{
- if (!m_userTiming)
- m_userTiming = UserTiming::create(this);
- m_userTiming->clearMeasures(measureName);
-}
-
-double Performance::now() const
-{
- return 1000.0 * (monotonicallyIncreasingTime() - m_referenceTime);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/page/Performance.h b/chromium/third_party/WebKit/Source/core/page/Performance.h
deleted file mode 100644
index b695b5dabe5..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/Performance.h
+++ /dev/null
@@ -1,113 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- * Copyright (C) 2012 Intel Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef Performance_h
-#define Performance_h
-
-#include "bindings/v8/ScriptWrappable.h"
-#include "core/dom/EventTarget.h"
-#include "core/page/DOMWindowProperty.h"
-#include "core/page/MemoryInfo.h"
-#include "core/page/PerformanceEntry.h"
-#include "core/page/PerformanceNavigation.h"
-#include "core/page/PerformanceTiming.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/RefPtr.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class Document;
-class ExceptionState;
-class ResourceRequest;
-class ResourceResponse;
-class ResourceTimingInfo;
-class UserTiming;
-
-class Performance : public ScriptWrappable, public RefCounted<Performance>, public DOMWindowProperty, public EventTarget {
-public:
- static PassRefPtr<Performance> create(Frame* frame) { return adoptRef(new Performance(frame)); }
- ~Performance();
-
- virtual const AtomicString& interfaceName() const;
- virtual ScriptExecutionContext* scriptExecutionContext() const;
-
- PassRefPtr<MemoryInfo> memory() const;
- PerformanceNavigation* navigation() const;
- PerformanceTiming* timing() const;
- double now() const;
-
- Vector<RefPtr<PerformanceEntry> > getEntries() const;
- Vector<RefPtr<PerformanceEntry> > getEntriesByType(const String& entryType);
- Vector<RefPtr<PerformanceEntry> > getEntriesByName(const String& name, const String& entryType);
-
- void webkitClearResourceTimings();
- void webkitSetResourceTimingBufferSize(unsigned int);
-
- DEFINE_ATTRIBUTE_EVENT_LISTENER(webkitresourcetimingbufferfull);
-
- void addResourceTiming(const ResourceTimingInfo&, Document*);
-
- using RefCounted<Performance>::ref;
- using RefCounted<Performance>::deref;
-
- void mark(const String& markName, ExceptionState&);
- void clearMarks(const String& markName);
-
- void measure(const String& measureName, const String& startMark, const String& endMark, ExceptionState&);
- void clearMeasures(const String& measureName);
-
-private:
- explicit Performance(Frame*);
-
- virtual void refEventTarget() { ref(); }
- virtual void derefEventTarget() { deref(); }
- virtual EventTargetData* eventTargetData();
- virtual EventTargetData* ensureEventTargetData();
- bool isResourceTimingBufferFull();
- void addResourceTimingBuffer(PassRefPtr<PerformanceEntry>);
-
- EventTargetData m_eventTargetData;
-
- mutable RefPtr<PerformanceNavigation> m_navigation;
- mutable RefPtr<PerformanceTiming> m_timing;
-
- Vector<RefPtr<PerformanceEntry> > m_resourceTimingBuffer;
- unsigned m_resourceTimingBufferSize;
- double m_referenceTime;
-
- RefPtr<UserTiming> m_userTiming;
-};
-
-}
-
-#endif // Performance_h
diff --git a/chromium/third_party/WebKit/Source/core/page/Performance.idl b/chromium/third_party/WebKit/Source/core/page/Performance.idl
deleted file mode 100644
index 8dd3ea834b9..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/Performance.idl
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- * Copyright (C) 2012 Intel Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-// See: http://dev.w3.org/2006/webapi/WebTiming/
-interface Performance : EventTarget {
- readonly attribute PerformanceNavigation navigation;
- readonly attribute PerformanceTiming timing;
- readonly attribute MemoryInfo memory;
-
- [MeasureAs=UnprefixedPerformanceTimeline] sequence<PerformanceEntry> getEntries();
- [MeasureAs=UnprefixedPerformanceTimeline] sequence<PerformanceEntry> getEntriesByType(DOMString entryType);
- [MeasureAs=UnprefixedPerformanceTimeline] sequence<PerformanceEntry> getEntriesByName(DOMString name, [Default=NullString] optional DOMString entryType);
- [DeprecateAs=PrefixedPerformanceTimeline,ImplementedAs=getEntries] sequence<PerformanceEntry> webkitGetEntries();
- [DeprecateAs=PrefixedPerformanceTimeline,ImplementedAs=getEntriesByType] sequence<PerformanceEntry> webkitGetEntriesByType(DOMString entryType);
- [DeprecateAs=PrefixedPerformanceTimeline,ImplementedAs=getEntriesByName] sequence<PerformanceEntry> webkitGetEntriesByName(DOMString name, [Default=NullString] optional DOMString entryType);
-
- void webkitClearResourceTimings();
- void webkitSetResourceTimingBufferSize(unsigned long maxSize);
-
- attribute EventHandler onwebkitresourcetimingbufferfull;
-
- // See http://www.w3.org/TR/2012/CR-user-timing-20120726/
- [RaisesException,MeasureAs=UnprefixedUserTiming] void mark(DOMString markName);
- [MeasureAs=UnprefixedUserTiming] void clearMarks([Default=NullString] optional DOMString markName);
-
- [RaisesException,MeasureAs=UnprefixedUserTiming] void measure(DOMString measureName, [Default=NullString] optional DOMString startMark, [Default=NullString] optional DOMString endMark);
- [MeasureAs=UnprefixedUserTiming] void clearMeasures([Default=NullString] optional DOMString measureName);
-
- [RaisesException,DeprecateAs=PrefixedUserTiming,ImplementedAs=mark] void webkitMark(DOMString markName);
- [DeprecateAs=PrefixedUserTiming,ImplementedAs=clearMarks] void webkitClearMarks([Default=NullString] optional DOMString markName);
-
- [RaisesException,DeprecateAs=PrefixedUserTiming,ImplementedAs=measure] void webkitMeasure(DOMString measureName, [Default=NullString] optional DOMString startMark, [Default=NullString] optional DOMString endMark);
- [DeprecateAs=PrefixedUserTiming,ImplementedAs=clearMeasures] void webkitClearMeasures([Default=NullString] optional DOMString measureName);
-
- // See http://www.w3.org/TR/hr-time/ for details.
- double now();
-};
-
diff --git a/chromium/third_party/WebKit/Source/core/page/PerformanceEntry.cpp b/chromium/third_party/WebKit/Source/core/page/PerformanceEntry.cpp
deleted file mode 100644
index ac69608c870..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/PerformanceEntry.cpp
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/page/PerformanceEntry.h"
-
-namespace WebCore {
-
-PerformanceEntry::PerformanceEntry(const String& name, const String& entryType, double startTime, double finishTime)
- : m_name(name)
- , m_entryType(entryType)
- , m_startTime(startTime)
- , m_duration(finishTime - startTime)
-{
- ScriptWrappable::init(this);
-}
-
-PerformanceEntry::~PerformanceEntry()
-{
-}
-
-String PerformanceEntry::name() const
-{
- return m_name;
-}
-
-String PerformanceEntry::entryType() const
-{
- return m_entryType;
-}
-
-double PerformanceEntry::startTime() const
-{
- return m_startTime;
-}
-
-double PerformanceEntry::duration() const
-{
- return m_duration;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/page/PerformanceEntry.idl b/chromium/third_party/WebKit/Source/core/page/PerformanceEntry.idl
deleted file mode 100644
index 6199ccecdbc..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/PerformanceEntry.idl
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-// See: https://dvcs.w3.org/hg/webperf/raw-file/tip/specs/PerformanceTimeline/Overview.html
-[
- CustomToV8
-] interface PerformanceEntry {
- readonly attribute DOMString name;
- readonly attribute DOMString entryType;
- readonly attribute double startTime;
- readonly attribute double duration;
-};
diff --git a/chromium/third_party/WebKit/Source/core/page/PerformanceMark.h b/chromium/third_party/WebKit/Source/core/page/PerformanceMark.h
deleted file mode 100644
index 4e66458112b..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/PerformanceMark.h
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Copyright (C) 2012 Intel Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef PerformanceMark_h
-#define PerformanceMark_h
-
-#include "core/page/PerformanceEntry.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class PerformanceMark : public PerformanceEntry {
-public:
- static PassRefPtr<PerformanceMark> create(const String& name, double startTime) { return adoptRef(new PerformanceMark(name, startTime)); }
-
- virtual bool isMark() { return true; }
-
-private:
- PerformanceMark(const String& name, double startTime) : PerformanceEntry(name, "mark", startTime, startTime)
- {
- ScriptWrappable::init(this);
- }
-
- ~PerformanceMark() { }
-};
-
-}
-
-#endif // !defined(PerformanceMark_h)
diff --git a/chromium/third_party/WebKit/Source/core/page/PerformanceMeasure.h b/chromium/third_party/WebKit/Source/core/page/PerformanceMeasure.h
deleted file mode 100644
index 9708d338f5f..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/PerformanceMeasure.h
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Copyright (C) 2012 Intel Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef PerformanceMeasure_h
-#define PerformanceMeasure_h
-
-#include "core/page/PerformanceEntry.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class PerformanceMeasure : public PerformanceEntry {
-public:
- static PassRefPtr<PerformanceMeasure> create(const String& name, double startTime, double endTime) { return adoptRef(new PerformanceMeasure(name, startTime, endTime)); }
-
- virtual bool isMeasure() { return true; }
-
-private:
- PerformanceMeasure(const String& name, double startTime, double endTime) : PerformanceEntry(name, "measure", startTime, endTime)
- {
- ScriptWrappable::init(this);
- }
- ~PerformanceMeasure() { }
-};
-
-}
-
-#endif // !defined(PerformanceMeasure_h)
diff --git a/chromium/third_party/WebKit/Source/core/page/PerformanceNavigation.cpp b/chromium/third_party/WebKit/Source/core/page/PerformanceNavigation.cpp
deleted file mode 100644
index 9e3a031e2de..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/PerformanceNavigation.cpp
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/page/PerformanceNavigation.h"
-
-#include "core/loader/DocumentLoader.h"
-#include "core/loader/FrameLoaderTypes.h"
-#include "core/page/Frame.h"
-
-namespace WebCore {
-
-PerformanceNavigation::PerformanceNavigation(Frame* frame)
- : DOMWindowProperty(frame)
-{
- ScriptWrappable::init(this);
-}
-
-unsigned short PerformanceNavigation::type() const
-{
- if (!m_frame)
- return TYPE_NAVIGATE;
-
- DocumentLoader* documentLoader = m_frame->loader()->documentLoader();
- if (!documentLoader)
- return TYPE_NAVIGATE;
-
- WebCore::NavigationType navigationType = documentLoader->triggeringAction().type();
- switch (navigationType) {
- case NavigationTypeReload:
- return TYPE_RELOAD;
- case NavigationTypeBackForward:
- return TYPE_BACK_FORWARD;
- default:
- return TYPE_NAVIGATE;
- }
-}
-
-unsigned short PerformanceNavigation::redirectCount() const
-{
- if (!m_frame)
- return 0;
-
- DocumentLoader* loader = m_frame->loader()->documentLoader();
- if (!loader)
- return 0;
-
- DocumentLoadTiming* timing = loader->timing();
- if (timing->hasCrossOriginRedirect())
- return 0;
-
- return timing->redirectCount();
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/page/PerformanceNavigation.h b/chromium/third_party/WebKit/Source/core/page/PerformanceNavigation.h
deleted file mode 100644
index 1fab79822ff..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/PerformanceNavigation.h
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef PerformanceNavigation_h
-#define PerformanceNavigation_h
-
-#include "bindings/v8/ScriptWrappable.h"
-#include "core/page/DOMWindowProperty.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-
-namespace WebCore {
-
-class Frame;
-
-class PerformanceNavigation : public RefCounted<PerformanceNavigation>, public ScriptWrappable, public DOMWindowProperty {
-public:
- static PassRefPtr<PerformanceNavigation> create(Frame* frame) { return adoptRef(new PerformanceNavigation(frame)); }
-
- enum PerformanceNavigationType {
- TYPE_NAVIGATE,
- TYPE_RELOAD,
- TYPE_BACK_FORWARD,
- TYPE_RESERVED = 255
- };
-
- unsigned short type() const;
- unsigned short redirectCount() const;
-
-private:
- explicit PerformanceNavigation(Frame*);
-};
-
-}
-
-#endif // !defined(PerformanceNavigation_h)
diff --git a/chromium/third_party/WebKit/Source/core/page/PerformanceResourceTiming.cpp b/chromium/third_party/WebKit/Source/core/page/PerformanceResourceTiming.cpp
deleted file mode 100644
index 4f1f7a5a14f..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/PerformanceResourceTiming.cpp
+++ /dev/null
@@ -1,194 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- * Copyright (C) 2012 Intel Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/page/PerformanceResourceTiming.h"
-
-#include "core/dom/Document.h"
-#include "core/loader/DocumentLoadTiming.h"
-#include "core/loader/DocumentLoader.h"
-#include "core/page/ResourceTimingInfo.h"
-#include "core/platform/network/ResourceRequest.h"
-#include "core/platform/network/ResourceResponse.h"
-
-namespace WebCore {
-
-static double monotonicTimeToDocumentMilliseconds(Document* document, double seconds)
-{
- ASSERT(seconds >= 0.0);
- return document->loader()->timing()->monotonicTimeToZeroBasedDocumentTime(seconds) * 1000.0;
-}
-
-PerformanceResourceTiming::PerformanceResourceTiming(const ResourceTimingInfo& info, Document* requestingDocument, double startTime, double lastRedirectEndTime, bool allowTimingDetails, bool allowRedirectDetails)
- : PerformanceEntry(info.initialRequest().url().string(), "resource", monotonicTimeToDocumentMilliseconds(requestingDocument, startTime), monotonicTimeToDocumentMilliseconds(requestingDocument, info.loadFinishTime()))
- , m_initiatorType(info.initiatorType())
- , m_timing(info.finalResponse().resourceLoadTiming())
- , m_lastRedirectEndTime(lastRedirectEndTime)
- , m_finishTime(info.loadFinishTime())
- , m_didReuseConnection(info.finalResponse().connectionReused())
- , m_allowTimingDetails(allowTimingDetails)
- , m_allowRedirectDetails(allowRedirectDetails)
- , m_requestingDocument(requestingDocument)
-{
- ScriptWrappable::init(this);
-}
-
-PerformanceResourceTiming::~PerformanceResourceTiming()
-{
-}
-
-AtomicString PerformanceResourceTiming::initiatorType() const
-{
- return m_initiatorType;
-}
-
-double PerformanceResourceTiming::redirectStart() const
-{
- if (!m_lastRedirectEndTime || !m_allowRedirectDetails)
- return 0.0;
-
- return PerformanceEntry::startTime();
-}
-
-double PerformanceResourceTiming::redirectEnd() const
-{
- if (!m_lastRedirectEndTime || !m_allowRedirectDetails)
- return 0.0;
-
- return monotonicTimeToDocumentMilliseconds(m_requestingDocument.get(), m_lastRedirectEndTime);
-}
-
-double PerformanceResourceTiming::fetchStart() const
-{
- if (m_lastRedirectEndTime) {
- // FIXME: ASSERT(m_timing) should be in constructor once timeticks of
- // AppCache is exposed from chrome network stack, crbug/251100
- ASSERT(m_timing);
- return monotonicTimeToDocumentMilliseconds(m_requestingDocument.get(), m_timing->requestTime);
- }
-
- return PerformanceEntry::startTime();
-}
-
-double PerformanceResourceTiming::domainLookupStart() const
-{
- if (!m_allowTimingDetails)
- return 0.0;
-
- if (!m_timing || m_timing->dnsStart == 0.0)
- return fetchStart();
-
- return monotonicTimeToDocumentMilliseconds(m_requestingDocument.get(), m_timing->dnsStart);
-}
-
-double PerformanceResourceTiming::domainLookupEnd() const
-{
- if (!m_allowTimingDetails)
- return 0.0;
-
- if (!m_timing || m_timing->dnsEnd == 0.0)
- return domainLookupStart();
-
- return monotonicTimeToDocumentMilliseconds(m_requestingDocument.get(), m_timing->dnsEnd);
-}
-
-double PerformanceResourceTiming::connectStart() const
-{
- if (!m_allowTimingDetails)
- return 0.0;
-
- // connectStart will be zero when a network request is not made.
- if (!m_timing || m_timing->connectStart == 0.0 || m_didReuseConnection)
- return domainLookupEnd();
-
- // connectStart includes any DNS time, so we may need to trim that off.
- double connectStart = m_timing->connectStart;
- if (m_timing->dnsEnd > 0.0)
- connectStart = m_timing->dnsEnd;
-
- return monotonicTimeToDocumentMilliseconds(m_requestingDocument.get(), connectStart);
-}
-
-double PerformanceResourceTiming::connectEnd() const
-{
- if (!m_allowTimingDetails)
- return 0.0;
-
- // connectStart will be zero when a network request is not made.
- if (!m_timing || m_timing->connectEnd == 0.0 || m_didReuseConnection)
- return connectStart();
-
- return monotonicTimeToDocumentMilliseconds(m_requestingDocument.get(), m_timing->connectEnd);
-}
-
-double PerformanceResourceTiming::secureConnectionStart() const
-{
- if (!m_allowTimingDetails)
- return 0.0;
-
- if (!m_timing || m_timing->sslStart == 0.0) // Secure connection not negotiated.
- return 0.0;
-
- return monotonicTimeToDocumentMilliseconds(m_requestingDocument.get(), m_timing->sslStart);
-}
-
-double PerformanceResourceTiming::requestStart() const
-{
- if (!m_allowTimingDetails)
- return 0.0;
-
- if (!m_timing)
- return connectEnd();
-
- return monotonicTimeToDocumentMilliseconds(m_requestingDocument.get(), m_timing->sendStart);
-}
-
-double PerformanceResourceTiming::responseStart() const
-{
- if (!m_allowTimingDetails)
- return 0.0;
-
- if (!m_timing)
- return requestStart();
-
- // FIXME: This number isn't exactly correct. See the notes in PerformanceTiming::responseStart().
- return monotonicTimeToDocumentMilliseconds(m_requestingDocument.get(), m_timing->receiveHeadersEnd);
-}
-
-double PerformanceResourceTiming::responseEnd() const
-{
- if (!m_finishTime)
- return responseStart();
-
- return monotonicTimeToDocumentMilliseconds(m_requestingDocument.get(), m_finishTime);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/page/PerformanceResourceTiming.h b/chromium/third_party/WebKit/Source/core/page/PerformanceResourceTiming.h
deleted file mode 100644
index 5ea27eaa6eb..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/PerformanceResourceTiming.h
+++ /dev/null
@@ -1,92 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- * Copyright (C) 2012 Intel Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef PerformanceResourceTiming_h
-#define PerformanceResourceTiming_h
-
-#include "core/page/PerformanceEntry.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefPtr.h"
-
-namespace WebCore {
-
-class Document;
-class KURL;
-class ResourceLoadTiming;
-class ResourceRequest;
-class ResourceResponse;
-class ResourceTimingInfo;
-
-class PerformanceResourceTiming : public PerformanceEntry {
-public:
- static PassRefPtr<PerformanceResourceTiming> create(const ResourceTimingInfo& info, Document* requestingDocument, double startTime, double lastRedirectEndTime, bool m_allowTimingDetails, bool m_allowRedirectDetails)
- {
- return adoptRef(new PerformanceResourceTiming(info, requestingDocument, startTime, lastRedirectEndTime, m_allowTimingDetails, m_allowRedirectDetails));
- }
-
- static PassRefPtr<PerformanceResourceTiming> create(const ResourceTimingInfo& info, Document* requestingDocument, double startTime, bool m_allowTimingDetails)
- {
- return adoptRef(new PerformanceResourceTiming(info, requestingDocument, startTime, 0.0, m_allowTimingDetails, false));
- }
-
- AtomicString initiatorType() const;
-
- double redirectStart() const;
- double redirectEnd() const;
- double fetchStart() const;
- double domainLookupStart() const;
- double domainLookupEnd() const;
- double connectStart() const;
- double connectEnd() const;
- double secureConnectionStart() const;
- double requestStart() const;
- double responseStart() const;
- double responseEnd() const;
-
- virtual bool isResource() { return true; }
-
-private:
- PerformanceResourceTiming(const ResourceTimingInfo&, Document* requestingDocument, double startTime, double lastRedirectEndTime, bool m_allowTimingDetails, bool m_allowRedirectDetails);
- ~PerformanceResourceTiming();
-
- AtomicString m_initiatorType;
- RefPtr<ResourceLoadTiming> m_timing;
- double m_lastRedirectEndTime;
- double m_finishTime;
- bool m_didReuseConnection;
- bool m_allowTimingDetails;
- bool m_allowRedirectDetails;
- RefPtr<Document> m_requestingDocument;
-};
-
-}
-
-#endif // !defined(PerformanceResourceTiming_h)
diff --git a/chromium/third_party/WebKit/Source/core/page/PerformanceTiming.cpp b/chromium/third_party/WebKit/Source/core/page/PerformanceTiming.cpp
deleted file mode 100644
index 81214c3c008..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/PerformanceTiming.cpp
+++ /dev/null
@@ -1,356 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/page/PerformanceTiming.h"
-
-#include "core/dom/Document.h"
-#include "core/dom/DocumentTiming.h"
-#include "core/loader/DocumentLoadTiming.h"
-#include "core/loader/DocumentLoader.h"
-#include "core/loader/FrameLoader.h"
-#include "core/page/Frame.h"
-#include "core/platform/network/ResourceLoadTiming.h"
-#include "core/platform/network/ResourceResponse.h"
-
-namespace WebCore {
-
-static unsigned long long toIntegerMilliseconds(double seconds)
-{
- ASSERT(seconds >= 0);
- return static_cast<unsigned long long>(seconds * 1000.0);
-}
-
-PerformanceTiming::PerformanceTiming(Frame* frame)
- : DOMWindowProperty(frame)
-{
- ScriptWrappable::init(this);
-}
-
-unsigned long long PerformanceTiming::navigationStart() const
-{
- DocumentLoadTiming* timing = documentLoadTiming();
- if (!timing)
- return 0;
-
- return monotonicTimeToIntegerMilliseconds(timing->navigationStart());
-}
-
-unsigned long long PerformanceTiming::unloadEventStart() const
-{
- DocumentLoadTiming* timing = documentLoadTiming();
- if (!timing)
- return 0;
-
- if (timing->hasCrossOriginRedirect() || !timing->hasSameOriginAsPreviousDocument())
- return 0;
-
- return monotonicTimeToIntegerMilliseconds(timing->unloadEventStart());
-}
-
-unsigned long long PerformanceTiming::unloadEventEnd() const
-{
- DocumentLoadTiming* timing = documentLoadTiming();
- if (!timing)
- return 0;
-
- if (timing->hasCrossOriginRedirect() || !timing->hasSameOriginAsPreviousDocument())
- return 0;
-
- return monotonicTimeToIntegerMilliseconds(timing->unloadEventEnd());
-}
-
-unsigned long long PerformanceTiming::redirectStart() const
-{
- DocumentLoadTiming* timing = documentLoadTiming();
- if (!timing)
- return 0;
-
- if (timing->hasCrossOriginRedirect())
- return 0;
-
- return monotonicTimeToIntegerMilliseconds(timing->redirectStart());
-}
-
-unsigned long long PerformanceTiming::redirectEnd() const
-{
- DocumentLoadTiming* timing = documentLoadTiming();
- if (!timing)
- return 0;
-
- if (timing->hasCrossOriginRedirect())
- return 0;
-
- return monotonicTimeToIntegerMilliseconds(timing->redirectEnd());
-}
-
-unsigned long long PerformanceTiming::fetchStart() const
-{
- DocumentLoadTiming* timing = documentLoadTiming();
- if (!timing)
- return 0;
-
- return monotonicTimeToIntegerMilliseconds(timing->fetchStart());
-}
-
-unsigned long long PerformanceTiming::domainLookupStart() const
-{
- ResourceLoadTiming* timing = resourceLoadTiming();
- if (!timing)
- return fetchStart();
-
- // This will be zero when a DNS request is not performed.
- // Rather than exposing a special value that indicates no DNS, we "backfill" with fetchStart.
- double dnsStart = timing->dnsStart;
- if (dnsStart == 0.0)
- return fetchStart();
-
- return monotonicTimeToIntegerMilliseconds(dnsStart);
-}
-
-unsigned long long PerformanceTiming::domainLookupEnd() const
-{
- ResourceLoadTiming* timing = resourceLoadTiming();
- if (!timing)
- return domainLookupStart();
-
- // This will be zero when a DNS request is not performed.
- // Rather than exposing a special value that indicates no DNS, we "backfill" with domainLookupStart.
- double dnsEnd = timing->dnsEnd;
- if (dnsEnd == 0.0)
- return domainLookupStart();
-
- return monotonicTimeToIntegerMilliseconds(dnsEnd);
-}
-
-unsigned long long PerformanceTiming::connectStart() const
-{
- DocumentLoader* loader = documentLoader();
- if (!loader)
- return domainLookupEnd();
-
- ResourceLoadTiming* timing = loader->response().resourceLoadTiming();
- if (!timing)
- return domainLookupEnd();
-
- // connectStart will be zero when a network request is not made.
- // Rather than exposing a special value that indicates no new connection, we "backfill" with domainLookupEnd.
- double connectStart = timing->connectStart;
- if (connectStart == 0.0 || loader->response().connectionReused())
- return domainLookupEnd();
-
- // ResourceLoadTiming's connect phase includes DNS, however Navigation Timing's
- // connect phase should not. So if there is DNS time, trim it from the start.
- if (timing->dnsEnd > 0.0 && timing->dnsEnd > connectStart)
- connectStart = timing->dnsEnd;
-
- return monotonicTimeToIntegerMilliseconds(connectStart);
-}
-
-unsigned long long PerformanceTiming::connectEnd() const
-{
- DocumentLoader* loader = documentLoader();
- if (!loader)
- return connectStart();
-
- ResourceLoadTiming* timing = loader->response().resourceLoadTiming();
- if (!timing)
- return connectStart();
-
- // connectEnd will be zero when a network request is not made.
- // Rather than exposing a special value that indicates no new connection, we "backfill" with connectStart.
- double connectEnd = timing->connectEnd;
- if (connectEnd == 0.0 || loader->response().connectionReused())
- return connectStart();
-
- return monotonicTimeToIntegerMilliseconds(connectEnd);
-}
-
-unsigned long long PerformanceTiming::secureConnectionStart() const
-{
- DocumentLoader* loader = documentLoader();
- if (!loader)
- return 0;
-
- ResourceLoadTiming* timing = loader->response().resourceLoadTiming();
- if (!timing)
- return 0;
-
- double sslStart = timing->sslStart;
- if (sslStart == 0.0)
- return 0;
-
- return monotonicTimeToIntegerMilliseconds(sslStart);
-}
-
-unsigned long long PerformanceTiming::requestStart() const
-{
- ResourceLoadTiming* timing = resourceLoadTiming();
-
- if (!timing || timing->sendStart == 0.0)
- return connectEnd();
-
- return monotonicTimeToIntegerMilliseconds(timing->sendStart);
-}
-
-unsigned long long PerformanceTiming::responseStart() const
-{
- ResourceLoadTiming* timing = resourceLoadTiming();
- if (!timing || timing->receiveHeadersEnd == 0.0)
- return requestStart();
-
- // FIXME: Response start needs to be the time of the first received byte.
- // However, the ResourceLoadTiming API currently only supports the time
- // the last header byte was received. For many responses with reasonable
- // sized cookies, the HTTP headers fit into a single packet so this time
- // is basically equivalent. But for some responses, particularly those with
- // headers larger than a single packet, this time will be too late.
- return monotonicTimeToIntegerMilliseconds(timing->receiveHeadersEnd);
-}
-
-unsigned long long PerformanceTiming::responseEnd() const
-{
- DocumentLoadTiming* timing = documentLoadTiming();
- if (!timing)
- return 0;
-
- return monotonicTimeToIntegerMilliseconds(timing->responseEnd());
-}
-
-unsigned long long PerformanceTiming::domLoading() const
-{
- const DocumentTiming* timing = documentTiming();
- if (!timing)
- return fetchStart();
-
- return monotonicTimeToIntegerMilliseconds(timing->domLoading);
-}
-
-unsigned long long PerformanceTiming::domInteractive() const
-{
- const DocumentTiming* timing = documentTiming();
- if (!timing)
- return 0;
-
- return monotonicTimeToIntegerMilliseconds(timing->domInteractive);
-}
-
-unsigned long long PerformanceTiming::domContentLoadedEventStart() const
-{
- const DocumentTiming* timing = documentTiming();
- if (!timing)
- return 0;
-
- return monotonicTimeToIntegerMilliseconds(timing->domContentLoadedEventStart);
-}
-
-unsigned long long PerformanceTiming::domContentLoadedEventEnd() const
-{
- const DocumentTiming* timing = documentTiming();
- if (!timing)
- return 0;
-
- return monotonicTimeToIntegerMilliseconds(timing->domContentLoadedEventEnd);
-}
-
-unsigned long long PerformanceTiming::domComplete() const
-{
- const DocumentTiming* timing = documentTiming();
- if (!timing)
- return 0;
-
- return monotonicTimeToIntegerMilliseconds(timing->domComplete);
-}
-
-unsigned long long PerformanceTiming::loadEventStart() const
-{
- DocumentLoadTiming* timing = documentLoadTiming();
- if (!timing)
- return 0;
-
- return monotonicTimeToIntegerMilliseconds(timing->loadEventStart());
-}
-
-unsigned long long PerformanceTiming::loadEventEnd() const
-{
- DocumentLoadTiming* timing = documentLoadTiming();
- if (!timing)
- return 0;
-
- return monotonicTimeToIntegerMilliseconds(timing->loadEventEnd());
-}
-
-DocumentLoader* PerformanceTiming::documentLoader() const
-{
- if (!m_frame)
- return 0;
-
- return m_frame->loader()->documentLoader();
-}
-
-const DocumentTiming* PerformanceTiming::documentTiming() const
-{
- if (!m_frame)
- return 0;
-
- Document* document = m_frame->document();
- if (!document)
- return 0;
-
- return document->timing();
-}
-
-DocumentLoadTiming* PerformanceTiming::documentLoadTiming() const
-{
- DocumentLoader* loader = documentLoader();
- if (!loader)
- return 0;
-
- return loader->timing();
-}
-
-ResourceLoadTiming* PerformanceTiming::resourceLoadTiming() const
-{
- DocumentLoader* loader = documentLoader();
- if (!loader)
- return 0;
-
- return loader->response().resourceLoadTiming();
-}
-
-unsigned long long PerformanceTiming::monotonicTimeToIntegerMilliseconds(double monotonicSeconds) const
-{
- ASSERT(monotonicSeconds >= 0);
- const DocumentLoadTiming* timing = documentLoadTiming();
- ASSERT(timing);
- return toIntegerMilliseconds(timing->monotonicTimeToPseudoWallTime(monotonicSeconds));
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/page/PerformanceTiming.h b/chromium/third_party/WebKit/Source/core/page/PerformanceTiming.h
deleted file mode 100644
index ff9b8754b75..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/PerformanceTiming.h
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef PerformanceTiming_h
-#define PerformanceTiming_h
-
-#include "bindings/v8/ScriptWrappable.h"
-#include "core/page/DOMWindowProperty.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-
-namespace WebCore {
-
-class DocumentLoadTiming;
-class DocumentLoader;
-struct DocumentTiming;
-class Frame;
-class ResourceLoadTiming;
-
-class PerformanceTiming : public RefCounted<PerformanceTiming>, public ScriptWrappable, public DOMWindowProperty {
-public:
- static PassRefPtr<PerformanceTiming> create(Frame* frame) { return adoptRef(new PerformanceTiming(frame)); }
-
- unsigned long long navigationStart() const;
- unsigned long long unloadEventStart() const;
- unsigned long long unloadEventEnd() const;
- unsigned long long redirectStart() const;
- unsigned long long redirectEnd() const;
- unsigned long long fetchStart() const;
- unsigned long long domainLookupStart() const;
- unsigned long long domainLookupEnd() const;
- unsigned long long connectStart() const;
- unsigned long long connectEnd() const;
- unsigned long long secureConnectionStart() const;
- unsigned long long requestStart() const;
- unsigned long long responseStart() const;
- unsigned long long responseEnd() const;
- unsigned long long domLoading() const;
- unsigned long long domInteractive() const;
- unsigned long long domContentLoadedEventStart() const;
- unsigned long long domContentLoadedEventEnd() const;
- unsigned long long domComplete() const;
- unsigned long long loadEventStart() const;
- unsigned long long loadEventEnd() const;
-
-private:
- explicit PerformanceTiming(Frame*);
-
- const DocumentTiming* documentTiming() const;
- DocumentLoader* documentLoader() const;
- DocumentLoadTiming* documentLoadTiming() const;
- ResourceLoadTiming* resourceLoadTiming() const;
-
- unsigned long long monotonicTimeToIntegerMilliseconds(double) const;
-};
-
-}
-
-#endif // !defined(PerformanceTiming_h)
diff --git a/chromium/third_party/WebKit/Source/core/page/PerformanceUserTiming.cpp b/chromium/third_party/WebKit/Source/core/page/PerformanceUserTiming.cpp
deleted file mode 100644
index 568fa357f52..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/PerformanceUserTiming.cpp
+++ /dev/null
@@ -1,209 +0,0 @@
-/*
- * Copyright (C) 2012 Intel Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/page/PerformanceUserTiming.h"
-
-#include "bindings/v8/ExceptionState.h"
-#include "core/dom/ExceptionCode.h"
-#include "core/page/Performance.h"
-#include "core/page/PerformanceMark.h"
-#include "core/page/PerformanceMeasure.h"
-#include "core/platform/HistogramSupport.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-namespace {
-
-typedef HashMap<String, NavigationTimingFunction> RestrictedKeyMap;
-static RestrictedKeyMap restrictedKeyMap()
-{
- DEFINE_STATIC_LOCAL(RestrictedKeyMap, map, ());
- if (map.isEmpty()) {
- map.add("navigationStart", &PerformanceTiming::navigationStart);
- map.add("unloadEventStart", &PerformanceTiming::unloadEventStart);
- map.add("unloadEventEnd", &PerformanceTiming::unloadEventEnd);
- map.add("redirectStart", &PerformanceTiming::redirectStart);
- map.add("redirectEnd", &PerformanceTiming::redirectEnd);
- map.add("fetchStart", &PerformanceTiming::fetchStart);
- map.add("domainLookupStart", &PerformanceTiming::domainLookupStart);
- map.add("domainLookupEnd", &PerformanceTiming::domainLookupEnd);
- map.add("connectStart", &PerformanceTiming::connectStart);
- map.add("connectEnd", &PerformanceTiming::connectEnd);
- map.add("secureConnectionStart", &PerformanceTiming::secureConnectionStart);
- map.add("requestStart", &PerformanceTiming::requestStart);
- map.add("responseStart", &PerformanceTiming::responseStart);
- map.add("responseEnd", &PerformanceTiming::responseEnd);
- map.add("domLoading", &PerformanceTiming::domLoading);
- map.add("domInteractive", &PerformanceTiming::domInteractive);
- map.add("domContentLoadedEventStart", &PerformanceTiming::domContentLoadedEventStart);
- map.add("domContentLoadedEventEnd", &PerformanceTiming::domContentLoadedEventEnd);
- map.add("domComplete", &PerformanceTiming::domComplete);
- map.add("loadEventStart", &PerformanceTiming::loadEventStart);
- map.add("loadEventEnd", &PerformanceTiming::loadEventEnd);
- }
- return map;
-}
-
-} // namespace anonymous
-
-UserTiming::UserTiming(Performance* performance)
- : m_performance(performance)
-{
-}
-
-static void insertPerformanceEntry(PerformanceEntryMap& performanceEntryMap, PassRefPtr<PerformanceEntry> performanceEntry)
-{
- RefPtr<PerformanceEntry> entry = performanceEntry;
- PerformanceEntryMap::iterator it = performanceEntryMap.find(entry->name());
- if (it != performanceEntryMap.end())
- it->value.append(entry);
- else {
- Vector<RefPtr<PerformanceEntry> > v(1);
- v[0] = entry;
- performanceEntryMap.set(entry->name(), v);
- }
-}
-
-static void clearPeformanceEntries(PerformanceEntryMap& performanceEntryMap, const String& name)
-{
- if (name.isNull()) {
- performanceEntryMap.clear();
- return;
- }
-
- if (performanceEntryMap.contains(name))
- performanceEntryMap.remove(name);
-}
-
-void UserTiming::mark(const String& markName, ExceptionState& es)
-{
- if (restrictedKeyMap().contains(markName)) {
- es.throwDOMException(SyntaxError, "'" + markName + "' is part of the PerformanceTiming interface, and cannot be used as a mark name.");
- return;
- }
-
- double startTime = m_performance->now();
- insertPerformanceEntry(m_marksMap, PerformanceMark::create(markName, startTime));
- HistogramSupport::histogramCustomCounts("PLT.UserTiming_Mark", static_cast<int>(startTime), 0, 600000, 100);
-}
-
-void UserTiming::clearMarks(const String& markName)
-{
- clearPeformanceEntries(m_marksMap, markName);
-}
-
-double UserTiming::findExistingMarkStartTime(const String& markName, ExceptionState& es)
-{
- if (m_marksMap.contains(markName))
- return m_marksMap.get(markName).last()->startTime();
-
- if (restrictedKeyMap().contains(markName)) {
- double value = static_cast<double>((m_performance->timing()->*(restrictedKeyMap().get(markName)))());
- if (!value) {
- es.throwDOMException(InvalidAccessError, "'" + markName + "' is empty: either the event hasn't happened yet, or it would provide cross-origin timing information.");
- return 0.0;
- }
- return value - m_performance->timing()->navigationStart();
- }
-
- es.throwDOMException(SyntaxError, "The mark '" + markName + "' does not exist.");
- return 0.0;
-}
-
-void UserTiming::measure(const String& measureName, const String& startMark, const String& endMark, ExceptionState& es)
-{
- double startTime = 0.0;
- double endTime = 0.0;
-
- if (startMark.isNull())
- endTime = m_performance->now();
- else if (endMark.isNull()) {
- endTime = m_performance->now();
- startTime = findExistingMarkStartTime(startMark, es);
- if (es.hadException())
- return;
- } else {
- endTime = findExistingMarkStartTime(endMark, es);
- if (es.hadException())
- return;
- startTime = findExistingMarkStartTime(startMark, es);
- if (es.hadException())
- return;
- }
-
- insertPerformanceEntry(m_measuresMap, PerformanceMeasure::create(measureName, startTime, endTime));
- if (endTime >= startTime)
- HistogramSupport::histogramCustomCounts("PLT.UserTiming_MeasureDuration", static_cast<int>(endTime - startTime), 0, 600000, 100);
-}
-
-void UserTiming::clearMeasures(const String& measureName)
-{
- clearPeformanceEntries(m_measuresMap, measureName);
-}
-
-static Vector<RefPtr<PerformanceEntry> > convertToEntrySequence(const PerformanceEntryMap& performanceEntryMap)
-{
- Vector<RefPtr<PerformanceEntry> > entries;
-
- for (PerformanceEntryMap::const_iterator it = performanceEntryMap.begin(); it != performanceEntryMap.end(); ++it)
- entries.append(it->value);
-
- return entries;
-}
-
-static Vector<RefPtr<PerformanceEntry> > getEntrySequenceByName(const PerformanceEntryMap& performanceEntryMap, const String& name)
-{
- Vector<RefPtr<PerformanceEntry> > entries;
-
- PerformanceEntryMap::const_iterator it = performanceEntryMap.find(name);
- if (it != performanceEntryMap.end())
- entries.append(it->value);
-
- return entries;
-}
-
-Vector<RefPtr<PerformanceEntry> > UserTiming::getMarks() const
-{
- return convertToEntrySequence(m_marksMap);
-}
-
-Vector<RefPtr<PerformanceEntry> > UserTiming::getMarks(const String& name) const
-{
- return getEntrySequenceByName(m_marksMap, name);
-}
-
-Vector<RefPtr<PerformanceEntry> > UserTiming::getMeasures() const
-{
- return convertToEntrySequence(m_measuresMap);
-}
-
-Vector<RefPtr<PerformanceEntry> > UserTiming::getMeasures(const String& name) const
-{
- return getEntrySequenceByName(m_measuresMap, name);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/page/PerformanceUserTiming.h b/chromium/third_party/WebKit/Source/core/page/PerformanceUserTiming.h
deleted file mode 100644
index 1f150aeb61e..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/PerformanceUserTiming.h
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Copyright (C) 2012 Intel Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef PerformanceUserTiming_h
-#define PerformanceUserTiming_h
-
-#include "core/page/PerformanceTiming.h"
-#include "wtf/HashMap.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/text/StringHash.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class ExceptionState;
-class Performance;
-class PerformanceEntry;
-
-typedef unsigned long long (PerformanceTiming::*NavigationTimingFunction)() const;
-typedef HashMap<String, Vector<RefPtr<PerformanceEntry> > > PerformanceEntryMap;
-
-class UserTiming : public RefCounted<UserTiming> {
-public:
- static PassRefPtr<UserTiming> create(Performance* performance) { return adoptRef(new UserTiming(performance)); }
-
- void mark(const String& markName, ExceptionState&);
- void clearMarks(const String& markName);
-
- void measure(const String& measureName, const String& startMark, const String& endMark, ExceptionState&);
- void clearMeasures(const String& measureName);
-
- Vector<RefPtr<PerformanceEntry> > getMarks() const;
- Vector<RefPtr<PerformanceEntry> > getMeasures() const;
-
- Vector<RefPtr<PerformanceEntry> > getMarks(const String& name) const;
- Vector<RefPtr<PerformanceEntry> > getMeasures(const String& name) const;
-
-private:
- explicit UserTiming(Performance*);
-
- double findExistingMarkStartTime(const String& markName, ExceptionState&);
- Performance* m_performance;
- PerformanceEntryMap m_marksMap;
- PerformanceEntryMap m_measuresMap;
-};
-
-}
-
-#endif // !defined(PerformanceUserTiming_h)
diff --git a/chromium/third_party/WebKit/Source/core/page/PointerLockController.cpp b/chromium/third_party/WebKit/Source/core/page/PointerLockController.cpp
index 015c7ff9904..d83f7b4dc95 100644
--- a/chromium/third_party/WebKit/Source/core/page/PointerLockController.cpp
+++ b/chromium/third_party/WebKit/Source/core/page/PointerLockController.cpp
@@ -26,11 +26,12 @@
#include "core/page/PointerLockController.h"
#include "core/dom/Element.h"
-#include "core/dom/Event.h"
+#include "core/events/Event.h"
+#include "core/frame/DOMWindow.h"
#include "core/page/Chrome.h"
#include "core/page/ChromeClient.h"
#include "core/page/Page.h"
-#include "core/platform/PlatformMouseEvent.h"
+#include "platform/PlatformMouseEvent.h"
namespace WebCore {
@@ -47,29 +48,29 @@ PassOwnPtr<PointerLockController> PointerLockController::create(Page* page)
void PointerLockController::requestPointerLock(Element* target)
{
if (!target || !target->inDocument() || m_documentOfRemovedElementWhileWaitingForUnlock) {
- enqueueEvent(eventNames().webkitpointerlockerrorEvent, target);
+ enqueueEvent(EventTypeNames::webkitpointerlockerror, target);
return;
}
if (target->document().isSandboxed(SandboxPointerLock)) {
// FIXME: This message should be moved off the console once a solution to https://bugs.webkit.org/show_bug.cgi?id=103274 exists.
target->document().addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, "Blocked pointer lock on an element because the element's frame is sandboxed and the 'allow-pointer-lock' permission is not set.");
- enqueueEvent(eventNames().webkitpointerlockerrorEvent, target);
+ enqueueEvent(EventTypeNames::webkitpointerlockerror, target);
return;
}
if (m_element) {
- if (&m_element->document() != &target->document()) {
- enqueueEvent(eventNames().webkitpointerlockerrorEvent, target);
+ if (m_element->document() != target->document()) {
+ enqueueEvent(EventTypeNames::webkitpointerlockerror, target);
return;
}
- enqueueEvent(eventNames().webkitpointerlockchangeEvent, target);
+ enqueueEvent(EventTypeNames::webkitpointerlockchange, target);
m_element = target;
} else if (m_page->chrome().client().requestPointerLock()) {
m_lockPending = true;
m_element = target;
} else {
- enqueueEvent(eventNames().webkitpointerlockerrorEvent, target);
+ enqueueEvent(EventTypeNames::webkitpointerlockerror, target);
}
}
@@ -91,7 +92,7 @@ void PointerLockController::elementRemoved(Element* element)
void PointerLockController::documentDetached(Document* document)
{
- if (m_element && &m_element->document() == document) {
+ if (m_element && m_element->document() == document) {
clearElement();
requestPointerUnlock();
}
@@ -109,19 +110,19 @@ Element* PointerLockController::element() const
void PointerLockController::didAcquirePointerLock()
{
- enqueueEvent(eventNames().webkitpointerlockchangeEvent, m_element.get());
+ enqueueEvent(EventTypeNames::webkitpointerlockchange, m_element.get());
m_lockPending = false;
}
void PointerLockController::didNotAcquirePointerLock()
{
- enqueueEvent(eventNames().webkitpointerlockerrorEvent, m_element.get());
+ enqueueEvent(EventTypeNames::webkitpointerlockerror, m_element.get());
clearElement();
}
void PointerLockController::didLosePointerLock()
{
- enqueueEvent(eventNames().webkitpointerlockchangeEvent, m_element ? &m_element->document() : m_documentOfRemovedElementWhileWaitingForUnlock.get());
+ enqueueEvent(EventTypeNames::webkitpointerlockchange, m_element ? &m_element->document() : m_documentOfRemovedElementWhileWaitingForUnlock.get());
clearElement();
m_documentOfRemovedElementWhileWaitingForUnlock = 0;
}
@@ -134,8 +135,8 @@ void PointerLockController::dispatchLockedMouseEvent(const PlatformMouseEvent& e
m_element->dispatchMouseEvent(event, eventType, event.clickCount());
// Create click events
- if (eventType == eventNames().mouseupEvent)
- m_element->dispatchMouseEvent(event, eventNames().clickEvent, event.clickCount());
+ if (eventType == EventTypeNames::mouseup)
+ m_element->dispatchMouseEvent(event, EventTypeNames::click, event.clickCount());
}
void PointerLockController::clearElement()
@@ -152,8 +153,8 @@ void PointerLockController::enqueueEvent(const AtomicString& type, Element* elem
void PointerLockController::enqueueEvent(const AtomicString& type, Document* document)
{
- if (document)
- document->enqueueDocumentEvent(Event::createBubble(type));
+ if (document && document->domWindow())
+ document->domWindow()->enqueueDocumentEvent(Event::create(type));
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/page/PrintContext.cpp b/chromium/third_party/WebKit/Source/core/page/PrintContext.cpp
index 0803a419c2d..61a4f8adfd8 100644
--- a/chromium/third_party/WebKit/Source/core/page/PrintContext.cpp
+++ b/chromium/third_party/WebKit/Source/core/page/PrintContext.cpp
@@ -21,11 +21,10 @@
#include "config.h"
#include "core/page/PrintContext.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameView.h"
-#include "core/platform/graphics/GraphicsContext.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
#include "core/rendering/RenderView.h"
-#include "wtf/text/WTFString.h"
+#include "platform/graphics/GraphicsContext.h"
namespace WebCore {
@@ -64,7 +63,7 @@ void PrintContext::computePageRects(const FloatRect& printRect, float headerHeig
return;
if (userScaleFactor <= 0) {
- LOG_ERROR("userScaleFactor has bad value %.2f", userScaleFactor);
+ WTF_LOG_ERROR("userScaleFactor has bad value %.2f", userScaleFactor);
return;
}
@@ -78,7 +77,7 @@ void PrintContext::computePageRects(const FloatRect& printRect, float headerHeig
pageHeight -= headerHeight + footerHeight;
if (pageHeight <= 0) {
- LOG_ERROR("pageHeight has bad value %.2f", pageHeight);
+ WTF_LOG_ERROR("pageHeight has bad value %.2f", pageHeight);
return;
}
diff --git a/chromium/third_party/WebKit/Source/core/page/ResourceTimingInfo.h b/chromium/third_party/WebKit/Source/core/page/ResourceTimingInfo.h
deleted file mode 100644
index 8679bdf4626..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/ResourceTimingInfo.h
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * Copyright (C) 2013 Intel Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ResourceTimingInfo_h
-#define ResourceTimingInfo_h
-
-#include "core/platform/network/ResourceRequest.h"
-#include "core/platform/network/ResourceResponse.h"
-#include "wtf/text/AtomicString.h"
-
-namespace WebCore {
-
-class ResourceTimingInfo : public RefCounted<ResourceTimingInfo> {
-public:
- static PassRefPtr<ResourceTimingInfo> create(const AtomicString& type, const double time)
- {
- return adoptRef(new ResourceTimingInfo(type, time));
- }
-
- double initialTime() const { return m_initialTime; }
-
- void setInitiatorType(const AtomicString& type) { m_type = type; }
- const AtomicString& initiatorType() const { return m_type; }
-
- void setLoadFinishTime(double time) { m_loadFinishTime = time; }
- double loadFinishTime() const { return m_loadFinishTime; }
-
- void setInitialRequest(const ResourceRequest& request) { m_initialRequest = request; }
- const ResourceRequest& initialRequest() const { return m_initialRequest; }
-
- void setFinalResponse(const ResourceResponse& response) { m_finalResponse = response; }
- const ResourceResponse& finalResponse() const { return m_finalResponse; }
-
- void addRedirect(const ResourceResponse& redirectResponse) { m_redirectChain.append(redirectResponse); }
- const Vector<ResourceResponse>& redirectChain() const { return m_redirectChain; }
-
-private:
- ResourceTimingInfo(const AtomicString& type, const double time)
- : m_type(type)
- , m_initialTime(time)
- {
- }
-
- AtomicString m_type;
- double m_initialTime;
- double m_loadFinishTime;
- ResourceRequest m_initialRequest;
- ResourceResponse m_finalResponse;
- Vector<ResourceResponse> m_redirectChain;
-};
-
-} // namespace WebCore
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/page/RuntimeCSSEnabled.cpp b/chromium/third_party/WebKit/Source/core/page/RuntimeCSSEnabled.cpp
deleted file mode 100644
index 42934b3ad44..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/RuntimeCSSEnabled.cpp
+++ /dev/null
@@ -1,166 +0,0 @@
-/*
- * Copyright (C) 2013 Adobe Systems Incorporated. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above
- * copyright notice, this list of conditions and the following
- * disclaimer.
- * 2. Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following
- * disclaimer in the documentation and/or other materials
- * provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
- * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
- * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
- * OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/page/RuntimeCSSEnabled.h"
-#include "RuntimeEnabledFeatures.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-// FIXME: We should use a real BitVector class instead!
-typedef Vector<bool> BoolVector;
-
-static void setCSSPropertiesEnabled(CSSPropertyID* properties, size_t length, bool featureFlag)
-{
- for (size_t i = 0; i < length; i++)
- RuntimeCSSEnabled::setCSSPropertyEnabled(properties[i], featureFlag);
-}
-
-static void setPropertySwitchesFromRuntimeFeatures()
-{
- CSSPropertyID regionProperites[] = {
- CSSPropertyWebkitFlowInto,
- CSSPropertyWebkitFlowFrom,
- CSSPropertyWebkitRegionFragment,
- CSSPropertyWebkitRegionBreakAfter,
- CSSPropertyWebkitRegionBreakBefore,
- CSSPropertyWebkitRegionBreakInside
- };
- setCSSPropertiesEnabled(regionProperites, WTF_ARRAY_LENGTH(regionProperites), RuntimeEnabledFeatures::cssRegionsEnabled());
- CSSPropertyID exclusionProperties[] = {
- CSSPropertyWebkitWrapFlow,
- CSSPropertyWebkitWrapThrough,
- };
- setCSSPropertiesEnabled(exclusionProperties, WTF_ARRAY_LENGTH(exclusionProperties), RuntimeEnabledFeatures::cssExclusionsEnabled());
- CSSPropertyID shapeProperties[] = {
- CSSPropertyWebkitShapeMargin,
- CSSPropertyWebkitShapePadding,
- CSSPropertyWebkitShapeInside,
- CSSPropertyWebkitShapeOutside,
- };
- setCSSPropertiesEnabled(shapeProperties, WTF_ARRAY_LENGTH(shapeProperties), RuntimeEnabledFeatures::cssShapesEnabled());
- CSSPropertyID css3TextDecorationProperties[] = {
- CSSPropertyTextDecorationColor,
- CSSPropertyTextDecorationLine,
- CSSPropertyTextDecorationStyle,
- };
- setCSSPropertiesEnabled(css3TextDecorationProperties, WTF_ARRAY_LENGTH(css3TextDecorationProperties), RuntimeEnabledFeatures::css3TextDecorationsEnabled());
- CSSPropertyID css3TextProperties[] = {
- CSSPropertyTextAlignLast,
- };
- setCSSPropertiesEnabled(css3TextProperties, WTF_ARRAY_LENGTH(css3TextProperties), RuntimeEnabledFeatures::css3TextEnabled());
- CSSPropertyID cssGridLayoutProperties[] = {
- CSSPropertyGridAutoColumns,
- CSSPropertyGridAutoRows,
- CSSPropertyGridDefinitionColumns,
- CSSPropertyGridDefinitionRows,
- CSSPropertyGridColumnStart,
- CSSPropertyGridColumnEnd,
- CSSPropertyGridRowStart,
- CSSPropertyGridRowEnd,
- CSSPropertyGridColumn,
- CSSPropertyGridRow,
- CSSPropertyGridArea,
- CSSPropertyGridAutoFlow,
- CSSPropertyGridTemplate
- };
- setCSSPropertiesEnabled(cssGridLayoutProperties, WTF_ARRAY_LENGTH(cssGridLayoutProperties), RuntimeEnabledFeatures::cssGridLayoutEnabled());
- CSSPropertyID cssObjectFitPositionProperties[] = {
- CSSPropertyObjectFit,
- CSSPropertyObjectPosition
- };
- setCSSPropertiesEnabled(cssObjectFitPositionProperties, WTF_ARRAY_LENGTH(cssObjectFitPositionProperties), RuntimeEnabledFeatures::objectFitPositionEnabled());
-
- CSSPropertyID animationProperties[] = {
- CSSPropertyAnimation,
- CSSPropertyAnimationName,
- CSSPropertyAnimationDuration,
- CSSPropertyAnimationTimingFunction,
- CSSPropertyAnimationDelay,
- CSSPropertyAnimationIterationCount,
- CSSPropertyAnimationDirection,
- CSSPropertyAnimationFillMode,
- CSSPropertyAnimationPlayState
- };
- setCSSPropertiesEnabled(animationProperties, WTF_ARRAY_LENGTH(animationProperties), RuntimeEnabledFeatures::cssAnimationUnprefixedEnabled());
-
- RuntimeCSSEnabled::setCSSPropertyEnabled(CSSPropertyBackgroundBlendMode, RuntimeEnabledFeatures::cssCompositingEnabled());
- RuntimeCSSEnabled::setCSSPropertyEnabled(CSSPropertyMixBlendMode, RuntimeEnabledFeatures::cssCompositingEnabled());
- RuntimeCSSEnabled::setCSSPropertyEnabled(CSSPropertyIsolation, RuntimeEnabledFeatures::cssCompositingEnabled());
- RuntimeCSSEnabled::setCSSPropertyEnabled(CSSPropertyTouchAction, RuntimeEnabledFeatures::cssTouchActionEnabled());
- RuntimeCSSEnabled::setCSSPropertyEnabled(CSSPropertyPaintOrder, RuntimeEnabledFeatures::svgPaintOrderEnabled());
- RuntimeCSSEnabled::setCSSPropertyEnabled(CSSPropertyVariable, RuntimeEnabledFeatures::cssVariablesEnabled());
- RuntimeCSSEnabled::setCSSPropertyEnabled(CSSPropertyMaskSourceType, RuntimeEnabledFeatures::cssMaskSourceTypeEnabled());
-}
-
-static BoolVector& propertySwitches()
-{
- static BoolVector* switches = 0;
- if (!switches) {
- switches = new BoolVector;
- // Accomodate CSSPropertyIDs that fall outside the firstCSSProperty, lastCSSProperty range (eg. CSSPropertyVariable).
- switches->fill(true, lastCSSProperty + 1);
- setPropertySwitchesFromRuntimeFeatures();
- }
- return *switches;
-}
-
-size_t indexForProperty(CSSPropertyID propertyId)
-{
- RELEASE_ASSERT(propertyId >= 0 && propertyId <= lastCSSProperty);
- ASSERT(propertyId != CSSPropertyInvalid);
- return static_cast<size_t>(propertyId);
-}
-
-bool RuntimeCSSEnabled::isCSSPropertyEnabled(CSSPropertyID propertyId)
-{
- // Internal properties shouldn't be exposed to the web
- // so they are considered to be always disabled.
- if (isInternalProperty(propertyId))
- return false;
-
- return propertySwitches()[indexForProperty(propertyId)];
-}
-
-void RuntimeCSSEnabled::setCSSPropertyEnabled(CSSPropertyID propertyId, bool enable)
-{
- propertySwitches()[indexForProperty(propertyId)] = enable;
-}
-
-void RuntimeCSSEnabled::filterEnabledCSSPropertiesIntoVector(const CSSPropertyID* properties, size_t propertyCount, Vector<CSSPropertyID>& outVector)
-{
- for (unsigned i = 0; i < propertyCount; i++) {
- CSSPropertyID property = properties[i];
- if (RuntimeCSSEnabled::isCSSPropertyEnabled(property))
- outVector.append(property);
- }
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/page/RuntimeEnabledFeatures.in b/chromium/third_party/WebKit/Source/core/page/RuntimeEnabledFeatures.in
deleted file mode 100644
index 31042232829..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/RuntimeEnabledFeatures.in
+++ /dev/null
@@ -1,105 +0,0 @@
-// http://dev.chromium.org/blink/runtime-enabled-features
-//
-// This list is used to generate RuntimeEnabledFeatures.h/cpp which contains
-// a class that stores static enablers for all experimental features.
-//
-// Each feature can be assigned a "status":
-// status=stable -> Enable this in all Blink configurations. We are committed to these APIs indefinitely.
-// status=experimental -> In-progress features, Web Developers might play with, but are not on by default in stable.
-// status=test -> Enabled in ContentShell for testing, otherwise off.
-// Features without a status are not enabled anywhere by default.
-//
-// "stable" features listed here should be rare, as anything which we've shipped stable
-// can have its runtime flag removed soon after.
-//
-// condition=ENABLE_NAME is used for wrapping features in compile-time
-// #if ENABLE(FEATURE) guards. These are deprecated and should all be removed.
-
-AnimatedWebP status=experimental
-ApplicationCache status=stable
-AuthorShadowDOMForAnyElement
-Crypto status=test
-CSSAnimationUnprefixed status=experimental
-CSSCompositing status=experimental
-CSSExclusions status=experimental
-CSSGridLayout status=experimental
-CSSMaskSourceType status=experimental
-CSSRegions status=experimental
-CSSShapes status=experimental
-CSSTouchAction status=test
-CSSVariables status=experimental
-CSSViewport status=experimental
-CSS3Text status=experimental
-CSS3TextDecorations status=experimental
-CustomElements status=experimental
-Database status=stable
-DataListElement status=stable
-DeviceMotion status=stable
-DeviceOrientation status=stable
-DevicePixelRatioIncludesZoom status=stable
-DialogElement status=experimental
-DirectoryUpload status=stable
-// FIXME: Remove this separate feature when CustomElements are always enabled
-EmbedderCustomElements
-EncodingAPI status=experimental
-EncryptedMedia status=experimental
-EncryptedMediaAnyVersion status=stable
-ExperimentalCanvasFeatures status=test
-ExperimentalContentSecurityPolicyFeatures status=experimental
-FileSystem status=stable
-FontLoadEvents status=experimental
-Fullscreen status=stable
-Gamepad status=stable
-Geolocation status=stable
-HTMLImports status=test
-HighResolutionTimeInWorkers status=experimental
-IMEAPI status=test
-IndexedDB status=stable
-InputModeAttribute status=test
-InputTypeColor status=stable
-InputTypeWeek status=stable
-LangAttributeAwareFormControlUI
-LegacyEncryptedMedia status=stable
-LocalStorage status=stable
-Media status=stable
-MediaSource status=stable
-MediaStream status=stable
-Notifications status=stable
-ObjectFitPosition status=experimental
-// Only enabled on Android, and for certain layout tests on Linux.
-OverlayFullscreenVideo
-PagePopup status=stable
-PartialLayout status=experimental
-PathOpsSVGClipping
-PeerConnection depends_on=MediaStream, status=stable
-ProgrammaticScrollNotifications status=test
-Promise status=experimental
-Quota status=stable
-OverlayScrollbars
-RequestAutocomplete status=test
-RowSpanLogicalHeightSpreading status=test
-ScriptedSpeech status=stable
-SeamlessIFrames status=experimental
-ServiceWorker status=experimental
-SessionStorage status=stable
-ShadowDOM status=experimental
-SharedWorker custom
-SpeechInput status=stable
-SpeechSynthesis status=experimental
-Srcset status=experimental
-Stream status=experimental
-StyleScoped status=experimental
-SubpixelFontScaling
-SVGPaintOrder status=experimental
-Touch status=stable
-UserSelectAll status=experimental
-Vibration status=experimental
-VideoTrack status=stable
-WebAnimations
-WebAnimationsCSS depends_on=WebAnimations
-WebAnimationsSVG depends_on=WebAnimations
-WebAudio condition=WEB_AUDIO, status=stable
-WebGLDraftExtensions status=experimental
-WebMIDI status=test
-WebKitMediaSource status=stable
-WOFF2 status=experimental
diff --git a/chromium/third_party/WebKit/Source/core/page/RuntimeEnabledFeaturesCustom.cpp b/chromium/third_party/WebKit/Source/core/page/RuntimeEnabledFeaturesCustom.cpp
deleted file mode 100644
index 2ac204d2e28..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/RuntimeEnabledFeaturesCustom.cpp
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "RuntimeEnabledFeatures.h"
-
-#include "core/workers/SharedWorkerRepository.h"
-
-namespace WebCore {
-
-bool RuntimeEnabledFeatures::sharedWorkerEnabled()
-{
- return SharedWorkerRepository::isAvailable();
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/page/Screen.cpp b/chromium/third_party/WebKit/Source/core/page/Screen.cpp
deleted file mode 100644
index 7b7b4d318c9..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/Screen.cpp
+++ /dev/null
@@ -1,107 +0,0 @@
-/*
- * Copyright (C) 2007 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-
-#include "config.h"
-#include "core/page/Screen.h"
-
-#include "core/inspector/InspectorInstrumentation.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameView.h"
-#include "core/platform/PlatformScreen.h"
-#include "core/platform/graphics/FloatRect.h"
-
-namespace WebCore {
-
-Screen::Screen(Frame* frame)
- : DOMWindowProperty(frame)
-{
- ScriptWrappable::init(this);
-}
-
-unsigned Screen::height() const
-{
- if (!m_frame)
- return 0;
- long height = static_cast<long>(screenRect(m_frame->view()).height());
- InspectorInstrumentation::applyScreenHeightOverride(m_frame, &height);
- return static_cast<unsigned>(height);
-}
-
-unsigned Screen::width() const
-{
- if (!m_frame)
- return 0;
- long width = static_cast<long>(screenRect(m_frame->view()).width());
- InspectorInstrumentation::applyScreenWidthOverride(m_frame, &width);
- return static_cast<unsigned>(width);
-}
-
-unsigned Screen::colorDepth() const
-{
- if (!m_frame)
- return 0;
- return static_cast<unsigned>(screenDepth(m_frame->view()));
-}
-
-unsigned Screen::pixelDepth() const
-{
- if (!m_frame)
- return 0;
- return static_cast<unsigned>(screenDepth(m_frame->view()));
-}
-
-int Screen::availLeft() const
-{
- if (!m_frame)
- return 0;
- return static_cast<int>(screenAvailableRect(m_frame->view()).x());
-}
-
-int Screen::availTop() const
-{
- if (!m_frame)
- return 0;
- return static_cast<int>(screenAvailableRect(m_frame->view()).y());
-}
-
-unsigned Screen::availHeight() const
-{
- if (!m_frame)
- return 0;
- return static_cast<unsigned>(screenAvailableRect(m_frame->view()).height());
-}
-
-unsigned Screen::availWidth() const
-{
- if (!m_frame)
- return 0;
- return static_cast<unsigned>(screenAvailableRect(m_frame->view()).width());
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/page/Screen.h b/chromium/third_party/WebKit/Source/core/page/Screen.h
deleted file mode 100644
index 59fba130b08..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/Screen.h
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Copyright (C) 2007 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-
-#ifndef Screen_h
-#define Screen_h
-
-#include "bindings/v8/ScriptWrappable.h"
-#include "core/page/DOMWindowProperty.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-
-namespace WebCore {
-
- class Frame;
-
- class Screen : public ScriptWrappable, public RefCounted<Screen>, public DOMWindowProperty {
- public:
- static PassRefPtr<Screen> create(Frame *frame) { return adoptRef(new Screen(frame)); }
-
- unsigned height() const;
- unsigned width() const;
- unsigned colorDepth() const;
- unsigned pixelDepth() const;
- int availLeft() const;
- int availTop() const;
- unsigned availHeight() const;
- unsigned availWidth() const;
-
- private:
- explicit Screen(Frame*);
- };
-
-} // namespace WebCore
-
-#endif // Screen_h
diff --git a/chromium/third_party/WebKit/Source/core/page/Selection.idl b/chromium/third_party/WebKit/Source/core/page/Selection.idl
index e5d7a9e2f83..8f03f8e45d3 100644
--- a/chromium/third_party/WebKit/Source/core/page/Selection.idl
+++ b/chromium/third_party/WebKit/Source/core/page/Selection.idl
@@ -45,7 +45,7 @@
[RaisesException] void collapseToEnd();
[RaisesException] void collapseToStart();
- [CustomElementCallbacks=Enable] void deleteFromDocument();
+ [CustomElementCallbacks] void deleteFromDocument();
boolean containsNode([Default=Undefined] optional Node node,
[Default=Undefined] optional boolean allowPartial);
[RaisesException] void selectAllChildren([Default=Undefined] optional Node node);
diff --git a/chromium/third_party/WebKit/Source/core/page/Settings.cpp b/chromium/third_party/WebKit/Source/core/page/Settings.cpp
deleted file mode 100644
index d46062dcaef..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/Settings.cpp
+++ /dev/null
@@ -1,382 +0,0 @@
-/*
- * Copyright (C) 2006, 2007, 2008, 2009, 2011, 2012 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/page/Settings.h"
-
-#include <limits>
-#include "core/dom/Document.h"
-#include "core/fetch/ResourceFetcher.h"
-#include "core/inspector/InspectorInstrumentation.h"
-#include "core/page/Chrome.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameTree.h"
-#include "core/page/FrameView.h"
-#include "core/page/Page.h"
-#include "core/rendering/TextAutosizer.h"
-
-using namespace std;
-
-namespace WebCore {
-
-static void setImageLoadingSettings(Page* page)
-{
- for (Frame* frame = page->mainFrame(); frame; frame = frame->tree()->traverseNext()) {
- frame->document()->fetcher()->setImagesEnabled(page->settings().areImagesEnabled());
- frame->document()->fetcher()->setAutoLoadImages(page->settings().loadsImagesAutomatically());
- }
-}
-
-// Sets the entry in the font map for the given script. If family is the empty string, removes the entry instead.
-static inline void setGenericFontFamilyMap(ScriptFontFamilyMap& fontMap, const AtomicString& family, UScriptCode script, Page* page)
-{
- ScriptFontFamilyMap::iterator it = fontMap.find(static_cast<int>(script));
- if (family.isEmpty()) {
- if (it == fontMap.end())
- return;
- fontMap.remove(it);
- } else if (it != fontMap.end() && it->value == family)
- return;
- else
- fontMap.set(static_cast<int>(script), family);
-
- if (page)
- page->setNeedsRecalcStyleInAllFrames();
-}
-
-static inline const AtomicString& getGenericFontFamilyForScript(const ScriptFontFamilyMap& fontMap, UScriptCode script)
-{
- ScriptFontFamilyMap::const_iterator it = fontMap.find(static_cast<int>(script));
- if (it != fontMap.end())
- return it->value;
- if (script != USCRIPT_COMMON)
- return getGenericFontFamilyForScript(fontMap, USCRIPT_COMMON);
- return emptyAtom;
-}
-
-bool Settings::gMockScrollbarsEnabled = false;
-
-// NOTEs
-// 1) EditingMacBehavior comprises builds on Mac;
-// 2) EditingWindowsBehavior comprises builds on Windows;
-// 3) EditingUnixBehavior comprises all unix-based systems, but Darwin/MacOS/Android (and then abusing the terminology);
-// 4) EditingAndroidBehavior comprises Android builds.
-// 99) MacEditingBehavior is used a fallback.
-static EditingBehaviorType editingBehaviorTypeForPlatform()
-{
- return
-#if OS(MACOSX)
- EditingMacBehavior
-#elif OS(WIN)
- EditingWindowsBehavior
-#elif OS(ANDROID)
- EditingAndroidBehavior
-#else // Rest of the UNIX-like systems
- EditingUnixBehavior
-#endif
- ;
-}
-
-static const bool defaultUnifiedTextCheckerEnabled = false;
-#if OS(MACOSX)
-static const bool defaultSmartInsertDeleteEnabled = true;
-#else
-static const bool defaultSmartInsertDeleteEnabled = false;
-#endif
-#if OS(WIN)
-static const bool defaultSelectTrailingWhitespaceEnabled = true;
-#else
-static const bool defaultSelectTrailingWhitespaceEnabled = false;
-#endif
-
-Settings::Settings(Page* page)
- : m_page(0)
- , m_mediaTypeOverride("screen")
- , m_textAutosizingFontScaleFactor(1)
-#if HACK_FORCE_TEXT_AUTOSIZING_ON_DESKTOP
- , m_textAutosizingWindowSizeOverride(320, 480)
- , m_textAutosizingEnabled(true)
-#else
- , m_textAutosizingEnabled(false)
-#endif
- , m_useWideViewport(true)
- , m_loadWithOverviewMode(true)
- SETTINGS_INITIALIZER_LIST
- , m_isJavaEnabled(false)
- , m_loadsImagesAutomatically(false)
- , m_areImagesEnabled(true)
- , m_arePluginsEnabled(false)
- , m_isScriptEnabled(false)
- , m_isCSSCustomFilterEnabled(false)
- , m_cssStickyPositionEnabled(true)
- , m_dnsPrefetchingEnabled(false)
- , m_touchEventEmulationEnabled(false)
- , m_openGLMultisamplingEnabled(false)
- , m_viewportEnabled(false)
- , m_setImageLoadingSettingsTimer(this, &Settings::imageLoadingSettingsTimerFired)
- , m_compositorDrivenAcceleratedScrollingEnabled(false)
-{
- m_page = page; // Page is not yet fully initialized wen constructing Settings, so keeping m_page null over initializeDefaultFontFamilies() call.
-}
-
-PassOwnPtr<Settings> Settings::create(Page* page)
-{
- return adoptPtr(new Settings(page));
-}
-
-SETTINGS_SETTER_BODIES
-
-const AtomicString& Settings::standardFontFamily(UScriptCode script) const
-{
- return getGenericFontFamilyForScript(m_standardFontFamilyMap, script);
-}
-
-void Settings::setStandardFontFamily(const AtomicString& family, UScriptCode script)
-{
- setGenericFontFamilyMap(m_standardFontFamilyMap, family, script, m_page);
-}
-
-const AtomicString& Settings::fixedFontFamily(UScriptCode script) const
-{
- return getGenericFontFamilyForScript(m_fixedFontFamilyMap, script);
-}
-
-void Settings::setFixedFontFamily(const AtomicString& family, UScriptCode script)
-{
- setGenericFontFamilyMap(m_fixedFontFamilyMap, family, script, m_page);
-}
-
-const AtomicString& Settings::serifFontFamily(UScriptCode script) const
-{
- return getGenericFontFamilyForScript(m_serifFontFamilyMap, script);
-}
-
-void Settings::setSerifFontFamily(const AtomicString& family, UScriptCode script)
-{
- setGenericFontFamilyMap(m_serifFontFamilyMap, family, script, m_page);
-}
-
-const AtomicString& Settings::sansSerifFontFamily(UScriptCode script) const
-{
- return getGenericFontFamilyForScript(m_sansSerifFontFamilyMap, script);
-}
-
-void Settings::setSansSerifFontFamily(const AtomicString& family, UScriptCode script)
-{
- setGenericFontFamilyMap(m_sansSerifFontFamilyMap, family, script, m_page);
-}
-
-const AtomicString& Settings::cursiveFontFamily(UScriptCode script) const
-{
- return getGenericFontFamilyForScript(m_cursiveFontFamilyMap, script);
-}
-
-void Settings::setCursiveFontFamily(const AtomicString& family, UScriptCode script)
-{
- setGenericFontFamilyMap(m_cursiveFontFamilyMap, family, script, m_page);
-}
-
-const AtomicString& Settings::fantasyFontFamily(UScriptCode script) const
-{
- return getGenericFontFamilyForScript(m_fantasyFontFamilyMap, script);
-}
-
-void Settings::setFantasyFontFamily(const AtomicString& family, UScriptCode script)
-{
- setGenericFontFamilyMap(m_fantasyFontFamilyMap, family, script, m_page);
-}
-
-const AtomicString& Settings::pictographFontFamily(UScriptCode script) const
-{
- return getGenericFontFamilyForScript(m_pictographFontFamilyMap, script);
-}
-
-void Settings::setPictographFontFamily(const AtomicString& family, UScriptCode script)
-{
- setGenericFontFamilyMap(m_pictographFontFamilyMap, family, script, m_page);
-}
-
-void Settings::setTextAutosizingEnabled(bool textAutosizingEnabled)
-{
- if (m_textAutosizingEnabled == textAutosizingEnabled)
- return;
-
- m_textAutosizingEnabled = textAutosizingEnabled;
- m_page->setNeedsRecalcStyleInAllFrames();
-}
-
-void Settings::setTextAutosizingWindowSizeOverride(const IntSize& textAutosizingWindowSizeOverride)
-{
- if (m_textAutosizingWindowSizeOverride == textAutosizingWindowSizeOverride)
- return;
-
- m_textAutosizingWindowSizeOverride = textAutosizingWindowSizeOverride;
- m_page->setNeedsRecalcStyleInAllFrames();
-}
-
-void Settings::setUseWideViewport(bool useWideViewport)
-{
- if (m_useWideViewport == useWideViewport)
- return;
-
- m_useWideViewport = useWideViewport;
- if (m_page->mainFrame())
- m_page->chrome().dispatchViewportPropertiesDidChange(m_page->mainFrame()->document()->viewportArguments());
-}
-
-void Settings::setLoadWithOverviewMode(bool loadWithOverviewMode)
-{
- if (m_loadWithOverviewMode == loadWithOverviewMode)
- return;
-
- m_loadWithOverviewMode = loadWithOverviewMode;
- if (m_page->mainFrame())
- m_page->chrome().dispatchViewportPropertiesDidChange(m_page->mainFrame()->document()->viewportArguments());
-}
-
-void Settings::setTextAutosizingFontScaleFactor(float fontScaleFactor)
-{
- m_textAutosizingFontScaleFactor = fontScaleFactor;
-
- // FIXME: I wonder if this needs to traverse frames like in WebViewImpl::resize, or whether there is only one document per Settings instance?
- for (Frame* frame = m_page->mainFrame(); frame; frame = frame->tree()->traverseNext())
- frame->document()->textAutosizer()->recalculateMultipliers();
-
- m_page->setNeedsRecalcStyleInAllFrames();
-}
-
-void Settings::setMediaTypeOverride(const String& mediaTypeOverride)
-{
- if (m_mediaTypeOverride == mediaTypeOverride)
- return;
-
- m_mediaTypeOverride = mediaTypeOverride;
-
- Frame* mainFrame = m_page->mainFrame();
- ASSERT(mainFrame);
- FrameView* view = mainFrame->view();
- ASSERT(view);
-
- view->setMediaType(mediaTypeOverride);
- m_page->setNeedsRecalcStyleInAllFrames();
-}
-
-void Settings::setLoadsImagesAutomatically(bool loadsImagesAutomatically)
-{
- m_loadsImagesAutomatically = loadsImagesAutomatically;
-
- // Changing this setting to true might immediately start new loads for images that had previously had loading disabled.
- // If this happens while a WebView is being dealloc'ed, and we don't know the WebView is being dealloc'ed, these new loads
- // can cause crashes downstream when the WebView memory has actually been free'd.
- // One example where this can happen is in Mac apps that subclass WebView then do work in their overridden dealloc methods.
- // Starting these loads synchronously is not important. By putting it on a 0-delay, properly closing the Page cancels them
- // before they have a chance to really start.
- // See http://webkit.org/b/60572 for more discussion.
- m_setImageLoadingSettingsTimer.startOneShot(0);
-}
-
-void Settings::imageLoadingSettingsTimerFired(Timer<Settings>*)
-{
- setImageLoadingSettings(m_page);
-}
-
-void Settings::setScriptEnabled(bool isScriptEnabled)
-{
- m_isScriptEnabled = isScriptEnabled;
- InspectorInstrumentation::scriptsEnabled(m_page, m_isScriptEnabled);
-}
-
-void Settings::setJavaEnabled(bool isJavaEnabled)
-{
- m_isJavaEnabled = isJavaEnabled;
-}
-
-void Settings::setImagesEnabled(bool areImagesEnabled)
-{
- m_areImagesEnabled = areImagesEnabled;
-
- // See comment in setLoadsImagesAutomatically.
- m_setImageLoadingSettingsTimer.startOneShot(0);
-}
-
-void Settings::setPluginsEnabled(bool arePluginsEnabled)
-{
- m_arePluginsEnabled = arePluginsEnabled;
-}
-
-void Settings::setUserStyleSheetLocation(const KURL& userStyleSheetLocation)
-{
- if (m_userStyleSheetLocation == userStyleSheetLocation)
- return;
-
- m_userStyleSheetLocation = userStyleSheetLocation;
-
- m_page->userStyleSheetLocationChanged();
-}
-
-void Settings::setDNSPrefetchingEnabled(bool dnsPrefetchingEnabled)
-{
- if (m_dnsPrefetchingEnabled == dnsPrefetchingEnabled)
- return;
-
- m_dnsPrefetchingEnabled = dnsPrefetchingEnabled;
- m_page->dnsPrefetchingStateChanged();
-}
-
-void Settings::setMockScrollbarsEnabled(bool flag)
-{
- gMockScrollbarsEnabled = flag;
-}
-
-bool Settings::mockScrollbarsEnabled()
-{
- return gMockScrollbarsEnabled;
-}
-
-void Settings::setOpenGLMultisamplingEnabled(bool flag)
-{
- if (m_openGLMultisamplingEnabled == flag)
- return;
-
- m_openGLMultisamplingEnabled = flag;
- m_page->multisamplingChanged();
-}
-
-bool Settings::openGLMultisamplingEnabled()
-{
- return m_openGLMultisamplingEnabled;
-}
-
-void Settings::setViewportEnabled(bool enabled)
-{
- if (m_viewportEnabled == enabled)
- return;
-
- m_viewportEnabled = enabled;
- if (m_page->mainFrame())
- m_page->mainFrame()->document()->updateViewportArguments();
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/page/Settings.h b/chromium/third_party/WebKit/Source/core/page/Settings.h
deleted file mode 100644
index 588380bf66a..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/Settings.h
+++ /dev/null
@@ -1,206 +0,0 @@
-/*
- * Copyright (C) 2003, 2006, 2007, 2008, 2009, 2011, 2012 Apple Inc. All rights reserved.
- * (C) 2006 Graham Dennis (graham.dennis@gmail.com)
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef Settings_h
-#define Settings_h
-
-#include "SettingsMacros.h"
-#include "core/editing/EditingBehaviorTypes.h"
-#include "core/platform/Timer.h"
-#include "core/platform/graphics/IntSize.h"
-#include "weborigin/KURL.h"
-#include "wtf/HashMap.h"
-#include "wtf/text/AtomicString.h"
-#include "wtf/text/AtomicStringHash.h"
-
-namespace WebCore {
-
-class Page;
-
-enum EditableLinkBehavior {
- EditableLinkDefaultBehavior,
- EditableLinkAlwaysLive,
- EditableLinkOnlyLiveWithShiftKey,
- EditableLinkLiveWhenNotFocused,
- EditableLinkNeverLive
-};
-
-// UScriptCode uses -1 and 0 for UScriptInvalidCode and UScriptCommon.
-// We need to use -2 and -3 for empty value and deleted value.
-struct UScriptCodeHashTraits : WTF::GenericHashTraits<int> {
- static const bool emptyValueIsZero = false;
- static int emptyValue() { return -2; }
- static void constructDeletedValue(int& slot) { slot = -3; }
- static bool isDeletedValue(int value) { return value == -3; }
-};
-
-typedef HashMap<int, AtomicString, DefaultHash<int>::Hash, UScriptCodeHashTraits> ScriptFontFamilyMap;
-
-class Settings {
- WTF_MAKE_NONCOPYABLE(Settings); WTF_MAKE_FAST_ALLOCATED;
-public:
- static PassOwnPtr<Settings> create(Page*);
-
- void setStandardFontFamily(const AtomicString&, UScriptCode = USCRIPT_COMMON);
- const AtomicString& standardFontFamily(UScriptCode = USCRIPT_COMMON) const;
-
- void setFixedFontFamily(const AtomicString&, UScriptCode = USCRIPT_COMMON);
- const AtomicString& fixedFontFamily(UScriptCode = USCRIPT_COMMON) const;
-
- void setSerifFontFamily(const AtomicString&, UScriptCode = USCRIPT_COMMON);
- const AtomicString& serifFontFamily(UScriptCode = USCRIPT_COMMON) const;
-
- void setSansSerifFontFamily(const AtomicString&, UScriptCode = USCRIPT_COMMON);
- const AtomicString& sansSerifFontFamily(UScriptCode = USCRIPT_COMMON) const;
-
- void setCursiveFontFamily(const AtomicString&, UScriptCode = USCRIPT_COMMON);
- const AtomicString& cursiveFontFamily(UScriptCode = USCRIPT_COMMON) const;
-
- void setFantasyFontFamily(const AtomicString&, UScriptCode = USCRIPT_COMMON);
- const AtomicString& fantasyFontFamily(UScriptCode = USCRIPT_COMMON) const;
-
- void setPictographFontFamily(const AtomicString&, UScriptCode = USCRIPT_COMMON);
- const AtomicString& pictographFontFamily(UScriptCode = USCRIPT_COMMON) const;
-
- void setTextAutosizingEnabled(bool);
- bool textAutosizingEnabled() const { return m_textAutosizingEnabled; }
-
- void setTextAutosizingFontScaleFactor(float);
- float textAutosizingFontScaleFactor() const { return m_textAutosizingFontScaleFactor; }
-
- // Only set by Layout Tests, and only used if textAutosizingEnabled() returns true.
- void setTextAutosizingWindowSizeOverride(const IntSize&);
- const IntSize& textAutosizingWindowSizeOverride() const { return m_textAutosizingWindowSizeOverride; }
-
- void setUseWideViewport(bool);
- bool useWideViewport() const { return m_useWideViewport; }
-
- void setLoadWithOverviewMode(bool);
- bool loadWithOverviewMode() const { return m_loadWithOverviewMode; }
-
- // Only set by Layout Tests.
- void setMediaTypeOverride(const String&);
- const String& mediaTypeOverride() const { return m_mediaTypeOverride; }
-
- // Unlike areImagesEnabled, this only suppresses the network load of
- // the image URL. A cached image will still be rendered if requested.
- void setLoadsImagesAutomatically(bool);
- bool loadsImagesAutomatically() const { return m_loadsImagesAutomatically; }
-
- // Clients that execute script should call ScriptController::canExecuteScripts()
- // instead of this function. ScriptController::canExecuteScripts() checks the
- // HTML sandbox, plug-in sandboxing, and other important details.
- bool isScriptEnabled() const { return m_isScriptEnabled; }
- void setScriptEnabled(bool);
-
- SETTINGS_GETTERS_AND_SETTERS
-
- void setJavaEnabled(bool);
- bool isJavaEnabled() const { return m_isJavaEnabled; }
-
- void setImagesEnabled(bool);
- bool areImagesEnabled() const { return m_areImagesEnabled; }
-
- void setPluginsEnabled(bool);
- bool arePluginsEnabled() const { return m_arePluginsEnabled; }
-
- void setDNSPrefetchingEnabled(bool);
- bool dnsPrefetchingEnabled() const { return m_dnsPrefetchingEnabled; }
-
- void setUserStyleSheetLocation(const KURL&);
- const KURL& userStyleSheetLocation() const { return m_userStyleSheetLocation; }
-
- void setCSSCustomFilterEnabled(bool enabled) { m_isCSSCustomFilterEnabled = enabled; }
- bool isCSSCustomFilterEnabled() const { return m_isCSSCustomFilterEnabled; }
-
- void setCSSStickyPositionEnabled(bool enabled) { m_cssStickyPositionEnabled = enabled; }
- bool cssStickyPositionEnabled() const { return m_cssStickyPositionEnabled; }
-
- static void setMockScrollbarsEnabled(bool flag);
- static bool mockScrollbarsEnabled();
-
- void setTouchEventEmulationEnabled(bool enabled) { m_touchEventEmulationEnabled = enabled; }
- bool isTouchEventEmulationEnabled() const { return m_touchEventEmulationEnabled; }
-
- void setOpenGLMultisamplingEnabled(bool flag);
- bool openGLMultisamplingEnabled();
-
- void setViewportEnabled(bool);
- bool viewportEnabled() const { return m_viewportEnabled; }
-
- // FIXME: This is a temporary flag and should be removed once accelerated
- // overflow scroll is ready (crbug.com/254111).
- void setCompositorDrivenAcceleratedScrollingEnabled(bool enabled) { m_compositorDrivenAcceleratedScrollingEnabled = enabled; }
- bool isCompositorDrivenAcceleratedScrollingEnabled() const { return m_compositorDrivenAcceleratedScrollingEnabled; }
-
-private:
- explicit Settings(Page*);
-
- Page* m_page;
-
- String m_mediaTypeOverride;
- KURL m_userStyleSheetLocation;
- ScriptFontFamilyMap m_standardFontFamilyMap;
- ScriptFontFamilyMap m_serifFontFamilyMap;
- ScriptFontFamilyMap m_fixedFontFamilyMap;
- ScriptFontFamilyMap m_sansSerifFontFamilyMap;
- ScriptFontFamilyMap m_cursiveFontFamilyMap;
- ScriptFontFamilyMap m_fantasyFontFamilyMap;
- ScriptFontFamilyMap m_pictographFontFamilyMap;
- float m_textAutosizingFontScaleFactor;
- IntSize m_textAutosizingWindowSizeOverride;
- bool m_textAutosizingEnabled : 1;
- bool m_useWideViewport : 1;
- bool m_loadWithOverviewMode : 1;
-
- SETTINGS_MEMBER_VARIABLES
-
- bool m_isJavaEnabled : 1;
- bool m_loadsImagesAutomatically : 1;
- bool m_areImagesEnabled : 1;
- bool m_arePluginsEnabled : 1;
- bool m_isScriptEnabled : 1;
- bool m_isCSSCustomFilterEnabled : 1;
- bool m_cssStickyPositionEnabled : 1;
- bool m_dnsPrefetchingEnabled : 1;
-
- bool m_touchEventEmulationEnabled : 1;
- bool m_openGLMultisamplingEnabled : 1;
- bool m_viewportEnabled : 1;
-
- // FIXME: This is a temporary flag and should be removed once accelerated
- // overflow scroll is ready (crbug.com/254111).
- bool m_compositorDrivenAcceleratedScrollingEnabled : 1;
-
- Timer<Settings> m_setImageLoadingSettingsTimer;
- void imageLoadingSettingsTimerFired(Timer<Settings>*);
-
- static bool gMockScrollbarsEnabled;
-};
-
-} // namespace WebCore
-
-#endif // Settings_h
diff --git a/chromium/third_party/WebKit/Source/core/page/Settings.in b/chromium/third_party/WebKit/Source/core/page/Settings.in
deleted file mode 100644
index 5383a4a0405..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/Settings.in
+++ /dev/null
@@ -1,152 +0,0 @@
-# FIXME: Add support for global settings.
-# FIXME: Add support for custom getters/setters.
-
-defaultTextEncodingName type=String
-editableLinkBehavior type=EditableLinkBehavior, initial=EditableLinkDefaultBehavior
-passwordEchoDurationInSeconds type=double, initial=1
-
-# Sets the magnification value for validation message timer. If the
-# magnification value is N, a validation message disappears automatically after
-# <message length> * N / 1000 seconds. If N is equal to or less than 0, a
-# validation message doesn't disappears automaticaly.
-validationMessageTimerMagnification type=int, initial=50
-
-# Number of pixels below which 2D canvas is rendered in software
-# even if hardware acceleration is enabled.
-# Hardware acceleration is useful for large canvases where it can avoid the
-# pixel bandwidth between the CPU and GPU. But GPU acceleration comes at
-# a price - extra back-buffer and texture copy. Small canvases are also
-# widely used for stylized fonts. Anti-aliasing text in hardware at that
-# scale is generally slower. So below a certain size it is better to
-# draw canvas in software.
-minimumAccelerated2dCanvasSize type=int, initial=257*256
-
-layoutFallbackWidth type=int, initial=980
-
-minimumFontSize type=int, initial=0, setNeedsStyleRecalcInAllFrames=1
-minimumLogicalFontSize type=int, initial=0, setNeedsStyleRecalcInAllFrames=1
-defaultFontSize type=int, initial=0, setNeedsStyleRecalcInAllFrames=1
-defaultFixedFontSize type=int, initial=0, setNeedsStyleRecalcInAllFrames=1
-
-editingBehaviorType type=EditingBehaviorType, initial=editingBehaviorTypeForPlatform()
-
-caretBrowsingEnabled initial=false
-localStorageEnabled initial=false
-allowUniversalAccessFromFileURLs initial=true
-allowFileAccessFromFileURLs initial=true
-javaScriptCanOpenWindowsAutomatically initial=false
-supportsMultipleWindows initial=true
-javaScriptCanAccessClipboard initial=false
-shouldPrintBackgrounds initial=false
-
-textAreasAreResizable initial=false, setNeedsStyleRecalcInAllFrames=1
-authorAndUserStylesEnabled initial=true, setNeedsStyleRecalcInAllFrames=1
-acceleratedCompositingEnabled initial=true, setNeedsStyleRecalcInAllFrames=1
-showRepaintCounter initial=false, setNeedsStyleRecalcInAllFrames=1
-
-shrinksStandaloneImagesToFit initial=true
-pageCacheSupportsPlugins initial=false
-needsSiteSpecificQuirks initial=false
-offlineWebApplicationCacheEnabled initial=false
-usesEncodingDetector initial=false
-allowScriptsToCloseWindows initial=false
-acceleratedFiltersEnabled initial=false
-regionBasedColumnsEnabled initial=false
-
-# FIXME: This should really be disabled by default as it makes platforms that don't support the feature download files
-# they can't use by. Leaving enabled for now to not change existing behavior.
-downloadableBinaryFontsEnabled initial=true
-
-xssAuditorEnabled initial=false
-unsafePluginPastingEnabled initial=true
-acceleratedCompositingFor3DTransformsEnabled initial=true
-acceleratedCompositingForVideoEnabled initial=true
-acceleratedCompositingForPluginsEnabled initial=true
-acceleratedCompositingForCanvasEnabled initial=true
-acceleratedCompositingForAnimationEnabled initial=true
-acceleratedCompositingForFiltersEnabled initial=false
-acceleratedCompositingForFixedPositionEnabled initial=false
-acceleratedCompositingForOverflowScrollEnabled initial=false
-acceleratedCompositingForTransitionEnabled initial=false
-acceleratedCompositingForFixedRootBackgroundEnabled initial=false
-
-# Works only in conjunction with forceCompositingMode.
-acceleratedCompositingForScrollableFramesEnabled initial=false
-compositedScrollingForFramesEnabled initial=false
-
-webGLEnabled initial=false
-webGLErrorsToConsoleEnabled initial=true
-privilegedWebGLExtensionsEnabled initial=false
-accelerated2dCanvasEnabled initial=false
-antialiased2dCanvasEnabled initial=true
-webAudioEnabled initial=false
-fullScreenEnabled initial=false
-asynchronousSpellCheckingEnabled initial=false
-memoryInfoEnabled initial=false
-
-hyperlinkAuditingEnabled initial=false
-forceCompositingMode initial=false
-allowDisplayOfInsecureContent initial=true
-allowRunningOfInsecureContent initial=true
-mediaPlaybackRequiresUserGesture initial=false
-mediaFullscreenRequiresUserGesture initial=true
-passwordEchoEnabled initial=false
-visualWordMovementEnabled initial=false
-shouldDisplaySubtitles initial=false
-shouldDisplayCaptions initial=false
-shouldDisplayTextDescriptions initial=false
-scrollingCoordinatorEnabled initial=false
-scrollAnimatorEnabled initial=true
-
-shouldRespectImageOrientation initial=false
-deviceSupportsTouch initial=false
-deviceSupportsMouse initial=true
-
-touchAdjustmentEnabled initial=true
-
-fixedPositionCreatesStackingContext initial=false
-syncXHRInDocumentsEnabled initial=true
-cookieEnabled initial=true
-mediaEnabled initial=true
-DOMPasteAllowed initial=false
-
-threadedHTMLParser initial=false
-useThreadedHTMLParserForDataURLs initial=false
-
-applyPageScaleFactorInCompositor initial=false
-
-allowCustomScrollbarInMainFrame initial=true
-webSecurityEnabled initial=true
-spatialNavigationEnabled initial=false
-
-# This setting adds a means to enable/disable touch initiated drag & drop. If
-# enabled, the user can initiate drag using long press.
-touchDragDropEnabled initial=false
-
-unifiedTextCheckerEnabled initial=defaultUnifiedTextCheckerEnabled
-
-# Some apps could have a default video poster if it is not set.
-defaultVideoPosterURL type=String
-
-smartInsertDeleteEnabled initial=defaultSmartInsertDeleteEnabled
-selectTrailingWhitespaceEnabled initial=defaultSelectTrailingWhitespaceEnabled
-
-selectionIncludesAltImageText initial=false
-useLegacyBackgroundSizeShorthandBehavior initial=false
-# This quirk is to maintain compatibility with Android apps built on
-# the Android SDK prior to and including version 18. Presumably, this
-# can be removed any time after 2015. See http://crbug.com/282130.
-viewportMetaZeroValuesQuirk initial=false
-# Another Android SDK <= 18 quirk, removable 2015. http://crbug.com/295287
-ignoreMainFrameOverflowHiddenQuirk initial=false
-# This quirk is to maintain compatibility with Android apps.
-# It will be possible to remove it once WebSettings.{get|set}UseWideViewPort
-# API function will be removed. See http://crbug.com/288037.
-wideViewportQuirkEnabled initial=false
-
-# This setting enables touch based text selection and editing.
-touchEditingEnabled initial=false
-
-experimentalWebSocketEnabled initial=false
-pinchVirtualViewportEnabled initial=false
-useSolidColorScrollbars initial=false
diff --git a/chromium/third_party/WebKit/Source/core/page/SpatialNavigation.cpp b/chromium/third_party/WebKit/Source/core/page/SpatialNavigation.cpp
index 37426cb6a4d..b3c5c869179 100644
--- a/chromium/third_party/WebKit/Source/core/page/SpatialNavigation.cpp
+++ b/chromium/third_party/WebKit/Source/core/page/SpatialNavigation.cpp
@@ -30,16 +30,15 @@
#include "core/page/SpatialNavigation.h"
#include "HTMLNames.h"
-#include "core/dom/Node.h"
#include "core/html/HTMLAreaElement.h"
#include "core/html/HTMLImageElement.h"
-#include "core/page/Frame.h"
+#include "core/frame/Frame.h"
#include "core/page/FrameTree.h"
-#include "core/page/FrameView.h"
+#include "core/frame/FrameView.h"
#include "core/page/Page.h"
-#include "core/page/Settings.h"
-#include "core/platform/graphics/IntRect.h"
+#include "core/frame/Settings.h"
#include "core/rendering/RenderLayer.h"
+#include "platform/geometry/IntRect.h"
namespace WebCore {
@@ -396,7 +395,7 @@ bool scrollInDirection(Node* container, FocusDirection direction)
return false;
}
- container->renderBox()->enclosingLayer()->scrollByRecursively(IntSize(dx, dy));
+ container->renderBox()->scrollByRecursively(IntSize(dx, dy));
return true;
}
@@ -502,7 +501,7 @@ bool canScrollInDirection(const Frame* frame, FocusDirection direction)
static LayoutRect rectToAbsoluteCoordinates(Frame* initialFrame, const LayoutRect& initialRect)
{
LayoutRect rect = initialRect;
- for (Frame* frame = initialFrame; frame; frame = frame->tree()->parent()) {
+ for (Frame* frame = initialFrame; frame; frame = frame->tree().parent()) {
if (Element* element = frame->ownerElement()) {
do {
rect.move(element->offsetLeft(), element->offsetTop());
diff --git a/chromium/third_party/WebKit/Source/core/page/SpatialNavigation.h b/chromium/third_party/WebKit/Source/core/page/SpatialNavigation.h
index e56c734ca56..1e2f56c40df 100644
--- a/chromium/third_party/WebKit/Source/core/page/SpatialNavigation.h
+++ b/chromium/third_party/WebKit/Source/core/page/SpatialNavigation.h
@@ -24,7 +24,7 @@
#include "core/dom/Node.h"
#include "core/html/HTMLFrameOwnerElement.h"
#include "core/page/FocusDirection.h"
-#include "core/platform/graphics/LayoutRect.h"
+#include "platform/geometry/LayoutRect.h"
#include <limits>
diff --git a/chromium/third_party/WebKit/Source/core/page/SpeechInput.cpp b/chromium/third_party/WebKit/Source/core/page/SpeechInput.cpp
deleted file mode 100644
index 0ad8c86e0e1..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/SpeechInput.cpp
+++ /dev/null
@@ -1,131 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/page/SpeechInput.h"
-
-#if ENABLE(INPUT_SPEECH)
-
-#include "core/page/SpeechInputClient.h"
-#include "core/page/SpeechInputListener.h"
-#include "wtf/PassOwnPtr.h"
-
-namespace WebCore {
-
-SpeechInput::SpeechInput(SpeechInputClient* client)
- : m_client(client)
- , m_nextListenerId(1)
-{
- m_client->setListener(this);
-}
-
-SpeechInput::~SpeechInput()
-{
- m_client->setListener(0);
-}
-
-PassOwnPtr<SpeechInput> SpeechInput::create(SpeechInputClient* client)
-{
- return adoptPtr(new SpeechInput(client));
-}
-
-int SpeechInput::registerListener(SpeechInputListener* listener)
-{
-#if defined(DEBUG)
- // Check if already present.
- for (HashMap<int, SpeechInputListener*>::iterator it = m_listeners.begin(); it != m_listeners.end(); ++it)
- ASSERT(it->value != listener);
-#endif
-
- m_listeners.add(m_nextListenerId, listener);
- return m_nextListenerId++;
-}
-
-void SpeechInput::unregisterListener(int listenerId)
-{
- if (m_listeners.contains(listenerId))
- m_listeners.remove(listenerId);
-}
-
-void SpeechInput::didCompleteRecording(int listenerId)
-{
- // Don't assert if not present as the element might have been removed by the page while
- // this event was on the way.
- if (m_listeners.contains(listenerId))
- m_listeners.get(listenerId)->didCompleteRecording(listenerId);
-}
-
-void SpeechInput::didCompleteRecognition(int listenerId)
-{
- // Don't assert if not present as the element might have been removed by the page while
- // this event was on the way.
- if (m_listeners.contains(listenerId))
- m_listeners.get(listenerId)->didCompleteRecognition(listenerId);
-}
-
-void SpeechInput::setRecognitionResult(int listenerId, const SpeechInputResultArray& result)
-{
- // Don't assert if not present as the element might have been removed by the page while
- // this event was on the way.
- if (m_listeners.contains(listenerId))
- m_listeners.get(listenerId)->setRecognitionResult(listenerId, result);
-}
-
-bool SpeechInput::startRecognition(int listenerId, const IntRect& elementRect, const AtomicString& language, const String& grammar, SecurityOrigin* origin)
-{
- ASSERT(m_listeners.contains(listenerId));
- return m_client->startRecognition(listenerId, elementRect, language, grammar, origin);
-}
-
-void SpeechInput::stopRecording(int listenerId)
-{
- ASSERT(m_listeners.contains(listenerId));
- m_client->stopRecording(listenerId);
-}
-
-void SpeechInput::cancelRecognition(int listenerId)
-{
- ASSERT(m_listeners.contains(listenerId));
- m_client->cancelRecognition(listenerId);
-}
-
-const char* SpeechInput::supplementName()
-{
- return "SpeechInput";
-}
-
-void provideSpeechInputTo(Page* page, SpeechInputClient* client)
-{
- SpeechInput::provideTo(page, SpeechInput::supplementName(), SpeechInput::create(client));
-}
-
-} // namespace WebCore
-
-#endif // ENABLE(INPUT_SPEECH)
diff --git a/chromium/third_party/WebKit/Source/core/page/SpeechInput.h b/chromium/third_party/WebKit/Source/core/page/SpeechInput.h
deleted file mode 100644
index 8544e2136b3..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/SpeechInput.h
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SpeechInput_h
-#define SpeechInput_h
-
-#if ENABLE(INPUT_SPEECH)
-
-#include "core/page/Page.h"
-#include "core/page/SpeechInputListener.h"
-#include "wtf/Forward.h"
-#include "wtf/HashMap.h"
-
-namespace WebCore {
-
-class IntRect;
-class SecurityOrigin;
-class SpeechInputClient;
-class SpeechInputListener;
-
-// This class connects the input elements requiring speech input with the platform specific
-// speech recognition engine. It provides methods for the input elements to activate speech
-// recognition and methods for the speech recognition engine to return back the results.
-class SpeechInput : public SpeechInputListener,
- public Supplement<Page> {
- WTF_MAKE_NONCOPYABLE(SpeechInput);
-public:
- virtual ~SpeechInput();
-
- static PassOwnPtr<SpeechInput> create(SpeechInputClient*);
- static const char* supplementName();
- static SpeechInput* from(Page* page) { return static_cast<SpeechInput*>(Supplement<Page>::from(page, supplementName())); }
-
- // Generates a unique ID for the given listener to be used for speech requests.
- // This should be the first call made by listeners before anything else.
- int registerListener(SpeechInputListener*);
-
- // Invoked when the listener is done with recording or getting destroyed.
- // Failure to unregister may result in crashes if there were any pending speech events.
- void unregisterListener(int);
-
- // Methods invoked by the input elements.
- bool startRecognition(int listenerId, const IntRect& elementRect, const AtomicString& language, const String& grammar, SecurityOrigin*);
- void stopRecording(int);
- void cancelRecognition(int);
-
- // SpeechInputListener methods.
- virtual void didCompleteRecording(int);
- virtual void didCompleteRecognition(int);
- virtual void setRecognitionResult(int, const SpeechInputResultArray&);
-
-private:
- explicit SpeechInput(SpeechInputClient*);
-
- SpeechInputClient* m_client;
- HashMap<int, SpeechInputListener*> m_listeners;
- int m_nextListenerId;
-};
-
-} // namespace WebCore
-
-#endif // ENABLE(INPUT_SPEECH)
-
-#endif // SpeechInput_h
diff --git a/chromium/third_party/WebKit/Source/core/page/SpeechInputEvent.cpp b/chromium/third_party/WebKit/Source/core/page/SpeechInputEvent.cpp
deleted file mode 100644
index fec8d2780dd..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/SpeechInputEvent.cpp
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#if ENABLE(INPUT_SPEECH)
-
-#include "core/page/SpeechInputEvent.h"
-
-#include "core/dom/EventNames.h"
-
-namespace WebCore {
-
-PassRefPtr<SpeechInputEvent> SpeechInputEvent::create()
-{
- return adoptRef(new SpeechInputEvent);
-}
-
-PassRefPtr<SpeechInputEvent> SpeechInputEvent::create(const AtomicString& eventType, const SpeechInputResultArray& results)
-{
- return adoptRef(new SpeechInputEvent(eventType, results));
-}
-
-SpeechInputEvent::SpeechInputEvent()
-{
- ScriptWrappable::init(this);
-}
-
-SpeechInputEvent::SpeechInputEvent(const AtomicString& eventType, const SpeechInputResultArray& results)
- : Event(eventType, true, false) // Can bubble, not cancelable
- , m_results(SpeechInputResultList::create(results))
-{
- ScriptWrappable::init(this);
-}
-
-SpeechInputEvent::~SpeechInputEvent()
-{
-}
-
-const AtomicString& SpeechInputEvent::interfaceName() const
-{
- return eventNames().interfaceForSpeechInputEvent;
-}
-
-} // namespace WebCore
-
-#endif // ENABLE(INPUT_SPEECH)
diff --git a/chromium/third_party/WebKit/Source/core/page/SpeechInputEvent.h b/chromium/third_party/WebKit/Source/core/page/SpeechInputEvent.h
deleted file mode 100644
index 8166c0c927f..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/SpeechInputEvent.h
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SpeechInputEvent_h
-#define SpeechInputEvent_h
-
-#if ENABLE(INPUT_SPEECH)
-
-#include "core/dom/Event.h"
-#include "core/page/SpeechInputResultList.h"
-
-#include "wtf/PassRefPtr.h"
-
-namespace WebCore {
-
-class SpeechInputEvent : public Event {
-public:
- static PassRefPtr<SpeechInputEvent> create();
- static PassRefPtr<SpeechInputEvent> create(const AtomicString& eventType, const SpeechInputResultArray& results);
- ~SpeechInputEvent();
-
- SpeechInputResultList* results() const { return m_results.get(); }
-
- virtual const AtomicString& interfaceName() const;
-
-private:
- SpeechInputEvent();
- SpeechInputEvent(const AtomicString& eventType, const SpeechInputResultArray& results);
-
- RefPtr<SpeechInputResultList> m_results;
-};
-
-} // namespace WebCore
-
-#endif // ENABLE(INPUT_SPEECH)
-
-#endif // SpeechInputEvent_h
diff --git a/chromium/third_party/WebKit/Source/core/page/SpeechInputListener.h b/chromium/third_party/WebKit/Source/core/page/SpeechInputListener.h
deleted file mode 100644
index d9f501c4bf9..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/SpeechInputListener.h
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SpeechInputListener_h
-#define SpeechInputListener_h
-
-#if ENABLE(INPUT_SPEECH)
-
-#include "core/page/SpeechInputResult.h"
-#include "wtf/Forward.h"
-
-namespace WebCore {
-
-// Interface to be implemented by the element which invokes SpeechInput.
-class SpeechInputListener {
-public:
- // Informs that audio recording has completed and recognition is underway.
- virtual void didCompleteRecording(int requestId) = 0;
-
- // Informs that speech recognition has completed. This gets invoked irrespective of whether
- // recognition was succesful or not, whether setRecognitionResult() was invoked or not. The
- // handler typically frees up any temporary resources allocated and waits for the next speech
- // recognition request.
- virtual void didCompleteRecognition(int requestId) = 0;
-
- // Gives results from speech recognition, either partial or the final results.
- // This method can potentially get called multiple times if there are partial results
- // available as the user keeps speaking. If the speech could not be recognized properly
- // or if there was any other errors in the process, this method may never be called.
- virtual void setRecognitionResult(int requestId, const SpeechInputResultArray&) = 0;
-
-protected:
- virtual ~SpeechInputListener() { }
-};
-
-} // namespace WebCore
-
-#endif // ENABLE(INPUT_SPEECH)
-
-#endif // SpeechInputListener_h
diff --git a/chromium/third_party/WebKit/Source/core/page/SpeechInputResult.cpp b/chromium/third_party/WebKit/Source/core/page/SpeechInputResult.cpp
deleted file mode 100644
index 82ef65b8580..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/SpeechInputResult.cpp
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/page/SpeechInputResult.h"
-
-#if ENABLE(INPUT_SPEECH)
-
-namespace WebCore {
-
-PassRefPtr<SpeechInputResult> SpeechInputResult::create(const String& utterance, double confidence)
-{
- return adoptRef(new SpeechInputResult(utterance, confidence));
-}
-
-PassRefPtr<SpeechInputResult> SpeechInputResult::create(const SpeechInputResult& source)
-{
- return adoptRef(new SpeechInputResult(source.m_utterance, source.m_confidence));
-}
-
-SpeechInputResult::SpeechInputResult(const String& utterance, double confidence)
- : m_utterance(utterance)
- , m_confidence(confidence)
-{
- ScriptWrappable::init(this);
-}
-
-double SpeechInputResult::confidence() const
-{
- return m_confidence;
-}
-
-const String& SpeechInputResult::utterance() const
-{
- return m_utterance;
-}
-
-} // namespace WebCore
-
-#endif // ENABLE(INPUT_SPEECH)
diff --git a/chromium/third_party/WebKit/Source/core/page/SpeechInputResultList.cpp b/chromium/third_party/WebKit/Source/core/page/SpeechInputResultList.cpp
deleted file mode 100644
index 89905a101ba..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/SpeechInputResultList.cpp
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/page/SpeechInputResultList.h"
-
-#if ENABLE(INPUT_SPEECH)
-
-namespace WebCore {
-
-PassRefPtr<SpeechInputResultList> SpeechInputResultList::create(const SpeechInputResultArray& results)
-{
- return adoptRef(new SpeechInputResultList(results));
-}
-
-SpeechInputResult* SpeechInputResultList::item(unsigned index)
-{
- return index >= m_results.size() ? 0 : m_results[index].get();
-}
-
-SpeechInputResultList::SpeechInputResultList(const SpeechInputResultArray& results)
- : m_results(results) // Takes a copy of the array of RefPtrs.
-{
- ScriptWrappable::init(this);
-}
-
-} // namespace WebCore
-
-#endif // ENABLE(INPUT_SPEECH)
diff --git a/chromium/third_party/WebKit/Source/core/page/SpeechInputResultList.h b/chromium/third_party/WebKit/Source/core/page/SpeechInputResultList.h
deleted file mode 100644
index eef6ca3624b..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/SpeechInputResultList.h
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SpeechInputResultList_h
-#define SpeechInputResultList_h
-
-#if ENABLE(INPUT_SPEECH)
-
-#include "bindings/v8/ScriptWrappable.h"
-#include "core/page/SpeechInputResult.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-
-namespace WebCore {
-
-class SpeechInputResultList : public RefCounted<SpeechInputResultList>, public ScriptWrappable {
-public:
- static PassRefPtr<SpeechInputResultList> create(const SpeechInputResultArray& results);
-
- // Methods from the IDL.
- size_t length() { return m_results.size(); }
- SpeechInputResult* item(unsigned index);
-
-private:
- explicit SpeechInputResultList(const SpeechInputResultArray& results);
-
- SpeechInputResultArray m_results;
-};
-
-} // namespace WebCore
-
-#endif // ENABLE(INPUT_SPEECH)
-
-#endif // SpeechInputResultList_h
diff --git a/chromium/third_party/WebKit/Source/core/page/SpellCheckerClient.h b/chromium/third_party/WebKit/Source/core/page/SpellCheckerClient.h
new file mode 100644
index 00000000000..73a49e5852d
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/page/SpellCheckerClient.h
@@ -0,0 +1,53 @@
+/*
+ * Copyright (C) 2006, 2007 Apple Inc. All rights reserved.
+ * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SpellCheckerClient_h
+#define SpellCheckerClient_h
+
+#include "wtf/Forward.h"
+
+namespace WebCore {
+
+class TextCheckerClient;
+
+class SpellCheckerClient {
+public:
+ virtual ~SpellCheckerClient() { }
+
+ virtual bool isContinuousSpellCheckingEnabled() = 0;
+ virtual void toggleContinuousSpellChecking() = 0;
+ virtual bool isGrammarCheckingEnabled() = 0;
+
+ virtual TextCheckerClient& textChecker() = 0;
+
+ virtual void updateSpellingUIWithMisspelledWord(const WTF::String&) = 0;
+ virtual void showSpellingUI(bool show) = 0;
+ virtual bool spellingUIIsShowing() = 0;
+};
+
+}
+
+#endif // SpellCheckerClient_h
diff --git a/chromium/third_party/WebKit/Source/core/page/SuspendableTimer.cpp b/chromium/third_party/WebKit/Source/core/page/SuspendableTimer.cpp
deleted file mode 100644
index 471f68cef5d..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/SuspendableTimer.cpp
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * Copyright (C) 2008 Apple Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-#include "config.h"
-#include "core/page/SuspendableTimer.h"
-
-namespace WebCore {
-
-SuspendableTimer::SuspendableTimer(ScriptExecutionContext* context)
- : ActiveDOMObject(context)
- , m_nextFireInterval(0)
- , m_repeatInterval(0)
- , m_active(false)
-#if !ASSERT_DISABLED
- , m_suspended(false)
-#endif
-{
-}
-
-SuspendableTimer::~SuspendableTimer()
-{
-}
-
-bool SuspendableTimer::hasPendingActivity() const
-{
- return isActive();
-}
-
-void SuspendableTimer::stop()
-{
- TimerBase::stop();
-}
-
-void SuspendableTimer::suspend(ReasonForSuspension)
-{
-#if !ASSERT_DISABLED
- ASSERT(!m_suspended);
- m_suspended = true;
-#endif
- m_active = isActive();
- if (m_active) {
- m_nextFireInterval = nextUnalignedFireInterval();
- m_repeatInterval = repeatInterval();
- TimerBase::stop();
- }
-}
-
-void SuspendableTimer::resume()
-{
-#if !ASSERT_DISABLED
- ASSERT(m_suspended);
- m_suspended = false;
-#endif
- if (m_active)
- start(m_nextFireInterval, m_repeatInterval);
-}
-
-bool SuspendableTimer::canSuspend() const
-{
- return true;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/page/SuspendableTimer.h b/chromium/third_party/WebKit/Source/core/page/SuspendableTimer.h
deleted file mode 100644
index 8d8f539b6aa..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/SuspendableTimer.h
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Copyright (C) 2008 Apple Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-#ifndef SuspendableTimer_h
-#define SuspendableTimer_h
-
-#include "core/dom/ActiveDOMObject.h"
-#include "core/platform/Timer.h"
-
-namespace WebCore {
-
-class SuspendableTimer : public TimerBase, public ActiveDOMObject {
-public:
- explicit SuspendableTimer(ScriptExecutionContext*);
- virtual ~SuspendableTimer();
-
- // ActiveDOMObject
- virtual bool hasPendingActivity() const;
- virtual void stop();
- virtual bool canSuspend() const;
- virtual void suspend(ReasonForSuspension);
- virtual void resume();
-
-private:
- virtual void fired() = 0;
-
- double m_nextFireInterval;
- double m_repeatInterval;
- bool m_active;
-#if !ASSERT_DISABLED
- bool m_suspended;
-#endif
-};
-
-} // namespace WebCore
-
-#endif // SuspendableTimer_h
-
diff --git a/chromium/third_party/WebKit/Source/core/page/TouchAdjustment.cpp b/chromium/third_party/WebKit/Source/core/page/TouchAdjustment.cpp
index fcd5901d796..be85ae4f143 100644
--- a/chromium/third_party/WebKit/Source/core/page/TouchAdjustment.cpp
+++ b/chromium/third_party/WebKit/Source/core/page/TouchAdjustment.cpp
@@ -27,17 +27,16 @@
#include "core/dom/Text.h"
#include "core/editing/Editor.h"
#include "core/html/HTMLFrameOwnerElement.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameView.h"
-#include "core/platform/graphics/FloatPoint.h"
-#include "core/platform/graphics/FloatQuad.h"
-#include "core/platform/graphics/IntPoint.h"
-#include "core/platform/graphics/IntSize.h"
-#include "core/platform/text/TextBreakIterator.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
#include "core/rendering/RenderBox.h"
#include "core/rendering/RenderObject.h"
#include "core/rendering/RenderText.h"
#include "core/rendering/style/RenderStyle.h"
+#include "platform/geometry/FloatPoint.h"
+#include "platform/geometry/FloatQuad.h"
+#include "platform/geometry/IntSize.h"
+#include "platform/text/TextBreakIterator.h"
namespace WebCore {
@@ -151,18 +150,18 @@ static inline void appendContextSubtargetsForNode(Node* node, SubtargetGeometryL
if (!node->isTextNode())
return appendBasicSubtargetsForNode(node, subtargets);
- Text* textNode = static_cast<WebCore::Text*>(node);
- RenderText* textRenderer = static_cast<RenderText*>(textNode->renderer());
+ Text* textNode = toText(node);
+ RenderText* textRenderer = toRenderText(textNode->renderer());
if (textRenderer->frame()->editor().behavior().shouldSelectOnContextualMenuClick()) {
// Make subtargets out of every word.
String textValue = textNode->data();
TextBreakIterator* wordIterator = wordBreakIterator(textValue, 0, textValue.length());
- int lastOffset = textBreakFirst(wordIterator);
+ int lastOffset = wordIterator->first();
if (lastOffset == -1)
return;
int offset;
- while ((offset = textBreakNext(wordIterator)) != -1) {
+ while ((offset = wordIterator->next()) != -1) {
if (isWordTextBreak(wordIterator)) {
Vector<FloatQuad> quads;
textRenderer->absoluteQuadsForRange(quads, lastOffset, offset);
diff --git a/chromium/third_party/WebKit/Source/core/page/TouchAdjustment.h b/chromium/third_party/WebKit/Source/core/page/TouchAdjustment.h
index 16bfe856e1d..2bd66d637d6 100644
--- a/chromium/third_party/WebKit/Source/core/page/TouchAdjustment.h
+++ b/chromium/third_party/WebKit/Source/core/page/TouchAdjustment.h
@@ -20,8 +20,8 @@
#ifndef TouchAdjustment_h
#define TouchAdjustment_h
-#include "core/platform/graphics/IntPoint.h"
-#include "core/platform/graphics/IntRect.h"
+#include "platform/geometry/IntPoint.h"
+#include "platform/geometry/IntRect.h"
#include "wtf/RefPtr.h"
#include "wtf/Vector.h"
diff --git a/chromium/third_party/WebKit/Source/core/page/TouchDisambiguation.cpp b/chromium/third_party/WebKit/Source/core/page/TouchDisambiguation.cpp
index 6638ce39c96..5fda7d8dc93 100644
--- a/chromium/third_party/WebKit/Source/core/page/TouchDisambiguation.cpp
+++ b/chromium/third_party/WebKit/Source/core/page/TouchDisambiguation.cpp
@@ -40,8 +40,8 @@
#include "core/dom/NodeTraversal.h"
#include "core/html/HTMLHtmlElement.h"
#include "core/page/EventHandler.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameView.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
#include "core/rendering/HitTestResult.h"
#include "core/rendering/RenderBlock.h"
@@ -59,11 +59,11 @@ static IntRect boundingBoxForEventNodes(Node* eventNode)
while (node) {
// Skip the whole sub-tree if the node doesn't propagate events.
if (node != eventNode && node->willRespondToMouseClickEvents()) {
- node = NodeTraversal::nextSkippingChildren(node, eventNode);
+ node = NodeTraversal::nextSkippingChildren(*node, eventNode);
continue;
}
result.unite(node->pixelSnappedBoundingBox());
- node = NodeTraversal::next(node, eventNode);
+ node = NodeTraversal::next(*node, eventNode);
}
return eventNode->document().view()->contentsToWindow(result);
}
@@ -97,7 +97,7 @@ void findGoodTouchTargets(const IntRect& touchBox, Frame* mainFrame, Vector<IntR
IntPoint touchPoint = touchBox.center();
IntPoint contentsPoint = mainFrame->view()->windowToContents(touchPoint);
- HitTestResult result = mainFrame->eventHandler()->hitTestResultAtPoint(contentsPoint, HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::DisallowShadowContent, IntSize(touchPointPadding, touchPointPadding));
+ HitTestResult result = mainFrame->eventHandler().hitTestResultAtPoint(contentsPoint, HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent, IntSize(touchPointPadding, touchPointPadding));
const ListHashSet<RefPtr<Node> >& hitResults = result.rectBasedTestResult();
// Blacklist nodes that are container of disambiguated nodes.
diff --git a/chromium/third_party/WebKit/Source/core/page/UseCounter.cpp b/chromium/third_party/WebKit/Source/core/page/UseCounter.cpp
deleted file mode 100644
index 652e04e6f16..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/UseCounter.cpp
+++ /dev/null
@@ -1,717 +0,0 @@
-
-/*
- * Copyright (C) 2012 Google, Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY GOOGLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/page/UseCounter.h"
-
-#include "core/css/CSSStyleSheet.h"
-#include "core/css/StyleSheetContents.h"
-#include "core/dom/Document.h"
-#include "core/dom/ScriptExecutionContext.h"
-#include "core/page/DOMWindow.h"
-#include "core/page/Page.h"
-#include "core/page/PageConsole.h"
-#include "core/platform/HistogramSupport.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-static int totalPagesMeasuredCSSSampleId() { return 1; }
-
-// FIXME : This mapping should be autogenerated. This function should
-// be moved to a separate file and a script run at build time
-// to detect new values in CSSPropertyID and add them to the
-// end of this function. This file would be checked in.
-// https://code.google.com/p/chromium/issues/detail?id=234940
-int UseCounter::mapCSSPropertyIdToCSSSampleIdForHistogram(int id)
-{
- CSSPropertyID cssPropertyID = convertToCSSPropertyID(id);
-
- switch (cssPropertyID) {
- // Begin at 2, because 1 is reserved for totalPagesMeasuredCSSSampleId.
- case CSSPropertyColor: return 2;
- case CSSPropertyDirection: return 3;
- case CSSPropertyDisplay: return 4;
- case CSSPropertyFont: return 5;
- case CSSPropertyFontFamily: return 6;
- case CSSPropertyFontSize: return 7;
- case CSSPropertyFontStyle: return 8;
- case CSSPropertyFontVariant: return 9;
- case CSSPropertyFontWeight: return 10;
- case CSSPropertyTextRendering: return 11;
- case CSSPropertyWebkitFontFeatureSettings: return 12;
- case CSSPropertyWebkitFontKerning: return 13;
- case CSSPropertyWebkitFontSmoothing: return 14;
- case CSSPropertyWebkitFontVariantLigatures: return 15;
- case CSSPropertyWebkitLocale: return 16;
- case CSSPropertyWebkitTextOrientation: return 17;
- case CSSPropertyWebkitWritingMode: return 18;
- case CSSPropertyZoom: return 19;
- case CSSPropertyLineHeight: return 20;
- case CSSPropertyBackground: return 21;
- case CSSPropertyBackgroundAttachment: return 22;
- case CSSPropertyBackgroundClip: return 23;
- case CSSPropertyBackgroundColor: return 24;
- case CSSPropertyBackgroundImage: return 25;
- case CSSPropertyBackgroundOrigin: return 26;
- case CSSPropertyBackgroundPosition: return 27;
- case CSSPropertyBackgroundPositionX: return 28;
- case CSSPropertyBackgroundPositionY: return 29;
- case CSSPropertyBackgroundRepeat: return 30;
- case CSSPropertyBackgroundRepeatX: return 31;
- case CSSPropertyBackgroundRepeatY: return 32;
- case CSSPropertyBackgroundSize: return 33;
- case CSSPropertyBorder: return 34;
- case CSSPropertyBorderBottom: return 35;
- case CSSPropertyBorderBottomColor: return 36;
- case CSSPropertyBorderBottomLeftRadius: return 37;
- case CSSPropertyBorderBottomRightRadius: return 38;
- case CSSPropertyBorderBottomStyle: return 39;
- case CSSPropertyBorderBottomWidth: return 40;
- case CSSPropertyBorderCollapse: return 41;
- case CSSPropertyBorderColor: return 42;
- case CSSPropertyBorderImage: return 43;
- case CSSPropertyBorderImageOutset: return 44;
- case CSSPropertyBorderImageRepeat: return 45;
- case CSSPropertyBorderImageSlice: return 46;
- case CSSPropertyBorderImageSource: return 47;
- case CSSPropertyBorderImageWidth: return 48;
- case CSSPropertyBorderLeft: return 49;
- case CSSPropertyBorderLeftColor: return 50;
- case CSSPropertyBorderLeftStyle: return 51;
- case CSSPropertyBorderLeftWidth: return 52;
- case CSSPropertyBorderRadius: return 53;
- case CSSPropertyBorderRight: return 54;
- case CSSPropertyBorderRightColor: return 55;
- case CSSPropertyBorderRightStyle: return 56;
- case CSSPropertyBorderRightWidth: return 57;
- case CSSPropertyBorderSpacing: return 58;
- case CSSPropertyBorderStyle: return 59;
- case CSSPropertyBorderTop: return 60;
- case CSSPropertyBorderTopColor: return 61;
- case CSSPropertyBorderTopLeftRadius: return 62;
- case CSSPropertyBorderTopRightRadius: return 63;
- case CSSPropertyBorderTopStyle: return 64;
- case CSSPropertyBorderTopWidth: return 65;
- case CSSPropertyBorderWidth: return 66;
- case CSSPropertyBottom: return 67;
- case CSSPropertyBoxShadow: return 68;
- case CSSPropertyBoxSizing: return 69;
- case CSSPropertyCaptionSide: return 70;
- case CSSPropertyClear: return 71;
- case CSSPropertyClip: return 72;
- case CSSPropertyWebkitClipPath: return 73;
- case CSSPropertyContent: return 74;
- case CSSPropertyCounterIncrement: return 75;
- case CSSPropertyCounterReset: return 76;
- case CSSPropertyCursor: return 77;
- case CSSPropertyEmptyCells: return 78;
- case CSSPropertyFloat: return 79;
- case CSSPropertyFontStretch: return 80;
- case CSSPropertyHeight: return 81;
- case CSSPropertyImageRendering: return 82;
- case CSSPropertyLeft: return 83;
- case CSSPropertyLetterSpacing: return 84;
- case CSSPropertyListStyle: return 85;
- case CSSPropertyListStyleImage: return 86;
- case CSSPropertyListStylePosition: return 87;
- case CSSPropertyListStyleType: return 88;
- case CSSPropertyMargin: return 89;
- case CSSPropertyMarginBottom: return 90;
- case CSSPropertyMarginLeft: return 91;
- case CSSPropertyMarginRight: return 92;
- case CSSPropertyMarginTop: return 93;
- case CSSPropertyMaxHeight: return 94;
- case CSSPropertyMaxWidth: return 95;
- case CSSPropertyMinHeight: return 96;
- case CSSPropertyMinWidth: return 97;
- case CSSPropertyOpacity: return 98;
- case CSSPropertyOrphans: return 99;
- case CSSPropertyOutline: return 100;
- case CSSPropertyOutlineColor: return 101;
- case CSSPropertyOutlineOffset: return 102;
- case CSSPropertyOutlineStyle: return 103;
- case CSSPropertyOutlineWidth: return 104;
- case CSSPropertyOverflow: return 105;
- case CSSPropertyOverflowWrap: return 106;
- case CSSPropertyOverflowX: return 107;
- case CSSPropertyOverflowY: return 108;
- case CSSPropertyPadding: return 109;
- case CSSPropertyPaddingBottom: return 110;
- case CSSPropertyPaddingLeft: return 111;
- case CSSPropertyPaddingRight: return 112;
- case CSSPropertyPaddingTop: return 113;
- case CSSPropertyPage: return 114;
- case CSSPropertyPageBreakAfter: return 115;
- case CSSPropertyPageBreakBefore: return 116;
- case CSSPropertyPageBreakInside: return 117;
- case CSSPropertyPointerEvents: return 118;
- case CSSPropertyPosition: return 119;
- case CSSPropertyQuotes: return 120;
- case CSSPropertyResize: return 121;
- case CSSPropertyRight: return 122;
- case CSSPropertySize: return 123;
- case CSSPropertySrc: return 124;
- case CSSPropertySpeak: return 125;
- case CSSPropertyTableLayout: return 126;
- case CSSPropertyTabSize: return 127;
- case CSSPropertyTextAlign: return 128;
- case CSSPropertyTextDecoration: return 129;
- case CSSPropertyTextIndent: return 130;
- /* Removed CSSPropertyTextLineThrough - 131 */
- case CSSPropertyTextLineThroughColor: return 132;
- case CSSPropertyTextLineThroughMode: return 133;
- case CSSPropertyTextLineThroughStyle: return 134;
- case CSSPropertyTextLineThroughWidth: return 135;
- case CSSPropertyTextOverflow: return 136;
- /* Removed CSSPropertyTextOverline - 137 */
- case CSSPropertyTextOverlineColor: return 138;
- case CSSPropertyTextOverlineMode: return 139;
- case CSSPropertyTextOverlineStyle: return 140;
- case CSSPropertyTextOverlineWidth: return 141;
- case CSSPropertyTextShadow: return 142;
- case CSSPropertyTextTransform: return 143;
- /* Removed CSSPropertyTextUnderline - 144 */
- case CSSPropertyTextUnderlineColor: return 145;
- case CSSPropertyTextUnderlineMode: return 146;
- case CSSPropertyTextUnderlineStyle: return 147;
- case CSSPropertyTextUnderlineWidth: return 148;
- case CSSPropertyTop: return 149;
- case CSSPropertyTransition: return 150;
- case CSSPropertyTransitionDelay: return 151;
- case CSSPropertyTransitionDuration: return 152;
- case CSSPropertyTransitionProperty: return 153;
- case CSSPropertyTransitionTimingFunction: return 154;
- case CSSPropertyUnicodeBidi: return 155;
- case CSSPropertyUnicodeRange: return 156;
- case CSSPropertyVerticalAlign: return 157;
- case CSSPropertyVisibility: return 158;
- case CSSPropertyWhiteSpace: return 159;
- case CSSPropertyWidows: return 160;
- case CSSPropertyWidth: return 161;
- case CSSPropertyWordBreak: return 162;
- case CSSPropertyWordSpacing: return 163;
- case CSSPropertyWordWrap: return 164;
- case CSSPropertyZIndex: return 165;
- case CSSPropertyWebkitAnimation: return 166;
- case CSSPropertyWebkitAnimationDelay: return 167;
- case CSSPropertyWebkitAnimationDirection: return 168;
- case CSSPropertyWebkitAnimationDuration: return 169;
- case CSSPropertyWebkitAnimationFillMode: return 170;
- case CSSPropertyWebkitAnimationIterationCount: return 171;
- case CSSPropertyWebkitAnimationName: return 172;
- case CSSPropertyWebkitAnimationPlayState: return 173;
- case CSSPropertyWebkitAnimationTimingFunction: return 174;
- case CSSPropertyWebkitAppearance: return 175;
- case CSSPropertyWebkitAspectRatio: return 176;
- case CSSPropertyWebkitBackfaceVisibility: return 177;
- case CSSPropertyWebkitBackgroundClip: return 178;
- case CSSPropertyWebkitBackgroundComposite: return 179;
- case CSSPropertyWebkitBackgroundOrigin: return 180;
- case CSSPropertyWebkitBackgroundSize: return 181;
- case CSSPropertyWebkitBorderAfter: return 182;
- case CSSPropertyWebkitBorderAfterColor: return 183;
- case CSSPropertyWebkitBorderAfterStyle: return 184;
- case CSSPropertyWebkitBorderAfterWidth: return 185;
- case CSSPropertyWebkitBorderBefore: return 186;
- case CSSPropertyWebkitBorderBeforeColor: return 187;
- case CSSPropertyWebkitBorderBeforeStyle: return 188;
- case CSSPropertyWebkitBorderBeforeWidth: return 189;
- case CSSPropertyWebkitBorderEnd: return 190;
- case CSSPropertyWebkitBorderEndColor: return 191;
- case CSSPropertyWebkitBorderEndStyle: return 192;
- case CSSPropertyWebkitBorderEndWidth: return 193;
- case CSSPropertyWebkitBorderFit: return 194;
- case CSSPropertyWebkitBorderHorizontalSpacing: return 195;
- case CSSPropertyWebkitBorderImage: return 196;
- case CSSPropertyWebkitBorderRadius: return 197;
- case CSSPropertyWebkitBorderStart: return 198;
- case CSSPropertyWebkitBorderStartColor: return 199;
- case CSSPropertyWebkitBorderStartStyle: return 200;
- case CSSPropertyWebkitBorderStartWidth: return 201;
- case CSSPropertyWebkitBorderVerticalSpacing: return 202;
- case CSSPropertyWebkitBoxAlign: return 203;
- case CSSPropertyWebkitBoxDirection: return 204;
- case CSSPropertyWebkitBoxFlex: return 205;
- case CSSPropertyWebkitBoxFlexGroup: return 206;
- case CSSPropertyWebkitBoxLines: return 207;
- case CSSPropertyWebkitBoxOrdinalGroup: return 208;
- case CSSPropertyWebkitBoxOrient: return 209;
- case CSSPropertyWebkitBoxPack: return 210;
- case CSSPropertyWebkitBoxReflect: return 211;
- case CSSPropertyWebkitBoxShadow: return 212;
- case CSSPropertyWebkitColumnAxis: return 214;
- case CSSPropertyWebkitColumnBreakAfter: return 215;
- case CSSPropertyWebkitColumnBreakBefore: return 216;
- case CSSPropertyWebkitColumnBreakInside: return 217;
- case CSSPropertyWebkitColumnCount: return 218;
- case CSSPropertyWebkitColumnGap: return 219;
- case CSSPropertyWebkitColumnProgression: return 220;
- case CSSPropertyWebkitColumnRule: return 221;
- case CSSPropertyWebkitColumnRuleColor: return 222;
- case CSSPropertyWebkitColumnRuleStyle: return 223;
- case CSSPropertyWebkitColumnRuleWidth: return 224;
- case CSSPropertyWebkitColumnSpan: return 225;
- case CSSPropertyWebkitColumnWidth: return 226;
- case CSSPropertyWebkitColumns: return 227;
-#if defined(ENABLE_CSS_BOX_DECORATION_BREAK) && ENABLE_CSS_BOX_DECORATION_BREAK
- case CSSPropertyWebkitBoxDecorationBreak: return 228;
-#endif
-#if defined(ENABLE_CSS_FILTERS) && ENABLE_CSS_FILTERS
- case CSSPropertyWebkitFilter: return 229;
-#endif
- case CSSPropertyAlignContent: return 230;
- case CSSPropertyAlignItems: return 231;
- case CSSPropertyAlignSelf: return 232;
- case CSSPropertyFlex: return 233;
- case CSSPropertyFlexBasis: return 234;
- case CSSPropertyFlexDirection: return 235;
- case CSSPropertyFlexFlow: return 236;
- case CSSPropertyFlexGrow: return 237;
- case CSSPropertyFlexShrink: return 238;
- case CSSPropertyFlexWrap: return 239;
- case CSSPropertyJustifyContent: return 240;
- case CSSPropertyWebkitFontSizeDelta: return 241;
- case CSSPropertyGridDefinitionColumns: return 242;
- case CSSPropertyGridDefinitionRows: return 243;
- case CSSPropertyGridColumnStart: return 244;
- case CSSPropertyGridColumnEnd: return 245;
- case CSSPropertyGridRowStart: return 246;
- case CSSPropertyGridRowEnd: return 247;
- case CSSPropertyGridColumn: return 248;
- case CSSPropertyGridRow: return 249;
- case CSSPropertyGridAutoFlow: return 250;
- case CSSPropertyWebkitHighlight: return 251;
- case CSSPropertyWebkitHyphenateCharacter: return 252;
- case CSSPropertyWebkitLineBoxContain: return 257;
- case CSSPropertyWebkitLineAlign: return 258;
- case CSSPropertyWebkitLineBreak: return 259;
- case CSSPropertyWebkitLineClamp: return 260;
- case CSSPropertyWebkitLineGrid: return 261;
- case CSSPropertyWebkitLineSnap: return 262;
- case CSSPropertyWebkitLogicalWidth: return 263;
- case CSSPropertyWebkitLogicalHeight: return 264;
- case CSSPropertyWebkitMarginAfterCollapse: return 265;
- case CSSPropertyWebkitMarginBeforeCollapse: return 266;
- case CSSPropertyWebkitMarginBottomCollapse: return 267;
- case CSSPropertyWebkitMarginTopCollapse: return 268;
- case CSSPropertyWebkitMarginCollapse: return 269;
- case CSSPropertyWebkitMarginAfter: return 270;
- case CSSPropertyWebkitMarginBefore: return 271;
- case CSSPropertyWebkitMarginEnd: return 272;
- case CSSPropertyWebkitMarginStart: return 273;
- // CSSPropertyWebkitMarquee was 274.
- case CSSPropertyInternalMarqueeDirection: return 275;
- case CSSPropertyInternalMarqueeIncrement: return 276;
- case CSSPropertyInternalMarqueeRepetition: return 277;
- case CSSPropertyInternalMarqueeSpeed: return 278;
- case CSSPropertyInternalMarqueeStyle: return 279;
- case CSSPropertyWebkitMask: return 280;
- case CSSPropertyWebkitMaskBoxImage: return 281;
- case CSSPropertyWebkitMaskBoxImageOutset: return 282;
- case CSSPropertyWebkitMaskBoxImageRepeat: return 283;
- case CSSPropertyWebkitMaskBoxImageSlice: return 284;
- case CSSPropertyWebkitMaskBoxImageSource: return 285;
- case CSSPropertyWebkitMaskBoxImageWidth: return 286;
- case CSSPropertyWebkitMaskClip: return 287;
- case CSSPropertyWebkitMaskComposite: return 288;
- case CSSPropertyWebkitMaskImage: return 289;
- case CSSPropertyWebkitMaskOrigin: return 290;
- case CSSPropertyWebkitMaskPosition: return 291;
- case CSSPropertyWebkitMaskPositionX: return 292;
- case CSSPropertyWebkitMaskPositionY: return 293;
- case CSSPropertyWebkitMaskRepeat: return 294;
- case CSSPropertyWebkitMaskRepeatX: return 295;
- case CSSPropertyWebkitMaskRepeatY: return 296;
- case CSSPropertyWebkitMaskSize: return 297;
- case CSSPropertyWebkitMaxLogicalWidth: return 298;
- case CSSPropertyWebkitMaxLogicalHeight: return 299;
- case CSSPropertyWebkitMinLogicalWidth: return 300;
- case CSSPropertyWebkitMinLogicalHeight: return 301;
- // WebkitNbspMode has been deleted, was return 302;
- case CSSPropertyOrder: return 303;
- case CSSPropertyWebkitPaddingAfter: return 304;
- case CSSPropertyWebkitPaddingBefore: return 305;
- case CSSPropertyWebkitPaddingEnd: return 306;
- case CSSPropertyWebkitPaddingStart: return 307;
- case CSSPropertyWebkitPerspective: return 308;
- case CSSPropertyWebkitPerspectiveOrigin: return 309;
- case CSSPropertyWebkitPerspectiveOriginX: return 310;
- case CSSPropertyWebkitPerspectiveOriginY: return 311;
- case CSSPropertyWebkitPrintColorAdjust: return 312;
- case CSSPropertyWebkitRtlOrdering: return 313;
- case CSSPropertyWebkitRubyPosition: return 314;
- case CSSPropertyWebkitTextCombine: return 315;
- case CSSPropertyWebkitTextDecorationsInEffect: return 316;
- case CSSPropertyWebkitTextEmphasis: return 317;
- case CSSPropertyWebkitTextEmphasisColor: return 318;
- case CSSPropertyWebkitTextEmphasisPosition: return 319;
- case CSSPropertyWebkitTextEmphasisStyle: return 320;
- case CSSPropertyWebkitTextFillColor: return 321;
- case CSSPropertyWebkitTextSecurity: return 322;
- case CSSPropertyWebkitTextStroke: return 323;
- case CSSPropertyWebkitTextStrokeColor: return 324;
- case CSSPropertyWebkitTextStrokeWidth: return 325;
- case CSSPropertyWebkitTransform: return 326;
- case CSSPropertyWebkitTransformOrigin: return 327;
- case CSSPropertyWebkitTransformOriginX: return 328;
- case CSSPropertyWebkitTransformOriginY: return 329;
- case CSSPropertyWebkitTransformOriginZ: return 330;
- case CSSPropertyWebkitTransformStyle: return 331;
- case CSSPropertyWebkitTransition: return 332;
- case CSSPropertyWebkitTransitionDelay: return 333;
- case CSSPropertyWebkitTransitionDuration: return 334;
- case CSSPropertyWebkitTransitionProperty: return 335;
- case CSSPropertyWebkitTransitionTimingFunction: return 336;
- case CSSPropertyWebkitUserDrag: return 337;
- case CSSPropertyWebkitUserModify: return 338;
- case CSSPropertyWebkitUserSelect: return 339;
- case CSSPropertyWebkitFlowInto: return 340;
- case CSSPropertyWebkitFlowFrom: return 341;
- case CSSPropertyWebkitRegionFragment: return 342;
- case CSSPropertyWebkitRegionBreakAfter: return 343;
- case CSSPropertyWebkitRegionBreakBefore: return 344;
- case CSSPropertyWebkitRegionBreakInside: return 345;
- case CSSPropertyWebkitShapeInside: return 346;
- case CSSPropertyWebkitShapeOutside: return 347;
- case CSSPropertyWebkitShapeMargin: return 348;
- case CSSPropertyWebkitShapePadding: return 349;
- case CSSPropertyWebkitWrapFlow: return 350;
- case CSSPropertyWebkitWrapThrough: return 351;
- // CSSPropertyWebkitWrap was 352.
-#if defined(ENABLE_TOUCH_EVENTS) && ENABLE_TOUCH_EVENTS
- case CSSPropertyWebkitTapHighlightColor: return 353;
-#endif
-#if defined(ENABLE_DRAGGABLE_REGION) && ENABLE_DRAGGABLE_REGION
- case CSSPropertyWebkitAppRegion: return 354;
-#endif
- case CSSPropertyClipPath: return 355;
- case CSSPropertyClipRule: return 356;
- case CSSPropertyMask: return 357;
- case CSSPropertyEnableBackground: return 358;
- case CSSPropertyFilter: return 359;
- case CSSPropertyFloodColor: return 360;
- case CSSPropertyFloodOpacity: return 361;
- case CSSPropertyLightingColor: return 362;
- case CSSPropertyStopColor: return 363;
- case CSSPropertyStopOpacity: return 364;
- case CSSPropertyColorInterpolation: return 365;
- case CSSPropertyColorInterpolationFilters: return 366;
- case CSSPropertyColorProfile: return 367;
- case CSSPropertyColorRendering: return 368;
- case CSSPropertyFill: return 369;
- case CSSPropertyFillOpacity: return 370;
- case CSSPropertyFillRule: return 371;
- case CSSPropertyMarker: return 372;
- case CSSPropertyMarkerEnd: return 373;
- case CSSPropertyMarkerMid: return 374;
- case CSSPropertyMarkerStart: return 375;
- case CSSPropertyMaskType: return 376;
- case CSSPropertyShapeRendering: return 377;
- case CSSPropertyStroke: return 378;
- case CSSPropertyStrokeDasharray: return 379;
- case CSSPropertyStrokeDashoffset: return 380;
- case CSSPropertyStrokeLinecap: return 381;
- case CSSPropertyStrokeLinejoin: return 382;
- case CSSPropertyStrokeMiterlimit: return 383;
- case CSSPropertyStrokeOpacity: return 384;
- case CSSPropertyStrokeWidth: return 385;
- case CSSPropertyAlignmentBaseline: return 386;
- case CSSPropertyBaselineShift: return 387;
- case CSSPropertyDominantBaseline: return 388;
- case CSSPropertyGlyphOrientationHorizontal: return 389;
- case CSSPropertyGlyphOrientationVertical: return 390;
- case CSSPropertyKerning: return 391;
- case CSSPropertyTextAnchor: return 392;
- case CSSPropertyVectorEffect: return 393;
- case CSSPropertyWritingMode: return 394;
- // CSSPropertyWebkitSvgShadow has been removed, was return 395;
-#if defined(ENABLE_CURSOR_VISIBILITY) && ENABLE_CURSOR_VISIBILITY
- case CSSPropertyWebkitCursorVisibility: return 396;
-#endif
- // CSSPropertyImageOrientation has been removed, was return 397;
- // CSSPropertyImageResolution has been removed, was return 398;
-#if defined(ENABLE_CSS_COMPOSITING) && ENABLE_CSS_COMPOSITING
- case CSSPropertyWebkitBlendMode: return 399;
- case CSSPropertyWebkitBackgroundBlendMode: return 400;
-#endif
- case CSSPropertyTextDecorationLine: return 401;
- case CSSPropertyTextDecorationStyle: return 402;
- case CSSPropertyTextDecorationColor: return 403;
- case CSSPropertyTextAlignLast: return 404;
-#if defined(ENABLE_CSS3_TEXT) && ENABLE_CSS3_TEXT
- case CSSPropertyWebkitTextUnderlinePosition: return 405;
-#endif
- case CSSPropertyMaxZoom: return 406;
- case CSSPropertyMinZoom: return 407;
- case CSSPropertyOrientation: return 408;
- case CSSPropertyUserZoom: return 409;
- // CSSPropertyWebkitDashboardRegion was 410.
- // CSSPropertyWebkitOverflowScrolling was 411.
- case CSSPropertyWebkitAppRegion: return 412;
- case CSSPropertyWebkitFilter: return 413;
- case CSSPropertyWebkitBoxDecorationBreak: return 414;
- case CSSPropertyWebkitTapHighlightColor: return 415;
- case CSSPropertyBufferedRendering: return 416;
- case CSSPropertyGridAutoRows: return 417;
- case CSSPropertyGridAutoColumns: return 418;
- case CSSPropertyBackgroundBlendMode: return 419;
- case CSSPropertyMixBlendMode: return 420;
- case CSSPropertyTouchAction: return 421;
- case CSSPropertyGridArea: return 422;
- case CSSPropertyGridTemplate: return 423;
- case CSSPropertyAnimation: return 424;
- case CSSPropertyAnimationDelay: return 425;
- case CSSPropertyAnimationDirection: return 426;
- case CSSPropertyAnimationDuration: return 427;
- case CSSPropertyAnimationFillMode: return 428;
- case CSSPropertyAnimationIterationCount: return 429;
- case CSSPropertyAnimationName: return 430;
- case CSSPropertyAnimationPlayState: return 431;
- case CSSPropertyAnimationTimingFunction: return 432;
- case CSSPropertyObjectFit: return 433;
- case CSSPropertyPaintOrder: return 434;
- case CSSPropertyMaskSourceType: return 435;
- case CSSPropertyIsolation: return 436;
- case CSSPropertyObjectPosition: return 437;
-
- // Add new features above this line (don't change the assigned numbers of the existing
- // items) and update maximumCSSSampleId() with the new maximum value.
-
- case CSSPropertyInvalid:
- case CSSPropertyVariable:
- ASSERT_NOT_REACHED();
- return 0;
- }
-
- ASSERT_NOT_REACHED();
- return 0;
-}
-
-static int maximumCSSSampleId() { return 437; }
-
-UseCounter::UseCounter()
-{
- m_CSSFeatureBits.ensureSize(lastCSSProperty + 1);
- m_CSSFeatureBits.clearAll();
-}
-
-UseCounter::~UseCounter()
-{
- // We always log PageDestruction so that we have a scale for the rest of the features.
- HistogramSupport::histogramEnumeration("WebCore.FeatureObserver", PageDestruction, NumberOfFeatures);
-
- updateMeasurements();
-}
-
-void UseCounter::updateMeasurements()
-{
- HistogramSupport::histogramEnumeration("WebCore.FeatureObserver", PageVisits, NumberOfFeatures);
-
- if (m_countBits) {
- for (unsigned i = 0; i < NumberOfFeatures; ++i) {
- if (m_countBits->quickGet(i))
- HistogramSupport::histogramEnumeration("WebCore.FeatureObserver", i, NumberOfFeatures);
- }
- // Clearing count bits is timing sensitive.
- m_countBits->clearAll();
- }
-
- // FIXME: Sometimes this function is called more than once per page. The following
- // bool guards against incrementing the page count when there are no CSS
- // bits set. http://crbug.com/236262.
- bool needsPagesMeasuredUpdate = false;
- for (int i = firstCSSProperty; i <= lastCSSProperty; ++i) {
- if (m_CSSFeatureBits.quickGet(i)) {
- int cssSampleId = mapCSSPropertyIdToCSSSampleIdForHistogram(i);
- HistogramSupport::histogramEnumeration("WebCore.FeatureObserver.CSSProperties", cssSampleId, maximumCSSSampleId());
- needsPagesMeasuredUpdate = true;
- }
- }
-
- if (needsPagesMeasuredUpdate)
- HistogramSupport::histogramEnumeration("WebCore.FeatureObserver.CSSProperties", totalPagesMeasuredCSSSampleId(), maximumCSSSampleId());
-
- m_CSSFeatureBits.clearAll();
-}
-
-void UseCounter::didCommitLoad()
-{
- updateMeasurements();
-}
-
-void UseCounter::count(Document* document, Feature feature)
-{
- if (!document)
- return;
-
- Page* page = document->page();
- if (!page)
- return;
-
- ASSERT(page->useCounter().deprecationMessage(feature).isEmpty());
- page->useCounter().recordMeasurement(feature);
-}
-
-void UseCounter::count(DOMWindow* domWindow, Feature feature)
-{
- ASSERT(domWindow);
- count(domWindow->document(), feature);
-}
-
-void UseCounter::countDeprecation(ScriptExecutionContext* context, Feature feature)
-{
- if (!context || !context->isDocument())
- return;
- UseCounter::countDeprecation(toDocument(context), feature);
-}
-
-void UseCounter::countDeprecation(DOMWindow* window, Feature feature)
-{
- if (!window)
- return;
- UseCounter::countDeprecation(window->document(), feature);
-}
-
-void UseCounter::countDeprecation(Document* document, Feature feature)
-{
- if (!document)
- return;
-
- Page* page = document->page();
- if (!page)
- return;
-
- if (page->useCounter().recordMeasurement(feature)) {
- ASSERT(!page->useCounter().deprecationMessage(feature).isEmpty());
- page->console().addMessage(DeprecationMessageSource, WarningMessageLevel, page->useCounter().deprecationMessage(feature));
- }
-}
-
-String UseCounter::deprecationMessage(Feature feature)
-{
- switch (feature) {
- // Content Security Policy
- case PrefixedContentSecurityPolicy:
- case PrefixedContentSecurityPolicyReportOnly:
- return "The 'X-WebKit-CSP' headers are deprecated; please consider using the canonical 'Content-Security-Policy' header instead.";
-
- // HTMLMediaElement
- case PrefixedMediaGenerateKeyRequest:
- return "'HTMLMediaElement.webkitGenerateKeyRequest()' is deprecated. Please use 'MediaKeys.createSession()' instead.";
-
- // Quota
- case StorageInfo:
- return "'window.webkitStorageInfo' is deprecated. Please use 'navigator.webkitTemporaryStorage' or 'navigator.webkitPersistentStorage' instead.";
-
- // Performance
- case PrefixedPerformanceTimeline:
- return "'window.performance.webkitGet*' methods have been deprecated. Please use the unprefixed 'performance.get*' methods instead.";
- case PrefixedUserTiming:
- return "'window.performance.webkit*' methods have been deprecated. Please use the unprefixed 'window.performance.*' methods instead.";
-
- // Web Audio
- case WebAudioLooping:
- return "AudioBufferSourceNode 'looping' attribute is deprecated. Use 'loop' instead.";
-
- case DocumentClear:
- return "document.clear() is deprecated. This method doesn't do anything.";
-
- case PrefixedTransitionMediaFeature:
- return "The '(-webkit-transition)' media query feature is deprecated; please consider using the more exact conditional \"@supports('(transition-property: prop_name)')\" instead.";
-
- // Web Components
- case HTMLShadowElementOlderShadowRoot:
- return "HTMLShadowElement.olderShadowRoot is deprecated.";
- case PrefixedDocumentRegister:
- return "The document.webkitRegister method is deprecated. Use the document.register method instead.";
-
- // HTML Media Capture
- case CaptureAttributeAsEnum:
- return "Using the 'capture' attribute as an enum is deprecated. Please use it as a boolean and specify the media types that should be accepted in the 'accept' attribute.";
-
- // Keyboard Event (DOM Level 3)
- case KeyboardEventKeyLocation:
- return "'KeyboardEvent.keyLocation'' is deprecated. Please use 'KeyboardEvent.location' instead.";
-
- case CaptureEvents:
- return "captureEvents() is deprecated. This method doesn't do anything.";
-
- case ReleaseEvents:
- return "releaseEvents() is deprecated. This method doesn't do anything.";
-
- case ConsoleMarkTimeline:
- return "console.markTimeline is deprecated. Please use the console.timeStamp instead.";
-
- case FileError:
- return "FileError is deprecated. Please use the 'name' or 'message' attributes of DOMError rather than 'code'.";
-
- case EventReturnValue:
- return "event.returnValue is deprecated. Please use the standard event.preventDefault() instead.";
-
- // Features that aren't deprecated don't have a deprecation message.
- default:
- return String();
- }
-}
-
-void UseCounter::count(CSSPropertyID feature)
-{
- ASSERT(feature >= firstCSSProperty);
- ASSERT(feature <= lastCSSProperty);
- m_CSSFeatureBits.quickSet(feature);
-}
-
-void UseCounter::count(Feature feature)
-{
- ASSERT(deprecationMessage(feature).isEmpty());
- recordMeasurement(feature);
-}
-
-UseCounter* UseCounter::getFrom(const Document* document)
-{
- if (document && document->page())
- return &document->page()->useCounter();
- return 0;
-}
-
-UseCounter* UseCounter::getFrom(const CSSStyleSheet* sheet)
-{
- if (sheet)
- return getFrom(sheet->contents());
- return 0;
-}
-
-UseCounter* UseCounter::getFrom(const StyleSheetContents* sheetContents)
-{
- // FIXME: We may want to handle stylesheets that have multiple owners
- // http://crbug.com/242125
- if (sheetContents && !sheetContents->isUserStyleSheet() && sheetContents->hasSingleOwnerNode())
- return getFrom(sheetContents->singleOwnerDocument());
- return 0;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/page/UseCounter.h b/chromium/third_party/WebKit/Source/core/page/UseCounter.h
deleted file mode 100644
index c93fd34637f..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/UseCounter.h
+++ /dev/null
@@ -1,270 +0,0 @@
-/*
- * Copyright (C) 2012 Google, Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY GOOGLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef UseCounter_h
-#define UseCounter_h
-
-#include "CSSPropertyNames.h"
-#include "wtf/BitVector.h"
-#include "wtf/Noncopyable.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class CSSStyleSheet;
-class DOMWindow;
-class Document;
-class ScriptExecutionContext;
-class StyleSheetContents;
-
-// UseCounter is used for counting the number of times features of
-// Blink are used on real web pages and help us know commonly
-// features are used and thus when it's safe to remove or change them.
-//
-// The Chromium Content layer controls what is done with this data.
-// For instance, in Google Chrome, these counts are submitted
-// anonymously through the Histogram recording system in Chrome
-// for users who opt-in to "Usage Statistics" submission
-// during their install of Google Chrome:
-// http://www.google.com/chrome/intl/en/privacy.html
-
-class UseCounter {
- WTF_MAKE_NONCOPYABLE(UseCounter);
-public:
- UseCounter();
- ~UseCounter();
-
- enum Feature {
- PageDestruction,
- LegacyNotifications,
- MultipartMainResource,
- PrefixedIndexedDB,
- WorkerStart,
- SharedWorkerStart,
- LegacyWebAudio,
- WebAudioStart,
- PrefixedContentSecurityPolicy,
- UnprefixedIndexedDB,
- OpenWebDatabase,
- UnusedSlot01, // Prior to 7/2013, we used this slot for LegacyHTMLNotifications.
- LegacyTextNotifications,
- UnprefixedRequestAnimationFrame,
- PrefixedRequestAnimationFrame,
- ContentSecurityPolicy,
- ContentSecurityPolicyReportOnly,
- PrefixedContentSecurityPolicyReportOnly,
- PrefixedTransitionEndEvent,
- UnprefixedTransitionEndEvent,
- PrefixedAndUnprefixedTransitionEndEvent,
- AutoFocusAttribute,
- UnusedSlot02, // Prior to 4/2013, we used this slot for AutoSaveAttribute.
- DataListElement,
- FormAttribute,
- IncrementalAttribute,
- InputTypeColor,
- InputTypeDate,
- InputTypeDateTime,
- InputTypeDateTimeFallback,
- InputTypeDateTimeLocal,
- InputTypeEmail,
- InputTypeMonth,
- InputTypeNumber,
- InputTypeRange,
- InputTypeSearch,
- InputTypeTel,
- InputTypeTime,
- InputTypeURL,
- InputTypeWeek,
- InputTypeWeekFallback,
- ListAttribute,
- MaxAttribute,
- MinAttribute,
- PatternAttribute,
- PlaceholderAttribute,
- PrecisionAttribute,
- PrefixedDirectoryAttribute,
- PrefixedSpeechAttribute,
- RequiredAttribute,
- ResultsAttribute,
- StepAttribute,
- PageVisits,
- HTMLMarqueeElement,
- UnusedSlot03, // Removed, was tracking overflow: -webkit-marquee.
- Reflection,
- CursorVisibility, // Removed, was -webkit-cursor-visibility.
- StorageInfo,
- XFrameOptions,
- XFrameOptionsSameOrigin,
- XFrameOptionsSameOriginWithBadAncestorChain,
- DeprecatedFlexboxWebContent,
- DeprecatedFlexboxChrome,
- DeprecatedFlexboxChromeExtension,
- UnusedSlot04,
- UnprefixedPerformanceTimeline,
- PrefixedPerformanceTimeline,
- UnprefixedUserTiming,
- PrefixedUserTiming,
- WindowEvent,
- ContentSecurityPolicyWithBaseElement,
- PrefixedMediaAddKey,
- PrefixedMediaGenerateKeyRequest,
- WebAudioLooping,
- DocumentClear,
- PrefixedTransitionMediaFeature,
- SVGFontElement,
- XMLDocument,
- XSLProcessingInstruction,
- XSLTProcessor,
- SVGSwitchElement,
- PrefixedDocumentRegister,
- HTMLShadowElementOlderShadowRoot,
- DocumentAll,
- FormElement,
- DemotedFormElement,
- CaptureAttributeAsEnum,
- ShadowDOMPrefixedPseudo,
- ShadowDOMPrefixedCreateShadowRoot,
- ShadowDOMPrefixedShadowRoot,
- SVGAnimationElement,
- KeyboardEventKeyLocation,
- CaptureEvents,
- ReleaseEvents,
- CSSDisplayRunIn,
- CSSDisplayCompact,
- LineClamp,
- SubFrameBeforeUnloadRegistered,
- SubFrameBeforeUnloadFired,
- CSSPseudoElementPrefixedDistributed,
- TextReplaceWholeText,
- PrefixedShadowRootConstructor,
- ConsoleMarkTimeline,
- CSSPseudoElementUserAgentCustomPseudo,
- DocumentTypeEntities, // Removed from DOM4.
- DocumentTypeInternalSubset, // Removed from DOM4.
- DocumentTypeNotations, // Removed from DOM4.
- ElementGetAttributeNode, // Removed from DOM4.
- ElementSetAttributeNode, // Removed from DOM4.
- ElementRemoveAttributeNode, // Removed from DOM4.
- ElementGetAttributeNodeNS, // Removed from DOM4.
- DocumentCreateAttribute, // Removed from DOM4.
- DocumentCreateAttributeNS, // Removed from DOM4.
- DocumentCreateCDATASection, // Removed from DOM4.
- DocumentInputEncoding, // Removed from DOM4.
- DocumentXMLEncoding, // Removed from DOM4.
- DocumentXMLStandalone, // Removed from DOM4.
- DocumentXMLVersion, // Removed from DOM4.
- NodeIsSameNode, // Removed from DOM4.
- NodeIsSupported, // Removed from DOM4.
- NodeNamespaceURI, // Removed from DOM4.
- NodePrefix, // Removed from DOM4.
- NodeLocalName, // Removed from DOM4.
- NavigatorProductSub,
- NavigatorVendor,
- NavigatorVendorSub,
- FileError,
- DocumentCharset, // Documented as IE extensions, from KHTML days.
- PrefixedAnimationEndEvent,
- UnprefixedAnimationEndEvent,
- PrefixedAndUnprefixedAnimationEndEvent,
- PrefixedAnimationStartEvent,
- UnprefixedAnimationStartEvent,
- PrefixedAndUnprefixedAnimationStartEvent,
- PrefixedAnimationIterationEvent,
- UnprefixedAnimationIterationEvent,
- PrefixedAndUnprefixedAnimationIterationEvent,
- EventReturnValue, // Legacy IE extension.
- SVGSVGElement,
- SVGAnimateColorElement,
- InsertAdjacentText,
- InsertAdjacentElement,
- HasAttributes, // Removed from DOM4.
- DOMSubtreeModifiedEvent,
- DOMNodeInsertedEvent,
- DOMNodeRemovedEvent,
- DOMNodeRemovedFromDocumentEvent,
- DOMNodeInsertedIntoDocumentEvent,
- DOMCharacterDataModifiedEvent,
- DocumentAllTags,
- DocumentAllLegacyCall,
- HTMLAppletElementLegacyCall,
- HTMLEmbedElementLegacyCall,
- HTMLObjectElementLegacyCall,
- // Add new features immediately above this line. Don't change assigned
- // numbers of each items, and don't reuse unused slots.
- NumberOfFeatures, // This enum value must be last.
- };
-
- // "count" sets the bit for this feature to 1. Repeated calls are ignored.
- static void count(Document*, Feature);
- static void count(DOMWindow*, Feature);
- void count(CSSPropertyID);
- void count(Feature);
-
- // "countDeprecation" sets the bit for this feature to 1, and sends a deprecation
- // warning to the console. Repeated calls are ignored.
- //
- // Be considerate to developers' consoles: features should only send deprecation warnings
- // when we're actively interested in removing them from the platform.
- static void countDeprecation(DOMWindow*, Feature);
- static void countDeprecation(ScriptExecutionContext*, Feature);
- static void countDeprecation(Document*, Feature);
- String deprecationMessage(Feature);
-
- void didCommitLoad();
-
- static UseCounter* getFrom(const Document*);
- static UseCounter* getFrom(const CSSStyleSheet*);
- static UseCounter* getFrom(const StyleSheetContents*);
-
- static int mapCSSPropertyIdToCSSSampleIdForHistogram(int id);
-
-private:
- bool recordMeasurement(Feature feature)
- {
- ASSERT(feature != PageDestruction); // PageDestruction is reserved as a scaling factor.
- ASSERT(feature < NumberOfFeatures);
- if (!m_countBits) {
- m_countBits = adoptPtr(new BitVector(NumberOfFeatures));
- m_countBits->clearAll();
- }
-
- if (m_countBits->quickGet(feature))
- return false;
-
- m_countBits->quickSet(feature);
- return true;
- }
-
- void updateMeasurements();
-
- OwnPtr<BitVector> m_countBits;
- BitVector m_CSSFeatureBits;
-};
-
-} // namespace WebCore
-
-#endif // UseCounter_h
diff --git a/chromium/third_party/WebKit/Source/core/page/UserContentTypes.h b/chromium/third_party/WebKit/Source/core/page/UserContentTypes.h
deleted file mode 100644
index 58c8bb980d6..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/UserContentTypes.h
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright (C) 2009 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef UserContentTypes_h
-#define UserContentTypes_h
-
-namespace WebCore {
-
-enum UserContentInjectedFrames { InjectInAllFrames, InjectInTopFrameOnly };
-
-} // namespace WebCore
-
-#endif // UserContentTypes_h
diff --git a/chromium/third_party/WebKit/Source/core/page/UserContentURLPattern.cpp b/chromium/third_party/WebKit/Source/core/page/UserContentURLPattern.cpp
deleted file mode 100644
index 4f18ab875ac..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/UserContentURLPattern.cpp
+++ /dev/null
@@ -1,234 +0,0 @@
-/*
- * Copyright (C) 2009, 2010 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/page/UserContentURLPattern.h"
-
-#include "weborigin/KURL.h"
-#include "wtf/StdLibExtras.h"
-
-namespace WebCore {
-
-bool UserContentURLPattern::matchesPatterns(const KURL& url, const Vector<String>& whitelist, const Vector<String>& blacklist)
-{
- // In order for a URL to be a match it has to be present in the whitelist and not present in the blacklist.
- // If there is no whitelist at all, then all URLs are assumed to be in the whitelist.
- bool matchesWhitelist = whitelist.isEmpty();
- if (!matchesWhitelist) {
- size_t whitelistSize = whitelist.size();
- for (size_t i = 0; i < whitelistSize; ++i) {
- UserContentURLPattern contentPattern(whitelist[i]);
- if (contentPattern.matches(url)) {
- matchesWhitelist = true;
- break;
- }
- }
- }
-
- bool matchesBlacklist = false;
- if (!blacklist.isEmpty()) {
- size_t blacklistSize = blacklist.size();
- for (size_t i = 0; i < blacklistSize; ++i) {
- UserContentURLPattern contentPattern(blacklist[i]);
- if (contentPattern.matches(url)) {
- matchesBlacklist = true;
- break;
- }
- }
- }
-
- return matchesWhitelist && !matchesBlacklist;
-}
-
-bool UserContentURLPattern::parse(const String& pattern)
-{
- DEFINE_STATIC_LOCAL(const String, schemeSeparator, ("://"));
-
- size_t schemeEndPos = pattern.find(schemeSeparator);
- if (schemeEndPos == kNotFound)
- return false;
-
- m_scheme = pattern.left(schemeEndPos);
-
- unsigned hostStartPos = schemeEndPos + schemeSeparator.length();
- if (hostStartPos >= pattern.length())
- return false;
-
- int pathStartPos = 0;
-
- if (equalIgnoringCase(m_scheme, "file"))
- pathStartPos = hostStartPos;
- else {
- size_t hostEndPos = pattern.find("/", hostStartPos);
- if (hostEndPos == kNotFound)
- return false;
-
- m_host = pattern.substring(hostStartPos, hostEndPos - hostStartPos);
- m_matchSubdomains = false;
-
- if (m_host == "*") {
- // The pattern can be just '*', which means match all domains.
- m_host = "";
- m_matchSubdomains = true;
- } else if (m_host.startsWith("*.")) {
- // The first component can be '*', which means to match all subdomains.
- m_host = m_host.substring(2); // Length of "*."
- m_matchSubdomains = true;
- }
-
- // No other '*' can occur in the host.
- if (m_host.find("*") != kNotFound)
- return false;
-
- pathStartPos = hostEndPos;
- }
-
- m_path = pattern.right(pattern.length() - pathStartPos);
-
- return true;
-}
-
-bool UserContentURLPattern::matches(const KURL& test) const
-{
- if (m_invalid)
- return false;
-
- if (!equalIgnoringCase(test.protocol(), m_scheme))
- return false;
-
- if (!equalIgnoringCase(m_scheme, "file") && !matchesHost(test))
- return false;
-
- return matchesPath(test);
-}
-
-bool UserContentURLPattern::matchesHost(const KURL& test) const
-{
- const String& host = test.host();
- if (equalIgnoringCase(host, m_host))
- return true;
-
- if (!m_matchSubdomains)
- return false;
-
- // If we're matching subdomains, and we have no host, that means the pattern
- // was <scheme>://*/<whatever>, so we match anything.
- if (!m_host.length())
- return true;
-
- // Check if the domain is a subdomain of our host.
- if (!host.endsWith(m_host, false))
- return false;
-
- ASSERT(host.length() > m_host.length());
-
- // Check that the character before the suffix is a period.
- return host[host.length() - m_host.length() - 1] == '.';
-}
-
-struct MatchTester
-{
- const String m_pattern;
- unsigned m_patternIndex;
-
- const String m_test;
- unsigned m_testIndex;
-
- MatchTester(const String& pattern, const String& test)
- : m_pattern(pattern)
- , m_patternIndex(0)
- , m_test(test)
- , m_testIndex(0)
- {
- }
-
- bool testStringFinished() const { return m_testIndex >= m_test.length(); }
- bool patternStringFinished() const { return m_patternIndex >= m_pattern.length(); }
-
- void eatWildcard()
- {
- while (!patternStringFinished()) {
- if (m_pattern[m_patternIndex] != '*')
- return;
- m_patternIndex++;
- }
- }
-
- void eatSameChars()
- {
- while (!patternStringFinished() && !testStringFinished()) {
- if (m_pattern[m_patternIndex] == '*')
- return;
- if (m_pattern[m_patternIndex] != m_test[m_testIndex])
- return;
- m_patternIndex++;
- m_testIndex++;
- }
- }
-
- bool test()
- {
- // Eat all the matching chars.
- eatSameChars();
-
- // If the string is finished, then the pattern must be empty too, or contains
- // only wildcards.
- if (testStringFinished()) {
- eatWildcard();
- if (patternStringFinished())
- return true;
- return false;
- }
-
- // Pattern is empty but not string, this is not a match.
- if (patternStringFinished())
- return false;
-
- // If we don't encounter a *, then we're hosed.
- if (m_pattern[m_patternIndex] != '*')
- return false;
-
- while (!testStringFinished()) {
- MatchTester nextMatch(*this);
- nextMatch.m_patternIndex++;
- if (nextMatch.test())
- return true;
- m_testIndex++;
- }
-
- // We reached the end of the string. Let's see if the pattern contains only
- // wildcards.
- eatWildcard();
- return patternStringFinished();
- }
-};
-
-bool UserContentURLPattern::matchesPath(const KURL& test) const
-{
- MatchTester match(m_path, test.path());
- return match.test();
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/page/UserContentURLPattern.h b/chromium/third_party/WebKit/Source/core/page/UserContentURLPattern.h
deleted file mode 100644
index 7415b887053..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/UserContentURLPattern.h
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * Copyright (C) 2009 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef UserContentURLPattern_h
-#define UserContentURLPattern_h
-
-#include "wtf/Vector.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class KURL;
-
-class UserContentURLPattern {
-public:
- UserContentURLPattern() : m_invalid(true), m_matchSubdomains(false) { }
-
- UserContentURLPattern(const String& pattern)
- : m_matchSubdomains(false)
- {
- m_invalid = !parse(pattern);
- }
-
- bool isValid() const { return !m_invalid; }
-
- bool matches(const KURL&) const;
-
- const String& scheme() const { return m_scheme; }
- const String& host() const { return m_host; }
- const String& path() const { return m_path; }
-
- bool matchSubdomains() const { return m_matchSubdomains; }
-
- static bool matchesPatterns(const KURL&, const Vector<String>& whitelist, const Vector<String>& blacklist);
-
-private:
- bool parse(const String& pattern);
-
- bool matchesHost(const KURL&) const;
- bool matchesPath(const KURL&) const;
-
- bool m_invalid;
-
- String m_scheme;
- String m_host;
- String m_path;
-
- bool m_matchSubdomains;
-};
-
-
-} // namespace WebCore
-
-#endif // UserContentURLPattern_h
diff --git a/chromium/third_party/WebKit/Source/core/page/UserStyleSheet.h b/chromium/third_party/WebKit/Source/core/page/UserStyleSheet.h
deleted file mode 100644
index c5f8e197234..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/UserStyleSheet.h
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * Copyright (C) 2009 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef UserStyleSheet_h
-#define UserStyleSheet_h
-
-#include "core/page/UserContentTypes.h"
-#include "core/page/UserStyleSheetTypes.h"
-#include "weborigin/KURL.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-class UserStyleSheet {
- WTF_MAKE_FAST_ALLOCATED;
-public:
- UserStyleSheet()
- : m_injectedFrames(InjectInAllFrames)
- , m_level(UserStyleUserLevel)
- {
- }
-
- UserStyleSheet(const String& source, const KURL& url, const Vector<String>& whitelist, const Vector<String>& blacklist, UserContentInjectedFrames injectedFrames, UserStyleLevel level)
- : m_source(source)
- , m_url(url)
- , m_whitelist(whitelist)
- , m_blacklist(blacklist)
- , m_injectedFrames(injectedFrames)
- , m_level(level)
- {
- }
-
- const String& source() const { return m_source; }
- const KURL& url() const { return m_url; }
- const Vector<String>& whitelist() const { return m_whitelist; }
- const Vector<String>& blacklist() const { return m_blacklist; }
- UserContentInjectedFrames injectedFrames() const { return m_injectedFrames; }
- UserStyleLevel level() const { return m_level; }
-
-private:
- String m_source;
- KURL m_url;
- Vector<String> m_whitelist;
- Vector<String> m_blacklist;
- UserContentInjectedFrames m_injectedFrames;
- UserStyleLevel m_level;
-};
-
-} // namespace WebCore
-
-#endif // UserStyleSheet_h
diff --git a/chromium/third_party/WebKit/Source/core/page/UserStyleSheetTypes.h b/chromium/third_party/WebKit/Source/core/page/UserStyleSheetTypes.h
deleted file mode 100644
index 6ddebdacc62..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/UserStyleSheetTypes.h
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright (C) 2009 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef UserStyleSheetTypes_h
-#define UserStyleSheetTypes_h
-
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-enum UserStyleInjectionTime { InjectInExistingDocuments, InjectInSubsequentDocuments };
-enum UserStyleLevel { UserStyleUserLevel, UserStyleAuthorLevel };
-
-class UserStyleSheet;
-
-typedef Vector<OwnPtr<UserStyleSheet> > UserStyleSheetVector;
-
-} // namespace WebCore
-
-#endif // UserStyleSheetTypes_h
diff --git a/chromium/third_party/WebKit/Source/core/page/WebKitPoint.idl b/chromium/third_party/WebKit/Source/core/page/WebKitPoint.idl
deleted file mode 100644
index 4e3637ac227..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/WebKitPoint.idl
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Copyright (C) 2009, 2010 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-[
- CustomConstructor,
- CustomConstructor(float x, float y),
- ImplementedAs=DOMPoint
-] interface WebKitPoint {
- attribute float x;
- attribute float y;
-};
-
diff --git a/chromium/third_party/WebKit/Source/core/page/Window.idl b/chromium/third_party/WebKit/Source/core/page/Window.idl
deleted file mode 100644
index c720658c5e8..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/Window.idl
+++ /dev/null
@@ -1,315 +0,0 @@
-/*
- * Copyright (C) 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-[
- CheckSecurity,
- CustomToV8,
- DoNotGenerateWrap,
- ImplementedAs=DOMWindow
-] interface Window : EventTarget {
- // DOM Level 0
- [Replaceable] readonly attribute Screen screen;
- [Replaceable] readonly attribute History history;
- [Replaceable] readonly attribute BarProp locationbar;
- [Replaceable] readonly attribute BarProp menubar;
- [Replaceable] readonly attribute BarProp personalbar;
- [Replaceable] readonly attribute BarProp scrollbars;
- [Replaceable] readonly attribute BarProp statusbar;
- [Replaceable] readonly attribute BarProp toolbar;
- [Replaceable, PerWorldBindings, ActivityLog=GetterForIsolatedWorlds] readonly attribute Navigator navigator;
- [Replaceable] readonly attribute Navigator clientInformation;
- [DoNotCheckSecurity, CustomSetter, Unforgeable, Replaceable, PerWorldBindings, ActivityLog=AccessForIsolatedWorlds] readonly attribute Location location;
- [MeasureAs=WindowEvent, NotEnumerable, Replaceable, CustomGetter, CustomSetter] readonly attribute Event event;
-
- Selection getSelection();
-
- [CheckSecurityForNode] readonly attribute Element frameElement;
-
- [DoNotCheckSecurity, CallWith=ScriptExecutionContext] void focus();
- [DoNotCheckSecurity] void blur();
- [DoNotCheckSecurity, CallWith=ScriptExecutionContext] void close();
-
- void print();
- void stop();
-
- [Custom] Window open(DOMString url,
- DOMString name,
- optional DOMString options);
-
- [Custom] any showModalDialog(DOMString url,
- optional any dialogArgs,
- optional DOMString featureArgs);
-
- void alert([Default=Undefined] optional DOMString message);
- boolean confirm([Default=Undefined] optional DOMString message);
- [TreatReturnedNullStringAs=Null] DOMString prompt([Default=Undefined] optional DOMString message,
- [TreatNullAs=NullString, TreatUndefinedAs=NullString,Default=Undefined] optional DOMString defaultValue);
-
- boolean find([Default=Undefined] optional DOMString string,
- [Default=Undefined] optional boolean caseSensitive,
- [Default=Undefined] optional boolean backwards,
- [Default=Undefined] optional boolean wrap,
- [Default=Undefined] optional boolean wholeWord,
- [Default=Undefined] optional boolean searchInFrames,
- [Default=Undefined] optional boolean showDialog);
-
- [Replaceable] readonly attribute boolean offscreenBuffering;
-
- [Replaceable] readonly attribute long outerHeight;
- [Replaceable] readonly attribute long outerWidth;
- [Replaceable] readonly attribute long innerHeight;
- [Replaceable] readonly attribute long innerWidth;
- [Replaceable] readonly attribute long screenX;
- [Replaceable] readonly attribute long screenY;
- [Replaceable] readonly attribute long screenLeft;
- [Replaceable] readonly attribute long screenTop;
- [Replaceable] readonly attribute long scrollX;
- [Replaceable] readonly attribute long scrollY;
- readonly attribute long pageXOffset;
- readonly attribute long pageYOffset;
-
- void scrollBy([Default=Undefined] optional long x, [Default=Undefined] optional long y);
- void scrollTo([Default=Undefined] optional long x, [Default=Undefined] optional long y);
- void scroll([Default=Undefined] optional long x, [Default=Undefined] optional long y);
- void moveBy([Default=Undefined] optional float x, [Default=Undefined] optional float y); // FIXME: this should take longs not floats.
- void moveTo([Default=Undefined] optional float x, [Default=Undefined] optional float y); // FIXME: this should take longs not floats.
- void resizeBy([Default=Undefined] optional float x, [Default=Undefined] optional float y); // FIXME: this should take longs not floats.
- void resizeTo([Default=Undefined] optional float width, [Default=Undefined] optional float height); // FIXME: this should take longs not floats.
-
- [DoNotCheckSecurity] readonly attribute boolean closed;
-
- [Replaceable, DoNotCheckSecurityOnGetter] readonly attribute unsigned long length;
-
- attribute DOMString name;
-
- attribute DOMString status;
- attribute DOMString defaultStatus;
- // This attribute is an alias of defaultStatus and is necessary for legacy uses.
- attribute DOMString defaultstatus;
-
- // Self referential attributes
- [Replaceable, DoNotCheckSecurityOnGetter] readonly attribute Window self;
- [DoNotCheckSecurity, Unforgeable] readonly attribute Window window;
- [Replaceable, DoNotCheckSecurityOnGetter] readonly attribute Window frames;
-
- [Replaceable, DoNotCheckSecurityOnGetter, CustomSetter] readonly attribute Window opener;
- [Replaceable, DoNotCheckSecurityOnGetter] readonly attribute Window parent;
- [DoNotCheckSecurityOnGetter, Unforgeable] readonly attribute Window top;
-
- // DOM Level 2 AbstractView Interface
- readonly attribute Document document;
-
- // CSSOM View Module
- MediaQueryList matchMedia(DOMString query);
-
- // styleMedia has been removed from the CSSOM View specification.
- readonly attribute StyleMedia styleMedia;
-
- // DOM Level 2 Style Interface
- [PerWorldBindings] CSSStyleDeclaration getComputedStyle([Default=Undefined] optional Element element,
- [TreatNullAs=NullString, TreatUndefinedAs=NullString,Default=Undefined] optional DOMString pseudoElement);
-
- // WebKit extensions
- CSSRuleList getMatchedCSSRules([Default=Undefined] optional Element element,
- [TreatNullAs=NullString, TreatUndefinedAs=NullString,Default=Undefined] optional DOMString pseudoElement);
-
- [Replaceable] readonly attribute double devicePixelRatio;
-
- WebKitPoint webkitConvertPointFromPageToNode([Default=Undefined] optional Node node,
- [Default=Undefined] optional WebKitPoint p);
- WebKitPoint webkitConvertPointFromNodeToPage([Default=Undefined] optional Node node,
- [Default=Undefined] optional WebKitPoint p);
-
- [EnabledAtRuntime=ApplicationCache, PerWorldBindings, ActivityLog=GetterForIsolatedWorlds] readonly attribute ApplicationCache applicationCache;
-
- [EnabledAtRuntime=SessionStorage, PerWorldBindings, ActivityLog=GetterForIsolatedWorlds, GetterRaisesException] readonly attribute Storage sessionStorage;
- [EnabledAtRuntime=LocalStorage, PerWorldBindings, ActivityLog=GetterForIsolatedWorlds, GetterRaisesException] readonly attribute Storage localStorage;
-
- // This is the interface orientation in degrees. Some examples are:
- // 0 is straight up; -90 is when the device is rotated 90 clockwise;
- // 90 is when rotated counter clockwise.
- [Conditional=ORIENTATION_EVENTS] readonly attribute long orientation;
-
- [Replaceable] readonly attribute Console console;
-
- // cross-document messaging
- [DoNotCheckSecurity, Custom, RaisesException] void postMessage(SerializedScriptValue message, DOMString targetOrigin, optional Array messagePorts);
-
- [Replaceable] readonly attribute Performance performance;
-
- [MeasureAs=UnprefixedRequestAnimationFrame] long requestAnimationFrame(RequestAnimationFrameCallback callback);
- void cancelAnimationFrame(long id);
- [MeasureAs=PrefixedRequestAnimationFrame] long webkitRequestAnimationFrame(RequestAnimationFrameCallback callback);
- [ImplementedAs=cancelAnimationFrame] void webkitCancelAnimationFrame(long id);
- [ImplementedAs=cancelAnimationFrame] void webkitCancelRequestAnimationFrame(long id); // This is a deprecated alias for webkitCancelAnimationFrame(). Remove this when removing vendor prefix.
-
- [Replaceable] readonly attribute CSS CSS;
-
- // Events
- attribute EventHandler onabort;
- attribute EventHandler onbeforeunload;
- attribute EventHandler onblur;
- attribute EventHandler oncanplay;
- attribute EventHandler oncanplaythrough;
- attribute EventHandler onchange;
- [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onclick;
- attribute EventHandler oncontextmenu;
- [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler ondblclick;
- [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler ondrag;
- [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler ondragend;
- [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler ondragenter;
- [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler ondragleave;
- [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler ondragover;
- [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler ondragstart;
- [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler ondrop;
- attribute EventHandler ondurationchange;
- attribute EventHandler onemptied;
- attribute EventHandler onended;
- attribute EventHandler onerror;
- attribute EventHandler onfocus;
- attribute EventHandler onhashchange;
- [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler oninput;
- attribute EventHandler oninvalid;
- [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onkeydown;
- [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onkeypress;
- [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onkeyup;
- attribute EventHandler onload;
- attribute EventHandler onloadeddata;
- attribute EventHandler onloadedmetadata;
- attribute EventHandler onloadstart;
- attribute EventHandler onmessage;
- [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onmousedown;
- [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onmouseenter;
- [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onmouseleave;
- [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onmousemove;
- [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onmouseout;
- [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onmouseover;
- [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onmouseup;
- [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onmousewheel; // Deprecated in favor of onwheel.
- [PerWorldBindings, ActivityLog=SetterForIsolatedWorlds] attribute EventHandler onwheel;
- attribute EventHandler onoffline;
- attribute EventHandler ononline;
- attribute EventHandler onpagehide;
- attribute EventHandler onpageshow;
- attribute EventHandler onpause;
- attribute EventHandler onplay;
- attribute EventHandler onplaying;
- attribute EventHandler onpopstate;
- attribute EventHandler onprogress;
- attribute EventHandler onratechange;
- attribute EventHandler onresize;
- attribute EventHandler onscroll;
- attribute EventHandler onseeked;
- attribute EventHandler onseeking;
- attribute EventHandler onselect;
- attribute EventHandler onstalled;
- attribute EventHandler onstorage;
- attribute EventHandler onsubmit;
- attribute EventHandler onsuspend;
- attribute EventHandler ontimeupdate;
- attribute EventHandler onunload;
- attribute EventHandler onvolumechange;
- attribute EventHandler onwaiting;
-
- // Not implemented yet.
- // attribute EventHandler onafterprint;
- // attribute EventHandler onbeforeprint;
- // attribute EventHandler onreadystatechange;
- // attribute EventHandler onredo;
- // attribute EventHandler onshow;
- // attribute EventHandler onundo;
-
- // Webkit extensions
- attribute EventHandler onreset;
- attribute EventHandler onsearch;
- [EnabledAtRuntime=CSSAnimationUnprefixed] attribute EventHandler onanimationend;
- [EnabledAtRuntime=CSSAnimationUnprefixed] attribute EventHandler onanimationiteration;
- [EnabledAtRuntime=CSSAnimationUnprefixed] attribute EventHandler onanimationstart;
- attribute EventHandler onwebkitanimationend;
- attribute EventHandler onwebkitanimationiteration;
- attribute EventHandler onwebkitanimationstart;
- attribute EventHandler onwebkittransitionend;
- attribute EventHandler ontransitionend;
- [Conditional=ORIENTATION_EVENTS] attribute EventHandler onorientationchange;
- [EnabledAtRuntime=Touch] attribute EventHandler ontouchstart;
- [EnabledAtRuntime=Touch] attribute EventHandler ontouchmove;
- [EnabledAtRuntime=Touch] attribute EventHandler ontouchend;
- [EnabledAtRuntime=Touch] attribute EventHandler ontouchcancel;
-
- [EnabledAtRuntime=DeviceMotion] attribute EventHandler ondevicemotion;
- [EnabledAtRuntime=DeviceOrientation] attribute EventHandler ondeviceorientation;
-
- [DeprecateAs=CaptureEvents] void captureEvents();
- [DeprecateAs=ReleaseEvents] void releaseEvents();
-
- // Additional constructors.
- attribute TransitionEventConstructor WebKitTransitionEvent;
- [EnabledAtRuntime=CSSAnimationUnprefixed] attribute WebKitAnimationEventConstructor AnimationEvent;
- [CustomConstructor] attribute HTMLImageElementConstructorConstructor Image; // Usable with new operator
- // Mozilla has a separate XMLDocument object for XML documents.
- // We just use Document for this.
- attribute DocumentConstructor XMLDocument;
- attribute URLConstructor webkitURL; // FIXME: deprecate this.
- attribute MutationObserverConstructor WebKitMutationObserver; // FIXME: Add metrics to determine when we can remove this.
- attribute IDBCursorConstructor webkitIDBCursor;
- attribute IDBDatabaseConstructor webkitIDBDatabase;
- attribute IDBFactoryConstructor webkitIDBFactory;
- attribute IDBIndexConstructor webkitIDBIndex;
- attribute IDBKeyRangeConstructor webkitIDBKeyRange;
- attribute IDBObjectStoreConstructor webkitIDBObjectStore;
- attribute IDBRequestConstructor webkitIDBRequest;
- attribute IDBTransactionConstructor webkitIDBTransaction;
-
- // Constructors whose name does not match the interface name.
- // FIXME: Remove these once [ImplementedAs] is used and once constructor names match interface names.
- [EnabledAtRuntime=MediaStream] attribute MediaStreamConstructor webkitMediaStream;
- [Conditional=WEB_AUDIO, EnabledAtRuntime=WebAudio] attribute AudioContextConstructor webkitAudioContext;
- [Conditional=WEB_AUDIO, EnabledAtRuntime=WebAudio] attribute OfflineAudioContextConstructor webkitOfflineAudioContext;
- [EnabledAtRuntime=PeerConnection] attribute RTCPeerConnectionConstructor webkitRTCPeerConnection;
- [EnabledAtRuntime=ScriptedSpeech] attribute SpeechGrammarConstructor webkitSpeechGrammar;
- [EnabledAtRuntime=ScriptedSpeech] attribute SpeechGrammarListConstructor webkitSpeechGrammarList;
- [EnabledAtRuntime=ScriptedSpeech] attribute SpeechRecognitionConstructor webkitSpeechRecognition;
- [EnabledAtRuntime=ScriptedSpeech] attribute SpeechRecognitionErrorConstructor webkitSpeechRecognitionError;
- [EnabledAtRuntime=ScriptedSpeech] attribute SpeechRecognitionEventConstructor webkitSpeechRecognitionEvent;
- [Conditional=WEB_AUDIO] attribute PannerNodeConstructor webkitAudioPannerNode;
-
- // Prefixed ShadowRoot constructor should be phased out eventually, but for the moment it must be always exposed.
- // Unprefixed ShadowRoot constructor should be visible when the feature flag is enabled.
- // FIXME: When it's ready to remove WebKitShadowRoot, get rid of both constructors from Window.idl and remove
- // [NoInterfaceObject] from ShadowRoot interface definition.
- [EnabledAtRuntime=ShadowDOM] attribute ShadowRootConstructor ShadowRoot;
- [MeasureAs=PrefixedShadowRootConstructor] attribute ShadowRootConstructor WebKitShadowRoot;
-
- // window.toString() requires special handling in V8
- [DoNotCheckSignature, DoNotCheckSecurity, Custom, NotEnumerable] DOMString toString();
-
- [ImplementedAs=anonymousIndexedGetter, NotEnumerable] getter Window(unsigned long index);
- [Custom, NotEnumerable] getter Window (DOMString name);
-};
-
-Window implements ImageBitmapFactories;
-Window implements WindowTimers;
-Window implements WindowBase64;
diff --git a/chromium/third_party/WebKit/Source/core/page/WindowBase64.idl b/chromium/third_party/WebKit/Source/core/page/WindowBase64.idl
deleted file mode 100644
index e27a93b90ee..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/WindowBase64.idl
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Copyright (C) 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
- * Copyright (C) 2011 Google Inc. All rights reserved.
- * Copyright (C) 2013 Samsung Electronics. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-[
- NoInterfaceObject,
- ImplementedAs=DOMWindowBase64
-] interface WindowBase64 {
- [RaisesException] DOMString atob(DOMString string);
- [RaisesException] DOMString btoa(DOMString string);
-};
diff --git a/chromium/third_party/WebKit/Source/core/page/WindowFeatures.cpp b/chromium/third_party/WebKit/Source/core/page/WindowFeatures.cpp
index 8614ea0d6fa..3796f0bb496 100644
--- a/chromium/third_party/WebKit/Source/core/page/WindowFeatures.cpp
+++ b/chromium/third_party/WebKit/Source/core/page/WindowFeatures.cpp
@@ -23,7 +23,7 @@
#include "config.h"
#include "core/page/WindowFeatures.h"
-#include "core/platform/graphics/FloatRect.h"
+#include "platform/geometry/FloatRect.h"
#include "wtf/Assertions.h"
#include "wtf/MathExtras.h"
#include "wtf/text/StringHash.h"
diff --git a/chromium/third_party/WebKit/Source/core/page/WindowPagePopup.idl b/chromium/third_party/WebKit/Source/core/page/WindowPagePopup.idl
index 0ae9bbe30b7..e4b58393448 100644
--- a/chromium/third_party/WebKit/Source/core/page/WindowPagePopup.idl
+++ b/chromium/third_party/WebKit/Source/core/page/WindowPagePopup.idl
@@ -29,8 +29,8 @@
*/
[
- EnabledAtRuntime=PagePopup,
+ RuntimeEnabled=PagePopup,
ImplementedAs=DOMWindowPagePopup
] partial interface Window {
- [EnabledPerContext=pagePopup] readonly attribute PagePopupController pagePopupController;
+ [PerContextEnabled=PagePopup] readonly attribute PagePopupController pagePopupController;
};
diff --git a/chromium/third_party/WebKit/Source/core/page/WorkerNavigator.cpp b/chromium/third_party/WebKit/Source/core/page/WorkerNavigator.cpp
deleted file mode 100644
index 76d5058d400..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/WorkerNavigator.cpp
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Copyright (C) 2008 Apple Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-#include "config.h"
-
-#include "core/page/WorkerNavigator.h"
-
-namespace WebCore {
-
-WorkerNavigator::WorkerNavigator(const String& userAgent)
- : m_userAgent(userAgent)
-{
- ScriptWrappable::init(this);
-}
-
-WorkerNavigator::~WorkerNavigator()
-{
-}
-
-String WorkerNavigator::userAgent() const
-{
- return m_userAgent;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/page/WorkerNavigator.h b/chromium/third_party/WebKit/Source/core/page/WorkerNavigator.h
deleted file mode 100644
index 710f30752f0..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/WorkerNavigator.h
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright (C) 2008 Apple Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-*/
-
-#ifndef WorkerNavigator_h
-#define WorkerNavigator_h
-
-#include "bindings/v8/ScriptWrappable.h"
-#include "core/page/NavigatorBase.h"
-#include "core/platform/Supplementable.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class WorkerNavigator : public RefCounted<WorkerNavigator>, public ScriptWrappable, public NavigatorBase, public Supplementable<WorkerNavigator> {
-public:
- static PassRefPtr<WorkerNavigator> create(const String& userAgent) { return adoptRef(new WorkerNavigator(userAgent)); }
- virtual ~WorkerNavigator();
-
- virtual String userAgent() const OVERRIDE;
-
-private:
- explicit WorkerNavigator(const String&);
-
- String m_userAgent;
-};
-
-} // namespace WebCore
-
-#endif // WorkerNavigator_h
diff --git a/chromium/third_party/WebKit/Source/core/page/animation/AnimationBase.cpp b/chromium/third_party/WebKit/Source/core/page/animation/AnimationBase.cpp
deleted file mode 100644
index f5dd049cf0b..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/animation/AnimationBase.cpp
+++ /dev/null
@@ -1,594 +0,0 @@
-/*
- * Copyright (C) 2007, 2008, 2009 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/page/animation/AnimationBase.h"
-
-#include "core/page/animation/AnimationControllerPrivate.h"
-#include "core/page/animation/CompositeAnimation.h"
-#include "core/platform/animation/AnimationUtilities.h"
-#include "core/platform/animation/TimingFunction.h"
-#include "core/rendering/RenderBox.h"
-#include <algorithm>
-
-using namespace std;
-
-namespace WebCore {
-
-AnimationBase::AnimationBase(const CSSAnimationData* transition, RenderObject* renderer, CompositeAnimation* compAnim)
- : m_animState(AnimationStateNew)
- , m_isAccelerated(false)
- , m_transformFunctionListValid(false)
- , m_filterFunctionListsMatch(false)
- , m_startTime(0)
- , m_pauseTime(-1)
- , m_requestedStartTime(0)
- , m_totalDuration(-1)
- , m_nextIterationDuration(-1)
- , m_object(renderer)
- , m_animation(const_cast<CSSAnimationData*>(transition))
- , m_compAnim(compAnim)
-{
- // Compute the total duration
- if (m_animation->iterationCount() > 0)
- m_totalDuration = m_animation->duration() * m_animation->iterationCount();
-}
-
-void AnimationBase::setNeedsStyleRecalc(Node* node)
-{
- if (node)
- node->setNeedsStyleRecalc(LocalStyleChange);
-}
-
-double AnimationBase::duration() const
-{
- return m_animation->duration();
-}
-
-bool AnimationBase::playStatePlaying() const
-{
- return m_animation->playState() == AnimPlayStatePlaying;
-}
-
-void AnimationBase::updateStateMachine(AnimStateInput input, double param)
-{
- if (!m_compAnim)
- return;
-
- // If we get AnimationStateInputRestartAnimation then we force a new animation, regardless of state.
- if (input == AnimationStateInputMakeNew) {
- if (m_animState == AnimationStateStartWaitStyleAvailable)
- m_compAnim->animationController()->removeFromAnimationsWaitingForStyle(this);
- m_animState = AnimationStateNew;
- m_startTime = 0;
- m_pauseTime = -1;
- m_requestedStartTime = 0;
- m_nextIterationDuration = -1;
- endAnimation();
- return;
- }
-
- if (input == AnimationStateInputRestartAnimation) {
- if (m_animState == AnimationStateStartWaitStyleAvailable)
- m_compAnim->animationController()->removeFromAnimationsWaitingForStyle(this);
- m_animState = AnimationStateNew;
- m_startTime = 0;
- m_pauseTime = -1;
- m_requestedStartTime = 0;
- m_nextIterationDuration = -1;
- endAnimation();
-
- if (!paused())
- updateStateMachine(AnimationStateInputStartAnimation, -1);
- return;
- }
-
- if (input == AnimationStateInputEndAnimation) {
- if (m_animState == AnimationStateStartWaitStyleAvailable)
- m_compAnim->animationController()->removeFromAnimationsWaitingForStyle(this);
- m_animState = AnimationStateDone;
- endAnimation();
- return;
- }
-
- if (input == AnimationStateInputPauseOverride) {
- if (m_animState == AnimationStateStartWaitResponse) {
- // If we are in AnimationStateStartWaitResponse, the animation will get canceled before
- // we get a response, so move to the next state.
- endAnimation();
- updateStateMachine(AnimationStateInputStartTimeSet, beginAnimationUpdateTime());
- }
- return;
- }
-
- if (input == AnimationStateInputResumeOverride) {
- if (m_animState == AnimationStateLooping || m_animState == AnimationStateEnding) {
- // Start the animation
- startAnimation(beginAnimationUpdateTime() - m_startTime);
- }
- return;
- }
-
- // Execute state machine
- switch (m_animState) {
- case AnimationStateNew:
- ASSERT(input == AnimationStateInputStartAnimation || input == AnimationStateInputPlayStateRunning || input == AnimationStateInputPlayStatePaused);
- if (input == AnimationStateInputStartAnimation || input == AnimationStateInputPlayStateRunning) {
- m_requestedStartTime = beginAnimationUpdateTime();
- m_animState = AnimationStateStartWaitTimer;
- }
- break;
- case AnimationStateStartWaitTimer:
- ASSERT(input == AnimationStateInputStartTimerFired || input == AnimationStateInputPlayStatePaused);
-
- if (input == AnimationStateInputStartTimerFired) {
- ASSERT(param >= 0);
- // Start timer has fired, tell the animation to start and wait for it to respond with start time
- m_animState = AnimationStateStartWaitStyleAvailable;
- m_compAnim->animationController()->addToAnimationsWaitingForStyle(this);
-
- // Trigger a render so we can start the animation
- if (m_object)
- m_compAnim->animationController()->addNodeChangeToDispatch(m_object->node());
- } else {
- ASSERT(!paused());
- // We're waiting for the start timer to fire and we got a pause. Cancel the timer, pause and wait
- m_pauseTime = beginAnimationUpdateTime();
- m_animState = AnimationStatePausedWaitTimer;
- }
- break;
- case AnimationStateStartWaitStyleAvailable:
- ASSERT(input == AnimationStateInputStyleAvailable || input == AnimationStateInputPlayStatePaused);
-
- if (input == AnimationStateInputStyleAvailable) {
- // Start timer has fired, tell the animation to start and wait for it to respond with start time
- m_animState = AnimationStateStartWaitResponse;
-
- overrideAnimations();
-
- // Start the animation
- if (overridden()) {
- // We won't try to start accelerated animations if we are overridden and
- // just move on to the next state.
- m_animState = AnimationStateStartWaitResponse;
- m_isAccelerated = false;
- updateStateMachine(AnimationStateInputStartTimeSet, beginAnimationUpdateTime());
- } else {
- double timeOffset = 0;
- // If the value for 'animation-delay' is negative then the animation appears to have started in the past.
- if (m_animation->delay() < 0)
- timeOffset = -m_animation->delay();
- bool started = startAnimation(timeOffset);
-
- m_compAnim->animationController()->addToAnimationsWaitingForStartTimeResponse(this, started);
- m_isAccelerated = started;
- }
- } else {
- // We're waiting for the style to be available and we got a pause. Pause and wait
- m_pauseTime = beginAnimationUpdateTime();
- m_animState = AnimationStatePausedWaitStyleAvailable;
- }
- break;
- case AnimationStateStartWaitResponse:
- ASSERT(input == AnimationStateInputStartTimeSet || input == AnimationStateInputPlayStatePaused);
-
- if (input == AnimationStateInputStartTimeSet) {
- ASSERT(param >= 0);
- // We have a start time, set it, unless the startTime is already set
- if (m_startTime <= 0) {
- m_startTime = param;
- // If the value for 'animation-delay' is negative then the animation appears to have started in the past.
- if (m_animation->delay() < 0)
- m_startTime += m_animation->delay();
- }
-
- // Now that we know the start time, fire the start event.
- onAnimationStart(0); // The elapsedTime is 0.
-
- // Decide whether to go into looping or ending state
- goIntoEndingOrLoopingState();
-
- // Dispatch updateStyleIfNeeded so we can start the animation
- if (m_object)
- m_compAnim->animationController()->addNodeChangeToDispatch(m_object->node());
- } else {
- // We are pausing while waiting for a start response. Cancel the animation and wait. When
- // we unpause, we will act as though the start timer just fired
- m_pauseTime = beginAnimationUpdateTime();
- pauseAnimation(beginAnimationUpdateTime() - m_startTime);
- m_animState = AnimationStatePausedWaitResponse;
- }
- break;
- case AnimationStateLooping:
- ASSERT(input == AnimationStateInputLoopTimerFired || input == AnimationStateInputPlayStatePaused);
-
- if (input == AnimationStateInputLoopTimerFired) {
- ASSERT(param >= 0);
- // Loop timer fired, loop again or end.
- onAnimationIteration(param);
-
- // Decide whether to go into looping or ending state
- goIntoEndingOrLoopingState();
- } else {
- // We are pausing while running. Cancel the animation and wait
- m_pauseTime = beginAnimationUpdateTime();
- pauseAnimation(beginAnimationUpdateTime() - m_startTime);
- m_animState = AnimationStatePausedRun;
- }
- break;
- case AnimationStateEnding:
-#if !LOG_DISABLED
- if (input != AnimationStateInputEndTimerFired && input != AnimationStateInputPlayStatePaused)
- LOG_ERROR("State is AnimationStateEnding, but input is not AnimationStateInputEndTimerFired or AnimationStateInputPlayStatePaused. It is %d.", input);
-#endif
- if (input == AnimationStateInputEndTimerFired) {
-
- ASSERT(param >= 0);
- // End timer fired, finish up
- onAnimationEnd(param);
-
- m_animState = AnimationStateDone;
-
- if (m_object) {
- if (m_animation->fillsForwards())
- m_animState = AnimationStateFillingForwards;
- else
- resumeOverriddenAnimations();
-
- // Fire off another style change so we can set the final value
- m_compAnim->animationController()->addNodeChangeToDispatch(m_object->node());
- }
- } else {
- // We are pausing while running. Cancel the animation and wait
- m_pauseTime = beginAnimationUpdateTime();
- pauseAnimation(beginAnimationUpdateTime() - m_startTime);
- m_animState = AnimationStatePausedRun;
- }
- // |this| may be deleted here
- break;
- case AnimationStatePausedWaitTimer:
- ASSERT(input == AnimationStateInputPlayStateRunning);
- ASSERT(paused());
- // Update the times
- m_startTime += beginAnimationUpdateTime() - m_pauseTime;
- m_pauseTime = -1;
-
- // we were waiting for the start timer to fire, go back and wait again
- m_animState = AnimationStateNew;
- updateStateMachine(AnimationStateInputStartAnimation, 0);
- break;
- case AnimationStatePausedWaitResponse:
- case AnimationStatePausedWaitStyleAvailable:
- case AnimationStatePausedRun:
- // We treat these two cases the same. The only difference is that, when we are in
- // AnimationStatePausedWaitResponse, we don't yet have a valid startTime, so we send 0 to startAnimation.
- // When the AnimationStateInputStartTimeSet comes in and we were in AnimationStatePausedRun, we will notice
- // that we have already set the startTime and will ignore it.
- ASSERT(input == AnimationStateInputPlayStateRunning || input == AnimationStateInputStartTimeSet || input == AnimationStateInputStyleAvailable);
- ASSERT(paused());
-
- if (input == AnimationStateInputPlayStateRunning) {
- // Update the times
- if (m_animState == AnimationStatePausedRun)
- m_startTime += beginAnimationUpdateTime() - m_pauseTime;
- else
- m_startTime = 0;
- m_pauseTime = -1;
-
- if (m_animState == AnimationStatePausedWaitStyleAvailable)
- m_animState = AnimationStateStartWaitStyleAvailable;
- else {
- // We were either running or waiting for a begin time response from the animation.
- // Either way we need to restart the animation (possibly with an offset if we
- // had already been running) and wait for it to start.
- m_animState = AnimationStateStartWaitResponse;
-
- // Start the animation
- if (overridden()) {
- // We won't try to start accelerated animations if we are overridden and
- // just move on to the next state.
- updateStateMachine(AnimationStateInputStartTimeSet, beginAnimationUpdateTime());
- m_isAccelerated = true;
- } else {
- bool started = startAnimation(beginAnimationUpdateTime() - m_startTime);
- m_compAnim->animationController()->addToAnimationsWaitingForStartTimeResponse(this, started);
- m_isAccelerated = started;
- }
- }
- break;
- }
-
- if (input == AnimationStateInputStartTimeSet) {
- ASSERT(m_animState == AnimationStatePausedWaitResponse);
-
- // We are paused but we got the callback that notifies us that an accelerated animation started.
- // We ignore the start time and just move into the paused-run state.
- m_animState = AnimationStatePausedRun;
- ASSERT(m_startTime == 0);
- m_startTime = param;
- m_pauseTime += m_startTime;
- break;
- }
-
- ASSERT(m_animState == AnimationStatePausedWaitStyleAvailable);
- // We are paused but we got the callback that notifies us that style has been updated.
- // We move to the AnimationStatePausedWaitResponse state
- m_animState = AnimationStatePausedWaitResponse;
- overrideAnimations();
- break;
- case AnimationStateFillingForwards:
- case AnimationStateDone:
- // We're done. Stay in this state until we are deleted
- break;
- }
-}
-
-void AnimationBase::fireAnimationEventsIfNeeded()
-{
- if (!m_compAnim)
- return;
-
- // If we are waiting for the delay time to expire and it has, go to the next state
- if (m_animState != AnimationStateStartWaitTimer && m_animState != AnimationStateLooping && m_animState != AnimationStateEnding)
- return;
-
- // We have to make sure to keep a ref to the this pointer, because it could get destroyed
- // during an animation callback that might get called. Since the owner is a CompositeAnimation
- // and it ref counts this object, we will keep a ref to that instead. That way the AnimationBase
- // can still access the resources of its CompositeAnimation as needed.
- RefPtr<AnimationBase> protector(this);
- RefPtr<CompositeAnimation> compProtector(m_compAnim);
-
- // Check for start timeout
- if (m_animState == AnimationStateStartWaitTimer) {
- if (beginAnimationUpdateTime() - m_requestedStartTime >= m_animation->delay())
- updateStateMachine(AnimationStateInputStartTimerFired, 0);
- return;
- }
-
- double elapsedDuration = getElapsedTime();
-
- // Check for end timeout
- if (m_totalDuration >= 0 && elapsedDuration >= m_totalDuration) {
- // We may still be in AnimationStateLooping if we've managed to skip a
- // whole iteration, in which case we should jump to the end state.
- m_animState = AnimationStateEnding;
-
- // Fire an end event
- updateStateMachine(AnimationStateInputEndTimerFired, m_totalDuration);
- } else {
- // Check for iteration timeout
- if (m_nextIterationDuration < 0) {
- // Hasn't been set yet, set it
- double durationLeft = m_animation->duration() - fmod(elapsedDuration, m_animation->duration());
- m_nextIterationDuration = elapsedDuration + durationLeft;
- }
-
- if (elapsedDuration >= m_nextIterationDuration) {
- // Set to the next iteration
- double previous = m_nextIterationDuration;
- double durationLeft = m_animation->duration() - fmod(elapsedDuration, m_animation->duration());
- m_nextIterationDuration = elapsedDuration + durationLeft;
-
- // Send the event
- updateStateMachine(AnimationStateInputLoopTimerFired, previous);
- }
- }
-}
-
-void AnimationBase::updatePlayState(EAnimPlayState playState)
-{
- if (!m_compAnim)
- return;
-
- // When we get here, we can have one of 4 desired states: running, paused, suspended, paused & suspended.
- // The state machine can be in one of two states: running, paused.
- // Set the state machine to the desired state.
- bool pause = playState == AnimPlayStatePaused || m_compAnim->suspended();
-
- if (pause == paused() && !isNew())
- return;
-
- updateStateMachine(pause ? AnimationStateInputPlayStatePaused : AnimationStateInputPlayStateRunning, -1);
-}
-
-double AnimationBase::timeToNextService()
-{
- // Returns the time at which next service is required. -1 means no service is required. 0 means
- // service is required now, and > 0 means service is required that many seconds in the future.
- if (paused() || isNew() || m_animState == AnimationStateFillingForwards)
- return -1;
-
- if (m_animState == AnimationStateStartWaitTimer) {
- double timeFromNow = m_animation->delay() - (beginAnimationUpdateTime() - m_requestedStartTime);
- return max(timeFromNow, 0.0);
- }
-
- fireAnimationEventsIfNeeded();
-
- // In all other cases, we need service right away.
- return 0;
-}
-
-// Compute the fractional time, taking into account direction.
-// There is no need to worry about iterations, we assume that we would have
-// short circuited above if we were done.
-
-double AnimationBase::fractionalTime(double scale, double elapsedTime, double offset) const
-{
- double fractionalTime = m_animation->duration() ? (elapsedTime / m_animation->duration()) : 1;
- // FIXME: startTime can be before the current animation "frame" time. This is to sync with the frame time
- // concept in AnimationTimeController. So we need to somehow sync the two. Until then, the possible
- // error is small and will probably not be noticeable. Until we fix this, remove the assert.
- // https://bugs.webkit.org/show_bug.cgi?id=52037
- // ASSERT(fractionalTime >= 0);
- if (fractionalTime < 0)
- fractionalTime = 0;
-
- int integralTime = static_cast<int>(fractionalTime);
- const int integralIterationCount = static_cast<int>(m_animation->iterationCount());
- const bool iterationCountHasFractional = m_animation->iterationCount() - integralIterationCount;
- if (m_animation->iterationCount() != CSSAnimationData::IterationCountInfinite && !iterationCountHasFractional)
- integralTime = min(integralTime, integralIterationCount - 1);
-
- fractionalTime -= integralTime;
-
- // Thie method can be called with an elapsedTime which very slightly
- // exceeds the end of the animation. In this case, clamp the
- // fractionalTime.
- if (fractionalTime > 1)
- fractionalTime = 1;
- ASSERT(fractionalTime >= 0 && fractionalTime <= 1);
-
- if (((m_animation->direction() == CSSAnimationData::AnimationDirectionAlternate) && (integralTime & 1))
- || ((m_animation->direction() == CSSAnimationData::AnimationDirectionAlternateReverse) && !(integralTime & 1))
- || m_animation->direction() == CSSAnimationData::AnimationDirectionReverse)
- fractionalTime = 1 - fractionalTime;
-
- fractionalTime -= offset;
- // Note that if fractionalTime == 0 here, scale may be infinity, but in
- // this case we don't need to apply scale anyway.
- if (scale != 1.0 && fractionalTime) {
- ASSERT(scale >= 0 && !std::isinf(scale));
- fractionalTime *= scale;
- }
-
- ASSERT(fractionalTime >= 0 && fractionalTime <= 1);
- return fractionalTime;
-}
-
-double AnimationBase::progress(double scale, double offset, const TimingFunction* timingFunction) const
-{
- if (preActive())
- return 0;
-
- double dur = m_animation->duration();
- if (m_animation->iterationCount() > 0)
- dur *= m_animation->iterationCount();
-
- if (postActive() || !m_animation->duration())
- return 1.0;
-
- double elapsedTime = getElapsedTime();
- if (m_animation->iterationCount() > 0 && elapsedTime >= dur) {
- const int integralIterationCount = static_cast<int>(m_animation->iterationCount());
- const bool iterationCountHasFractional = m_animation->iterationCount() - integralIterationCount;
- return (integralIterationCount % 2 || iterationCountHasFractional) ? 1.0 : 0.0;
- }
-
- const double fractionalTime = this->fractionalTime(scale, elapsedTime, offset);
-
- if (!timingFunction)
- timingFunction = m_animation->timingFunction();
-
- return timingFunction->evaluate(fractionalTime, accuracyForDuration(m_animation->duration()));
-}
-
-void AnimationBase::getTimeToNextEvent(double& time, bool& isLooping) const
-{
- if (postActive()) {
- time = -1;
- isLooping = false;
- return;
- }
-
- // Decide when the end or loop event needs to fire
- const double elapsedDuration = getElapsedTime();
- double durationLeft = 0;
- double nextIterationTime = m_totalDuration;
-
- if (m_totalDuration < 0 || elapsedDuration < m_totalDuration) {
- durationLeft = m_animation->duration() > 0 ? (m_animation->duration() - fmod(elapsedDuration, m_animation->duration())) : 0;
- nextIterationTime = elapsedDuration + durationLeft;
- }
-
- if (m_totalDuration < 0 || nextIterationTime < m_totalDuration) {
- // We are not at the end yet
- ASSERT(nextIterationTime > 0);
- isLooping = true;
- } else {
- // We are at the end
- isLooping = false;
- }
-
- time = durationLeft;
-}
-
-void AnimationBase::goIntoEndingOrLoopingState()
-{
- double t;
- bool isLooping;
- getTimeToNextEvent(t, isLooping);
- m_animState = isLooping ? AnimationStateLooping : AnimationStateEnding;
-}
-
-void AnimationBase::freezeAtTime(double t)
-{
- if (!m_compAnim)
- return;
-
- if (!m_startTime) {
- // If we haven't started yet, make it as if we started.
- m_animState = AnimationStateStartWaitResponse;
- onAnimationStartResponse(beginAnimationUpdateTime());
- }
-
- ASSERT(m_startTime); // if m_startTime is zero, we haven't started yet, so we'll get a bad pause time.
- if (t <= m_animation->delay())
- m_pauseTime = m_startTime;
- else
- m_pauseTime = m_startTime + t - m_animation->delay();
-
- if (m_object && m_object->isComposited())
- toRenderBoxModelObject(m_object)->suspendAnimations(m_pauseTime);
-}
-
-double AnimationBase::beginAnimationUpdateTime() const
-{
- if (!m_compAnim)
- return 0;
-
- return m_compAnim->animationController()->beginAnimationUpdateTime();
-}
-
-double AnimationBase::getElapsedTime() const
-{
- ASSERT(!postActive());
- if (paused())
- return m_pauseTime - m_startTime;
- if (m_startTime <= 0)
- return 0;
-
- double elapsedTime = beginAnimationUpdateTime() - m_startTime;
- // It's possible for the start time to be ahead of the last update time
- // if the compositor has just sent notification for the start of an
- // accelerated animation.
- return max(elapsedTime, 0.0);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/page/animation/AnimationBase.h b/chromium/third_party/WebKit/Source/core/page/animation/AnimationBase.h
deleted file mode 100644
index 29cdb42175b..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/animation/AnimationBase.h
+++ /dev/null
@@ -1,229 +0,0 @@
-/*
- * Copyright (C) 2007 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef AnimationBase_h
-#define AnimationBase_h
-
-#include "CSSPropertyNames.h"
-#include "core/platform/animation/CSSAnimationData.h"
-#include "core/rendering/style/RenderStyleConstants.h"
-#include "wtf/RefCounted.h"
-
-namespace WebCore {
-
-class AnimationBase;
-class AnimationController;
-class CompositeAnimation;
-class Element;
-class Node;
-class RenderObject;
-class RenderStyle;
-class TimingFunction;
-
-class AnimationBase : public RefCounted<AnimationBase> {
- friend class CompositeAnimation;
- friend class CSSPropertyAnimation;
-
-public:
- AnimationBase(const CSSAnimationData* transition, RenderObject* renderer, CompositeAnimation* compAnim);
- virtual ~AnimationBase() { }
-
- RenderObject* renderer() const { return m_object; }
- void clear()
- {
- endAnimation();
- m_object = 0;
- m_compAnim = 0;
- }
-
- double duration() const;
-
- // Animations and Transitions go through the states below. When entering the STARTED state
- // the animation is started. This may or may not require deferred response from the animator.
- // If so, we stay in this state until that response is received (and it returns the start time).
- // Otherwise, we use the current time as the start time and go immediately to AnimationStateLooping
- // or AnimationStateEnding.
- enum AnimState {
- AnimationStateNew, // animation just created, animation not running yet
- AnimationStateStartWaitTimer, // start timer running, waiting for fire
- AnimationStateStartWaitStyleAvailable, // waiting for style setup so we can start animations
- AnimationStateStartWaitResponse, // animation started, waiting for response
- AnimationStateLooping, // response received, animation running, loop timer running, waiting for fire
- AnimationStateEnding, // received, animation running, end timer running, waiting for fire
- AnimationStatePausedWaitTimer, // in pause mode when animation started
- AnimationStatePausedWaitStyleAvailable, // in pause mode when waiting for style setup
- AnimationStatePausedWaitResponse, // animation paused when in STARTING state
- AnimationStatePausedRun, // animation paused when in LOOPING or ENDING state
- AnimationStateDone, // end timer fired, animation finished and removed
- AnimationStateFillingForwards // animation has ended and is retaining its final value
- };
-
- enum AnimStateInput {
- AnimationStateInputMakeNew, // reset back to new from any state
- AnimationStateInputStartAnimation, // animation requests a start
- AnimationStateInputRestartAnimation, // force a restart from any state
- AnimationStateInputStartTimerFired, // start timer fired
- AnimationStateInputStyleAvailable, // style is setup, ready to start animating
- AnimationStateInputStartTimeSet, // m_startTime was set
- AnimationStateInputLoopTimerFired, // loop timer fired
- AnimationStateInputEndTimerFired, // end timer fired
- AnimationStateInputPauseOverride, // pause an animation due to override
- AnimationStateInputResumeOverride, // resume an overridden animation
- AnimationStateInputPlayStateRunning, // play state paused -> running
- AnimationStateInputPlayStatePaused, // play state running -> paused
- AnimationStateInputEndAnimation // force an end from any state
- };
-
- // Called when animation is in AnimationStateNew to start animation
- void updateStateMachine(AnimStateInput, double param);
-
- // Animation has actually started, at passed time
- void onAnimationStartResponse(double startTime)
- {
- updateStateMachine(AnimationBase::AnimationStateInputStartTimeSet, startTime);
- }
-
- // Called to change to or from paused state
- void updatePlayState(EAnimPlayState);
- bool playStatePlaying() const;
-
- bool waitingToStart() const { return m_animState == AnimationStateNew || m_animState == AnimationStateStartWaitTimer; }
- bool preActive() const
- {
- return m_animState == AnimationStateNew || m_animState == AnimationStateStartWaitTimer || m_animState == AnimationStateStartWaitStyleAvailable || m_animState == AnimationStateStartWaitResponse;
- }
-
- bool postActive() const { return m_animState == AnimationStateDone; }
- bool active() const { return !postActive() && !preActive(); }
- bool running() const { return !isNew() && !postActive(); }
- bool paused() const { return m_pauseTime >= 0; }
- bool isNew() const { return m_animState == AnimationStateNew; }
- bool waitingForStartTime() const { return m_animState == AnimationStateStartWaitResponse; }
- bool waitingForStyleAvailable() const { return m_animState == AnimationStateStartWaitStyleAvailable; }
-
- virtual double timeToNextService();
-
- double progress(double scale, double offset, const TimingFunction*) const;
-
- virtual void animate(CompositeAnimation*, RenderObject*, const RenderStyle* /*currentStyle*/, RenderStyle* /*targetStyle*/, RefPtr<RenderStyle>& /*animatedStyle*/) = 0;
- virtual void getAnimatedStyle(RefPtr<RenderStyle>& /*animatedStyle*/) = 0;
-
- virtual bool shouldFireEvents() const { return false; }
-
- void fireAnimationEventsIfNeeded();
-
- void setAnimation(const CSSAnimationData* anim) { m_animation = const_cast<CSSAnimationData*>(anim); }
-
- // Return true if this animation is overridden. This will only be the case for
- // ImplicitAnimations and is used to determine whether or not we should force
- // set the start time. If an animation is overridden, it will probably not get
- // back the AnimationStateInputStartTimeSet input.
- virtual bool overridden() const { return false; }
-
- // Does this animation/transition involve the given property?
- virtual bool affectsProperty(CSSPropertyID /*property*/) const { return false; }
-
- bool isAnimatingProperty(CSSPropertyID property, bool acceleratedOnly, bool isRunningNow) const
- {
- if (acceleratedOnly && !m_isAccelerated)
- return false;
-
- if (isRunningNow)
- return (!waitingToStart() && !postActive()) && affectsProperty(property);
-
- return !postActive() && affectsProperty(property);
- }
-
- // FIXME: rename this using the "lists match" terminology.
- bool isTransformFunctionListValid() const { return m_transformFunctionListValid; }
- bool filterFunctionListsMatch() const { return m_filterFunctionListsMatch; }
-
- // Freeze the animation; used by DumpRenderTree.
- void freezeAtTime(double t);
-
- double beginAnimationUpdateTime() const;
-
- double getElapsedTime() const;
-
- void styleAvailable()
- {
- ASSERT(waitingForStyleAvailable());
- updateStateMachine(AnimationBase::AnimationStateInputStyleAvailable, -1);
- }
-
- const CSSAnimationData* animation() const { return m_animation.get(); }
-
-protected:
- virtual void overrideAnimations() { }
- virtual void resumeOverriddenAnimations() { }
-
- CompositeAnimation* compositeAnimation() { return m_compAnim; }
-
- // These are called when the corresponding timer fires so subclasses can do any extra work
- virtual void onAnimationStart(double /*elapsedTime*/) { }
- virtual void onAnimationIteration(double /*elapsedTime*/) { }
- virtual void onAnimationEnd(double /*elapsedTime*/) { }
-
- // timeOffset is an offset from the current time when the animation should start. Negative values are OK.
- // Return value indicates whether to expect an asynchronous notifyAnimationStarted() callback.
- virtual bool startAnimation(double /*timeOffset*/) { return false; }
- // timeOffset is the time at which the animation is being paused.
- virtual void pauseAnimation(double /*timeOffset*/) { }
- virtual void endAnimation() { }
-
- void goIntoEndingOrLoopingState();
-
- bool isAccelerated() const { return m_isAccelerated; }
-
- static void setNeedsStyleRecalc(Node*);
-
- void getTimeToNextEvent(double& time, bool& isLooping) const;
-
- double fractionalTime(double scale, double elapsedTime, double offset) const;
-
- AnimState m_animState;
-
- bool m_isAccelerated;
- bool m_transformFunctionListValid;
- bool m_filterFunctionListsMatch;
- double m_startTime;
- double m_pauseTime;
- double m_requestedStartTime;
-
- double m_totalDuration;
- double m_nextIterationDuration;
-
- RenderObject* m_object;
-
- RefPtr<CSSAnimationData> m_animation;
- CompositeAnimation* m_compAnim;
-};
-
-} // namespace WebCore
-
-#endif // AnimationBase_h
diff --git a/chromium/third_party/WebKit/Source/core/page/animation/AnimationController.cpp b/chromium/third_party/WebKit/Source/core/page/animation/AnimationController.cpp
deleted file mode 100644
index 087325e88c4..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/animation/AnimationController.cpp
+++ /dev/null
@@ -1,615 +0,0 @@
-/*
- * Copyright (C) 2007, 2008, 2009 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/page/animation/AnimationController.h"
-
-#include "core/dom/EventNames.h"
-#include "core/dom/PseudoElement.h"
-#include "core/dom/TransitionEvent.h"
-#include "core/dom/WebKitAnimationEvent.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameView.h"
-#include "core/page/Page.h"
-#include "core/page/animation/AnimationBase.h"
-#include "core/page/animation/AnimationControllerPrivate.h"
-#include "core/page/animation/CSSPropertyAnimation.h"
-#include "core/page/animation/CompositeAnimation.h"
-#include "core/rendering/RenderView.h"
-#include "wtf/CurrentTime.h"
-
-namespace WebCore {
-
-static const double cBeginAnimationUpdateTimeNotSet = -1;
-
-AnimationControllerPrivate::AnimationControllerPrivate(Frame* frame)
- : m_animationTimer(this, &AnimationControllerPrivate::animationTimerFired)
- , m_updateStyleIfNeededDispatcher(this, &AnimationControllerPrivate::updateStyleIfNeededDispatcherFired)
- , m_frame(frame)
- , m_beginAnimationUpdateTime(cBeginAnimationUpdateTimeNotSet)
- , m_animationsWaitingForStyle()
- , m_animationsWaitingForStartTimeResponse()
- , m_waitingForAsyncStartNotification(false)
-{
-}
-
-AnimationControllerPrivate::~AnimationControllerPrivate()
-{
-}
-
-PassRefPtr<CompositeAnimation> AnimationControllerPrivate::accessCompositeAnimation(RenderObject* renderer)
-{
- RefPtr<CompositeAnimation> animation = m_compositeAnimations.get(renderer);
- if (!animation) {
- animation = CompositeAnimation::create(this);
- m_compositeAnimations.set(renderer, animation);
- }
- return animation;
-}
-
-bool AnimationControllerPrivate::clear(RenderObject* renderer)
-{
- // Return false if we didn't do anything OR we are suspended (so we don't try to
- // do a setNeedsStyleRecalc() when suspended).
- PassRefPtr<CompositeAnimation> animation = m_compositeAnimations.take(renderer);
- if (!animation)
- return false;
- animation->clearRenderer();
- return animation->suspended();
-}
-
-void AnimationControllerPrivate::updateAnimations(double& timeToNextService, double& timeToNextEvent, SetNeedsStyleRecalc callSetNeedsStyleRecalc/* = DoNotCallSetNeedsStyleRecalc*/)
-{
- double minTimeToNextService = -1;
- double minTimeToNextEvent = -1;
- bool updateStyleNeeded = false;
-
- RenderObjectAnimationMap::const_iterator animationsEnd = m_compositeAnimations.end();
- for (RenderObjectAnimationMap::const_iterator it = m_compositeAnimations.begin(); it != animationsEnd; ++it) {
- CompositeAnimation* compAnim = it->value.get();
- if (!compAnim->suspended() && compAnim->hasAnimations()) {
- double t = compAnim->timeToNextService();
- if (t != -1 && (t < minTimeToNextService || minTimeToNextService == -1))
- minTimeToNextService = t;
- double nextEvent = compAnim->timeToNextEvent();
- if (nextEvent != -1 && (nextEvent < minTimeToNextEvent || minTimeToNextEvent == -1))
- minTimeToNextEvent = nextEvent;
- if (callSetNeedsStyleRecalc == CallSetNeedsStyleRecalc) {
- if (!t) {
- Node* node = it->key->node();
- node->setNeedsStyleRecalc(LocalStyleChange, StyleChangeFromRenderer);
- updateStyleNeeded = true;
- }
- } else if (!minTimeToNextService && !minTimeToNextEvent) {
- // Found the minimum values and do not need to mark for style recalc.
- break;
- }
- }
- }
-
- if (updateStyleNeeded)
- m_frame->document()->updateStyleIfNeeded();
-
- timeToNextService = minTimeToNextService;
- timeToNextEvent = minTimeToNextEvent;
-}
-
-void AnimationControllerPrivate::scheduleServiceForRenderer(RenderObject* renderer)
-{
- double timeToNextService = -1;
- double timeToNextEvent = -1;
-
- RefPtr<CompositeAnimation> compAnim = m_compositeAnimations.get(renderer);
- if (!compAnim->suspended() && compAnim->hasAnimations()) {
- timeToNextService = compAnim->timeToNextService();
- timeToNextEvent = compAnim->timeToNextEvent();
- }
-
- if (timeToNextService >= 0)
- scheduleService(timeToNextService, timeToNextEvent);
-}
-
-void AnimationControllerPrivate::scheduleService()
-{
- double timeToNextService = -1;
- double timeToNextEvent = -1;
- updateAnimations(timeToNextService, timeToNextEvent, DoNotCallSetNeedsStyleRecalc);
- scheduleService(timeToNextService, timeToNextEvent);
-}
-
-void AnimationControllerPrivate::scheduleService(double timeToNextService, double timeToNextEvent)
-{
- if (!m_frame->page())
- return;
-
- bool visible = m_frame->page()->visibilityState() == WebCore::PageVisibilityStateVisible;
-
- // This std::max to 1 second limits how often we service animations on background tabs.
- // Without this, plus and gmail were recalculating style as every 200ms or even more
- // often, burning CPU needlessly for background tabs.
- // FIXME: Do we want to fire events at all on background tabs?
- if (!visible)
- timeToNextService = std::max(timeToNextEvent, 1.0);
-
- if (visible && !timeToNextService) {
- m_frame->document()->view()->scheduleAnimation();
- if (m_animationTimer.isActive())
- m_animationTimer.stop();
- return;
- }
-
- if (timeToNextService < 0) {
- if (m_animationTimer.isActive())
- m_animationTimer.stop();
- return;
- }
-
- if (m_animationTimer.isActive() && m_animationTimer.nextFireInterval() <= timeToNextService)
- return;
-
- m_animationTimer.startOneShot(timeToNextService);
-}
-
-void AnimationControllerPrivate::updateStyleIfNeededDispatcherFired(Timer<AnimationControllerPrivate>*)
-{
- fireEventsAndUpdateStyle();
-}
-
-void AnimationControllerPrivate::fireEventsAndUpdateStyle()
-{
- // Protect the frame from getting destroyed in the event handler
- RefPtr<Frame> protector = m_frame;
-
- bool updateStyle = !m_eventsToDispatch.isEmpty() || !m_nodeChangesToDispatch.isEmpty();
-
- // fire all the events
- Vector<EventToDispatch> eventsToDispatch = m_eventsToDispatch;
- m_eventsToDispatch.clear();
- Vector<EventToDispatch>::const_iterator eventsToDispatchEnd = eventsToDispatch.end();
- for (Vector<EventToDispatch>::const_iterator it = eventsToDispatch.begin(); it != eventsToDispatchEnd; ++it) {
- Element* element = it->element.get();
- if (it->eventType == eventNames().transitionendEvent)
- element->dispatchEvent(TransitionEvent::create(it->eventType, it->name, it->elapsedTime, PseudoElement::pseudoElementNameForEvents(element->pseudoId())));
- else
- element->dispatchEvent(WebKitAnimationEvent::create(it->eventType, it->name, it->elapsedTime));
- }
-
- // call setChanged on all the elements
- Vector<RefPtr<Node> >::const_iterator nodeChangesToDispatchEnd = m_nodeChangesToDispatch.end();
- for (Vector<RefPtr<Node> >::const_iterator it = m_nodeChangesToDispatch.begin(); it != nodeChangesToDispatchEnd; ++it)
- (*it)->setNeedsStyleRecalc(LocalStyleChange, StyleChangeFromRenderer);
-
- m_nodeChangesToDispatch.clear();
-
- if (updateStyle && m_frame)
- m_frame->document()->updateStyleIfNeeded();
-}
-
-void AnimationControllerPrivate::startUpdateStyleIfNeededDispatcher()
-{
- if (!m_updateStyleIfNeededDispatcher.isActive())
- m_updateStyleIfNeededDispatcher.startOneShot(0);
-}
-
-void AnimationControllerPrivate::addEventToDispatch(PassRefPtr<Element> element, const AtomicString& eventType, const String& name, double elapsedTime)
-{
- m_eventsToDispatch.grow(m_eventsToDispatch.size()+1);
- EventToDispatch& event = m_eventsToDispatch[m_eventsToDispatch.size()-1];
- event.element = element;
- event.eventType = eventType;
- event.name = name;
- event.elapsedTime = elapsedTime;
-
- startUpdateStyleIfNeededDispatcher();
-}
-
-void AnimationControllerPrivate::addNodeChangeToDispatch(PassRefPtr<Node> node)
-{
- if (!node)
- return;
-
- m_nodeChangesToDispatch.append(node);
- startUpdateStyleIfNeededDispatcher();
-}
-
-void AnimationControllerPrivate::serviceAnimations()
-{
- double timeToNextService = -1;
- double timeToNextEvent = -1;
- updateAnimations(timeToNextService, timeToNextEvent, CallSetNeedsStyleRecalc);
- scheduleService(timeToNextService, timeToNextEvent);
-
- // Fire events right away, to avoid a flash of unanimated style after an animation completes, and before
- // the 'end' event fires.
- fireEventsAndUpdateStyle();
-}
-
-void AnimationControllerPrivate::animationTimerFired(Timer<AnimationControllerPrivate>*)
-{
- // Make sure animationUpdateTime is updated, so that it is current even if no
- // styleChange has happened (e.g. accelerated animations)
- setBeginAnimationUpdateTime(cBeginAnimationUpdateTimeNotSet);
- serviceAnimations();
-}
-
-bool AnimationControllerPrivate::isRunningAnimationOnRenderer(RenderObject* renderer, CSSPropertyID property, bool isRunningNow) const
-{
- RefPtr<CompositeAnimation> animation = m_compositeAnimations.get(renderer);
- if (!animation)
- return false;
-
- return animation->isAnimatingProperty(property, false, isRunningNow);
-}
-
-bool AnimationControllerPrivate::isRunningAcceleratableAnimationOnRenderer(RenderObject *renderer) const
-{
- RefPtr<CompositeAnimation> animation = m_compositeAnimations.get(renderer);
- if (!animation)
- return false;
-
- bool acceleratedOnly = false;
- bool isRunningNow = true;
- return animation->isAnimatingProperty(CSSPropertyOpacity, acceleratedOnly, isRunningNow)
- || animation->isAnimatingProperty(CSSPropertyWebkitTransform, acceleratedOnly, isRunningNow)
- || animation->isAnimatingProperty(CSSPropertyWebkitFilter, acceleratedOnly, isRunningNow);
-}
-
-bool AnimationControllerPrivate::isRunningAcceleratedAnimationOnRenderer(RenderObject* renderer, CSSPropertyID property, bool isRunningNow) const
-{
- RefPtr<CompositeAnimation> animation = m_compositeAnimations.get(renderer);
- if (!animation)
- return false;
-
- return animation->isAnimatingProperty(property, true, isRunningNow);
-}
-
-void AnimationControllerPrivate::suspendAnimations()
-{
- suspendAnimationsForDocument(m_frame->document());
-
- // Traverse subframes
- for (Frame* child = m_frame->tree()->firstChild(); child; child = child->tree()->nextSibling())
- child->animation()->suspendAnimations();
-}
-
-void AnimationControllerPrivate::resumeAnimations()
-{
- resumeAnimationsForDocument(m_frame->document());
-
- // Traverse subframes
- for (Frame* child = m_frame->tree()->firstChild(); child; child = child->tree()->nextSibling())
- child->animation()->resumeAnimations();
-}
-
-void AnimationControllerPrivate::suspendAnimationsForDocument(Document* document)
-{
- setBeginAnimationUpdateTime(cBeginAnimationUpdateTimeNotSet);
-
- RenderObjectAnimationMap::const_iterator animationsEnd = m_compositeAnimations.end();
- for (RenderObjectAnimationMap::const_iterator it = m_compositeAnimations.begin(); it != animationsEnd; ++it) {
- RenderObject* renderer = it->key;
- if (&renderer->document() == document) {
- CompositeAnimation* compAnim = it->value.get();
- compAnim->suspendAnimations();
- }
- }
-
- scheduleService();
-}
-
-void AnimationControllerPrivate::resumeAnimationsForDocument(Document* document)
-{
- setBeginAnimationUpdateTime(cBeginAnimationUpdateTimeNotSet);
-
- RenderObjectAnimationMap::const_iterator animationsEnd = m_compositeAnimations.end();
- for (RenderObjectAnimationMap::const_iterator it = m_compositeAnimations.begin(); it != animationsEnd; ++it) {
- RenderObject* renderer = it->key;
- if (&renderer->document() == document) {
- CompositeAnimation* compAnim = it->value.get();
- compAnim->resumeAnimations();
- }
- }
-
- scheduleService();
-}
-
-void AnimationControllerPrivate::pauseAnimationsForTesting(double t)
-{
- RenderObjectAnimationMap::const_iterator animationsEnd = m_compositeAnimations.end();
- for (RenderObjectAnimationMap::const_iterator it = m_compositeAnimations.begin(); it != animationsEnd; ++it) {
- it->value->pauseAnimationsForTesting(t);
- it->key->node()->setNeedsStyleRecalc(LocalStyleChange, StyleChangeFromRenderer);
- }
-}
-
-double AnimationControllerPrivate::beginAnimationUpdateTime()
-{
- if (m_beginAnimationUpdateTime == cBeginAnimationUpdateTimeNotSet)
- m_beginAnimationUpdateTime = currentTime();
- return m_beginAnimationUpdateTime;
-}
-
-void AnimationControllerPrivate::endAnimationUpdate()
-{
- styleAvailable();
- if (!m_waitingForAsyncStartNotification)
- startTimeResponse(beginAnimationUpdateTime());
-}
-
-void AnimationControllerPrivate::receivedStartTimeResponse(double time)
-{
- m_waitingForAsyncStartNotification = false;
- startTimeResponse(time);
-}
-
-PassRefPtr<RenderStyle> AnimationControllerPrivate::getAnimatedStyleForRenderer(RenderObject* renderer)
-{
- if (!renderer)
- return 0;
-
- RefPtr<CompositeAnimation> rendererAnimations = m_compositeAnimations.get(renderer);
- if (!rendererAnimations)
- return renderer->style();
-
- RefPtr<RenderStyle> animatingStyle = rendererAnimations->getAnimatedStyle();
- if (!animatingStyle)
- animatingStyle = renderer->style();
-
- return animatingStyle.release();
-}
-
-unsigned AnimationControllerPrivate::numberOfActiveAnimations(Document* document) const
-{
- unsigned count = 0;
-
- RenderObjectAnimationMap::const_iterator animationsEnd = m_compositeAnimations.end();
- for (RenderObjectAnimationMap::const_iterator it = m_compositeAnimations.begin(); it != animationsEnd; ++it) {
- RenderObject* renderer = it->key;
- CompositeAnimation* compAnim = it->value.get();
- if (&renderer->document() == document)
- count += compAnim->numberOfActiveAnimations();
- }
-
- return count;
-}
-
-void AnimationControllerPrivate::addToAnimationsWaitingForStyle(AnimationBase* animation)
-{
- // Make sure this animation is not in the start time waiters
- m_animationsWaitingForStartTimeResponse.remove(animation);
-
- m_animationsWaitingForStyle.add(animation);
-}
-
-void AnimationControllerPrivate::removeFromAnimationsWaitingForStyle(AnimationBase* animationToRemove)
-{
- m_animationsWaitingForStyle.remove(animationToRemove);
-}
-
-void AnimationControllerPrivate::styleAvailable()
-{
- // Go through list of waiters and send them on their way
- WaitingAnimationsSet::const_iterator it = m_animationsWaitingForStyle.begin();
- WaitingAnimationsSet::const_iterator end = m_animationsWaitingForStyle.end();
- for (; it != end; ++it)
- (*it)->styleAvailable();
-
- m_animationsWaitingForStyle.clear();
-}
-
-void AnimationControllerPrivate::addToAnimationsWaitingForStartTimeResponse(AnimationBase* animation, bool willGetResponse)
-{
- // If willGetResponse is true, it means this animation is actually waiting for a response
- // (which will come in as a call to notifyAnimationStarted()).
- // In that case we don't need to add it to this list. We just set a waitingForAResponse flag
- // which says we are waiting for the response. If willGetResponse is false, this animation
- // is not waiting for a response for itself, but rather for a notifyXXXStarted() call for
- // another animation to which it will sync.
- //
- // When endAnimationUpdate() is called we check to see if the waitingForAResponse flag is
- // true. If so, we just return and will do our work when the first notifyXXXStarted() call
- // comes in. If it is false, we will not be getting a notifyXXXStarted() call, so we will
- // do our work right away. In both cases we call the onAnimationStartResponse() method
- // on each animation. In the first case we send in the time we got from notifyXXXStarted().
- // In the second case, we just pass in the beginAnimationUpdateTime().
- //
- // This will synchronize all software and accelerated animations started in the same
- // updateStyleIfNeeded cycle.
- //
-
- if (willGetResponse)
- m_waitingForAsyncStartNotification = true;
-
- m_animationsWaitingForStartTimeResponse.add(animation);
-}
-
-void AnimationControllerPrivate::removeFromAnimationsWaitingForStartTimeResponse(AnimationBase* animationToRemove)
-{
- m_animationsWaitingForStartTimeResponse.remove(animationToRemove);
-
- if (m_animationsWaitingForStartTimeResponse.isEmpty())
- m_waitingForAsyncStartNotification = false;
-}
-
-void AnimationControllerPrivate::startTimeResponse(double time)
-{
- // Go through list of waiters and send them on their way
-
- WaitingAnimationsSet::const_iterator it = m_animationsWaitingForStartTimeResponse.begin();
- WaitingAnimationsSet::const_iterator end = m_animationsWaitingForStartTimeResponse.end();
- for (; it != end; ++it)
- (*it)->onAnimationStartResponse(time);
-
- m_animationsWaitingForStartTimeResponse.clear();
- m_waitingForAsyncStartNotification = false;
-}
-
-void AnimationControllerPrivate::animationWillBeRemoved(AnimationBase* animation)
-{
- removeFromAnimationsWaitingForStyle(animation);
- removeFromAnimationsWaitingForStartTimeResponse(animation);
-}
-
-AnimationController::AnimationController(Frame* frame)
- : m_data(adoptPtr(new AnimationControllerPrivate(frame)))
- , m_beginAnimationUpdateCount(0)
-{
-}
-
-AnimationController::~AnimationController()
-{
-}
-
-void AnimationController::cancelAnimations(RenderObject* renderer)
-{
- if (!m_data->hasAnimations())
- return;
-
- if (m_data->clear(renderer)) {
- if (Node* node = renderer->node())
- node->setNeedsStyleRecalc(LocalStyleChange, StyleChangeFromRenderer);
- }
-}
-
-PassRefPtr<RenderStyle> AnimationController::updateAnimations(RenderObject* renderer, RenderStyle* newStyle)
-{
- RenderStyle* oldStyle = renderer->style();
-
- if ((!oldStyle || (!oldStyle->animations() && !oldStyle->transitions())) && (!newStyle->animations() && !newStyle->transitions()))
- return newStyle;
-
- // Don't run transitions when printing.
- if (renderer->view()->document().printing())
- return newStyle;
-
- // Fetch our current set of implicit animations from a hashtable. We then compare them
- // against the animations in the style and make sure we're in sync. If destination values
- // have changed, we reset the animation. We then do a blend to get new values and we return
- // a new style.
-
- // We don't support anonymous pseudo elements like :first-line or :first-letter.
- ASSERT(renderer->node());
-
- RefPtr<CompositeAnimation> rendererAnimations = m_data->accessCompositeAnimation(renderer);
- RefPtr<RenderStyle> blendedStyle = rendererAnimations->animate(renderer, oldStyle, newStyle);
-
- if (renderer->parent() || newStyle->animations() || (oldStyle && oldStyle->animations())) {
- m_data->scheduleServiceForRenderer(renderer);
- }
-
- if (blendedStyle != newStyle) {
- // If the animations/transitions change opacity or transform, we need to update
- // the style to impose the stacking rules. Note that this is also
- // done in StyleResolver::adjustRenderStyle().
- if (blendedStyle->hasAutoZIndex() && (blendedStyle->opacity() < 1.0f || blendedStyle->hasTransform()))
- blendedStyle->setZIndex(0);
- }
- return blendedStyle.release();
-}
-
-PassRefPtr<RenderStyle> AnimationController::getAnimatedStyleForRenderer(RenderObject* renderer)
-{
- return m_data->getAnimatedStyleForRenderer(renderer);
-}
-
-void AnimationController::notifyAnimationStarted(RenderObject*, double startTime)
-{
- m_data->receivedStartTimeResponse(startTime);
-}
-
-void AnimationController::pauseAnimationsForTesting(double t)
-{
- m_data->pauseAnimationsForTesting(t);
-}
-
-unsigned AnimationController::numberOfActiveAnimations(Document* document) const
-{
- return m_data->numberOfActiveAnimations(document);
-}
-
-bool AnimationController::isRunningAnimationOnRenderer(RenderObject* renderer, CSSPropertyID property, bool isRunningNow) const
-{
- return m_data->isRunningAnimationOnRenderer(renderer, property, isRunningNow);
-}
-
-bool AnimationController::isRunningAcceleratableAnimationOnRenderer(RenderObject* renderer) const
-{
- return m_data->isRunningAcceleratableAnimationOnRenderer(renderer);
-}
-
-bool AnimationController::isRunningAcceleratedAnimationOnRenderer(RenderObject* renderer, CSSPropertyID property, bool isRunningNow) const
-{
- return m_data->isRunningAcceleratedAnimationOnRenderer(renderer, property, isRunningNow);
-}
-
-void AnimationController::suspendAnimations()
-{
- m_data->suspendAnimations();
-}
-
-void AnimationController::resumeAnimations()
-{
- m_data->resumeAnimations();
-}
-
-void AnimationController::serviceAnimations()
-{
- m_data->serviceAnimations();
-}
-
-void AnimationController::suspendAnimationsForDocument(Document* document)
-{
- m_data->suspendAnimationsForDocument(document);
-}
-
-void AnimationController::resumeAnimationsForDocument(Document* document)
-{
- m_data->resumeAnimationsForDocument(document);
-}
-
-void AnimationController::beginAnimationUpdate()
-{
- if (!m_beginAnimationUpdateCount)
- m_data->setBeginAnimationUpdateTime(cBeginAnimationUpdateTimeNotSet);
- ++m_beginAnimationUpdateCount;
-}
-
-void AnimationController::endAnimationUpdate()
-{
- ASSERT(m_beginAnimationUpdateCount > 0);
- --m_beginAnimationUpdateCount;
- if (!m_beginAnimationUpdateCount)
- m_data->endAnimationUpdate();
-}
-
-bool AnimationController::supportsAcceleratedAnimationOfProperty(CSSPropertyID property)
-{
- return CSSPropertyAnimation::animationOfPropertyIsAccelerated(property);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/page/animation/AnimationController.h b/chromium/third_party/WebKit/Source/core/page/animation/AnimationController.h
deleted file mode 100644
index fb9046f1a90..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/animation/AnimationController.h
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- * Copyright (C) 2007 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef AnimationController_h
-#define AnimationController_h
-
-#include "CSSPropertyNames.h"
-#include "wtf/Forward.h"
-#include "wtf/OwnPtr.h"
-
-namespace WebCore {
-
-class AnimationBase;
-class AnimationControllerPrivate;
-class Document;
-class Element;
-class Frame;
-class Node;
-class RenderObject;
-class RenderStyle;
-
-class AnimationController {
-public:
- AnimationController(Frame*);
- ~AnimationController();
-
- void cancelAnimations(RenderObject*);
- PassRefPtr<RenderStyle> updateAnimations(RenderObject*, RenderStyle* newStyle);
- PassRefPtr<RenderStyle> getAnimatedStyleForRenderer(RenderObject*);
-
- // This is called when an accelerated animation or transition has actually started to animate.
- void notifyAnimationStarted(RenderObject*, double startTime);
-
- void pauseAnimationsForTesting(double t);
- unsigned numberOfActiveAnimations(Document*) const; // To be used only for testing
-
- bool isRunningAnimationOnRenderer(RenderObject*, CSSPropertyID, bool isRunningNow = true) const;
- bool isRunningAcceleratableAnimationOnRenderer(RenderObject*) const;
- bool isRunningAcceleratedAnimationOnRenderer(RenderObject*, CSSPropertyID, bool isRunningNow = true) const;
-
- void suspendAnimations();
- void resumeAnimations();
- void serviceAnimations();
-
- void suspendAnimationsForDocument(Document*);
- void resumeAnimationsForDocument(Document*);
-
- void beginAnimationUpdate();
- void endAnimationUpdate();
-
- static bool supportsAcceleratedAnimationOfProperty(CSSPropertyID);
-
-private:
- OwnPtr<AnimationControllerPrivate> m_data;
- int m_beginAnimationUpdateCount;
-};
-
-class AnimationUpdateBlock {
-public:
- AnimationUpdateBlock(AnimationController* animationController)
- : m_animationController(animationController)
- {
- if (m_animationController)
- m_animationController->beginAnimationUpdate();
- }
-
- ~AnimationUpdateBlock()
- {
- if (m_animationController)
- m_animationController->endAnimationUpdate();
- }
-
- AnimationController* m_animationController;
-};
-
-} // namespace WebCore
-
-#endif // AnimationController_h
diff --git a/chromium/third_party/WebKit/Source/core/page/animation/AnimationControllerPrivate.h b/chromium/third_party/WebKit/Source/core/page/animation/AnimationControllerPrivate.h
deleted file mode 100644
index 5a603fc86c0..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/animation/AnimationControllerPrivate.h
+++ /dev/null
@@ -1,145 +0,0 @@
-/*
- * Copyright (C) 2009 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef AnimationControllerPrivate_h
-#define AnimationControllerPrivate_h
-
-#include "CSSPropertyNames.h"
-#include "core/platform/Timer.h"
-#include "wtf/HashMap.h"
-#include "wtf/HashSet.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefPtr.h"
-#include "wtf/Vector.h"
-#include "wtf/text/AtomicString.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class AnimationBase;
-class CompositeAnimation;
-class Document;
-class Element;
-class Frame;
-class Node;
-class RenderObject;
-class RenderStyle;
-
-enum SetNeedsStyleRecalc {
- DoNotCallSetNeedsStyleRecalc = 0,
- CallSetNeedsStyleRecalc = 1
-};
-
-class AnimationControllerPrivate {
- WTF_MAKE_NONCOPYABLE(AnimationControllerPrivate); WTF_MAKE_FAST_ALLOCATED;
-public:
- AnimationControllerPrivate(Frame*);
- ~AnimationControllerPrivate();
-
- void updateAnimations(double& timeToNextService, double& timeToNextEvent, SetNeedsStyleRecalc callSetNeedsStyleRecalc = DoNotCallSetNeedsStyleRecalc);
- void scheduleService();
-
- PassRefPtr<CompositeAnimation> accessCompositeAnimation(RenderObject*);
- bool clear(RenderObject*);
-
- void updateStyleIfNeededDispatcherFired(Timer<AnimationControllerPrivate>*);
- void startUpdateStyleIfNeededDispatcher();
- void addEventToDispatch(PassRefPtr<Element> element, const AtomicString& eventType, const String& name, double elapsedTime);
- void addNodeChangeToDispatch(PassRefPtr<Node>);
-
- bool hasAnimations() const { return !m_compositeAnimations.isEmpty(); }
-
- void suspendAnimations();
- void resumeAnimations();
- void serviceAnimations();
-
- void suspendAnimationsForDocument(Document*);
- void resumeAnimationsForDocument(Document*);
-
- bool isRunningAnimationOnRenderer(RenderObject*, CSSPropertyID, bool isRunningNow) const;
- bool isRunningAcceleratableAnimationOnRenderer(RenderObject*) const;
- bool isRunningAcceleratedAnimationOnRenderer(RenderObject*, CSSPropertyID, bool isRunningNow) const;
-
- void pauseAnimationsForTesting(double t);
- unsigned numberOfActiveAnimations(Document*) const;
-
- PassRefPtr<RenderStyle> getAnimatedStyleForRenderer(RenderObject* renderer);
-
- double beginAnimationUpdateTime();
- void setBeginAnimationUpdateTime(double t) { m_beginAnimationUpdateTime = t; }
- void endAnimationUpdate();
- void receivedStartTimeResponse(double);
-
- void addToAnimationsWaitingForStyle(AnimationBase*);
- void removeFromAnimationsWaitingForStyle(AnimationBase*);
-
- void addToAnimationsWaitingForStartTimeResponse(AnimationBase*, bool willGetResponse);
- void removeFromAnimationsWaitingForStartTimeResponse(AnimationBase*);
-
- void animationWillBeRemoved(AnimationBase*);
-
- void scheduleServiceForRenderer(RenderObject*);
-
-private:
- void animationTimerFired(Timer<AnimationControllerPrivate>*);
-
- void scheduleService(double timeToNextService, double timeToNextEvent);
-
- void styleAvailable();
- void fireEventsAndUpdateStyle();
- void startTimeResponse(double t);
-
- typedef HashMap<RenderObject*, RefPtr<CompositeAnimation> > RenderObjectAnimationMap;
-
- RenderObjectAnimationMap m_compositeAnimations;
- Timer<AnimationControllerPrivate> m_animationTimer;
- Timer<AnimationControllerPrivate> m_updateStyleIfNeededDispatcher;
- Frame* m_frame;
-
- class EventToDispatch {
- public:
- RefPtr<Element> element;
- AtomicString eventType;
- String name;
- double elapsedTime;
- };
-
- Vector<EventToDispatch> m_eventsToDispatch;
- Vector<RefPtr<Node> > m_nodeChangesToDispatch;
-
- double m_beginAnimationUpdateTime;
-
- typedef HashSet<RefPtr<AnimationBase> > WaitingAnimationsSet;
- WaitingAnimationsSet m_animationsWaitingForStyle;
- WaitingAnimationsSet m_animationsWaitingForStartTimeResponse;
- bool m_waitingForAsyncStartNotification;
-};
-
-} // namespace WebCore
-
-#endif // AnimationControllerPrivate_h
diff --git a/chromium/third_party/WebKit/Source/core/page/animation/CSSPropertyAnimation.cpp b/chromium/third_party/WebKit/Source/core/page/animation/CSSPropertyAnimation.cpp
deleted file mode 100644
index 4f5ab988a32..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/animation/CSSPropertyAnimation.cpp
+++ /dev/null
@@ -1,1279 +0,0 @@
-/*
- * Copyright (C) 2007, 2008, 2009 Apple Inc. All rights reserved.
- * Copyright (C) 2012 Adobe Systems Incorporated. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/page/animation/CSSPropertyAnimation.h"
-
-#include <algorithm>
-#include "CSSPropertyNames.h"
-#include "StylePropertyShorthand.h"
-#include "core/animation/css/CSSAnimations.h"
-#include "core/css/CSSCrossfadeValue.h"
-#include "core/css/CSSImageValue.h"
-#include "core/css/CSSPrimitiveValue.h"
-#include "core/fetch/ImageResource.h"
-#include "core/page/animation/AnimationBase.h"
-#include "core/platform/FloatConversion.h"
-#include "core/rendering/ClipPathOperation.h"
-#include "core/rendering/RenderBox.h"
-#include "core/rendering/style/RenderStyle.h"
-#include "core/rendering/style/StyleFetchedImage.h"
-#include "core/rendering/style/StyleGeneratedImage.h"
-#include "wtf/Noncopyable.h"
-
-namespace WebCore {
-
-static inline int blendFunc(const AnimationBase*, int from, int to, double progress)
-{
- return blend(from, to, progress);
-}
-
-static inline unsigned blendFunc(const AnimationBase*, unsigned from, unsigned to, double progress)
-{
- return blend(from, to, progress);
-}
-
-static inline double blendFunc(const AnimationBase*, double from, double to, double progress)
-{
- return blend(from, to, progress);
-}
-
-static inline float blendFunc(const AnimationBase*, float from, float to, double progress)
-{
- return narrowPrecisionToFloat(from + (to - from) * progress);
-}
-
-static inline Color blendFunc(const AnimationBase*, const Color& from, const Color& to, double progress)
-{
- return blend(from, to, progress);
-}
-
-static inline Length blendFunc(const AnimationBase*, const Length& from, const Length& to, double progress)
-{
- return to.blend(from, narrowPrecisionToFloat(progress));
-}
-
-static inline LengthSize blendFunc(const AnimationBase* anim, const LengthSize& from, const LengthSize& to, double progress)
-{
- return LengthSize(blendFunc(anim, from.width(), to.width(), progress),
- blendFunc(anim, from.height(), to.height(), progress));
-}
-
-static inline LengthPoint blendFunc(const AnimationBase* anim, const LengthPoint& from, const LengthPoint& to, double progress)
-{
- return LengthPoint(blendFunc(anim, from.x(), to.x(), progress), blendFunc(anim, from.y(), to.y(), progress));
-}
-
-static inline IntSize blendFunc(const AnimationBase* anim, const IntSize& from, const IntSize& to, double progress)
-{
- return IntSize(blendFunc(anim, from.width(), to.width(), progress),
- blendFunc(anim, from.height(), to.height(), progress));
-}
-
-static inline ShadowStyle blendFunc(const AnimationBase* anim, ShadowStyle from, ShadowStyle to, double progress)
-{
- if (from == to)
- return to;
-
- double fromVal = from == Normal ? 1 : 0;
- double toVal = to == Normal ? 1 : 0;
- double result = blendFunc(anim, fromVal, toVal, progress);
- return result > 0 ? Normal : Inset;
-}
-
-static inline PassOwnPtr<ShadowData> blendFunc(const AnimationBase* anim, const ShadowData* from, const ShadowData* to, double progress)
-{
- ASSERT(from && to);
- if (from->style() != to->style())
- return to->clone();
-
- return ShadowData::create(blend(from->location(), to->location(), progress),
- blend(from->blur(), to->blur(), progress),
- blend(from->spread(), to->spread(), progress),
- blendFunc(anim, from->style(), to->style(), progress),
- blend(from->color(), to->color(), progress));
-}
-
-static inline TransformOperations blendFunc(const AnimationBase* anim, const TransformOperations& from, const TransformOperations& to, double progress)
-{
- if (anim->isTransformFunctionListValid())
- return to.blendByMatchingOperations(from, progress);
- return to.blendByUsingMatrixInterpolation(from, progress);
-}
-
-static inline PassRefPtr<ClipPathOperation> blendFunc(const AnimationBase*, ClipPathOperation* from, ClipPathOperation* to, double progress)
-{
- // Other clip-path operations than BasicShapes can not be animated.
- if (from->getOperationType() != ClipPathOperation::SHAPE || to->getOperationType() != ClipPathOperation::SHAPE)
- return to;
-
- const BasicShape* fromShape = static_cast<ShapeClipPathOperation*>(from)->basicShape();
- const BasicShape* toShape = static_cast<ShapeClipPathOperation*>(to)->basicShape();
-
- if (!fromShape->canBlend(toShape))
- return to;
-
- return ShapeClipPathOperation::create(toShape->blend(fromShape, progress));
-}
-
-static inline PassRefPtr<ShapeValue> blendFunc(const AnimationBase*, ShapeValue* from, ShapeValue* to, double progress)
-{
- // FIXME Bug 102723: Shape-inside should be able to animate a value of 'outside-shape' when shape-outside is set to a BasicShape
- if (from->type() != ShapeValue::Shape || to->type() != ShapeValue::Shape)
- return to;
-
- const BasicShape* fromShape = from->shape();
- const BasicShape* toShape = to->shape();
-
- if (!fromShape->canBlend(toShape))
- return to;
-
- return ShapeValue::createShapeValue(toShape->blend(fromShape, progress));
-}
-
-static inline PassRefPtr<FilterOperation> blendFunc(const AnimationBase* anim, FilterOperation* fromOp, FilterOperation* toOp, double progress, bool blendToPassthrough = false)
-{
- ASSERT(toOp);
- return toOp->blend(fromOp, progress, blendToPassthrough);
-}
-
-static inline FilterOperations blendFunc(const AnimationBase* anim, const FilterOperations& from, const FilterOperations& to, double progress)
-{
- FilterOperations result;
-
- // If we have a filter function list, use that to do a per-function animation.
- if (anim->filterFunctionListsMatch()) {
- size_t fromSize = from.operations().size();
- size_t toSize = to.operations().size();
- size_t size = max(fromSize, toSize);
- for (size_t i = 0; i < size; i++) {
- RefPtr<FilterOperation> fromOp = (i < fromSize) ? from.operations()[i].get() : 0;
- RefPtr<FilterOperation> toOp = (i < toSize) ? to.operations()[i].get() : 0;
- RefPtr<FilterOperation> blendedOp = toOp ? blendFunc(anim, fromOp.get(), toOp.get(), progress) : (fromOp ? blendFunc(anim, 0, fromOp.get(), progress, true) : 0);
- if (blendedOp)
- result.operations().append(blendedOp);
- else {
- RefPtr<FilterOperation> identityOp = PassthroughFilterOperation::create();
- if (progress > 0.5)
- result.operations().append(toOp ? toOp : identityOp);
- else
- result.operations().append(fromOp ? fromOp : identityOp);
- }
- }
- } else {
- // If the filter function lists don't match, we could try to cross-fade, but don't yet have a way to represent that in CSS.
- // For now we'll just fail to animate.
- result = to;
- }
-
- return result;
-}
-
-static inline EVisibility blendFunc(const AnimationBase* anim, EVisibility from, EVisibility to, double progress)
-{
- // Any non-zero result means we consider the object to be visible. Only at 0 do we consider the object to be
- // invisible. The invisible value we use (HIDDEN vs. COLLAPSE) depends on the specified from/to values.
- double fromVal = from == VISIBLE ? 1. : 0.;
- double toVal = to == VISIBLE ? 1. : 0.;
- if (fromVal == toVal)
- return to;
- double result = blendFunc(anim, fromVal, toVal, progress);
- return result > 0. ? VISIBLE : (to != VISIBLE ? to : from);
-}
-
-static inline LengthBox blendFunc(const AnimationBase* anim, const LengthBox& from, const LengthBox& to, double progress)
-{
- // Length types have to match to animate
- if (from.top().type() != to.top().type()
- || from.right().type() != to.right().type()
- || from.bottom().type() != to.bottom().type()
- || from.left().type() != to.left().type())
- return to;
-
- LengthBox result(blendFunc(anim, from.top(), to.top(), progress),
- blendFunc(anim, from.right(), to.right(), progress),
- blendFunc(anim, from.bottom(), to.bottom(), progress),
- blendFunc(anim, from.left(), to.left(), progress));
- return result;
-}
-
-static inline SVGLength blendFunc(const AnimationBase*, const SVGLength& from, const SVGLength& to, double progress)
-{
- return to.blend(from, narrowPrecisionToFloat(progress));
-}
-
-static inline Vector<SVGLength> blendFunc(const AnimationBase*, const Vector<SVGLength>& from, const Vector<SVGLength>& to, double progress)
-{
- size_t fromLength = from.size();
- size_t toLength = to.size();
- if (!fromLength)
- return !progress ? from : to;
- if (!toLength)
- return progress == 1 ? from : to;
-
- size_t resultLength = fromLength;
- if (fromLength != toLength) {
- if (!(fromLength % toLength))
- resultLength = fromLength;
- else if (!(toLength % fromLength))
- resultLength = toLength;
- else
- resultLength = fromLength * toLength;
- }
- Vector<SVGLength> result(resultLength);
- for (size_t i = 0; i < resultLength; ++i)
- result[i] = to[i % toLength].blend(from[i % fromLength], narrowPrecisionToFloat(progress));
- return result;
-}
-
-static inline PassRefPtr<StyleImage> crossfadeBlend(const AnimationBase*, StyleFetchedImage* fromStyleImage, StyleFetchedImage* toStyleImage, double progress)
-{
- // If progress is at one of the extremes, we want getComputedStyle to show the image,
- // not a completed cross-fade, so we hand back one of the existing images.
- if (!progress)
- return fromStyleImage;
- if (progress == 1)
- return toStyleImage;
-
- ImageResource* fromImageResource = static_cast<ImageResource*>(fromStyleImage->data());
- ImageResource* toImageResource = static_cast<ImageResource*>(toStyleImage->data());
-
- RefPtr<CSSImageValue> fromImageValue = CSSImageValue::create(fromImageResource->url(), fromStyleImage);
- RefPtr<CSSImageValue> toImageValue = CSSImageValue::create(toImageResource->url(), toStyleImage);
- RefPtr<CSSCrossfadeValue> crossfadeValue = CSSCrossfadeValue::create(fromImageValue, toImageValue);
-
- crossfadeValue->setPercentage(CSSPrimitiveValue::create(progress, CSSPrimitiveValue::CSS_NUMBER));
-
- return StyleGeneratedImage::create(crossfadeValue.get());
-}
-
-static inline PassRefPtr<StyleImage> blendFunc(const AnimationBase* anim, StyleImage* from, StyleImage* to, double progress)
-{
- if (!from || !to)
- return to;
-
- if (from->isImageResource() && to->isImageResource())
- return crossfadeBlend(anim, static_cast<StyleFetchedImage*>(from), static_cast<StyleFetchedImage*>(to), progress);
-
- // FIXME: Support transitioning generated images as well. (gradients, etc.)
-
- return to;
-}
-
-static inline NinePieceImage blendFunc(const AnimationBase* anim, const NinePieceImage& from, const NinePieceImage& to, double progress)
-{
- if (!from.hasImage() || !to.hasImage())
- return to;
-
- // FIXME (74112): Support transitioning between NinePieceImages that differ by more than image content.
-
- if (from.imageSlices() != to.imageSlices() || from.borderSlices() != to.borderSlices() || from.outset() != to.outset() || from.fill() != to.fill() || from.horizontalRule() != to.horizontalRule() || from.verticalRule() != to.verticalRule())
- return to;
-
- if (from.image()->imageSize(anim->renderer(), 1.0) != to.image()->imageSize(anim->renderer(), 1.0))
- return to;
-
- RefPtr<StyleImage> newContentImage = blendFunc(anim, from.image(), to.image(), progress);
-
- return NinePieceImage(newContentImage, from.imageSlices(), from.fill(), from.borderSlices(), from.outset(), from.horizontalRule(), from.verticalRule());
-}
-
-class AnimationPropertyWrapperBase {
- WTF_MAKE_NONCOPYABLE(AnimationPropertyWrapperBase);
- WTF_MAKE_FAST_ALLOCATED;
-public:
- AnimationPropertyWrapperBase(CSSPropertyID prop)
- : m_prop(prop)
- {
- }
-
- virtual ~AnimationPropertyWrapperBase() { }
-
- virtual bool isShorthandWrapper() const { return false; }
- virtual bool equals(const RenderStyle* a, const RenderStyle* b) const = 0;
- virtual void blend(const AnimationBase*, RenderStyle*, const RenderStyle*, const RenderStyle*, double) const = 0;
-
- CSSPropertyID property() const { return m_prop; }
-
- virtual bool animationIsAccelerated() const { return false; }
-
-private:
- CSSPropertyID m_prop;
-};
-
-static int gPropertyWrapperMap[numCSSProperties];
-static const int cInvalidPropertyWrapperIndex = -1;
-static Vector<AnimationPropertyWrapperBase*>* gPropertyWrappers = 0;
-
-static void addPropertyWrapper(CSSPropertyID propertyID, AnimationPropertyWrapperBase* wrapper)
-{
- int propIndex = propertyID - firstCSSProperty;
-
- ASSERT(gPropertyWrapperMap[propIndex] == cInvalidPropertyWrapperIndex);
-
- unsigned wrapperIndex = gPropertyWrappers->size();
- gPropertyWrappers->append(wrapper);
- gPropertyWrapperMap[propIndex] = wrapperIndex;
-}
-
-static AnimationPropertyWrapperBase* wrapperForProperty(CSSPropertyID propertyID)
-{
- int propIndex = propertyID - firstCSSProperty;
- if (propIndex >= 0 && propIndex < numCSSProperties) {
- int wrapperIndex = gPropertyWrapperMap[propIndex];
- if (wrapperIndex >= 0)
- return (*gPropertyWrappers)[wrapperIndex];
- }
- return 0;
-}
-
-template <typename T>
-class PropertyWrapperGetter : public AnimationPropertyWrapperBase {
-public:
- PropertyWrapperGetter(CSSPropertyID prop, T (RenderStyle::*getter)() const)
- : AnimationPropertyWrapperBase(prop)
- , m_getter(getter)
- {
- }
-
- virtual bool equals(const RenderStyle* a, const RenderStyle* b) const
- {
- // If the style pointers are the same, don't bother doing the test.
- // If either is null, return false. If both are null, return true.
- if ((!a && !b) || a == b)
- return true;
- if (!a || !b)
- return false;
- return (a->*m_getter)() == (b->*m_getter)();
- }
-
-protected:
- T (RenderStyle::*m_getter)() const;
-};
-
-template <typename T>
-class PropertyWrapper : public PropertyWrapperGetter<T> {
-public:
- PropertyWrapper(CSSPropertyID prop, T (RenderStyle::*getter)() const, void (RenderStyle::*setter)(T))
- : PropertyWrapperGetter<T>(prop, getter)
- , m_setter(setter)
- {
- }
-
- virtual void blend(const AnimationBase* anim, RenderStyle* dst, const RenderStyle* a, const RenderStyle* b, double progress) const
- {
- (dst->*m_setter)(blendFunc(anim, (a->*PropertyWrapperGetter<T>::m_getter)(), (b->*PropertyWrapperGetter<T>::m_getter)(), progress));
- }
-
-protected:
- void (RenderStyle::*m_setter)(T);
-};
-
-template <typename T>
-class RefCountedPropertyWrapper : public PropertyWrapperGetter<T*> {
-public:
- RefCountedPropertyWrapper(CSSPropertyID prop, T* (RenderStyle::*getter)() const, void (RenderStyle::*setter)(PassRefPtr<T>))
- : PropertyWrapperGetter<T*>(prop, getter)
- , m_setter(setter)
- {
- }
-
- virtual void blend(const AnimationBase* anim, RenderStyle* dst, const RenderStyle* a, const RenderStyle* b, double progress) const
- {
- (dst->*m_setter)(blendFunc(anim, (a->*PropertyWrapperGetter<T*>::m_getter)(), (b->*PropertyWrapperGetter<T*>::m_getter)(), progress));
- }
-
-protected:
- void (RenderStyle::*m_setter)(PassRefPtr<T>);
-};
-
-
-class PropertyWrapperClipPath : public RefCountedPropertyWrapper<ClipPathOperation> {
-public:
- PropertyWrapperClipPath(CSSPropertyID prop, ClipPathOperation* (RenderStyle::*getter)() const, void (RenderStyle::*setter)(PassRefPtr<ClipPathOperation>))
- : RefCountedPropertyWrapper<ClipPathOperation>(prop, getter, setter)
- {
- }
-};
-
-class PropertyWrapperShape : public RefCountedPropertyWrapper<ShapeValue> {
-public:
- PropertyWrapperShape(CSSPropertyID prop, ShapeValue* (RenderStyle::*getter)() const, void (RenderStyle::*setter)(PassRefPtr<ShapeValue>))
- : RefCountedPropertyWrapper<ShapeValue>(prop, getter, setter)
- {
- }
-};
-
-class StyleImagePropertyWrapper : public RefCountedPropertyWrapper<StyleImage> {
-public:
- StyleImagePropertyWrapper(CSSPropertyID prop, StyleImage* (RenderStyle::*getter)() const, void (RenderStyle::*setter)(PassRefPtr<StyleImage>))
- : RefCountedPropertyWrapper<StyleImage>(prop, getter, setter)
- {
- }
-
- virtual bool equals(const RenderStyle* a, const RenderStyle* b) const
- {
- // If the style pointers are the same, don't bother doing the test.
- // If either is null, return false. If both are null, return true.
- if (a == b)
- return true;
- if (!a || !b)
- return false;
-
- StyleImage* imageA = (a->*m_getter)();
- StyleImage* imageB = (b->*m_getter)();
- return StyleImage::imagesEquivalent(imageA, imageB);
- }
-};
-
-class PropertyWrapperColor : public PropertyWrapperGetter<Color> {
-public:
- PropertyWrapperColor(CSSPropertyID prop, Color (RenderStyle::*getter)() const, void (RenderStyle::*setter)(const Color&))
- : PropertyWrapperGetter<Color>(prop, getter)
- , m_setter(setter)
- {
- }
-
- virtual void blend(const AnimationBase* anim, RenderStyle* dst, const RenderStyle* a, const RenderStyle* b, double progress) const
- {
- (dst->*m_setter)(blendFunc(anim, (a->*PropertyWrapperGetter<Color>::m_getter)(), (b->*PropertyWrapperGetter<Color>::m_getter)(), progress));
- }
-
-protected:
- void (RenderStyle::*m_setter)(const Color&);
-};
-
-class PropertyWrapperAcceleratedOpacity : public PropertyWrapper<float> {
-public:
- PropertyWrapperAcceleratedOpacity()
- : PropertyWrapper<float>(CSSPropertyOpacity, &RenderStyle::opacity, &RenderStyle::setOpacity)
- {
- }
-
- virtual bool animationIsAccelerated() const { return true; }
-
- virtual void blend(const AnimationBase* anim, RenderStyle* dst, const RenderStyle* a, const RenderStyle* b, double progress) const
- {
- float fromOpacity = a->opacity();
-
- // This makes sure we put the object being animated into a RenderLayer during the animation
- dst->setOpacity(blendFunc(anim, (fromOpacity == 1) ? 0.999999f : fromOpacity, b->opacity(), progress));
- }
-};
-
-class PropertyWrapperAcceleratedTransform : public PropertyWrapper<const TransformOperations&> {
-public:
- PropertyWrapperAcceleratedTransform()
- : PropertyWrapper<const TransformOperations&>(CSSPropertyWebkitTransform, &RenderStyle::transform, &RenderStyle::setTransform)
- {
- }
-
- virtual bool animationIsAccelerated() const { return true; }
-
- virtual void blend(const AnimationBase* anim, RenderStyle* dst, const RenderStyle* a, const RenderStyle* b, double progress) const
- {
- dst->setTransform(blendFunc(anim, a->transform(), b->transform(), progress));
- }
-};
-
-class PropertyWrapperAcceleratedFilter : public PropertyWrapper<const FilterOperations&> {
-public:
- PropertyWrapperAcceleratedFilter()
- : PropertyWrapper<const FilterOperations&>(CSSPropertyWebkitFilter, &RenderStyle::filter, &RenderStyle::setFilter)
- {
- }
-
- virtual bool animationIsAccelerated() const { return true; }
-
- virtual void blend(const AnimationBase* anim, RenderStyle* dst, const RenderStyle* a, const RenderStyle* b, double progress) const
- {
- dst->setFilter(blendFunc(anim, a->filter(), b->filter(), progress));
- }
-};
-
-static inline size_t shadowListLength(const ShadowData* shadow)
-{
- size_t count;
- for (count = 0; shadow; shadow = shadow->next())
- ++count;
- return count;
-}
-
-static inline const ShadowData* shadowForBlending(const ShadowData* srcShadow, const ShadowData* otherShadow)
-{
- DEFINE_STATIC_LOCAL(OwnPtr<ShadowData>, defaultShadowData, (ShadowData::create(IntPoint(), 0, 0, Normal, Color::transparent)));
- DEFINE_STATIC_LOCAL(OwnPtr<ShadowData>, defaultInsetShadowData, (ShadowData::create(IntPoint(), 0, 0, Inset, Color::transparent)));
-
- if (srcShadow)
- return srcShadow;
-
- if (otherShadow->style() == Inset)
- return defaultInsetShadowData.get();
-
- return defaultShadowData.get();
-}
-
-class PropertyWrapperShadow : public AnimationPropertyWrapperBase {
-public:
- PropertyWrapperShadow(CSSPropertyID prop, const ShadowData* (RenderStyle::*getter)() const, void (RenderStyle::*setter)(PassOwnPtr<ShadowData>, bool))
- : AnimationPropertyWrapperBase(prop)
- , m_getter(getter)
- , m_setter(setter)
- {
- }
-
- virtual bool equals(const RenderStyle* a, const RenderStyle* b) const
- {
- const ShadowData* shadowA = (a->*m_getter)();
- const ShadowData* shadowB = (b->*m_getter)();
-
- while (true) {
- // end of both lists
- if (!shadowA && !shadowB)
- return true;
-
- // end of just one of the lists
- if (!shadowA || !shadowB)
- return false;
-
- if (*shadowA != *shadowB)
- return false;
-
- shadowA = shadowA->next();
- shadowB = shadowB->next();
- }
-
- return true;
- }
-
- virtual void blend(const AnimationBase* anim, RenderStyle* dst, const RenderStyle* a, const RenderStyle* b, double progress) const
- {
- const ShadowData* shadowA = (a->*m_getter)();
- const ShadowData* shadowB = (b->*m_getter)();
-
- int fromLength = shadowListLength(shadowA);
- int toLength = shadowListLength(shadowB);
-
- if (fromLength == toLength || (fromLength <= 1 && toLength <= 1)) {
- (dst->*m_setter)(blendSimpleOrMatchedShadowLists(anim, progress, shadowA, shadowB), false);
- return;
- }
-
- (dst->*m_setter)(blendMismatchedShadowLists(anim, progress, shadowA, shadowB, fromLength, toLength), false);
- }
-
-private:
- PassOwnPtr<ShadowData> blendSimpleOrMatchedShadowLists(const AnimationBase* anim, double progress, const ShadowData* shadowA, const ShadowData* shadowB) const
- {
- OwnPtr<ShadowData> newShadowData;
- ShadowData* lastShadow = 0;
-
- while (shadowA || shadowB) {
- const ShadowData* srcShadow = shadowForBlending(shadowA, shadowB);
- const ShadowData* dstShadow = shadowForBlending(shadowB, shadowA);
-
- OwnPtr<ShadowData> blendedShadow = blendFunc(anim, srcShadow, dstShadow, progress);
- ShadowData* blendedShadowPtr = blendedShadow.get();
-
- if (!lastShadow)
- newShadowData = blendedShadow.release();
- else
- lastShadow->setNext(blendedShadow.release());
-
- lastShadow = blendedShadowPtr;
-
- shadowA = shadowA ? shadowA->next() : 0;
- shadowB = shadowB ? shadowB->next() : 0;
- }
-
- return newShadowData.release();
- }
-
- PassOwnPtr<ShadowData> blendMismatchedShadowLists(const AnimationBase* anim, double progress, const ShadowData* shadowA, const ShadowData* shadowB, int fromLength, int toLength) const
- {
- // The shadows in ShadowData are stored in reverse order, so when animating mismatched lists,
- // reverse them and match from the end.
- Vector<const ShadowData*, 4> fromShadows(fromLength);
- for (int i = fromLength - 1; i >= 0; --i) {
- fromShadows[i] = shadowA;
- shadowA = shadowA->next();
- }
-
- Vector<const ShadowData*, 4> toShadows(toLength);
- for (int i = toLength - 1; i >= 0; --i) {
- toShadows[i] = shadowB;
- shadowB = shadowB->next();
- }
-
- OwnPtr<ShadowData> newShadowData;
-
- int maxLength = max(fromLength, toLength);
- for (int i = 0; i < maxLength; ++i) {
- const ShadowData* fromShadow = i < fromLength ? fromShadows[i] : 0;
- const ShadowData* toShadow = i < toLength ? toShadows[i] : 0;
-
- const ShadowData* srcShadow = shadowForBlending(fromShadow, toShadow);
- const ShadowData* dstShadow = shadowForBlending(toShadow, fromShadow);
-
- OwnPtr<ShadowData> blendedShadow = blendFunc(anim, srcShadow, dstShadow, progress);
- // Insert at the start of the list to preserve the order.
- blendedShadow->setNext(newShadowData.release());
- newShadowData = blendedShadow.release();
- }
-
- return newShadowData.release();
- }
-
- const ShadowData* (RenderStyle::*m_getter)() const;
- void (RenderStyle::*m_setter)(PassOwnPtr<ShadowData>, bool);
-};
-
-class PropertyWrapperMaybeInvalidColor : public AnimationPropertyWrapperBase {
-public:
- PropertyWrapperMaybeInvalidColor(CSSPropertyID prop, Color (RenderStyle::*getter)() const, void (RenderStyle::*setter)(const Color&))
- : AnimationPropertyWrapperBase(prop)
- , m_getter(getter)
- , m_setter(setter)
- {
- }
-
- virtual bool equals(const RenderStyle* a, const RenderStyle* b) const
- {
- Color fromColor = (a->*m_getter)();
- Color toColor = (b->*m_getter)();
-
- if (!fromColor.isValid() && !toColor.isValid())
- return true;
-
- if (!fromColor.isValid())
- fromColor = a->color();
- if (!toColor.isValid())
- toColor = b->color();
-
- return fromColor == toColor;
- }
-
- virtual void blend(const AnimationBase* anim, RenderStyle* dst, const RenderStyle* a, const RenderStyle* b, double progress) const
- {
- Color fromColor = (a->*m_getter)();
- Color toColor = (b->*m_getter)();
-
- if (!fromColor.isValid() && !toColor.isValid())
- return;
-
- if (!fromColor.isValid())
- fromColor = a->color();
- if (!toColor.isValid())
- toColor = b->color();
- (dst->*m_setter)(blendFunc(anim, fromColor, toColor, progress));
- }
-
-private:
- Color (RenderStyle::*m_getter)() const;
- void (RenderStyle::*m_setter)(const Color&);
-};
-
-
-enum MaybeInvalidColorTag { MaybeInvalidColor };
-class PropertyWrapperVisitedAffectedColor : public AnimationPropertyWrapperBase {
-public:
- PropertyWrapperVisitedAffectedColor(CSSPropertyID prop, Color (RenderStyle::*getter)() const, void (RenderStyle::*setter)(const Color&),
- Color (RenderStyle::*visitedGetter)() const, void (RenderStyle::*visitedSetter)(const Color&))
- : AnimationPropertyWrapperBase(prop)
- , m_wrapper(adoptPtr(new PropertyWrapperColor(prop, getter, setter)))
- , m_visitedWrapper(adoptPtr(new PropertyWrapperColor(prop, visitedGetter, visitedSetter)))
- {
- }
- PropertyWrapperVisitedAffectedColor(CSSPropertyID prop, MaybeInvalidColorTag, Color (RenderStyle::*getter)() const, void (RenderStyle::*setter)(const Color&),
- Color (RenderStyle::*visitedGetter)() const, void (RenderStyle::*visitedSetter)(const Color&))
- : AnimationPropertyWrapperBase(prop)
- , m_wrapper(adoptPtr(new PropertyWrapperMaybeInvalidColor(prop, getter, setter)))
- , m_visitedWrapper(adoptPtr(new PropertyWrapperMaybeInvalidColor(prop, visitedGetter, visitedSetter)))
- {
- }
- virtual bool equals(const RenderStyle* a, const RenderStyle* b) const
- {
- return m_wrapper->equals(a, b) && m_visitedWrapper->equals(a, b);
- }
- virtual void blend(const AnimationBase* anim, RenderStyle* dst, const RenderStyle* a, const RenderStyle* b, double progress) const
- {
- m_wrapper->blend(anim, dst, a, b, progress);
- m_visitedWrapper->blend(anim, dst, a, b, progress);
- }
-
-private:
- OwnPtr<AnimationPropertyWrapperBase> m_wrapper;
- OwnPtr<AnimationPropertyWrapperBase> m_visitedWrapper;
-};
-
-// Wrapper base class for an animatable property in a FillLayer
-class FillLayerAnimationPropertyWrapperBase {
-public:
- FillLayerAnimationPropertyWrapperBase()
- {
- }
-
- virtual ~FillLayerAnimationPropertyWrapperBase() { }
-
- virtual bool equals(const FillLayer*, const FillLayer*) const = 0;
- virtual void blend(const AnimationBase*, FillLayer*, const FillLayer*, const FillLayer*, double) const = 0;
-};
-
-template <typename T>
-class FillLayerPropertyWrapperGetter : public FillLayerAnimationPropertyWrapperBase {
- WTF_MAKE_NONCOPYABLE(FillLayerPropertyWrapperGetter);
-public:
- FillLayerPropertyWrapperGetter(T (FillLayer::*getter)() const)
- : m_getter(getter)
- {
- }
-
- virtual bool equals(const FillLayer* a, const FillLayer* b) const
- {
- // If the style pointers are the same, don't bother doing the test.
- // If either is null, return false. If both are null, return true.
- if ((!a && !b) || a == b)
- return true;
- if (!a || !b)
- return false;
- return (a->*m_getter)() == (b->*m_getter)();
- }
-
-protected:
- T (FillLayer::*m_getter)() const;
-};
-
-template <typename T>
-class FillLayerPropertyWrapper : public FillLayerPropertyWrapperGetter<T> {
-public:
- FillLayerPropertyWrapper(T (FillLayer::*getter)() const, void (FillLayer::*setter)(T))
- : FillLayerPropertyWrapperGetter<T>(getter)
- , m_setter(setter)
- {
- }
-
- virtual void blend(const AnimationBase* anim, FillLayer* dst, const FillLayer* a, const FillLayer* b, double progress) const
- {
- (dst->*m_setter)(blendFunc(anim, (a->*FillLayerPropertyWrapperGetter<T>::m_getter)(), (b->*FillLayerPropertyWrapperGetter<T>::m_getter)(), progress));
- }
-
-protected:
- void (FillLayer::*m_setter)(T);
-};
-
-template <typename T>
-class FillLayerRefCountedPropertyWrapper : public FillLayerPropertyWrapperGetter<T*> {
-public:
- FillLayerRefCountedPropertyWrapper(T* (FillLayer::*getter)() const, void (FillLayer::*setter)(PassRefPtr<T>))
- : FillLayerPropertyWrapperGetter<T*>(getter)
- , m_setter(setter)
- {
- }
-
- virtual void blend(const AnimationBase* anim, FillLayer* dst, const FillLayer* a, const FillLayer* b, double progress) const
- {
- (dst->*m_setter)(blendFunc(anim, (a->*FillLayerPropertyWrapperGetter<T*>::m_getter)(), (b->*FillLayerPropertyWrapperGetter<T*>::m_getter)(), progress));
- }
-
-protected:
- void (FillLayer::*m_setter)(PassRefPtr<T>);
-};
-
-class FillLayerStyleImagePropertyWrapper : public FillLayerRefCountedPropertyWrapper<StyleImage> {
-public:
- FillLayerStyleImagePropertyWrapper(StyleImage* (FillLayer::*getter)() const, void (FillLayer::*setter)(PassRefPtr<StyleImage>))
- : FillLayerRefCountedPropertyWrapper<StyleImage>(getter, setter)
- {
- }
-
- virtual bool equals(const FillLayer* a, const FillLayer* b) const
- {
- // If the style pointers are the same, don't bother doing the test.
- // If either is null, return false. If both are null, return true.
- if (a == b)
- return true;
- if (!a || !b)
- return false;
-
- StyleImage* imageA = (a->*m_getter)();
- StyleImage* imageB = (b->*m_getter)();
- return StyleImage::imagesEquivalent(imageA, imageB);
- }
-};
-
-
-class FillLayersPropertyWrapper : public AnimationPropertyWrapperBase {
-public:
- typedef const FillLayer* (RenderStyle::*LayersGetter)() const;
- typedef FillLayer* (RenderStyle::*LayersAccessor)();
-
- FillLayersPropertyWrapper(CSSPropertyID prop, LayersGetter getter, LayersAccessor accessor)
- : AnimationPropertyWrapperBase(prop)
- , m_layersGetter(getter)
- , m_layersAccessor(accessor)
- {
- switch (prop) {
- case CSSPropertyBackgroundPositionX:
- case CSSPropertyWebkitMaskPositionX:
- m_fillLayerPropertyWrapper = new FillLayerPropertyWrapper<Length>(&FillLayer::xPosition, &FillLayer::setXPosition);
- break;
- case CSSPropertyBackgroundPositionY:
- case CSSPropertyWebkitMaskPositionY:
- m_fillLayerPropertyWrapper = new FillLayerPropertyWrapper<Length>(&FillLayer::yPosition, &FillLayer::setYPosition);
- break;
- case CSSPropertyBackgroundSize:
- case CSSPropertyWebkitBackgroundSize:
- case CSSPropertyWebkitMaskSize:
- m_fillLayerPropertyWrapper = new FillLayerPropertyWrapper<LengthSize>(&FillLayer::sizeLength, &FillLayer::setSizeLength);
- break;
- case CSSPropertyBackgroundImage:
- m_fillLayerPropertyWrapper = new FillLayerStyleImagePropertyWrapper(&FillLayer::image, &FillLayer::setImage);
- break;
- default:
- break;
- }
- }
-
- virtual bool equals(const RenderStyle* a, const RenderStyle* b) const
- {
- const FillLayer* fromLayer = (a->*m_layersGetter)();
- const FillLayer* toLayer = (b->*m_layersGetter)();
-
- while (fromLayer && toLayer) {
- if (!m_fillLayerPropertyWrapper->equals(fromLayer, toLayer))
- return false;
-
- fromLayer = fromLayer->next();
- toLayer = toLayer->next();
- }
-
- return true;
- }
-
- virtual void blend(const AnimationBase* anim, RenderStyle* dst, const RenderStyle* a, const RenderStyle* b, double progress) const
- {
- const FillLayer* aLayer = (a->*m_layersGetter)();
- const FillLayer* bLayer = (b->*m_layersGetter)();
- FillLayer* dstLayer = (dst->*m_layersAccessor)();
-
- while (aLayer && bLayer && dstLayer) {
- m_fillLayerPropertyWrapper->blend(anim, dstLayer, aLayer, bLayer, progress);
- aLayer = aLayer->next();
- bLayer = bLayer->next();
- dstLayer = dstLayer->next();
- }
- }
-
-private:
- FillLayerAnimationPropertyWrapperBase* m_fillLayerPropertyWrapper;
-
- LayersGetter m_layersGetter;
- LayersAccessor m_layersAccessor;
-};
-
-class ShorthandPropertyWrapper : public AnimationPropertyWrapperBase {
-public:
- ShorthandPropertyWrapper(CSSPropertyID property, const StylePropertyShorthand& shorthand)
- : AnimationPropertyWrapperBase(property)
- {
- for (unsigned i = 0; i < shorthand.length(); ++i) {
- AnimationPropertyWrapperBase* wrapper = wrapperForProperty(shorthand.properties()[i]);
- if (wrapper)
- m_propertyWrappers.append(wrapper);
- }
- }
-
- virtual bool isShorthandWrapper() const { return true; }
-
- virtual bool equals(const RenderStyle* a, const RenderStyle* b) const
- {
- Vector<AnimationPropertyWrapperBase*>::const_iterator end = m_propertyWrappers.end();
- for (Vector<AnimationPropertyWrapperBase*>::const_iterator it = m_propertyWrappers.begin(); it != end; ++it) {
- if (!(*it)->equals(a, b))
- return false;
- }
- return true;
- }
-
- virtual void blend(const AnimationBase* anim, RenderStyle* dst, const RenderStyle* a, const RenderStyle* b, double progress) const
- {
- Vector<AnimationPropertyWrapperBase*>::const_iterator end = m_propertyWrappers.end();
- for (Vector<AnimationPropertyWrapperBase*>::const_iterator it = m_propertyWrappers.begin(); it != end; ++it)
- (*it)->blend(anim, dst, a, b, progress);
- }
-
- const Vector<AnimationPropertyWrapperBase*> propertyWrappers() const { return m_propertyWrappers; }
-
-private:
- Vector<AnimationPropertyWrapperBase*> m_propertyWrappers;
-};
-
-class PropertyWrapperFlex : public AnimationPropertyWrapperBase {
-public:
- PropertyWrapperFlex()
- : AnimationPropertyWrapperBase(CSSPropertyFlex)
- {
- }
-
- virtual bool equals(const RenderStyle* a, const RenderStyle* b) const
- {
- // If the style pointers are the same, don't bother doing the test.
- // If either is null, return false. If both are null, return true.
- if ((!a && !b) || a == b)
- return true;
- if (!a || !b)
- return false;
-
- return a->flexBasis() == b->flexBasis() && a->flexGrow() == b->flexGrow() && a->flexShrink() == b->flexShrink();
- }
-
- virtual void blend(const AnimationBase* anim, RenderStyle* dst, const RenderStyle* a, const RenderStyle* b, double progress) const
- {
- dst->setFlexBasis(blendFunc(anim, a->flexBasis(), b->flexBasis(), progress));
- dst->setFlexGrow(blendFunc(anim, a->flexGrow(), b->flexGrow(), progress));
- dst->setFlexShrink(blendFunc(anim, a->flexShrink(), b->flexShrink(), progress));
- }
-};
-
-class PropertyWrapperSVGPaint : public AnimationPropertyWrapperBase {
-public:
- PropertyWrapperSVGPaint(CSSPropertyID prop, const SVGPaint::SVGPaintType& (RenderStyle::*paintTypeGetter)() const, Color (RenderStyle::*getter)() const, void (RenderStyle::*setter)(const Color&))
- : AnimationPropertyWrapperBase(prop)
- , m_paintTypeGetter(paintTypeGetter)
- , m_getter(getter)
- , m_setter(setter)
- {
- }
-
- virtual bool equals(const RenderStyle* a, const RenderStyle* b) const
- {
- if ((a->*m_paintTypeGetter)() != (b->*m_paintTypeGetter)())
- return false;
-
- // We only support animations between SVGPaints that are pure Color values.
- // For everything else we must return true for this method, otherwise
- // we will try to animate between values forever.
- if ((a->*m_paintTypeGetter)() == SVGPaint::SVG_PAINTTYPE_RGBCOLOR) {
- Color fromColor = (a->*m_getter)();
- Color toColor = (b->*m_getter)();
-
- if (!fromColor.isValid() && !toColor.isValid())
- return true;
-
- if (!fromColor.isValid())
- fromColor = Color();
- if (!toColor.isValid())
- toColor = Color();
-
- return fromColor == toColor;
- }
- return true;
- }
-
- virtual void blend(const AnimationBase* anim, RenderStyle* dst, const RenderStyle* a, const RenderStyle* b, double progress) const
- {
- if ((a->*m_paintTypeGetter)() != SVGPaint::SVG_PAINTTYPE_RGBCOLOR
- || (b->*m_paintTypeGetter)() != SVGPaint::SVG_PAINTTYPE_RGBCOLOR)
- return;
-
- Color fromColor = (a->*m_getter)();
- Color toColor = (b->*m_getter)();
-
- if (!fromColor.isValid() && !toColor.isValid())
- return;
-
- if (!fromColor.isValid())
- fromColor = Color();
- if (!toColor.isValid())
- toColor = Color();
- (dst->*m_setter)(blendFunc(anim, fromColor, toColor, progress));
- }
-
-private:
- const SVGPaint::SVGPaintType& (RenderStyle::*m_paintTypeGetter)() const;
- Color (RenderStyle::*m_getter)() const;
- void (RenderStyle::*m_setter)(const Color&);
-};
-
-static void addShorthandProperties()
-{
- static const CSSPropertyID animatableShorthandProperties[] = {
- CSSPropertyBackground, // for background-color, background-position, background-image
- CSSPropertyBackgroundPosition,
- CSSPropertyFont, // for font-size, font-weight
- CSSPropertyWebkitMask, // for mask-position
- CSSPropertyWebkitMaskPosition,
- CSSPropertyBorderTop, CSSPropertyBorderRight, CSSPropertyBorderBottom, CSSPropertyBorderLeft,
- CSSPropertyBorderColor,
- CSSPropertyBorderRadius,
- CSSPropertyBorderWidth,
- CSSPropertyBorder,
- CSSPropertyBorderImage,
- CSSPropertyBorderSpacing,
- CSSPropertyListStyle, // for list-style-image
- CSSPropertyMargin,
- CSSPropertyOutline,
- CSSPropertyPadding,
- CSSPropertyWebkitTextStroke,
- CSSPropertyWebkitColumnRule,
- CSSPropertyWebkitBorderRadius,
- CSSPropertyWebkitTransformOrigin
- };
-
- for (size_t i = 0; i < WTF_ARRAY_LENGTH(animatableShorthandProperties); ++i) {
- CSSPropertyID propertyID = animatableShorthandProperties[i];
- StylePropertyShorthand shorthand = shorthandForProperty(propertyID);
- if (shorthand.length() > 0)
- addPropertyWrapper(propertyID, new ShorthandPropertyWrapper(propertyID, shorthand));
- }
-}
-
-void CSSPropertyAnimation::ensurePropertyMap()
-{
- // FIXME: This data is never destroyed. Maybe we should ref count it and toss it when the last AnimationController is destroyed?
- if (gPropertyWrappers)
- return;
-
- gPropertyWrappers = new Vector<AnimationPropertyWrapperBase*>();
-
- // build the list of property wrappers to do the comparisons and blends
- gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyLeft, &RenderStyle::left, &RenderStyle::setLeft));
- gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyRight, &RenderStyle::right, &RenderStyle::setRight));
- gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyTop, &RenderStyle::top, &RenderStyle::setTop));
- gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyBottom, &RenderStyle::bottom, &RenderStyle::setBottom));
-
- gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyWidth, &RenderStyle::width, &RenderStyle::setWidth));
- gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyMinWidth, &RenderStyle::minWidth, &RenderStyle::setMinWidth));
- gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyMaxWidth, &RenderStyle::maxWidth, &RenderStyle::setMaxWidth));
-
- gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyHeight, &RenderStyle::height, &RenderStyle::setHeight));
- gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyMinHeight, &RenderStyle::minHeight, &RenderStyle::setMinHeight));
- gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyMaxHeight, &RenderStyle::maxHeight, &RenderStyle::setMaxHeight));
-
- gPropertyWrappers->append(new PropertyWrapperFlex());
-
- gPropertyWrappers->append(new PropertyWrapper<unsigned>(CSSPropertyBorderLeftWidth, &RenderStyle::borderLeftWidth, &RenderStyle::setBorderLeftWidth));
- gPropertyWrappers->append(new PropertyWrapper<unsigned>(CSSPropertyBorderRightWidth, &RenderStyle::borderRightWidth, &RenderStyle::setBorderRightWidth));
- gPropertyWrappers->append(new PropertyWrapper<unsigned>(CSSPropertyBorderTopWidth, &RenderStyle::borderTopWidth, &RenderStyle::setBorderTopWidth));
- gPropertyWrappers->append(new PropertyWrapper<unsigned>(CSSPropertyBorderBottomWidth, &RenderStyle::borderBottomWidth, &RenderStyle::setBorderBottomWidth));
- gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyMarginLeft, &RenderStyle::marginLeft, &RenderStyle::setMarginLeft));
- gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyMarginRight, &RenderStyle::marginRight, &RenderStyle::setMarginRight));
- gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyMarginTop, &RenderStyle::marginTop, &RenderStyle::setMarginTop));
- gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyMarginBottom, &RenderStyle::marginBottom, &RenderStyle::setMarginBottom));
- gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyPaddingLeft, &RenderStyle::paddingLeft, &RenderStyle::setPaddingLeft));
- gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyPaddingRight, &RenderStyle::paddingRight, &RenderStyle::setPaddingRight));
- gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyPaddingTop, &RenderStyle::paddingTop, &RenderStyle::setPaddingTop));
- gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyPaddingBottom, &RenderStyle::paddingBottom, &RenderStyle::setPaddingBottom));
- gPropertyWrappers->append(new PropertyWrapperVisitedAffectedColor(CSSPropertyColor, &RenderStyle::color, &RenderStyle::setColor, &RenderStyle::visitedLinkColor, &RenderStyle::setVisitedLinkColor));
-
- gPropertyWrappers->append(new PropertyWrapperVisitedAffectedColor(CSSPropertyBackgroundColor, &RenderStyle::backgroundColor, &RenderStyle::setBackgroundColor, &RenderStyle::visitedLinkBackgroundColor, &RenderStyle::setVisitedLinkBackgroundColor));
-
- gPropertyWrappers->append(new FillLayersPropertyWrapper(CSSPropertyBackgroundImage, &RenderStyle::backgroundLayers, &RenderStyle::accessBackgroundLayers));
- gPropertyWrappers->append(new StyleImagePropertyWrapper(CSSPropertyListStyleImage, &RenderStyle::listStyleImage, &RenderStyle::setListStyleImage));
- gPropertyWrappers->append(new StyleImagePropertyWrapper(CSSPropertyWebkitMaskImage, &RenderStyle::maskImage, &RenderStyle::setMaskImage));
-
- gPropertyWrappers->append(new StyleImagePropertyWrapper(CSSPropertyBorderImageSource, &RenderStyle::borderImageSource, &RenderStyle::setBorderImageSource));
- gPropertyWrappers->append(new PropertyWrapper<LengthBox>(CSSPropertyBorderImageSlice, &RenderStyle::borderImageSlices, &RenderStyle::setBorderImageSlices));
- gPropertyWrappers->append(new PropertyWrapper<LengthBox>(CSSPropertyBorderImageWidth, &RenderStyle::borderImageWidth, &RenderStyle::setBorderImageWidth));
- gPropertyWrappers->append(new PropertyWrapper<LengthBox>(CSSPropertyBorderImageOutset, &RenderStyle::borderImageOutset, &RenderStyle::setBorderImageOutset));
-
- gPropertyWrappers->append(new StyleImagePropertyWrapper(CSSPropertyWebkitMaskBoxImageSource, &RenderStyle::maskBoxImageSource, &RenderStyle::setMaskBoxImageSource));
- gPropertyWrappers->append(new PropertyWrapper<const NinePieceImage&>(CSSPropertyWebkitMaskBoxImage, &RenderStyle::maskBoxImage, &RenderStyle::setMaskBoxImage));
-
- gPropertyWrappers->append(new FillLayersPropertyWrapper(CSSPropertyBackgroundPositionX, &RenderStyle::backgroundLayers, &RenderStyle::accessBackgroundLayers));
- gPropertyWrappers->append(new FillLayersPropertyWrapper(CSSPropertyBackgroundPositionY, &RenderStyle::backgroundLayers, &RenderStyle::accessBackgroundLayers));
- gPropertyWrappers->append(new FillLayersPropertyWrapper(CSSPropertyBackgroundSize, &RenderStyle::backgroundLayers, &RenderStyle::accessBackgroundLayers));
- gPropertyWrappers->append(new FillLayersPropertyWrapper(CSSPropertyWebkitBackgroundSize, &RenderStyle::backgroundLayers, &RenderStyle::accessBackgroundLayers));
-
- gPropertyWrappers->append(new FillLayersPropertyWrapper(CSSPropertyWebkitMaskPositionX, &RenderStyle::maskLayers, &RenderStyle::accessMaskLayers));
- gPropertyWrappers->append(new FillLayersPropertyWrapper(CSSPropertyWebkitMaskPositionY, &RenderStyle::maskLayers, &RenderStyle::accessMaskLayers));
- gPropertyWrappers->append(new FillLayersPropertyWrapper(CSSPropertyWebkitMaskSize, &RenderStyle::maskLayers, &RenderStyle::accessMaskLayers));
-
- gPropertyWrappers->append(new PropertyWrapper<LengthPoint>(CSSPropertyObjectPosition, &RenderStyle::objectPosition, &RenderStyle::setObjectPosition));
-
- gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyFontSize,
- // Must pass a specified size to setFontSize if Text Autosizing is enabled, but a computed size
- // if text zoom is enabled (if neither is enabled it's irrelevant as they're probably the same).
- // FIXME: Should we introduce an option to pass the computed font size here, allowing consumers to
- // enable text zoom rather than Text Autosizing? See http://crbug.com/227545.
- &RenderStyle::specifiedFontSize,
- &RenderStyle::setFontSize));
- gPropertyWrappers->append(new PropertyWrapper<unsigned short>(CSSPropertyWebkitColumnRuleWidth, &RenderStyle::columnRuleWidth, &RenderStyle::setColumnRuleWidth));
- gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyWebkitColumnGap, &RenderStyle::columnGap, &RenderStyle::setColumnGap));
- gPropertyWrappers->append(new PropertyWrapper<unsigned short>(CSSPropertyWebkitColumnCount, &RenderStyle::columnCount, &RenderStyle::setColumnCount));
- gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyWebkitColumnWidth, &RenderStyle::columnWidth, &RenderStyle::setColumnWidth));
- gPropertyWrappers->append(new PropertyWrapper<short>(CSSPropertyWebkitBorderHorizontalSpacing, &RenderStyle::horizontalBorderSpacing, &RenderStyle::setHorizontalBorderSpacing));
- gPropertyWrappers->append(new PropertyWrapper<short>(CSSPropertyWebkitBorderVerticalSpacing, &RenderStyle::verticalBorderSpacing, &RenderStyle::setVerticalBorderSpacing));
- gPropertyWrappers->append(new PropertyWrapper<int>(CSSPropertyZIndex, &RenderStyle::zIndex, &RenderStyle::setZIndex));
- gPropertyWrappers->append(new PropertyWrapper<short>(CSSPropertyOrphans, &RenderStyle::orphans, &RenderStyle::setOrphans));
- gPropertyWrappers->append(new PropertyWrapper<short>(CSSPropertyWidows, &RenderStyle::widows, &RenderStyle::setWidows));
- gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyLineHeight, &RenderStyle::specifiedLineHeight, &RenderStyle::setLineHeight));
- gPropertyWrappers->append(new PropertyWrapper<int>(CSSPropertyOutlineOffset, &RenderStyle::outlineOffset, &RenderStyle::setOutlineOffset));
- gPropertyWrappers->append(new PropertyWrapper<unsigned short>(CSSPropertyOutlineWidth, &RenderStyle::outlineWidth, &RenderStyle::setOutlineWidth));
- gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyLetterSpacing, &RenderStyle::letterSpacing, &RenderStyle::setLetterSpacing));
- gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyWordSpacing, &RenderStyle::wordSpacing, &RenderStyle::setWordSpacing));
- gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyTextIndent, &RenderStyle::textIndent, &RenderStyle::setTextIndent));
-
- gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyWebkitPerspective, &RenderStyle::perspective, &RenderStyle::setPerspective));
- gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyWebkitPerspectiveOriginX, &RenderStyle::perspectiveOriginX, &RenderStyle::setPerspectiveOriginX));
- gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyWebkitPerspectiveOriginY, &RenderStyle::perspectiveOriginY, &RenderStyle::setPerspectiveOriginY));
- gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyWebkitTransformOriginX, &RenderStyle::transformOriginX, &RenderStyle::setTransformOriginX));
- gPropertyWrappers->append(new PropertyWrapper<Length>(CSSPropertyWebkitTransformOriginY, &RenderStyle::transformOriginY, &RenderStyle::setTransformOriginY));
- gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyWebkitTransformOriginZ, &RenderStyle::transformOriginZ, &RenderStyle::setTransformOriginZ));
- gPropertyWrappers->append(new PropertyWrapper<LengthSize>(CSSPropertyBorderTopLeftRadius, &RenderStyle::borderTopLeftRadius, &RenderStyle::setBorderTopLeftRadius));
- gPropertyWrappers->append(new PropertyWrapper<LengthSize>(CSSPropertyBorderTopRightRadius, &RenderStyle::borderTopRightRadius, &RenderStyle::setBorderTopRightRadius));
- gPropertyWrappers->append(new PropertyWrapper<LengthSize>(CSSPropertyBorderBottomLeftRadius, &RenderStyle::borderBottomLeftRadius, &RenderStyle::setBorderBottomLeftRadius));
- gPropertyWrappers->append(new PropertyWrapper<LengthSize>(CSSPropertyBorderBottomRightRadius, &RenderStyle::borderBottomRightRadius, &RenderStyle::setBorderBottomRightRadius));
- gPropertyWrappers->append(new PropertyWrapper<EVisibility>(CSSPropertyVisibility, &RenderStyle::visibility, &RenderStyle::setVisibility));
- gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyZoom, &RenderStyle::zoom, &RenderStyle::setZoomWithoutReturnValue));
-
- gPropertyWrappers->append(new PropertyWrapper<LengthBox>(CSSPropertyClip, &RenderStyle::clip, &RenderStyle::setClip));
-
- gPropertyWrappers->append(new PropertyWrapperAcceleratedOpacity());
- gPropertyWrappers->append(new PropertyWrapperAcceleratedTransform());
- gPropertyWrappers->append(new PropertyWrapperAcceleratedFilter());
-
- gPropertyWrappers->append(new PropertyWrapperClipPath(CSSPropertyWebkitClipPath, &RenderStyle::clipPath, &RenderStyle::setClipPath));
-
- gPropertyWrappers->append(new PropertyWrapperShape(CSSPropertyWebkitShapeInside, &RenderStyle::shapeInside, &RenderStyle::setShapeInside));
-
- gPropertyWrappers->append(new PropertyWrapperVisitedAffectedColor(CSSPropertyWebkitColumnRuleColor, MaybeInvalidColor, &RenderStyle::columnRuleColor, &RenderStyle::setColumnRuleColor, &RenderStyle::visitedLinkColumnRuleColor, &RenderStyle::setVisitedLinkColumnRuleColor));
- gPropertyWrappers->append(new PropertyWrapperVisitedAffectedColor(CSSPropertyWebkitTextStrokeColor, MaybeInvalidColor, &RenderStyle::textStrokeColor, &RenderStyle::setTextStrokeColor, &RenderStyle::visitedLinkTextStrokeColor, &RenderStyle::setVisitedLinkTextStrokeColor));
- gPropertyWrappers->append(new PropertyWrapperVisitedAffectedColor(CSSPropertyWebkitTextFillColor, MaybeInvalidColor, &RenderStyle::textFillColor, &RenderStyle::setTextFillColor, &RenderStyle::visitedLinkTextFillColor, &RenderStyle::setVisitedLinkTextFillColor));
- gPropertyWrappers->append(new PropertyWrapperVisitedAffectedColor(CSSPropertyBorderLeftColor, MaybeInvalidColor, &RenderStyle::borderLeftColor, &RenderStyle::setBorderLeftColor, &RenderStyle::visitedLinkBorderLeftColor, &RenderStyle::setVisitedLinkBorderLeftColor));
- gPropertyWrappers->append(new PropertyWrapperVisitedAffectedColor(CSSPropertyBorderRightColor, MaybeInvalidColor, &RenderStyle::borderRightColor, &RenderStyle::setBorderRightColor, &RenderStyle::visitedLinkBorderRightColor, &RenderStyle::setVisitedLinkBorderRightColor));
- gPropertyWrappers->append(new PropertyWrapperVisitedAffectedColor(CSSPropertyBorderTopColor, MaybeInvalidColor, &RenderStyle::borderTopColor, &RenderStyle::setBorderTopColor, &RenderStyle::visitedLinkBorderTopColor, &RenderStyle::setVisitedLinkBorderTopColor));
- gPropertyWrappers->append(new PropertyWrapperVisitedAffectedColor(CSSPropertyBorderBottomColor, MaybeInvalidColor, &RenderStyle::borderBottomColor, &RenderStyle::setBorderBottomColor, &RenderStyle::visitedLinkBorderBottomColor, &RenderStyle::setVisitedLinkBorderBottomColor));
- gPropertyWrappers->append(new PropertyWrapperVisitedAffectedColor(CSSPropertyOutlineColor, MaybeInvalidColor, &RenderStyle::outlineColor, &RenderStyle::setOutlineColor, &RenderStyle::visitedLinkOutlineColor, &RenderStyle::setVisitedLinkOutlineColor));
-
- gPropertyWrappers->append(new PropertyWrapperShadow(CSSPropertyBoxShadow, &RenderStyle::boxShadow, &RenderStyle::setBoxShadow));
- gPropertyWrappers->append(new PropertyWrapperShadow(CSSPropertyWebkitBoxShadow, &RenderStyle::boxShadow, &RenderStyle::setBoxShadow));
- gPropertyWrappers->append(new PropertyWrapperShadow(CSSPropertyTextShadow, &RenderStyle::textShadow, &RenderStyle::setTextShadow));
-
- gPropertyWrappers->append(new PropertyWrapperSVGPaint(CSSPropertyFill, &RenderStyle::fillPaintType, &RenderStyle::fillPaintColor, &RenderStyle::setFillPaintColor));
- gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyFillOpacity, &RenderStyle::fillOpacity, &RenderStyle::setFillOpacity));
-
- gPropertyWrappers->append(new PropertyWrapperSVGPaint(CSSPropertyStroke, &RenderStyle::strokePaintType, &RenderStyle::strokePaintColor, &RenderStyle::setStrokePaintColor));
- gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyStrokeOpacity, &RenderStyle::strokeOpacity, &RenderStyle::setStrokeOpacity));
- gPropertyWrappers->append(new PropertyWrapper<SVGLength>(CSSPropertyStrokeWidth, &RenderStyle::strokeWidth, &RenderStyle::setStrokeWidth));
- gPropertyWrappers->append(new PropertyWrapper< Vector<SVGLength> >(CSSPropertyStrokeDasharray, &RenderStyle::strokeDashArray, &RenderStyle::setStrokeDashArray));
- gPropertyWrappers->append(new PropertyWrapper<SVGLength>(CSSPropertyStrokeDashoffset, &RenderStyle::strokeDashOffset, &RenderStyle::setStrokeDashOffset));
- gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyStrokeMiterlimit, &RenderStyle::strokeMiterLimit, &RenderStyle::setStrokeMiterLimit));
-
- gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyFloodOpacity, &RenderStyle::floodOpacity, &RenderStyle::setFloodOpacity));
- gPropertyWrappers->append(new PropertyWrapperMaybeInvalidColor(CSSPropertyFloodColor, &RenderStyle::floodColor, &RenderStyle::setFloodColor));
-
- gPropertyWrappers->append(new PropertyWrapper<float>(CSSPropertyStopOpacity, &RenderStyle::stopOpacity, &RenderStyle::setStopOpacity));
- gPropertyWrappers->append(new PropertyWrapperMaybeInvalidColor(CSSPropertyStopColor, &RenderStyle::stopColor, &RenderStyle::setStopColor));
-
- gPropertyWrappers->append(new PropertyWrapperMaybeInvalidColor(CSSPropertyLightingColor, &RenderStyle::lightingColor, &RenderStyle::setLightingColor));
-
- gPropertyWrappers->append(new PropertyWrapper<SVGLength>(CSSPropertyBaselineShift, &RenderStyle::baselineShiftValue, &RenderStyle::setBaselineShiftValue));
- gPropertyWrappers->append(new PropertyWrapper<SVGLength>(CSSPropertyKerning, &RenderStyle::kerning, &RenderStyle::setKerning));
-
- // TODO:
- //
- // CSSPropertyVerticalAlign
- //
- // Compound properties that have components that should be animatable:
- //
- // CSSPropertyWebkitColumns
- // CSSPropertyWebkitBoxReflect
-
- // Make sure unused slots have a value
- for (unsigned int i = 0; i < static_cast<unsigned int>(numCSSProperties); ++i)
- gPropertyWrapperMap[i] = cInvalidPropertyWrapperIndex;
-
- // First we put the non-shorthand property wrappers into the map, so the shorthand-building
- // code can find them.
- size_t n = gPropertyWrappers->size();
- for (unsigned int i = 0; i < n; ++i) {
- CSSPropertyID property = (*gPropertyWrappers)[i]->property();
- ASSERT_WITH_MESSAGE(CSSAnimations::isAnimatableProperty(property), "%s is not whitelisted for animation", getPropertyNameString(property).utf8().data());
- ASSERT(property - firstCSSProperty < numCSSProperties);
- gPropertyWrapperMap[property - firstCSSProperty] = i;
- }
-
- // Now add the shorthand wrappers.
- addShorthandProperties();
-}
-
-// Returns true if we need to start animation timers
-bool CSSPropertyAnimation::blendProperties(const AnimationBase* anim, CSSPropertyID prop, RenderStyle* dst, const RenderStyle* a, const RenderStyle* b, double progress)
-{
- ASSERT(prop != CSSPropertyInvalid);
-
- ensurePropertyMap();
-
- AnimationPropertyWrapperBase* wrapper = wrapperForProperty(prop);
- if (wrapper) {
- wrapper->blend(anim, dst, a, b, progress);
- return !wrapper->animationIsAccelerated() || !anim->isAccelerated();
- }
-
- return false;
-}
-
-bool CSSPropertyAnimation::animationOfPropertyIsAccelerated(CSSPropertyID prop)
-{
- ensurePropertyMap();
- AnimationPropertyWrapperBase* wrapper = wrapperForProperty(prop);
- return wrapper ? wrapper->animationIsAccelerated() : false;
-}
-
-bool CSSPropertyAnimation::propertiesEqual(CSSPropertyID prop, const RenderStyle* a, const RenderStyle* b)
-{
- ensurePropertyMap();
-
- AnimationPropertyWrapperBase* wrapper = wrapperForProperty(prop);
- if (wrapper)
- return wrapper->equals(a, b);
- return true;
-}
-
-CSSPropertyID CSSPropertyAnimation::getPropertyAtIndex(int i, bool& isShorthand)
-{
- ensurePropertyMap();
-
- if (i < 0 || i >= getNumProperties())
- return CSSPropertyInvalid;
-
- AnimationPropertyWrapperBase* wrapper = (*gPropertyWrappers)[i];
- isShorthand = wrapper->isShorthandWrapper();
- return wrapper->property();
-}
-
-int CSSPropertyAnimation::getNumProperties()
-{
- ensurePropertyMap();
-
- return gPropertyWrappers->size();
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/page/animation/CompositeAnimation.cpp b/chromium/third_party/WebKit/Source/core/page/animation/CompositeAnimation.cpp
deleted file mode 100644
index 761571578d8..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/animation/CompositeAnimation.cpp
+++ /dev/null
@@ -1,562 +0,0 @@
-/*
- * Copyright (C) 2007 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/page/animation/CompositeAnimation.h"
-
-#include "CSSPropertyNames.h"
-#include "core/page/animation/AnimationControllerPrivate.h"
-#include "core/page/animation/CSSPropertyAnimation.h"
-#include "core/page/animation/ImplicitAnimation.h"
-#include "core/page/animation/KeyframeAnimation.h"
-#include "core/rendering/style/RenderStyle.h"
-
-namespace WebCore {
-
-CompositeAnimation::~CompositeAnimation()
-{
- // Toss the refs to all animations, but make sure we remove them from
- // any waiting lists first.
-
- clearRenderer();
- m_transitions.clear();
- m_keyframeAnimations.clear();
-}
-
-void CompositeAnimation::clearRenderer()
-{
- if (!m_transitions.isEmpty()) {
- // Clear the renderers from all running animations, in case we are in the middle of
- // an animation callback (see https://bugs.webkit.org/show_bug.cgi?id=22052)
- CSSPropertyTransitionsMap::const_iterator transitionsEnd = m_transitions.end();
- for (CSSPropertyTransitionsMap::const_iterator it = m_transitions.begin(); it != transitionsEnd; ++it) {
- ImplicitAnimation* transition = it->value.get();
- animationController()->animationWillBeRemoved(transition);
- transition->clear();
- }
- }
- if (!m_keyframeAnimations.isEmpty()) {
- AnimationNameMap::const_iterator animationsEnd = m_keyframeAnimations.end();
- for (AnimationNameMap::const_iterator it = m_keyframeAnimations.begin(); it != animationsEnd; ++it) {
- KeyframeAnimation* anim = it->value.get();
- animationController()->animationWillBeRemoved(anim);
- anim->clear();
- }
- }
-}
-
-void CompositeAnimation::updateTransitions(RenderObject* renderer, RenderStyle* currentStyle, RenderStyle* targetStyle)
-{
- // If currentStyle is null or there are no old or new transitions, just skip it
- if (!currentStyle || (!targetStyle->transitions() && m_transitions.isEmpty()))
- return;
-
- // Mark all existing transitions as no longer active. We will mark the still active ones
- // in the next loop and then toss the ones that didn't get marked.
- CSSPropertyTransitionsMap::const_iterator end = m_transitions.end();
- for (CSSPropertyTransitionsMap::const_iterator it = m_transitions.begin(); it != end; ++it)
- it->value->setActive(false);
-
- RefPtr<RenderStyle> modifiedCurrentStyle;
-
- // Check to see if we need to update the active transitions
- if (targetStyle->transitions()) {
- for (size_t i = 0; i < targetStyle->transitions()->size(); ++i) {
- const CSSAnimationData* anim = targetStyle->transitions()->animation(i);
- bool isActiveTransition = anim->duration() || anim->delay() > 0;
-
- CSSAnimationData::AnimationMode mode = anim->animationMode();
- if (mode == CSSAnimationData::AnimateNone)
- continue;
-
- CSSPropertyID prop = anim->property();
-
- bool all = mode == CSSAnimationData::AnimateAll;
-
- // Handle both the 'all' and single property cases. For the single prop case, we make only one pass
- // through the loop.
- for (int propertyIndex = 0; propertyIndex < CSSPropertyAnimation::getNumProperties(); ++propertyIndex) {
- if (all) {
- // Get the next property which is not a shorthand.
- bool isShorthand;
- prop = CSSPropertyAnimation::getPropertyAtIndex(propertyIndex, isShorthand);
- if (isShorthand)
- continue;
- }
-
- // ImplicitAnimations are always hashed by actual properties, never animateAll.
- ASSERT(prop >= firstCSSProperty && prop < (firstCSSProperty + numCSSProperties));
-
- // If there is a running animation for this property, the transition is overridden
- // and we have to use the unanimatedStyle from the animation. We do the test
- // against the unanimated style here, but we "override" the transition later.
- RefPtr<KeyframeAnimation> keyframeAnim = getAnimationForProperty(prop);
- RenderStyle* fromStyle = keyframeAnim ? keyframeAnim->unanimatedStyle() : currentStyle;
-
- // See if there is a current transition for this prop
- ImplicitAnimation* implAnim = m_transitions.get(prop);
- bool equal = true;
-
- if (implAnim) {
- // If we are post active don't bother setting the active flag. This will cause
- // this animation to get removed at the end of this function.
- if (!implAnim->postActive())
- implAnim->setActive(true);
-
- // This might be a transition that is just finishing. That would be the case
- // if it were postActive. But we still need to check for equality because
- // it could be just finishing AND changing to a new goal state.
- //
- // This implAnim might also not be an already running transition. It might be
- // newly added to the list in a previous iteration. This would happen if
- // you have both an explicit transition-property and 'all' in the same
- // list. In this case, the latter one overrides the earlier one, so we
- // behave as though this is a running animation being replaced.
- if (!implAnim->isTargetPropertyEqual(prop, targetStyle)) {
- // For accelerated animations we need to return a new RenderStyle with the _current_ value
- // of the property, so that restarted transitions use the correct starting point.
- if (CSSPropertyAnimation::animationOfPropertyIsAccelerated(prop) && implAnim->isAccelerated()) {
- if (!modifiedCurrentStyle)
- modifiedCurrentStyle = RenderStyle::clone(currentStyle);
-
- implAnim->blendPropertyValueInStyle(prop, modifiedCurrentStyle.get());
- }
- animationController()->animationWillBeRemoved(implAnim);
- m_transitions.remove(prop);
- equal = false;
- }
- } else {
- // We need to start a transition if it is active and the properties don't match
- equal = !isActiveTransition || CSSPropertyAnimation::propertiesEqual(prop, fromStyle, targetStyle);
- }
-
- // We can be in this loop with an inactive transition (!isActiveTransition). We need
- // to do that to check to see if we are canceling a transition. But we don't want to
- // start one of the inactive transitions. So short circuit that here. (See
- // <https://bugs.webkit.org/show_bug.cgi?id=24787>
- if (!equal && isActiveTransition) {
- // Add the new transition
- m_transitions.set(prop, ImplicitAnimation::create(const_cast<CSSAnimationData*>(anim), prop, renderer, this, modifiedCurrentStyle ? modifiedCurrentStyle.get() : fromStyle));
- }
-
- // We only need one pass for the single prop case
- if (!all)
- break;
- }
- }
- }
-
- // Make a list of transitions to be removed
- Vector<int> toBeRemoved;
- end = m_transitions.end();
- for (CSSPropertyTransitionsMap::const_iterator it = m_transitions.begin(); it != end; ++it) {
- ImplicitAnimation* anim = it->value.get();
- if (!anim->active()) {
- animationController()->animationWillBeRemoved(anim);
- toBeRemoved.append(anim->animatingProperty());
- }
- }
-
- // Now remove the transitions from the list
- for (size_t j = 0; j < toBeRemoved.size(); ++j)
- m_transitions.remove(toBeRemoved[j]);
-}
-
-void CompositeAnimation::updateKeyframeAnimations(RenderObject* renderer, RenderStyle* currentStyle, RenderStyle* targetStyle)
-{
- // Nothing to do if we don't have any animations, and didn't have any before
- if (m_keyframeAnimations.isEmpty() && !targetStyle->hasAnimations())
- return;
-
- AnimationNameMap::const_iterator kfend = m_keyframeAnimations.end();
-
- if (currentStyle && currentStyle->hasAnimations() && targetStyle->hasAnimations() && *(currentStyle->animations()) == *(targetStyle->animations())) {
- // The current and target animations are the same so we just need to toss any
- // animation which is finished (postActive).
- for (AnimationNameMap::const_iterator it = m_keyframeAnimations.begin(); it != kfend; ++it) {
- if (it->value->postActive())
- it->value->setIndex(-1);
- }
- } else {
- // Mark all existing animations as no longer active.
- for (AnimationNameMap::const_iterator it = m_keyframeAnimations.begin(); it != kfend; ++it)
- it->value->setIndex(-1);
-
- // Toss the animation order map.
- m_keyframeAnimationOrderList.clear();
-
- DEFINE_STATIC_LOCAL(const AtomicString, none, ("none", AtomicString::ConstructFromLiteral));
-
- // Now mark any still active animations as active and add any new animations.
- if (targetStyle->animations()) {
- int numAnims = targetStyle->animations()->size();
- for (int i = 0; i < numAnims; ++i) {
- const CSSAnimationData* anim = targetStyle->animations()->animation(i);
- if (!anim->isValidAnimation())
- continue;
-
- // See if there is a current animation for this name.
- AtomicString name(anim->name());
- RefPtr<KeyframeAnimation> keyframeAnim = m_keyframeAnimations.get(name);
- if (keyframeAnim) {
- // If this animation is postActive, skip it so it gets removed at the end of this function.
- if (keyframeAnim->postActive())
- continue;
-
- // This one is still active.
-
- // Animations match, but play states may differ. Update if needed.
- keyframeAnim->updatePlayState(anim->playState());
-
- // Set the saved animation to this new one, just in case the play state has changed.
- keyframeAnim->setAnimation(anim);
- keyframeAnim->setIndex(i);
- } else if ((anim->duration() || anim->delay()) && anim->iterationCount() && name != none) {
- keyframeAnim = KeyframeAnimation::create(const_cast<CSSAnimationData*>(anim), renderer, i, this, targetStyle);
- m_keyframeAnimations.set(name, keyframeAnim);
- }
-
- // Add this to the animation order map.
- if (keyframeAnim)
- m_keyframeAnimationOrderList.append(name);
- }
- }
- }
-
- // Make a list of animations to be removed.
- Vector<AtomicString> animsToBeRemoved;
- kfend = m_keyframeAnimations.end();
- for (AnimationNameMap::const_iterator it = m_keyframeAnimations.begin(); it != kfend; ++it) {
- KeyframeAnimation* keyframeAnim = it->value.get();
- if (keyframeAnim->index() < 0) {
- animsToBeRemoved.append(keyframeAnim->name());
- animationController()->animationWillBeRemoved(keyframeAnim);
- keyframeAnim->clear();
- }
- }
-
- // Now remove the animations from the list, and keep stale keys out of the order list.
- if (animsToBeRemoved.size()) {
- for (size_t j = 0; j < animsToBeRemoved.size(); ++j) {
- ASSERT(m_keyframeAnimations.contains(animsToBeRemoved[j]));
- m_keyframeAnimations.remove(animsToBeRemoved[j]);
- }
- Vector<AtomicString> newOrderList;
- for (size_t j = 0; j < m_keyframeAnimationOrderList.size(); ++j) {
- AtomicString key = m_keyframeAnimationOrderList[j];
- if (m_keyframeAnimations.contains(key))
- newOrderList.append(key);
- }
- m_keyframeAnimationOrderList.swap(newOrderList);
- }
-}
-
-PassRefPtr<RenderStyle> CompositeAnimation::animate(RenderObject* renderer, RenderStyle* currentStyle, RenderStyle* targetStyle)
-{
- RefPtr<RenderStyle> resultStyle;
-
- // We don't do any transitions if we don't have a currentStyle (on startup).
- updateTransitions(renderer, currentStyle, targetStyle);
- updateKeyframeAnimations(renderer, currentStyle, targetStyle);
-
- if (currentStyle) {
- // Now that we have transition objects ready, let them know about the new goal state. We want them
- // to fill in a RenderStyle*& only if needed.
- if (!m_transitions.isEmpty()) {
- CSSPropertyTransitionsMap::const_iterator end = m_transitions.end();
- for (CSSPropertyTransitionsMap::const_iterator it = m_transitions.begin(); it != end; ++it) {
- if (ImplicitAnimation* anim = it->value.get())
- anim->animate(this, renderer, currentStyle, targetStyle, resultStyle);
- }
- }
- }
-
- // Now that we have animation objects ready, let them know about the new goal state. We want them
- // to fill in a RenderStyle*& only if needed.
- for (Vector<AtomicString>::const_iterator it = m_keyframeAnimationOrderList.begin(); it != m_keyframeAnimationOrderList.end(); ++it) {
- RefPtr<KeyframeAnimation> keyframeAnim = m_keyframeAnimations.get(*it);
- ASSERT(keyframeAnim);
- keyframeAnim->animate(this, renderer, currentStyle, targetStyle, resultStyle);
- }
-
- return resultStyle ? resultStyle.release() : targetStyle;
-}
-
-PassRefPtr<RenderStyle> CompositeAnimation::getAnimatedStyle() const
-{
- RefPtr<RenderStyle> resultStyle;
- CSSPropertyTransitionsMap::const_iterator end = m_transitions.end();
- for (CSSPropertyTransitionsMap::const_iterator it = m_transitions.begin(); it != end; ++it) {
- if (ImplicitAnimation* implicitAnimation = it->value.get())
- implicitAnimation->getAnimatedStyle(resultStyle);
- }
-
- for (Vector<AtomicString>::const_iterator it = m_keyframeAnimationOrderList.begin(); it != m_keyframeAnimationOrderList.end(); ++it) {
- RefPtr<KeyframeAnimation> keyframeAnimation = m_keyframeAnimations.get(*it);
- ASSERT(keyframeAnimation);
- keyframeAnimation->getAnimatedStyle(resultStyle);
- }
-
- return resultStyle;
-}
-
-double CompositeAnimation::timeToNextService() const
-{
- // Returns the time at which next service is required. -1 means no service is required. 0 means
- // service is required now, and > 0 means service is required that many seconds in the future.
- double minT = -1;
-
- if (!m_transitions.isEmpty()) {
- CSSPropertyTransitionsMap::const_iterator transitionsEnd = m_transitions.end();
- for (CSSPropertyTransitionsMap::const_iterator it = m_transitions.begin(); it != transitionsEnd; ++it) {
- ImplicitAnimation* transition = it->value.get();
- double t = transition ? transition->timeToNextService() : -1;
- if (t < minT || minT == -1)
- minT = t;
- if (minT == 0)
- return 0;
- }
- }
- if (!m_keyframeAnimations.isEmpty()) {
- AnimationNameMap::const_iterator animationsEnd = m_keyframeAnimations.end();
- for (AnimationNameMap::const_iterator it = m_keyframeAnimations.begin(); it != animationsEnd; ++it) {
- KeyframeAnimation* animation = it->value.get();
- double t = animation ? animation->timeToNextService() : -1;
- if (t < minT || minT == -1)
- minT = t;
- if (minT == 0)
- return 0;
- }
- }
-
- return minT;
-}
-
-double CompositeAnimation::timeToNextEvent() const
-{
- // Returns the time at which next service to trigger events is required. -1 means no service is required. 0 means
- // service is required now, and > 0 means service is required that many seconds in the future.
- double minT = -1;
-
- if (!m_transitions.isEmpty()) {
- CSSPropertyTransitionsMap::const_iterator transitionsEnd = m_transitions.end();
- for (CSSPropertyTransitionsMap::const_iterator it = m_transitions.begin(); it != transitionsEnd; ++it) {
- ImplicitAnimation* transition = it->value.get();
- double t = -1;
- bool isLooping;
- if (transition)
- transition->getTimeToNextEvent(t, isLooping);
- if (t < minT || minT == -1)
- minT = t;
- if (!minT)
- return 0;
- }
- }
- if (!m_keyframeAnimations.isEmpty()) {
- AnimationNameMap::const_iterator animationsEnd = m_keyframeAnimations.end();
- for (AnimationNameMap::const_iterator it = m_keyframeAnimations.begin(); it != animationsEnd; ++it) {
- KeyframeAnimation* animation = it->value.get();
- double t = -1;
- bool isLooping;
- if (animation)
- animation->getTimeToNextEvent(t, isLooping);
- if (t < minT || minT == -1)
- minT = t;
- if (!minT)
- return 0;
- }
- }
-
- return minT;
-}
-
-PassRefPtr<KeyframeAnimation> CompositeAnimation::getAnimationForProperty(CSSPropertyID property) const
-{
- RefPtr<KeyframeAnimation> retval;
-
- // We want to send back the last animation with the property if there are multiples.
- // So we need to iterate through all animations
- if (!m_keyframeAnimations.isEmpty()) {
- AnimationNameMap::const_iterator animationsEnd = m_keyframeAnimations.end();
- for (AnimationNameMap::const_iterator it = m_keyframeAnimations.begin(); it != animationsEnd; ++it) {
- RefPtr<KeyframeAnimation> anim = it->value;
- if (anim->hasAnimationForProperty(property))
- retval = anim;
- }
- }
-
- return retval;
-}
-
-void CompositeAnimation::suspendAnimations()
-{
- if (m_suspended)
- return;
-
- m_suspended = true;
-
- if (!m_keyframeAnimations.isEmpty()) {
- AnimationNameMap::const_iterator animationsEnd = m_keyframeAnimations.end();
- for (AnimationNameMap::const_iterator it = m_keyframeAnimations.begin(); it != animationsEnd; ++it) {
- if (KeyframeAnimation* anim = it->value.get())
- anim->updatePlayState(AnimPlayStatePaused);
- }
- }
- if (!m_transitions.isEmpty()) {
- CSSPropertyTransitionsMap::const_iterator transitionsEnd = m_transitions.end();
- for (CSSPropertyTransitionsMap::const_iterator it = m_transitions.begin(); it != transitionsEnd; ++it) {
- ImplicitAnimation* anim = it->value.get();
- if (anim && anim->hasStyle())
- anim->updatePlayState(AnimPlayStatePaused);
- }
- }
-}
-
-void CompositeAnimation::resumeAnimations()
-{
- if (!m_suspended)
- return;
-
- m_suspended = false;
-
- if (!m_keyframeAnimations.isEmpty()) {
- AnimationNameMap::const_iterator animationsEnd = m_keyframeAnimations.end();
- for (AnimationNameMap::const_iterator it = m_keyframeAnimations.begin(); it != animationsEnd; ++it) {
- KeyframeAnimation* anim = it->value.get();
- if (anim && anim->playStatePlaying())
- anim->updatePlayState(AnimPlayStatePlaying);
- }
- }
-
- if (!m_transitions.isEmpty()) {
- CSSPropertyTransitionsMap::const_iterator transitionsEnd = m_transitions.end();
- for (CSSPropertyTransitionsMap::const_iterator it = m_transitions.begin(); it != transitionsEnd; ++it) {
- ImplicitAnimation* anim = it->value.get();
- if (anim && anim->hasStyle())
- anim->updatePlayState(AnimPlayStatePlaying);
- }
- }
-}
-
-void CompositeAnimation::overrideImplicitAnimations(CSSPropertyID property)
-{
- CSSPropertyTransitionsMap::const_iterator end = m_transitions.end();
- if (!m_transitions.isEmpty()) {
- for (CSSPropertyTransitionsMap::const_iterator it = m_transitions.begin(); it != end; ++it) {
- ImplicitAnimation* anim = it->value.get();
- if (anim && anim->animatingProperty() == property)
- anim->setOverridden(true);
- }
- }
-}
-
-void CompositeAnimation::resumeOverriddenImplicitAnimations(CSSPropertyID property)
-{
- if (!m_transitions.isEmpty()) {
- CSSPropertyTransitionsMap::const_iterator end = m_transitions.end();
- for (CSSPropertyTransitionsMap::const_iterator it = m_transitions.begin(); it != end; ++it) {
- ImplicitAnimation* anim = it->value.get();
- if (anim && anim->animatingProperty() == property)
- anim->setOverridden(false);
- }
- }
-}
-
-bool CompositeAnimation::isAnimatingProperty(CSSPropertyID property, bool acceleratedOnly, bool isRunningNow) const
-{
- if (!m_keyframeAnimations.isEmpty()) {
- AnimationNameMap::const_iterator animationsEnd = m_keyframeAnimations.end();
- for (AnimationNameMap::const_iterator it = m_keyframeAnimations.begin(); it != animationsEnd; ++it) {
- KeyframeAnimation* anim = it->value.get();
- if (anim && anim->isAnimatingProperty(property, acceleratedOnly, isRunningNow))
- return true;
- }
- }
-
- if (!m_transitions.isEmpty()) {
- CSSPropertyTransitionsMap::const_iterator transitionsEnd = m_transitions.end();
- for (CSSPropertyTransitionsMap::const_iterator it = m_transitions.begin(); it != transitionsEnd; ++it) {
- ImplicitAnimation* anim = it->value.get();
- if (anim && anim->isAnimatingProperty(property, acceleratedOnly, isRunningNow))
- return true;
- }
- }
- return false;
-}
-
-void CompositeAnimation::pauseAnimationsForTesting(double t)
-{
- AnimationNameMap::const_iterator animationsEnd = m_keyframeAnimations.end();
- for (AnimationNameMap::const_iterator it = m_keyframeAnimations.begin(); it != animationsEnd; ++it) {
- RefPtr<KeyframeAnimation> keyframeAnim = it->value;
- if (!keyframeAnim || !keyframeAnim->running())
- continue;
-
- double count = keyframeAnim->m_animation->iterationCount();
- if ((t >= 0.0) && ((count == CSSAnimationData::IterationCountInfinite) || (t <= count * keyframeAnim->duration())))
- keyframeAnim->freezeAtTime(t);
- }
-
- CSSPropertyTransitionsMap::const_iterator transitionsEnd = m_transitions.end();
- for (CSSPropertyTransitionsMap::const_iterator it = m_transitions.begin(); it != transitionsEnd; ++it) {
- RefPtr<ImplicitAnimation> implAnim = it->value;
-
- if (!implAnim->running())
- continue;
-
- if ((t >= 0.0) && (t <= implAnim->duration()))
- implAnim->freezeAtTime(t);
- }
-}
-
-unsigned CompositeAnimation::numberOfActiveAnimations() const
-{
- unsigned count = 0;
-
- if (!m_keyframeAnimations.isEmpty()) {
- AnimationNameMap::const_iterator animationsEnd = m_keyframeAnimations.end();
- for (AnimationNameMap::const_iterator it = m_keyframeAnimations.begin(); it != animationsEnd; ++it) {
- KeyframeAnimation* anim = it->value.get();
- if (anim->running())
- ++count;
- }
- }
-
- if (!m_transitions.isEmpty()) {
- CSSPropertyTransitionsMap::const_iterator transitionsEnd = m_transitions.end();
- for (CSSPropertyTransitionsMap::const_iterator it = m_transitions.begin(); it != transitionsEnd; ++it) {
- ImplicitAnimation* anim = it->value.get();
- if (anim->running())
- ++count;
- }
- }
-
- return count;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/page/animation/CompositeAnimation.h b/chromium/third_party/WebKit/Source/core/page/animation/CompositeAnimation.h
deleted file mode 100644
index 96221bafffe..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/animation/CompositeAnimation.h
+++ /dev/null
@@ -1,102 +0,0 @@
-/*
- * Copyright (C) 2007 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef CompositeAnimation_h
-#define CompositeAnimation_h
-
-#include "core/page/animation/ImplicitAnimation.h"
-#include "core/page/animation/KeyframeAnimation.h"
-#include "wtf/HashMap.h"
-
-namespace WebCore {
-
-class AnimationControllerPrivate;
-class AnimationController;
-class RenderObject;
-class RenderStyle;
-
-// A CompositeAnimation represents a collection of animations that are running
-// on a single RenderObject, such as a number of properties transitioning at once.
-class CompositeAnimation : public RefCounted<CompositeAnimation> {
-public:
- static PassRefPtr<CompositeAnimation> create(AnimationControllerPrivate* animationController)
- {
- return adoptRef(new CompositeAnimation(animationController));
- };
-
- ~CompositeAnimation();
-
- void clearRenderer();
-
- PassRefPtr<RenderStyle> animate(RenderObject*, RenderStyle* currentStyle, RenderStyle* targetStyle);
- PassRefPtr<RenderStyle> getAnimatedStyle() const;
-
- double timeToNextService() const;
- double timeToNextEvent() const;
-
- AnimationControllerPrivate* animationController() const { return m_animationController; }
-
- void suspendAnimations();
- void resumeAnimations();
- bool suspended() const { return m_suspended; }
-
- bool hasAnimations() const { return !m_transitions.isEmpty() || !m_keyframeAnimations.isEmpty(); }
-
- bool isAnimatingProperty(CSSPropertyID, bool acceleratedOnly, bool isRunningNow) const;
-
- PassRefPtr<KeyframeAnimation> getAnimationForProperty(CSSPropertyID) const;
-
- void overrideImplicitAnimations(CSSPropertyID);
- void resumeOverriddenImplicitAnimations(CSSPropertyID);
-
- void pauseAnimationsForTesting(double t);
- unsigned numberOfActiveAnimations() const;
-
-private:
- CompositeAnimation(AnimationControllerPrivate* animationController)
- : m_animationController(animationController)
- , m_suspended(false)
- {
- }
-
- void updateTransitions(RenderObject*, RenderStyle* currentStyle, RenderStyle* targetStyle);
- void updateKeyframeAnimations(RenderObject*, RenderStyle* currentStyle, RenderStyle* targetStyle);
-
- typedef HashMap<int, RefPtr<ImplicitAnimation> > CSSPropertyTransitionsMap;
- typedef HashMap<AtomicString, RefPtr<KeyframeAnimation> > AnimationNameMap;
-
- AnimationControllerPrivate* m_animationController;
- CSSPropertyTransitionsMap m_transitions;
- AnimationNameMap m_keyframeAnimations;
- Vector<AtomicString> m_keyframeAnimationOrderList;
- bool m_suspended;
-};
-
-} // namespace WebCore
-
-#endif // CompositeAnimation_h
diff --git a/chromium/third_party/WebKit/Source/core/page/animation/ImplicitAnimation.cpp b/chromium/third_party/WebKit/Source/core/page/animation/ImplicitAnimation.cpp
deleted file mode 100644
index 4ceeff678ae..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/animation/ImplicitAnimation.cpp
+++ /dev/null
@@ -1,291 +0,0 @@
-/*
- * Copyright (C) 2007 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/dom/EventNames.h"
-#include "core/page/UseCounter.h"
-#include "core/page/animation/AnimationControllerPrivate.h"
-#include "core/page/animation/CSSPropertyAnimation.h"
-#include "core/page/animation/CompositeAnimation.h"
-#include "core/page/animation/ImplicitAnimation.h"
-#include "core/page/animation/KeyframeAnimation.h"
-#include "core/rendering/RenderBoxModelObject.h"
-#include "public/platform/Platform.h"
-
-namespace WebCore {
-
-ImplicitAnimation::ImplicitAnimation(const CSSAnimationData* transition, CSSPropertyID animatingProperty, RenderObject* renderer, CompositeAnimation* compAnim, RenderStyle* fromStyle)
- : AnimationBase(transition, renderer, compAnim)
- , m_transitionProperty(transition->property())
- , m_animatingProperty(animatingProperty)
- , m_overridden(false)
- , m_active(true)
- , m_fromStyle(fromStyle)
-{
- ASSERT(animatingProperty != CSSPropertyInvalid);
- WebKit::Platform::current()->histogramSparse("WebCore.Animation.CSSProperties", UseCounter::mapCSSPropertyIdToCSSSampleIdForHistogram(m_animatingProperty));
-}
-
-ImplicitAnimation::~ImplicitAnimation()
-{
- // // Make sure to tell the renderer that we are ending. This will make sure any accelerated animations are removed.
- if (!postActive())
- endAnimation();
-}
-
-bool ImplicitAnimation::shouldSendEventForListener(Document::ListenerType inListenerType) const
-{
- return m_object->document().hasListenerType(inListenerType);
-}
-
-void ImplicitAnimation::animate(CompositeAnimation*, RenderObject*, const RenderStyle*, RenderStyle* targetStyle, RefPtr<RenderStyle>& animatedStyle)
-{
- // If we get this far and the animation is done, it means we are cleaning up a just finished animation.
- // So just return. Everything is already all cleaned up.
- if (postActive())
- return;
-
- // Reset to start the transition if we are new
- if (isNew())
- reset(targetStyle);
-
- // Run a cycle of animation.
- // We know we will need a new render style, so make one if needed
- if (!animatedStyle)
- animatedStyle = RenderStyle::clone(targetStyle);
-
- bool needsAnim = CSSPropertyAnimation::blendProperties(this, m_animatingProperty, animatedStyle.get(), m_fromStyle.get(), m_toStyle.get(), progress(1, 0, 0));
- // FIXME: we also need to detect cases where we have to software animate for other reasons,
- // such as a child using inheriting the transform. https://bugs.webkit.org/show_bug.cgi?id=23902
- if (!needsAnim)
- // If we are running an accelerated animation, set a flag in the style which causes the style
- // to compare as different to any other style. This ensures that changes to the property
- // that is animating are correctly detected during the animation (e.g. when a transition
- // gets interrupted).
- animatedStyle->setIsRunningAcceleratedAnimation();
-
- // Fire the start timeout if needed
- fireAnimationEventsIfNeeded();
-}
-
-void ImplicitAnimation::getAnimatedStyle(RefPtr<RenderStyle>& animatedStyle)
-{
- if (!animatedStyle)
- animatedStyle = RenderStyle::clone(m_toStyle.get());
-
- CSSPropertyAnimation::blendProperties(this, m_animatingProperty, animatedStyle.get(), m_fromStyle.get(), m_toStyle.get(), progress(1, 0, 0));
-}
-
-bool ImplicitAnimation::startAnimation(double timeOffset)
-{
- if (m_object && m_object->isComposited())
- return toRenderBoxModelObject(m_object)->startTransition(timeOffset, m_animatingProperty, m_fromStyle.get(), m_toStyle.get());
-
- return false;
-}
-
-void ImplicitAnimation::pauseAnimation(double timeOffset)
-{
- if (!m_object)
- return;
-
- if (m_object->isComposited())
- toRenderBoxModelObject(m_object)->transitionPaused(timeOffset, m_animatingProperty);
-
- // Restore the original (unanimated) style
- if (!paused())
- setNeedsStyleRecalc(m_object->node());
-}
-
-void ImplicitAnimation::endAnimation()
-{
- if (m_object && m_object->isComposited())
- toRenderBoxModelObject(m_object)->transitionFinished(m_animatingProperty);
-}
-
-void ImplicitAnimation::onAnimationEnd(double elapsedTime)
-{
- // If we have a keyframe animation on this property, this transition is being overridden. The keyframe
- // animation keeps an unanimated style in case a transition starts while the keyframe animation is
- // running. But now that the transition has completed, we need to update this style with its new
- // destination. If we didn't, the next time through we would think a transition had started
- // (comparing the old unanimated style with the new final style of the transition).
- RefPtr<KeyframeAnimation> keyframeAnim = m_compAnim->getAnimationForProperty(m_animatingProperty);
- if (keyframeAnim)
- keyframeAnim->setUnanimatedStyle(m_toStyle);
-
- sendTransitionEvent(eventNames().transitionendEvent, elapsedTime);
- endAnimation();
-}
-
-bool ImplicitAnimation::sendTransitionEvent(const AtomicString& eventType, double elapsedTime)
-{
- if (eventType == eventNames().transitionendEvent) {
- Document::ListenerType listenerType = Document::TRANSITIONEND_LISTENER;
-
- if (shouldSendEventForListener(listenerType)) {
- String propertyName = getPropertyNameString(m_animatingProperty);
-
- // Dispatch the event
- RefPtr<Element> element = 0;
- if (m_object->node() && m_object->node()->isElementNode())
- element = toElement(m_object->node());
-
- if (!element)
- return false;
-
- // Schedule event handling
- m_compAnim->animationController()->addEventToDispatch(element, eventType, propertyName, elapsedTime);
-
- // Restore the original (unanimated) style
- if (eventType == eventNames().transitionendEvent && element->renderer())
- setNeedsStyleRecalc(element.get());
-
- return true; // Did dispatch an event
- }
- }
-
- return false; // Didn't dispatch an event
-}
-
-void ImplicitAnimation::reset(RenderStyle* to)
-{
- ASSERT(to);
- ASSERT(m_fromStyle);
-
- m_toStyle = to;
-
- // Restart the transition
- if (m_fromStyle && m_toStyle)
- updateStateMachine(AnimationStateInputRestartAnimation, -1);
-
- // set the transform animation list
- validateTransformFunctionList();
- checkForMatchingFilterFunctionLists();
-}
-
-void ImplicitAnimation::setOverridden(bool b)
-{
- if (b == m_overridden)
- return;
-
- m_overridden = b;
- updateStateMachine(m_overridden ? AnimationStateInputPauseOverride : AnimationStateInputResumeOverride, -1);
-}
-
-bool ImplicitAnimation::affectsProperty(CSSPropertyID property) const
-{
- return (m_animatingProperty == property);
-}
-
-bool ImplicitAnimation::isTargetPropertyEqual(CSSPropertyID prop, const RenderStyle* targetStyle)
-{
- // We can get here for a transition that has not started yet. This would make m_toStyle unset and null.
- // So we check that here (see <https://bugs.webkit.org/show_bug.cgi?id=26706>)
- if (!m_toStyle)
- return false;
- return CSSPropertyAnimation::propertiesEqual(prop, m_toStyle.get(), targetStyle);
-}
-
-void ImplicitAnimation::blendPropertyValueInStyle(CSSPropertyID prop, RenderStyle* currentStyle)
-{
- // We should never add a transition with a 0 duration and delay. But if we ever did
- // it would have a null toStyle. So just in case, let's check that here. (See
- // <https://bugs.webkit.org/show_bug.cgi?id=24787>
- if (!m_toStyle)
- return;
-
- CSSPropertyAnimation::blendProperties(this, prop, currentStyle, m_fromStyle.get(), m_toStyle.get(), progress(1, 0, 0));
-}
-
-void ImplicitAnimation::validateTransformFunctionList()
-{
- m_transformFunctionListValid = false;
-
- if (!m_fromStyle || !m_toStyle)
- return;
-
- const TransformOperations* val = &m_fromStyle->transform();
- const TransformOperations* toVal = &m_toStyle->transform();
-
- if (val->operations().isEmpty())
- val = toVal;
-
- if (val->operations().isEmpty())
- return;
-
- // An emtpy transform list matches anything.
- if (val != toVal && !toVal->operations().isEmpty() && !val->operationsMatch(*toVal))
- return;
-
- // Transform lists match.
- m_transformFunctionListValid = true;
-}
-
-void ImplicitAnimation::checkForMatchingFilterFunctionLists()
-{
- m_filterFunctionListsMatch = false;
-
- if (!m_fromStyle || !m_toStyle)
- return;
-
- const FilterOperations* val = &m_fromStyle->filter();
- const FilterOperations* toVal = &m_toStyle->filter();
-
- if (val->operations().isEmpty())
- val = toVal;
-
- if (val->operations().isEmpty())
- return;
-
- // An emtpy filter list matches anything.
- if (val != toVal && !toVal->operations().isEmpty() && !val->operationsMatch(*toVal))
- return;
-
- // Filter lists match.
- m_filterFunctionListsMatch = true;
-}
-
-double ImplicitAnimation::timeToNextService()
-{
- double t = AnimationBase::timeToNextService();
- if (t != 0 || preActive())
- return t;
-
- // A return value of 0 means we need service. But if this is an accelerated animation we
- // only need service at the end of the transition.
- if (CSSPropertyAnimation::animationOfPropertyIsAccelerated(m_animatingProperty) && isAccelerated()) {
- bool isLooping;
- getTimeToNextEvent(t, isLooping);
- }
-
- return t;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/page/animation/ImplicitAnimation.h b/chromium/third_party/WebKit/Source/core/page/animation/ImplicitAnimation.h
deleted file mode 100644
index a33c2c937f1..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/animation/ImplicitAnimation.h
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
- * Copyright (C) 2007 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ImplicitAnimation_h
-#define ImplicitAnimation_h
-
-#include "CSSPropertyNames.h"
-#include "core/dom/Document.h"
-#include "core/page/animation/AnimationBase.h"
-
-namespace WebCore {
-
-// An ImplicitAnimation tracks the state of a transition of a specific CSS property
-// for a single RenderObject.
-class ImplicitAnimation : public AnimationBase {
-public:
- static PassRefPtr<ImplicitAnimation> create(const CSSAnimationData* animation, CSSPropertyID animatingProperty, RenderObject* renderer, CompositeAnimation* compositeAnimation, RenderStyle* fromStyle)
- {
- return adoptRef(new ImplicitAnimation(animation, animatingProperty, renderer, compositeAnimation, fromStyle));
- };
-
- CSSPropertyID transitionProperty() const { return m_transitionProperty; }
- CSSPropertyID animatingProperty() const { return m_animatingProperty; }
-
- virtual void onAnimationEnd(double elapsedTime);
- virtual bool startAnimation(double timeOffset);
- virtual void pauseAnimation(double /*timeOffset*/);
- virtual void endAnimation();
-
- virtual void animate(CompositeAnimation*, RenderObject*, const RenderStyle* currentStyle, RenderStyle* targetStyle, RefPtr<RenderStyle>& animatedStyle);
- virtual void getAnimatedStyle(RefPtr<RenderStyle>& animatedStyle);
- virtual void reset(RenderStyle* to);
-
- void setOverridden(bool);
- virtual bool overridden() const { return m_overridden; }
-
- virtual bool affectsProperty(CSSPropertyID) const;
-
- bool hasStyle() const { return m_fromStyle && m_toStyle; }
-
- bool isTargetPropertyEqual(CSSPropertyID, const RenderStyle*);
-
- void blendPropertyValueInStyle(CSSPropertyID, RenderStyle*);
-
- virtual double timeToNextService();
-
- bool active() const { return m_active; }
- void setActive(bool b) { m_active = b; }
-
-protected:
- bool shouldSendEventForListener(Document::ListenerType) const;
- bool sendTransitionEvent(const AtomicString&, double elapsedTime);
-
- void validateTransformFunctionList();
- void checkForMatchingFilterFunctionLists();
-
-private:
- ImplicitAnimation(const CSSAnimationData*, CSSPropertyID, RenderObject*, CompositeAnimation*, RenderStyle*);
- virtual ~ImplicitAnimation();
-
- CSSPropertyID m_transitionProperty; // Transition property as specified in the RenderStyle.
- CSSPropertyID m_animatingProperty; // Specific property for this ImplicitAnimation
- bool m_overridden; // true when there is a keyframe animation that overrides the transitioning property
- bool m_active; // used for culling the list of transitions
-
- // The two styles that we are blending.
- RefPtr<RenderStyle> m_fromStyle;
- RefPtr<RenderStyle> m_toStyle;
-};
-
-} // namespace WebCore
-
-#endif // ImplicitAnimation_h
diff --git a/chromium/third_party/WebKit/Source/core/page/animation/KeyframeAnimation.cpp b/chromium/third_party/WebKit/Source/core/page/animation/KeyframeAnimation.cpp
deleted file mode 100644
index 8017ca10905..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/animation/KeyframeAnimation.cpp
+++ /dev/null
@@ -1,462 +0,0 @@
-/*
- * Copyright (C) 2007, 2012 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/page/animation/KeyframeAnimation.h"
-
-#include "CSSPropertyNames.h"
-#include "core/css/resolver/StyleResolver.h"
-#include "core/dom/EventNames.h"
-#include "core/page/UseCounter.h"
-#include "core/page/animation/AnimationControllerPrivate.h"
-#include "core/page/animation/CSSPropertyAnimation.h"
-#include "core/page/animation/CompositeAnimation.h"
-#include "core/rendering/RenderBoxModelObject.h"
-#include "core/rendering/style/RenderStyle.h"
-#include "public/platform/Platform.h"
-
-using namespace std;
-
-namespace WebCore {
-
-KeyframeAnimation::KeyframeAnimation(const CSSAnimationData* animation, RenderObject* renderer, int index, CompositeAnimation* compAnim, RenderStyle* unanimatedStyle)
- : AnimationBase(animation, renderer, compAnim)
- , m_keyframes(renderer, animation->name())
- , m_index(index)
- , m_startEventDispatched(false)
- , m_unanimatedStyle(unanimatedStyle)
-{
- // Get the keyframe RenderStyles
- if (m_object && m_object->node() && m_object->node()->isElementNode())
- m_object->document().styleResolver()->keyframeStylesForAnimation(toElement(m_object->node()), unanimatedStyle, m_keyframes);
-
- // Update the m_transformFunctionListValid flag based on whether the function lists in the keyframes match.
- validateTransformFunctionList();
- checkForMatchingFilterFunctionLists();
- HashSet<CSSPropertyID>::const_iterator endProperties = m_keyframes.endProperties();
- for (HashSet<CSSPropertyID>::const_iterator it = m_keyframes.beginProperties(); it != endProperties; ++it)
- WebKit::Platform::current()->histogramSparse("WebCore.Animation.CSSProperties", UseCounter::mapCSSPropertyIdToCSSSampleIdForHistogram(*it));
-}
-
-KeyframeAnimation::~KeyframeAnimation()
-{
- // Make sure to tell the renderer that we are ending. This will make sure any accelerated animations are removed.
- if (!postActive())
- endAnimation();
-}
-
-void KeyframeAnimation::fetchIntervalEndpointsForProperty(CSSPropertyID property, const RenderStyle*& fromStyle, const RenderStyle*& toStyle, double& prog) const
-{
- // Find the first key
- double elapsedTime = getElapsedTime();
- if (m_animation->duration() && m_animation->iterationCount() != CSSAnimationData::IterationCountInfinite)
- elapsedTime = min(elapsedTime, m_animation->duration() * m_animation->iterationCount());
-
- const double fractionalTime = this->fractionalTime(1, elapsedTime, 0);
-
- size_t numKeyframes = m_keyframes.size();
- if (!numKeyframes)
- return;
-
- ASSERT(!m_keyframes[0].key());
- ASSERT(m_keyframes[m_keyframes.size() - 1].key() == 1);
-
- size_t currentIndex = 0;
- size_t firstIndex = 0;
- size_t lastIndex = numKeyframes - 1;
- size_t distance = numKeyframes;
-
- // Find keyframe that is closest to elapsed time.
- while (distance > 1) {
- currentIndex = (lastIndex + firstIndex) >> 1;
- double key = m_keyframes[currentIndex].key();
- distance = lastIndex - currentIndex;
-
- if (key < fractionalTime) {
- if (distance < 2)
- currentIndex++;
- firstIndex = currentIndex;
- } else {
- lastIndex = currentIndex;
- }
- }
-
- int prevIndex = -1;
- int nextIndex = -1;
-
- // Iterate forward to find next keyframe that is used to animate CSS property.
- for (size_t i = currentIndex; i < numKeyframes; ++i) {
- const KeyframeValue& keyFrame = m_keyframes[i];
- if (keyFrame.key() > fractionalTime && keyFrame.containsProperty(property)) {
- nextIndex = i;
- break;
- }
- }
-
- // Iterate backward to find previous keyframe.
- for (int i = currentIndex; i >= 0; --i) {
- const KeyframeValue& keyFrame = m_keyframes[i];
- if (keyFrame.key() <= fractionalTime && keyFrame.containsProperty(property)) {
- prevIndex = i;
- break;
- }
- }
-
- double scale = 1;
- double offset = 0;
-
- if (prevIndex == -1)
- prevIndex = 0;
-
- if (nextIndex == -1)
- nextIndex = numKeyframes - 1;
-
- const KeyframeValue& prevKeyframe = m_keyframes[prevIndex];
- const KeyframeValue& nextKeyframe = m_keyframes[nextIndex];
-
- fromStyle = prevKeyframe.style();
- toStyle = nextKeyframe.style();
-
- offset = prevKeyframe.key();
- scale = 1.0 / (nextKeyframe.key() - prevKeyframe.key());
- // A scale of infinity is handled in AnimationBase::fractionalTime().
- ASSERT(scale >= 0 && (!std::isinf(scale) || prevIndex == nextIndex));
-
- // FIXME: This sometimes gets the wrong timing function. See crbug.com/288540.
- const TimingFunction* timingFunction = KeyframeValue::timingFunction(prevKeyframe.style(), name());
- prog = progress(scale, offset, timingFunction);
-}
-
-void KeyframeAnimation::animate(CompositeAnimation*, RenderObject*, const RenderStyle*, RenderStyle* targetStyle, RefPtr<RenderStyle>& animatedStyle)
-{
- // Fire the start timeout if needed
- fireAnimationEventsIfNeeded();
-
- // If we have not yet started, we will not have a valid start time, so just start the animation if needed.
- if (isNew() && m_animation->playState() == AnimPlayStatePlaying)
- updateStateMachine(AnimationStateInputStartAnimation, -1);
-
- // If we get this far and the animation is done, it means we are cleaning up a just finished animation.
- // If so, we need to send back the targetStyle.
- if (postActive()) {
- if (!animatedStyle)
- animatedStyle = const_cast<RenderStyle*>(targetStyle);
- return;
- }
-
- // If we are waiting for the start timer, we don't want to change the style yet.
- // Special case 1 - if the delay time is 0, then we do want to set the first frame of the
- // animation right away. This avoids a flash when the animation starts.
- // Special case 2 - if there is a backwards fill mode, then we want to continue
- // through to the style blend so that we get the fromStyle.
- if (waitingToStart() && m_animation->delay() > 0 && !m_animation->fillsBackwards())
- return;
-
- // If we have no keyframes, don't animate.
- if (!m_keyframes.size()) {
- updateStateMachine(AnimationStateInputEndAnimation, -1);
- return;
- }
-
- // Run a cycle of animation.
- // We know we will need a new render style, so make one if needed.
- if (!animatedStyle)
- animatedStyle = RenderStyle::clone(targetStyle);
-
- // FIXME: we need to be more efficient about determining which keyframes we are animating between.
- // We should cache the last pair or something.
- HashSet<CSSPropertyID>::const_iterator endProperties = m_keyframes.endProperties();
- for (HashSet<CSSPropertyID>::const_iterator it = m_keyframes.beginProperties(); it != endProperties; ++it) {
- // Get the from/to styles and progress between
- const RenderStyle* fromStyle = 0;
- const RenderStyle* toStyle = 0;
- double progress = 0.0;
- fetchIntervalEndpointsForProperty(*it, fromStyle, toStyle, progress);
-
- bool needsAnim = CSSPropertyAnimation::blendProperties(this, *it, animatedStyle.get(), fromStyle, toStyle, progress);
- if (!needsAnim)
- // If we are running an accelerated animation, set a flag in the style
- // to indicate it. This can be used to make sure we get an updated
- // style for hit testing, etc.
- animatedStyle->setIsRunningAcceleratedAnimation();
- }
-}
-
-void KeyframeAnimation::getAnimatedStyle(RefPtr<RenderStyle>& animatedStyle)
-{
- // If we're in the delay phase and we're not backwards filling, tell the caller
- // to use the current style.
- if (waitingToStart() && m_animation->delay() > 0 && !m_animation->fillsBackwards())
- return;
-
- if (!m_keyframes.size())
- return;
-
- if (!animatedStyle)
- animatedStyle = RenderStyle::clone(m_object->style());
-
- HashSet<CSSPropertyID>::const_iterator endProperties = m_keyframes.endProperties();
- for (HashSet<CSSPropertyID>::const_iterator it = m_keyframes.beginProperties(); it != endProperties; ++it) {
- // Get the from/to styles and progress between
- const RenderStyle* fromStyle = 0;
- const RenderStyle* toStyle = 0;
- double progress = 0.0;
- fetchIntervalEndpointsForProperty(*it, fromStyle, toStyle, progress);
-
- CSSPropertyAnimation::blendProperties(this, *it, animatedStyle.get(), fromStyle, toStyle, progress);
- }
-}
-
-bool KeyframeAnimation::hasAnimationForProperty(CSSPropertyID property) const
-{
- return m_keyframes.containsProperty(property);
-}
-
-bool KeyframeAnimation::startAnimation(double timeOffset)
-{
- if (m_object && m_object->isComposited()) {
- return toRenderBoxModelObject(m_object)->startAnimation(timeOffset, m_animation.get(), m_keyframes);
- }
- return false;
-}
-
-void KeyframeAnimation::pauseAnimation(double timeOffset)
-{
- if (!m_object)
- return;
-
- if (m_object->isComposited())
- toRenderBoxModelObject(m_object)->animationPaused(timeOffset, m_keyframes.animationName());
-
- // Restore the original (unanimated) style
- if (!paused())
- setNeedsStyleRecalc(m_object->node());
-}
-
-void KeyframeAnimation::endAnimation()
-{
- if (!m_object)
- return;
-
- if (m_object->isComposited())
- toRenderBoxModelObject(m_object)->animationFinished(m_keyframes.animationName());
-
- // Restore the original (unanimated) style
- if (!paused())
- setNeedsStyleRecalc(m_object->node());
-}
-
-bool KeyframeAnimation::shouldSendEventForListener(Document::ListenerType listenerType) const
-{
- return m_object->document().hasListenerType(listenerType);
-}
-
-void KeyframeAnimation::onAnimationStart(double elapsedTime)
-{
- sendAnimationEvent(eventNames().animationstartEvent, elapsedTime);
-}
-
-void KeyframeAnimation::onAnimationIteration(double elapsedTime)
-{
- sendAnimationEvent(eventNames().animationiterationEvent, elapsedTime);
-}
-
-void KeyframeAnimation::onAnimationEnd(double elapsedTime)
-{
- sendAnimationEvent(eventNames().animationendEvent, elapsedTime);
- // End the animation if we don't fill forwards. Forward filling
- // animations are ended properly in the class destructor.
- if (!m_animation->fillsForwards())
- endAnimation();
-}
-
-bool KeyframeAnimation::sendAnimationEvent(const AtomicString& eventType, double elapsedTime)
-{
- Document::ListenerType listenerType;
- if (eventType == eventNames().animationiterationEvent)
- listenerType = Document::ANIMATIONITERATION_LISTENER;
- else if (eventType == eventNames().animationendEvent)
- listenerType = Document::ANIMATIONEND_LISTENER;
- else {
- ASSERT(eventType == eventNames().animationstartEvent);
- if (m_startEventDispatched)
- return false;
- m_startEventDispatched = true;
- listenerType = Document::ANIMATIONSTART_LISTENER;
- }
-
- if (shouldSendEventForListener(listenerType)) {
- // Dispatch the event
- RefPtr<Element> element;
- if (m_object->node() && m_object->node()->isElementNode())
- element = toElement(m_object->node());
-
- if (!element)
- return false;
-
- // Schedule event handling
- m_compAnim->animationController()->addEventToDispatch(element, eventType, m_keyframes.animationName(), elapsedTime);
-
- // Restore the original (unanimated) style
- if (eventType == eventNames().animationendEvent && element->renderer())
- setNeedsStyleRecalc(element.get());
-
- return true; // Did dispatch an event
- }
-
- return false; // Did not dispatch an event
-}
-
-void KeyframeAnimation::overrideAnimations()
-{
- // This will override implicit animations that match the properties in the keyframe animation
- HashSet<CSSPropertyID>::const_iterator end = m_keyframes.endProperties();
- for (HashSet<CSSPropertyID>::const_iterator it = m_keyframes.beginProperties(); it != end; ++it)
- compositeAnimation()->overrideImplicitAnimations(*it);
-}
-
-void KeyframeAnimation::resumeOverriddenAnimations()
-{
- // This will resume overridden implicit animations
- HashSet<CSSPropertyID>::const_iterator end = m_keyframes.endProperties();
- for (HashSet<CSSPropertyID>::const_iterator it = m_keyframes.beginProperties(); it != end; ++it)
- compositeAnimation()->resumeOverriddenImplicitAnimations(*it);
-}
-
-bool KeyframeAnimation::affectsProperty(CSSPropertyID property) const
-{
- return m_keyframes.containsProperty(property);
-}
-
-void KeyframeAnimation::validateTransformFunctionList()
-{
- m_transformFunctionListValid = false;
-
- if (m_keyframes.size() < 2 || !m_keyframes.containsProperty(CSSPropertyWebkitTransform))
- return;
-
- // Empty transforms match anything, so find the first non-empty entry as the reference
- size_t numKeyframes = m_keyframes.size();
- size_t firstNonEmptyTransformKeyframeIndex = numKeyframes;
-
- for (size_t i = 0; i < numKeyframes; ++i) {
- const KeyframeValue& currentKeyframe = m_keyframes[i];
- if (currentKeyframe.style()->transform().operations().size()) {
- firstNonEmptyTransformKeyframeIndex = i;
- break;
- }
- }
-
- if (firstNonEmptyTransformKeyframeIndex == numKeyframes)
- return;
-
- const TransformOperations* firstVal = &m_keyframes[firstNonEmptyTransformKeyframeIndex].style()->transform();
-
- // See if the keyframes are valid
- for (size_t i = firstNonEmptyTransformKeyframeIndex + 1; i < numKeyframes; ++i) {
- const KeyframeValue& currentKeyframe = m_keyframes[i];
- const TransformOperations* val = &currentKeyframe.style()->transform();
-
- // An emtpy transform list matches anything.
- if (val->operations().isEmpty())
- continue;
-
- if (!firstVal->operationsMatch(*val))
- return;
- }
-
- // Keyframes are valid
- m_transformFunctionListValid = true;
-}
-
-void KeyframeAnimation::checkForMatchingFilterFunctionLists()
-{
- m_filterFunctionListsMatch = false;
-
- if (m_keyframes.size() < 2 || !m_keyframes.containsProperty(CSSPropertyWebkitFilter))
- return;
-
- // Empty filters match anything, so find the first non-empty entry as the reference
- size_t numKeyframes = m_keyframes.size();
- size_t firstNonEmptyFilterKeyframeIndex = numKeyframes;
-
- for (size_t i = 0; i < numKeyframes; ++i) {
- const KeyframeValue& currentKeyframe = m_keyframes[i];
- if (currentKeyframe.style()->filter().operations().size()) {
- firstNonEmptyFilterKeyframeIndex = i;
- break;
- }
- }
-
- if (firstNonEmptyFilterKeyframeIndex == numKeyframes)
- return;
-
- const FilterOperations* firstVal = &m_keyframes[firstNonEmptyFilterKeyframeIndex].style()->filter();
-
- for (size_t i = firstNonEmptyFilterKeyframeIndex + 1; i < numKeyframes; ++i) {
- const KeyframeValue& currentKeyframe = m_keyframes[i];
- const FilterOperations* val = &currentKeyframe.style()->filter();
-
- // An emtpy filter list matches anything.
- if (val->operations().isEmpty())
- continue;
-
- if (!firstVal->operationsMatch(*val))
- return;
- }
-
- m_filterFunctionListsMatch = true;
-}
-
-double KeyframeAnimation::timeToNextService()
-{
- double t = AnimationBase::timeToNextService();
- if (t != 0 || preActive())
- return t;
-
- // A return value of 0 means we need service. But if we only have accelerated animations we
- // only need service at the end of the transition
- HashSet<CSSPropertyID>::const_iterator endProperties = m_keyframes.endProperties();
- bool acceleratedPropertiesOnly = true;
-
- for (HashSet<CSSPropertyID>::const_iterator it = m_keyframes.beginProperties(); it != endProperties; ++it) {
- if (!CSSPropertyAnimation::animationOfPropertyIsAccelerated(*it) || !isAccelerated()) {
- acceleratedPropertiesOnly = false;
- break;
- }
- }
-
- if (acceleratedPropertiesOnly) {
- bool isLooping;
- getTimeToNextEvent(t, isLooping);
- }
-
- return t;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/page/animation/KeyframeAnimation.h b/chromium/third_party/WebKit/Source/core/page/animation/KeyframeAnimation.h
deleted file mode 100644
index 0d8b159c11f..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/animation/KeyframeAnimation.h
+++ /dev/null
@@ -1,102 +0,0 @@
-/*
- * Copyright (C) 2007 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef KeyframeAnimation_h
-#define KeyframeAnimation_h
-
-#include "core/dom/Document.h"
-#include "core/page/animation/AnimationBase.h"
-#include "core/rendering/style/KeyframeList.h"
-
-namespace WebCore {
-
-class RenderStyle;
-
-// A KeyframeAnimation tracks the state of an explicit animation
-// for a single RenderObject.
-class KeyframeAnimation : public AnimationBase {
-public:
- static PassRefPtr<KeyframeAnimation> create(const CSSAnimationData* animation, RenderObject* renderer, int index, CompositeAnimation* compositeAnimation, RenderStyle* unanimatedStyle)
- {
- return adoptRef(new KeyframeAnimation(animation, renderer, index, compositeAnimation, unanimatedStyle));
- };
-
- virtual void animate(CompositeAnimation*, RenderObject*, const RenderStyle* currentStyle, RenderStyle* targetStyle, RefPtr<RenderStyle>& animatedStyle);
- virtual void getAnimatedStyle(RefPtr<RenderStyle>& animatedStyle);
-
- const AtomicString& name() const { return m_keyframes.animationName(); }
- int index() const { return m_index; }
- void setIndex(int i) { m_index = i; }
-
- bool hasAnimationForProperty(CSSPropertyID) const;
-
- void setUnanimatedStyle(PassRefPtr<RenderStyle> style) { m_unanimatedStyle = style; }
- RenderStyle* unanimatedStyle() const { return m_unanimatedStyle.get(); }
-
- virtual double timeToNextService();
-
-protected:
- virtual void onAnimationStart(double elapsedTime);
- virtual void onAnimationIteration(double elapsedTime);
- virtual void onAnimationEnd(double elapsedTime);
- virtual bool startAnimation(double timeOffset);
- virtual void pauseAnimation(double timeOffset);
- virtual void endAnimation();
-
- virtual void overrideAnimations();
- virtual void resumeOverriddenAnimations();
-
- bool shouldSendEventForListener(Document::ListenerType inListenerType) const;
- bool sendAnimationEvent(const AtomicString&, double elapsedTime);
-
- virtual bool affectsProperty(CSSPropertyID) const;
-
- void validateTransformFunctionList();
- void checkForMatchingFilterFunctionLists();
-
-private:
- KeyframeAnimation(const CSSAnimationData* animation, RenderObject*, int index, CompositeAnimation*, RenderStyle* unanimatedStyle);
- virtual ~KeyframeAnimation();
-
- // Get the styles for the given property surrounding the current animation time and the progress between them.
- void fetchIntervalEndpointsForProperty(CSSPropertyID, const RenderStyle*& fromStyle, const RenderStyle*& toStyle, double& progress) const;
-
- // The keyframes that we are blending.
- KeyframeList m_keyframes;
-
- // The order in which this animation appears in the animation-name style.
- int m_index;
- bool m_startEventDispatched;
-
- // The style just before we started animation
- RefPtr<RenderStyle> m_unanimatedStyle;
-};
-
-} // namespace WebCore
-
-#endif // KeyframeAnimation_h
diff --git a/chromium/third_party/WebKit/Source/core/page/make_settings.pl b/chromium/third_party/WebKit/Source/core/page/make_settings.pl
deleted file mode 100755
index dd29711f4d4..00000000000
--- a/chromium/third_party/WebKit/Source/core/page/make_settings.pl
+++ /dev/null
@@ -1,531 +0,0 @@
-#!/usr/bin/perl -w
-
-# Copyright (C) 2012 Tony Chang <tony@chromium.org>
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions
-# are met:
-# 1. Redistributions of source code must retain the above copyright
-# notice, this list of conditions and the following disclaimer.
-# 2. Redistributions in binary form must reproduce the above copyright
-# notice, this list of conditions and the following disclaimer in the
-# documentation and/or other materials provided with the distribution.
-#
-# THIS SOFTWARE IS PROVIDED BY GOOGLE, INC. `AS IS'' AND ANY
-# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
-# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
-# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
-# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
-# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
-# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
-# OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-use strict;
-
-use InFilesCompiler;
-
-my %defaultParameters = (
-);
-
-my %webcoreTypeToIdlType = (
- 'int' => 'long',
- 'unsigned' => 'unsigned long',
- 'size_t' => 'unsigned long',
- 'double' => 'double',
- 'float' => 'float',
- 'String' => 'DOMString',
- 'bool' => 'boolean'
-);
-
-sub defaultItemFactory
-{
- return (
- 'conditional' => 0,
- 'initial' => '',
- 'type' => 'bool',
- 'setNeedsStyleRecalcInAllFrames' => 0,
- );
-}
-
-my $InCompiler = InFilesCompiler->new(\%defaultParameters, \&defaultItemFactory);
-
-my $outputDir = $InCompiler->initializeFromCommandLine();
-$InCompiler->compile(\&generateCode);
-
-sub generateCode()
-{
- my $parsedParametersRef = shift;
- my $parsedItemsRef = shift;
-
- generateSettingsMacrosHeader($parsedItemsRef);
- generateInternalSettingsIdlFile($parsedItemsRef);
- generateInternalSettingsHeaderFile($parsedItemsRef);
- generateInternalSettingsCppFile($parsedItemsRef);
-}
-
-sub generateSettingsMacrosHeader($)
-{
- my $parsedItemsRef = shift;
-
- my %parsedItems = %{ $parsedItemsRef };
- my $outputFile = "$outputDir/SettingsMacros.h";
-
- my %unconditionalSettings = ();
- my %settingsByConditional = ();
-
- for my $settingName (sort keys %parsedItems) {
- my $conditional = $parsedItems{$settingName}{"conditional"};
-
- if ($conditional) {
- if (!defined($settingsByConditional{$conditional})) {
- $settingsByConditional{$conditional} = ();
- }
- $settingsByConditional{$conditional}{$settingName} = 1;
- } else {
- $unconditionalSettings{$settingName} = 1;
- }
- }
-
- open my $file, ">$outputFile" or die "Failed to open file: $!";
-
- print $file $InCompiler->license();
-
- # FIXME: Sort by type so bools come last and are bit packed.
-
- print $file "#ifndef SettingsMacros_h\n";
- print $file "#define SettingsMacros_h\n\n";
-
- printConditionalMacros($file, \%settingsByConditional, $parsedItemsRef);
-
- printGettersAndSetters($file, \%unconditionalSettings, \%settingsByConditional, $parsedItemsRef);
- printMemberVariables($file, \%unconditionalSettings, \%settingsByConditional, $parsedItemsRef);
- printInitializerList($file, \%unconditionalSettings, \%settingsByConditional, $parsedItemsRef);
- printSetterBodies($file, \%unconditionalSettings, \%settingsByConditional, $parsedItemsRef);
-
- print $file "#endif // SettingsMacros_h\n";
-
- close $file;
-}
-
-sub printConditionalMacros($$$)
-{
- my ($file, $settingsByConditionalRef, $parsedItemsRef) = @_;
- my %parsedItems = %{ $parsedItemsRef };
- my %settingsByConditional = %{ $settingsByConditionalRef };
-
- for my $conditional (sort keys %settingsByConditional) {
- my $preferredConditional = $InCompiler->preferredConditional($conditional);
- print $file "#if " . $InCompiler->conditionalStringFromAttributeValue($conditional) . "\n";
-
- print $file "#define ${preferredConditional}_SETTINGS_GETTER_AND_SETTERS \\\n";
- for my $settingName (sort keys %{ $settingsByConditional{$conditional} }) {
- printGetterAndSetter($file, $settingName, $parsedItems{$settingName}{"type"}, $parsedItems{$settingName}{"setNeedsStyleRecalcInAllFrames"});
- }
- print $file "// End of ${preferredConditional}_SETTINGS_GETTER_AND_SETTERS\n";
-
- print $file "#define ${preferredConditional}_SETTINGS_NON_BOOL_MEMBER_VARIABLES \\\n";
- for my $settingName (sort keys %{ $settingsByConditional{$conditional} }) {
- my $type = $parsedItems{$settingName}{"type"};
- next if $type eq "bool";
- print $file " $type m_$settingName; \\\n"
- }
- print $file "// End of ${preferredConditional}_SETTINGS_NON_BOOL_MEMBER_VARIABLES\n";
-
- print $file "#define ${preferredConditional}_SETTINGS_BOOL_MEMBER_VARIABLES \\\n";
- for my $settingName (sort keys %{ $settingsByConditional{$conditional} }) {
- next if $parsedItems{$settingName}{"type"} ne "bool";
- print $file " bool m_$settingName : 1; \\\n"
- }
- print $file "// End of ${preferredConditional}_SETTINGS_BOOL_MEMBER_VARIABLES\n";
-
- print $file "#define ${preferredConditional}_SETTINGS_NON_BOOL_INITIALIZERS \\\n";
- for my $settingName (sort keys %{ $settingsByConditional{$conditional} }) {
- next if $parsedItems{$settingName}{"type"} eq "bool";
- printInitializer($file, $settingName, $parsedItemsRef);
- }
- print $file "// End of ${preferredConditional}_SETTINGS_NON_BOOL_INITIALIZERS\n";
-
- print $file "#define ${preferredConditional}_SETTINGS_BOOL_INITIALIZERS \\\n";
- for my $settingName (sort keys %{ $settingsByConditional{$conditional} }) {
- next if $parsedItems{$settingName}{"type"} ne "bool";
- printInitializer($file, $settingName, $parsedItemsRef);
- }
- print $file "// End of ${preferredConditional}_SETTINGS_BOOL_INITIALIZERS\n";
-
- print $file "#define ${preferredConditional}_SETTINGS_SETTER_BODIES \\\n";
- for my $settingName (sort keys %{ $settingsByConditional{$conditional} }) {
- printSetterBody($file, $settingName, $parsedItems{$settingName}{"type"}, $parsedItems{$settingName}{"setNeedsStyleRecalcInAllFrames"});
- }
- print $file "// End of ${preferredConditional}_SETTINGS_SETTER_BODIES\n";
-
- print $file "#else\n";
- print $file "#define ${preferredConditional}_SETTINGS_GETTER_AND_SETTERS\n";
- print $file "#define ${preferredConditional}_SETTINGS_NON_BOOL_MEMBER_VARIABLES\n";
- print $file "#define ${preferredConditional}_SETTINGS_BOOL_MEMBER_VARIABLES\n";
- print $file "#define ${preferredConditional}_SETTINGS_NON_BOOL_INITIALIZERS\n";
- print $file "#define ${preferredConditional}_SETTINGS_BOOL_INITIALIZERS\n";
- print $file "#define ${preferredConditional}_SETTINGS_SETTER_BODIES\n";
- print $file "#endif\n";
- print $file "\n";
- }
-}
-
-sub printGettersAndSetters($$$$)
-{
- my ($file, $unconditionalSettingsRef, $settingsByConditionalRef, $parsedItemsRef) = @_;
- my %parsedItems = %{ $parsedItemsRef };
- my %unconditionalSettings = %{ $unconditionalSettingsRef };
- my %settingsByConditional = %{ $settingsByConditionalRef };
-
- print $file "#define SETTINGS_GETTERS_AND_SETTERS \\\n";
- for my $settingName (sort keys %unconditionalSettings) {
- printGetterAndSetter($file, $settingName, $parsedItems{$settingName}{"type"}, $parsedItems{$settingName}{"setNeedsStyleRecalcInAllFrames"});
- }
- for my $conditional (sort keys %settingsByConditional) {
- my $preferredConditional = $InCompiler->preferredConditional($conditional);
- print $file " ${preferredConditional}_SETTINGS_GETTER_AND_SETTERS \\\n";
- }
- print $file "// End of SETTINGS_GETTERS_AND_SETTERS.\n\n";
-}
-
-sub printMemberVariables($$$$)
-{
- my ($file, $unconditionalSettingsRef, $settingsByConditionalRef, $parsedItemsRef) = @_;
- my %parsedItems = %{ $parsedItemsRef };
- my %unconditionalSettings = %{ $unconditionalSettingsRef };
- my %settingsByConditional = %{ $settingsByConditionalRef };
-
- print $file "#define SETTINGS_MEMBER_VARIABLES \\\n";
- # We list the bools last so we can bit pack them.
- for my $settingName (sort keys %unconditionalSettings) {
- my $type = $parsedItems{$settingName}{"type"};
- next if $type eq "bool";
- print $file " $type m_$settingName; \\\n"
- }
- for my $conditional (sort keys %settingsByConditional) {
- my $preferredConditional = $InCompiler->preferredConditional($conditional);
- print $file " ${preferredConditional}_SETTINGS_NON_BOOL_MEMBER_VARIABLES \\\n";
- }
- for my $settingName (sort keys %unconditionalSettings) {
- next if $parsedItems{$settingName}{"type"} ne "bool";
- print $file " bool m_$settingName : 1; \\\n"
- }
- for my $conditional (sort keys %settingsByConditional) {
- my $preferredConditional = $InCompiler->preferredConditional($conditional);
- print $file " ${preferredConditional}_SETTINGS_BOOL_MEMBER_VARIABLES \\\n";
- }
- print $file "// End of SETTINGS_MEMBER_VARIABLES.\n\n";
-}
-
-sub setterFunctionName($)
-{
- my $settingName = shift;
- my $setterFunctionName = "set" . $settingName;
- substr($setterFunctionName, 3, 1) = uc(substr($setterFunctionName, 3, 1));
- my @prefixesToUpperCase = ("css", "xss", "ftp", "dom");
- foreach my $prefix (@prefixesToUpperCase) {
- my $prefixLength = length($prefix);
- if (substr($settingName, 0, $prefixLength) eq $prefix) {
- substr($setterFunctionName, $prefixLength, $prefixLength) = uc(substr($setterFunctionName, 3, 3));
- }
- }
- return $setterFunctionName;
-}
-
-sub printGetterAndSetter($$$$)
-{
- my ($file, $settingName, $type, $setNeedsStyleRecalcInAllFrames) = @_;
- my $setterFunctionName = setterFunctionName($settingName);
- if (lc(substr($type, 0, 1)) eq substr($type, 0, 1)) {
- print $file " $type $settingName() const { return m_$settingName; } \\\n";
- print $file " void $setterFunctionName($type $settingName)";
- } else {
- print $file " const $type& $settingName() { return m_$settingName; } \\\n";
- print $file " void $setterFunctionName(const $type& $settingName)";
- }
- if ($setNeedsStyleRecalcInAllFrames) {
- print $file "; \\\n";
- } else {
- print $file " { m_$settingName = $settingName; } \\\n";
- }
-}
-
-sub printInitializerList($$$$)
-{
- my ($file, $unconditionalSettingsRef, $settingsByConditionalRef, $parsedItemsRef) = @_;
- my %parsedItems = %{ $parsedItemsRef };
- my %unconditionalSettings = %{ $unconditionalSettingsRef };
- my %settingsByConditional = %{ $settingsByConditionalRef };
-
- print $file "#define SETTINGS_INITIALIZER_LIST \\\n";
- for my $settingName (sort keys %unconditionalSettings) {
- next if $parsedItems{$settingName}{"type"} eq "bool";
- printInitializer($file, $settingName, $parsedItemsRef);
- }
- for my $conditional (sort keys %settingsByConditional) {
- my $preferredConditional = $InCompiler->preferredConditional($conditional);
- print $file " ${preferredConditional}_SETTINGS_NON_BOOL_INITIALIZERS \\\n";
- }
- for my $settingName (sort keys %unconditionalSettings) {
- next if $parsedItems{$settingName}{"type"} ne "bool";
- printInitializer($file, $settingName, $parsedItemsRef);
- }
- for my $conditional (sort keys %settingsByConditional) {
- my $preferredConditional = $InCompiler->preferredConditional($conditional);
- print $file " ${preferredConditional}_SETTINGS_BOOL_INITIALIZERS \\\n";
- }
- print $file "// End of SETTINGS_INITIALIZER_LIST.\n\n";
-}
-
-sub printInitializer($$$)
-{
- my ($file, $settingName, $parsedItemsRef) = @_;
- my %parsedItems = %{ $parsedItemsRef };
-
- my $initialValue = $parsedItems{$settingName}{"initial"};
- my $type = $parsedItems{$settingName}{"type"};
- die "Must provide an initial value for $settingName." if ($initialValue eq '' && lc(substr($type, 0, 1)) eq substr($type, 0, 1));
- return if ($initialValue eq '');
- print $file " , m_$settingName($initialValue) \\\n"
-}
-
-sub printSetterBodies($$$$)
-{
- my ($file, $unconditionalSettingsRef, $settingsByConditionalRef, $parsedItemsRef) = @_;
- my %parsedItems = %{ $parsedItemsRef };
- my %unconditionalSettings = %{ $unconditionalSettingsRef };
- my %settingsByConditional = %{ $settingsByConditionalRef };
-
- print $file "#define SETTINGS_SETTER_BODIES \\\n";
- for my $settingName (sort keys %unconditionalSettings) {
- printSetterBody($file, $settingName, $parsedItems{$settingName}{"type"}, $parsedItems{$settingName}{"setNeedsStyleRecalcInAllFrames"});
- }
- for my $conditional (sort keys %settingsByConditional) {
- my $preferredConditional = $InCompiler->preferredConditional($conditional);
- print $file " ${preferredConditional}_SETTINGS_SETTER_BODIES \\\n";
- }
- print $file "// End of SETTINGS_SETTER_BODIES.\n\n";
-}
-
-sub printSetterBody($$$$)
-{
- my ($file, $settingName, $type, $setNeedsStyleRecalcInAllFrames) = @_;
- return if (!$setNeedsStyleRecalcInAllFrames);
-
- my $setterFunctionName = setterFunctionName($settingName);
- if (lc(substr($type, 0, 1)) eq substr($type, 0, 1)) {
- print $file "void Settings::$setterFunctionName($type $settingName) \\\n";
- } else {
- print $file "void Settings::$setterFunctionName(const $type& $settingName) \\\n";
- }
- print $file "{ \\\n";
- print $file " if (m_$settingName == $settingName) \\\n";
- print $file " return; \\\n";
- print $file " m_$settingName = $settingName; \\\n";
- print $file " m_page->setNeedsRecalcStyleInAllFrames(); \\\n";
- print $file "} \\\n";
-}
-
-sub enumerateParsedItems($$$)
-{
- my ($file, $parsedItemsRef, $visitorFunction) = @_;
- my %parsedItems = %{ $parsedItemsRef };
-
- for my $settingName (sort keys %parsedItems) {
- my $type = $parsedItems{$settingName}{"type"};
- # FIXME: Learn how to auto-generate code for enumerate types.
- next if (!defined($webcoreTypeToIdlType{$type}));
-
- &$visitorFunction($file, $parsedItemsRef, $settingName)
- }
-}
-
-sub generateInternalSettingsIdlFile($)
-{
- my $parsedItemsRef = shift;
-
- my $filename = "$outputDir/InternalSettingsGenerated.idl";
- open my $file, ">$filename" or die "Failed to open file: $!";
- print $file $InCompiler->license();
-
- print $file "interface InternalSettingsGenerated {\n";
-
- sub writeIdlSetter($$$) {
- my ($file, $parsedItemsRef, $settingName) = @_;
- my %parsedItems = %{ $parsedItemsRef };
- my $type = $parsedItems{$settingName}{"type"};
- my $idlType = $webcoreTypeToIdlType{$type};
- my $setterFunctionName = setterFunctionName($settingName);
- print $file " void $setterFunctionName($idlType $settingName);\n";
- };
-
- enumerateParsedItems($file, $parsedItemsRef, \&writeIdlSetter);
-
- print $file "};\n";
- close $file;
-}
-
-sub generateInternalSettingsHeaderFile($)
-{
- my $parsedItemsRef = shift;
- my %parsedItems = %{ $parsedItemsRef };
-
- my $filename = "$outputDir/InternalSettingsGenerated.h";
- open my $file, ">$filename" or die "Failed to open file: $!";
- print $file $InCompiler->license();
-
- print $file <<EOF;
-#ifndef InternalSettingsGenerated_h
-#define InternalSettingsGenerated_h
-
-#include "core/platform/RefCountedSupplement.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class Page;
-
-class InternalSettingsGenerated : public RefCounted<InternalSettingsGenerated> {
-public:
- explicit InternalSettingsGenerated(Page*);
- virtual ~InternalSettingsGenerated();
- void resetToConsistentState();
-EOF
- sub writeHeaderPrototypes($$$) {
- my ($file, $parsedItemsRef, $settingName) = @_;
- my %parsedItems = %{ $parsedItemsRef };
- my $type = $parsedItems{$settingName}{"type"};
- my $setterFunctionName = setterFunctionName($settingName);
- $type = "const String&" if $type eq "String";
- print $file " void $setterFunctionName($type $settingName);\n";
- };
- enumerateParsedItems($file, $parsedItemsRef, \&writeHeaderPrototypes);
-
- print $file <<EOF;
-
-private:
- Page* m_page;
-
-EOF
-
- sub writeBackupMembers($$$) {
- my ($file, $parsedItemsRef, $settingName) = @_;
- my %parsedItems = %{ $parsedItemsRef };
- my $type = $parsedItems{$settingName}{"type"};
- my $conditional = $parsedItems{$settingName}{"conditional"};
- if ($conditional) {
- print $file "#if " . $InCompiler->conditionalStringFromAttributeValue($conditional) . "\n";
- }
- print $file " $type m_$settingName;\n";
- if ($conditional) {
- print $file "#endif\n";
- }
- };
- enumerateParsedItems($file, $parsedItemsRef, \&writeBackupMembers);
-
- print $file "};\n\n";
- print $file "} // namespace WebCore\n";
- print $file "#endif // InternalSettingsGenerated_h\n";
-
- close $file;
-}
-
-sub generateInternalSettingsCppFile($)
-{
- my $parsedItemsRef = shift;
- my %parsedItems = %{ $parsedItemsRef };
-
- my $filename = "$outputDir/InternalSettingsGenerated.cpp";
- open my $file, ">$filename" or die "Failed to open file: $!";
- print $file $InCompiler->license();
-
- print $file <<EOF;
-#include "config.h"
-#include "InternalSettingsGenerated.h"
-
-#include "core/page/Page.h"
-#include "core/page/Settings.h"
-
-namespace WebCore {
-
-InternalSettingsGenerated::InternalSettingsGenerated(Page* page)
- : m_page(page)
-EOF
-
- sub writeBackupInitializers($$$) {
- my ($file, $parsedItemsRef, $settingName) = @_;
- my %parsedItems = %{ $parsedItemsRef };
- my $type = $parsedItems{$settingName}{"type"};
- my $conditional = $parsedItems{$settingName}{"conditional"};
- if ($conditional) {
- print $file "#if " . $InCompiler->conditionalStringFromAttributeValue($conditional) . "\n";
- }
- print $file " , m_$settingName(page->settings().$settingName())\n";
- if ($conditional) {
- print $file "#endif\n";
- }
- };
- enumerateParsedItems($file, $parsedItemsRef, \&writeBackupInitializers);
-
- print $file <<EOF;
-{
-}
-
-InternalSettingsGenerated::~InternalSettingsGenerated()
-{
-}
-
-void InternalSettingsGenerated::resetToConsistentState()
-{
-EOF
- sub writeResetToConsistentState($$$) {
- my ($file, $parsedItemsRef, $settingName) = @_;
- my %parsedItems = %{ $parsedItemsRef };
- my $type = $parsedItems{$settingName}{"type"};
- my $setterFunctionName = setterFunctionName($settingName);
- my $conditional = $parsedItems{$settingName}{"conditional"};
- if ($conditional) {
- print $file "#if " . $InCompiler->conditionalStringFromAttributeValue($conditional) . "\n";
- }
- print $file " m_page->settings().$setterFunctionName(m_$settingName);\n";
- if ($conditional) {
- print $file "#endif\n";
- }
- };
- enumerateParsedItems($file, $parsedItemsRef, \&writeResetToConsistentState);
-
- print $file "}\n";
-
- sub writeSetterFunctions($$$) {
- my ($file, $parsedItemsRef, $settingName) = @_;
- my %parsedItems = %{ $parsedItemsRef };
- my $type = $parsedItems{$settingName}{"type"};
- my $conditional = $parsedItems{$settingName}{"conditional"};
- my $setterFunctionName = setterFunctionName($settingName);
- $type = "const String&" if $type eq "String";
-
- print $file "void InternalSettingsGenerated::$setterFunctionName($type $settingName)\n";
- print $file "{\n";
-
- if ($conditional) {
- print $file "#if " . $InCompiler->conditionalStringFromAttributeValue($conditional) . "\n";
- }
- print $file " m_page->settings().$setterFunctionName($settingName);\n";
- if ($conditional) {
- print $file "#else\n";
- print $file " UNUSED_PARAM($settingName);\n";
- print $file "#endif\n";
- }
- print $file "}\n\n";
- };
- enumerateParsedItems($file, $parsedItemsRef, \&writeSetterFunctions);
-
- print $file "} // namespace WebCore\n";
-
- close $file;
-}
diff --git a/chromium/third_party/WebKit/Source/core/page/scrolling/ScrollingConstraints.h b/chromium/third_party/WebKit/Source/core/page/scrolling/ScrollingConstraints.h
index 8e7b0c74f85..993f2340734 100644
--- a/chromium/third_party/WebKit/Source/core/page/scrolling/ScrollingConstraints.h
+++ b/chromium/third_party/WebKit/Source/core/page/scrolling/ScrollingConstraints.h
@@ -26,7 +26,7 @@
#ifndef ScrollingConstraints_h
#define ScrollingConstraints_h
-#include "core/platform/graphics/FloatRect.h"
+#include "platform/geometry/FloatRect.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/page/scrolling/ScrollingCoordinator.cpp b/chromium/third_party/WebKit/Source/core/page/scrolling/ScrollingCoordinator.cpp
index fbff981432f..51ecb5d055d 100644
--- a/chromium/third_party/WebKit/Source/core/page/scrolling/ScrollingCoordinator.cpp
+++ b/chromium/third_party/WebKit/Source/core/page/scrolling/ScrollingCoordinator.cpp
@@ -32,26 +32,24 @@
#include "core/dom/Node.h"
#include "core/dom/WheelController.h"
#include "core/html/HTMLElement.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameView.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
#include "core/page/Page.h"
-#include "core/page/Settings.h"
-#include "core/platform/PlatformWheelEvent.h"
-#include "core/platform/ScrollAnimator.h"
-#include "core/platform/ScrollbarTheme.h"
-#include "core/platform/chromium/TraceEvent.h"
-#include "core/platform/chromium/support/WebScrollbarImpl.h"
-#include "core/platform/chromium/support/WebScrollbarThemeGeometryNative.h"
-#include "core/platform/graphics/GraphicsLayer.h"
-#include "core/platform/graphics/IntRect.h"
-#include "core/platform/graphics/Region.h"
-#include "core/platform/graphics/transforms/TransformState.h"
+#include "core/frame/Settings.h"
+#include "platform/TraceEvent.h"
+#include "platform/exported/WebScrollbarImpl.h"
+#include "platform/exported/WebScrollbarThemeGeometryNative.h"
+#include "platform/geometry/Region.h"
+#include "platform/geometry/TransformState.h"
+#include "platform/graphics/GraphicsLayer.h"
#if OS(MACOSX)
-#include "core/platform/mac/ScrollAnimatorMac.h"
+#include "platform/mac/ScrollAnimatorMac.h"
#endif
+#include "platform/scroll/ScrollAnimator.h"
+#include "platform/scroll/ScrollbarTheme.h"
#include "core/plugins/PluginView.h"
+#include "core/rendering/CompositedLayerMapping.h"
#include "core/rendering/RenderGeometryMap.h"
-#include "core/rendering/RenderLayerBacking.h"
#include "core/rendering/RenderLayerCompositor.h"
#include "core/rendering/RenderView.h"
#include "public/platform/Platform.h"
@@ -62,11 +60,11 @@
#include "public/platform/WebScrollbarThemePainter.h"
#include "wtf/text/StringBuilder.h"
-using WebKit::WebLayer;
-using WebKit::WebLayerPositionConstraint;
-using WebKit::WebRect;
-using WebKit::WebScrollbarLayer;
-using WebKit::WebVector;
+using blink::WebLayer;
+using blink::WebLayerPositionConstraint;
+using blink::WebRect;
+using blink::WebScrollbarLayer;
+using blink::WebVector;
namespace WebCore {
@@ -89,6 +87,10 @@ PassRefPtr<ScrollingCoordinator> ScrollingCoordinator::create(Page* page)
ScrollingCoordinator::ScrollingCoordinator(Page* page)
: m_page(page)
+ , m_scrollGestureRegionIsDirty(false)
+ , m_touchEventTargetRectsAreDirty(false)
+ , m_wasFrameScrollable(false)
+ , m_lastMainThreadScrollingReasons(0)
{
}
@@ -105,7 +107,8 @@ ScrollingCoordinator::~ScrollingCoordinator()
bool ScrollingCoordinator::touchHitTestingEnabled() const
{
RenderView* contentRenderer = m_page->mainFrame()->contentRenderer();
- return RuntimeEnabledFeatures::touchEnabled() && contentRenderer && contentRenderer->usesCompositing();
+ Settings* settings = m_page->mainFrame()->document()->settings();
+ return RuntimeEnabledFeatures::touchEnabled() && settings->compositorTouchHitTesting() && contentRenderer && contentRenderer->usesCompositing();
}
void ScrollingCoordinator::setShouldHandleScrollGestureOnMainThreadRegion(const Region& region)
@@ -119,29 +122,47 @@ void ScrollingCoordinator::setShouldHandleScrollGestureOnMainThreadRegion(const
}
}
-void ScrollingCoordinator::frameViewLayoutUpdated(FrameView* frameView)
+void ScrollingCoordinator::notifyLayoutUpdated()
{
- TRACE_EVENT0("input", "ScrollingCoordinator::frameViewLayoutUpdated");
+ // These computations need to happen after compositing is updated.
+ m_scrollGestureRegionIsDirty = true;
+ m_touchEventTargetRectsAreDirty = true;
+}
- // Compute the region of the page where we can't handle scroll gestures and mousewheel events
- // on the impl thread. This currently includes:
- // 1. All scrollable areas, such as subframes, overflow divs and list boxes, whose composited
- // scrolling are not enabled. We need to do this even if the frame view whose layout was updated
- // is not the main frame.
- // 2. Resize control areas, e.g. the small rect at the right bottom of div/textarea/iframe when
- // CSS property "resize" is enabled.
- // 3. Plugin areas.
- Region shouldHandleScrollGestureOnMainThreadRegion = computeShouldHandleScrollGestureOnMainThreadRegion(m_page->mainFrame(), IntPoint());
- setShouldHandleScrollGestureOnMainThreadRegion(shouldHandleScrollGestureOnMainThreadRegion);
+void ScrollingCoordinator::updateAfterCompositingChange()
+{
+ TRACE_EVENT0("input", "ScrollingCoordinator::updateAfterCompositingChange");
- if (touchHitTestingEnabled()) {
- LayerHitTestRects touchEventTargetRects;
- computeTouchEventTargetRects(touchEventTargetRects);
- setTouchEventTargetRects(touchEventTargetRects);
+ if (m_scrollGestureRegionIsDirty) {
+ // Compute the region of the page where we can't handle scroll gestures and mousewheel events
+ // on the impl thread. This currently includes:
+ // 1. All scrollable areas, such as subframes, overflow divs and list boxes, whose composited
+ // scrolling are not enabled. We need to do this even if the frame view whose layout was updated
+ // is not the main frame.
+ // 2. Resize control areas, e.g. the small rect at the right bottom of div/textarea/iframe when
+ // CSS property "resize" is enabled.
+ // 3. Plugin areas.
+ Region shouldHandleScrollGestureOnMainThreadRegion = computeShouldHandleScrollGestureOnMainThreadRegion(m_page->mainFrame(), IntPoint());
+ setShouldHandleScrollGestureOnMainThreadRegion(shouldHandleScrollGestureOnMainThreadRegion);
+ m_scrollGestureRegionIsDirty = false;
}
- if (WebLayer* scrollLayer = scrollingWebLayerForScrollableArea(frameView))
- scrollLayer->setBounds(frameView->contentsSize());
+ if (m_touchEventTargetRectsAreDirty) {
+ updateTouchEventTargetRectsIfNeeded();
+ m_touchEventTargetRectsAreDirty = false;
+ }
+
+ FrameView* frameView = m_page->mainFrame()->view();
+ bool frameIsScrollable = frameView && frameView->isScrollable();
+ if (m_wasFrameScrollable != frameIsScrollable)
+ updateShouldUpdateScrollLayerPositionOnMainThread();
+ m_wasFrameScrollable = frameIsScrollable;
+
+ const FrameTree& tree = m_page->mainFrame()->tree();
+ for (const Frame* child = tree.firstChild(); child; child = child->tree().nextSibling()) {
+ if (WebLayer* scrollLayer = scrollingWebLayerForScrollableArea(child->view()))
+ scrollLayer->setBounds(child->view()->contentsSize());
+ }
}
void ScrollingCoordinator::setLayerIsContainerForFixedPositionLayers(GraphicsLayer* layer, bool enable)
@@ -158,7 +179,7 @@ static void clearPositionConstraintExceptForLayer(GraphicsLayer* layer, Graphics
static WebLayerPositionConstraint computePositionConstraint(const RenderLayer* layer)
{
- ASSERT(layer->isComposited());
+ ASSERT(layer->hasCompositedLayerMapping());
do {
if (layer->renderer()->style()->position() == FixedPosition) {
const RenderObject* fixedPositionObject = layer->renderer();
@@ -168,19 +189,22 @@ static WebLayerPositionConstraint computePositionConstraint(const RenderLayer* l
}
layer = layer->parent();
- } while (layer && !layer->isComposited());
+
+ // Composited layers that inherit a fixed position state will be positioned with respect to the nearest compositedLayerMapping's GraphicsLayer.
+ // So, once we find a layer that has its own compositedLayerMapping, we can stop searching for a fixed position RenderObject.
+ } while (layer && !layer->hasCompositedLayerMapping());
return WebLayerPositionConstraint();
}
void ScrollingCoordinator::updateLayerPositionConstraint(RenderLayer* layer)
{
- ASSERT(layer->backing());
- RenderLayerBacking* backing = layer->backing();
- GraphicsLayer* mainLayer = backing->childForSuperlayers();
+ ASSERT(layer->hasCompositedLayerMapping());
+ CompositedLayerMappingPtr compositedLayerMapping = layer->compositedLayerMapping();
+ GraphicsLayer* mainLayer = compositedLayerMapping->childForSuperlayers();
// Avoid unnecessary commits
- clearPositionConstraintExceptForLayer(backing->ancestorClippingLayer(), mainLayer);
- clearPositionConstraintExceptForLayer(backing->graphicsLayer(), mainLayer);
+ clearPositionConstraintExceptForLayer(compositedLayerMapping->ancestorClippingLayer(), mainLayer);
+ clearPositionConstraintExceptForLayer(compositedLayerMapping->mainGraphicsLayer(), mainLayer);
if (WebLayer* scrollableLayer = scrollingWebLayerForGraphicsLayer(mainLayer))
scrollableLayer->setPositionConstraint(computePositionConstraint(layer));
@@ -202,18 +226,18 @@ void ScrollingCoordinator::removeWebScrollbarLayer(ScrollableArea* scrollableAre
static PassOwnPtr<WebScrollbarLayer> createScrollbarLayer(Scrollbar* scrollbar)
{
ScrollbarTheme* theme = scrollbar->theme();
- WebKit::WebScrollbarThemePainter painter(theme, scrollbar);
- OwnPtr<WebKit::WebScrollbarThemeGeometry> geometry(WebKit::WebScrollbarThemeGeometryNative::create(theme));
+ blink::WebScrollbarThemePainter painter(theme, scrollbar);
+ OwnPtr<blink::WebScrollbarThemeGeometry> geometry(blink::WebScrollbarThemeGeometryNative::create(theme));
- OwnPtr<WebScrollbarLayer> scrollbarLayer = adoptPtr(WebKit::Platform::current()->compositorSupport()->createScrollbarLayer(new WebKit::WebScrollbarImpl(scrollbar), painter, geometry.leakPtr()));
+ OwnPtr<WebScrollbarLayer> scrollbarLayer = adoptPtr(blink::Platform::current()->compositorSupport()->createScrollbarLayer(new blink::WebScrollbarImpl(scrollbar), painter, geometry.leakPtr()));
GraphicsLayer::registerContentsLayer(scrollbarLayer->layer());
return scrollbarLayer.release();
}
PassOwnPtr<WebScrollbarLayer> ScrollingCoordinator::createSolidColorScrollbarLayer(ScrollbarOrientation orientation, int thumbThickness, bool isLeftSideVerticalScrollbar)
{
- WebKit::WebScrollbar::Orientation webOrientation = (orientation == HorizontalScrollbar) ? WebKit::WebScrollbar::Horizontal : WebKit::WebScrollbar::Vertical;
- OwnPtr<WebScrollbarLayer> scrollbarLayer = adoptPtr(WebKit::Platform::current()->compositorSupport()->createSolidColorScrollbarLayer(webOrientation, thumbThickness, isLeftSideVerticalScrollbar));
+ blink::WebScrollbar::Orientation webOrientation = (orientation == HorizontalScrollbar) ? blink::WebScrollbar::Horizontal : blink::WebScrollbar::Vertical;
+ OwnPtr<WebScrollbarLayer> scrollbarLayer = adoptPtr(blink::Platform::current()->compositorSupport()->createSolidColorScrollbarLayer(webOrientation, thumbThickness, isLeftSideVerticalScrollbar));
GraphicsLayer::registerContentsLayer(scrollbarLayer->layer());
return scrollbarLayer.release();
}
@@ -240,7 +264,7 @@ static void setupScrollbarLayer(GraphicsLayer* scrollbarGraphicsLayer, WebScroll
scrollbarGraphicsLayer->setDrawsContent(false);
}
-WebScrollbarLayer* ScrollingCoordinator::addWebScrollbarLayer(ScrollableArea* scrollableArea, ScrollbarOrientation orientation, PassOwnPtr<WebKit::WebScrollbarLayer> scrollbarLayer)
+WebScrollbarLayer* ScrollingCoordinator::addWebScrollbarLayer(ScrollableArea* scrollableArea, ScrollbarOrientation orientation, PassOwnPtr<blink::WebScrollbarLayer> scrollbarLayer)
{
ScrollbarMap& scrollbars = orientation == HorizontalScrollbar ? m_horizontalScrollbars : m_verticalScrollbars;
return scrollbars.add(scrollableArea, scrollbarLayer).iterator->value.get();
@@ -319,6 +343,9 @@ bool ScrollingCoordinator::scrollableAreaScrollLayerDidChange(ScrollableArea* sc
webLayer->setScrollable(true);
webLayer->setScrollPosition(IntPoint(scrollableArea->scrollPosition() - scrollableArea->minimumScrollPosition()));
webLayer->setMaxScrollPosition(IntSize(scrollableArea->scrollSize(HorizontalScrollbar), scrollableArea->scrollSize(VerticalScrollbar)));
+ bool canScrollX = scrollableArea->userInputScrollable(HorizontalScrollbar);
+ bool canScrollY = scrollableArea->userInputScrollable(VerticalScrollbar);
+ webLayer->setUserScrollable(canScrollX, canScrollY);
}
if (WebScrollbarLayer* scrollbarLayer = getWebScrollbarLayer(scrollableArea, HorizontalScrollbar)) {
GraphicsLayer* horizontalScrollbarLayer = horizontalScrollbarLayerForScrollableArea(scrollableArea);
@@ -342,8 +369,8 @@ typedef HashMap<const RenderLayer*, Vector<const Frame*> > LayerFrameMap;
static void makeLayerChildFrameMap(const Frame* currentFrame, LayerFrameMap* map)
{
map->clear();
- const FrameTree* tree = currentFrame->tree();
- for (const Frame* child = tree->firstChild(); child; child = child->tree()->nextSibling()) {
+ const FrameTree& tree = currentFrame->tree();
+ for (const Frame* child = tree.firstChild(); child; child = child->tree().nextSibling()) {
const RenderLayer* containingLayer = child->ownerRenderer()->enclosingLayer();
LayerFrameMap::iterator iter = map->find(containingLayer);
if (iter == map->end())
@@ -393,7 +420,8 @@ static void convertLayerRectsToEnclosingCompositedLayerRecursive(
// If the enclosing composited layer itself is scrolled, we have to undo the subtraction
// of its scroll offset since we want the offset relative to the scrolling content, not
// the element itself.
- rect.move(compositedLayer->scrolledContentOffset());
+ if (compositedLayer->renderer()->hasOverflowClip())
+ rect.move(compositedLayer->renderBox()->scrolledContentOffset());
}
compIter->value.append(rect);
}
@@ -460,6 +488,30 @@ static void convertLayerRectsToEnclosingCompositedLayer(Frame* mainFrame, const
convertLayerRectsToEnclosingCompositedLayerRecursive(mainFrame->contentRenderer()->layer(), layerRects, compositorRects, geometryMap, layersWithRects, layerChildFrameMap);
}
+void ScrollingCoordinator::updateTouchEventTargetRectsIfNeeded()
+{
+ TRACE_EVENT0("input", "ScrollingCoordinator::updateTouchEventTargetRectsIfNeeded");
+
+ if (!touchHitTestingEnabled())
+ return;
+
+ LayerHitTestRects touchEventTargetRects;
+ computeTouchEventTargetRects(touchEventTargetRects);
+ setTouchEventTargetRects(touchEventTargetRects);
+}
+
+void ScrollingCoordinator::reset()
+{
+ m_horizontalScrollbars.clear();
+ m_verticalScrollbars.clear();
+ m_layersWithTouchRects.clear();
+ m_wasFrameScrollable = false;
+
+ // This is retained for testing.
+ m_lastMainThreadScrollingReasons = 0;
+ setShouldUpdateScrollLayerPositionOnMainThread(m_lastMainThreadScrollingReasons);
+}
+
// Note that in principle this could be called more often than computeTouchEventTargetRects, for
// example during a non-composited scroll (although that's not yet implemented - crbug.com/261307).
void ScrollingCoordinator::setTouchEventTargetRects(const LayerHitTestRects& layerRects)
@@ -477,12 +529,14 @@ void ScrollingCoordinator::setTouchEventTargetRects(const LayerHitTestRects& lay
WebVector<WebRect> webRects(iter->value.size());
for (size_t i = 0; i < iter->value.size(); ++i)
webRects[i] = enclosingIntRect(iter->value[i]);
- RenderLayerBacking* backing = layer->backing();
+ // This should be ensured by convertLayerRectsToEnclosingCompositedLayer above.
+ ASSERT(layer->hasCompositedLayerMapping());
+ CompositedLayerMappingPtr compositedLayerMapping = layer->compositedLayerMapping();
// If the layer is using composited scrolling, then it's the contents that these
// rects apply to.
- GraphicsLayer* graphicsLayer = backing->scrollingContentsLayer();
+ GraphicsLayer* graphicsLayer = compositedLayerMapping->scrollingContentsLayer();
if (!graphicsLayer)
- graphicsLayer = backing->graphicsLayer();
+ graphicsLayer = compositedLayerMapping->mainGraphicsLayer();
graphicsLayer->platformLayer()->setTouchEventHandlerRegion(webRects);
oldLayersWithTouchRects.remove(layer);
m_layersWithTouchRects.add(layer);
@@ -490,10 +544,14 @@ void ScrollingCoordinator::setTouchEventTargetRects(const LayerHitTestRects& lay
// If there are any layers left that we haven't updated, clear them out.
for (HashSet<const RenderLayer*>::iterator it = oldLayersWithTouchRects.begin(); it != oldLayersWithTouchRects.end(); ++it) {
- if (RenderLayerBacking* backing = (*it)->backing()) {
- GraphicsLayer* graphicsLayer = backing->scrollingContentsLayer();
+ // FIXME: This is a bug. What's happening here is that we're clearing touch regions for
+ // layers that we didn't visit above. That assumes a 1:1 mapping between RenderLayer and
+ // the graphics layer that owns the touch rects. This is false in the case of
+ // HasOwnBackingButPaintsIntoAncestor and will be extra-false in the world of squashing.
+ if ((*it)->hasCompositedLayerMapping()) {
+ GraphicsLayer* graphicsLayer = (*it)->compositedLayerMapping()->scrollingContentsLayer();
if (!graphicsLayer)
- graphicsLayer = backing->graphicsLayer();
+ graphicsLayer = (*it)->compositedLayerMapping()->mainGraphicsLayer();
graphicsLayer->platformLayer()->setTouchEventHandlerRegion(WebVector<WebRect>());
}
}
@@ -508,37 +566,31 @@ void ScrollingCoordinator::touchEventTargetRectsDidChange(const Document*)
if (m_page->mainFrame()->view()->needsLayout())
return;
- TRACE_EVENT0("input", "ScrollingCoordinator::touchEventTargetRectsDidChange");
+ // FIXME: scheduleAnimation() is just a method of forcing the compositor to realize that it
+ // needs to commit here. We should expose a cleaner API for this.
+ RenderView* renderView = m_page->mainFrame()->contentRenderer();
+ if (renderView && renderView->compositor() && renderView->compositor()->inCompositingMode())
+ m_page->mainFrame()->view()->scheduleAnimation();
- LayerHitTestRects touchEventTargetRects;
- computeTouchEventTargetRects(touchEventTargetRects);
- setTouchEventTargetRects(touchEventTargetRects);
+ m_touchEventTargetRectsAreDirty = true;
}
-void ScrollingCoordinator::updateScrollParentForLayer(RenderLayer* child, RenderLayer* parent)
+void ScrollingCoordinator::updateScrollParentForGraphicsLayer(GraphicsLayer* child, RenderLayer* parent)
{
- WebLayer* childWebLayer = scrollingWebLayerForGraphicsLayer(child->layerForScrollChild());
- if (!childWebLayer)
- return;
-
WebLayer* scrollParentWebLayer = 0;
- if (parent && parent->backing())
- scrollParentWebLayer = scrollingWebLayerForGraphicsLayer(parent->backing()->parentForSublayers());
+ if (parent && parent->hasCompositedLayerMapping())
+ scrollParentWebLayer = scrollingWebLayerForGraphicsLayer(parent->compositedLayerMapping()->parentForSublayers());
- childWebLayer->setScrollParent(scrollParentWebLayer);
+ child->setScrollParent(scrollParentWebLayer);
}
-void ScrollingCoordinator::updateClipParentForLayer(RenderLayer* child, RenderLayer* parent)
+void ScrollingCoordinator::updateClipParentForGraphicsLayer(GraphicsLayer* child, RenderLayer* parent)
{
- WebLayer* childWebLayer = scrollingWebLayerForGraphicsLayer(child->backing()->graphicsLayer());
- if (!childWebLayer)
- return;
-
WebLayer* clipParentWebLayer = 0;
- if (parent && parent->backing())
- clipParentWebLayer = scrollingWebLayerForGraphicsLayer(parent->backing()->parentForSublayers());
+ if (parent && parent->hasCompositedLayerMapping())
+ clipParentWebLayer = scrollingWebLayerForGraphicsLayer(parent->compositedLayerMapping()->parentForSublayers());
- childWebLayer->setClipParent(clipParentWebLayer);
+ child->setClipParent(clipParentWebLayer);
}
void ScrollingCoordinator::willDestroyRenderLayer(RenderLayer* layer)
@@ -552,16 +604,17 @@ void ScrollingCoordinator::setWheelEventHandlerCount(unsigned count)
scrollLayer->setHaveWheelEventHandlers(count > 0);
}
-void ScrollingCoordinator::recomputeWheelEventHandlerCountForFrameView(FrameView* frameView)
+void ScrollingCoordinator::recomputeWheelEventHandlerCountForFrameView(FrameView*)
{
- UNUSED_PARAM(frameView);
setWheelEventHandlerCount(computeCurrentWheelEventHandlerCount());
}
void ScrollingCoordinator::setShouldUpdateScrollLayerPositionOnMainThread(MainThreadScrollingReasons reasons)
{
- if (WebLayer* scrollLayer = scrollingWebLayerForScrollableArea(m_page->mainFrame()->view()))
+ if (WebLayer* scrollLayer = scrollingWebLayerForScrollableArea(m_page->mainFrame()->view())) {
+ m_lastMainThreadScrollingReasons = reasons;
scrollLayer->setShouldScrollOnMainThread(reasons);
+ }
}
void ScrollingCoordinator::pageDestroyed()
@@ -614,9 +667,9 @@ Region ScrollingCoordinator::computeShouldHandleScrollGestureOnMainThreadRegion(
// on main thread).
if (const FrameView::ResizerAreaSet* resizerAreas = frameView->resizerAreas()) {
for (FrameView::ResizerAreaSet::const_iterator it = resizerAreas->begin(), end = resizerAreas->end(); it != end; ++it) {
- RenderLayer* layer = *it;
- IntRect bounds = layer->renderer()->absoluteBoundingBoxRect();
- IntRect corner = layer->resizerCornerRect(bounds, ResizerForTouch);
+ RenderBox* box = *it;
+ IntRect bounds = box->absoluteBoundingBoxRect();
+ IntRect corner = box->layer()->scrollableArea()->touchResizerCornerRect(bounds);
corner.moveBy(offset);
shouldHandleScrollGestureOnMainThreadRegion.unite(corner);
}
@@ -633,8 +686,8 @@ Region ScrollingCoordinator::computeShouldHandleScrollGestureOnMainThreadRegion(
}
}
- FrameTree* tree = frame->tree();
- for (Frame* subFrame = tree->firstChild(); subFrame; subFrame = subFrame->tree()->nextSibling())
+ const FrameTree& tree = frame->tree();
+ for (Frame* subFrame = tree.firstChild(); subFrame; subFrame = subFrame->tree().nextSibling())
shouldHandleScrollGestureOnMainThreadRegion.unite(computeShouldHandleScrollGestureOnMainThreadRegion(subFrame, offset));
return shouldHandleScrollGestureOnMainThreadRegion;
@@ -701,7 +754,7 @@ unsigned ScrollingCoordinator::computeCurrentWheelEventHandlerCount()
{
unsigned wheelEventHandlerCount = 0;
- for (Frame* frame = m_page->mainFrame(); frame; frame = frame->tree()->traverseNext()) {
+ for (Frame* frame = m_page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
if (frame->document())
wheelEventHandlerCount += WheelController::from(frame->document())->wheelEventHandlerCount();
}
@@ -780,7 +833,7 @@ void ScrollingCoordinator::frameViewRootLayerDidChange(FrameView* frameView)
if (!coordinatesScrollingForFrameView(frameView))
return;
- frameViewLayoutUpdated(frameView);
+ notifyLayoutUpdated();
recomputeWheelEventHandlerCountForFrameView(frameView);
updateShouldUpdateScrollLayerPositionOnMainThread();
}
@@ -813,12 +866,12 @@ bool ScrollingCoordinator::hasVisibleSlowRepaintViewportConstrainedObjects(Frame
return true;
RenderLayer* layer = toRenderBoxModelObject(viewportConstrainedObject)->layer();
// Any explicit reason that a fixed position element is not composited shouldn't cause slow scrolling.
- if (!layer->isComposited() && layer->viewportConstrainedNotCompositedReason() == RenderLayer::NoNotCompositedReason)
+ if (layer->compositingState() != PaintsIntoOwnBacking && layer->viewportConstrainedNotCompositedReason() == RenderLayer::NoNotCompositedReason)
return true;
// Composited layers that actually paint into their enclosing ancestor
// must also force main thread scrolling.
- if (layer->isComposited() && layer->backing()->paintsIntoCompositedAncestor())
+ if (layer->compositingState() == HasOwnBackingButPaintsIntoAncestor)
return true;
}
return false;
@@ -826,6 +879,9 @@ bool ScrollingCoordinator::hasVisibleSlowRepaintViewportConstrainedObjects(Frame
MainThreadScrollingReasons ScrollingCoordinator::mainThreadScrollingReasons() const
{
+ // The main thread scrolling reasons are applicable to scrolls of the main
+ // frame. If it does not exist or if it is not scrollable, there is no
+ // reason to force main thread scrolling.
FrameView* frameView = m_page->mainFrame()->view();
if (!frameView)
return static_cast<MainThreadScrollingReasons>(0);
@@ -863,7 +919,14 @@ String ScrollingCoordinator::mainThreadScrollingReasonsAsText(MainThreadScrollin
String ScrollingCoordinator::mainThreadScrollingReasonsAsText() const
{
- return mainThreadScrollingReasonsAsText(mainThreadScrollingReasons());
+ return mainThreadScrollingReasonsAsText(m_lastMainThreadScrollingReasons);
+}
+
+bool ScrollingCoordinator::frameViewIsScrollableIsDirty() const
+{
+ FrameView* frameView = m_page->mainFrame()->view();
+ bool frameIsScrollable = frameView && frameView->isScrollable();
+ return frameIsScrollable != m_wasFrameScrollable;
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/page/scrolling/ScrollingCoordinator.h b/chromium/third_party/WebKit/Source/core/page/scrolling/ScrollingCoordinator.h
index 0f08aabd335..3acfe9ad895 100644
--- a/chromium/third_party/WebKit/Source/core/page/scrolling/ScrollingCoordinator.h
+++ b/chromium/third_party/WebKit/Source/core/page/scrolling/ScrollingCoordinator.h
@@ -26,13 +26,13 @@
#ifndef ScrollingCoordinator_h
#define ScrollingCoordinator_h
-#include "core/platform/PlatformWheelEvent.h"
-#include "core/platform/ScrollTypes.h"
-#include "core/platform/graphics/IntRect.h"
#include "core/rendering/RenderObject.h"
+#include "platform/PlatformWheelEvent.h"
+#include "platform/geometry/IntRect.h"
+#include "platform/scroll/ScrollTypes.h"
#include "wtf/text/WTFString.h"
-namespace WebKit {
+namespace blink {
class WebLayer;
class WebScrollbarLayer;
}
@@ -60,8 +60,13 @@ public:
// Return whether this scrolling coordinator handles scrolling for the given frame view.
bool coordinatesScrollingForFrameView(FrameView*) const;
- // Should be called whenever the given frame view has been laid out.
- void frameViewLayoutUpdated(FrameView*);
+ // Called when any frame has done its layout.
+ void notifyLayoutUpdated();
+
+ // Should be called after compositing has been updated.
+ void updateAfterCompositingChange();
+
+ bool needsToUpdateAfterCompositingChange() const { return m_scrollGestureRegionIsDirty || m_touchEventTargetRectsAreDirty || frameViewIsScrollableIsDirty(); }
// Should be called whenever a wheel event handler is added or removed in the
// frame view's underlying document.
@@ -90,7 +95,7 @@ public:
MainThreadScrollingReasons mainThreadScrollingReasons() const;
bool shouldUpdateScrollLayerPositionOnMainThread() const { return mainThreadScrollingReasons() != 0; }
- PassOwnPtr<WebKit::WebScrollbarLayer> createSolidColorScrollbarLayer(ScrollbarOrientation, int thumbThickness, bool isLeftSideVerticalScrollbar);
+ PassOwnPtr<blink::WebScrollbarLayer> createSolidColorScrollbarLayer(ScrollbarOrientation, int thumbThickness, bool isLeftSideVerticalScrollbar);
void willDestroyScrollableArea(ScrollableArea*);
// Returns true if the coordinator handled this change.
@@ -101,13 +106,19 @@ public:
void touchEventTargetRectsDidChange(const Document*);
void willDestroyRenderLayer(RenderLayer*);
- void updateScrollParentForLayer(RenderLayer* child, RenderLayer* parent);
- void updateClipParentForLayer(RenderLayer* child, RenderLayer* parent);
+ void updateScrollParentForGraphicsLayer(GraphicsLayer* child, RenderLayer* parent);
+ void updateClipParentForGraphicsLayer(GraphicsLayer* child, RenderLayer* parent);
static String mainThreadScrollingReasonsAsText(MainThreadScrollingReasons);
String mainThreadScrollingReasonsAsText() const;
Region computeShouldHandleScrollGestureOnMainThreadRegion(const Frame*, const IntPoint& frameLocation) const;
+ void updateTouchEventTargetRectsIfNeeded();
+
+ // For testing purposes only. This ScrollingCoordinator is reused between layout test, and must be reset
+ // for the results to be valid.
+ void reset();
+
protected:
explicit ScrollingCoordinator(Page*);
@@ -122,6 +133,10 @@ protected:
Page* m_page;
+ // Dirty flags used to idenfity what really needs to be computed after compositing is updated.
+ bool m_scrollGestureRegionIsDirty;
+ bool m_touchEventTargetRectsAreDirty;
+
private:
void recomputeWheelEventHandlerCountForFrameView(FrameView*);
void setShouldUpdateScrollLayerPositionOnMainThread(MainThreadScrollingReasons);
@@ -129,7 +144,7 @@ private:
bool hasVisibleSlowRepaintViewportConstrainedObjects(FrameView*) const;
void updateShouldUpdateScrollLayerPositionOnMainThread();
- static WebKit::WebLayer* scrollingWebLayerForScrollableArea(ScrollableArea*);
+ static blink::WebLayer* scrollingWebLayerForScrollableArea(ScrollableArea*);
bool touchHitTestingEnabled() const;
void setShouldHandleScrollGestureOnMainThreadRegion(const Region&);
@@ -137,15 +152,20 @@ private:
void computeTouchEventTargetRects(LayerHitTestRects&);
void setWheelEventHandlerCount(unsigned);
- WebKit::WebScrollbarLayer* addWebScrollbarLayer(ScrollableArea*, ScrollbarOrientation, PassOwnPtr<WebKit::WebScrollbarLayer>);
- WebKit::WebScrollbarLayer* getWebScrollbarLayer(ScrollableArea*, ScrollbarOrientation);
+ blink::WebScrollbarLayer* addWebScrollbarLayer(ScrollableArea*, ScrollbarOrientation, PassOwnPtr<blink::WebScrollbarLayer>);
+ blink::WebScrollbarLayer* getWebScrollbarLayer(ScrollableArea*, ScrollbarOrientation);
void removeWebScrollbarLayer(ScrollableArea*, ScrollbarOrientation);
+ bool frameViewIsScrollableIsDirty() const;
- typedef HashMap<ScrollableArea*, OwnPtr<WebKit::WebScrollbarLayer> > ScrollbarMap;
+ typedef HashMap<ScrollableArea*, OwnPtr<blink::WebScrollbarLayer> > ScrollbarMap;
ScrollbarMap m_horizontalScrollbars;
ScrollbarMap m_verticalScrollbars;
HashSet<const RenderLayer*> m_layersWithTouchRects;
+ bool m_wasFrameScrollable;
+
+ // This is retained for testing.
+ MainThreadScrollingReasons m_lastMainThreadScrollingReasons;
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/AsyncFileSystem.h b/chromium/third_party/WebKit/Source/core/platform/AsyncFileSystem.h
deleted file mode 100644
index a50517571dd..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/AsyncFileSystem.h
+++ /dev/null
@@ -1,134 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef AsyncFileSystem_h
-#define AsyncFileSystem_h
-
-#include "core/platform/Timer.h"
-#include "modules/filesystem/FileSystemType.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebKit { class WebFileWriterClient; }
-
-namespace WebCore {
-
-class AsyncFileSystem;
-class AsyncFileSystemCallbacks;
-class KURL;
-
-// This class provides async interface for platform-specific file system implementation. Note that all the methods take platform paths.
-class AsyncFileSystem {
- WTF_MAKE_NONCOPYABLE(AsyncFileSystem);
-public:
- virtual ~AsyncFileSystem() { }
-
- virtual void stop() { }
- virtual bool hasPendingActivity() { return false; }
-
- // Subclass must implement this if it supports synchronous operations.
- // This should return false if there are no pending operations.
- virtual bool waitForOperationToComplete() { return true; }
-
- // Creates and returns a new platform-specific AsyncFileSystem instance if the platform has its own implementation.
- static PassOwnPtr<AsyncFileSystem> create();
-
- // Moves a file or directory from srcPath to destPath.
- // AsyncFileSystemCallbacks::didSucceed() is called when the operation is completed successfully.
- // AsyncFileSystemCallbacks::didFail() is called otherwise.
- virtual void move(const KURL& srcPath, const KURL& destPath, PassOwnPtr<AsyncFileSystemCallbacks>) = 0;
-
- // Copies a file or directory from srcPath to destPath.
- // AsyncFileSystemCallbacks::didSucceed() is called when the operation is completed successfully.
- // AsyncFileSystemCallbacks::didFail() is called otherwise.
- virtual void copy(const KURL& srcPath, const KURL& destPath, PassOwnPtr<AsyncFileSystemCallbacks>) = 0;
-
- // Deletes a file or directory at a given path.
- // It is an error to try to remove a directory that is not empty.
- // AsyncFileSystemCallbacks::didSucceed() is called when the operation is completed successfully.
- // AsyncFileSystemCallbacks::didFail() is called otherwise.
- virtual void remove(const KURL& path, PassOwnPtr<AsyncFileSystemCallbacks>) = 0;
-
- // Recursively deletes a directory at a given path.
- // AsyncFileSystemCallbacks::didSucceed() is called when the operation is completed successfully.
- // AsyncFileSystemCallbacks::didFail() is called otherwise.
- virtual void removeRecursively(const KURL& path, PassOwnPtr<AsyncFileSystemCallbacks>) = 0;
-
- // Retrieves the metadata information of the file or directory at a given path.
- // AsyncFileSystemCallbacks::didReadMetadata() is called when the operation is completed successfully.
- // AsyncFileSystemCallbacks::didFail() is called otherwise.
- virtual void readMetadata(const KURL& path, PassOwnPtr<AsyncFileSystemCallbacks>) = 0;
-
- // Creates a file at a given path. If exclusive flag is true, it fails if the path already exists.
- // AsyncFileSystemCallbacks::didSucceed() is called when the operation is completed successfully.
- // AsyncFileSystemCallbacks::didFail() is called otherwise.
- virtual void createFile(const KURL& path, bool exclusive, PassOwnPtr<AsyncFileSystemCallbacks>) = 0;
-
- // Creates a directory at a given path. If exclusive flag is true, it fails if the path already exists.
- // AsyncFileSystemCallbacks::didSucceed() is called when the operation is completed successfully.
- // AsyncFileSystemCallbacks::didFail() is called otherwise.
- virtual void createDirectory(const KURL& path, bool exclusive, PassOwnPtr<AsyncFileSystemCallbacks>) = 0;
-
- // Checks if a file exists at a given path.
- // AsyncFileSystemCallbacks::didSucceed() is called if the file exists.
- // AsyncFileSystemCallbacks::didFail() is called otherwise.
- virtual void fileExists(const KURL& path, PassOwnPtr<AsyncFileSystemCallbacks>) = 0;
-
- // Checks if a directory exists at a given path.
- // AsyncFileSystemCallbacks::didSucceed() is called if the directory exists.
- // AsyncFileSystemCallbacks::didFail() is called otherwise.
- virtual void directoryExists(const KURL& path, PassOwnPtr<AsyncFileSystemCallbacks>) = 0;
-
- // Reads directory entries of a given directory at path.
- // AsyncFileSystemCallbacks::didReadDirectoryEntry() is called when each directory entry is called. AsyncFileSystemCallbacks::didReadDirectoryEntries() is called after a chunk of directory entries have been read.
- // AsyncFileSystemCallbacks::didFail() is when there is an error.
- virtual void readDirectory(const KURL& path, PassOwnPtr<AsyncFileSystemCallbacks>) = 0;
-
- // Creates an WebFileWriter for a given file path.
- // AsyncFileSystemCallbacks::didCreateFileWriter() is called when an AsyncFileWriter is created successfully.
- // AsyncFileSystemCallbacks::didFail() is called otherwise.
- virtual void createWriter(WebKit::WebFileWriterClient*, const KURL& path, PassOwnPtr<AsyncFileSystemCallbacks>) = 0;
-
- // Creates a snapshot file and read its metadata for a new File object.
- // In local filesystem cases the backend may simply return the metadata of the file itself (as well as readMetadata does),
- // while in remote filesystem case the backend may download the file into a temporary snapshot file and return the metadata of the temporary file.
- // AsyncFileSystemCallbacks::didReadMetadata() is called when the metadata for the snapshot file is successfully returned.
- // AsyncFileSystemCallbacks::didFail() is called otherwise.
- //
- // Note: the returned metadata info is cached in the File object for non-regular filesystem types (neither Temporary nor Persistent). The port could return valid metadata if it wants File object to cache metadata (e.g. if the file body is on a remote server), but otherwise should NOT return valid metadata.
- virtual void createSnapshotFileAndReadMetadata(const KURL& path, PassOwnPtr<AsyncFileSystemCallbacks>) = 0;
-
-protected:
- AsyncFileSystem() { }
-};
-
-} // namespace WebCore
-
-#endif // AsyncFileSystem_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/AsyncFileSystemCallbacks.h b/chromium/third_party/WebKit/Source/core/platform/AsyncFileSystemCallbacks.h
deleted file mode 100644
index a210b9901f1..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/AsyncFileSystemCallbacks.h
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef AsyncFileSystemCallbacks_h
-#define AsyncFileSystemCallbacks_h
-
-#include "core/platform/AsyncFileSystem.h"
-#include "core/platform/FileMetadata.h"
-#include "core/platform/network/BlobData.h"
-#include "public/platform/WebFileWriter.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class AsyncFileSystemCallbacks {
- WTF_MAKE_NONCOPYABLE(AsyncFileSystemCallbacks);
-public:
- AsyncFileSystemCallbacks() : m_blockUntilCompletion(false) { }
-
- // Called when a requested operation is completed successfully.
- virtual void didSucceed() { ASSERT_NOT_REACHED(); }
-
- // Called when a requested file system is opened.
- virtual void didOpenFileSystem(const String& name, const KURL& rootURL) { ASSERT_NOT_REACHED(); }
-
- // Called when a filesystem URL is resolved.
- virtual void didResolveURL(const String& name, const KURL& rootURL, FileSystemType, const String& filePath, bool isDirectory) { ASSERT_NOT_REACHED(); }
-
- // Called when a file metadata is read successfully.
- virtual void didReadMetadata(const FileMetadata&) { ASSERT_NOT_REACHED(); }
-
- // Called when a snapshot file is created successfully.
- virtual void didCreateSnapshotFile(const FileMetadata&, PassRefPtr<BlobDataHandle> snapshot) { ASSERT_NOT_REACHED(); }
-
- // Called when a directory entry is read.
- virtual void didReadDirectoryEntry(const String& name, bool isDirectory) { ASSERT_NOT_REACHED(); }
-
- // Called after a chunk of directory entries have been read (i.e. indicates it's good time to call back to the application). If hasMore is true there can be more chunks.
- virtual void didReadDirectoryEntries(bool hasMore) { ASSERT_NOT_REACHED(); }
-
- // Called when an AsyncFileWrter has been created successfully.
- virtual void didCreateFileWriter(PassOwnPtr<WebKit::WebFileWriter>, long long length) { ASSERT_NOT_REACHED(); }
-
- // Called when there was an error.
- virtual void didFail(int code) = 0;
-
- // Returns true if the caller expects that the calling thread blocks
- // until completion.
- virtual bool shouldBlockUntilCompletion() const
- {
- return m_blockUntilCompletion;
- }
-
- void setShouldBlockUntilCompletion(bool flag)
- {
- m_blockUntilCompletion = flag;
- }
-
- virtual ~AsyncFileSystemCallbacks() { }
-
-private:
- bool m_blockUntilCompletion;
-};
-
-} // namespace
-
-#endif // AsyncFileSystemCallbacks_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/CalculationValue.cpp b/chromium/third_party/WebKit/Source/core/platform/CalculationValue.cpp
deleted file mode 100644
index e45aae5fbe2..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/CalculationValue.cpp
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/CalculationValue.h"
-
-#include <limits>
-
-namespace WebCore {
-
-float CalcExpressionBinaryOperation::evaluate(float maxValue) const
-{
- float left = m_leftSide->evaluate(maxValue);
- float right = m_rightSide->evaluate(maxValue);
- switch (m_operator) {
- case CalcAdd:
- return left + right;
- case CalcSubtract:
- return left - right;
- case CalcMultiply:
- return left * right;
- case CalcDivide:
- if (!right)
- return std::numeric_limits<float>::quiet_NaN();
- return left / right;
- }
- ASSERT_NOT_REACHED();
- return std::numeric_limits<float>::quiet_NaN();
-}
-
-PassRefPtr<CalculationValue> CalculationValue::create(PassOwnPtr<CalcExpressionNode> value, CalculationPermittedValueRange range)
-{
- return adoptRef(new CalculationValue(value, range));
-}
-
-float CalculationValue::evaluate(float maxValue) const
-{
- float result = m_value->evaluate(maxValue);
- // FIXME calc https://webkit.org/b/80411 : result is NaN when there is a division
- // by zero which isn't found at parse time.
- if (std::isnan(result))
- return 0;
- return m_isNonNegative && result < 0 ? 0 : result;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/CalculationValue.h b/chromium/third_party/WebKit/Source/core/platform/CalculationValue.h
deleted file mode 100644
index 95456723f7b..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/CalculationValue.h
+++ /dev/null
@@ -1,259 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef CalculationValue_h
-#define CalculationValue_h
-
-#include "core/css/LengthFunctions.h"
-#include "core/platform/Length.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-enum CalcOperator {
- CalcAdd = '+',
- CalcSubtract = '-',
- CalcMultiply = '*',
- CalcDivide = '/'
-};
-
-enum CalculationPermittedValueRange {
- CalculationRangeAll,
- CalculationRangeNonNegative
-};
-
-enum CalcExpressionNodeType {
- CalcExpressionNodeUndefined,
- CalcExpressionNodeNumber,
- CalcExpressionNodeLength,
- CalcExpressionNodeBinaryOperation,
- CalcExpressionNodeBlendLength,
-};
-
-class CalcExpressionNode {
- WTF_MAKE_FAST_ALLOCATED;
-public:
- CalcExpressionNode()
- : m_type(CalcExpressionNodeUndefined)
- {
- }
-
- virtual ~CalcExpressionNode()
- {
- }
-
- virtual float evaluate(float maxValue) const = 0;
- virtual bool operator==(const CalcExpressionNode&) const = 0;
-
- CalcExpressionNodeType type() const { return m_type; }
-
-protected:
- CalcExpressionNodeType m_type;
-};
-
-class CalculationValue : public RefCounted<CalculationValue> {
-public:
- static PassRefPtr<CalculationValue> create(PassOwnPtr<CalcExpressionNode> value, CalculationPermittedValueRange);
- float evaluate(float maxValue) const;
-
- bool operator==(const CalculationValue& o) const
- {
- return *(m_value.get()) == *(o.m_value.get());
- }
-
- bool isNonNegative() const { return m_isNonNegative; }
- const CalcExpressionNode* expression() const { return m_value.get(); }
-
-private:
- CalculationValue(PassOwnPtr<CalcExpressionNode> value, CalculationPermittedValueRange range)
- : m_value(value)
- , m_isNonNegative(range == CalculationRangeNonNegative)
- {
- }
-
- OwnPtr<CalcExpressionNode> m_value;
- bool m_isNonNegative;
-};
-
-class CalcExpressionNumber : public CalcExpressionNode {
-public:
- explicit CalcExpressionNumber(float value)
- : m_value(value)
- {
- m_type = CalcExpressionNodeNumber;
- }
-
- bool operator==(const CalcExpressionNumber& o) const
- {
- return m_value == o.m_value;
- }
-
- virtual bool operator==(const CalcExpressionNode& o) const OVERRIDE
- {
- return type() == o.type() && *this == static_cast<const CalcExpressionNumber&>(o);
- }
-
- virtual float evaluate(float) const OVERRIDE
- {
- return m_value;
- }
-
- float value() const { return m_value; }
-
-private:
- float m_value;
-};
-
-inline const CalcExpressionNumber* toCalcExpressionNumber(const CalcExpressionNode* value)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!value || value->type() == CalcExpressionNodeNumber);
- return static_cast<const CalcExpressionNumber*>(value);
-}
-
-class CalcExpressionLength : public CalcExpressionNode {
-public:
- explicit CalcExpressionLength(Length length)
- : m_length(length)
- {
- m_type = CalcExpressionNodeLength;
- }
-
- bool operator==(const CalcExpressionLength& o) const
- {
- return m_length == o.m_length;
- }
-
- virtual bool operator==(const CalcExpressionNode& o) const OVERRIDE
- {
- return type() == o.type() && *this == static_cast<const CalcExpressionLength&>(o);
- }
-
- virtual float evaluate(float maxValue) const OVERRIDE
- {
- return floatValueForLength(m_length, maxValue);
- }
-
- const Length& length() const { return m_length; }
-
-private:
- Length m_length;
-};
-
-inline const CalcExpressionLength* toCalcExpressionLength(const CalcExpressionNode* value)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!value || value->type() == CalcExpressionNodeLength);
- return static_cast<const CalcExpressionLength*>(value);
-}
-
-class CalcExpressionBinaryOperation : public CalcExpressionNode {
-public:
- CalcExpressionBinaryOperation(PassOwnPtr<CalcExpressionNode> leftSide, PassOwnPtr<CalcExpressionNode> rightSide, CalcOperator op)
- : m_leftSide(leftSide)
- , m_rightSide(rightSide)
- , m_operator(op)
- {
- m_type = CalcExpressionNodeBinaryOperation;
- }
-
- bool operator==(const CalcExpressionBinaryOperation& o) const
- {
- return m_operator == o.m_operator && *m_leftSide == *o.m_leftSide && *m_rightSide == *o.m_rightSide;
- }
-
- virtual bool operator==(const CalcExpressionNode& o) const OVERRIDE
- {
- return type() == o.type() && *this == static_cast<const CalcExpressionBinaryOperation&>(o);
- }
-
- virtual float evaluate(float) const OVERRIDE;
-
- const CalcExpressionNode* leftSide() const { return m_leftSide.get(); }
- const CalcExpressionNode* rightSide() const { return m_rightSide.get(); }
- CalcOperator getOperator() const { return m_operator; }
-
-private:
- OwnPtr<CalcExpressionNode> m_leftSide;
- OwnPtr<CalcExpressionNode> m_rightSide;
- CalcOperator m_operator;
-};
-
-inline const CalcExpressionBinaryOperation* toCalcExpressionBinaryOperation(const CalcExpressionNode* value)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!value || value->type() == CalcExpressionNodeBinaryOperation);
- return static_cast<const CalcExpressionBinaryOperation*>(value);
-}
-
-class CalcExpressionBlendLength : public CalcExpressionNode {
-public:
- CalcExpressionBlendLength(Length from, Length to, float progress)
- : m_from(from)
- , m_to(to)
- , m_progress(progress)
- {
- m_type = CalcExpressionNodeBlendLength;
- }
-
- bool operator==(const CalcExpressionBlendLength& o) const
- {
- return m_progress == o.m_progress && m_from == o.m_from && m_to == o.m_to;
- }
-
- virtual bool operator==(const CalcExpressionNode& o) const OVERRIDE
- {
- return type() == o.type() && *this == static_cast<const CalcExpressionBlendLength&>(o);
- }
-
- virtual float evaluate(float maxValue) const OVERRIDE
- {
- return (1.0f - m_progress) * floatValueForLength(m_from, maxValue) + m_progress * floatValueForLength(m_to, maxValue);
- }
-
- const Length& from() const { return m_from; }
- const Length& to() const { return m_to; }
- float progress() const { return m_progress; }
-
-private:
- Length m_from;
- Length m_to;
- float m_progress;
-};
-
-inline const CalcExpressionBlendLength* toCalcExpressionBlendLength(const CalcExpressionNode* value)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!value || value->type() == CalcExpressionNodeBlendLength);
- return static_cast<const CalcExpressionBlendLength*>(value);
-}
-
-} // namespace WebCore
-
-#endif // CalculationValue_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/Clock.cpp b/chromium/third_party/WebKit/Source/core/platform/Clock.cpp
deleted file mode 100644
index 4d2da23cdaf..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/Clock.cpp
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
- * Copyright (C) 2011 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/Clock.h"
-
-#include "wtf/CurrentTime.h"
-
-using namespace WebCore;
-
-Clock::Clock()
- : m_running(false)
- , m_rate(1)
- , m_offset(0)
-{
- m_startTime = m_lastTime = now();
-}
-
-void Clock::setCurrentTime(double time)
-{
- m_startTime = m_lastTime = now();
- m_offset = time;
-}
-
-double Clock::currentTime() const
-{
- if (m_running)
- m_lastTime = now();
- return ((m_lastTime - m_startTime) * m_rate) + m_offset;
-}
-
-void Clock::setPlayRate(double rate)
-{
- m_offset = now();
- m_lastTime = m_startTime = now();
- m_rate = rate;
-}
-
-void Clock::start()
-{
- if (m_running)
- return;
-
- m_lastTime = m_startTime = now();
- m_running = true;
-}
-
-void Clock::stop()
-{
- if (!m_running)
- return;
-
- m_offset = now();
- m_lastTime = m_startTime = now();
- m_running = false;
-}
-
-double Clock::now() const
-{
- return WTF::currentTime();
-}
-
-PassRefPtr<Clock> Clock::create()
-{
- return adoptRef(new Clock());
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/Clock.h b/chromium/third_party/WebKit/Source/core/platform/Clock.h
deleted file mode 100644
index b298bf08d49..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/Clock.h
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Copyright (C) 2011 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef Clock_h
-#define Clock_h
-
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-
-namespace WebCore {
-
-class Clock : public RefCounted<Clock> {
-public:
- static PassRefPtr<Clock> create();
-
- void setCurrentTime(double);
- double currentTime() const;
-
- void setPlayRate(double);
- virtual double playRate() const { return m_rate; }
-
- void start();
- void stop();
- bool isRunning() const { return m_running; }
-
-private:
- Clock();
- double now() const;
-
- bool m_running;
- double m_rate;
- double m_offset;
- double m_startTime;
- mutable double m_lastTime;
-};
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/ColorChooser.h b/chromium/third_party/WebKit/Source/core/platform/ColorChooser.h
deleted file mode 100644
index b6f1a3a5691..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/ColorChooser.h
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-#ifndef ColorChooser_h
-#define ColorChooser_h
-
-namespace WebCore {
-
-class Color;
-
-class ColorChooser {
-public:
- virtual ~ColorChooser() { }
-
- virtual void setSelectedColor(const Color&) { }
- virtual void endChooser() { }
-};
-
-} // namespace WebCore
-
-#endif // ColorChooser_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/ColorChooserClient.h b/chromium/third_party/WebKit/Source/core/platform/ColorChooserClient.h
deleted file mode 100644
index ba00ba580ed..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/ColorChooserClient.h
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ColorChooserClient_h
-#define ColorChooserClient_h
-
-#include "core/platform/ColorChooser.h"
-#include "core/platform/graphics/IntRect.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-class Color;
-
-class ColorChooserClient {
-public:
- virtual ~ColorChooserClient() { }
-
- virtual void didChooseColor(const Color&) = 0;
- virtual void didEndChooser() = 0;
- virtual IntRect elementRectRelativeToRootView() const = 0;
- virtual Color currentColor() = 0;
- virtual bool shouldShowSuggestions() const = 0;
- virtual Vector<Color> suggestions() const = 0;
-};
-
-} // namespace WebCore
-
-#endif // ColorChooserClient_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/ColorData.gperf b/chromium/third_party/WebKit/Source/core/platform/ColorData.gperf
deleted file mode 100644
index cf2956a3ae4..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/ColorData.gperf
+++ /dev/null
@@ -1,175 +0,0 @@
-%{
-#include "core/platform/HashTools.h"
-#include <string.h>
-
-namespace WebCore {
-%}
-%struct-type
-struct NamedColor;
-%omit-struct-type
-%language=C++
-%readonly-tables
-%global-table
-%compare-strncmp
-%define class-name ColorDataHash
-%define lookup-function-name findColorImpl
-%define hash-function-name colordata_hash_function
-%enum
-%%
-aliceblue, 0xfff0f8ff
-antiquewhite, 0xfffaebd7
-aqua, 0xff00ffff
-aquamarine, 0xff7fffd4
-azure, 0xfff0ffff
-beige, 0xfff5f5dc
-bisque, 0xffffe4c4
-black, 0xff000000
-blanchedalmond, 0xffffebcd
-blue, 0xff0000ff
-blueviolet, 0xff8a2be2
-brown, 0xffa52a2a
-burlywood, 0xffdeb887
-cadetblue, 0xff5f9ea0
-chartreuse, 0xff7fff00
-chocolate, 0xffd2691e
-coral, 0xffff7f50
-cornflowerblue, 0xff6495ed
-cornsilk, 0xfffff8dc
-crimson, 0xffdc143c
-cyan, 0xff00ffff
-darkblue, 0xff00008b
-darkcyan, 0xff008b8b
-darkgoldenrod, 0xffb8860b
-darkgray, 0xffa9a9a9
-darkgrey, 0xffa9a9a9
-darkgreen, 0xff006400
-darkkhaki, 0xffbdb76b
-darkmagenta, 0xff8b008b
-darkolivegreen, 0xff556b2f
-darkorange, 0xffff8c00
-darkorchid, 0xff9932cc
-darkred, 0xff8b0000
-darksalmon, 0xffe9967a
-darkseagreen, 0xff8fbc8f
-darkslateblue, 0xff483d8b
-darkslategray, 0xff2f4f4f
-darkslategrey, 0xff2f4f4f
-darkturquoise, 0xff00ced1
-darkviolet, 0xff9400d3
-deeppink, 0xffff1493
-deepskyblue, 0xff00bfff
-dimgray, 0xff696969
-dimgrey, 0xff696969
-dodgerblue, 0xff1e90ff
-firebrick, 0xffb22222
-floralwhite, 0xfffffaf0
-forestgreen, 0xff228b22
-fuchsia, 0xffff00ff
-gainsboro, 0xffdcdcdc
-ghostwhite, 0xfff8f8ff
-gold, 0xffffd700
-goldenrod, 0xffdaa520
-gray, 0xff808080
-grey, 0xff808080
-green, 0xff008000
-greenyellow, 0xffadff2f
-honeydew, 0xfff0fff0
-hotpink, 0xffff69b4
-indianred, 0xffcd5c5c
-indigo, 0xff4b0082
-ivory, 0xfffffff0
-khaki, 0xfff0e68c
-lavender, 0xffe6e6fa
-lavenderblush, 0xfffff0f5
-lawngreen, 0xff7cfc00
-lemonchiffon, 0xfffffacd
-lightblue, 0xffadd8e6
-lightcoral, 0xfff08080
-lightcyan, 0xffe0ffff
-lightgoldenrodyellow, 0xfffafad2
-lightgray, 0xffd3d3d3
-lightgrey, 0xffd3d3d3
-lightgreen, 0xff90ee90
-lightpink, 0xffffb6c1
-lightsalmon, 0xffffa07a
-lightseagreen, 0xff20b2aa
-lightskyblue, 0xff87cefa
-lightslateblue, 0xff8470ff
-lightslategray, 0xff778899
-lightslategrey, 0xff778899
-lightsteelblue, 0xffb0c4de
-lightyellow, 0xffffffe0
-lime, 0xff00ff00
-limegreen, 0xff32cd32
-linen, 0xfffaf0e6
-magenta, 0xffff00ff
-maroon, 0xff800000
-mediumaquamarine, 0xff66cdaa
-mediumblue, 0xff0000cd
-mediumorchid, 0xffba55d3
-mediumpurple, 0xff9370db
-mediumseagreen, 0xff3cb371
-mediumslateblue, 0xff7b68ee
-mediumspringgreen, 0xff00fa9a
-mediumturquoise, 0xff48d1cc
-mediumvioletred, 0xffc71585
-midnightblue, 0xff191970
-mintcream, 0xfff5fffa
-mistyrose, 0xffffe4e1
-moccasin, 0xffffe4b5
-navajowhite, 0xffffdead
-navy, 0xff000080
-oldlace, 0xfffdf5e6
-olive, 0xff808000
-olivedrab, 0xff6b8e23
-orange, 0xffffa500
-orangered, 0xffff4500
-orchid, 0xffda70d6
-palegoldenrod, 0xffeee8aa
-palegreen, 0xff98fb98
-paleturquoise, 0xffafeeee
-palevioletred, 0xffdb7093
-papayawhip, 0xffffefd5
-peachpuff, 0xffffdab9
-peru, 0xffcd853f
-pink, 0xffffc0cb
-plum, 0xffdda0dd
-powderblue, 0xffb0e0e6
-purple, 0xff800080
-red, 0xffff0000
-rosybrown, 0xffbc8f8f
-royalblue, 0xff4169e1
-saddlebrown, 0xff8b4513
-salmon, 0xfffa8072
-sandybrown, 0xfff4a460
-seagreen, 0xff2e8b57
-seashell, 0xfffff5ee
-sienna, 0xffa0522d
-silver, 0xffc0c0c0
-skyblue, 0xff87ceeb
-slateblue, 0xff6a5acd
-slategray, 0xff708090
-slategrey, 0xff708090
-snow, 0xfffffafa
-springgreen, 0xff00ff7f
-steelblue, 0xff4682b4
-tan, 0xffd2b48c
-teal, 0xff008080
-thistle, 0xffd8bfd8
-tomato, 0xffff6347
-transparent, 0x00000000
-turquoise, 0xff40e0d0
-violet, 0xffee82ee
-violetred, 0xffd02090
-wheat, 0xfff5deb3
-white, 0xffffffff
-whitesmoke, 0xfff5f5f5
-yellow, 0xffffff00
-yellowgreen, 0xff9acd32
-%%
-const struct NamedColor* findColor(register const char* str, register unsigned int len)
-{
- return ColorDataHash::findColorImpl(str, len);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/ContentType.cpp b/chromium/third_party/WebKit/Source/core/platform/ContentType.cpp
deleted file mode 100644
index 7136ea538bb..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/ContentType.cpp
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- * Copyright (C) 2006, 2008 Apple Inc. All rights reserved.
- * Copyright (C) 2008 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
- * Copyright (C) 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/ContentType.h"
-
-namespace WebCore {
-
-ContentType::ContentType(const String& contentType)
- : m_type(contentType)
-{
-}
-
-String ContentType::parameter(const String& parameterName) const
-{
- String parameterValue;
- String strippedType = m_type.stripWhiteSpace();
-
- // a MIME type can have one or more "param=value" after a semi-colon, and separated from each other by semi-colons
- size_t semi = strippedType.find(';');
- if (semi != kNotFound) {
- size_t start = strippedType.find(parameterName, semi + 1, false);
- if (start != kNotFound) {
- start = strippedType.find('=', start + parameterName.length());
- if (start != kNotFound) {
- size_t quote = strippedType.find('\"', start + 1);
- size_t end = strippedType.find('\"', start + 2);
- if (quote != kNotFound && end != kNotFound)
- start = quote;
- else {
- end = strippedType.find(';', start + 1);
- if (end == kNotFound)
- end = strippedType.length();
- }
- parameterValue = strippedType.substring(start + 1, end - (start + 1)).stripWhiteSpace();
- }
- }
- }
-
- return parameterValue;
-}
-
-String ContentType::type() const
-{
- String strippedType = m_type.stripWhiteSpace();
-
- // "type" can have parameters after a semi-colon, strip them
- size_t semi = strippedType.find(';');
- if (semi != kNotFound)
- strippedType = strippedType.left(semi).stripWhiteSpace();
-
- return strippedType;
-}
-
-Vector<String> ContentType::codecs() const
-{
- String codecsParameter = parameter("codecs");
-
- if (codecsParameter.isEmpty())
- return Vector<String>();
-
- Vector<String> codecs;
- codecsParameter.split(",", codecs);
- for (size_t i = 0; i < codecs.size(); ++i)
- codecs[i] = codecs[i].simplifyWhiteSpace();
-
- return codecs;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/ContentType.h b/chromium/third_party/WebKit/Source/core/platform/ContentType.h
deleted file mode 100644
index 848cc1d04e2..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/ContentType.h
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Copyright (C) 2006 Apple Computer, Inc. All rights reserved.
- * Copyright (C) 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ContentType_h
-#define ContentType_h
-
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
- class ContentType {
- public:
- explicit ContentType(const String& type);
-
- String parameter (const String& parameterName) const;
- String type() const;
- Vector<String> codecs() const;
- const String& raw() const { return m_type; }
- private:
- String m_type;
- };
-
-} // namespace WebCore
-
-#endif // ContentType_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/ContextMenu.cpp b/chromium/third_party/WebKit/Source/core/platform/ContextMenu.cpp
deleted file mode 100644
index 746bc5a7c0a..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/ContextMenu.cpp
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Copyright (C) 2010 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/ContextMenu.h"
-
-namespace WebCore {
-
-static const ContextMenuItem* findItemWithAction(unsigned action, const Vector<ContextMenuItem>& items)
-{
- for (size_t i = 0; i < items.size(); ++i) {
- const ContextMenuItem& item = items[i];
- if (item.action() == static_cast<ContextMenuAction>(action))
- return &item;
- if (item.type() != SubmenuType)
- continue;
- if (const ContextMenuItem* subMenuItem = findItemWithAction(action, item.subMenuItems()))
- return subMenuItem;
- }
-
- return 0;
-}
-
-const ContextMenuItem* ContextMenu::itemWithAction(unsigned action) const
-{
- return findItemWithAction(action, m_items);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/ContextMenu.h b/chromium/third_party/WebKit/Source/core/platform/ContextMenu.h
deleted file mode 100644
index f2c9a913e16..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/ContextMenu.h
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Copyright (C) 2006 Apple Computer, Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ContextMenu_h
-#define ContextMenu_h
-
-#include "core/platform/ContextMenuItem.h"
-#include "wtf/Noncopyable.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
- class ContextMenu {
- WTF_MAKE_NONCOPYABLE(ContextMenu); WTF_MAKE_FAST_ALLOCATED;
- public:
- ContextMenu() { }
- const ContextMenuItem* itemWithAction(unsigned) const;
- const Vector<ContextMenuItem>& items() const { return m_items; }
- void appendItem(const ContextMenuItem& item) { m_items.append(item); }
-
- private:
- Vector<ContextMenuItem> m_items;
- };
-}
-
-#endif // ContextMenu_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/ContextMenuItem.cpp b/chromium/third_party/WebKit/Source/core/platform/ContextMenuItem.cpp
deleted file mode 100644
index 3be567be6df..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/ContextMenuItem.cpp
+++ /dev/null
@@ -1,118 +0,0 @@
-/*
- * Copyright (C) 2010 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/ContextMenuItem.h"
-
-#include "core/platform/ContextMenu.h"
-
-namespace WebCore {
-
-ContextMenuItem::ContextMenuItem(ContextMenuItemType type, ContextMenuAction action, const String& title, ContextMenu* subMenu)
- : m_type(type)
- , m_action(action)
- , m_title(title)
- , m_enabled(true)
- , m_checked(false)
-{
- if (subMenu)
- setSubMenu(subMenu);
-}
-
-ContextMenuItem::ContextMenuItem(ContextMenuItemType type, ContextMenuAction action, const String& title, bool enabled, bool checked)
- : m_type(type)
- , m_action(action)
- , m_title(title)
- , m_enabled(enabled)
- , m_checked(checked)
-{
-}
-
-ContextMenuItem::ContextMenuItem(ContextMenuAction action, const String& title, bool enabled, bool checked, const Vector<ContextMenuItem>& subMenuItems)
- : m_type(SubmenuType)
- , m_action(action)
- , m_title(title)
- , m_enabled(enabled)
- , m_checked(checked)
- , m_subMenuItems(subMenuItems)
-{
-}
-
-ContextMenuItem::~ContextMenuItem()
-{
-}
-
-void ContextMenuItem::setSubMenu(ContextMenu* subMenu)
-{
- if (subMenu) {
- m_type = SubmenuType;
- m_subMenuItems = subMenu->items();
- } else {
- m_type = ActionType;
- m_subMenuItems.clear();
- }
-}
-
-void ContextMenuItem::setType(ContextMenuItemType type)
-{
- m_type = type;
-}
-
-ContextMenuItemType ContextMenuItem::type() const
-{
- return m_type;
-}
-
-void ContextMenuItem::setAction(ContextMenuAction action)
-{
- m_action = action;
-}
-
-ContextMenuAction ContextMenuItem::action() const
-{
- return m_action;
-}
-
-void ContextMenuItem::setChecked(bool checked)
-{
- m_checked = checked;
-}
-
-bool ContextMenuItem::checked() const
-{
- return m_checked;
-}
-
-void ContextMenuItem::setEnabled(bool enabled)
-{
- m_enabled = enabled;
-}
-
-bool ContextMenuItem::enabled() const
-{
- return m_enabled;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/ContextMenuItem.h b/chromium/third_party/WebKit/Source/core/platform/ContextMenuItem.h
deleted file mode 100644
index 67cc7c4e61b..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/ContextMenuItem.h
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
- * Copyright (C) 2006 Apple Computer, Inc. All rights reserved.
- * Copyright (C) 2010 Igalia S.L
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ContextMenuItem_h
-#define ContextMenuItem_h
-
-#include "wtf/OwnPtr.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
- class ContextMenu;
-
- enum ContextMenuAction {
- ContextMenuItemBaseCustomTag = 5000,
- ContextMenuItemCustomTagNoAction = 5998,
- ContextMenuItemLastCustomTag = 5999
- };
-
- enum ContextMenuItemType {
- ActionType,
- CheckableActionType,
- SeparatorType,
- SubmenuType
- };
-
- class ContextMenuItem {
- WTF_MAKE_FAST_ALLOCATED;
- public:
- ContextMenuItem(ContextMenuItemType, ContextMenuAction, const String&, ContextMenu* subMenu = 0);
- ContextMenuItem(ContextMenuItemType, ContextMenuAction, const String&, bool enabled, bool checked);
-
- ~ContextMenuItem();
-
- void setType(ContextMenuItemType);
- ContextMenuItemType type() const;
-
- void setAction(ContextMenuAction);
- ContextMenuAction action() const;
-
- void setChecked(bool = true);
- bool checked() const;
-
- void setEnabled(bool = true);
- bool enabled() const;
-
- void setSubMenu(ContextMenu*);
-
- ContextMenuItem(ContextMenuAction, const String&, bool enabled, bool checked, const Vector<ContextMenuItem>& subMenuItems);
-
- void setTitle(const String& title) { m_title = title; }
- const String& title() const { return m_title; }
-
- const Vector<ContextMenuItem>& subMenuItems() const { return m_subMenuItems; }
- private:
- ContextMenuItemType m_type;
- ContextMenuAction m_action;
- String m_title;
- bool m_enabled;
- bool m_checked;
- Vector<ContextMenuItem> m_subMenuItems;
- };
-}
-
-#endif // ContextMenuItem_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/Cookie.h b/chromium/third_party/WebKit/Source/core/platform/Cookie.h
deleted file mode 100644
index 287a990f62e..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/Cookie.h
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * Copyright (C) 2009 Joseph Pecoraro. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef Cookie_h
-#define Cookie_h
-
-#include "wtf/text/StringHash.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
- // This struct is currently only used to provide more cookies information
- // to the Web Inspector.
-
- struct Cookie {
- Cookie() { }
-
- Cookie(const String& name, const String& value, const String& domain,
- const String& path, double expires, bool httpOnly, bool secure,
- bool session)
- : name(name)
- , value(value)
- , domain(domain)
- , path(path)
- , expires(expires)
- , httpOnly(httpOnly)
- , secure(secure)
- , session(session)
- {
- }
-
- String name;
- String value;
- String domain;
- String path;
- double expires;
- bool httpOnly;
- bool secure;
- bool session;
- };
-
- struct CookieHash {
- static unsigned hash(Cookie key)
- {
- return StringHash::hash(key.name) + StringHash::hash(key.domain) + StringHash::hash(key.path) + key.secure;
- }
-
- static bool equal(Cookie a, Cookie b)
- {
- return a.name == b.name && a.domain == b.domain && a.path == b.path && a.secure == b.secure;
- }
- };
-}
-
-namespace WTF {
- template<typename T> struct DefaultHash;
- template<> struct DefaultHash<WebCore::Cookie> {
- typedef WebCore::CookieHash Hash;
- };
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/CrossThreadCopier.cpp b/chromium/third_party/WebKit/Source/core/platform/CrossThreadCopier.cpp
deleted file mode 100644
index ceb9bba46f5..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/CrossThreadCopier.cpp
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
- * Copyright (C) 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/platform/CrossThreadCopier.h"
-
-#include "core/platform/network/ResourceError.h"
-#include "core/platform/network/ResourceRequest.h"
-#include "core/platform/network/ResourceResponse.h"
-#include "weborigin/KURL.h"
-#include "wtf/Assertions.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-CrossThreadCopierBase<false, false, KURL>::Type CrossThreadCopierBase<false, false, KURL>::copy(const KURL& url)
-{
- return url.copy();
-}
-
-CrossThreadCopierBase<false, false, String>::Type CrossThreadCopierBase<false, false, String>::copy(const String& str)
-{
- return str.isolatedCopy();
-}
-
-CrossThreadCopierBase<false, false, ResourceError>::Type CrossThreadCopierBase<false, false, ResourceError>::copy(const ResourceError& error)
-{
- return error.copy();
-}
-
-CrossThreadCopierBase<false, false, ResourceRequest>::Type CrossThreadCopierBase<false, false, ResourceRequest>::copy(const ResourceRequest& request)
-{
- return request.copyData();
-}
-
-CrossThreadCopierBase<false, false, ResourceResponse>::Type CrossThreadCopierBase<false, false, ResourceResponse>::copy(const ResourceResponse& response)
-{
- return response.copyData();
-}
-
-// Test CrossThreadCopier using COMPILE_ASSERT.
-
-// Verify that ThreadSafeRefCounted objects get handled correctly.
-class CopierThreadSafeRefCountedTest : public ThreadSafeRefCounted<CopierThreadSafeRefCountedTest> {
-};
-
-COMPILE_ASSERT((WTF::IsSameType<
- PassRefPtr<CopierThreadSafeRefCountedTest>,
- CrossThreadCopier<PassRefPtr<CopierThreadSafeRefCountedTest> >::Type
- >::value),
- PassRefPtrTest);
-COMPILE_ASSERT((WTF::IsSameType<
- PassRefPtr<CopierThreadSafeRefCountedTest>,
- CrossThreadCopier<RefPtr<CopierThreadSafeRefCountedTest> >::Type
- >::value),
- RefPtrTest);
-COMPILE_ASSERT((WTF::IsSameType<
- PassRefPtr<CopierThreadSafeRefCountedTest>,
- CrossThreadCopier<CopierThreadSafeRefCountedTest*>::Type
- >::value),
- RawPointerTest);
-
-
-// Add a generic specialization which will let's us verify that no other template matches.
-template<typename T> struct CrossThreadCopierBase<false, false, T> {
- typedef int Type;
-};
-
-// Verify that RefCounted objects only match our generic template which exposes Type as int.
-class CopierRefCountedTest : public RefCounted<CopierRefCountedTest> {
-};
-
-COMPILE_ASSERT((WTF::IsSameType<
- int,
- CrossThreadCopier<PassRefPtr<CopierRefCountedTest> >::Type
- >::value),
- PassRefPtrRefCountedTest);
-
-COMPILE_ASSERT((WTF::IsSameType<
- int,
- CrossThreadCopier<RefPtr<CopierRefCountedTest> >::Type
- >::value),
- RefPtrRefCountedTest);
-
-COMPILE_ASSERT((WTF::IsSameType<
- int,
- CrossThreadCopier<CopierRefCountedTest*>::Type
- >::value),
- RawPointerRefCountedTest);
-
-// Verify that PassOwnPtr gets passed through.
-COMPILE_ASSERT((WTF::IsSameType<
- PassOwnPtr<float>,
- CrossThreadCopier<PassOwnPtr<float> >::Type
- >::value),
- PassOwnPtrTest);
-
-// Verify that PassOwnPtr does not get passed through.
-COMPILE_ASSERT((WTF::IsSameType<
- int,
- CrossThreadCopier<OwnPtr<float> >::Type
- >::value),
- OwnPtrTest);
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/CrossThreadCopier.h b/chromium/third_party/WebKit/Source/core/platform/CrossThreadCopier.h
deleted file mode 100644
index 8e8220b728e..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/CrossThreadCopier.h
+++ /dev/null
@@ -1,179 +0,0 @@
-/*
- * Copyright (C) 2009, 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef CrossThreadCopier_h
-#define CrossThreadCopier_h
-
-#include "wtf/Assertions.h"
-#include "wtf/Forward.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefPtr.h"
-#include "wtf/ThreadSafeRefCounted.h"
-#include "wtf/TypeTraits.h"
-
-namespace WebCore {
-
- class IntRect;
- class IntSize;
- class KURL;
- class ResourceError;
- class ResourceRequest;
- class ResourceResponse;
- struct CrossThreadResourceResponseData;
- struct CrossThreadResourceRequestData;
- struct ThreadableLoaderOptions;
-
- template<typename T> struct CrossThreadCopierPassThrough {
- typedef T Type;
- static Type copy(const T& parameter)
- {
- return parameter;
- }
- };
-
- template<bool isConvertibleToInteger, bool isThreadSafeRefCounted, typename T> struct CrossThreadCopierBase;
-
- // Integers get passed through without any changes.
- template<typename T> struct CrossThreadCopierBase<true, false, T> : public CrossThreadCopierPassThrough<T> {
- };
-
- // To allow a type to be passed across threads using its copy constructor, add a forward declaration of the type and
- // a CopyThreadCopierBase<false, false, TypeName> : public CrossThreadCopierPassThrough<TypeName> { }; to this file.
- template<> struct CrossThreadCopierBase<false, false, ThreadableLoaderOptions> : public CrossThreadCopierPassThrough<ThreadableLoaderOptions> {
- };
-
- template<> struct CrossThreadCopierBase<false, false, IntRect> : public CrossThreadCopierPassThrough<IntRect> {
- };
-
- template<> struct CrossThreadCopierBase<false, false, IntSize> : public CrossThreadCopierPassThrough<IntSize> {
- };
-
- // Custom copy methods.
- template<typename T> struct CrossThreadCopierBase<false, true, T> {
- typedef typename WTF::RemoveTemplate<T, RefPtr>::Type TypeWithoutRefPtr;
- typedef typename WTF::RemoveTemplate<TypeWithoutRefPtr, PassRefPtr>::Type TypeWithoutPassRefPtr;
- typedef typename WTF::RemovePointer<TypeWithoutPassRefPtr>::Type RefCountedType;
-
- // Verify that only one of the above did a change.
- COMPILE_ASSERT((WTF::IsSameType<RefPtr<RefCountedType>, T>::value
- || WTF::IsSameType<PassRefPtr<RefCountedType>, T>::value
- || WTF::IsSameType<RefCountedType*, T>::value),
- OnlyAllowOneTypeModification);
-
- typedef PassRefPtr<RefCountedType> Type;
- static Type copy(const T& refPtr)
- {
- return refPtr;
- }
- };
-
- template<typename T> struct CrossThreadCopierBase<false, false, PassOwnPtr<T> > {
- typedef PassOwnPtr<T> Type;
- static Type copy(Type ownPtr)
- {
- return ownPtr;
- }
- };
-
- template<> struct CrossThreadCopierBase<false, false, KURL> {
- typedef KURL Type;
- static Type copy(const KURL&);
- };
-
- template<> struct CrossThreadCopierBase<false, false, String> {
- typedef String Type;
- static Type copy(const String&);
- };
-
- template<> struct CrossThreadCopierBase<false, false, ResourceError> {
- typedef ResourceError Type;
- static Type copy(const ResourceError&);
- };
-
- template<> struct CrossThreadCopierBase<false, false, ResourceRequest> {
- typedef PassOwnPtr<CrossThreadResourceRequestData> Type;
- static Type copy(const ResourceRequest&);
- };
-
- template<> struct CrossThreadCopierBase<false, false, ResourceResponse> {
- typedef PassOwnPtr<CrossThreadResourceResponseData> Type;
- static Type copy(const ResourceResponse&);
- };
-
- template<typename T> struct CrossThreadCopier : public CrossThreadCopierBase<WTF::IsConvertibleToInteger<T>::value,
- WTF::IsSubclassOfTemplate<typename WTF::RemoveTemplate<T, RefPtr>::Type, ThreadSafeRefCounted>::value
- || WTF::IsSubclassOfTemplate<typename WTF::RemovePointer<T>::Type, ThreadSafeRefCounted>::value
- || WTF::IsSubclassOfTemplate<typename WTF::RemoveTemplate<T, PassRefPtr>::Type, ThreadSafeRefCounted>::value,
- T> {
- };
-
- template<typename T> struct AllowCrossThreadAccessWrapper {
- public:
- explicit AllowCrossThreadAccessWrapper(T* value) : m_value(value) { }
- T* value() const { return m_value; }
- private:
- T* m_value;
- };
-
- template<typename T> struct CrossThreadCopierBase<false, false, AllowCrossThreadAccessWrapper<T> > {
- typedef T* Type;
- static Type copy(const AllowCrossThreadAccessWrapper<T>& wrapper) { return wrapper.value(); }
- };
-
- template<typename T> AllowCrossThreadAccessWrapper<T> AllowCrossThreadAccess(T* value)
- {
- return AllowCrossThreadAccessWrapper<T>(value);
- }
-
- // FIXME: Move to a different header file. AllowAccessLater is for cross-thread access
- // that is not cross-thread (tasks posted to a queue guaranteed to run on the same thread).
- template<typename T> struct AllowAccessLaterWrapper {
- public:
- explicit AllowAccessLaterWrapper(T* value) : m_value(value) { }
- T* value() const { return m_value; }
- private:
- T* m_value;
- };
-
- template<typename T> struct CrossThreadCopierBase<false, false, AllowAccessLaterWrapper<T> > {
- typedef T* Type;
- static Type copy(const AllowAccessLaterWrapper<T>& wrapper) { return wrapper.value(); }
- };
-
- template<typename T> AllowAccessLaterWrapper<T> AllowAccessLater(T* value)
- {
- return AllowAccessLaterWrapper<T>(value);
- }
-
-
-} // namespace WebCore
-
-#endif // CrossThreadCopier_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/CryptoResult.h b/chromium/third_party/WebKit/Source/core/platform/CryptoResult.h
new file mode 100644
index 00000000000..45aaef5945b
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/platform/CryptoResult.h
@@ -0,0 +1,58 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef CryptoResult_h
+#define CryptoResult_h
+
+#include "public/platform/WebCrypto.h"
+#include "wtf/ThreadSafeRefCounted.h"
+
+namespace WebCore {
+
+// Receives notification of completion of the crypto operation.
+class CryptoResult : public ThreadSafeRefCounted<CryptoResult> {
+public:
+ virtual ~CryptoResult() { }
+
+ virtual void completeWithError() = 0;
+ virtual void completeWithBuffer(const blink::WebArrayBuffer&) = 0;
+ virtual void completeWithBoolean(bool) = 0;
+ virtual void completeWithKey(const blink::WebCryptoKey&) = 0;
+ virtual void completeWithKeyPair(const blink::WebCryptoKey& publicKey, const blink::WebCryptoKey& privateKey) = 0;
+
+ blink::WebCryptoResult result()
+ {
+ return blink::WebCryptoResult(this);
+ }
+};
+
+} // namespace WebCore
+
+#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/Cursor.cpp b/chromium/third_party/WebKit/Source/core/platform/Cursor.cpp
deleted file mode 100644
index 4ad73b96aa1..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/Cursor.cpp
+++ /dev/null
@@ -1,446 +0,0 @@
-/*
- * Copyright (C) 2010 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/Cursor.h"
-
-namespace WebCore {
-
-IntPoint determineHotSpot(Image* image, const IntPoint& specifiedHotSpot)
-{
- if (image->isNull())
- return IntPoint();
-
- // Hot spot must be inside cursor rectangle.
- IntRect imageRect = image->rect();
- if (imageRect.contains(specifiedHotSpot))
- return specifiedHotSpot;
-
- // If hot spot is not specified externally, it can be extracted from some image formats (e.g. .cur).
- IntPoint intrinsicHotSpot;
- bool imageHasIntrinsicHotSpot = image->getHotSpot(intrinsicHotSpot);
- if (imageHasIntrinsicHotSpot && imageRect.contains(intrinsicHotSpot))
- return intrinsicHotSpot;
-
- return IntPoint();
-}
-
-const Cursor& Cursor::fromType(Cursor::Type type)
-{
- switch (type) {
- case Cursor::Pointer:
- return pointerCursor();
- case Cursor::Cross:
- return crossCursor();
- case Cursor::Hand:
- return handCursor();
- case Cursor::IBeam:
- return iBeamCursor();
- case Cursor::Wait:
- return waitCursor();
- case Cursor::Help:
- return helpCursor();
- case Cursor::EastResize:
- return eastResizeCursor();
- case Cursor::NorthResize:
- return northResizeCursor();
- case Cursor::NorthEastResize:
- return northEastResizeCursor();
- case Cursor::NorthWestResize:
- return northWestResizeCursor();
- case Cursor::SouthResize:
- return southResizeCursor();
- case Cursor::SouthEastResize:
- return southEastResizeCursor();
- case Cursor::SouthWestResize:
- return southWestResizeCursor();
- case Cursor::WestResize:
- return westResizeCursor();
- case Cursor::NorthSouthResize:
- return northSouthResizeCursor();
- case Cursor::EastWestResize:
- return eastWestResizeCursor();
- case Cursor::NorthEastSouthWestResize:
- return northEastSouthWestResizeCursor();
- case Cursor::NorthWestSouthEastResize:
- return northWestSouthEastResizeCursor();
- case Cursor::ColumnResize:
- return columnResizeCursor();
- case Cursor::RowResize:
- return rowResizeCursor();
- case Cursor::MiddlePanning:
- return middlePanningCursor();
- case Cursor::EastPanning:
- return eastPanningCursor();
- case Cursor::NorthPanning:
- return northPanningCursor();
- case Cursor::NorthEastPanning:
- return northEastPanningCursor();
- case Cursor::NorthWestPanning:
- return northWestPanningCursor();
- case Cursor::SouthPanning:
- return southPanningCursor();
- case Cursor::SouthEastPanning:
- return southEastPanningCursor();
- case Cursor::SouthWestPanning:
- return southWestPanningCursor();
- case Cursor::WestPanning:
- return westPanningCursor();
- case Cursor::Move:
- return moveCursor();
- case Cursor::VerticalText:
- return verticalTextCursor();
- case Cursor::Cell:
- return cellCursor();
- case Cursor::ContextMenu:
- return contextMenuCursor();
- case Cursor::Alias:
- return aliasCursor();
- case Cursor::Progress:
- return progressCursor();
- case Cursor::NoDrop:
- return noDropCursor();
- case Cursor::Copy:
- return copyCursor();
- case Cursor::None:
- return noneCursor();
- case Cursor::NotAllowed:
- return notAllowedCursor();
- case Cursor::ZoomIn:
- return zoomInCursor();
- case Cursor::ZoomOut:
- return zoomOutCursor();
- case Cursor::Grab:
- return grabCursor();
- case Cursor::Grabbing:
- return grabbingCursor();
- case Cursor::Custom:
- ASSERT_NOT_REACHED();
- }
- return pointerCursor();
-}
-
-Cursor::Cursor(Image* image, const IntPoint& hotSpot)
- : m_type(Custom)
- , m_image(image)
- , m_hotSpot(determineHotSpot(image, hotSpot))
- , m_imageScaleFactor(1)
-{
-}
-
-Cursor::Cursor(Image* image, const IntPoint& hotSpot, float scale)
- : m_type(Custom)
- , m_image(image)
- , m_hotSpot(determineHotSpot(image, hotSpot))
- , m_imageScaleFactor(scale)
-{
-}
-
-Cursor::Cursor(Type type)
- : m_type(type)
- , m_imageScaleFactor(1)
-{
-}
-
-Cursor::Cursor(const Cursor& other)
- : m_type(other.m_type)
- , m_image(other.m_image)
- , m_hotSpot(other.m_hotSpot)
- , m_imageScaleFactor(other.m_imageScaleFactor)
-{
-}
-
-Cursor& Cursor::operator=(const Cursor& other)
-{
- m_type = other.m_type;
- m_image = other.m_image;
- m_hotSpot = other.m_hotSpot;
- m_imageScaleFactor = other.m_imageScaleFactor;
- return *this;
-}
-
-Cursor::~Cursor()
-{
-}
-
-const Cursor& pointerCursor()
-{
- DEFINE_STATIC_LOCAL(Cursor, c, (Cursor::Pointer));
- return c;
-}
-
-const Cursor& crossCursor()
-{
- DEFINE_STATIC_LOCAL(Cursor, c, (Cursor::Cross));
- return c;
-}
-
-const Cursor& handCursor()
-{
- DEFINE_STATIC_LOCAL(Cursor, c, (Cursor::Hand));
- return c;
-}
-
-const Cursor& moveCursor()
-{
- DEFINE_STATIC_LOCAL(Cursor, c, (Cursor::Move));
- return c;
-}
-
-const Cursor& verticalTextCursor()
-{
- DEFINE_STATIC_LOCAL(Cursor, c, (Cursor::VerticalText));
- return c;
-}
-
-const Cursor& cellCursor()
-{
- DEFINE_STATIC_LOCAL(Cursor, c, (Cursor::Cell));
- return c;
-}
-
-const Cursor& contextMenuCursor()
-{
- DEFINE_STATIC_LOCAL(Cursor, c, (Cursor::ContextMenu));
- return c;
-}
-
-const Cursor& aliasCursor()
-{
- DEFINE_STATIC_LOCAL(Cursor, c, (Cursor::Alias));
- return c;
-}
-
-const Cursor& zoomInCursor()
-{
- DEFINE_STATIC_LOCAL(Cursor, c, (Cursor::ZoomIn));
- return c;
-}
-
-const Cursor& zoomOutCursor()
-{
- DEFINE_STATIC_LOCAL(Cursor, c, (Cursor::ZoomOut));
- return c;
-}
-
-const Cursor& copyCursor()
-{
- DEFINE_STATIC_LOCAL(Cursor, c, (Cursor::Copy));
- return c;
-}
-
-const Cursor& noneCursor()
-{
- DEFINE_STATIC_LOCAL(Cursor, c, (Cursor::None));
- return c;
-}
-
-const Cursor& progressCursor()
-{
- DEFINE_STATIC_LOCAL(Cursor, c, (Cursor::Progress));
- return c;
-}
-
-const Cursor& noDropCursor()
-{
- DEFINE_STATIC_LOCAL(Cursor, c, (Cursor::NoDrop));
- return c;
-}
-
-const Cursor& notAllowedCursor()
-{
- DEFINE_STATIC_LOCAL(Cursor, c, (Cursor::NotAllowed));
- return c;
-}
-
-const Cursor& iBeamCursor()
-{
- DEFINE_STATIC_LOCAL(Cursor, c, (Cursor::IBeam));
- return c;
-}
-
-const Cursor& waitCursor()
-{
- DEFINE_STATIC_LOCAL(Cursor, c, (Cursor::Wait));
- return c;
-}
-
-const Cursor& helpCursor()
-{
- DEFINE_STATIC_LOCAL(Cursor, c, (Cursor::Help));
- return c;
-}
-
-const Cursor& eastResizeCursor()
-{
- DEFINE_STATIC_LOCAL(Cursor, c, (Cursor::EastResize));
- return c;
-}
-
-const Cursor& northResizeCursor()
-{
- DEFINE_STATIC_LOCAL(Cursor, c, (Cursor::NorthResize));
- return c;
-}
-
-const Cursor& northEastResizeCursor()
-{
- DEFINE_STATIC_LOCAL(Cursor, c, (Cursor::NorthEastResize));
- return c;
-}
-
-const Cursor& northWestResizeCursor()
-{
- DEFINE_STATIC_LOCAL(Cursor, c, (Cursor::NorthWestResize));
- return c;
-}
-
-const Cursor& southResizeCursor()
-{
- DEFINE_STATIC_LOCAL(Cursor, c, (Cursor::SouthResize));
- return c;
-}
-
-const Cursor& southEastResizeCursor()
-{
- DEFINE_STATIC_LOCAL(Cursor, c, (Cursor::SouthEastResize));
- return c;
-}
-
-const Cursor& southWestResizeCursor()
-{
- DEFINE_STATIC_LOCAL(Cursor, c, (Cursor::SouthWestResize));
- return c;
-}
-
-const Cursor& westResizeCursor()
-{
- DEFINE_STATIC_LOCAL(Cursor, c, (Cursor::WestResize));
- return c;
-}
-
-const Cursor& northSouthResizeCursor()
-{
- DEFINE_STATIC_LOCAL(Cursor, c, (Cursor::NorthSouthResize));
- return c;
-}
-
-const Cursor& eastWestResizeCursor()
-{
- DEFINE_STATIC_LOCAL(Cursor, c, (Cursor::EastWestResize));
- return c;
-}
-
-const Cursor& northEastSouthWestResizeCursor()
-{
- DEFINE_STATIC_LOCAL(Cursor, c, (Cursor::NorthEastSouthWestResize));
- return c;
-}
-
-const Cursor& northWestSouthEastResizeCursor()
-{
- DEFINE_STATIC_LOCAL(Cursor, c, (Cursor::NorthWestSouthEastResize));
- return c;
-}
-
-const Cursor& columnResizeCursor()
-{
- DEFINE_STATIC_LOCAL(Cursor, c, (Cursor::ColumnResize));
- return c;
-}
-
-const Cursor& rowResizeCursor()
-{
- DEFINE_STATIC_LOCAL(Cursor, c, (Cursor::RowResize));
- return c;
-}
-
-const Cursor& middlePanningCursor()
-{
- DEFINE_STATIC_LOCAL(Cursor, c, (Cursor::MiddlePanning));
- return c;
-}
-
-const Cursor& eastPanningCursor()
-{
- DEFINE_STATIC_LOCAL(Cursor, c, (Cursor::EastPanning));
- return c;
-}
-
-const Cursor& northPanningCursor()
-{
- DEFINE_STATIC_LOCAL(Cursor, c, (Cursor::NorthPanning));
- return c;
-}
-
-const Cursor& northEastPanningCursor()
-{
- DEFINE_STATIC_LOCAL(Cursor, c, (Cursor::NorthEastPanning));
- return c;
-}
-
-const Cursor& northWestPanningCursor()
-{
- DEFINE_STATIC_LOCAL(Cursor, c, (Cursor::NorthWestPanning));
- return c;
-}
-
-const Cursor& southPanningCursor()
-{
- DEFINE_STATIC_LOCAL(Cursor, c, (Cursor::SouthPanning));
- return c;
-}
-
-const Cursor& southEastPanningCursor()
-{
- DEFINE_STATIC_LOCAL(Cursor, c, (Cursor::SouthEastPanning));
- return c;
-}
-
-const Cursor& southWestPanningCursor()
-{
- DEFINE_STATIC_LOCAL(Cursor, c, (Cursor::SouthWestPanning));
- return c;
-}
-
-const Cursor& westPanningCursor()
-{
- DEFINE_STATIC_LOCAL(Cursor, c, (Cursor::WestPanning));
- return c;
-}
-
-const Cursor& grabCursor()
-{
- DEFINE_STATIC_LOCAL(Cursor, c, (Cursor::Grab));
- return c;
-}
-
-const Cursor& grabbingCursor()
-{
- DEFINE_STATIC_LOCAL(Cursor, c, (Cursor::Grabbing));
- return c;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/Cursor.h b/chromium/third_party/WebKit/Source/core/platform/Cursor.h
deleted file mode 100644
index a124ccb97ac..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/Cursor.h
+++ /dev/null
@@ -1,169 +0,0 @@
-/*
- * Copyright (C) 2004, 2006, 2008 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef Cursor_h
-#define Cursor_h
-
-#include "core/platform/graphics/Image.h"
-#include "core/platform/graphics/IntPoint.h"
-#include "wtf/Assertions.h"
-#include "wtf/RefPtr.h"
-
-namespace WebCore {
-
-class Cursor {
- WTF_MAKE_FAST_ALLOCATED;
-public:
- enum Type {
- Pointer = 0,
- Cross,
- Hand,
- IBeam,
- Wait,
- Help,
- EastResize,
- NorthResize,
- NorthEastResize,
- NorthWestResize,
- SouthResize,
- SouthEastResize,
- SouthWestResize,
- WestResize,
- NorthSouthResize,
- EastWestResize,
- NorthEastSouthWestResize,
- NorthWestSouthEastResize,
- ColumnResize,
- RowResize,
- MiddlePanning,
- EastPanning,
- NorthPanning,
- NorthEastPanning,
- NorthWestPanning,
- SouthPanning,
- SouthEastPanning,
- SouthWestPanning,
- WestPanning,
- Move,
- VerticalText,
- Cell,
- ContextMenu,
- Alias,
- Progress,
- NoDrop,
- Copy,
- None,
- NotAllowed,
- ZoomIn,
- ZoomOut,
- Grab,
- Grabbing,
- Custom
- };
-
- static const Cursor& fromType(Cursor::Type);
-
- Cursor()
- // This is an invalid Cursor and should never actually get used.
- : m_type(static_cast<Type>(-1))
- {
- }
-
- Cursor(Image*, const IntPoint& hotSpot);
-
- // Hot spot is in image pixels.
- Cursor(Image*, const IntPoint& hotSpot, float imageScaleFactor);
-
- Cursor(const Cursor&);
- ~Cursor();
- Cursor& operator=(const Cursor&);
-
- explicit Cursor(Type);
- Type type() const
- {
- ASSERT(m_type >= 0 && m_type <= Custom);
- return m_type;
- }
- Image* image() const { return m_image.get(); }
- const IntPoint& hotSpot() const { return m_hotSpot; }
- // Image scale in image pixels per logical (UI) pixel.
- float imageScaleFactor() const { return m_imageScaleFactor; }
-
-private:
- Type m_type;
- RefPtr<Image> m_image;
- IntPoint m_hotSpot;
- float m_imageScaleFactor;
-};
-
-IntPoint determineHotSpot(Image*, const IntPoint& specifiedHotSpot);
-
-const Cursor& pointerCursor();
-const Cursor& crossCursor();
-const Cursor& handCursor();
-const Cursor& moveCursor();
-const Cursor& iBeamCursor();
-const Cursor& waitCursor();
-const Cursor& helpCursor();
-const Cursor& eastResizeCursor();
-const Cursor& northResizeCursor();
-const Cursor& northEastResizeCursor();
-const Cursor& northWestResizeCursor();
-const Cursor& southResizeCursor();
-const Cursor& southEastResizeCursor();
-const Cursor& southWestResizeCursor();
-const Cursor& westResizeCursor();
-const Cursor& northSouthResizeCursor();
-const Cursor& eastWestResizeCursor();
-const Cursor& northEastSouthWestResizeCursor();
-const Cursor& northWestSouthEastResizeCursor();
-const Cursor& columnResizeCursor();
-const Cursor& rowResizeCursor();
-const Cursor& middlePanningCursor();
-const Cursor& eastPanningCursor();
-const Cursor& northPanningCursor();
-const Cursor& northEastPanningCursor();
-const Cursor& northWestPanningCursor();
-const Cursor& southPanningCursor();
-const Cursor& southEastPanningCursor();
-const Cursor& southWestPanningCursor();
-const Cursor& westPanningCursor();
-const Cursor& verticalTextCursor();
-const Cursor& cellCursor();
-const Cursor& contextMenuCursor();
-const Cursor& noDropCursor();
-const Cursor& notAllowedCursor();
-const Cursor& progressCursor();
-const Cursor& aliasCursor();
-const Cursor& zoomInCursor();
-const Cursor& zoomOutCursor();
-const Cursor& copyCursor();
-const Cursor& noneCursor();
-const Cursor& grabCursor();
-const Cursor& grabbingCursor();
-
-} // namespace WebCore
-
-#endif // Cursor_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/DEPS b/chromium/third_party/WebKit/Source/core/platform/DEPS
index cfd697d11ac..8f464900d63 100644
--- a/chromium/third_party/WebKit/Source/core/platform/DEPS
+++ b/chromium/third_party/WebKit/Source/core/platform/DEPS
@@ -7,18 +7,9 @@ include_rules = [
"+dl",
"+skia",
"+third_party",
- "+webp",
# platform/ shouldn't depends on core/ but unfortunately does (crbug.com/258901).
# Please don't add anything to this list of exceptions.
- "!core/accessibility",
- "!core/css",
"!core/dom",
- "!core/editing",
"!core/fileapi",
- "!core/html",
- "!core/inspector",
- "!core/fetch",
- "!core/page",
- "!core/plugins",
"!core/rendering",
]
diff --git a/chromium/third_party/WebKit/Source/core/platform/DateComponents.cpp b/chromium/third_party/WebKit/Source/core/platform/DateComponents.cpp
deleted file mode 100644
index 3e0790649d5..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/DateComponents.cpp
+++ /dev/null
@@ -1,723 +0,0 @@
-/*
- * Copyright (C) 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/DateComponents.h"
-
-#include <limits.h>
-#include "wtf/ASCIICType.h"
-#include "wtf/DateMath.h"
-#include "wtf/MathExtras.h"
-#include "wtf/text/WTFString.h"
-
-using namespace std;
-
-namespace WebCore {
-
-// HTML5 specification defines minimum week of year is one.
-const int DateComponents::minimumWeekNumber = 1;
-
-// HTML5 specification defines maximum week of year is 53.
-const int DateComponents::maximumWeekNumber = 53;
-
-static const int maximumMonthInMaximumYear = 8; // This is September, since months are 0 based.
-static const int maximumDayInMaximumMonth = 13;
-static const int maximumWeekInMaximumYear = 37; // The week of 275760-09-13
-
-static const int daysInMonth[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
-
-static bool isLeapYear(int year)
-{
- if (year % 4)
- return false;
- if (!(year % 400))
- return true;
- if (!(year % 100))
- return false;
- return true;
-}
-
-// 'month' is 0-based.
-static int maxDayOfMonth(int year, int month)
-{
- if (month != 1) // February?
- return daysInMonth[month];
- return isLeapYear(year) ? 29 : 28;
-}
-
-// 'month' is 0-based.
-static int dayOfWeek(int year, int month, int day)
-{
- int shiftedMonth = month + 2;
- // 2:January, 3:Feburuary, 4:March, ...
-
- // Zeller's congruence
- if (shiftedMonth <= 3) {
- shiftedMonth += 12;
- year--;
- }
- // 4:March, ..., 14:January, 15:February
-
- int highYear = year / 100;
- int lowYear = year % 100;
- // We add 6 to make the result Sunday-origin.
- int result = (day + 13 * shiftedMonth / 5 + lowYear + lowYear / 4 + highYear / 4 + 5 * highYear + 6) % 7;
- return result;
-}
-
-int DateComponents::maxWeekNumberInYear() const
-{
- int day = dayOfWeek(m_year, 0, 1); // January 1.
- return day == Thursday || (day == Wednesday && isLeapYear(m_year)) ? maximumWeekNumber : maximumWeekNumber - 1;
-}
-
-static unsigned countDigits(const String& src, unsigned start)
-{
- unsigned index = start;
- for (; index < src.length(); ++index) {
- if (!isASCIIDigit(src[index]))
- break;
- }
- return index - start;
-}
-
-// Very strict integer parser. Do not allow leading or trailing whitespace unlike charactersToIntStrict().
-static bool toInt(const String& src, unsigned parseStart, unsigned parseLength, int& out)
-{
- if (parseStart + parseLength > src.length() || parseLength <= 0)
- return false;
- int value = 0;
- unsigned current = parseStart;
- unsigned end = current + parseLength;
-
- // We don't need to handle negative numbers for ISO 8601.
- for (; current < end; ++current) {
- if (!isASCIIDigit(src[current]))
- return false;
- int digit = src[current] - '0';
- if (value > (INT_MAX - digit) / 10) // Check for overflow.
- return false;
- value = value * 10 + digit;
- }
- out = value;
- return true;
-}
-
-bool DateComponents::parseYear(const String& src, unsigned start, unsigned& end)
-{
- unsigned digitsLength = countDigits(src, start);
- // Needs at least 4 digits according to the standard.
- if (digitsLength < 4)
- return false;
- int year;
- if (!toInt(src, start, digitsLength, year))
- return false;
- if (year < minimumYear() || year > maximumYear())
- return false;
- m_year = year;
- end = start + digitsLength;
- return true;
-}
-
-static bool withinHTMLDateLimits(int year, int month)
-{
- if (year < DateComponents::minimumYear())
- return false;
- if (year < DateComponents::maximumYear())
- return true;
- return month <= maximumMonthInMaximumYear;
-}
-
-static bool withinHTMLDateLimits(int year, int month, int monthDay)
-{
- if (year < DateComponents::minimumYear())
- return false;
- if (year < DateComponents::maximumYear())
- return true;
- if (month < maximumMonthInMaximumYear)
- return true;
- return monthDay <= maximumDayInMaximumMonth;
-}
-
-static bool withinHTMLDateLimits(int year, int month, int monthDay, int hour, int minute, int second, int millisecond)
-{
- if (year < DateComponents::minimumYear())
- return false;
- if (year < DateComponents::maximumYear())
- return true;
- if (month < maximumMonthInMaximumYear)
- return true;
- if (monthDay < maximumDayInMaximumMonth)
- return true;
- if (monthDay > maximumDayInMaximumMonth)
- return false;
- // (year, month, monthDay) = (maximumYear, maximumMonthInMaximumYear, maximumDayInMaximumMonth)
- return !hour && !minute && !second && !millisecond;
-}
-
-bool DateComponents::addDay(int dayDiff)
-{
- ASSERT(m_monthDay);
-
- int day = m_monthDay + dayDiff;
- if (day > maxDayOfMonth(m_year, m_month)) {
- day = m_monthDay;
- int year = m_year;
- int month = m_month;
- int maxDay = maxDayOfMonth(year, month);
- for (; dayDiff > 0; --dayDiff) {
- ++day;
- if (day > maxDay) {
- day = 1;
- ++month;
- if (month >= 12) { // month is 0-origin.
- month = 0;
- ++year;
- }
- maxDay = maxDayOfMonth(year, month);
- }
- }
- if (!withinHTMLDateLimits(year, month, day))
- return false;
- m_year = year;
- m_month = month;
- } else if (day < 1) {
- int month = m_month;
- int year = m_year;
- day = m_monthDay;
- for (; dayDiff < 0; ++dayDiff) {
- --day;
- if (day < 1) {
- --month;
- if (month < 0) {
- month = 11;
- --year;
- }
- day = maxDayOfMonth(year, month);
- }
- }
- if (!withinHTMLDateLimits(year, month, day))
- return false;
- m_year = year;
- m_month = month;
- } else {
- if (!withinHTMLDateLimits(m_year, m_month, day))
- return false;
- }
- m_monthDay = day;
- return true;
-}
-
-bool DateComponents::addMinute(int minute)
-{
- // This function is used to adjust timezone offset. So m_year, m_month,
- // m_monthDay have values between the lower and higher limits.
- ASSERT(withinHTMLDateLimits(m_year, m_month, m_monthDay));
-
- int carry;
- // minute can be negative or greater than 59.
- minute += m_minute;
- if (minute > 59) {
- carry = minute / 60;
- minute = minute % 60;
- } else if (minute < 0) {
- carry = (59 - minute) / 60;
- minute += carry * 60;
- carry = -carry;
- ASSERT(minute >= 0 && minute <= 59);
- } else {
- if (!withinHTMLDateLimits(m_year, m_month, m_monthDay, m_hour, minute, m_second, m_millisecond))
- return false;
- m_minute = minute;
- return true;
- }
-
- int hour = m_hour + carry;
- if (hour > 23) {
- carry = hour / 24;
- hour = hour % 24;
- } else if (hour < 0) {
- carry = (23 - hour) / 24;
- hour += carry * 24;
- carry = -carry;
- ASSERT(hour >= 0 && hour <= 23);
- } else {
- if (!withinHTMLDateLimits(m_year, m_month, m_monthDay, hour, minute, m_second, m_millisecond))
- return false;
- m_minute = minute;
- m_hour = hour;
- return true;
- }
- if (!addDay(carry))
- return false;
- if (!withinHTMLDateLimits(m_year, m_month, m_monthDay, hour, minute, m_second, m_millisecond))
- return false;
- m_minute = minute;
- m_hour = hour;
- return true;
-}
-
-// Parses a timezone part, and adjust year, month, monthDay, hour, minute, second, millisecond.
-bool DateComponents::parseTimeZone(const String& src, unsigned start, unsigned& end)
-{
- if (start >= src.length())
- return false;
- unsigned index = start;
- if (src[index] == 'Z') {
- end = index + 1;
- return true;
- }
-
- bool minus;
- if (src[index] == '+')
- minus = false;
- else if (src[index] == '-')
- minus = true;
- else
- return false;
- ++index;
-
- int hour;
- int minute;
- if (!toInt(src, index, 2, hour) || hour < 0 || hour > 23)
- return false;
- index += 2;
-
- if (index >= src.length() || src[index] != ':')
- return false;
- ++index;
-
- if (!toInt(src, index, 2, minute) || minute < 0 || minute > 59)
- return false;
- index += 2;
-
- if (minus) {
- hour = -hour;
- minute = -minute;
- }
-
- // Subtract the timezone offset.
- if (!addMinute(-(hour * 60 + minute)))
- return false;
- end = index;
- return true;
-}
-
-bool DateComponents::parseMonth(const String& src, unsigned start, unsigned& end)
-{
- unsigned index;
- if (!parseYear(src, start, index))
- return false;
- if (index >= src.length() || src[index] != '-')
- return false;
- ++index;
-
- int month;
- if (!toInt(src, index, 2, month) || month < 1 || month > 12)
- return false;
- --month;
- if (!withinHTMLDateLimits(m_year, month))
- return false;
- m_month = month;
- end = index + 2;
- m_type = Month;
- return true;
-}
-
-bool DateComponents::parseDate(const String& src, unsigned start, unsigned& end)
-{
- unsigned index;
- if (!parseMonth(src, start, index))
- return false;
- // '-' and 2-digits are needed.
- if (index + 2 >= src.length())
- return false;
- if (src[index] != '-')
- return false;
- ++index;
-
- int day;
- if (!toInt(src, index, 2, day) || day < 1 || day > maxDayOfMonth(m_year, m_month))
- return false;
- if (!withinHTMLDateLimits(m_year, m_month, day))
- return false;
- m_monthDay = day;
- end = index + 2;
- m_type = Date;
- return true;
-}
-
-bool DateComponents::parseWeek(const String& src, unsigned start, unsigned& end)
-{
- unsigned index;
- if (!parseYear(src, start, index))
- return false;
-
- // 4 characters ('-' 'W' digit digit) are needed.
- if (index + 3 >= src.length())
- return false;
- if (src[index] != '-')
- return false;
- ++index;
- if (src[index] != 'W')
- return false;
- ++index;
-
- int week;
- if (!toInt(src, index, 2, week) || week < minimumWeekNumber || week > maxWeekNumberInYear())
- return false;
- if (m_year == maximumYear() && week > maximumWeekInMaximumYear)
- return false;
- m_week = week;
- end = index + 2;
- m_type = Week;
- return true;
-}
-
-bool DateComponents::parseTime(const String& src, unsigned start, unsigned& end)
-{
- int hour;
- if (!toInt(src, start, 2, hour) || hour < 0 || hour > 23)
- return false;
- unsigned index = start + 2;
- if (index >= src.length())
- return false;
- if (src[index] != ':')
- return false;
- ++index;
-
- int minute;
- if (!toInt(src, index, 2, minute) || minute < 0 || minute > 59)
- return false;
- index += 2;
-
- int second = 0;
- int millisecond = 0;
- // Optional second part.
- // Do not return with false because the part is optional.
- if (index + 2 < src.length() && src[index] == ':') {
- if (toInt(src, index + 1, 2, second) && second >= 0 && second <= 59) {
- index += 3;
-
- // Optional fractional second part.
- if (index < src.length() && src[index] == '.') {
- unsigned digitsLength = countDigits(src, index + 1);
- if (digitsLength > 0) {
- ++index;
- bool ok;
- if (digitsLength == 1) {
- ok = toInt(src, index, 1, millisecond);
- millisecond *= 100;
- } else if (digitsLength == 2) {
- ok = toInt(src, index, 2, millisecond);
- millisecond *= 10;
- } else { // digitsLength >= 3
- ok = toInt(src, index, 3, millisecond);
- }
- ASSERT_UNUSED(ok, ok);
- index += digitsLength;
- }
- }
- }
- }
- m_hour = hour;
- m_minute = minute;
- m_second = second;
- m_millisecond = millisecond;
- end = index;
- m_type = Time;
- return true;
-}
-
-bool DateComponents::parseDateTimeLocal(const String& src, unsigned start, unsigned& end)
-{
- unsigned index;
- if (!parseDate(src, start, index))
- return false;
- if (index >= src.length())
- return false;
- if (src[index] != 'T')
- return false;
- ++index;
- if (!parseTime(src, index, end))
- return false;
- if (!withinHTMLDateLimits(m_year, m_month, m_monthDay, m_hour, m_minute, m_second, m_millisecond))
- return false;
- m_type = DateTimeLocal;
- return true;
-}
-
-bool DateComponents::parseDateTime(const String& src, unsigned start, unsigned& end)
-{
- unsigned index;
- if (!parseDate(src, start, index))
- return false;
- if (index >= src.length())
- return false;
- if (src[index] != 'T')
- return false;
- ++index;
- if (!parseTime(src, index, index))
- return false;
- if (!parseTimeZone(src, index, end))
- return false;
- if (!withinHTMLDateLimits(m_year, m_month, m_monthDay, m_hour, m_minute, m_second, m_millisecond))
- return false;
- m_type = DateTime;
- return true;
-}
-
-static inline double positiveFmod(double value, double divider)
-{
- double remainder = fmod(value, divider);
- return remainder < 0 ? remainder + divider : remainder;
-}
-
-void DateComponents::setMillisecondsSinceMidnightInternal(double msInDay)
-{
- ASSERT(msInDay >= 0 && msInDay < msPerDay);
- m_millisecond = static_cast<int>(fmod(msInDay, msPerSecond));
- double value = floor(msInDay / msPerSecond);
- m_second = static_cast<int>(fmod(value, secondsPerMinute));
- value = floor(value / secondsPerMinute);
- m_minute = static_cast<int>(fmod(value, minutesPerHour));
- m_hour = static_cast<int>(value / minutesPerHour);
-}
-
-bool DateComponents::setMillisecondsSinceEpochForDateInternal(double ms)
-{
- m_year = msToYear(ms);
- int yearDay = dayInYear(ms, m_year);
- m_month = monthFromDayInYear(yearDay, isLeapYear(m_year));
- m_monthDay = dayInMonthFromDayInYear(yearDay, isLeapYear(m_year));
- return true;
-}
-
-bool DateComponents::setMillisecondsSinceEpochForDate(double ms)
-{
- m_type = Invalid;
- if (!std::isfinite(ms))
- return false;
- if (!setMillisecondsSinceEpochForDateInternal(round(ms)))
- return false;
- if (!withinHTMLDateLimits(m_year, m_month, m_monthDay))
- return false;
- m_type = Date;
- return true;
-}
-
-bool DateComponents::setMillisecondsSinceEpochForDateTime(double ms)
-{
- m_type = Invalid;
- if (!std::isfinite(ms))
- return false;
- ms = round(ms);
- setMillisecondsSinceMidnightInternal(positiveFmod(ms, msPerDay));
- if (!setMillisecondsSinceEpochForDateInternal(ms))
- return false;
- if (!withinHTMLDateLimits(m_year, m_month, m_monthDay, m_hour, m_minute, m_second, m_millisecond))
- return false;
- m_type = DateTime;
- return true;
-}
-
-bool DateComponents::setMillisecondsSinceEpochForDateTimeLocal(double ms)
-{
- // Internal representation of DateTimeLocal is the same as DateTime except m_type.
- if (!setMillisecondsSinceEpochForDateTime(ms))
- return false;
- m_type = DateTimeLocal;
- return true;
-}
-
-bool DateComponents::setMillisecondsSinceEpochForMonth(double ms)
-{
- m_type = Invalid;
- if (!std::isfinite(ms))
- return false;
- if (!setMillisecondsSinceEpochForDateInternal(round(ms)))
- return false;
- if (!withinHTMLDateLimits(m_year, m_month))
- return false;
- m_type = Month;
- return true;
-}
-
-bool DateComponents::setMillisecondsSinceMidnight(double ms)
-{
- m_type = Invalid;
- if (!std::isfinite(ms))
- return false;
- setMillisecondsSinceMidnightInternal(positiveFmod(round(ms), msPerDay));
- m_type = Time;
- return true;
-}
-
-bool DateComponents::setMonthsSinceEpoch(double months)
-{
- if (!std::isfinite(months))
- return false;
- months = round(months);
- double doubleMonth = positiveFmod(months, 12);
- double doubleYear = 1970 + (months - doubleMonth) / 12;
- if (doubleYear < minimumYear() || maximumYear() < doubleYear)
- return false;
- int year = static_cast<int>(doubleYear);
- int month = static_cast<int>(doubleMonth);
- if (!withinHTMLDateLimits(year, month))
- return false;
- m_year = year;
- m_month = month;
- m_type = Month;
- return true;
-}
-
-// Offset from January 1st to Monday of the ISO 8601's first week.
-// ex. If January 1st is Friday, such Monday is 3 days later. Returns 3.
-static int offsetTo1stWeekStart(int year)
-{
- int offsetTo1stWeekStart = 1 - dayOfWeek(year, 0, 1);
- if (offsetTo1stWeekStart <= -4)
- offsetTo1stWeekStart += 7;
- return offsetTo1stWeekStart;
-}
-
-bool DateComponents::setMillisecondsSinceEpochForWeek(double ms)
-{
- m_type = Invalid;
- if (!std::isfinite(ms))
- return false;
- ms = round(ms);
-
- m_year = msToYear(ms);
- if (m_year < minimumYear() || m_year > maximumYear())
- return false;
-
- int yearDay = dayInYear(ms, m_year);
- int offset = offsetTo1stWeekStart(m_year);
- if (yearDay < offset) {
- // The day belongs to the last week of the previous year.
- m_year--;
- if (m_year <= minimumYear())
- return false;
- m_week = maxWeekNumberInYear();
- } else {
- m_week = ((yearDay - offset) / 7) + 1;
- if (m_week > maxWeekNumberInYear()) {
- m_year++;
- m_week = 1;
- }
- if (m_year > maximumYear() || (m_year == maximumYear() && m_week > maximumWeekInMaximumYear))
- return false;
- }
- m_type = Week;
- return true;
-}
-
-double DateComponents::millisecondsSinceEpochForTime() const
-{
- ASSERT(m_type == Time || m_type == DateTime || m_type == DateTimeLocal);
- return ((m_hour * minutesPerHour + m_minute) * secondsPerMinute + m_second) * msPerSecond + m_millisecond;
-}
-
-double DateComponents::millisecondsSinceEpoch() const
-{
- switch (m_type) {
- case Date:
- return dateToDaysFrom1970(m_year, m_month, m_monthDay) * msPerDay;
- case DateTime:
- case DateTimeLocal:
- return dateToDaysFrom1970(m_year, m_month, m_monthDay) * msPerDay + millisecondsSinceEpochForTime();
- case Month:
- return dateToDaysFrom1970(m_year, m_month, 1) * msPerDay;
- case Time:
- return millisecondsSinceEpochForTime();
- case Week:
- return (dateToDaysFrom1970(m_year, 0, 1) + offsetTo1stWeekStart(m_year) + (m_week - 1) * 7) * msPerDay;
- case Invalid:
- break;
- }
- ASSERT_NOT_REACHED();
- return invalidMilliseconds();
-}
-
-double DateComponents::monthsSinceEpoch() const
-{
- ASSERT(m_type == Month);
- return (m_year - 1970) * 12 + m_month;
-}
-
-String DateComponents::toStringForTime(SecondFormat format) const
-{
- ASSERT(m_type == DateTime || m_type == DateTimeLocal || m_type == Time);
- SecondFormat effectiveFormat = format;
- if (m_millisecond)
- effectiveFormat = Millisecond;
- else if (format == None && m_second)
- effectiveFormat = Second;
-
- switch (effectiveFormat) {
- default:
- ASSERT_NOT_REACHED();
- // Fallback to None.
- case None:
- return String::format("%02d:%02d", m_hour, m_minute);
- case Second:
- return String::format("%02d:%02d:%02d", m_hour, m_minute, m_second);
- case Millisecond:
- return String::format("%02d:%02d:%02d.%03d", m_hour, m_minute, m_second, m_millisecond);
- }
-}
-
-String DateComponents::toString(SecondFormat format) const
-{
- switch (m_type) {
- case Date:
- return String::format("%04d-%02d-%02d", m_year, m_month + 1, m_monthDay);
- case DateTime:
- return String::format("%04d-%02d-%02dT", m_year, m_month + 1, m_monthDay)
- + toStringForTime(format) + String("Z");
- case DateTimeLocal:
- return String::format("%04d-%02d-%02dT", m_year, m_month + 1, m_monthDay)
- + toStringForTime(format);
- case Month:
- return String::format("%04d-%02d", m_year, m_month + 1);
- case Time:
- return toStringForTime(format);
- case Week:
- return String::format("%04d-W%02d", m_year, m_week);
- case Invalid:
- break;
- }
- ASSERT_NOT_REACHED();
- return String("(Invalid DateComponents)");
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/DateComponents.h b/chromium/third_party/WebKit/Source/core/platform/DateComponents.h
deleted file mode 100644
index a8f4a493389..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/DateComponents.h
+++ /dev/null
@@ -1,213 +0,0 @@
-/*
- * Copyright (C) 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef DateComponents_h
-#define DateComponents_h
-
-#include <limits>
-#include "wtf/Forward.h"
-#include "wtf/unicode/Unicode.h"
-
-namespace WebCore {
-
-// A DateComponents instance represents one of the following date and time combinations:
-// * Month type: year-month
-// * Date type: year-month-day
-// * Week type: year-week
-// * Time type: hour-minute-second-millisecond
-// * DateTime or DateTimeLocal type: year-month-day hour-minute-second-millisecond
-class DateComponents {
-public:
- DateComponents()
- : m_millisecond(0)
- , m_second(0)
- , m_minute(0)
- , m_hour(0)
- , m_monthDay(0)
- , m_month(0)
- , m_year(0)
- , m_week(0)
- , m_type(Invalid)
- {
- }
-
- enum Type {
- Invalid,
- Date,
- DateTime,
- DateTimeLocal,
- Month,
- Time,
- Week,
- };
-
- int millisecond() const { return m_millisecond; }
- int second() const { return m_second; }
- int minute() const { return m_minute; }
- int hour() const { return m_hour; }
- int monthDay() const { return m_monthDay; }
- int month() const { return m_month; }
- int fullYear() const { return m_year; }
- int week() const { return m_week; }
- Type type() const { return m_type; }
-
- enum SecondFormat {
- None, // Suppress the second part and the millisecond part if they are 0.
- Second, // Always show the second part, and suppress the millisecond part if it is 0.
- Millisecond // Always show the second part and the millisecond part.
- };
-
- // Returns an ISO 8601 representation for this instance.
- // The format argument is valid for DateTime, DateTimeLocal, and Time types.
- String toString(SecondFormat format = None) const;
-
- // parse*() and setMillisecondsSince*() functions are initializers for an
- // DateComponents instance. If these functions return false, the instance
- // might be invalid.
-
- // The following six functions parse the input 'src' whose length is
- // 'length', and updates some fields of this instance. The parsing starts at
- // src[start] and examines characters before src[length].
- // 'src' must be non-null. The 'src' string doesn't need to be
- // null-terminated.
- // The functions return true if the parsing succeeds, and set 'end' to the
- // next index after the last consumed. Extra leading characters cause parse
- // failures, and the trailing extra characters don't cause parse failures.
-
- // Sets year and month.
- bool parseMonth(const String&, unsigned start, unsigned& end);
- // Sets year, month and monthDay.
- bool parseDate(const String&, unsigned start, unsigned& end);
- // Sets year and week.
- bool parseWeek(const String&, unsigned start, unsigned& end);
- // Sets hour, minute, second and millisecond.
- bool parseTime(const String&, unsigned start, unsigned& end);
- // Sets year, month, monthDay, hour, minute, second and millisecond.
- bool parseDateTimeLocal(const String&, unsigned start, unsigned& end);
- // Sets year, month, monthDay, hour, minute, second and millisecond, and adjusts timezone.
- bool parseDateTime(const String&, unsigned start, unsigned& end);
-
- // The following setMillisecondsSinceEpochFor*() functions take
- // the number of milliseconds since 1970-01-01 00:00:00.000 UTC as
- // the argument, and update all fields for the corresponding
- // DateComponents type. The functions return true if it succeeds, and
- // false if they fail.
-
- // For Date type. Updates m_year, m_month and m_monthDay.
- bool setMillisecondsSinceEpochForDate(double ms);
- // For DateTime type. Updates m_year, m_month, m_monthDay, m_hour, m_minute, m_second and m_millisecond.
- bool setMillisecondsSinceEpochForDateTime(double ms);
- // For DateTimeLocal type. Updates m_year, m_month, m_monthDay, m_hour, m_minute, m_second and m_millisecond.
- bool setMillisecondsSinceEpochForDateTimeLocal(double ms);
- // For Month type. Updates m_year and m_month.
- bool setMillisecondsSinceEpochForMonth(double ms);
- // For Week type. Updates m_year and m_week.
- bool setMillisecondsSinceEpochForWeek(double ms);
-
- // For Time type. Updates m_hour, m_minute, m_second and m_millisecond.
- bool setMillisecondsSinceMidnight(double ms);
-
- // Another initializer for Month type. Updates m_year and m_month.
- bool setMonthsSinceEpoch(double months);
-
- // Returns the number of milliseconds from 1970-01-01 00:00:00 UTC.
- // For a DateComponents initialized with parseDateTimeLocal(),
- // millisecondsSinceEpoch() returns a value for UTC timezone.
- double millisecondsSinceEpoch() const;
- // Returns the number of months from 1970-01.
- // Do not call this for types other than Month.
- double monthsSinceEpoch() const;
- static inline double invalidMilliseconds() { return std::numeric_limits<double>::quiet_NaN(); }
-
- // Minimum and maxmimum limits for setMillisecondsSince*(),
- // setMonthsSinceEpoch(), millisecondsSinceEpoch(), and monthsSinceEpoch().
- static inline double minimumDate() { return -62135596800000.0; } // 0001-01-01T00:00Z
- static inline double minimumDateTime() { return -62135596800000.0; } // ditto.
- static inline double minimumMonth() { return (1 - 1970) * 12.0 + 1 - 1; } // 0001-01
- static inline double minimumTime() { return 0; } // 00:00:00.000
- static inline double minimumWeek() { return -62135596800000.0; } // 0001-01-01, the first Monday of 0001.
- static inline double maximumDate() { return 8640000000000000.0; } // 275760-09-13T00:00Z
- static inline double maximumDateTime() { return 8640000000000000.0; } // ditto.
- static inline double maximumMonth() { return (275760 - 1970) * 12.0 + 9 - 1; } // 275760-09
- static inline double maximumTime() { return 86399999; } // 23:59:59.999
- static inline double maximumWeek() { return 8639999568000000.0; } // 275760-09-08, the Monday of the week including 275760-09-13.
-
- // HTML5 uses ISO-8601 format with year >= 1. Gregorian calendar started in
- // 1582. However, we need to support 0001-01-01 in Gregorian calendar rule.
- static inline int minimumYear() { return 1; }
- // Date in ECMAScript can't represent dates later than 275760-09-13T00:00Z.
- // So, we have the same upper limit in HTML5 date/time types.
- static inline int maximumYear() { return 275760; }
- static const int minimumWeekNumber;
- static const int maximumWeekNumber;
-
-private:
- // Returns the maximum week number in this DateComponents's year.
- // The result is either of 52 and 53.
- int maxWeekNumberInYear() const;
- bool parseYear(const String&, unsigned start, unsigned& end);
- bool addDay(int);
- bool addMinute(int);
- bool parseTimeZone(const String&, unsigned start, unsigned& end);
- // Helper for millisecondsSinceEpoch().
- double millisecondsSinceEpochForTime() const;
- // Helpers for setMillisecondsSinceEpochFor*().
- bool setMillisecondsSinceEpochForDateInternal(double ms);
- void setMillisecondsSinceMidnightInternal(double ms);
- // Helper for toString().
- String toStringForTime(SecondFormat) const;
-
- // m_weekDay values
- enum {
- Sunday = 0,
- Monday,
- Tuesday,
- Wednesday,
- Thursday,
- Friday,
- Saturday,
- };
-
- int m_millisecond; // 0 - 999
- int m_second;
- int m_minute;
- int m_hour;
- int m_monthDay; // 1 - 31
- int m_month; // 0:January - 11:December
- int m_year; // 1582 -
- int m_week; // 1 - 53
-
- Type m_type;
-};
-
-
-} // namespace WebCore
-
-#endif // DateComponents_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/DateTimeChooser.h b/chromium/third_party/WebKit/Source/core/platform/DateTimeChooser.h
deleted file mode 100644
index 814d24d54f5..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/DateTimeChooser.h
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef DateTimeChooser_h
-#define DateTimeChooser_h
-
-#include "core/platform/graphics/IntRect.h"
-#include "wtf/RefCounted.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-struct DateTimeChooserParameters {
- AtomicString type;
- IntRect anchorRectInRootView;
- // Locale name for which the chooser should be localized. This
- // might be an invalid name because it comes from HTML lang
- // attributes.
- AtomicString locale;
- String currentValue;
- Vector<String> suggestionValues;
- Vector<String> localizedSuggestionValues;
- Vector<String> suggestionLabels;
- double minimum;
- double maximum;
- double step;
- double stepBase;
- bool required;
- bool isAnchorElementRTL;
-};
-
-// For pickers like color pickers and date pickers.
-class DateTimeChooser : public RefCounted<DateTimeChooser> {
-public:
- virtual ~DateTimeChooser() { }
-
- virtual void endChooser() = 0;
-};
-
-} // namespace WebCore
-#endif // DateTimeChooser_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/DateTimeChooserClient.h b/chromium/third_party/WebKit/Source/core/platform/DateTimeChooserClient.h
deleted file mode 100644
index 6d92ce731fa..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/DateTimeChooserClient.h
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef DateTimeChooserClient_h
-#define DateTimeChooserClient_h
-
-namespace WebCore {
-
-class DateTimeChooserClient {
-public:
- virtual ~DateTimeChooserClient() { }
-
- // Called when user picked a value.
- virtual void didChooseValue(const String&) = 0;
- // Called when chooser has ended.
- virtual void didEndChooser() = 0;
-};
-
-} // namespace WebCore
-#endif // DateTimeChooserClient_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/Decimal.cpp b/chromium/third_party/WebKit/Source/core/platform/Decimal.cpp
deleted file mode 100644
index e61d5bb10f3..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/Decimal.cpp
+++ /dev/null
@@ -1,1034 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/Decimal.h"
-
-#include <float.h>
-#include <algorithm>
-
-#include "wtf/Assertions.h"
-#include "wtf/MathExtras.h"
-#include "wtf/Noncopyable.h"
-#include "wtf/text/StringBuilder.h"
-
-namespace WebCore {
-
-namespace DecimalPrivate {
-
-static int const ExponentMax = 1023;
-static int const ExponentMin = -1023;
-static int const Precision = 18;
-
-static const uint64_t MaxCoefficient = UINT64_C(0x16345785D89FFFF); // 999999999999999999 == 18 9's
-
-// This class handles Decimal special values.
-class SpecialValueHandler {
- WTF_MAKE_NONCOPYABLE(SpecialValueHandler);
-public:
- enum HandleResult {
- BothFinite,
- BothInfinity,
- EitherNaN,
- LHSIsInfinity,
- RHSIsInfinity,
- };
-
- SpecialValueHandler(const Decimal& lhs, const Decimal& rhs);
- HandleResult handle();
- Decimal value() const;
-
-private:
- enum Result {
- ResultIsLHS,
- ResultIsRHS,
- ResultIsUnknown,
- };
-
- const Decimal& m_lhs;
- const Decimal& m_rhs;
- Result m_result;
-};
-
-SpecialValueHandler::SpecialValueHandler(const Decimal& lhs, const Decimal& rhs)
- : m_lhs(lhs), m_rhs(rhs), m_result(ResultIsUnknown)
-{
-}
-
-SpecialValueHandler::HandleResult SpecialValueHandler::handle()
-{
- if (m_lhs.isFinite() && m_rhs.isFinite())
- return BothFinite;
-
- const Decimal::EncodedData::FormatClass lhsClass = m_lhs.value().formatClass();
- const Decimal::EncodedData::FormatClass rhsClass = m_rhs.value().formatClass();
- if (lhsClass == Decimal::EncodedData::ClassNaN) {
- m_result = ResultIsLHS;
- return EitherNaN;
- }
-
- if (rhsClass == Decimal::EncodedData::ClassNaN) {
- m_result = ResultIsRHS;
- return EitherNaN;
- }
-
- if (lhsClass == Decimal::EncodedData::ClassInfinity)
- return rhsClass == Decimal::EncodedData::ClassInfinity ? BothInfinity : LHSIsInfinity;
-
- if (rhsClass == Decimal::EncodedData::ClassInfinity)
- return RHSIsInfinity;
-
- ASSERT_NOT_REACHED();
- return BothFinite;
-}
-
-Decimal SpecialValueHandler::value() const
-{
- switch (m_result) {
- case ResultIsLHS:
- return m_lhs;
- case ResultIsRHS:
- return m_rhs;
- case ResultIsUnknown:
- default:
- ASSERT_NOT_REACHED();
- return m_lhs;
- }
-}
-
-// This class is used for 128 bit unsigned integer arithmetic.
-class UInt128 {
-public:
- UInt128(uint64_t low, uint64_t high)
- : m_high(high), m_low(low)
- {
- }
-
- UInt128& operator/=(uint32_t);
-
- uint64_t high() const { return m_high; }
- uint64_t low() const { return m_low; }
-
- static UInt128 multiply(uint64_t u, uint64_t v) { return UInt128(u * v, multiplyHigh(u, v)); }
-
-private:
- static uint32_t highUInt32(uint64_t x) { return static_cast<uint32_t>(x >> 32); }
- static uint32_t lowUInt32(uint64_t x) { return static_cast<uint32_t>(x & ((static_cast<uint64_t>(1) << 32) - 1)); }
- bool isZero() const { return !m_low && !m_high; }
- static uint64_t makeUInt64(uint32_t low, uint32_t high) { return low | (static_cast<uint64_t>(high) << 32); }
-
- static uint64_t multiplyHigh(uint64_t, uint64_t);
-
- uint64_t m_high;
- uint64_t m_low;
-};
-
-UInt128& UInt128::operator/=(const uint32_t divisor)
-{
- ASSERT(divisor);
-
- if (!m_high) {
- m_low /= divisor;
- return *this;
- }
-
- uint32_t dividend[4];
- dividend[0] = lowUInt32(m_low);
- dividend[1] = highUInt32(m_low);
- dividend[2] = lowUInt32(m_high);
- dividend[3] = highUInt32(m_high);
-
- uint32_t quotient[4];
- uint32_t remainder = 0;
- for (int i = 3; i >= 0; --i) {
- const uint64_t work = makeUInt64(dividend[i], remainder);
- remainder = static_cast<uint32_t>(work % divisor);
- quotient[i] = static_cast<uint32_t>(work / divisor);
- }
- m_low = makeUInt64(quotient[0], quotient[1]);
- m_high = makeUInt64(quotient[2], quotient[3]);
- return *this;
-}
-
-// Returns high 64bit of 128bit product.
-uint64_t UInt128::multiplyHigh(uint64_t u, uint64_t v)
-{
- const uint64_t uLow = lowUInt32(u);
- const uint64_t uHigh = highUInt32(u);
- const uint64_t vLow = lowUInt32(v);
- const uint64_t vHigh = highUInt32(v);
- const uint64_t partialProduct = uHigh * vLow + highUInt32(uLow * vLow);
- return uHigh * vHigh + highUInt32(partialProduct) + highUInt32(uLow * vHigh + lowUInt32(partialProduct));
-}
-
-static int countDigits(uint64_t x)
-{
- int numberOfDigits = 0;
- for (uint64_t powerOfTen = 1; x >= powerOfTen; powerOfTen *= 10) {
- ++numberOfDigits;
- if (powerOfTen >= std::numeric_limits<uint64_t>::max() / 10)
- break;
- }
- return numberOfDigits;
-}
-
-static uint64_t scaleDown(uint64_t x, int n)
-{
- ASSERT(n >= 0);
- while (n > 0 && x) {
- x /= 10;
- --n;
- }
- return x;
-}
-
-static uint64_t scaleUp(uint64_t x, int n)
-{
- ASSERT(n >= 0);
- ASSERT(n < Precision);
-
- uint64_t y = 1;
- uint64_t z = 10;
- for (;;) {
- if (n & 1)
- y = y * z;
-
- n >>= 1;
- if (!n)
- return x * y;
-
- z = z * z;
- }
-}
-
-} // namespace DecimalPrivate
-
-using namespace DecimalPrivate;
-
-Decimal::EncodedData::EncodedData(Sign sign, FormatClass formatClass)
- : m_coefficient(0)
- , m_exponent(0)
- , m_formatClass(formatClass)
- , m_sign(sign)
-{
-}
-
-Decimal::EncodedData::EncodedData(Sign sign, int exponent, uint64_t coefficient)
- : m_formatClass(coefficient ? ClassNormal : ClassZero)
- , m_sign(sign)
-{
- if (exponent >= ExponentMin && exponent <= ExponentMax) {
- while (coefficient > MaxCoefficient) {
- coefficient /= 10;
- ++exponent;
- }
- }
-
- if (exponent > ExponentMax) {
- m_coefficient = 0;
- m_exponent = 0;
- m_formatClass = ClassInfinity;
- return;
- }
-
- if (exponent < ExponentMin) {
- m_coefficient = 0;
- m_exponent = 0;
- m_formatClass = ClassZero;
- return;
- }
-
- m_coefficient = coefficient;
- m_exponent = static_cast<int16_t>(exponent);
-}
-
-bool Decimal::EncodedData::operator==(const EncodedData& another) const
-{
- return m_sign == another.m_sign
- && m_formatClass == another.m_formatClass
- && m_exponent == another.m_exponent
- && m_coefficient == another.m_coefficient;
-}
-
-Decimal::Decimal(int32_t i32)
- : m_data(i32 < 0 ? Negative : Positive, 0, i32 < 0 ? static_cast<uint64_t>(-static_cast<int64_t>(i32)) : static_cast<uint64_t>(i32))
-{
-}
-
-Decimal::Decimal(Sign sign, int exponent, uint64_t coefficient)
- : m_data(sign, exponent, coefficient)
-{
-}
-
-Decimal::Decimal(const EncodedData& data)
- : m_data(data)
-{
-}
-
-Decimal::Decimal(const Decimal& other)
- : m_data(other.m_data)
-{
-}
-
-Decimal& Decimal::operator=(const Decimal& other)
-{
- m_data = other.m_data;
- return *this;
-}
-
-Decimal& Decimal::operator+=(const Decimal& other)
-{
- m_data = (*this + other).m_data;
- return *this;
-}
-
-Decimal& Decimal::operator-=(const Decimal& other)
-{
- m_data = (*this - other).m_data;
- return *this;
-}
-
-Decimal& Decimal::operator*=(const Decimal& other)
-{
- m_data = (*this * other).m_data;
- return *this;
-}
-
-Decimal& Decimal::operator/=(const Decimal& other)
-{
- m_data = (*this / other).m_data;
- return *this;
-}
-
-Decimal Decimal::operator-() const
-{
- if (isNaN())
- return *this;
-
- Decimal result(*this);
- result.m_data.setSign(invertSign(m_data.sign()));
- return result;
-}
-
-Decimal Decimal::operator+(const Decimal& rhs) const
-{
- const Decimal& lhs = *this;
- const Sign lhsSign = lhs.sign();
- const Sign rhsSign = rhs.sign();
-
- SpecialValueHandler handler(lhs, rhs);
- switch (handler.handle()) {
- case SpecialValueHandler::BothFinite:
- break;
-
- case SpecialValueHandler::BothInfinity:
- return lhsSign == rhsSign ? lhs : nan();
-
- case SpecialValueHandler::EitherNaN:
- return handler.value();
-
- case SpecialValueHandler::LHSIsInfinity:
- return lhs;
-
- case SpecialValueHandler::RHSIsInfinity:
- return rhs;
- }
-
- const AlignedOperands alignedOperands = alignOperands(lhs, rhs);
-
- const uint64_t result = lhsSign == rhsSign
- ? alignedOperands.lhsCoefficient + alignedOperands.rhsCoefficient
- : alignedOperands.lhsCoefficient - alignedOperands.rhsCoefficient;
-
- if (lhsSign == Negative && rhsSign == Positive && !result)
- return Decimal(Positive, alignedOperands.exponent, 0);
-
- return static_cast<int64_t>(result) >= 0
- ? Decimal(lhsSign, alignedOperands.exponent, result)
- : Decimal(invertSign(lhsSign), alignedOperands.exponent, -static_cast<int64_t>(result));
-}
-
-Decimal Decimal::operator-(const Decimal& rhs) const
-{
- const Decimal& lhs = *this;
- const Sign lhsSign = lhs.sign();
- const Sign rhsSign = rhs.sign();
-
- SpecialValueHandler handler(lhs, rhs);
- switch (handler.handle()) {
- case SpecialValueHandler::BothFinite:
- break;
-
- case SpecialValueHandler::BothInfinity:
- return lhsSign == rhsSign ? nan() : lhs;
-
- case SpecialValueHandler::EitherNaN:
- return handler.value();
-
- case SpecialValueHandler::LHSIsInfinity:
- return lhs;
-
- case SpecialValueHandler::RHSIsInfinity:
- return infinity(invertSign(rhsSign));
- }
-
- const AlignedOperands alignedOperands = alignOperands(lhs, rhs);
-
- const uint64_t result = lhsSign == rhsSign
- ? alignedOperands.lhsCoefficient - alignedOperands.rhsCoefficient
- : alignedOperands.lhsCoefficient + alignedOperands.rhsCoefficient;
-
- if (lhsSign == Negative && rhsSign == Negative && !result)
- return Decimal(Positive, alignedOperands.exponent, 0);
-
- return static_cast<int64_t>(result) >= 0
- ? Decimal(lhsSign, alignedOperands.exponent, result)
- : Decimal(invertSign(lhsSign), alignedOperands.exponent, -static_cast<int64_t>(result));
-}
-
-Decimal Decimal::operator*(const Decimal& rhs) const
-{
- const Decimal& lhs = *this;
- const Sign lhsSign = lhs.sign();
- const Sign rhsSign = rhs.sign();
- const Sign resultSign = lhsSign == rhsSign ? Positive : Negative;
-
- SpecialValueHandler handler(lhs, rhs);
- switch (handler.handle()) {
- case SpecialValueHandler::BothFinite: {
- const uint64_t lhsCoefficient = lhs.m_data.coefficient();
- const uint64_t rhsCoefficient = rhs.m_data.coefficient();
- int resultExponent = lhs.exponent() + rhs.exponent();
- UInt128 work(UInt128::multiply(lhsCoefficient, rhsCoefficient));
- while (work.high()) {
- work /= 10;
- ++resultExponent;
- }
- return Decimal(resultSign, resultExponent, work.low());
- }
-
- case SpecialValueHandler::BothInfinity:
- return infinity(resultSign);
-
- case SpecialValueHandler::EitherNaN:
- return handler.value();
-
- case SpecialValueHandler::LHSIsInfinity:
- return rhs.isZero() ? nan() : infinity(resultSign);
-
- case SpecialValueHandler::RHSIsInfinity:
- return lhs.isZero() ? nan() : infinity(resultSign);
- }
-
- ASSERT_NOT_REACHED();
- return nan();
-}
-
-Decimal Decimal::operator/(const Decimal& rhs) const
-{
- const Decimal& lhs = *this;
- const Sign lhsSign = lhs.sign();
- const Sign rhsSign = rhs.sign();
- const Sign resultSign = lhsSign == rhsSign ? Positive : Negative;
-
- SpecialValueHandler handler(lhs, rhs);
- switch (handler.handle()) {
- case SpecialValueHandler::BothFinite:
- break;
-
- case SpecialValueHandler::BothInfinity:
- return nan();
-
- case SpecialValueHandler::EitherNaN:
- return handler.value();
-
- case SpecialValueHandler::LHSIsInfinity:
- return infinity(resultSign);
-
- case SpecialValueHandler::RHSIsInfinity:
- return zero(resultSign);
- }
-
- ASSERT(lhs.isFinite());
- ASSERT(rhs.isFinite());
-
- if (rhs.isZero())
- return lhs.isZero() ? nan() : infinity(resultSign);
-
- int resultExponent = lhs.exponent() - rhs.exponent();
-
- if (lhs.isZero())
- return Decimal(resultSign, resultExponent, 0);
-
- uint64_t remainder = lhs.m_data.coefficient();
- const uint64_t divisor = rhs.m_data.coefficient();
- uint64_t result = 0;
- while (result < MaxCoefficient / 100) {
- while (remainder < divisor) {
- remainder *= 10;
- result *= 10;
- --resultExponent;
- }
- result += remainder / divisor;
- remainder %= divisor;
- if (!remainder)
- break;
- }
-
- if (remainder > divisor / 2)
- ++result;
-
- return Decimal(resultSign, resultExponent, result);
-}
-
-bool Decimal::operator==(const Decimal& rhs) const
-{
- return m_data == rhs.m_data || compareTo(rhs).isZero();
-}
-
-bool Decimal::operator!=(const Decimal& rhs) const
-{
- if (m_data == rhs.m_data)
- return false;
- const Decimal result = compareTo(rhs);
- if (result.isNaN())
- return false;
- return !result.isZero();
-}
-
-bool Decimal::operator<(const Decimal& rhs) const
-{
- const Decimal result = compareTo(rhs);
- if (result.isNaN())
- return false;
- return !result.isZero() && result.isNegative();
-}
-
-bool Decimal::operator<=(const Decimal& rhs) const
-{
- if (m_data == rhs.m_data)
- return true;
- const Decimal result = compareTo(rhs);
- if (result.isNaN())
- return false;
- return result.isZero() || result.isNegative();
-}
-
-bool Decimal::operator>(const Decimal& rhs) const
-{
- const Decimal result = compareTo(rhs);
- if (result.isNaN())
- return false;
- return !result.isZero() && result.isPositive();
-}
-
-bool Decimal::operator>=(const Decimal& rhs) const
-{
- if (m_data == rhs.m_data)
- return true;
- const Decimal result = compareTo(rhs);
- if (result.isNaN())
- return false;
- return result.isZero() || !result.isNegative();
-}
-
-Decimal Decimal::abs() const
-{
- Decimal result(*this);
- result.m_data.setSign(Positive);
- return result;
-}
-
-Decimal::AlignedOperands Decimal::alignOperands(const Decimal& lhs, const Decimal& rhs)
-{
- ASSERT(lhs.isFinite());
- ASSERT(rhs.isFinite());
-
- const int lhsExponent = lhs.exponent();
- const int rhsExponent = rhs.exponent();
- int exponent = std::min(lhsExponent, rhsExponent);
- uint64_t lhsCoefficient = lhs.m_data.coefficient();
- uint64_t rhsCoefficient = rhs.m_data.coefficient();
-
- if (lhsExponent > rhsExponent) {
- const int numberOfLHSDigits = countDigits(lhsCoefficient);
- if (numberOfLHSDigits) {
- const int lhsShiftAmount = lhsExponent - rhsExponent;
- const int overflow = numberOfLHSDigits + lhsShiftAmount - Precision;
- if (overflow <= 0)
- lhsCoefficient = scaleUp(lhsCoefficient, lhsShiftAmount);
- else {
- lhsCoefficient = scaleUp(lhsCoefficient, lhsShiftAmount - overflow);
- rhsCoefficient = scaleDown(rhsCoefficient, overflow);
- exponent += overflow;
- }
- }
-
- } else if (lhsExponent < rhsExponent) {
- const int numberOfRHSDigits = countDigits(rhsCoefficient);
- if (numberOfRHSDigits) {
- const int rhsShiftAmount = rhsExponent - lhsExponent;
- const int overflow = numberOfRHSDigits + rhsShiftAmount - Precision;
- if (overflow <= 0)
- rhsCoefficient = scaleUp(rhsCoefficient, rhsShiftAmount);
- else {
- rhsCoefficient = scaleUp(rhsCoefficient, rhsShiftAmount - overflow);
- lhsCoefficient = scaleDown(lhsCoefficient, overflow);
- exponent += overflow;
- }
- }
- }
-
- AlignedOperands alignedOperands;
- alignedOperands.exponent = exponent;
- alignedOperands.lhsCoefficient = lhsCoefficient;
- alignedOperands.rhsCoefficient = rhsCoefficient;
- return alignedOperands;
-}
-
-// Round toward positive infinity.
-// Note: Mac ports defines ceil(x) as wtf_ceil(x), so we can't use name "ceil" here.
-Decimal Decimal::ceiling() const
-{
- if (isSpecial())
- return *this;
-
- if (exponent() >= 0)
- return *this;
-
- uint64_t result = m_data.coefficient();
- const int numberOfDigits = countDigits(result);
- const int numberOfDropDigits = -exponent();
- if (numberOfDigits < numberOfDropDigits)
- return isPositive() ? Decimal(1) : zero(Positive);
-
- result = scaleDown(result, numberOfDropDigits - 1);
- if (sign() == Positive && result % 10 > 0)
- result += 10;
- result /= 10;
- return Decimal(sign(), 0, result);
-}
-
-Decimal Decimal::compareTo(const Decimal& rhs) const
-{
- const Decimal result(*this - rhs);
- switch (result.m_data.formatClass()) {
- case EncodedData::ClassInfinity:
- return result.isNegative() ? Decimal(-1) : Decimal(1);
-
- case EncodedData::ClassNaN:
- case EncodedData::ClassNormal:
- return result;
-
- case EncodedData::ClassZero:
- return zero(Positive);
-
- default:
- ASSERT_NOT_REACHED();
- return nan();
- }
-}
-
-// Round toward negative infinity.
-Decimal Decimal::floor() const
-{
- if (isSpecial())
- return *this;
-
- if (exponent() >= 0)
- return *this;
-
- uint64_t result = m_data.coefficient();
- const int numberOfDigits = countDigits(result);
- const int numberOfDropDigits = -exponent();
- if (numberOfDigits < numberOfDropDigits)
- return isPositive() ? zero(Positive) : Decimal(-1);
-
- result = scaleDown(result, numberOfDropDigits - 1);
- if (isNegative() && result % 10 > 0)
- result += 10;
- result /= 10;
- return Decimal(sign(), 0, result);
-}
-
-Decimal Decimal::fromDouble(double doubleValue)
-{
- if (std::isfinite(doubleValue))
- return fromString(String::numberToStringECMAScript(doubleValue));
-
- if (std::isinf(doubleValue))
- return infinity(doubleValue < 0 ? Negative : Positive);
-
- return nan();
-}
-
-Decimal Decimal::fromString(const String& str)
-{
- int exponent = 0;
- Sign exponentSign = Positive;
- int numberOfDigits = 0;
- int numberOfDigitsAfterDot = 0;
- int numberOfExtraDigits = 0;
- Sign sign = Positive;
-
- enum {
- StateDigit,
- StateDot,
- StateDotDigit,
- StateE,
- StateEDigit,
- StateESign,
- StateSign,
- StateStart,
- StateZero,
- } state = StateStart;
-
-#define HandleCharAndBreak(expected, nextState) \
- if (ch == expected) { \
- state = nextState; \
- break; \
- }
-
-#define HandleTwoCharsAndBreak(expected1, expected2, nextState) \
- if (ch == expected1 || ch == expected2) { \
- state = nextState; \
- break; \
- }
-
- uint64_t accumulator = 0;
- for (unsigned index = 0; index < str.length(); ++index) {
- const int ch = str[index];
- switch (state) {
- case StateDigit:
- if (ch >= '0' && ch <= '9') {
- if (numberOfDigits < Precision) {
- ++numberOfDigits;
- accumulator *= 10;
- accumulator += ch - '0';
- } else
- ++numberOfExtraDigits;
- break;
- }
-
- HandleCharAndBreak('.', StateDot);
- HandleTwoCharsAndBreak('E', 'e', StateE);
- return nan();
-
- case StateDot:
- if (ch >= '0' && ch <= '9') {
- if (numberOfDigits < Precision) {
- ++numberOfDigits;
- ++numberOfDigitsAfterDot;
- accumulator *= 10;
- accumulator += ch - '0';
- }
- state = StateDotDigit;
- break;
- }
-
- case StateDotDigit:
- if (ch >= '0' && ch <= '9') {
- if (numberOfDigits < Precision) {
- ++numberOfDigits;
- ++numberOfDigitsAfterDot;
- accumulator *= 10;
- accumulator += ch - '0';
- }
- break;
- }
-
- HandleTwoCharsAndBreak('E', 'e', StateE);
- return nan();
-
- case StateE:
- if (ch == '+') {
- exponentSign = Positive;
- state = StateESign;
- break;
- }
-
- if (ch == '-') {
- exponentSign = Negative;
- state = StateESign;
- break;
- }
-
- if (ch >= '0' && ch <= '9') {
- exponent = ch - '0';
- state = StateEDigit;
- break;
- }
-
- return nan();
-
- case StateEDigit:
- if (ch >= '0' && ch <= '9') {
- exponent *= 10;
- exponent += ch - '0';
- if (exponent > ExponentMax + Precision) {
- if (accumulator)
- return exponentSign == Negative ? zero(Positive) : infinity(sign);
- return zero(sign);
- }
- state = StateEDigit;
- break;
- }
-
- return nan();
-
- case StateESign:
- if (ch >= '0' && ch <= '9') {
- exponent = ch - '0';
- state = StateEDigit;
- break;
- }
-
- return nan();
-
- case StateSign:
- if (ch >= '1' && ch <= '9') {
- accumulator = ch - '0';
- numberOfDigits = 1;
- state = StateDigit;
- break;
- }
-
- HandleCharAndBreak('0', StateZero);
- return nan();
-
- case StateStart:
- if (ch >= '1' && ch <= '9') {
- accumulator = ch - '0';
- numberOfDigits = 1;
- state = StateDigit;
- break;
- }
-
- if (ch == '-') {
- sign = Negative;
- state = StateSign;
- break;
- }
-
- if (ch == '+') {
- sign = Positive;
- state = StateSign;
- break;
- }
-
- HandleCharAndBreak('0', StateZero);
- HandleCharAndBreak('.', StateDot);
- return nan();
-
- case StateZero:
- if (ch == '0')
- break;
-
- if (ch >= '1' && ch <= '9') {
- accumulator = ch - '0';
- numberOfDigits = 1;
- state = StateDigit;
- break;
- }
-
- HandleCharAndBreak('.', StateDot);
- HandleTwoCharsAndBreak('E', 'e', StateE);
- return nan();
-
- default:
- ASSERT_NOT_REACHED();
- return nan();
- }
- }
-
- if (state == StateZero)
- return zero(sign);
-
- if (state == StateDigit || state == StateEDigit || state == StateDotDigit) {
- int resultExponent = exponent * (exponentSign == Negative ? -1 : 1) - numberOfDigitsAfterDot + numberOfExtraDigits;
- if (resultExponent < ExponentMin)
- return zero(Positive);
-
- const int overflow = resultExponent - ExponentMax + 1;
- if (overflow > 0) {
- if (overflow + numberOfDigits - numberOfDigitsAfterDot > Precision)
- return infinity(sign);
- accumulator = scaleUp(accumulator, overflow);
- resultExponent -= overflow;
- }
-
- return Decimal(sign, resultExponent, accumulator);
- }
-
- return nan();
-}
-
-Decimal Decimal::infinity(const Sign sign)
-{
- return Decimal(EncodedData(sign, EncodedData::ClassInfinity));
-}
-
-Decimal Decimal::nan()
-{
- return Decimal(EncodedData(Positive, EncodedData::ClassNaN));
-}
-
-Decimal Decimal::remainder(const Decimal& rhs) const
-{
- const Decimal quotient = *this / rhs;
- return quotient.isSpecial() ? quotient : *this - (quotient.isNegative() ? quotient.ceiling() : quotient.floor()) * rhs;
-}
-
-Decimal Decimal::round() const
-{
- if (isSpecial())
- return *this;
-
- if (exponent() >= 0)
- return *this;
-
- uint64_t result = m_data.coefficient();
- const int numberOfDigits = countDigits(result);
- const int numberOfDropDigits = -exponent();
- if (numberOfDigits < numberOfDropDigits)
- return zero(Positive);
-
- result = scaleDown(result, numberOfDropDigits - 1);
- if (result % 10 >= 5)
- result += 10;
- result /= 10;
- return Decimal(sign(), 0, result);
-}
-
-double Decimal::toDouble() const
-{
- if (isFinite()) {
- bool valid;
- const double doubleValue = toString().toDouble(&valid);
- return valid ? doubleValue : std::numeric_limits<double>::quiet_NaN();
- }
-
- if (isInfinity())
- return isNegative() ? -std::numeric_limits<double>::infinity() : std::numeric_limits<double>::infinity();
-
- return std::numeric_limits<double>::quiet_NaN();
-}
-
-String Decimal::toString() const
-{
- switch (m_data.formatClass()) {
- case EncodedData::ClassInfinity:
- return sign() ? "-Infinity" : "Infinity";
-
- case EncodedData::ClassNaN:
- return "NaN";
-
- case EncodedData::ClassNormal:
- case EncodedData::ClassZero:
- break;
-
- default:
- ASSERT_NOT_REACHED();
- return "";
- }
-
- StringBuilder builder;
- if (sign())
- builder.append('-');
-
- int originalExponent = exponent();
- uint64_t coefficient = m_data.coefficient();
-
- if (originalExponent < 0) {
- const int maxDigits = DBL_DIG;
- uint64_t lastDigit = 0;
- while (countDigits(coefficient) > maxDigits) {
- lastDigit = coefficient % 10;
- coefficient /= 10;
- ++originalExponent;
- }
-
- if (lastDigit >= 5)
- ++coefficient;
-
- while (originalExponent < 0 && coefficient && !(coefficient % 10)) {
- coefficient /= 10;
- ++originalExponent;
- }
- }
-
- const String digits = String::number(coefficient);
- int coefficientLength = static_cast<int>(digits.length());
- const int adjustedExponent = originalExponent + coefficientLength - 1;
- if (originalExponent <= 0 && adjustedExponent >= -6) {
- if (!originalExponent) {
- builder.append(digits);
- return builder.toString();
- }
-
- if (adjustedExponent >= 0) {
- for (int i = 0; i < coefficientLength; ++i) {
- builder.append(digits[i]);
- if (i == adjustedExponent)
- builder.append('.');
- }
- return builder.toString();
- }
-
- builder.appendLiteral("0.");
- for (int i = adjustedExponent + 1; i < 0; ++i)
- builder.append('0');
-
- builder.append(digits);
-
- } else {
- builder.append(digits[0]);
- while (coefficientLength >= 2 && digits[coefficientLength - 1] == '0')
- --coefficientLength;
- if (coefficientLength >= 2) {
- builder.append('.');
- for (int i = 1; i < coefficientLength; ++i)
- builder.append(digits[i]);
- }
-
- if (adjustedExponent) {
- builder.append(adjustedExponent < 0 ? "e" : "e+");
- builder.appendNumber(adjustedExponent);
- }
- }
- return builder.toString();
-}
-
-Decimal Decimal::zero(Sign sign)
-{
- return Decimal(EncodedData(sign, EncodedData::ClassZero));
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/Decimal.h b/chromium/third_party/WebKit/Source/core/platform/Decimal.h
deleted file mode 100644
index fa9a1a34bfe..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/Decimal.h
+++ /dev/null
@@ -1,181 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef Decimal_h
-#define Decimal_h
-
-#include <stdint.h>
-#include "wtf/Assertions.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-namespace DecimalPrivate {
-class SpecialValueHandler;
-}
-
-// This class represents decimal base floating point number.
-//
-// FIXME: Once all C++ compiler support decimal type, we should replace this
-// class to compiler supported one. See below URI for current status of decimal
-// type for C++: // http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1977.html
-class Decimal {
- WTF_MAKE_FAST_ALLOCATED;
-public:
- enum Sign {
- Positive,
- Negative,
- };
-
- // You should not use EncodedData other than unit testing.
- class EncodedData {
- // For accessing FormatClass.
- friend class Decimal;
- friend class DecimalPrivate::SpecialValueHandler;
- public:
- EncodedData(Sign, int exponent, uint64_t coefficient);
-
- bool operator==(const EncodedData&) const;
- bool operator!=(const EncodedData& another) const { return !operator==(another); }
-
- uint64_t coefficient() const { return m_coefficient; }
- int countDigits() const;
- int exponent() const { return m_exponent; }
- bool isFinite() const { return !isSpecial(); }
- bool isInfinity() const { return m_formatClass == ClassInfinity; }
- bool isNaN() const { return m_formatClass == ClassNaN; }
- bool isSpecial() const { return m_formatClass == ClassInfinity || m_formatClass == ClassNaN; }
- bool isZero() const { return m_formatClass == ClassZero; }
- Sign sign() const { return m_sign; }
- void setSign(Sign sign) { m_sign = sign; }
-
- private:
- enum FormatClass {
- ClassInfinity,
- ClassNormal,
- ClassNaN,
- ClassZero,
- };
-
- EncodedData(Sign, FormatClass);
- FormatClass formatClass() const { return m_formatClass; }
-
- uint64_t m_coefficient;
- int16_t m_exponent;
- FormatClass m_formatClass;
- Sign m_sign;
- };
-
- Decimal(int32_t = 0);
- Decimal(Sign, int exponent, uint64_t coefficient);
- Decimal(const Decimal&);
-
- Decimal& operator=(const Decimal&);
- Decimal& operator+=(const Decimal&);
- Decimal& operator-=(const Decimal&);
- Decimal& operator*=(const Decimal&);
- Decimal& operator/=(const Decimal&);
-
- Decimal operator-() const;
-
- bool operator==(const Decimal&) const;
- bool operator!=(const Decimal&) const;
- bool operator<(const Decimal&) const;
- bool operator<=(const Decimal&) const;
- bool operator>(const Decimal&) const;
- bool operator>=(const Decimal&) const;
-
- Decimal operator+(const Decimal&) const;
- Decimal operator-(const Decimal&) const;
- Decimal operator*(const Decimal&) const;
- Decimal operator/(const Decimal&) const;
-
- int exponent() const
- {
- ASSERT(isFinite());
- return m_data.exponent();
- }
-
- bool isFinite() const { return m_data.isFinite(); }
- bool isInfinity() const { return m_data.isInfinity(); }
- bool isNaN() const { return m_data.isNaN(); }
- bool isNegative() const { return sign() == Negative; }
- bool isPositive() const { return sign() == Positive; }
- bool isSpecial() const { return m_data.isSpecial(); }
- bool isZero() const { return m_data.isZero(); }
-
- Decimal abs() const;
- Decimal ceiling() const;
- Decimal floor() const;
- Decimal remainder(const Decimal&) const;
- Decimal round() const;
-
- double toDouble() const;
- // Note: toString method supports infinity and nan but fromString not.
- String toString() const;
-
- static Decimal fromDouble(double);
- // fromString supports following syntax EBNF:
- // number ::= sign? digit+ ('.' digit*) (exponent-marker sign? digit+)?
- // | sign? '.' digit+ (exponent-marker sign? digit+)?
- // sign ::= '+' | '-'
- // exponent-marker ::= 'e' | 'E'
- // digit ::= '0' | '1' | ... | '9'
- // Note: fromString doesn't support "infinity" and "nan".
- static Decimal fromString(const String&);
- static Decimal infinity(Sign);
- static Decimal nan();
- static Decimal zero(Sign);
-
- // You should not use below methods. We expose them for unit testing.
- explicit Decimal(const EncodedData&);
- const EncodedData& value() const { return m_data; }
-
-private:
- struct AlignedOperands {
- uint64_t lhsCoefficient;
- uint64_t rhsCoefficient;
- int exponent;
- };
-
- Decimal(double);
- Decimal compareTo(const Decimal&) const;
-
- static AlignedOperands alignOperands(const Decimal& lhs, const Decimal& rhs);
- static inline Sign invertSign(Sign sign) { return sign == Negative ? Positive : Negative; }
-
- Sign sign() const { return m_data.sign(); }
-
- EncodedData m_data;
-};
-
-} // namespace WebCore
-
-#endif // Decimal_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/DecimalTest.cpp b/chromium/third_party/WebKit/Source/core/platform/DecimalTest.cpp
deleted file mode 100644
index b56fe88017f..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/DecimalTest.cpp
+++ /dev/null
@@ -1,1097 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/Decimal.h"
-
-#include "wtf/MathExtras.h"
-#include "wtf/text/CString.h"
-#include <float.h>
-#include <gtest/gtest.h>
-
-namespace WebCore {
-
-std::ostream& operator<<(std::ostream& os, const Decimal& decimal)
-{
- Decimal::EncodedData data = decimal.value();
- return os
- << "encode(" << String::number(data.coefficient()).ascii().data()
- << ", " << String::number(data.exponent()).ascii().data()
- << ", " << (data.sign() == Decimal::Negative ? "Negative" : "Positive")
- << ")=" << decimal.toString().ascii().data();
-}
-
-} // namespace WebCore
-
-using namespace WebCore;
-
-// Simulate WebCore/html/StepRange
-class DecimalStepRange {
-public:
- Decimal maximum;
- Decimal minimum;
- Decimal step;
-
- DecimalStepRange(const Decimal& minimum, const Decimal& maximum, const Decimal& step)
- : maximum(maximum)
- , minimum(minimum)
- , step(step)
- {
- }
-
- Decimal clampValue(Decimal value) const
- {
- const Decimal result = minimum + ((value - minimum) / step).round() * step;
- ASSERT(result.isFinite());
- return result > maximum ? result - step : result;
- }
-};
-
-class DecimalTest : public ::testing::Test {
-protected:
- typedef Decimal::Sign Sign;
- protected: static const Sign Positive = Decimal::Positive;
- protected: static const Sign Negative = Decimal::Negative;
-
- Decimal encode(uint64_t coefficient, int exponent, Sign sign)
- {
- return Decimal(sign, exponent, coefficient);
- }
-
- protected: Decimal fromString(const String& string)
- {
- return Decimal::fromString(string);
- }
-
- protected: Decimal stepDown(const String& minimum, const String& maximum, const String& step, const String& valueString, int numberOfStepTimes)
- {
- DecimalStepRange stepRange(fromString(minimum), fromString(maximum), fromString(step));
- Decimal value = fromString(valueString);
- for (int i = 0; i < numberOfStepTimes; ++i) {
- value -= stepRange.step;
- value = stepRange.clampValue(value);
- }
- return value;
- }
-
- protected: Decimal stepUp(const String& minimum, const String& maximum, const String& step, const String& valueString, int numberOfStepTimes)
- {
- DecimalStepRange stepRange(fromString(minimum), fromString(maximum), fromString(step));
- Decimal value = fromString(valueString);
- for (int i = 0; i < numberOfStepTimes; ++i) {
- value += stepRange.step;
- value = stepRange.clampValue(value);
- }
- return value;
- }
-};
-
-// FIXME: We should use expectedSign without "Decimal::", however, g++ causes undefined references for DecimalTest::Positive and Negative.
-#define EXPECT_DECIMAL_ENCODED_DATA_EQ(expectedCoefficient, expectedExponent, expectedSign, decimal) \
- EXPECT_EQ((expectedCoefficient), (decimal).value().coefficient()); \
- EXPECT_EQ((expectedExponent), (decimal).value().exponent()); \
- EXPECT_EQ(Decimal::expectedSign, (decimal).value().sign());
-
-#define EXPECT_DECIMAL_STREQ(expected, decimal) EXPECT_STREQ((expected), (decimal).toString().ascii().data())
-
-TEST_F(DecimalTest, Abs)
-{
- EXPECT_EQ(encode(0, 0, Positive), encode(0, 0, Positive).abs());
- EXPECT_EQ(encode(0, 0, Positive), encode(0, 0, Negative).abs());
-
- EXPECT_EQ(encode(0, 10, Positive), encode(0, 10, Positive).abs());
- EXPECT_EQ(encode(0, 10, Positive), encode(0, 10, Negative).abs());
-
- EXPECT_EQ(encode(0, -10, Positive), encode(0, -10, Positive).abs());
- EXPECT_EQ(encode(0, -10, Positive), encode(0, -10, Negative).abs());
-
- EXPECT_EQ(encode(1, 0, Positive), encode(1, 0, Positive).abs());
- EXPECT_EQ(encode(1, 0, Positive), encode(1, 0, Negative).abs());
-
- EXPECT_EQ(encode(1, 10, Positive), encode(1, 10, Positive).abs());
- EXPECT_EQ(encode(1, 10, Positive), encode(1, 10, Negative).abs());
-
- EXPECT_EQ(encode(1, -10, Positive), encode(1, -10, Positive).abs());
- EXPECT_EQ(encode(1, -10, Positive), encode(1, -10, Negative).abs());
-}
-
-TEST_F(DecimalTest, AbsBigExponent)
-{
- EXPECT_EQ(encode(1, 1000, Positive), encode(1, 1000, Positive).abs());
- EXPECT_EQ(encode(1, 1000, Positive), encode(1, 1000, Negative).abs());
-}
-
-TEST_F(DecimalTest, AbsSmallExponent)
-{
- EXPECT_EQ(encode(1, -1000, Positive), encode(1, -1000, Positive).abs());
- EXPECT_EQ(encode(1, -1000, Positive), encode(1, -1000, Negative).abs());
-}
-
-TEST_F(DecimalTest, AbsSpecialValues)
-{
- EXPECT_EQ(Decimal::infinity(Positive), Decimal::infinity(Positive).abs());
- EXPECT_EQ(Decimal::infinity(Positive), Decimal::infinity(Negative).abs());
- EXPECT_EQ(Decimal::nan(), Decimal::nan().abs());
-}
-
-TEST_F(DecimalTest, Add)
-{
- EXPECT_EQ(encode(0, 0, Positive), Decimal(0) + Decimal(0));
- EXPECT_EQ(Decimal(1), Decimal(2) + Decimal(-1));
- EXPECT_EQ(Decimal(1), Decimal(-1) + Decimal(2));
- EXPECT_EQ(encode(100, 0, Positive), Decimal(99) + Decimal(1));
- EXPECT_EQ(encode(100, 0, Negative), Decimal(-50) + Decimal(-50));
- EXPECT_EQ(encode(UINT64_C(1000000000000000), 35, Positive), encode(1, 50, Positive) + Decimal(1));
- EXPECT_EQ(encode(UINT64_C(1000000000000000), 35, Positive), Decimal(1) + encode(1, 50, Positive));
- EXPECT_EQ(encode(UINT64_C(10000000001), 0, Positive), encode(1, 10, Positive) + Decimal(1));
- EXPECT_EQ(encode(UINT64_C(10000000001), 0, Positive), Decimal(1) + encode(1, 10, Positive));
- EXPECT_EQ(encode(1, 0, Positive), encode(1, -1022, Positive) + encode(1, 0, Positive));
- EXPECT_EQ(encode(2, -1022, Positive), encode(1, -1022, Positive) + encode(1, -1022, Positive));
-}
-
-TEST_F(DecimalTest, AddBigExponent)
-{
- EXPECT_EQ(encode(1, 1022, Positive), encode(1, 1022, Positive) + encode(1, 0, Positive));
- EXPECT_EQ(encode(2, 1022, Positive), encode(1, 1022, Positive) + encode(1, 1022, Positive));
- EXPECT_EQ(Decimal::infinity(Positive), encode(std::numeric_limits<uint64_t>::max(), 1022, Positive) + encode(1, 0, Positive));
- EXPECT_EQ(encode(1, 1022, Positive), encode(1, 1022, Positive) + encode(1, -1000, Positive));
-}
-
-TEST_F(DecimalTest, AddSmallExponent)
-{
- EXPECT_EQ(encode(1, 0, Positive), encode(1, -1022, Positive) + encode(1, 0, Positive));
- EXPECT_EQ(encode(2, -1022, Positive), encode(1, -1022, Positive) + encode(1, -1022, Positive));
-}
-
-TEST_F(DecimalTest, AddSpecialValues)
-{
- const Decimal Infinity(Decimal::infinity(Positive));
- const Decimal MinusInfinity(Decimal::infinity(Negative));
- const Decimal NaN(Decimal::nan());
- const Decimal Ten(10);
-
- EXPECT_EQ(Infinity, Infinity + Infinity);
- EXPECT_EQ(NaN, Infinity + MinusInfinity);
- EXPECT_EQ(NaN, MinusInfinity + Infinity);
- EXPECT_EQ(MinusInfinity, MinusInfinity + MinusInfinity);
-
- EXPECT_EQ(Infinity, Infinity + Ten);
- EXPECT_EQ(Infinity, Ten + Infinity);
- EXPECT_EQ(MinusInfinity, MinusInfinity + Ten);
- EXPECT_EQ(MinusInfinity, Ten + MinusInfinity);
-
- EXPECT_EQ(NaN, NaN + NaN);
- EXPECT_EQ(NaN, NaN + Ten);
- EXPECT_EQ(NaN, Ten + NaN);
-
- EXPECT_EQ(NaN, NaN - Infinity);
- EXPECT_EQ(NaN, NaN - MinusInfinity);
- EXPECT_EQ(NaN, Infinity - NaN);
- EXPECT_EQ(NaN, MinusInfinity - NaN);
-}
-
-TEST_F(DecimalTest, Ceiling)
-{
- EXPECT_EQ(Decimal(1), Decimal(1).ceiling());
- EXPECT_EQ(Decimal(1), encode(1, -10, Positive).ceiling());
- EXPECT_EQ(Decimal(2), encode(11, -1, Positive).ceiling());
- EXPECT_EQ(Decimal(2), encode(13, -1, Positive).ceiling());
- EXPECT_EQ(Decimal(2), encode(15, -1, Positive).ceiling());
- EXPECT_EQ(Decimal(2), encode(19, -1, Positive).ceiling());
-
- EXPECT_EQ(Decimal(-1), Decimal(-1).ceiling());
- EXPECT_EQ(Decimal(0), encode(1, -10, Negative).ceiling());
- EXPECT_EQ(Decimal(-1), encode(11, -1, Negative).ceiling());
- EXPECT_EQ(Decimal(-1), encode(13, -1, Negative).ceiling());
- EXPECT_EQ(Decimal(-1), encode(15, -1, Negative).ceiling());
- EXPECT_EQ(Decimal(-1), encode(19, -1, Negative).ceiling());
-}
-
-TEST_F(DecimalTest, CeilingBigExponent)
-{
- EXPECT_EQ(encode(1, 1000, Positive), encode(1, 1000, Positive).ceiling());
- EXPECT_EQ(encode(1, 1000, Negative), encode(1, 1000, Negative).ceiling());
-}
-
-TEST_F(DecimalTest, CeilingSmallExponent)
-{
- EXPECT_EQ(encode(1, 0, Positive), encode(1, -1000, Positive).ceiling());
- EXPECT_EQ(encode(0, 0, Negative), encode(1, -1000, Negative).ceiling());
-}
-
-TEST_F(DecimalTest, CeilingSpecialValues)
-{
- EXPECT_EQ(Decimal::infinity(Positive), Decimal::infinity(Positive).ceiling());
- EXPECT_EQ(Decimal::infinity(Negative), Decimal::infinity(Negative).ceiling());
- EXPECT_EQ(Decimal::nan(), Decimal::nan().ceiling());
-}
-
-TEST_F(DecimalTest, Compare)
-{
- EXPECT_TRUE(Decimal(0) == Decimal(0));
- EXPECT_TRUE(Decimal(0) != Decimal(1));
- EXPECT_TRUE(Decimal(0) < Decimal(1));
- EXPECT_TRUE(Decimal(0) <= Decimal(0));
- EXPECT_TRUE(Decimal(0) > Decimal(-1));
- EXPECT_TRUE(Decimal(0) >= Decimal(0));
-
- EXPECT_FALSE(Decimal(1) == Decimal(2));
- EXPECT_FALSE(Decimal(1) != Decimal(1));
- EXPECT_FALSE(Decimal(1) < Decimal(0));
- EXPECT_FALSE(Decimal(1) <= Decimal(0));
- EXPECT_FALSE(Decimal(1) > Decimal(2));
- EXPECT_FALSE(Decimal(1) >= Decimal(2));
-}
-
-TEST_F(DecimalTest, CompareBigExponent)
-{
- EXPECT_TRUE(encode(1, 1000, Positive) == encode(1, 1000, Positive));
- EXPECT_FALSE(encode(1, 1000, Positive) != encode(1, 1000, Positive));
- EXPECT_FALSE(encode(1, 1000, Positive) < encode(1, 1000, Positive));
- EXPECT_TRUE(encode(1, 1000, Positive) <= encode(1, 1000, Positive));
- EXPECT_FALSE(encode(1, 1000, Positive) > encode(1, 1000, Positive));
- EXPECT_TRUE(encode(1, 1000, Positive) >= encode(1, 1000, Positive));
-
- EXPECT_TRUE(encode(1, 1000, Negative) == encode(1, 1000, Negative));
- EXPECT_FALSE(encode(1, 1000, Negative) != encode(1, 1000, Negative));
- EXPECT_FALSE(encode(1, 1000, Negative) < encode(1, 1000, Negative));
- EXPECT_TRUE(encode(1, 1000, Negative) <= encode(1, 1000, Negative));
- EXPECT_FALSE(encode(1, 1000, Negative) > encode(1, 1000, Negative));
- EXPECT_TRUE(encode(1, 1000, Negative) >= encode(1, 1000, Negative));
-
- EXPECT_FALSE(encode(2, 1000, Positive) == encode(1, 1000, Positive));
- EXPECT_TRUE(encode(2, 1000, Positive) != encode(1, 1000, Positive));
- EXPECT_FALSE(encode(2, 1000, Positive) < encode(1, 1000, Positive));
- EXPECT_FALSE(encode(2, 1000, Positive) <= encode(1, 1000, Positive));
- EXPECT_TRUE(encode(2, 1000, Positive) > encode(1, 1000, Positive));
- EXPECT_TRUE(encode(2, 1000, Positive) >= encode(1, 1000, Positive));
-
- EXPECT_FALSE(encode(2, 1000, Negative) == encode(1, 1000, Negative));
- EXPECT_TRUE(encode(2, 1000, Negative) != encode(1, 1000, Negative));
- EXPECT_TRUE(encode(2, 1000, Negative) < encode(1, 1000, Negative));
- EXPECT_TRUE(encode(2, 1000, Negative) <= encode(1, 1000, Negative));
- EXPECT_FALSE(encode(2, 1000, Negative) > encode(1, 1000, Negative));
- EXPECT_FALSE(encode(2, 1000, Negative) >= encode(1, 1000, Negative));
-}
-
-TEST_F(DecimalTest, CompareSmallExponent)
-{
- EXPECT_TRUE(encode(1, -1000, Positive) == encode(1, -1000, Positive));
- EXPECT_FALSE(encode(1, -1000, Positive) != encode(1, -1000, Positive));
- EXPECT_FALSE(encode(1, -1000, Positive) < encode(1, -1000, Positive));
- EXPECT_TRUE(encode(1, -1000, Positive) <= encode(1, -1000, Positive));
- EXPECT_FALSE(encode(1, -1000, Positive) > encode(1, -1000, Positive));
- EXPECT_TRUE(encode(1, -1000, Positive) >= encode(1, -1000, Positive));
-
- EXPECT_TRUE(encode(1, -1000, Negative) == encode(1, -1000, Negative));
- EXPECT_FALSE(encode(1, -1000, Negative) != encode(1, -1000, Negative));
- EXPECT_FALSE(encode(1, -1000, Negative) < encode(1, -1000, Negative));
- EXPECT_TRUE(encode(1, -1000, Negative) <= encode(1, -1000, Negative));
- EXPECT_FALSE(encode(1, -1000, Negative) > encode(1, -1000, Negative));
- EXPECT_TRUE(encode(1, -1000, Negative) >= encode(1, -1000, Negative));
-
- EXPECT_FALSE(encode(2, -1000, Positive) == encode(1, -1000, Positive));
- EXPECT_TRUE(encode(2, -1000, Positive) != encode(1, -1000, Positive));
- EXPECT_FALSE(encode(2, -1000, Positive) < encode(1, -1000, Positive));
- EXPECT_FALSE(encode(2, -1000, Positive) <= encode(1, -1000, Positive));
- EXPECT_TRUE(encode(2, -1000, Positive) > encode(1, -1000, Positive));
- EXPECT_TRUE(encode(2, -1000, Positive) >= encode(1, -1000, Positive));
-
- EXPECT_FALSE(encode(2, -1000, Negative) == encode(1, -1000, Negative));
- EXPECT_TRUE(encode(2, -1000, Negative) != encode(1, -1000, Negative));
- EXPECT_TRUE(encode(2, -1000, Negative) < encode(1, -1000, Negative));
- EXPECT_TRUE(encode(2, -1000, Negative) <= encode(1, -1000, Negative));
- EXPECT_FALSE(encode(2, -1000, Negative) > encode(1, -1000, Negative));
- EXPECT_FALSE(encode(2, -1000, Negative) >= encode(1, -1000, Negative));
-}
-
-TEST_F(DecimalTest, CompareSpecialValues)
-{
- const Decimal Infinity(Decimal::infinity(Positive));
- const Decimal MinusInfinity(Decimal::infinity(Negative));
- const Decimal NaN(Decimal::nan());
- const Decimal Zero(Decimal::zero(Positive));
- const Decimal MinusZero(Decimal::zero(Negative));
- const Decimal Ten(10);
-
- EXPECT_TRUE(Zero == Zero);
- EXPECT_FALSE(Zero != Zero);
- EXPECT_FALSE(Zero < Zero);
- EXPECT_TRUE(Zero <= Zero);
- EXPECT_FALSE(Zero > Zero);
- EXPECT_TRUE(Zero >= Zero);
-
- EXPECT_TRUE(Zero == MinusZero);
- EXPECT_FALSE(Zero != MinusZero);
- EXPECT_FALSE(Zero < MinusZero);
- EXPECT_TRUE(Zero <= MinusZero);
- EXPECT_FALSE(Zero > MinusZero);
- EXPECT_TRUE(Zero >= MinusZero);
-
- EXPECT_TRUE(MinusZero == Zero);
- EXPECT_FALSE(MinusZero != Zero);
- EXPECT_FALSE(MinusZero < Zero);
- EXPECT_TRUE(MinusZero <= Zero);
- EXPECT_FALSE(MinusZero > Zero);
- EXPECT_TRUE(MinusZero >= Zero);
-
- EXPECT_TRUE(MinusZero == MinusZero);
- EXPECT_FALSE(MinusZero != MinusZero);
- EXPECT_FALSE(MinusZero < MinusZero);
- EXPECT_TRUE(MinusZero <= MinusZero);
- EXPECT_FALSE(MinusZero > MinusZero);
- EXPECT_TRUE(MinusZero >= MinusZero);
-
- EXPECT_TRUE(Infinity == Infinity);
- EXPECT_FALSE(Infinity != Infinity);
- EXPECT_FALSE(Infinity < Infinity);
- EXPECT_TRUE(Infinity <= Infinity);
- EXPECT_FALSE(Infinity > Infinity);
- EXPECT_TRUE(Infinity >= Infinity);
-
- EXPECT_FALSE(Infinity == Ten);
- EXPECT_TRUE(Infinity != Ten);
- EXPECT_FALSE(Infinity < Ten);
- EXPECT_FALSE(Infinity <= Ten);
- EXPECT_TRUE(Infinity > Ten);
- EXPECT_TRUE(Infinity >= Ten);
-
- EXPECT_FALSE(Infinity == MinusInfinity);
- EXPECT_TRUE(Infinity != MinusInfinity);
- EXPECT_FALSE(Infinity < MinusInfinity);
- EXPECT_FALSE(Infinity <= MinusInfinity);
- EXPECT_TRUE(Infinity > MinusInfinity);
- EXPECT_TRUE(Infinity >= MinusInfinity);
-
- EXPECT_FALSE(Infinity == NaN);
- EXPECT_FALSE(Infinity != NaN);
- EXPECT_FALSE(Infinity < NaN);
- EXPECT_FALSE(Infinity <= NaN);
- EXPECT_FALSE(Infinity > NaN);
- EXPECT_FALSE(Infinity >= NaN);
-
- EXPECT_FALSE(MinusInfinity == Infinity);
- EXPECT_TRUE(MinusInfinity != Infinity);
- EXPECT_TRUE(MinusInfinity < Infinity);
- EXPECT_TRUE(MinusInfinity <= Infinity);
- EXPECT_FALSE(MinusInfinity > Infinity);
- EXPECT_FALSE(MinusInfinity >= Infinity);
-
- EXPECT_FALSE(MinusInfinity == Ten);
- EXPECT_TRUE(MinusInfinity != Ten);
- EXPECT_TRUE(MinusInfinity < Ten);
- EXPECT_TRUE(MinusInfinity <= Ten);
- EXPECT_FALSE(MinusInfinity > Ten);
- EXPECT_FALSE(MinusInfinity >= Ten);
-
- EXPECT_TRUE(MinusInfinity == MinusInfinity);
- EXPECT_FALSE(MinusInfinity != MinusInfinity);
- EXPECT_FALSE(MinusInfinity < MinusInfinity);
- EXPECT_TRUE(MinusInfinity <= MinusInfinity);
- EXPECT_FALSE(MinusInfinity > MinusInfinity);
- EXPECT_TRUE(MinusInfinity >= MinusInfinity);
-
- EXPECT_FALSE(MinusInfinity == NaN);
- EXPECT_FALSE(MinusInfinity != NaN);
- EXPECT_FALSE(MinusInfinity < NaN);
- EXPECT_FALSE(MinusInfinity <= NaN);
- EXPECT_FALSE(MinusInfinity > NaN);
- EXPECT_FALSE(MinusInfinity >= NaN);
-
- EXPECT_FALSE(NaN == Infinity);
- EXPECT_FALSE(NaN != Infinity);
- EXPECT_FALSE(NaN < Infinity);
- EXPECT_FALSE(NaN <= Infinity);
- EXPECT_FALSE(NaN > Infinity);
- EXPECT_FALSE(NaN >= Infinity);
-
- EXPECT_FALSE(NaN == Ten);
- EXPECT_FALSE(NaN != Ten);
- EXPECT_FALSE(NaN < Ten);
- EXPECT_FALSE(NaN <= Ten);
- EXPECT_FALSE(NaN > Ten);
- EXPECT_FALSE(NaN >= Ten);
-
- EXPECT_FALSE(NaN == MinusInfinity);
- EXPECT_FALSE(NaN != MinusInfinity);
- EXPECT_FALSE(NaN < MinusInfinity);
- EXPECT_FALSE(NaN <= MinusInfinity);
- EXPECT_FALSE(NaN > MinusInfinity);
- EXPECT_FALSE(NaN >= MinusInfinity);
-
- EXPECT_TRUE(NaN == NaN);
- EXPECT_FALSE(NaN != NaN);
- EXPECT_FALSE(NaN < NaN);
- EXPECT_TRUE(NaN <= NaN);
- EXPECT_FALSE(NaN > NaN);
- EXPECT_TRUE(NaN >= NaN);
-}
-
-TEST_F(DecimalTest, Constructor)
-{
- EXPECT_DECIMAL_ENCODED_DATA_EQ(0u, 0, Positive, encode(0, 0, Positive));
- EXPECT_DECIMAL_ENCODED_DATA_EQ(0u, 0, Negative, encode(0, 0, Negative));
- EXPECT_DECIMAL_ENCODED_DATA_EQ(1u, 0, Positive, encode(1, 0, Positive));
- EXPECT_DECIMAL_ENCODED_DATA_EQ(1u, 0, Negative, encode(1, 0, Negative));
- EXPECT_DECIMAL_ENCODED_DATA_EQ(1u, 1022, Positive, encode(1, 1022, Positive));
- EXPECT_DECIMAL_ENCODED_DATA_EQ(1u, 1022, Negative, encode(1, 1022, Negative));
- EXPECT_DECIMAL_ENCODED_DATA_EQ(1u, 1023, Positive, encode(1, 1023, Positive));
- EXPECT_DECIMAL_ENCODED_DATA_EQ(1u, 1023, Negative, encode(1, 1023, Negative));
- EXPECT_TRUE(encode(1, 2000, Positive).isInfinity());
- EXPECT_TRUE(encode(1, 2000, Negative).isInfinity());
- EXPECT_DECIMAL_ENCODED_DATA_EQ(0u, 0, Positive, encode(1, -2000, Positive));
- EXPECT_DECIMAL_ENCODED_DATA_EQ(0u, 0, Negative, encode(1, -2000, Negative));
- EXPECT_DECIMAL_ENCODED_DATA_EQ(UINT64_C(99999999999999998), 0, Positive, encode(UINT64_C(99999999999999998), 0, Positive));
- EXPECT_DECIMAL_ENCODED_DATA_EQ(UINT64_C(99999999999999998), 0, Negative, encode(UINT64_C(99999999999999998), 0, Negative));
- EXPECT_DECIMAL_ENCODED_DATA_EQ(UINT64_C(99999999999999999), 0, Positive, encode(UINT64_C(99999999999999999), 0, Positive));
- EXPECT_DECIMAL_ENCODED_DATA_EQ(UINT64_C(99999999999999999), 0, Negative, encode(UINT64_C(99999999999999999), 0, Negative));
- EXPECT_DECIMAL_ENCODED_DATA_EQ(UINT64_C(10000000000000000), 1, Positive, encode(UINT64_C(100000000000000000), 0, Positive));
- EXPECT_DECIMAL_ENCODED_DATA_EQ(UINT64_C(10000000000000000), 1, Negative, encode(UINT64_C(100000000000000000), 0, Negative));
-}
-
-TEST_F(DecimalTest, Division)
-{
- EXPECT_EQ(encode(0, 0, Positive), Decimal(0) / Decimal(1));
- EXPECT_EQ(encode(2, 0, Negative), Decimal(2) / Decimal(-1));
- EXPECT_EQ(encode(5, -1, Negative), Decimal(-1) / Decimal(2));
- EXPECT_EQ(encode(99, 0, Positive), Decimal(99) / Decimal(1));
- EXPECT_EQ(Decimal(1), Decimal(-50) / Decimal(-50));
- EXPECT_EQ(encode(UINT64_C(3333333333333333), -16, Positive), Decimal(1) / Decimal(3));
- EXPECT_EQ(encode(UINT64_C(12345678901234), -1, Positive), encode(UINT64_C(12345678901234), 0, Positive) / Decimal(10));
-}
-
-TEST_F(DecimalTest, DivisionBigExponent)
-{
- EXPECT_EQ(encode(1, 1022, Positive), encode(1, 1022, Positive) / encode(1, 0, Positive));
- EXPECT_EQ(encode(1, 0, Positive), encode(1, 1022, Positive) / encode(1, 1022, Positive));
- EXPECT_EQ(Decimal::infinity(Positive), encode(1, 1022, Positive) / encode(1, -1000, Positive));
-}
-
-TEST_F(DecimalTest, DivisionSmallExponent)
-{
- EXPECT_EQ(encode(1, -1022, Positive), encode(1, -1022, Positive) / encode(1, 0, Positive));
- EXPECT_EQ(encode(1, 0, Positive), encode(1, -1022, Positive) / encode(1, -1022, Positive));
-}
-
-TEST_F(DecimalTest, DivisionSpecialValues)
-{
- const Decimal Infinity(Decimal::infinity(Positive));
- const Decimal MinusInfinity(Decimal::infinity(Negative));
- const Decimal NaN(Decimal::nan());
- const Decimal Zero(Decimal::zero(Positive));
- const Decimal MinusZero(Decimal::zero(Negative));
- const Decimal Ten(10);
- const Decimal MinusTen(-10);
-
- EXPECT_EQ(NaN, Zero / Zero);
- EXPECT_EQ(NaN, Zero / MinusZero);
- EXPECT_EQ(NaN, MinusZero / Zero);
- EXPECT_EQ(NaN, MinusZero / MinusZero);
-
- EXPECT_EQ(Infinity, Ten / Zero);
- EXPECT_EQ(MinusInfinity, Ten / MinusZero);
- EXPECT_EQ(MinusInfinity, MinusTen / Zero);
- EXPECT_EQ(Infinity, MinusTen / MinusZero);
-
- EXPECT_EQ(Infinity, Infinity / Zero);
- EXPECT_EQ(MinusInfinity, Infinity / MinusZero);
- EXPECT_EQ(MinusInfinity, MinusInfinity / Zero);
- EXPECT_EQ(Infinity, MinusInfinity / MinusZero);
-
- EXPECT_EQ(NaN, Infinity / Infinity);
- EXPECT_EQ(NaN, Infinity / MinusInfinity);
- EXPECT_EQ(NaN, MinusInfinity / Infinity);
- EXPECT_EQ(NaN, MinusInfinity / MinusInfinity);
-
- EXPECT_EQ(Zero, Ten / Infinity);
- EXPECT_EQ(MinusZero, Ten / MinusInfinity);
- EXPECT_EQ(MinusZero, MinusTen / Infinity);
- EXPECT_EQ(Zero, MinusTen / MinusInfinity);
-
- EXPECT_EQ(NaN, NaN / NaN);
- EXPECT_EQ(NaN, NaN / Ten);
- EXPECT_EQ(NaN, Ten / NaN);
-
- EXPECT_EQ(NaN, NaN / Infinity);
- EXPECT_EQ(NaN, NaN / MinusInfinity);
- EXPECT_EQ(NaN, Infinity / NaN);
- EXPECT_EQ(NaN, MinusInfinity / NaN);
-}
-
-TEST_F(DecimalTest, EncodedData)
-{
- EXPECT_EQ(encode(0, 0, Positive), encode(0, 0, Positive));
- EXPECT_EQ(encode(0, 0, Negative), encode(0, 0, Negative));
- EXPECT_EQ(Decimal(1), Decimal(1));
- EXPECT_EQ(encode(1, 0, Negative), encode(1, 0, Negative));
- EXPECT_EQ(Decimal::infinity(Positive), encode(1, 2000, Positive));
- EXPECT_EQ(Decimal::zero(Positive), encode(1, -2000, Positive));
-}
-
-TEST_F(DecimalTest, Floor)
-{
- EXPECT_EQ(Decimal(1), Decimal(1).floor());
- EXPECT_EQ(Decimal(0), encode(1, -10, Positive).floor());
- EXPECT_EQ(Decimal(1), encode(11, -1, Positive).floor());
- EXPECT_EQ(Decimal(1), encode(13, -1, Positive).floor());
- EXPECT_EQ(Decimal(1), encode(15, -1, Positive).floor());
- EXPECT_EQ(Decimal(1), encode(19, -1, Positive).floor());
-
- EXPECT_EQ(Decimal(-1), Decimal(-1).floor());
- EXPECT_EQ(Decimal(-1), encode(1, -10, Negative).floor());
- EXPECT_EQ(Decimal(-2), encode(11, -1, Negative).floor());
- EXPECT_EQ(Decimal(-2), encode(13, -1, Negative).floor());
- EXPECT_EQ(Decimal(-2), encode(15, -1, Negative).floor());
- EXPECT_EQ(Decimal(-2), encode(19, -1, Negative).floor());
-}
-
-TEST_F(DecimalTest, FloorBigExponent)
-{
- EXPECT_EQ(encode(1, 1000, Positive), encode(1, 1000, Positive).floor());
- EXPECT_EQ(encode(1, 1000, Negative), encode(1, 1000, Negative).floor());
-}
-
-TEST_F(DecimalTest, FloorSmallExponent)
-{
- EXPECT_EQ(encode(0, 0, Positive), encode(1, -1000, Positive).floor());
- EXPECT_EQ(encode(1, 0, Negative), encode(1, -1000, Negative).floor());
-}
-
-TEST_F(DecimalTest, FloorSpecialValues)
-{
- EXPECT_EQ(Decimal::infinity(Positive), Decimal::infinity(Positive).floor());
- EXPECT_EQ(Decimal::infinity(Negative), Decimal::infinity(Negative).floor());
- EXPECT_EQ(Decimal::nan(), Decimal::nan().floor());
-}
-
-TEST_F(DecimalTest, FromDouble)
-{
- EXPECT_EQ(encode(0, 0, Positive), Decimal::fromDouble(0.0));
- EXPECT_EQ(encode(0, 0, Negative), Decimal::fromDouble(-0.0));
- EXPECT_EQ(encode(1, 0, Positive), Decimal::fromDouble(1));
- EXPECT_EQ(encode(1, 0, Negative), Decimal::fromDouble(-1));
- EXPECT_EQ(encode(123, 0, Positive), Decimal::fromDouble(123));
- EXPECT_EQ(encode(123, 0, Negative), Decimal::fromDouble(-123));
- EXPECT_EQ(encode(1, -1, Positive), Decimal::fromDouble(0.1));
- EXPECT_EQ(encode(1, -1, Negative), Decimal::fromDouble(-0.1));
-}
-
-TEST_F(DecimalTest, FromDoubleLimits)
-{
- EXPECT_EQ(encode(UINT64_C(2220446049250313), -31, Positive), Decimal::fromDouble(std::numeric_limits<double>::epsilon()));
- EXPECT_EQ(encode(UINT64_C(2220446049250313), -31, Negative), Decimal::fromDouble(-std::numeric_limits<double>::epsilon()));
- EXPECT_EQ(encode(UINT64_C(17976931348623157), 292, Positive), Decimal::fromDouble(std::numeric_limits<double>::max()));
- EXPECT_EQ(encode(UINT64_C(17976931348623157), 292, Negative), Decimal::fromDouble(-std::numeric_limits<double>::max()));
- EXPECT_EQ(encode(UINT64_C(22250738585072014), -324, Positive), Decimal::fromDouble(std::numeric_limits<double>::min()));
- EXPECT_EQ(encode(UINT64_C(22250738585072014), -324, Negative), Decimal::fromDouble(-std::numeric_limits<double>::min()));
- EXPECT_TRUE(Decimal::fromDouble(std::numeric_limits<double>::infinity()).isInfinity());
- EXPECT_TRUE(Decimal::fromDouble(-std::numeric_limits<double>::infinity()).isInfinity());
- EXPECT_TRUE(Decimal::fromDouble(std::numeric_limits<double>::quiet_NaN()).isNaN());
- EXPECT_TRUE(Decimal::fromDouble(-std::numeric_limits<double>::quiet_NaN()).isNaN());
-}
-
-TEST_F(DecimalTest, FromInt32)
-{
- EXPECT_EQ(encode(0, 0, Positive), Decimal(0));
- EXPECT_EQ(encode(1, 0, Positive), Decimal(1));
- EXPECT_EQ(encode(1, 0, Negative), Decimal(-1));
- EXPECT_EQ(encode(100, 0, Positive), Decimal(100));
- EXPECT_EQ(encode(100, 0, Negative), Decimal(-100));
- EXPECT_EQ(encode(0x7FFFFFFF, 0, Positive), Decimal(std::numeric_limits<int32_t>::max()));
- EXPECT_EQ(encode(0x80000000u, 0, Negative), Decimal(std::numeric_limits<int32_t>::min()));
-}
-
-TEST_F(DecimalTest, FromString)
-{
- EXPECT_EQ(encode(0, 0, Positive), fromString("0"));
- EXPECT_EQ(encode(0, 0, Negative), fromString("-0"));
- EXPECT_EQ(Decimal(1), fromString("1"));
- EXPECT_EQ(encode(1, 0, Negative), fromString("-1"));
- EXPECT_EQ(Decimal(1), fromString("01"));
- EXPECT_EQ(encode(3, 0, Positive), fromString("+3"));
- EXPECT_EQ(encode(0, 3, Positive), fromString("0E3"));
- EXPECT_EQ(encode(5, -1, Positive), fromString(".5"));
- EXPECT_EQ(encode(100, 0, Positive), fromString("100"));
- EXPECT_EQ(encode(100, 0, Negative), fromString("-100"));
- EXPECT_EQ(encode(123, -2, Positive), fromString("1.23"));
- EXPECT_EQ(encode(123, -2, Negative), fromString("-1.23"));
- EXPECT_EQ(encode(123, 8, Positive), fromString("1.23E10"));
- EXPECT_EQ(encode(123, 8, Negative), fromString("-1.23E10"));
- EXPECT_EQ(encode(123, 8, Positive), fromString("1.23E+10"));
- EXPECT_EQ(encode(123, 8, Negative), fromString("-1.23E+10"));
- EXPECT_EQ(encode(123, -12, Positive), fromString("1.23E-10"));
- EXPECT_EQ(encode(123, -12, Negative), fromString("-1.23E-10"));
- EXPECT_EQ(encode(5, -7, Positive), fromString("0.0000005"));
- EXPECT_EQ(encode(0, 0, Positive), fromString("0e9999"));
- EXPECT_EQ(encode(123, -3, Positive), fromString("0.123"));
- EXPECT_EQ(encode(0, -2, Positive), fromString("00.00"));
- EXPECT_EQ(encode(1, 2, Positive), fromString("1E2"));
- EXPECT_EQ(Decimal::infinity(Positive), fromString("1E20000"));
- EXPECT_EQ(Decimal::zero(Positive), fromString("1E-20000"));
- EXPECT_EQ(encode(1000, 1023, Positive), fromString("1E1026"));
- EXPECT_EQ(Decimal::zero(Positive), fromString("1E-1026"));
- EXPECT_EQ(Decimal::infinity(Positive), fromString("1234567890E1036"));
-
- // 2^1024
- const uint64_t leadingDigitsOf2PowerOf1024 = UINT64_C(17976931348623159);
- EXPECT_EQ(encode(leadingDigitsOf2PowerOf1024, 292, Positive), fromString("179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477322407536021120113879871393357658789768814416622492847430639474124377767893424865485276302219601246094119453082952085005768838150682342462881473913110540827237163350510684586298239947245938479716304835356329624224137216"));
-}
-
-// These strings are look like proper number, but we don't accept them.
-TEST_F(DecimalTest, FromStringLikeNumber)
-{
- EXPECT_EQ(Decimal::nan(), fromString(" 123 "));
- EXPECT_EQ(Decimal::nan(), fromString("1,234"));
-}
-
-// fromString doesn't support infinity and NaN.
-TEST_F(DecimalTest, FromStringSpecialValues)
-{
- EXPECT_EQ(Decimal::nan(), fromString("INF"));
- EXPECT_EQ(Decimal::nan(), fromString("Infinity"));
- EXPECT_EQ(Decimal::nan(), fromString("infinity"));
- EXPECT_EQ(Decimal::nan(), fromString("+Infinity"));
- EXPECT_EQ(Decimal::nan(), fromString("+infinity"));
- EXPECT_EQ(Decimal::nan(), fromString("-Infinity"));
- EXPECT_EQ(Decimal::nan(), fromString("-infinity"));
- EXPECT_EQ(Decimal::nan(), fromString("NaN"));
- EXPECT_EQ(Decimal::nan(), fromString("nan"));
- EXPECT_EQ(Decimal::nan(), fromString("+NaN"));
- EXPECT_EQ(Decimal::nan(), fromString("+nan"));
- EXPECT_EQ(Decimal::nan(), fromString("-NaN"));
- EXPECT_EQ(Decimal::nan(), fromString("-nan"));
-}
-
-TEST_F(DecimalTest, fromStringTruncated)
-{
- EXPECT_EQ(Decimal::nan(), fromString("x"));
- EXPECT_EQ(Decimal::nan(), fromString("0."));
- EXPECT_EQ(Decimal::nan(), fromString("1x"));
-
- EXPECT_EQ(Decimal::nan(), fromString("1Ex"));
- EXPECT_EQ(Decimal::nan(), fromString("1E2x"));
- EXPECT_EQ(Decimal::nan(), fromString("1E+x"));
-}
-
-TEST_F(DecimalTest, Multiplication)
-{
- EXPECT_EQ(encode(0, 0, Positive), Decimal(0) * Decimal(0));
- EXPECT_EQ(encode(2, 0, Negative), Decimal(2) * Decimal(-1));
- EXPECT_EQ(encode(2, 0, Negative), Decimal(-1) * Decimal(2));
- EXPECT_EQ(encode(99, 0, Positive), Decimal(99) * Decimal(1));
- EXPECT_EQ(encode(2500, 0, Positive), Decimal(-50) * Decimal(-50));
- EXPECT_EQ(encode(1, 21, Positive), encode(UINT64_C(10000000000), 0, Positive) * encode(UINT64_C(100000000000), 0, Positive));
-}
-
-TEST_F(DecimalTest, MultiplicationBigExponent)
-{
- EXPECT_EQ(encode(1, 1022, Positive), encode(1, 1022, Positive) * encode(1, 0, Positive));
- EXPECT_EQ(Decimal::infinity(Positive), encode(1, 1022, Positive) * encode(1, 1022, Positive));
- EXPECT_EQ(encode(1, 22, Positive), encode(1, 1022, Positive) * encode(1, -1000, Positive));
-}
-
-TEST_F(DecimalTest, MultiplicationSmallExponent)
-{
- EXPECT_EQ(encode(1, -1022, Positive), encode(1, -1022, Positive) * encode(1, 0, Positive));
- EXPECT_EQ(encode(0, 0, Positive), encode(1, -1022, Positive) * encode(1, -1022, Positive));
-}
-
-TEST_F(DecimalTest, MultiplicationSpecialValues)
-{
- const Decimal Infinity(Decimal::infinity(Positive));
- const Decimal MinusInfinity(Decimal::infinity(Negative));
- const Decimal NaN(Decimal::nan());
- const Decimal Ten(10);
- const Decimal MinusTen(-10);
- const Decimal Zero(Decimal::zero(Positive));
- const Decimal MinusZero(Decimal::zero(Negative));
-
- EXPECT_EQ(Infinity, Infinity * Infinity);
- EXPECT_EQ(MinusInfinity, Infinity * MinusInfinity);
- EXPECT_EQ(MinusInfinity, MinusInfinity * Infinity);
- EXPECT_EQ(Infinity, MinusInfinity * MinusInfinity);
-
- EXPECT_EQ(NaN, Infinity * Zero);
- EXPECT_EQ(NaN, Zero * MinusInfinity);
- EXPECT_EQ(NaN, MinusInfinity * Zero);
- EXPECT_EQ(NaN, MinusInfinity * Zero);
-
- EXPECT_EQ(NaN, Infinity * MinusZero);
- EXPECT_EQ(NaN, MinusZero * MinusInfinity);
- EXPECT_EQ(NaN, MinusInfinity * MinusZero);
- EXPECT_EQ(NaN, MinusInfinity * MinusZero);
-
- EXPECT_EQ(Infinity, Infinity * Ten);
- EXPECT_EQ(Infinity, Ten * Infinity);
- EXPECT_EQ(MinusInfinity, MinusInfinity * Ten);
- EXPECT_EQ(MinusInfinity, Ten * MinusInfinity);
-
- EXPECT_EQ(MinusInfinity, Infinity * MinusTen);
- EXPECT_EQ(MinusInfinity, MinusTen * Infinity);
- EXPECT_EQ(Infinity, MinusInfinity * MinusTen);
- EXPECT_EQ(Infinity, MinusTen * MinusInfinity);
-
- EXPECT_EQ(NaN, NaN * NaN);
- EXPECT_EQ(NaN, NaN * Ten);
- EXPECT_EQ(NaN, Ten * NaN);
-
- EXPECT_EQ(NaN, NaN * Infinity);
- EXPECT_EQ(NaN, NaN * MinusInfinity);
- EXPECT_EQ(NaN, Infinity * NaN);
- EXPECT_EQ(NaN, MinusInfinity * NaN);
-}
-
-TEST_F(DecimalTest, Negate)
-{
- EXPECT_EQ(encode(0, 0, Negative), -encode(0, 0, Positive));
- EXPECT_EQ(encode(0, 0, Positive), -encode(0, 0, Negative));
-
- EXPECT_EQ(encode(0, 10, Negative), -encode(0, 10, Positive));
- EXPECT_EQ(encode(0, 10, Positive), -encode(0, 10, Negative));
-
- EXPECT_EQ(encode(0, -10, Negative), -encode(0, -10, Positive));
- EXPECT_EQ(encode(0, -10, Positive), -encode(0, -10, Negative));
-
- EXPECT_EQ(encode(1, 0, Negative), -encode(1, 0, Positive));
- EXPECT_EQ(encode(1, 0, Positive), -encode(1, 0, Negative));
-
- EXPECT_EQ(encode(1, 10, Negative), -encode(1, 10, Positive));
- EXPECT_EQ(encode(1, 10, Positive), -encode(1, 10, Negative));
-
- EXPECT_EQ(encode(1, -10, Negative), -encode(1, -10, Positive));
- EXPECT_EQ(encode(1, -10, Positive), -encode(1, -10, Negative));
-}
-
-TEST_F(DecimalTest, NegateBigExponent)
-{
- EXPECT_EQ(encode(1, 1000, Negative), -encode(1, 1000, Positive));
- EXPECT_EQ(encode(1, 1000, Positive), -encode(1, 1000, Negative));
-}
-
-TEST_F(DecimalTest, NegateSmallExponent)
-{
- EXPECT_EQ(encode(1, -1000, Negative), -encode(1, -1000, Positive));
- EXPECT_EQ(encode(1, -1000, Positive), -encode(1, -1000, Negative));
-}
-
-TEST_F(DecimalTest, NegateSpecialValues)
-{
- EXPECT_EQ(Decimal::infinity(Negative), -Decimal::infinity(Positive));
- EXPECT_EQ(Decimal::infinity(Positive), -Decimal::infinity(Negative));
- EXPECT_EQ(Decimal::nan(), -Decimal::nan());
-}
-
-TEST_F(DecimalTest, Predicates)
-{
- EXPECT_TRUE(Decimal::zero(Positive).isFinite());
- EXPECT_FALSE(Decimal::zero(Positive).isInfinity());
- EXPECT_FALSE(Decimal::zero(Positive).isNaN());
- EXPECT_TRUE(Decimal::zero(Positive).isPositive());
- EXPECT_FALSE(Decimal::zero(Positive).isNegative());
- EXPECT_FALSE(Decimal::zero(Positive).isSpecial());
- EXPECT_TRUE(Decimal::zero(Positive).isZero());
-
- EXPECT_TRUE(Decimal::zero(Negative).isFinite());
- EXPECT_FALSE(Decimal::zero(Negative).isInfinity());
- EXPECT_FALSE(Decimal::zero(Negative).isNaN());
- EXPECT_FALSE(Decimal::zero(Negative).isPositive());
- EXPECT_TRUE(Decimal::zero(Negative).isNegative());
- EXPECT_FALSE(Decimal::zero(Negative).isSpecial());
- EXPECT_TRUE(Decimal::zero(Negative).isZero());
-
- EXPECT_TRUE(Decimal(123).isFinite());
- EXPECT_FALSE(Decimal(123).isInfinity());
- EXPECT_FALSE(Decimal(123).isNaN());
- EXPECT_TRUE(Decimal(123).isPositive());
- EXPECT_FALSE(Decimal(123).isNegative());
- EXPECT_FALSE(Decimal(123).isSpecial());
- EXPECT_FALSE(Decimal(123).isZero());
-
- EXPECT_TRUE(Decimal(-123).isFinite());
- EXPECT_FALSE(Decimal(-123).isInfinity());
- EXPECT_FALSE(Decimal(-123).isNaN());
- EXPECT_FALSE(Decimal(-123).isPositive());
- EXPECT_TRUE(Decimal(-123).isNegative());
- EXPECT_FALSE(Decimal(-123).isSpecial());
- EXPECT_FALSE(Decimal(-123).isZero());
-}
-
-TEST_F(DecimalTest, PredicatesSpecialValues)
-{
- EXPECT_FALSE(Decimal::infinity(Positive).isFinite());
- EXPECT_TRUE(Decimal::infinity(Positive).isInfinity());
- EXPECT_FALSE(Decimal::infinity(Positive).isNaN());
- EXPECT_TRUE(Decimal::infinity(Positive).isPositive());
- EXPECT_FALSE(Decimal::infinity(Positive).isNegative());
- EXPECT_TRUE(Decimal::infinity(Positive).isSpecial());
- EXPECT_FALSE(Decimal::infinity(Positive).isZero());
-
- EXPECT_FALSE(Decimal::infinity(Negative).isFinite());
- EXPECT_TRUE(Decimal::infinity(Negative).isInfinity());
- EXPECT_FALSE(Decimal::infinity(Negative).isNaN());
- EXPECT_FALSE(Decimal::infinity(Negative).isPositive());
- EXPECT_TRUE(Decimal::infinity(Negative).isNegative());
- EXPECT_TRUE(Decimal::infinity(Negative).isSpecial());
- EXPECT_FALSE(Decimal::infinity(Negative).isZero());
-
- EXPECT_FALSE(Decimal::nan().isFinite());
- EXPECT_FALSE(Decimal::nan().isInfinity());
- EXPECT_TRUE(Decimal::nan().isNaN());
- EXPECT_TRUE(Decimal::nan().isSpecial());
- EXPECT_FALSE(Decimal::nan().isZero());
-}
-
-// LayoutTests/fast/forms/number/number-stepup-stepdown-from-renderer
-TEST_F(DecimalTest, RealWorldExampleNumberStepUpStepDownFromRenderer)
-{
- EXPECT_DECIMAL_STREQ("10", stepDown("0", "100", "10", "19", 1));
- EXPECT_DECIMAL_STREQ("90", stepUp("0", "99", "10", "89", 1));
- EXPECT_DECIMAL_STREQ("1", stepUp("0", "1", "0.33333333333333333", "0", 3)); // step=1/3
- EXPECT_DECIMAL_STREQ("0.01", stepUp("0", "0.01", "0.0033333333333333333", "0", 3)); // step=1/300
- EXPECT_DECIMAL_STREQ("1", stepUp("0", "1", "0.003921568627450980", "0", 255)); // step=1/255
- EXPECT_DECIMAL_STREQ("1", stepUp("0", "1", "0.1", "0", 10));
-}
-
-TEST_F(DecimalTest, RealWorldExampleNumberStepUpStepDownFromRendererRounding)
-{
- EXPECT_DECIMAL_STREQ("5.015", stepUp("0", "100", "0.005", "5.005", 2));
- EXPECT_DECIMAL_STREQ("5.06", stepUp("0", "100", "0.005", "5.005", 11));
- EXPECT_DECIMAL_STREQ("5.065", stepUp("0", "100", "0.005", "5.005", 12));
-
- EXPECT_DECIMAL_STREQ("5.015", stepUp("4", "9", "0.005", "5.005", 2));
- EXPECT_DECIMAL_STREQ("5.06", stepUp("4", "9", "0.005", "5.005", 11));
- EXPECT_DECIMAL_STREQ("5.065", stepUp("4", "9", "0.005", "5.005", 12));
-}
-
-TEST_F(DecimalTest, RealWorldExampleRangeStepUpStepDown)
-{
- EXPECT_DECIMAL_STREQ("1e+38", stepUp("0", "1E38", "1", "1E38", 9));
- EXPECT_DECIMAL_STREQ("1e+38", stepDown("0", "1E38", "1", "1E38", 9));
-}
-
-TEST_F(DecimalTest, Remainder)
-{
- EXPECT_EQ(encode(21, -1, Positive), encode(21, -1, Positive).remainder(3));
- EXPECT_EQ(Decimal(1), Decimal(10).remainder(3));
- EXPECT_EQ(Decimal(1), Decimal(10).remainder(-3));
- EXPECT_EQ(encode(1, 0, Negative), Decimal(-10).remainder(3));
- EXPECT_EQ(Decimal(-1), Decimal(-10).remainder(-3));
- EXPECT_EQ(encode(2, -1, Positive), encode(102, -1, Positive).remainder(1));
- EXPECT_EQ(encode(1, -1, Positive), Decimal(10).remainder(encode(3, -1, Positive)));
- EXPECT_EQ(Decimal(1), encode(36, -1, Positive).remainder(encode(13, -1, Positive)));
- EXPECT_EQ(encode(1, 87, Positive), (encode(1234, 100, Positive).remainder(Decimal(3))));
- EXPECT_EQ(Decimal(500), (Decimal(500).remainder(1000)));
- EXPECT_EQ(Decimal(-500), (Decimal(-500).remainder(1000)));
-}
-
-TEST_F(DecimalTest, RemainderBigExponent)
-{
- EXPECT_EQ(encode(0, 1022, Positive), encode(1, 1022, Positive).remainder(encode(1, 0, Positive)));
- EXPECT_EQ(encode(0, 1022, Positive), encode(1, 1022, Positive).remainder(encode(1, 1022, Positive)));
- EXPECT_EQ(Decimal::infinity(Positive), encode(1, 1022, Positive).remainder(encode(1, -1000, Positive)));
-}
-
-TEST_F(DecimalTest, RemainderSmallExponent)
-{
- EXPECT_EQ(encode(1, -1022, Positive), encode(1, -1022, Positive).remainder(encode(1, 0, Positive)));
- EXPECT_EQ(encode(0, -1022, Positive), encode(1, -1022, Positive).remainder(encode(1, -1022, Positive)));
-}
-
-TEST_F(DecimalTest, RemainderSpecialValues)
-{
- EXPECT_EQ(Decimal::infinity(Positive), Decimal::infinity(Positive).remainder(1));
- EXPECT_EQ(Decimal::infinity(Negative), Decimal::infinity(Negative).remainder(1));
- EXPECT_EQ(Decimal::nan(), Decimal::nan().remainder(1));
-
- EXPECT_EQ(Decimal::infinity(Negative), Decimal::infinity(Positive).remainder(-1));
- EXPECT_EQ(Decimal::infinity(Positive), Decimal::infinity(Negative).remainder(-1));
- EXPECT_EQ(Decimal::nan(), Decimal::nan().remainder(-1));
-
- EXPECT_EQ(Decimal::infinity(Positive), Decimal::infinity(Positive).remainder(3));
- EXPECT_EQ(Decimal::infinity(Negative), Decimal::infinity(Negative).remainder(3));
- EXPECT_EQ(Decimal::nan(), Decimal::nan().remainder(3));
-
- EXPECT_EQ(Decimal::infinity(Negative), Decimal::infinity(Positive).remainder(-1));
- EXPECT_EQ(Decimal::infinity(Positive), Decimal::infinity(Negative).remainder(-1));
- EXPECT_EQ(Decimal::nan(), Decimal::nan().remainder(-1));
-
- EXPECT_EQ(Decimal::nan(), Decimal(1).remainder(Decimal::infinity(Positive)));
- EXPECT_EQ(Decimal::nan(), Decimal(1).remainder(Decimal::infinity(Negative)));
- EXPECT_EQ(Decimal::nan(), Decimal(1).remainder(Decimal::nan()));
-}
-
-TEST_F(DecimalTest, Round)
-{
- EXPECT_EQ(Decimal(1), (Decimal(9) / Decimal(10)).round());
- EXPECT_EQ(Decimal(25), (Decimal(5) / fromString("0.200")).round());
- EXPECT_EQ(Decimal(3), (Decimal(5) / Decimal(2)).round());
- EXPECT_EQ(Decimal(1), (Decimal(2) / Decimal(3)).round());
- EXPECT_EQ(Decimal(3), (Decimal(10) / Decimal(3)).round());
- EXPECT_EQ(Decimal(3), (Decimal(1) / fromString("0.3")).round());
- EXPECT_EQ(Decimal(10), (Decimal(1) / fromString("0.1")).round());
- EXPECT_EQ(Decimal(5), (Decimal(1) / fromString("0.2")).round());
- EXPECT_EQ(Decimal(10), (fromString("10.2") / 1).round());
- EXPECT_EQ(encode(1234, 100, Positive), encode(1234, 100, Positive).round());
-}
-
-TEST_F(DecimalTest, RoundSpecialValues)
-{
- EXPECT_EQ(Decimal::infinity(Positive), Decimal::infinity(Positive).round());
- EXPECT_EQ(Decimal::infinity(Negative), Decimal::infinity(Negative).round());
- EXPECT_EQ(Decimal::nan(), Decimal::nan().round());
-}
-
-TEST_F(DecimalTest, Subtract)
-{
- EXPECT_EQ(encode(0, 0, Positive), Decimal(0) - Decimal(0));
- EXPECT_EQ(encode(3, 0, Positive), Decimal(2) - Decimal(-1));
- EXPECT_EQ(encode(3, 0, Negative), Decimal(-1) - Decimal(2));
- EXPECT_EQ(encode(98, 0, Positive), Decimal(99) - Decimal(1));
- EXPECT_EQ(encode(0, 0, Positive), Decimal(-50) - Decimal(-50));
- EXPECT_EQ(encode(UINT64_C(1000000000000000), 35, Positive), encode(1, 50, Positive) - Decimal(1));
- EXPECT_EQ(encode(UINT64_C(1000000000000000), 35, Negative), Decimal(1) - encode(1, 50, Positive));
-}
-
-TEST_F(DecimalTest, SubtractBigExponent)
-{
- EXPECT_EQ(encode(1, 1022, Positive), encode(1, 1022, Positive) - encode(1, 0, Positive));
- EXPECT_EQ(encode(0, 0, Positive), encode(1, 1022, Positive) - encode(1, 1022, Positive));
- EXPECT_EQ(encode(1, 1022, Positive), encode(1, 1022, Positive) + encode(1, -1000, Positive));
-}
-
-TEST_F(DecimalTest, SubtractSmallExponent)
-{
- EXPECT_EQ(encode(UINT64_C(10000000000000000), -16, Negative), encode(1, -1022, Positive) - encode(1, 0, Positive));
- EXPECT_EQ(encode(0, 0, Positive), encode(1, -1022, Positive) - encode(1, -1022, Positive));
-}
-
-TEST_F(DecimalTest, SubtractSpecialValues)
-{
- const Decimal Infinity(Decimal::infinity(Positive));
- const Decimal MinusInfinity(Decimal::infinity(Negative));
- const Decimal NaN(Decimal::nan());
- const Decimal Ten(10);
-
- EXPECT_EQ(NaN, Infinity - Infinity);
- EXPECT_EQ(Infinity, Infinity - MinusInfinity);
- EXPECT_EQ(MinusInfinity, MinusInfinity - Infinity);
- EXPECT_EQ(NaN, MinusInfinity - MinusInfinity);
-
- EXPECT_EQ(Infinity, Infinity - Ten);
- EXPECT_EQ(MinusInfinity, Ten - Infinity);
- EXPECT_EQ(MinusInfinity, MinusInfinity - Ten);
- EXPECT_EQ(Infinity, Ten - MinusInfinity);
-
- EXPECT_EQ(NaN, NaN - NaN);
- EXPECT_EQ(NaN, NaN - Ten);
- EXPECT_EQ(NaN, Ten - NaN);
-
- EXPECT_EQ(NaN, NaN - Infinity);
- EXPECT_EQ(NaN, NaN - MinusInfinity);
- EXPECT_EQ(NaN, Infinity - NaN);
- EXPECT_EQ(NaN, MinusInfinity - NaN);
-}
-
-TEST_F(DecimalTest, ToDouble)
-{
- EXPECT_EQ(0.0, encode(0, 0, Positive).toDouble());
- EXPECT_EQ(-0.0, encode(0, 0, Negative).toDouble());
-
- EXPECT_EQ(1.0, encode(1, 0, Positive).toDouble());
- EXPECT_EQ(-1.0, encode(1, 0, Negative).toDouble());
-
- EXPECT_EQ(0.1, encode(1, -1, Positive).toDouble());
- EXPECT_EQ(-0.1, encode(1, -1, Negative).toDouble());
- EXPECT_EQ(0.3, encode(3, -1, Positive).toDouble());
- EXPECT_EQ(-0.3, encode(3, -1, Negative).toDouble());
- EXPECT_EQ(0.6, encode(6, -1, Positive).toDouble());
- EXPECT_EQ(-0.6, encode(6, -1, Negative).toDouble());
- EXPECT_EQ(0.7, encode(7, -1, Positive).toDouble());
- EXPECT_EQ(-0.7, encode(7, -1, Negative).toDouble());
-
- EXPECT_EQ(0.01, encode(1, -2, Positive).toDouble());
- EXPECT_EQ(0.001, encode(1, -3, Positive).toDouble());
- EXPECT_EQ(0.0001, encode(1, -4, Positive).toDouble());
- EXPECT_EQ(0.00001, encode(1, -5, Positive).toDouble());
-
- EXPECT_EQ(1e+308, encode(1, 308, Positive).toDouble());
- EXPECT_EQ(1e-307, encode(1, -307, Positive).toDouble());
-
- EXPECT_TRUE(std::isinf(encode(1, 1000, Positive).toDouble()));
- EXPECT_EQ(0.0, encode(1, -1000, Positive).toDouble());
-}
-
-TEST_F(DecimalTest, ToDoubleSpecialValues)
-{
- EXPECT_TRUE(std::isinf(Decimal::infinity(Decimal::Positive).toDouble()));
- EXPECT_TRUE(std::isinf(Decimal::infinity(Decimal::Negative).toDouble()));
- EXPECT_TRUE(std::isnan(Decimal::nan().toDouble()));
-}
-
-TEST_F(DecimalTest, ToString)
-{
- EXPECT_DECIMAL_STREQ("0", Decimal::zero(Positive));
- EXPECT_DECIMAL_STREQ("-0", Decimal::zero(Negative));
- EXPECT_DECIMAL_STREQ("1", Decimal(1));
- EXPECT_DECIMAL_STREQ("-1", Decimal(-1));
- EXPECT_DECIMAL_STREQ("1234567", Decimal(1234567));
- EXPECT_DECIMAL_STREQ("-1234567", Decimal(-1234567));
- EXPECT_DECIMAL_STREQ("0.5", encode(5, -1, Positive));
- EXPECT_DECIMAL_STREQ("-0.5", encode(5, -1, Negative));
- EXPECT_DECIMAL_STREQ("12.345", encode(12345, -3, Positive));
- EXPECT_DECIMAL_STREQ("-12.345", encode(12345, -3, Negative));
- EXPECT_DECIMAL_STREQ("0.12345", encode(12345, -5, Positive));
- EXPECT_DECIMAL_STREQ("-0.12345", encode(12345, -5, Negative));
- EXPECT_DECIMAL_STREQ("50", encode(50, 0, Positive));
- EXPECT_DECIMAL_STREQ("-50", encode(50, 0, Negative));
- EXPECT_DECIMAL_STREQ("5e+1", encode(5, 1, Positive));
- EXPECT_DECIMAL_STREQ("-5e+1", encode(5, 1, Negative));
- EXPECT_DECIMAL_STREQ("5.678e+103", encode(5678, 100, Positive));
- EXPECT_DECIMAL_STREQ("-5.678e+103", encode(5678, 100, Negative));
- EXPECT_DECIMAL_STREQ("5.678e-97", encode(5678, -100, Positive));
- EXPECT_DECIMAL_STREQ("-5.678e-97", encode(5678, -100, Negative));
- EXPECT_DECIMAL_STREQ("8639999913600001", encode(UINT64_C(8639999913600001), 0, Positive));
- EXPECT_DECIMAL_STREQ("9007199254740991", encode((static_cast<uint64_t>(1) << DBL_MANT_DIG) - 1, 0, Positive));
- EXPECT_DECIMAL_STREQ("99999999999999999", encode(UINT64_C(99999999999999999), 0, Positive));
- EXPECT_DECIMAL_STREQ("9.9999999999999999e+17", encode(UINT64_C(99999999999999999), 1, Positive));
- EXPECT_DECIMAL_STREQ("9.9999999999999999e+18", encode(UINT64_C(99999999999999999), 2, Positive));
- EXPECT_DECIMAL_STREQ("1e+16", encode(UINT64_C(99999999999999999), -1, Positive));
- EXPECT_DECIMAL_STREQ("1000000000000000", encode(UINT64_C(99999999999999999), -2, Positive));
- EXPECT_DECIMAL_STREQ("1", encode(UINT64_C(99999999999999999), -17, Positive));
- EXPECT_DECIMAL_STREQ("0.001", encode(UINT64_C(99999999999999999), -20, Positive));
- EXPECT_DECIMAL_STREQ("1e-83", encode(UINT64_C(99999999999999999), -100, Positive));
-}
-
-TEST_F(DecimalTest, ToStringSpecialValues)
-{
- EXPECT_DECIMAL_STREQ("Infinity", Decimal::infinity(Positive));
- EXPECT_DECIMAL_STREQ("-Infinity", Decimal::infinity(Negative));
- EXPECT_DECIMAL_STREQ("NaN", Decimal::nan());
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/DragData.cpp b/chromium/third_party/WebKit/Source/core/platform/DragData.cpp
deleted file mode 100644
index ce0d1425355..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/DragData.cpp
+++ /dev/null
@@ -1,175 +0,0 @@
-/*
- * Copyright (C) 2007 Apple Inc. All rights reserved.
- * Copyright (C) 2013 Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/DragData.h"
-
-#include "core/dom/Document.h"
-#include "core/dom/DocumentFragment.h"
-#include "core/dom/Range.h"
-#include "core/editing/markup.h"
-#include "core/page/Frame.h"
-#include "core/platform/FileSystem.h"
-#include "core/platform/chromium/ChromiumDataObject.h"
-#include "core/platform/chromium/ClipboardMimeTypes.h"
-#include "modules/filesystem/DraggedIsolatedFileSystem.h"
-#include "weborigin/KURL.h"
-#include "wtf/text/WTFString.h"
-
-#include "public/platform/Platform.h"
-#include "public/platform/WebFileUtilities.h"
-
-namespace WebCore {
-
-DragData::DragData(ChromiumDataObject* data, const IntPoint& clientPosition, const IntPoint& globalPosition,
- DragOperation sourceOperationMask, DragApplicationFlags flags)
- : m_clientPosition(clientPosition)
- , m_globalPosition(globalPosition)
- , m_platformDragData(data)
- , m_draggingSourceOperationMask(sourceOperationMask)
- , m_applicationFlags(flags)
-{
-}
-
-DragData::DragData(const String&, const IntPoint& clientPosition, const IntPoint& globalPosition,
- DragOperation sourceOperationMask, DragApplicationFlags flags)
- : m_clientPosition(clientPosition)
- , m_globalPosition(globalPosition)
- , m_platformDragData(0)
- , m_draggingSourceOperationMask(sourceOperationMask)
- , m_applicationFlags(flags)
-{
-}
-
-static bool containsHTML(const ChromiumDataObject* dropData)
-{
- return dropData->types().contains(mimeTypeTextHTML);
-}
-
-bool DragData::containsURL(Frame*, FilenameConversionPolicy filenamePolicy) const
-{
- return m_platformDragData->types().contains(mimeTypeTextURIList)
- || (filenamePolicy == ConvertFilenames && m_platformDragData->containsFilenames());
-}
-
-String DragData::asURL(Frame*, FilenameConversionPolicy filenamePolicy, String* title) const
-{
- String url;
- if (m_platformDragData->types().contains(mimeTypeTextURIList))
- m_platformDragData->urlAndTitle(url, title);
- else if (filenamePolicy == ConvertFilenames && containsFiles())
- url = KURL(WebKit::Platform::current()->fileUtilities()->filePathToURL(m_platformDragData->filenames()[0]));
- return url;
-}
-
-bool DragData::containsFiles() const
-{
- return m_platformDragData->containsFilenames();
-}
-
-unsigned DragData::numberOfFiles() const
-{
- return m_platformDragData->filenames().size();
-}
-
-int DragData::modifierKeyState() const
-{
- return m_platformDragData->modifierKeyState();
-}
-
-void DragData::asFilenames(Vector<String>& result) const
-{
- const Vector<String>& filenames = m_platformDragData->filenames();
- for (size_t i = 0; i < filenames.size(); ++i)
- result.append(filenames[i]);
-}
-
-bool DragData::containsPlainText() const
-{
- return m_platformDragData->types().contains(mimeTypeTextPlain);
-}
-
-String DragData::asPlainText(Frame*) const
-{
- return m_platformDragData->getData(mimeTypeTextPlain);
-}
-
-bool DragData::canSmartReplace() const
-{
- // Mimic the situations in which mac allows drag&drop to do a smart replace.
- // This is allowed whenever the drag data contains a 'range' (ie.,
- // ClipboardWin::writeRange is called). For example, dragging a link
- // should not result in a space being added.
- return m_platformDragData->types().contains(mimeTypeTextPlain)
- && !m_platformDragData->types().contains(mimeTypeTextURIList);
-}
-
-bool DragData::containsCompatibleContent() const
-{
- return containsPlainText()
- || containsURL(0)
- || containsHTML(m_platformDragData)
- || containsFiles();
-}
-
-PassRefPtr<DocumentFragment> DragData::asFragment(Frame* frame, PassRefPtr<Range>, bool, bool&) const
-{
- /*
- * Order is richest format first. On OSX this is:
- * * Web Archive
- * * Filenames
- * * HTML
- * * RTF
- * * TIFF
- * * PICT
- */
-
- if (containsFiles()) {
- // FIXME: Implement this. Should be pretty simple to make some HTML
- // and call createFragmentFromMarkup.
- }
-
- if (m_platformDragData->types().contains(mimeTypeTextHTML)) {
- String html;
- KURL baseURL;
- m_platformDragData->htmlAndBaseURL(html, baseURL);
- ASSERT(frame->document());
- if (RefPtr<DocumentFragment> fragment = createFragmentFromMarkup(*frame->document(), html, baseURL, DisallowScriptingAndPluginContent))
- return fragment.release();
- }
-
- return 0;
-}
-
-String DragData::droppedFileSystemId() const
-{
- DraggedIsolatedFileSystem* filesystem = DraggedIsolatedFileSystem::from(m_platformDragData);
- if (!filesystem)
- return String();
- return filesystem->filesystemId();
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/DragData.h b/chromium/third_party/WebKit/Source/core/platform/DragData.h
deleted file mode 100644
index cf8fad145a0..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/DragData.h
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * Copyright (C) 2007 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef DragData_h
-#define DragData_h
-
-#include "core/page/DragActions.h"
-#include "core/platform/graphics/IntPoint.h"
-
-#include "wtf/Forward.h"
-#include "wtf/HashMap.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-class ChromiumDataObject;
-class DocumentFragment;
-class Frame;
-class KURL;
-class Range;
-
-enum DragApplicationFlags {
- DragApplicationNone = 0,
- DragApplicationIsModal = 1,
- DragApplicationIsSource = 2,
- DragApplicationHasAttachedSheet = 4,
- DragApplicationIsCopyKeyDown = 8
-};
-
-class DragData {
-public:
- enum FilenameConversionPolicy { DoNotConvertFilenames, ConvertFilenames };
-
- // clientPosition is taken to be the position of the drag event within the target window, with (0,0) at the top left
- DragData(ChromiumDataObject*, const IntPoint& clientPosition, const IntPoint& globalPosition, DragOperation, DragApplicationFlags = DragApplicationNone);
- DragData(const String& dragStorageName, const IntPoint& clientPosition, const IntPoint& globalPosition, DragOperation, DragApplicationFlags = DragApplicationNone);
- const IntPoint& clientPosition() const { return m_clientPosition; }
- const IntPoint& globalPosition() const { return m_globalPosition; }
- DragApplicationFlags flags() const { return m_applicationFlags; }
- ChromiumDataObject* platformData() const { return m_platformDragData; }
- DragOperation draggingSourceOperationMask() const { return m_draggingSourceOperationMask; }
- bool containsURL(Frame*, FilenameConversionPolicy filenamePolicy = ConvertFilenames) const;
- bool containsPlainText() const;
- bool containsCompatibleContent() const;
- String asURL(Frame*, FilenameConversionPolicy filenamePolicy = ConvertFilenames, String* title = 0) const;
- String asPlainText(Frame*) const;
- void asFilenames(Vector<String>&) const;
- PassRefPtr<DocumentFragment> asFragment(Frame*, PassRefPtr<Range> context,
- bool allowPlainText, bool& chosePlainText) const;
- bool canSmartReplace() const;
- bool containsFiles() const;
- unsigned numberOfFiles() const;
- int modifierKeyState() const;
-
- String droppedFileSystemId() const;
-
-private:
- IntPoint m_clientPosition;
- IntPoint m_globalPosition;
- ChromiumDataObject* m_platformDragData;
- DragOperation m_draggingSourceOperationMask;
- DragApplicationFlags m_applicationFlags;
-};
-
-}
-
-#endif // !DragData_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/DragImage.cpp b/chromium/third_party/WebKit/Source/core/platform/DragImage.cpp
index 9de673d01a6..f8fe7734277 100644
--- a/chromium/third_party/WebKit/Source/core/platform/DragImage.cpp
+++ b/chromium/third_party/WebKit/Source/core/platform/DragImage.cpp
@@ -26,27 +26,26 @@
#include "config.h"
#include "core/platform/DragImage.h"
-#include "core/platform/graphics/BitmapImage.h"
-#include "core/platform/graphics/Color.h"
-#include "core/platform/graphics/FloatPoint.h"
-#include "core/platform/graphics/FloatRect.h"
-#include "core/platform/graphics/Font.h"
-#include "core/platform/graphics/FontCache.h"
-#include "core/platform/graphics/FontDescription.h"
-#include "core/platform/graphics/FontMetrics.h"
-#include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/graphics/Image.h"
-#include "core/platform/graphics/ImageBuffer.h"
-#include "core/platform/graphics/IntPoint.h"
-#include "core/platform/graphics/IntSize.h"
-#include "core/platform/graphics/StringTruncator.h"
-#include "core/platform/graphics/TextRun.h"
-#include "core/platform/graphics/skia/NativeImageSkia.h"
-#include "core/platform/graphics/transforms/AffineTransform.h"
+#include "platform/fonts/Font.h"
+#include "platform/fonts/FontCache.h"
+#include "platform/fonts/FontDescription.h"
+#include "platform/fonts/FontMetrics.h"
+#include "platform/geometry/FloatPoint.h"
+#include "platform/geometry/FloatRect.h"
+#include "platform/geometry/IntPoint.h"
+#include "platform/graphics/BitmapImage.h"
+#include "platform/graphics/Color.h"
+#include "platform/graphics/GraphicsContext.h"
+#include "platform/graphics/Image.h"
+#include "platform/graphics/ImageBuffer.h"
+#include "platform/graphics/skia/NativeImageSkia.h"
+#include "platform/text/StringTruncator.h"
+#include "platform/text/TextRun.h"
+#include "platform/transforms/AffineTransform.h"
+#include "platform/weborigin/KURL.h"
#include "skia/ext/image_operations.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "third_party/skia/include/core/SkMatrix.h"
-#include "weborigin/KURL.h"
#include "wtf/PassOwnPtr.h"
#include "wtf/RefPtr.h"
#include "wtf/text/WTFString.h"
@@ -58,17 +57,15 @@ namespace WebCore {
const float kDragLabelBorderX = 4;
// Keep border_y in synch with DragController::LinkDragBorderInset.
const float kDragLabelBorderY = 2;
-const float kDragLabelRadius = 5;
const float kLabelBorderYOffset = 2;
-const float kMinDragLabelWidthBeforeClip = 120;
const float kMaxDragLabelWidth = 300;
const float kMaxDragLabelStringWidth = (kMaxDragLabelWidth - 2 * kDragLabelBorderX);
const float kDragLinkLabelFontSize = 11;
const float kDragLinkUrlFontSize = 10;
-PassOwnPtr<DragImage> DragImage::create(Image* image, RespectImageOrientationEnum shouldRespectImageOrientation)
+PassOwnPtr<DragImage> DragImage::create(Image* image, RespectImageOrientationEnum shouldRespectImageOrientation, float deviceScaleFactor)
{
if (!image)
return nullptr;
@@ -79,7 +76,7 @@ PassOwnPtr<DragImage> DragImage::create(Image* image, RespectImageOrientationEnu
if (image->isBitmapImage()) {
ImageOrientation orientation = DefaultImageOrientation;
- BitmapImage* bitmapImage = static_cast<BitmapImage*>(image);
+ BitmapImage* bitmapImage = toBitmapImage(image);
IntSize sizeRespectingOrientation = bitmapImage->sizeRespectingOrientation();
if (shouldRespectImageOrientation == RespectImageOrientation)
@@ -97,17 +94,17 @@ PassOwnPtr<DragImage> DragImage::create(Image* image, RespectImageOrientationEnu
return nullptr;
SkCanvas canvas(skBitmap);
- canvas.concat(orientation.transformFromDefault(sizeRespectingOrientation));
+ canvas.concat(affineTransformToSkMatrix(orientation.transformFromDefault(sizeRespectingOrientation)));
canvas.drawBitmapRect(bitmap->bitmap(), 0, destRect);
- return adoptPtr(new DragImage(skBitmap, bitmap->resolutionScale()));
+ return adoptPtr(new DragImage(skBitmap, deviceScaleFactor));
}
}
SkBitmap skBitmap;
if (!bitmap->bitmap().copyTo(&skBitmap, SkBitmap::kARGB_8888_Config))
return nullptr;
- return adoptPtr(new DragImage(skBitmap, bitmap->resolutionScale()));
+ return adoptPtr(new DragImage(skBitmap, deviceScaleFactor));
}
static Font deriveDragLabelFont(int size, FontWeight fontWeight, const FontDescription& systemFont)
@@ -166,9 +163,10 @@ PassOwnPtr<DragImage> DragImage::create(const KURL& url, const String& inLabel,
// fill the background
IntSize scaledImageSize = imageSize;
scaledImageSize.scale(deviceScaleFactor);
- OwnPtr<ImageBuffer> buffer(ImageBuffer::create(scaledImageSize, deviceScaleFactor));
+ OwnPtr<ImageBuffer> buffer(ImageBuffer::create(scaledImageSize));
if (!buffer)
return nullptr;
+ buffer->context()->scale(FloatSize(deviceScaleFactor, deviceScaleFactor));
const float DragLabelRadius = 5;
const IntSize radii(DragLabelRadius, DragLabelRadius);
@@ -193,7 +191,7 @@ PassOwnPtr<DragImage> DragImage::create(const KURL& url, const String& inLabel,
buffer->context()->drawText(urlFont, TextRunPaintInfo(textRun), textPos);
RefPtr<Image> image = buffer->copyImage();
- return DragImage::create(image.get());
+ return DragImage::create(image.get(), DoNotRespectImageOrientation, deviceScaleFactor);
}
DragImage::DragImage(const SkBitmap& bitmap, float resolutionScale)
@@ -251,7 +249,7 @@ void DragImage::scale(float scaleX, float scaleY)
void DragImage::dissolveToFraction(float fraction)
{
- m_bitmap.setIsOpaque(false);
+ m_bitmap.setAlphaType(kPremul_SkAlphaType);
SkAutoLockPixels lock(m_bitmap);
for (int row = 0; row < m_bitmap.height(); ++row) {
diff --git a/chromium/third_party/WebKit/Source/core/platform/DragImage.h b/chromium/third_party/WebKit/Source/core/platform/DragImage.h
index 129383db2b7..a350ad899d6 100644
--- a/chromium/third_party/WebKit/Source/core/platform/DragImage.h
+++ b/chromium/third_party/WebKit/Source/core/platform/DragImage.h
@@ -26,8 +26,8 @@
#ifndef DragImage_h
#define DragImage_h
-#include "core/platform/graphics/ImageOrientation.h"
-#include "core/platform/graphics/IntSize.h"
+#include "platform/geometry/IntSize.h"
+#include "platform/graphics/ImageOrientation.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "wtf/Forward.h"
@@ -39,7 +39,7 @@ class KURL;
class DragImage {
public:
- static PassOwnPtr<DragImage> create(Image*, RespectImageOrientationEnum = DoNotRespectImageOrientation);
+ static PassOwnPtr<DragImage> create(Image*, RespectImageOrientationEnum = DoNotRespectImageOrientation, float deviceScaleFactor = 1);
static PassOwnPtr<DragImage> create(const KURL&, const String& label, const FontDescription& systemFont, float deviceScaleFactor);
~DragImage();
diff --git a/chromium/third_party/WebKit/Source/core/platform/EventTracer.cpp b/chromium/third_party/WebKit/Source/core/platform/EventTracer.cpp
deleted file mode 100644
index d10037c885a..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/EventTracer.cpp
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/EventTracer.h"
-
-#include "public/platform/Platform.h"
-#include <stdio.h>
-
-namespace WebCore {
-
-// The dummy variable is needed to avoid a crash when someone updates the state variables
-// before EventTracer::initialize() is called.
-long dummyTraceSamplingState = 0;
-long* traceSamplingState[3] = {&dummyTraceSamplingState, &dummyTraceSamplingState, &dummyTraceSamplingState };
-
-void EventTracer::initialize()
-{
- traceSamplingState[0] = WebKit::Platform::current()->getTraceSamplingState(0);
- // FIXME: traceSamplingState[0] can be 0 in split-dll build. http://crbug.com/256965
- if (!traceSamplingState[0])
- traceSamplingState[0] = &dummyTraceSamplingState;
- traceSamplingState[1] = WebKit::Platform::current()->getTraceSamplingState(1);
- if (!traceSamplingState[1])
- traceSamplingState[1] = &dummyTraceSamplingState;
- traceSamplingState[2] = WebKit::Platform::current()->getTraceSamplingState(2);
- if (!traceSamplingState[2])
- traceSamplingState[2] = &dummyTraceSamplingState;
-}
-
-const unsigned char* EventTracer::getTraceCategoryEnabledFlag(const char* categoryName)
-{
- return WebKit::Platform::current()->getTraceCategoryEnabledFlag(categoryName);
-}
-
-void EventTracer::addTraceEvent(char phase, const unsigned char* categoryEnabledFlag,
- const char* name, unsigned long long id, int numArgs, const char** argNames,
- const unsigned char* argTypes, const unsigned long long* argValues, unsigned char flags)
-{
- return WebKit::Platform::current()->addTraceEvent(phase, categoryEnabledFlag, name, id, numArgs, argNames, argTypes, argValues, flags);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/EventTracer.h b/chromium/third_party/WebKit/Source/core/platform/EventTracer.h
deleted file mode 100644
index d1a1b0d8cdd..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/EventTracer.h
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef EventTracer_h
-#define EventTracer_h
-
-// This will mark the trace event as disabled by default. The user will need
-// to explicitly enable the event.
-#define TRACE_DISABLED_BY_DEFAULT(name) "disabled-by-default-" name
-
-namespace WebCore {
-
-// FIXME: Make these global variables thread-safe. Make a value update atomic.
-extern long* traceSamplingState[3];
-
-class EventTracer {
-public:
- static void initialize();
- static const unsigned char* getTraceCategoryEnabledFlag(const char*);
- static void addTraceEvent(char phase,
- const unsigned char* categoryEnabledFlag,
- const char* name,
- unsigned long long id,
- int numArgs,
- const char** argNames,
- const unsigned char* argTypes,
- const unsigned long long* argValues,
- unsigned char flags);
-};
-
-} // namespace WebCore
-
-#endif // EventTracer_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/FileChooser.cpp b/chromium/third_party/WebKit/Source/core/platform/FileChooser.cpp
deleted file mode 100644
index f8815505aa8..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/FileChooser.cpp
+++ /dev/null
@@ -1,111 +0,0 @@
-/*
- * Copyright (C) 2007, 2008 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/FileChooser.h"
-
-namespace WebCore {
-
-FileChooserClient::~FileChooserClient()
-{
- discardChooser();
-}
-
-FileChooser* FileChooserClient::newFileChooser(const FileChooserSettings& settings)
-{
- discardChooser();
-
- m_chooser = FileChooser::create(this, settings);
- return m_chooser.get();
-}
-
-void FileChooserClient::discardChooser()
-{
- if (m_chooser)
- m_chooser->disconnectClient();
-}
-
-inline FileChooser::FileChooser(FileChooserClient* client, const FileChooserSettings& settings)
- : m_client(client)
- , m_settings(settings)
-{
-}
-
-PassRefPtr<FileChooser> FileChooser::create(FileChooserClient* client, const FileChooserSettings& settings)
-{
- return adoptRef(new FileChooser(client, settings));
-}
-
-FileChooser::~FileChooser()
-{
-}
-
-void FileChooser::chooseFile(const String& filename)
-{
- Vector<String> filenames;
- filenames.append(filename);
- chooseFiles(filenames);
-}
-
-void FileChooser::chooseFiles(const Vector<String>& filenames)
-{
- // FIXME: This is inelegant. We should not be looking at settings here.
- if (m_settings.selectedFiles == filenames)
- return;
-
- if (m_client) {
- Vector<FileChooserFileInfo> files;
- for (unsigned i = 0; i < filenames.size(); ++i)
- files.append(FileChooserFileInfo(filenames[i]));
- m_client->filesChosen(files);
- }
-}
-
-void FileChooser::chooseFiles(const Vector<FileChooserFileInfo>& files)
-{
- // FIXME: This is inelegant. We should not be looking at settings here.
- Vector<String> paths;
- for (unsigned i = 0; i < files.size(); ++i)
- paths.append(files[i].path);
- if (m_settings.selectedFiles == paths)
- return;
-
- if (m_client)
- m_client->filesChosen(files);
-}
-
-Vector<String> FileChooserSettings::acceptTypes() const
-{
- Vector<String> acceptTypes;
- acceptTypes.reserveCapacity(acceptMIMETypes.size() + acceptFileExtensions.size());
- acceptTypes.append(acceptMIMETypes);
- acceptTypes.append(acceptFileExtensions);
- return acceptTypes;
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/FileChooser.h b/chromium/third_party/WebKit/Source/core/platform/FileChooser.h
deleted file mode 100644
index 95fabf09be4..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/FileChooser.h
+++ /dev/null
@@ -1,104 +0,0 @@
-/*
- * Copyright (C) 2006, 2007, 2008 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-#ifndef FileChooser_h
-#define FileChooser_h
-
-#include "wtf/RefCounted.h"
-#include "wtf/Vector.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class FileChooser;
-
-struct FileChooserFileInfo {
- FileChooserFileInfo(const String& path, const String& displayName = String())
- : path(path)
- , displayName(displayName)
- {
- }
-
- const String path;
- const String displayName;
-};
-
-struct FileChooserSettings {
- bool allowsMultipleFiles;
- bool allowsDirectoryUpload;
- Vector<String> acceptMIMETypes;
- Vector<String> acceptFileExtensions;
- Vector<String> selectedFiles;
-#if ENABLE(MEDIA_CAPTURE)
- bool useMediaCapture;
-#endif
-
- // Returns a combined vector of acceptMIMETypes and acceptFileExtensions.
- Vector<String> acceptTypes() const;
-};
-
-class FileChooserClient {
-public:
- virtual void filesChosen(const Vector<FileChooserFileInfo>&) = 0;
- virtual ~FileChooserClient();
-
-protected:
- FileChooser* newFileChooser(const FileChooserSettings&);
-
-private:
- void discardChooser();
-
- RefPtr<FileChooser> m_chooser;
-};
-
-class FileChooser : public RefCounted<FileChooser> {
-public:
- static PassRefPtr<FileChooser> create(FileChooserClient*, const FileChooserSettings&);
- ~FileChooser();
-
- void disconnectClient() { m_client = 0; }
-
- void chooseFile(const String& path);
- void chooseFiles(const Vector<String>& paths);
-
- // FIXME: We should probably just pass file paths that could be virtual paths with proper display names rather than passing structs.
- void chooseFiles(const Vector<FileChooserFileInfo>& files);
-
- const FileChooserSettings& settings() const { return m_settings; }
-
-private:
- FileChooser(FileChooserClient*, const FileChooserSettings&);
-
- FileChooserClient* m_client;
- FileChooserSettings m_settings;
-};
-
-} // namespace WebCore
-
-#endif // FileChooser_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/FileMetadata.h b/chromium/third_party/WebKit/Source/core/platform/FileMetadata.h
deleted file mode 100644
index 9da2570cbfd..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/FileMetadata.h
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef FileMetadata_h
-#define FileMetadata_h
-
-#include "core/platform/FileSystem.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-struct FileMetadata {
- // The last modification time of the file, in seconds.
- // The value 0.0 means that the time is not set.
- double modificationTime;
-
- // The length of the file in bytes.
- // The value -1 means that the length is not set.
- long long length;
-
- enum Type {
- TypeUnknown = 0,
- TypeFile,
- TypeDirectory
- };
-
- Type type;
- String platformPath;
-
- FileMetadata() : modificationTime(invalidFileTime()), length(-1), type(TypeUnknown) { }
-};
-
-} // namespace WebCore
-
-#endif // FileMetadata_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/FileSystem.h b/chromium/third_party/WebKit/Source/core/platform/FileSystem.h
deleted file mode 100644
index 0d96833fa8d..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/FileSystem.h
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright (C) 2007, 2008, 2011 Apple Inc. All rights reserved.
- * Copyright (C) 2008 Collabora, Ltd. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef FileSystem_h
-#define FileSystem_h
-
-#include <time.h>
-#include "wtf/Forward.h"
-#include "wtf/MathExtras.h"
-#include "wtf/Vector.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-struct FileMetadata;
-
-bool getFileSize(const String&, long long& result);
-bool getFileModificationTime(const String&, time_t& result);
-bool getFileMetadata(const String&, FileMetadata&);
-String directoryName(const String&);
-
-inline double invalidFileTime() { return std::numeric_limits<double>::quiet_NaN(); }
-inline bool isValidFileTime(double time) { return std::isfinite(time); }
-
-} // namespace WebCore
-
-#endif // FileSystem_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/FloatConversion.h b/chromium/third_party/WebKit/Source/core/platform/FloatConversion.h
deleted file mode 100644
index 95f013a0a0d..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/FloatConversion.h
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright (C) 2007 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef FloatConversion_h
-#define FloatConversion_h
-
-namespace WebCore {
-
- template<typename T>
- float narrowPrecisionToFloat(T);
-
- template<>
- inline float narrowPrecisionToFloat(double number)
- {
- return static_cast<float>(number);
- }
-} // namespace WebCore
-
-#endif // FloatConversion_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/HashTools.h b/chromium/third_party/WebKit/Source/core/platform/HashTools.h
deleted file mode 100644
index c376470e6df..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/HashTools.h
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Copyright (C) 2010 Andras Becsi <abecsi@inf.u-szeged.hu>, University of Szeged
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#ifndef HashTools_h
-#define HashTools_h
-
-namespace WebCore {
-
-struct NamedColor {
- const char* name;
- unsigned ARGBValue;
-};
-
-struct Property {
- int nameOffset;
- int id;
-};
-
-struct Value {
- int nameOffset;
- int id;
-};
-
-const NamedColor* findColor(register const char* str, register unsigned int len);
-const Property* findProperty(register const char* str, register unsigned int len);
-const Value* findValue(register const char* str, register unsigned int len);
-
-} // namespace WebCore
-
-#endif // HashTools_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/HistogramSupport.h b/chromium/third_party/WebKit/Source/core/platform/HistogramSupport.h
deleted file mode 100644
index 9bb265a8fe2..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/HistogramSupport.h
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef HistogramSupport_h
-#define HistogramSupport_h
-
-namespace WebCore {
-
-class HistogramSupport {
-public:
- static void histogramEnumeration(const char* name, int sample, int boundaryValue);
- static void histogramCustomCounts(const char* name, int sample, int min, int max, int bucketCount);
-};
-
-} // namespace WebCore
-
-#endif // HistogramSupport_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/HostWindow.h b/chromium/third_party/WebKit/Source/core/platform/HostWindow.h
deleted file mode 100644
index aec1b0e972b..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/HostWindow.h
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Copyright (C) 2008 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef HostWindow_h
-#define HostWindow_h
-
-#include "wtf/FastAllocBase.h"
-#include "wtf/Noncopyable.h"
-
-namespace WebKit {
-struct WebScreenInfo;
-}
-
-namespace WebCore {
-class Cursor;
-class IntPoint;
-class IntRect;
-class IntSize;
-
-class HostWindow {
- WTF_MAKE_NONCOPYABLE(HostWindow); WTF_MAKE_FAST_ALLOCATED;
-public:
- HostWindow() { }
- virtual ~HostWindow() { }
-
- // Requests the host invalidate the contents and the root view.
- virtual void invalidateContentsAndRootView(const IntRect& updateRect) = 0;
-
- // Requests the host scroll backingstore by the specified delta, rect to scroll, and clip rect.
- virtual void scroll(const IntSize& scrollDelta, const IntRect& rectToScroll, const IntRect& clipRect) = 0;
-
- // Requests the host invalidate the contents, not the root view. This is the slow path for scrolling.
- virtual void invalidateContentsForSlowScroll(const IntRect& updateRect) = 0;
-
- // Methods for doing coordinate conversions to and from screen coordinates.
- virtual IntPoint screenToRootView(const IntPoint&) const = 0;
- virtual IntRect rootViewToScreen(const IntRect&) const = 0;
-
- virtual WebKit::WebScreenInfo screenInfo() const = 0;
-
- // Request that the cursor change.
- virtual void setCursor(const Cursor&) = 0;
-
- virtual void scheduleAnimation() = 0;
-};
-
-} // namespace WebCore
-
-#endif // HostWindow_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/JSONValues.cpp b/chromium/third_party/WebKit/Source/core/platform/JSONValues.cpp
deleted file mode 100644
index 667beddb20c..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/JSONValues.cpp
+++ /dev/null
@@ -1,386 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/JSONValues.h"
-
-#include "wtf/DecimalNumber.h"
-#include "wtf/dtoa.h"
-#include "wtf/text/StringBuilder.h"
-
-namespace WebCore {
-
-namespace {
-
-const char* const nullString = "null";
-const char* const trueString = "true";
-const char* const falseString = "false";
-
-inline bool escapeChar(UChar c, StringBuilder* dst)
-{
- switch (c) {
- case '\b': dst->append("\\b", 2); break;
- case '\f': dst->append("\\f", 2); break;
- case '\n': dst->append("\\n", 2); break;
- case '\r': dst->append("\\r", 2); break;
- case '\t': dst->append("\\t", 2); break;
- case '\\': dst->append("\\\\", 2); break;
- case '"': dst->append("\\\"", 2); break;
- default:
- return false;
- }
- return true;
-}
-
-inline void doubleQuoteString(const String& str, StringBuilder* dst)
-{
- dst->append('"');
- for (unsigned i = 0; i < str.length(); ++i) {
- UChar c = str[i];
- if (!escapeChar(c, dst)) {
- if (c < 32 || c > 126 || c == '<' || c == '>') {
- // 1. Escaping <, > to prevent script execution.
- // 2. Technically, we could also pass through c > 126 as UTF8, but this
- // is also optional. It would also be a pain to implement here.
- unsigned symbol = static_cast<unsigned>(c);
- String symbolCode = String::format("\\u%04X", symbol);
- dst->append(symbolCode);
- } else {
- dst->append(c);
- }
- }
- }
- dst->append('"');
-}
-
-} // anonymous namespace
-
-bool JSONValue::asBoolean(bool*) const
-{
- return false;
-}
-
-bool JSONValue::asNumber(double*) const
-{
- return false;
-}
-
-bool JSONValue::asNumber(long*) const
-{
- return false;
-}
-
-bool JSONValue::asNumber(int*) const
-{
- return false;
-}
-
-bool JSONValue::asNumber(unsigned long*) const
-{
- return false;
-}
-
-bool JSONValue::asNumber(unsigned*) const
-{
- return false;
-}
-
-bool JSONValue::asString(String*) const
-{
- return false;
-}
-
-bool JSONValue::asValue(RefPtr<JSONValue>* output)
-{
- *output = this;
- return true;
-}
-
-bool JSONValue::asObject(RefPtr<JSONObject>*)
-{
- return false;
-}
-
-bool JSONValue::asArray(RefPtr<JSONArray>*)
-{
- return false;
-}
-
-PassRefPtr<JSONObject> JSONValue::asObject()
-{
- return 0;
-}
-
-PassRefPtr<JSONArray> JSONValue::asArray()
-{
- return 0;
-}
-
-String JSONValue::toJSONString() const
-{
- StringBuilder result;
- result.reserveCapacity(512);
- writeJSON(&result);
- return result.toString();
-}
-
-void JSONValue::writeJSON(StringBuilder* output) const
-{
- ASSERT(m_type == TypeNull);
- output->append(nullString, 4);
-}
-
-bool JSONBasicValue::asBoolean(bool* output) const
-{
- if (type() != TypeBoolean)
- return false;
- *output = m_boolValue;
- return true;
-}
-
-bool JSONBasicValue::asNumber(double* output) const
-{
- if (type() != TypeNumber)
- return false;
- *output = m_doubleValue;
- return true;
-}
-
-bool JSONBasicValue::asNumber(long* output) const
-{
- if (type() != TypeNumber)
- return false;
- *output = static_cast<long>(m_doubleValue);
- return true;
-}
-
-bool JSONBasicValue::asNumber(int* output) const
-{
- if (type() != TypeNumber)
- return false;
- *output = static_cast<int>(m_doubleValue);
- return true;
-}
-
-bool JSONBasicValue::asNumber(unsigned long* output) const
-{
- if (type() != TypeNumber)
- return false;
- *output = static_cast<unsigned long>(m_doubleValue);
- return true;
-}
-
-bool JSONBasicValue::asNumber(unsigned* output) const
-{
- if (type() != TypeNumber)
- return false;
- *output = static_cast<unsigned>(m_doubleValue);
- return true;
-}
-
-void JSONBasicValue::writeJSON(StringBuilder* output) const
-{
- ASSERT(type() == TypeBoolean || type() == TypeNumber);
- if (type() == TypeBoolean) {
- if (m_boolValue)
- output->append(trueString, 4);
- else
- output->append(falseString, 5);
- } else if (type() == TypeNumber) {
- NumberToLStringBuffer buffer;
- if (!std::isfinite(m_doubleValue)) {
- output->append(nullString, 4);
- return;
- }
- DecimalNumber decimal = m_doubleValue;
- unsigned length = 0;
- if (decimal.bufferLengthForStringDecimal() > WTF::NumberToStringBufferLength) {
- // Not enough room for decimal. Use exponential format.
- if (decimal.bufferLengthForStringExponential() > WTF::NumberToStringBufferLength) {
- // Fallback for an abnormal case if it's too little even for exponential.
- output->append("NaN", 3);
- return;
- }
- length = decimal.toStringExponential(buffer, WTF::NumberToStringBufferLength);
- } else {
- length = decimal.toStringDecimal(buffer, WTF::NumberToStringBufferLength);
- }
- output->append(buffer, length);
- }
-}
-
-bool JSONString::asString(String* output) const
-{
- *output = m_stringValue;
- return true;
-}
-
-void JSONString::writeJSON(StringBuilder* output) const
-{
- ASSERT(type() == TypeString);
- doubleQuoteString(m_stringValue, output);
-}
-
-JSONObjectBase::~JSONObjectBase()
-{
-}
-
-bool JSONObjectBase::asObject(RefPtr<JSONObject>* output)
-{
- COMPILE_ASSERT(sizeof(JSONObject) == sizeof(JSONObjectBase), cannot_cast);
- *output = static_cast<JSONObject*>(this);
- return true;
-}
-
-PassRefPtr<JSONObject> JSONObjectBase::asObject()
-{
- return openAccessors();
-}
-
-JSONObject* JSONObjectBase::openAccessors()
-{
- COMPILE_ASSERT(sizeof(JSONObject) == sizeof(JSONObjectBase), cannot_cast);
- return static_cast<JSONObject*>(this);
-}
-
-bool JSONObjectBase::getBoolean(const String& name, bool* output) const
-{
- RefPtr<JSONValue> value = get(name);
- if (!value)
- return false;
- return value->asBoolean(output);
-}
-
-bool JSONObjectBase::getString(const String& name, String* output) const
-{
- RefPtr<JSONValue> value = get(name);
- if (!value)
- return false;
- return value->asString(output);
-}
-
-PassRefPtr<JSONObject> JSONObjectBase::getObject(const String& name) const
-{
- RefPtr<JSONValue> value = get(name);
- if (!value)
- return 0;
- return value->asObject();
-}
-
-PassRefPtr<JSONArray> JSONObjectBase::getArray(const String& name) const
-{
- RefPtr<JSONValue> value = get(name);
- if (!value)
- return 0;
- return value->asArray();
-}
-
-PassRefPtr<JSONValue> JSONObjectBase::get(const String& name) const
-{
- Dictionary::const_iterator it = m_data.find(name);
- if (it == m_data.end())
- return 0;
- return it->value;
-}
-
-void JSONObjectBase::remove(const String& name)
-{
- m_data.remove(name);
- for (size_t i = 0; i < m_order.size(); ++i) {
- if (m_order[i] == name) {
- m_order.remove(i);
- break;
- }
- }
-}
-
-void JSONObjectBase::writeJSON(StringBuilder* output) const
-{
- output->append('{');
- for (size_t i = 0; i < m_order.size(); ++i) {
- Dictionary::const_iterator it = m_data.find(m_order[i]);
- ASSERT(it != m_data.end());
- if (i)
- output->append(',');
- doubleQuoteString(it->key, output);
- output->append(':');
- it->value->writeJSON(output);
- }
- output->append('}');
-}
-
-JSONObjectBase::JSONObjectBase()
- : JSONValue(TypeObject)
- , m_data()
- , m_order()
-{
-}
-
-JSONArrayBase::~JSONArrayBase()
-{
-}
-
-bool JSONArrayBase::asArray(RefPtr<JSONArray>* output)
-{
- COMPILE_ASSERT(sizeof(JSONArrayBase) == sizeof(JSONArray), cannot_cast);
- *output = static_cast<JSONArray*>(this);
- return true;
-}
-
-PassRefPtr<JSONArray> JSONArrayBase::asArray()
-{
- COMPILE_ASSERT(sizeof(JSONArrayBase) == sizeof(JSONArray), cannot_cast);
- return static_cast<JSONArray*>(this);
-}
-
-void JSONArrayBase::writeJSON(StringBuilder* output) const
-{
- output->append('[');
- for (Vector<RefPtr<JSONValue> >::const_iterator it = m_data.begin(); it != m_data.end(); ++it) {
- if (it != m_data.begin())
- output->append(',');
- (*it)->writeJSON(output);
- }
- output->append(']');
-}
-
-JSONArrayBase::JSONArrayBase()
- : JSONValue(TypeArray)
- , m_data()
-{
-}
-
-PassRefPtr<JSONValue> JSONArrayBase::get(size_t index)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(index < m_data.size());
- return m_data[index];
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/JSONValues.h b/chromium/third_party/WebKit/Source/core/platform/JSONValues.h
deleted file mode 100644
index f1f3bf7ac4f..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/JSONValues.h
+++ /dev/null
@@ -1,393 +0,0 @@
-/*
- * Copyright (C) 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef JSONValues_h
-#define JSONValues_h
-
-#include "wtf/Forward.h"
-#include "wtf/HashMap.h"
-#include "wtf/RefCounted.h"
-#include "wtf/Vector.h"
-#include "wtf/text/StringHash.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class JSONArray;
-class JSONObject;
-
-class JSONValue : public RefCounted<JSONValue> {
-public:
- static const int maxDepth = 1000;
-
- JSONValue() : m_type(TypeNull) { }
- virtual ~JSONValue() { }
-
- static PassRefPtr<JSONValue> null()
- {
- return adoptRef(new JSONValue());
- }
-
- typedef enum {
- TypeNull = 0,
- TypeBoolean,
- TypeNumber,
- TypeString,
- TypeObject,
- TypeArray
- } Type;
-
- Type type() const { return m_type; }
-
- bool isNull() const { return m_type == TypeNull; }
-
- virtual bool asBoolean(bool* output) const;
- virtual bool asNumber(double* output) const;
- virtual bool asNumber(long* output) const;
- virtual bool asNumber(int* output) const;
- virtual bool asNumber(unsigned long* output) const;
- virtual bool asNumber(unsigned* output) const;
- virtual bool asString(String* output) const;
- virtual bool asValue(RefPtr<JSONValue>* output);
- virtual bool asObject(RefPtr<JSONObject>* output);
- virtual bool asArray(RefPtr<JSONArray>* output);
- virtual PassRefPtr<JSONObject> asObject();
- virtual PassRefPtr<JSONArray> asArray();
-
- String toJSONString() const;
- virtual void writeJSON(StringBuilder* output) const;
-
-protected:
- explicit JSONValue(Type type) : m_type(type) { }
-
-private:
- Type m_type;
-};
-
-class JSONBasicValue : public JSONValue {
-public:
-
- static PassRefPtr<JSONBasicValue> create(bool value)
- {
- return adoptRef(new JSONBasicValue(value));
- }
-
- static PassRefPtr<JSONBasicValue> create(int value)
- {
- return adoptRef(new JSONBasicValue(value));
- }
-
- static PassRefPtr<JSONBasicValue> create(double value)
- {
- return adoptRef(new JSONBasicValue(value));
- }
-
- virtual bool asBoolean(bool* output) const;
- virtual bool asNumber(double* output) const;
- virtual bool asNumber(long* output) const;
- virtual bool asNumber(int* output) const;
- virtual bool asNumber(unsigned long* output) const;
- virtual bool asNumber(unsigned* output) const;
-
- virtual void writeJSON(StringBuilder* output) const;
-
-private:
- explicit JSONBasicValue(bool value) : JSONValue(TypeBoolean), m_boolValue(value) { }
- explicit JSONBasicValue(int value) : JSONValue(TypeNumber), m_doubleValue((double)value) { }
- explicit JSONBasicValue(double value) : JSONValue(TypeNumber), m_doubleValue(value) { }
-
- union {
- bool m_boolValue;
- double m_doubleValue;
- };
-};
-
-class JSONString : public JSONValue {
-public:
- static PassRefPtr<JSONString> create(const String& value)
- {
- return adoptRef(new JSONString(value));
- }
-
- static PassRefPtr<JSONString> create(const char* value)
- {
- return adoptRef(new JSONString(value));
- }
-
- virtual bool asString(String* output) const;
-
- virtual void writeJSON(StringBuilder* output) const;
-
-private:
- explicit JSONString(const String& value) : JSONValue(TypeString), m_stringValue(value) { }
- explicit JSONString(const char* value) : JSONValue(TypeString), m_stringValue(value) { }
-
- String m_stringValue;
-};
-
-class JSONObjectBase : public JSONValue {
-private:
- typedef HashMap<String, RefPtr<JSONValue> > Dictionary;
-
-public:
- typedef Dictionary::iterator iterator;
- typedef Dictionary::const_iterator const_iterator;
-
- virtual PassRefPtr<JSONObject> asObject();
- JSONObject* openAccessors();
-
-protected:
- ~JSONObjectBase();
-
- virtual bool asObject(RefPtr<JSONObject>* output);
-
- void setBoolean(const String& name, bool);
- void setNumber(const String& name, double);
- void setString(const String& name, const String&);
- void setValue(const String& name, PassRefPtr<JSONValue>);
- void setObject(const String& name, PassRefPtr<JSONObject>);
- void setArray(const String& name, PassRefPtr<JSONArray>);
-
- iterator find(const String& name);
- const_iterator find(const String& name) const;
- bool getBoolean(const String& name, bool* output) const;
- template<class T> bool getNumber(const String& name, T* output) const
- {
- RefPtr<JSONValue> value = get(name);
- if (!value)
- return false;
- return value->asNumber(output);
- }
- bool getString(const String& name, String* output) const;
- PassRefPtr<JSONObject> getObject(const String& name) const;
- PassRefPtr<JSONArray> getArray(const String& name) const;
- PassRefPtr<JSONValue> get(const String& name) const;
-
- void remove(const String& name);
-
- virtual void writeJSON(StringBuilder* output) const;
-
- iterator begin() { return m_data.begin(); }
- iterator end() { return m_data.end(); }
- const_iterator begin() const { return m_data.begin(); }
- const_iterator end() const { return m_data.end(); }
-
- int size() const { return m_data.size(); }
-
-protected:
- JSONObjectBase();
-
-private:
- Dictionary m_data;
- Vector<String> m_order;
-};
-
-class JSONObject : public JSONObjectBase {
-public:
- static PassRefPtr<JSONObject> create()
- {
- return adoptRef(new JSONObject());
- }
-
- using JSONObjectBase::asObject;
-
- using JSONObjectBase::setBoolean;
- using JSONObjectBase::setNumber;
- using JSONObjectBase::setString;
- using JSONObjectBase::setValue;
- using JSONObjectBase::setObject;
- using JSONObjectBase::setArray;
-
- using JSONObjectBase::find;
- using JSONObjectBase::getBoolean;
- using JSONObjectBase::getNumber;
- using JSONObjectBase::getString;
- using JSONObjectBase::getObject;
- using JSONObjectBase::getArray;
- using JSONObjectBase::get;
-
- using JSONObjectBase::remove;
-
- using JSONObjectBase::begin;
- using JSONObjectBase::end;
-
- using JSONObjectBase::size;
-};
-
-
-class JSONArrayBase : public JSONValue {
-public:
- typedef Vector<RefPtr<JSONValue> >::iterator iterator;
- typedef Vector<RefPtr<JSONValue> >::const_iterator const_iterator;
-
- virtual PassRefPtr<JSONArray> asArray();
-
- unsigned length() const { return m_data.size(); }
-
-protected:
- ~JSONArrayBase();
-
- virtual bool asArray(RefPtr<JSONArray>* output);
-
- void pushBoolean(bool);
- void pushInt(int);
- void pushNumber(double);
- void pushString(const String&);
- void pushValue(PassRefPtr<JSONValue>);
- void pushObject(PassRefPtr<JSONObject>);
- void pushArray(PassRefPtr<JSONArray>);
-
- PassRefPtr<JSONValue> get(size_t index);
-
- virtual void writeJSON(StringBuilder* output) const;
-
- iterator begin() { return m_data.begin(); }
- iterator end() { return m_data.end(); }
- const_iterator begin() const { return m_data.begin(); }
- const_iterator end() const { return m_data.end(); }
-
-protected:
- JSONArrayBase();
-
-private:
- Vector<RefPtr<JSONValue> > m_data;
-};
-
-class JSONArray : public JSONArrayBase {
-public:
- static PassRefPtr<JSONArray> create()
- {
- return adoptRef(new JSONArray());
- }
-
- using JSONArrayBase::asArray;
-
- using JSONArrayBase::pushBoolean;
- using JSONArrayBase::pushInt;
- using JSONArrayBase::pushNumber;
- using JSONArrayBase::pushString;
- using JSONArrayBase::pushValue;
- using JSONArrayBase::pushObject;
- using JSONArrayBase::pushArray;
-
- using JSONArrayBase::get;
-
- using JSONArrayBase::begin;
- using JSONArrayBase::end;
-};
-
-
-inline JSONObjectBase::iterator JSONObjectBase::find(const String& name)
-{
- return m_data.find(name);
-}
-
-inline JSONObjectBase::const_iterator JSONObjectBase::find(const String& name) const
-{
- return m_data.find(name);
-}
-
-inline void JSONObjectBase::setBoolean(const String& name, bool value)
-{
- setValue(name, JSONBasicValue::create(value));
-}
-
-inline void JSONObjectBase::setNumber(const String& name, double value)
-{
- setValue(name, JSONBasicValue::create(value));
-}
-
-inline void JSONObjectBase::setString(const String& name, const String& value)
-{
- setValue(name, JSONString::create(value));
-}
-
-inline void JSONObjectBase::setValue(const String& name, PassRefPtr<JSONValue> value)
-{
- ASSERT(value);
- if (m_data.set(name, value).isNewEntry)
- m_order.append(name);
-}
-
-inline void JSONObjectBase::setObject(const String& name, PassRefPtr<JSONObject> value)
-{
- ASSERT(value);
- if (m_data.set(name, value).isNewEntry)
- m_order.append(name);
-}
-
-inline void JSONObjectBase::setArray(const String& name, PassRefPtr<JSONArray> value)
-{
- ASSERT(value);
- if (m_data.set(name, value).isNewEntry)
- m_order.append(name);
-}
-
-inline void JSONArrayBase::pushBoolean(bool value)
-{
- m_data.append(JSONBasicValue::create(value));
-}
-
-inline void JSONArrayBase::pushInt(int value)
-{
- m_data.append(JSONBasicValue::create(value));
-}
-
-inline void JSONArrayBase::pushNumber(double value)
-{
- m_data.append(JSONBasicValue::create(value));
-}
-
-inline void JSONArrayBase::pushString(const String& value)
-{
- m_data.append(JSONString::create(value));
-}
-
-inline void JSONArrayBase::pushValue(PassRefPtr<JSONValue> value)
-{
- ASSERT(value);
- m_data.append(value);
-}
-
-inline void JSONArrayBase::pushObject(PassRefPtr<JSONObject> value)
-{
- ASSERT(value);
- m_data.append(value);
-}
-
-inline void JSONArrayBase::pushArray(PassRefPtr<JSONArray> value)
-{
- ASSERT(value);
- m_data.append(value);
-}
-
-} // namespace WebCore
-
-#endif // !defined(JSONValues_h)
diff --git a/chromium/third_party/WebKit/Source/core/platform/KillRing.h b/chromium/third_party/WebKit/Source/core/platform/KillRing.h
deleted file mode 100644
index 5e743bb923a..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/KillRing.h
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef KillRing_h
-#define KillRing_h
-
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class KillRing {
- WTF_MAKE_FAST_ALLOCATED;
-public:
- void append(const String&);
- void prepend(const String&);
- String yank();
- void startNewSequence();
- void setToYankedState();
-};
-
-} // namespace WebCore
-
-#endif // KillRing_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/KillRingNone.cpp b/chromium/third_party/WebKit/Source/core/platform/KillRingNone.cpp
deleted file mode 100644
index 2fce3923da3..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/KillRingNone.cpp
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/KillRing.h"
-
-namespace WebCore {
-
-void KillRing::append(const String&)
-{
-}
-
-void KillRing::prepend(const String&)
-{
-}
-
-String KillRing::yank()
-{
- return String();
-}
-
-void KillRing::startNewSequence()
-{
-}
-
-void KillRing::setToYankedState()
-{
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/Language.cpp b/chromium/third_party/WebKit/Source/core/platform/Language.cpp
deleted file mode 100644
index 3376fab415c..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/Language.cpp
+++ /dev/null
@@ -1,117 +0,0 @@
-/*
- * Copyright (C) 2010, 2013 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/Language.h"
-
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-String defaultLanguage()
-{
- Vector<String> languages = userPreferredLanguages();
- if (languages.size())
- return languages[0];
-
- return emptyString();
-}
-
-static Vector<String>& preferredLanguagesOverride()
-{
- DEFINE_STATIC_LOCAL(Vector<String>, override, ());
- return override;
-}
-
-Vector<String> userPreferredLanguagesOverride()
-{
- return preferredLanguagesOverride();
-}
-
-void overrideUserPreferredLanguages(const Vector<String>& override)
-{
- preferredLanguagesOverride() = override;
-}
-
-Vector<String> userPreferredLanguages()
-{
- Vector<String>& override = preferredLanguagesOverride();
- if (!override.isEmpty())
- return override;
-
- return platformUserPreferredLanguages();
-}
-
-static String canonicalLanguageIdentifier(const String& languageCode)
-{
- String lowercaseLanguageCode = languageCode.lower();
-
- if (lowercaseLanguageCode.length() >= 3 && lowercaseLanguageCode[2] == '_')
- lowercaseLanguageCode.replace(2, 1, "-");
-
- return lowercaseLanguageCode;
-}
-
-size_t indexOfBestMatchingLanguageInList(const String& language, const Vector<String>& languageList)
-{
- String languageWithoutLocaleMatch;
- String languageMatchButNotLocale;
- size_t languageWithoutLocaleMatchIndex = 0;
- size_t languageMatchButNotLocaleMatchIndex = 0;
- bool canMatchLanguageOnly = (language.length() == 2 || (language.length() >= 3 && language[2] == '-'));
-
- for (size_t i = 0; i < languageList.size(); ++i) {
- String canonicalizedLanguageFromList = canonicalLanguageIdentifier(languageList[i]);
-
- if (language == canonicalizedLanguageFromList)
- return i;
-
- if (canMatchLanguageOnly && canonicalizedLanguageFromList.length() >= 2) {
- if (language[0] == canonicalizedLanguageFromList[0] && language[1] == canonicalizedLanguageFromList[1]) {
- if (!languageWithoutLocaleMatch.length() && canonicalizedLanguageFromList.length() == 2) {
- languageWithoutLocaleMatch = languageList[i];
- languageWithoutLocaleMatchIndex = i;
- }
- if (!languageMatchButNotLocale.length() && canonicalizedLanguageFromList.length() >= 3) {
- languageMatchButNotLocale = languageList[i];
- languageMatchButNotLocaleMatchIndex = i;
- }
- }
- }
- }
-
- // If we have both a language-only match and a languge-but-not-locale match, return the
- // languge-only match as is considered a "better" match. For example, if the list
- // provided has both "en-GB" and "en" and the user prefers "en-US" we will return "en".
- if (languageWithoutLocaleMatch.length())
- return languageWithoutLocaleMatchIndex;
-
- if (languageMatchButNotLocale.length())
- return languageMatchButNotLocaleMatchIndex;
-
- return languageList.size();
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/Language.h b/chromium/third_party/WebKit/Source/core/platform/Language.h
deleted file mode 100644
index 26260855063..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/Language.h
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright (C) 2003, 2006, 2010, 2013 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef Language_h
-#define Language_h
-
-#include "wtf/Forward.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-String defaultLanguage();
-Vector<String> userPreferredLanguages();
-Vector<String> userPreferredLanguagesOverride();
-void overrideUserPreferredLanguages(const Vector<String>&);
-size_t indexOfBestMatchingLanguageInList(const String& language, const Vector<String>& languageList);
-
-Vector<String> platformUserPreferredLanguages();
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/LayoutTestSupport.cpp b/chromium/third_party/WebKit/Source/core/platform/LayoutTestSupport.cpp
deleted file mode 100644
index b6a75b1c26c..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/LayoutTestSupport.cpp
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/LayoutTestSupport.h"
-
-namespace WebCore {
-
-static bool s_isRunningLayoutTest = false;
-
-bool isRunningLayoutTest()
-{
- return s_isRunningLayoutTest;
-}
-
-void setIsRunningLayoutTest(bool value)
-{
- s_isRunningLayoutTest = value;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/LayoutTestSupport.h b/chromium/third_party/WebKit/Source/core/platform/LayoutTestSupport.h
deleted file mode 100644
index 48aa2191ad4..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/LayoutTestSupport.h
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef LayoutTestSupport_h
-#define LayoutTestSupport_h
-
-namespace WebCore {
-
-bool isRunningLayoutTest();
-void setIsRunningLayoutTest(bool);
-
-} // namespace WebCore
-
-#endif // LayoutTestSupport_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/LayoutUnit.h b/chromium/third_party/WebKit/Source/core/platform/LayoutUnit.h
deleted file mode 100644
index 712fc88e4fb..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/LayoutUnit.h
+++ /dev/null
@@ -1,799 +0,0 @@
-/*
- * Copyright (c) 2012, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef LayoutUnit_h
-#define LayoutUnit_h
-
-#include "wtf/Assertions.h"
-#include "wtf/MathExtras.h"
-#include "wtf/SaturatedArithmetic.h"
-#include <limits.h>
-#include <limits>
-#include <stdlib.h>
-
-namespace WebCore {
-
-#ifdef NDEBUG
-
-#define REPORT_OVERFLOW(doesOverflow) ((void)0)
-
-#else
-
-#define REPORT_OVERFLOW(doesOverflow) do \
- if (!(doesOverflow)) { \
- WTFReportError(__FILE__, __LINE__, WTF_PRETTY_FUNCTION, "!(%s)", #doesOverflow); \
- } \
-while (0)
-
-#endif
-
-static const int kFixedPointDenominator = 64;
-
-const int intMaxForLayoutUnit = INT_MAX / kFixedPointDenominator;
-const int intMinForLayoutUnit = INT_MIN / kFixedPointDenominator;
-
-class LayoutUnit {
-public:
- LayoutUnit() : m_value(0) { }
- LayoutUnit(int value) { setValue(value); }
- LayoutUnit(unsigned short value) { setValue(value); }
- LayoutUnit(unsigned value) { setValue(value); }
- LayoutUnit(unsigned long value) { m_value = clampTo<int>(value * kFixedPointDenominator); }
- LayoutUnit(unsigned long long value) { m_value = clampTo<int>(value * kFixedPointDenominator); }
- LayoutUnit(float value) { m_value = clampTo<float>(value * kFixedPointDenominator, static_cast<float>(INT_MIN), static_cast<float>(INT_MAX)); }
- LayoutUnit(double value) { m_value = clampTo<double>(value * kFixedPointDenominator, static_cast<double>(INT_MIN), static_cast<double>(INT_MAX)); }
-
- static LayoutUnit fromFloatCeil(float value)
- {
- LayoutUnit v;
- v.m_value = clampToInteger(ceilf(value * kFixedPointDenominator));
- return v;
- }
-
- static LayoutUnit fromFloatFloor(float value)
- {
- LayoutUnit v;
- v.m_value = clampToInteger(floorf(value * kFixedPointDenominator));
- return v;
- }
-
- static LayoutUnit fromFloatRound(float value)
- {
- if (value >= 0)
- return clamp(value + epsilon() / 2.0f);
- return clamp(value - epsilon() / 2.0f);
- }
-
- int toInt() const { return m_value / kFixedPointDenominator; }
- float toFloat() const { return static_cast<float>(m_value) / kFixedPointDenominator; }
- double toDouble() const { return static_cast<double>(m_value) / kFixedPointDenominator; }
- float ceilToFloat() const
- {
- float floatValue = toFloat();
- if (static_cast<int>(floatValue * kFixedPointDenominator) == m_value)
- return floatValue;
- if (floatValue > 0)
- return nextafterf(floatValue, std::numeric_limits<float>::max());
- return nextafterf(floatValue, std::numeric_limits<float>::min());
- }
- unsigned toUnsigned() const { REPORT_OVERFLOW(m_value >= 0); return toInt(); }
-
- operator int() const { return toInt(); }
- operator unsigned() const { return toUnsigned(); }
- operator float() const { return toFloat(); }
- operator double() const { return toDouble(); }
- operator bool() const { return m_value; }
-
- LayoutUnit operator++(int)
- {
- m_value += kFixedPointDenominator;
- return *this;
- }
-
- inline int rawValue() const { return m_value; }
- inline void setRawValue(int value) { m_value = value; }
- void setRawValue(long long value)
- {
- REPORT_OVERFLOW(value > std::numeric_limits<int>::min() && value < std::numeric_limits<int>::max());
- m_value = static_cast<int>(value);
- }
-
- LayoutUnit abs() const
- {
- LayoutUnit returnValue;
- returnValue.setRawValue(::abs(m_value));
- return returnValue;
- }
-#if OS(MACOSX)
- int wtf_ceil() const
-#else
- int ceil() const
-#endif
- {
- if (UNLIKELY(m_value >= INT_MAX - kFixedPointDenominator + 1))
- return intMaxForLayoutUnit;
-
- if (m_value >= 0)
- return (m_value + kFixedPointDenominator - 1) / kFixedPointDenominator;
- return toInt();
- }
- int round() const
- {
- if (m_value > 0)
- return saturatedAddition(rawValue(), kFixedPointDenominator / 2) / kFixedPointDenominator;
- return saturatedSubtraction(rawValue(), (kFixedPointDenominator / 2) - 1) / kFixedPointDenominator;
- }
-
- int floor() const
- {
- if (UNLIKELY(m_value <= INT_MIN + kFixedPointDenominator - 1))
- return intMinForLayoutUnit;
-
- if (m_value >= 0)
- return toInt();
- return (m_value - kFixedPointDenominator + 1) / kFixedPointDenominator;
- }
-
- LayoutUnit fraction() const
- {
- // Add the fraction to the size (as opposed to the full location) to avoid overflows.
- // Compute fraction using the mod operator to preserve the sign of the value as it may affect rounding.
- LayoutUnit fraction;
- fraction.setRawValue(rawValue() % kFixedPointDenominator);
- return fraction;
- }
-
- bool mightBeSaturated() const
- {
- return rawValue() == std::numeric_limits<int>::max()
- || rawValue() == std::numeric_limits<int>::min();
- }
-
- static float epsilon() { return 1.0f / kFixedPointDenominator; }
-
- static const LayoutUnit max()
- {
- LayoutUnit m;
- m.m_value = std::numeric_limits<int>::max();
- return m;
- }
- static const LayoutUnit min()
- {
- LayoutUnit m;
- m.m_value = std::numeric_limits<int>::min();
- return m;
- }
-
- // Versions of max/min that are slightly smaller/larger than max/min() to allow for roinding without overflowing.
- static const LayoutUnit nearlyMax()
- {
- LayoutUnit m;
- m.m_value = std::numeric_limits<int>::max() - kFixedPointDenominator / 2;
- return m;
- }
- static const LayoutUnit nearlyMin()
- {
- LayoutUnit m;
- m.m_value = std::numeric_limits<int>::min() + kFixedPointDenominator / 2;
- return m;
- }
-
- static LayoutUnit clamp(double value)
- {
- return clampTo<LayoutUnit>(value, LayoutUnit::min(), LayoutUnit::max());
- }
-
-private:
- static bool isInBounds(int value)
- {
- return ::abs(value) <= std::numeric_limits<int>::max() / kFixedPointDenominator;
- }
- static bool isInBounds(unsigned value)
- {
- return value <= static_cast<unsigned>(std::numeric_limits<int>::max()) / kFixedPointDenominator;
- }
- static bool isInBounds(double value)
- {
- return ::fabs(value) <= std::numeric_limits<int>::max() / kFixedPointDenominator;
- }
-
- inline void setValue(int value)
- {
- if (value > intMaxForLayoutUnit)
- m_value = std::numeric_limits<int>::max();
- else if (value < intMinForLayoutUnit)
- m_value = std::numeric_limits<int>::min();
- else
- m_value = value * kFixedPointDenominator;
- }
- inline void setValue(unsigned value)
- {
- if (value >= static_cast<unsigned>(intMaxForLayoutUnit))
- m_value = std::numeric_limits<int>::max();
- else
- m_value = value * kFixedPointDenominator;
- }
-
- int m_value;
-};
-
-inline bool operator<=(const LayoutUnit& a, const LayoutUnit& b)
-{
- return a.rawValue() <= b.rawValue();
-}
-
-inline bool operator<=(const LayoutUnit& a, float b)
-{
- return a.toFloat() <= b;
-}
-
-inline bool operator<=(const LayoutUnit& a, int b)
-{
- return a <= LayoutUnit(b);
-}
-
-inline bool operator<=(const float a, const LayoutUnit& b)
-{
- return a <= b.toFloat();
-}
-
-inline bool operator<=(const int a, const LayoutUnit& b)
-{
- return LayoutUnit(a) <= b;
-}
-
-inline bool operator>=(const LayoutUnit& a, const LayoutUnit& b)
-{
- return a.rawValue() >= b.rawValue();
-}
-
-inline bool operator>=(const LayoutUnit& a, int b)
-{
- return a >= LayoutUnit(b);
-}
-
-inline bool operator>=(const float a, const LayoutUnit& b)
-{
- return a >= b.toFloat();
-}
-
-inline bool operator>=(const LayoutUnit& a, float b)
-{
- return a.toFloat() >= b;
-}
-
-inline bool operator>=(const int a, const LayoutUnit& b)
-{
- return LayoutUnit(a) >= b;
-}
-
-inline bool operator<(const LayoutUnit& a, const LayoutUnit& b)
-{
- return a.rawValue() < b.rawValue();
-}
-
-inline bool operator<(const LayoutUnit& a, int b)
-{
- return a < LayoutUnit(b);
-}
-
-inline bool operator<(const LayoutUnit& a, float b)
-{
- return a.toFloat() < b;
-}
-
-inline bool operator<(const LayoutUnit& a, double b)
-{
- return a.toDouble() < b;
-}
-
-inline bool operator<(const int a, const LayoutUnit& b)
-{
- return LayoutUnit(a) < b;
-}
-
-inline bool operator<(const float a, const LayoutUnit& b)
-{
- return a < b.toFloat();
-}
-
-inline bool operator>(const LayoutUnit& a, const LayoutUnit& b)
-{
- return a.rawValue() > b.rawValue();
-}
-
-inline bool operator>(const LayoutUnit& a, double b)
-{
- return a.toDouble() > b;
-}
-
-inline bool operator>(const LayoutUnit& a, float b)
-{
- return a.toFloat() > b;
-}
-
-inline bool operator>(const LayoutUnit& a, int b)
-{
- return a > LayoutUnit(b);
-}
-
-inline bool operator>(const int a, const LayoutUnit& b)
-{
- return LayoutUnit(a) > b;
-}
-
-inline bool operator>(const float a, const LayoutUnit& b)
-{
- return a > b.toFloat();
-}
-
-inline bool operator>(const double a, const LayoutUnit& b)
-{
- return a > b.toDouble();
-}
-
-inline bool operator!=(const LayoutUnit& a, const LayoutUnit& b)
-{
- return a.rawValue() != b.rawValue();
-}
-
-inline bool operator!=(const LayoutUnit& a, float b)
-{
- return a != LayoutUnit(b);
-}
-
-inline bool operator!=(const int a, const LayoutUnit& b)
-{
- return LayoutUnit(a) != b;
-}
-
-inline bool operator!=(const LayoutUnit& a, int b)
-{
- return a != LayoutUnit(b);
-}
-
-inline bool operator==(const LayoutUnit& a, const LayoutUnit& b)
-{
- return a.rawValue() == b.rawValue();
-}
-
-inline bool operator==(const LayoutUnit& a, int b)
-{
- return a == LayoutUnit(b);
-}
-
-inline bool operator==(const int a, const LayoutUnit& b)
-{
- return LayoutUnit(a) == b;
-}
-
-inline bool operator==(const LayoutUnit& a, float b)
-{
- return a.toFloat() == b;
-}
-
-inline bool operator==(const float a, const LayoutUnit& b)
-{
- return a == b.toFloat();
-}
-
-// For multiplication that's prone to overflow, this bounds it to LayoutUnit::max() and ::min()
-inline LayoutUnit boundedMultiply(const LayoutUnit& a, const LayoutUnit& b)
-{
- int64_t result = static_cast<int64_t>(a.rawValue()) * static_cast<int64_t>(b.rawValue()) / kFixedPointDenominator;
- int32_t high = static_cast<int32_t>(result >> 32);
- int32_t low = static_cast<int32_t>(result);
- uint32_t saturated = (static_cast<uint32_t>(a.rawValue() ^ b.rawValue()) >> 31) + std::numeric_limits<int>::max();
- // If the higher 32 bits does not match the lower 32 with sign extension the operation overflowed.
- if (high != low >> 31)
- result = saturated;
-
- LayoutUnit returnVal;
- returnVal.setRawValue(static_cast<int>(result));
- return returnVal;
-}
-
-inline LayoutUnit operator*(const LayoutUnit& a, const LayoutUnit& b)
-{
- return boundedMultiply(a, b);
-}
-
-inline double operator*(const LayoutUnit& a, double b)
-{
- return a.toDouble() * b;
-}
-
-inline float operator*(const LayoutUnit& a, float b)
-{
- return a.toFloat() * b;
-}
-
-inline LayoutUnit operator*(const LayoutUnit& a, int b)
-{
- return a * LayoutUnit(b);
-}
-
-inline LayoutUnit operator*(const LayoutUnit& a, unsigned short b)
-{
- return a * LayoutUnit(b);
-}
-
-inline LayoutUnit operator*(const LayoutUnit& a, unsigned b)
-{
- return a * LayoutUnit(b);
-}
-
-inline LayoutUnit operator*(const LayoutUnit& a, unsigned long b)
-{
- return a * LayoutUnit(b);
-}
-
-inline LayoutUnit operator*(const LayoutUnit& a, unsigned long long b)
-{
- return a * LayoutUnit(b);
-}
-
-inline LayoutUnit operator*(unsigned short a, const LayoutUnit& b)
-{
- return LayoutUnit(a) * b;
-}
-
-inline LayoutUnit operator*(unsigned a, const LayoutUnit& b)
-{
- return LayoutUnit(a) * b;
-}
-
-inline LayoutUnit operator*(unsigned long a, const LayoutUnit& b)
-{
- return LayoutUnit(a) * b;
-}
-
-inline LayoutUnit operator*(unsigned long long a, const LayoutUnit& b)
-{
- return LayoutUnit(a) * b;
-}
-
-inline LayoutUnit operator*(const int a, const LayoutUnit& b)
-{
- return LayoutUnit(a) * b;
-}
-
-inline float operator*(const float a, const LayoutUnit& b)
-{
- return a * b.toFloat();
-}
-
-inline double operator*(const double a, const LayoutUnit& b)
-{
- return a * b.toDouble();
-}
-
-inline LayoutUnit operator/(const LayoutUnit& a, const LayoutUnit& b)
-{
- LayoutUnit returnVal;
- long long rawVal = static_cast<long long>(kFixedPointDenominator) * a.rawValue() / b.rawValue();
- returnVal.setRawValue(clampTo<int>(rawVal));
- return returnVal;
-}
-
-inline float operator/(const LayoutUnit& a, float b)
-{
- return a.toFloat() / b;
-}
-
-inline double operator/(const LayoutUnit& a, double b)
-{
- return a.toDouble() / b;
-}
-
-inline LayoutUnit operator/(const LayoutUnit& a, int b)
-{
- return a / LayoutUnit(b);
-}
-
-inline LayoutUnit operator/(const LayoutUnit& a, unsigned short b)
-{
- return a / LayoutUnit(b);
-}
-
-inline LayoutUnit operator/(const LayoutUnit& a, unsigned b)
-{
- return a / LayoutUnit(b);
-}
-
-inline LayoutUnit operator/(const LayoutUnit& a, unsigned long b)
-{
- return a / LayoutUnit(b);
-}
-
-inline LayoutUnit operator/(const LayoutUnit& a, unsigned long long b)
-{
- return a / LayoutUnit(b);
-}
-
-inline float operator/(const float a, const LayoutUnit& b)
-{
- return a / b.toFloat();
-}
-
-inline double operator/(const double a, const LayoutUnit& b)
-{
- return a / b.toDouble();
-}
-
-inline LayoutUnit operator/(const int a, const LayoutUnit& b)
-{
- return LayoutUnit(a) / b;
-}
-
-inline LayoutUnit operator/(unsigned short a, const LayoutUnit& b)
-{
- return LayoutUnit(a) / b;
-}
-
-inline LayoutUnit operator/(unsigned a, const LayoutUnit& b)
-{
- return LayoutUnit(a) / b;
-}
-
-inline LayoutUnit operator/(unsigned long a, const LayoutUnit& b)
-{
- return LayoutUnit(a) / b;
-}
-
-inline LayoutUnit operator/(unsigned long long a, const LayoutUnit& b)
-{
- return LayoutUnit(a) / b;
-}
-
-inline LayoutUnit operator+(const LayoutUnit& a, const LayoutUnit& b)
-{
- LayoutUnit returnVal;
- returnVal.setRawValue(saturatedAddition(a.rawValue(), b.rawValue()));
- return returnVal;
-}
-
-inline LayoutUnit operator+(const LayoutUnit& a, int b)
-{
- return a + LayoutUnit(b);
-}
-
-inline float operator+(const LayoutUnit& a, float b)
-{
- return a.toFloat() + b;
-}
-
-inline double operator+(const LayoutUnit& a, double b)
-{
- return a.toDouble() + b;
-}
-
-inline LayoutUnit operator+(const int a, const LayoutUnit& b)
-{
- return LayoutUnit(a) + b;
-}
-
-inline float operator+(const float a, const LayoutUnit& b)
-{
- return a + b.toFloat();
-}
-
-inline double operator+(const double a, const LayoutUnit& b)
-{
- return a + b.toDouble();
-}
-
-inline LayoutUnit operator-(const LayoutUnit& a, const LayoutUnit& b)
-{
- LayoutUnit returnVal;
- returnVal.setRawValue(saturatedSubtraction(a.rawValue(), b.rawValue()));
- return returnVal;
-}
-
-inline LayoutUnit operator-(const LayoutUnit& a, int b)
-{
- return a - LayoutUnit(b);
-}
-
-inline LayoutUnit operator-(const LayoutUnit& a, unsigned b)
-{
- return a - LayoutUnit(b);
-}
-
-inline float operator-(const LayoutUnit& a, float b)
-{
- return a.toFloat() - b;
-}
-
-inline LayoutUnit operator-(const int a, const LayoutUnit& b)
-{
- return LayoutUnit(a) - b;
-}
-
-inline float operator-(const float a, const LayoutUnit& b)
-{
- return a - b.toFloat();
-}
-
-inline LayoutUnit operator-(const LayoutUnit& a)
-{
- LayoutUnit returnVal;
- returnVal.setRawValue(-a.rawValue());
- return returnVal;
-}
-
-// For returning the remainder after a division with integer results.
-inline LayoutUnit intMod(const LayoutUnit& a, const LayoutUnit& b)
-{
- // This calculates the modulo so that: a = static_cast<int>(a / b) * b + intMod(a, b).
- LayoutUnit returnVal;
- returnVal.setRawValue(a.rawValue() % b.rawValue());
- return returnVal;
-}
-
-inline LayoutUnit operator%(const LayoutUnit& a, const LayoutUnit& b)
-{
- // This calculates the modulo so that: a = (a / b) * b + a % b.
- LayoutUnit returnVal;
- long long rawVal = (static_cast<long long>(kFixedPointDenominator) * a.rawValue()) % b.rawValue();
- returnVal.setRawValue(rawVal / kFixedPointDenominator);
- return returnVal;
-}
-
-inline LayoutUnit operator%(const LayoutUnit& a, int b)
-{
- return a % LayoutUnit(b);
-}
-
-inline LayoutUnit operator%(int a, const LayoutUnit& b)
-{
- return LayoutUnit(a) % b;
-}
-
-inline LayoutUnit& operator+=(LayoutUnit& a, const LayoutUnit& b)
-{
- a.setRawValue(saturatedAddition(a.rawValue(), b.rawValue()));
- return a;
-}
-
-inline LayoutUnit& operator+=(LayoutUnit& a, int b)
-{
- a = a + b;
- return a;
-}
-
-inline LayoutUnit& operator+=(LayoutUnit& a, float b)
-{
- a = a + b;
- return a;
-}
-
-inline float& operator+=(float& a, const LayoutUnit& b)
-{
- a = a + b;
- return a;
-}
-
-inline LayoutUnit& operator-=(LayoutUnit& a, int b)
-{
- a = a - b;
- return a;
-}
-
-inline LayoutUnit& operator-=(LayoutUnit& a, const LayoutUnit& b)
-{
- a.setRawValue(saturatedSubtraction(a.rawValue(), b.rawValue()));
- return a;
-}
-
-inline LayoutUnit& operator-=(LayoutUnit& a, float b)
-{
- a = a - b;
- return a;
-}
-
-inline float& operator-=(float& a, const LayoutUnit& b)
-{
- a = a - b;
- return a;
-}
-
-inline LayoutUnit& operator*=(LayoutUnit& a, const LayoutUnit& b)
-{
- a = a * b;
- return a;
-}
-// operator*=(LayoutUnit& a, int b) is supported by the operator above plus LayoutUnit(int).
-
-inline LayoutUnit& operator*=(LayoutUnit& a, float b)
-{
- a = a * b;
- return a;
-}
-
-inline float& operator*=(float& a, const LayoutUnit& b)
-{
- a = a * b;
- return a;
-}
-
-inline LayoutUnit& operator/=(LayoutUnit& a, const LayoutUnit& b)
-{
- a = a / b;
- return a;
-}
-// operator/=(LayoutUnit& a, int b) is supported by the operator above plus LayoutUnit(int).
-
-inline LayoutUnit& operator/=(LayoutUnit& a, float b)
-{
- a = a / b;
- return a;
-}
-
-inline float& operator/=(float& a, const LayoutUnit& b)
-{
- a = a / b;
- return a;
-}
-
-inline int snapSizeToPixel(LayoutUnit size, LayoutUnit location)
-{
- LayoutUnit fraction = location.fraction();
- return (fraction + size).round() - fraction.round();
-}
-
-inline int roundToInt(LayoutUnit value)
-{
- return value.round();
-}
-
-inline int floorToInt(LayoutUnit value)
-{
- return value.floor();
-}
-
-inline LayoutUnit absoluteValue(const LayoutUnit& value)
-{
- return value.abs();
-}
-
-inline LayoutUnit layoutMod(const LayoutUnit& numerator, const LayoutUnit& denominator)
-{
- return numerator % denominator;
-}
-
-inline bool isIntegerValue(const LayoutUnit value)
-{
- return value.toInt() == value;
-}
-
-} // namespace WebCore
-
-#endif // LayoutUnit_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/Length.cpp b/chromium/third_party/WebKit/Source/core/platform/Length.cpp
deleted file mode 100644
index 95a3733e2b2..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/Length.cpp
+++ /dev/null
@@ -1,219 +0,0 @@
-/*
- * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
- * (C) 1999 Antti Koivisto (koivisto@kde.org)
- * (C) 2001 Dirk Mueller ( mueller@kde.org )
- * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
- * Copyright (C) 2006 Andrew Wellington (proton@wiretapped.net)
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#include "config.h"
-#include "core/platform/Length.h"
-
-#include "core/platform/CalculationValue.h"
-#include "wtf/ASCIICType.h"
-#include "wtf/Assertions.h"
-#include "wtf/text/StringBuffer.h"
-#include "wtf/text/WTFString.h"
-
-using namespace WTF;
-
-namespace WebCore {
-
-template<typename CharType>
-static unsigned splitLength(const CharType* data, unsigned length, unsigned& intLength, unsigned& doubleLength)
-{
- ASSERT(length);
-
- unsigned i = 0;
- while (i < length && isSpaceOrNewline(data[i]))
- ++i;
- if (i < length && (data[i] == '+' || data[i] == '-'))
- ++i;
- while (i < length && isASCIIDigit(data[i]))
- ++i;
- intLength = i;
- while (i < length && (isASCIIDigit(data[i]) || data[i] == '.'))
- ++i;
- doubleLength = i;
-
- // IE quirk: Skip whitespace between the number and the % character (20 % => 20%).
- while (i < length && isSpaceOrNewline(data[i]))
- ++i;
-
- return i;
-}
-
-template<typename CharType>
-static Length parseHTMLAreaCoordinate(const CharType* data, unsigned length)
-{
- unsigned intLength;
- unsigned doubleLength;
- splitLength(data, length, intLength, doubleLength);
-
- bool ok;
- int r = charactersToIntStrict(data, intLength, &ok);
- if (ok)
- return Length(r, Fixed);
- return Length(0, Fixed);
-}
-
-// FIXME: Per HTML5, this should follow the "rules for parsing a list of integers".
-Vector<Length> parseHTMLAreaElementCoords(const String& string)
-{
- unsigned length = string.length();
- StringBuffer<LChar> spacified(length);
- for (unsigned i = 0; i < length; i++) {
- UChar cc = string[i];
- if (cc > '9' || (cc < '0' && cc != '-' && cc != '.'))
- spacified[i] = ' ';
- else
- spacified[i] = cc;
- }
- RefPtr<StringImpl> str = spacified.release();
- str = str->simplifyWhiteSpace();
- ASSERT(str->is8Bit());
-
- if (!str->length())
- return Vector<Length>();
-
- unsigned len = str->count(' ') + 1;
- Vector<Length> r(len);
-
- int i = 0;
- unsigned pos = 0;
- size_t pos2;
-
- while ((pos2 = str->find(' ', pos)) != kNotFound) {
- r[i++] = parseHTMLAreaCoordinate(str->characters8() + pos, pos2 - pos);
- pos = pos2 + 1;
- }
- r[i] = parseHTMLAreaCoordinate(str->characters8() + pos, str->length() - pos);
-
- ASSERT(i == len - 1);
-
- return r;
-}
-
-class CalculationValueHandleMap {
- WTF_MAKE_FAST_ALLOCATED;
-public:
- CalculationValueHandleMap()
- : m_index(1)
- {
- }
-
- int insert(PassRefPtr<CalculationValue> calcValue)
- {
- ASSERT(m_index);
- // FIXME calc(): https://bugs.webkit.org/show_bug.cgi?id=80489
- // This monotonically increasing handle generation scheme is potentially wasteful
- // of the handle space. Consider reusing empty handles.
- while (m_map.contains(m_index))
- m_index++;
-
- m_map.set(m_index, calcValue);
-
- return m_index;
- }
-
- void remove(int index)
- {
- ASSERT(m_map.contains(index));
- m_map.remove(index);
- }
-
- PassRefPtr<CalculationValue> get(int index)
- {
- ASSERT(m_map.contains(index));
- return m_map.get(index);
- }
-
-private:
- int m_index;
- HashMap<int, RefPtr<CalculationValue> > m_map;
-};
-
-static CalculationValueHandleMap& calcHandles()
-{
- DEFINE_STATIC_LOCAL(CalculationValueHandleMap, handleMap, ());
- return handleMap;
-}
-
-Length::Length(PassRefPtr<CalculationValue> calc)
- : m_quirk(false)
- , m_type(Calculated)
- , m_isFloat(false)
-{
- m_intValue = calcHandles().insert(calc);
-}
-
-Length Length::blendMixedTypes(const Length& from, double progress) const
-{
- if (progress <= 0.0)
- return from;
-
- if (progress >= 1.0)
- return *this;
-
- OwnPtr<CalcExpressionNode> blend = adoptPtr(new CalcExpressionBlendLength(from, *this, progress));
- return Length(CalculationValue::create(blend.release(), CalculationRangeAll));
-}
-
-PassRefPtr<CalculationValue> Length::calculationValue() const
-{
- ASSERT(isCalculated());
- return calcHandles().get(calculationHandle());
-}
-
-void Length::incrementCalculatedRef() const
-{
- ASSERT(isCalculated());
- calculationValue()->ref();
-}
-
-void Length::decrementCalculatedRef() const
-{
- ASSERT(isCalculated());
- RefPtr<CalculationValue> calcLength = calculationValue();
- if (calcLength->hasOneRef())
- calcHandles().remove(calculationHandle());
- calcLength->deref();
-}
-
-float Length::nonNanCalculatedValue(int maxValue) const
-{
- ASSERT(isCalculated());
- float result = calculationValue()->evaluate(maxValue);
- if (std::isnan(result))
- return 0;
- return result;
-}
-
-bool Length::isCalculatedEqual(const Length& o) const
-{
- return isCalculated() && (calculationValue() == o.calculationValue() || *calculationValue() == *o.calculationValue());
-}
-
-struct SameSizeAsLength {
- int32_t value;
- int32_t metaData;
-};
-COMPILE_ASSERT(sizeof(Length) == sizeof(SameSizeAsLength), length_should_stay_small);
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/Length.h b/chromium/third_party/WebKit/Source/core/platform/Length.h
deleted file mode 100644
index 1a655d464d0..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/Length.h
+++ /dev/null
@@ -1,320 +0,0 @@
-/*
- Copyright (C) 1999 Lars Knoll (knoll@kde.org)
- Copyright (C) 2006, 2008 Apple Inc. All rights reserved.
- Copyright (C) 2011 Rik Cabanier (cabanier@adobe.com)
- Copyright (C) 2011 Adobe Systems Incorporated. All rights reserved.
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#ifndef Length_h
-#define Length_h
-
-#include <cstring>
-#include "core/platform/animation/AnimationUtilities.h"
-#include "wtf/Assertions.h"
-#include "wtf/FastAllocBase.h"
-#include "wtf/Forward.h"
-#include "wtf/HashMap.h"
-#include "wtf/MathExtras.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-enum LengthType {
- Auto, Relative, Percent, Fixed,
- Intrinsic, MinIntrinsic,
- MinContent, MaxContent, FillAvailable, FitContent,
- Calculated,
- ViewportPercentageWidth, ViewportPercentageHeight, ViewportPercentageMin, ViewportPercentageMax,
- ExtendToZoom,
- Undefined
-};
-
-class CalculationValue;
-
-struct Length {
- WTF_MAKE_FAST_ALLOCATED;
-public:
- Length()
- : m_intValue(0), m_quirk(false), m_type(Auto), m_isFloat(false)
- {
- }
-
- Length(LengthType t)
- : m_intValue(0), m_quirk(false), m_type(t), m_isFloat(false)
- {
- ASSERT(t != Calculated);
- }
-
- Length(int v, LengthType t, bool q = false)
- : m_intValue(v), m_quirk(q), m_type(t), m_isFloat(false)
- {
- ASSERT(t != Calculated);
- }
-
- Length(LayoutUnit v, LengthType t, bool q = false)
- : m_floatValue(v.toFloat()), m_quirk(q), m_type(t), m_isFloat(true)
- {
- ASSERT(t != Calculated);
- }
-
- Length(float v, LengthType t, bool q = false)
- : m_floatValue(v), m_quirk(q), m_type(t), m_isFloat(true)
- {
- ASSERT(t != Calculated);
- }
-
- Length(double v, LengthType t, bool q = false)
- : m_quirk(q), m_type(t), m_isFloat(true)
- {
- m_floatValue = static_cast<float>(v);
- }
-
- explicit Length(PassRefPtr<CalculationValue>);
-
- Length(const Length& length)
- {
- initFromLength(length);
- }
-
- Length& operator=(const Length& length)
- {
- initFromLength(length);
- return *this;
- }
-
- ~Length()
- {
- if (isCalculated())
- decrementCalculatedRef();
- }
-
- bool operator==(const Length& o) const { return (m_type == o.m_type) && (m_quirk == o.m_quirk) && (isUndefined() || (getFloatValue() == o.getFloatValue()) || isCalculatedEqual(o)); }
- bool operator!=(const Length& o) const { return !(*this == o); }
-
- const Length& operator*=(float v)
- {
- if (isCalculated()) {
- ASSERT_NOT_REACHED();
- return *this;
- }
-
- if (m_isFloat)
- m_floatValue = static_cast<float>(m_floatValue * v);
- else
- m_intValue = static_cast<int>(m_intValue * v);
-
- return *this;
- }
-
- inline float value() const
- {
- return getFloatValue();
- }
-
- int intValue() const
- {
- if (isCalculated()) {
- ASSERT_NOT_REACHED();
- return 0;
- }
- return getIntValue();
- }
-
- float percent() const
- {
- ASSERT(type() == Percent);
- return getFloatValue();
- }
-
- PassRefPtr<CalculationValue> calculationValue() const;
-
- LengthType type() const { return static_cast<LengthType>(m_type); }
- bool quirk() const { return m_quirk; }
-
- void setQuirk(bool quirk)
- {
- m_quirk = quirk;
- }
-
- void setValue(LengthType t, int value)
- {
- m_type = t;
- m_intValue = value;
- m_isFloat = false;
- }
-
- void setValue(int value)
- {
- if (isCalculated()) {
- ASSERT_NOT_REACHED();
- return;
- }
- setValue(Fixed, value);
- }
-
- void setValue(LengthType t, float value)
- {
- m_type = t;
- m_floatValue = value;
- m_isFloat = true;
- }
-
- void setValue(LengthType t, LayoutUnit value)
- {
- m_type = t;
- m_floatValue = value;
- m_isFloat = true;
- }
-
- void setValue(float value)
- {
- *this = Length(value, Fixed);
- }
-
- bool isUndefined() const { return type() == Undefined; }
-
- // FIXME calc: https://bugs.webkit.org/show_bug.cgi?id=80357. A calculated Length
- // always contains a percentage, and without a maxValue passed to these functions
- // it's impossible to determine the sign or zero-ness. We assume all calc values
- // are positive and non-zero for now.
- bool isZero() const
- {
- ASSERT(!isUndefined());
- if (isCalculated())
- return false;
-
- return m_isFloat ? !m_floatValue : !m_intValue;
- }
- bool isPositive() const
- {
- if (isUndefined())
- return false;
- if (isCalculated())
- return true;
-
- return getFloatValue() > 0;
- }
- bool isNegative() const
- {
- if (isUndefined() || isCalculated())
- return false;
-
- return getFloatValue() < 0;
- }
-
- bool isAuto() const { return type() == Auto; }
- bool isRelative() const { return type() == Relative; }
- bool isPercent() const { return type() == Percent || type() == Calculated; }
- bool isFixed() const { return type() == Fixed; }
- bool isIntrinsicOrAuto() const { return type() == Auto || isLegacyIntrinsic() || isIntrinsic(); }
- bool isLegacyIntrinsic() const { return type() == Intrinsic || type() == MinIntrinsic; }
- bool isIntrinsic() const { return type() == MinContent || type() == MaxContent || type() == FillAvailable || type() == FitContent; }
- bool isSpecified() const { return type() == Fixed || type() == Percent || type() == Calculated || isViewportPercentage(); }
- bool isSpecifiedOrIntrinsic() const { return isSpecified() || isIntrinsic(); }
- bool isCalculated() const { return type() == Calculated; }
- bool isCalculatedEqual(const Length&) const;
- bool isMinContent() const { return type() == MinContent; }
- bool isMaxContent() const { return type() == MaxContent; }
- bool isFillAvailable() const { return type() == FillAvailable; }
- bool isFitContent() const { return type() == FitContent; }
-
- Length blend(const Length& from, double progress) const
- {
- if (isUndefined() || from.isUndefined())
- return *this;
-
- // Blend two lengths to produce a new length that is in between them. Used for animation.
- if (from.type() == Calculated || type() == Calculated)
- return blendMixedTypes(from, progress);
-
- if (!from.isZero() && !isZero() && from.type() != type())
- return blendMixedTypes(from, progress);
-
- if (from.isZero() && isZero())
- return *this;
-
- LengthType resultType = type();
- if (isZero())
- resultType = from.type();
-
- if (resultType == Percent) {
- float fromPercent = from.isZero() ? 0 : from.percent();
- float toPercent = isZero() ? 0 : percent();
- return Length(WebCore::blend(fromPercent, toPercent, progress), Percent);
- }
-
- float fromValue = from.isZero() ? 0 : from.value();
- float toValue = isZero() ? 0 : value();
- return Length(WebCore::blend(fromValue, toValue, progress), resultType);
- }
-
- float getFloatValue() const
- {
- ASSERT(!isUndefined());
- return m_isFloat ? m_floatValue : m_intValue;
- }
- float nonNanCalculatedValue(int maxValue) const;
-
- bool isViewportPercentage() const
- {
- LengthType lengthType = type();
- return lengthType >= ViewportPercentageWidth && lengthType <= ViewportPercentageMax;
- }
- float viewportPercentageLength() const
- {
- ASSERT(isViewportPercentage());
- return getFloatValue();
- }
-private:
- int getIntValue() const
- {
- ASSERT(!isUndefined());
- return m_isFloat ? static_cast<int>(m_floatValue) : m_intValue;
- }
- void initFromLength(const Length& length)
- {
- memcpy(this, &length, sizeof(Length));
-
- if (isCalculated())
- incrementCalculatedRef();
- }
-
- Length blendMixedTypes(const Length& from, double progress) const;
-
- int calculationHandle() const
- {
- ASSERT(isCalculated());
- return getIntValue();
- }
- void incrementCalculatedRef() const;
- void decrementCalculatedRef() const;
-
- union {
- int m_intValue;
- float m_floatValue;
- };
- bool m_quirk;
- unsigned char m_type;
- bool m_isFloat;
-};
-
-Vector<Length> parseHTMLAreaElementCoords(const String&);
-
-} // namespace WebCore
-
-#endif // Length_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/LengthBox.cpp b/chromium/third_party/WebKit/Source/core/platform/LengthBox.cpp
deleted file mode 100644
index f2a2e70d491..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/LengthBox.cpp
+++ /dev/null
@@ -1,92 +0,0 @@
-/*
- * Copyright (c) 2012, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/LengthBox.h"
-
-namespace WebCore {
-
-Length LengthBox::logicalLeft(WritingMode writingMode) const
-{
- return isHorizontalWritingMode(writingMode) ? m_left : m_top;
-}
-
-Length LengthBox::logicalRight(WritingMode writingMode) const
-{
- return isHorizontalWritingMode(writingMode) ? m_right : m_bottom;
-}
-
-Length LengthBox::before(WritingMode writingMode) const
-{
- switch (writingMode) {
- case TopToBottomWritingMode:
- return m_top;
- case BottomToTopWritingMode:
- return m_bottom;
- case LeftToRightWritingMode:
- return m_left;
- case RightToLeftWritingMode:
- return m_right;
- }
- ASSERT_NOT_REACHED();
- return m_top;
-}
-
-Length LengthBox::after(WritingMode writingMode) const
-{
- switch (writingMode) {
- case TopToBottomWritingMode:
- return m_bottom;
- case BottomToTopWritingMode:
- return m_top;
- case LeftToRightWritingMode:
- return m_right;
- case RightToLeftWritingMode:
- return m_left;
- }
- ASSERT_NOT_REACHED();
- return m_bottom;
-}
-
-Length LengthBox::start(WritingMode writingMode, TextDirection direction) const
-{
- if (isHorizontalWritingMode(writingMode))
- return isLeftToRightDirection(direction) ? m_left : m_right;
- return isLeftToRightDirection(direction) ? m_top : m_bottom;
-}
-
-Length LengthBox::end(WritingMode writingMode, TextDirection direction) const
-{
- if (isHorizontalWritingMode(writingMode))
- return isLeftToRightDirection(direction) ? m_right : m_left;
- return isLeftToRightDirection(direction) ? m_bottom : m_top;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/LengthBox.h b/chromium/third_party/WebKit/Source/core/platform/LengthBox.h
deleted file mode 100644
index a0e13e23561..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/LengthBox.h
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- Copyright (C) 1999 Lars Knoll (knoll@kde.org)
- Copyright (C) 2006, 2008 Apple Inc. All rights reserved.
- Copyright (c) 2012, Google Inc. All rights reserved.
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#ifndef LengthBox_h
-#define LengthBox_h
-
-#include "core/platform/Length.h"
-#include "core/platform/text/TextDirection.h"
-#include "core/platform/text/WritingMode.h"
-
-namespace WebCore {
-
-class RenderStyle;
-
-struct LengthBox {
- LengthBox()
- {
- }
-
- LengthBox(LengthType t)
- : m_left(t)
- , m_right(t)
- , m_top(t)
- , m_bottom(t)
- {
- }
-
- LengthBox(int v)
- : m_left(Length(v, Fixed))
- , m_right(Length(v, Fixed))
- , m_top(Length(v, Fixed))
- , m_bottom(Length(v, Fixed))
- {
- }
-
- LengthBox(Length t, Length r, Length b, Length l)
- : m_left(l)
- , m_right(r)
- , m_top(t)
- , m_bottom(b)
- {
- }
-
- LengthBox(int t, int r, int b, int l)
- : m_left(Length(l, Fixed))
- , m_right(Length(r, Fixed))
- , m_top(Length(t, Fixed))
- , m_bottom(Length(b, Fixed))
- {
- }
-
- Length left() const { return m_left; }
- Length right() const { return m_right; }
- Length top() const { return m_top; }
- Length bottom() const { return m_bottom; }
-
- Length logicalLeft(WritingMode) const;
- Length logicalRight(WritingMode) const;
-
- Length before(WritingMode) const;
- Length after(WritingMode) const;
- Length start(WritingMode, TextDirection) const;
- Length end(WritingMode, TextDirection) const;
-
- bool operator==(const LengthBox& o) const
- {
- return m_left == o.m_left && m_right == o.m_right && m_top == o.m_top && m_bottom == o.m_bottom;
- }
-
- bool operator!=(const LengthBox& o) const
- {
- return !(*this == o);
- }
-
- bool nonZero() const
- {
- return !(m_left.isZero() && m_right.isZero() && m_top.isZero() && m_bottom.isZero());
- }
-
- Length m_left;
- Length m_right;
- Length m_top;
- Length m_bottom;
-};
-
-} // namespace WebCore
-
-#endif // LengthBox_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/LengthPoint.h b/chromium/third_party/WebKit/Source/core/platform/LengthPoint.h
deleted file mode 100644
index 151a852579c..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/LengthPoint.h
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * Copyright (c) 2013, Opera Software ASA. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Opera Software ASA nor the names of its
- * contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
- * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
- * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
- * OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef LengthPoint_h
-#define LengthPoint_h
-
-#include "core/platform/Length.h"
-
-namespace WebCore {
-
-struct LengthPoint {
-public:
- LengthPoint()
- {
- }
-
- LengthPoint(Length x, Length y)
- : m_x(x)
- , m_y(y)
- {
- }
-
- bool operator==(const LengthPoint& o) const { return m_x == o.m_x && m_y == o.m_y; }
- bool operator!=(const LengthPoint& o) const { return m_x != o.m_x || m_y != o.m_y; }
-
- void setX(Length x) { m_x = x; }
- Length x() const { return m_x; }
-
- void setY(Length y) { m_y = y; }
- Length y() const { return m_y; }
-
-private:
- Length m_x;
- Length m_y;
-};
-
-} // namespace WebCore
-
-#endif // LengthPoint_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/LengthSize.h b/chromium/third_party/WebKit/Source/core/platform/LengthSize.h
deleted file mode 100644
index 623bb1cdd20..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/LengthSize.h
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- Copyright (C) 1999 Lars Knoll (knoll@kde.org)
- Copyright (C) 2006, 2008 Apple Inc. All rights reserved.
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#ifndef LengthSize_h
-#define LengthSize_h
-
-#include "core/platform/Length.h"
-
-namespace WebCore {
-
-struct LengthSize {
-public:
- LengthSize()
- {
- }
-
- LengthSize(Length width, Length height)
- : m_width(width)
- , m_height(height)
- {
- }
-
- bool operator==(const LengthSize& o) const
- {
- return m_width == o.m_width && m_height == o.m_height;
- }
-
- void setWidth(Length width) { m_width = width; }
- Length width() const { return m_width; }
-
- void setHeight(Length height) { m_height = height; }
- Length height() const { return m_height; }
-
-private:
- Length m_width;
- Length m_height;
-};
-
-} // namespace WebCore
-
-#endif // LengthSize_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/LifecycleContext.cpp b/chromium/third_party/WebKit/Source/core/platform/LifecycleContext.cpp
deleted file mode 100644
index d0b21656f51..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/LifecycleContext.cpp
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-#include "config.h"
-#include "core/platform/LifecycleContext.h"
-
-#include "core/platform/LifecycleNotifier.h"
-
-namespace WebCore {
-
-LifecycleContext::LifecycleContext()
-{
-}
-
-LifecycleContext::~LifecycleContext()
-{
-}
-
-void LifecycleContext::wasObservedBy(LifecycleObserver* observer)
-{
- lifecycleNotifier()->addObserver(observer);
-}
-
-void LifecycleContext::wasUnobservedBy(LifecycleObserver* observer)
-{
- lifecycleNotifier()->removeObserver(observer);
-}
-
-LifecycleNotifier* LifecycleContext::lifecycleNotifier()
-{
- if (!m_lifecycleNotifier)
- m_lifecycleNotifier = const_cast<LifecycleContext*>(this)->createLifecycleNotifier();
- return m_lifecycleNotifier.get();
-}
-
-PassOwnPtr<LifecycleNotifier> LifecycleContext::createLifecycleNotifier()
-{
- return LifecycleNotifier::create(this);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/LifecycleContext.h b/chromium/third_party/WebKit/Source/core/platform/LifecycleContext.h
deleted file mode 100644
index c23e8d3556c..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/LifecycleContext.h
+++ /dev/null
@@ -1,65 +0,0 @@
-
-/*
- * Copyright (C) 2013 Google Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-#ifndef LifecycleContext_h
-#define LifecycleContext_h
-
-#include "core/platform/LifecycleObserver.h"
-#include "wtf/HashSet.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/PassOwnPtr.h"
-
-namespace WebCore {
-
-class LifecycleNotifier;
-class LifecycleObserver;
-
-class LifecycleContext {
-public:
- LifecycleContext();
- virtual ~LifecycleContext();
-
- virtual bool isContextThread() const { return true; }
-
- // Called from the constructor of observers.
- void wasObservedBy(LifecycleObserver*);
-
- // Called from the destructor of observers.
- void wasUnobservedBy(LifecycleObserver*);
-
-protected:
- LifecycleNotifier* lifecycleNotifier();
-
-private:
- virtual PassOwnPtr<LifecycleNotifier> createLifecycleNotifier();
-
- OwnPtr<LifecycleNotifier> m_lifecycleNotifier;
-};
-
-} // namespace WebCore
-
-#endif // LifecycleContext_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/LifecycleNotifier.cpp b/chromium/third_party/WebKit/Source/core/platform/LifecycleNotifier.cpp
deleted file mode 100644
index 0afb5728d7c..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/LifecycleNotifier.cpp
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Copyright (C) 2008 Apple Inc. All Rights Reserved.
- * Copyright (C) 2013 Google Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-#include "config.h"
-#include "core/platform/LifecycleNotifier.h"
-
-namespace WebCore {
-
-LifecycleNotifier::LifecycleNotifier(LifecycleContext* context)
- : m_context(context)
- , m_inDestructor(false)
- , m_iterating(IteratingNone)
-{
-}
-
-LifecycleNotifier::~LifecycleNotifier()
-{
- m_inDestructor = true;
- for (ObserverSet::iterator it = m_observers.begin(); it != m_observers.end(); it = m_observers.begin()) {
- LifecycleObserver* observer = *it;
- m_observers.remove(observer);
- ASSERT(observer->lifecycleContext() == m_context);
- observer->contextDestroyed();
- }
-}
-
-void LifecycleNotifier::addObserver(LifecycleObserver* observer)
-{
- RELEASE_ASSERT(!m_inDestructor);
- m_observers.add(observer);
-}
-
-void LifecycleNotifier::removeObserver(LifecycleObserver* observer)
-{
- RELEASE_ASSERT(!m_inDestructor);
- m_observers.remove(observer);
-}
-
-LifecycleContext* LifecycleNotifier::context()
-{
- return m_context;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/LifecycleNotifier.h b/chromium/third_party/WebKit/Source/core/platform/LifecycleNotifier.h
deleted file mode 100644
index 0dea4ef0791..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/LifecycleNotifier.h
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * Copyright (C) 2008 Apple Inc. All Rights Reserved.
- * Copyright (C) 2013 Google Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-#ifndef LifecycleNotifier_h
-#define LifecycleNotifier_h
-
-#include "core/platform/LifecycleObserver.h"
-#include "wtf/HashSet.h"
-#include "wtf/PassOwnPtr.h"
-
-namespace WebCore {
-
-class LifecycleContext;
-class LifecycleObserver;
-
-class LifecycleNotifier {
-public:
- static PassOwnPtr<LifecycleNotifier> create(LifecycleContext*);
-
- virtual ~LifecycleNotifier();
-
- virtual void addObserver(LifecycleObserver*);
- virtual void removeObserver(LifecycleObserver*);
-
-protected:
- explicit LifecycleNotifier(LifecycleContext*);
-
- LifecycleContext* context();
-
- enum IterationType {
- IteratingNone,
- IteratingOverActiveDOMObjects,
- IteratingOverContextObservers,
- IteratingOverDocumentObservers,
- IteratingOverPageObservers,
- IteratingOverDOMWindowObservers
- };
-
- IterationType m_iterating;
-
-private:
- typedef HashSet<LifecycleObserver*> ObserverSet;
-
- ObserverSet m_observers;
- LifecycleContext* m_context;
- bool m_inDestructor;
-};
-
-inline PassOwnPtr<LifecycleNotifier> LifecycleNotifier::create(LifecycleContext* context)
-{
- return adoptPtr(new LifecycleNotifier(context));
-}
-
-} // namespace WebCore
-
-#endif // LifecycleNotifier_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/LifecycleObserver.cpp b/chromium/third_party/WebKit/Source/core/platform/LifecycleObserver.cpp
deleted file mode 100644
index 97452bab36d..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/LifecycleObserver.cpp
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright (C) 2008 Apple Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-#include "config.h"
-#include "core/platform/LifecycleObserver.h"
-
-#include "core/platform/LifecycleContext.h"
-
-namespace WebCore {
-
-LifecycleObserver::LifecycleObserver(LifecycleContext* lifecycleContext, Type type)
- : m_lifecycleContext(0)
- , m_observerType(type)
-{
- observeContext(lifecycleContext);
-}
-
-LifecycleObserver::~LifecycleObserver()
-{
- observeContext(0);
-}
-
-void LifecycleObserver::observeContext(LifecycleContext* context)
-{
- if (m_lifecycleContext) {
- ASSERT(m_lifecycleContext->isContextThread());
- m_lifecycleContext->wasUnobservedBy(this);
- }
-
- m_lifecycleContext = context;
-
- if (m_lifecycleContext) {
- ASSERT(m_lifecycleContext->isContextThread());
- m_lifecycleContext->wasObservedBy(this);
- }
-}
-
-void LifecycleObserver::contextDestroyed()
-{
- m_lifecycleContext = 0;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/LifecycleObserver.h b/chromium/third_party/WebKit/Source/core/platform/LifecycleObserver.h
deleted file mode 100644
index 19b00f92b3e..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/LifecycleObserver.h
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * Copyright (C) 2008 Apple Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-#ifndef LifecycleObserver_h
-#define LifecycleObserver_h
-
-namespace WebCore {
-
-class LifecycleContext;
-
-class LifecycleObserver {
-public:
- enum Type {
- ActiveDOMObjectType,
- DocumentLifecycleObserverType,
- GenericType,
- PageLifecycleObserverType,
- DOMWindowLifecycleObserverType
- };
-
- explicit LifecycleObserver(LifecycleContext*, Type = GenericType);
-
- virtual void contextDestroyed();
-
- LifecycleContext* lifecycleContext() const { return m_lifecycleContext; }
- Type observerType() const { return m_observerType; }
-
-protected:
- virtual ~LifecycleObserver();
-
- void observeContext(LifecycleContext*);
-
- LifecycleContext* m_lifecycleContext;
- Type m_observerType;
-};
-
-} // namespace WebCore
-
-#endif // LifecycleObserver_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/LinkHash.cpp b/chromium/third_party/WebKit/Source/core/platform/LinkHash.cpp
deleted file mode 100644
index 03d4bb639f2..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/LinkHash.cpp
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Copyright (c) 2008, 2009, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/LinkHash.h"
-
-#include "public/platform/Platform.h"
-#include "weborigin/KURL.h"
-#include "wtf/text/StringUTF8Adaptor.h"
-#include <url/url_util.h>
-
-namespace WebCore {
-
-static bool resolveRelative(const KURL& base, const String& relative, url_canon::RawCanonOutput<2048>* buffer)
-{
- // We use these low-level GURL functions to avoid converting back and forth from UTF-8 unnecessarily.
- url_parse::Parsed parsed;
- StringUTF8Adaptor baseUTF8(base.string());
- if (relative.is8Bit()) {
- StringUTF8Adaptor relativeUTF8(relative);
- return url_util::ResolveRelative(baseUTF8.data(), baseUTF8.length(), base.parsed(), relativeUTF8.data(), relativeUTF8.length(), 0, buffer, &parsed);
- }
- return url_util::ResolveRelative(baseUTF8.data(), baseUTF8.length(), base.parsed(), relative.characters16(), relative.length(), 0, buffer, &parsed);
-}
-
-LinkHash visitedLinkHash(const KURL& base, const AtomicString& relative)
-{
- if (relative.isNull())
- return 0;
- url_canon::RawCanonOutput<2048> buffer;
- if (!resolveRelative(base, relative.string(), &buffer))
- return 0;
- return WebKit::Platform::current()->visitedLinkHash(buffer.data(), buffer.length());
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/LinkHash.h b/chromium/third_party/WebKit/Source/core/platform/LinkHash.h
deleted file mode 100644
index 4ea5cec8370..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/LinkHash.h
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Copyright (C) 2008 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef LinkHash_h
-#define LinkHash_h
-
-#include "wtf/Forward.h"
-#include "wtf/text/StringHash.h"
-
-namespace WebCore {
-
-class KURL;
-
-typedef uint64_t LinkHash;
-
-// Use the low 32-bits of the 64-bit LinkHash as the key for HashSets.
-struct LinkHashHash {
- static unsigned hash(LinkHash key) { return static_cast<unsigned>(key); }
- static bool equal(LinkHash a, LinkHash b) { return a == b; }
- static const bool safeToCompareToEmptyOrDeleted = true;
-
- // See AlreadyHashed::avoidDeletedValue.
- static unsigned avoidDeletedValue(LinkHash hash64)
- {
- ASSERT(hash64);
- unsigned hash = static_cast<unsigned>(hash64);
- unsigned newHash = hash | (!(hash + 1) << 31);
- ASSERT(newHash);
- ASSERT(newHash != 0xFFFFFFFF);
- return newHash;
- }
-};
-
-// Resolves the potentially relative URL "attributeURL" relative to the given
-// base URL, and returns the hash of the string that will be used for visited
-// link coloring. It will return the special value of 0 if attributeURL does not
-// look like a relative URL.
-LinkHash visitedLinkHash(const KURL& base, const AtomicString& attributeURL);
-
-} // namespace WebCore
-
-#endif // LinkHash_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/LocalizedStrings.cpp b/chromium/third_party/WebKit/Source/core/platform/LocalizedStrings.cpp
deleted file mode 100644
index 8d4c29427fe..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/LocalizedStrings.cpp
+++ /dev/null
@@ -1,477 +0,0 @@
-/*
- * Copyright (C) 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/LocalizedStrings.h"
-
-#include "core/platform/NotImplemented.h"
-#include "core/platform/graphics/IntSize.h"
-#include "core/platform/text/DateTimeFormat.h"
-#include "public/platform/Platform.h"
-#include "public/platform/WebString.h"
-#include "wtf/text/StringBuilder.h"
-#include "wtf/text/WTFString.h"
-
-using WebKit::WebLocalizedString;
-using WebKit::WebString;
-
-namespace WebCore {
-
-static String query(WebLocalizedString::Name name)
-{
- return WebKit::Platform::current()->queryLocalizedString(name);
-}
-
-static String query(WebLocalizedString::Name name, const WebString& parameter)
-{
- return WebKit::Platform::current()->queryLocalizedString(name, parameter);
-}
-
-static String query(WebLocalizedString::Name name, const WebString& parameter1, const WebString& parameter2)
-{
- return WebKit::Platform::current()->queryLocalizedString(name, parameter1, parameter2);
-}
-
-String searchableIndexIntroduction()
-{
- return query(WebLocalizedString::SearchableIndexIntroduction);
-}
-
-String submitButtonDefaultLabel()
-{
- return query(WebLocalizedString::SubmitButtonDefaultLabel);
-}
-
-String inputElementAltText()
-{
- return query(WebLocalizedString::InputElementAltText);
-}
-
-String resetButtonDefaultLabel()
-{
- return query(WebLocalizedString::ResetButtonDefaultLabel);
-}
-
-String fileButtonChooseFileLabel()
-{
- return query(WebLocalizedString::FileButtonChooseFileLabel);
-}
-
-String fileButtonChooseMultipleFilesLabel()
-{
- return query(WebLocalizedString::FileButtonChooseMultipleFilesLabel);
-}
-
-String defaultDetailsSummaryText()
-{
- return query(WebLocalizedString::DetailsLabel);
-}
-
-String fileButtonNoFileSelectedLabel()
-{
- return query(WebLocalizedString::FileButtonNoFileSelectedLabel);
-}
-
-String fileButtonNoFilesSelectedLabel()
-{
- return query(WebLocalizedString::FileButtonNoFileSelectedLabel);
-}
-
-String searchMenuNoRecentSearchesText()
-{
- return query(WebLocalizedString::SearchMenuNoRecentSearchesText);
-}
-String searchMenuRecentSearchesText()
-{
- return query(WebLocalizedString::SearchMenuRecentSearchesText);
-}
-
-String searchMenuClearRecentSearchesText()
-{
- return query(WebLocalizedString::SearchMenuClearRecentSearchesText);
-}
-
-String AXWebAreaText()
-{
- return query(WebLocalizedString::AXWebAreaText);
-}
-
-String AXLinkText()
-{
- return query(WebLocalizedString::AXLinkText);
-}
-
-String AXListMarkerText()
-{
- return query(WebLocalizedString::AXListMarkerText);
-}
-
-String AXImageMapText()
-{
- return query(WebLocalizedString::AXImageMapText);
-}
-
-String AXHeadingText()
-{
- return query(WebLocalizedString::AXHeadingText);
-}
-
-String AXButtonActionVerb()
-{
- return query(WebLocalizedString::AXButtonActionVerb);
-}
-
-String AXRadioButtonActionVerb()
-{
- return query(WebLocalizedString::AXRadioButtonActionVerb);
-}
-
-String AXTextFieldActionVerb()
-{
- return query(WebLocalizedString::AXTextFieldActionVerb);
-}
-
-String AXCheckedCheckBoxActionVerb()
-{
- return query(WebLocalizedString::AXCheckedCheckBoxActionVerb);
-}
-
-String AXUncheckedCheckBoxActionVerb()
-{
- return query(WebLocalizedString::AXUncheckedCheckBoxActionVerb);
-}
-
-String AXLinkActionVerb()
-{
- return query(WebLocalizedString::AXLinkActionVerb);
-}
-
-String AXMenuListPopupActionVerb()
-{
- return String();
-}
-
-String AXMenuListActionVerb()
-{
- return String();
-}
-
-#if ENABLE(INPUT_MULTIPLE_FIELDS_UI)
-String AXAMPMFieldText()
-{
- return query(WebLocalizedString::AXAMPMFieldText);
-}
-
-String AXDayOfMonthFieldText()
-{
- return query(WebLocalizedString::AXDayOfMonthFieldText);
-}
-
-String AXDateTimeFieldEmptyValueText()
-{
- return query(WebLocalizedString::AXDateTimeFieldEmptyValueText);
-}
-
-String AXHourFieldText()
-{
- return query(WebLocalizedString::AXHourFieldText);
-}
-
-String AXMillisecondFieldText()
-{
- return query(WebLocalizedString::AXMillisecondFieldText);
-}
-
-String AXMinuteFieldText()
-{
- return query(WebLocalizedString::AXMinuteFieldText);
-}
-
-String AXMonthFieldText()
-{
- return query(WebLocalizedString::AXMonthFieldText);
-}
-
-String AXSecondFieldText()
-{
- return query(WebLocalizedString::AXSecondFieldText);
-}
-
-String AXWeekOfYearFieldText()
-{
- return query(WebLocalizedString::AXWeekOfYearFieldText);
-}
-
-String AXYearFieldText()
-{
- return query(WebLocalizedString::AXYearFieldText);
-}
-
-String placeholderForDayOfMonthField()
-{
- return query(WebLocalizedString::PlaceholderForDayOfMonthField);
-}
-
-String placeholderForMonthField()
-{
- return query(WebLocalizedString::PlaceholderForMonthField);
-}
-
-String placeholderForYearField()
-{
- return query(WebLocalizedString::PlaceholderForYearField);
-}
-#endif
-
-String weekFormatInLDML()
-{
- String templ = query(WebLocalizedString::WeekFormatTemplate);
- // Converts a string like "Week $2, $1" to an LDML date format pattern like
- // "'Week 'ww', 'yyyy".
- StringBuilder builder;
- unsigned literalStart = 0;
- unsigned length = templ.length();
- for (unsigned i = 0; i + 1 < length; ++i) {
- if (templ[i] == '$' && (templ[i + 1] == '1' || templ[i + 1] == '2')) {
- if (literalStart < i)
- DateTimeFormat::quoteAndAppendLiteral(templ.substring(literalStart, i - literalStart), builder);
- builder.append(templ[++i] == '1' ? "yyyy" : "ww");
- literalStart = i + 1;
- }
- }
- if (literalStart < length)
- DateTimeFormat::quoteAndAppendLiteral(templ.substring(literalStart, length - literalStart), builder);
- return builder.toString();
-}
-
-String missingPluginText()
-{
- return query(WebLocalizedString::MissingPluginText);
-}
-
-String blockedPluginByContentSecurityPolicyText()
-{
- notImplemented();
- return String();
-}
-
-String multipleFileUploadText(unsigned numberOfFiles)
-{
- return query(WebLocalizedString::MultipleFileUploadText, String::number(numberOfFiles));
-}
-
-// The following two functions are not declared in core/platform/LocalizedStrings.h.
-// They are used by the menu for the HTML keygen tag.
-String keygenMenuHighGradeKeySize()
-{
- return query(WebLocalizedString::KeygenMenuHighGradeKeySize);
-}
-
-String keygenMenuMediumGradeKeySize()
-{
- return query(WebLocalizedString::KeygenMenuMediumGradeKeySize);
-}
-
-// Used in ImageDocument.cpp as the title for pages when that page is an image.
-String imageTitle(const String& filename, const IntSize& size)
-{
- StringBuilder result;
- result.append(filename);
- result.append(" (");
- result.append(String::number(size.width()));
- result.append(static_cast<UChar>(0xD7)); // U+00D7 (multiplication sign)
- result.append(String::number(size.height()));
- result.append(')');
- return result.toString();
-}
-
-String textTrackClosedCaptionsText() { return String(); }
-String textTrackSubtitlesText() { return String(); }
-String textTrackOffText() { return String(); }
-String textTrackNoLabelText() { return String(); }
-
-String localizedMediaControlElementString(const String& name)
-{
- if (name == "AudioElement")
- return query(WebLocalizedString::AXMediaAudioElement);
- if (name == "VideoElement")
- return query(WebLocalizedString::AXMediaVideoElement);
- if (name == "MuteButton")
- return query(WebLocalizedString::AXMediaMuteButton);
- if (name == "UnMuteButton")
- return query(WebLocalizedString::AXMediaUnMuteButton);
- if (name == "PlayButton")
- return query(WebLocalizedString::AXMediaPlayButton);
- if (name == "PauseButton")
- return query(WebLocalizedString::AXMediaPauseButton);
- if (name == "Slider")
- return query(WebLocalizedString::AXMediaSlider);
- if (name == "SliderThumb")
- return query(WebLocalizedString::AXMediaSliderThumb);
- if (name == "RewindButton")
- return query(WebLocalizedString::AXMediaRewindButton);
- if (name == "ReturnToRealtimeButton")
- return query(WebLocalizedString::AXMediaReturnToRealTime);
- if (name == "CurrentTimeDisplay")
- return query(WebLocalizedString::AXMediaCurrentTimeDisplay);
- if (name == "TimeRemainingDisplay")
- return query(WebLocalizedString::AXMediaTimeRemainingDisplay);
- if (name == "StatusDisplay")
- return query(WebLocalizedString::AXMediaStatusDisplay);
- if (name == "EnterFullscreenButton")
- return query(WebLocalizedString::AXMediaEnterFullscreenButton);
- if (name == "ExitFullscreenButton")
- return query(WebLocalizedString::AXMediaExitFullscreenButton);
- if (name == "SeekForwardButton")
- return query(WebLocalizedString::AXMediaSeekForwardButton);
- if (name == "SeekBackButton")
- return query(WebLocalizedString::AXMediaSeekBackButton);
- if (name == "ShowClosedCaptionsButton")
- return query(WebLocalizedString::AXMediaShowClosedCaptionsButton);
- if (name == "HideClosedCaptionsButton")
- return query(WebLocalizedString::AXMediaHideClosedCaptionsButton);
-
- // FIXME: the ControlsPanel container should never be visible in the accessibility hierarchy.
- if (name == "ControlsPanel")
- return query(WebLocalizedString::AXMediaDefault);
-
- ASSERT_NOT_REACHED();
- return query(WebLocalizedString::AXMediaDefault);
-}
-
-String localizedMediaControlElementHelpText(const String& name)
-{
- if (name == "AudioElement")
- return query(WebLocalizedString::AXMediaAudioElementHelp);
- if (name == "VideoElement")
- return query(WebLocalizedString::AXMediaVideoElementHelp);
- if (name == "MuteButton")
- return query(WebLocalizedString::AXMediaMuteButtonHelp);
- if (name == "UnMuteButton")
- return query(WebLocalizedString::AXMediaUnMuteButtonHelp);
- if (name == "PlayButton")
- return query(WebLocalizedString::AXMediaPlayButtonHelp);
- if (name == "PauseButton")
- return query(WebLocalizedString::AXMediaPauseButtonHelp);
- if (name == "Slider")
- return query(WebLocalizedString::AXMediaSliderHelp);
- if (name == "SliderThumb")
- return query(WebLocalizedString::AXMediaSliderThumbHelp);
- if (name == "RewindButton")
- return query(WebLocalizedString::AXMediaRewindButtonHelp);
- if (name == "ReturnToRealtimeButton")
- return query(WebLocalizedString::AXMediaReturnToRealTimeHelp);
- if (name == "CurrentTimeDisplay")
- return query(WebLocalizedString::AXMediaCurrentTimeDisplayHelp);
- if (name == "TimeRemainingDisplay")
- return query(WebLocalizedString::AXMediaTimeRemainingDisplayHelp);
- if (name == "StatusDisplay")
- return query(WebLocalizedString::AXMediaStatusDisplayHelp);
- if (name == "EnterFullscreenButton")
- return query(WebLocalizedString::AXMediaEnterFullscreenButtonHelp);
- if (name == "ExitFullscreenButton")
- return query(WebLocalizedString::AXMediaExitFullscreenButtonHelp);
- if (name == "SeekForwardButton")
- return query(WebLocalizedString::AXMediaSeekForwardButtonHelp);
- if (name == "SeekBackButton")
- return query(WebLocalizedString::AXMediaSeekBackButtonHelp);
- if (name == "ShowClosedCaptionsButton")
- return query(WebLocalizedString::AXMediaShowClosedCaptionsButtonHelp);
- if (name == "HideClosedCaptionsButton")
- return query(WebLocalizedString::AXMediaHideClosedCaptionsButtonHelp);
-
- ASSERT_NOT_REACHED();
- return query(WebLocalizedString::AXMediaDefault);
-}
-
-String localizedMediaTimeDescription(float /*time*/)
-{
- // FIXME: to be fixed.
- return String();
-}
-
-String validationMessageValueMissingText()
-{
- return query(WebLocalizedString::ValidationValueMissing);
-}
-
-String validationMessageValueMissingForCheckboxText()
-{
- return query(WebLocalizedString::ValidationValueMissingForCheckbox);
-}
-
-String validationMessageValueMissingForFileText()
-{
- return query(WebLocalizedString::ValidationValueMissingForFile);
-}
-
-String validationMessageValueMissingForMultipleFileText()
-{
- return query(WebLocalizedString::ValidationValueMissingForMultipleFile);
-}
-
-String validationMessageValueMissingForRadioText()
-{
- return query(WebLocalizedString::ValidationValueMissingForRadio);
-}
-
-String validationMessageValueMissingForSelectText()
-{
- return query(WebLocalizedString::ValidationValueMissingForSelect);
-}
-
-String validationMessageTypeMismatchText()
-{
- return query(WebLocalizedString::ValidationTypeMismatch);
-}
-
-String validationMessageTypeMismatchForURLText()
-{
- return query(WebLocalizedString::ValidationTypeMismatchForURL);
-}
-
-String validationMessagePatternMismatchText()
-{
- return query(WebLocalizedString::ValidationPatternMismatch);
-}
-
-String validationMessageBadInputForNumberText()
-{
- return query(WebLocalizedString::ValidationBadInputForNumber);
-}
-
-#if ENABLE(INPUT_MULTIPLE_FIELDS_UI)
-String validationMessageBadInputForDateTimeText()
-{
- return query(WebLocalizedString::ValidationBadInputForDateTime);
-}
-#endif
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/LocalizedStrings.h b/chromium/third_party/WebKit/Source/core/platform/LocalizedStrings.h
deleted file mode 100644
index e025aad6849..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/LocalizedStrings.h
+++ /dev/null
@@ -1,132 +0,0 @@
-/*
- * Copyright (C) 2003, 2006, 2009, 2011, 2012, 2013 Apple Inc. All rights reserved.
- * Copyright (C) 2010 Igalia S.L
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef LocalizedStrings_h
-#define LocalizedStrings_h
-
-#include "public/platform/WebLocalizedString.h"
-#include "wtf/Forward.h"
-
-namespace WebCore {
-
- class IntSize;
-
- // FIXME: Use Locale::queryString instead of the following functions.
-
- String inputElementAltText();
- String resetButtonDefaultLabel();
- String searchableIndexIntroduction();
- String submitButtonDefaultLabel();
- String fileButtonChooseFileLabel();
- String fileButtonChooseMultipleFilesLabel();
- String fileButtonNoFileSelectedLabel();
- String fileButtonNoFilesSelectedLabel();
- String defaultDetailsSummaryText();
-
- String searchMenuNoRecentSearchesText();
- String searchMenuRecentSearchesText();
- String searchMenuClearRecentSearchesText();
-
- String AXWebAreaText();
- String AXLinkText();
- String AXListMarkerText();
- String AXImageMapText();
- String AXHeadingText();
- String AXFileUploadButtonText();
- String AXButtonActionVerb();
- String AXRadioButtonActionVerb();
- String AXTextFieldActionVerb();
- String AXCheckedCheckBoxActionVerb();
- String AXUncheckedCheckBoxActionVerb();
- String AXMenuListActionVerb();
- String AXMenuListPopupActionVerb();
- String AXLinkActionVerb();
-
-#if ENABLE(INPUT_MULTIPLE_FIELDS_UI)
- String AXAMPMFieldText();
- String AXDayOfMonthFieldText();
- String AXDateTimeFieldEmptyValueText();
- String AXHourFieldText();
- String AXMillisecondFieldText();
- String AXMinuteFieldText();
- String AXMonthFieldText();
- String AXSecondFieldText();
- String AXWeekOfYearFieldText();
- String AXYearFieldText();
-
- // placeholderForDayOfMonthField() returns localized placeholder text, e.g.
- // "dd", for date field used in multiple fields "date", "datetime", and
- // "datetime-local" input UI instead "--".
- String placeholderForDayOfMonthField();
-
- // placeholderForfMonthField() returns localized placeholder text, e.g.
- // "mm", for month field used in multiple fields "date", "datetime", and
- // "datetime-local" input UI instead "--".
- String placeholderForMonthField();
-
- // placeholderForYearField() returns localized placeholder text, e.g.
- // "yyyy", for year field used in multiple fields "date", "datetime", and
- // "datetime-local" input UI instead "----".
- String placeholderForYearField();
-#endif
- // weekFormatInLDML() returns week and year format in LDML, Unicode
- // technical standard 35, Locale Data Markup Language, e.g. "'Week' ww, yyyy"
- String weekFormatInLDML();
-
- String missingPluginText();
- String blockedPluginByContentSecurityPolicyText();
-
- String multipleFileUploadText(unsigned numberOfFiles);
-
- String imageTitle(const String& filename, const IntSize& size);
-
- String localizedMediaControlElementString(const String&);
- String localizedMediaControlElementHelpText(const String&);
- String localizedMediaTimeDescription(float);
-
- String validationMessageValueMissingText();
- String validationMessageValueMissingForCheckboxText();
- String validationMessageValueMissingForFileText();
- String validationMessageValueMissingForMultipleFileText();
- String validationMessageValueMissingForRadioText();
- String validationMessageValueMissingForSelectText();
- String validationMessageTypeMismatchText();
- String validationMessageTypeMismatchForURLText();
- String validationMessagePatternMismatchText();
- String validationMessageBadInputForNumberText();
-#if ENABLE(INPUT_MULTIPLE_FIELDS_UI)
- String validationMessageBadInputForDateTimeText();
-#endif
-
- String clickToExitFullScreenText();
-
- String textTrackSubtitlesText();
- String textTrackOffText();
- String textTrackNoLabelText();
-
-} // namespace WebCore
-
-#endif // LocalizedStrings_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/Logging.cpp b/chromium/third_party/WebKit/Source/core/platform/Logging.cpp
deleted file mode 100644
index 834ece6fa72..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/Logging.cpp
+++ /dev/null
@@ -1,156 +0,0 @@
-/*
- * Copyright (C) 2003, 2006 Apple Computer, Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/Logging.h"
-
-#include "wtf/text/WTFString.h"
-
-#if !LOG_DISABLED
-
-namespace WebCore {
-
-WTFLogChannel LogNotYetImplemented = { 0x00000001, "WebCoreLogLevel", WTFLogChannelOff };
-
-WTFLogChannel LogFrames = { 0x00000010, "WebCoreLogLevel", WTFLogChannelOff };
-WTFLogChannel LogLoading = { 0x00000020, "WebCoreLogLevel", WTFLogChannelOff };
-WTFLogChannel LogPopupBlocking = { 0x00000040, "WebCoreLogLevel", WTFLogChannelOff };
-WTFLogChannel LogEvents = { 0x00000080, "WebCoreLogLevel", WTFLogChannelOff };
-
-WTFLogChannel LogEditing = { 0x00000100, "WebCoreLogLevel", WTFLogChannelOff };
-WTFLogChannel LogLiveConnect = { 0x00000200, "WebCoreLogLevel", WTFLogChannelOff };
-WTFLogChannel LogIconDatabase = { 0x00000400, "WebCoreLogLevel", WTFLogChannelOff };
-WTFLogChannel LogSQLDatabase = { 0x00000800, "WebCoreLogLevel", WTFLogChannelOff };
-
-WTFLogChannel LogSpellingAndGrammar ={ 0x00001000, "WebCoreLogLevel", WTFLogChannelOff };
-WTFLogChannel LogBackForward = { 0x00002000, "WebCoreLogLevel", WTFLogChannelOff };
-WTFLogChannel LogHistory = { 0x00004000, "WebCoreLogLevel", WTFLogChannelOff };
-
-WTFLogChannel LogPlatformLeaks = { 0x00010000, "WebCoreLogLevel", WTFLogChannelOff };
-WTFLogChannel LogResourceLoading = { 0x00020000, "WebCoreLogLevel", WTFLogChannelOff };
-
-WTFLogChannel LogNetwork = { 0x00100000, "WebCoreLogLevel", WTFLogChannelOff };
-WTFLogChannel LogFTP = { 0x00200000, "WebCoreLogLevel", WTFLogChannelOff };
-WTFLogChannel LogThreading = { 0x00400000, "WebCoreLogLevel", WTFLogChannelOff };
-WTFLogChannel LogStorageAPI = { 0x00800000, "WebCoreLogLevel", WTFLogChannelOff };
-
-WTFLogChannel LogMedia = { 0x01000000, "WebCoreLogLevel", WTFLogChannelOff };
-WTFLogChannel LogPlugins = { 0x02000000, "WebCoreLogLevel", WTFLogChannelOff };
-WTFLogChannel LogArchives = { 0x04000000, "WebCoreLogLevel", WTFLogChannelOff };
-WTFLogChannel LogProgress = { 0x08000000, "WebCoreLogLevel", WTFLogChannelOff };
-
-WTFLogChannel LogFileAPI = { 0x10000000, "WebCoreLogLevel", WTFLogChannelOff };
-
-WTFLogChannel LogWebAudio = { 0x20000000, "WebCoreLogLevel", WTFLogChannelOff };
-WTFLogChannel LogCompositing = { 0x40000000, "WebCoreLogLevel", WTFLogChannelOff };
-WTFLogChannel LogGamepad = { 0x80000000, "WebCoreLogLevel", WTFLogChannelOff };
-
-
-WTFLogChannel* getChannelFromName(const String& channelName)
-{
- if (!(channelName.length() >= 2))
- return 0;
-
- if (equalIgnoringCase(channelName, String("BackForward")))
- return &LogBackForward;
-
- if (equalIgnoringCase(channelName, String("Editing")))
- return &LogEditing;
-
- if (equalIgnoringCase(channelName, String("Events")))
- return &LogEvents;
-
- if (equalIgnoringCase(channelName, String("Frames")))
- return &LogFrames;
-
- if (equalIgnoringCase(channelName, String("FTP")))
- return &LogFTP;
-
- if (equalIgnoringCase(channelName, String("History")))
- return &LogHistory;
-
- if (equalIgnoringCase(channelName, String("IconDatabase")))
- return &LogIconDatabase;
-
- if (equalIgnoringCase(channelName, String("Loading")))
- return &LogLoading;
-
- if (equalIgnoringCase(channelName, String("Media")))
- return &LogMedia;
-
- if (equalIgnoringCase(channelName, String("Network")))
- return &LogNetwork;
-
- if (equalIgnoringCase(channelName, String("NotYetImplemented")))
- return &LogNotYetImplemented;
-
- if (equalIgnoringCase(channelName, String("PlatformLeaks")))
- return &LogPlatformLeaks;
-
- if (equalIgnoringCase(channelName, String("ResourceLoading")))
- return &LogResourceLoading;
-
- if (equalIgnoringCase(channelName, String("Plugins")))
- return &LogPlugins;
-
- if (equalIgnoringCase(channelName, String("PopupBlocking")))
- return &LogPopupBlocking;
-
- if (equalIgnoringCase(channelName, String("Progress")))
- return &LogProgress;
-
- if (equalIgnoringCase(channelName, String("SpellingAndGrammar")))
- return &LogSpellingAndGrammar;
-
- if (equalIgnoringCase(channelName, String("SQLDatabase")))
- return &LogSQLDatabase;
-
- if (equalIgnoringCase(channelName, String("StorageAPI")))
- return &LogStorageAPI;
-
- if (equalIgnoringCase(channelName, String("LiveConnect")))
- return &LogLiveConnect;
-
- if (equalIgnoringCase(channelName, String("Threading")))
- return &LogThreading;
-
- if (equalIgnoringCase(channelName, String("FileAPI")))
- return &LogFileAPI;
-
- if (equalIgnoringCase(channelName, String("WebAudio")))
- return &LogWebAudio;
-
- if (equalIgnoringCase(channelName, String("Compositing")))
- return &LogCompositing;
-
- if (equalIgnoringCase(channelName, String("Gamepad")))
- return &LogGamepad;
-
- return 0;
-}
-
-}
-
-#endif // !LOG_DISABLED
diff --git a/chromium/third_party/WebKit/Source/core/platform/Logging.h b/chromium/third_party/WebKit/Source/core/platform/Logging.h
deleted file mode 100644
index bdad93f4139..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/Logging.h
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Copyright (C) 2003, 2006 Apple Computer, Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef Logging_h
-#define Logging_h
-
-#include "wtf/Assertions.h"
-#include "wtf/Forward.h"
-
-#if !LOG_DISABLED
-
-#ifndef LOG_CHANNEL_PREFIX
-#define LOG_CHANNEL_PREFIX Log
-#endif
-
-namespace WebCore {
-
- extern WTFLogChannel LogNotYetImplemented;
- extern WTFLogChannel LogFrames;
- extern WTFLogChannel LogLoading;
- extern WTFLogChannel LogPopupBlocking;
- extern WTFLogChannel LogEvents;
- extern WTFLogChannel LogEditing;
- extern WTFLogChannel LogLiveConnect;
- extern WTFLogChannel LogIconDatabase;
- extern WTFLogChannel LogSQLDatabase;
- extern WTFLogChannel LogSpellingAndGrammar;
- extern WTFLogChannel LogBackForward;
- extern WTFLogChannel LogHistory;
- extern WTFLogChannel LogPlatformLeaks;
- extern WTFLogChannel LogResourceLoading;
- extern WTFLogChannel LogNetwork;
- extern WTFLogChannel LogFTP;
- extern WTFLogChannel LogThreading;
- extern WTFLogChannel LogStorageAPI;
- extern WTFLogChannel LogMedia;
- extern WTFLogChannel LogPlugins;
- extern WTFLogChannel LogArchives;
- extern WTFLogChannel LogProgress;
- extern WTFLogChannel LogFileAPI;
- extern WTFLogChannel LogWebAudio;
- extern WTFLogChannel LogCompositing;
- extern WTFLogChannel LogGamepad;
-
- WTFLogChannel* getChannelFromName(const String& channelName);
-}
-
-#endif // !LOG_DISABLED
-
-#endif // Logging_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/MIMETypeFromURL.cpp b/chromium/third_party/WebKit/Source/core/platform/MIMETypeFromURL.cpp
deleted file mode 100644
index 74dba93ede2..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/MIMETypeFromURL.cpp
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Copyright (C) 2004, 2007, 2008, 2011, 2012 Apple Inc. All rights reserved.
- * Copyright (C) 2012 Research In Motion Limited. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/MIMETypeFromURL.h"
-
-#include "core/platform/MIMETypeRegistry.h"
-#include "weborigin/KURL.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-String mimeTypeFromDataURL(const String& url)
-{
- ASSERT(protocolIs(url, "data"));
- size_t index = url.find(';');
- if (index == kNotFound)
- index = url.find(',');
- if (index != kNotFound) {
- if (index > 5)
- return url.substring(5, index - 5).lower();
- return "text/plain"; // Data URLs with no MIME type are considered text/plain.
- }
- return "";
-}
-
-String mimeTypeFromURL(const KURL& url)
-{
- String decodedPath = decodeURLEscapeSequences(url.path());
- String extension = decodedPath.substring(decodedPath.reverseFind('.') + 1);
-
- // We don't use MIMETypeRegistry::getMIMETypeForPath() because it returns "application/octet-stream" upon failure
- return MIMETypeRegistry::getMIMETypeForExtension(extension);
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/MIMETypeFromURL.h b/chromium/third_party/WebKit/Source/core/platform/MIMETypeFromURL.h
deleted file mode 100644
index 50af6c29c9b..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/MIMETypeFromURL.h
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2011, 2012 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef MIMETypeFromURL_h
-#define MIMETypeFromURL_h
-
-#include "wtf/Forward.h"
-
-namespace WebCore {
-
-class KURL;
-
-String mimeTypeFromDataURL(const String& url);
-String mimeTypeFromURL(const KURL&);
-
-} // namespace WebCore
-
-#endif // MIMETypeFromURL_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/MIMETypeRegistry.h b/chromium/third_party/WebKit/Source/core/platform/MIMETypeRegistry.h
deleted file mode 100644
index 983aa853ab5..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/MIMETypeRegistry.h
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Copyright (C) 2006 Apple Computer, Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef MIMETypeRegistry_h
-#define MIMETypeRegistry_h
-
-#include "wtf/HashSet.h"
-#include "wtf/Vector.h"
-#include "wtf/text/StringHash.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class MIMETypeRegistry {
-public:
- static String getMIMETypeForExtension(const String& extension);
- static String getWellKnownMIMETypeForExtension(const String& extension);
-
- static String getMIMETypeForPath(const String& path);
-
- // Check to see if a mime type is suitable for being loaded inline as an
- // image (e.g., <img> tags).
- static bool isSupportedImageMIMEType(const String& mimeType);
-
- // Check to see if a mime type is suitable for being loaded as an image
- // document in a frame.
- static bool isSupportedImageResourceMIMEType(const String& mimeType);
-
- // Check to see if a mime type is suitable for being encoded.
- static bool isSupportedImageMIMETypeForEncoding(const String& mimeType);
-
- // Check to see if a mime type is suitable for being loaded as a JavaScript
- // resource.
- static bool isSupportedJavaScriptMIMEType(const String& mimeType);
-
- // Check to see if a non-image mime type is suitable for being loaded as a
- // document in a frame. Includes supported JavaScript MIME types.
- static bool isSupportedNonImageMIMEType(const String& mimeType);
-
- // Check to see if the mime type and codecs are supported by the MediaSource implementation.
- static bool isSupportedMediaSourceMIMEType(const String& mimeType, const String& codecs);
-
- // Check to see if a mime type is a valid Java applet mime type
- static bool isJavaAppletMIMEType(const String& mimeType);
-};
-
-} // namespace WebCore
-
-#endif // MIMETypeRegistry_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/MemoryUsageSupport.h b/chromium/third_party/WebKit/Source/core/platform/MemoryUsageSupport.h
deleted file mode 100644
index 36128e10a58..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/MemoryUsageSupport.h
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef MemoryUsageSupport_h
-#define MemoryUsageSupport_h
-
-#include "wtf/Forward.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class MemoryUsageSupport {
-public:
- // Returns the current space allocated for the pagefile, in MB.
- // That is committed size for Windows and virtual memory size for POSIX.
- static int memoryUsageMB();
-
- // Same as above, but always returns actual value, without any
- // caches.
- static int actualMemoryUsageMB();
-
- // Returns private and shared usage, in bytes. Private bytes is the amount of
- // memory currently allocated to this process that cannot be shared. Returns
- // false on platform specific error conditions.
- static bool processMemorySizesInBytes(size_t* privateBytes, size_t* sharedBytes);
-
- // A callback for requestProcessMemorySizes
- class ProcessMemorySizesCallback {
- public:
- virtual ~ProcessMemorySizesCallback() { }
- virtual void dataReceived(size_t privateBytes, size_t sharedBytes) = 0;
- };
-
- // Requests private and shared usage, in bytes. Private bytes is the amount of
- // memory currently allocated to this process that cannot be shared.
- static void requestProcessMemorySizes(PassOwnPtr<ProcessMemorySizesCallback> requestCallback);
-};
-
-} // namespace WebCore
-
-#endif // MemoryUsageSupport_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/NotImplemented.cpp b/chromium/third_party/WebKit/Source/core/platform/NotImplemented.cpp
deleted file mode 100644
index 4b7584a8515..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/NotImplemented.cpp
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright (C) 2012 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/NotImplemented.h"
-
-#include "core/platform/Logging.h"
-
-namespace WebCore {
-
-#if !LOG_DISABLED
-
-WTFLogChannel* notImplementedLoggingChannel()
-{
- return &LogNotYetImplemented;
-}
-
-#endif
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/NotImplemented.h b/chromium/third_party/WebKit/Source/core/platform/NotImplemented.h
deleted file mode 100644
index d55301812c6..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/NotImplemented.h
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright (C) 2007 Apple Computer, Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef NotImplemented_h
-#define NotImplemented_h
-
-#include "wtf/Assertions.h"
-
-#if LOG_DISABLED
- #define notImplemented() ((void)0)
-#else
-
-namespace WebCore {
-WTFLogChannel* notImplementedLoggingChannel();
-}
-
-#define notImplemented() do { \
- static bool havePrinted = false; \
- if (!havePrinted) { \
- WTFLogVerbose(__FILE__, __LINE__, WTF_PRETTY_FUNCTION, WebCore::notImplementedLoggingChannel(), "UNIMPLEMENTED: "); \
- havePrinted = true; \
- } \
- } while (0)
-
-#endif // NDEBUG
-
-#endif // NotImplemented_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/PODArena.h b/chromium/third_party/WebKit/Source/core/platform/PODArena.h
deleted file mode 100644
index bc65de66452..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/PODArena.h
+++ /dev/null
@@ -1,201 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef PODArena_h
-#define PODArena_h
-
-#include <stdint.h>
-#include "wtf/Assertions.h"
-#include "wtf/FastMalloc.h"
-#include "wtf/Noncopyable.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-// An arena which allocates only Plain Old Data (POD), or classes and
-// structs bottoming out in Plain Old Data. NOTE: the constructors of
-// the objects allocated in this arena are called, but _not_ their
-// destructors.
-
-class PODArena : public RefCounted<PODArena> {
-public:
- // The arena is configured with an allocator, which is responsible
- // for allocating and freeing chunks of memory at a time.
- class Allocator : public RefCounted<Allocator> {
- public:
- virtual void* allocate(size_t size) = 0;
- virtual void free(void* ptr) = 0;
- protected:
- virtual ~Allocator() { }
- friend class WTF::RefCounted<Allocator>;
- };
-
- // The Arena's default allocator, which uses fastMalloc and
- // fastFree to allocate chunks of storage.
- class FastMallocAllocator : public Allocator {
- public:
- static PassRefPtr<FastMallocAllocator> create()
- {
- return adoptRef(new FastMallocAllocator);
- }
-
- virtual void* allocate(size_t size) { return fastMalloc(size); }
- virtual void free(void* ptr) { fastFree(ptr); }
-
- protected:
- FastMallocAllocator() { }
- };
-
- // Creates a new PODArena configured with a FastMallocAllocator.
- static PassRefPtr<PODArena> create()
- {
- return adoptRef(new PODArena);
- }
-
- // Creates a new PODArena configured with the given Allocator.
- static PassRefPtr<PODArena> create(PassRefPtr<Allocator> allocator)
- {
- return adoptRef(new PODArena(allocator));
- }
-
- // Allocates an object from the arena.
- template<class T> T* allocateObject()
- {
- return new (allocateBase<T>()) T();
- }
-
- // Allocates an object from the arena, calling a single-argument constructor.
- template<class T, class Argument1Type> T* allocateObject(const Argument1Type& argument1)
- {
- return new (allocateBase<T>()) T(argument1);
- }
-
- // The initial size of allocated chunks; increases as necessary to
- // satisfy large allocations. Mainly public for unit tests.
- enum {
- DefaultChunkSize = 16384
- };
-
-protected:
- virtual ~PODArena() { }
- friend class WTF::RefCounted<PODArena>;
-
- PODArena()
- : m_allocator(FastMallocAllocator::create())
- , m_current(0)
- , m_currentChunkSize(DefaultChunkSize) { }
-
- explicit PODArena(PassRefPtr<Allocator> allocator)
- : m_allocator(allocator)
- , m_current(0)
- , m_currentChunkSize(DefaultChunkSize) { }
-
- // Returns the alignment requirement for classes and structs on the
- // current platform.
- template <class T> static size_t minAlignment()
- {
- return WTF_ALIGN_OF(T);
- }
-
- template<class T> void* allocateBase()
- {
- void* ptr = 0;
- size_t roundedSize = roundUp(sizeof(T), minAlignment<T>());
- if (m_current)
- ptr = m_current->allocate(roundedSize);
-
- if (!ptr) {
- if (roundedSize > m_currentChunkSize)
- m_currentChunkSize = roundedSize;
- m_chunks.append(adoptPtr(new Chunk(m_allocator.get(), m_currentChunkSize)));
- m_current = m_chunks.last().get();
- ptr = m_current->allocate(roundedSize);
- }
- return ptr;
- }
-
- // Rounds up the given allocation size to the specified alignment.
- size_t roundUp(size_t size, size_t alignment)
- {
- ASSERT(!(alignment % 2));
- return (size + alignment - 1) & ~(alignment - 1);
- }
-
- // Manages a chunk of memory and individual allocations out of it.
- class Chunk {
- WTF_MAKE_NONCOPYABLE(Chunk);
- public:
- // Allocates a block of memory of the given size from the passed
- // Allocator.
- Chunk(Allocator* allocator, size_t size)
- : m_allocator(allocator)
- , m_size(size)
- , m_currentOffset(0)
- {
- m_base = static_cast<uint8_t*>(m_allocator->allocate(size));
- }
-
- // Frees the memory allocated from the Allocator in the
- // constructor.
- virtual ~Chunk()
- {
- m_allocator->free(m_base);
- }
-
- // Returns a pointer to "size" bytes of storage, or 0 if this
- // Chunk could not satisfy the allocation.
- void* allocate(size_t size)
- {
- // Check for overflow
- if (m_currentOffset + size < m_currentOffset)
- return 0;
-
- if (m_currentOffset + size > m_size)
- return 0;
-
- void* result = m_base + m_currentOffset;
- m_currentOffset += size;
- return result;
- }
-
- protected:
- Allocator* m_allocator;
- uint8_t* m_base;
- size_t m_size;
- size_t m_currentOffset;
- };
-
- RefPtr<Allocator> m_allocator;
- Chunk* m_current;
- size_t m_currentChunkSize;
- Vector<OwnPtr<Chunk> > m_chunks;
-};
-
-} // namespace WebCore
-
-#endif // PODArena_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/PODFreeListArena.h b/chromium/third_party/WebKit/Source/core/platform/PODFreeListArena.h
deleted file mode 100644
index 2eacd2df6a2..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/PODFreeListArena.h
+++ /dev/null
@@ -1,132 +0,0 @@
-/*
- * Copyright (C) 2011 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef PODFreeListArena_h
-#define PODFreeListArena_h
-
-#include "core/platform/PODArena.h"
-
-namespace WebCore {
-
-// FIXME: Disassociate PODFreeListArena from PODArena, crbug.com/266535
-template <class T>
-class PODFreeListArena : public PODArena {
-public:
- typedef Vector<OwnPtr<Chunk> > ChunkVector;
-
- static PassRefPtr<PODFreeListArena> create()
- {
- return adoptRef(new PODFreeListArena);
- }
-
- // Creates a new PODArena configured with the given Allocator.
- static PassRefPtr<PODFreeListArena> create(PassRefPtr<Allocator> allocator)
- {
- return adoptRef(new PODFreeListArena(allocator));
- }
-
- // Allocates an object from the arena.
- T* allocateObject()
- {
- size_t roundedSize = roundUp(sizeof(T), minAlignment<T>());
- void* ptr = allocate(roundedSize);
- if (ptr) {
- // Use placement operator new to allocate a T at this location.
- new(ptr) T();
- }
- return static_cast<T*>(ptr);
- }
-
- template<class Argument1Type> T* allocateObject(const Argument1Type& argument1)
- {
- size_t roundedSize = roundUp(sizeof(T), minAlignment<T>());
- void* ptr = allocate(roundedSize);
- if (ptr) {
- // Use placement operator new to allocate a T at this location.
- new(ptr) T(argument1);
- }
- return static_cast<T*>(ptr);
- }
-
- void freeObject(T* ptr)
- {
- FixedSizeMemoryChunk* oldFreeList = m_freeList;
-
- m_freeList = reinterpret_cast<FixedSizeMemoryChunk*>(ptr);
- m_freeList->next = oldFreeList;
- }
-
-private:
- PODFreeListArena()
- : PODArena(), m_freeList(0) { }
-
- explicit PODFreeListArena(PassRefPtr<Allocator> allocator)
- : PODArena(allocator), m_freeList(0) { }
-
- void* allocate(size_t size)
- {
- ASSERT(size == roundUp(sizeof(T), minAlignment<T>()));
-
- if (m_freeList) {
- void* memory = m_freeList;
- m_freeList = m_freeList->next;
- return memory;
- }
-
- void* memory = 0;
- if (m_current)
- memory = m_current->allocate(size);
-
- if (!memory) {
- m_chunks.append(adoptPtr(new Chunk(m_allocator.get(), m_currentChunkSize)));
- m_current = m_chunks.last().get();
- memory = m_current->allocate(size);
- }
- return memory;
- }
-
- int getFreeListSizeForTesting() const
- {
- int total = 0;
- for (FixedSizeMemoryChunk* cur = m_freeList; cur; cur = cur->next) {
- total++;
- }
- return total;
- }
-
- // This free list contains pointers within every chunk that's been allocated so
- // far. None of the individual chunks can be freed until the arena is
- // destroyed.
- struct FixedSizeMemoryChunk {
- FixedSizeMemoryChunk* next;
- };
- FixedSizeMemoryChunk* m_freeList;
-
- friend class PODFreeListArenaTest;
-};
-
-} // namespace WebCore
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/PODInterval.h b/chromium/third_party/WebKit/Source/core/platform/PODInterval.h
deleted file mode 100644
index 925187c563d..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/PODInterval.h
+++ /dev/null
@@ -1,165 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef PODInterval_h
-#define PODInterval_h
-
-#ifndef NDEBUG
-#include "wtf/text/StringBuilder.h"
-#endif
-
-namespace WebCore {
-
-// Class representing a closed interval which can hold an arbitrary
-// Plain Old Datatype (POD) as its endpoints and a piece of user
-// data. An important characteristic for the algorithms we use is that
-// if two intervals have identical endpoints but different user data,
-// they are not considered to be equal. This situation can arise when
-// representing the vertical extents of bounding boxes of overlapping
-// triangles, where the pointer to the triangle is the user data of
-// the interval.
-//
-// *Note* that the destructors of type T and UserData will *not* be
-// called by this class. They must not allocate any memory that is
-// required to be cleaned up in their destructors.
-//
-// The following constructors and operators must be implemented on
-// type T:
-//
-// - Copy constructor (if user data is desired)
-// - operator<
-// - operator==
-// - operator=
-//
-// If the UserData type is specified, it must support a copy
-// constructor and assignment operator.
-//
-// In debug mode, printing of intervals and the data they contain is
-// enabled. This requires the following template specializations to be
-// available:
-//
-// template<> struct WebCore::ValueToString<T> {
-// static String string(const T& t);
-// };
-// template<> struct WebCore::ValueToString<UserData> {
-// static String string(const UserData& t);
-// };
-//
-// Note that this class requires a copy constructor and assignment
-// operator in order to be stored in the red-black tree.
-
-#ifndef NDEBUG
-template<class T>
-struct ValueToString;
-#endif
-
-template<class T, class UserData = void*>
-class PODInterval {
-public:
- // Constructor from endpoints. This constructor only works when the
- // UserData type is a pointer or other type which can be initialized
- // with 0.
- PODInterval(const T& low, const T& high)
- : m_low(low)
- , m_high(high)
- , m_data(0)
- , m_maxHigh(high)
- {
- }
-
- // Constructor from two endpoints plus explicit user data.
- PODInterval(const T& low, const T& high, const UserData data)
- : m_low(low)
- , m_high(high)
- , m_data(data)
- , m_maxHigh(high)
- {
- }
-
- const T& low() const { return m_low; }
- const T& high() const { return m_high; }
- const UserData& data() const { return m_data; }
-
- bool overlaps(const T& low, const T& high) const
- {
- if (this->high() < low)
- return false;
- if (high < this->low())
- return false;
- return true;
- }
-
- bool overlaps(const PODInterval& other) const
- {
- return overlaps(other.low(), other.high());
- }
-
- // Returns true if this interval is "less" than the other. The
- // comparison is performed on the low endpoints of the intervals.
- bool operator<(const PODInterval& other) const
- {
- return low() < other.low();
- }
-
- // Returns true if this interval is strictly equal to the other,
- // including comparison of the user data.
- bool operator==(const PODInterval& other) const
- {
- return (low() == other.low()
- && high() == other.high()
- && data() == other.data());
- }
-
- const T& maxHigh() const { return m_maxHigh; }
- void setMaxHigh(const T& maxHigh) { m_maxHigh = maxHigh; }
-
-#ifndef NDEBUG
- // Support for printing PODIntervals.
- String toString() const
- {
- StringBuilder builder;
- builder.append("[PODInterval (");
- builder.append(ValueToString<T>::string(low()));
- builder.append(", ");
- builder.append(ValueToString<T>::string(high()));
- builder.append("), data=");
- builder.append(ValueToString<UserData>::string(data()));
- builder.append(", maxHigh=");
- builder.append(ValueToString<T>::string(maxHigh()));
- builder.append("]");
- return builder.toString();
- }
-#endif
-
-private:
- T m_low;
- T m_high;
- UserData m_data;
- T m_maxHigh;
-};
-
-} // namespace WebCore
-
-#endif // PODInterval_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/PODIntervalTree.h b/chromium/third_party/WebKit/Source/core/platform/PODIntervalTree.h
deleted file mode 100644
index b3e11e2b594..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/PODIntervalTree.h
+++ /dev/null
@@ -1,266 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef PODIntervalTree_h
-#define PODIntervalTree_h
-
-#include "core/platform/PODArena.h"
-#include "core/platform/PODInterval.h"
-#include "core/platform/PODRedBlackTree.h"
-#include "wtf/Assertions.h"
-#include "wtf/Noncopyable.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-#ifndef NDEBUG
-template<class T>
-struct ValueToString;
-#endif
-
-template <class T, class UserData = void*>
-class PODIntervalSearchAdapter {
-public:
- typedef PODInterval<T, UserData> IntervalType;
-
- PODIntervalSearchAdapter(Vector<IntervalType>& result, const T& lowValue, const T& highValue)
- : m_result(result)
- , m_lowValue(lowValue)
- , m_highValue(highValue)
- {
- }
-
- const T& lowValue() const { return m_lowValue; }
- const T& highValue() const { return m_highValue; }
- void collectIfNeeded(const IntervalType& data) const
- {
- if (data.overlaps(m_lowValue, m_highValue))
- m_result.append(data);
- }
-
-private:
- Vector<IntervalType>& m_result;
- T m_lowValue;
- T m_highValue;
-};
-
-// An interval tree, which is a form of augmented red-black tree. It
-// supports efficient (O(lg n)) insertion, removal and querying of
-// intervals in the tree.
-template<class T, class UserData = void*>
-class PODIntervalTree : public PODRedBlackTree<PODInterval<T, UserData> > {
- WTF_MAKE_NONCOPYABLE(PODIntervalTree);
-public:
- // Typedef to reduce typing when declaring intervals to be stored in
- // this tree.
- typedef PODInterval<T, UserData> IntervalType;
- typedef PODIntervalSearchAdapter<T, UserData> IntervalSearchAdapterType;
-
- PODIntervalTree(UninitializedTreeEnum unitializedTree)
- : PODRedBlackTree<IntervalType>(unitializedTree)
- {
- init();
- }
-
- PODIntervalTree()
- : PODRedBlackTree<IntervalType>()
- {
- init();
- }
-
- explicit PODIntervalTree(PassRefPtr<PODArena> arena)
- : PODRedBlackTree<IntervalType>(arena)
- {
- init();
- }
-
- // Returns all intervals in the tree which overlap the given query
- // interval. The returned intervals are sorted by increasing low
- // endpoint.
- Vector<IntervalType> allOverlaps(const IntervalType& interval) const
- {
- Vector<IntervalType> result;
- allOverlaps(interval, result);
- return result;
- }
-
- // Returns all intervals in the tree which overlap the given query
- // interval. The returned intervals are sorted by increasing low
- // endpoint.
- void allOverlaps(const IntervalType& interval, Vector<IntervalType>& result) const
- {
- // Explicit dereference of "this" required because of
- // inheritance rules in template classes.
- IntervalSearchAdapterType adapter(result, interval.low(), interval.high());
- searchForOverlapsFrom<IntervalSearchAdapterType>(this->root(), adapter);
- }
-
- template <class AdapterType>
- void allOverlapsWithAdapter(AdapterType& adapter) const
- {
- // Explicit dereference of "this" required because of
- // inheritance rules in template classes.
- searchForOverlapsFrom<AdapterType>(this->root(), adapter);
- }
-
- // Helper to create interval objects.
- static IntervalType createInterval(const T& low, const T& high, const UserData data = 0)
- {
- return IntervalType(low, high, data);
- }
-
- virtual bool checkInvariants() const
- {
- if (!PODRedBlackTree<IntervalType>::checkInvariants())
- return false;
- if (!this->root())
- return true;
- return checkInvariantsFromNode(this->root(), 0);
- }
-
-private:
- typedef typename PODRedBlackTree<IntervalType>::Node IntervalNode;
-
- // Initializes the tree.
- void init()
- {
- // Explicit dereference of "this" required because of
- // inheritance rules in template classes.
- this->setNeedsFullOrderingComparisons(true);
- }
-
- // Starting from the given node, adds all overlaps with the given
- // interval to the result vector. The intervals are sorted by
- // increasing low endpoint.
- template <class AdapterType>
- void searchForOverlapsFrom(IntervalNode* node, AdapterType& adapter) const
- {
- if (!node)
- return;
-
- // Because the intervals are sorted by left endpoint, inorder
- // traversal produces results sorted as desired.
-
- // See whether we need to traverse the left subtree.
- IntervalNode* left = node->left();
- if (left
- // This is phrased this way to avoid the need for operator
- // <= on type T.
- && !(left->data().maxHigh() < adapter.lowValue()))
- searchForOverlapsFrom<AdapterType>(left, adapter);
-
- // Check for overlap with current node.
- adapter.collectIfNeeded(node->data());
-
- // See whether we need to traverse the right subtree.
- // This is phrased this way to avoid the need for operator <=
- // on type T.
- if (!(adapter.highValue() < node->data().low()))
- searchForOverlapsFrom<AdapterType>(node->right(), adapter);
- }
-
- virtual bool updateNode(IntervalNode* node)
- {
- // Would use const T&, but need to reassign this reference in this
- // function.
- const T* curMax = &node->data().high();
- IntervalNode* left = node->left();
- if (left) {
- if (*curMax < left->data().maxHigh())
- curMax = &left->data().maxHigh();
- }
- IntervalNode* right = node->right();
- if (right) {
- if (*curMax < right->data().maxHigh())
- curMax = &right->data().maxHigh();
- }
- // This is phrased like this to avoid needing operator!= on type T.
- if (!(*curMax == node->data().maxHigh())) {
- node->data().setMaxHigh(*curMax);
- return true;
- }
- return false;
- }
-
- bool checkInvariantsFromNode(IntervalNode* node, T* currentMaxValue) const
- {
- // These assignments are only done in order to avoid requiring
- // a default constructor on type T.
- T leftMaxValue(node->data().maxHigh());
- T rightMaxValue(node->data().maxHigh());
- IntervalNode* left = node->left();
- IntervalNode* right = node->right();
- if (left) {
- if (!checkInvariantsFromNode(left, &leftMaxValue))
- return false;
- }
- if (right) {
- if (!checkInvariantsFromNode(right, &rightMaxValue))
- return false;
- }
- if (!left && !right) {
- // Base case.
- if (currentMaxValue)
- *currentMaxValue = node->data().high();
- return (node->data().high() == node->data().maxHigh());
- }
- T localMaxValue(node->data().maxHigh());
- if (!left || !right) {
- if (left)
- localMaxValue = leftMaxValue;
- else
- localMaxValue = rightMaxValue;
- } else
- localMaxValue = (leftMaxValue < rightMaxValue) ? rightMaxValue : leftMaxValue;
- if (localMaxValue < node->data().high())
- localMaxValue = node->data().high();
- if (!(localMaxValue == node->data().maxHigh())) {
-#ifndef NDEBUG
- String localMaxValueString = ValueToString<T>::string(localMaxValue);
- LOG_ERROR("PODIntervalTree verification failed at node 0x%p: localMaxValue=%s and data=%s",
- node, localMaxValueString.utf8().data(), node->data().toString().utf8().data());
-#endif
- return false;
- }
- if (currentMaxValue)
- *currentMaxValue = localMaxValue;
- return true;
- }
-};
-
-#ifndef NDEBUG
-// Support for printing PODIntervals at the PODRedBlackTree level.
-template<class T, class UserData>
-struct ValueToString<PODInterval<T, UserData> > {
- static String string(const PODInterval<T, UserData>& interval)
- {
- return interval.toString();
- }
-};
-#endif
-
-} // namespace WebCore
-
-#endif // PODIntervalTree_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/PODRedBlackTree.h b/chromium/third_party/WebKit/Source/core/platform/PODRedBlackTree.h
deleted file mode 100644
index 80a7160cc0b..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/PODRedBlackTree.h
+++ /dev/null
@@ -1,827 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-// A red-black tree, which is a form of a balanced binary tree. It
-// supports efficient insertion, deletion and queries of comparable
-// elements. The same element may be inserted multiple times. The
-// algorithmic complexity of common operations is:
-//
-// Insertion: O(lg(n))
-// Deletion: O(lg(n))
-// Querying: O(lg(n))
-//
-// The data type T that is stored in this red-black tree must be only
-// Plain Old Data (POD), or bottom out into POD. It must _not_ rely on
-// having its destructor called. This implementation internally
-// allocates storage in large chunks and does not call the destructor
-// on each object.
-//
-// Type T must supply a default constructor, a copy constructor, and
-// the "<" and "==" operators.
-//
-// In debug mode, printing of the data contained in the tree is
-// enabled. This requires the template specialization to be available:
-//
-// template<> struct WebCore::ValueToString<T> {
-// static String string(const T& t);
-// };
-//
-// Note that when complex types are stored in this red/black tree, it
-// is possible that single invocations of the "<" and "==" operators
-// will be insufficient to describe the ordering of elements in the
-// tree during queries. As a concrete example, consider the case where
-// intervals are stored in the tree sorted by low endpoint. The "<"
-// operator on the Interval class only compares the low endpoint, but
-// the "==" operator takes into account the high endpoint as well.
-// This makes the necessary logic for querying and deletion somewhat
-// more complex. In order to properly handle such situations, the
-// property "needsFullOrderingComparisons" must be set to true on
-// the tree.
-//
-// This red-black tree is designed to be _augmented_; subclasses can
-// add additional and summary information to each node to efficiently
-// store and index more complex data structures. A concrete example is
-// the IntervalTree, which extends each node with a summary statistic
-// to efficiently store one-dimensional intervals.
-//
-// The design of this red-black tree comes from Cormen, Leiserson,
-// and Rivest, _Introduction to Algorithms_, MIT Press, 1990.
-
-#ifndef PODRedBlackTree_h
-#define PODRedBlackTree_h
-
-#include "core/platform/PODFreeListArena.h"
-#include "wtf/Assertions.h"
-#include "wtf/Noncopyable.h"
-#include "wtf/RefPtr.h"
-#ifndef NDEBUG
-#include "wtf/text/CString.h"
-#include "wtf/text/StringBuilder.h"
-#include "wtf/text/WTFString.h"
-#endif
-
-namespace WebCore {
-
-#ifndef NDEBUG
-template<class T>
-struct ValueToString;
-#endif
-
-enum UninitializedTreeEnum {
- UninitializedTree
-};
-
-template<class T>
-class PODRedBlackTree {
-public:
- class Node;
-
- // Visitor interface for walking all of the tree's elements.
- class Visitor {
- public:
- virtual void visit(const T& data) = 0;
- protected:
- virtual ~Visitor() { }
- };
-
- // Constructs a new red-black tree without allocating an arena.
- // isInitialized will return false in this case. initIfNeeded can be used
- // to init the structure. This constructor is usefull for creating
- // lazy initialized tree.
- explicit PODRedBlackTree(UninitializedTreeEnum)
- : m_root(0)
- , m_needsFullOrderingComparisons(false)
-#ifndef NDEBUG
- , m_verboseDebugging(false)
-#endif
- {
- }
-
- // Constructs a new red-black tree, allocating temporary objects
- // from a newly constructed PODFreeListArena.
- PODRedBlackTree()
- : m_arena(PODFreeListArena<Node>::create())
- , m_root(0)
- , m_needsFullOrderingComparisons(false)
-#ifndef NDEBUG
- , m_verboseDebugging(false)
-#endif
- {
- }
-
- // Constructs a new red-black tree, allocating temporary objects
- // from the given PODArena.
- explicit PODRedBlackTree(PassRefPtr<PODFreeListArena<Node> > arena)
- : m_arena(arena)
- , m_root(0)
- , m_needsFullOrderingComparisons(false)
-#ifndef NDEBUG
- , m_verboseDebugging(false)
-#endif
- {
- }
-
- virtual ~PODRedBlackTree() { }
-
- // Clearing will delete the contents of the tree. After this call
- // isInitialized will return false.
- void clear()
- {
- markFree(m_root);
- m_arena = 0;
- m_root = 0;
- }
-
- bool isInitialized() const
- {
- return m_arena;
- }
-
- void initIfNeeded()
- {
- if (!m_arena)
- m_arena = PODFreeListArena<Node>::create();
- }
-
- void initIfNeeded(PODFreeListArena<Node>* arena)
- {
- if (!m_arena)
- m_arena = arena;
- }
-
- void add(const T& data)
- {
- ASSERT(isInitialized());
- Node* node = m_arena->template allocateObject<T>(data);
- insertNode(node);
- }
-
- // Returns true if the datum was found in the tree.
- bool remove(const T& data)
- {
- ASSERT(isInitialized());
- Node* node = treeSearch(data);
- if (node) {
- deleteNode(node);
- return true;
- }
- return false;
- }
-
- bool contains(const T& data) const
- {
- ASSERT(isInitialized());
- return treeSearch(data);
- }
-
- void visitInorder(Visitor* visitor) const
- {
- ASSERT(isInitialized());
- if (!m_root)
- return;
- visitInorderImpl(m_root, visitor);
- }
-
- int size() const
- {
- ASSERT(isInitialized());
- Counter counter;
- visitInorder(&counter);
- return counter.count();
- }
-
- // See the class documentation for an explanation of this property.
- void setNeedsFullOrderingComparisons(bool needsFullOrderingComparisons)
- {
- m_needsFullOrderingComparisons = needsFullOrderingComparisons;
- }
-
- virtual bool checkInvariants() const
- {
- ASSERT(isInitialized());
- int blackCount;
- return checkInvariantsFromNode(m_root, &blackCount);
- }
-
-#ifndef NDEBUG
- // Dumps the tree's contents to the logging info stream for
- // debugging purposes.
- void dump() const
- {
- if (m_arena)
- dumpFromNode(m_root, 0);
- }
-
- // Turns on or off verbose debugging of the tree, causing many
- // messages to be logged during insertion and other operations in
- // debug mode.
- void setVerboseDebugging(bool verboseDebugging)
- {
- m_verboseDebugging = verboseDebugging;
- }
-#endif
-
- enum Color {
- Red = 1,
- Black
- };
-
- // The base Node class which is stored in the tree. Nodes are only
- // an internal concept; users of the tree deal only with the data
- // they store in it.
- class Node {
- WTF_MAKE_NONCOPYABLE(Node);
- public:
- // Constructor. Newly-created nodes are colored red.
- explicit Node(const T& data)
- : m_left(0)
- , m_right(0)
- , m_parent(0)
- , m_color(Red)
- , m_data(data)
- {
- }
-
- virtual ~Node() { }
-
- Color color() const { return m_color; }
- void setColor(Color color) { m_color = color; }
-
- // Fetches the user data.
- T& data() { return m_data; }
-
- // Copies all user-level fields from the source node, but not
- // internal fields. For example, the base implementation of this
- // method copies the "m_data" field, but not the child or parent
- // fields. Any augmentation information also does not need to be
- // copied, as it will be recomputed. Subclasses must call the
- // superclass implementation.
- virtual void copyFrom(Node* src) { m_data = src->data(); }
-
- Node* left() const { return m_left; }
- void setLeft(Node* node) { m_left = node; }
-
- Node* right() const { return m_right; }
- void setRight(Node* node) { m_right = node; }
-
- Node* parent() const { return m_parent; }
- void setParent(Node* node) { m_parent = node; }
-
- private:
- Node* m_left;
- Node* m_right;
- Node* m_parent;
- Color m_color;
- T m_data;
- };
-
-protected:
- // Returns the root of the tree, which is needed by some subclasses.
- Node* root() const { return m_root; }
-
-private:
- // This virtual method is the hook that subclasses should use when
- // augmenting the red-black tree with additional per-node summary
- // information. For example, in the case of an interval tree, this
- // is used to compute the maximum endpoint of the subtree below the
- // given node based on the values in the left and right children. It
- // is guaranteed that this will be called in the correct order to
- // properly update such summary information based only on the values
- // in the left and right children. This method should return true if
- // the node's summary information changed.
- virtual bool updateNode(Node*) { return false; }
-
- //----------------------------------------------------------------------
- // Generic binary search tree operations
- //
-
- // Searches the tree for the given datum.
- Node* treeSearch(const T& data) const
- {
- if (m_needsFullOrderingComparisons)
- return treeSearchFullComparisons(m_root, data);
-
- return treeSearchNormal(m_root, data);
- }
-
- // Searches the tree using the normal comparison operations,
- // suitable for simple data types such as numbers.
- Node* treeSearchNormal(Node* current, const T& data) const
- {
- while (current) {
- if (current->data() == data)
- return current;
- if (data < current->data())
- current = current->left();
- else
- current = current->right();
- }
- return 0;
- }
-
- // Searches the tree using multiple comparison operations, required
- // for data types with more complex behavior such as intervals.
- Node* treeSearchFullComparisons(Node* current, const T& data) const
- {
- if (!current)
- return 0;
- if (data < current->data())
- return treeSearchFullComparisons(current->left(), data);
- if (current->data() < data)
- return treeSearchFullComparisons(current->right(), data);
- if (data == current->data())
- return current;
-
- // We may need to traverse both the left and right subtrees.
- Node* result = treeSearchFullComparisons(current->left(), data);
- if (!result)
- result = treeSearchFullComparisons(current->right(), data);
- return result;
- }
-
- void treeInsert(Node* z)
- {
- Node* y = 0;
- Node* x = m_root;
- while (x) {
- y = x;
- if (z->data() < x->data())
- x = x->left();
- else
- x = x->right();
- }
- z->setParent(y);
- if (!y)
- m_root = z;
- else {
- if (z->data() < y->data())
- y->setLeft(z);
- else
- y->setRight(z);
- }
- }
-
- // Finds the node following the given one in sequential ordering of
- // their data, or null if none exists.
- Node* treeSuccessor(Node* x)
- {
- if (x->right())
- return treeMinimum(x->right());
- Node* y = x->parent();
- while (y && x == y->right()) {
- x = y;
- y = y->parent();
- }
- return y;
- }
-
- // Finds the minimum element in the sub-tree rooted at the given
- // node.
- Node* treeMinimum(Node* x)
- {
- while (x->left())
- x = x->left();
- return x;
- }
-
- // Helper for maintaining the augmented red-black tree.
- void propagateUpdates(Node* start)
- {
- bool shouldContinue = true;
- while (start && shouldContinue) {
- shouldContinue = updateNode(start);
- start = start->parent();
- }
- }
-
- //----------------------------------------------------------------------
- // Red-Black tree operations
- //
-
- // Left-rotates the subtree rooted at x.
- // Returns the new root of the subtree (x's right child).
- Node* leftRotate(Node* x)
- {
- // Set y.
- Node* y = x->right();
-
- // Turn y's left subtree into x's right subtree.
- x->setRight(y->left());
- if (y->left())
- y->left()->setParent(x);
-
- // Link x's parent to y.
- y->setParent(x->parent());
- if (!x->parent())
- m_root = y;
- else {
- if (x == x->parent()->left())
- x->parent()->setLeft(y);
- else
- x->parent()->setRight(y);
- }
-
- // Put x on y's left.
- y->setLeft(x);
- x->setParent(y);
-
- // Update nodes lowest to highest.
- updateNode(x);
- updateNode(y);
- return y;
- }
-
- // Right-rotates the subtree rooted at y.
- // Returns the new root of the subtree (y's left child).
- Node* rightRotate(Node* y)
- {
- // Set x.
- Node* x = y->left();
-
- // Turn x's right subtree into y's left subtree.
- y->setLeft(x->right());
- if (x->right())
- x->right()->setParent(y);
-
- // Link y's parent to x.
- x->setParent(y->parent());
- if (!y->parent())
- m_root = x;
- else {
- if (y == y->parent()->left())
- y->parent()->setLeft(x);
- else
- y->parent()->setRight(x);
- }
-
- // Put y on x's right.
- x->setRight(y);
- y->setParent(x);
-
- // Update nodes lowest to highest.
- updateNode(y);
- updateNode(x);
- return x;
- }
-
- // Inserts the given node into the tree.
- void insertNode(Node* x)
- {
- treeInsert(x);
- x->setColor(Red);
- updateNode(x);
-
- logIfVerbose(" PODRedBlackTree::InsertNode");
-
- // The node from which to start propagating updates upwards.
- Node* updateStart = x->parent();
-
- while (x != m_root && x->parent()->color() == Red) {
- if (x->parent() == x->parent()->parent()->left()) {
- Node* y = x->parent()->parent()->right();
- if (y && y->color() == Red) {
- // Case 1
- logIfVerbose(" Case 1/1");
- x->parent()->setColor(Black);
- y->setColor(Black);
- x->parent()->parent()->setColor(Red);
- updateNode(x->parent());
- x = x->parent()->parent();
- updateNode(x);
- updateStart = x->parent();
- } else {
- if (x == x->parent()->right()) {
- logIfVerbose(" Case 1/2");
- // Case 2
- x = x->parent();
- leftRotate(x);
- }
- // Case 3
- logIfVerbose(" Case 1/3");
- x->parent()->setColor(Black);
- x->parent()->parent()->setColor(Red);
- Node* newSubTreeRoot = rightRotate(x->parent()->parent());
- updateStart = newSubTreeRoot->parent();
- }
- } else {
- // Same as "then" clause with "right" and "left" exchanged.
- Node* y = x->parent()->parent()->left();
- if (y && y->color() == Red) {
- // Case 1
- logIfVerbose(" Case 2/1");
- x->parent()->setColor(Black);
- y->setColor(Black);
- x->parent()->parent()->setColor(Red);
- updateNode(x->parent());
- x = x->parent()->parent();
- updateNode(x);
- updateStart = x->parent();
- } else {
- if (x == x->parent()->left()) {
- // Case 2
- logIfVerbose(" Case 2/2");
- x = x->parent();
- rightRotate(x);
- }
- // Case 3
- logIfVerbose(" Case 2/3");
- x->parent()->setColor(Black);
- x->parent()->parent()->setColor(Red);
- Node* newSubTreeRoot = leftRotate(x->parent()->parent());
- updateStart = newSubTreeRoot->parent();
- }
- }
- }
-
- propagateUpdates(updateStart);
-
- m_root->setColor(Black);
- }
-
- // Restores the red-black property to the tree after splicing out
- // a node. Note that x may be null, which is why xParent must be
- // supplied.
- void deleteFixup(Node* x, Node* xParent)
- {
- while (x != m_root && (!x || x->color() == Black)) {
- if (x == xParent->left()) {
- // Note: the text points out that w can not be null.
- // The reason is not obvious from simply looking at
- // the code; it comes about from the properties of the
- // red-black tree.
- Node* w = xParent->right();
- ASSERT(w); // x's sibling should not be null.
- if (w->color() == Red) {
- // Case 1
- w->setColor(Black);
- xParent->setColor(Red);
- leftRotate(xParent);
- w = xParent->right();
- }
- if ((!w->left() || w->left()->color() == Black)
- && (!w->right() || w->right()->color() == Black)) {
- // Case 2
- w->setColor(Red);
- x = xParent;
- xParent = x->parent();
- } else {
- if (!w->right() || w->right()->color() == Black) {
- // Case 3
- w->left()->setColor(Black);
- w->setColor(Red);
- rightRotate(w);
- w = xParent->right();
- }
- // Case 4
- w->setColor(xParent->color());
- xParent->setColor(Black);
- if (w->right())
- w->right()->setColor(Black);
- leftRotate(xParent);
- x = m_root;
- xParent = x->parent();
- }
- } else {
- // Same as "then" clause with "right" and "left"
- // exchanged.
-
- // Note: the text points out that w can not be null.
- // The reason is not obvious from simply looking at
- // the code; it comes about from the properties of the
- // red-black tree.
- Node* w = xParent->left();
- ASSERT(w); // x's sibling should not be null.
- if (w->color() == Red) {
- // Case 1
- w->setColor(Black);
- xParent->setColor(Red);
- rightRotate(xParent);
- w = xParent->left();
- }
- if ((!w->right() || w->right()->color() == Black)
- && (!w->left() || w->left()->color() == Black)) {
- // Case 2
- w->setColor(Red);
- x = xParent;
- xParent = x->parent();
- } else {
- if (!w->left() || w->left()->color() == Black) {
- // Case 3
- w->right()->setColor(Black);
- w->setColor(Red);
- leftRotate(w);
- w = xParent->left();
- }
- // Case 4
- w->setColor(xParent->color());
- xParent->setColor(Black);
- if (w->left())
- w->left()->setColor(Black);
- rightRotate(xParent);
- x = m_root;
- xParent = x->parent();
- }
- }
- }
- if (x)
- x->setColor(Black);
- }
-
- // Deletes the given node from the tree. Note that this
- // particular node may not actually be removed from the tree;
- // instead, another node might be removed and its contents
- // copied into z.
- void deleteNode(Node* z)
- {
- // Y is the node to be unlinked from the tree.
- Node* y;
- if (!z->left() || !z->right())
- y = z;
- else
- y = treeSuccessor(z);
-
- // Y is guaranteed to be non-null at this point.
- Node* x;
- if (y->left())
- x = y->left();
- else
- x = y->right();
-
- // X is the child of y which might potentially replace y in
- // the tree. X might be null at this point.
- Node* xParent;
- if (x) {
- x->setParent(y->parent());
- xParent = x->parent();
- } else
- xParent = y->parent();
- if (!y->parent())
- m_root = x;
- else {
- if (y == y->parent()->left())
- y->parent()->setLeft(x);
- else
- y->parent()->setRight(x);
- }
- if (y != z) {
- z->copyFrom(y);
- // This node has changed location in the tree and must be updated.
- updateNode(z);
- // The parent and its parents may now be out of date.
- propagateUpdates(z->parent());
- }
-
- // If we haven't already updated starting from xParent, do so now.
- if (xParent && xParent != y && xParent != z)
- propagateUpdates(xParent);
- if (y->color() == Black)
- deleteFixup(x, xParent);
-
- m_arena->freeObject(y);
- }
-
- // Visits the subtree rooted at the given node in order.
- void visitInorderImpl(Node* node, Visitor* visitor) const
- {
- if (node->left())
- visitInorderImpl(node->left(), visitor);
- visitor->visit(node->data());
- if (node->right())
- visitInorderImpl(node->right(), visitor);
- }
-
- void markFree(Node *node)
- {
- if (!node)
- return;
-
- if (node->left())
- markFree(node->left());
- if (node->right())
- markFree(node->right());
- m_arena->freeObject(node);
- }
-
- //----------------------------------------------------------------------
- // Helper class for size()
-
- // A Visitor which simply counts the number of visited elements.
- class Counter : public Visitor {
- WTF_MAKE_NONCOPYABLE(Counter);
- public:
- Counter()
- : m_count(0) { }
-
- virtual void visit(const T&) { ++m_count; }
- int count() const { return m_count; }
-
- private:
- int m_count;
- };
-
- //----------------------------------------------------------------------
- // Verification and debugging routines
- //
-
- // Returns in the "blackCount" parameter the number of black
- // children along all paths to all leaves of the given node.
- bool checkInvariantsFromNode(Node* node, int* blackCount) const
- {
- // Base case is a leaf node.
- if (!node) {
- *blackCount = 1;
- return true;
- }
-
- // Each node is either red or black.
- if (!(node->color() == Red || node->color() == Black))
- return false;
-
- // Every leaf (or null) is black.
-
- if (node->color() == Red) {
- // Both of its children are black.
- if (!((!node->left() || node->left()->color() == Black)))
- return false;
- if (!((!node->right() || node->right()->color() == Black)))
- return false;
- }
-
- // Every simple path to a leaf node contains the same number of
- // black nodes.
- int leftCount = 0, rightCount = 0;
- bool leftValid = checkInvariantsFromNode(node->left(), &leftCount);
- bool rightValid = checkInvariantsFromNode(node->right(), &rightCount);
- if (!leftValid || !rightValid)
- return false;
- *blackCount = leftCount + (node->color() == Black ? 1 : 0);
- return leftCount == rightCount;
- }
-
-#ifdef NDEBUG
- void logIfVerbose(const char*) const { }
-#else
- void logIfVerbose(const char* output) const
- {
- if (m_verboseDebugging)
- LOG_ERROR("%s", output);
- }
-#endif
-
-#ifndef NDEBUG
- // Dumps the subtree rooted at the given node.
- void dumpFromNode(Node* node, int indentation) const
- {
- StringBuilder builder;
- for (int i = 0; i < indentation; i++)
- builder.append(" ");
- builder.append("-");
- if (node) {
- builder.append(" ");
- builder.append(ValueToString<T>::string(node->data()));
- builder.append((node->color() == Black) ? " (black)" : " (red)");
- }
- LOG_ERROR("%s", builder.toString().ascii().data());
- if (node) {
- dumpFromNode(node->left(), indentation + 2);
- dumpFromNode(node->right(), indentation + 2);
- }
- }
-#endif
-
- //----------------------------------------------------------------------
- // Data members
-
- RefPtr<PODFreeListArena<Node> > m_arena;
- Node* m_root;
- bool m_needsFullOrderingComparisons;
-#ifndef NDEBUG
- bool m_verboseDebugging;
-#endif
-};
-
-} // namespace WebCore
-
-#endif // PODRedBlackTree_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/ParsingUtilities.h b/chromium/third_party/WebKit/Source/core/platform/ParsingUtilities.h
deleted file mode 100644
index ba8fa9e5529..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/ParsingUtilities.h
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ParsingUtilities_h
-#define ParsingUtilities_h
-
-template<typename CharType>
-bool skipExactly(const CharType*& position, const CharType* end, CharType delimiter)
-{
- if (position < end && *position == delimiter) {
- ++position;
- return true;
- }
- return false;
-}
-
-template<typename CharType, bool characterPredicate(CharType)>
-bool skipExactly(const CharType*& position, const CharType* end)
-{
- if (position < end && characterPredicate(*position)) {
- ++position;
- return true;
- }
- return false;
-}
-
-template<typename CharType>
-void skipUntil(const CharType*& position, const CharType* end, CharType delimiter)
-{
- while (position < end && *position != delimiter)
- ++position;
-}
-
-template<typename CharType, bool characterPredicate(CharType)>
-void skipUntil(const CharType*& position, const CharType* end)
-{
- while (position < end && !characterPredicate(*position))
- ++position;
-}
-
-template<typename CharType, bool characterPredicate(CharType)>
-void skipWhile(const CharType*& position, const CharType* end)
-{
- while (position < end && characterPredicate(*position))
- ++position;
-}
-
-#endif
-
diff --git a/chromium/third_party/WebKit/Source/core/platform/Partitions.cpp b/chromium/third_party/WebKit/Source/core/platform/Partitions.cpp
deleted file mode 100644
index 05ee880e17e..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/Partitions.cpp
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-
-#include "config.h"
-#include "core/platform/Partitions.h"
-
-namespace WebCore {
-
-PartitionAllocator<3072> Partitions::m_objectModelAllocator;
-PartitionAllocator<1024> Partitions::m_renderingAllocator;
-
-void Partitions::init()
-{
- m_objectModelAllocator.init();
- m_renderingAllocator.init();
-}
-
-void Partitions::shutdown()
-{
- // We could ASSERT here for a memory leak within the partition, but it leads
- // to very hard to diagnose ASSERTs, so it's best to leave leak checking for
- // the valgrind and heapcheck bots, which run without partitions.
- (void) m_renderingAllocator.shutdown();
- (void) m_objectModelAllocator.shutdown();
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/Partitions.h b/chromium/third_party/WebKit/Source/core/platform/Partitions.h
deleted file mode 100644
index 6f20e708420..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/Partitions.h
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef Partitions_h
-#define Partitions_h
-
-#include "wtf/PartitionAlloc.h"
-
-namespace WebCore {
-
-class Partitions {
-public:
- static void init();
- static void shutdown();
-
- ALWAYS_INLINE static PartitionRoot* getObjectModelPartition() { return m_objectModelAllocator.root(); }
- ALWAYS_INLINE static PartitionRoot* getRenderingPartition() { return m_renderingAllocator.root(); }
-
-private:
- static PartitionAllocator<3072> m_objectModelAllocator;
- static PartitionAllocator<1024> m_renderingAllocator;
-};
-
-} // namespace WebCore
-
-#endif // Partitions_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/Pasteboard.cpp b/chromium/third_party/WebKit/Source/core/platform/Pasteboard.cpp
index 0c36c92b70b..bcf42d5cf4b 100644
--- a/chromium/third_party/WebKit/Source/core/platform/Pasteboard.cpp
+++ b/chromium/third_party/WebKit/Source/core/platform/Pasteboard.cpp
@@ -31,26 +31,15 @@
#include "config.h"
#include "core/platform/Pasteboard.h"
-#include "HTMLNames.h"
-#include "SVGNames.h"
-#include "XLinkNames.h"
-#include "core/dom/Document.h"
-#include "core/dom/DocumentFragment.h"
-#include "core/dom/Element.h"
-#include "core/dom/Range.h"
-#include "core/editing/markup.h"
-#include "core/fetch/ImageResource.h"
-#include "core/html/parser/HTMLParserIdioms.h"
-#include "core/page/Frame.h"
#include "core/platform/chromium/ChromiumDataObject.h"
-#include "core/platform/chromium/ClipboardUtilitiesChromium.h"
-#include "core/platform/graphics/Image.h"
-#include "core/platform/graphics/skia/NativeImageSkia.h"
-#include "core/rendering/RenderImage.h"
+#include "platform/clipboard/ClipboardUtilities.h"
+#include "platform/graphics/Image.h"
+#include "platform/graphics/skia/NativeImageSkia.h"
+#include "platform/weborigin/KURL.h"
#include "public/platform/Platform.h"
-#include "public/platform/WebClipboard.h"
#include "public/platform/WebDragData.h"
-#include "weborigin/KURL.h"
+#include "public/platform/WebString.h"
+#include "public/platform/WebURL.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefPtr.h"
@@ -63,31 +52,18 @@ Pasteboard* Pasteboard::generalPasteboard()
}
Pasteboard::Pasteboard()
- : m_buffer(WebKit::WebClipboard::BufferStandard)
+ : m_buffer(blink::WebClipboard::BufferStandard)
{
}
bool Pasteboard::isSelectionMode() const
{
- return m_buffer == WebKit::WebClipboard::BufferSelection;
+ return m_buffer == blink::WebClipboard::BufferSelection;
}
void Pasteboard::setSelectionMode(bool selectionMode)
{
- m_buffer = selectionMode ? WebKit::WebClipboard::BufferSelection : WebKit::WebClipboard::BufferStandard;
-}
-
-void Pasteboard::writeSelection(Range* selectedRange, bool canSmartCopyOrDelete, const String& text)
-{
- String html = createMarkup(selectedRange, 0, AnnotateForInterchange, false, ResolveNonLocalURLs);
- KURL url = selectedRange->startContainer()->document().url();
- String plainText = text;
-#if OS(WIN)
- replaceNewlinesWithWindowsStyleNewlines(plainText);
-#endif
- replaceNBSPWithSpace(plainText);
-
- WebKit::Platform::current()->clipboard()->writeHTML(html, url, plainText, canSmartCopyOrDelete);
+ m_buffer = selectionMode ? blink::WebClipboard::BufferSelection : blink::WebClipboard::BufferStandard;
}
void Pasteboard::writePlainText(const String& text, SmartReplaceOption)
@@ -96,99 +72,68 @@ void Pasteboard::writePlainText(const String& text, SmartReplaceOption)
#if OS(WIN)
String plainText(text);
replaceNewlinesWithWindowsStyleNewlines(plainText);
- WebKit::Platform::current()->clipboard()->writePlainText(plainText);
+ blink::Platform::current()->clipboard()->writePlainText(plainText);
#else
- WebKit::Platform::current()->clipboard()->writePlainText(text);
+ blink::Platform::current()->clipboard()->writePlainText(text);
#endif
}
-void Pasteboard::writeURL(const KURL& url, const String& titleStr)
-{
- ASSERT(!url.isEmpty());
-
- String title(titleStr);
- if (title.isEmpty()) {
- title = url.lastPathComponent();
- if (title.isEmpty())
- title = url.host();
- }
-
- WebKit::Platform::current()->clipboard()->writeURL(url, title);
-}
-
-void Pasteboard::writeImage(Node* node, const KURL&, const String& title)
+void Pasteboard::writeImage(Image* image, const KURL& url, const String& title)
{
- ASSERT(node);
-
- if (!(node->renderer() && node->renderer()->isImage()))
- return;
-
- RenderImage* renderer = toRenderImage(node->renderer());
- ImageResource* cachedImage = renderer->cachedImage();
- if (!cachedImage || cachedImage->errorOccurred())
- return;
- Image* image = cachedImage->imageForRenderer(renderer);
ASSERT(image);
RefPtr<NativeImageSkia> bitmap = image->nativeImageForCurrentFrame();
if (!bitmap)
return;
- // If the image is wrapped in a link, |url| points to the target of the
- // link. This isn't useful to us, so get the actual image URL.
- AtomicString urlString;
- if (node->hasTagName(HTMLNames::imgTag) || node->hasTagName(HTMLNames::inputTag))
- urlString = toElement(node)->getAttribute(HTMLNames::srcAttr);
- else if (node->hasTagName(SVGNames::imageTag))
- urlString = toElement(node)->getAttribute(XLinkNames::hrefAttr);
- else if (node->hasTagName(HTMLNames::embedTag) || node->hasTagName(HTMLNames::objectTag))
- urlString = toElement(node)->imageSourceURL();
- KURL url = urlString.isEmpty() ? KURL() : node->document().completeURL(stripLeadingAndTrailingHTMLSpaces(urlString));
- WebKit::WebImage webImage = bitmap->bitmap();
- WebKit::Platform::current()->clipboard()->writeImage(webImage, WebKit::WebURL(url), WebKit::WebString(title));
+ blink::WebImage webImage = bitmap->bitmap();
+ blink::Platform::current()->clipboard()->writeImage(webImage, blink::WebURL(url), blink::WebString(title));
}
void Pasteboard::writeDataObject(PassRefPtr<ChromiumDataObject> dataObject)
{
- WebKit::Platform::current()->clipboard()->writeDataObject(dataObject);
+ blink::Platform::current()->clipboard()->writeDataObject(dataObject);
}
bool Pasteboard::canSmartReplace()
{
- return WebKit::Platform::current()->clipboard()->isFormatAvailable(WebKit::WebClipboard::FormatSmartPaste, m_buffer);
+ return blink::Platform::current()->clipboard()->isFormatAvailable(blink::WebClipboard::FormatSmartPaste, m_buffer);
+}
+
+bool Pasteboard::isHTMLAvailable()
+{
+ return blink::Platform::current()->clipboard()->isFormatAvailable(blink::WebClipboard::FormatHTML, m_buffer);
}
String Pasteboard::plainText()
{
- return WebKit::Platform::current()->clipboard()->readPlainText(m_buffer);
+ return blink::Platform::current()->clipboard()->readPlainText(m_buffer);
}
-PassRefPtr<DocumentFragment> Pasteboard::documentFragment(Frame* frame, PassRefPtr<Range> context, bool allowPlainText, bool& chosePlainText)
+String Pasteboard::readHTML(KURL& url, unsigned& fragmentStart, unsigned& fragmentEnd)
{
- chosePlainText = false;
-
- if (WebKit::Platform::current()->clipboard()->isFormatAvailable(WebKit::WebClipboard::FormatHTML, m_buffer)) {
- unsigned fragmentStart = 0;
- unsigned fragmentEnd = 0;
- WebKit::WebURL url;
- WebKit::WebString markup = WebKit::Platform::current()->clipboard()->readHTML(m_buffer, &url, &fragmentStart, &fragmentEnd);
- if (!markup.isEmpty()) {
- ASSERT(frame->document());
- if (RefPtr<DocumentFragment> fragment = createFragmentFromMarkupWithContext(*frame->document(), markup, fragmentStart, fragmentEnd, KURL(url), DisallowScriptingAndPluginContent))
- return fragment.release();
- }
+ blink::WebURL webURL;
+ blink::WebString markup = blink::Platform::current()->clipboard()->readHTML(m_buffer, &webURL, &fragmentStart, &fragmentEnd);
+ if (!markup.isEmpty()) {
+ url = webURL;
+ // fragmentStart and fragmentEnd are populated by WebClipboard::readHTML.
+ } else {
+ url = KURL();
+ fragmentStart = 0;
+ fragmentEnd = 0;
}
+ return markup;
+}
- if (allowPlainText) {
- String markup = WebKit::Platform::current()->clipboard()->readPlainText(m_buffer);
- if (!markup.isEmpty()) {
- chosePlainText = true;
- if (RefPtr<DocumentFragment> fragment = createFragmentFromText(context.get(), markup))
- return fragment.release();
- }
- }
+void Pasteboard::writeHTML(const String& markup, const KURL& documentURL, const String& plainText, bool canSmartCopyOrDelete)
+{
+ String text = plainText;
+#if OS(WIN)
+ replaceNewlinesWithWindowsStyleNewlines(text);
+#endif
+ replaceNBSPWithSpace(text);
- return 0;
+ blink::Platform::current()->clipboard()->writeHTML(markup, documentURL, text, canSmartCopyOrDelete);
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/Pasteboard.h b/chromium/third_party/WebKit/Source/core/platform/Pasteboard.h
index 58a498e6284..f7fa5845c26 100644
--- a/chromium/third_party/WebKit/Source/core/platform/Pasteboard.h
+++ b/chromium/third_party/WebKit/Source/core/platform/Pasteboard.h
@@ -28,26 +28,15 @@
#include "public/platform/WebClipboard.h"
#include "wtf/Forward.h"
-#include "wtf/HashSet.h"
#include "wtf/Noncopyable.h"
#include "wtf/text/WTFString.h"
#include "wtf/Vector.h"
-// FIXME: This class is too high-level to be in the platform directory, since it
-// uses the DOM and makes calls to Editor. It should either be divested of its
-// knowledge of the frame and editor or moved into the editing directory.
-
namespace WebCore {
-class ArchiveResource;
class ChromiumDataObject;
-class DocumentFragment;
-class Frame;
-class HitTestResult;
+class Image;
class KURL;
-class Node;
-class Range;
-class SharedBuffer;
class Pasteboard {
WTF_MAKE_NONCOPYABLE(Pasteboard); WTF_MAKE_FAST_ALLOCATED;
@@ -58,22 +47,31 @@ public:
};
static Pasteboard* generalPasteboard();
- void writeSelection(Range*, bool canSmartCopyOrDelete, const String& text);
void writePlainText(const String&, SmartReplaceOption);
- void writeURL(const KURL&, const String&);
- void writeImage(Node*, const KURL&, const String& title);
+ void writeImage(Image*, const KURL&, const String& title);
void writeDataObject(PassRefPtr<ChromiumDataObject>);
bool canSmartReplace();
- PassRefPtr<DocumentFragment> documentFragment(Frame*, PassRefPtr<Range>, bool allowPlainText, bool& chosePlainText);
+ bool isHTMLAvailable();
String plainText();
+ // If no data is read, an empty string will be returned and all out parameters will be cleared.
+ // If applicable, the page URL will be assigned to the KURL parameter.
+ // fragmentStart and fragmentEnd are indexes into the returned markup that indicate
+ // the start and end of the returned markup. If there is no additional context,
+ // fragmentStart will be zero and fragmentEnd will be the same as the length of the markup.
+ String readHTML(KURL&, unsigned& fragmentStart, unsigned& fragmentEnd);
+
+ void writeHTML(const String& markup, const KURL& documentURL, const String& plainText, bool canSmartCopyOrDelete);
+
bool isSelectionMode() const;
void setSelectionMode(bool);
+ blink::WebClipboard::Buffer buffer() const { return m_buffer; }
+
private:
Pasteboard();
- WebKit::WebClipboard::Buffer m_buffer;
+ blink::WebClipboard::Buffer m_buffer;
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/PlatformEvent.cpp b/chromium/third_party/WebKit/Source/core/platform/PlatformEvent.cpp
deleted file mode 100644
index 28bfb2b28f3..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/PlatformEvent.cpp
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * Copyright (C) 2011 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/PlatformEvent.h"
diff --git a/chromium/third_party/WebKit/Source/core/platform/PlatformEvent.h b/chromium/third_party/WebKit/Source/core/platform/PlatformEvent.h
deleted file mode 100644
index ff14a97ba68..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/PlatformEvent.h
+++ /dev/null
@@ -1,142 +0,0 @@
-/*
- * Copyright (C) 2011 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef PlatformEvent_h
-#define PlatformEvent_h
-
-namespace WebCore {
-
-class PlatformEvent {
-public:
- enum Type {
- NoType = 0,
-
- // PlatformKeyboardEvent
- KeyDown,
- KeyUp,
- RawKeyDown,
- Char,
-
- // PlatformMouseEvent
- MouseMoved,
- MousePressed,
- MouseReleased,
- MouseScroll,
-
- // PlatformWheelEvent
- Wheel,
-
- // PlatformGestureEvent
- GestureScrollBegin,
- GestureScrollEnd,
- GestureScrollUpdate,
- GestureScrollUpdateWithoutPropagation,
- GestureTap,
- GestureTapUnconfirmed,
- GestureTapDown,
- GestureTapDownCancel,
- GestureTwoFingerTap,
- GestureLongPress,
- GestureLongTap,
- GesturePinchBegin,
- GesturePinchEnd,
- GesturePinchUpdate,
-
- // PlatformTouchEvent
- TouchStart,
- TouchMove,
- TouchEnd,
- TouchCancel,
- };
-
- enum Modifiers {
- AltKey = 1 << 0,
- CtrlKey = 1 << 1,
- MetaKey = 1 << 2,
- ShiftKey = 1 << 3,
- };
-
- Type type() const { return static_cast<Type>(m_type); }
-
- bool shiftKey() const { return m_modifiers & ShiftKey; }
- bool ctrlKey() const { return m_modifiers & CtrlKey; }
- bool altKey() const { return m_modifiers & AltKey; }
- bool metaKey() const { return m_modifiers & MetaKey; }
-
- unsigned modifiers() const { return m_modifiers; }
-
- double timestamp() const { return m_timestamp; }
-
-protected:
- PlatformEvent()
- : m_type(NoType)
- , m_modifiers(0)
- , m_timestamp(0)
- {
- }
-
- explicit PlatformEvent(Type type)
- : m_type(type)
- , m_modifiers(0)
- , m_timestamp(0)
- {
- }
-
- PlatformEvent(Type type, Modifiers modifiers, double timestamp)
- : m_type(type)
- , m_modifiers(modifiers)
- , m_timestamp(timestamp)
- {
- }
-
- PlatformEvent(Type type, bool shiftKey, bool ctrlKey, bool altKey, bool metaKey, double timestamp)
- : m_type(type)
- , m_modifiers(0)
- , m_timestamp(timestamp)
- {
- if (shiftKey)
- m_modifiers |= ShiftKey;
- if (ctrlKey)
- m_modifiers |= CtrlKey;
- if (altKey)
- m_modifiers |= AltKey;
- if (metaKey)
- m_modifiers |= MetaKey;
- }
-
- // Explicit protected destructor so that people don't accidentally
- // delete a PlatformEvent.
- ~PlatformEvent()
- {
- }
-
- unsigned m_type;
- unsigned m_modifiers;
- double m_timestamp;
-};
-
-} // namespace WebCore
-
-#endif // PlatformEvent_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/PlatformGestureEvent.h b/chromium/third_party/WebKit/Source/core/platform/PlatformGestureEvent.h
deleted file mode 100644
index 42f69b30aa7..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/PlatformGestureEvent.h
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * Copyright (C) 2011 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef PlatformGestureEvent_h
-#define PlatformGestureEvent_h
-
-#include "core/platform/PlatformEvent.h"
-#include "core/platform/graphics/FloatPoint.h"
-#include "core/platform/graphics/IntPoint.h"
-#include "core/platform/graphics/IntSize.h"
-
-namespace WebCore {
-
-class PlatformGestureEvent : public PlatformEvent {
-public:
- PlatformGestureEvent()
- : PlatformEvent(PlatformEvent::GestureScrollBegin)
- , m_deltaX(0)
- , m_deltaY(0)
- {
- }
-
- PlatformGestureEvent(Type type, const IntPoint& position, const IntPoint& globalPosition, double timestamp, float deltaX, float deltaY, bool shiftKey, bool ctrlKey, bool altKey, bool metaKey)
- : PlatformEvent(type, shiftKey, ctrlKey, altKey, metaKey, timestamp)
- , m_position(position)
- , m_globalPosition(globalPosition)
- , m_deltaX(deltaX)
- , m_deltaY(deltaY)
- {
- }
-
- PlatformGestureEvent(Type type, const IntPoint& position, const IntPoint& globalPosition, double timestamp, const IntSize& area, const FloatPoint& delta, bool shiftKey, bool ctrlKey, bool altKey, bool metaKey)
- : PlatformEvent(type, shiftKey, ctrlKey, altKey, metaKey, timestamp)
- , m_position(position)
- , m_globalPosition(globalPosition)
- , m_area(area)
- , m_deltaX(delta.x())
- , m_deltaY(delta.y())
- {
- }
-
- const IntPoint& position() const { return m_position; } // PlatformWindow coordinates.
- const IntPoint& globalPosition() const { return m_globalPosition; } // Screen coordinates.
-
- const IntSize& area() const { return m_area; }
-
- float deltaX() const { return m_deltaX; }
- float deltaY() const { return m_deltaY; }
-
-protected:
- IntPoint m_position;
- IntPoint m_globalPosition;
- IntSize m_area;
- float m_deltaX;
- float m_deltaY;
-};
-
-} // namespace WebCore
-
-#endif // PlatformGestureEvent_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/PlatformInstrumentation.cpp b/chromium/third_party/WebKit/Source/core/platform/PlatformInstrumentation.cpp
deleted file mode 100644
index ce1202bdc2e..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/PlatformInstrumentation.cpp
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/platform/PlatformInstrumentation.h"
-
-namespace WebCore {
-
-const char PlatformInstrumentation::CategoryName[] = "webkit";
-
-const char PlatformInstrumentation::ImageDecodeEvent[] = "Decode Image";
-const char PlatformInstrumentation::ImageResizeEvent[] = "Resize Image";
-
-const char PlatformInstrumentation::ImageTypeArgument[] = "imageType";
-const char PlatformInstrumentation::CachedArgument[] = "cached";
-
-PlatformInstrumentationClient* PlatformInstrumentation::m_client;
-
-PlatformInstrumentationClient::~PlatformInstrumentationClient()
-{
-}
-
-void PlatformInstrumentation::setClient(PlatformInstrumentationClient* client)
-{
- m_client = client;
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/PlatformInstrumentation.h b/chromium/third_party/WebKit/Source/core/platform/PlatformInstrumentation.h
deleted file mode 100644
index 33414fd1fdb..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/PlatformInstrumentation.h
+++ /dev/null
@@ -1,105 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef PlatformInstrumentation_h
-#define PlatformInstrumentation_h
-
-#include "wtf/MainThread.h"
-#include "wtf/text/WTFString.h"
-
-#include "core/platform/chromium/TraceEvent.h"
-
-namespace WebCore {
-
-class PlatformInstrumentationClient {
-public:
- virtual ~PlatformInstrumentationClient();
-
- virtual void willDecodeImage(const String& imageType) = 0;
- virtual void didDecodeImage() = 0;
- virtual void willResizeImage(bool shouldCache) = 0;
- virtual void didResizeImage() = 0;
-};
-
-class PlatformInstrumentation {
-public:
- static const char ImageDecodeEvent[];
- static const char ImageResizeEvent[];
-
- static const char ImageTypeArgument[];
- static const char CachedArgument[];
-
- static void setClient(PlatformInstrumentationClient*);
- static bool hasClient() { return m_client; }
-
- static void willDecodeImage(const String& imageType);
- static void didDecodeImage();
- static void willResizeImage(bool shouldCache);
- static void didResizeImage();
-
-private:
- static const char CategoryName[];
-
- static PlatformInstrumentationClient* m_client;
-};
-
-#define FAST_RETURN_IF_NO_CLIENT_OR_NOT_MAIN_THREAD() if (!m_client || !isMainThread()) return;
-
-inline void PlatformInstrumentation::willDecodeImage(const String& imageType)
-{
- TRACE_EVENT_BEGIN1(CategoryName, ImageDecodeEvent, ImageTypeArgument, TRACE_STR_COPY(imageType.ascii().data()));
- FAST_RETURN_IF_NO_CLIENT_OR_NOT_MAIN_THREAD();
- m_client->willDecodeImage(imageType);
-}
-
-inline void PlatformInstrumentation::didDecodeImage()
-{
- TRACE_EVENT_END0(CategoryName, ImageDecodeEvent);
- FAST_RETURN_IF_NO_CLIENT_OR_NOT_MAIN_THREAD();
- m_client->didDecodeImage();
-}
-
-inline void PlatformInstrumentation::willResizeImage(bool shouldCache)
-{
- TRACE_EVENT_BEGIN1(CategoryName, ImageResizeEvent, CachedArgument, shouldCache);
- FAST_RETURN_IF_NO_CLIENT_OR_NOT_MAIN_THREAD();
- m_client->willResizeImage(shouldCache);
-}
-
-inline void PlatformInstrumentation::didResizeImage()
-{
- TRACE_EVENT_END0(CategoryName, ImageResizeEvent);
- FAST_RETURN_IF_NO_CLIENT_OR_NOT_MAIN_THREAD();
- m_client->didResizeImage();
-}
-
-} // namespace WebCore
-
-#endif // PlatformInstrumentation_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/PlatformKeyboardEvent.h b/chromium/third_party/WebKit/Source/core/platform/PlatformKeyboardEvent.h
deleted file mode 100644
index 4ad6ded9210..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/PlatformKeyboardEvent.h
+++ /dev/null
@@ -1,107 +0,0 @@
-/*
- * Copyright (C) 2004, 2005, 2006 Apple Computer, Inc. All rights reserved.
- * Copyright (C) 2008 Collabora, Ltd. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef PlatformKeyboardEvent_h
-#define PlatformKeyboardEvent_h
-
-#include "core/platform/PlatformEvent.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
- class PlatformKeyboardEvent : public PlatformEvent {
- WTF_MAKE_FAST_ALLOCATED;
- public:
- PlatformKeyboardEvent()
- : PlatformEvent(PlatformEvent::KeyDown)
- , m_windowsVirtualKeyCode(0)
- , m_nativeVirtualKeyCode(0)
- , m_macCharCode(0)
- , m_autoRepeat(false)
- , m_isKeypad(false)
- , m_isSystemKey(false)
- {
- }
-
- PlatformKeyboardEvent(Type type, const String& text, const String& unmodifiedText, const String& keyIdentifier, int windowsVirtualKeyCode, int nativeVirtualKeyCode, int macCharCode, bool isAutoRepeat, bool isKeypad, bool isSystemKey, Modifiers modifiers, double timestamp)
- : PlatformEvent(type, modifiers, timestamp)
- , m_text(text)
- , m_unmodifiedText(unmodifiedText)
- , m_keyIdentifier(keyIdentifier)
- , m_windowsVirtualKeyCode(windowsVirtualKeyCode)
- , m_nativeVirtualKeyCode(nativeVirtualKeyCode)
- , m_macCharCode(macCharCode)
- , m_autoRepeat(isAutoRepeat)
- , m_isKeypad(isKeypad)
- , m_isSystemKey(isSystemKey)
- {
- }
-
- void disambiguateKeyDownEvent(Type);
-
- // Text as as generated by processing a virtual key code with a keyboard layout
- // (in most cases, just a character code, but the layout can emit several
- // characters in a single keypress event on some platforms).
- // This may bear no resemblance to the ultimately inserted text if an input method
- // processes the input.
- // Will be null for KeyUp and RawKeyDown events.
- String text() const { return m_text; }
-
- // Text that would have been generated by the keyboard if no modifiers were pressed
- // (except for Shift); useful for shortcut (accelerator) key handling.
- // Otherwise, same as text().
- String unmodifiedText() const { return m_unmodifiedText; }
-
- String keyIdentifier() const { return m_keyIdentifier; }
-
- // Most compatible Windows virtual key code associated with the event.
- // Zero for Char events.
- int windowsVirtualKeyCode() const { return m_windowsVirtualKeyCode; }
-
- int nativeVirtualKeyCode() const { return m_nativeVirtualKeyCode; }
- int macCharCode() const { return m_macCharCode; }
-
- bool isAutoRepeat() const { return m_autoRepeat; }
- bool isKeypad() const { return m_isKeypad; }
- bool isSystemKey() const { return m_isSystemKey; }
-
- static bool currentCapsLockState();
- static void getCurrentModifierState(bool& shiftKey, bool& ctrlKey, bool& altKey, bool& metaKey);
- protected:
- String m_text;
- String m_unmodifiedText;
- String m_keyIdentifier;
- int m_windowsVirtualKeyCode;
- int m_nativeVirtualKeyCode;
- int m_macCharCode;
- bool m_autoRepeat;
- bool m_isKeypad;
- bool m_isSystemKey;
- };
-
-} // namespace WebCore
-
-#endif // PlatformKeyboardEvent_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/PlatformMouseEvent.h b/chromium/third_party/WebKit/Source/core/platform/PlatformMouseEvent.h
deleted file mode 100644
index f5424613524..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/PlatformMouseEvent.h
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * Copyright (C) 2004, 2005, 2006, 2009 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef PlatformMouseEvent_h
-#define PlatformMouseEvent_h
-
-#include "core/platform/PlatformEvent.h"
-#include "core/platform/graphics/IntPoint.h"
-
-namespace WebCore {
-
- // These button numbers match the ones used in the DOM API, 0 through 2, except for NoButton which isn't specified.
- enum MouseButton { NoButton = -1, LeftButton, MiddleButton, RightButton };
-
- class PlatformMouseEvent : public PlatformEvent {
- public:
- PlatformMouseEvent()
- : PlatformEvent(PlatformEvent::MouseMoved)
- , m_button(NoButton)
- , m_clickCount(0)
- , m_modifierFlags(0)
- {
- }
-
- PlatformMouseEvent(const IntPoint& position, const IntPoint& globalPosition, MouseButton button, PlatformEvent::Type type,
- int clickCount, bool shiftKey, bool ctrlKey, bool altKey, bool metaKey, double timestamp)
- : PlatformEvent(type, shiftKey, ctrlKey, altKey, metaKey, timestamp)
- , m_position(position)
- , m_globalPosition(globalPosition)
- , m_button(button)
- , m_clickCount(clickCount)
- , m_modifierFlags(0)
- {
- }
-
- const IntPoint& position() const { return m_position; }
- const IntPoint& globalPosition() const { return m_globalPosition; }
- const IntPoint& movementDelta() const { return m_movementDelta; }
-
- MouseButton button() const { return m_button; }
- int clickCount() const { return m_clickCount; }
- unsigned modifierFlags() const { return m_modifierFlags; }
-
- protected:
- IntPoint m_position;
- IntPoint m_globalPosition;
- IntPoint m_movementDelta;
- MouseButton m_button;
- int m_clickCount;
- unsigned m_modifierFlags;
- };
-
-} // namespace WebCore
-
-#endif // PlatformMouseEvent_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/PlatformScreen.h b/chromium/third_party/WebKit/Source/core/platform/PlatformScreen.h
deleted file mode 100644
index 096f026abf5..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/PlatformScreen.h
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Copyright (C) 2006 Apple Computer, Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef PlatformScreen_h
-#define PlatformScreen_h
-
-#include "core/platform/graphics/FloatRect.h"
-#include "wtf/Forward.h"
-#include "wtf/RefPtr.h"
-
-typedef uint32_t PlatformDisplayID;
-
-typedef WTF::Vector<char> ColorProfile;
-
-namespace WebCore {
-
- class FloatRect;
- class Widget;
-
- int screenDepth(Widget*);
- int screenDepthPerComponent(Widget*);
- bool screenIsMonochrome(Widget*);
-
- FloatRect screenRect(Widget*);
- FloatRect screenAvailableRect(Widget*);
- void screenColorProfile(ColorProfile&);
-} // namespace WebCore
-
-#endif // PlatformScreen_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/PlatformSpeechSynthesisUtterance.cpp b/chromium/third_party/WebKit/Source/core/platform/PlatformSpeechSynthesisUtterance.cpp
deleted file mode 100644
index a137c588614..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/PlatformSpeechSynthesisUtterance.cpp
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright (C) 2013 Apple Computer, Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/PlatformSpeechSynthesisUtterance.h"
-
-namespace WebCore {
-
-PassRefPtr<PlatformSpeechSynthesisUtterance> PlatformSpeechSynthesisUtterance::create(PlatformSpeechSynthesisUtteranceClient* client)
-{
- return adoptRef(new PlatformSpeechSynthesisUtterance(client));
-}
-
-PlatformSpeechSynthesisUtterance::PlatformSpeechSynthesisUtterance(PlatformSpeechSynthesisUtteranceClient* client)
- : m_client(client)
- , m_volume(1.0f)
- , m_rate(1.0f)
- , m_pitch(1.0f)
-{
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/PlatformSpeechSynthesisUtterance.h b/chromium/third_party/WebKit/Source/core/platform/PlatformSpeechSynthesisUtterance.h
deleted file mode 100644
index 7d1dee271fb..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/PlatformSpeechSynthesisUtterance.h
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * Copyright (C) 2013 Apple Computer, Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef PlatformSpeechSynthesisUtterance_h
-#define PlatformSpeechSynthesisUtterance_h
-
-#include "core/platform/PlatformSpeechSynthesisVoice.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class PlatformSpeechSynthesisUtteranceClient {
-public:
- // Implement methods as needed.
-protected:
- virtual ~PlatformSpeechSynthesisUtteranceClient() { }
-};
-
-class PlatformSpeechSynthesisUtterance : public RefCounted<PlatformSpeechSynthesisUtterance> {
-public:
- static PassRefPtr<PlatformSpeechSynthesisUtterance> create(PlatformSpeechSynthesisUtteranceClient*);
-
- const String& text() const { return m_text; }
- void setText(const String& text) { m_text = text; }
-
- const String& lang() const { return m_lang; }
- void setLang(const String& lang) { m_lang = lang; }
-
- PlatformSpeechSynthesisVoice* voice() const { return m_voice.get(); }
- void setVoice(PlatformSpeechSynthesisVoice* voice) { m_voice = voice; }
-
- // Range = [0, 1] where 1 is the default.
- float volume() const { return m_volume; }
- void setVolume(float volume) { m_volume = std::max(std::min(1.0f, volume), 0.0f); }
-
- // Range = [0.1, 10] where 1 is the default.
- float rate() const { return m_rate; }
- void setRate(float rate) { m_rate = std::max(std::min(10.0f, rate), 0.1f); }
-
- // Range = [0, 2] where 1 is the default.
- float pitch() const { return m_pitch; }
- void setPitch(float pitch) { m_pitch = std::max(std::min(2.0f, pitch), 0.0f); }
-
- double startTime() const { return m_startTime; }
- void setStartTime(double startTime) { m_startTime = startTime; }
-
- PlatformSpeechSynthesisUtteranceClient* client() const { return m_client; }
- void setClient(PlatformSpeechSynthesisUtteranceClient* client) { m_client = client; }
-
-private:
- explicit PlatformSpeechSynthesisUtterance(PlatformSpeechSynthesisUtteranceClient*);
-
- PlatformSpeechSynthesisUtteranceClient* m_client;
- String m_text;
- String m_lang;
- RefPtr<PlatformSpeechSynthesisVoice> m_voice;
- float m_volume;
- float m_rate;
- float m_pitch;
- double m_startTime;
-};
-
-} // namespace WebCore
-
-#endif // PlatformSpeechSynthesisUtterance_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/PlatformSpeechSynthesisVoice.cpp b/chromium/third_party/WebKit/Source/core/platform/PlatformSpeechSynthesisVoice.cpp
deleted file mode 100644
index 39941d156fc..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/PlatformSpeechSynthesisVoice.cpp
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright (C) 2013 Apple Computer, Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/PlatformSpeechSynthesisVoice.h"
-
-namespace WebCore {
-
-PassRefPtr<PlatformSpeechSynthesisVoice> PlatformSpeechSynthesisVoice::create(const String& voiceURI, const String& name, const String& lang, bool localService, bool isDefault)
-{
- return adoptRef(new PlatformSpeechSynthesisVoice(voiceURI, name, lang, localService, isDefault));
-}
-
-PassRefPtr<PlatformSpeechSynthesisVoice> PlatformSpeechSynthesisVoice::create()
-{
- return adoptRef(new PlatformSpeechSynthesisVoice());
-}
-
-PlatformSpeechSynthesisVoice::PlatformSpeechSynthesisVoice(const String& voiceURI, const String& name, const String& lang, bool localService, bool isDefault)
- : m_voiceURI(voiceURI)
- , m_name(name)
- , m_lang(lang)
- , m_localService(localService)
- , m_default(isDefault)
-{
-}
-
-PlatformSpeechSynthesisVoice::PlatformSpeechSynthesisVoice()
- : m_localService(false)
- , m_default(false)
-{
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/PlatformSpeechSynthesisVoice.h b/chromium/third_party/WebKit/Source/core/platform/PlatformSpeechSynthesisVoice.h
deleted file mode 100644
index b475a2c2693..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/PlatformSpeechSynthesisVoice.h
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Copyright (C) 2013 Apple Computer, Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef PlatformSpeechSynthesisVoice_h
-#define PlatformSpeechSynthesisVoice_h
-
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class PlatformSpeechSynthesisVoice : public RefCounted<PlatformSpeechSynthesisVoice> {
-public:
- static PassRefPtr<PlatformSpeechSynthesisVoice> create(const String& voiceURI, const String& name, const String& lang, bool localService, bool isDefault);
- static PassRefPtr<PlatformSpeechSynthesisVoice> create();
-
- const String& voiceURI() const { return m_voiceURI; }
- void setVoiceURI(const String& voiceURI) { m_voiceURI = voiceURI; }
-
- const String& name() const { return m_name; }
- void setName(const String& name) { m_name = name; }
-
- const String& lang() const { return m_lang; }
- void setLang(const String& lang) { m_lang = lang; }
-
- bool localService() const { return m_localService; }
- void setLocalService(bool localService) { m_localService = localService; }
-
- bool isDefault() const { return m_default; }
- void setIsDefault(bool isDefault) { m_default = isDefault; }
-
-private:
- PlatformSpeechSynthesisVoice(const String& voiceURI, const String& name, const String& lang, bool localService, bool isDefault);
- PlatformSpeechSynthesisVoice();
-
- String m_voiceURI;
- String m_name;
- String m_lang;
- bool m_localService;
- bool m_default;
-};
-
-} // namespace WebCore
-
-#endif // PlatformSpeechSynthesisVoice_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/PlatformSpeechSynthesizer.cpp b/chromium/third_party/WebKit/Source/core/platform/PlatformSpeechSynthesizer.cpp
deleted file mode 100644
index 9200480a65b..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/PlatformSpeechSynthesizer.cpp
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright (C) 2013 Apple Computer, Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/PlatformSpeechSynthesizer.h"
-
-namespace WebCore {
-
-PassOwnPtr<PlatformSpeechSynthesizer> PlatformSpeechSynthesizer::create(PlatformSpeechSynthesizerClient* client)
-{
- OwnPtr<PlatformSpeechSynthesizer> synthesizer = adoptPtr(new PlatformSpeechSynthesizer(client));
- synthesizer->initializeVoiceList();
- return synthesizer.release();
-}
-
-void PlatformSpeechSynthesizer::setVoiceList(Vector<RefPtr<PlatformSpeechSynthesisVoice> >& voices)
-{
- m_voiceList = voices;
-}
-
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/PlatformSpeechSynthesizer.h b/chromium/third_party/WebKit/Source/core/platform/PlatformSpeechSynthesizer.h
deleted file mode 100644
index 3d1b81589a9..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/PlatformSpeechSynthesizer.h
+++ /dev/null
@@ -1,90 +0,0 @@
-/*
- * Copyright (C) 2013 Apple Computer, Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef PlatformSpeechSynthesizer_h
-#define PlatformSpeechSynthesizer_h
-
-#include "core/platform/PlatformSpeechSynthesisVoice.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/Vector.h"
-
-namespace WebKit {
-class WebSpeechSynthesizer;
-class WebSpeechSynthesizerClient;
-}
-
-namespace WebCore {
-
-enum SpeechBoundary {
- SpeechWordBoundary,
- SpeechSentenceBoundary
-};
-
-class PlatformSpeechSynthesisUtterance;
-
-class PlatformSpeechSynthesizerClient {
-public:
- virtual void didStartSpeaking(PassRefPtr<PlatformSpeechSynthesisUtterance>) = 0;
- virtual void didFinishSpeaking(PassRefPtr<PlatformSpeechSynthesisUtterance>) = 0;
- virtual void didPauseSpeaking(PassRefPtr<PlatformSpeechSynthesisUtterance>) = 0;
- virtual void didResumeSpeaking(PassRefPtr<PlatformSpeechSynthesisUtterance>) = 0;
- virtual void speakingErrorOccurred(PassRefPtr<PlatformSpeechSynthesisUtterance>) = 0;
- virtual void boundaryEventOccurred(PassRefPtr<PlatformSpeechSynthesisUtterance>, SpeechBoundary, unsigned charIndex) = 0;
- virtual void voicesDidChange() = 0;
-protected:
- virtual ~PlatformSpeechSynthesizerClient() { }
-};
-
-class PlatformSpeechSynthesizer {
-public:
- static PassOwnPtr<PlatformSpeechSynthesizer> create(PlatformSpeechSynthesizerClient*);
-
- virtual ~PlatformSpeechSynthesizer();
-
- const Vector<RefPtr<PlatformSpeechSynthesisVoice> >& voiceList() const { return m_voiceList; }
- virtual void speak(PassRefPtr<PlatformSpeechSynthesisUtterance>);
- virtual void pause();
- virtual void resume();
- virtual void cancel();
-
- PlatformSpeechSynthesizerClient* client() const { return m_speechSynthesizerClient; }
-
- void setVoiceList(Vector<RefPtr<PlatformSpeechSynthesisVoice> >&);
-
-protected:
- virtual void initializeVoiceList();
- explicit PlatformSpeechSynthesizer(PlatformSpeechSynthesizerClient*);
- Vector<RefPtr<PlatformSpeechSynthesisVoice> > m_voiceList;
-
-private:
- PlatformSpeechSynthesizerClient* m_speechSynthesizerClient;
-
- OwnPtr<WebKit::WebSpeechSynthesizer> m_webSpeechSynthesizer;
- OwnPtr<WebKit::WebSpeechSynthesizerClient> m_webSpeechSynthesizerClient;
-};
-
-} // namespace WebCore
-
-#endif // PlatformSpeechSynthesizer_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/PlatformTouchEvent.h b/chromium/third_party/WebKit/Source/core/platform/PlatformTouchEvent.h
deleted file mode 100644
index d3b1eef00c9..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/PlatformTouchEvent.h
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies)
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#ifndef PlatformTouchEvent_h
-#define PlatformTouchEvent_h
-
-#include "core/platform/PlatformEvent.h"
-#include "core/platform/PlatformTouchPoint.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-
-class PlatformTouchEvent : public PlatformEvent {
-public:
- PlatformTouchEvent()
- : PlatformEvent(PlatformEvent::TouchStart)
- {
- }
-
- const Vector<PlatformTouchPoint>& touchPoints() const { return m_touchPoints; }
-
-protected:
- Vector<PlatformTouchPoint> m_touchPoints;
-};
-
-}
-
-#endif // PlatformTouchEvent_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/PlatformTouchPoint.h b/chromium/third_party/WebKit/Source/core/platform/PlatformTouchPoint.h
deleted file mode 100644
index f6609a8ab8c..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/PlatformTouchPoint.h
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies)
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#ifndef PlatformTouchPoint_h
-#define PlatformTouchPoint_h
-
-#include "core/platform/graphics/IntPoint.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-class PlatformTouchEvent;
-
-class PlatformTouchPoint {
-public:
- enum State {
- TouchReleased,
- TouchPressed,
- TouchMoved,
- TouchStationary,
- TouchCancelled,
- TouchStateEnd // Placeholder: must remain the last item.
- };
-
- // This is necessary for us to be able to build synthetic events.
- PlatformTouchPoint()
- : m_id(0)
- , m_radiusY(0)
- , m_radiusX(0)
- , m_rotationAngle(0)
- , m_force(0)
- {
- }
-
- unsigned id() const { return m_id; }
- State state() const { return m_state; }
- IntPoint screenPos() const { return m_screenPos; }
- IntPoint pos() const { return m_pos; }
- int radiusX() const { return m_radiusX; }
- int radiusY() const { return m_radiusY; }
- float rotationAngle() const { return m_rotationAngle; }
- float force() const { return m_force; }
-
-protected:
- unsigned m_id;
- State m_state;
- IntPoint m_screenPos;
- IntPoint m_pos;
- int m_radiusY;
- int m_radiusX;
- float m_rotationAngle;
- float m_force;
-};
-
-}
-
-#endif // PlatformTouchPoint_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/PlatformWheelEvent.h b/chromium/third_party/WebKit/Source/core/platform/PlatformWheelEvent.h
deleted file mode 100644
index 894c776154f..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/PlatformWheelEvent.h
+++ /dev/null
@@ -1,160 +0,0 @@
-/*
- * Copyright (C) 2004, 2005, 2006, 2009 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef PlatformWheelEvent_h
-#define PlatformWheelEvent_h
-
-#include "core/platform/PlatformEvent.h"
-#include "core/platform/graphics/IntPoint.h"
-
-namespace WebCore {
-
- class FloatPoint;
- class FloatSize;
-
- // Wheel events come in two flavors:
- // The ScrollByPixelWheelEvent is a fine-grained event that specifies the precise number of pixels to scroll. It is sent directly by MacBook touchpads on OS X,
- // and synthesized in other cases where platforms generate line-by-line scrolling events.
- // The ScrollByPageWheelEvent indicates that the wheel event should scroll an entire page. In this case WebCore's built in paging behavior is used to page
- // up and down (you get the same behavior as if the user was clicking in a scrollbar track to page up or page down).
- enum PlatformWheelEventGranularity {
- ScrollByPageWheelEvent,
- ScrollByPixelWheelEvent,
- };
-
-#if OS(MACOSX)
- enum PlatformWheelEventPhase {
- PlatformWheelEventPhaseNone = 0,
- PlatformWheelEventPhaseBegan = 1 << 0,
- PlatformWheelEventPhaseStationary = 1 << 1,
- PlatformWheelEventPhaseChanged = 1 << 2,
- PlatformWheelEventPhaseEnded = 1 << 3,
- PlatformWheelEventPhaseCancelled = 1 << 4,
- PlatformWheelEventPhaseMayBegin = 1 << 5,
- };
-#endif
-
- class PlatformWheelEvent : public PlatformEvent {
- public:
- PlatformWheelEvent()
- : PlatformEvent(PlatformEvent::Wheel)
- , m_deltaX(0)
- , m_deltaY(0)
- , m_wheelTicksX(0)
- , m_wheelTicksY(0)
- , m_granularity(ScrollByPixelWheelEvent)
- , m_directionInvertedFromDevice(false)
- , m_hasPreciseScrollingDeltas(false)
-#if OS(MACOSX)
- , m_phase(PlatformWheelEventPhaseNone)
- , m_momentumPhase(PlatformWheelEventPhaseNone)
- , m_scrollCount(0)
- , m_unacceleratedScrollingDeltaX(0)
- , m_unacceleratedScrollingDeltaY(0)
-#endif
- {
- }
-
- PlatformWheelEvent(IntPoint position, IntPoint globalPosition, float deltaX, float deltaY, float wheelTicksX, float wheelTicksY, PlatformWheelEventGranularity granularity, bool shiftKey, bool ctrlKey, bool altKey, bool metaKey)
- : PlatformEvent(PlatformEvent::Wheel, shiftKey, ctrlKey, altKey, metaKey, 0)
- , m_position(position)
- , m_globalPosition(globalPosition)
- , m_deltaX(deltaX)
- , m_deltaY(deltaY)
- , m_wheelTicksX(wheelTicksX)
- , m_wheelTicksY(wheelTicksY)
- , m_granularity(granularity)
- , m_directionInvertedFromDevice(false)
- , m_hasPreciseScrollingDeltas(false)
-#if OS(MACOSX)
- , m_phase(PlatformWheelEventPhaseNone)
- , m_momentumPhase(PlatformWheelEventPhaseNone)
- , m_scrollCount(0)
- , m_unacceleratedScrollingDeltaX(0)
- , m_unacceleratedScrollingDeltaY(0)
-#endif
- {
- }
-
- PlatformWheelEvent copyTurningVerticalTicksIntoHorizontalTicks() const
- {
- PlatformWheelEvent copy = *this;
-
- copy.m_deltaX = copy.m_deltaY;
- copy.m_deltaY = 0;
- copy.m_wheelTicksX = copy.m_wheelTicksY;
- copy.m_wheelTicksY = 0;
-
- return copy;
- }
-
- const IntPoint& position() const { return m_position; } // PlatformWindow coordinates.
- const IntPoint& globalPosition() const { return m_globalPosition; } // Screen coordinates.
-
- float deltaX() const { return m_deltaX; }
- float deltaY() const { return m_deltaY; }
-
- float wheelTicksX() const { return m_wheelTicksX; }
- float wheelTicksY() const { return m_wheelTicksY; }
-
- PlatformWheelEventGranularity granularity() const { return m_granularity; }
-
- bool directionInvertedFromDevice() const { return m_directionInvertedFromDevice; }
-
- bool hasPreciseScrollingDeltas() const { return m_hasPreciseScrollingDeltas; }
- void setHasPreciseScrollingDeltas(bool b) { m_hasPreciseScrollingDeltas = b; }
-#if OS(MACOSX)
- PlatformWheelEventPhase phase() const { return m_phase; }
- PlatformWheelEventPhase momentumPhase() const { return m_momentumPhase; }
- unsigned scrollCount() const { return m_scrollCount; }
- float unacceleratedScrollingDeltaX() const { return m_unacceleratedScrollingDeltaX; }
- float unacceleratedScrollingDeltaY() const { return m_unacceleratedScrollingDeltaY; }
- bool useLatchedEventNode() const { return m_momentumPhase == PlatformWheelEventPhaseBegan || m_momentumPhase == PlatformWheelEventPhaseChanged; }
-#else
- bool useLatchedEventNode() const { return false; }
-#endif
-
- protected:
- IntPoint m_position;
- IntPoint m_globalPosition;
- float m_deltaX;
- float m_deltaY;
- float m_wheelTicksX;
- float m_wheelTicksY;
- PlatformWheelEventGranularity m_granularity;
- bool m_directionInvertedFromDevice;
- bool m_hasPreciseScrollingDeltas;
-#if OS(MACOSX)
- PlatformWheelEventPhase m_phase;
- PlatformWheelEventPhase m_momentumPhase;
- unsigned m_scrollCount;
- float m_unacceleratedScrollingDeltaX;
- float m_unacceleratedScrollingDeltaY;
-#endif
- };
-
-} // namespace WebCore
-
-#endif // PlatformWheelEvent_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/PopupMenu.h b/chromium/third_party/WebKit/Source/core/platform/PopupMenu.h
deleted file mode 100644
index e0938dace29..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/PopupMenu.h
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#ifndef PopupMenu_h
-#define PopupMenu_h
-
-#include "wtf/RefCounted.h"
-
-namespace WebCore {
-
-class FloatQuad;
-class FrameView;
-class IntRect;
-class IntSize;
-
-class PopupMenu : public RefCounted<PopupMenu> {
-public:
- virtual ~PopupMenu() { }
- virtual void show(const FloatQuad& controlPosition, const IntSize& controlSize, int index) = 0;
- virtual void hide() = 0;
- virtual void updateFromElement() = 0;
- virtual void disconnectClient() = 0;
-};
-
-}
-
-#endif // PopupMenu_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/PopupMenuClient.h b/chromium/third_party/WebKit/Source/core/platform/PopupMenuClient.h
deleted file mode 100644
index ed41b514346..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/PopupMenuClient.h
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
- * Copyright (C) 2006 Apple Computer, Inc.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#ifndef PopupMenuClient_h
-#define PopupMenuClient_h
-
-#include "core/platform/LayoutUnit.h"
-#include "core/platform/PopupMenuStyle.h"
-#include "core/platform/ScrollTypes.h"
-#include "wtf/Forward.h"
-
-namespace WebCore {
-
-class Color;
-class FontSelector;
-class HostWindow;
-class Scrollbar;
-class ScrollableArea;
-
-class PopupMenuClient {
-public:
- virtual ~PopupMenuClient() {}
- virtual void valueChanged(unsigned listIndex, bool fireEvents = true) = 0;
- virtual void selectionChanged(unsigned listIndex, bool fireEvents = true) = 0;
- virtual void selectionCleared() = 0;
-
- virtual String itemText(unsigned listIndex) const = 0;
- virtual String itemLabel(unsigned listIndex) const = 0;
- virtual String itemIcon(unsigned listIndex) const = 0;
- virtual String itemToolTip(unsigned listIndex) const = 0;
- virtual String itemAccessibilityText(unsigned listIndex) const = 0;
- virtual bool itemIsEnabled(unsigned listIndex) const = 0;
- virtual PopupMenuStyle itemStyle(unsigned listIndex) const = 0;
- virtual PopupMenuStyle menuStyle() const = 0;
- virtual int clientInsetLeft() const = 0;
- virtual int clientInsetRight() const = 0;
- virtual LayoutUnit clientPaddingLeft() const = 0;
- virtual LayoutUnit clientPaddingRight() const = 0;
- virtual int listSize() const = 0;
- virtual int selectedIndex() const = 0;
- virtual void popupDidHide() = 0;
- virtual bool itemIsSeparator(unsigned listIndex) const = 0;
- virtual bool itemIsLabel(unsigned listIndex) const = 0;
- virtual bool itemIsSelected(unsigned listIndex) const = 0;
- virtual bool valueShouldChangeOnHotTrack() const = 0;
- virtual void setTextFromItem(unsigned listIndex) = 0;
-
- virtual void listBoxSelectItem(int /*listIndex*/, bool /*allowMultiplySelections*/, bool /*shift*/, bool /*fireOnChangeNow*/ = true) { ASSERT_NOT_REACHED(); }
- virtual bool multiple() const
- {
- ASSERT_NOT_REACHED();
- return false;
- }
-
- virtual FontSelector* fontSelector() const = 0;
- virtual HostWindow* hostWindow() const = 0;
-
- virtual PassRefPtr<Scrollbar> createScrollbar(ScrollableArea*, ScrollbarOrientation, ScrollbarControlSize) = 0;
-};
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/PopupMenuStyle.h b/chromium/third_party/WebKit/Source/core/platform/PopupMenuStyle.h
deleted file mode 100644
index 63ea3efcce3..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/PopupMenuStyle.h
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * Copyright (C) 2008, 2011 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef PopupMenuStyle_h
-#define PopupMenuStyle_h
-
-#include "core/platform/Length.h"
-#include "core/platform/graphics/Color.h"
-#include "core/platform/graphics/Font.h"
-#include "core/platform/text/TextDirection.h"
-
-namespace WebCore {
-
-class PopupMenuStyle {
-public:
- enum PopupMenuType { SelectPopup, AutofillPopup };
- enum BackgroundColorType { DefaultBackgroundColor, CustomBackgroundColor };
- PopupMenuStyle(const Color& foreground, const Color& background, const Font& font, bool visible, bool isDisplayNone, Length textIndent, TextDirection textDirection, bool hasTextDirectionOverride, BackgroundColorType backgroundColorType = DefaultBackgroundColor, PopupMenuType menuType = SelectPopup)
- : m_foregroundColor(foreground)
- , m_backgroundColor(background)
- , m_font(font)
- , m_visible(visible)
- , m_isDisplayNone(isDisplayNone)
- , m_textIndent(textIndent)
- , m_textDirection(textDirection)
- , m_hasTextDirectionOverride(hasTextDirectionOverride)
- , m_backgroundColorType(backgroundColorType)
- , m_menuType(menuType)
- {
- }
-
- const Color& foregroundColor() const { return m_foregroundColor; }
- const Color& backgroundColor() const { return m_backgroundColor; }
- const Font& font() const { return m_font; }
- bool isVisible() const { return m_visible; }
- bool isDisplayNone() const { return m_isDisplayNone; }
- Length textIndent() const { return m_textIndent; }
- TextDirection textDirection() const { return m_textDirection; }
- bool hasTextDirectionOverride() const { return m_hasTextDirectionOverride; }
- BackgroundColorType backgroundColorType() const { return m_backgroundColorType; }
- PopupMenuType menuType() const { return m_menuType; }
-private:
- Color m_foregroundColor;
- Color m_backgroundColor;
- Font m_font;
- bool m_visible;
- bool m_isDisplayNone;
- Length m_textIndent;
- TextDirection m_textDirection;
- bool m_hasTextDirectionOverride;
- BackgroundColorType m_backgroundColorType;
- PopupMenuType m_menuType;
-};
-
-} // namespace WebCore
-
-#endif // PopupMenuStyle_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/PrerenderClient.h b/chromium/third_party/WebKit/Source/core/platform/PrerenderClient.h
deleted file mode 100644
index 989d75fd641..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/PrerenderClient.h
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-#ifndef PrerenderClient_h
-#define PrerenderClient_h
-
-namespace WebCore {
-
-class PrerenderClient {
-public:
- virtual ~PrerenderClient() { }
-
- virtual void didStartPrerender() = 0;
- virtual void didStopPrerender() = 0;
- virtual void didSendLoadForPrerender() = 0;
- virtual void didSendDOMContentLoadedForPrerender() = 0;
-};
-
-}
-
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/PrerenderHandle.h b/chromium/third_party/WebKit/Source/core/platform/PrerenderHandle.h
deleted file mode 100644
index 90dd511be6e..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/PrerenderHandle.h
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-#ifndef PrerenderHandle_h
-#define PrerenderHandle_h
-
-#include "weborigin/ReferrerPolicy.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/RefPtr.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class KURL;
-class Prerender;
-class PrerenderClient;
-
-class PrerenderHandle : public RefCounted<PrerenderHandle> {
- WTF_MAKE_NONCOPYABLE(PrerenderHandle);
-public:
- static PassRefPtr<PrerenderHandle> create(PrerenderClient*, const KURL&, const String& referrer, ReferrerPolicy);
- ~PrerenderHandle();
-
- Prerender* prerender();
-
- void removeClient();
-
- // A prerender link element is added when it is inserted into a document.
- void add();
-
- // A prerender is abandoned when it's navigated away from. This is is a weaker signal
- // than cancel(), since the launcher hasn't indicated that the prerender isn't wanted,
- // and we may end up using it after, for instance, a short redirect chain.
- void abandon();
-
- // A prerender is canceled when it is removed from a document.
- void cancel();
-
- // A prerender is suspended along with the DOM containing its linkloader & prerenderer.
- void suspend();
- void resume();
-
- const KURL& url() const;
- const String& referrer() const;
- ReferrerPolicy referrerPolicy() const;
-
-private:
- PrerenderHandle(PrerenderClient*, const KURL&, const String& referrer, ReferrerPolicy);
-
- RefPtr<Prerender> m_prerender;
-};
-
-} // namespace WebCore
-
-#endif // PrerenderHandle_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/PurgeableBuffer.cpp b/chromium/third_party/WebKit/Source/core/platform/PurgeableBuffer.cpp
deleted file mode 100644
index a5811381d4d..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/PurgeableBuffer.cpp
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- * Copyright (C) 2013 Google, Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY GOOGLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GOOGLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/PurgeableBuffer.h"
-
-#include "public/platform/Platform.h"
-#include "public/platform/WebDiscardableMemory.h"
-
-#include <string.h>
-
-namespace WebCore {
-
-// WebDiscardableMemory allocations are a limited resource. We only use them
-// when there's a reasonable amount of memory to be saved by the OS discarding
-// the memory.
-static size_t minimumSize = 4 * 4096;
-
-PassOwnPtr<PurgeableBuffer> PurgeableBuffer::create(const char* data, size_t size)
-{
- if (size < minimumSize)
- return nullptr;
-
- OwnPtr<WebKit::WebDiscardableMemory> memory = adoptPtr(WebKit::Platform::current()->allocateAndLockDiscardableMemory(size));
- if (!memory)
- return nullptr;
-
- return adoptPtr(new PurgeableBuffer(memory.release(), data, size));
-}
-
-PurgeableBuffer::~PurgeableBuffer()
-{
- if (m_state == Locked)
- m_memory->unlock();
-}
-
-const char* PurgeableBuffer::data() const
-{
- ASSERT(m_state == Locked);
- return static_cast<const char*>(m_memory->data());
-}
-
-bool PurgeableBuffer::wasPurged() const
-{
- return m_state == Purged;
-}
-
-bool PurgeableBuffer::lock()
-{
- ASSERT(m_state == Unlocked);
- if (!m_memory->lock()) {
- m_state = Purged;
- m_memory = nullptr;
- return false;
- }
- m_state = Locked;
- return true;
-}
-
-void PurgeableBuffer::unlock()
-{
- ASSERT(m_state == Locked);
- m_memory->unlock();
- m_state = Unlocked;
-}
-
-PurgeableBuffer::PurgeableBuffer(PassOwnPtr<WebKit::WebDiscardableMemory> memory, const char* data, size_t size)
- : m_memory(memory)
- , m_size(size)
- , m_state(Locked)
-{
- memcpy(m_memory->data(), data, size);
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/PurgeableBuffer.h b/chromium/third_party/WebKit/Source/core/platform/PurgeableBuffer.h
deleted file mode 100644
index 4b5fc2edfc7..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/PurgeableBuffer.h
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Copyright (C) 2008, 2010 Apple Inc. All Rights Reserved.
- * Copyright (C) 2013 Google Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef PurgeableBuffer_h
-#define PurgeableBuffer_h
-
-#include "wtf/OwnPtr.h"
-#include "wtf/PassOwnPtr.h"
-
-namespace WebKit {
-class WebDiscardableMemory;
-}
-
-namespace WebCore {
-
-class PurgeableBuffer {
- WTF_MAKE_NONCOPYABLE(PurgeableBuffer);
-public:
- static PassOwnPtr<PurgeableBuffer> create(const char* data, size_t);
- ~PurgeableBuffer();
-
- // Call lock and check the return value before accessing the data.
- const char* data() const;
- size_t size() const { return m_size; }
-
- bool isPurgeable() const { return m_state != Locked; }
- bool wasPurged() const;
-
- bool lock();
- void unlock();
-
-private:
- enum State {
- Locked,
- Unlocked,
- Purged
- };
-
- PurgeableBuffer(PassOwnPtr<WebKit::WebDiscardableMemory>, const char* data, size_t);
-
- OwnPtr<WebKit::WebDiscardableMemory> m_memory;
- size_t m_size;
- State m_state;
-};
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/RefCountedSupplement.h b/chromium/third_party/WebKit/Source/core/platform/RefCountedSupplement.h
deleted file mode 100644
index 985c81fbbf7..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/RefCountedSupplement.h
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * Copyright (C) 2012 Google, Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef RefCountedSupplement_h
-#define RefCountedSupplement_h
-
-#include "core/platform/Supplementable.h"
-#include "wtf/RefCounted.h"
-#include "wtf/RefPtr.h"
-
-namespace WebCore {
-
-template<class T, class S>
-class RefCountedSupplement : public RefCounted<S> {
-public:
- typedef RefCountedSupplement<T, S> ThisType;
-
- virtual ~RefCountedSupplement() { }
- virtual void hostDestroyed() { }
-
- class Wrapper : public Supplement<T> {
- public:
- explicit Wrapper(PassRefPtr<ThisType> wrapped) : m_wrapped(wrapped) { }
- virtual ~Wrapper() { m_wrapped->hostDestroyed(); }
-#if !ASSERT_DISABLED || defined(ADDRESS_SANITIZER)
- virtual bool isRefCountedWrapper() const OVERRIDE { return true; }
-#endif
- ThisType* wrapped() const { return m_wrapped.get(); }
- private:
-
- RefPtr<ThisType> m_wrapped;
- };
-
- static void provideTo(Supplementable<T>* host, const char* key, PassRefPtr<ThisType> supplement)
- {
- host->provideSupplement(key, adoptPtr(new Wrapper(supplement)));
- }
-
- static ThisType* from(Supplementable<T>* host, const char* key)
- {
- Supplement<T>* found = host->requireSupplement(key);
- if (!found)
- return 0;
- ASSERT_WITH_SECURITY_IMPLICATION(found->isRefCountedWrapper());
- return static_cast<Wrapper*>(found)->wrapped();
- }
-};
-
-} // namespace WebCore
-
-#endif // RefCountedSupplement_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/SSLKeyGenerator.h b/chromium/third_party/WebKit/Source/core/platform/SSLKeyGenerator.h
deleted file mode 100644
index 9ab52cca0b2..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/SSLKeyGenerator.h
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Copyright (C) 2003, 2006 Apple Computer, Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SSLKeyGenerator_h
-#define SSLKeyGenerator_h
-
-#include "wtf/Vector.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
- class KURL;
-
- // Returns strings representing key sizes that may be used
- // for the <keygen> tag. The first string is displayed as the default
- // key size in the <keygen> menu.
- void getSupportedKeySizes(Vector<String>& sizes);
-
- // This function handles the <keygen> tag in form elements.
- // Returns a signed copy of the combined challenge string and public
- // key (from a newly generated key pair).
- String signedPublicKeyAndChallengeString(unsigned keySizeIndex, const String& challengeString, const KURL&);
-
-} // namespace WebCore
-
-#endif // SSLKeyGenerator_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/ScrollAnimator.cpp b/chromium/third_party/WebKit/Source/core/platform/ScrollAnimator.cpp
deleted file mode 100644
index 3be5c1387a6..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/ScrollAnimator.cpp
+++ /dev/null
@@ -1,152 +0,0 @@
-/*
- * Copyright (c) 2010, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/ScrollAnimator.h"
-
-#include <algorithm>
-#include "core/platform/PlatformWheelEvent.h"
-#include "core/platform/ScrollableArea.h"
-#include "core/platform/graphics/FloatPoint.h"
-#include "wtf/PassOwnPtr.h"
-
-using namespace std;
-
-namespace WebCore {
-
-ScrollAnimator::ScrollAnimator(ScrollableArea* scrollableArea)
- : m_scrollableArea(scrollableArea)
- , m_currentPosX(0)
- , m_currentPosY(0)
-{
-}
-
-ScrollAnimator::~ScrollAnimator()
-{
-}
-
-bool ScrollAnimator::scroll(ScrollbarOrientation orientation, ScrollGranularity, float step, float multiplier)
-{
- float* currentPos = (orientation == HorizontalScrollbar) ? &m_currentPosX : &m_currentPosY;
- float newPos = clampScrollPosition(orientation, *currentPos + step * multiplier);
- float delta = *currentPos - newPos;
- if (*currentPos == newPos)
- return false;
- *currentPos = newPos;
-
- notifyPositionChanged(orientation == HorizontalScrollbar ? FloatSize(delta, 0) : FloatSize(0, delta));
-
- return true;
-}
-
-void ScrollAnimator::scrollToOffsetWithoutAnimation(const FloatPoint& offset)
-{
- FloatSize delta = FloatSize(offset.x() - m_currentPosX, offset.y() - m_currentPosY);
- m_currentPosX = offset.x();
- m_currentPosY = offset.y();
- notifyPositionChanged(delta);
-}
-
-bool ScrollAnimator::handleWheelEvent(const PlatformWheelEvent& e)
-{
- bool canScrollX = m_scrollableArea->userInputScrollable(HorizontalScrollbar);
- bool canScrollY = m_scrollableArea->userInputScrollable(VerticalScrollbar);
-
- // Accept the event if we are scrollable in that direction and can still
- // scroll any further.
- float deltaX = canScrollX ? e.deltaX() : 0;
- float deltaY = canScrollY ? e.deltaY() : 0;
-
- bool handled = false;
-
-#if !OS(MACOSX)
- ScrollGranularity granularity = e.hasPreciseScrollingDeltas() ? ScrollByPrecisePixel : ScrollByPixel;
-#else
- ScrollGranularity granularity = ScrollByPixel;
-#endif
-
- IntSize maxForwardScrollDelta = m_scrollableArea->maximumScrollPosition() - m_scrollableArea->scrollPosition();
- IntSize maxBackwardScrollDelta = m_scrollableArea->scrollPosition() - m_scrollableArea->minimumScrollPosition();
- if ((deltaX < 0 && maxForwardScrollDelta.width() > 0)
- || (deltaX > 0 && maxBackwardScrollDelta.width() > 0)
- || (deltaY < 0 && maxForwardScrollDelta.height() > 0)
- || (deltaY > 0 && maxBackwardScrollDelta.height() > 0)) {
- handled = true;
-
- if (deltaY) {
- if (e.granularity() == ScrollByPageWheelEvent) {
- bool negative = deltaY < 0;
- deltaY = m_scrollableArea->pageStep(VerticalScrollbar);
- if (negative)
- deltaY = -deltaY;
- }
-
- scroll(VerticalScrollbar, granularity, m_scrollableArea->pixelStep(VerticalScrollbar), -deltaY);
- }
-
- if (deltaX) {
- if (e.granularity() == ScrollByPageWheelEvent) {
- bool negative = deltaX < 0;
- deltaX = m_scrollableArea->pageStep(HorizontalScrollbar);
- if (negative)
- deltaX = -deltaX;
- }
-
- scroll(HorizontalScrollbar, granularity, m_scrollableArea->pixelStep(HorizontalScrollbar), -deltaX);
- }
- }
- return handled;
-}
-
-void ScrollAnimator::setCurrentPosition(const FloatPoint& position)
-{
- m_currentPosX = position.x();
- m_currentPosY = position.y();
-}
-
-FloatPoint ScrollAnimator::currentPosition() const
-{
- return FloatPoint(m_currentPosX, m_currentPosY);
-}
-
-void ScrollAnimator::notifyPositionChanged(const FloatSize& delta)
-{
- UNUSED_PARAM(delta);
- m_scrollableArea->setScrollOffsetFromAnimation(IntPoint(m_currentPosX, m_currentPosY));
-}
-
-float ScrollAnimator::clampScrollPosition(ScrollbarOrientation orientation, float pos)
-{
- float maxScrollPos = m_scrollableArea->maximumScrollPosition(orientation);
- float minScrollPos = m_scrollableArea->minimumScrollPosition(orientation);
- return std::max(std::min(pos, maxScrollPos), minScrollPos);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/ScrollAnimator.h b/chromium/third_party/WebKit/Source/core/platform/ScrollAnimator.h
deleted file mode 100644
index 964a46b57fe..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/ScrollAnimator.h
+++ /dev/null
@@ -1,118 +0,0 @@
-/*
- * Copyright (c) 2010, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ScrollAnimator_h
-#define ScrollAnimator_h
-
-#include "core/platform/PlatformWheelEvent.h"
-#include "core/platform/ScrollTypes.h"
-#include "core/platform/graphics/FloatSize.h"
-#include "wtf/FastAllocBase.h"
-#include "wtf/Forward.h"
-#include "wtf/UnusedParam.h"
-
-namespace WebCore {
-
-class FloatPoint;
-class ScrollableArea;
-class Scrollbar;
-
-class ScrollAnimator {
- WTF_MAKE_FAST_ALLOCATED;
-public:
- static PassOwnPtr<ScrollAnimator> create(ScrollableArea*);
-
- virtual ~ScrollAnimator();
-
- // Computes a scroll destination for the given parameters. Returns false if
- // already at the destination. Otherwise, starts scrolling towards the
- // destination and returns true. Scrolling may be immediate or animated.
- // The base class implementation always scrolls immediately, never animates.
- virtual bool scroll(ScrollbarOrientation, ScrollGranularity, float step, float multiplier);
-
- virtual void scrollToOffsetWithoutAnimation(const FloatPoint&);
-
- ScrollableArea* scrollableArea() const { return m_scrollableArea; }
-
- virtual void setIsActive() { }
-
- virtual bool handleWheelEvent(const PlatformWheelEvent&);
-
-#if OS(MACOSX)
- virtual void handleWheelEventPhase(PlatformWheelEventPhase) { }
-#endif
-
- void setCurrentPosition(const FloatPoint&);
- FloatPoint currentPosition() const;
-
- virtual void cancelAnimations() { }
- virtual void serviceScrollAnimations() { }
-
- virtual void contentAreaWillPaint() const { }
- virtual void mouseEnteredContentArea() const { }
- virtual void mouseExitedContentArea() const { }
- virtual void mouseMovedInContentArea() const { }
- virtual void mouseEnteredScrollbar(Scrollbar*) const { }
- virtual void mouseExitedScrollbar(Scrollbar*) const { }
- virtual void willStartLiveResize() { }
- virtual void contentsResized() const { }
- virtual void willEndLiveResize() { }
- virtual void contentAreaDidShow() const { }
- virtual void contentAreaDidHide() const { }
-
- virtual void finishCurrentScrollAnimations() { }
-
- virtual void didAddVerticalScrollbar(Scrollbar*) { }
- virtual void willRemoveVerticalScrollbar(Scrollbar*) { }
- virtual void didAddHorizontalScrollbar(Scrollbar*) { }
- virtual void willRemoveHorizontalScrollbar(Scrollbar*) { }
-
- virtual bool shouldScrollbarParticipateInHitTesting(Scrollbar*) { return true; }
-
- virtual void notifyContentAreaScrolled(const FloatSize& delta) { UNUSED_PARAM(delta); }
-
- virtual bool isRubberBandInProgress() const { return false; }
-
-protected:
- explicit ScrollAnimator(ScrollableArea*);
-
- virtual void notifyPositionChanged(const FloatSize& delta);
-
- ScrollableArea* m_scrollableArea;
- float m_currentPosX; // We avoid using a FloatPoint in order to reduce
- float m_currentPosY; // subclass code complexity.
-
-private:
- float clampScrollPosition(ScrollbarOrientation, float);
-};
-
-} // namespace WebCore
-
-#endif // ScrollAnimator_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/ScrollAnimatorNone.cpp b/chromium/third_party/WebKit/Source/core/platform/ScrollAnimatorNone.cpp
deleted file mode 100644
index 27c12c39fcf..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/ScrollAnimatorNone.cpp
+++ /dev/null
@@ -1,531 +0,0 @@
-/*
- * Copyright (c) 2011, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/platform/ScrollAnimatorNone.h"
-
-#include <algorithm>
-#include "core/platform/ScrollableArea.h"
-#include "core/platform/graphics/FloatPoint.h"
-#include "wtf/CurrentTime.h"
-#include "wtf/OwnArrayPtr.h"
-#include "wtf/PassOwnPtr.h"
-
-#include "core/platform/chromium/TraceEvent.h"
-
-using namespace std;
-
-namespace WebCore {
-
-const double kFrameRate = 60;
-const double kTickTime = 1 / kFrameRate;
-const double kMinimumTimerInterval = .001;
-const double kZoomTicks = 11;
-
-PassOwnPtr<ScrollAnimator> ScrollAnimator::create(ScrollableArea* scrollableArea)
-{
- if (scrollableArea && scrollableArea->scrollAnimatorEnabled())
- return adoptPtr(new ScrollAnimatorNone(scrollableArea));
- return adoptPtr(new ScrollAnimator(scrollableArea));
-}
-
-ScrollAnimatorNone::Parameters::Parameters()
- : m_isEnabled(false)
-{
-}
-
-ScrollAnimatorNone::Parameters::Parameters(bool isEnabled, double animationTime, double repeatMinimumSustainTime, Curve attackCurve, double attackTime, Curve releaseCurve, double releaseTime, Curve coastTimeCurve, double maximumCoastTime)
- : m_isEnabled(isEnabled)
- , m_animationTime(animationTime)
- , m_repeatMinimumSustainTime(repeatMinimumSustainTime)
- , m_attackCurve(attackCurve)
- , m_attackTime(attackTime)
- , m_releaseCurve(releaseCurve)
- , m_releaseTime(releaseTime)
- , m_coastTimeCurve(coastTimeCurve)
- , m_maximumCoastTime(maximumCoastTime)
-{
-}
-
-double ScrollAnimatorNone::PerAxisData::curveAt(Curve curve, double t)
-{
- switch (curve) {
- case Linear:
- return t;
- case Quadratic:
- return t * t;
- case Cubic:
- return t * t * t;
- case Quartic:
- return t * t * t * t;
- case Bounce:
- // Time base is chosen to keep the bounce points simpler:
- // 1 (half bounce coming in) + 1 + .5 + .25
- const double kTimeBase = 2.75;
- const double kTimeBaseSquared = kTimeBase * kTimeBase;
- if (t < 1 / kTimeBase)
- return kTimeBaseSquared * t * t;
- if (t < 2 / kTimeBase) {
- // Invert a [-.5,.5] quadratic parabola, center it in [1,2].
- double t1 = t - 1.5 / kTimeBase;
- const double kParabolaAtEdge = 1 - .5 * .5;
- return kTimeBaseSquared * t1 * t1 + kParabolaAtEdge;
- }
- if (t < 2.5 / kTimeBase) {
- // Invert a [-.25,.25] quadratic parabola, center it in [2,2.5].
- double t2 = t - 2.25 / kTimeBase;
- const double kParabolaAtEdge = 1 - .25 * .25;
- return kTimeBaseSquared * t2 * t2 + kParabolaAtEdge;
- }
- // Invert a [-.125,.125] quadratic parabola, center it in [2.5,2.75].
- const double kParabolaAtEdge = 1 - .125 * .125;
- t -= 2.625 / kTimeBase;
- return kTimeBaseSquared * t * t + kParabolaAtEdge;
- }
- ASSERT_NOT_REACHED();
- return 0;
-}
-
-double ScrollAnimatorNone::PerAxisData::attackCurve(Curve curve, double deltaTime, double curveT, double startPosition, double attackPosition)
-{
- double t = deltaTime / curveT;
- double positionFactor = curveAt(curve, t);
- return startPosition + positionFactor * (attackPosition - startPosition);
-}
-
-double ScrollAnimatorNone::PerAxisData::releaseCurve(Curve curve, double deltaTime, double curveT, double releasePosition, double desiredPosition)
-{
- double t = deltaTime / curveT;
- double positionFactor = 1 - curveAt(curve, 1 - t);
- return releasePosition + (positionFactor * (desiredPosition - releasePosition));
-}
-
-double ScrollAnimatorNone::PerAxisData::coastCurve(Curve curve, double factor)
-{
- return 1 - curveAt(curve, 1 - factor);
-}
-
-double ScrollAnimatorNone::PerAxisData::curveIntegralAt(Curve curve, double t)
-{
- switch (curve) {
- case Linear:
- return t * t / 2;
- case Quadratic:
- return t * t * t / 3;
- case Cubic:
- return t * t * t * t / 4;
- case Quartic:
- return t * t * t * t * t / 5;
- case Bounce:
- const double kTimeBase = 2.75;
- const double kTimeBaseSquared = kTimeBase * kTimeBase;
- const double kTimeBaseSquaredOverThree = kTimeBaseSquared / 3;
- double area;
- double t1 = min(t, 1 / kTimeBase);
- area = kTimeBaseSquaredOverThree * t1 * t1 * t1;
- if (t < 1 / kTimeBase)
- return area;
-
- t1 = min(t - 1 / kTimeBase, 1 / kTimeBase);
- // The integral of kTimeBaseSquared * (t1 - .5 / kTimeBase) * (t1 - .5 / kTimeBase) + kParabolaAtEdge
- const double kSecondInnerOffset = kTimeBaseSquared * .5 / kTimeBase;
- double bounceArea = t1 * (t1 * (kTimeBaseSquaredOverThree * t1 - kSecondInnerOffset) + 1);
- area += bounceArea;
- if (t < 2 / kTimeBase)
- return area;
-
- t1 = min(t - 2 / kTimeBase, 0.5 / kTimeBase);
- // The integral of kTimeBaseSquared * (t1 - .25 / kTimeBase) * (t1 - .25 / kTimeBase) + kParabolaAtEdge
- const double kThirdInnerOffset = kTimeBaseSquared * .25 / kTimeBase;
- bounceArea = t1 * (t1 * (kTimeBaseSquaredOverThree * t1 - kThirdInnerOffset) + 1);
- area += bounceArea;
- if (t < 2.5 / kTimeBase)
- return area;
-
- t1 = t - 2.5 / kTimeBase;
- // The integral of kTimeBaseSquared * (t1 - .125 / kTimeBase) * (t1 - .125 / kTimeBase) + kParabolaAtEdge
- const double kFourthInnerOffset = kTimeBaseSquared * .125 / kTimeBase;
- bounceArea = t1 * (t1 * (kTimeBaseSquaredOverThree * t1 - kFourthInnerOffset) + 1);
- area += bounceArea;
- return area;
- }
- ASSERT_NOT_REACHED();
- return 0;
-}
-
-double ScrollAnimatorNone::PerAxisData::attackArea(Curve curve, double startT, double endT)
-{
- double startValue = curveIntegralAt(curve, startT);
- double endValue = curveIntegralAt(curve, endT);
- return endValue - startValue;
-}
-
-double ScrollAnimatorNone::PerAxisData::releaseArea(Curve curve, double startT, double endT)
-{
- double startValue = curveIntegralAt(curve, 1 - endT);
- double endValue = curveIntegralAt(curve, 1 - startT);
- return endValue - startValue;
-}
-
-ScrollAnimatorNone::PerAxisData::PerAxisData(ScrollAnimatorNone* parent, float* currentPosition, int visibleLength)
- : m_currentPosition(currentPosition)
- , m_visibleLength(visibleLength)
-{
- reset();
-}
-
-void ScrollAnimatorNone::PerAxisData::reset()
-{
- m_currentVelocity = 0;
-
- m_desiredPosition = 0;
- m_desiredVelocity = 0;
-
- m_startPosition = 0;
- m_startTime = 0;
- m_startVelocity = 0;
-
- m_animationTime = 0;
- m_lastAnimationTime = 0;
-
- m_attackPosition = 0;
- m_attackTime = 0;
- m_attackCurve = Quadratic;
-
- m_releasePosition = 0;
- m_releaseTime = 0;
- m_releaseCurve = Quadratic;
-}
-
-
-bool ScrollAnimatorNone::PerAxisData::updateDataFromParameters(float step, float multiplier, float scrollableSize, double currentTime, Parameters* parameters)
-{
- float delta = step * multiplier;
- if (!m_startTime || !delta || (delta < 0) != (m_desiredPosition - *m_currentPosition < 0)) {
- m_desiredPosition = *m_currentPosition;
- m_startTime = 0;
- }
- float newPosition = m_desiredPosition + delta;
-
- if (newPosition < 0 || newPosition > scrollableSize)
- newPosition = max(min(newPosition, scrollableSize), 0.0f);
-
- if (newPosition == m_desiredPosition)
- return false;
-
- m_desiredPosition = newPosition;
-
- if (!m_startTime) {
- m_attackTime = parameters->m_attackTime;
- m_attackCurve = parameters->m_attackCurve;
- }
- m_animationTime = parameters->m_animationTime;
- m_releaseTime = parameters->m_releaseTime;
- m_releaseCurve = parameters->m_releaseCurve;
-
- // Prioritize our way out of over constraint.
- if (m_attackTime + m_releaseTime > m_animationTime) {
- if (m_releaseTime > m_animationTime)
- m_releaseTime = m_animationTime;
- m_attackTime = m_animationTime - m_releaseTime;
- }
-
- if (!m_startTime) {
- // FIXME: This should be the time from the event that got us here.
- m_startTime = currentTime - kTickTime / 2;
- m_startPosition = *m_currentPosition;
- m_lastAnimationTime = m_startTime;
- }
- m_startVelocity = m_currentVelocity;
-
- double remainingDelta = m_desiredPosition - *m_currentPosition;
-
- double attackAreaLeft = 0;
-
- double deltaTime = m_lastAnimationTime - m_startTime;
- double attackTimeLeft = max(0., m_attackTime - deltaTime);
- double timeLeft = m_animationTime - deltaTime;
- double minTimeLeft = m_releaseTime + min(parameters->m_repeatMinimumSustainTime, m_animationTime - m_releaseTime - attackTimeLeft);
- if (timeLeft < minTimeLeft) {
- m_animationTime = deltaTime + minTimeLeft;
- timeLeft = minTimeLeft;
- }
-
- if (parameters->m_maximumCoastTime > (parameters->m_repeatMinimumSustainTime + parameters->m_releaseTime)) {
- double targetMaxCoastVelocity = m_visibleLength * .25 * kFrameRate;
- // This needs to be as minimal as possible while not being intrusive to page up/down.
- double minCoastDelta = m_visibleLength;
-
- if (fabs(remainingDelta) > minCoastDelta) {
- double maxCoastDelta = parameters->m_maximumCoastTime * targetMaxCoastVelocity;
- double coastFactor = min(1., (fabs(remainingDelta) - minCoastDelta) / (maxCoastDelta - minCoastDelta));
-
- // We could play with the curve here - linear seems a little soft. Initial testing makes me want to feed into the sustain time more aggressively.
- double coastMinTimeLeft = min(parameters->m_maximumCoastTime, minTimeLeft + coastCurve(parameters->m_coastTimeCurve, coastFactor) * (parameters->m_maximumCoastTime - minTimeLeft));
-
- double additionalTime = max(0., coastMinTimeLeft - minTimeLeft);
- if (additionalTime) {
- double additionalReleaseTime = min(additionalTime, parameters->m_releaseTime / (parameters->m_releaseTime + parameters->m_repeatMinimumSustainTime) * additionalTime);
- m_releaseTime = parameters->m_releaseTime + additionalReleaseTime;
- m_animationTime = deltaTime + coastMinTimeLeft;
- timeLeft = coastMinTimeLeft;
- }
- }
- }
-
- double releaseTimeLeft = min(timeLeft, m_releaseTime);
- double sustainTimeLeft = max(0., timeLeft - releaseTimeLeft - attackTimeLeft);
-
- if (attackTimeLeft) {
- double attackSpot = deltaTime / m_attackTime;
- attackAreaLeft = attackArea(m_attackCurve, attackSpot, 1) * m_attackTime;
- }
-
- double releaseSpot = (m_releaseTime - releaseTimeLeft) / m_releaseTime;
- double releaseAreaLeft = releaseArea(m_releaseCurve, releaseSpot, 1) * m_releaseTime;
-
- m_desiredVelocity = remainingDelta / (attackAreaLeft + sustainTimeLeft + releaseAreaLeft);
- m_releasePosition = m_desiredPosition - m_desiredVelocity * releaseAreaLeft;
- if (attackAreaLeft)
- m_attackPosition = m_startPosition + m_desiredVelocity * attackAreaLeft;
- else
- m_attackPosition = m_releasePosition - (m_animationTime - m_releaseTime - m_attackTime) * m_desiredVelocity;
-
- if (sustainTimeLeft) {
- double roundOff = m_releasePosition - ((attackAreaLeft ? m_attackPosition : *m_currentPosition) + m_desiredVelocity * sustainTimeLeft);
- m_desiredVelocity += roundOff / sustainTimeLeft;
- }
-
- return true;
-}
-
-// FIXME: Add in jank detection trace events into this function.
-bool ScrollAnimatorNone::PerAxisData::animateScroll(double currentTime)
-{
- double lastScrollInterval = currentTime - m_lastAnimationTime;
- if (lastScrollInterval < kMinimumTimerInterval)
- return true;
-
- m_lastAnimationTime = currentTime;
-
- double deltaTime = currentTime - m_startTime;
- double newPosition = *m_currentPosition;
-
- if (deltaTime > m_animationTime) {
- *m_currentPosition = m_desiredPosition;
- reset();
- return false;
- }
- if (deltaTime < m_attackTime)
- newPosition = attackCurve(m_attackCurve, deltaTime, m_attackTime, m_startPosition, m_attackPosition);
- else if (deltaTime < (m_animationTime - m_releaseTime))
- newPosition = m_attackPosition + (deltaTime - m_attackTime) * m_desiredVelocity;
- else {
- // release is based on targeting the exact final position.
- double releaseDeltaT = deltaTime - (m_animationTime - m_releaseTime);
- newPosition = releaseCurve(m_releaseCurve, releaseDeltaT, m_releaseTime, m_releasePosition, m_desiredPosition);
- }
-
- // Normalize velocity to a per second amount. Could be used to check for jank.
- if (lastScrollInterval > 0)
- m_currentVelocity = (newPosition - *m_currentPosition) / lastScrollInterval;
- *m_currentPosition = newPosition;
-
- return true;
-}
-
-void ScrollAnimatorNone::PerAxisData::updateVisibleLength(int visibleLength)
-{
- m_visibleLength = visibleLength;
-}
-
-ScrollAnimatorNone::ScrollAnimatorNone(ScrollableArea* scrollableArea)
- : ScrollAnimator(scrollableArea)
- , m_horizontalData(this, &m_currentPosX, scrollableArea->visibleWidth())
- , m_verticalData(this, &m_currentPosY, scrollableArea->visibleHeight())
- , m_startTime(0)
- , m_animationActive(false)
-{
-}
-
-ScrollAnimatorNone::~ScrollAnimatorNone()
-{
- stopAnimationTimerIfNeeded();
-}
-
-ScrollAnimatorNone::Parameters ScrollAnimatorNone::parametersForScrollGranularity(ScrollGranularity granularity) const
-{
- switch (granularity) {
- case ScrollByDocument:
- return Parameters(true, 20 * kTickTime, 10 * kTickTime, Cubic, 10 * kTickTime, Cubic, 10 * kTickTime, Linear, 1);
- case ScrollByLine:
- return Parameters(true, 10 * kTickTime, 7 * kTickTime, Cubic, 3 * kTickTime, Cubic, 3 * kTickTime, Linear, 1);
- case ScrollByPage:
- return Parameters(true, 15 * kTickTime, 10 * kTickTime, Cubic, 5 * kTickTime, Cubic, 5 * kTickTime, Linear, 1);
- case ScrollByPixel:
- return Parameters(true, 11 * kTickTime, 2 * kTickTime, Cubic, 3 * kTickTime, Cubic, 3 * kTickTime, Quadratic, 1.25);
- default:
- ASSERT_NOT_REACHED();
- }
- return Parameters();
-}
-
-bool ScrollAnimatorNone::scroll(ScrollbarOrientation orientation, ScrollGranularity granularity, float step, float multiplier)
-{
- if (!m_scrollableArea->scrollAnimatorEnabled())
- return ScrollAnimator::scroll(orientation, granularity, step, multiplier);
-
- TRACE_EVENT0("webkit", "ScrollAnimatorNone::scroll");
-
- // FIXME: get the type passed in. MouseWheel could also be by line, but should still have different
- // animation parameters than the keyboard.
- Parameters parameters;
- switch (granularity) {
- case ScrollByDocument:
- case ScrollByLine:
- case ScrollByPage:
- case ScrollByPixel:
- parameters = parametersForScrollGranularity(granularity);
- break;
- case ScrollByPrecisePixel:
- return ScrollAnimator::scroll(orientation, granularity, step, multiplier);
- }
-
- // If the individual input setting is disabled, bail.
- if (!parameters.m_isEnabled)
- return ScrollAnimator::scroll(orientation, granularity, step, multiplier);
-
- // This is an animatable scroll. Set the animation in motion using the appropriate parameters.
- float scrollableSize = static_cast<float>(m_scrollableArea->scrollSize(orientation));
-
- PerAxisData& data = (orientation == VerticalScrollbar) ? m_verticalData : m_horizontalData;
- bool needToScroll = data.updateDataFromParameters(step, multiplier, scrollableSize, WTF::monotonicallyIncreasingTime(), &parameters);
- if (needToScroll && !animationTimerActive()) {
- m_startTime = data.m_startTime;
- animationWillStart();
- animationTimerFired();
- }
- return needToScroll;
-}
-
-void ScrollAnimatorNone::scrollToOffsetWithoutAnimation(const FloatPoint& offset)
-{
- stopAnimationTimerIfNeeded();
-
- FloatSize delta = FloatSize(offset.x() - *m_horizontalData.m_currentPosition, offset.y() - *m_verticalData.m_currentPosition);
-
- m_horizontalData.reset();
- *m_horizontalData.m_currentPosition = offset.x();
- m_horizontalData.m_desiredPosition = offset.x();
-
- m_verticalData.reset();
- *m_verticalData.m_currentPosition = offset.y();
- m_verticalData.m_desiredPosition = offset.y();
-
- notifyPositionChanged(delta);
-}
-
-void ScrollAnimatorNone::cancelAnimations()
-{
- m_animationActive = false;
-}
-
-void ScrollAnimatorNone::serviceScrollAnimations()
-{
- if (m_animationActive)
- animationTimerFired();
-}
-
-void ScrollAnimatorNone::willEndLiveResize()
-{
- updateVisibleLengths();
-}
-
-void ScrollAnimatorNone::didAddVerticalScrollbar(Scrollbar*)
-{
- updateVisibleLengths();
-}
-
-void ScrollAnimatorNone::didAddHorizontalScrollbar(Scrollbar*)
-{
- updateVisibleLengths();
-}
-
-void ScrollAnimatorNone::updateVisibleLengths()
-{
- m_horizontalData.updateVisibleLength(scrollableArea()->visibleWidth());
- m_verticalData.updateVisibleLength(scrollableArea()->visibleHeight());
-}
-
-void ScrollAnimatorNone::animationTimerFired()
-{
- TRACE_EVENT0("webkit", "ScrollAnimatorNone::animationTimerFired");
-
- double currentTime = WTF::monotonicallyIncreasingTime();
- double deltaToNextFrame = ceil((currentTime - m_startTime) * kFrameRate) / kFrameRate - (currentTime - m_startTime);
- currentTime += deltaToNextFrame;
-
- bool continueAnimation = false;
- if (m_horizontalData.m_startTime && m_horizontalData.animateScroll(currentTime))
- continueAnimation = true;
- if (m_verticalData.m_startTime && m_verticalData.animateScroll(currentTime))
- continueAnimation = true;
-
- if (continueAnimation)
- startNextTimer();
- else
- m_animationActive = false;
-
- TRACE_EVENT0("webkit", "ScrollAnimatorNone::notifyPositionChanged");
- notifyPositionChanged(FloatSize());
-
- if (!continueAnimation)
- animationDidFinish();
-}
-
-void ScrollAnimatorNone::startNextTimer()
-{
- if (scrollableArea()->scheduleAnimation())
- m_animationActive = true;
-}
-
-bool ScrollAnimatorNone::animationTimerActive()
-{
- return m_animationActive;
-}
-
-void ScrollAnimatorNone::stopAnimationTimerIfNeeded()
-{
- if (animationTimerActive())
- m_animationActive = false;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/ScrollAnimatorNone.h b/chromium/third_party/WebKit/Source/core/platform/ScrollAnimatorNone.h
deleted file mode 100644
index f54f9de1d24..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/ScrollAnimatorNone.h
+++ /dev/null
@@ -1,155 +0,0 @@
-/*
- * Copyright (c) 2011, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ScrollAnimatorNone_h
-#define ScrollAnimatorNone_h
-
-#include "core/platform/ScrollAnimator.h"
-#include "core/platform/Timer.h"
-#include "core/platform/graphics/FloatPoint.h"
-#include "wtf/OwnPtr.h"
-
-class ScrollAnimatorNoneTest;
-
-namespace WebCore {
-
-class IntPoint;
-class ActivePlatformGestureAnimation;
-struct ScrollAnimatorParameters;
-
-class ScrollAnimatorNone : public ScrollAnimator {
-public:
- explicit ScrollAnimatorNone(ScrollableArea*);
- virtual ~ScrollAnimatorNone();
-
- virtual bool scroll(ScrollbarOrientation, ScrollGranularity, float step, float multiplier);
- virtual void scrollToOffsetWithoutAnimation(const FloatPoint&);
-
- virtual void cancelAnimations();
- virtual void serviceScrollAnimations();
-
- virtual void willEndLiveResize();
- virtual void didAddVerticalScrollbar(Scrollbar*);
- virtual void didAddHorizontalScrollbar(Scrollbar*);
-
- enum Curve {
- Linear,
- Quadratic,
- Cubic,
- Quartic,
- Bounce
- };
-
- struct Parameters {
- Parameters();
- Parameters(bool isEnabled, double animationTime, double repeatMinimumSustainTime, Curve attackCurve, double attackTime, Curve releaseCurve, double releaseTime, Curve coastTimeCurve, double maximumCoastTime);
-
- // Note that the times can be overspecified such that releaseTime or releaseTime and attackTime are greater
- // than animationTime. animationTime takes priority over releaseTime, capping it. attackTime is capped at
- // whatever time remains, or zero if none.
- bool m_isEnabled;
- double m_animationTime;
- double m_repeatMinimumSustainTime;
-
- Curve m_attackCurve;
- double m_attackTime;
-
- Curve m_releaseCurve;
- double m_releaseTime;
-
- Curve m_coastTimeCurve;
- double m_maximumCoastTime;
- };
-
-protected:
- virtual void animationWillStart() { }
- virtual void animationDidFinish() { }
-
- Parameters parametersForScrollGranularity(ScrollGranularity) const;
-
- friend class ::ScrollAnimatorNoneTest;
-
- struct PerAxisData {
- PerAxisData(ScrollAnimatorNone* parent, float* currentPos, int visibleLength);
- void reset();
- bool updateDataFromParameters(float step, float multiplier, float scrollableSize, double currentTime, Parameters*);
- bool animateScroll(double currentTime);
- void updateVisibleLength(int visibleLength);
-
- static double curveAt(Curve, double t);
- static double attackCurve(Curve, double deltaT, double curveT, double startPos, double attackPos);
- static double releaseCurve(Curve, double deltaT, double curveT, double releasePos, double desiredPos);
- static double coastCurve(Curve, double factor);
-
- static double curveIntegralAt(Curve, double t);
- static double attackArea(Curve, double startT, double endT);
- static double releaseArea(Curve, double startT, double endT);
-
- float* m_currentPosition;
- double m_currentVelocity;
-
- double m_desiredPosition;
- double m_desiredVelocity;
-
- double m_startPosition;
- double m_startTime;
- double m_startVelocity;
-
- double m_animationTime;
- double m_lastAnimationTime;
-
- double m_attackPosition;
- double m_attackTime;
- Curve m_attackCurve;
-
- double m_releasePosition;
- double m_releaseTime;
- Curve m_releaseCurve;
-
- int m_visibleLength;
- };
-
- void startNextTimer();
- void animationTimerFired();
-
- void stopAnimationTimerIfNeeded();
- bool animationTimerActive();
- void updateVisibleLengths();
-
- PerAxisData m_horizontalData;
- PerAxisData m_verticalData;
-
- double m_startTime;
- bool m_animationActive;
-};
-
-} // namespace WebCore
-
-#endif // ScrollAnimatorNone_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/ScrollTypes.h b/chromium/third_party/WebKit/Source/core/platform/ScrollTypes.h
deleted file mode 100644
index 8f333d8e207..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/ScrollTypes.h
+++ /dev/null
@@ -1,166 +0,0 @@
-/*
- * Copyright (C) 2006 Apple Computer, Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ScrollTypes_h
-#define ScrollTypes_h
-
-#include "wtf/Assertions.h"
-
-namespace WebCore {
-
- enum ScrollDirection {
- ScrollUp,
- ScrollDown,
- ScrollLeft,
- ScrollRight
- };
-
- enum ScrollLogicalDirection {
- ScrollBlockDirectionBackward,
- ScrollBlockDirectionForward,
- ScrollInlineDirectionBackward,
- ScrollInlineDirectionForward
- };
-
-
- inline ScrollDirection logicalToPhysical(ScrollLogicalDirection direction, bool isVertical, bool isFlipped)
- {
- switch (direction) {
- case ScrollBlockDirectionBackward: {
- if (isVertical) {
- if (!isFlipped)
- return ScrollUp;
- return ScrollDown;
- } else {
- if (!isFlipped)
- return ScrollLeft;
- return ScrollRight;
- }
- break;
- }
- case ScrollBlockDirectionForward: {
- if (isVertical) {
- if (!isFlipped)
- return ScrollDown;
- return ScrollUp;
- } else {
- if (!isFlipped)
- return ScrollRight;
- return ScrollLeft;
- }
- break;
- }
- case ScrollInlineDirectionBackward: {
- if (isVertical) {
- if (!isFlipped)
- return ScrollLeft;
- return ScrollRight;
- } else {
- if (!isFlipped)
- return ScrollUp;
- return ScrollDown;
- }
- break;
- }
- case ScrollInlineDirectionForward: {
- if (isVertical) {
- if (!isFlipped)
- return ScrollRight;
- return ScrollLeft;
- } else {
- if (!isFlipped)
- return ScrollDown;
- return ScrollUp;
- }
- break;
- }
- default:
- ASSERT_NOT_REACHED();
- break;
- }
- return ScrollUp;
- }
-
- enum ScrollGranularity {
- ScrollByLine,
- ScrollByPage,
- ScrollByDocument,
- ScrollByPixel,
- ScrollByPrecisePixel
- };
-
- enum ScrollElasticity {
- ScrollElasticityAutomatic,
- ScrollElasticityNone,
- ScrollElasticityAllowed
- };
-
- enum ScrollbarOrientation { HorizontalScrollbar, VerticalScrollbar };
-
- enum ScrollbarMode { ScrollbarAuto, ScrollbarAlwaysOff, ScrollbarAlwaysOn };
-
- enum ScrollbarControlSize { RegularScrollbar, SmallScrollbar };
-
- typedef unsigned ScrollbarControlState;
-
- enum ScrollbarControlStateMask {
- ActiveScrollbarState = 1,
- EnabledScrollbarState = 1 << 1,
- PressedScrollbarState = 1 << 2
- };
-
- enum ScrollbarPart {
- NoPart = 0,
- BackButtonStartPart = 1,
- ForwardButtonStartPart = 1 << 1,
- BackTrackPart = 1 << 2,
- ThumbPart = 1 << 3,
- ForwardTrackPart = 1 << 4,
- BackButtonEndPart = 1 << 5,
- ForwardButtonEndPart = 1 << 6,
- ScrollbarBGPart = 1 << 7,
- TrackBGPart = 1 << 8,
- AllParts = 0xffffffff
- };
-
- enum ScrollbarButtonsPlacement {
- ScrollbarButtonsNone,
- ScrollbarButtonsSingle,
- ScrollbarButtonsDoubleStart,
- ScrollbarButtonsDoubleEnd,
- ScrollbarButtonsDoubleBoth
- };
-
- enum ScrollbarOverlayStyle {
- ScrollbarOverlayStyleDefault,
- ScrollbarOverlayStyleDark,
- ScrollbarOverlayStyleLight
- };
-
- typedef unsigned ScrollbarControlPartMask;
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/ScrollView.cpp b/chromium/third_party/WebKit/Source/core/platform/ScrollView.cpp
deleted file mode 100644
index 616dee26b7c..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/ScrollView.cpp
+++ /dev/null
@@ -1,1201 +0,0 @@
-/*
- * Copyright (C) 2006, 2007, 2008 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/ScrollView.h"
-
-#include "core/accessibility/AXObjectCache.h"
-#include "core/platform/HostWindow.h"
-#include "core/platform/Scrollbar.h"
-#include "core/platform/ScrollbarTheme.h"
-#include "core/platform/graphics/GraphicsContextStateSaver.h"
-#include "core/platform/graphics/GraphicsLayer.h"
-#include "wtf/StdLibExtras.h"
-
-using namespace std;
-
-namespace WebCore {
-
-ScrollView::ScrollView()
- : m_horizontalScrollbarMode(ScrollbarAuto)
- , m_verticalScrollbarMode(ScrollbarAuto)
- , m_horizontalScrollbarLock(false)
- , m_verticalScrollbarLock(false)
- , m_canBlitOnScroll(true)
- , m_scrollbarsAvoidingResizer(0)
- , m_scrollbarsSuppressed(false)
- , m_inUpdateScrollbars(false)
- , m_updateScrollbarsPass(0)
- , m_drawPanScrollIcon(false)
- , m_useFixedLayout(false)
- , m_paintsEntireContents(false)
- , m_clipsRepaints(true)
-{
-}
-
-ScrollView::~ScrollView()
-{
-}
-
-void ScrollView::addChild(PassRefPtr<Widget> prpChild)
-{
- Widget* child = prpChild.get();
- ASSERT(child != this && !child->parent());
- child->setParent(this);
- m_children.add(prpChild);
-}
-
-void ScrollView::removeChild(Widget* child)
-{
- ASSERT(child->parent() == this);
- child->setParent(0);
- m_children.remove(child);
-}
-
-void ScrollView::setHasHorizontalScrollbar(bool hasBar)
-{
- if (hasBar && !m_horizontalScrollbar) {
- m_horizontalScrollbar = createScrollbar(HorizontalScrollbar);
- addChild(m_horizontalScrollbar.get());
- didAddHorizontalScrollbar(m_horizontalScrollbar.get());
- m_horizontalScrollbar->styleChanged();
- } else if (!hasBar && m_horizontalScrollbar) {
- willRemoveHorizontalScrollbar(m_horizontalScrollbar.get());
- removeChild(m_horizontalScrollbar.get());
- m_horizontalScrollbar = 0;
- }
-
- if (AXObjectCache* cache = axObjectCache())
- cache->handleScrollbarUpdate(this);
-}
-
-void ScrollView::setHasVerticalScrollbar(bool hasBar)
-{
- if (hasBar && !m_verticalScrollbar) {
- m_verticalScrollbar = createScrollbar(VerticalScrollbar);
- addChild(m_verticalScrollbar.get());
- didAddVerticalScrollbar(m_verticalScrollbar.get());
- m_verticalScrollbar->styleChanged();
- } else if (!hasBar && m_verticalScrollbar) {
- willRemoveVerticalScrollbar(m_verticalScrollbar.get());
- removeChild(m_verticalScrollbar.get());
- m_verticalScrollbar = 0;
- }
-
- if (AXObjectCache* cache = axObjectCache())
- cache->handleScrollbarUpdate(this);
-}
-
-PassRefPtr<Scrollbar> ScrollView::createScrollbar(ScrollbarOrientation orientation)
-{
- return Scrollbar::create(this, orientation, RegularScrollbar);
-}
-
-void ScrollView::setScrollbarModes(ScrollbarMode horizontalMode, ScrollbarMode verticalMode,
- bool horizontalLock, bool verticalLock)
-{
- bool needsUpdate = false;
-
- if (horizontalMode != horizontalScrollbarMode() && !m_horizontalScrollbarLock) {
- m_horizontalScrollbarMode = horizontalMode;
- needsUpdate = true;
- }
-
- if (verticalMode != verticalScrollbarMode() && !m_verticalScrollbarLock) {
- m_verticalScrollbarMode = verticalMode;
- needsUpdate = true;
- }
-
- if (horizontalLock)
- setHorizontalScrollbarLock();
-
- if (verticalLock)
- setVerticalScrollbarLock();
-
- if (!needsUpdate)
- return;
-
- updateScrollbars(scrollOffset());
-}
-
-void ScrollView::scrollbarModes(ScrollbarMode& horizontalMode, ScrollbarMode& verticalMode) const
-{
- horizontalMode = m_horizontalScrollbarMode;
- verticalMode = m_verticalScrollbarMode;
-}
-
-void ScrollView::setCanHaveScrollbars(bool canScroll)
-{
- ScrollbarMode newHorizontalMode;
- ScrollbarMode newVerticalMode;
-
- scrollbarModes(newHorizontalMode, newVerticalMode);
-
- if (canScroll && newVerticalMode == ScrollbarAlwaysOff)
- newVerticalMode = ScrollbarAuto;
- else if (!canScroll)
- newVerticalMode = ScrollbarAlwaysOff;
-
- if (canScroll && newHorizontalMode == ScrollbarAlwaysOff)
- newHorizontalMode = ScrollbarAuto;
- else if (!canScroll)
- newHorizontalMode = ScrollbarAlwaysOff;
-
- setScrollbarModes(newHorizontalMode, newVerticalMode);
-}
-
-void ScrollView::setCanBlitOnScroll(bool b)
-{
- m_canBlitOnScroll = b;
-}
-
-bool ScrollView::canBlitOnScroll() const
-{
- return m_canBlitOnScroll;
-}
-
-void ScrollView::setPaintsEntireContents(bool paintsEntireContents)
-{
- m_paintsEntireContents = paintsEntireContents;
-}
-
-void ScrollView::setClipsRepaints(bool clipsRepaints)
-{
- m_clipsRepaints = clipsRepaints;
-}
-
-IntSize ScrollView::unscaledVisibleContentSize(VisibleContentRectIncludesScrollbars scrollbarInclusion) const
-{
- int verticalScrollbarWidth = 0;
- int horizontalScrollbarHeight = 0;
-
- if (scrollbarInclusion == ExcludeScrollbars) {
- if (Scrollbar* verticalBar = verticalScrollbar())
- verticalScrollbarWidth = !verticalBar->isOverlayScrollbar() ? verticalBar->width() : 0;
- if (Scrollbar* horizontalBar = horizontalScrollbar())
- horizontalScrollbarHeight = !horizontalBar->isOverlayScrollbar() ? horizontalBar->height() : 0;
- }
-
- return IntSize(max(0, width() - verticalScrollbarWidth),
- max(0, height() - horizontalScrollbarHeight));
-}
-
-IntRect ScrollView::visibleContentRect(VisibleContentRectIncludesScrollbars scollbarInclusion) const
-{
- FloatSize visibleContentSize = unscaledVisibleContentSize(scollbarInclusion);
- visibleContentSize.scale(1 / visibleContentScaleFactor());
- return IntRect(IntPoint(m_scrollOffset), expandedIntSize(visibleContentSize));
-}
-
-IntSize ScrollView::layoutSize(VisibleContentRectIncludesScrollbars scrollbarInclusion) const
-{
- return m_fixedLayoutSize.isZero() || !m_useFixedLayout ? unscaledVisibleContentSize(scrollbarInclusion) : m_fixedLayoutSize;
-}
-
-IntSize ScrollView::fixedLayoutSize() const
-{
- return m_fixedLayoutSize;
-}
-
-void ScrollView::setFixedLayoutSize(const IntSize& newSize)
-{
- if (fixedLayoutSize() == newSize)
- return;
- m_fixedLayoutSize = newSize;
- updateScrollbars(scrollOffset());
- if (m_useFixedLayout)
- contentsResized();
-}
-
-bool ScrollView::useFixedLayout() const
-{
- return m_useFixedLayout;
-}
-
-void ScrollView::setUseFixedLayout(bool enable)
-{
- if (useFixedLayout() == enable)
- return;
- m_useFixedLayout = enable;
- updateScrollbars(scrollOffset());
- contentsResized();
-}
-
-IntSize ScrollView::contentsSize() const
-{
- return m_contentsSize;
-}
-
-void ScrollView::setContentsSize(const IntSize& newSize)
-{
- if (contentsSize() == newSize)
- return;
- m_contentsSize = newSize;
- updateScrollbars(scrollOffset());
- updateOverhangAreas();
-}
-
-IntPoint ScrollView::maximumScrollPosition() const
-{
- IntPoint maximumOffset(contentsWidth() - visibleWidth() - scrollOrigin().x(), contentsHeight() - visibleHeight() - scrollOrigin().y());
- maximumOffset.clampNegativeToZero();
- return maximumOffset;
-}
-
-IntPoint ScrollView::minimumScrollPosition() const
-{
- return IntPoint(-scrollOrigin().x(), -scrollOrigin().y());
-}
-
-IntPoint ScrollView::adjustScrollPositionWithinRange(const IntPoint& scrollPoint) const
-{
- if (!constrainsScrollingToContentEdge())
- return scrollPoint;
-
- IntPoint newScrollPosition = scrollPoint.shrunkTo(maximumScrollPosition());
- newScrollPosition = newScrollPosition.expandedTo(minimumScrollPosition());
- return newScrollPosition;
-}
-
-int ScrollView::scrollSize(ScrollbarOrientation orientation) const
-{
- Scrollbar* scrollbar = ((orientation == HorizontalScrollbar) ? m_horizontalScrollbar : m_verticalScrollbar).get();
-
- // If no scrollbars are present, the content may still be scrollable.
- if (!scrollbar) {
- IntSize scrollSize = m_contentsSize - visibleContentRect().size();
- scrollSize.clampNegativeToZero();
- return orientation == HorizontalScrollbar ? scrollSize.width() : scrollSize.height();
- }
-
- return scrollbar->totalSize() - scrollbar->visibleSize();
-}
-
-void ScrollView::notifyPageThatContentAreaWillPaint() const
-{
-}
-
-void ScrollView::setScrollOffset(const IntPoint& offset)
-{
- scrollTo(toIntSize(adjustScrollPositionWithinRange(offset)));
-}
-
-void ScrollView::scrollTo(const IntSize& newOffset)
-{
- IntSize scrollDelta = newOffset - m_scrollOffset;
- if (scrollDelta == IntSize())
- return;
- m_scrollOffset = newOffset;
-
- if (scrollbarsSuppressed())
- return;
-
- repaintFixedElementsAfterScrolling();
- scrollContents(scrollDelta);
- updateFixedElementsAfterScrolling();
-}
-
-void ScrollView::setScrollPosition(const IntPoint& scrollPoint)
-{
- IntPoint newScrollPosition = adjustScrollPositionWithinRange(scrollPoint);
-
- if (newScrollPosition == scrollPosition())
- return;
-
- updateScrollbars(IntSize(newScrollPosition.x(), newScrollPosition.y()));
-}
-
-bool ScrollView::logicalScroll(ScrollLogicalDirection direction, ScrollGranularity granularity)
-{
- return scroll(logicalToPhysical(direction, isVerticalDocument(), isFlippedDocument()), granularity);
-}
-
-IntSize ScrollView::overhangAmount() const
-{
- IntSize stretch;
-
- int physicalScrollY = scrollPosition().y() + scrollOrigin().y();
- if (physicalScrollY < 0)
- stretch.setHeight(physicalScrollY);
- else if (contentsHeight() && physicalScrollY > contentsHeight() - visibleHeight())
- stretch.setHeight(physicalScrollY - (contentsHeight() - visibleHeight()));
-
- int physicalScrollX = scrollPosition().x() + scrollOrigin().x();
- if (physicalScrollX < 0)
- stretch.setWidth(physicalScrollX);
- else if (contentsWidth() && physicalScrollX > contentsWidth() - visibleWidth())
- stretch.setWidth(physicalScrollX - (contentsWidth() - visibleWidth()));
-
- return stretch;
-}
-
-void ScrollView::windowResizerRectChanged()
-{
- updateScrollbars(scrollOffset());
-}
-
-static const unsigned cMaxUpdateScrollbarsPass = 2;
-
-void ScrollView::updateScrollbars(const IntSize& desiredOffset)
-{
- if (m_inUpdateScrollbars)
- return;
-
- // If we came in here with the view already needing a layout, then go ahead and do that
- // first. (This will be the common case, e.g., when the page changes due to window resizing for example).
- // This layout will not re-enter updateScrollbars and does not count towards our max layout pass total.
- if (!m_scrollbarsSuppressed) {
- m_inUpdateScrollbars = true;
- visibleContentsResized();
- m_inUpdateScrollbars = false;
- }
-
- IntRect oldScrollCornerRect = scrollCornerRect();
-
- bool hasHorizontalScrollbar = m_horizontalScrollbar;
- bool hasVerticalScrollbar = m_verticalScrollbar;
-
- bool newHasHorizontalScrollbar = hasHorizontalScrollbar;
- bool newHasVerticalScrollbar = hasVerticalScrollbar;
-
- ScrollbarMode hScroll = m_horizontalScrollbarMode;
- ScrollbarMode vScroll = m_verticalScrollbarMode;
-
- if (hScroll != ScrollbarAuto)
- newHasHorizontalScrollbar = (hScroll == ScrollbarAlwaysOn);
- if (vScroll != ScrollbarAuto)
- newHasVerticalScrollbar = (vScroll == ScrollbarAlwaysOn);
-
- if (m_scrollbarsSuppressed || (hScroll != ScrollbarAuto && vScroll != ScrollbarAuto)) {
- if (hasHorizontalScrollbar != newHasHorizontalScrollbar)
- setHasHorizontalScrollbar(newHasHorizontalScrollbar);
- if (hasVerticalScrollbar != newHasVerticalScrollbar)
- setHasVerticalScrollbar(newHasVerticalScrollbar);
- } else {
- bool scrollbarExistenceChanged = false;
-
- IntSize docSize = contentsSize();
- IntSize fullVisibleSize = visibleContentRect(IncludeScrollbars).size();
-
- bool scrollbarsAreOverlay = ScrollbarTheme::theme()->usesOverlayScrollbars();
-
- if (hScroll == ScrollbarAuto) {
- newHasHorizontalScrollbar = docSize.width() > visibleWidth();
- if (!scrollbarsAreOverlay && newHasHorizontalScrollbar && !m_updateScrollbarsPass && docSize.width() <= fullVisibleSize.width() && docSize.height() <= fullVisibleSize.height())
- newHasHorizontalScrollbar = false;
- }
- if (vScroll == ScrollbarAuto) {
- newHasVerticalScrollbar = docSize.height() > visibleHeight();
- if (!scrollbarsAreOverlay && newHasVerticalScrollbar && !m_updateScrollbarsPass && docSize.width() <= fullVisibleSize.width() && docSize.height() <= fullVisibleSize.height())
- newHasVerticalScrollbar = false;
- }
-
- if (!scrollbarsAreOverlay) {
- // If we ever turn one scrollbar off, always turn the other one off too. Never ever
- // try to both gain/lose a scrollbar in the same pass.
- if (!newHasHorizontalScrollbar && hasHorizontalScrollbar && vScroll != ScrollbarAlwaysOn)
- newHasVerticalScrollbar = false;
- if (!newHasVerticalScrollbar && hasVerticalScrollbar && hScroll != ScrollbarAlwaysOn)
- newHasHorizontalScrollbar = false;
- }
-
- if (hasHorizontalScrollbar != newHasHorizontalScrollbar) {
- scrollbarExistenceChanged = true;
- if (scrollOrigin().y() && !newHasHorizontalScrollbar && !scrollbarsAreOverlay)
- ScrollableArea::setScrollOrigin(IntPoint(scrollOrigin().x(), scrollOrigin().y() - m_horizontalScrollbar->height()));
- if (hasHorizontalScrollbar)
- m_horizontalScrollbar->invalidate();
- setHasHorizontalScrollbar(newHasHorizontalScrollbar);
- }
-
- if (hasVerticalScrollbar != newHasVerticalScrollbar) {
- scrollbarExistenceChanged = true;
- if (scrollOrigin().x() && !newHasVerticalScrollbar && !scrollbarsAreOverlay)
- ScrollableArea::setScrollOrigin(IntPoint(scrollOrigin().x() - m_verticalScrollbar->width(), scrollOrigin().y()));
- if (hasVerticalScrollbar)
- m_verticalScrollbar->invalidate();
- setHasVerticalScrollbar(newHasVerticalScrollbar);
- }
-
- if (scrollbarExistenceChanged) {
- if (scrollbarsAreOverlay) {
- // Synchronize status of scrollbar layers if necessary.
- m_inUpdateScrollbars = true;
- visibleContentsResized();
- m_inUpdateScrollbars = false;
- } else if (m_updateScrollbarsPass < cMaxUpdateScrollbarsPass) {
- m_updateScrollbarsPass++;
- contentsResized();
- visibleContentsResized();
- IntSize newDocSize = contentsSize();
- if (newDocSize == docSize) {
- // The layout with the new scroll state had no impact on
- // the document's overall size, so updateScrollbars didn't get called.
- // Recur manually.
- updateScrollbars(desiredOffset);
- }
- m_updateScrollbarsPass--;
- }
- }
- }
-
- // Set up the range, but only do this if we're not in a nested call (to avoid
- // doing it multiple times).
- if (m_updateScrollbarsPass)
- return;
-
- m_inUpdateScrollbars = true;
-
- if (m_horizontalScrollbar) {
- int clientWidth = visibleWidth();
- IntRect oldRect(m_horizontalScrollbar->frameRect());
- IntRect hBarRect(0,
- height() - m_horizontalScrollbar->height(),
- width() - (m_verticalScrollbar ? m_verticalScrollbar->width() : 0),
- m_horizontalScrollbar->height());
- m_horizontalScrollbar->setFrameRect(hBarRect);
- if (!m_scrollbarsSuppressed && oldRect != m_horizontalScrollbar->frameRect())
- m_horizontalScrollbar->invalidate();
-
- if (m_scrollbarsSuppressed)
- m_horizontalScrollbar->setSuppressInvalidation(true);
- m_horizontalScrollbar->setEnabled(contentsWidth() > clientWidth);
- m_horizontalScrollbar->setProportion(clientWidth, contentsWidth());
- if (m_scrollbarsSuppressed)
- m_horizontalScrollbar->setSuppressInvalidation(false);
- }
-
- if (m_verticalScrollbar) {
- int clientHeight = visibleHeight();
- IntRect oldRect(m_verticalScrollbar->frameRect());
- IntRect vBarRect(width() - m_verticalScrollbar->width(),
- 0,
- m_verticalScrollbar->width(),
- height() - (m_horizontalScrollbar ? m_horizontalScrollbar->height() : 0));
- m_verticalScrollbar->setFrameRect(vBarRect);
- if (!m_scrollbarsSuppressed && oldRect != m_verticalScrollbar->frameRect())
- m_verticalScrollbar->invalidate();
-
- if (m_scrollbarsSuppressed)
- m_verticalScrollbar->setSuppressInvalidation(true);
- m_verticalScrollbar->setEnabled(contentsHeight() > clientHeight);
- m_verticalScrollbar->setProportion(clientHeight, contentsHeight());
- if (m_scrollbarsSuppressed)
- m_verticalScrollbar->setSuppressInvalidation(false);
- }
-
- if (hasHorizontalScrollbar != newHasHorizontalScrollbar || hasVerticalScrollbar != newHasVerticalScrollbar) {
- // FIXME: Is frameRectsChanged really necessary here? Have any frame rects changed?
- frameRectsChanged();
- positionScrollbarLayers();
- updateScrollCorner();
- if (!m_horizontalScrollbar && !m_verticalScrollbar)
- invalidateScrollCornerRect(oldScrollCornerRect);
- }
-
- IntPoint adjustedScrollPosition = IntPoint(desiredOffset);
- if (!isRubberBandInProgress())
- adjustedScrollPosition = adjustScrollPositionWithinRange(adjustedScrollPosition);
-
- if (adjustedScrollPosition != scrollPosition() || scrollOriginChanged()) {
- ScrollableArea::scrollToOffsetWithoutAnimation(adjustedScrollPosition);
- resetScrollOriginChanged();
- }
-
- // Make sure the scrollbar offsets are up to date.
- if (m_horizontalScrollbar)
- m_horizontalScrollbar->offsetDidChange();
- if (m_verticalScrollbar)
- m_verticalScrollbar->offsetDidChange();
-
- m_inUpdateScrollbars = false;
-}
-
-const int panIconSizeLength = 16;
-
-IntRect ScrollView::rectToCopyOnScroll() const
-{
- IntRect scrollViewRect = convertToRootView(IntRect(0, 0, visibleWidth(), visibleHeight()));
- if (hasOverlayScrollbars()) {
- int verticalScrollbarWidth = (verticalScrollbar() && !hasLayerForVerticalScrollbar()) ? verticalScrollbar()->width() : 0;
- int horizontalScrollbarHeight = (horizontalScrollbar() && !hasLayerForHorizontalScrollbar()) ? horizontalScrollbar()->height() : 0;
-
- scrollViewRect.setWidth(scrollViewRect.width() - verticalScrollbarWidth);
- scrollViewRect.setHeight(scrollViewRect.height() - horizontalScrollbarHeight);
- }
- return scrollViewRect;
-}
-
-void ScrollView::scrollContents(const IntSize& scrollDelta)
-{
- HostWindow* window = hostWindow();
- if (!window)
- return;
-
- // Since scrolling is double buffered, we will be blitting the scroll view's intersection
- // with the clip rect every time to keep it smooth.
- IntRect clipRect = windowClipRect();
- IntRect scrollViewRect = rectToCopyOnScroll();
- IntRect updateRect = clipRect;
- updateRect.intersect(scrollViewRect);
-
- if (m_drawPanScrollIcon) {
- // FIXME: the pan icon is broken when accelerated compositing is on, since it will draw under the compositing layers.
- // https://bugs.webkit.org/show_bug.cgi?id=47837
- int panIconDirtySquareSizeLength = 2 * (panIconSizeLength + max(abs(scrollDelta.width()), abs(scrollDelta.height()))); // We only want to repaint what's necessary
- IntPoint panIconDirtySquareLocation = IntPoint(m_panScrollIconPoint.x() - (panIconDirtySquareSizeLength / 2), m_panScrollIconPoint.y() - (panIconDirtySquareSizeLength / 2));
- IntRect panScrollIconDirtyRect = IntRect(panIconDirtySquareLocation, IntSize(panIconDirtySquareSizeLength, panIconDirtySquareSizeLength));
- panScrollIconDirtyRect.intersect(clipRect);
- window->invalidateContentsAndRootView(panScrollIconDirtyRect);
- }
-
- if (canBlitOnScroll()) { // The main frame can just blit the WebView window
- // FIXME: Find a way to scroll subframes with this faster path
- if (!scrollContentsFastPath(-scrollDelta, scrollViewRect, clipRect))
- scrollContentsSlowPath(updateRect);
- } else {
- // We need to go ahead and repaint the entire backing store. Do it now before moving the
- // windowed plugins.
- scrollContentsSlowPath(updateRect);
- }
-
- // Invalidate the overhang areas if they are visible.
- updateOverhangAreas();
-
- // This call will move children with native widgets (plugins) and invalidate them as well.
- frameRectsChanged();
-}
-
-bool ScrollView::scrollContentsFastPath(const IntSize& scrollDelta, const IntRect& rectToScroll, const IntRect& clipRect)
-{
- hostWindow()->scroll(scrollDelta, rectToScroll, clipRect);
- return true;
-}
-
-void ScrollView::scrollContentsSlowPath(const IntRect& updateRect)
-{
- hostWindow()->invalidateContentsForSlowScroll(updateRect);
-}
-
-IntPoint ScrollView::rootViewToContents(const IntPoint& rootViewPoint) const
-{
- IntPoint viewPoint = convertFromRootView(rootViewPoint);
- return viewPoint + scrollOffset();
-}
-
-IntPoint ScrollView::contentsToRootView(const IntPoint& contentsPoint) const
-{
- IntPoint viewPoint = contentsPoint - scrollOffset();
- return convertToRootView(viewPoint);
-}
-
-IntRect ScrollView::rootViewToContents(const IntRect& rootViewRect) const
-{
- IntRect viewRect = convertFromRootView(rootViewRect);
- viewRect.move(scrollOffset());
- return viewRect;
-}
-
-IntRect ScrollView::contentsToRootView(const IntRect& contentsRect) const
-{
- IntRect viewRect = contentsRect;
- viewRect.move(-scrollOffset());
- return convertToRootView(viewRect);
-}
-
-IntPoint ScrollView::windowToContents(const IntPoint& windowPoint) const
-{
- IntPoint viewPoint = convertFromContainingWindow(windowPoint);
- return viewPoint + scrollOffset();
-}
-
-IntPoint ScrollView::contentsToWindow(const IntPoint& contentsPoint) const
-{
- IntPoint viewPoint = contentsPoint - scrollOffset();
- return convertToContainingWindow(viewPoint);
-}
-
-IntRect ScrollView::windowToContents(const IntRect& windowRect) const
-{
- IntRect viewRect = convertFromContainingWindow(windowRect);
- viewRect.move(scrollOffset());
- return viewRect;
-}
-
-IntRect ScrollView::contentsToWindow(const IntRect& contentsRect) const
-{
- IntRect viewRect = contentsRect;
- viewRect.move(-scrollOffset());
- return convertToContainingWindow(viewRect);
-}
-
-IntRect ScrollView::contentsToScreen(const IntRect& rect) const
-{
- HostWindow* window = hostWindow();
- if (!window)
- return IntRect();
- return window->rootViewToScreen(contentsToRootView(rect));
-}
-
-IntPoint ScrollView::screenToContents(const IntPoint& point) const
-{
- HostWindow* window = hostWindow();
- if (!window)
- return IntPoint();
- return rootViewToContents(window->screenToRootView(point));
-}
-
-bool ScrollView::containsScrollbarsAvoidingResizer() const
-{
- return !m_scrollbarsAvoidingResizer;
-}
-
-void ScrollView::adjustScrollbarsAvoidingResizerCount(int overlapDelta)
-{
- int oldCount = m_scrollbarsAvoidingResizer;
- m_scrollbarsAvoidingResizer += overlapDelta;
- if (parent())
- parent()->adjustScrollbarsAvoidingResizerCount(overlapDelta);
- else if (!scrollbarsSuppressed()) {
- // If we went from n to 0 or from 0 to n and we're the outermost view,
- // we need to invalidate the windowResizerRect(), since it will now need to paint
- // differently.
- if ((oldCount > 0 && m_scrollbarsAvoidingResizer == 0) ||
- (oldCount == 0 && m_scrollbarsAvoidingResizer > 0))
- invalidateRect(windowResizerRect());
- }
-}
-
-void ScrollView::setParent(ScrollView* parentView)
-{
- if (parentView == parent())
- return;
-
- if (m_scrollbarsAvoidingResizer && parent())
- parent()->adjustScrollbarsAvoidingResizerCount(-m_scrollbarsAvoidingResizer);
-
- Widget::setParent(parentView);
-
- if (m_scrollbarsAvoidingResizer && parent())
- parent()->adjustScrollbarsAvoidingResizerCount(m_scrollbarsAvoidingResizer);
-}
-
-void ScrollView::setScrollbarsSuppressed(bool suppressed, bool repaintOnUnsuppress)
-{
- if (suppressed == m_scrollbarsSuppressed)
- return;
-
- m_scrollbarsSuppressed = suppressed;
-
- if (repaintOnUnsuppress && !suppressed) {
- if (m_horizontalScrollbar)
- m_horizontalScrollbar->invalidate();
- if (m_verticalScrollbar)
- m_verticalScrollbar->invalidate();
-
- // Invalidate the scroll corner too on unsuppress.
- invalidateRect(scrollCornerRect());
- }
-}
-
-Scrollbar* ScrollView::scrollbarAtPoint(const IntPoint& windowPoint)
-{
- IntPoint viewPoint = convertFromContainingWindow(windowPoint);
- if (m_horizontalScrollbar && m_horizontalScrollbar->shouldParticipateInHitTesting() && m_horizontalScrollbar->frameRect().contains(viewPoint))
- return m_horizontalScrollbar.get();
- if (m_verticalScrollbar && m_verticalScrollbar->shouldParticipateInHitTesting() && m_verticalScrollbar->frameRect().contains(viewPoint))
- return m_verticalScrollbar.get();
- return 0;
-}
-
-void ScrollView::setFrameRect(const IntRect& newRect)
-{
- IntRect oldRect = frameRect();
-
- if (newRect == oldRect)
- return;
-
- Widget::setFrameRect(newRect);
-
- frameRectsChanged();
-
- updateScrollbars(scrollOffset());
-
- if (!m_useFixedLayout && oldRect.size() != newRect.size())
- contentsResized();
-}
-
-void ScrollView::frameRectsChanged()
-{
- HashSet<RefPtr<Widget> >::const_iterator end = m_children.end();
- for (HashSet<RefPtr<Widget> >::const_iterator current = m_children.begin(); current != end; ++current)
- (*current)->frameRectsChanged();
-}
-
-void ScrollView::clipRectChanged()
-{
- HashSet<RefPtr<Widget> >::const_iterator end = m_children.end();
- for (HashSet<RefPtr<Widget> >::const_iterator current = m_children.begin(); current != end; ++current)
- (*current)->clipRectChanged();
-}
-
-static void positionScrollbarLayer(GraphicsLayer* graphicsLayer, Scrollbar* scrollbar)
-{
- if (!graphicsLayer || !scrollbar)
- return;
-
- IntRect scrollbarRect = scrollbar->frameRect();
- graphicsLayer->setPosition(scrollbarRect.location());
-
- if (scrollbarRect.size() == graphicsLayer->size())
- return;
-
- graphicsLayer->setSize(scrollbarRect.size());
-
- if (graphicsLayer->hasContentsLayer()) {
- graphicsLayer->setContentsRect(IntRect(0, 0, scrollbarRect.width(), scrollbarRect.height()));
- return;
- }
-
- graphicsLayer->setDrawsContent(true);
- graphicsLayer->setNeedsDisplay();
-}
-
-static void positionScrollCornerLayer(GraphicsLayer* graphicsLayer, const IntRect& cornerRect)
-{
- if (!graphicsLayer)
- return;
- graphicsLayer->setDrawsContent(!cornerRect.isEmpty());
- graphicsLayer->setPosition(cornerRect.location());
- if (cornerRect.size() != graphicsLayer->size())
- graphicsLayer->setNeedsDisplay();
- graphicsLayer->setSize(cornerRect.size());
-}
-
-void ScrollView::positionScrollbarLayers()
-{
- positionScrollbarLayer(layerForHorizontalScrollbar(), horizontalScrollbar());
- positionScrollbarLayer(layerForVerticalScrollbar(), verticalScrollbar());
- positionScrollCornerLayer(layerForScrollCorner(), scrollCornerRect());
-}
-
-bool ScrollView::userInputScrollable(ScrollbarOrientation orientation) const
-{
- ScrollbarMode mode = (orientation == HorizontalScrollbar) ?
- m_horizontalScrollbarMode : m_verticalScrollbarMode;
-
- return mode == ScrollbarAuto || mode == ScrollbarAlwaysOn;
-}
-
-bool ScrollView::shouldPlaceVerticalScrollbarOnLeft() const
-{
- return false;
-}
-
-void ScrollView::repaintContentRectangle(const IntRect& rect)
-{
- IntRect paintRect = rect;
- if (clipsRepaints() && !paintsEntireContents())
- paintRect.intersect(visibleContentRect());
- if (paintRect.isEmpty())
- return;
-
- if (HostWindow* window = hostWindow())
- window->invalidateContentsAndRootView(contentsToWindow(paintRect));
-}
-
-IntRect ScrollView::scrollCornerRect() const
-{
- IntRect cornerRect;
-
- if (hasOverlayScrollbars())
- return cornerRect;
-
- if (m_horizontalScrollbar && width() - m_horizontalScrollbar->width() > 0) {
- cornerRect.unite(IntRect(m_horizontalScrollbar->width(),
- height() - m_horizontalScrollbar->height(),
- width() - m_horizontalScrollbar->width(),
- m_horizontalScrollbar->height()));
- }
-
- if (m_verticalScrollbar && height() - m_verticalScrollbar->height() > 0) {
- cornerRect.unite(IntRect(width() - m_verticalScrollbar->width(),
- m_verticalScrollbar->height(),
- m_verticalScrollbar->width(),
- height() - m_verticalScrollbar->height()));
- }
-
- return cornerRect;
-}
-
-bool ScrollView::isScrollCornerVisible() const
-{
- return !scrollCornerRect().isEmpty();
-}
-
-void ScrollView::scrollbarStyleChanged(int, bool forceUpdate)
-{
- if (!forceUpdate)
- return;
-
- contentsResized();
- updateScrollbars(scrollOffset());
- positionScrollbarLayers();
-}
-
-void ScrollView::updateScrollCorner()
-{
-}
-
-void ScrollView::paintScrollCorner(GraphicsContext* context, const IntRect& cornerRect)
-{
- ScrollbarTheme::theme()->paintScrollCorner(this, context, cornerRect);
-}
-
-void ScrollView::paintScrollbar(GraphicsContext* context, Scrollbar* bar, const IntRect& rect)
-{
- bar->paint(context, rect);
-}
-
-void ScrollView::invalidateScrollCornerRect(const IntRect& rect)
-{
- invalidateRect(rect);
-}
-
-void ScrollView::paintScrollbars(GraphicsContext* context, const IntRect& rect)
-{
- if (m_horizontalScrollbar && !layerForHorizontalScrollbar())
- paintScrollbar(context, m_horizontalScrollbar.get(), rect);
- if (m_verticalScrollbar && !layerForVerticalScrollbar())
- paintScrollbar(context, m_verticalScrollbar.get(), rect);
-
- if (layerForScrollCorner())
- return;
- paintScrollCorner(context, scrollCornerRect());
-}
-
-void ScrollView::paintPanScrollIcon(GraphicsContext* context)
-{
- static Image* panScrollIcon = Image::loadPlatformResource("panIcon").leakRef();
- IntPoint iconGCPoint = m_panScrollIconPoint;
- if (parent())
- iconGCPoint = parent()->windowToContents(iconGCPoint);
- context->drawImage(panScrollIcon, iconGCPoint);
-}
-
-void ScrollView::paint(GraphicsContext* context, const IntRect& rect)
-{
- if (context->paintingDisabled() && !context->updatingControlTints())
- return;
-
- notifyPageThatContentAreaWillPaint();
-
- IntRect documentDirtyRect = rect;
- if (!paintsEntireContents()) {
- IntRect visibleAreaWithoutScrollbars(location(), visibleContentRect().size());
- documentDirtyRect.intersect(visibleAreaWithoutScrollbars);
- }
-
- if (!documentDirtyRect.isEmpty()) {
- GraphicsContextStateSaver stateSaver(*context);
-
- context->translate(x(), y());
- documentDirtyRect.moveBy(-location());
-
- if (!paintsEntireContents()) {
- context->translate(-scrollX(), -scrollY());
- documentDirtyRect.moveBy(scrollPosition());
-
- context->clip(visibleContentRect());
- }
-
- paintContents(context, documentDirtyRect);
- }
-
-#if USE(RUBBER_BANDING)
- if (!layerForOverhangAreas())
- calculateAndPaintOverhangAreas(context, rect);
-#else
- calculateAndPaintOverhangAreas(context, rect);
-#endif
-
- // Now paint the scrollbars.
- if (!m_scrollbarsSuppressed && (m_horizontalScrollbar || m_verticalScrollbar)) {
- GraphicsContextStateSaver stateSaver(*context);
- IntRect scrollViewDirtyRect = rect;
- IntRect visibleAreaWithScrollbars(location(), visibleContentRect(IncludeScrollbars).size());
- scrollViewDirtyRect.intersect(visibleAreaWithScrollbars);
- context->translate(x(), y());
- scrollViewDirtyRect.moveBy(-location());
-
- paintScrollbars(context, scrollViewDirtyRect);
- }
-
- // Paint the panScroll Icon
- if (m_drawPanScrollIcon)
- paintPanScrollIcon(context);
-}
-
-void ScrollView::calculateOverhangAreasForPainting(IntRect& horizontalOverhangRect, IntRect& verticalOverhangRect)
-{
- int verticalScrollbarWidth = (verticalScrollbar() && !verticalScrollbar()->isOverlayScrollbar())
- ? verticalScrollbar()->width() : 0;
- int horizontalScrollbarHeight = (horizontalScrollbar() && !horizontalScrollbar()->isOverlayScrollbar())
- ? horizontalScrollbar()->height() : 0;
-
- int physicalScrollY = scrollPosition().y() + scrollOrigin().y();
- if (physicalScrollY < 0) {
- horizontalOverhangRect = frameRect();
- horizontalOverhangRect.setHeight(-physicalScrollY);
- horizontalOverhangRect.setWidth(horizontalOverhangRect.width() - verticalScrollbarWidth);
- } else if (contentsHeight() && physicalScrollY > contentsHeight() - visibleHeight()) {
- int height = physicalScrollY - (contentsHeight() - visibleHeight());
- horizontalOverhangRect = frameRect();
- horizontalOverhangRect.setY(frameRect().maxY() - height - horizontalScrollbarHeight);
- horizontalOverhangRect.setHeight(height);
- horizontalOverhangRect.setWidth(horizontalOverhangRect.width() - verticalScrollbarWidth);
- }
-
- int physicalScrollX = scrollPosition().x() + scrollOrigin().x();
- if (physicalScrollX < 0) {
- verticalOverhangRect.setWidth(-physicalScrollX);
- verticalOverhangRect.setHeight(frameRect().height() - horizontalOverhangRect.height() - horizontalScrollbarHeight);
- verticalOverhangRect.setX(frameRect().x());
- if (horizontalOverhangRect.y() == frameRect().y())
- verticalOverhangRect.setY(frameRect().y() + horizontalOverhangRect.height());
- else
- verticalOverhangRect.setY(frameRect().y());
- } else if (contentsWidth() && physicalScrollX > contentsWidth() - visibleWidth()) {
- int width = physicalScrollX - (contentsWidth() - visibleWidth());
- verticalOverhangRect.setWidth(width);
- verticalOverhangRect.setHeight(frameRect().height() - horizontalOverhangRect.height() - horizontalScrollbarHeight);
- verticalOverhangRect.setX(frameRect().maxX() - width - verticalScrollbarWidth);
- if (horizontalOverhangRect.y() == frameRect().y())
- verticalOverhangRect.setY(frameRect().y() + horizontalOverhangRect.height());
- else
- verticalOverhangRect.setY(frameRect().y());
- }
-}
-
-void ScrollView::updateOverhangAreas()
-{
- HostWindow* window = hostWindow();
- if (!window)
- return;
-
- IntRect horizontalOverhangRect;
- IntRect verticalOverhangRect;
- calculateOverhangAreasForPainting(horizontalOverhangRect, verticalOverhangRect);
-#if USE(RUBBER_BANDING)
- if (GraphicsLayer* overhangLayer = layerForOverhangAreas()) {
- bool hasOverhangArea = !horizontalOverhangRect.isEmpty() || !verticalOverhangRect.isEmpty();
- overhangLayer->setDrawsContent(hasOverhangArea);
- if (hasOverhangArea)
- overhangLayer->setNeedsDisplay();
- }
-#endif
- if (!horizontalOverhangRect.isEmpty())
- window->invalidateContentsAndRootView(horizontalOverhangRect);
- if (!verticalOverhangRect.isEmpty())
- window->invalidateContentsAndRootView(verticalOverhangRect);
-}
-
-void ScrollView::paintOverhangAreas(GraphicsContext* context, const IntRect& horizontalOverhangRect, const IntRect& verticalOverhangRect, const IntRect& dirtyRect)
-{
- ScrollbarTheme::theme()->paintOverhangBackground(this, context, horizontalOverhangRect, verticalOverhangRect, dirtyRect);
- ScrollbarTheme::theme()->paintOverhangShadows(this, context, horizontalOverhangRect, verticalOverhangRect, dirtyRect);
-}
-
-void ScrollView::calculateAndPaintOverhangAreas(GraphicsContext* context, const IntRect& dirtyRect)
-{
- IntRect horizontalOverhangRect;
- IntRect verticalOverhangRect;
- calculateOverhangAreasForPainting(horizontalOverhangRect, verticalOverhangRect);
-
- if (dirtyRect.intersects(horizontalOverhangRect) || dirtyRect.intersects(verticalOverhangRect))
- paintOverhangAreas(context, horizontalOverhangRect, verticalOverhangRect, dirtyRect);
-}
-
-void ScrollView::calculateAndPaintOverhangBackground(GraphicsContext* context, const IntRect& dirtyRect)
-{
- IntRect horizontalOverhangRect;
- IntRect verticalOverhangRect;
- calculateOverhangAreasForPainting(horizontalOverhangRect, verticalOverhangRect);
-
- if (dirtyRect.intersects(horizontalOverhangRect) || dirtyRect.intersects(verticalOverhangRect))
- ScrollbarTheme::theme()->paintOverhangBackground(this, context, horizontalOverhangRect, verticalOverhangRect, dirtyRect);
-}
-
-bool ScrollView::isPointInScrollbarCorner(const IntPoint& windowPoint)
-{
- if (!scrollbarCornerPresent())
- return false;
-
- IntPoint viewPoint = convertFromContainingWindow(windowPoint);
-
- if (m_horizontalScrollbar) {
- int horizontalScrollbarYMin = m_horizontalScrollbar->frameRect().y();
- int horizontalScrollbarYMax = m_horizontalScrollbar->frameRect().y() + m_horizontalScrollbar->frameRect().height();
- int horizontalScrollbarXMin = m_horizontalScrollbar->frameRect().x() + m_horizontalScrollbar->frameRect().width();
-
- return viewPoint.y() > horizontalScrollbarYMin && viewPoint.y() < horizontalScrollbarYMax && viewPoint.x() > horizontalScrollbarXMin;
- }
-
- int verticalScrollbarXMin = m_verticalScrollbar->frameRect().x();
- int verticalScrollbarXMax = m_verticalScrollbar->frameRect().x() + m_verticalScrollbar->frameRect().width();
- int verticalScrollbarYMin = m_verticalScrollbar->frameRect().y() + m_verticalScrollbar->frameRect().height();
-
- return viewPoint.x() > verticalScrollbarXMin && viewPoint.x() < verticalScrollbarXMax && viewPoint.y() > verticalScrollbarYMin;
-}
-
-bool ScrollView::scrollbarCornerPresent() const
-{
- return (m_horizontalScrollbar && width() - m_horizontalScrollbar->width() > 0)
- || (m_verticalScrollbar && height() - m_verticalScrollbar->height() > 0);
-}
-
-IntRect ScrollView::convertFromScrollbarToContainingView(const Scrollbar* scrollbar, const IntRect& localRect) const
-{
- // Scrollbars won't be transformed within us
- IntRect newRect = localRect;
- newRect.moveBy(scrollbar->location());
- return newRect;
-}
-
-IntRect ScrollView::convertFromContainingViewToScrollbar(const Scrollbar* scrollbar, const IntRect& parentRect) const
-{
- IntRect newRect = parentRect;
- // Scrollbars won't be transformed within us
- newRect.moveBy(-scrollbar->location());
- return newRect;
-}
-
-// FIXME: test these on windows
-IntPoint ScrollView::convertFromScrollbarToContainingView(const Scrollbar* scrollbar, const IntPoint& localPoint) const
-{
- // Scrollbars won't be transformed within us
- IntPoint newPoint = localPoint;
- newPoint.moveBy(scrollbar->location());
- return newPoint;
-}
-
-IntPoint ScrollView::convertFromContainingViewToScrollbar(const Scrollbar* scrollbar, const IntPoint& parentPoint) const
-{
- IntPoint newPoint = parentPoint;
- // Scrollbars won't be transformed within us
- newPoint.moveBy(-scrollbar->location());
- return newPoint;
-}
-
-void ScrollView::setParentVisible(bool visible)
-{
- if (isParentVisible() == visible)
- return;
-
- Widget::setParentVisible(visible);
-
- if (!isSelfVisible())
- return;
-
- HashSet<RefPtr<Widget> >::iterator end = m_children.end();
- for (HashSet<RefPtr<Widget> >::iterator it = m_children.begin(); it != end; ++it)
- (*it)->setParentVisible(visible);
-}
-
-void ScrollView::show()
-{
- if (!isSelfVisible()) {
- setSelfVisible(true);
- if (isParentVisible()) {
- HashSet<RefPtr<Widget> >::iterator end = m_children.end();
- for (HashSet<RefPtr<Widget> >::iterator it = m_children.begin(); it != end; ++it)
- (*it)->setParentVisible(true);
- }
- }
-
- Widget::show();
-}
-
-void ScrollView::hide()
-{
- if (isSelfVisible()) {
- if (isParentVisible()) {
- HashSet<RefPtr<Widget> >::iterator end = m_children.end();
- for (HashSet<RefPtr<Widget> >::iterator it = m_children.begin(); it != end; ++it)
- (*it)->setParentVisible(false);
- }
- setSelfVisible(false);
- }
-
- Widget::hide();
-}
-
-bool ScrollView::isOffscreen() const
-{
- return !isVisible();
-}
-
-
-void ScrollView::addPanScrollIcon(const IntPoint& iconPosition)
-{
- HostWindow* window = hostWindow();
- if (!window)
- return;
- m_drawPanScrollIcon = true;
- m_panScrollIconPoint = IntPoint(iconPosition.x() - panIconSizeLength / 2 , iconPosition.y() - panIconSizeLength / 2) ;
- window->invalidateContentsAndRootView(IntRect(m_panScrollIconPoint, IntSize(panIconSizeLength, panIconSizeLength)));
-}
-
-void ScrollView::removePanScrollIcon()
-{
- HostWindow* window = hostWindow();
- if (!window)
- return;
- m_drawPanScrollIcon = false;
- window->invalidateContentsAndRootView(IntRect(m_panScrollIconPoint, IntSize(panIconSizeLength, panIconSizeLength)));
-}
-
-void ScrollView::setScrollOrigin(const IntPoint& origin, bool updatePositionAtAll, bool updatePositionSynchronously)
-{
- if (scrollOrigin() == origin)
- return;
-
- ScrollableArea::setScrollOrigin(origin);
-
- // Update if the scroll origin changes, since our position will be different if the content size did not change.
- if (updatePositionAtAll && updatePositionSynchronously)
- updateScrollbars(scrollOffset());
-}
-
-int ScrollView::pageStep(ScrollbarOrientation orientation) const
-{
- int length = (orientation == HorizontalScrollbar) ? visibleWidth() : visibleHeight();
- int minPageStep = static_cast<float>(length) * minFractionToStepWhenPaging();
- int pageStep = std::max(minPageStep, length - maxOverlapBetweenPages());
-
- return std::max(pageStep, 1);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/ScrollView.h b/chromium/third_party/WebKit/Source/core/platform/ScrollView.h
deleted file mode 100644
index bea72cfd8b3..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/ScrollView.h
+++ /dev/null
@@ -1,365 +0,0 @@
-/*
- * Copyright (C) 2004, 2006, 2007, 2008 Apple Inc. All rights reserved.
- * Copyright (C) 2009 Holger Hans Peter Freyther
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ScrollView_h
-#define ScrollView_h
-
-#include "core/platform/ScrollTypes.h"
-#include "core/platform/ScrollableArea.h"
-#include "core/platform/Scrollbar.h"
-#include "core/platform/Widget.h"
-#include "core/platform/graphics/IntRect.h"
-
-#include "wtf/HashSet.h"
-
-namespace WebCore {
-
-class HostWindow;
-class Scrollbar;
-
-class ScrollView : public Widget, public ScrollableArea {
-public:
- ~ScrollView();
-
- // ScrollableArea functions.
- virtual int scrollSize(ScrollbarOrientation) const OVERRIDE;
- virtual void setScrollOffset(const IntPoint&) OVERRIDE;
- virtual bool isScrollCornerVisible() const OVERRIDE;
- virtual void scrollbarStyleChanged(int newStyle, bool forceUpdate) OVERRIDE;
- virtual bool userInputScrollable(ScrollbarOrientation) const OVERRIDE;
- virtual bool shouldPlaceVerticalScrollbarOnLeft() const OVERRIDE;
-
- virtual void notifyPageThatContentAreaWillPaint() const;
-
- // NOTE: This should only be called by the overriden setScrollOffset from ScrollableArea.
- virtual void scrollTo(const IntSize& newOffset);
-
- // The window thats hosts the ScrollView. The ScrollView will communicate scrolls and repaints to the
- // host window in the window's coordinate space.
- virtual HostWindow* hostWindow() const = 0;
-
- // Returns a clip rect in host window coordinates. Used to clip the blit on a scroll.
- virtual IntRect windowClipRect(bool clipToContents = true) const = 0;
-
- // Functions for child manipulation and inspection.
- const HashSet<RefPtr<Widget> >* children() const { return &m_children; }
- virtual void addChild(PassRefPtr<Widget>);
- virtual void removeChild(Widget*);
-
- // If the scroll view does not use a native widget, then it will have cross-platform Scrollbars. These functions
- // can be used to obtain those scrollbars.
- virtual Scrollbar* horizontalScrollbar() const OVERRIDE { return m_horizontalScrollbar.get(); }
- virtual Scrollbar* verticalScrollbar() const OVERRIDE { return m_verticalScrollbar.get(); }
- bool isScrollViewScrollbar(const Widget* child) const { return horizontalScrollbar() == child || verticalScrollbar() == child; }
-
- void positionScrollbarLayers();
-
- // Functions for setting and retrieving the scrolling mode in each axis (horizontal/vertical). The mode has values of
- // AlwaysOff, AlwaysOn, and Auto. AlwaysOff means never show a scrollbar, AlwaysOn means always show a scrollbar.
- // Auto means show a scrollbar only when one is needed.
- // Note that for platforms with native widgets, these modes are considered advisory. In other words the underlying native
- // widget may choose not to honor the requested modes.
- void setScrollbarModes(ScrollbarMode horizontalMode, ScrollbarMode verticalMode, bool horizontalLock = false, bool verticalLock = false);
- void setHorizontalScrollbarMode(ScrollbarMode mode, bool lock = false) { setScrollbarModes(mode, verticalScrollbarMode(), lock, verticalScrollbarLock()); }
- void setVerticalScrollbarMode(ScrollbarMode mode, bool lock = false) { setScrollbarModes(horizontalScrollbarMode(), mode, horizontalScrollbarLock(), lock); };
- void scrollbarModes(ScrollbarMode& horizontalMode, ScrollbarMode& verticalMode) const;
- ScrollbarMode horizontalScrollbarMode() const { ScrollbarMode horizontal, vertical; scrollbarModes(horizontal, vertical); return horizontal; }
- ScrollbarMode verticalScrollbarMode() const { ScrollbarMode horizontal, vertical; scrollbarModes(horizontal, vertical); return vertical; }
-
- void setHorizontalScrollbarLock(bool lock = true) { m_horizontalScrollbarLock = lock; }
- bool horizontalScrollbarLock() const { return m_horizontalScrollbarLock; }
- void setVerticalScrollbarLock(bool lock = true) { m_verticalScrollbarLock = lock; }
- bool verticalScrollbarLock() const { return m_verticalScrollbarLock; }
-
- void setScrollingModesLock(bool lock = true) { m_horizontalScrollbarLock = m_verticalScrollbarLock = lock; }
-
- virtual void setCanHaveScrollbars(bool);
- bool canHaveScrollbars() const { return horizontalScrollbarMode() != ScrollbarAlwaysOff || verticalScrollbarMode() != ScrollbarAlwaysOff; }
-
- // By default you only receive paint events for the area that is visible. In the case of using a
- // tiled backing store, this function can be set, so that the view paints the entire contents.
- bool paintsEntireContents() const { return m_paintsEntireContents; }
- void setPaintsEntireContents(bool);
-
- // By default, paint events are clipped to the visible area. If set to
- // false, paint events are no longer clipped. paintsEntireContents() implies !clipsRepaints().
- bool clipsRepaints() const { return m_clipsRepaints; }
- void setClipsRepaints(bool);
-
- // Overridden by FrameView to create custom CSS scrollbars if applicable.
- virtual PassRefPtr<Scrollbar> createScrollbar(ScrollbarOrientation);
-
- // Whether or not a scroll view will blit visible contents when it is scrolled. Blitting is disabled in situations
- // where it would cause rendering glitches (such as with fixed backgrounds or when the view is partially transparent).
- void setCanBlitOnScroll(bool);
- bool canBlitOnScroll() const;
-
- // The visible content rect has a location that is the scrolled offset of the document. The width and height are the viewport width
- // and height. By default the scrollbars themselves are excluded from this rectangle, but an optional boolean argument allows them to be
- // included.
- virtual IntRect visibleContentRect(VisibleContentRectIncludesScrollbars = ExcludeScrollbars) const OVERRIDE;
- IntSize visibleSize() const { return visibleContentRect().size(); }
- virtual int visibleWidth() const OVERRIDE { return visibleContentRect().width(); }
- virtual int visibleHeight() const OVERRIDE { return visibleContentRect().height(); }
-
- // visibleContentRect().size() is computed from unscaledVisibleContentSize() divided by the value of visibleContentScaleFactor.
- // For the main frame, visibleContentScaleFactor is equal to the page's pageScaleFactor; it's 1 otherwise.
- IntSize unscaledVisibleContentSize(VisibleContentRectIncludesScrollbars = ExcludeScrollbars) const;
- virtual float visibleContentScaleFactor() const { return 1; }
-
- // Functions for getting/setting the size webkit should use to layout the contents. By default this is the same as the visible
- // content size. Explicitly setting a layout size value will cause webkit to layout the contents using this size instead.
- IntSize layoutSize(VisibleContentRectIncludesScrollbars = ExcludeScrollbars) const;
- int layoutWidth(VisibleContentRectIncludesScrollbars scrollbarInclusion = ExcludeScrollbars) const { return layoutSize(scrollbarInclusion).width(); }
- int layoutHeight(VisibleContentRectIncludesScrollbars scrollbarInclusion = ExcludeScrollbars) const { return layoutSize(scrollbarInclusion).height(); }
- IntSize fixedLayoutSize() const;
- void setFixedLayoutSize(const IntSize&);
- bool useFixedLayout() const;
- void setUseFixedLayout(bool enable);
-
- // Functions for getting/setting the size of the document contained inside the ScrollView (as an IntSize or as individual width and height
- // values).
- virtual IntSize contentsSize() const OVERRIDE; // Always at least as big as the visibleWidth()/visibleHeight().
- int contentsWidth() const { return contentsSize().width(); }
- int contentsHeight() const { return contentsSize().height(); }
- virtual void setContentsSize(const IntSize&);
-
- // Functions for querying the current scrolled position (both as a point, a size, or as individual X and Y values).
- virtual IntPoint scrollPosition() const OVERRIDE { return visibleContentRect().location(); }
- IntSize scrollOffset() const { return toIntSize(visibleContentRect().location()); } // Gets the scrolled position as an IntSize. Convenient for adding to other sizes.
- virtual IntPoint maximumScrollPosition() const OVERRIDE; // The maximum position we can be scrolled to.
- virtual IntPoint minimumScrollPosition() const OVERRIDE; // The minimum position we can be scrolled to.
- // Adjust the passed in scroll position to keep it between the minimum and maximum positions.
- IntPoint adjustScrollPositionWithinRange(const IntPoint&) const;
- int scrollX() const { return scrollPosition().x(); }
- int scrollY() const { return scrollPosition().y(); }
-
- virtual IntSize overhangAmount() const OVERRIDE;
-
- void cacheCurrentScrollPosition() { m_cachedScrollPosition = scrollPosition(); }
- IntPoint cachedScrollPosition() const { return m_cachedScrollPosition; }
-
- // Functions for scrolling the view.
- virtual void setScrollPosition(const IntPoint&);
- void scrollBy(const IntSize& s) { return setScrollPosition(scrollPosition() + s); }
-
- // A logical scroll that just ends up calling the corresponding physical scroll() based off the document's writing mode.
- bool logicalScroll(ScrollLogicalDirection, ScrollGranularity);
-
- // Scroll the actual contents of the view (either blitting or invalidating as needed).
- void scrollContents(const IntSize& scrollDelta);
-
- // This gives us a means of blocking painting on our scrollbars until the first layout has occurred.
- void setScrollbarsSuppressed(bool suppressed, bool repaintOnUnsuppress = false);
- bool scrollbarsSuppressed() const { return m_scrollbarsSuppressed; }
-
- IntPoint rootViewToContents(const IntPoint&) const;
- IntPoint contentsToRootView(const IntPoint&) const;
- IntRect rootViewToContents(const IntRect&) const;
- IntRect contentsToRootView(const IntRect&) const;
-
- // Event coordinates are assumed to be in the coordinate space of a window that contains
- // the entire widget hierarchy. It is up to the platform to decide what the precise definition
- // of containing window is. (For example on Mac it is the containing NSWindow.)
- IntPoint windowToContents(const IntPoint&) const;
- IntPoint contentsToWindow(const IntPoint&) const;
- IntRect windowToContents(const IntRect&) const;
- IntRect contentsToWindow(const IntRect&) const;
-
- // Functions for converting to and from screen coordinates.
- IntRect contentsToScreen(const IntRect&) const;
- IntPoint screenToContents(const IntPoint&) const;
-
- // The purpose of this function is to answer whether or not the scroll view is currently visible. Animations and painting updates can be suspended if
- // we know that we are either not in a window right now or if that window is not visible.
- bool isOffscreen() const;
-
- // These functions are used to enable scrollbars to avoid window resizer controls that overlap the scroll view. This happens on Mac
- // for example.
- virtual IntRect windowResizerRect() const { return IntRect(); }
- bool containsScrollbarsAvoidingResizer() const;
- void adjustScrollbarsAvoidingResizerCount(int overlapDelta);
- void windowResizerRectChanged();
-
- virtual void setParent(ScrollView*); // Overridden to update the overlapping scrollbar count.
-
- // Called when our frame rect changes (or the rect/scroll position of an ancestor changes).
- virtual void frameRectsChanged();
-
- // Widget override to update our scrollbars and notify our contents of the resize.
- virtual void setFrameRect(const IntRect&);
-
- // Widget override to notify our contents of a cliprect change.
- virtual void clipRectChanged() OVERRIDE;
-
- // For platforms that need to hit test scrollbars from within the engine's event handlers (like Win32).
- Scrollbar* scrollbarAtPoint(const IntPoint& windowPoint);
-
- IntPoint convertChildToSelf(const Widget* child, const IntPoint& point) const
- {
- IntPoint newPoint = point;
- if (!isScrollViewScrollbar(child))
- newPoint = point - scrollOffset();
- newPoint.moveBy(child->location());
- return newPoint;
- }
-
- IntPoint convertSelfToChild(const Widget* child, const IntPoint& point) const
- {
- IntPoint newPoint = point;
- if (!isScrollViewScrollbar(child))
- newPoint = point + scrollOffset();
- newPoint.moveBy(-child->location());
- return newPoint;
- }
-
- // Widget override. Handles painting of the contents of the view as well as the scrollbars.
- virtual void paint(GraphicsContext*, const IntRect&);
- void paintScrollbars(GraphicsContext*, const IntRect&);
-
- // Widget overrides to ensure that our children's visibility status is kept up to date when we get shown and hidden.
- virtual void show();
- virtual void hide();
- virtual void setParentVisible(bool);
-
- // Pan scrolling.
- static const int noPanScrollRadius = 15;
- void addPanScrollIcon(const IntPoint&);
- void removePanScrollIcon();
- void paintPanScrollIcon(GraphicsContext*);
-
- virtual bool isPointInScrollbarCorner(const IntPoint&);
- virtual bool scrollbarCornerPresent() const;
- virtual IntRect scrollCornerRect() const;
- virtual void paintScrollCorner(GraphicsContext*, const IntRect& cornerRect);
- virtual void paintScrollbar(GraphicsContext*, Scrollbar*, const IntRect&);
-
- virtual IntRect convertFromScrollbarToContainingView(const Scrollbar*, const IntRect&) const OVERRIDE;
- virtual IntRect convertFromContainingViewToScrollbar(const Scrollbar*, const IntRect&) const OVERRIDE;
- virtual IntPoint convertFromScrollbarToContainingView(const Scrollbar*, const IntPoint&) const OVERRIDE;
- virtual IntPoint convertFromContainingViewToScrollbar(const Scrollbar*, const IntPoint&) const OVERRIDE;
-
- void calculateAndPaintOverhangAreas(GraphicsContext*, const IntRect& dirtyRect);
- void calculateAndPaintOverhangBackground(GraphicsContext*, const IntRect& dirtyRect);
-
- virtual bool isScrollView() const OVERRIDE { return true; }
-
-protected:
- ScrollView();
-
- virtual void repaintContentRectangle(const IntRect&);
- virtual void paintContents(GraphicsContext*, const IntRect& damageRect) = 0;
-
- virtual void paintOverhangAreas(GraphicsContext*, const IntRect& horizontalOverhangArea, const IntRect& verticalOverhangArea, const IntRect& dirtyRect);
-
- virtual void visibleContentsResized() = 0;
- // These functions are used to create/destroy scrollbars.
- void setHasHorizontalScrollbar(bool);
- void setHasVerticalScrollbar(bool);
-
- virtual void updateScrollCorner();
- virtual void invalidateScrollCornerRect(const IntRect&) OVERRIDE;
-
- // Scroll the content by blitting the pixels.
- virtual bool scrollContentsFastPath(const IntSize& scrollDelta, const IntRect& rectToScroll, const IntRect& clipRect);
- // Scroll the content by invalidating everything.
- virtual void scrollContentsSlowPath(const IntRect& updateRect);
-
- void setScrollOrigin(const IntPoint&, bool updatePositionAtAll, bool updatePositionSynchronously);
-
- // Subclassed by FrameView to check the writing-mode of the document.
- virtual bool isVerticalDocument() const { return true; }
- virtual bool isFlippedDocument() const { return false; }
-
- // Called to update the scrollbars to accurately reflect the state of the view.
- void updateScrollbars(const IntSize& desiredOffset);
-
-private:
- RefPtr<Scrollbar> m_horizontalScrollbar;
- RefPtr<Scrollbar> m_verticalScrollbar;
- ScrollbarMode m_horizontalScrollbarMode;
- ScrollbarMode m_verticalScrollbarMode;
-
- bool m_horizontalScrollbarLock;
- bool m_verticalScrollbarLock;
-
- HashSet<RefPtr<Widget> > m_children;
-
- // This bool is unused on Mac OS because we directly ask the platform widget
- // whether it is safe to blit on scroll.
- bool m_canBlitOnScroll;
-
- IntSize m_scrollOffset; // FIXME: Would rather store this as a position, but we will wait to make this change until more code is shared.
- IntPoint m_cachedScrollPosition;
- IntSize m_fixedLayoutSize;
- IntSize m_contentsSize;
-
- int m_scrollbarsAvoidingResizer;
- bool m_scrollbarsSuppressed;
-
- bool m_inUpdateScrollbars;
- unsigned m_updateScrollbarsPass;
-
- IntPoint m_panScrollIconPoint;
- bool m_drawPanScrollIcon;
- bool m_useFixedLayout;
-
- bool m_paintsEntireContents;
- bool m_clipsRepaints;
-
- void init();
- void destroy();
-
- IntRect rectToCopyOnScroll() const;
-
- // Called when the scroll position within this view changes. FrameView overrides this to generate repaint invalidations.
- virtual void repaintFixedElementsAfterScrolling() { }
- virtual void updateFixedElementsAfterScrolling() { }
-
- void calculateOverhangAreasForPainting(IntRect& horizontalOverhangRect, IntRect& verticalOverhangRect);
- void updateOverhangAreas();
-
- int pageStep(ScrollbarOrientation) const;
-}; // class ScrollView
-
-inline ScrollView* toScrollView(Widget* widget)
-{
- ASSERT(!widget || widget->isScrollView());
- return static_cast<ScrollView*>(widget);
-}
-
-inline const ScrollView* toScrollView(const Widget* widget)
-{
- ASSERT(!widget || widget->isScrollView());
- return static_cast<const ScrollView*>(widget);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toScrollView(const ScrollView*);
-
-} // namespace WebCore
-
-#endif // ScrollView_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/ScrollableArea.cpp b/chromium/third_party/WebKit/Source/core/platform/ScrollableArea.cpp
deleted file mode 100644
index 8bb6bed3891..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/ScrollableArea.cpp
+++ /dev/null
@@ -1,420 +0,0 @@
-/*
- * Copyright (c) 2010, Google Inc. All rights reserved.
- * Copyright (C) 2008, 2011 Apple Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/ScrollableArea.h"
-
-#include "core/platform/ScrollAnimator.h"
-#include "core/platform/ScrollbarTheme.h"
-#include "core/platform/graphics/FloatPoint.h"
-#include "core/platform/graphics/GraphicsLayer.h"
-#include "wtf/PassOwnPtr.h"
-
-#include "core/platform/chromium/TraceEvent.h"
-
-static const int kPixelsPerLineStep = 40;
-static const float kMinFractionToStepWhenPaging = 0.875f;
-
-namespace WebCore {
-
-struct SameSizeAsScrollableArea {
- virtual ~SameSizeAsScrollableArea();
- void* pointer;
- unsigned bitfields : 16;
- IntPoint origin;
-};
-
-COMPILE_ASSERT(sizeof(ScrollableArea) == sizeof(SameSizeAsScrollableArea), ScrollableArea_should_stay_small);
-
-int ScrollableArea::pixelsPerLineStep()
-{
- return kPixelsPerLineStep;
-}
-
-float ScrollableArea::minFractionToStepWhenPaging()
-{
- return kMinFractionToStepWhenPaging;
-}
-
-int ScrollableArea::maxOverlapBetweenPages()
-{
- static int maxOverlapBetweenPages = ScrollbarTheme::theme()->maxOverlapBetweenPages();
- return maxOverlapBetweenPages;
-}
-
-ScrollableArea::ScrollableArea()
- : m_constrainsScrollingToContentEdge(true)
- , m_inLiveResize(false)
- , m_verticalScrollElasticity(ScrollElasticityNone)
- , m_horizontalScrollElasticity(ScrollElasticityNone)
- , m_scrollbarOverlayStyle(ScrollbarOverlayStyleDefault)
- , m_scrollOriginChanged(false)
-{
-}
-
-ScrollableArea::~ScrollableArea()
-{
-}
-
-ScrollAnimator* ScrollableArea::scrollAnimator() const
-{
- if (!m_scrollAnimator)
- m_scrollAnimator = ScrollAnimator::create(const_cast<ScrollableArea*>(this));
-
- return m_scrollAnimator.get();
-}
-
-void ScrollableArea::setScrollOrigin(const IntPoint& origin)
-{
- if (m_scrollOrigin != origin) {
- m_scrollOrigin = origin;
- m_scrollOriginChanged = true;
- }
-}
-
-bool ScrollableArea::scroll(ScrollDirection direction, ScrollGranularity granularity, float multiplier)
-{
- ScrollbarOrientation orientation;
-
- if (direction == ScrollUp || direction == ScrollDown)
- orientation = VerticalScrollbar;
- else
- orientation = HorizontalScrollbar;
-
- if (!userInputScrollable(orientation))
- return false;
-
- float step = 0;
- switch (granularity) {
- case ScrollByLine:
- step = lineStep(orientation);
- break;
- case ScrollByPage:
- step = pageStep(orientation);
- break;
- case ScrollByDocument:
- step = documentStep(orientation);
- break;
- case ScrollByPixel:
- case ScrollByPrecisePixel:
- step = pixelStep(orientation);
- break;
- }
-
- if (direction == ScrollUp || direction == ScrollLeft)
- multiplier = -multiplier;
-
- return scrollAnimator()->scroll(orientation, granularity, step, multiplier);
-}
-
-void ScrollableArea::scrollToOffsetWithoutAnimation(const FloatPoint& offset)
-{
- scrollAnimator()->scrollToOffsetWithoutAnimation(offset);
-}
-
-void ScrollableArea::scrollToOffsetWithoutAnimation(ScrollbarOrientation orientation, float offset)
-{
- if (orientation == HorizontalScrollbar)
- scrollToOffsetWithoutAnimation(FloatPoint(offset, scrollAnimator()->currentPosition().y()));
- else
- scrollToOffsetWithoutAnimation(FloatPoint(scrollAnimator()->currentPosition().x(), offset));
-}
-
-void ScrollableArea::notifyScrollPositionChanged(const IntPoint& position)
-{
- scrollPositionChanged(position);
- scrollAnimator()->setCurrentPosition(position);
-}
-
-void ScrollableArea::scrollPositionChanged(const IntPoint& position)
-{
- TRACE_EVENT0("webkit", "ScrollableArea::scrollPositionChanged");
-
- IntPoint oldPosition = scrollPosition();
- // Tell the derived class to scroll its contents.
- setScrollOffset(position);
-
- Scrollbar* verticalScrollbar = this->verticalScrollbar();
-
- // Tell the scrollbars to update their thumb postions.
- if (Scrollbar* horizontalScrollbar = this->horizontalScrollbar()) {
- horizontalScrollbar->offsetDidChange();
- if (horizontalScrollbar->isOverlayScrollbar() && !hasLayerForHorizontalScrollbar()) {
- if (!verticalScrollbar)
- horizontalScrollbar->invalidate();
- else {
- // If there is both a horizontalScrollbar and a verticalScrollbar,
- // then we must also invalidate the corner between them.
- IntRect boundsAndCorner = horizontalScrollbar->boundsRect();
- boundsAndCorner.setWidth(boundsAndCorner.width() + verticalScrollbar->width());
- horizontalScrollbar->invalidateRect(boundsAndCorner);
- }
- }
- }
- if (verticalScrollbar) {
- verticalScrollbar->offsetDidChange();
- if (verticalScrollbar->isOverlayScrollbar() && !hasLayerForVerticalScrollbar())
- verticalScrollbar->invalidate();
- }
-
- if (scrollPosition() != oldPosition)
- scrollAnimator()->notifyContentAreaScrolled(scrollPosition() - oldPosition);
-}
-
-bool ScrollableArea::handleWheelEvent(const PlatformWheelEvent& wheelEvent)
-{
- return scrollAnimator()->handleWheelEvent(wheelEvent);
-}
-
-// NOTE: Only called from Internals for testing.
-void ScrollableArea::setScrollOffsetFromInternals(const IntPoint& offset)
-{
- setScrollOffsetFromAnimation(offset);
-}
-
-void ScrollableArea::setScrollOffsetFromAnimation(const IntPoint& offset)
-{
- if (requestScrollPositionUpdate(offset))
- return;
-
- scrollPositionChanged(offset);
-}
-
-void ScrollableArea::willStartLiveResize()
-{
- if (m_inLiveResize)
- return;
- m_inLiveResize = true;
- if (ScrollAnimator* scrollAnimator = existingScrollAnimator())
- scrollAnimator->willStartLiveResize();
-}
-
-void ScrollableArea::willEndLiveResize()
-{
- if (!m_inLiveResize)
- return;
- m_inLiveResize = false;
- if (ScrollAnimator* scrollAnimator = existingScrollAnimator())
- scrollAnimator->willEndLiveResize();
-}
-
-void ScrollableArea::contentAreaWillPaint() const
-{
- if (ScrollAnimator* scrollAnimator = existingScrollAnimator())
- scrollAnimator->contentAreaWillPaint();
-}
-
-void ScrollableArea::mouseEnteredContentArea() const
-{
- if (ScrollAnimator* scrollAnimator = existingScrollAnimator())
- scrollAnimator->mouseEnteredContentArea();
-}
-
-void ScrollableArea::mouseExitedContentArea() const
-{
- if (ScrollAnimator* scrollAnimator = existingScrollAnimator())
- scrollAnimator->mouseEnteredContentArea();
-}
-
-void ScrollableArea::mouseMovedInContentArea() const
-{
- if (ScrollAnimator* scrollAnimator = existingScrollAnimator())
- scrollAnimator->mouseMovedInContentArea();
-}
-
-void ScrollableArea::mouseEnteredScrollbar(Scrollbar* scrollbar) const
-{
- scrollAnimator()->mouseEnteredScrollbar(scrollbar);
-}
-
-void ScrollableArea::mouseExitedScrollbar(Scrollbar* scrollbar) const
-{
- scrollAnimator()->mouseExitedScrollbar(scrollbar);
-}
-
-void ScrollableArea::contentAreaDidShow() const
-{
- if (ScrollAnimator* scrollAnimator = existingScrollAnimator())
- scrollAnimator->contentAreaDidShow();
-}
-
-void ScrollableArea::contentAreaDidHide() const
-{
- if (ScrollAnimator* scrollAnimator = existingScrollAnimator())
- scrollAnimator->contentAreaDidHide();
-}
-
-void ScrollableArea::finishCurrentScrollAnimations() const
-{
- if (ScrollAnimator* scrollAnimator = existingScrollAnimator())
- scrollAnimator->finishCurrentScrollAnimations();
-}
-
-void ScrollableArea::didAddVerticalScrollbar(Scrollbar* scrollbar)
-{
- scrollAnimator()->didAddVerticalScrollbar(scrollbar);
-
- // <rdar://problem/9797253> AppKit resets the scrollbar's style when you attach a scrollbar
- setScrollbarOverlayStyle(scrollbarOverlayStyle());
-}
-
-void ScrollableArea::willRemoveVerticalScrollbar(Scrollbar* scrollbar)
-{
- scrollAnimator()->willRemoveVerticalScrollbar(scrollbar);
-}
-
-void ScrollableArea::didAddHorizontalScrollbar(Scrollbar* scrollbar)
-{
- scrollAnimator()->didAddHorizontalScrollbar(scrollbar);
-
- // <rdar://problem/9797253> AppKit resets the scrollbar's style when you attach a scrollbar
- setScrollbarOverlayStyle(scrollbarOverlayStyle());
-}
-
-void ScrollableArea::willRemoveHorizontalScrollbar(Scrollbar* scrollbar)
-{
- scrollAnimator()->willRemoveHorizontalScrollbar(scrollbar);
-}
-
-void ScrollableArea::contentsResized()
-{
- if (ScrollAnimator* scrollAnimator = existingScrollAnimator())
- scrollAnimator->contentsResized();
-}
-
-bool ScrollableArea::hasOverlayScrollbars() const
-{
- return (verticalScrollbar() && verticalScrollbar()->isOverlayScrollbar())
- || (horizontalScrollbar() && horizontalScrollbar()->isOverlayScrollbar());
-}
-
-void ScrollableArea::setScrollbarOverlayStyle(ScrollbarOverlayStyle overlayStyle)
-{
- m_scrollbarOverlayStyle = overlayStyle;
-
- if (horizontalScrollbar()) {
- ScrollbarTheme::theme()->updateScrollbarOverlayStyle(horizontalScrollbar());
- horizontalScrollbar()->invalidate();
- }
-
- if (verticalScrollbar()) {
- ScrollbarTheme::theme()->updateScrollbarOverlayStyle(verticalScrollbar());
- verticalScrollbar()->invalidate();
- }
-}
-
-void ScrollableArea::invalidateScrollbar(Scrollbar* scrollbar, const IntRect& rect)
-{
- if (scrollbar == horizontalScrollbar()) {
- if (GraphicsLayer* graphicsLayer = layerForHorizontalScrollbar()) {
- graphicsLayer->setNeedsDisplay();
- graphicsLayer->setContentsNeedsDisplay();
- return;
- }
- } else if (scrollbar == verticalScrollbar()) {
- if (GraphicsLayer* graphicsLayer = layerForVerticalScrollbar()) {
- graphicsLayer->setNeedsDisplay();
- graphicsLayer->setContentsNeedsDisplay();
- return;
- }
- }
- invalidateScrollbarRect(scrollbar, rect);
-}
-
-void ScrollableArea::invalidateScrollCorner(const IntRect& rect)
-{
- if (GraphicsLayer* graphicsLayer = layerForScrollCorner()) {
- graphicsLayer->setNeedsDisplay();
- return;
- }
- invalidateScrollCornerRect(rect);
-}
-
-bool ScrollableArea::hasLayerForHorizontalScrollbar() const
-{
- return layerForHorizontalScrollbar();
-}
-
-bool ScrollableArea::hasLayerForVerticalScrollbar() const
-{
- return layerForVerticalScrollbar();
-}
-
-bool ScrollableArea::hasLayerForScrollCorner() const
-{
- return layerForScrollCorner();
-}
-
-void ScrollableArea::serviceScrollAnimations()
-{
- if (ScrollAnimator* scrollAnimator = existingScrollAnimator())
- scrollAnimator->serviceScrollAnimations();
-}
-
-IntRect ScrollableArea::visibleContentRect(VisibleContentRectIncludesScrollbars scrollbarInclusion) const
-{
- int verticalScrollbarWidth = 0;
- int horizontalScrollbarHeight = 0;
-
- if (scrollbarInclusion == IncludeScrollbars) {
- if (Scrollbar* verticalBar = verticalScrollbar())
- verticalScrollbarWidth = !verticalBar->isOverlayScrollbar() ? verticalBar->width() : 0;
- if (Scrollbar* horizontalBar = horizontalScrollbar())
- horizontalScrollbarHeight = !horizontalBar->isOverlayScrollbar() ? horizontalBar->height() : 0;
- }
-
- return IntRect(scrollPosition().x(),
- scrollPosition().y(),
- std::max(0, visibleWidth() + verticalScrollbarWidth),
- std::max(0, visibleHeight() + horizontalScrollbarHeight));
-}
-
-IntPoint ScrollableArea::clampScrollPosition(const IntPoint& scrollPosition) const
-{
- return scrollPosition.shrunkTo(maximumScrollPosition()).expandedTo(minimumScrollPosition());
-}
-
-int ScrollableArea::lineStep(ScrollbarOrientation) const
-{
- return pixelsPerLineStep();
-}
-
-int ScrollableArea::documentStep(ScrollbarOrientation orientation) const
-{
- return scrollSize(orientation);
-}
-
-float ScrollableArea::pixelStep(ScrollbarOrientation) const
-{
- return 1;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/ScrollableArea.h b/chromium/third_party/WebKit/Source/core/platform/ScrollableArea.h
deleted file mode 100644
index 46696686e02..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/ScrollableArea.h
+++ /dev/null
@@ -1,256 +0,0 @@
-/*
- * Copyright (C) 2008, 2011 Apple Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ScrollableArea_h
-#define ScrollableArea_h
-
-#include "core/platform/Scrollbar.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-class FloatPoint;
-class GraphicsContext;
-class GraphicsLayer;
-class PlatformGestureEvent;
-class PlatformWheelEvent;
-class ScrollAnimator;
-
-class ScrollableArea {
-public:
- static int pixelsPerLineStep();
- static float minFractionToStepWhenPaging();
- static int maxOverlapBetweenPages();
-
- bool scroll(ScrollDirection, ScrollGranularity, float multiplier = 1);
- void scrollToOffsetWithoutAnimation(const FloatPoint&);
- void scrollToOffsetWithoutAnimation(ScrollbarOrientation, float offset);
-
- // Should be called when the scroll position changes externally, for example if the scroll layer position
- // is updated on the scrolling thread and we need to notify the main thread.
- void notifyScrollPositionChanged(const IntPoint&);
-
- // Allows subclasses to handle scroll position updates themselves. If this member function
- // returns true, the scrollable area won't actually update the scroll position and instead
- // expect it to happen sometime in the future.
- virtual bool requestScrollPositionUpdate(const IntPoint&) { return false; }
-
- bool handleWheelEvent(const PlatformWheelEvent&);
-
- // Functions for controlling if you can scroll past the end of the document.
- bool constrainsScrollingToContentEdge() const { return m_constrainsScrollingToContentEdge; }
- void setConstrainsScrollingToContentEdge(bool constrainsScrollingToContentEdge) { m_constrainsScrollingToContentEdge = constrainsScrollingToContentEdge; }
-
- void setVerticalScrollElasticity(ScrollElasticity scrollElasticity) { m_verticalScrollElasticity = scrollElasticity; }
- ScrollElasticity verticalScrollElasticity() const { return static_cast<ScrollElasticity>(m_verticalScrollElasticity); }
-
- void setHorizontalScrollElasticity(ScrollElasticity scrollElasticity) { m_horizontalScrollElasticity = scrollElasticity; }
- ScrollElasticity horizontalScrollElasticity() const { return static_cast<ScrollElasticity>(m_horizontalScrollElasticity); }
-
- bool inLiveResize() const { return m_inLiveResize; }
- void willStartLiveResize();
- void willEndLiveResize();
-
- void contentAreaWillPaint() const;
- void mouseEnteredContentArea() const;
- void mouseExitedContentArea() const;
- void mouseMovedInContentArea() const;
- void mouseEnteredScrollbar(Scrollbar*) const;
- void mouseExitedScrollbar(Scrollbar*) const;
- void contentAreaDidShow() const;
- void contentAreaDidHide() const;
-
- void finishCurrentScrollAnimations() const;
-
- void didAddVerticalScrollbar(Scrollbar*);
- void willRemoveVerticalScrollbar(Scrollbar*);
- virtual void didAddHorizontalScrollbar(Scrollbar*);
- virtual void willRemoveHorizontalScrollbar(Scrollbar*);
-
- virtual void contentsResized();
-
- bool hasOverlayScrollbars() const;
- void setScrollbarOverlayStyle(ScrollbarOverlayStyle);
- ScrollbarOverlayStyle scrollbarOverlayStyle() const { return static_cast<ScrollbarOverlayStyle>(m_scrollbarOverlayStyle); }
-
- // This getter will create a ScrollAnimator if it doesn't already exist.
- ScrollAnimator* scrollAnimator() const;
-
- // This getter will return null if the ScrollAnimator hasn't been created yet.
- ScrollAnimator* existingScrollAnimator() const { return m_scrollAnimator.get(); }
-
- const IntPoint& scrollOrigin() const { return m_scrollOrigin; }
- bool scrollOriginChanged() const { return m_scrollOriginChanged; }
-
- virtual bool isActive() const = 0;
- virtual int scrollSize(ScrollbarOrientation) const = 0;
- virtual void invalidateScrollbar(Scrollbar*, const IntRect&);
- virtual bool isScrollCornerVisible() const = 0;
- virtual IntRect scrollCornerRect() const = 0;
- virtual void invalidateScrollCorner(const IntRect&);
- virtual void getTickmarks(Vector<IntRect>&) const { }
-
- // Convert points and rects between the scrollbar and its containing view.
- // The client needs to implement these in order to be aware of layout effects
- // like CSS transforms.
- virtual IntRect convertFromScrollbarToContainingView(const Scrollbar* scrollbar, const IntRect& scrollbarRect) const
- {
- return scrollbar->Widget::convertToContainingView(scrollbarRect);
- }
- virtual IntRect convertFromContainingViewToScrollbar(const Scrollbar* scrollbar, const IntRect& parentRect) const
- {
- return scrollbar->Widget::convertFromContainingView(parentRect);
- }
- virtual IntPoint convertFromScrollbarToContainingView(const Scrollbar* scrollbar, const IntPoint& scrollbarPoint) const
- {
- return scrollbar->Widget::convertToContainingView(scrollbarPoint);
- }
- virtual IntPoint convertFromContainingViewToScrollbar(const Scrollbar* scrollbar, const IntPoint& parentPoint) const
- {
- return scrollbar->Widget::convertFromContainingView(parentPoint);
- }
-
- virtual Scrollbar* horizontalScrollbar() const { return 0; }
- virtual Scrollbar* verticalScrollbar() const { return 0; }
-
- // scrollPosition is relative to the scrollOrigin. i.e. If the page is RTL
- // then scrollPosition will be negative.
- virtual IntPoint scrollPosition() const = 0;
- virtual IntPoint minimumScrollPosition() const = 0;
- virtual IntPoint maximumScrollPosition() const = 0;
-
- enum VisibleContentRectIncludesScrollbars { ExcludeScrollbars, IncludeScrollbars };
- virtual IntRect visibleContentRect(VisibleContentRectIncludesScrollbars = ExcludeScrollbars) const;
- virtual int visibleHeight() const = 0;
- virtual int visibleWidth() const = 0;
- virtual IntSize contentsSize() const = 0;
- virtual IntSize overhangAmount() const { return IntSize(); }
- virtual IntPoint lastKnownMousePosition() const { return IntPoint(); }
-
- virtual bool shouldSuspendScrollAnimations() const { return true; }
- virtual void scrollbarStyleChanged(int /*newStyle*/, bool /*forceUpdate*/) { }
-
- virtual bool scrollbarsCanBeActive() const = 0;
-
- // Note that this only returns scrollable areas that can actually be scrolled.
- virtual ScrollableArea* enclosingScrollableArea() const = 0;
-
- // Returns the bounding box of this scrollable area, in the coordinate system of the enclosing scroll view.
- virtual IntRect scrollableAreaBoundingBox() const = 0;
-
- virtual bool shouldRubberBandInDirection(ScrollDirection) const { return true; }
- virtual bool isRubberBandInProgress() const { return false; }
-
- virtual bool scrollAnimatorEnabled() const { return false; }
-
- // NOTE: Only called from Internals for testing.
- void setScrollOffsetFromInternals(const IntPoint&);
-
- IntPoint clampScrollPosition(const IntPoint&) const;
-
- // Let subclasses provide a way of asking for and servicing scroll
- // animations.
- virtual bool scheduleAnimation() { return false; }
- void serviceScrollAnimations();
-
- virtual bool usesCompositedScrolling() const { return false; }
- virtual void updateNeedsCompositedScrolling() { }
-
- virtual bool userInputScrollable(ScrollbarOrientation) const = 0;
- virtual bool shouldPlaceVerticalScrollbarOnLeft() const = 0;
-
- // Convenience functions
- int scrollPosition(ScrollbarOrientation orientation) { return orientation == HorizontalScrollbar ? scrollPosition().x() : scrollPosition().y(); }
- int minimumScrollPosition(ScrollbarOrientation orientation) { return orientation == HorizontalScrollbar ? minimumScrollPosition().x() : minimumScrollPosition().y(); }
- int maximumScrollPosition(ScrollbarOrientation orientation) { return orientation == HorizontalScrollbar ? maximumScrollPosition().x() : maximumScrollPosition().y(); }
- int clampScrollPosition(ScrollbarOrientation orientation, int pos) { return std::max(std::min(pos, maximumScrollPosition(orientation)), minimumScrollPosition(orientation)); }
-
-protected:
- ScrollableArea();
- virtual ~ScrollableArea();
-
- void setScrollOrigin(const IntPoint&);
- void resetScrollOriginChanged() { m_scrollOriginChanged = false; }
-
- virtual void invalidateScrollbarRect(Scrollbar*, const IntRect&) = 0;
- virtual void invalidateScrollCornerRect(const IntRect&) = 0;
-
- friend class ScrollingCoordinator;
- virtual GraphicsLayer* layerForScrolling() const { return 0; }
- virtual GraphicsLayer* layerForHorizontalScrollbar() const { return 0; }
- virtual GraphicsLayer* layerForVerticalScrollbar() const { return 0; }
- virtual GraphicsLayer* layerForScrollCorner() const { return 0; }
-#if USE(RUBBER_BANDING)
- virtual GraphicsLayer* layerForOverhangAreas() const { return 0; }
-#endif
- bool hasLayerForHorizontalScrollbar() const;
- bool hasLayerForVerticalScrollbar() const;
- bool hasLayerForScrollCorner() const;
-
-private:
- void scrollPositionChanged(const IntPoint&);
-
- // NOTE: Only called from the ScrollAnimator.
- friend class ScrollAnimator;
- void setScrollOffsetFromAnimation(const IntPoint&);
-
- // This function should be overriden by subclasses to perform the actual
- // scroll of the content.
- virtual void setScrollOffset(const IntPoint&) = 0;
-
- virtual int lineStep(ScrollbarOrientation) const;
- virtual int pageStep(ScrollbarOrientation) const = 0;
- virtual int documentStep(ScrollbarOrientation) const;
- virtual float pixelStep(ScrollbarOrientation) const;
-
- mutable OwnPtr<ScrollAnimator> m_scrollAnimator;
- unsigned m_constrainsScrollingToContentEdge : 1;
-
- unsigned m_inLiveResize : 1;
-
- unsigned m_verticalScrollElasticity : 2; // ScrollElasticity
- unsigned m_horizontalScrollElasticity : 2; // ScrollElasticity
-
- unsigned m_scrollbarOverlayStyle : 2; // ScrollbarOverlayStyle
-
- unsigned m_scrollOriginChanged : 1;
-
- // There are 8 possible combinations of writing mode and direction. Scroll origin will be non-zero in the x or y axis
- // if there is any reversed direction or writing-mode. The combinations are:
- // writing-mode / direction scrollOrigin.x() set scrollOrigin.y() set
- // horizontal-tb / ltr NO NO
- // horizontal-tb / rtl YES NO
- // horizontal-bt / ltr NO YES
- // horizontal-bt / rtl YES YES
- // vertical-lr / ltr NO NO
- // vertical-lr / rtl NO YES
- // vertical-rl / ltr YES NO
- // vertical-rl / rtl YES YES
- IntPoint m_scrollOrigin;
-};
-
-} // namespace WebCore
-
-#endif // ScrollableArea_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/Scrollbar.cpp b/chromium/third_party/WebKit/Source/core/platform/Scrollbar.cpp
deleted file mode 100644
index 96c712b1110..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/Scrollbar.cpp
+++ /dev/null
@@ -1,604 +0,0 @@
-/*
- * Copyright (C) 2004, 2006, 2008 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/Scrollbar.h"
-
-#include <algorithm>
-#include "core/platform/PlatformGestureEvent.h"
-#include "core/platform/PlatformMouseEvent.h"
-#include "core/platform/ScrollAnimator.h"
-#include "core/platform/ScrollableArea.h"
-#include "core/platform/ScrollbarTheme.h"
-#include "core/platform/graphics/GraphicsContext.h"
-
-// FIXME: The following #includes are a layering violation and should be removed.
-#include "core/accessibility/AXObjectCache.h"
-#include "core/page/EventHandler.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameView.h"
-
-using namespace std;
-
-#if OS(POSIX) && !OS(MACOSX)
-// The position of the scrollbar thumb affects the appearance of the steppers, so
-// when the thumb moves, we have to invalidate them for painting.
-#define THUMB_POSITION_AFFECTS_BUTTONS
-#endif
-
-namespace WebCore {
-
-PassRefPtr<Scrollbar> Scrollbar::create(ScrollableArea* scrollableArea, ScrollbarOrientation orientation, ScrollbarControlSize size)
-{
- return adoptRef(new Scrollbar(scrollableArea, orientation, size));
-}
-
-Scrollbar::Scrollbar(ScrollableArea* scrollableArea, ScrollbarOrientation orientation, ScrollbarControlSize controlSize, ScrollbarTheme* theme)
- : m_scrollableArea(scrollableArea)
- , m_orientation(orientation)
- , m_controlSize(controlSize)
- , m_theme(theme)
- , m_visibleSize(0)
- , m_totalSize(0)
- , m_currentPos(0)
- , m_dragOrigin(0)
- , m_hoveredPart(NoPart)
- , m_pressedPart(NoPart)
- , m_pressedPos(0)
- , m_scrollPos(0)
- , m_draggingDocument(false)
- , m_documentDragPos(0)
- , m_enabled(true)
- , m_scrollTimer(this, &Scrollbar::autoscrollTimerFired)
- , m_overlapsResizer(false)
- , m_suppressInvalidation(false)
- , m_isAlphaLocked(false)
-{
- if (!m_theme)
- m_theme = ScrollbarTheme::theme();
-
- m_theme->registerScrollbar(this);
-
- // FIXME: This is ugly and would not be necessary if we fix cross-platform code to actually query for
- // scrollbar thickness and use it when sizing scrollbars (rather than leaving one dimension of the scrollbar
- // alone when sizing).
- int thickness = m_theme->scrollbarThickness(controlSize);
- Widget::setFrameRect(IntRect(0, 0, thickness, thickness));
-
- m_currentPos = scrollableAreaCurrentPos();
-}
-
-Scrollbar::~Scrollbar()
-{
- if (AXObjectCache* cache = existingAXObjectCache())
- cache->remove(this);
-
- stopTimerIfNeeded();
-
- m_theme->unregisterScrollbar(this);
-}
-
-ScrollbarOverlayStyle Scrollbar::scrollbarOverlayStyle() const
-{
- return m_scrollableArea ? m_scrollableArea->scrollbarOverlayStyle() : ScrollbarOverlayStyleDefault;
-}
-
-void Scrollbar::getTickmarks(Vector<IntRect>& tickmarks) const
-{
- if (m_scrollableArea)
- m_scrollableArea->getTickmarks(tickmarks);
-}
-
-bool Scrollbar::isScrollableAreaActive() const
-{
- return m_scrollableArea && m_scrollableArea->isActive();
-}
-
-bool Scrollbar::isScrollViewScrollbar() const
-{
- return parent() && parent()->isFrameView() && toFrameView(parent())->isScrollViewScrollbar(this);
-}
-
-bool Scrollbar::isLeftSideVerticalScrollbar() const
-{
- if (m_orientation == VerticalScrollbar && m_scrollableArea)
- return m_scrollableArea->shouldPlaceVerticalScrollbarOnLeft();
- return false;
-}
-
-void Scrollbar::offsetDidChange()
-{
- ASSERT(m_scrollableArea);
-
- float position = scrollableAreaCurrentPos();
- if (position == m_currentPos)
- return;
-
- int oldThumbPosition = theme()->thumbPosition(this);
- m_currentPos = position;
- updateThumbPosition();
- if (m_pressedPart == ThumbPart)
- setPressedPos(m_pressedPos + theme()->thumbPosition(this) - oldThumbPosition);
-}
-
-void Scrollbar::setProportion(int visibleSize, int totalSize)
-{
- if (visibleSize == m_visibleSize && totalSize == m_totalSize)
- return;
-
- m_visibleSize = visibleSize;
- m_totalSize = totalSize;
-
- updateThumbProportion();
-}
-
-void Scrollbar::updateThumb()
-{
-#ifdef THUMB_POSITION_AFFECTS_BUTTONS
- invalidate();
-#else
- theme()->invalidateParts(this, ForwardTrackPart | BackTrackPart | ThumbPart);
-#endif
-}
-
-void Scrollbar::updateThumbPosition()
-{
- updateThumb();
-}
-
-void Scrollbar::updateThumbProportion()
-{
- updateThumb();
-}
-
-void Scrollbar::paint(GraphicsContext* context, const IntRect& damageRect)
-{
- if (context->updatingControlTints() && theme()->supportsControlTints()) {
- invalidate();
- return;
- }
-
- if (context->paintingDisabled() || !frameRect().intersects(damageRect))
- return;
-
- if (!theme()->paint(this, context, damageRect))
- Widget::paint(context, damageRect);
-}
-
-void Scrollbar::autoscrollTimerFired(Timer<Scrollbar>*)
-{
- autoscrollPressedPart(theme()->autoscrollTimerDelay());
-}
-
-static bool thumbUnderMouse(Scrollbar* scrollbar)
-{
- int thumbPos = scrollbar->theme()->trackPosition(scrollbar) + scrollbar->theme()->thumbPosition(scrollbar);
- int thumbLength = scrollbar->theme()->thumbLength(scrollbar);
- return scrollbar->pressedPos() >= thumbPos && scrollbar->pressedPos() < thumbPos + thumbLength;
-}
-
-void Scrollbar::autoscrollPressedPart(double delay)
-{
- // Don't do anything for the thumb or if nothing was pressed.
- if (m_pressedPart == ThumbPart || m_pressedPart == NoPart)
- return;
-
- // Handle the track.
- if ((m_pressedPart == BackTrackPart || m_pressedPart == ForwardTrackPart) && thumbUnderMouse(this)) {
- theme()->invalidatePart(this, m_pressedPart);
- setHoveredPart(ThumbPart);
- return;
- }
-
- // Handle the arrows and track.
- if (m_scrollableArea && m_scrollableArea->scroll(pressedPartScrollDirection(), pressedPartScrollGranularity()))
- startTimerIfNeeded(delay);
-}
-
-void Scrollbar::startTimerIfNeeded(double delay)
-{
- // Don't do anything for the thumb.
- if (m_pressedPart == ThumbPart)
- return;
-
- // Handle the track. We halt track scrolling once the thumb is level
- // with us.
- if ((m_pressedPart == BackTrackPart || m_pressedPart == ForwardTrackPart) && thumbUnderMouse(this)) {
- theme()->invalidatePart(this, m_pressedPart);
- setHoveredPart(ThumbPart);
- return;
- }
-
- // We can't scroll if we've hit the beginning or end.
- ScrollDirection dir = pressedPartScrollDirection();
- if (dir == ScrollUp || dir == ScrollLeft) {
- if (m_currentPos == 0)
- return;
- } else {
- if (m_currentPos == maximum())
- return;
- }
-
- m_scrollTimer.startOneShot(delay);
-}
-
-void Scrollbar::stopTimerIfNeeded()
-{
- if (m_scrollTimer.isActive())
- m_scrollTimer.stop();
-}
-
-ScrollDirection Scrollbar::pressedPartScrollDirection()
-{
- if (m_orientation == HorizontalScrollbar) {
- if (m_pressedPart == BackButtonStartPart || m_pressedPart == BackButtonEndPart || m_pressedPart == BackTrackPart)
- return ScrollLeft;
- return ScrollRight;
- } else {
- if (m_pressedPart == BackButtonStartPart || m_pressedPart == BackButtonEndPart || m_pressedPart == BackTrackPart)
- return ScrollUp;
- return ScrollDown;
- }
-}
-
-ScrollGranularity Scrollbar::pressedPartScrollGranularity()
-{
- if (m_pressedPart == BackButtonStartPart || m_pressedPart == BackButtonEndPart || m_pressedPart == ForwardButtonStartPart || m_pressedPart == ForwardButtonEndPart)
- return ScrollByLine;
- return ScrollByPage;
-}
-
-void Scrollbar::moveThumb(int pos, bool draggingDocument)
-{
- if (!m_scrollableArea)
- return;
-
- int delta = pos - m_pressedPos;
-
- if (draggingDocument) {
- if (m_draggingDocument)
- delta = pos - m_documentDragPos;
- m_draggingDocument = true;
- FloatPoint currentPosition = m_scrollableArea->scrollAnimator()->currentPosition();
- float destinationPosition = (m_orientation == HorizontalScrollbar ? currentPosition.x() : currentPosition.y()) + delta;
- destinationPosition = m_scrollableArea->clampScrollPosition(m_orientation, destinationPosition);
- m_scrollableArea->scrollToOffsetWithoutAnimation(m_orientation, destinationPosition);
- m_documentDragPos = pos;
- return;
- }
-
- if (m_draggingDocument) {
- delta += m_pressedPos - m_documentDragPos;
- m_draggingDocument = false;
- }
-
- // Drag the thumb.
- int thumbPos = theme()->thumbPosition(this);
- int thumbLen = theme()->thumbLength(this);
- int trackLen = theme()->trackLength(this);
- if (delta > 0)
- delta = min(trackLen - thumbLen - thumbPos, delta);
- else if (delta < 0)
- delta = max(-thumbPos, delta);
-
- float minPos = m_scrollableArea->minimumScrollPosition(m_orientation);
- float maxPos = m_scrollableArea->maximumScrollPosition(m_orientation);
- if (delta) {
- float newPosition = static_cast<float>(thumbPos + delta) * (maxPos - minPos) / (trackLen - thumbLen) + minPos;
- m_scrollableArea->scrollToOffsetWithoutAnimation(m_orientation, newPosition);
- }
-}
-
-void Scrollbar::setHoveredPart(ScrollbarPart part)
-{
- if (part == m_hoveredPart)
- return;
-
- if ((m_hoveredPart == NoPart || part == NoPart) && theme()->invalidateOnMouseEnterExit())
- invalidate(); // Just invalidate the whole scrollbar, since the buttons at either end change anyway.
- else if (m_pressedPart == NoPart) { // When there's a pressed part, we don't draw a hovered state, so there's no reason to invalidate.
- theme()->invalidatePart(this, part);
- theme()->invalidatePart(this, m_hoveredPart);
- }
- m_hoveredPart = part;
-}
-
-void Scrollbar::setPressedPart(ScrollbarPart part)
-{
- if (m_pressedPart != NoPart)
- theme()->invalidatePart(this, m_pressedPart);
- m_pressedPart = part;
- if (m_pressedPart != NoPart)
- theme()->invalidatePart(this, m_pressedPart);
- else if (m_hoveredPart != NoPart) // When we no longer have a pressed part, we can start drawing a hovered state on the hovered part.
- theme()->invalidatePart(this, m_hoveredPart);
-}
-
-bool Scrollbar::gestureEvent(const PlatformGestureEvent& evt)
-{
- bool handled = false;
- switch (evt.type()) {
- case PlatformEvent::GestureTapDown:
- setPressedPart(theme()->hitTest(this, evt.position()));
- m_pressedPos = (orientation() == HorizontalScrollbar ? convertFromContainingWindow(evt.position()).x() : convertFromContainingWindow(evt.position()).y());
- return true;
- case PlatformEvent::GestureTapDownCancel:
- case PlatformEvent::GestureScrollBegin:
- if (m_pressedPart == ThumbPart) {
- m_scrollPos = m_pressedPos;
- return true;
- }
- break;
- case PlatformEvent::GestureScrollUpdate:
- case PlatformEvent::GestureScrollUpdateWithoutPropagation:
- if (m_pressedPart == ThumbPart) {
- m_scrollPos += HorizontalScrollbar ? evt.deltaX() : evt.deltaY();
- moveThumb(m_scrollPos, false);
- return true;
- }
- break;
- case PlatformEvent::GestureScrollEnd:
- m_scrollPos = 0;
- break;
- case PlatformEvent::GestureTap:
- if (m_pressedPart != ThumbPart && m_pressedPart != NoPart)
- handled = m_scrollableArea && m_scrollableArea->scroll(pressedPartScrollDirection(), pressedPartScrollGranularity());
- break;
- default:
- break;
- }
- setPressedPart(NoPart);
- m_pressedPos = 0;
- return handled;
-}
-
-void Scrollbar::mouseMoved(const PlatformMouseEvent& evt)
-{
- if (m_pressedPart == ThumbPart) {
- if (theme()->shouldSnapBackToDragOrigin(this, evt)) {
- if (m_scrollableArea)
- m_scrollableArea->scrollToOffsetWithoutAnimation(m_orientation, m_dragOrigin);
- } else {
- moveThumb(m_orientation == HorizontalScrollbar ?
- convertFromContainingWindow(evt.position()).x() :
- convertFromContainingWindow(evt.position()).y(), theme()->shouldDragDocumentInsteadOfThumb(this, evt));
- }
- return;
- }
-
- if (m_pressedPart != NoPart)
- m_pressedPos = (orientation() == HorizontalScrollbar ? convertFromContainingWindow(evt.position()).x() : convertFromContainingWindow(evt.position()).y());
-
- ScrollbarPart part = theme()->hitTest(this, evt.position());
- if (part != m_hoveredPart) {
- if (m_pressedPart != NoPart) {
- if (part == m_pressedPart) {
- // The mouse is moving back over the pressed part. We
- // need to start up the timer action again.
- startTimerIfNeeded(theme()->autoscrollTimerDelay());
- theme()->invalidatePart(this, m_pressedPart);
- } else if (m_hoveredPart == m_pressedPart) {
- // The mouse is leaving the pressed part. Kill our timer
- // if needed.
- stopTimerIfNeeded();
- theme()->invalidatePart(this, m_pressedPart);
- }
- }
-
- setHoveredPart(part);
- }
-
- return;
-}
-
-void Scrollbar::mouseEntered()
-{
- if (m_scrollableArea)
- m_scrollableArea->mouseEnteredScrollbar(this);
-}
-
-void Scrollbar::mouseExited()
-{
- if (m_scrollableArea)
- m_scrollableArea->mouseExitedScrollbar(this);
- setHoveredPart(NoPart);
-}
-
-void Scrollbar::mouseUp(const PlatformMouseEvent& mouseEvent)
-{
- setPressedPart(NoPart);
- m_pressedPos = 0;
- m_draggingDocument = false;
- stopTimerIfNeeded();
-
- if (m_scrollableArea) {
- // m_hoveredPart won't be updated until the next mouseMoved or mouseDown, so we have to hit test
- // to really know if the mouse has exited the scrollbar on a mouseUp.
- ScrollbarPart part = theme()->hitTest(this, mouseEvent.position());
- if (part == NoPart)
- m_scrollableArea->mouseExitedScrollbar(this);
- }
-
- if (parent() && parent()->isFrameView())
- toFrameView(parent())->frame().eventHandler()->setMousePressed(false);
-}
-
-void Scrollbar::mouseDown(const PlatformMouseEvent& evt)
-{
- // Early exit for right click
- if (evt.button() == RightButton)
- return;
-
- setPressedPart(theme()->hitTest(this, evt.position()));
- int pressedPos = (orientation() == HorizontalScrollbar ? convertFromContainingWindow(evt.position()).x() : convertFromContainingWindow(evt.position()).y());
-
- if ((m_pressedPart == BackTrackPart || m_pressedPart == ForwardTrackPart) && theme()->shouldCenterOnThumb(this, evt)) {
- setHoveredPart(ThumbPart);
- setPressedPart(ThumbPart);
- m_dragOrigin = m_currentPos;
- int thumbLen = theme()->thumbLength(this);
- int desiredPos = pressedPos;
- // Set the pressed position to the middle of the thumb so that when we do the move, the delta
- // will be from the current pixel position of the thumb to the new desired position for the thumb.
- m_pressedPos = theme()->trackPosition(this) + theme()->thumbPosition(this) + thumbLen / 2;
- moveThumb(desiredPos);
- return;
- } else if (m_pressedPart == ThumbPart)
- m_dragOrigin = m_currentPos;
-
- m_pressedPos = pressedPos;
-
- autoscrollPressedPart(theme()->initialAutoscrollTimerDelay());
-}
-
-void Scrollbar::setFrameRect(const IntRect& rect)
-{
- // Get our window resizer rect and see if we overlap. Adjust to avoid the overlap
- // if necessary.
- IntRect adjustedRect(rect);
- bool overlapsResizer = false;
- ScrollView* view = parent();
- if (view && !rect.isEmpty() && !view->windowResizerRect().isEmpty()) {
- IntRect resizerRect = view->convertFromContainingWindow(view->windowResizerRect());
- if (rect.intersects(resizerRect)) {
- if (orientation() == HorizontalScrollbar) {
- int overlap = rect.maxX() - resizerRect.x();
- if (overlap > 0 && resizerRect.maxX() >= rect.maxX()) {
- adjustedRect.setWidth(rect.width() - overlap);
- overlapsResizer = true;
- }
- } else {
- int overlap = rect.maxY() - resizerRect.y();
- if (overlap > 0 && resizerRect.maxY() >= rect.maxY()) {
- adjustedRect.setHeight(rect.height() - overlap);
- overlapsResizer = true;
- }
- }
- }
- }
- if (overlapsResizer != m_overlapsResizer) {
- m_overlapsResizer = overlapsResizer;
- if (view)
- view->adjustScrollbarsAvoidingResizerCount(m_overlapsResizer ? 1 : -1);
- }
-
- Widget::setFrameRect(adjustedRect);
-}
-
-void Scrollbar::setParent(ScrollView* parentView)
-{
- if (!parentView && m_overlapsResizer && parent())
- parent()->adjustScrollbarsAvoidingResizerCount(-1);
- Widget::setParent(parentView);
-}
-
-void Scrollbar::setEnabled(bool e)
-{
- if (m_enabled == e)
- return;
- m_enabled = e;
- theme()->updateEnabledState(this);
- invalidate();
-}
-
-bool Scrollbar::isOverlayScrollbar() const
-{
- return m_theme->usesOverlayScrollbars();
-}
-
-bool Scrollbar::shouldParticipateInHitTesting()
-{
- // Non-overlay scrollbars should always participate in hit testing.
- if (!isOverlayScrollbar())
- return true;
- return m_scrollableArea->scrollAnimator()->shouldScrollbarParticipateInHitTesting(this);
-}
-
-bool Scrollbar::isWindowActive() const
-{
- return m_scrollableArea && m_scrollableArea->isActive();
-}
-
-AXObjectCache* Scrollbar::existingAXObjectCache() const
-{
- if (!parent())
- return 0;
-
- return parent()->axObjectCache();
-}
-
-void Scrollbar::invalidateRect(const IntRect& rect)
-{
- if (suppressInvalidation())
- return;
-
- if (m_scrollableArea)
- m_scrollableArea->invalidateScrollbar(this, rect);
-}
-
-IntRect Scrollbar::convertToContainingView(const IntRect& localRect) const
-{
- if (m_scrollableArea)
- return m_scrollableArea->convertFromScrollbarToContainingView(this, localRect);
-
- return Widget::convertToContainingView(localRect);
-}
-
-IntRect Scrollbar::convertFromContainingView(const IntRect& parentRect) const
-{
- if (m_scrollableArea)
- return m_scrollableArea->convertFromContainingViewToScrollbar(this, parentRect);
-
- return Widget::convertFromContainingView(parentRect);
-}
-
-IntPoint Scrollbar::convertToContainingView(const IntPoint& localPoint) const
-{
- if (m_scrollableArea)
- return m_scrollableArea->convertFromScrollbarToContainingView(this, localPoint);
-
- return Widget::convertToContainingView(localPoint);
-}
-
-IntPoint Scrollbar::convertFromContainingView(const IntPoint& parentPoint) const
-{
- if (m_scrollableArea)
- return m_scrollableArea->convertFromContainingViewToScrollbar(this, parentPoint);
-
- return Widget::convertFromContainingView(parentPoint);
-}
-
-float Scrollbar::scrollableAreaCurrentPos() const
-{
- if (!m_scrollableArea)
- return 0;
-
- if (m_orientation == HorizontalScrollbar)
- return m_scrollableArea->scrollPosition().x() - m_scrollableArea->minimumScrollPosition().x();
-
- return m_scrollableArea->scrollPosition().y() - m_scrollableArea->minimumScrollPosition().y();
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/Scrollbar.h b/chromium/third_party/WebKit/Source/core/platform/Scrollbar.h
deleted file mode 100644
index f8de1fa6a2d..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/Scrollbar.h
+++ /dev/null
@@ -1,197 +0,0 @@
-/*
- * Copyright (C) 2004, 2006 Apple Computer, Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef Scrollbar_h
-#define Scrollbar_h
-
-#include "core/platform/ScrollTypes.h"
-#include "core/platform/ScrollbarThemeClient.h"
-#include "core/platform/Timer.h"
-#include "core/platform/Widget.h"
-#include "wtf/MathExtras.h"
-#include "wtf/PassRefPtr.h"
-
-namespace WebCore {
-
-class GraphicsContext;
-class IntRect;
-class PlatformGestureEvent;
-class PlatformMouseEvent;
-class ScrollableArea;
-class ScrollbarTheme;
-
-class Scrollbar : public Widget,
- public ScrollbarThemeClient {
-
-public:
- static PassRefPtr<Scrollbar> create(ScrollableArea*, ScrollbarOrientation, ScrollbarControlSize);
-
- virtual ~Scrollbar();
-
- // ScrollbarThemeClient implementation.
- virtual int x() const { return Widget::x(); }
- virtual int y() const { return Widget::y(); }
- virtual int width() const { return Widget::width(); }
- virtual int height() const { return Widget::height(); }
- virtual IntSize size() const { return Widget::size(); }
- virtual IntPoint location() const { return Widget::location(); }
-
- virtual ScrollView* parent() const { return Widget::parent(); }
- virtual ScrollView* root() const { return Widget::root(); }
-
- virtual void setFrameRect(const IntRect&);
- virtual IntRect frameRect() const { return Widget::frameRect(); }
-
- virtual void invalidate() { Widget::invalidate(); }
- virtual void invalidateRect(const IntRect&);
-
- virtual ScrollbarOverlayStyle scrollbarOverlayStyle() const;
- virtual void getTickmarks(Vector<IntRect>&) const;
- virtual bool isScrollableAreaActive() const;
- virtual bool isScrollViewScrollbar() const;
-
- virtual IntPoint convertFromContainingWindow(const IntPoint& windowPoint) { return Widget::convertFromContainingWindow(windowPoint); }
-
- virtual bool isCustomScrollbar() const { return false; }
- virtual ScrollbarOrientation orientation() const { return m_orientation; }
- virtual bool isLeftSideVerticalScrollbar() const;
-
- virtual int value() const { return lroundf(m_currentPos); }
- virtual float currentPos() const { return m_currentPos; }
- virtual int visibleSize() const { return m_visibleSize; }
- virtual int totalSize() const { return m_totalSize; }
- virtual int maximum() const { return m_totalSize - m_visibleSize; }
- virtual ScrollbarControlSize controlSize() const { return m_controlSize; }
-
- virtual ScrollbarPart pressedPart() const { return m_pressedPart; }
- virtual ScrollbarPart hoveredPart() const { return m_hoveredPart; }
-
- virtual void styleChanged() { }
-
- virtual bool enabled() const { return m_enabled; }
- virtual void setEnabled(bool);
-
- // Called by the ScrollableArea when the scroll offset changes.
- void offsetDidChange();
-
- void disconnectFromScrollableArea() { m_scrollableArea = 0; }
- ScrollableArea* scrollableArea() const { return m_scrollableArea; }
-
- int pressedPos() const { return m_pressedPos; }
-
- virtual void setHoveredPart(ScrollbarPart);
- virtual void setPressedPart(ScrollbarPart);
-
- void setProportion(int visibleSize, int totalSize);
- void setPressedPos(int p) { m_pressedPos = p; }
-
- virtual void paint(GraphicsContext*, const IntRect& damageRect);
-
- virtual bool isOverlayScrollbar() const;
- bool shouldParticipateInHitTesting();
-
- bool isWindowActive() const;
-
- bool gestureEvent(const PlatformGestureEvent&);
-
- // These methods are used for platform scrollbars to give :hover feedback. They will not get called
- // when the mouse went down in a scrollbar, since it is assumed the scrollbar will start
- // grabbing all events in that case anyway.
- void mouseMoved(const PlatformMouseEvent&);
- void mouseEntered();
- void mouseExited();
-
- // Used by some platform scrollbars to know when they've been released from capture.
- void mouseUp(const PlatformMouseEvent&);
- void mouseDown(const PlatformMouseEvent&);
-
- ScrollbarTheme* theme() const { return m_theme; }
-
- virtual void setParent(ScrollView*);
-
- bool suppressInvalidation() const { return m_suppressInvalidation; }
- void setSuppressInvalidation(bool s) { m_suppressInvalidation = s; }
-
- virtual IntRect convertToContainingView(const IntRect&) const;
- virtual IntRect convertFromContainingView(const IntRect&) const;
-
- virtual IntPoint convertToContainingView(const IntPoint&) const;
- virtual IntPoint convertFromContainingView(const IntPoint&) const;
-
- void moveThumb(int pos, bool draggingDocument = false);
-
- virtual bool isAlphaLocked() const { return m_isAlphaLocked; }
- virtual void setIsAlphaLocked(bool flag) { m_isAlphaLocked = flag; }
-
-protected:
- Scrollbar(ScrollableArea*, ScrollbarOrientation, ScrollbarControlSize, ScrollbarTheme* = 0);
-
- void updateThumb();
- virtual void updateThumbPosition();
- virtual void updateThumbProportion();
-
- void autoscrollTimerFired(Timer<Scrollbar>*);
- void startTimerIfNeeded(double delay);
- void stopTimerIfNeeded();
- void autoscrollPressedPart(double delay);
- ScrollDirection pressedPartScrollDirection();
- ScrollGranularity pressedPartScrollGranularity();
-
- ScrollableArea* m_scrollableArea;
- ScrollbarOrientation m_orientation;
- ScrollbarControlSize m_controlSize;
- ScrollbarTheme* m_theme;
-
- int m_visibleSize;
- int m_totalSize;
- float m_currentPos;
- float m_dragOrigin;
-
- ScrollbarPart m_hoveredPart;
- ScrollbarPart m_pressedPart;
- int m_pressedPos;
- float m_scrollPos;
- bool m_draggingDocument;
- int m_documentDragPos;
-
- bool m_enabled;
-
- Timer<Scrollbar> m_scrollTimer;
- bool m_overlapsResizer;
-
- bool m_suppressInvalidation;
-
- bool m_isAlphaLocked;
-
-private:
- virtual bool isScrollbar() const { return true; }
- virtual AXObjectCache* existingAXObjectCache() const;
-
- float scrollableAreaCurrentPos() const;
-};
-
-} // namespace WebCore
-
-#endif // Scrollbar_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/ScrollbarTheme.cpp b/chromium/third_party/WebKit/Source/core/platform/ScrollbarTheme.cpp
deleted file mode 100644
index 4e910b0619a..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/ScrollbarTheme.cpp
+++ /dev/null
@@ -1,317 +0,0 @@
-/*
- * Copyright (C) 2011 Apple Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/ScrollbarTheme.h"
-
-#include "RuntimeEnabledFeatures.h"
-#include "core/page/Settings.h"
-#include "core/platform/ScrollbarThemeClient.h"
-#include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/mock/ScrollbarThemeMock.h"
-#include "core/platform/mock/ScrollbarThemeOverlayMock.h"
-
-namespace WebCore {
-
-ScrollbarTheme* ScrollbarTheme::theme()
-{
- if (Settings::mockScrollbarsEnabled()) {
- if (RuntimeEnabledFeatures::overlayScrollbarsEnabled()) {
- DEFINE_STATIC_LOCAL(ScrollbarThemeOverlayMock, overlayMockTheme, ());
- return &overlayMockTheme;
- }
-
- DEFINE_STATIC_LOCAL(ScrollbarThemeMock, mockTheme, ());
- return &mockTheme;
- }
- return nativeTheme();
-}
-
-bool ScrollbarTheme::paint(ScrollbarThemeClient* scrollbar, GraphicsContext* graphicsContext, const IntRect& damageRect)
-{
- // Create the ScrollbarControlPartMask based on the damageRect
- ScrollbarControlPartMask scrollMask = NoPart;
-
- IntRect backButtonStartPaintRect;
- IntRect backButtonEndPaintRect;
- IntRect forwardButtonStartPaintRect;
- IntRect forwardButtonEndPaintRect;
- if (hasButtons(scrollbar)) {
- backButtonStartPaintRect = backButtonRect(scrollbar, BackButtonStartPart, true);
- if (damageRect.intersects(backButtonStartPaintRect))
- scrollMask |= BackButtonStartPart;
- backButtonEndPaintRect = backButtonRect(scrollbar, BackButtonEndPart, true);
- if (damageRect.intersects(backButtonEndPaintRect))
- scrollMask |= BackButtonEndPart;
- forwardButtonStartPaintRect = forwardButtonRect(scrollbar, ForwardButtonStartPart, true);
- if (damageRect.intersects(forwardButtonStartPaintRect))
- scrollMask |= ForwardButtonStartPart;
- forwardButtonEndPaintRect = forwardButtonRect(scrollbar, ForwardButtonEndPart, true);
- if (damageRect.intersects(forwardButtonEndPaintRect))
- scrollMask |= ForwardButtonEndPart;
- }
-
- IntRect startTrackRect;
- IntRect thumbRect;
- IntRect endTrackRect;
- IntRect trackPaintRect = trackRect(scrollbar, true);
- if (damageRect.intersects(trackPaintRect))
- scrollMask |= TrackBGPart;
- bool thumbPresent = hasThumb(scrollbar);
- if (thumbPresent) {
- IntRect track = trackRect(scrollbar);
- splitTrack(scrollbar, track, startTrackRect, thumbRect, endTrackRect);
- if (damageRect.intersects(thumbRect))
- scrollMask |= ThumbPart;
- if (damageRect.intersects(startTrackRect))
- scrollMask |= BackTrackPart;
- if (damageRect.intersects(endTrackRect))
- scrollMask |= ForwardTrackPart;
- }
-
- // Paint the scrollbar background (only used by custom CSS scrollbars).
- paintScrollbarBackground(graphicsContext, scrollbar);
-
- // Paint the back and forward buttons.
- if (scrollMask & BackButtonStartPart)
- paintButton(graphicsContext, scrollbar, backButtonStartPaintRect, BackButtonStartPart);
- if (scrollMask & BackButtonEndPart)
- paintButton(graphicsContext, scrollbar, backButtonEndPaintRect, BackButtonEndPart);
- if (scrollMask & ForwardButtonStartPart)
- paintButton(graphicsContext, scrollbar, forwardButtonStartPaintRect, ForwardButtonStartPart);
- if (scrollMask & ForwardButtonEndPart)
- paintButton(graphicsContext, scrollbar, forwardButtonEndPaintRect, ForwardButtonEndPart);
-
- if (scrollMask & TrackBGPart)
- paintTrackBackground(graphicsContext, scrollbar, trackPaintRect);
-
- if ((scrollMask & ForwardTrackPart) || (scrollMask & BackTrackPart)) {
- // Paint the track pieces above and below the thumb.
- if (scrollMask & BackTrackPart)
- paintTrackPiece(graphicsContext, scrollbar, startTrackRect, BackTrackPart);
- if (scrollMask & ForwardTrackPart)
- paintTrackPiece(graphicsContext, scrollbar, endTrackRect, ForwardTrackPart);
-
- paintTickmarks(graphicsContext, scrollbar, trackPaintRect);
- }
-
- // Paint the thumb.
- if (scrollMask & ThumbPart)
- paintThumb(graphicsContext, scrollbar, thumbRect);
-
- return true;
-}
-
-ScrollbarPart ScrollbarTheme::hitTest(ScrollbarThemeClient* scrollbar, const IntPoint& position)
-{
- ScrollbarPart result = NoPart;
- if (!scrollbar->enabled())
- return result;
-
- IntPoint testPosition = scrollbar->convertFromContainingWindow(position);
- testPosition.move(scrollbar->x(), scrollbar->y());
-
- if (!scrollbar->frameRect().contains(testPosition))
- return NoPart;
-
- result = ScrollbarBGPart;
-
- IntRect track = trackRect(scrollbar);
- if (track.contains(testPosition)) {
- IntRect beforeThumbRect;
- IntRect thumbRect;
- IntRect afterThumbRect;
- splitTrack(scrollbar, track, beforeThumbRect, thumbRect, afterThumbRect);
- if (thumbRect.contains(testPosition))
- result = ThumbPart;
- else if (beforeThumbRect.contains(testPosition))
- result = BackTrackPart;
- else if (afterThumbRect.contains(testPosition))
- result = ForwardTrackPart;
- else
- result = TrackBGPart;
- } else if (backButtonRect(scrollbar, BackButtonStartPart).contains(testPosition)) {
- result = BackButtonStartPart;
- } else if (backButtonRect(scrollbar, BackButtonEndPart).contains(testPosition)) {
- result = BackButtonEndPart;
- } else if (forwardButtonRect(scrollbar, ForwardButtonStartPart).contains(testPosition)) {
- result = ForwardButtonStartPart;
- } else if (forwardButtonRect(scrollbar, ForwardButtonEndPart).contains(testPosition)) {
- result = ForwardButtonEndPart;
- }
- return result;
-}
-
-void ScrollbarTheme::invalidatePart(ScrollbarThemeClient* scrollbar, ScrollbarPart part)
-{
- if (part == NoPart)
- return;
-
- IntRect result;
- switch (part) {
- case BackButtonStartPart:
- result = backButtonRect(scrollbar, BackButtonStartPart, true);
- break;
- case BackButtonEndPart:
- result = backButtonRect(scrollbar, BackButtonEndPart, true);
- break;
- case ForwardButtonStartPart:
- result = forwardButtonRect(scrollbar, ForwardButtonStartPart, true);
- break;
- case ForwardButtonEndPart:
- result = forwardButtonRect(scrollbar, ForwardButtonEndPart, true);
- break;
- case TrackBGPart:
- result = trackRect(scrollbar, true);
- break;
- case ScrollbarBGPart:
- result = scrollbar->frameRect();
- break;
- default: {
- IntRect beforeThumbRect, thumbRect, afterThumbRect;
- splitTrack(scrollbar, trackRect(scrollbar), beforeThumbRect, thumbRect, afterThumbRect);
- if (part == BackTrackPart)
- result = beforeThumbRect;
- else if (part == ForwardTrackPart)
- result = afterThumbRect;
- else
- result = thumbRect;
- }
- }
- result.moveBy(-scrollbar->location());
- scrollbar->invalidateRect(result);
-}
-
-void ScrollbarTheme::splitTrack(ScrollbarThemeClient* scrollbar, const IntRect& unconstrainedTrackRect, IntRect& beforeThumbRect, IntRect& thumbRect, IntRect& afterThumbRect)
-{
- // This function won't even get called unless we're big enough to have some combination of these three rects where at least
- // one of them is non-empty.
- IntRect trackRect = constrainTrackRectToTrackPieces(scrollbar, unconstrainedTrackRect);
- int thumbPos = thumbPosition(scrollbar);
- if (scrollbar->orientation() == HorizontalScrollbar) {
- thumbRect = IntRect(trackRect.x() + thumbPos, trackRect.y(), thumbLength(scrollbar), scrollbar->height());
- beforeThumbRect = IntRect(trackRect.x(), trackRect.y(), thumbPos + thumbRect.width() / 2, trackRect.height());
- afterThumbRect = IntRect(trackRect.x() + beforeThumbRect.width(), trackRect.y(), trackRect.maxX() - beforeThumbRect.maxX(), trackRect.height());
- } else {
- thumbRect = IntRect(trackRect.x(), trackRect.y() + thumbPos, scrollbar->width(), thumbLength(scrollbar));
- beforeThumbRect = IntRect(trackRect.x(), trackRect.y(), trackRect.width(), thumbPos + thumbRect.height() / 2);
- afterThumbRect = IntRect(trackRect.x(), trackRect.y() + beforeThumbRect.height(), trackRect.width(), trackRect.maxY() - beforeThumbRect.maxY());
- }
-}
-
-// Returns the size represented by track taking into account scrolling past
-// the end of the document.
-static float usedTotalSize(ScrollbarThemeClient* scrollbar)
-{
- float overhangAtStart = -scrollbar->currentPos();
- float overhangAtEnd = scrollbar->currentPos() + scrollbar->visibleSize() - scrollbar->totalSize();
- float overhang = std::max(0.0f, std::max(overhangAtStart, overhangAtEnd));
- return scrollbar->totalSize() + overhang;
-}
-
-int ScrollbarTheme::thumbPosition(ScrollbarThemeClient* scrollbar)
-{
- if (scrollbar->enabled()) {
- float size = usedTotalSize(scrollbar) - scrollbar->visibleSize();
- // Avoid doing a floating point divide by zero and return 1 when usedTotalSize == visibleSize.
- if (!size)
- return 1;
- float pos = std::max(0.0f, scrollbar->currentPos()) * (trackLength(scrollbar) - thumbLength(scrollbar)) / size;
- return (pos < 1 && pos > 0) ? 1 : pos;
- }
- return 0;
-}
-
-int ScrollbarTheme::thumbLength(ScrollbarThemeClient* scrollbar)
-{
- if (!scrollbar->enabled())
- return 0;
-
- float overhang = 0;
- if (scrollbar->currentPos() < 0)
- overhang = -scrollbar->currentPos();
- else if (scrollbar->visibleSize() + scrollbar->currentPos() > scrollbar->totalSize())
- overhang = scrollbar->currentPos() + scrollbar->visibleSize() - scrollbar->totalSize();
- float proportion = (scrollbar->visibleSize() - overhang) / usedTotalSize(scrollbar);
- int trackLen = trackLength(scrollbar);
- int length = round(proportion * trackLen);
- length = std::max(length, minimumThumbLength(scrollbar));
- if (length > trackLen)
- length = 0; // Once the thumb is below the track length, it just goes away (to make more room for the track).
- return length;
-}
-
-int ScrollbarTheme::minimumThumbLength(ScrollbarThemeClient* scrollbar)
-{
- return scrollbarThickness(scrollbar->controlSize());
-}
-
-int ScrollbarTheme::trackPosition(ScrollbarThemeClient* scrollbar)
-{
- IntRect constrainedTrackRect = constrainTrackRectToTrackPieces(scrollbar, trackRect(scrollbar));
- return (scrollbar->orientation() == HorizontalScrollbar) ? constrainedTrackRect.x() - scrollbar->x() : constrainedTrackRect.y() - scrollbar->y();
-}
-
-int ScrollbarTheme::trackLength(ScrollbarThemeClient* scrollbar)
-{
- IntRect constrainedTrackRect = constrainTrackRectToTrackPieces(scrollbar, trackRect(scrollbar));
- return (scrollbar->orientation() == HorizontalScrollbar) ? constrainedTrackRect.width() : constrainedTrackRect.height();
-}
-
-void ScrollbarTheme::paintScrollCorner(ScrollView*, GraphicsContext* context, const IntRect& cornerRect)
-{
- context->fillRect(cornerRect, Color::white);
-}
-
-IntRect ScrollbarTheme::thumbRect(ScrollbarThemeClient* scrollbar)
-{
- if (!hasThumb(scrollbar))
- return IntRect();
-
- IntRect track = trackRect(scrollbar);
- IntRect startTrackRect;
- IntRect thumbRect;
- IntRect endTrackRect;
- splitTrack(scrollbar, track, startTrackRect, thumbRect, endTrackRect);
-
- return thumbRect;
-}
-
-int ScrollbarTheme::thumbThickness(ScrollbarThemeClient* scrollbar)
-{
- IntRect track = trackRect(scrollbar);
- return scrollbar->orientation() == HorizontalScrollbar ? track.height() : track.width();
-}
-
-void ScrollbarTheme::paintOverhangBackground(ScrollView*, GraphicsContext* context, const IntRect& horizontalOverhangRect, const IntRect& verticalOverhangRect, const IntRect& dirtyRect)
-{
- context->setFillColor(Color::white);
- if (!horizontalOverhangRect.isEmpty())
- context->fillRect(intersection(horizontalOverhangRect, dirtyRect));
- if (!verticalOverhangRect.isEmpty())
- context->fillRect(intersection(verticalOverhangRect, dirtyRect));
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/ScrollbarTheme.h b/chromium/third_party/WebKit/Source/core/platform/ScrollbarTheme.h
deleted file mode 100644
index 12b48291ecd..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/ScrollbarTheme.h
+++ /dev/null
@@ -1,146 +0,0 @@
-/*
- * Copyright (C) 2008 Apple Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ScrollbarTheme_h
-#define ScrollbarTheme_h
-
-#include "core/platform/ScrollTypes.h"
-#include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/graphics/IntRect.h"
-
-namespace WebCore {
-
-class PlatformMouseEvent;
-class ScrollbarThemeClient;
-class ScrollView;
-
-#if USE(RUBBER_BANDING)
-class GraphicsLayer;
-#endif
-
-class ScrollbarTheme {
- WTF_MAKE_NONCOPYABLE(ScrollbarTheme); WTF_MAKE_FAST_ALLOCATED;
-public:
- ScrollbarTheme() { }
- virtual ~ScrollbarTheme() { }
-
- virtual void updateEnabledState(ScrollbarThemeClient*) { }
-
- virtual bool paint(ScrollbarThemeClient*, GraphicsContext*, const IntRect& damageRect);
- virtual ScrollbarPart hitTest(ScrollbarThemeClient*, const IntPoint&);
-
- virtual int scrollbarThickness(ScrollbarControlSize = RegularScrollbar) { return 0; }
-
- virtual ScrollbarButtonsPlacement buttonsPlacement() const { return ScrollbarButtonsSingle; }
-
- virtual bool supportsControlTints() const { return false; }
- virtual bool usesOverlayScrollbars() const { return false; }
- virtual void updateScrollbarOverlayStyle(ScrollbarThemeClient*) { }
-
- virtual bool invalidateOnMouseEnterExit() { return false; }
-
- void invalidateParts(ScrollbarThemeClient* scrollbar, ScrollbarControlPartMask mask)
- {
- if (mask & BackButtonStartPart)
- invalidatePart(scrollbar, BackButtonStartPart);
- if (mask & ForwardButtonStartPart)
- invalidatePart(scrollbar, ForwardButtonStartPart);
- if (mask & BackTrackPart)
- invalidatePart(scrollbar, BackTrackPart);
- if (mask & ThumbPart)
- invalidatePart(scrollbar, ThumbPart);
- if (mask & ForwardTrackPart)
- invalidatePart(scrollbar, ForwardTrackPart);
- if (mask & BackButtonEndPart)
- invalidatePart(scrollbar, BackButtonEndPart);
- if (mask & ForwardButtonEndPart)
- invalidatePart(scrollbar, ForwardButtonEndPart);
- }
-
- virtual void invalidatePart(ScrollbarThemeClient*, ScrollbarPart);
-
- virtual void paintScrollCorner(ScrollView*, GraphicsContext*, const IntRect& cornerRect);
-
- virtual void paintTickmarks(GraphicsContext*, ScrollbarThemeClient*, const IntRect&) { }
- virtual void paintOverhangBackground(ScrollView*, GraphicsContext*, const IntRect&, const IntRect&, const IntRect&);
- virtual void paintOverhangShadows(ScrollView*, GraphicsContext*, const IntRect&, const IntRect&, const IntRect&) { }
-
-#if USE(RUBBER_BANDING)
- virtual void setUpOverhangShadowLayer(GraphicsLayer*) { }
- virtual void updateOverhangShadowLayer(GraphicsLayer* shadowLayer, GraphicsLayer* rootContentLayer) { }
-#endif
-
- virtual bool shouldCenterOnThumb(ScrollbarThemeClient*, const PlatformMouseEvent&) { return false; }
- virtual bool shouldSnapBackToDragOrigin(ScrollbarThemeClient*, const PlatformMouseEvent&) { return false; }
- virtual bool shouldDragDocumentInsteadOfThumb(ScrollbarThemeClient*, const PlatformMouseEvent&) { return false; }
-
- // The position of the thumb relative to the track.
- virtual int thumbPosition(ScrollbarThemeClient*);
- // The length of the thumb along the axis of the scrollbar.
- virtual int thumbLength(ScrollbarThemeClient*);
- // The position of the track relative to the scrollbar.
- virtual int trackPosition(ScrollbarThemeClient*);
- // The length of the track along the axis of the scrollbar.
- virtual int trackLength(ScrollbarThemeClient*);
-
- virtual bool hasButtons(ScrollbarThemeClient*) = 0;
- virtual bool hasThumb(ScrollbarThemeClient*) = 0;
-
- virtual IntRect backButtonRect(ScrollbarThemeClient*, ScrollbarPart, bool painting = false) = 0;
- virtual IntRect forwardButtonRect(ScrollbarThemeClient*, ScrollbarPart, bool painting = false) = 0;
- virtual IntRect trackRect(ScrollbarThemeClient*, bool painting = false) = 0;
- virtual IntRect thumbRect(ScrollbarThemeClient*);
- virtual int thumbThickness(ScrollbarThemeClient*);
-
- virtual int minimumThumbLength(ScrollbarThemeClient*);
-
- virtual void splitTrack(ScrollbarThemeClient*, const IntRect& track, IntRect& startTrack, IntRect& thumb, IntRect& endTrack);
-
- virtual void paintScrollbarBackground(GraphicsContext*, ScrollbarThemeClient*) { }
- virtual void paintTrackBackground(GraphicsContext*, ScrollbarThemeClient*, const IntRect&) { }
- virtual void paintTrackPiece(GraphicsContext*, ScrollbarThemeClient*, const IntRect&, ScrollbarPart) { }
- virtual void paintButton(GraphicsContext*, ScrollbarThemeClient*, const IntRect&, ScrollbarPart) { }
- virtual void paintThumb(GraphicsContext*, ScrollbarThemeClient*, const IntRect&) { }
-
- virtual int maxOverlapBetweenPages() { return std::numeric_limits<int>::max(); }
-
- virtual double initialAutoscrollTimerDelay() { return 0.25; }
- virtual double autoscrollTimerDelay() { return 0.05; }
-
- virtual IntRect constrainTrackRectToTrackPieces(ScrollbarThemeClient*, const IntRect& rect) { return rect; }
-
- virtual void registerScrollbar(ScrollbarThemeClient*) { }
- virtual void unregisterScrollbar(ScrollbarThemeClient*) { }
-
- virtual bool isMockTheme() const { return false; }
-
- static ScrollbarTheme* theme();
-
-private:
- static ScrollbarTheme* nativeTheme(); // Must be implemented to return the correct theme subclass.
-};
-
-}
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeAndroid.cpp b/chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeAndroid.cpp
deleted file mode 100644
index 48103ce57c0..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeAndroid.cpp
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/ScrollbarTheme.h"
-
-#include "core/platform/ScrollbarThemeOverlay.h"
-
-namespace WebCore {
-
-ScrollbarTheme* ScrollbarTheme::nativeTheme()
-{
- DEFINE_STATIC_LOCAL(ScrollbarThemeOverlay, theme, (3, 4, ScrollbarThemeOverlay::DisallowHitTest));
- return &theme;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeAuraOrGtk.cpp b/chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeAuraOrGtk.cpp
deleted file mode 100644
index 88791dfcbae..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeAuraOrGtk.cpp
+++ /dev/null
@@ -1,153 +0,0 @@
-/*
- * Copyright (c) 2008, 2009, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/ScrollbarThemeAuraOrGtk.h"
-
-#include "RuntimeEnabledFeatures.h"
-#include "core/platform/PlatformMouseEvent.h"
-#include "core/platform/Scrollbar.h"
-#include "core/platform/ScrollbarThemeOverlay.h"
-#include "core/platform/graphics/GraphicsContext.h"
-#include "public/platform/Platform.h"
-#include "public/platform/WebRect.h"
-#include "public/platform/default/WebThemeEngine.h"
-
-namespace WebCore {
-
-ScrollbarTheme* ScrollbarTheme::nativeTheme()
-{
- if (RuntimeEnabledFeatures::overlayScrollbarsEnabled()) {
- DEFINE_STATIC_LOCAL(ScrollbarThemeOverlay, theme, (10, 0, ScrollbarThemeOverlay::AllowHitTest, Color(128, 128, 128, 192)));
- return &theme;
- }
-
- DEFINE_STATIC_LOCAL(ScrollbarThemeAuraOrGtk, theme, ());
- return &theme;
-}
-
-int ScrollbarThemeAuraOrGtk::scrollbarThickness(ScrollbarControlSize controlSize)
-{
- // Horiz and Vert scrollbars are the same thickness.
- IntSize scrollbarSize = WebKit::Platform::current()->themeEngine()->getSize(WebKit::WebThemeEngine::PartScrollbarVerticalTrack);
- return scrollbarSize.width();
-}
-
-void ScrollbarThemeAuraOrGtk::paintTrackPiece(GraphicsContext* gc, ScrollbarThemeClient* scrollbar, const IntRect& rect, ScrollbarPart partType)
-{
- WebKit::WebThemeEngine::State state = scrollbar->hoveredPart() == partType ? WebKit::WebThemeEngine::StateHover : WebKit::WebThemeEngine::StateNormal;
- IntRect alignRect = trackRect(scrollbar, false);
- WebKit::WebThemeEngine::ExtraParams extraParams;
- WebKit::WebCanvas* canvas = gc->canvas();
- extraParams.scrollbarTrack.trackX = alignRect.x();
- extraParams.scrollbarTrack.trackY = alignRect.y();
- extraParams.scrollbarTrack.trackWidth = alignRect.width();
- extraParams.scrollbarTrack.trackHeight = alignRect.height();
- WebKit::Platform::current()->themeEngine()->paint(canvas, scrollbar->orientation() == HorizontalScrollbar ? WebKit::WebThemeEngine::PartScrollbarHorizontalTrack : WebKit::WebThemeEngine::PartScrollbarVerticalTrack, state, WebKit::WebRect(rect), &extraParams);
-}
-
-void ScrollbarThemeAuraOrGtk::paintButton(GraphicsContext* gc, ScrollbarThemeClient* scrollbar, const IntRect& rect, ScrollbarPart part)
-{
- WebKit::WebThemeEngine::Part paintPart;
- WebKit::WebThemeEngine::State state = WebKit::WebThemeEngine::StateNormal;
- WebKit::WebCanvas* canvas = gc->canvas();
- bool checkMin = false;
- bool checkMax = false;
- if (scrollbar->orientation() == HorizontalScrollbar) {
- if (part == BackButtonStartPart) {
- paintPart = WebKit::WebThemeEngine::PartScrollbarLeftArrow;
- checkMin = true;
- } else {
- paintPart = WebKit::WebThemeEngine::PartScrollbarRightArrow;
- checkMax = true;
- }
- } else {
- if (part == BackButtonStartPart) {
- paintPart = WebKit::WebThemeEngine::PartScrollbarUpArrow;
- checkMin = true;
- } else {
- paintPart = WebKit::WebThemeEngine::PartScrollbarDownArrow;
- checkMax = true;
- }
- }
- if ((checkMin && (scrollbar->currentPos() <= 0))
- || (checkMax && scrollbar->currentPos() == scrollbar->maximum())) {
- state = WebKit::WebThemeEngine::StateDisabled;
- } else {
- if (part == scrollbar->pressedPart())
- state = WebKit::WebThemeEngine::StatePressed;
- else if (part == scrollbar->hoveredPart())
- state = WebKit::WebThemeEngine::StateHover;
- }
- WebKit::Platform::current()->themeEngine()->paint(canvas, paintPart, state, WebKit::WebRect(rect), 0);
-}
-
-void ScrollbarThemeAuraOrGtk::paintThumb(GraphicsContext* gc, ScrollbarThemeClient* scrollbar, const IntRect& rect)
-{
- WebKit::WebThemeEngine::State state;
- WebKit::WebCanvas* canvas = gc->canvas();
- if (scrollbar->pressedPart() == ThumbPart)
- state = WebKit::WebThemeEngine::StatePressed;
- else if (scrollbar->hoveredPart() == ThumbPart)
- state = WebKit::WebThemeEngine::StateHover;
- else
- state = WebKit::WebThemeEngine::StateNormal;
- WebKit::Platform::current()->themeEngine()->paint(canvas, scrollbar->orientation() == HorizontalScrollbar ? WebKit::WebThemeEngine::PartScrollbarHorizontalThumb : WebKit::WebThemeEngine::PartScrollbarVerticalThumb, state, WebKit::WebRect(rect), 0);
-}
-
-bool ScrollbarThemeAuraOrGtk::shouldCenterOnThumb(ScrollbarThemeClient*, const PlatformMouseEvent& evt)
-{
- return (evt.shiftKey() && evt.button() == LeftButton) || (evt.button() == MiddleButton);
-}
-
-IntSize ScrollbarThemeAuraOrGtk::buttonSize(ScrollbarThemeClient* scrollbar)
-{
- if (scrollbar->orientation() == VerticalScrollbar) {
- IntSize size = WebKit::Platform::current()->themeEngine()->getSize(WebKit::WebThemeEngine::PartScrollbarUpArrow);
- return IntSize(size.width(), scrollbar->height() < 2 * size.height() ? scrollbar->height() / 2 : size.height());
- }
-
- // HorizontalScrollbar
- IntSize size = WebKit::Platform::current()->themeEngine()->getSize(WebKit::WebThemeEngine::PartScrollbarLeftArrow);
- return IntSize(scrollbar->width() < 2 * size.width() ? scrollbar->width() / 2 : size.width(), size.height());
-}
-
-int ScrollbarThemeAuraOrGtk::minimumThumbLength(ScrollbarThemeClient* scrollbar)
-{
- if (scrollbar->orientation() == VerticalScrollbar) {
- IntSize size = WebKit::Platform::current()->themeEngine()->getSize(WebKit::WebThemeEngine::PartScrollbarVerticalThumb);
- return size.height();
- }
-
- IntSize size = WebKit::Platform::current()->themeEngine()->getSize(WebKit::WebThemeEngine::PartScrollbarHorizontalThumb);
- return size.width();
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeAuraOrGtk.h b/chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeAuraOrGtk.h
deleted file mode 100644
index ec37c2c1f78..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeAuraOrGtk.h
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright (c) 2009, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ScrollbarThemeAuraOrGtk_h
-#define ScrollbarThemeAuraOrGtk_h
-
-#include "core/platform/ScrollbarThemeNonMacCommon.h"
-
-namespace WebCore {
-
-class ScrollbarThemeAuraOrGtk : public ScrollbarThemeNonMacCommon {
-public:
- virtual int scrollbarThickness(ScrollbarControlSize);
-
-protected:
- virtual void paintTrackPiece(GraphicsContext*, ScrollbarThemeClient*, const IntRect&, ScrollbarPart);
- virtual void paintButton(GraphicsContext*, ScrollbarThemeClient*, const IntRect&, ScrollbarPart);
- virtual void paintThumb(GraphicsContext*, ScrollbarThemeClient*, const IntRect&);
- virtual bool shouldCenterOnThumb(ScrollbarThemeClient*, const PlatformMouseEvent&);
- virtual IntSize buttonSize(ScrollbarThemeClient*);
- virtual int minimumThumbLength(ScrollbarThemeClient*);
-};
-
-} // namespace WebCore
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeClient.h b/chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeClient.h
deleted file mode 100644
index 1fca367d520..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeClient.h
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ScrollbarThemeClient_h
-#define ScrollbarThemeClient_h
-
-#include "core/platform/ScrollTypes.h"
-#include "core/platform/graphics/IntPoint.h"
-#include "core/platform/graphics/IntRect.h"
-#include "core/platform/graphics/IntSize.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-class ScrollView;
-
-class ScrollbarThemeClient {
-public:
- virtual int x() const = 0;
- virtual int y() const = 0;
- virtual int width() const = 0;
- virtual int height() const = 0;
- virtual IntSize size() const = 0;
- virtual IntPoint location() const = 0;
-
- virtual ScrollView* parent() const = 0;
- virtual ScrollView* root() const = 0;
-
- virtual void setFrameRect(const IntRect&) = 0;
- virtual IntRect frameRect() const = 0;
-
- virtual void invalidate() = 0;
- virtual void invalidateRect(const IntRect&) = 0;
-
- virtual ScrollbarOverlayStyle scrollbarOverlayStyle() const = 0;
- virtual void getTickmarks(Vector<IntRect>&) const = 0;
- virtual bool isScrollableAreaActive() const = 0;
- virtual bool isScrollViewScrollbar() const = 0;
-
- virtual IntPoint convertFromContainingWindow(const IntPoint& windowPoint) = 0;
-
- virtual bool isCustomScrollbar() const = 0;
- virtual ScrollbarOrientation orientation() const = 0;
- virtual bool isLeftSideVerticalScrollbar() const = 0;
-
- virtual int value() const = 0;
- virtual float currentPos() const = 0;
- virtual int visibleSize() const = 0;
- virtual int totalSize() const = 0;
- virtual int maximum() const = 0;
- virtual ScrollbarControlSize controlSize() const = 0;
-
- virtual ScrollbarPart pressedPart() const = 0;
- virtual ScrollbarPart hoveredPart() const = 0;
-
- virtual void styleChanged() = 0;
-
- virtual bool enabled() const = 0;
- virtual void setEnabled(bool) = 0;
-
- virtual bool isOverlayScrollbar() const = 0;
-
- virtual bool isAlphaLocked() const = 0;
- virtual void setIsAlphaLocked(bool) = 0;
-
-protected:
- virtual ~ScrollbarThemeClient() { }
-};
-
-} // namespace WebCore
-
-#endif // ScollbarThemeClient_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeMacCommon.h b/chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeMacCommon.h
deleted file mode 100644
index 524d8333d4c..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeMacCommon.h
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Copyright (C) 2008 Apple Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ScrollbarThemeMacCommon_h
-#define ScrollbarThemeMacCommon_h
-
-#include "core/platform/ScrollbarTheme.h"
-
-namespace WebCore {
-
-class ScrollbarThemeMacCommon : public ScrollbarTheme {
-public:
- ScrollbarThemeMacCommon();
- virtual ~ScrollbarThemeMacCommon();
-
- virtual void registerScrollbar(ScrollbarThemeClient*) OVERRIDE;
- virtual void unregisterScrollbar(ScrollbarThemeClient*) OVERRIDE;
- void preferencesChanged();
-
- virtual bool supportsControlTints() const OVERRIDE { return true; }
-
- virtual double initialAutoscrollTimerDelay() OVERRIDE;
- virtual double autoscrollTimerDelay() OVERRIDE;
-
- virtual void paintOverhangBackground(ScrollView*, GraphicsContext*, const IntRect& horizontalOverhangArea, const IntRect& verticalOverhangArea, const IntRect& dirtyRect) OVERRIDE;
- virtual void paintOverhangShadows(ScrollView*, GraphicsContext*, const IntRect& horizontalOverhangArea, const IntRect& verticalOverhangArea, const IntRect& dirtyRect) OVERRIDE;
- virtual void paintTickmarks(GraphicsContext*, ScrollbarThemeClient*, const IntRect&) OVERRIDE;
-
- virtual void setUpOverhangShadowLayer(GraphicsLayer*) OVERRIDE;
- virtual void updateOverhangShadowLayer(GraphicsLayer* shadowLayer, GraphicsLayer* rootContentLayer) OVERRIDE;
-
-protected:
- virtual int maxOverlapBetweenPages() OVERRIDE { return 40; }
-
- virtual bool shouldCenterOnThumb(ScrollbarThemeClient*, const PlatformMouseEvent&) OVERRIDE;
- virtual bool shouldDragDocumentInsteadOfThumb(ScrollbarThemeClient*, const PlatformMouseEvent&) OVERRIDE;
- int scrollbarPartToHIPressedState(ScrollbarPart);
-
- virtual void updateButtonPlacement() { }
-
- void paintGivenTickmarks(GraphicsContext*, ScrollbarThemeClient*, const IntRect&, const Vector<IntRect>&);
-
- RefPtr<Image> m_overhangShadow;
- RefPtr<Pattern> m_overhangPattern;
-};
-
-}
-
-#endif // ScrollbarThemeMacCommon_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeMacCommon.mm b/chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeMacCommon.mm
deleted file mode 100644
index 9aacbf4d0c8..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeMacCommon.mm
+++ /dev/null
@@ -1,428 +0,0 @@
-/*
- * Copyright (C) 2008, 2011 Apple Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/ScrollbarThemeMacCommon.h"
-
-#include <Carbon/Carbon.h>
-#include "core/page/FrameView.h"
-#include "core/platform/PlatformMouseEvent.h"
-#include "core/platform/ScrollView.h"
-#include "core/platform/ScrollbarThemeMacNonOverlayAPI.h"
-#include "core/platform/ScrollbarThemeMacOverlayAPI.h"
-#include "core/platform/graphics/Gradient.h"
-#include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/graphics/GraphicsContextStateSaver.h"
-#include "core/platform/graphics/GraphicsLayer.h"
-#include "core/platform/graphics/ImageBuffer.h"
-#include "core/platform/graphics/mac/ColorMac.h"
-#include "core/platform/mac/LocalCurrentGraphicsContext.h"
-#include "core/platform/mac/NSScrollerImpDetails.h"
-#include "core/platform/mac/ScrollAnimatorMac.h"
-#include "public/platform/mac/WebThemeEngine.h"
-#include "public/platform/Platform.h"
-#include "public/platform/WebRect.h"
-#include "skia/ext/skia_utils_mac.h"
-#include "wtf/HashSet.h"
-#include "wtf/StdLibExtras.h"
-#include "wtf/TemporaryChange.h"
-#include "wtf/UnusedParam.h"
-
-// FIXME: There are repainting problems due to Aqua scroll bar buttons' visual overflow.
-
-using namespace std;
-using namespace WebCore;
-
-@interface NSColor (WebNSColorDetails)
-+ (NSImage *)_linenPatternImage;
-@end
-
-namespace WebCore {
-
-typedef HashSet<ScrollbarThemeClient*> ScrollbarSet;
-
-static ScrollbarSet& scrollbarSet()
-{
- DEFINE_STATIC_LOCAL(ScrollbarSet, set, ());
- return set;
-}
-
-}
-
-@interface WebScrollbarPrefsObserver : NSObject
-{
-}
-
-+ (void)registerAsObserver;
-+ (void)appearancePrefsChanged:(NSNotification*)theNotification;
-+ (void)behaviorPrefsChanged:(NSNotification*)theNotification;
-
-@end
-
-@implementation WebScrollbarPrefsObserver
-
-+ (void)appearancePrefsChanged:(NSNotification*)unusedNotification
-{
- UNUSED_PARAM(unusedNotification);
-
- ScrollbarTheme* theme = ScrollbarTheme::theme();
- if (theme->isMockTheme())
- return;
-
- static_cast<ScrollbarThemeMacCommon*>(ScrollbarTheme::theme())->preferencesChanged();
- if (scrollbarSet().isEmpty())
- return;
- ScrollbarSet::iterator end = scrollbarSet().end();
- for (ScrollbarSet::iterator it = scrollbarSet().begin(); it != end; ++it) {
- (*it)->styleChanged();
- (*it)->invalidate();
- }
-}
-
-+ (void)behaviorPrefsChanged:(NSNotification*)unusedNotification
-{
- UNUSED_PARAM(unusedNotification);
-
- ScrollbarTheme* theme = ScrollbarTheme::theme();
- if (theme->isMockTheme())
- return;
-
- static_cast<ScrollbarThemeMacCommon*>(ScrollbarTheme::theme())->preferencesChanged();
-}
-
-+ (void)registerAsObserver
-{
- [[NSDistributedNotificationCenter defaultCenter] addObserver:self selector:@selector(appearancePrefsChanged:) name:@"AppleAquaScrollBarVariantChanged" object:nil suspensionBehavior:NSNotificationSuspensionBehaviorDeliverImmediately];
- [[NSDistributedNotificationCenter defaultCenter] addObserver:self selector:@selector(behaviorPrefsChanged:) name:@"AppleNoRedisplayAppearancePreferenceChanged" object:nil suspensionBehavior:NSNotificationSuspensionBehaviorCoalesce];
-}
-
-@end
-
-namespace WebCore {
-
-static float gInitialButtonDelay = 0.5f;
-static float gAutoscrollButtonDelay = 0.05f;
-static bool gJumpOnTrackClick = false;
-
-ScrollbarTheme* ScrollbarTheme::nativeTheme()
-{
- if (isScrollbarOverlayAPIAvailable()) {
- DEFINE_STATIC_LOCAL(ScrollbarThemeMacOverlayAPI, theme, ());
- return &theme;
- } else {
- DEFINE_STATIC_LOCAL(ScrollbarThemeMacNonOverlayAPI, theme, ());
- return &theme;
- }
- return NULL;
-}
-
-void ScrollbarThemeMacCommon::registerScrollbar(ScrollbarThemeClient* scrollbar)
-{
- scrollbarSet().add(scrollbar);
-}
-
-void ScrollbarThemeMacCommon::unregisterScrollbar(ScrollbarThemeClient* scrollbar)
-{
- scrollbarSet().remove(scrollbar);
-}
-
-void ScrollbarThemeMacCommon::paintGivenTickmarks(GraphicsContext* context, ScrollbarThemeClient* scrollbar, const IntRect& rect, const Vector<IntRect>& tickmarks)
-{
- if (scrollbar->orientation() != VerticalScrollbar)
- return;
-
- if (rect.height() <= 0 || rect.width() <= 0)
- return; // nothing to draw on.
-
- if (!tickmarks.size())
- return;
-
- GraphicsContextStateSaver stateSaver(*context);
- context->setShouldAntialias(false);
- context->setStrokeColor(Color(0xCC, 0xAA, 0x00, 0xFF));
- context->setFillColor(Color(0xFF, 0xDD, 0x00, 0xFF));
-
- for (Vector<IntRect>::const_iterator i = tickmarks.begin(); i != tickmarks.end(); ++i) {
- // Calculate how far down (in %) the tick-mark should appear.
- const float percent = static_cast<float>(i->y()) / scrollbar->totalSize();
- if (percent < 0.0 || percent > 1.0)
- continue;
-
- // Calculate how far down (in pixels) the tick-mark should appear.
- const int yPos = rect.y() + (rect.height() * percent);
-
- // Paint.
- FloatRect tickRect(rect.x(), yPos, rect.width(), 2);
- context->fillRect(tickRect);
- context->strokeRect(tickRect, 1);
- }
-}
-
-void ScrollbarThemeMacCommon::paintOverhangBackground(ScrollView* view, GraphicsContext* context, const IntRect& horizontalOverhangRect, const IntRect& verticalOverhangRect, const IntRect& dirtyRect)
-{
- const bool hasHorizontalOverhang = !horizontalOverhangRect.isEmpty();
- const bool hasVerticalOverhang = !verticalOverhangRect.isEmpty();
-
- GraphicsContextStateSaver stateSaver(*context);
- context->setFillPattern(m_overhangPattern);
- if (hasHorizontalOverhang)
- context->fillRect(intersection(horizontalOverhangRect, dirtyRect));
- if (hasVerticalOverhang)
- context->fillRect(intersection(verticalOverhangRect, dirtyRect));
-}
-
-void ScrollbarThemeMacCommon::paintOverhangShadows(ScrollView* view, GraphicsContext* context, const IntRect& horizontalOverhangRect, const IntRect& verticalOverhangRect, const IntRect& dirtyRect)
-{
- // The extent of each shadow in pixels.
- const int kShadowSize = 4;
- // Offset of negative one pixel to make the gradient blend with the toolbar's bottom border.
- const int kToolbarShadowOffset = -1;
- const struct {
- float stop;
- Color color;
- } kShadowColors[] = {
- { 0.000, Color(0, 0, 0, 255) },
- { 0.125, Color(0, 0, 0, 57) },
- { 0.375, Color(0, 0, 0, 41) },
- { 0.625, Color(0, 0, 0, 18) },
- { 0.875, Color(0, 0, 0, 6) },
- { 1.000, Color(0, 0, 0, 0) }
- };
- const unsigned kNumShadowColors = sizeof(kShadowColors)/sizeof(kShadowColors[0]);
-
- const bool hasHorizontalOverhang = !horizontalOverhangRect.isEmpty();
- const bool hasVerticalOverhang = !verticalOverhangRect.isEmpty();
- // Prefer non-additive shadows, but degrade to additive shadows if there is vertical overhang.
- const bool useAdditiveShadows = hasVerticalOverhang;
-
- GraphicsContextStateSaver stateSaver(*context);
-
- IntSize scrollOffset = view->scrollOffset();
- FloatPoint shadowCornerOrigin;
- FloatPoint shadowCornerOffset;
-
- // Draw the shadow for the horizontal overhang.
- if (hasHorizontalOverhang) {
- int toolbarShadowHeight = kShadowSize;
- RefPtr<Gradient> gradient;
- IntRect shadowRect = horizontalOverhangRect;
- shadowRect.setHeight(kShadowSize);
- if (scrollOffset.height() < 0) {
- if (useAdditiveShadows) {
- toolbarShadowHeight = std::min(horizontalOverhangRect.height(), kShadowSize);
- } else if (horizontalOverhangRect.height() < 2 * kShadowSize + kToolbarShadowOffset) {
- // Split the overhang area between the web content shadow and toolbar shadow if it's too small.
- shadowRect.setHeight((horizontalOverhangRect.height() + 1) / 2);
- toolbarShadowHeight = horizontalOverhangRect.height() - shadowRect.height() - kToolbarShadowOffset;
- }
- shadowRect.setY(horizontalOverhangRect.maxY() - shadowRect.height());
- gradient = Gradient::create(FloatPoint(0, shadowRect.maxY()), FloatPoint(0, shadowRect.maxY() - kShadowSize));
- shadowCornerOrigin.setY(shadowRect.maxY());
- shadowCornerOffset.setY(-kShadowSize);
- } else {
- gradient = Gradient::create(FloatPoint(0, shadowRect.y()), FloatPoint(0, shadowRect.maxY()));
- shadowCornerOrigin.setY(shadowRect.y());
- }
- if (hasVerticalOverhang) {
- shadowRect.setWidth(shadowRect.width() - verticalOverhangRect.width());
- if (scrollOffset.width() < 0) {
- shadowRect.setX(shadowRect.x() + verticalOverhangRect.width());
- shadowCornerOrigin.setX(shadowRect.x());
- shadowCornerOffset.setX(-kShadowSize);
- } else {
- shadowCornerOrigin.setX(shadowRect.maxX());
- }
- }
- for (unsigned i = 0; i < kNumShadowColors; i++)
- gradient->addColorStop(kShadowColors[i].stop, kShadowColors[i].color);
- context->setFillGradient(gradient);
- context->fillRect(intersection(shadowRect, dirtyRect));
-
- // Draw a drop-shadow from the toolbar.
- if (scrollOffset.height() < 0) {
- shadowRect.setY(kToolbarShadowOffset);
- shadowRect.setHeight(toolbarShadowHeight);
- gradient = Gradient::create(FloatPoint(0, shadowRect.y()), FloatPoint(0, shadowRect.y() + kShadowSize));
- for (unsigned i = 0; i < kNumShadowColors; i++)
- gradient->addColorStop(kShadowColors[i].stop, kShadowColors[i].color);
- context->setFillGradient(gradient);
- context->fillRect(intersection(shadowRect, dirtyRect));
- }
- }
-
- // Draw the shadow for the vertical overhang.
- if (hasVerticalOverhang) {
- RefPtr<Gradient> gradient;
- IntRect shadowRect = verticalOverhangRect;
- shadowRect.setWidth(kShadowSize);
- if (scrollOffset.width() < 0) {
- shadowRect.setX(verticalOverhangRect.maxX() - shadowRect.width());
- gradient = Gradient::create(FloatPoint(shadowRect.maxX(), 0), FloatPoint(shadowRect.x(), 0));
- } else {
- gradient = Gradient::create(FloatPoint(shadowRect.x(), 0), FloatPoint(shadowRect.maxX(), 0));
- }
- for (unsigned i = 0; i < kNumShadowColors; i++)
- gradient->addColorStop(kShadowColors[i].stop, kShadowColors[i].color);
- context->setFillGradient(gradient);
- context->fillRect(intersection(shadowRect, dirtyRect));
-
- // Draw a drop-shadow from the toolbar.
- shadowRect = verticalOverhangRect;
- shadowRect.setY(kToolbarShadowOffset);
- shadowRect.setHeight(kShadowSize);
- gradient = Gradient::create(FloatPoint(0, shadowRect.y()), FloatPoint(0, shadowRect.maxY()));
- for (unsigned i = 0; i < kNumShadowColors; i++)
- gradient->addColorStop(kShadowColors[i].stop, kShadowColors[i].color);
- context->setFillGradient(gradient);
- context->fillRect(intersection(shadowRect, dirtyRect));
- }
-
- // If both rectangles present, draw a radial gradient for the corner.
- if (hasHorizontalOverhang && hasVerticalOverhang) {
- RefPtr<Gradient> gradient = Gradient::create(shadowCornerOrigin, 0, shadowCornerOrigin, kShadowSize);
- for (unsigned i = 0; i < kNumShadowColors; i++)
- gradient->addColorStop(kShadowColors[i].stop, kShadowColors[i].color);
- context->setFillGradient(gradient);
- context->fillRect(FloatRect(shadowCornerOrigin.x() + shadowCornerOffset.x(), shadowCornerOrigin.y() + shadowCornerOffset.y(), kShadowSize, kShadowSize));
- }
-}
-
-void ScrollbarThemeMacCommon::paintTickmarks(GraphicsContext* context, ScrollbarThemeClient* scrollbar, const IntRect& rect)
-{
- // Note: This is only used for css-styled scrollbars on mac.
- if (scrollbar->orientation() != VerticalScrollbar)
- return;
-
- if (rect.height() <= 0 || rect.width() <= 0)
- return;
-
- Vector<IntRect> tickmarks;
- scrollbar->getTickmarks(tickmarks);
- if (!tickmarks.size())
- return;
-
- // Inset a bit.
- IntRect tickmarkTrackRect = rect;
- tickmarkTrackRect.setX(tickmarkTrackRect.x() + 1);
- tickmarkTrackRect.setWidth(tickmarkTrackRect.width() - 2);
- paintGivenTickmarks(context, scrollbar, tickmarkTrackRect, tickmarks);
-}
-
-ScrollbarThemeMacCommon::ScrollbarThemeMacCommon()
-{
- static bool initialized;
- if (!initialized) {
- initialized = true;
- [WebScrollbarPrefsObserver registerAsObserver];
- preferencesChanged();
- }
-
- // Load the shadow for the overhang.
- m_overhangShadow = Image::loadPlatformResource("overhangShadow");
-
- // Load the linen pattern image used for overhang drawing.
- RefPtr<Image> patternImage = Image::loadPlatformResource("overhangPattern");
- m_overhangPattern = Pattern::create(patternImage, true, true);
-}
-
-ScrollbarThemeMacCommon::~ScrollbarThemeMacCommon()
-{
-}
-
-void ScrollbarThemeMacCommon::setUpOverhangShadowLayer(GraphicsLayer* overhangShadowLayer)
-{
- // The shadow texture is has a 1-pixel aperture in the center, so the division by
- // two is doing an intentional round-down.
- overhangShadowLayer->setContentsToNinePatch(
- m_overhangShadow.get(),
- IntRect(m_overhangShadow->width() / 2, m_overhangShadow->height() / 2, 1, 1));
-}
-
-void ScrollbarThemeMacCommon::updateOverhangShadowLayer(GraphicsLayer* shadowLayer, GraphicsLayer* rootContentLayer)
-{
- // Note that for the position, the division m_overhangShadow->width() / 2 is an intentional
- // round-down, and that for the width and height, the 1-pixel aperture is being replaced
- // by the root contents layer, hence subtracting 1 and adding the rootContentsLayer size.
- IntRect shadowRect (
- static_cast<int>(rootContentLayer->position().x()) - m_overhangShadow->width() / 2,
- static_cast<int>(rootContentLayer->position().y()) - m_overhangShadow->height() / 2,
- static_cast<int>(rootContentLayer->size().width()) + m_overhangShadow->width() - 1,
- static_cast<int>(rootContentLayer->size().height()) + m_overhangShadow->height() - 1);
- shadowLayer->setContentsRect(shadowRect);
-}
-
-void ScrollbarThemeMacCommon::preferencesChanged()
-{
- NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
- [defaults synchronize];
- updateButtonPlacement();
- gInitialButtonDelay = [defaults floatForKey:@"NSScrollerButtonDelay"];
- gAutoscrollButtonDelay = [defaults floatForKey:@"NSScrollerButtonPeriod"];
- gJumpOnTrackClick = [defaults boolForKey:@"AppleScrollerPagingBehavior"];
-}
-
-double ScrollbarThemeMacCommon::initialAutoscrollTimerDelay()
-{
- return gInitialButtonDelay;
-}
-
-double ScrollbarThemeMacCommon::autoscrollTimerDelay()
-{
- return gAutoscrollButtonDelay;
-}
-
-bool ScrollbarThemeMacCommon::shouldCenterOnThumb(ScrollbarThemeClient*, const PlatformMouseEvent& evt)
-{
- if (evt.button() != LeftButton)
- return false;
- if (gJumpOnTrackClick)
- return !evt.altKey();
- return evt.altKey();
-}
-
-bool ScrollbarThemeMacCommon::shouldDragDocumentInsteadOfThumb(ScrollbarThemeClient*, const PlatformMouseEvent& event)
-{
- return event.altKey();
-}
-
-int ScrollbarThemeMacCommon::scrollbarPartToHIPressedState(ScrollbarPart part)
-{
- switch (part) {
- case BackButtonStartPart:
- return kThemeTopOutsideArrowPressed;
- case BackButtonEndPart:
- return kThemeTopOutsideArrowPressed; // This does not make much sense. For some reason the outside constant is required.
- case ForwardButtonStartPart:
- return kThemeTopInsideArrowPressed;
- case ForwardButtonEndPart:
- return kThemeBottomOutsideArrowPressed;
- case ThumbPart:
- return kThemeThumbPressed;
- default:
- return 0;
- }
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeMacNonOverlayAPI.h b/chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeMacNonOverlayAPI.h
deleted file mode 100644
index e51380059f4..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeMacNonOverlayAPI.h
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ScrollbarThemeMacNonOverlayAPI_h
-#define ScrollbarThemeMacNonOverlayAPI_h
-
-#include "core/platform/ScrollbarThemeMacCommon.h"
-
-namespace WebCore {
-
-class ScrollbarThemeMacNonOverlayAPI : public ScrollbarThemeMacCommon {
-public:
- virtual int scrollbarThickness(ScrollbarControlSize = RegularScrollbar) OVERRIDE;
- virtual bool usesOverlayScrollbars() const OVERRIDE { return false; }
- virtual ScrollbarButtonsPlacement buttonsPlacement() const OVERRIDE;
-
- virtual bool paint(ScrollbarThemeClient*, GraphicsContext*, const IntRect& damageRect) OVERRIDE;
-
-protected:
- virtual IntRect trackRect(ScrollbarThemeClient*, bool painting = false) OVERRIDE;
- virtual IntRect backButtonRect(ScrollbarThemeClient*, ScrollbarPart, bool painting = false) OVERRIDE;
- virtual IntRect forwardButtonRect(ScrollbarThemeClient*, ScrollbarPart, bool painting = false) OVERRIDE;
-
- virtual void updateButtonPlacement() OVERRIDE;
-
- virtual bool hasButtons(ScrollbarThemeClient*) OVERRIDE;
- virtual bool hasThumb(ScrollbarThemeClient*) OVERRIDE;
-
- virtual int minimumThumbLength(ScrollbarThemeClient*) OVERRIDE;
-};
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeMacNonOverlayAPI.mm b/chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeMacNonOverlayAPI.mm
deleted file mode 100644
index dc8540053d9..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeMacNonOverlayAPI.mm
+++ /dev/null
@@ -1,336 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/ScrollbarThemeMacNonOverlayAPI.h"
-
-#include <Carbon/Carbon.h>
-#include "core/platform/ScrollbarThemeClient.h"
-#include "public/platform/mac/WebThemeEngine.h"
-#include "public/platform/Platform.h"
-#include "public/platform/WebRect.h"
-#include "skia/ext/skia_utils_mac.h"
-
-namespace WebCore {
-
-// FIXME: Get these numbers from CoreUI.
-static int cRealButtonLength[] = { 28, 21 };
-static int cButtonHitInset[] = { 3, 2 };
-// cRealButtonLength - cButtonInset
-static int cButtonLength[] = { 14, 10 };
-static int cScrollbarThickness[] = { 15, 11 };
-static int cButtonInset[] = { 14, 11 };
-static int cThumbMinLength[] = { 26, 20 };
-
-static int cOuterButtonLength[] = { 16, 14 }; // The outer button in a double button pair is a bit bigger.
-static int cOuterButtonOverlap = 2;
-
-static ScrollbarButtonsPlacement gButtonPlacement = ScrollbarButtonsDoubleEnd;
-
-void ScrollbarThemeMacNonOverlayAPI::updateButtonPlacement()
-{
- NSString *buttonPlacement = [[NSUserDefaults standardUserDefaults] objectForKey:@"AppleScrollBarVariant"];
- if ([buttonPlacement isEqualToString:@"Single"])
- gButtonPlacement = ScrollbarButtonsSingle;
- else if ([buttonPlacement isEqualToString:@"DoubleMin"])
- gButtonPlacement = ScrollbarButtonsDoubleStart;
- else if ([buttonPlacement isEqualToString:@"DoubleBoth"])
- gButtonPlacement = ScrollbarButtonsDoubleBoth;
- else {
- gButtonPlacement = ScrollbarButtonsDoubleEnd;
- }
-}
-
-static WebKit::WebThemeEngine::State scrollbarStateToThemeState(ScrollbarThemeClient* scrollbar)
-{
- if (!scrollbar->enabled())
- return WebKit::WebThemeEngine::StateDisabled;
- if (!scrollbar->isScrollableAreaActive())
- return WebKit::WebThemeEngine::StateInactive;
- if (scrollbar->pressedPart() == ThumbPart)
- return WebKit::WebThemeEngine::StatePressed;
-
- return WebKit::WebThemeEngine::StateActive;
-}
-
-// Override ScrollbarThemeMacCommon::paint() to add support for the following:
-// - drawing using WebThemeEngine functions
-// - drawing tickmarks
-// - Skia specific changes
-bool ScrollbarThemeMacNonOverlayAPI::paint(ScrollbarThemeClient* scrollbar, GraphicsContext* context, const IntRect& damageRect)
-{
- // Get the tickmarks for the frameview.
- Vector<IntRect> tickmarks;
- scrollbar->getTickmarks(tickmarks);
-
- HIThemeTrackDrawInfo trackInfo;
- trackInfo.version = 0;
- trackInfo.kind = scrollbar->controlSize() == RegularScrollbar ? kThemeMediumScrollBar : kThemeSmallScrollBar;
- trackInfo.bounds = scrollbar->frameRect();
- trackInfo.min = 0;
- trackInfo.max = scrollbar->maximum();
- trackInfo.value = scrollbar->currentPos();
- trackInfo.trackInfo.scrollbar.viewsize = scrollbar->visibleSize();
- trackInfo.attributes = 0;
- if (scrollbar->orientation() == HorizontalScrollbar)
- trackInfo.attributes |= kThemeTrackHorizontal;
-
- if (!scrollbar->enabled())
- trackInfo.enableState = kThemeTrackDisabled;
- else
- trackInfo.enableState = scrollbar->isScrollableAreaActive() ? kThemeTrackActive : kThemeTrackInactive;
-
- if (!hasButtons(scrollbar))
- trackInfo.enableState = kThemeTrackNothingToScroll;
- trackInfo.trackInfo.scrollbar.pressState = scrollbarPartToHIPressedState(scrollbar->pressedPart());
-
- SkCanvas* canvas = context->canvas();
- CGAffineTransform currentCTM = gfx::SkMatrixToCGAffineTransform(canvas->getTotalMatrix());
-
- // The Aqua scrollbar is buggy when rotated and scaled. We will just draw into a bitmap if we detect a scale or rotation.
- bool canDrawDirectly = currentCTM.a == 1.0f && currentCTM.b == 0.0f && currentCTM.c == 0.0f && (currentCTM.d == 1.0f || currentCTM.d == -1.0f);
- GraphicsContext* drawingContext = context;
- OwnPtr<ImageBuffer> imageBuffer;
- if (!canDrawDirectly) {
- trackInfo.bounds = IntRect(IntPoint(), scrollbar->frameRect().size());
-
- IntRect bufferRect(scrollbar->frameRect());
- bufferRect.intersect(damageRect);
- bufferRect.move(-scrollbar->frameRect().x(), -scrollbar->frameRect().y());
-
- imageBuffer = ImageBuffer::create(bufferRect.size());
- if (!imageBuffer)
- return true;
-
- drawingContext = imageBuffer->context();
- }
-
- // Draw thumbless.
- gfx::SkiaBitLocker bitLocker(drawingContext->canvas());
- CGContextRef cgContext = bitLocker.cgContext();
- HIThemeDrawTrack(&trackInfo, 0, cgContext, kHIThemeOrientationNormal);
-
- IntRect tickmarkTrackRect = trackRect(scrollbar, false);
- if (!canDrawDirectly) {
- tickmarkTrackRect.setX(0);
- tickmarkTrackRect.setY(0);
- }
- // The ends are rounded and the thumb doesn't go there.
- tickmarkTrackRect.inflateY(-tickmarkTrackRect.width());
- // Inset a bit.
- tickmarkTrackRect.setX(tickmarkTrackRect.x() + 2);
- tickmarkTrackRect.setWidth(tickmarkTrackRect.width() - 5);
- paintGivenTickmarks(drawingContext, scrollbar, tickmarkTrackRect, tickmarks);
-
- if (hasThumb(scrollbar)) {
- WebKit::WebThemeEngine::ScrollbarInfo scrollbarInfo;
- scrollbarInfo.orientation = scrollbar->orientation() == HorizontalScrollbar ? WebKit::WebThemeEngine::ScrollbarOrientationHorizontal : WebKit::WebThemeEngine::ScrollbarOrientationVertical;
- scrollbarInfo.parent = scrollbar->isScrollViewScrollbar() ? WebKit::WebThemeEngine::ScrollbarParentScrollView : WebKit::WebThemeEngine::ScrollbarParentRenderLayer;
- scrollbarInfo.maxValue = scrollbar->maximum();
- scrollbarInfo.currentValue = scrollbar->currentPos();
- scrollbarInfo.visibleSize = scrollbar->visibleSize();
- scrollbarInfo.totalSize = scrollbar->totalSize();
-
- WebKit::WebCanvas* webCanvas = drawingContext->canvas();
- WebKit::Platform::current()->themeEngine()->paintScrollbarThumb(
- webCanvas,
- scrollbarStateToThemeState(scrollbar),
- scrollbar->controlSize() == RegularScrollbar ? WebKit::WebThemeEngine::SizeRegular : WebKit::WebThemeEngine::SizeSmall,
- WebKit::WebRect(scrollbar->frameRect()),
- scrollbarInfo);
- }
-
- if (!canDrawDirectly)
- context->drawImageBuffer(imageBuffer.get(), scrollbar->frameRect().location());
-
- return true;
-}
-
-int ScrollbarThemeMacNonOverlayAPI::scrollbarThickness(ScrollbarControlSize controlSize)
-{
- return cScrollbarThickness[controlSize];
-}
-
-ScrollbarButtonsPlacement ScrollbarThemeMacNonOverlayAPI::buttonsPlacement() const
-{
- return gButtonPlacement;
-}
-
-bool ScrollbarThemeMacNonOverlayAPI::hasButtons(ScrollbarThemeClient* scrollbar)
-{
- return scrollbar->enabled() && buttonsPlacement() != ScrollbarButtonsNone
- && (scrollbar->orientation() == HorizontalScrollbar
- ? scrollbar->width()
- : scrollbar->height()) >= 2 * (cRealButtonLength[scrollbar->controlSize()] - cButtonHitInset[scrollbar->controlSize()]);
-}
-
-bool ScrollbarThemeMacNonOverlayAPI::hasThumb(ScrollbarThemeClient* scrollbar)
-{
- int minLengthForThumb = 2 * cButtonInset[scrollbar->controlSize()] + cThumbMinLength[scrollbar->controlSize()] + 1;
- return scrollbar->enabled() && (scrollbar->orientation() == HorizontalScrollbar ?
- scrollbar->width() :
- scrollbar->height()) >= minLengthForThumb;
-}
-
-static IntRect buttonRepaintRect(const IntRect& buttonRect, ScrollbarOrientation orientation, ScrollbarControlSize controlSize, bool start)
-{
- ASSERT(gButtonPlacement != ScrollbarButtonsNone);
-
- IntRect paintRect(buttonRect);
- if (orientation == HorizontalScrollbar) {
- paintRect.setWidth(cRealButtonLength[controlSize]);
- if (!start)
- paintRect.setX(buttonRect.x() - (cRealButtonLength[controlSize] - buttonRect.width()));
- } else {
- paintRect.setHeight(cRealButtonLength[controlSize]);
- if (!start)
- paintRect.setY(buttonRect.y() - (cRealButtonLength[controlSize] - buttonRect.height()));
- }
-
- return paintRect;
-}
-
-IntRect ScrollbarThemeMacNonOverlayAPI::backButtonRect(ScrollbarThemeClient* scrollbar, ScrollbarPart part, bool painting)
-{
- IntRect result;
-
- if (part == BackButtonStartPart && (buttonsPlacement() == ScrollbarButtonsNone || buttonsPlacement() == ScrollbarButtonsDoubleEnd))
- return result;
-
- if (part == BackButtonEndPart && (buttonsPlacement() == ScrollbarButtonsNone || buttonsPlacement() == ScrollbarButtonsDoubleStart || buttonsPlacement() == ScrollbarButtonsSingle))
- return result;
-
- int thickness = scrollbarThickness(scrollbar->controlSize());
- bool outerButton = part == BackButtonStartPart && (buttonsPlacement() == ScrollbarButtonsDoubleStart || buttonsPlacement() == ScrollbarButtonsDoubleBoth);
- if (outerButton) {
- if (scrollbar->orientation() == HorizontalScrollbar)
- result = IntRect(scrollbar->x(), scrollbar->y(), cOuterButtonLength[scrollbar->controlSize()] + (painting ? cOuterButtonOverlap : 0), thickness);
- else
- result = IntRect(scrollbar->x(), scrollbar->y(), thickness, cOuterButtonLength[scrollbar->controlSize()] + (painting ? cOuterButtonOverlap : 0));
- return result;
- }
-
- // Our repaint rect is slightly larger, since we are a button that is adjacent to the track.
- if (scrollbar->orientation() == HorizontalScrollbar) {
- int start = part == BackButtonStartPart ? scrollbar->x() : scrollbar->x() + scrollbar->width() - cOuterButtonLength[scrollbar->controlSize()] - cButtonLength[scrollbar->controlSize()];
- result = IntRect(start, scrollbar->y(), cButtonLength[scrollbar->controlSize()], thickness);
- } else {
- int start = part == BackButtonStartPart ? scrollbar->y() : scrollbar->y() + scrollbar->height() - cOuterButtonLength[scrollbar->controlSize()] - cButtonLength[scrollbar->controlSize()];
- result = IntRect(scrollbar->x(), start, thickness, cButtonLength[scrollbar->controlSize()]);
- }
-
- if (painting)
- return buttonRepaintRect(result, scrollbar->orientation(), scrollbar->controlSize(), part == BackButtonStartPart);
- return result;
-}
-
-IntRect ScrollbarThemeMacNonOverlayAPI::forwardButtonRect(ScrollbarThemeClient* scrollbar, ScrollbarPart part, bool painting)
-{
- IntRect result;
-
- if (part == ForwardButtonEndPart && (buttonsPlacement() == ScrollbarButtonsNone || buttonsPlacement() == ScrollbarButtonsDoubleStart))
- return result;
-
- if (part == ForwardButtonStartPart && (buttonsPlacement() == ScrollbarButtonsNone || buttonsPlacement() == ScrollbarButtonsDoubleEnd || buttonsPlacement() == ScrollbarButtonsSingle))
- return result;
-
- int thickness = scrollbarThickness(scrollbar->controlSize());
- int outerButtonLength = cOuterButtonLength[scrollbar->controlSize()];
- int buttonLength = cButtonLength[scrollbar->controlSize()];
-
- bool outerButton = part == ForwardButtonEndPart && (buttonsPlacement() == ScrollbarButtonsDoubleEnd || buttonsPlacement() == ScrollbarButtonsDoubleBoth);
- if (outerButton) {
- if (scrollbar->orientation() == HorizontalScrollbar) {
- result = IntRect(scrollbar->x() + scrollbar->width() - outerButtonLength, scrollbar->y(), outerButtonLength, thickness);
- if (painting)
- result.inflateX(cOuterButtonOverlap);
- } else {
- result = IntRect(scrollbar->x(), scrollbar->y() + scrollbar->height() - outerButtonLength, thickness, outerButtonLength);
- if (painting)
- result.inflateY(cOuterButtonOverlap);
- }
- return result;
- }
-
- if (scrollbar->orientation() == HorizontalScrollbar) {
- int start = part == ForwardButtonEndPart ? scrollbar->x() + scrollbar->width() - buttonLength : scrollbar->x() + outerButtonLength;
- result = IntRect(start, scrollbar->y(), buttonLength, thickness);
- } else {
- int start = part == ForwardButtonEndPart ? scrollbar->y() + scrollbar->height() - buttonLength : scrollbar->y() + outerButtonLength;
- result = IntRect(scrollbar->x(), start, thickness, buttonLength);
- }
- if (painting)
- return buttonRepaintRect(result, scrollbar->orientation(), scrollbar->controlSize(), part == ForwardButtonStartPart);
- return result;
-}
-
-IntRect ScrollbarThemeMacNonOverlayAPI::trackRect(ScrollbarThemeClient* scrollbar, bool painting)
-{
- if (painting || !hasButtons(scrollbar))
- return scrollbar->frameRect();
-
- IntRect result;
- int thickness = scrollbarThickness(scrollbar->controlSize());
- int startWidth = 0;
- int endWidth = 0;
- int outerButtonLength = cOuterButtonLength[scrollbar->controlSize()];
- int buttonLength = cButtonLength[scrollbar->controlSize()];
- int doubleButtonLength = outerButtonLength + buttonLength;
- switch (buttonsPlacement()) {
- case ScrollbarButtonsSingle:
- startWidth = buttonLength;
- endWidth = buttonLength;
- break;
- case ScrollbarButtonsDoubleStart:
- startWidth = doubleButtonLength;
- break;
- case ScrollbarButtonsDoubleEnd:
- endWidth = doubleButtonLength;
- break;
- case ScrollbarButtonsDoubleBoth:
- startWidth = doubleButtonLength;
- endWidth = doubleButtonLength;
- break;
- default:
- break;
- }
-
- int totalWidth = startWidth + endWidth;
- if (scrollbar->orientation() == HorizontalScrollbar)
- return IntRect(scrollbar->x() + startWidth, scrollbar->y(), scrollbar->width() - totalWidth, thickness);
- return IntRect(scrollbar->x(), scrollbar->y() + startWidth, thickness, scrollbar->height() - totalWidth);
-}
-
-int ScrollbarThemeMacNonOverlayAPI::minimumThumbLength(ScrollbarThemeClient* scrollbar)
-{
- return cThumbMinLength[scrollbar->controlSize()];
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeMacOverlayAPI.h b/chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeMacOverlayAPI.h
deleted file mode 100644
index b0c5aef9eb7..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeMacOverlayAPI.h
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ScrollbarThemeMacOverlayAPI_h
-#define ScrollbarThemeMacOverlayAPI_h
-
-#include "core/platform/ScrollbarThemeMacCommon.h"
-
-typedef id ScrollbarPainter;
-
-namespace WebCore {
-
-class ScrollbarThemeMacOverlayAPI : public ScrollbarThemeMacCommon {
-public:
- virtual void updateEnabledState(ScrollbarThemeClient*) OVERRIDE;
- virtual int scrollbarThickness(ScrollbarControlSize = RegularScrollbar) OVERRIDE;
- virtual bool usesOverlayScrollbars() const OVERRIDE;
- virtual void updateScrollbarOverlayStyle(ScrollbarThemeClient*) OVERRIDE;
- virtual ScrollbarButtonsPlacement buttonsPlacement() const OVERRIDE;
-
- virtual void registerScrollbar(ScrollbarThemeClient*) OVERRIDE;
- virtual void unregisterScrollbar(ScrollbarThemeClient*) OVERRIDE;
-
- void setNewPainterForScrollbar(ScrollbarThemeClient*, ScrollbarPainter);
- ScrollbarPainter painterForScrollbar(ScrollbarThemeClient*);
-
- virtual void paintTrackBackground(GraphicsContext*, ScrollbarThemeClient*, const IntRect&) OVERRIDE;
- virtual void paintThumb(GraphicsContext*, ScrollbarThemeClient*, const IntRect&) OVERRIDE;
-
-protected:
- virtual IntRect trackRect(ScrollbarThemeClient*, bool painting = false) OVERRIDE;
- virtual IntRect backButtonRect(ScrollbarThemeClient*, ScrollbarPart, bool painting = false) OVERRIDE;
- virtual IntRect forwardButtonRect(ScrollbarThemeClient*, ScrollbarPart, bool painting = false) OVERRIDE;
-
- virtual bool hasButtons(ScrollbarThemeClient*) OVERRIDE { return false; }
- virtual bool hasThumb(ScrollbarThemeClient*) OVERRIDE;
-
- virtual int minimumThumbLength(ScrollbarThemeClient*) OVERRIDE;
-};
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeMacOverlayAPI.mm b/chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeMacOverlayAPI.mm
deleted file mode 100644
index cac425ed928..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeMacOverlayAPI.mm
+++ /dev/null
@@ -1,196 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/ScrollbarThemeMacOverlayAPI.h"
-
-#include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/graphics/GraphicsContextStateSaver.h"
-#include "core/platform/mac/LocalCurrentGraphicsContext.h"
-#include "core/platform/mac/NSScrollerImpDetails.h"
-#include "core/platform/ScrollbarThemeClient.h"
-
-namespace WebCore {
-
-typedef HashMap<ScrollbarThemeClient*, RetainPtr<ScrollbarPainter> > ScrollbarPainterMap;
-
-static ScrollbarPainterMap* scrollbarPainterMap()
-{
- static ScrollbarPainterMap* map = new ScrollbarPainterMap;
- return map;
-}
-
-static bool supportsExpandedScrollbars()
-{
- // FIXME: This is temporary until all platforms that support ScrollbarPainter support this part of the API.
- static bool globalSupportsExpandedScrollbars = [NSClassFromString(@"NSScrollerImp") instancesRespondToSelector:@selector(setExpanded:)];
- return globalSupportsExpandedScrollbars;
-}
-
-void ScrollbarThemeMacOverlayAPI::registerScrollbar(ScrollbarThemeClient* scrollbar)
-{
- ScrollbarThemeMacCommon::registerScrollbar(scrollbar);
-
- bool isHorizontal = scrollbar->orientation() == HorizontalScrollbar;
- ScrollbarPainter scrollbarPainter = [NSClassFromString(@"NSScrollerImp") scrollerImpWithStyle:recommendedScrollerStyle() controlSize:(NSControlSize)scrollbar->controlSize() horizontal:isHorizontal replacingScrollerImp:nil];
- scrollbarPainterMap()->add(scrollbar, scrollbarPainter);
- updateEnabledState(scrollbar);
- updateScrollbarOverlayStyle(scrollbar);
-}
-
-void ScrollbarThemeMacOverlayAPI::unregisterScrollbar(ScrollbarThemeClient* scrollbar)
-{
- scrollbarPainterMap()->remove(scrollbar);
-
- ScrollbarThemeMacCommon::unregisterScrollbar(scrollbar);
-}
-
-void ScrollbarThemeMacOverlayAPI::setNewPainterForScrollbar(ScrollbarThemeClient* scrollbar, ScrollbarPainter newPainter)
-{
- scrollbarPainterMap()->set(scrollbar, newPainter);
- updateEnabledState(scrollbar);
- updateScrollbarOverlayStyle(scrollbar);
-}
-
-ScrollbarPainter ScrollbarThemeMacOverlayAPI::painterForScrollbar(ScrollbarThemeClient* scrollbar)
-{
- return scrollbarPainterMap()->get(scrollbar).get();
-}
-
-void ScrollbarThemeMacOverlayAPI::paintTrackBackground(GraphicsContext* context, ScrollbarThemeClient* scrollbar, const IntRect& rect) {
- ASSERT(isScrollbarOverlayAPIAvailable());
-
- GraphicsContextStateSaver stateSaver(*context);
- context->translate(rect.x(), rect.y());
- LocalCurrentGraphicsContext localContext(context);
-
- CGRect frameRect = scrollbar->frameRect();
- ScrollbarPainter scrollbarPainter = painterForScrollbar(scrollbar);
- [scrollbarPainter setEnabled:scrollbar->enabled()];
- [scrollbarPainter setBoundsSize: NSSizeFromCGSize(frameRect.size)];
-
- NSRect trackRect = NSMakeRect(0, 0, frameRect.size.width, frameRect.size.height);
- [scrollbarPainter drawKnobSlotInRect:trackRect highlight:NO];
-}
-
-void ScrollbarThemeMacOverlayAPI::paintThumb(GraphicsContext* context, ScrollbarThemeClient* scrollbar, const IntRect& rect) {
- ASSERT(isScrollbarOverlayAPIAvailable());
-
- GraphicsContextStateSaver stateSaver(*context);
- context->translate(rect.x(), rect.y());
- LocalCurrentGraphicsContext localContext(context);
-
- ScrollbarPainter scrollbarPainter = painterForScrollbar(scrollbar);
- CGRect frameRect = scrollbar->frameRect();
- [scrollbarPainter setEnabled:scrollbar->enabled()];
- [scrollbarPainter setBoundsSize:NSSizeFromCGSize(rect.size())];
- [scrollbarPainter setDoubleValue:0];
- [scrollbarPainter setKnobProportion:1];
- if (scrollbar->enabled())
- [scrollbarPainter drawKnob];
-
- // If this state is not set, then moving the cursor over the scrollbar area will only cause the
- // scrollbar to engorge when moved over the top of the scrollbar area.
- [scrollbarPainter setBoundsSize: NSSizeFromCGSize(scrollbar->frameRect().size())];
-}
-
-int ScrollbarThemeMacOverlayAPI::scrollbarThickness(ScrollbarControlSize controlSize)
-{
- ScrollbarPainter scrollbarPainter = [NSClassFromString(@"NSScrollerImp") scrollerImpWithStyle:recommendedScrollerStyle() controlSize:controlSize horizontal:NO replacingScrollerImp:nil];
- if (supportsExpandedScrollbars())
- [scrollbarPainter setExpanded:YES];
- return [scrollbarPainter trackBoxWidth];
-}
-
-bool ScrollbarThemeMacOverlayAPI::usesOverlayScrollbars() const
-{
- return recommendedScrollerStyle() == NSScrollerStyleOverlay;
-}
-
-void ScrollbarThemeMacOverlayAPI::updateScrollbarOverlayStyle(ScrollbarThemeClient* scrollbar)
-{
- ScrollbarPainter painter = painterForScrollbar(scrollbar);
- switch (scrollbar->scrollbarOverlayStyle()) {
- case ScrollbarOverlayStyleDefault:
- [painter setKnobStyle:NSScrollerKnobStyleDefault];
- break;
- case ScrollbarOverlayStyleDark:
- [painter setKnobStyle:NSScrollerKnobStyleDark];
- break;
- case ScrollbarOverlayStyleLight:
- [painter setKnobStyle:NSScrollerKnobStyleLight];
- break;
- }
-}
-
-ScrollbarButtonsPlacement ScrollbarThemeMacOverlayAPI::buttonsPlacement() const
-{
- return ScrollbarButtonsNone;
-}
-
-bool ScrollbarThemeMacOverlayAPI::hasThumb(ScrollbarThemeClient* scrollbar)
-{
- ScrollbarPainter painter = painterForScrollbar(scrollbar);
- int minLengthForThumb = [painter knobMinLength] + [painter trackOverlapEndInset] + [painter knobOverlapEndInset]
- + 2 * ([painter trackEndInset] + [painter knobEndInset]);
- return scrollbar->enabled() && (scrollbar->orientation() == HorizontalScrollbar ?
- scrollbar->width() :
- scrollbar->height()) >= minLengthForThumb;
-}
-
-IntRect ScrollbarThemeMacOverlayAPI::backButtonRect(ScrollbarThemeClient* scrollbar, ScrollbarPart part, bool painting)
-{
- ASSERT(buttonsPlacement() == ScrollbarButtonsNone);
- return IntRect();
-}
-
-IntRect ScrollbarThemeMacOverlayAPI::forwardButtonRect(ScrollbarThemeClient* scrollbar, ScrollbarPart part, bool painting)
-{
- ASSERT(buttonsPlacement() == ScrollbarButtonsNone);
- return IntRect();
-}
-
-IntRect ScrollbarThemeMacOverlayAPI::trackRect(ScrollbarThemeClient* scrollbar, bool painting)
-{
- ASSERT(!hasButtons(scrollbar));
- return scrollbar->frameRect();
-}
-
-int ScrollbarThemeMacOverlayAPI::minimumThumbLength(ScrollbarThemeClient* scrollbar)
-{
- return [painterForScrollbar(scrollbar) knobMinLength];
-}
-
-void ScrollbarThemeMacOverlayAPI::updateEnabledState(ScrollbarThemeClient* scrollbar)
-{
- [painterForScrollbar(scrollbar) setEnabled:scrollbar->enabled()];
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeNonMacCommon.cpp b/chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeNonMacCommon.cpp
deleted file mode 100644
index 72208ba0493..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeNonMacCommon.cpp
+++ /dev/null
@@ -1,130 +0,0 @@
-/*
- * Copyright (C) 2008 Apple Inc. All Rights Reserved.
- * Copyright (C) 2008, 2009 Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/ScrollbarThemeNonMacCommon.h"
-
-#include "core/platform/PlatformMouseEvent.h"
-#include "core/platform/ScrollableArea.h"
-#include "core/platform/Scrollbar.h"
-#include "core/platform/ScrollbarTheme.h"
-#include "core/platform/graphics/GraphicsContextStateSaver.h"
-
-namespace WebCore {
-
-bool ScrollbarThemeNonMacCommon::hasThumb(ScrollbarThemeClient* scrollbar)
-{
- // This method is just called as a paint-time optimization to see if
- // painting the thumb can be skipped. We don't have to be exact here.
- return thumbLength(scrollbar) > 0;
-}
-
-IntRect ScrollbarThemeNonMacCommon::backButtonRect(ScrollbarThemeClient* scrollbar, ScrollbarPart part, bool)
-{
- // Windows and Linux just have single arrows.
- if (part == BackButtonEndPart)
- return IntRect();
-
- IntSize size = buttonSize(scrollbar);
- return IntRect(scrollbar->x(), scrollbar->y(), size.width(), size.height());
-}
-
-IntRect ScrollbarThemeNonMacCommon::forwardButtonRect(ScrollbarThemeClient* scrollbar, ScrollbarPart part, bool)
-{
- // Windows and Linux just have single arrows.
- if (part == ForwardButtonStartPart)
- return IntRect();
-
- IntSize size = buttonSize(scrollbar);
- int x, y;
- if (scrollbar->orientation() == HorizontalScrollbar) {
- x = scrollbar->x() + scrollbar->width() - size.width();
- y = scrollbar->y();
- } else {
- x = scrollbar->x();
- y = scrollbar->y() + scrollbar->height() - size.height();
- }
- return IntRect(x, y, size.width(), size.height());
-}
-
-IntRect ScrollbarThemeNonMacCommon::trackRect(ScrollbarThemeClient* scrollbar, bool)
-{
- IntSize bs = buttonSize(scrollbar);
- int thickness = scrollbarThickness(scrollbar->controlSize());
- if (scrollbar->orientation() == HorizontalScrollbar) {
- // Once the scrollbar becomes smaller than the size of the
- // two buttons with a 1 pixel gap, the track disappears.
- if (scrollbar->width() <= 2 * bs.width() + 1)
- return IntRect();
- return IntRect(scrollbar->x() + bs.width(), scrollbar->y(), scrollbar->width() - 2 * bs.width(), thickness);
- }
- if (scrollbar->height() <= 2 * bs.height() + 1)
- return IntRect();
- return IntRect(scrollbar->x(), scrollbar->y() + bs.height(), thickness, scrollbar->height() - 2 * bs.height());
-}
-
-void ScrollbarThemeNonMacCommon::paintTrackBackground(GraphicsContext* context, ScrollbarThemeClient* scrollbar, const IntRect& rect)
-{
- // Just assume a forward track part. We only paint the track as a single piece when there is no thumb.
- if (!hasThumb(scrollbar))
- paintTrackPiece(context, scrollbar, rect, ForwardTrackPart);
-}
-
-void ScrollbarThemeNonMacCommon::paintTickmarks(GraphicsContext* context, ScrollbarThemeClient* scrollbar, const IntRect& rect)
-{
- if (scrollbar->orientation() != VerticalScrollbar)
- return;
-
- if (rect.height() <= 0 || rect.width() <= 0)
- return;
-
- // Get the tickmarks for the frameview.
- Vector<IntRect> tickmarks;
- scrollbar->getTickmarks(tickmarks);
- if (!tickmarks.size())
- return;
-
- GraphicsContextStateSaver stateSaver(*context);
- context->setShouldAntialias(false);
-
- for (Vector<IntRect>::const_iterator i = tickmarks.begin(); i != tickmarks.end(); ++i) {
- // Calculate how far down (in %) the tick-mark should appear.
- const float percent = static_cast<float>(i->y()) / scrollbar->totalSize();
-
- // Calculate how far down (in pixels) the tick-mark should appear.
- const int yPos = rect.y() + (rect.height() * percent);
-
- context->setFillColor(Color(0xCC, 0xAA, 0x00, 0xFF));
- FloatRect tickRect(rect.x(), yPos, rect.width(), 3);
- context->fillRect(tickRect);
-
- context->setFillColor(Color(0xFF, 0xDD, 0x00, 0xFF));
- FloatRect tickStroke(rect.x(), yPos + 1, rect.width(), 1);
- context->fillRect(tickStroke);
- }
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeNonMacCommon.h b/chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeNonMacCommon.h
deleted file mode 100644
index 3fc76476037..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeNonMacCommon.h
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Copyright (c) 2008, 2009, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ScrollbarThemeNonMacCommon_h
-#define ScrollbarThemeNonMacCommon_h
-
-#include "core/platform/ScrollbarTheme.h"
-
-namespace WebCore {
-
-class PlatformMouseEvent;
-
-class ScrollbarThemeNonMacCommon : public ScrollbarTheme {
-protected:
- virtual bool hasButtons(ScrollbarThemeClient*) OVERRIDE { return true; }
- virtual bool hasThumb(ScrollbarThemeClient*) OVERRIDE;
-
- virtual IntRect backButtonRect(ScrollbarThemeClient*, ScrollbarPart, bool painting = false) OVERRIDE;
- virtual IntRect forwardButtonRect(ScrollbarThemeClient*, ScrollbarPart, bool painting = false) OVERRIDE;
- virtual IntRect trackRect(ScrollbarThemeClient*, bool painting = false) OVERRIDE;
-
- virtual void paintTrackBackground(GraphicsContext*, ScrollbarThemeClient*, const IntRect&) OVERRIDE;
- virtual void paintTickmarks(GraphicsContext*, ScrollbarThemeClient*, const IntRect&) OVERRIDE;
-
- virtual IntSize buttonSize(ScrollbarThemeClient*) = 0;
-};
-
-} // namespace WebCore
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeOverlay.cpp b/chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeOverlay.cpp
deleted file mode 100644
index 4d705a0b8b7..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeOverlay.cpp
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/ScrollbarThemeOverlay.h"
-
-#include "core/platform/PlatformMouseEvent.h"
-#include "core/platform/Scrollbar.h"
-#include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/graphics/transforms/TransformationMatrix.h"
-
-#include <algorithm>
-
-using namespace std;
-
-namespace WebCore {
-
-ScrollbarThemeOverlay::ScrollbarThemeOverlay(int thumbThickness, int scrollbarMargin, HitTestBehavior allowHitTest, Color color)
- : ScrollbarTheme()
- , m_thumbThickness(thumbThickness)
- , m_scrollbarMargin(scrollbarMargin)
- , m_allowHitTest(allowHitTest)
- , m_color(color)
-{
-}
-
-int ScrollbarThemeOverlay::scrollbarThickness(ScrollbarControlSize controlSize)
-{
- return m_thumbThickness + m_scrollbarMargin;
-}
-
-bool ScrollbarThemeOverlay::usesOverlayScrollbars() const
-{
- return true;
-}
-
-int ScrollbarThemeOverlay::thumbPosition(ScrollbarThemeClient* scrollbar)
-{
- if (!scrollbar->totalSize())
- return 0;
-
- int trackLen = trackLength(scrollbar);
- float proportion = static_cast<float>(scrollbar->currentPos()) / scrollbar->totalSize();
- return round(proportion * trackLen);
-}
-
-int ScrollbarThemeOverlay::thumbLength(ScrollbarThemeClient* scrollbar)
-{
- int trackLen = trackLength(scrollbar);
-
- if (!scrollbar->totalSize())
- return trackLen;
-
- float proportion = static_cast<float>(scrollbar->visibleSize()) / scrollbar->totalSize();
- int length = round(proportion * trackLen);
- length = min(max(length, minimumThumbLength(scrollbar)), trackLen);
- return length;
-}
-
-bool ScrollbarThemeOverlay::hasThumb(ScrollbarThemeClient* scrollbar)
-{
- return true;
-}
-
-IntRect ScrollbarThemeOverlay::backButtonRect(ScrollbarThemeClient*, ScrollbarPart, bool)
-{
- return IntRect();
-}
-
-IntRect ScrollbarThemeOverlay::forwardButtonRect(ScrollbarThemeClient*, ScrollbarPart, bool)
-{
- return IntRect();
-}
-
-IntRect ScrollbarThemeOverlay::trackRect(ScrollbarThemeClient* scrollbar, bool)
-{
- IntRect rect = scrollbar->frameRect();
- if (scrollbar->orientation() == HorizontalScrollbar)
- rect.inflateX(-m_scrollbarMargin);
- else
- rect.inflateY(-m_scrollbarMargin);
- return rect;
-}
-
-int ScrollbarThemeOverlay::thumbThickness(ScrollbarThemeClient*)
-{
- return m_thumbThickness;
-}
-
-void ScrollbarThemeOverlay::paintThumb(GraphicsContext* context, ScrollbarThemeClient* scrollbar, const IntRect& rect)
-{
- IntRect thumbRect = rect;
- if (scrollbar->orientation() == HorizontalScrollbar) {
- thumbRect.setHeight(thumbRect.height() - m_scrollbarMargin);
- } else {
- thumbRect.setWidth(thumbRect.width() - m_scrollbarMargin);
- if (scrollbar->isLeftSideVerticalScrollbar())
- thumbRect.setX(thumbRect.x() + m_scrollbarMargin);
- }
- context->fillRect(thumbRect, m_color);
-}
-
-ScrollbarPart ScrollbarThemeOverlay::hitTest(ScrollbarThemeClient* scrollbar, const IntPoint& position)
-{
- if (m_allowHitTest == DisallowHitTest)
- return NoPart;
-
- return ScrollbarTheme::hitTest(scrollbar, position);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeOverlay.h b/chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeOverlay.h
deleted file mode 100644
index 0a7e2d1639d..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeOverlay.h
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ScrollbarThemeOverlay_h
-#define ScrollbarThemeOverlay_h
-
-#include "core/platform/ScrollbarTheme.h"
-
-namespace WebCore {
-
-// This scrollbar theme is used to get overlay scrollbar for platforms other
-// than Mac. Mac's overlay scrollbars are in ScrollbarThemeMac*.
-class ScrollbarThemeOverlay : public ScrollbarTheme {
-public:
- enum HitTestBehavior { AllowHitTest, DisallowHitTest };
-
- ScrollbarThemeOverlay(int thumbThickness, int scrollbarMargin, HitTestBehavior, Color = Color(128, 128, 128, 128));
- virtual ~ScrollbarThemeOverlay() { }
-
- virtual int scrollbarThickness(ScrollbarControlSize) OVERRIDE;
- virtual bool usesOverlayScrollbars() const OVERRIDE;
-
- virtual int thumbPosition(ScrollbarThemeClient*) OVERRIDE;
- virtual int thumbLength(ScrollbarThemeClient*) OVERRIDE;
-
- virtual bool hasButtons(ScrollbarThemeClient*) OVERRIDE { return false; };
- virtual bool hasThumb(ScrollbarThemeClient*) OVERRIDE;
-
- virtual IntRect backButtonRect(ScrollbarThemeClient*, ScrollbarPart, bool painting = false) OVERRIDE;
- virtual IntRect forwardButtonRect(ScrollbarThemeClient*, ScrollbarPart, bool painting = false) OVERRIDE;
- virtual IntRect trackRect(ScrollbarThemeClient*, bool painting = false) OVERRIDE;
- virtual int thumbThickness(ScrollbarThemeClient*) OVERRIDE;
-
- virtual void paintThumb(GraphicsContext*, ScrollbarThemeClient*, const IntRect&) OVERRIDE;
- virtual ScrollbarPart hitTest(ScrollbarThemeClient*, const IntPoint&) OVERRIDE;
-
-private:
- int m_thumbThickness;
- int m_scrollbarMargin;
- HitTestBehavior m_allowHitTest;
- Color m_color;
-};
-
-} // namespace WebCore
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeWin.cpp b/chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeWin.cpp
deleted file mode 100644
index d8f51e4e4c0..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeWin.cpp
+++ /dev/null
@@ -1,255 +0,0 @@
-/*
- * Copyright (C) 2008 Apple Inc. All Rights Reserved.
- * Copyright (C) 2008, 2009 Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/ScrollbarThemeWin.h"
-
-#include <windows.h>
-#include <vsstyle.h>
-
-#include "core/platform/LayoutTestSupport.h"
-#include "core/platform/PlatformMouseEvent.h"
-#include "core/platform/Scrollbar.h"
-#include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/win/SystemInfo.h"
-#include "public/platform/Platform.h"
-#include "public/platform/WebRect.h"
-#include "public/platform/win/WebThemeEngine.h"
-namespace WebCore {
-
-ScrollbarTheme* ScrollbarTheme::nativeTheme()
-{
- static ScrollbarThemeWin theme;
- return &theme;
-}
-
-// The scrollbar size in DumpRenderTree on the Mac - so we can match their
-// layout results. Entries are for regular, small, and mini scrollbars.
-// Metrics obtained using [NSScroller scrollerWidthForControlSize:]
-static const int kMacScrollbarSize[3] = { 15, 11, 15 };
-
-// Constants used to figure the drag rect outside which we should snap the
-// scrollbar thumb back to its origin. These calculations are based on
-// observing the behavior of the MSVC8 main window scrollbar + some
-// guessing/extrapolation.
-static const int kOffEndMultiplier = 3;
-static const int kOffSideMultiplier = 8;
-
-int ScrollbarThemeWin::scrollbarThickness(ScrollbarControlSize controlSize)
-{
- static int thickness;
- if (!thickness) {
- if (isRunningLayoutTest())
- return kMacScrollbarSize[controlSize];
- thickness = IntSize(WebKit::Platform::current()->themeEngine()->getSize(SBP_ARROWBTN)).width();
- }
- return thickness;
-}
-
-bool ScrollbarThemeWin::invalidateOnMouseEnterExit()
-{
- return windowsVersion() >= WindowsVista;
-}
-
-bool ScrollbarThemeWin::shouldSnapBackToDragOrigin(ScrollbarThemeClient* scrollbar, const PlatformMouseEvent& evt)
-{
- // Find the rect within which we shouldn't snap, by expanding the track rect
- // in both dimensions.
- IntRect rect = trackRect(scrollbar);
- const bool horz = scrollbar->orientation() == HorizontalScrollbar;
- const int thickness = scrollbarThickness(scrollbar->controlSize());
- rect.inflateX((horz ? kOffEndMultiplier : kOffSideMultiplier) * thickness);
- rect.inflateY((horz ? kOffSideMultiplier : kOffEndMultiplier) * thickness);
-
- // Convert the event to local coordinates.
- IntPoint mousePosition = scrollbar->convertFromContainingWindow(evt.position());
- mousePosition.move(scrollbar->x(), scrollbar->y());
-
- // We should snap iff the event is outside our calculated rect.
- return !rect.contains(mousePosition);
-}
-
-void ScrollbarThemeWin::paintTrackPiece(GraphicsContext* gc, ScrollbarThemeClient* scrollbar, const IntRect& rect, ScrollbarPart partType)
-{
- bool horz = scrollbar->orientation() == HorizontalScrollbar;
-
- int partId;
- if (partType == BackTrackPart)
- partId = horz ? SBP_UPPERTRACKHORZ : SBP_UPPERTRACKVERT;
- else
- partId = horz ? SBP_LOWERTRACKHORZ : SBP_LOWERTRACKVERT;
-
- IntRect alignRect = trackRect(scrollbar, false);
-
- WebKit::WebCanvas* canvas = gc->canvas();
- // Draw the track area before/after the thumb on the scroll bar.
- WebKit::Platform::current()->themeEngine()->paintScrollbarTrack(canvas, partId, getThemeState(scrollbar, partType), getClassicThemeState(scrollbar, partType), WebKit::WebRect(rect), WebKit::WebRect(alignRect));
-}
-
-void ScrollbarThemeWin::paintButton(GraphicsContext* gc, ScrollbarThemeClient* scrollbar, const IntRect& rect, ScrollbarPart part)
-{
- bool horz = scrollbar->orientation() == HorizontalScrollbar;
-
- int partId;
- if (part == BackButtonStartPart || part == ForwardButtonStartPart)
- partId = horz ? DFCS_SCROLLLEFT : DFCS_SCROLLUP;
- else
- partId = horz ? DFCS_SCROLLRIGHT : DFCS_SCROLLDOWN;
-
- WebKit::WebCanvas* canvas = gc->canvas();
- // Draw the thumb (the box you drag in the scroll bar to scroll).
- WebKit::Platform::current()->themeEngine()->paintScrollbarArrow(canvas, getThemeArrowState(scrollbar, part), partId | getClassicThemeState(scrollbar, part), WebKit::WebRect(rect));
-}
-
-void ScrollbarThemeWin::paintThumb(GraphicsContext* gc, ScrollbarThemeClient* scrollbar, const IntRect& rect)
-{
- bool horz = scrollbar->orientation() == HorizontalScrollbar;
-
- WebKit::WebCanvas* canvas = gc->canvas();
- // Draw the thumb (the box you drag in the scroll bar to scroll).
- WebKit::Platform::current()->themeEngine()->paintScrollbarThumb(canvas, horz ? SBP_THUMBBTNHORZ : SBP_THUMBBTNVERT, getThemeState(scrollbar, ThumbPart), getClassicThemeState(scrollbar, ThumbPart), WebKit::WebRect(rect));
-
- // Draw the gripper (the three little lines on the thumb).
- WebKit::Platform::current()->themeEngine()->paintScrollbarThumb(canvas, horz ? SBP_GRIPPERHORZ : SBP_GRIPPERVERT, getThemeState(scrollbar, ThumbPart), getClassicThemeState(scrollbar, ThumbPart), WebKit::WebRect(rect));
-}
-
-int ScrollbarThemeWin::getThemeState(ScrollbarThemeClient* scrollbar, ScrollbarPart part) const
-{
- // When dragging the thumb, draw thumb pressed and other segments normal
- // regardless of where the cursor actually is. See also four places in
- // getThemeArrowState().
- if (scrollbar->pressedPart() == ThumbPart) {
- if (part == ThumbPart)
- return SCRBS_PRESSED;
- return (windowsVersion() < WindowsVista) ? SCRBS_NORMAL : SCRBS_HOVER;
- }
- if (!scrollbar->enabled())
- return SCRBS_DISABLED;
- if (scrollbar->hoveredPart() != part || part == BackTrackPart || part == ForwardTrackPart)
- return (scrollbar->hoveredPart() == NoPart || (windowsVersion() < WindowsVista)) ? SCRBS_NORMAL : SCRBS_HOVER;
- if (scrollbar->pressedPart() == NoPart)
- return SCRBS_HOT;
- return (scrollbar->pressedPart() == part) ? SCRBS_PRESSED : SCRBS_NORMAL;
-}
-
-int ScrollbarThemeWin::getThemeArrowState(ScrollbarThemeClient* scrollbar, ScrollbarPart part) const
-{
- // We could take advantage of knowing the values in the state enum to write
- // some simpler code, but treating the state enum as a black box seems
- // clearer and more future-proof.
- if (part == BackButtonStartPart || part == ForwardButtonStartPart) {
- if (scrollbar->orientation() == HorizontalScrollbar) {
- if (scrollbar->pressedPart() == ThumbPart)
- return (windowsVersion() < WindowsVista) ? ABS_LEFTNORMAL : ABS_LEFTHOVER;
- if (!scrollbar->enabled())
- return ABS_LEFTDISABLED;
- if (scrollbar->hoveredPart() != part)
- return ((scrollbar->hoveredPart() == NoPart) || (windowsVersion() < WindowsVista)) ? ABS_LEFTNORMAL : ABS_LEFTHOVER;
- if (scrollbar->pressedPart() == NoPart)
- return ABS_LEFTHOT;
- return (scrollbar->pressedPart() == part) ?
- ABS_LEFTPRESSED : ABS_LEFTNORMAL;
- }
- if (scrollbar->pressedPart() == ThumbPart)
- return (windowsVersion() < WindowsVista) ? ABS_UPNORMAL : ABS_UPHOVER;
- if (!scrollbar->enabled())
- return ABS_UPDISABLED;
- if (scrollbar->hoveredPart() != part)
- return ((scrollbar->hoveredPart() == NoPart) || (windowsVersion() < WindowsVista)) ? ABS_UPNORMAL : ABS_UPHOVER;
- if (scrollbar->pressedPart() == NoPart)
- return ABS_UPHOT;
- return (scrollbar->pressedPart() == part) ? ABS_UPPRESSED : ABS_UPNORMAL;
- }
- if (scrollbar->orientation() == HorizontalScrollbar) {
- if (scrollbar->pressedPart() == ThumbPart)
- return (windowsVersion() < WindowsVista) ? ABS_RIGHTNORMAL : ABS_RIGHTHOVER;
- if (!scrollbar->enabled())
- return ABS_RIGHTDISABLED;
- if (scrollbar->hoveredPart() != part)
- return ((scrollbar->hoveredPart() == NoPart) || (windowsVersion() < WindowsVista)) ? ABS_RIGHTNORMAL : ABS_RIGHTHOVER;
- if (scrollbar->pressedPart() == NoPart)
- return ABS_RIGHTHOT;
- return (scrollbar->pressedPart() == part) ? ABS_RIGHTPRESSED : ABS_RIGHTNORMAL;
- }
- if (scrollbar->pressedPart() == ThumbPart)
- return (windowsVersion() < WindowsVista) ? ABS_DOWNNORMAL : ABS_DOWNHOVER;
- if (!scrollbar->enabled())
- return ABS_DOWNDISABLED;
- if (scrollbar->hoveredPart() != part)
- return ((scrollbar->hoveredPart() == NoPart) || (windowsVersion() < WindowsVista)) ? ABS_DOWNNORMAL : ABS_DOWNHOVER;
- if (scrollbar->pressedPart() == NoPart)
- return ABS_DOWNHOT;
- return (scrollbar->pressedPart() == part) ? ABS_DOWNPRESSED : ABS_DOWNNORMAL;
-}
-
-int ScrollbarThemeWin::getClassicThemeState(ScrollbarThemeClient* scrollbar, ScrollbarPart part) const
-{
- // When dragging the thumb, draw the buttons normal even when hovered.
- if (scrollbar->pressedPart() == ThumbPart)
- return 0;
- if (!scrollbar->enabled())
- return DFCS_INACTIVE;
- if (scrollbar->hoveredPart() != part || part == BackTrackPart || part == ForwardTrackPart)
- return 0;
- if (scrollbar->pressedPart() == NoPart)
- return DFCS_HOT;
- return (scrollbar->pressedPart() == part) ? (DFCS_PUSHED | DFCS_FLAT) : 0;
-}
-
-bool ScrollbarThemeWin::shouldCenterOnThumb(ScrollbarThemeClient*, const PlatformMouseEvent& evt)
-{
- return evt.shiftKey() && evt.button() == LeftButton;
-}
-
-IntSize ScrollbarThemeWin::buttonSize(ScrollbarThemeClient* scrollbar)
-{
- // Our desired rect is essentially thickness by thickness.
-
- // Our actual rect will shrink to half the available space when we have < 2
- // times thickness pixels left. This allows the scrollbar to scale down
- // and function even at tiny sizes.
-
- int thickness = scrollbarThickness(scrollbar->controlSize());
-
- // In layout test mode, we force the button "girth" (i.e., the length of
- // the button along the axis of the scrollbar) to be a fixed size.
- // FIXME: This is retarded! scrollbarThickness is already fixed in layout
- // test mode so that should be enough to result in repeatable results, but
- // preserving this hack avoids having to rebaseline pixel tests.
- const int kLayoutTestModeGirth = 17;
- int girth = isRunningLayoutTest() ? kLayoutTestModeGirth : thickness;
-
- if (scrollbar->orientation() == HorizontalScrollbar) {
- int width = scrollbar->width() < 2 * girth ? scrollbar->width() / 2 : girth;
- return IntSize(width, thickness);
- }
-
- int height = scrollbar->height() < 2 * girth ? scrollbar->height() / 2 : girth;
- return IntSize(thickness, height);
-}
-
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeWin.h b/chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeWin.h
deleted file mode 100644
index 5b5ee6e444a..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/ScrollbarThemeWin.h
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Copyright (c) 2009, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ScrollbarThemeWin_h
-#define ScrollbarThemeWin_h
-
-#include "core/platform/ScrollbarThemeNonMacCommon.h"
-
-namespace WebCore {
-
-class ScrollbarThemeWin : public ScrollbarThemeNonMacCommon {
-public:
- virtual int scrollbarThickness(ScrollbarControlSize) OVERRIDE;
- virtual bool invalidateOnMouseEnterExit() OVERRIDE;
- virtual bool shouldSnapBackToDragOrigin(ScrollbarThemeClient*, const PlatformMouseEvent&) OVERRIDE;
-
-protected:
- virtual void paintTrackPiece(GraphicsContext*, ScrollbarThemeClient*, const IntRect&, ScrollbarPart) OVERRIDE;
- virtual void paintButton(GraphicsContext*, ScrollbarThemeClient*, const IntRect&, ScrollbarPart) OVERRIDE;
- virtual void paintThumb(GraphicsContext*, ScrollbarThemeClient*, const IntRect&) OVERRIDE;
- virtual bool shouldCenterOnThumb(ScrollbarThemeClient*, const PlatformMouseEvent&) OVERRIDE;
- virtual IntSize buttonSize(ScrollbarThemeClient*) OVERRIDE;
-
-private:
- int getThemeState(ScrollbarThemeClient*, ScrollbarPart) const;
- int getThemeArrowState(ScrollbarThemeClient*, ScrollbarPart) const;
- int getClassicThemeState(ScrollbarThemeClient*, ScrollbarPart) const;
-};
-
-} // namespace WebCore
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/SecureTextInput.cpp b/chromium/third_party/WebKit/Source/core/platform/SecureTextInput.cpp
deleted file mode 100644
index 78d3b81498e..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/SecureTextInput.cpp
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Copyright (C) 2006, 2007 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-// FIXME: This should be moved to WebKit, because browser process needs to track secure input state anyway to manipulate input contexts.
-#if OS(MACOSX)
-#include "core/platform/SecureTextInput.h"
-
-#import <Carbon/Carbon.h>
-
-namespace WebCore {
-
-void enableSecureTextInput()
-{
- if (IsSecureEventInputEnabled())
- return;
- EnableSecureEventInput();
-}
-
-void disableSecureTextInput()
-{
- if (!IsSecureEventInputEnabled())
- return;
- DisableSecureEventInput();
-}
-
-} // namespace WebCore
-
-#endif // OS(MACOSX)
diff --git a/chromium/third_party/WebKit/Source/core/platform/SecureTextInput.h b/chromium/third_party/WebKit/Source/core/platform/SecureTextInput.h
deleted file mode 100644
index 146e62c598d..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/SecureTextInput.h
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Copyright (c) 2009, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SecureTextInput_h
-#define SecureTextInput_h
-
-namespace WebCore {
-
-// Once enableSecureTextInput is called, secure text input mode is set until
-// disableSecureTextInput has been called.
-void enableSecureTextInput();
-void disableSecureTextInput();
-
-#if !OS(MACOSX)
-inline void enableSecureTextInput() { }
-inline void disableSecureTextInput() { }
-#endif
-
-} // namespace WebCore
-
-#endif // SecureTextInput_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/SerializedResource.h b/chromium/third_party/WebKit/Source/core/platform/SerializedResource.h
deleted file mode 100644
index 76fd022cd59..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/SerializedResource.h
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SerializedResource_h
-#define SerializedResource_h
-
-#include "core/platform/SharedBuffer.h"
-#include "weborigin/KURL.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-struct SerializedResource {
- KURL url;
- String mimeType;
- RefPtr<SharedBuffer> data;
-
- SerializedResource(const KURL& url, const String& mimeType, PassRefPtr<SharedBuffer> data)
- : url(url)
- , mimeType(mimeType)
- , data(data)
- {
- }
-};
-
-}
-
-#endif // SerializedResource_h
-
diff --git a/chromium/third_party/WebKit/Source/core/platform/SharedBuffer.cpp b/chromium/third_party/WebKit/Source/core/platform/SharedBuffer.cpp
deleted file mode 100644
index ce2c37a0f01..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/SharedBuffer.cpp
+++ /dev/null
@@ -1,440 +0,0 @@
-/*
- * Copyright (C) 2006, 2008 Apple Inc. All rights reserved.
- * Copyright (C) Research In Motion Limited 2009-2010. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/SharedBuffer.h"
-
-#include "core/platform/PurgeableBuffer.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/unicode/Unicode.h"
-#include "wtf/unicode/UTF8.h"
-
-#undef SHARED_BUFFER_STATS
-
-#ifdef SHARED_BUFFER_STATS
-#include "wtf/DataLog.h"
-#include "wtf/MainThread.h"
-#endif
-
-using namespace std;
-
-namespace WebCore {
-
-static const unsigned segmentSize = 0x1000;
-static const unsigned segmentPositionMask = 0x0FFF;
-
-static inline unsigned segmentIndex(unsigned position)
-{
- return position / segmentSize;
-}
-
-static inline unsigned offsetInSegment(unsigned position)
-{
- return position & segmentPositionMask;
-}
-
-static inline char* allocateSegment()
-{
- return static_cast<char*>(fastMalloc(segmentSize));
-}
-
-static inline void freeSegment(char* p)
-{
- fastFree(p);
-}
-
-#ifdef SHARED_BUFFER_STATS
-
-static Mutex& statsMutex()
-{
- DEFINE_STATIC_LOCAL(Mutex, mutex, ());
- return mutex;
-}
-
-static HashSet<SharedBuffer*>& liveBuffers()
-{
- DEFINE_STATIC_LOCAL(HashSet<SharedBuffer*>, buffers, ());
- return buffers;
-}
-
-static bool sizeComparator(SharedBuffer* a, SharedBuffer* b)
-{
- return a->size() > b->size();
-}
-
-static CString snippetForBuffer(SharedBuffer* sharedBuffer)
-{
- const unsigned kMaxSnippetLength = 64;
- char* snippet = 0;
- unsigned snippetLength = std::min(sharedBuffer->size(), kMaxSnippetLength);
- CString result = CString::newUninitialized(snippetLength, snippet);
-
- const char* segment;
- unsigned offset = 0;
- while (unsigned segmentLength = sharedBuffer->getSomeData(segment, offset)) {
- unsigned length = std::min(segmentLength, snippetLength - offset);
- memcpy(snippet + offset, segment, length);
- offset += segmentLength;
- if (offset >= snippetLength)
- break;
- }
-
- for (unsigned i = 0; i < snippetLength; ++i) {
- if (!isASCIIPrintable(snippet[i]))
- snippet[i] = '?';
- }
-
- return result;
-}
-
-static void printStats(void*)
-{
- MutexLocker locker(statsMutex());
- Vector<SharedBuffer*> buffers;
- for (HashSet<SharedBuffer*>::const_iterator iter = liveBuffers().begin(); iter != liveBuffers().end(); ++iter)
- buffers.append(*iter);
- std::sort(buffers.begin(), buffers.end(), sizeComparator);
-
- dataLogF("---- Shared Buffer Stats ----\n");
- for (size_t i = 0; i < buffers.size() && i < 64; ++i) {
- CString snippet = snippetForBuffer(buffers[i]);
- dataLogF("Buffer size=%8u %s\n", buffers[i]->size(), snippet.data());
- }
-}
-
-static void didCreateSharedBuffer(SharedBuffer* buffer)
-{
- MutexLocker locker(statsMutex());
- liveBuffers().add(buffer);
-
- callOnMainThread(printStats, 0);
-}
-
-static void willDestroySharedBuffer(SharedBuffer* buffer)
-{
- MutexLocker locker(statsMutex());
- liveBuffers().remove(buffer);
-}
-
-#endif
-
-SharedBuffer::SharedBuffer()
- : m_size(0)
-{
-#ifdef SHARED_BUFFER_STATS
- didCreateSharedBuffer(this);
-#endif
-}
-
-SharedBuffer::SharedBuffer(size_t size)
- : m_size(size)
- , m_buffer(size)
-{
-#ifdef SHARED_BUFFER_STATS
- didCreateSharedBuffer(this);
-#endif
-}
-
-SharedBuffer::SharedBuffer(const char* data, int size)
- : m_size(0)
-{
- // FIXME: Use unsigned consistently, and check for invalid casts when calling into SharedBuffer from other code.
- if (size < 0)
- CRASH();
-
- append(data, size);
-
-#ifdef SHARED_BUFFER_STATS
- didCreateSharedBuffer(this);
-#endif
-}
-
-SharedBuffer::SharedBuffer(const unsigned char* data, int size)
- : m_size(0)
-{
- // FIXME: Use unsigned consistently, and check for invalid casts when calling into SharedBuffer from other code.
- if (size < 0)
- CRASH();
-
- append(reinterpret_cast<const char*>(data), size);
-
-#ifdef SHARED_BUFFER_STATS
- didCreateSharedBuffer(this);
-#endif
-}
-
-SharedBuffer::~SharedBuffer()
-{
- clear();
-
-#ifdef SHARED_BUFFER_STATS
- willDestroySharedBuffer(this);
-#endif
-}
-
-PassRefPtr<SharedBuffer> SharedBuffer::adoptVector(Vector<char>& vector)
-{
- RefPtr<SharedBuffer> buffer = create();
- buffer->m_buffer.swap(vector);
- buffer->m_size = buffer->m_buffer.size();
- return buffer.release();
-}
-
-PassRefPtr<SharedBuffer> SharedBuffer::adoptPurgeableBuffer(PassOwnPtr<PurgeableBuffer> purgeableBuffer)
-{
- ASSERT(!purgeableBuffer->isPurgeable());
- RefPtr<SharedBuffer> buffer = create();
- buffer->m_purgeableBuffer = purgeableBuffer;
- return buffer.release();
-}
-
-unsigned SharedBuffer::size() const
-{
- if (m_purgeableBuffer)
- return m_purgeableBuffer->size();
-
- return m_size;
-}
-
-void SharedBuffer::createPurgeableBuffer() const
-{
- if (m_purgeableBuffer)
- return;
-
- m_purgeableBuffer = PurgeableBuffer::create(buffer().data(), m_size);
-}
-
-const char* SharedBuffer::data() const
-{
- if (m_purgeableBuffer)
- return m_purgeableBuffer->data();
-
- return this->buffer().data();
-}
-
-void SharedBuffer::moveTo(Vector<char>& result)
-{
- ASSERT(result.isEmpty());
- if (m_purgeableBuffer) {
- result.reserveCapacity(m_purgeableBuffer->size());
- result.append(m_purgeableBuffer->data(), m_purgeableBuffer->size());
- clear();
- return;
- }
-
- unsigned bufferSize = m_buffer.size();
- if (m_size == bufferSize) {
- m_buffer.swap(result);
- clear();
- return;
- }
-
- result.reserveCapacity(m_size);
-
- const char* segment = 0;
- unsigned position = 0;
- while (unsigned segmentSize = getSomeData(segment, position)) {
- result.append(segment, segmentSize);
- position += segmentSize;
- }
- ASSERT(result.size() == m_size);
- clear();
- return;
-}
-
-void SharedBuffer::append(SharedBuffer* data)
-{
- const char* segment;
- size_t position = 0;
- while (size_t length = data->getSomeData(segment, position)) {
- append(segment, length);
- position += length;
- }
-}
-
-void SharedBuffer::append(const char* data, unsigned length)
-{
- ASSERT(!m_purgeableBuffer);
- if (!length)
- return;
-
- unsigned positionInSegment = offsetInSegment(m_size - m_buffer.size());
- m_size += length;
-
- if (m_size <= segmentSize) {
- // No need to use segments for small resource data
- if (m_buffer.isEmpty())
- m_buffer.reserveInitialCapacity(length);
- m_buffer.append(data, length);
- return;
- }
-
- char* segment;
- if (!positionInSegment) {
- segment = allocateSegment();
- m_segments.append(segment);
- } else
- segment = m_segments.last() + positionInSegment;
-
- unsigned segmentFreeSpace = segmentSize - positionInSegment;
- unsigned bytesToCopy = min(length, segmentFreeSpace);
-
- for (;;) {
- memcpy(segment, data, bytesToCopy);
- if (static_cast<unsigned>(length) == bytesToCopy)
- break;
-
- length -= bytesToCopy;
- data += bytesToCopy;
- segment = allocateSegment();
- m_segments.append(segment);
- bytesToCopy = min(length, segmentSize);
- }
-}
-
-void SharedBuffer::append(const Vector<char>& data)
-{
- append(data.data(), data.size());
-}
-
-void SharedBuffer::clear()
-{
- for (unsigned i = 0; i < m_segments.size(); ++i)
- freeSegment(m_segments[i]);
-
- m_segments.clear();
- m_size = 0;
-
- m_buffer.clear();
- m_purgeableBuffer.clear();
-}
-
-PassRefPtr<SharedBuffer> SharedBuffer::copy() const
-{
- RefPtr<SharedBuffer> clone(adoptRef(new SharedBuffer));
- if (m_purgeableBuffer) {
- clone->append(data(), size());
- return clone.release();
- }
-
- clone->m_size = m_size;
- clone->m_buffer.reserveCapacity(m_size);
- clone->m_buffer.append(m_buffer.data(), m_buffer.size());
- if (!m_segments.isEmpty()) {
- const char* segment = 0;
- unsigned position = m_buffer.size();
- while (unsigned segmentSize = getSomeData(segment, position)) {
- clone->m_buffer.append(segment, segmentSize);
- position += segmentSize;
- }
- ASSERT(position == clone->size());
- }
- return clone.release();
-}
-
-PassOwnPtr<PurgeableBuffer> SharedBuffer::releasePurgeableBuffer()
-{
- ASSERT(hasOneRef());
- return m_purgeableBuffer.release();
-}
-
-const Vector<char>& SharedBuffer::buffer() const
-{
- unsigned bufferSize = m_buffer.size();
- if (m_size > bufferSize) {
- m_buffer.resize(m_size);
- char* destination = m_buffer.data() + bufferSize;
- unsigned bytesLeft = m_size - bufferSize;
- for (unsigned i = 0; i < m_segments.size(); ++i) {
- unsigned bytesToCopy = min(bytesLeft, segmentSize);
- memcpy(destination, m_segments[i], bytesToCopy);
- destination += bytesToCopy;
- bytesLeft -= bytesToCopy;
- freeSegment(m_segments[i]);
- }
- m_segments.clear();
- }
- return m_buffer;
-}
-
-unsigned SharedBuffer::getSomeData(const char*& someData, unsigned position) const
-{
- unsigned totalSize = size();
- if (position >= totalSize) {
- someData = 0;
- return 0;
- }
-
- if (m_purgeableBuffer) {
- ASSERT_WITH_SECURITY_IMPLICATION(position < size());
- someData = data() + position;
- return totalSize - position;
- }
-
- ASSERT_WITH_SECURITY_IMPLICATION(position < m_size);
- unsigned consecutiveSize = m_buffer.size();
- if (position < consecutiveSize) {
- someData = m_buffer.data() + position;
- return consecutiveSize - position;
- }
-
- position -= consecutiveSize;
- unsigned segments = m_segments.size();
- unsigned maxSegmentedSize = segments * segmentSize;
- unsigned segment = segmentIndex(position);
- if (segment < segments) {
- unsigned bytesLeft = totalSize - consecutiveSize;
- unsigned segmentedSize = min(maxSegmentedSize, bytesLeft);
-
- unsigned positionInSegment = offsetInSegment(position);
- someData = m_segments[segment] + positionInSegment;
- return segment == segments - 1 ? segmentedSize - position : segmentSize - positionInSegment;
- }
- ASSERT_NOT_REACHED();
- return 0;
-}
-
-PassRefPtr<ArrayBuffer> SharedBuffer::getAsArrayBuffer() const
-{
- RefPtr<ArrayBuffer> arrayBuffer = ArrayBuffer::createUninitialized(static_cast<unsigned>(size()), 1);
-
- const char* segment = 0;
- unsigned position = 0;
- while (unsigned segmentSize = getSomeData(segment, position)) {
- memcpy(static_cast<char*>(arrayBuffer->data()) + position, segment, segmentSize);
- position += segmentSize;
- }
-
- if (position != arrayBuffer->byteLength()) {
- ASSERT_NOT_REACHED();
- // Don't return the incomplete ArrayBuffer.
- return 0;
- }
-
- return arrayBuffer;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/SharedBuffer.h b/chromium/third_party/WebKit/Source/core/platform/SharedBuffer.h
deleted file mode 100644
index 4e6dcf8b869..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/SharedBuffer.h
+++ /dev/null
@@ -1,121 +0,0 @@
-/*
- * Copyright (C) 2006 Apple Computer, Inc. All rights reserved.
- * Copyright (C) Research In Motion Limited 2009-2010. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SharedBuffer_h
-#define SharedBuffer_h
-
-#include "wtf/ArrayBuffer.h"
-#include "wtf/Forward.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/Vector.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class PurgeableBuffer;
-
-class SharedBuffer : public RefCounted<SharedBuffer> {
-public:
- static PassRefPtr<SharedBuffer> create() { return adoptRef(new SharedBuffer); }
- static PassRefPtr<SharedBuffer> create(size_t size) { return adoptRef(new SharedBuffer(size)); }
- static PassRefPtr<SharedBuffer> create(const char* c, int i) { return adoptRef(new SharedBuffer(c, i)); }
- static PassRefPtr<SharedBuffer> create(const unsigned char* c, int i) { return adoptRef(new SharedBuffer(c, i)); }
-
- static PassRefPtr<SharedBuffer> adoptVector(Vector<char>& vector);
-
- // The buffer must be in non-purgeable state before adopted to a SharedBuffer.
- // It will stay that way until released.
- static PassRefPtr<SharedBuffer> adoptPurgeableBuffer(PassOwnPtr<PurgeableBuffer>);
-
- ~SharedBuffer();
-
- // Calling this function will force internal segmented buffers
- // to be merged into a flat buffer. Use getSomeData() whenever possible
- // for better performance.
- const char* data() const;
-
- void moveTo(Vector<char>&);
-
- unsigned size() const;
-
- bool isEmpty() const { return !size(); }
-
- void append(SharedBuffer*);
- void append(const char*, unsigned);
- void append(const Vector<char>&);
-
- void clear();
-
- PassRefPtr<SharedBuffer> copy() const;
-
- bool hasPurgeableBuffer() const { return m_purgeableBuffer.get(); }
-
- // Ensure this buffer has no other clients before calling this.
- PassOwnPtr<PurgeableBuffer> releasePurgeableBuffer();
-
- // Return the number of consecutive bytes after "position". "data"
- // points to the first byte.
- // Return 0 when no more data left.
- // When extracting all data with getSomeData(), the caller should
- // repeat calling it until it returns 0.
- // Usage:
- // const char* segment;
- // unsigned pos = 0;
- // while (unsigned length = sharedBuffer->getSomeData(segment, pos)) {
- // // Use the data. for example: decoder->decode(segment, length);
- // pos += length;
- // }
- unsigned getSomeData(const char*& data, unsigned position = 0) const;
-
- void createPurgeableBuffer() const;
-
- // Creates an ArrayBuffer and copies this SharedBuffer's contents to that
- // ArrayBuffer without merging segmented buffers into a flat buffer.
- PassRefPtr<ArrayBuffer> getAsArrayBuffer() const;
-
-private:
- SharedBuffer();
- explicit SharedBuffer(size_t);
- SharedBuffer(const char*, int);
- SharedBuffer(const unsigned char*, int);
-
- // Calling this function will force internal segmented buffers
- // to be merged into a flat buffer. Use getSomeData() whenever possible
- // for better performance.
- // As well, be aware that this method does *not* return any purgeable
- // memory, which can be a source of bugs.
- const Vector<char>& buffer() const;
-
- unsigned m_size;
- mutable Vector<char> m_buffer;
- mutable Vector<char*> m_segments;
- mutable OwnPtr<PurgeableBuffer> m_purgeableBuffer;
-};
-
-} // namespace WebCore
-
-#endif // SharedBuffer_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/SharedBufferChunkReader.cpp b/chromium/third_party/WebKit/Source/core/platform/SharedBufferChunkReader.cpp
deleted file mode 100644
index 8b216bd5623..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/SharedBufferChunkReader.cpp
+++ /dev/null
@@ -1,150 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/SharedBufferChunkReader.h"
-
-#include "core/platform/SharedBuffer.h"
-
-namespace WebCore {
-
-SharedBufferChunkReader::SharedBufferChunkReader(SharedBuffer* buffer, const Vector<char>& separator)
- : m_buffer(buffer)
- , m_bufferPosition(0)
- , m_segment(0)
- , m_segmentLength(0)
- , m_segmentIndex(0)
- , m_reachedEndOfFile(false)
- , m_separator(separator)
- , m_separatorIndex(0)
-{
-}
-
-SharedBufferChunkReader::SharedBufferChunkReader(SharedBuffer* buffer, const char* separator)
- : m_buffer(buffer)
- , m_bufferPosition(0)
- , m_segment(0)
- , m_segmentLength(0)
- , m_segmentIndex(0)
- , m_reachedEndOfFile(false)
- , m_separatorIndex(0)
-{
- setSeparator(separator);
-}
-
-void SharedBufferChunkReader::setSeparator(const Vector<char>& separator)
-{
- m_separator = separator;
-}
-
-void SharedBufferChunkReader::setSeparator(const char* separator)
-{
- m_separator.clear();
- m_separator.append(separator, strlen(separator));
-}
-
-bool SharedBufferChunkReader::nextChunk(Vector<char>& chunk, bool includeSeparator)
-{
- if (m_reachedEndOfFile)
- return false;
-
- chunk.clear();
- while (true) {
- while (m_segmentIndex < m_segmentLength) {
- char currentCharacter = m_segment[m_segmentIndex++];
- if (currentCharacter != m_separator[m_separatorIndex]) {
- if (m_separatorIndex > 0) {
- ASSERT_WITH_SECURITY_IMPLICATION(m_separatorIndex <= m_separator.size());
- chunk.append(m_separator.data(), m_separatorIndex);
- m_separatorIndex = 0;
- }
- chunk.append(currentCharacter);
- continue;
- }
- m_separatorIndex++;
- if (m_separatorIndex == m_separator.size()) {
- if (includeSeparator)
- chunk.append(m_separator);
- m_separatorIndex = 0;
- return true;
- }
- }
-
- // Read the next segment.
- m_segmentIndex = 0;
- m_bufferPosition += m_segmentLength;
- m_segmentLength = m_buffer->getSomeData(m_segment, m_bufferPosition);
- if (!m_segmentLength) {
- m_reachedEndOfFile = true;
- if (m_separatorIndex > 0)
- chunk.append(m_separator.data(), m_separatorIndex);
- return !chunk.isEmpty();
- }
- }
- ASSERT_NOT_REACHED();
- return false;
-}
-
-String SharedBufferChunkReader::nextChunkAsUTF8StringWithLatin1Fallback(bool includeSeparator)
-{
- Vector<char> data;
- if (!nextChunk(data, includeSeparator))
- return String();
-
- return data.size() ? String::fromUTF8WithLatin1Fallback(data.data(), data.size()) : emptyString();
-}
-
-size_t SharedBufferChunkReader::peek(Vector<char>& data, size_t requestedSize)
-{
- data.clear();
- if (requestedSize <= m_segmentLength - m_segmentIndex) {
- data.append(m_segment + m_segmentIndex, requestedSize);
- return requestedSize;
- }
-
- size_t readBytesCount = m_segmentLength - m_segmentIndex;
- data.append(m_segment + m_segmentIndex, readBytesCount);
-
- size_t bufferPosition = m_bufferPosition + m_segmentLength;
- const char* segment = 0;
- while (size_t segmentLength = m_buffer->getSomeData(segment, bufferPosition)) {
- if (requestedSize <= readBytesCount + segmentLength) {
- data.append(segment, requestedSize - readBytesCount);
- readBytesCount += (requestedSize - readBytesCount);
- break;
- }
- data.append(segment, segmentLength);
- readBytesCount += segmentLength;
- bufferPosition += segmentLength;
- }
- return readBytesCount;
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/SharedBufferChunkReader.h b/chromium/third_party/WebKit/Source/core/platform/SharedBufferChunkReader.h
deleted file mode 100644
index 107b46056fb..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/SharedBufferChunkReader.h
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SharedBufferChunkReader_h
-#define SharedBufferChunkReader_h
-
-#include "wtf/Vector.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class SharedBuffer;
-
-class SharedBufferChunkReader {
-public:
- SharedBufferChunkReader(SharedBuffer*, const Vector<char>& separator);
- SharedBufferChunkReader(SharedBuffer*, const char* separator);
-
- void setSeparator(const Vector<char>&);
- void setSeparator(const char*);
-
- // Returns false when the end of the buffer was reached.
- bool nextChunk(Vector<char>& data, bool includeSeparator = false);
-
- // Returns a null string when the end of the buffer has been reached.
- String nextChunkAsUTF8StringWithLatin1Fallback(bool includeSeparator = false);
-
- // Reads size bytes at the current location in the buffer, without changing the buffer position.
- // Returns the number of bytes read. That number might be less than the specified size if the end of the buffer was reached.
- size_t peek(Vector<char>&, size_t);
-
-private:
- SharedBuffer* m_buffer;
- size_t m_bufferPosition;
- const char* m_segment;
- size_t m_segmentLength;
- size_t m_segmentIndex;
- bool m_reachedEndOfFile;
- Vector<char> m_separator;
- size_t m_separatorIndex;
-};
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/SharedBufferTest.cpp b/chromium/third_party/WebKit/Source/core/platform/SharedBufferTest.cpp
deleted file mode 100644
index 1afa9140698..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/SharedBufferTest.cpp
+++ /dev/null
@@ -1,173 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/platform/SharedBuffer.h"
-
-#include "wtf/ArrayBuffer.h"
-#include "wtf/RefPtr.h"
-#include "wtf/Vector.h"
-#include <gtest/gtest.h>
-
-using namespace WebCore;
-
-namespace {
-
-TEST(SharedBufferTest, getAsArrayBuffer)
-{
- char testData0[] = "Hello";
- char testData1[] = "World";
- char testData2[] = "Goodbye";
-
- RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(testData0, strlen(testData0));
- sharedBuffer->append(testData1, strlen(testData1));
- sharedBuffer->append(testData2, strlen(testData2));
-
- RefPtr<ArrayBuffer> arrayBuffer = sharedBuffer->getAsArrayBuffer();
-
- char expectedConcatenation[] = "HelloWorldGoodbye";
- ASSERT_EQ(strlen(expectedConcatenation), arrayBuffer->byteLength());
- EXPECT_EQ(0, memcmp(expectedConcatenation, arrayBuffer->data(), strlen(expectedConcatenation)));
-}
-
-TEST(SharedBufferTest, moveToAvoidsMemcpy)
-{
- char testData[] = "Hello";
-
- RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(testData, strlen(testData));
-
- const char* originalData = sharedBuffer->data();
- const size_t originalSize = sharedBuffer->size();
-
- Vector<char> result;
- sharedBuffer->moveTo(result);
-
- EXPECT_TRUE(sharedBuffer->isEmpty());
- EXPECT_EQ(originalData, result.data());
- EXPECT_EQ(originalSize, result.size());
-}
-
-TEST(SharedBufferTest, moveToHandlesSegments)
-{
- Vector<char> vector0(0x4000);
- for (size_t i = 0; i < vector0.size(); ++i)
- vector0[i] = 'a';
- Vector<char> vector1(0x4000);
- for (size_t i = 0; i < vector1.size(); ++i)
- vector1[i] = 'b';
- Vector<char> vector2(0x4000);
- for (size_t i = 0; i < vector2.size(); ++i)
- vector2[i] = 'c';
-
- RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::adoptVector(vector0);
- sharedBuffer->append(vector1);
- sharedBuffer->append(vector2);
-
- const size_t originalSize = sharedBuffer->size();
-
- Vector<char> result;
- sharedBuffer->moveTo(result);
-
- EXPECT_TRUE(sharedBuffer->isEmpty());
- EXPECT_EQ(originalSize, result.size());
-}
-
-TEST(SharedBufferTest, getAsArrayBufferLargeSegments)
-{
- Vector<char> vector0(0x4000);
- for (size_t i = 0; i < vector0.size(); ++i)
- vector0[i] = 'a';
- Vector<char> vector1(0x4000);
- for (size_t i = 0; i < vector1.size(); ++i)
- vector1[i] = 'b';
- Vector<char> vector2(0x4000);
- for (size_t i = 0; i < vector2.size(); ++i)
- vector2[i] = 'c';
-
- RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::adoptVector(vector0);
- sharedBuffer->append(vector1);
- sharedBuffer->append(vector2);
-
- RefPtr<ArrayBuffer> arrayBuffer = sharedBuffer->getAsArrayBuffer();
-
- ASSERT_EQ(0x4000U + 0x4000U + 0x4000U, arrayBuffer->byteLength());
- int position = 0;
- for (int i = 0; i < 0x4000; ++i) {
- EXPECT_EQ('a', static_cast<char*>(arrayBuffer->data())[position]);
- ++position;
- }
- for (int i = 0; i < 0x4000; ++i) {
- EXPECT_EQ('b', static_cast<char*>(arrayBuffer->data())[position]);
- ++position;
- }
- for (int i = 0; i < 0x4000; ++i) {
- EXPECT_EQ('c', static_cast<char*>(arrayBuffer->data())[position]);
- ++position;
- }
-}
-
-TEST(SharedBufferTest, copy)
-{
- char testData[] = "Habitasse integer eros tincidunt a scelerisque! Enim elit? Scelerisque magnis,"
- "et montes ultrices tristique a! Pid. Velit turpis, dapibus integer rhoncus sociis amet facilisis,"
- "adipiscing pulvinar nascetur magnis tempor sit pulvinar, massa urna enim porttitor sociis sociis proin enim?"
- "Lectus, platea dolor, integer a. A habitasse hac nunc, nunc, nec placerat vut in sit nunc nec, sed. Sociis,"
- "vut! Hac, velit rhoncus facilisis. Rhoncus et, enim, sed et in tristique nunc montes,"
- "natoque nunc sagittis elementum parturient placerat dolor integer? Pulvinar,"
- "magnis dignissim porttitor ac pulvinar mid tempor. A risus sed mid! Magnis elit duis urna,"
- "cras massa, magna duis. Vut magnis pid a! Penatibus aliquet porttitor nunc, adipiscing massa odio lundium,"
- "risus elementum ac turpis massa pellentesque parturient augue. Purus amet turpis pid aliquam?"
- "Dolor est tincidunt? Dolor? Dignissim porttitor sit in aliquam! Tincidunt, non nunc, rhoncus dictumst!"
- "Porta augue etiam. Cursus augue nunc lacus scelerisque. Rhoncus lectus, integer hac, nec pulvinar augue massa,"
- "integer amet nisi facilisis? A! A, enim velit pulvinar elit in non scelerisque in et ultricies amet est!"
- "in porttitor montes lorem et, hac aliquet pellentesque a sed? Augue mid purus ridiculus vel dapibus,"
- "sagittis sed, tortor auctor nascetur rhoncus nec, rhoncus, magna integer. Sit eu massa vut?"
- "Porta augue porttitor elementum, enim, rhoncus pulvinar duis integer scelerisque rhoncus natoque,"
- "mattis dignissim massa ac pulvinar urna, nunc ut. Sagittis, aliquet penatibus proin lorem, pulvinar lectus,"
- "augue proin! Ac, arcu quis. Placerat habitasse, ridiculus ridiculus.";
-
- unsigned length = strlen(testData);
- RefPtr<SharedBuffer> sharedBuffer = SharedBuffer::create(testData, length);
- sharedBuffer->append(testData, length);
- sharedBuffer->append(testData, length);
- sharedBuffer->append(testData, length);
- // sharedBuffer must contain data more than segmentSize (= 0x1000) to check copy().
- ASSERT_EQ(length * 4, sharedBuffer->size());
-
- RefPtr<SharedBuffer> clone = sharedBuffer->copy();
- ASSERT_EQ(length * 4, clone->size());
- ASSERT_EQ(0, memcmp(clone->data(), sharedBuffer->data(), clone->size()));
-
- clone->append(testData, length);
- ASSERT_EQ(length * 5, clone->size());
-}
-
-} // namespace
diff --git a/chromium/third_party/WebKit/Source/core/platform/SharedTimer.h b/chromium/third_party/WebKit/Source/core/platform/SharedTimer.h
deleted file mode 100644
index eddeaf95483..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/SharedTimer.h
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * Copyright (C) 2006 Apple Computer, Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SharedTimer_h
-#define SharedTimer_h
-
-#include "wtf/FastAllocBase.h"
-#include "wtf/Noncopyable.h"
-
-namespace WebCore {
-
- // Each thread has its own single instance of shared timer, which implements this interface.
- // This instance is shared by all timers in the thread.
- // Not intended to be used directly; use the Timer class instead.
- class SharedTimer {
- WTF_MAKE_NONCOPYABLE(SharedTimer); WTF_MAKE_FAST_ALLOCATED;
- public:
- SharedTimer() { }
- virtual ~SharedTimer() {}
- virtual void setFiredFunction(void (*)()) = 0;
-
- // The fire interval is in seconds relative to the current monotonic clock time.
- virtual void setFireInterval(double) = 0;
- virtual void stop() = 0;
- };
-
-
- // Implemented by port (since it provides the run loop for the main thread).
- // FIXME: make ports implement MainThreadSharedTimer directly instead.
- void setSharedTimerFiredFunction(void (*)());
- void setSharedTimerFireInterval(double);
- void stopSharedTimer();
-
- // Implementation of SharedTimer for the main thread.
- class MainThreadSharedTimer : public SharedTimer {
- public:
- virtual void setFiredFunction(void (*function)())
- {
- setSharedTimerFiredFunction(function);
- }
-
- virtual void setFireInterval(double interval)
- {
- setSharedTimerFireInterval(interval);
- }
-
- virtual void stop()
- {
- stopSharedTimer();
- }
- };
-
-} // namespace WebCore
-
-#endif // SharedTimer_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/Sound.h b/chromium/third_party/WebKit/Source/core/platform/Sound.h
deleted file mode 100644
index be9ebe8a57a..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/Sound.h
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright (C) 2006 Apple Computer, Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef Sound_h
-#define Sound_h
-
-namespace WebCore {
-
- void systemBeep();
-
-} // namespace WebCore
-
-#endif // Sound_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/StatsCounter.h b/chromium/third_party/WebKit/Source/core/platform/StatsCounter.h
deleted file mode 100644
index edd3e796f54..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/StatsCounter.h
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef StatsCounter_h
-#define StatsCounter_h
-
-namespace WebCore {
-
-class StatsCounter {
-public:
- static void incrementStatsCounter(const char*);
-};
-
-} // namespace WebCore
-
-#endif // StatsCounter_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/SuddenTermination.h b/chromium/third_party/WebKit/Source/core/platform/SuddenTermination.h
deleted file mode 100644
index 2534f94c0d5..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/SuddenTermination.h
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright (C) 2009 Apple Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SuddenTermination_h
-#define SuddenTermination_h
-
-namespace WebCore {
-
- // Once disabled via one or more more calls to disableSuddenTermination(), fast shutdown
- // is not valid until enableSuddenTermination() has been called an equal number of times.
- // On Mac, these are thin wrappers around Mac OS X functions of the same name.
- void disableSuddenTermination();
- void enableSuddenTermination();
-} // namespace WebCore
-
-#endif // SuddenTermination_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/Supplementable.h b/chromium/third_party/WebKit/Source/core/platform/Supplementable.h
deleted file mode 100644
index e87c12fb68d..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/Supplementable.h
+++ /dev/null
@@ -1,156 +0,0 @@
-/*
- * Copyright (C) 2012 Google, Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef Supplementable_h
-#define Supplementable_h
-
-#include "wtf/Assertions.h"
-#include "wtf/HashMap.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/PassOwnPtr.h"
-
-#if !ASSERT_DISABLED
-#include "wtf/Threading.h"
-#endif
-
-namespace WebCore {
-
-// What you should know about Supplementable and Supplement
-// ========================================================
-// Supplementable and Supplement instances are meant to be thread local. They
-// should only be accessed from within the thread that created them. The
-// 2 classes are not designed for safe access from another thread. Violating
-// this design assumption can result in memory corruption and unpredictable
-// behavior.
-//
-// What you should know about the Supplement keys
-// ==============================================
-// The Supplement is expected to use the same const char* string instance
-// as its key. The Supplementable's SupplementMap will use the address of the
-// string as the key and not the characters themselves. Hence, 2 strings with
-// the same characters will be treated as 2 different keys.
-//
-// In practice, it is recommended that Supplements implements a static method
-// for returning its key to use. For example:
-//
-// class MyClass : public Supplement<MySupplementable> {
-// ...
-// static const char* supplementName();
-// }
-//
-// const char* MyClass::supplementName()
-// {
-// return "MyClass";
-// }
-//
-// An example of the using the key:
-//
-// MyClass* MyClass::from(MySupplementable* host)
-// {
-// return reinterpret_cast<MyClass*>(Supplement<MySupplementable>::from(host, supplementName()));
-// }
-//
-// What you should know about thread checks
-// ========================================
-// When assertion is enabled this class performs thread-safety check so that
-// provideTo and from happen on the same thread. If you want to provide
-// some value for Workers this thread check may not work very well though,
-// since in most case you'd provide the value while worker preparation is
-// being done on the main thread, even before the worker thread is started.
-// If that's the case you can explicitly call reattachThread() when the
-// Supplementable object is passed to the final destination thread (i.e.
-// worker thread). Please be extremely careful to use the method though,
-// as randomly calling the method could easily cause racy condition.
-//
-// Note that reattachThread() does nothing if assertion is not enabled.
-//
-
-template<typename T>
-class Supplementable;
-
-template<typename T>
-class Supplement {
-public:
- virtual ~Supplement() { }
-#if !ASSERT_DISABLED || defined(ADDRESS_SANITIZER)
- virtual bool isRefCountedWrapper() const { return false; }
-#endif
-
- static void provideTo(Supplementable<T>* host, const char* key, PassOwnPtr<Supplement<T> > supplement)
- {
- host->provideSupplement(key, supplement);
- }
-
- static Supplement<T>* from(Supplementable<T>* host, const char* key)
- {
- return host ? host->requireSupplement(key) : 0;
- }
-};
-
-template<typename T>
-class Supplementable {
-public:
- void provideSupplement(const char* key, PassOwnPtr<Supplement<T> > supplement)
- {
- ASSERT(m_threadId == currentThread());
- ASSERT(!m_supplements.get(key));
- m_supplements.set(key, supplement);
- }
-
- void removeSupplement(const char* key)
- {
- ASSERT(m_threadId == currentThread());
- m_supplements.remove(key);
- }
-
- Supplement<T>* requireSupplement(const char* key)
- {
- ASSERT(m_threadId == currentThread());
- return m_supplements.get(key);
- }
-
- void reattachThread()
- {
-#if !ASSERT_DISABLED
- m_threadId = currentThread();
-#endif
- }
-
-#if !ASSERT_DISABLED
-protected:
- Supplementable() : m_threadId(currentThread()) { }
-#endif
-
-private:
- typedef HashMap<const char*, OwnPtr<Supplement<T> >, PtrHash<const char*> > SupplementMap;
- SupplementMap m_supplements;
-#if !ASSERT_DISABLED
- ThreadIdentifier m_threadId;
-#endif
-};
-
-} // namespace WebCore
-
-#endif // Supplementable_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/Task.h b/chromium/third_party/WebKit/Source/core/platform/Task.h
deleted file mode 100644
index b9d2e46802a..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/Task.h
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef Task_h
-#define Task_h
-
-#include "wtf/Functional.h"
-#include "public/platform/WebThread.h"
-
-namespace WebCore {
-
-class Task : public WebKit::WebThread::Task {
-public:
- explicit Task(const Closure& closure)
- : m_closure(closure)
- {
- }
-
- virtual void run() OVERRIDE
- {
- m_closure();
- }
-
-private:
- Closure m_closure;
-};
-
-} // namespace WebCore
-
-#endif // Task_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/Theme.cpp b/chromium/third_party/WebKit/Source/core/platform/Theme.cpp
deleted file mode 100644
index 1aa63bee880..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/Theme.cpp
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * Copyright (C) 2008 Apple Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/Theme.h"
-
-namespace WebCore {
-
-LengthBox Theme::controlBorder(ControlPart part, const Font&, const LengthBox& zoomedBox, float) const
-{
- switch (part) {
- case PushButtonPart:
- case MenulistPart:
- case SearchFieldPart:
- case CheckboxPart:
- case RadioPart:
- return LengthBox(0);
- default:
- return zoomedBox;
- }
-}
-
-LengthBox Theme::controlPadding(ControlPart part, const Font&, const LengthBox& zoomedBox, float) const
-{
- switch (part) {
- case MenulistPart:
- case MenulistButtonPart:
- case CheckboxPart:
- case RadioPart:
- return LengthBox(0);
- default:
- return zoomedBox;
- }
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/Theme.h b/chromium/third_party/WebKit/Source/core/platform/Theme.h
deleted file mode 100644
index d4ba7979d09..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/Theme.h
+++ /dev/null
@@ -1,115 +0,0 @@
-/*
- * Copyright (C) 2008 Apple Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef Theme_h
-#define Theme_h
-
-#include "core/platform/LengthBox.h"
-#include "core/platform/LengthSize.h"
-#include "core/platform/ThemeTypes.h"
-#include "core/platform/graphics/Color.h"
-#include "core/platform/graphics/Font.h"
-#include "core/platform/graphics/IntRect.h"
-#include "wtf/Forward.h"
-
-namespace WebCore {
-
-class GraphicsContext;
-class ScrollView;
-
-// Unlike other platform classes, Theme does extensively use virtual functions. This design allows a platform to switch between multiple themes at runtime.
-class Theme {
-public:
- Theme() { }
- virtual ~Theme() { }
-
- // A method to obtain the baseline position adjustment for a "leaf" control. This will only be used if a baseline
- // position cannot be determined by examining child content. Checkboxes and radio buttons are examples of
- // controls that need to do this. The adjustment is an offset that adds to the baseline, e.g., marginTop() + height() + |offset|.
- // The offset is not zoomed.
- virtual int baselinePositionAdjustment(ControlPart) const { return 0; }
-
- // A method asking if the control changes its appearance when the window is inactive.
- virtual bool controlHasInactiveAppearance(ControlPart) const { return false; }
-
- // General methods for whether or not any of the controls in the theme change appearance when the window is inactive or
- // when hovered over.
- virtual bool controlsCanHaveInactiveAppearance() const { return false; }
- virtual bool controlsCanHaveHoveredAppearance() const { return false; }
-
- // Used by RenderTheme::isControlStyled to figure out if the native look and feel should be turned off.
- virtual bool controlDrawsBorder(ControlPart) const { return true; }
- virtual bool controlDrawsBackground(ControlPart) const { return true; }
- virtual bool controlDrawsFocusOutline(ControlPart) const { return true; }
-
- // Methods for obtaining platform-specific colors.
- virtual Color selectionColor(ControlPart, ControlState, SelectionPart) const { return Color(); }
- virtual Color textSearchHighlightColor() const { return Color(); }
-
- // CSS system colors and fonts
- virtual Color systemColor(ThemeColor) const { return Color(); }
- virtual Font systemFont(ThemeFont, FontDescription&) const { return Font(); }
-
- // How fast the caret blinks in text fields.
- virtual double caretBlinkInterval() const { return 0.5; }
-
- // Methods used to adjust the RenderStyles of controls.
-
- // The font description result should have a zoomed font size.
- virtual FontDescription controlFont(ControlPart, const Font& font, float /*zoomFactor*/) const { return font.fontDescription(); }
-
- // The size here is in zoomed coordinates already. If a new size is returned, it also needs to be in zoomed coordinates.
- virtual LengthSize controlSize(ControlPart, const Font&, const LengthSize& zoomedSize, float /*zoomFactor*/) const { return zoomedSize; }
-
- // Returns the minimum size for a control in zoomed coordinates.
- virtual LengthSize minimumControlSize(ControlPart, const Font&, float /*zoomFactor*/) const { return LengthSize(Length(0, Fixed), Length(0, Fixed)); }
-
- // Allows the theme to modify the existing padding/border.
- virtual LengthBox controlPadding(ControlPart, const Font&, const LengthBox& zoomedBox, float zoomFactor) const;
- virtual LengthBox controlBorder(ControlPart, const Font&, const LengthBox& zoomedBox, float zoomFactor) const;
-
- // Whether or not whitespace: pre should be forced on always.
- virtual bool controlRequiresPreWhiteSpace(ControlPart) const { return false; }
-
- // Method for painting a control. The rect is in zoomed coordinates.
- virtual void paint(ControlPart, ControlStates, GraphicsContext*, const IntRect& /*zoomedRect*/, float /*zoomFactor*/, ScrollView*) const { }
-
- // Some controls may spill out of their containers (e.g., the check on an OS X checkbox). When these controls repaint,
- // the theme needs to communicate this inflated rect to the engine so that it can invalidate the whole control.
- // The rect passed in is in zoomed coordinates, so the inflation should take that into account and make sure the inflation
- // amount is also scaled by the zoomFactor.
- virtual void inflateControlPaintRect(ControlPart, ControlStates, IntRect& /*zoomedRect*/, float /*zoomFactor*/) const { }
-
-private:
- mutable Color m_activeSelectionColor;
- mutable Color m_inactiveSelectionColor;
-};
-
-// Function to obtain the theme. This is implemented in the platform-specific subclasses.
-Theme* platformTheme();
-
-} // namespace WebCore
-
-#endif // Theme_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/ThemeTypes.h b/chromium/third_party/WebKit/Source/core/platform/ThemeTypes.h
deleted file mode 100644
index 1d58bd4b8b8..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/ThemeTypes.h
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * Copyright (C) 2008, 2009, 2010 Apple Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ThemeTypes_h
-#define ThemeTypes_h
-
-namespace WebCore {
-
-enum ControlState {
- HoverState = 1,
- PressedState = 1 << 1,
- FocusState = 1 << 2,
- EnabledState = 1 << 3,
- CheckedState = 1 << 4,
- ReadOnlyState = 1 << 5,
- WindowInactiveState = 1 << 7,
- IndeterminateState = 1 << 8,
- SpinUpState = 1 << 9, // Sub-state for HoverState and PressedState.
- AllStates = 0xffffffff
-};
-
-typedef unsigned ControlStates;
-
-// Must follow CSSValueKeywords.in order
-enum ControlPart {
- NoControlPart, CheckboxPart, RadioPart, PushButtonPart, SquareButtonPart, ButtonPart,
- ButtonBevelPart, InnerSpinButtonPart, InputSpeechButtonPart, ListboxPart, ListItemPart,
- MediaEnterFullscreenButtonPart, MediaExitFullscreenButtonPart, MediaFullScreenVolumeSliderPart, MediaFullScreenVolumeSliderThumbPart, MediaMuteButtonPart, MediaPlayButtonPart,
- MediaOverlayPlayButtonPart, MediaSeekBackButtonPart, MediaSeekForwardButtonPart, MediaRewindButtonPart, MediaReturnToRealtimeButtonPart, MediaToggleClosedCaptionsButtonPart,
- MediaSliderPart, MediaSliderThumbPart, MediaVolumeSliderContainerPart, MediaVolumeSliderPart, MediaVolumeSliderThumbPart,
- MediaVolumeSliderMuteButtonPart, MediaControlsBackgroundPart, MediaControlsFullscreenBackgroundPart, MediaCurrentTimePart, MediaTimeRemainingPart,
- MenulistPart, MenulistButtonPart, MenulistTextPart, MenulistTextFieldPart, MeterPart, ProgressBarPart, ProgressBarValuePart,
- SliderHorizontalPart, SliderVerticalPart, SliderThumbHorizontalPart,
- SliderThumbVerticalPart, CaretPart, SearchFieldPart, SearchFieldDecorationPart,
- SearchFieldResultsDecorationPart,
- SearchFieldCancelButtonPart, TextFieldPart,
- RelevancyLevelIndicatorPart, ContinuousCapacityLevelIndicatorPart, DiscreteCapacityLevelIndicatorPart, RatingLevelIndicatorPart,
- TextAreaPart, CapsLockIndicatorPart
-};
-
-enum SelectionPart {
- SelectionBackground, SelectionForeground
-};
-
-enum ThemeFont {
- CaptionFont, IconFont, MenuFont, MessageBoxFont, SmallCaptionFont, StatusBarFont, MiniControlFont, SmallControlFont, ControlFont
-};
-
-enum ThemeColor {
- ActiveBorderColor, ActiveCaptionColor, AppWorkspaceColor, BackgroundColor, ButtonFaceColor, ButtonHighlightColor, ButtonShadowColor,
- ButtonTextColor, CaptionTextColor, GrayTextColor, HighlightColor, HighlightTextColor, InactiveBorderColor, InactiveCaptionColor,
- InactiveCaptionTextColor, InfoBackgroundColor, InfoTextColor, MatchColor, MenuTextColor, ScrollbarColor, ThreeDDarkDhasowColor,
- ThreeDFaceColor, ThreeDHighlightColor, ThreeDLightShadowColor, ThreeDShadowCLor, WindowColor, WindowFrameColor, WindowTextColor,
- FocusRingColor, ActiveListBoxSelection, ActiveListBoxSelectionText, InactiveListBoxSelection, InactiveListBoxSelectionText
-};
-
-}
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/ThreadGlobalData.cpp b/chromium/third_party/WebKit/Source/core/platform/ThreadGlobalData.cpp
deleted file mode 100644
index a6f0aac6680..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/ThreadGlobalData.cpp
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Copyright (C) 2008 Apple Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-#include "config.h"
-#include "core/platform/ThreadGlobalData.h"
-
-#include "core/dom/EventNames.h"
-#include "core/inspector/InspectorCounters.h"
-#include "core/platform/ThreadTimers.h"
-#include "wtf/MainThread.h"
-#include "wtf/ThreadSpecific.h"
-#include "wtf/Threading.h"
-#include "wtf/WTFThreadData.h"
-#include "wtf/text/StringImpl.h"
-
-using namespace WTF;
-
-namespace WebCore {
-
-ThreadSpecific<ThreadGlobalData>* ThreadGlobalData::staticData;
-
-ThreadGlobalData::ThreadGlobalData()
- : m_eventNames(adoptPtr(new EventNames))
- , m_threadTimers(adoptPtr(new ThreadTimers))
-#ifndef NDEBUG
- , m_isMainThread(isMainThread())
-#endif
- , m_inspectorCounters(adoptPtr(new ThreadLocalInspectorCounters()))
-{
- // This constructor will have been called on the main thread before being called on
- // any other thread, and is only called once per thread - this makes this a convenient
- // point to call methods that internally perform a one-time initialization that is not
- // threadsafe.
- wtfThreadData();
- StringImpl::empty();
-}
-
-ThreadGlobalData::~ThreadGlobalData()
-{
-}
-
-void ThreadGlobalData::destroy()
-{
- m_inspectorCounters.clear();
- m_eventNames.clear();
- m_threadTimers.clear();
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/ThreadGlobalData.h b/chromium/third_party/WebKit/Source/core/platform/ThreadGlobalData.h
deleted file mode 100644
index cc56f0e6268..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/ThreadGlobalData.h
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
- * Copyright (C) 2008 Apple Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-#ifndef ThreadGlobalData_h
-#define ThreadGlobalData_h
-
-#include "wtf/HashMap.h"
-#include "wtf/HashSet.h"
-#include "wtf/Noncopyable.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/ThreadSpecific.h"
-#include "wtf/Threading.h"
-#include "wtf/text/StringHash.h"
-
-using WTF::ThreadSpecific;
-
-namespace WebCore {
-
- class EventNames;
- class ThreadLocalInspectorCounters;
- class ThreadTimers;
-
- struct TECConverterWrapper;
-
- class ThreadGlobalData {
- WTF_MAKE_NONCOPYABLE(ThreadGlobalData);
- public:
- ThreadGlobalData();
- ~ThreadGlobalData();
- void destroy(); // called on workers to clean up the ThreadGlobalData before the thread exits.
-
- EventNames& eventNames() { return *m_eventNames; }
- ThreadTimers& threadTimers() { return *m_threadTimers; }
-
- ThreadLocalInspectorCounters& inspectorCounters() { return *m_inspectorCounters; }
-
- private:
- OwnPtr<EventNames> m_eventNames;
- OwnPtr<ThreadTimers> m_threadTimers;
-
-#ifndef NDEBUG
- bool m_isMainThread;
-#endif
-
- OwnPtr<ThreadLocalInspectorCounters> m_inspectorCounters;
-
- static ThreadSpecific<ThreadGlobalData>* staticData;
- friend ThreadGlobalData& threadGlobalData();
- };
-
-inline ThreadGlobalData& threadGlobalData()
-{
- // FIXME: Workers are not necessarily the only feature that make per-thread global data necessary.
- // We need to check for e.g. database objects manipulating strings on secondary threads.
-
- // ThreadGlobalData is used on main thread before it could possibly be used on secondary ones, so there is no need for synchronization here.
- if (!ThreadGlobalData::staticData)
- ThreadGlobalData::staticData = new ThreadSpecific<ThreadGlobalData>;
- return **ThreadGlobalData::staticData;
-}
-
-} // namespace WebCore
-
-#endif // ThreadGlobalData_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/ThreadTimers.cpp b/chromium/third_party/WebKit/Source/core/platform/ThreadTimers.cpp
deleted file mode 100644
index 884f6444e2f..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/ThreadTimers.cpp
+++ /dev/null
@@ -1,154 +0,0 @@
-/*
- * Copyright (C) 2006, 2008 Apple Inc. All rights reserved.
- * Copyright (C) 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/ThreadTimers.h"
-
-#include "core/platform/SharedTimer.h"
-#include "core/platform/ThreadGlobalData.h"
-#include "core/platform/Timer.h"
-#include "core/platform/chromium/TraceEvent.h"
-#include "wtf/CurrentTime.h"
-#include "wtf/MainThread.h"
-
-using namespace std;
-
-namespace WebCore {
-
-// Fire timers for this length of time, and then quit to let the run loop process user input events.
-// 100ms is about a perceptable delay in UI, so use a half of that as a threshold.
-// This is to prevent UI freeze when there are too many timers or machine performance is low.
-static const double maxDurationOfFiringTimers = 0.050;
-
-// Timers are created, started and fired on the same thread, and each thread has its own ThreadTimers
-// copy to keep the heap and a set of currently firing timers.
-
-static MainThreadSharedTimer* mainThreadSharedTimer()
-{
- static MainThreadSharedTimer* timer = new MainThreadSharedTimer;
- return timer;
-}
-
-ThreadTimers::ThreadTimers()
- : m_sharedTimer(0)
- , m_firingTimers(false)
- , m_pendingSharedTimerFireTime(0)
-{
- if (isMainThread())
- setSharedTimer(mainThreadSharedTimer());
-}
-
-// A worker thread may initialize SharedTimer after some timers are created.
-// Also, SharedTimer can be replaced with 0 before all timers are destroyed.
-void ThreadTimers::setSharedTimer(SharedTimer* sharedTimer)
-{
- if (m_sharedTimer) {
- m_sharedTimer->setFiredFunction(0);
- m_sharedTimer->stop();
- m_pendingSharedTimerFireTime = 0;
- }
-
- m_sharedTimer = sharedTimer;
-
- if (sharedTimer) {
- m_sharedTimer->setFiredFunction(ThreadTimers::sharedTimerFired);
- updateSharedTimer();
- }
-}
-
-void ThreadTimers::updateSharedTimer()
-{
- if (!m_sharedTimer)
- return;
-
- if (m_firingTimers || m_timerHeap.isEmpty()) {
- m_pendingSharedTimerFireTime = 0;
- m_sharedTimer->stop();
- } else {
- double nextFireTime = m_timerHeap.first()->m_nextFireTime;
- double currentMonotonicTime = monotonicallyIncreasingTime();
- if (m_pendingSharedTimerFireTime) {
- // No need to restart the timer if both the pending fire time and the new fire time are in the past.
- if (m_pendingSharedTimerFireTime <= currentMonotonicTime && nextFireTime <= currentMonotonicTime)
- return;
- }
- m_pendingSharedTimerFireTime = nextFireTime;
- m_sharedTimer->setFireInterval(max(nextFireTime - currentMonotonicTime, 0.0));
- }
-}
-
-void ThreadTimers::sharedTimerFired()
-{
- TRACE_EVENT_SET_SAMPLING_STATE("Blink", "Internal");
-
- // Redirect to non-static method.
- threadGlobalData().threadTimers().sharedTimerFiredInternal();
-
- TRACE_EVENT_SET_SAMPLING_STATE("Blink", "Sleeping");
-}
-
-void ThreadTimers::sharedTimerFiredInternal()
-{
- // Do a re-entrancy check.
- if (m_firingTimers)
- return;
- m_firingTimers = true;
- m_pendingSharedTimerFireTime = 0;
-
- double fireTime = monotonicallyIncreasingTime();
- double timeToQuit = fireTime + maxDurationOfFiringTimers;
-
- while (!m_timerHeap.isEmpty() && m_timerHeap.first()->m_nextFireTime <= fireTime) {
- TimerBase* timer = m_timerHeap.first();
- timer->m_nextFireTime = 0;
- timer->m_unalignedNextFireTime = 0;
- timer->heapDeleteMin();
-
- double interval = timer->repeatInterval();
- timer->setNextFireTime(interval ? fireTime + interval : 0);
-
- // Once the timer has been fired, it may be deleted, so do nothing else with it after this point.
- timer->fired();
-
- // Catch the case where the timer asked timers to fire in a nested event loop, or we are over time limit.
- if (!m_firingTimers || timeToQuit < monotonicallyIncreasingTime())
- break;
- }
-
- m_firingTimers = false;
-
- updateSharedTimer();
-}
-
-void ThreadTimers::fireTimersInNestedEventLoop()
-{
- // Reset the reentrancy guard so the timers can fire again.
- m_firingTimers = false;
- updateSharedTimer();
-}
-
-} // namespace WebCore
-
diff --git a/chromium/third_party/WebKit/Source/core/platform/ThreadTimers.h b/chromium/third_party/WebKit/Source/core/platform/ThreadTimers.h
deleted file mode 100644
index 2201a5a13c0..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/ThreadTimers.h
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Copyright (C) 2006 Apple Computer, Inc. All rights reserved.
- * Copyright (C) 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ThreadTimers_h
-#define ThreadTimers_h
-
-#include "wtf/Noncopyable.h"
-#include "wtf/HashSet.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
- class SharedTimer;
- class TimerBase;
-
- // A collection of timers per thread. Kept in ThreadGlobalData.
- class ThreadTimers {
- WTF_MAKE_NONCOPYABLE(ThreadTimers); WTF_MAKE_FAST_ALLOCATED;
- public:
- ThreadTimers();
-
- // On a thread different then main, we should set the thread's instance of the SharedTimer.
- void setSharedTimer(SharedTimer*);
-
- Vector<TimerBase*>& timerHeap() { return m_timerHeap; }
-
- void updateSharedTimer();
- void fireTimersInNestedEventLoop();
-
- private:
- static void sharedTimerFired();
-
- void sharedTimerFiredInternal();
- void fireTimersInNestedEventLoopInternal();
-
- Vector<TimerBase*> m_timerHeap;
- SharedTimer* m_sharedTimer; // External object, can be a run loop on a worker thread. Normally set/reset by worker thread.
- bool m_firingTimers; // Reentrancy guard.
- double m_pendingSharedTimerFireTime;
- };
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/Timer.cpp b/chromium/third_party/WebKit/Source/core/platform/Timer.cpp
deleted file mode 100644
index 783e6d3de0a..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/Timer.cpp
+++ /dev/null
@@ -1,416 +0,0 @@
-/*
- * Copyright (C) 2006, 2008 Apple Inc. All rights reserved.
- * Copyright (C) 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/Timer.h"
-
-#include <limits.h>
-#include <math.h>
-#include <limits>
-#include "core/platform/ThreadGlobalData.h"
-#include "core/platform/ThreadTimers.h"
-#include "wtf/CurrentTime.h"
-#include "wtf/HashSet.h"
-#include "wtf/Vector.h"
-
-using namespace std;
-
-namespace WebCore {
-
-class TimerHeapReference;
-
-// Timers are stored in a heap data structure, used to implement a priority queue.
-// This allows us to efficiently determine which timer needs to fire the soonest.
-// Then we set a single shared system timer to fire at that time.
-//
-// When a timer's "next fire time" changes, we need to move it around in the priority queue.
-static Vector<TimerBase*>& threadGlobalTimerHeap()
-{
- return threadGlobalData().threadTimers().timerHeap();
-}
-// ----------------
-
-class TimerHeapPointer {
-public:
- TimerHeapPointer(TimerBase** pointer) : m_pointer(pointer) { }
- TimerHeapReference operator*() const;
- TimerBase* operator->() const { return *m_pointer; }
-private:
- TimerBase** m_pointer;
-};
-
-class TimerHeapReference {
-public:
- TimerHeapReference(TimerBase*& reference) : m_reference(reference) { }
- operator TimerBase*() const { return m_reference; }
- TimerHeapPointer operator&() const { return &m_reference; }
- TimerHeapReference& operator=(TimerBase*);
- TimerHeapReference& operator=(TimerHeapReference);
-private:
- TimerBase*& m_reference;
-};
-
-inline TimerHeapReference TimerHeapPointer::operator*() const
-{
- return *m_pointer;
-}
-
-inline TimerHeapReference& TimerHeapReference::operator=(TimerBase* timer)
-{
- m_reference = timer;
- Vector<TimerBase*>& heap = timer->timerHeap();
- if (&m_reference >= heap.data() && &m_reference < heap.data() + heap.size())
- timer->m_heapIndex = &m_reference - heap.data();
- return *this;
-}
-
-inline TimerHeapReference& TimerHeapReference::operator=(TimerHeapReference b)
-{
- TimerBase* timer = b;
- return *this = timer;
-}
-
-inline void swap(TimerHeapReference a, TimerHeapReference b)
-{
- TimerBase* timerA = a;
- TimerBase* timerB = b;
-
- // Invoke the assignment operator, since that takes care of updating m_heapIndex.
- a = timerB;
- b = timerA;
-}
-
-// ----------------
-
-// Class to represent iterators in the heap when calling the standard library heap algorithms.
-// Uses a custom pointer and reference type that update indices for pointers in the heap.
-class TimerHeapIterator : public iterator<random_access_iterator_tag, TimerBase*, ptrdiff_t, TimerHeapPointer, TimerHeapReference> {
-public:
- explicit TimerHeapIterator(TimerBase** pointer) : m_pointer(pointer) { checkConsistency(); }
-
- TimerHeapIterator& operator++() { checkConsistency(); ++m_pointer; checkConsistency(); return *this; }
- TimerHeapIterator operator++(int) { checkConsistency(1); return TimerHeapIterator(m_pointer++); }
-
- TimerHeapIterator& operator--() { checkConsistency(); --m_pointer; checkConsistency(); return *this; }
- TimerHeapIterator operator--(int) { checkConsistency(-1); return TimerHeapIterator(m_pointer--); }
-
- TimerHeapIterator& operator+=(ptrdiff_t i) { checkConsistency(); m_pointer += i; checkConsistency(); return *this; }
- TimerHeapIterator& operator-=(ptrdiff_t i) { checkConsistency(); m_pointer -= i; checkConsistency(); return *this; }
-
- TimerHeapReference operator*() const { return TimerHeapReference(*m_pointer); }
- TimerHeapReference operator[](ptrdiff_t i) const { return TimerHeapReference(m_pointer[i]); }
- TimerBase* operator->() const { return *m_pointer; }
-
-private:
- void checkConsistency(ptrdiff_t offset = 0) const
- {
- ASSERT(m_pointer >= threadGlobalTimerHeap().data());
- ASSERT(m_pointer <= threadGlobalTimerHeap().data() + threadGlobalTimerHeap().size());
- ASSERT_UNUSED(offset, m_pointer + offset >= threadGlobalTimerHeap().data());
- ASSERT_UNUSED(offset, m_pointer + offset <= threadGlobalTimerHeap().data() + threadGlobalTimerHeap().size());
- }
-
- friend bool operator==(TimerHeapIterator, TimerHeapIterator);
- friend bool operator!=(TimerHeapIterator, TimerHeapIterator);
- friend bool operator<(TimerHeapIterator, TimerHeapIterator);
- friend bool operator>(TimerHeapIterator, TimerHeapIterator);
- friend bool operator<=(TimerHeapIterator, TimerHeapIterator);
- friend bool operator>=(TimerHeapIterator, TimerHeapIterator);
-
- friend TimerHeapIterator operator+(TimerHeapIterator, size_t);
- friend TimerHeapIterator operator+(size_t, TimerHeapIterator);
-
- friend TimerHeapIterator operator-(TimerHeapIterator, size_t);
- friend ptrdiff_t operator-(TimerHeapIterator, TimerHeapIterator);
-
- TimerBase** m_pointer;
-};
-
-inline bool operator==(TimerHeapIterator a, TimerHeapIterator b) { return a.m_pointer == b.m_pointer; }
-inline bool operator!=(TimerHeapIterator a, TimerHeapIterator b) { return a.m_pointer != b.m_pointer; }
-inline bool operator<(TimerHeapIterator a, TimerHeapIterator b) { return a.m_pointer < b.m_pointer; }
-inline bool operator>(TimerHeapIterator a, TimerHeapIterator b) { return a.m_pointer > b.m_pointer; }
-inline bool operator<=(TimerHeapIterator a, TimerHeapIterator b) { return a.m_pointer <= b.m_pointer; }
-inline bool operator>=(TimerHeapIterator a, TimerHeapIterator b) { return a.m_pointer >= b.m_pointer; }
-
-inline TimerHeapIterator operator+(TimerHeapIterator a, size_t b) { return TimerHeapIterator(a.m_pointer + b); }
-inline TimerHeapIterator operator+(size_t a, TimerHeapIterator b) { return TimerHeapIterator(a + b.m_pointer); }
-
-inline TimerHeapIterator operator-(TimerHeapIterator a, size_t b) { return TimerHeapIterator(a.m_pointer - b); }
-inline ptrdiff_t operator-(TimerHeapIterator a, TimerHeapIterator b) { return a.m_pointer - b.m_pointer; }
-
-// ----------------
-
-class TimerHeapLessThanFunction {
-public:
- bool operator()(const TimerBase*, const TimerBase*) const;
-};
-
-inline bool TimerHeapLessThanFunction::operator()(const TimerBase* a, const TimerBase* b) const
-{
- // The comparisons below are "backwards" because the heap puts the largest
- // element first and we want the lowest time to be the first one in the heap.
- double aFireTime = a->m_nextFireTime;
- double bFireTime = b->m_nextFireTime;
- if (bFireTime != aFireTime)
- return bFireTime < aFireTime;
-
- // We need to look at the difference of the insertion orders instead of comparing the two
- // outright in case of overflow.
- unsigned difference = a->m_heapInsertionOrder - b->m_heapInsertionOrder;
- return difference < numeric_limits<unsigned>::max() / 2;
-}
-
-// ----------------
-
-TimerBase::TimerBase()
- : m_nextFireTime(0)
- , m_unalignedNextFireTime(0)
- , m_repeatInterval(0)
- , m_heapIndex(-1)
- , m_cachedThreadGlobalTimerHeap(0)
-#ifndef NDEBUG
- , m_thread(currentThread())
-#endif
-{
-}
-
-TimerBase::~TimerBase()
-{
- stop();
- ASSERT(!inHeap());
-}
-
-void TimerBase::start(double nextFireInterval, double repeatInterval)
-{
- ASSERT(m_thread == currentThread());
-
- m_repeatInterval = repeatInterval;
- setNextFireTime(monotonicallyIncreasingTime() + nextFireInterval);
-}
-
-void TimerBase::stop()
-{
- ASSERT(m_thread == currentThread());
-
- m_repeatInterval = 0;
- setNextFireTime(0);
-
- ASSERT(m_nextFireTime == 0);
- ASSERT(m_repeatInterval == 0);
- ASSERT(!inHeap());
-}
-
-double TimerBase::nextFireInterval() const
-{
- ASSERT(isActive());
- double current = monotonicallyIncreasingTime();
- if (m_nextFireTime < current)
- return 0;
- return m_nextFireTime - current;
-}
-
-inline void TimerBase::checkHeapIndex() const
-{
- ASSERT(timerHeap() == threadGlobalTimerHeap());
- ASSERT(!timerHeap().isEmpty());
- ASSERT(m_heapIndex >= 0);
- ASSERT(m_heapIndex < static_cast<int>(timerHeap().size()));
- ASSERT(timerHeap()[m_heapIndex] == this);
-}
-
-inline void TimerBase::checkConsistency() const
-{
- // Timers should be in the heap if and only if they have a non-zero next fire time.
- ASSERT(inHeap() == (m_nextFireTime != 0));
- if (inHeap())
- checkHeapIndex();
-}
-
-void TimerBase::heapDecreaseKey()
-{
- ASSERT(m_nextFireTime != 0);
- checkHeapIndex();
- TimerBase** heapData = timerHeap().data();
- push_heap(TimerHeapIterator(heapData), TimerHeapIterator(heapData + m_heapIndex + 1), TimerHeapLessThanFunction());
- checkHeapIndex();
-}
-
-inline void TimerBase::heapDelete()
-{
- ASSERT(m_nextFireTime == 0);
- heapPop();
- timerHeap().removeLast();
- m_heapIndex = -1;
-}
-
-void TimerBase::heapDeleteMin()
-{
- ASSERT(m_nextFireTime == 0);
- heapPopMin();
- timerHeap().removeLast();
- m_heapIndex = -1;
-}
-
-inline void TimerBase::heapIncreaseKey()
-{
- ASSERT(m_nextFireTime != 0);
- heapPop();
- heapDecreaseKey();
-}
-
-inline void TimerBase::heapInsert()
-{
- ASSERT(!inHeap());
- timerHeap().append(this);
- m_heapIndex = timerHeap().size() - 1;
- heapDecreaseKey();
-}
-
-inline void TimerBase::heapPop()
-{
- // Temporarily force this timer to have the minimum key so we can pop it.
- double fireTime = m_nextFireTime;
- m_nextFireTime = -numeric_limits<double>::infinity();
- heapDecreaseKey();
- heapPopMin();
- m_nextFireTime = fireTime;
-}
-
-void TimerBase::heapPopMin()
-{
- ASSERT(this == timerHeap().first());
- checkHeapIndex();
- Vector<TimerBase*>& heap = timerHeap();
- TimerBase** heapData = heap.data();
- pop_heap(TimerHeapIterator(heapData), TimerHeapIterator(heapData + heap.size()), TimerHeapLessThanFunction());
- checkHeapIndex();
- ASSERT(this == timerHeap().last());
-}
-
-static inline bool parentHeapPropertyHolds(const TimerBase* current, const Vector<TimerBase*>& heap, unsigned currentIndex)
-{
- if (!currentIndex)
- return true;
- unsigned parentIndex = (currentIndex - 1) / 2;
- TimerHeapLessThanFunction compareHeapPosition;
- return compareHeapPosition(current, heap[parentIndex]);
-}
-
-static inline bool childHeapPropertyHolds(const TimerBase* current, const Vector<TimerBase*>& heap, unsigned childIndex)
-{
- if (childIndex >= heap.size())
- return true;
- TimerHeapLessThanFunction compareHeapPosition;
- return compareHeapPosition(heap[childIndex], current);
-}
-
-bool TimerBase::hasValidHeapPosition() const
-{
- ASSERT(m_nextFireTime);
- if (!inHeap())
- return false;
- // Check if the heap property still holds with the new fire time. If it does we don't need to do anything.
- // This assumes that the STL heap is a standard binary heap. In an unlikely event it is not, the assertions
- // in updateHeapIfNeeded() will get hit.
- const Vector<TimerBase*>& heap = timerHeap();
- if (!parentHeapPropertyHolds(this, heap, m_heapIndex))
- return false;
- unsigned childIndex1 = 2 * m_heapIndex + 1;
- unsigned childIndex2 = childIndex1 + 1;
- return childHeapPropertyHolds(this, heap, childIndex1) && childHeapPropertyHolds(this, heap, childIndex2);
-}
-
-void TimerBase::updateHeapIfNeeded(double oldTime)
-{
- if (m_nextFireTime && hasValidHeapPosition())
- return;
-#ifndef NDEBUG
- int oldHeapIndex = m_heapIndex;
-#endif
- if (!oldTime)
- heapInsert();
- else if (!m_nextFireTime)
- heapDelete();
- else if (m_nextFireTime < oldTime)
- heapDecreaseKey();
- else
- heapIncreaseKey();
- ASSERT(m_heapIndex != oldHeapIndex);
- ASSERT(!inHeap() || hasValidHeapPosition());
-}
-
-void TimerBase::setNextFireTime(double newUnalignedTime)
-{
- ASSERT(m_thread == currentThread());
-
- if (m_unalignedNextFireTime != newUnalignedTime)
- m_unalignedNextFireTime = newUnalignedTime;
-
- // Accessing thread global data is slow. Cache the heap pointer.
- if (!m_cachedThreadGlobalTimerHeap)
- m_cachedThreadGlobalTimerHeap = &threadGlobalTimerHeap();
-
- // Keep heap valid while changing the next-fire time.
- double oldTime = m_nextFireTime;
- double newTime = alignedFireTime(newUnalignedTime);
- if (oldTime != newTime) {
- m_nextFireTime = newTime;
- static unsigned currentHeapInsertionOrder;
- m_heapInsertionOrder = currentHeapInsertionOrder++;
-
- bool wasFirstTimerInHeap = m_heapIndex == 0;
-
- updateHeapIfNeeded(oldTime);
-
- bool isFirstTimerInHeap = m_heapIndex == 0;
-
- if (wasFirstTimerInHeap || isFirstTimerInHeap)
- threadGlobalData().threadTimers().updateSharedTimer();
- }
-
- checkConsistency();
-}
-
-void TimerBase::fireTimersInNestedEventLoop()
-{
- // Redirect to ThreadTimers.
- threadGlobalData().threadTimers().fireTimersInNestedEventLoop();
-}
-
-void TimerBase::didChangeAlignmentInterval()
-{
- setNextFireTime(m_unalignedNextFireTime);
-}
-
-double TimerBase::nextUnalignedFireInterval() const
-{
- ASSERT(isActive());
- return max(m_unalignedNextFireTime - monotonicallyIncreasingTime(), 0.0);
-}
-
-} // namespace WebCore
-
diff --git a/chromium/third_party/WebKit/Source/core/platform/Timer.h b/chromium/third_party/WebKit/Source/core/platform/Timer.h
deleted file mode 100644
index 7a1c408aff6..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/Timer.h
+++ /dev/null
@@ -1,175 +0,0 @@
-/*
- * Copyright (C) 2006 Apple Computer, Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef Timer_h
-#define Timer_h
-
-#include "wtf/Noncopyable.h"
-#include "wtf/Threading.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-// Time intervals are all in seconds.
-
-class TimerHeapElement;
-
-class TimerBase {
- WTF_MAKE_NONCOPYABLE(TimerBase); WTF_MAKE_FAST_ALLOCATED;
-public:
- TimerBase();
- virtual ~TimerBase();
-
- void start(double nextFireInterval, double repeatInterval);
-
- void startRepeating(double repeatInterval) { start(repeatInterval, repeatInterval); }
- void startOneShot(double interval) { start(interval, 0); }
-
- void stop();
- bool isActive() const;
-
- double nextFireInterval() const;
- double nextUnalignedFireInterval() const;
- double repeatInterval() const { return m_repeatInterval; }
-
- void augmentRepeatInterval(double delta) {
- setNextFireTime(m_nextFireTime + delta);
- m_repeatInterval += delta;
- }
-
- void didChangeAlignmentInterval();
-
- static void fireTimersInNestedEventLoop();
-
-private:
- virtual void fired() = 0;
-
- virtual double alignedFireTime(double fireTime) const { return fireTime; }
-
- void checkConsistency() const;
- void checkHeapIndex() const;
-
- void setNextFireTime(double);
-
- bool inHeap() const { return m_heapIndex != -1; }
-
- bool hasValidHeapPosition() const;
- void updateHeapIfNeeded(double oldTime);
-
- void heapDecreaseKey();
- void heapDelete();
- void heapDeleteMin();
- void heapIncreaseKey();
- void heapInsert();
- void heapPop();
- void heapPopMin();
-
- Vector<TimerBase*>& timerHeap() const { ASSERT(m_cachedThreadGlobalTimerHeap); return *m_cachedThreadGlobalTimerHeap; }
-
- double m_nextFireTime; // 0 if inactive
- double m_unalignedNextFireTime; // m_nextFireTime not considering alignment interval
- double m_repeatInterval; // 0 if not repeating
- int m_heapIndex; // -1 if not in heap
- unsigned m_heapInsertionOrder; // Used to keep order among equal-fire-time timers
- Vector<TimerBase*>* m_cachedThreadGlobalTimerHeap;
-
-#ifndef NDEBUG
- ThreadIdentifier m_thread;
-#endif
-
- friend class ThreadTimers;
- friend class TimerHeapLessThanFunction;
- friend class TimerHeapReference;
-};
-
-template <typename TimerFiredClass> class Timer : public TimerBase {
-public:
- typedef void (TimerFiredClass::*TimerFiredFunction)(Timer*);
-
- Timer(TimerFiredClass* o, TimerFiredFunction f)
- : m_object(o), m_function(f) { }
-
-private:
- virtual void fired() { (m_object->*m_function)(this); }
-
- TimerFiredClass* m_object;
- TimerFiredFunction m_function;
-};
-
-inline bool TimerBase::isActive() const
-{
- ASSERT(m_thread == currentThread());
- return m_nextFireTime;
-}
-
-template <typename TimerFiredClass> class DeferrableOneShotTimer : private TimerBase {
-public:
- typedef void (TimerFiredClass::*TimerFiredFunction)(DeferrableOneShotTimer*);
-
- DeferrableOneShotTimer(TimerFiredClass* o, TimerFiredFunction f, double delay)
- : m_object(o)
- , m_function(f)
- , m_delay(delay)
- , m_shouldRestartWhenTimerFires(false)
- {
- }
-
- void restart()
- {
- // Setting this boolean is much more efficient than calling startOneShot
- // again, which might result in rescheduling the system timer which
- // can be quite expensive.
-
- if (isActive()) {
- m_shouldRestartWhenTimerFires = true;
- return;
- }
- startOneShot(m_delay);
- }
-
- using TimerBase::stop;
- using TimerBase::isActive;
-private:
- virtual void fired()
- {
- if (m_shouldRestartWhenTimerFires) {
- m_shouldRestartWhenTimerFires = false;
- startOneShot(m_delay);
- return;
- }
-
- (m_object->*m_function)(this);
- }
-
- TimerFiredClass* m_object;
- TimerFiredFunction m_function;
-
- double m_delay;
- bool m_shouldRestartWhenTimerFires;
-};
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/TreeShared.h b/chromium/third_party/WebKit/Source/core/platform/TreeShared.h
deleted file mode 100644
index 9c1b8d9a89a..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/TreeShared.h
+++ /dev/null
@@ -1,123 +0,0 @@
-/*
- * Copyright (C) 2006, 2007, 2009, 2010, 2012 Apple Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#ifndef TreeShared_h
-#define TreeShared_h
-
-#include "wtf/Assertions.h"
-#include "wtf/MainThread.h"
-#include "wtf/Noncopyable.h"
-
-namespace WebCore {
-
-#ifndef NDEBUG
-template<typename NodeType> class TreeShared;
-template<typename NodeType> void adopted(TreeShared<NodeType>*);
-#endif
-
-template<typename NodeType> class TreeShared {
- WTF_MAKE_NONCOPYABLE(TreeShared);
-protected:
- TreeShared()
- : m_refCount(1)
-#ifndef NDEBUG
- , m_deletionHasBegun(false)
- , m_inRemovedLastRefFunction(false)
- , m_adoptionIsRequired(true)
-#endif
- {
- ASSERT(isMainThread());
- }
-
- ~TreeShared()
- {
- ASSERT(isMainThread());
- ASSERT(!m_refCount);
- ASSERT(m_deletionHasBegun);
- ASSERT(!m_adoptionIsRequired);
- }
-
-public:
- void ref()
- {
- ASSERT(isMainThread());
- ASSERT(!m_deletionHasBegun);
- ASSERT(!m_inRemovedLastRefFunction);
- ASSERT(!m_adoptionIsRequired);
- ++m_refCount;
- }
-
- void deref()
- {
- ASSERT(isMainThread());
- ASSERT(m_refCount >= 0);
- ASSERT(!m_deletionHasBegun);
- ASSERT(!m_inRemovedLastRefFunction);
- ASSERT(!m_adoptionIsRequired);
- NodeType* thisNode = static_cast<NodeType*>(this);
- if (--m_refCount <= 0 && !thisNode->hasTreeSharedParent()) {
-#ifndef NDEBUG
- m_inRemovedLastRefFunction = true;
-#endif
- thisNode->removedLastRef();
- }
- }
-
- bool hasOneRef() const
- {
- ASSERT(!m_deletionHasBegun);
- ASSERT(!m_inRemovedLastRefFunction);
- return m_refCount == 1;
- }
-
- int refCount() const
- {
- return m_refCount;
- }
-
-private:
- int m_refCount;
-
-#ifndef NDEBUG
-public:
- bool m_deletionHasBegun;
- bool m_inRemovedLastRefFunction;
-private:
- friend void adopted<>(TreeShared<NodeType>*);
- bool m_adoptionIsRequired;
-#endif
-};
-
-#ifndef NDEBUG
-
-template<typename NodeType> inline void adopted(TreeShared<NodeType>* object)
-{
- if (!object)
- return;
- ASSERT(!object->m_deletionHasBegun);
- ASSERT(!object->m_inRemovedLastRefFunction);
- object->m_adoptionIsRequired = false;
-}
-
-#endif
-
-}
-
-#endif // TreeShared.h
diff --git a/chromium/third_party/WebKit/Source/core/platform/UUID.cpp b/chromium/third_party/WebKit/Source/core/platform/UUID.cpp
deleted file mode 100644
index 8e453f5a07b..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/UUID.cpp
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
-* Copyright (C) 2010 Google Inc. All rights reserved.
-*
-* Redistribution and use in source and binary forms, with or without
-* modification, are permitted provided that the following conditions are
-* met:
-*
-* * Redistributions of source code must retain the above copyright
-* notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/UUID.h"
-
-#include "wtf/CryptographicallyRandomNumber.h"
-#include "wtf/HexNumber.h"
-#include "wtf/text/StringBuilder.h"
-
-namespace WebCore {
-
-String createCanonicalUUIDString()
-{
- unsigned randomData[4];
- cryptographicallyRandomValues(reinterpret_cast<unsigned char*>(randomData), sizeof(randomData));
-
- // Format as Version 4 UUID.
- StringBuilder builder;
- builder.reserveCapacity(36);
- appendUnsignedAsHexFixedSize(randomData[0], builder, 8, Lowercase);
- builder.append("-");
- appendUnsignedAsHexFixedSize(randomData[1] >> 16, builder, 4, Lowercase);
- builder.append("-4");
- appendUnsignedAsHexFixedSize(randomData[1] & 0x00000fff, builder, 3, Lowercase);
- builder.append("-");
- appendUnsignedAsHexFixedSize((randomData[2] >> 30) | 0x8, builder, 1, Lowercase);
- appendUnsignedAsHexFixedSize((randomData[2] >> 16) & 0x00000fff, builder, 3, Lowercase);
- builder.append("-");
- appendUnsignedAsHexFixedSize(randomData[2] & 0x0000ffff, builder, 4, Lowercase);
- appendUnsignedAsHexFixedSize(randomData[3], builder, 8, Lowercase);
- return builder.toString();
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/UUID.h b/chromium/third_party/WebKit/Source/core/platform/UUID.h
deleted file mode 100644
index 99ab7812a5b..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/UUID.h
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
-* Copyright (C) 2010 Google Inc. All rights reserved.
-*
-* Redistribution and use in source and binary forms, with or without
-* modification, are permitted provided that the following conditions are
-* met:
-*
-* * Redistributions of source code must retain the above copyright
-* notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef UUID_h
-#define UUID_h
-
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-// Creates a UUID that consists of 32 hexadecimal digits and returns its canonical form.
-// The canonical form is displayed in 5 groups separated by hyphens, in the form 8-4-4-4-12 for a total of 36 characters.
-// The hexadecimal values "a" through "f" are output as lower case characters.
-//
-// Note: for security reason, we should always generate version 4 UUID that use a scheme relying only on random numbers.
-// This algorithm sets the version number as well as two reserved bits. All other bits are set using a random or pseudorandom
-// data source. Version 4 UUIDs have the form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx with hexadecimal digits for x and one of 8,
-// 9, A, or B for y.
-//
-// On Windows, version 4 UUIDs are used since Windows 2000 (http://msdn.microsoft.com/en-us/library/aa446557.aspx).
-// On MacOSX, version 4 UUIDs are used since Tiger (http://developer.apple.com/mac/library/technotes/tn/tn1103.html#TNTAG8).
-// On Linux, the kernel offers the procfs pseudo-file /proc/sys/kernel/random/uuid that yields version 4 UUIDs (http://hbfs.wordpress.com/2008/09/30/ueid-unique-enough-ids/).
-String createCanonicalUUIDString();
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/Widget.cpp b/chromium/third_party/WebKit/Source/core/platform/Widget.cpp
deleted file mode 100644
index 8b26cb6a5ce..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/Widget.cpp
+++ /dev/null
@@ -1,191 +0,0 @@
-/*
- * Copyright (C) 2004, 2005, 2006, 2010 Apple Inc. All rights reserved.
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/Widget.h"
-
-#include "core/platform/HostWindow.h"
-#include "core/platform/ScrollView.h"
-#include "core/platform/graphics/IntRect.h"
-
-#include "wtf/Assertions.h"
-
-namespace WebCore {
-
-Widget::Widget()
- : m_parent(0)
- , m_selfVisible(false)
- , m_parentVisible(false)
-{
-}
-
-Widget::~Widget()
-{
- ASSERT(!parent());
-}
-
-void Widget::setCursor(const Cursor& cursor)
-{
- if (ScrollView* view = root())
- view->hostWindow()->setCursor(cursor);
-}
-
-void Widget::removeFromParent()
-{
- if (parent())
- parent()->removeChild(this);
-}
-
-void Widget::setParent(ScrollView* view)
-{
- ASSERT(!view || !m_parent);
- if (!view || !view->isVisible())
- setParentVisible(false);
- m_parent = view;
- if (view && view->isVisible())
- setParentVisible(true);
-}
-
-ScrollView* Widget::root() const
-{
- const Widget* top = this;
- while (top->parent())
- top = top->parent();
- if (top->isFrameView())
- return const_cast<ScrollView*>(static_cast<const ScrollView*>(top));
- return 0;
-}
-
-IntRect Widget::convertFromRootView(const IntRect& rootRect) const
-{
- if (const ScrollView* parentScrollView = parent()) {
- IntRect parentRect = parentScrollView->convertFromRootView(rootRect);
- return convertFromContainingView(parentRect);
- }
- return rootRect;
-}
-
-IntRect Widget::convertToRootView(const IntRect& localRect) const
-{
- if (const ScrollView* parentScrollView = parent()) {
- IntRect parentRect = convertToContainingView(localRect);
- return parentScrollView->convertToRootView(parentRect);
- }
- return localRect;
-}
-
-IntPoint Widget::convertFromRootView(const IntPoint& rootPoint) const
-{
- if (const ScrollView* parentScrollView = parent()) {
- IntPoint parentPoint = parentScrollView->convertFromRootView(rootPoint);
- return convertFromContainingView(parentPoint);
- }
- return rootPoint;
-}
-
-IntPoint Widget::convertToRootView(const IntPoint& localPoint) const
-{
- if (const ScrollView* parentScrollView = parent()) {
- IntPoint parentPoint = convertToContainingView(localPoint);
- return parentScrollView->convertToRootView(parentPoint);
- }
- return localPoint;
-}
-
-IntRect Widget::convertFromContainingWindow(const IntRect& windowRect) const
-{
- if (const ScrollView* parentScrollView = parent()) {
- IntRect parentRect = parentScrollView->convertFromContainingWindow(windowRect);
- return convertFromContainingView(parentRect);
- }
- return windowRect;
-}
-
-IntRect Widget::convertToContainingWindow(const IntRect& localRect) const
-{
- if (const ScrollView* parentScrollView = parent()) {
- IntRect parentRect = convertToContainingView(localRect);
- return parentScrollView->convertToContainingWindow(parentRect);
- }
- return localRect;
-}
-
-IntPoint Widget::convertFromContainingWindow(const IntPoint& windowPoint) const
-{
- if (const ScrollView* parentScrollView = parent()) {
- IntPoint parentPoint = parentScrollView->convertFromContainingWindow(windowPoint);
- return convertFromContainingView(parentPoint);
- }
- return windowPoint;
-}
-
-IntPoint Widget::convertToContainingWindow(const IntPoint& localPoint) const
-{
- if (const ScrollView* parentScrollView = parent()) {
- IntPoint parentPoint = convertToContainingView(localPoint);
- return parentScrollView->convertToContainingWindow(parentPoint);
- }
- return localPoint;
-}
-
-IntRect Widget::convertToContainingView(const IntRect& localRect) const
-{
- if (const ScrollView* parentScrollView = parent()) {
- IntRect parentRect(localRect);
- parentRect.setLocation(parentScrollView->convertChildToSelf(this, localRect.location()));
- return parentRect;
- }
- return localRect;
-}
-
-IntRect Widget::convertFromContainingView(const IntRect& parentRect) const
-{
- if (const ScrollView* parentScrollView = parent()) {
- IntRect localRect = parentRect;
- localRect.setLocation(parentScrollView->convertSelfToChild(this, localRect.location()));
- return localRect;
- }
-
- return parentRect;
-}
-
-IntPoint Widget::convertToContainingView(const IntPoint& localPoint) const
-{
- if (const ScrollView* parentScrollView = parent())
- return parentScrollView->convertChildToSelf(this, localPoint);
-
- return localPoint;
-}
-
-IntPoint Widget::convertFromContainingView(const IntPoint& parentPoint) const
-{
- if (const ScrollView* parentScrollView = parent())
- return parentScrollView->convertSelfToChild(this, parentPoint);
-
- return parentPoint;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/Widget.h b/chromium/third_party/WebKit/Source/core/platform/Widget.h
deleted file mode 100644
index 6a871a3caec..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/Widget.h
+++ /dev/null
@@ -1,145 +0,0 @@
-/*
- * Copyright (C) 2004, 2005, 2006 Apple Computer, Inc. All rights reserved.
- * Copyright (C) 2008 Collabora Ltd. All rights reserved.
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef Widget_h
-#define Widget_h
-
-#include "core/platform/graphics/IntRect.h"
-#include "wtf/Forward.h"
-#include "wtf/RefCounted.h"
-
-namespace WebCore {
-
-class AXObjectCache;
-class Cursor;
-class Event;
-class GraphicsContext;
-class ScrollView;
-
-// The Widget class serves as a base class for three kinds of objects:
-// (1) Scrollable areas (ScrollView)
-// (2) Scrollbars (Scrollbar)
-// (3) Plugins (PluginView)
-//
-// Widgets are connected in a hierarchy, with the restriction that plugins and scrollbars are always leaves of the
-// tree. Only ScrollViews can have children (and therefore the Widget class has no concept of children).
-class Widget : public RefCounted<Widget> {
-public:
- Widget();
- virtual ~Widget();
-
- int x() const { return frameRect().x(); }
- int y() const { return frameRect().y(); }
- int width() const { return frameRect().width(); }
- int height() const { return frameRect().height(); }
- IntSize size() const { return frameRect().size(); }
- IntPoint location() const { return frameRect().location(); }
-
- virtual void setFrameRect(const IntRect& frame) { m_frame = frame; }
- const IntRect& frameRect() const { return m_frame; }
- IntRect boundsRect() const { return IntRect(0, 0, width(), height()); }
-
- void resize(int w, int h) { setFrameRect(IntRect(x(), y(), w, h)); }
- void resize(const IntSize& s) { setFrameRect(IntRect(location(), s)); }
- void move(int x, int y) { setFrameRect(IntRect(x, y, width(), height())); }
- void move(const IntPoint& p) { setFrameRect(IntRect(p, size())); }
-
- virtual void paint(GraphicsContext*, const IntRect&) { }
- void invalidate() { invalidateRect(boundsRect()); }
- virtual void invalidateRect(const IntRect&) = 0;
-
- virtual void setFocus(bool) { }
-
- void setCursor(const Cursor&);
-
- virtual void show() { }
- virtual void hide() { }
- bool isSelfVisible() const { return m_selfVisible; } // Whether or not we have been explicitly marked as visible or not.
- bool isParentVisible() const { return m_parentVisible; } // Whether or not our parent is visible.
- bool isVisible() const { return m_selfVisible && m_parentVisible; } // Whether or not we are actually visible.
- virtual void setParentVisible(bool visible) { m_parentVisible = visible; }
- void setSelfVisible(bool v) { m_selfVisible = v; }
-
- virtual bool isFrameView() const { return false; }
- virtual bool isPluginView() const { return false; }
- virtual bool isPluginContainer() const { return false; }
- virtual bool isScrollbar() const { return false; }
- virtual bool isScrollView() const { return false; }
-
- void removeFromParent();
- virtual void setParent(ScrollView* view);
- ScrollView* parent() const { return m_parent; }
- ScrollView* root() const;
-
- virtual void handleEvent(Event*) { }
-
- IntRect convertToRootView(const IntRect&) const;
- IntRect convertFromRootView(const IntRect&) const;
-
- IntPoint convertToRootView(const IntPoint&) const;
- IntPoint convertFromRootView(const IntPoint&) const;
-
- // It is important for cross-platform code to realize that Mac has flipped coordinates. Therefore any code
- // that tries to convert the location of a rect using the point-based convertFromContainingWindow will end
- // up with an inaccurate rect. Always make sure to use the rect-based convertFromContainingWindow method
- // when converting window rects.
- IntRect convertToContainingWindow(const IntRect&) const;
- IntRect convertFromContainingWindow(const IntRect&) const;
-
- IntPoint convertToContainingWindow(const IntPoint&) const;
- IntPoint convertFromContainingWindow(const IntPoint&) const;
-
- virtual void frameRectsChanged() { }
-
- // Notifies this widget that other widgets on the page have been repositioned.
- virtual void widgetPositionsUpdated() {}
-
- // Notifies this widget that its clip rect changed.
- virtual void clipRectChanged() { }
-
- // Virtual methods to convert points to/from the containing ScrollView
- virtual IntRect convertToContainingView(const IntRect&) const;
- virtual IntRect convertFromContainingView(const IntRect&) const;
- virtual IntPoint convertToContainingView(const IntPoint&) const;
- virtual IntPoint convertFromContainingView(const IntPoint&) const;
-
- // A means to access the AX cache when this object can get a pointer to it.
- virtual AXObjectCache* axObjectCache() const { return 0; }
-
- // Notifies this widget that it will no longer be receiving events.
- virtual void eventListenersRemoved() { }
-
-private:
- ScrollView* m_parent;
- IntRect m_frame;
- bool m_selfVisible;
- bool m_parentVisible;
-};
-
-} // namespace WebCore
-
-#endif // Widget_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/WindowsKeyboardCodes.h b/chromium/third_party/WebKit/Source/core/platform/WindowsKeyboardCodes.h
deleted file mode 100644
index 237b91670f9..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/WindowsKeyboardCodes.h
+++ /dev/null
@@ -1,320 +0,0 @@
-/*
- * Copyright (C) 2010 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef VK_UNKNOWN
-
-#define VK_UNKNOWN 0
-
-// Left mouse button
-// Right mouse button
-// Control-break processing
-// Middle mouse button (three-button mouse)
-// VK_XBUTTON1 (05)
-// VK_XBUTTON2 (06)
-
-#ifndef VK_BACK
-#define VK_BACK 0x08
-#endif
-#ifndef VK_TAB
-#define VK_TAB 0x09
-#endif
-#ifndef VK_CLEAR
-#define VK_CLEAR 0x0C
-#endif
-#ifndef VK_RETURN
-#define VK_RETURN 0x0D
-#endif
-#ifndef VK_SHIFT
-#define VK_SHIFT 0x10
-#endif
-#ifndef VK_CONTROL
-#define VK_CONTROL 0x11 // CTRL key
-#endif
-#ifndef VK_MENU
-#define VK_MENU 0x12 // ALT key
-#endif
-#ifndef VK_PAUSE
-#define VK_PAUSE 0x13 // PAUSE key
-#endif
-#ifndef VK_CAPITAL
-#define VK_CAPITAL 0x14 // CAPS LOCK key
-#endif
-#ifndef VK_KANA
-#define VK_KANA 0x15 // Input Method Editor (IME) Kana mode
-#endif
-#ifndef VK_HANGUL
-#define VK_HANGUL 0x15 // IME Hangul mode
-#endif
-#ifndef VK_JUNJA
-#define VK_JUNJA 0x17 // IME Junja mode
-#endif
-#ifndef VK_FINAL
-#define VK_FINAL 0x18 // IME final mode
-#endif
-#ifndef VK_HANJA
-#define VK_HANJA 0x19 // IME Hanja mode
-#endif
-#ifndef VK_KANJI
-#define VK_KANJI 0x19 // IME Kanji mode
-#endif
-#ifndef VK_ESCAPE
-#define VK_ESCAPE 0x1B // ESC key
-#endif
-#ifndef VK_CONVERT
-#define VK_CONVERT 0x1C // IME convert
-#endif
-#ifndef VK_NONCONVERT
-#define VK_NONCONVERT 0x1D // IME nonconvert
-#endif
-#ifndef VK_ACCEPT
-#define VK_ACCEPT 0x1E // IME accept
-#endif
-#ifndef VK_MODECHANGE
-#define VK_MODECHANGE 0x1F // IME mode change request
-#endif
-#ifndef VK_SPACE
-#define VK_SPACE 0x20 // SPACE key
-#endif
-#ifndef VK_PRIOR
-#define VK_PRIOR 0x21 // PAGE UP key
-#endif
-#ifndef VK_NEXT
-#define VK_NEXT 0x22 // PAGE DOWN key
-#endif
-#ifndef VK_END
-#define VK_END 0x23 // END key
-#endif
-#ifndef VK_HOME
-#define VK_HOME 0x24 // HOME key
-#endif
-#ifndef VK_LEFT
-#define VK_LEFT 0x25 // LEFT ARROW key
-#endif
-#ifndef VK_UP
-#define VK_UP 0x26 // UP ARROW key
-#endif
-#ifndef VK_RIGHT
-#define VK_RIGHT 0x27 // RIGHT ARROW key
-#endif
-#ifndef VK_DOWN
-#define VK_DOWN 0x28 // DOWN ARROW key
-#endif
-#ifndef VK_SELECT
-#define VK_SELECT 0x29 // SELECT key
-#endif
-#ifndef VK_PRINT
-#define VK_PRINT 0x2A // PRINT key
-#endif
-#ifndef VK_EXECUTE
-#define VK_EXECUTE 0x2B // EXECUTE key
-#endif
-#ifndef VK_SNAPSHOT
-#define VK_SNAPSHOT 0x2C // PRINT SCREEN key
-#endif
-#ifndef VK_INSERT
-#define VK_INSERT 0x2D // INS key
-#endif
-#ifndef VK_DELETE
-#define VK_DELETE 0x2E // DEL key
-#endif
-#ifndef VK_HELP
-#define VK_HELP 0x2F // HELP key
-#endif
-
-#define VK_0 0x30
-#define VK_1 0x31
-#define VK_2 0x32
-#define VK_3 0x33
-#define VK_4 0x34
-#define VK_5 0x35
-#define VK_6 0x36
-#define VK_7 0x37
-#define VK_8 0x38
-#define VK_9 0x39
-#define VK_A 0x41
-#define VK_B 0x42
-#define VK_C 0x43
-#define VK_D 0x44
-#define VK_E 0x45
-#define VK_F 0x46
-#define VK_G 0x47
-#define VK_H 0x48
-#define VK_I 0x49
-#define VK_J 0x4A
-#define VK_K 0x4B
-#define VK_L 0x4C
-#define VK_M 0x4D
-#define VK_N 0x4E
-#define VK_O 0x4F
-#define VK_P 0x50
-#define VK_Q 0x51
-#define VK_R 0x52
-#define VK_S 0x53
-#define VK_T 0x54
-#define VK_U 0x55
-#define VK_V 0x56
-#define VK_W 0x57
-#define VK_X 0x58
-#define VK_Y 0x59
-#define VK_Z 0x5A
-
-#define VK_LWIN 0x5B // Left Windows key (Microsoft Natural keyboard)
-
-#define VK_RWIN 0x5C // Right Windows key (Natural keyboard)
-
-#define VK_APPS 0x5D // Applications key (Natural keyboard)
-
-#define VK_SLEEP 0x5F // Computer Sleep key
-
-// Num pad keys
-#define VK_NUMPAD0 0x60
-#define VK_NUMPAD1 0x61
-#define VK_NUMPAD2 0x62
-#define VK_NUMPAD3 0x63
-#define VK_NUMPAD4 0x64
-#define VK_NUMPAD5 0x65
-#define VK_NUMPAD6 0x66
-#define VK_NUMPAD7 0x67
-#define VK_NUMPAD8 0x68
-#define VK_NUMPAD9 0x69
-#define VK_MULTIPLY 0x6A
-#define VK_ADD 0x6B
-#define VK_SEPARATOR 0x6C
-#define VK_SUBTRACT 0x6D
-#define VK_DECIMAL 0x6E
-#define VK_DIVIDE 0x6F
-
-#define VK_F1 0x70
-#define VK_F2 0x71
-#define VK_F3 0x72
-#define VK_F4 0x73
-#define VK_F5 0x74
-#define VK_F6 0x75
-#define VK_F7 0x76
-#define VK_F8 0x77
-#define VK_F9 0x78
-#define VK_F10 0x79
-#define VK_F11 0x7A
-#define VK_F12 0x7B
-#define VK_F13 0x7C
-#define VK_F14 0x7D
-#define VK_F15 0x7E
-#define VK_F16 0x7F
-#define VK_F17 0x80
-#define VK_F18 0x81
-#define VK_F19 0x82
-#define VK_F20 0x83
-#define VK_F21 0x84
-#define VK_F22 0x85
-#define VK_F23 0x86
-#define VK_F24 0x87
-
-#define VK_NUMLOCK 0x90
-#define VK_SCROLL 0x91
-#define VK_LSHIFT 0xA0
-#define VK_RSHIFT 0xA1
-#define VK_LCONTROL 0xA2
-#define VK_RCONTROL 0xA3
-#define VK_LMENU 0xA4
-#define VK_RMENU 0xA5
-
-#define VK_BROWSER_BACK 0xA6 // Windows 2000/XP: Browser Back key
-#define VK_BROWSER_FORWARD 0xA7 // Windows 2000/XP: Browser Forward key
-#define VK_BROWSER_REFRESH 0xA8 // Windows 2000/XP: Browser Refresh key
-#define VK_BROWSER_STOP 0xA9 // Windows 2000/XP: Browser Stop key
-#define VK_BROWSER_SEARCH 0xAA // Windows 2000/XP: Browser Search key
-#define VK_BROWSER_FAVORITES 0xAB // Windows 2000/XP: Browser Favorites key
-#define VK_BROWSER_HOME 0xAC // Windows 2000/XP: Browser Start and Home key
-#define VK_VOLUME_MUTE 0xAD // Windows 2000/XP: Volume Mute key
-#define VK_VOLUME_DOWN 0xAE // Windows 2000/XP: Volume Down key
-#define VK_VOLUME_UP 0xAF // Windows 2000/XP: Volume Up key
-#define VK_MEDIA_NEXT_TRACK 0xB0 // Windows 2000/XP: Next Track key
-#define VK_MEDIA_PREV_TRACK 0xB1 // Windows 2000/XP: Previous Track key
-#define VK_MEDIA_STOP 0xB2 // Windows 2000/XP: Stop Media key
-#define VK_MEDIA_PLAY_PAUSE 0xB3 // Windows 2000/XP: Play/Pause Media key
-#define VK_MEDIA_LAUNCH_MAIL 0xB4 // Windows 2000/XP: Start Mail key
-#define VK_MEDIA_LAUNCH_MEDIA_SELECT 0xB5 // Windows 2000/XP: Select Media key
-#define VK_MEDIA_LAUNCH_APP1 0xB6 // VK_LAUNCH_APP1 (B6) Windows 2000/XP: Start Application 1 key
-#define VK_MEDIA_LAUNCH_APP2 0xB7 // VK_LAUNCH_APP2 (B7) Windows 2000/XP: Start Application 2 key
-
-// VK_OEM_1 (BA) Used for miscellaneous characters; it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the ';:' key
-#define VK_OEM_1 0xBA
-
-// Windows 2000/XP: For any country/region, the '+' key
-#define VK_OEM_PLUS 0xBB
-
-// Windows 2000/XP: For any country/region, the ',' key
-#define VK_OEM_COMMA 0xBC
-
-// Windows 2000/XP: For any country/region, the '-' key
-#define VK_OEM_MINUS 0xBD
-
-// Windows 2000/XP: For any country/region, the '.' key
-#define VK_OEM_PERIOD 0xBE
-
-// VK_OEM_2 (BF) Used for miscellaneous characters; it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the '/?' key
-#define VK_OEM_2 0xBF
-
-// VK_OEM_3 (C0) Used for miscellaneous characters; it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the '`~' key
-#define VK_OEM_3 0xC0
-
-// VK_OEM_4 (DB) Used for miscellaneous characters; it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the '[{' key
-#define VK_OEM_4 0xDB
-
-// VK_OEM_5 (DC) Used for miscellaneous characters; it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the '\|' key
-#define VK_OEM_5 0xDC
-
-// VK_OEM_6 (DD) Used for miscellaneous characters; it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the ']}' key
-#define VK_OEM_6 0xDD
-
-// VK_OEM_7 (DE) Used for miscellaneous characters; it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the 'single-quote/double-quote' key
-#define VK_OEM_7 0xDE
-
-// VK_OEM_8 (DF) Used for miscellaneous characters; it can vary by keyboard.
-#define VK_OEM_8 0xDF
-
-// VK_OEM_102 (E2) Windows 2000/XP: Either the angle bracket key or the backslash key on the RT 102-key keyboard
-#define VK_OEM_102 0xE2
-
-// Windows 95/98/Me, Windows NT 4.0, Windows 2000/XP: IME PROCESS key
-#define VK_PROCESSKEY 0xE5
-
-// Windows 2000/XP: Used to pass Unicode characters as if they were keystrokes. The VK_PACKET key is the low word of a 32-bit Virtual Key value used for non-keyboard input methods. For more information, see Remark in KEYBDINPUT,SendInput, WM_KEYDOWN, and WM_KEYUP
-#define VK_PACKET 0xE7
-
-#define VK_ATTN 0xF6 // Attn key
-#define VK_CRSEL 0xF7 // CrSel key
-#define VK_EXSEL 0xF8 // ExSel key
-#define VK_EREOF 0xF9 // Erase EOF key
-#define VK_PLAY 0xFA // Play key
-#define VK_ZOOM 0xFB // Zoom key
-
-#define VK_NONAME 0xFC // Reserved for future use
-
-#define VK_PA1 0xFD // VK_PA1 (FD) PA1 key
-
-#define VK_OEM_CLEAR 0xFE // Clear key
-
-#endif // VK_UNKNOWN
diff --git a/chromium/third_party/WebKit/Source/core/platform/animation/AnimationTranslationUtil.cpp b/chromium/third_party/WebKit/Source/core/platform/animation/AnimationTranslationUtil.cpp
new file mode 100644
index 00000000000..cbb7c79f630
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/platform/animation/AnimationTranslationUtil.cpp
@@ -0,0 +1,355 @@
+/*
+ * Copyright (C) 2012 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+
+#include "core/platform/animation/AnimationTranslationUtil.h"
+
+#include "core/platform/animation/CSSAnimationData.h"
+#include "core/platform/animation/KeyframeValueList.h"
+#include "platform/LengthFunctions.h"
+#include "platform/geometry/FloatSize.h"
+#include "platform/graphics/filters/SkiaImageFilterBuilder.h"
+#include "platform/transforms/InterpolatedTransformOperation.h"
+#include "platform/transforms/Matrix3DTransformOperation.h"
+#include "platform/transforms/MatrixTransformOperation.h"
+#include "platform/transforms/PerspectiveTransformOperation.h"
+#include "platform/transforms/RotateTransformOperation.h"
+#include "platform/transforms/ScaleTransformOperation.h"
+#include "platform/transforms/SkewTransformOperation.h"
+#include "platform/transforms/TransformationMatrix.h"
+#include "platform/transforms/TranslateTransformOperation.h"
+
+#include "public/platform/Platform.h"
+#include "public/platform/WebAnimation.h"
+#include "public/platform/WebAnimationCurve.h"
+#include "public/platform/WebCompositorSupport.h"
+#include "public/platform/WebFilterAnimationCurve.h"
+#include "public/platform/WebFloatAnimationCurve.h"
+#include "public/platform/WebTransformAnimationCurve.h"
+
+#include "wtf/OwnPtr.h"
+#include "wtf/text/CString.h"
+
+using namespace std;
+using namespace blink;
+
+namespace WebCore {
+
+void toWebTransformOperations(const TransformOperations& transformOperations, const FloatSize& boxSize, WebTransformOperations* webTransformOperations)
+{
+ // We need to do a deep copy the transformOperations may contain ref pointers to TransformOperation objects.
+ for (size_t j = 0; j < transformOperations.size(); ++j) {
+ switch (transformOperations.operations()[j]->type()) {
+ case TransformOperation::ScaleX:
+ case TransformOperation::ScaleY:
+ case TransformOperation::ScaleZ:
+ case TransformOperation::Scale3D:
+ case TransformOperation::Scale: {
+ ScaleTransformOperation* transform = static_cast<ScaleTransformOperation*>(transformOperations.operations()[j].get());
+ webTransformOperations->appendScale(transform->x(), transform->y(), transform->z());
+ break;
+ }
+ case TransformOperation::TranslateX:
+ case TransformOperation::TranslateY:
+ case TransformOperation::TranslateZ:
+ case TransformOperation::Translate3D:
+ case TransformOperation::Translate: {
+ TranslateTransformOperation* transform = static_cast<TranslateTransformOperation*>(transformOperations.operations()[j].get());
+ webTransformOperations->appendTranslate(floatValueForLength(transform->x(), boxSize.width()), floatValueForLength(transform->y(), boxSize.height()), floatValueForLength(transform->z(), 1));
+ break;
+ }
+ case TransformOperation::RotateX:
+ case TransformOperation::RotateY:
+ case TransformOperation::Rotate3D:
+ case TransformOperation::Rotate: {
+ RotateTransformOperation* transform = static_cast<RotateTransformOperation*>(transformOperations.operations()[j].get());
+ webTransformOperations->appendRotate(transform->x(), transform->y(), transform->z(), transform->angle());
+ break;
+ }
+ case TransformOperation::SkewX:
+ case TransformOperation::SkewY:
+ case TransformOperation::Skew: {
+ SkewTransformOperation* transform = static_cast<SkewTransformOperation*>(transformOperations.operations()[j].get());
+ webTransformOperations->appendSkew(transform->angleX(), transform->angleY());
+ break;
+ }
+ case TransformOperation::Matrix: {
+ MatrixTransformOperation* transform = static_cast<MatrixTransformOperation*>(transformOperations.operations()[j].get());
+ TransformationMatrix m = transform->matrix();
+ webTransformOperations->appendMatrix(TransformationMatrix::toSkMatrix44(m));
+ break;
+ }
+ case TransformOperation::Matrix3D: {
+ Matrix3DTransformOperation* transform = static_cast<Matrix3DTransformOperation*>(transformOperations.operations()[j].get());
+ TransformationMatrix m = transform->matrix();
+ webTransformOperations->appendMatrix(TransformationMatrix::toSkMatrix44(m));
+ break;
+ }
+ case TransformOperation::Perspective: {
+ PerspectiveTransformOperation* transform = static_cast<PerspectiveTransformOperation*>(transformOperations.operations()[j].get());
+ webTransformOperations->appendPerspective(floatValueForLength(transform->perspective(), 0));
+ break;
+ }
+ case TransformOperation::Interpolated: {
+ TransformationMatrix m;
+ transformOperations.operations()[j]->apply(m, boxSize);
+ webTransformOperations->appendMatrix(TransformationMatrix::toSkMatrix44(m));
+ break;
+ }
+ case TransformOperation::Identity:
+ webTransformOperations->appendIdentity();
+ break;
+ case TransformOperation::None:
+ // Do nothing.
+ break;
+ } // switch
+ } // for each operation
+}
+
+template <class Value, class Keyframe, class Curve>
+bool appendKeyframeWithStandardTimingFunction(Curve* curve, double keyTime, const Value* value, const Value* lastValue, blink::WebAnimationCurve::TimingFunctionType timingFunctionType, const FloatSize&)
+{
+ curve->add(Keyframe(keyTime, value->value()), timingFunctionType);
+ return true;
+}
+
+template <class Value, class Keyframe, class Curve>
+bool appendKeyframeWithCustomBezierTimingFunction(Curve* curve, double keyTime, const Value* value, const Value* lastValue, double x1, double y1, double x2, double y2, const FloatSize&)
+{
+ curve->add(Keyframe(keyTime, value->value()), x1, y1, x2, y2);
+ return true;
+}
+
+template <>
+bool appendKeyframeWithStandardTimingFunction<TransformAnimationValue, WebTransformKeyframe, WebTransformAnimationCurve>(WebTransformAnimationCurve* curve, double keyTime, const TransformAnimationValue* value, const TransformAnimationValue* lastValue, blink::WebAnimationCurve::TimingFunctionType timingFunctionType, const FloatSize& boxSize)
+{
+ bool canBlend = !lastValue;
+ OwnPtr<WebTransformOperations> operations = adoptPtr(Platform::current()->compositorSupport()->createTransformOperations());
+ if (!operations)
+ return false;
+ toWebTransformOperations(*value->value(), boxSize, operations.get());
+ if (!canBlend) {
+ OwnPtr<WebTransformOperations> lastOperations = adoptPtr(Platform::current()->compositorSupport()->createTransformOperations());
+ if (!lastOperations)
+ return false;
+ toWebTransformOperations(*lastValue->value(), boxSize, lastOperations.get());
+ canBlend = lastOperations->canBlendWith(*operations);
+ }
+ if (canBlend) {
+ curve->add(WebTransformKeyframe(keyTime, operations.release()), timingFunctionType);
+ return true;
+ }
+ return false;
+}
+
+template <>
+bool appendKeyframeWithCustomBezierTimingFunction<TransformAnimationValue, WebTransformKeyframe, WebTransformAnimationCurve>(WebTransformAnimationCurve* curve, double keyTime, const TransformAnimationValue* value, const TransformAnimationValue* lastValue, double x1, double y1, double x2, double y2, const FloatSize& boxSize)
+{
+ bool canBlend = !lastValue;
+ OwnPtr<WebTransformOperations> operations = adoptPtr(Platform::current()->compositorSupport()->createTransformOperations());
+ if (!operations)
+ return false;
+ toWebTransformOperations(*value->value(), boxSize, operations.get());
+ if (!canBlend) {
+ OwnPtr<WebTransformOperations> lastOperations = adoptPtr(Platform::current()->compositorSupport()->createTransformOperations());
+ if (!lastOperations)
+ return false;
+ toWebTransformOperations(*lastValue->value(), boxSize, lastOperations.get());
+ canBlend = lastOperations->canBlendWith(*operations);
+ }
+ if (canBlend) {
+ curve->add(WebTransformKeyframe(keyTime, operations.release()), x1, y1, x2, y2);
+ return true;
+ }
+ return false;
+}
+
+bool toWebFilterOperations(const FilterOperations& inOperations, WebFilterOperations* outOperations)
+{
+ SkiaImageFilterBuilder builder;
+ FilterOutsets outsets = inOperations.outsets();
+ builder.setCropOffset(FloatSize(outsets.left(), outsets.top()));
+ return builder.buildFilterOperations(inOperations, outOperations);
+}
+
+template <>
+bool appendKeyframeWithStandardTimingFunction<FilterAnimationValue, WebFilterKeyframe, WebFilterAnimationCurve>(WebFilterAnimationCurve* curve, double keyTime, const FilterAnimationValue* value, const FilterAnimationValue* lastValue, blink::WebAnimationCurve::TimingFunctionType timingFunctionType, const FloatSize& boxSize)
+{
+ // FIXME(ajuma): In order to animate pixel-moving filters on the compositor thread, we need
+ // to update overlap testing to take into account the bounds within which the animation
+ // will be contained, and we need the compositor to update layer bounds as the animation
+ // progresses.
+ if (value->value()->hasFilterThatMovesPixels())
+ return false;
+ OwnPtr<WebFilterOperations> operations = adoptPtr(Platform::current()->compositorSupport()->createFilterOperations());
+ if (!toWebFilterOperations(*(value->value()), operations.get()))
+ return false;
+ curve->add(WebFilterKeyframe(keyTime, operations.release()), timingFunctionType);
+ return true;
+}
+
+template <>
+bool appendKeyframeWithCustomBezierTimingFunction<FilterAnimationValue, WebFilterKeyframe, WebFilterAnimationCurve>(WebFilterAnimationCurve* curve, double keyTime, const FilterAnimationValue* value, const FilterAnimationValue* lastValue, double x1, double y1, double x2, double y2, const FloatSize& boxSize)
+{
+ // FIXME(ajuma): In order to animate pixel-moving filters on the compositor thread, we need
+ // to update overlap testing to take into account the bounds within which the animation
+ // will be contained, and we need the compositor to update layer bounds as the animation
+ // progresses.
+ if (value->value()->hasFilterThatMovesPixels())
+ return false;
+
+ OwnPtr<WebFilterOperations> operations = adoptPtr(Platform::current()->compositorSupport()->createFilterOperations());
+ if (!toWebFilterOperations(*(value->value()), operations.get()))
+ return false;
+ curve->add(WebFilterKeyframe(keyTime, operations.release()), x1, y1, x2, y2);
+ return true;
+}
+
+template <class Value, class Keyframe, class Curve>
+PassOwnPtr<blink::WebAnimation> createWebAnimation(const KeyframeValueList& valueList, const CSSAnimationData* animation, int animationId, double timeOffset, Curve* curve, blink::WebAnimation::TargetProperty targetProperty, const FloatSize& boxSize)
+{
+ bool alternate = false;
+ bool reverse = false;
+ if (animation && animation->isDirectionSet()) {
+ CSSAnimationData::AnimationDirection direction = animation->direction();
+ if (direction == CSSAnimationData::AnimationDirectionAlternate || direction == CSSAnimationData::AnimationDirectionAlternateReverse)
+ alternate = true;
+ if (direction == CSSAnimationData::AnimationDirectionReverse || direction == CSSAnimationData::AnimationDirectionAlternateReverse)
+ reverse = true;
+ }
+
+ for (size_t i = 0; i < valueList.size(); i++) {
+ size_t index = reverse ? valueList.size() - i - 1 : i;
+ const Value* originalValue = static_cast<const Value*>(valueList.at(index));
+ const Value* lastOriginalValue = 0;
+ if (valueList.size() > 1 && ((reverse && index + 1 < valueList.size()) || (!reverse && index > 0)))
+ lastOriginalValue = static_cast<const Value*>(valueList.at(reverse ? index + 1 : index - 1));
+
+ const TimingFunction* originalTimingFunction = originalValue->timingFunction();
+
+ // If there hasn't been a timing function associated with this keyframe, use the
+ // animation's timing function, if we have one.
+ if (!originalTimingFunction && animation->isTimingFunctionSet())
+ originalTimingFunction = animation->timingFunction();
+
+ // Ease is the default timing function.
+ blink::WebAnimationCurve::TimingFunctionType timingFunctionType = blink::WebAnimationCurve::TimingFunctionTypeEase;
+
+ bool isUsingCustomBezierTimingFunction = false;
+ double x1 = 0;
+ double y1 = 0;
+ double x2 = 1;
+ double y2 = 1;
+
+ if (originalTimingFunction) {
+ switch (originalTimingFunction->type()) {
+ case TimingFunction::StepsFunction:
+ // FIXME: add support for steps timing function.
+ return nullptr;
+ case TimingFunction::LinearFunction:
+ // This doesn't need to be flipped when the animation is reversed.
+ timingFunctionType = blink::WebAnimationCurve::TimingFunctionTypeLinear;
+ break;
+ case TimingFunction::CubicBezierFunction:
+ {
+ const CubicBezierTimingFunction* originalBezierTimingFunction = toCubicBezierTimingFunction(originalTimingFunction);
+ isUsingCustomBezierTimingFunction = true;
+ x1 = originalBezierTimingFunction->x1();
+ y1 = originalBezierTimingFunction->y1();
+ x2 = originalBezierTimingFunction->x2();
+ y2 = originalBezierTimingFunction->y2();
+ if (reverse) {
+ // When the animation is reversed, we need to swap the
+ // start and end keyframes, and flip the timing
+ // function in both x and y.
+ double x1Old = x1;
+ double y1Old = y1;
+ x1 = 1 - x2;
+ y1 = 1 - y2;
+ x2 = 1 - x1Old;
+ y2 = 1 - y1Old;
+ }
+ break;
+ }
+ default:
+ ASSERT_NOT_REACHED();
+ } // switch
+ }
+
+ double duration = (animation && animation->isDurationSet()) ? animation->duration() : 1;
+ double keyTime = originalValue->keyTime() * duration;
+
+ if (reverse)
+ keyTime = duration - keyTime;
+
+ bool addedKeyframe = false;
+ if (isUsingCustomBezierTimingFunction)
+ addedKeyframe = appendKeyframeWithCustomBezierTimingFunction<Value, Keyframe, Curve>(curve, keyTime, originalValue, lastOriginalValue, x1, y1, x2, y2, boxSize);
+ else
+ addedKeyframe = appendKeyframeWithStandardTimingFunction<Value, Keyframe, Curve>(curve, keyTime, originalValue, lastOriginalValue, timingFunctionType, boxSize);
+
+ if (!addedKeyframe)
+ return nullptr;
+ }
+
+ OwnPtr<blink::WebAnimation> webAnimation = adoptPtr(Platform::current()->compositorSupport()->createAnimation(*curve, targetProperty, animationId));
+
+ int iterations = (animation && animation->isIterationCountSet()) ? animation->iterationCount() : 1;
+ webAnimation->setIterations(iterations);
+ webAnimation->setAlternatesDirection(alternate);
+
+ // If timeOffset > 0, then the animation has started in the past.
+ webAnimation->setTimeOffset(timeOffset);
+
+ return webAnimation.release();
+}
+
+PassOwnPtr<blink::WebAnimation> createWebAnimation(const KeyframeValueList& values, const CSSAnimationData* animation, int animationId, double timeOffset, const FloatSize& boxSize)
+{
+ switch (values.property()) {
+ case AnimatedPropertyWebkitTransform: {
+ OwnPtr<WebTransformAnimationCurve> curve = adoptPtr(Platform::current()->compositorSupport()->createTransformAnimationCurve());
+ return createWebAnimation<TransformAnimationValue, WebTransformKeyframe, WebTransformAnimationCurve>(values, animation, animationId, timeOffset, curve.get(), blink::WebAnimation::TargetPropertyTransform, FloatSize(boxSize));
+ }
+
+ case AnimatedPropertyOpacity: {
+ OwnPtr<WebFloatAnimationCurve> curve = adoptPtr(Platform::current()->compositorSupport()->createFloatAnimationCurve());
+ return createWebAnimation<FloatAnimationValue, WebFloatKeyframe, WebFloatAnimationCurve>(values, animation, animationId, timeOffset, curve.get(), blink::WebAnimation::TargetPropertyOpacity, FloatSize());
+ }
+
+ case AnimatedPropertyWebkitFilter: {
+ OwnPtr<WebFilterAnimationCurve> curve = adoptPtr(Platform::current()->compositorSupport()->createFilterAnimationCurve());
+ return createWebAnimation<FilterAnimationValue, WebFilterKeyframe, WebFilterAnimationCurve>(values, animation, animationId, timeOffset, curve.get(), blink::WebAnimation::TargetPropertyFilter, FloatSize(boxSize));
+ }
+
+ case AnimatedPropertyBackgroundColor:
+ case AnimatedPropertyInvalid:
+ return nullptr;
+ }
+
+ return nullptr;
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/animation/AnimationTranslationUtil.h b/chromium/third_party/WebKit/Source/core/platform/animation/AnimationTranslationUtil.h
new file mode 100644
index 00000000000..2c95cdfaac6
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/platform/animation/AnimationTranslationUtil.h
@@ -0,0 +1,63 @@
+/*
+ * Copyright (C) 2010 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef AnimationTranslationUtil_h
+#define AnimationTranslationUtil_h
+
+#include "platform/graphics/filters/FilterOperations.h"
+#include "platform/transforms/TransformOperations.h"
+#include "public/platform/WebTransformOperations.h"
+#include "wtf/PassOwnPtr.h"
+
+namespace blink {
+class WebAnimation;
+class WebFilterOperations;
+}
+
+namespace WebCore {
+
+class KeyframeValueList;
+class CSSAnimationData;
+class FloatSize;
+
+
+// Translates WebCore animation data into a WebAnimation. If we are unable
+// to perform this translation, we return nullptr. This can happen if
+// - a steps timing function is used,
+// - a property other than AnimatedPropertyWebkitTransform, or AnimatedPropertyOpacity is animated, or
+// - a transform animation involves a non-invertable transform.
+PassOwnPtr<blink::WebAnimation> createWebAnimation(const KeyframeValueList&, const CSSAnimationData*, int animationId, double timeOffset, const FloatSize& boxSize);
+
+void toWebTransformOperations(const TransformOperations& inOperations, const FloatSize& boxSize, blink::WebTransformOperations* outOperations);
+
+bool toWebFilterOperations(const FilterOperations& inOperations, blink::WebFilterOperations* outOperations);
+} // namespace WebCore
+
+#endif // AnimationTranslationUtil_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/animation/AnimationTranslationUtilTest.cpp b/chromium/third_party/WebKit/Source/core/platform/animation/AnimationTranslationUtilTest.cpp
new file mode 100644
index 00000000000..59dcbe91cea
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/platform/animation/AnimationTranslationUtilTest.cpp
@@ -0,0 +1,352 @@
+/*
+ * Copyright (C) 2012 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+
+#include "core/platform/animation/AnimationTranslationUtil.h"
+
+#include "core/platform/animation/CSSAnimationData.h"
+#include "core/platform/animation/KeyframeValueList.h"
+#include "platform/geometry/IntSize.h"
+#include "platform/graphics/filters/FilterOperations.h"
+#include "platform/transforms/Matrix3DTransformOperation.h"
+#include "platform/transforms/RotateTransformOperation.h"
+#include "platform/transforms/ScaleTransformOperation.h"
+#include "platform/transforms/TransformOperations.h"
+#include "platform/transforms/TranslateTransformOperation.h"
+#include "public/platform/WebAnimation.h"
+#include "public/platform/WebFilterOperations.h"
+#include "wtf/RefPtr.h"
+#include <gmock/gmock.h>
+#include <gtest/gtest.h>
+
+using namespace WebCore;
+using namespace blink;
+
+namespace {
+
+class WebTransformOperationsMock : public blink::WebTransformOperations {
+public:
+ MOCK_CONST_METHOD1(canBlendWith, bool(const WebTransformOperations&));
+ MOCK_METHOD3(appendTranslate, void(double, double, double));
+ MOCK_METHOD4(appendRotate, void(double, double, double, double));
+ MOCK_METHOD3(appendScale, void(double, double, double));
+ MOCK_METHOD2(appendSkew, void(double, double));
+ MOCK_METHOD1(appendPerspective, void(double));
+ MOCK_METHOD1(appendMatrix, void(const SkMatrix44&));
+ MOCK_METHOD0(appendIdentity, void());
+ MOCK_CONST_METHOD0(isIdentity, bool());
+};
+
+class WebFilterOperationsMock : public blink::WebFilterOperations {
+public:
+ MOCK_METHOD1(appendGrayscaleFilter, void(float));
+ MOCK_METHOD1(appendSepiaFilter, void(float));
+ MOCK_METHOD1(appendSaturateFilter, void(float));
+ MOCK_METHOD1(appendHueRotateFilter, void(float));
+ MOCK_METHOD1(appendInvertFilter, void(float));
+ MOCK_METHOD1(appendBrightnessFilter, void(float));
+ MOCK_METHOD1(appendContrastFilter, void(float));
+ MOCK_METHOD1(appendOpacityFilter, void(float));
+ MOCK_METHOD1(appendBlurFilter, void(float));
+ MOCK_METHOD3(appendDropShadowFilter, void(WebPoint, float, WebColor));
+ MOCK_METHOD1(appendColorMatrixFilter, void(SkScalar[20]));
+ MOCK_METHOD2(appendZoomFilter, void(float, int));
+ MOCK_METHOD1(appendSaturatingBrightnessFilter, void(float));
+ MOCK_METHOD1(appendReferenceFilter, void(SkImageFilter*));
+ MOCK_METHOD0(clear, void());
+};
+
+bool animationCanBeTranslated(const KeyframeValueList& values, CSSAnimationData* animation)
+{
+ IntSize boxSize;
+ return createWebAnimation(values, animation, 0, 0, boxSize);
+}
+
+TEST(AnimationTranslationUtilTest, createOpacityAnimation)
+{
+ const double duration = 1;
+ WebCore::KeyframeValueList values(AnimatedPropertyOpacity);
+ values.insert(adoptPtr(new FloatAnimationValue(0, 0)));
+ values.insert(adoptPtr(new FloatAnimationValue(duration, 1)));
+
+ RefPtr<CSSAnimationData> animation = CSSAnimationData::create();
+ animation->setDuration(duration);
+
+ EXPECT_TRUE(animationCanBeTranslated(values, animation.get()));
+}
+
+TEST(AnimationTranslationUtilTest, createFilterAnimation)
+{
+ const double duration = 1;
+ WebCore::KeyframeValueList values(AnimatedPropertyWebkitFilter);
+
+ FilterOperations operations1;
+ operations1.operations().append(BasicColorMatrixFilterOperation::create(0.5, FilterOperation::SATURATE));
+ values.insert(adoptPtr(new FilterAnimationValue(0, &operations1)));
+
+ FilterOperations operations2;
+ operations2.operations().append(BasicColorMatrixFilterOperation::create(1.0, FilterOperation::SATURATE));
+ values.insert(adoptPtr(new FilterAnimationValue(duration, &operations2)));
+
+ RefPtr<CSSAnimationData> animation = CSSAnimationData::create();
+ animation->setDuration(duration);
+
+ EXPECT_TRUE(animationCanBeTranslated(values, animation.get()));
+}
+
+TEST(AnimationTranslationUtilTest, createTransformAnimation)
+{
+ const double duration = 1;
+ WebCore::KeyframeValueList values(AnimatedPropertyWebkitTransform);
+
+ TransformOperations operations1;
+ operations1.operations().append(TranslateTransformOperation::create(Length(2, WebCore::Fixed), Length(0, WebCore::Fixed), TransformOperation::TranslateX));
+ values.insert(adoptPtr(new TransformAnimationValue(0, &operations1)));
+
+ TransformOperations operations2;
+ operations2.operations().append(TranslateTransformOperation::create(Length(4, WebCore::Fixed), Length(0, WebCore::Fixed), TransformOperation::TranslateX));
+ values.insert(adoptPtr(new TransformAnimationValue(duration, &operations2)));
+
+ RefPtr<CSSAnimationData> animation = CSSAnimationData::create();
+ animation->setDuration(duration);
+
+ EXPECT_TRUE(animationCanBeTranslated(values, animation.get()));
+}
+
+TEST(AnimationTranslationUtilTest, createTransformAnimationWithBigRotation)
+{
+ const double duration = 1;
+ WebCore::KeyframeValueList values(AnimatedPropertyWebkitTransform);
+
+ TransformOperations operations1;
+ operations1.operations().append(RotateTransformOperation::create(0, TransformOperation::Rotate));
+ values.insert(adoptPtr(new TransformAnimationValue(0, &operations1)));
+
+ TransformOperations operations2;
+ operations2.operations().append(RotateTransformOperation::create(270, TransformOperation::Rotate));
+ values.insert(adoptPtr(new TransformAnimationValue(duration, &operations2)));
+
+ RefPtr<CSSAnimationData> animation = CSSAnimationData::create();
+ animation->setDuration(duration);
+
+ EXPECT_TRUE(animationCanBeTranslated(values, animation.get()));
+}
+
+TEST(AnimationTranslationUtilTest, createTransformAnimationWithBigRotationAndEmptyTransformOperationList)
+{
+ const double duration = 1;
+ WebCore::KeyframeValueList values(AnimatedPropertyWebkitTransform);
+
+ TransformOperations operations1;
+ values.insert(adoptPtr(new TransformAnimationValue(0, &operations1)));
+
+ TransformOperations operations2;
+ operations2.operations().append(RotateTransformOperation::create(270, TransformOperation::Rotate));
+ values.insert(adoptPtr(new TransformAnimationValue(duration, &operations2)));
+
+ RefPtr<CSSAnimationData> animation = CSSAnimationData::create();
+ animation->setDuration(duration);
+
+ EXPECT_TRUE(animationCanBeTranslated(values, animation.get()));
+}
+
+TEST(AnimationTranslationUtilTest, createTransformAnimationWithRotationInvolvingNegativeAngles)
+{
+ const double duration = 1;
+ WebCore::KeyframeValueList values(AnimatedPropertyWebkitTransform);
+
+ TransformOperations operations1;
+ operations1.operations().append(RotateTransformOperation::create(-330, TransformOperation::Rotate));
+ values.insert(adoptPtr(new TransformAnimationValue(0, &operations1)));
+
+ TransformOperations operations2;
+ operations2.operations().append(RotateTransformOperation::create(-320, TransformOperation::Rotate));
+ values.insert(adoptPtr(new TransformAnimationValue(duration, &operations2)));
+
+ RefPtr<CSSAnimationData> animation = CSSAnimationData::create();
+ animation->setDuration(duration);
+
+ EXPECT_TRUE(animationCanBeTranslated(values, animation.get()));
+}
+
+TEST(AnimationTranslationUtilTest, createTransformAnimationWithSmallRotationInvolvingLargeAngles)
+{
+ const double duration = 1;
+ WebCore::KeyframeValueList values(AnimatedPropertyWebkitTransform);
+
+ TransformOperations operations1;
+ operations1.operations().append(RotateTransformOperation::create(270, TransformOperation::Rotate));
+ values.insert(adoptPtr(new TransformAnimationValue(0, &operations1)));
+
+ TransformOperations operations2;
+ operations2.operations().append(RotateTransformOperation::create(360, TransformOperation::Rotate));
+ values.insert(adoptPtr(new TransformAnimationValue(duration, &operations2)));
+
+ RefPtr<CSSAnimationData> animation = CSSAnimationData::create();
+ animation->setDuration(duration);
+
+ EXPECT_TRUE(animationCanBeTranslated(values, animation.get()));
+}
+
+TEST(AnimationTranslationUtilTest, createTransformAnimationWithNonDecomposableMatrix)
+{
+ const double duration = 1;
+ WebCore::KeyframeValueList values(AnimatedPropertyWebkitTransform);
+
+ TransformationMatrix matrix1;
+ TransformOperations operations1;
+ operations1.operations().append(Matrix3DTransformOperation::create(matrix1));
+ values.insert(adoptPtr(new TransformAnimationValue(0, &operations1)));
+
+ TransformationMatrix matrix2;
+ matrix2.setM11(0);
+ TransformOperations operations2;
+ operations2.operations().append(Matrix3DTransformOperation::create(matrix2));
+ values.insert(adoptPtr(new TransformAnimationValue(duration, &operations2)));
+
+ RefPtr<CSSAnimationData> animation = CSSAnimationData::create();
+ animation->setDuration(duration);
+
+ EXPECT_FALSE(animationCanBeTranslated(values, animation.get()));
+}
+
+TEST(AnimationTranslationUtilTest, createTransformAnimationWithNonInvertibleTransform)
+{
+ const double duration = 1;
+ WebCore::KeyframeValueList values(AnimatedPropertyWebkitTransform);
+
+ TransformOperations operations1;
+ operations1.operations().append(ScaleTransformOperation::create(1, 1, 1, TransformOperation::Scale3D));
+ values.insert(adoptPtr(new TransformAnimationValue(0, &operations1)));
+
+ TransformOperations operations2;
+ operations2.operations().append(ScaleTransformOperation::create(1, 0, 1, TransformOperation::Scale3D));
+ values.insert(adoptPtr(new TransformAnimationValue(duration, &operations2)));
+
+ RefPtr<CSSAnimationData> animation = CSSAnimationData::create();
+ animation->setDuration(duration);
+
+ EXPECT_TRUE(animationCanBeTranslated(values, animation.get()));
+}
+
+TEST(AnimationTranslationUtilTest, createReversedAnimation)
+{
+ const double duration = 1;
+ WebCore::KeyframeValueList values(AnimatedPropertyWebkitTransform);
+
+ TransformOperations operations1;
+ operations1.operations().append(TranslateTransformOperation::create(Length(2, WebCore::Fixed), Length(0, WebCore::Fixed), TransformOperation::TranslateX));
+ values.insert(adoptPtr(new TransformAnimationValue(0, &operations1)));
+
+ TransformOperations operations2;
+ operations2.operations().append(TranslateTransformOperation::create(Length(4, WebCore::Fixed), Length(0, WebCore::Fixed), TransformOperation::TranslateX));
+ values.insert(adoptPtr(new TransformAnimationValue(duration, &operations2)));
+
+ RefPtr<CSSAnimationData> animation = CSSAnimationData::create();
+ animation->setDuration(duration);
+ animation->setDirection(CSSAnimationData::AnimationDirectionReverse);
+
+ EXPECT_TRUE(animationCanBeTranslated(values, animation.get()));
+}
+
+TEST(AnimationTranslationUtilTest, createAlternatingAnimation)
+{
+ const double duration = 1;
+ WebCore::KeyframeValueList values(AnimatedPropertyWebkitTransform);
+
+ TransformOperations operations1;
+ operations1.operations().append(TranslateTransformOperation::create(Length(2, WebCore::Fixed), Length(0, WebCore::Fixed), TransformOperation::TranslateX));
+ values.insert(adoptPtr(new TransformAnimationValue(0, &operations1)));
+
+ TransformOperations operations2;
+ operations2.operations().append(TranslateTransformOperation::create(Length(4, WebCore::Fixed), Length(0, WebCore::Fixed), TransformOperation::TranslateX));
+ values.insert(adoptPtr(new TransformAnimationValue(duration, &operations2)));
+
+ RefPtr<CSSAnimationData> animation = CSSAnimationData::create();
+ animation->setDuration(duration);
+ animation->setDirection(CSSAnimationData::AnimationDirectionAlternate);
+ animation->setIterationCount(2);
+
+ EXPECT_TRUE(animationCanBeTranslated(values, animation.get()));
+}
+
+TEST(AnimationTranslationUtilTest, createReversedAlternatingAnimation)
+{
+ const double duration = 1;
+ WebCore::KeyframeValueList values(AnimatedPropertyWebkitTransform);
+
+ TransformOperations operations1;
+ operations1.operations().append(TranslateTransformOperation::create(Length(2, WebCore::Fixed), Length(0, WebCore::Fixed), TransformOperation::TranslateX));
+ values.insert(adoptPtr(new TransformAnimationValue(0, &operations1)));
+
+ TransformOperations operations2;
+ operations2.operations().append(TranslateTransformOperation::create(Length(4, WebCore::Fixed), Length(0, WebCore::Fixed), TransformOperation::TranslateX));
+ values.insert(adoptPtr(new TransformAnimationValue(duration, &operations2)));
+
+ RefPtr<CSSAnimationData> animation = CSSAnimationData::create();
+ animation->setDuration(duration);
+ animation->setDirection(CSSAnimationData::AnimationDirectionAlternateReverse);
+ animation->setIterationCount(2);
+
+ EXPECT_TRUE(animationCanBeTranslated(values, animation.get()));
+}
+
+TEST(AnimationTranslationUtilTest, transformsWork)
+{
+ TransformOperations ops;
+ FloatSize box(100, 200);
+ WebTransformOperationsMock outOps;
+
+ EXPECT_CALL(outOps, appendTranslate(2, 0, 0));
+ EXPECT_CALL(outOps, appendTranslate(2, 60, 0));
+ EXPECT_CALL(outOps, appendRotate(0.1, 0.2, 0.3, 200000.4));
+ EXPECT_CALL(outOps, appendScale(50.2, 100, -4));
+
+ ops.operations().append(TranslateTransformOperation::create(Length(2, WebCore::Fixed), Length(0, WebCore::Fixed), TransformOperation::TranslateX));
+ ops.operations().append(TranslateTransformOperation::create(Length(2, WebCore::Percent), Length(30, WebCore::Percent), TransformOperation::Translate));
+ ops.operations().append(RotateTransformOperation::create(0.1, 0.2, 0.3, 200000.4, TransformOperation::Rotate3D));
+ ops.operations().append(ScaleTransformOperation::create(50.2, 100, -4, TransformOperation::Scale3D));
+ toWebTransformOperations(ops, box, &outOps);
+}
+
+TEST(AnimationTranslationUtilTest, filtersWork)
+{
+ FilterOperations ops;
+ WebFilterOperationsMock outOps;
+
+ EXPECT_CALL(outOps, appendSaturateFilter(0.5));
+ EXPECT_CALL(outOps, appendGrayscaleFilter(0.2f));
+ EXPECT_CALL(outOps, appendSepiaFilter(0.8f));
+ EXPECT_CALL(outOps, appendOpacityFilter(0.1f));
+
+ ops.operations().append(BasicColorMatrixFilterOperation::create(0.5, FilterOperation::SATURATE));
+ ops.operations().append(BasicColorMatrixFilterOperation::create(0.2, FilterOperation::GRAYSCALE));
+ ops.operations().append(BasicColorMatrixFilterOperation::create(0.8, FilterOperation::SEPIA));
+ ops.operations().append(BasicColorMatrixFilterOperation::create(0.1, FilterOperation::OPACITY));
+ toWebFilterOperations(ops, &outOps);
+}
+
+}
+
diff --git a/chromium/third_party/WebKit/Source/core/platform/animation/AnimationUtilities.h b/chromium/third_party/WebKit/Source/core/platform/animation/AnimationUtilities.h
deleted file mode 100644
index 4c86e770b43..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/animation/AnimationUtilities.h
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * Copyright (C) 2011 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef AnimationUtilities_h
-#define AnimationUtilities_h
-
-#include "core/platform/LayoutUnit.h"
-#include "core/platform/graphics/IntPoint.h"
-#include "wtf/MathExtras.h"
-
-namespace WebCore {
-
-inline int blend(int from, int to, double progress)
-{
- return lround(from + (to - from) * progress);
-}
-
-inline unsigned blend(unsigned from, unsigned to, double progress)
-{
- return clampTo<unsigned>(round(to > from ? from + (to - from) * progress : from - (from - to) * progress));
-}
-
-inline double blend(double from, double to, double progress)
-{
- return from + (to - from) * progress;
-}
-
-inline float blend(float from, float to, double progress)
-{
- return static_cast<float>(from + (to - from) * progress);
-}
-
-inline LayoutUnit blend(LayoutUnit from, LayoutUnit to, double progress)
-{
- return from + (to - from) * progress;
-}
-
-inline IntPoint blend(const IntPoint& from, const IntPoint& to, double progress)
-{
- return IntPoint(blend(from.x(), to.x(), progress), blend(from.y(), to.y(), progress));
-}
-
-// Calculates the accuracy for evaluating a timing function for an animation with the specified duration.
-inline double accuracyForDuration(double duration)
-{
- return 1.0 / (200.0 * duration);
-}
-
-} // namespace WebCore
-
-#endif // AnimationUtilities_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/animation/AnimationValue.h b/chromium/third_party/WebKit/Source/core/platform/animation/AnimationValue.h
index c6298dc2ac2..cba337cbf2e 100644
--- a/chromium/third_party/WebKit/Source/core/platform/animation/AnimationValue.h
+++ b/chromium/third_party/WebKit/Source/core/platform/animation/AnimationValue.h
@@ -28,8 +28,8 @@
#define AnimationValue_h
#include "core/platform/animation/TimingFunction.h"
-#include "core/platform/graphics/filters/FilterOperations.h"
-#include "core/platform/graphics/transforms/TransformOperations.h"
+#include "platform/graphics/filters/FilterOperations.h"
+#include "platform/transforms/TransformOperations.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefPtr.h"
diff --git a/chromium/third_party/WebKit/Source/core/platform/animation/CSSAnimationData.cpp b/chromium/third_party/WebKit/Source/core/platform/animation/CSSAnimationData.cpp
index 65f2fa6290b..277944ba1d3 100644
--- a/chromium/third_party/WebKit/Source/core/platform/animation/CSSAnimationData.cpp
+++ b/chromium/third_party/WebKit/Source/core/platform/animation/CSSAnimationData.cpp
@@ -104,39 +104,24 @@ CSSAnimationData::~CSSAnimationData()
{
}
-bool CSSAnimationData::animationsMatch(const CSSAnimationData* o, bool matchPlayStates) const
+bool CSSAnimationData::animationsMatchForStyleRecalc(const CSSAnimationData* o) const
{
if (!o)
return false;
- bool result = m_name == o->m_name
- && m_property == o->m_property
- && m_mode == o->m_mode
- && m_iterationCount == o->m_iterationCount
- && m_delay == o->m_delay
- && m_duration == o->m_duration
- && *(m_timingFunction.get()) == *(o->m_timingFunction.get())
- && m_direction == o->m_direction
- && m_fillMode == o->m_fillMode
- && m_delaySet == o->m_delaySet
- && m_directionSet == o->m_directionSet
- && m_durationSet == o->m_durationSet
- && m_fillModeSet == o->m_fillModeSet
- && m_iterationCountSet == o->m_iterationCountSet
- && m_nameSet == o->m_nameSet
- && m_propertySet == o->m_propertySet
- && m_timingFunctionSet == o->m_timingFunctionSet
- && m_isNone == o->m_isNone;
-
- if (!result)
- return false;
-
- return !matchPlayStates || (m_playState == o->m_playState && m_playStateSet == o->m_playStateSet);
+ return m_name == o->m_name
+ && m_playState == o->m_playState
+ && m_property == o->m_property
+ && m_mode == o->m_mode
+ && m_nameSet == o->m_nameSet
+ && m_playStateSet == o->m_playStateSet
+ && m_propertySet == o->m_propertySet
+ && m_isNone == o->m_isNone;
}
-const String& CSSAnimationData::initialAnimationName()
+const AtomicString& CSSAnimationData::initialAnimationName()
{
- DEFINE_STATIC_LOCAL(String, initialValue, ("none"));
+ DEFINE_STATIC_LOCAL(const AtomicString, initialValue, ("none"));
return initialValue;
}
diff --git a/chromium/third_party/WebKit/Source/core/platform/animation/CSSAnimationData.h b/chromium/third_party/WebKit/Source/core/platform/animation/CSSAnimationData.h
index 49c4bebed6a..7f6e79ab910 100644
--- a/chromium/third_party/WebKit/Source/core/platform/animation/CSSAnimationData.h
+++ b/chromium/third_party/WebKit/Source/core/platform/animation/CSSAnimationData.h
@@ -115,7 +115,7 @@ public:
enum { IterationCountInfinite = -1 };
double iterationCount() const { return m_iterationCount; }
- const String& name() const { return m_name; }
+ const AtomicString& name() const { return m_name; }
EAnimPlayState playState() const { return static_cast<EAnimPlayState>(m_playState); }
CSSPropertyID property() const { return m_property; }
TimingFunction* timingFunction() const { return m_timingFunction.get(); }
@@ -137,7 +137,7 @@ public:
CSSAnimationData& operator=(const CSSAnimationData& o);
// return true every CSSAnimationData in the chain (defined by m_next) match
- bool operator==(const CSSAnimationData& o) const { return animationsMatch(&o); }
+ bool operator==(const CSSAnimationData& o) const { return animationsMatchForStyleRecalc(&o); }
bool operator!=(const CSSAnimationData& o) const { return !(*this == o); }
bool fillsBackwards() const { return m_fillModeSet && (m_fillMode == AnimationFillModeBackwards || m_fillMode == AnimationFillModeBoth); }
@@ -147,8 +147,9 @@ private:
CSSAnimationData();
explicit CSSAnimationData(const CSSAnimationData&);
- // return true if all members of this class match (excluding m_next)
- bool animationsMatch(const CSSAnimationData*, bool matchPlayStates = true) const;
+ // Return whether this object matches another CSSAnimationData object for
+ // the purposes of style recalc. This excludes some properties.
+ bool animationsMatchForStyleRecalc(const CSSAnimationData*) const;
AtomicString m_name;
CSSPropertyID m_property;
@@ -180,7 +181,7 @@ public:
static double initialAnimationDuration() { return 0; }
static unsigned initialAnimationFillMode() { return AnimationFillModeNone; }
static double initialAnimationIterationCount() { return 1.0; }
- static const String& initialAnimationName();
+ static const AtomicString& initialAnimationName();
static EAnimPlayState initialAnimationPlayState() { return AnimPlayStatePlaying; }
static CSSPropertyID initialAnimationProperty() { return CSSPropertyInvalid; }
static const PassRefPtr<TimingFunction> initialAnimationTimingFunction() { return CubicBezierTimingFunction::preset(CubicBezierTimingFunction::Ease); }
diff --git a/chromium/third_party/WebKit/Source/core/platform/animation/TimingFunction.h b/chromium/third_party/WebKit/Source/core/platform/animation/TimingFunction.h
index 5ee850705ef..147d86b390b 100644
--- a/chromium/third_party/WebKit/Source/core/platform/animation/TimingFunction.h
+++ b/chromium/third_party/WebKit/Source/core/platform/animation/TimingFunction.h
@@ -26,15 +26,17 @@
#define TimingFunction_h
#include "RuntimeEnabledFeatures.h"
-#include "core/platform/animation/AnimationUtilities.h" // For blend()
-#include "core/platform/graphics/UnitBezier.h"
+#include "platform/animation/AnimationUtilities.h" // For blend()
+#include "platform/animation/UnitBezier.h"
#include "wtf/OwnPtr.h"
#include "wtf/PassOwnPtr.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefCounted.h"
+#include "wtf/StdLibExtras.h"
#include "wtf/Vector.h"
#include <algorithm>
+
namespace WebCore {
class TimingFunction : public RefCounted<TimingFunction> {
@@ -51,7 +53,6 @@ public:
// Evaluates the timing function at the given fraction. The accuracy parameter provides a hint as to the required
// accuracy and is not guaranteed.
virtual double evaluate(double fraction, double accuracy) const = 0;
- virtual bool operator==(const TimingFunction& other) const = 0;
protected:
TimingFunction(Type type)
@@ -74,16 +75,11 @@ public:
virtual double evaluate(double fraction, double) const
{
- ASSERT(RuntimeEnabledFeatures::webAnimationsEnabled() || (fraction >= 0 && fraction <= 1));
- RELEASE_ASSERT_WITH_MESSAGE(!RuntimeEnabledFeatures::webAnimationsEnabled() || (fraction >= 0 && fraction <= 1), "Web Animations not yet implemented: Timing function behavior outside the range [0, 1] is not yet specified");
+ ASSERT(RuntimeEnabledFeatures::webAnimationsCSSEnabled() || (fraction >= 0 && fraction <= 1));
+ ASSERT_WITH_MESSAGE(!RuntimeEnabledFeatures::webAnimationsCSSEnabled() || (fraction >= 0 && fraction <= 1), "Web Animations not yet implemented: Timing function behavior outside the range [0, 1] is not yet specified");
return fraction;
}
- virtual bool operator==(const TimingFunction& other) const
- {
- return other.type() == LinearFunction;
- }
-
private:
LinearTimingFunction()
: TimingFunction(LinearFunction)
@@ -91,6 +87,10 @@ private:
}
};
+
+// Forward declare so we can friend it below. Don't use in production code!
+class ChainedTimingFunctionTestHelper;
+
class CubicBezierTimingFunction : public TimingFunction {
public:
enum SubType {
@@ -111,22 +111,22 @@ public:
switch (subType) {
case Ease:
{
- static CubicBezierTimingFunction* ease = adoptRef(new CubicBezierTimingFunction(Ease, 0.25, 0.1, 0.25, 1.0)).leakRef();
+ DEFINE_STATIC_REF(CubicBezierTimingFunction, ease, (adoptRef(new CubicBezierTimingFunction(Ease, 0.25, 0.1, 0.25, 1.0))));
return ease;
}
case EaseIn:
{
- static CubicBezierTimingFunction* easeIn = adoptRef(new CubicBezierTimingFunction(EaseIn, 0.42, 0.0, 1.0, 1.0)).leakRef();
+ DEFINE_STATIC_REF(CubicBezierTimingFunction, easeIn, (adoptRef(new CubicBezierTimingFunction(EaseIn, 0.42, 0.0, 1.0, 1.0))));
return easeIn;
}
case EaseOut:
{
- static CubicBezierTimingFunction* easeOut = adoptRef(new CubicBezierTimingFunction(EaseOut, 0.0, 0.0, 0.58, 1.0)).leakRef();
+ DEFINE_STATIC_REF(CubicBezierTimingFunction, easeOut, (adoptRef(new CubicBezierTimingFunction(EaseOut, 0.0, 0.0, 0.58, 1.0))));
return easeOut;
}
case EaseInOut:
{
- static CubicBezierTimingFunction* easeInOut = adoptRef(new CubicBezierTimingFunction(EaseInOut, 0.42, 0.0, 0.58, 1.0)).leakRef();
+ DEFINE_STATIC_REF(CubicBezierTimingFunction, easeInOut, (adoptRef(new CubicBezierTimingFunction(EaseInOut, 0.42, 0.0, 0.58, 1.0))));
return easeInOut;
}
default:
@@ -139,25 +139,13 @@ public:
virtual double evaluate(double fraction, double accuracy) const
{
- ASSERT(RuntimeEnabledFeatures::webAnimationsEnabled() || (fraction >= 0 && fraction <= 1));
- RELEASE_ASSERT_WITH_MESSAGE(!RuntimeEnabledFeatures::webAnimationsEnabled() || (fraction >= 0 && fraction <= 1), "Web Animations not yet implemented: Timing function behavior outside the range [0, 1] is not yet specified");
+ ASSERT(RuntimeEnabledFeatures::webAnimationsCSSEnabled() || (fraction >= 0 && fraction <= 1));
+ ASSERT_WITH_MESSAGE(!RuntimeEnabledFeatures::webAnimationsCSSEnabled() || (fraction >= 0 && fraction <= 1), "Web Animations not yet implemented: Timing function behavior outside the range [0, 1] is not yet specified");
if (!m_bezier)
m_bezier = adoptPtr(new UnitBezier(m_x1, m_y1, m_x2, m_y2));
return m_bezier->solve(fraction, accuracy);
}
- virtual bool operator==(const TimingFunction& other) const
- {
- if (other.type() == CubicBezierFunction) {
- const CubicBezierTimingFunction* ctf = static_cast<const CubicBezierTimingFunction*>(&other);
- if (m_subType != Custom)
- return m_subType == ctf->m_subType;
-
- return m_x1 == ctf->m_x1 && m_y1 == ctf->m_y1 && m_x2 == ctf->m_x2 && m_y2 == ctf->m_y2;
- }
- return false;
- }
-
double x1() const { return m_x1; }
double y1() const { return m_y1; }
double x2() const { return m_x2; }
@@ -202,12 +190,12 @@ public:
switch (subType) {
case Start:
{
- static StepsTimingFunction* start = adoptRef(new StepsTimingFunction(Start, 1, true)).leakRef();
+ DEFINE_STATIC_REF(StepsTimingFunction, start, (adoptRef(new StepsTimingFunction(Start, 1, true))));
return start;
}
case End:
{
- static StepsTimingFunction* end = adoptRef(new StepsTimingFunction(End, 1, false)).leakRef();
+ DEFINE_STATIC_REF(StepsTimingFunction, end, (adoptRef(new StepsTimingFunction(End, 1, false))));
return end;
}
default:
@@ -221,22 +209,11 @@ public:
virtual double evaluate(double fraction, double) const
{
- ASSERT(RuntimeEnabledFeatures::webAnimationsEnabled() || (fraction >= 0 && fraction <= 1));
- RELEASE_ASSERT_WITH_MESSAGE(!RuntimeEnabledFeatures::webAnimationsEnabled() || (fraction >= 0 && fraction <= 1), "Web Animations not yet implemented: Timing function behavior outside the range [0, 1] is not yet specified");
+ ASSERT(RuntimeEnabledFeatures::webAnimationsCSSEnabled() || (fraction >= 0 && fraction <= 1));
+ ASSERT_WITH_MESSAGE(!RuntimeEnabledFeatures::webAnimationsCSSEnabled() || (fraction >= 0 && fraction <= 1), "Web Animations not yet implemented: Timing function behavior outside the range [0, 1] is not yet specified");
return std::min(1.0, (floor(m_steps * fraction) + m_stepAtStart) / m_steps);
}
- virtual bool operator==(const TimingFunction& other) const
- {
- if (other.type() == StepsFunction) {
- const StepsTimingFunction* stf = static_cast<const StepsTimingFunction*>(&other);
- if (m_subType != Custom)
- return m_subType == stf->m_subType;
- return m_steps == stf->m_steps && m_stepAtStart == stf->m_stepAtStart;
- }
- return false;
- }
-
int numberOfSteps() const { return m_steps; }
bool stepAtStart() const { return m_stepAtStart; }
@@ -271,25 +248,17 @@ public:
}
virtual double evaluate(double fraction, double accuracy) const
{
- RELEASE_ASSERT_WITH_MESSAGE(fraction >= 0 && fraction <= 1, "Web Animations not yet implemented: Timing function behavior outside the range [0, 1] is not yet specified");
+ ASSERT_WITH_MESSAGE(fraction >= 0 && fraction <= 1, "Web Animations not yet implemented: Timing function behavior outside the range [0, 1] is not yet specified");
ASSERT(!m_segments.isEmpty());
ASSERT(m_segments.last().max() == 1);
- const Segment* segment;
- for (size_t i = 0; i < m_segments.size(); ++i) {
- segment = &m_segments[i];
- if (fraction < segment->max())
- break;
+ size_t i = 0;
+ const Segment* segment = &m_segments[i++];
+ while (fraction >= segment->max() && i < m_segments.size()) {
+ segment = &m_segments[i++];
}
return segment->evaluate(fraction, accuracy);
}
- virtual bool operator==(const TimingFunction& other) const
- {
- // This class is not exposed to CSS, so this method is not required.
- ASSERT_NOT_REACHED();
- return false;
- }
-
private:
class Segment {
public:
@@ -297,7 +266,7 @@ private:
: m_min(min)
, m_max(max)
, m_timingFunction(timingFunction)
- { }
+ { ASSERT(timingFunction); }
double max() const { return m_max; }
double evaluate(double fraction, double accuracy) const
@@ -312,17 +281,50 @@ private:
double m_min;
double m_max;
RefPtr<TimingFunction> m_timingFunction;
+
+ // FIXME: Come up with a public API for the segments and remove this.
+ friend class CompositorAnimationsImpl;
+ friend class CompositorAnimations;
+
+ // Allow the compositor to reverse the timing function.
+ friend class CompositorAnimationsTimingFunctionReverser;
+
+ // Allow PrintTo/operator== of the segments. Can be removed once
+ // ChainedTimingFunction has a public API for segments.
+ friend class ChainedTimingFunctionTestHelper;
};
ChainedTimingFunction()
: TimingFunction(ChainedFunction)
{
- ASSERT(RuntimeEnabledFeatures::webAnimationsEnabled());
+ ASSERT(RuntimeEnabledFeatures::webAnimationsCSSEnabled());
}
Vector<Segment> m_segments;
+
+ // FIXME: Come up with a public API for the segments and remove this.
+ friend class CompositorAnimationsImpl;
+ friend class CompositorAnimations;
+
+ // Allow the compositor to reverse the timing function.
+ friend class CompositorAnimationsTimingFunctionReverser;
+
+ // Allow PrintTo/operator== of the segments. Can be removed once
+ // ChainedTimingFunction has a public API for segments.
+ friend class ChainedTimingFunctionTestHelper;
};
+#define DEFINE_TIMING_FUNCTION_TYPE_CASTS(typeName) \
+ DEFINE_TYPE_CASTS( \
+ typeName##TimingFunction, TimingFunction, value, \
+ value->type() == TimingFunction::typeName##Function, \
+ value.type() == TimingFunction::typeName##Function)
+
+DEFINE_TIMING_FUNCTION_TYPE_CASTS(Linear);
+DEFINE_TIMING_FUNCTION_TYPE_CASTS(CubicBezier);
+DEFINE_TIMING_FUNCTION_TYPE_CASTS(Steps);
+DEFINE_TIMING_FUNCTION_TYPE_CASTS(Chained);
+
} // namespace WebCore
#endif // TimingFunction_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/animation/TimingFunctionTestHelper.cpp b/chromium/third_party/WebKit/Source/core/platform/animation/TimingFunctionTestHelper.cpp
new file mode 100644
index 00000000000..f1eeb962374
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/platform/animation/TimingFunctionTestHelper.cpp
@@ -0,0 +1,253 @@
+/*
+ * Copyright (c) 2013, Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/platform/animation/TimingFunctionTestHelper.h"
+
+
+namespace WebCore {
+
+// This class exists so that ChainedTimingFunction only needs to friend one thing.
+class ChainedTimingFunctionTestHelper {
+ static void PrintTo(const ChainedTimingFunction& timingFunction, ::std::ostream* os)
+ {
+ // Forward declare the generic PrintTo function as ChainedTimingFunction needs to call it.
+ void PrintTo(const TimingFunction&, ::std::ostream*);
+
+ *os << "ChainedTimingFunction@" << &timingFunction << "(";
+ for (size_t i = 0; i < timingFunction.m_segments.size(); i++) {
+ ChainedTimingFunction::Segment segment = timingFunction.m_segments[i];
+ PrintTo(*(segment.m_timingFunction.get()), os);
+ *os << "[" << segment.m_min << " -> " << segment.m_max << "]";
+ if (i+1 != timingFunction.m_segments.size()) {
+ *os << ", ";
+ }
+ }
+ *os << ")";
+ }
+
+ static bool equals(const ChainedTimingFunction& lhs, const TimingFunction& rhs)
+ {
+ if (rhs.type() != TimingFunction::ChainedFunction)
+ return false;
+
+ if (&lhs == &rhs)
+ return true;
+
+ const ChainedTimingFunction& ctf = toChainedTimingFunction(rhs);
+ if (lhs.m_segments.size() != ctf.m_segments.size())
+ return false;
+
+ for (size_t i = 0; i < lhs.m_segments.size(); i++) {
+ if (!equals(lhs.m_segments[i], ctf.m_segments[i]))
+ return false;
+ }
+ return true;
+ }
+
+ static bool equals(const ChainedTimingFunction::Segment& lhs, const ChainedTimingFunction::Segment& rhs)
+ {
+ if (&lhs == &rhs)
+ return true;
+
+ if ((lhs.m_min != rhs.m_min) || (lhs.m_max != rhs.m_max))
+ return false;
+
+ if (lhs.m_timingFunction == rhs.m_timingFunction)
+ return true;
+
+ ASSERT(lhs.m_timingFunction);
+ ASSERT(rhs.m_timingFunction);
+
+ return (*(lhs.m_timingFunction.get())) == (*(rhs.m_timingFunction.get()));
+ }
+
+ friend void PrintTo(const ChainedTimingFunction&, ::std::ostream*);
+ friend bool operator==(const ChainedTimingFunction& lhs, const TimingFunction& rhs);
+};
+
+void PrintTo(const LinearTimingFunction& timingFunction, ::std::ostream* os)
+{
+ *os << "LinearTimingFunction@" << &timingFunction;
+}
+
+void PrintTo(const CubicBezierTimingFunction& timingFunction, ::std::ostream* os)
+{
+ *os << "CubicBezierTimingFunction@" << &timingFunction << "(";
+ switch (timingFunction.subType()) {
+ case CubicBezierTimingFunction::Ease:
+ *os << "Ease";
+ break;
+ case CubicBezierTimingFunction::EaseIn:
+ *os << "EaseIn";
+ break;
+ case CubicBezierTimingFunction::EaseOut:
+ *os << "EaseOut";
+ break;
+ case CubicBezierTimingFunction::EaseInOut:
+ *os << "EaseInOut";
+ break;
+ case CubicBezierTimingFunction::Custom:
+ *os << "Custom";
+ break;
+ default:
+ ASSERT_NOT_REACHED();
+ }
+ *os << ", " << timingFunction.x1();
+ *os << ", " << timingFunction.y1();
+ *os << ", " << timingFunction.x2();
+ *os << ", " << timingFunction.y2();
+ *os << ")";
+}
+
+void PrintTo(const StepsTimingFunction& timingFunction, ::std::ostream* os)
+{
+ *os << "StepsTimingFunction@" << &timingFunction << "(";
+ switch (timingFunction.subType()) {
+ case StepsTimingFunction::Start:
+ *os << "Start";
+ break;
+ case StepsTimingFunction::End:
+ *os << "End";
+ break;
+ case StepsTimingFunction::Custom:
+ *os << "Custom";
+ break;
+ default:
+ ASSERT_NOT_REACHED();
+ }
+ *os << ", " << timingFunction.numberOfSteps();
+ *os << ", " << (timingFunction.stepAtStart() ? "true" : "false");
+ *os << ")";
+}
+
+void PrintTo(const ChainedTimingFunction& timingFunction, ::std::ostream* os)
+{
+ ChainedTimingFunctionTestHelper::PrintTo(timingFunction, os);
+}
+
+// The generic PrintTo *must* come after the non-generic PrintTo otherwise it
+// will end up calling itself.
+void PrintTo(const TimingFunction& timingFunction, ::std::ostream* os)
+{
+ switch (timingFunction.type()) {
+ case TimingFunction::LinearFunction: {
+ const LinearTimingFunction& linear = toLinearTimingFunction(timingFunction);
+ PrintTo(linear, os);
+ return;
+ }
+ case TimingFunction::CubicBezierFunction: {
+ const CubicBezierTimingFunction& cubic = toCubicBezierTimingFunction(timingFunction);
+ PrintTo(cubic, os);
+ return;
+ }
+ case TimingFunction::StepsFunction: {
+ const StepsTimingFunction& step = toStepsTimingFunction(timingFunction);
+ PrintTo(step, os);
+ return;
+ }
+ case TimingFunction::ChainedFunction: {
+ const ChainedTimingFunction& chained = toChainedTimingFunction(timingFunction);
+ PrintTo(chained, os);
+ return;
+ }
+ default:
+ ASSERT_NOT_REACHED();
+ }
+}
+
+bool operator==(const LinearTimingFunction& lhs, const TimingFunction& rhs)
+{
+ return rhs.type() == TimingFunction::LinearFunction;
+}
+
+bool operator==(const CubicBezierTimingFunction& lhs, const TimingFunction& rhs)
+{
+ if (rhs.type() != TimingFunction::CubicBezierFunction)
+ return false;
+
+ const CubicBezierTimingFunction& ctf = toCubicBezierTimingFunction(rhs);
+ if ((lhs.subType() == CubicBezierTimingFunction::Custom) && (ctf.subType() == CubicBezierTimingFunction::Custom))
+ return (lhs.x1() == ctf.x1()) && (lhs.y1() == ctf.y1()) && (lhs.x2() == ctf.x2()) && (lhs.y2() == ctf.y2());
+
+ return lhs.subType() == ctf.subType();
+}
+
+bool operator==(const StepsTimingFunction& lhs, const TimingFunction& rhs)
+{
+ if (rhs.type() != TimingFunction::StepsFunction)
+ return false;
+
+ const StepsTimingFunction& stf = toStepsTimingFunction(rhs);
+ if ((lhs.subType() == StepsTimingFunction::Custom) && (stf.subType() == StepsTimingFunction::Custom))
+ return (lhs.numberOfSteps() == stf.numberOfSteps()) && (lhs.stepAtStart() == stf.stepAtStart());
+
+ return lhs.subType() == stf.subType();
+}
+
+bool operator==(const ChainedTimingFunction& lhs, const TimingFunction& rhs)
+{
+ return ChainedTimingFunctionTestHelper::equals(lhs, rhs);
+}
+
+// Like in the PrintTo case, the generic operator== *must* come after the
+// non-generic operator== otherwise it will end up calling itself.
+bool operator==(const TimingFunction& lhs, const TimingFunction& rhs)
+{
+ switch (lhs.type()) {
+ case TimingFunction::LinearFunction: {
+ const LinearTimingFunction& linear = toLinearTimingFunction(lhs);
+ return (linear == rhs);
+ }
+ case TimingFunction::CubicBezierFunction: {
+ const CubicBezierTimingFunction& cubic = toCubicBezierTimingFunction(lhs);
+ return (cubic == rhs);
+ }
+ case TimingFunction::StepsFunction: {
+ const StepsTimingFunction& step = toStepsTimingFunction(lhs);
+ return (step == rhs);
+ }
+ case TimingFunction::ChainedFunction: {
+ const ChainedTimingFunction& chained = toChainedTimingFunction(lhs);
+ return (chained == rhs);
+ }
+ default:
+ ASSERT_NOT_REACHED();
+ }
+ return false;
+}
+
+// No need to define specific operator!= as they can all come via this function.
+bool operator!=(const TimingFunction& lhs, const TimingFunction& rhs)
+{
+ return !(lhs == rhs);
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/animation/TimingFunctionTestHelper.h b/chromium/third_party/WebKit/Source/core/platform/animation/TimingFunctionTestHelper.h
new file mode 100644
index 00000000000..06eaf0604f6
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/platform/animation/TimingFunctionTestHelper.h
@@ -0,0 +1,63 @@
+/*
+ * Copyright (c) 2013, Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * Make testing with gtest and gmock nicer by adding pretty print and other
+ * helper functions.
+ */
+
+#ifndef TimingFunctionTestHelper_h
+#define TimingFunctionTestHelper_h
+
+#include "core/platform/animation/TimingFunction.h"
+
+#include <ostream> // NOLINT
+
+namespace WebCore {
+
+// PrintTo functions
+void PrintTo(const LinearTimingFunction&, ::std::ostream*);
+void PrintTo(const CubicBezierTimingFunction&, ::std::ostream*);
+void PrintTo(const StepsTimingFunction&, ::std::ostream*);
+void PrintTo(const ChainedTimingFunction&, ::std::ostream*);
+void PrintTo(const TimingFunction&, ::std::ostream*);
+
+// operator== functions
+bool operator==(const LinearTimingFunction&, const TimingFunction&);
+bool operator==(const CubicBezierTimingFunction&, const TimingFunction&);
+bool operator==(const StepsTimingFunction&, const TimingFunction&);
+bool operator==(const ChainedTimingFunction&, const TimingFunction&);
+
+bool operator==(const TimingFunction&, const TimingFunction&);
+bool operator!=(const TimingFunction&, const TimingFunction&);
+
+} // namespace WebCore
+
+#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/animation/TimingFunctionTestHelperTest.cpp b/chromium/third_party/WebKit/Source/core/platform/animation/TimingFunctionTestHelperTest.cpp
new file mode 100644
index 00000000000..01059a6c3ac
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/platform/animation/TimingFunctionTestHelperTest.cpp
@@ -0,0 +1,326 @@
+/*
+ * Copyright (c) 2013, Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+
+#include "core/platform/animation/TimingFunctionTestHelper.h"
+
+#include <gmock/gmock.h>
+#include <gtest/gtest.h>
+#include <sstream>
+#include <string>
+
+// FIXME: Remove once https://codereview.chromium.org/50603011/ lands.
+#define EXPECT_REFV_EQ(a, b) EXPECT_EQ(*(a.get()), *(b.get()))
+#define EXPECT_REFV_NE(a, b) EXPECT_NE(*(a.get()), *(b.get()))
+
+// Couple of macros to quickly assert a bunch of timing functions are not
+// equal.
+#define NE_STRINGIZE(x) NE_STRINGIZE2(x)
+#define NE_STRINGIZE2(x) #x
+#define NE_HELPER(v) \
+ Vector<std::pair<std::string, RefPtr<TimingFunction> > > v;
+#define NE_HELPER_APPEND(v, x) \
+ v.append(std::make_pair(std::string("Line " NE_STRINGIZE(__LINE__) ":" # x), x))
+#define NE_HELPER_LOOP(v) \
+ for (size_t i = 0; i != v.size(); ++i) { \
+ for (size_t j = 0; j != v.size(); ++j) { \
+ if (i == j) \
+ continue; \
+ EXPECT_REFV_NE(v[i].second, v[j].second) \
+ << v[i].first \
+ << " (" << ::testing::PrintToString(*v[i].second.get()) << ")" \
+ << " == " \
+ << v[j].first \
+ << " (" << ::testing::PrintToString(*v[j].second.get()) << ")" \
+ << "\n"; \
+ } \
+ }
+
+namespace {
+
+using namespace WebCore;
+
+class TimingFunctionTestHelperTest : public ::testing::Test {
+
+public:
+ // Make sure that the CubicBezierTimingFunction call goes via the generic
+ // TimingFunction PrintTo.
+ ::std::string PrintToString(RefPtr<CubicBezierTimingFunction> timing)
+ {
+ RefPtr<TimingFunction> generic = timing;
+ return PrintToString(generic.get());
+ }
+
+ ::std::string PrintToString(RefPtr<TimingFunction> timing)
+ {
+ return PrintToString(timing.get());
+ }
+
+ ::std::string PrintToString(const TimingFunction* timing)
+ {
+ return ::testing::PrintToString(*timing);
+ }
+};
+
+TEST_F(TimingFunctionTestHelperTest, LinearPrintTo)
+{
+ RefPtr<TimingFunction> linearTiming = LinearTimingFunction::create();
+ EXPECT_THAT(
+ PrintToString(linearTiming),
+ ::testing::MatchesRegex("LinearTimingFunction@.*"));
+}
+
+TEST_F(TimingFunctionTestHelperTest, CubicPrintTo)
+{
+ RefPtr<TimingFunction> cubicEaseTiming = CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseIn);
+ EXPECT_THAT(
+ PrintToString(cubicEaseTiming),
+ ::testing::MatchesRegex("CubicBezierTimingFunction@.*\\(EaseIn, 0.42, 0, 1, 1\\)"));
+
+ RefPtr<TimingFunction> cubicCustomTiming = CubicBezierTimingFunction::create(0.17, 0.67, 1, -1.73);
+ EXPECT_THAT(
+ PrintToString(cubicCustomTiming),
+ ::testing::MatchesRegex("CubicBezierTimingFunction@.*\\(Custom, 0.17, 0.67, 1, -1.73\\)"));
+}
+
+TEST_F(TimingFunctionTestHelperTest, StepPrintTo)
+{
+ RefPtr<TimingFunction> stepTimingStart = StepsTimingFunction::preset(StepsTimingFunction::Start);
+ EXPECT_THAT(
+ PrintToString(stepTimingStart),
+ ::testing::MatchesRegex("StepsTimingFunction@.*\\(Start, 1, true\\)"));
+
+ RefPtr<TimingFunction> stepTimingCustom = StepsTimingFunction::create(5, false);
+ EXPECT_THAT(
+ PrintToString(stepTimingCustom),
+ ::testing::MatchesRegex("StepsTimingFunction@.*\\(Custom, 5, false\\)"));
+}
+
+TEST_F(TimingFunctionTestHelperTest, ChainedPrintTo)
+{
+ RefPtr<TimingFunction> linearTiming = LinearTimingFunction::create();
+ RefPtr<ChainedTimingFunction> chainedLinearSingle = ChainedTimingFunction::create();
+ chainedLinearSingle->appendSegment(1.0, linearTiming.get());
+ EXPECT_THAT(
+ PrintToString(chainedLinearSingle),
+ ::testing::MatchesRegex(
+ "ChainedTimingFunction@.*\\("
+ "LinearTimingFunction@.*\\[0 -> 1\\]"
+ "\\)"));
+
+ RefPtr<TimingFunction> cubicCustomTiming = CubicBezierTimingFunction::create(1.0, 0.0, 1, -1);
+
+ RefPtr<ChainedTimingFunction> chainedMixed = ChainedTimingFunction::create();
+ chainedMixed->appendSegment(0.75, chainedLinearSingle.get());
+ chainedMixed->appendSegment(1.0, cubicCustomTiming.get());
+ EXPECT_THAT(
+ PrintToString(chainedMixed),
+ ::testing::MatchesRegex(
+ "ChainedTimingFunction@.*\\("
+ "ChainedTimingFunction@.*\\("
+ "LinearTimingFunction@.*\\[0 -> 1\\]"
+ "\\)\\[0 -> 0.75\\], "
+ "CubicBezierTimingFunction@.*\\(Custom, 1, 0, 1, -1\\)\\[0.75 -> 1\\]"
+ "\\)"));
+}
+
+TEST_F(TimingFunctionTestHelperTest, BaseOperatorEq)
+{
+ RefPtr<TimingFunction> linearTiming = LinearTimingFunction::create();
+ RefPtr<TimingFunction> cubicTiming1 = CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseIn);
+ RefPtr<TimingFunction> cubicTiming2 = CubicBezierTimingFunction::create(0.17, 0.67, 1, -1.73);
+ RefPtr<TimingFunction> stepsTiming1 = StepsTimingFunction::preset(StepsTimingFunction::End);
+ RefPtr<TimingFunction> stepsTiming2 = StepsTimingFunction::create(5, true);
+
+ RefPtr<ChainedTimingFunction> chainedTiming1 = ChainedTimingFunction::create();
+ chainedTiming1->appendSegment(1.0, linearTiming.get());
+
+ RefPtr<ChainedTimingFunction> chainedTiming2 = ChainedTimingFunction::create();
+ chainedTiming2->appendSegment(0.5, cubicTiming1.get());
+ chainedTiming2->appendSegment(1.0, cubicTiming2.get());
+
+ NE_HELPER(v);
+ NE_HELPER_APPEND(v, linearTiming);
+ NE_HELPER_APPEND(v, cubicTiming1);
+ NE_HELPER_APPEND(v, cubicTiming2);
+ NE_HELPER_APPEND(v, stepsTiming1);
+ NE_HELPER_APPEND(v, stepsTiming2);
+ NE_HELPER_APPEND(v, chainedTiming1);
+ NE_HELPER_APPEND(v, chainedTiming2);
+ NE_HELPER_LOOP(v);
+}
+
+TEST_F(TimingFunctionTestHelperTest, LinearOperatorEq)
+{
+ RefPtr<TimingFunction> linearTiming1 = LinearTimingFunction::create();
+ RefPtr<TimingFunction> linearTiming2 = LinearTimingFunction::create();
+ EXPECT_REFV_EQ(linearTiming1, linearTiming1);
+ EXPECT_REFV_EQ(linearTiming1, linearTiming2);
+}
+
+TEST_F(TimingFunctionTestHelperTest, CubicOperatorEq)
+{
+ RefPtr<TimingFunction> cubicEaseInTiming1 = CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseIn);
+ RefPtr<TimingFunction> cubicEaseInTiming2 = CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseIn);
+ EXPECT_REFV_EQ(cubicEaseInTiming1, cubicEaseInTiming1);
+ EXPECT_REFV_EQ(cubicEaseInTiming1, cubicEaseInTiming2);
+
+ RefPtr<TimingFunction> cubicEaseOutTiming1 = CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseOut);
+ RefPtr<TimingFunction> cubicEaseOutTiming2 = CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseOut);
+ EXPECT_REFV_EQ(cubicEaseOutTiming1, cubicEaseOutTiming2);
+
+ RefPtr<TimingFunction> cubicEaseInOutTiming1 = CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseInOut);
+ RefPtr<TimingFunction> cubicEaseInOutTiming2 = CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseInOut);
+ EXPECT_REFV_EQ(cubicEaseInOutTiming1, cubicEaseInOutTiming2);
+
+ RefPtr<TimingFunction> cubicCustomTiming1 = CubicBezierTimingFunction::create(0.17, 0.67, 1, -1.73);
+ RefPtr<TimingFunction> cubicCustomTiming2 = CubicBezierTimingFunction::create(0.17, 0.67, 1, -1.73);
+ EXPECT_REFV_EQ(cubicCustomTiming1, cubicCustomTiming2);
+
+ NE_HELPER(v);
+ NE_HELPER_APPEND(v, cubicEaseInTiming1);
+ NE_HELPER_APPEND(v, cubicEaseOutTiming1);
+ NE_HELPER_APPEND(v, cubicEaseInOutTiming1);
+ NE_HELPER_APPEND(v, cubicCustomTiming1);
+ NE_HELPER_LOOP(v);
+}
+
+TEST_F(TimingFunctionTestHelperTest, CubicOperatorEqReflectivity)
+{
+ RefPtr<TimingFunction> cubicA = CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseIn);
+ RefPtr<TimingFunction> cubicB = CubicBezierTimingFunction::create(0.42, 0.0, 1.0, 1.0);
+ EXPECT_REFV_NE(cubicA, cubicB);
+ EXPECT_REFV_NE(cubicB, cubicA);
+}
+
+TEST_F(TimingFunctionTestHelperTest, StepsOperatorEq)
+{
+ RefPtr<TimingFunction> stepsTimingStart1 = StepsTimingFunction::preset(StepsTimingFunction::Start);
+ RefPtr<TimingFunction> stepsTimingStart2 = StepsTimingFunction::preset(StepsTimingFunction::Start);
+ EXPECT_REFV_EQ(stepsTimingStart1, stepsTimingStart1);
+ EXPECT_REFV_EQ(stepsTimingStart1, stepsTimingStart2);
+
+ RefPtr<TimingFunction> stepsTimingEnd1 = StepsTimingFunction::preset(StepsTimingFunction::End);
+ RefPtr<TimingFunction> stepsTimingEnd2 = StepsTimingFunction::preset(StepsTimingFunction::End);
+ EXPECT_REFV_EQ(stepsTimingEnd1, stepsTimingEnd2);
+
+ RefPtr<TimingFunction> stepsTimingCustom1 = StepsTimingFunction::create(5, true);
+ RefPtr<TimingFunction> stepsTimingCustom2 = StepsTimingFunction::create(5, false);
+ RefPtr<TimingFunction> stepsTimingCustom3 = StepsTimingFunction::create(7, true);
+ RefPtr<TimingFunction> stepsTimingCustom4 = StepsTimingFunction::create(7, false);
+
+ EXPECT_REFV_EQ(stepsTimingCustom1, StepsTimingFunction::create(5, true));
+ EXPECT_REFV_EQ(stepsTimingCustom2, StepsTimingFunction::create(5, false));
+ EXPECT_REFV_EQ(stepsTimingCustom3, StepsTimingFunction::create(7, true));
+ EXPECT_REFV_EQ(stepsTimingCustom4, StepsTimingFunction::create(7, false));
+
+ NE_HELPER(v);
+ NE_HELPER_APPEND(v, stepsTimingStart1);
+ NE_HELPER_APPEND(v, stepsTimingEnd1);
+ NE_HELPER_APPEND(v, stepsTimingCustom1);
+ NE_HELPER_APPEND(v, stepsTimingCustom2);
+ NE_HELPER_APPEND(v, stepsTimingCustom3);
+ NE_HELPER_APPEND(v, stepsTimingCustom4);
+ NE_HELPER_LOOP(v);
+}
+
+TEST_F(TimingFunctionTestHelperTest, StepsOperatorEqReflectivity)
+{
+ RefPtr<TimingFunction> stepsA = StepsTimingFunction::preset(StepsTimingFunction::Start);
+ RefPtr<TimingFunction> stepsB = StepsTimingFunction::create(1, true);
+ EXPECT_REFV_NE(stepsA, stepsB);
+ EXPECT_REFV_NE(stepsB, stepsA);
+}
+
+TEST_F(TimingFunctionTestHelperTest, ChainedEq)
+{
+ // Single item in chain
+ RefPtr<TimingFunction> cubicTiming1 = CubicBezierTimingFunction::create(0.25, 0.1, 0.25, 1.0);
+ RefPtr<TimingFunction> cubicTiming2 = CubicBezierTimingFunction::create(0.25, 0.1, 0.25, 1.0);
+ RefPtr<TimingFunction> cubicTiming3 = CubicBezierTimingFunction::preset(CubicBezierTimingFunction::EaseOut);
+
+ RefPtr<ChainedTimingFunction> chainedSingleCubic1 = ChainedTimingFunction::create();
+ chainedSingleCubic1->appendSegment(1.0, cubicTiming1.get());
+ EXPECT_REFV_EQ(chainedSingleCubic1, chainedSingleCubic1);
+
+ RefPtr<ChainedTimingFunction> chainedSingleCubic2 = ChainedTimingFunction::create();
+ chainedSingleCubic2->appendSegment(1.0, cubicTiming1.get()); // Same inner timing function
+ EXPECT_REFV_EQ(chainedSingleCubic1, chainedSingleCubic2);
+
+ RefPtr<ChainedTimingFunction> chainedSingleCubic3 = ChainedTimingFunction::create();
+ chainedSingleCubic3->appendSegment(1.0, cubicTiming2.get()); // == inner timing function
+ EXPECT_REFV_EQ(chainedSingleCubic1, chainedSingleCubic3);
+
+ RefPtr<ChainedTimingFunction> chainedSingleCubic4 = ChainedTimingFunction::create();
+ chainedSingleCubic4->appendSegment(0.5, cubicTiming1.get()); // Different offset
+ EXPECT_REFV_NE(chainedSingleCubic1, chainedSingleCubic4);
+ EXPECT_REFV_NE(chainedSingleCubic3, chainedSingleCubic4);
+
+ RefPtr<ChainedTimingFunction> chainedSingleCubic5 = ChainedTimingFunction::create();
+ chainedSingleCubic5->appendSegment(1.0, cubicTiming3.get()); // != inner timing function (same type)
+ EXPECT_REFV_NE(chainedSingleCubic1, chainedSingleCubic5);
+ EXPECT_REFV_NE(chainedSingleCubic2, chainedSingleCubic5);
+ EXPECT_REFV_NE(chainedSingleCubic3, chainedSingleCubic5);
+ EXPECT_REFV_NE(chainedSingleCubic4, chainedSingleCubic5);
+
+ RefPtr<TimingFunction> linearTiming1 = LinearTimingFunction::create();
+ RefPtr<ChainedTimingFunction> chainedSingleLinear1 = ChainedTimingFunction::create();
+ chainedSingleLinear1->appendSegment(1.0, linearTiming1.get()); // != inner timing function (different type)
+ EXPECT_REFV_NE(chainedSingleLinear1, chainedSingleCubic1);
+ EXPECT_REFV_NE(chainedSingleLinear1, chainedSingleCubic2);
+ EXPECT_REFV_NE(chainedSingleLinear1, chainedSingleCubic3);
+ EXPECT_REFV_NE(chainedSingleLinear1, chainedSingleCubic4);
+
+ // Multiple items in chain
+ RefPtr<ChainedTimingFunction> chainedMixed1 = ChainedTimingFunction::create();
+ chainedMixed1->appendSegment(0.25, chainedSingleLinear1.get());
+ chainedMixed1->appendSegment(1.0, cubicTiming1.get());
+
+ RefPtr<ChainedTimingFunction> chainedMixed2 = ChainedTimingFunction::create();
+ chainedMixed2->appendSegment(0.25, chainedSingleLinear1.get());
+ chainedMixed2->appendSegment(1.0, cubicTiming1.get());
+
+ RefPtr<ChainedTimingFunction> chainedMixed3 = ChainedTimingFunction::create();
+ chainedMixed3->appendSegment(0.25, chainedSingleLinear1.get());
+ chainedMixed3->appendSegment(1.0, cubicTiming2.get());
+
+ EXPECT_REFV_EQ(chainedMixed1, chainedMixed2);
+ EXPECT_REFV_EQ(chainedMixed1, chainedMixed3);
+ EXPECT_REFV_NE(chainedMixed1, chainedSingleCubic1);
+ EXPECT_REFV_NE(chainedMixed1, chainedSingleLinear1);
+
+ RefPtr<ChainedTimingFunction> chainedMixed4 = ChainedTimingFunction::create();
+ chainedMixed4->appendSegment(0.20, chainedSingleLinear1.get()); // Different offset
+ chainedMixed4->appendSegment(1.0, cubicTiming1.get());
+ EXPECT_REFV_NE(chainedMixed1, chainedMixed4);
+}
+
+} // namespace
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/AudioArray.h b/chromium/third_party/WebKit/Source/core/platform/audio/AudioArray.h
deleted file mode 100644
index f611a2b10ab..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/AudioArray.h
+++ /dev/null
@@ -1,162 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef AudioArray_h
-#define AudioArray_h
-
-#include <string.h>
-#include "wtf/FastMalloc.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-template<typename T>
-class AudioArray {
-public:
- AudioArray() : m_allocation(0), m_alignedData(0), m_size(0) { }
- explicit AudioArray(size_t n) : m_allocation(0), m_alignedData(0), m_size(0)
- {
- allocate(n);
- }
-
- ~AudioArray()
- {
- fastFree(m_allocation);
- }
-
- // It's OK to call allocate() multiple times, but data will *not* be copied from an initial allocation
- // if re-allocated. Allocations are zero-initialized.
- void allocate(size_t n)
- {
- // Although n is a size_t, its true limit is max unsigned because we use unsigned in zeroRange()
- // and copyToRange(). Also check for integer overflow.
- if (n > std::numeric_limits<unsigned>::max() / sizeof(T))
- CRASH();
-
- unsigned initialSize = sizeof(T) * n;
-
-#if USE(WEBAUDIO_FFMPEG) || USE(WEBAUDIO_OPENMAX_DL_FFT)
- const size_t alignment = 32;
-#else
- const size_t alignment = 16;
-#endif
-
- if (m_allocation)
- fastFree(m_allocation);
-
- bool isAllocationGood = false;
-
- while (!isAllocationGood) {
- // Initially we try to allocate the exact size, but if it's not aligned
- // then we'll have to reallocate and from then on allocate extra.
- static size_t extraAllocationBytes = 0;
-
- // Again, check for integer overflow.
- if (initialSize + extraAllocationBytes < initialSize)
- CRASH();
-
- T* allocation = static_cast<T*>(fastMalloc(initialSize + extraAllocationBytes));
- if (!allocation)
- CRASH();
- T* alignedData = alignedAddress(allocation, alignment);
-
- if (alignedData == allocation || extraAllocationBytes == alignment) {
- m_allocation = allocation;
- m_alignedData = alignedData;
- m_size = n;
- isAllocationGood = true;
- zero();
- } else {
- extraAllocationBytes = alignment; // always allocate extra after the first alignment failure.
- fastFree(allocation);
- }
- }
- }
-
- T* data() { return m_alignedData; }
- const T* data() const { return m_alignedData; }
- size_t size() const { return m_size; }
-
- T& at(size_t i)
- {
- // Note that although it is a size_t, m_size is now guaranteed to be
- // no greater than max unsigned. This guarantee is enforced in allocate().
- ASSERT_WITH_SECURITY_IMPLICATION(i < size());
- return data()[i];
- }
-
- T& operator[](size_t i) { return at(i); }
-
- void zero()
- {
- // This multiplication is made safe by the check in allocate().
- memset(this->data(), 0, sizeof(T) * this->size());
- }
-
- void zeroRange(unsigned start, unsigned end)
- {
- bool isSafe = (start <= end) && (end <= this->size());
- ASSERT(isSafe);
- if (!isSafe)
- return;
-
- // This expression cannot overflow because end - start cannot be
- // greater than m_size, which is safe due to the check in allocate().
- memset(this->data() + start, 0, sizeof(T) * (end - start));
- }
-
- void copyToRange(const T* sourceData, unsigned start, unsigned end)
- {
- bool isSafe = (start <= end) && (end <= this->size());
- ASSERT(isSafe);
- if (!isSafe)
- return;
-
- // This expression cannot overflow because end - start cannot be
- // greater than m_size, which is safe due to the check in allocate().
- memcpy(this->data() + start, sourceData, sizeof(T) * (end - start));
- }
-
-private:
- static T* alignedAddress(T* address, intptr_t alignment)
- {
- intptr_t value = reinterpret_cast<intptr_t>(address);
- return reinterpret_cast<T*>((value + alignment - 1) & ~(alignment - 1));
- }
-
- T* m_allocation;
- T* m_alignedData;
- size_t m_size;
-};
-
-typedef AudioArray<float> AudioFloatArray;
-typedef AudioArray<double> AudioDoubleArray;
-
-} // WebCore
-
-#endif // AudioArray_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/AudioBus.cpp b/chromium/third_party/WebKit/Source/core/platform/audio/AudioBus.cpp
deleted file mode 100644
index dd8acffeef4..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/AudioBus.cpp
+++ /dev/null
@@ -1,638 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#if ENABLE(WEB_AUDIO)
-
-#include "core/platform/audio/AudioBus.h"
-
-#include "core/platform/audio/DenormalDisabler.h"
-
-#include <assert.h>
-#include <math.h>
-#include <algorithm>
-#include "core/platform/audio/SincResampler.h"
-#include "core/platform/audio/VectorMath.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/PassOwnPtr.h"
-
-namespace WebCore {
-
-using namespace VectorMath;
-
-const unsigned MaxBusChannels = 32;
-
-PassRefPtr<AudioBus> AudioBus::create(unsigned numberOfChannels, size_t length, bool allocate)
-{
- ASSERT(numberOfChannels <= MaxBusChannels);
- if (numberOfChannels > MaxBusChannels)
- return 0;
-
- return adoptRef(new AudioBus(numberOfChannels, length, allocate));
-}
-
-AudioBus::AudioBus(unsigned numberOfChannels, size_t length, bool allocate)
- : m_length(length)
- , m_busGain(1)
- , m_isFirstTime(true)
- , m_sampleRate(0)
-{
- m_channels.reserveInitialCapacity(numberOfChannels);
-
- for (unsigned i = 0; i < numberOfChannels; ++i) {
- PassOwnPtr<AudioChannel> channel = allocate ? adoptPtr(new AudioChannel(length)) : adoptPtr(new AudioChannel(0, length));
- m_channels.append(channel);
- }
-
- m_layout = LayoutCanonical; // for now this is the only layout we define
-}
-
-void AudioBus::setChannelMemory(unsigned channelIndex, float* storage, size_t length)
-{
- if (channelIndex < m_channels.size()) {
- channel(channelIndex)->set(storage, length);
- m_length = length; // FIXME: verify that this length matches all the other channel lengths
- }
-}
-
-void AudioBus::resizeSmaller(size_t newLength)
-{
- ASSERT(newLength <= m_length);
- if (newLength <= m_length)
- m_length = newLength;
-
- for (unsigned i = 0; i < m_channels.size(); ++i)
- m_channels[i]->resizeSmaller(newLength);
-}
-
-void AudioBus::zero()
-{
- for (unsigned i = 0; i < m_channels.size(); ++i)
- m_channels[i]->zero();
-}
-
-AudioChannel* AudioBus::channelByType(unsigned channelType)
-{
- // For now we only support canonical channel layouts...
- if (m_layout != LayoutCanonical)
- return 0;
-
- switch (numberOfChannels()) {
- case 1: // mono
- if (channelType == ChannelMono || channelType == ChannelLeft)
- return channel(0);
- return 0;
-
- case 2: // stereo
- switch (channelType) {
- case ChannelLeft: return channel(0);
- case ChannelRight: return channel(1);
- default: return 0;
- }
-
- case 4: // quad
- switch (channelType) {
- case ChannelLeft: return channel(0);
- case ChannelRight: return channel(1);
- case ChannelSurroundLeft: return channel(2);
- case ChannelSurroundRight: return channel(3);
- default: return 0;
- }
-
- case 5: // 5.0
- switch (channelType) {
- case ChannelLeft: return channel(0);
- case ChannelRight: return channel(1);
- case ChannelCenter: return channel(2);
- case ChannelSurroundLeft: return channel(3);
- case ChannelSurroundRight: return channel(4);
- default: return 0;
- }
-
- case 6: // 5.1
- switch (channelType) {
- case ChannelLeft: return channel(0);
- case ChannelRight: return channel(1);
- case ChannelCenter: return channel(2);
- case ChannelLFE: return channel(3);
- case ChannelSurroundLeft: return channel(4);
- case ChannelSurroundRight: return channel(5);
- default: return 0;
- }
- }
-
- ASSERT_NOT_REACHED();
- return 0;
-}
-
-const AudioChannel* AudioBus::channelByType(unsigned type) const
-{
- return const_cast<AudioBus*>(this)->channelByType(type);
-}
-
-// Returns true if the channel count and frame-size match.
-bool AudioBus::topologyMatches(const AudioBus& bus) const
-{
- if (numberOfChannels() != bus.numberOfChannels())
- return false; // channel mismatch
-
- // Make sure source bus has enough frames.
- if (length() > bus.length())
- return false; // frame-size mismatch
-
- return true;
-}
-
-PassRefPtr<AudioBus> AudioBus::createBufferFromRange(const AudioBus* sourceBuffer, unsigned startFrame, unsigned endFrame)
-{
- size_t numberOfSourceFrames = sourceBuffer->length();
- unsigned numberOfChannels = sourceBuffer->numberOfChannels();
-
- // Sanity checking
- bool isRangeSafe = startFrame < endFrame && endFrame <= numberOfSourceFrames;
- ASSERT(isRangeSafe);
- if (!isRangeSafe)
- return 0;
-
- size_t rangeLength = endFrame - startFrame;
-
- RefPtr<AudioBus> audioBus = create(numberOfChannels, rangeLength);
- audioBus->setSampleRate(sourceBuffer->sampleRate());
-
- for (unsigned i = 0; i < numberOfChannels; ++i)
- audioBus->channel(i)->copyFromRange(sourceBuffer->channel(i), startFrame, endFrame);
-
- return audioBus;
-}
-
-float AudioBus::maxAbsValue() const
-{
- float max = 0.0f;
- for (unsigned i = 0; i < numberOfChannels(); ++i) {
- const AudioChannel* channel = this->channel(i);
- max = std::max(max, channel->maxAbsValue());
- }
-
- return max;
-}
-
-void AudioBus::normalize()
-{
- float max = maxAbsValue();
- if (max)
- scale(1.0f / max);
-}
-
-void AudioBus::scale(float scale)
-{
- for (unsigned i = 0; i < numberOfChannels(); ++i)
- channel(i)->scale(scale);
-}
-
-void AudioBus::copyFrom(const AudioBus& sourceBus, ChannelInterpretation channelInterpretation)
-{
- if (&sourceBus == this)
- return;
-
- unsigned numberOfSourceChannels = sourceBus.numberOfChannels();
- unsigned numberOfDestinationChannels = numberOfChannels();
-
- if (numberOfDestinationChannels == numberOfSourceChannels) {
- for (unsigned i = 0; i < numberOfSourceChannels; ++i)
- channel(i)->copyFrom(sourceBus.channel(i));
- } else {
- switch (channelInterpretation) {
- case Speakers:
- speakersCopyFrom(sourceBus);
- break;
- case Discrete:
- discreteCopyFrom(sourceBus);
- break;
- default:
- ASSERT_NOT_REACHED();
- }
- }
-}
-
-void AudioBus::sumFrom(const AudioBus& sourceBus, ChannelInterpretation channelInterpretation)
-{
- if (&sourceBus == this)
- return;
-
- unsigned numberOfSourceChannels = sourceBus.numberOfChannels();
- unsigned numberOfDestinationChannels = numberOfChannels();
-
- if (numberOfDestinationChannels == numberOfSourceChannels) {
- for (unsigned i = 0; i < numberOfSourceChannels; ++i)
- channel(i)->sumFrom(sourceBus.channel(i));
- } else {
- switch (channelInterpretation) {
- case Speakers:
- speakersSumFrom(sourceBus);
- break;
- case Discrete:
- discreteSumFrom(sourceBus);
- break;
- default:
- ASSERT_NOT_REACHED();
- }
- }
-}
-
-void AudioBus::speakersCopyFrom(const AudioBus& sourceBus)
-{
- // FIXME: Implement down mixing 5.1 to stereo.
- // https://bugs.webkit.org/show_bug.cgi?id=79192
-
- unsigned numberOfSourceChannels = sourceBus.numberOfChannels();
- unsigned numberOfDestinationChannels = numberOfChannels();
-
- if (numberOfDestinationChannels == 2 && numberOfSourceChannels == 1) {
- // Handle mono -> stereo case (for now simply copy mono channel into both left and right)
- // FIXME: Really we should apply an equal-power scaling factor here, since we're effectively panning center...
- const AudioChannel* sourceChannel = sourceBus.channel(0);
- channel(0)->copyFrom(sourceChannel);
- channel(1)->copyFrom(sourceChannel);
- } else if (numberOfDestinationChannels == 1 && numberOfSourceChannels == 2) {
- // Handle stereo -> mono case. output = 0.5 * (input.L + input.R).
- AudioBus& sourceBusSafe = const_cast<AudioBus&>(sourceBus);
-
- const float* sourceL = sourceBusSafe.channelByType(ChannelLeft)->data();
- const float* sourceR = sourceBusSafe.channelByType(ChannelRight)->data();
-
- float* destination = channelByType(ChannelLeft)->mutableData();
- vadd(sourceL, 1, sourceR, 1, destination, 1, length());
- float scale = 0.5;
- vsmul(destination, 1, &scale, destination, 1, length());
- } else if (numberOfDestinationChannels == 6 && numberOfSourceChannels == 1) {
- // Handle mono -> 5.1 case, copy mono channel to center.
- channel(2)->copyFrom(sourceBus.channel(0));
- channel(0)->zero();
- channel(1)->zero();
- channel(3)->zero();
- channel(4)->zero();
- channel(5)->zero();
- } else if (numberOfDestinationChannels == 1 && numberOfSourceChannels == 6) {
- // Handle 5.1 -> mono case.
- zero();
- speakersSumFrom5_1_ToMono(sourceBus);
- } else {
- // Fallback for unknown combinations.
- discreteCopyFrom(sourceBus);
- }
-}
-
-void AudioBus::speakersSumFrom(const AudioBus& sourceBus)
-{
- // FIXME: Implement down mixing 5.1 to stereo.
- // https://bugs.webkit.org/show_bug.cgi?id=79192
-
- unsigned numberOfSourceChannels = sourceBus.numberOfChannels();
- unsigned numberOfDestinationChannels = numberOfChannels();
-
- if (numberOfDestinationChannels == 2 && numberOfSourceChannels == 1) {
- // Handle mono -> stereo case (summing mono channel into both left and right).
- const AudioChannel* sourceChannel = sourceBus.channel(0);
- channel(0)->sumFrom(sourceChannel);
- channel(1)->sumFrom(sourceChannel);
- } else if (numberOfDestinationChannels == 1 && numberOfSourceChannels == 2) {
- // Handle stereo -> mono case. output += 0.5 * (input.L + input.R).
- AudioBus& sourceBusSafe = const_cast<AudioBus&>(sourceBus);
-
- const float* sourceL = sourceBusSafe.channelByType(ChannelLeft)->data();
- const float* sourceR = sourceBusSafe.channelByType(ChannelRight)->data();
-
- float* destination = channelByType(ChannelLeft)->mutableData();
- float scale = 0.5;
- vsma(sourceL, 1, &scale, destination, 1, length());
- vsma(sourceR, 1, &scale, destination, 1, length());
- } else if (numberOfDestinationChannels == 6 && numberOfSourceChannels == 1) {
- // Handle mono -> 5.1 case, sum mono channel into center.
- channel(2)->sumFrom(sourceBus.channel(0));
- } else if (numberOfDestinationChannels == 1 && numberOfSourceChannels == 6) {
- // Handle 5.1 -> mono case.
- speakersSumFrom5_1_ToMono(sourceBus);
- } else {
- // Fallback for unknown combinations.
- discreteSumFrom(sourceBus);
- }
-}
-
-void AudioBus::speakersSumFrom5_1_ToMono(const AudioBus& sourceBus)
-{
- AudioBus& sourceBusSafe = const_cast<AudioBus&>(sourceBus);
-
- const float* sourceL = sourceBusSafe.channelByType(ChannelLeft)->data();
- const float* sourceR = sourceBusSafe.channelByType(ChannelRight)->data();
- const float* sourceC = sourceBusSafe.channelByType(ChannelCenter)->data();
- const float* sourceSL = sourceBusSafe.channelByType(ChannelSurroundLeft)->data();
- const float* sourceSR = sourceBusSafe.channelByType(ChannelSurroundRight)->data();
-
- float* destination = channelByType(ChannelLeft)->mutableData();
-
- AudioFloatArray temp(length());
- float* tempData = temp.data();
-
- // Sum in L and R.
- vadd(sourceL, 1, sourceR, 1, tempData, 1, length());
- float scale = 0.7071;
- vsmul(tempData, 1, &scale, tempData, 1, length());
- vadd(tempData, 1, destination, 1, destination, 1, length());
-
- // Sum in SL and SR.
- vadd(sourceSL, 1, sourceSR, 1, tempData, 1, length());
- scale = 0.5;
- vsmul(tempData, 1, &scale, tempData, 1, length());
- vadd(tempData, 1, destination, 1, destination, 1, length());
-
- // Sum in center.
- vadd(sourceC, 1, destination, 1, destination, 1, length());
-}
-
-void AudioBus::discreteCopyFrom(const AudioBus& sourceBus)
-{
- unsigned numberOfSourceChannels = sourceBus.numberOfChannels();
- unsigned numberOfDestinationChannels = numberOfChannels();
-
- if (numberOfDestinationChannels < numberOfSourceChannels) {
- // Down-mix by copying channels and dropping the remaining.
- for (unsigned i = 0; i < numberOfDestinationChannels; ++i)
- channel(i)->copyFrom(sourceBus.channel(i));
- } else if (numberOfDestinationChannels > numberOfSourceChannels) {
- // Up-mix by copying as many channels as we have, then zeroing remaining channels.
- for (unsigned i = 0; i < numberOfSourceChannels; ++i)
- channel(i)->copyFrom(sourceBus.channel(i));
- for (unsigned i = numberOfSourceChannels; i < numberOfDestinationChannels; ++i)
- channel(i)->zero();
- }
-}
-
-void AudioBus::discreteSumFrom(const AudioBus& sourceBus)
-{
- unsigned numberOfSourceChannels = sourceBus.numberOfChannels();
- unsigned numberOfDestinationChannels = numberOfChannels();
-
- if (numberOfDestinationChannels < numberOfSourceChannels) {
- // Down-mix by summing channels and dropping the remaining.
- for (unsigned i = 0; i < numberOfDestinationChannels; ++i)
- channel(i)->sumFrom(sourceBus.channel(i));
- } else if (numberOfDestinationChannels > numberOfSourceChannels) {
- // Up-mix by summing as many channels as we have.
- for (unsigned i = 0; i < numberOfSourceChannels; ++i)
- channel(i)->sumFrom(sourceBus.channel(i));
- }
-}
-
-void AudioBus::copyWithGainFrom(const AudioBus &sourceBus, float* lastMixGain, float targetGain)
-{
- if (!topologyMatches(sourceBus)) {
- ASSERT_NOT_REACHED();
- zero();
- return;
- }
-
- if (sourceBus.isSilent()) {
- zero();
- return;
- }
-
- unsigned numberOfChannels = this->numberOfChannels();
- ASSERT(numberOfChannels <= MaxBusChannels);
- if (numberOfChannels > MaxBusChannels)
- return;
-
- // If it is copying from the same bus and no need to change gain, just return.
- if (this == &sourceBus && *lastMixGain == targetGain && targetGain == 1)
- return;
-
- AudioBus& sourceBusSafe = const_cast<AudioBus&>(sourceBus);
- const float* sources[MaxBusChannels];
- float* destinations[MaxBusChannels];
-
- for (unsigned i = 0; i < numberOfChannels; ++i) {
- sources[i] = sourceBusSafe.channel(i)->data();
- destinations[i] = channel(i)->mutableData();
- }
-
- // We don't want to suddenly change the gain from mixing one time slice to the next,
- // so we "de-zipper" by slowly changing the gain each sample-frame until we've achieved the target gain.
-
- // Take master bus gain into account as well as the targetGain.
- float totalDesiredGain = static_cast<float>(m_busGain * targetGain);
-
- // First time, snap directly to totalDesiredGain.
- float gain = static_cast<float>(m_isFirstTime ? totalDesiredGain : *lastMixGain);
- m_isFirstTime = false;
-
- const float DezipperRate = 0.005f;
- unsigned framesToProcess = length();
-
- // If the gain is within epsilon of totalDesiredGain, we can skip dezippering.
- // FIXME: this value may need tweaking.
- const float epsilon = 0.001f;
- float gainDiff = fabs(totalDesiredGain - gain);
-
- // Number of frames to de-zipper before we are close enough to the target gain.
- // FIXME: framesToDezipper could be smaller when target gain is close enough within this process loop.
- unsigned framesToDezipper = (gainDiff < epsilon) ? 0 : framesToProcess;
-
- if (framesToDezipper) {
- if (!m_dezipperGainValues.get() || m_dezipperGainValues->size() < framesToDezipper)
- m_dezipperGainValues = adoptPtr(new AudioFloatArray(framesToDezipper));
-
- float* gainValues = m_dezipperGainValues->data();
- for (unsigned i = 0; i < framesToDezipper; ++i) {
- gain += (totalDesiredGain - gain) * DezipperRate;
-
- // FIXME: If we are clever enough in calculating the framesToDezipper value, we can probably get
- // rid of this DenormalDisabler::flushDenormalFloatToZero() call.
- gain = DenormalDisabler::flushDenormalFloatToZero(gain);
- *gainValues++ = gain;
- }
-
- for (unsigned channelIndex = 0; channelIndex < numberOfChannels; ++channelIndex) {
- vmul(sources[channelIndex], 1, m_dezipperGainValues->data(), 1, destinations[channelIndex], 1, framesToDezipper);
- sources[channelIndex] += framesToDezipper;
- destinations[channelIndex] += framesToDezipper;
- }
- } else
- gain = totalDesiredGain;
-
- // Apply constant gain after de-zippering has converged on target gain.
- if (framesToDezipper < framesToProcess) {
- for (unsigned channelIndex = 0; channelIndex < numberOfChannels; ++channelIndex)
- vsmul(sources[channelIndex], 1, &gain, destinations[channelIndex], 1, framesToProcess - framesToDezipper);
- }
-
- // Save the target gain as the starting point for next time around.
- *lastMixGain = gain;
-}
-
-void AudioBus::copyWithSampleAccurateGainValuesFrom(const AudioBus &sourceBus, float* gainValues, unsigned numberOfGainValues)
-{
- // Make sure we're processing from the same type of bus.
- // We *are* able to process from mono -> stereo
- if (sourceBus.numberOfChannels() != 1 && !topologyMatches(sourceBus)) {
- ASSERT_NOT_REACHED();
- return;
- }
-
- if (!gainValues || numberOfGainValues > sourceBus.length()) {
- ASSERT_NOT_REACHED();
- return;
- }
-
- if (sourceBus.length() == numberOfGainValues && sourceBus.length() == length() && sourceBus.isSilent()) {
- zero();
- return;
- }
-
- // We handle both the 1 -> N and N -> N case here.
- const float* source = sourceBus.channel(0)->data();
- for (unsigned channelIndex = 0; channelIndex < numberOfChannels(); ++channelIndex) {
- if (sourceBus.numberOfChannels() == numberOfChannels())
- source = sourceBus.channel(channelIndex)->data();
- float* destination = channel(channelIndex)->mutableData();
- vmul(source, 1, gainValues, 1, destination, 1, numberOfGainValues);
- }
-}
-
-PassRefPtr<AudioBus> AudioBus::createBySampleRateConverting(const AudioBus* sourceBus, bool mixToMono, double newSampleRate)
-{
- // sourceBus's sample-rate must be known.
- ASSERT(sourceBus && sourceBus->sampleRate());
- if (!sourceBus || !sourceBus->sampleRate())
- return 0;
-
- double sourceSampleRate = sourceBus->sampleRate();
- double destinationSampleRate = newSampleRate;
- double sampleRateRatio = sourceSampleRate / destinationSampleRate;
- unsigned numberOfSourceChannels = sourceBus->numberOfChannels();
-
- if (numberOfSourceChannels == 1)
- mixToMono = false; // already mono
-
- if (sourceSampleRate == destinationSampleRate) {
- // No sample-rate conversion is necessary.
- if (mixToMono)
- return AudioBus::createByMixingToMono(sourceBus);
-
- // Return exact copy.
- return AudioBus::createBufferFromRange(sourceBus, 0, sourceBus->length());
- }
-
- if (sourceBus->isSilent()) {
- RefPtr<AudioBus> silentBus = create(numberOfSourceChannels, sourceBus->length() / sampleRateRatio);
- silentBus->setSampleRate(newSampleRate);
- return silentBus;
- }
-
- // First, mix to mono (if necessary) then sample-rate convert.
- const AudioBus* resamplerSourceBus;
- RefPtr<AudioBus> mixedMonoBus;
- if (mixToMono) {
- mixedMonoBus = AudioBus::createByMixingToMono(sourceBus);
- resamplerSourceBus = mixedMonoBus.get();
- } else {
- // Directly resample without down-mixing.
- resamplerSourceBus = sourceBus;
- }
-
- // Calculate destination length based on the sample-rates.
- int sourceLength = resamplerSourceBus->length();
- int destinationLength = sourceLength / sampleRateRatio;
-
- // Create destination bus with same number of channels.
- unsigned numberOfDestinationChannels = resamplerSourceBus->numberOfChannels();
- RefPtr<AudioBus> destinationBus = create(numberOfDestinationChannels, destinationLength);
-
- // Sample-rate convert each channel.
- for (unsigned i = 0; i < numberOfDestinationChannels; ++i) {
- const float* source = resamplerSourceBus->channel(i)->data();
- float* destination = destinationBus->channel(i)->mutableData();
-
- SincResampler resampler(sampleRateRatio);
- resampler.process(source, destination, sourceLength);
- }
-
- destinationBus->clearSilentFlag();
- destinationBus->setSampleRate(newSampleRate);
- return destinationBus;
-}
-
-PassRefPtr<AudioBus> AudioBus::createByMixingToMono(const AudioBus* sourceBus)
-{
- if (sourceBus->isSilent())
- return create(1, sourceBus->length());
-
- switch (sourceBus->numberOfChannels()) {
- case 1:
- // Simply create an exact copy.
- return AudioBus::createBufferFromRange(sourceBus, 0, sourceBus->length());
- case 2:
- {
- unsigned n = sourceBus->length();
- RefPtr<AudioBus> destinationBus = create(1, n);
-
- const float* sourceL = sourceBus->channel(0)->data();
- const float* sourceR = sourceBus->channel(1)->data();
- float* destination = destinationBus->channel(0)->mutableData();
-
- // Do the mono mixdown.
- for (unsigned i = 0; i < n; ++i)
- destination[i] = (sourceL[i] + sourceR[i]) / 2;
-
- destinationBus->clearSilentFlag();
- destinationBus->setSampleRate(sourceBus->sampleRate());
- return destinationBus;
- }
- }
-
- ASSERT_NOT_REACHED();
- return 0;
-}
-
-bool AudioBus::isSilent() const
-{
- for (size_t i = 0; i < m_channels.size(); ++i) {
- if (!m_channels[i]->isSilent())
- return false;
- }
- return true;
-}
-
-void AudioBus::clearSilentFlag()
-{
- for (size_t i = 0; i < m_channels.size(); ++i)
- m_channels[i]->clearSilentFlag();
-}
-
-} // WebCore
-
-#endif // ENABLE(WEB_AUDIO)
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/AudioBus.h b/chromium/third_party/WebKit/Source/core/platform/audio/AudioBus.h
deleted file mode 100644
index d13b0e7a0b1..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/AudioBus.h
+++ /dev/null
@@ -1,171 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef AudioBus_h
-#define AudioBus_h
-
-#include "core/platform/audio/AudioChannel.h"
-#include "wtf/Noncopyable.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/ThreadSafeRefCounted.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-// An AudioBus represents a collection of one or more AudioChannels.
-// The data layout is "planar" as opposed to "interleaved".
-// An AudioBus with one channel is mono, an AudioBus with two channels is stereo, etc.
-class AudioBus : public ThreadSafeRefCounted<AudioBus> {
- WTF_MAKE_NONCOPYABLE(AudioBus);
-public:
- enum {
- ChannelLeft = 0,
- ChannelRight = 1,
- ChannelCenter = 2, // center and mono are the same
- ChannelMono = 2,
- ChannelLFE = 3,
- ChannelSurroundLeft = 4,
- ChannelSurroundRight = 5,
- };
-
- enum {
- LayoutCanonical = 0
- // Can define non-standard layouts here
- };
-
- enum ChannelInterpretation {
- Speakers,
- Discrete,
- };
-
- // allocate indicates whether or not to initially have the AudioChannels created with managed storage.
- // Normal usage is to pass true here, in which case the AudioChannels will memory-manage their own storage.
- // If allocate is false then setChannelMemory() has to be called later on for each channel before the AudioBus is useable...
- static PassRefPtr<AudioBus> create(unsigned numberOfChannels, size_t length, bool allocate = true);
-
- // Tells the given channel to use an externally allocated buffer.
- void setChannelMemory(unsigned channelIndex, float* storage, size_t length);
-
- // Channels
- unsigned numberOfChannels() const { return m_channels.size(); }
-
- AudioChannel* channel(unsigned channel) { return m_channels[channel].get(); }
- const AudioChannel* channel(unsigned channel) const { return const_cast<AudioBus*>(this)->m_channels[channel].get(); }
- AudioChannel* channelByType(unsigned type);
- const AudioChannel* channelByType(unsigned type) const;
-
- // Number of sample-frames
- size_t length() const { return m_length; }
-
- // resizeSmaller() can only be called with a new length <= the current length.
- // The data stored in the bus will remain undisturbed.
- void resizeSmaller(size_t newLength);
-
- // Sample-rate : 0.0 if unknown or "don't care"
- float sampleRate() const { return m_sampleRate; }
- void setSampleRate(float sampleRate) { m_sampleRate = sampleRate; }
-
- // Zeroes all channels.
- void zero();
-
- // Clears the silent flag on all channels.
- void clearSilentFlag();
-
- // Returns true if the silent bit is set on all channels.
- bool isSilent() const;
-
- // Returns true if the channel count and frame-size match.
- bool topologyMatches(const AudioBus &sourceBus) const;
-
- // Creates a new buffer from a range in the source buffer.
- // 0 may be returned if the range does not fit in the sourceBuffer
- static PassRefPtr<AudioBus> createBufferFromRange(const AudioBus* sourceBuffer, unsigned startFrame, unsigned endFrame);
-
-
- // Creates a new AudioBus by sample-rate converting sourceBus to the newSampleRate.
- // setSampleRate() must have been previously called on sourceBus.
- // Note: sample-rate conversion is already handled in the file-reading code for the mac port, so we don't need this.
- static PassRefPtr<AudioBus> createBySampleRateConverting(const AudioBus* sourceBus, bool mixToMono, double newSampleRate);
-
- // Creates a new AudioBus by mixing all the channels down to mono.
- // If sourceBus is already mono, then the returned AudioBus will simply be a copy.
- static PassRefPtr<AudioBus> createByMixingToMono(const AudioBus* sourceBus);
-
- // Scales all samples by the same amount.
- void scale(float scale);
-
- void reset() { m_isFirstTime = true; } // for de-zippering
-
- // Copies the samples from the source bus to this one.
- // This is just a simple per-channel copy if the number of channels match, otherwise an up-mix or down-mix is done.
- void copyFrom(const AudioBus& sourceBus, ChannelInterpretation = Speakers);
-
- // Sums the samples from the source bus to this one.
- // This is just a simple per-channel summing if the number of channels match, otherwise an up-mix or down-mix is done.
- void sumFrom(const AudioBus& sourceBus, ChannelInterpretation = Speakers);
-
- // Copy each channel from sourceBus into our corresponding channel.
- // We scale by targetGain (and our own internal gain m_busGain), performing "de-zippering" to smoothly change from *lastMixGain to (targetGain*m_busGain).
- // The caller is responsible for setting up lastMixGain to point to storage which is unique for every "stream" which will be applied to this bus.
- // This represents the dezippering memory.
- void copyWithGainFrom(const AudioBus &sourceBus, float* lastMixGain, float targetGain);
-
- // Copies the sourceBus by scaling with sample-accurate gain values.
- void copyWithSampleAccurateGainValuesFrom(const AudioBus &sourceBus, float* gainValues, unsigned numberOfGainValues);
-
- // Returns maximum absolute value across all channels (useful for normalization).
- float maxAbsValue() const;
-
- // Makes maximum absolute value == 1.0 (if possible).
- void normalize();
-
- static PassRefPtr<AudioBus> loadPlatformResource(const char* name, float sampleRate);
-
-protected:
- AudioBus() { };
-
- AudioBus(unsigned numberOfChannels, size_t length, bool allocate);
-
- void speakersCopyFrom(const AudioBus&);
- void discreteCopyFrom(const AudioBus&);
- void speakersSumFrom(const AudioBus&);
- void discreteSumFrom(const AudioBus&);
- void speakersSumFrom5_1_ToMono(const AudioBus&);
-
- size_t m_length;
- Vector<OwnPtr<AudioChannel> > m_channels;
- int m_layout;
- float m_busGain;
- OwnPtr<AudioFloatArray> m_dezipperGainValues;
- bool m_isFirstTime;
- float m_sampleRate; // 0.0 if unknown or N/A
-};
-
-} // WebCore
-
-#endif // AudioBus_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/AudioChannel.cpp b/chromium/third_party/WebKit/Source/core/platform/audio/AudioChannel.cpp
deleted file mode 100644
index 786d48b37da..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/AudioChannel.cpp
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#if ENABLE(WEB_AUDIO)
-
-#include "core/platform/audio/AudioChannel.h"
-
-#include <math.h>
-#include <algorithm>
-#include "core/platform/audio/VectorMath.h"
-#include "wtf/OwnPtr.h"
-
-namespace WebCore {
-
-using namespace VectorMath;
-
-void AudioChannel::resizeSmaller(size_t newLength)
-{
- ASSERT(newLength <= m_length);
- if (newLength <= m_length)
- m_length = newLength;
-}
-
-void AudioChannel::scale(float scale)
-{
- if (isSilent())
- return;
-
- vsmul(data(), 1, &scale, mutableData(), 1, length());
-}
-
-void AudioChannel::copyFrom(const AudioChannel* sourceChannel)
-{
- bool isSafe = (sourceChannel && sourceChannel->length() >= length());
- ASSERT(isSafe);
- if (!isSafe)
- return;
-
- if (sourceChannel->isSilent()) {
- zero();
- return;
- }
- memcpy(mutableData(), sourceChannel->data(), sizeof(float) * length());
-}
-
-void AudioChannel::copyFromRange(const AudioChannel* sourceChannel, unsigned startFrame, unsigned endFrame)
-{
- // Check that range is safe for reading from sourceChannel.
- bool isRangeSafe = sourceChannel && startFrame < endFrame && endFrame <= sourceChannel->length();
- ASSERT(isRangeSafe);
- if (!isRangeSafe)
- return;
-
- if (sourceChannel->isSilent() && isSilent())
- return;
-
- // Check that this channel has enough space.
- size_t rangeLength = endFrame - startFrame;
- bool isRangeLengthSafe = rangeLength <= length();
- ASSERT(isRangeLengthSafe);
- if (!isRangeLengthSafe)
- return;
-
- const float* source = sourceChannel->data();
- float* destination = mutableData();
-
- if (sourceChannel->isSilent()) {
- if (rangeLength == length())
- zero();
- else
- memset(destination, 0, sizeof(float) * rangeLength);
- } else
- memcpy(destination, source + startFrame, sizeof(float) * rangeLength);
-}
-
-void AudioChannel::sumFrom(const AudioChannel* sourceChannel)
-{
- bool isSafe = sourceChannel && sourceChannel->length() >= length();
- ASSERT(isSafe);
- if (!isSafe)
- return;
-
- if (sourceChannel->isSilent())
- return;
-
- if (isSilent())
- copyFrom(sourceChannel);
- else
- vadd(data(), 1, sourceChannel->data(), 1, mutableData(), 1, length());
-}
-
-float AudioChannel::maxAbsValue() const
-{
- if (isSilent())
- return 0;
-
- float max = 0;
-
- vmaxmgv(data(), 1, &max, length());
-
- return max;
-}
-
-} // WebCore
-
-#endif // ENABLE(WEB_AUDIO)
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/AudioChannel.h b/chromium/third_party/WebKit/Source/core/platform/audio/AudioChannel.h
deleted file mode 100644
index 74a43ddf518..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/AudioChannel.h
+++ /dev/null
@@ -1,139 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef AudioChannel_h
-#define AudioChannel_h
-
-#include "core/platform/audio/AudioArray.h"
-#include "wtf/PassOwnPtr.h"
-
-namespace WebCore {
-
-// An AudioChannel represents a buffer of non-interleaved floating-point audio samples.
-// The PCM samples are normally assumed to be in a nominal range -1.0 -> +1.0
-class AudioChannel {
- WTF_MAKE_NONCOPYABLE(AudioChannel);
-public:
- // Memory can be externally referenced, or can be internally allocated with an AudioFloatArray.
-
- // Reference an external buffer.
- AudioChannel(float* storage, size_t length)
- : m_length(length)
- , m_rawPointer(storage)
- , m_silent(false)
- {
- }
-
- // Manage storage for us.
- explicit AudioChannel(size_t length)
- : m_length(length)
- , m_rawPointer(0)
- , m_silent(true)
- {
- m_memBuffer = adoptPtr(new AudioFloatArray(length));
- }
-
- // A "blank" audio channel -- must call set() before it's useful...
- AudioChannel()
- : m_length(0)
- , m_rawPointer(0)
- , m_silent(true)
- {
- }
-
- // Redefine the memory for this channel.
- // storage represents external memory not managed by this object.
- void set(float* storage, size_t length)
- {
- m_memBuffer.clear(); // cleanup managed storage
- m_rawPointer = storage;
- m_length = length;
- m_silent = false;
- }
-
- // How many sample-frames do we contain?
- size_t length() const { return m_length; }
-
- // resizeSmaller() can only be called with a new length <= the current length.
- // The data stored in the bus will remain undisturbed.
- void resizeSmaller(size_t newLength);
-
- // Direct access to PCM sample data. Non-const accessor clears silent flag.
- float* mutableData()
- {
- clearSilentFlag();
- return m_rawPointer ? m_rawPointer : m_memBuffer->data();
- }
-
- const float* data() const { return m_rawPointer ? m_rawPointer : m_memBuffer->data(); }
-
- // Zeroes out all sample values in buffer.
- void zero()
- {
- if (m_silent)
- return;
-
- m_silent = true;
-
- if (m_memBuffer.get())
- m_memBuffer->zero();
- else
- memset(m_rawPointer, 0, sizeof(float) * m_length);
- }
-
- // Clears the silent flag.
- void clearSilentFlag() { m_silent = false; }
-
- bool isSilent() const { return m_silent; }
-
- // Scales all samples by the same amount.
- void scale(float scale);
-
- // A simple memcpy() from the source channel
- void copyFrom(const AudioChannel* sourceChannel);
-
- // Copies the given range from the source channel.
- void copyFromRange(const AudioChannel* sourceChannel, unsigned startFrame, unsigned endFrame);
-
- // Sums (with unity gain) from the source channel.
- void sumFrom(const AudioChannel* sourceChannel);
-
- // Returns maximum absolute value (useful for normalization).
- float maxAbsValue() const;
-
-private:
- size_t m_length;
-
- float* m_rawPointer;
- OwnPtr<AudioFloatArray> m_memBuffer;
- bool m_silent;
-};
-
-} // WebCore
-
-#endif // AudioChannel_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/AudioDSPKernel.h b/chromium/third_party/WebKit/Source/core/platform/audio/AudioDSPKernel.h
deleted file mode 100644
index 67b893038d3..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/AudioDSPKernel.h
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef AudioDSPKernel_h
-#define AudioDSPKernel_h
-
-#include "core/platform/audio/AudioDSPKernelProcessor.h"
-
-namespace WebCore {
-
-// AudioDSPKernel does the processing for one channel of an AudioDSPKernelProcessor.
-
-class AudioDSPKernel {
-public:
- AudioDSPKernel(AudioDSPKernelProcessor* kernelProcessor)
- : m_kernelProcessor(kernelProcessor)
- , m_sampleRate(kernelProcessor->sampleRate())
- {
- }
-
- AudioDSPKernel(float sampleRate)
- : m_kernelProcessor(0)
- , m_sampleRate(sampleRate)
- {
- }
-
- virtual ~AudioDSPKernel() { };
-
- // Subclasses must override process() to do the processing and reset() to reset DSP state.
- virtual void process(const float* source, float* destination, size_t framesToProcess) = 0;
- virtual void reset() = 0;
-
- float sampleRate() const { return m_sampleRate; }
- double nyquist() const { return 0.5 * sampleRate(); }
-
- AudioDSPKernelProcessor* processor() { return m_kernelProcessor; }
- const AudioDSPKernelProcessor* processor() const { return m_kernelProcessor; }
-
- virtual double tailTime() const = 0;
- virtual double latencyTime() const = 0;
-
-protected:
- AudioDSPKernelProcessor* m_kernelProcessor;
- float m_sampleRate;
-};
-
-} // namespace WebCore
-
-#endif // AudioDSPKernel_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/AudioDSPKernelProcessor.cpp b/chromium/third_party/WebKit/Source/core/platform/audio/AudioDSPKernelProcessor.cpp
deleted file mode 100644
index d284b1c9868..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/AudioDSPKernelProcessor.cpp
+++ /dev/null
@@ -1,157 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#if ENABLE(WEB_AUDIO)
-
-#include "core/platform/audio/AudioDSPKernelProcessor.h"
-
-#include "core/platform/audio/AudioDSPKernel.h"
-#include "wtf/MainThread.h"
-
-namespace WebCore {
-
-// setNumberOfChannels() may later be called if the object is not yet in an "initialized" state.
-AudioDSPKernelProcessor::AudioDSPKernelProcessor(float sampleRate, unsigned numberOfChannels)
- : AudioProcessor(sampleRate, numberOfChannels)
- , m_hasJustReset(true)
-{
-}
-
-void AudioDSPKernelProcessor::initialize()
-{
- if (isInitialized())
- return;
-
- MutexLocker locker(m_processLock);
- ASSERT(!m_kernels.size());
-
- // Create processing kernels, one per channel.
- for (unsigned i = 0; i < numberOfChannels(); ++i)
- m_kernels.append(createKernel());
-
- m_initialized = true;
- m_hasJustReset = true;
-}
-
-void AudioDSPKernelProcessor::uninitialize()
-{
- if (!isInitialized())
- return;
-
- MutexLocker locker(m_processLock);
- m_kernels.clear();
-
- m_initialized = false;
-}
-
-void AudioDSPKernelProcessor::process(const AudioBus* source, AudioBus* destination, size_t framesToProcess)
-{
- ASSERT(source && destination);
- if (!source || !destination)
- return;
-
- if (!isInitialized()) {
- destination->zero();
- return;
- }
-
- MutexTryLocker tryLocker(m_processLock);
- if (tryLocker.locked()) {
- bool channelCountMatches = source->numberOfChannels() == destination->numberOfChannels() && source->numberOfChannels() == m_kernels.size();
- ASSERT(channelCountMatches);
- if (!channelCountMatches)
- return;
-
- for (unsigned i = 0; i < m_kernels.size(); ++i)
- m_kernels[i]->process(source->channel(i)->data(), destination->channel(i)->mutableData(), framesToProcess);
- } else {
- // Unfortunately, the kernel is being processed by another thread.
- // See also ConvolverNode::process().
- destination->zero();
- }
-}
-
-// Resets filter state
-void AudioDSPKernelProcessor::reset()
-{
- ASSERT(isMainThread());
- if (!isInitialized())
- return;
-
- // Forces snap to parameter values - first time.
- // Any processing depending on this value must set it to false at the appropriate time.
- m_hasJustReset = true;
-
- MutexLocker locker(m_processLock);
- for (unsigned i = 0; i < m_kernels.size(); ++i)
- m_kernels[i]->reset();
-}
-
-void AudioDSPKernelProcessor::setNumberOfChannels(unsigned numberOfChannels)
-{
- if (numberOfChannels == m_numberOfChannels)
- return;
-
- ASSERT(!isInitialized());
- if (!isInitialized())
- m_numberOfChannels = numberOfChannels;
-}
-
-double AudioDSPKernelProcessor::tailTime() const
-{
- ASSERT(!isMainThread());
- MutexTryLocker tryLocker(m_processLock);
- if (tryLocker.locked()) {
- // It is expected that all the kernels have the same tailTime.
- return !m_kernels.isEmpty() ? m_kernels.first()->tailTime() : 0;
- }
- // Since we don't want to block the Audio Device thread, we return a large value
- // instead of trying to acquire the lock.
- return std::numeric_limits<double>::infinity();
-}
-
-double AudioDSPKernelProcessor::latencyTime() const
-{
- ASSERT(!isMainThread());
- MutexTryLocker tryLocker(m_processLock);
- if (tryLocker.locked()) {
- // It is expected that all the kernels have the same latencyTime.
- return !m_kernels.isEmpty() ? m_kernels.first()->latencyTime() : 0;
- }
- // Since we don't want to block the Audio Device thread, we return a large value
- // instead of trying to acquire the lock.
- return std::numeric_limits<double>::infinity();
-}
-
-} // namespace WebCore
-
-#endif // ENABLE(WEB_AUDIO)
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/AudioDSPKernelProcessor.h b/chromium/third_party/WebKit/Source/core/platform/audio/AudioDSPKernelProcessor.h
deleted file mode 100644
index 41c168a14e8..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/AudioDSPKernelProcessor.h
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef AudioDSPKernelProcessor_h
-#define AudioDSPKernelProcessor_h
-
-#include "core/platform/audio/AudioBus.h"
-#include "core/platform/audio/AudioProcessor.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/ThreadingPrimitives.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-class AudioBus;
-class AudioDSPKernel;
-class AudioProcessor;
-
-// AudioDSPKernelProcessor processes one input -> one output (N channels each)
-// It uses one AudioDSPKernel object per channel to do the processing, thus there is no cross-channel processing.
-// Despite this limitation it turns out to be a very common and useful type of processor.
-
-class AudioDSPKernelProcessor : public AudioProcessor {
-public:
- // numberOfChannels may be later changed if object is not yet in an "initialized" state
- AudioDSPKernelProcessor(float sampleRate, unsigned numberOfChannels);
-
- // Subclasses create the appropriate type of processing kernel here.
- // We'll call this to create a kernel for each channel.
- virtual PassOwnPtr<AudioDSPKernel> createKernel() = 0;
-
- // AudioProcessor methods
- virtual void initialize();
- virtual void uninitialize();
- virtual void process(const AudioBus* source, AudioBus* destination, size_t framesToProcess);
- virtual void reset();
- virtual void setNumberOfChannels(unsigned numberOfChannels);
- virtual unsigned numberOfChannels() const { return m_numberOfChannels; }
-
- virtual double tailTime() const OVERRIDE;
- virtual double latencyTime() const OVERRIDE;
-
-protected:
- Vector<OwnPtr<AudioDSPKernel> > m_kernels;
- mutable Mutex m_processLock;
- bool m_hasJustReset;
-};
-
-} // namespace WebCore
-
-#endif // AudioDSPKernelProcessor_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/AudioDestination.h b/chromium/third_party/WebKit/Source/core/platform/audio/AudioDestination.h
deleted file mode 100644
index 4c1a56f9570..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/AudioDestination.h
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef AudioDestination_h
-#define AudioDestination_h
-
-#include "wtf/OwnPtr.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class AudioIOCallback;
-
-// AudioDestination is an abstraction for audio hardware I/O.
-// The audio hardware periodically calls the AudioIOCallback render() method asking it to render/output the next render quantum of audio.
-// It optionally will pass in local/live audio input when it calls render().
-
-class AudioDestination {
-public:
- // Pass in (numberOfInputChannels > 0) if live/local audio input is desired.
- // Port-specific device identification information for live/local input streams can be passed in the inputDeviceId.
- static PassOwnPtr<AudioDestination> create(AudioIOCallback&, const String& inputDeviceId, unsigned numberOfInputChannels, unsigned numberOfOutputChannels, float sampleRate);
-
- virtual ~AudioDestination() { }
-
- virtual void start() = 0;
- virtual void stop() = 0;
- virtual bool isPlaying() = 0;
-
- // Sample-rate conversion may happen in AudioDestination to the hardware sample-rate
- virtual float sampleRate() const = 0;
- static float hardwareSampleRate();
-
- // maxChannelCount() returns the total number of output channels of the audio hardware.
- // A value of 0 indicates that the number of channels cannot be configured and
- // that only stereo (2-channel) destinations can be created.
- // The numberOfOutputChannels parameter of AudioDestination::create() is allowed to
- // be a value: 1 <= numberOfOutputChannels <= maxChannelCount(),
- // or if maxChannelCount() equals 0, then numberOfOutputChannels must be 2.
- static unsigned long maxChannelCount();
-};
-
-} // namespace WebCore
-
-#endif // AudioDestination_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/AudioDestinationConsumer.h b/chromium/third_party/WebKit/Source/core/platform/audio/AudioDestinationConsumer.h
deleted file mode 100644
index 35bc396a9be..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/AudioDestinationConsumer.h
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * 3. Neither the name of Google Inc. nor the names of its contributors
- * may be used to endorse or promote products derived from this
- * software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef AudioDestinationConsumer_h
-#define AudioDestinationConsumer_h
-
-#include "wtf/RefCounted.h"
-
-namespace WebCore {
-
-class AudioBus;
-
-class AudioDestinationConsumer : public RefCounted<AudioDestinationConsumer> {
-public:
- virtual ~AudioDestinationConsumer() { }
-
- virtual void setFormat(size_t numberOfChannels, float sampleRate) = 0;
- virtual void consumeAudio(AudioBus*, size_t numberOfFrames) = 0;
-};
-
-} // WebCore
-
-#endif // AudioDestinationConsumer_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/AudioFIFO.cpp b/chromium/third_party/WebKit/Source/core/platform/audio/AudioFIFO.cpp
deleted file mode 100644
index f468d25ffb0..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/AudioFIFO.cpp
+++ /dev/null
@@ -1,144 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#if ENABLE(WEB_AUDIO)
-
-#include "core/platform/audio/AudioFIFO.h"
-
-namespace WebCore {
-
-AudioFIFO::AudioFIFO(unsigned numberOfChannels, size_t fifoLength)
- : m_fifoAudioBus(AudioBus::create(numberOfChannels, fifoLength))
- , m_fifoLength(fifoLength)
- , m_framesInFifo(0)
- , m_readIndex(0)
- , m_writeIndex(0)
-{
-}
-
-void AudioFIFO::consume(AudioBus* destination, size_t framesToConsume)
-{
- bool isGood = destination && (framesToConsume <= m_fifoLength) && (framesToConsume <= m_framesInFifo) && (destination->length() >= framesToConsume);
- ASSERT(isGood);
- if (!isGood)
- return;
-
- // Copy the requested number of samples to the destination.
-
- size_t part1Length;
- size_t part2Length;
- findWrapLengths(m_readIndex, framesToConsume, part1Length, part2Length);
-
- size_t numberOfChannels = m_fifoAudioBus->numberOfChannels();
-
- for (size_t channelIndex = 0; channelIndex < numberOfChannels; ++channelIndex) {
- float* destinationData = destination->channel(channelIndex)->mutableData();
- const float* sourceData = m_fifoAudioBus->channel(channelIndex)->data();
-
- bool isCopyGood = ((m_readIndex < m_fifoLength)
- && (m_readIndex + part1Length) <= m_fifoLength
- && (part1Length <= destination->length())
- && (part1Length + part2Length) <= destination->length());
- ASSERT(isCopyGood);
- if (!isCopyGood)
- return;
-
- memcpy(destinationData, sourceData + m_readIndex, part1Length * sizeof(*sourceData));
- // Handle wrap around of the FIFO, if needed.
- if (part2Length)
- memcpy(destinationData + part1Length, sourceData, part2Length * sizeof(*sourceData));
- }
- m_readIndex = updateIndex(m_readIndex, framesToConsume);
- ASSERT(m_framesInFifo >= framesToConsume);
- m_framesInFifo -= framesToConsume;
-}
-
-void AudioFIFO::push(const AudioBus* sourceBus)
-{
- // Copy the sourceBus into the FIFO buffer.
-
- bool isGood = sourceBus && (m_framesInFifo + sourceBus->length() <= m_fifoLength);
- if (!isGood)
- return;
-
- size_t sourceLength = sourceBus->length();
- size_t part1Length;
- size_t part2Length;
- findWrapLengths(m_writeIndex, sourceLength, part1Length, part2Length);
-
- size_t numberOfChannels = m_fifoAudioBus->numberOfChannels();
-
- for (size_t channelIndex = 0; channelIndex < numberOfChannels; ++channelIndex) {
- float* destination = m_fifoAudioBus->channel(channelIndex)->mutableData();
- const float* source = sourceBus->channel(channelIndex)->data();
-
- bool isCopyGood = ((m_writeIndex < m_fifoLength)
- && (m_writeIndex + part1Length) <= m_fifoLength
- && part2Length < m_fifoLength
- && part1Length + part2Length <= sourceLength);
- ASSERT(isCopyGood);
- if (!isCopyGood)
- return;
-
- memcpy(destination + m_writeIndex, source, part1Length * sizeof(*destination));
-
- // Handle wrap around of the FIFO, if needed.
- if (part2Length)
- memcpy(destination, source + part1Length, part2Length * sizeof(*destination));
- }
-
- m_framesInFifo += sourceLength;
- ASSERT(m_framesInFifo <= m_fifoLength);
- m_writeIndex = updateIndex(m_writeIndex, sourceLength);
-}
-
-void AudioFIFO::findWrapLengths(size_t index, size_t size, size_t& part1Length, size_t& part2Length)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(index < m_fifoLength && size <= m_fifoLength);
- if (index < m_fifoLength && size <= m_fifoLength) {
- if (index + size > m_fifoLength) {
- // Need to wrap. Figure out the length of each piece.
- part1Length = m_fifoLength - index;
- part2Length = size - part1Length;
- } else {
- // No wrap needed.
- part1Length = size;
- part2Length = 0;
- }
- } else {
- // Invalid values for index or size. Set the part lengths to zero so nothing is copied.
- part1Length = 0;
- part2Length = 0;
- }
-}
-
-} // namespace WebCore
-
-#endif // ENABLE(WEB_AUDIO)
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/AudioFIFO.h b/chromium/third_party/WebKit/Source/core/platform/audio/AudioFIFO.h
deleted file mode 100644
index 920e606e268..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/AudioFIFO.h
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef AudioFIFO_h
-#define AudioFIFO_h
-
-#include "core/platform/audio/AudioBus.h"
-
-namespace WebCore {
-
-class AudioFIFO {
-public:
- // Create a FIFO large enough to hold |fifoLength| frames of data of |numberOfChannels| channels.
- AudioFIFO(unsigned numberOfChannels, size_t fifoLength);
-
- // Push the data from the bus into the FIFO.
- void push(const AudioBus*);
-
- // Consume |framesToConsume| frames of data from the FIFO and put them in |destination|. The
- // corresponding frames are removed from the FIFO.
- void consume(AudioBus* destination, size_t framesToConsume);
-
- // Number of frames of data that are currently in the FIFO.
- size_t framesInFifo() const { return m_framesInFifo; }
-
-private:
- // Update the FIFO index by the step, with appropriate wrapping around the endpoint.
- int updateIndex(int index, int step) { return (index + step) % m_fifoLength; }
-
- void findWrapLengths(size_t index, size_t providerSize, size_t& part1Length, size_t& part2Length);
-
- // The FIFO itself. In reality, the FIFO is a circular buffer.
- RefPtr<AudioBus> m_fifoAudioBus;
-
- // The total available space in the FIFO.
- size_t m_fifoLength;
-
- // The number of actual elements in the FIFO
- size_t m_framesInFifo;
-
- // Where to start reading from the FIFO.
- size_t m_readIndex;
-
- // Where to start writing to the FIFO.
- size_t m_writeIndex;
-};
-
-} // namespace WebCore
-
-#endif // AudioFIFO.h
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/AudioFileReader.h b/chromium/third_party/WebKit/Source/core/platform/audio/AudioFileReader.h
deleted file mode 100644
index 198d54d2876..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/AudioFileReader.h
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef AudioFileReader_h
-#define AudioFileReader_h
-
-#include "wtf/PassRefPtr.h"
-
-namespace WebCore {
-
-class AudioBus;
-
-// For both create functions:
-// Pass in 0.0 for sampleRate to use the file's sample-rate, otherwise a sample-rate conversion to the requested
-// sampleRate will be made (if it doesn't already match the file's sample-rate).
-// The created buffer will have its sample-rate set correctly to the result.
-
-PassRefPtr<AudioBus> createBusFromInMemoryAudioFile(const void* data, size_t dataSize, bool mixToMono, float sampleRate);
-
-PassRefPtr<AudioBus> createBusFromAudioFile(const char* filePath, bool mixToMono, float sampleRate);
-
-// May pass in 0.0 for sampleRate in which case it will use the AudioBus's sampleRate
-void writeBusToAudioFile(AudioBus* bus, const char* filePath, double fileSampleRate);
-
-} // namespace WebCore
-
-#endif // AudioFileReader_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/AudioIOCallback.h b/chromium/third_party/WebKit/Source/core/platform/audio/AudioIOCallback.h
deleted file mode 100644
index 2cc3a9df2dd..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/AudioIOCallback.h
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef AudioIOCallback_h
-#define AudioIOCallback_h
-
-namespace WebCore {
-
-class AudioBus;
-
-// Abstract base-class for isochronous audio I/O client.
-class AudioIOCallback {
-public:
- // render() is called periodically to get the next render quantum of audio into destinationBus.
- // Optional audio input is given in sourceBus (if it's not 0).
- virtual void render(AudioBus* sourceBus, AudioBus* destinationBus, size_t framesToProcess) = 0;
-
- virtual ~AudioIOCallback() { }
-};
-
-} // WebCore
-
-#endif // AudioIOCallback_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/AudioProcessor.h b/chromium/third_party/WebKit/Source/core/platform/audio/AudioProcessor.h
deleted file mode 100644
index 589b7f99a76..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/AudioProcessor.h
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef AudioProcessor_h
-#define AudioProcessor_h
-
-namespace WebCore {
-
-class AudioBus;
-
-// AudioProcessor is an abstract base class representing an audio signal processing object with a single input and a single output,
-// where the number of input channels equals the number of output channels. It can be used as one part of a complex DSP algorithm,
-// or as the processor for a basic (one input - one output) AudioNode.
-
-class AudioProcessor {
-public:
- AudioProcessor(float sampleRate, unsigned numberOfChannels)
- : m_initialized(false)
- , m_numberOfChannels(numberOfChannels)
- , m_sampleRate(sampleRate)
- {
- }
-
- virtual ~AudioProcessor() { }
-
- // Full initialization can be done here instead of in the constructor.
- virtual void initialize() = 0;
- virtual void uninitialize() = 0;
-
- // Processes the source to destination bus. The number of channels must match in source and destination.
- virtual void process(const AudioBus* source, AudioBus* destination, size_t framesToProcess) = 0;
-
- // Resets filter state
- virtual void reset() = 0;
-
- virtual void setNumberOfChannels(unsigned) = 0;
- virtual unsigned numberOfChannels() const = 0;
-
- bool isInitialized() const { return m_initialized; }
-
- float sampleRate() const { return m_sampleRate; }
-
- virtual double tailTime() const = 0;
- virtual double latencyTime() const = 0;
-
-protected:
- bool m_initialized;
- unsigned m_numberOfChannels;
- float m_sampleRate;
-};
-
-} // namespace WebCore
-
-#endif // AudioProcessor_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/AudioPullFIFO.cpp b/chromium/third_party/WebKit/Source/core/platform/audio/AudioPullFIFO.cpp
deleted file mode 100644
index ce8c0d99050..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/AudioPullFIFO.cpp
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#if ENABLE(WEB_AUDIO)
-
-#include "core/platform/audio/AudioPullFIFO.h"
-
-namespace WebCore {
-
-AudioPullFIFO::AudioPullFIFO(AudioSourceProvider& audioProvider, unsigned numberOfChannels, size_t fifoLength, size_t providerSize)
- : m_provider(audioProvider)
- , m_fifo(numberOfChannels, fifoLength)
- , m_providerSize(providerSize)
- , m_tempBus(AudioBus::create(numberOfChannels, providerSize))
-{
-}
-
-void AudioPullFIFO::consume(AudioBus* destination, size_t framesToConsume)
-{
- if (!destination)
- return;
-
- if (framesToConsume > m_fifo.framesInFifo()) {
- // We don't have enough data in the FIFO to fulfill the request. Ask for more data.
- fillBuffer(framesToConsume - m_fifo.framesInFifo());
- }
-
- m_fifo.consume(destination, framesToConsume);
-}
-
-void AudioPullFIFO::fillBuffer(size_t numberOfFrames)
-{
- // Keep asking the provider to give us data until we have received at least |numberOfFrames| of
- // data. Stuff the data into the FIFO.
- size_t framesProvided = 0;
-
- while (framesProvided < numberOfFrames) {
- m_provider.provideInput(m_tempBus.get(), m_providerSize);
-
- m_fifo.push(m_tempBus.get());
-
- framesProvided += m_providerSize;
- }
-}
-
-} // namespace WebCore
-
-#endif // ENABLE(WEB_AUDIO)
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/AudioPullFIFO.h b/chromium/third_party/WebKit/Source/core/platform/audio/AudioPullFIFO.h
deleted file mode 100644
index 86795a18043..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/AudioPullFIFO.h
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef AudioPullFIFO_h
-#define AudioPullFIFO_h
-
-#include "core/platform/audio/AudioBus.h"
-#include "core/platform/audio/AudioFIFO.h"
-#include "core/platform/audio/AudioSourceProvider.h"
-
-namespace WebCore {
-
-// A FIFO (First In First Out) buffer to handle mismatches in buffer sizes between a provider and
-// receiver. The receiver will "pull" data from this FIFO. If data is already available in the
-// FIFO, it is provided to the receiver. If insufficient data is available to satisfy the request,
-// the FIFO will ask the provider for more data when necessary to fulfill a request. Contrast this
-// with a "push" FIFO, where the sender pushes data to the FIFO which will itself push the data to
-// the receiver when the FIFO is full.
-class AudioPullFIFO {
-public:
- // Create a FIFO that gets data from |provider|. The FIFO will be large enough to hold
- // |fifoLength| frames of data of |numberOfChannels| channels. The AudioSourceProvider will be
- // asked to produce |providerSize| frames when the FIFO needs more data.
- AudioPullFIFO(AudioSourceProvider& audioProvider, unsigned numberOfChannels, size_t fifoLength, size_t providerSize);
-
- // Read |framesToConsume| frames from the FIFO into the destination. If the FIFO does not have
- // enough data, we ask the |provider| to get more data to fulfill the request.
- void consume(AudioBus* destination, size_t framesToConsume);
-
-private:
- // Fill the FIFO buffer with at least |numberOfFrames| more data.
- void fillBuffer(size_t numberOfFrames);
-
- // The provider of the data in our FIFO.
- AudioSourceProvider& m_provider;
-
- // The actual FIFO
- AudioFIFO m_fifo;
-
- // Number of frames of data that the provider will produce per call.
- unsigned int m_providerSize;
-
- // Temporary workspace to hold the data from the provider.
- RefPtr<AudioBus> m_tempBus;
-};
-
-} // namespace WebCore
-
-#endif // AudioPullFIFO.h
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/AudioResampler.cpp b/chromium/third_party/WebKit/Source/core/platform/audio/AudioResampler.cpp
deleted file mode 100644
index 58ceae1c6fc..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/AudioResampler.cpp
+++ /dev/null
@@ -1,128 +0,0 @@
-/*
- * Copyright (C) 2010, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#if ENABLE(WEB_AUDIO)
-
-#include "core/platform/audio/AudioResampler.h"
-
-#include <algorithm>
-#include "core/platform/audio/AudioBus.h"
-#include "wtf/MathExtras.h"
-
-using namespace std;
-
-namespace WebCore {
-
-const double AudioResampler::MaxRate = 8.0;
-
-AudioResampler::AudioResampler()
- : m_rate(1.0)
-{
- m_kernels.append(adoptPtr(new AudioResamplerKernel(this)));
- m_sourceBus = AudioBus::create(1, 0, false);
-}
-
-AudioResampler::AudioResampler(unsigned numberOfChannels)
- : m_rate(1.0)
-{
- for (unsigned i = 0; i < numberOfChannels; ++i)
- m_kernels.append(adoptPtr(new AudioResamplerKernel(this)));
-
- m_sourceBus = AudioBus::create(numberOfChannels, 0, false);
-}
-
-void AudioResampler::configureChannels(unsigned numberOfChannels)
-{
- unsigned currentSize = m_kernels.size();
- if (numberOfChannels == currentSize)
- return; // already setup
-
- // First deal with adding or removing kernels.
- if (numberOfChannels > currentSize) {
- for (unsigned i = currentSize; i < numberOfChannels; ++i)
- m_kernels.append(adoptPtr(new AudioResamplerKernel(this)));
- } else
- m_kernels.resize(numberOfChannels);
-
- // Reconfigure our source bus to the new channel size.
- m_sourceBus = AudioBus::create(numberOfChannels, 0, false);
-}
-
-void AudioResampler::process(AudioSourceProvider* provider, AudioBus* destinationBus, size_t framesToProcess)
-{
- ASSERT(provider);
- if (!provider)
- return;
-
- unsigned numberOfChannels = m_kernels.size();
-
- // Make sure our configuration matches the bus we're rendering to.
- bool channelsMatch = (destinationBus && destinationBus->numberOfChannels() == numberOfChannels);
- ASSERT(channelsMatch);
- if (!channelsMatch)
- return;
-
- // Setup the source bus.
- for (unsigned i = 0; i < numberOfChannels; ++i) {
- // Figure out how many frames we need to get from the provider, and a pointer to the buffer.
- size_t framesNeeded;
- float* fillPointer = m_kernels[i]->getSourcePointer(framesToProcess, &framesNeeded);
- ASSERT(fillPointer);
- if (!fillPointer)
- return;
-
- m_sourceBus->setChannelMemory(i, fillPointer, framesNeeded);
- }
-
- // Ask the provider to supply the desired number of source frames.
- provider->provideInput(m_sourceBus.get(), m_sourceBus->length());
-
- // Now that we have the source data, resample each channel into the destination bus.
- // FIXME: optimize for the common stereo case where it's faster to process both left/right channels in the same inner loop.
- for (unsigned i = 0; i < numberOfChannels; ++i) {
- float* destination = destinationBus->channel(i)->mutableData();
- m_kernels[i]->process(destination, framesToProcess);
- }
-}
-
-void AudioResampler::setRate(double rate)
-{
- if (std::isnan(rate) || std::isinf(rate) || rate <= 0.0)
- return;
-
- m_rate = min(AudioResampler::MaxRate, rate);
-}
-
-void AudioResampler::reset()
-{
- unsigned numberOfChannels = m_kernels.size();
- for (unsigned i = 0; i < numberOfChannels; ++i)
- m_kernels[i]->reset();
-}
-
-} // namespace WebCore
-
-#endif // ENABLE(WEB_AUDIO)
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/AudioResampler.h b/chromium/third_party/WebKit/Source/core/platform/audio/AudioResampler.h
deleted file mode 100644
index 5ef70ac6126..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/AudioResampler.h
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Copyright (C) 2010, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef AudioResampler_h
-#define AudioResampler_h
-
-#include "core/platform/audio/AudioBus.h"
-#include "core/platform/audio/AudioResamplerKernel.h"
-#include "core/platform/audio/AudioSourceProvider.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-// AudioResampler resamples the audio stream from an AudioSourceProvider.
-// The audio stream may be single or multi-channel.
-// The default constructor defaults to single-channel (mono).
-
-class AudioResampler {
-public:
- AudioResampler();
- AudioResampler(unsigned numberOfChannels);
- ~AudioResampler() { }
-
- // Given an AudioSourceProvider, process() resamples the source stream into destinationBus.
- void process(AudioSourceProvider*, AudioBus* destinationBus, size_t framesToProcess);
-
- // Resets the processing state.
- void reset();
-
- void configureChannels(unsigned numberOfChannels);
-
- // 0 < rate <= MaxRate
- void setRate(double rate);
- double rate() const { return m_rate; }
-
- static const double MaxRate;
-
-private:
- double m_rate;
- Vector<OwnPtr<AudioResamplerKernel> > m_kernels;
- RefPtr<AudioBus> m_sourceBus;
-};
-
-} // namespace WebCore
-
-#endif // AudioResampler_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/AudioResamplerKernel.cpp b/chromium/third_party/WebKit/Source/core/platform/audio/AudioResamplerKernel.cpp
deleted file mode 100644
index 8b9b457517a..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/AudioResamplerKernel.cpp
+++ /dev/null
@@ -1,143 +0,0 @@
-/*
- * Copyright (C) 2010, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#if ENABLE(WEB_AUDIO)
-
-#include "core/platform/audio/AudioResamplerKernel.h"
-
-#include <algorithm>
-#include "core/platform/audio/AudioResampler.h"
-
-using namespace std;
-
-namespace WebCore {
-
-const size_t AudioResamplerKernel::MaxFramesToProcess = 128;
-
-AudioResamplerKernel::AudioResamplerKernel(AudioResampler* resampler)
- : m_resampler(resampler)
- // The buffer size must be large enough to hold up to two extra sample frames for the linear interpolation.
- , m_sourceBuffer(2 + static_cast<int>(MaxFramesToProcess * AudioResampler::MaxRate))
- , m_virtualReadIndex(0.0)
- , m_fillIndex(0)
-{
- m_lastValues[0] = 0.0f;
- m_lastValues[1] = 0.0f;
-}
-
-float* AudioResamplerKernel::getSourcePointer(size_t framesToProcess, size_t* numberOfSourceFramesNeededP)
-{
- ASSERT(framesToProcess <= MaxFramesToProcess);
-
- // Calculate the next "virtual" index. After process() is called, m_virtualReadIndex will equal this value.
- double nextFractionalIndex = m_virtualReadIndex + framesToProcess * rate();
-
- // Because we're linearly interpolating between the previous and next sample we need to round up so we include the next sample.
- int endIndex = static_cast<int>(nextFractionalIndex + 1.0); // round up to next integer index
-
- // Determine how many input frames we'll need.
- // We need to fill the buffer up to and including endIndex (so add 1) but we've already buffered m_fillIndex frames from last time.
- size_t framesNeeded = 1 + endIndex - m_fillIndex;
- if (numberOfSourceFramesNeededP)
- *numberOfSourceFramesNeededP = framesNeeded;
-
- // Do bounds checking for the source buffer.
- bool isGood = m_fillIndex < m_sourceBuffer.size() && m_fillIndex + framesNeeded <= m_sourceBuffer.size();
- ASSERT(isGood);
- if (!isGood)
- return 0;
-
- return m_sourceBuffer.data() + m_fillIndex;
-}
-
-void AudioResamplerKernel::process(float* destination, size_t framesToProcess)
-{
- ASSERT(framesToProcess <= MaxFramesToProcess);
-
- float* source = m_sourceBuffer.data();
-
- double rate = this->rate();
- rate = max(0.0, rate);
- rate = min(AudioResampler::MaxRate, rate);
-
- // Start out with the previous saved values (if any).
- if (m_fillIndex > 0) {
- source[0] = m_lastValues[0];
- source[1] = m_lastValues[1];
- }
-
- // Make a local copy.
- double virtualReadIndex = m_virtualReadIndex;
-
- // Sanity check source buffer access.
- ASSERT(framesToProcess > 0);
- ASSERT(virtualReadIndex >= 0 && 1 + static_cast<unsigned>(virtualReadIndex + (framesToProcess - 1) * rate) < m_sourceBuffer.size());
-
- // Do the linear interpolation.
- int n = framesToProcess;
- while (n--) {
- unsigned readIndex = static_cast<unsigned>(virtualReadIndex);
- double interpolationFactor = virtualReadIndex - readIndex;
-
- double sample1 = source[readIndex];
- double sample2 = source[readIndex + 1];
-
- double sample = (1.0 - interpolationFactor) * sample1 + interpolationFactor * sample2;
-
- *destination++ = static_cast<float>(sample);
-
- virtualReadIndex += rate;
- }
-
- // Save the last two sample-frames which will later be used at the beginning of the source buffer the next time around.
- int readIndex = static_cast<int>(virtualReadIndex);
- m_lastValues[0] = source[readIndex];
- m_lastValues[1] = source[readIndex + 1];
- m_fillIndex = 2;
-
- // Wrap the virtual read index back to the start of the buffer.
- virtualReadIndex -= readIndex;
-
- // Put local copy back into member variable.
- m_virtualReadIndex = virtualReadIndex;
-}
-
-void AudioResamplerKernel::reset()
-{
- m_virtualReadIndex = 0.0;
- m_fillIndex = 0;
- m_lastValues[0] = 0.0f;
- m_lastValues[1] = 0.0f;
-}
-
-double AudioResamplerKernel::rate() const
-{
- return m_resampler->rate();
-}
-
-} // namespace WebCore
-
-#endif // ENABLE(WEB_AUDIO)
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/AudioResamplerKernel.h b/chromium/third_party/WebKit/Source/core/platform/audio/AudioResamplerKernel.h
deleted file mode 100644
index 8bfb8a8014b..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/AudioResamplerKernel.h
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * Copyright (C) 2010, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef AudioResamplerKernel_h
-#define AudioResamplerKernel_h
-
-#include "core/platform/audio/AudioArray.h"
-
-namespace WebCore {
-
-class AudioResampler;
-
-// AudioResamplerKernel does resampling on a single mono channel.
-// It uses a simple linear interpolation for good performance.
-
-class AudioResamplerKernel {
-public:
- AudioResamplerKernel(AudioResampler*);
-
- // getSourcePointer() should be called each time before process() is called.
- // Given a number of frames to process (for subsequent call to process()), it returns a pointer and numberOfSourceFramesNeeded
- // where sample data should be copied. This sample data provides the input to the resampler when process() is called.
- // framesToProcess must be less than or equal to MaxFramesToProcess.
- float* getSourcePointer(size_t framesToProcess, size_t* numberOfSourceFramesNeeded);
-
- // process() resamples framesToProcess frames from the source into destination.
- // Each call to process() must be preceded by a call to getSourcePointer() so that source input may be supplied.
- // framesToProcess must be less than or equal to MaxFramesToProcess.
- void process(float* destination, size_t framesToProcess);
-
- // Resets the processing state.
- void reset();
-
- static const size_t MaxFramesToProcess;
-
-private:
- double rate() const;
-
- AudioResampler* m_resampler;
- AudioFloatArray m_sourceBuffer;
-
- // This is a (floating point) read index on the input stream.
- double m_virtualReadIndex;
-
- // We need to have continuity from one call of process() to the next.
- // m_lastValues stores the last two sample values from the last call to process().
- // m_fillIndex represents how many buffered samples we have which can be as many as 2.
- // For the first call to process() (or after reset()) there will be no buffered samples.
- float m_lastValues[2];
- unsigned m_fillIndex;
-};
-
-} // namespace WebCore
-
-#endif // AudioResamplerKernel_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/AudioSourceProvider.h b/chromium/third_party/WebKit/Source/core/platform/audio/AudioSourceProvider.h
deleted file mode 100644
index db82ba6e275..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/AudioSourceProvider.h
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef AudioSourceProvider_h
-#define AudioSourceProvider_h
-
-namespace WebCore {
-
-class AudioBus;
-class AudioSourceProviderClient;
-
-// Abstract base-class for a pull-model client.
-class AudioSourceProvider {
-public:
- // provideInput() gets called repeatedly to render time-slices of a continuous audio stream.
- virtual void provideInput(AudioBus* bus, size_t framesToProcess) = 0;
-
- // If a client is set, we call it back when the audio format is available or changes.
- virtual void setClient(AudioSourceProviderClient*) { };
-
- virtual ~AudioSourceProvider() { }
-};
-
-} // WebCore
-
-#endif // AudioSourceProvider_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/AudioSourceProviderClient.h b/chromium/third_party/WebKit/Source/core/platform/audio/AudioSourceProviderClient.h
deleted file mode 100644
index 28489e0e611..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/AudioSourceProviderClient.h
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright (C) 2011, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef AudioSourceProviderClient_h
-#define AudioSourceProviderClient_h
-
-namespace WebCore {
-
-class AudioSourceProviderClient {
-public:
- virtual void setFormat(size_t numberOfChannels, float sampleRate) = 0;
-protected:
- virtual ~AudioSourceProviderClient() { }
-};
-
-} // WebCore
-
-#endif // AudioSourceProviderClient_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/AudioUtilities.cpp b/chromium/third_party/WebKit/Source/core/platform/audio/AudioUtilities.cpp
deleted file mode 100644
index a76753e4f43..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/AudioUtilities.cpp
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright (C) 2010, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#if ENABLE(WEB_AUDIO)
-
-#include "core/platform/audio/AudioUtilities.h"
-#include "wtf/Assertions.h"
-#include "wtf/MathExtras.h"
-
-namespace WebCore {
-
-namespace AudioUtilities {
-
-float decibelsToLinear(float decibels)
-{
- return powf(10, 0.05f * decibels);
-}
-
-float linearToDecibels(float linear)
-{
- // It's not possible to calculate decibels for a zero linear value since it would be -Inf.
- // -1000.0 dB represents a very tiny linear value in case we ever reach this case.
- ASSERT(linear);
- if (!linear)
- return -1000;
-
- return 20 * log10f(linear);
-}
-
-double discreteTimeConstantForSampleRate(double timeConstant, double sampleRate)
-{
- return 1 - exp(-1 / (sampleRate * timeConstant));
-}
-
-size_t timeToSampleFrame(double time, double sampleRate)
-{
- return static_cast<size_t>(round(time * sampleRate));
-}
-} // AudioUtilites
-
-} // WebCore
-
-#endif // ENABLE(WEB_AUDIO)
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/AudioUtilities.h b/chromium/third_party/WebKit/Source/core/platform/audio/AudioUtilities.h
deleted file mode 100644
index c191e871c23..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/AudioUtilities.h
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright (C) 2010, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef AudioUtilities_h
-#define AudioUtilities_h
-
-namespace WebCore {
-
-namespace AudioUtilities {
-
-// Standard functions for converting to and from decibel values from linear.
-float linearToDecibels(float);
-float decibelsToLinear(float);
-
-// timeConstant is the time it takes a first-order linear time-invariant system
-// to reach the value 1 - 1/e (around 63.2%) given a step input response.
-// discreteTimeConstantForSampleRate() will return the discrete time-constant for the specific sampleRate.
-double discreteTimeConstantForSampleRate(double timeConstant, double sampleRate);
-
-// Convert the time to a sample frame at the given sample rate.
-size_t timeToSampleFrame(double time, double sampleRate);
-} // AudioUtilites
-
-} // WebCore
-
-#endif // AudioUtilities_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/Biquad.cpp b/chromium/third_party/WebKit/Source/core/platform/audio/Biquad.cpp
deleted file mode 100644
index 20c6487a63c..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/Biquad.cpp
+++ /dev/null
@@ -1,587 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#if ENABLE(WEB_AUDIO)
-
-#include "core/platform/audio/Biquad.h"
-
-#include <stdio.h>
-#include <algorithm>
-#include "core/platform/audio/DenormalDisabler.h"
-#include "wtf/MathExtras.h"
-
-#if OS(MACOSX)
-#include <Accelerate/Accelerate.h>
-#endif
-
-namespace WebCore {
-
-const int kBufferSize = 1024;
-
-Biquad::Biquad()
-{
-#if OS(MACOSX)
- // Allocate two samples more for filter history
- m_inputBuffer.allocate(kBufferSize + 2);
- m_outputBuffer.allocate(kBufferSize + 2);
-#endif
-
-#if USE(WEBAUDIO_IPP)
- int bufferSize;
- ippsIIRGetStateSize64f_BiQuad_32f(1, &bufferSize);
- m_ippInternalBuffer = ippsMalloc_8u(bufferSize);
-#endif // USE(WEBAUDIO_IPP)
-
- // Initialize as pass-thru (straight-wire, no filter effect)
- setNormalizedCoefficients(1, 0, 0, 1, 0, 0);
-
- reset(); // clear filter memory
-}
-
-Biquad::~Biquad()
-{
-#if USE(WEBAUDIO_IPP)
- ippsFree(m_ippInternalBuffer);
-#endif // USE(WEBAUDIO_IPP)
-}
-
-void Biquad::process(const float* sourceP, float* destP, size_t framesToProcess)
-{
-#if OS(MACOSX)
- // Use vecLib if available
- processFast(sourceP, destP, framesToProcess);
-
-#elif USE(WEBAUDIO_IPP)
- ippsIIR64f_32f(sourceP, destP, static_cast<int>(framesToProcess), m_biquadState);
-#else // USE(WEBAUDIO_IPP)
-
- int n = framesToProcess;
-
- // Create local copies of member variables
- double x1 = m_x1;
- double x2 = m_x2;
- double y1 = m_y1;
- double y2 = m_y2;
-
- double b0 = m_b0;
- double b1 = m_b1;
- double b2 = m_b2;
- double a1 = m_a1;
- double a2 = m_a2;
-
- while (n--) {
- // FIXME: this can be optimized by pipelining the multiply adds...
- float x = *sourceP++;
- float y = b0*x + b1*x1 + b2*x2 - a1*y1 - a2*y2;
-
- *destP++ = y;
-
- // Update state variables
- x2 = x1;
- x1 = x;
- y2 = y1;
- y1 = y;
- }
-
- // Local variables back to member. Flush denormals here so we
- // don't slow down the inner loop above.
- m_x1 = DenormalDisabler::flushDenormalFloatToZero(x1);
- m_x2 = DenormalDisabler::flushDenormalFloatToZero(x2);
- m_y1 = DenormalDisabler::flushDenormalFloatToZero(y1);
- m_y2 = DenormalDisabler::flushDenormalFloatToZero(y2);
-
- m_b0 = b0;
- m_b1 = b1;
- m_b2 = b2;
- m_a1 = a1;
- m_a2 = a2;
-#endif
-}
-
-#if OS(MACOSX)
-
-// Here we have optimized version using Accelerate.framework
-
-void Biquad::processFast(const float* sourceP, float* destP, size_t framesToProcess)
-{
- double filterCoefficients[5];
- filterCoefficients[0] = m_b0;
- filterCoefficients[1] = m_b1;
- filterCoefficients[2] = m_b2;
- filterCoefficients[3] = m_a1;
- filterCoefficients[4] = m_a2;
-
- double* inputP = m_inputBuffer.data();
- double* outputP = m_outputBuffer.data();
-
- double* input2P = inputP + 2;
- double* output2P = outputP + 2;
-
- // Break up processing into smaller slices (kBufferSize) if necessary.
-
- int n = framesToProcess;
-
- while (n > 0) {
- int framesThisTime = n < kBufferSize ? n : kBufferSize;
-
- // Copy input to input buffer
- for (int i = 0; i < framesThisTime; ++i)
- input2P[i] = *sourceP++;
-
- processSliceFast(inputP, outputP, filterCoefficients, framesThisTime);
-
- // Copy output buffer to output (converts float -> double).
- for (int i = 0; i < framesThisTime; ++i)
- *destP++ = static_cast<float>(output2P[i]);
-
- n -= framesThisTime;
- }
-}
-
-void Biquad::processSliceFast(double* sourceP, double* destP, double* coefficientsP, size_t framesToProcess)
-{
- // Use double-precision for filter stability
- vDSP_deq22D(sourceP, 1, coefficientsP, destP, 1, framesToProcess);
-
- // Save history. Note that sourceP and destP reference m_inputBuffer and m_outputBuffer respectively.
- // These buffers are allocated (in the constructor) with space for two extra samples so it's OK to access
- // array values two beyond framesToProcess.
- sourceP[0] = sourceP[framesToProcess - 2 + 2];
- sourceP[1] = sourceP[framesToProcess - 1 + 2];
- destP[0] = destP[framesToProcess - 2 + 2];
- destP[1] = destP[framesToProcess - 1 + 2];
-}
-
-#endif // OS(MACOSX)
-
-
-void Biquad::reset()
-{
-#if OS(MACOSX)
- // Two extra samples for filter history
- double* inputP = m_inputBuffer.data();
- inputP[0] = 0;
- inputP[1] = 0;
-
- double* outputP = m_outputBuffer.data();
- outputP[0] = 0;
- outputP[1] = 0;
-
-#elif USE(WEBAUDIO_IPP)
- int bufferSize;
- ippsIIRGetStateSize64f_BiQuad_32f(1, &bufferSize);
- ippsZero_8u(m_ippInternalBuffer, bufferSize);
-
-#else
- m_x1 = m_x2 = m_y1 = m_y2 = 0;
-#endif
-}
-
-void Biquad::setLowpassParams(double cutoff, double resonance)
-{
- // Limit cutoff to 0 to 1.
- cutoff = std::max(0.0, std::min(cutoff, 1.0));
-
- if (cutoff == 1) {
- // When cutoff is 1, the z-transform is 1.
- setNormalizedCoefficients(1, 0, 0,
- 1, 0, 0);
- } else if (cutoff > 0) {
- // Compute biquad coefficients for lowpass filter
- resonance = std::max(0.0, resonance); // can't go negative
- double g = pow(10.0, 0.05 * resonance);
- double d = sqrt((4 - sqrt(16 - 16 / (g * g))) / 2);
-
- double theta = piDouble * cutoff;
- double sn = 0.5 * d * sin(theta);
- double beta = 0.5 * (1 - sn) / (1 + sn);
- double gamma = (0.5 + beta) * cos(theta);
- double alpha = 0.25 * (0.5 + beta - gamma);
-
- double b0 = 2 * alpha;
- double b1 = 2 * 2 * alpha;
- double b2 = 2 * alpha;
- double a1 = 2 * -gamma;
- double a2 = 2 * beta;
-
- setNormalizedCoefficients(b0, b1, b2, 1, a1, a2);
- } else {
- // When cutoff is zero, nothing gets through the filter, so set
- // coefficients up correctly.
- setNormalizedCoefficients(0, 0, 0,
- 1, 0, 0);
- }
-}
-
-void Biquad::setHighpassParams(double cutoff, double resonance)
-{
- // Limit cutoff to 0 to 1.
- cutoff = std::max(0.0, std::min(cutoff, 1.0));
-
- if (cutoff == 1) {
- // The z-transform is 0.
- setNormalizedCoefficients(0, 0, 0,
- 1, 0, 0);
- } else if (cutoff > 0) {
- // Compute biquad coefficients for highpass filter
- resonance = std::max(0.0, resonance); // can't go negative
- double g = pow(10.0, 0.05 * resonance);
- double d = sqrt((4 - sqrt(16 - 16 / (g * g))) / 2);
-
- double theta = piDouble * cutoff;
- double sn = 0.5 * d * sin(theta);
- double beta = 0.5 * (1 - sn) / (1 + sn);
- double gamma = (0.5 + beta) * cos(theta);
- double alpha = 0.25 * (0.5 + beta + gamma);
-
- double b0 = 2 * alpha;
- double b1 = 2 * -2 * alpha;
- double b2 = 2 * alpha;
- double a1 = 2 * -gamma;
- double a2 = 2 * beta;
-
- setNormalizedCoefficients(b0, b1, b2, 1, a1, a2);
- } else {
- // When cutoff is zero, we need to be careful because the above
- // gives a quadratic divided by the same quadratic, with poles
- // and zeros on the unit circle in the same place. When cutoff
- // is zero, the z-transform is 1.
- setNormalizedCoefficients(1, 0, 0,
- 1, 0, 0);
- }
-}
-
-void Biquad::setNormalizedCoefficients(double b0, double b1, double b2, double a0, double a1, double a2)
-{
- double a0Inverse = 1 / a0;
-
- m_b0 = b0 * a0Inverse;
- m_b1 = b1 * a0Inverse;
- m_b2 = b2 * a0Inverse;
- m_a1 = a1 * a0Inverse;
- m_a2 = a2 * a0Inverse;
-
-#if USE(WEBAUDIO_IPP)
- Ipp64f taps[6];
- taps[0] = m_b0;
- taps[1] = m_b1;
- taps[2] = m_b2;
- taps[3] = 1;
- taps[4] = m_a1;
- taps[5] = m_a2;
- m_biquadState = 0;
-
- ippsIIRInit64f_BiQuad_32f(&m_biquadState, taps, 1, 0, m_ippInternalBuffer);
-#endif // USE(WEBAUDIO_IPP)
-}
-
-void Biquad::setLowShelfParams(double frequency, double dbGain)
-{
- // Clip frequencies to between 0 and 1, inclusive.
- frequency = std::max(0.0, std::min(frequency, 1.0));
-
- double A = pow(10.0, dbGain / 40);
-
- if (frequency == 1) {
- // The z-transform is a constant gain.
- setNormalizedCoefficients(A * A, 0, 0,
- 1, 0, 0);
- } else if (frequency > 0) {
- double w0 = piDouble * frequency;
- double S = 1; // filter slope (1 is max value)
- double alpha = 0.5 * sin(w0) * sqrt((A + 1 / A) * (1 / S - 1) + 2);
- double k = cos(w0);
- double k2 = 2 * sqrt(A) * alpha;
- double aPlusOne = A + 1;
- double aMinusOne = A - 1;
-
- double b0 = A * (aPlusOne - aMinusOne * k + k2);
- double b1 = 2 * A * (aMinusOne - aPlusOne * k);
- double b2 = A * (aPlusOne - aMinusOne * k - k2);
- double a0 = aPlusOne + aMinusOne * k + k2;
- double a1 = -2 * (aMinusOne + aPlusOne * k);
- double a2 = aPlusOne + aMinusOne * k - k2;
-
- setNormalizedCoefficients(b0, b1, b2, a0, a1, a2);
- } else {
- // When frequency is 0, the z-transform is 1.
- setNormalizedCoefficients(1, 0, 0,
- 1, 0, 0);
- }
-}
-
-void Biquad::setHighShelfParams(double frequency, double dbGain)
-{
- // Clip frequencies to between 0 and 1, inclusive.
- frequency = std::max(0.0, std::min(frequency, 1.0));
-
- double A = pow(10.0, dbGain / 40);
-
- if (frequency == 1) {
- // The z-transform is 1.
- setNormalizedCoefficients(1, 0, 0,
- 1, 0, 0);
- } else if (frequency > 0) {
- double w0 = piDouble * frequency;
- double S = 1; // filter slope (1 is max value)
- double alpha = 0.5 * sin(w0) * sqrt((A + 1 / A) * (1 / S - 1) + 2);
- double k = cos(w0);
- double k2 = 2 * sqrt(A) * alpha;
- double aPlusOne = A + 1;
- double aMinusOne = A - 1;
-
- double b0 = A * (aPlusOne + aMinusOne * k + k2);
- double b1 = -2 * A * (aMinusOne + aPlusOne * k);
- double b2 = A * (aPlusOne + aMinusOne * k - k2);
- double a0 = aPlusOne - aMinusOne * k + k2;
- double a1 = 2 * (aMinusOne - aPlusOne * k);
- double a2 = aPlusOne - aMinusOne * k - k2;
-
- setNormalizedCoefficients(b0, b1, b2, a0, a1, a2);
- } else {
- // When frequency = 0, the filter is just a gain, A^2.
- setNormalizedCoefficients(A * A, 0, 0,
- 1, 0, 0);
- }
-}
-
-void Biquad::setPeakingParams(double frequency, double Q, double dbGain)
-{
- // Clip frequencies to between 0 and 1, inclusive.
- frequency = std::max(0.0, std::min(frequency, 1.0));
-
- // Don't let Q go negative, which causes an unstable filter.
- Q = std::max(0.0, Q);
-
- double A = pow(10.0, dbGain / 40);
-
- if (frequency > 0 && frequency < 1) {
- if (Q > 0) {
- double w0 = piDouble * frequency;
- double alpha = sin(w0) / (2 * Q);
- double k = cos(w0);
-
- double b0 = 1 + alpha * A;
- double b1 = -2 * k;
- double b2 = 1 - alpha * A;
- double a0 = 1 + alpha / A;
- double a1 = -2 * k;
- double a2 = 1 - alpha / A;
-
- setNormalizedCoefficients(b0, b1, b2, a0, a1, a2);
- } else {
- // When Q = 0, the above formulas have problems. If we look at
- // the z-transform, we can see that the limit as Q->0 is A^2, so
- // set the filter that way.
- setNormalizedCoefficients(A * A, 0, 0,
- 1, 0, 0);
- }
- } else {
- // When frequency is 0 or 1, the z-transform is 1.
- setNormalizedCoefficients(1, 0, 0,
- 1, 0, 0);
- }
-}
-
-void Biquad::setAllpassParams(double frequency, double Q)
-{
- // Clip frequencies to between 0 and 1, inclusive.
- frequency = std::max(0.0, std::min(frequency, 1.0));
-
- // Don't let Q go negative, which causes an unstable filter.
- Q = std::max(0.0, Q);
-
- if (frequency > 0 && frequency < 1) {
- if (Q > 0) {
- double w0 = piDouble * frequency;
- double alpha = sin(w0) / (2 * Q);
- double k = cos(w0);
-
- double b0 = 1 - alpha;
- double b1 = -2 * k;
- double b2 = 1 + alpha;
- double a0 = 1 + alpha;
- double a1 = -2 * k;
- double a2 = 1 - alpha;
-
- setNormalizedCoefficients(b0, b1, b2, a0, a1, a2);
- } else {
- // When Q = 0, the above formulas have problems. If we look at
- // the z-transform, we can see that the limit as Q->0 is -1, so
- // set the filter that way.
- setNormalizedCoefficients(-1, 0, 0,
- 1, 0, 0);
- }
- } else {
- // When frequency is 0 or 1, the z-transform is 1.
- setNormalizedCoefficients(1, 0, 0,
- 1, 0, 0);
- }
-}
-
-void Biquad::setNotchParams(double frequency, double Q)
-{
- // Clip frequencies to between 0 and 1, inclusive.
- frequency = std::max(0.0, std::min(frequency, 1.0));
-
- // Don't let Q go negative, which causes an unstable filter.
- Q = std::max(0.0, Q);
-
- if (frequency > 0 && frequency < 1) {
- if (Q > 0) {
- double w0 = piDouble * frequency;
- double alpha = sin(w0) / (2 * Q);
- double k = cos(w0);
-
- double b0 = 1;
- double b1 = -2 * k;
- double b2 = 1;
- double a0 = 1 + alpha;
- double a1 = -2 * k;
- double a2 = 1 - alpha;
-
- setNormalizedCoefficients(b0, b1, b2, a0, a1, a2);
- } else {
- // When Q = 0, the above formulas have problems. If we look at
- // the z-transform, we can see that the limit as Q->0 is 0, so
- // set the filter that way.
- setNormalizedCoefficients(0, 0, 0,
- 1, 0, 0);
- }
- } else {
- // When frequency is 0 or 1, the z-transform is 1.
- setNormalizedCoefficients(1, 0, 0,
- 1, 0, 0);
- }
-}
-
-void Biquad::setBandpassParams(double frequency, double Q)
-{
- // No negative frequencies allowed.
- frequency = std::max(0.0, frequency);
-
- // Don't let Q go negative, which causes an unstable filter.
- Q = std::max(0.0, Q);
-
- if (frequency > 0 && frequency < 1) {
- double w0 = piDouble * frequency;
- if (Q > 0) {
- double alpha = sin(w0) / (2 * Q);
- double k = cos(w0);
-
- double b0 = alpha;
- double b1 = 0;
- double b2 = -alpha;
- double a0 = 1 + alpha;
- double a1 = -2 * k;
- double a2 = 1 - alpha;
-
- setNormalizedCoefficients(b0, b1, b2, a0, a1, a2);
- } else {
- // When Q = 0, the above formulas have problems. If we look at
- // the z-transform, we can see that the limit as Q->0 is 1, so
- // set the filter that way.
- setNormalizedCoefficients(1, 0, 0,
- 1, 0, 0);
- }
- } else {
- // When the cutoff is zero, the z-transform approaches 0, if Q
- // > 0. When both Q and cutoff are zero, the z-transform is
- // pretty much undefined. What should we do in this case?
- // For now, just make the filter 0. When the cutoff is 1, the
- // z-transform also approaches 0.
- setNormalizedCoefficients(0, 0, 0,
- 1, 0, 0);
- }
-}
-
-void Biquad::setZeroPolePairs(const Complex &zero, const Complex &pole)
-{
- double b0 = 1;
- double b1 = -2 * zero.real();
-
- double zeroMag = abs(zero);
- double b2 = zeroMag * zeroMag;
-
- double a1 = -2 * pole.real();
-
- double poleMag = abs(pole);
- double a2 = poleMag * poleMag;
- setNormalizedCoefficients(b0, b1, b2, 1, a1, a2);
-}
-
-void Biquad::setAllpassPole(const Complex &pole)
-{
- Complex zero = Complex(1, 0) / pole;
- setZeroPolePairs(zero, pole);
-}
-
-void Biquad::getFrequencyResponse(int nFrequencies,
- const float* frequency,
- float* magResponse,
- float* phaseResponse)
-{
- // Evaluate the Z-transform of the filter at given normalized
- // frequency from 0 to 1. (1 corresponds to the Nyquist
- // frequency.)
- //
- // The z-transform of the filter is
- //
- // H(z) = (b0 + b1*z^(-1) + b2*z^(-2))/(1 + a1*z^(-1) + a2*z^(-2))
- //
- // Evaluate as
- //
- // b0 + (b1 + b2*z1)*z1
- // --------------------
- // 1 + (a1 + a2*z1)*z1
- //
- // with z1 = 1/z and z = exp(j*pi*frequency). Hence z1 = exp(-j*pi*frequency)
-
- // Make local copies of the coefficients as a micro-optimization.
- double b0 = m_b0;
- double b1 = m_b1;
- double b2 = m_b2;
- double a1 = m_a1;
- double a2 = m_a2;
-
- for (int k = 0; k < nFrequencies; ++k) {
- double omega = -piDouble * frequency[k];
- Complex z = Complex(cos(omega), sin(omega));
- Complex numerator = b0 + (b1 + b2 * z) * z;
- Complex denominator = Complex(1, 0) + (a1 + a2 * z) * z;
- Complex response = numerator / denominator;
- magResponse[k] = static_cast<float>(abs(response));
- phaseResponse[k] = static_cast<float>(atan2(imag(response), real(response)));
- }
-}
-
-} // namespace WebCore
-
-#endif // ENABLE(WEB_AUDIO)
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/Biquad.h b/chromium/third_party/WebKit/Source/core/platform/audio/Biquad.h
deleted file mode 100644
index ae0baf962c2..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/Biquad.h
+++ /dev/null
@@ -1,117 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef Biquad_h
-#define Biquad_h
-
-#include <sys/types.h>
-#include "core/platform/audio/AudioArray.h"
-#include "wtf/Complex.h"
-
-#if USE(WEBAUDIO_IPP)
-#include <ipps.h>
-#endif // USE(WEBAUDIO_IPP)
-
-namespace WebCore {
-
-// A basic biquad (two-zero / two-pole digital filter)
-//
-// It can be configured to a number of common and very useful filters:
-// lowpass, highpass, shelving, parameteric, notch, allpass, ...
-
-class Biquad {
-public:
- Biquad();
- virtual ~Biquad();
-
- void process(const float* sourceP, float* destP, size_t framesToProcess);
-
- // frequency is 0 - 1 normalized, resonance and dbGain are in decibels.
- // Q is a unitless quality factor.
- void setLowpassParams(double frequency, double resonance);
- void setHighpassParams(double frequency, double resonance);
- void setBandpassParams(double frequency, double Q);
- void setLowShelfParams(double frequency, double dbGain);
- void setHighShelfParams(double frequency, double dbGain);
- void setPeakingParams(double frequency, double Q, double dbGain);
- void setAllpassParams(double frequency, double Q);
- void setNotchParams(double frequency, double Q);
-
- // Set the biquad coefficients given a single zero (other zero will be conjugate)
- // and a single pole (other pole will be conjugate)
- void setZeroPolePairs(const Complex& zero, const Complex& pole);
-
- // Set the biquad coefficients given a single pole (other pole will be conjugate)
- // (The zeroes will be the inverse of the poles)
- void setAllpassPole(const Complex& pole);
-
- // Resets filter state
- void reset();
-
- // Filter response at a set of n frequencies. The magnitude and
- // phase response are returned in magResponse and phaseResponse.
- // The phase response is in radians.
- void getFrequencyResponse(int nFrequencies,
- const float* frequency,
- float* magResponse,
- float* phaseResponse);
-private:
- void setNormalizedCoefficients(double b0, double b1, double b2, double a0, double a1, double a2);
-
- // Filter coefficients. The filter is defined as
- //
- // y[n] + m_a1*y[n-1] + m_a2*y[n-2] = m_b0*x[n] + m_b1*x[n-1] + m_b2*x[n-2].
- double m_b0;
- double m_b1;
- double m_b2;
- double m_a1;
- double m_a2;
-
-#if OS(MACOSX)
- void processFast(const float* sourceP, float* destP, size_t framesToProcess);
- void processSliceFast(double* sourceP, double* destP, double* coefficientsP, size_t framesToProcess);
-
- AudioDoubleArray m_inputBuffer;
- AudioDoubleArray m_outputBuffer;
-
-#elif USE(WEBAUDIO_IPP)
- IppsIIRState64f_32f* m_biquadState;
- Ipp8u* m_ippInternalBuffer;
-
-#else
- // Filter memory
- double m_x1; // input delayed by 1 sample
- double m_x2; // input delayed by 2 samples
- double m_y1; // output delayed by 1 sample
- double m_y2; // output delayed by 2 samples
-#endif
-};
-
-} // namespace WebCore
-
-#endif // Biquad_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/Cone.cpp b/chromium/third_party/WebKit/Source/core/platform/audio/Cone.cpp
deleted file mode 100644
index c38138a6f60..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/Cone.cpp
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#if ENABLE(WEB_AUDIO)
-
-#include "core/platform/audio/Cone.h"
-#include "wtf/MathExtras.h"
-
-namespace WebCore {
-
-ConeEffect::ConeEffect()
- : m_innerAngle(360.0)
- , m_outerAngle(360.0)
- , m_outerGain(0.0)
-{
-}
-
-double ConeEffect::gain(FloatPoint3D sourcePosition, FloatPoint3D sourceOrientation, FloatPoint3D listenerPosition)
-{
- if (sourceOrientation.isZero() || ((m_innerAngle == 360.0) && (m_outerAngle == 360.0)))
- return 1.0; // no cone specified - unity gain
-
- // Normalized source-listener vector
- FloatPoint3D sourceToListener = listenerPosition - sourcePosition;
- sourceToListener.normalize();
-
- FloatPoint3D normalizedSourceOrientation = sourceOrientation;
- normalizedSourceOrientation.normalize();
-
- // Angle between the source orientation vector and the source-listener vector
- double dotProduct = sourceToListener.dot(normalizedSourceOrientation);
- double angle = 180.0 * acos(dotProduct) / piDouble;
- double absAngle = fabs(angle);
-
- // Divide by 2.0 here since API is entire angle (not half-angle)
- double absInnerAngle = fabs(m_innerAngle) / 2.0;
- double absOuterAngle = fabs(m_outerAngle) / 2.0;
- double gain = 1.0;
-
- if (absAngle <= absInnerAngle)
- // No attenuation
- gain = 1.0;
- else if (absAngle >= absOuterAngle)
- // Max attenuation
- gain = m_outerGain;
- else {
- // Between inner and outer cones
- // inner -> outer, x goes from 0 -> 1
- double x = (absAngle - absInnerAngle) / (absOuterAngle - absInnerAngle);
- gain = (1.0 - x) + m_outerGain * x;
- }
-
- return gain;
-}
-
-} // namespace WebCore
-
-#endif // ENABLE(WEB_AUDIO)
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/Cone.h b/chromium/third_party/WebKit/Source/core/platform/audio/Cone.h
deleted file mode 100644
index 4435e21299c..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/Cone.h
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef Cone_h
-#define Cone_h
-
-#include "core/platform/graphics/FloatPoint3D.h"
-
-namespace WebCore {
-
-// Cone gain is defined according to the OpenAL specification
-
-class ConeEffect {
-public:
- ConeEffect();
-
- // Returns scalar gain for the given source/listener positions/orientations
- double gain(FloatPoint3D sourcePosition, FloatPoint3D sourceOrientation, FloatPoint3D listenerPosition);
-
- // Angles in degrees
- void setInnerAngle(double innerAngle) { m_innerAngle = innerAngle; }
- double innerAngle() const { return m_innerAngle; }
-
- void setOuterAngle(double outerAngle) { m_outerAngle = outerAngle; }
- double outerAngle() const { return m_outerAngle; }
-
- void setOuterGain(double outerGain) { m_outerGain = outerGain; }
- double outerGain() const { return m_outerGain; }
-
-protected:
- double m_innerAngle;
- double m_outerAngle;
- double m_outerGain;
-};
-
-} // namespace WebCore
-
-#endif // Cone_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/DenormalDisabler.h b/chromium/third_party/WebKit/Source/core/platform/audio/DenormalDisabler.h
deleted file mode 100644
index 802cb73c864..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/DenormalDisabler.h
+++ /dev/null
@@ -1,125 +0,0 @@
-/*
- * Copyright (C) 2011, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef DenormalDisabler_h
-#define DenormalDisabler_h
-
-#include "wtf/CPU.h"
-#include "wtf/MathExtras.h"
-#include <float.h>
-
-namespace WebCore {
-
-// Deal with denormals. They can very seriously impact performance on x86.
-
-// Define HAVE_DENORMAL if we support flushing denormals to zero.
-#if OS(WIN) && COMPILER(MSVC)
-#define HAVE_DENORMAL 1
-#endif
-
-#if COMPILER(GCC) && (CPU(X86) || CPU(X86_64))
-#define HAVE_DENORMAL 1
-#endif
-
-#if HAVE(DENORMAL)
-class DenormalDisabler {
-public:
- DenormalDisabler()
- : m_savedCSR(0)
- {
-#if OS(WIN) && COMPILER(MSVC)
- // Save the current state, and set mode to flush denormals.
- //
- // http://stackoverflow.com/questions/637175/possible-bug-in-controlfp-s-may-not-restore-control-word-correctly
- _controlfp_s(&m_savedCSR, 0, 0);
- unsigned int unused;
- _controlfp_s(&unused, _DN_FLUSH, _MCW_DN);
-#else
- m_savedCSR = getCSR();
- setCSR(m_savedCSR | 0x8040);
-#endif
- }
-
- ~DenormalDisabler()
- {
-#if OS(WIN) && COMPILER(MSVC)
- unsigned int unused;
- _controlfp_s(&unused, m_savedCSR, _MCW_DN);
-#else
- setCSR(m_savedCSR);
-#endif
- }
-
- // This is a nop if we can flush denormals to zero in hardware.
- static inline float flushDenormalFloatToZero(float f)
- {
-#if OS(WIN) && COMPILER(MSVC) && (!_M_IX86_FP)
- // For systems using x87 instead of sse, there's no hardware support
- // to flush denormals automatically. Hence, we need to flush
- // denormals to zero manually.
- return (fabs(f) < FLT_MIN) ? 0.0f : f;
-#else
- return f;
-#endif
- }
-private:
-#if COMPILER(GCC) && (CPU(X86) || CPU(X86_64))
- inline int getCSR()
- {
- int result;
- asm volatile("stmxcsr %0" : "=m" (result));
- return result;
- }
-
- inline void setCSR(int a)
- {
- int temp = a;
- asm volatile("ldmxcsr %0" : : "m" (temp));
- }
-
-#endif
-
- unsigned int m_savedCSR;
-};
-
-#else
-// FIXME: add implementations for other architectures and compilers
-class DenormalDisabler {
-public:
- DenormalDisabler() { }
-
- // Assume the worst case that other architectures and compilers
- // need to flush denormals to zero manually.
- static inline float flushDenormalFloatToZero(float f)
- {
- return (fabs(f) < FLT_MIN) ? 0.0f : f;
- }
-};
-
-#endif
-
-} // WebCore
-
-#undef HAVE_DENORMAL
-#endif // DenormalDisabler_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/DirectConvolver.cpp b/chromium/third_party/WebKit/Source/core/platform/audio/DirectConvolver.cpp
deleted file mode 100644
index d74fea43819..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/DirectConvolver.cpp
+++ /dev/null
@@ -1,386 +0,0 @@
-/*
- * Copyright (C) 2012 Intel Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#if ENABLE(WEB_AUDIO)
-
-#include "core/platform/audio/DirectConvolver.h"
-
-#if OS(MACOSX)
-#include <Accelerate/Accelerate.h>
-#endif
-
-#include "core/platform/audio/VectorMath.h"
-#include "wtf/CPU.h"
-
-namespace WebCore {
-
-using namespace VectorMath;
-
-DirectConvolver::DirectConvolver(size_t inputBlockSize)
- : m_inputBlockSize(inputBlockSize)
-#if USE(WEBAUDIO_IPP)
- , m_overlayBuffer(inputBlockSize)
-#endif // USE(WEBAUDIO_IPP)
- , m_buffer(inputBlockSize * 2)
-{
-}
-
-void DirectConvolver::process(AudioFloatArray* convolutionKernel, const float* sourceP, float* destP, size_t framesToProcess)
-{
- ASSERT(framesToProcess == m_inputBlockSize);
- if (framesToProcess != m_inputBlockSize)
- return;
-
- // Only support kernelSize <= m_inputBlockSize
- size_t kernelSize = convolutionKernel->size();
- ASSERT(kernelSize <= m_inputBlockSize);
- if (kernelSize > m_inputBlockSize)
- return;
-
- float* kernelP = convolutionKernel->data();
-
- // Sanity check
- bool isCopyGood = kernelP && sourceP && destP && m_buffer.data();
- ASSERT(isCopyGood);
- if (!isCopyGood)
- return;
-
-#if USE(WEBAUDIO_IPP)
- float* outputBuffer = m_buffer.data();
- float* overlayBuffer = m_overlayBuffer.data();
- bool isCopyGood2 = overlayBuffer && m_overlayBuffer.size() >= kernelSize && m_buffer.size() == m_inputBlockSize * 2;
- ASSERT(isCopyGood2);
- if (!isCopyGood2)
- return;
-
- ippsConv_32f(static_cast<const Ipp32f*>(sourceP), framesToProcess, static_cast<Ipp32f*>(kernelP), kernelSize, static_cast<Ipp32f*>(outputBuffer));
-
- vadd(outputBuffer, 1, overlayBuffer, 1, destP, 1, framesToProcess);
- memcpy(overlayBuffer, outputBuffer + m_inputBlockSize, sizeof(float) * kernelSize);
-#else
- float* inputP = m_buffer.data() + m_inputBlockSize;
-
- // Copy samples to 2nd half of input buffer.
- memcpy(inputP, sourceP, sizeof(float) * framesToProcess);
-
-#if OS(MACOSX)
-#if CPU(X86)
- conv(inputP - kernelSize + 1, 1, kernelP + kernelSize - 1, -1, destP, 1, framesToProcess, kernelSize);
-#else
- vDSP_conv(inputP - kernelSize + 1, 1, kernelP + kernelSize - 1, -1, destP, 1, framesToProcess, kernelSize);
-#endif // CPU(X86)
-#else
- // FIXME: The macro can be further optimized to avoid pipeline stalls. One possibility is to maintain 4 separate sums and change the macro to CONVOLVE_FOUR_SAMPLES.
-#define CONVOLVE_ONE_SAMPLE \
- sum += inputP[i - j] * kernelP[j]; \
- j++;
-
- size_t i = 0;
- while (i < framesToProcess) {
- size_t j = 0;
- float sum = 0;
-
- // FIXME: SSE optimization may be applied here.
- if (kernelSize == 32) {
- CONVOLVE_ONE_SAMPLE // 1
- CONVOLVE_ONE_SAMPLE // 2
- CONVOLVE_ONE_SAMPLE // 3
- CONVOLVE_ONE_SAMPLE // 4
- CONVOLVE_ONE_SAMPLE // 5
- CONVOLVE_ONE_SAMPLE // 6
- CONVOLVE_ONE_SAMPLE // 7
- CONVOLVE_ONE_SAMPLE // 8
- CONVOLVE_ONE_SAMPLE // 9
- CONVOLVE_ONE_SAMPLE // 10
-
- CONVOLVE_ONE_SAMPLE // 11
- CONVOLVE_ONE_SAMPLE // 12
- CONVOLVE_ONE_SAMPLE // 13
- CONVOLVE_ONE_SAMPLE // 14
- CONVOLVE_ONE_SAMPLE // 15
- CONVOLVE_ONE_SAMPLE // 16
- CONVOLVE_ONE_SAMPLE // 17
- CONVOLVE_ONE_SAMPLE // 18
- CONVOLVE_ONE_SAMPLE // 19
- CONVOLVE_ONE_SAMPLE // 20
-
- CONVOLVE_ONE_SAMPLE // 21
- CONVOLVE_ONE_SAMPLE // 22
- CONVOLVE_ONE_SAMPLE // 23
- CONVOLVE_ONE_SAMPLE // 24
- CONVOLVE_ONE_SAMPLE // 25
- CONVOLVE_ONE_SAMPLE // 26
- CONVOLVE_ONE_SAMPLE // 27
- CONVOLVE_ONE_SAMPLE // 28
- CONVOLVE_ONE_SAMPLE // 29
- CONVOLVE_ONE_SAMPLE // 30
-
- CONVOLVE_ONE_SAMPLE // 31
- CONVOLVE_ONE_SAMPLE // 32
-
- } else if (kernelSize == 64) {
- CONVOLVE_ONE_SAMPLE // 1
- CONVOLVE_ONE_SAMPLE // 2
- CONVOLVE_ONE_SAMPLE // 3
- CONVOLVE_ONE_SAMPLE // 4
- CONVOLVE_ONE_SAMPLE // 5
- CONVOLVE_ONE_SAMPLE // 6
- CONVOLVE_ONE_SAMPLE // 7
- CONVOLVE_ONE_SAMPLE // 8
- CONVOLVE_ONE_SAMPLE // 9
- CONVOLVE_ONE_SAMPLE // 10
-
- CONVOLVE_ONE_SAMPLE // 11
- CONVOLVE_ONE_SAMPLE // 12
- CONVOLVE_ONE_SAMPLE // 13
- CONVOLVE_ONE_SAMPLE // 14
- CONVOLVE_ONE_SAMPLE // 15
- CONVOLVE_ONE_SAMPLE // 16
- CONVOLVE_ONE_SAMPLE // 17
- CONVOLVE_ONE_SAMPLE // 18
- CONVOLVE_ONE_SAMPLE // 19
- CONVOLVE_ONE_SAMPLE // 20
-
- CONVOLVE_ONE_SAMPLE // 21
- CONVOLVE_ONE_SAMPLE // 22
- CONVOLVE_ONE_SAMPLE // 23
- CONVOLVE_ONE_SAMPLE // 24
- CONVOLVE_ONE_SAMPLE // 25
- CONVOLVE_ONE_SAMPLE // 26
- CONVOLVE_ONE_SAMPLE // 27
- CONVOLVE_ONE_SAMPLE // 28
- CONVOLVE_ONE_SAMPLE // 29
- CONVOLVE_ONE_SAMPLE // 30
-
- CONVOLVE_ONE_SAMPLE // 31
- CONVOLVE_ONE_SAMPLE // 32
- CONVOLVE_ONE_SAMPLE // 33
- CONVOLVE_ONE_SAMPLE // 34
- CONVOLVE_ONE_SAMPLE // 35
- CONVOLVE_ONE_SAMPLE // 36
- CONVOLVE_ONE_SAMPLE // 37
- CONVOLVE_ONE_SAMPLE // 38
- CONVOLVE_ONE_SAMPLE // 39
- CONVOLVE_ONE_SAMPLE // 40
-
- CONVOLVE_ONE_SAMPLE // 41
- CONVOLVE_ONE_SAMPLE // 42
- CONVOLVE_ONE_SAMPLE // 43
- CONVOLVE_ONE_SAMPLE // 44
- CONVOLVE_ONE_SAMPLE // 45
- CONVOLVE_ONE_SAMPLE // 46
- CONVOLVE_ONE_SAMPLE // 47
- CONVOLVE_ONE_SAMPLE // 48
- CONVOLVE_ONE_SAMPLE // 49
- CONVOLVE_ONE_SAMPLE // 50
-
- CONVOLVE_ONE_SAMPLE // 51
- CONVOLVE_ONE_SAMPLE // 52
- CONVOLVE_ONE_SAMPLE // 53
- CONVOLVE_ONE_SAMPLE // 54
- CONVOLVE_ONE_SAMPLE // 55
- CONVOLVE_ONE_SAMPLE // 56
- CONVOLVE_ONE_SAMPLE // 57
- CONVOLVE_ONE_SAMPLE // 58
- CONVOLVE_ONE_SAMPLE // 59
- CONVOLVE_ONE_SAMPLE // 60
-
- CONVOLVE_ONE_SAMPLE // 61
- CONVOLVE_ONE_SAMPLE // 62
- CONVOLVE_ONE_SAMPLE // 63
- CONVOLVE_ONE_SAMPLE // 64
-
- } else if (kernelSize == 128) {
- CONVOLVE_ONE_SAMPLE // 1
- CONVOLVE_ONE_SAMPLE // 2
- CONVOLVE_ONE_SAMPLE // 3
- CONVOLVE_ONE_SAMPLE // 4
- CONVOLVE_ONE_SAMPLE // 5
- CONVOLVE_ONE_SAMPLE // 6
- CONVOLVE_ONE_SAMPLE // 7
- CONVOLVE_ONE_SAMPLE // 8
- CONVOLVE_ONE_SAMPLE // 9
- CONVOLVE_ONE_SAMPLE // 10
-
- CONVOLVE_ONE_SAMPLE // 11
- CONVOLVE_ONE_SAMPLE // 12
- CONVOLVE_ONE_SAMPLE // 13
- CONVOLVE_ONE_SAMPLE // 14
- CONVOLVE_ONE_SAMPLE // 15
- CONVOLVE_ONE_SAMPLE // 16
- CONVOLVE_ONE_SAMPLE // 17
- CONVOLVE_ONE_SAMPLE // 18
- CONVOLVE_ONE_SAMPLE // 19
- CONVOLVE_ONE_SAMPLE // 20
-
- CONVOLVE_ONE_SAMPLE // 21
- CONVOLVE_ONE_SAMPLE // 22
- CONVOLVE_ONE_SAMPLE // 23
- CONVOLVE_ONE_SAMPLE // 24
- CONVOLVE_ONE_SAMPLE // 25
- CONVOLVE_ONE_SAMPLE // 26
- CONVOLVE_ONE_SAMPLE // 27
- CONVOLVE_ONE_SAMPLE // 28
- CONVOLVE_ONE_SAMPLE // 29
- CONVOLVE_ONE_SAMPLE // 30
-
- CONVOLVE_ONE_SAMPLE // 31
- CONVOLVE_ONE_SAMPLE // 32
- CONVOLVE_ONE_SAMPLE // 33
- CONVOLVE_ONE_SAMPLE // 34
- CONVOLVE_ONE_SAMPLE // 35
- CONVOLVE_ONE_SAMPLE // 36
- CONVOLVE_ONE_SAMPLE // 37
- CONVOLVE_ONE_SAMPLE // 38
- CONVOLVE_ONE_SAMPLE // 39
- CONVOLVE_ONE_SAMPLE // 40
-
- CONVOLVE_ONE_SAMPLE // 41
- CONVOLVE_ONE_SAMPLE // 42
- CONVOLVE_ONE_SAMPLE // 43
- CONVOLVE_ONE_SAMPLE // 44
- CONVOLVE_ONE_SAMPLE // 45
- CONVOLVE_ONE_SAMPLE // 46
- CONVOLVE_ONE_SAMPLE // 47
- CONVOLVE_ONE_SAMPLE // 48
- CONVOLVE_ONE_SAMPLE // 49
- CONVOLVE_ONE_SAMPLE // 50
-
- CONVOLVE_ONE_SAMPLE // 51
- CONVOLVE_ONE_SAMPLE // 52
- CONVOLVE_ONE_SAMPLE // 53
- CONVOLVE_ONE_SAMPLE // 54
- CONVOLVE_ONE_SAMPLE // 55
- CONVOLVE_ONE_SAMPLE // 56
- CONVOLVE_ONE_SAMPLE // 57
- CONVOLVE_ONE_SAMPLE // 58
- CONVOLVE_ONE_SAMPLE // 59
- CONVOLVE_ONE_SAMPLE // 60
-
- CONVOLVE_ONE_SAMPLE // 61
- CONVOLVE_ONE_SAMPLE // 62
- CONVOLVE_ONE_SAMPLE // 63
- CONVOLVE_ONE_SAMPLE // 64
- CONVOLVE_ONE_SAMPLE // 65
- CONVOLVE_ONE_SAMPLE // 66
- CONVOLVE_ONE_SAMPLE // 67
- CONVOLVE_ONE_SAMPLE // 68
- CONVOLVE_ONE_SAMPLE // 69
- CONVOLVE_ONE_SAMPLE // 70
-
- CONVOLVE_ONE_SAMPLE // 71
- CONVOLVE_ONE_SAMPLE // 72
- CONVOLVE_ONE_SAMPLE // 73
- CONVOLVE_ONE_SAMPLE // 74
- CONVOLVE_ONE_SAMPLE // 75
- CONVOLVE_ONE_SAMPLE // 76
- CONVOLVE_ONE_SAMPLE // 77
- CONVOLVE_ONE_SAMPLE // 78
- CONVOLVE_ONE_SAMPLE // 79
- CONVOLVE_ONE_SAMPLE // 80
-
- CONVOLVE_ONE_SAMPLE // 81
- CONVOLVE_ONE_SAMPLE // 82
- CONVOLVE_ONE_SAMPLE // 83
- CONVOLVE_ONE_SAMPLE // 84
- CONVOLVE_ONE_SAMPLE // 85
- CONVOLVE_ONE_SAMPLE // 86
- CONVOLVE_ONE_SAMPLE // 87
- CONVOLVE_ONE_SAMPLE // 88
- CONVOLVE_ONE_SAMPLE // 89
- CONVOLVE_ONE_SAMPLE // 90
-
- CONVOLVE_ONE_SAMPLE // 91
- CONVOLVE_ONE_SAMPLE // 92
- CONVOLVE_ONE_SAMPLE // 93
- CONVOLVE_ONE_SAMPLE // 94
- CONVOLVE_ONE_SAMPLE // 95
- CONVOLVE_ONE_SAMPLE // 96
- CONVOLVE_ONE_SAMPLE // 97
- CONVOLVE_ONE_SAMPLE // 98
- CONVOLVE_ONE_SAMPLE // 99
- CONVOLVE_ONE_SAMPLE // 100
-
- CONVOLVE_ONE_SAMPLE // 101
- CONVOLVE_ONE_SAMPLE // 102
- CONVOLVE_ONE_SAMPLE // 103
- CONVOLVE_ONE_SAMPLE // 104
- CONVOLVE_ONE_SAMPLE // 105
- CONVOLVE_ONE_SAMPLE // 106
- CONVOLVE_ONE_SAMPLE // 107
- CONVOLVE_ONE_SAMPLE // 108
- CONVOLVE_ONE_SAMPLE // 109
- CONVOLVE_ONE_SAMPLE // 110
-
- CONVOLVE_ONE_SAMPLE // 111
- CONVOLVE_ONE_SAMPLE // 112
- CONVOLVE_ONE_SAMPLE // 113
- CONVOLVE_ONE_SAMPLE // 114
- CONVOLVE_ONE_SAMPLE // 115
- CONVOLVE_ONE_SAMPLE // 116
- CONVOLVE_ONE_SAMPLE // 117
- CONVOLVE_ONE_SAMPLE // 118
- CONVOLVE_ONE_SAMPLE // 119
- CONVOLVE_ONE_SAMPLE // 120
-
- CONVOLVE_ONE_SAMPLE // 121
- CONVOLVE_ONE_SAMPLE // 122
- CONVOLVE_ONE_SAMPLE // 123
- CONVOLVE_ONE_SAMPLE // 124
- CONVOLVE_ONE_SAMPLE // 125
- CONVOLVE_ONE_SAMPLE // 126
- CONVOLVE_ONE_SAMPLE // 127
- CONVOLVE_ONE_SAMPLE // 128
- } else {
- while (j < kernelSize) {
- // Non-optimized using actual while loop.
- CONVOLVE_ONE_SAMPLE
- }
- }
- destP[i++] = sum;
- }
-#endif // OS(MACOSX)
-
- // Copy 2nd half of input buffer to 1st half.
- memcpy(m_buffer.data(), inputP, sizeof(float) * framesToProcess);
-#endif
-}
-
-void DirectConvolver::reset()
-{
- m_buffer.zero();
-#if USE(WEBAUDIO_IPP)
- m_overlayBuffer.zero();
-#endif // USE(WEBAUDIO_IPP)
-}
-
-} // namespace WebCore
-
-#endif // ENABLE(WEB_AUDIO)
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/DirectConvolver.h b/chromium/third_party/WebKit/Source/core/platform/audio/DirectConvolver.h
deleted file mode 100644
index 0528d7cb6ce..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/DirectConvolver.h
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Copyright (C) 2012 Intel Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef DirectConvolver_h
-#define DirectConvolver_h
-
-#include "core/platform/audio/AudioArray.h"
-
-#if USE(WEBAUDIO_IPP)
-#include <ipps.h>
-#endif // USE(WEBAUDIO_IPP)
-
-namespace WebCore {
-
-class DirectConvolver {
-public:
- DirectConvolver(size_t inputBlockSize);
-
- void process(AudioFloatArray* convolutionKernel, const float* sourceP, float* destP, size_t framesToProcess);
-
- void reset();
-
-private:
- size_t m_inputBlockSize;
-
-#if USE(WEBAUDIO_IPP)
- AudioFloatArray m_overlayBuffer;
-#endif // USE(WEBAUDIO_IPP)
- AudioFloatArray m_buffer;
-};
-
-} // namespace WebCore
-
-#endif // DirectConvolver_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/Distance.cpp b/chromium/third_party/WebKit/Source/core/platform/audio/Distance.cpp
deleted file mode 100644
index 91a4a5f7220..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/Distance.cpp
+++ /dev/null
@@ -1,92 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#if ENABLE(WEB_AUDIO)
-
-#include "core/platform/audio/Distance.h"
-#include "wtf/Assertions.h"
-
-#include <math.h>
-#include <algorithm>
-
-using namespace std;
-
-namespace WebCore {
-
-DistanceEffect::DistanceEffect()
- : m_model(ModelInverse)
- , m_isClamped(true)
- , m_refDistance(1.0)
- , m_maxDistance(10000.0)
- , m_rolloffFactor(1.0)
-{
-}
-
-double DistanceEffect::gain(double distance)
-{
- // don't go beyond maximum distance
- distance = min(distance, m_maxDistance);
-
- // if clamped, don't get closer than reference distance
- if (m_isClamped)
- distance = max(distance, m_refDistance);
-
- switch (m_model) {
- case ModelLinear:
- return linearGain(distance);
- case ModelInverse:
- return inverseGain(distance);
- case ModelExponential:
- return exponentialGain(distance);
- }
- ASSERT_NOT_REACHED();
- return 0.0;
-}
-
-double DistanceEffect::linearGain(double distance)
-{
- // We want a gain that decreases linearly from m_refDistance to
- // m_maxDistance. The gain is 1 at m_refDistance.
- return (1.0 - m_rolloffFactor * (distance - m_refDistance) / (m_maxDistance - m_refDistance));
-}
-
-double DistanceEffect::inverseGain(double distance)
-{
- return m_refDistance / (m_refDistance + m_rolloffFactor * (distance - m_refDistance));
-}
-
-double DistanceEffect::exponentialGain(double distance)
-{
- return pow(distance / m_refDistance, -m_rolloffFactor);
-}
-
-} // namespace WebCore
-
-#endif // ENABLE(WEB_AUDIO)
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/Distance.h b/chromium/third_party/WebKit/Source/core/platform/audio/Distance.h
deleted file mode 100644
index c5b6cc949cc..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/Distance.h
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef Distance_h
-#define Distance_h
-
-namespace WebCore {
-
-// Distance models are defined according to the OpenAL specification:
-// http://connect.creativelabs.com/openal/Documentation/OpenAL%201.1%20Specification.htm.
-
-class DistanceEffect {
-public:
- enum ModelType {
- ModelLinear = 0,
- ModelInverse = 1,
- ModelExponential = 2
- };
-
- DistanceEffect();
-
- // Returns scalar gain for the given distance the current distance model is used
- double gain(double distance);
-
- ModelType model() { return m_model; }
-
- void setModel(ModelType model, bool clamped)
- {
- m_model = model;
- m_isClamped = clamped;
- }
-
- // Distance params
- void setRefDistance(double refDistance) { m_refDistance = refDistance; }
- void setMaxDistance(double maxDistance) { m_maxDistance = maxDistance; }
- void setRolloffFactor(double rolloffFactor) { m_rolloffFactor = rolloffFactor; }
-
- double refDistance() const { return m_refDistance; }
- double maxDistance() const { return m_maxDistance; }
- double rolloffFactor() const { return m_rolloffFactor; }
-
-protected:
- double linearGain(double distance);
- double inverseGain(double distance);
- double exponentialGain(double distance);
-
- ModelType m_model;
- bool m_isClamped;
- double m_refDistance;
- double m_maxDistance;
- double m_rolloffFactor;
-};
-
-} // namespace WebCore
-
-#endif // Distance_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/DownSampler.cpp b/chromium/third_party/WebKit/Source/core/platform/audio/DownSampler.cpp
deleted file mode 100644
index e2c9518444a..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/DownSampler.cpp
+++ /dev/null
@@ -1,151 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#if ENABLE(WEB_AUDIO)
-
-#include "core/platform/audio/DownSampler.h"
-
-#include "wtf/MathExtras.h"
-
-namespace WebCore {
-
-DownSampler::DownSampler(size_t inputBlockSize)
- : m_inputBlockSize(inputBlockSize)
- , m_reducedKernel(DefaultKernelSize / 2)
- , m_tempBuffer(inputBlockSize / 2)
- , m_inputBuffer(inputBlockSize * 2)
- , m_convolver(inputBlockSize / 2) // runs at 1/2 source sample-rate
-{
- initializeKernel();
-}
-
-void DownSampler::initializeKernel()
-{
- // Blackman window parameters.
- double alpha = 0.16;
- double a0 = 0.5 * (1.0 - alpha);
- double a1 = 0.5;
- double a2 = 0.5 * alpha;
-
- int n = DefaultKernelSize;
- int halfSize = n / 2;
-
- // Half-band filter.
- double sincScaleFactor = 0.5;
-
- // Compute only the odd terms because the even ones are zero, except
- // right in the middle at halfSize, which is 0.5 and we'll handle specially during processing
- // after doing the main convolution using m_reducedKernel.
- for (int i = 1; i < n; i += 2) {
- // Compute the sinc() with offset.
- double s = sincScaleFactor * piDouble * (i - halfSize);
- double sinc = !s ? 1.0 : sin(s) / s;
- sinc *= sincScaleFactor;
-
- // Compute Blackman window, matching the offset of the sinc().
- double x = static_cast<double>(i) / n;
- double window = a0 - a1 * cos(2.0 * piDouble * x) + a2 * cos(4.0 * piDouble * x);
-
- // Window the sinc() function.
- // Then store only the odd terms in the kernel.
- // In a sense, this is shifting forward in time by one sample-frame at the destination sample-rate.
- m_reducedKernel[(i - 1) / 2] = sinc * window;
- }
-}
-
-void DownSampler::process(const float* sourceP, float* destP, size_t sourceFramesToProcess)
-{
- bool isInputBlockSizeGood = sourceFramesToProcess == m_inputBlockSize;
- ASSERT(isInputBlockSizeGood);
- if (!isInputBlockSizeGood)
- return;
-
- size_t destFramesToProcess = sourceFramesToProcess / 2;
-
- bool isTempBufferGood = destFramesToProcess == m_tempBuffer.size();
- ASSERT(isTempBufferGood);
- if (!isTempBufferGood)
- return;
-
- bool isReducedKernelGood = m_reducedKernel.size() == DefaultKernelSize / 2;
- ASSERT(isReducedKernelGood);
- if (!isReducedKernelGood)
- return;
-
- size_t halfSize = DefaultKernelSize / 2;
-
- // Copy source samples to 2nd half of input buffer.
- bool isInputBufferGood = m_inputBuffer.size() == sourceFramesToProcess * 2 && halfSize <= sourceFramesToProcess;
- ASSERT(isInputBufferGood);
- if (!isInputBufferGood)
- return;
-
- float* inputP = m_inputBuffer.data() + sourceFramesToProcess;
- memcpy(inputP, sourceP, sizeof(float) * sourceFramesToProcess);
-
- // Copy the odd sample-frames from sourceP, delayed by one sample-frame (destination sample-rate)
- // to match shifting forward in time in m_reducedKernel.
- float* oddSamplesP = m_tempBuffer.data();
- for (unsigned i = 0; i < destFramesToProcess; ++i)
- oddSamplesP[i] = *((inputP - 1) + i * 2);
-
- // Actually process oddSamplesP with m_reducedKernel for efficiency.
- // The theoretical kernel is double this size with 0 values for even terms (except center).
- m_convolver.process(&m_reducedKernel, oddSamplesP, destP, destFramesToProcess);
-
- // Now, account for the 0.5 term right in the middle of the kernel.
- // This amounts to a delay-line of length halfSize (at the source sample-rate),
- // scaled by 0.5.
-
- // Sum into the destination.
- for (unsigned i = 0; i < destFramesToProcess; ++i)
- destP[i] += 0.5 * *((inputP - halfSize) + i * 2);
-
- // Copy 2nd half of input buffer to 1st half.
- memcpy(m_inputBuffer.data(), inputP, sizeof(float) * sourceFramesToProcess);
-}
-
-void DownSampler::reset()
-{
- m_convolver.reset();
- m_inputBuffer.zero();
-}
-
-size_t DownSampler::latencyFrames() const
-{
- // Divide by two since this is a linear phase kernel and the delay is at the center of the kernel.
- return m_reducedKernel.size() / 2;
-}
-
-} // namespace WebCore
-
-#endif // ENABLE(WEB_AUDIO)
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/DownSampler.h b/chromium/third_party/WebKit/Source/core/platform/audio/DownSampler.h
deleted file mode 100644
index afd5d98cf2d..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/DownSampler.h
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef DownSampler_h
-#define DownSampler_h
-
-#include "core/platform/audio/AudioArray.h"
-#include "core/platform/audio/DirectConvolver.h"
-
-namespace WebCore {
-
-// DownSampler down-samples the source stream by a factor of 2x.
-
-class DownSampler {
-public:
- DownSampler(size_t inputBlockSize);
-
- // The destination buffer |destP| is of size sourceFramesToProcess / 2.
- void process(const float* sourceP, float* destP, size_t sourceFramesToProcess);
-
- void reset();
-
- // Latency based on the destination sample-rate.
- size_t latencyFrames() const;
-
-private:
- enum { DefaultKernelSize = 256 };
-
- size_t m_inputBlockSize;
-
- // Computes ideal band-limited half-band filter coefficients.
- // In other words, filter out all frequencies higher than 0.25 * Nyquist.
- void initializeKernel();
- AudioFloatArray m_reducedKernel;
-
- // Half-band filter.
- DirectConvolver m_convolver;
-
- AudioFloatArray m_tempBuffer;
-
- // Used as delay-line (FIR filter history) for the input samples to account for the 0.5 term right in the middle of the kernel.
- AudioFloatArray m_inputBuffer;
-};
-
-} // namespace WebCore
-
-#endif // DownSampler_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/DynamicsCompressor.cpp b/chromium/third_party/WebKit/Source/core/platform/audio/DynamicsCompressor.cpp
deleted file mode 100644
index 46621bb4811..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/DynamicsCompressor.cpp
+++ /dev/null
@@ -1,286 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#if ENABLE(WEB_AUDIO)
-
-#include "core/platform/audio/DynamicsCompressor.h"
-
-#include "core/platform/audio/AudioBus.h"
-#include "core/platform/audio/AudioUtilities.h"
-#include "wtf/MathExtras.h"
-
-namespace WebCore {
-
-using namespace AudioUtilities;
-
-DynamicsCompressor::DynamicsCompressor(float sampleRate, unsigned numberOfChannels)
- : m_numberOfChannels(numberOfChannels)
- , m_sampleRate(sampleRate)
- , m_compressor(sampleRate, numberOfChannels)
-{
- // Uninitialized state - for parameter recalculation.
- m_lastFilterStageRatio = -1;
- m_lastAnchor = -1;
- m_lastFilterStageGain = -1;
-
- setNumberOfChannels(numberOfChannels);
- initializeParameters();
-}
-
-void DynamicsCompressor::setParameterValue(unsigned parameterID, float value)
-{
- ASSERT(parameterID < ParamLast);
- if (parameterID < ParamLast)
- m_parameters[parameterID] = value;
-}
-
-void DynamicsCompressor::initializeParameters()
-{
- // Initializes compressor to default values.
-
- m_parameters[ParamThreshold] = -24; // dB
- m_parameters[ParamKnee] = 30; // dB
- m_parameters[ParamRatio] = 12; // unit-less
- m_parameters[ParamAttack] = 0.003f; // seconds
- m_parameters[ParamRelease] = 0.250f; // seconds
- m_parameters[ParamPreDelay] = 0.006f; // seconds
-
- // Release zone values 0 -> 1.
- m_parameters[ParamReleaseZone1] = 0.09f;
- m_parameters[ParamReleaseZone2] = 0.16f;
- m_parameters[ParamReleaseZone3] = 0.42f;
- m_parameters[ParamReleaseZone4] = 0.98f;
-
- m_parameters[ParamFilterStageGain] = 4.4f; // dB
- m_parameters[ParamFilterStageRatio] = 2;
- m_parameters[ParamFilterAnchor] = 15000 / nyquist();
-
- m_parameters[ParamPostGain] = 0; // dB
- m_parameters[ParamReduction] = 0; // dB
-
- // Linear crossfade (0 -> 1).
- m_parameters[ParamEffectBlend] = 1;
-}
-
-float DynamicsCompressor::parameterValue(unsigned parameterID)
-{
- ASSERT(parameterID < ParamLast);
- return m_parameters[parameterID];
-}
-
-void DynamicsCompressor::setEmphasisStageParameters(unsigned stageIndex, float gain, float normalizedFrequency /* 0 -> 1 */)
-{
- float gk = 1 - gain / 20;
- float f1 = normalizedFrequency * gk;
- float f2 = normalizedFrequency / gk;
- float r1 = expf(-f1 * piFloat);
- float r2 = expf(-f2 * piFloat);
-
- ASSERT(m_numberOfChannels == m_preFilterPacks.size());
-
- for (unsigned i = 0; i < m_numberOfChannels; ++i) {
- // Set pre-filter zero and pole to create an emphasis filter.
- ZeroPole& preFilter = m_preFilterPacks[i]->filters[stageIndex];
- preFilter.setZero(r1);
- preFilter.setPole(r2);
-
- // Set post-filter with zero and pole reversed to create the de-emphasis filter.
- // If there were no compressor kernel in between, they would cancel each other out (allpass filter).
- ZeroPole& postFilter = m_postFilterPacks[i]->filters[stageIndex];
- postFilter.setZero(r2);
- postFilter.setPole(r1);
- }
-}
-
-void DynamicsCompressor::setEmphasisParameters(float gain, float anchorFreq, float filterStageRatio)
-{
- setEmphasisStageParameters(0, gain, anchorFreq);
- setEmphasisStageParameters(1, gain, anchorFreq / filterStageRatio);
- setEmphasisStageParameters(2, gain, anchorFreq / (filterStageRatio * filterStageRatio));
- setEmphasisStageParameters(3, gain, anchorFreq / (filterStageRatio * filterStageRatio * filterStageRatio));
-}
-
-void DynamicsCompressor::process(const AudioBus* sourceBus, AudioBus* destinationBus, unsigned framesToProcess)
-{
- // Though numberOfChannels is retrived from destinationBus, we still name it numberOfChannels instead of numberOfDestinationChannels.
- // It's because we internally match sourceChannels's size to destinationBus by channel up/down mix. Thus we need numberOfChannels
- // to do the loop work for both m_sourceChannels and m_destinationChannels.
-
- unsigned numberOfChannels = destinationBus->numberOfChannels();
- unsigned numberOfSourceChannels = sourceBus->numberOfChannels();
-
- ASSERT(numberOfChannels == m_numberOfChannels && numberOfSourceChannels);
-
- if (numberOfChannels != m_numberOfChannels || !numberOfSourceChannels) {
- destinationBus->zero();
- return;
- }
-
- switch (numberOfChannels) {
- case 2: // stereo
- m_sourceChannels[0] = sourceBus->channel(0)->data();
-
- if (numberOfSourceChannels > 1)
- m_sourceChannels[1] = sourceBus->channel(1)->data();
- else
- // Simply duplicate mono channel input data to right channel for stereo processing.
- m_sourceChannels[1] = m_sourceChannels[0];
-
- break;
- default:
- // FIXME : support other number of channels.
- ASSERT_NOT_REACHED();
- destinationBus->zero();
- return;
- }
-
- for (unsigned i = 0; i < numberOfChannels; ++i)
- m_destinationChannels[i] = destinationBus->channel(i)->mutableData();
-
- float filterStageGain = parameterValue(ParamFilterStageGain);
- float filterStageRatio = parameterValue(ParamFilterStageRatio);
- float anchor = parameterValue(ParamFilterAnchor);
-
- if (filterStageGain != m_lastFilterStageGain || filterStageRatio != m_lastFilterStageRatio || anchor != m_lastAnchor) {
- m_lastFilterStageGain = filterStageGain;
- m_lastFilterStageRatio = filterStageRatio;
- m_lastAnchor = anchor;
-
- setEmphasisParameters(filterStageGain, anchor, filterStageRatio);
- }
-
- // Apply pre-emphasis filter.
- // Note that the final three stages are computed in-place in the destination buffer.
- for (unsigned i = 0; i < numberOfChannels; ++i) {
- const float* sourceData = m_sourceChannels[i];
- float* destinationData = m_destinationChannels[i];
- ZeroPole* preFilters = m_preFilterPacks[i]->filters;
-
- preFilters[0].process(sourceData, destinationData, framesToProcess);
- preFilters[1].process(destinationData, destinationData, framesToProcess);
- preFilters[2].process(destinationData, destinationData, framesToProcess);
- preFilters[3].process(destinationData, destinationData, framesToProcess);
- }
-
- float dbThreshold = parameterValue(ParamThreshold);
- float dbKnee = parameterValue(ParamKnee);
- float ratio = parameterValue(ParamRatio);
- float attackTime = parameterValue(ParamAttack);
- float releaseTime = parameterValue(ParamRelease);
- float preDelayTime = parameterValue(ParamPreDelay);
-
- // This is effectively a master volume on the compressed signal (pre-blending).
- float dbPostGain = parameterValue(ParamPostGain);
-
- // Linear blending value from dry to completely processed (0 -> 1)
- // 0 means the signal is completely unprocessed.
- // 1 mixes in only the compressed signal.
- float effectBlend = parameterValue(ParamEffectBlend);
-
- float releaseZone1 = parameterValue(ParamReleaseZone1);
- float releaseZone2 = parameterValue(ParamReleaseZone2);
- float releaseZone3 = parameterValue(ParamReleaseZone3);
- float releaseZone4 = parameterValue(ParamReleaseZone4);
-
- // Apply compression to the pre-filtered signal.
- // The processing is performed in place.
- m_compressor.process(m_destinationChannels.get(),
- m_destinationChannels.get(),
- numberOfChannels,
- framesToProcess,
-
- dbThreshold,
- dbKnee,
- ratio,
- attackTime,
- releaseTime,
- preDelayTime,
- dbPostGain,
- effectBlend,
-
- releaseZone1,
- releaseZone2,
- releaseZone3,
- releaseZone4
- );
-
- // Update the compression amount.
- setParameterValue(ParamReduction, m_compressor.meteringGain());
-
- // Apply de-emphasis filter.
- for (unsigned i = 0; i < numberOfChannels; ++i) {
- float* destinationData = m_destinationChannels[i];
- ZeroPole* postFilters = m_postFilterPacks[i]->filters;
-
- postFilters[0].process(destinationData, destinationData, framesToProcess);
- postFilters[1].process(destinationData, destinationData, framesToProcess);
- postFilters[2].process(destinationData, destinationData, framesToProcess);
- postFilters[3].process(destinationData, destinationData, framesToProcess);
- }
-}
-
-void DynamicsCompressor::reset()
-{
- m_lastFilterStageRatio = -1; // for recalc
- m_lastAnchor = -1;
- m_lastFilterStageGain = -1;
-
- for (unsigned channel = 0; channel < m_numberOfChannels; ++channel) {
- for (unsigned stageIndex = 0; stageIndex < 4; ++stageIndex) {
- m_preFilterPacks[channel]->filters[stageIndex].reset();
- m_postFilterPacks[channel]->filters[stageIndex].reset();
- }
- }
-
- m_compressor.reset();
-}
-
-void DynamicsCompressor::setNumberOfChannels(unsigned numberOfChannels)
-{
- if (m_preFilterPacks.size() == numberOfChannels)
- return;
-
- m_preFilterPacks.clear();
- m_postFilterPacks.clear();
- for (unsigned i = 0; i < numberOfChannels; ++i) {
- m_preFilterPacks.append(adoptPtr(new ZeroPoleFilterPack4()));
- m_postFilterPacks.append(adoptPtr(new ZeroPoleFilterPack4()));
- }
-
- m_sourceChannels = adoptArrayPtr(new const float* [numberOfChannels]);
- m_destinationChannels = adoptArrayPtr(new float* [numberOfChannels]);
-
- m_compressor.setNumberOfChannels(numberOfChannels);
- m_numberOfChannels = numberOfChannels;
-}
-
-} // namespace WebCore
-
-#endif // ENABLE(WEB_AUDIO)
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/DynamicsCompressor.h b/chromium/third_party/WebKit/Source/core/platform/audio/DynamicsCompressor.h
deleted file mode 100644
index 90922e6b232..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/DynamicsCompressor.h
+++ /dev/null
@@ -1,118 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef DynamicsCompressor_h
-#define DynamicsCompressor_h
-
-#include "core/platform/audio/AudioArray.h"
-#include "core/platform/audio/DynamicsCompressorKernel.h"
-#include "core/platform/audio/ZeroPole.h"
-
-#include "wtf/OwnArrayPtr.h"
-
-namespace WebCore {
-
-class AudioBus;
-
-// DynamicsCompressor implements a flexible audio dynamics compression effect such as
-// is commonly used in musical production and game audio. It lowers the volume
-// of the loudest parts of the signal and raises the volume of the softest parts,
-// making the sound richer, fuller, and more controlled.
-
-class DynamicsCompressor {
-public:
- enum {
- ParamThreshold,
- ParamKnee,
- ParamRatio,
- ParamAttack,
- ParamRelease,
- ParamPreDelay,
- ParamReleaseZone1,
- ParamReleaseZone2,
- ParamReleaseZone3,
- ParamReleaseZone4,
- ParamPostGain,
- ParamFilterStageGain,
- ParamFilterStageRatio,
- ParamFilterAnchor,
- ParamEffectBlend,
- ParamReduction,
- ParamLast
- };
-
- DynamicsCompressor(float sampleRate, unsigned numberOfChannels);
-
- void process(const AudioBus* sourceBus, AudioBus* destinationBus, unsigned framesToProcess);
- void reset();
- void setNumberOfChannels(unsigned);
-
- void setParameterValue(unsigned parameterID, float value);
- float parameterValue(unsigned parameterID);
-
- float sampleRate() const { return m_sampleRate; }
- float nyquist() const { return m_sampleRate / 2; }
-
- double tailTime() const { return 0; }
- double latencyTime() const { return m_compressor.latencyFrames() / static_cast<double>(sampleRate()); }
-
-protected:
- unsigned m_numberOfChannels;
-
- // m_parameters holds the tweakable compressor parameters.
- float m_parameters[ParamLast];
- void initializeParameters();
-
- float m_sampleRate;
-
- // Emphasis filter controls.
- float m_lastFilterStageRatio;
- float m_lastAnchor;
- float m_lastFilterStageGain;
-
- typedef struct {
- ZeroPole filters[4];
- } ZeroPoleFilterPack4;
-
- // Per-channel emphasis filters.
- Vector<OwnPtr<ZeroPoleFilterPack4> > m_preFilterPacks;
- Vector<OwnPtr<ZeroPoleFilterPack4> > m_postFilterPacks;
-
- OwnArrayPtr<const float*> m_sourceChannels;
- OwnArrayPtr<float*> m_destinationChannels;
-
- void setEmphasisStageParameters(unsigned stageIndex, float gain, float normalizedFrequency /* 0 -> 1 */);
- void setEmphasisParameters(float gain, float anchorFreq, float filterStageRatio);
-
- // The core compressor.
- DynamicsCompressorKernel m_compressor;
-};
-
-} // namespace WebCore
-
-#endif // DynamicsCompressor_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/DynamicsCompressorKernel.cpp b/chromium/third_party/WebKit/Source/core/platform/audio/DynamicsCompressorKernel.cpp
deleted file mode 100644
index e5ee8a64356..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/DynamicsCompressorKernel.cpp
+++ /dev/null
@@ -1,479 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#if ENABLE(WEB_AUDIO)
-
-#include "core/platform/audio/DynamicsCompressorKernel.h"
-
-#include <algorithm>
-#include "core/platform/audio/AudioUtilities.h"
-#include "core/platform/audio/DenormalDisabler.h"
-#include "wtf/MathExtras.h"
-
-using namespace std;
-
-namespace WebCore {
-
-using namespace AudioUtilities;
-
-// Metering hits peaks instantly, but releases this fast (in seconds).
-const float meteringReleaseTimeConstant = 0.325f;
-
-const float uninitializedValue = -1;
-
-DynamicsCompressorKernel::DynamicsCompressorKernel(float sampleRate, unsigned numberOfChannels)
- : m_sampleRate(sampleRate)
- , m_lastPreDelayFrames(DefaultPreDelayFrames)
- , m_preDelayReadIndex(0)
- , m_preDelayWriteIndex(DefaultPreDelayFrames)
- , m_ratio(uninitializedValue)
- , m_slope(uninitializedValue)
- , m_linearThreshold(uninitializedValue)
- , m_dbThreshold(uninitializedValue)
- , m_dbKnee(uninitializedValue)
- , m_kneeThreshold(uninitializedValue)
- , m_kneeThresholdDb(uninitializedValue)
- , m_ykneeThresholdDb(uninitializedValue)
- , m_K(uninitializedValue)
-{
- setNumberOfChannels(numberOfChannels);
-
- // Initializes most member variables
- reset();
-
- m_meteringReleaseK = static_cast<float>(discreteTimeConstantForSampleRate(meteringReleaseTimeConstant, sampleRate));
-}
-
-void DynamicsCompressorKernel::setNumberOfChannels(unsigned numberOfChannels)
-{
- if (m_preDelayBuffers.size() == numberOfChannels)
- return;
-
- m_preDelayBuffers.clear();
- for (unsigned i = 0; i < numberOfChannels; ++i)
- m_preDelayBuffers.append(adoptPtr(new AudioFloatArray(MaxPreDelayFrames)));
-}
-
-void DynamicsCompressorKernel::setPreDelayTime(float preDelayTime)
-{
- // Re-configure look-ahead section pre-delay if delay time has changed.
- unsigned preDelayFrames = preDelayTime * sampleRate();
- if (preDelayFrames > MaxPreDelayFrames - 1)
- preDelayFrames = MaxPreDelayFrames - 1;
-
- if (m_lastPreDelayFrames != preDelayFrames) {
- m_lastPreDelayFrames = preDelayFrames;
- for (unsigned i = 0; i < m_preDelayBuffers.size(); ++i)
- m_preDelayBuffers[i]->zero();
-
- m_preDelayReadIndex = 0;
- m_preDelayWriteIndex = preDelayFrames;
- }
-}
-
-// Exponential curve for the knee.
-// It is 1st derivative matched at m_linearThreshold and asymptotically approaches the value m_linearThreshold + 1 / k.
-float DynamicsCompressorKernel::kneeCurve(float x, float k)
-{
- // Linear up to threshold.
- if (x < m_linearThreshold)
- return x;
-
- return m_linearThreshold + (1 - expf(-k * (x - m_linearThreshold))) / k;
-}
-
-// Full compression curve with constant ratio after knee.
-float DynamicsCompressorKernel::saturate(float x, float k)
-{
- float y;
-
- if (x < m_kneeThreshold)
- y = kneeCurve(x, k);
- else {
- // Constant ratio after knee.
- float xDb = linearToDecibels(x);
- float yDb = m_ykneeThresholdDb + m_slope * (xDb - m_kneeThresholdDb);
-
- y = decibelsToLinear(yDb);
- }
-
- return y;
-}
-
-// Approximate 1st derivative with input and output expressed in dB.
-// This slope is equal to the inverse of the compression "ratio".
-// In other words, a compression ratio of 20 would be a slope of 1/20.
-float DynamicsCompressorKernel::slopeAt(float x, float k)
-{
- if (x < m_linearThreshold)
- return 1;
-
- float x2 = x * 1.001;
-
- float xDb = linearToDecibels(x);
- float x2Db = linearToDecibels(x2);
-
- float yDb = linearToDecibels(kneeCurve(x, k));
- float y2Db = linearToDecibels(kneeCurve(x2, k));
-
- float m = (y2Db - yDb) / (x2Db - xDb);
-
- return m;
-}
-
-float DynamicsCompressorKernel::kAtSlope(float desiredSlope)
-{
- float xDb = m_dbThreshold + m_dbKnee;
- float x = decibelsToLinear(xDb);
-
- // Approximate k given initial values.
- float minK = 0.1;
- float maxK = 10000;
- float k = 5;
-
- for (int i = 0; i < 15; ++i) {
- // A high value for k will more quickly asymptotically approach a slope of 0.
- float slope = slopeAt(x, k);
-
- if (slope < desiredSlope) {
- // k is too high.
- maxK = k;
- } else {
- // k is too low.
- minK = k;
- }
-
- // Re-calculate based on geometric mean.
- k = sqrtf(minK * maxK);
- }
-
- return k;
-}
-
-float DynamicsCompressorKernel::updateStaticCurveParameters(float dbThreshold, float dbKnee, float ratio)
-{
- if (dbThreshold != m_dbThreshold || dbKnee != m_dbKnee || ratio != m_ratio) {
- // Threshold and knee.
- m_dbThreshold = dbThreshold;
- m_linearThreshold = decibelsToLinear(dbThreshold);
- m_dbKnee = dbKnee;
-
- // Compute knee parameters.
- m_ratio = ratio;
- m_slope = 1 / m_ratio;
-
- float k = kAtSlope(1 / m_ratio);
-
- m_kneeThresholdDb = dbThreshold + dbKnee;
- m_kneeThreshold = decibelsToLinear(m_kneeThresholdDb);
-
- m_ykneeThresholdDb = linearToDecibels(kneeCurve(m_kneeThreshold, k));
-
- m_K = k;
- }
- return m_K;
-}
-
-void DynamicsCompressorKernel::process(float* sourceChannels[],
- float* destinationChannels[],
- unsigned numberOfChannels,
- unsigned framesToProcess,
-
- float dbThreshold,
- float dbKnee,
- float ratio,
- float attackTime,
- float releaseTime,
- float preDelayTime,
- float dbPostGain,
- float effectBlend, /* equal power crossfade */
-
- float releaseZone1,
- float releaseZone2,
- float releaseZone3,
- float releaseZone4
- )
-{
- ASSERT(m_preDelayBuffers.size() == numberOfChannels);
-
- float sampleRate = this->sampleRate();
-
- float dryMix = 1 - effectBlend;
- float wetMix = effectBlend;
-
- float k = updateStaticCurveParameters(dbThreshold, dbKnee, ratio);
-
- // Makeup gain.
- float fullRangeGain = saturate(1, k);
- float fullRangeMakeupGain = 1 / fullRangeGain;
-
- // Empirical/perceptual tuning.
- fullRangeMakeupGain = powf(fullRangeMakeupGain, 0.6f);
-
- float masterLinearGain = decibelsToLinear(dbPostGain) * fullRangeMakeupGain;
-
- // Attack parameters.
- attackTime = max(0.001f, attackTime);
- float attackFrames = attackTime * sampleRate;
-
- // Release parameters.
- float releaseFrames = sampleRate * releaseTime;
-
- // Detector release time.
- float satReleaseTime = 0.0025f;
- float satReleaseFrames = satReleaseTime * sampleRate;
-
- // Create a smooth function which passes through four points.
-
- // Polynomial of the form
- // y = a + b*x + c*x^2 + d*x^3 + e*x^4;
-
- float y1 = releaseFrames * releaseZone1;
- float y2 = releaseFrames * releaseZone2;
- float y3 = releaseFrames * releaseZone3;
- float y4 = releaseFrames * releaseZone4;
-
- // All of these coefficients were derived for 4th order polynomial curve fitting where the y values
- // match the evenly spaced x values as follows: (y1 : x == 0, y2 : x == 1, y3 : x == 2, y4 : x == 3)
- float kA = 0.9999999999999998f*y1 + 1.8432219684323923e-16f*y2 - 1.9373394351676423e-16f*y3 + 8.824516011816245e-18f*y4;
- float kB = -1.5788320352845888f*y1 + 2.3305837032074286f*y2 - 0.9141194204840429f*y3 + 0.1623677525612032f*y4;
- float kC = 0.5334142869106424f*y1 - 1.272736789213631f*y2 + 0.9258856042207512f*y3 - 0.18656310191776226f*y4;
- float kD = 0.08783463138207234f*y1 - 0.1694162967925622f*y2 + 0.08588057951595272f*y3 - 0.00429891410546283f*y4;
- float kE = -0.042416883008123074f*y1 + 0.1115693827987602f*y2 - 0.09764676325265872f*y3 + 0.028494263462021576f*y4;
-
- // x ranges from 0 -> 3 0 1 2 3
- // -15 -10 -5 0db
-
- // y calculates adaptive release frames depending on the amount of compression.
-
- setPreDelayTime(preDelayTime);
-
- const int nDivisionFrames = 32;
-
- const int nDivisions = framesToProcess / nDivisionFrames;
-
- unsigned frameIndex = 0;
- for (int i = 0; i < nDivisions; ++i) {
- // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- // Calculate desired gain
- // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
- // Fix gremlins.
- if (std::isnan(m_detectorAverage))
- m_detectorAverage = 1;
- if (std::isinf(m_detectorAverage))
- m_detectorAverage = 1;
-
- float desiredGain = m_detectorAverage;
-
- // Pre-warp so we get desiredGain after sin() warp below.
- float scaledDesiredGain = asinf(desiredGain) / (0.5f * piFloat);
-
- // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- // Deal with envelopes
- // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
- // envelopeRate is the rate we slew from current compressor level to the desired level.
- // The exact rate depends on if we're attacking or releasing and by how much.
- float envelopeRate;
-
- bool isReleasing = scaledDesiredGain > m_compressorGain;
-
- // compressionDiffDb is the difference between current compression level and the desired level.
- float compressionDiffDb = linearToDecibels(m_compressorGain / scaledDesiredGain);
-
- if (isReleasing) {
- // Release mode - compressionDiffDb should be negative dB
- m_maxAttackCompressionDiffDb = -1;
-
- // Fix gremlins.
- if (std::isnan(compressionDiffDb))
- compressionDiffDb = -1;
- if (std::isinf(compressionDiffDb))
- compressionDiffDb = -1;
-
- // Adaptive release - higher compression (lower compressionDiffDb) releases faster.
-
- // Contain within range: -12 -> 0 then scale to go from 0 -> 3
- float x = compressionDiffDb;
- x = max(-12.0f, x);
- x = min(0.0f, x);
- x = 0.25f * (x + 12);
-
- // Compute adaptive release curve using 4th order polynomial.
- // Normal values for the polynomial coefficients would create a monotonically increasing function.
- float x2 = x * x;
- float x3 = x2 * x;
- float x4 = x2 * x2;
- float releaseFrames = kA + kB * x + kC * x2 + kD * x3 + kE * x4;
-
-#define kSpacingDb 5
- float dbPerFrame = kSpacingDb / releaseFrames;
-
- envelopeRate = decibelsToLinear(dbPerFrame);
- } else {
- // Attack mode - compressionDiffDb should be positive dB
-
- // Fix gremlins.
- if (std::isnan(compressionDiffDb))
- compressionDiffDb = 1;
- if (std::isinf(compressionDiffDb))
- compressionDiffDb = 1;
-
- // As long as we're still in attack mode, use a rate based off
- // the largest compressionDiffDb we've encountered so far.
- if (m_maxAttackCompressionDiffDb == -1 || m_maxAttackCompressionDiffDb < compressionDiffDb)
- m_maxAttackCompressionDiffDb = compressionDiffDb;
-
- float effAttenDiffDb = max(0.5f, m_maxAttackCompressionDiffDb);
-
- float x = 0.25f / effAttenDiffDb;
- envelopeRate = 1 - powf(x, 1 / attackFrames);
- }
-
- // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- // Inner loop - calculate shaped power average - apply compression.
- // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
- {
- int preDelayReadIndex = m_preDelayReadIndex;
- int preDelayWriteIndex = m_preDelayWriteIndex;
- float detectorAverage = m_detectorAverage;
- float compressorGain = m_compressorGain;
-
- int loopFrames = nDivisionFrames;
- while (loopFrames--) {
- float compressorInput = 0;
-
- // Predelay signal, computing compression amount from un-delayed version.
- for (unsigned i = 0; i < numberOfChannels; ++i) {
- float* delayBuffer = m_preDelayBuffers[i]->data();
- float undelayedSource = sourceChannels[i][frameIndex];
- delayBuffer[preDelayWriteIndex] = undelayedSource;
-
- float absUndelayedSource = undelayedSource > 0 ? undelayedSource : -undelayedSource;
- if (compressorInput < absUndelayedSource)
- compressorInput = absUndelayedSource;
- }
-
- // Calculate shaped power on undelayed input.
-
- float scaledInput = compressorInput;
- float absInput = scaledInput > 0 ? scaledInput : -scaledInput;
-
- // Put through shaping curve.
- // This is linear up to the threshold, then enters a "knee" portion followed by the "ratio" portion.
- // The transition from the threshold to the knee is smooth (1st derivative matched).
- // The transition from the knee to the ratio portion is smooth (1st derivative matched).
- float shapedInput = saturate(absInput, k);
-
- float attenuation = absInput <= 0.0001f ? 1 : shapedInput / absInput;
-
- float attenuationDb = -linearToDecibels(attenuation);
- attenuationDb = max(2.0f, attenuationDb);
-
- float dbPerFrame = attenuationDb / satReleaseFrames;
-
- float satReleaseRate = decibelsToLinear(dbPerFrame) - 1;
-
- bool isRelease = (attenuation > detectorAverage);
- float rate = isRelease ? satReleaseRate : 1;
-
- detectorAverage += (attenuation - detectorAverage) * rate;
- detectorAverage = min(1.0f, detectorAverage);
-
- // Fix gremlins.
- if (std::isnan(detectorAverage))
- detectorAverage = 1;
- if (std::isinf(detectorAverage))
- detectorAverage = 1;
-
- // Exponential approach to desired gain.
- if (envelopeRate < 1) {
- // Attack - reduce gain to desired.
- compressorGain += (scaledDesiredGain - compressorGain) * envelopeRate;
- } else {
- // Release - exponentially increase gain to 1.0
- compressorGain *= envelopeRate;
- compressorGain = min(1.0f, compressorGain);
- }
-
- // Warp pre-compression gain to smooth out sharp exponential transition points.
- float postWarpCompressorGain = sinf(0.5f * piFloat * compressorGain);
-
- // Calculate total gain using master gain and effect blend.
- float totalGain = dryMix + wetMix * masterLinearGain * postWarpCompressorGain;
-
- // Calculate metering.
- float dbRealGain = 20 * log10(postWarpCompressorGain);
- if (dbRealGain < m_meteringGain)
- m_meteringGain = dbRealGain;
- else
- m_meteringGain += (dbRealGain - m_meteringGain) * m_meteringReleaseK;
-
- // Apply final gain.
- for (unsigned i = 0; i < numberOfChannels; ++i) {
- float* delayBuffer = m_preDelayBuffers[i]->data();
- destinationChannels[i][frameIndex] = delayBuffer[preDelayReadIndex] * totalGain;
- }
-
- frameIndex++;
- preDelayReadIndex = (preDelayReadIndex + 1) & MaxPreDelayFramesMask;
- preDelayWriteIndex = (preDelayWriteIndex + 1) & MaxPreDelayFramesMask;
- }
-
- // Locals back to member variables.
- m_preDelayReadIndex = preDelayReadIndex;
- m_preDelayWriteIndex = preDelayWriteIndex;
- m_detectorAverage = DenormalDisabler::flushDenormalFloatToZero(detectorAverage);
- m_compressorGain = DenormalDisabler::flushDenormalFloatToZero(compressorGain);
- }
- }
-}
-
-void DynamicsCompressorKernel::reset()
-{
- m_detectorAverage = 0;
- m_compressorGain = 1;
- m_meteringGain = 1;
-
- // Predelay section.
- for (unsigned i = 0; i < m_preDelayBuffers.size(); ++i)
- m_preDelayBuffers[i]->zero();
-
- m_preDelayReadIndex = 0;
- m_preDelayWriteIndex = DefaultPreDelayFrames;
-
- m_maxAttackCompressionDiffDb = -1; // uninitialized state
-}
-
-} // namespace WebCore
-
-#endif // ENABLE(WEB_AUDIO)
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/DynamicsCompressorKernel.h b/chromium/third_party/WebKit/Source/core/platform/audio/DynamicsCompressorKernel.h
deleted file mode 100644
index f9e821b7c8c..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/DynamicsCompressorKernel.h
+++ /dev/null
@@ -1,129 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef DynamicsCompressorKernel_h
-#define DynamicsCompressorKernel_h
-
-#include "core/platform/audio/AudioArray.h"
-
-#include "wtf/OwnPtr.h"
-#include "wtf/PassOwnPtr.h"
-
-namespace WebCore {
-
-class DynamicsCompressorKernel {
-public:
- DynamicsCompressorKernel(float sampleRate, unsigned numberOfChannels);
-
- void setNumberOfChannels(unsigned);
-
- // Performs stereo-linked compression.
- void process(float* sourceChannels[],
- float* destinationChannels[],
- unsigned numberOfChannels,
- unsigned framesToProcess,
-
- float dbThreshold,
- float dbKnee,
- float ratio,
- float attackTime,
- float releaseTime,
- float preDelayTime,
- float dbPostGain,
- float effectBlend,
-
- float releaseZone1,
- float releaseZone2,
- float releaseZone3,
- float releaseZone4
- );
-
- void reset();
-
- unsigned latencyFrames() const { return m_lastPreDelayFrames; }
-
- float sampleRate() const { return m_sampleRate; }
-
- float meteringGain() const { return m_meteringGain; }
-
-protected:
- float m_sampleRate;
-
- float m_detectorAverage;
- float m_compressorGain;
-
- // Metering
- float m_meteringReleaseK;
- float m_meteringGain;
-
- // Lookahead section.
- enum { MaxPreDelayFrames = 1024 };
- enum { MaxPreDelayFramesMask = MaxPreDelayFrames - 1 };
- enum { DefaultPreDelayFrames = 256 }; // setPreDelayTime() will override this initial value
- unsigned m_lastPreDelayFrames;
- void setPreDelayTime(float);
-
- Vector<OwnPtr<AudioFloatArray> > m_preDelayBuffers;
- int m_preDelayReadIndex;
- int m_preDelayWriteIndex;
-
- float m_maxAttackCompressionDiffDb;
-
- // Static compression curve.
- float kneeCurve(float x, float k);
- float saturate(float x, float k);
- float slopeAt(float x, float k);
- float kAtSlope(float desiredSlope);
-
- float updateStaticCurveParameters(float dbThreshold, float dbKnee, float ratio);
-
- // Amount of input change in dB required for 1 dB of output change.
- // This applies to the portion of the curve above m_kneeThresholdDb (see below).
- float m_ratio;
- float m_slope; // Inverse ratio.
-
- // The input to output change below the threshold is linear 1:1.
- float m_linearThreshold;
- float m_dbThreshold;
-
- // m_dbKnee is the number of dB above the threshold before we enter the "ratio" portion of the curve.
- // m_kneeThresholdDb = m_dbThreshold + m_dbKnee
- // The portion between m_dbThreshold and m_kneeThresholdDb is the "soft knee" portion of the curve
- // which transitions smoothly from the linear portion to the ratio portion.
- float m_dbKnee;
- float m_kneeThreshold;
- float m_kneeThresholdDb;
- float m_ykneeThresholdDb;
-
- // Internal parameter for the knee portion of the curve.
- float m_K;
-};
-
-} // namespace WebCore
-
-#endif // DynamicsCompressorKernel_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/EqualPowerPanner.cpp b/chromium/third_party/WebKit/Source/core/platform/audio/EqualPowerPanner.cpp
deleted file mode 100644
index aed8f2ff738..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/EqualPowerPanner.cpp
+++ /dev/null
@@ -1,159 +0,0 @@
-/*
- * Copyright (C) 2010, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#if ENABLE(WEB_AUDIO)
-
-#include "core/platform/audio/EqualPowerPanner.h"
-
-#include <algorithm>
-#include "core/platform/audio/AudioBus.h"
-#include "core/platform/audio/AudioUtilities.h"
-#include "wtf/MathExtras.h"
-
-// Use a 50ms smoothing / de-zippering time-constant.
-const float SmoothingTimeConstant = 0.050f;
-
-using namespace std;
-
-namespace WebCore {
-
-EqualPowerPanner::EqualPowerPanner(float sampleRate)
- : Panner(PanningModelEqualPower)
- , m_isFirstRender(true)
- , m_gainL(0.0)
- , m_gainR(0.0)
-{
- m_smoothingConstant = AudioUtilities::discreteTimeConstantForSampleRate(SmoothingTimeConstant, sampleRate);
-}
-
-void EqualPowerPanner::pan(double azimuth, double /*elevation*/, const AudioBus* inputBus, AudioBus* outputBus, size_t framesToProcess)
-{
- bool isInputSafe = inputBus && (inputBus->numberOfChannels() == 1 || inputBus->numberOfChannels() == 2) && framesToProcess <= inputBus->length();
- ASSERT(isInputSafe);
- if (!isInputSafe)
- return;
-
- unsigned numberOfInputChannels = inputBus->numberOfChannels();
-
- bool isOutputSafe = outputBus && outputBus->numberOfChannels() == 2 && framesToProcess <= outputBus->length();
- ASSERT(isOutputSafe);
- if (!isOutputSafe)
- return;
-
- const float* sourceL = inputBus->channel(0)->data();
- const float* sourceR = numberOfInputChannels > 1 ? inputBus->channel(1)->data() : sourceL;
- float* destinationL = outputBus->channelByType(AudioBus::ChannelLeft)->mutableData();
- float* destinationR = outputBus->channelByType(AudioBus::ChannelRight)->mutableData();
-
- if (!sourceL || !sourceR || !destinationL || !destinationR)
- return;
-
- // Clamp azimuth to allowed range of -180 -> +180.
- azimuth = max(-180.0, azimuth);
- azimuth = min(180.0, azimuth);
-
- // Alias the azimuth ranges behind us to in front of us:
- // -90 -> -180 to -90 -> 0 and 90 -> 180 to 90 -> 0
- if (azimuth < -90)
- azimuth = -180 - azimuth;
- else if (azimuth > 90)
- azimuth = 180 - azimuth;
-
- double desiredPanPosition;
- double desiredGainL;
- double desiredGainR;
-
- if (numberOfInputChannels == 1) { // For mono source case.
- // Pan smoothly from left to right with azimuth going from -90 -> +90 degrees.
- desiredPanPosition = (azimuth + 90) / 180;
- } else { // For stereo source case.
- if (azimuth <= 0) { // from -90 -> 0
- // sourceL -> destL and "equal-power pan" sourceR as in mono case
- // by transforming the "azimuth" value from -90 -> 0 degrees into the range -90 -> +90.
- desiredPanPosition = (azimuth + 90) / 90;
- } else { // from 0 -> +90
- // sourceR -> destR and "equal-power pan" sourceL as in mono case
- // by transforming the "azimuth" value from 0 -> +90 degrees into the range -90 -> +90.
- desiredPanPosition = azimuth / 90;
- }
- }
-
- desiredGainL = cos(0.5 * piDouble * desiredPanPosition);
- desiredGainR = sin(0.5 * piDouble * desiredPanPosition);
-
- // Don't de-zipper on first render call.
- if (m_isFirstRender) {
- m_isFirstRender = false;
- m_gainL = desiredGainL;
- m_gainR = desiredGainR;
- }
-
- // Cache in local variables.
- double gainL = m_gainL;
- double gainR = m_gainR;
-
- // Get local copy of smoothing constant.
- const double SmoothingConstant = m_smoothingConstant;
-
- int n = framesToProcess;
-
- if (numberOfInputChannels == 1) { // For mono source case.
- while (n--) {
- float inputL = *sourceL++;
- gainL += (desiredGainL - gainL) * SmoothingConstant;
- gainR += (desiredGainR - gainR) * SmoothingConstant;
- *destinationL++ = static_cast<float>(inputL * gainL);
- *destinationR++ = static_cast<float>(inputL * gainR);
- }
- } else { // For stereo source case.
- if (azimuth <= 0) { // from -90 -> 0
- while (n--) {
- float inputL = *sourceL++;
- float inputR = *sourceR++;
- gainL += (desiredGainL - gainL) * SmoothingConstant;
- gainR += (desiredGainR - gainR) * SmoothingConstant;
- *destinationL++ = static_cast<float>(inputL + inputR * gainL);
- *destinationR++ = static_cast<float>(inputR * gainR);
- }
- } else { // from 0 -> +90
- while (n--) {
- float inputL = *sourceL++;
- float inputR = *sourceR++;
- gainL += (desiredGainL - gainL) * SmoothingConstant;
- gainR += (desiredGainR - gainR) * SmoothingConstant;
- *destinationL++ = static_cast<float>(inputL * gainL);
- *destinationR++ = static_cast<float>(inputR + inputL * gainR);
- }
- }
- }
-
- m_gainL = gainL;
- m_gainR = gainR;
-}
-
-} // namespace WebCore
-
-#endif // ENABLE(WEB_AUDIO)
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/EqualPowerPanner.h b/chromium/third_party/WebKit/Source/core/platform/audio/EqualPowerPanner.h
deleted file mode 100644
index ebdd9f907b5..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/EqualPowerPanner.h
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright (C) 2010, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef EqualPowerPanner_h
-#define EqualPowerPanner_h
-
-#include "core/platform/audio/Panner.h"
-
-namespace WebCore {
-
-// Common type of stereo panner as found in normal audio mixing equipment.
-
-class EqualPowerPanner : public Panner {
-public:
- EqualPowerPanner(float sampleRate);
-
- virtual void pan(double azimuth, double elevation, const AudioBus* inputBus, AudioBus* outputBuf, size_t framesToProcess);
-
- virtual void reset() { m_isFirstRender = true; }
-
- virtual double tailTime() const OVERRIDE { return 0; }
- virtual double latencyTime() const OVERRIDE { return 0; }
-
-private:
- // For smoothing / de-zippering
- bool m_isFirstRender;
- double m_smoothingConstant;
-
- double m_gainL;
- double m_gainR;
-};
-
-} // namespace WebCore
-
-#endif // EqualPowerPanner_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/FFTConvolver.cpp b/chromium/third_party/WebKit/Source/core/platform/audio/FFTConvolver.cpp
deleted file mode 100644
index ed62abcab32..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/FFTConvolver.cpp
+++ /dev/null
@@ -1,120 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#if ENABLE(WEB_AUDIO)
-
-#include "core/platform/audio/FFTConvolver.h"
-
-#include "core/platform/audio/VectorMath.h"
-
-namespace WebCore {
-
-using namespace VectorMath;
-
-FFTConvolver::FFTConvolver(size_t fftSize)
- : m_frame(fftSize)
- , m_readWriteIndex(0)
- , m_inputBuffer(fftSize) // 2nd half of buffer is always zeroed
- , m_outputBuffer(fftSize)
- , m_lastOverlapBuffer(fftSize / 2)
-{
-}
-
-void FFTConvolver::process(FFTFrame* fftKernel, const float* sourceP, float* destP, size_t framesToProcess)
-{
- size_t halfSize = fftSize() / 2;
-
- // framesToProcess must be an exact multiple of halfSize,
- // or halfSize is a multiple of framesToProcess when halfSize > framesToProcess.
- bool isGood = !(halfSize % framesToProcess && framesToProcess % halfSize);
- ASSERT(isGood);
- if (!isGood)
- return;
-
- size_t numberOfDivisions = halfSize <= framesToProcess ? (framesToProcess / halfSize) : 1;
- size_t divisionSize = numberOfDivisions == 1 ? framesToProcess : halfSize;
-
- for (size_t i = 0; i < numberOfDivisions; ++i, sourceP += divisionSize, destP += divisionSize) {
- // Copy samples to input buffer (note contraint above!)
- float* inputP = m_inputBuffer.data();
-
- // Sanity check
- bool isCopyGood1 = sourceP && inputP && m_readWriteIndex + divisionSize <= m_inputBuffer.size();
- ASSERT(isCopyGood1);
- if (!isCopyGood1)
- return;
-
- memcpy(inputP + m_readWriteIndex, sourceP, sizeof(float) * divisionSize);
-
- // Copy samples from output buffer
- float* outputP = m_outputBuffer.data();
-
- // Sanity check
- bool isCopyGood2 = destP && outputP && m_readWriteIndex + divisionSize <= m_outputBuffer.size();
- ASSERT(isCopyGood2);
- if (!isCopyGood2)
- return;
-
- memcpy(destP, outputP + m_readWriteIndex, sizeof(float) * divisionSize);
- m_readWriteIndex += divisionSize;
-
- // Check if it's time to perform the next FFT
- if (m_readWriteIndex == halfSize) {
- // The input buffer is now filled (get frequency-domain version)
- m_frame.doFFT(m_inputBuffer.data());
- m_frame.multiply(*fftKernel);
- m_frame.doInverseFFT(m_outputBuffer.data());
-
- // Overlap-add 1st half from previous time
- vadd(m_outputBuffer.data(), 1, m_lastOverlapBuffer.data(), 1, m_outputBuffer.data(), 1, halfSize);
-
- // Finally, save 2nd half of result
- bool isCopyGood3 = m_outputBuffer.size() == 2 * halfSize && m_lastOverlapBuffer.size() == halfSize;
- ASSERT(isCopyGood3);
- if (!isCopyGood3)
- return;
-
- memcpy(m_lastOverlapBuffer.data(), m_outputBuffer.data() + halfSize, sizeof(float) * halfSize);
-
- // Reset index back to start for next time
- m_readWriteIndex = 0;
- }
- }
-}
-
-void FFTConvolver::reset()
-{
- m_lastOverlapBuffer.zero();
- m_readWriteIndex = 0;
-}
-
-} // namespace WebCore
-
-#endif // ENABLE(WEB_AUDIO)
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/FFTConvolver.h b/chromium/third_party/WebKit/Source/core/platform/audio/FFTConvolver.h
deleted file mode 100644
index 73f6e58a469..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/FFTConvolver.h
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef FFTConvolver_h
-#define FFTConvolver_h
-
-#include "core/platform/audio/AudioArray.h"
-#include "core/platform/audio/FFTFrame.h"
-
-namespace WebCore {
-
-class FFTConvolver {
-public:
- // fftSize must be a power of two
- FFTConvolver(size_t fftSize);
-
- // For now, with multiple calls to Process(), framesToProcess MUST add up EXACTLY to fftSize / 2
- //
- // FIXME: Later, we can do more sophisticated buffering to relax this requirement...
- //
- // The input to output latency is equal to fftSize / 2
- //
- // Processing in-place is allowed...
- void process(FFTFrame* fftKernel, const float* sourceP, float* destP, size_t framesToProcess);
-
- void reset();
-
- size_t fftSize() const { return m_frame.fftSize(); }
-
-private:
- FFTFrame m_frame;
-
- // Buffer input until we get fftSize / 2 samples then do an FFT
- size_t m_readWriteIndex;
- AudioFloatArray m_inputBuffer;
-
- // Stores output which we read a little at a time
- AudioFloatArray m_outputBuffer;
-
- // Saves the 2nd half of the FFT buffer, so we can do an overlap-add with the 1st half of the next one
- AudioFloatArray m_lastOverlapBuffer;
-};
-
-} // namespace WebCore
-
-#endif // FFTConvolver_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/FFTFrame.cpp b/chromium/third_party/WebKit/Source/core/platform/audio/FFTFrame.cpp
deleted file mode 100644
index 1bd5a63fbb6..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/FFTFrame.cpp
+++ /dev/null
@@ -1,274 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#if ENABLE(WEB_AUDIO)
-
-#include "core/platform/audio/FFTFrame.h"
-
-#ifndef NDEBUG
-#include <stdio.h>
-#endif
-
-#include "core/platform/Logging.h"
-#include "wtf/Complex.h"
-#include "wtf/MathExtras.h"
-#include "wtf/OwnPtr.h"
-
-namespace WebCore {
-
-void FFTFrame::doPaddedFFT(const float* data, size_t dataSize)
-{
- // Zero-pad the impulse response
- AudioFloatArray paddedResponse(fftSize()); // zero-initialized
- paddedResponse.copyToRange(data, 0, dataSize);
-
- // Get the frequency-domain version of padded response
- doFFT(paddedResponse.data());
-}
-
-PassOwnPtr<FFTFrame> FFTFrame::createInterpolatedFrame(const FFTFrame& frame1, const FFTFrame& frame2, double x)
-{
- OwnPtr<FFTFrame> newFrame = adoptPtr(new FFTFrame(frame1.fftSize()));
-
- newFrame->interpolateFrequencyComponents(frame1, frame2, x);
-
- // In the time-domain, the 2nd half of the response must be zero, to avoid circular convolution aliasing...
- int fftSize = newFrame->fftSize();
- AudioFloatArray buffer(fftSize);
- newFrame->doInverseFFT(buffer.data());
- buffer.zeroRange(fftSize / 2, fftSize);
-
- // Put back into frequency domain.
- newFrame->doFFT(buffer.data());
-
- return newFrame.release();
-}
-
-void FFTFrame::interpolateFrequencyComponents(const FFTFrame& frame1, const FFTFrame& frame2, double interp)
-{
- // FIXME : with some work, this method could be optimized
-
- float* realP = realData();
- float* imagP = imagData();
-
- const float* realP1 = frame1.realData();
- const float* imagP1 = frame1.imagData();
- const float* realP2 = frame2.realData();
- const float* imagP2 = frame2.imagData();
-
- m_FFTSize = frame1.fftSize();
- m_log2FFTSize = frame1.log2FFTSize();
-
- double s1base = (1.0 - interp);
- double s2base = interp;
-
- double phaseAccum = 0.0;
- double lastPhase1 = 0.0;
- double lastPhase2 = 0.0;
-
- realP[0] = static_cast<float>(s1base * realP1[0] + s2base * realP2[0]);
- imagP[0] = static_cast<float>(s1base * imagP1[0] + s2base * imagP2[0]);
-
- int n = m_FFTSize / 2;
-
- for (int i = 1; i < n; ++i) {
- Complex c1(realP1[i], imagP1[i]);
- Complex c2(realP2[i], imagP2[i]);
-
- double mag1 = abs(c1);
- double mag2 = abs(c2);
-
- // Interpolate magnitudes in decibels
- double mag1db = 20.0 * log10(mag1);
- double mag2db = 20.0 * log10(mag2);
-
- double s1 = s1base;
- double s2 = s2base;
-
- double magdbdiff = mag1db - mag2db;
-
- // Empirical tweak to retain higher-frequency zeroes
- double threshold = (i > 16) ? 5.0 : 2.0;
-
- if (magdbdiff < -threshold && mag1db < 0.0) {
- s1 = pow(s1, 0.75);
- s2 = 1.0 - s1;
- } else if (magdbdiff > threshold && mag2db < 0.0) {
- s2 = pow(s2, 0.75);
- s1 = 1.0 - s2;
- }
-
- // Average magnitude by decibels instead of linearly
- double magdb = s1 * mag1db + s2 * mag2db;
- double mag = pow(10.0, 0.05 * magdb);
-
- // Now, deal with phase
- double phase1 = arg(c1);
- double phase2 = arg(c2);
-
- double deltaPhase1 = phase1 - lastPhase1;
- double deltaPhase2 = phase2 - lastPhase2;
- lastPhase1 = phase1;
- lastPhase2 = phase2;
-
- // Unwrap phase deltas
- if (deltaPhase1 > piDouble)
- deltaPhase1 -= 2.0 * piDouble;
- if (deltaPhase1 < -piDouble)
- deltaPhase1 += 2.0 * piDouble;
- if (deltaPhase2 > piDouble)
- deltaPhase2 -= 2.0 * piDouble;
- if (deltaPhase2 < -piDouble)
- deltaPhase2 += 2.0 * piDouble;
-
- // Blend group-delays
- double deltaPhaseBlend;
-
- if (deltaPhase1 - deltaPhase2 > piDouble)
- deltaPhaseBlend = s1 * deltaPhase1 + s2 * (2.0 * piDouble + deltaPhase2);
- else if (deltaPhase2 - deltaPhase1 > piDouble)
- deltaPhaseBlend = s1 * (2.0 * piDouble + deltaPhase1) + s2 * deltaPhase2;
- else
- deltaPhaseBlend = s1 * deltaPhase1 + s2 * deltaPhase2;
-
- phaseAccum += deltaPhaseBlend;
-
- // Unwrap
- if (phaseAccum > piDouble)
- phaseAccum -= 2.0 * piDouble;
- if (phaseAccum < -piDouble)
- phaseAccum += 2.0 * piDouble;
-
- Complex c = complexFromMagnitudePhase(mag, phaseAccum);
-
- realP[i] = static_cast<float>(c.real());
- imagP[i] = static_cast<float>(c.imag());
- }
-}
-
-double FFTFrame::extractAverageGroupDelay()
-{
- float* realP = realData();
- float* imagP = imagData();
-
- double aveSum = 0.0;
- double weightSum = 0.0;
- double lastPhase = 0.0;
-
- int halfSize = fftSize() / 2;
-
- const double kSamplePhaseDelay = (2.0 * piDouble) / double(fftSize());
-
- // Calculate weighted average group delay
- for (int i = 0; i < halfSize; i++) {
- Complex c(realP[i], imagP[i]);
- double mag = abs(c);
- double phase = arg(c);
-
- double deltaPhase = phase - lastPhase;
- lastPhase = phase;
-
- // Unwrap
- if (deltaPhase < -piDouble)
- deltaPhase += 2.0 * piDouble;
- if (deltaPhase > piDouble)
- deltaPhase -= 2.0 * piDouble;
-
- aveSum += mag * deltaPhase;
- weightSum += mag;
- }
-
- // Note how we invert the phase delta wrt frequency since this is how group delay is defined
- double ave = aveSum / weightSum;
- double aveSampleDelay = -ave / kSamplePhaseDelay;
-
- // Leave 20 sample headroom (for leading edge of impulse)
- if (aveSampleDelay > 20.0)
- aveSampleDelay -= 20.0;
-
- // Remove average group delay (minus 20 samples for headroom)
- addConstantGroupDelay(-aveSampleDelay);
-
- // Remove DC offset
- realP[0] = 0.0f;
-
- return aveSampleDelay;
-}
-
-void FFTFrame::addConstantGroupDelay(double sampleFrameDelay)
-{
- int halfSize = fftSize() / 2;
-
- float* realP = realData();
- float* imagP = imagData();
-
- const double kSamplePhaseDelay = (2.0 * piDouble) / double(fftSize());
-
- double phaseAdj = -sampleFrameDelay * kSamplePhaseDelay;
-
- // Add constant group delay
- for (int i = 1; i < halfSize; i++) {
- Complex c(realP[i], imagP[i]);
- double mag = abs(c);
- double phase = arg(c);
-
- phase += i * phaseAdj;
-
- Complex c2 = complexFromMagnitudePhase(mag, phase);
-
- realP[i] = static_cast<float>(c2.real());
- imagP[i] = static_cast<float>(c2.imag());
- }
-}
-
-#ifndef NDEBUG
-void FFTFrame::print()
-{
- FFTFrame& frame = *this;
- float* realP = frame.realData();
- float* imagP = frame.imagData();
- LOG(WebAudio, "**** \n");
- LOG(WebAudio, "DC = %f : nyquist = %f\n", realP[0], imagP[0]);
-
- int n = m_FFTSize / 2;
-
- for (int i = 1; i < n; i++) {
- double mag = sqrt(realP[i] * realP[i] + imagP[i] * imagP[i]);
- double phase = atan2(realP[i], imagP[i]);
-
- LOG(WebAudio, "[%d] (%f %f)\n", i, mag, phase);
- }
- LOG(WebAudio, "****\n");
-}
-#endif // NDEBUG
-
-} // namespace WebCore
-
-#endif // ENABLE(WEB_AUDIO)
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/FFTFrame.h b/chromium/third_party/WebKit/Source/core/platform/audio/FFTFrame.h
deleted file mode 100644
index 38f9016dd4c..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/FFTFrame.h
+++ /dev/null
@@ -1,159 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef FFTFrame_h
-#define FFTFrame_h
-
-#include "core/platform/audio/AudioArray.h"
-
-#if OS(MACOSX) && !USE(WEBAUDIO_FFMPEG)
-#define USE_ACCELERATE_FFT 1
-#else
-#define USE_ACCELERATE_FFT 0
-#endif
-
-#if USE_ACCELERATE_FFT
-#include <Accelerate/Accelerate.h>
-#endif
-
-#if !USE_ACCELERATE_FFT
-
-#if USE(WEBAUDIO_OPENMAX_DL_FFT)
-#include "dl/sp/api/omxSP.h"
-#elif USE(WEBAUDIO_FFMPEG)
-struct RDFTContext;
-#endif
-
-#endif // !USE_ACCELERATE_FFT
-
-#if USE(WEBAUDIO_IPP)
-#include <ipps.h>
-#endif // USE(WEBAUDIO_IPP)
-
-#include "wtf/Forward.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/Threading.h"
-
-namespace WebCore {
-
-// Defines the interface for an "FFT frame", an object which is able to perform a forward
-// and reverse FFT, internally storing the resultant frequency-domain data.
-
-class FFTFrame {
-public:
- // The constructors, destructor, and methods up to the CROSS-PLATFORM section have platform-dependent implementations.
-
- FFTFrame(unsigned fftSize);
- FFTFrame(); // creates a blank/empty frame for later use with createInterpolatedFrame()
- FFTFrame(const FFTFrame& frame);
- ~FFTFrame();
-
- static void initialize();
- static void cleanup();
- void doFFT(const float* data);
- void doInverseFFT(float* data);
- void multiply(const FFTFrame& frame); // multiplies ourself with frame : effectively operator*=()
-
- float* realData() const;
- float* imagData() const;
-
- void print(); // for debugging
-
- // CROSS-PLATFORM
- // The remaining public methods have cross-platform implementations:
-
- // Interpolates from frame1 -> frame2 as x goes from 0.0 -> 1.0
- static PassOwnPtr<FFTFrame> createInterpolatedFrame(const FFTFrame& frame1, const FFTFrame& frame2, double x);
-
- void doPaddedFFT(const float* data, size_t dataSize); // zero-padding with dataSize <= fftSize
- double extractAverageGroupDelay();
- void addConstantGroupDelay(double sampleFrameDelay);
-
- unsigned fftSize() const { return m_FFTSize; }
- unsigned log2FFTSize() const { return m_log2FFTSize; }
-
-private:
- unsigned m_FFTSize;
- unsigned m_log2FFTSize;
-
- void interpolateFrequencyComponents(const FFTFrame& frame1, const FFTFrame& frame2, double x);
-
-#if USE_ACCELERATE_FFT
- DSPSplitComplex& dspSplitComplex() { return m_frame; }
- DSPSplitComplex dspSplitComplex() const { return m_frame; }
-
- static FFTSetup fftSetupForSize(unsigned fftSize);
-
- static FFTSetup* fftSetups;
-
- FFTSetup m_FFTSetup;
-
- DSPSplitComplex m_frame;
- AudioFloatArray m_realData;
- AudioFloatArray m_imagData;
-#else // !USE_ACCELERATE_FFT
-
-#if USE(WEBAUDIO_FFMPEG)
- static RDFTContext* contextForSize(unsigned fftSize, int trans);
-
- RDFTContext* m_forwardContext;
- RDFTContext* m_inverseContext;
-
- float* getUpToDateComplexData();
- AudioFloatArray m_complexData;
- AudioFloatArray m_realData;
- AudioFloatArray m_imagData;
-#endif // USE(WEBAUDIO_FFMPEG)
-
-#if USE(WEBAUDIO_IPP)
- Ipp8u* m_buffer;
- IppsDFTSpec_R_32f* m_DFTSpec;
-
- float* getUpToDateComplexData();
- AudioFloatArray m_complexData;
- AudioFloatArray m_realData;
- AudioFloatArray m_imagData;
-#endif // USE(WEBAUDIO_IPP)
-
-#if USE(WEBAUDIO_OPENMAX_DL_FFT)
- static OMXFFTSpec_R_F32* contextForSize(unsigned log2FFTSize);
-
- OMXFFTSpec_R_F32* m_forwardContext;
- OMXFFTSpec_R_F32* m_inverseContext;
-
- AudioFloatArray m_complexData;
- AudioFloatArray m_realData;
- AudioFloatArray m_imagData;
-#endif
-
-#endif // !USE_ACCELERATE_FFT
-};
-
-} // namespace WebCore
-
-#endif // FFTFrame_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/FFTFrameStub.cpp b/chromium/third_party/WebKit/Source/core/platform/audio/FFTFrameStub.cpp
deleted file mode 100644
index 6a0f887a581..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/FFTFrameStub.cpp
+++ /dev/null
@@ -1,107 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-// FFTFrame stub implementation to avoid link errors during bringup
-
-#include "config.h"
-
-#if ENABLE(WEB_AUDIO)
-
-#if !OS(MACOSX) && !USE(WEBAUDIO_FFMPEG) && !USE(WEBAUDIO_IPP) && !USE(WEBAUDIO_OPENMAX_DL_FFT)
-
-#include "core/platform/audio/FFTFrame.h"
-
-namespace WebCore {
-
-// Normal constructor: allocates for a given fftSize.
-FFTFrame::FFTFrame(unsigned /*fftSize*/)
- : m_FFTSize(0)
- , m_log2FFTSize(0)
-{
- ASSERT_NOT_REACHED();
-}
-
-// Creates a blank/empty frame (interpolate() must later be called).
-FFTFrame::FFTFrame()
- : m_FFTSize(0)
- , m_log2FFTSize(0)
-{
- ASSERT_NOT_REACHED();
-}
-
-// Copy constructor.
-FFTFrame::FFTFrame(const FFTFrame& frame)
- : m_FFTSize(frame.m_FFTSize)
- , m_log2FFTSize(frame.m_log2FFTSize)
-{
- ASSERT_NOT_REACHED();
-}
-
-FFTFrame::~FFTFrame()
-{
- ASSERT_NOT_REACHED();
-}
-
-void FFTFrame::multiply(const FFTFrame& frame)
-{
- ASSERT_NOT_REACHED();
-}
-
-void FFTFrame::doFFT(const float* data)
-{
- ASSERT_NOT_REACHED();
-}
-
-void FFTFrame::doInverseFFT(float* data)
-{
- ASSERT_NOT_REACHED();
-}
-
-void FFTFrame::initialize()
-{
-}
-
-void FFTFrame::cleanup()
-{
- ASSERT_NOT_REACHED();
-}
-
-float* FFTFrame::realData() const
-{
- ASSERT_NOT_REACHED();
- return 0;
-}
-
-float* FFTFrame::imagData() const
-{
- ASSERT_NOT_REACHED();
- return 0;
-}
-
-} // namespace WebCore
-
-#endif // !OS(MACOSX) && !USE(WEBAUDIO_FFMPEG) && !USE(WEBAUDIO_IPP) && !USE(WEBAUDIO_OPENMAX_DL_FFT)
-
-#endif // ENABLE(WEB_AUDIO)
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/HRTFDatabase.cpp b/chromium/third_party/WebKit/Source/core/platform/audio/HRTFDatabase.cpp
deleted file mode 100644
index 9980211c575..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/HRTFDatabase.cpp
+++ /dev/null
@@ -1,124 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#if ENABLE(WEB_AUDIO)
-
-#include "core/platform/audio/HRTFDatabase.h"
-
-#include "core/platform/audio/HRTFElevation.h"
-
-using namespace std;
-
-namespace WebCore {
-
-const int HRTFDatabase::MinElevation = -45;
-const int HRTFDatabase::MaxElevation = 90;
-const unsigned HRTFDatabase::RawElevationAngleSpacing = 15;
-const unsigned HRTFDatabase::NumberOfRawElevations = 10; // -45 -> +90 (each 15 degrees)
-const unsigned HRTFDatabase::InterpolationFactor = 1;
-const unsigned HRTFDatabase::NumberOfTotalElevations = NumberOfRawElevations * InterpolationFactor;
-
-PassOwnPtr<HRTFDatabase> HRTFDatabase::create(float sampleRate)
-{
- OwnPtr<HRTFDatabase> hrtfDatabase = adoptPtr(new HRTFDatabase(sampleRate));
- return hrtfDatabase.release();
-}
-
-HRTFDatabase::HRTFDatabase(float sampleRate)
- : m_elevations(NumberOfTotalElevations)
- , m_sampleRate(sampleRate)
-{
- unsigned elevationIndex = 0;
- for (int elevation = MinElevation; elevation <= MaxElevation; elevation += RawElevationAngleSpacing) {
- OwnPtr<HRTFElevation> hrtfElevation = HRTFElevation::createForSubject("Composite", elevation, sampleRate);
- ASSERT(hrtfElevation.get());
- if (!hrtfElevation.get())
- return;
-
- m_elevations[elevationIndex] = hrtfElevation.release();
- elevationIndex += InterpolationFactor;
- }
-
- // Now, go back and interpolate elevations.
- if (InterpolationFactor > 1) {
- for (unsigned i = 0; i < NumberOfTotalElevations; i += InterpolationFactor) {
- unsigned j = (i + InterpolationFactor);
- if (j >= NumberOfTotalElevations)
- j = i; // for last elevation interpolate with itself
-
- // Create the interpolated convolution kernels and delays.
- for (unsigned jj = 1; jj < InterpolationFactor; ++jj) {
- float x = static_cast<float>(jj) / static_cast<float>(InterpolationFactor);
- m_elevations[i + jj] = HRTFElevation::createByInterpolatingSlices(m_elevations[i].get(), m_elevations[j].get(), x, sampleRate);
- ASSERT(m_elevations[i + jj].get());
- }
- }
- }
-}
-
-void HRTFDatabase::getKernelsFromAzimuthElevation(double azimuthBlend, unsigned azimuthIndex, double elevationAngle, HRTFKernel* &kernelL, HRTFKernel* &kernelR,
- double& frameDelayL, double& frameDelayR)
-{
- unsigned elevationIndex = indexFromElevationAngle(elevationAngle);
- ASSERT_WITH_SECURITY_IMPLICATION(elevationIndex < m_elevations.size() && m_elevations.size() > 0);
-
- if (!m_elevations.size()) {
- kernelL = 0;
- kernelR = 0;
- return;
- }
-
- if (elevationIndex > m_elevations.size() - 1)
- elevationIndex = m_elevations.size() - 1;
-
- HRTFElevation* hrtfElevation = m_elevations[elevationIndex].get();
- ASSERT(hrtfElevation);
- if (!hrtfElevation) {
- kernelL = 0;
- kernelR = 0;
- return;
- }
-
- hrtfElevation->getKernelsFromAzimuth(azimuthBlend, azimuthIndex, kernelL, kernelR, frameDelayL, frameDelayR);
-}
-
-unsigned HRTFDatabase::indexFromElevationAngle(double elevationAngle)
-{
- // Clamp to allowed range.
- elevationAngle = max(static_cast<double>(MinElevation), elevationAngle);
- elevationAngle = min(static_cast<double>(MaxElevation), elevationAngle);
-
- unsigned elevationIndex = static_cast<int>(InterpolationFactor * (elevationAngle - MinElevation) / RawElevationAngleSpacing);
- return elevationIndex;
-}
-
-} // namespace WebCore
-
-#endif // ENABLE(WEB_AUDIO)
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/HRTFDatabase.h b/chromium/third_party/WebKit/Source/core/platform/audio/HRTFDatabase.h
deleted file mode 100644
index 30c2c263ded..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/HRTFDatabase.h
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef HRTFDatabase_h
-#define HRTFDatabase_h
-
-#include "core/platform/audio/HRTFElevation.h"
-#include "wtf/Forward.h"
-#include "wtf/Noncopyable.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-class HRTFKernel;
-
-class HRTFDatabase {
- WTF_MAKE_NONCOPYABLE(HRTFDatabase);
-public:
- static PassOwnPtr<HRTFDatabase> create(float sampleRate);
-
- // getKernelsFromAzimuthElevation() returns a left and right ear kernel, and an interpolated left and right frame delay for the given azimuth and elevation.
- // azimuthBlend must be in the range 0 -> 1.
- // Valid values for azimuthIndex are 0 -> HRTFElevation::NumberOfTotalAzimuths - 1 (corresponding to angles of 0 -> 360).
- // Valid values for elevationAngle are MinElevation -> MaxElevation.
- void getKernelsFromAzimuthElevation(double azimuthBlend, unsigned azimuthIndex, double elevationAngle, HRTFKernel* &kernelL, HRTFKernel* &kernelR, double& frameDelayL, double& frameDelayR);
-
- // Returns the number of different azimuth angles.
- static unsigned numberOfAzimuths() { return HRTFElevation::NumberOfTotalAzimuths; }
-
- float sampleRate() const { return m_sampleRate; }
-
- // Number of elevations loaded from resource.
- static const unsigned NumberOfRawElevations;
-
-private:
- explicit HRTFDatabase(float sampleRate);
-
- // Minimum and maximum elevation angles (inclusive) for a HRTFDatabase.
- static const int MinElevation;
- static const int MaxElevation;
- static const unsigned RawElevationAngleSpacing;
-
- // Interpolates by this factor to get the total number of elevations from every elevation loaded from resource.
- static const unsigned InterpolationFactor;
-
- // Total number of elevations after interpolation.
- static const unsigned NumberOfTotalElevations;
-
- // Returns the index for the correct HRTFElevation given the elevation angle.
- static unsigned indexFromElevationAngle(double);
-
- Vector<OwnPtr<HRTFElevation> > m_elevations;
- float m_sampleRate;
-};
-
-} // namespace WebCore
-
-#endif // HRTFDatabase_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/HRTFDatabaseLoader.cpp b/chromium/third_party/WebKit/Source/core/platform/audio/HRTFDatabaseLoader.cpp
deleted file mode 100644
index 47219ec6365..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/HRTFDatabaseLoader.cpp
+++ /dev/null
@@ -1,131 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#if ENABLE(WEB_AUDIO)
-
-#include "core/platform/audio/HRTFDatabaseLoader.h"
-
-#include "core/platform/audio/HRTFDatabase.h"
-#include "wtf/MainThread.h"
-
-namespace WebCore {
-
-// Singleton
-HRTFDatabaseLoader::LoaderMap* HRTFDatabaseLoader::s_loaderMap = 0;
-
-PassRefPtr<HRTFDatabaseLoader> HRTFDatabaseLoader::createAndLoadAsynchronouslyIfNecessary(float sampleRate)
-{
- ASSERT(isMainThread());
-
- RefPtr<HRTFDatabaseLoader> loader;
-
- if (!s_loaderMap)
- s_loaderMap = adoptPtr(new LoaderMap()).leakPtr();
-
- loader = s_loaderMap->get(sampleRate);
- if (loader) {
- ASSERT(sampleRate == loader->databaseSampleRate());
- return loader;
- }
-
- loader = adoptRef(new HRTFDatabaseLoader(sampleRate));
- s_loaderMap->add(sampleRate, loader.get());
-
- loader->loadAsynchronously();
-
- return loader;
-}
-
-HRTFDatabaseLoader::HRTFDatabaseLoader(float sampleRate)
- : m_databaseLoaderThread(0)
- , m_databaseSampleRate(sampleRate)
-{
- ASSERT(isMainThread());
-}
-
-HRTFDatabaseLoader::~HRTFDatabaseLoader()
-{
- ASSERT(isMainThread());
-
- waitForLoaderThreadCompletion();
- m_hrtfDatabase.clear();
-
- // Remove ourself from the map.
- if (s_loaderMap)
- s_loaderMap->remove(m_databaseSampleRate);
-}
-
-// Asynchronously load the database in this thread.
-static void databaseLoaderEntry(void* threadData)
-{
- HRTFDatabaseLoader* loader = reinterpret_cast<HRTFDatabaseLoader*>(threadData);
- ASSERT(loader);
- loader->load();
-}
-
-void HRTFDatabaseLoader::load()
-{
- ASSERT(!isMainThread());
- if (!m_hrtfDatabase.get()) {
- // Load the default HRTF database.
- m_hrtfDatabase = HRTFDatabase::create(m_databaseSampleRate);
- }
-}
-
-void HRTFDatabaseLoader::loadAsynchronously()
-{
- ASSERT(isMainThread());
-
- MutexLocker locker(m_threadLock);
-
- if (!m_hrtfDatabase.get() && !m_databaseLoaderThread) {
- // Start the asynchronous database loading process.
- m_databaseLoaderThread = createThread(databaseLoaderEntry, this, "HRTF database loader");
- }
-}
-
-bool HRTFDatabaseLoader::isLoaded() const
-{
- return m_hrtfDatabase.get();
-}
-
-void HRTFDatabaseLoader::waitForLoaderThreadCompletion()
-{
- MutexLocker locker(m_threadLock);
-
- // waitForThreadCompletion() should not be called twice for the same thread.
- if (m_databaseLoaderThread)
- waitForThreadCompletion(m_databaseLoaderThread);
- m_databaseLoaderThread = 0;
-}
-
-} // namespace WebCore
-
-#endif // ENABLE(WEB_AUDIO)
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/HRTFDatabaseLoader.h b/chromium/third_party/WebKit/Source/core/platform/audio/HRTFDatabaseLoader.h
deleted file mode 100644
index 65de173a010..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/HRTFDatabaseLoader.h
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef HRTFDatabaseLoader_h
-#define HRTFDatabaseLoader_h
-
-#include "core/platform/audio/HRTFDatabase.h"
-#include "wtf/HashMap.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/RefPtr.h"
-#include "wtf/Threading.h"
-#include "wtf/ThreadingPrimitives.h"
-
-namespace WebCore {
-
-// HRTFDatabaseLoader will asynchronously load the default HRTFDatabase in a new thread.
-
-class HRTFDatabaseLoader : public RefCounted<HRTFDatabaseLoader> {
-public:
- // Lazily creates a HRTFDatabaseLoader (if not already created) for the given sample-rate
- // and starts loading asynchronously (when created the first time).
- // Returns the HRTFDatabaseLoader.
- // Must be called from the main thread.
- static PassRefPtr<HRTFDatabaseLoader> createAndLoadAsynchronouslyIfNecessary(float sampleRate);
-
- // Both constructor and destructor must be called from the main thread.
- ~HRTFDatabaseLoader();
-
- // Returns true once the default database has been completely loaded.
- bool isLoaded() const;
-
- // waitForLoaderThreadCompletion() may be called more than once and is thread-safe.
- void waitForLoaderThreadCompletion();
-
- HRTFDatabase* database() { return m_hrtfDatabase.get(); }
-
- float databaseSampleRate() const { return m_databaseSampleRate; }
-
- // Called in asynchronous loading thread.
- void load();
-
-private:
- // Both constructor and destructor must be called from the main thread.
- explicit HRTFDatabaseLoader(float sampleRate);
-
- // If it hasn't already been loaded, creates a new thread and initiates asynchronous loading of the default database.
- // This must be called from the main thread.
- void loadAsynchronously();
-
- // Map from sample-rate to loader.
- typedef HashMap<double, HRTFDatabaseLoader*> LoaderMap;
-
- // Keeps track of loaders on a per-sample-rate basis.
- static LoaderMap* s_loaderMap; // singleton
-
- OwnPtr<HRTFDatabase> m_hrtfDatabase;
-
- // Holding a m_threadLock is required when accessing m_databaseLoaderThread.
- Mutex m_threadLock;
- ThreadIdentifier m_databaseLoaderThread;
-
- float m_databaseSampleRate;
-};
-
-} // namespace WebCore
-
-#endif // HRTFDatabaseLoader_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/HRTFElevation.cpp b/chromium/third_party/WebKit/Source/core/platform/audio/HRTFElevation.cpp
deleted file mode 100644
index a5c606cdb95..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/HRTFElevation.cpp
+++ /dev/null
@@ -1,342 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#if ENABLE(WEB_AUDIO)
-
-#include "core/platform/audio/HRTFElevation.h"
-
-#include <math.h>
-#include <algorithm>
-#include "core/platform/audio/AudioBus.h"
-#include "core/platform/audio/HRTFPanner.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/ThreadingPrimitives.h"
-
-using namespace std;
-
-namespace WebCore {
-
-const unsigned HRTFElevation::AzimuthSpacing = 15;
-const unsigned HRTFElevation::NumberOfRawAzimuths = 360 / AzimuthSpacing;
-const unsigned HRTFElevation::InterpolationFactor = 8;
-const unsigned HRTFElevation::NumberOfTotalAzimuths = NumberOfRawAzimuths * InterpolationFactor;
-
-// Total number of components of an HRTF database.
-const size_t TotalNumberOfResponses = 240;
-
-// Number of frames in an individual impulse response.
-const size_t ResponseFrameSize = 256;
-
-// Sample-rate of the spatialization impulse responses as stored in the resource file.
-// The impulse responses may be resampled to a different sample-rate (depending on the audio hardware) when they are loaded.
-const float ResponseSampleRate = 44100;
-
-#if USE(CONCATENATED_IMPULSE_RESPONSES)
-// Lazily load a concatenated HRTF database for given subject and store it in a
-// local hash table to ensure quick efficient future retrievals.
-static PassRefPtr<AudioBus> getConcatenatedImpulseResponsesForSubject(const String& subjectName)
-{
- typedef HashMap<String, RefPtr<AudioBus> > AudioBusMap;
- DEFINE_STATIC_LOCAL(AudioBusMap, audioBusMap, ());
- DEFINE_STATIC_LOCAL(Mutex, mutex, ());
-
- MutexLocker locker(mutex);
- RefPtr<AudioBus> bus;
- AudioBusMap::iterator iterator = audioBusMap.find(subjectName);
- if (iterator == audioBusMap.end()) {
- RefPtr<AudioBus> concatenatedImpulseResponses(AudioBus::loadPlatformResource(subjectName.utf8().data(), ResponseSampleRate));
- ASSERT(concatenatedImpulseResponses);
- if (!concatenatedImpulseResponses)
- return 0;
-
- bus = concatenatedImpulseResponses;
- audioBusMap.set(subjectName, bus);
- } else
- bus = iterator->value;
-
- size_t responseLength = bus->length();
- size_t expectedLength = static_cast<size_t>(TotalNumberOfResponses * ResponseFrameSize);
-
- // Check number of channels and length. For now these are fixed and known.
- bool isBusGood = responseLength == expectedLength && bus->numberOfChannels() == 2;
- ASSERT(isBusGood);
- if (!isBusGood)
- return 0;
-
- return bus;
-}
-#endif
-
-// Takes advantage of the symmetry and creates a composite version of the two measured versions. For example, we have both azimuth 30 and -30 degrees
-// where the roles of left and right ears are reversed with respect to each other.
-bool HRTFElevation::calculateSymmetricKernelsForAzimuthElevation(int azimuth, int elevation, float sampleRate, const String& subjectName,
- RefPtr<HRTFKernel>& kernelL, RefPtr<HRTFKernel>& kernelR)
-{
- RefPtr<HRTFKernel> kernelL1;
- RefPtr<HRTFKernel> kernelR1;
- bool success = calculateKernelsForAzimuthElevation(azimuth, elevation, sampleRate, subjectName, kernelL1, kernelR1);
- if (!success)
- return false;
-
- // And symmetric version
- int symmetricAzimuth = !azimuth ? 0 : 360 - azimuth;
-
- RefPtr<HRTFKernel> kernelL2;
- RefPtr<HRTFKernel> kernelR2;
- success = calculateKernelsForAzimuthElevation(symmetricAzimuth, elevation, sampleRate, subjectName, kernelL2, kernelR2);
- if (!success)
- return false;
-
- // Notice L/R reversal in symmetric version.
- kernelL = HRTFKernel::createInterpolatedKernel(kernelL1.get(), kernelR2.get(), 0.5f);
- kernelR = HRTFKernel::createInterpolatedKernel(kernelR1.get(), kernelL2.get(), 0.5f);
-
- return true;
-}
-
-bool HRTFElevation::calculateKernelsForAzimuthElevation(int azimuth, int elevation, float sampleRate, const String& subjectName,
- RefPtr<HRTFKernel>& kernelL, RefPtr<HRTFKernel>& kernelR)
-{
- // Valid values for azimuth are 0 -> 345 in 15 degree increments.
- // Valid values for elevation are -45 -> +90 in 15 degree increments.
-
- bool isAzimuthGood = azimuth >= 0 && azimuth <= 345 && (azimuth / 15) * 15 == azimuth;
- ASSERT(isAzimuthGood);
- if (!isAzimuthGood)
- return false;
-
- bool isElevationGood = elevation >= -45 && elevation <= 90 && (elevation / 15) * 15 == elevation;
- ASSERT(isElevationGood);
- if (!isElevationGood)
- return false;
-
- // Construct the resource name from the subject name, azimuth, and elevation, for example:
- // "IRC_Composite_C_R0195_T015_P000"
- // Note: the passed in subjectName is not a string passed in via JavaScript or the web.
- // It's passed in as an internal ASCII identifier and is an implementation detail.
- int positiveElevation = elevation < 0 ? elevation + 360 : elevation;
-
-#if USE(CONCATENATED_IMPULSE_RESPONSES)
- RefPtr<AudioBus> bus(getConcatenatedImpulseResponsesForSubject(subjectName));
-
- if (!bus)
- return false;
-
- int elevationIndex = positiveElevation / AzimuthSpacing;
- if (positiveElevation > 90)
- elevationIndex -= AzimuthSpacing;
-
- // The concatenated impulse response is a bus containing all
- // the elevations per azimuth, for all azimuths by increasing
- // order. So for a given azimuth and elevation we need to compute
- // the index of the wanted audio frames in the concatenated table.
- unsigned index = ((azimuth / AzimuthSpacing) * HRTFDatabase::NumberOfRawElevations) + elevationIndex;
- bool isIndexGood = index < TotalNumberOfResponses;
- ASSERT(isIndexGood);
- if (!isIndexGood)
- return false;
-
- // Extract the individual impulse response from the concatenated
- // responses and potentially sample-rate convert it to the desired
- // (hardware) sample-rate.
- unsigned startFrame = index * ResponseFrameSize;
- unsigned stopFrame = startFrame + ResponseFrameSize;
- RefPtr<AudioBus> preSampleRateConvertedResponse(AudioBus::createBufferFromRange(bus.get(), startFrame, stopFrame));
- RefPtr<AudioBus> response(AudioBus::createBySampleRateConverting(preSampleRateConvertedResponse.get(), false, sampleRate));
- AudioChannel* leftEarImpulseResponse = response->channel(AudioBus::ChannelLeft);
- AudioChannel* rightEarImpulseResponse = response->channel(AudioBus::ChannelRight);
-#else
- String resourceName = String::format("IRC_%s_C_R0195_T%03d_P%03d", subjectName.utf8().data(), azimuth, positiveElevation);
-
- RefPtr<AudioBus> impulseResponse(AudioBus::loadPlatformResource(resourceName.utf8().data(), sampleRate));
-
- ASSERT(impulseResponse.get());
- if (!impulseResponse.get())
- return false;
-
- size_t responseLength = impulseResponse->length();
- size_t expectedLength = static_cast<size_t>(256 * (sampleRate / 44100.0));
-
- // Check number of channels and length. For now these are fixed and known.
- bool isBusGood = responseLength == expectedLength && impulseResponse->numberOfChannels() == 2;
- ASSERT(isBusGood);
- if (!isBusGood)
- return false;
-
- AudioChannel* leftEarImpulseResponse = impulseResponse->channelByType(AudioBus::ChannelLeft);
- AudioChannel* rightEarImpulseResponse = impulseResponse->channelByType(AudioBus::ChannelRight);
-#endif
-
- // Note that depending on the fftSize returned by the panner, we may be truncating the impulse response we just loaded in.
- const size_t fftSize = HRTFPanner::fftSizeForSampleRate(sampleRate);
- kernelL = HRTFKernel::create(leftEarImpulseResponse, fftSize, sampleRate);
- kernelR = HRTFKernel::create(rightEarImpulseResponse, fftSize, sampleRate);
-
- return true;
-}
-
-// The range of elevations for the IRCAM impulse responses varies depending on azimuth, but the minimum elevation appears to always be -45.
-//
-// Here's how it goes:
-static int maxElevations[] = {
- // Azimuth
- //
- 90, // 0
- 45, // 15
- 60, // 30
- 45, // 45
- 75, // 60
- 45, // 75
- 60, // 90
- 45, // 105
- 75, // 120
- 45, // 135
- 60, // 150
- 45, // 165
- 75, // 180
- 45, // 195
- 60, // 210
- 45, // 225
- 75, // 240
- 45, // 255
- 60, // 270
- 45, // 285
- 75, // 300
- 45, // 315
- 60, // 330
- 45 // 345
-};
-
-PassOwnPtr<HRTFElevation> HRTFElevation::createForSubject(const String& subjectName, int elevation, float sampleRate)
-{
- bool isElevationGood = elevation >= -45 && elevation <= 90 && (elevation / 15) * 15 == elevation;
- ASSERT(isElevationGood);
- if (!isElevationGood)
- return nullptr;
-
- OwnPtr<HRTFKernelList> kernelListL = adoptPtr(new HRTFKernelList(NumberOfTotalAzimuths));
- OwnPtr<HRTFKernelList> kernelListR = adoptPtr(new HRTFKernelList(NumberOfTotalAzimuths));
-
- // Load convolution kernels from HRTF files.
- int interpolatedIndex = 0;
- for (unsigned rawIndex = 0; rawIndex < NumberOfRawAzimuths; ++rawIndex) {
- // Don't let elevation exceed maximum for this azimuth.
- int maxElevation = maxElevations[rawIndex];
- int actualElevation = min(elevation, maxElevation);
-
- bool success = calculateKernelsForAzimuthElevation(rawIndex * AzimuthSpacing, actualElevation, sampleRate, subjectName, kernelListL->at(interpolatedIndex), kernelListR->at(interpolatedIndex));
- if (!success)
- return nullptr;
-
- interpolatedIndex += InterpolationFactor;
- }
-
- // Now go back and interpolate intermediate azimuth values.
- for (unsigned i = 0; i < NumberOfTotalAzimuths; i += InterpolationFactor) {
- int j = (i + InterpolationFactor) % NumberOfTotalAzimuths;
-
- // Create the interpolated convolution kernels and delays.
- for (unsigned jj = 1; jj < InterpolationFactor; ++jj) {
- float x = float(jj) / float(InterpolationFactor); // interpolate from 0 -> 1
-
- (*kernelListL)[i + jj] = HRTFKernel::createInterpolatedKernel(kernelListL->at(i).get(), kernelListL->at(j).get(), x);
- (*kernelListR)[i + jj] = HRTFKernel::createInterpolatedKernel(kernelListR->at(i).get(), kernelListR->at(j).get(), x);
- }
- }
-
- OwnPtr<HRTFElevation> hrtfElevation = adoptPtr(new HRTFElevation(kernelListL.release(), kernelListR.release(), elevation, sampleRate));
- return hrtfElevation.release();
-}
-
-PassOwnPtr<HRTFElevation> HRTFElevation::createByInterpolatingSlices(HRTFElevation* hrtfElevation1, HRTFElevation* hrtfElevation2, float x, float sampleRate)
-{
- ASSERT(hrtfElevation1 && hrtfElevation2);
- if (!hrtfElevation1 || !hrtfElevation2)
- return nullptr;
-
- ASSERT(x >= 0.0 && x < 1.0);
-
- OwnPtr<HRTFKernelList> kernelListL = adoptPtr(new HRTFKernelList(NumberOfTotalAzimuths));
- OwnPtr<HRTFKernelList> kernelListR = adoptPtr(new HRTFKernelList(NumberOfTotalAzimuths));
-
- HRTFKernelList* kernelListL1 = hrtfElevation1->kernelListL();
- HRTFKernelList* kernelListR1 = hrtfElevation1->kernelListR();
- HRTFKernelList* kernelListL2 = hrtfElevation2->kernelListL();
- HRTFKernelList* kernelListR2 = hrtfElevation2->kernelListR();
-
- // Interpolate kernels of corresponding azimuths of the two elevations.
- for (unsigned i = 0; i < NumberOfTotalAzimuths; ++i) {
- (*kernelListL)[i] = HRTFKernel::createInterpolatedKernel(kernelListL1->at(i).get(), kernelListL2->at(i).get(), x);
- (*kernelListR)[i] = HRTFKernel::createInterpolatedKernel(kernelListR1->at(i).get(), kernelListR2->at(i).get(), x);
- }
-
- // Interpolate elevation angle.
- double angle = (1.0 - x) * hrtfElevation1->elevationAngle() + x * hrtfElevation2->elevationAngle();
-
- OwnPtr<HRTFElevation> hrtfElevation = adoptPtr(new HRTFElevation(kernelListL.release(), kernelListR.release(), static_cast<int>(angle), sampleRate));
- return hrtfElevation.release();
-}
-
-void HRTFElevation::getKernelsFromAzimuth(double azimuthBlend, unsigned azimuthIndex, HRTFKernel* &kernelL, HRTFKernel* &kernelR, double& frameDelayL, double& frameDelayR)
-{
- bool checkAzimuthBlend = azimuthBlend >= 0.0 && azimuthBlend < 1.0;
- ASSERT(checkAzimuthBlend);
- if (!checkAzimuthBlend)
- azimuthBlend = 0.0;
-
- unsigned numKernels = m_kernelListL->size();
-
- bool isIndexGood = azimuthIndex < numKernels;
- ASSERT(isIndexGood);
- if (!isIndexGood) {
- kernelL = 0;
- kernelR = 0;
- return;
- }
-
- // Return the left and right kernels.
- kernelL = m_kernelListL->at(azimuthIndex).get();
- kernelR = m_kernelListR->at(azimuthIndex).get();
-
- frameDelayL = m_kernelListL->at(azimuthIndex)->frameDelay();
- frameDelayR = m_kernelListR->at(azimuthIndex)->frameDelay();
-
- int azimuthIndex2 = (azimuthIndex + 1) % numKernels;
- double frameDelay2L = m_kernelListL->at(azimuthIndex2)->frameDelay();
- double frameDelay2R = m_kernelListR->at(azimuthIndex2)->frameDelay();
-
- // Linearly interpolate delays.
- frameDelayL = (1.0 - azimuthBlend) * frameDelayL + azimuthBlend * frameDelay2L;
- frameDelayR = (1.0 - azimuthBlend) * frameDelayR + azimuthBlend * frameDelay2R;
-}
-
-} // namespace WebCore
-
-#endif // ENABLE(WEB_AUDIO)
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/HRTFElevation.h b/chromium/third_party/WebKit/Source/core/platform/audio/HRTFElevation.h
deleted file mode 100644
index b16408d66b9..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/HRTFElevation.h
+++ /dev/null
@@ -1,112 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef HRTFElevation_h
-#define HRTFElevation_h
-
-#include "core/platform/audio/HRTFKernel.h"
-#include "wtf/Noncopyable.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/RefPtr.h"
-#include "wtf/text/CString.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-// HRTFElevation contains all of the HRTFKernels (one left ear and one right ear per azimuth angle) for a particular elevation.
-
-class HRTFElevation {
- WTF_MAKE_NONCOPYABLE(HRTFElevation);
-public:
- // Loads and returns an HRTFElevation with the given HRTF database subject name and elevation from browser (or WebKit.framework) resources.
- // Normally, there will only be a single HRTF database set, but this API supports the possibility of multiple ones with different names.
- // Interpolated azimuths will be generated based on InterpolationFactor.
- // Valid values for elevation are -45 -> +90 in 15 degree increments.
- static PassOwnPtr<HRTFElevation> createForSubject(const String& subjectName, int elevation, float sampleRate);
-
- // Given two HRTFElevations, and an interpolation factor x: 0 -> 1, returns an interpolated HRTFElevation.
- static PassOwnPtr<HRTFElevation> createByInterpolatingSlices(HRTFElevation* hrtfElevation1, HRTFElevation* hrtfElevation2, float x, float sampleRate);
-
- // Returns the list of left or right ear HRTFKernels for all the azimuths going from 0 to 360 degrees.
- HRTFKernelList* kernelListL() { return m_kernelListL.get(); }
- HRTFKernelList* kernelListR() { return m_kernelListR.get(); }
-
- double elevationAngle() const { return m_elevationAngle; }
- unsigned numberOfAzimuths() const { return NumberOfTotalAzimuths; }
- float sampleRate() const { return m_sampleRate; }
-
- // Returns the left and right kernels for the given azimuth index.
- // The interpolated delays based on azimuthBlend: 0 -> 1 are returned in frameDelayL and frameDelayR.
- void getKernelsFromAzimuth(double azimuthBlend, unsigned azimuthIndex, HRTFKernel* &kernelL, HRTFKernel* &kernelR, double& frameDelayL, double& frameDelayR);
-
- // Spacing, in degrees, between every azimuth loaded from resource.
- static const unsigned AzimuthSpacing;
-
- // Number of azimuths loaded from resource.
- static const unsigned NumberOfRawAzimuths;
-
- // Interpolates by this factor to get the total number of azimuths from every azimuth loaded from resource.
- static const unsigned InterpolationFactor;
-
- // Total number of azimuths after interpolation.
- static const unsigned NumberOfTotalAzimuths;
-
- // Given a specific azimuth and elevation angle, returns the left and right HRTFKernel.
- // Valid values for azimuth are 0 -> 345 in 15 degree increments.
- // Valid values for elevation are -45 -> +90 in 15 degree increments.
- // Returns true on success.
- static bool calculateKernelsForAzimuthElevation(int azimuth, int elevation, float sampleRate, const String& subjectName,
- RefPtr<HRTFKernel>& kernelL, RefPtr<HRTFKernel>& kernelR);
-
- // Given a specific azimuth and elevation angle, returns the left and right HRTFKernel in kernelL and kernelR.
- // This method averages the measured response using symmetry of azimuth (for example by averaging the -30.0 and +30.0 azimuth responses).
- // Returns true on success.
- static bool calculateSymmetricKernelsForAzimuthElevation(int azimuth, int elevation, float sampleRate, const String& subjectName,
- RefPtr<HRTFKernel>& kernelL, RefPtr<HRTFKernel>& kernelR);
-
-private:
- HRTFElevation(PassOwnPtr<HRTFKernelList> kernelListL, PassOwnPtr<HRTFKernelList> kernelListR, int elevation, float sampleRate)
- : m_kernelListL(kernelListL)
- , m_kernelListR(kernelListR)
- , m_elevationAngle(elevation)
- , m_sampleRate(sampleRate)
- {
- }
-
- OwnPtr<HRTFKernelList> m_kernelListL;
- OwnPtr<HRTFKernelList> m_kernelListR;
- double m_elevationAngle;
- float m_sampleRate;
-};
-
-} // namespace WebCore
-
-#endif // HRTFElevation_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/HRTFKernel.cpp b/chromium/third_party/WebKit/Source/core/platform/audio/HRTFKernel.cpp
deleted file mode 100644
index d825962cd37..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/HRTFKernel.cpp
+++ /dev/null
@@ -1,136 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#if ENABLE(WEB_AUDIO)
-
-#include "core/platform/audio/HRTFKernel.h"
-
-#include "core/platform/FloatConversion.h"
-#include "core/platform/audio/AudioChannel.h"
-#include "core/platform/audio/FFTFrame.h"
-#include "wtf/MathExtras.h"
-
-using namespace std;
-
-namespace WebCore {
-
-// Takes the input AudioChannel as an input impulse response and calculates the average group delay.
-// This represents the initial delay before the most energetic part of the impulse response.
-// The sample-frame delay is removed from the impulseP impulse response, and this value is returned.
-// the length of the passed in AudioChannel must be a power of 2.
-static float extractAverageGroupDelay(AudioChannel* channel, size_t analysisFFTSize)
-{
- ASSERT(channel);
-
- float* impulseP = channel->mutableData();
-
- bool isSizeGood = channel->length() >= analysisFFTSize;
- ASSERT(isSizeGood);
- if (!isSizeGood)
- return 0;
-
- // Check for power-of-2.
- ASSERT(1UL << static_cast<unsigned>(log2(analysisFFTSize)) == analysisFFTSize);
-
- FFTFrame estimationFrame(analysisFFTSize);
- estimationFrame.doFFT(impulseP);
-
- float frameDelay = narrowPrecisionToFloat(estimationFrame.extractAverageGroupDelay());
- estimationFrame.doInverseFFT(impulseP);
-
- return frameDelay;
-}
-
-HRTFKernel::HRTFKernel(AudioChannel* channel, size_t fftSize, float sampleRate)
- : m_frameDelay(0)
- , m_sampleRate(sampleRate)
-{
- ASSERT(channel);
-
- // Determine the leading delay (average group delay) for the response.
- m_frameDelay = extractAverageGroupDelay(channel, fftSize / 2);
-
- float* impulseResponse = channel->mutableData();
- size_t responseLength = channel->length();
-
- // We need to truncate to fit into 1/2 the FFT size (with zero padding) in order to do proper convolution.
- size_t truncatedResponseLength = min(responseLength, fftSize / 2); // truncate if necessary to max impulse response length allowed by FFT
-
- // Quick fade-out (apply window) at truncation point
- unsigned numberOfFadeOutFrames = static_cast<unsigned>(sampleRate / 4410); // 10 sample-frames @44.1KHz sample-rate
- ASSERT(numberOfFadeOutFrames < truncatedResponseLength);
- if (numberOfFadeOutFrames < truncatedResponseLength) {
- for (unsigned i = truncatedResponseLength - numberOfFadeOutFrames; i < truncatedResponseLength; ++i) {
- float x = 1.0f - static_cast<float>(i - (truncatedResponseLength - numberOfFadeOutFrames)) / numberOfFadeOutFrames;
- impulseResponse[i] *= x;
- }
- }
-
- m_fftFrame = adoptPtr(new FFTFrame(fftSize));
- m_fftFrame->doPaddedFFT(impulseResponse, truncatedResponseLength);
-}
-
-PassOwnPtr<AudioChannel> HRTFKernel::createImpulseResponse()
-{
- OwnPtr<AudioChannel> channel = adoptPtr(new AudioChannel(fftSize()));
- FFTFrame fftFrame(*m_fftFrame);
-
- // Add leading delay back in.
- fftFrame.addConstantGroupDelay(m_frameDelay);
- fftFrame.doInverseFFT(channel->mutableData());
-
- return channel.release();
-}
-
-// Interpolates two kernels with x: 0 -> 1 and returns the result.
-PassRefPtr<HRTFKernel> HRTFKernel::createInterpolatedKernel(HRTFKernel* kernel1, HRTFKernel* kernel2, float x)
-{
- ASSERT(kernel1 && kernel2);
- if (!kernel1 || !kernel2)
- return 0;
-
- ASSERT(x >= 0.0 && x < 1.0);
- x = min(1.0f, max(0.0f, x));
-
- float sampleRate1 = kernel1->sampleRate();
- float sampleRate2 = kernel2->sampleRate();
- ASSERT(sampleRate1 == sampleRate2);
- if (sampleRate1 != sampleRate2)
- return 0;
-
- float frameDelay = (1 - x) * kernel1->frameDelay() + x * kernel2->frameDelay();
-
- OwnPtr<FFTFrame> interpolatedFrame = FFTFrame::createInterpolatedFrame(*kernel1->fftFrame(), *kernel2->fftFrame(), x);
- return HRTFKernel::create(interpolatedFrame.release(), frameDelay, sampleRate1);
-}
-
-} // namespace WebCore
-
-#endif // ENABLE(WEB_AUDIO)
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/HRTFKernel.h b/chromium/third_party/WebKit/Source/core/platform/audio/HRTFKernel.h
deleted file mode 100644
index 14b1db0655c..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/HRTFKernel.h
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef HRTFKernel_h
-#define HRTFKernel_h
-
-#include "core/platform/audio/FFTFrame.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/RefPtr.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-class AudioChannel;
-
-// HRTF stands for Head-Related Transfer Function.
-// HRTFKernel is a frequency-domain representation of an impulse-response used as part of the spatialized panning system.
-// For a given azimuth / elevation angle there will be one HRTFKernel for the left ear transfer function, and one for the right ear.
-// The leading delay (average group delay) for each impulse response is extracted:
-// m_fftFrame is the frequency-domain representation of the impulse response with the delay removed
-// m_frameDelay is the leading delay of the original impulse response.
-class HRTFKernel : public RefCounted<HRTFKernel> {
-public:
- // Note: this is destructive on the passed in AudioChannel.
- // The length of channel must be a power of two.
- static PassRefPtr<HRTFKernel> create(AudioChannel* channel, size_t fftSize, float sampleRate)
- {
- return adoptRef(new HRTFKernel(channel, fftSize, sampleRate));
- }
-
- static PassRefPtr<HRTFKernel> create(PassOwnPtr<FFTFrame> fftFrame, float frameDelay, float sampleRate)
- {
- return adoptRef(new HRTFKernel(fftFrame, frameDelay, sampleRate));
- }
-
- // Given two HRTFKernels, and an interpolation factor x: 0 -> 1, returns an interpolated HRTFKernel.
- static PassRefPtr<HRTFKernel> createInterpolatedKernel(HRTFKernel* kernel1, HRTFKernel* kernel2, float x);
-
- FFTFrame* fftFrame() { return m_fftFrame.get(); }
-
- size_t fftSize() const { return m_fftFrame->fftSize(); }
- float frameDelay() const { return m_frameDelay; }
-
- float sampleRate() const { return m_sampleRate; }
- double nyquist() const { return 0.5 * sampleRate(); }
-
- // Converts back into impulse-response form.
- PassOwnPtr<AudioChannel> createImpulseResponse();
-
-private:
- // Note: this is destructive on the passed in AudioChannel.
- HRTFKernel(AudioChannel*, size_t fftSize, float sampleRate);
-
- HRTFKernel(PassOwnPtr<FFTFrame> fftFrame, float frameDelay, float sampleRate)
- : m_fftFrame(fftFrame)
- , m_frameDelay(frameDelay)
- , m_sampleRate(sampleRate)
- {
- }
-
- OwnPtr<FFTFrame> m_fftFrame;
- float m_frameDelay;
- float m_sampleRate;
-};
-
-typedef Vector<RefPtr<HRTFKernel> > HRTFKernelList;
-
-} // namespace WebCore
-
-#endif // HRTFKernel_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/HRTFPanner.cpp b/chromium/third_party/WebKit/Source/core/platform/audio/HRTFPanner.cpp
deleted file mode 100644
index db7f2d88663..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/HRTFPanner.cpp
+++ /dev/null
@@ -1,314 +0,0 @@
-/*
- * Copyright (C) 2010, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#if ENABLE(WEB_AUDIO)
-
-#include "core/platform/audio/HRTFPanner.h"
-
-#include <algorithm>
-#include "core/platform/audio/AudioBus.h"
-#include "core/platform/audio/FFTConvolver.h"
-#include "core/platform/audio/HRTFDatabase.h"
-#include "wtf/MathExtras.h"
-#include "wtf/RefPtr.h"
-
-using namespace std;
-
-namespace WebCore {
-
-// The value of 2 milliseconds is larger than the largest delay which exists in any HRTFKernel from the default HRTFDatabase (0.0136 seconds).
-// We ASSERT the delay values used in process() with this value.
-const double MaxDelayTimeSeconds = 0.002;
-
-const int UninitializedAzimuth = -1;
-const unsigned RenderingQuantum = 128;
-
-HRTFPanner::HRTFPanner(float sampleRate, HRTFDatabaseLoader* databaseLoader)
- : Panner(PanningModelHRTF)
- , m_databaseLoader(databaseLoader)
- , m_sampleRate(sampleRate)
- , m_crossfadeSelection(CrossfadeSelection1)
- , m_azimuthIndex1(UninitializedAzimuth)
- , m_elevation1(0)
- , m_azimuthIndex2(UninitializedAzimuth)
- , m_elevation2(0)
- , m_crossfadeX(0)
- , m_crossfadeIncr(0)
- , m_convolverL1(fftSizeForSampleRate(sampleRate))
- , m_convolverR1(fftSizeForSampleRate(sampleRate))
- , m_convolverL2(fftSizeForSampleRate(sampleRate))
- , m_convolverR2(fftSizeForSampleRate(sampleRate))
- , m_delayLineL(MaxDelayTimeSeconds, sampleRate)
- , m_delayLineR(MaxDelayTimeSeconds, sampleRate)
- , m_tempL1(RenderingQuantum)
- , m_tempR1(RenderingQuantum)
- , m_tempL2(RenderingQuantum)
- , m_tempR2(RenderingQuantum)
-{
- ASSERT(databaseLoader);
-}
-
-HRTFPanner::~HRTFPanner()
-{
-}
-
-size_t HRTFPanner::fftSizeForSampleRate(float sampleRate)
-{
- // The HRTF impulse responses (loaded as audio resources) are 512 sample-frames @44.1KHz.
- // Currently, we truncate the impulse responses to half this size, but an FFT-size of twice impulse response size is needed (for convolution).
- // So for sample rates around 44.1KHz an FFT size of 512 is good. We double the FFT-size only for sample rates at least double this.
- ASSERT(sampleRate >= 44100 && sampleRate <= 96000.0);
- return (sampleRate < 88200.0) ? 512 : 1024;
-}
-
-void HRTFPanner::reset()
-{
- m_convolverL1.reset();
- m_convolverR1.reset();
- m_convolverL2.reset();
- m_convolverR2.reset();
- m_delayLineL.reset();
- m_delayLineR.reset();
-}
-
-int HRTFPanner::calculateDesiredAzimuthIndexAndBlend(double azimuth, double& azimuthBlend)
-{
- // Convert the azimuth angle from the range -180 -> +180 into the range 0 -> 360.
- // The azimuth index may then be calculated from this positive value.
- if (azimuth < 0)
- azimuth += 360.0;
-
- HRTFDatabase* database = m_databaseLoader->database();
- ASSERT(database);
-
- int numberOfAzimuths = database->numberOfAzimuths();
- const double angleBetweenAzimuths = 360.0 / numberOfAzimuths;
-
- // Calculate the azimuth index and the blend (0 -> 1) for interpolation.
- double desiredAzimuthIndexFloat = azimuth / angleBetweenAzimuths;
- int desiredAzimuthIndex = static_cast<int>(desiredAzimuthIndexFloat);
- azimuthBlend = desiredAzimuthIndexFloat - static_cast<double>(desiredAzimuthIndex);
-
- // We don't immediately start using this azimuth index, but instead approach this index from the last index we rendered at.
- // This minimizes the clicks and graininess for moving sources which occur otherwise.
- desiredAzimuthIndex = max(0, desiredAzimuthIndex);
- desiredAzimuthIndex = min(numberOfAzimuths - 1, desiredAzimuthIndex);
- return desiredAzimuthIndex;
-}
-
-void HRTFPanner::pan(double desiredAzimuth, double elevation, const AudioBus* inputBus, AudioBus* outputBus, size_t framesToProcess)
-{
- unsigned numInputChannels = inputBus ? inputBus->numberOfChannels() : 0;
-
- bool isInputGood = inputBus && numInputChannels >= 1 && numInputChannels <= 2;
- ASSERT(isInputGood);
-
- bool isOutputGood = outputBus && outputBus->numberOfChannels() == 2 && framesToProcess <= outputBus->length();
- ASSERT(isOutputGood);
-
- if (!isInputGood || !isOutputGood) {
- if (outputBus)
- outputBus->zero();
- return;
- }
-
- HRTFDatabase* database = m_databaseLoader->database();
- ASSERT(database);
- if (!database) {
- outputBus->zero();
- return;
- }
-
- // IRCAM HRTF azimuths values from the loaded database is reversed from the panner's notion of azimuth.
- double azimuth = -desiredAzimuth;
-
- bool isAzimuthGood = azimuth >= -180.0 && azimuth <= 180.0;
- ASSERT(isAzimuthGood);
- if (!isAzimuthGood) {
- outputBus->zero();
- return;
- }
-
- // Normally, we'll just be dealing with mono sources.
- // If we have a stereo input, implement stereo panning with left source processed by left HRTF, and right source by right HRTF.
- const AudioChannel* inputChannelL = inputBus->channelByType(AudioBus::ChannelLeft);
- const AudioChannel* inputChannelR = numInputChannels > 1 ? inputBus->channelByType(AudioBus::ChannelRight) : 0;
-
- // Get source and destination pointers.
- const float* sourceL = inputChannelL->data();
- const float* sourceR = numInputChannels > 1 ? inputChannelR->data() : sourceL;
- float* destinationL = outputBus->channelByType(AudioBus::ChannelLeft)->mutableData();
- float* destinationR = outputBus->channelByType(AudioBus::ChannelRight)->mutableData();
-
- double azimuthBlend;
- int desiredAzimuthIndex = calculateDesiredAzimuthIndexAndBlend(azimuth, azimuthBlend);
-
- // Initially snap azimuth and elevation values to first values encountered.
- if (m_azimuthIndex1 == UninitializedAzimuth) {
- m_azimuthIndex1 = desiredAzimuthIndex;
- m_elevation1 = elevation;
- }
- if (m_azimuthIndex2 == UninitializedAzimuth) {
- m_azimuthIndex2 = desiredAzimuthIndex;
- m_elevation2 = elevation;
- }
-
- // Cross-fade / transition over a period of around 45 milliseconds.
- // This is an empirical value tuned to be a reasonable trade-off between
- // smoothness and speed.
- const double fadeFrames = sampleRate() <= 48000 ? 2048 : 4096;
-
- // Check for azimuth and elevation changes, initiating a cross-fade if needed.
- if (!m_crossfadeX && m_crossfadeSelection == CrossfadeSelection1) {
- if (desiredAzimuthIndex != m_azimuthIndex1 || elevation != m_elevation1) {
- // Cross-fade from 1 -> 2
- m_crossfadeIncr = 1 / fadeFrames;
- m_azimuthIndex2 = desiredAzimuthIndex;
- m_elevation2 = elevation;
- }
- }
- if (m_crossfadeX == 1 && m_crossfadeSelection == CrossfadeSelection2) {
- if (desiredAzimuthIndex != m_azimuthIndex2 || elevation != m_elevation2) {
- // Cross-fade from 2 -> 1
- m_crossfadeIncr = -1 / fadeFrames;
- m_azimuthIndex1 = desiredAzimuthIndex;
- m_elevation1 = elevation;
- }
- }
-
- // This algorithm currently requires that we process in power-of-two size chunks at least RenderingQuantum.
- ASSERT(1UL << static_cast<int>(log2(framesToProcess)) == framesToProcess);
- ASSERT(framesToProcess >= RenderingQuantum);
-
- const unsigned framesPerSegment = RenderingQuantum;
- const unsigned numberOfSegments = framesToProcess / framesPerSegment;
-
- for (unsigned segment = 0; segment < numberOfSegments; ++segment) {
- // Get the HRTFKernels and interpolated delays.
- HRTFKernel* kernelL1;
- HRTFKernel* kernelR1;
- HRTFKernel* kernelL2;
- HRTFKernel* kernelR2;
- double frameDelayL1;
- double frameDelayR1;
- double frameDelayL2;
- double frameDelayR2;
- database->getKernelsFromAzimuthElevation(azimuthBlend, m_azimuthIndex1, m_elevation1, kernelL1, kernelR1, frameDelayL1, frameDelayR1);
- database->getKernelsFromAzimuthElevation(azimuthBlend, m_azimuthIndex2, m_elevation2, kernelL2, kernelR2, frameDelayL2, frameDelayR2);
-
- bool areKernelsGood = kernelL1 && kernelR1 && kernelL2 && kernelR2;
- ASSERT(areKernelsGood);
- if (!areKernelsGood) {
- outputBus->zero();
- return;
- }
-
- ASSERT(frameDelayL1 / sampleRate() < MaxDelayTimeSeconds && frameDelayR1 / sampleRate() < MaxDelayTimeSeconds);
- ASSERT(frameDelayL2 / sampleRate() < MaxDelayTimeSeconds && frameDelayR2 / sampleRate() < MaxDelayTimeSeconds);
-
- // Crossfade inter-aural delays based on transitions.
- double frameDelayL = (1 - m_crossfadeX) * frameDelayL1 + m_crossfadeX * frameDelayL2;
- double frameDelayR = (1 - m_crossfadeX) * frameDelayR1 + m_crossfadeX * frameDelayR2;
-
- // Calculate the source and destination pointers for the current segment.
- unsigned offset = segment * framesPerSegment;
- const float* segmentSourceL = sourceL + offset;
- const float* segmentSourceR = sourceR + offset;
- float* segmentDestinationL = destinationL + offset;
- float* segmentDestinationR = destinationR + offset;
-
- // First run through delay lines for inter-aural time difference.
- m_delayLineL.setDelayFrames(frameDelayL);
- m_delayLineR.setDelayFrames(frameDelayR);
- m_delayLineL.process(segmentSourceL, segmentDestinationL, framesPerSegment);
- m_delayLineR.process(segmentSourceR, segmentDestinationR, framesPerSegment);
-
- bool needsCrossfading = m_crossfadeIncr;
-
- // Have the convolvers render directly to the final destination if we're not cross-fading.
- float* convolutionDestinationL1 = needsCrossfading ? m_tempL1.data() : segmentDestinationL;
- float* convolutionDestinationR1 = needsCrossfading ? m_tempR1.data() : segmentDestinationR;
- float* convolutionDestinationL2 = needsCrossfading ? m_tempL2.data() : segmentDestinationL;
- float* convolutionDestinationR2 = needsCrossfading ? m_tempR2.data() : segmentDestinationR;
-
- // Now do the convolutions.
- // Note that we avoid doing convolutions on both sets of convolvers if we're not currently cross-fading.
-
- if (m_crossfadeSelection == CrossfadeSelection1 || needsCrossfading) {
- m_convolverL1.process(kernelL1->fftFrame(), segmentDestinationL, convolutionDestinationL1, framesPerSegment);
- m_convolverR1.process(kernelR1->fftFrame(), segmentDestinationR, convolutionDestinationR1, framesPerSegment);
- }
-
- if (m_crossfadeSelection == CrossfadeSelection2 || needsCrossfading) {
- m_convolverL2.process(kernelL2->fftFrame(), segmentDestinationL, convolutionDestinationL2, framesPerSegment);
- m_convolverR2.process(kernelR2->fftFrame(), segmentDestinationR, convolutionDestinationR2, framesPerSegment);
- }
-
- if (needsCrossfading) {
- // Apply linear cross-fade.
- float x = m_crossfadeX;
- float incr = m_crossfadeIncr;
- for (unsigned i = 0; i < framesPerSegment; ++i) {
- segmentDestinationL[i] = (1 - x) * convolutionDestinationL1[i] + x * convolutionDestinationL2[i];
- segmentDestinationR[i] = (1 - x) * convolutionDestinationR1[i] + x * convolutionDestinationR2[i];
- x += incr;
- }
- // Update cross-fade value from local.
- m_crossfadeX = x;
-
- if (m_crossfadeIncr > 0 && fabs(m_crossfadeX - 1) < m_crossfadeIncr) {
- // We've fully made the crossfade transition from 1 -> 2.
- m_crossfadeSelection = CrossfadeSelection2;
- m_crossfadeX = 1;
- m_crossfadeIncr = 0;
- } else if (m_crossfadeIncr < 0 && fabs(m_crossfadeX) < -m_crossfadeIncr) {
- // We've fully made the crossfade transition from 2 -> 1.
- m_crossfadeSelection = CrossfadeSelection1;
- m_crossfadeX = 0;
- m_crossfadeIncr = 0;
- }
- }
- }
-}
-
-double HRTFPanner::tailTime() const
-{
- // Because HRTFPanner is implemented with a DelayKernel and a FFTConvolver, the tailTime of the HRTFPanner
- // is the sum of the tailTime of the DelayKernel and the tailTime of the FFTConvolver, which is MaxDelayTimeSeconds
- // and fftSize() / 2, respectively.
- return MaxDelayTimeSeconds + (fftSize() / 2) / static_cast<double>(sampleRate());
-}
-
-double HRTFPanner::latencyTime() const
-{
- // The latency of a FFTConvolver is also fftSize() / 2, and is in addition to its tailTime of the
- // same value.
- return (fftSize() / 2) / static_cast<double>(sampleRate());
-}
-
-} // namespace WebCore
-
-#endif // ENABLE(WEB_AUDIO)
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/HRTFPanner.h b/chromium/third_party/WebKit/Source/core/platform/audio/HRTFPanner.h
deleted file mode 100644
index 1e63ddd79c0..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/HRTFPanner.h
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * Copyright (C) 2010, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef HRTFPanner_h
-#define HRTFPanner_h
-
-#include "core/platform/audio/FFTConvolver.h"
-#include "core/platform/audio/HRTFDatabaseLoader.h"
-#include "core/platform/audio/Panner.h"
-#include "modules/webaudio/DelayDSPKernel.h"
-
-namespace WebCore {
-
-class HRTFPanner : public Panner {
-public:
- HRTFPanner(float sampleRate, HRTFDatabaseLoader*);
- virtual ~HRTFPanner();
-
- // Panner
- virtual void pan(double azimuth, double elevation, const AudioBus* inputBus, AudioBus* outputBus, size_t framesToProcess);
- virtual void reset();
-
- size_t fftSize() const { return fftSizeForSampleRate(m_sampleRate); }
- static size_t fftSizeForSampleRate(float sampleRate);
-
- float sampleRate() const { return m_sampleRate; }
-
- virtual double tailTime() const OVERRIDE;
- virtual double latencyTime() const OVERRIDE;
-
-private:
- // Given an azimuth angle in the range -180 -> +180, returns the corresponding azimuth index for the database,
- // and azimuthBlend which is an interpolation value from 0 -> 1.
- int calculateDesiredAzimuthIndexAndBlend(double azimuth, double& azimuthBlend);
-
- RefPtr<HRTFDatabaseLoader> m_databaseLoader;
-
- float m_sampleRate;
-
- // We maintain two sets of convolvers for smooth cross-faded interpolations when
- // then azimuth and elevation are dynamically changing.
- // When the azimuth and elevation are not changing, we simply process with one of the two sets.
- // Initially we use CrossfadeSelection1 corresponding to m_convolverL1 and m_convolverR1.
- // Whenever the azimuth or elevation changes, a crossfade is initiated to transition
- // to the new position. So if we're currently processing with CrossfadeSelection1, then
- // we transition to CrossfadeSelection2 (and vice versa).
- // If we're in the middle of a transition, then we wait until it is complete before
- // initiating a new transition.
-
- // Selects either the convolver set (m_convolverL1, m_convolverR1) or (m_convolverL2, m_convolverR2).
- enum CrossfadeSelection {
- CrossfadeSelection1,
- CrossfadeSelection2
- };
-
- CrossfadeSelection m_crossfadeSelection;
-
- // azimuth/elevation for CrossfadeSelection1.
- int m_azimuthIndex1;
- double m_elevation1;
-
- // azimuth/elevation for CrossfadeSelection2.
- int m_azimuthIndex2;
- double m_elevation2;
-
- // A crossfade value 0 <= m_crossfadeX <= 1.
- float m_crossfadeX;
-
- // Per-sample-frame crossfade value increment.
- float m_crossfadeIncr;
-
- FFTConvolver m_convolverL1;
- FFTConvolver m_convolverR1;
- FFTConvolver m_convolverL2;
- FFTConvolver m_convolverR2;
-
- DelayDSPKernel m_delayLineL;
- DelayDSPKernel m_delayLineR;
-
- AudioFloatArray m_tempL1;
- AudioFloatArray m_tempR1;
- AudioFloatArray m_tempL2;
- AudioFloatArray m_tempR2;
-};
-
-} // namespace WebCore
-
-#endif // HRTFPanner_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/MultiChannelResampler.cpp b/chromium/third_party/WebKit/Source/core/platform/audio/MultiChannelResampler.cpp
deleted file mode 100644
index 4bd742fde1e..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/MultiChannelResampler.cpp
+++ /dev/null
@@ -1,123 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#if ENABLE(WEB_AUDIO)
-
-#include "core/platform/audio/MultiChannelResampler.h"
-
-#include "core/platform/audio/AudioBus.h"
-
-namespace WebCore {
-
-namespace {
-
-// ChannelProvider provides a single channel of audio data (one channel at a time) for each channel
-// of data provided to us in a multi-channel provider.
-
-class ChannelProvider : public AudioSourceProvider {
-public:
- ChannelProvider(AudioSourceProvider* multiChannelProvider, unsigned numberOfChannels)
- : m_multiChannelProvider(multiChannelProvider)
- , m_numberOfChannels(numberOfChannels)
- , m_currentChannel(0)
- , m_framesToProcess(0)
- {
- }
-
- // provideInput() will be called once for each channel, starting with the first channel.
- // Each time it's called, it will provide the next channel of data.
- virtual void provideInput(AudioBus* bus, size_t framesToProcess)
- {
- bool isBusGood = bus && bus->numberOfChannels() == 1;
- ASSERT(isBusGood);
- if (!isBusGood)
- return;
-
- // Get the data from the multi-channel provider when the first channel asks for it.
- // For subsequent channels, we can just dish out the channel data from that (stored in m_multiChannelBus).
- if (!m_currentChannel) {
- m_framesToProcess = framesToProcess;
- m_multiChannelBus = AudioBus::create(m_numberOfChannels, framesToProcess);
- m_multiChannelProvider->provideInput(m_multiChannelBus.get(), framesToProcess);
- }
-
- // All channels must ask for the same amount. This should always be the case, but let's just make sure.
- bool isGood = m_multiChannelBus.get() && framesToProcess == m_framesToProcess;
- ASSERT(isGood);
- if (!isGood)
- return;
-
- // Copy the channel data from what we received from m_multiChannelProvider.
- ASSERT(m_currentChannel <= m_numberOfChannels);
- if (m_currentChannel < m_numberOfChannels) {
- memcpy(bus->channel(0)->mutableData(), m_multiChannelBus->channel(m_currentChannel)->data(), sizeof(float) * framesToProcess);
- ++m_currentChannel;
- }
- }
-
-private:
- AudioSourceProvider* m_multiChannelProvider;
- RefPtr<AudioBus> m_multiChannelBus;
- unsigned m_numberOfChannels;
- unsigned m_currentChannel;
- size_t m_framesToProcess; // Used to verify that all channels ask for the same amount.
-};
-
-} // namespace
-
-MultiChannelResampler::MultiChannelResampler(double scaleFactor, unsigned numberOfChannels)
- : m_numberOfChannels(numberOfChannels)
-{
- // Create each channel's resampler.
- for (unsigned channelIndex = 0; channelIndex < numberOfChannels; ++channelIndex)
- m_kernels.append(adoptPtr(new SincResampler(scaleFactor)));
-}
-
-void MultiChannelResampler::process(AudioSourceProvider* provider, AudioBus* destination, size_t framesToProcess)
-{
- // The provider can provide us with multi-channel audio data. But each of our single-channel resamplers (kernels)
- // below requires a provider which provides a single unique channel of data.
- // channelProvider wraps the original multi-channel provider and dishes out one channel at a time.
- ChannelProvider channelProvider(provider, m_numberOfChannels);
-
- for (unsigned channelIndex = 0; channelIndex < m_numberOfChannels; ++channelIndex) {
- // Depending on the sample-rate scale factor, and the internal buffering used in a SincResampler
- // kernel, this call to process() will only sometimes call provideInput() on the channelProvider.
- // However, if it calls provideInput() for the first channel, then it will call it for the remaining
- // channels, since they all buffer in the same way and are processing the same number of frames.
- m_kernels[channelIndex]->process(&channelProvider,
- destination->channel(channelIndex)->mutableData(),
- framesToProcess);
- }
-}
-
-} // namespace WebCore
-
-#endif // ENABLE(WEB_AUDIO)
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/MultiChannelResampler.h b/chromium/third_party/WebKit/Source/core/platform/audio/MultiChannelResampler.h
deleted file mode 100644
index 16a57fd532c..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/MultiChannelResampler.h
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef MultiChannelResampler_h
-#define MultiChannelResampler_h
-
-#include "core/platform/audio/SincResampler.h"
-#include "wtf/OwnPtr.h"
-
-namespace WebCore {
-
-class AudioBus;
-
-class MultiChannelResampler {
-public:
- MultiChannelResampler(double scaleFactor, unsigned numberOfChannels);
-
- // Process given AudioSourceProvider for streaming applications.
- void process(AudioSourceProvider*, AudioBus* destination, size_t framesToProcess);
-
-private:
- // FIXME: the mac port can have a more highly optimized implementation based on CoreAudio
- // instead of SincResampler. For now the default implementation will be used on all ports.
- // https://bugs.webkit.org/show_bug.cgi?id=75118
-
- // Each channel will be resampled using a high-quality SincResampler.
- Vector<OwnPtr<SincResampler> > m_kernels;
-
- unsigned m_numberOfChannels;
-};
-
-} // namespace WebCore
-
-#endif // MultiChannelResampler_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/Panner.cpp b/chromium/third_party/WebKit/Source/core/platform/audio/Panner.cpp
deleted file mode 100644
index 30fca6e73f8..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/Panner.cpp
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#if ENABLE(WEB_AUDIO)
-
-#include "core/platform/audio/Panner.h"
-
-#include "core/platform/audio/EqualPowerPanner.h"
-#include "core/platform/audio/HRTFPanner.h"
-#include "wtf/OwnPtr.h"
-
-namespace WebCore {
-
-PassOwnPtr<Panner> Panner::create(PanningModel model, float sampleRate, HRTFDatabaseLoader* databaseLoader)
-{
- OwnPtr<Panner> panner;
-
- switch (model) {
- case PanningModelEqualPower:
- panner = adoptPtr(new EqualPowerPanner(sampleRate));
- break;
-
- case PanningModelHRTF:
- panner = adoptPtr(new HRTFPanner(sampleRate, databaseLoader));
- break;
-
- // FIXME: sound field panning is not yet implemented...
- case PanningModelSoundField:
- default:
- ASSERT_NOT_REACHED();
- return nullptr;
- }
-
- return panner.release();
-}
-
-} // namespace WebCore
-
-#endif // ENABLE(WEB_AUDIO)
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/Panner.h b/chromium/third_party/WebKit/Source/core/platform/audio/Panner.h
deleted file mode 100644
index d6eac042049..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/Panner.h
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Copyright (C) 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef Panner_h
-#define Panner_h
-
-#include "wtf/PassOwnPtr.h"
-
-namespace WebCore {
-
-class AudioBus;
-class HRTFDatabaseLoader;
-
-// Abstract base class for panning a mono or stereo source.
-
-class Panner {
-public:
- enum {
- PanningModelEqualPower = 0,
- PanningModelHRTF = 1,
- PanningModelSoundField = 2
- };
-
- typedef unsigned PanningModel;
-
- static PassOwnPtr<Panner> create(PanningModel, float sampleRate, HRTFDatabaseLoader*);
-
- virtual ~Panner() { };
-
- PanningModel panningModel() const { return m_panningModel; }
-
- virtual void pan(double azimuth, double elevation, const AudioBus* inputBus, AudioBus* outputBus, size_t framesToProcess) = 0;
-
- virtual void reset() = 0;
-
- virtual double tailTime() const = 0;
- virtual double latencyTime() const = 0;
-
-protected:
- Panner(PanningModel model) : m_panningModel(model) { }
-
- PanningModel m_panningModel;
-};
-
-} // namespace WebCore
-
-#endif // Panner_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/Reverb.cpp b/chromium/third_party/WebKit/Source/core/platform/audio/Reverb.cpp
deleted file mode 100644
index 9ca5c907f10..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/Reverb.cpp
+++ /dev/null
@@ -1,242 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#if ENABLE(WEB_AUDIO)
-
-#include "core/platform/audio/Reverb.h"
-
-#include <math.h>
-#include "core/platform/audio/AudioBus.h"
-#include "core/platform/audio/ReverbConvolver.h"
-#include "core/platform/audio/VectorMath.h"
-#include "wtf/MathExtras.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/PassOwnPtr.h"
-
-#if OS(MACOSX)
-using namespace std;
-#endif
-
-namespace WebCore {
-
-using namespace VectorMath;
-
-// Empirical gain calibration tested across many impulse responses to ensure perceived volume is same as dry (unprocessed) signal
-const float GainCalibration = -58;
-const float GainCalibrationSampleRate = 44100;
-
-// A minimum power value to when normalizing a silent (or very quiet) impulse response
-const float MinPower = 0.000125f;
-
-static float calculateNormalizationScale(AudioBus* response)
-{
- // Normalize by RMS power
- size_t numberOfChannels = response->numberOfChannels();
- size_t length = response->length();
-
- float power = 0;
-
- for (size_t i = 0; i < numberOfChannels; ++i) {
- float channelPower = 0;
- vsvesq(response->channel(i)->data(), 1, &channelPower, length);
- power += channelPower;
- }
-
- power = sqrt(power / (numberOfChannels * length));
-
- // Protect against accidental overload
- if (std::isinf(power) || std::isnan(power) || power < MinPower)
- power = MinPower;
-
- float scale = 1 / power;
-
- scale *= powf(10, GainCalibration * 0.05f); // calibrate to make perceived volume same as unprocessed
-
- // Scale depends on sample-rate.
- if (response->sampleRate())
- scale *= GainCalibrationSampleRate / response->sampleRate();
-
- // True-stereo compensation
- if (response->numberOfChannels() == 4)
- scale *= 0.5f;
-
- return scale;
-}
-
-Reverb::Reverb(AudioBus* impulseResponse, size_t renderSliceSize, size_t maxFFTSize, size_t numberOfChannels, bool useBackgroundThreads, bool normalize)
-{
- float scale = 1;
-
- if (normalize) {
- scale = calculateNormalizationScale(impulseResponse);
-
- if (scale)
- impulseResponse->scale(scale);
- }
-
- initialize(impulseResponse, renderSliceSize, maxFFTSize, numberOfChannels, useBackgroundThreads);
-
- // Undo scaling since this shouldn't be a destructive operation on impulseResponse.
- // FIXME: What about roundoff? Perhaps consider making a temporary scaled copy
- // instead of scaling and unscaling in place.
- if (normalize && scale)
- impulseResponse->scale(1 / scale);
-}
-
-void Reverb::initialize(AudioBus* impulseResponseBuffer, size_t renderSliceSize, size_t maxFFTSize, size_t numberOfChannels, bool useBackgroundThreads)
-{
- m_impulseResponseLength = impulseResponseBuffer->length();
-
- // The reverb can handle a mono impulse response and still do stereo processing
- size_t numResponseChannels = impulseResponseBuffer->numberOfChannels();
- m_convolvers.reserveCapacity(numberOfChannels);
-
- int convolverRenderPhase = 0;
- for (size_t i = 0; i < numResponseChannels; ++i) {
- AudioChannel* channel = impulseResponseBuffer->channel(i);
-
- OwnPtr<ReverbConvolver> convolver = adoptPtr(new ReverbConvolver(channel, renderSliceSize, maxFFTSize, convolverRenderPhase, useBackgroundThreads));
- m_convolvers.append(convolver.release());
-
- convolverRenderPhase += renderSliceSize;
- }
-
- // For "True" stereo processing we allocate a temporary buffer to avoid repeatedly allocating it in the process() method.
- // It can be bad to allocate memory in a real-time thread.
- if (numResponseChannels == 4)
- m_tempBuffer = AudioBus::create(2, MaxFrameSize);
-}
-
-void Reverb::process(const AudioBus* sourceBus, AudioBus* destinationBus, size_t framesToProcess)
-{
- // Do a fairly comprehensive sanity check.
- // If these conditions are satisfied, all of the source and destination pointers will be valid for the various matrixing cases.
- bool isSafeToProcess = sourceBus && destinationBus && sourceBus->numberOfChannels() > 0 && destinationBus->numberOfChannels() > 0
- && framesToProcess <= MaxFrameSize && framesToProcess <= sourceBus->length() && framesToProcess <= destinationBus->length();
-
- ASSERT(isSafeToProcess);
- if (!isSafeToProcess)
- return;
-
- // For now only handle mono or stereo output
- if (destinationBus->numberOfChannels() > 2) {
- destinationBus->zero();
- return;
- }
-
- AudioChannel* destinationChannelL = destinationBus->channel(0);
- const AudioChannel* sourceChannelL = sourceBus->channel(0);
-
- // Handle input -> output matrixing...
- size_t numInputChannels = sourceBus->numberOfChannels();
- size_t numOutputChannels = destinationBus->numberOfChannels();
- size_t numReverbChannels = m_convolvers.size();
-
- if (numInputChannels == 2 && numReverbChannels == 2 && numOutputChannels == 2) {
- // 2 -> 2 -> 2
- const AudioChannel* sourceChannelR = sourceBus->channel(1);
- AudioChannel* destinationChannelR = destinationBus->channel(1);
- m_convolvers[0]->process(sourceChannelL, destinationChannelL, framesToProcess);
- m_convolvers[1]->process(sourceChannelR, destinationChannelR, framesToProcess);
- } else if (numInputChannels == 1 && numOutputChannels == 2 && numReverbChannels == 2) {
- // 1 -> 2 -> 2
- for (int i = 0; i < 2; ++i) {
- AudioChannel* destinationChannel = destinationBus->channel(i);
- m_convolvers[i]->process(sourceChannelL, destinationChannel, framesToProcess);
- }
- } else if (numInputChannels == 1 && numReverbChannels == 1 && numOutputChannels == 2) {
- // 1 -> 1 -> 2
- m_convolvers[0]->process(sourceChannelL, destinationChannelL, framesToProcess);
-
- // simply copy L -> R
- AudioChannel* destinationChannelR = destinationBus->channel(1);
- bool isCopySafe = destinationChannelL->data() && destinationChannelR->data() && destinationChannelL->length() >= framesToProcess && destinationChannelR->length() >= framesToProcess;
- ASSERT(isCopySafe);
- if (!isCopySafe)
- return;
- memcpy(destinationChannelR->mutableData(), destinationChannelL->data(), sizeof(float) * framesToProcess);
- } else if (numInputChannels == 1 && numReverbChannels == 1 && numOutputChannels == 1) {
- // 1 -> 1 -> 1
- m_convolvers[0]->process(sourceChannelL, destinationChannelL, framesToProcess);
- } else if (numInputChannels == 2 && numReverbChannels == 4 && numOutputChannels == 2) {
- // 2 -> 4 -> 2 ("True" stereo)
- const AudioChannel* sourceChannelR = sourceBus->channel(1);
- AudioChannel* destinationChannelR = destinationBus->channel(1);
-
- AudioChannel* tempChannelL = m_tempBuffer->channel(0);
- AudioChannel* tempChannelR = m_tempBuffer->channel(1);
-
- // Process left virtual source
- m_convolvers[0]->process(sourceChannelL, destinationChannelL, framesToProcess);
- m_convolvers[1]->process(sourceChannelL, destinationChannelR, framesToProcess);
-
- // Process right virtual source
- m_convolvers[2]->process(sourceChannelR, tempChannelL, framesToProcess);
- m_convolvers[3]->process(sourceChannelR, tempChannelR, framesToProcess);
-
- destinationBus->sumFrom(*m_tempBuffer);
- } else if (numInputChannels == 1 && numReverbChannels == 4 && numOutputChannels == 2) {
- // 1 -> 4 -> 2 (Processing mono with "True" stereo impulse response)
- // This is an inefficient use of a four-channel impulse response, but we should handle the case.
- AudioChannel* destinationChannelR = destinationBus->channel(1);
-
- AudioChannel* tempChannelL = m_tempBuffer->channel(0);
- AudioChannel* tempChannelR = m_tempBuffer->channel(1);
-
- // Process left virtual source
- m_convolvers[0]->process(sourceChannelL, destinationChannelL, framesToProcess);
- m_convolvers[1]->process(sourceChannelL, destinationChannelR, framesToProcess);
-
- // Process right virtual source
- m_convolvers[2]->process(sourceChannelL, tempChannelL, framesToProcess);
- m_convolvers[3]->process(sourceChannelL, tempChannelR, framesToProcess);
-
- destinationBus->sumFrom(*m_tempBuffer);
- } else {
- // Handle gracefully any unexpected / unsupported matrixing
- // FIXME: add code for 5.1 support...
- destinationBus->zero();
- }
-}
-
-void Reverb::reset()
-{
- for (size_t i = 0; i < m_convolvers.size(); ++i)
- m_convolvers[i]->reset();
-}
-
-size_t Reverb::latencyFrames() const
-{
- return !m_convolvers.isEmpty() ? m_convolvers.first()->latencyFrames() : 0;
-}
-
-} // namespace WebCore
-
-#endif // ENABLE(WEB_AUDIO)
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/Reverb.h b/chromium/third_party/WebKit/Source/core/platform/audio/Reverb.h
deleted file mode 100644
index 1e7959630b6..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/Reverb.h
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef Reverb_h
-#define Reverb_h
-
-#include "core/platform/audio/ReverbConvolver.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-class AudioBus;
-
-// Multi-channel convolution reverb with channel matrixing - one or more ReverbConvolver objects are used internally.
-
-class Reverb {
-public:
- enum { MaxFrameSize = 256 };
-
- // renderSliceSize is a rendering hint, so the FFTs can be optimized to not all occur at the same time (very bad when rendering on a real-time thread).
- Reverb(AudioBus* impulseResponseBuffer, size_t renderSliceSize, size_t maxFFTSize, size_t numberOfChannels, bool useBackgroundThreads, bool normalize);
-
- void process(const AudioBus* sourceBus, AudioBus* destinationBus, size_t framesToProcess);
- void reset();
-
- size_t impulseResponseLength() const { return m_impulseResponseLength; }
- size_t latencyFrames() const;
-
-private:
- void initialize(AudioBus* impulseResponseBuffer, size_t renderSliceSize, size_t maxFFTSize, size_t numberOfChannels, bool useBackgroundThreads);
-
- size_t m_impulseResponseLength;
-
- Vector<OwnPtr<ReverbConvolver> > m_convolvers;
-
- // For "True" stereo processing
- RefPtr<AudioBus> m_tempBuffer;
-};
-
-} // namespace WebCore
-
-#endif // Reverb_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/ReverbAccumulationBuffer.cpp b/chromium/third_party/WebKit/Source/core/platform/audio/ReverbAccumulationBuffer.cpp
deleted file mode 100644
index e7506fa0152..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/ReverbAccumulationBuffer.cpp
+++ /dev/null
@@ -1,119 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#if ENABLE(WEB_AUDIO)
-
-#include "core/platform/audio/ReverbAccumulationBuffer.h"
-
-#include "core/platform/audio/VectorMath.h"
-
-namespace WebCore {
-
-using namespace VectorMath;
-
-ReverbAccumulationBuffer::ReverbAccumulationBuffer(size_t length)
- : m_buffer(length)
- , m_readIndex(0)
- , m_readTimeFrame(0)
-{
-}
-
-void ReverbAccumulationBuffer::readAndClear(float* destination, size_t numberOfFrames)
-{
- size_t bufferLength = m_buffer.size();
- bool isCopySafe = m_readIndex <= bufferLength && numberOfFrames <= bufferLength;
-
- ASSERT(isCopySafe);
- if (!isCopySafe)
- return;
-
- size_t framesAvailable = bufferLength - m_readIndex;
- size_t numberOfFrames1 = std::min(numberOfFrames, framesAvailable);
- size_t numberOfFrames2 = numberOfFrames - numberOfFrames1;
-
- float* source = m_buffer.data();
- memcpy(destination, source + m_readIndex, sizeof(float) * numberOfFrames1);
- memset(source + m_readIndex, 0, sizeof(float) * numberOfFrames1);
-
- // Handle wrap-around if necessary
- if (numberOfFrames2 > 0) {
- memcpy(destination + numberOfFrames1, source, sizeof(float) * numberOfFrames2);
- memset(source, 0, sizeof(float) * numberOfFrames2);
- }
-
- m_readIndex = (m_readIndex + numberOfFrames) % bufferLength;
- m_readTimeFrame += numberOfFrames;
-}
-
-void ReverbAccumulationBuffer::updateReadIndex(int* readIndex, size_t numberOfFrames) const
-{
- // Update caller's readIndex
- *readIndex = (*readIndex + numberOfFrames) % m_buffer.size();
-}
-
-int ReverbAccumulationBuffer::accumulate(float* source, size_t numberOfFrames, int* readIndex, size_t delayFrames)
-{
- size_t bufferLength = m_buffer.size();
-
- size_t writeIndex = (*readIndex + delayFrames) % bufferLength;
-
- // Update caller's readIndex
- *readIndex = (*readIndex + numberOfFrames) % bufferLength;
-
- size_t framesAvailable = bufferLength - writeIndex;
- size_t numberOfFrames1 = std::min(numberOfFrames, framesAvailable);
- size_t numberOfFrames2 = numberOfFrames - numberOfFrames1;
-
- float* destination = m_buffer.data();
-
- bool isSafe = writeIndex <= bufferLength && numberOfFrames1 + writeIndex <= bufferLength && numberOfFrames2 <= bufferLength;
- ASSERT(isSafe);
- if (!isSafe)
- return 0;
-
- vadd(source, 1, destination + writeIndex, 1, destination + writeIndex, 1, numberOfFrames1);
-
- // Handle wrap-around if necessary
- if (numberOfFrames2 > 0)
- vadd(source + numberOfFrames1, 1, destination, 1, destination, 1, numberOfFrames2);
-
- return writeIndex;
-}
-
-void ReverbAccumulationBuffer::reset()
-{
- m_buffer.zero();
- m_readIndex = 0;
- m_readTimeFrame = 0;
-}
-
-} // namespace WebCore
-
-#endif // ENABLE(WEB_AUDIO)
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/ReverbAccumulationBuffer.h b/chromium/third_party/WebKit/Source/core/platform/audio/ReverbAccumulationBuffer.h
deleted file mode 100644
index fe3f3a58bf9..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/ReverbAccumulationBuffer.h
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ReverbAccumulationBuffer_h
-#define ReverbAccumulationBuffer_h
-
-#include "core/platform/audio/AudioArray.h"
-
-namespace WebCore {
-
-// ReverbAccumulationBuffer is a circular delay buffer with one client reading from it and multiple clients
-// writing/accumulating to it at different delay offsets from the read position. The read operation will zero the memory
-// just read from the buffer, so it will be ready for accumulation the next time around.
-class ReverbAccumulationBuffer {
-public:
- ReverbAccumulationBuffer(size_t length);
-
- // This will read from, then clear-out numberOfFrames
- void readAndClear(float* destination, size_t numberOfFrames);
-
- // Each ReverbConvolverStage will accumulate its output at the appropriate delay from the read position.
- // We need to pass in and update readIndex here, since each ReverbConvolverStage may be running in
- // a different thread than the realtime thread calling ReadAndClear() and maintaining m_readIndex
- // Returns the writeIndex where the accumulation took place
- int accumulate(float* source, size_t numberOfFrames, int* readIndex, size_t delayFrames);
-
- size_t readIndex() const { return m_readIndex; }
- void updateReadIndex(int* readIndex, size_t numberOfFrames) const;
-
- size_t readTimeFrame() const { return m_readTimeFrame; }
-
- void reset();
-
-private:
- AudioFloatArray m_buffer;
- size_t m_readIndex;
- size_t m_readTimeFrame; // for debugging (frame on continuous timeline)
-};
-
-} // namespace WebCore
-
-#endif // ReverbAccumulationBuffer_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/ReverbConvolver.cpp b/chromium/third_party/WebKit/Source/core/platform/audio/ReverbConvolver.cpp
deleted file mode 100644
index 17ace84d828..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/ReverbConvolver.cpp
+++ /dev/null
@@ -1,238 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#if ENABLE(WEB_AUDIO)
-
-#include "core/platform/audio/ReverbConvolver.h"
-
-#include "core/platform/audio/AudioBus.h"
-#include "core/platform/audio/VectorMath.h"
-
-namespace WebCore {
-
-using namespace VectorMath;
-
-const int InputBufferSize = 8 * 16384;
-
-// We only process the leading portion of the impulse response in the real-time thread. We don't exceed this length.
-// It turns out then, that the background thread has about 278msec of scheduling slop.
-// Empirically, this has been found to be a good compromise between giving enough time for scheduling slop,
-// while still minimizing the amount of processing done in the primary (high-priority) thread.
-// This was found to be a good value on Mac OS X, and may work well on other platforms as well, assuming
-// the very rough scheduling latencies are similar on these time-scales. Of course, this code may need to be
-// tuned for individual platforms if this assumption is found to be incorrect.
-const size_t RealtimeFrameLimit = 8192 + 4096; // ~278msec @ 44.1KHz
-
-const size_t MinFFTSize = 128;
-const size_t MaxRealtimeFFTSize = 2048;
-
-static void backgroundThreadEntry(void* threadData)
-{
- ReverbConvolver* reverbConvolver = static_cast<ReverbConvolver*>(threadData);
- reverbConvolver->backgroundThreadEntry();
-}
-
-ReverbConvolver::ReverbConvolver(AudioChannel* impulseResponse, size_t renderSliceSize, size_t maxFFTSize, size_t convolverRenderPhase, bool useBackgroundThreads)
- : m_impulseResponseLength(impulseResponse->length())
- , m_accumulationBuffer(impulseResponse->length() + renderSliceSize)
- , m_inputBuffer(InputBufferSize)
- , m_minFFTSize(MinFFTSize) // First stage will have this size - successive stages will double in size each time
- , m_maxFFTSize(maxFFTSize) // until we hit m_maxFFTSize
- , m_useBackgroundThreads(useBackgroundThreads)
- , m_backgroundThread(0)
- , m_wantsToExit(false)
- , m_moreInputBuffered(false)
-{
- // If we are using background threads then don't exceed this FFT size for the
- // stages which run in the real-time thread. This avoids having only one or two
- // large stages (size 16384 or so) at the end which take a lot of time every several
- // processing slices. This way we amortize the cost over more processing slices.
- m_maxRealtimeFFTSize = MaxRealtimeFFTSize;
-
- // For the moment, a good way to know if we have real-time constraint is to check if we're using background threads.
- // Otherwise, assume we're being run from a command-line tool.
- bool hasRealtimeConstraint = useBackgroundThreads;
-
- const float* response = impulseResponse->data();
- size_t totalResponseLength = impulseResponse->length();
-
- // The total latency is zero because the direct-convolution is used in the leading portion.
- size_t reverbTotalLatency = 0;
-
- size_t stageOffset = 0;
- int i = 0;
- size_t fftSize = m_minFFTSize;
- while (stageOffset < totalResponseLength) {
- size_t stageSize = fftSize / 2;
-
- // For the last stage, it's possible that stageOffset is such that we're straddling the end
- // of the impulse response buffer (if we use stageSize), so reduce the last stage's length...
- if (stageSize + stageOffset > totalResponseLength)
- stageSize = totalResponseLength - stageOffset;
-
- // This "staggers" the time when each FFT happens so they don't all happen at the same time
- int renderPhase = convolverRenderPhase + i * renderSliceSize;
-
- bool useDirectConvolver = !stageOffset;
-
- OwnPtr<ReverbConvolverStage> stage = adoptPtr(new ReverbConvolverStage(response, totalResponseLength, reverbTotalLatency, stageOffset, stageSize, fftSize, renderPhase, renderSliceSize, &m_accumulationBuffer, useDirectConvolver));
-
- bool isBackgroundStage = false;
-
- if (this->useBackgroundThreads() && stageOffset > RealtimeFrameLimit) {
- m_backgroundStages.append(stage.release());
- isBackgroundStage = true;
- } else
- m_stages.append(stage.release());
-
- stageOffset += stageSize;
- ++i;
-
- if (!useDirectConvolver) {
- // Figure out next FFT size
- fftSize *= 2;
- }
-
- if (hasRealtimeConstraint && !isBackgroundStage && fftSize > m_maxRealtimeFFTSize)
- fftSize = m_maxRealtimeFFTSize;
- if (fftSize > m_maxFFTSize)
- fftSize = m_maxFFTSize;
- }
-
- // Start up background thread
- // FIXME: would be better to up the thread priority here. It doesn't need to be real-time, but higher than the default...
- if (this->useBackgroundThreads() && m_backgroundStages.size() > 0)
- m_backgroundThread = createThread(WebCore::backgroundThreadEntry, this, "convolution background thread");
-}
-
-ReverbConvolver::~ReverbConvolver()
-{
- // Wait for background thread to stop
- if (useBackgroundThreads() && m_backgroundThread) {
- m_wantsToExit = true;
-
- // Wake up thread so it can return
- {
- MutexLocker locker(m_backgroundThreadLock);
- m_moreInputBuffered = true;
- m_backgroundThreadCondition.signal();
- }
-
- waitForThreadCompletion(m_backgroundThread);
- }
-}
-
-void ReverbConvolver::backgroundThreadEntry()
-{
- while (!m_wantsToExit) {
- // Wait for realtime thread to give us more input
- m_moreInputBuffered = false;
- {
- MutexLocker locker(m_backgroundThreadLock);
- while (!m_moreInputBuffered && !m_wantsToExit)
- m_backgroundThreadCondition.wait(m_backgroundThreadLock);
- }
-
- // Process all of the stages until their read indices reach the input buffer's write index
- int writeIndex = m_inputBuffer.writeIndex();
-
- // Even though it doesn't seem like every stage needs to maintain its own version of readIndex
- // we do this in case we want to run in more than one background thread.
- int readIndex;
-
- while ((readIndex = m_backgroundStages[0]->inputReadIndex()) != writeIndex) { // FIXME: do better to detect buffer overrun...
- // The ReverbConvolverStages need to process in amounts which evenly divide half the FFT size
- const int SliceSize = MinFFTSize / 2;
-
- // Accumulate contributions from each stage
- for (size_t i = 0; i < m_backgroundStages.size(); ++i)
- m_backgroundStages[i]->processInBackground(this, SliceSize);
- }
- }
-}
-
-void ReverbConvolver::process(const AudioChannel* sourceChannel, AudioChannel* destinationChannel, size_t framesToProcess)
-{
- bool isSafe = sourceChannel && destinationChannel && sourceChannel->length() >= framesToProcess && destinationChannel->length() >= framesToProcess;
- ASSERT(isSafe);
- if (!isSafe)
- return;
-
- const float* source = sourceChannel->data();
- float* destination = destinationChannel->mutableData();
- bool isDataSafe = source && destination;
- ASSERT(isDataSafe);
- if (!isDataSafe)
- return;
-
- // Feed input buffer (read by all threads)
- m_inputBuffer.write(source, framesToProcess);
-
- // Accumulate contributions from each stage
- for (size_t i = 0; i < m_stages.size(); ++i)
- m_stages[i]->process(source, framesToProcess);
-
- // Finally read from accumulation buffer
- m_accumulationBuffer.readAndClear(destination, framesToProcess);
-
- // Now that we've buffered more input, wake up our background thread.
-
- // Not using a MutexLocker looks strange, but we use a tryLock() instead because this is run on the real-time
- // thread where it is a disaster for the lock to be contended (causes audio glitching). It's OK if we fail to
- // signal from time to time, since we'll get to it the next time we're called. We're called repeatedly
- // and frequently (around every 3ms). The background thread is processing well into the future and has a considerable amount of
- // leeway here...
- if (m_backgroundThreadLock.tryLock()) {
- m_moreInputBuffered = true;
- m_backgroundThreadCondition.signal();
- m_backgroundThreadLock.unlock();
- }
-}
-
-void ReverbConvolver::reset()
-{
- for (size_t i = 0; i < m_stages.size(); ++i)
- m_stages[i]->reset();
-
- for (size_t i = 0; i < m_backgroundStages.size(); ++i)
- m_backgroundStages[i]->reset();
-
- m_accumulationBuffer.reset();
- m_inputBuffer.reset();
-}
-
-size_t ReverbConvolver::latencyFrames() const
-{
- return 0;
-}
-
-} // namespace WebCore
-
-#endif // ENABLE(WEB_AUDIO)
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/ReverbConvolver.h b/chromium/third_party/WebKit/Source/core/platform/audio/ReverbConvolver.h
deleted file mode 100644
index 9c2616b3f89..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/ReverbConvolver.h
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ReverbConvolver_h
-#define ReverbConvolver_h
-
-#include "core/platform/audio/AudioArray.h"
-#include "core/platform/audio/DirectConvolver.h"
-#include "core/platform/audio/FFTConvolver.h"
-#include "core/platform/audio/ReverbAccumulationBuffer.h"
-#include "core/platform/audio/ReverbConvolverStage.h"
-#include "core/platform/audio/ReverbInputBuffer.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/Threading.h"
-#include "wtf/ThreadingPrimitives.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-class AudioChannel;
-
-class ReverbConvolver {
-public:
- // maxFFTSize can be adjusted (from say 2048 to 32768) depending on how much precision is necessary.
- // For certain tweaky de-convolving applications the phase errors add up quickly and lead to non-sensical results with
- // larger FFT sizes and single-precision floats. In these cases 2048 is a good size.
- // If not doing multi-threaded convolution, then should not go > 8192.
- ReverbConvolver(AudioChannel* impulseResponse, size_t renderSliceSize, size_t maxFFTSize, size_t convolverRenderPhase, bool useBackgroundThreads);
- ~ReverbConvolver();
-
- void process(const AudioChannel* sourceChannel, AudioChannel* destinationChannel, size_t framesToProcess);
- void reset();
-
- size_t impulseResponseLength() const { return m_impulseResponseLength; }
-
- ReverbInputBuffer* inputBuffer() { return &m_inputBuffer; }
-
- bool useBackgroundThreads() const { return m_useBackgroundThreads; }
- void backgroundThreadEntry();
-
- size_t latencyFrames() const;
-private:
- Vector<OwnPtr<ReverbConvolverStage> > m_stages;
- Vector<OwnPtr<ReverbConvolverStage> > m_backgroundStages;
- size_t m_impulseResponseLength;
-
- ReverbAccumulationBuffer m_accumulationBuffer;
-
- // One or more background threads read from this input buffer which is fed from the realtime thread.
- ReverbInputBuffer m_inputBuffer;
-
- // First stage will be of size m_minFFTSize. Each next stage will be twice as big until we hit m_maxFFTSize.
- size_t m_minFFTSize;
- size_t m_maxFFTSize;
-
- // But don't exceed this size in the real-time thread (if we're doing background processing).
- size_t m_maxRealtimeFFTSize;
-
- // Background thread and synchronization
- bool m_useBackgroundThreads;
- ThreadIdentifier m_backgroundThread;
- bool m_wantsToExit;
- bool m_moreInputBuffered;
- mutable Mutex m_backgroundThreadLock;
- mutable ThreadCondition m_backgroundThreadCondition;
-};
-
-} // namespace WebCore
-
-#endif // ReverbConvolver_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/ReverbConvolverStage.cpp b/chromium/third_party/WebKit/Source/core/platform/audio/ReverbConvolverStage.cpp
deleted file mode 100644
index 51fe8983152..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/ReverbConvolverStage.cpp
+++ /dev/null
@@ -1,185 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#if ENABLE(WEB_AUDIO)
-
-#include "core/platform/audio/ReverbConvolverStage.h"
-
-#include "core/platform/audio/ReverbAccumulationBuffer.h"
-#include "core/platform/audio/ReverbConvolver.h"
-#include "core/platform/audio/ReverbInputBuffer.h"
-#include "core/platform/audio/VectorMath.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/PassOwnPtr.h"
-
-namespace WebCore {
-
-using namespace VectorMath;
-
-ReverbConvolverStage::ReverbConvolverStage(const float* impulseResponse, size_t, size_t reverbTotalLatency, size_t stageOffset, size_t stageLength,
- size_t fftSize, size_t renderPhase, size_t renderSliceSize, ReverbAccumulationBuffer* accumulationBuffer, bool directMode)
- : m_accumulationBuffer(accumulationBuffer)
- , m_accumulationReadIndex(0)
- , m_inputReadIndex(0)
- , m_directMode(directMode)
-{
- ASSERT(impulseResponse);
- ASSERT(accumulationBuffer);
-
- if (!m_directMode) {
- m_fftKernel = adoptPtr(new FFTFrame(fftSize));
- m_fftKernel->doPaddedFFT(impulseResponse + stageOffset, stageLength);
- m_fftConvolver = adoptPtr(new FFTConvolver(fftSize));
- } else {
- ASSERT(!stageOffset);
- ASSERT(stageLength <= fftSize / 2);
-
- m_directKernel = adoptPtr(new AudioFloatArray(fftSize / 2));
- m_directKernel->copyToRange(impulseResponse, 0, stageLength);
- m_directConvolver = adoptPtr(new DirectConvolver(renderSliceSize));
- }
- m_temporaryBuffer.allocate(renderSliceSize);
-
- // The convolution stage at offset stageOffset needs to have a corresponding delay to cancel out the offset.
- size_t totalDelay = stageOffset + reverbTotalLatency;
-
- // But, the FFT convolution itself incurs fftSize / 2 latency, so subtract this out...
- size_t halfSize = fftSize / 2;
- if (!m_directMode) {
- ASSERT(totalDelay >= halfSize);
- if (totalDelay >= halfSize)
- totalDelay -= halfSize;
- }
-
- // We divide up the total delay, into pre and post delay sections so that we can schedule at exactly the moment when the FFT will happen.
- // This is coordinated with the other stages, so they don't all do their FFTs at the same time...
- int maxPreDelayLength = std::min(halfSize, totalDelay);
- m_preDelayLength = totalDelay > 0 ? renderPhase % maxPreDelayLength : 0;
- if (m_preDelayLength > totalDelay)
- m_preDelayLength = 0;
-
- m_postDelayLength = totalDelay - m_preDelayLength;
- m_preReadWriteIndex = 0;
- m_framesProcessed = 0; // total frames processed so far
-
- size_t delayBufferSize = m_preDelayLength < fftSize ? fftSize : m_preDelayLength;
- delayBufferSize = delayBufferSize < renderSliceSize ? renderSliceSize : delayBufferSize;
- m_preDelayBuffer.allocate(delayBufferSize);
-}
-
-void ReverbConvolverStage::processInBackground(ReverbConvolver* convolver, size_t framesToProcess)
-{
- ReverbInputBuffer* inputBuffer = convolver->inputBuffer();
- float* source = inputBuffer->directReadFrom(&m_inputReadIndex, framesToProcess);
- process(source, framesToProcess);
-}
-
-void ReverbConvolverStage::process(const float* source, size_t framesToProcess)
-{
- ASSERT(source);
- if (!source)
- return;
-
- // Deal with pre-delay stream : note special handling of zero delay.
-
- const float* preDelayedSource;
- float* preDelayedDestination;
- float* temporaryBuffer;
- bool isTemporaryBufferSafe = false;
- if (m_preDelayLength > 0) {
- // Handles both the read case (call to process() ) and the write case (memcpy() )
- bool isPreDelaySafe = m_preReadWriteIndex + framesToProcess <= m_preDelayBuffer.size();
- ASSERT(isPreDelaySafe);
- if (!isPreDelaySafe)
- return;
-
- isTemporaryBufferSafe = framesToProcess <= m_temporaryBuffer.size();
-
- preDelayedDestination = m_preDelayBuffer.data() + m_preReadWriteIndex;
- preDelayedSource = preDelayedDestination;
- temporaryBuffer = m_temporaryBuffer.data();
- } else {
- // Zero delay
- preDelayedDestination = 0;
- preDelayedSource = source;
- temporaryBuffer = m_preDelayBuffer.data();
-
- isTemporaryBufferSafe = framesToProcess <= m_preDelayBuffer.size();
- }
-
- ASSERT(isTemporaryBufferSafe);
- if (!isTemporaryBufferSafe)
- return;
-
- if (m_framesProcessed < m_preDelayLength) {
- // For the first m_preDelayLength frames don't process the convolver, instead simply buffer in the pre-delay.
- // But while buffering the pre-delay, we still need to update our index.
- m_accumulationBuffer->updateReadIndex(&m_accumulationReadIndex, framesToProcess);
- } else {
- // Now, run the convolution (into the delay buffer).
- // An expensive FFT will happen every fftSize / 2 frames.
- // We process in-place here...
- if (!m_directMode)
- m_fftConvolver->process(m_fftKernel.get(), preDelayedSource, temporaryBuffer, framesToProcess);
- else
- m_directConvolver->process(m_directKernel.get(), preDelayedSource, temporaryBuffer, framesToProcess);
-
- // Now accumulate into reverb's accumulation buffer.
- m_accumulationBuffer->accumulate(temporaryBuffer, framesToProcess, &m_accumulationReadIndex, m_postDelayLength);
- }
-
- // Finally copy input to pre-delay.
- if (m_preDelayLength > 0) {
- memcpy(preDelayedDestination, source, sizeof(float) * framesToProcess);
- m_preReadWriteIndex += framesToProcess;
-
- ASSERT(m_preReadWriteIndex <= m_preDelayLength);
- if (m_preReadWriteIndex >= m_preDelayLength)
- m_preReadWriteIndex = 0;
- }
-
- m_framesProcessed += framesToProcess;
-}
-
-void ReverbConvolverStage::reset()
-{
- if (!m_directMode)
- m_fftConvolver->reset();
- else
- m_directConvolver->reset();
- m_preDelayBuffer.zero();
- m_accumulationReadIndex = 0;
- m_inputReadIndex = 0;
- m_framesProcessed = 0;
-}
-
-} // namespace WebCore
-
-#endif // ENABLE(WEB_AUDIO)
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/ReverbConvolverStage.h b/chromium/third_party/WebKit/Source/core/platform/audio/ReverbConvolverStage.h
deleted file mode 100644
index c88f41b8c9b..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/ReverbConvolverStage.h
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ReverbConvolverStage_h
-#define ReverbConvolverStage_h
-
-#include "core/platform/audio/AudioArray.h"
-#include "core/platform/audio/FFTFrame.h"
-#include "wtf/OwnPtr.h"
-
-namespace WebCore {
-
-class ReverbAccumulationBuffer;
-class ReverbConvolver;
-class FFTConvolver;
-class DirectConvolver;
-
-// A ReverbConvolverStage represents the convolution associated with a sub-section of a large impulse response.
-// It incorporates a delay line to account for the offset of the sub-section within the larger impulse response.
-class ReverbConvolverStage {
-public:
- // renderPhase is useful to know so that we can manipulate the pre versus post delay so that stages will perform
- // their heavy work (FFT processing) on different slices to balance the load in a real-time thread.
- ReverbConvolverStage(const float* impulseResponse, size_t responseLength, size_t reverbTotalLatency, size_t stageOffset, size_t stageLength, size_t fftSize, size_t renderPhase, size_t renderSliceSize, ReverbAccumulationBuffer*, bool directMode = false);
-
- // WARNING: framesToProcess must be such that it evenly divides the delay buffer size (stage_offset).
- void process(const float* source, size_t framesToProcess);
-
- void processInBackground(ReverbConvolver* convolver, size_t framesToProcess);
-
- void reset();
-
- // Useful for background processing
- int inputReadIndex() const { return m_inputReadIndex; }
-
-private:
- OwnPtr<FFTFrame> m_fftKernel;
- OwnPtr<FFTConvolver> m_fftConvolver;
-
- AudioFloatArray m_preDelayBuffer;
-
- ReverbAccumulationBuffer* m_accumulationBuffer;
- int m_accumulationReadIndex;
- int m_inputReadIndex;
-
- size_t m_preDelayLength;
- size_t m_postDelayLength;
- size_t m_preReadWriteIndex;
- size_t m_framesProcessed;
-
- AudioFloatArray m_temporaryBuffer;
-
- bool m_directMode;
- OwnPtr<AudioFloatArray> m_directKernel;
- OwnPtr<DirectConvolver> m_directConvolver;
-};
-
-} // namespace WebCore
-
-#endif // ReverbConvolverStage_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/ReverbInputBuffer.cpp b/chromium/third_party/WebKit/Source/core/platform/audio/ReverbInputBuffer.cpp
deleted file mode 100644
index 0a6dca7f804..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/ReverbInputBuffer.cpp
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#if ENABLE(WEB_AUDIO)
-
-#include "core/platform/audio/ReverbInputBuffer.h"
-
-namespace WebCore {
-
-ReverbInputBuffer::ReverbInputBuffer(size_t length)
- : m_buffer(length)
- , m_writeIndex(0)
-{
-}
-
-void ReverbInputBuffer::write(const float* sourceP, size_t numberOfFrames)
-{
- size_t bufferLength = m_buffer.size();
- bool isCopySafe = m_writeIndex + numberOfFrames <= bufferLength;
- ASSERT(isCopySafe);
- if (!isCopySafe)
- return;
-
- memcpy(m_buffer.data() + m_writeIndex, sourceP, sizeof(float) * numberOfFrames);
-
- m_writeIndex += numberOfFrames;
- ASSERT(m_writeIndex <= bufferLength);
-
- if (m_writeIndex >= bufferLength)
- m_writeIndex = 0;
-}
-
-float* ReverbInputBuffer::directReadFrom(int* readIndex, size_t numberOfFrames)
-{
- size_t bufferLength = m_buffer.size();
- bool isPointerGood = readIndex && *readIndex >= 0 && *readIndex + numberOfFrames <= bufferLength;
- ASSERT(isPointerGood);
- if (!isPointerGood) {
- // Should never happen in practice but return pointer to start of buffer (avoid crash)
- if (readIndex)
- *readIndex = 0;
- return m_buffer.data();
- }
-
- float* sourceP = m_buffer.data();
- float* p = sourceP + *readIndex;
-
- // Update readIndex
- *readIndex = (*readIndex + numberOfFrames) % bufferLength;
-
- return p;
-}
-
-void ReverbInputBuffer::reset()
-{
- m_buffer.zero();
- m_writeIndex = 0;
-}
-
-} // namespace WebCore
-
-#endif // ENABLE(WEB_AUDIO)
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/ReverbInputBuffer.h b/chromium/third_party/WebKit/Source/core/platform/audio/ReverbInputBuffer.h
deleted file mode 100644
index ea1233ffbc5..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/ReverbInputBuffer.h
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ReverbInputBuffer_h
-#define ReverbInputBuffer_h
-
-#include "core/platform/audio/AudioArray.h"
-
-namespace WebCore {
-
-// ReverbInputBuffer is used to buffer input samples for deferred processing by the background threads.
-class ReverbInputBuffer {
-public:
- ReverbInputBuffer(size_t length);
-
- // The realtime audio thread keeps writing samples here.
- // The assumption is that the buffer's length is evenly divisible by numberOfFrames (for nearly all cases this will be fine).
- // FIXME: remove numberOfFrames restriction...
- void write(const float* sourceP, size_t numberOfFrames);
-
- // Background threads can call this to check if there's anything to read...
- size_t writeIndex() const { return m_writeIndex; }
-
- // The individual background threads read here (and hope that they can keep up with the buffer writing).
- // readIndex is updated with the next readIndex to read from...
- // The assumption is that the buffer's length is evenly divisible by numberOfFrames.
- // FIXME: remove numberOfFrames restriction...
- float* directReadFrom(int* readIndex, size_t numberOfFrames);
-
- void reset();
-
-private:
- AudioFloatArray m_buffer;
- size_t m_writeIndex;
-};
-
-} // namespace WebCore
-
-#endif // ReverbInputBuffer_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/SincResampler.cpp b/chromium/third_party/WebKit/Source/core/platform/audio/SincResampler.cpp
deleted file mode 100644
index d429fbc978b..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/SincResampler.cpp
+++ /dev/null
@@ -1,474 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#if ENABLE(WEB_AUDIO)
-
-#include "core/platform/audio/SincResampler.h"
-
-#include "core/platform/audio/AudioBus.h"
-#include "wtf/MathExtras.h"
-
-#ifdef __SSE2__
-#include <emmintrin.h>
-#endif
-
-using namespace std;
-
-// Input buffer layout, dividing the total buffer into regions (r0 - r5):
-//
-// |----------------|----------------------------------------------------------------|----------------|
-//
-// blockSize + kernelSize / 2
-// <-------------------------------------------------------------------------------->
-// r0
-//
-// kernelSize / 2 kernelSize / 2 kernelSize / 2 kernelSize / 2
-// <---------------> <---------------> <---------------> <--------------->
-// r1 r2 r3 r4
-//
-// blockSize
-// <-------------------------------------------------------------->
-// r5
-
-// The Algorithm:
-//
-// 1) Consume input frames into r0 (r1 is zero-initialized).
-// 2) Position kernel centered at start of r0 (r2) and generate output frames until kernel is centered at start of r4.
-// or we've finished generating all the output frames.
-// 3) Copy r3 to r1 and r4 to r2.
-// 4) Consume input frames into r5 (zero-pad if we run out of input).
-// 5) Goto (2) until all of input is consumed.
-//
-// note: we're glossing over how the sub-sample handling works with m_virtualSourceIndex, etc.
-
-namespace WebCore {
-
-SincResampler::SincResampler(double scaleFactor, unsigned kernelSize, unsigned numberOfKernelOffsets)
- : m_scaleFactor(scaleFactor)
- , m_kernelSize(kernelSize)
- , m_numberOfKernelOffsets(numberOfKernelOffsets)
- , m_kernelStorage(m_kernelSize * (m_numberOfKernelOffsets + 1))
- , m_virtualSourceIndex(0)
- , m_blockSize(512)
- , m_inputBuffer(m_blockSize + m_kernelSize) // See input buffer layout above.
- , m_source(0)
- , m_sourceFramesAvailable(0)
- , m_sourceProvider(0)
- , m_isBufferPrimed(false)
-{
- initializeKernel();
-}
-
-void SincResampler::initializeKernel()
-{
- // Blackman window parameters.
- double alpha = 0.16;
- double a0 = 0.5 * (1.0 - alpha);
- double a1 = 0.5;
- double a2 = 0.5 * alpha;
-
- // sincScaleFactor is basically the normalized cutoff frequency of the low-pass filter.
- double sincScaleFactor = m_scaleFactor > 1.0 ? 1.0 / m_scaleFactor : 1.0;
-
- // The sinc function is an idealized brick-wall filter, but since we're windowing it the
- // transition from pass to stop does not happen right away. So we should adjust the
- // lowpass filter cutoff slightly downward to avoid some aliasing at the very high-end.
- // FIXME: this value is empirical and to be more exact should vary depending on m_kernelSize.
- sincScaleFactor *= 0.9;
-
- int n = m_kernelSize;
- int halfSize = n / 2;
-
- // Generates a set of windowed sinc() kernels.
- // We generate a range of sub-sample offsets from 0.0 to 1.0.
- for (unsigned offsetIndex = 0; offsetIndex <= m_numberOfKernelOffsets; ++offsetIndex) {
- double subsampleOffset = static_cast<double>(offsetIndex) / m_numberOfKernelOffsets;
-
- for (int i = 0; i < n; ++i) {
- // Compute the sinc() with offset.
- double s = sincScaleFactor * piDouble * (i - halfSize - subsampleOffset);
- double sinc = !s ? 1.0 : sin(s) / s;
- sinc *= sincScaleFactor;
-
- // Compute Blackman window, matching the offset of the sinc().
- double x = (i - subsampleOffset) / n;
- double window = a0 - a1 * cos(2.0 * piDouble * x) + a2 * cos(4.0 * piDouble * x);
-
- // Window the sinc() function and store at the correct offset.
- m_kernelStorage[i + offsetIndex * m_kernelSize] = sinc * window;
- }
- }
-}
-
-void SincResampler::consumeSource(float* buffer, unsigned numberOfSourceFrames)
-{
- ASSERT(m_sourceProvider);
- if (!m_sourceProvider)
- return;
-
- // Wrap the provided buffer by an AudioBus for use by the source provider.
- RefPtr<AudioBus> bus = AudioBus::create(1, numberOfSourceFrames, false);
-
- // FIXME: Find a way to make the following const-correct:
- bus->setChannelMemory(0, buffer, numberOfSourceFrames);
-
- m_sourceProvider->provideInput(bus.get(), numberOfSourceFrames);
-}
-
-namespace {
-
-// BufferSourceProvider is an AudioSourceProvider wrapping an in-memory buffer.
-
-class BufferSourceProvider : public AudioSourceProvider {
-public:
- BufferSourceProvider(const float* source, size_t numberOfSourceFrames)
- : m_source(source)
- , m_sourceFramesAvailable(numberOfSourceFrames)
- {
- }
-
- // Consumes samples from the in-memory buffer.
- virtual void provideInput(AudioBus* bus, size_t framesToProcess)
- {
- ASSERT(m_source && bus);
- if (!m_source || !bus)
- return;
-
- float* buffer = bus->channel(0)->mutableData();
-
- // Clamp to number of frames available and zero-pad.
- size_t framesToCopy = min(m_sourceFramesAvailable, framesToProcess);
- memcpy(buffer, m_source, sizeof(float) * framesToCopy);
-
- // Zero-pad if necessary.
- if (framesToCopy < framesToProcess)
- memset(buffer + framesToCopy, 0, sizeof(float) * (framesToProcess - framesToCopy));
-
- m_sourceFramesAvailable -= framesToCopy;
- m_source += framesToCopy;
- }
-
-private:
- const float* m_source;
- size_t m_sourceFramesAvailable;
-};
-
-} // namespace
-
-void SincResampler::process(const float* source, float* destination, unsigned numberOfSourceFrames)
-{
- // Resample an in-memory buffer using an AudioSourceProvider.
- BufferSourceProvider sourceProvider(source, numberOfSourceFrames);
-
- unsigned numberOfDestinationFrames = static_cast<unsigned>(numberOfSourceFrames / m_scaleFactor);
- unsigned remaining = numberOfDestinationFrames;
-
- while (remaining) {
- unsigned framesThisTime = min(remaining, m_blockSize);
- process(&sourceProvider, destination, framesThisTime);
-
- destination += framesThisTime;
- remaining -= framesThisTime;
- }
-}
-
-void SincResampler::process(AudioSourceProvider* sourceProvider, float* destination, size_t framesToProcess)
-{
- bool isGood = sourceProvider && m_blockSize > m_kernelSize && m_inputBuffer.size() >= m_blockSize + m_kernelSize && !(m_kernelSize % 2);
- ASSERT(isGood);
- if (!isGood)
- return;
-
- m_sourceProvider = sourceProvider;
-
- unsigned numberOfDestinationFrames = framesToProcess;
-
- // Setup various region pointers in the buffer (see diagram above).
- float* r0 = m_inputBuffer.data() + m_kernelSize / 2;
- float* r1 = m_inputBuffer.data();
- float* r2 = r0;
- float* r3 = r0 + m_blockSize - m_kernelSize / 2;
- float* r4 = r0 + m_blockSize;
- float* r5 = r0 + m_kernelSize / 2;
-
- // Step (1)
- // Prime the input buffer at the start of the input stream.
- if (!m_isBufferPrimed) {
- consumeSource(r0, m_blockSize + m_kernelSize / 2);
- m_isBufferPrimed = true;
- }
-
- // Step (2)
-
- while (numberOfDestinationFrames) {
- while (m_virtualSourceIndex < m_blockSize) {
- // m_virtualSourceIndex lies in between two kernel offsets so figure out what they are.
- int sourceIndexI = static_cast<int>(m_virtualSourceIndex);
- double subsampleRemainder = m_virtualSourceIndex - sourceIndexI;
-
- double virtualOffsetIndex = subsampleRemainder * m_numberOfKernelOffsets;
- int offsetIndex = static_cast<int>(virtualOffsetIndex);
-
- float* k1 = m_kernelStorage.data() + offsetIndex * m_kernelSize;
- float* k2 = k1 + m_kernelSize;
-
- // Initialize input pointer based on quantized m_virtualSourceIndex.
- float* inputP = r1 + sourceIndexI;
-
- // We'll compute "convolutions" for the two kernels which straddle m_virtualSourceIndex
- float sum1 = 0;
- float sum2 = 0;
-
- // Figure out how much to weight each kernel's "convolution".
- double kernelInterpolationFactor = virtualOffsetIndex - offsetIndex;
-
- // Generate a single output sample.
- int n = m_kernelSize;
-
-#define CONVOLVE_ONE_SAMPLE \
- input = *inputP++; \
- sum1 += input * *k1; \
- sum2 += input * *k2; \
- ++k1; \
- ++k2;
-
- {
- float input;
-
-#ifdef __SSE2__
- // If the sourceP address is not 16-byte aligned, the first several frames (at most three) should be processed seperately.
- while ((reinterpret_cast<uintptr_t>(inputP) & 0x0F) && n) {
- CONVOLVE_ONE_SAMPLE
- n--;
- }
-
- // Now the inputP is aligned and start to apply SSE.
- float* endP = inputP + n - n % 4;
- __m128 mInput;
- __m128 mK1;
- __m128 mK2;
- __m128 mul1;
- __m128 mul2;
-
- __m128 sums1 = _mm_setzero_ps();
- __m128 sums2 = _mm_setzero_ps();
- bool k1Aligned = !(reinterpret_cast<uintptr_t>(k1) & 0x0F);
- bool k2Aligned = !(reinterpret_cast<uintptr_t>(k2) & 0x0F);
-
-#define LOAD_DATA(l1, l2) \
- mInput = _mm_load_ps(inputP); \
- mK1 = _mm_##l1##_ps(k1); \
- mK2 = _mm_##l2##_ps(k2);
-
-#define CONVOLVE_4_SAMPLES \
- mul1 = _mm_mul_ps(mInput, mK1); \
- mul2 = _mm_mul_ps(mInput, mK2); \
- sums1 = _mm_add_ps(sums1, mul1); \
- sums2 = _mm_add_ps(sums2, mul2); \
- inputP += 4; \
- k1 += 4; \
- k2 += 4;
-
- if (k1Aligned && k2Aligned) { // both aligned
- while (inputP < endP) {
- LOAD_DATA(load, load)
- CONVOLVE_4_SAMPLES
- }
- } else if (!k1Aligned && k2Aligned) { // only k2 aligned
- while (inputP < endP) {
- LOAD_DATA(loadu, load)
- CONVOLVE_4_SAMPLES
- }
- } else if (k1Aligned && !k2Aligned) { // only k1 aligned
- while (inputP < endP) {
- LOAD_DATA(load, loadu)
- CONVOLVE_4_SAMPLES
- }
- } else { // both non-aligned
- while (inputP < endP) {
- LOAD_DATA(loadu, loadu)
- CONVOLVE_4_SAMPLES
- }
- }
-
- // Summarize the SSE results to sum1 and sum2.
- float* groupSumP = reinterpret_cast<float*>(&sums1);
- sum1 += groupSumP[0] + groupSumP[1] + groupSumP[2] + groupSumP[3];
- groupSumP = reinterpret_cast<float*>(&sums2);
- sum2 += groupSumP[0] + groupSumP[1] + groupSumP[2] + groupSumP[3];
-
- n %= 4;
- while (n) {
- CONVOLVE_ONE_SAMPLE
- n--;
- }
-#else
- // FIXME: add ARM NEON optimizations for the following. The scalar code-path can probably also be optimized better.
-
- // Optimize size 32 and size 64 kernels by unrolling the while loop.
- // A 20 - 30% speed improvement was measured in some cases by using this approach.
-
- if (n == 32) {
- CONVOLVE_ONE_SAMPLE // 1
- CONVOLVE_ONE_SAMPLE // 2
- CONVOLVE_ONE_SAMPLE // 3
- CONVOLVE_ONE_SAMPLE // 4
- CONVOLVE_ONE_SAMPLE // 5
- CONVOLVE_ONE_SAMPLE // 6
- CONVOLVE_ONE_SAMPLE // 7
- CONVOLVE_ONE_SAMPLE // 8
- CONVOLVE_ONE_SAMPLE // 9
- CONVOLVE_ONE_SAMPLE // 10
- CONVOLVE_ONE_SAMPLE // 11
- CONVOLVE_ONE_SAMPLE // 12
- CONVOLVE_ONE_SAMPLE // 13
- CONVOLVE_ONE_SAMPLE // 14
- CONVOLVE_ONE_SAMPLE // 15
- CONVOLVE_ONE_SAMPLE // 16
- CONVOLVE_ONE_SAMPLE // 17
- CONVOLVE_ONE_SAMPLE // 18
- CONVOLVE_ONE_SAMPLE // 19
- CONVOLVE_ONE_SAMPLE // 20
- CONVOLVE_ONE_SAMPLE // 21
- CONVOLVE_ONE_SAMPLE // 22
- CONVOLVE_ONE_SAMPLE // 23
- CONVOLVE_ONE_SAMPLE // 24
- CONVOLVE_ONE_SAMPLE // 25
- CONVOLVE_ONE_SAMPLE // 26
- CONVOLVE_ONE_SAMPLE // 27
- CONVOLVE_ONE_SAMPLE // 28
- CONVOLVE_ONE_SAMPLE // 29
- CONVOLVE_ONE_SAMPLE // 30
- CONVOLVE_ONE_SAMPLE // 31
- CONVOLVE_ONE_SAMPLE // 32
- } else if (n == 64) {
- CONVOLVE_ONE_SAMPLE // 1
- CONVOLVE_ONE_SAMPLE // 2
- CONVOLVE_ONE_SAMPLE // 3
- CONVOLVE_ONE_SAMPLE // 4
- CONVOLVE_ONE_SAMPLE // 5
- CONVOLVE_ONE_SAMPLE // 6
- CONVOLVE_ONE_SAMPLE // 7
- CONVOLVE_ONE_SAMPLE // 8
- CONVOLVE_ONE_SAMPLE // 9
- CONVOLVE_ONE_SAMPLE // 10
- CONVOLVE_ONE_SAMPLE // 11
- CONVOLVE_ONE_SAMPLE // 12
- CONVOLVE_ONE_SAMPLE // 13
- CONVOLVE_ONE_SAMPLE // 14
- CONVOLVE_ONE_SAMPLE // 15
- CONVOLVE_ONE_SAMPLE // 16
- CONVOLVE_ONE_SAMPLE // 17
- CONVOLVE_ONE_SAMPLE // 18
- CONVOLVE_ONE_SAMPLE // 19
- CONVOLVE_ONE_SAMPLE // 20
- CONVOLVE_ONE_SAMPLE // 21
- CONVOLVE_ONE_SAMPLE // 22
- CONVOLVE_ONE_SAMPLE // 23
- CONVOLVE_ONE_SAMPLE // 24
- CONVOLVE_ONE_SAMPLE // 25
- CONVOLVE_ONE_SAMPLE // 26
- CONVOLVE_ONE_SAMPLE // 27
- CONVOLVE_ONE_SAMPLE // 28
- CONVOLVE_ONE_SAMPLE // 29
- CONVOLVE_ONE_SAMPLE // 30
- CONVOLVE_ONE_SAMPLE // 31
- CONVOLVE_ONE_SAMPLE // 32
- CONVOLVE_ONE_SAMPLE // 33
- CONVOLVE_ONE_SAMPLE // 34
- CONVOLVE_ONE_SAMPLE // 35
- CONVOLVE_ONE_SAMPLE // 36
- CONVOLVE_ONE_SAMPLE // 37
- CONVOLVE_ONE_SAMPLE // 38
- CONVOLVE_ONE_SAMPLE // 39
- CONVOLVE_ONE_SAMPLE // 40
- CONVOLVE_ONE_SAMPLE // 41
- CONVOLVE_ONE_SAMPLE // 42
- CONVOLVE_ONE_SAMPLE // 43
- CONVOLVE_ONE_SAMPLE // 44
- CONVOLVE_ONE_SAMPLE // 45
- CONVOLVE_ONE_SAMPLE // 46
- CONVOLVE_ONE_SAMPLE // 47
- CONVOLVE_ONE_SAMPLE // 48
- CONVOLVE_ONE_SAMPLE // 49
- CONVOLVE_ONE_SAMPLE // 50
- CONVOLVE_ONE_SAMPLE // 51
- CONVOLVE_ONE_SAMPLE // 52
- CONVOLVE_ONE_SAMPLE // 53
- CONVOLVE_ONE_SAMPLE // 54
- CONVOLVE_ONE_SAMPLE // 55
- CONVOLVE_ONE_SAMPLE // 56
- CONVOLVE_ONE_SAMPLE // 57
- CONVOLVE_ONE_SAMPLE // 58
- CONVOLVE_ONE_SAMPLE // 59
- CONVOLVE_ONE_SAMPLE // 60
- CONVOLVE_ONE_SAMPLE // 61
- CONVOLVE_ONE_SAMPLE // 62
- CONVOLVE_ONE_SAMPLE // 63
- CONVOLVE_ONE_SAMPLE // 64
- } else {
- while (n--) {
- // Non-optimized using actual while loop.
- CONVOLVE_ONE_SAMPLE
- }
- }
-#endif
- }
-
- // Linearly interpolate the two "convolutions".
- double result = (1.0 - kernelInterpolationFactor) * sum1 + kernelInterpolationFactor * sum2;
-
- *destination++ = result;
-
- // Advance the virtual index.
- m_virtualSourceIndex += m_scaleFactor;
-
- --numberOfDestinationFrames;
- if (!numberOfDestinationFrames)
- return;
- }
-
- // Wrap back around to the start.
- m_virtualSourceIndex -= m_blockSize;
-
- // Step (3) Copy r3 to r1 and r4 to r2.
- // This wraps the last input frames back to the start of the buffer.
- memcpy(r1, r3, sizeof(float) * (m_kernelSize / 2));
- memcpy(r2, r4, sizeof(float) * (m_kernelSize / 2));
-
- // Step (4)
- // Refresh the buffer with more input.
- consumeSource(r5, m_blockSize);
- }
-}
-
-} // namespace WebCore
-
-#endif // ENABLE(WEB_AUDIO)
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/SincResampler.h b/chromium/third_party/WebKit/Source/core/platform/audio/SincResampler.h
deleted file mode 100644
index 807596e3796..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/SincResampler.h
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SincResampler_h
-#define SincResampler_h
-
-#include "core/platform/audio/AudioArray.h"
-#include "core/platform/audio/AudioSourceProvider.h"
-
-namespace WebCore {
-
-// SincResampler is a high-quality sample-rate converter.
-
-class SincResampler {
-public:
- // scaleFactor == sourceSampleRate / destinationSampleRate
- // kernelSize can be adjusted for quality (higher is better)
- // numberOfKernelOffsets is used for interpolation and is the number of sub-sample kernel shifts.
- SincResampler(double scaleFactor, unsigned kernelSize = 32, unsigned numberOfKernelOffsets = 32);
-
- // Processes numberOfSourceFrames from source to produce numberOfSourceFrames / scaleFactor frames in destination.
- void process(const float* source, float* destination, unsigned numberOfSourceFrames);
-
- // Process with input source callback function for streaming applications.
- void process(AudioSourceProvider*, float* destination, size_t framesToProcess);
-
-protected:
- void initializeKernel();
- void consumeSource(float* buffer, unsigned numberOfSourceFrames);
-
- double m_scaleFactor;
- unsigned m_kernelSize;
- unsigned m_numberOfKernelOffsets;
-
- // m_kernelStorage has m_numberOfKernelOffsets kernels back-to-back, each of size m_kernelSize.
- // The kernel offsets are sub-sample shifts of a windowed sinc() shifted from 0.0 to 1.0 sample.
- AudioFloatArray m_kernelStorage;
-
- // m_virtualSourceIndex is an index on the source input buffer with sub-sample precision.
- // It must be double precision to avoid drift.
- double m_virtualSourceIndex;
-
- // This is the number of destination frames we generate per processing pass on the buffer.
- unsigned m_blockSize;
-
- // Source is copied into this buffer for each processing pass.
- AudioFloatArray m_inputBuffer;
-
- const float* m_source;
- unsigned m_sourceFramesAvailable;
-
- // m_sourceProvider is used to provide the audio input stream to the resampler.
- AudioSourceProvider* m_sourceProvider;
-
- // The buffer is primed once at the very beginning of processing.
- bool m_isBufferPrimed;
-};
-
-} // namespace WebCore
-
-#endif // SincResampler_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/UpSampler.cpp b/chromium/third_party/WebKit/Source/core/platform/audio/UpSampler.cpp
deleted file mode 100644
index ebc17610ea2..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/UpSampler.cpp
+++ /dev/null
@@ -1,134 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#if ENABLE(WEB_AUDIO)
-
-#include "core/platform/audio/UpSampler.h"
-
-#include "wtf/MathExtras.h"
-
-namespace WebCore {
-
-UpSampler::UpSampler(size_t inputBlockSize)
- : m_inputBlockSize(inputBlockSize)
- , m_kernel(DefaultKernelSize)
- , m_tempBuffer(inputBlockSize)
- , m_inputBuffer(inputBlockSize * 2)
- , m_convolver(inputBlockSize)
-{
- initializeKernel();
-}
-
-void UpSampler::initializeKernel()
-{
- // Blackman window parameters.
- double alpha = 0.16;
- double a0 = 0.5 * (1.0 - alpha);
- double a1 = 0.5;
- double a2 = 0.5 * alpha;
-
- int n = m_kernel.size();
- int halfSize = n / 2;
- double subsampleOffset = -0.5;
-
- for (int i = 0; i < n; ++i) {
- // Compute the sinc() with offset.
- double s = piDouble * (i - halfSize - subsampleOffset);
- double sinc = !s ? 1.0 : sin(s) / s;
-
- // Compute Blackman window, matching the offset of the sinc().
- double x = (i - subsampleOffset) / n;
- double window = a0 - a1 * cos(2.0 * piDouble * x) + a2 * cos(4.0 * piDouble * x);
-
- // Window the sinc() function.
- m_kernel[i] = sinc * window;
- }
-}
-
-void UpSampler::process(const float* sourceP, float* destP, size_t sourceFramesToProcess)
-{
- bool isInputBlockSizeGood = sourceFramesToProcess == m_inputBlockSize;
- ASSERT(isInputBlockSizeGood);
- if (!isInputBlockSizeGood)
- return;
-
- bool isTempBufferGood = sourceFramesToProcess == m_tempBuffer.size();
- ASSERT(isTempBufferGood);
- if (!isTempBufferGood)
- return;
-
- bool isKernelGood = m_kernel.size() == DefaultKernelSize;
- ASSERT(isKernelGood);
- if (!isKernelGood)
- return;
-
- size_t halfSize = m_kernel.size() / 2;
-
- // Copy source samples to 2nd half of input buffer.
- bool isInputBufferGood = m_inputBuffer.size() == sourceFramesToProcess * 2 && halfSize <= sourceFramesToProcess;
- ASSERT(isInputBufferGood);
- if (!isInputBufferGood)
- return;
-
- float* inputP = m_inputBuffer.data() + sourceFramesToProcess;
- memcpy(inputP, sourceP, sizeof(float) * sourceFramesToProcess);
-
- // Copy even sample-frames 0,2,4,6... (delayed by the linear phase delay) directly into destP.
- for (unsigned i = 0; i < sourceFramesToProcess; ++i)
- destP[i * 2] = *((inputP - halfSize) + i);
-
- // Compute odd sample-frames 1,3,5,7...
- float* oddSamplesP = m_tempBuffer.data();
- m_convolver.process(&m_kernel, sourceP, oddSamplesP, sourceFramesToProcess);
-
- for (unsigned i = 0; i < sourceFramesToProcess; ++i)
- destP[i * 2 + 1] = oddSamplesP[i];
-
- // Copy 2nd half of input buffer to 1st half.
- memcpy(m_inputBuffer.data(), inputP, sizeof(float) * sourceFramesToProcess);
-}
-
-void UpSampler::reset()
-{
- m_convolver.reset();
- m_inputBuffer.zero();
-}
-
-size_t UpSampler::latencyFrames() const
-{
- // Divide by two since this is a linear phase kernel and the delay is at the center of the kernel.
- return m_kernel.size() / 2;
-}
-
-} // namespace WebCore
-
-#endif // ENABLE(WEB_AUDIO)
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/UpSampler.h b/chromium/third_party/WebKit/Source/core/platform/audio/UpSampler.h
deleted file mode 100644
index ebd39935098..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/UpSampler.h
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef UpSampler_h
-#define UpSampler_h
-
-#include "core/platform/audio/AudioArray.h"
-#include "core/platform/audio/DirectConvolver.h"
-
-namespace WebCore {
-
-// UpSampler up-samples the source stream by a factor of 2x.
-
-class UpSampler {
-public:
- UpSampler(size_t inputBlockSize);
-
- // The destination buffer |destP| is of size sourceFramesToProcess * 2.
- void process(const float* sourceP, float* destP, size_t sourceFramesToProcess);
-
- void reset();
-
- // Latency based on the source sample-rate.
- size_t latencyFrames() const;
-
-private:
- enum { DefaultKernelSize = 128 };
-
- size_t m_inputBlockSize;
-
- // Computes ideal band-limited filter coefficients to sample in between each source sample-frame.
- // This filter will be used to compute the odd sample-frames of the output.
- void initializeKernel();
- AudioFloatArray m_kernel;
-
- // Computes the odd sample-frames of the output.
- DirectConvolver m_convolver;
-
- AudioFloatArray m_tempBuffer;
-
- // Delay line for generating the even sample-frames of the output.
- // The source samples are delayed exactly to match the linear phase delay of the FIR filter (convolution)
- // used to generate the odd sample-frames of the output.
- AudioFloatArray m_inputBuffer;
-};
-
-} // namespace WebCore
-
-#endif // UpSampler_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/VectorMath.cpp b/chromium/third_party/WebKit/Source/core/platform/audio/VectorMath.cpp
deleted file mode 100644
index d16f3c813cd..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/VectorMath.cpp
+++ /dev/null
@@ -1,690 +0,0 @@
-/*
- * Copyright (C) 2010, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#if ENABLE(WEB_AUDIO)
-
-#include "core/platform/audio/VectorMath.h"
-#include "wtf/Assertions.h"
-#include "wtf/CPU.h"
-#include <stdint.h>
-
-#if OS(MACOSX)
-#include <Accelerate/Accelerate.h>
-#endif
-
-#ifdef __SSE2__
-#include <emmintrin.h>
-#endif
-
-#if HAVE(ARM_NEON_INTRINSICS)
-#include <arm_neon.h>
-#endif
-
-#include <math.h>
-#include <algorithm>
-
-namespace WebCore {
-
-namespace VectorMath {
-
-#if OS(MACOSX)
-// On the Mac we use the highly optimized versions in Accelerate.framework
-// In 32-bit mode (__ppc__ or __i386__) <Accelerate/Accelerate.h> includes <vecLib/vDSP_translate.h> which defines macros of the same name as
-// our namespaced function names, so we must handle this case differently. Other architectures (64bit, ARM, etc.) do not include this header file.
-
-void vsmul(const float* sourceP, int sourceStride, const float* scale, float* destP, int destStride, size_t framesToProcess)
-{
-#if CPU(X86)
- ::vsmul(sourceP, sourceStride, scale, destP, destStride, framesToProcess);
-#else
- vDSP_vsmul(sourceP, sourceStride, scale, destP, destStride, framesToProcess);
-#endif
-}
-
-void vadd(const float* source1P, int sourceStride1, const float* source2P, int sourceStride2, float* destP, int destStride, size_t framesToProcess)
-{
-#if CPU(X86)
- ::vadd(source1P, sourceStride1, source2P, sourceStride2, destP, destStride, framesToProcess);
-#else
- vDSP_vadd(source1P, sourceStride1, source2P, sourceStride2, destP, destStride, framesToProcess);
-#endif
-}
-
-void vmul(const float* source1P, int sourceStride1, const float* source2P, int sourceStride2, float* destP, int destStride, size_t framesToProcess)
-{
-#if CPU(X86)
- ::vmul(source1P, sourceStride1, source2P, sourceStride2, destP, destStride, framesToProcess);
-#else
- vDSP_vmul(source1P, sourceStride1, source2P, sourceStride2, destP, destStride, framesToProcess);
-#endif
-}
-
-void zvmul(const float* real1P, const float* imag1P, const float* real2P, const float* imag2P, float* realDestP, float* imagDestP, size_t framesToProcess)
-{
- DSPSplitComplex sc1;
- DSPSplitComplex sc2;
- DSPSplitComplex dest;
- sc1.realp = const_cast<float*>(real1P);
- sc1.imagp = const_cast<float*>(imag1P);
- sc2.realp = const_cast<float*>(real2P);
- sc2.imagp = const_cast<float*>(imag2P);
- dest.realp = realDestP;
- dest.imagp = imagDestP;
-#if CPU(X86)
- ::zvmul(&sc1, 1, &sc2, 1, &dest, 1, framesToProcess, 1);
-#else
- vDSP_zvmul(&sc1, 1, &sc2, 1, &dest, 1, framesToProcess, 1);
-#endif
-}
-
-void vsma(const float* sourceP, int sourceStride, const float* scale, float* destP, int destStride, size_t framesToProcess)
-{
- vDSP_vsma(sourceP, sourceStride, scale, destP, destStride, destP, destStride, framesToProcess);
-}
-
-void vmaxmgv(const float* sourceP, int sourceStride, float* maxP, size_t framesToProcess)
-{
- vDSP_maxmgv(sourceP, sourceStride, maxP, framesToProcess);
-}
-
-void vsvesq(const float* sourceP, int sourceStride, float* sumP, size_t framesToProcess)
-{
- vDSP_svesq(const_cast<float*>(sourceP), sourceStride, sumP, framesToProcess);
-}
-
-void vclip(const float* sourceP, int sourceStride, const float* lowThresholdP, const float* highThresholdP, float* destP, int destStride, size_t framesToProcess)
-{
- vDSP_vclip(const_cast<float*>(sourceP), sourceStride, const_cast<float*>(lowThresholdP), const_cast<float*>(highThresholdP), destP, destStride, framesToProcess);
-}
-#else
-
-void vsma(const float* sourceP, int sourceStride, const float* scale, float* destP, int destStride, size_t framesToProcess)
-{
- int n = framesToProcess;
-
-#ifdef __SSE2__
- if ((sourceStride == 1) && (destStride == 1)) {
- float k = *scale;
-
- // If the sourceP address is not 16-byte aligned, the first several frames (at most three) should be processed separately.
- while ((reinterpret_cast<uintptr_t>(sourceP) & 0x0F) && n) {
- *destP += k * *sourceP;
- sourceP++;
- destP++;
- n--;
- }
-
- // Now the sourceP is aligned, use SSE.
- int tailFrames = n % 4;
- const float* endP = destP + n - tailFrames;
-
- __m128 pSource;
- __m128 dest;
- __m128 temp;
- __m128 mScale = _mm_set_ps1(k);
-
- bool destAligned = !(reinterpret_cast<uintptr_t>(destP) & 0x0F);
-
-#define SSE2_MULT_ADD(loadInstr, storeInstr) \
- while (destP < endP) \
- { \
- pSource = _mm_load_ps(sourceP); \
- temp = _mm_mul_ps(pSource, mScale); \
- dest = _mm_##loadInstr##_ps(destP); \
- dest = _mm_add_ps(dest, temp); \
- _mm_##storeInstr##_ps(destP, dest); \
- sourceP += 4; \
- destP += 4; \
- }
-
- if (destAligned)
- SSE2_MULT_ADD(load, store)
- else
- SSE2_MULT_ADD(loadu, storeu)
-
- n = tailFrames;
- }
-#elif HAVE(ARM_NEON_INTRINSICS)
- if ((sourceStride == 1) && (destStride == 1)) {
- int tailFrames = n % 4;
- const float* endP = destP + n - tailFrames;
-
- float32x4_t k = vdupq_n_f32(*scale);
- while (destP < endP) {
- float32x4_t source = vld1q_f32(sourceP);
- float32x4_t dest = vld1q_f32(destP);
-
- dest = vmlaq_f32(dest, source, k);
- vst1q_f32(destP, dest);
-
- sourceP += 4;
- destP += 4;
- }
- n = tailFrames;
- }
-#endif
- while (n) {
- *destP += *sourceP * *scale;
- sourceP += sourceStride;
- destP += destStride;
- n--;
- }
-}
-
-void vsmul(const float* sourceP, int sourceStride, const float* scale, float* destP, int destStride, size_t framesToProcess)
-{
- int n = framesToProcess;
-
-#ifdef __SSE2__
- if ((sourceStride == 1) && (destStride == 1)) {
- float k = *scale;
-
- // If the sourceP address is not 16-byte aligned, the first several frames (at most three) should be processed separately.
- while ((reinterpret_cast<size_t>(sourceP) & 0x0F) && n) {
- *destP = k * *sourceP;
- sourceP++;
- destP++;
- n--;
- }
-
- // Now the sourceP address is aligned and start to apply SSE.
- int group = n / 4;
- __m128 mScale = _mm_set_ps1(k);
- __m128* pSource;
- __m128* pDest;
- __m128 dest;
-
-
- if (reinterpret_cast<size_t>(destP) & 0x0F) {
- while (group--) {
- pSource = reinterpret_cast<__m128*>(const_cast<float*>(sourceP));
- dest = _mm_mul_ps(*pSource, mScale);
- _mm_storeu_ps(destP, dest);
-
- sourceP += 4;
- destP += 4;
- }
- } else {
- while (group--) {
- pSource = reinterpret_cast<__m128*>(const_cast<float*>(sourceP));
- pDest = reinterpret_cast<__m128*>(destP);
- *pDest = _mm_mul_ps(*pSource, mScale);
-
- sourceP += 4;
- destP += 4;
- }
- }
-
- // Non-SSE handling for remaining frames which is less than 4.
- n %= 4;
- while (n) {
- *destP = k * *sourceP;
- sourceP++;
- destP++;
- n--;
- }
- } else { // If strides are not 1, rollback to normal algorithm.
-#elif HAVE(ARM_NEON_INTRINSICS)
- if ((sourceStride == 1) && (destStride == 1)) {
- float k = *scale;
- int tailFrames = n % 4;
- const float* endP = destP + n - tailFrames;
-
- while (destP < endP) {
- float32x4_t source = vld1q_f32(sourceP);
- vst1q_f32(destP, vmulq_n_f32(source, k));
-
- sourceP += 4;
- destP += 4;
- }
- n = tailFrames;
- }
-#endif
- float k = *scale;
- while (n--) {
- *destP = k * *sourceP;
- sourceP += sourceStride;
- destP += destStride;
- }
-#ifdef __SSE2__
- }
-#endif
-}
-
-void vadd(const float* source1P, int sourceStride1, const float* source2P, int sourceStride2, float* destP, int destStride, size_t framesToProcess)
-{
- int n = framesToProcess;
-
-#ifdef __SSE2__
- if ((sourceStride1 ==1) && (sourceStride2 == 1) && (destStride == 1)) {
- // If the sourceP address is not 16-byte aligned, the first several frames (at most three) should be processed separately.
- while ((reinterpret_cast<size_t>(source1P) & 0x0F) && n) {
- *destP = *source1P + *source2P;
- source1P++;
- source2P++;
- destP++;
- n--;
- }
-
- // Now the source1P address is aligned and start to apply SSE.
- int group = n / 4;
- __m128* pSource1;
- __m128* pSource2;
- __m128* pDest;
- __m128 source2;
- __m128 dest;
-
- bool source2Aligned = !(reinterpret_cast<size_t>(source2P) & 0x0F);
- bool destAligned = !(reinterpret_cast<size_t>(destP) & 0x0F);
-
- if (source2Aligned && destAligned) { // all aligned
- while (group--) {
- pSource1 = reinterpret_cast<__m128*>(const_cast<float*>(source1P));
- pSource2 = reinterpret_cast<__m128*>(const_cast<float*>(source2P));
- pDest = reinterpret_cast<__m128*>(destP);
- *pDest = _mm_add_ps(*pSource1, *pSource2);
-
- source1P += 4;
- source2P += 4;
- destP += 4;
- }
-
- } else if (source2Aligned && !destAligned) { // source2 aligned but dest not aligned
- while (group--) {
- pSource1 = reinterpret_cast<__m128*>(const_cast<float*>(source1P));
- pSource2 = reinterpret_cast<__m128*>(const_cast<float*>(source2P));
- dest = _mm_add_ps(*pSource1, *pSource2);
- _mm_storeu_ps(destP, dest);
-
- source1P += 4;
- source2P += 4;
- destP += 4;
- }
-
- } else if (!source2Aligned && destAligned) { // source2 not aligned but dest aligned
- while (group--) {
- pSource1 = reinterpret_cast<__m128*>(const_cast<float*>(source1P));
- source2 = _mm_loadu_ps(source2P);
- pDest = reinterpret_cast<__m128*>(destP);
- *pDest = _mm_add_ps(*pSource1, source2);
-
- source1P += 4;
- source2P += 4;
- destP += 4;
- }
- } else if (!source2Aligned && !destAligned) { // both source2 and dest not aligned
- while (group--) {
- pSource1 = reinterpret_cast<__m128*>(const_cast<float*>(source1P));
- source2 = _mm_loadu_ps(source2P);
- dest = _mm_add_ps(*pSource1, source2);
- _mm_storeu_ps(destP, dest);
-
- source1P += 4;
- source2P += 4;
- destP += 4;
- }
- }
-
- // Non-SSE handling for remaining frames which is less than 4.
- n %= 4;
- while (n) {
- *destP = *source1P + *source2P;
- source1P++;
- source2P++;
- destP++;
- n--;
- }
- } else { // if strides are not 1, rollback to normal algorithm
-#elif HAVE(ARM_NEON_INTRINSICS)
- if ((sourceStride1 ==1) && (sourceStride2 == 1) && (destStride == 1)) {
- int tailFrames = n % 4;
- const float* endP = destP + n - tailFrames;
-
- while (destP < endP) {
- float32x4_t source1 = vld1q_f32(source1P);
- float32x4_t source2 = vld1q_f32(source2P);
- vst1q_f32(destP, vaddq_f32(source1, source2));
-
- source1P += 4;
- source2P += 4;
- destP += 4;
- }
- n = tailFrames;
- }
-#endif
- while (n--) {
- *destP = *source1P + *source2P;
- source1P += sourceStride1;
- source2P += sourceStride2;
- destP += destStride;
- }
-#ifdef __SSE2__
- }
-#endif
-}
-
-void vmul(const float* source1P, int sourceStride1, const float* source2P, int sourceStride2, float* destP, int destStride, size_t framesToProcess)
-{
-
- int n = framesToProcess;
-
-#ifdef __SSE2__
- if ((sourceStride1 == 1) && (sourceStride2 == 1) && (destStride == 1)) {
- // If the source1P address is not 16-byte aligned, the first several frames (at most three) should be processed separately.
- while ((reinterpret_cast<uintptr_t>(source1P) & 0x0F) && n) {
- *destP = *source1P * *source2P;
- source1P++;
- source2P++;
- destP++;
- n--;
- }
-
- // Now the source1P address aligned and start to apply SSE.
- int tailFrames = n % 4;
- const float* endP = destP + n - tailFrames;
- __m128 pSource1;
- __m128 pSource2;
- __m128 dest;
-
- bool source2Aligned = !(reinterpret_cast<uintptr_t>(source2P) & 0x0F);
- bool destAligned = !(reinterpret_cast<uintptr_t>(destP) & 0x0F);
-
-#define SSE2_MULT(loadInstr, storeInstr) \
- while (destP < endP) \
- { \
- pSource1 = _mm_load_ps(source1P); \
- pSource2 = _mm_##loadInstr##_ps(source2P); \
- dest = _mm_mul_ps(pSource1, pSource2); \
- _mm_##storeInstr##_ps(destP, dest); \
- source1P += 4; \
- source2P += 4; \
- destP += 4; \
- }
-
- if (source2Aligned && destAligned) // Both aligned.
- SSE2_MULT(load, store)
- else if (source2Aligned && !destAligned) // Source2 is aligned but dest not.
- SSE2_MULT(load, storeu)
- else if (!source2Aligned && destAligned) // Dest is aligned but source2 not.
- SSE2_MULT(loadu, store)
- else // Neither aligned.
- SSE2_MULT(loadu, storeu)
-
- n = tailFrames;
- }
-#elif HAVE(ARM_NEON_INTRINSICS)
- if ((sourceStride1 ==1) && (sourceStride2 == 1) && (destStride == 1)) {
- int tailFrames = n % 4;
- const float* endP = destP + n - tailFrames;
-
- while (destP < endP) {
- float32x4_t source1 = vld1q_f32(source1P);
- float32x4_t source2 = vld1q_f32(source2P);
- vst1q_f32(destP, vmulq_f32(source1, source2));
-
- source1P += 4;
- source2P += 4;
- destP += 4;
- }
- n = tailFrames;
- }
-#endif
- while (n) {
- *destP = *source1P * *source2P;
- source1P += sourceStride1;
- source2P += sourceStride2;
- destP += destStride;
- n--;
- }
-}
-
-void zvmul(const float* real1P, const float* imag1P, const float* real2P, const float* imag2P, float* realDestP, float* imagDestP, size_t framesToProcess)
-{
- unsigned i = 0;
-#ifdef __SSE2__
- // Only use the SSE optimization in the very common case that all addresses are 16-byte aligned.
- // Otherwise, fall through to the scalar code below.
- if (!(reinterpret_cast<uintptr_t>(real1P) & 0x0F)
- && !(reinterpret_cast<uintptr_t>(imag1P) & 0x0F)
- && !(reinterpret_cast<uintptr_t>(real2P) & 0x0F)
- && !(reinterpret_cast<uintptr_t>(imag2P) & 0x0F)
- && !(reinterpret_cast<uintptr_t>(realDestP) & 0x0F)
- && !(reinterpret_cast<uintptr_t>(imagDestP) & 0x0F)) {
-
- unsigned endSize = framesToProcess - framesToProcess % 4;
- while (i < endSize) {
- __m128 real1 = _mm_load_ps(real1P + i);
- __m128 real2 = _mm_load_ps(real2P + i);
- __m128 imag1 = _mm_load_ps(imag1P + i);
- __m128 imag2 = _mm_load_ps(imag2P + i);
- __m128 real = _mm_mul_ps(real1, real2);
- real = _mm_sub_ps(real, _mm_mul_ps(imag1, imag2));
- __m128 imag = _mm_mul_ps(real1, imag2);
- imag = _mm_add_ps(imag, _mm_mul_ps(imag1, real2));
- _mm_store_ps(realDestP + i, real);
- _mm_store_ps(imagDestP + i, imag);
- i += 4;
- }
- }
-#elif HAVE(ARM_NEON_INTRINSICS)
- unsigned endSize = framesToProcess - framesToProcess % 4;
- while (i < endSize) {
- float32x4_t real1 = vld1q_f32(real1P + i);
- float32x4_t real2 = vld1q_f32(real2P + i);
- float32x4_t imag1 = vld1q_f32(imag1P + i);
- float32x4_t imag2 = vld1q_f32(imag2P + i);
-
- float32x4_t realResult = vmlsq_f32(vmulq_f32(real1, real2), imag1, imag2);
- float32x4_t imagResult = vmlaq_f32(vmulq_f32(real1, imag2), imag1, real2);
-
- vst1q_f32(realDestP + i, realResult);
- vst1q_f32(imagDestP + i, imagResult);
-
- i += 4;
- }
-#endif
- for (; i < framesToProcess; ++i) {
- // Read and compute result before storing them, in case the
- // destination is the same as one of the sources.
- float realResult = real1P[i] * real2P[i] - imag1P[i] * imag2P[i];
- float imagResult = real1P[i] * imag2P[i] + imag1P[i] * real2P[i];
-
- realDestP[i] = realResult;
- imagDestP[i] = imagResult;
- }
-}
-
-void vsvesq(const float* sourceP, int sourceStride, float* sumP, size_t framesToProcess)
-{
- int n = framesToProcess;
- float sum = 0;
-
-#ifdef __SSE2__
- if (sourceStride == 1) {
- // If the sourceP address is not 16-byte aligned, the first several frames (at most three) should be processed separately.
- while ((reinterpret_cast<uintptr_t>(sourceP) & 0x0F) && n) {
- float sample = *sourceP;
- sum += sample * sample;
- sourceP++;
- n--;
- }
-
- // Now the sourceP is aligned, use SSE.
- int tailFrames = n % 4;
- const float* endP = sourceP + n - tailFrames;
- __m128 source;
- __m128 mSum = _mm_setzero_ps();
-
- while (sourceP < endP) {
- source = _mm_load_ps(sourceP);
- source = _mm_mul_ps(source, source);
- mSum = _mm_add_ps(mSum, source);
- sourceP += 4;
- }
-
- // Summarize the SSE results.
- const float* groupSumP = reinterpret_cast<float*>(&mSum);
- sum += groupSumP[0] + groupSumP[1] + groupSumP[2] + groupSumP[3];
-
- n = tailFrames;
- }
-#elif HAVE(ARM_NEON_INTRINSICS)
- if (sourceStride == 1) {
- int tailFrames = n % 4;
- const float* endP = sourceP + n - tailFrames;
-
- float32x4_t fourSum = vdupq_n_f32(0);
- while (sourceP < endP) {
- float32x4_t source = vld1q_f32(sourceP);
- fourSum = vmlaq_f32(fourSum, source, source);
- sourceP += 4;
- }
- float32x2_t twoSum = vadd_f32(vget_low_f32(fourSum), vget_high_f32(fourSum));
-
- float groupSum[2];
- vst1_f32(groupSum, twoSum);
- sum += groupSum[0] + groupSum[1];
-
- n = tailFrames;
- }
-#endif
-
- while (n--) {
- float sample = *sourceP;
- sum += sample * sample;
- sourceP += sourceStride;
- }
-
- ASSERT(sumP);
- *sumP = sum;
-}
-
-void vmaxmgv(const float* sourceP, int sourceStride, float* maxP, size_t framesToProcess)
-{
- int n = framesToProcess;
- float max = 0;
-
-#ifdef __SSE2__
- if (sourceStride == 1) {
- // If the sourceP address is not 16-byte aligned, the first several frames (at most three) should be processed separately.
- while ((reinterpret_cast<uintptr_t>(sourceP) & 0x0F) && n) {
- max = std::max(max, fabsf(*sourceP));
- sourceP++;
- n--;
- }
-
- // Now the sourceP is aligned, use SSE.
- int tailFrames = n % 4;
- const float* endP = sourceP + n - tailFrames;
- __m128 source;
- __m128 mMax = _mm_setzero_ps();
- int mask = 0x7FFFFFFF;
- __m128 mMask = _mm_set1_ps(*reinterpret_cast<float*>(&mask));
-
- while (sourceP < endP) {
- source = _mm_load_ps(sourceP);
- // Calculate the absolute value by anding source with mask, the sign bit is set to 0.
- source = _mm_and_ps(source, mMask);
- mMax = _mm_max_ps(mMax, source);
- sourceP += 4;
- }
-
- // Get max from the SSE results.
- const float* groupMaxP = reinterpret_cast<float*>(&mMax);
- max = std::max(max, groupMaxP[0]);
- max = std::max(max, groupMaxP[1]);
- max = std::max(max, groupMaxP[2]);
- max = std::max(max, groupMaxP[3]);
-
- n = tailFrames;
- }
-#elif HAVE(ARM_NEON_INTRINSICS)
- if (sourceStride == 1) {
- int tailFrames = n % 4;
- const float* endP = sourceP + n - tailFrames;
-
- float32x4_t fourMax = vdupq_n_f32(0);
- while (sourceP < endP) {
- float32x4_t source = vld1q_f32(sourceP);
- fourMax = vmaxq_f32(fourMax, vabsq_f32(source));
- sourceP += 4;
- }
- float32x2_t twoMax = vmax_f32(vget_low_f32(fourMax), vget_high_f32(fourMax));
-
- float groupMax[2];
- vst1_f32(groupMax, twoMax);
- max = std::max(groupMax[0], groupMax[1]);
-
- n = tailFrames;
- }
-#endif
-
- while (n--) {
- max = std::max(max, fabsf(*sourceP));
- sourceP += sourceStride;
- }
-
- ASSERT(maxP);
- *maxP = max;
-}
-
-void vclip(const float* sourceP, int sourceStride, const float* lowThresholdP, const float* highThresholdP, float* destP, int destStride, size_t framesToProcess)
-{
- int n = framesToProcess;
- float lowThreshold = *lowThresholdP;
- float highThreshold = *highThresholdP;
-
- // FIXME: Optimize for SSE2.
-#if HAVE(ARM_NEON_INTRINSICS)
- if ((sourceStride == 1) && (destStride == 1)) {
- int tailFrames = n % 4;
- const float* endP = destP + n - tailFrames;
-
- float32x4_t low = vdupq_n_f32(lowThreshold);
- float32x4_t high = vdupq_n_f32(highThreshold);
- while (destP < endP) {
- float32x4_t source = vld1q_f32(sourceP);
- vst1q_f32(destP, vmaxq_f32(vminq_f32(source, high), low));
- sourceP += 4;
- destP += 4;
- }
- n = tailFrames;
- }
-#endif
- while (n--) {
- *destP = std::max(std::min(*sourceP, highThreshold), lowThreshold);
- sourceP += sourceStride;
- destP += destStride;
- }
-}
-
-#endif // OS(MACOSX)
-
-} // namespace VectorMath
-
-} // namespace WebCore
-
-#endif // ENABLE(WEB_AUDIO)
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/VectorMath.h b/chromium/third_party/WebKit/Source/core/platform/audio/VectorMath.h
deleted file mode 100644
index 863bc4be75e..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/VectorMath.h
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Copyright (C) 2010, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef VectorMath_h
-#define VectorMath_h
-
-// Defines the interface for several vector math functions whose implementation will ideally be optimized.
-
-namespace WebCore {
-
-namespace VectorMath {
-
-// Vector scalar multiply and then add.
-void vsma(const float* sourceP, int sourceStride, const float* scale, float* destP, int destStride, size_t framesToProcess);
-
-void vsmul(const float* sourceP, int sourceStride, const float* scale, float* destP, int destStride, size_t framesToProcess);
-void vadd(const float* source1P, int sourceStride1, const float* source2P, int sourceStride2, float* destP, int destStride, size_t framesToProcess);
-
-// Finds the maximum magnitude of a float vector.
-void vmaxmgv(const float* sourceP, int sourceStride, float* maxP, size_t framesToProcess);
-
-// Sums the squares of a float vector's elements.
-void vsvesq(const float* sourceP, int sourceStride, float* sumP, size_t framesToProcess);
-
-// For an element-by-element multiply of two float vectors.
-void vmul(const float* source1P, int sourceStride1, const float* source2P, int sourceStride2, float* destP, int destStride, size_t framesToProcess);
-
-// Multiplies two complex vectors.
-void zvmul(const float* real1P, const float* imag1P, const float* real2P, const float* imag2P, float* realDestP, float* imagDestP, size_t framesToProcess);
-
-// Copies elements while clipping values to the threshold inputs.
-void vclip(const float* sourceP, int sourceStride, const float* lowThresholdP, const float* highThresholdP, float* destP, int destStride, size_t framesToProcess);
-
-} // namespace VectorMath
-
-} // namespace WebCore
-
-#endif // VectorMath_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/ZeroPole.cpp b/chromium/third_party/WebKit/Source/core/platform/audio/ZeroPole.cpp
deleted file mode 100644
index 86daf4e3562..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/ZeroPole.cpp
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#if ENABLE(WEB_AUDIO)
-
-#include "core/platform/audio/ZeroPole.h"
-
-#include "core/platform/audio/DenormalDisabler.h"
-
-namespace WebCore {
-
-void ZeroPole::process(const float *source, float *destination, unsigned framesToProcess)
-{
- float zero = m_zero;
- float pole = m_pole;
-
- // Gain compensation to make 0dB @ 0Hz
- const float k1 = 1 / (1 - zero);
- const float k2 = 1 - pole;
-
- // Member variables to locals.
- float lastX = m_lastX;
- float lastY = m_lastY;
-
- while (framesToProcess--) {
- float input = *source++;
-
- // Zero
- float output1 = k1 * (input - zero * lastX);
- lastX = input;
-
- // Pole
- float output2 = k2 * output1 + pole * lastY;
- lastY = output2;
-
- *destination++ = output2;
- }
-
- // Locals to member variables. Flush denormals here so we don't
- // slow down the inner loop above.
- m_lastX = DenormalDisabler::flushDenormalFloatToZero(lastX);
- m_lastY = DenormalDisabler::flushDenormalFloatToZero(lastY);
-}
-
-} // namespace WebCore
-
-#endif // ENABLE(WEB_AUDIO)
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/ZeroPole.h b/chromium/third_party/WebKit/Source/core/platform/audio/ZeroPole.h
deleted file mode 100644
index a6de4e2f21b..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/ZeroPole.h
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ZeroPole_h
-#define ZeroPole_h
-
-namespace WebCore {
-
-// ZeroPole is a simple filter with one zero and one pole.
-
-class ZeroPole {
-public:
- ZeroPole()
- : m_zero(0)
- , m_pole(0)
- , m_lastX(0)
- , m_lastY(0)
- {
- }
-
- void process(const float *source, float *destination, unsigned framesToProcess);
-
- // Reset filter state.
- void reset() { m_lastX = 0; m_lastY = 0; }
-
- void setZero(float zero) { m_zero = zero; }
- void setPole(float pole) { m_pole = pole; }
-
- float zero() const { return m_zero; }
- float pole() const { return m_pole; }
-
-private:
- float m_zero;
- float m_pole;
- float m_lastX;
- float m_lastY;
-};
-
-} // namespace WebCore
-
-#endif // ZeroPole_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/chromium/AudioBusChromium.cpp b/chromium/third_party/WebKit/Source/core/platform/audio/chromium/AudioBusChromium.cpp
deleted file mode 100644
index 08bab5a1b27..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/chromium/AudioBusChromium.cpp
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * Copyright (C) 2010, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#if ENABLE(WEB_AUDIO)
-
-#include "core/platform/audio/AudioBus.h"
-
-#include "public/platform/Platform.h"
-#include "public/platform/WebAudioBus.h"
-
-namespace WebCore {
-
-PassRefPtr<AudioBus> decodeAudioFileData(const char* data, size_t size, double sampleRate)
-{
- WebKit::WebAudioBus webAudioBus;
- if (WebKit::Platform::current()->loadAudioResource(&webAudioBus, data, size, sampleRate))
- return webAudioBus.release();
- return 0;
-}
-
-PassRefPtr<AudioBus> AudioBus::loadPlatformResource(const char* name, float sampleRate)
-{
- const WebKit::WebData& resource = WebKit::Platform::current()->loadResource(name);
- if (resource.isEmpty())
- return 0;
-
- // FIXME: the sampleRate parameter is ignored. It should be removed from the API.
- RefPtr<AudioBus> audioBus = decodeAudioFileData(resource.data(), resource.size(), sampleRate);
-
- if (!audioBus.get())
- return 0;
-
- // If the bus is already at the requested sample-rate then return as is.
- if (audioBus->sampleRate() == sampleRate)
- return audioBus;
-
- return AudioBus::createBySampleRateConverting(audioBus.get(), false, sampleRate);
-}
-
-PassRefPtr<AudioBus> createBusFromInMemoryAudioFile(const void* data, size_t dataSize, bool mixToMono, float sampleRate)
-{
- // FIXME: the sampleRate parameter is ignored. It should be removed from the API.
- RefPtr<AudioBus> audioBus = decodeAudioFileData(static_cast<const char*>(data), dataSize, sampleRate);
- if (!audioBus.get())
- return 0;
-
- // If the bus needs no conversion then return as is.
- if ((!mixToMono || audioBus->numberOfChannels() == 1) && audioBus->sampleRate() == sampleRate)
- return audioBus;
-
- return AudioBus::createBySampleRateConverting(audioBus.get(), mixToMono, sampleRate);
-}
-
-} // namespace WebCore
-
-#endif // ENABLE(WEB_AUDIO)
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/chromium/AudioDestinationChromium.cpp b/chromium/third_party/WebKit/Source/core/platform/audio/chromium/AudioDestinationChromium.cpp
deleted file mode 100644
index 42ead256002..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/chromium/AudioDestinationChromium.cpp
+++ /dev/null
@@ -1,180 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#if ENABLE(WEB_AUDIO)
-
-#include "core/platform/audio/chromium/AudioDestinationChromium.h"
-
-#include "core/platform/audio/AudioFIFO.h"
-#include "core/platform/audio/AudioPullFIFO.h"
-#include "public/platform/Platform.h"
-
-namespace WebCore {
-
-// Buffer size at which the web audio engine will render.
-const unsigned renderBufferSize = 128;
-
-// Size of the FIFO
-const size_t fifoSize = 8192;
-
-// Factory method: Chromium-implementation
-PassOwnPtr<AudioDestination> AudioDestination::create(AudioIOCallback& callback, const String& inputDeviceId, unsigned numberOfInputChannels, unsigned numberOfOutputChannels, float sampleRate)
-{
- return adoptPtr(new AudioDestinationChromium(callback, inputDeviceId, numberOfInputChannels, numberOfOutputChannels, sampleRate));
-}
-
-AudioDestinationChromium::AudioDestinationChromium(AudioIOCallback& callback, const String& inputDeviceId, unsigned numberOfInputChannels, unsigned numberOfOutputChannels, float sampleRate)
- : m_callback(callback)
- , m_numberOfOutputChannels(numberOfOutputChannels)
- , m_inputBus(AudioBus::create(numberOfInputChannels, renderBufferSize))
- , m_renderBus(AudioBus::create(numberOfOutputChannels, renderBufferSize, false))
- , m_sampleRate(sampleRate)
- , m_isPlaying(false)
-{
- // Use the optimal buffer size recommended by the audio backend.
- m_callbackBufferSize = WebKit::Platform::current()->audioHardwareBufferSize();
-
-#if OS(ANDROID)
- // The optimum low-latency hardware buffer size is usually too small on Android for WebAudio to
- // render without glitching. So, if it is small, use a larger size. If it was already large, use
- // the requested size.
- //
- // Since WebAudio renders in 128-frame blocks, the small buffer sizes (144 for a Galaxy Nexus),
- // cause significant processing jitter. Sometimes multiple blocks will processed, but other
- // times will not be since the FIFO can satisfy the request. By using a larger
- // callbackBufferSize, we smooth out the jitter.
- const size_t kSmallBufferSize = 1024;
- const size_t kDefaultCallbackBufferSize = 2048;
-
- if (m_callbackBufferSize <= kSmallBufferSize)
- m_callbackBufferSize = kDefaultCallbackBufferSize;
-#endif
-
- // Quick exit if the requested size is too large.
- ASSERT(m_callbackBufferSize + renderBufferSize <= fifoSize);
- if (m_callbackBufferSize + renderBufferSize > fifoSize)
- return;
-
- m_audioDevice = adoptPtr(WebKit::Platform::current()->createAudioDevice(m_callbackBufferSize, numberOfInputChannels, numberOfOutputChannels, sampleRate, this, inputDeviceId));
- ASSERT(m_audioDevice);
-
- // Create a FIFO to handle the possibility of the callback size
- // not being a multiple of the render size. If the FIFO already
- // contains enough data, the data will be provided directly.
- // Otherwise, the FIFO will call the provider enough times to
- // satisfy the request for data.
- m_fifo = adoptPtr(new AudioPullFIFO(*this, numberOfOutputChannels, fifoSize, renderBufferSize));
-
- // Input buffering.
- m_inputFifo = adoptPtr(new AudioFIFO(numberOfInputChannels, fifoSize));
-
- // If the callback size does not match the render size, then we need to buffer some
- // extra silence for the input. Otherwise, we can over-consume the input FIFO.
- if (m_callbackBufferSize != renderBufferSize) {
- // FIXME: handle multi-channel input and don't hard-code to stereo.
- RefPtr<AudioBus> silence = AudioBus::create(2, renderBufferSize);
- m_inputFifo->push(silence.get());
- }
-}
-
-AudioDestinationChromium::~AudioDestinationChromium()
-{
- stop();
-}
-
-void AudioDestinationChromium::start()
-{
- if (!m_isPlaying && m_audioDevice) {
- m_audioDevice->start();
- m_isPlaying = true;
- }
-}
-
-void AudioDestinationChromium::stop()
-{
- if (m_isPlaying && m_audioDevice) {
- m_audioDevice->stop();
- m_isPlaying = false;
- }
-}
-
-float AudioDestination::hardwareSampleRate()
-{
- return static_cast<float>(WebKit::Platform::current()->audioHardwareSampleRate());
-}
-
-unsigned long AudioDestination::maxChannelCount()
-{
- return static_cast<float>(WebKit::Platform::current()->audioHardwareOutputChannels());
-}
-
-void AudioDestinationChromium::render(const WebKit::WebVector<float*>& sourceData, const WebKit::WebVector<float*>& audioData, size_t numberOfFrames)
-{
- bool isNumberOfChannelsGood = audioData.size() == m_numberOfOutputChannels;
- if (!isNumberOfChannelsGood) {
- ASSERT_NOT_REACHED();
- return;
- }
-
- bool isBufferSizeGood = numberOfFrames == m_callbackBufferSize;
- if (!isBufferSizeGood) {
- ASSERT_NOT_REACHED();
- return;
- }
-
- // Buffer optional live input.
- if (sourceData.size() >= 2) {
- // FIXME: handle multi-channel input and don't hard-code to stereo.
- RefPtr<AudioBus> wrapperBus = AudioBus::create(2, numberOfFrames, false);
- wrapperBus->setChannelMemory(0, sourceData[0], numberOfFrames);
- wrapperBus->setChannelMemory(1, sourceData[1], numberOfFrames);
- m_inputFifo->push(wrapperBus.get());
- }
-
- for (unsigned i = 0; i < m_numberOfOutputChannels; ++i)
- m_renderBus->setChannelMemory(i, audioData[i], numberOfFrames);
-
- m_fifo->consume(m_renderBus.get(), numberOfFrames);
-}
-
-void AudioDestinationChromium::provideInput(AudioBus* bus, size_t framesToProcess)
-{
- AudioBus* sourceBus = 0;
- if (m_inputFifo->framesInFifo() >= framesToProcess) {
- m_inputFifo->consume(m_inputBus.get(), framesToProcess);
- sourceBus = m_inputBus.get();
- }
-
- m_callback.render(sourceBus, bus, framesToProcess);
-}
-
-} // namespace WebCore
-
-#endif // ENABLE(WEB_AUDIO)
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/chromium/AudioDestinationChromium.h b/chromium/third_party/WebKit/Source/core/platform/audio/chromium/AudioDestinationChromium.h
deleted file mode 100644
index 253556a3e70..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/chromium/AudioDestinationChromium.h
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef AudioDestinationChromium_h
-#define AudioDestinationChromium_h
-
-#include "core/platform/audio/AudioBus.h"
-#include "core/platform/audio/AudioDestination.h"
-#include "core/platform/audio/AudioIOCallback.h"
-#include "core/platform/audio/AudioSourceProvider.h"
-#include "public/platform/WebAudioDevice.h"
-#include "public/platform/WebVector.h"
-
-namespace WebCore {
-
-class AudioFIFO;
-class AudioPullFIFO;
-
-// An AudioDestination using Chromium's audio system
-
-class AudioDestinationChromium : public AudioDestination, public WebKit::WebAudioDevice::RenderCallback, public AudioSourceProvider {
-public:
- AudioDestinationChromium(AudioIOCallback&, const String& inputDeviceId, unsigned numberOfInputChannels, unsigned numberOfOutputChannels, float sampleRate);
- virtual ~AudioDestinationChromium();
-
- virtual void start();
- virtual void stop();
- bool isPlaying() { return m_isPlaying; }
-
- float sampleRate() const { return m_sampleRate; }
-
- // WebKit::WebAudioDevice::RenderCallback
- virtual void render(const WebKit::WebVector<float*>& sourceData, const WebKit::WebVector<float*>& audioData, size_t numberOfFrames);
-
- // WebCore::AudioSourceProvider
- virtual void provideInput(AudioBus*, size_t framesToProcess);
-
-private:
- AudioIOCallback& m_callback;
- unsigned m_numberOfOutputChannels;
- RefPtr<AudioBus> m_inputBus;
- RefPtr<AudioBus> m_renderBus;
- float m_sampleRate;
- bool m_isPlaying;
- OwnPtr<WebKit::WebAudioDevice> m_audioDevice;
- size_t m_callbackBufferSize;
-
- OwnPtr<AudioFIFO> m_inputFifo;
- OwnPtr<AudioPullFIFO> m_fifo;
-};
-
-} // namespace WebCore
-
-#endif // AudioDestinationChromium_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/chromium/FFTFrameOpenMAXDLAndroid.cpp b/chromium/third_party/WebKit/Source/core/platform/audio/chromium/FFTFrameOpenMAXDLAndroid.cpp
deleted file mode 100644
index 6e501edc979..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/chromium/FFTFrameOpenMAXDLAndroid.cpp
+++ /dev/null
@@ -1,208 +0,0 @@
-/* Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#if ENABLE(WEB_AUDIO)
-
-#if OS(ANDROID) && USE(WEBAUDIO_OPENMAX_DL_FFT)
-
-#include "core/platform/audio/FFTFrame.h"
-
-#include "core/platform/audio/AudioArray.h"
-#include "core/platform/audio/VectorMath.h"
-#include "dl/sp/api/armSP.h"
-#include "dl/sp/api/omxSP.h"
-
-#include "wtf/MathExtras.h"
-
-namespace WebCore {
-
-const unsigned kMaxFFTPow2Size = 15;
-
-// Normal constructor: allocates for a given fftSize.
-FFTFrame::FFTFrame(unsigned fftSize)
- : m_FFTSize(fftSize)
- , m_log2FFTSize(static_cast<unsigned>(log2(fftSize)))
- , m_forwardContext(0)
- , m_inverseContext(0)
- , m_complexData(fftSize)
- , m_realData(fftSize / 2)
- , m_imagData(fftSize / 2)
-{
- // We only allow power of two.
- ASSERT(1UL << m_log2FFTSize == m_FFTSize);
-
- m_forwardContext = contextForSize(m_log2FFTSize);
- m_inverseContext = contextForSize(m_log2FFTSize);
-}
-
-// Creates a blank/empty frame (interpolate() must later be called).
-FFTFrame::FFTFrame()
- : m_FFTSize(0)
- , m_log2FFTSize(0)
- , m_forwardContext(0)
- , m_inverseContext(0)
-{
-}
-
-// Copy constructor.
-FFTFrame::FFTFrame(const FFTFrame& frame)
- : m_FFTSize(frame.m_FFTSize)
- , m_log2FFTSize(frame.m_log2FFTSize)
- , m_forwardContext(0)
- , m_inverseContext(0)
- , m_complexData(frame.m_FFTSize)
- , m_realData(frame.m_FFTSize / 2)
- , m_imagData(frame.m_FFTSize / 2)
-{
- m_forwardContext = contextForSize(m_log2FFTSize);
- m_inverseContext = contextForSize(m_log2FFTSize);
-
- // Copy/setup frame data.
- unsigned nbytes = sizeof(float) * (m_FFTSize / 2);
- memcpy(realData(), frame.realData(), nbytes);
- memcpy(imagData(), frame.imagData(), nbytes);
-}
-
-void FFTFrame::initialize()
-{
-}
-
-void FFTFrame::cleanup()
-{
-}
-
-FFTFrame::~FFTFrame()
-{
- if (m_forwardContext)
- free(m_forwardContext);
- if (m_inverseContext)
- free(m_inverseContext);
-}
-
-void FFTFrame::multiply(const FFTFrame& frame)
-{
- FFTFrame& frame1 = *this;
- FFTFrame& frame2 = const_cast<FFTFrame&>(frame);
-
- float* realP1 = frame1.realData();
- float* imagP1 = frame1.imagData();
- const float* realP2 = frame2.realData();
- const float* imagP2 = frame2.imagData();
-
- unsigned halfSize = fftSize() / 2;
- float real0 = realP1[0];
- float imag0 = imagP1[0];
-
- VectorMath::zvmul(realP1, imagP1, realP2, imagP2, realP1, imagP1, halfSize);
-
- // Multiply the packed DC/nyquist component
- realP1[0] = real0 * realP2[0];
- imagP1[0] = imag0 * imagP2[0];
-}
-
-void FFTFrame::doFFT(const float* data)
-{
- ASSERT(m_forwardContext);
-
- if (m_forwardContext) {
- AudioFloatArray complexFFT(m_FFTSize + 2);
-
- omxSP_FFTFwd_RToCCS_F32_Sfs(data, complexFFT.data(), m_forwardContext);
-
- unsigned len = m_FFTSize / 2;
-
- // Split FFT data into real and imaginary arrays.
- const float* c = complexFFT.data();
- float* real = m_realData.data();
- float* imag = m_imagData.data();
- for (unsigned k = 1; k < len; ++k) {
- int index = 2 * k;
- real[k] = c[index];
- imag[k] = c[index + 1];
- }
- real[0] = c[0];
- imag[0] = c[m_FFTSize];
- }
-}
-
-void FFTFrame::doInverseFFT(float* data)
-{
- ASSERT(m_inverseContext);
-
- if (m_inverseContext) {
- AudioFloatArray fftDataArray(m_FFTSize + 2);
-
- unsigned len = m_FFTSize / 2;
-
- // Pack the real and imaginary data into the complex array format
- float* fftData = fftDataArray.data();
- const float* real = m_realData.data();
- const float* imag = m_imagData.data();
- for (unsigned k = 1; k < len; ++k) {
- int index = 2 * k;
- fftData[index] = real[k];
- fftData[index + 1] = imag[k];
- }
- fftData[0] = real[0];
- fftData[1] = 0;
- fftData[m_FFTSize] = imag[0];
- fftData[m_FFTSize + 1] = 0;
-
- omxSP_FFTInv_CCSToR_F32_Sfs(fftData, data, m_inverseContext);
- }
-}
-
-float* FFTFrame::realData() const
-{
- return const_cast<float*>(m_realData.data());
-}
-
-float* FFTFrame::imagData() const
-{
- return const_cast<float*>(m_imagData.data());
-}
-
-OMXFFTSpec_R_F32* FFTFrame::contextForSize(unsigned log2FFTSize)
-{
- ASSERT(log2FFTSize);
- ASSERT(log2FFTSize <= kMaxFFTPow2Size);
- int bufSize;
- OMXResult status = omxSP_FFTGetBufSize_R_F32(log2FFTSize, &bufSize);
-
- if (status == OMX_Sts_NoErr) {
- OMXFFTSpec_R_F32* context = static_cast<OMXFFTSpec_R_F32*>(malloc(bufSize));
- omxSP_FFTInit_R_F32(context, log2FFTSize);
- return context;
- }
-
- return 0;
-}
-
-} // namespace WebCore
-
-#endif // #if OS(ANDROID) && !USE(WEBAUDIO_OPENMAX_DL_FFT)
-
-#endif // ENABLE(WEB_AUDIO)
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/ffmpeg/FFTFrameFFMPEG.cpp b/chromium/third_party/WebKit/Source/core/platform/audio/ffmpeg/FFTFrameFFMPEG.cpp
deleted file mode 100644
index 59f182f9e42..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/ffmpeg/FFTFrameFFMPEG.cpp
+++ /dev/null
@@ -1,253 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-// FFTFrame implementation using FFmpeg's RDFT algorithm,
-// suitable for use on Windows and Linux.
-
-#include "config.h"
-
-#if ENABLE(WEB_AUDIO)
-
-#if USE(WEBAUDIO_FFMPEG)
-
-#include "core/platform/audio/FFTFrame.h"
-
-#include "core/platform/audio/VectorMath.h"
-
-extern "C" {
- #include <libavcodec/avfft.h>
-}
-
-#include "wtf/MathExtras.h"
-
-namespace {
-
-struct FFTComplexProxy {
- int16_t re;
- int16_t im;
-};
-
-struct FFTContextProxy {
- int nbits;
- int inverse;
- uint16_t* revtab;
- FFTComplexProxy* tmpBuf;
- int mdctSize;
- int mdctBits;
- void* tcos;
- void* tsin;
- void (*fftPermute)();
- void (*fftCalc)();
- void (*imdctCalc)();
- void (*imdctHalf)();
- void (*mdctCalc)();
- void (*mdctCalcw)();
- int fftPermutation;
- int mdctPermutation;
-};
-
-struct RDFTContextProxy {
- int nbits;
- int inverse;
- int signConvention;
- const void* tcos;
- const void* tsin;
- FFTContextProxy fft;
- void (*rdft_calc)();
-};
-
-}
-
-namespace WebCore {
-
-const int kMaxFFTPow2Size = 24;
-
-// Normal constructor: allocates for a given fftSize.
-FFTFrame::FFTFrame(unsigned fftSize)
- : m_FFTSize(fftSize)
- , m_log2FFTSize(static_cast<unsigned>(log2(fftSize)))
- , m_forwardContext(0)
- , m_inverseContext(0)
- , m_complexData(fftSize)
- , m_realData(fftSize / 2)
- , m_imagData(fftSize / 2)
-{
- // We only allow power of two.
- ASSERT(1UL << m_log2FFTSize == m_FFTSize);
-
- m_forwardContext = contextForSize(fftSize, DFT_R2C);
- m_inverseContext = contextForSize(fftSize, IDFT_C2R);
-}
-
-// Creates a blank/empty frame (interpolate() must later be called).
-FFTFrame::FFTFrame()
- : m_FFTSize(0)
- , m_log2FFTSize(0)
- , m_forwardContext(0)
- , m_inverseContext(0)
-{
-}
-
-// Copy constructor.
-FFTFrame::FFTFrame(const FFTFrame& frame)
- : m_FFTSize(frame.m_FFTSize)
- , m_log2FFTSize(frame.m_log2FFTSize)
- , m_forwardContext(0)
- , m_inverseContext(0)
- , m_complexData(frame.m_FFTSize)
- , m_realData(frame.m_FFTSize / 2)
- , m_imagData(frame.m_FFTSize / 2)
-{
- m_forwardContext = contextForSize(m_FFTSize, DFT_R2C);
- m_inverseContext = contextForSize(m_FFTSize, IDFT_C2R);
-
- // Copy/setup frame data.
- unsigned nbytes = sizeof(float) * (m_FFTSize / 2);
- memcpy(realData(), frame.realData(), nbytes);
- memcpy(imagData(), frame.imagData(), nbytes);
-}
-
-void FFTFrame::initialize()
-{
-}
-
-void FFTFrame::cleanup()
-{
-}
-
-FFTFrame::~FFTFrame()
-{
- av_rdft_end(m_forwardContext);
- av_rdft_end(m_inverseContext);
-}
-
-void FFTFrame::multiply(const FFTFrame& frame)
-{
- FFTFrame& frame1 = *this;
- FFTFrame& frame2 = const_cast<FFTFrame&>(frame);
-
- float* realP1 = frame1.realData();
- float* imagP1 = frame1.imagData();
- const float* realP2 = frame2.realData();
- const float* imagP2 = frame2.imagData();
-
- unsigned halfSize = fftSize() / 2;
- float real0 = realP1[0];
- float imag0 = imagP1[0];
-
- VectorMath::zvmul(realP1, imagP1, realP2, imagP2, realP1, imagP1, halfSize);
-
- // Multiply the packed DC/nyquist component
- realP1[0] = real0 * realP2[0];
- imagP1[0] = imag0 * imagP2[0];
-
- // Scale accounts the peculiar scaling of vecLib on the Mac.
- // This ensures the right scaling all the way back to inverse FFT.
- // FIXME: if we change the scaling on the Mac then this scale
- // factor will need to change too.
- float scale = 0.5f;
-
- VectorMath::vsmul(realP1, 1, &scale, realP1, 1, halfSize);
- VectorMath::vsmul(imagP1, 1, &scale, imagP1, 1, halfSize);
-}
-
-void FFTFrame::doFFT(const float* data)
-{
- // Copy since processing is in-place.
- float* p = m_complexData.data();
- memcpy(p, data, sizeof(float) * m_FFTSize);
-
- // Compute Forward transform.
- av_rdft_calc(m_forwardContext, p);
-
- // De-interleave to separate real and complex arrays.
- int len = m_FFTSize / 2;
-
- // FIXME: see above comment in multiply() about scaling.
- const float scale = 2.0f;
-
- for (int i = 0; i < len; ++i) {
- int baseComplexIndex = 2 * i;
- // m_realData[0] is the DC component and m_imagData[0] is the nyquist component
- // since the interleaved complex data is packed.
- m_realData[i] = scale * p[baseComplexIndex];
- m_imagData[i] = scale * p[baseComplexIndex + 1];
- }
-}
-
-void FFTFrame::doInverseFFT(float* data)
-{
- // Prepare interleaved data.
- float* interleavedData = getUpToDateComplexData();
-
- // Compute inverse transform.
- av_rdft_calc(m_inverseContext, interleavedData);
-
- // Scale so that a forward then inverse FFT yields exactly the original data.
- const float scale = 1.0 / m_FFTSize;
- VectorMath::vsmul(interleavedData, 1, &scale, data, 1, m_FFTSize);
-}
-
-float* FFTFrame::realData() const
-{
- return const_cast<float*>(m_realData.data());
-}
-
-float* FFTFrame::imagData() const
-{
- return const_cast<float*>(m_imagData.data());
-}
-
-float* FFTFrame::getUpToDateComplexData()
-{
- // FIXME: if we can't completely get rid of this method, SSE
- // optimization could be considered if it shows up hot on profiles.
- int len = m_FFTSize / 2;
- for (int i = 0; i < len; ++i) {
- int baseComplexIndex = 2 * i;
- m_complexData[baseComplexIndex] = m_realData[i];
- m_complexData[baseComplexIndex + 1] = m_imagData[i];
- }
- return const_cast<float*>(m_complexData.data());
-}
-
-RDFTContext* FFTFrame::contextForSize(unsigned fftSize, int trans)
-{
- // FIXME: This is non-optimal. Ideally, we'd like to share the contexts for FFTFrames of the same size.
- // But FFmpeg's RDFT uses a scratch buffer inside the context and so they are not thread-safe.
- // We could improve this by sharing the FFTFrames on a per-thread basis.
- ASSERT(fftSize);
- int pow2size = static_cast<int>(log2(fftSize));
- ASSERT(pow2size < kMaxFFTPow2Size);
-
- RDFTContext* context = av_rdft_init(pow2size, (RDFTransformType)trans);
- return context;
-}
-
-} // namespace WebCore
-
-#endif // !OS(MACOSX) && USE(WEBAUDIO_FFMPEG)
-
-#endif // ENABLE(WEB_AUDIO)
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/ipp/FFTFrameIPP.cpp b/chromium/third_party/WebKit/Source/core/platform/audio/ipp/FFTFrameIPP.cpp
deleted file mode 100644
index fa25a9f60aa..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/ipp/FFTFrameIPP.cpp
+++ /dev/null
@@ -1,189 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- * Copyright (C) 2012 Intel Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-// FFTFrame implementation using Intel IPP's DFT algorithm,
-// suitable for use on Linux.
-
-#include "config.h"
-
-#if ENABLE(WEB_AUDIO)
-
-#if USE(WEBAUDIO_IPP)
-
-#include "core/platform/audio/FFTFrame.h"
-
-#include "core/platform/audio/VectorMath.h"
-
-#include "wtf/MathExtras.h"
-
-namespace WebCore {
-
-const unsigned maximumFFTPower2Size = 24;
-
-// Normal constructor: allocates for a given fftSize.
-FFTFrame::FFTFrame(unsigned fftSize)
- : m_FFTSize(fftSize)
- , m_log2FFTSize(static_cast<unsigned>(log2(fftSize)))
- , m_complexData(fftSize)
- , m_realData(fftSize / 2)
- , m_imagData(fftSize / 2)
-{
- // We only allow power of two.
- ASSERT(1UL << m_log2FFTSize == m_FFTSize);
- ASSERT(m_log2FFTSize <= maximumFFTPower2Size);
-
- ippsDFTInitAlloc_R_32f(&m_DFTSpec, m_FFTSize, IPP_FFT_NODIV_BY_ANY, ippAlgHintFast);
- int bufferSize = 0;
- ippsDFTGetBufSize_R_32f(m_DFTSpec, &bufferSize);
- m_buffer = ippsMalloc_8u(bufferSize);
-}
-
-// Creates a blank/empty frame (interpolate() must later be called).
-FFTFrame::FFTFrame()
- : m_FFTSize(0)
- , m_log2FFTSize(0)
-{
-}
-
-// Copy constructor.
-FFTFrame::FFTFrame(const FFTFrame& frame)
- : m_FFTSize(frame.m_FFTSize)
- , m_log2FFTSize(frame.m_log2FFTSize)
- , m_complexData(frame.m_FFTSize)
- , m_realData(frame.m_FFTSize / 2)
- , m_imagData(frame.m_FFTSize / 2)
-{
- ippsDFTInitAlloc_R_32f(&m_DFTSpec, m_FFTSize, IPP_FFT_NODIV_BY_ANY, ippAlgHintFast);
- int bufferSize = 0;
- ippsDFTGetBufSize_R_32f(m_DFTSpec, &bufferSize);
- m_buffer = ippsMalloc_8u(bufferSize);
-
- // Copy/setup frame data.
- unsigned numberOfBytes = sizeof(float) * m_FFTSize;
- memcpy(realData(), frame.realData(), numberOfBytes);
- memcpy(imagData(), frame.imagData(), numberOfBytes);
-}
-
-void FFTFrame::initialize()
-{
-}
-
-void FFTFrame::cleanup()
-{
-}
-
-FFTFrame::~FFTFrame()
-{
- ippsFree(m_buffer);
- ippsDFTFree_R_32f(m_DFTSpec);
-}
-
-void FFTFrame::multiply(const FFTFrame& frame)
-{
- FFTFrame& frame1 = *this;
- FFTFrame& frame2 = const_cast<FFTFrame&>(frame);
-
- float* realP1 = frame1.realData();
- float* imagP1 = frame1.imagData();
- const float* realP2 = frame2.realData();
- const float* imagP2 = frame2.imagData();
-
- unsigned halfSize = fftSize() / 2;
- float real0 = realP1[0];
- float imag0 = imagP1[0];
-
- VectorMath::zvmul(realP1, imagP1, realP2, imagP2, realP1, imagP1, halfSize);
-
- // Multiply the packed DC/nyquist component
- realP1[0] = real0 * realP2[0];
- imagP1[0] = imag0 * imagP2[0];
-
- // Scale accounts the peculiar scaling of vecLib on the Mac.
- // This ensures the right scaling all the way back to inverse FFT.
- // FIXME: if we change the scaling on the Mac then this scale
- // factor will need to change too.
- float scale = 0.5f;
-
- VectorMath::vsmul(realP1, 1, &scale, realP1, 1, halfSize);
- VectorMath::vsmul(imagP1, 1, &scale, imagP1, 1, halfSize);
-}
-
-void FFTFrame::doFFT(const float* data)
-{
- Ipp32f* complexP = m_complexData.data();
-
- // Compute Forward transform to perm format.
- ippsDFTFwd_RToPerm_32f(reinterpret_cast<Ipp32f*>(const_cast<float*>(data)), complexP, m_DFTSpec, m_buffer);
-
- const Ipp32f scale = 2.0f;
-
- ippsMulC_32f_I(scale, complexP, m_FFTSize);
-
- Ipp32f* realP = m_realData.data();
- Ipp32f* imagP = m_imagData.data();
- ippsCplxToReal_32fc(reinterpret_cast<Ipp32fc*>(complexP), realP, imagP, m_FFTSize >> 1);
-}
-
-void FFTFrame::doInverseFFT(float* data)
-{
- Ipp32f* complexP = getUpToDateComplexData();
-
- // Compute inverse transform.
- ippsDFTInv_PermToR_32f(complexP, reinterpret_cast<Ipp32f*>(data), m_DFTSpec, m_buffer);
-
- // Scale so that a forward then inverse FFT yields exactly the original data.
- const float scale = 1.0 / (2 * m_FFTSize);
-
- ippsMulC_32f_I(scale, reinterpret_cast<Ipp32f*>(data), m_FFTSize);
-}
-
-float* FFTFrame::realData() const
-{
- return const_cast<float*>(m_realData.data());
-}
-
-float* FFTFrame::imagData() const
-{
- return const_cast<float*>(m_imagData.data());
-}
-
-float* FFTFrame::getUpToDateComplexData()
-{
- int len = m_FFTSize >> 1;
- // Merge the real and imagimary vectors to complex vector.
- Ipp32f* realP = m_realData.data();
- Ipp32f* imagP = m_imagData.data();
- Ipp32fc* complexP = reinterpret_cast<Ipp32fc*>(m_complexData.data());
- ippsRealToCplx_32f(realP, imagP, complexP, len);
-
- return const_cast<float*>(m_complexData.data());
-}
-
-} // namespace WebCore
-
-#endif // USE(WEBAUDIO_IPP)
-
-#endif // ENABLE(WEB_AUDIO)
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/mac/FFTFrameMac.cpp b/chromium/third_party/WebKit/Source/core/platform/audio/mac/FFTFrameMac.cpp
deleted file mode 100644
index 344f953ac6a..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/mac/FFTFrameMac.cpp
+++ /dev/null
@@ -1,193 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-// Mac OS X - specific FFTFrame implementation
-
-#include "config.h"
-
-#if ENABLE(WEB_AUDIO)
-
-#if OS(MACOSX) && !USE(WEBAUDIO_FFMPEG)
-
-#include "core/platform/audio/FFTFrame.h"
-
-#include "core/platform/audio/VectorMath.h"
-
-namespace WebCore {
-
-const int kMaxFFTPow2Size = 24;
-
-FFTSetup* FFTFrame::fftSetups = 0;
-
-// Normal constructor: allocates for a given fftSize
-FFTFrame::FFTFrame(unsigned fftSize)
- : m_realData(fftSize)
- , m_imagData(fftSize)
-{
- m_FFTSize = fftSize;
- m_log2FFTSize = static_cast<unsigned>(log2(fftSize));
-
- // We only allow power of two
- ASSERT(1UL << m_log2FFTSize == m_FFTSize);
-
- // Lazily create and share fftSetup with other frames
- m_FFTSetup = fftSetupForSize(fftSize);
-
- // Setup frame data
- m_frame.realp = m_realData.data();
- m_frame.imagp = m_imagData.data();
-}
-
-// Creates a blank/empty frame (interpolate() must later be called)
-FFTFrame::FFTFrame()
- : m_realData(0)
- , m_imagData(0)
-{
- // Later will be set to correct values when interpolate() is called
- m_frame.realp = 0;
- m_frame.imagp = 0;
-
- m_FFTSize = 0;
- m_log2FFTSize = 0;
-}
-
-// Copy constructor
-FFTFrame::FFTFrame(const FFTFrame& frame)
- : m_FFTSize(frame.m_FFTSize)
- , m_log2FFTSize(frame.m_log2FFTSize)
- , m_FFTSetup(frame.m_FFTSetup)
- , m_realData(frame.m_FFTSize)
- , m_imagData(frame.m_FFTSize)
-{
- // Setup frame data
- m_frame.realp = m_realData.data();
- m_frame.imagp = m_imagData.data();
-
- // Copy/setup frame data
- unsigned nbytes = sizeof(float) * m_FFTSize;
- memcpy(realData(), frame.m_frame.realp, nbytes);
- memcpy(imagData(), frame.m_frame.imagp, nbytes);
-}
-
-FFTFrame::~FFTFrame()
-{
-}
-
-void FFTFrame::multiply(const FFTFrame& frame)
-{
- FFTFrame& frame1 = *this;
- const FFTFrame& frame2 = frame;
-
- float* realP1 = frame1.realData();
- float* imagP1 = frame1.imagData();
- const float* realP2 = frame2.realData();
- const float* imagP2 = frame2.imagData();
-
- unsigned halfSize = m_FFTSize / 2;
- float real0 = realP1[0];
- float imag0 = imagP1[0];
-
- // Complex multiply
- VectorMath::zvmul(realP1, imagP1, realP2, imagP2, realP1, imagP1, halfSize);
-
- // Multiply the packed DC/nyquist component
- realP1[0] = real0 * realP2[0];
- imagP1[0] = imag0 * imagP2[0];
-
- // Scale accounts for vecLib's peculiar scaling
- // This ensures the right scaling all the way back to inverse FFT
- float scale = 0.5f;
-
- VectorMath::vsmul(realP1, 1, &scale, realP1, 1, halfSize);
- VectorMath::vsmul(imagP1, 1, &scale, imagP1, 1, halfSize);
-}
-
-void FFTFrame::doFFT(const float* data)
-{
- vDSP_ctoz((DSPComplex*)data, 2, &m_frame, 1, m_FFTSize / 2);
- vDSP_fft_zrip(m_FFTSetup, &m_frame, 1, m_log2FFTSize, FFT_FORWARD);
-}
-
-void FFTFrame::doInverseFFT(float* data)
-{
- vDSP_fft_zrip(m_FFTSetup, &m_frame, 1, m_log2FFTSize, FFT_INVERSE);
- vDSP_ztoc(&m_frame, 1, (DSPComplex*)data, 2, m_FFTSize / 2);
-
- // Do final scaling so that x == IFFT(FFT(x))
- float scale = 0.5f / m_FFTSize;
- vDSP_vsmul(data, 1, &scale, data, 1, m_FFTSize);
-}
-
-FFTSetup FFTFrame::fftSetupForSize(unsigned fftSize)
-{
- if (!fftSetups) {
- fftSetups = (FFTSetup*)malloc(sizeof(FFTSetup) * kMaxFFTPow2Size);
- memset(fftSetups, 0, sizeof(FFTSetup) * kMaxFFTPow2Size);
- }
-
- int pow2size = static_cast<int>(log2(fftSize));
- ASSERT(pow2size < kMaxFFTPow2Size);
- if (!fftSetups[pow2size])
- fftSetups[pow2size] = vDSP_create_fftsetup(pow2size, FFT_RADIX2);
-
- return fftSetups[pow2size];
-}
-
-void FFTFrame::initialize()
-{
-}
-
-void FFTFrame::cleanup()
-{
- if (!fftSetups)
- return;
-
- for (int i = 0; i < kMaxFFTPow2Size; ++i) {
- if (fftSetups[i])
- vDSP_destroy_fftsetup(fftSetups[i]);
- }
-
- free(fftSetups);
- fftSetups = 0;
-}
-
-float* FFTFrame::realData() const
-{
- return m_frame.realp;
-}
-
-float* FFTFrame::imagData() const
-{
- return m_frame.imagp;
-}
-
-} // namespace WebCore
-
-#endif // #if OS(MACOSX) && !USE(WEBAUDIO_FFMPEG)
-
-#endif // ENABLE(WEB_AUDIO)
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/Composite.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/Composite.wav
deleted file mode 100644
index fab198d7727..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/Composite.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T000_P000.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T000_P000.wav
deleted file mode 100644
index 57f2ef32eb2..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T000_P000.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T000_P015.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T000_P015.wav
deleted file mode 100644
index 3ecea337867..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T000_P015.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T000_P030.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T000_P030.wav
deleted file mode 100644
index 7320802ac8f..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T000_P030.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T000_P045.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T000_P045.wav
deleted file mode 100644
index 1a10d9ac44f..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T000_P045.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T000_P060.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T000_P060.wav
deleted file mode 100644
index 9b12c228e11..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T000_P060.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T000_P075.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T000_P075.wav
deleted file mode 100644
index 3153bb86af0..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T000_P075.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T000_P090.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T000_P090.wav
deleted file mode 100644
index 3282da981f8..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T000_P090.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T000_P315.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T000_P315.wav
deleted file mode 100644
index b9998521a6a..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T000_P315.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T000_P330.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T000_P330.wav
deleted file mode 100644
index 53a03b68818..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T000_P330.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T000_P345.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T000_P345.wav
deleted file mode 100644
index 16d57668e30..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T000_P345.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T015_P000.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T015_P000.wav
deleted file mode 100644
index 3788e169e10..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T015_P000.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T015_P015.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T015_P015.wav
deleted file mode 100644
index ad2efb6d336..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T015_P015.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T015_P030.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T015_P030.wav
deleted file mode 100644
index ee86702b30e..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T015_P030.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T015_P045.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T015_P045.wav
deleted file mode 100644
index 98ff82e045f..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T015_P045.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T015_P060.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T015_P060.wav
deleted file mode 100644
index 98ff82e045f..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T015_P060.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T015_P075.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T015_P075.wav
deleted file mode 100644
index 98ff82e045f..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T015_P075.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T015_P090.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T015_P090.wav
deleted file mode 100644
index 98ff82e045f..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T015_P090.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T015_P315.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T015_P315.wav
deleted file mode 100644
index 10bdf78573e..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T015_P315.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T015_P330.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T015_P330.wav
deleted file mode 100644
index c8398a48f69..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T015_P330.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T015_P345.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T015_P345.wav
deleted file mode 100644
index 82b92a81bc4..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T015_P345.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T030_P000.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T030_P000.wav
deleted file mode 100644
index 8b8714ce4bc..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T030_P000.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T030_P015.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T030_P015.wav
deleted file mode 100644
index 882efd482a1..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T030_P015.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T030_P030.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T030_P030.wav
deleted file mode 100644
index abd99e64eff..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T030_P030.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T030_P045.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T030_P045.wav
deleted file mode 100644
index 28765be4f13..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T030_P045.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T030_P060.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T030_P060.wav
deleted file mode 100644
index 42c144505a4..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T030_P060.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T030_P075.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T030_P075.wav
deleted file mode 100644
index 42c144505a4..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T030_P075.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T030_P090.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T030_P090.wav
deleted file mode 100644
index 42c144505a4..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T030_P090.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T030_P315.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T030_P315.wav
deleted file mode 100644
index 99b00f748bd..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T030_P315.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T030_P330.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T030_P330.wav
deleted file mode 100644
index f81bee2a940..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T030_P330.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T030_P345.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T030_P345.wav
deleted file mode 100644
index 139d0cb9afc..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T030_P345.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T045_P000.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T045_P000.wav
deleted file mode 100644
index 68b7b4fda79..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T045_P000.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T045_P015.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T045_P015.wav
deleted file mode 100644
index d6773aec50d..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T045_P015.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T045_P030.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T045_P030.wav
deleted file mode 100644
index 9e786bbcf9e..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T045_P030.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T045_P045.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T045_P045.wav
deleted file mode 100644
index fbef2f384f4..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T045_P045.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T045_P060.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T045_P060.wav
deleted file mode 100644
index fbef2f384f4..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T045_P060.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T045_P075.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T045_P075.wav
deleted file mode 100644
index fbef2f384f4..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T045_P075.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T045_P090.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T045_P090.wav
deleted file mode 100644
index fbef2f384f4..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T045_P090.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T045_P315.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T045_P315.wav
deleted file mode 100644
index 3c53b767047..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T045_P315.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T045_P330.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T045_P330.wav
deleted file mode 100644
index e4524c0eb13..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T045_P330.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T045_P345.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T045_P345.wav
deleted file mode 100644
index ff12535f799..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T045_P345.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T060_P000.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T060_P000.wav
deleted file mode 100644
index 5bb1b175390..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T060_P000.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T060_P015.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T060_P015.wav
deleted file mode 100644
index 47e0209e654..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T060_P015.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T060_P030.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T060_P030.wav
deleted file mode 100644
index 536b4ac9056..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T060_P030.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T060_P045.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T060_P045.wav
deleted file mode 100644
index 05152ad862d..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T060_P045.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T060_P060.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T060_P060.wav
deleted file mode 100644
index 221637b4f9c..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T060_P060.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T060_P075.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T060_P075.wav
deleted file mode 100644
index 7d6d07f4635..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T060_P075.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T060_P090.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T060_P090.wav
deleted file mode 100644
index 7d6d07f4635..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T060_P090.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T060_P315.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T060_P315.wav
deleted file mode 100644
index a4eca78f849..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T060_P315.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T060_P330.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T060_P330.wav
deleted file mode 100644
index 37393c21a10..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T060_P330.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T060_P345.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T060_P345.wav
deleted file mode 100644
index 3d56e26c958..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T060_P345.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T075_P000.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T075_P000.wav
deleted file mode 100644
index 2159f3debc7..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T075_P000.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T075_P015.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T075_P015.wav
deleted file mode 100644
index 8b689f6c477..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T075_P015.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T075_P030.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T075_P030.wav
deleted file mode 100644
index 9ee8ac5894d..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T075_P030.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T075_P045.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T075_P045.wav
deleted file mode 100644
index 88124e91464..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T075_P045.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T075_P060.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T075_P060.wav
deleted file mode 100644
index 88124e91464..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T075_P060.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T075_P075.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T075_P075.wav
deleted file mode 100644
index 88124e91464..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T075_P075.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T075_P090.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T075_P090.wav
deleted file mode 100644
index 88124e91464..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T075_P090.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T075_P315.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T075_P315.wav
deleted file mode 100644
index 59441a617e7..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T075_P315.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T075_P330.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T075_P330.wav
deleted file mode 100644
index 7cac0f5bbca..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T075_P330.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T075_P345.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T075_P345.wav
deleted file mode 100644
index dc28d64c7fb..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T075_P345.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T090_P000.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T090_P000.wav
deleted file mode 100644
index ae7e5833817..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T090_P000.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T090_P015.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T090_P015.wav
deleted file mode 100644
index 509449e984c..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T090_P015.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T090_P030.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T090_P030.wav
deleted file mode 100644
index e23b20ca54a..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T090_P030.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T090_P045.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T090_P045.wav
deleted file mode 100644
index cf247b98b9e..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T090_P045.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T090_P060.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T090_P060.wav
deleted file mode 100644
index f49d52049a8..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T090_P060.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T090_P075.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T090_P075.wav
deleted file mode 100644
index f49d52049a8..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T090_P075.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T090_P090.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T090_P090.wav
deleted file mode 100644
index f49d52049a8..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T090_P090.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T090_P315.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T090_P315.wav
deleted file mode 100644
index e5472f1fc8a..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T090_P315.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T090_P330.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T090_P330.wav
deleted file mode 100644
index 8e1af836997..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T090_P330.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T090_P345.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T090_P345.wav
deleted file mode 100644
index c477193a1cb..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T090_P345.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T105_P000.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T105_P000.wav
deleted file mode 100644
index 4236e085f07..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T105_P000.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T105_P015.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T105_P015.wav
deleted file mode 100644
index 2461fb0783e..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T105_P015.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T105_P030.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T105_P030.wav
deleted file mode 100644
index 11d549becef..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T105_P030.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T105_P045.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T105_P045.wav
deleted file mode 100644
index 0aa100e3d89..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T105_P045.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T105_P060.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T105_P060.wav
deleted file mode 100644
index 0aa100e3d89..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T105_P060.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T105_P075.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T105_P075.wav
deleted file mode 100644
index 0aa100e3d89..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T105_P075.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T105_P090.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T105_P090.wav
deleted file mode 100644
index 0aa100e3d89..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T105_P090.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T105_P315.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T105_P315.wav
deleted file mode 100644
index 572e602991b..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T105_P315.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T105_P330.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T105_P330.wav
deleted file mode 100644
index 7f41da37c32..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T105_P330.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T105_P345.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T105_P345.wav
deleted file mode 100644
index d0101b81005..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T105_P345.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T120_P000.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T120_P000.wav
deleted file mode 100644
index 800fbd783bb..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T120_P000.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T120_P015.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T120_P015.wav
deleted file mode 100644
index 9b35e726464..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T120_P015.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T120_P030.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T120_P030.wav
deleted file mode 100644
index bb58c4eb749..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T120_P030.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T120_P045.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T120_P045.wav
deleted file mode 100644
index 8963e3e56d4..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T120_P045.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T120_P060.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T120_P060.wav
deleted file mode 100644
index 22241ee9a79..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T120_P060.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T120_P075.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T120_P075.wav
deleted file mode 100644
index 9e4fee09e80..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T120_P075.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T120_P090.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T120_P090.wav
deleted file mode 100644
index 9e4fee09e80..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T120_P090.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T120_P315.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T120_P315.wav
deleted file mode 100644
index 95976c6492d..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T120_P315.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T120_P330.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T120_P330.wav
deleted file mode 100644
index 8fc55f12bc1..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T120_P330.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T120_P345.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T120_P345.wav
deleted file mode 100644
index eeeb70276c9..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T120_P345.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T135_P000.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T135_P000.wav
deleted file mode 100644
index 1847d8d26d6..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T135_P000.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T135_P015.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T135_P015.wav
deleted file mode 100644
index 52e812c8b69..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T135_P015.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T135_P030.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T135_P030.wav
deleted file mode 100644
index 32ca3447152..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T135_P030.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T135_P045.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T135_P045.wav
deleted file mode 100644
index 3de60c8737f..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T135_P045.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T135_P060.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T135_P060.wav
deleted file mode 100644
index 3de60c8737f..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T135_P060.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T135_P075.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T135_P075.wav
deleted file mode 100644
index 3de60c8737f..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T135_P075.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T135_P090.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T135_P090.wav
deleted file mode 100644
index 3de60c8737f..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T135_P090.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T135_P315.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T135_P315.wav
deleted file mode 100644
index 2668e41d0fe..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T135_P315.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T135_P330.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T135_P330.wav
deleted file mode 100644
index e69670baacf..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T135_P330.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T135_P345.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T135_P345.wav
deleted file mode 100644
index 1cc48eed3f0..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T135_P345.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T150_P000.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T150_P000.wav
deleted file mode 100644
index 252968b67d1..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T150_P000.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T150_P015.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T150_P015.wav
deleted file mode 100644
index 50aff3c13de..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T150_P015.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T150_P030.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T150_P030.wav
deleted file mode 100644
index 3abd6e89001..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T150_P030.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T150_P045.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T150_P045.wav
deleted file mode 100644
index 3f0d5ef936b..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T150_P045.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T150_P060.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T150_P060.wav
deleted file mode 100644
index 616f760d522..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T150_P060.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T150_P075.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T150_P075.wav
deleted file mode 100644
index 616f760d522..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T150_P075.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T150_P090.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T150_P090.wav
deleted file mode 100644
index 616f760d522..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T150_P090.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T150_P315.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T150_P315.wav
deleted file mode 100644
index bfb603225d9..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T150_P315.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T150_P330.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T150_P330.wav
deleted file mode 100644
index 1983cdbfd3c..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T150_P330.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T150_P345.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T150_P345.wav
deleted file mode 100644
index 27c07628a6a..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T150_P345.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T165_P000.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T165_P000.wav
deleted file mode 100644
index b04391b9fb8..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T165_P000.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T165_P015.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T165_P015.wav
deleted file mode 100644
index 5955612bbe1..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T165_P015.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T165_P030.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T165_P030.wav
deleted file mode 100644
index af5d83a5da2..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T165_P030.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T165_P045.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T165_P045.wav
deleted file mode 100644
index a592f717ffb..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T165_P045.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T165_P060.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T165_P060.wav
deleted file mode 100644
index a592f717ffb..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T165_P060.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T165_P075.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T165_P075.wav
deleted file mode 100644
index a592f717ffb..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T165_P075.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T165_P090.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T165_P090.wav
deleted file mode 100644
index a592f717ffb..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T165_P090.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T165_P315.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T165_P315.wav
deleted file mode 100644
index a985aa15c4d..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T165_P315.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T165_P330.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T165_P330.wav
deleted file mode 100644
index a8b83d1e336..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T165_P330.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T165_P345.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T165_P345.wav
deleted file mode 100644
index 7e649a3af1a..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T165_P345.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T180_P000.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T180_P000.wav
deleted file mode 100644
index b74985c9446..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T180_P000.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T180_P015.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T180_P015.wav
deleted file mode 100644
index e112ee07048..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T180_P015.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T180_P030.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T180_P030.wav
deleted file mode 100644
index ac842ccb070..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T180_P030.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T180_P045.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T180_P045.wav
deleted file mode 100644
index 95c3a6df07e..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T180_P045.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T180_P060.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T180_P060.wav
deleted file mode 100644
index 610eedba585..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T180_P060.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T180_P075.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T180_P075.wav
deleted file mode 100644
index d4a57bfb573..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T180_P075.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T180_P090.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T180_P090.wav
deleted file mode 100644
index d4a57bfb573..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T180_P090.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T180_P315.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T180_P315.wav
deleted file mode 100644
index bd6e4f8d85a..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T180_P315.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T180_P330.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T180_P330.wav
deleted file mode 100644
index 7d4be6f1e89..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T180_P330.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T180_P345.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T180_P345.wav
deleted file mode 100644
index b7ef81a9d0a..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T180_P345.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T195_P000.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T195_P000.wav
deleted file mode 100644
index 0c4af2a8613..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T195_P000.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T195_P015.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T195_P015.wav
deleted file mode 100644
index dd7a5056faa..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T195_P015.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T195_P030.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T195_P030.wav
deleted file mode 100644
index e1690496cae..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T195_P030.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T195_P045.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T195_P045.wav
deleted file mode 100644
index 49008a067ca..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T195_P045.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T195_P060.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T195_P060.wav
deleted file mode 100644
index 49008a067ca..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T195_P060.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T195_P075.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T195_P075.wav
deleted file mode 100644
index 49008a067ca..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T195_P075.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T195_P090.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T195_P090.wav
deleted file mode 100644
index 49008a067ca..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T195_P090.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T195_P315.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T195_P315.wav
deleted file mode 100644
index 1e7d478cd3b..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T195_P315.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T195_P330.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T195_P330.wav
deleted file mode 100644
index 2a77d74d887..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T195_P330.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T195_P345.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T195_P345.wav
deleted file mode 100644
index 843b92865f2..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T195_P345.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T210_P000.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T210_P000.wav
deleted file mode 100644
index 770af176a34..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T210_P000.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T210_P015.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T210_P015.wav
deleted file mode 100644
index 437a1c6d342..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T210_P015.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T210_P030.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T210_P030.wav
deleted file mode 100644
index f0d9d8e3f28..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T210_P030.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T210_P045.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T210_P045.wav
deleted file mode 100644
index cd4ae55a071..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T210_P045.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T210_P060.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T210_P060.wav
deleted file mode 100644
index 7dd5a1a2ec4..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T210_P060.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T210_P075.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T210_P075.wav
deleted file mode 100644
index 7dd5a1a2ec4..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T210_P075.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T210_P090.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T210_P090.wav
deleted file mode 100644
index 7dd5a1a2ec4..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T210_P090.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T210_P315.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T210_P315.wav
deleted file mode 100644
index bfac19d6615..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T210_P315.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T210_P330.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T210_P330.wav
deleted file mode 100644
index 8b3e086ff7d..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T210_P330.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T210_P345.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T210_P345.wav
deleted file mode 100644
index 8b4da465b3a..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T210_P345.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T225_P000.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T225_P000.wav
deleted file mode 100644
index b6d47036a33..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T225_P000.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T225_P015.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T225_P015.wav
deleted file mode 100644
index 0ff35e93a58..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T225_P015.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T225_P030.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T225_P030.wav
deleted file mode 100644
index e934c7837b6..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T225_P030.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T225_P045.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T225_P045.wav
deleted file mode 100644
index c931e3ca2eb..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T225_P045.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T225_P060.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T225_P060.wav
deleted file mode 100644
index c931e3ca2eb..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T225_P060.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T225_P075.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T225_P075.wav
deleted file mode 100644
index c931e3ca2eb..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T225_P075.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T225_P090.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T225_P090.wav
deleted file mode 100644
index c931e3ca2eb..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T225_P090.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T225_P315.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T225_P315.wav
deleted file mode 100644
index f9999666454..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T225_P315.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T225_P330.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T225_P330.wav
deleted file mode 100644
index d95859015bb..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T225_P330.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T225_P345.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T225_P345.wav
deleted file mode 100644
index ac062606820..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T225_P345.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T240_P000.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T240_P000.wav
deleted file mode 100644
index b720ed16b84..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T240_P000.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T240_P015.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T240_P015.wav
deleted file mode 100644
index b48852a7e80..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T240_P015.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T240_P030.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T240_P030.wav
deleted file mode 100644
index 92c7ef04f09..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T240_P030.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T240_P045.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T240_P045.wav
deleted file mode 100644
index 2d5ff652de0..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T240_P045.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T240_P060.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T240_P060.wav
deleted file mode 100644
index 07dcfde6afd..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T240_P060.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T240_P075.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T240_P075.wav
deleted file mode 100644
index 283e250334a..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T240_P075.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T240_P090.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T240_P090.wav
deleted file mode 100644
index 283e250334a..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T240_P090.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T240_P315.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T240_P315.wav
deleted file mode 100644
index b99ad7de245..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T240_P315.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T240_P330.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T240_P330.wav
deleted file mode 100644
index 48869156a22..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T240_P330.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T240_P345.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T240_P345.wav
deleted file mode 100644
index c93283343eb..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T240_P345.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T255_P000.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T255_P000.wav
deleted file mode 100644
index b204deff4ed..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T255_P000.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T255_P015.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T255_P015.wav
deleted file mode 100644
index fa48113c022..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T255_P015.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T255_P030.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T255_P030.wav
deleted file mode 100644
index 2e2de705aeb..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T255_P030.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T255_P045.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T255_P045.wav
deleted file mode 100644
index 685f102d379..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T255_P045.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T255_P060.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T255_P060.wav
deleted file mode 100644
index 685f102d379..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T255_P060.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T255_P075.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T255_P075.wav
deleted file mode 100644
index 685f102d379..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T255_P075.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T255_P090.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T255_P090.wav
deleted file mode 100644
index 685f102d379..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T255_P090.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T255_P315.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T255_P315.wav
deleted file mode 100644
index c7cce6ecce3..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T255_P315.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T255_P330.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T255_P330.wav
deleted file mode 100644
index 93a6b8a7808..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T255_P330.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T255_P345.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T255_P345.wav
deleted file mode 100644
index efc72bc5ee1..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T255_P345.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T270_P000.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T270_P000.wav
deleted file mode 100644
index 8f490785cb4..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T270_P000.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T270_P015.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T270_P015.wav
deleted file mode 100644
index 96510f7b262..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T270_P015.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T270_P030.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T270_P030.wav
deleted file mode 100644
index 60b84f49072..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T270_P030.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T270_P045.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T270_P045.wav
deleted file mode 100644
index ec995e6c06b..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T270_P045.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T270_P060.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T270_P060.wav
deleted file mode 100644
index e287d0e4a42..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T270_P060.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T270_P075.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T270_P075.wav
deleted file mode 100644
index e287d0e4a42..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T270_P075.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T270_P090.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T270_P090.wav
deleted file mode 100644
index e287d0e4a42..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T270_P090.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T270_P315.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T270_P315.wav
deleted file mode 100644
index 01f0921731e..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T270_P315.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T270_P330.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T270_P330.wav
deleted file mode 100644
index 380e7073c2c..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T270_P330.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T270_P345.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T270_P345.wav
deleted file mode 100644
index 124a5348a82..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T270_P345.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T285_P000.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T285_P000.wav
deleted file mode 100644
index 1a577f37f8c..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T285_P000.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T285_P015.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T285_P015.wav
deleted file mode 100644
index ce698bbd0aa..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T285_P015.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T285_P030.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T285_P030.wav
deleted file mode 100644
index 8d5134ff88f..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T285_P030.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T285_P045.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T285_P045.wav
deleted file mode 100644
index 583c6edb901..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T285_P045.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T285_P060.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T285_P060.wav
deleted file mode 100644
index 583c6edb901..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T285_P060.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T285_P075.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T285_P075.wav
deleted file mode 100644
index 583c6edb901..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T285_P075.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T285_P090.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T285_P090.wav
deleted file mode 100644
index 583c6edb901..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T285_P090.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T285_P315.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T285_P315.wav
deleted file mode 100644
index 7b1b43badb2..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T285_P315.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T285_P330.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T285_P330.wav
deleted file mode 100644
index e9ed7edc879..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T285_P330.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T285_P345.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T285_P345.wav
deleted file mode 100644
index 6ce83edf96d..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T285_P345.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T300_P000.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T300_P000.wav
deleted file mode 100644
index b4ea6bfb238..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T300_P000.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T300_P015.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T300_P015.wav
deleted file mode 100644
index 76d5b7127df..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T300_P015.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T300_P030.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T300_P030.wav
deleted file mode 100644
index 04ee0034f0b..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T300_P030.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T300_P045.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T300_P045.wav
deleted file mode 100644
index 22d74137b9d..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T300_P045.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T300_P060.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T300_P060.wav
deleted file mode 100644
index 1b35018446d..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T300_P060.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T300_P075.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T300_P075.wav
deleted file mode 100644
index 2f55df8a071..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T300_P075.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T300_P090.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T300_P090.wav
deleted file mode 100644
index 2f55df8a071..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T300_P090.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T300_P315.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T300_P315.wav
deleted file mode 100644
index 7bcc8a425ee..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T300_P315.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T300_P330.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T300_P330.wav
deleted file mode 100644
index a3bacf3a53a..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T300_P330.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T300_P345.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T300_P345.wav
deleted file mode 100644
index bdfba2dfceb..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T300_P345.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T315_P000.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T315_P000.wav
deleted file mode 100644
index 719320c0a33..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T315_P000.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T315_P015.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T315_P015.wav
deleted file mode 100644
index 5d366fc3bc7..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T315_P015.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T315_P030.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T315_P030.wav
deleted file mode 100644
index e10e88bcd1f..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T315_P030.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T315_P045.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T315_P045.wav
deleted file mode 100644
index ecb4b50ea2b..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T315_P045.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T315_P060.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T315_P060.wav
deleted file mode 100644
index ecb4b50ea2b..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T315_P060.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T315_P075.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T315_P075.wav
deleted file mode 100644
index ecb4b50ea2b..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T315_P075.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T315_P090.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T315_P090.wav
deleted file mode 100644
index ecb4b50ea2b..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T315_P090.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T315_P315.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T315_P315.wav
deleted file mode 100644
index 35c44d4082f..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T315_P315.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T315_P330.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T315_P330.wav
deleted file mode 100644
index 8fe859bfd2f..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T315_P330.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T315_P345.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T315_P345.wav
deleted file mode 100644
index 3e44b83087e..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T315_P345.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T330_P000.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T330_P000.wav
deleted file mode 100644
index e8782204a18..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T330_P000.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T330_P015.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T330_P015.wav
deleted file mode 100644
index 7628cbc9e7f..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T330_P015.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T330_P030.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T330_P030.wav
deleted file mode 100644
index 7c4430c27ea..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T330_P030.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T330_P045.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T330_P045.wav
deleted file mode 100644
index 55e3c5ec8fe..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T330_P045.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T330_P060.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T330_P060.wav
deleted file mode 100644
index 563313e9ce2..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T330_P060.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T330_P075.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T330_P075.wav
deleted file mode 100644
index 563313e9ce2..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T330_P075.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T330_P090.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T330_P090.wav
deleted file mode 100644
index 563313e9ce2..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T330_P090.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T330_P315.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T330_P315.wav
deleted file mode 100644
index 3eccc16d06d..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T330_P315.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T330_P330.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T330_P330.wav
deleted file mode 100644
index fd3f5e1f5bd..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T330_P330.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T330_P345.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T330_P345.wav
deleted file mode 100644
index 5937c5930c1..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T330_P345.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T345_P000.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T345_P000.wav
deleted file mode 100644
index 99dc851bf70..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T345_P000.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T345_P015.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T345_P015.wav
deleted file mode 100644
index 28994d57c73..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T345_P015.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T345_P030.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T345_P030.wav
deleted file mode 100644
index beb24a2357a..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T345_P030.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T345_P045.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T345_P045.wav
deleted file mode 100644
index f840c591efa..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T345_P045.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T345_P060.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T345_P060.wav
deleted file mode 100644
index f840c591efa..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T345_P060.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T345_P075.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T345_P075.wav
deleted file mode 100644
index f840c591efa..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T345_P075.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T345_P090.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T345_P090.wav
deleted file mode 100644
index f840c591efa..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T345_P090.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T345_P315.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T345_P315.wav
deleted file mode 100644
index 68baa8ea7f9..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T345_P315.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T345_P330.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T345_P330.wav
deleted file mode 100644
index 6cb01b8f463..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T345_P330.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T345_P345.wav b/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T345_P345.wav
deleted file mode 100644
index b2ae88c78af..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/audio/resources/IRC_Composite_C_R0195_T345_P345.wav
+++ /dev/null
Binary files differ
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/ChromiumDataObject.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/ChromiumDataObject.cpp
index a9a536dfcfa..afbf866911b 100644
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/ChromiumDataObject.cpp
+++ b/chromium/third_party/WebKit/Source/core/platform/chromium/ChromiumDataObject.cpp
@@ -31,28 +31,29 @@
#include "config.h"
#include "core/platform/chromium/ChromiumDataObject.h"
-#include "bindings/v8/ExceptionState.h"
-#include "bindings/v8/ExceptionStatePlaceholder.h"
-#include "core/dom/DataTransferItem.h"
-#include "core/dom/ExceptionCode.h"
-#include "core/platform/chromium/ClipboardMimeTypes.h"
-#include "core/platform/chromium/ClipboardUtilitiesChromium.h"
+#include "core/platform/Pasteboard.h"
+#include "platform/clipboard/ClipboardMimeTypes.h"
+#include "platform/clipboard/ClipboardUtilities.h"
#include "public/platform/Platform.h"
#include "public/platform/WebClipboard.h"
namespace WebCore {
-PassRefPtr<ChromiumDataObject> ChromiumDataObject::createFromPasteboard()
+PassRefPtr<ChromiumDataObject> ChromiumDataObject::createFromPasteboard(PasteMode pasteMode)
{
RefPtr<ChromiumDataObject> dataObject = create();
- uint64_t sequenceNumber = WebKit::Platform::current()->clipboard()->sequenceNumber(currentPasteboardBuffer());
+ blink::WebClipboard::Buffer buffer = Pasteboard::generalPasteboard()->buffer();
+ uint64_t sequenceNumber = blink::Platform::current()->clipboard()->sequenceNumber(buffer);
bool ignored;
- WebKit::WebVector<WebKit::WebString> webTypes = WebKit::Platform::current()->clipboard()->readAvailableTypes(currentPasteboardBuffer(), &ignored);
+ blink::WebVector<blink::WebString> webTypes = blink::Platform::current()->clipboard()->readAvailableTypes(buffer, &ignored);
ListHashSet<String> types;
for (size_t i = 0; i < webTypes.size(); ++i)
types.add(webTypes[i]);
- for (ListHashSet<String>::const_iterator it = types.begin(); it != types.end(); ++it)
+ for (ListHashSet<String>::const_iterator it = types.begin(); it != types.end(); ++it) {
+ if (pasteMode == PlainTextOnly && *it != mimeTypeTextPlain)
+ continue;
dataObject->m_itemList.append(ChromiumDataObjectItem::createFromPasteboard(*it, sequenceNumber));
+ }
return dataObject.release();
}
@@ -90,17 +91,15 @@ void ChromiumDataObject::clearAll()
m_itemList.clear();
}
-PassRefPtr<ChromiumDataObjectItem> ChromiumDataObject::add(const String& data, const String& type, ExceptionState& es)
+PassRefPtr<ChromiumDataObjectItem> ChromiumDataObject::add(const String& data, const String& type)
{
RefPtr<ChromiumDataObjectItem> item = ChromiumDataObjectItem::createFromString(type, data);
- if (!internalAddStringItem(item)) {
- es.throwDOMException(NotSupportedError);
+ if (!internalAddStringItem(item))
return 0;
- }
return item;
}
-PassRefPtr<ChromiumDataObjectItem> ChromiumDataObject::add(PassRefPtr<File> file, ScriptExecutionContext* context)
+PassRefPtr<ChromiumDataObjectItem> ChromiumDataObject::add(PassRefPtr<File> file)
{
if (!file)
return 0;
@@ -113,7 +112,7 @@ PassRefPtr<ChromiumDataObjectItem> ChromiumDataObject::add(PassRefPtr<File> file
void ChromiumDataObject::clearData(const String& type)
{
for (size_t i = 0; i < m_itemList.size(); ++i) {
- if (m_itemList[i]->kind() == DataTransferItem::kindString && m_itemList[i]->type() == type) {
+ if (m_itemList[i]->kind() == ChromiumDataObjectItem::StringKind && m_itemList[i]->type() == type) {
// Per the spec, type must be unique among all items of kind 'string'.
m_itemList.remove(i);
return;
@@ -124,7 +123,7 @@ void ChromiumDataObject::clearData(const String& type)
void ChromiumDataObject::clearAllExceptFiles()
{
for (size_t i = 0; i < m_itemList.size(); ) {
- if (m_itemList[i]->kind() != DataTransferItem::kindFile) {
+ if (m_itemList[i]->kind() != ChromiumDataObjectItem::FileKind) {
m_itemList.remove(i);
continue;
}
@@ -137,12 +136,14 @@ ListHashSet<String> ChromiumDataObject::types() const
ListHashSet<String> results;
bool containsFiles = false;
for (size_t i = 0; i < m_itemList.size(); ++i) {
- if (m_itemList[i]->kind() == DataTransferItem::kindString)
+ switch (m_itemList[i]->kind()) {
+ case ChromiumDataObjectItem::StringKind:
results.add(m_itemList[i]->type());
- else if (m_itemList[i]->kind() == DataTransferItem::kindFile)
+ break;
+ case ChromiumDataObjectItem::FileKind:
containsFiles = true;
- else
- ASSERT_NOT_REACHED();
+ break;
+ }
}
if (containsFiles)
results.add(mimeTypeFiles);
@@ -152,7 +153,7 @@ ListHashSet<String> ChromiumDataObject::types() const
String ChromiumDataObject::getData(const String& type) const
{
for (size_t i = 0; i < m_itemList.size(); ++i) {
- if (m_itemList[i]->kind() == DataTransferItem::kindString && m_itemList[i]->type() == type)
+ if (m_itemList[i]->kind() == ChromiumDataObjectItem::StringKind && m_itemList[i]->type() == type)
return m_itemList[i]->internalGetAsString();
}
return String();
@@ -161,7 +162,8 @@ String ChromiumDataObject::getData(const String& type) const
bool ChromiumDataObject::setData(const String& type, const String& data)
{
clearData(type);
- add(data, type, ASSERT_NO_EXCEPTION);
+ if (!add(data, type))
+ ASSERT_NOT_REACHED();
return true;
}
@@ -238,7 +240,7 @@ ChromiumDataObject::ChromiumDataObject(const ChromiumDataObject& other)
PassRefPtr<ChromiumDataObjectItem> ChromiumDataObject::findStringItem(const String& type) const
{
for (size_t i = 0; i < m_itemList.size(); ++i) {
- if (m_itemList[i]->kind() == DataTransferItem::kindString && m_itemList[i]->type() == type)
+ if (m_itemList[i]->kind() == ChromiumDataObjectItem::StringKind && m_itemList[i]->type() == type)
return m_itemList[i];
}
return 0;
@@ -246,9 +248,9 @@ PassRefPtr<ChromiumDataObjectItem> ChromiumDataObject::findStringItem(const Stri
bool ChromiumDataObject::internalAddStringItem(PassRefPtr<ChromiumDataObjectItem> item)
{
- ASSERT(item->kind() == DataTransferItem::kindString);
+ ASSERT(item->kind() == ChromiumDataObjectItem::StringKind);
for (size_t i = 0; i < m_itemList.size(); ++i)
- if (m_itemList[i]->kind() == DataTransferItem::kindString && m_itemList[i]->type() == item->type())
+ if (m_itemList[i]->kind() == ChromiumDataObjectItem::StringKind && m_itemList[i]->type() == item->type())
return false;
m_itemList.append(item);
@@ -257,7 +259,7 @@ bool ChromiumDataObject::internalAddStringItem(PassRefPtr<ChromiumDataObjectItem
void ChromiumDataObject::internalAddFileItem(PassRefPtr<ChromiumDataObjectItem> item)
{
- ASSERT(item->kind() == DataTransferItem::kindFile);
+ ASSERT(item->kind() == ChromiumDataObjectItem::FileKind);
m_itemList.append(item);
}
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/ChromiumDataObject.h b/chromium/third_party/WebKit/Source/core/platform/chromium/ChromiumDataObject.h
index dfb9a75d207..506952d0581 100644
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/ChromiumDataObject.h
+++ b/chromium/third_party/WebKit/Source/core/platform/chromium/ChromiumDataObject.h
@@ -31,8 +31,9 @@
#ifndef ChromiumDataObject_h
#define ChromiumDataObject_h
-#include "core/platform/Supplementable.h"
#include "core/platform/chromium/ChromiumDataObjectItem.h"
+#include "platform/PasteMode.h"
+#include "platform/Supplementable.h"
#include "wtf/ListHashSet.h"
#include "wtf/RefCounted.h"
#include "wtf/RefPtr.h"
@@ -42,7 +43,6 @@
namespace WebCore {
-class ExceptionState;
class KURL;
class SharedBuffer;
@@ -51,7 +51,7 @@ class SharedBuffer;
// of and is not specific to a platform.
class ChromiumDataObject : public RefCounted<ChromiumDataObject>, public Supplementable<ChromiumDataObject> {
public:
- static PassRefPtr<ChromiumDataObject> createFromPasteboard();
+ static PassRefPtr<ChromiumDataObject> createFromPasteboard(PasteMode);
static PassRefPtr<ChromiumDataObject> create();
PassRefPtr<ChromiumDataObject> copy() const;
@@ -62,8 +62,9 @@ public:
// FIXME: Implement V8DataTransferItemList::indexedPropertyDeleter to get this called.
void deleteItem(unsigned long index);
void clearAll();
- PassRefPtr<ChromiumDataObjectItem> add(const String& data, const String& type, ExceptionState&);
- PassRefPtr<ChromiumDataObjectItem> add(PassRefPtr<File>, ScriptExecutionContext*);
+ // Returns null if an item already exists with the provided type.
+ PassRefPtr<ChromiumDataObjectItem> add(const String& data, const String& type);
+ PassRefPtr<ChromiumDataObjectItem> add(PassRefPtr<File>);
// WebCore helpers.
void clearData(const String& type);
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/ChromiumDataObjectItem.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/ChromiumDataObjectItem.cpp
index e12314983e6..bae44138447 100644
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/ChromiumDataObjectItem.cpp
+++ b/chromium/third_party/WebKit/Source/core/platform/chromium/ChromiumDataObjectItem.cpp
@@ -31,14 +31,10 @@
#include "config.h"
#include "core/platform/chromium/ChromiumDataObjectItem.h"
-#include "core/dom/DataTransferItem.h"
#include "core/dom/StringCallback.h"
#include "core/fileapi/Blob.h"
-#include "core/fileapi/File.h"
-#include "core/platform/SharedBuffer.h"
-#include "core/platform/chromium/ClipboardMimeTypes.h"
-#include "core/platform/chromium/ClipboardUtilitiesChromium.h"
-
+#include "core/platform/Pasteboard.h"
+#include "platform/clipboard/ClipboardMimeTypes.h"
#include "public/platform/Platform.h"
#include "public/platform/WebClipboard.h"
@@ -46,21 +42,21 @@ namespace WebCore {
PassRefPtr<ChromiumDataObjectItem> ChromiumDataObjectItem::createFromString(const String& type, const String& data)
{
- RefPtr<ChromiumDataObjectItem> item = adoptRef(new ChromiumDataObjectItem(DataTransferItem::kindString, type));
+ RefPtr<ChromiumDataObjectItem> item = adoptRef(new ChromiumDataObjectItem(StringKind, type));
item->m_data = data;
return item.release();
}
PassRefPtr<ChromiumDataObjectItem> ChromiumDataObjectItem::createFromFile(PassRefPtr<File> file)
{
- RefPtr<ChromiumDataObjectItem> item = adoptRef(new ChromiumDataObjectItem(DataTransferItem::kindFile, file->type()));
+ RefPtr<ChromiumDataObjectItem> item = adoptRef(new ChromiumDataObjectItem(FileKind, file->type()));
item->m_file = file;
return item.release();
}
PassRefPtr<ChromiumDataObjectItem> ChromiumDataObjectItem::createFromURL(const String& url, const String& title)
{
- RefPtr<ChromiumDataObjectItem> item = adoptRef(new ChromiumDataObjectItem(DataTransferItem::kindString, mimeTypeTextURIList));
+ RefPtr<ChromiumDataObjectItem> item = adoptRef(new ChromiumDataObjectItem(StringKind, mimeTypeTextURIList));
item->m_data = url;
item->m_title = title;
return item.release();
@@ -68,7 +64,7 @@ PassRefPtr<ChromiumDataObjectItem> ChromiumDataObjectItem::createFromURL(const S
PassRefPtr<ChromiumDataObjectItem> ChromiumDataObjectItem::createFromHTML(const String& html, const KURL& baseURL)
{
- RefPtr<ChromiumDataObjectItem> item = adoptRef(new ChromiumDataObjectItem(DataTransferItem::kindString, mimeTypeTextHTML));
+ RefPtr<ChromiumDataObjectItem> item = adoptRef(new ChromiumDataObjectItem(StringKind, mimeTypeTextHTML));
item->m_data = html;
item->m_baseURL = baseURL;
return item.release();
@@ -76,7 +72,7 @@ PassRefPtr<ChromiumDataObjectItem> ChromiumDataObjectItem::createFromHTML(const
PassRefPtr<ChromiumDataObjectItem> ChromiumDataObjectItem::createFromSharedBuffer(const String& name, PassRefPtr<SharedBuffer> buffer)
{
- RefPtr<ChromiumDataObjectItem> item = adoptRef(new ChromiumDataObjectItem(DataTransferItem::kindFile, String()));
+ RefPtr<ChromiumDataObjectItem> item = adoptRef(new ChromiumDataObjectItem(FileKind, String()));
item->m_sharedBuffer = buffer;
item->m_title = name;
return item.release();
@@ -85,11 +81,11 @@ PassRefPtr<ChromiumDataObjectItem> ChromiumDataObjectItem::createFromSharedBuffe
PassRefPtr<ChromiumDataObjectItem> ChromiumDataObjectItem::createFromPasteboard(const String& type, uint64_t sequenceNumber)
{
if (type == mimeTypeImagePng)
- return adoptRef(new ChromiumDataObjectItem(DataTransferItem::kindFile, type, sequenceNumber));
- return adoptRef(new ChromiumDataObjectItem(DataTransferItem::kindString, type, sequenceNumber));
+ return adoptRef(new ChromiumDataObjectItem(FileKind, type, sequenceNumber));
+ return adoptRef(new ChromiumDataObjectItem(StringKind, type, sequenceNumber));
}
-ChromiumDataObjectItem::ChromiumDataObjectItem(const String& kind, const String& type)
+ChromiumDataObjectItem::ChromiumDataObjectItem(Kind kind, const String& type)
: m_source(InternalSource)
, m_kind(kind)
, m_type(type)
@@ -97,7 +93,7 @@ ChromiumDataObjectItem::ChromiumDataObjectItem(const String& kind, const String&
{
}
-ChromiumDataObjectItem::ChromiumDataObjectItem(const String& kind, const String& type, uint64_t sequenceNumber)
+ChromiumDataObjectItem::ChromiumDataObjectItem(Kind kind, const String& type, uint64_t sequenceNumber)
: m_source(PasteboardSource)
, m_kind(kind)
, m_type(type)
@@ -105,17 +101,17 @@ ChromiumDataObjectItem::ChromiumDataObjectItem(const String& kind, const String&
{
}
-void ChromiumDataObjectItem::getAsString(PassRefPtr<StringCallback> callback, ScriptExecutionContext* context) const
+void ChromiumDataObjectItem::getAsString(PassOwnPtr<StringCallback> callback, ExecutionContext* context) const
{
- if (!callback || kind() != DataTransferItem::kindString)
+ if (!callback || kind() != StringKind)
return;
- callback->scheduleCallback(context, internalGetAsString());
+ StringCallback::scheduleCallback(callback, context, internalGetAsString());
}
PassRefPtr<Blob> ChromiumDataObjectItem::getAsFile() const
{
- if (kind() != DataTransferItem::kindFile)
+ if (kind() != FileKind)
return 0;
if (m_source == InternalSource) {
@@ -139,13 +135,13 @@ PassRefPtr<Blob> ChromiumDataObjectItem::getAsFile() const
// method to the blob registry; that way the data is only copied over
// into the renderer when it's actually read, not when the blob is
// initially constructed).
- RefPtr<SharedBuffer> data = static_cast<PassRefPtr<SharedBuffer> >(WebKit::Platform::current()->clipboard()->readImage(WebKit::WebClipboard::BufferStandard));
+ RefPtr<SharedBuffer> data = static_cast<PassRefPtr<SharedBuffer> >(blink::Platform::current()->clipboard()->readImage(blink::WebClipboard::BufferStandard));
RefPtr<RawData> rawData = RawData::create();
rawData->mutableData()->append(data->data(), data->size());
OwnPtr<BlobData> blobData = BlobData::create();
blobData->appendData(rawData, 0, -1);
blobData->setContentType(mimeTypeImagePng);
- return Blob::create(blobData.release(), data->size());
+ return Blob::create(BlobDataHandle::create(blobData.release(), data->size()));
}
return 0;
@@ -153,32 +149,33 @@ PassRefPtr<Blob> ChromiumDataObjectItem::getAsFile() const
String ChromiumDataObjectItem::internalGetAsString() const
{
- ASSERT(m_kind == DataTransferItem::kindString);
+ ASSERT(m_kind == StringKind);
if (m_source == InternalSource)
return m_data;
ASSERT(m_source == PasteboardSource);
+ blink::WebClipboard::Buffer buffer = Pasteboard::generalPasteboard()->buffer();
String data;
// This is ugly but there's no real alternative.
if (m_type == mimeTypeTextPlain)
- data = WebKit::Platform::current()->clipboard()->readPlainText(currentPasteboardBuffer());
+ data = blink::Platform::current()->clipboard()->readPlainText(buffer);
else if (m_type == mimeTypeTextHTML) {
- WebKit::WebURL ignoredSourceURL;
+ blink::WebURL ignoredSourceURL;
unsigned ignored;
- data = WebKit::Platform::current()->clipboard()->readHTML(currentPasteboardBuffer(), &ignoredSourceURL, &ignored, &ignored);
+ data = blink::Platform::current()->clipboard()->readHTML(buffer, &ignoredSourceURL, &ignored, &ignored);
} else
- data = WebKit::Platform::current()->clipboard()->readCustomData(currentPasteboardBuffer(), m_type);
+ data = blink::Platform::current()->clipboard()->readCustomData(buffer, m_type);
- return WebKit::Platform::current()->clipboard()->sequenceNumber(currentPasteboardBuffer()) == m_sequenceNumber ? data : String();
+ return blink::Platform::current()->clipboard()->sequenceNumber(buffer) == m_sequenceNumber ? data : String();
}
bool ChromiumDataObjectItem::isFilename() const
{
// FIXME: https://bugs.webkit.org/show_bug.cgi?id=81261: When we properly support File dragout,
// we'll need to make sure this works as expected for DragDataChromium.
- return m_kind == DataTransferItem::kindFile && m_file;
+ return m_kind == FileKind && m_file;
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/ChromiumDataObjectItem.h b/chromium/third_party/WebKit/Source/core/platform/chromium/ChromiumDataObjectItem.h
index 82956b3bbb2..ecd328d54ab 100644
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/ChromiumDataObjectItem.h
+++ b/chromium/third_party/WebKit/Source/core/platform/chromium/ChromiumDataObjectItem.h
@@ -32,8 +32,8 @@
#define ChromiumDataObjectItem_h
#include "core/fileapi/File.h"
-#include "core/platform/SharedBuffer.h"
-#include "weborigin/KURL.h"
+#include "platform/SharedBuffer.h"
+#include "platform/weborigin/KURL.h"
#include "wtf/RefCounted.h"
#include "wtf/RefPtr.h"
#include "wtf/text/WTFString.h"
@@ -41,11 +41,16 @@
namespace WebCore {
class Blob;
-class ScriptExecutionContext;
+class ExecutionContext;
class StringCallback;
class ChromiumDataObjectItem : public RefCounted<ChromiumDataObjectItem> {
public:
+ enum Kind {
+ StringKind,
+ FileKind
+ };
+
static PassRefPtr<ChromiumDataObjectItem> createFromString(const String& type, const String& data);
static PassRefPtr<ChromiumDataObjectItem> createFromFile(PassRefPtr<File>);
static PassRefPtr<ChromiumDataObjectItem> createFromURL(const String& url, const String& title);
@@ -53,9 +58,9 @@ public:
static PassRefPtr<ChromiumDataObjectItem> createFromSharedBuffer(const String& filename, PassRefPtr<SharedBuffer>);
static PassRefPtr<ChromiumDataObjectItem> createFromPasteboard(const String& type, uint64_t sequenceNumber);
- String kind() const { return m_kind; }
+ Kind kind() const { return m_kind; }
String type() const { return m_type; }
- void getAsString(PassRefPtr<StringCallback>, ScriptExecutionContext*) const;
+ void getAsString(PassOwnPtr<StringCallback>, ExecutionContext*) const;
PassRefPtr<Blob> getAsFile() const;
// Used to support legacy DataTransfer APIs and renderer->browser serialization.
@@ -71,11 +76,11 @@ private:
InternalSource,
};
- ChromiumDataObjectItem(const String& kind, const String& type);
- ChromiumDataObjectItem(const String& kind, const String& type, uint64_t sequenceNumber);
+ ChromiumDataObjectItem(Kind, const String& type);
+ ChromiumDataObjectItem(Kind, const String& type, uint64_t sequenceNumber);
DataSource m_source;
- String m_kind;
+ Kind m_kind;
String m_type;
String m_data;
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/ClipboardChromium.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/ClipboardChromium.cpp
deleted file mode 100644
index 54afa4d9098..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/ClipboardChromium.cpp
+++ /dev/null
@@ -1,479 +0,0 @@
-/*
- * Copyright (C) 2006, 2007 Apple Inc. All rights reserved.
- * Copyright (C) 2008, 2009 Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/chromium/ClipboardChromium.h"
-
-#include "HTMLNames.h"
-#include "bindings/v8/ExceptionState.h"
-#include "core/dom/DataTransferItemList.h"
-#include "core/dom/Document.h"
-#include "core/dom/Element.h"
-#include "core/dom/ExceptionCode.h"
-#include "core/dom/StringCallback.h"
-#include "core/editing/markup.h"
-#include "core/fetch/ImageResource.h"
-#include "core/fileapi/File.h"
-#include "core/fileapi/FileList.h"
-#include "core/page/Frame.h"
-#include "core/platform/DragData.h"
-#include "core/platform/MIMETypeRegistry.h"
-#include "core/platform/chromium/ChromiumDataObject.h"
-#include "core/platform/chromium/ChromiumDataObjectItem.h"
-#include "core/platform/chromium/ClipboardMimeTypes.h"
-#include "core/platform/chromium/ClipboardUtilitiesChromium.h"
-#include "core/platform/graphics/Image.h"
-#include "core/rendering/RenderImage.h"
-
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-namespace {
-
-// A wrapper class that invalidates a DataTransferItemList when the associated Clipboard object goes out of scope.
-class DataTransferItemListPolicyWrapper : public DataTransferItemList {
-public:
- static PassRefPtr<DataTransferItemListPolicyWrapper> create(PassRefPtr<ClipboardChromium>, PassRefPtr<ChromiumDataObject>);
- virtual ~DataTransferItemListPolicyWrapper();
-
- virtual size_t length() const;
- virtual PassRefPtr<DataTransferItem> item(unsigned long index) OVERRIDE;
- virtual void deleteItem(unsigned long index, ExceptionState&) OVERRIDE;
- virtual void clear() OVERRIDE;
- virtual PassRefPtr<DataTransferItem> add(const String& data, const String& type, ExceptionState&) OVERRIDE;
- virtual PassRefPtr<DataTransferItem> add(PassRefPtr<File>) OVERRIDE;
-
-private:
- DataTransferItemListPolicyWrapper(PassRefPtr<ClipboardChromium>, PassRefPtr<ChromiumDataObject>);
-
- RefPtr<ClipboardChromium> m_clipboard;
- RefPtr<ChromiumDataObject> m_dataObject;
-};
-
-
-PassRefPtr<DataTransferItemListPolicyWrapper> DataTransferItemListPolicyWrapper::create(
- PassRefPtr<ClipboardChromium> clipboard, PassRefPtr<ChromiumDataObject> list)
-{
- return adoptRef(new DataTransferItemListPolicyWrapper(clipboard, list));
-}
-
-DataTransferItemListPolicyWrapper::~DataTransferItemListPolicyWrapper()
-{
-}
-
-size_t DataTransferItemListPolicyWrapper::length() const
-{
- if (!m_clipboard->canReadTypes())
- return 0;
- return m_dataObject->length();
-}
-
-PassRefPtr<DataTransferItem> DataTransferItemListPolicyWrapper::item(unsigned long index)
-{
- if (!m_clipboard->canReadTypes())
- return 0;
- RefPtr<ChromiumDataObjectItem> item = m_dataObject->item(index);
- if (!item)
- return 0;
-
- return DataTransferItemPolicyWrapper::create(m_clipboard, item);
-}
-
-void DataTransferItemListPolicyWrapper::deleteItem(unsigned long index, ExceptionState& es)
-{
- if (!m_clipboard->canWriteData()) {
- es.throwDOMException(InvalidStateError);
- return;
- }
- m_dataObject->deleteItem(index);
-}
-
-void DataTransferItemListPolicyWrapper::clear()
-{
- if (!m_clipboard->canWriteData())
- return;
- m_dataObject->clearAll();
-}
-
-PassRefPtr<DataTransferItem> DataTransferItemListPolicyWrapper::add(const String& data, const String& type, ExceptionState& es)
-{
- if (!m_clipboard->canWriteData())
- return 0;
- RefPtr<ChromiumDataObjectItem> item = m_dataObject->add(data, type, es);
- if (!item)
- return 0;
- return DataTransferItemPolicyWrapper::create(m_clipboard, item);
-}
-
-PassRefPtr<DataTransferItem> DataTransferItemListPolicyWrapper::add(PassRefPtr<File> file)
-{
- if (!m_clipboard->canWriteData())
- return 0;
- RefPtr<ChromiumDataObjectItem> item = m_dataObject->add(file, m_clipboard->frame()->document()->scriptExecutionContext());
- if (!item)
- return 0;
- return DataTransferItemPolicyWrapper::create(m_clipboard, item);
-}
-
-DataTransferItemListPolicyWrapper::DataTransferItemListPolicyWrapper(
- PassRefPtr<ClipboardChromium> clipboard, PassRefPtr<ChromiumDataObject> dataObject)
- : m_clipboard(clipboard)
- , m_dataObject(dataObject)
-{
-}
-
-} // namespace
-
-PassRefPtr<DataTransferItemPolicyWrapper> DataTransferItemPolicyWrapper::create(
- PassRefPtr<ClipboardChromium> clipboard, PassRefPtr<ChromiumDataObjectItem> item)
-{
- return adoptRef(new DataTransferItemPolicyWrapper(clipboard, item));
-}
-
-DataTransferItemPolicyWrapper::~DataTransferItemPolicyWrapper()
-{
-}
-
-String DataTransferItemPolicyWrapper::kind() const
-{
- if (!m_clipboard->canReadTypes())
- return String();
- return m_item->kind();
-}
-
-String DataTransferItemPolicyWrapper::type() const
-{
- if (!m_clipboard->canReadTypes())
- return String();
- return m_item->type();
-}
-
-void DataTransferItemPolicyWrapper::getAsString(PassRefPtr<StringCallback> callback) const
-{
- if (!m_clipboard->canReadData())
- return;
-
- m_item->getAsString(callback, m_clipboard->frame()->document()->scriptExecutionContext());
-}
-
-PassRefPtr<Blob> DataTransferItemPolicyWrapper::getAsFile() const
-{
- if (!m_clipboard->canReadData())
- return 0;
-
- return m_item->getAsFile();
-}
-
-DataTransferItemPolicyWrapper::DataTransferItemPolicyWrapper(
- PassRefPtr<ClipboardChromium> clipboard, PassRefPtr<ChromiumDataObjectItem> item)
- : m_clipboard(clipboard)
- , m_item(item)
-{
-}
-
-using namespace HTMLNames;
-
-// We provide the IE clipboard types (URL and Text), and the clipboard types specified in the WHATWG Web Applications 1.0 draft
-// see http://www.whatwg.org/specs/web-apps/current-work/ Section 6.3.5.3
-
-static String normalizeType(const String& type, bool* convertToURL = 0)
-{
- String cleanType = type.stripWhiteSpace().lower();
- if (cleanType == mimeTypeText || cleanType.startsWith(mimeTypeTextPlainEtc))
- return mimeTypeTextPlain;
- if (cleanType == mimeTypeURL) {
- if (convertToURL)
- *convertToURL = true;
- return mimeTypeTextURIList;
- }
- return cleanType;
-}
-
-PassRefPtr<Clipboard> Clipboard::create(ClipboardAccessPolicy policy, DragData* dragData, Frame* frame)
-{
- return ClipboardChromium::create(DragAndDrop, dragData->platformData(), policy, frame);
-}
-
-ClipboardChromium::ClipboardChromium(ClipboardType clipboardType,
- PassRefPtr<ChromiumDataObject> dataObject,
- ClipboardAccessPolicy policy,
- Frame* frame)
- : Clipboard(policy, clipboardType)
- , m_dataObject(dataObject)
- , m_frame(frame)
-{
-}
-
-ClipboardChromium::~ClipboardChromium()
-{
- if (m_dragImage)
- m_dragImage->removeClient(this);
-}
-
-PassRefPtr<ClipboardChromium> ClipboardChromium::create(ClipboardType clipboardType,
- PassRefPtr<ChromiumDataObject> dataObject, ClipboardAccessPolicy policy, Frame* frame)
-{
- return adoptRef(new ClipboardChromium(clipboardType, dataObject, policy, frame));
-}
-
-void ClipboardChromium::clearData(const String& type)
-{
- if (!canWriteData())
- return;
-
- m_dataObject->clearData(normalizeType(type));
-}
-
-void ClipboardChromium::clearAllData()
-{
- if (!canWriteData())
- return;
-
- m_dataObject->clearAll();
-}
-
-String ClipboardChromium::getData(const String& type) const
-{
- if (!canReadData())
- return String();
-
- bool convertToURL = false;
- String data = m_dataObject->getData(normalizeType(type, &convertToURL));
- if (!convertToURL)
- return data;
- return convertURIListToURL(data);
-}
-
-bool ClipboardChromium::setData(const String& type, const String& data)
-{
- if (!canWriteData())
- return false;
-
- return m_dataObject->setData(normalizeType(type), data);
-}
-
-// extensions beyond IE's API
-ListHashSet<String> ClipboardChromium::types() const
-{
- if (!canReadTypes())
- return ListHashSet<String>();
-
- return m_dataObject->types();
-}
-
-PassRefPtr<FileList> ClipboardChromium::files() const
-{
- RefPtr<FileList> files = FileList::create();
- if (!canReadData())
- return files.release();
-
- for (size_t i = 0; i < m_dataObject->length(); ++i) {
- if (m_dataObject->item(i)->kind() == DataTransferItem::kindFile) {
- RefPtr<Blob> blob = m_dataObject->item(i)->getAsFile();
- if (blob && blob->isFile())
- files->append(toFile(blob.get()));
- }
- }
-
- return files.release();
-}
-
-void ClipboardChromium::setDragImage(ImageResource* image, Node* node, const IntPoint& loc)
-{
- if (!canSetDragImage())
- return;
-
- if (m_dragImage)
- m_dragImage->removeClient(this);
- m_dragImage = image;
- if (m_dragImage)
- m_dragImage->addClient(this);
-
- m_dragLoc = loc;
- m_dragImageElement = node;
-}
-
-void ClipboardChromium::setDragImage(ImageResource* img, const IntPoint& loc)
-{
- setDragImage(img, 0, loc);
-}
-
-void ClipboardChromium::setDragImageElement(Node* node, const IntPoint& loc)
-{
- setDragImage(0, node, loc);
-}
-
-PassOwnPtr<DragImage> ClipboardChromium::createDragImage(IntPoint& loc) const
-{
- if (m_dragImageElement) {
- if (m_frame) {
- loc = m_dragLoc;
- return m_frame->nodeImage(m_dragImageElement.get());
- }
- } else if (m_dragImage) {
- loc = m_dragLoc;
- return DragImage::create(m_dragImage->image());
- }
- return nullptr;
-}
-
-static ImageResource* getImageResource(Element* element)
-{
- // Attempt to pull ImageResource from element
- ASSERT(element);
- RenderObject* renderer = element->renderer();
- if (!renderer || !renderer->isImage())
- return 0;
-
- RenderImage* image = toRenderImage(renderer);
- if (image->cachedImage() && !image->cachedImage()->errorOccurred())
- return image->cachedImage();
-
- return 0;
-}
-
-static void writeImageToDataObject(ChromiumDataObject* dataObject, Element* element,
- const KURL& url)
-{
- // Shove image data into a DataObject for use as a file
- ImageResource* cachedImage = getImageResource(element);
- if (!cachedImage || !cachedImage->imageForRenderer(element->renderer()) || !cachedImage->isLoaded())
- return;
-
- SharedBuffer* imageBuffer = cachedImage->imageForRenderer(element->renderer())->data();
- if (!imageBuffer || !imageBuffer->size())
- return;
-
- String imageExtension = cachedImage->image()->filenameExtension();
- ASSERT(!imageExtension.isEmpty());
-
- // Determine the filename for the file contents of the image.
- String filename = cachedImage->response().suggestedFilename();
- if (filename.isEmpty())
- filename = url.lastPathComponent();
-
- String fileExtension;
- if (filename.isEmpty()) {
- filename = element->getAttribute(altAttr);
- } else {
- // Strip any existing extension. Assume that alt text is usually not a filename.
- int extensionIndex = filename.reverseFind('.');
- if (extensionIndex != -1) {
- fileExtension = filename.substring(extensionIndex + 1);
- filename.truncate(extensionIndex);
- }
- }
-
- if (!fileExtension.isEmpty() && fileExtension != imageExtension) {
- String imageMimeType = MIMETypeRegistry::getMIMETypeForExtension(imageExtension);
- ASSERT(imageMimeType.startsWith("image/"));
- // Use the file extension only if it has imageMimeType: it's untrustworthy otherwise.
- if (imageMimeType == MIMETypeRegistry::getMIMETypeForExtension(fileExtension))
- imageExtension = fileExtension;
- }
-
- imageExtension = "." + imageExtension;
- ClipboardChromium::validateFilename(filename, imageExtension);
-
- dataObject->addSharedBuffer(filename + imageExtension, imageBuffer);
-}
-
-void ClipboardChromium::declareAndWriteDragImage(Element* element, const KURL& url, const String& title, Frame* frame)
-{
- if (!m_dataObject)
- return;
-
- m_dataObject->setURLAndTitle(url, title);
-
- // Write the bytes in the image to the file format.
- writeImageToDataObject(m_dataObject.get(), element, url);
-
- // Put img tag on the clipboard referencing the image
- m_dataObject->setData(mimeTypeTextHTML, createMarkup(element, IncludeNode, 0, ResolveAllURLs));
-}
-
-void ClipboardChromium::writeURL(const KURL& url, const String& title, Frame*)
-{
- if (!m_dataObject)
- return;
- ASSERT(!url.isEmpty());
-
- m_dataObject->setURLAndTitle(url, title);
-
- // The URL can also be used as plain text.
- m_dataObject->setData(mimeTypeTextPlain, url.string());
-
- // The URL can also be used as an HTML fragment.
- m_dataObject->setHTMLAndBaseURL(urlToMarkup(url, title), url);
-}
-
-void ClipboardChromium::writeRange(Range* selectedRange, Frame* frame)
-{
- ASSERT(selectedRange);
- if (!m_dataObject)
- return;
-
- m_dataObject->setHTMLAndBaseURL(createMarkup(selectedRange, 0, AnnotateForInterchange, false, ResolveNonLocalURLs), frame->document()->url());
-
- String str = frame->selectedTextForClipboard();
-#if OS(WIN)
- replaceNewlinesWithWindowsStyleNewlines(str);
-#endif
- replaceNBSPWithSpace(str);
- m_dataObject->setData(mimeTypeTextPlain, str);
-}
-
-void ClipboardChromium::writePlainText(const String& text)
-{
- if (!m_dataObject)
- return;
-
- String str = text;
-#if OS(WIN)
- replaceNewlinesWithWindowsStyleNewlines(str);
-#endif
- replaceNBSPWithSpace(str);
-
- m_dataObject->setData(mimeTypeTextPlain, str);
-}
-
-bool ClipboardChromium::hasData()
-{
- ASSERT(isForDragAndDrop());
-
- return m_dataObject->length() > 0;
-}
-
-PassRefPtr<DataTransferItemList> ClipboardChromium::items()
-{
- // FIXME: According to the spec, we are supposed to return the same collection of items each
- // time. We now return a wrapper that always wraps the *same* set of items, so JS shouldn't be
- // able to tell, but we probably still want to fix this.
- return DataTransferItemListPolicyWrapper::create(this, m_dataObject);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/ClipboardChromium.h b/chromium/third_party/WebKit/Source/core/platform/chromium/ClipboardChromium.h
deleted file mode 100644
index 4cc14168802..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/ClipboardChromium.h
+++ /dev/null
@@ -1,120 +0,0 @@
-// Copyright (c) 2008, Google Inc.
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-#ifndef ClipboardChromium_h
-#define ClipboardChromium_h
-
-#include "core/dom/Clipboard.h"
-#include "core/dom/DataTransferItem.h"
-#include "core/fetch/ImageResourceClient.h"
-#include "core/platform/chromium/ChromiumDataObject.h"
-
-namespace WebCore {
-
-class ImageResource;
- class ChromiumDataObjectItem;
- class ClipboardChromium;
- class Frame;
- class IntPoint;
-
- // A wrapper class that invalidates a DataTransferItem when the associated Clipboard object goes out of scope.
- class DataTransferItemPolicyWrapper : public DataTransferItem {
- public:
- static PassRefPtr<DataTransferItemPolicyWrapper> create(PassRefPtr<ClipboardChromium>, PassRefPtr<ChromiumDataObjectItem>);
- virtual ~DataTransferItemPolicyWrapper();
-
- virtual String kind() const OVERRIDE;
- virtual String type() const OVERRIDE;
- virtual void getAsString(PassRefPtr<StringCallback>) const OVERRIDE;
- virtual PassRefPtr<Blob> getAsFile() const OVERRIDE;
-
- ClipboardChromium* clipboard() { return m_clipboard.get(); }
- ChromiumDataObjectItem* dataObjectItem() { return m_item.get(); }
-
- private:
- DataTransferItemPolicyWrapper(PassRefPtr<ClipboardChromium>, PassRefPtr<ChromiumDataObjectItem>);
-
- RefPtr<ClipboardChromium> m_clipboard;
- RefPtr<ChromiumDataObjectItem> m_item;
- };
-
- class ClipboardChromium : public Clipboard, public ImageResourceClient {
- WTF_MAKE_FAST_ALLOCATED;
- public:
- ~ClipboardChromium();
-
- static PassRefPtr<ClipboardChromium> create(
- ClipboardType, PassRefPtr<ChromiumDataObject>, ClipboardAccessPolicy, Frame*);
-
- // Validates a filename (without the extension) and the extension. This removes any invalid
- // file system characters as well as making sure the path + extension is not bigger than
- // allowed by the file system.
- static void validateFilename(String& name, String& extension);
-
- virtual void clearData(const String& type);
- void clearAllData();
- String getData(const String& type) const;
- bool setData(const String& type, const String& data);
- bool platformClipboardChanged() const;
-
- // extensions beyond IE's API
- virtual ListHashSet<String> types() const;
- virtual PassRefPtr<FileList> files() const;
-
- void setDragImage(ImageResource*, const IntPoint&);
- void setDragImageElement(Node*, const IntPoint&);
-
- PassRefPtr<ChromiumDataObject> dataObject()
- {
- return m_dataObject;
- }
-
- virtual PassOwnPtr<DragImage> createDragImage(IntPoint& dragLoc) const;
- virtual void declareAndWriteDragImage(Element*, const KURL&, const String& title, Frame*);
- virtual void writeURL(const KURL&, const String&, Frame*);
- virtual void writeRange(Range*, Frame*);
- virtual void writePlainText(const String&);
-
- virtual bool hasData();
-
- virtual PassRefPtr<DataTransferItemList> items();
- Frame* frame() const { return m_frame; }
-
- private:
- ClipboardChromium(ClipboardType, PassRefPtr<ChromiumDataObject>, ClipboardAccessPolicy, Frame*);
-
- void resetFromClipboard();
- void setDragImage(ImageResource*, Node*, const IntPoint&);
- RefPtr<ChromiumDataObject> m_dataObject;
- Frame* m_frame;
- };
-
-} // namespace WebCore
-
-#endif // ClipboardChromium_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/ClipboardChromiumPosix.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/ClipboardChromiumPosix.cpp
deleted file mode 100644
index ee5b741a354..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/ClipboardChromiumPosix.cpp
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * Copyright (C) 2009 Apple Inc. All rights reserved.
- * Copyright (C) 2009 Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/chromium/ClipboardChromium.h"
-
-namespace WebCore {
-
-// On POSIX systems, the typical filename length limit is 255 character units. HFS+'s limit is
-// actually 255 Unicode characters using Apple's modification of Normzliation Form D, but the
-// differences aren't really worth dealing with here.
-static const unsigned maxFilenameLength = 255;
-
-static bool isInvalidFileCharacter(UChar c)
-{
- // HFS+ disallows '/' and Linux systems also disallow null. For sanity's sake we'll also
- // disallow control characters.
- return c < ' ' || c == 0x7F || c == '/';
-}
-
-void ClipboardChromium::validateFilename(String& name, String& extension)
-{
- // Remove any invalid file system characters, especially "/".
- name = name.removeCharacters(&isInvalidFileCharacter);
- extension = extension.removeCharacters(&isInvalidFileCharacter);
-
- // Remove a ridiculously-long extension.
- if (extension.length() >= maxFilenameLength)
- extension = String();
-
- // Truncate an overly-long filename, reserving one character for a dot.
- name.truncate(maxFilenameLength - extension.length() - 1);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/ClipboardChromiumTest.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/ClipboardChromiumTest.cpp
deleted file mode 100644
index 8bbaf5a3de9..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/ClipboardChromiumTest.cpp
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/platform/chromium/ClipboardChromium.h"
-
-#include <gtest/gtest.h>
-
-using namespace WebCore;
-
-namespace {
-
-#if OS(WIN)
-const char invalidCharacters[] = "\x00/\\:*?\"<>|";
-#else
-const char invalidCharacters[] =
- "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f"
- "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f"
- "\x7f/";
-#endif
-const char longString[] =
- "0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368,"
- "75025,121393,196418,317811,514229,832040,1346269,2178309,3524578,5702887,9227465,14930352";
-
-TEST(ClipboardChromiumTest, Normal)
-{
- String name = "name";
- String extension = "ext";
- ClipboardChromium::validateFilename(name, extension);
- EXPECT_EQ("name", name);
- EXPECT_EQ("ext", extension);
-}
-
-TEST(ClipboardChromiumTest, InvalidCharacters)
-{
- String name = "na" + String(invalidCharacters, arraysize(invalidCharacters)) + "me";
- String extension = "e" + String(invalidCharacters, arraysize(invalidCharacters)) + "xt";
- ClipboardChromium::validateFilename(name, extension);
- EXPECT_EQ("name", name);
- EXPECT_EQ("ext", extension);
-}
-
-TEST(ClipboardChromiumTest, ExtensionTooLong)
-{
- String name;
- String extension = String(longString) + longString;
- ClipboardChromium::validateFilename(name, extension);
- EXPECT_EQ(String(), extension);
-}
-
-TEST(ClipboardChromiumTest, NamePlusExtensionTooLong)
-{
- String name = String(longString) + longString;
- String extension = longString;
- ClipboardChromium::validateFilename(name, extension);
- EXPECT_EQ("0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765,109", name);
- EXPECT_EQ(longString, extension);
- EXPECT_EQ(254u, name.length() + extension.length());
-}
-
-} // anonymous namespace
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/ClipboardChromiumWin.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/ClipboardChromiumWin.cpp
deleted file mode 100644
index 176462d2ef6..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/ClipboardChromiumWin.cpp
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Copyright (C) 2009 Apple Inc. All rights reserved.
- * Copyright (C) 2009 Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/chromium/ClipboardChromium.h"
-
-#include <shlwapi.h>
-
-namespace WebCore {
-
-// FAT32 and NTFS both limit filenames to a maximum of 255 characters.
-static const unsigned maxFilenameLength = 255;
-
-// Returns true if the specified character is not valid in a file name. This
-// is intended for use with removeCharacters.
-static bool isInvalidFileCharacter(UChar c)
-{
- return (PathGetCharType(c) & (GCT_LFNCHAR | GCT_SHORTCHAR)) == 0;
-}
-
-void ClipboardChromium::validateFilename(String& name, String& extension)
-{
- // Remove any invalid file system characters.
- name = name.removeCharacters(&isInvalidFileCharacter);
- extension = extension.removeCharacters(&isInvalidFileCharacter);
-
- if (extension.length() >= maxFilenameLength)
- extension = String();
-
- // Truncate overly-long filenames, reserving one character for a dot.
- name.truncate(maxFilenameLength - extension.length() - 1);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/ClipboardMimeTypes.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/ClipboardMimeTypes.cpp
deleted file mode 100644
index 75b91954ed4..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/ClipboardMimeTypes.cpp
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Copyright (c) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/chromium/ClipboardMimeTypes.h"
-
-namespace WebCore {
-
-const char mimeTypeText[] = "text";
-const char mimeTypeTextPlain[] = "text/plain";
-const char mimeTypeTextPlainEtc[] = "text/plain;";
-const char mimeTypeTextHTML[] = "text/html";
-const char mimeTypeURL[] = "url";
-const char mimeTypeTextURIList[] = "text/uri-list";
-const char mimeTypeDownloadURL[] = "downloadurl";
-const char mimeTypeFiles[] = "Files";
-const char mimeTypeImagePng[] = "image/png";
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/ClipboardMimeTypes.h b/chromium/third_party/WebKit/Source/core/platform/chromium/ClipboardMimeTypes.h
deleted file mode 100644
index 3e4ab507d26..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/ClipboardMimeTypes.h
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Copyright (c) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ClipboardMimeTypes_h
-#define ClipboardMimeTypes_h
-
-namespace WebCore {
-
-extern const char mimeTypeText[];
-extern const char mimeTypeTextPlain[];
-extern const char mimeTypeTextPlainEtc[];
-extern const char mimeTypeTextHTML[];
-extern const char mimeTypeURL[];
-extern const char mimeTypeTextURIList[];
-extern const char mimeTypeDownloadURL[];
-extern const char mimeTypeFiles[];
-extern const char mimeTypeImagePng[];
-
-} // namespace WebCore
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/ClipboardUtilitiesChromium.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/ClipboardUtilitiesChromium.cpp
deleted file mode 100644
index 6d86b7e2744..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/ClipboardUtilitiesChromium.cpp
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
- * Copyright (c) 2008, 2009, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/chromium/ClipboardUtilitiesChromium.h"
-
-#include "core/platform/Pasteboard.h"
-#include "public/platform/WebClipboard.h"
-#include "weborigin/KURL.h"
-#include "wtf/text/StringBuilder.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-WebKit::WebClipboard::Buffer currentPasteboardBuffer()
-{
- return Pasteboard::generalPasteboard()->isSelectionMode() ?
- WebKit::WebClipboard::BufferSelection :
- WebKit::WebClipboard::BufferStandard;
-}
-
-#if OS(WIN)
-void replaceNewlinesWithWindowsStyleNewlines(String& str)
-{
- DEFINE_STATIC_LOCAL(String, windowsNewline, ("\r\n"));
- StringBuilder result;
- for (unsigned index = 0; index < str.length(); ++index) {
- if (str[index] != '\n' || (index > 0 && str[index - 1] == '\r'))
- result.append(str[index]);
- else
- result.append(windowsNewline);
- }
- str = result.toString();
-}
-#endif
-
-void replaceNBSPWithSpace(String& str)
-{
- static const UChar NonBreakingSpaceCharacter = 0xA0;
- static const UChar SpaceCharacter = ' ';
- str.replace(NonBreakingSpaceCharacter, SpaceCharacter);
-}
-
-String convertURIListToURL(const String& uriList)
-{
- Vector<String> items;
- // Line separator is \r\n per RFC 2483 - however, for compatibility
- // reasons we allow just \n here.
- uriList.split('\n', items);
- // Process the input and return the first valid URL. In case no URLs can
- // be found, return an empty string. This is in line with the HTML5 spec.
- for (size_t i = 0; i < items.size(); ++i) {
- String& line = items[i];
- line = line.stripWhiteSpace();
- if (line.isEmpty())
- continue;
- if (line[0] == '#')
- continue;
- KURL url = KURL(ParsedURLString, line);
- if (url.isValid())
- return url;
- }
- return String();
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/ClipboardUtilitiesChromium.h b/chromium/third_party/WebKit/Source/core/platform/chromium/ClipboardUtilitiesChromium.h
deleted file mode 100644
index 1a9cb3db3b4..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/ClipboardUtilitiesChromium.h
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright (c) 2008, 2009, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ClipboardUtilitiesChromium_h
-#define ClipboardUtilitiesChromium_h
-
-#include "public/platform/WebClipboard.h"
-#include "wtf/Forward.h"
-
-namespace WebCore {
-
-class KURL;
-
-WebKit::WebClipboard::Buffer currentPasteboardBuffer();
-#if OS(WIN)
-void replaceNewlinesWithWindowsStyleNewlines(String&);
-#endif
-void replaceNBSPWithSpace(String&);
-String convertURIListToURL(const String& uriList);
-
-} // namespace WebCore
-
-#endif // ClipboardUtilitiesChromium_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/FileSystemChromium.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/FileSystemChromium.cpp
deleted file mode 100644
index e3d1853cef8..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/FileSystemChromium.cpp
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * Copyright (c) 2008, 2009, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/FileSystem.h"
-
-#include "core/platform/FileMetadata.h"
-#include "core/platform/NotImplemented.h"
-
-#include "public/platform/Platform.h"
-#include "public/platform/WebFileInfo.h"
-#include "public/platform/WebFileUtilities.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-bool getFileSize(const String& path, long long& result)
-{
- FileMetadata metadata;
- if (!getFileMetadata(path, metadata))
- return false;
- result = metadata.length;
- return true;
-}
-
-bool getFileModificationTime(const String& path, time_t& result)
-{
- FileMetadata metadata;
- if (!getFileMetadata(path, metadata))
- return false;
- result = metadata.modificationTime;
- return true;
-}
-
-bool getFileMetadata(const String& path, FileMetadata& metadata)
-{
- WebKit::WebFileInfo webFileInfo;
- if (!WebKit::Platform::current()->fileUtilities()->getFileInfo(path, webFileInfo))
- return false;
- metadata.modificationTime = webFileInfo.modificationTime;
- metadata.length = webFileInfo.length;
- metadata.type = static_cast<FileMetadata::Type>(webFileInfo.type);
- return true;
-}
-
-String directoryName(const String& path)
-{
- return WebKit::Platform::current()->fileUtilities()->directoryName(path);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/FramelessScrollView.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/FramelessScrollView.cpp
deleted file mode 100644
index 0a98c868a50..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/FramelessScrollView.cpp
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- * Copyright (c) 2008, 2009, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/chromium/FramelessScrollView.h"
-
-#include "core/platform/chromium/FramelessScrollViewClient.h"
-
-namespace WebCore {
-
-FramelessScrollView::~FramelessScrollView()
-{
- // Remove native scrollbars now before we lose the connection to the HostWindow.
- setHasHorizontalScrollbar(false);
- setHasVerticalScrollbar(false);
-}
-
-void FramelessScrollView::invalidateScrollbarRect(Scrollbar* scrollbar, const IntRect& rect)
-{
- // Add in our offset within the ScrollView.
- IntRect dirtyRect = rect;
- dirtyRect.move(scrollbar->x(), scrollbar->y());
- invalidateRect(dirtyRect);
-}
-
-bool FramelessScrollView::isActive() const
-{
- // FIXME
- return true;
-}
-
-ScrollableArea* FramelessScrollView::enclosingScrollableArea() const
-{
- // FIXME: Look for an ancestor scrollable area that can be scrolled.
- return 0;
-}
-
-bool FramelessScrollView::scrollbarsCanBeActive() const
-{
- return isActive();
-}
-
-IntRect FramelessScrollView::scrollableAreaBoundingBox() const
-{
- return windowClipRect(false);
-}
-
-void FramelessScrollView::invalidateRect(const IntRect& rect)
-{
- if (HostWindow* h = hostWindow())
- h->invalidateContentsAndRootView(rect);
-}
-
-HostWindow* FramelessScrollView::hostWindow() const
-{
- return const_cast<FramelessScrollViewClient*>(m_client);
-}
-
-IntRect FramelessScrollView::windowClipRect(bool clipToContents) const
-{
- return contentsToWindow(visibleContentRect(clipToContents ? ExcludeScrollbars : IncludeScrollbars));
-}
-
-void FramelessScrollView::paintContents(GraphicsContext*, const IntRect&)
-{
-}
-
-void FramelessScrollView::contentsResized()
-{
-}
-
-void FramelessScrollView::visibleContentsResized()
-{
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/FramelessScrollView.h b/chromium/third_party/WebKit/Source/core/platform/chromium/FramelessScrollView.h
deleted file mode 100644
index aed283995f9..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/FramelessScrollView.h
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- * Copyright (c) 2008, 2009, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef FramelessScrollView_h
-#define FramelessScrollView_h
-
-#include "core/platform/ScrollView.h"
-
-namespace WebCore {
-
- class FramelessScrollViewClient;
- class PlatformGestureEvent;
- class PlatformKeyboardEvent;
- class PlatformMouseEvent;
- class PlatformTouchEvent;
- class PlatformWheelEvent;
-
- // A FramelessScrollView is a ScrollView that can be used to render custom
- // content, which does not have an associated Frame.
- //
- // NOTE: It may be better to just develop a custom subclass of Widget that
- // can have scroll bars for this instead of trying to reuse ScrollView.
- //
- class FramelessScrollView : public ScrollView {
- public:
- FramelessScrollView() : m_client(0) {}
- ~FramelessScrollView();
-
- FramelessScrollViewClient* client() const { return m_client; }
- void setClient(FramelessScrollViewClient* client) { m_client = client; }
-
- // Event handlers that subclasses must implement.
- virtual bool handleMouseDownEvent(const PlatformMouseEvent&) = 0;
- virtual bool handleMouseMoveEvent(const PlatformMouseEvent&) = 0;
- virtual bool handleMouseReleaseEvent(const PlatformMouseEvent&) = 0;
- virtual bool handleWheelEvent(const PlatformWheelEvent&) = 0;
- virtual bool handleKeyEvent(const PlatformKeyboardEvent&) = 0;
- virtual bool handleTouchEvent(const PlatformTouchEvent&) = 0;
- virtual bool handleGestureEvent(const PlatformGestureEvent&) = 0;
-
- // ScrollableArea public methods:
- virtual void invalidateScrollbarRect(Scrollbar*, const IntRect&) OVERRIDE;
- virtual bool isActive() const OVERRIDE;
- virtual ScrollableArea* enclosingScrollableArea() const OVERRIDE;
- virtual bool scrollbarsCanBeActive() const OVERRIDE;
- virtual IntRect scrollableAreaBoundingBox() const OVERRIDE;
-
- // Widget public methods:
- virtual void invalidateRect(const IntRect&);
-
- // ScrollView public methods:
- virtual HostWindow* hostWindow() const;
- virtual IntRect windowClipRect(bool clipToContents = true) const;
-
- protected:
- // ScrollView protected methods:
- virtual void paintContents(GraphicsContext*, const IntRect&);
- virtual void contentsResized();
- virtual void visibleContentsResized();
-
- private:
- FramelessScrollViewClient* m_client;
- };
-
-} // namespace WebCore
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/FramelessScrollViewClient.h b/chromium/third_party/WebKit/Source/core/platform/chromium/FramelessScrollViewClient.h
deleted file mode 100644
index a5c94747d88..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/FramelessScrollViewClient.h
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Copyright (c) 2008, 2009, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef FramelessScrollViewClient_h
-#define FramelessScrollViewClient_h
-
-#include "core/platform/HostWindow.h"
-
-namespace WebCore {
- class FramelessScrollView;
-
- class FramelessScrollViewClient : public HostWindow {
- public:
- virtual void popupClosed(FramelessScrollView* popup_view) = 0;
- };
-
-} // namespace WebCore
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/HistogramSupportChromium.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/HistogramSupportChromium.cpp
deleted file mode 100644
index 3834958c7c8..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/HistogramSupportChromium.cpp
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/HistogramSupport.h"
-
-#include "public/platform/Platform.h"
-
-namespace WebCore {
-
-void HistogramSupport::histogramEnumeration(const char* name, int sample, int boundaryValue)
-{
- WebKit::Platform::current()->histogramEnumeration(name, sample, boundaryValue);
-}
-
-void HistogramSupport::histogramCustomCounts(const char* name, int sample, int min, int max, int bucketCount)
-{
- WebKit::Platform::current()->histogramCustomCounts(name, sample, min, max, bucketCount);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/KeyCodeConversionAndroid.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/KeyCodeConversionAndroid.cpp
index e2a2df1e480..ae5a2869c9c 100644
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/KeyCodeConversionAndroid.cpp
+++ b/chromium/third_party/WebKit/Source/core/platform/chromium/KeyCodeConversionAndroid.cpp
@@ -29,7 +29,7 @@
*/
#include "config.h"
-#include "core/platform/chromium/KeyboardCodes.h"
+#include "platform/KeyboardCodes.h"
#include <android/keycodes.h>
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/KeyCodeConversionGtk.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/KeyCodeConversionGtk.cpp
index 354acc02de5..e20dabd62a6 100644
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/KeyCodeConversionGtk.cpp
+++ b/chromium/third_party/WebKit/Source/core/platform/chromium/KeyCodeConversionGtk.cpp
@@ -32,7 +32,7 @@
#include "config.h"
#include "core/platform/chromium/KeyCodeConversion.h"
-#include "core/platform/chromium/KeyboardCodes.h"
+#include "platform/KeyboardCodes.h"
#include <gdk/gdkkeysyms.h>
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/KeyboardCodes.h b/chromium/third_party/WebKit/Source/core/platform/chromium/KeyboardCodes.h
deleted file mode 100644
index 9228fddb4c4..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/KeyboardCodes.h
+++ /dev/null
@@ -1,561 +0,0 @@
-/*
- * Copyright (c) 2008, 2009, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef KeyboardCodes_h
-#define KeyboardCodes_h
-
-#if OS(WIN)
-#include <windows.h>
-#endif
-
-#include "core/platform/WindowsKeyboardCodes.h"
-
-namespace WebCore {
-
- enum {
- // VKEY_LBUTTON (01) Left mouse button
- // VKEY_RBUTTON (02) Right mouse button
- // VKEY_CANCEL (03) Control-break processing
- // VKEY_MBUTTON (04) Middle mouse button (three-button mouse)
- // VKEY_XBUTTON1 (05)
- // VKEY_XBUTTON2 (06)
-
- // VKEY_BACK (08) BACKSPACE key
- VKEY_BACK = VK_BACK,
-
- // VKEY_TAB (09) TAB key
- VKEY_TAB = VK_TAB,
-
- // VKEY_CLEAR (0C) CLEAR key
- VKEY_CLEAR = VK_CLEAR,
-
- // VKEY_RETURN (0D)
- VKEY_RETURN = VK_RETURN,
-
- // VKEY_SHIFT (10) SHIFT key
- VKEY_SHIFT = VK_SHIFT,
-
- // VKEY_CONTROL (11) CTRL key
- VKEY_CONTROL = VK_CONTROL,
-
- // VKEY_MENU (12) ALT key
- VKEY_MENU = VK_MENU,
-
- // VKEY_PAUSE (13) PAUSE key
- VKEY_PAUSE = VK_PAUSE,
-
- // VKEY_CAPITAL (14) CAPS LOCK key
- VKEY_CAPITAL = VK_CAPITAL,
-
- // VKEY_KANA (15) Input Method Editor (IME) Kana mode
- VKEY_KANA = VK_KANA,
-
- // VKEY_HANGUEL (15) IME Hanguel mode (maintained for compatibility, use VKEY_HANGUL)
- // VKEY_HANGUL (15) IME Hangul mode
- VKEY_HANGUL = VK_HANGUL,
-
- // VKEY_JUNJA (17) IME Junja mode
- VKEY_JUNJA = VK_JUNJA,
-
- // VKEY_FINAL (18) IME final mode
- VKEY_FINAL = VK_FINAL,
-
- // VKEY_HANJA (19) IME Hanja mode
- VKEY_HANJA = VK_HANJA,
-
- // VKEY_KANJI (19) IME Kanji mode
- VKEY_KANJI = VK_KANJI,
-
- // VKEY_ESCAPE (1B) ESC key
- VKEY_ESCAPE = VK_ESCAPE,
-
- // VKEY_CONVERT (1C) IME convert
- VKEY_CONVERT = VK_CONVERT,
-
- // VKEY_NONCONVERT (1D) IME nonconvert
- VKEY_NONCONVERT = VK_NONCONVERT,
-
- // VKEY_ACCEPT (1E) IME accept
- VKEY_ACCEPT = VK_ACCEPT,
-
- // VKEY_MODECHANGE (1F) IME mode change request
- VKEY_MODECHANGE = VK_MODECHANGE,
-
- // VKEY_SPACE (20) SPACEBAR
- VKEY_SPACE = VK_SPACE,
-
- // VKEY_PRIOR (21) PAGE UP key
- VKEY_PRIOR = VK_PRIOR,
-
- // VKEY_NEXT (22) PAGE DOWN key
- VKEY_NEXT = VK_NEXT,
-
- // VKEY_END (23) END key
- VKEY_END = VK_END,
-
- // VKEY_HOME (24) HOME key
- VKEY_HOME = VK_HOME,
-
- // VKEY_LEFT (25) LEFT ARROW key
- VKEY_LEFT = VK_LEFT,
-
- // VKEY_UP (26) UP ARROW key
- VKEY_UP = VK_UP,
-
- // VKEY_RIGHT (27) RIGHT ARROW key
- VKEY_RIGHT = VK_RIGHT,
-
- // VKEY_DOWN (28) DOWN ARROW key
- VKEY_DOWN = VK_DOWN,
-
- // VKEY_SELECT (29) SELECT key
- VKEY_SELECT = VK_SELECT,
-
- // VKEY_PRINT (2A) PRINT key
- VKEY_PRINT = VK_PRINT,
-
- // VKEY_EXECUTE (2B) EXECUTE key
- VKEY_EXECUTE = VK_EXECUTE,
-
- // VKEY_SNAPSHOT (2C) PRINT SCREEN key
- VKEY_SNAPSHOT = VK_SNAPSHOT,
-
- // VKEY_INSERT (2D) INS key
- VKEY_INSERT = VK_INSERT,
-
- // VKEY_DELETE (2E) DEL key
- VKEY_DELETE = VK_DELETE,
-
- // VKEY_HELP (2F) HELP key
- VKEY_HELP = VK_HELP,
-
- // (30) 0 key
- VKEY_0 = '0',
-
- // (31) 1 key
- VKEY_1 = '1',
-
- // (32) 2 key
- VKEY_2 = '2',
-
- // (33) 3 key
- VKEY_3 = '3',
-
- // (34) 4 key
- VKEY_4 = '4',
-
- // (35) 5 key,
-
- VKEY_5 = '5',
-
- // (36) 6 key
- VKEY_6 = '6',
-
- // (37) 7 key
- VKEY_7 = '7',
-
- // (38) 8 key
- VKEY_8 = '8',
-
- // (39) 9 key
- VKEY_9 = '9',
-
- // (41) A key
- VKEY_A = 'A',
-
- // (42) B key
- VKEY_B = 'B',
-
- // (43) C key
- VKEY_C = 'C',
-
- // (44) D key
- VKEY_D = 'D',
-
- // (45) E key
- VKEY_E = 'E',
-
- // (46) F key
- VKEY_F = 'F',
-
- // (47) G key
- VKEY_G = 'G',
-
- // (48) H key
- VKEY_H = 'H',
-
- // (49) I key
- VKEY_I = 'I',
-
- // (4A) J key
- VKEY_J = 'J',
-
- // (4B) K key
- VKEY_K = 'K',
-
- // (4C) L key
- VKEY_L = 'L',
-
- // (4D) M key
- VKEY_M = 'M',
-
- // (4E) N key
- VKEY_N = 'N',
-
- // (4F) O key
- VKEY_O = 'O',
-
- // (50) P key
- VKEY_P = 'P',
-
- // (51) Q key
- VKEY_Q = 'Q',
-
- // (52) R key
- VKEY_R = 'R',
-
- // (53) S key
- VKEY_S = 'S',
-
- // (54) T key
- VKEY_T = 'T',
-
- // (55) U key
- VKEY_U = 'U',
-
- // (56) V key
- VKEY_V = 'V',
-
- // (57) W key
- VKEY_W = 'W',
-
- // (58) X key
- VKEY_X = 'X',
-
- // (59) Y key
- VKEY_Y = 'Y',
-
- // (5A) Z key
- VKEY_Z = 'Z',
-
- // VKEY_LWIN (5B) Left Windows key (Microsoft Natural keyboard)
- VKEY_LWIN = VK_LWIN,
-
- // VKEY_RWIN (5C) Right Windows key (Natural keyboard)
- VKEY_RWIN = VK_RWIN,
-
- // VKEY_APPS (5D) Applications key (Natural keyboard)
- VKEY_APPS = VK_APPS,
-
- // VKEY_SLEEP (5F) Computer Sleep key
- VKEY_SLEEP = VK_SLEEP,
-
- // VKEY_NUMPAD0 (60) Numeric keypad 0 key
- VKEY_NUMPAD0 = VK_NUMPAD0,
-
- // VKEY_NUMPAD1 (61) Numeric keypad 1 key
- VKEY_NUMPAD1 = VK_NUMPAD1,
-
- // VKEY_NUMPAD2 (62) Numeric keypad 2 key
- VKEY_NUMPAD2 = VK_NUMPAD2,
-
- // VKEY_NUMPAD3 (63) Numeric keypad 3 key
- VKEY_NUMPAD3 = VK_NUMPAD3,
-
- // VKEY_NUMPAD4 (64) Numeric keypad 4 key
- VKEY_NUMPAD4 = VK_NUMPAD4,
-
- // VKEY_NUMPAD5 (65) Numeric keypad 5 key
- VKEY_NUMPAD5 = VK_NUMPAD5,
-
- // VKEY_NUMPAD6 (66) Numeric keypad 6 key
- VKEY_NUMPAD6 = VK_NUMPAD6,
-
- // VKEY_NUMPAD7 (67) Numeric keypad 7 key
- VKEY_NUMPAD7 = VK_NUMPAD7,
-
- // VKEY_NUMPAD8 (68) Numeric keypad 8 key
- VKEY_NUMPAD8 = VK_NUMPAD8,
-
- // VKEY_NUMPAD9 (69) Numeric keypad 9 key
- VKEY_NUMPAD9 = VK_NUMPAD9,
-
- // VKEY_MULTIPLY (6A) Multiply key
- VKEY_MULTIPLY = VK_MULTIPLY,
-
- // VKEY_ADD (6B) Add key
- VKEY_ADD = VK_ADD,
-
- // VKEY_SEPARATOR (6C) Separator key
- VKEY_SEPARATOR = VK_SEPARATOR,
-
- // VKEY_SUBTRACT (6D) Subtract key
- VKEY_SUBTRACT = VK_SUBTRACT,
-
- // VKEY_DECIMAL (6E) Decimal key
- VKEY_DECIMAL = VK_DECIMAL,
-
- // VKEY_DIVIDE (6F) Divide key
- VKEY_DIVIDE = VK_DIVIDE,
-
- // VKEY_F1 (70) F1 key
- VKEY_F1 = VK_F1,
-
- // VKEY_F2 (71) F2 key
- VKEY_F2 = VK_F2,
-
- // VKEY_F3 (72) F3 key
- VKEY_F3 = VK_F3,
-
- // VKEY_F4 (73) F4 key
- VKEY_F4 = VK_F4,
-
- // VKEY_F5 (74) F5 key
- VKEY_F5 = VK_F5,
-
- // VKEY_F6 (75) F6 key
- VKEY_F6 = VK_F6,
-
- // VKEY_F7 (76) F7 key
- VKEY_F7 = VK_F7,
-
- // VKEY_F8 (77) F8 key
- VKEY_F8 = VK_F8,
-
- // VKEY_F9 (78) F9 key
- VKEY_F9 = VK_F9,
-
- // VKEY_F10 (79) F10 key
- VKEY_F10 = VK_F10,
-
- // VKEY_F11 (7A) F11 key
- VKEY_F11 = VK_F11,
-
- // VKEY_F12 (7B) F12 key
- VKEY_F12 = VK_F12,
-
- // VKEY_F13 (7C) F13 key
- VKEY_F13 = VK_F13,
-
- // VKEY_F14 (7D) F14 key
- VKEY_F14 = VK_F14,
-
- // VKEY_F15 (7E) F15 key
- VKEY_F15 = VK_F15,
-
- // VKEY_F16 (7F) F16 key
- VKEY_F16 = VK_F16,
-
- // VKEY_F17 (80H) F17 key
- VKEY_F17 = VK_F17,
-
- // VKEY_F18 (81H) F18 key
- VKEY_F18 = VK_F18,
-
- // VKEY_F19 (82H) F19 key
- VKEY_F19 = VK_F19,
-
- // VKEY_F20 (83H) F20 key
- VKEY_F20 = VK_F20,
-
- // VKEY_F21 (84H) F21 key
- VKEY_F21 = VK_F21,
-
- // VKEY_F22 (85H) F22 key
- VKEY_F22 = VK_F22,
-
- // VKEY_F23 (86H) F23 key
- VKEY_F23 = VK_F23,
-
- // VKEY_F24 (87H) F24 key
- VKEY_F24 = VK_F24,
-
- // VKEY_NUMLOCK (90) NUM LOCK key
- VKEY_NUMLOCK = VK_NUMLOCK,
-
- // VKEY_SCROLL (91) SCROLL LOCK key
- VKEY_SCROLL = VK_SCROLL,
-
- // VKEY_LSHIFT (A0) Left SHIFT key
- VKEY_LSHIFT = VK_LSHIFT,
-
- // VKEY_RSHIFT (A1) Right SHIFT key
- VKEY_RSHIFT = VK_RSHIFT,
-
- // VKEY_LCONTROL (A2) Left CONTROL key
- VKEY_LCONTROL = VK_LCONTROL,
-
- // VKEY_RCONTROL (A3) Right CONTROL key
- VKEY_RCONTROL = VK_RCONTROL,
-
- // VKEY_LMENU (A4) Left MENU key
- VKEY_LMENU = VK_LMENU,
-
- // VKEY_RMENU (A5) Right MENU key
- VKEY_RMENU = VK_RMENU,
-
- // VKEY_BROWSER_BACK (A6) Windows 2000/XP: Browser Back key
- VKEY_BROWSER_BACK = VK_BROWSER_BACK,
-
- // VKEY_BROWSER_FORWARD (A7) Windows 2000/XP: Browser Forward key
- VKEY_BROWSER_FORWARD = VK_BROWSER_FORWARD,
-
- // VKEY_BROWSER_REFRESH (A8) Windows 2000/XP: Browser Refresh key
- VKEY_BROWSER_REFRESH = VK_BROWSER_REFRESH,
-
- // VKEY_BROWSER_STOP (A9) Windows 2000/XP: Browser Stop key
- VKEY_BROWSER_STOP = VK_BROWSER_STOP,
-
- // VKEY_BROWSER_SEARCH (AA) Windows 2000/XP: Browser Search key
- VKEY_BROWSER_SEARCH = VK_BROWSER_SEARCH,
-
- // VKEY_BROWSER_FAVORITES (AB) Windows 2000/XP: Browser Favorites key
- VKEY_BROWSER_FAVORITES = VK_BROWSER_FAVORITES,
-
- // VKEY_BROWSER_HOME (AC) Windows 2000/XP: Browser Start and Home key
- VKEY_BROWSER_HOME = VK_BROWSER_HOME,
-
- // VKEY_VOLUME_MUTE (AD) Windows 2000/XP: Volume Mute key
- VKEY_VOLUME_MUTE = VK_VOLUME_MUTE,
-
- // VKEY_VOLUME_DOWN (AE) Windows 2000/XP: Volume Down key
- VKEY_VOLUME_DOWN = VK_VOLUME_DOWN,
-
- // VKEY_VOLUME_UP (AF) Windows 2000/XP: Volume Up key
- VKEY_VOLUME_UP = VK_VOLUME_UP,
-
- // VKEY_MEDIA_NEXT_TRACK (B0) Windows 2000/XP: Next Track key
- VKEY_MEDIA_NEXT_TRACK = VK_MEDIA_NEXT_TRACK,
-
- // VKEY_MEDIA_PREV_TRACK (B1) Windows 2000/XP: Previous Track key
- VKEY_MEDIA_PREV_TRACK = VK_MEDIA_PREV_TRACK,
-
- // VKEY_MEDIA_STOP (B2) Windows 2000/XP: Stop Media key
- VKEY_MEDIA_STOP = VK_MEDIA_STOP,
-
- // VKEY_MEDIA_PLAY_PAUSE (B3) Windows 2000/XP: Play/Pause Media key
- VKEY_MEDIA_PLAY_PAUSE = VK_MEDIA_PLAY_PAUSE,
-
- // VKEY_LAUNCH_MAIL (B4) Windows 2000/XP: Start Mail key
- VKEY_MEDIA_LAUNCH_MAIL = 0xB4,
-
- // VKEY_LAUNCH_MEDIA_SELECT (B5) Windows 2000/XP: Select Media key
- VKEY_MEDIA_LAUNCH_MEDIA_SELECT = 0xB5,
-
- // VKEY_LAUNCH_APP1 (B6) Windows 2000/XP: Start Application 1 key
- VKEY_MEDIA_LAUNCH_APP1 = 0xB6,
-
- // VKEY_LAUNCH_APP2 (B7) Windows 2000/XP: Start Application 2 key
- VKEY_MEDIA_LAUNCH_APP2 = 0xB7,
-
- // VKEY_OEM_1 (BA) Used for miscellaneous characters, it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the ',:' key
- VKEY_OEM_1 = VK_OEM_1,
-
- // VKEY_OEM_PLUS (BB) Windows 2000/XP: For any country/region, the '+' key
- VKEY_OEM_PLUS = VK_OEM_PLUS,
-
- // VKEY_OEM_COMMA (BC) Windows 2000/XP: For any country/region, the ',' key
- VKEY_OEM_COMMA = VK_OEM_COMMA,
-
- // VKEY_OEM_MINUS (BD) Windows 2000/XP: For any country/region, the '-' key
- VKEY_OEM_MINUS = VK_OEM_MINUS,
-
- // VKEY_OEM_PERIOD (BE) Windows 2000/XP: For any country/region, the '.' key
- VKEY_OEM_PERIOD = VK_OEM_PERIOD,
-
- // VKEY_OEM_2 (BF) Used for miscellaneous characters, it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the '/?' key
- VKEY_OEM_2 = VK_OEM_2,
-
- // VKEY_OEM_3 (C0) Used for miscellaneous characters, it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the '`~' key
- VKEY_OEM_3 = VK_OEM_3,
-
- // VKEY_OEM_4 (DB) Used for miscellaneous characters, it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the '[{' key
- VKEY_OEM_4 = VK_OEM_4,
-
- // VKEY_OEM_5 (DC) Used for miscellaneous characters, it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the '\|' key
- VKEY_OEM_5 = VK_OEM_5,
-
- // VKEY_OEM_6 (DD) Used for miscellaneous characters, it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the ']}' key
- VKEY_OEM_6 = VK_OEM_6,
-
- // VKEY_OEM_7 (DE) Used for miscellaneous characters, it can vary by keyboard. Windows 2000/XP: For the US standard keyboard, the 'single-quote/double-quote' key
- VKEY_OEM_7 = VK_OEM_7,
-
- // VKEY_OEM_8 (DF) Used for miscellaneous characters, it can vary by keyboard.
- VKEY_OEM_8 = VK_OEM_8,
-
- // VKEY_OEM_102 (E2) Windows 2000/XP: Either the angle bracket key or the backslash key on the RT 102-key keyboard
- VKEY_OEM_102 = VK_OEM_102,
-
- // VKEY_OEM_103 (E3) GTV KEYCODE_MEDIA_REWIND
- VKEY_OEM_103 = 0xE3,
-
- // VKEY_OEM_104 (E4) GTV KEYCODE_MEDIA_FAST_FORWARD
- VKEY_OEM_104 = 0xE4,
-
- // VKEY_PROCESSKEY (E5) Windows 95/98/Me, Windows NT 4.0, Windows 2000/XP: IME PROCESS key
- VKEY_PROCESSKEY = VK_PROCESSKEY,
-
- // VKEY_PACKET (E7) Windows 2000/XP: Used to pass Unicode characters as if they were keystrokes. The VKEY_PACKET key is the low word of a 32-bit Virtual Key value used for non-keyboard input methods. For more information, see Remark in KEYBDINPUT,SendInput, WM_KEYDOWN, and WM_KEYUP
- VKEY_PACKET = VK_PACKET,
-
- // VKEY_ATTN (F6) Attn key
- VKEY_ATTN = VK_ATTN,
-
- // VKEY_CRSEL (F7) CrSel key
- VKEY_CRSEL = VK_CRSEL,
-
- // VKEY_EXSEL (F8) ExSel key
- VKEY_EXSEL = VK_EXSEL,
-
- // VKEY_EREOF (F9) Erase EOF key
- VKEY_EREOF = VK_EREOF,
-
- // VKEY_PLAY (FA) Play key
- VKEY_PLAY = VK_PLAY,
-
- // VKEY_ZOOM (FB) Zoom key
- VKEY_ZOOM = VK_ZOOM,
-
- // VKEY_NONAME (FC) Reserved for future use
- VKEY_NONAME = VK_NONAME,
-
- // VKEY_PA1 (FD) PA1 key
- VKEY_PA1 = VK_PA1,
-
- // VKEY_OEM_CLEAR (FE) Clear key
- VKEY_OEM_CLEAR = VK_OEM_CLEAR,
-
- VKEY_UNKNOWN = 0
- };
-
-} // namespace WebCore
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/LanguageChromium.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/LanguageChromium.cpp
deleted file mode 100644
index d937bbb97e1..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/LanguageChromium.cpp
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Copyright (c) 2008, 2009, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/Language.h"
-
-#include "public/platform/Platform.h"
-#include "wtf/text/WTFString.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-static String platformLanguage()
-{
- DEFINE_STATIC_LOCAL(String, computedDefaultLanguage, ());
- if (computedDefaultLanguage.isEmpty()) {
- computedDefaultLanguage.append(WebKit::Platform::current()->defaultLocale());
- ASSERT(!computedDefaultLanguage.isEmpty());
- }
- return computedDefaultLanguage;
-}
-
-Vector<String> platformUserPreferredLanguages()
-{
- Vector<String> userPreferredLanguages;
- userPreferredLanguages.append(platformLanguage());
- return userPreferredLanguages;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/MIMETypeRegistryChromium.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/MIMETypeRegistryChromium.cpp
deleted file mode 100644
index 1d93eeb7463..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/MIMETypeRegistryChromium.cpp
+++ /dev/null
@@ -1,119 +0,0 @@
-/*
- * Copyright (c) 2008, 2009, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/MIMETypeRegistry.h"
-
-#include "core/plugins/PluginData.h"
-
-#include "public/platform/Platform.h"
-#include "public/platform/WebMimeRegistry.h"
-#include "wtf/text/CString.h"
-
-namespace WebCore {
-
-String MIMETypeRegistry::getMIMETypeForExtension(const String &ext)
-{
- return WebKit::Platform::current()->mimeRegistry()->mimeTypeForExtension(ext);
-}
-
-String MIMETypeRegistry::getWellKnownMIMETypeForExtension(const String &ext)
-{
- // This method must be thread safe and should not consult the OS/registry.
- return WebKit::Platform::current()->mimeRegistry()->wellKnownMimeTypeForExtension(ext);
-}
-
-String MIMETypeRegistry::getMIMETypeForPath(const String& path)
-{
- int pos = path.reverseFind('.');
- if (pos < 0)
- return "application/octet-stream";
- String extension = path.substring(pos + 1);
- String mimeType = getMIMETypeForExtension(extension);
- if (mimeType.isEmpty()) {
- // If there's no mimetype registered for the extension, check to see
- // if a plugin can handle the extension.
- mimeType = getPluginMimeTypeFromExtension(extension);
- }
- if (mimeType.isEmpty())
- return "application/octet-stream";
- return mimeType;
-}
-
-bool MIMETypeRegistry::isSupportedImageMIMEType(const String& mimeType)
-{
- return WebKit::Platform::current()->mimeRegistry()->supportsImageMIMEType(mimeType)
- != WebKit::WebMimeRegistry::IsNotSupported;
-}
-
-bool MIMETypeRegistry::isSupportedImageResourceMIMEType(const String& mimeType)
-{
- return isSupportedImageMIMEType(mimeType);
-}
-
-bool MIMETypeRegistry::isSupportedImageMIMETypeForEncoding(const String& mimeType)
-{
- if (mimeType == "image/jpeg" || mimeType == "image/png")
- return true;
- if (mimeType == "image/webp")
- return true;
- return false;
-}
-
-bool MIMETypeRegistry::isSupportedJavaScriptMIMEType(const String& mimeType)
-{
- return WebKit::Platform::current()->mimeRegistry()->supportsJavaScriptMIMEType(mimeType)
- != WebKit::WebMimeRegistry::IsNotSupported;
-}
-
-bool MIMETypeRegistry::isSupportedNonImageMIMEType(const String& mimeType)
-{
- return WebKit::Platform::current()->mimeRegistry()->supportsNonImageMIMEType(mimeType)
- != WebKit::WebMimeRegistry::IsNotSupported;
-}
-
-bool MIMETypeRegistry::isSupportedMediaSourceMIMEType(const String& mimeType, const String& codecs)
-{
- return !mimeType.isEmpty()
- && WebKit::Platform::current()->mimeRegistry()->supportsMediaSourceMIMEType(mimeType, codecs);
-}
-
-bool MIMETypeRegistry::isJavaAppletMIMEType(const String& mimeType)
-{
- // Since this set is very limited and is likely to remain so we won't bother with the overhead
- // of using a hash set.
- // Any of the MIME types below may be followed by any number of specific versions of the JVM,
- // which is why we use startsWith()
- return mimeType.startsWith("application/x-java-applet", false)
- || mimeType.startsWith("application/x-java-bean", false)
- || mimeType.startsWith("application/x-java-vm", false);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/MemoryUsageSupportChromium.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/MemoryUsageSupportChromium.cpp
deleted file mode 100644
index 2975d482468..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/MemoryUsageSupportChromium.cpp
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/MemoryUsageSupport.h"
-
-#include <SkGraphics.h>
-#include "public/platform/Platform.h"
-#include "wtf/OwnPtr.h"
-
-namespace WebCore {
-
-int MemoryUsageSupport::memoryUsageMB()
-{
- return WebKit::Platform::current()->memoryUsageMB();
-}
-
-int MemoryUsageSupport::actualMemoryUsageMB()
-{
- return WebKit::Platform::current()->actualMemoryUsageMB();
-}
-
-bool MemoryUsageSupport::processMemorySizesInBytes(size_t* privateBytes, size_t* sharedBytes)
-{
- return WebKit::Platform::current()->processMemorySizesInBytes(privateBytes, sharedBytes);
-}
-
-void MemoryUsageSupport::requestProcessMemorySizes(PassOwnPtr<WebCore::MemoryUsageSupport::ProcessMemorySizesCallback> requestCallback)
-{
- class ProcessMemorySizesCallbackImpl : public WebKit::Platform::ProcessMemorySizesCallback {
- public:
- ProcessMemorySizesCallbackImpl(PassOwnPtr<WebCore::MemoryUsageSupport::ProcessMemorySizesCallback> callback) :
- m_callback(callback) { }
- virtual void dataReceived(size_t privateBytes, size_t sharedBytes)
- {
- m_callback->dataReceived(privateBytes, sharedBytes);
- }
- private:
- OwnPtr<WebCore::MemoryUsageSupport::ProcessMemorySizesCallback> m_callback;
- };
- WebKit::Platform::ProcessMemorySizesCallback* callback = new ProcessMemorySizesCallbackImpl(requestCallback);
- WebKit::Platform::current()->requestProcessMemorySizes(callback);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/PlatformKeyboardEventChromium.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/PlatformKeyboardEventChromium.cpp
deleted file mode 100644
index 228686bab09..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/PlatformKeyboardEventChromium.cpp
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * Copyright (C) 2006, 2007 Apple Inc. All rights reserved.
- * Copyright (C) 2008, 2009 Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/PlatformKeyboardEvent.h"
-
-#if OS(WIN)
-#include <windows.h>
-#elif OS(MACOSX)
-#import <Carbon/Carbon.h>
-#else
-#include "core/platform/NotImplemented.h"
-#endif
-
-namespace WebCore {
-
-#if OS(WIN)
-static const unsigned short HIGH_BIT_MASK_SHORT = 0x8000;
-#endif
-
-void PlatformKeyboardEvent::disambiguateKeyDownEvent(Type type)
-{
-#if OS(WIN)
- // No KeyDown events on Windows to disambiguate.
- ASSERT_NOT_REACHED();
-#else
- // Can only change type from KeyDown to RawKeyDown or Char, as we lack information for other conversions.
- ASSERT(m_type == PlatformEvent::KeyDown);
- ASSERT(type == PlatformEvent::RawKeyDown || type == PlatformEvent::Char);
- m_type = type;
-
- if (type == RawKeyDown) {
- m_text = String();
- m_unmodifiedText = String();
- } else {
- m_keyIdentifier = String();
- m_windowsVirtualKeyCode = 0;
-#if OS(MACOSX)
- if (m_text.length() == 1 && (m_text[0U] >= 0xF700 && m_text[0U] <= 0xF7FF)) {
- // According to NSEvents.h, OpenStep reserves the range 0xF700-0xF8FF for function keys. However, some actual private use characters
- // happen to be in this range, e.g. the Apple logo (Option+Shift+K).
- // 0xF7FF is an arbitrary cut-off.
- m_text = String();
- m_unmodifiedText = String();
- }
-#endif
- }
-#endif
-}
-
-bool PlatformKeyboardEvent::currentCapsLockState()
-{
-#if OS(WIN)
- // FIXME: Does this even work inside the sandbox?
- return GetKeyState(VK_CAPITAL) & 1;
-#elif OS(MACOSX)
- return GetCurrentKeyModifiers() & alphaLock;
-#else
- notImplemented();
- return false;
-#endif
-}
-
-void PlatformKeyboardEvent::getCurrentModifierState(bool& shiftKey, bool& ctrlKey, bool& altKey, bool& metaKey)
-{
-#if OS(WIN)
- shiftKey = GetKeyState(VK_SHIFT) & HIGH_BIT_MASK_SHORT;
- ctrlKey = GetKeyState(VK_CONTROL) & HIGH_BIT_MASK_SHORT;
- altKey = GetKeyState(VK_MENU) & HIGH_BIT_MASK_SHORT;
- metaKey = false;
-#elif OS(MACOSX)
- UInt32 currentModifiers = GetCurrentKeyModifiers();
- shiftKey = currentModifiers & ::shiftKey;
- ctrlKey = currentModifiers & ::controlKey;
- altKey = currentModifiers & ::optionKey;
- metaKey = currentModifiers & ::cmdKey;
-#else
- shiftKey = false;
- ctrlKey = false;
- altKey = false;
- metaKey = false;
- notImplemented();
-#endif
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/PlatformScreenChromium.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/PlatformScreenChromium.cpp
deleted file mode 100644
index b33c37b8191..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/PlatformScreenChromium.cpp
+++ /dev/null
@@ -1,99 +0,0 @@
-/*
- * Copyright (c) 2008, 2009, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/PlatformScreen.h"
-
-#include "core/platform/HostWindow.h"
-#include "core/platform/ScrollView.h"
-#include "core/platform/graphics/FloatRect.h"
-#include "public/platform/Platform.h"
-#include "public/platform/WebScreenInfo.h"
-
-namespace WebCore {
-
-static HostWindow* toHostWindow(Widget* widget)
-{
- if (!widget)
- return 0;
- ScrollView* root = widget->root();
- if (!root)
- return 0;
- return root->hostWindow();
-}
-
-int screenDepth(Widget* widget)
-{
- HostWindow* hostWindow = toHostWindow(widget);
- if (!hostWindow)
- return 0;
- return hostWindow->screenInfo().depth;
-}
-
-int screenDepthPerComponent(Widget* widget)
-{
- HostWindow* hostWindow = toHostWindow(widget);
- if (!hostWindow)
- return 0;
- return hostWindow->screenInfo().depthPerComponent;
-}
-
-bool screenIsMonochrome(Widget* widget)
-{
- HostWindow* hostWindow = toHostWindow(widget);
- if (!hostWindow)
- return false;
- return hostWindow->screenInfo().isMonochrome;
-}
-
-FloatRect screenRect(Widget* widget)
-{
- HostWindow* hostWindow = toHostWindow(widget);
- if (!hostWindow)
- return FloatRect();
- return IntRect(hostWindow->screenInfo().rect);
-}
-
-FloatRect screenAvailableRect(Widget* widget)
-{
- HostWindow* hostWindow = toHostWindow(widget);
- if (!hostWindow)
- return FloatRect();
- return IntRect(hostWindow->screenInfo().availableRect);
-}
-
-void screenColorProfile(ColorProfile& toProfile)
-{
- WebKit::WebVector<char> profile;
- WebKit::Platform::current()->screenColorProfile(&profile);
- toProfile.append(profile.data(), profile.size());
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/PlatformSpeechSynthesizerChromium.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/PlatformSpeechSynthesizerChromium.cpp
deleted file mode 100644
index 370c43afa48..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/PlatformSpeechSynthesizerChromium.cpp
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
- * Copyright (c) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/PlatformSpeechSynthesizer.h"
-
-#include "core/platform/PlatformSpeechSynthesisUtterance.h"
-#include "core/platform/PlatformSpeechSynthesisVoice.h"
-#include "core/platform/chromium/support/WebSpeechSynthesizerClientImpl.h"
-#include "public/platform/Platform.h"
-#include "public/platform/WebSpeechSynthesisUtterance.h"
-#include "public/platform/WebSpeechSynthesizer.h"
-#include "public/platform/WebSpeechSynthesizerClient.h"
-#include "wtf/RetainPtr.h"
-
-namespace WebCore {
-
-PlatformSpeechSynthesizer::PlatformSpeechSynthesizer(PlatformSpeechSynthesizerClient* client)
- : m_speechSynthesizerClient(client)
-{
- m_webSpeechSynthesizerClient = adoptPtr(new WebSpeechSynthesizerClientImpl(this, client));
- m_webSpeechSynthesizer = adoptPtr(WebKit::Platform::current()->createSpeechSynthesizer(m_webSpeechSynthesizerClient.get()));
-}
-
-PlatformSpeechSynthesizer::~PlatformSpeechSynthesizer()
-{
-}
-
-void PlatformSpeechSynthesizer::initializeVoiceList()
-{
- if (m_webSpeechSynthesizer.get())
- m_webSpeechSynthesizer->updateVoiceList();
-}
-
-void PlatformSpeechSynthesizer::speak(PassRefPtr<PlatformSpeechSynthesisUtterance> utterance)
-{
- if (!m_webSpeechSynthesizer || !m_webSpeechSynthesizerClient)
- return;
-
- m_webSpeechSynthesizer->speak(WebKit::WebSpeechSynthesisUtterance(utterance));
-}
-
-void PlatformSpeechSynthesizer::pause()
-{
- if (m_webSpeechSynthesizer.get())
- m_webSpeechSynthesizer->pause();
-}
-
-void PlatformSpeechSynthesizer::resume()
-{
- if (m_webSpeechSynthesizer.get())
- m_webSpeechSynthesizer->resume();
-}
-
-void PlatformSpeechSynthesizer::cancel()
-{
- if (m_webSpeechSynthesizer.get())
- m_webSpeechSynthesizer->cancel();
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/PlatformThemeChromiumDefault.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/PlatformThemeChromiumDefault.cpp
deleted file mode 100644
index f257da14b09..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/PlatformThemeChromiumDefault.cpp
+++ /dev/null
@@ -1,221 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/chromium/PlatformThemeChromiumDefault.h"
-
-namespace WebCore {
-
-unsigned PlatformThemeChromiumDefault::s_thumbInactiveColor = 0xeaeaea;
-unsigned PlatformThemeChromiumDefault::s_thumbActiveColor = 0xf4f4f4;
-unsigned PlatformThemeChromiumDefault::s_trackColor = 0xd3d3d3;
-
-void PlatformThemeChromiumDefault::setScrollbarColors(
- SkColor inactiveColor, SkColor activeColor, SkColor trackColor)
-{
- s_thumbInactiveColor = inactiveColor;
- s_thumbActiveColor = activeColor;
- s_trackColor = trackColor;
-}
-
-static SkScalar clamp(SkScalar value, SkScalar min, SkScalar max)
-{
- return std::min(std::max(value, min), max);
-}
-
-SkColor PlatformThemeChromiumDefault::saturateAndBrighten(const SkScalar hsv[3], SkScalar saturateAmount, SkScalar brightenAmount)
-{
- SkScalar color[3];
- color[0] = hsv[0];
- color[1] = clamp(hsv[1] + saturateAmount, 0.0, 1.0);
- color[2] = clamp(hsv[2] + brightenAmount, 0.0, 1.0);
- return SkHSVToColor(color);
-}
-
-SkColor PlatformThemeChromiumDefault::outlineColor(const SkScalar hsv1[3], const SkScalar hsv2[3])
-{
- // GTK Theme engines have way too much control over the layout of
- // the scrollbar. We might be able to more closely approximate its
- // look-and-feel, if we sent whole images instead of just colors
- // from the browser to the renderer. But even then, some themes
- // would just break.
- //
- // So, instead, we don't even try to 100% replicate the look of
- // the native scrollbar. We render our own version, but we make
- // sure to pick colors that blend in nicely with the system GTK
- // theme. In most cases, we can just sample a couple of pixels
- // from the system scrollbar and use those colors to draw our
- // scrollbar.
- //
- // This works fine for the track color and the overall thumb
- // color. But it fails spectacularly for the outline color used
- // around the thumb piece. Not all themes have a clearly defined
- // outline. For some of them it is partially transparent, and for
- // others the thickness is very unpredictable.
- //
- // So, instead of trying to approximate the system theme, we
- // instead try to compute a reasonable looking choice based on the
- // known color of the track and the thumb piece. This is difficult
- // when trying to deal both with high- and low-contrast themes,
- // and both with positive and inverted themes.
- //
- // The following code has been tested to look OK with all of the
- // default GTK themes.
- SkScalar minDiff = clamp((hsv1[1] + hsv2[1]) * 1.2, 0.28, 0.5);
- SkScalar diff = clamp(fabs(hsv1[2] - hsv2[2]) / 2, minDiff, 0.5);
-
- if (hsv1[2] + hsv2[2] > 1.0)
- diff = -diff;
-
- return saturateAndBrighten(hsv2, -0.2, diff);
-}
-
-void PlatformThemeChromiumDefault::paintArrowButton(GraphicsContext* gc, const IntRect& rect, ArrowDirection direction, ControlStates states)
-{
- SkCanvas* const canvas = gc->canvas();
- int widthMiddle, lengthMiddle;
- SkPaint paint;
- if (direction == North || direction == South) {
- widthMiddle = rect.width() / 2 + 1;
- lengthMiddle = rect.height() / 2 + 1;
- } else {
- lengthMiddle = rect.width() / 2 + 1;
- widthMiddle = rect.height() / 2 + 1;
- }
-
- // Calculate button color.
- SkScalar trackHSV[3];
- SkColorToHSV(trackColor(), trackHSV);
- SkColor buttonColor = saturateAndBrighten(trackHSV, 0, 0.2);
- SkColor backgroundColor = buttonColor;
- if (states & PressedState) {
- SkScalar buttonHSV[3];
- SkColorToHSV(buttonColor, buttonHSV);
- buttonColor = saturateAndBrighten(buttonHSV, 0, -0.1);
- } else if (states & HoverState) {
- SkScalar buttonHSV[3];
- SkColorToHSV(buttonColor, buttonHSV);
- buttonColor = saturateAndBrighten(buttonHSV, 0, 0.05);
- }
-
- SkIRect skrect;
- skrect.set(rect.x(), rect.y(), rect.x() + rect.width(), rect.y() + rect.height());
- // Paint the background (the area visible behind the rounded corners).
- paint.setColor(backgroundColor);
- canvas->drawIRect(skrect, paint);
-
- // Paint the button's outline and fill the middle
- SkPath outline;
- switch (direction) {
- case North:
- outline.moveTo(rect.x() + 0.5, rect.y() + rect.height() + 0.5);
- outline.rLineTo(0, -(rect.height() - 2));
- outline.rLineTo(2, -2);
- outline.rLineTo(rect.width() - 5, 0);
- outline.rLineTo(2, 2);
- outline.rLineTo(0, rect.height() - 2);
- break;
- case South:
- outline.moveTo(rect.x() + 0.5, rect.y() - 0.5);
- outline.rLineTo(0, rect.height() - 2);
- outline.rLineTo(2, 2);
- outline.rLineTo(rect.width() - 5, 0);
- outline.rLineTo(2, -2);
- outline.rLineTo(0, -(rect.height() - 2));
- break;
- case East:
- outline.moveTo(rect.x() - 0.5, rect.y() + 0.5);
- outline.rLineTo(rect.width() - 2, 0);
- outline.rLineTo(2, 2);
- outline.rLineTo(0, rect.height() - 5);
- outline.rLineTo(-2, 2);
- outline.rLineTo(-(rect.width() - 2), 0);
- break;
- case West:
- outline.moveTo(rect.x() + rect.width() + 0.5, rect.y() + 0.5);
- outline.rLineTo(-(rect.width() - 2), 0);
- outline.rLineTo(-2, 2);
- outline.rLineTo(0, rect.height() - 5);
- outline.rLineTo(2, 2);
- outline.rLineTo(rect.width() - 2, 0);
- break;
- }
- outline.close();
-
- paint.setStyle(SkPaint::kFill_Style);
- paint.setColor(buttonColor);
- canvas->drawPath(outline, paint);
-
- paint.setAntiAlias(true);
- paint.setStyle(SkPaint::kStroke_Style);
- SkScalar thumbHSV[3];
- SkColorToHSV(thumbInactiveColor(), thumbHSV);
- paint.setColor(outlineColor(trackHSV, thumbHSV));
- canvas->drawPath(outline, paint);
-
- // If the button is disabled or read-only, the arrow is drawn with the outline color.
- if (states & EnabledState && !(states & ReadOnlyState))
- paint.setColor(SK_ColorBLACK);
-
- paint.setAntiAlias(false);
- paint.setStyle(SkPaint::kFill_Style);
-
- SkPath path;
- // The constants in this block of code are hand-tailored to produce good
- // looking arrows without anti-aliasing.
- switch (direction) {
- case North:
- path.moveTo(rect.x() + widthMiddle - 4, rect.y() + lengthMiddle + 2);
- path.rLineTo(7, 0);
- path.rLineTo(-4, -4);
- break;
- case South:
- path.moveTo(rect.x() + widthMiddle - 4, rect.y() + lengthMiddle - 3);
- path.rLineTo(7, 0);
- path.rLineTo(-4, 4);
- break;
- case East:
- path.moveTo(rect.x() + lengthMiddle - 3, rect.y() + widthMiddle - 4);
- path.rLineTo(0, 7);
- path.rLineTo(4, -4);
- break;
- case West:
- path.moveTo(rect.x() + lengthMiddle + 1, rect.y() + widthMiddle - 5);
- path.rLineTo(0, 9);
- path.rLineTo(-4, -4);
- break;
- }
- path.close();
-
- canvas->drawPath(path, paint);
-}
-
-} // namespace WebCore
-
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/PlatformThemeChromiumDefault.h b/chromium/third_party/WebKit/Source/core/platform/chromium/PlatformThemeChromiumDefault.h
deleted file mode 100644
index a19402f8b32..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/PlatformThemeChromiumDefault.h
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef PlatformThemeChromiumDefault_h
-#define PlatformThemeChromiumDefault_h
-
-#include "SkColor.h"
-#include "SkScalar.h"
-#include "core/platform/ThemeTypes.h"
-#include "core/platform/graphics/GraphicsContext.h"
-
-namespace WebCore {
-
-class PlatformThemeChromiumDefault {
-public:
- enum ArrowDirection {
- North,
- East,
- South,
- West,
- };
-
- static void setScrollbarColors(unsigned inactiveColor,
- unsigned activeColor,
- unsigned trackColor);
- static unsigned thumbInactiveColor() { return s_thumbInactiveColor; }
- static unsigned thumbActiveColor() { return s_thumbActiveColor; }
- static unsigned trackColor() { return s_trackColor; }
-
- static SkColor saturateAndBrighten(const SkScalar hsv[3], SkScalar saturateAmount, SkScalar brightenAmount);
- static SkColor outlineColor(const SkScalar hsv1[3], const SkScalar hsv2[3]);
- static void paintArrowButton(GraphicsContext*, const IntRect&, ArrowDirection, ControlStates);
-
-private:
- PlatformThemeChromiumDefault() { }
-
- static unsigned s_thumbInactiveColor;
- static unsigned s_thumbActiveColor;
- static unsigned s_trackColor;
-};
-
-} // namespace WebCore
-
-#endif // PlatformThemeChromiumDefault_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/Prerender.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/Prerender.cpp
deleted file mode 100644
index 3b17885ace6..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/Prerender.cpp
+++ /dev/null
@@ -1,135 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-#include "config.h"
-#include "core/platform/PrerenderClient.h"
-#include "core/platform/chromium/Prerender.h"
-
-#include "public/platform/Platform.h"
-#include "public/platform/WebPrerender.h"
-#include "public/platform/WebPrerenderingSupport.h"
-#include "public/platform/WebReferrerPolicy.h"
-#include "public/platform/WebString.h"
-#include "public/platform/WebURL.h"
-
-namespace WebCore {
-
-Prerender::Prerender(PrerenderClient* client, const KURL& url, const String& referrer, ReferrerPolicy policy)
- : m_client(client)
- , m_url(url)
- , m_referrer(referrer)
- , m_referrerPolicy(policy)
- , m_isActive(false)
-{
-}
-
-Prerender::~Prerender()
-{
-}
-
-void Prerender::removeClient()
-{
- m_client = 0;
-}
-
-void Prerender::add()
-{
- ASSERT(!m_isActive);
- m_isActive = true;
- WebKit::WebPrerenderingSupport* platform = WebKit::WebPrerenderingSupport::current();
- if (!platform)
- return;
- platform->add(WebKit::WebPrerender(this));
-}
-
-void Prerender::cancel()
-{
- // The LinkLoader and the Document (via Prerenderer) share ownership of
- // the Prerender, so it may have been abandoned by the Prerenderer and
- // then later canceled by the LinkLoader.
- if (!m_isActive)
- return;
- m_isActive = false;
- WebKit::WebPrerenderingSupport* platform = WebKit::WebPrerenderingSupport::current();
- if (!platform)
- return;
- platform->cancel(WebKit::WebPrerender(this));
-}
-
-void Prerender::abandon()
-{
- // The LinkLoader and the Document (via Prerenderer) share ownership of
- // the Prerender, so it may have been canceled by the LinkLoader and
- // then later abandoned by the Prerenderer.
- if (!m_isActive)
- return;
- m_isActive = false;
- WebKit::WebPrerenderingSupport* platform = WebKit::WebPrerenderingSupport::current();
- if (!platform)
- return;
- platform->abandon(WebKit::WebPrerender(this));
-}
-
-void Prerender::suspend()
-{
- abandon();
-}
-
-void Prerender::resume()
-{
- add();
-}
-
-void Prerender::didStartPrerender()
-{
- if (m_client)
- m_client->didStartPrerender();
-}
-
-void Prerender::didStopPrerender()
-{
- if (m_client)
- m_client->didStopPrerender();
-}
-
-void Prerender::didSendLoadForPrerender()
-{
- if (m_client)
- m_client->didSendLoadForPrerender();
-}
-
-void Prerender::didSendDOMContentLoadedForPrerender()
-{
- if (m_client)
- m_client->didSendDOMContentLoadedForPrerender();
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/Prerender.h b/chromium/third_party/WebKit/Source/core/platform/chromium/Prerender.h
deleted file mode 100644
index 8177f0be348..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/Prerender.h
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-#ifndef Prerender_h
-#define Prerender_h
-
-#include "weborigin/KURL.h"
-#include "weborigin/ReferrerPolicy.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/RefPtr.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebKit {
-class WebPrerender;
-}
-
-namespace WebCore {
-
-class PrerenderClient;
-
-class Prerender : public RefCounted<Prerender> {
- WTF_MAKE_NONCOPYABLE(Prerender);
-public:
- class ExtraData : public RefCounted<ExtraData> {
- public:
- virtual ~ExtraData() { }
- };
-
- Prerender(PrerenderClient*, const KURL&, const String& referrer, ReferrerPolicy);
- ~Prerender();
-
- void removeClient();
-
- void add();
- void cancel();
- void abandon();
- void suspend();
- void resume();
-
- const KURL& url() const { return m_url; }
- const String& referrer() const { return m_referrer; }
- ReferrerPolicy referrerPolicy() const { return m_referrerPolicy; }
-
- void setExtraData(PassRefPtr<ExtraData> extraData) { m_extraData = extraData; }
- ExtraData* extraData() { return m_extraData.get(); }
-
- void didStartPrerender();
- void didStopPrerender();
- void didSendLoadForPrerender();
- void didSendDOMContentLoadedForPrerender();
-
-private:
- PrerenderClient* m_client;
-
- const KURL m_url;
- const String m_referrer;
- const ReferrerPolicy m_referrerPolicy;
-
- bool m_isActive;
-
- RefPtr<ExtraData> m_extraData;
-};
-
-}
-
-#endif // Prerender_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/PrerenderHandle.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/PrerenderHandle.cpp
deleted file mode 100644
index 2f9c0869fc3..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/PrerenderHandle.cpp
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-#include "config.h"
-#include "core/platform/PrerenderHandle.h"
-
-#include "core/platform/chromium/Prerender.h"
-#include "weborigin/ReferrerPolicy.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class KURL;
-
-PassRefPtr<PrerenderHandle> PrerenderHandle::create(PrerenderClient* client, const KURL& url, const String& referrer, ReferrerPolicy policy)
-{
- return adoptRef(new PrerenderHandle(client, url, referrer, policy));
-}
-
-PrerenderHandle::PrerenderHandle(PrerenderClient* client, const KURL& url, const String& referrer, ReferrerPolicy policy)
- : m_prerender(adoptRef(new Prerender(client, url, referrer, policy)))
-{
-}
-
-PrerenderHandle::~PrerenderHandle()
-{
- m_prerender->removeClient();
-}
-
-Prerender* PrerenderHandle::prerender()
-{
- return m_prerender.get();
-}
-
-void PrerenderHandle::removeClient()
-{
- prerender()->removeClient();
-}
-
-void PrerenderHandle::add()
-{
- prerender()->add();
-}
-
-void PrerenderHandle::cancel()
-{
- prerender()->cancel();
-}
-
-void PrerenderHandle::abandon()
-{
- prerender()->abandon();
-}
-
-void PrerenderHandle::suspend()
-{
- prerender()->suspend();
-}
-
-void PrerenderHandle::resume()
-{
- prerender()->resume();
-}
-
-const KURL& PrerenderHandle::url() const
-{
- return m_prerender->url();
-}
-
-const String& PrerenderHandle::referrer() const
-{
- return m_prerender->url();
-}
-
-ReferrerPolicy PrerenderHandle::referrerPolicy() const
-{
- return m_prerender->referrerPolicy();
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/SSLKeyGeneratorChromium.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/SSLKeyGeneratorChromium.cpp
deleted file mode 100644
index 80ef10b351c..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/SSLKeyGeneratorChromium.cpp
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Copyright (c) 2008, 2009, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/SSLKeyGenerator.h"
-
-#include "public/platform/Platform.h"
-#include "public/platform/WebString.h"
-#include "public/platform/WebURL.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-// These are defined in webkit/api/src/LocalizedStrings.cpp.
-String keygenMenuHighGradeKeySize();
-String keygenMenuMediumGradeKeySize();
-
-void getSupportedKeySizes(Vector<String>& sizes)
-{
- sizes.resize(2);
- sizes[0] = keygenMenuHighGradeKeySize();
- sizes[1] = keygenMenuMediumGradeKeySize();
-}
-
-String signedPublicKeyAndChallengeString(unsigned keySizeIndex, const String& challengeString, const KURL& url)
-{
- return WebKit::Platform::current()->signedPublicKeyAndChallengeString(keySizeIndex,
- WebKit::WebString(challengeString),
- WebKit::WebURL(url));
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/SharedTimerChromium.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/SharedTimerChromium.cpp
deleted file mode 100644
index 95c04c44d30..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/SharedTimerChromium.cpp
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Copyright (C) 2006 Apple Computer, Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/SharedTimer.h"
-
-#include "public/platform/Platform.h"
-
-namespace WebCore {
-
-void setSharedTimerFiredFunction(void (*f)())
-{
- WebKit::Platform::current()->setSharedTimerFiredFunction(f);
-}
-
-void setSharedTimerFireInterval(double fireTime)
-{
- WebKit::Platform::current()->setSharedTimerFireInterval(fireTime);
-}
-
-void stopSharedTimer()
-{
- WebKit::Platform::current()->stopSharedTimer();
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/SoundChromiumPosix.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/SoundChromiumPosix.cpp
deleted file mode 100644
index 163d123042d..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/SoundChromiumPosix.cpp
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright (c) 2008, 2009, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/Sound.h"
-
-#include "core/platform/NotImplemented.h"
-
-namespace WebCore {
-
-void systemBeep()
-{
- notImplemented();
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/SoundChromiumWin.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/SoundChromiumWin.cpp
deleted file mode 100644
index 6a73decc64e..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/SoundChromiumWin.cpp
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright (C) 2006, 2007 Apple Inc. All rights reserved.
- * Copyright (C) 2008, 2009 Google Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/Sound.h"
-
-#include <windows.h>
-
-namespace WebCore {
-
-void systemBeep()
-{
- MessageBeep(static_cast<UINT>(-1));
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/StatsCounterChromium.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/StatsCounterChromium.cpp
deleted file mode 100644
index 28f3564031e..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/StatsCounterChromium.cpp
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/StatsCounter.h"
-
-#include "public/platform/Platform.h"
-
-namespace WebCore {
-
-void StatsCounter::incrementStatsCounter(const char* counterName)
-{
- WebKit::Platform::current()->incrementStatsCounter(counterName);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/SuddenTerminationChromium.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/SuddenTerminationChromium.cpp
deleted file mode 100644
index fdd7e7d4ea6..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/SuddenTerminationChromium.cpp
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Copyright (C) 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/SuddenTermination.h"
-
-#include "public/platform/Platform.h"
-
-namespace WebCore {
-
-void disableSuddenTermination()
-{
- WebKit::Platform::current()->suddenTerminationChanged(false);
-}
-
-void enableSuddenTermination()
-{
- WebKit::Platform::current()->suddenTerminationChanged(true);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/TraceEvent.h b/chromium/third_party/WebKit/Source/core/platform/chromium/TraceEvent.h
deleted file mode 100644
index d56a1dae126..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/TraceEvent.h
+++ /dev/null
@@ -1,911 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-// Trace events are for tracking application performance and resource usage.
-// Macros are provided to track:
-// Begin and end of function calls
-// Counters
-//
-// Events are issued against categories. Whereas LOG's
-// categories are statically defined, TRACE categories are created
-// implicitly with a string. For example:
-// TRACE_EVENT_INSTANT0("MY_SUBSYSTEM", "SomeImportantEvent")
-//
-// Events can be INSTANT, or can be pairs of BEGIN and END in the same scope:
-// TRACE_EVENT_BEGIN0("MY_SUBSYSTEM", "SomethingCostly")
-// doSomethingCostly()
-// TRACE_EVENT_END0("MY_SUBSYSTEM", "SomethingCostly")
-// Note: our tools can't always determine the correct BEGIN/END pairs unless
-// these are used in the same scope. Use ASYNC_BEGIN/ASYNC_END macros if you need them
-// to be in separate scopes.
-//
-// A common use case is to trace entire function scopes. This
-// issues a trace BEGIN and END automatically:
-// void doSomethingCostly() {
-// TRACE_EVENT0("MY_SUBSYSTEM", "doSomethingCostly");
-// ...
-// }
-//
-// Additional parameters can be associated with an event:
-// void doSomethingCostly2(int howMuch) {
-// TRACE_EVENT1("MY_SUBSYSTEM", "doSomethingCostly",
-// "howMuch", howMuch);
-// ...
-// }
-//
-// The trace system will automatically add to this information the
-// current process id, thread id, and a timestamp in microseconds.
-//
-// To trace an asynchronous procedure such as an IPC send/receive, use ASYNC_BEGIN and
-// ASYNC_END:
-// [single threaded sender code]
-// static int send_count = 0;
-// ++send_count;
-// TRACE_EVENT_ASYNC_BEGIN0("ipc", "message", send_count);
-// Send(new MyMessage(send_count));
-// [receive code]
-// void OnMyMessage(send_count) {
-// TRACE_EVENT_ASYNC_END0("ipc", "message", send_count);
-// }
-// The third parameter is a unique ID to match ASYNC_BEGIN/ASYNC_END pairs.
-// ASYNC_BEGIN and ASYNC_END can occur on any thread of any traced process. Pointers can
-// be used for the ID parameter, and they will be mangled internally so that
-// the same pointer on two different processes will not match. For example:
-// class MyTracedClass {
-// public:
-// MyTracedClass() {
-// TRACE_EVENT_ASYNC_BEGIN0("category", "MyTracedClass", this);
-// }
-// ~MyTracedClass() {
-// TRACE_EVENT_ASYNC_END0("category", "MyTracedClass", this);
-// }
-// }
-//
-// Trace event also supports counters, which is a way to track a quantity
-// as it varies over time. Counters are created with the following macro:
-// TRACE_COUNTER1("MY_SUBSYSTEM", "myCounter", g_myCounterValue);
-//
-// Counters are process-specific. The macro itself can be issued from any
-// thread, however.
-//
-// Sometimes, you want to track two counters at once. You can do this with two
-// counter macros:
-// TRACE_COUNTER1("MY_SUBSYSTEM", "myCounter0", g_myCounterValue[0]);
-// TRACE_COUNTER1("MY_SUBSYSTEM", "myCounter1", g_myCounterValue[1]);
-// Or you can do it with a combined macro:
-// TRACE_COUNTER2("MY_SUBSYSTEM", "myCounter",
-// "bytesPinned", g_myCounterValue[0],
-// "bytesAllocated", g_myCounterValue[1]);
-// This indicates to the tracing UI that these counters should be displayed
-// in a single graph, as a summed area chart.
-//
-// Since counters are in a global namespace, you may want to disembiguate with a
-// unique ID, by using the TRACE_COUNTER_ID* variations.
-//
-// By default, trace collection is compiled in, but turned off at runtime.
-// Collecting trace data is the responsibility of the embedding
-// application. In Chrome's case, navigating to about:tracing will turn on
-// tracing and display data collected across all active processes.
-//
-//
-// Memory scoping note:
-// Tracing copies the pointers, not the string content, of the strings passed
-// in for category, name, and arg_names. Thus, the following code will
-// cause problems:
-// char* str = strdup("impprtantName");
-// TRACE_EVENT_INSTANT0("SUBSYSTEM", str); // BAD!
-// free(str); // Trace system now has dangling pointer
-//
-// To avoid this issue with the |name| and |arg_name| parameters, use the
-// TRACE_EVENT_COPY_XXX overloads of the macros at additional runtime overhead.
-// Notes: The category must always be in a long-lived char* (i.e. static const).
-// The |arg_values|, when used, are always deep copied with the _COPY
-// macros.
-//
-// When are string argument values copied:
-// const char* arg_values are only referenced by default:
-// TRACE_EVENT1("category", "name",
-// "arg1", "literal string is only referenced");
-// Use TRACE_STR_COPY to force copying of a const char*:
-// TRACE_EVENT1("category", "name",
-// "arg1", TRACE_STR_COPY("string will be copied"));
-// std::string arg_values are always copied:
-// TRACE_EVENT1("category", "name",
-// "arg1", std::string("string will be copied"));
-//
-//
-// Thread Safety:
-// A thread safe singleton and mutex are used for thread safety. Category
-// enabled flags are used to limit the performance impact when the system
-// is not enabled.
-//
-// TRACE_EVENT macros first cache a pointer to a category. The categories are
-// statically allocated and safe at all times, even after exit. Fetching a
-// category is protected by the TraceLog::lock_. Multiple threads initializing
-// the static variable is safe, as they will be serialized by the lock and
-// multiple calls will return the same pointer to the category.
-//
-// Then the category_enabled flag is checked. This is a unsigned char, and
-// not intended to be multithread safe. It optimizes access to addTraceEvent
-// which is threadsafe internally via TraceLog::lock_. The enabled flag may
-// cause some threads to incorrectly call or skip calling addTraceEvent near
-// the time of the system being enabled or disabled. This is acceptable as
-// we tolerate some data loss while the system is being enabled/disabled and
-// because addTraceEvent is threadsafe internally and checks the enabled state
-// again under lock.
-//
-// Without the use of these static category pointers and enabled flags all
-// trace points would carry a significant performance cost of aquiring a lock
-// and resolving the category.
-
-#ifndef TraceEvent_h
-#define TraceEvent_h
-
-#include "core/platform/EventTracer.h"
-
-#include "wtf/DynamicAnnotations.h"
-#include "wtf/UnusedParam.h"
-#include "wtf/text/CString.h"
-
-// By default, const char* argument values are assumed to have long-lived scope
-// and will not be copied. Use this macro to force a const char* to be copied.
-#define TRACE_STR_COPY(str) \
- WebCore::TraceEvent::TraceStringWithCopy(str)
-
-// By default, uint64 ID argument values are not mangled with the Process ID in
-// TRACE_EVENT_ASYNC macros. Use this macro to force Process ID mangling.
-#define TRACE_ID_MANGLE(id) \
- TraceID::ForceMangle(id)
-
-// By default, pointers are mangled with the Process ID in TRACE_EVENT_ASYNC
-// macros. Use this macro to prevent Process ID mangling.
-#define TRACE_ID_DONT_MANGLE(id) \
- TraceID::DontMangle(id)
-
-// Records a pair of begin and end events called "name" for the current
-// scope, with 0, 1 or 2 associated arguments. If the category is not
-// enabled, then this does nothing.
-// - category and name strings must have application lifetime (statics or
-// literals). They may not include " chars.
-#define TRACE_EVENT0(category, name) \
- INTERNAL_TRACE_EVENT_ADD_SCOPED(category, name)
-#define TRACE_EVENT1(category, name, arg1_name, arg1_val) \
- INTERNAL_TRACE_EVENT_ADD_SCOPED(category, name, arg1_name, arg1_val)
-#define TRACE_EVENT2(category, name, arg1_name, arg1_val, arg2_name, arg2_val) \
- INTERNAL_TRACE_EVENT_ADD_SCOPED(category, name, arg1_name, arg1_val, \
- arg2_name, arg2_val)
-
-// Records a single event called "name" immediately, with 0, 1 or 2
-// associated arguments. If the category is not enabled, then this
-// does nothing.
-// - category and name strings must have application lifetime (statics or
-// literals). They may not include " chars.
-#define TRACE_EVENT_INSTANT0(category, name) \
- INTERNAL_TRACE_EVENT_ADD(TRACE_EVENT_PHASE_INSTANT, \
- category, name, TRACE_EVENT_FLAG_NONE)
-#define TRACE_EVENT_INSTANT1(category, name, arg1_name, arg1_val) \
- INTERNAL_TRACE_EVENT_ADD(TRACE_EVENT_PHASE_INSTANT, \
- category, name, TRACE_EVENT_FLAG_NONE, arg1_name, arg1_val)
-#define TRACE_EVENT_INSTANT2(category, name, arg1_name, arg1_val, \
- arg2_name, arg2_val) \
- INTERNAL_TRACE_EVENT_ADD(TRACE_EVENT_PHASE_INSTANT, \
- category, name, TRACE_EVENT_FLAG_NONE, arg1_name, arg1_val, \
- arg2_name, arg2_val)
-#define TRACE_EVENT_COPY_INSTANT0(category, name) \
- INTERNAL_TRACE_EVENT_ADD(TRACE_EVENT_PHASE_INSTANT, \
- category, name, TRACE_EVENT_FLAG_COPY)
-#define TRACE_EVENT_COPY_INSTANT1(category, name, arg1_name, arg1_val) \
- INTERNAL_TRACE_EVENT_ADD(TRACE_EVENT_PHASE_INSTANT, \
- category, name, TRACE_EVENT_FLAG_COPY, arg1_name, arg1_val)
-#define TRACE_EVENT_COPY_INSTANT2(category, name, arg1_name, arg1_val, \
- arg2_name, arg2_val) \
- INTERNAL_TRACE_EVENT_ADD(TRACE_EVENT_PHASE_INSTANT, \
- category, name, TRACE_EVENT_FLAG_COPY, arg1_name, arg1_val, \
- arg2_name, arg2_val)
-
-// Records a single BEGIN event called "name" immediately, with 0, 1 or 2
-// associated arguments. If the category is not enabled, then this
-// does nothing.
-// - category and name strings must have application lifetime (statics or
-// literals). They may not include " chars.
-#define TRACE_EVENT_BEGIN0(category, name) \
- INTERNAL_TRACE_EVENT_ADD(TRACE_EVENT_PHASE_BEGIN, \
- category, name, TRACE_EVENT_FLAG_NONE)
-#define TRACE_EVENT_BEGIN1(category, name, arg1_name, arg1_val) \
- INTERNAL_TRACE_EVENT_ADD(TRACE_EVENT_PHASE_BEGIN, \
- category, name, TRACE_EVENT_FLAG_NONE, arg1_name, arg1_val)
-#define TRACE_EVENT_BEGIN2(category, name, arg1_name, arg1_val, \
- arg2_name, arg2_val) \
- INTERNAL_TRACE_EVENT_ADD(TRACE_EVENT_PHASE_BEGIN, \
- category, name, TRACE_EVENT_FLAG_NONE, arg1_name, arg1_val, \
- arg2_name, arg2_val)
-#define TRACE_EVENT_COPY_BEGIN0(category, name) \
- INTERNAL_TRACE_EVENT_ADD(TRACE_EVENT_PHASE_BEGIN, \
- category, name, TRACE_EVENT_FLAG_COPY)
-#define TRACE_EVENT_COPY_BEGIN1(category, name, arg1_name, arg1_val) \
- INTERNAL_TRACE_EVENT_ADD(TRACE_EVENT_PHASE_BEGIN, \
- category, name, TRACE_EVENT_FLAG_COPY, arg1_name, arg1_val)
-#define TRACE_EVENT_COPY_BEGIN2(category, name, arg1_name, arg1_val, \
- arg2_name, arg2_val) \
- INTERNAL_TRACE_EVENT_ADD(TRACE_EVENT_PHASE_BEGIN, \
- category, name, TRACE_EVENT_FLAG_COPY, arg1_name, arg1_val, \
- arg2_name, arg2_val)
-
-// Records a single END event for "name" immediately. If the category
-// is not enabled, then this does nothing.
-// - category and name strings must have application lifetime (statics or
-// literals). They may not include " chars.
-#define TRACE_EVENT_END0(category, name) \
- INTERNAL_TRACE_EVENT_ADD(TRACE_EVENT_PHASE_END, \
- category, name, TRACE_EVENT_FLAG_NONE)
-#define TRACE_EVENT_END1(category, name, arg1_name, arg1_val) \
- INTERNAL_TRACE_EVENT_ADD(TRACE_EVENT_PHASE_END, \
- category, name, TRACE_EVENT_FLAG_NONE, arg1_name, arg1_val)
-#define TRACE_EVENT_END2(category, name, arg1_name, arg1_val, \
- arg2_name, arg2_val) \
- INTERNAL_TRACE_EVENT_ADD(TRACE_EVENT_PHASE_END, \
- category, name, TRACE_EVENT_FLAG_NONE, arg1_name, arg1_val, \
- arg2_name, arg2_val)
-#define TRACE_EVENT_COPY_END0(category, name) \
- INTERNAL_TRACE_EVENT_ADD(TRACE_EVENT_PHASE_END, \
- category, name, TRACE_EVENT_FLAG_COPY)
-#define TRACE_EVENT_COPY_END1(category, name, arg1_name, arg1_val) \
- INTERNAL_TRACE_EVENT_ADD(TRACE_EVENT_PHASE_END, \
- category, name, TRACE_EVENT_FLAG_COPY, arg1_name, arg1_val)
-#define TRACE_EVENT_COPY_END2(category, name, arg1_name, arg1_val, \
- arg2_name, arg2_val) \
- INTERNAL_TRACE_EVENT_ADD(TRACE_EVENT_PHASE_END, \
- category, name, TRACE_EVENT_FLAG_COPY, arg1_name, arg1_val, \
- arg2_name, arg2_val)
-
-// Records the value of a counter called "name" immediately. Value
-// must be representable as a 32 bit integer.
-// - category and name strings must have application lifetime (statics or
-// literals). They may not include " chars.
-#define TRACE_COUNTER1(category, name, value) \
- INTERNAL_TRACE_EVENT_ADD(TRACE_EVENT_PHASE_COUNTER, \
- category, name, TRACE_EVENT_FLAG_NONE, \
- "value", static_cast<int>(value))
-#define TRACE_COPY_COUNTER1(category, name, value) \
- INTERNAL_TRACE_EVENT_ADD(TRACE_EVENT_PHASE_COUNTER, \
- category, name, TRACE_EVENT_FLAG_COPY, \
- "value", static_cast<int>(value))
-
-// Records the values of a multi-parted counter called "name" immediately.
-// The UI will treat value1 and value2 as parts of a whole, displaying their
-// values as a stacked-bar chart.
-// - category and name strings must have application lifetime (statics or
-// literals). They may not include " chars.
-#define TRACE_COUNTER2(category, name, value1_name, value1_val, \
- value2_name, value2_val) \
- INTERNAL_TRACE_EVENT_ADD(TRACE_EVENT_PHASE_COUNTER, \
- category, name, TRACE_EVENT_FLAG_NONE, \
- value1_name, static_cast<int>(value1_val), \
- value2_name, static_cast<int>(value2_val))
-#define TRACE_COPY_COUNTER2(category, name, value1_name, value1_val, \
- value2_name, value2_val) \
- INTERNAL_TRACE_EVENT_ADD(TRACE_EVENT_PHASE_COUNTER, \
- category, name, TRACE_EVENT_FLAG_COPY, \
- value1_name, static_cast<int>(value1_val), \
- value2_name, static_cast<int>(value2_val))
-
-// Records the value of a counter called "name" immediately. Value
-// must be representable as a 32 bit integer.
-// - category and name strings must have application lifetime (statics or
-// literals). They may not include " chars.
-// - |id| is used to disambiguate counters with the same name. It must either
-// be a pointer or an integer value up to 64 bits. If it's a pointer, the bits
-// will be xored with a hash of the process ID so that the same pointer on
-// two different processes will not collide.
-#define TRACE_COUNTER_ID1(category, name, id, value) \
- INTERNAL_TRACE_EVENT_ADD_WITH_ID(TRACE_EVENT_PHASE_COUNTER, \
- category, name, id, TRACE_EVENT_FLAG_NONE, \
- "value", static_cast<int>(value))
-#define TRACE_COPY_COUNTER_ID1(category, name, id, value) \
- INTERNAL_TRACE_EVENT_ADD_WITH_ID(TRACE_EVENT_PHASE_COUNTER, \
- category, name, id, TRACE_EVENT_FLAG_COPY, \
- "value", static_cast<int>(value))
-
-// Records the values of a multi-parted counter called "name" immediately.
-// The UI will treat value1 and value2 as parts of a whole, displaying their
-// values as a stacked-bar chart.
-// - category and name strings must have application lifetime (statics or
-// literals). They may not include " chars.
-// - |id| is used to disambiguate counters with the same name. It must either
-// be a pointer or an integer value up to 64 bits. If it's a pointer, the bits
-// will be xored with a hash of the process ID so that the same pointer on
-// two different processes will not collide.
-#define TRACE_COUNTER_ID2(category, name, id, value1_name, value1_val, \
- value2_name, value2_val) \
- INTERNAL_TRACE_EVENT_ADD_WITH_ID(TRACE_EVENT_PHASE_COUNTER, \
- category, name, id, TRACE_EVENT_FLAG_NONE, \
- value1_name, static_cast<int>(value1_val), \
- value2_name, static_cast<int>(value2_val))
-#define TRACE_COPY_COUNTER_ID2(category, name, id, value1_name, value1_val, \
- value2_name, value2_val) \
- INTERNAL_TRACE_EVENT_ADD_WITH_ID(TRACE_EVENT_PHASE_COUNTER, \
- category, name, id, TRACE_EVENT_FLAG_COPY, \
- value1_name, static_cast<int>(value1_val), \
- value2_name, static_cast<int>(value2_val))
-
-// Records a single ASYNC_BEGIN event called "name" immediately, with 0, 1 or 2
-// associated arguments. If the category is not enabled, then this
-// does nothing.
-// - category and name strings must have application lifetime (statics or
-// literals). They may not include " chars.
-// - |id| is used to match the ASYNC_BEGIN event with the ASYNC_END event. ASYNC
-// events are considered to match if their category, name and id values all
-// match. |id| must either be a pointer or an integer value up to 64 bits. If
-// it's a pointer, the bits will be xored with a hash of the process ID so
-// that the same pointer on two different processes will not collide.
-// An asynchronous operation can consist of multiple phases. The first phase is
-// defined by the ASYNC_BEGIN calls. Additional phases can be defined using the
-// ASYNC_STEP_BEGIN macros. When the operation completes, call ASYNC_END.
-// An async operation can span threads and processes, but all events in that
-// operation must use the same |name| and |id|. Each event can have its own
-// args.
-#define TRACE_EVENT_ASYNC_BEGIN0(category, name, id) \
- INTERNAL_TRACE_EVENT_ADD_WITH_ID(TRACE_EVENT_PHASE_ASYNC_BEGIN, \
- category, name, id, TRACE_EVENT_FLAG_NONE)
-#define TRACE_EVENT_ASYNC_BEGIN1(category, name, id, arg1_name, arg1_val) \
- INTERNAL_TRACE_EVENT_ADD_WITH_ID(TRACE_EVENT_PHASE_ASYNC_BEGIN, \
- category, name, id, TRACE_EVENT_FLAG_NONE, arg1_name, arg1_val)
-#define TRACE_EVENT_ASYNC_BEGIN2(category, name, id, arg1_name, arg1_val, \
- arg2_name, arg2_val) \
- INTERNAL_TRACE_EVENT_ADD_WITH_ID(TRACE_EVENT_PHASE_ASYNC_BEGIN, \
- category, name, id, TRACE_EVENT_FLAG_NONE, \
- arg1_name, arg1_val, arg2_name, arg2_val)
-#define TRACE_EVENT_COPY_ASYNC_BEGIN0(category, name, id) \
- INTERNAL_TRACE_EVENT_ADD_WITH_ID(TRACE_EVENT_PHASE_ASYNC_BEGIN, \
- category, name, id, TRACE_EVENT_FLAG_COPY)
-#define TRACE_EVENT_COPY_ASYNC_BEGIN1(category, name, id, arg1_name, arg1_val) \
- INTERNAL_TRACE_EVENT_ADD_WITH_ID(TRACE_EVENT_PHASE_ASYNC_BEGIN, \
- category, name, id, TRACE_EVENT_FLAG_COPY, \
- arg1_name, arg1_val)
-#define TRACE_EVENT_COPY_ASYNC_BEGIN2(category, name, id, arg1_name, arg1_val, \
- arg2_name, arg2_val) \
- INTERNAL_TRACE_EVENT_ADD_WITH_ID(TRACE_EVENT_PHASE_ASYNC_BEGIN, \
- category, name, id, TRACE_EVENT_FLAG_COPY, \
- arg1_name, arg1_val, arg2_name, arg2_val)
-
-// Records a single ASYNC_STEP event for |step| immediately. If the category
-// is not enabled, then this does nothing. The |name| and |id| must match the
-// ASYNC_BEGIN event above. The |step| param identifies this step within the
-// async event. This should be called at the beginning of the next phase of an
-// asynchronous operation.
-#define TRACE_EVENT_ASYNC_STEP0(category, name, id, step) \
- INTERNAL_TRACE_EVENT_ADD_WITH_ID(TRACE_EVENT_PHASE_ASYNC_STEP, \
- category, name, id, TRACE_EVENT_FLAG_NONE, "step", step)
-#define TRACE_EVENT_ASYNC_STEP1(category, name, id, step, \
- arg1_name, arg1_val) \
- INTERNAL_TRACE_EVENT_ADD_WITH_ID(TRACE_EVENT_PHASE_ASYNC_STEP, \
- category, name, id, TRACE_EVENT_FLAG_NONE, "step", step, \
- arg1_name, arg1_val)
-#define TRACE_EVENT_COPY_ASYNC_STEP0(category, name, id, step) \
- INTERNAL_TRACE_EVENT_ADD_WITH_ID(TRACE_EVENT_PHASE_ASYNC_STEP, \
- category, name, id, TRACE_EVENT_FLAG_COPY, "step", step)
-#define TRACE_EVENT_COPY_ASYNC_STEP1(category, name, id, step, \
- arg1_name, arg1_val) \
- INTERNAL_TRACE_EVENT_ADD_WITH_ID(TRACE_EVENT_PHASE_ASYNC_STEP, \
- category, name, id, TRACE_EVENT_FLAG_COPY, "step", step, \
- arg1_name, arg1_val)
-
-// Records a single ASYNC_END event for "name" immediately. If the category
-// is not enabled, then this does nothing.
-#define TRACE_EVENT_ASYNC_END0(category, name, id) \
- INTERNAL_TRACE_EVENT_ADD_WITH_ID(TRACE_EVENT_PHASE_ASYNC_END, \
- category, name, id, TRACE_EVENT_FLAG_NONE)
-#define TRACE_EVENT_ASYNC_END1(category, name, id, arg1_name, arg1_val) \
- INTERNAL_TRACE_EVENT_ADD_WITH_ID(TRACE_EVENT_PHASE_ASYNC_END, \
- category, name, id, TRACE_EVENT_FLAG_NONE, arg1_name, arg1_val)
-#define TRACE_EVENT_ASYNC_END2(category, name, id, arg1_name, arg1_val, \
- arg2_name, arg2_val) \
- INTERNAL_TRACE_EVENT_ADD_WITH_ID(TRACE_EVENT_PHASE_ASYNC_END, \
- category, name, id, TRACE_EVENT_FLAG_NONE, \
- arg1_name, arg1_val, arg2_name, arg2_val)
-#define TRACE_EVENT_COPY_ASYNC_END0(category, name, id) \
- INTERNAL_TRACE_EVENT_ADD_WITH_ID(TRACE_EVENT_PHASE_ASYNC_END, \
- category, name, id, TRACE_EVENT_FLAG_COPY)
-#define TRACE_EVENT_COPY_ASYNC_END1(category, name, id, arg1_name, arg1_val) \
- INTERNAL_TRACE_EVENT_ADD_WITH_ID(TRACE_EVENT_PHASE_ASYNC_END, \
- category, name, id, TRACE_EVENT_FLAG_COPY, \
- arg1_name, arg1_val)
-#define TRACE_EVENT_COPY_ASYNC_END2(category, name, id, arg1_name, arg1_val, \
- arg2_name, arg2_val) \
- INTERNAL_TRACE_EVENT_ADD_WITH_ID(TRACE_EVENT_PHASE_ASYNC_END, \
- category, name, id, TRACE_EVENT_FLAG_COPY, \
- arg1_name, arg1_val, arg2_name, arg2_val)
-
-// Creates a scope of a sampling state with the given category and name (both must
-// be constant strings). These states are intended for a sampling profiler.
-// Implementation note: we store category and name together because we don't
-// want the inconsistency/expense of storing two pointers.
-// |thread_bucket| is [0..2] and is used to statically isolate samples in one
-// thread from others.
-//
-// { // The sampling state is set within this scope.
-// TRACE_EVENT_SAMPLING_STATE_SCOPE_FOR_BUCKET(0, "category", "name");
-// ...;
-// }
-#define TRACE_EVENT_SCOPED_SAMPLING_STATE_FOR_BUCKET(bucket_number, category, name) \
- TraceEvent::SamplingStateScope<bucket_number> traceEventSamplingScope(category "\0" name);
-
-// Returns a current sampling state of the given bucket.
-// The format of the returned string is "category\0name".
-#define TRACE_EVENT_GET_SAMPLING_STATE_FOR_BUCKET(bucket_number) \
- TraceEvent::SamplingStateScope<bucket_number>::current()
-
-// Sets a current sampling state of the given bucket.
-// |category| and |name| have to be constant strings.
-#define TRACE_EVENT_SET_SAMPLING_STATE_FOR_BUCKET(bucket_number, category, name) \
- TraceEvent::SamplingStateScope<bucket_number>::set(category "\0" name)
-
-// Sets a current sampling state of the given bucket.
-// |categoryAndName| doesn't need to be a constant string.
-// The format of the string is "category\0name".
-#define TRACE_EVENT_SET_NONCONST_SAMPLING_STATE_FOR_BUCKET(bucket_number, categoryAndName) \
- TraceEvent::SamplingStateScope<bucket_number>::set(categoryAndName)
-
-// Syntactic sugars for the sampling tracing in the main thread.
-#define TRACE_EVENT_SCOPED_SAMPLING_STATE(category, name) \
- TRACE_EVENT_SCOPED_SAMPLING_STATE_FOR_BUCKET(0, category, name)
-#define TRACE_EVENT_GET_SAMPLING_STATE() \
- TRACE_EVENT_GET_SAMPLING_STATE_FOR_BUCKET(0)
-#define TRACE_EVENT_SET_SAMPLING_STATE(category, name) \
- TRACE_EVENT_SET_SAMPLING_STATE_FOR_BUCKET(0, category, name)
-#define TRACE_EVENT_SET_NONCONST_SAMPLING_STATE(categoryAndName) \
- TRACE_EVENT_SET_NONCONST_SAMPLING_STATE_FOR_BUCKET(0, categoryAndName)
-
-// Macros to track the life time and value of arbitrary client objects.
-// See also TraceTrackableObject.
-#define TRACE_EVENT_OBJECT_CREATED_WITH_ID(categoryGroup, name, id) \
- INTERNAL_TRACE_EVENT_ADD_WITH_ID(TRACE_EVENT_PHASE_CREATE_OBJECT, \
- categoryGroup, name, TRACE_ID_DONT_MANGLE(id), TRACE_EVENT_FLAG_NONE)
-
-#define TRACE_EVENT_OBJECT_DELETED_WITH_ID(categoryGroup, name, id) \
- INTERNAL_TRACE_EVENT_ADD_WITH_ID(TRACE_EVENT_PHASE_DELETE_OBJECT, \
- categoryGroup, name, TRACE_ID_DONT_MANGLE(id), TRACE_EVENT_FLAG_NONE)
-
-////////////////////////////////////////////////////////////////////////////////
-// Implementation specific tracing API definitions.
-
-// Get a pointer to the enabled state of the given trace category. Only
-// long-lived literal strings should be given as the category name. The returned
-// pointer can be held permanently in a local static for example. If the
-// unsigned char is non-zero, tracing is enabled. If tracing is enabled,
-// TRACE_EVENT_API_ADD_TRACE_EVENT can be called. It's OK if tracing is disabled
-// between the load of the tracing state and the call to
-// TRACE_EVENT_API_ADD_TRACE_EVENT, because this flag only provides an early out
-// for best performance when tracing is disabled.
-// const unsigned char*
-// TRACE_EVENT_API_GET_CATEGORY_ENABLED(const char* category_name)
-#define TRACE_EVENT_API_GET_CATEGORY_ENABLED \
- WebCore::EventTracer::getTraceCategoryEnabledFlag
-
-// Add a trace event to the platform tracing system.
-// void TRACE_EVENT_API_ADD_TRACE_EVENT(
-// char phase,
-// const unsigned char* category_enabled,
-// const char* name,
-// unsigned long long id,
-// int num_args,
-// const char** arg_names,
-// const unsigned char* arg_types,
-// const unsigned long long* arg_values,
-// unsigned char flags)
-#define TRACE_EVENT_API_ADD_TRACE_EVENT \
- WebCore::EventTracer::addTraceEvent
-
-////////////////////////////////////////////////////////////////////////////////
-
-// Implementation detail: trace event macros create temporary variables
-// to keep instrumentation overhead low. These macros give each temporary
-// variable a unique name based on the line number to prevent name collissions.
-#define INTERNAL_TRACE_EVENT_UID3(a, b) \
- trace_event_unique_##a##b
-#define INTERNAL_TRACE_EVENT_UID2(a, b) \
- INTERNAL_TRACE_EVENT_UID3(a, b)
-#define INTERNALTRACEEVENTUID(name_prefix) \
- INTERNAL_TRACE_EVENT_UID2(name_prefix, __LINE__)
-
-// Implementation detail: internal macro to create static category.
-// - WTF_ANNOTATE_BENIGN_RACE, see Thread Safety above.
-#define INTERNAL_TRACE_EVENT_GET_CATEGORY_INFO(category) \
- static const unsigned char* INTERNALTRACEEVENTUID(catstatic) = 0; \
- WTF_ANNOTATE_BENIGN_RACE(&INTERNALTRACEEVENTUID(catstatic), \
- "trace_event category"); \
- if (!INTERNALTRACEEVENTUID(catstatic)) \
- INTERNALTRACEEVENTUID(catstatic) = \
- TRACE_EVENT_API_GET_CATEGORY_ENABLED(category);
-
-// Implementation detail: internal macro to create static category and add
-// event if the category is enabled.
-#define INTERNAL_TRACE_EVENT_ADD(phase, category, name, flags, ...) \
- do { \
- INTERNAL_TRACE_EVENT_GET_CATEGORY_INFO(category); \
- if (*INTERNALTRACEEVENTUID(catstatic)) { \
- WebCore::TraceEvent::addTraceEvent( \
- phase, INTERNALTRACEEVENTUID(catstatic), name, \
- WebCore::TraceEvent::noEventId, flags, ##__VA_ARGS__); \
- } \
- } while (0)
-
-// Implementation detail: internal macro to create static category and add begin
-// event if the category is enabled. Also adds the end event when the scope
-// ends.
-#define INTERNAL_TRACE_EVENT_ADD_SCOPED(category, name, ...) \
- INTERNAL_TRACE_EVENT_GET_CATEGORY_INFO(category); \
- WebCore::TraceEvent::TraceEndOnScopeClose \
- INTERNALTRACEEVENTUID(profileScope); \
- if (*INTERNALTRACEEVENTUID(catstatic)) { \
- WebCore::TraceEvent::addTraceEvent( \
- TRACE_EVENT_PHASE_BEGIN, \
- INTERNALTRACEEVENTUID(catstatic), \
- name, WebCore::TraceEvent::noEventId, \
- TRACE_EVENT_FLAG_NONE, ##__VA_ARGS__); \
- INTERNALTRACEEVENTUID(profileScope).initialize( \
- INTERNALTRACEEVENTUID(catstatic), name); \
- }
-
-// Implementation detail: internal macro to create static category and add
-// event if the category is enabled.
-#define INTERNAL_TRACE_EVENT_ADD_WITH_ID(phase, category, name, id, flags, \
- ...) \
- do { \
- INTERNAL_TRACE_EVENT_GET_CATEGORY_INFO(category); \
- if (*INTERNALTRACEEVENTUID(catstatic)) { \
- unsigned char traceEventFlags = flags | TRACE_EVENT_FLAG_HAS_ID; \
- WebCore::TraceEvent::TraceID traceEventTraceID( \
- id, &traceEventFlags); \
- WebCore::TraceEvent::addTraceEvent( \
- phase, INTERNALTRACEEVENTUID(catstatic), \
- name, traceEventTraceID.data(), traceEventFlags, \
- ##__VA_ARGS__); \
- } \
- } while (0)
-
-// Notes regarding the following definitions:
-// New values can be added and propagated to third party libraries, but existing
-// definitions must never be changed, because third party libraries may use old
-// definitions.
-
-// Phase indicates the nature of an event entry. E.g. part of a begin/end pair.
-#define TRACE_EVENT_PHASE_BEGIN ('B')
-#define TRACE_EVENT_PHASE_END ('E')
-#define TRACE_EVENT_PHASE_INSTANT ('I')
-#define TRACE_EVENT_PHASE_ASYNC_BEGIN ('S')
-#define TRACE_EVENT_PHASE_ASYNC_STEP ('T')
-#define TRACE_EVENT_PHASE_ASYNC_END ('F')
-#define TRACE_EVENT_PHASE_METADATA ('M')
-#define TRACE_EVENT_PHASE_COUNTER ('C')
-#define TRACE_EVENT_PHASE_SAMPLE ('P')
-#define TRACE_EVENT_PHASE_CREATE_OBJECT ('N')
-#define TRACE_EVENT_PHASE_DELETE_OBJECT ('D')
-
-// Flags for changing the behavior of TRACE_EVENT_API_ADD_TRACE_EVENT.
-#define TRACE_EVENT_FLAG_NONE (static_cast<unsigned char>(0))
-#define TRACE_EVENT_FLAG_COPY (static_cast<unsigned char>(1 << 0))
-#define TRACE_EVENT_FLAG_HAS_ID (static_cast<unsigned char>(1 << 1))
-#define TRACE_EVENT_FLAG_MANGLE_ID (static_cast<unsigned char>(1 << 2))
-
-// Type values for identifying types in the TraceValue union.
-#define TRACE_VALUE_TYPE_BOOL (static_cast<unsigned char>(1))
-#define TRACE_VALUE_TYPE_UINT (static_cast<unsigned char>(2))
-#define TRACE_VALUE_TYPE_INT (static_cast<unsigned char>(3))
-#define TRACE_VALUE_TYPE_DOUBLE (static_cast<unsigned char>(4))
-#define TRACE_VALUE_TYPE_POINTER (static_cast<unsigned char>(5))
-#define TRACE_VALUE_TYPE_STRING (static_cast<unsigned char>(6))
-#define TRACE_VALUE_TYPE_COPY_STRING (static_cast<unsigned char>(7))
-
-
-namespace WebCore {
-
-namespace TraceEvent {
-
-// Specify these values when the corresponding argument of addTraceEvent is not
-// used.
-const int zeroNumArgs = 0;
-const unsigned long long noEventId = 0;
-
-// TraceID encapsulates an ID that can either be an integer or pointer. Pointers
-// are mangled with the Process ID so that they are unlikely to collide when the
-// same pointer is used on different processes.
-class TraceID {
-public:
- template<bool dummyMangle> class MangleBehavior {
- public:
- template<typename T> explicit MangleBehavior(T id) : m_data(reinterpret_cast<unsigned long long>(id)) { }
- unsigned long long data() const { return m_data; }
- private:
- unsigned long long m_data;
- };
- typedef MangleBehavior<false> DontMangle;
- typedef MangleBehavior<true> ForceMangle;
-
- TraceID(const void* id, unsigned char* flags) :
- m_data(static_cast<unsigned long long>(reinterpret_cast<unsigned long>(id)))
- {
- *flags |= TRACE_EVENT_FLAG_MANGLE_ID;
- }
- TraceID(ForceMangle id, unsigned char* flags) : m_data(id.data())
- {
- *flags |= TRACE_EVENT_FLAG_MANGLE_ID;
- }
- TraceID(DontMangle id, unsigned char* flags) : m_data(id.data()) { UNUSED_PARAM(flags); }
- TraceID(unsigned long long id, unsigned char* flags) : m_data(id) { UNUSED_PARAM(flags); }
- TraceID(unsigned long id, unsigned char* flags) : m_data(id) { UNUSED_PARAM(flags); }
- TraceID(unsigned id, unsigned char* flags) : m_data(id) { UNUSED_PARAM(flags); }
- TraceID(unsigned short id, unsigned char* flags) : m_data(id) { UNUSED_PARAM(flags); }
- TraceID(unsigned char id, unsigned char* flags) : m_data(id) { UNUSED_PARAM(flags); }
- TraceID(long long id, unsigned char* flags) :
- m_data(static_cast<unsigned long long>(id)) { UNUSED_PARAM(flags); }
- TraceID(long id, unsigned char* flags) :
- m_data(static_cast<unsigned long long>(id)) { UNUSED_PARAM(flags); }
- TraceID(int id, unsigned char* flags) :
- m_data(static_cast<unsigned long long>(id)) { UNUSED_PARAM(flags); }
- TraceID(short id, unsigned char* flags) :
- m_data(static_cast<unsigned long long>(id)) { UNUSED_PARAM(flags); }
- TraceID(signed char id, unsigned char* flags) :
- m_data(static_cast<unsigned long long>(id)) { UNUSED_PARAM(flags); }
-
- unsigned long long data() const { return m_data; }
-
-private:
- unsigned long long m_data;
-};
-
-// Simple union to store various types as unsigned long long.
-union TraceValueUnion {
- bool m_bool;
- unsigned long long m_uint;
- long long m_int;
- double m_double;
- const void* m_pointer;
- const char* m_string;
-};
-
-// Simple container for const char* that should be copied instead of retained.
-class TraceStringWithCopy {
-public:
- explicit TraceStringWithCopy(const char* str) : m_str(str) { }
- operator const char* () const { return m_str; }
-private:
- const char* m_str;
-};
-
-// Define setTraceValue for each allowed type. It stores the type and
-// value in the return arguments. This allows this API to avoid declaring any
-// structures so that it is portable to third_party libraries.
-#define INTERNAL_DECLARE_SET_TRACE_VALUE(actual_type, \
- union_member, \
- value_type_id) \
- static inline void setTraceValue(actual_type arg, \
- unsigned char* type, \
- unsigned long long* value) { \
- TraceValueUnion typeValue; \
- typeValue.union_member = arg; \
- *type = value_type_id; \
- *value = typeValue.m_uint; \
- }
-// Simpler form for int types that can be safely casted.
-#define INTERNAL_DECLARE_SET_TRACE_VALUE_INT(actual_type, \
- value_type_id) \
- static inline void setTraceValue(actual_type arg, \
- unsigned char* type, \
- unsigned long long* value) { \
- *type = value_type_id; \
- *value = static_cast<unsigned long long>(arg); \
- }
-
-INTERNAL_DECLARE_SET_TRACE_VALUE_INT(unsigned long long, TRACE_VALUE_TYPE_UINT)
-INTERNAL_DECLARE_SET_TRACE_VALUE_INT(unsigned int, TRACE_VALUE_TYPE_UINT)
-INTERNAL_DECLARE_SET_TRACE_VALUE_INT(unsigned short, TRACE_VALUE_TYPE_UINT)
-INTERNAL_DECLARE_SET_TRACE_VALUE_INT(unsigned char, TRACE_VALUE_TYPE_UINT)
-INTERNAL_DECLARE_SET_TRACE_VALUE_INT(long long, TRACE_VALUE_TYPE_INT)
-INTERNAL_DECLARE_SET_TRACE_VALUE_INT(int, TRACE_VALUE_TYPE_INT)
-INTERNAL_DECLARE_SET_TRACE_VALUE_INT(short, TRACE_VALUE_TYPE_INT)
-INTERNAL_DECLARE_SET_TRACE_VALUE_INT(signed char, TRACE_VALUE_TYPE_INT)
-INTERNAL_DECLARE_SET_TRACE_VALUE(bool, m_bool, TRACE_VALUE_TYPE_BOOL)
-INTERNAL_DECLARE_SET_TRACE_VALUE(double, m_double, TRACE_VALUE_TYPE_DOUBLE)
-INTERNAL_DECLARE_SET_TRACE_VALUE(const void*, m_pointer,
- TRACE_VALUE_TYPE_POINTER)
-INTERNAL_DECLARE_SET_TRACE_VALUE(const char*, m_string,
- TRACE_VALUE_TYPE_STRING)
-INTERNAL_DECLARE_SET_TRACE_VALUE(const TraceStringWithCopy&, m_string,
- TRACE_VALUE_TYPE_COPY_STRING)
-
-#undef INTERNAL_DECLARE_SET_TRACE_VALUE
-#undef INTERNAL_DECLARE_SET_TRACE_VALUE_INT
-
-// WTF::String version of setTraceValue so that trace arguments can be strings.
-static inline void setTraceValue(const WTF::CString& arg,
- unsigned char* type,
- unsigned long long* value) {
- TraceValueUnion typeValue;
- typeValue.m_string = arg.data();
- *type = TRACE_VALUE_TYPE_COPY_STRING;
- *value = typeValue.m_uint;
-}
-
-// These addTraceEvent template functions are defined here instead of in the
-// macro, because the arg values could be temporary string objects. In order to
-// store pointers to the internal c_str and pass through to the tracing API, the
-// arg values must live throughout these procedures.
-
-static inline void addTraceEvent(char phase,
- const unsigned char* categoryEnabled,
- const char* name,
- unsigned long long id,
- unsigned char flags) {
- TRACE_EVENT_API_ADD_TRACE_EVENT(
- phase, categoryEnabled, name, id,
- zeroNumArgs, 0, 0, 0,
- flags);
-}
-
-template<class ARG1_TYPE>
-static inline void addTraceEvent(char phase,
- const unsigned char* categoryEnabled,
- const char* name,
- unsigned long long id,
- unsigned char flags,
- const char* arg1Name,
- const ARG1_TYPE& arg1Val) {
- const int numArgs = 1;
- unsigned char argTypes[1];
- unsigned long long argValues[1];
- setTraceValue(arg1Val, &argTypes[0], &argValues[0]);
- TRACE_EVENT_API_ADD_TRACE_EVENT(
- phase, categoryEnabled, name, id,
- numArgs, &arg1Name, argTypes, argValues,
- flags);
-}
-
-template<class ARG1_TYPE, class ARG2_TYPE>
-static inline void addTraceEvent(char phase,
- const unsigned char* categoryEnabled,
- const char* name,
- unsigned long long id,
- unsigned char flags,
- const char* arg1Name,
- const ARG1_TYPE& arg1Val,
- const char* arg2Name,
- const ARG2_TYPE& arg2Val) {
- const int numArgs = 2;
- const char* argNames[2] = { arg1Name, arg2Name };
- unsigned char argTypes[2];
- unsigned long long argValues[2];
- setTraceValue(arg1Val, &argTypes[0], &argValues[0]);
- setTraceValue(arg2Val, &argTypes[1], &argValues[1]);
- return TRACE_EVENT_API_ADD_TRACE_EVENT(
- phase, categoryEnabled, name, id,
- numArgs, argNames, argTypes, argValues,
- flags);
-}
-
-// Used by TRACE_EVENTx macro. Do not use directly.
-class TraceEndOnScopeClose {
-public:
- // Note: members of m_data intentionally left uninitialized. See initialize.
- TraceEndOnScopeClose() : m_pdata(0) { }
- ~TraceEndOnScopeClose()
- {
- if (m_pdata)
- addEventIfEnabled();
- }
-
- void initialize(const unsigned char* categoryEnabled,
- const char* name)
- {
- m_data.categoryEnabled = categoryEnabled;
- m_data.name = name;
- m_pdata = &m_data;
- }
-
-private:
- // Add the end event if the category is still enabled.
- void addEventIfEnabled()
- {
- // Only called when m_pdata is non-null.
- if (*m_pdata->categoryEnabled) {
- TRACE_EVENT_API_ADD_TRACE_EVENT(
- TRACE_EVENT_PHASE_END,
- m_pdata->categoryEnabled,
- m_pdata->name, noEventId,
- zeroNumArgs, 0, 0, 0,
- TRACE_EVENT_FLAG_NONE);
- }
- }
-
- // This Data struct workaround is to avoid initializing all the members
- // in Data during construction of this object, since this object is always
- // constructed, even when tracing is disabled. If the members of Data were
- // members of this class instead, compiler warnings occur about potential
- // uninitialized accesses.
- struct Data {
- const unsigned char* categoryEnabled;
- const char* name;
- };
- Data* m_pdata;
- Data m_data;
-};
-
-// TraceEventSamplingStateScope records the current sampling state
-// and sets a new sampling state. When the scope exists, it restores
-// the sampling state having recorded.
-template<size_t BucketNumber>
-class SamplingStateScope {
- WTF_MAKE_FAST_ALLOCATED;
-public:
- SamplingStateScope(const char* categoryAndName)
- {
- m_previousState = SamplingStateScope<BucketNumber>::current();
- SamplingStateScope<BucketNumber>::set(categoryAndName);
- }
-
- ~SamplingStateScope()
- {
- SamplingStateScope<BucketNumber>::set(m_previousState);
- }
-
- // FIXME: Make load/store to traceSamplingState[] thread-safe and atomic.
- static inline const char* current()
- {
- return reinterpret_cast<const char*>(*WebCore::traceSamplingState[BucketNumber]);
- }
- static inline void set(const char* categoryAndName)
- {
- *WebCore::traceSamplingState[BucketNumber] = reinterpret_cast<long>(const_cast<char*>(categoryAndName));
- }
-
-private:
- const char* m_previousState;
-};
-
-template<typename IDType> class TraceScopedTrackableObject {
- WTF_MAKE_NONCOPYABLE(TraceScopedTrackableObject);
-public:
- TraceScopedTrackableObject(const char* categoryGroup, const char* name, IDType id)
- : m_categoryGroup(categoryGroup), m_name(name), m_id(id)
- {
- TRACE_EVENT_OBJECT_CREATED_WITH_ID(m_categoryGroup, m_name, m_id);
- }
-
- ~TraceScopedTrackableObject()
- {
- TRACE_EVENT_OBJECT_DELETED_WITH_ID(m_categoryGroup, m_name, m_id);
- }
-
-private:
- const char* m_categoryGroup;
- const char* m_name;
- IDType m_id;
-};
-
-} // namespace TraceEvent
-
-} // namespace WebCore
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/support/Platform.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/support/Platform.cpp
deleted file mode 100644
index bf87d3e7323..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/support/Platform.cpp
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "public/platform/Platform.h"
-
-namespace WebKit {
-
-static Platform* s_platform = 0;
-
-void Platform::initialize(Platform* platform)
-{
- s_platform = platform;
-}
-
-void Platform::shutdown()
-{
- s_platform = 0;
-}
-
-Platform* Platform::current()
-{
- return s_platform;
-}
-
-} // namespace WebKit
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebActiveGestureAnimation.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebActiveGestureAnimation.cpp
deleted file mode 100644
index da27bb76b53..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebActiveGestureAnimation.cpp
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/chromium/support/WebActiveGestureAnimation.h"
-
-#include "public/platform/WebGestureCurve.h"
-#include "public/platform/WebGestureCurveTarget.h"
-
-namespace WebKit {
-
-PassOwnPtr<WebActiveGestureAnimation> WebActiveGestureAnimation::createAtAnimationStart(PassOwnPtr<WebGestureCurve> curve, WebGestureCurveTarget* target)
-{
- return adoptPtr(new WebActiveGestureAnimation(curve, target, 0, true));
-}
-
-PassOwnPtr<WebActiveGestureAnimation> WebActiveGestureAnimation::createWithTimeOffset(PassOwnPtr<WebGestureCurve> curve, WebGestureCurveTarget* target, double startTime)
-{
- return adoptPtr(new WebActiveGestureAnimation(curve, target, startTime, false));
-}
-
-WebActiveGestureAnimation::~WebActiveGestureAnimation()
-{
-}
-
-WebActiveGestureAnimation::WebActiveGestureAnimation(PassOwnPtr<WebGestureCurve> curve, WebGestureCurveTarget* target, double startTime, bool waitingForFirstTick)
- : m_startTime(startTime)
- , m_waitingForFirstTick(waitingForFirstTick)
- , m_curve(curve)
- , m_target(target)
-{
-}
-
-bool WebActiveGestureAnimation::animate(double time)
-{
- if (m_waitingForFirstTick) {
- m_startTime = time;
- m_waitingForFirstTick = false;
- }
- // All WebGestureCurves assume zero-based time, so we subtract
- // the animation start time before passing to the curve.
- return m_curve->apply(time - m_startTime, m_target);
-}
-
-} // namespace WebKit
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebActiveGestureAnimation.h b/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebActiveGestureAnimation.h
deleted file mode 100644
index 71a158e236c..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebActiveGestureAnimation.h
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef WebActiveGestureAnimation_h
-#define WebActiveGestureAnimation_h
-
-#include "wtf/Noncopyable.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/PassOwnPtr.h"
-
-namespace WebKit {
-
-class WebGestureCurve;
-class WebGestureCurveTarget;
-
-// Implements a gesture animation (fling scroll, etc.) using a curve with a generic interface
-// to define the animation parameters as a function of time, and applies the animation
-// to a target, again via a generic interface. It is assumed that animate() is called
-// on a more-or-less regular basis by the owner.
-class WebActiveGestureAnimation {
- WTF_MAKE_NONCOPYABLE(WebActiveGestureAnimation);
-public:
- static PassOwnPtr<WebActiveGestureAnimation> createAtAnimationStart(PassOwnPtr<WebGestureCurve>, WebGestureCurveTarget*);
- static PassOwnPtr<WebActiveGestureAnimation> createWithTimeOffset(PassOwnPtr<WebGestureCurve>, WebGestureCurveTarget*, double startTime);
- ~WebActiveGestureAnimation();
-
- bool animate(double time);
-
-private:
- // Assumes a valid WebGestureCurveTarget that outlives the animation.
- WebActiveGestureAnimation(PassOwnPtr<WebGestureCurve>, WebGestureCurveTarget*, double startTime, bool waitingForFirstTick);
-
- double m_startTime;
- bool m_waitingForFirstTick;
- OwnPtr<WebGestureCurve> m_curve;
- WebGestureCurveTarget* m_target;
-};
-
-} // namespace WebKit
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebArrayBuffer.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebArrayBuffer.cpp
index 3b01f5e1e9e..05429fe8fa0 100644
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebArrayBuffer.cpp
+++ b/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebArrayBuffer.cpp
@@ -37,7 +37,7 @@
using namespace WebCore;
-namespace WebKit {
+namespace blink {
WebArrayBuffer WebArrayBuffer::create(unsigned numElements, unsigned elementByteSize)
{
@@ -78,7 +78,7 @@ v8::Handle<v8::Value> WebArrayBuffer::toV8Value()
WebArrayBuffer* WebArrayBuffer::createFromV8Value(v8::Handle<v8::Value> value)
{
- if (!V8ArrayBuffer::HasInstanceInAnyWorld(value, v8::Isolate::GetCurrent()))
+ if (!V8ArrayBuffer::hasInstanceInAnyWorld(value, v8::Isolate::GetCurrent()))
return 0;
WTF::ArrayBuffer* buffer = V8ArrayBuffer::toNative(value->ToObject());
return new WebArrayBuffer(buffer);
@@ -100,4 +100,4 @@ WebArrayBuffer::operator WTF::PassRefPtr<WTF::ArrayBuffer>() const
return m_private.get();
}
-} // namespace WebKit
+} // namespace blink
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebAudioBus.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebAudioBus.cpp
deleted file mode 100644
index 56f7770f6e0..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebAudioBus.cpp
+++ /dev/null
@@ -1,151 +0,0 @@
-/*
- * Copyright (C) 2010, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "public/platform/WebAudioBus.h"
-
-#if ENABLE(WEB_AUDIO)
-#include "core/platform/audio/AudioBus.h"
-#else
-#include "wtf/ThreadSafeRefCounted.h"
-
-namespace WebCore {
-class AudioBus : public ThreadSafeRefCounted<AudioBus> {
-};
-} // namespace WebCore
-#endif
-
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefPtr.h"
-
-using namespace WebCore;
-
-namespace WebKit {
-
-class WebAudioBusPrivate : public AudioBus {
-};
-
-void WebAudioBus::initialize(unsigned numberOfChannels, size_t length, double sampleRate)
-{
-#if ENABLE(WEB_AUDIO)
- RefPtr<AudioBus> audioBus = AudioBus::create(numberOfChannels, length);
- audioBus->setSampleRate(sampleRate);
-
- if (m_private)
- (static_cast<AudioBus*>(m_private))->deref();
-
- audioBus->ref();
- m_private = static_cast<WebAudioBusPrivate*>(audioBus.get());
-#else
- ASSERT_NOT_REACHED();
-#endif
-}
-
-void WebAudioBus::resizeSmaller(size_t newLength)
-{
-#if ENABLE(WEB_AUDIO)
- ASSERT(m_private);
- if (m_private) {
- ASSERT(newLength <= length());
- m_private->resizeSmaller(newLength);
- }
-#else
- ASSERT_NOT_REACHED();
-#endif
-}
-
-void WebAudioBus::reset()
-{
-#if ENABLE(WEB_AUDIO)
- if (m_private) {
- (static_cast<AudioBus*>(m_private))->deref();
- m_private = 0;
- }
-#else
- ASSERT_NOT_REACHED();
-#endif
-}
-
-unsigned WebAudioBus::numberOfChannels() const
-{
-#if ENABLE(WEB_AUDIO)
- if (!m_private)
- return 0;
- return m_private->numberOfChannels();
-#else
- ASSERT_NOT_REACHED();
- return 0;
-#endif
-}
-
-size_t WebAudioBus::length() const
-{
-#if ENABLE(WEB_AUDIO)
- if (!m_private)
- return 0;
- return m_private->length();
-#else
- ASSERT_NOT_REACHED();
- return 0;
-#endif
-}
-
-double WebAudioBus::sampleRate() const
-{
-#if ENABLE(WEB_AUDIO)
- if (!m_private)
- return 0;
- return m_private->sampleRate();
-#else
- ASSERT_NOT_REACHED();
- return 0;
-#endif
-}
-
-float* WebAudioBus::channelData(unsigned channelIndex)
-{
-#if ENABLE(WEB_AUDIO)
- if (!m_private)
- return 0;
- ASSERT(channelIndex < numberOfChannels());
- return m_private->channel(channelIndex)->mutableData();
-#else
- ASSERT_NOT_REACHED();
- return 0;
-#endif
-}
-
-PassRefPtr<AudioBus> WebAudioBus::release()
-{
-#if ENABLE(WEB_AUDIO)
- RefPtr<AudioBus> audioBus(adoptRef(static_cast<AudioBus*>(m_private)));
- m_private = 0;
- return audioBus;
-#else
- ASSERT_NOT_REACHED();
- return 0;
-#endif
-}
-
-} // namespace WebKit
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebCString.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebCString.cpp
deleted file mode 100644
index a48abb41731..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebCString.cpp
+++ /dev/null
@@ -1,108 +0,0 @@
-/*
- * Copyright (C) 2009 Google Inc. All rights reserved.
- * Copyright (C) 2012 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "public/platform/WebCString.h"
-
-#include "public/platform/WebString.h"
-#include "wtf/text/CString.h"
-#include <string.h>
-
-namespace WebKit {
-
-int WebCString::compare(const WebCString& other) const
-{
- // A null string is always less than a non null one.
- if (isNull() != other.isNull())
- return isNull() ? -1 : 1;
-
- if (isNull())
- return 0; // Both WebStrings are null.
-
- return strcmp(m_private->data(), other.m_private->data());
-}
-
-void WebCString::reset()
-{
- m_private.reset();
-}
-
-void WebCString::assign(const WebCString& other)
-{
- assign(other.m_private.get());
-}
-
-void WebCString::assign(const char* data, size_t length)
-{
- char* newData;
- RefPtr<WTF::CStringBuffer> buffer =
- WTF::CString::newUninitialized(length, newData).buffer();
- memcpy(newData, data, length);
- assign(buffer.get());
-}
-
-size_t WebCString::length() const
-{
- return m_private.isNull() ? 0 : m_private->length();
-}
-
-const char* WebCString::data() const
-{
- return m_private.isNull() ? 0 : m_private->data();
-}
-
-WebString WebCString::utf16() const
-{
- return WebString::fromUTF8(data(), length());
-}
-
-WebCString::WebCString(const WTF::CString& s)
-{
- assign(s.buffer());
-}
-
-WebCString& WebCString::operator=(const WTF::CString& s)
-{
- assign(s.buffer());
- return *this;
-}
-
-WebCString::operator WTF::CString() const
-{
- return m_private.get();
-}
-
-void WebCString::assign(WTF::CStringBuffer* p)
-{
- m_private = p;
-}
-
-} // namespace WebKit
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebCrypto.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebCrypto.cpp
index db3a0ffe0e9..3fd68afd82a 100644
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebCrypto.cpp
+++ b/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebCrypto.cpp
@@ -31,11 +31,11 @@
#include "config.h"
#include "public/platform/WebCrypto.h"
-#include "modules/crypto/CryptoResult.h"
+#include "core/platform/CryptoResult.h"
#include "public/platform/WebArrayBuffer.h"
#include <string.h>
-namespace WebKit {
+namespace blink {
void WebCryptoResult::completeWithError()
{
@@ -52,7 +52,7 @@ void WebCryptoResult::completeWithBuffer(const WebArrayBuffer& buffer)
void WebCryptoResult::completeWithBuffer(const void* bytes, unsigned bytesSize)
{
- WebArrayBuffer buffer = WebKit::WebArrayBuffer::create(bytesSize, 1);
+ WebArrayBuffer buffer = blink::WebArrayBuffer::create(bytesSize, 1);
RELEASE_ASSERT(!buffer.isNull());
memcpy(buffer.data(), bytes, bytesSize);
completeWithBuffer(buffer);
@@ -66,12 +66,15 @@ void WebCryptoResult::completeWithBoolean(bool b)
void WebCryptoResult::completeWithKey(const WebCryptoKey& key)
{
+ ASSERT(!key.isNull());
m_impl->completeWithKey(key);
reset();
}
void WebCryptoResult::completeWithKeyPair(const WebCryptoKey& publicKey, const WebCryptoKey& privateKey)
{
+ ASSERT(!publicKey.isNull());
+ ASSERT(!privateKey.isNull());
m_impl->completeWithKeyPair(publicKey, privateKey);
reset();
}
@@ -92,4 +95,4 @@ void WebCryptoResult::assign(const WebCryptoResult& o)
m_impl = o.m_impl;
}
-} // namespace WebKit
+} // namespace blink
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebCryptoAlgorithm.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebCryptoAlgorithm.cpp
deleted file mode 100644
index 464dbae30bf..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebCryptoAlgorithm.cpp
+++ /dev/null
@@ -1,126 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "public/platform/WebCryptoAlgorithm.h"
-
-#include "public/platform/WebCryptoAlgorithmParams.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/ThreadSafeRefCounted.h"
-
-namespace WebKit {
-
-class WebCryptoAlgorithmPrivate : public ThreadSafeRefCounted<WebCryptoAlgorithmPrivate> {
-public:
- WebCryptoAlgorithmPrivate(WebCryptoAlgorithmId id, PassOwnPtr<WebCryptoAlgorithmParams> params)
- : id(id)
- , params(params)
- {
- }
-
- WebCryptoAlgorithmId id;
- OwnPtr<WebCryptoAlgorithmParams> params;
-};
-
-WebCryptoAlgorithm::WebCryptoAlgorithm(WebCryptoAlgorithmId id, PassOwnPtr<WebCryptoAlgorithmParams> params)
- : m_private(adoptRef(new WebCryptoAlgorithmPrivate(id, params)))
-{
-}
-
-WebCryptoAlgorithm WebCryptoAlgorithm::adoptParamsAndCreate(WebCryptoAlgorithmId id, WebCryptoAlgorithmParams* params)
-{
- return WebCryptoAlgorithm(id, adoptPtr(params));
-}
-
-WebCryptoAlgorithmId WebCryptoAlgorithm::id() const
-{
- return m_private->id;
-}
-
-WebCryptoAlgorithmParamsType WebCryptoAlgorithm::paramsType() const
-{
- if (!m_private->params)
- return WebCryptoAlgorithmParamsTypeNone;
- return m_private->params->type();
-}
-
-const WebCryptoAesCbcParams* WebCryptoAlgorithm::aesCbcParams() const
-{
- if (paramsType() == WebCryptoAlgorithmParamsTypeAesCbcParams)
- return static_cast<WebCryptoAesCbcParams*>(m_private->params.get());
- return 0;
-}
-
-const WebCryptoAesKeyGenParams* WebCryptoAlgorithm::aesKeyGenParams() const
-{
- if (paramsType() == WebCryptoAlgorithmParamsTypeAesKeyGenParams)
- return static_cast<WebCryptoAesKeyGenParams*>(m_private->params.get());
- return 0;
-}
-
-const WebCryptoHmacParams* WebCryptoAlgorithm::hmacParams() const
-{
- if (paramsType() == WebCryptoAlgorithmParamsTypeHmacParams)
- return static_cast<WebCryptoHmacParams*>(m_private->params.get());
- return 0;
-}
-
-const WebCryptoHmacKeyParams* WebCryptoAlgorithm::hmacKeyParams() const
-{
- if (paramsType() == WebCryptoAlgorithmParamsTypeHmacKeyParams)
- return static_cast<WebCryptoHmacKeyParams*>(m_private->params.get());
- return 0;
-}
-
-const WebCryptoRsaSsaParams* WebCryptoAlgorithm::rsaSsaParams() const
-{
- if (paramsType() == WebCryptoAlgorithmParamsTypeRsaSsaParams)
- return static_cast<WebCryptoRsaSsaParams*>(m_private->params.get());
- return 0;
-}
-
-const WebCryptoRsaKeyGenParams* WebCryptoAlgorithm::rsaKeyGenParams() const
-{
- if (paramsType() == WebCryptoAlgorithmParamsTypeRsaKeyGenParams)
- return static_cast<WebCryptoRsaKeyGenParams*>(m_private->params.get());
- return 0;
-}
-
-void WebCryptoAlgorithm::assign(const WebCryptoAlgorithm& other)
-{
- m_private = other.m_private;
-}
-
-void WebCryptoAlgorithm::reset()
-{
- m_private.reset();
-}
-
-} // namespace WebKit
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebCryptoKey.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebCryptoKey.cpp
deleted file mode 100644
index 64e3b9ce780..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebCryptoKey.cpp
+++ /dev/null
@@ -1,100 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "public/platform/WebCryptoKey.h"
-
-#include "public/platform/WebCryptoAlgorithm.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/ThreadSafeRefCounted.h"
-
-namespace WebKit {
-
-class WebCryptoKeyPrivate : public ThreadSafeRefCounted<WebCryptoKeyPrivate> {
-public:
- WebCryptoKeyPrivate(PassOwnPtr<WebCryptoKeyHandle> handle, WebCryptoKeyType type, bool extractable, const WebCryptoAlgorithm& algorithm, WebCryptoKeyUsageMask usages)
- : handle(handle)
- , type(type)
- , extractable(extractable)
- , algorithm(algorithm)
- , usages(usages)
- {
- }
-
- const OwnPtr<WebCryptoKeyHandle> handle;
- const WebCryptoKeyType type;
- const bool extractable;
- const WebCryptoAlgorithm algorithm;
- const WebCryptoKeyUsageMask usages;
-};
-
-WebCryptoKey WebCryptoKey::create(WebCryptoKeyHandle* handle, WebCryptoKeyType type, bool extractable, const WebCryptoAlgorithm& algorithm, WebCryptoKeyUsageMask usages)
-{
- WebCryptoKey key;
- key.m_private = adoptRef(new WebCryptoKeyPrivate(adoptPtr(handle), type, extractable, algorithm, usages));
- return key;
-}
-
-WebCryptoKeyHandle* WebCryptoKey::handle() const
-{
- return m_private->handle.get();
-}
-
-WebCryptoKeyType WebCryptoKey::type() const
-{
- return m_private->type;
-}
-
-bool WebCryptoKey::extractable() const
-{
- return m_private->extractable;
-}
-
-const WebCryptoAlgorithm& WebCryptoKey::algorithm() const
-{
- return m_private->algorithm;
-}
-
-WebCryptoKeyUsageMask WebCryptoKey::usages() const
-{
- return m_private->usages;
-}
-
-void WebCryptoKey::assign(const WebCryptoKey& other)
-{
- m_private = other.m_private;
-}
-
-void WebCryptoKey::reset()
-{
- m_private.reset();
-}
-
-} // namespace WebKit
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebCursorInfo.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebCursorInfo.cpp
deleted file mode 100644
index 0e7dfa51365..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebCursorInfo.cpp
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Copyright (C) 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "WebCursorInfo.h"
-
-#include "core/platform/Cursor.h"
-
-using namespace WebCore;
-
-namespace WebKit {
-
-WebCursorInfo::WebCursorInfo(const Cursor& cursor)
- : type(static_cast<Type>(cursor.type()))
- , hotSpot(cursor.hotSpot())
- , imageScaleFactor(cursor.imageScaleFactor())
- , customImage(cursor.image())
-#ifdef WIN32
- , externalHandle(0)
-#endif
-{
-}
-
-} // namespace WebKit
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebData.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebData.cpp
deleted file mode 100644
index 737bad74e2e..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebData.cpp
+++ /dev/null
@@ -1,108 +0,0 @@
-/*
- * Copyright (C) 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "public/platform/WebData.h"
-
-#include "core/platform/SharedBuffer.h"
-
-using namespace WebCore;
-
-namespace WebKit {
-
-class WebDataPrivate : public SharedBuffer {
-};
-
-void WebData::reset()
-{
- if (m_private) {
- m_private->deref();
- m_private = 0;
- }
-}
-
-void WebData::assign(const WebData& other)
-{
- WebDataPrivate* p = const_cast<WebDataPrivate*>(other.m_private);
- if (p)
- p->ref();
- assign(p);
-}
-
-void WebData::assign(const char* data, size_t size)
-{
- assign(static_cast<WebDataPrivate*>(
- SharedBuffer::create(data, size).leakRef()));
-}
-
-size_t WebData::size() const
-{
- if (!m_private)
- return 0;
- return const_cast<WebDataPrivate*>(m_private)->size();
-}
-
-const char* WebData::data() const
-{
- if (!m_private)
- return 0;
- return const_cast<WebDataPrivate*>(m_private)->data();
-}
-
-WebData::WebData(const PassRefPtr<SharedBuffer>& buffer)
- : m_private(static_cast<WebDataPrivate*>(buffer.leakRef()))
-{
-}
-
-WebData& WebData::operator=(const PassRefPtr<SharedBuffer>& buffer)
-{
- assign(static_cast<WebDataPrivate*>(buffer.leakRef()));
- return *this;
-}
-
-WebData::operator PassRefPtr<SharedBuffer>() const
-{
- return PassRefPtr<SharedBuffer>(const_cast<WebDataPrivate*>(m_private));
-}
-
-WebData::operator RefPtr<SharedBuffer>() const
-{
- return PassRefPtr<SharedBuffer>(const_cast<WebDataPrivate*>(m_private));
-}
-
-void WebData::assign(WebDataPrivate* p)
-{
- // p is already ref'd for us by the caller
- if (m_private)
- m_private->deref();
- m_private = p;
-}
-
-} // namespace WebKit
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebDeviceMotionData.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebDeviceMotionData.cpp
deleted file mode 100644
index 8d2595dd403..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebDeviceMotionData.cpp
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "public/platform/WebDeviceMotionData.h"
-
-#include <string.h>
-
-namespace WebKit {
-
-WebDeviceMotionData::WebDeviceMotionData()
-{
- // Make sure to zero out the memory so that there are no uninitialized bits.
- // This object is used in the shared memory buffer and is memory copied by
- // two processes. Valgrind will complain if we copy around memory that is
- // only partially initialized.
- memset(this, 0, sizeof(*this));
-}
-
-} // namespace WebKit
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebDeviceOrientationData.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebDeviceOrientationData.cpp
deleted file mode 100644
index 2e9817f9683..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebDeviceOrientationData.cpp
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "public/platform/WebDeviceOrientationData.h"
-
-#include <string.h>
-
-namespace WebKit {
-
-WebDeviceOrientationData::WebDeviceOrientationData()
-{
- // Make sure to zero out the memory so that there are no uninitialized bits.
- // This object is used in the shared memory buffer and is memory copied by
- // two processes. Valgrind will complain if we copy around memory that is
- // only partially initialized.
- memset(this, 0, sizeof(*this));
-}
-
-} // namespace WebKit
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebFileSystemCallbacks.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebFileSystemCallbacks.cpp
deleted file mode 100644
index 2430c54e4e0..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebFileSystemCallbacks.cpp
+++ /dev/null
@@ -1,158 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "public/platform/WebFileSystemCallbacks.h"
-
-#include "core/platform/AsyncFileSystemCallbacks.h"
-#include "core/platform/FileMetadata.h"
-#include "public/platform/WebFileInfo.h"
-#include "public/platform/WebFileSystem.h"
-#include "public/platform/WebFileSystemEntry.h"
-#include "public/platform/WebFileWriter.h"
-#include "public/platform/WebString.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-
-using namespace WebCore;
-
-namespace WebKit {
-
-class WebFileSystemCallbacksPrivate : public RefCounted<WebFileSystemCallbacksPrivate> {
-public:
- static PassRefPtr<WebFileSystemCallbacksPrivate> create(const PassOwnPtr<AsyncFileSystemCallbacks>& callbacks)
- {
- return adoptRef(new WebFileSystemCallbacksPrivate(callbacks));
- }
-
- AsyncFileSystemCallbacks* callbacks() { return m_callbacks.get(); }
-
-private:
- WebFileSystemCallbacksPrivate(const PassOwnPtr<AsyncFileSystemCallbacks>& callbacks) : m_callbacks(callbacks) { }
- OwnPtr<AsyncFileSystemCallbacks> m_callbacks;
-};
-
-WebFileSystemCallbacks::WebFileSystemCallbacks(const PassOwnPtr<AsyncFileSystemCallbacks>& callbacks)
-{
- m_private = WebFileSystemCallbacksPrivate::create(callbacks);
-}
-
-void WebFileSystemCallbacks::reset()
-{
- m_private.reset();
-}
-
-void WebFileSystemCallbacks::assign(const WebFileSystemCallbacks& other)
-{
- m_private = other.m_private;
-}
-
-void WebFileSystemCallbacks::didSucceed()
-{
- ASSERT(!m_private.isNull());
- m_private->callbacks()->didSucceed();
- m_private.reset();
-}
-
-void WebFileSystemCallbacks::didReadMetadata(const WebFileInfo& webFileInfo)
-{
- ASSERT(!m_private.isNull());
- FileMetadata fileMetadata;
- fileMetadata.modificationTime = webFileInfo.modificationTime;
- fileMetadata.length = webFileInfo.length;
- fileMetadata.type = static_cast<FileMetadata::Type>(webFileInfo.type);
- fileMetadata.platformPath = webFileInfo.platformPath;
- m_private->callbacks()->didReadMetadata(fileMetadata);
- m_private.reset();
-}
-
-void WebFileSystemCallbacks::didCreateSnapshotFile(const WebFileInfo& webFileInfo)
-{
- ASSERT(!m_private.isNull());
- // It's important to create a BlobDataHandle that refers to the platform file path prior
- // to return from this method so the underlying file will not be deleted.
- OwnPtr<BlobData> blobData = BlobData::create();
- blobData->appendFile(webFileInfo.platformPath);
- RefPtr<BlobDataHandle> snapshotBlob = BlobDataHandle::create(blobData.release(), webFileInfo.length);
-
- FileMetadata fileMetadata;
- fileMetadata.modificationTime = webFileInfo.modificationTime;
- fileMetadata.length = webFileInfo.length;
- fileMetadata.type = static_cast<FileMetadata::Type>(webFileInfo.type);
- fileMetadata.platformPath = webFileInfo.platformPath;
- m_private->callbacks()->didCreateSnapshotFile(fileMetadata, snapshotBlob);
- m_private.reset();
-}
-
-void WebFileSystemCallbacks::didReadDirectory(const WebVector<WebFileSystemEntry>& entries, bool hasMore)
-{
- ASSERT(!m_private.isNull());
- for (size_t i = 0; i < entries.size(); ++i)
- m_private->callbacks()->didReadDirectoryEntry(entries[i].name, entries[i].isDirectory);
- m_private->callbacks()->didReadDirectoryEntries(hasMore);
- m_private.reset();
-}
-
-void WebFileSystemCallbacks::didOpenFileSystem(const WebString& name, const WebURL& rootURL)
-{
- ASSERT(!m_private.isNull());
- m_private->callbacks()->didOpenFileSystem(name, rootURL);
- m_private.reset();
-}
-
-void WebFileSystemCallbacks::didResolveURL(const WebString& name, const WebURL& rootURL, WebFileSystemType type, const WebString& filePath, bool isDirectory)
-{
- ASSERT(!m_private.isNull());
- m_private->callbacks()->didResolveURL(name, rootURL, static_cast<WebCore::FileSystemType>(type), filePath, isDirectory);
- m_private.reset();
-}
-
-void WebFileSystemCallbacks::didCreateFileWriter(WebFileWriter* webFileWriter, long long length)
-{
- ASSERT(!m_private.isNull());
- m_private->callbacks()->didCreateFileWriter(adoptPtr(webFileWriter), length);
- m_private.reset();
-}
-
-void WebFileSystemCallbacks::didFail(WebFileError error)
-{
- ASSERT(!m_private.isNull());
- m_private->callbacks()->didFail(error);
- m_private.reset();
-}
-
-bool WebFileSystemCallbacks::shouldBlockUntilCompletion() const
-{
- ASSERT(!m_private.isNull());
- return m_private->callbacks()->shouldBlockUntilCompletion();
-}
-
-} // namespace WebKit
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebFloatQuad.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebFloatQuad.cpp
deleted file mode 100644
index 9bb616bfada..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebFloatQuad.cpp
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "public/platform/WebFloatQuad.h"
-
-#include <algorithm>
-#include <math.h>
-
-using namespace std;
-
-namespace WebKit {
-
-WebRect WebFloatQuad::enclosingRect() const
-{
- int left = static_cast<int>(floorf(min(min(min(p[0].x, p[1].x), p[2].x), p[3].x)));
- int top = static_cast<int>(floorf(min(min(min(p[0].y, p[1].y), p[2].y), p[3].y)));
- int right = static_cast<int>(ceilf(max(max(max(p[0].x, p[1].x), p[2].x), p[3].x)));
- int bottom = static_cast<int>(ceilf(max(max(max(p[0].y, p[1].y), p[2].y), p[3].y)));
-
- return WebRect(left, top, right - left, bottom - top);
-}
-
-} // namespace WebKit
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebHTTPBody.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebHTTPBody.cpp
deleted file mode 100644
index 0b1116defdd..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebHTTPBody.cpp
+++ /dev/null
@@ -1,212 +0,0 @@
-/*
- * Copyright (C) 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "public/platform/WebHTTPBody.h"
-
-#include "core/platform/FileSystem.h"
-#include "core/platform/network/FormData.h"
-
-using namespace WebCore;
-
-namespace WebKit {
-
-class WebHTTPBodyPrivate : public FormData {
-};
-
-void WebHTTPBody::initialize()
-{
- assign(static_cast<WebHTTPBodyPrivate*>(FormData::create().leakRef()));
-}
-
-void WebHTTPBody::reset()
-{
- assign(0);
-}
-
-void WebHTTPBody::assign(const WebHTTPBody& other)
-{
- WebHTTPBodyPrivate* p = const_cast<WebHTTPBodyPrivate*>(other.m_private);
- if (p)
- p->ref();
- assign(p);
-}
-
-size_t WebHTTPBody::elementCount() const
-{
- ASSERT(!isNull());
- return m_private->elements().size();
-}
-
-bool WebHTTPBody::elementAt(size_t index, Element& result) const
-{
- ASSERT(!isNull());
-
- if (index >= m_private->elements().size())
- return false;
-
- const FormDataElement& element = m_private->elements()[index];
-
- result.data.reset();
- result.filePath.reset();
- result.fileStart = 0;
- result.fileLength = 0;
- result.modificationTime = invalidFileTime();
- result.url = KURL();
- result.blobURL = KURL();
- result.blobUUID.reset();
-
- switch (element.m_type) {
- case FormDataElement::data:
- result.type = Element::TypeData;
- result.data.assign(element.m_data.data(), element.m_data.size());
- break;
- case FormDataElement::encodedFile:
- result.type = Element::TypeFile;
- result.filePath = element.m_filename;
- result.fileStart = element.m_fileStart;
- result.fileLength = element.m_fileLength;
- result.modificationTime = element.m_expectedFileModificationTime;
- break;
- case FormDataElement::encodedBlob:
- result.type = Element::TypeBlob;
- result.url = element.m_url; // DEPRECATED, should be able to remove after https://codereview.chromium.org/23223003/ lands
- result.blobURL = element.m_url; // FIXME: deprecate this.
- break;
- case FormDataElement::encodedURL:
- result.type = Element::TypeFileSystemURL;
- result.url = element.m_url; // DEPRECATED
- result.fileSystemURL = element.m_url;
- result.fileStart = element.m_fileStart;
- result.fileLength = element.m_fileLength;
- result.modificationTime = element.m_expectedFileModificationTime;
- break;
- default:
- ASSERT_NOT_REACHED();
- return false;
- }
-
- return true;
-}
-
-void WebHTTPBody::appendData(const WebData& data)
-{
- ensureMutable();
- // FIXME: FormDataElement::m_data should be a SharedBuffer<char>. Then we
- // could avoid this buffer copy.
- m_private->appendData(data.data(), data.size());
-}
-
-void WebHTTPBody::appendFile(const WebString& filePath)
-{
- ensureMutable();
- m_private->appendFile(filePath);
-}
-
-void WebHTTPBody::appendFileRange(const WebString& filePath, long long fileStart, long long fileLength, double modificationTime)
-{
- ensureMutable();
- m_private->appendFileRange(filePath, fileStart, fileLength, modificationTime);
-}
-
-void WebHTTPBody::appendFileSystemURLRange(const WebURL& url, long long start, long long length, double modificationTime)
-{
- // Currently we only support filesystem URL.
- ASSERT(KURL(url).protocolIs("filesystem"));
- ensureMutable();
- m_private->appendURLRange(url, start, length, modificationTime);
-}
-
-void WebHTTPBody::appendURLRange(const WebURL& url, long long start, long long length, double modificationTime)
-{
- appendFileSystemURLRange(url, start, length, modificationTime);
-}
-
-void WebHTTPBody::appendBlob(const WebURL& blobURL)
-{
- ASSERT(KURL(blobURL).protocolIs("blob"));
- ensureMutable();
- m_private->appendBlob(blobURL);
-}
-
-long long WebHTTPBody::identifier() const
-{
- ASSERT(!isNull());
- return m_private->identifier();
-}
-
-void WebHTTPBody::setIdentifier(long long identifier)
-{
- ensureMutable();
- return m_private->setIdentifier(identifier);
-}
-
-bool WebHTTPBody::containsPasswordData() const
-{
- return m_private->containsPasswordData();
-}
-
-void WebHTTPBody::setContainsPasswordData(bool containsPasswordData)
-{
- m_private->setContainsPasswordData(containsPasswordData);
-}
-
-WebHTTPBody::WebHTTPBody(const PassRefPtr<FormData>& data)
- : m_private(static_cast<WebHTTPBodyPrivate*>(data.leakRef()))
-{
-}
-
-WebHTTPBody& WebHTTPBody::operator=(const PassRefPtr<FormData>& data)
-{
- assign(static_cast<WebHTTPBodyPrivate*>(data.leakRef()));
- return *this;
-}
-
-WebHTTPBody::operator PassRefPtr<FormData>() const
-{
- return m_private;
-}
-
-void WebHTTPBody::assign(WebHTTPBodyPrivate* p)
-{
- // p is already ref'd for us by the caller
- if (m_private)
- m_private->deref();
- m_private = p;
-}
-
-void WebHTTPBody::ensureMutable()
-{
- ASSERT(!isNull());
- if (!m_private->hasOneRef())
- assign(static_cast<WebHTTPBodyPrivate*>(m_private->copy().leakRef()));
-}
-
-} // namespace WebKit
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebHTTPLoadInfo.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebHTTPLoadInfo.cpp
deleted file mode 100644
index e0b8267891a..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebHTTPLoadInfo.cpp
+++ /dev/null
@@ -1,147 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "public/platform/WebHTTPLoadInfo.h"
-
-#include "core/platform/network/ResourceLoadInfo.h"
-#include "public/platform/WebHTTPHeaderVisitor.h"
-#include "public/platform/WebString.h"
-
-using namespace WebCore;
-
-namespace WebKit {
-
-void WebHTTPLoadInfo::initialize()
-{
- m_private = adoptRef(new ResourceLoadInfo());
-}
-
-void WebHTTPLoadInfo::reset()
-{
- m_private.reset();
-}
-
-void WebHTTPLoadInfo::assign(const WebHTTPLoadInfo& r)
-{
- m_private = r.m_private;
-}
-
-WebHTTPLoadInfo::WebHTTPLoadInfo(WTF::PassRefPtr<WebCore::ResourceLoadInfo> value)
-{
- m_private = value;
-}
-
-WebHTTPLoadInfo::operator WTF::PassRefPtr<WebCore::ResourceLoadInfo>() const
-{
- return m_private.get();
-}
-
-int WebHTTPLoadInfo::httpStatusCode() const
-{
- ASSERT(!m_private.isNull());
- return m_private->httpStatusCode;
-}
-
-void WebHTTPLoadInfo::setHTTPStatusCode(int statusCode)
-{
- ASSERT(!m_private.isNull());
- m_private->httpStatusCode = statusCode;
-}
-
-WebString WebHTTPLoadInfo::httpStatusText() const
-{
- ASSERT(!m_private.isNull());
- return m_private->httpStatusText;
-}
-
-void WebHTTPLoadInfo::setHTTPStatusText(const WebString& statusText)
-{
- ASSERT(!m_private.isNull());
- m_private->httpStatusText = statusText;
-}
-
-long long WebHTTPLoadInfo::encodedDataLength() const
-{
- ASSERT(!m_private.isNull());
- return m_private->encodedDataLength;
-}
-
-void WebHTTPLoadInfo::setEncodedDataLength(long long encodedDataLength)
-{
- ASSERT(!m_private.isNull());
- m_private->encodedDataLength = encodedDataLength;
-}
-
-static void addHeader(HTTPHeaderMap* map, const WebString& name, const WebString& value)
-{
- HTTPHeaderMap::AddResult result = map->add(name, value);
- // It is important that values are separated by '\n', not comma, otherwise Set-Cookie header is not parseable.
- if (!result.isNewEntry)
- result.iterator->value = result.iterator->value + "\n" + String(value);
-}
-
-void WebHTTPLoadInfo::addRequestHeader(const WebString& name, const WebString& value)
-{
- ASSERT(!m_private.isNull());
- addHeader(&m_private->requestHeaders, name, value);
-}
-
-void WebHTTPLoadInfo::addResponseHeader(const WebString& name, const WebString& value)
-{
- ASSERT(!m_private.isNull());
- addHeader(&m_private->responseHeaders, name, value);
-}
-
-WebString WebHTTPLoadInfo::requestHeadersText() const
-{
- ASSERT(!m_private.isNull());
- return m_private->requestHeadersText;
-}
-
-void WebHTTPLoadInfo::setRequestHeadersText(const WebString& headersText)
-{
- ASSERT(!m_private.isNull());
- m_private->requestHeadersText = headersText;
-}
-
-WebString WebHTTPLoadInfo::responseHeadersText() const
-{
- ASSERT(!m_private.isNull());
- return m_private->responseHeadersText;
-}
-
-void WebHTTPLoadInfo::setResponseHeadersText(const WebString& headersText)
-{
- ASSERT(!m_private.isNull());
- m_private->responseHeadersText = headersText;
-}
-
-} // namespace WebKit
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebMediaConstraints.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebMediaConstraints.cpp
deleted file mode 100644
index d64ef773525..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebMediaConstraints.cpp
+++ /dev/null
@@ -1,108 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "public/platform/WebMediaConstraints.h"
-
-#include "core/platform/mediastream/MediaConstraints.h"
-
-using namespace WebCore;
-
-namespace WebKit {
-
-WebMediaConstraint::WebMediaConstraint(const WebCore::MediaConstraint& other)
- : m_name(other.m_name)
- , m_value(other.m_value)
-{
-}
-
-WebMediaConstraints::WebMediaConstraints(const PassRefPtr<MediaConstraints>& constraints)
- : m_private(constraints)
-{
-}
-
-WebMediaConstraints::WebMediaConstraints(MediaConstraints* constraints)
- : m_private(constraints)
-{
-}
-
-void WebMediaConstraints::assign(const WebMediaConstraints& other)
-{
- m_private = other.m_private;
-}
-
-void WebMediaConstraints::reset()
-{
- m_private.reset();
-}
-
-void WebMediaConstraints::getMandatoryConstraints(WebVector<WebMediaConstraint>& constraints) const
-{
- ASSERT(!isNull());
- Vector<MediaConstraint> mandatoryConstraints;
- m_private->getMandatoryConstraints(mandatoryConstraints);
- WebVector<WebMediaConstraint> result(mandatoryConstraints);
- constraints.swap(result);
-}
-
-void WebMediaConstraints::getOptionalConstraints(WebVector<WebMediaConstraint>& constraints) const
-{
- ASSERT(!isNull());
- Vector<MediaConstraint> optionalConstraints;
- m_private->getOptionalConstraints(optionalConstraints);
- WebVector<WebMediaConstraint> result(optionalConstraints);
- constraints.swap(result);
-}
-
-bool WebMediaConstraints::getMandatoryConstraintValue(const WebString& name, WebString& value) const
-{
- ASSERT(!isNull());
- String result;
- if (m_private->getMandatoryConstraintValue(name, result)) {
- value = result;
- return true;
- }
- return false;
-}
-
-bool WebMediaConstraints::getOptionalConstraintValue(const WebString& name, WebString& value) const
-{
- ASSERT(!isNull());
- String result;
- if (m_private->getOptionalConstraintValue(name, result)) {
- value = result;
- return true;
- }
- return false;
-}
-
-} // namespace WebKit
-
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebMediaStream.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebMediaStream.cpp
index d7ddd7bf49d..7572def9072 100644
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebMediaStream.cpp
+++ b/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebMediaStream.cpp
@@ -26,10 +26,10 @@
#include "public/platform/WebMediaStream.h"
-#include "core/platform/UUID.h"
-#include "core/platform/mediastream/MediaStreamComponent.h"
#include "core/platform/mediastream/MediaStreamDescriptor.h"
-#include "core/platform/mediastream/MediaStreamSource.h"
+#include "platform/UUID.h"
+#include "platform/mediastream/MediaStreamComponent.h"
+#include "platform/mediastream/MediaStreamSource.h"
#include "public/platform/WebMediaStreamSource.h"
#include "public/platform/WebMediaStreamTrack.h"
#include "public/platform/WebString.h"
@@ -39,7 +39,7 @@
using namespace WebCore;
-namespace WebKit {
+namespace blink {
namespace {
@@ -158,4 +158,4 @@ void WebMediaStream::assign(const WebMediaStream& other)
m_private = other.m_private;
}
-} // namespace WebKit
+} // namespace blink
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebMediaStreamSource.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebMediaStreamSource.cpp
deleted file mode 100644
index 96646ffee19..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebMediaStreamSource.cpp
+++ /dev/null
@@ -1,246 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "public/platform/WebMediaStreamSource.h"
-
-#include "core/platform/audio/AudioBus.h"
-#include "core/platform/mediastream/MediaConstraints.h"
-#include "core/platform/mediastream/MediaStreamSource.h"
-#include "public/platform/WebAudioDestinationConsumer.h"
-#include "public/platform/WebMediaConstraints.h"
-#include "public/platform/WebString.h"
-#include "wtf/MainThread.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/Vector.h"
-
-using namespace WebCore;
-
-namespace WebKit {
-
-namespace {
-
-class ExtraDataContainer : public MediaStreamSource::ExtraData {
-public:
- ExtraDataContainer(WebMediaStreamSource::ExtraData* extraData) : m_extraData(adoptPtr(extraData)) { }
-
- WebMediaStreamSource::ExtraData* extraData() { return m_extraData.get(); }
-
-private:
- OwnPtr<WebMediaStreamSource::ExtraData> m_extraData;
-};
-
-} // namespace
-
-WebMediaStreamSource WebMediaStreamSource::ExtraData::owner()
-{
- ASSERT(m_owner);
- return WebMediaStreamSource(m_owner);
-}
-
-void WebMediaStreamSource::ExtraData::setOwner(WebCore::MediaStreamSource* owner)
-{
- ASSERT(!m_owner);
- m_owner = owner;
-}
-
-WebMediaStreamSource::WebMediaStreamSource(const PassRefPtr<MediaStreamSource>& mediaStreamSource)
- : m_private(mediaStreamSource)
-{
-}
-
-WebMediaStreamSource& WebMediaStreamSource::operator=(WebCore::MediaStreamSource* mediaStreamSource)
-{
- m_private = mediaStreamSource;
- return *this;
-}
-
-void WebMediaStreamSource::assign(const WebMediaStreamSource& other)
-{
- m_private = other.m_private;
-}
-
-void WebMediaStreamSource::reset()
-{
- m_private.reset();
-}
-
-WebMediaStreamSource::operator PassRefPtr<MediaStreamSource>() const
-{
- return m_private.get();
-}
-
-WebMediaStreamSource::operator MediaStreamSource*() const
-{
- return m_private.get();
-}
-
-void WebMediaStreamSource::initialize(const WebString& id, Type type, const WebString& name)
-{
- m_private = MediaStreamSource::create(id, static_cast<MediaStreamSource::Type>(type), name);
-}
-
-WebString WebMediaStreamSource::id() const
-{
- ASSERT(!m_private.isNull());
- return m_private.get()->id();
-}
-
-WebMediaStreamSource::Type WebMediaStreamSource::type() const
-{
- ASSERT(!m_private.isNull());
- return static_cast<Type>(m_private.get()->type());
-}
-
-WebString WebMediaStreamSource::name() const
-{
- ASSERT(!m_private.isNull());
- return m_private.get()->name();
-}
-
-void WebMediaStreamSource::setReadyState(ReadyState state)
-{
- ASSERT(!m_private.isNull());
- m_private->setReadyState(static_cast<MediaStreamSource::ReadyState>(state));
-}
-
-WebMediaStreamSource::ReadyState WebMediaStreamSource::readyState() const
-{
- ASSERT(!m_private.isNull());
- return static_cast<ReadyState>(m_private->readyState());
-}
-
-WebMediaStreamSource::ExtraData* WebMediaStreamSource::extraData() const
-{
- ASSERT(!m_private.isNull());
- MediaStreamSource::ExtraData* data = m_private->extraData();
- if (!data)
- return 0;
- return static_cast<ExtraDataContainer*>(data)->extraData();
-}
-
-void WebMediaStreamSource::setExtraData(ExtraData* extraData)
-{
- ASSERT(!m_private.isNull());
-
- if (extraData)
- extraData->setOwner(m_private.get());
-
- m_private->setExtraData(new ExtraDataContainer(extraData));
-}
-
-WebMediaConstraints WebMediaStreamSource::constraints()
-{
- ASSERT(!m_private.isNull());
- return m_private->constraints();
-}
-
-WebString WebMediaStreamSource::deviceId() const
-{
- ASSERT(!m_private.isNull());
- return m_private->deviceId();
-}
-
-void WebMediaStreamSource::setDeviceId(const WebString& deviceId)
-{
- ASSERT(!m_private.isNull());
- m_private->setDeviceId(deviceId);
-}
-
-bool WebMediaStreamSource::requiresAudioConsumer() const
-{
- ASSERT(!m_private.isNull());
- return m_private->requiresAudioConsumer();
-}
-
-class ConsumerWrapper : public WebCore::AudioDestinationConsumer {
-public:
- static PassRefPtr<ConsumerWrapper> create(WebAudioDestinationConsumer* consumer)
- {
- return adoptRef(new ConsumerWrapper(consumer));
- }
-
- virtual void setFormat(size_t numberOfChannels, float sampleRate) OVERRIDE;
- virtual void consumeAudio(AudioBus*, size_t numberOfFrames) OVERRIDE;
-
- WebAudioDestinationConsumer* consumer() { return m_consumer; }
-
-private:
- explicit ConsumerWrapper(WebAudioDestinationConsumer* consumer) : m_consumer(consumer) { }
-
- // m_consumer is not owned by this class.
- WebAudioDestinationConsumer* m_consumer;
-};
-
-void ConsumerWrapper::setFormat(size_t numberOfChannels, float sampleRate)
-{
- m_consumer->setFormat(numberOfChannels, sampleRate);
-}
-
-void ConsumerWrapper::consumeAudio(AudioBus* bus, size_t numberOfFrames)
-{
- if (!bus)
- return;
-
- // Wrap AudioBus.
- size_t numberOfChannels = bus->numberOfChannels();
- WebKit::WebVector<const float*> busVector(numberOfChannels);
- for (size_t i = 0; i < numberOfChannels; ++i)
- busVector[i] = bus->channel(i)->data();
-
- m_consumer->consumeAudio(busVector, numberOfFrames);
-}
-
-void WebMediaStreamSource::addAudioConsumer(WebAudioDestinationConsumer* consumer)
-{
- ASSERT(isMainThread());
- ASSERT(!m_private.isNull() && consumer);
-
- m_private->addAudioConsumer(ConsumerWrapper::create(consumer));
-}
-
-bool WebMediaStreamSource::removeAudioConsumer(WebAudioDestinationConsumer* consumer)
-{
- ASSERT(isMainThread());
- ASSERT(!m_private.isNull() && consumer);
-
- const Vector<RefPtr<AudioDestinationConsumer> >& consumers = m_private->audioConsumers();
- for (Vector<RefPtr<AudioDestinationConsumer> >::const_iterator it = consumers.begin(); it != consumers.end(); ++it) {
- ConsumerWrapper* wrapper = static_cast<ConsumerWrapper*>((*it).get());
- if (wrapper->consumer() == consumer) {
- m_private->removeAudioConsumer(wrapper);
- return true;
- }
- }
- return false;
-}
-
-} // namespace WebKit
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebMediaStreamTrack.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebMediaStreamTrack.cpp
index 8da7cbdf04f..39dabdfa8f3 100644
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebMediaStreamTrack.cpp
+++ b/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebMediaStreamTrack.cpp
@@ -26,17 +26,31 @@
#include "public/platform/WebMediaStreamTrack.h"
-#include "core/platform/mediastream/MediaStreamComponent.h"
-#include "core/platform/mediastream/MediaStreamSource.h"
+#include "platform/mediastream/MediaStreamComponent.h"
+#include "platform/mediastream/MediaStreamSource.h"
+#include "public/platform/WebAudioSourceProvider.h"
#include "public/platform/WebMediaStream.h"
#include "public/platform/WebMediaStreamSource.h"
#include "public/platform/WebString.h"
-#include "public/web/WebAudioSourceProvider.h"
#include "wtf/Vector.h"
using namespace WebCore;
-namespace WebKit {
+namespace blink {
+
+namespace {
+
+class ExtraDataContainer : public MediaStreamComponent::ExtraData {
+public:
+ explicit ExtraDataContainer(PassOwnPtr<WebMediaStreamTrack::ExtraData> extraData) : m_extraData(extraData) { }
+
+ WebMediaStreamTrack::ExtraData* extraData() { return m_extraData.get(); }
+
+private:
+ OwnPtr<WebMediaStreamTrack::ExtraData> m_extraData;
+};
+
+} // namespace
WebMediaStreamTrack::WebMediaStreamTrack(PassRefPtr<WebCore::MediaStreamComponent> mediaStreamComponent)
: m_private(mediaStreamComponent)
@@ -103,6 +117,19 @@ WebMediaStreamSource WebMediaStreamTrack::source() const
return WebMediaStreamSource(m_private->source());
}
+WebMediaStreamTrack::ExtraData* WebMediaStreamTrack::extraData() const
+{
+ RefPtr<MediaStreamComponent::ExtraData> data = m_private->extraData();
+ if (!data)
+ return 0;
+ return static_cast<ExtraDataContainer*>(data.get())->extraData();
+}
+
+void WebMediaStreamTrack::setExtraData(ExtraData* extraData)
+{
+ m_private->setExtraData(adoptRef(new ExtraDataContainer(adoptPtr(extraData))));
+}
+
void WebMediaStreamTrack::setSourceProvider(WebAudioSourceProvider* provider)
{
#if ENABLE(WEB_AUDIO)
@@ -116,4 +143,4 @@ void WebMediaStreamTrack::assign(const WebMediaStreamTrack& other)
m_private = other.m_private;
}
-} // namespace WebKit
+} // namespace blink
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebPrerender.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebPrerender.cpp
deleted file mode 100644
index 55d354e4a9f..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebPrerender.cpp
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "public/platform/WebPrerender.h"
-#include "wtf/PassRefPtr.h"
-
-#include "core/platform/chromium/Prerender.h"
-
-namespace WebKit {
-
-namespace {
-
-class ExtraDataContainer : public WebCore::Prerender::ExtraData {
-public:
- static PassRefPtr<ExtraDataContainer> create(WebPrerender::ExtraData* extraData) { return adoptRef(new ExtraDataContainer(extraData)); }
-
- virtual ~ExtraDataContainer() { }
-
- WebPrerender::ExtraData* extraData() const { return m_extraData.get(); }
-
-private:
- explicit ExtraDataContainer(WebPrerender::ExtraData* extraData)
- : m_extraData(adoptPtr(extraData))
- {
- }
-
- OwnPtr<WebPrerender::ExtraData> m_extraData;
-};
-
-} // anon namespace
-
-WebPrerender::WebPrerender(PassRefPtr<WebCore::Prerender> prerender)
- : m_private(prerender)
-{
-}
-
-const WebCore::Prerender* WebPrerender::toPrerender() const
-{
- return m_private.get();
-}
-
-void WebPrerender::reset()
-{
- m_private.reset();
-}
-
-void WebPrerender::assign(const WebPrerender& other)
-{
- m_private = other.m_private;
-}
-
-bool WebPrerender::isNull() const
-{
- return m_private.isNull();
-}
-
-WebURL WebPrerender::url() const
-{
- return WebURL(m_private->url());
-}
-
-WebString WebPrerender::referrer() const
-{
- return m_private->referrer();
-}
-
-WebReferrerPolicy WebPrerender::referrerPolicy() const
-{
- return static_cast<WebReferrerPolicy>(m_private->referrerPolicy());
-}
-
-void WebPrerender::setExtraData(WebPrerender::ExtraData* extraData)
-{
- m_private->setExtraData(ExtraDataContainer::create(extraData));
-}
-
-const WebPrerender::ExtraData* WebPrerender::extraData() const
-{
- RefPtr<WebCore::Prerender::ExtraData> webcoreExtraData = m_private->extraData();
- if (!webcoreExtraData)
- return 0;
- return static_cast<ExtraDataContainer*>(webcoreExtraData.get())->extraData();
-}
-
-void WebPrerender::didStartPrerender()
-{
- m_private->didStartPrerender();
-}
-
-void WebPrerender::didStopPrerender()
-{
- m_private->didStopPrerender();
-}
-
-void WebPrerender::didSendLoadForPrerender()
-{
- m_private->didSendLoadForPrerender();
-}
-
-void WebPrerender::didSendDOMContentLoadedForPrerender()
-{
- m_private->didSendDOMContentLoadedForPrerender();
-}
-
-} // namespace WebKit
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebPrerenderingSupport.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebPrerenderingSupport.cpp
deleted file mode 100644
index a8cbfc4f413..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebPrerenderingSupport.cpp
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "public/platform/WebPrerenderingSupport.h"
-
-namespace WebKit {
-
-WebPrerenderingSupport* WebPrerenderingSupport::s_platform = 0;
-
-void WebPrerenderingSupport::initialize(WebPrerenderingSupport* platform)
-{
- s_platform = platform;
-}
-
-void WebPrerenderingSupport::shutdown()
-{
- s_platform = 0;
-}
-
-WebPrerenderingSupport* WebPrerenderingSupport::current()
-{
- return s_platform;
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebRTCConfiguration.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebRTCConfiguration.cpp
deleted file mode 100644
index 57d0d009dac..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebRTCConfiguration.cpp
+++ /dev/null
@@ -1,104 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "public/platform/WebRTCConfiguration.h"
-
-#include "core/platform/mediastream/RTCConfiguration.h"
-#include "public/platform/WebString.h"
-#include "public/platform/WebURL.h"
-#include "public/platform/WebVector.h"
-
-using namespace WebCore;
-
-namespace WebKit {
-
-WebRTCICEServer::WebRTCICEServer(const PassRefPtr<RTCIceServer>& iceServer)
- : m_private(iceServer)
-{
-}
-
-void WebRTCICEServer::assign(const WebRTCICEServer& other)
-{
- m_private = other.m_private;
-}
-
-void WebRTCICEServer::reset()
-{
- m_private.reset();
-}
-
-WebURL WebRTCICEServer::uri() const
-{
- ASSERT(!isNull());
- return m_private->uri();
-}
-
-WebString WebRTCICEServer::username() const
-{
- ASSERT(!isNull());
- return m_private->username();
-}
-
-WebString WebRTCICEServer::credential() const
-{
- ASSERT(!isNull());
- return m_private->credential();
-}
-
-WebRTCConfiguration::WebRTCConfiguration(const PassRefPtr<RTCConfiguration>& configuration)
- : m_private(configuration)
-{
-}
-
-void WebRTCConfiguration::assign(const WebRTCConfiguration& other)
-{
- m_private = other.m_private;
-}
-
-void WebRTCConfiguration::reset()
-{
- m_private.reset();
-}
-
-size_t WebRTCConfiguration::numberOfServers() const
-{
- ASSERT(!isNull());
- return m_private->numberOfServers();
-}
-
-WebRTCICEServer WebRTCConfiguration::server(size_t index) const
-{
- ASSERT(!isNull());
- return WebRTCICEServer(m_private->server(index));
-}
-
-} // namespace WebKit
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebRTCICECandidate.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebRTCICECandidate.cpp
deleted file mode 100644
index 755e9410696..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebRTCICECandidate.cpp
+++ /dev/null
@@ -1,105 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "public/platform/WebRTCICECandidate.h"
-
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-#include "public/platform/WebString.h"
-
-namespace WebKit {
-
-class WebRTCICECandidatePrivate : public RefCounted<WebRTCICECandidatePrivate> {
-public:
- static PassRefPtr<WebRTCICECandidatePrivate> create(const WebString& candidate, const WebString& sdpMid, unsigned short sdpMLineIndex)
- {
- return adoptRef(new WebRTCICECandidatePrivate(candidate, sdpMid, sdpMLineIndex));
- }
- virtual ~WebRTCICECandidatePrivate();
-
- const WebString& candidate() const { return m_candidate; }
- const WebString& sdpMid() const { return m_sdpMid; }
- unsigned short sdpMLineIndex() const { return m_sdpMLineIndex; }
-
-private:
- WebRTCICECandidatePrivate(const WebString& candidate, const WebString& sdpMid, unsigned short sdpMLineIndex);
-
- WebString m_candidate;
- WebString m_sdpMid;
- unsigned short m_sdpMLineIndex;
-};
-
-WebRTCICECandidatePrivate::WebRTCICECandidatePrivate(const WebString& candidate, const WebString& sdpMid, unsigned short sdpMLineIndex)
- : m_candidate(candidate)
- , m_sdpMid(sdpMid)
- , m_sdpMLineIndex(sdpMLineIndex)
-{
-}
-
-WebRTCICECandidatePrivate::~WebRTCICECandidatePrivate()
-{
-}
-
-void WebRTCICECandidate::assign(const WebRTCICECandidate& other)
-{
- m_private = other.m_private;
-}
-
-void WebRTCICECandidate::reset()
-{
- m_private.reset();
-}
-
-void WebRTCICECandidate::initialize(const WebString& candidate, const WebString& sdpMid, unsigned short sdpMLineIndex)
-{
- m_private = WebRTCICECandidatePrivate::create(candidate, sdpMid, sdpMLineIndex);
-}
-
-WebString WebRTCICECandidate::candidate() const
-{
- ASSERT(!m_private.isNull());
- return m_private->candidate();
-}
-
-WebString WebRTCICECandidate::sdpMid() const
-{
- ASSERT(!m_private.isNull());
- return m_private->sdpMid();
-}
-
-unsigned short WebRTCICECandidate::sdpMLineIndex() const
-{
- ASSERT(!m_private.isNull());
- return m_private->sdpMLineIndex();
-}
-
-} // namespace WebKit
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebRTCSessionDescription.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebRTCSessionDescription.cpp
index 8e2921342d8..1fc0cafec96 100644
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebRTCSessionDescription.cpp
+++ b/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebRTCSessionDescription.cpp
@@ -36,12 +36,11 @@
#include "wtf/RefCounted.h"
#include "public/platform/WebString.h"
-namespace WebKit {
+namespace blink {
-class WebRTCSessionDescriptionPrivate : public RefCounted<WebRTCSessionDescriptionPrivate> {
+class WebRTCSessionDescriptionPrivate FINAL : public RefCounted<WebRTCSessionDescriptionPrivate> {
public:
static PassRefPtr<WebRTCSessionDescriptionPrivate> create(const WebString& type, const WebString& sdp);
- virtual ~WebRTCSessionDescriptionPrivate();
WebString type() { return m_type; }
void setType(const WebString& type) { m_type = type; }
@@ -67,10 +66,6 @@ WebRTCSessionDescriptionPrivate::WebRTCSessionDescriptionPrivate(const WebString
{
}
-WebRTCSessionDescriptionPrivate::~WebRTCSessionDescriptionPrivate()
-{
-}
-
void WebRTCSessionDescription::assign(const WebRTCSessionDescription& other)
{
m_private = other.m_private;
@@ -110,5 +105,5 @@ void WebRTCSessionDescription::setSDP(const WebString& sdp)
return m_private->setSdp(sdp);
}
-} // namespace WebKit
+} // namespace blink
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebRTCSessionDescriptionRequest.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebRTCSessionDescriptionRequest.cpp
index 7575a51d90f..b35f305ff1f 100644
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebRTCSessionDescriptionRequest.cpp
+++ b/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebRTCSessionDescriptionRequest.cpp
@@ -32,13 +32,13 @@
#include "public/platform/WebRTCSessionDescriptionRequest.h"
-#include "core/platform/mediastream/RTCSessionDescriptionRequest.h"
+#include "platform/mediastream/RTCSessionDescriptionRequest.h"
#include "public/platform/WebRTCSessionDescription.h"
#include "wtf/PassOwnPtr.h"
using namespace WebCore;
-namespace WebKit {
+namespace blink {
namespace {
@@ -94,5 +94,5 @@ void WebRTCSessionDescriptionRequest::setExtraData(ExtraData* extraData)
m_private->setExtraData(adoptRef(new ExtraDataContainer(extraData)));
}
-} // namespace WebKit
+} // namespace blink
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebRTCStatsRequest.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebRTCStatsRequest.cpp
index c5c925a5e7a..617bd56256c 100644
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebRTCStatsRequest.cpp
+++ b/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebRTCStatsRequest.cpp
@@ -41,7 +41,7 @@
using namespace WebCore;
-namespace WebKit {
+namespace blink {
WebRTCStatsRequest::WebRTCStatsRequest(const PassRefPtr<RTCStatsRequest>& request)
: m_private(request)
@@ -83,4 +83,4 @@ void WebRTCStatsRequest::requestSucceeded(const WebRTCStatsResponse& response) c
m_private->requestSucceeded(response);
}
-} // namespace WebKit
+} // namespace blink
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebRTCStatsResponse.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebRTCStatsResponse.cpp
deleted file mode 100644
index 59a61911623..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebRTCStatsResponse.cpp
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "public/platform/WebRTCStatsResponse.h"
-
-#include "core/platform/mediastream/RTCStatsResponseBase.h"
-#include "wtf/PassOwnPtr.h"
-
-using namespace WebCore;
-
-namespace WebKit {
-
-WebRTCStatsResponse::WebRTCStatsResponse(const PassRefPtr<RTCStatsResponseBase>& request)
- : m_private(request)
-{
-}
-
-void WebRTCStatsResponse::assign(const WebRTCStatsResponse& other)
-{
- m_private = other.m_private;
-}
-
-void WebRTCStatsResponse::reset()
-{
- m_private.reset();
-}
-
-WebRTCStatsResponse::operator WTF::PassRefPtr<WebCore::RTCStatsResponseBase>() const
-{
- return m_private.get();
-}
-
-size_t WebRTCStatsResponse::addReport(WebString id, WebString type, double timestamp)
-{
- ASSERT(!m_private.isNull());
- return m_private->addReport(id, type, timestamp);
-}
-
-void WebRTCStatsResponse::addStatistic(size_t report, WebString name, WebString value)
-{
- ASSERT(!m_private.isNull());
- m_private->addStatistic(report, name, value);
-}
-
-} // namespace WebKit
-
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebRTCVoidRequest.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebRTCVoidRequest.cpp
deleted file mode 100644
index 0f5603b50f5..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebRTCVoidRequest.cpp
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "public/platform/WebRTCVoidRequest.h"
-
-#include "core/platform/mediastream/RTCVoidRequest.h"
-#include "wtf/PassOwnPtr.h"
-
-using namespace WebCore;
-
-namespace WebKit {
-
-namespace {
-
-class ExtraDataContainer : public RTCVoidRequest::ExtraData {
-public:
- ExtraDataContainer(WebRTCVoidRequest::ExtraData* extraData) : m_extraData(adoptPtr(extraData)) { }
-
- WebRTCVoidRequest::ExtraData* extraData() { return m_extraData.get(); }
-
-private:
- OwnPtr<WebRTCVoidRequest::ExtraData> m_extraData;
-};
-
-} // namespace
-
-WebRTCVoidRequest::WebRTCVoidRequest(const PassRefPtr<RTCVoidRequest>& constraints)
- : m_private(constraints)
-{
-}
-
-void WebRTCVoidRequest::assign(const WebRTCVoidRequest& other)
-{
- m_private = other.m_private;
-}
-
-void WebRTCVoidRequest::reset()
-{
- m_private.reset();
-}
-
-void WebRTCVoidRequest::requestSucceeded() const
-{
- ASSERT(m_private.get());
- m_private->requestSucceeded();
-}
-
-void WebRTCVoidRequest::requestFailed(const WebString& error) const
-{
- ASSERT(m_private.get());
- m_private->requestFailed(error);
-}
-
-WebRTCVoidRequest::ExtraData* WebRTCVoidRequest::extraData() const
-{
- RefPtr<RTCVoidRequest::ExtraData> data = m_private->extraData();
- if (!data)
- return 0;
- return static_cast<ExtraDataContainer*>(data.get())->extraData();
-}
-
-void WebRTCVoidRequest::setExtraData(ExtraData* extraData)
-{
- m_private->setExtraData(adoptRef(new ExtraDataContainer(extraData)));
-}
-
-} // namespace WebKit
-
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebScrollbarImpl.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebScrollbarImpl.cpp
deleted file mode 100644
index 6e5258dee74..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebScrollbarImpl.cpp
+++ /dev/null
@@ -1,141 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/platform/chromium/support/WebScrollbarImpl.h"
-
-#include "core/platform/Scrollbar.h"
-#include "core/platform/graphics/IntRect.h"
-
-namespace WebKit {
-
-WebScrollbarImpl::WebScrollbarImpl(WebCore::Scrollbar* scrollbar)
- : m_scrollbar(scrollbar)
-{
-}
-
-bool WebScrollbarImpl::isOverlay() const
-{
- return m_scrollbar->isOverlayScrollbar();
-}
-
-int WebScrollbarImpl::value() const
-{
- return m_scrollbar->value();
-}
-
-WebPoint WebScrollbarImpl::location() const
-{
- return m_scrollbar->location();
-}
-
-WebSize WebScrollbarImpl::size() const
-{
- return m_scrollbar->size();
-}
-
-bool WebScrollbarImpl::enabled() const
-{
- return m_scrollbar->enabled();
-}
-
-int WebScrollbarImpl::maximum() const
-{
- return m_scrollbar->maximum();
-}
-
-int WebScrollbarImpl::totalSize() const
-{
- return m_scrollbar->totalSize();
-}
-
-bool WebScrollbarImpl::isScrollViewScrollbar() const
-{
- return m_scrollbar->isScrollViewScrollbar();
-}
-
-bool WebScrollbarImpl::isScrollableAreaActive() const
-{
- return m_scrollbar->isScrollableAreaActive();
-}
-
-void WebScrollbarImpl::getTickmarks(WebVector<WebRect>& webTickmarks) const
-{
- Vector<WebCore::IntRect> tickmarks;
- m_scrollbar->getTickmarks(tickmarks);
-
- WebVector<WebRect> result(tickmarks.size());
- for (size_t i = 0; i < tickmarks.size(); ++i)
- result[i] = tickmarks[i];
-
- webTickmarks.swap(result);
-}
-
-WebScrollbar::ScrollbarControlSize WebScrollbarImpl::controlSize() const
-{
- return static_cast<WebScrollbar::ScrollbarControlSize>(m_scrollbar->controlSize());
-}
-
-WebScrollbar::ScrollbarPart WebScrollbarImpl::pressedPart() const
-{
- return static_cast<WebScrollbar::ScrollbarPart>(m_scrollbar->pressedPart());
-}
-
-WebScrollbar::ScrollbarPart WebScrollbarImpl::hoveredPart() const
-{
- return static_cast<WebScrollbar::ScrollbarPart>(m_scrollbar->hoveredPart());
-}
-
-WebScrollbar::ScrollbarOverlayStyle WebScrollbarImpl::scrollbarOverlayStyle() const
-{
- return static_cast<WebScrollbar::ScrollbarOverlayStyle>(m_scrollbar->scrollbarOverlayStyle());
-}
-
-WebScrollbar::Orientation WebScrollbarImpl::orientation() const
-{
- return static_cast<WebScrollbar::Orientation>(m_scrollbar->orientation());
-}
-
-bool WebScrollbarImpl::isLeftSideVerticalScrollbar() const
-{
- return m_scrollbar->isLeftSideVerticalScrollbar();
-}
-
-bool WebScrollbarImpl::isCustomScrollbar() const
-{
- return m_scrollbar->isCustomScrollbar();
-}
-
-bool WebScrollbarImpl::isAlphaLocked() const
-{
- return m_scrollbar->isAlphaLocked();
-}
-
-void WebScrollbarImpl::setIsAlphaLocked(bool flag)
-{
- m_scrollbar->setIsAlphaLocked(flag);
-}
-
-} // namespace WebKit
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebScrollbarImpl.h b/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebScrollbarImpl.h
deleted file mode 100644
index e5459ded05b..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebScrollbarImpl.h
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef WebScrollbarImpl_h
-#define WebScrollbarImpl_h
-
-#include "public/platform/WebScrollbar.h"
-
-namespace WebCore {
-class Scrollbar;
-}
-
-namespace WebKit {
-
-class WebScrollbarImpl : public WebScrollbar {
-public:
- explicit WebScrollbarImpl(WebCore::Scrollbar*);
-
- // Implement WebKit::WebScrollbar methods
- virtual bool isOverlay() const OVERRIDE;
- virtual int value() const OVERRIDE;
- virtual WebPoint location() const OVERRIDE;
- virtual WebSize size() const OVERRIDE;
- virtual bool enabled() const OVERRIDE;
- virtual int maximum() const OVERRIDE;
- virtual int totalSize() const OVERRIDE;
- virtual bool isScrollViewScrollbar() const OVERRIDE;
- virtual bool isScrollableAreaActive() const OVERRIDE;
- virtual void getTickmarks(WebVector<WebRect>& tickmarks) const OVERRIDE;
- virtual ScrollbarControlSize controlSize() const OVERRIDE;
- virtual ScrollbarPart pressedPart() const OVERRIDE;
- virtual ScrollbarPart hoveredPart() const OVERRIDE;
- virtual ScrollbarOverlayStyle scrollbarOverlayStyle() const OVERRIDE;
- virtual bool isCustomScrollbar() const OVERRIDE;
- virtual Orientation orientation() const OVERRIDE;
- virtual bool isLeftSideVerticalScrollbar() const OVERRIDE;
- virtual bool isAlphaLocked() const OVERRIDE;
- virtual void setIsAlphaLocked(bool) OVERRIDE;
-
-private:
- RefPtr<WebCore::Scrollbar> m_scrollbar;
-};
-
-} // namespace WebKit
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebScrollbarThemeClientImpl.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebScrollbarThemeClientImpl.cpp
deleted file mode 100644
index bd6780d407d..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebScrollbarThemeClientImpl.cpp
+++ /dev/null
@@ -1,231 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/platform/chromium/support/WebScrollbarThemeClientImpl.h"
-#include "core/platform/ScrollbarTheme.h"
-
-using WebKit::WebScrollbar;
-
-namespace WebCore {
-
-WebScrollbarThemeClientImpl::WebScrollbarThemeClientImpl(WebScrollbar* scrollbar)
- : m_scrollbar(scrollbar)
-{
- ScrollbarTheme::theme()->registerScrollbar(this);
-}
-
-WebScrollbarThemeClientImpl::~WebScrollbarThemeClientImpl()
-{
- ScrollbarTheme::theme()->unregisterScrollbar(this);
-}
-
-int WebScrollbarThemeClientImpl::x() const
-{
- return location().x();
-}
-
-int WebScrollbarThemeClientImpl::y() const
-{
- return location().y();
-}
-
-int WebScrollbarThemeClientImpl::width() const
-{
- return size().width();
-}
-
-int WebScrollbarThemeClientImpl::height() const
-{
- return size().height();
-}
-
-IntSize WebScrollbarThemeClientImpl::size() const
-{
- return m_scrollbar->size();
-}
-
-IntPoint WebScrollbarThemeClientImpl::location() const
-{
- return m_scrollbar->location();
-}
-
-ScrollView* WebScrollbarThemeClientImpl::parent() const
-{
- // Unused by Chromium scrollbar themes.
- ASSERT_NOT_REACHED();
- return 0;
-}
-
-ScrollView* WebScrollbarThemeClientImpl::root() const
-{
- // Unused by Chromium scrollbar themes.
- ASSERT_NOT_REACHED();
- return 0;
-}
-
-void WebScrollbarThemeClientImpl::setFrameRect(const IntRect&)
-{
- // Unused by Chromium scrollbar themes.
- ASSERT_NOT_REACHED();
-}
-
-IntRect WebScrollbarThemeClientImpl::frameRect() const
-{
- return IntRect(location(), size());
-}
-
-void WebScrollbarThemeClientImpl::invalidate()
-{
- // Unused by Chromium scrollbar themes.
- ASSERT_NOT_REACHED();
-}
-
-void WebScrollbarThemeClientImpl::invalidateRect(const IntRect&)
-{
- // Unused by Chromium scrollbar themes.
- ASSERT_NOT_REACHED();
-}
-
-WebCore::ScrollbarOverlayStyle WebScrollbarThemeClientImpl::scrollbarOverlayStyle() const
-{
- return static_cast<WebCore::ScrollbarOverlayStyle>(m_scrollbar->scrollbarOverlayStyle());
-}
-
-void WebScrollbarThemeClientImpl::getTickmarks(Vector<IntRect>& tickmarks) const
-{
- WebKit::WebVector<WebKit::WebRect> webTickmarks;
- m_scrollbar->getTickmarks(webTickmarks);
- tickmarks.resize(webTickmarks.size());
- for (size_t i = 0; i < webTickmarks.size(); ++i)
- tickmarks[i] = webTickmarks[i];
-}
-
-bool WebScrollbarThemeClientImpl::isScrollableAreaActive() const
-{
- return m_scrollbar->isScrollableAreaActive();
-}
-
-bool WebScrollbarThemeClientImpl::isScrollViewScrollbar() const
-{
- // Unused by Chromium scrollbar themes.
- ASSERT_NOT_REACHED();
- return false;
-}
-
-IntPoint WebScrollbarThemeClientImpl::convertFromContainingWindow(const IntPoint& windowPoint)
-{
- // Unused by Chromium scrollbar themes.
- ASSERT_NOT_REACHED();
- return windowPoint;
-}
-
-bool WebScrollbarThemeClientImpl::isCustomScrollbar() const
-{
- return m_scrollbar->isCustomScrollbar();
-}
-
-WebCore::ScrollbarOrientation WebScrollbarThemeClientImpl::orientation() const
-{
- return static_cast<WebCore::ScrollbarOrientation>(m_scrollbar->orientation());
-}
-
-bool WebScrollbarThemeClientImpl::isLeftSideVerticalScrollbar() const
-{
- return m_scrollbar->isLeftSideVerticalScrollbar();
-}
-
-int WebScrollbarThemeClientImpl::value() const
-{
- return m_scrollbar->value();
-}
-
-float WebScrollbarThemeClientImpl::currentPos() const
-{
- return value();
-}
-
-int WebScrollbarThemeClientImpl::visibleSize() const
-{
- return totalSize() - maximum();
-}
-
-int WebScrollbarThemeClientImpl::totalSize() const
-{
- return m_scrollbar->totalSize();
-}
-
-int WebScrollbarThemeClientImpl::maximum() const
-{
- return m_scrollbar->maximum();
-}
-
-WebCore::ScrollbarControlSize WebScrollbarThemeClientImpl::controlSize() const
-{
- return static_cast<WebCore::ScrollbarControlSize>(m_scrollbar->controlSize());
-}
-
-WebCore::ScrollbarPart WebScrollbarThemeClientImpl::pressedPart() const
-{
- return static_cast<WebCore::ScrollbarPart>(m_scrollbar->pressedPart());
-}
-
-WebCore::ScrollbarPart WebScrollbarThemeClientImpl::hoveredPart() const
-{
- return static_cast<WebCore::ScrollbarPart>(m_scrollbar->hoveredPart());
-}
-
-void WebScrollbarThemeClientImpl::styleChanged()
-{
- ASSERT_NOT_REACHED();
-}
-
-bool WebScrollbarThemeClientImpl::enabled() const
-{
- return m_scrollbar->enabled();
-}
-
-void WebScrollbarThemeClientImpl::setEnabled(bool)
-{
- ASSERT_NOT_REACHED();
-}
-
-bool WebScrollbarThemeClientImpl::isOverlayScrollbar() const
-{
- return m_scrollbar->isOverlay();
-}
-
-bool WebScrollbarThemeClientImpl::isAlphaLocked() const
-{
- return m_scrollbar->isAlphaLocked();
-}
-
-void WebScrollbarThemeClientImpl::setIsAlphaLocked(bool flag)
-{
- m_scrollbar->setIsAlphaLocked(flag);
-}
-
-} // namespace WebKit
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebScrollbarThemeClientImpl.h b/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebScrollbarThemeClientImpl.h
deleted file mode 100644
index 3c08004b7da..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebScrollbarThemeClientImpl.h
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef WebScrollbarThemeClientImpl_h
-#define WebScrollbarThemeClientImpl_h
-
-#include "core/platform/ScrollbarThemeClient.h"
-#include "wtf/Noncopyable.h"
-#include "public/platform/WebScrollbar.h"
-
-namespace WebCore {
-class ScrollView;
-
-// Adapts a WebScrollbar to the ScrollbarThemeClient interface
-class WebScrollbarThemeClientImpl : public ScrollbarThemeClient {
- WTF_MAKE_NONCOPYABLE(WebScrollbarThemeClientImpl);
-public:
- // Caller must retain ownership of this pointer and ensure that its lifetime
- // exceeds this instance.
- WebScrollbarThemeClientImpl(WebKit::WebScrollbar*);
- ~WebScrollbarThemeClientImpl();
-
- // Implement ScrollbarThemeClient interface
- virtual int x() const OVERRIDE;
- virtual int y() const OVERRIDE;
- virtual int width() const OVERRIDE;
- virtual int height() const OVERRIDE;
- virtual IntSize size() const OVERRIDE;
- virtual IntPoint location() const OVERRIDE;
- virtual ScrollView* parent() const OVERRIDE;
- virtual ScrollView* root() const OVERRIDE;
- virtual void setFrameRect(const IntRect&) OVERRIDE;
- virtual IntRect frameRect() const OVERRIDE;
- virtual void invalidate() OVERRIDE;
- virtual void invalidateRect(const IntRect&) OVERRIDE;
- virtual ScrollbarOverlayStyle scrollbarOverlayStyle() const OVERRIDE;
- virtual void getTickmarks(Vector<IntRect>&) const OVERRIDE;
- virtual bool isScrollableAreaActive() const OVERRIDE;
- virtual bool isScrollViewScrollbar() const OVERRIDE;
- virtual IntPoint convertFromContainingWindow(const IntPoint&) OVERRIDE;
- virtual bool isCustomScrollbar() const OVERRIDE;
- virtual ScrollbarOrientation orientation() const OVERRIDE;
- virtual bool isLeftSideVerticalScrollbar() const OVERRIDE;
- virtual int value() const OVERRIDE;
- virtual float currentPos() const OVERRIDE;
- virtual int visibleSize() const OVERRIDE;
- virtual int totalSize() const OVERRIDE;
- virtual int maximum() const OVERRIDE;
- virtual ScrollbarControlSize controlSize() const OVERRIDE;
- virtual ScrollbarPart pressedPart() const OVERRIDE;
- virtual ScrollbarPart hoveredPart() const OVERRIDE;
- virtual void styleChanged() OVERRIDE;
- virtual bool enabled() const OVERRIDE;
- virtual void setEnabled(bool) OVERRIDE;
- virtual bool isOverlayScrollbar() const OVERRIDE;
- virtual bool isAlphaLocked() const OVERRIDE;
- virtual void setIsAlphaLocked(bool) OVERRIDE;
-
-private:
- WebKit::WebScrollbar* m_scrollbar;
-};
-
-}
-
-#endif // WebScrollbarThemeClientImpl_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebScrollbarThemeGeometryNative.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebScrollbarThemeGeometryNative.cpp
deleted file mode 100644
index 849732a4208..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebScrollbarThemeGeometryNative.cpp
+++ /dev/null
@@ -1,157 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/platform/chromium/support/WebScrollbarThemeGeometryNative.h"
-
-#include "core/platform/ScrollbarTheme.h"
-#include "core/platform/chromium/support/WebScrollbarThemeClientImpl.h"
-#include "public/platform/WebScrollbar.h"
-
-using namespace WebCore;
-
-namespace WebKit {
-
-PassOwnPtr<WebKit::WebScrollbarThemeGeometryNative> WebScrollbarThemeGeometryNative::create(WebCore::ScrollbarTheme* theme)
-{
- return adoptPtr(new WebScrollbarThemeGeometryNative(theme));
-}
-
-WebScrollbarThemeGeometryNative::WebScrollbarThemeGeometryNative(WebCore::ScrollbarTheme* theme)
- : m_theme(theme)
-{
-}
-
-WebScrollbarThemeGeometryNative* WebScrollbarThemeGeometryNative::clone() const
-{
- return new WebScrollbarThemeGeometryNative(m_theme);
-}
-
-int WebScrollbarThemeGeometryNative::thumbPosition(WebScrollbar* scrollbar)
-{
- WebScrollbarThemeClientImpl client(scrollbar);
- return m_theme->thumbPosition(&client);
-}
-
-int WebScrollbarThemeGeometryNative::thumbLength(WebScrollbar* scrollbar)
-{
- WebScrollbarThemeClientImpl client(scrollbar);
- return m_theme->thumbLength(&client);
-}
-
-int WebScrollbarThemeGeometryNative::trackPosition(WebScrollbar* scrollbar)
-{
- WebScrollbarThemeClientImpl client(scrollbar);
- return m_theme->trackPosition(&client);
-}
-
-int WebScrollbarThemeGeometryNative::trackLength(WebScrollbar* scrollbar)
-{
- WebScrollbarThemeClientImpl client(scrollbar);
- return m_theme->trackLength(&client);
-}
-
-bool WebScrollbarThemeGeometryNative::hasButtons(WebScrollbar* scrollbar)
-{
- WebScrollbarThemeClientImpl client(scrollbar);
- return m_theme->hasButtons(&client);
-}
-
-bool WebScrollbarThemeGeometryNative::hasThumb(WebScrollbar* scrollbar)
-{
- WebScrollbarThemeClientImpl client(scrollbar);
- return m_theme->hasThumb(&client);
-}
-
-WebRect WebScrollbarThemeGeometryNative::trackRect(WebScrollbar* scrollbar)
-{
- WebScrollbarThemeClientImpl client(scrollbar);
- return m_theme->trackRect(&client);
-}
-
-WebRect WebScrollbarThemeGeometryNative::thumbRect(WebScrollbar* scrollbar)
-{
- WebScrollbarThemeClientImpl client(scrollbar);
- return m_theme->thumbRect(&client);
-}
-
-int WebScrollbarThemeGeometryNative::minimumThumbLength(WebScrollbar* scrollbar)
-{
- WebScrollbarThemeClientImpl client(scrollbar);
- return m_theme->minimumThumbLength(&client);
-}
-
-int WebScrollbarThemeGeometryNative::scrollbarThickness(WebScrollbar* scrollbar)
-{
- WebScrollbarThemeClientImpl client(scrollbar);
- return m_theme->scrollbarThickness(client.controlSize());
-}
-
-WebRect WebScrollbarThemeGeometryNative::backButtonStartRect(WebScrollbar* scrollbar)
-{
- WebScrollbarThemeClientImpl client(scrollbar);
- return m_theme->backButtonRect(&client, BackButtonStartPart, false);
-}
-
-WebRect WebScrollbarThemeGeometryNative::backButtonEndRect(WebScrollbar* scrollbar)
-{
- WebScrollbarThemeClientImpl client(scrollbar);
- return m_theme->backButtonRect(&client, BackButtonEndPart, false);
-}
-
-WebRect WebScrollbarThemeGeometryNative::forwardButtonStartRect(WebScrollbar* scrollbar)
-{
- WebScrollbarThemeClientImpl client(scrollbar);
- return m_theme->forwardButtonRect(&client, ForwardButtonStartPart, false);
-}
-
-WebRect WebScrollbarThemeGeometryNative::forwardButtonEndRect(WebScrollbar* scrollbar)
-{
- WebScrollbarThemeClientImpl client(scrollbar);
- return m_theme->forwardButtonRect(&client, ForwardButtonEndPart, false);
-}
-
-WebRect WebScrollbarThemeGeometryNative::constrainTrackRectToTrackPieces(WebScrollbar* scrollbar, const WebRect& rect)
-{
- WebScrollbarThemeClientImpl client(scrollbar);
- return m_theme->constrainTrackRectToTrackPieces(&client, IntRect(rect));
-}
-
-void WebScrollbarThemeGeometryNative::splitTrack(WebScrollbar* scrollbar, const WebRect& webTrack, WebRect& webStartTrack, WebRect& webThumb, WebRect& webEndTrack)
-{
- WebScrollbarThemeClientImpl client(scrollbar);
- IntRect track(webTrack);
- IntRect startTrack;
- IntRect thumb;
- IntRect endTrack;
- m_theme->splitTrack(&client, track, startTrack, thumb, endTrack);
-
- webStartTrack = startTrack;
- webThumb = thumb;
- webEndTrack = endTrack;
-}
-
-} // namespace WebKit
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebScrollbarThemeGeometryNative.h b/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebScrollbarThemeGeometryNative.h
deleted file mode 100644
index bd461299694..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebScrollbarThemeGeometryNative.h
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef WebScrollbarThemeGeometryNative_h
-#define WebScrollbarThemeGeometryNative_h
-
-#include "public/platform/WebRect.h"
-#include "public/platform/WebScrollbarThemeGeometry.h"
-#include "wtf/PassOwnPtr.h"
-
-namespace WebCore {
-class ScrollbarTheme;
-}
-
-namespace WebKit {
-
-class WebScrollbar;
-
-class WebScrollbarThemeGeometryNative : public WebScrollbarThemeGeometry {
-public:
- static PassOwnPtr<WebScrollbarThemeGeometryNative> create(WebCore::ScrollbarTheme*);
-
- // WebScrollbarThemeGeometry overrides
- virtual WebScrollbarThemeGeometryNative* clone() const OVERRIDE;
- virtual int thumbPosition(WebScrollbar*) OVERRIDE;
- virtual int thumbLength(WebScrollbar*) OVERRIDE;
- virtual int trackPosition(WebScrollbar*) OVERRIDE;
- virtual int trackLength(WebScrollbar*) OVERRIDE;
- virtual bool hasButtons(WebScrollbar*) OVERRIDE;
- virtual bool hasThumb(WebScrollbar*) OVERRIDE;
- virtual WebRect trackRect(WebScrollbar*) OVERRIDE;
- virtual WebRect thumbRect(WebScrollbar*) OVERRIDE;
- virtual int minimumThumbLength(WebScrollbar*) OVERRIDE;
- virtual int scrollbarThickness(WebScrollbar*) OVERRIDE;
- virtual WebRect backButtonStartRect(WebScrollbar*) OVERRIDE;
- virtual WebRect backButtonEndRect(WebScrollbar*) OVERRIDE;
- virtual WebRect forwardButtonStartRect(WebScrollbar*) OVERRIDE;
- virtual WebRect forwardButtonEndRect(WebScrollbar*) OVERRIDE;
- virtual WebRect constrainTrackRectToTrackPieces(WebScrollbar*, const WebRect&) OVERRIDE;
- virtual void splitTrack(WebScrollbar*, const WebRect& track, WebRect& startTrack, WebRect& thumb, WebRect& endTrack) OVERRIDE;
-
-private:
- explicit WebScrollbarThemeGeometryNative(WebCore::ScrollbarTheme*);
-
- // The theme is not owned by this class. It is assumed that the theme is a
- // static pointer and its lifetime is essentially infinite. Only thread-safe
- // functions on the theme can be called by this theme.
- WebCore::ScrollbarTheme* m_theme;
-};
-
-} // namespace WebKit
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebSocketStreamError.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebSocketStreamError.cpp
deleted file mode 100644
index 43d6b084af0..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebSocketStreamError.cpp
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Copyright (C) 2013 Intel Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "public/platform/WebSocketStreamError.h"
-
-#include "core/platform/network/SocketStreamError.h"
-#include "public/platform/WebString.h"
-
-using namespace WebCore;
-
-namespace WebKit {
-
-void WebSocketStreamError::assign(int code, const WebString& message)
-{
- m_private = SocketStreamError::create(code, message);
-}
-
-void WebSocketStreamError::assign(const WebSocketStreamError& other)
-{
- m_private = other.m_private;
-}
-
-void WebSocketStreamError::reset()
-{
- m_private.reset();
-}
-
-WebSocketStreamError::WebSocketStreamError(PassRefPtr<SocketStreamError> error)
-{
- m_private = error;
-}
-
-WebSocketStreamError& WebSocketStreamError::operator=(PassRefPtr<SocketStreamError> error)
-{
- m_private = error;
- return *this;
-}
-
-WebSocketStreamError::operator PassRefPtr<SocketStreamError>() const
-{
- return m_private.get();
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebSourceInfo.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebSourceInfo.cpp
deleted file mode 100644
index 449e6d9eaf3..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebSourceInfo.cpp
+++ /dev/null
@@ -1,112 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY GOOGLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GOOGLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "public/platform/WebSourceInfo.h"
-
-#include "public/platform/WebString.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-
-namespace WebKit {
-
-class WebSourceInfoPrivate : public RefCounted<WebSourceInfoPrivate> {
-public:
- static PassRefPtr<WebSourceInfoPrivate> create(const WebString& id, WebSourceInfo::SourceKind, const WebString& label, WebSourceInfo::VideoFacingMode);
- virtual ~WebSourceInfoPrivate();
-
- const WebString& id() const { return m_id; }
- WebSourceInfo::SourceKind kind() const { return m_kind; }
- const WebString& label() const { return m_label; }
- WebSourceInfo::VideoFacingMode facing() const { return m_facing; }
-
-private:
- WebSourceInfoPrivate(const WebString& id, WebSourceInfo::SourceKind, const WebString& label, WebSourceInfo::VideoFacingMode);
-
- WebString m_id;
- WebSourceInfo::SourceKind m_kind;
- WebString m_label;
- WebSourceInfo::VideoFacingMode m_facing;
-};
-
-PassRefPtr<WebSourceInfoPrivate> WebSourceInfoPrivate::create(const WebString& id, WebSourceInfo::SourceKind kind, const WebString& label, WebSourceInfo::VideoFacingMode facing)
-{
- return adoptRef(new WebSourceInfoPrivate(id, kind, label, facing));
-}
-
-WebSourceInfoPrivate::WebSourceInfoPrivate(const WebString& id, WebSourceInfo::SourceKind kind, const WebString& label, WebSourceInfo::VideoFacingMode facing)
- : m_id(id)
- , m_kind(kind)
- , m_label(label)
- , m_facing(facing)
-{
-}
-
-WebSourceInfoPrivate::~WebSourceInfoPrivate()
-{
-}
-
-void WebSourceInfo::assign(const WebSourceInfo& other)
-{
- m_private = other.m_private;
-}
-
-void WebSourceInfo::reset()
-{
- m_private.reset();
-}
-
-void WebSourceInfo::initialize(const WebString& id, WebSourceInfo::SourceKind kind, const WebString& label, WebSourceInfo::VideoFacingMode facing)
-{
- m_private = WebSourceInfoPrivate::create(id, kind, label, facing);
-}
-
-WebString WebSourceInfo::id() const
-{
- ASSERT(!m_private.isNull());
- return m_private->id();
-}
-
-WebSourceInfo::SourceKind WebSourceInfo::kind() const
-{
- ASSERT(!m_private.isNull());
- return m_private->kind();
-}
-
-WebString WebSourceInfo::label() const
-{
- ASSERT(!m_private.isNull());
- return m_private->label();
-}
-
-WebSourceInfo::VideoFacingMode WebSourceInfo::facing() const
-{
- ASSERT(!m_private.isNull());
- return m_private->facing();
-}
-
-} // namespace WebKit
-
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebSpeechSynthesisUtterance.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebSpeechSynthesisUtterance.cpp
deleted file mode 100644
index 9a511a242e9..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebSpeechSynthesisUtterance.cpp
+++ /dev/null
@@ -1,104 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "public/platform/WebSpeechSynthesisUtterance.h"
-
-#include "core/platform/PlatformSpeechSynthesisUtterance.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefPtr.h"
-
-using namespace WebCore;
-
-namespace WebKit {
-
-WebSpeechSynthesisUtterance::WebSpeechSynthesisUtterance(const PassRefPtr<PlatformSpeechSynthesisUtterance>& utterance)
- : m_private(utterance)
-{
-}
-
-WebSpeechSynthesisUtterance& WebSpeechSynthesisUtterance::operator=(WebCore::PlatformSpeechSynthesisUtterance* utterance)
-{
- m_private = utterance;
- return *this;
-}
-
-void WebSpeechSynthesisUtterance::assign(const WebSpeechSynthesisUtterance& other)
-{
- m_private = other.m_private;
-}
-
-void WebSpeechSynthesisUtterance::reset()
-{
- m_private.reset();
-}
-
-WebSpeechSynthesisUtterance::operator PassRefPtr<PlatformSpeechSynthesisUtterance>() const
-{
- return m_private.get();
-}
-
-WebSpeechSynthesisUtterance::operator PlatformSpeechSynthesisUtterance*() const
-{
- return m_private.get();
-}
-
-WebString WebSpeechSynthesisUtterance::text() const
-{
- return m_private->text();
-}
-
-WebString WebSpeechSynthesisUtterance::lang() const
-{
- return m_private->lang();
-}
-
-WebString WebSpeechSynthesisUtterance::voice() const
-{
- return m_private->voice() ? WebString(m_private->voice()->name()) : WebString();
-}
-
-float WebSpeechSynthesisUtterance::volume() const
-{
- return m_private->volume();
-}
-
-float WebSpeechSynthesisUtterance::rate() const
-{
- return m_private->rate();
-}
-
-float WebSpeechSynthesisUtterance::pitch() const
-{
- return m_private->pitch();
-}
-
-double WebSpeechSynthesisUtterance::startTime() const
-{
- return m_private->startTime();
-}
-
-} // namespace WebKit
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebSpeechSynthesisVoice.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebSpeechSynthesisVoice.cpp
deleted file mode 100644
index 1fcbd29d874..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebSpeechSynthesisVoice.cpp
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "public/platform/WebSpeechSynthesisVoice.h"
-
-#include "modules/speech/SpeechRecognitionAlternative.h"
-#include "modules/speech/SpeechSynthesisVoice.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/Vector.h"
-
-namespace WebKit {
-
-WebSpeechSynthesisVoice::WebSpeechSynthesisVoice()
- : m_private(WebCore::PlatformSpeechSynthesisVoice::create())
-{
-}
-
-void WebSpeechSynthesisVoice::assign(const WebSpeechSynthesisVoice& other)
-{
- m_private = other.m_private;
-}
-
-void WebSpeechSynthesisVoice::reset()
-{
- m_private.reset();
-}
-
-void WebSpeechSynthesisVoice::setVoiceURI(const WebString& voiceURI)
-{
- m_private->setVoiceURI(voiceURI);
-}
-
-void WebSpeechSynthesisVoice::setName(const WebString& name)
-{
- m_private->setName(name);
-}
-
-void WebSpeechSynthesisVoice::setLanguage(const WebString& language)
-{
- m_private->setLang(language);
-}
-
-void WebSpeechSynthesisVoice::setIsLocalService(bool isLocalService)
-{
- m_private->setLocalService(isLocalService);
-}
-
-void WebSpeechSynthesisVoice::setIsDefault(bool isDefault)
-{
- m_private->setIsDefault(isDefault);
-}
-
-WebSpeechSynthesisVoice::operator PassRefPtr<WebCore::PlatformSpeechSynthesisVoice>() const
-{
- return m_private.get();
-}
-
-} // namespace WebKit
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebSpeechSynthesizerClientImpl.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebSpeechSynthesizerClientImpl.cpp
deleted file mode 100644
index 0b49a2fcd28..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebSpeechSynthesizerClientImpl.cpp
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/chromium/support/WebSpeechSynthesizerClientImpl.h"
-
-#include "core/platform/PlatformSpeechSynthesisUtterance.h"
-
-namespace WebCore {
-
-WebSpeechSynthesizerClientImpl::WebSpeechSynthesizerClientImpl(PlatformSpeechSynthesizer* synthesizer, PlatformSpeechSynthesizerClient* client)
- : m_synthesizer(synthesizer)
- , m_client(client)
-{
-}
-
-WebSpeechSynthesizerClientImpl::~WebSpeechSynthesizerClientImpl()
-{
-}
-
-void WebSpeechSynthesizerClientImpl::setVoiceList(const WebKit::WebVector<WebKit::WebSpeechSynthesisVoice>& voices)
-{
- Vector<RefPtr<PlatformSpeechSynthesisVoice> > outVoices;
- for (size_t i = 0; i < voices.size(); i++)
- outVoices.append(PassRefPtr<PlatformSpeechSynthesisVoice>(voices[i]));
- m_synthesizer->setVoiceList(outVoices);
- m_client->voicesDidChange();
-}
-
-void WebSpeechSynthesizerClientImpl::didStartSpeaking(const WebKit::WebSpeechSynthesisUtterance& utterance)
-{
- m_client->didStartSpeaking(utterance);
-}
-
-void WebSpeechSynthesizerClientImpl::didFinishSpeaking(const WebKit::WebSpeechSynthesisUtterance& utterance)
-{
- m_client->didFinishSpeaking(utterance);
-}
-
-void WebSpeechSynthesizerClientImpl::didPauseSpeaking(const WebKit::WebSpeechSynthesisUtterance& utterance)
-{
- m_client->didPauseSpeaking(utterance);
-}
-
-void WebSpeechSynthesizerClientImpl::didResumeSpeaking(const WebKit::WebSpeechSynthesisUtterance& utterance)
-{
- m_client->didResumeSpeaking(utterance);
-}
-
-void WebSpeechSynthesizerClientImpl::speakingErrorOccurred(const WebKit::WebSpeechSynthesisUtterance& utterance)
-{
- m_client->speakingErrorOccurred(utterance);
-}
-
-void WebSpeechSynthesizerClientImpl::wordBoundaryEventOccurred(const WebKit::WebSpeechSynthesisUtterance& utterance, unsigned charIndex)
-{
- m_client->boundaryEventOccurred(utterance, SpeechWordBoundary, charIndex);
-}
-
-void WebSpeechSynthesizerClientImpl::sentenceBoundaryEventOccurred(const WebKit::WebSpeechSynthesisUtterance& utterance, unsigned charIndex)
-{
- m_client->boundaryEventOccurred(utterance, SpeechSentenceBoundary, charIndex);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebSpeechSynthesizerClientImpl.h b/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebSpeechSynthesizerClientImpl.h
deleted file mode 100644
index 91681a1ca90..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebSpeechSynthesizerClientImpl.h
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef WebSpeechSynthesizerClientImpl_h
-#define WebSpeechSynthesizerClientImpl_h
-
-#include "core/platform/PlatformSpeechSynthesizer.h"
-#include "public/platform/WebSpeechSynthesisUtterance.h"
-#include "public/platform/WebSpeechSynthesisVoice.h"
-#include "public/platform/WebSpeechSynthesizerClient.h"
-#include "wtf/HashMap.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-class PlatformSpeechSynthesizer;
-class PlatformSpeechSynthesizerClient;
-
-class WebSpeechSynthesizerClientImpl : public WebKit::WebSpeechSynthesizerClient {
-public:
- explicit WebSpeechSynthesizerClientImpl(PlatformSpeechSynthesizer*, PlatformSpeechSynthesizerClient*);
- virtual ~WebSpeechSynthesizerClientImpl();
-
- virtual void setVoiceList(const WebKit::WebVector<WebKit::WebSpeechSynthesisVoice>& voices);
- virtual void didStartSpeaking(const WebKit::WebSpeechSynthesisUtterance&);
- virtual void didFinishSpeaking(const WebKit::WebSpeechSynthesisUtterance&);
- virtual void didPauseSpeaking(const WebKit::WebSpeechSynthesisUtterance&);
- virtual void didResumeSpeaking(const WebKit::WebSpeechSynthesisUtterance&);
- virtual void speakingErrorOccurred(const WebKit::WebSpeechSynthesisUtterance&);
- virtual void wordBoundaryEventOccurred(const WebKit::WebSpeechSynthesisUtterance&, unsigned charIndex);
- virtual void sentenceBoundaryEventOccurred(const WebKit::WebSpeechSynthesisUtterance&, unsigned charIndex);
-
-private:
- PlatformSpeechSynthesizer* m_synthesizer;
- PlatformSpeechSynthesizerClient* m_client;
-};
-
-} // namespace WebCore
-
-#endif // WebSpeechSynthesizerClientImpl_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebString.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebString.cpp
deleted file mode 100644
index c3ed5dba29a..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebString.cpp
+++ /dev/null
@@ -1,160 +0,0 @@
-/*
- * Copyright (C) 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "public/platform/WebString.h"
-
-#include "public/platform/WebCString.h"
-#include "wtf/text/AtomicString.h"
-#include "wtf/text/CString.h"
-#include "wtf/text/StringUTF8Adaptor.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebKit {
-
-void WebString::reset()
-{
- m_private.reset();
-}
-
-void WebString::assign(const WebString& other)
-{
- assign(other.m_private.get());
-}
-
-void WebString::assign(const WebUChar* data, size_t length)
-{
- assign(StringImpl::create8BitIfPossible(data, length).get());
-}
-
-size_t WebString::length() const
-{
- return m_private.isNull() ? 0 : m_private->length();
-}
-
-WebUChar WebString::at(unsigned i) const
-{
- ASSERT(!m_private.isNull());
- return (*m_private.get())[i];
-}
-
-bool WebString::is8Bit() const
-{
- return m_private->is8Bit();
-}
-
-const WebLChar* WebString::data8() const
-{
- return !m_private.isNull() && is8Bit() ? m_private->characters8() : 0;
-}
-
-const WebUChar* WebString::data16() const
-{
- return !m_private.isNull() && !is8Bit() ? m_private->characters16() : 0;
-}
-
-std::string WebString::utf8() const
-{
- StringUTF8Adaptor utf8(m_private.get());
- return std::string(utf8.data(), utf8.length());
-}
-
-WebString WebString::fromUTF8(const char* data, size_t length)
-{
- return String::fromUTF8(data, length);
-}
-
-WebString WebString::fromUTF8(const char* data)
-{
- return String::fromUTF8(data);
-}
-
-std::string WebString::latin1() const
-{
- String string(m_private.get());
-
- if (string.isEmpty())
- return std::string();
-
- if (string.is8Bit())
- return std::string(reinterpret_cast<const char*>(string.characters8()), string.length());
-
- WebCString latin1 = string.latin1();
- return std::string(latin1.data(), latin1.length());
-}
-
-WebString WebString::fromLatin1(const WebLChar* data, size_t length)
-{
- return String(data, length);
-}
-
-bool WebString::equals(const WebString& s) const
-{
- return equal(m_private.get(), s.m_private.get());
-}
-
-WebString::WebString(const WTF::String& s)
-{
- m_private = s.impl();
-}
-
-WebString& WebString::operator=(const WTF::String& s)
-{
- assign(s.impl());
- return *this;
-}
-
-WebString::operator WTF::String() const
-{
- return m_private.get();
-}
-
-WebString::WebString(const WTF::AtomicString& s)
-{
- assign(s.string());
-}
-
-WebString& WebString::operator=(const WTF::AtomicString& s)
-{
- assign(s.string());
- return *this;
-}
-
-WebString::operator WTF::AtomicString() const
-{
- return WTF::AtomicString(m_private.get());
-}
-
-void WebString::assign(WTF::StringImpl* p)
-{
- m_private = p;
-}
-
-} // namespace WebKit
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebThreadSafeData.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebThreadSafeData.cpp
deleted file mode 100644
index a53e36674a2..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebThreadSafeData.cpp
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "public/platform/WebThreadSafeData.h"
-
-#include "core/platform/network/BlobData.h"
-
-using namespace WebCore;
-
-namespace WebKit {
-
-void WebThreadSafeData::reset()
-{
- m_private.reset();
-}
-
-void WebThreadSafeData::assign(const WebThreadSafeData& other)
-{
- m_private = other.m_private;
-}
-
-size_t WebThreadSafeData::size() const
-{
- if (m_private.isNull())
- return 0;
- return m_private->length();
-}
-
-const char* WebThreadSafeData::data() const
-{
- if (m_private.isNull())
- return 0;
- return m_private->data();
-}
-
-WebThreadSafeData::WebThreadSafeData(const PassRefPtr<RawData>& data)
- : m_private(data.leakRef())
-{
-}
-
-WebThreadSafeData& WebThreadSafeData::operator=(const PassRefPtr<RawData>& data)
-{
- m_private = data;
- return *this;
-}
-
-} // namespace WebKit
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebTransformKeyframe.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebTransformKeyframe.cpp
deleted file mode 100644
index 4e4c2851cf0..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebTransformKeyframe.cpp
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "public/platform/WebTransformKeyframe.h"
-
-namespace WebKit {
-
-WebTransformKeyframe::WebTransformKeyframe(double time, WebTransformOperations* value)
- : m_time(time)
- , m_value(value)
-{
-}
-
-WebTransformKeyframe::~WebTransformKeyframe()
-{
- m_value.reset(0);
-}
-
-double WebTransformKeyframe::time() const
-{
- return m_time;
-}
-
-const WebTransformOperations& WebTransformKeyframe::value() const
-{
- return *m_value.get();
-}
-
-
-} // namespace WebKit
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebURL.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebURL.cpp
deleted file mode 100644
index 5af208edda4..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebURL.cpp
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * Copyright (C) 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "public/platform/WebURL.h"
-
-#include "weborigin/KURL.h"
-
-namespace WebKit {
-
-WebURL::WebURL(const WebCore::KURL& url)
- : m_string(url.string())
- , m_parsed(url.parsed())
- , m_isValid(url.isValid())
-{
-}
-
-WebURL& WebURL::operator=(const WebCore::KURL& url)
-{
- m_string = url.string();
- m_parsed = url.parsed();
- m_isValid = url.isValid();
- return *this;
-}
-
-WebURL::operator WebCore::KURL() const
-{
- return WebCore::KURL(m_string, m_parsed, m_isValid);
-}
-
-} // namespace WebKit
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebURLError.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebURLError.cpp
deleted file mode 100644
index a236af22f29..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebURLError.cpp
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * Copyright (C) 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "public/platform/WebURLError.h"
-
-#include "core/platform/network/ResourceError.h"
-#include "weborigin/KURL.h"
-#include "wtf/text/CString.h"
-
-using namespace WebCore;
-
-namespace WebKit {
-
-WebURLError::WebURLError(const ResourceError& error)
-{
- *this = error;
-}
-
-WebURLError& WebURLError::operator=(const ResourceError& error)
-{
- if (error.isNull())
- *this = WebURLError();
- else {
- domain = error.domain();
- reason = error.errorCode();
- unreachableURL = KURL(ParsedURLString, error.failingURL());
- isCancellation = error.isCancellation();
- localizedDescription = error.localizedDescription();
- }
- return *this;
-}
-
-WebURLError::operator ResourceError() const
-{
- if (!reason)
- return ResourceError();
- CString spec = unreachableURL.spec();
- ResourceError resourceError = ResourceError(domain, reason,
- String::fromUTF8(spec.data(),
- spec.length()),
- localizedDescription);
- resourceError.setIsCancellation(isCancellation);
- return resourceError;
-}
-
-} // namespace WebKit
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebURLRequest.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebURLRequest.cpp
deleted file mode 100644
index 9751d56275e..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebURLRequest.cpp
+++ /dev/null
@@ -1,352 +0,0 @@
-/*
- * Copyright (C) 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "public/platform/WebURLRequest.h"
-
-#include "core/platform/chromium/support/WebURLRequestPrivate.h"
-#include "core/platform/network/ResourceRequest.h"
-#include "public/platform/WebHTTPBody.h"
-#include "public/platform/WebHTTPHeaderVisitor.h"
-#include "public/platform/WebURL.h"
-
-using namespace WebCore;
-
-namespace WebKit {
-
-namespace {
-
-class ExtraDataContainer : public ResourceRequest::ExtraData {
-public:
- static PassRefPtr<ExtraDataContainer> create(WebURLRequest::ExtraData* extraData) { return adoptRef(new ExtraDataContainer(extraData)); }
-
- virtual ~ExtraDataContainer() { }
-
- WebURLRequest::ExtraData* extraData() const { return m_extraData.get(); }
-
-private:
- explicit ExtraDataContainer(WebURLRequest::ExtraData* extraData)
- : m_extraData(adoptPtr(extraData))
- {
- }
-
- OwnPtr<WebURLRequest::ExtraData> m_extraData;
-};
-
-} // namespace
-
-// The standard implementation of WebURLRequestPrivate, which maintains
-// ownership of a ResourceRequest instance.
-class WebURLRequestPrivateImpl : public WebURLRequestPrivate {
-public:
- WebURLRequestPrivateImpl()
- {
- m_resourceRequest = &m_resourceRequestAllocation;
- }
-
- WebURLRequestPrivateImpl(const WebURLRequestPrivate* p)
- : m_resourceRequestAllocation(*p->m_resourceRequest)
- {
- m_resourceRequest = &m_resourceRequestAllocation;
- m_allowStoredCredentials = p->m_allowStoredCredentials;
- }
-
- virtual void dispose() { delete this; }
-
-private:
- virtual ~WebURLRequestPrivateImpl() { }
-
- ResourceRequest m_resourceRequestAllocation;
-};
-
-void WebURLRequest::initialize()
-{
- assign(new WebURLRequestPrivateImpl());
-}
-
-void WebURLRequest::reset()
-{
- assign(0);
-}
-
-void WebURLRequest::assign(const WebURLRequest& r)
-{
- if (&r != this)
- assign(r.m_private ? new WebURLRequestPrivateImpl(r.m_private) : 0);
-}
-
-bool WebURLRequest::isNull() const
-{
- return !m_private || m_private->m_resourceRequest->isNull();
-}
-
-WebURL WebURLRequest::url() const
-{
- return m_private->m_resourceRequest->url();
-}
-
-void WebURLRequest::setURL(const WebURL& url)
-{
- m_private->m_resourceRequest->setURL(url);
-}
-
-WebURL WebURLRequest::firstPartyForCookies() const
-{
- return m_private->m_resourceRequest->firstPartyForCookies();
-}
-
-void WebURLRequest::setFirstPartyForCookies(const WebURL& firstPartyForCookies)
-{
- m_private->m_resourceRequest->setFirstPartyForCookies(firstPartyForCookies);
-}
-
-bool WebURLRequest::allowCookies() const
-{
- return m_private->m_resourceRequest->allowCookies();
-}
-
-void WebURLRequest::setAllowCookies(bool allowCookies)
-{
- m_private->m_resourceRequest->setAllowCookies(allowCookies);
-}
-
-bool WebURLRequest::allowStoredCredentials() const
-{
- return m_private->m_allowStoredCredentials;
-}
-
-void WebURLRequest::setAllowStoredCredentials(bool allowStoredCredentials)
-{
- m_private->m_allowStoredCredentials = allowStoredCredentials;
-}
-
-WebURLRequest::CachePolicy WebURLRequest::cachePolicy() const
-{
- return static_cast<WebURLRequest::CachePolicy>(
- m_private->m_resourceRequest->cachePolicy());
-}
-
-void WebURLRequest::setCachePolicy(CachePolicy cachePolicy)
-{
- m_private->m_resourceRequest->setCachePolicy(
- static_cast<ResourceRequestCachePolicy>(cachePolicy));
-}
-
-WebString WebURLRequest::httpMethod() const
-{
- return m_private->m_resourceRequest->httpMethod();
-}
-
-void WebURLRequest::setHTTPMethod(const WebString& httpMethod)
-{
- m_private->m_resourceRequest->setHTTPMethod(httpMethod);
-}
-
-WebString WebURLRequest::httpHeaderField(const WebString& name) const
-{
- return m_private->m_resourceRequest->httpHeaderField(name);
-}
-
-void WebURLRequest::setHTTPHeaderField(const WebString& name, const WebString& value)
-{
- m_private->m_resourceRequest->setHTTPHeaderField(name, value);
-}
-
-void WebURLRequest::addHTTPHeaderField(const WebString& name, const WebString& value)
-{
- m_private->m_resourceRequest->addHTTPHeaderField(name, value);
-}
-
-void WebURLRequest::clearHTTPHeaderField(const WebString& name)
-{
- // FIXME: Add a clearHTTPHeaderField method to ResourceRequest.
- const HTTPHeaderMap& map = m_private->m_resourceRequest->httpHeaderFields();
- const_cast<HTTPHeaderMap*>(&map)->remove(name);
-}
-
-void WebURLRequest::visitHTTPHeaderFields(WebHTTPHeaderVisitor* visitor) const
-{
- const HTTPHeaderMap& map = m_private->m_resourceRequest->httpHeaderFields();
- for (HTTPHeaderMap::const_iterator it = map.begin(); it != map.end(); ++it)
- visitor->visitHeader(it->key, it->value);
-}
-
-WebHTTPBody WebURLRequest::httpBody() const
-{
- return WebHTTPBody(m_private->m_resourceRequest->httpBody());
-}
-
-void WebURLRequest::setHTTPBody(const WebHTTPBody& httpBody)
-{
- m_private->m_resourceRequest->setHTTPBody(httpBody);
-}
-
-bool WebURLRequest::reportUploadProgress() const
-{
- return m_private->m_resourceRequest->reportUploadProgress();
-}
-
-void WebURLRequest::setReportUploadProgress(bool reportUploadProgress)
-{
- m_private->m_resourceRequest->setReportUploadProgress(reportUploadProgress);
-}
-
-bool WebURLRequest::reportLoadTiming() const
-{
- return m_private->m_resourceRequest->reportLoadTiming();
-}
-
-void WebURLRequest::setReportRawHeaders(bool reportRawHeaders)
-{
- m_private->m_resourceRequest->setReportRawHeaders(reportRawHeaders);
-}
-
-bool WebURLRequest::reportRawHeaders() const
-{
- return m_private->m_resourceRequest->reportRawHeaders();
-}
-
-void WebURLRequest::setReportLoadTiming(bool reportLoadTiming)
-{
- m_private->m_resourceRequest->setReportLoadTiming(reportLoadTiming);
-}
-
-WebURLRequest::TargetType WebURLRequest::targetType() const
-{
- // FIXME: Temporary special case until downstream chromium.org knows of the new TargetTypes.
- TargetType targetType = static_cast<TargetType>(m_private->m_resourceRequest->targetType());
- if (targetType == TargetIsTextTrack || targetType == TargetIsUnspecified)
- return TargetIsSubresource;
- return targetType;
-}
-
-bool WebURLRequest::hasUserGesture() const
-{
- return m_private->m_resourceRequest->hasUserGesture();
-}
-
-void WebURLRequest::setHasUserGesture(bool hasUserGesture)
-{
- m_private->m_resourceRequest->setHasUserGesture(hasUserGesture);
-}
-
-void WebURLRequest::setTargetType(TargetType targetType)
-{
- m_private->m_resourceRequest->setTargetType(
- static_cast<ResourceRequest::TargetType>(targetType));
-}
-
-int WebURLRequest::requestorID() const
-{
- return m_private->m_resourceRequest->requestorID();
-}
-
-void WebURLRequest::setRequestorID(int requestorID)
-{
- m_private->m_resourceRequest->setRequestorID(requestorID);
-}
-
-int WebURLRequest::requestorProcessID() const
-{
- return m_private->m_resourceRequest->requestorProcessID();
-}
-
-void WebURLRequest::setRequestorProcessID(int requestorProcessID)
-{
- m_private->m_resourceRequest->setRequestorProcessID(requestorProcessID);
-}
-
-int WebURLRequest::appCacheHostID() const
-{
- return m_private->m_resourceRequest->appCacheHostID();
-}
-
-void WebURLRequest::setAppCacheHostID(int appCacheHostID)
-{
- m_private->m_resourceRequest->setAppCacheHostID(appCacheHostID);
-}
-
-bool WebURLRequest::downloadToFile() const
-{
- return m_private->m_resourceRequest->downloadToFile();
-}
-
-void WebURLRequest::setDownloadToFile(bool downloadToFile)
-{
- m_private->m_resourceRequest->setDownloadToFile(downloadToFile);
-}
-
-WebURLRequest::ExtraData* WebURLRequest::extraData() const
-{
- RefPtr<ResourceRequest::ExtraData> data = m_private->m_resourceRequest->extraData();
- if (!data)
- return 0;
- return static_cast<ExtraDataContainer*>(data.get())->extraData();
-}
-
-void WebURLRequest::setExtraData(WebURLRequest::ExtraData* extraData)
-{
- m_private->m_resourceRequest->setExtraData(ExtraDataContainer::create(extraData));
-}
-
-ResourceRequest& WebURLRequest::toMutableResourceRequest()
-{
- ASSERT(m_private);
- ASSERT(m_private->m_resourceRequest);
-
- return *m_private->m_resourceRequest;
-}
-
-WebURLRequest::Priority WebURLRequest::priority() const
-{
- return static_cast<WebURLRequest::Priority>(
- m_private->m_resourceRequest->priority());
-}
-
-const ResourceRequest& WebURLRequest::toResourceRequest() const
-{
- ASSERT(m_private);
- ASSERT(m_private->m_resourceRequest);
-
- return *m_private->m_resourceRequest;
-}
-
-void WebURLRequest::assign(WebURLRequestPrivate* p)
-{
- // Subclasses may call this directly so a self-assignment check is needed
- // here as well as in the public assign method.
- if (m_private == p)
- return;
- if (m_private)
- m_private->dispose();
- m_private = p;
-}
-
-} // namespace WebKit
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebURLRequestPrivate.h b/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebURLRequestPrivate.h
deleted file mode 100644
index 1c1b69608ec..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebURLRequestPrivate.h
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright (C) 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef WebURLRequestPrivate_h
-#define WebURLRequestPrivate_h
-
-namespace WebCore { class ResourceRequest; }
-
-namespace WebKit {
-
-class WebURLRequestPrivate {
-public:
- WebURLRequestPrivate()
- : m_resourceRequest(0)
- , m_allowStoredCredentials(true) { }
-
- // Called by WebURLRequest when it no longer needs this object.
- virtual void dispose() = 0;
-
- WebCore::ResourceRequest* m_resourceRequest;
- bool m_allowStoredCredentials;
-};
-
-} // namespace WebKit
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebURLResponse.cpp b/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebURLResponse.cpp
deleted file mode 100644
index a69027b310f..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebURLResponse.cpp
+++ /dev/null
@@ -1,447 +0,0 @@
-/*
- * Copyright (C) 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "public/platform/WebURLResponse.h"
-
-#include "core/platform/chromium/support/WebURLResponsePrivate.h"
-#include "core/platform/network/ResourceLoadTiming.h"
-#include "core/platform/network/ResourceResponse.h"
-#include "public/platform/WebHTTPHeaderVisitor.h"
-#include "public/platform/WebHTTPLoadInfo.h"
-#include "public/platform/WebString.h"
-#include "public/platform/WebURL.h"
-#include "public/platform/WebURLLoadTiming.h"
-#include "wtf/RefPtr.h"
-
-using namespace WebCore;
-
-namespace WebKit {
-
-namespace {
-
-class ExtraDataContainer : public ResourceResponse::ExtraData {
-public:
- static PassRefPtr<ExtraDataContainer> create(WebURLResponse::ExtraData* extraData) { return adoptRef(new ExtraDataContainer(extraData)); }
-
- virtual ~ExtraDataContainer() { }
-
- WebURLResponse::ExtraData* extraData() const { return m_extraData.get(); }
-
-private:
- explicit ExtraDataContainer(WebURLResponse::ExtraData* extraData)
- : m_extraData(adoptPtr(extraData))
- {
- }
-
- OwnPtr<WebURLResponse::ExtraData> m_extraData;
-};
-
-} // namespace
-
-// The standard implementation of WebURLResponsePrivate, which maintains
-// ownership of a ResourceResponse instance.
-class WebURLResponsePrivateImpl : public WebURLResponsePrivate {
-public:
- WebURLResponsePrivateImpl()
- {
- m_resourceResponse = &m_resourceResponseAllocation;
- }
-
- WebURLResponsePrivateImpl(const WebURLResponsePrivate* p)
- : m_resourceResponseAllocation(*p->m_resourceResponse)
- {
- m_resourceResponse = &m_resourceResponseAllocation;
- }
-
- virtual void dispose() { delete this; }
-
-private:
- virtual ~WebURLResponsePrivateImpl() { }
-
- ResourceResponse m_resourceResponseAllocation;
-};
-
-void WebURLResponse::initialize()
-{
- assign(new WebURLResponsePrivateImpl());
-}
-
-void WebURLResponse::reset()
-{
- assign(0);
-}
-
-void WebURLResponse::assign(const WebURLResponse& r)
-{
- if (&r != this)
- assign(r.m_private ? new WebURLResponsePrivateImpl(r.m_private) : 0);
-}
-
-bool WebURLResponse::isNull() const
-{
- return !m_private || m_private->m_resourceResponse->isNull();
-}
-
-WebURL WebURLResponse::url() const
-{
- return m_private->m_resourceResponse->url();
-}
-
-void WebURLResponse::setURL(const WebURL& url)
-{
- m_private->m_resourceResponse->setURL(url);
-}
-
-unsigned WebURLResponse::connectionID() const
-{
- return m_private->m_resourceResponse->connectionID();
-}
-
-void WebURLResponse::setConnectionID(unsigned connectionID)
-{
- m_private->m_resourceResponse->setConnectionID(connectionID);
-}
-
-bool WebURLResponse::connectionReused() const
-{
- return m_private->m_resourceResponse->connectionReused();
-}
-
-void WebURLResponse::setConnectionReused(bool connectionReused)
-{
- m_private->m_resourceResponse->setConnectionReused(connectionReused);
-}
-
-WebURLLoadTiming WebURLResponse::loadTiming()
-{
- return WebURLLoadTiming(m_private->m_resourceResponse->resourceLoadTiming());
-}
-
-void WebURLResponse::setLoadTiming(const WebURLLoadTiming& timing)
-{
- RefPtr<ResourceLoadTiming> loadTiming = PassRefPtr<ResourceLoadTiming>(timing);
- m_private->m_resourceResponse->setResourceLoadTiming(loadTiming.release());
-}
-
-WebHTTPLoadInfo WebURLResponse::httpLoadInfo()
-{
- return WebHTTPLoadInfo(m_private->m_resourceResponse->resourceLoadInfo());
-}
-
-void WebURLResponse::setHTTPLoadInfo(const WebHTTPLoadInfo& value)
-{
- m_private->m_resourceResponse->setResourceLoadInfo(value);
-}
-
-double WebURLResponse::responseTime() const
-{
- return m_private->m_resourceResponse->responseTime();
-}
-
-void WebURLResponse::setResponseTime(double responseTime)
-{
- m_private->m_resourceResponse->setResponseTime(responseTime);
-}
-
-WebString WebURLResponse::mimeType() const
-{
- return m_private->m_resourceResponse->mimeType();
-}
-
-void WebURLResponse::setMIMEType(const WebString& mimeType)
-{
- m_private->m_resourceResponse->setMimeType(mimeType);
-}
-
-long long WebURLResponse::expectedContentLength() const
-{
- return m_private->m_resourceResponse->expectedContentLength();
-}
-
-void WebURLResponse::setExpectedContentLength(long long expectedContentLength)
-{
- m_private->m_resourceResponse->setExpectedContentLength(expectedContentLength);
-}
-
-WebString WebURLResponse::textEncodingName() const
-{
- return m_private->m_resourceResponse->textEncodingName();
-}
-
-void WebURLResponse::setTextEncodingName(const WebString& textEncodingName)
-{
- m_private->m_resourceResponse->setTextEncodingName(textEncodingName);
-}
-
-WebString WebURLResponse::suggestedFileName() const
-{
- return m_private->m_resourceResponse->suggestedFilename();
-}
-
-void WebURLResponse::setSuggestedFileName(const WebString& suggestedFileName)
-{
- m_private->m_resourceResponse->setSuggestedFilename(suggestedFileName);
-}
-
-WebURLResponse::HTTPVersion WebURLResponse::httpVersion() const
-{
- return static_cast<HTTPVersion>(m_private->m_resourceResponse->httpVersion());
-}
-
-void WebURLResponse::setHTTPVersion(HTTPVersion version)
-{
- m_private->m_resourceResponse->setHTTPVersion(static_cast<ResourceResponse::HTTPVersion>(version));
-}
-
-int WebURLResponse::httpStatusCode() const
-{
- return m_private->m_resourceResponse->httpStatusCode();
-}
-
-void WebURLResponse::setHTTPStatusCode(int httpStatusCode)
-{
- m_private->m_resourceResponse->setHTTPStatusCode(httpStatusCode);
-}
-
-WebString WebURLResponse::httpStatusText() const
-{
- return m_private->m_resourceResponse->httpStatusText();
-}
-
-void WebURLResponse::setHTTPStatusText(const WebString& httpStatusText)
-{
- m_private->m_resourceResponse->setHTTPStatusText(httpStatusText);
-}
-
-WebString WebURLResponse::httpHeaderField(const WebString& name) const
-{
- return m_private->m_resourceResponse->httpHeaderField(name);
-}
-
-void WebURLResponse::setHTTPHeaderField(const WebString& name, const WebString& value)
-{
- m_private->m_resourceResponse->setHTTPHeaderField(name, value);
-}
-
-void WebURLResponse::addHTTPHeaderField(const WebString& name, const WebString& value)
-{
- if (name.isNull() || value.isNull())
- return;
-
- m_private->m_resourceResponse->addHTTPHeaderField(name, value);
-}
-
-void WebURLResponse::clearHTTPHeaderField(const WebString& name)
-{
- // FIXME: Add a clearHTTPHeaderField method to ResourceResponse.
- const HTTPHeaderMap& map = m_private->m_resourceResponse->httpHeaderFields();
- const_cast<HTTPHeaderMap*>(&map)->remove(name);
-}
-
-void WebURLResponse::visitHTTPHeaderFields(WebHTTPHeaderVisitor* visitor) const
-{
- const HTTPHeaderMap& map = m_private->m_resourceResponse->httpHeaderFields();
- for (HTTPHeaderMap::const_iterator it = map.begin(); it != map.end(); ++it)
- visitor->visitHeader(it->key, it->value);
-}
-
-double WebURLResponse::lastModifiedDate() const
-{
- return static_cast<double>(m_private->m_resourceResponse->lastModifiedDate());
-}
-
-void WebURLResponse::setLastModifiedDate(double lastModifiedDate)
-{
- m_private->m_resourceResponse->setLastModifiedDate(static_cast<time_t>(lastModifiedDate));
-}
-
-long long WebURLResponse::appCacheID() const
-{
- return m_private->m_resourceResponse->appCacheID();
-}
-
-void WebURLResponse::setAppCacheID(long long appCacheID)
-{
- m_private->m_resourceResponse->setAppCacheID(appCacheID);
-}
-
-WebURL WebURLResponse::appCacheManifestURL() const
-{
- return m_private->m_resourceResponse->appCacheManifestURL();
-}
-
-void WebURLResponse::setAppCacheManifestURL(const WebURL& url)
-{
- m_private->m_resourceResponse->setAppCacheManifestURL(url);
-}
-
-WebCString WebURLResponse::securityInfo() const
-{
- // FIXME: getSecurityInfo is misnamed.
- return m_private->m_resourceResponse->getSecurityInfo();
-}
-
-void WebURLResponse::setSecurityInfo(const WebCString& securityInfo)
-{
- m_private->m_resourceResponse->setSecurityInfo(securityInfo);
-}
-
-ResourceResponse& WebURLResponse::toMutableResourceResponse()
-{
- ASSERT(m_private);
- ASSERT(m_private->m_resourceResponse);
-
- return *m_private->m_resourceResponse;
-}
-
-const ResourceResponse& WebURLResponse::toResourceResponse() const
-{
- ASSERT(m_private);
- ASSERT(m_private->m_resourceResponse);
-
- return *m_private->m_resourceResponse;
-}
-
-bool WebURLResponse::wasCached() const
-{
- return m_private->m_resourceResponse->wasCached();
-}
-
-void WebURLResponse::setWasCached(bool value)
-{
- m_private->m_resourceResponse->setWasCached(value);
-}
-
-bool WebURLResponse::wasFetchedViaSPDY() const
-{
- return m_private->m_resourceResponse->wasFetchedViaSPDY();
-}
-
-void WebURLResponse::setWasFetchedViaSPDY(bool value)
-{
- m_private->m_resourceResponse->setWasFetchedViaSPDY(value);
-}
-
-bool WebURLResponse::wasNpnNegotiated() const
-{
- return m_private->m_resourceResponse->wasNpnNegotiated();
-}
-
-void WebURLResponse::setWasNpnNegotiated(bool value)
-{
- m_private->m_resourceResponse->setWasNpnNegotiated(value);
-}
-
-bool WebURLResponse::wasAlternateProtocolAvailable() const
-{
- return m_private->m_resourceResponse->wasAlternateProtocolAvailable();
-}
-
-void WebURLResponse::setWasAlternateProtocolAvailable(bool value)
-{
- m_private->m_resourceResponse->setWasAlternateProtocolAvailable(value);
-}
-
-bool WebURLResponse::wasFetchedViaProxy() const
-{
- return m_private->m_resourceResponse->wasFetchedViaProxy();
-}
-
-void WebURLResponse::setWasFetchedViaProxy(bool value)
-{
- m_private->m_resourceResponse->setWasFetchedViaProxy(value);
-}
-
-bool WebURLResponse::isMultipartPayload() const
-{
- return m_private->m_resourceResponse->isMultipartPayload();
-}
-
-void WebURLResponse::setIsMultipartPayload(bool value)
-{
- m_private->m_resourceResponse->setIsMultipartPayload(value);
-}
-
-WebString WebURLResponse::downloadFilePath() const
-{
- return m_private->m_resourceResponse->downloadedFilePath();
-}
-
-void WebURLResponse::setDownloadFilePath(const WebString& downloadFilePath)
-{
- m_private->m_resourceResponse->setDownloadedFilePath(downloadFilePath);
-}
-
-WebString WebURLResponse::remoteIPAddress() const
-{
- return m_private->m_resourceResponse->remoteIPAddress();
-}
-
-void WebURLResponse::setRemoteIPAddress(const WebString& remoteIPAddress)
-{
- m_private->m_resourceResponse->setRemoteIPAddress(remoteIPAddress);
-}
-
-unsigned short WebURLResponse::remotePort() const
-{
- return m_private->m_resourceResponse->remotePort();
-}
-
-void WebURLResponse::setRemotePort(unsigned short remotePort)
-{
- m_private->m_resourceResponse->setRemotePort(remotePort);
-}
-
-WebURLResponse::ExtraData* WebURLResponse::extraData() const
-{
- RefPtr<ResourceResponse::ExtraData> data = m_private->m_resourceResponse->extraData();
- if (!data)
- return 0;
- return static_cast<ExtraDataContainer*>(data.get())->extraData();
-}
-
-void WebURLResponse::setExtraData(WebURLResponse::ExtraData* extraData)
-{
- m_private->m_resourceResponse->setExtraData(ExtraDataContainer::create(extraData));
-}
-
-void WebURLResponse::assign(WebURLResponsePrivate* p)
-{
- // Subclasses may call this directly so a self-assignment check is needed
- // here as well as in the public assign method.
- if (m_private == p)
- return;
- if (m_private)
- m_private->dispose();
- m_private = p;
-}
-
-} // namespace WebKit
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebURLResponsePrivate.h b/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebURLResponsePrivate.h
deleted file mode 100644
index e6b6c782746..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WebURLResponsePrivate.h
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Copyright (C) 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef WebURLResponsePrivate_h
-#define WebURLResponsePrivate_h
-
-#include "public/platform/WebString.h"
-
-namespace WebCore { class ResourceResponse; }
-
-namespace WebKit {
-
-class WebURLResponsePrivate {
-public:
- WebURLResponsePrivate() : m_resourceResponse(0) { }
-
- // Called by WebURLResponse when it no longer needs this object.
- virtual void dispose() = 0;
-
- WebCore::ResourceResponse* m_resourceResponse;
-};
-
-} // namespace WebKit
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WrappedResourceRequest.h b/chromium/third_party/WebKit/Source/core/platform/chromium/support/WrappedResourceRequest.h
deleted file mode 100644
index f1dc7a99c23..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WrappedResourceRequest.h
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * Copyright (C) 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef WrappedResourceRequest_h
-#define WrappedResourceRequest_h
-
-#include "core/platform/chromium/support/WebURLRequestPrivate.h"
-#include "public/platform/WebURLRequest.h"
-
-namespace WebKit {
-
-class WrappedResourceRequest : public WebURLRequest {
-public:
- ~WrappedResourceRequest()
- {
- reset(); // Need to drop reference to m_handle
- }
-
- WrappedResourceRequest() { }
-
- WrappedResourceRequest(WebCore::ResourceRequest& resourceRequest)
- {
- bind(resourceRequest);
- }
-
- WrappedResourceRequest(const WebCore::ResourceRequest& resourceRequest)
- {
- bind(resourceRequest);
- }
-
- void bind(WebCore::ResourceRequest& resourceRequest)
- {
- m_handle.m_resourceRequest = &resourceRequest;
- assign(&m_handle);
- }
-
- void bind(const WebCore::ResourceRequest& resourceRequest)
- {
- bind(*const_cast<WebCore::ResourceRequest*>(&resourceRequest));
- }
-
-private:
- class Handle : public WebURLRequestPrivate {
- public:
- virtual void dispose() { m_resourceRequest = 0; }
- };
-
- Handle m_handle;
-};
-
-} // namespace WebKit
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WrappedResourceResponse.h b/chromium/third_party/WebKit/Source/core/platform/chromium/support/WrappedResourceResponse.h
deleted file mode 100644
index 672ca52bb14..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/chromium/support/WrappedResourceResponse.h
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * Copyright (C) 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef WrappedResourceResponse_h
-#define WrappedResourceResponse_h
-
-#include "core/platform/chromium/support/WebURLResponsePrivate.h"
-#include "public/platform/WebURLResponse.h"
-
-namespace WebKit {
-
-class WrappedResourceResponse : public WebURLResponse {
-public:
- ~WrappedResourceResponse()
- {
- reset(); // Need to drop reference to m_handle
- }
-
- WrappedResourceResponse() { }
-
- WrappedResourceResponse(WebCore::ResourceResponse& resourceResponse)
- {
- bind(resourceResponse);
- }
-
- WrappedResourceResponse(const WebCore::ResourceResponse& resourceResponse)
- {
- bind(resourceResponse);
- }
-
- void bind(WebCore::ResourceResponse& resourceResponse)
- {
- m_handle.m_resourceResponse = &resourceResponse;
- assign(&m_handle);
- }
-
- void bind(const WebCore::ResourceResponse& resourceResponse)
- {
- bind(*const_cast<WebCore::ResourceResponse*>(&resourceResponse));
- }
-
-private:
- class Handle : public WebURLResponsePrivate {
- public:
- virtual void dispose() { m_resourceResponse = 0; }
- };
-
- Handle m_handle;
-};
-
-} // namespace WebKit
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/cocoa/KeyEventCocoa.h b/chromium/third_party/WebKit/Source/core/platform/cocoa/KeyEventCocoa.h
deleted file mode 100644
index f45c5933537..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/cocoa/KeyEventCocoa.h
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef KeyEventCocoa_h
-#define KeyEventCocoa_h
-
-#include "wtf/Forward.h"
-
-namespace WebCore {
-
-String keyIdentifierForCharCode(unichar charCode);
-
-int windowsKeyCodeForKeyCode(uint16_t keyCode);
-int windowsKeyCodeForCharCode(unichar charCode);
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/cocoa/KeyEventCocoa.mm b/chromium/third_party/WebKit/Source/core/platform/cocoa/KeyEventCocoa.mm
deleted file mode 100644
index 1180578238d..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/cocoa/KeyEventCocoa.mm
+++ /dev/null
@@ -1,531 +0,0 @@
-/*
- * Copyright (C) 2004, 2006, 2007, 2008, 2009, 2010 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#import "config.h"
-#import "core/platform/cocoa/KeyEventCocoa.h"
-
-#import "core/platform/Logging.h"
-#import "core/platform/WindowsKeyboardCodes.h"
-#import <wtf/ASCIICType.h>
-#import <wtf/text/WTFString.h>
-
-using namespace WTF;
-
-namespace WebCore {
-
-String keyIdentifierForCharCode(unichar charCode)
-{
- switch (charCode) {
- // Each identifier listed in the DOM spec is listed here.
- // Many are simply commented out since they do not appear on standard Macintosh keyboards
- // or are on a key that doesn't have a corresponding character.
-
- // "Accept"
- // "AllCandidates"
-
- // "Alt"
- case NSMenuFunctionKey:
- return "Alt";
-
- // "Apps"
- // "BrowserBack"
- // "BrowserForward"
- // "BrowserHome"
- // "BrowserRefresh"
- // "BrowserSearch"
- // "BrowserStop"
- // "CapsLock"
-
- // "Clear"
- case NSClearLineFunctionKey:
- return "Clear";
-
- // "CodeInput"
- // "Compose"
- // "Control"
- // "Crsel"
- // "Convert"
- // "Copy"
- // "Cut"
-
- // "Down"
- case NSDownArrowFunctionKey:
- return "Down";
- // "End"
- case NSEndFunctionKey:
- return "End";
- // "Enter"
- case 0x3: case 0xA: case 0xD: // Macintosh calls the one on the main keyboard Return, but Windows calls it Enter, so we'll do the same for the DOM
- return "Enter";
-
- // "EraseEof"
-
- // "Execute"
- case NSExecuteFunctionKey:
- return "Execute";
-
- // "Exsel"
-
- // "F1"
- case NSF1FunctionKey:
- return "F1";
- // "F2"
- case NSF2FunctionKey:
- return "F2";
- // "F3"
- case NSF3FunctionKey:
- return "F3";
- // "F4"
- case NSF4FunctionKey:
- return "F4";
- // "F5"
- case NSF5FunctionKey:
- return "F5";
- // "F6"
- case NSF6FunctionKey:
- return "F6";
- // "F7"
- case NSF7FunctionKey:
- return "F7";
- // "F8"
- case NSF8FunctionKey:
- return "F8";
- // "F9"
- case NSF9FunctionKey:
- return "F9";
- // "F10"
- case NSF10FunctionKey:
- return "F10";
- // "F11"
- case NSF11FunctionKey:
- return "F11";
- // "F12"
- case NSF12FunctionKey:
- return "F12";
- // "F13"
- case NSF13FunctionKey:
- return "F13";
- // "F14"
- case NSF14FunctionKey:
- return "F14";
- // "F15"
- case NSF15FunctionKey:
- return "F15";
- // "F16"
- case NSF16FunctionKey:
- return "F16";
- // "F17"
- case NSF17FunctionKey:
- return "F17";
- // "F18"
- case NSF18FunctionKey:
- return "F18";
- // "F19"
- case NSF19FunctionKey:
- return "F19";
- // "F20"
- case NSF20FunctionKey:
- return "F20";
- // "F21"
- case NSF21FunctionKey:
- return "F21";
- // "F22"
- case NSF22FunctionKey:
- return "F22";
- // "F23"
- case NSF23FunctionKey:
- return "F23";
- // "F24"
- case NSF24FunctionKey:
- return "F24";
-
- // "FinalMode"
-
- // "Find"
- case NSFindFunctionKey:
- return "Find";
-
- // "FullWidth"
- // "HalfWidth"
- // "HangulMode"
- // "HanjaMode"
-
- // "Help"
- case NSHelpFunctionKey:
- return "Help";
-
- // "Hiragana"
-
- // "Home"
- case NSHomeFunctionKey:
- return "Home";
- // "Insert"
- case NSInsertFunctionKey:
- return "Insert";
-
- // "JapaneseHiragana"
- // "JapaneseKatakana"
- // "JapaneseRomaji"
- // "JunjaMode"
- // "KanaMode"
- // "KanjiMode"
- // "Katakana"
- // "LaunchApplication1"
- // "LaunchApplication2"
- // "LaunchMail"
-
- // "Left"
- case NSLeftArrowFunctionKey:
- return "Left";
-
- // "Meta"
- // "MediaNextTrack"
- // "MediaPlayPause"
- // "MediaPreviousTrack"
- // "MediaStop"
-
- // "ModeChange"
- case NSModeSwitchFunctionKey:
- return "ModeChange";
-
- // "Nonconvert"
- // "NumLock"
-
- // "PageDown"
- case NSPageDownFunctionKey:
- return "PageDown";
- // "PageUp"
- case NSPageUpFunctionKey:
- return "PageUp";
-
- // "Paste"
-
- // "Pause"
- case NSPauseFunctionKey:
- return "Pause";
-
- // "Play"
- // "PreviousCandidate"
-
- // "PrintScreen"
- case NSPrintScreenFunctionKey:
- return "PrintScreen";
-
- // "Process"
- // "Props"
-
- // "Right"
- case NSRightArrowFunctionKey:
- return "Right";
-
- // "RomanCharacters"
-
- // "Scroll"
- case NSScrollLockFunctionKey:
- return "Scroll";
- // "Select"
- case NSSelectFunctionKey:
- return "Select";
-
- // "SelectMedia"
- // "Shift"
-
- // "Stop"
- case NSStopFunctionKey:
- return "Stop";
- // "Up"
- case NSUpArrowFunctionKey:
- return "Up";
- // "Undo"
- case NSUndoFunctionKey:
- return "Undo";
-
- // "VolumeDown"
- // "VolumeMute"
- // "VolumeUp"
- // "Win"
- // "Zoom"
-
- // More function keys, not in the key identifier specification.
- case NSF25FunctionKey:
- return "F25";
- case NSF26FunctionKey:
- return "F26";
- case NSF27FunctionKey:
- return "F27";
- case NSF28FunctionKey:
- return "F28";
- case NSF29FunctionKey:
- return "F29";
- case NSF30FunctionKey:
- return "F30";
- case NSF31FunctionKey:
- return "F31";
- case NSF32FunctionKey:
- return "F32";
- case NSF33FunctionKey:
- return "F33";
- case NSF34FunctionKey:
- return "F34";
- case NSF35FunctionKey:
- return "F35";
-
- // Turn 0x7F into 0x08, because backspace needs to always be 0x08.
- case 0x7F:
- return "U+0008";
- // Standard says that DEL becomes U+007F.
- case NSDeleteFunctionKey:
- return "U+007F";
-
- // Always use 0x09 for tab instead of AppKit's backtab character.
- case NSBackTabCharacter:
- return "U+0009";
-
- case NSBeginFunctionKey:
- case NSBreakFunctionKey:
- case NSClearDisplayFunctionKey:
- case NSDeleteCharFunctionKey:
- case NSDeleteLineFunctionKey:
- case NSInsertCharFunctionKey:
- case NSInsertLineFunctionKey:
- case NSNextFunctionKey:
- case NSPrevFunctionKey:
- case NSPrintFunctionKey:
- case NSRedoFunctionKey:
- case NSResetFunctionKey:
- case NSSysReqFunctionKey:
- case NSSystemFunctionKey:
- case NSUserFunctionKey:
- // FIXME: We should use something other than the vendor-area Unicode values for the above keys.
- // For now, just fall through to the default.
- default:
- return String::format("U+%04X", toASCIIUpper(charCode));
- }
-}
-
-int windowsKeyCodeForKeyCode(uint16_t keyCode)
-{
- static const int windowsKeyCode[] = {
- /* 0 */ VK_A,
- /* 1 */ VK_S,
- /* 2 */ VK_D,
- /* 3 */ VK_F,
- /* 4 */ VK_H,
- /* 5 */ VK_G,
- /* 6 */ VK_Z,
- /* 7 */ VK_X,
- /* 8 */ VK_C,
- /* 9 */ VK_V,
- /* 0x0A */ VK_OEM_3, // "Section" - key to the left from 1 (ISO Keyboard Only)
- /* 0x0B */ VK_B,
- /* 0x0C */ VK_Q,
- /* 0x0D */ VK_W,
- /* 0x0E */ VK_E,
- /* 0x0F */ VK_R,
- /* 0x10 */ VK_Y,
- /* 0x11 */ VK_T,
- /* 0x12 */ VK_1,
- /* 0x13 */ VK_2,
- /* 0x14 */ VK_3,
- /* 0x15 */ VK_4,
- /* 0x16 */ VK_6,
- /* 0x17 */ VK_5,
- /* 0x18 */ VK_OEM_PLUS, // =+
- /* 0x19 */ VK_9,
- /* 0x1A */ VK_7,
- /* 0x1B */ VK_OEM_MINUS, // -_
- /* 0x1C */ VK_8,
- /* 0x1D */ VK_0,
- /* 0x1E */ VK_OEM_6, // ]}
- /* 0x1F */ VK_O,
- /* 0x20 */ VK_U,
- /* 0x21 */ VK_OEM_4, // {[
- /* 0x22 */ VK_I,
- /* 0x23 */ VK_P,
- /* 0x24 */ VK_RETURN, // Return
- /* 0x25 */ VK_L,
- /* 0x26 */ VK_J,
- /* 0x27 */ VK_OEM_7, // '"
- /* 0x28 */ VK_K,
- /* 0x29 */ VK_OEM_1, // ;:
- /* 0x2A */ VK_OEM_5, // \|
- /* 0x2B */ VK_OEM_COMMA, // ,<
- /* 0x2C */ VK_OEM_2, // /?
- /* 0x2D */ VK_N,
- /* 0x2E */ VK_M,
- /* 0x2F */ VK_OEM_PERIOD, // .>
- /* 0x30 */ VK_TAB,
- /* 0x31 */ VK_SPACE,
- /* 0x32 */ VK_OEM_3, // `~
- /* 0x33 */ VK_BACK, // Backspace
- /* 0x34 */ 0, // n/a
- /* 0x35 */ VK_ESCAPE,
- /* 0x36 */ VK_APPS, // Right Command
- /* 0x37 */ VK_LWIN, // Left Command
- /* 0x38 */ VK_LSHIFT, // Left Shift
- /* 0x39 */ VK_CAPITAL, // Caps Lock
- /* 0x3A */ VK_LMENU, // Left Option
- /* 0x3B */ VK_LCONTROL, // Left Ctrl
- /* 0x3C */ VK_RSHIFT, // Right Shift
- /* 0x3D */ VK_RMENU, // Right Option
- /* 0x3E */ VK_RCONTROL, // Right Ctrl
- /* 0x3F */ 0, // fn
- /* 0x40 */ VK_F17,
- /* 0x41 */ VK_DECIMAL, // Num Pad .
- /* 0x42 */ 0, // n/a
- /* 0x43 */ VK_MULTIPLY, // Num Pad *
- /* 0x44 */ 0, // n/a
- /* 0x45 */ VK_ADD, // Num Pad +
- /* 0x46 */ 0, // n/a
- /* 0x47 */ VK_CLEAR, // Num Pad Clear
- /* 0x48 */ VK_VOLUME_UP,
- /* 0x49 */ VK_VOLUME_DOWN,
- /* 0x4A */ VK_VOLUME_MUTE,
- /* 0x4B */ VK_DIVIDE, // Num Pad /
- /* 0x4C */ VK_RETURN, // Num Pad Enter
- /* 0x4D */ 0, // n/a
- /* 0x4E */ VK_SUBTRACT, // Num Pad -
- /* 0x4F */ VK_F18,
- /* 0x50 */ VK_F19,
- /* 0x51 */ VK_OEM_PLUS, // Num Pad =. There is no such key on common PC keyboards, mapping to normal "+=".
- /* 0x52 */ VK_NUMPAD0,
- /* 0x53 */ VK_NUMPAD1,
- /* 0x54 */ VK_NUMPAD2,
- /* 0x55 */ VK_NUMPAD3,
- /* 0x56 */ VK_NUMPAD4,
- /* 0x57 */ VK_NUMPAD5,
- /* 0x58 */ VK_NUMPAD6,
- /* 0x59 */ VK_NUMPAD7,
- /* 0x5A */ VK_F20,
- /* 0x5B */ VK_NUMPAD8,
- /* 0x5C */ VK_NUMPAD9,
- /* 0x5D */ 0, // Yen (JIS Keyboard Only)
- /* 0x5E */ 0, // Underscore (JIS Keyboard Only)
- /* 0x5F */ 0, // KeypadComma (JIS Keyboard Only)
- /* 0x60 */ VK_F5,
- /* 0x61 */ VK_F6,
- /* 0x62 */ VK_F7,
- /* 0x63 */ VK_F3,
- /* 0x64 */ VK_F8,
- /* 0x65 */ VK_F9,
- /* 0x66 */ 0, // Eisu (JIS Keyboard Only)
- /* 0x67 */ VK_F11,
- /* 0x68 */ 0, // Kana (JIS Keyboard Only)
- /* 0x69 */ VK_F13,
- /* 0x6A */ VK_F16,
- /* 0x6B */ VK_F14,
- /* 0x6C */ 0, // n/a
- /* 0x6D */ VK_F10,
- /* 0x6E */ 0, // n/a (Windows95 key?)
- /* 0x6F */ VK_F12,
- /* 0x70 */ 0, // n/a
- /* 0x71 */ VK_F15,
- /* 0x72 */ VK_INSERT, // Help
- /* 0x73 */ VK_HOME, // Home
- /* 0x74 */ VK_PRIOR, // Page Up
- /* 0x75 */ VK_DELETE, // Forward Delete
- /* 0x76 */ VK_F4,
- /* 0x77 */ VK_END, // End
- /* 0x78 */ VK_F2,
- /* 0x79 */ VK_NEXT, // Page Down
- /* 0x7A */ VK_F1,
- /* 0x7B */ VK_LEFT, // Left Arrow
- /* 0x7C */ VK_RIGHT, // Right Arrow
- /* 0x7D */ VK_DOWN, // Down Arrow
- /* 0x7E */ VK_UP, // Up Arrow
- /* 0x7F */ 0 // n/a
- };
-
- if (keyCode >= 0x80)
- return 0;
-
- return windowsKeyCode[keyCode];
-}
-
-int windowsKeyCodeForCharCode(unichar charCode)
-{
- switch (charCode) {
-
- case 'a': case 'A': return VK_A;
- case 'b': case 'B': return VK_B;
- case 'c': case 'C': return VK_C;
- case 'd': case 'D': return VK_D;
- case 'e': case 'E': return VK_E;
- case 'f': case 'F': return VK_F;
- case 'g': case 'G': return VK_G;
- case 'h': case 'H': return VK_H;
- case 'i': case 'I': return VK_I;
- case 'j': case 'J': return VK_J;
- case 'k': case 'K': return VK_K;
- case 'l': case 'L': return VK_L;
- case 'm': case 'M': return VK_M;
- case 'n': case 'N': return VK_N;
- case 'o': case 'O': return VK_O;
- case 'p': case 'P': return VK_P;
- case 'q': case 'Q': return VK_Q;
- case 'r': case 'R': return VK_R;
- case 's': case 'S': return VK_S;
- case 't': case 'T': return VK_T;
- case 'u': case 'U': return VK_U;
- case 'v': case 'V': return VK_V;
- case 'w': case 'W': return VK_W;
- case 'x': case 'X': return VK_X;
- case 'y': case 'Y': return VK_Y;
- case 'z': case 'Z': return VK_Z;
-
- // AppKit generates Unicode PUA character codes for some function keys; using these when key code is not known.
- case NSPauseFunctionKey: return VK_PAUSE;
- case NSSelectFunctionKey: return VK_SELECT;
- case NSPrintFunctionKey: return VK_PRINT;
- case NSExecuteFunctionKey: return VK_EXECUTE;
- case NSPrintScreenFunctionKey: return VK_SNAPSHOT;
- case NSInsertFunctionKey: return VK_INSERT;
-
- case NSF21FunctionKey: return VK_F21;
- case NSF22FunctionKey: return VK_F22;
- case NSF23FunctionKey: return VK_F23;
- case NSF24FunctionKey: return VK_F24;
- case NSScrollLockFunctionKey: return VK_SCROLL;
-
- // This is for U.S. keyboard mapping, and doesn't necessarily make sense for different keyboard layouts.
- // For example, '"' on Windows Russian layout is VK_2, not VK_OEM_7.
- case ';': case ':': return VK_OEM_1;
- case '=': case '+': return VK_OEM_PLUS;
- case ',': case '<': return VK_OEM_COMMA;
- case '-': case '_': return VK_OEM_MINUS;
- case '.': case '>': return VK_OEM_PERIOD;
- case '/': case '?': return VK_OEM_2;
- case '`': case '~': return VK_OEM_3;
- case '[': case '{': return VK_OEM_4;
- case '\\': case '|': return VK_OEM_5;
- case ']': case '}': return VK_OEM_6;
- case '\'': case '"': return VK_OEM_7;
-
- }
-
- return 0;
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/ANGLEWebKitBridge.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/ANGLEWebKitBridge.cpp
deleted file mode 100644
index 4b5021d1382..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/ANGLEWebKitBridge.cpp
+++ /dev/null
@@ -1,227 +0,0 @@
-/*
- * Copyright (C) 2010 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/platform/graphics/ANGLEWebKitBridge.h"
-#include "wtf/OwnArrayPtr.h"
-
-namespace WebCore {
-
-typedef size_t ANGLEGetInfoType;
-
-inline static ANGLEGetInfoType getValidationResultValue(const ShHandle compiler, ShShaderInfo shaderInfo)
-{
- ANGLEGetInfoType value = 0;
- ShGetInfo(compiler, shaderInfo, &value);
- return value;
-}
-
-static bool getSymbolInfo(ShHandle compiler, ShShaderInfo symbolType, Vector<ANGLEShaderSymbol>& symbols)
-{
- ShShaderInfo symbolMaxNameLengthType;
-
- switch (symbolType) {
- case SH_ACTIVE_ATTRIBUTES:
- symbolMaxNameLengthType = SH_ACTIVE_ATTRIBUTE_MAX_LENGTH;
- break;
- case SH_ACTIVE_UNIFORMS:
- symbolMaxNameLengthType = SH_ACTIVE_UNIFORM_MAX_LENGTH;
- break;
- default:
- ASSERT_NOT_REACHED();
- return false;
- }
-
- ANGLEGetInfoType numSymbols = getValidationResultValue(compiler, symbolType);
-
- ANGLEGetInfoType maxNameLength = getValidationResultValue(compiler, symbolMaxNameLengthType);
- if (maxNameLength <= 1)
- return false;
-
- ANGLEGetInfoType maxMappedNameLength = getValidationResultValue(compiler, SH_MAPPED_NAME_MAX_LENGTH);
- if (maxMappedNameLength <= 1)
- return false;
-
- // The maximum allowed symbol name length is 256 characters.
- Vector<char, 256> nameBuffer(maxNameLength);
- Vector<char, 256> mappedNameBuffer(maxMappedNameLength);
-
- for (ANGLEGetInfoType i = 0; i < numSymbols; ++i) {
- ANGLEShaderSymbol symbol;
- ANGLEGetInfoType nameLength = 0;
- switch (symbolType) {
- case SH_ACTIVE_ATTRIBUTES:
- symbol.symbolType = SHADER_SYMBOL_TYPE_ATTRIBUTE;
-#if ANGLE_SH_VERSION >= 112
- ShGetVariableInfo(compiler, symbolType, i, &nameLength, &symbol.size, &symbol.dataType, &symbol.precision, &symbol.staticUse, nameBuffer.data(), mappedNameBuffer.data());
-#else
- ShGetVariableInfo(compiler, symbolType, i, &nameLength, &symbol.size, &symbol.dataType, &symbol.precision, nameBuffer.data(), mappedNameBuffer.data());
-#endif
- break;
- case SH_ACTIVE_UNIFORMS:
- symbol.symbolType = SHADER_SYMBOL_TYPE_UNIFORM;
-#if ANGLE_SH_VERSION >= 112
- ShGetVariableInfo(compiler, symbolType, i, &nameLength, &symbol.size, &symbol.dataType, &symbol.precision, &symbol.staticUse, nameBuffer.data(), mappedNameBuffer.data());
-#else
- ShGetVariableInfo(compiler, symbolType, i, &nameLength, &symbol.size, &symbol.dataType, &symbol.precision, nameBuffer.data(), mappedNameBuffer.data());
-#endif
- break;
- default:
- ASSERT_NOT_REACHED();
- return false;
- }
- if (!nameLength)
- return false;
-
- // The ShGetActive* calls above are guaranteed to produce null-terminated strings for
- // nameBuffer and mappedNameBuffer. Also, the character set for symbol names
- // is a subset of Latin-1 as specified by the OpenGL ES Shading Language, Section 3.1 and
- // WebGL, Section "Characters Outside the GLSL Source Character Set".
-
- String name = String(nameBuffer.data());
- String mappedName = String(mappedNameBuffer.data());
-
- // ANGLE returns array names in the format "array[0]".
- // The only way to know if a symbol is an array is to check if it ends with "[0]".
- // We can't check the size because regular symbols and arrays of length 1 both have a size of 1.
- symbol.isArray = name.endsWith("[0]") && mappedName.endsWith("[0]");
- if (symbol.isArray) {
- // Add a symbol for the array name without the "[0]" suffix.
- name.truncate(name.length() - 3);
- mappedName.truncate(mappedName.length() - 3);
- }
-
- symbol.name = name;
- symbol.mappedName = mappedName;
- symbols.append(symbol);
-
- if (symbol.isArray) {
- // Add symbols for each array element.
- symbol.isArray = false;
- for (int i = 0; i < symbol.size; i++) {
- String arrayBrackets = "[" + String::number(i) + "]";
- symbol.name = name + arrayBrackets;
- symbol.mappedName = mappedName + arrayBrackets;
- symbols.append(symbol);
- }
- }
- }
- return true;
-}
-
-ANGLEWebKitBridge::ANGLEWebKitBridge(ShShaderOutput shaderOutput, ShShaderSpec shaderSpec)
- : builtCompilers(false)
- , m_fragmentCompiler(0)
- , m_vertexCompiler(0)
- , m_shaderOutput(shaderOutput)
- , m_shaderSpec(shaderSpec)
-{
- // This is a no-op if it's already initialized.
- ShInitialize();
-}
-
-ANGLEWebKitBridge::~ANGLEWebKitBridge()
-{
- cleanupCompilers();
-}
-
-void ANGLEWebKitBridge::cleanupCompilers()
-{
- if (m_fragmentCompiler)
- ShDestruct(m_fragmentCompiler);
- m_fragmentCompiler = 0;
- if (m_vertexCompiler)
- ShDestruct(m_vertexCompiler);
- m_vertexCompiler = 0;
-
- builtCompilers = false;
-}
-
-void ANGLEWebKitBridge::setResources(ShBuiltInResources resources)
-{
- // Resources are (possibly) changing - cleanup compilers if we had them already
- cleanupCompilers();
-
- m_resources = resources;
-}
-
-bool ANGLEWebKitBridge::compileShaderSource(const char* shaderSource, ANGLEShaderType shaderType, String& translatedShaderSource, String& shaderValidationLog, Vector<ANGLEShaderSymbol>& symbols, int extraCompileOptions)
-{
- if (!builtCompilers) {
- m_fragmentCompiler = ShConstructCompiler(SH_FRAGMENT_SHADER, m_shaderSpec, m_shaderOutput, &m_resources);
- m_vertexCompiler = ShConstructCompiler(SH_VERTEX_SHADER, m_shaderSpec, m_shaderOutput, &m_resources);
- if (!m_fragmentCompiler || !m_vertexCompiler) {
- cleanupCompilers();
- return false;
- }
-
- builtCompilers = true;
- }
-
- ShHandle compiler;
-
- if (shaderType == SHADER_TYPE_VERTEX)
- compiler = m_vertexCompiler;
- else
- compiler = m_fragmentCompiler;
-
- const char* const shaderSourceStrings[] = { shaderSource };
-
-#if ANGLE_SH_VERSION >= 111
- bool validateSuccess = ShCompile(compiler, shaderSourceStrings, 1, SH_OBJECT_CODE | SH_VARIABLES | extraCompileOptions);
-#else
- bool validateSuccess = ShCompile(compiler, shaderSourceStrings, 1, SH_OBJECT_CODE | SH_ATTRIBUTES_UNIFORMS | extraCompileOptions);
-#endif
- if (!validateSuccess) {
- int logSize = getValidationResultValue(compiler, SH_INFO_LOG_LENGTH);
- if (logSize > 1) {
- OwnArrayPtr<char> logBuffer = adoptArrayPtr(new char[logSize]);
- if (logBuffer) {
- ShGetInfoLog(compiler, logBuffer.get());
- shaderValidationLog = logBuffer.get();
- }
- }
- return false;
- }
-
- int translationLength = getValidationResultValue(compiler, SH_OBJECT_CODE_LENGTH);
- if (translationLength > 1) {
- OwnArrayPtr<char> translationBuffer = adoptArrayPtr(new char[translationLength]);
- if (!translationBuffer)
- return false;
- ShGetObjectCode(compiler, translationBuffer.get());
- translatedShaderSource = translationBuffer.get();
- }
-
- if (!getSymbolInfo(compiler, SH_ACTIVE_ATTRIBUTES, symbols))
- return false;
- if (!getSymbolInfo(compiler, SH_ACTIVE_UNIFORMS, symbols))
- return false;
-
- return true;
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/ANGLEWebKitBridge.h b/chromium/third_party/WebKit/Source/core/platform/graphics/ANGLEWebKitBridge.h
deleted file mode 100644
index d41c8309ac1..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/ANGLEWebKitBridge.h
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * Copyright (C) 2010 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ANGLEWebKitBridge_h
-#define ANGLEWebKitBridge_h
-
-#include "wtf/text/CString.h"
-#include "wtf/text/WTFString.h"
-
-#include "ShaderLang.h"
-
-namespace WebCore {
-
-enum ANGLEShaderType {
- SHADER_TYPE_VERTEX = SH_VERTEX_SHADER,
- SHADER_TYPE_FRAGMENT = SH_FRAGMENT_SHADER,
-};
-
-enum ANGLEShaderSymbolType {
- SHADER_SYMBOL_TYPE_ATTRIBUTE,
- SHADER_SYMBOL_TYPE_UNIFORM
-};
-
-struct ANGLEShaderSymbol {
- ANGLEShaderSymbolType symbolType;
- String name;
- String mappedName;
- ShDataType dataType;
- int size;
- bool isArray;
- ShPrecisionType precision;
-#if ANGLE_SH_VERSION >= 112
- int staticUse;
-#endif
-
- bool isSampler() const
- {
- return symbolType == SHADER_SYMBOL_TYPE_UNIFORM
- && (dataType == SH_SAMPLER_2D
- || dataType == SH_SAMPLER_CUBE
- || dataType == SH_SAMPLER_2D_RECT_ARB
- || dataType == SH_SAMPLER_EXTERNAL_OES);
- }
-};
-
-class ANGLEWebKitBridge {
-public:
-
- ANGLEWebKitBridge(ShShaderOutput = SH_GLSL_OUTPUT, ShShaderSpec = SH_WEBGL_SPEC);
- ~ANGLEWebKitBridge();
-
- ShBuiltInResources getResources() { return m_resources; }
- void setResources(ShBuiltInResources);
-
- bool compileShaderSource(const char* shaderSource, ANGLEShaderType, String& translatedShaderSource, String& shaderValidationLog, Vector<ANGLEShaderSymbol>& symbols, int extraCompileOptions = 0);
-
-private:
-
- void cleanupCompilers();
-
- bool builtCompilers;
-
- ShHandle m_fragmentCompiler;
- ShHandle m_vertexCompiler;
-
- ShShaderOutput m_shaderOutput;
- ShShaderSpec m_shaderSpec;
-
- ShBuiltInResources m_resources;
-};
-
-} // namespace WebCore
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/BitmapImage.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/BitmapImage.cpp
deleted file mode 100644
index 00320fbc729..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/BitmapImage.cpp
+++ /dev/null
@@ -1,654 +0,0 @@
-/*
- * Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
- * Copyright (C) 2004, 2005, 2006, 2008 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/BitmapImage.h"
-
-#include "core/platform/Timer.h"
-#include "core/platform/graphics/FloatRect.h"
-#include "core/platform/graphics/GraphicsContextStateSaver.h"
-#include "core/platform/graphics/ImageObserver.h"
-#include "core/platform/graphics/skia/NativeImageSkia.h"
-#include "core/platform/graphics/skia/SkiaUtils.h"
-#include "wtf/CurrentTime.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/Vector.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-BitmapImage::BitmapImage(ImageObserver* observer)
- : Image(observer)
- , m_currentFrame(0)
- , m_frames(0)
- , m_frameTimer(0)
- , m_repetitionCount(cAnimationNone)
- , m_repetitionCountStatus(Unknown)
- , m_repetitionsComplete(0)
- , m_desiredFrameStartTime(0)
- , m_decodedSize(0)
- , m_decodedPropertiesSize(0)
- , m_frameCount(0)
- , m_isSolidColor(false)
- , m_checkedForSolidColor(false)
- , m_animationFinished(false)
- , m_allDataReceived(false)
- , m_haveSize(false)
- , m_sizeAvailable(false)
- , m_hasUniformFrameSize(true)
- , m_haveFrameCount(false)
-{
-}
-
-BitmapImage::BitmapImage(PassRefPtr<NativeImageSkia> nativeImage, ImageObserver* observer)
- : Image(observer)
- , m_size(nativeImage->bitmap().width(), nativeImage->bitmap().height())
- , m_currentFrame(0)
- , m_frames(0)
- , m_frameTimer(0)
- , m_repetitionCount(cAnimationNone)
- , m_repetitionCountStatus(Unknown)
- , m_repetitionsComplete(0)
- , m_decodedSize(nativeImage->decodedSize())
- , m_decodedPropertiesSize(0)
- , m_frameCount(1)
- , m_isSolidColor(false)
- , m_checkedForSolidColor(false)
- , m_animationFinished(true)
- , m_allDataReceived(true)
- , m_haveSize(true)
- , m_sizeAvailable(true)
- , m_haveFrameCount(true)
-{
- // Since we don't have a decoder, we can't figure out the image orientation.
- // Set m_sizeRespectingOrientation to be the same as m_size so it's not 0x0.
- m_sizeRespectingOrientation = m_size;
-
- m_frames.grow(1);
- m_frames[0].m_hasAlpha = !nativeImage->bitmap().isOpaque();
- m_frames[0].m_frame = nativeImage;
- m_frames[0].m_haveMetadata = true;
-
- checkForSolidColor();
-}
-
-BitmapImage::~BitmapImage()
-{
- stopAnimation();
-}
-
-bool BitmapImage::isBitmapImage() const
-{
- return true;
-}
-
-void BitmapImage::destroyDecodedData(bool destroyAll)
-{
- for (size_t i = 0; i < m_frames.size(); ++i) {
- // The underlying frame isn't actually changing (we're just trying to
- // save the memory for the framebuffer data), so we don't need to clear
- // the metadata.
- m_frames[i].clear(false);
- }
-
- destroyMetadataAndNotify(m_source.clearCacheExceptFrame(destroyAll ? kNotFound : m_currentFrame));
-}
-
-void BitmapImage::destroyDecodedDataIfNecessary()
-{
- // Animated images >5MB are considered large enough that we'll only hang on
- // to one frame at a time.
- static const size_t cLargeAnimationCutoff = 5242880;
- size_t allFrameBytes = 0;
- for (size_t i = 0; i < m_frames.size(); ++i)
- allFrameBytes += m_frames[i].m_frameBytes;
-
- if (allFrameBytes > cLargeAnimationCutoff)
- destroyDecodedData(false);
-}
-
-void BitmapImage::destroyMetadataAndNotify(size_t frameBytesCleared)
-{
- m_isSolidColor = false;
- m_checkedForSolidColor = false;
-
- ASSERT(m_decodedSize >= frameBytesCleared);
- m_decodedSize -= frameBytesCleared;
- if (frameBytesCleared > 0) {
- frameBytesCleared += m_decodedPropertiesSize;
- m_decodedPropertiesSize = 0;
- }
- if (frameBytesCleared && imageObserver())
- imageObserver()->decodedSizeChanged(this, -safeCast<int>(frameBytesCleared));
-}
-
-void BitmapImage::cacheFrame(size_t index)
-{
- size_t numFrames = frameCount();
- if (m_frames.size() < numFrames)
- m_frames.grow(numFrames);
-
- m_frames[index].m_frame = m_source.createFrameAtIndex(index);
- if (numFrames == 1 && m_frames[index].m_frame)
- checkForSolidColor();
-
- m_frames[index].m_orientation = m_source.orientationAtIndex(index);
- m_frames[index].m_haveMetadata = true;
- m_frames[index].m_isComplete = m_source.frameIsCompleteAtIndex(index);
- if (repetitionCount(false) != cAnimationNone)
- m_frames[index].m_duration = m_source.frameDurationAtIndex(index);
- m_frames[index].m_hasAlpha = m_source.frameHasAlphaAtIndex(index);
- m_frames[index].m_frameBytes = m_source.frameBytesAtIndex(index);
-
- const IntSize frameSize(index ? m_source.frameSizeAtIndex(index) : m_size);
- if (frameSize != m_size)
- m_hasUniformFrameSize = false;
- if (m_frames[index].m_frame) {
- int deltaBytes = safeCast<int>(m_frames[index].m_frameBytes);
- m_decodedSize += deltaBytes;
- // The fully-decoded frame will subsume the partially decoded data used
- // to determine image properties.
- deltaBytes -= m_decodedPropertiesSize;
- m_decodedPropertiesSize = 0;
- if (imageObserver())
- imageObserver()->decodedSizeChanged(this, deltaBytes);
- }
-}
-
-void BitmapImage::didDecodeProperties() const
-{
- if (m_decodedSize)
- return;
- size_t updatedSize = m_source.bytesDecodedToDetermineProperties();
- if (m_decodedPropertiesSize == updatedSize)
- return;
- int deltaBytes = updatedSize - m_decodedPropertiesSize;
-#if !ASSERT_DISABLED
- bool overflow = updatedSize > m_decodedPropertiesSize && deltaBytes < 0;
- bool underflow = updatedSize < m_decodedPropertiesSize && deltaBytes > 0;
- ASSERT(!overflow && !underflow);
-#endif
- m_decodedPropertiesSize = updatedSize;
- if (imageObserver())
- imageObserver()->decodedSizeChanged(this, deltaBytes);
-}
-
-void BitmapImage::updateSize() const
-{
- if (!m_sizeAvailable || m_haveSize)
- return;
-
- m_size = m_source.size();
- m_sizeRespectingOrientation = m_source.size(RespectImageOrientation);
- m_haveSize = true;
- didDecodeProperties();
-}
-
-IntSize BitmapImage::size() const
-{
- updateSize();
- return m_size;
-}
-
-IntSize BitmapImage::sizeRespectingOrientation() const
-{
- updateSize();
- return m_sizeRespectingOrientation;
-}
-
-IntSize BitmapImage::currentFrameSize() const
-{
- if (!m_currentFrame || m_hasUniformFrameSize)
- return size();
- IntSize frameSize = m_source.frameSizeAtIndex(m_currentFrame);
- didDecodeProperties();
- return frameSize;
-}
-
-bool BitmapImage::getHotSpot(IntPoint& hotSpot) const
-{
- bool result = m_source.getHotSpot(hotSpot);
- didDecodeProperties();
- return result;
-}
-
-bool BitmapImage::dataChanged(bool allDataReceived)
-{
- // Clear all partially-decoded frames. For most image formats, there is only
- // one frame, but at least GIF and ICO can have more. With GIFs, the frames
- // come in order and we ask to decode them in order, waiting to request a
- // subsequent frame until the prior one is complete. Given that we clear
- // incomplete frames here, this means there is at most one incomplete frame
- // (even if we use destroyDecodedData() -- since it doesn't reset the
- // metadata), and it is after all the complete frames.
- //
- // With ICOs, on the other hand, we may ask for arbitrary frames at
- // different times (e.g. because we're displaying a higher-resolution image
- // in the content area and using a lower-resolution one for the favicon),
- // and the frames aren't even guaranteed to appear in the file in the same
- // order as in the directory, so an arbitrary number of the frames might be
- // incomplete (if we ask for frames for which we've not yet reached the
- // start of the frame data), and any or none of them might be the particular
- // frame affected by appending new data here. Thus we have to clear all the
- // incomplete frames to be safe.
- unsigned frameBytesCleared = 0;
- for (size_t i = 0; i < m_frames.size(); ++i) {
- // NOTE: Don't call frameIsCompleteAtIndex() here, that will try to
- // decode any uncached (i.e. never-decoded or
- // cleared-on-a-previous-pass) frames!
- unsigned frameBytes = m_frames[i].m_frameBytes;
- if (m_frames[i].m_haveMetadata && !m_frames[i].m_isComplete)
- frameBytesCleared += (m_frames[i].clear(true) ? frameBytes : 0);
- }
- destroyMetadataAndNotify(frameBytesCleared);
-
- // Feed all the data we've seen so far to the image decoder.
- m_allDataReceived = allDataReceived;
- m_source.setData(data(), allDataReceived);
-
- m_haveFrameCount = false;
- m_hasUniformFrameSize = true;
- return isSizeAvailable();
-}
-
-String BitmapImage::filenameExtension() const
-{
- return m_source.filenameExtension();
-}
-
-void BitmapImage::draw(GraphicsContext* ctxt, const FloatRect& dstRect, const FloatRect& srcRect, CompositeOperator compositeOp, BlendMode blendMode)
-{
- draw(ctxt, dstRect, srcRect, compositeOp, blendMode, DoNotRespectImageOrientation);
-}
-
-void BitmapImage::draw(GraphicsContext* ctxt, const FloatRect& dstRect, const FloatRect& srcRect, CompositeOperator compositeOp, BlendMode blendMode, RespectImageOrientationEnum shouldRespectImageOrientation)
-{
- // Spin the animation to the correct frame before we try to draw it, so we
- // don't draw an old frame and then immediately need to draw a newer one,
- // causing flicker and wasting CPU.
- startAnimation();
-
- RefPtr<NativeImageSkia> bm = nativeImageForCurrentFrame();
- if (!bm)
- return; // It's too early and we don't have an image yet.
-
- FloatRect normDstRect = adjustForNegativeSize(dstRect);
- FloatRect normSrcRect = adjustForNegativeSize(srcRect);
- normSrcRect.intersect(FloatRect(0, 0, bm->bitmap().width(), bm->bitmap().height()));
-
- if (normSrcRect.isEmpty() || normDstRect.isEmpty())
- return; // Nothing to draw.
-
- ImageOrientation orientation = DefaultImageOrientation;
- if (shouldRespectImageOrientation == RespectImageOrientation)
- orientation = frameOrientationAtIndex(m_currentFrame);
-
- GraphicsContextStateSaver saveContext(*ctxt, false);
- if (orientation != DefaultImageOrientation) {
- saveContext.save();
-
- // ImageOrientation expects the origin to be at (0, 0)
- ctxt->translate(normDstRect.x(), normDstRect.y());
- normDstRect.setLocation(FloatPoint());
-
- ctxt->concatCTM(orientation.transformFromDefault(normDstRect.size()));
-
- if (orientation.usesWidthAsHeight()) {
- // The destination rect will have it's width and height already reversed for the orientation of
- // the image, as it was needed for page layout, so we need to reverse it back here.
- normDstRect = FloatRect(normDstRect.x(), normDstRect.y(), normDstRect.height(), normDstRect.width());
- }
- }
-
- bm->draw(ctxt, normSrcRect, normDstRect, WebCoreCompositeToSkiaComposite(compositeOp, blendMode));
-
- if (ImageObserver* observer = imageObserver())
- observer->didDraw(this);
-}
-
-size_t BitmapImage::frameCount()
-{
- if (!m_haveFrameCount) {
- m_frameCount = m_source.frameCount();
- // If decoder is not initialized yet, m_source.frameCount() returns 0.
- if (m_frameCount) {
- didDecodeProperties();
- m_haveFrameCount = true;
- }
- }
- return m_frameCount;
-}
-
-bool BitmapImage::isSizeAvailable()
-{
- if (m_sizeAvailable)
- return true;
-
- m_sizeAvailable = m_source.isSizeAvailable();
- didDecodeProperties();
-
- return m_sizeAvailable;
-}
-
-bool BitmapImage::ensureFrameIsCached(size_t index)
-{
- if (index >= frameCount())
- return false;
-
- if (index >= m_frames.size() || !m_frames[index].m_frame)
- cacheFrame(index);
- return true;
-}
-
-PassRefPtr<NativeImageSkia> BitmapImage::frameAtIndex(size_t index)
-{
- if (!ensureFrameIsCached(index))
- return 0;
- return m_frames[index].m_frame;
-}
-
-bool BitmapImage::frameIsCompleteAtIndex(size_t index)
-{
- if (index < m_frames.size() && m_frames[index].m_haveMetadata && m_frames[index].m_isComplete)
- return true;
- return m_source.frameIsCompleteAtIndex(index);
-}
-
-float BitmapImage::frameDurationAtIndex(size_t index)
-{
- if (index < m_frames.size() && m_frames[index].m_haveMetadata)
- return m_frames[index].m_duration;
- return m_source.frameDurationAtIndex(index);
-}
-
-PassRefPtr<NativeImageSkia> BitmapImage::nativeImageForCurrentFrame()
-{
- return frameAtIndex(currentFrame());
-}
-
-bool BitmapImage::frameHasAlphaAtIndex(size_t index)
-{
- if (m_frames.size() <= index)
- return true;
-
- if (m_frames[index].m_haveMetadata)
- return m_frames[index].m_hasAlpha;
-
- return m_source.frameHasAlphaAtIndex(index);
-}
-
-bool BitmapImage::currentFrameKnownToBeOpaque()
-{
- return !frameHasAlphaAtIndex(currentFrame());
-}
-
-ImageOrientation BitmapImage::currentFrameOrientation()
-{
- return frameOrientationAtIndex(currentFrame());
-}
-
-ImageOrientation BitmapImage::frameOrientationAtIndex(size_t index)
-{
- if (m_frames.size() <= index)
- return DefaultImageOrientation;
-
- if (m_frames[index].m_haveMetadata)
- return m_frames[index].m_orientation;
-
- return m_source.orientationAtIndex(index);
-}
-
-#if !ASSERT_DISABLED
-bool BitmapImage::notSolidColor()
-{
- return size().width() != 1 || size().height() != 1 || frameCount() > 1;
-}
-#endif
-
-
-
-int BitmapImage::repetitionCount(bool imageKnownToBeComplete)
-{
- if ((m_repetitionCountStatus == Unknown) || ((m_repetitionCountStatus == Uncertain) && imageKnownToBeComplete)) {
- // Snag the repetition count. If |imageKnownToBeComplete| is false, the
- // repetition count may not be accurate yet for GIFs; in this case the
- // decoder will default to cAnimationLoopOnce, and we'll try and read
- // the count again once the whole image is decoded.
- m_repetitionCount = m_source.repetitionCount();
- didDecodeProperties();
- m_repetitionCountStatus = (imageKnownToBeComplete || m_repetitionCount == cAnimationNone) ? Certain : Uncertain;
- }
- return m_repetitionCount;
-}
-
-bool BitmapImage::shouldAnimate()
-{
- return (repetitionCount(false) != cAnimationNone && !m_animationFinished && imageObserver());
-}
-
-void BitmapImage::startAnimation(bool catchUpIfNecessary)
-{
- if (m_frameTimer || !shouldAnimate() || frameCount() <= 1)
- return;
-
- // If we aren't already animating, set now as the animation start time.
- const double time = monotonicallyIncreasingTime();
- if (!m_desiredFrameStartTime)
- m_desiredFrameStartTime = time;
-
- // Don't advance the animation to an incomplete frame.
- size_t nextFrame = (m_currentFrame + 1) % frameCount();
- if (!m_allDataReceived && !frameIsCompleteAtIndex(nextFrame))
- return;
-
- // Don't advance past the last frame if we haven't decoded the whole image
- // yet and our repetition count is potentially unset. The repetition count
- // in a GIF can potentially come after all the rest of the image data, so
- // wait on it.
- if (!m_allDataReceived && repetitionCount(false) == cAnimationLoopOnce && m_currentFrame >= (frameCount() - 1))
- return;
-
- // Determine time for next frame to start. By ignoring paint and timer lag
- // in this calculation, we make the animation appear to run at its desired
- // rate regardless of how fast it's being repainted.
- const double currentDuration = frameDurationAtIndex(m_currentFrame);
- m_desiredFrameStartTime += currentDuration;
-
- // When an animated image is more than five minutes out of date, the
- // user probably doesn't care about resyncing and we could burn a lot of
- // time looping through frames below. Just reset the timings.
- const double cAnimationResyncCutoff = 5 * 60;
- if ((time - m_desiredFrameStartTime) > cAnimationResyncCutoff)
- m_desiredFrameStartTime = time + currentDuration;
-
- // The image may load more slowly than it's supposed to animate, so that by
- // the time we reach the end of the first repetition, we're well behind.
- // Clamp the desired frame start time in this case, so that we don't skip
- // frames (or whole iterations) trying to "catch up". This is a tradeoff:
- // It guarantees users see the whole animation the second time through and
- // don't miss any repetitions, and is closer to what other browsers do; on
- // the other hand, it makes animations "less accurate" for pages that try to
- // sync an image and some other resource (e.g. audio), especially if users
- // switch tabs (and thus stop drawing the animation, which will pause it)
- // during that initial loop, then switch back later.
- if (nextFrame == 0 && m_repetitionsComplete == 0 && m_desiredFrameStartTime < time)
- m_desiredFrameStartTime = time;
-
- if (!catchUpIfNecessary || time < m_desiredFrameStartTime) {
- // Haven't yet reached time for next frame to start; delay until then.
- m_frameTimer = new Timer<BitmapImage>(this, &BitmapImage::advanceAnimation);
- m_frameTimer->startOneShot(std::max(m_desiredFrameStartTime - time, 0.));
- } else {
- // We've already reached or passed the time for the next frame to start.
- // See if we've also passed the time for frames after that to start, in
- // case we need to skip some frames entirely. Remember not to advance
- // to an incomplete frame.
- for (size_t frameAfterNext = (nextFrame + 1) % frameCount(); frameIsCompleteAtIndex(frameAfterNext); frameAfterNext = (nextFrame + 1) % frameCount()) {
- // Should we skip the next frame?
- double frameAfterNextStartTime = m_desiredFrameStartTime + frameDurationAtIndex(nextFrame);
- if (time < frameAfterNextStartTime)
- break;
-
- // Yes; skip over it without notifying our observers.
- if (!internalAdvanceAnimation(true))
- return;
- m_desiredFrameStartTime = frameAfterNextStartTime;
- nextFrame = frameAfterNext;
- }
-
- // Draw the next frame immediately. Note that m_desiredFrameStartTime
- // may be in the past, meaning the next time through this function we'll
- // kick off the next advancement sooner than this frame's duration would
- // suggest.
- if (internalAdvanceAnimation(false)) {
- // The image region has been marked dirty, but once we return to our
- // caller, draw() will clear it, and nothing will cause the
- // animation to advance again. We need to start the timer for the
- // next frame running, or the animation can hang. (Compare this
- // with when advanceAnimation() is called, and the region is dirtied
- // while draw() is not in the callstack, meaning draw() gets called
- // to update the region and thus startAnimation() is reached again.)
- // NOTE: For large images with slow or heavily-loaded systems,
- // throwing away data as we go (see destroyDecodedData()) means we
- // can spend so much time re-decoding data above that by the time we
- // reach here we're behind again. If we let startAnimation() run
- // the catch-up code again, we can get long delays without painting
- // as we race the timer, or even infinite recursion. In this
- // situation the best we can do is to simply change frames as fast
- // as possible, so force startAnimation() to set a zero-delay timer
- // and bail out if we're not caught up.
- startAnimation(false);
- }
- }
-}
-
-void BitmapImage::stopAnimation()
-{
- // This timer is used to animate all occurrences of this image. Don't invalidate
- // the timer unless all renderers have stopped drawing.
- delete m_frameTimer;
- m_frameTimer = 0;
-}
-
-void BitmapImage::resetAnimation()
-{
- stopAnimation();
- m_currentFrame = 0;
- m_repetitionsComplete = 0;
- m_desiredFrameStartTime = 0;
- m_animationFinished = false;
-
- // For extremely large animations, when the animation is reset, we just throw everything away.
- destroyDecodedDataIfNecessary();
-}
-
-unsigned BitmapImage::decodedSize() const
-{
- return m_decodedSize;
-}
-
-
-
-void BitmapImage::advanceAnimation(Timer<BitmapImage>*)
-{
- internalAdvanceAnimation(false);
- // At this point the image region has been marked dirty, and if it's
- // onscreen, we'll soon make a call to draw(), which will call
- // startAnimation() again to keep the animation moving.
-}
-
-bool BitmapImage::internalAdvanceAnimation(bool skippingFrames)
-{
- // Stop the animation.
- stopAnimation();
-
- // See if anyone is still paying attention to this animation. If not, we don't
- // advance and will remain suspended at the current frame until the animation is resumed.
- if (!skippingFrames && imageObserver()->shouldPauseAnimation(this))
- return false;
-
- ++m_currentFrame;
- bool advancedAnimation = true;
- if (m_currentFrame >= frameCount()) {
- ++m_repetitionsComplete;
-
- // Get the repetition count again. If we weren't able to get a
- // repetition count before, we should have decoded the whole image by
- // now, so it should now be available.
- // Note that we don't need to special-case cAnimationLoopOnce here
- // because it is 0 (see comments on its declaration in ImageSource.h).
- if (repetitionCount(true) != cAnimationLoopInfinite && m_repetitionsComplete > m_repetitionCount) {
- m_animationFinished = true;
- m_desiredFrameStartTime = 0;
- --m_currentFrame;
- advancedAnimation = false;
- } else
- m_currentFrame = 0;
- }
- destroyDecodedDataIfNecessary();
-
- // We need to draw this frame if we advanced to it while not skipping, or if
- // while trying to skip frames we hit the last frame and thus had to stop.
- if (skippingFrames != advancedAnimation)
- imageObserver()->animationAdvanced(this);
- return advancedAnimation;
-}
-
-void BitmapImage::checkForSolidColor()
-{
- m_isSolidColor = false;
- m_checkedForSolidColor = true;
-
- if (frameCount() > 1)
- return;
-
- RefPtr<NativeImageSkia> frame = frameAtIndex(0);
-
- if (frame && size().width() == 1 && size().height() == 1) {
- SkAutoLockPixels lock(frame->bitmap());
- if (!frame->bitmap().getPixels())
- return;
-
- m_isSolidColor = true;
- m_solidColor = Color(frame->bitmap().getColor(0, 0));
- }
-}
-
-bool BitmapImage::mayFillWithSolidColor()
-{
- if (!m_checkedForSolidColor && frameCount() > 0) {
- checkForSolidColor();
- ASSERT(m_checkedForSolidColor);
- }
- return m_isSolidColor && !m_currentFrame;
-}
-
-Color BitmapImage::solidColor() const
-{
- return m_solidColor;
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/BitmapImage.h b/chromium/third_party/WebKit/Source/core/platform/graphics/BitmapImage.h
deleted file mode 100644
index 6914f233f9a..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/BitmapImage.h
+++ /dev/null
@@ -1,200 +0,0 @@
-/*
- * Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
- * Copyright (C) 2004, 2005, 2006 Apple Computer, Inc. All rights reserved.
- * Copyright (C) 2008-2009 Torch Mobile, Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef BitmapImage_h
-#define BitmapImage_h
-
-#include "core/platform/graphics/Color.h"
-#include "core/platform/graphics/FrameData.h"
-#include "core/platform/graphics/Image.h"
-#include "core/platform/graphics/ImageOrientation.h"
-#include "core/platform/graphics/ImageSource.h"
-#include "core/platform/graphics/IntSize.h"
-#include "wtf/Forward.h"
-
-namespace WebCore {
-
-class NativeImageSkia;
-template <typename T> class Timer;
-
-class BitmapImage : public Image {
- friend class GeneratedImage;
- friend class CrossfadeGeneratedImage;
- friend class GeneratorGeneratedImage;
- friend class GraphicsContext;
-public:
- static PassRefPtr<BitmapImage> create(PassRefPtr<NativeImageSkia> nativeImage, ImageObserver* observer = 0)
- {
- return adoptRef(new BitmapImage(nativeImage, observer));
- }
- static PassRefPtr<BitmapImage> create(ImageObserver* observer = 0)
- {
- return adoptRef(new BitmapImage(observer));
- }
- virtual ~BitmapImage();
-
- virtual bool isBitmapImage() const OVERRIDE;
-
- virtual bool currentFrameHasSingleSecurityOrigin() const OVERRIDE { return true; };
-
- virtual IntSize size() const OVERRIDE;
- IntSize sizeRespectingOrientation() const;
- IntSize currentFrameSize() const;
- virtual bool getHotSpot(IntPoint&) const OVERRIDE;
-
- virtual bool dataChanged(bool allDataReceived) OVERRIDE;
- virtual String filenameExtension() const OVERRIDE;
-
- // It may look unusual that there is no start animation call as public API. This is because
- // we start and stop animating lazily. Animation begins whenever someone draws the image. It will
- // automatically pause once all observers no longer want to render the image anywhere.
- virtual void stopAnimation() OVERRIDE;
- virtual void resetAnimation() OVERRIDE;
-
- virtual unsigned decodedSize() const OVERRIDE;
-
- virtual PassRefPtr<NativeImageSkia> nativeImageForCurrentFrame() OVERRIDE;
- virtual bool currentFrameKnownToBeOpaque() OVERRIDE;
-
- ImageOrientation currentFrameOrientation();
-
-#if !ASSERT_DISABLED
- virtual bool notSolidColor() OVERRIDE;
-#endif
-
-private:
- friend class BitmapImageTest;
-
- void updateSize() const;
-
-protected:
- enum RepetitionCountStatus {
- Unknown, // We haven't checked the source's repetition count.
- Uncertain, // We have a repetition count, but it might be wrong (some GIFs have a count after the image data, and will report "loop once" until all data has been decoded).
- Certain // The repetition count is known to be correct.
- };
-
- BitmapImage(PassRefPtr<NativeImageSkia>, ImageObserver* = 0);
- BitmapImage(ImageObserver* = 0);
-
- virtual void draw(GraphicsContext*, const FloatRect& dstRect, const FloatRect& srcRect, CompositeOperator, BlendMode) OVERRIDE;
- virtual void draw(GraphicsContext*, const FloatRect& dstRect, const FloatRect& srcRect, CompositeOperator, BlendMode, RespectImageOrientationEnum) OVERRIDE;
-
- size_t currentFrame() const { return m_currentFrame; }
- size_t frameCount();
- PassRefPtr<NativeImageSkia> frameAtIndex(size_t);
- bool frameIsCompleteAtIndex(size_t);
- float frameDurationAtIndex(size_t);
- bool frameHasAlphaAtIndex(size_t);
- ImageOrientation frameOrientationAtIndex(size_t);
-
- // Decodes and caches a frame. Never accessed except internally.
- void cacheFrame(size_t index);
- // Called before accessing m_frames[index]. Returns false on index out of bounds.
- bool ensureFrameIsCached(size_t index);
-
- // Called to invalidate cached data. When |destroyAll| is true, we wipe out
- // the entire frame buffer cache and tell the image source to destroy
- // everything; this is used when e.g. we want to free some room in the image
- // cache. If |destroyAll| is false, we delete frames except the current
- // frame; this is used while animating large images to keep memory footprint
- // low; the decoder should preserve the current frame and may preserve some
- // other frames to avoid redecoding the whole image on every frame.
- virtual void destroyDecodedData(bool destroyAll) OVERRIDE;
-
- // If the image is large enough, calls destroyDecodedData().
- void destroyDecodedDataIfNecessary();
-
- // Generally called by destroyDecodedData(), destroys whole-image metadata
- // and notifies observers that the memory footprint has (hopefully)
- // decreased by |frameBytesCleared|.
- void destroyMetadataAndNotify(size_t frameBytesCleared);
-
- // Whether or not size is available yet.
- bool isSizeAvailable();
-
- // Called after asking the source for any information that may require
- // decoding part of the image (e.g., the image size). We need to report
- // the partially decoded data to our observer so it has an accurate
- // account of the BitmapImage's memory usage.
- void didDecodeProperties() const;
-
- // Animation.
- int repetitionCount(bool imageKnownToBeComplete); // |imageKnownToBeComplete| should be set if the caller knows the entire image has been decoded.
- bool shouldAnimate();
- virtual void startAnimation(bool catchUpIfNecessary = true) OVERRIDE;
- void advanceAnimation(Timer<BitmapImage>*);
-
- // Function that does the real work of advancing the animation. When
- // skippingFrames is true, we're in the middle of a loop trying to skip over
- // a bunch of animation frames, so we should not do things like decode each
- // one or notify our observers.
- // Returns whether the animation was advanced.
- bool internalAdvanceAnimation(bool skippingFrames);
-
- // Checks to see if the image is a 1x1 solid color. We optimize these images and just do a fill rect instead.
- // This check should happen regardless whether m_checkedForSolidColor is already set, as the frame may have
- // changed.
- void checkForSolidColor();
-
- virtual bool mayFillWithSolidColor();
- virtual Color solidColor() const;
-
- ImageSource m_source;
- mutable IntSize m_size; // The size to use for the overall image (will just be the size of the first image).
- mutable IntSize m_sizeRespectingOrientation;
-
- size_t m_currentFrame; // The index of the current frame of animation.
- Vector<FrameData, 1> m_frames; // An array of the cached frames of the animation. We have to ref frames to pin them in the cache.
-
- Timer<BitmapImage>* m_frameTimer;
- int m_repetitionCount; // How many total animation loops we should do. This will be cAnimationNone if this image type is incapable of animation.
- RepetitionCountStatus m_repetitionCountStatus;
- int m_repetitionsComplete; // How many repetitions we've finished.
- double m_desiredFrameStartTime; // The system time at which we hope to see the next call to startAnimation().
-
- Color m_solidColor; // If we're a 1x1 solid color, this is the color to use to fill.
-
- unsigned m_decodedSize; // The current size of all decoded frames.
- mutable unsigned m_decodedPropertiesSize; // The size of data decoded by the source to determine image properties (e.g. size, frame count, etc).
- size_t m_frameCount;
-
- bool m_isSolidColor : 1; // Whether or not we are a 1x1 solid image.
- bool m_checkedForSolidColor : 1; // Whether we've checked the frame for solid color.
-
- bool m_animationFinished : 1; // Whether or not we've completed the entire animation.
-
- bool m_allDataReceived : 1; // Whether or not we've received all our data.
- mutable bool m_haveSize : 1; // Whether or not our |m_size| member variable has the final overall image size yet.
- bool m_sizeAvailable : 1; // Whether or not we can obtain the size of the first image frame yet from ImageIO.
- mutable bool m_hasUniformFrameSize : 1;
- mutable bool m_haveFrameCount : 1;
-};
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/BitmapImageTest.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/BitmapImageTest.cpp
deleted file mode 100644
index 0a12c5ee6eb..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/BitmapImageTest.cpp
+++ /dev/null
@@ -1,119 +0,0 @@
-/*
- * Copyright (c) 2013, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/BitmapImage.h"
-
-#include "core/platform/SharedBuffer.h"
-#include "core/platform/graphics/ImageObserver.h"
-#include "public/platform/Platform.h"
-#include "public/platform/WebUnitTestSupport.h"
-
-#include <gtest/gtest.h>
-
-namespace WebCore {
-
-class BitmapImageTest : public ::testing::Test {
-public:
- class FakeImageObserver : public ImageObserver {
- public:
- FakeImageObserver() : m_lastDecodedSizeChangedDelta(0) { }
-
- virtual void decodedSizeChanged(const Image*, int delta)
- {
- m_lastDecodedSizeChangedDelta = delta;
- }
- virtual void didDraw(const Image*) OVERRIDE { }
- virtual bool shouldPauseAnimation(const Image*) OVERRIDE { return false; }
- virtual void animationAdvanced(const Image*) OVERRIDE { }
- virtual void changedInRect(const Image*, const IntRect&) { }
-
- int m_lastDecodedSizeChangedDelta;
- };
-
- static PassRefPtr<SharedBuffer> readFile(const char* fileName)
- {
- String filePath = WebKit::Platform::current()->unitTestSupport()->webKitRootDir();
- filePath.append(fileName);
- return WebKit::Platform::current()->unitTestSupport()->readFromFile(filePath);
- }
-
- // Accessors to BitmapImage's protected methods.
- void destroyDecodedData(bool destroyAll) { m_image->destroyDecodedData(destroyAll); }
- size_t frameCount() { return m_image->frameCount(); }
- void setCurrentFrame(size_t frame) { m_image->m_currentFrame = frame; }
- size_t frameDecodedSize(size_t frame) { return m_image->m_frames[frame].m_frameBytes; }
-
- void loadImage(const char* fileName)
- {
- RefPtr<SharedBuffer> imageData = readFile("/LayoutTests/fast/images/resources/animated-10color.gif");
- ASSERT_TRUE(imageData.get());
-
- m_image->setData(imageData, true);
- EXPECT_EQ(0u, m_image->decodedSize());
-
- size_t frameCount = m_image->frameCount();
- for (size_t i = 0; i < frameCount; ++i)
- m_image->frameAtIndex(i);
- }
-
-protected:
- virtual void SetUp() OVERRIDE
- {
- m_image = BitmapImage::create(&m_imageObserver);
- }
-
- FakeImageObserver m_imageObserver;
- RefPtr<BitmapImage> m_image;
-};
-
-TEST_F(BitmapImageTest, destroyDecodedDataExceptCurrentFrame)
-{
- loadImage("/LayoutTests/fast/images/resources/animated-10color.gif");
- size_t totalSize = m_image->decodedSize();
- size_t frame = frameCount() / 2;
- setCurrentFrame(frame);
- size_t size = frameDecodedSize(frame);
- destroyDecodedData(false);
- EXPECT_LT(m_imageObserver.m_lastDecodedSizeChangedDelta, 0);
- EXPECT_GE(m_imageObserver.m_lastDecodedSizeChangedDelta, -static_cast<int>(totalSize - size));
-}
-
-TEST_F(BitmapImageTest, destroyAllDecodedData)
-{
- loadImage("/LayoutTests/fast/images/resources/animated-10color.gif");
- size_t decodedSize = m_image->decodedSize();
- EXPECT_GT(decodedSize, 0u);
- destroyDecodedData(true);
- EXPECT_EQ(-static_cast<int>(decodedSize), m_imageObserver.m_lastDecodedSizeChangedDelta);
- EXPECT_EQ(0u, m_image->decodedSize());
-}
-
-} // namespace
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/Color.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/Color.cpp
deleted file mode 100644
index c76efef25cb..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/Color.cpp
+++ /dev/null
@@ -1,448 +0,0 @@
-/*
- * Copyright (C) 2003, 2004, 2005, 2006, 2008 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/Color.h"
-
-#include "core/platform/HashTools.h"
-#include "wtf/Assertions.h"
-#include "wtf/DecimalNumber.h"
-#include "wtf/HexNumber.h"
-#include "wtf/MathExtras.h"
-#include "wtf/text/StringBuilder.h"
-
-using namespace std;
-
-namespace WebCore {
-
-#if !COMPILER(MSVC)
-const RGBA32 Color::black;
-const RGBA32 Color::white;
-const RGBA32 Color::darkGray;
-const RGBA32 Color::gray;
-const RGBA32 Color::lightGray;
-const RGBA32 Color::transparent;
-#endif
-
-static const RGBA32 lightenedBlack = 0xFF545454;
-static const RGBA32 darkenedWhite = 0xFFABABAB;
-
-RGBA32 makeRGB(int r, int g, int b)
-{
- return 0xFF000000 | max(0, min(r, 255)) << 16 | max(0, min(g, 255)) << 8 | max(0, min(b, 255));
-}
-
-RGBA32 makeRGBA(int r, int g, int b, int a)
-{
- return max(0, min(a, 255)) << 24 | max(0, min(r, 255)) << 16 | max(0, min(g, 255)) << 8 | max(0, min(b, 255));
-}
-
-static int colorFloatToRGBAByte(float f)
-{
- // We use lroundf and 255 instead of nextafterf(256, 0) to match CG's rounding
- return max(0, min(static_cast<int>(lroundf(255.0f * f)), 255));
-}
-
-RGBA32 makeRGBA32FromFloats(float r, float g, float b, float a)
-{
- return colorFloatToRGBAByte(a) << 24 | colorFloatToRGBAByte(r) << 16 | colorFloatToRGBAByte(g) << 8 | colorFloatToRGBAByte(b);
-}
-
-RGBA32 colorWithOverrideAlpha(RGBA32 color, float overrideAlpha)
-{
- RGBA32 rgbOnly = color & 0x00FFFFFF;
- RGBA32 rgba = rgbOnly | colorFloatToRGBAByte(overrideAlpha) << 24;
- return rgba;
-}
-
-static double calcHue(double temp1, double temp2, double hueVal)
-{
- if (hueVal < 0.0)
- hueVal++;
- else if (hueVal > 1.0)
- hueVal--;
- if (hueVal * 6.0 < 1.0)
- return temp1 + (temp2 - temp1) * hueVal * 6.0;
- if (hueVal * 2.0 < 1.0)
- return temp2;
- if (hueVal * 3.0 < 2.0)
- return temp1 + (temp2 - temp1) * (2.0 / 3.0 - hueVal) * 6.0;
- return temp1;
-}
-
-// Explanation of this algorithm can be found in the CSS3 Color Module
-// specification at http://www.w3.org/TR/css3-color/#hsl-color with further
-// explanation available at http://en.wikipedia.org/wiki/HSL_color_space
-
-// all values are in the range of 0 to 1.0
-RGBA32 makeRGBAFromHSLA(double hue, double saturation, double lightness, double alpha)
-{
- const double scaleFactor = nextafter(256.0, 0.0);
-
- if (!saturation) {
- int greyValue = static_cast<int>(lightness * scaleFactor);
- return makeRGBA(greyValue, greyValue, greyValue, static_cast<int>(alpha * scaleFactor));
- }
-
- double temp2 = lightness < 0.5 ? lightness * (1.0 + saturation) : lightness + saturation - lightness * saturation;
- double temp1 = 2.0 * lightness - temp2;
-
- return makeRGBA(static_cast<int>(calcHue(temp1, temp2, hue + 1.0 / 3.0) * scaleFactor),
- static_cast<int>(calcHue(temp1, temp2, hue) * scaleFactor),
- static_cast<int>(calcHue(temp1, temp2, hue - 1.0 / 3.0) * scaleFactor),
- static_cast<int>(alpha * scaleFactor));
-}
-
-RGBA32 makeRGBAFromCMYKA(float c, float m, float y, float k, float a)
-{
- double colors = 1 - k;
- int r = static_cast<int>(nextafter(256, 0) * (colors * (1 - c)));
- int g = static_cast<int>(nextafter(256, 0) * (colors * (1 - m)));
- int b = static_cast<int>(nextafter(256, 0) * (colors * (1 - y)));
- return makeRGBA(r, g, b, static_cast<float>(nextafter(256, 0) * a));
-}
-
-// originally moved here from the CSS parser
-template <typename CharacterType>
-static inline bool parseHexColorInternal(const CharacterType* name, unsigned length, RGBA32& rgb)
-{
- if (length != 3 && length != 6)
- return false;
- unsigned value = 0;
- for (unsigned i = 0; i < length; ++i) {
- if (!isASCIIHexDigit(name[i]))
- return false;
- value <<= 4;
- value |= toASCIIHexValue(name[i]);
- }
- if (length == 6) {
- rgb = 0xFF000000 | value;
- return true;
- }
- // #abc converts to #aabbcc
- rgb = 0xFF000000
- | (value & 0xF00) << 12 | (value & 0xF00) << 8
- | (value & 0xF0) << 8 | (value & 0xF0) << 4
- | (value & 0xF) << 4 | (value & 0xF);
- return true;
-}
-
-bool Color::parseHexColor(const LChar* name, unsigned length, RGBA32& rgb)
-{
- return parseHexColorInternal(name, length, rgb);
-}
-
-bool Color::parseHexColor(const UChar* name, unsigned length, RGBA32& rgb)
-{
- return parseHexColorInternal(name, length, rgb);
-}
-
-bool Color::parseHexColor(const String& name, RGBA32& rgb)
-{
- unsigned length = name.length();
-
- if (!length)
- return false;
- if (name.is8Bit())
- return parseHexColor(name.characters8(), name.length(), rgb);
- return parseHexColor(name.characters16(), name.length(), rgb);
-}
-
-int differenceSquared(const Color& c1, const Color& c2)
-{
- int dR = c1.red() - c2.red();
- int dG = c1.green() - c2.green();
- int dB = c1.blue() - c2.blue();
- return dR * dR + dG * dG + dB * dB;
-}
-
-Color::Color(const String& name)
-{
- if (name[0] == '#') {
- if (name.is8Bit())
- m_valid = parseHexColor(name.characters8() + 1, name.length() - 1, m_color);
- else
- m_valid = parseHexColor(name.characters16() + 1, name.length() - 1, m_color);
- } else {
- setNamedColor(name);
- }
-}
-
-Color::Color(const char* name)
-{
- if (name[0] == '#') {
- m_valid = parseHexColor(&name[1], m_color);
- } else {
- const NamedColor* foundColor = findColor(name, strlen(name));
- m_color = foundColor ? foundColor->ARGBValue : 0;
- m_valid = foundColor;
- }
-}
-
-String Color::serialized() const
-{
- if (!hasAlpha()) {
- StringBuilder builder;
- builder.reserveCapacity(7);
- builder.append('#');
- appendByteAsHex(red(), builder, Lowercase);
- appendByteAsHex(green(), builder, Lowercase);
- appendByteAsHex(blue(), builder, Lowercase);
- return builder.toString();
- }
-
- StringBuilder result;
- result.reserveCapacity(28);
- const char commaSpace[] = ", ";
- const char rgbaParen[] = "rgba(";
-
- result.append(rgbaParen, 5);
- result.appendNumber(red());
- result.append(commaSpace, 2);
- result.appendNumber(green());
- result.append(commaSpace, 2);
- result.appendNumber(blue());
- result.append(commaSpace, 2);
-
- if (!alpha())
- result.append('0');
- else {
- NumberToLStringBuffer buffer;
- unsigned length = DecimalNumber(alpha() / 255.0).toStringDecimal(buffer, WTF::NumberToStringBufferLength);
- result.append(buffer, length);
- }
-
- result.append(')');
- return result.toString();
-}
-
-String Color::nameForRenderTreeAsText() const
-{
- if (alpha() < 0xFF)
- return String::format("#%02X%02X%02X%02X", red(), green(), blue(), alpha());
- return String::format("#%02X%02X%02X", red(), green(), blue());
-}
-
-static inline const NamedColor* findNamedColor(const String& name)
-{
- char buffer[64]; // easily big enough for the longest color name
- unsigned length = name.length();
- if (length > sizeof(buffer) - 1)
- return 0;
- for (unsigned i = 0; i < length; ++i) {
- UChar c = name[i];
- if (!c || c > 0x7F)
- return 0;
- buffer[i] = toASCIILower(static_cast<char>(c));
- }
- buffer[length] = '\0';
- return findColor(buffer, length);
-}
-
-void Color::setNamedColor(const String& name)
-{
- const NamedColor* foundColor = findNamedColor(name);
- m_color = foundColor ? foundColor->ARGBValue : 0;
- m_valid = foundColor;
-}
-
-Color Color::light() const
-{
- // Hardcode this common case for speed.
- if (m_color == black)
- return lightenedBlack;
-
- const float scaleFactor = nextafterf(256.0f, 0.0f);
-
- float r, g, b, a;
- getRGBA(r, g, b, a);
-
- float v = max(r, max(g, b));
-
- if (v == 0.0f)
- // Lightened black with alpha.
- return Color(0x54, 0x54, 0x54, alpha());
-
- float multiplier = min(1.0f, v + 0.33f) / v;
-
- return Color(static_cast<int>(multiplier * r * scaleFactor),
- static_cast<int>(multiplier * g * scaleFactor),
- static_cast<int>(multiplier * b * scaleFactor),
- alpha());
-}
-
-Color Color::dark() const
-{
- // Hardcode this common case for speed.
- if (m_color == white)
- return darkenedWhite;
-
- const float scaleFactor = nextafterf(256.0f, 0.0f);
-
- float r, g, b, a;
- getRGBA(r, g, b, a);
-
- float v = max(r, max(g, b));
- float multiplier = max(0.0f, (v - 0.33f) / v);
-
- return Color(static_cast<int>(multiplier * r * scaleFactor),
- static_cast<int>(multiplier * g * scaleFactor),
- static_cast<int>(multiplier * b * scaleFactor),
- alpha());
-}
-
-static int blendComponent(int c, int a)
-{
- // We use white.
- float alpha = a / 255.0f;
- int whiteBlend = 255 - a;
- c -= whiteBlend;
- return static_cast<int>(c / alpha);
-}
-
-const int cStartAlpha = 153; // 60%
-const int cEndAlpha = 204; // 80%;
-const int cAlphaIncrement = 17; // Increments in between.
-
-Color Color::blend(const Color& source) const
-{
- if (!alpha() || !source.hasAlpha())
- return source;
-
- if (!source.alpha())
- return *this;
-
- int d = 255 * (alpha() + source.alpha()) - alpha() * source.alpha();
- int a = d / 255;
- int r = (red() * alpha() * (255 - source.alpha()) + 255 * source.alpha() * source.red()) / d;
- int g = (green() * alpha() * (255 - source.alpha()) + 255 * source.alpha() * source.green()) / d;
- int b = (blue() * alpha() * (255 - source.alpha()) + 255 * source.alpha() * source.blue()) / d;
- return Color(r, g, b, a);
-}
-
-Color Color::blendWithWhite() const
-{
- // If the color contains alpha already, we leave it alone.
- if (hasAlpha())
- return *this;
-
- Color newColor;
- for (int alpha = cStartAlpha; alpha <= cEndAlpha; alpha += cAlphaIncrement) {
- // We have a solid color. Convert to an equivalent color that looks the same when blended with white
- // at the current alpha. Try using less transparency if the numbers end up being negative.
- int r = blendComponent(red(), alpha);
- int g = blendComponent(green(), alpha);
- int b = blendComponent(blue(), alpha);
-
- newColor = Color(r, g, b, alpha);
-
- if (r >= 0 && g >= 0 && b >= 0)
- break;
- }
- return newColor;
-}
-
-void Color::getRGBA(float& r, float& g, float& b, float& a) const
-{
- r = red() / 255.0f;
- g = green() / 255.0f;
- b = blue() / 255.0f;
- a = alpha() / 255.0f;
-}
-
-void Color::getRGBA(double& r, double& g, double& b, double& a) const
-{
- r = red() / 255.0;
- g = green() / 255.0;
- b = blue() / 255.0;
- a = alpha() / 255.0;
-}
-
-void Color::getHSL(double& hue, double& saturation, double& lightness) const
-{
- // http://en.wikipedia.org/wiki/HSL_color_space. This is a direct copy of
- // the algorithm therein, although it's 360^o based and we end up wanting
- // [0...1) based. It's clearer if we stick to 360^o until the end.
- double r = static_cast<double>(red()) / 255.0;
- double g = static_cast<double>(green()) / 255.0;
- double b = static_cast<double>(blue()) / 255.0;
- double max = std::max(std::max(r, g), b);
- double min = std::min(std::min(r, g), b);
-
- if (max == min)
- hue = 0.0;
- else if (max == r)
- hue = (60.0 * ((g - b) / (max - min))) + 360.0;
- else if (max == g)
- hue = (60.0 * ((b - r) / (max - min))) + 120.0;
- else
- hue = (60.0 * ((r - g) / (max - min))) + 240.0;
-
- if (hue >= 360.0)
- hue -= 360.0;
-
- // makeRGBAFromHSLA assumes that hue is in [0...1).
- hue /= 360.0;
-
- lightness = 0.5 * (max + min);
- if (max == min)
- saturation = 0.0;
- else if (lightness <= 0.5)
- saturation = ((max - min) / (max + min));
- else
- saturation = ((max - min) / (2.0 - (max + min)));
-}
-
-Color colorFromPremultipliedARGB(RGBA32 pixelColor)
-{
- int alpha = alphaChannel(pixelColor);
- if (alpha && alpha < 255) {
- return Color::createUnchecked(
- redChannel(pixelColor) * 255 / alpha,
- greenChannel(pixelColor) * 255 / alpha,
- blueChannel(pixelColor) * 255 / alpha,
- alpha);
- } else
- return Color(pixelColor);
-}
-
-RGBA32 premultipliedARGBFromColor(const Color& color)
-{
- unsigned pixelColor;
-
- unsigned alpha = color.alpha();
- if (alpha < 255) {
- pixelColor = Color::createUnchecked(
- (color.red() * alpha + 254) / 255,
- (color.green() * alpha + 254) / 255,
- (color.blue() * alpha + 254) / 255,
- alpha).rgb();
- } else
- pixelColor = color.rgb();
-
- return pixelColor;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/Color.h b/chromium/third_party/WebKit/Source/core/platform/graphics/Color.h
deleted file mode 100644
index 012d6416466..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/Color.h
+++ /dev/null
@@ -1,169 +0,0 @@
-/*
- * Copyright (C) 2003, 2004, 2005, 2006, 2010 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef Color_h
-#define Color_h
-
-#include "core/platform/animation/AnimationUtilities.h"
-#include "wtf/FastAllocBase.h"
-#include "wtf/Forward.h"
-#include "wtf/unicode/Unicode.h"
-
-namespace WebCore {
-
-class Color;
-
-typedef unsigned RGBA32; // RGBA quadruplet
-
-RGBA32 makeRGB(int r, int g, int b);
-RGBA32 makeRGBA(int r, int g, int b, int a);
-
-RGBA32 colorWithOverrideAlpha(RGBA32 color, float overrideAlpha);
-RGBA32 makeRGBA32FromFloats(float r, float g, float b, float a);
-RGBA32 makeRGBAFromHSLA(double h, double s, double l, double a);
-RGBA32 makeRGBAFromCMYKA(float c, float m, float y, float k, float a);
-
-int differenceSquared(const Color&, const Color&);
-
-inline int redChannel(RGBA32 color) { return (color >> 16) & 0xFF; }
-inline int greenChannel(RGBA32 color) { return (color >> 8) & 0xFF; }
-inline int blueChannel(RGBA32 color) { return color & 0xFF; }
-inline int alphaChannel(RGBA32 color) { return (color >> 24) & 0xFF; }
-
-class Color {
- WTF_MAKE_FAST_ALLOCATED;
-public:
- Color() : m_color(0), m_valid(false) { }
- Color(RGBA32 color, bool valid = true) : m_color(color), m_valid(valid) { ASSERT(!m_color || m_valid); }
- Color(int r, int g, int b) : m_color(makeRGB(r, g, b)), m_valid(true) { }
- Color(int r, int g, int b, int a) : m_color(makeRGBA(r, g, b, a)), m_valid(true) { }
- // Color is currently limited to 32bit RGBA, perhaps some day we'll support better colors
- Color(float r, float g, float b, float a) : m_color(makeRGBA32FromFloats(r, g, b, a)), m_valid(true) { }
- // Creates a new color from the specific CMYK and alpha values.
- Color(float c, float m, float y, float k, float a) : m_color(makeRGBAFromCMYKA(c, m, y, k, a)), m_valid(true) { }
- explicit Color(const String&);
- explicit Color(const char*);
-
- static Color createUnchecked(int r, int g, int b)
- {
- RGBA32 color = 0xFF000000 | r << 16 | g << 8 | b;
- return Color(color);
- }
- static Color createUnchecked(int r, int g, int b, int a)
- {
- RGBA32 color = a << 24 | r << 16 | g << 8 | b;
- return Color(color);
- }
-
- // Returns the color serialized according to HTML5
- // - http://www.whatwg.org/specs/web-apps/current-work/#serialization-of-a-color
- String serialized() const;
-
- // Returns the color serialized as either #RRGGBB or #RRGGBBAA
- // The latter format is not a valid CSS color, and should only be seen in DRT dumps.
- String nameForRenderTreeAsText() const;
-
- void setNamedColor(const String&);
-
- bool isValid() const { return m_valid; }
-
- bool hasAlpha() const { return alpha() < 255; }
-
- int red() const { return redChannel(m_color); }
- int green() const { return greenChannel(m_color); }
- int blue() const { return blueChannel(m_color); }
- int alpha() const { return alphaChannel(m_color); }
-
- RGBA32 rgb() const { return m_color; } // Preserve the alpha.
- void setRGB(int r, int g, int b) { m_color = makeRGB(r, g, b); m_valid = true; }
- void setRGB(RGBA32 rgb) { m_color = rgb; m_valid = true; }
- void getRGBA(float& r, float& g, float& b, float& a) const;
- void getRGBA(double& r, double& g, double& b, double& a) const;
- void getHSL(double& h, double& s, double& l) const;
-
- Color light() const;
- Color dark() const;
-
- // This is an implementation of Porter-Duff's "source-over" equation
- Color blend(const Color&) const;
- Color blendWithWhite() const;
-
- static bool parseHexColor(const String&, RGBA32&);
- static bool parseHexColor(const LChar*, unsigned, RGBA32&);
- static bool parseHexColor(const UChar*, unsigned, RGBA32&);
-
- static const RGBA32 black = 0xFF000000;
- static const RGBA32 white = 0xFFFFFFFF;
- static const RGBA32 darkGray = 0xFF808080;
- static const RGBA32 gray = 0xFFA0A0A0;
- static const RGBA32 lightGray = 0xFFC0C0C0;
- static const RGBA32 transparent = 0x00000000;
-
-private:
- RGBA32 m_color;
- bool m_valid;
-};
-
-inline bool operator==(const Color& a, const Color& b)
-{
- return a.rgb() == b.rgb() && a.isValid() == b.isValid();
-}
-
-inline bool operator!=(const Color& a, const Color& b)
-{
- return !(a == b);
-}
-
-Color colorFromPremultipliedARGB(RGBA32);
-RGBA32 premultipliedARGBFromColor(const Color&);
-
-inline Color blend(const Color& from, const Color& to, double progress, bool blendPremultiplied = true)
-{
- // We need to preserve the state of the valid flag at the end of the animation
- if (progress == 1 && !to.isValid())
- return Color();
-
- if (blendPremultiplied) {
- // Contrary to the name, RGBA32 actually stores ARGB, so we can initialize Color directly from premultipliedARGBFromColor().
- // Also, premultipliedARGBFromColor() bails on zero alpha, so special-case that.
- Color premultFrom = from.alpha() ? premultipliedARGBFromColor(from) : 0;
- Color premultTo = to.alpha() ? premultipliedARGBFromColor(to) : 0;
-
- Color premultBlended(blend(premultFrom.red(), premultTo.red(), progress),
- blend(premultFrom.green(), premultTo.green(), progress),
- blend(premultFrom.blue(), premultTo.blue(), progress),
- blend(premultFrom.alpha(), premultTo.alpha(), progress));
-
- return Color(colorFromPremultipliedARGB(premultBlended.rgb()));
- }
-
- return Color(blend(from.red(), to.red(), progress),
- blend(from.green(), to.green(), progress),
- blend(from.blue(), to.blue(), progress),
- blend(from.alpha(), to.alpha(), progress));
-}
-} // namespace WebCore
-
-#endif // Color_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/ColorSpace.h b/chromium/third_party/WebKit/Source/core/platform/graphics/ColorSpace.h
deleted file mode 100644
index 989d0fb0f58..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/ColorSpace.h
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright (C) 2009 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ColorSpace_h
-#define ColorSpace_h
-
-namespace WebCore {
-
-enum ColorSpace {
- ColorSpaceDeviceRGB,
- ColorSpaceSRGB,
- ColorSpaceLinearRGB
-};
-
-} // namespace WebCore
-
-#endif // ColorSpace_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/ContentDecryptionModule.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/ContentDecryptionModule.cpp
deleted file mode 100644
index e83486d6556..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/ContentDecryptionModule.cpp
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/ContentDecryptionModule.h"
-
-#include "core/platform/NotImplemented.h"
-#include "core/platform/graphics/ContentDecryptionModuleSession.h"
-#include "public/platform/Platform.h"
-
-namespace WebCore {
-
-bool ContentDecryptionModule::supportsKeySystem(const String& keySystem)
-{
- // FIXME: Chromium should handle this, possibly using
- // MIMETypeRegistry::isSupportedEncryptedMediaMIMEType().
- notImplemented();
- return keySystem == "org.w3.clearkey";
-}
-
-PassOwnPtr<ContentDecryptionModule> ContentDecryptionModule::create(const String& keySystem)
-{
- ASSERT(!keySystem.isEmpty());
- OwnPtr<WebKit::WebContentDecryptionModule> cdm = adoptPtr(WebKit::Platform::current()->createContentDecryptionModule(keySystem));
- if (!cdm)
- return nullptr;
- return adoptPtr(new ContentDecryptionModule(cdm.release()));
-}
-
-ContentDecryptionModule::ContentDecryptionModule(PassOwnPtr<WebKit::WebContentDecryptionModule> cdm)
- : m_cdm(cdm)
-{
- ASSERT(m_cdm);
-}
-
-ContentDecryptionModule::~ContentDecryptionModule()
-{
-}
-
-bool ContentDecryptionModule::supportsMIMEType(const String& mimeType)
-{
- // FIXME: Chromium should handle this, possibly using
- // MIMETypeRegistry::isSupportedEncryptedMediaMIMEType().
- notImplemented();
- return mimeType == "video/webm";
-}
-
-PassOwnPtr<ContentDecryptionModuleSession> ContentDecryptionModule::createSession(ContentDecryptionModuleSessionClient* client)
-{
- return adoptPtr(new ContentDecryptionModuleSession(m_cdm.get(), client));
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/ContentDecryptionModule.h b/chromium/third_party/WebKit/Source/core/platform/graphics/ContentDecryptionModule.h
deleted file mode 100644
index 3fe04049cfa..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/ContentDecryptionModule.h
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ContentDecryptionModule_h
-#define ContentDecryptionModule_h
-
-#include "public/platform/WebContentDecryptionModule.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class ContentDecryptionModuleSession;
-class ContentDecryptionModuleSessionClient;
-
-class ContentDecryptionModule {
-public:
- static bool supportsKeySystem(const String&);
- static PassOwnPtr<ContentDecryptionModule> create(const String& keySystem);
-
- ContentDecryptionModule(PassOwnPtr<WebKit::WebContentDecryptionModule>);
- ~ContentDecryptionModule();
-
- // ContentDecryptionModule
- bool supportsMIMEType(const String&);
- PassOwnPtr<ContentDecryptionModuleSession> createSession(ContentDecryptionModuleSessionClient*);
-
-private:
- OwnPtr<WebKit::WebContentDecryptionModule> m_cdm;
-};
-
-} // namespace WebCore
-
-#endif // ContentDecryptionModule_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/ContentDecryptionModuleSession.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/ContentDecryptionModuleSession.cpp
deleted file mode 100644
index 60d3ac12f81..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/ContentDecryptionModuleSession.cpp
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/ContentDecryptionModuleSession.h"
-
-#include "core/platform/NotImplemented.h"
-#include "public/platform/Platform.h"
-#include "public/platform/WebContentDecryptionModule.h"
-#include "public/platform/WebURL.h"
-#include "weborigin/KURL.h"
-#include "wtf/Uint8Array.h"
-
-namespace WebCore {
-
-ContentDecryptionModuleSession::ContentDecryptionModuleSession(WebKit::WebContentDecryptionModule* contentDecryptionModule, ContentDecryptionModuleSessionClient* client)
- : m_client(client)
-{
- m_session = adoptPtr(contentDecryptionModule->createSession(this));
- ASSERT(m_session);
-}
-
-ContentDecryptionModuleSession::~ContentDecryptionModuleSession()
-{
-}
-
-String ContentDecryptionModuleSession::sessionId() const
-{
- return m_session->sessionId();
-}
-
-void ContentDecryptionModuleSession::generateKeyRequest(const String& mimeType, const Uint8Array& initData)
-{
- m_session->generateKeyRequest(mimeType, initData.data(), initData.length());
-}
-
-void ContentDecryptionModuleSession::update(const Uint8Array& key)
-{
- m_session->update(key.data(), key.length());
-}
-
-void ContentDecryptionModuleSession::close()
-{
- m_session->close();
-}
-
-void ContentDecryptionModuleSession::keyAdded()
-{
- m_client->keyAdded();
-}
-
-void ContentDecryptionModuleSession::keyError(MediaKeyErrorCode errorCode, unsigned long systemCode)
-{
- m_client->keyError(static_cast<ContentDecryptionModuleSessionClient::MediaKeyErrorCode>(errorCode), systemCode);
-}
-
-void ContentDecryptionModuleSession::keyMessage(const unsigned char* message, size_t messageLength, const WebKit::WebURL& destinationURL)
-{
- m_client->keyMessage(message, messageLength, destinationURL);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/ContentDecryptionModuleSession.h b/chromium/third_party/WebKit/Source/core/platform/graphics/ContentDecryptionModuleSession.h
deleted file mode 100644
index 30ead6fe8ba..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/ContentDecryptionModuleSession.h
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ContentDecryptionModuleSession_h
-#define ContentDecryptionModuleSession_h
-
-#include "public/platform/WebContentDecryptionModuleSession.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebKit {
-class WebContentDecryptionModule;
-}
-
-namespace WTF {
-class Uint8Array;
-}
-
-namespace WebCore {
-
-class KURL;
-
-class ContentDecryptionModuleSessionClient {
-public:
- enum MediaKeyErrorCode { UnknownError = 1, ClientError };
- virtual void keyAdded() = 0;
- virtual void keyError(MediaKeyErrorCode, unsigned long systemCode) = 0;
- virtual void keyMessage(const unsigned char* message, size_t messageLength, const KURL& destinationURL) = 0;
-};
-
-class ContentDecryptionModuleSession : private WebKit::WebContentDecryptionModuleSession::Client {
-public:
- static PassOwnPtr<ContentDecryptionModuleSession> create(ContentDecryptionModuleSessionClient*);
-
- ContentDecryptionModuleSession(WebKit::WebContentDecryptionModule*, ContentDecryptionModuleSessionClient*);
- ~ContentDecryptionModuleSession();
-
- String sessionId() const;
- void generateKeyRequest(const String& mimeType, const WTF::Uint8Array& initData);
- void update(const WTF::Uint8Array& key);
- void close();
-
-private:
- // WebKit::WebContentDecryptionModuleSession::Client
- virtual void keyAdded() OVERRIDE;
- virtual void keyError(MediaKeyErrorCode, unsigned long systemCode) OVERRIDE;
- virtual void keyMessage(const unsigned char* message, size_t messageLength, const WebKit::WebURL& destinationURL) OVERRIDE;
-
- OwnPtr<WebKit::WebContentDecryptionModuleSession> m_session;
-
- ContentDecryptionModuleSessionClient* m_client;
-};
-
-} // namespace WebCore
-
-#endif // ContentDecryptionModuleSession_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/CrossfadeGeneratedImage.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/CrossfadeGeneratedImage.cpp
deleted file mode 100644
index 46ff30e1709..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/CrossfadeGeneratedImage.cpp
+++ /dev/null
@@ -1,110 +0,0 @@
-/*
- * Copyright (C) 2011 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/CrossfadeGeneratedImage.h"
-
-#include "core/platform/graphics/FloatRect.h"
-#include "core/platform/graphics/GraphicsContextStateSaver.h"
-#include "core/platform/graphics/ImageBuffer.h"
-
-using namespace std;
-
-namespace WebCore {
-
-CrossfadeGeneratedImage::CrossfadeGeneratedImage(Image* fromImage, Image* toImage, float percentage, IntSize crossfadeSize, const IntSize& size)
- : m_fromImage(fromImage)
- , m_toImage(toImage)
- , m_percentage(percentage)
- , m_crossfadeSize(crossfadeSize)
-{
- m_size = size;
-}
-
-void CrossfadeGeneratedImage::drawCrossfade(GraphicsContext* context)
-{
- float inversePercentage = 1 - m_percentage;
-
- IntSize fromImageSize = m_fromImage->size();
- IntSize toImageSize = m_toImage->size();
-
- // Draw nothing if either of the images hasn't loaded yet.
- if (m_fromImage == Image::nullImage() || m_toImage == Image::nullImage())
- return;
-
- GraphicsContextStateSaver stateSaver(*context);
-
- context->clip(IntRect(IntPoint(), m_crossfadeSize));
- context->beginTransparencyLayer(1);
-
- // Draw the image we're fading away from.
- context->save();
- if (m_crossfadeSize != fromImageSize)
- context->scale(FloatSize(static_cast<float>(m_crossfadeSize.width()) / fromImageSize.width(),
- static_cast<float>(m_crossfadeSize.height()) / fromImageSize.height()));
- context->setAlpha(inversePercentage);
- context->drawImage(m_fromImage, IntPoint());
- context->restore();
-
- // Draw the image we're fading towards.
- context->save();
- if (m_crossfadeSize != toImageSize)
- context->scale(FloatSize(static_cast<float>(m_crossfadeSize.width()) / toImageSize.width(),
- static_cast<float>(m_crossfadeSize.height()) / toImageSize.height()));
- context->setAlpha(m_percentage);
- context->drawImage(m_toImage, IntPoint(), CompositePlusLighter);
- context->restore();
-
- context->endLayer();
-}
-
-void CrossfadeGeneratedImage::draw(GraphicsContext* context, const FloatRect& dstRect, const FloatRect& srcRect, CompositeOperator compositeOp, BlendMode blendMode)
-{
- GraphicsContextStateSaver stateSaver(*context);
- context->setCompositeOperation(compositeOp, blendMode);
- context->clip(dstRect);
- context->translate(dstRect.x(), dstRect.y());
- if (dstRect.size() != srcRect.size())
- context->scale(FloatSize(dstRect.width() / srcRect.width(), dstRect.height() / srcRect.height()));
- context->translate(-srcRect.x(), -srcRect.y());
-
- drawCrossfade(context);
-}
-
-void CrossfadeGeneratedImage::drawPattern(GraphicsContext* context, const FloatRect& srcRect, const FloatSize& scale, const FloatPoint& phase, CompositeOperator compositeOp, const FloatRect& dstRect, BlendMode blendMode)
-{
- OwnPtr<ImageBuffer> imageBuffer = ImageBuffer::create(m_size, 1, context->isAccelerated() ? Accelerated : Unaccelerated);
- if (!imageBuffer)
- return;
-
- // Fill with the cross-faded image.
- GraphicsContext* graphicsContext = imageBuffer->context();
- drawCrossfade(graphicsContext);
-
- // Tile the image buffer into the context.
- imageBuffer->drawPattern(context, srcRect, scale, phase, compositeOp, dstRect, blendMode);
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/CrossfadeGeneratedImage.h b/chromium/third_party/WebKit/Source/core/platform/graphics/CrossfadeGeneratedImage.h
deleted file mode 100644
index 4090d7a7ad2..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/CrossfadeGeneratedImage.h
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * Copyright (C) 2011 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef CrossfadeGeneratedImage_h
-#define CrossfadeGeneratedImage_h
-
-#include "core/platform/graphics/GeneratedImage.h"
-#include "core/platform/graphics/Image.h"
-#include "core/platform/graphics/ImageObserver.h"
-#include "core/platform/graphics/IntSize.h"
-#include "wtf/RefPtr.h"
-
-namespace WebCore {
-
-class CSSCrossfadeValue;
-
-class CrossfadeGeneratedImage : public GeneratedImage {
-public:
- static PassRefPtr<CrossfadeGeneratedImage> create(Image* fromImage, Image* toImage, float percentage, IntSize crossfadeSize, const IntSize& size)
- {
- return adoptRef(new CrossfadeGeneratedImage(fromImage, toImage, percentage, crossfadeSize, size));
- }
-
- virtual void setContainerSize(const IntSize&) { }
- virtual bool usesContainerSize() const { return false; }
- virtual bool hasRelativeWidth() const { return false; }
- virtual bool hasRelativeHeight() const { return false; }
-
- virtual IntSize size() const { return m_crossfadeSize; }
-
-protected:
- virtual void draw(GraphicsContext*, const FloatRect&, const FloatRect&,
- CompositeOperator, BlendMode) OVERRIDE;
- virtual void drawPattern(GraphicsContext*, const FloatRect&,
- const FloatSize&, const FloatPoint&, CompositeOperator,
- const FloatRect&, BlendMode) OVERRIDE;
-
- CrossfadeGeneratedImage(Image* fromImage, Image* toImage, float percentage, IntSize crossfadeSize, const IntSize&);
-
-private:
- void drawCrossfade(GraphicsContext*);
-
- Image* m_fromImage;
- Image* m_toImage;
-
- float m_percentage;
- IntSize m_crossfadeSize;
-};
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/DashArray.h b/chromium/third_party/WebKit/Source/core/platform/graphics/DashArray.h
deleted file mode 100644
index 1134eb444c5..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/DashArray.h
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright (C) 2008 Dirk Schulze <vbs85@gmx.de>
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef DashArray_h
-#define DashArray_h
-
-#include "wtf/Vector.h"
-
-typedef float DashArrayElement;
-
-typedef Vector<DashArrayElement> DashArray;
-
-#endif // DashArray_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/DrawLooper.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/DrawLooper.cpp
deleted file mode 100644
index 461db1c0269..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/DrawLooper.cpp
+++ /dev/null
@@ -1,108 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/DrawLooper.h"
-
-#include "core/platform/graphics/Color.h"
-#include "core/platform/graphics/FloatSize.h"
-#include "third_party/skia/include/core/SkColor.h"
-#include "third_party/skia/include/core/SkColorFilter.h"
-#include "third_party/skia/include/core/SkDrawLooper.h"
-#include "third_party/skia/include/core/SkPaint.h"
-#include "third_party/skia/include/core/SkXfermode.h"
-#include "third_party/skia/include/effects/SkBlurMaskFilter.h"
-#include "third_party/skia/include/effects/SkLayerDrawLooper.h"
-
-namespace WebCore {
-
-DrawLooper::DrawLooper() : m_skDrawLooper(adoptRef(new SkLayerDrawLooper)) { }
-
-DrawLooper::~DrawLooper() { }
-
-SkDrawLooper* DrawLooper::skDrawLooper() const
-{
- return m_skDrawLooper.get();
-}
-
-void DrawLooper::addUnmodifiedContent()
-{
- SkLayerDrawLooper::LayerInfo info;
- m_skDrawLooper->addLayerOnTop(info);
-}
-
-void DrawLooper::addShadow(const FloatSize& offset, float blur, const Color& color,
- ShadowTransformMode shadowTransformMode, ShadowAlphaMode shadowAlphaMode)
-{
- // Detect when there's no effective shadow.
- if (!color.isValid() || !color.alpha())
- return;
-
- SkColor skColor;
- if (color.isValid())
- skColor = color.rgb();
- else
- skColor = SkColorSetARGB(0xFF / 3, 0, 0, 0); // "std" apple shadow color.
-
- SkLayerDrawLooper::LayerInfo info;
-
- switch (shadowAlphaMode) {
- case ShadowRespectsAlpha:
- info.fColorMode = SkXfermode::kDst_Mode;
- break;
- case ShadowIgnoresAlpha:
- info.fColorMode = SkXfermode::kSrc_Mode;
- break;
- default:
- ASSERT_NOT_REACHED();
- }
-
- if (blur)
- info.fPaintBits |= SkLayerDrawLooper::kMaskFilter_Bit; // our blur
- info.fPaintBits |= SkLayerDrawLooper::kColorFilter_Bit;
- info.fOffset.set(offset.width(), offset.height());
- info.fPostTranslate = (shadowTransformMode == ShadowIgnoresTransforms);
-
- SkPaint* paint = m_skDrawLooper->addLayerOnTop(info);
-
- if (blur) {
- uint32_t mfFlags = SkBlurMaskFilter::kHighQuality_BlurFlag;
- if (shadowTransformMode == ShadowIgnoresTransforms)
- mfFlags |= SkBlurMaskFilter::kIgnoreTransform_BlurFlag;
- RefPtr<SkMaskFilter> mf = adoptRef(SkBlurMaskFilter::Create(
- (double)blur / 2.0, SkBlurMaskFilter::kNormal_BlurStyle, mfFlags));
- paint->setMaskFilter(mf.get());
- }
-
- RefPtr<SkColorFilter> cf = adoptRef(SkColorFilter::CreateModeFilter(skColor, SkXfermode::kSrcIn_Mode));
- paint->setColorFilter(cf.get());
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/DrawLooper.h b/chromium/third_party/WebKit/Source/core/platform/graphics/DrawLooper.h
deleted file mode 100644
index 97a3b0d4f7b..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/DrawLooper.h
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef DrawLooper_h
-#define DrawLooper_h
-
-#include "wtf/Noncopyable.h"
-#include "wtf/RefPtr.h"
-
-class SkDrawLooper;
-class SkLayerDrawLooper;
-
-namespace WebCore {
-
-class Color;
-class FloatSize;
-
-class DrawLooper {
- // Implementing the copy constructor properly would require writing code to
- // copy the underlying SkDrawLooper.
- WTF_MAKE_NONCOPYABLE(DrawLooper);
-
-public:
- enum ShadowTransformMode {
- ShadowRespectsTransforms,
- ShadowIgnoresTransforms
- };
- enum ShadowAlphaMode {
- ShadowRespectsAlpha,
- ShadowIgnoresAlpha
- };
-
- DrawLooper();
- ~DrawLooper();
-
- // Callees should not modify this looper other than to iterate over it.
- // A downcast to SkLayerDrawLooper* is tantamount to a const_cast.
- SkDrawLooper* skDrawLooper() const;
-
- void addUnmodifiedContent();
- void addShadow(const FloatSize& offset, float blur, const Color&,
- ShadowTransformMode = ShadowRespectsTransforms,
- ShadowAlphaMode = ShadowRespectsAlpha);
-
-private:
- RefPtr<SkLayerDrawLooper> m_skDrawLooper;
-};
-
-} // namespace WebCore
-
-#endif // DrawLooper_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/Extensions3D.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/Extensions3D.cpp
deleted file mode 100644
index 22833b3fd6a..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/Extensions3D.cpp
+++ /dev/null
@@ -1,238 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/platform/graphics/Extensions3D.h"
-
-#include "core/platform/NotImplemented.h"
-#include "core/platform/graphics/GraphicsContext3D.h"
-#include "public/platform/WebGraphicsContext3D.h"
-#include "wtf/text/CString.h"
-
-namespace WebCore {
-
-Extensions3D::Extensions3D(GraphicsContext3D* context)
- : m_context(context)
-{
-}
-
-Extensions3D::~Extensions3D()
-{
-}
-
-bool Extensions3D::supports(const String& name)
-{
- return m_context->supportsExtension(name);
-}
-
-void Extensions3D::ensureEnabled(const String& name)
-{
- bool result = m_context->ensureExtensionEnabled(name);
- ASSERT_UNUSED(result, result);
-}
-
-bool Extensions3D::isEnabled(const String& name)
-{
- return m_context->isExtensionEnabled(name);
-}
-
-int Extensions3D::getGraphicsResetStatusARB()
-{
- return static_cast<int>(m_context->webContext()->getGraphicsResetStatusARB());
-}
-
-void Extensions3D::blitFramebuffer(long srcX0, long srcY0, long srcX1, long srcY1, long dstX0, long dstY0, long dstX1, long dstY1, unsigned long mask, unsigned long filter)
-{
- m_context->webContext()->blitFramebufferCHROMIUM(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter);
-}
-
-void Extensions3D::renderbufferStorageMultisample(unsigned long target, unsigned long samples, unsigned long internalformat, unsigned long width, unsigned long height)
-{
- m_context->webContext()->renderbufferStorageMultisampleCHROMIUM(target, samples, internalformat, width, height);
-}
-
-void* Extensions3D::mapBufferSubDataCHROMIUM(unsigned target, int offset, int size, unsigned access)
-{
- return m_context->webContext()->mapBufferSubDataCHROMIUM(target, offset, size, access);
-}
-
-void Extensions3D::unmapBufferSubDataCHROMIUM(const void* data)
-{
- m_context->webContext()->unmapBufferSubDataCHROMIUM(data);
-}
-
-void* Extensions3D::mapTexSubImage2DCHROMIUM(unsigned target, int level, int xoffset, int yoffset, int width, int height, unsigned format, unsigned type, unsigned access)
-{
- return m_context->webContext()->mapTexSubImage2DCHROMIUM(target, level, xoffset, yoffset, width, height, format, type, access);
-}
-
-void Extensions3D::unmapTexSubImage2DCHROMIUM(const void* data)
-{
- m_context->webContext()->unmapTexSubImage2DCHROMIUM(data);
-}
-
-Platform3DObject Extensions3D::createVertexArrayOES()
-{
- return m_context->webContext()->createVertexArrayOES();
-}
-
-void Extensions3D::deleteVertexArrayOES(Platform3DObject array)
-{
- m_context->webContext()->deleteVertexArrayOES(array);
-}
-
-GC3Dboolean Extensions3D::isVertexArrayOES(Platform3DObject array)
-{
- return m_context->webContext()->isVertexArrayOES(array);
-}
-
-void Extensions3D::bindVertexArrayOES(Platform3DObject array)
-{
- m_context->webContext()->bindVertexArrayOES(array);
-}
-
-String Extensions3D::getTranslatedShaderSourceANGLE(Platform3DObject shader)
-{
- return m_context->webContext()->getTranslatedShaderSourceANGLE(shader);
-}
-
-void Extensions3D::rateLimitOffscreenContextCHROMIUM()
-{
- m_context->webContext()->rateLimitOffscreenContextCHROMIUM();
-}
-
-void Extensions3D::paintFramebufferToCanvas(int framebuffer, int width, int height, bool premultiplyAlpha, ImageBuffer* imageBuffer)
-{
- m_context->paintFramebufferToCanvas(framebuffer, width, height, premultiplyAlpha, imageBuffer);
-}
-
-void Extensions3D::texImageIOSurface2DCHROMIUM(unsigned target, int width, int height, uint32_t ioSurfaceId, unsigned plane)
-{
- m_context->webContext()->texImageIOSurface2DCHROMIUM(target, width, height, ioSurfaceId, plane);
-}
-
-void Extensions3D::texStorage2DEXT(unsigned int target, int levels, unsigned int internalFormat, int width, int height)
-{
- m_context->webContext()->texStorage2DEXT(target, levels, internalFormat, width, height);
-}
-
-Platform3DObject Extensions3D::createQueryEXT()
-{
- return m_context->webContext()->createQueryEXT();
-}
-
-void Extensions3D::deleteQueryEXT(Platform3DObject query)
-{
- m_context->webContext()->deleteQueryEXT(query);
-}
-
-GC3Dboolean Extensions3D::isQueryEXT(Platform3DObject query)
-{
- return m_context->webContext()->isQueryEXT(query);
-}
-
-void Extensions3D::beginQueryEXT(GC3Denum target, Platform3DObject query)
-{
- m_context->webContext()->beginQueryEXT(target, query);
-}
-
-void Extensions3D::endQueryEXT(GC3Denum target)
-{
- m_context->webContext()->endQueryEXT(target);
-}
-
-void Extensions3D::getQueryivEXT(GC3Denum target, GC3Denum pname, GC3Dint* params)
-{
- m_context->webContext()->getQueryivEXT(target, pname, params);
-}
-
-void Extensions3D::getQueryObjectuivEXT(Platform3DObject query, GC3Denum pname, GC3Duint* params)
-{
- m_context->webContext()->getQueryObjectuivEXT(query, pname, params);
-}
-
-bool Extensions3D::canUseCopyTextureCHROMIUM(GC3Denum destFormat, GC3Denum destType, GC3Dint level)
-{
- // FIXME: restriction of (RGB || RGBA)/UNSIGNED_BYTE/(Level 0) should be lifted when
- // WebGraphicsContext3D::copyTextureCHROMIUM(...) are fully functional.
- if ((destFormat == GraphicsContext3D::RGB || destFormat == GraphicsContext3D::RGBA)
- && destType == GraphicsContext3D::UNSIGNED_BYTE
- && !level)
- return true;
- return false;
-}
-
-void Extensions3D::copyTextureCHROMIUM(GC3Denum target, Platform3DObject sourceId, Platform3DObject destId, GC3Dint level, GC3Denum internalFormat, GC3Denum destType)
-{
- m_context->webContext()->copyTextureCHROMIUM(target, sourceId, destId, level, internalFormat, destType);
-}
-
-void Extensions3D::shallowFlushCHROMIUM()
-{
- return m_context->webContext()->shallowFlushCHROMIUM();
-}
-
-void Extensions3D::insertEventMarkerEXT(const String& marker)
-{
- m_context->webContext()->insertEventMarkerEXT(marker.utf8().data());
-}
-
-void Extensions3D::pushGroupMarkerEXT(const String& marker)
-{
- m_context->webContext()->pushGroupMarkerEXT(marker.utf8().data());
-}
-
-void Extensions3D::popGroupMarkerEXT(void)
-{
- m_context->webContext()->popGroupMarkerEXT();
-}
-
-void Extensions3D::drawBuffersEXT(GC3Dsizei n, const GC3Denum* bufs)
-{
- m_context->webContext()->drawBuffersEXT(n, bufs);
-}
-
-void Extensions3D::drawArraysInstancedANGLE(GC3Denum mode, GC3Dint first, GC3Dsizei count, GC3Dsizei primcount)
-{
- m_context->webContext()->drawArraysInstancedANGLE(mode, first, count, primcount);
-}
-
-void Extensions3D::drawElementsInstancedANGLE(GC3Denum mode, GC3Dsizei count, GC3Denum type, GC3Dintptr offset, GC3Dsizei primcount)
-{
- m_context->webContext()->drawElementsInstancedANGLE(mode, count, type, offset, primcount);
-}
-
-void Extensions3D::vertexAttribDivisorANGLE(GC3Duint index, GC3Duint divisor)
-{
- m_context->webContext()->vertexAttribDivisorANGLE(index, divisor);
-}
-
-void Extensions3D::loseContextCHROMIUM(GC3Denum current, GC3Denum other)
-{
- m_context->webContext()->loseContextCHROMIUM(current, other);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/Extensions3D.h b/chromium/third_party/WebKit/Source/core/platform/graphics/Extensions3D.h
deleted file mode 100644
index 80704c4ee0d..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/Extensions3D.h
+++ /dev/null
@@ -1,333 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef Extensions3D_h
-#define Extensions3D_h
-
-#include "core/platform/graphics/GraphicsTypes3D.h"
-
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class GraphicsContext3D;
-class ImageBuffer;
-
-// The supported extensions are defined below.
-//
-// Calling any extension function not supported by the current context
-// must be a no-op; in particular, it may not have side effects. In
-// this situation, if the function has a return value, 0 is returned.
-class Extensions3D {
-public:
- ~Extensions3D();
-
- // Supported extensions:
- // GL_EXT_texture_format_BGRA8888
- // GL_EXT_read_format_bgra
- // GL_ARB_robustness
- // GL_ARB_texture_non_power_of_two / GL_OES_texture_npot
- // GL_EXT_packed_depth_stencil / GL_OES_packed_depth_stencil
- // GL_ANGLE_framebuffer_blit / GL_ANGLE_framebuffer_multisample
- // GL_OES_texture_float
- // GL_OES_texture_float_linear
- // GL_OES_texture_half_float
- // GL_OES_texture_half_float_linear
- // GL_OES_standard_derivatives
- // GL_OES_rgb8_rgba8
- // GL_OES_vertex_array_object
- // GL_OES_element_index_uint
- // GL_ANGLE_translated_shader_source
- // GL_ARB_texture_rectangle (only the subset required to
- // implement IOSurface binding; it's recommended to support
- // this only on Mac OS X to limit the amount of code dependent
- // on this extension)
- // GL_EXT_texture_compression_dxt1
- // GL_EXT_texture_compression_s3tc
- // GL_OES_compressed_ETC1_RGB8_texture
- // GL_IMG_texture_compression_pvrtc
- // EXT_texture_filter_anisotropic
- // GL_EXT_debug_marker
- // GL_CHROMIUM_copy_texture
- // GL_CHROMIUM_flipy
- // GL_ARB_draw_buffers / GL_EXT_draw_buffers
- // GL_ANGLE_instanced_arrays
-
- // GL_CHROMIUM_shallow_flush : only supported if an ipc command buffer is used.
- // GL_CHROMIUM_resource_safe : indicating that textures/renderbuffers are always initialized before read/write.
- // GL_CHROMIUM_strict_attribs : indicating a GL error is generated for out-of-bounds buffer accesses.
- // GL_CHROMIUM_post_sub_buffer
- // GL_CHROMIUM_map_sub
- // GL_CHROMIUM_swapbuffers_complete_callback
- // GL_CHROMIUM_rate_limit_offscreen_context
- // GL_CHROMIUM_paint_framebuffer_canvas
- // GL_CHROMIUM_iosurface (Mac OS X specific)
- // GL_CHROMIUM_command_buffer_query
- // GL_ANGLE_texture_usage
- // GL_EXT_debug_marker
- // GL_EXT_texture_storage
- // GL_EXT_occlusion_query_boolean
-
- // Takes full name of extension; for example,
- // "GL_EXT_texture_format_BGRA8888".
- bool supports(const String&);
-
- // Certain OpenGL and WebGL implementations may support enabling
- // extensions lazily. This method may only be called with
- // extension names for which supports returns true.
- void ensureEnabled(const String&);
-
- // Takes full name of extension: for example, "GL_EXT_texture_format_BGRA8888".
- // Checks to see whether the given extension is actually enabled (see ensureEnabled).
- // Has no other side-effects.
- bool isEnabled(const String&);
-
- enum ExtensionsEnumType {
- // GL_EXT_texture_format_BGRA8888 enums
- BGRA_EXT = 0x80E1,
-
- // GL_ARB_robustness/GL_CHROMIUM_lose_context enums
- GUILTY_CONTEXT_RESET_ARB = 0x8253,
- INNOCENT_CONTEXT_RESET_ARB = 0x8254,
- UNKNOWN_CONTEXT_RESET_ARB = 0x8255,
-
- // GL_EXT/OES_packed_depth_stencil enums
- DEPTH24_STENCIL8 = 0x88F0,
-
- // GL_ANGLE_framebuffer_blit names
- READ_FRAMEBUFFER = 0x8CA8,
- DRAW_FRAMEBUFFER = 0x8CA9,
- DRAW_FRAMEBUFFER_BINDING = 0x8CA6,
- READ_FRAMEBUFFER_BINDING = 0x8CAA,
-
- // GL_ANGLE_framebuffer_multisample names
- RENDERBUFFER_SAMPLES = 0x8CAB,
- FRAMEBUFFER_INCOMPLETE_MULTISAMPLE = 0x8D56,
- MAX_SAMPLES = 0x8D57,
-
- // GL_OES_standard_derivatives names
- FRAGMENT_SHADER_DERIVATIVE_HINT_OES = 0x8B8B,
-
- // GL_OES_rgb8_rgba8 names
- RGB8_OES = 0x8051,
- RGBA8_OES = 0x8058,
-
- // GL_OES_vertex_array_object names
- VERTEX_ARRAY_BINDING_OES = 0x85B5,
-
- // GL_ANGLE_translated_shader_source
- TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE = 0x93A0,
-
- // GL_ARB_texture_rectangle
- TEXTURE_RECTANGLE_ARB = 0x84F5,
- TEXTURE_BINDING_RECTANGLE_ARB = 0x84F6,
-
- // GL_EXT_texture_compression_dxt1
- // GL_EXT_texture_compression_s3tc
- COMPRESSED_RGB_S3TC_DXT1_EXT = 0x83F0,
- COMPRESSED_RGBA_S3TC_DXT1_EXT = 0x83F1,
- COMPRESSED_RGBA_S3TC_DXT3_EXT = 0x83F2,
- COMPRESSED_RGBA_S3TC_DXT5_EXT = 0x83F3,
-
- // GL_OES_compressed_ETC1_RGB8_texture
- ETC1_RGB8_OES = 0x8D64,
-
- // GL_IMG_texture_compression_pvrtc
- COMPRESSED_RGB_PVRTC_4BPPV1_IMG = 0x8C00,
- COMPRESSED_RGB_PVRTC_2BPPV1_IMG = 0x8C01,
- COMPRESSED_RGBA_PVRTC_4BPPV1_IMG = 0x8C02,
- COMPRESSED_RGBA_PVRTC_2BPPV1_IMG = 0x8C03,
-
- // GL_AMD_compressed_ATC_texture
- COMPRESSED_ATC_RGB_AMD = 0x8C92,
- COMPRESSED_ATC_RGBA_EXPLICIT_ALPHA_AMD = 0x8C93,
- COMPRESSED_ATC_RGBA_INTERPOLATED_ALPHA_AMD = 0x87EE,
-
- // GL_EXT_texture_filter_anisotropic
- TEXTURE_MAX_ANISOTROPY_EXT = 0x84FE,
- MAX_TEXTURE_MAX_ANISOTROPY_EXT = 0x84FF,
-
- // GL_CHROMIUM_flipy
- UNPACK_FLIP_Y_CHROMIUM = 0x9240,
-
- // GL_CHROMIUM_copy_texture
- UNPACK_PREMULTIPLY_ALPHA_CHROMIUM = 0x9241,
- UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM = 0x9242,
-
- // GL_ARB_draw_buffers / GL_EXT_draw_buffers
- MAX_DRAW_BUFFERS_EXT = 0x8824,
- DRAW_BUFFER0_EXT = 0x8825,
- DRAW_BUFFER1_EXT = 0x8826,
- DRAW_BUFFER2_EXT = 0x8827,
- DRAW_BUFFER3_EXT = 0x8828,
- DRAW_BUFFER4_EXT = 0x8829,
- DRAW_BUFFER5_EXT = 0x882A,
- DRAW_BUFFER6_EXT = 0x882B,
- DRAW_BUFFER7_EXT = 0x882C,
- DRAW_BUFFER8_EXT = 0x882D,
- DRAW_BUFFER9_EXT = 0x882E,
- DRAW_BUFFER10_EXT = 0x882F,
- DRAW_BUFFER11_EXT = 0x8830,
- DRAW_BUFFER12_EXT = 0x8831,
- DRAW_BUFFER13_EXT = 0x8832,
- DRAW_BUFFER14_EXT = 0x8833,
- DRAW_BUFFER15_EXT = 0x8834,
- MAX_COLOR_ATTACHMENTS_EXT = 0x8CDF,
- COLOR_ATTACHMENT0_EXT = 0x8CE0,
- COLOR_ATTACHMENT1_EXT = 0x8CE1,
- COLOR_ATTACHMENT2_EXT = 0x8CE2,
- COLOR_ATTACHMENT3_EXT = 0x8CE3,
- COLOR_ATTACHMENT4_EXT = 0x8CE4,
- COLOR_ATTACHMENT5_EXT = 0x8CE5,
- COLOR_ATTACHMENT6_EXT = 0x8CE6,
- COLOR_ATTACHMENT7_EXT = 0x8CE7,
- COLOR_ATTACHMENT8_EXT = 0x8CE8,
- COLOR_ATTACHMENT9_EXT = 0x8CE9,
- COLOR_ATTACHMENT10_EXT = 0x8CEA,
- COLOR_ATTACHMENT11_EXT = 0x8CEB,
- COLOR_ATTACHMENT12_EXT = 0x8CEC,
- COLOR_ATTACHMENT13_EXT = 0x8CED,
- COLOR_ATTACHMENT14_EXT = 0x8CEE,
- COLOR_ATTACHMENT15_EXT = 0x8CEF,
-
- // GL_OES_EGL_image_external
- GL_TEXTURE_EXTERNAL_OES = 0x8D65,
-
- // GL_CHROMIUM_map_sub (enums inherited from GL_ARB_vertex_buffer_object)
- READ_ONLY = 0x88B8,
- WRITE_ONLY = 0x88B9,
-
- // GL_ANGLE_texture_usage
- GL_TEXTURE_USAGE_ANGLE = 0x93A2,
- GL_FRAMEBUFFER_ATTACHMENT_ANGLE = 0x93A3,
-
- // GL_EXT_texture_storage
- BGRA8_EXT = 0x93A1,
-
- // GL_EXT_occlusion_query_boolean
- ANY_SAMPLES_PASSED_EXT = 0x8C2F,
- ANY_SAMPLES_PASSED_CONSERVATIVE_EXT = 0x8D6A,
- CURRENT_QUERY_EXT = 0x8865,
- QUERY_RESULT_EXT = 0x8866,
- QUERY_RESULT_AVAILABLE_EXT = 0x8867,
-
- // GL_CHROMIUM_command_buffer_query
- COMMANDS_ISSUED_CHROMIUM = 0x84F2,
-
- // GL_ANGLE_instanced_arrays
- VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE = 0x88FE
- };
-
- // GL_ARB_robustness
- // Note: This method's behavior differs from the GL_ARB_robustness
- // specification in the following way:
- // The implementation must not reset the error state during this call.
- // If getGraphicsResetStatusARB returns an error, it should continue
- // returning the same error. Restoring the GraphicsContext3D is handled
- // externally.
- int getGraphicsResetStatusARB();
-
- // GL_ANGLE_framebuffer_blit
- void blitFramebuffer(long srcX0, long srcY0, long srcX1, long srcY1, long dstX0, long dstY0, long dstX1, long dstY1, unsigned long mask, unsigned long filter);
-
- // GL_ANGLE_framebuffer_multisample
- void renderbufferStorageMultisample(unsigned long target, unsigned long samples, unsigned long internalformat, unsigned long width, unsigned long height);
-
- // GL_OES_vertex_array_object
- Platform3DObject createVertexArrayOES();
- void deleteVertexArrayOES(Platform3DObject);
- GC3Dboolean isVertexArrayOES(Platform3DObject);
- void bindVertexArrayOES(Platform3DObject);
-
- // GL_ANGLE_translated_shader_source
- String getTranslatedShaderSourceANGLE(Platform3DObject);
-
- // GL_CHROMIUM_copy_texture
- // canUseCopyTextureCHROMIUM(...) is used to check if copyTextureCHROMIUM(...) can work for the specified
- // format, type and level for the destination texture.
- bool canUseCopyTextureCHROMIUM(GC3Denum destFormat, GC3Denum destType, GC3Dint level);
- void copyTextureCHROMIUM(GC3Denum, Platform3DObject, Platform3DObject, GC3Dint, GC3Denum, GC3Denum);
-
- // GL_EXT_debug_marker
- void insertEventMarkerEXT(const String&);
- void pushGroupMarkerEXT(const String&);
- void popGroupMarkerEXT(void);
-
- // GL_ARB_draw_buffers / GL_EXT_draw_buffers
- void drawBuffersEXT(GC3Dsizei n, const GC3Denum* bufs);
-
- // GL_CHROMIUM_map_sub
- void* mapBufferSubDataCHROMIUM(unsigned target, int offset, int size, unsigned access);
- void unmapBufferSubDataCHROMIUM(const void*);
- void* mapTexSubImage2DCHROMIUM(unsigned target, int level, int xoffset, int yoffset, int width, int height, unsigned format, unsigned type, unsigned access);
- void unmapTexSubImage2DCHROMIUM(const void*);
-
- // GL_CHROMIUM_rate_limit_offscreen_context
- void rateLimitOffscreenContextCHROMIUM();
-
- // GL_CHROMIUM_paint_framebuffer_canvas
- void paintFramebufferToCanvas(int framebuffer, int width, int height, bool premultiplyAlpha, ImageBuffer*);
-
- // GL_CHROMIUM_iosurface
- // To avoid needing to expose extraneous enums, assumes internal format
- // RGBA, format BGRA, and type UNSIGNED_INT_8_8_8_8_REV.
- void texImageIOSurface2DCHROMIUM(unsigned target, int width, int height, uint32_t ioSurfaceId, unsigned plane);
-
- // GL_EXT_texture_storage
- void texStorage2DEXT(unsigned target, int levels, unsigned internalformat, int width, int height);
-
- // GL_EXT_occlusion_query
- Platform3DObject createQueryEXT();
- void deleteQueryEXT(Platform3DObject);
- GC3Dboolean isQueryEXT(Platform3DObject);
- void beginQueryEXT(GC3Denum, Platform3DObject);
- void endQueryEXT(GC3Denum);
- void getQueryivEXT(GC3Denum, GC3Denum, GC3Dint*);
- void getQueryObjectuivEXT(Platform3DObject, GC3Denum, GC3Duint*);
-
- // GL_CHROMIUM_shallow_flush
- void shallowFlushCHROMIUM();
-
- // GL_ANGLE_instanced_arrays
- void drawArraysInstancedANGLE(GC3Denum mode, GC3Dint first, GC3Dsizei count, GC3Dsizei primcount);
- void drawElementsInstancedANGLE(GC3Denum mode, GC3Dsizei count, GC3Denum type, GC3Dintptr offset, GC3Dsizei primcount);
- void vertexAttribDivisorANGLE(GC3Duint index, GC3Duint divisor);
-
- // GL_CHROMIUM_lose_context
- void loseContextCHROMIUM(GC3Denum, GC3Denum);
-
-private:
- // Instances of this class are strictly owned by the GraphicsContext3D implementation and do not
- // need to be instantiated by any other code.
- friend class GraphicsContext3D;
- explicit Extensions3D(GraphicsContext3D*);
-
- // Weak pointer back to GraphicsContext3D.
- GraphicsContext3D* m_context;
-};
-
-} // namespace WebCore
-
-#endif // Extensions3D_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/FloatPoint.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/FloatPoint.cpp
deleted file mode 100644
index d92d6abfdd0..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/FloatPoint.cpp
+++ /dev/null
@@ -1,147 +0,0 @@
-/*
- * Copyright (C) 2004, 2006, 2007 Apple Inc. All rights reserved.
- * Copyright (C) 2005 Nokia. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/FloatPoint.h"
-
-#include <math.h>
-#include <limits>
-#include "core/platform/FloatConversion.h"
-#include "core/platform/graphics/IntPoint.h"
-#include "core/platform/graphics/LayoutPoint.h"
-#include "core/platform/graphics/LayoutSize.h"
-#include "core/platform/graphics/skia/SkiaUtils.h"
-#include "core/platform/graphics/transforms/AffineTransform.h"
-#include "core/platform/graphics/transforms/TransformationMatrix.h"
-#include "third_party/skia/include/core/SkPoint.h"
-
-namespace WebCore {
-
-FloatPoint::FloatPoint(const IntPoint& p) : m_x(p.x()), m_y(p.y())
-{
-}
-
-FloatPoint::FloatPoint(const LayoutPoint& p) : m_x(p.x()), m_y(p.y())
-{
-}
-
-void FloatPoint::normalize()
-{
- float tempLength = length();
-
- if (tempLength) {
- m_x /= tempLength;
- m_y /= tempLength;
- }
-}
-
-float FloatPoint::slopeAngleRadians() const
-{
- return atan2f(m_y, m_x);
-}
-
-float FloatPoint::length() const
-{
- return sqrtf(lengthSquared());
-}
-
-void FloatPoint::move(const LayoutSize& size)
-{
- m_x += size.width();
- m_y += size.height();
-}
-
-void FloatPoint::moveBy(const LayoutPoint& point)
-{
- m_x += point.x();
- m_y += point.y();
-}
-
-FloatPoint::operator SkPoint() const
-{
- SkPoint p = { WebCoreFloatToSkScalar(m_x), WebCoreFloatToSkScalar(m_y) };
- return p;
-}
-
-FloatPoint FloatPoint::matrixTransform(const AffineTransform& transform) const
-{
- double newX, newY;
- transform.map(static_cast<double>(m_x), static_cast<double>(m_y), newX, newY);
- return narrowPrecision(newX, newY);
-}
-
-FloatPoint FloatPoint::matrixTransform(const TransformationMatrix& transform) const
-{
- double newX, newY;
- transform.map(static_cast<double>(m_x), static_cast<double>(m_y), newX, newY);
- return narrowPrecision(newX, newY);
-}
-
-FloatPoint FloatPoint::narrowPrecision(double x, double y)
-{
- return FloatPoint(narrowPrecisionToFloat(x), narrowPrecisionToFloat(y));
-}
-
-float findSlope(const FloatPoint& p1, const FloatPoint& p2, float& c)
-{
- if (p2.x() == p1.x())
- return std::numeric_limits<float>::infinity();
-
- // y = mx + c
- float slope = (p2.y() - p1.y()) / (p2.x() - p1.x());
- c = p1.y() - slope * p1.x();
- return slope;
-}
-
-bool findIntersection(const FloatPoint& p1, const FloatPoint& p2, const FloatPoint& d1, const FloatPoint& d2, FloatPoint& intersection)
-{
- float pOffset = 0;
- float pSlope = findSlope(p1, p2, pOffset);
-
- float dOffset = 0;
- float dSlope = findSlope(d1, d2, dOffset);
-
- if (dSlope == pSlope)
- return false;
-
- if (pSlope == std::numeric_limits<float>::infinity()) {
- intersection.setX(p1.x());
- intersection.setY(dSlope * intersection.x() + dOffset);
- return true;
- }
- if (dSlope == std::numeric_limits<float>::infinity()) {
- intersection.setX(d1.x());
- intersection.setY(pSlope * intersection.x() + pOffset);
- return true;
- }
-
- // Find x at intersection, where ys overlap; x = (c' - c) / (m - m')
- intersection.setX((dOffset - pOffset) / (pSlope - dSlope));
- intersection.setY(pSlope * intersection.x() + pOffset);
- return true;
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/FloatPoint.h b/chromium/third_party/WebKit/Source/core/platform/graphics/FloatPoint.h
deleted file mode 100644
index 9ddbc2beec9..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/FloatPoint.h
+++ /dev/null
@@ -1,245 +0,0 @@
-/*
- * Copyright (C) 2004, 2006, 2007 Apple Inc. All rights reserved.
- * Copyright (C) 2005 Nokia. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef FloatPoint_h
-#define FloatPoint_h
-
-#include "core/platform/graphics/FloatSize.h"
-#include "core/platform/graphics/IntPoint.h"
-#include "wtf/MathExtras.h"
-#include <algorithm>
-
-#if OS(MACOSX)
-typedef struct CGPoint CGPoint;
-
-#ifdef NSGEOMETRY_TYPES_SAME_AS_CGGEOMETRY_TYPES
-typedef struct CGPoint NSPoint;
-#else
-typedef struct _NSPoint NSPoint;
-#endif
-#endif
-
-struct SkPoint;
-
-namespace WebCore {
-
-class AffineTransform;
-class TransformationMatrix;
-class IntPoint;
-class IntSize;
-class LayoutPoint;
-class LayoutSize;
-
-class FloatPoint {
-public:
- FloatPoint() : m_x(0), m_y(0) { }
- FloatPoint(float x, float y) : m_x(x), m_y(y) { }
- FloatPoint(const IntPoint&);
- FloatPoint(const LayoutPoint&);
- explicit FloatPoint(const FloatSize& size) : m_x(size.width()), m_y(size.height()) { }
-
- static FloatPoint zero() { return FloatPoint(); }
-
- static FloatPoint narrowPrecision(double x, double y);
-
- float x() const { return m_x; }
- float y() const { return m_y; }
-
- void setX(float x) { m_x = x; }
- void setY(float y) { m_y = y; }
- void set(float x, float y)
- {
- m_x = x;
- m_y = y;
- }
- void move(float dx, float dy)
- {
- m_x += dx;
- m_y += dy;
- }
- void move(const IntSize& a)
- {
- m_x += a.width();
- m_y += a.height();
- }
- void move(const LayoutSize&);
- void move(const FloatSize& a)
- {
- m_x += a.width();
- m_y += a.height();
- }
- void moveBy(const IntPoint& a)
- {
- m_x += a.x();
- m_y += a.y();
- }
- void moveBy(const LayoutPoint&);
- void moveBy(const FloatPoint& a)
- {
- m_x += a.x();
- m_y += a.y();
- }
- void scale(float sx, float sy)
- {
- m_x *= sx;
- m_y *= sy;
- }
-
- void normalize();
-
- float dot(const FloatPoint& a) const
- {
- return m_x * a.x() + m_y * a.y();
- }
-
- float slopeAngleRadians() const;
- float length() const;
- float lengthSquared() const
- {
- return m_x * m_x + m_y * m_y;
- }
-
- FloatPoint expandedTo(const FloatPoint& other) const
- {
- return FloatPoint(std::max(m_x, other.m_x), std::max(m_y, other.m_y));
- }
-
- FloatPoint transposedPoint() const
- {
- return FloatPoint(m_y, m_x);
- }
-
-#if OS(MACOSX)
- FloatPoint(const CGPoint&);
- operator CGPoint() const;
-#if !defined(NSGEOMETRY_TYPES_SAME_AS_CGGEOMETRY_TYPES)
- FloatPoint(const NSPoint&);
- operator NSPoint() const;
-#endif
-#endif
-
- operator SkPoint() const;
-
- FloatPoint matrixTransform(const TransformationMatrix&) const;
- FloatPoint matrixTransform(const AffineTransform&) const;
-
-private:
- float m_x, m_y;
-};
-
-
-inline FloatPoint& operator+=(FloatPoint& a, const FloatSize& b)
-{
- a.move(b.width(), b.height());
- return a;
-}
-
-inline FloatPoint& operator+=(FloatPoint& a, const FloatPoint& b)
-{
- a.move(b.x(), b.y());
- return a;
-}
-
-inline FloatPoint& operator-=(FloatPoint& a, const FloatSize& b)
-{
- a.move(-b.width(), -b.height());
- return a;
-}
-
-inline FloatPoint operator+(const FloatPoint& a, const FloatSize& b)
-{
- return FloatPoint(a.x() + b.width(), a.y() + b.height());
-}
-
-inline FloatPoint operator+(const FloatPoint& a, const FloatPoint& b)
-{
- return FloatPoint(a.x() + b.x(), a.y() + b.y());
-}
-
-inline FloatSize operator-(const FloatPoint& a, const FloatPoint& b)
-{
- return FloatSize(a.x() - b.x(), a.y() - b.y());
-}
-
-inline FloatPoint operator-(const FloatPoint& a, const FloatSize& b)
-{
- return FloatPoint(a.x() - b.width(), a.y() - b.height());
-}
-
-inline FloatPoint operator-(const FloatPoint& a)
-{
- return FloatPoint(-a.x(), -a.y());
-}
-
-inline bool operator==(const FloatPoint& a, const FloatPoint& b)
-{
- return a.x() == b.x() && a.y() == b.y();
-}
-
-inline bool operator!=(const FloatPoint& a, const FloatPoint& b)
-{
- return a.x() != b.x() || a.y() != b.y();
-}
-
-inline float operator*(const FloatPoint& a, const FloatPoint& b)
-{
- // dot product
- return a.dot(b);
-}
-
-inline IntPoint roundedIntPoint(const FloatPoint& p)
-{
- return IntPoint(clampToInteger(roundf(p.x())), clampToInteger(roundf(p.y())));
-}
-
-inline IntPoint flooredIntPoint(const FloatPoint& p)
-{
- return IntPoint(clampToInteger(floorf(p.x())), clampToInteger(floorf(p.y())));
-}
-
-inline IntPoint ceiledIntPoint(const FloatPoint& p)
-{
- return IntPoint(clampToInteger(ceilf(p.x())), clampToInteger(ceilf(p.y())));
-}
-
-inline IntSize flooredIntSize(const FloatPoint& p)
-{
- return IntSize(clampToInteger(floorf(p.x())), clampToInteger(floorf(p.y())));
-}
-
-inline FloatSize toFloatSize(const FloatPoint& a)
-{
- return FloatSize(a.x(), a.y());
-}
-
-float findSlope(const FloatPoint& p1, const FloatPoint& p2, float& c);
-
-// Find point where lines through the two pairs of points intersect. Returns false if the lines don't intersect.
-bool findIntersection(const FloatPoint& p1, const FloatPoint& p2, const FloatPoint& d1, const FloatPoint& d2, FloatPoint& intersection);
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/FloatPoint3D.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/FloatPoint3D.cpp
deleted file mode 100644
index 75bc4abfcc8..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/FloatPoint3D.cpp
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- Copyright (C) 2004, 2005, 2006 Nikolas Zimmermann <wildfox@kde.org>
- 2004, 2005 Rob Buis <buis@kde.org>
- 2005 Eric Seidel <eric@webkit.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- aint with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include "config.h"
-
-#include "core/platform/graphics/FloatPoint3D.h"
-
-#include <math.h>
-
-namespace WebCore {
-
-void FloatPoint3D::normalize()
-{
- float tempLength = length();
-
- if (tempLength) {
- m_x /= tempLength;
- m_y /= tempLength;
- m_z /= tempLength;
- }
-}
-
-} // namespace WebCore
-
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/FloatPoint3D.h b/chromium/third_party/WebKit/Source/core/platform/graphics/FloatPoint3D.h
deleted file mode 100644
index 2a136c9ea48..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/FloatPoint3D.h
+++ /dev/null
@@ -1,187 +0,0 @@
-/*
- Copyright (C) 2004, 2005, 2006 Nikolas Zimmermann <wildfox@kde.org>
- 2004, 2005 Rob Buis <buis@kde.org>
- 2005 Eric Seidel <eric@webkit.org>
- 2010 Zoltan Herczeg <zherczeg@webkit.org>
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- aint with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#ifndef FloatPoint3D_h
-#define FloatPoint3D_h
-
-#include "core/platform/graphics/FloatPoint.h"
-
-namespace WebCore {
-
-class FloatPoint3D {
-public:
- FloatPoint3D()
- : m_x(0)
- , m_y(0)
- , m_z(0)
- {
- }
-
- FloatPoint3D(float x, float y, float z)
- : m_x(x)
- , m_y(y)
- , m_z(z)
- {
- }
-
- FloatPoint3D(const FloatPoint& p)
- : m_x(p.x())
- , m_y(p.y())
- , m_z(0)
- {
- }
-
- FloatPoint3D(const FloatPoint3D& p)
- : m_x(p.x())
- , m_y(p.y())
- , m_z(p.z())
- {
- }
-
- float x() const { return m_x; }
- void setX(float x) { m_x = x; }
-
- float y() const { return m_y; }
- void setY(float y) { m_y = y; }
-
- float z() const { return m_z; }
- void setZ(float z) { m_z = z; }
- void set(float x, float y, float z)
- {
- m_x = x;
- m_y = y;
- m_z = z;
- }
- void move(float dx, float dy, float dz)
- {
- m_x += dx;
- m_y += dy;
- m_z += dz;
- }
- void scale(float sx, float sy, float sz)
- {
- m_x *= sx;
- m_y *= sy;
- m_z *= sz;
- }
-
- bool isZero() const
- {
- return !m_x && !m_y && !m_z;
- }
-
- void normalize();
-
- float dot(const FloatPoint3D& a) const
- {
- return m_x * a.x() + m_y * a.y() + m_z * a.z();
- }
-
- // Sets this FloatPoint3D to the cross product of the passed two.
- // It is safe for "this" to be the same as either or both of the
- // arguments.
- void cross(const FloatPoint3D& a, const FloatPoint3D& b)
- {
- float x = a.y() * b.z() - a.z() * b.y();
- float y = a.z() * b.x() - a.x() * b.z();
- float z = a.x() * b.y() - a.y() * b.x();
- m_x = x;
- m_y = y;
- m_z = z;
- }
-
- // Convenience function returning "this cross point" as a
- // stack-allocated result.
- FloatPoint3D cross(const FloatPoint3D& point) const
- {
- FloatPoint3D result;
- result.cross(*this, point);
- return result;
- }
-
- float lengthSquared() const { return this->dot(*this); }
- float length() const { return sqrtf(lengthSquared()); }
-
- float distanceTo(const FloatPoint3D& a) const;
-
-private:
- float m_x;
- float m_y;
- float m_z;
-};
-
-inline FloatPoint3D& operator +=(FloatPoint3D& a, const FloatPoint3D& b)
-{
- a.move(b.x(), b.y(), b.z());
- return a;
-}
-
-inline FloatPoint3D& operator -=(FloatPoint3D& a, const FloatPoint3D& b)
-{
- a.move(-b.x(), -b.y(), -b.z());
- return a;
-}
-
-inline FloatPoint3D operator+(const FloatPoint3D& a, const FloatPoint3D& b)
-{
- return FloatPoint3D(a.x() + b.x(), a.y() + b.y(), a.z() + b.z());
-}
-
-inline FloatPoint3D operator-(const FloatPoint3D& a, const FloatPoint3D& b)
-{
- return FloatPoint3D(a.x() - b.x(), a.y() - b.y(), a.z() - b.z());
-}
-
-inline bool operator==(const FloatPoint3D& a, const FloatPoint3D& b)
-{
- return a.x() == b.x() && a.y() == b.y() && a.z() == b.z();
-}
-
-inline bool operator!=(const FloatPoint3D& a, const FloatPoint3D& b)
-{
- return a.x() != b.x() || a.y() != b.y() || a.z() != b.z();
-}
-
-inline float operator*(const FloatPoint3D& a, const FloatPoint3D& b)
-{
- // dot product
- return a.dot(b);
-}
-
-inline FloatPoint3D operator*(float k, const FloatPoint3D& v)
-{
- return FloatPoint3D(k * v.x(), k * v.y(), k * v.z());
-}
-
-inline FloatPoint3D operator*(const FloatPoint3D& v, float k)
-{
- return FloatPoint3D(k * v.x(), k * v.y(), k * v.z());
-}
-
-inline float FloatPoint3D::distanceTo(const FloatPoint3D& a) const
-{
- return (*this - a).length();
-}
-
-} // namespace WebCore
-
-#endif // FloatPoint3D_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/FloatPolygon.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/FloatPolygon.cpp
deleted file mode 100644
index c455a3e1c7f..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/FloatPolygon.cpp
+++ /dev/null
@@ -1,254 +0,0 @@
-/*
- * Copyright (C) 2012 Adobe Systems Incorporated. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above
- * copyright notice, this list of conditions and the following
- * disclaimer.
- * 2. Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following
- * disclaimer in the documentation and/or other materials
- * provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
- * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
- * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
- * OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/FloatPolygon.h"
-
-#include "wtf/MathExtras.h"
-
-namespace WebCore {
-
-static inline float determinant(const FloatSize& a, const FloatSize& b)
-{
- return a.width() * b.height() - a.height() * b.width();
-}
-
-static inline bool areCollinearPoints(const FloatPoint& p0, const FloatPoint& p1, const FloatPoint& p2)
-{
- return !determinant(p1 - p0, p2 - p0);
-}
-
-static inline bool areCoincidentPoints(const FloatPoint& p0, const FloatPoint& p1)
-{
- return p0.x() == p1.x() && p0.y() == p1.y();
-}
-
-static inline bool isPointOnLineSegment(const FloatPoint& vertex1, const FloatPoint& vertex2, const FloatPoint& point)
-{
- return point.x() >= std::min(vertex1.x(), vertex2.x())
- && point.x() <= std::max(vertex1.x(), vertex2.x())
- && areCollinearPoints(vertex1, vertex2, point);
-}
-
-static inline unsigned nextVertexIndex(unsigned vertexIndex, unsigned nVertices, bool clockwise)
-{
- return ((clockwise) ? vertexIndex + 1 : vertexIndex - 1 + nVertices) % nVertices;
-}
-
-static unsigned findNextEdgeVertexIndex(const FloatPolygon& polygon, unsigned vertexIndex1, bool clockwise)
-{
- unsigned nVertices = polygon.numberOfVertices();
- unsigned vertexIndex2 = nextVertexIndex(vertexIndex1, nVertices, clockwise);
-
- while (vertexIndex2 && areCoincidentPoints(polygon.vertexAt(vertexIndex1), polygon.vertexAt(vertexIndex2)))
- vertexIndex2 = nextVertexIndex(vertexIndex2, nVertices, clockwise);
-
- while (vertexIndex2) {
- unsigned vertexIndex3 = nextVertexIndex(vertexIndex2, nVertices, clockwise);
- if (!areCollinearPoints(polygon.vertexAt(vertexIndex1), polygon.vertexAt(vertexIndex2), polygon.vertexAt(vertexIndex3)))
- break;
- vertexIndex2 = vertexIndex3;
- }
-
- return vertexIndex2;
-}
-
-FloatPolygon::FloatPolygon(PassOwnPtr<Vector<FloatPoint> > vertices, WindRule fillRule)
- : m_vertices(vertices)
- , m_fillRule(fillRule)
-{
- unsigned nVertices = numberOfVertices();
- m_edges.resize(nVertices);
- m_empty = nVertices < 3;
-
- if (nVertices)
- m_boundingBox.setLocation(vertexAt(0));
-
- if (m_empty)
- return;
-
- unsigned minVertexIndex = 0;
- for (unsigned i = 1; i < nVertices; ++i) {
- const FloatPoint& vertex = vertexAt(i);
- if (vertex.y() < vertexAt(minVertexIndex).y() || (vertex.y() == vertexAt(minVertexIndex).y() && vertex.x() < vertexAt(minVertexIndex).x()))
- minVertexIndex = i;
- }
- FloatPoint nextVertex = vertexAt((minVertexIndex + 1) % nVertices);
- FloatPoint prevVertex = vertexAt((minVertexIndex + nVertices - 1) % nVertices);
- bool clockwise = determinant(vertexAt(minVertexIndex) - prevVertex, nextVertex - prevVertex) > 0;
-
- unsigned edgeIndex = 0;
- unsigned vertexIndex1 = 0;
- do {
- m_boundingBox.extend(vertexAt(vertexIndex1));
- unsigned vertexIndex2 = findNextEdgeVertexIndex(*this, vertexIndex1, clockwise);
- m_edges[edgeIndex].m_polygon = this;
- m_edges[edgeIndex].m_vertexIndex1 = vertexIndex1;
- m_edges[edgeIndex].m_vertexIndex2 = vertexIndex2;
- m_edges[edgeIndex].m_edgeIndex = edgeIndex;
- ++edgeIndex;
- vertexIndex1 = vertexIndex2;
- } while (vertexIndex1);
-
- if (edgeIndex > 3) {
- const FloatPolygonEdge& firstEdge = m_edges[0];
- const FloatPolygonEdge& lastEdge = m_edges[edgeIndex - 1];
- if (areCollinearPoints(lastEdge.vertex1(), lastEdge.vertex2(), firstEdge.vertex2())) {
- m_edges[0].m_vertexIndex1 = lastEdge.m_vertexIndex1;
- edgeIndex--;
- }
- }
-
- m_edges.resize(edgeIndex);
- m_empty = m_edges.size() < 3;
-
- if (m_empty)
- return;
-
- for (unsigned i = 0; i < m_edges.size(); ++i) {
- FloatPolygonEdge* edge = &m_edges[i];
- m_edgeTree.add(EdgeInterval(edge->minY(), edge->maxY(), edge));
- }
-}
-
-bool FloatPolygon::overlappingEdges(float minY, float maxY, Vector<const FloatPolygonEdge*>& result) const
-{
- Vector<FloatPolygon::EdgeInterval> overlappingEdgeIntervals;
- m_edgeTree.allOverlaps(FloatPolygon::EdgeInterval(minY, maxY, 0), overlappingEdgeIntervals);
- unsigned overlappingEdgeIntervalsSize = overlappingEdgeIntervals.size();
- result.resize(overlappingEdgeIntervalsSize);
- for (unsigned i = 0; i < overlappingEdgeIntervalsSize; ++i) {
- const FloatPolygonEdge* edge = static_cast<const FloatPolygonEdge*>(overlappingEdgeIntervals[i].data());
- ASSERT(edge);
- result[i] = edge;
- }
- return overlappingEdgeIntervalsSize > 0;
-}
-
-static inline float leftSide(const FloatPoint& vertex1, const FloatPoint& vertex2, const FloatPoint& point)
-{
- return ((point.x() - vertex1.x()) * (vertex2.y() - vertex1.y())) - ((vertex2.x() - vertex1.x()) * (point.y() - vertex1.y()));
-}
-
-bool FloatPolygon::containsEvenOdd(const FloatPoint& point) const
-{
- unsigned crossingCount = 0;
- for (unsigned i = 0; i < numberOfEdges(); ++i) {
- const FloatPoint& vertex1 = edgeAt(i).vertex1();
- const FloatPoint& vertex2 = edgeAt(i).vertex2();
- if (isPointOnLineSegment(vertex1, vertex2, point))
- return true;
- if ((vertex1.y() <= point.y() && vertex2.y() > point.y()) || (vertex1.y() > point.y() && vertex2.y() <= point.y())) {
- float vt = (point.y() - vertex1.y()) / (vertex2.y() - vertex1.y());
- if (point.x() < vertex1.x() + vt * (vertex2.x() - vertex1.x()))
- ++crossingCount;
- }
- }
- return crossingCount & 1;
-}
-
-bool FloatPolygon::containsNonZero(const FloatPoint& point) const
-{
- int windingNumber = 0;
- for (unsigned i = 0; i < numberOfEdges(); ++i) {
- const FloatPoint& vertex1 = edgeAt(i).vertex1();
- const FloatPoint& vertex2 = edgeAt(i).vertex2();
- if (isPointOnLineSegment(vertex1, vertex2, point))
- return true;
- if (vertex2.y() < point.y()) {
- if ((vertex1.y() > point.y()) && (leftSide(vertex1, vertex2, point) > 0))
- ++windingNumber;
- } else if (vertex2.y() > point.y()) {
- if ((vertex1.y() <= point.y()) && (leftSide(vertex1, vertex2, point) < 0))
- --windingNumber;
- }
- }
- return windingNumber;
-}
-
-bool FloatPolygon::contains(const FloatPoint& point) const
-{
- if (!m_boundingBox.contains(point))
- return false;
- return (fillRule() == RULE_NONZERO) ? containsNonZero(point) : containsEvenOdd(point);
-}
-
-bool VertexPair::overlapsRect(const FloatRect& rect) const
-{
- bool boundsOverlap = (minX() < rect.maxX()) && (maxX() > rect.x()) && (minY() < rect.maxY()) && (maxY() > rect.y());
- if (!boundsOverlap)
- return false;
-
- float leftSideValues[4] = {
- leftSide(vertex1(), vertex2(), rect.minXMinYCorner()),
- leftSide(vertex1(), vertex2(), rect.maxXMinYCorner()),
- leftSide(vertex1(), vertex2(), rect.minXMaxYCorner()),
- leftSide(vertex1(), vertex2(), rect.maxXMaxYCorner())
- };
-
- int currentLeftSideSign = 0;
- for (unsigned i = 0; i < 4; ++i) {
- if (!leftSideValues[i])
- continue;
- int leftSideSign = leftSideValues[i] > 0 ? 1 : -1;
- if (!currentLeftSideSign)
- currentLeftSideSign = leftSideSign;
- else if (currentLeftSideSign != leftSideSign)
- return true;
- }
-
- return false;
-}
-
-bool VertexPair::intersection(const VertexPair& other, FloatPoint& point) const
-{
- // See: http://paulbourke.net/geometry/pointlineplane/, "Intersection point of two lines in 2 dimensions"
-
- const FloatSize& thisDelta = vertex2() - vertex1();
- const FloatSize& otherDelta = other.vertex2() - other.vertex1();
- float denominator = determinant(thisDelta, otherDelta);
- if (!denominator)
- return false;
-
- // The two line segments: "this" vertex1,vertex2 and "other" vertex1,vertex2, have been defined
- // in parametric form. Each point on the line segment is: vertex1 + u * (vertex2 - vertex1),
- // when 0 <= u <= 1. We're computing the values of u for each line at their intersection point.
-
- const FloatSize& vertex1Delta = vertex1() - other.vertex1();
- float uThisLine = determinant(otherDelta, vertex1Delta) / denominator;
- float uOtherLine = determinant(thisDelta, vertex1Delta) / denominator;
-
- if (uThisLine < 0 || uOtherLine < 0 || uThisLine > 1 || uOtherLine > 1)
- return false;
-
- point = vertex1() + uThisLine * thisDelta;
- return true;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/FloatPolygon.h b/chromium/third_party/WebKit/Source/core/platform/graphics/FloatPolygon.h
deleted file mode 100644
index c2ab193ec91..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/FloatPolygon.h
+++ /dev/null
@@ -1,153 +0,0 @@
-/*
- * Copyright (C) 2012 Adobe Systems Incorporated. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above
- * copyright notice, this list of conditions and the following
- * disclaimer.
- * 2. Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following
- * disclaimer in the documentation and/or other materials
- * provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
- * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
- * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
- * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
- * OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef FloatPolygon_h
-#define FloatPolygon_h
-
-#include "core/platform/PODIntervalTree.h"
-#include "core/platform/graphics/FloatPoint.h"
-#include "core/platform/graphics/FloatRect.h"
-#include "core/platform/graphics/WindRule.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-class FloatPolygonEdge;
-
-// This class is used by PODIntervalTree for debugging.
-#ifndef NDEBUG
-template <class> struct ValueToString;
-#endif
-
-class FloatPolygon {
-public:
- FloatPolygon(PassOwnPtr<Vector<FloatPoint> > vertices, WindRule fillRule);
-
- const FloatPoint& vertexAt(unsigned index) const { return (*m_vertices)[index]; }
- unsigned numberOfVertices() const { return m_vertices->size(); }
-
- WindRule fillRule() const { return m_fillRule; }
-
- const FloatPolygonEdge& edgeAt(unsigned index) const { return m_edges[index]; }
- unsigned numberOfEdges() const { return m_edges.size(); }
-
- FloatRect boundingBox() const { return m_boundingBox; }
- bool overlappingEdges(float minY, float maxY, Vector<const FloatPolygonEdge*>& result) const;
- bool contains(const FloatPoint&) const;
- bool isEmpty() const { return m_empty; }
-
-private:
- typedef PODInterval<float, FloatPolygonEdge*> EdgeInterval;
- typedef PODIntervalTree<float, FloatPolygonEdge*> EdgeIntervalTree;
-
- bool containsNonZero(const FloatPoint&) const;
- bool containsEvenOdd(const FloatPoint&) const;
-
- OwnPtr<Vector<FloatPoint> > m_vertices;
- WindRule m_fillRule;
- FloatRect m_boundingBox;
- bool m_empty;
- Vector<FloatPolygonEdge> m_edges;
- EdgeIntervalTree m_edgeTree; // Each EdgeIntervalTree node stores minY, maxY, and a ("UserData") pointer to a FloatPolygonEdge.
-
-};
-
-class VertexPair {
-public:
- virtual ~VertexPair() { }
-
- virtual const FloatPoint& vertex1() const = 0;
- virtual const FloatPoint& vertex2() const = 0;
-
- float minX() const { return std::min(vertex1().x(), vertex2().x()); }
- float minY() const { return std::min(vertex1().y(), vertex2().y()); }
- float maxX() const { return std::max(vertex1().x(), vertex2().x()); }
- float maxY() const { return std::max(vertex1().y(), vertex2().y()); }
-
- bool overlapsRect(const FloatRect&) const;
- bool intersection(const VertexPair&, FloatPoint&) const;
-};
-
-class FloatPolygonEdge : public VertexPair {
- friend class FloatPolygon;
-public:
- virtual const FloatPoint& vertex1() const OVERRIDE
- {
- ASSERT(m_polygon);
- return m_polygon->vertexAt(m_vertexIndex1);
- }
-
- virtual const FloatPoint& vertex2() const OVERRIDE
- {
- ASSERT(m_polygon);
- return m_polygon->vertexAt(m_vertexIndex2);
- }
-
- const FloatPolygonEdge& previousEdge() const
- {
- ASSERT(m_polygon && m_polygon->numberOfEdges() > 1);
- return m_polygon->edgeAt((m_edgeIndex + m_polygon->numberOfEdges() - 1) % m_polygon->numberOfEdges());
- }
-
- const FloatPolygonEdge& nextEdge() const
- {
- ASSERT(m_polygon && m_polygon->numberOfEdges() > 1);
- return m_polygon->edgeAt((m_edgeIndex + 1) % m_polygon->numberOfEdges());
- }
-
- const FloatPolygon* polygon() const { return m_polygon; }
- unsigned vertexIndex1() const { return m_vertexIndex1; }
- unsigned vertexIndex2() const { return m_vertexIndex2; }
- unsigned edgeIndex() const { return m_edgeIndex; }
-
-private:
- // Edge vertex index1 is less than index2, except the last edge, where index2 is 0. When a polygon edge
- // is defined by 3 or more colinear vertices, index2 can be the the index of the last colinear vertex.
- unsigned m_vertexIndex1;
- unsigned m_vertexIndex2;
- unsigned m_edgeIndex;
- const FloatPolygon* m_polygon;
-};
-
-// These structures are used by PODIntervalTree for debugging.
-#ifndef NDEBUG
-template <> struct ValueToString<float> {
- static String string(const float value) { return String::number(value); }
-};
-
-template<> struct ValueToString<FloatPolygonEdge*> {
- static String string(const FloatPolygonEdge* edge) { return String::format("%p (%f,%f %f,%f)", edge, edge->vertex1().x(), edge->vertex1().y(), edge->vertex2().x(), edge->vertex2().y()); }
-};
-#endif
-
-} // namespace WebCore
-
-#endif // FloatPolygon_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/FloatQuad.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/FloatQuad.cpp
deleted file mode 100644
index 0a7e09284f4..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/FloatQuad.cpp
+++ /dev/null
@@ -1,236 +0,0 @@
-/*
- * Copyright (C) 2008 Apple Inc. All rights reserved.
- * Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies)
- * Copyright (C) 2013 Xidorn Quan (quanxunzhen@gmail.com)
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/FloatQuad.h"
-
-#include <algorithm>
-#include <limits>
-
-using namespace std;
-
-namespace WebCore {
-
-static inline float min4(float a, float b, float c, float d)
-{
- return min(min(a, b), min(c, d));
-}
-
-static inline float max4(float a, float b, float c, float d)
-{
- return max(max(a, b), max(c, d));
-}
-
-inline float dot(const FloatSize& a, const FloatSize& b)
-{
- return a.width() * b.width() + a.height() * b.height();
-}
-
-inline float determinant(const FloatSize& a, const FloatSize& b)
-{
- return a.width() * b.height() - a.height() * b.width();
-}
-
-inline bool isPointInTriangle(const FloatPoint& p, const FloatPoint& t1, const FloatPoint& t2, const FloatPoint& t3)
-{
- // Compute vectors
- FloatSize v0 = t3 - t1;
- FloatSize v1 = t2 - t1;
- FloatSize v2 = p - t1;
-
- // Compute dot products
- float dot00 = dot(v0, v0);
- float dot01 = dot(v0, v1);
- float dot02 = dot(v0, v2);
- float dot11 = dot(v1, v1);
- float dot12 = dot(v1, v2);
-
- // Compute barycentric coordinates
- float invDenom = 1.0f / (dot00 * dot11 - dot01 * dot01);
- float u = (dot11 * dot02 - dot01 * dot12) * invDenom;
- float v = (dot00 * dot12 - dot01 * dot02) * invDenom;
-
- // Check if point is in triangle
- return (u >= 0) && (v >= 0) && (u + v <= 1);
-}
-
-FloatRect FloatQuad::boundingBox() const
-{
- float left = min4(m_p1.x(), m_p2.x(), m_p3.x(), m_p4.x());
- float top = min4(m_p1.y(), m_p2.y(), m_p3.y(), m_p4.y());
-
- float right = max4(m_p1.x(), m_p2.x(), m_p3.x(), m_p4.x());
- float bottom = max4(m_p1.y(), m_p2.y(), m_p3.y(), m_p4.y());
-
- return FloatRect(left, top, right - left, bottom - top);
-}
-
-static inline bool withinEpsilon(float a, float b)
-{
- return fabs(a - b) < numeric_limits<float>::epsilon();
-}
-
-bool FloatQuad::isRectilinear() const
-{
- return (withinEpsilon(m_p1.x(), m_p2.x()) && withinEpsilon(m_p2.y(), m_p3.y()) && withinEpsilon(m_p3.x(), m_p4.x()) && withinEpsilon(m_p4.y(), m_p1.y()))
- || (withinEpsilon(m_p1.y(), m_p2.y()) && withinEpsilon(m_p2.x(), m_p3.x()) && withinEpsilon(m_p3.y(), m_p4.y()) && withinEpsilon(m_p4.x(), m_p1.x()));
-}
-
-bool FloatQuad::containsPoint(const FloatPoint& p) const
-{
- return isPointInTriangle(p, m_p1, m_p2, m_p3) || isPointInTriangle(p, m_p1, m_p3, m_p4);
-}
-
-// Note that we only handle convex quads here.
-bool FloatQuad::containsQuad(const FloatQuad& other) const
-{
- return containsPoint(other.p1()) && containsPoint(other.p2()) && containsPoint(other.p3()) && containsPoint(other.p4());
-}
-
-static inline FloatPoint rightMostCornerToVector(const FloatRect& rect, const FloatSize& vector)
-{
- // Return the corner of the rectangle that if it is to the left of the vector
- // would mean all of the rectangle is to the left of the vector.
- // The vector here represents the side between two points in a clockwise convex polygon.
- //
- // Q XXX
- // QQQ XXX If the lower left corner of X is left of the vector that goes from the top corner of Q to
- // QQQ the right corner of Q, then all of X is left of the vector, and intersection impossible.
- // Q
- //
- FloatPoint point;
- if (vector.width() >= 0)
- point.setY(rect.maxY());
- else
- point.setY(rect.y());
- if (vector.height() >= 0)
- point.setX(rect.x());
- else
- point.setX(rect.maxX());
- return point;
-}
-
-bool FloatQuad::intersectsRect(const FloatRect& rect) const
-{
- // For each side of the quad clockwise we check if the rectangle is to the left of it
- // since only content on the right can onlap with the quad.
- // This only works if the quad is convex.
- FloatSize v1, v2, v3, v4;
-
- // Ensure we use clockwise vectors.
- if (!isCounterclockwise()) {
- v1 = m_p2 - m_p1;
- v2 = m_p3 - m_p2;
- v3 = m_p4 - m_p3;
- v4 = m_p1 - m_p4;
- } else {
- v1 = m_p4 - m_p1;
- v2 = m_p1 - m_p2;
- v3 = m_p2 - m_p3;
- v4 = m_p3 - m_p4;
- }
-
- FloatPoint p = rightMostCornerToVector(rect, v1);
- if (determinant(v1, p - m_p1) < 0)
- return false;
-
- p = rightMostCornerToVector(rect, v2);
- if (determinant(v2, p - m_p2) < 0)
- return false;
-
- p = rightMostCornerToVector(rect, v3);
- if (determinant(v3, p - m_p3) < 0)
- return false;
-
- p = rightMostCornerToVector(rect, v4);
- if (determinant(v4, p - m_p4) < 0)
- return false;
-
- // If not all of the rectangle is outside one of the quad's four sides, then that means at least
- // a part of the rectangle is overlapping the quad.
- return true;
-}
-
-// Tests whether the line is contained by or intersected with the circle.
-static inline bool lineIntersectsCircle(const FloatPoint& center, float radius, const FloatPoint& p0, const FloatPoint& p1)
-{
- float x0 = p0.x() - center.x(), y0 = p0.y() - center.y();
- float x1 = p1.x() - center.x(), y1 = p1.y() - center.y();
- float radius2 = radius * radius;
- if ((x0 * x0 + y0 * y0) <= radius2 || (x1 * x1 + y1 * y1) <= radius2)
- return true;
- if (p0 == p1)
- return false;
-
- float a = y0 - y1;
- float b = x1 - x0;
- float c = x0 * y1 - x1 * y0;
- float distance2 = c * c / (a * a + b * b);
- // If distance between the center point and the line > the radius,
- // the line doesn't cross (or is contained by) the ellipse.
- if (distance2 > radius2)
- return false;
-
- // The nearest point on the line is between p0 and p1?
- float x = - a * c / (a * a + b * b);
- float y = - b * c / (a * a + b * b);
- return (((x0 <= x && x <= x1) || (x0 >= x && x >= x1))
- && ((y0 <= y && y <= y1) || (y1 <= y && y <= y0)));
-}
-
-bool FloatQuad::intersectsCircle(const FloatPoint& center, float radius) const
-{
- return containsPoint(center) // The circle may be totally contained by the quad.
- || lineIntersectsCircle(center, radius, m_p1, m_p2)
- || lineIntersectsCircle(center, radius, m_p2, m_p3)
- || lineIntersectsCircle(center, radius, m_p3, m_p4)
- || lineIntersectsCircle(center, radius, m_p4, m_p1);
-}
-
-bool FloatQuad::intersectsEllipse(const FloatPoint& center, const FloatSize& radii) const
-{
- // Transform the ellipse to an origin-centered circle whose radius is the product of major radius and minor radius.
- // Here we apply the same transformation to the quad.
- FloatQuad transformedQuad(*this);
- transformedQuad.move(-center.x(), -center.y());
- transformedQuad.scale(radii.height(), radii.width());
-
- FloatPoint originPoint;
- return transformedQuad.intersectsCircle(originPoint, radii.height() * radii.width());
-
-}
-
-bool FloatQuad::isCounterclockwise() const
-{
- // Return if the two first vectors are turning clockwise. If the quad is convex then all following vectors will turn the same way.
- return determinant(m_p2 - m_p1, m_p3 - m_p2) < 0;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/FloatQuad.h b/chromium/third_party/WebKit/Source/core/platform/graphics/FloatQuad.h
deleted file mode 100644
index 3a8e822712b..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/FloatQuad.h
+++ /dev/null
@@ -1,180 +0,0 @@
-/*
- * Copyright (C) 2008 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef FloatQuad_h
-#define FloatQuad_h
-
-#include "core/platform/graphics/FloatPoint.h"
-#include "core/platform/graphics/FloatRect.h"
-#include "core/platform/graphics/IntRect.h"
-
-namespace WebCore {
-
-// A FloatQuad is a collection of 4 points, often representing the result of
-// mapping a rectangle through transforms. When initialized from a rect, the
-// points are in clockwise order from top left.
-class FloatQuad {
-public:
- FloatQuad()
- {
- }
-
- FloatQuad(const FloatPoint& p1, const FloatPoint& p2, const FloatPoint& p3, const FloatPoint& p4)
- : m_p1(p1)
- , m_p2(p2)
- , m_p3(p3)
- , m_p4(p4)
- {
- }
-
- FloatQuad(const FloatRect& inRect)
- : m_p1(inRect.location())
- , m_p2(inRect.maxX(), inRect.y())
- , m_p3(inRect.maxX(), inRect.maxY())
- , m_p4(inRect.x(), inRect.maxY())
- {
- }
-
- FloatPoint p1() const { return m_p1; }
- FloatPoint p2() const { return m_p2; }
- FloatPoint p3() const { return m_p3; }
- FloatPoint p4() const { return m_p4; }
-
- void setP1(const FloatPoint& p) { m_p1 = p; }
- void setP2(const FloatPoint& p) { m_p2 = p; }
- void setP3(const FloatPoint& p) { m_p3 = p; }
- void setP4(const FloatPoint& p) { m_p4 = p; }
-
- // isEmpty tests that the bounding box is empty. This will not identify
- // "slanted" empty quads.
- bool isEmpty() const { return boundingBox().isEmpty(); }
-
- // Tests whether this quad can be losslessly represented by a FloatRect,
- // that is, if two edges are parallel to the x-axis and the other two
- // are parallel to the y-axis. If this method returns true, the
- // corresponding FloatRect can be retrieved with boundingBox().
- bool isRectilinear() const;
-
- // Tests whether the given point is inside, or on an edge or corner of this quad.
- bool containsPoint(const FloatPoint&) const;
-
- // Tests whether the four corners of other are inside, or coincident with the sides of this quad.
- // Note that this only works for convex quads, but that includes all quads that originate
- // from transformed rects.
- bool containsQuad(const FloatQuad&) const;
-
- // Tests whether any part of the rectangle intersects with this quad.
- // This only works for convex quads.
- bool intersectsRect(const FloatRect&) const;
-
- // Test whether any part of the circle/ellipse intersects with this quad.
- // Note that these two functions only work for convex quads.
- bool intersectsCircle(const FloatPoint& center, float radius) const;
- bool intersectsEllipse(const FloatPoint& center, const FloatSize& radii) const;
-
- // The center of the quad. If the quad is the result of a affine-transformed rectangle this is the same as the original center transformed.
- FloatPoint center() const
- {
- return FloatPoint((m_p1.x() + m_p2.x() + m_p3.x() + m_p4.x()) / 4.0,
- (m_p1.y() + m_p2.y() + m_p3.y() + m_p4.y()) / 4.0);
- }
-
- FloatRect boundingBox() const;
- IntRect enclosingBoundingBox() const
- {
- return enclosingIntRect(boundingBox());
- }
-
- void move(const FloatSize& offset)
- {
- m_p1 += offset;
- m_p2 += offset;
- m_p3 += offset;
- m_p4 += offset;
- }
-
- void move(float dx, float dy)
- {
- m_p1.move(dx, dy);
- m_p2.move(dx, dy);
- m_p3.move(dx, dy);
- m_p4.move(dx, dy);
- }
-
- void scale(float dx, float dy)
- {
- m_p1.scale(dx, dy);
- m_p2.scale(dx, dy);
- m_p3.scale(dx, dy);
- m_p4.scale(dx, dy);
- }
-
- // Tests whether points are in clock-wise, or counter clock-wise order.
- // Note that output is undefined when all points are colinear.
- bool isCounterclockwise() const;
-
-private:
- FloatPoint m_p1;
- FloatPoint m_p2;
- FloatPoint m_p3;
- FloatPoint m_p4;
-};
-
-inline FloatQuad& operator+=(FloatQuad& a, const FloatSize& b)
-{
- a.move(b);
- return a;
-}
-
-inline FloatQuad& operator-=(FloatQuad& a, const FloatSize& b)
-{
- a.move(-b.width(), -b.height());
- return a;
-}
-
-inline bool operator==(const FloatQuad& a, const FloatQuad& b)
-{
- return a.p1() == b.p1() &&
- a.p2() == b.p2() &&
- a.p3() == b.p3() &&
- a.p4() == b.p4();
-}
-
-inline bool operator!=(const FloatQuad& a, const FloatQuad& b)
-{
- return a.p1() != b.p1() ||
- a.p2() != b.p2() ||
- a.p3() != b.p3() ||
- a.p4() != b.p4();
-}
-
-} // namespace WebCore
-
-
-#endif // FloatQuad_h
-
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/FloatRect.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/FloatRect.cpp
deleted file mode 100644
index d37da05921c..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/FloatRect.cpp
+++ /dev/null
@@ -1,272 +0,0 @@
-/*
- * Copyright (C) 2003, 2006, 2007 Apple Inc. All rights reserved.
- * Copyright (C) 2005 Nokia. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/FloatRect.h"
-
-#include "core/platform/FloatConversion.h"
-#include "core/platform/graphics/IntRect.h"
-#include "core/platform/graphics/LayoutRect.h"
-#include "third_party/skia/include/core/SkRect.h"
-#include "wtf/MathExtras.h"
-
-#include <algorithm>
-#include <math.h>
-
-using std::max;
-using std::min;
-
-namespace WebCore {
-
-FloatRect::FloatRect(const IntRect& r) : m_location(r.location()), m_size(r.size())
-{
-}
-
-FloatRect::FloatRect(const LayoutRect& r) : m_location(r.location()), m_size(r.size())
-{
-}
-
-FloatRect::FloatRect(const SkRect& r) : m_location(r.fLeft, r.fTop), m_size(r.width(), r.height())
-{
-}
-
-FloatRect FloatRect::narrowPrecision(double x, double y, double width, double height)
-{
- return FloatRect(narrowPrecisionToFloat(x), narrowPrecisionToFloat(y), narrowPrecisionToFloat(width), narrowPrecisionToFloat(height));
-}
-
-bool FloatRect::isExpressibleAsIntRect() const
-{
- return isWithinIntRange(x()) && isWithinIntRange(y())
- && isWithinIntRange(width()) && isWithinIntRange(height())
- && isWithinIntRange(maxX()) && isWithinIntRange(maxY());
-}
-
-bool FloatRect::intersects(const FloatRect& other) const
-{
- // Checking emptiness handles negative widths as well as zero.
- return !isEmpty() && !other.isEmpty()
- && x() < other.maxX() && other.x() < maxX()
- && y() < other.maxY() && other.y() < maxY();
-}
-
-bool FloatRect::contains(const FloatRect& other) const
-{
- return x() <= other.x() && maxX() >= other.maxX()
- && y() <= other.y() && maxY() >= other.maxY();
-}
-
-bool FloatRect::contains(const FloatPoint& point, ContainsMode containsMode) const
-{
- if (containsMode == InsideOrOnStroke)
- return contains(point.x(), point.y());
- return x() < point.x() && maxX() > point.x() && y() < point.y() && maxY() > point.y();
-}
-
-void FloatRect::intersect(const FloatRect& other)
-{
- float l = max(x(), other.x());
- float t = max(y(), other.y());
- float r = min(maxX(), other.maxX());
- float b = min(maxY(), other.maxY());
-
- // Return a clean empty rectangle for non-intersecting cases.
- if (l >= r || t >= b) {
- l = 0;
- t = 0;
- r = 0;
- b = 0;
- }
-
- setLocationAndSizeFromEdges(l, t, r, b);
-}
-
-void FloatRect::unite(const FloatRect& other)
-{
- // Handle empty special cases first.
- if (other.isEmpty())
- return;
- if (isEmpty()) {
- *this = other;
- return;
- }
-
- uniteEvenIfEmpty(other);
-}
-
-void FloatRect::uniteEvenIfEmpty(const FloatRect& other)
-{
- float minX = min(x(), other.x());
- float minY = min(y(), other.y());
- float maxX = max(this->maxX(), other.maxX());
- float maxY = max(this->maxY(), other.maxY());
-
- setLocationAndSizeFromEdges(minX, minY, maxX, maxY);
-}
-
-void FloatRect::uniteIfNonZero(const FloatRect& other)
-{
- // Handle empty special cases first.
- if (other.isZero())
- return;
- if (isZero()) {
- *this = other;
- return;
- }
-
- uniteEvenIfEmpty(other);
-}
-
-void FloatRect::extend(const FloatPoint& p)
-{
- float minX = min(x(), p.x());
- float minY = min(y(), p.y());
- float maxX = max(this->maxX(), p.x());
- float maxY = max(this->maxY(), p.y());
-
- setLocationAndSizeFromEdges(minX, minY, maxX, maxY);
-}
-
-void FloatRect::scale(float sx, float sy)
-{
- m_location.setX(x() * sx);
- m_location.setY(y() * sy);
- m_size.setWidth(width() * sx);
- m_size.setHeight(height() * sy);
-}
-
-FloatRect unionRect(const Vector<FloatRect>& rects)
-{
- FloatRect result;
-
- size_t count = rects.size();
- for (size_t i = 0; i < count; ++i)
- result.unite(rects[i]);
-
- return result;
-}
-
-void FloatRect::fitToPoints(const FloatPoint& p0, const FloatPoint& p1)
-{
- float left = min(p0.x(), p1.x());
- float top = min(p0.y(), p1.y());
- float right = max(p0.x(), p1.x());
- float bottom = max(p0.y(), p1.y());
-
- setLocationAndSizeFromEdges(left, top, right, bottom);
-}
-
-namespace {
-// Helpers for 3- and 4-way max and min.
-
-template <typename T>
-T min3(const T& v1, const T& v2, const T& v3)
-{
- return min(min(v1, v2), v3);
-}
-
-template <typename T>
-T max3(const T& v1, const T& v2, const T& v3)
-{
- return max(max(v1, v2), v3);
-}
-
-template <typename T>
-T min4(const T& v1, const T& v2, const T& v3, const T& v4)
-{
- return min(min(v1, v2), min(v3, v4));
-}
-
-template <typename T>
-T max4(const T& v1, const T& v2, const T& v3, const T& v4)
-{
- return max(max(v1, v2), max(v3, v4));
-}
-
-} // anonymous namespace
-
-void FloatRect::fitToPoints(const FloatPoint& p0, const FloatPoint& p1, const FloatPoint& p2)
-{
- float left = min3(p0.x(), p1.x(), p2.x());
- float top = min3(p0.y(), p1.y(), p2.y());
- float right = max3(p0.x(), p1.x(), p2.x());
- float bottom = max3(p0.y(), p1.y(), p2.y());
-
- setLocationAndSizeFromEdges(left, top, right, bottom);
-}
-
-void FloatRect::fitToPoints(const FloatPoint& p0, const FloatPoint& p1, const FloatPoint& p2, const FloatPoint& p3)
-{
- float left = min4(p0.x(), p1.x(), p2.x(), p3.x());
- float top = min4(p0.y(), p1.y(), p2.y(), p3.y());
- float right = max4(p0.x(), p1.x(), p2.x(), p3.x());
- float bottom = max4(p0.y(), p1.y(), p2.y(), p3.y());
-
- setLocationAndSizeFromEdges(left, top, right, bottom);
-}
-
-FloatRect::operator SkRect() const
-{
- SkRect rect = { x(), y(), maxX(), maxY() };
- return rect;
-}
-
-IntRect enclosingIntRect(const FloatRect& rect)
-{
- IntPoint location = flooredIntPoint(rect.minXMinYCorner());
- IntPoint maxPoint = ceiledIntPoint(rect.maxXMaxYCorner());
-
- return IntRect(location, maxPoint - location);
-}
-
-IntRect enclosedIntRect(const FloatRect& rect)
-{
- IntPoint location = ceiledIntPoint(rect.minXMinYCorner());
- IntPoint maxPoint = flooredIntPoint(rect.maxXMaxYCorner());
- IntSize size = maxPoint - location;
- size.clampNegativeToZero();
-
- return IntRect(location, size);
-}
-
-IntRect roundedIntRect(const FloatRect& rect)
-{
- return IntRect(roundedIntPoint(rect.location()), roundedIntSize(rect.size()));
-}
-
-FloatRect mapRect(const FloatRect& r, const FloatRect& srcRect, const FloatRect& destRect)
-{
- if (srcRect.width() == 0 || srcRect.height() == 0)
- return FloatRect();
-
- float widthScale = destRect.width() / srcRect.width();
- float heightScale = destRect.height() / srcRect.height();
- return FloatRect(destRect.x() + (r.x() - srcRect.x()) * widthScale,
- destRect.y() + (r.y() - srcRect.y()) * heightScale,
- r.width() * widthScale, r.height() * heightScale);
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/FloatRect.h b/chromium/third_party/WebKit/Source/core/platform/graphics/FloatRect.h
deleted file mode 100644
index e0b631f79de..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/FloatRect.h
+++ /dev/null
@@ -1,239 +0,0 @@
-/*
- * Copyright (C) 2003, 2006, 2007 Apple Inc. All rights reserved.
- * Copyright (C) 2005 Nokia. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef FloatRect_h
-#define FloatRect_h
-
-#include "core/platform/graphics/FloatPoint.h"
-#include "wtf/Vector.h"
-
-#if OS(MACOSX)
-typedef struct CGRect CGRect;
-#ifdef NSGEOMETRY_TYPES_SAME_AS_CGGEOMETRY_TYPES
-typedef struct CGRect NSRect;
-#else
-typedef struct _NSRect NSRect;
-#endif
-#endif
-
-struct SkRect;
-
-namespace WebCore {
-
-class LayoutRect;
-class IntRect;
-class IntPoint;
-
-class FloatRect {
-public:
- enum ContainsMode {
- InsideOrOnStroke,
- InsideButNotOnStroke
- };
-
- FloatRect() { }
- FloatRect(const FloatPoint& location, const FloatSize& size)
- : m_location(location), m_size(size) { }
- FloatRect(float x, float y, float width, float height)
- : m_location(FloatPoint(x, y)), m_size(FloatSize(width, height)) { }
- FloatRect(const IntRect&);
- FloatRect(const LayoutRect&);
- FloatRect(const SkRect&);
-
- static FloatRect narrowPrecision(double x, double y, double width, double height);
-
- FloatPoint location() const { return m_location; }
- FloatSize size() const { return m_size; }
-
- void setLocation(const FloatPoint& location) { m_location = location; }
- void setSize(const FloatSize& size) { m_size = size; }
-
- float x() const { return m_location.x(); }
- float y() const { return m_location.y(); }
- float maxX() const { return x() + width(); }
- float maxY() const { return y() + height(); }
- float width() const { return m_size.width(); }
- float height() const { return m_size.height(); }
-
- void setX(float x) { m_location.setX(x); }
- void setY(float y) { m_location.setY(y); }
- void setWidth(float width) { m_size.setWidth(width); }
- void setHeight(float height) { m_size.setHeight(height); }
-
- bool isEmpty() const { return m_size.isEmpty(); }
- bool isZero() const { return m_size.isZero(); }
- bool isExpressibleAsIntRect() const;
-
- FloatPoint center() const { return FloatPoint(x() + width() / 2, y() + height() / 2); }
-
- void move(const FloatSize& delta) { m_location += delta; }
- void moveBy(const FloatPoint& delta) { m_location.move(delta.x(), delta.y()); }
- void move(float dx, float dy) { m_location.move(dx, dy); }
-
- void expand(const FloatSize& size) { m_size += size; }
- void expand(float dw, float dh) { m_size.expand(dw, dh); }
- void contract(const FloatSize& size) { m_size -= size; }
- void contract(float dw, float dh) { m_size.expand(-dw, -dh); }
-
- void shiftXEdgeTo(float edge)
- {
- float delta = edge - x();
- setX(edge);
- setWidth(std::max(0.0f, width() - delta));
- }
- void shiftMaxXEdgeTo(float edge)
- {
- float delta = edge - maxX();
- setWidth(std::max(0.0f, width() + delta));
- }
- void shiftYEdgeTo(float edge)
- {
- float delta = edge - y();
- setY(edge);
- setHeight(std::max(0.0f, height() - delta));
- }
- void shiftMaxYEdgeTo(float edge)
- {
- float delta = edge - maxY();
- setHeight(std::max(0.0f, height() + delta));
- }
-
- FloatPoint minXMinYCorner() const { return m_location; } // typically topLeft
- FloatPoint maxXMinYCorner() const { return FloatPoint(m_location.x() + m_size.width(), m_location.y()); } // typically topRight
- FloatPoint minXMaxYCorner() const { return FloatPoint(m_location.x(), m_location.y() + m_size.height()); } // typically bottomLeft
- FloatPoint maxXMaxYCorner() const { return FloatPoint(m_location.x() + m_size.width(), m_location.y() + m_size.height()); } // typically bottomRight
-
- bool intersects(const FloatRect&) const;
- bool contains(const FloatRect&) const;
- bool contains(const FloatPoint&, ContainsMode = InsideOrOnStroke) const;
-
- void intersect(const FloatRect&);
- void unite(const FloatRect&);
- void uniteEvenIfEmpty(const FloatRect&);
- void uniteIfNonZero(const FloatRect&);
- void extend(const FloatPoint&);
-
- // Note, this doesn't match what IntRect::contains(IntPoint&) does; the int version
- // is really checking for containment of 1x1 rect, but that doesn't make sense with floats.
- bool contains(float px, float py) const
- { return px >= x() && px <= maxX() && py >= y() && py <= maxY(); }
-
- void inflateX(float dx) {
- m_location.setX(m_location.x() - dx);
- m_size.setWidth(m_size.width() + dx + dx);
- }
- void inflateY(float dy) {
- m_location.setY(m_location.y() - dy);
- m_size.setHeight(m_size.height() + dy + dy);
- }
- void inflate(float d) { inflateX(d); inflateY(d); }
- void scale(float s) { scale(s, s); }
- void scale(float sx, float sy);
-
- FloatRect transposedRect() const { return FloatRect(m_location.transposedPoint(), m_size.transposedSize()); }
-
- // Re-initializes this rectangle to fit the sets of passed points.
- void fitToPoints(const FloatPoint& p0, const FloatPoint& p1);
- void fitToPoints(const FloatPoint& p0, const FloatPoint& p1, const FloatPoint& p2);
- void fitToPoints(const FloatPoint& p0, const FloatPoint& p1, const FloatPoint& p2, const FloatPoint& p3);
-
-#if OS(MACOSX)
- FloatRect(const CGRect&);
- operator CGRect() const;
-#if !defined(NSGEOMETRY_TYPES_SAME_AS_CGGEOMETRY_TYPES)
- FloatRect(const NSRect&);
- operator NSRect() const;
-#endif
-#endif
-
- operator SkRect() const;
-
-private:
- FloatPoint m_location;
- FloatSize m_size;
-
- void setLocationAndSizeFromEdges(float left, float top, float right, float bottom)
- {
- m_location.set(left, top);
- m_size.setWidth(right - left);
- m_size.setHeight(bottom - top);
- }
-};
-
-inline FloatRect intersection(const FloatRect& a, const FloatRect& b)
-{
- FloatRect c = a;
- c.intersect(b);
- return c;
-}
-
-inline FloatRect unionRect(const FloatRect& a, const FloatRect& b)
-{
- FloatRect c = a;
- c.unite(b);
- return c;
-}
-
-FloatRect unionRect(const Vector<FloatRect>&);
-
-inline FloatRect& operator+=(FloatRect& a, const FloatRect& b)
-{
- a.move(b.x(), b.y());
- a.setWidth(a.width() + b.width());
- a.setHeight(a.height() + b.height());
- return a;
-}
-
-inline FloatRect operator+(const FloatRect& a, const FloatRect& b)
-{
- FloatRect c = a;
- c += b;
- return c;
-}
-
-inline bool operator==(const FloatRect& a, const FloatRect& b)
-{
- return a.location() == b.location() && a.size() == b.size();
-}
-
-inline bool operator!=(const FloatRect& a, const FloatRect& b)
-{
- return a.location() != b.location() || a.size() != b.size();
-}
-
-IntRect enclosingIntRect(const FloatRect&);
-
-// Returns a valid IntRect contained within the given FloatRect.
-IntRect enclosedIntRect(const FloatRect&);
-
-IntRect roundedIntRect(const FloatRect&);
-
-// Map rect r from srcRect to an equivalent rect in destRect.
-FloatRect mapRect(const FloatRect& r, const FloatRect& srcRect, const FloatRect& destRect);
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/FloatSize.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/FloatSize.cpp
deleted file mode 100644
index f3283b259ae..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/FloatSize.cpp
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Copyright (C) 2003, 2006 Apple Computer, Inc. All rights reserved.
- * Copyright (C) 2005 Nokia. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/FloatSize.h"
-
-#include <math.h>
-#include <limits>
-#include "core/platform/FloatConversion.h"
-#include "core/platform/graphics/IntSize.h"
-#include "core/platform/graphics/LayoutSize.h"
-
-using namespace std;
-
-namespace WebCore {
-
-FloatSize::FloatSize(const IntSize& size) : m_width(size.width()), m_height(size.height())
-{
-}
-
-FloatSize::FloatSize(const LayoutSize& size) : m_width(size.width()), m_height(size.height())
-{
-}
-
-float FloatSize::diagonalLength() const
-{
- return sqrtf(diagonalLengthSquared());
-}
-
-bool FloatSize::isZero() const
-{
- return fabs(m_width) < numeric_limits<float>::epsilon() && fabs(m_height) < numeric_limits<float>::epsilon();
-}
-
-bool FloatSize::isExpressibleAsIntSize() const
-{
- return isWithinIntRange(m_width) && isWithinIntRange(m_height);
-}
-
-FloatSize FloatSize::narrowPrecision(double width, double height)
-{
- return FloatSize(narrowPrecisionToFloat(width), narrowPrecisionToFloat(height));
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/FloatSize.h b/chromium/third_party/WebKit/Source/core/platform/graphics/FloatSize.h
deleted file mode 100644
index 320fa67038c..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/FloatSize.h
+++ /dev/null
@@ -1,192 +0,0 @@
-/*
- * Copyright (C) 2003, 2006 Apple Computer, Inc. All rights reserved.
- * Copyright (C) 2005 Nokia. All rights reserved.
- * 2008 Eric Seidel <eric@webkit.org>
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef FloatSize_h
-#define FloatSize_h
-
-#include "core/platform/graphics/IntPoint.h"
-#include "wtf/MathExtras.h"
-
-
-#if OS(MACOSX)
-typedef struct CGSize CGSize;
-
-#ifdef NSGEOMETRY_TYPES_SAME_AS_CGGEOMETRY_TYPES
-typedef struct CGSize NSSize;
-#else
-typedef struct _NSSize NSSize;
-#endif
-#endif
-
-namespace WebCore {
-
-class IntSize;
-class LayoutSize;
-
-class FloatSize {
-public:
- FloatSize() : m_width(0), m_height(0) { }
- FloatSize(float width, float height) : m_width(width), m_height(height) { }
- FloatSize(const IntSize&);
- FloatSize(const LayoutSize&);
-
- static FloatSize narrowPrecision(double width, double height);
-
- float width() const { return m_width; }
- float height() const { return m_height; }
-
- void setWidth(float width) { m_width = width; }
- void setHeight(float height) { m_height = height; }
-
- bool isEmpty() const { return m_width <= 0 || m_height <= 0; }
- bool isZero() const;
- bool isExpressibleAsIntSize() const;
-
- float aspectRatio() const { return m_width / m_height; }
-
- void expand(float width, float height)
- {
- m_width += width;
- m_height += height;
- }
-
- void scale(float s) { scale(s, s); }
-
- void scale(float scaleX, float scaleY)
- {
- m_width *= scaleX;
- m_height *= scaleY;
- }
-
- FloatSize expandedTo(const FloatSize& other) const
- {
- return FloatSize(m_width > other.m_width ? m_width : other.m_width,
- m_height > other.m_height ? m_height : other.m_height);
- }
-
- FloatSize shrunkTo(const FloatSize& other) const
- {
- return FloatSize(m_width < other.m_width ? m_width : other.m_width,
- m_height < other.m_height ? m_height : other.m_height);
- }
-
- float diagonalLength() const;
- float diagonalLengthSquared() const
- {
- return m_width * m_width + m_height * m_height;
- }
-
- FloatSize transposedSize() const
- {
- return FloatSize(m_height, m_width);
- }
-
-#if OS(MACOSX)
- explicit FloatSize(const CGSize&); // don't do this implicitly since it's lossy
- operator CGSize() const;
-#if !defined(NSGEOMETRY_TYPES_SAME_AS_CGGEOMETRY_TYPES)
- explicit FloatSize(const NSSize &); // don't do this implicitly since it's lossy
- operator NSSize() const;
-#endif
-#endif
-
-private:
- float m_width, m_height;
-};
-
-inline FloatSize& operator+=(FloatSize& a, const FloatSize& b)
-{
- a.setWidth(a.width() + b.width());
- a.setHeight(a.height() + b.height());
- return a;
-}
-
-inline FloatSize& operator-=(FloatSize& a, const FloatSize& b)
-{
- a.setWidth(a.width() - b.width());
- a.setHeight(a.height() - b.height());
- return a;
-}
-
-inline FloatSize operator+(const FloatSize& a, const FloatSize& b)
-{
- return FloatSize(a.width() + b.width(), a.height() + b.height());
-}
-
-inline FloatSize operator-(const FloatSize& a, const FloatSize& b)
-{
- return FloatSize(a.width() - b.width(), a.height() - b.height());
-}
-
-inline FloatSize operator-(const FloatSize& size)
-{
- return FloatSize(-size.width(), -size.height());
-}
-
-inline FloatSize operator*(const FloatSize& a, const float b)
-{
- return FloatSize(a.width() * b, a.height() * b);
-}
-
-inline FloatSize operator*(const float a, const FloatSize& b)
-{
- return FloatSize(a * b.width(), a * b.height());
-}
-
-inline bool operator==(const FloatSize& a, const FloatSize& b)
-{
- return a.width() == b.width() && a.height() == b.height();
-}
-
-inline bool operator!=(const FloatSize& a, const FloatSize& b)
-{
- return a.width() != b.width() || a.height() != b.height();
-}
-
-inline IntSize roundedIntSize(const FloatSize& p)
-{
- return IntSize(clampToInteger(roundf(p.width())), clampToInteger(roundf(p.height())));
-}
-
-inline IntSize flooredIntSize(const FloatSize& p)
-{
- return IntSize(clampToInteger(floorf(p.width())), clampToInteger(floorf(p.height())));
-}
-
-inline IntSize expandedIntSize(const FloatSize& p)
-{
- return IntSize(clampToInteger(ceilf(p.width())), clampToInteger(ceilf(p.height())));
-}
-
-inline IntPoint flooredIntPoint(const FloatSize& p)
-{
- return IntPoint(clampToInteger(floorf(p.width())), clampToInteger(floorf(p.height())));
-}
-
-} // namespace WebCore
-
-#endif // FloatSize_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/Font.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/Font.cpp
deleted file mode 100644
index bdf6843bace..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/Font.cpp
+++ /dev/null
@@ -1,704 +0,0 @@
-/*
- * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
- * (C) 1999 Antti Koivisto (koivisto@kde.org)
- * (C) 2000 Dirk Mueller (mueller@kde.org)
- * Copyright (C) 2003, 2006, 2010, 2011 Apple Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#include "config.h"
-#include "core/platform/graphics/Font.h"
-
-#include "core/platform/graphics/FloatRect.h"
-#include "core/platform/graphics/TextRun.h"
-#include "core/platform/graphics/WidthIterator.h"
-#include "core/platform/text/transcoder/FontTranscoder.h"
-#include "wtf/MainThread.h"
-#include "wtf/MathExtras.h"
-#include "wtf/StdLibExtras.h"
-#include "wtf/UnusedParam.h"
-#include "wtf/text/StringBuilder.h"
-
-using namespace WTF;
-using namespace Unicode;
-
-namespace WTF {
-
-// allow compilation of OwnPtr<TextLayout> in source files that don't have access to the TextLayout class definition
-template <> void deleteOwnedPtr<WebCore::TextLayout>(WebCore::TextLayout* ptr)
-{
- WebCore::Font::deleteLayout(ptr);
-}
-
-}
-
-namespace WebCore {
-
-const uint8_t Font::s_roundingHackCharacterTable[256] = {
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 /*\t*/, 1 /*\n*/, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 1 /*space*/, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 /*-*/, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 /*?*/,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 1 /*no-break space*/, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
-};
-
-static const UChar32 cjkIsolatedSymbolsArray[] = {
- // 0x2C7 Caron, Mandarin Chinese 3rd Tone
- 0x2C7,
- // 0x2CA Modifier Letter Acute Accent, Mandarin Chinese 2nd Tone
- 0x2CA,
- // 0x2CB Modifier Letter Grave Access, Mandarin Chinese 4th Tone
- 0x2CB,
- // 0x2D9 Dot Above, Mandarin Chinese 5th Tone
- 0x2D9,
- 0x2020, 0x2021, 0x2030, 0x203B, 0x203C, 0x2042, 0x2047, 0x2048, 0x2049, 0x2051,
- 0x20DD, 0x20DE, 0x2100, 0x2103, 0x2105, 0x2109, 0x210A, 0x2113, 0x2116, 0x2121,
- 0x212B, 0x213B, 0x2150, 0x2151, 0x2152, 0x217F, 0x2189, 0x2307, 0x2312, 0x23CE,
- 0x2423, 0x25A0, 0x25A1, 0x25A2, 0x25AA, 0x25AB, 0x25B1, 0x25B2, 0x25B3, 0x25B6,
- 0x25B7, 0x25BC, 0x25BD, 0x25C0, 0x25C1, 0x25C6, 0x25C7, 0x25C9, 0x25CB, 0x25CC,
- 0x25EF, 0x2605, 0x2606, 0x260E, 0x2616, 0x2617, 0x2640, 0x2642, 0x26A0, 0x26BD,
- 0x26BE, 0x2713, 0x271A, 0x273F, 0x2740, 0x2756, 0x2B1A, 0xFE10, 0xFE11, 0xFE12,
- 0xFE19, 0xFF1D,
- // Emoji.
- 0x1F100
-};
-
-Font::CodePath Font::s_codePath = Auto;
-
-TypesettingFeatures Font::s_defaultTypesettingFeatures = 0;
-
-// ============================================================================================
-// Font Implementation (Cross-Platform Portion)
-// ============================================================================================
-
-Font::Font()
- : m_letterSpacing(0)
- , m_wordSpacing(0)
- , m_isPlatformFont(false)
- , m_needsTranscoding(false)
- , m_typesettingFeatures(0)
-{
-}
-
-Font::Font(const FontDescription& fd, float letterSpacing, float wordSpacing)
- : m_fontDescription(fd)
- , m_letterSpacing(letterSpacing)
- , m_wordSpacing(wordSpacing)
- , m_isPlatformFont(false)
- , m_needsTranscoding(fontTranscoder().needsTranscoding(fd))
- , m_typesettingFeatures(computeTypesettingFeatures())
-{
-}
-
-Font::Font(const FontPlatformData& fontData, bool isPrinterFont, FontSmoothingMode fontSmoothingMode)
- : m_fontFallbackList(FontFallbackList::create())
- , m_letterSpacing(0)
- , m_wordSpacing(0)
- , m_isPlatformFont(true)
- , m_typesettingFeatures(computeTypesettingFeatures())
-{
- m_fontDescription.setUsePrinterFont(isPrinterFont);
- m_fontDescription.setFontSmoothing(fontSmoothingMode);
- m_needsTranscoding = fontTranscoder().needsTranscoding(fontDescription());
- m_fontFallbackList->setPlatformFont(fontData);
-}
-
-Font::Font(const Font& other)
- : m_fontDescription(other.m_fontDescription)
- , m_fontFallbackList(other.m_fontFallbackList)
- , m_letterSpacing(other.m_letterSpacing)
- , m_wordSpacing(other.m_wordSpacing)
- , m_isPlatformFont(other.m_isPlatformFont)
- , m_needsTranscoding(other.m_needsTranscoding)
- , m_typesettingFeatures(computeTypesettingFeatures())
-{
-}
-
-Font& Font::operator=(const Font& other)
-{
- m_fontDescription = other.m_fontDescription;
- m_fontFallbackList = other.m_fontFallbackList;
- m_letterSpacing = other.m_letterSpacing;
- m_wordSpacing = other.m_wordSpacing;
- m_isPlatformFont = other.m_isPlatformFont;
- m_needsTranscoding = other.m_needsTranscoding;
- m_typesettingFeatures = other.m_typesettingFeatures;
- return *this;
-}
-
-bool Font::operator==(const Font& other) const
-{
- // Our FontData don't have to be checked, since checking the font description will be fine.
- // FIXME: This does not work if the font was made with the FontPlatformData constructor.
- if (loadingCustomFonts() || other.loadingCustomFonts())
- return false;
-
- FontSelector* first = m_fontFallbackList ? m_fontFallbackList->fontSelector() : 0;
- FontSelector* second = other.m_fontFallbackList ? other.m_fontFallbackList->fontSelector() : 0;
-
- return first == second
- && m_fontDescription == other.m_fontDescription
- && m_letterSpacing == other.m_letterSpacing
- && m_wordSpacing == other.m_wordSpacing
- && (m_fontFallbackList ? m_fontFallbackList->fontSelectorVersion() : 0) == (other.m_fontFallbackList ? other.m_fontFallbackList->fontSelectorVersion() : 0)
- && (m_fontFallbackList ? m_fontFallbackList->generation() : 0) == (other.m_fontFallbackList ? other.m_fontFallbackList->generation() : 0);
-}
-
-void Font::update(PassRefPtr<FontSelector> fontSelector) const
-{
- // FIXME: It is pretty crazy that we are willing to just poke into a RefPtr, but it ends up
- // being reasonably safe (because inherited fonts in the render tree pick up the new
- // style anyway. Other copies are transient, e.g., the state in the GraphicsContext, and
- // won't stick around long enough to get you in trouble). Still, this is pretty disgusting,
- // and could eventually be rectified by using RefPtrs for Fonts themselves.
- if (!m_fontFallbackList)
- m_fontFallbackList = FontFallbackList::create();
- m_fontFallbackList->invalidate(fontSelector);
- m_typesettingFeatures = computeTypesettingFeatures();
-}
-
-void Font::drawText(GraphicsContext* context, const TextRunPaintInfo& runInfo, const FloatPoint& point, CustomFontNotReadyAction customFontNotReadyAction) const
-{
- // Don't draw anything while we are using custom fonts that are in the process of loading,
- // except if the 'force' argument is set to true (in which case it will use a fallback
- // font).
- if (loadingCustomFonts() && customFontNotReadyAction == DoNotPaintIfFontNotReady)
- return;
-
- CodePath codePathToUse = codePath(runInfo.run);
- // FIXME: Use the fast code path once it handles partial runs with kerning and ligatures. See http://webkit.org/b/100050
- if (codePathToUse != Complex && typesettingFeatures() && (runInfo.from || runInfo.to != runInfo.run.length()))
- codePathToUse = Complex;
-
- if (codePathToUse != Complex)
- return drawSimpleText(context, runInfo, point);
-
- return drawComplexText(context, runInfo, point);
-}
-
-void Font::drawEmphasisMarks(GraphicsContext* context, const TextRunPaintInfo& runInfo, const AtomicString& mark, const FloatPoint& point) const
-{
- if (loadingCustomFonts())
- return;
-
- CodePath codePathToUse = codePath(runInfo.run);
- // FIXME: Use the fast code path once it handles partial runs with kerning and ligatures. See http://webkit.org/b/100050
- if (codePathToUse != Complex && typesettingFeatures() && (runInfo.from || runInfo.to != runInfo.run.length()))
- codePathToUse = Complex;
-
- if (codePathToUse != Complex)
- drawEmphasisMarksForSimpleText(context, runInfo, mark, point);
- else
- drawEmphasisMarksForComplexText(context, runInfo, mark, point);
-}
-
-float Font::width(const TextRun& run, HashSet<const SimpleFontData*>* fallbackFonts, GlyphOverflow* glyphOverflow) const
-{
- CodePath codePathToUse = codePath(run);
- if (codePathToUse != Complex) {
- // The complex path is more restrictive about returning fallback fonts than the simple path, so we need an explicit test to make their behaviors match.
- if (!canReturnFallbackFontsForComplexText())
- fallbackFonts = 0;
- // The simple path can optimize the case where glyph overflow is not observable.
- if (codePathToUse != SimpleWithGlyphOverflow && (glyphOverflow && !glyphOverflow->computeBounds))
- glyphOverflow = 0;
- }
-
- bool hasKerningOrLigatures = typesettingFeatures() & (Kerning | Ligatures);
- bool hasWordSpacingOrLetterSpacing = wordSpacing() || letterSpacing();
- float* cacheEntry = m_fontFallbackList->widthCache().add(run, std::numeric_limits<float>::quiet_NaN(), hasKerningOrLigatures, hasWordSpacingOrLetterSpacing, glyphOverflow);
- if (cacheEntry && !std::isnan(*cacheEntry))
- return *cacheEntry;
-
- float result;
- if (codePathToUse == Complex)
- result = floatWidthForComplexText(run, fallbackFonts, glyphOverflow);
- else
- result = floatWidthForSimpleText(run, fallbackFonts, glyphOverflow);
-
- if (cacheEntry && (!fallbackFonts || fallbackFonts->isEmpty()))
- *cacheEntry = result;
- return result;
-}
-
-float Font::width(const TextRun& run, int& charsConsumed, String& glyphName) const
-{
-#if ENABLE(SVG_FONTS)
- if (TextRun::RenderingContext* renderingContext = run.renderingContext())
- return renderingContext->floatWidthUsingSVGFont(*this, run, charsConsumed, glyphName);
-#endif
-
- charsConsumed = run.length();
- glyphName = "";
- return width(run);
-}
-
-#if !OS(MACOSX)
-
-PassOwnPtr<TextLayout> Font::createLayout(RenderText*, float, bool) const
-{
- return nullptr;
-}
-
-void Font::deleteLayout(TextLayout*)
-{
-}
-
-float Font::width(TextLayout&, unsigned, unsigned, HashSet<const SimpleFontData*>*)
-{
- ASSERT_NOT_REACHED();
- return 0;
-}
-
-#endif
-
-FloatRect Font::selectionRectForText(const TextRun& run, const FloatPoint& point, int h, int from, int to) const
-{
- to = (to == -1 ? run.length() : to);
-
- CodePath codePathToUse = codePath(run);
- // FIXME: Use the fast code path once it handles partial runs with kerning and ligatures. See http://webkit.org/b/100050
- if (codePathToUse != Complex && typesettingFeatures() && (from || to != run.length()))
- codePathToUse = Complex;
-
- if (codePathToUse != Complex)
- return selectionRectForSimpleText(run, point, h, from, to);
-
- return selectionRectForComplexText(run, point, h, from, to);
-}
-
-int Font::offsetForPosition(const TextRun& run, float x, bool includePartialGlyphs) const
-{
- // FIXME: Use the fast code path once it handles partial runs with kerning and ligatures. See http://webkit.org/b/100050
- if (codePath(run) != Complex && !typesettingFeatures())
- return offsetForPositionForSimpleText(run, x, includePartialGlyphs);
-
- return offsetForPositionForComplexText(run, x, includePartialGlyphs);
-}
-
-template <typename CharacterType>
-static inline String normalizeSpacesInternal(const CharacterType* characters, unsigned length)
-{
- StringBuilder normalized;
- normalized.reserveCapacity(length);
-
- for (unsigned i = 0; i < length; ++i)
- normalized.append(Font::normalizeSpaces(characters[i]));
-
- return normalized.toString();
-}
-
-String Font::normalizeSpaces(const LChar* characters, unsigned length)
-{
- return normalizeSpacesInternal(characters, length);
-}
-
-String Font::normalizeSpaces(const UChar* characters, unsigned length)
-{
- return normalizeSpacesInternal(characters, length);
-}
-
-static bool shouldUseFontSmoothing = true;
-
-void Font::setShouldUseSmoothing(bool shouldUseSmoothing)
-{
- ASSERT(isMainThread());
- shouldUseFontSmoothing = shouldUseSmoothing;
-}
-
-bool Font::shouldUseSmoothing()
-{
- return shouldUseFontSmoothing;
-}
-
-void Font::setCodePath(CodePath p)
-{
- s_codePath = p;
-}
-
-Font::CodePath Font::codePath()
-{
- return s_codePath;
-}
-
-void Font::setDefaultTypesettingFeatures(TypesettingFeatures typesettingFeatures)
-{
- s_defaultTypesettingFeatures = typesettingFeatures;
-}
-
-TypesettingFeatures Font::defaultTypesettingFeatures()
-{
- return s_defaultTypesettingFeatures;
-}
-
-Font::CodePath Font::codePath(const TextRun& run) const
-{
- if (s_codePath != Auto)
- return s_codePath;
-
-#if ENABLE(SVG_FONTS)
- if (run.renderingContext())
- return Simple;
-#endif
-
- if (m_fontDescription.featureSettings() && m_fontDescription.featureSettings()->size() > 0)
- return Complex;
-
- if (run.length() > 1 && !WidthIterator::supportsTypesettingFeatures(*this))
- return Complex;
-
- if (!run.characterScanForCodePath())
- return Simple;
-
- if (run.is8Bit())
- return Simple;
-
- // Start from 0 since drawing and highlighting also measure the characters before run->from.
- return characterRangeCodePath(run.characters16(), run.length());
-}
-
-static inline UChar keyExtractorUChar(const UChar* value)
-{
- return *value;
-}
-
-static inline UChar32 keyExtractorUChar32(const UChar32* value)
-{
- return *value;
-}
-
-Font::CodePath Font::characterRangeCodePath(const UChar* characters, unsigned len)
-{
- static UChar complexCodePathRanges[] = {
- // U+02E5 through U+02E9 (Modifier Letters : Tone letters)
- 0x2E5, 0x2E9,
- // U+0300 through U+036F Combining diacritical marks
- 0x300, 0x36F,
- // U+0591 through U+05CF excluding U+05BE Hebrew combining marks, ...
- 0x0591, 0x05BD,
- // ... Hebrew punctuation Paseq, Sof Pasuq and Nun Hafukha
- 0x05BF, 0x05CF,
- // U+0600 through U+109F Arabic, Syriac, Thaana, NKo, Samaritan, Mandaic,
- // Devanagari, Bengali, Gurmukhi, Gujarati, Oriya, Tamil, Telugu, Kannada,
- // Malayalam, Sinhala, Thai, Lao, Tibetan, Myanmar
- 0x0600, 0x109F,
- // U+1100 through U+11FF Hangul Jamo (only Ancient Korean should be left
- // here if you precompose; Modern Korean will be precomposed as a result of step A)
- 0x1100, 0x11FF,
- // U+135D through U+135F Ethiopic combining marks
- 0x135D, 0x135F,
- // U+1780 through U+18AF Tagalog, Hanunoo, Buhid, Taghanwa,Khmer, Mongolian
- 0x1700, 0x18AF,
- // U+1900 through U+194F Limbu (Unicode 4.0)
- 0x1900, 0x194F,
- // U+1980 through U+19DF New Tai Lue
- 0x1980, 0x19DF,
- // U+1A00 through U+1CFF Buginese, Tai Tham, Balinese, Batak, Lepcha, Vedic
- 0x1A00, 0x1CFF,
- // U+1DC0 through U+1DFF Comining diacritical mark supplement
- 0x1DC0, 0x1DFF,
- // U+20D0 through U+20FF Combining marks for symbols
- 0x20D0, 0x20FF,
- // U+2CEF through U+2CF1 Combining marks for Coptic
- 0x2CEF, 0x2CF1,
- // U+302A through U+302F Ideographic and Hangul Tone marks
- 0x302A, 0x302F,
- // U+A67C through U+A67D Combining marks for old Cyrillic
- 0xA67C, 0xA67D,
- // U+A6F0 through U+A6F1 Combining mark for Bamum
- 0xA6F0, 0xA6F1,
- // U+A800 through U+ABFF Nagri, Phags-pa, Saurashtra, Devanagari Extended,
- // Hangul Jamo Ext. A, Javanese, Myanmar Extended A, Tai Viet, Meetei Mayek
- 0xA800, 0xABFF,
- // U+D7B0 through U+D7FF Hangul Jamo Ext. B
- 0xD7B0, 0xD7FF,
- // U+FE00 through U+FE0F Unicode variation selectors
- 0xFE00, 0xFE0F,
- // U+FE20 through U+FE2F Combining half marks
- 0xFE20, 0xFE2F
- };
- static size_t complexCodePathRangesCount = WTF_ARRAY_LENGTH(complexCodePathRanges);
-
- CodePath result = Simple;
- for (unsigned i = 0; i < len; i++) {
- const UChar c = characters[i];
-
- // Shortcut for common case
- if (c < 0x2E5)
- continue;
-
- // U+1E00 through U+2000 characters with diacritics and stacked diacritics
- if (c >= 0x1E00 && c <= 0x2000) {
- result = SimpleWithGlyphOverflow;
- continue;
- }
-
- // Surrogate pairs
- if (c > 0xD7FF && c <= 0xDBFF) {
- if (i == len - 1)
- continue;
-
- UChar next = characters[++i];
- if (!U16_IS_TRAIL(next))
- continue;
-
- UChar32 supplementaryCharacter = U16_GET_SUPPLEMENTARY(c, next);
-
- if (supplementaryCharacter < 0x1F1E6) // U+1F1E6 through U+1F1FF Regional Indicator Symbols
- continue;
- if (supplementaryCharacter <= 0x1F1FF)
- return Complex;
-
- if (supplementaryCharacter < 0xE0100) // U+E0100 through U+E01EF Unicode variation selectors.
- continue;
- if (supplementaryCharacter <= 0xE01EF)
- return Complex;
-
- // FIXME: Check for Brahmi (U+11000 block), Kaithi (U+11080 block) and other complex scripts
- // in plane 1 or higher.
-
- continue;
- }
-
- // Search for other Complex cases
- UChar* boundingCharacter = approximateBinarySearch<UChar, UChar>(
- (UChar*)complexCodePathRanges, complexCodePathRangesCount, c, keyExtractorUChar);
- // Exact matches are complex
- if (*boundingCharacter == c)
- return Complex;
- bool isEndOfRange = ((boundingCharacter - complexCodePathRanges) % 2);
- if (*boundingCharacter < c) {
- // Determine if we are in a range or out
- if (!isEndOfRange)
- return Complex;
- continue;
- }
- ASSERT(*boundingCharacter > c);
- // Determine if we are in a range or out - opposite condition to above
- if (isEndOfRange)
- return Complex;
- }
-
- return result;
-}
-
-bool Font::isCJKIdeograph(UChar32 c)
-{
- static UChar32 cjkIdeographRanges[] = {
- // CJK Radicals Supplement and Kangxi Radicals.
- 0x2E80, 0x2FDF,
- // CJK Strokes.
- 0x31C0, 0x31EF,
- // CJK Unified Ideographs Extension A.
- 0x3400, 0x4DBF,
- // The basic CJK Unified Ideographs block.
- 0x4E00, 0x9FFF,
- // CJK Compatibility Ideographs.
- 0xF900, 0xFAFF,
- // CJK Unified Ideographs Extension B.
- 0x20000, 0x2A6DF,
- // CJK Unified Ideographs Extension C.
- // CJK Unified Ideographs Extension D.
- 0x2A700, 0x2B81F,
- // CJK Compatibility Ideographs Supplement.
- 0x2F800, 0x2FA1F
- };
- static size_t cjkIdeographRangesCount = WTF_ARRAY_LENGTH(cjkIdeographRanges);
-
- // Early out
- if (c < cjkIdeographRanges[0] || c > cjkIdeographRanges[cjkIdeographRangesCount - 1])
- return false;
-
- UChar32* boundingCharacter = approximateBinarySearch<UChar32, UChar32>(
- (UChar32*)cjkIdeographRanges, cjkIdeographRangesCount, c, keyExtractorUChar32);
- // Exact matches are CJK
- if (*boundingCharacter == c)
- return true;
- bool isEndOfRange = ((boundingCharacter - cjkIdeographRanges) % 2);
- if (*boundingCharacter < c)
- return !isEndOfRange;
- return isEndOfRange;
-}
-
-bool Font::isCJKIdeographOrSymbol(UChar32 c)
-{
- // Likely common case
- if (c < 0x2C7)
- return false;
-
- // Hash lookup for isolated symbols (those not part of a contiguous range)
- static HashSet<UChar32>* cjkIsolatedSymbols = 0;
- if (!cjkIsolatedSymbols) {
- cjkIsolatedSymbols = new HashSet<UChar32>();
- for (size_t i = 0; i < WTF_ARRAY_LENGTH(cjkIsolatedSymbolsArray); ++i)
- cjkIsolatedSymbols->add(cjkIsolatedSymbolsArray[i]);
- }
- if (cjkIsolatedSymbols->contains(c))
- return true;
-
- if (isCJKIdeograph(c))
- return true;
-
- static UChar32 cjkSymbolRanges[] = {
- 0x2156, 0x215A,
- 0x2160, 0x216B,
- 0x2170, 0x217B,
- 0x23BE, 0x23CC,
- 0x2460, 0x2492,
- 0x249C, 0x24FF,
- 0x25CE, 0x25D3,
- 0x25E2, 0x25E6,
- 0x2600, 0x2603,
- 0x2660, 0x266F,
- 0x2672, 0x267D,
- 0x2776, 0x277F,
- // Ideographic Description Characters, with CJK Symbols and Punctuation, excluding 0x3030.
- // Then Hiragana 0x3040 .. 0x309F, Katakana 0x30A0 .. 0x30FF, Bopomofo 0x3100 .. 0x312F
- 0x2FF0, 0x302F,
- 0x3031, 0x312F,
- // More Bopomofo and Bopomofo Extended 0x31A0 .. 0x31BF
- 0x3190, 0x31BF,
- // Enclosed CJK Letters and Months (0x3200 .. 0x32FF).
- // CJK Compatibility (0x3300 .. 0x33FF).
- 0x3200, 0x33FF,
- 0xF860, 0xF862,
- // CJK Compatibility Forms.
- 0xFE30, 0xFE4F,
- // Halfwidth and Fullwidth Forms
- // Usually only used in CJK
- 0xFF00, 0xFF0C,
- 0xFF0E, 0xFF1A,
- 0xFF1F, 0xFFEF,
- // Emoji.
- 0x1F110, 0x1F129,
- 0x1F130, 0x1F149,
- 0x1F150, 0x1F169,
- 0x1F170, 0x1F189,
- 0x1F200, 0x1F6FF
- };
- static size_t cjkSymbolRangesCount = WTF_ARRAY_LENGTH(cjkSymbolRanges);
-
- UChar32* boundingCharacter = approximateBinarySearch<UChar32, UChar32>(
- (UChar32*)cjkSymbolRanges, cjkSymbolRangesCount, c, keyExtractorUChar32);
- // Exact matches are CJK Symbols
- if (*boundingCharacter == c)
- return true;
- bool isEndOfRange = ((boundingCharacter - cjkSymbolRanges) % 2);
- if (*boundingCharacter < c)
- return !isEndOfRange;
- return isEndOfRange;
-}
-
-unsigned Font::expansionOpportunityCount(const LChar* characters, size_t length, TextDirection direction, bool& isAfterExpansion)
-{
- unsigned count = 0;
- if (direction == LTR) {
- for (size_t i = 0; i < length; ++i) {
- if (treatAsSpace(characters[i])) {
- count++;
- isAfterExpansion = true;
- } else
- isAfterExpansion = false;
- }
- } else {
- for (size_t i = length; i > 0; --i) {
- if (treatAsSpace(characters[i - 1])) {
- count++;
- isAfterExpansion = true;
- } else
- isAfterExpansion = false;
- }
- }
- return count;
-}
-
-unsigned Font::expansionOpportunityCount(const UChar* characters, size_t length, TextDirection direction, bool& isAfterExpansion)
-{
- static bool expandAroundIdeographs = canExpandAroundIdeographsInComplexText();
- unsigned count = 0;
- if (direction == LTR) {
- for (size_t i = 0; i < length; ++i) {
- UChar32 character = characters[i];
- if (treatAsSpace(character)) {
- count++;
- isAfterExpansion = true;
- continue;
- }
- if (U16_IS_LEAD(character) && i + 1 < length && U16_IS_TRAIL(characters[i + 1])) {
- character = U16_GET_SUPPLEMENTARY(character, characters[i + 1]);
- i++;
- }
- if (expandAroundIdeographs && isCJKIdeographOrSymbol(character)) {
- if (!isAfterExpansion)
- count++;
- count++;
- isAfterExpansion = true;
- continue;
- }
- isAfterExpansion = false;
- }
- } else {
- for (size_t i = length; i > 0; --i) {
- UChar32 character = characters[i - 1];
- if (treatAsSpace(character)) {
- count++;
- isAfterExpansion = true;
- continue;
- }
- if (U16_IS_TRAIL(character) && i > 1 && U16_IS_LEAD(characters[i - 2])) {
- character = U16_GET_SUPPLEMENTARY(characters[i - 2], character);
- i--;
- }
- if (expandAroundIdeographs && isCJKIdeographOrSymbol(character)) {
- if (!isAfterExpansion)
- count++;
- count++;
- isAfterExpansion = true;
- continue;
- }
- isAfterExpansion = false;
- }
- }
- return count;
-}
-
-bool Font::canReceiveTextEmphasis(UChar32 c)
-{
- CharCategory category = Unicode::category(c);
- if (category & (Separator_Space | Separator_Line | Separator_Paragraph | Other_NotAssigned | Other_Control | Other_Format))
- return false;
-
- // Additional word-separator characters listed in CSS Text Level 3 Editor's Draft 3 November 2010.
- if (c == ethiopicWordspace || c == aegeanWordSeparatorLine || c == aegeanWordSeparatorDot
- || c == ugariticWordDivider || c == tibetanMarkIntersyllabicTsheg || c == tibetanMarkDelimiterTshegBstar)
- return false;
-
- return true;
-}
-
-void Font::willUseFontData() const
-{
- const FontFamily& family = fontDescription().family();
- if (m_fontFallbackList && m_fontFallbackList->fontSelector() && !family.familyIsEmpty())
- m_fontFallbackList->fontSelector()->willUseFontData(fontDescription(), family.family());
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/Font.h b/chromium/third_party/WebKit/Source/core/platform/graphics/Font.h
deleted file mode 100644
index 9e83145bbcb..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/Font.h
+++ /dev/null
@@ -1,342 +0,0 @@
-/*
- * Copyright (C) 2000 Lars Knoll (knoll@kde.org)
- * (C) 2000 Antti Koivisto (koivisto@kde.org)
- * (C) 2000 Dirk Mueller (mueller@kde.org)
- * Copyright (C) 2003, 2006, 2007, 2010, 2011 Apple Inc. All rights reserved.
- * Copyright (C) 2008 Holger Hans Peter Freyther
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#ifndef Font_h
-#define Font_h
-
-#include "core/platform/graphics/FontDescription.h"
-#include "core/platform/graphics/FontFallbackList.h"
-#include "core/platform/graphics/SimpleFontData.h"
-#include "core/platform/graphics/TypesettingFeatures.h"
-#include "core/platform/text/TextDirection.h"
-#include "wtf/HashMap.h"
-#include "wtf/HashSet.h"
-#include "wtf/MathExtras.h"
-#include "wtf/unicode/CharacterNames.h"
-
-// "X11/X.h" defines Complex to 0 and conflicts
-// with Complex value in CodePath enum.
-#ifdef Complex
-#undef Complex
-#endif
-
-namespace WebCore {
-
-class FloatPoint;
-class FloatRect;
-class FontData;
-class FontMetrics;
-class FontPlatformData;
-class FontSelector;
-class GlyphBuffer;
-class GraphicsContext;
-class RenderText;
-class TextLayout;
-class TextRun;
-struct TextRunPaintInfo;
-
-struct GlyphData;
-
-struct GlyphOverflow {
- GlyphOverflow()
- : left(0)
- , right(0)
- , top(0)
- , bottom(0)
- , computeBounds(false)
- {
- }
-
- int left;
- int right;
- int top;
- int bottom;
- bool computeBounds;
-};
-
-
-class Font {
-public:
- Font();
- Font(const FontDescription&, float letterSpacing, float wordSpacing);
- // This constructor is only used if the platform wants to start with a native font.
- Font(const FontPlatformData&, bool isPrinting, FontSmoothingMode = AutoSmoothing);
- ~Font();
-
- Font(const Font&);
- Font& operator=(const Font&);
-
- bool operator==(const Font& other) const;
- bool operator!=(const Font& other) const { return !(*this == other); }
-
- const FontDescription& fontDescription() const { return m_fontDescription; }
-
- int pixelSize() const { return fontDescription().computedPixelSize(); }
- float size() const { return fontDescription().computedSize(); }
-
- void update(PassRefPtr<FontSelector>) const;
-
- enum CustomFontNotReadyAction { DoNotPaintIfFontNotReady, UseFallbackIfFontNotReady };
- void drawText(GraphicsContext*, const TextRunPaintInfo&, const FloatPoint&, CustomFontNotReadyAction = DoNotPaintIfFontNotReady) const;
- void drawEmphasisMarks(GraphicsContext*, const TextRunPaintInfo&, const AtomicString& mark, const FloatPoint&) const;
-
- float width(const TextRun&, HashSet<const SimpleFontData*>* fallbackFonts = 0, GlyphOverflow* = 0) const;
- float width(const TextRun&, int& charsConsumed, String& glyphName) const;
-
- PassOwnPtr<TextLayout> createLayout(RenderText*, float xPos, bool collapseWhiteSpace) const;
- static void deleteLayout(TextLayout*);
- static float width(TextLayout&, unsigned from, unsigned len, HashSet<const SimpleFontData*>* fallbackFonts = 0);
-
- int offsetForPosition(const TextRun&, float position, bool includePartialGlyphs) const;
- FloatRect selectionRectForText(const TextRun&, const FloatPoint&, int h, int from = 0, int to = -1) const;
-
- bool isSmallCaps() const { return m_fontDescription.smallCaps(); }
-
- float wordSpacing() const { return m_wordSpacing; }
- float letterSpacing() const { return m_letterSpacing; }
- void setWordSpacing(float s) { m_wordSpacing = s; }
- void setLetterSpacing(float s) { m_letterSpacing = s; }
- bool isFixedPitch() const;
- bool isPrinterFont() const { return m_fontDescription.usePrinterFont(); }
-
- TypesettingFeatures typesettingFeatures() const { return static_cast<TypesettingFeatures>(m_typesettingFeatures); }
-
- FontFamily& firstFamily() { return m_fontDescription.firstFamily(); }
- const FontFamily& family() const { return m_fontDescription.family(); }
-
- FontItalic italic() const { return m_fontDescription.italic(); }
- FontWeight weight() const { return m_fontDescription.weight(); }
- FontWidthVariant widthVariant() const { return m_fontDescription.widthVariant(); }
-
- bool isPlatformFont() const { return m_isPlatformFont; }
-
- // Metrics that we query the FontFallbackList for.
- const FontMetrics& fontMetrics() const { return primaryFont()->fontMetrics(); }
- float spaceWidth() const { return primaryFont()->spaceWidth() + m_letterSpacing; }
- float tabWidth(const SimpleFontData&, unsigned tabSize, float position) const;
- float tabWidth(unsigned tabSize, float position) const { return tabWidth(*primaryFont(), tabSize, position); }
-
- int emphasisMarkAscent(const AtomicString&) const;
- int emphasisMarkDescent(const AtomicString&) const;
- int emphasisMarkHeight(const AtomicString&) const;
-
- const SimpleFontData* primaryFont() const;
- const FontData* fontDataAt(unsigned) const;
- inline GlyphData glyphDataForCharacter(UChar32 c, bool mirror, FontDataVariant variant = AutoVariant) const
- {
- return glyphDataAndPageForCharacter(c, mirror, variant).first;
- }
-#if OS(MACOSX)
- const SimpleFontData* fontDataForCombiningCharacterSequence(const UChar*, size_t length, FontDataVariant) const;
-#endif
- std::pair<GlyphData, GlyphPage*> glyphDataAndPageForCharacter(UChar32, bool mirror, FontDataVariant = AutoVariant) const;
- bool primaryFontHasGlyphForCharacter(UChar32) const;
-
- static bool isCJKIdeograph(UChar32);
- static bool isCJKIdeographOrSymbol(UChar32);
-
- static unsigned expansionOpportunityCount(const LChar*, size_t length, TextDirection, bool& isAfterExpansion);
- static unsigned expansionOpportunityCount(const UChar*, size_t length, TextDirection, bool& isAfterExpansion);
-
- static void setShouldUseSmoothing(bool);
- static bool shouldUseSmoothing();
-
- enum CodePath { Auto, Simple, Complex, SimpleWithGlyphOverflow };
- CodePath codePath(const TextRun&) const;
- static CodePath characterRangeCodePath(const LChar*, unsigned) { return Simple; }
- static CodePath characterRangeCodePath(const UChar*, unsigned len);
-
-private:
- enum ForTextEmphasisOrNot { NotForTextEmphasis, ForTextEmphasis };
-
- // Returns the initial in-stream advance.
- float getGlyphsAndAdvancesForSimpleText(const TextRun&, int from, int to, GlyphBuffer&, ForTextEmphasisOrNot = NotForTextEmphasis) const;
- void drawSimpleText(GraphicsContext*, const TextRunPaintInfo&, const FloatPoint&) const;
- void drawEmphasisMarksForSimpleText(GraphicsContext*, const TextRunPaintInfo&, const AtomicString& mark, const FloatPoint&) const;
- void drawGlyphs(GraphicsContext*, const SimpleFontData*, const GlyphBuffer&, int from, int to, const FloatPoint&, const FloatRect& textRect) const;
- void drawGlyphBuffer(GraphicsContext*, const TextRunPaintInfo&, const GlyphBuffer&, const FloatPoint&) const;
- void drawEmphasisMarks(GraphicsContext*, const TextRunPaintInfo&, const GlyphBuffer&, const AtomicString&, const FloatPoint&) const;
- float floatWidthForSimpleText(const TextRun&, HashSet<const SimpleFontData*>* fallbackFonts = 0, GlyphOverflow* = 0) const;
- int offsetForPositionForSimpleText(const TextRun&, float position, bool includePartialGlyphs) const;
- FloatRect selectionRectForSimpleText(const TextRun&, const FloatPoint&, int h, int from, int to) const;
-
- bool getEmphasisMarkGlyphData(const AtomicString&, GlyphData&) const;
-
- static bool canReturnFallbackFontsForComplexText();
- static bool canExpandAroundIdeographsInComplexText();
-
- // Returns the initial in-stream advance.
- float getGlyphsAndAdvancesForComplexText(const TextRun&, int from, int to, GlyphBuffer&, ForTextEmphasisOrNot = NotForTextEmphasis) const;
- void drawComplexText(GraphicsContext*, const TextRunPaintInfo&, const FloatPoint&) const;
- void drawEmphasisMarksForComplexText(GraphicsContext*, const TextRunPaintInfo&, const AtomicString& mark, const FloatPoint&) const;
- float floatWidthForComplexText(const TextRun&, HashSet<const SimpleFontData*>* fallbackFonts = 0, GlyphOverflow* = 0) const;
- int offsetForPositionForComplexText(const TextRun&, float position, bool includePartialGlyphs) const;
- FloatRect selectionRectForComplexText(const TextRun&, const FloatPoint&, int h, int from, int to) const;
-
- friend struct WidthIterator;
- friend class SVGTextRunRenderingContext;
-
-public:
- // Useful for debugging the different font rendering code paths.
- static void setCodePath(CodePath);
- static CodePath codePath();
- static CodePath s_codePath;
-
- static void setDefaultTypesettingFeatures(TypesettingFeatures);
- static TypesettingFeatures defaultTypesettingFeatures();
-
- static const uint8_t s_roundingHackCharacterTable[256];
- static bool isRoundingHackCharacter(UChar32 c)
- {
- return !(c & ~0xFF) && s_roundingHackCharacterTable[c];
- }
-
- FontSelector* fontSelector() const;
- static bool treatAsSpace(UChar c) { return c == ' ' || c == '\t' || c == '\n' || c == noBreakSpace; }
- static bool treatAsZeroWidthSpace(UChar c) { return treatAsZeroWidthSpaceInComplexScript(c) || c == 0x200c || c == 0x200d; }
- static bool treatAsZeroWidthSpaceInComplexScript(UChar c) { return c < 0x20 || (c >= 0x7F && c < 0xA0) || c == softHyphen || c == zeroWidthSpace || (c >= 0x200e && c <= 0x200f) || (c >= 0x202a && c <= 0x202e) || c == zeroWidthNoBreakSpace || c == objectReplacementCharacter; }
- static bool canReceiveTextEmphasis(UChar32 c);
-
- static inline UChar normalizeSpaces(UChar character)
- {
- if (treatAsSpace(character))
- return space;
-
- if (treatAsZeroWidthSpace(character))
- return zeroWidthSpace;
-
- return character;
- }
-
- static String normalizeSpaces(const LChar*, unsigned length);
- static String normalizeSpaces(const UChar*, unsigned length);
-
- bool needsTranscoding() const { return m_needsTranscoding; }
- FontFallbackList* fontList() const { return m_fontFallbackList.get(); }
-
- void willUseFontData() const;
-
-private:
- bool loadingCustomFonts() const
- {
- return m_fontFallbackList && m_fontFallbackList->loadingCustomFonts();
- }
-
- TypesettingFeatures computeTypesettingFeatures() const
- {
- TextRenderingMode textRenderingMode = m_fontDescription.textRenderingMode();
- TypesettingFeatures features = s_defaultTypesettingFeatures;
-
- switch (textRenderingMode) {
- case AutoTextRendering:
- break;
- case OptimizeSpeed:
- features &= ~(Kerning | Ligatures);
- break;
- case GeometricPrecision:
- case OptimizeLegibility:
- features |= Kerning | Ligatures;
- break;
- }
-
- switch (m_fontDescription.kerning()) {
- case FontDescription::NoneKerning:
- features &= ~Kerning;
- break;
- case FontDescription::NormalKerning:
- features |= Kerning;
- break;
- case FontDescription::AutoKerning:
- break;
- }
-
- switch (m_fontDescription.commonLigaturesState()) {
- case FontDescription::DisabledLigaturesState:
- features &= ~Ligatures;
- break;
- case FontDescription::EnabledLigaturesState:
- features |= Ligatures;
- break;
- case FontDescription::NormalLigaturesState:
- break;
- }
-
- return features;
- }
-
- static TypesettingFeatures s_defaultTypesettingFeatures;
-
- FontDescription m_fontDescription;
- mutable RefPtr<FontFallbackList> m_fontFallbackList;
- float m_letterSpacing;
- float m_wordSpacing;
- bool m_isPlatformFont;
- bool m_needsTranscoding;
- mutable unsigned m_typesettingFeatures : 2; // (TypesettingFeatures) Caches values computed from m_fontDescription.
-};
-
-inline Font::~Font()
-{
-}
-
-inline const SimpleFontData* Font::primaryFont() const
-{
- ASSERT(m_fontFallbackList);
- return m_fontFallbackList->primarySimpleFontData(this);
-}
-
-inline const FontData* Font::fontDataAt(unsigned index) const
-{
- ASSERT(m_fontFallbackList);
- return m_fontFallbackList->fontDataAt(this, index);
-}
-
-inline bool Font::isFixedPitch() const
-{
- ASSERT(m_fontFallbackList);
- return m_fontFallbackList->isFixedPitch(this);
-}
-
-inline FontSelector* Font::fontSelector() const
-{
- return m_fontFallbackList ? m_fontFallbackList->fontSelector() : 0;
-}
-
-inline float Font::tabWidth(const SimpleFontData& fontData, unsigned tabSize, float position) const
-{
- if (!tabSize)
- return letterSpacing();
- float tabWidth = tabSize * fontData.spaceWidth() + letterSpacing();
- return tabWidth - fmodf(position, tabWidth);
-}
-
-}
-
-namespace WTF {
-
-template <> void deleteOwnedPtr<WebCore::TextLayout>(WebCore::TextLayout*);
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/FontBaseline.h b/chromium/third_party/WebKit/Source/core/platform/graphics/FontBaseline.h
deleted file mode 100644
index 7e416f9152c..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/FontBaseline.h
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright (C) 2010 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef FontBaseline_h
-#define FontBaseline_h
-
-namespace WebCore {
-
-enum FontBaseline { AlphabeticBaseline, IdeographicBaseline };
-
-} // namespace WebCore
-
-#endif // FontBaseline_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/FontCache.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/FontCache.cpp
deleted file mode 100644
index 2d7403c9c82..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/FontCache.cpp
+++ /dev/null
@@ -1,599 +0,0 @@
-/*
- * Copyright (C) 2006, 2008 Apple Inc. All rights reserved.
- * Copyright (C) 2007 Nicholas Shanks <webkit@nickshanks.com>
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/FontCache.h"
-
-#include "FontFamilyNames.h"
-#include "RuntimeEnabledFeatures.h"
-#include "core/platform/graphics/Font.h"
-#include "core/platform/graphics/FontFallbackList.h"
-#include "core/platform/graphics/FontPlatformData.h"
-#include "core/platform/graphics/FontSelector.h"
-#include "core/platform/graphics/opentype/OpenTypeVerticalData.h"
-#include "wtf/HashMap.h"
-#include "wtf/HashTableDeletedValueType.h"
-#include "wtf/ListHashSet.h"
-#include "wtf/StdLibExtras.h"
-#include "wtf/text/AtomicStringHash.h"
-#include "wtf/text/StringHash.h"
-
-using namespace WTF;
-
-namespace WebCore {
-
-FontCache* fontCache()
-{
- DEFINE_STATIC_LOCAL(FontCache, globalFontCache, ());
- return &globalFontCache;
-}
-
-#if !OS(WIN) || ENABLE(GDI_FONTS_ON_WINDOWS)
-FontCache::FontCache()
- : m_purgePreventCount(0)
-{
-}
-#endif // !OS(WIN) || ENABLE(GDI_FONTS_ON_WINDOWS)
-
-struct FontPlatformDataCacheKey {
- WTF_MAKE_FAST_ALLOCATED;
-public:
- FontPlatformDataCacheKey(const AtomicString& family = AtomicString(), float size = 0, unsigned weight = 0, bool italic = false,
- bool isPrinterFont = false, FontOrientation orientation = Horizontal, FontWidthVariant widthVariant = RegularWidth)
- : m_size(size * s_fontSizePrecisionMultiplier)
- , m_weight(weight)
- , m_family(family)
- , m_italic(italic)
- , m_printerFont(isPrinterFont)
- , m_orientation(orientation)
- , m_widthVariant(widthVariant)
- {
- }
-
- FontPlatformDataCacheKey(HashTableDeletedValueType) : m_size(hashTableDeletedSize()) { }
- bool isHashTableDeletedValue() const { return m_size == hashTableDeletedSize(); }
-
- bool operator==(const FontPlatformDataCacheKey& other) const
- {
- return equalIgnoringCase(m_family, other.m_family) && m_size == other.m_size
- && m_weight == other.m_weight && m_italic == other.m_italic && m_printerFont == other.m_printerFont
- && m_orientation == other.m_orientation && m_widthVariant == other.m_widthVariant;
- }
-
- unsigned m_size;
- unsigned m_weight;
- AtomicString m_family;
- bool m_italic;
- bool m_printerFont;
- FontOrientation m_orientation;
- FontWidthVariant m_widthVariant;
-
-private:
- // Multiplying the floating point size by 100 gives two decimal
- // point precision which should be sufficient.
- static const unsigned s_fontSizePrecisionMultiplier = 100;
-
- static unsigned hashTableDeletedSize() { return 0xFFFFFFFFU; }
-};
-
-inline unsigned computeHash(const FontPlatformDataCacheKey& fontKey)
-{
- unsigned hashCodes[5] = {
- CaseFoldingHash::hash(fontKey.m_family),
- fontKey.m_size,
- fontKey.m_weight,
- fontKey.m_widthVariant,
- static_cast<unsigned>(fontKey.m_orientation) << 2 | static_cast<unsigned>(fontKey.m_italic) << 1 | static_cast<unsigned>(fontKey.m_printerFont)
- };
- return StringHasher::hashMemory<sizeof(hashCodes)>(hashCodes);
-}
-
-struct FontPlatformDataCacheKeyHash {
- static unsigned hash(const FontPlatformDataCacheKey& font)
- {
- return computeHash(font);
- }
-
- static bool equal(const FontPlatformDataCacheKey& a, const FontPlatformDataCacheKey& b)
- {
- return a == b;
- }
-
- static const bool safeToCompareToEmptyOrDeleted = true;
-};
-
-struct FontPlatformDataCacheKeyTraits : WTF::SimpleClassHashTraits<FontPlatformDataCacheKey> { };
-
-typedef HashMap<FontPlatformDataCacheKey, FontPlatformData*, FontPlatformDataCacheKeyHash, FontPlatformDataCacheKeyTraits> FontPlatformDataCache;
-
-static FontPlatformDataCache* gFontPlatformDataCache = 0;
-
-static const AtomicString& alternateFamilyName(const AtomicString& familyName)
-{
- // Alias Courier <-> Courier New
- DEFINE_STATIC_LOCAL(AtomicString, courier, ("Courier", AtomicString::ConstructFromLiteral));
- DEFINE_STATIC_LOCAL(AtomicString, courierNew, ("Courier New", AtomicString::ConstructFromLiteral));
- if (equalIgnoringCase(familyName, courier))
- return courierNew;
-#if !OS(WIN)
- // On Windows, Courier New (truetype font) is always present and
- // Courier is a bitmap font. So, we don't want to map Courier New to
- // Courier.
- if (equalIgnoringCase(familyName, courierNew))
- return courier;
-#endif
-
- // Alias Times and Times New Roman.
- DEFINE_STATIC_LOCAL(AtomicString, times, ("Times", AtomicString::ConstructFromLiteral));
- DEFINE_STATIC_LOCAL(AtomicString, timesNewRoman, ("Times New Roman", AtomicString::ConstructFromLiteral));
- if (equalIgnoringCase(familyName, times))
- return timesNewRoman;
- if (equalIgnoringCase(familyName, timesNewRoman))
- return times;
-
- // Alias Arial and Helvetica
- DEFINE_STATIC_LOCAL(AtomicString, arial, ("Arial", AtomicString::ConstructFromLiteral));
- DEFINE_STATIC_LOCAL(AtomicString, helvetica, ("Helvetica", AtomicString::ConstructFromLiteral));
- if (equalIgnoringCase(familyName, arial))
- return helvetica;
- if (equalIgnoringCase(familyName, helvetica))
- return arial;
-
-#if OS(WIN)
- // On Windows, bitmap fonts are blocked altogether so that we have to
- // alias MS Sans Serif (bitmap font) -> Microsoft Sans Serif (truetype font)
- DEFINE_STATIC_LOCAL(AtomicString, msSans, ("MS Sans Serif", AtomicString::ConstructFromLiteral));
- DEFINE_STATIC_LOCAL(AtomicString, microsoftSans, ("Microsoft Sans Serif", AtomicString::ConstructFromLiteral));
- if (equalIgnoringCase(familyName, msSans))
- return microsoftSans;
-
- // Alias MS Serif (bitmap) -> Times New Roman (truetype font). There's no
- // 'Microsoft Sans Serif-equivalent' for Serif.
- DEFINE_STATIC_LOCAL(AtomicString, msSerif, ("MS Serif", AtomicString::ConstructFromLiteral));
- if (equalIgnoringCase(familyName, msSerif))
- return timesNewRoman;
-#endif
-
- return emptyAtom;
-}
-
-FontPlatformData* FontCache::getFontResourcePlatformData(const FontDescription& fontDescription,
- const AtomicString& passedFamilyName,
- bool checkingAlternateName)
-{
-#if OS(WIN) && ENABLE(OPENTYPE_VERTICAL)
- // Leading "@" in the font name enables Windows vertical flow flag for the font.
- // Because we do vertical flow by ourselves, we don't want to use the Windows feature.
- // IE disregards "@" regardless of the orientatoin, so we follow the behavior.
- const AtomicString& familyName = (passedFamilyName.isEmpty() || passedFamilyName[0] != '@') ?
- passedFamilyName : AtomicString(passedFamilyName.impl()->substring(1));
-#else
- const AtomicString& familyName = passedFamilyName;
-#endif
-
- if (!gFontPlatformDataCache) {
- gFontPlatformDataCache = new FontPlatformDataCache;
- platformInit();
- }
-
- float fontSize;
- if (RuntimeEnabledFeatures::subpixelFontScalingEnabled())
- fontSize = fontDescription.computedSize();
- else
- fontSize = fontDescription.computedPixelSize();
- FontPlatformDataCacheKey key(familyName, fontSize, fontDescription.weight(), fontDescription.italic(),
-
- fontDescription.usePrinterFont(), fontDescription.orientation(), fontDescription.widthVariant());
- FontPlatformData* result = 0;
- bool foundResult;
- FontPlatformDataCache::iterator it = gFontPlatformDataCache->find(key);
- if (it == gFontPlatformDataCache->end()) {
- result = createFontPlatformData(fontDescription, familyName);
- gFontPlatformDataCache->set(key, result);
- foundResult = result;
- } else {
- result = it->value;
- foundResult = true;
- }
-
- if (!foundResult && !checkingAlternateName) {
- // We were unable to find a font. We have a small set of fonts that we alias to other names,
- // e.g., Arial/Helvetica, Courier/Courier New, etc. Try looking up the font under the aliased name.
- const AtomicString& alternateName = alternateFamilyName(familyName);
- if (!alternateName.isEmpty())
- result = getFontResourcePlatformData(fontDescription, alternateName, true);
- if (result)
- gFontPlatformDataCache->set(key, new FontPlatformData(*result)); // Cache the result under the old name.
- }
-
- return result;
-}
-
-#if ENABLE(OPENTYPE_VERTICAL)
-typedef HashMap<FontCache::FontFileKey, RefPtr<OpenTypeVerticalData>, WTF::IntHash<FontCache::FontFileKey>, WTF::UnsignedWithZeroKeyHashTraits<FontCache::FontFileKey> > FontVerticalDataCache;
-
-FontVerticalDataCache& fontVerticalDataCacheInstance()
-{
- DEFINE_STATIC_LOCAL(FontVerticalDataCache, fontVerticalDataCache, ());
- return fontVerticalDataCache;
-}
-
-PassRefPtr<OpenTypeVerticalData> FontCache::getVerticalData(const FontFileKey& key, const FontPlatformData& platformData)
-{
- FontVerticalDataCache& fontVerticalDataCache = fontVerticalDataCacheInstance();
- FontVerticalDataCache::iterator result = fontVerticalDataCache.find(key);
- if (result != fontVerticalDataCache.end())
- return result.get()->value;
-
- RefPtr<OpenTypeVerticalData> verticalData = OpenTypeVerticalData::create(platformData);
- if (!verticalData->isOpenType())
- verticalData.clear();
- fontVerticalDataCache.set(key, verticalData);
- return verticalData;
-}
-#endif
-
-struct FontDataCacheKeyHash {
- static unsigned hash(const FontPlatformData& platformData)
- {
- return platformData.hash();
- }
-
- static bool equal(const FontPlatformData& a, const FontPlatformData& b)
- {
- return a == b;
- }
-
- static const bool safeToCompareToEmptyOrDeleted = true;
-};
-
-struct FontDataCacheKeyTraits : WTF::GenericHashTraits<FontPlatformData> {
- static const bool emptyValueIsZero = true;
- static const bool needsDestruction = true;
- static const FontPlatformData& emptyValue()
- {
- DEFINE_STATIC_LOCAL(FontPlatformData, key, (0.f, false, false));
- return key;
- }
- static void constructDeletedValue(FontPlatformData& slot)
- {
- new (NotNull, &slot) FontPlatformData(HashTableDeletedValue);
- }
- static bool isDeletedValue(const FontPlatformData& value)
- {
- return value.isHashTableDeletedValue();
- }
-};
-
-typedef HashMap<FontPlatformData, pair<RefPtr<SimpleFontData>, unsigned>, FontDataCacheKeyHash, FontDataCacheKeyTraits> FontDataCache;
-
-static FontDataCache* gFontDataCache = 0;
-
-#if !OS(ANDROID)
-const int cMaxInactiveFontData = 250;
-const int cTargetInactiveFontData = 200;
-#else
-const int cMaxInactiveFontData = 225;
-const int cTargetInactiveFontData = 200;
-#endif
-static ListHashSet<RefPtr<SimpleFontData> >* gInactiveFontData = 0;
-
-PassRefPtr<SimpleFontData> FontCache::getFontResourceData(const FontDescription& fontDescription, const AtomicString& family, bool checkingAlternateName, ShouldRetain shouldRetain)
-{
- FontPlatformData* platformData = getFontResourcePlatformData(fontDescription, family, checkingAlternateName);
- if (!platformData)
- return 0;
-
- return getFontResourceData(platformData, shouldRetain);
-}
-
-PassRefPtr<SimpleFontData> FontCache::getFontResourceData(const FontPlatformData* platformData, ShouldRetain shouldRetain)
-{
- if (!platformData)
- return 0;
-
-#if !ASSERT_DISABLED
- if (shouldRetain == DoNotRetain)
- ASSERT(m_purgePreventCount);
-#endif
-
- if (!gFontDataCache) {
- gFontDataCache = new FontDataCache;
- gInactiveFontData = new ListHashSet<RefPtr<SimpleFontData> >;
- }
-
- FontDataCache::iterator result = gFontDataCache->find(*platformData);
- if (result == gFontDataCache->end()) {
- pair<RefPtr<SimpleFontData>, unsigned> newValue(SimpleFontData::create(*platformData), shouldRetain == Retain ? 1 : 0);
- gFontDataCache->set(*platformData, newValue);
- if (shouldRetain == DoNotRetain)
- gInactiveFontData->add(newValue.first);
- return newValue.first.release();
- }
-
- if (!result.get()->value.second) {
- ASSERT(gInactiveFontData->contains(result.get()->value.first));
- gInactiveFontData->remove(result.get()->value.first);
- }
-
- if (shouldRetain == Retain)
- result.get()->value.second++;
- else if (!result.get()->value.second) {
- // If shouldRetain is DoNotRetain and count is 0, we want to remove the fontData from
- // gInactiveFontData (above) and re-add here to update LRU position.
- gInactiveFontData->add(result.get()->value.first);
- }
-
- return result.get()->value.first;
-}
-
-bool FontCache::isPlatformFontAvailable(const FontDescription& fontDescription, const AtomicString& family, bool checkingAlternateName)
-{
- return getFontResourcePlatformData(fontDescription, family, checkingAlternateName);
-}
-
-SimpleFontData* FontCache::getNonRetainedLastResortFallbackFont(const FontDescription& fontDescription)
-{
- return getLastResortFallbackFont(fontDescription, DoNotRetain).leakRef();
-}
-
-void FontCache::releaseFontData(const SimpleFontData* fontData)
-{
- ASSERT(gFontDataCache);
- ASSERT(!fontData->isCustomFont());
-
- FontDataCache::iterator it = gFontDataCache->find(fontData->platformData());
- ASSERT(it != gFontDataCache->end());
- if (it == gFontDataCache->end())
- return;
-
- ASSERT(it->value.second);
- if (!--it->value.second)
- gInactiveFontData->add(it->value.first);
-}
-
-void FontCache::purgeInactiveFontDataIfNeeded()
-{
- if (gInactiveFontData && !m_purgePreventCount && gInactiveFontData->size() > cMaxInactiveFontData)
- purgeInactiveFontData(gInactiveFontData->size() - cTargetInactiveFontData);
-}
-
-void FontCache::purgeInactiveFontData(int count)
-{
- if (!gInactiveFontData || m_purgePreventCount)
- return;
-
- static bool isPurging; // Guard against reentry when e.g. a deleted FontData releases its small caps FontData.
- if (isPurging)
- return;
-
- isPurging = true;
-
- Vector<RefPtr<SimpleFontData>, 20> fontDataToDelete;
- ListHashSet<RefPtr<SimpleFontData> >::iterator end = gInactiveFontData->end();
- ListHashSet<RefPtr<SimpleFontData> >::iterator it = gInactiveFontData->begin();
- for (int i = 0; i < count && it != end; ++it, ++i) {
- RefPtr<SimpleFontData>& fontData = *it.get();
- gFontDataCache->remove(fontData->platformData());
- // We should not delete SimpleFontData here because deletion can modify gInactiveFontData. See http://trac.webkit.org/changeset/44011
- fontDataToDelete.append(fontData);
- }
-
- if (it == end) {
- // Removed everything
- gInactiveFontData->clear();
- } else {
- for (int i = 0; i < count; ++i)
- gInactiveFontData->remove(gInactiveFontData->begin());
- }
-
- fontDataToDelete.clear();
-
- if (gFontPlatformDataCache) {
- Vector<FontPlatformDataCacheKey> keysToRemove;
- keysToRemove.reserveInitialCapacity(gFontPlatformDataCache->size());
- FontPlatformDataCache::iterator platformDataEnd = gFontPlatformDataCache->end();
- for (FontPlatformDataCache::iterator platformData = gFontPlatformDataCache->begin(); platformData != platformDataEnd; ++platformData) {
- if (platformData->value && !gFontDataCache->contains(*platformData->value))
- keysToRemove.append(platformData->key);
- }
-
- size_t keysToRemoveCount = keysToRemove.size();
- for (size_t i = 0; i < keysToRemoveCount; ++i)
- delete gFontPlatformDataCache->take(keysToRemove[i]);
- }
-
-#if ENABLE(OPENTYPE_VERTICAL)
- FontVerticalDataCache& fontVerticalDataCache = fontVerticalDataCacheInstance();
- if (!fontVerticalDataCache.isEmpty()) {
- // Mark & sweep unused verticalData
- FontVerticalDataCache::iterator verticalDataEnd = fontVerticalDataCache.end();
- for (FontVerticalDataCache::iterator verticalData = fontVerticalDataCache.begin(); verticalData != verticalDataEnd; ++verticalData) {
- if (verticalData->value)
- verticalData->value->m_inFontCache = false;
- }
- FontDataCache::iterator fontDataEnd = gFontDataCache->end();
- for (FontDataCache::iterator fontData = gFontDataCache->begin(); fontData != fontDataEnd; ++fontData) {
- OpenTypeVerticalData* verticalData = const_cast<OpenTypeVerticalData*>(fontData->value.first->verticalData());
- if (verticalData)
- verticalData->m_inFontCache = true;
- }
- Vector<FontFileKey> keysToRemove;
- keysToRemove.reserveInitialCapacity(fontVerticalDataCache.size());
- for (FontVerticalDataCache::iterator verticalData = fontVerticalDataCache.begin(); verticalData != verticalDataEnd; ++verticalData) {
- if (!verticalData->value || !verticalData->value->m_inFontCache)
- keysToRemove.append(verticalData->key);
- }
- for (size_t i = 0, count = keysToRemove.size(); i < count; ++i)
- fontVerticalDataCache.take(keysToRemove[i]);
- }
-#endif
-
- isPurging = false;
-}
-
-size_t FontCache::fontDataCount()
-{
- if (gFontDataCache)
- return gFontDataCache->size();
- return 0;
-}
-
-size_t FontCache::inactiveFontDataCount()
-{
- if (gInactiveFontData)
- return gInactiveFontData->size();
- return 0;
-}
-
-PassRefPtr<FontData> FontCache::getFontData(const Font& font, int& familyIndex, FontSelector* fontSelector)
-{
- RefPtr<FontData> result;
-
- int startIndex = familyIndex;
- const FontFamily* startFamily = &font.fontDescription().family();
- for (int i = 0; startFamily && i < startIndex; i++)
- startFamily = startFamily->next();
- const FontFamily* currFamily = startFamily;
- while (currFamily && !result) {
- familyIndex++;
- if (currFamily->family().length()) {
- if (fontSelector)
- result = fontSelector->getFontData(font.fontDescription(), currFamily->family());
-
- if (!result)
- result = getFontResourceData(font.fontDescription(), currFamily->family());
- }
- currFamily = currFamily->next();
- }
-
- if (!currFamily)
- familyIndex = cAllFamiliesScanned;
-
- if (!result)
- // We didn't find a font. Try to find a similar font using our own specific knowledge about our platform.
- // For example on OS X, we know to map any families containing the words Arabic, Pashto, or Urdu to the
- // Geeza Pro font.
- result = getSimilarFontPlatformData(font);
-
- if (!result && startIndex == 0) {
- // If it's the primary font that we couldn't find, we try the following. In all other cases, we will
- // just use per-character system fallback.
-
- if (fontSelector) {
- // Try the user's preferred standard font.
- if (RefPtr<FontData> data = fontSelector->getFontData(font.fontDescription(), standardFamily))
- return data.release();
- }
-
- // Still no result. Hand back our last resort fallback font.
- result = getLastResortFallbackFont(font.fontDescription());
- }
- return result.release();
-}
-
-static HashSet<FontSelector*>* gClients;
-
-void FontCache::addClient(FontSelector* client)
-{
- if (!gClients)
- gClients = new HashSet<FontSelector*>;
-
- ASSERT(!gClients->contains(client));
- gClients->add(client);
-}
-
-void FontCache::removeClient(FontSelector* client)
-{
- ASSERT(gClients);
- ASSERT(gClients->contains(client));
-
- gClients->remove(client);
-}
-
-static unsigned short gGeneration = 0;
-
-unsigned short FontCache::generation()
-{
- return gGeneration;
-}
-
-void FontCache::invalidate()
-{
- if (!gClients) {
- ASSERT(!gFontPlatformDataCache);
- return;
- }
-
- if (gFontPlatformDataCache) {
- deleteAllValues(*gFontPlatformDataCache);
- delete gFontPlatformDataCache;
- gFontPlatformDataCache = new FontPlatformDataCache;
- }
-
- gGeneration++;
-
- Vector<RefPtr<FontSelector> > clients;
- size_t numClients = gClients->size();
- clients.reserveInitialCapacity(numClients);
- HashSet<FontSelector*>::iterator end = gClients->end();
- for (HashSet<FontSelector*>::iterator it = gClients->begin(); it != end; ++it)
- clients.append(*it);
-
- ASSERT(numClients == clients.size());
- for (size_t i = 0; i < numClients; ++i)
- clients[i]->fontCacheInvalidated();
-
- purgeInactiveFontData();
-}
-
-const FontPlatformData* FontCache::getFallbackFontData(const FontDescription& description)
-{
- DEFINE_STATIC_LOCAL(const AtomicString, sansStr, ("Sans", AtomicString::ConstructFromLiteral));
- DEFINE_STATIC_LOCAL(const AtomicString, serifStr, ("Serif", AtomicString::ConstructFromLiteral));
- DEFINE_STATIC_LOCAL(const AtomicString, monospaceStr, ("Monospace", AtomicString::ConstructFromLiteral));
-
- FontPlatformData* fontPlatformData = 0;
- switch (description.genericFamily()) {
- case FontDescription::SerifFamily:
- fontPlatformData = getFontResourcePlatformData(description, serifStr);
- break;
- case FontDescription::MonospaceFamily:
- fontPlatformData = getFontResourcePlatformData(description, monospaceStr);
- break;
- case FontDescription::SansSerifFamily:
- default:
- fontPlatformData = getFontResourcePlatformData(description, sansStr);
- break;
- }
-
- return fontPlatformData;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/FontCache.h b/chromium/third_party/WebKit/Source/core/platform/graphics/FontCache.h
deleted file mode 100644
index 882b5eeb7b1..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/FontCache.h
+++ /dev/null
@@ -1,168 +0,0 @@
-/*
- * Copyright (C) 2006, 2008 Apple Computer, Inc. All rights reserved.
- * Copyright (C) 2007-2008 Torch Mobile, Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef FontCache_h
-#define FontCache_h
-
-#include <limits.h>
-#include "wtf/Forward.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefPtr.h"
-#include "wtf/Vector.h"
-#include "wtf/text/CString.h"
-#include "wtf/text/WTFString.h"
-#include "wtf/unicode/Unicode.h"
-
-#if OS(WIN)
-#include <windows.h>
-#include <objidl.h>
-#include <mlang.h>
-#endif
-
-#if OS(WIN) && !ENABLE(GDI_FONTS_ON_WINDOWS)
-#include "SkFontMgr.h"
-#endif
-
-class SkTypeface;
-
-namespace WebCore {
-
-class Font;
-class FontPlatformData;
-class FontData;
-class FontDescription;
-class FontSelector;
-class OpenTypeVerticalData;
-class SimpleFontData;
-
-class FontCache {
- friend class FontCachePurgePreventer;
-
- WTF_MAKE_NONCOPYABLE(FontCache); WTF_MAKE_FAST_ALLOCATED;
-public:
- friend FontCache* fontCache();
-
- enum ShouldRetain { Retain, DoNotRetain };
-
- PassRefPtr<FontData> getFontData(const Font&, int& familyIndex, FontSelector*);
- void releaseFontData(const SimpleFontData*);
-
- // This method is implemented by the plaform and used by
- // FontFastPath to lookup the font for a given character.
- PassRefPtr<SimpleFontData> getFontDataForCharacter(const Font&, UChar32);
-
- // Also implemented by the platform.
- void platformInit();
-
- void getTraitsInFamily(const AtomicString&, Vector<unsigned>&);
-
- PassRefPtr<SimpleFontData> getFontResourceData(const FontDescription&, const AtomicString&, bool checkingAlternateName = false, ShouldRetain = Retain);
- PassRefPtr<SimpleFontData> getLastResortFallbackFont(const FontDescription&, ShouldRetain = Retain);
- SimpleFontData* getNonRetainedLastResortFallbackFont(const FontDescription&);
- bool isPlatformFontAvailable(const FontDescription&, const AtomicString&, bool checkingAlternateName = false);
-
- void addClient(FontSelector*);
- void removeClient(FontSelector*);
-
- unsigned short generation();
- void invalidate();
-
- size_t fontDataCount();
- size_t inactiveFontDataCount();
- void purgeInactiveFontData(int count = INT_MAX);
-
-#if OS(WIN)
- PassRefPtr<SimpleFontData> fontDataFromDescriptionAndLogFont(const FontDescription&, ShouldRetain, const LOGFONT&, wchar_t* outFontFamilyName);
-#endif
-
-#if ENABLE(OPENTYPE_VERTICAL)
- typedef uint32_t FontFileKey;
- PassRefPtr<OpenTypeVerticalData> getVerticalData(const FontFileKey&, const FontPlatformData&);
-#endif
-
- struct SimpleFontFamily {
- String name;
- bool isBold;
- bool isItalic;
- };
- static void getFontFamilyForCharacter(UChar32, const char* preferredLocale, SimpleFontFamily*);
-
-private:
- FontCache();
- ~FontCache();
-
- void disablePurging() { m_purgePreventCount++; }
- void enablePurging()
- {
- ASSERT(m_purgePreventCount);
- if (!--m_purgePreventCount)
- purgeInactiveFontDataIfNeeded();
- }
-
- void purgeInactiveFontDataIfNeeded();
-
- // FIXME: This method should eventually be removed.
- FontPlatformData* getFontResourcePlatformData(const FontDescription&, const AtomicString& family, bool checkingAlternateName = false);
-
- // These methods are implemented by each platform.
- PassRefPtr<SimpleFontData> getSimilarFontPlatformData(const Font&);
- FontPlatformData* createFontPlatformData(const FontDescription&, const AtomicString& family);
-
- // Implemented on skia platforms.
- SkTypeface* createTypeface(const FontDescription&, const AtomicString& family, CString& name);
-
- PassRefPtr<SimpleFontData> getFontResourceData(const FontPlatformData*, ShouldRetain = Retain);
- const FontPlatformData* getFallbackFontData(const FontDescription&);
-
- // Don't purge if this count is > 0;
- int m_purgePreventCount;
-
-#if OS(WIN) && !ENABLE(GDI_FONTS_ON_WINDOWS)
- OwnPtr<SkFontMgr> m_fontManager;
-#endif
-
-#if OS(MACOSX) || OS(ANDROID)
- friend class ComplexTextController;
-#endif
- friend class SimpleFontData; // For getFontResourceData(const FontPlatformData*)
- friend class FontFallbackList;
-};
-
-// Get the global fontCache.
-FontCache* fontCache();
-
-class FontCachePurgePreventer {
-public:
- FontCachePurgePreventer() { fontCache()->disablePurging(); }
- ~FontCachePurgePreventer() { fontCache()->enablePurging(); }
-};
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/FontCustomPlatformData.h b/chromium/third_party/WebKit/Source/core/platform/graphics/FontCustomPlatformData.h
deleted file mode 100644
index f07a1176555..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/FontCustomPlatformData.h
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
- * Copyright (C) 2007 Apple Computer, Inc.
- * Copyright (c) 2007, 2008, 2009, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef FontCustomPlatformData_h
-#define FontCustomPlatformData_h
-
-#include "core/platform/graphics/FontOrientation.h"
-#include "core/platform/graphics/FontWidthVariant.h"
-#include "wtf/Forward.h"
-#include "wtf/Noncopyable.h"
-#include "wtf/text/WTFString.h"
-
-#if OS(WIN) && ENABLE(GDI_FONTS_ON_WINDOWS)
-#include <windows.h>
-#endif
-
-#if OS(MACOSX)
-#include "wtf/RetainPtr.h"
-#include <CoreFoundation/CFBase.h>
-typedef struct CGFont* CGFontRef;
-#endif
-
-#if OS(MACOSX) || OS(POSIX) || (OS(WIN) && !ENABLE(GDI_FONTS_ON_WINDOWS))
-#include "wtf/RefPtr.h"
-class SkTypeface;
-#endif
-
-namespace WebCore {
-
-class FontPlatformData;
-class SharedBuffer;
-
-class FontCustomPlatformData {
- WTF_MAKE_NONCOPYABLE(FontCustomPlatformData);
-public:
- static PassOwnPtr<FontCustomPlatformData> create(SharedBuffer*);
- ~FontCustomPlatformData();
-
- FontPlatformData fontPlatformData(int size, bool bold, bool italic, FontOrientation = Horizontal, FontWidthVariant = RegularWidth);
-
- static bool supportsFormat(const String&);
-
-private:
-#if OS(WIN) && ENABLE(GDI_FONTS_ON_WINDOWS)
- FontCustomPlatformData(HANDLE fontReference, const String& name);
- HANDLE m_fontReference;
- String m_name;
-#elif OS(MACOSX)
- explicit FontCustomPlatformData(CGFontRef, PassRefPtr<SkTypeface>);
- RetainPtr<CGFontRef> m_cgFont;
- RefPtr<SkTypeface> m_typeface;
-#elif OS(POSIX) || (OS(WIN) && !ENABLE(GDI_FONTS_ON_WINDOWS))
- explicit FontCustomPlatformData(PassRefPtr<SkTypeface>);
- RefPtr<SkTypeface> m_typeface;
-#endif
-};
-
-} // namespace WebCore
-
-#endif // FontCustomPlatformData_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/FontData.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/FontData.cpp
deleted file mode 100644
index 60449332afd..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/FontData.cpp
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright (C) 2008 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/FontData.h"
-
-namespace WebCore {
-
-FontData::~FontData()
-{
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/FontData.h b/chromium/third_party/WebKit/Source/core/platform/graphics/FontData.h
deleted file mode 100644
index f4d64ab1ec7..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/FontData.h
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * Copyright (C) 2008 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef FontData_h
-#define FontData_h
-
-#include "wtf/FastAllocBase.h"
-#include "wtf/Forward.h"
-#include "wtf/Noncopyable.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/unicode/Unicode.h"
-
-namespace WebCore {
-
-class SimpleFontData;
-
-class FontData : public RefCounted<FontData> {
- WTF_MAKE_NONCOPYABLE(FontData); WTF_MAKE_FAST_ALLOCATED;
-public:
- FontData()
- : m_maxGlyphPageTreeLevel(0)
- {
- }
-
- virtual ~FontData();
-
- virtual const SimpleFontData* fontDataForCharacter(UChar32) const = 0;
- virtual bool containsCharacters(const UChar*, int length) const = 0;
- virtual bool isCustomFont() const = 0;
- virtual bool isLoading() const = 0;
- virtual bool isSegmented() const = 0;
-
- void setMaxGlyphPageTreeLevel(unsigned level) const { m_maxGlyphPageTreeLevel = level; }
- unsigned maxGlyphPageTreeLevel() const { return m_maxGlyphPageTreeLevel; }
-
-#ifndef NDEBUG
- virtual String description() const = 0;
-#endif
-
-private:
- mutable unsigned m_maxGlyphPageTreeLevel;
-};
-
-} // namespace WebCore
-
-#endif // FontData_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/FontDescription.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/FontDescription.cpp
deleted file mode 100644
index 716251210e9..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/FontDescription.cpp
+++ /dev/null
@@ -1,105 +0,0 @@
-/*
- * Copyright (C) 2007 Nicholas Shanks <contact@nickshanks.com>
- * Copyright (C) 2008 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/FontDescription.h"
-
-namespace WebCore {
-
-struct SameSizeAsFontDescription {
- FontFamily familyList;
- RefPtr<FontFeatureSettings> m_featureSettings;
- float sizes[2];
- // FXIME: Make them fit into one word.
- uint32_t bitfields;
- uint32_t bitfields2 : 8;
-};
-
-COMPILE_ASSERT(sizeof(FontDescription) == sizeof(SameSizeAsFontDescription), FontDescription_should_stay_small);
-
-FontWeight FontDescription::lighterWeight(void) const
-{
- switch (m_weight) {
- case FontWeight100:
- case FontWeight200:
- case FontWeight300:
- case FontWeight400:
- case FontWeight500:
- return FontWeight100;
-
- case FontWeight600:
- case FontWeight700:
- return FontWeight400;
-
- case FontWeight800:
- case FontWeight900:
- return FontWeight700;
- }
- ASSERT_NOT_REACHED();
- return FontWeightNormal;
-}
-
-FontWeight FontDescription::bolderWeight(void) const
-{
- switch (m_weight) {
- case FontWeight100:
- case FontWeight200:
- case FontWeight300:
- return FontWeight400;
-
- case FontWeight400:
- case FontWeight500:
- return FontWeight700;
-
- case FontWeight600:
- case FontWeight700:
- case FontWeight800:
- case FontWeight900:
- return FontWeight900;
- }
- ASSERT_NOT_REACHED();
- return FontWeightNormal;
-}
-
-FontTraitsMask FontDescription::traitsMask() const
-{
- return static_cast<FontTraitsMask>((m_italic ? FontStyleItalicMask : FontStyleNormalMask)
- | (m_smallCaps ? FontVariantSmallCapsMask : FontVariantNormalMask)
- | (FontWeight100Mask << (m_weight - FontWeight100)));
-
-}
-
-FontDescription FontDescription::makeNormalFeatureSettings() const
-{
- FontDescription normalDescription(*this);
- normalDescription.setFeatureSettings(0);
- return normalDescription;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/FontDescription.h b/chromium/third_party/WebKit/Source/core/platform/graphics/FontDescription.h
deleted file mode 100644
index 7aa15222676..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/FontDescription.h
+++ /dev/null
@@ -1,231 +0,0 @@
-/*
- * Copyright (C) 2000 Lars Knoll (knoll@kde.org)
- * (C) 2000 Antti Koivisto (koivisto@kde.org)
- * (C) 2000 Dirk Mueller (mueller@kde.org)
- * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
- * Copyright (C) 2007 Nicholas Shanks <webkit@nickshanks.com>
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIother.m_ If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USm_
- *
- */
-
-#ifndef FontDescription_h
-#define FontDescription_h
-
-#include "FontFamilyNames.h"
-#include "core/platform/graphics/FontFamily.h"
-#include "core/platform/graphics/FontFeatureSettings.h"
-#include "core/platform/graphics/FontOrientation.h"
-#include "core/platform/graphics/FontSmoothingMode.h"
-#include "core/platform/graphics/FontTraitsMask.h"
-#include "core/platform/graphics/FontWidthVariant.h"
-#include "core/platform/graphics/TextRenderingMode.h"
-#include "core/platform/text/NonCJKGlyphOrientation.h"
-#include "wtf/MathExtras.h"
-
-#include "wtf/RefPtr.h"
-
-namespace WebCore {
-
-using namespace FontFamilyNames;
-
-enum FontWeight {
- FontWeight100,
- FontWeight200,
- FontWeight300,
- FontWeight400,
- FontWeight500,
- FontWeight600,
- FontWeight700,
- FontWeight800,
- FontWeight900,
- FontWeightNormal = FontWeight400,
- FontWeightBold = FontWeight700
-};
-
-enum FontItalic {
- FontItalicOff = 0,
- FontItalicOn = 1
-};
-
-enum FontSmallCaps {
- FontSmallCapsOff = 0,
- FontSmallCapsOn = 1
-};
-
-class FontDescription {
-public:
- enum GenericFamilyType { NoFamily, StandardFamily, SerifFamily, SansSerifFamily,
- MonospaceFamily, CursiveFamily, FantasyFamily, PictographFamily };
-
- enum Kerning { AutoKerning, NormalKerning, NoneKerning };
-
- enum LigaturesState { NormalLigaturesState, DisabledLigaturesState, EnabledLigaturesState };
-
- FontDescription()
- : m_specifiedSize(0)
- , m_computedSize(0)
- , m_orientation(Horizontal)
- , m_nonCJKGlyphOrientation(NonCJKGlyphOrientationVerticalRight)
- , m_widthVariant(RegularWidth)
- , m_italic(FontItalicOff)
- , m_smallCaps(FontSmallCapsOff)
- , m_isAbsoluteSize(false)
- , m_weight(FontWeightNormal)
- , m_genericFamily(NoFamily)
- , m_usePrinterFont(false)
- , m_kerning(AutoKerning)
- , m_commonLigaturesState(NormalLigaturesState)
- , m_discretionaryLigaturesState(NormalLigaturesState)
- , m_historicalLigaturesState(NormalLigaturesState)
- , m_keywordSize(0)
- , m_fontSmoothing(AutoSmoothing)
- , m_textRendering(AutoTextRendering)
- , m_isSpecifiedFont(false)
- , m_script(USCRIPT_COMMON)
- {
- }
-
- bool operator==(const FontDescription&) const;
- bool operator!=(const FontDescription& other) const { return !(*this == other); }
-
- const FontFamily& family() const { return m_familyList; }
- FontFamily& firstFamily() { return m_familyList; }
- float specifiedSize() const { return m_specifiedSize; }
- float computedSize() const { return m_computedSize; }
- FontItalic italic() const { return static_cast<FontItalic>(m_italic); }
- int computedPixelSize() const { return int(m_computedSize + 0.5f); }
- FontSmallCaps smallCaps() const { return static_cast<FontSmallCaps>(m_smallCaps); }
- bool isAbsoluteSize() const { return m_isAbsoluteSize; }
- FontWeight weight() const { return static_cast<FontWeight>(m_weight); }
- FontWeight lighterWeight() const;
- FontWeight bolderWeight() const;
- GenericFamilyType genericFamily() const { return static_cast<GenericFamilyType>(m_genericFamily); }
- bool usePrinterFont() const { return m_usePrinterFont; }
- // only use fixed default size when there is only one font family, and that family is "monospace"
- bool useFixedDefaultSize() const { return genericFamily() == MonospaceFamily && !family().next() && family().family() == monospaceFamily; }
- Kerning kerning() const { return static_cast<Kerning>(m_kerning); }
- LigaturesState commonLigaturesState() const { return static_cast<LigaturesState>(m_commonLigaturesState); }
- LigaturesState discretionaryLigaturesState() const { return static_cast<LigaturesState>(m_discretionaryLigaturesState); }
- LigaturesState historicalLigaturesState() const { return static_cast<LigaturesState>(m_historicalLigaturesState); }
- unsigned keywordSize() const { return m_keywordSize; }
- FontSmoothingMode fontSmoothing() const { return static_cast<FontSmoothingMode>(m_fontSmoothing); }
- TextRenderingMode textRenderingMode() const { return static_cast<TextRenderingMode>(m_textRendering); }
- UScriptCode script() const { return static_cast<UScriptCode>(m_script); }
-
- FontTraitsMask traitsMask() const;
- bool isSpecifiedFont() const { return m_isSpecifiedFont; }
- FontOrientation orientation() const { return static_cast<FontOrientation>(m_orientation); }
- NonCJKGlyphOrientation nonCJKGlyphOrientation() const { return static_cast<NonCJKGlyphOrientation>(m_nonCJKGlyphOrientation); }
- FontWidthVariant widthVariant() const { return static_cast<FontWidthVariant>(m_widthVariant); }
- FontFeatureSettings* featureSettings() const { return m_featureSettings.get(); }
- FontDescription makeNormalFeatureSettings() const;
-
- void setFamily(const FontFamily& family) { m_familyList = family; }
- void setComputedSize(float s) { m_computedSize = clampToFloat(s); }
- void setSpecifiedSize(float s) { m_specifiedSize = clampToFloat(s); }
- void setItalic(FontItalic i) { m_italic = i; }
- void setItalic(bool i) { setItalic(i ? FontItalicOn : FontItalicOff); }
- void setSmallCaps(FontSmallCaps c) { m_smallCaps = c; }
- void setSmallCaps(bool c) { setSmallCaps(c ? FontSmallCapsOn : FontSmallCapsOff); }
- void setIsAbsoluteSize(bool s) { m_isAbsoluteSize = s; }
- void setWeight(FontWeight w) { m_weight = w; }
- void setGenericFamily(GenericFamilyType genericFamily) { m_genericFamily = genericFamily; }
-#if OS(MACOSX)
- void setUsePrinterFont(bool) { }
-#else
- void setUsePrinterFont(bool p) { m_usePrinterFont = p; }
-#endif
- void setKerning(Kerning kerning) { m_kerning = kerning; }
- void setCommonLigaturesState(LigaturesState commonLigaturesState) { m_commonLigaturesState = commonLigaturesState; }
- void setDiscretionaryLigaturesState(LigaturesState discretionaryLigaturesState) { m_discretionaryLigaturesState = discretionaryLigaturesState; }
- void setHistoricalLigaturesState(LigaturesState historicalLigaturesState) { m_historicalLigaturesState = historicalLigaturesState; }
- void setKeywordSize(unsigned s) { m_keywordSize = s; }
- void setFontSmoothing(FontSmoothingMode smoothing) { m_fontSmoothing = smoothing; }
- void setTextRenderingMode(TextRenderingMode rendering) { m_textRendering = rendering; }
- void setIsSpecifiedFont(bool isSpecifiedFont) { m_isSpecifiedFont = isSpecifiedFont; }
- void setOrientation(FontOrientation orientation) { m_orientation = orientation; }
- void setNonCJKGlyphOrientation(NonCJKGlyphOrientation orientation) { m_nonCJKGlyphOrientation = orientation; }
- void setWidthVariant(FontWidthVariant widthVariant) { m_widthVariant = widthVariant; }
- void setScript(UScriptCode s) { m_script = s; }
- void setFeatureSettings(PassRefPtr<FontFeatureSettings> settings) { m_featureSettings = settings; }
-
-private:
- FontFamily m_familyList; // The list of font families to be used.
- RefPtr<FontFeatureSettings> m_featureSettings;
-
- float m_specifiedSize; // Specified CSS value. Independent of rendering issues such as integer
- // rounding, minimum font sizes, and zooming.
- float m_computedSize; // Computed size adjusted for the minimum font size and the zoom factor.
-
- unsigned m_orientation : 1; // FontOrientation - Whether the font is rendering on a horizontal line or a vertical line.
- unsigned m_nonCJKGlyphOrientation : 1; // NonCJKGlyphOrientation - Only used by vertical text. Determines the default orientation for non-ideograph glyphs.
-
- unsigned m_widthVariant : 2; // FontWidthVariant
-
- unsigned m_italic : 1; // FontItalic
- unsigned m_smallCaps : 1; // FontSmallCaps
- unsigned m_isAbsoluteSize : 1; // Whether or not CSS specified an explicit size
- // (logical sizes like "medium" don't count).
- unsigned m_weight : 8; // FontWeight
- unsigned m_genericFamily : 3; // GenericFamilyType
- unsigned m_usePrinterFont : 1;
-
- unsigned m_kerning : 2; // Kerning
-
- unsigned m_commonLigaturesState : 2;
- unsigned m_discretionaryLigaturesState : 2;
- unsigned m_historicalLigaturesState : 2;
-
- unsigned m_keywordSize : 4; // We cache whether or not a font is currently represented by a CSS keyword (e.g., medium). If so,
- // then we can accurately translate across different generic families to adjust for different preference settings
- // (e.g., 13px monospace vs. 16px everything else). Sizes are 1-8 (like the HTML size values for <font>).
-
- unsigned m_fontSmoothing : 2; // FontSmoothingMode
- unsigned m_textRendering : 2; // TextRenderingMode
- unsigned m_isSpecifiedFont : 1; // True if a web page specifies a non-generic font family as the first font family.
- unsigned m_script : 7; // Used to help choose an appropriate font for generic font families.
-};
-
-inline bool FontDescription::operator==(const FontDescription& other) const
-{
- return m_familyList == other.m_familyList
- && m_specifiedSize == other.m_specifiedSize
- && m_computedSize == other.m_computedSize
- && m_italic == other.m_italic
- && m_smallCaps == other.m_smallCaps
- && m_isAbsoluteSize == other.m_isAbsoluteSize
- && m_weight == other.m_weight
- && m_genericFamily == other.m_genericFamily
- && m_usePrinterFont == other.m_usePrinterFont
- && m_kerning == other.m_kerning
- && m_commonLigaturesState == other.m_commonLigaturesState
- && m_discretionaryLigaturesState == other.m_discretionaryLigaturesState
- && m_historicalLigaturesState == other.m_historicalLigaturesState
- && m_keywordSize == other.m_keywordSize
- && m_fontSmoothing == other.m_fontSmoothing
- && m_textRendering == other.m_textRendering
- && m_isSpecifiedFont == other.m_isSpecifiedFont
- && m_orientation == other.m_orientation
- && m_nonCJKGlyphOrientation == other.m_nonCJKGlyphOrientation
- && m_widthVariant == other.m_widthVariant
- && m_script == other.m_script
- && m_featureSettings == other.m_featureSettings;
-}
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/FontFallbackList.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/FontFallbackList.cpp
deleted file mode 100644
index a68e8ba9430..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/FontFallbackList.cpp
+++ /dev/null
@@ -1,139 +0,0 @@
-/*
- * Copyright (C) 2006 Apple Computer, Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/FontFallbackList.h"
-
-#include "core/platform/graphics/FontCache.h"
-#include "core/platform/graphics/SegmentedFontData.h"
-
-namespace WebCore {
-
-FontFallbackList::FontFallbackList()
- : m_pageZero(0)
- , m_cachedPrimarySimpleFontData(0)
- , m_fontSelector(0)
- , m_fontSelectorVersion(0)
- , m_familyIndex(0)
- , m_generation(fontCache()->generation())
- , m_pitch(UnknownPitch)
- , m_loadingCustomFonts(false)
-{
-}
-
-void FontFallbackList::invalidate(PassRefPtr<FontSelector> fontSelector)
-{
- releaseFontData();
- m_fontList.clear();
- m_pageZero = 0;
- m_pages.clear();
- m_cachedPrimarySimpleFontData = 0;
- m_familyIndex = 0;
- m_pitch = UnknownPitch;
- m_loadingCustomFonts = false;
- m_fontSelector = fontSelector;
- m_fontSelectorVersion = m_fontSelector ? m_fontSelector->version() : 0;
- m_generation = fontCache()->generation();
- m_widthCache.clear();
-}
-
-void FontFallbackList::releaseFontData()
-{
- unsigned numFonts = m_fontList.size();
- for (unsigned i = 0; i < numFonts; ++i) {
- if (!m_fontList[i]->isCustomFont()) {
- ASSERT(!m_fontList[i]->isSegmented());
- fontCache()->releaseFontData(static_cast<const SimpleFontData*>(m_fontList[i].get()));
- }
- }
-}
-
-void FontFallbackList::determinePitch(const Font* font) const
-{
- const FontData* fontData = primaryFontData(font);
- if (!fontData->isSegmented())
- m_pitch = static_cast<const SimpleFontData*>(fontData)->pitch();
- else {
- const SegmentedFontData* segmentedFontData = static_cast<const SegmentedFontData*>(fontData);
- unsigned numRanges = segmentedFontData->numRanges();
- if (numRanges == 1)
- m_pitch = segmentedFontData->rangeAt(0).fontData()->pitch();
- else
- m_pitch = VariablePitch;
- }
-}
-
-bool FontFallbackList::loadingCustomFonts() const
-{
- if (m_loadingCustomFonts)
- return true;
-
- unsigned numFonts = m_fontList.size();
- for (unsigned i = 0; i < numFonts; ++i) {
- if (m_fontList[i]->isCustomFont() && m_fontList[i]->isLoading()) {
- m_loadingCustomFonts = true;
- return true;
- }
- }
- return false;
-}
-
-const FontData* FontFallbackList::fontDataAt(const Font* font, unsigned realizedFontIndex) const
-{
- if (realizedFontIndex < m_fontList.size())
- return m_fontList[realizedFontIndex].get(); // This fallback font is already in our list.
-
- // Make sure we're not passing in some crazy value here.
- ASSERT(realizedFontIndex == m_fontList.size());
-
- if (m_familyIndex == cAllFamiliesScanned)
- return 0;
-
- // Ask the font cache for the font data.
- // We are obtaining this font for the first time. We keep track of the families we've looked at before
- // in |m_familyIndex|, so that we never scan the same spot in the list twice. getFontData will adjust our
- // |m_familyIndex| as it scans for the right font to make.
- ASSERT(fontCache()->generation() == m_generation);
- RefPtr<FontData> result = fontCache()->getFontData(*font, m_familyIndex, m_fontSelector.get());
- if (result) {
- m_fontList.append(result);
- if (result->isLoading())
- m_loadingCustomFonts = true;
- }
- return result.get();
-}
-
-void FontFallbackList::setPlatformFont(const FontPlatformData& platformData)
-{
- m_familyIndex = cAllFamiliesScanned;
- ASSERT(fontCache()->generation() == m_generation);
- RefPtr<FontData> fontData = fontCache()->getFontResourceData(&platformData);
- m_fontList.append(fontData);
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/FontFallbackList.h b/chromium/third_party/WebKit/Source/core/platform/graphics/FontFallbackList.h
deleted file mode 100644
index a952158d6df..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/FontFallbackList.h
+++ /dev/null
@@ -1,123 +0,0 @@
-/*
- * Copyright (C) 2006, 2010 Apple Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#ifndef FontFallbackList_h
-#define FontFallbackList_h
-
-#include "core/platform/graphics/FontSelector.h"
-#include "core/platform/graphics/SimpleFontData.h"
-#include "core/platform/graphics/WidthCache.h"
-#include "wtf/Forward.h"
-#include "wtf/MainThread.h"
-
-namespace WebCore {
-
-class Font;
-class GlyphPageTreeNode;
-class GraphicsContext;
-class IntRect;
-class FontDescription;
-class FontPlatformData;
-class FontSelector;
-
-const int cAllFamiliesScanned = -1;
-
-class FontFallbackList : public RefCounted<FontFallbackList> {
- WTF_MAKE_NONCOPYABLE(FontFallbackList);
-public:
- typedef HashMap<int, GlyphPageTreeNode*, DefaultHash<int>::Hash> GlyphPages;
-
- class GlyphPagesStateSaver {
- public:
- GlyphPagesStateSaver(FontFallbackList& fallbackList)
- : m_fallbackList(fallbackList)
- , m_pages(fallbackList.m_pages)
- , m_pageZero(fallbackList.m_pageZero)
- {
- }
-
- ~GlyphPagesStateSaver()
- {
- m_fallbackList.m_pages = m_pages;
- m_fallbackList.m_pageZero = m_pageZero;
- }
-
- private:
- FontFallbackList& m_fallbackList;
- GlyphPages& m_pages;
- GlyphPageTreeNode* m_pageZero;
- };
-
- static PassRefPtr<FontFallbackList> create() { return adoptRef(new FontFallbackList()); }
-
- ~FontFallbackList() { releaseFontData(); }
- void invalidate(PassRefPtr<FontSelector>);
-
- bool isFixedPitch(const Font* f) const { if (m_pitch == UnknownPitch) determinePitch(f); return m_pitch == FixedPitch; };
- void determinePitch(const Font*) const;
-
- bool loadingCustomFonts() const;
-
- FontSelector* fontSelector() const { return m_fontSelector.get(); }
- // FIXME: It should be possible to combine fontSelectorVersion and generation.
- unsigned fontSelectorVersion() const { return m_fontSelectorVersion; }
- unsigned generation() const { return m_generation; }
-
- WidthCache& widthCache() const { return m_widthCache; }
-
-private:
- FontFallbackList();
-
- const SimpleFontData* primarySimpleFontData(const Font* f)
- {
- ASSERT(isMainThread());
- if (!m_cachedPrimarySimpleFontData) {
- m_cachedPrimarySimpleFontData = primaryFontData(f)->fontDataForCharacter(' ');
- if (m_cachedPrimarySimpleFontData)
- m_cachedPrimarySimpleFontData->beginLoadIfNeeded();
- }
- return m_cachedPrimarySimpleFontData;
- }
-
- const FontData* primaryFontData(const Font* f) const { return fontDataAt(f, 0); }
- const FontData* fontDataAt(const Font*, unsigned index) const;
-
- void setPlatformFont(const FontPlatformData&);
-
- void releaseFontData();
-
- mutable Vector<RefPtr<FontData>, 1> m_fontList;
- mutable GlyphPages m_pages;
- mutable GlyphPageTreeNode* m_pageZero;
- mutable const SimpleFontData* m_cachedPrimarySimpleFontData;
- RefPtr<FontSelector> m_fontSelector;
- mutable WidthCache m_widthCache;
- unsigned m_fontSelectorVersion;
- mutable int m_familyIndex;
- unsigned short m_generation;
- mutable unsigned m_pitch : 3; // Pitch
- mutable bool m_loadingCustomFonts : 1;
-
- friend class Font;
-};
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/FontFamily.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/FontFamily.cpp
deleted file mode 100644
index 513c2bf47f4..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/FontFamily.cpp
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Copyright (C) 2004, 2008 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/FontFamily.h"
-
-namespace WebCore {
-
-bool operator==(const FontFamily& a, const FontFamily& b)
-{
- if (a.family() != b.family())
- return false;
- const FontFamily* ap;
- const FontFamily* bp;
- for (ap = a.next(), bp = b.next(); ap != bp; ap = ap->next(), bp = bp->next()) {
- if (!ap || !bp)
- return false;
- if (ap->family() != bp->family())
- return false;
- }
- return true;
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/FontFamily.h b/chromium/third_party/WebKit/Source/core/platform/graphics/FontFamily.h
deleted file mode 100644
index 6c032ed74aa..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/FontFamily.h
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- * Copyright (C) 2003, 2006, 2008 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef FontFamily_h
-#define FontFamily_h
-
-#include "wtf/RefCounted.h"
-#include "wtf/RefPtr.h"
-#include "wtf/text/AtomicString.h"
-
-namespace WebCore {
-
-class SharedFontFamily;
-
-class FontFamily {
-public:
- FontFamily() { }
- ~FontFamily();
-
- void setFamily(const AtomicString& family) { m_family = family; }
- const AtomicString& family() const { return m_family; }
- bool familyIsEmpty() const { return m_family.isEmpty(); }
-
- const FontFamily* next() const;
-
- void appendFamily(PassRefPtr<SharedFontFamily>);
- PassRefPtr<SharedFontFamily> releaseNext();
-
-private:
- AtomicString m_family;
- RefPtr<SharedFontFamily> m_next;
-};
-
-class SharedFontFamily : public FontFamily, public RefCounted<SharedFontFamily> {
-public:
- static PassRefPtr<SharedFontFamily> create()
- {
- return adoptRef(new SharedFontFamily);
- }
-
-private:
- SharedFontFamily() { }
-};
-
-bool operator==(const FontFamily&, const FontFamily&);
-inline bool operator!=(const FontFamily& a, const FontFamily& b) { return !(a == b); }
-
-inline FontFamily::~FontFamily()
-{
- RefPtr<SharedFontFamily> reaper = m_next.release();
- while (reaper && reaper->hasOneRef())
- reaper = reaper->releaseNext(); // implicitly protects reaper->next, then derefs reaper
-}
-
-inline const FontFamily* FontFamily::next() const
-{
- return m_next.get();
-}
-
-inline void FontFamily::appendFamily(PassRefPtr<SharedFontFamily> family)
-{
- m_next = family;
-}
-
-inline PassRefPtr<SharedFontFamily> FontFamily::releaseNext()
-{
- return m_next.release();
-}
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/FontFastPath.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/FontFastPath.cpp
deleted file mode 100644
index aae868ad95f..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/FontFastPath.cpp
+++ /dev/null
@@ -1,612 +0,0 @@
-/**
- * Copyright (C) 2003, 2006, 2010 Apple Inc. All rights reserved.
- * Copyright (C) 2008 Holger Hans Peter Freyther
- * Copyright (C) 2009 Torch Mobile, Inc.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#include "config.h"
-#include "core/platform/graphics/Font.h"
-
-#include "core/platform/graphics/FloatRect.h"
-#include "core/platform/graphics/FontCache.h"
-#include "core/platform/graphics/FontFallbackList.h"
-#include "core/platform/graphics/GlyphBuffer.h"
-#include "core/platform/graphics/GlyphPageTreeNode.h"
-#include "core/platform/graphics/SimpleFontData.h"
-#include "core/platform/graphics/TextRun.h"
-#include "core/platform/graphics/WidthIterator.h"
-#include "wtf/MainThread.h"
-#include "wtf/MathExtras.h"
-#include "wtf/unicode/CharacterNames.h"
-#include "wtf/unicode/Unicode.h"
-
-using namespace WTF;
-using namespace Unicode;
-using namespace std;
-
-namespace WebCore {
-
-static inline bool isInRange(UChar32 character, UChar32 lowerBound, UChar32 upperBound)
-{
- return character >= lowerBound && character <= upperBound;
-}
-
-static bool shouldIgnoreRotation(UChar32 character)
-{
- if (character == 0x000A7 || character == 0x000A9 || character == 0x000AE)
- return true;
-
- if (character == 0x000B6 || character == 0x000BC || character == 0x000BD || character == 0x000BE)
- return true;
-
- if (isInRange(character, 0x002E5, 0x002EB))
- return true;
-
- if (isInRange(character, 0x01100, 0x011FF) || isInRange(character, 0x01401, 0x0167F) || isInRange(character, 0x01800, 0x018FF))
- return true;
-
- if (character == 0x02016 || character == 0x02018 || character == 0x02019 || character == 0x02020 || character == 0x02021
- || character == 0x2030 || character == 0x02031)
- return true;
-
- if (isInRange(character, 0x0203B, 0x0203D) || character == 0x02042 || character == 0x02044 || character == 0x02047
- || character == 0x02048 || character == 0x02049 || character == 0x2051)
- return true;
-
- if (isInRange(character, 0x02065, 0x02069) || isInRange(character, 0x020DD, 0x020E0)
- || isInRange(character, 0x020E2, 0x020E4) || isInRange(character, 0x02100, 0x02117)
- || isInRange(character, 0x02119, 0x02131) || isInRange(character, 0x02133, 0x0213F))
- return true;
-
- if (isInRange(character, 0x02145, 0x0214A) || character == 0x0214C || character == 0x0214D
- || isInRange(character, 0x0214F, 0x0218F))
- return true;
-
- if (isInRange(character, 0x02300, 0x02307) || isInRange(character, 0x0230C, 0x0231F)
- || isInRange(character, 0x02322, 0x0232B) || isInRange(character, 0x0237D, 0x0239A)
- || isInRange(character, 0x023B4, 0x023B6) || isInRange(character, 0x023BA, 0x023CF)
- || isInRange(character, 0x023D1, 0x023DB) || isInRange(character, 0x023E2, 0x024FF))
- return true;
-
- if (isInRange(character, 0x025A0, 0x02619) || isInRange(character, 0x02620, 0x02767)
- || isInRange(character, 0x02776, 0x02793) || isInRange(character, 0x02B12, 0x02B2F)
- || isInRange(character, 0x02B4D, 0x02BFF) || isInRange(character, 0x02E80, 0x03007))
- return true;
-
- if (character == 0x03012 || character == 0x03013 || isInRange(character, 0x03020, 0x0302F)
- || isInRange(character, 0x03031, 0x0309F) || isInRange(character, 0x030A1, 0x030FB)
- || isInRange(character, 0x030FD, 0x0A4CF))
- return true;
-
- if (isInRange(character, 0x0A840, 0x0A87F) || isInRange(character, 0x0A960, 0x0A97F)
- || isInRange(character, 0x0AC00, 0x0D7FF) || isInRange(character, 0x0E000, 0x0FAFF))
- return true;
-
- if (isInRange(character, 0x0FE10, 0x0FE1F) || isInRange(character, 0x0FE30, 0x0FE48)
- || isInRange(character, 0x0FE50, 0x0FE57) || isInRange(character, 0x0FE5F, 0x0FE62)
- || isInRange(character, 0x0FE67, 0x0FE6F))
- return true;
-
- if (isInRange(character, 0x0FF01, 0x0FF07) || isInRange(character, 0x0FF0A, 0x0FF0C)
- || isInRange(character, 0x0FF0E, 0x0FF19) ||isInRange (character, 0x0FF1F, 0x0FF3A))
- return true;
-
- if (character == 0x0FF3C || character == 0x0FF3E)
- return true;
-
- if (isInRange(character, 0x0FF40, 0x0FF5A) || isInRange(character, 0x0FFE0, 0x0FFE2)
- || isInRange(character, 0x0FFE4, 0x0FFE7) || isInRange(character, 0x0FFF0, 0x0FFF8)
- || character == 0x0FFFD)
- return true;
-
- if (isInRange(character, 0x13000, 0x1342F) || isInRange(character, 0x1B000, 0x1B0FF)
- || isInRange(character, 0x1D000, 0x1D1FF) || isInRange(character, 0x1D300, 0x1D37F)
- || isInRange(character, 0x1F000, 0x1F64F) || isInRange(character, 0x1F680, 0x1F77F))
- return true;
-
- if (isInRange(character, 0x20000, 0x2FFFD) || isInRange(character, 0x30000, 0x3FFFD))
- return true;
-
- return false;
-}
-
-static inline std::pair<GlyphData, GlyphPage*> glyphDataAndPageForNonCJKCharacterWithGlyphOrientation(UChar32 character, NonCJKGlyphOrientation orientation, GlyphData& data, GlyphPage* page, unsigned pageNumber)
-{
- if (orientation == NonCJKGlyphOrientationUpright || shouldIgnoreRotation(character)) {
- RefPtr<SimpleFontData> uprightFontData = data.fontData->uprightOrientationFontData();
- GlyphPageTreeNode* uprightNode = GlyphPageTreeNode::getRootChild(uprightFontData.get(), pageNumber);
- GlyphPage* uprightPage = uprightNode->page();
- if (uprightPage) {
- GlyphData uprightData = uprightPage->glyphDataForCharacter(character);
- // If the glyphs are the same, then we know we can just use the horizontal glyph rotated vertically to be upright.
- if (data.glyph == uprightData.glyph)
- return make_pair(data, page);
- // The glyphs are distinct, meaning that the font has a vertical-right glyph baked into it. We can't use that
- // glyph, so we fall back to the upright data and use the horizontal glyph.
- if (uprightData.fontData)
- return make_pair(uprightData, uprightPage);
- }
- } else if (orientation == NonCJKGlyphOrientationVerticalRight) {
- RefPtr<SimpleFontData> verticalRightFontData = data.fontData->verticalRightOrientationFontData();
- GlyphPageTreeNode* verticalRightNode = GlyphPageTreeNode::getRootChild(verticalRightFontData.get(), pageNumber);
- GlyphPage* verticalRightPage = verticalRightNode->page();
- if (verticalRightPage) {
- GlyphData verticalRightData = verticalRightPage->glyphDataForCharacter(character);
- // If the glyphs are distinct, we will make the assumption that the font has a vertical-right glyph baked
- // into it.
- if (data.glyph != verticalRightData.glyph)
- return make_pair(data, page);
- // The glyphs are identical, meaning that we should just use the horizontal glyph.
- if (verticalRightData.fontData)
- return make_pair(verticalRightData, verticalRightPage);
- }
- }
- return make_pair(data, page);
-}
-
-std::pair<GlyphData, GlyphPage*> Font::glyphDataAndPageForCharacter(UChar32 c, bool mirror, FontDataVariant variant) const
-{
- ASSERT(isMainThread());
-
- if (variant == AutoVariant) {
- if (m_fontDescription.smallCaps() && !primaryFont()->isSVGFont()) {
- UChar32 upperC = toUpper(c);
- if (upperC != c) {
- c = upperC;
- variant = SmallCapsVariant;
- } else
- variant = NormalVariant;
- } else
- variant = NormalVariant;
- }
-
- if (mirror)
- c = mirroredChar(c);
-
- unsigned pageNumber = (c / GlyphPage::size);
-
- GlyphPageTreeNode* node = pageNumber ? m_fontFallbackList->m_pages.get(pageNumber) : m_fontFallbackList->m_pageZero;
- if (!node) {
- node = GlyphPageTreeNode::getRootChild(fontDataAt(0), pageNumber);
- if (pageNumber)
- m_fontFallbackList->m_pages.set(pageNumber, node);
- else
- m_fontFallbackList->m_pageZero = node;
- }
-
- GlyphPage* page = 0;
- if (variant == NormalVariant) {
- // Fastest loop, for the common case (normal variant).
- while (true) {
- page = node->page();
- if (page) {
- GlyphData data = page->glyphDataForCharacter(c);
- if (data.fontData && (data.fontData->platformData().orientation() == Horizontal || data.fontData->isTextOrientationFallback()))
- return make_pair(data, page);
-
- if (data.fontData) {
- if (isCJKIdeographOrSymbol(c)) {
- if (!data.fontData->hasVerticalGlyphs()) {
- // Use the broken ideograph font data. The broken ideograph font will use the horizontal width of glyphs
- // to make sure you get a square (even for broken glyphs like symbols used for punctuation).
- variant = BrokenIdeographVariant;
- break;
- }
- } else
- return glyphDataAndPageForNonCJKCharacterWithGlyphOrientation(c, m_fontDescription.nonCJKGlyphOrientation(), data, page, pageNumber);
-
- return make_pair(data, page);
- }
-
- if (node->isSystemFallback())
- break;
- }
-
- // Proceed with the fallback list.
- node = node->getChild(fontDataAt(node->level()), pageNumber);
- if (pageNumber)
- m_fontFallbackList->m_pages.set(pageNumber, node);
- else
- m_fontFallbackList->m_pageZero = node;
- }
- }
- if (variant != NormalVariant) {
- while (true) {
- page = node->page();
- if (page) {
- GlyphData data = page->glyphDataForCharacter(c);
- if (data.fontData) {
- // The variantFontData function should not normally return 0.
- // But if it does, we will just render the capital letter big.
- RefPtr<SimpleFontData> variantFontData = data.fontData->variantFontData(m_fontDescription, variant);
- if (!variantFontData)
- return make_pair(data, page);
-
- GlyphPageTreeNode* variantNode = GlyphPageTreeNode::getRootChild(variantFontData.get(), pageNumber);
- GlyphPage* variantPage = variantNode->page();
- if (variantPage) {
- GlyphData data = variantPage->glyphDataForCharacter(c);
- if (data.fontData)
- return make_pair(data, variantPage);
- }
-
- // Do not attempt system fallback off the variantFontData. This is the very unlikely case that
- // a font has the lowercase character but the small caps font does not have its uppercase version.
- return make_pair(variantFontData->missingGlyphData(), page);
- }
-
- if (node->isSystemFallback())
- break;
- }
-
- // Proceed with the fallback list.
- node = node->getChild(fontDataAt(node->level()), pageNumber);
- if (pageNumber)
- m_fontFallbackList->m_pages.set(pageNumber, node);
- else
- m_fontFallbackList->m_pageZero = node;
- }
- }
-
- ASSERT(page);
- ASSERT(node->isSystemFallback());
-
- // System fallback is character-dependent. When we get here, we
- // know that the character in question isn't in the system fallback
- // font's glyph page. Try to lazily create it here.
-
- // FIXME: Unclear if this should normalizeSpaces above 0xFFFF.
- // Doing so changes fast/text/international/plane2-diffs.html
- UChar32 characterToRender = c;
- if (characterToRender <= 0xFFFF)
- characterToRender = Font::normalizeSpaces(characterToRender);
- RefPtr<SimpleFontData> characterFontData = fontCache()->getFontDataForCharacter(*this, characterToRender);
- if (characterFontData) {
- if (characterFontData->platformData().orientation() == Vertical && !characterFontData->hasVerticalGlyphs() && isCJKIdeographOrSymbol(c))
- variant = BrokenIdeographVariant;
- if (variant != NormalVariant)
- characterFontData = characterFontData->variantFontData(m_fontDescription, variant);
- }
- if (characterFontData) {
- // Got the fallback glyph and font.
- GlyphPage* fallbackPage = GlyphPageTreeNode::getRootChild(characterFontData.get(), pageNumber)->page();
- GlyphData data = fallbackPage && fallbackPage->fontDataForCharacter(c) ? fallbackPage->glyphDataForCharacter(c) : characterFontData->missingGlyphData();
- // Cache it so we don't have to do system fallback again next time.
- if (variant == NormalVariant) {
- page->setGlyphDataForCharacter(c, data.glyph, data.fontData);
- data.fontData->setMaxGlyphPageTreeLevel(max(data.fontData->maxGlyphPageTreeLevel(), node->level()));
- if (!isCJKIdeographOrSymbol(c) && data.fontData->platformData().orientation() != Horizontal && !data.fontData->isTextOrientationFallback())
- return glyphDataAndPageForNonCJKCharacterWithGlyphOrientation(c, m_fontDescription.nonCJKGlyphOrientation(), data, fallbackPage, pageNumber);
- }
- return make_pair(data, page);
- }
-
- // Even system fallback can fail; use the missing glyph in that case.
- // FIXME: It would be nicer to use the missing glyph from the last resort font instead.
- GlyphData data = primaryFont()->missingGlyphData();
- if (variant == NormalVariant) {
- page->setGlyphDataForCharacter(c, data.glyph, data.fontData);
- data.fontData->setMaxGlyphPageTreeLevel(max(data.fontData->maxGlyphPageTreeLevel(), node->level()));
- }
- return make_pair(data, page);
-}
-
-bool Font::primaryFontHasGlyphForCharacter(UChar32 character) const
-{
- unsigned pageNumber = (character / GlyphPage::size);
-
- GlyphPageTreeNode* node = GlyphPageTreeNode::getRootChild(primaryFont(), pageNumber);
- GlyphPage* page = node->page();
-
- return page && page->fontDataForCharacter(character);
-}
-
-// FIXME: This function may not work if the emphasis mark uses a complex script, but none of the
-// standard emphasis marks do so.
-bool Font::getEmphasisMarkGlyphData(const AtomicString& mark, GlyphData& glyphData) const
-{
- if (mark.isEmpty())
- return false;
-
- UChar32 character = mark[0];
-
- if (U16_IS_SURROGATE(character)) {
- if (!U16_IS_SURROGATE_LEAD(character))
- return false;
-
- if (mark.length() < 2)
- return false;
-
- UChar low = mark[1];
- if (!U16_IS_TRAIL(low))
- return false;
-
- character = U16_GET_SUPPLEMENTARY(character, low);
- }
-
- glyphData = glyphDataForCharacter(character, false, EmphasisMarkVariant);
- return true;
-}
-
-int Font::emphasisMarkAscent(const AtomicString& mark) const
-{
- FontCachePurgePreventer purgePreventer;
-
- GlyphData markGlyphData;
- if (!getEmphasisMarkGlyphData(mark, markGlyphData))
- return 0;
-
- const SimpleFontData* markFontData = markGlyphData.fontData;
- ASSERT(markFontData);
- if (!markFontData)
- return 0;
-
- return markFontData->fontMetrics().ascent();
-}
-
-int Font::emphasisMarkDescent(const AtomicString& mark) const
-{
- FontCachePurgePreventer purgePreventer;
-
- GlyphData markGlyphData;
- if (!getEmphasisMarkGlyphData(mark, markGlyphData))
- return 0;
-
- const SimpleFontData* markFontData = markGlyphData.fontData;
- ASSERT(markFontData);
- if (!markFontData)
- return 0;
-
- return markFontData->fontMetrics().descent();
-}
-
-int Font::emphasisMarkHeight(const AtomicString& mark) const
-{
- FontCachePurgePreventer purgePreventer;
-
- GlyphData markGlyphData;
- if (!getEmphasisMarkGlyphData(mark, markGlyphData))
- return 0;
-
- const SimpleFontData* markFontData = markGlyphData.fontData;
- ASSERT(markFontData);
- if (!markFontData)
- return 0;
-
- return markFontData->fontMetrics().height();
-}
-
-float Font::getGlyphsAndAdvancesForSimpleText(const TextRun& run, int from, int to, GlyphBuffer& glyphBuffer, ForTextEmphasisOrNot forTextEmphasis) const
-{
- float initialAdvance;
-
- WidthIterator it(this, run, 0, false, forTextEmphasis);
- // FIXME: Using separate glyph buffers for the prefix and the suffix is incorrect when kerning or
- // ligatures are enabled.
- GlyphBuffer localGlyphBuffer;
- it.advance(from, &localGlyphBuffer);
- float beforeWidth = it.m_runWidthSoFar;
- it.advance(to, &glyphBuffer);
-
- if (glyphBuffer.isEmpty())
- return 0;
-
- float afterWidth = it.m_runWidthSoFar;
-
- if (run.rtl()) {
- float finalRoundingWidth = it.m_finalRoundingWidth;
- it.advance(run.length(), &localGlyphBuffer);
- initialAdvance = finalRoundingWidth + it.m_runWidthSoFar - afterWidth;
- } else
- initialAdvance = beforeWidth;
-
- if (run.rtl())
- glyphBuffer.reverse(0, glyphBuffer.size());
-
- return initialAdvance;
-}
-
-void Font::drawSimpleText(GraphicsContext* context, const TextRunPaintInfo& runInfo, const FloatPoint& point) const
-{
- // This glyph buffer holds our glyphs+advances+font data for each glyph.
- GlyphBuffer glyphBuffer;
-
- float startX = point.x() + getGlyphsAndAdvancesForSimpleText(runInfo.run, runInfo.from, runInfo.to, glyphBuffer);
-
- if (glyphBuffer.isEmpty())
- return;
-
- FloatPoint startPoint(startX, point.y());
- drawGlyphBuffer(context, runInfo, glyphBuffer, startPoint);
-}
-
-void Font::drawEmphasisMarksForSimpleText(GraphicsContext* context, const TextRunPaintInfo& runInfo, const AtomicString& mark, const FloatPoint& point) const
-{
- GlyphBuffer glyphBuffer;
- float initialAdvance = getGlyphsAndAdvancesForSimpleText(runInfo.run, runInfo.from, runInfo.to, glyphBuffer, ForTextEmphasis);
-
- if (glyphBuffer.isEmpty())
- return;
-
- drawEmphasisMarks(context, runInfo, glyphBuffer, mark, FloatPoint(point.x() + initialAdvance, point.y()));
-}
-
-void Font::drawGlyphBuffer(GraphicsContext* context, const TextRunPaintInfo& runInfo, const GlyphBuffer& glyphBuffer, const FloatPoint& point) const
-{
- // Draw each contiguous run of glyphs that use the same font data.
- const SimpleFontData* fontData = glyphBuffer.fontDataAt(0);
- FloatPoint startPoint(point);
- float nextX = startPoint.x() + glyphBuffer.advanceAt(0);
- int lastFrom = 0;
- int nextGlyph = 1;
-#if ENABLE(SVG_FONTS)
- TextRun::RenderingContext* renderingContext = runInfo.run.renderingContext();
-#endif
- while (nextGlyph < glyphBuffer.size()) {
- const SimpleFontData* nextFontData = glyphBuffer.fontDataAt(nextGlyph);
-
- if (nextFontData != fontData) {
-#if ENABLE(SVG_FONTS)
- if (renderingContext && fontData->isSVGFont())
- renderingContext->drawSVGGlyphs(context, runInfo.run, fontData, glyphBuffer, lastFrom, nextGlyph - lastFrom, startPoint);
- else
-#endif
- drawGlyphs(context, fontData, glyphBuffer, lastFrom, nextGlyph - lastFrom, startPoint, runInfo.bounds);
-
- lastFrom = nextGlyph;
- fontData = nextFontData;
- startPoint.setX(nextX);
- }
- nextX += glyphBuffer.advanceAt(nextGlyph);
- nextGlyph++;
- }
-
-#if ENABLE(SVG_FONTS)
- if (renderingContext && fontData->isSVGFont())
- renderingContext->drawSVGGlyphs(context, runInfo.run, fontData, glyphBuffer, lastFrom, nextGlyph - lastFrom, startPoint);
- else
-#endif
- drawGlyphs(context, fontData, glyphBuffer, lastFrom, nextGlyph - lastFrom, startPoint, runInfo.bounds);
-}
-
-inline static float offsetToMiddleOfGlyph(const SimpleFontData* fontData, Glyph glyph)
-{
- if (fontData->platformData().orientation() == Horizontal) {
- FloatRect bounds = fontData->boundsForGlyph(glyph);
- return bounds.x() + bounds.width() / 2;
- }
- // FIXME: Use glyph bounds once they make sense for vertical fonts.
- return fontData->widthForGlyph(glyph) / 2;
-}
-
-inline static float offsetToMiddleOfGlyphAtIndex(const GlyphBuffer& glyphBuffer, size_t i)
-{
- return offsetToMiddleOfGlyph(glyphBuffer.fontDataAt(i), glyphBuffer.glyphAt(i));
-}
-
-void Font::drawEmphasisMarks(GraphicsContext* context, const TextRunPaintInfo& runInfo, const GlyphBuffer& glyphBuffer, const AtomicString& mark, const FloatPoint& point) const
-{
- FontCachePurgePreventer purgePreventer;
-
- GlyphData markGlyphData;
- if (!getEmphasisMarkGlyphData(mark, markGlyphData))
- return;
-
- const SimpleFontData* markFontData = markGlyphData.fontData;
- ASSERT(markFontData);
- if (!markFontData)
- return;
-
- Glyph markGlyph = markGlyphData.glyph;
- Glyph spaceGlyph = markFontData->spaceGlyph();
-
- float middleOfLastGlyph = offsetToMiddleOfGlyphAtIndex(glyphBuffer, 0);
- FloatPoint startPoint(point.x() + middleOfLastGlyph - offsetToMiddleOfGlyph(markFontData, markGlyph), point.y());
-
- GlyphBuffer markBuffer;
- for (int i = 0; i + 1 < glyphBuffer.size(); ++i) {
- float middleOfNextGlyph = offsetToMiddleOfGlyphAtIndex(glyphBuffer, i + 1);
- float advance = glyphBuffer.advanceAt(i) - middleOfLastGlyph + middleOfNextGlyph;
- markBuffer.add(glyphBuffer.glyphAt(i) ? markGlyph : spaceGlyph, markFontData, advance);
- middleOfLastGlyph = middleOfNextGlyph;
- }
- markBuffer.add(glyphBuffer.glyphAt(glyphBuffer.size() - 1) ? markGlyph : spaceGlyph, markFontData, 0);
-
- drawGlyphBuffer(context, runInfo, markBuffer, startPoint);
-}
-
-float Font::floatWidthForSimpleText(const TextRun& run, HashSet<const SimpleFontData*>* fallbackFonts, GlyphOverflow* glyphOverflow) const
-{
- WidthIterator it(this, run, fallbackFonts, glyphOverflow);
- GlyphBuffer glyphBuffer;
- it.advance(run.length(), (typesettingFeatures() & (Kerning | Ligatures)) ? &glyphBuffer : 0);
-
- if (glyphOverflow) {
- glyphOverflow->top = max<int>(glyphOverflow->top, ceilf(-it.minGlyphBoundingBoxY()) - (glyphOverflow->computeBounds ? 0 : fontMetrics().ascent()));
- glyphOverflow->bottom = max<int>(glyphOverflow->bottom, ceilf(it.maxGlyphBoundingBoxY()) - (glyphOverflow->computeBounds ? 0 : fontMetrics().descent()));
- glyphOverflow->left = ceilf(it.firstGlyphOverflow());
- glyphOverflow->right = ceilf(it.lastGlyphOverflow());
- }
-
- return it.m_runWidthSoFar;
-}
-
-FloatRect Font::selectionRectForSimpleText(const TextRun& run, const FloatPoint& point, int h, int from, int to) const
-{
- GlyphBuffer glyphBuffer;
- WidthIterator it(this, run);
- it.advance(from, &glyphBuffer);
- float beforeWidth = it.m_runWidthSoFar;
- it.advance(to, &glyphBuffer);
- float afterWidth = it.m_runWidthSoFar;
-
- // Using roundf() rather than ceilf() for the right edge as a compromise to ensure correct caret positioning.
- if (run.rtl()) {
- it.advance(run.length(), &glyphBuffer);
- float totalWidth = it.m_runWidthSoFar;
- return FloatRect(floorf(point.x() + totalWidth - afterWidth), point.y(), roundf(point.x() + totalWidth - beforeWidth) - floorf(point.x() + totalWidth - afterWidth), h);
- }
-
- return FloatRect(floorf(point.x() + beforeWidth), point.y(), roundf(point.x() + afterWidth) - floorf(point.x() + beforeWidth), h);
-}
-
-int Font::offsetForPositionForSimpleText(const TextRun& run, float x, bool includePartialGlyphs) const
-{
- float delta = x;
-
- WidthIterator it(this, run);
- GlyphBuffer localGlyphBuffer;
- unsigned offset;
- if (run.rtl()) {
- delta -= floatWidthForSimpleText(run);
- while (1) {
- offset = it.m_currentCharacter;
- float w;
- if (!it.advanceOneCharacter(w, localGlyphBuffer))
- break;
- delta += w;
- if (includePartialGlyphs) {
- if (delta - w / 2 >= 0)
- break;
- } else {
- if (delta >= 0)
- break;
- }
- }
- } else {
- while (1) {
- offset = it.m_currentCharacter;
- float w;
- if (!it.advanceOneCharacter(w, localGlyphBuffer))
- break;
- delta -= w;
- if (includePartialGlyphs) {
- if (delta + w / 2 <= 0)
- break;
- } else {
- if (delta <= 0)
- break;
- }
- }
- }
-
- return offset;
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/FontFeatureSettings.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/FontFeatureSettings.cpp
deleted file mode 100644
index 8ea3ee3d00c..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/FontFeatureSettings.cpp
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/FontFeatureSettings.h"
-
-namespace WebCore {
-
-FontFeature::FontFeature(const AtomicString& tag, int value)
- : m_tag(tag)
- , m_value(value)
-{
-}
-
-bool FontFeature::operator==(const FontFeature& other)
-{
- return m_tag == other.m_tag && m_value == other.m_value;
-}
-
-FontFeatureSettings::FontFeatureSettings()
-{
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/FontFeatureSettings.h b/chromium/third_party/WebKit/Source/core/platform/graphics/FontFeatureSettings.h
deleted file mode 100644
index b40c4bf5e2d..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/FontFeatureSettings.h
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef FontFeatureSettings_h
-#define FontFeatureSettings_h
-
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/RefPtr.h"
-#include "wtf/Vector.h"
-#include "wtf/text/AtomicString.h"
-
-namespace WebCore {
-
-class FontFeature {
-public:
- FontFeature(const AtomicString& tag, int value);
- bool operator==(const FontFeature&);
-
- const AtomicString& tag() const { return m_tag; }
- int value() const { return m_value; }
-
-private:
- AtomicString m_tag;
- const int m_value;
-};
-
-class FontFeatureSettings : public RefCounted<FontFeatureSettings> {
-public:
- static PassRefPtr<FontFeatureSettings> create()
- {
- return adoptRef(new FontFeatureSettings());
- }
- void append(const FontFeature& feature) { m_list.append(feature); }
- size_t size() const { return m_list.size(); }
- const FontFeature& operator[](int index) const { return m_list[index]; }
- const FontFeature& at(size_t index) const { return m_list.at(index); }
-
-private:
- FontFeatureSettings();
- Vector<FontFeature> m_list;
-};
-
-}
-
-#endif // FontFeatureSettings_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/FontMetrics.h b/chromium/third_party/WebKit/Source/core/platform/graphics/FontMetrics.h
deleted file mode 100644
index 5f0073a600f..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/FontMetrics.h
+++ /dev/null
@@ -1,157 +0,0 @@
-/*
- * Copyright (C) Research In Motion Limited 2010-2011. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#ifndef FontMetrics_h
-#define FontMetrics_h
-
-#include "core/platform/graphics/FontBaseline.h"
-#include "wtf/MathExtras.h"
-
-namespace WebCore {
-
-const unsigned gDefaultUnitsPerEm = 1000;
-
-class FontMetrics {
-public:
- FontMetrics()
- : m_unitsPerEm(gDefaultUnitsPerEm)
- , m_ascent(0)
- , m_descent(0)
- , m_lineGap(0)
- , m_lineSpacing(0)
- , m_xHeight(0)
- , m_zeroWidth(0)
- , m_hasXHeight(false)
- , m_hasZeroWidth(false)
- {
- }
-
- unsigned unitsPerEm() const { return m_unitsPerEm; }
- void setUnitsPerEm(unsigned unitsPerEm) { m_unitsPerEm = unitsPerEm; }
-
- float floatAscent(FontBaseline baselineType = AlphabeticBaseline) const
- {
- if (baselineType == AlphabeticBaseline)
- return m_ascent;
- return floatHeight() / 2;
- }
-
- void setAscent(float ascent) { m_ascent = ascent; }
-
- float floatDescent(FontBaseline baselineType = AlphabeticBaseline) const
- {
- if (baselineType == AlphabeticBaseline)
- return m_descent;
- return floatHeight() / 2;
- }
-
- void setDescent(float descent) { m_descent = descent; }
-
- float floatHeight(FontBaseline baselineType = AlphabeticBaseline) const
- {
- return floatAscent(baselineType) + floatDescent(baselineType);
- }
-
- float floatLineGap() const { return m_lineGap; }
- void setLineGap(float lineGap) { m_lineGap = lineGap; }
-
- float floatLineSpacing() const { return m_lineSpacing; }
- void setLineSpacing(float lineSpacing) { m_lineSpacing = lineSpacing; }
-
- float xHeight() const { return m_xHeight; }
- void setXHeight(float xHeight)
- {
- m_xHeight = xHeight;
- m_hasXHeight = true;
- }
-
- bool hasXHeight() const { return m_hasXHeight && m_xHeight > 0; }
- void setHasXHeight(bool hasXHeight) { m_hasXHeight = hasXHeight; }
-
- // Integer variants of certain metrics, used for HTML rendering.
- int ascent(FontBaseline baselineType = AlphabeticBaseline) const
- {
- if (baselineType == AlphabeticBaseline)
- return lroundf(m_ascent);
- return height() - height() / 2;
- }
-
- int descent(FontBaseline baselineType = AlphabeticBaseline) const
- {
- if (baselineType == AlphabeticBaseline)
- return lroundf(m_descent);
- return height() / 2;
- }
-
- int height(FontBaseline baselineType = AlphabeticBaseline) const
- {
- return ascent(baselineType) + descent(baselineType);
- }
-
- int lineGap() const { return lroundf(m_lineGap); }
- int lineSpacing() const { return lroundf(m_lineSpacing); }
-
- bool hasIdenticalAscentDescentAndLineGap(const FontMetrics& other) const
- {
- return ascent() == other.ascent() && descent() == other.descent() && lineGap() == other.lineGap();
- }
-
- float zeroWidth() const { return m_zeroWidth; }
- void setZeroWidth(float zeroWidth)
- {
- m_zeroWidth = zeroWidth;
- m_hasZeroWidth = true;
- }
-
- bool hasZeroWidth() const { return m_hasZeroWidth; }
- void setHasZeroWidth(bool hasZeroWidth) { m_hasZeroWidth = hasZeroWidth; }
-
-private:
- friend class SimpleFontData;
-
- void reset()
- {
- m_unitsPerEm = gDefaultUnitsPerEm;
- m_ascent = 0;
- m_descent = 0;
- m_lineGap = 0;
- m_lineSpacing = 0;
- m_xHeight = 0;
- m_hasXHeight = false;
- }
-
- unsigned m_unitsPerEm;
- float m_ascent;
- float m_descent;
- float m_lineGap;
- float m_lineSpacing;
- float m_xHeight;
- float m_zeroWidth;
- bool m_hasXHeight;
- bool m_hasZeroWidth;
-};
-
-static inline float scaleEmToUnits(float x, unsigned unitsPerEm)
-{
- return unitsPerEm ? x / unitsPerEm : x;
-}
-
-} // namespace WebCore
-
-#endif // FontMetrics_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/FontOrientation.h b/chromium/third_party/WebKit/Source/core/platform/graphics/FontOrientation.h
deleted file mode 100644
index 9239e3821c1..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/FontOrientation.h
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright (C) 2010 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef FontOrientation_h
-#define FontOrientation_h
-
-namespace WebCore {
-
-enum FontOrientation { Horizontal, Vertical };
-
-} // namespace WebCore
-
-#endif // FontOrientation_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/FontPlatformData.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/FontPlatformData.cpp
deleted file mode 100644
index 3e2f72c5fae..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/FontPlatformData.cpp
+++ /dev/null
@@ -1,140 +0,0 @@
-/*
- * Copyright (C) 2011 Brent Fulgham
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#include "config.h"
-#include "core/platform/graphics/FontPlatformData.h"
-
-#include "wtf/HashMap.h"
-#include "wtf/RetainPtr.h"
-#include "wtf/text/StringHash.h"
-#include "wtf/text/WTFString.h"
-#include "wtf/Vector.h"
-
-#if OS(MACOSX)
-#include "core/platform/graphics/harfbuzz/HarfBuzzFace.h"
-#endif
-
-using namespace std;
-
-namespace WebCore {
-
-FontPlatformData::FontPlatformData(WTF::HashTableDeletedValueType)
- : m_syntheticBold(false)
- , m_syntheticOblique(false)
- , m_orientation(Horizontal)
- , m_size(0)
- , m_widthVariant(RegularWidth)
-#if OS(MACOSX)
- , m_font(hashTableDeletedFontValue())
-#endif
- , m_isColorBitmapFont(false)
- , m_isCompositeFontReference(false)
-#if OS(MACOSX)
- , m_isPrinterFont(false)
-#endif
-{
-}
-
-FontPlatformData::FontPlatformData()
- : m_syntheticBold(false)
- , m_syntheticOblique(false)
- , m_orientation(Horizontal)
- , m_size(0)
- , m_widthVariant(RegularWidth)
-#if OS(MACOSX)
- , m_font(0)
-#endif
- , m_isColorBitmapFont(false)
- , m_isCompositeFontReference(false)
-#if OS(MACOSX)
- , m_isPrinterFont(false)
-#endif
-{
-}
-
-FontPlatformData::FontPlatformData(float size, bool syntheticBold, bool syntheticOblique, FontOrientation orientation, FontWidthVariant widthVariant)
- : m_syntheticBold(syntheticBold)
- , m_syntheticOblique(syntheticOblique)
- , m_orientation(orientation)
- , m_size(size)
- , m_widthVariant(widthVariant)
-#if OS(MACOSX)
- , m_font(0)
-#endif
- , m_isColorBitmapFont(false)
- , m_isCompositeFontReference(false)
-#if OS(MACOSX)
- , m_isPrinterFont(false)
-#endif
-{
-}
-
-#if OS(MACOSX)
-FontPlatformData::FontPlatformData(CGFontRef cgFont, float size, bool syntheticBold, bool syntheticOblique, FontOrientation orientation, FontWidthVariant widthVariant)
- : m_syntheticBold(syntheticBold)
- , m_syntheticOblique(syntheticOblique)
- , m_orientation(orientation)
- , m_size(size)
- , m_widthVariant(widthVariant)
- , m_font(0)
- , m_cgFont(cgFont)
- , m_isColorBitmapFont(false)
- , m_isCompositeFontReference(false)
- , m_isPrinterFont(false)
-{
-}
-#endif
-
-FontPlatformData::FontPlatformData(const FontPlatformData& source)
- : m_syntheticBold(source.m_syntheticBold)
- , m_syntheticOblique(source.m_syntheticOblique)
- , m_orientation(source.m_orientation)
- , m_size(source.m_size)
- , m_widthVariant(source.m_widthVariant)
- , m_isColorBitmapFont(source.m_isColorBitmapFont)
- , m_isCompositeFontReference(source.m_isCompositeFontReference)
-#if OS(MACOSX)
- , m_isPrinterFont(source.m_isPrinterFont)
-#endif
-{
- platformDataInit(source);
-}
-
-const FontPlatformData& FontPlatformData::operator=(const FontPlatformData& other)
-{
- // Check for self-assignment.
- if (this == &other)
- return *this;
-
- m_syntheticBold = other.m_syntheticBold;
- m_syntheticOblique = other.m_syntheticOblique;
- m_orientation = other.m_orientation;
- m_size = other.m_size;
- m_widthVariant = other.m_widthVariant;
- m_isColorBitmapFont = other.m_isColorBitmapFont;
- m_isCompositeFontReference = other.m_isCompositeFontReference;
-#if OS(MACOSX)
- m_isPrinterFont = other.m_isPrinterFont;
-#endif
-
- return platformDataAssign(other);
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/FontPlatformData.h b/chromium/third_party/WebKit/Source/core/platform/graphics/FontPlatformData.h
deleted file mode 100644
index 5571b23c8a1..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/FontPlatformData.h
+++ /dev/null
@@ -1,213 +0,0 @@
-/*
- * Copyright (C) 2006, 2007, 2008, 2010 Apple Inc.
- * Copyright (C) 2006 Michael Emmel mike.emmel@gmail.com
- * Copyright (C) 2007 Holger Hans Peter Freyther
- * Copyright (C) 2007 Pioneer Research Center USA, Inc.
- * Copyright (C) 2010, 2011 Brent Fulgham <bfulgham@webkit.org>
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-// FIXME: This is temporary until all ports switch to using this file.
-#if OS(WIN)
-#include "core/platform/graphics/chromium/FontPlatformDataChromiumWin.h"
-#elif !OS(MACOSX)
-#include "core/platform/graphics/harfbuzz/FontPlatformDataHarfBuzz.h"
-
-#else
-
-#ifndef FontPlatformData_h
-#define FontPlatformData_h
-
-#include "core/platform/graphics/FontOrientation.h"
-#include "core/platform/graphics/FontWidthVariant.h"
-
-#if OS(MACOSX)
-OBJC_CLASS NSFont;
-
-typedef struct CGFont* CGFontRef;
-typedef const struct __CTFont* CTFontRef;
-
-#include <CoreFoundation/CFBase.h>
-#include <objc/objc-auto.h>
-#endif
-
-#include "wtf/Forward.h"
-#include "wtf/HashTableDeletedValueType.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/RetainPtr.h"
-#include "wtf/text/StringImpl.h"
-
-#if OS(MACOSX)
-#include "core/platform/graphics/chromium/CrossProcessFontLoading.h"
-#endif
-
-#if OS(MACOSX)
-typedef struct CGFont* CGFontRef;
-typedef const struct __CTFont* CTFontRef;
-typedef UInt32 FMFont;
-typedef FMFont ATSUFontID;
-typedef UInt32 ATSFontRef;
-#endif
-
-namespace WebCore {
-
-class FontDescription;
-class SharedBuffer;
-
-#if OS(MACOSX)
-class HarfBuzzFace;
-#endif
-
-#if OS(MACOSX)
-inline CTFontRef toCTFontRef(NSFont *nsFont) { return reinterpret_cast<CTFontRef>(nsFont); }
-#endif
-
-class FontPlatformData {
-public:
- FontPlatformData(WTF::HashTableDeletedValueType);
- FontPlatformData();
- FontPlatformData(const FontPlatformData&);
- FontPlatformData(const FontDescription&, const AtomicString& family);
- FontPlatformData(float size, bool syntheticBold, bool syntheticOblique, FontOrientation = Horizontal, FontWidthVariant = RegularWidth);
-
-#if OS(MACOSX)
- FontPlatformData(NSFont*, float size, bool isPrinterFont = false, bool syntheticBold = false, bool syntheticOblique = false,
- FontOrientation = Horizontal, FontWidthVariant = RegularWidth);
- FontPlatformData(CGFontRef, float size, bool syntheticBold, bool syntheticOblique, FontOrientation, FontWidthVariant);
-#endif
-
- ~FontPlatformData();
-
-#if OS(MACOSX)
- NSFont* font() const { return m_font; }
- void setFont(NSFont*);
-#endif
-
-#if OS(MACOSX)
- CGFontRef cgFont() const { return m_cgFont.get(); }
- CTFontRef ctFont() const;
-
- bool roundsGlyphAdvances() const;
- bool allowsLigatures() const;
-#endif
-
- String fontFamilyName() const;
- bool isFixedPitch() const;
- float size() const { return m_size; }
- void setSize(float size) { m_size = size; }
- bool syntheticBold() const { return m_syntheticBold; }
- bool syntheticOblique() const { return m_syntheticOblique; }
- bool isColorBitmapFont() const { return m_isColorBitmapFont; }
- bool isCompositeFontReference() const { return m_isCompositeFontReference; }
-#if OS(MACOSX)
- bool isPrinterFont() const { return m_isPrinterFont; }
-#endif
- FontOrientation orientation() const { return m_orientation; }
- FontWidthVariant widthVariant() const { return m_widthVariant; }
-
- void setOrientation(FontOrientation orientation) { m_orientation = orientation; }
-
-#if OS(MACOSX)
- HarfBuzzFace* harfBuzzFace();
-#endif
-
- unsigned hash() const
- {
-#if OS(MACOSX)
- ASSERT(m_font || !m_cgFont);
- uintptr_t hashCodes[3] = { (uintptr_t)m_font, m_widthVariant, static_cast<uintptr_t>(m_isPrinterFont << 3 | m_orientation << 2 | m_syntheticBold << 1 | m_syntheticOblique) };
- return StringHasher::hashMemory<sizeof(hashCodes)>(hashCodes);
-#endif
- }
-
- const FontPlatformData& operator=(const FontPlatformData&);
-
- bool operator==(const FontPlatformData& other) const
- {
- return platformIsEqual(other)
- && m_size == other.m_size
- && m_syntheticBold == other.m_syntheticBold
- && m_syntheticOblique == other.m_syntheticOblique
- && m_isColorBitmapFont == other.m_isColorBitmapFont
- && m_isCompositeFontReference == other.m_isCompositeFontReference
-#if OS(MACOSX)
- && m_isPrinterFont == other.m_isPrinterFont
-#endif
- && m_orientation == other.m_orientation
- && m_widthVariant == other.m_widthVariant;
- }
-
- bool isHashTableDeletedValue() const
- {
-#if OS(MACOSX)
- return m_font == hashTableDeletedFontValue();
-#endif
- }
-
-#ifndef NDEBUG
- String description() const;
-#endif
-
-private:
- bool platformIsEqual(const FontPlatformData&) const;
- void platformDataInit(const FontPlatformData&);
- const FontPlatformData& platformDataAssign(const FontPlatformData&);
-#if OS(MACOSX)
- // Load various data about the font specified by |nsFont| with the size fontSize into the following output paramters:
- // Note: Callers should always take into account that for the Chromium port, |outNSFont| isn't necessarily the same
- // font as |nsFont|. This because the sandbox may block loading of the original font.
- // * outNSFont - The font that was actually loaded, for the Chromium port this may be different than nsFont.
- // The caller is responsible for calling CFRelease() on this parameter when done with it.
- // * cgFont - CGFontRef representing the input font at the specified point size.
- void loadFont(NSFont*, float fontSize, NSFont*& outNSFont, CGFontRef&);
- static NSFont* hashTableDeletedFontValue() { return reinterpret_cast<NSFont *>(-1); }
-#endif
-
-public:
- bool m_syntheticBold;
- bool m_syntheticOblique;
- FontOrientation m_orientation;
- float m_size;
- FontWidthVariant m_widthVariant;
-
-private:
-#if OS(MACOSX)
- NSFont* m_font;
-#endif
-
-#if OS(MACOSX)
- RetainPtr<CGFontRef> m_cgFont;
- mutable RetainPtr<CTFontRef> m_CTFont;
-
- RefPtr<MemoryActivatedFont> m_inMemoryFont;
- RefPtr<HarfBuzzFace> m_harfBuzzFace;
-#endif
-
- bool m_isColorBitmapFont;
- bool m_isCompositeFontReference;
-#if OS(MACOSX)
- bool m_isPrinterFont;
-#endif
-};
-
-} // namespace WebCore
-
-#endif // FontPlatformData_h
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/FontSelector.h b/chromium/third_party/WebKit/Source/core/platform/graphics/FontSelector.h
deleted file mode 100644
index 1225ffc783c..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/FontSelector.h
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * Copyright (C) 2007, 2008 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef FontSelector_h
-#define FontSelector_h
-
-#include "wtf/Forward.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-
-namespace WebCore {
-
-class FontData;
-class FontDescription;
-class FontSelectorClient;
-
-class FontSelector : public RefCounted<FontSelector> {
-public:
- virtual ~FontSelector() { }
- virtual PassRefPtr<FontData> getFontData(const FontDescription&, const AtomicString& familyName) = 0;
- virtual void willUseFontData(const FontDescription&, const AtomicString& familyName) = 0;
-
- virtual void fontCacheInvalidated() { }
-
- virtual void registerForInvalidationCallbacks(FontSelectorClient*) = 0;
- virtual void unregisterForInvalidationCallbacks(FontSelectorClient*) = 0;
-
- virtual unsigned version() const = 0;
-};
-
-class FontSelectorClient {
-public:
- virtual ~FontSelectorClient() { }
-
- virtual void fontsNeedUpdate(FontSelector*) = 0;
-};
-
-} // namespace WebCore
-
-#endif // FontSelector_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/FontSmoothingMode.h b/chromium/third_party/WebKit/Source/core/platform/graphics/FontSmoothingMode.h
deleted file mode 100644
index 90b0c5c62d1..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/FontSmoothingMode.h
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright (C) 2009 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef FontSmoothingMode_h
-#define FontSmoothingMode_h
-
-namespace WebCore {
-
-enum FontSmoothingMode { AutoSmoothing, NoSmoothing, Antialiased, SubpixelAntialiased };
-
-} // namespace WebCore
-
-#endif // FontSmoothingMode_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/FontTest.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/FontTest.cpp
deleted file mode 100644
index a5ee4f46ab1..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/FontTest.cpp
+++ /dev/null
@@ -1,365 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-// Tests for the Font class.
-
-#include "config.h"
-
-#include "core/platform/graphics/Font.h"
-
-#include <gtest/gtest.h>
-
-namespace WebCore {
-
-static void TestSpecificUCharRange(UChar rangeStart, UChar rangeEnd)
-{
- UChar below[1];
- UChar start[1];
- UChar midway[1];
- UChar end[1];
- UChar above[1];
-
- below[0] = rangeStart - 1;
- start[0] = rangeStart;
- midway[0] = ((int)rangeStart + (int)rangeEnd) / 2;
- end[0] = rangeEnd;
- above[0] = rangeEnd + 1;
-
- EXPECT_EQ(Font::Simple, Font::characterRangeCodePath(below, 1));
- EXPECT_EQ(Font::Complex, Font::characterRangeCodePath(start, 1));
- EXPECT_EQ(Font::Complex, Font::characterRangeCodePath(midway, 1));
- EXPECT_EQ(Font::Complex, Font::characterRangeCodePath(end, 1));
- EXPECT_EQ(Font::Simple, Font::characterRangeCodePath(above, 1));
-}
-
-TEST(FontTest, TestCharacterRangeCodePath)
-{
- static UChar c1[] = { 0x0 };
- EXPECT_EQ(Font::Simple, Font::characterRangeCodePath(c1, 1));
-
- TestSpecificUCharRange(0x2E5, 0x2E9);
- TestSpecificUCharRange(0x300, 0x36F);
- TestSpecificUCharRange(0x0591, 0x05BD);
- TestSpecificUCharRange(0x05BF, 0x05CF);
- TestSpecificUCharRange(0x0600, 0x109F);
- TestSpecificUCharRange(0x1100, 0x11FF);
- TestSpecificUCharRange(0x135D, 0x135F);
- TestSpecificUCharRange(0x1700, 0x18AF);
- TestSpecificUCharRange(0x1900, 0x194F);
- TestSpecificUCharRange(0x1980, 0x19DF);
- TestSpecificUCharRange(0x1A00, 0x1CFF);
-
- static UChar c2[] = { 0x1DBF };
- EXPECT_EQ(Font::Simple, Font::characterRangeCodePath(c2, 1));
- static UChar c3[] = { 0x1DC0 };
- EXPECT_EQ(Font::Complex, Font::characterRangeCodePath(c3, 1));
- static UChar c4[] = { 0x1DD0 };
- EXPECT_EQ(Font::Complex, Font::characterRangeCodePath(c4, 1));
- static UChar c5[] = { 0x1DFF };
- EXPECT_EQ(Font::Complex, Font::characterRangeCodePath(c5, 1));
- static UChar c6[] = { 0x1E00 };
- EXPECT_EQ(Font::SimpleWithGlyphOverflow, Font::characterRangeCodePath(c6, 1));
- static UChar c7[] = { 0x2000 };
- EXPECT_EQ(Font::SimpleWithGlyphOverflow, Font::characterRangeCodePath(c7, 1));
- static UChar c8[] = { 0x2001 };
- EXPECT_EQ(Font::Simple, Font::characterRangeCodePath(c8, 1));
-
- TestSpecificUCharRange(0x20D0, 0x20FF);
- TestSpecificUCharRange(0x2CEF, 0x2CF1);
- TestSpecificUCharRange(0x302A, 0x302F);
-
- TestSpecificUCharRange(0xA67C, 0xA67D);
- TestSpecificUCharRange(0xA6F0, 0xA6F1);
- TestSpecificUCharRange(0xA800, 0xABFF);
-
- TestSpecificUCharRange(0xD7B0, 0xD7FF);
- TestSpecificUCharRange(0xFE00, 0xFE0F);
- TestSpecificUCharRange(0xFE20, 0xFE2F);
-}
-
-TEST(FontTest, TestCharacterRangeCodePathSurrogate1)
-{
- /* To be surrogate ... */
- /* 1st character must be 0xD800 .. 0xDBFF */
- /* 2nd character must be 0xdc00 .. 0xdfff */
-
- /* The following 5 should all be Simple because they are not surrogate. */
- static UChar c1[] = { 0xD800, 0xDBFE };
- EXPECT_EQ(Font::Simple, Font::characterRangeCodePath(c1, 2));
- static UChar c2[] = { 0xD800, 0xE000 };
- EXPECT_EQ(Font::Simple, Font::characterRangeCodePath(c2, 2));
- static UChar c3[] = { 0xDBFF, 0xDBFE };
- EXPECT_EQ(Font::Simple, Font::characterRangeCodePath(c3, 2));
- static UChar c4[] = { 0xDBFF, 0xE000 };
- EXPECT_EQ(Font::Simple, Font::characterRangeCodePath(c4, 2));
- static UChar c5[] = { 0xDC00, 0xDBFF };
- EXPECT_EQ(Font::Simple, Font::characterRangeCodePath(c5, 2));
-
- /* To be Complex, the Supplementary Character must be in either */
- /* U+1F1E6 through U+1F1FF or U+E0100 through U+E01EF. */
- /* That is, a lead of 0xD83C with trail 0xDDE6 .. 0xDDFF or */
- /* a lead of 0xDB40 with trail 0xDD00 .. 0xDDEF. */
- static UChar c6[] = { 0xD83C, 0xDDE5 };
- EXPECT_EQ(Font::Simple, Font::characterRangeCodePath(c6, 2));
- static UChar c7[] = { 0xD83C, 0xDDE6 };
- EXPECT_EQ(Font::Complex, Font::characterRangeCodePath(c7, 2));
- static UChar c8[] = { 0xD83C, 0xDDF0 };
- EXPECT_EQ(Font::Complex, Font::characterRangeCodePath(c8, 2));
- static UChar c9[] = { 0xD83C, 0xDDFF };
- EXPECT_EQ(Font::Complex, Font::characterRangeCodePath(c9, 2));
- static UChar c10[] = { 0xD83C, 0xDE00 };
- EXPECT_EQ(Font::Simple, Font::characterRangeCodePath(c10, 2));
-
- static UChar c11[] = { 0xDB40, 0xDCFF };
- EXPECT_EQ(Font::Simple, Font::characterRangeCodePath(c11, 2));
- static UChar c12[] = { 0xDB40, 0xDD00 };
- EXPECT_EQ(Font::Complex, Font::characterRangeCodePath(c12, 2));
- static UChar c13[] = { 0xDB40, 0xDDED };
- EXPECT_EQ(Font::Complex, Font::characterRangeCodePath(c13, 2));
- static UChar c14[] = { 0xDB40, 0xDDEF };
- EXPECT_EQ(Font::Complex, Font::characterRangeCodePath(c14, 2));
- static UChar c15[] = { 0xDB40, 0xDDF0 };
- EXPECT_EQ(Font::Simple, Font::characterRangeCodePath(c15, 2));
-}
-
-TEST(FontTest, TestCharacterRangeCodePathString)
-{
- // Simple-Simple is still simple
- static UChar c1[] = { 0x2FF, 0x2FF };
- EXPECT_EQ(Font::Simple, Font::characterRangeCodePath(c1, 2));
- // Complex-Simple is Complex
- static UChar c2[] = { 0x300, 0x2FF };
- EXPECT_EQ(Font::Complex, Font::characterRangeCodePath(c2, 2));
- // Simple-Complex is Complex
- static UChar c3[] = { 0x2FF, 0x330 };
- EXPECT_EQ(Font::Complex, Font::characterRangeCodePath(c3, 2));
- // Complex-Complex is Complex
- static UChar c4[] = { 0x36F, 0x330 };
- EXPECT_EQ(Font::Complex, Font::characterRangeCodePath(c4, 2));
- // SimpleWithGlyphOverflow-Simple is SimpleWithGlyphOverflow
- static UChar c5[] = { 0x1E00, 0x2FF };
- EXPECT_EQ(Font::SimpleWithGlyphOverflow, Font::characterRangeCodePath(c5, 2));
- // Simple-SimpleWithGlyphOverflow is SimpleWithGlyphOverflow
- static UChar c6[] = { 0x2FF, 0x2000 };
- EXPECT_EQ(Font::SimpleWithGlyphOverflow, Font::characterRangeCodePath(c6, 2));
- // SimpleWithGlyphOverflow-Complex is Complex
- static UChar c7[] = { 0x1E00, 0x330 };
- EXPECT_EQ(Font::Complex, Font::characterRangeCodePath(c7, 2));
- // Complex-SimpleWithGlyphOverflow is Complex
- static UChar c8[] = { 0x330, 0x2000 };
- EXPECT_EQ(Font::Complex, Font::characterRangeCodePath(c8, 2));
- // Surrogate-Complex is Complex
- static UChar c9[] = { 0xD83C, 0xDDE5, 0x330 };
- EXPECT_EQ(Font::Complex, Font::characterRangeCodePath(c9, 3));
- // Complex-Surrogate is Complex
- static UChar c10[] = { 0x330, 0xD83C, 0xDDE5 };
- EXPECT_EQ(Font::Complex, Font::characterRangeCodePath(c10, 3));
-}
-
-static void TestSpecificUChar32RangeIdeograph(UChar32 rangeStart, UChar32 rangeEnd)
-{
- EXPECT_FALSE(Font::isCJKIdeograph(rangeStart - 1));
- EXPECT_TRUE(Font::isCJKIdeograph(rangeStart));
- EXPECT_TRUE(Font::isCJKIdeograph((UChar32)((uint64_t)rangeStart + (uint64_t)rangeEnd) / 2));
- EXPECT_TRUE(Font::isCJKIdeograph(rangeEnd));
- EXPECT_FALSE(Font::isCJKIdeograph(rangeEnd + 1));
-}
-
-TEST(FontTest, TestIsCJKIdeograph)
-{
- // The basic CJK Unified Ideographs block.
- TestSpecificUChar32RangeIdeograph(0x4E00, 0x9FFF);
- // CJK Unified Ideographs Extension A.
- TestSpecificUChar32RangeIdeograph(0x3400, 0x4DBF);
- // CJK Unified Ideographs Extension A and Kangxi Radicals.
- TestSpecificUChar32RangeIdeograph(0x2E80, 0x2FDF);
- // CJK Strokes.
- TestSpecificUChar32RangeIdeograph(0x31C0, 0x31EF);
- // CJK Compatibility Ideographs.
- TestSpecificUChar32RangeIdeograph(0xF900, 0xFAFF);
- // CJK Unified Ideographs Extension B.
- TestSpecificUChar32RangeIdeograph(0x20000, 0x2A6DF);
- // CJK Unified Ideographs Extension C.
- // CJK Unified Ideographs Extension D.
- TestSpecificUChar32RangeIdeograph(0x2A700, 0x2B81F);
- // CJK Compatibility Ideographs Supplement.
- TestSpecificUChar32RangeIdeograph(0x2F800, 0x2FA1F);
-}
-
-static void TestSpecificUChar32RangeIdeographSymbol(UChar32 rangeStart, UChar32 rangeEnd)
-{
- EXPECT_FALSE(Font::isCJKIdeographOrSymbol(rangeStart - 1));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(rangeStart));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol((UChar32)((uint64_t)rangeStart + (uint64_t)rangeEnd) / 2));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(rangeEnd));
- EXPECT_FALSE(Font::isCJKIdeographOrSymbol(rangeEnd + 1));
-}
-
-TEST(FontTest, TestIsCJKIdeographOrSymbol)
-{
- // CJK Compatibility Ideographs Supplement.
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x2C7));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x2CA));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x2CB));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x2D9));
-
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x2020));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x2021));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x2030));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x203B));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x203C));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x2042));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x2047));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x2048));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x2049));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x2051));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x20DD));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x20DE));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x2100));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x2103));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x2105));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x2109));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x210A));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x2113));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x2116));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x2121));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x212B));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x213B));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x2150));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x2151));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x2152));
-
- TestSpecificUChar32RangeIdeographSymbol(0x2156, 0x215A);
- TestSpecificUChar32RangeIdeographSymbol(0x2160, 0x216B);
- TestSpecificUChar32RangeIdeographSymbol(0x2170, 0x217B);
-
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x217F));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x2189));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x2307));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x2312));
-
- EXPECT_FALSE(Font::isCJKIdeographOrSymbol(0x23BD));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x23BE));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x23C4));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x23CC));
- EXPECT_FALSE(Font::isCJKIdeographOrSymbol(0x23CD));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x23CE));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x2423));
-
- TestSpecificUChar32RangeIdeographSymbol(0x2460, 0x2492);
- TestSpecificUChar32RangeIdeographSymbol(0x249C, 0x24FF);
-
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x25A0));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x25A1));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x25A2));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x25AA));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x25AB));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x25B1));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x25B2));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x25B3));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x25B6));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x25B7));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x25BC));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x25BD));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x25C0));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x25C1));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x25C6));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x25C7));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x25C9));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x25CB));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x25CC));
-
- TestSpecificUChar32RangeIdeographSymbol(0x25CE, 0x25D3);
- TestSpecificUChar32RangeIdeographSymbol(0x25E2, 0x25E6);
-
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x25EF));
-
- TestSpecificUChar32RangeIdeographSymbol(0x2600, 0x2603);
-
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x2605));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x2606));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x260E));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x2616));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x2617));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x2640));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x2642));
-
- TestSpecificUChar32RangeIdeographSymbol(0x2660, 0x266F);
- TestSpecificUChar32RangeIdeographSymbol(0x2672, 0x267D);
-
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x26A0));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x26BD));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x26BE));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x2713));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x271A));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x273F));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x2740));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x2756));
-
- TestSpecificUChar32RangeIdeographSymbol(0x2776, 0x277F);
-
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x2B1A));
-
- TestSpecificUChar32RangeIdeographSymbol(0x2FF0, 0x302F);
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x3031));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x312F));
- EXPECT_FALSE(Font::isCJKIdeographOrSymbol(0x3130));
-
- EXPECT_FALSE(Font::isCJKIdeographOrSymbol(0x318F));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x3190));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x319F));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x31BF));
-
- EXPECT_FALSE(Font::isCJKIdeographOrSymbol(0x31FF));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x3200));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x3300));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x33FF));
-
- TestSpecificUChar32RangeIdeographSymbol(0xF860, 0xF862);
- TestSpecificUChar32RangeIdeographSymbol(0xFE30, 0xFE4F);
-
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0xFE10));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0xFE11));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0xFE12));
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0xFE19));
-
- EXPECT_FALSE(Font::isCJKIdeographOrSymbol(0xFF0D));
- EXPECT_FALSE(Font::isCJKIdeographOrSymbol(0xFF1B));
- EXPECT_FALSE(Font::isCJKIdeographOrSymbol(0xFF1C));
- EXPECT_FALSE(Font::isCJKIdeographOrSymbol(0xFF1E));
-
- TestSpecificUChar32RangeIdeographSymbol(0xFF00, 0xFFEF);
-
- EXPECT_TRUE(Font::isCJKIdeographOrSymbol(0x1F100));
-
- TestSpecificUChar32RangeIdeographSymbol(0x1F110, 0x1F129);
- TestSpecificUChar32RangeIdeographSymbol(0x1F130, 0x1F149);
- TestSpecificUChar32RangeIdeographSymbol(0x1F150, 0x1F169);
- TestSpecificUChar32RangeIdeographSymbol(0x1F170, 0x1F189);
- TestSpecificUChar32RangeIdeographSymbol(0x1F200, 0x1F6FF);
-}
-
-} // namespace WebCore
-
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/FontTraitsMask.h b/chromium/third_party/WebKit/Source/core/platform/graphics/FontTraitsMask.h
deleted file mode 100644
index b95d131ff5d..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/FontTraitsMask.h
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * Copyright (C) 2008 Apple Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef FontTraitsMask_h
-#define FontTraitsMask_h
-
-namespace WebCore {
-
-enum {
- FontStyleNormalBit = 0,
- FontStyleItalicBit,
- FontVariantNormalBit,
- FontVariantSmallCapsBit,
- FontWeight100Bit,
- FontWeight200Bit,
- FontWeight300Bit,
- FontWeight400Bit,
- FontWeight500Bit,
- FontWeight600Bit,
- FontWeight700Bit,
- FontWeight800Bit,
- FontWeight900Bit,
- FontTraitsMaskWidth
-};
-
-enum FontTraitsMask {
- FontStyleNormalMask = 1 << FontStyleNormalBit,
- FontStyleItalicMask = 1 << FontStyleItalicBit,
- FontStyleMask = FontStyleNormalMask | FontStyleItalicMask,
-
- FontVariantNormalMask = 1 << FontVariantNormalBit,
- FontVariantSmallCapsMask = 1 << FontVariantSmallCapsBit,
- FontVariantMask = FontVariantNormalMask | FontVariantSmallCapsMask,
-
- FontWeight100Mask = 1 << FontWeight100Bit,
- FontWeight200Mask = 1 << FontWeight200Bit,
- FontWeight300Mask = 1 << FontWeight300Bit,
- FontWeight400Mask = 1 << FontWeight400Bit,
- FontWeight500Mask = 1 << FontWeight500Bit,
- FontWeight600Mask = 1 << FontWeight600Bit,
- FontWeight700Mask = 1 << FontWeight700Bit,
- FontWeight800Mask = 1 << FontWeight800Bit,
- FontWeight900Mask = 1 << FontWeight900Bit,
- FontWeightMask = FontWeight100Mask | FontWeight200Mask | FontWeight300Mask | FontWeight400Mask | FontWeight500Mask | FontWeight600Mask | FontWeight700Mask | FontWeight800Mask | FontWeight900Mask
-};
-
-} // namespace WebCore
-#endif // FontTraitsMask_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/FontWidthVariant.h b/chromium/third_party/WebKit/Source/core/platform/graphics/FontWidthVariant.h
deleted file mode 100644
index 6016437f2c3..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/FontWidthVariant.h
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright (C) 2011 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef FontWidthVariant_h
-#define FontWidthVariant_h
-
-#include "wtf/Assertions.h"
-
-namespace WebCore {
-
-enum FontWidthVariant {
- RegularWidth,
- HalfWidth,
- ThirdWidth,
- QuarterWidth,
- LastFontWidthVariant = QuarterWidth
-};
-
-const unsigned FontWidthVariantWidth = 2;
-
-COMPILE_ASSERT(LastFontWidthVariant >> FontWidthVariantWidth == 0, FontWidthVariantWidth_is_correct);
-
-} // namespace WebCore
-
-#endif // FontWidthVariant_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/FrameData.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/FrameData.cpp
deleted file mode 100644
index 17b40859814..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/FrameData.cpp
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
- * Copyright (C) 2004, 2005, 2006, 2008 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/FrameData.h"
-
-#include "core/platform/graphics/skia/NativeImageSkia.h"
-
-namespace WebCore {
-
-FrameData::FrameData()
- : m_frame(0)
- , m_orientation(DefaultImageOrientation)
- , m_duration(0)
- , m_haveMetadata(false)
- , m_isComplete(false)
- , m_hasAlpha(true)
- , m_frameBytes(0)
-{
-}
-
-FrameData::~FrameData()
-{
- clear(true);
-}
-
-bool FrameData::clear(bool clearMetadata)
-{
- if (clearMetadata)
- m_haveMetadata = false;
-
- m_orientation = DefaultImageOrientation;
-
- if (m_frame) {
- m_frame.clear();
-
- return true;
- }
- return false;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/FrameData.h b/chromium/third_party/WebKit/Source/core/platform/graphics/FrameData.h
deleted file mode 100644
index a2c2381636d..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/FrameData.h
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
- * Copyright (C) 2004, 2005, 2006 Apple Computer, Inc. All rights reserved.
- * Copyright (C) 2008-2009 Torch Mobile, Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef FrameData_h
-#define FrameData_h
-
-#include "core/platform/graphics/ImageOrientation.h"
-#include "wtf/Noncopyable.h"
-#include "wtf/RefPtr.h"
-#include "wtf/VectorTraits.h"
-
-namespace WebCore {
-struct FrameData;
-}
-
-namespace WTF {
-template<> struct VectorTraits<WebCore::FrameData> : public SimpleClassVectorTraits {
- static const bool canInitializeWithMemset = false; // Not all FrameData members initialize to 0.
-};
-}
-
-namespace WebCore {
-
-class NativeImageSkia;
-
-struct FrameData {
- WTF_MAKE_NONCOPYABLE(FrameData);
-public:
- FrameData();
- ~FrameData();
-
- // Clear the cached image data on the frame, and (optionally) the metadata.
- // Returns whether there was cached image data to clear.
- bool clear(bool clearMetadata);
-
- RefPtr<NativeImageSkia> m_frame;
- ImageOrientation m_orientation;
- float m_duration;
- bool m_haveMetadata : 1;
- bool m_isComplete : 1;
- bool m_hasAlpha : 1;
- unsigned m_frameBytes;
-};
-
-} // namespace WebCore
-
-#endif // FrameData_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/GeneratedImage.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/GeneratedImage.cpp
deleted file mode 100644
index bb7aa0b2460..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/GeneratedImage.cpp
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/GeneratedImage.h"
-
-#include "core/platform/graphics/FloatSize.h"
-
-
-namespace WebCore {
-
-void GeneratedImage::computeIntrinsicDimensions(Length& intrinsicWidth, Length& intrinsicHeight, FloatSize& intrinsicRatio)
-{
- Image::computeIntrinsicDimensions(intrinsicWidth, intrinsicHeight, intrinsicRatio);
- intrinsicRatio = FloatSize();
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/GeneratedImage.h b/chromium/third_party/WebKit/Source/core/platform/graphics/GeneratedImage.h
deleted file mode 100644
index 8c5bfb1f8c1..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/GeneratedImage.h
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright (C) 2008 Apple Computer, Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef GeneratedImage_h
-#define GeneratedImage_h
-
-#include "core/platform/graphics/Image.h"
-#include "core/platform/graphics/IntSize.h"
-#include "wtf/RefPtr.h"
-
-namespace WebCore {
-
-class GeneratedImage : public Image {
-public:
- virtual bool currentFrameHasSingleSecurityOrigin() const OVERRIDE { return true; }
-
- virtual void setContainerSize(const IntSize& size) OVERRIDE { m_size = size; }
- virtual bool usesContainerSize() const OVERRIDE { return true; }
- virtual bool hasRelativeWidth() const OVERRIDE { return true; }
- virtual bool hasRelativeHeight() const OVERRIDE { return true; }
- virtual void computeIntrinsicDimensions(Length& intrinsicWidth, Length& intrinsicHeight, FloatSize& intrinsicRatio) OVERRIDE;
-
- virtual IntSize size() const OVERRIDE { return m_size; }
-
- // Assume that generated content has no decoded data we need to worry about
- virtual void destroyDecodedData(bool) OVERRIDE { }
- virtual unsigned decodedSize() const OVERRIDE { return 0; }
-
-protected:
- virtual void drawPattern(GraphicsContext*, const FloatRect&,
- const FloatSize&, const FloatPoint&, CompositeOperator,
- const FloatRect&, BlendMode) OVERRIDE = 0;
-
- // FIXME: Implement this to be less conservative.
- virtual bool currentFrameKnownToBeOpaque() OVERRIDE { return false; }
-
- GeneratedImage() { }
-
- IntSize m_size;
-};
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/GeneratorGeneratedImage.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/GeneratorGeneratedImage.cpp
deleted file mode 100644
index 149bc1bb2f9..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/GeneratorGeneratedImage.cpp
+++ /dev/null
@@ -1,152 +0,0 @@
-/*
- * Copyright (C) 2008, 2009, 2010, 2012 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/GeneratorGeneratedImage.h"
-
-#include "core/platform/graphics/FloatRect.h"
-#include "core/platform/graphics/GraphicsContextStateSaver.h"
-
-#define SKIA_MAX_PATTERN_SIZE 32767
-
-namespace WebCore {
-
-void GeneratorGeneratedImage::draw(GraphicsContext* destContext, const FloatRect& destRect, const FloatRect& srcRect, CompositeOperator compositeOp, BlendMode blendMode)
-{
- GraphicsContextStateSaver stateSaver(*destContext);
- destContext->setCompositeOperation(compositeOp, blendMode);
- destContext->clip(destRect);
- destContext->translate(destRect.x(), destRect.y());
- if (destRect.size() != srcRect.size())
- destContext->scale(FloatSize(destRect.width() / srcRect.width(), destRect.height() / srcRect.height()));
- destContext->translate(-srcRect.x(), -srcRect.y());
- destContext->setFillGradient(m_gradient);
- destContext->fillRect(FloatRect(FloatPoint(), m_size));
-}
-
-void GeneratorGeneratedImage::drawPatternWithoutCache(GraphicsContext* destContext, const FloatRect& srcRect, const FloatSize& scale,
- const FloatPoint& phase, CompositeOperator compositeOp, const FloatRect& destRect, BlendMode blendMode)
-{
- int firstColumn = static_cast<int>(floorf((((destRect.x() - phase.x()) / scale.width()) - srcRect.x()) / srcRect.width()));
- int firstRow = static_cast<int>(floorf((((destRect.y() - phase.y()) / scale.height()) - srcRect.y()) / srcRect.height()));
- for (int i = firstColumn; ; ++i) {
- float dstX = (srcRect.x() + i * srcRect.width()) * scale.width() + phase.x();
- // assert that first column encroaches left edge of dstRect.
- ASSERT(i > firstColumn || dstX <= destRect.x());
- ASSERT(i == firstColumn || dstX > destRect.x());
-
- if (dstX >= destRect.maxX())
- break;
- float dstMaxX = dstX + srcRect.width() * scale.width();
- if (dstX < destRect.x())
- dstX = destRect.x();
- if (dstMaxX > destRect.maxX())
- dstMaxX = destRect.maxX();
- if (dstX >= dstMaxX)
- continue;
-
- FloatRect visibleSrcRect;
- FloatRect tileDstRect;
- tileDstRect.setX(dstX);
- tileDstRect.setWidth(dstMaxX - dstX);
- visibleSrcRect.setX((tileDstRect.x() - phase.x()) / scale.width() - i * srcRect.width());
- visibleSrcRect.setWidth(tileDstRect.width() / scale.width());
-
- for (int j = firstRow; ; j++) {
- float dstY = (srcRect.y() + j * srcRect.height()) * scale.height() + phase.y();
- // assert that first row encroaches top edge of dstRect.
- ASSERT(j > firstRow || dstY <= destRect.y());
- ASSERT(j == firstRow || dstY > destRect.y());
-
- if (dstY >= destRect.maxY())
- break;
- float dstMaxY = dstY + srcRect.height() * scale.height();
- if (dstY < destRect.y())
- dstY = destRect.y();
- if (dstMaxY > destRect.maxY())
- dstMaxY = destRect.maxY();
- if (dstY >= dstMaxY)
- continue;
-
- tileDstRect.setY(dstY);
- tileDstRect.setHeight(dstMaxY - dstY);
- visibleSrcRect.setY((tileDstRect.y() - phase.y()) / scale.height() - j * srcRect.height());
- visibleSrcRect.setHeight(tileDstRect.height() / scale.height());
- draw(destContext, tileDstRect, visibleSrcRect, compositeOp, blendMode);
- }
- }
-}
-
-void GeneratorGeneratedImage::drawPattern(GraphicsContext* destContext, const FloatRect& srcRect, const FloatSize& scale,
- const FloatPoint& phase, CompositeOperator compositeOp, const FloatRect& destRect, BlendMode blendMode)
-{
- // Allow the generator to provide visually-equivalent tiling parameters for better performance.
- IntSize adjustedSize = m_size;
- FloatRect adjustedSrcRect = srcRect;
-
- m_gradient->adjustParametersForTiledDrawing(adjustedSize, adjustedSrcRect);
-
- if (adjustedSize.width() > SKIA_MAX_PATTERN_SIZE || adjustedSize.height() > SKIA_MAX_PATTERN_SIZE) {
- // Workaround to fix crbug.com/241486
- // SkBitmapProcShader is unable to handle cached tiles >= 32k pixels high or wide.
- drawPatternWithoutCache(destContext, srcRect, scale, phase, compositeOp, destRect, blendMode);
- return;
- }
-
- // Factor in the destination context's scale to generate at the best resolution.
- // FIXME: No need to get the full CTM here, we just need the scale.
- AffineTransform destContextCTM = destContext->getCTM(GraphicsContext::DefinitelyIncludeDeviceScale);
- float xScale = fabs(destContextCTM.xScale());
- float yScale = fabs(destContextCTM.yScale());
- FloatSize scaleWithoutCTM(scale.width() / xScale, scale.height() / yScale);
- adjustedSrcRect.scale(xScale, yScale);
-
- unsigned generatorHash = m_gradient->hash();
-
- if (!m_cachedImageBuffer || m_cachedGeneratorHash != generatorHash || m_cachedAdjustedSize != adjustedSize || !destContext->isCompatibleWithBuffer(m_cachedImageBuffer.get())) {
- m_cachedImageBuffer = destContext->createCompatibleBuffer(adjustedSize, m_gradient->hasAlpha());
- if (!m_cachedImageBuffer)
- return;
-
- // Fill with the generated image.
- m_cachedImageBuffer->context()->setFillGradient(m_gradient);
- m_cachedImageBuffer->context()->fillRect(FloatRect(FloatPoint(), adjustedSize));
-
- m_cachedGeneratorHash = generatorHash;
- m_cachedAdjustedSize = adjustedSize;
- }
-
- // Tile the image buffer into the context.
- m_cachedImageBuffer->drawPattern(destContext, adjustedSrcRect, scaleWithoutCTM, phase, compositeOp, destRect, blendMode);
- m_cacheTimer.restart();
-}
-
-void GeneratorGeneratedImage::invalidateCacheTimerFired(DeferrableOneShotTimer<GeneratorGeneratedImage>*)
-{
- m_cachedImageBuffer.clear();
- m_cachedAdjustedSize = IntSize();
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/GeneratorGeneratedImage.h b/chromium/third_party/WebKit/Source/core/platform/graphics/GeneratorGeneratedImage.h
deleted file mode 100644
index 1b7b0f3c2a0..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/GeneratorGeneratedImage.h
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * Copyright (C) 2008, 2012 Apple Computer, Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef GeneratorGeneratedImage_h
-#define GeneratorGeneratedImage_h
-
-#include "core/platform/Timer.h"
-#include "core/platform/graphics/GeneratedImage.h"
-#include "core/platform/graphics/Gradient.h"
-#include "core/platform/graphics/Image.h"
-#include "core/platform/graphics/ImageBuffer.h"
-#include "core/platform/graphics/IntSize.h"
-#include "wtf/RefPtr.h"
-
-namespace WebCore {
-
-static const int generatedImageCacheClearDelay = 1;
-
-class GeneratorGeneratedImage : public GeneratedImage {
-public:
- static PassRefPtr<GeneratorGeneratedImage> create(PassRefPtr<Gradient> generator, const IntSize& size)
- {
- return adoptRef(new GeneratorGeneratedImage(generator, size));
- }
-
- virtual ~GeneratorGeneratedImage()
- {
- m_cacheTimer.stop();
- }
-
-protected:
- virtual void draw(GraphicsContext*, const FloatRect&, const FloatRect&,
- CompositeOperator, BlendMode) OVERRIDE;
- virtual void drawPattern(GraphicsContext*, const FloatRect&,
- const FloatSize&, const FloatPoint&, CompositeOperator,
- const FloatRect&, BlendMode) OVERRIDE;
-
- void drawPatternWithoutCache(GraphicsContext*, const FloatRect&, const FloatSize&,
- const FloatPoint&, CompositeOperator, const FloatRect&, BlendMode);
-
- void invalidateCacheTimerFired(DeferrableOneShotTimer<GeneratorGeneratedImage>*);
-
- GeneratorGeneratedImage(PassRefPtr<Gradient> generator, const IntSize& size)
- : m_gradient(generator)
- , m_cacheTimer(this, &GeneratorGeneratedImage::invalidateCacheTimerFired, generatedImageCacheClearDelay)
- {
- m_size = size;
- }
-
- RefPtr<Gradient> m_gradient;
-
- OwnPtr<ImageBuffer> m_cachedImageBuffer;
- DeferrableOneShotTimer<GeneratorGeneratedImage> m_cacheTimer;
- IntSize m_cachedAdjustedSize;
- unsigned m_cachedGeneratorHash;
-};
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/Glyph.h b/chromium/third_party/WebKit/Source/core/platform/graphics/Glyph.h
deleted file mode 100644
index a96770f0341..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/Glyph.h
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright (C) 2006, 2007, 2008 Apple Inc. All rights reserved.
- * Copyright (C) Research In Motion Limited 2011. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef Glyph_h
-#define Glyph_h
-
-namespace WebCore {
-
-typedef unsigned short Glyph;
-
-} // namespace WebCore
-
-#endif // Glyph_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/GlyphBuffer.h b/chromium/third_party/WebKit/Source/core/platform/graphics/GlyphBuffer.h
deleted file mode 100644
index b5806156a5e..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/GlyphBuffer.h
+++ /dev/null
@@ -1,149 +0,0 @@
-/*
- * Copyright (C) 2006, 2009, 2011 Apple Inc. All rights reserved.
- * Copyright (C) 2007-2008 Torch Mobile Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef GlyphBuffer_h
-#define GlyphBuffer_h
-
-#include "core/platform/graphics/FloatSize.h"
-#include "core/platform/graphics/Glyph.h"
-#include "wtf/UnusedParam.h"
-#include "wtf/Vector.h"
-
-#if OS(MACOSX)
-#include <ApplicationServices/ApplicationServices.h>
-#endif
-
-namespace WebCore {
-
-class SimpleFontData;
-
-typedef Glyph GlyphBufferGlyph;
-
-// CG uses CGSize instead of FloatSize so that the result of advances()
-// can be passed directly to CGContextShowGlyphsWithAdvances in FontMac.mm
-#if OS(MACOSX)
-struct GlyphBufferAdvance : CGSize {
-public:
- GlyphBufferAdvance(CGSize size) : CGSize(size)
- {
- }
-
- void setWidth(CGFloat width) { this->CGSize::width = width; }
- CGFloat width() const { return this->CGSize::width; }
- CGFloat height() const { return this->CGSize::height; }
-};
-#else
-typedef FloatSize GlyphBufferAdvance;
-#endif
-
-class GlyphBuffer {
-public:
- bool isEmpty() const { return m_fontData.isEmpty(); }
- int size() const { return m_fontData.size(); }
-
- void clear()
- {
- m_fontData.clear();
- m_glyphs.clear();
- m_advances.clear();
- }
-
- GlyphBufferGlyph* glyphs(int from) { return m_glyphs.data() + from; }
- GlyphBufferAdvance* advances(int from) { return m_advances.data() + from; }
- const GlyphBufferGlyph* glyphs(int from) const { return m_glyphs.data() + from; }
- const GlyphBufferAdvance* advances(int from) const { return m_advances.data() + from; }
-
- const SimpleFontData* fontDataAt(int index) const { return m_fontData[index]; }
-
- Glyph glyphAt(int index) const
- {
- return m_glyphs[index];
- }
-
- float advanceAt(int index) const
- {
- return m_advances[index].width();
- }
-
- void add(Glyph glyph, const SimpleFontData* font, float width)
- {
- m_fontData.append(font);
- m_glyphs.append(glyph);
-
-#if OS(MACOSX)
- CGSize advance = { width, 0 };
- m_advances.append(advance);
-#else
- m_advances.append(FloatSize(width, 0));
-#endif
- }
-
- void add(Glyph glyph, const SimpleFontData* font, GlyphBufferAdvance advance)
- {
- m_fontData.append(font);
- m_glyphs.append(glyph);
- m_advances.append(advance);
- }
-
- void reverse(int from, int length)
- {
- for (int i = from, end = from + length - 1; i < end; ++i, --end)
- swap(i, end);
- }
-
- void expandLastAdvance(float width)
- {
- ASSERT(!isEmpty());
- GlyphBufferAdvance& lastAdvance = m_advances.last();
- lastAdvance.setWidth(lastAdvance.width() + width);
- }
-
-private:
- void swap(int index1, int index2)
- {
- const SimpleFontData* f = m_fontData[index1];
- m_fontData[index1] = m_fontData[index2];
- m_fontData[index2] = f;
-
- GlyphBufferGlyph g = m_glyphs[index1];
- m_glyphs[index1] = m_glyphs[index2];
- m_glyphs[index2] = g;
-
- GlyphBufferAdvance s = m_advances[index1];
- m_advances[index1] = m_advances[index2];
- m_advances[index2] = s;
- }
-
- Vector<const SimpleFontData*, 2048> m_fontData;
- Vector<GlyphBufferGlyph, 2048> m_glyphs;
- Vector<GlyphBufferAdvance, 2048> m_advances;
-};
-
-}
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/GlyphMetricsMap.h b/chromium/third_party/WebKit/Source/core/platform/graphics/GlyphMetricsMap.h
deleted file mode 100644
index 64245a22b18..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/GlyphMetricsMap.h
+++ /dev/null
@@ -1,129 +0,0 @@
-/*
- * Copyright (C) 2006, 2009 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef GlyphMetricsMap_h
-#define GlyphMetricsMap_h
-
-#include "core/platform/graphics/Glyph.h"
-#include "wtf/Assertions.h"
-#include "wtf/HashMap.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/unicode/Unicode.h"
-
-namespace WebCore {
-
-const float cGlyphSizeUnknown = -1;
-
-template<class T> class GlyphMetricsMap {
- WTF_MAKE_NONCOPYABLE(GlyphMetricsMap);
-public:
- GlyphMetricsMap() : m_filledPrimaryPage(false) { }
- T metricsForGlyph(Glyph glyph)
- {
- return locatePage(glyph / GlyphMetricsPage::size)->metricsForGlyph(glyph);
- }
-
- void setMetricsForGlyph(Glyph glyph, const T& metrics)
- {
- locatePage(glyph / GlyphMetricsPage::size)->setMetricsForGlyph(glyph, metrics);
- }
-
-private:
- class GlyphMetricsPage {
- public:
- static const size_t size = 256; // Usually covers Latin-1 in a single page.
-
- T metricsForGlyph(Glyph glyph) const { return m_metrics[glyph % size]; }
- void setMetricsForGlyph(Glyph glyph, const T& metrics)
- {
- setMetricsForIndex(glyph % size, metrics);
- }
- void setMetricsForIndex(unsigned index, const T& metrics)
- {
- ASSERT_WITH_SECURITY_IMPLICATION(index < size);
- m_metrics[index] = metrics;
- }
-
- private:
- T m_metrics[size];
- };
-
- GlyphMetricsPage* locatePage(unsigned pageNumber)
- {
- if (!pageNumber && m_filledPrimaryPage)
- return &m_primaryPage;
- return locatePageSlowCase(pageNumber);
- }
-
- GlyphMetricsPage* locatePageSlowCase(unsigned pageNumber);
-
- static T unknownMetrics();
-
- bool m_filledPrimaryPage;
- GlyphMetricsPage m_primaryPage; // We optimize for the page that contains glyph indices 0-255.
- OwnPtr<HashMap<int, OwnPtr<GlyphMetricsPage> > > m_pages;
-};
-
-template<> inline float GlyphMetricsMap<float>::unknownMetrics()
-{
- return cGlyphSizeUnknown;
-}
-
-template<> inline FloatRect GlyphMetricsMap<FloatRect>::unknownMetrics()
-{
- return FloatRect(0, 0, cGlyphSizeUnknown, cGlyphSizeUnknown);
-}
-
-template<class T> typename GlyphMetricsMap<T>::GlyphMetricsPage* GlyphMetricsMap<T>::locatePageSlowCase(unsigned pageNumber)
-{
- GlyphMetricsPage* page;
- if (!pageNumber) {
- ASSERT(!m_filledPrimaryPage);
- page = &m_primaryPage;
- m_filledPrimaryPage = true;
- } else {
- if (m_pages) {
- if ((page = m_pages->get(pageNumber)))
- return page;
- } else
- m_pages = adoptPtr(new HashMap<int, OwnPtr<GlyphMetricsPage> >);
- page = new GlyphMetricsPage;
- m_pages->set(pageNumber, adoptPtr(page));
- }
-
- // Fill in the whole page with the unknown glyph information.
- for (unsigned i = 0; i < GlyphMetricsPage::size; i++)
- page->setMetricsForIndex(i, unknownMetrics());
-
- return page;
-}
-
-} // namespace WebCore
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/GlyphPage.h b/chromium/third_party/WebKit/Source/core/platform/graphics/GlyphPage.h
deleted file mode 100644
index 3c65ccb3133..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/GlyphPage.h
+++ /dev/null
@@ -1,204 +0,0 @@
-/*
- * Copyright (C) 2006, 2007, 2008, 2013 Apple Inc. All rights reserved.
- * Copyright (C) Research In Motion Limited 2011. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef GlyphPage_h
-#define GlyphPage_h
-
-#include <string.h>
-#include "core/platform/graphics/Glyph.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/RefPtr.h"
-#include "wtf/unicode/Unicode.h"
-
-namespace WebCore {
-
-class SimpleFontData;
-class GlyphPageTreeNode;
-
-// Holds the glyph index and the corresponding SimpleFontData information for a given
-// character.
-struct GlyphData {
- GlyphData(Glyph g = 0, const SimpleFontData* f = 0)
- : glyph(g)
- , fontData(f)
- {
- }
- Glyph glyph;
- const SimpleFontData* fontData;
-};
-
-#if COMPILER(MSVC)
-#pragma warning(push)
-#pragma warning(disable: 4200) // Disable "zero-sized array in struct/union" warning
-#endif
-
-// A GlyphPage contains a fixed-size set of GlyphData mappings for a contiguous
-// range of characters in the Unicode code space. GlyphPages are indexed
-// starting from 0 and incrementing for each 256 glyphs.
-//
-// One page may actually include glyphs from other fonts if the characters are
-// missing in the primary font. It is owned by exactly one GlyphPageTreeNode,
-// although multiple nodes may reference it as their "page" if they are supposed
-// to be overriding the parent's node, but provide no additional information.
-class GlyphPage : public RefCounted<GlyphPage> {
-public:
- static PassRefPtr<GlyphPage> createForMixedFontData(GlyphPageTreeNode* owner)
- {
- void* slot = fastMalloc(sizeof(GlyphPage) + sizeof(SimpleFontData*) * GlyphPage::size);
- return adoptRef(new (slot) GlyphPage(owner));
- }
-
- static PassRefPtr<GlyphPage> createForSingleFontData(GlyphPageTreeNode* owner, const SimpleFontData* fontData)
- {
- ASSERT(fontData);
- return adoptRef(new GlyphPage(owner, fontData));
- }
-
- PassRefPtr<GlyphPage> createCopiedSystemFallbackPage(GlyphPageTreeNode* owner) const
- {
- RefPtr<GlyphPage> page = GlyphPage::createForMixedFontData(owner);
- memcpy(page->m_glyphs, m_glyphs, sizeof(m_glyphs));
- if (hasPerGlyphFontData())
- memcpy(page->m_perGlyphFontData, m_perGlyphFontData, sizeof(SimpleFontData*) * GlyphPage::size);
- else {
- for (size_t i = 0; i < GlyphPage::size; ++i) {
- page->m_perGlyphFontData[i] = m_glyphs[i] ? m_fontDataForAllGlyphs : 0;
- }
- }
- return page.release();
- }
-
- ~GlyphPage() { }
-
- static const size_t size = 256; // Covers Latin-1 in a single page.
- static unsigned indexForCharacter(UChar32 c) { return c % GlyphPage::size; }
-
- ALWAYS_INLINE GlyphData glyphDataForCharacter(UChar32 c) const
- {
- return glyphDataForIndex(indexForCharacter(c));
- }
-
- ALWAYS_INLINE GlyphData glyphDataForIndex(unsigned index) const
- {
- ASSERT_WITH_SECURITY_IMPLICATION(index < size);
- Glyph glyph = m_glyphs[index];
- if (hasPerGlyphFontData())
- return GlyphData(glyph, m_perGlyphFontData[index]);
- return GlyphData(glyph, glyph ? m_fontDataForAllGlyphs : 0);
- }
-
- ALWAYS_INLINE Glyph glyphForCharacter(UChar32 c) const
- {
- return glyphAt(indexForCharacter(c));
- }
-
- ALWAYS_INLINE Glyph glyphAt(unsigned index) const
- {
- ASSERT_WITH_SECURITY_IMPLICATION(index < size);
- return m_glyphs[index];
- }
-
- ALWAYS_INLINE const SimpleFontData* fontDataForCharacter(UChar32 c) const
- {
- unsigned index = indexForCharacter(c);
- if (hasPerGlyphFontData())
- return m_perGlyphFontData[index];
- return m_glyphs[index] ? m_fontDataForAllGlyphs : 0;
- }
-
- void setGlyphDataForCharacter(UChar32 c, Glyph g, const SimpleFontData* f)
- {
- setGlyphDataForIndex(indexForCharacter(c), g, f);
- }
-
- void setGlyphDataForIndex(unsigned index, Glyph glyph, const SimpleFontData* fontData)
- {
- ASSERT_WITH_SECURITY_IMPLICATION(index < size);
- m_glyphs[index] = glyph;
-
- // GlyphPage getters will always return a null SimpleFontData* for glyph #0 if there's no per-glyph font array.
- if (hasPerGlyphFontData()) {
- m_perGlyphFontData[index] = glyph ? fontData : 0;
- return;
- }
-
- // A single-font GlyphPage already assigned m_fontDataForAllGlyphs in the constructor.
- ASSERT(!glyph || fontData == m_fontDataForAllGlyphs);
- }
-
- void setGlyphDataForIndex(unsigned index, const GlyphData& glyphData)
- {
- setGlyphDataForIndex(index, glyphData.glyph, glyphData.fontData);
- }
-
- void removeFontDataFromSystemFallbackPage(const SimpleFontData* fontData)
- {
- // This method should only be called on the system fallback page, which is never single-font.
- ASSERT(hasPerGlyphFontData());
- for (size_t i = 0; i < size; ++i) {
- if (m_perGlyphFontData[i] == fontData) {
- m_glyphs[i] = 0;
- m_perGlyphFontData[i] = 0;
- }
- }
- }
-
- GlyphPageTreeNode* owner() const { return m_owner; }
-
- // Implemented by the platform.
- bool fill(unsigned offset, unsigned length, UChar* characterBuffer, unsigned bufferLength, const SimpleFontData*);
-
-private:
- explicit GlyphPage(GlyphPageTreeNode* owner, const SimpleFontData* fontDataForAllGlyphs = 0)
- : m_fontDataForAllGlyphs(fontDataForAllGlyphs)
- , m_owner(owner)
- {
- memset(m_glyphs, 0, sizeof(m_glyphs));
- if (hasPerGlyphFontData())
- memset(m_perGlyphFontData, 0, sizeof(SimpleFontData*) * GlyphPage::size);
- }
-
- bool hasPerGlyphFontData() const { return !m_fontDataForAllGlyphs; }
-
- const SimpleFontData* m_fontDataForAllGlyphs;
- GlyphPageTreeNode* m_owner;
- Glyph m_glyphs[size];
-
- // NOTE: This array has (GlyphPage::size) elements if m_fontDataForAllGlyphs is null.
- const SimpleFontData* m_perGlyphFontData[0];
-};
-
-#if COMPILER(MSVC)
-#pragma warning(pop)
-#endif
-
-} // namespace WebCore
-
-#endif // GlyphPage_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/GlyphPageTreeNode.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/GlyphPageTreeNode.cpp
deleted file mode 100644
index 23a66b75678..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/GlyphPageTreeNode.cpp
+++ /dev/null
@@ -1,437 +0,0 @@
-/*
- * Copyright (C) 2006, 2007, 2008 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/GlyphPageTreeNode.h"
-
-#include <stdio.h>
-#include "core/platform/graphics/SegmentedFontData.h"
-#include "core/platform/graphics/SimpleFontData.h"
-#include "core/platform/graphics/opentype/OpenTypeVerticalData.h"
-#include "wtf/text/CString.h"
-#include "wtf/text/WTFString.h"
-#include "wtf/unicode/CharacterNames.h"
-#include "wtf/unicode/Unicode.h"
-
-namespace WebCore {
-
-using std::max;
-using std::min;
-
-HashMap<int, GlyphPageTreeNode*>* GlyphPageTreeNode::roots = 0;
-GlyphPageTreeNode* GlyphPageTreeNode::pageZeroRoot = 0;
-
-GlyphPageTreeNode* GlyphPageTreeNode::getRoot(unsigned pageNumber)
-{
- static bool initialized;
- if (!initialized) {
- initialized = true;
- roots = new HashMap<int, GlyphPageTreeNode*>;
- pageZeroRoot = new GlyphPageTreeNode;
- }
-
- if (!pageNumber)
- return pageZeroRoot;
-
- if (GlyphPageTreeNode* foundNode = roots->get(pageNumber))
- return foundNode;
-
- GlyphPageTreeNode* node = new GlyphPageTreeNode;
-#ifndef NDEBUG
- node->m_pageNumber = pageNumber;
-#endif
- roots->set(pageNumber, node);
- return node;
-}
-
-size_t GlyphPageTreeNode::treeGlyphPageCount()
-{
- size_t count = 0;
- if (roots) {
- HashMap<int, GlyphPageTreeNode*>::iterator end = roots->end();
- for (HashMap<int, GlyphPageTreeNode*>::iterator it = roots->begin(); it != end; ++it)
- count += it->value->pageCount();
- }
-
- if (pageZeroRoot)
- count += pageZeroRoot->pageCount();
-
- return count;
-}
-
-size_t GlyphPageTreeNode::pageCount() const
-{
- size_t count = m_page && m_page->owner() == this ? 1 : 0;
- GlyphPageTreeNodeMap::const_iterator end = m_children.end();
- for (GlyphPageTreeNodeMap::const_iterator it = m_children.begin(); it != end; ++it)
- count += it->value->pageCount();
-
- return count;
-}
-
-void GlyphPageTreeNode::pruneTreeCustomFontData(const FontData* fontData)
-{
- // Enumerate all the roots and prune any tree that contains our custom font data.
- if (roots) {
- HashMap<int, GlyphPageTreeNode*>::iterator end = roots->end();
- for (HashMap<int, GlyphPageTreeNode*>::iterator it = roots->begin(); it != end; ++it)
- it->value->pruneCustomFontData(fontData);
- }
-
- if (pageZeroRoot)
- pageZeroRoot->pruneCustomFontData(fontData);
-}
-
-void GlyphPageTreeNode::pruneTreeFontData(const SimpleFontData* fontData)
-{
- if (roots) {
- HashMap<int, GlyphPageTreeNode*>::iterator end = roots->end();
- for (HashMap<int, GlyphPageTreeNode*>::iterator it = roots->begin(); it != end; ++it)
- it->value->pruneFontData(fontData);
- }
-
- if (pageZeroRoot)
- pageZeroRoot->pruneFontData(fontData);
-}
-
-static bool fill(GlyphPage* pageToFill, unsigned offset, unsigned length, UChar* buffer, unsigned bufferLength, const SimpleFontData* fontData)
-{
-#if ENABLE(SVG_FONTS)
- if (SimpleFontData::AdditionalFontData* additionalFontData = fontData->fontData())
- return additionalFontData->fillSVGGlyphPage(pageToFill, offset, length, buffer, bufferLength, fontData);
-#endif
- bool hasGlyphs = pageToFill->fill(offset, length, buffer, bufferLength, fontData);
-#if ENABLE(OPENTYPE_VERTICAL)
- if (hasGlyphs && fontData->verticalData())
- fontData->verticalData()->substituteWithVerticalGlyphs(fontData, pageToFill, offset, length);
-#endif
- return hasGlyphs;
-}
-
-void GlyphPageTreeNode::initializePage(const FontData* fontData, unsigned pageNumber)
-{
- ASSERT(!m_page);
-
- // This function must not be called for the root of the tree, because that
- // level does not contain any glyphs.
- ASSERT(m_level > 0 && m_parent);
-
- // The parent's page will be 0 if we are level one or the parent's font data
- // did not contain any glyphs for that page.
- GlyphPage* parentPage = m_parent->page();
-
- // NULL FontData means we're being asked for the system fallback font.
- if (fontData) {
- if (m_level == 1) {
- // Children of the root hold pure pages. These will cover only one
- // font data's glyphs, and will have glyph index 0 if the font data does not
- // contain the glyph.
- unsigned start = pageNumber * GlyphPage::size;
- UChar buffer[GlyphPage::size * 2 + 2];
- unsigned bufferLength;
- unsigned i;
-
- // Fill in a buffer with the entire "page" of characters that we want to look up glyphs for.
- if (start < 0x10000) {
- bufferLength = GlyphPage::size;
- for (i = 0; i < GlyphPage::size; i++)
- buffer[i] = start + i;
-
- if (start == 0) {
- // Control characters must not render at all.
- for (i = 0; i < 0x20; ++i)
- buffer[i] = zeroWidthSpace;
- for (i = 0x7F; i < 0xA0; i++)
- buffer[i] = zeroWidthSpace;
- buffer[softHyphen] = zeroWidthSpace;
-
- // \n, \t, and nonbreaking space must render as a space.
- buffer[(int)'\n'] = ' ';
- buffer[(int)'\t'] = ' ';
- buffer[noBreakSpace] = ' ';
- } else if (start == (leftToRightMark & ~(GlyphPage::size - 1))) {
- // LRM, RLM, LRE, RLE, ZWNJ, ZWJ, and PDF must not render at all.
- buffer[leftToRightMark - start] = zeroWidthSpace;
- buffer[rightToLeftMark - start] = zeroWidthSpace;
- buffer[leftToRightEmbed - start] = zeroWidthSpace;
- buffer[rightToLeftEmbed - start] = zeroWidthSpace;
- buffer[leftToRightOverride - start] = zeroWidthSpace;
- buffer[rightToLeftOverride - start] = zeroWidthSpace;
- buffer[zeroWidthNonJoiner - start] = zeroWidthSpace;
- buffer[zeroWidthJoiner - start] = zeroWidthSpace;
- buffer[popDirectionalFormatting - start] = zeroWidthSpace;
- } else if (start == (objectReplacementCharacter & ~(GlyphPage::size - 1))) {
- // Object replacement character must not render at all.
- buffer[objectReplacementCharacter - start] = zeroWidthSpace;
- } else if (start == (zeroWidthNoBreakSpace & ~(GlyphPage::size - 1))) {
- // ZWNBS/BOM must not render at all.
- buffer[zeroWidthNoBreakSpace - start] = zeroWidthSpace;
- }
- } else {
- bufferLength = GlyphPage::size * 2;
- for (i = 0; i < GlyphPage::size; i++) {
- int c = i + start;
- buffer[i * 2] = U16_LEAD(c);
- buffer[i * 2 + 1] = U16_TRAIL(c);
- }
- }
-
- // Now that we have a buffer full of characters, we want to get back an array
- // of glyph indices. This part involves calling into the platform-specific
- // routine of our glyph map for actually filling in the page with the glyphs.
- // Success is not guaranteed. For example, Times fails to fill page 260, giving glyph data
- // for only 128 out of 256 characters.
- bool haveGlyphs;
- if (!fontData->isSegmented()) {
- m_page = GlyphPage::createForSingleFontData(this, static_cast<const SimpleFontData*>(fontData));
- haveGlyphs = fill(m_page.get(), 0, GlyphPage::size, buffer, bufferLength, static_cast<const SimpleFontData*>(fontData));
- } else {
- m_page = GlyphPage::createForMixedFontData(this);
- haveGlyphs = false;
-
- const SegmentedFontData* segmentedFontData = static_cast<const SegmentedFontData*>(fontData);
- unsigned numRanges = segmentedFontData->numRanges();
- bool zeroFilled = false;
- RefPtr<GlyphPage> scratchPage;
- GlyphPage* pageToFill = m_page.get();
- for (unsigned i = 0; i < numRanges; i++) {
- const FontDataRange& range = segmentedFontData->rangeAt(i);
- // all this casting is to ensure all the parameters to min and max have the same type,
- // to avoid ambiguous template parameter errors on Windows
- int from = max(0, static_cast<int>(range.from()) - static_cast<int>(start));
- int to = 1 + min(static_cast<int>(range.to()) - static_cast<int>(start), static_cast<int>(GlyphPage::size) - 1);
- if (from < static_cast<int>(GlyphPage::size) && to > 0) {
- // If this is a custom font needs to be loaded, kick off
- // the load here, and do not fill the page so that
- // font fallback is used while loading.
- if (range.fontData()->isLoadingFallback()) {
- range.fontData()->beginLoadIfNeeded();
- continue;
- }
-
- if (haveGlyphs && !scratchPage) {
- scratchPage = GlyphPage::createForMixedFontData(this);
- pageToFill = scratchPage.get();
- }
-
- if (!zeroFilled) {
- if (from > 0 || to < static_cast<int>(GlyphPage::size)) {
- for (unsigned i = 0; i < GlyphPage::size; i++)
- pageToFill->setGlyphDataForIndex(i, 0, 0);
- }
- zeroFilled = true;
- }
- haveGlyphs |= fill(pageToFill, from, to - from, buffer + from * (start < 0x10000 ? 1 : 2), (to - from) * (start < 0x10000 ? 1 : 2), range.fontData().get());
- if (scratchPage) {
- ASSERT_WITH_SECURITY_IMPLICATION(to <= static_cast<int>(GlyphPage::size));
- for (int j = from; j < to; j++) {
- if (!m_page->glyphAt(j) && pageToFill->glyphAt(j))
- m_page->setGlyphDataForIndex(j, pageToFill->glyphDataForIndex(j));
- }
- }
- }
- }
- }
-
- if (!haveGlyphs)
- m_page = 0;
- } else if (parentPage && parentPage->owner() != m_parent) {
- // The page we're overriding may not be owned by our parent node.
- // This happens when our parent node provides no useful overrides
- // and just copies the pointer to an already-existing page (see
- // below).
- //
- // We want our override to be shared by all nodes that reference
- // that page to avoid duplication, and so standardize on having the
- // page's owner collect all the overrides. Call getChild on the
- // page owner with the desired font data (this will populate
- // the page) and then reference it.
- m_page = parentPage->owner()->getChild(fontData, pageNumber)->page();
- } else {
- // Get the pure page for the fallback font (at level 1 with no
- // overrides). getRootChild will always create a page if one
- // doesn't exist, but the page doesn't necessarily have glyphs
- // (this pointer may be 0).
- GlyphPage* fallbackPage = getRootChild(fontData, pageNumber)->page();
- if (!parentPage) {
- // When the parent has no glyphs for this page, we can easily
- // override it just by supplying the glyphs from our font.
- m_page = fallbackPage;
- } else if (!fallbackPage) {
- // When our font has no glyphs for this page, we can just reference the
- // parent page.
- m_page = parentPage;
- } else {
- // Combine the parent's glyphs and ours to form a new more complete page.
- m_page = GlyphPage::createForMixedFontData(this);
-
- // Overlay the parent page on the fallback page. Check if the fallback font
- // has added anything.
- bool newGlyphs = false;
- for (unsigned i = 0; i < GlyphPage::size; i++) {
- if (parentPage->glyphAt(i))
- m_page->setGlyphDataForIndex(i, parentPage->glyphDataForIndex(i));
- else if (fallbackPage->glyphAt(i)) {
- m_page->setGlyphDataForIndex(i, fallbackPage->glyphDataForIndex(i));
- newGlyphs = true;
- } else
- m_page->setGlyphDataForIndex(i, 0, 0);
- }
-
- if (!newGlyphs)
- // We didn't override anything, so our override is just the parent page.
- m_page = parentPage;
- }
- }
- } else {
- // System fallback. Initialized with the parent's page here, as individual
- // entries may use different fonts depending on character. If the Font
- // ever finds it needs a glyph out of the system fallback page, it will
- // ask the system for the best font to use and fill that glyph in for us.
- if (parentPage)
- m_page = parentPage->createCopiedSystemFallbackPage(this);
- else
- m_page = GlyphPage::createForMixedFontData(this);
- }
-}
-
-GlyphPageTreeNode* GlyphPageTreeNode::getChild(const FontData* fontData, unsigned pageNumber)
-{
- ASSERT(fontData || !m_isSystemFallback);
- ASSERT(pageNumber == m_pageNumber);
-
- if (GlyphPageTreeNode* foundChild = fontData ? m_children.get(fontData) : m_systemFallbackChild.get())
- return foundChild;
-
- GlyphPageTreeNode* child = new GlyphPageTreeNode;
- child->m_parent = this;
- child->m_level = m_level + 1;
- if (fontData && fontData->isCustomFont()) {
- for (GlyphPageTreeNode* curr = this; curr; curr = curr->m_parent)
- curr->m_customFontCount++;
- }
-
-#ifndef NDEBUG
- child->m_pageNumber = m_pageNumber;
-#endif
- if (fontData) {
- m_children.set(fontData, adoptPtr(child));
- fontData->setMaxGlyphPageTreeLevel(max(fontData->maxGlyphPageTreeLevel(), child->m_level));
- } else {
- m_systemFallbackChild = adoptPtr(child);
- child->m_isSystemFallback = true;
- }
- child->initializePage(fontData, pageNumber);
- return child;
-}
-
-void GlyphPageTreeNode::pruneCustomFontData(const FontData* fontData)
-{
- if (!fontData || !m_customFontCount)
- return;
-
- // Prune any branch that contains this FontData.
- if (OwnPtr<GlyphPageTreeNode> node = m_children.take(fontData)) {
- if (unsigned customFontCount = node->m_customFontCount + 1) {
- for (GlyphPageTreeNode* curr = this; curr; curr = curr->m_parent)
- curr->m_customFontCount -= customFontCount;
- }
- }
-
- // Check any branches that remain that still have custom fonts underneath them.
- if (!m_customFontCount)
- return;
-
- GlyphPageTreeNodeMap::iterator end = m_children.end();
- for (GlyphPageTreeNodeMap::iterator it = m_children.begin(); it != end; ++it)
- it->value->pruneCustomFontData(fontData);
-}
-
-void GlyphPageTreeNode::pruneFontData(const SimpleFontData* fontData, unsigned level)
-{
- ASSERT(fontData);
-
- // Prune fall back child (if any) of this font.
- if (m_systemFallbackChild && m_systemFallbackChild->m_page)
- m_systemFallbackChild->m_page->removeFontDataFromSystemFallbackPage(fontData);
-
- // Prune any branch that contains this FontData.
- if (OwnPtr<GlyphPageTreeNode> node = m_children.take(fontData)) {
- if (unsigned customFontCount = node->m_customFontCount) {
- for (GlyphPageTreeNode* curr = this; curr; curr = curr->m_parent)
- curr->m_customFontCount -= customFontCount;
- }
- }
-
- level++;
- if (level > fontData->maxGlyphPageTreeLevel())
- return;
-
- GlyphPageTreeNodeMap::iterator end = m_children.end();
- for (GlyphPageTreeNodeMap::iterator it = m_children.begin(); it != end; ++it)
- it->value->pruneFontData(fontData, level);
-}
-
-#ifndef NDEBUG
- void GlyphPageTreeNode::showSubtree()
- {
- Vector<char> indent(level());
- indent.fill('\t', level());
- indent.append(0);
-
- GlyphPageTreeNodeMap::iterator end = m_children.end();
- for (GlyphPageTreeNodeMap::iterator it = m_children.begin(); it != end; ++it) {
- printf("%s\t%p %s\n", indent.data(), it->key, it->key->description().utf8().data());
- it->value->showSubtree();
- }
- if (m_systemFallbackChild) {
- printf("%s\t* fallback\n", indent.data());
- m_systemFallbackChild->showSubtree();
- }
- }
-#endif
-
-}
-
-#ifndef NDEBUG
-void showGlyphPageTrees()
-{
- printf("Page 0:\n");
- showGlyphPageTree(0);
- HashMap<int, WebCore::GlyphPageTreeNode*>::iterator end = WebCore::GlyphPageTreeNode::roots->end();
- for (HashMap<int, WebCore::GlyphPageTreeNode*>::iterator it = WebCore::GlyphPageTreeNode::roots->begin(); it != end; ++it) {
- printf("\nPage %d:\n", it->key);
- showGlyphPageTree(it->key);
- }
-}
-
-void showGlyphPageTree(unsigned pageNumber)
-{
- WebCore::GlyphPageTreeNode::getRoot(pageNumber)->showSubtree();
-}
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/GlyphPageTreeNode.h b/chromium/third_party/WebKit/Source/core/platform/graphics/GlyphPageTreeNode.h
deleted file mode 100644
index 63ffead2756..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/GlyphPageTreeNode.h
+++ /dev/null
@@ -1,141 +0,0 @@
-/*
- * Copyright (C) 2006, 2007, 2008 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef GlyphPageTreeNode_h
-#define GlyphPageTreeNode_h
-
-#include <string.h>
-#include "core/platform/graphics/GlyphPage.h"
-#include "wtf/HashMap.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/unicode/Unicode.h"
-
-#ifndef NDEBUG
-void showGlyphPageTrees();
-void showGlyphPageTree(unsigned pageNumber);
-#endif
-
-namespace WebCore {
-
-class FontData;
-class SimpleFontData;
-
-// The glyph page tree is a data structure that maps (FontData, glyph page number)
-// to a GlyphPage. Level 0 (the "root") is special. There is one root
-// GlyphPageTreeNode for each glyph page number. The roots do not have a
-// GlyphPage associated with them, and their initializePage() function is never
-// called to fill the glyphs.
-//
-// Each root node maps a FontData pointer to another GlyphPageTreeNode at
-// level 1 (the "root child") that stores the actual glyphs for a specific font data.
-// These nodes will only have a GlyphPage if they have glyphs for that range.
-//
-// Levels greater than one correspond to subsequent levels of the fallback list
-// for that font. These levels override their parent's page of glyphs by
-// filling in holes with the new font (thus making a more complete page).
-//
-// A NULL FontData pointer corresponds to the system fallback
-// font. It is tracked separately from the regular pages and overrides so that
-// the glyph pages do not get polluted with these last-resort glyphs. The
-// system fallback page is not populated at construction like the other pages,
-// but on demand for each glyph, because the system may need to use different
-// fallback fonts for each. This lazy population is done by the Font.
-class GlyphPageTreeNode {
- WTF_MAKE_FAST_ALLOCATED;
-public:
- static GlyphPageTreeNode* getRootChild(const FontData* fontData, unsigned pageNumber)
- {
- return getRoot(pageNumber)->getChild(fontData, pageNumber);
- }
-
- static void pruneTreeCustomFontData(const FontData*);
- static void pruneTreeFontData(const SimpleFontData*);
-
- void pruneCustomFontData(const FontData*);
- void pruneFontData(const SimpleFontData*, unsigned level = 0);
-
- GlyphPageTreeNode* parent() const { return m_parent; }
- GlyphPageTreeNode* getChild(const FontData*, unsigned pageNumber);
-
- // Returns a page of glyphs (or NULL if there are no glyphs in this page's character range).
- GlyphPage* page() const { return m_page.get(); }
-
- // Returns the level of this node. See class-level comment.
- unsigned level() const { return m_level; }
-
- // The system fallback font has special rules (see above).
- bool isSystemFallback() const { return m_isSystemFallback; }
-
- static size_t treeGlyphPageCount();
- size_t pageCount() const;
-
-private:
- GlyphPageTreeNode()
- : m_parent(0)
- , m_level(0)
- , m_isSystemFallback(false)
- , m_customFontCount(0)
-#ifndef NDEBUG
- , m_pageNumber(0)
-#endif
- {
- }
-
- static GlyphPageTreeNode* getRoot(unsigned pageNumber);
- void initializePage(const FontData*, unsigned pageNumber);
-
-#ifndef NDEBUG
- void showSubtree();
-#endif
-
- static HashMap<int, GlyphPageTreeNode*>* roots;
- static GlyphPageTreeNode* pageZeroRoot;
-
- typedef HashMap<const FontData*, OwnPtr<GlyphPageTreeNode> > GlyphPageTreeNodeMap;
-
- GlyphPageTreeNodeMap m_children;
- GlyphPageTreeNode* m_parent;
- RefPtr<GlyphPage> m_page;
- unsigned m_level : 31;
- bool m_isSystemFallback : 1;
- unsigned m_customFontCount;
- OwnPtr<GlyphPageTreeNode> m_systemFallbackChild;
-
-#ifndef NDEBUG
- unsigned m_pageNumber;
-
- friend void ::showGlyphPageTrees();
- friend void ::showGlyphPageTree(unsigned pageNumber);
-#endif
-};
-
-} // namespace WebCore
-
-#endif // GlyphPageTreeNode_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/Gradient.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/Gradient.cpp
deleted file mode 100644
index 30e1caceb09..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/Gradient.cpp
+++ /dev/null
@@ -1,364 +0,0 @@
-/*
- * Copyright (C) 2006, 2007, 2008, 2010 Apple Inc. All rights reserved.
- * Copyright (C) 2007 Alp Toker <alp@atoker.com>
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/Gradient.h"
-
-#include "core/platform/graphics/Color.h"
-#include "core/platform/graphics/FloatRect.h"
-#include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/graphics/skia/SkiaUtils.h"
-#include "third_party/skia/include/core/SkColorShader.h"
-#include "third_party/skia/include/core/SkShader.h"
-#include "third_party/skia/include/effects/SkGradientShader.h"
-#include "wtf/HashFunctions.h"
-#include "wtf/StringHasher.h"
-
-using WTF::pairIntHash;
-
-namespace WebCore {
-
-Gradient::Gradient(const FloatPoint& p0, const FloatPoint& p1)
- : m_radial(false)
- , m_p0(p0)
- , m_p1(p1)
- , m_r0(0)
- , m_r1(0)
- , m_aspectRatio(1)
- , m_stopsSorted(false)
- , m_spreadMethod(SpreadMethodPad)
- , m_cachedHash(0)
- , m_drawInPMColorSpace(false)
-{
-}
-
-Gradient::Gradient(const FloatPoint& p0, float r0, const FloatPoint& p1, float r1, float aspectRatio)
- : m_radial(true)
- , m_p0(p0)
- , m_p1(p1)
- , m_r0(r0)
- , m_r1(r1)
- , m_aspectRatio(aspectRatio)
- , m_stopsSorted(false)
- , m_spreadMethod(SpreadMethodPad)
- , m_cachedHash(0)
- , m_drawInPMColorSpace(false)
-{
-}
-
-Gradient::~Gradient()
-{
-}
-
-void Gradient::adjustParametersForTiledDrawing(IntSize& size, FloatRect& srcRect)
-{
- if (m_radial)
- return;
-
- if (srcRect.isEmpty())
- return;
-
- if (m_p0.x() == m_p1.x()) {
- size.setWidth(1);
- srcRect.setWidth(1);
- srcRect.setX(0);
- return;
- }
- if (m_p0.y() != m_p1.y())
- return;
-
- size.setHeight(1);
- srcRect.setHeight(1);
- srcRect.setY(0);
-}
-
-void Gradient::addColorStop(float value, const Color& color)
-{
- float r;
- float g;
- float b;
- float a;
- color.getRGBA(r, g, b, a);
- m_stops.append(ColorStop(value, r, g, b, a));
-
- m_stopsSorted = false;
- m_gradient.clear();
-
- invalidateHash();
-}
-
-void Gradient::addColorStop(const Gradient::ColorStop& stop)
-{
- m_stops.append(stop);
-
- m_stopsSorted = false;
- m_gradient.clear();
-
- invalidateHash();
-}
-
-static inline bool compareStops(const Gradient::ColorStop& a, const Gradient::ColorStop& b)
-{
- return a.stop < b.stop;
-}
-
-void Gradient::sortStopsIfNecessary()
-{
- if (m_stopsSorted)
- return;
-
- m_stopsSorted = true;
-
- if (!m_stops.size())
- return;
-
- std::stable_sort(m_stops.begin(), m_stops.end(), compareStops);
-
- invalidateHash();
-}
-
-bool Gradient::hasAlpha() const
-{
- for (size_t i = 0; i < m_stops.size(); i++) {
- if (m_stops[i].alpha < 1)
- return true;
- }
-
- return false;
-}
-
-void Gradient::setSpreadMethod(GradientSpreadMethod spreadMethod)
-{
- // FIXME: Should it become necessary, allow calls to this method after m_gradient has been set.
- ASSERT(!m_gradient);
-
- if (m_spreadMethod == spreadMethod)
- return;
-
- m_spreadMethod = spreadMethod;
-
- invalidateHash();
-}
-
-void Gradient::setDrawsInPMColorSpace(bool drawInPMColorSpace)
-{
- if (drawInPMColorSpace == m_drawInPMColorSpace)
- return;
-
- m_drawInPMColorSpace = drawInPMColorSpace;
- m_gradient.clear();
-
- invalidateHash();
-}
-
-void Gradient::setGradientSpaceTransform(const AffineTransform& gradientSpaceTransformation)
-{
- if (m_gradientSpaceTransformation == gradientSpaceTransformation)
- return;
-
- m_gradientSpaceTransformation = gradientSpaceTransformation;
- if (m_gradient)
- m_gradient->setLocalMatrix(m_gradientSpaceTransformation);
-
- invalidateHash();
-}
-
-unsigned Gradient::hash() const
-{
- if (m_cachedHash)
- return m_cachedHash;
-
- struct {
- AffineTransform gradientSpaceTransformation;
- FloatPoint p0;
- FloatPoint p1;
- float r0;
- float r1;
- float aspectRatio;
- GradientSpreadMethod spreadMethod;
- bool radial;
- bool drawInPMColorSpace;
- } parameters;
-
- // StringHasher requires that the memory it hashes be a multiple of two in size.
- COMPILE_ASSERT(!(sizeof(parameters) % 2), Gradient_parameters_size_should_be_multiple_of_two);
- COMPILE_ASSERT(!(sizeof(ColorStop) % 2), Color_stop_size_should_be_multiple_of_two);
-
- // Ensure that any padding in the struct is zero-filled, so it will not affect the hash value.
- memset(&parameters, 0, sizeof(parameters));
-
- parameters.gradientSpaceTransformation = m_gradientSpaceTransformation;
- parameters.p0 = m_p0;
- parameters.p1 = m_p1;
- parameters.r0 = m_r0;
- parameters.r1 = m_r1;
- parameters.aspectRatio = m_aspectRatio;
- parameters.spreadMethod = m_spreadMethod;
- parameters.radial = m_radial;
- parameters.drawInPMColorSpace = m_drawInPMColorSpace;
-
- unsigned parametersHash = StringHasher::hashMemory(&parameters, sizeof(parameters));
- unsigned stopHash = StringHasher::hashMemory(m_stops.data(), m_stops.size() * sizeof(ColorStop));
-
- m_cachedHash = pairIntHash(parametersHash, stopHash);
-
- return m_cachedHash;
-}
-
-static inline U8CPU F2B(float x)
-{
- return static_cast<int>(x * 255);
-}
-
-static SkColor makeSkColor(float a, float r, float g, float b)
-{
- return SkColorSetARGB(F2B(a), F2B(r), F2B(g), F2B(b));
-}
-
-// Determine the total number of stops needed, including pseudo-stops at the
-// ends as necessary.
-static size_t totalStopsNeeded(const Gradient::ColorStop* stopData, size_t count)
-{
- // N.B.: The tests in this function should kept in sync with the ones in
- // fillStops(), or badness happens.
- const Gradient::ColorStop* stop = stopData;
- size_t countUsed = count;
- if (count < 1 || stop->stop > 0.0)
- countUsed++;
- stop += count - 1;
- if (count < 1 || stop->stop < 1.0)
- countUsed++;
- return countUsed;
-}
-
-// Collect sorted stop position and color information into the pos and colors
-// buffers, ensuring stops at both 0.0 and 1.0. The buffers must be large
-// enough to hold information for all stops, including the new endpoints if
-// stops at 0.0 and 1.0 aren't already included.
-static void fillStops(const Gradient::ColorStop* stopData,
- size_t count, SkScalar* pos, SkColor* colors)
-{
- const Gradient::ColorStop* stop = stopData;
- size_t start = 0;
- if (count < 1) {
- // A gradient with no stops must be transparent black.
- pos[0] = WebCoreFloatToSkScalar(0.0);
- colors[0] = makeSkColor(0.0, 0.0, 0.0, 0.0);
- start = 1;
- } else if (stop->stop > 0.0) {
- // Copy the first stop to 0.0. The first stop position may have a slight
- // rounding error, but we don't care in this float comparison, since
- // 0.0 comes through cleanly and people aren't likely to want a gradient
- // with a stop at (0 + epsilon).
- pos[0] = WebCoreFloatToSkScalar(0.0);
- colors[0] = makeSkColor(stop->alpha, stop->red, stop->green, stop->blue);
- start = 1;
- }
-
- for (size_t i = start; i < start + count; i++) {
- pos[i] = WebCoreFloatToSkScalar(stop->stop);
- colors[i] = makeSkColor(stop->alpha, stop->red, stop->green, stop->blue);
- ++stop;
- }
-
- // Copy the last stop to 1.0 if needed. See comment above about this float
- // comparison.
- if (count < 1 || (--stop)->stop < 1.0) {
- pos[start + count] = WebCoreFloatToSkScalar(1.0);
- colors[start + count] = colors[start + count - 1];
- }
-}
-
-SkShader* Gradient::shader()
-{
- if (m_gradient)
- return m_gradient.get();
-
- sortStopsIfNecessary();
- ASSERT(m_stopsSorted);
-
- size_t countUsed = totalStopsNeeded(m_stops.data(), m_stops.size());
- ASSERT(countUsed >= 2);
- ASSERT(countUsed >= m_stops.size());
-
- // FIXME: Why is all this manual pointer math needed?!
- SkAutoMalloc storage(countUsed * (sizeof(SkColor) + sizeof(SkScalar)));
- SkColor* colors = (SkColor*)storage.get();
- SkScalar* pos = (SkScalar*)(colors + countUsed);
-
- fillStops(m_stops.data(), m_stops.size(), pos, colors);
-
- SkShader::TileMode tile = SkShader::kClamp_TileMode;
- switch (m_spreadMethod) {
- case SpreadMethodReflect:
- tile = SkShader::kMirror_TileMode;
- break;
- case SpreadMethodRepeat:
- tile = SkShader::kRepeat_TileMode;
- break;
- case SpreadMethodPad:
- tile = SkShader::kClamp_TileMode;
- break;
- }
-
- uint32_t shouldDrawInPMColorSpace = m_drawInPMColorSpace ? SkGradientShader::kInterpolateColorsInPremul_Flag : 0;
- if (m_radial) {
- // Since the two-point radial gradient is slower than the plain radial,
- // only use it if we have to.
- if (m_p0 == m_p1 && m_r0 <= 0.0f) {
- m_gradient = adoptRef(SkGradientShader::CreateRadial(m_p1, m_r1, colors, pos, static_cast<int>(countUsed), tile, 0, shouldDrawInPMColorSpace));
- } else {
- // The radii we give to Skia must be positive. If we're given a
- // negative radius, ask for zero instead.
- SkScalar radius0 = m_r0 >= 0.0f ? WebCoreFloatToSkScalar(m_r0) : 0;
- SkScalar radius1 = m_r1 >= 0.0f ? WebCoreFloatToSkScalar(m_r1) : 0;
- m_gradient = adoptRef(SkGradientShader::CreateTwoPointConical(m_p0, radius0, m_p1, radius1, colors, pos, static_cast<int>(countUsed), tile, 0, shouldDrawInPMColorSpace));
- }
-
- if (aspectRatio() != 1) {
- // CSS3 elliptical gradients: apply the elliptical scaling at the
- // gradient center point.
- m_gradientSpaceTransformation.translate(m_p0.x(), m_p0.y());
- m_gradientSpaceTransformation.scale(1, 1 / aspectRatio());
- m_gradientSpaceTransformation.translate(-m_p0.x(), -m_p0.y());
- ASSERT(m_p0 == m_p1);
- }
- } else {
- SkPoint pts[2] = { m_p0, m_p1 };
- m_gradient = adoptRef(SkGradientShader::CreateLinear(pts, colors, pos, static_cast<int>(countUsed), tile, 0, shouldDrawInPMColorSpace));
- }
-
- if (!m_gradient) {
- // use last color, since our "geometry" was degenerate (e.g. radius==0)
- m_gradient = adoptRef(new SkColorShader(colors[countUsed - 1]));
- } else {
- m_gradient->setLocalMatrix(m_gradientSpaceTransformation);
- }
- return m_gradient.get();
-}
-
-} //namespace
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/Gradient.h b/chromium/third_party/WebKit/Source/core/platform/graphics/Gradient.h
deleted file mode 100644
index 3c4d7d0a311..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/Gradient.h
+++ /dev/null
@@ -1,167 +0,0 @@
-/*
- * Copyright (C) 2006, 2007, 2008, 2011 Apple Inc. All rights reserved.
- * Copyright (C) 2007 Alp Toker <alp@atoker.com>
- * Copyright (C) 2008 Torch Mobile, Inc.
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef Gradient_h
-#define Gradient_h
-
-#include "core/platform/graphics/FloatPoint.h"
-#include "core/platform/graphics/GraphicsTypes.h"
-#include "core/platform/graphics/transforms/AffineTransform.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/RefPtr.h"
-#include "wtf/Vector.h"
-
-class SkShader;
-
-namespace WebCore {
-
-class Color;
-class FloatRect;
-class IntSize;
-
-class Gradient : public RefCounted<Gradient> {
-public:
- static PassRefPtr<Gradient> create(const FloatPoint& p0, const FloatPoint& p1)
- {
- return adoptRef(new Gradient(p0, p1));
- }
- static PassRefPtr<Gradient> create(const FloatPoint& p0, float r0, const FloatPoint& p1, float r1, float aspectRatio = 1)
- {
- return adoptRef(new Gradient(p0, r0, p1, r1, aspectRatio));
- }
- ~Gradient();
-
- struct ColorStop {
- float stop;
- float red;
- float green;
- float blue;
- float alpha;
-
- ColorStop() : stop(0), red(0), green(0), blue(0), alpha(0) { }
- ColorStop(float s, float r, float g, float b, float a) : stop(s), red(r), green(g), blue(b), alpha(a) { }
- };
- void addColorStop(const ColorStop&);
- void addColorStop(float, const Color&);
-
- bool hasAlpha() const;
-
- bool isRadial() const { return m_radial; }
- bool isZeroSize() const { return m_p0.x() == m_p1.x() && m_p0.y() == m_p1.y() && (!m_radial || m_r0 == m_r1); }
-
- const FloatPoint& p0() const { return m_p0; }
- const FloatPoint& p1() const { return m_p1; }
-
- void setP0(const FloatPoint& p)
- {
- if (m_p0 == p)
- return;
-
- m_p0 = p;
- invalidateHash();
- }
-
- void setP1(const FloatPoint& p)
- {
- if (m_p1 == p)
- return;
-
- m_p1 = p;
- invalidateHash();
- }
-
- float startRadius() const { return m_r0; }
- float endRadius() const { return m_r1; }
-
- void setStartRadius(float r)
- {
- if (m_r0 == r)
- return;
-
- m_r0 = r;
- invalidateHash();
- }
-
- void setEndRadius(float r)
- {
- if (m_r1 == r)
- return;
-
- m_r1 = r;
- invalidateHash();
- }
-
- float aspectRatio() const { return m_aspectRatio; }
-
- SkShader* shader();
-
- void setStopsSorted(bool s) { m_stopsSorted = s; }
-
- void setDrawsInPMColorSpace(bool drawInPMColorSpace);
-
- void setSpreadMethod(GradientSpreadMethod);
- GradientSpreadMethod spreadMethod() { return m_spreadMethod; }
- void setGradientSpaceTransform(const AffineTransform& gradientSpaceTransformation);
- AffineTransform gradientSpaceTransform() { return m_gradientSpaceTransformation; }
-
- void adjustParametersForTiledDrawing(IntSize&, FloatRect&);
-
- unsigned hash() const;
- void invalidateHash() { m_cachedHash = 0; }
-
-private:
- Gradient(const FloatPoint& p0, const FloatPoint& p1);
- Gradient(const FloatPoint& p0, float r0, const FloatPoint& p1, float r1, float aspectRatio);
-
- void destroyShader();
-
- void sortStopsIfNecessary();
-
- // Keep any parameters relevant to rendering in sync with the structure in Gradient::hash().
- bool m_radial;
- FloatPoint m_p0;
- FloatPoint m_p1;
- float m_r0;
- float m_r1;
- float m_aspectRatio; // For elliptical gradient, width / height.
- mutable Vector<ColorStop, 2> m_stops;
- mutable bool m_stopsSorted;
- GradientSpreadMethod m_spreadMethod;
- AffineTransform m_gradientSpaceTransformation;
-
- bool m_drawInPMColorSpace;
-
- mutable unsigned m_cachedHash;
-
- RefPtr<SkShader> m_gradient;
-};
-
-} // namespace WebCore
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsContext.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsContext.cpp
deleted file mode 100644
index e845bbd456b..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsContext.cpp
+++ /dev/null
@@ -1,1898 +0,0 @@
-/*
- * Copyright (C) 2003, 2004, 2005, 2006, 2009 Apple Inc. All rights reserved.
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/GraphicsContext.h"
-
-#include "core/platform/graphics/BitmapImage.h"
-#include "core/platform/graphics/Gradient.h"
-#include "core/platform/graphics/ImageBuffer.h"
-#include "core/platform/graphics/IntRect.h"
-#include "core/platform/graphics/RoundedRect.h"
-#include "core/platform/graphics/TextRunIterator.h"
-#include "core/platform/graphics/skia/SkiaUtils.h"
-#include "core/platform/text/BidiResolver.h"
-#include "third_party/skia/include/core/SkAnnotation.h"
-#include "third_party/skia/include/core/SkColorFilter.h"
-#include "third_party/skia/include/core/SkData.h"
-#include "third_party/skia/include/core/SkDevice.h"
-#include "third_party/skia/include/core/SkRRect.h"
-#include "third_party/skia/include/core/SkRefCnt.h"
-#include "third_party/skia/include/effects/SkBlurMaskFilter.h"
-#include "third_party/skia/include/effects/SkCornerPathEffect.h"
-#include "third_party/skia/include/effects/SkLumaXfermode.h"
-#include "weborigin/KURL.h"
-#include "wtf/Assertions.h"
-#include "wtf/MathExtras.h"
-
-#if OS(MACOSX)
-#include <ApplicationServices/ApplicationServices.h>
-#endif
-
-using namespace std;
-
-namespace WebCore {
-
-struct GraphicsContext::DeferredSaveState {
- DeferredSaveState(unsigned mask, int count) : m_flags(mask), m_restoreCount(count) { }
-
- unsigned m_flags;
- int m_restoreCount;
-};
-
-GraphicsContext::GraphicsContext(SkCanvas* canvas)
- : m_canvas(canvas)
- , m_deferredSaveFlags(0)
- , m_annotationMode(0)
-#if !ASSERT_DISABLED
- , m_annotationCount(0)
- , m_layerCount(0)
-#endif
- , m_trackOpaqueRegion(false)
- , m_trackTextRegion(false)
- , m_useHighResMarker(false)
- , m_updatingControlTints(false)
- , m_accelerated(false)
- , m_isCertainlyOpaque(true)
- , m_printing(false)
-{
- m_stateStack.append(adoptPtr(new GraphicsContextState()));
- m_state = m_stateStack.last().get();
-}
-
-GraphicsContext::~GraphicsContext()
-{
- ASSERT(m_stateStack.size() == 1);
- ASSERT(!m_annotationCount);
- ASSERT(!m_layerCount);
-}
-
-const SkBitmap* GraphicsContext::bitmap() const
-{
- TRACE_EVENT0("skia", "GraphicsContext::bitmap");
- return &m_canvas->getDevice()->accessBitmap(false);
-}
-
-const SkBitmap& GraphicsContext::layerBitmap(AccessMode access) const
-{
- return m_canvas->getTopDevice()->accessBitmap(access == ReadWrite);
-}
-
-SkBaseDevice* GraphicsContext::createCompatibleDevice(const IntSize& size, bool hasAlpha) const
-{
- if (paintingDisabled())
- return 0;
-
- return m_canvas->createCompatibleDevice(SkBitmap::kARGB_8888_Config, size.width(), size.height(), !hasAlpha);
-}
-
-void GraphicsContext::save()
-{
- if (paintingDisabled())
- return;
-
- m_stateStack.append(m_state->clone());
- m_state = m_stateStack.last().get();
-
- m_saveStateStack.append(DeferredSaveState(m_deferredSaveFlags, m_canvas->getSaveCount()));
- m_deferredSaveFlags |= SkCanvas::kMatrixClip_SaveFlag;
-}
-
-void GraphicsContext::restore()
-{
- if (paintingDisabled())
- return;
-
- if (m_stateStack.size() == 1) {
- LOG_ERROR("ERROR void GraphicsContext::restore() stack is empty");
- return;
- }
-
- m_stateStack.removeLast();
- m_state = m_stateStack.last().get();
-
- DeferredSaveState savedState = m_saveStateStack.last();
- m_saveStateStack.removeLast();
- m_deferredSaveFlags = savedState.m_flags;
- m_canvas->restoreToCount(savedState.m_restoreCount);
-}
-
-void GraphicsContext::saveLayer(const SkRect* bounds, const SkPaint* paint, SkCanvas::SaveFlags saveFlags)
-{
- if (paintingDisabled())
- return;
-
- realizeSave(SkCanvas::kMatrixClip_SaveFlag);
-
- m_canvas->saveLayer(bounds, paint, saveFlags);
- if (bounds)
- m_canvas->clipRect(*bounds);
- if (m_trackOpaqueRegion)
- m_opaqueRegion.pushCanvasLayer(paint);
-}
-
-void GraphicsContext::restoreLayer()
-{
- if (paintingDisabled())
- return;
-
- m_canvas->restore();
- if (m_trackOpaqueRegion)
- m_opaqueRegion.popCanvasLayer(this);
-}
-
-void GraphicsContext::beginAnnotation(const GraphicsContextAnnotation& annotation)
-{
- if (paintingDisabled())
- return;
-
- canvas()->beginCommentGroup("GraphicsContextAnnotation");
-
- AnnotationList annotations;
- annotation.asAnnotationList(annotations);
-
- AnnotationList::const_iterator end = annotations.end();
- for (AnnotationList::const_iterator it = annotations.begin(); it != end; ++it)
- canvas()->addComment(it->first, it->second.ascii().data());
-
-#if !ASSERT_DISABLED
- ++m_annotationCount;
-#endif
-}
-
-void GraphicsContext::endAnnotation()
-{
- if (paintingDisabled())
- return;
-
- canvas()->endCommentGroup();
-
- ASSERT(m_annotationCount > 0);
-#if !ASSERT_DISABLED
- --m_annotationCount;
-#endif
-}
-
-void GraphicsContext::setStrokeColor(const Color& color)
-{
- m_state->m_strokeData.setColor(color);
- m_state->m_strokeData.clearGradient();
- m_state->m_strokeData.clearPattern();
-}
-
-void GraphicsContext::setStrokePattern(PassRefPtr<Pattern> pattern)
-{
- if (paintingDisabled())
- return;
-
- ASSERT(pattern);
- if (!pattern) {
- setStrokeColor(Color::black);
- return;
- }
- m_state->m_strokeData.clearGradient();
- m_state->m_strokeData.setPattern(pattern);
-}
-
-void GraphicsContext::setStrokeGradient(PassRefPtr<Gradient> gradient)
-{
- if (paintingDisabled())
- return;
-
- ASSERT(gradient);
- if (!gradient) {
- setStrokeColor(Color::black);
- return;
- }
- m_state->m_strokeData.setGradient(gradient);
- m_state->m_strokeData.clearPattern();
-}
-
-void GraphicsContext::setFillColor(const Color& color)
-{
- m_state->m_fillColor = color;
- m_state->m_fillGradient.clear();
- m_state->m_fillPattern.clear();
-}
-
-void GraphicsContext::setFillPattern(PassRefPtr<Pattern> pattern)
-{
- if (paintingDisabled())
- return;
-
- ASSERT(pattern);
- if (!pattern) {
- setFillColor(Color::black);
- return;
- }
- m_state->m_fillGradient.clear();
- m_state->m_fillPattern = pattern;
-}
-
-void GraphicsContext::setFillGradient(PassRefPtr<Gradient> gradient)
-{
- if (paintingDisabled())
- return;
-
- ASSERT(gradient);
- if (!gradient) {
- setFillColor(Color::black);
- return;
- }
- m_state->m_fillGradient = gradient;
- m_state->m_fillPattern.clear();
-}
-
-void GraphicsContext::setShadow(const FloatSize& offset, float blur, const Color& color,
- DrawLooper::ShadowTransformMode shadowTransformMode,
- DrawLooper::ShadowAlphaMode shadowAlphaMode)
-{
- if (paintingDisabled())
- return;
-
- if (!color.isValid() || !color.alpha() || (!offset.width() && !offset.height() && !blur)) {
- clearShadow();
- return;
- }
-
- DrawLooper drawLooper;
- drawLooper.addShadow(offset, blur, color, shadowTransformMode, shadowAlphaMode);
- drawLooper.addUnmodifiedContent();
- setDrawLooper(drawLooper);
-}
-
-void GraphicsContext::setDrawLooper(const DrawLooper& drawLooper)
-{
- if (paintingDisabled())
- return;
-
- m_state->m_looper = drawLooper.skDrawLooper();
-}
-
-void GraphicsContext::clearDrawLooper()
-{
- if (paintingDisabled())
- return;
-
- m_state->m_looper.clear();
-}
-
-bool GraphicsContext::hasShadow() const
-{
- return !!m_state->m_looper;
-}
-
-int GraphicsContext::getNormalizedAlpha() const
-{
- int alpha = roundf(m_state->m_alpha * 256);
- if (alpha > 255)
- alpha = 255;
- else if (alpha < 0)
- alpha = 0;
- return alpha;
-}
-
-bool GraphicsContext::getClipBounds(SkRect* bounds) const
-{
- if (paintingDisabled())
- return false;
- return m_canvas->getClipBounds(bounds);
-}
-
-bool GraphicsContext::getTransformedClipBounds(FloatRect* bounds) const
-{
- if (paintingDisabled())
- return false;
- SkIRect skIBounds;
- if (!m_canvas->getClipDeviceBounds(&skIBounds))
- return false;
- SkRect skBounds = SkRect::MakeFromIRect(skIBounds);
- *bounds = FloatRect(skBounds);
- return true;
-}
-
-const SkMatrix& GraphicsContext::getTotalMatrix() const
-{
- if (paintingDisabled())
- return SkMatrix::I();
- return m_canvas->getTotalMatrix();
-}
-
-bool GraphicsContext::isPrintingDevice() const
-{
- if (paintingDisabled())
- return false;
- return m_canvas->getTopDevice()->getDeviceCapabilities() & SkBaseDevice::kVector_Capability;
-}
-
-void GraphicsContext::adjustTextRenderMode(SkPaint* paint)
-{
- if (paintingDisabled())
- return;
-
- if (!paint->isLCDRenderText())
- return;
-
- paint->setLCDRenderText(couldUseLCDRenderedText());
-}
-
-bool GraphicsContext::couldUseLCDRenderedText()
-{
- // Our layers only have a single alpha channel. This means that subpixel
- // rendered text cannot be composited correctly when the layer is
- // collapsed. Therefore, subpixel text is disabled when we are drawing
- // onto a layer.
- if (paintingDisabled() || isDrawingToLayer() || !isCertainlyOpaque())
- return false;
-
- return shouldSmoothFonts();
-}
-
-void GraphicsContext::setCompositeOperation(CompositeOperator compositeOperation, BlendMode blendMode)
-{
- m_state->m_compositeOperator = compositeOperation;
- m_state->m_blendMode = blendMode;
- m_state->m_xferMode = WebCoreCompositeToSkiaComposite(compositeOperation, blendMode);
-}
-
-void GraphicsContext::setColorSpaceConversion(ColorSpace srcColorSpace, ColorSpace dstColorSpace)
-{
- m_state->m_colorFilter = ImageBuffer::createColorSpaceFilter(srcColorSpace, dstColorSpace);
-}
-
-bool GraphicsContext::readPixels(SkBitmap* bitmap, int x, int y, SkCanvas::Config8888 config8888)
-{
- if (paintingDisabled())
- return false;
-
- return m_canvas->readPixels(bitmap, x, y, config8888);
-}
-
-void GraphicsContext::setMatrix(const SkMatrix& matrix)
-{
- if (paintingDisabled())
- return;
-
- realizeSave(SkCanvas::kMatrix_SaveFlag);
-
- m_canvas->setMatrix(matrix);
-}
-
-bool GraphicsContext::concat(const SkMatrix& matrix)
-{
- if (paintingDisabled())
- return false;
-
- realizeSave(SkCanvas::kMatrix_SaveFlag);
-
- return m_canvas->concat(matrix);
-}
-
-void GraphicsContext::beginTransparencyLayer(float opacity, const FloatRect* bounds)
-{
- beginTransparencyLayer(opacity, m_state->m_compositeOperator, bounds);
-}
-
-void GraphicsContext::beginTransparencyLayer(float opacity, CompositeOperator op, const FloatRect* bounds)
-{
- if (paintingDisabled())
- return;
-
- // We need the "alpha" layer flag here because the base layer is opaque
- // (the surface of the page) but layers on top may have transparent parts.
- // Without explicitly setting the alpha flag, the layer will inherit the
- // opaque setting of the base and some things won't work properly.
- SkCanvas::SaveFlags saveFlags = static_cast<SkCanvas::SaveFlags>(SkCanvas::kHasAlphaLayer_SaveFlag | SkCanvas::kFullColorLayer_SaveFlag);
-
- SkPaint layerPaint;
- layerPaint.setAlpha(static_cast<unsigned char>(opacity * 255));
- RefPtr<SkXfermode> xferMode = WebCoreCompositeToSkiaComposite(op, m_state->m_blendMode);
- layerPaint.setXfermode(xferMode.get());
-
- if (bounds) {
- SkRect skBounds = WebCoreFloatRectToSKRect(*bounds);
- saveLayer(&skBounds, &layerPaint, saveFlags);
- } else {
- saveLayer(0, &layerPaint, saveFlags);
- }
-
-
-#if !ASSERT_DISABLED
- ++m_layerCount;
-#endif
-}
-
-void GraphicsContext::beginMaskedLayer(const FloatRect& bounds, MaskType maskType)
-{
- if (paintingDisabled())
- return;
-
- SkPaint layerPaint;
- RefPtr<SkXfermode> xferMode = adoptRef(maskType == AlphaMaskType
- ? SkXfermode::Create(SkXfermode::kSrcIn_Mode)
- : SkLumaMaskXfermode::Create(SkXfermode::kSrcIn_Mode));
- layerPaint.setXfermode(xferMode.get());
-
- SkRect skBounds = WebCoreFloatRectToSKRect(bounds);
- saveLayer(&skBounds, &layerPaint);
-
-#if !ASSERT_DISABLED
- ++m_layerCount;
-#endif
-}
-
-void GraphicsContext::endLayer()
-{
- if (paintingDisabled())
- return;
-
- restoreLayer();
-
- ASSERT(m_layerCount > 0);
-#if !ASSERT_DISABLED
- --m_layerCount;
-#endif
-}
-
-void GraphicsContext::setupPaintForFilling(SkPaint* paint) const
-{
- if (paintingDisabled())
- return;
-
- setupPaintCommon(paint);
-
- setupShader(paint, m_state->m_fillGradient.get(), m_state->m_fillPattern.get(), m_state->m_fillColor.rgb());
-}
-
-float GraphicsContext::setupPaintForStroking(SkPaint* paint, int length) const
-{
- if (paintingDisabled())
- return 0.0f;
-
- setupPaintCommon(paint);
-
- setupShader(paint, m_state->m_strokeData.gradient(), m_state->m_strokeData.pattern(),
- m_state->m_strokeData.color().rgb());
-
- return m_state->m_strokeData.setupPaint(paint, length);
-}
-
-void GraphicsContext::drawConvexPolygon(size_t numPoints, const FloatPoint* points, bool shouldAntialias)
-{
- if (paintingDisabled())
- return;
-
- if (numPoints <= 1)
- return;
-
- SkPath path;
- setPathFromConvexPoints(&path, numPoints, points);
-
- SkPaint paint;
- setupPaintForFilling(&paint);
- paint.setAntiAlias(shouldAntialias);
- drawPath(path, paint);
-
- if (strokeStyle() != NoStroke) {
- paint.reset();
- setupPaintForStroking(&paint);
- drawPath(path, paint);
- }
-}
-
-// This method is only used to draw the little circles used in lists.
-void GraphicsContext::drawEllipse(const IntRect& elipseRect)
-{
- if (paintingDisabled())
- return;
-
- SkRect rect = elipseRect;
- SkPaint paint;
- setupPaintForFilling(&paint);
- drawOval(rect, paint);
-
- if (strokeStyle() != NoStroke) {
- paint.reset();
- setupPaintForStroking(&paint);
- drawOval(rect, paint);
- }
-}
-
-void GraphicsContext::drawFocusRing(const Path& focusRingPath, int width, int offset, const Color& color)
-{
- // FIXME: Implement support for offset.
- UNUSED_PARAM(offset);
-
- if (paintingDisabled())
- return;
-
- SkPaint paint;
- paint.setAntiAlias(true);
- paint.setStyle(SkPaint::kStroke_Style);
- paint.setColor(color.rgb());
-
- drawOuterPath(focusRingPath.skPath(), paint, width);
- drawInnerPath(focusRingPath.skPath(), paint, width);
-}
-
-void GraphicsContext::drawFocusRing(const Vector<IntRect>& rects, int width, int offset, const Color& color)
-{
- if (paintingDisabled())
- return;
-
- unsigned rectCount = rects.size();
- if (!rectCount)
- return;
-
- SkRegion focusRingRegion;
- const int focusRingOutset = getFocusRingOutset(offset);
- for (unsigned i = 0; i < rectCount; i++) {
- SkIRect r = rects[i];
- r.inset(-focusRingOutset, -focusRingOutset);
- focusRingRegion.op(r, SkRegion::kUnion_Op);
- }
-
- SkPath path;
- SkPaint paint;
- paint.setAntiAlias(true);
- paint.setStyle(SkPaint::kStroke_Style);
-
- paint.setColor(color.rgb());
- focusRingRegion.getBoundaryPath(&path);
- drawOuterPath(path, paint, width);
- drawInnerPath(path, paint, width);
-}
-
-static inline IntRect areaCastingShadowInHole(const IntRect& holeRect, int shadowBlur, int shadowSpread, const IntSize& shadowOffset)
-{
- IntRect bounds(holeRect);
-
- bounds.inflate(shadowBlur);
-
- if (shadowSpread < 0)
- bounds.inflate(-shadowSpread);
-
- IntRect offsetBounds = bounds;
- offsetBounds.move(-shadowOffset);
- return unionRect(bounds, offsetBounds);
-}
-
-void GraphicsContext::drawInnerShadow(const RoundedRect& rect, const Color& shadowColor, const IntSize shadowOffset, int shadowBlur, int shadowSpread, Edges clippedEdges)
-{
- IntRect holeRect(rect.rect());
- holeRect.inflate(-shadowSpread);
-
- if (holeRect.isEmpty()) {
- if (rect.isRounded())
- fillRoundedRect(rect, shadowColor);
- else
- fillRect(rect.rect(), shadowColor);
- return;
- }
-
- if (clippedEdges & LeftEdge) {
- holeRect.move(-max(shadowOffset.width(), 0) - shadowBlur, 0);
- holeRect.setWidth(holeRect.width() + max(shadowOffset.width(), 0) + shadowBlur);
- }
- if (clippedEdges & TopEdge) {
- holeRect.move(0, -max(shadowOffset.height(), 0) - shadowBlur);
- holeRect.setHeight(holeRect.height() + max(shadowOffset.height(), 0) + shadowBlur);
- }
- if (clippedEdges & RightEdge)
- holeRect.setWidth(holeRect.width() - min(shadowOffset.width(), 0) + shadowBlur);
- if (clippedEdges & BottomEdge)
- holeRect.setHeight(holeRect.height() - min(shadowOffset.height(), 0) + shadowBlur);
-
- Color fillColor(shadowColor.red(), shadowColor.green(), shadowColor.blue(), 255);
-
- IntRect outerRect = areaCastingShadowInHole(rect.rect(), shadowBlur, shadowSpread, shadowOffset);
- RoundedRect roundedHole(holeRect, rect.radii());
-
- save();
- if (rect.isRounded()) {
- Path path;
- path.addRoundedRect(rect);
- clipPath(path);
- roundedHole.shrinkRadii(shadowSpread);
- } else {
- clip(rect.rect());
- }
-
- DrawLooper drawLooper;
- drawLooper.addShadow(shadowOffset, shadowBlur, shadowColor,
- DrawLooper::ShadowRespectsTransforms, DrawLooper::ShadowIgnoresAlpha);
- setDrawLooper(drawLooper);
- fillRectWithRoundedHole(outerRect, roundedHole, fillColor);
- restore();
- clearDrawLooper();
-}
-
-// This is only used to draw borders.
-void GraphicsContext::drawLine(const IntPoint& point1, const IntPoint& point2)
-{
- if (paintingDisabled())
- return;
-
- StrokeStyle penStyle = strokeStyle();
- if (penStyle == NoStroke)
- return;
-
- SkPaint paint;
- FloatPoint p1 = point1;
- FloatPoint p2 = point2;
- bool isVerticalLine = (p1.x() == p2.x());
- int width = roundf(strokeThickness());
-
- // We know these are vertical or horizontal lines, so the length will just
- // be the sum of the displacement component vectors give or take 1 -
- // probably worth the speed up of no square root, which also won't be exact.
- FloatSize disp = p2 - p1;
- int length = SkScalarRound(disp.width() + disp.height());
- setupPaintForStroking(&paint, length);
-
- if (strokeStyle() == DottedStroke || strokeStyle() == DashedStroke) {
- // Do a rect fill of our endpoints. This ensures we always have the
- // appearance of being a border. We then draw the actual dotted/dashed line.
-
- SkRect r1, r2;
- r1.set(p1.x(), p1.y(), p1.x() + width, p1.y() + width);
- r2.set(p2.x(), p2.y(), p2.x() + width, p2.y() + width);
-
- if (isVerticalLine) {
- r1.offset(-width / 2, 0);
- r2.offset(-width / 2, -width);
- } else {
- r1.offset(0, -width / 2);
- r2.offset(-width, -width / 2);
- }
- SkPaint fillPaint;
- fillPaint.setColor(paint.getColor());
- drawRect(r1, fillPaint);
- drawRect(r2, fillPaint);
- }
-
- adjustLineToPixelBoundaries(p1, p2, width, penStyle);
- SkPoint pts[2] = { (SkPoint)p1, (SkPoint)p2 };
-
- m_canvas->drawPoints(SkCanvas::kLines_PointMode, 2, pts, paint);
-
- if (m_trackOpaqueRegion)
- m_opaqueRegion.didDrawPoints(this, SkCanvas::kLines_PointMode, 2, pts, paint);
-}
-
-void GraphicsContext::drawLineForDocumentMarker(const FloatPoint& pt, float width, DocumentMarkerLineStyle style)
-{
- if (paintingDisabled())
- return;
-
- int deviceScaleFactor = m_useHighResMarker ? 2 : 1;
-
- // Create the pattern we'll use to draw the underline.
- int index = style == DocumentMarkerGrammarLineStyle ? 1 : 0;
- static SkBitmap* misspellBitmap1x[2] = { 0, 0 };
- static SkBitmap* misspellBitmap2x[2] = { 0, 0 };
- SkBitmap** misspellBitmap = deviceScaleFactor == 2 ? misspellBitmap2x : misspellBitmap1x;
- if (!misspellBitmap[index]) {
-#if OS(MACOSX)
- // Match the artwork used by the Mac.
- const int rowPixels = 4 * deviceScaleFactor;
- const int colPixels = 3 * deviceScaleFactor;
- misspellBitmap[index] = new SkBitmap;
- misspellBitmap[index]->setConfig(SkBitmap::kARGB_8888_Config,
- rowPixels, colPixels);
- misspellBitmap[index]->allocPixels();
-
- misspellBitmap[index]->eraseARGB(0, 0, 0, 0);
- const uint32_t transparentColor = 0x00000000;
-
- if (deviceScaleFactor == 1) {
- const uint32_t colors[2][6] = {
- { 0x2a2a0600, 0x57571000, 0xa8a81b00, 0xbfbf1f00, 0x70701200, 0xe0e02400 },
- { 0x2a0f0f0f, 0x571e1e1e, 0xa83d3d3d, 0xbf454545, 0x70282828, 0xe0515151 }
- };
-
- // Pattern: a b a a b a
- // c d c c d c
- // e f e e f e
- for (int x = 0; x < colPixels; ++x) {
- uint32_t* row = misspellBitmap[index]->getAddr32(0, x);
- row[0] = colors[index][x * 2];
- row[1] = colors[index][x * 2 + 1];
- row[2] = colors[index][x * 2];
- row[3] = transparentColor;
- }
- } else if (deviceScaleFactor == 2) {
- const uint32_t colors[2][18] = {
- { 0x0a090101, 0x33320806, 0x55540f0a, 0x37360906, 0x6e6c120c, 0x6e6c120c, 0x7674140d, 0x8d8b1810, 0x8d8b1810,
- 0x96941a11, 0xb3b01f15, 0xb3b01f15, 0x6d6b130c, 0xd9d62619, 0xd9d62619, 0x19180402, 0x7c7a150e, 0xcecb2418 },
- { 0x0a020202, 0x33141414, 0x55232323, 0x37161616, 0x6e2e2e2e, 0x6e2e2e2e, 0x76313131, 0x8d3a3a3a, 0x8d3a3a3a,
- 0x963e3e3e, 0xb34b4b4b, 0xb34b4b4b, 0x6d2d2d2d, 0xd95b5b5b, 0xd95b5b5b, 0x19090909, 0x7c343434, 0xce575757 }
- };
-
- // Pattern: a b c c b a
- // d e f f e d
- // g h j j h g
- // k l m m l k
- // n o p p o n
- // q r s s r q
- for (int x = 0; x < colPixels; ++x) {
- uint32_t* row = misspellBitmap[index]->getAddr32(0, x);
- row[0] = colors[index][x * 3];
- row[1] = colors[index][x * 3 + 1];
- row[2] = colors[index][x * 3 + 2];
- row[3] = colors[index][x * 3 + 2];
- row[4] = colors[index][x * 3 + 1];
- row[5] = colors[index][x * 3];
- row[6] = transparentColor;
- row[7] = transparentColor;
- }
- } else
- ASSERT_NOT_REACHED();
-#else
- // We use a 2-pixel-high misspelling indicator because that seems to be
- // what WebKit is designed for, and how much room there is in a typical
- // page for it.
- const int rowPixels = 32 * deviceScaleFactor; // Must be multiple of 4 for pattern below.
- const int colPixels = 2 * deviceScaleFactor;
- misspellBitmap[index] = new SkBitmap;
- misspellBitmap[index]->setConfig(SkBitmap::kARGB_8888_Config, rowPixels, colPixels);
- misspellBitmap[index]->allocPixels();
-
- misspellBitmap[index]->eraseARGB(0, 0, 0, 0);
- if (deviceScaleFactor == 1)
- draw1xMarker(misspellBitmap[index], index);
- else if (deviceScaleFactor == 2)
- draw2xMarker(misspellBitmap[index], index);
- else
- ASSERT_NOT_REACHED();
-#endif
- }
-
-#if OS(MACOSX)
- SkScalar originX = WebCoreFloatToSkScalar(pt.x()) * deviceScaleFactor;
- SkScalar originY = WebCoreFloatToSkScalar(pt.y()) * deviceScaleFactor;
-
- // Make sure to draw only complete dots.
- int rowPixels = misspellBitmap[index]->width();
- float widthMod = fmodf(width * deviceScaleFactor, rowPixels);
- if (rowPixels - widthMod > deviceScaleFactor)
- width -= widthMod / deviceScaleFactor;
-#else
- SkScalar originX = WebCoreFloatToSkScalar(pt.x());
-
- // Offset it vertically by 1 so that there's some space under the text.
- SkScalar originY = WebCoreFloatToSkScalar(pt.y()) + 1;
- originX *= deviceScaleFactor;
- originY *= deviceScaleFactor;
-#endif
-
- RefPtr<SkShader> shader = adoptRef(SkShader::CreateBitmapShader(
- *misspellBitmap[index], SkShader::kRepeat_TileMode, SkShader::kRepeat_TileMode));
- SkMatrix matrix;
- matrix.setTranslate(originX, originY);
- shader->setLocalMatrix(matrix);
-
- SkPaint paint;
- paint.setShader(shader.get());
-
- SkRect rect;
- rect.set(originX, originY, originX + WebCoreFloatToSkScalar(width) * deviceScaleFactor, originY + SkIntToScalar(misspellBitmap[index]->height()));
-
- if (deviceScaleFactor == 2) {
- save();
- scale(FloatSize(0.5, 0.5));
- }
- drawRect(rect, paint);
- if (deviceScaleFactor == 2)
- restore();
-}
-
-void GraphicsContext::drawLineForText(const FloatPoint& pt, float width, bool printing)
-{
- if (paintingDisabled())
- return;
-
- if (width <= 0)
- return;
-
- int thickness = SkMax32(static_cast<int>(strokeThickness()), 1);
- SkRect r;
- r.fLeft = WebCoreFloatToSkScalar(pt.x());
- // Avoid anti-aliasing lines. Currently, these are always horizontal.
- // Round to nearest pixel to match text and other content.
- r.fTop = WebCoreFloatToSkScalar(floorf(pt.y() + 0.5f));
- r.fRight = r.fLeft + WebCoreFloatToSkScalar(width);
- r.fBottom = r.fTop + SkIntToScalar(thickness);
-
- SkPaint paint;
- switch (strokeStyle()) {
- case NoStroke:
- case SolidStroke:
- case DoubleStroke:
- case WavyStroke:
- setupPaintForFilling(&paint);
- break;
- case DottedStroke:
- case DashedStroke:
- setupPaintForStroking(&paint);
- break;
- }
-
- // Text lines are drawn using the stroke color.
- paint.setColor(effectiveStrokeColor());
- drawRect(r, paint);
-}
-
-// Draws a filled rectangle with a stroked border.
-void GraphicsContext::drawRect(const IntRect& rect)
-{
- if (paintingDisabled())
- return;
-
- ASSERT(!rect.isEmpty());
- if (rect.isEmpty())
- return;
-
- SkRect skRect = rect;
- SkPaint paint;
- int fillcolorNotTransparent = m_state->m_fillColor.rgb() & 0xFF000000;
- if (fillcolorNotTransparent) {
- setupPaintForFilling(&paint);
- drawRect(skRect, paint);
- }
-
- if (m_state->m_strokeData.style() != NoStroke && (m_state->m_strokeData.color().rgb() & 0xFF000000)) {
- // We do a fill of four rects to simulate the stroke of a border.
- paint.reset();
- setupPaintForFilling(&paint);
- // need to jam in the strokeColor
- paint.setColor(this->effectiveStrokeColor());
-
- SkRect topBorder = { skRect.fLeft, skRect.fTop, skRect.fRight, skRect.fTop + 1 };
- drawRect(topBorder, paint);
- SkRect bottomBorder = { skRect.fLeft, skRect.fBottom - 1, skRect.fRight, skRect.fBottom };
- drawRect(bottomBorder, paint);
- SkRect leftBorder = { skRect.fLeft, skRect.fTop + 1, skRect.fLeft + 1, skRect.fBottom - 1 };
- drawRect(leftBorder, paint);
- SkRect rightBorder = { skRect.fRight - 1, skRect.fTop + 1, skRect.fRight, skRect.fBottom - 1 };
- drawRect(rightBorder, paint);
- }
-}
-
-void GraphicsContext::drawText(const Font& font, const TextRunPaintInfo& runInfo, const FloatPoint& point)
-{
- if (paintingDisabled())
- return;
-
- font.drawText(this, runInfo, point);
-}
-
-void GraphicsContext::drawEmphasisMarks(const Font& font, const TextRunPaintInfo& runInfo, const AtomicString& mark, const FloatPoint& point)
-{
- if (paintingDisabled())
- return;
-
- font.drawEmphasisMarks(this, runInfo, mark, point);
-}
-
-void GraphicsContext::drawBidiText(const Font& font, const TextRunPaintInfo& runInfo, const FloatPoint& point, Font::CustomFontNotReadyAction customFontNotReadyAction)
-{
- if (paintingDisabled())
- return;
-
- // sub-run painting is not supported for Bidi text.
- const TextRun& run = runInfo.run;
- ASSERT((runInfo.from == 0) && (runInfo.to == run.length()));
- BidiResolver<TextRunIterator, BidiCharacterRun> bidiResolver;
- bidiResolver.setStatus(BidiStatus(run.direction(), run.directionalOverride()));
- bidiResolver.setPositionIgnoringNestedIsolates(TextRunIterator(&run, 0));
-
- // FIXME: This ownership should be reversed. We should pass BidiRunList
- // to BidiResolver in createBidiRunsForLine.
- BidiRunList<BidiCharacterRun>& bidiRuns = bidiResolver.runs();
- bidiResolver.createBidiRunsForLine(TextRunIterator(&run, run.length()));
- if (!bidiRuns.runCount())
- return;
-
- FloatPoint currPoint = point;
- BidiCharacterRun* bidiRun = bidiRuns.firstRun();
- while (bidiRun) {
- TextRun subrun = run.subRun(bidiRun->start(), bidiRun->stop() - bidiRun->start());
- bool isRTL = bidiRun->level() % 2;
- subrun.setDirection(isRTL ? RTL : LTR);
- subrun.setDirectionalOverride(bidiRun->dirOverride(false));
-
- TextRunPaintInfo subrunInfo(subrun);
- subrunInfo.bounds = runInfo.bounds;
- font.drawText(this, subrunInfo, currPoint, customFontNotReadyAction);
-
- bidiRun = bidiRun->next();
- // FIXME: Have Font::drawText return the width of what it drew so that we don't have to re-measure here.
- if (bidiRun)
- currPoint.move(font.width(subrun), 0);
- }
-
- bidiRuns.deleteRuns();
-}
-
-void GraphicsContext::drawHighlightForText(const Font& font, const TextRun& run, const FloatPoint& point, int h, const Color& backgroundColor, int from, int to)
-{
- if (paintingDisabled())
- return;
-
- fillRect(font.selectionRectForText(run, point, h, from, to), backgroundColor);
-}
-
-void GraphicsContext::drawImage(Image* image, const IntPoint& p, CompositeOperator op, RespectImageOrientationEnum shouldRespectImageOrientation)
-{
- if (!image)
- return;
- drawImage(image, FloatRect(IntRect(p, image->size())), FloatRect(FloatPoint(), FloatSize(image->size())), op, shouldRespectImageOrientation);
-}
-
-void GraphicsContext::drawImage(Image* image, const IntRect& r, CompositeOperator op, RespectImageOrientationEnum shouldRespectImageOrientation, bool useLowQualityScale)
-{
- if (!image)
- return;
- drawImage(image, FloatRect(r), FloatRect(FloatPoint(), FloatSize(image->size())), op, shouldRespectImageOrientation, useLowQualityScale);
-}
-
-void GraphicsContext::drawImage(Image* image, const IntPoint& dest, const IntRect& srcRect, CompositeOperator op, RespectImageOrientationEnum shouldRespectImageOrientation)
-{
- drawImage(image, FloatRect(IntRect(dest, srcRect.size())), FloatRect(srcRect), op, shouldRespectImageOrientation);
-}
-
-void GraphicsContext::drawImage(Image* image, const FloatRect& dest, const FloatRect& src, CompositeOperator op, RespectImageOrientationEnum shouldRespectImageOrientation, bool useLowQualityScale)
-{
- drawImage(image, dest, src, op, BlendModeNormal, shouldRespectImageOrientation, useLowQualityScale);
-}
-
-void GraphicsContext::drawImage(Image* image, const FloatRect& dest)
-{
- if (!image)
- return;
- drawImage(image, dest, FloatRect(IntRect(IntPoint(), image->size())));
-}
-
-void GraphicsContext::drawImage(Image* image, const FloatRect& dest, const FloatRect& src, CompositeOperator op, BlendMode blendMode, RespectImageOrientationEnum shouldRespectImageOrientation, bool useLowQualityScale)
-{ if (paintingDisabled() || !image)
- return;
-
- InterpolationQuality previousInterpolationQuality = InterpolationDefault;
-
- if (useLowQualityScale) {
- previousInterpolationQuality = imageInterpolationQuality();
- setImageInterpolationQuality(InterpolationLow);
- }
-
- image->draw(this, dest, src, op, blendMode, shouldRespectImageOrientation);
-
- if (useLowQualityScale)
- setImageInterpolationQuality(previousInterpolationQuality);
-}
-
-void GraphicsContext::drawTiledImage(Image* image, const IntRect& destRect, const IntPoint& srcPoint, const IntSize& tileSize, CompositeOperator op, bool useLowQualityScale, BlendMode blendMode)
-{
- if (paintingDisabled() || !image)
- return;
-
- if (useLowQualityScale) {
- InterpolationQuality previousInterpolationQuality = imageInterpolationQuality();
- setImageInterpolationQuality(InterpolationLow);
- image->drawTiled(this, destRect, srcPoint, tileSize, op, blendMode);
- setImageInterpolationQuality(previousInterpolationQuality);
- } else {
- image->drawTiled(this, destRect, srcPoint, tileSize, op, blendMode);
- }
-}
-
-void GraphicsContext::drawTiledImage(Image* image, const IntRect& dest, const IntRect& srcRect,
- const FloatSize& tileScaleFactor, Image::TileRule hRule, Image::TileRule vRule, CompositeOperator op, bool useLowQualityScale)
-{
- if (paintingDisabled() || !image)
- return;
-
- if (hRule == Image::StretchTile && vRule == Image::StretchTile) {
- // Just do a scale.
- drawImage(image, dest, srcRect, op);
- return;
- }
-
- if (useLowQualityScale) {
- InterpolationQuality previousInterpolationQuality = imageInterpolationQuality();
- setImageInterpolationQuality(InterpolationLow);
- image->drawTiled(this, dest, srcRect, tileScaleFactor, hRule, vRule, op);
- setImageInterpolationQuality(previousInterpolationQuality);
- } else {
- image->drawTiled(this, dest, srcRect, tileScaleFactor, hRule, vRule, op);
- }
-}
-
-void GraphicsContext::drawImageBuffer(ImageBuffer* image, const IntPoint& p, CompositeOperator op, BlendMode blendMode)
-{
- if (!image)
- return;
- drawImageBuffer(image, FloatRect(IntRect(p, image->logicalSize())), FloatRect(FloatPoint(), FloatSize(image->logicalSize())), op, blendMode);
-}
-
-void GraphicsContext::drawImageBuffer(ImageBuffer* image, const IntRect& r, CompositeOperator op, BlendMode blendMode, bool useLowQualityScale)
-{
- if (!image)
- return;
- drawImageBuffer(image, FloatRect(r), FloatRect(FloatPoint(), FloatSize(image->logicalSize())), op, blendMode, useLowQualityScale);
-}
-
-void GraphicsContext::drawImageBuffer(ImageBuffer* image, const IntPoint& dest, const IntRect& srcRect, CompositeOperator op, BlendMode blendMode)
-{
- drawImageBuffer(image, FloatRect(IntRect(dest, srcRect.size())), FloatRect(srcRect), op, blendMode);
-}
-
-void GraphicsContext::drawImageBuffer(ImageBuffer* image, const IntRect& dest, const IntRect& srcRect, CompositeOperator op, BlendMode blendMode, bool useLowQualityScale)
-{
- drawImageBuffer(image, FloatRect(dest), FloatRect(srcRect), op, blendMode, useLowQualityScale);
-}
-
-void GraphicsContext::drawImageBuffer(ImageBuffer* image, const FloatRect& dest)
-{
- if (!image)
- return;
- drawImageBuffer(image, dest, FloatRect(IntRect(IntPoint(), image->logicalSize())));
-}
-
-void GraphicsContext::drawImageBuffer(ImageBuffer* image, const FloatRect& dest, const FloatRect& src, CompositeOperator op, BlendMode blendMode, bool useLowQualityScale)
-{
- if (paintingDisabled() || !image)
- return;
-
- if (useLowQualityScale) {
- InterpolationQuality previousInterpolationQuality = imageInterpolationQuality();
- setImageInterpolationQuality(InterpolationLow);
- image->draw(this, dest, src, op, blendMode, useLowQualityScale);
- setImageInterpolationQuality(previousInterpolationQuality);
- } else {
- image->draw(this, dest, src, op, blendMode, useLowQualityScale);
- }
-}
-
-void GraphicsContext::writePixels(const SkBitmap& bitmap, int x, int y, SkCanvas::Config8888 config8888)
-{
- if (paintingDisabled())
- return;
-
- m_canvas->writePixels(bitmap, x, y, config8888);
-
- if (m_trackOpaqueRegion) {
- SkRect rect = SkRect::MakeXYWH(x, y, bitmap.width(), bitmap.height());
- SkPaint paint;
-
- paint.setXfermodeMode(SkXfermode::kSrc_Mode);
- m_opaqueRegion.didDrawRect(this, rect, paint, &bitmap);
- }
-}
-
-void GraphicsContext::drawBitmap(const SkBitmap& bitmap, SkScalar left, SkScalar top, const SkPaint* paint)
-{
- if (paintingDisabled())
- return;
-
- m_canvas->drawBitmap(bitmap, left, top, paint);
-
- if (m_trackOpaqueRegion) {
- SkRect rect = SkRect::MakeXYWH(left, top, bitmap.width(), bitmap.height());
- m_opaqueRegion.didDrawRect(this, rect, *paint, &bitmap);
- }
-}
-
-void GraphicsContext::drawBitmapRect(const SkBitmap& bitmap, const SkRect* src,
- const SkRect& dst, const SkPaint* paint)
-{
- if (paintingDisabled())
- return;
-
- SkCanvas::DrawBitmapRectFlags flags = m_state->m_shouldClampToSourceRect ? SkCanvas::kNone_DrawBitmapRectFlag : SkCanvas::kBleed_DrawBitmapRectFlag;
-
- m_canvas->drawBitmapRectToRect(bitmap, src, dst, paint, flags);
-
- if (m_trackOpaqueRegion)
- m_opaqueRegion.didDrawRect(this, dst, *paint, &bitmap);
-}
-
-void GraphicsContext::drawOval(const SkRect& oval, const SkPaint& paint)
-{
- if (paintingDisabled())
- return;
-
- m_canvas->drawOval(oval, paint);
-
- if (m_trackOpaqueRegion)
- m_opaqueRegion.didDrawBounded(this, oval, paint);
-}
-
-void GraphicsContext::drawPath(const SkPath& path, const SkPaint& paint)
-{
- if (paintingDisabled())
- return;
-
- m_canvas->drawPath(path, paint);
-
- if (m_trackOpaqueRegion)
- m_opaqueRegion.didDrawPath(this, path, paint);
-}
-
-void GraphicsContext::drawRect(const SkRect& rect, const SkPaint& paint)
-{
- if (paintingDisabled())
- return;
-
- m_canvas->drawRect(rect, paint);
-
- if (m_trackOpaqueRegion)
- m_opaqueRegion.didDrawRect(this, rect, paint, 0);
-}
-
-void GraphicsContext::didDrawRect(const SkRect& rect, const SkPaint& paint, const SkBitmap* bitmap)
-{
- if (m_trackOpaqueRegion)
- m_opaqueRegion.didDrawRect(this, rect, paint, bitmap);
-}
-
-void GraphicsContext::drawPosText(const void* text, size_t byteLength,
- const SkPoint pos[], const SkRect& textRect, const SkPaint& paint)
-{
- if (paintingDisabled())
- return;
-
- m_canvas->drawPosText(text, byteLength, pos, paint);
- didDrawTextInRect(textRect);
-
- // FIXME: compute bounds for positioned text.
- if (m_trackOpaqueRegion)
- m_opaqueRegion.didDrawUnbounded(this, paint, OpaqueRegionSkia::FillOrStroke);
-}
-
-void GraphicsContext::drawPosTextH(const void* text, size_t byteLength,
- const SkScalar xpos[], SkScalar constY, const SkRect& textRect, const SkPaint& paint)
-{
- if (paintingDisabled())
- return;
-
- m_canvas->drawPosTextH(text, byteLength, xpos, constY, paint);
- didDrawTextInRect(textRect);
-
- // FIXME: compute bounds for positioned text.
- if (m_trackOpaqueRegion)
- m_opaqueRegion.didDrawUnbounded(this, paint, OpaqueRegionSkia::FillOrStroke);
-}
-
-void GraphicsContext::drawTextOnPath(const void* text, size_t byteLength,
- const SkPath& path, const SkRect& textRect, const SkMatrix* matrix, const SkPaint& paint)
-{
- if (paintingDisabled())
- return;
-
- m_canvas->drawTextOnPath(text, byteLength, path, matrix, paint);
- didDrawTextInRect(textRect);
-
- // FIXME: compute bounds for positioned text.
- if (m_trackOpaqueRegion)
- m_opaqueRegion.didDrawUnbounded(this, paint, OpaqueRegionSkia::FillOrStroke);
-}
-
-void GraphicsContext::fillPath(const Path& pathToFill)
-{
- if (paintingDisabled() || pathToFill.isEmpty())
- return;
-
- // Use const_cast and temporarily modify the fill type instead of copying the path.
- SkPath& path = const_cast<SkPath&>(pathToFill.skPath());
- SkPath::FillType previousFillType = path.getFillType();
-
- SkPath::FillType temporaryFillType = m_state->m_fillRule == RULE_EVENODD ? SkPath::kEvenOdd_FillType : SkPath::kWinding_FillType;
- path.setFillType(temporaryFillType);
-
- SkPaint paint;
- setupPaintForFilling(&paint);
- drawPath(path, paint);
-
- path.setFillType(previousFillType);
-}
-
-void GraphicsContext::fillRect(const FloatRect& rect)
-{
- if (paintingDisabled())
- return;
-
- SkRect r = rect;
-
- SkPaint paint;
- setupPaintForFilling(&paint);
- drawRect(r, paint);
-}
-
-void GraphicsContext::fillRect(const FloatRect& rect, const Color& color)
-{
- if (paintingDisabled())
- return;
-
- SkRect r = rect;
- SkPaint paint;
- setupPaintCommon(&paint);
- paint.setColor(color.rgb());
- drawRect(r, paint);
-}
-
-void GraphicsContext::fillRoundedRect(const IntRect& rect, const IntSize& topLeft, const IntSize& topRight,
- const IntSize& bottomLeft, const IntSize& bottomRight, const Color& color)
-{
- if (paintingDisabled())
- return;
-
- if (topLeft.width() + topRight.width() > rect.width()
- || bottomLeft.width() + bottomRight.width() > rect.width()
- || topLeft.height() + bottomLeft.height() > rect.height()
- || topRight.height() + bottomRight.height() > rect.height()) {
- // Not all the radii fit, return a rect. This matches the behavior of
- // Path::createRoundedRectangle. Without this we attempt to draw a round
- // shadow for a square box.
- fillRect(rect, color);
- return;
- }
-
- SkVector radii[4];
- setRadii(radii, topLeft, topRight, bottomRight, bottomLeft);
-
- SkRRect rr;
- rr.setRectRadii(rect, radii);
-
- SkPaint paint;
- setupPaintForFilling(&paint);
- paint.setColor(color.rgb());
-
- m_canvas->drawRRect(rr, paint);
-
- if (m_trackOpaqueRegion)
- m_opaqueRegion.didDrawBounded(this, rr.getBounds(), paint);
-}
-
-void GraphicsContext::fillEllipse(const FloatRect& ellipse)
-{
- if (paintingDisabled())
- return;
-
- SkRect rect = ellipse;
- SkPaint paint;
- setupPaintForFilling(&paint);
- drawOval(rect, paint);
-}
-
-void GraphicsContext::strokePath(const Path& pathToStroke)
-{
- if (paintingDisabled() || pathToStroke.isEmpty())
- return;
-
- const SkPath& path = pathToStroke.skPath();
- SkPaint paint;
- setupPaintForStroking(&paint);
- drawPath(path, paint);
-}
-
-void GraphicsContext::strokeRect(const FloatRect& rect, float lineWidth)
-{
- if (paintingDisabled())
- return;
-
- SkPaint paint;
- setupPaintForStroking(&paint);
- paint.setStrokeWidth(WebCoreFloatToSkScalar(lineWidth));
- // strokerect has special rules for CSS when the rect is degenerate:
- // if width==0 && height==0, do nothing
- // if width==0 || height==0, then just draw line for the other dimension
- SkRect r(rect);
- bool validW = r.width() > 0;
- bool validH = r.height() > 0;
- if (validW && validH) {
- drawRect(r, paint);
- } else if (validW || validH) {
- // we are expected to respect the lineJoin, so we can't just call
- // drawLine -- we have to create a path that doubles back on itself.
- SkPath path;
- path.moveTo(r.fLeft, r.fTop);
- path.lineTo(r.fRight, r.fBottom);
- path.close();
- drawPath(path, paint);
- }
-}
-
-void GraphicsContext::strokeEllipse(const FloatRect& ellipse)
-{
- if (paintingDisabled())
- return;
-
- SkRect rect(ellipse);
- SkPaint paint;
- setupPaintForStroking(&paint);
- drawOval(rect, paint);
-}
-
-void GraphicsContext::clipRoundedRect(const RoundedRect& rect)
-{
- if (paintingDisabled())
- return;
-
- SkVector radii[4];
- RoundedRect::Radii wkRadii = rect.radii();
- setRadii(radii, wkRadii.topLeft(), wkRadii.topRight(), wkRadii.bottomRight(), wkRadii.bottomLeft());
-
- SkRRect r;
- r.setRectRadii(rect.rect(), radii);
-
- clipRRect(r, AntiAliased);
-}
-
-void GraphicsContext::clipOut(const Path& pathToClip)
-{
- if (paintingDisabled())
- return;
-
- // Use const_cast and temporarily toggle the inverse fill type instead of copying the path.
- SkPath& path = const_cast<SkPath&>(pathToClip.skPath());
- path.toggleInverseFillType();
- clipPath(path, AntiAliased);
- path.toggleInverseFillType();
-}
-
-void GraphicsContext::clipPath(const Path& pathToClip, WindRule clipRule)
-{
- if (paintingDisabled() || pathToClip.isEmpty())
- return;
-
- // Use const_cast and temporarily modify the fill type instead of copying the path.
- SkPath& path = const_cast<SkPath&>(pathToClip.skPath());
- SkPath::FillType previousFillType = path.getFillType();
-
- SkPath::FillType temporaryFillType = clipRule == RULE_EVENODD ? SkPath::kEvenOdd_FillType : SkPath::kWinding_FillType;
- path.setFillType(temporaryFillType);
- clipPath(path, AntiAliased);
-
- path.setFillType(previousFillType);
-}
-
-void GraphicsContext::clipConvexPolygon(size_t numPoints, const FloatPoint* points, bool antialiased)
-{
- if (paintingDisabled())
- return;
-
- if (numPoints <= 1)
- return;
-
- SkPath path;
- setPathFromConvexPoints(&path, numPoints, points);
- clipPath(path, antialiased ? AntiAliased : NotAntiAliased);
-}
-
-void GraphicsContext::clipOutRoundedRect(const RoundedRect& rect)
-{
- if (paintingDisabled())
- return;
-
- if (!rect.isRounded()) {
- clipOut(rect.rect());
- return;
- }
-
- Path path;
- path.addRoundedRect(rect);
- clipOut(path);
-}
-
-void GraphicsContext::canvasClip(const Path& pathToClip, WindRule clipRule)
-{
- if (paintingDisabled())
- return;
-
- // Use const_cast and temporarily modify the fill type instead of copying the path.
- SkPath& path = const_cast<SkPath&>(pathToClip.skPath());
- SkPath::FillType previousFillType = path.getFillType();
-
- SkPath::FillType temporaryFillType = clipRule == RULE_EVENODD ? SkPath::kEvenOdd_FillType : SkPath::kWinding_FillType;
- path.setFillType(temporaryFillType);
- clipPath(path);
-
- path.setFillType(previousFillType);
-}
-
-bool GraphicsContext::clipRect(const SkRect& rect, AntiAliasingMode aa, SkRegion::Op op)
-{
- if (paintingDisabled())
- return false;
-
- realizeSave(SkCanvas::kClip_SaveFlag);
-
- return m_canvas->clipRect(rect, op, aa == AntiAliased);
-}
-
-bool GraphicsContext::clipPath(const SkPath& path, AntiAliasingMode aa, SkRegion::Op op)
-{
- if (paintingDisabled())
- return false;
-
- realizeSave(SkCanvas::kClip_SaveFlag);
-
- return m_canvas->clipPath(path, op, aa == AntiAliased);
-}
-
-bool GraphicsContext::clipRRect(const SkRRect& rect, AntiAliasingMode aa, SkRegion::Op op)
-{
- if (paintingDisabled())
- return false;
-
- realizeSave(SkCanvas::kClip_SaveFlag);
-
- return m_canvas->clipRRect(rect, op, aa == AntiAliased);
-}
-
-void GraphicsContext::rotate(float angleInRadians)
-{
- if (paintingDisabled())
- return;
-
- realizeSave(SkCanvas::kMatrix_SaveFlag);
-
- m_canvas->rotate(WebCoreFloatToSkScalar(angleInRadians * (180.0f / 3.14159265f)));
-}
-
-void GraphicsContext::translate(float w, float h)
-{
- if (paintingDisabled())
- return;
-
- realizeSave(SkCanvas::kMatrix_SaveFlag);
-
- m_canvas->translate(WebCoreFloatToSkScalar(w), WebCoreFloatToSkScalar(h));
-}
-
-void GraphicsContext::scale(const FloatSize& size)
-{
- if (paintingDisabled())
- return;
-
- realizeSave(SkCanvas::kMatrix_SaveFlag);
-
- m_canvas->scale(WebCoreFloatToSkScalar(size.width()), WebCoreFloatToSkScalar(size.height()));
-}
-
-void GraphicsContext::setURLForRect(const KURL& link, const IntRect& destRect)
-{
- if (paintingDisabled())
- return;
-
- SkAutoDataUnref url(SkData::NewWithCString(link.string().utf8().data()));
- SkAnnotateRectWithURL(m_canvas, destRect, url.get());
-}
-
-void GraphicsContext::setURLFragmentForRect(const String& destName, const IntRect& rect)
-{
- if (paintingDisabled())
- return;
-
- SkAutoDataUnref skDestName(SkData::NewWithCString(destName.utf8().data()));
- SkAnnotateLinkToDestination(m_canvas, rect, skDestName.get());
-}
-
-void GraphicsContext::addURLTargetAtPoint(const String& name, const IntPoint& pos)
-{
- if (paintingDisabled())
- return;
-
- SkAutoDataUnref nameData(SkData::NewWithCString(name.utf8().data()));
- SkAnnotateNamedDestination(m_canvas, SkPoint::Make(pos.x(), pos.y()), nameData);
-}
-
-AffineTransform GraphicsContext::getCTM(IncludeDeviceScale) const
-{
- if (paintingDisabled())
- return AffineTransform();
-
- const SkMatrix& m = getTotalMatrix();
- return AffineTransform(SkScalarToDouble(m.getScaleX()),
- SkScalarToDouble(m.getSkewY()),
- SkScalarToDouble(m.getSkewX()),
- SkScalarToDouble(m.getScaleY()),
- SkScalarToDouble(m.getTranslateX()),
- SkScalarToDouble(m.getTranslateY()));
-}
-
-void GraphicsContext::fillRect(const FloatRect& rect, const Color& color, CompositeOperator op)
-{
- if (paintingDisabled())
- return;
-
- CompositeOperator previousOperator = compositeOperation();
- setCompositeOperation(op);
- fillRect(rect, color);
- setCompositeOperation(previousOperator);
-}
-
-void GraphicsContext::fillRoundedRect(const RoundedRect& rect, const Color& color)
-{
- if (rect.isRounded())
- fillRoundedRect(rect.rect(), rect.radii().topLeft(), rect.radii().topRight(), rect.radii().bottomLeft(), rect.radii().bottomRight(), color);
- else
- fillRect(rect.rect(), color);
-}
-
-void GraphicsContext::fillRectWithRoundedHole(const IntRect& rect, const RoundedRect& roundedHoleRect, const Color& color)
-{
- if (paintingDisabled())
- return;
-
- Path path;
- path.addRect(rect);
-
- if (!roundedHoleRect.radii().isZero())
- path.addRoundedRect(roundedHoleRect);
- else
- path.addRect(roundedHoleRect.rect());
-
- WindRule oldFillRule = fillRule();
- Color oldFillColor = fillColor();
-
- setFillRule(RULE_EVENODD);
- setFillColor(color);
-
- fillPath(path);
-
- setFillRule(oldFillRule);
- setFillColor(oldFillColor);
-}
-
-void GraphicsContext::clearRect(const FloatRect& rect)
-{
- if (paintingDisabled())
- return;
-
- SkRect r = rect;
- SkPaint paint;
- setupPaintForFilling(&paint);
- paint.setXfermodeMode(SkXfermode::kClear_Mode);
- drawRect(r, paint);
-}
-
-void GraphicsContext::adjustLineToPixelBoundaries(FloatPoint& p1, FloatPoint& p2, float strokeWidth, StrokeStyle penStyle)
-{
- // For odd widths, we add in 0.5 to the appropriate x/y so that the float arithmetic
- // works out. For example, with a border width of 3, WebKit will pass us (y1+y2)/2, e.g.,
- // (50+53)/2 = 103/2 = 51 when we want 51.5. It is always true that an even width gave
- // us a perfect position, but an odd width gave us a position that is off by exactly 0.5.
- if (penStyle == DottedStroke || penStyle == DashedStroke) {
- if (p1.x() == p2.x()) {
- p1.setY(p1.y() + strokeWidth);
- p2.setY(p2.y() - strokeWidth);
- } else {
- p1.setX(p1.x() + strokeWidth);
- p2.setX(p2.x() - strokeWidth);
- }
- }
-
- if (static_cast<int>(strokeWidth) % 2) { //odd
- if (p1.x() == p2.x()) {
- // We're a vertical line. Adjust our x.
- p1.setX(p1.x() + 0.5f);
- p2.setX(p2.x() + 0.5f);
- } else {
- // We're a horizontal line. Adjust our y.
- p1.setY(p1.y() + 0.5f);
- p2.setY(p2.y() + 0.5f);
- }
- }
-}
-
-static bool scalesMatch(AffineTransform a, AffineTransform b)
-{
- return a.xScale() == b.xScale() && a.yScale() == b.yScale();
-}
-
-PassOwnPtr<ImageBuffer> GraphicsContext::createCompatibleBuffer(const IntSize& size, bool hasAlpha) const
-{
- // Make the buffer larger if the context's transform is scaling it so we need a higher
- // resolution than one pixel per unit. Also set up a corresponding scale factor on the
- // graphics context.
-
- AffineTransform transform = getCTM(DefinitelyIncludeDeviceScale);
- IntSize scaledSize(static_cast<int>(ceil(size.width() * transform.xScale())), static_cast<int>(ceil(size.height() * transform.yScale())));
-
- OwnPtr<ImageBuffer> buffer = ImageBuffer::createCompatibleBuffer(scaledSize, 1, this, hasAlpha);
- if (!buffer)
- return nullptr;
-
- buffer->context()->scale(FloatSize(static_cast<float>(scaledSize.width()) / size.width(),
- static_cast<float>(scaledSize.height()) / size.height()));
-
- return buffer.release();
-}
-
-bool GraphicsContext::isCompatibleWithBuffer(ImageBuffer* buffer) const
-{
- GraphicsContext* bufferContext = buffer->context();
-
- return scalesMatch(getCTM(), bufferContext->getCTM()) && m_accelerated == bufferContext->isAccelerated();
-}
-
-void GraphicsContext::addCornerArc(SkPath* path, const SkRect& rect, const IntSize& size, int startAngle)
-{
- SkIRect ir;
- int rx = SkMin32(SkScalarRound(rect.width()), size.width());
- int ry = SkMin32(SkScalarRound(rect.height()), size.height());
-
- ir.set(-rx, -ry, rx, ry);
- switch (startAngle) {
- case 0:
- ir.offset(rect.fRight - ir.fRight, rect.fBottom - ir.fBottom);
- break;
- case 90:
- ir.offset(rect.fLeft - ir.fLeft, rect.fBottom - ir.fBottom);
- break;
- case 180:
- ir.offset(rect.fLeft - ir.fLeft, rect.fTop - ir.fTop);
- break;
- case 270:
- ir.offset(rect.fRight - ir.fRight, rect.fTop - ir.fTop);
- break;
- default:
- ASSERT(0);
- }
-
- SkRect r;
- r.set(ir);
- path->arcTo(r, SkIntToScalar(startAngle), SkIntToScalar(90), false);
-}
-
-void GraphicsContext::setPathFromConvexPoints(SkPath* path, size_t numPoints, const FloatPoint* points)
-{
- path->incReserve(numPoints);
- path->moveTo(WebCoreFloatToSkScalar(points[0].x()),
- WebCoreFloatToSkScalar(points[0].y()));
- for (size_t i = 1; i < numPoints; ++i) {
- path->lineTo(WebCoreFloatToSkScalar(points[i].x()),
- WebCoreFloatToSkScalar(points[i].y()));
- }
-
- /* The code used to just blindly call this
- path->setIsConvex(true);
- But webkit can sometimes send us non-convex 4-point values, so we mark the path's
- convexity as unknown, so it will get computed by skia at draw time.
- See crbug.com 108605
- */
- SkPath::Convexity convexity = SkPath::kConvex_Convexity;
- if (numPoints == 4)
- convexity = SkPath::kUnknown_Convexity;
- path->setConvexity(convexity);
-}
-
-void GraphicsContext::setupPaintCommon(SkPaint* paint) const
-{
-#if defined(SK_DEBUG)
- {
- SkPaint defaultPaint;
- SkASSERT(*paint == defaultPaint);
- }
-#endif
-
- paint->setAntiAlias(m_state->m_shouldAntialias);
-
- if (!SkXfermode::IsMode(m_state->m_xferMode.get(), SkXfermode::kSrcOver_Mode))
- paint->setXfermode(m_state->m_xferMode.get());
- if (this->drawLuminanceMask())
- paint->setXfermode(SkLumaMaskXfermode::Create(SkXfermode::kSrcOver_Mode));
-
- if (m_state->m_looper)
- paint->setLooper(m_state->m_looper.get());
-
- paint->setColorFilter(m_state->m_colorFilter.get());
-}
-
-void GraphicsContext::drawOuterPath(const SkPath& path, SkPaint& paint, int width)
-{
-#if OS(MACOSX)
- paint.setAlpha(64);
- paint.setStrokeWidth(width);
- paint.setPathEffect(new SkCornerPathEffect((width - 1) * 0.5f))->unref();
-#else
- paint.setStrokeWidth(1);
- paint.setPathEffect(new SkCornerPathEffect(1))->unref();
-#endif
- drawPath(path, paint);
-}
-
-void GraphicsContext::drawInnerPath(const SkPath& path, SkPaint& paint, int width)
-{
-#if OS(MACOSX)
- paint.setAlpha(128);
- paint.setStrokeWidth(width * 0.5f);
- drawPath(path, paint);
-#endif
-}
-
-void GraphicsContext::setRadii(SkVector* radii, IntSize topLeft, IntSize topRight, IntSize bottomRight, IntSize bottomLeft)
-{
- radii[SkRRect::kUpperLeft_Corner].set(SkIntToScalar(topLeft.width()),
- SkIntToScalar(topLeft.height()));
- radii[SkRRect::kUpperRight_Corner].set(SkIntToScalar(topRight.width()),
- SkIntToScalar(topRight.height()));
- radii[SkRRect::kLowerRight_Corner].set(SkIntToScalar(bottomRight.width()),
- SkIntToScalar(bottomRight.height()));
- radii[SkRRect::kLowerLeft_Corner].set(SkIntToScalar(bottomLeft.width()),
- SkIntToScalar(bottomLeft.height()));
-}
-
-#if OS(MACOSX)
-CGColorSpaceRef deviceRGBColorSpaceRef()
-{
- static CGColorSpaceRef deviceSpace = CGColorSpaceCreateDeviceRGB();
- return deviceSpace;
-}
-#else
-void GraphicsContext::draw2xMarker(SkBitmap* bitmap, int index)
-{
- const SkPMColor lineColor = lineColors(index);
- const SkPMColor antiColor1 = antiColors1(index);
- const SkPMColor antiColor2 = antiColors2(index);
-
- uint32_t* row1 = bitmap->getAddr32(0, 0);
- uint32_t* row2 = bitmap->getAddr32(0, 1);
- uint32_t* row3 = bitmap->getAddr32(0, 2);
- uint32_t* row4 = bitmap->getAddr32(0, 3);
-
- // Pattern: X0o o0X0o o0
- // XX0o o0XXX0o o0X
- // o0XXX0o o0XXX0o
- // o0X0o o0X0o
- const SkPMColor row1Color[] = { lineColor, antiColor1, antiColor2, 0, 0, 0, antiColor2, antiColor1 };
- const SkPMColor row2Color[] = { lineColor, lineColor, antiColor1, antiColor2, 0, antiColor2, antiColor1, lineColor };
- const SkPMColor row3Color[] = { 0, antiColor2, antiColor1, lineColor, lineColor, lineColor, antiColor1, antiColor2 };
- const SkPMColor row4Color[] = { 0, 0, antiColor2, antiColor1, lineColor, antiColor1, antiColor2, 0 };
-
- for (int x = 0; x < bitmap->width() + 8; x += 8) {
- int count = std::min(bitmap->width() - x, 8);
- if (count > 0) {
- memcpy(row1 + x, row1Color, count * sizeof(SkPMColor));
- memcpy(row2 + x, row2Color, count * sizeof(SkPMColor));
- memcpy(row3 + x, row3Color, count * sizeof(SkPMColor));
- memcpy(row4 + x, row4Color, count * sizeof(SkPMColor));
- }
- }
-}
-
-void GraphicsContext::draw1xMarker(SkBitmap* bitmap, int index)
-{
- const uint32_t lineColor = lineColors(index);
- const uint32_t antiColor = antiColors2(index);
-
- // Pattern: X o o X o o X
- // o X o o X o
- uint32_t* row1 = bitmap->getAddr32(0, 0);
- uint32_t* row2 = bitmap->getAddr32(0, 1);
- for (int x = 0; x < bitmap->width(); x++) {
- switch (x % 4) {
- case 0:
- row1[x] = lineColor;
- break;
- case 1:
- row1[x] = antiColor;
- row2[x] = antiColor;
- break;
- case 2:
- row2[x] = lineColor;
- break;
- case 3:
- row1[x] = antiColor;
- row2[x] = antiColor;
- break;
- }
- }
-}
-
-const SkPMColor GraphicsContext::lineColors(int index)
-{
- static const SkPMColor colors[] = {
- SkPreMultiplyARGB(0xFF, 0xFF, 0x00, 0x00), // Opaque red.
- SkPreMultiplyARGB(0xFF, 0xC0, 0xC0, 0xC0) // Opaque gray.
- };
-
- return colors[index];
-}
-
-const SkPMColor GraphicsContext::antiColors1(int index)
-{
- static const SkPMColor colors[] = {
- SkPreMultiplyARGB(0xB0, 0xFF, 0x00, 0x00), // Semitransparent red.
- SkPreMultiplyARGB(0xB0, 0xC0, 0xC0, 0xC0) // Semitransparent gray.
- };
-
- return colors[index];
-}
-
-const SkPMColor GraphicsContext::antiColors2(int index)
-{
- static const SkPMColor colors[] = {
- SkPreMultiplyARGB(0x60, 0xFF, 0x00, 0x00), // More transparent red
- SkPreMultiplyARGB(0x60, 0xC0, 0xC0, 0xC0) // More transparent gray
- };
-
- return colors[index];
-}
-#endif
-
-void GraphicsContext::setupShader(SkPaint* paint, Gradient* grad, Pattern* pat, SkColor color) const
-{
- RefPtr<SkShader> shader;
-
- if (grad) {
- shader = grad->shader();
- color = SK_ColorBLACK;
- } else if (pat) {
- shader = pat->shader();
- color = SK_ColorBLACK;
- paint->setFilterBitmap(imageInterpolationQuality() != InterpolationNone);
- }
-
- paint->setColor(m_state->applyAlpha(color));
-
- if (!shader)
- return;
-
- paint->setShader(shader.get());
-}
-
-void GraphicsContext::didDrawTextInRect(const SkRect& textRect)
-{
- if (m_trackTextRegion) {
- TRACE_EVENT0("skia", "PlatformContextSkia::trackTextRegion");
- m_textRegion.join(textRect);
- }
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsContext.h b/chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsContext.h
deleted file mode 100644
index 28b70886f46..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsContext.h
+++ /dev/null
@@ -1,479 +0,0 @@
-/*
- * Copyright (C) 2003, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
- * Copyright (C) 2008-2009 Torch Mobile, Inc.
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef GraphicsContext_h
-#define GraphicsContext_h
-
-#include "core/platform/chromium/TraceEvent.h"
-#include "core/platform/graphics/DashArray.h"
-#include "core/platform/graphics/DrawLooper.h"
-#include "core/platform/graphics/FloatRect.h"
-#include "core/platform/graphics/Font.h"
-#include "core/platform/graphics/GraphicsContextAnnotation.h"
-#include "core/platform/graphics/GraphicsContextState.h"
-#include "core/platform/graphics/ImageBuffer.h"
-#include "core/platform/graphics/ImageOrientation.h"
-#include "core/platform/graphics/skia/OpaqueRegionSkia.h"
-// TODO(robertphillips): replace this include with "class SkBaseDevice;"
-#include "third_party/skia/include/core/SkDevice.h"
-#include "wtf/FastAllocBase.h"
-#include "wtf/Forward.h"
-#include "wtf/Noncopyable.h"
-#include "wtf/PassOwnPtr.h"
-
-class SkBitmap;
-class SkPaint;
-class SkPath;
-class SkRRect;
-struct SkRect;
-
-namespace WebCore {
-
-class ImageBuffer;
-class KURL;
-
-class GraphicsContext {
- WTF_MAKE_NONCOPYABLE(GraphicsContext); WTF_MAKE_FAST_ALLOCATED;
-public:
- enum AntiAliasingMode {
- NotAntiAliased,
- AntiAliased
- };
- enum AccessMode {
- ReadOnly,
- ReadWrite
- };
-
- explicit GraphicsContext(SkCanvas*);
- ~GraphicsContext();
-
- // Returns the canvas used for painting, NOT guaranteed to be non-null.
- // Accessing the backing canvas this way flushes all queued save ops,
- // so it should be avoided. Use the corresponding draw/matrix/clip methods instead.
- SkCanvas* canvas()
- {
- // Flush any pending saves.
- realizeSave(SkCanvas::kMatrixClip_SaveFlag);
-
- return m_canvas;
- }
- const SkCanvas* canvas() const { return m_canvas; }
- bool paintingDisabled() const { return !m_canvas; }
-
- const SkBitmap* bitmap() const;
- const SkBitmap& layerBitmap(AccessMode = ReadOnly) const;
-
- SkBaseDevice* createCompatibleDevice(const IntSize&, bool hasAlpha) const;
-
- // ---------- State management methods -----------------
- void save();
- void restore();
-
- void saveLayer(const SkRect* bounds, const SkPaint*, SkCanvas::SaveFlags = SkCanvas::kARGB_ClipLayer_SaveFlag);
- void restoreLayer();
-
- float strokeThickness() const { return m_state->m_strokeData.thickness(); }
- void setStrokeThickness(float thickness) { m_state->m_strokeData.setThickness(thickness); }
-
- StrokeStyle strokeStyle() const { return m_state->m_strokeData.style(); }
- void setStrokeStyle(StrokeStyle style) { m_state->m_strokeData.setStyle(style); }
-
- Color strokeColor() const { return m_state->m_strokeData.color(); }
- void setStrokeColor(const Color&);
-
- Pattern* strokePattern() const { return m_state->m_strokeData.pattern(); }
- void setStrokePattern(PassRefPtr<Pattern>);
-
- Gradient* strokeGradient() const { return m_state->m_strokeData.gradient(); }
- void setStrokeGradient(PassRefPtr<Gradient>);
-
- void setLineCap(LineCap cap) { m_state->m_strokeData.setLineCap(cap); }
- void setLineDash(const DashArray& dashes, float dashOffset) { m_state->m_strokeData.setLineDash(dashes, dashOffset); }
- void setLineJoin(LineJoin join) { m_state->m_strokeData.setLineJoin(join); }
- void setMiterLimit(float limit) { m_state->m_strokeData.setMiterLimit(limit); }
-
- WindRule fillRule() const { return m_state->m_fillRule; }
- void setFillRule(WindRule fillRule) { m_state->m_fillRule = fillRule; }
-
- Color fillColor() const { return m_state->m_fillColor; }
- void setFillColor(const Color&);
- SkColor effectiveFillColor() const { return m_state->applyAlpha(m_state->m_fillColor.rgb()); }
-
- void setFillPattern(PassRefPtr<Pattern>);
- Pattern* fillPattern() const { return m_state->m_fillPattern.get(); }
-
- void setFillGradient(PassRefPtr<Gradient>);
- Gradient* fillGradient() const { return m_state->m_fillGradient.get(); }
-
- SkDrawLooper* drawLooper() const { return m_state->m_looper.get(); }
- SkColor effectiveStrokeColor() const { return m_state->applyAlpha(m_state->m_strokeData.color().rgb()); }
-
- int getNormalizedAlpha() const;
-
- bool getClipBounds(SkRect* bounds) const;
- bool getTransformedClipBounds(FloatRect* bounds) const;
- const SkMatrix& getTotalMatrix() const;
- bool isPrintingDevice() const;
-
- void setShouldAntialias(bool antialias) { m_state->m_shouldAntialias = antialias; }
- bool shouldAntialias() const { return m_state->m_shouldAntialias; }
-
- void setShouldClampToSourceRect(bool clampToSourceRect) { m_state->m_shouldClampToSourceRect = clampToSourceRect; }
- bool shouldClampToSourceRect() const { return m_state->m_shouldClampToSourceRect; }
-
- void setShouldSmoothFonts(bool smoothFonts) { m_state->m_shouldSmoothFonts = smoothFonts; }
- bool shouldSmoothFonts() const { return m_state->m_shouldSmoothFonts; }
-
- // Turn off LCD text for the paint if not supported on this context.
- void adjustTextRenderMode(SkPaint*);
- bool couldUseLCDRenderedText();
-
- TextDrawingModeFlags textDrawingMode() const { return m_state->m_textDrawingMode; }
- void setTextDrawingMode(TextDrawingModeFlags mode) { m_state->m_textDrawingMode = mode; }
-
- void setAlpha(float alpha) { m_state->m_alpha = alpha; }
-
- void setImageInterpolationQuality(InterpolationQuality quality) { m_state->m_interpolationQuality = quality; }
- InterpolationQuality imageInterpolationQuality() const { return m_state->m_interpolationQuality; }
-
- void setCompositeOperation(CompositeOperator, BlendMode = BlendModeNormal);
- CompositeOperator compositeOperation() const { return m_state->m_compositeOperator; }
- BlendMode blendModeOperation() const { return m_state->m_blendMode; }
-
- void setDrawLuminanceMask(bool drawLuminanceMask) { m_state->m_drawLuminanceMask = drawLuminanceMask; }
- bool drawLuminanceMask() const { return m_state->m_drawLuminanceMask; }
-
- // Change the way document markers are rendered.
- // Any deviceScaleFactor higher than 1.5 is enough to justify setting this flag.
- void setUseHighResMarkers(bool isHighRes) { m_useHighResMarker = isHighRes; }
-
- // If true we are (most likely) rendering to a web page and the
- // canvas has been prepared with an opaque background. If false,
- // the canvas may havbe transparency (as is the case when rendering
- // to a canvas object).
- void setCertainlyOpaque(bool isOpaque) { m_isCertainlyOpaque = isOpaque; }
- bool isCertainlyOpaque() const { return m_isCertainlyOpaque; }
-
- // Returns if the context is a printing context instead of a display
- // context. Bitmap shouldn't be resampled when printing to keep the best
- // possible quality.
- bool printing() const { return m_printing; }
- void setPrinting(bool printing) { m_printing = printing; }
-
- bool isAccelerated() const { return m_accelerated; }
- void setAccelerated(bool accelerated) { m_accelerated = accelerated; }
-
- // The opaque region is empty until tracking is turned on.
- // It is never clerared by the context.
- void setTrackOpaqueRegion(bool track) { m_trackOpaqueRegion = track; }
- const OpaqueRegionSkia& opaqueRegion() const { return m_opaqueRegion; }
-
- // The text region is empty until tracking is turned on.
- // It is never clerared by the context.
- void setTrackTextRegion(bool track) { m_trackTextRegion = track; }
- const SkRect& textRegion() const { return m_textRegion; }
-
- bool updatingControlTints() const { return m_updatingControlTints; }
- void setUpdatingControlTints(bool updatingTints) { m_updatingControlTints = updatingTints; }
-
- AnnotationModeFlags annotationMode() const { return m_annotationMode; }
- void setAnnotationMode(const AnnotationModeFlags mode) { m_annotationMode = mode; }
-
- void setColorSpaceConversion(ColorSpace srcColorSpace, ColorSpace dstColorSpace);
- // ---------- End state management methods -----------------
-
- // Get the contents of the image buffer
- bool readPixels(SkBitmap*, int, int, SkCanvas::Config8888 = SkCanvas::kNative_Premul_Config8888);
-
- // Sets up the paint for the current fill style.
- void setupPaintForFilling(SkPaint*) const;
-
- // Sets up the paint for stroking. Returns a float representing the
- // effective width of the pen. If a non-zero length is provided, the
- // number of dashes/dots on a dashed/dotted line will be adjusted to
- // start and end that length with a dash/dot.
- float setupPaintForStroking(SkPaint*, int length = 0) const;
-
- // These draw methods will do both stroking and filling.
- // FIXME: ...except drawRect(), which fills properly but always strokes
- // using a 1-pixel stroke inset from the rect borders (of the correct
- // stroke color).
- void drawRect(const IntRect&);
- void drawLine(const IntPoint&, const IntPoint&);
- void drawEllipse(const IntRect&);
- void drawConvexPolygon(size_t numPoints, const FloatPoint*, bool shouldAntialias = false);
-
- void fillPath(const Path&);
- void strokePath(const Path&);
-
- void fillEllipse(const FloatRect&);
- void strokeEllipse(const FloatRect&);
-
- void fillRect(const FloatRect&);
- void fillRect(const FloatRect&, const Color&);
- void fillRect(const FloatRect&, const Color&, CompositeOperator);
- void fillRoundedRect(const IntRect&, const IntSize& topLeft, const IntSize& topRight, const IntSize& bottomLeft, const IntSize& bottomRight, const Color&);
- void fillRoundedRect(const RoundedRect&, const Color&);
-
- void clearRect(const FloatRect&);
-
- void strokeRect(const FloatRect&, float lineWidth);
-
- void drawImage(Image*, const IntPoint&, CompositeOperator = CompositeSourceOver, RespectImageOrientationEnum = DoNotRespectImageOrientation);
- void drawImage(Image*, const IntRect&, CompositeOperator = CompositeSourceOver, RespectImageOrientationEnum = DoNotRespectImageOrientation, bool useLowQualityScale = false);
- void drawImage(Image*, const IntPoint& destPoint, const IntRect& srcRect, CompositeOperator = CompositeSourceOver, RespectImageOrientationEnum = DoNotRespectImageOrientation);
- void drawImage(Image*, const FloatRect& destRect);
- void drawImage(Image*, const FloatRect& destRect, const FloatRect& srcRect, CompositeOperator = CompositeSourceOver, RespectImageOrientationEnum = DoNotRespectImageOrientation, bool useLowQualityScale = false);
- void drawImage(Image*, const FloatRect& destRect, const FloatRect& srcRect, CompositeOperator, BlendMode, RespectImageOrientationEnum = DoNotRespectImageOrientation, bool useLowQualityScale = false);
-
- void drawTiledImage(Image*, const IntRect& destRect, const IntPoint& srcPoint, const IntSize& tileSize,
- CompositeOperator = CompositeSourceOver, bool useLowQualityScale = false, BlendMode = BlendModeNormal);
- void drawTiledImage(Image*, const IntRect& destRect, const IntRect& srcRect,
- const FloatSize& tileScaleFactor, Image::TileRule hRule = Image::StretchTile, Image::TileRule vRule = Image::StretchTile,
- CompositeOperator = CompositeSourceOver, bool useLowQualityScale = false);
-
- void drawImageBuffer(ImageBuffer*, const IntPoint&, CompositeOperator = CompositeSourceOver, BlendMode = BlendModeNormal);
- void drawImageBuffer(ImageBuffer*, const IntRect&, CompositeOperator = CompositeSourceOver, BlendMode = BlendModeNormal, bool useLowQualityScale = false);
- void drawImageBuffer(ImageBuffer*, const IntPoint& destPoint, const IntRect& srcRect, CompositeOperator = CompositeSourceOver, BlendMode = BlendModeNormal);
- void drawImageBuffer(ImageBuffer*, const IntRect& destRect, const IntRect& srcRect, CompositeOperator = CompositeSourceOver, BlendMode = BlendModeNormal, bool useLowQualityScale = false);
- void drawImageBuffer(ImageBuffer*, const FloatRect& destRect);
- void drawImageBuffer(ImageBuffer*, const FloatRect& destRect, const FloatRect& srcRect, CompositeOperator = CompositeSourceOver, BlendMode = BlendModeNormal, bool useLowQualityScale = false);
-
- // These methods write to the canvas and modify the opaque region, if tracked.
- // Also drawLine(const IntPoint& point1, const IntPoint& point2) and fillRoundedRect
- void writePixels(const SkBitmap&, int x, int y, SkCanvas::Config8888 = SkCanvas::kNative_Premul_Config8888);
- void drawBitmap(const SkBitmap&, SkScalar, SkScalar, const SkPaint* = 0);
- void drawBitmapRect(const SkBitmap&, const SkRect*, const SkRect&, const SkPaint* = 0);
- void drawOval(const SkRect&, const SkPaint&);
- void drawPath(const SkPath&, const SkPaint&);
- // After drawing directly to the context's canvas, use this function to notify the context so
- // it can track the opaque region.
- // FIXME: this is still needed only because ImageSkia::paintSkBitmap() may need to notify for a
- // smaller rect than the one drawn to, due to its clipping logic.
- void didDrawRect(const SkRect&, const SkPaint&, const SkBitmap* = 0);
- void drawRect(const SkRect&, const SkPaint&);
- void drawPosText(const void* text, size_t byteLength, const SkPoint pos[], const SkRect& textRect, const SkPaint&);
- void drawPosTextH(const void* text, size_t byteLength, const SkScalar xpos[], SkScalar constY, const SkRect& textRect, const SkPaint&);
- void drawTextOnPath(const void* text, size_t byteLength, const SkPath&, const SkRect& textRect, const SkMatrix*, const SkPaint&);
-
- void clip(const IntRect& rect) { clip(FloatRect(rect)); }
- void clip(const FloatRect& rect) { clipRect(rect); }
- void clipRoundedRect(const RoundedRect&);
- void clipOut(const IntRect& rect) { clipRect(rect, NotAntiAliased, SkRegion::kDifference_Op); }
- void clipOutRoundedRect(const RoundedRect&);
- void clipPath(const Path&, WindRule = RULE_EVENODD);
- void clipConvexPolygon(size_t numPoints, const FloatPoint*, bool antialias = true);
- bool clipRect(const SkRect&, AntiAliasingMode = NotAntiAliased, SkRegion::Op = SkRegion::kIntersect_Op);
-
- void drawText(const Font&, const TextRunPaintInfo&, const FloatPoint&);
- void drawEmphasisMarks(const Font&, const TextRunPaintInfo&, const AtomicString& mark, const FloatPoint&);
- void drawBidiText(const Font&, const TextRunPaintInfo&, const FloatPoint&, Font::CustomFontNotReadyAction = Font::DoNotPaintIfFontNotReady);
- void drawHighlightForText(const Font&, const TextRun&, const FloatPoint&, int h, const Color& backgroundColor, int from = 0, int to = -1);
-
- void drawLineForText(const FloatPoint&, float width, bool printing);
- enum DocumentMarkerLineStyle {
- DocumentMarkerSpellingLineStyle,
- DocumentMarkerGrammarLineStyle
- };
- void drawLineForDocumentMarker(const FloatPoint&, float width, DocumentMarkerLineStyle);
-
- void beginTransparencyLayer(float opacity, const FloatRect* = 0);
- void beginTransparencyLayer(float opacity, CompositeOperator, const FloatRect* = 0);
- void beginMaskedLayer(const FloatRect&, MaskType = AlphaMaskType);
- void endLayer();
-
- bool hasShadow() const;
- void setShadow(const FloatSize& offset, float blur, const Color&,
- DrawLooper::ShadowTransformMode = DrawLooper::ShadowRespectsTransforms,
- DrawLooper::ShadowAlphaMode = DrawLooper::ShadowRespectsAlpha);
- void clearShadow() { clearDrawLooper(); }
-
- // It is assumed that this draw looper is used only for shadows
- // (i.e. a draw looper is set if and only if there is a shadow).
- void setDrawLooper(const DrawLooper&);
- void clearDrawLooper();
-
- void drawFocusRing(const Vector<IntRect>&, int width, int offset, const Color&);
- void drawFocusRing(const Path&, int width, int offset, const Color&);
-
- enum Edge {
- NoEdge = 0,
- TopEdge = 1 << 1,
- RightEdge = 1 << 2,
- BottomEdge = 1 << 3,
- LeftEdge = 1 << 4
- };
- typedef unsigned Edges;
- void drawInnerShadow(const RoundedRect&, const Color& shadowColor, const IntSize shadowOffset, int shadowBlur, int shadowSpread, Edges clippedEdges = NoEdge);
-
- // This clip function is used only by <canvas> code. It allows
- // implementations to handle clipping on the canvas differently since
- // the discipline is different.
- void canvasClip(const Path&, WindRule = RULE_EVENODD);
- void clipOut(const Path&);
-
- // ---------- Transformation methods -----------------
- enum IncludeDeviceScale { DefinitelyIncludeDeviceScale, PossiblyIncludeDeviceScale };
- AffineTransform getCTM(IncludeDeviceScale includeScale = PossiblyIncludeDeviceScale) const;
- void concatCTM(const AffineTransform& affine) { concat(affine); }
- void setCTM(const AffineTransform& affine) { setMatrix(affine); }
- void setMatrix(const SkMatrix&);
-
- void scale(const FloatSize&);
- void rotate(float angleInRadians);
- void translate(const FloatSize& size) { translate(size.width(), size.height()); }
- void translate(float x, float y);
-
- // This function applies the device scale factor to the context, making the context capable of
- // acting as a base-level context for a HiDPI environment.
- void applyDeviceScaleFactor(float deviceScaleFactor) { scale(FloatSize(deviceScaleFactor, deviceScaleFactor)); }
- // ---------- End transformation methods -----------------
-
- // URL drawing
- void setURLForRect(const KURL&, const IntRect&);
- void setURLFragmentForRect(const String& name, const IntRect&);
- void addURLTargetAtPoint(const String& name, const IntPoint&);
- bool supportsURLFragments() { return printing(); }
-
- // Create an image buffer compatible with this context, with suitable resolution
- // for drawing into the buffer and then into this context.
- PassOwnPtr<ImageBuffer> createCompatibleBuffer(const IntSize&, bool hasAlpha = true) const;
- bool isCompatibleWithBuffer(ImageBuffer*) const;
-
- static void adjustLineToPixelBoundaries(FloatPoint& p1, FloatPoint& p2, float strokeWidth, StrokeStyle);
-
- void beginAnnotation(const GraphicsContextAnnotation&);
- void endAnnotation();
-
-private:
- static void addCornerArc(SkPath*, const SkRect&, const IntSize&, int);
- static void setPathFromConvexPoints(SkPath*, size_t, const FloatPoint*);
- static void setRadii(SkVector*, IntSize, IntSize, IntSize, IntSize);
-
-#if OS(MACOSX)
- static inline int getFocusRingOutset(int offset) { return offset + 2; }
-#else
- static inline int getFocusRingOutset(int offset) { return 0; }
- static const SkPMColor lineColors(int);
- static const SkPMColor antiColors1(int);
- static const SkPMColor antiColors2(int);
- static void draw1xMarker(SkBitmap*, int);
- static void draw2xMarker(SkBitmap*, int);
-#endif
-
- // Return value % max, but account for value possibly being negative.
- static int fastMod(int value, int max)
- {
- bool isNeg = false;
- if (value < 0) {
- value = -value;
- isNeg = true;
- }
- if (value >= max)
- value %= max;
- if (isNeg)
- value = -value;
- return value;
- }
-
- // Sets up the common flags on a paint for antialiasing, effects, etc.
- // This is implicitly called by setupPaintFill and setupPaintStroke, but
- // you may wish to call it directly sometimes if you don't want that other
- // behavior.
- void setupPaintCommon(SkPaint*) const;
-
- // Helpers for drawing a focus ring (drawFocusRing)
- void drawOuterPath(const SkPath&, SkPaint&, int);
- void drawInnerPath(const SkPath&, SkPaint&, int);
-
- // SkCanvas wrappers.
- bool isDrawingToLayer() const { return m_canvas->isDrawingToLayer(); }
-
- bool clipPath(const SkPath&, AntiAliasingMode = NotAntiAliased, SkRegion::Op = SkRegion::kIntersect_Op);
- bool clipRRect(const SkRRect&, AntiAliasingMode = NotAntiAliased, SkRegion::Op = SkRegion::kIntersect_Op);
-
- bool concat(const SkMatrix&);
-
- // common code between setupPaintFor[Filling,Stroking]
- void setupShader(SkPaint*, Gradient*, Pattern*, SkColor) const;
-
- // Apply deferred saves
- void realizeSave(SkCanvas::SaveFlags flags)
- {
- if (m_deferredSaveFlags & flags) {
- m_canvas->save((SkCanvas::SaveFlags)m_deferredSaveFlags);
- m_deferredSaveFlags = 0;
- }
- }
-
- void didDrawTextInRect(const SkRect& textRect);
-
- void fillRectWithRoundedHole(const IntRect&, const RoundedRect& roundedHoleRect, const Color&);
-
- // null indicates painting is disabled. Never delete this object.
- SkCanvas* m_canvas;
-
- // Pointer to the current drawing state. This is a cached value of m_stateStack.last().
- GraphicsContextState* m_state;
- // States stack. Enables local drawing state change with save()/restore() calls.
- // Use OwnPtr to avoid copying the large state structure.
- Vector<OwnPtr<GraphicsContextState> > m_stateStack;
-
- // Currently pending save flags.
- // FIXME: While defined as a bitmask of SkCanvas::SaveFlags, this is mostly used as a bool.
- // It will come in handy when adding granular save() support (clip vs. matrix vs. paint).
- // crbug.com/233713
- struct DeferredSaveState;
- unsigned m_deferredSaveFlags;
- Vector<DeferredSaveState> m_saveStateStack;
-
- AnnotationModeFlags m_annotationMode;
-
-#if !ASSERT_DISABLED
- unsigned m_annotationCount;
- unsigned m_layerCount;
-#endif
- // Tracks the region painted opaque via the GraphicsContext.
- OpaqueRegionSkia m_opaqueRegion;
- bool m_trackOpaqueRegion : 1;
-
- // Tracks the region where text is painted via the GraphicsContext.
- bool m_trackTextRegion : 1;
- SkRect m_textRegion;
-
- // Are we on a high DPI display? If so, spelling and grammar markers are larger.
- bool m_useHighResMarker : 1;
- // FIXME: Make this go away: crbug.com/236892
- bool m_updatingControlTints : 1;
- bool m_accelerated : 1;
- bool m_isCertainlyOpaque : 1;
- bool m_printing : 1;
-};
-
-} // namespace WebCore
-
-#endif // GraphicsContext_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsContext3D.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsContext3D.cpp
deleted file mode 100644
index 3d649282dc0..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsContext3D.cpp
+++ /dev/null
@@ -1,1025 +0,0 @@
-/*
- * Copyright (C) 2010 Apple Inc. All rights reserved.
- * Copyright (C) 2010 Google Inc. All rights reserved.
- * Copyright (C) 2010 Mozilla Corporation. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/platform/graphics/GraphicsContext3D.h"
-
-#include "core/html/ImageData.h"
-#include "core/html/canvas/CheckedInt.h"
-#include "core/platform/graphics/Extensions3D.h"
-#include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/graphics/Image.h"
-#include "core/platform/graphics/ImageBuffer.h"
-#include "core/platform/graphics/ImageObserver.h"
-#include "core/platform/graphics/gpu/DrawingBuffer.h"
-#include "core/platform/image-decoders/ImageDecoder.h"
-#include "third_party/skia/include/gpu/GrContext.h"
-#include "third_party/skia/include/gpu/gl/GrGLInterface.h"
-#include "wtf/CPU.h"
-#include "wtf/OwnArrayPtr.h"
-#include "wtf/PassOwnArrayPtr.h"
-#include "wtf/text/CString.h"
-#include "wtf/text/StringHash.h"
-#include "wtf/text/WTFString.h"
-
-#include "public/platform/Platform.h"
-#include "public/platform/WebGraphicsContext3D.h"
-#include "public/platform/WebGraphicsContext3DProvider.h"
-#include "public/platform/WebGraphicsMemoryAllocation.h"
-
-namespace {
-
-// The limit of the number of textures we hold in the GrContext's bitmap->texture cache.
-const int maxGaneshTextureCacheCount = 2048;
-// The limit of the bytes allocated toward textures in the GrContext's bitmap->texture cache.
-const size_t maxGaneshTextureCacheBytes = 96 * 1024 * 1024;
-
-}
-
-namespace WebCore {
-
-namespace {
-
-void getDrawingParameters(DrawingBuffer* drawingBuffer, WebKit::WebGraphicsContext3D* graphicsContext3D,
- Platform3DObject* frameBufferId, int* width, int* height)
-{
- if (drawingBuffer) {
- *frameBufferId = drawingBuffer->framebuffer();
- *width = drawingBuffer->size().width();
- *height = drawingBuffer->size().height();
- } else {
- *frameBufferId = 0;
- *width = graphicsContext3D->width();
- *height = graphicsContext3D->height();
- }
-}
-
-} // anonymous namespace
-
-GraphicsContext3D::GraphicsContext3D(PassOwnPtr<WebKit::WebGraphicsContext3D> webContext, bool preserveDrawingBuffer)
- : m_impl(webContext.get())
- , m_ownedWebContext(webContext)
- , m_initializedAvailableExtensions(false)
- , m_layerComposited(false)
- , m_preserveDrawingBuffer(preserveDrawingBuffer)
- , m_packAlignment(4)
- , m_resourceSafety(ResourceSafetyUnknown)
- , m_grContext(0)
-{
-}
-
-GraphicsContext3D::GraphicsContext3D(PassOwnPtr<WebKit::WebGraphicsContext3DProvider> provider, bool preserveDrawingBuffer)
- : m_provider(provider)
- , m_impl(m_provider->context3d())
- , m_initializedAvailableExtensions(false)
- , m_layerComposited(false)
- , m_preserveDrawingBuffer(preserveDrawingBuffer)
- , m_packAlignment(4)
- , m_resourceSafety(ResourceSafetyUnknown)
- , m_grContext(m_provider->grContext())
-{
-}
-
-GraphicsContext3D::~GraphicsContext3D()
-{
- setContextLostCallback(nullptr);
- setErrorMessageCallback(nullptr);
-
- if (m_ownedGrContext) {
- m_ownedWebContext->setMemoryAllocationChangedCallbackCHROMIUM(0);
- m_ownedGrContext->contextDestroyed();
- }
-}
-
-// Macros to assist in delegating from GraphicsContext3D to
-// WebGraphicsContext3D.
-
-#define DELEGATE_TO_WEBCONTEXT(name) \
-void GraphicsContext3D::name() \
-{ \
- m_impl->name(); \
-}
-
-#define DELEGATE_TO_WEBCONTEXT_R(name, rt) \
-rt GraphicsContext3D::name() \
-{ \
- return m_impl->name(); \
-}
-
-#define DELEGATE_TO_WEBCONTEXT_1(name, t1) \
-void GraphicsContext3D::name(t1 a1) \
-{ \
- m_impl->name(a1); \
-}
-
-#define DELEGATE_TO_WEBCONTEXT_1R(name, t1, rt) \
-rt GraphicsContext3D::name(t1 a1) \
-{ \
- return m_impl->name(a1); \
-}
-
-#define DELEGATE_TO_WEBCONTEXT_2(name, t1, t2) \
-void GraphicsContext3D::name(t1 a1, t2 a2) \
-{ \
- m_impl->name(a1, a2); \
-}
-
-#define DELEGATE_TO_WEBCONTEXT_2R(name, t1, t2, rt) \
-rt GraphicsContext3D::name(t1 a1, t2 a2) \
-{ \
- return m_impl->name(a1, a2); \
-}
-
-#define DELEGATE_TO_WEBCONTEXT_3(name, t1, t2, t3) \
-void GraphicsContext3D::name(t1 a1, t2 a2, t3 a3) \
-{ \
- m_impl->name(a1, a2, a3); \
-}
-
-#define DELEGATE_TO_WEBCONTEXT_3R(name, t1, t2, t3, rt) \
-rt GraphicsContext3D::name(t1 a1, t2 a2, t3 a3) \
-{ \
- return m_impl->name(a1, a2, a3); \
-}
-
-#define DELEGATE_TO_WEBCONTEXT_4(name, t1, t2, t3, t4) \
-void GraphicsContext3D::name(t1 a1, t2 a2, t3 a3, t4 a4) \
-{ \
- m_impl->name(a1, a2, a3, a4); \
-}
-
-#define DELEGATE_TO_WEBCONTEXT_4R(name, t1, t2, t3, t4, rt) \
-rt GraphicsContext3D::name(t1 a1, t2 a2, t3 a3, t4 a4) \
-{ \
- return m_impl->name(a1, a2, a3, a4); \
-}
-
-#define DELEGATE_TO_WEBCONTEXT_5(name, t1, t2, t3, t4, t5) \
-void GraphicsContext3D::name(t1 a1, t2 a2, t3 a3, t4 a4, t5 a5) \
-{ \
- m_impl->name(a1, a2, a3, a4, a5); \
-}
-
-#define DELEGATE_TO_WEBCONTEXT_6(name, t1, t2, t3, t4, t5, t6) \
-void GraphicsContext3D::name(t1 a1, t2 a2, t3 a3, t4 a4, t5 a5, t6 a6) \
-{ \
- m_impl->name(a1, a2, a3, a4, a5, a6); \
-}
-
-#define DELEGATE_TO_WEBCONTEXT_6R(name, t1, t2, t3, t4, t5, t6, rt) \
-rt GraphicsContext3D::name(t1 a1, t2 a2, t3 a3, t4 a4, t5 a5, t6 a6) \
-{ \
- return m_impl->name(a1, a2, a3, a4, a5, a6); \
-}
-
-#define DELEGATE_TO_WEBCONTEXT_7(name, t1, t2, t3, t4, t5, t6, t7) \
-void GraphicsContext3D::name(t1 a1, t2 a2, t3 a3, t4 a4, t5 a5, t6 a6, t7 a7) \
-{ \
- m_impl->name(a1, a2, a3, a4, a5, a6, a7); \
-}
-
-#define DELEGATE_TO_WEBCONTEXT_7R(name, t1, t2, t3, t4, t5, t6, t7, rt) \
-rt GraphicsContext3D::name(t1 a1, t2 a2, t3 a3, t4 a4, t5 a5, t6 a6, t7 a7) \
-{ \
- return m_impl->name(a1, a2, a3, a4, a5, a6, a7); \
-}
-
-#define DELEGATE_TO_WEBCONTEXT_8(name, t1, t2, t3, t4, t5, t6, t7, t8) \
-void GraphicsContext3D::name(t1 a1, t2 a2, t3 a3, t4 a4, t5 a5, t6 a6, t7 a7, t8 a8) \
-{ \
- m_impl->name(a1, a2, a3, a4, a5, a6, a7, a8); \
-}
-
-#define DELEGATE_TO_WEBCONTEXT_9(name, t1, t2, t3, t4, t5, t6, t7, t8, t9) \
-void GraphicsContext3D::name(t1 a1, t2 a2, t3 a3, t4 a4, t5 a5, t6 a6, t7 a7, t8 a8, t9 a9) \
-{ \
- m_impl->name(a1, a2, a3, a4, a5, a6, a7, a8, a9); \
-}
-
-#define DELEGATE_TO_WEBCONTEXT_9R(name, t1, t2, t3, t4, t5, t6, t7, t8, t9, rt) \
-rt GraphicsContext3D::name(t1 a1, t2 a2, t3 a3, t4 a4, t5 a5, t6 a6, t7 a7, t8 a8, t9 a9) \
-{ \
- return m_impl->name(a1, a2, a3, a4, a5, a6, a7, a8, a9); \
-}
-
-class GraphicsContext3DContextLostCallbackAdapter : public WebKit::WebGraphicsContext3D::WebGraphicsContextLostCallback {
-public:
- GraphicsContext3DContextLostCallbackAdapter(PassOwnPtr<GraphicsContext3D::ContextLostCallback> callback)
- : m_contextLostCallback(callback) { }
- virtual ~GraphicsContext3DContextLostCallbackAdapter() { }
-
- virtual void onContextLost()
- {
- if (m_contextLostCallback)
- m_contextLostCallback->onContextLost();
- }
-private:
- OwnPtr<GraphicsContext3D::ContextLostCallback> m_contextLostCallback;
-};
-
-class GraphicsContext3DErrorMessageCallbackAdapter : public WebKit::WebGraphicsContext3D::WebGraphicsErrorMessageCallback {
-public:
- GraphicsContext3DErrorMessageCallbackAdapter(PassOwnPtr<GraphicsContext3D::ErrorMessageCallback> callback)
- : m_errorMessageCallback(callback) { }
- virtual ~GraphicsContext3DErrorMessageCallbackAdapter() { }
-
- virtual void onErrorMessage(const WebKit::WebString& message, WebKit::WGC3Dint id)
- {
- if (m_errorMessageCallback)
- m_errorMessageCallback->onErrorMessage(message, id);
- }
-private:
- OwnPtr<GraphicsContext3D::ErrorMessageCallback> m_errorMessageCallback;
-};
-
-void GraphicsContext3D::setContextLostCallback(PassOwnPtr<GraphicsContext3D::ContextLostCallback> callback)
-{
- if (m_ownedWebContext) {
- m_contextLostCallbackAdapter = adoptPtr(new GraphicsContext3DContextLostCallbackAdapter(callback));
- m_ownedWebContext->setContextLostCallback(m_contextLostCallbackAdapter.get());
- }
-}
-
-void GraphicsContext3D::setErrorMessageCallback(PassOwnPtr<GraphicsContext3D::ErrorMessageCallback> callback)
-{
- if (m_ownedWebContext) {
- m_errorMessageCallbackAdapter = adoptPtr(new GraphicsContext3DErrorMessageCallbackAdapter(callback));
- m_ownedWebContext->setErrorMessageCallback(m_errorMessageCallbackAdapter.get());
- }
-}
-
-PassRefPtr<GraphicsContext3D> GraphicsContext3D::create(GraphicsContext3D::Attributes attrs)
-{
- WebKit::WebGraphicsContext3D::Attributes webAttributes;
- webAttributes.alpha = attrs.alpha;
- webAttributes.depth = attrs.depth;
- webAttributes.stencil = attrs.stencil;
- webAttributes.antialias = attrs.antialias;
- webAttributes.premultipliedAlpha = attrs.premultipliedAlpha;
- webAttributes.noExtensions = attrs.noExtensions;
- webAttributes.shareResources = attrs.shareResources;
- webAttributes.preferDiscreteGPU = attrs.preferDiscreteGPU;
- webAttributes.topDocumentURL = attrs.topDocumentURL.string();
-
- OwnPtr<WebKit::WebGraphicsContext3D> webContext = adoptPtr(WebKit::Platform::current()->createOffscreenGraphicsContext3D(webAttributes));
- if (!webContext)
- return 0;
-
- return GraphicsContext3D::createGraphicsContextFromWebContext(webContext.release(), attrs.preserveDrawingBuffer);
-}
-
-PassRefPtr<GraphicsContext3D> GraphicsContext3D::createGraphicsContextFromProvider(PassOwnPtr<WebKit::WebGraphicsContext3DProvider> provider, bool preserveDrawingBuffer)
-{
- RefPtr<GraphicsContext3D> context = adoptRef(new GraphicsContext3D(provider, preserveDrawingBuffer));
- return context.release();
-}
-
-PassRefPtr<GraphicsContext3D> GraphicsContext3D::createGraphicsContextFromWebContext(PassOwnPtr<WebKit::WebGraphicsContext3D> webContext, bool preserveDrawingBuffer)
-{
- RefPtr<GraphicsContext3D> context = adoptRef(new GraphicsContext3D(webContext, preserveDrawingBuffer));
- return context.release();
-}
-
-class GrMemoryAllocationChangedCallbackAdapter : public WebKit::WebGraphicsContext3D::WebGraphicsMemoryAllocationChangedCallbackCHROMIUM {
-public:
- GrMemoryAllocationChangedCallbackAdapter(GrContext* context)
- : m_context(context)
- {
- }
-
- virtual void onMemoryAllocationChanged(WebKit::WebGraphicsMemoryAllocation allocation) OVERRIDE
- {
- if (!m_context)
- return;
-
- if (!allocation.gpuResourceSizeInBytes) {
- m_context->freeGpuResources();
- m_context->setTextureCacheLimits(0, 0);
- } else
- m_context->setTextureCacheLimits(maxGaneshTextureCacheCount, maxGaneshTextureCacheBytes);
- }
-
-private:
- GrContext* m_context;
-};
-
-namespace {
-void bindWebGraphicsContext3DGLContextCallback(const GrGLInterface* interface)
-{
- reinterpret_cast<WebKit::WebGraphicsContext3D*>(interface->fCallbackData)->makeContextCurrent();
-}
-}
-
-GrContext* GraphicsContext3D::grContext()
-{
- if (m_grContext)
- return m_grContext;
- if (!m_ownedWebContext)
- return 0;
-
- SkAutoTUnref<GrGLInterface> interface(m_ownedWebContext->createGrGLInterface());
- if (!interface)
- return 0;
-
- interface->fCallback = bindWebGraphicsContext3DGLContextCallback;
- interface->fCallbackData = reinterpret_cast<GrGLInterfaceCallbackData>(m_ownedWebContext.get());
-
- m_ownedGrContext.reset(GrContext::Create(kOpenGL_GrBackend, reinterpret_cast<GrBackendContext>(interface.get())));
- m_grContext = m_ownedGrContext;
- if (!m_grContext)
- return 0;
-
- m_grContext->setTextureCacheLimits(maxGaneshTextureCacheCount, maxGaneshTextureCacheBytes);
- m_grContextMemoryAllocationCallbackAdapter = adoptPtr(new GrMemoryAllocationChangedCallbackAdapter(m_grContext));
- m_ownedWebContext->setMemoryAllocationChangedCallbackCHROMIUM(m_grContextMemoryAllocationCallbackAdapter.get());
-
- return m_grContext;
-}
-
-DELEGATE_TO_WEBCONTEXT_R(makeContextCurrent, bool)
-DELEGATE_TO_WEBCONTEXT_R(lastFlushID, uint32_t)
-
-DELEGATE_TO_WEBCONTEXT_1(activeTexture, GC3Denum)
-DELEGATE_TO_WEBCONTEXT_2(attachShader, Platform3DObject, Platform3DObject)
-
-void GraphicsContext3D::bindAttribLocation(Platform3DObject program, GC3Duint index, const String& name)
-{
- m_impl->bindAttribLocation(program, index, name.utf8().data());
-}
-
-DELEGATE_TO_WEBCONTEXT_2(bindBuffer, GC3Denum, Platform3DObject)
-DELEGATE_TO_WEBCONTEXT_2(bindFramebuffer, GC3Denum, Platform3DObject)
-DELEGATE_TO_WEBCONTEXT_2(bindRenderbuffer, GC3Denum, Platform3DObject)
-DELEGATE_TO_WEBCONTEXT_2(bindTexture, GC3Denum, Platform3DObject)
-DELEGATE_TO_WEBCONTEXT_4(blendColor, GC3Dclampf, GC3Dclampf, GC3Dclampf, GC3Dclampf)
-DELEGATE_TO_WEBCONTEXT_1(blendEquation, GC3Denum)
-DELEGATE_TO_WEBCONTEXT_2(blendEquationSeparate, GC3Denum, GC3Denum)
-DELEGATE_TO_WEBCONTEXT_2(blendFunc, GC3Denum, GC3Denum)
-DELEGATE_TO_WEBCONTEXT_4(blendFuncSeparate, GC3Denum, GC3Denum, GC3Denum, GC3Denum)
-
-void GraphicsContext3D::bufferData(GC3Denum target, GC3Dsizeiptr size, GC3Denum usage)
-{
- bufferData(target, size, 0, usage);
-}
-
-DELEGATE_TO_WEBCONTEXT_4(bufferData, GC3Denum, GC3Dsizeiptr, const void*, GC3Denum)
-DELEGATE_TO_WEBCONTEXT_4(bufferSubData, GC3Denum, GC3Dintptr, GC3Dsizeiptr, const void*)
-
-DELEGATE_TO_WEBCONTEXT_1R(checkFramebufferStatus, GC3Denum, GC3Denum)
-DELEGATE_TO_WEBCONTEXT_1(clear, GC3Dbitfield)
-DELEGATE_TO_WEBCONTEXT_4(clearColor, GC3Dclampf, GC3Dclampf, GC3Dclampf, GC3Dclampf)
-DELEGATE_TO_WEBCONTEXT_1(clearDepth, GC3Dclampf)
-DELEGATE_TO_WEBCONTEXT_1(clearStencil, GC3Dint)
-DELEGATE_TO_WEBCONTEXT_4(colorMask, GC3Dboolean, GC3Dboolean, GC3Dboolean, GC3Dboolean)
-DELEGATE_TO_WEBCONTEXT_1(compileShader, Platform3DObject)
-
-DELEGATE_TO_WEBCONTEXT_8(compressedTexImage2D, GC3Denum, GC3Dint, GC3Denum, GC3Dint, GC3Dint, GC3Dsizei, GC3Dsizei, const void*)
-DELEGATE_TO_WEBCONTEXT_9(compressedTexSubImage2D, GC3Denum, GC3Dint, GC3Dint, GC3Dint, GC3Dint, GC3Dint, GC3Denum, GC3Dsizei, const void*)
-DELEGATE_TO_WEBCONTEXT_8(copyTexImage2D, GC3Denum, GC3Dint, GC3Denum, GC3Dint, GC3Dint, GC3Dsizei, GC3Dsizei, GC3Dint)
-DELEGATE_TO_WEBCONTEXT_8(copyTexSubImage2D, GC3Denum, GC3Dint, GC3Dint, GC3Dint, GC3Dint, GC3Dint, GC3Dsizei, GC3Dsizei)
-DELEGATE_TO_WEBCONTEXT_1(cullFace, GC3Denum)
-DELEGATE_TO_WEBCONTEXT_1(depthFunc, GC3Denum)
-DELEGATE_TO_WEBCONTEXT_1(depthMask, GC3Dboolean)
-DELEGATE_TO_WEBCONTEXT_2(depthRange, GC3Dclampf, GC3Dclampf)
-DELEGATE_TO_WEBCONTEXT_2(detachShader, Platform3DObject, Platform3DObject)
-DELEGATE_TO_WEBCONTEXT_1(disable, GC3Denum)
-DELEGATE_TO_WEBCONTEXT_1(disableVertexAttribArray, GC3Duint)
-DELEGATE_TO_WEBCONTEXT_3(drawArrays, GC3Denum, GC3Dint, GC3Dsizei)
-DELEGATE_TO_WEBCONTEXT_4(drawElements, GC3Denum, GC3Dsizei, GC3Denum, GC3Dintptr)
-
-DELEGATE_TO_WEBCONTEXT_1(enable, GC3Denum)
-DELEGATE_TO_WEBCONTEXT_1(enableVertexAttribArray, GC3Duint)
-DELEGATE_TO_WEBCONTEXT(finish)
-DELEGATE_TO_WEBCONTEXT(flush)
-DELEGATE_TO_WEBCONTEXT_4(framebufferRenderbuffer, GC3Denum, GC3Denum, GC3Denum, Platform3DObject)
-DELEGATE_TO_WEBCONTEXT_5(framebufferTexture2D, GC3Denum, GC3Denum, GC3Denum, Platform3DObject, GC3Dint)
-DELEGATE_TO_WEBCONTEXT_1(frontFace, GC3Denum)
-DELEGATE_TO_WEBCONTEXT_1(generateMipmap, GC3Denum)
-
-bool GraphicsContext3D::getActiveAttrib(Platform3DObject program, GC3Duint index, ActiveInfo& info)
-{
- WebKit::WebGraphicsContext3D::ActiveInfo webInfo;
- if (!m_impl->getActiveAttrib(program, index, webInfo))
- return false;
- info.name = webInfo.name;
- info.type = webInfo.type;
- info.size = webInfo.size;
- return true;
-}
-
-bool GraphicsContext3D::getActiveUniform(Platform3DObject program, GC3Duint index, ActiveInfo& info)
-{
- WebKit::WebGraphicsContext3D::ActiveInfo webInfo;
- if (!m_impl->getActiveUniform(program, index, webInfo))
- return false;
- info.name = webInfo.name;
- info.type = webInfo.type;
- info.size = webInfo.size;
- return true;
-}
-
-DELEGATE_TO_WEBCONTEXT_4(getAttachedShaders, Platform3DObject, GC3Dsizei, GC3Dsizei*, Platform3DObject*)
-
-GC3Dint GraphicsContext3D::getAttribLocation(Platform3DObject program, const String& name)
-{
- return m_impl->getAttribLocation(program, name.utf8().data());
-}
-
-DELEGATE_TO_WEBCONTEXT_2(getBooleanv, GC3Denum, GC3Dboolean*)
-DELEGATE_TO_WEBCONTEXT_3(getBufferParameteriv, GC3Denum, GC3Denum, GC3Dint*)
-
-GraphicsContext3D::Attributes GraphicsContext3D::getContextAttributes()
-{
- WebKit::WebGraphicsContext3D::Attributes webAttributes = m_impl->getContextAttributes();
- GraphicsContext3D::Attributes attributes;
- attributes.alpha = webAttributes.alpha;
- attributes.depth = webAttributes.depth;
- attributes.stencil = webAttributes.stencil;
- attributes.antialias = webAttributes.antialias;
- attributes.premultipliedAlpha = webAttributes.premultipliedAlpha;
- attributes.preserveDrawingBuffer = m_preserveDrawingBuffer;
- attributes.preferDiscreteGPU = webAttributes.preferDiscreteGPU;
- return attributes;
-}
-
-DELEGATE_TO_WEBCONTEXT_R(getError, GC3Denum)
-DELEGATE_TO_WEBCONTEXT_2(getFloatv, GC3Denum, GC3Dfloat*)
-DELEGATE_TO_WEBCONTEXT_4(getFramebufferAttachmentParameteriv, GC3Denum, GC3Denum, GC3Denum, GC3Dint*)
-DELEGATE_TO_WEBCONTEXT_2(getIntegerv, GC3Denum, GC3Dint*)
-DELEGATE_TO_WEBCONTEXT_3(getProgramiv, Platform3DObject, GC3Denum, GC3Dint*)
-DELEGATE_TO_WEBCONTEXT_1R(getProgramInfoLog, Platform3DObject, String)
-DELEGATE_TO_WEBCONTEXT_3(getRenderbufferParameteriv, GC3Denum, GC3Denum, GC3Dint*)
-DELEGATE_TO_WEBCONTEXT_3(getShaderiv, Platform3DObject, GC3Denum, GC3Dint*)
-DELEGATE_TO_WEBCONTEXT_1R(getShaderInfoLog, Platform3DObject, String)
-DELEGATE_TO_WEBCONTEXT_4(getShaderPrecisionFormat, GC3Denum, GC3Denum, GC3Dint*, GC3Dint*)
-DELEGATE_TO_WEBCONTEXT_1R(getShaderSource, Platform3DObject, String)
-DELEGATE_TO_WEBCONTEXT_1R(getString, GC3Denum, String)
-DELEGATE_TO_WEBCONTEXT_3(getTexParameterfv, GC3Denum, GC3Denum, GC3Dfloat*)
-DELEGATE_TO_WEBCONTEXT_3(getTexParameteriv, GC3Denum, GC3Denum, GC3Dint*)
-DELEGATE_TO_WEBCONTEXT_3(getUniformfv, Platform3DObject, GC3Dint, GC3Dfloat*)
-DELEGATE_TO_WEBCONTEXT_3(getUniformiv, Platform3DObject, GC3Dint, GC3Dint*)
-
-GC3Dint GraphicsContext3D::getUniformLocation(Platform3DObject program, const String& name)
-{
- return m_impl->getUniformLocation(program, name.utf8().data());
-}
-
-DELEGATE_TO_WEBCONTEXT_3(getVertexAttribfv, GC3Duint, GC3Denum, GC3Dfloat*)
-DELEGATE_TO_WEBCONTEXT_3(getVertexAttribiv, GC3Duint, GC3Denum, GC3Dint*)
-DELEGATE_TO_WEBCONTEXT_2R(getVertexAttribOffset, GC3Duint, GC3Denum, GC3Dsizeiptr)
-
-DELEGATE_TO_WEBCONTEXT_2(hint, GC3Denum, GC3Denum)
-DELEGATE_TO_WEBCONTEXT_1R(isBuffer, Platform3DObject, GC3Dboolean)
-DELEGATE_TO_WEBCONTEXT_1R(isEnabled, GC3Denum, GC3Dboolean)
-DELEGATE_TO_WEBCONTEXT_1R(isFramebuffer, Platform3DObject, GC3Dboolean)
-DELEGATE_TO_WEBCONTEXT_1R(isProgram, Platform3DObject, GC3Dboolean)
-DELEGATE_TO_WEBCONTEXT_1R(isRenderbuffer, Platform3DObject, GC3Dboolean)
-DELEGATE_TO_WEBCONTEXT_1R(isShader, Platform3DObject, GC3Dboolean)
-DELEGATE_TO_WEBCONTEXT_1R(isTexture, Platform3DObject, GC3Dboolean)
-DELEGATE_TO_WEBCONTEXT_1(lineWidth, GC3Dfloat)
-DELEGATE_TO_WEBCONTEXT_1(linkProgram, Platform3DObject)
-
-void GraphicsContext3D::pixelStorei(GC3Denum pname, GC3Dint param)
-{
- if (pname == PACK_ALIGNMENT)
- m_packAlignment = param;
- m_impl->pixelStorei(pname, param);
-}
-
-DELEGATE_TO_WEBCONTEXT_2(polygonOffset, GC3Dfloat, GC3Dfloat)
-
-DELEGATE_TO_WEBCONTEXT_7(readPixels, GC3Dint, GC3Dint, GC3Dsizei, GC3Dsizei, GC3Denum, GC3Denum, void*)
-
-DELEGATE_TO_WEBCONTEXT(releaseShaderCompiler)
-DELEGATE_TO_WEBCONTEXT_4(renderbufferStorage, GC3Denum, GC3Denum, GC3Dsizei, GC3Dsizei)
-DELEGATE_TO_WEBCONTEXT_2(sampleCoverage, GC3Dclampf, GC3Dboolean)
-DELEGATE_TO_WEBCONTEXT_4(scissor, GC3Dint, GC3Dint, GC3Dsizei, GC3Dsizei)
-
-void GraphicsContext3D::shaderSource(Platform3DObject shader, const String& string)
-{
- m_impl->shaderSource(shader, string.utf8().data());
-}
-
-DELEGATE_TO_WEBCONTEXT_3(stencilFunc, GC3Denum, GC3Dint, GC3Duint)
-DELEGATE_TO_WEBCONTEXT_4(stencilFuncSeparate, GC3Denum, GC3Denum, GC3Dint, GC3Duint)
-DELEGATE_TO_WEBCONTEXT_1(stencilMask, GC3Duint)
-DELEGATE_TO_WEBCONTEXT_2(stencilMaskSeparate, GC3Denum, GC3Duint)
-DELEGATE_TO_WEBCONTEXT_3(stencilOp, GC3Denum, GC3Denum, GC3Denum)
-DELEGATE_TO_WEBCONTEXT_4(stencilOpSeparate, GC3Denum, GC3Denum, GC3Denum, GC3Denum)
-
-DELEGATE_TO_WEBCONTEXT_9(texImage2D, GC3Denum, GC3Dint, GC3Denum, GC3Dsizei, GC3Dsizei, GC3Dint, GC3Denum, GC3Denum, const void*)
-DELEGATE_TO_WEBCONTEXT_3(texParameterf, GC3Denum, GC3Denum, GC3Dfloat)
-DELEGATE_TO_WEBCONTEXT_3(texParameteri, GC3Denum, GC3Denum, GC3Dint)
-DELEGATE_TO_WEBCONTEXT_9(texSubImage2D, GC3Denum, GC3Dint, GC3Dint, GC3Dint, GC3Dsizei, GC3Dsizei, GC3Denum, GC3Denum, const void*)
-
-DELEGATE_TO_WEBCONTEXT_2(uniform1f, GC3Dint, GC3Dfloat)
-DELEGATE_TO_WEBCONTEXT_3(uniform1fv, GC3Dint, GC3Dsizei, GC3Dfloat*)
-DELEGATE_TO_WEBCONTEXT_2(uniform1i, GC3Dint, GC3Dint)
-DELEGATE_TO_WEBCONTEXT_3(uniform1iv, GC3Dint, GC3Dsizei, GC3Dint*)
-DELEGATE_TO_WEBCONTEXT_3(uniform2f, GC3Dint, GC3Dfloat, GC3Dfloat)
-DELEGATE_TO_WEBCONTEXT_3(uniform2fv, GC3Dint, GC3Dsizei, GC3Dfloat*)
-DELEGATE_TO_WEBCONTEXT_3(uniform2i, GC3Dint, GC3Dint, GC3Dint)
-DELEGATE_TO_WEBCONTEXT_3(uniform2iv, GC3Dint, GC3Dsizei, GC3Dint*)
-DELEGATE_TO_WEBCONTEXT_4(uniform3f, GC3Dint, GC3Dfloat, GC3Dfloat, GC3Dfloat)
-DELEGATE_TO_WEBCONTEXT_3(uniform3fv, GC3Dint, GC3Dsizei, GC3Dfloat*)
-DELEGATE_TO_WEBCONTEXT_4(uniform3i, GC3Dint, GC3Dint, GC3Dint, GC3Dint)
-DELEGATE_TO_WEBCONTEXT_3(uniform3iv, GC3Dint, GC3Dsizei, GC3Dint*)
-DELEGATE_TO_WEBCONTEXT_5(uniform4f, GC3Dint, GC3Dfloat, GC3Dfloat, GC3Dfloat, GC3Dfloat)
-DELEGATE_TO_WEBCONTEXT_3(uniform4fv, GC3Dint, GC3Dsizei, GC3Dfloat*)
-DELEGATE_TO_WEBCONTEXT_5(uniform4i, GC3Dint, GC3Dint, GC3Dint, GC3Dint, GC3Dint)
-DELEGATE_TO_WEBCONTEXT_3(uniform4iv, GC3Dint, GC3Dsizei, GC3Dint*)
-DELEGATE_TO_WEBCONTEXT_4(uniformMatrix2fv, GC3Dint, GC3Dsizei, GC3Dboolean, GC3Dfloat*)
-DELEGATE_TO_WEBCONTEXT_4(uniformMatrix3fv, GC3Dint, GC3Dsizei, GC3Dboolean, GC3Dfloat*)
-DELEGATE_TO_WEBCONTEXT_4(uniformMatrix4fv, GC3Dint, GC3Dsizei, GC3Dboolean, GC3Dfloat*)
-
-DELEGATE_TO_WEBCONTEXT_1(useProgram, Platform3DObject)
-DELEGATE_TO_WEBCONTEXT_1(validateProgram, Platform3DObject)
-
-DELEGATE_TO_WEBCONTEXT_2(vertexAttrib1f, GC3Duint, GC3Dfloat)
-DELEGATE_TO_WEBCONTEXT_2(vertexAttrib1fv, GC3Duint, GC3Dfloat*)
-DELEGATE_TO_WEBCONTEXT_3(vertexAttrib2f, GC3Duint, GC3Dfloat, GC3Dfloat)
-DELEGATE_TO_WEBCONTEXT_2(vertexAttrib2fv, GC3Duint, GC3Dfloat*)
-DELEGATE_TO_WEBCONTEXT_4(vertexAttrib3f, GC3Duint, GC3Dfloat, GC3Dfloat, GC3Dfloat)
-DELEGATE_TO_WEBCONTEXT_2(vertexAttrib3fv, GC3Duint, GC3Dfloat*)
-DELEGATE_TO_WEBCONTEXT_5(vertexAttrib4f, GC3Duint, GC3Dfloat, GC3Dfloat, GC3Dfloat, GC3Dfloat)
-DELEGATE_TO_WEBCONTEXT_2(vertexAttrib4fv, GC3Duint, GC3Dfloat*)
-DELEGATE_TO_WEBCONTEXT_6(vertexAttribPointer, GC3Duint, GC3Dint, GC3Denum, GC3Dboolean, GC3Dsizei, GC3Dintptr)
-
-DELEGATE_TO_WEBCONTEXT_4(viewport, GC3Dint, GC3Dint, GC3Dsizei, GC3Dsizei)
-
-void GraphicsContext3D::reshape(int width, int height)
-{
- if (width == m_impl->width() && height == m_impl->height())
- return;
-
- m_impl->reshape(width, height);
-}
-
-void GraphicsContext3D::markContextChanged()
-{
- m_layerComposited = false;
-}
-
-bool GraphicsContext3D::layerComposited() const
-{
- return m_layerComposited;
-}
-
-void GraphicsContext3D::markLayerComposited()
-{
- m_layerComposited = true;
-}
-
-void GraphicsContext3D::paintRenderingResultsToCanvas(ImageBuffer* imageBuffer, DrawingBuffer* drawingBuffer)
-{
- Platform3DObject framebufferId;
- int width, height;
- getDrawingParameters(drawingBuffer, m_impl, &framebufferId, &width, &height);
- paintFramebufferToCanvas(framebufferId, width, height, !getContextAttributes().premultipliedAlpha, imageBuffer);
-}
-
-PassRefPtr<ImageData> GraphicsContext3D::paintRenderingResultsToImageData(DrawingBuffer* drawingBuffer)
-{
- if (getContextAttributes().premultipliedAlpha)
- return 0;
-
- Platform3DObject framebufferId;
- int width, height;
- getDrawingParameters(drawingBuffer, m_impl, &framebufferId, &width, &height);
-
- RefPtr<ImageData> imageData = ImageData::create(IntSize(width, height));
- unsigned char* pixels = imageData->data()->data();
-
- m_impl->bindFramebuffer(FRAMEBUFFER, framebufferId);
- readBackFramebuffer(pixels, width, height, ReadbackRGBA, AlphaDoNothing);
- flipVertically(pixels, width, height);
-
- return imageData.release();
-}
-
-void GraphicsContext3D::readBackFramebuffer(unsigned char* pixels, int width, int height, ReadbackOrder readbackOrder, AlphaOp op)
-{
- if (m_packAlignment > 4)
- m_impl->pixelStorei(PACK_ALIGNMENT, 1);
- m_impl->readPixels(0, 0, width, height, RGBA, UNSIGNED_BYTE, pixels);
- if (m_packAlignment > 4)
- m_impl->pixelStorei(PACK_ALIGNMENT, m_packAlignment);
-
- size_t bufferSize = 4 * width * height;
-
- if (readbackOrder == ReadbackSkia) {
-#if (SK_R32_SHIFT == 16) && !SK_B32_SHIFT
- // Swizzle red and blue channels to match SkBitmap's byte ordering.
- // TODO(kbr): expose GL_BGRA as extension.
- for (size_t i = 0; i < bufferSize; i += 4) {
- std::swap(pixels[i], pixels[i + 2]);
- }
-#endif
- }
-
- if (op == AlphaDoPremultiply) {
- for (size_t i = 0; i < bufferSize; i += 4) {
- pixels[i + 0] = std::min(255, pixels[i + 0] * pixels[i + 3] / 255);
- pixels[i + 1] = std::min(255, pixels[i + 1] * pixels[i + 3] / 255);
- pixels[i + 2] = std::min(255, pixels[i + 2] * pixels[i + 3] / 255);
- }
- } else if (op != AlphaDoNothing) {
- ASSERT_NOT_REACHED();
- }
-}
-
-DELEGATE_TO_WEBCONTEXT_R(createBuffer, Platform3DObject)
-DELEGATE_TO_WEBCONTEXT_R(createFramebuffer, Platform3DObject)
-DELEGATE_TO_WEBCONTEXT_R(createProgram, Platform3DObject)
-DELEGATE_TO_WEBCONTEXT_R(createRenderbuffer, Platform3DObject)
-DELEGATE_TO_WEBCONTEXT_1R(createShader, GC3Denum, Platform3DObject)
-DELEGATE_TO_WEBCONTEXT_R(createTexture, Platform3DObject)
-
-DELEGATE_TO_WEBCONTEXT_1(deleteBuffer, Platform3DObject)
-DELEGATE_TO_WEBCONTEXT_1(deleteFramebuffer, Platform3DObject)
-DELEGATE_TO_WEBCONTEXT_1(deleteProgram, Platform3DObject)
-DELEGATE_TO_WEBCONTEXT_1(deleteRenderbuffer, Platform3DObject)
-DELEGATE_TO_WEBCONTEXT_1(deleteShader, Platform3DObject)
-DELEGATE_TO_WEBCONTEXT_1(deleteTexture, Platform3DObject)
-
-DELEGATE_TO_WEBCONTEXT_1(synthesizeGLError, GC3Denum)
-
-Extensions3D* GraphicsContext3D::extensions()
-{
- if (!m_extensions)
- m_extensions = adoptPtr(new Extensions3D(this));
- return m_extensions.get();
-}
-
-bool GraphicsContext3D::texImage2DResourceSafe(GC3Denum target, GC3Dint level, GC3Denum internalformat, GC3Dsizei width, GC3Dsizei height, GC3Dint border, GC3Denum format, GC3Denum type, GC3Dint unpackAlignment)
-{
- ASSERT(unpackAlignment == 1 || unpackAlignment == 2 || unpackAlignment == 4 || unpackAlignment == 8);
- texImage2D(target, level, internalformat, width, height, border, format, type, 0);
- return true;
-}
-
-bool GraphicsContext3D::computeFormatAndTypeParameters(GC3Denum format,
- GC3Denum type,
- unsigned int* componentsPerPixel,
- unsigned int* bytesPerComponent)
-{
- switch (format) {
- case GraphicsContext3D::ALPHA:
- case GraphicsContext3D::LUMINANCE:
- case GraphicsContext3D::DEPTH_COMPONENT:
- case GraphicsContext3D::DEPTH_STENCIL:
- *componentsPerPixel = 1;
- break;
- case GraphicsContext3D::LUMINANCE_ALPHA:
- *componentsPerPixel = 2;
- break;
- case GraphicsContext3D::RGB:
- *componentsPerPixel = 3;
- break;
- case GraphicsContext3D::RGBA:
- case Extensions3D::BGRA_EXT: // GL_EXT_texture_format_BGRA8888
- *componentsPerPixel = 4;
- break;
- default:
- return false;
- }
- switch (type) {
- case GraphicsContext3D::UNSIGNED_BYTE:
- *bytesPerComponent = sizeof(GC3Dubyte);
- break;
- case GraphicsContext3D::UNSIGNED_SHORT:
- *bytesPerComponent = sizeof(GC3Dushort);
- break;
- case GraphicsContext3D::UNSIGNED_SHORT_5_6_5:
- case GraphicsContext3D::UNSIGNED_SHORT_4_4_4_4:
- case GraphicsContext3D::UNSIGNED_SHORT_5_5_5_1:
- *componentsPerPixel = 1;
- *bytesPerComponent = sizeof(GC3Dushort);
- break;
- case GraphicsContext3D::UNSIGNED_INT_24_8:
- case GraphicsContext3D::UNSIGNED_INT:
- *bytesPerComponent = sizeof(GC3Duint);
- break;
- case GraphicsContext3D::FLOAT: // OES_texture_float
- *bytesPerComponent = sizeof(GC3Dfloat);
- break;
- case GraphicsContext3D::HALF_FLOAT_OES: // OES_texture_half_float
- *bytesPerComponent = sizeof(GC3Dhalffloat);
- break;
- default:
- return false;
- }
- return true;
-}
-
-GC3Denum GraphicsContext3D::computeImageSizeInBytes(GC3Denum format, GC3Denum type, GC3Dsizei width, GC3Dsizei height, GC3Dint alignment,
- unsigned int* imageSizeInBytes, unsigned int* paddingInBytes)
-{
- ASSERT(imageSizeInBytes);
- ASSERT(alignment == 1 || alignment == 2 || alignment == 4 || alignment == 8);
- if (width < 0 || height < 0)
- return GraphicsContext3D::INVALID_VALUE;
- unsigned int bytesPerComponent, componentsPerPixel;
- if (!computeFormatAndTypeParameters(format, type, &bytesPerComponent, &componentsPerPixel))
- return GraphicsContext3D::INVALID_ENUM;
- if (!width || !height) {
- *imageSizeInBytes = 0;
- if (paddingInBytes)
- *paddingInBytes = 0;
- return GraphicsContext3D::NO_ERROR;
- }
- CheckedInt<uint32_t> checkedValue(bytesPerComponent * componentsPerPixel);
- checkedValue *= width;
- if (!checkedValue.isValid())
- return GraphicsContext3D::INVALID_VALUE;
- unsigned int validRowSize = checkedValue.value();
- unsigned int padding = 0;
- unsigned int residual = validRowSize % alignment;
- if (residual) {
- padding = alignment - residual;
- checkedValue += padding;
- }
- // Last row needs no padding.
- checkedValue *= (height - 1);
- checkedValue += validRowSize;
- if (!checkedValue.isValid())
- return GraphicsContext3D::INVALID_VALUE;
- *imageSizeInBytes = checkedValue.value();
- if (paddingInBytes)
- *paddingInBytes = padding;
- return GraphicsContext3D::NO_ERROR;
-}
-
-GraphicsContext3D::ImageExtractor::ImageExtractor(Image* image, ImageHtmlDomSource imageHtmlDomSource, bool premultiplyAlpha, bool ignoreGammaAndColorProfile)
-{
- m_image = image;
- m_imageHtmlDomSource = imageHtmlDomSource;
- m_extractSucceeded = extractImage(premultiplyAlpha, ignoreGammaAndColorProfile);
-}
-
-GraphicsContext3D::ImageExtractor::~ImageExtractor()
-{
- if (m_skiaImage)
- m_skiaImage->bitmap().unlockPixels();
-}
-
-bool GraphicsContext3D::ImageExtractor::extractImage(bool premultiplyAlpha, bool ignoreGammaAndColorProfile)
-{
- if (!m_image)
- return false;
- m_skiaImage = m_image->nativeImageForCurrentFrame();
- m_alphaOp = AlphaDoNothing;
- bool hasAlpha = m_skiaImage ? !m_skiaImage->bitmap().isOpaque() : true;
- if ((!m_skiaImage || ignoreGammaAndColorProfile || (hasAlpha && !premultiplyAlpha)) && m_image->data()) {
- // Attempt to get raw unpremultiplied image data.
- OwnPtr<ImageDecoder> decoder(ImageDecoder::create(
- *(m_image->data()), ImageSource::AlphaNotPremultiplied,
- ignoreGammaAndColorProfile ? ImageSource::GammaAndColorProfileIgnored : ImageSource::GammaAndColorProfileApplied));
- if (!decoder)
- return false;
- decoder->setData(m_image->data(), true);
- if (!decoder->frameCount())
- return false;
- ImageFrame* frame = decoder->frameBufferAtIndex(0);
- if (!frame || frame->status() != ImageFrame::FrameComplete)
- return false;
- hasAlpha = frame->hasAlpha();
- m_nativeImage = frame->asNewNativeImage();
- if (!m_nativeImage.get() || !m_nativeImage->isDataComplete() || !m_nativeImage->bitmap().width() || !m_nativeImage->bitmap().height())
- return false;
- SkBitmap::Config skiaConfig = m_nativeImage->bitmap().config();
- if (skiaConfig != SkBitmap::kARGB_8888_Config)
- return false;
- m_skiaImage = m_nativeImage.get();
- if (hasAlpha && premultiplyAlpha)
- m_alphaOp = AlphaDoPremultiply;
- } else if (!premultiplyAlpha && hasAlpha) {
- // 1. For texImage2D with HTMLVideoElment input, assume no PremultiplyAlpha had been applied and the alpha value for each pixel is 0xFF
- // which is true at present and may be changed in the future and needs adjustment accordingly.
- // 2. For texImage2D with HTMLCanvasElement input in which Alpha is already Premultiplied in this port,
- // do AlphaDoUnmultiply if UNPACK_PREMULTIPLY_ALPHA_WEBGL is set to false.
- if (m_imageHtmlDomSource != HtmlDomVideo)
- m_alphaOp = AlphaDoUnmultiply;
- }
- if (!m_skiaImage)
- return false;
-
- m_imageSourceFormat = SK_B32_SHIFT ? DataFormatRGBA8 : DataFormatBGRA8;
- m_imageWidth = m_skiaImage->bitmap().width();
- m_imageHeight = m_skiaImage->bitmap().height();
- if (!m_imageWidth || !m_imageHeight)
- return false;
- m_imageSourceUnpackAlignment = 0;
- m_skiaImage->bitmap().lockPixels();
- m_imagePixelData = m_skiaImage->bitmap().getPixels();
- return true;
-}
-
-unsigned GraphicsContext3D::getClearBitsByFormat(GC3Denum format)
-{
- switch (format) {
- case GraphicsContext3D::ALPHA:
- case GraphicsContext3D::LUMINANCE:
- case GraphicsContext3D::LUMINANCE_ALPHA:
- case GraphicsContext3D::RGB:
- case GraphicsContext3D::RGB565:
- case GraphicsContext3D::RGBA:
- case GraphicsContext3D::RGBA4:
- case GraphicsContext3D::RGB5_A1:
- return GraphicsContext3D::COLOR_BUFFER_BIT;
- case GraphicsContext3D::DEPTH_COMPONENT16:
- case GraphicsContext3D::DEPTH_COMPONENT:
- return GraphicsContext3D::DEPTH_BUFFER_BIT;
- case GraphicsContext3D::STENCIL_INDEX8:
- return GraphicsContext3D::STENCIL_BUFFER_BIT;
- case GraphicsContext3D::DEPTH_STENCIL:
- return GraphicsContext3D::DEPTH_BUFFER_BIT | GraphicsContext3D::STENCIL_BUFFER_BIT;
- default:
- return 0;
- }
-}
-
-unsigned GraphicsContext3D::getChannelBitsByFormat(GC3Denum format)
-{
- switch (format) {
- case GraphicsContext3D::ALPHA:
- return ChannelAlpha;
- case GraphicsContext3D::LUMINANCE:
- return ChannelRGB;
- case GraphicsContext3D::LUMINANCE_ALPHA:
- return ChannelRGBA;
- case GraphicsContext3D::RGB:
- case GraphicsContext3D::RGB565:
- return ChannelRGB;
- case GraphicsContext3D::RGBA:
- case GraphicsContext3D::RGBA4:
- case GraphicsContext3D::RGB5_A1:
- return ChannelRGBA;
- case GraphicsContext3D::DEPTH_COMPONENT16:
- case GraphicsContext3D::DEPTH_COMPONENT:
- return ChannelDepth;
- case GraphicsContext3D::STENCIL_INDEX8:
- return ChannelStencil;
- case GraphicsContext3D::DEPTH_STENCIL:
- return ChannelDepth | ChannelStencil;
- default:
- return 0;
- }
-}
-
-void GraphicsContext3D::paintFramebufferToCanvas(int framebuffer, int width, int height, bool premultiplyAlpha, ImageBuffer* imageBuffer)
-{
- unsigned char* pixels = 0;
-
- const SkBitmap* canvasBitmap = imageBuffer->context()->bitmap();
- const SkBitmap* readbackBitmap = 0;
- ASSERT(canvasBitmap->config() == SkBitmap::kARGB_8888_Config);
- if (canvasBitmap->width() == width && canvasBitmap->height() == height) {
- // This is the fastest and most common case. We read back
- // directly into the canvas's backing store.
- readbackBitmap = canvasBitmap;
- m_resizingBitmap.reset();
- } else {
- // We need to allocate a temporary bitmap for reading back the
- // pixel data. We will then use Skia to rescale this bitmap to
- // the size of the canvas's backing store.
- if (m_resizingBitmap.width() != width || m_resizingBitmap.height() != height) {
- m_resizingBitmap.setConfig(SkBitmap::kARGB_8888_Config, width, height);
- if (!m_resizingBitmap.allocPixels())
- return;
- }
- readbackBitmap = &m_resizingBitmap;
- }
-
- // Read back the frame buffer.
- SkAutoLockPixels bitmapLock(*readbackBitmap);
- pixels = static_cast<unsigned char*>(readbackBitmap->getPixels());
-
- m_impl->bindFramebuffer(FRAMEBUFFER, framebuffer);
- readBackFramebuffer(pixels, width, height, ReadbackSkia, premultiplyAlpha ? AlphaDoPremultiply : AlphaDoNothing);
- flipVertically(pixels, width, height);
-
- readbackBitmap->notifyPixelsChanged();
- if (m_resizingBitmap.readyToDraw()) {
- // We need to draw the resizing bitmap into the canvas's backing store.
- SkCanvas canvas(*canvasBitmap);
- SkRect dst;
- dst.set(SkIntToScalar(0), SkIntToScalar(0), SkIntToScalar(canvasBitmap->width()), SkIntToScalar(canvasBitmap->height()));
- canvas.drawBitmapRect(m_resizingBitmap, 0, dst);
- }
-}
-
-namespace {
-
-void splitStringHelper(const String& str, HashSet<String>& set)
-{
- Vector<String> substrings;
- str.split(" ", substrings);
- for (size_t i = 0; i < substrings.size(); ++i)
- set.add(substrings[i]);
-}
-
-String mapExtensionName(const String& name)
-{
- if (name == "GL_ANGLE_framebuffer_blit"
- || name == "GL_ANGLE_framebuffer_multisample")
- return "GL_CHROMIUM_framebuffer_multisample";
- return name;
-}
-
-} // anonymous namespace
-
-void GraphicsContext3D::initializeExtensions()
-{
- if (m_initializedAvailableExtensions)
- return;
-
- m_initializedAvailableExtensions = true;
- bool success = m_impl->makeContextCurrent();
- ASSERT(success);
- if (!success)
- return;
-
- String extensionsString = m_impl->getString(GraphicsContext3D::EXTENSIONS);
- splitStringHelper(extensionsString, m_enabledExtensions);
-
- String requestableExtensionsString = m_impl->getRequestableExtensionsCHROMIUM();
- splitStringHelper(requestableExtensionsString, m_requestableExtensions);
-}
-
-
-bool GraphicsContext3D::supportsExtension(const String& name)
-{
- initializeExtensions();
- String mappedName = mapExtensionName(name);
- return m_enabledExtensions.contains(mappedName) || m_requestableExtensions.contains(mappedName);
-}
-
-bool GraphicsContext3D::ensureExtensionEnabled(const String& name)
-{
- initializeExtensions();
-
- String mappedName = mapExtensionName(name);
- if (m_enabledExtensions.contains(mappedName))
- return true;
-
- if (m_requestableExtensions.contains(mappedName)) {
- m_impl->requestExtensionCHROMIUM(mappedName.ascii().data());
- m_enabledExtensions.clear();
- m_requestableExtensions.clear();
- m_initializedAvailableExtensions = false;
- }
-
- initializeExtensions();
- fprintf(stderr, "m_enabledExtensions.contains(%s) == %d\n", mappedName.ascii().data(), m_enabledExtensions.contains(mappedName));
- return m_enabledExtensions.contains(mappedName);
-}
-
-bool GraphicsContext3D::isExtensionEnabled(const String& name)
-{
- initializeExtensions();
- String mappedName = mapExtensionName(name);
- return m_enabledExtensions.contains(mappedName);
-}
-
-void GraphicsContext3D::flipVertically(uint8_t* framebuffer, int width, int height)
-{
- m_scanline.resize(width * 4);
- uint8* scanline = &m_scanline[0];
- unsigned rowBytes = width * 4;
- unsigned count = height / 2;
- for (unsigned i = 0; i < count; i++) {
- uint8* rowA = framebuffer + i * rowBytes;
- uint8* rowB = framebuffer + (height - i - 1) * rowBytes;
- memcpy(scanline, rowB, rowBytes);
- memcpy(rowB, rowA, rowBytes);
- memcpy(rowA, scanline, rowBytes);
- }
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsContext3D.h b/chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsContext3D.h
deleted file mode 100644
index 7e7fe4d8428..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsContext3D.h
+++ /dev/null
@@ -1,867 +0,0 @@
-/*
- * Copyright (C) 2009 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef GraphicsContext3D_h
-#define GraphicsContext3D_h
-
-#include "core/platform/graphics/Extensions3D.h"
-#include "core/platform/graphics/GraphicsTypes3D.h"
-#include "core/platform/graphics/Image.h"
-#include "core/platform/graphics/IntRect.h"
-#include "third_party/skia/include/core/SkBitmap.h"
-#include "weborigin/KURL.h"
-#include "wtf/HashMap.h"
-#include "wtf/HashSet.h"
-#include "wtf/ListHashSet.h"
-#include "wtf/Noncopyable.h"
-#include "wtf/OwnArrayPtr.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/PassOwnArrayPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/text/WTFString.h"
-
-// FIXME: Find a better way to avoid the name confliction for NO_ERROR.
-#if OS(WIN)
-#undef NO_ERROR
-#endif
-
-class GrContext;
-
-namespace WebKit {
-class WebGraphicsContext3D;
-class WebGraphicsContext3DProvider;
-}
-
-namespace WebCore {
-class DrawingBuffer;
-class Extensions3D;
-class GraphicsContext3DContextLostCallbackAdapter;
-class GraphicsContext3DErrorMessageCallbackAdapter;
-class GrMemoryAllocationChangedCallbackAdapter;
-class Image;
-class ImageBuffer;
-class ImageData;
-class IntRect;
-class IntSize;
-
-struct ActiveInfo {
- String name;
- GC3Denum type;
- GC3Dint size;
-};
-
-class GraphicsContext3D : public RefCounted<GraphicsContext3D> {
-public:
- enum {
- DEPTH_BUFFER_BIT = 0x00000100,
- STENCIL_BUFFER_BIT = 0x00000400,
- COLOR_BUFFER_BIT = 0x00004000,
- POINTS = 0x0000,
- LINES = 0x0001,
- LINE_LOOP = 0x0002,
- LINE_STRIP = 0x0003,
- TRIANGLES = 0x0004,
- TRIANGLE_STRIP = 0x0005,
- TRIANGLE_FAN = 0x0006,
- ZERO = 0,
- ONE = 1,
- SRC_COLOR = 0x0300,
- ONE_MINUS_SRC_COLOR = 0x0301,
- SRC_ALPHA = 0x0302,
- ONE_MINUS_SRC_ALPHA = 0x0303,
- DST_ALPHA = 0x0304,
- ONE_MINUS_DST_ALPHA = 0x0305,
- DST_COLOR = 0x0306,
- ONE_MINUS_DST_COLOR = 0x0307,
- SRC_ALPHA_SATURATE = 0x0308,
- FUNC_ADD = 0x8006,
- BLEND_EQUATION = 0x8009,
- BLEND_EQUATION_RGB = 0x8009,
- BLEND_EQUATION_ALPHA = 0x883D,
- FUNC_SUBTRACT = 0x800A,
- FUNC_REVERSE_SUBTRACT = 0x800B,
- BLEND_DST_RGB = 0x80C8,
- BLEND_SRC_RGB = 0x80C9,
- BLEND_DST_ALPHA = 0x80CA,
- BLEND_SRC_ALPHA = 0x80CB,
- CONSTANT_COLOR = 0x8001,
- ONE_MINUS_CONSTANT_COLOR = 0x8002,
- CONSTANT_ALPHA = 0x8003,
- ONE_MINUS_CONSTANT_ALPHA = 0x8004,
- BLEND_COLOR = 0x8005,
- ARRAY_BUFFER = 0x8892,
- ELEMENT_ARRAY_BUFFER = 0x8893,
- ARRAY_BUFFER_BINDING = 0x8894,
- ELEMENT_ARRAY_BUFFER_BINDING = 0x8895,
- STREAM_DRAW = 0x88E0,
- STATIC_DRAW = 0x88E4,
- DYNAMIC_DRAW = 0x88E8,
- BUFFER_SIZE = 0x8764,
- BUFFER_USAGE = 0x8765,
- CURRENT_VERTEX_ATTRIB = 0x8626,
- FRONT = 0x0404,
- BACK = 0x0405,
- FRONT_AND_BACK = 0x0408,
- TEXTURE_2D = 0x0DE1,
- CULL_FACE = 0x0B44,
- BLEND = 0x0BE2,
- DITHER = 0x0BD0,
- STENCIL_TEST = 0x0B90,
- DEPTH_TEST = 0x0B71,
- SCISSOR_TEST = 0x0C11,
- POLYGON_OFFSET_FILL = 0x8037,
- SAMPLE_ALPHA_TO_COVERAGE = 0x809E,
- SAMPLE_COVERAGE = 0x80A0,
- NO_ERROR = 0,
- INVALID_ENUM = 0x0500,
- INVALID_VALUE = 0x0501,
- INVALID_OPERATION = 0x0502,
- OUT_OF_MEMORY = 0x0505,
- CW = 0x0900,
- CCW = 0x0901,
- LINE_WIDTH = 0x0B21,
- ALIASED_POINT_SIZE_RANGE = 0x846D,
- ALIASED_LINE_WIDTH_RANGE = 0x846E,
- CULL_FACE_MODE = 0x0B45,
- FRONT_FACE = 0x0B46,
- DEPTH_RANGE = 0x0B70,
- DEPTH_WRITEMASK = 0x0B72,
- DEPTH_CLEAR_VALUE = 0x0B73,
- DEPTH_FUNC = 0x0B74,
- STENCIL_CLEAR_VALUE = 0x0B91,
- STENCIL_FUNC = 0x0B92,
- STENCIL_FAIL = 0x0B94,
- STENCIL_PASS_DEPTH_FAIL = 0x0B95,
- STENCIL_PASS_DEPTH_PASS = 0x0B96,
- STENCIL_REF = 0x0B97,
- STENCIL_VALUE_MASK = 0x0B93,
- STENCIL_WRITEMASK = 0x0B98,
- STENCIL_BACK_FUNC = 0x8800,
- STENCIL_BACK_FAIL = 0x8801,
- STENCIL_BACK_PASS_DEPTH_FAIL = 0x8802,
- STENCIL_BACK_PASS_DEPTH_PASS = 0x8803,
- STENCIL_BACK_REF = 0x8CA3,
- STENCIL_BACK_VALUE_MASK = 0x8CA4,
- STENCIL_BACK_WRITEMASK = 0x8CA5,
- VIEWPORT = 0x0BA2,
- SCISSOR_BOX = 0x0C10,
- COLOR_CLEAR_VALUE = 0x0C22,
- COLOR_WRITEMASK = 0x0C23,
- UNPACK_ALIGNMENT = 0x0CF5,
- PACK_ALIGNMENT = 0x0D05,
- MAX_TEXTURE_SIZE = 0x0D33,
- MAX_VIEWPORT_DIMS = 0x0D3A,
- SUBPIXEL_BITS = 0x0D50,
- RED_BITS = 0x0D52,
- GREEN_BITS = 0x0D53,
- BLUE_BITS = 0x0D54,
- ALPHA_BITS = 0x0D55,
- DEPTH_BITS = 0x0D56,
- STENCIL_BITS = 0x0D57,
- POLYGON_OFFSET_UNITS = 0x2A00,
- POLYGON_OFFSET_FACTOR = 0x8038,
- TEXTURE_BINDING_2D = 0x8069,
- SAMPLE_BUFFERS = 0x80A8,
- SAMPLES = 0x80A9,
- SAMPLE_COVERAGE_VALUE = 0x80AA,
- SAMPLE_COVERAGE_INVERT = 0x80AB,
- NUM_COMPRESSED_TEXTURE_FORMATS = 0x86A2,
- COMPRESSED_TEXTURE_FORMATS = 0x86A3,
- DONT_CARE = 0x1100,
- FASTEST = 0x1101,
- NICEST = 0x1102,
- GENERATE_MIPMAP_HINT = 0x8192,
- BYTE = 0x1400,
- UNSIGNED_BYTE = 0x1401,
- SHORT = 0x1402,
- UNSIGNED_SHORT = 0x1403,
- INT = 0x1404,
- UNSIGNED_INT = 0x1405,
- FLOAT = 0x1406,
- HALF_FLOAT_OES = 0x8D61,
- FIXED = 0x140C,
- DEPTH_COMPONENT = 0x1902,
- ALPHA = 0x1906,
- RGB = 0x1907,
- RGBA = 0x1908,
- BGRA = 0x80E1,
- LUMINANCE = 0x1909,
- LUMINANCE_ALPHA = 0x190A,
- UNSIGNED_SHORT_4_4_4_4 = 0x8033,
- UNSIGNED_SHORT_5_5_5_1 = 0x8034,
- UNSIGNED_SHORT_5_6_5 = 0x8363,
- FRAGMENT_SHADER = 0x8B30,
- VERTEX_SHADER = 0x8B31,
- MAX_VERTEX_ATTRIBS = 0x8869,
- MAX_VERTEX_UNIFORM_VECTORS = 0x8DFB,
- MAX_VARYING_VECTORS = 0x8DFC,
- MAX_COMBINED_TEXTURE_IMAGE_UNITS = 0x8B4D,
- MAX_VERTEX_TEXTURE_IMAGE_UNITS = 0x8B4C,
- MAX_TEXTURE_IMAGE_UNITS = 0x8872,
- MAX_FRAGMENT_UNIFORM_VECTORS = 0x8DFD,
- SHADER_TYPE = 0x8B4F,
- DELETE_STATUS = 0x8B80,
- LINK_STATUS = 0x8B82,
- VALIDATE_STATUS = 0x8B83,
- ATTACHED_SHADERS = 0x8B85,
- ACTIVE_UNIFORMS = 0x8B86,
- ACTIVE_UNIFORM_MAX_LENGTH = 0x8B87,
- ACTIVE_ATTRIBUTES = 0x8B89,
- ACTIVE_ATTRIBUTE_MAX_LENGTH = 0x8B8A,
- SHADING_LANGUAGE_VERSION = 0x8B8C,
- CURRENT_PROGRAM = 0x8B8D,
- NEVER = 0x0200,
- LESS = 0x0201,
- EQUAL = 0x0202,
- LEQUAL = 0x0203,
- GREATER = 0x0204,
- NOTEQUAL = 0x0205,
- GEQUAL = 0x0206,
- ALWAYS = 0x0207,
- KEEP = 0x1E00,
- REPLACE = 0x1E01,
- INCR = 0x1E02,
- DECR = 0x1E03,
- INVERT = 0x150A,
- INCR_WRAP = 0x8507,
- DECR_WRAP = 0x8508,
- VENDOR = 0x1F00,
- RENDERER = 0x1F01,
- VERSION = 0x1F02,
- EXTENSIONS = 0x1F03,
- NEAREST = 0x2600,
- LINEAR = 0x2601,
- NEAREST_MIPMAP_NEAREST = 0x2700,
- LINEAR_MIPMAP_NEAREST = 0x2701,
- NEAREST_MIPMAP_LINEAR = 0x2702,
- LINEAR_MIPMAP_LINEAR = 0x2703,
- TEXTURE_MAG_FILTER = 0x2800,
- TEXTURE_MIN_FILTER = 0x2801,
- TEXTURE_WRAP_S = 0x2802,
- TEXTURE_WRAP_T = 0x2803,
- TEXTURE = 0x1702,
- TEXTURE_CUBE_MAP = 0x8513,
- TEXTURE_BINDING_CUBE_MAP = 0x8514,
- TEXTURE_CUBE_MAP_POSITIVE_X = 0x8515,
- TEXTURE_CUBE_MAP_NEGATIVE_X = 0x8516,
- TEXTURE_CUBE_MAP_POSITIVE_Y = 0x8517,
- TEXTURE_CUBE_MAP_NEGATIVE_Y = 0x8518,
- TEXTURE_CUBE_MAP_POSITIVE_Z = 0x8519,
- TEXTURE_CUBE_MAP_NEGATIVE_Z = 0x851A,
- MAX_CUBE_MAP_TEXTURE_SIZE = 0x851C,
- TEXTURE0 = 0x84C0,
- TEXTURE1 = 0x84C1,
- TEXTURE2 = 0x84C2,
- TEXTURE3 = 0x84C3,
- TEXTURE4 = 0x84C4,
- TEXTURE5 = 0x84C5,
- TEXTURE6 = 0x84C6,
- TEXTURE7 = 0x84C7,
- TEXTURE8 = 0x84C8,
- TEXTURE9 = 0x84C9,
- TEXTURE10 = 0x84CA,
- TEXTURE11 = 0x84CB,
- TEXTURE12 = 0x84CC,
- TEXTURE13 = 0x84CD,
- TEXTURE14 = 0x84CE,
- TEXTURE15 = 0x84CF,
- TEXTURE16 = 0x84D0,
- TEXTURE17 = 0x84D1,
- TEXTURE18 = 0x84D2,
- TEXTURE19 = 0x84D3,
- TEXTURE20 = 0x84D4,
- TEXTURE21 = 0x84D5,
- TEXTURE22 = 0x84D6,
- TEXTURE23 = 0x84D7,
- TEXTURE24 = 0x84D8,
- TEXTURE25 = 0x84D9,
- TEXTURE26 = 0x84DA,
- TEXTURE27 = 0x84DB,
- TEXTURE28 = 0x84DC,
- TEXTURE29 = 0x84DD,
- TEXTURE30 = 0x84DE,
- TEXTURE31 = 0x84DF,
- ACTIVE_TEXTURE = 0x84E0,
- REPEAT = 0x2901,
- CLAMP_TO_EDGE = 0x812F,
- MIRRORED_REPEAT = 0x8370,
- FLOAT_VEC2 = 0x8B50,
- FLOAT_VEC3 = 0x8B51,
- FLOAT_VEC4 = 0x8B52,
- INT_VEC2 = 0x8B53,
- INT_VEC3 = 0x8B54,
- INT_VEC4 = 0x8B55,
- BOOL = 0x8B56,
- BOOL_VEC2 = 0x8B57,
- BOOL_VEC3 = 0x8B58,
- BOOL_VEC4 = 0x8B59,
- FLOAT_MAT2 = 0x8B5A,
- FLOAT_MAT3 = 0x8B5B,
- FLOAT_MAT4 = 0x8B5C,
- SAMPLER_2D = 0x8B5E,
- SAMPLER_CUBE = 0x8B60,
- VERTEX_ATTRIB_ARRAY_ENABLED = 0x8622,
- VERTEX_ATTRIB_ARRAY_SIZE = 0x8623,
- VERTEX_ATTRIB_ARRAY_STRIDE = 0x8624,
- VERTEX_ATTRIB_ARRAY_TYPE = 0x8625,
- VERTEX_ATTRIB_ARRAY_NORMALIZED = 0x886A,
- VERTEX_ATTRIB_ARRAY_POINTER = 0x8645,
- VERTEX_ATTRIB_ARRAY_BUFFER_BINDING = 0x889F,
- COMPILE_STATUS = 0x8B81,
- INFO_LOG_LENGTH = 0x8B84,
- SHADER_SOURCE_LENGTH = 0x8B88,
- SHADER_COMPILER = 0x8DFA,
- SHADER_BINARY_FORMATS = 0x8DF8,
- NUM_SHADER_BINARY_FORMATS = 0x8DF9,
- LOW_FLOAT = 0x8DF0,
- MEDIUM_FLOAT = 0x8DF1,
- HIGH_FLOAT = 0x8DF2,
- LOW_INT = 0x8DF3,
- MEDIUM_INT = 0x8DF4,
- HIGH_INT = 0x8DF5,
- FRAMEBUFFER = 0x8D40,
- RENDERBUFFER = 0x8D41,
- RGBA4 = 0x8056,
- RGB5_A1 = 0x8057,
- RGB565 = 0x8D62,
- DEPTH_COMPONENT16 = 0x81A5,
- STENCIL_INDEX = 0x1901,
- STENCIL_INDEX8 = 0x8D48,
- DEPTH_STENCIL = 0x84F9,
- UNSIGNED_INT_24_8 = 0x84FA,
- DEPTH24_STENCIL8 = 0x88F0,
- RENDERBUFFER_WIDTH = 0x8D42,
- RENDERBUFFER_HEIGHT = 0x8D43,
- RENDERBUFFER_INTERNAL_FORMAT = 0x8D44,
- RENDERBUFFER_RED_SIZE = 0x8D50,
- RENDERBUFFER_GREEN_SIZE = 0x8D51,
- RENDERBUFFER_BLUE_SIZE = 0x8D52,
- RENDERBUFFER_ALPHA_SIZE = 0x8D53,
- RENDERBUFFER_DEPTH_SIZE = 0x8D54,
- RENDERBUFFER_STENCIL_SIZE = 0x8D55,
- FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE = 0x8CD0,
- FRAMEBUFFER_ATTACHMENT_OBJECT_NAME = 0x8CD1,
- FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL = 0x8CD2,
- FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE = 0x8CD3,
- COLOR_ATTACHMENT0 = 0x8CE0,
- DEPTH_ATTACHMENT = 0x8D00,
- STENCIL_ATTACHMENT = 0x8D20,
- DEPTH_STENCIL_ATTACHMENT = 0x821A,
- NONE = 0,
- FRAMEBUFFER_COMPLETE = 0x8CD5,
- FRAMEBUFFER_INCOMPLETE_ATTACHMENT = 0x8CD6,
- FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT = 0x8CD7,
- FRAMEBUFFER_INCOMPLETE_DIMENSIONS = 0x8CD9,
- FRAMEBUFFER_UNSUPPORTED = 0x8CDD,
- FRAMEBUFFER_BINDING = 0x8CA6,
- RENDERBUFFER_BINDING = 0x8CA7,
- MAX_RENDERBUFFER_SIZE = 0x84E8,
- INVALID_FRAMEBUFFER_OPERATION = 0x0506,
-
- // WebGL-specific enums
- UNPACK_FLIP_Y_WEBGL = 0x9240,
- UNPACK_PREMULTIPLY_ALPHA_WEBGL = 0x9241,
- CONTEXT_LOST_WEBGL = 0x9242,
- UNPACK_COLORSPACE_CONVERSION_WEBGL = 0x9243,
- BROWSER_DEFAULT_WEBGL = 0x9244
- };
-
- // Context creation attributes.
- struct Attributes {
- Attributes()
- : alpha(true)
- , depth(true)
- , stencil(false)
- , antialias(true)
- , premultipliedAlpha(true)
- , preserveDrawingBuffer(false)
- , noExtensions(false)
- , shareResources(true)
- , preferDiscreteGPU(false)
- {
- }
-
- bool alpha;
- bool depth;
- bool stencil;
- bool antialias;
- bool premultipliedAlpha;
- bool preserveDrawingBuffer;
- bool noExtensions;
- bool shareResources;
- bool preferDiscreteGPU;
- KURL topDocumentURL;
- };
-
- class ContextLostCallback {
- public:
- virtual void onContextLost() = 0;
- virtual ~ContextLostCallback() {}
- };
-
- class ErrorMessageCallback {
- public:
- virtual void onErrorMessage(const String& message, GC3Dint id) = 0;
- virtual ~ErrorMessageCallback() { }
- };
-
- void setContextLostCallback(PassOwnPtr<ContextLostCallback>);
- void setErrorMessageCallback(PassOwnPtr<ErrorMessageCallback>);
-
- static PassRefPtr<GraphicsContext3D> create(Attributes);
-
- // Callers must make the context current before using it AND check that the context was created successfully
- // via ContextLost before using the context in any way. Once made current on a thread, the context cannot
- // be used on any other thread.
- static PassRefPtr<GraphicsContext3D> createGraphicsContextFromWebContext(PassOwnPtr<WebKit::WebGraphicsContext3D>, bool preserveDrawingBuffer = false);
- static PassRefPtr<GraphicsContext3D> createGraphicsContextFromProvider(PassOwnPtr<WebKit::WebGraphicsContext3DProvider>, bool preserveDrawingBuffer = false);
-
- ~GraphicsContext3D();
-
- GrContext* grContext();
- WebKit::WebGraphicsContext3D* webContext() const { return m_impl; }
-
- bool makeContextCurrent();
-
- uint32_t lastFlushID();
-
- // Helper to texImage2D with pixel==0 case: pixels are initialized to 0.
- // Return true if no GL error is synthesized.
- // By default, alignment is 4, the OpenGL default setting.
- bool texImage2DResourceSafe(GC3Denum target, GC3Dint level, GC3Denum internalformat, GC3Dsizei width, GC3Dsizei height, GC3Dint border, GC3Denum format, GC3Denum type, GC3Dint alignment = 4);
-
- //----------------------------------------------------------------------
- // Helpers for texture uploading and pixel readback.
- //
-
- // Computes the components per pixel and bytes per component
- // for the given format and type combination. Returns false if
- // either was an invalid enum.
- static bool computeFormatAndTypeParameters(GC3Denum format,
- GC3Denum type,
- unsigned int* componentsPerPixel,
- unsigned int* bytesPerComponent);
-
- // Computes the image size in bytes. If paddingInBytes is not null, padding
- // is also calculated in return. Returns NO_ERROR if succeed, otherwise
- // return the suggested GL error indicating the cause of the failure:
- // INVALID_VALUE if width/height is negative or overflow happens.
- // INVALID_ENUM if format/type is illegal.
- static GC3Denum computeImageSizeInBytes(GC3Denum format,
- GC3Denum type,
- GC3Dsizei width,
- GC3Dsizei height,
- GC3Dint alignment,
- unsigned int* imageSizeInBytes,
- unsigned int* paddingInBytes);
-
- // Attempt to enumerate all possible native image formats to
- // reduce the amount of temporary allocations during texture
- // uploading. This enum must be public because it is accessed
- // by non-member functions.
- enum DataFormat {
- DataFormatRGBA8 = 0,
- DataFormatRGBA16F,
- DataFormatRGBA32F,
- DataFormatRGB8,
- DataFormatRGB16F,
- DataFormatRGB32F,
- DataFormatBGR8,
- DataFormatBGRA8,
- DataFormatARGB8,
- DataFormatABGR8,
- DataFormatRGBA5551,
- DataFormatRGBA4444,
- DataFormatRGB565,
- DataFormatR8,
- DataFormatR16F,
- DataFormatR32F,
- DataFormatRA8,
- DataFormatRA16F,
- DataFormatRA32F,
- DataFormatAR8,
- DataFormatA8,
- DataFormatA16F,
- DataFormatA32F,
- DataFormatNumFormats
- };
-
- // Check if the format is one of the formats from the ImageData or DOM elements.
- // The formats from ImageData is always RGBA8.
- // The formats from DOM elements vary with Graphics ports. It can only be RGBA8 or BGRA8.
- static ALWAYS_INLINE bool srcFormatComeFromDOMElementOrImageData(DataFormat SrcFormat)
- {
- return SrcFormat == DataFormatBGRA8 || SrcFormat == DataFormatRGBA8;
- }
-
- //----------------------------------------------------------------------
- // Entry points for WebGL.
- //
-
- void activeTexture(GC3Denum texture);
- void attachShader(Platform3DObject program, Platform3DObject shader);
- void bindAttribLocation(Platform3DObject, GC3Duint index, const String& name);
- void bindBuffer(GC3Denum target, Platform3DObject);
- void bindFramebuffer(GC3Denum target, Platform3DObject);
- void bindRenderbuffer(GC3Denum target, Platform3DObject);
- void bindTexture(GC3Denum target, Platform3DObject);
- void blendColor(GC3Dclampf red, GC3Dclampf green, GC3Dclampf blue, GC3Dclampf alpha);
- void blendEquation(GC3Denum mode);
- void blendEquationSeparate(GC3Denum modeRGB, GC3Denum modeAlpha);
- void blendFunc(GC3Denum sfactor, GC3Denum dfactor);
- void blendFuncSeparate(GC3Denum srcRGB, GC3Denum dstRGB, GC3Denum srcAlpha, GC3Denum dstAlpha);
-
- void bufferData(GC3Denum target, GC3Dsizeiptr size, GC3Denum usage);
- void bufferData(GC3Denum target, GC3Dsizeiptr size, const void* data, GC3Denum usage);
- void bufferSubData(GC3Denum target, GC3Dintptr offset, GC3Dsizeiptr size, const void* data);
-
- GC3Denum checkFramebufferStatus(GC3Denum target);
- void clear(GC3Dbitfield mask);
- void clearColor(GC3Dclampf red, GC3Dclampf green, GC3Dclampf blue, GC3Dclampf alpha);
- void clearDepth(GC3Dclampf depth);
- void clearStencil(GC3Dint s);
- void colorMask(GC3Dboolean red, GC3Dboolean green, GC3Dboolean blue, GC3Dboolean alpha);
- void compileShader(Platform3DObject);
-
- void compressedTexImage2D(GC3Denum target, GC3Dint level, GC3Denum internalformat, GC3Dsizei width, GC3Dsizei height, GC3Dint border, GC3Dsizei imageSize, const void* data);
- void compressedTexSubImage2D(GC3Denum target, GC3Dint level, GC3Dint xoffset, GC3Dint yoffset, GC3Dsizei width, GC3Dsizei height, GC3Denum format, GC3Dsizei imageSize, const void* data);
- void copyTexImage2D(GC3Denum target, GC3Dint level, GC3Denum internalformat, GC3Dint x, GC3Dint y, GC3Dsizei width, GC3Dsizei height, GC3Dint border);
- void copyTexSubImage2D(GC3Denum target, GC3Dint level, GC3Dint xoffset, GC3Dint yoffset, GC3Dint x, GC3Dint y, GC3Dsizei width, GC3Dsizei height);
- void cullFace(GC3Denum mode);
- void depthFunc(GC3Denum func);
- void depthMask(GC3Dboolean flag);
- void depthRange(GC3Dclampf zNear, GC3Dclampf zFar);
- void detachShader(Platform3DObject, Platform3DObject);
- void disable(GC3Denum cap);
- void disableVertexAttribArray(GC3Duint index);
- void drawArrays(GC3Denum mode, GC3Dint first, GC3Dsizei count);
- void drawElements(GC3Denum mode, GC3Dsizei count, GC3Denum type, GC3Dintptr offset);
-
- void enable(GC3Denum cap);
- void enableVertexAttribArray(GC3Duint index);
- void finish();
- void flush();
- void framebufferRenderbuffer(GC3Denum target, GC3Denum attachment, GC3Denum renderbuffertarget, Platform3DObject);
- void framebufferTexture2D(GC3Denum target, GC3Denum attachment, GC3Denum textarget, Platform3DObject, GC3Dint level);
- void frontFace(GC3Denum mode);
- void generateMipmap(GC3Denum target);
-
- bool getActiveAttrib(Platform3DObject program, GC3Duint index, ActiveInfo&);
- bool getActiveUniform(Platform3DObject program, GC3Duint index, ActiveInfo&);
- void getAttachedShaders(Platform3DObject program, GC3Dsizei maxCount, GC3Dsizei* count, Platform3DObject* shaders);
- GC3Dint getAttribLocation(Platform3DObject, const String& name);
- void getBooleanv(GC3Denum pname, GC3Dboolean* value);
- void getBufferParameteriv(GC3Denum target, GC3Denum pname, GC3Dint* value);
- Attributes getContextAttributes();
- GC3Denum getError();
- void getFloatv(GC3Denum pname, GC3Dfloat* value);
- void getFramebufferAttachmentParameteriv(GC3Denum target, GC3Denum attachment, GC3Denum pname, GC3Dint* value);
- void getIntegerv(GC3Denum pname, GC3Dint* value);
- void getProgramiv(Platform3DObject program, GC3Denum pname, GC3Dint* value);
- String getProgramInfoLog(Platform3DObject);
- void getRenderbufferParameteriv(GC3Denum target, GC3Denum pname, GC3Dint* value);
- void getShaderiv(Platform3DObject, GC3Denum pname, GC3Dint* value);
- String getShaderInfoLog(Platform3DObject);
- void getShaderPrecisionFormat(GC3Denum shaderType, GC3Denum precisionType, GC3Dint* range, GC3Dint* precision);
- String getShaderSource(Platform3DObject);
- String getString(GC3Denum name);
- void getTexParameterfv(GC3Denum target, GC3Denum pname, GC3Dfloat* value);
- void getTexParameteriv(GC3Denum target, GC3Denum pname, GC3Dint* value);
- void getUniformfv(Platform3DObject program, GC3Dint location, GC3Dfloat* value);
- void getUniformiv(Platform3DObject program, GC3Dint location, GC3Dint* value);
- GC3Dint getUniformLocation(Platform3DObject, const String& name);
- void getVertexAttribfv(GC3Duint index, GC3Denum pname, GC3Dfloat* value);
- void getVertexAttribiv(GC3Duint index, GC3Denum pname, GC3Dint* value);
- GC3Dsizeiptr getVertexAttribOffset(GC3Duint index, GC3Denum pname);
-
- void hint(GC3Denum target, GC3Denum mode);
- GC3Dboolean isBuffer(Platform3DObject);
- GC3Dboolean isEnabled(GC3Denum cap);
- GC3Dboolean isFramebuffer(Platform3DObject);
- GC3Dboolean isProgram(Platform3DObject);
- GC3Dboolean isRenderbuffer(Platform3DObject);
- GC3Dboolean isShader(Platform3DObject);
- GC3Dboolean isTexture(Platform3DObject);
- void lineWidth(GC3Dfloat);
- void linkProgram(Platform3DObject);
- void pixelStorei(GC3Denum pname, GC3Dint param);
- void polygonOffset(GC3Dfloat factor, GC3Dfloat units);
-
- void readPixels(GC3Dint x, GC3Dint y, GC3Dsizei width, GC3Dsizei height, GC3Denum format, GC3Denum type, void* data);
-
- void releaseShaderCompiler();
-
- void renderbufferStorage(GC3Denum target, GC3Denum internalformat, GC3Dsizei width, GC3Dsizei height);
- void sampleCoverage(GC3Dclampf value, GC3Dboolean invert);
- void scissor(GC3Dint x, GC3Dint y, GC3Dsizei width, GC3Dsizei height);
- void shaderSource(Platform3DObject, const String& string);
- void stencilFunc(GC3Denum func, GC3Dint ref, GC3Duint mask);
- void stencilFuncSeparate(GC3Denum face, GC3Denum func, GC3Dint ref, GC3Duint mask);
- void stencilMask(GC3Duint mask);
- void stencilMaskSeparate(GC3Denum face, GC3Duint mask);
- void stencilOp(GC3Denum fail, GC3Denum zfail, GC3Denum zpass);
- void stencilOpSeparate(GC3Denum face, GC3Denum fail, GC3Denum zfail, GC3Denum zpass);
-
- void texImage2D(GC3Denum target, GC3Dint level, GC3Denum internalformat, GC3Dsizei width, GC3Dsizei height, GC3Dint border, GC3Denum format, GC3Denum type, const void* pixels);
- void texParameterf(GC3Denum target, GC3Denum pname, GC3Dfloat param);
- void texParameteri(GC3Denum target, GC3Denum pname, GC3Dint param);
- void texSubImage2D(GC3Denum target, GC3Dint level, GC3Dint xoffset, GC3Dint yoffset, GC3Dsizei width, GC3Dsizei height, GC3Denum format, GC3Denum type, const void* pixels);
-
- void uniform1f(GC3Dint location, GC3Dfloat x);
- void uniform1fv(GC3Dint location, GC3Dsizei, GC3Dfloat* v);
- void uniform1i(GC3Dint location, GC3Dint x);
- void uniform1iv(GC3Dint location, GC3Dsizei, GC3Dint* v);
- void uniform2f(GC3Dint location, GC3Dfloat x, GC3Dfloat y);
- void uniform2fv(GC3Dint location, GC3Dsizei, GC3Dfloat* v);
- void uniform2i(GC3Dint location, GC3Dint x, GC3Dint y);
- void uniform2iv(GC3Dint location, GC3Dsizei, GC3Dint* v);
- void uniform3f(GC3Dint location, GC3Dfloat x, GC3Dfloat y, GC3Dfloat z);
- void uniform3fv(GC3Dint location, GC3Dsizei, GC3Dfloat* v);
- void uniform3i(GC3Dint location, GC3Dint x, GC3Dint y, GC3Dint z);
- void uniform3iv(GC3Dint location, GC3Dsizei, GC3Dint* v);
- void uniform4f(GC3Dint location, GC3Dfloat x, GC3Dfloat y, GC3Dfloat z, GC3Dfloat w);
- void uniform4fv(GC3Dint location, GC3Dsizei, GC3Dfloat* v);
- void uniform4i(GC3Dint location, GC3Dint x, GC3Dint y, GC3Dint z, GC3Dint w);
- void uniform4iv(GC3Dint location, GC3Dsizei, GC3Dint* v);
- void uniformMatrix2fv(GC3Dint location, GC3Dsizei, GC3Dboolean transpose, GC3Dfloat* value);
- void uniformMatrix3fv(GC3Dint location, GC3Dsizei, GC3Dboolean transpose, GC3Dfloat* value);
- void uniformMatrix4fv(GC3Dint location, GC3Dsizei, GC3Dboolean transpose, GC3Dfloat* value);
-
- void useProgram(Platform3DObject);
- void validateProgram(Platform3DObject);
-
- void vertexAttrib1f(GC3Duint index, GC3Dfloat x);
- void vertexAttrib1fv(GC3Duint index, GC3Dfloat* values);
- void vertexAttrib2f(GC3Duint index, GC3Dfloat x, GC3Dfloat y);
- void vertexAttrib2fv(GC3Duint index, GC3Dfloat* values);
- void vertexAttrib3f(GC3Duint index, GC3Dfloat x, GC3Dfloat y, GC3Dfloat z);
- void vertexAttrib3fv(GC3Duint index, GC3Dfloat* values);
- void vertexAttrib4f(GC3Duint index, GC3Dfloat x, GC3Dfloat y, GC3Dfloat z, GC3Dfloat w);
- void vertexAttrib4fv(GC3Duint index, GC3Dfloat* values);
- void vertexAttribPointer(GC3Duint index, GC3Dint size, GC3Denum type, GC3Dboolean normalized,
- GC3Dsizei stride, GC3Dintptr offset);
-
- void viewport(GC3Dint x, GC3Dint y, GC3Dsizei width, GC3Dsizei height);
-
- void reshape(int width, int height);
-
- void markContextChanged();
- void markLayerComposited();
- bool layerComposited() const;
-
- void paintRenderingResultsToCanvas(ImageBuffer*, DrawingBuffer*);
- PassRefPtr<ImageData> paintRenderingResultsToImageData(DrawingBuffer*);
-
- // Support for buffer creation and deletion
- Platform3DObject createBuffer();
- Platform3DObject createFramebuffer();
- Platform3DObject createProgram();
- Platform3DObject createRenderbuffer();
- Platform3DObject createShader(GC3Denum);
- Platform3DObject createTexture();
-
- void deleteBuffer(Platform3DObject);
- void deleteFramebuffer(Platform3DObject);
- void deleteProgram(Platform3DObject);
- void deleteRenderbuffer(Platform3DObject);
- void deleteShader(Platform3DObject);
- void deleteTexture(Platform3DObject);
-
- // Synthesizes an OpenGL error which will be returned from a
- // later call to getError. This is used to emulate OpenGL ES
- // 2.0 behavior on the desktop and to enforce additional error
- // checking mandated by WebGL.
- //
- // Per the behavior of glGetError, this stores at most one
- // instance of any given error, and returns them from calls to
- // getError in the order they were added.
- void synthesizeGLError(GC3Denum error);
-
- // Support for extensions. Returns a non-null object, though not
- // all methods it contains may necessarily be supported on the
- // current hardware. Must call Extensions3D::supports() to
- // determine this.
- Extensions3D* extensions();
-
- static unsigned getClearBitsByFormat(GC3Denum);
-
- enum ChannelBits {
- ChannelRed = 1,
- ChannelGreen = 2,
- ChannelBlue = 4,
- ChannelAlpha = 8,
- ChannelDepth = 16,
- ChannelStencil = 32,
- ChannelRGB = ChannelRed | ChannelGreen | ChannelBlue,
- ChannelRGBA = ChannelRGB | ChannelAlpha,
- };
-
- static unsigned getChannelBitsByFormat(GC3Denum);
-
- // Possible alpha operations that may need to occur during
- // pixel packing. FIXME: kAlphaDoUnmultiply is lossy and must
- // be removed.
- enum AlphaOp {
- AlphaDoNothing = 0,
- AlphaDoPremultiply = 1,
- AlphaDoUnmultiply = 2
- };
-
- enum ImageHtmlDomSource {
- HtmlDomImage = 0,
- HtmlDomCanvas = 1,
- HtmlDomVideo = 2,
- HtmlDomNone = 3
- };
-
- class ImageExtractor {
- public:
- ImageExtractor(Image*, ImageHtmlDomSource, bool premultiplyAlpha, bool ignoreGammaAndColorProfile);
-
- ~ImageExtractor();
-
- bool extractSucceeded() { return m_extractSucceeded; }
- const void* imagePixelData() { return m_imagePixelData; }
- unsigned imageWidth() { return m_imageWidth; }
- unsigned imageHeight() { return m_imageHeight; }
- DataFormat imageSourceFormat() { return m_imageSourceFormat; }
- AlphaOp imageAlphaOp() { return m_alphaOp; }
- unsigned imageSourceUnpackAlignment() { return m_imageSourceUnpackAlignment; }
- ImageHtmlDomSource imageHtmlDomSource() { return m_imageHtmlDomSource; }
- private:
- // Extract the image and keeps track of its status, such as width, height, Source Alignment, format and AlphaOp etc.
- // This needs to lock the resources or relevant data if needed and return true upon success
- bool extractImage(bool premultiplyAlpha, bool ignoreGammaAndColorProfile);
-
- RefPtr<NativeImageSkia> m_nativeImage;
- RefPtr<NativeImageSkia> m_skiaImage;
- Image* m_image;
- ImageHtmlDomSource m_imageHtmlDomSource;
- bool m_extractSucceeded;
- const void* m_imagePixelData;
- unsigned m_imageWidth;
- unsigned m_imageHeight;
- DataFormat m_imageSourceFormat;
- AlphaOp m_alphaOp;
- unsigned m_imageSourceUnpackAlignment;
- };
-
- // The Following functions are implemented in GraphicsContext3DImagePacking.cpp
-
- // Packs the contents of the given Image which is passed in |pixels| into the passed Vector
- // according to the given format and type, and obeying the flipY and AlphaOp flags.
- // Returns true upon success.
- static bool packImageData(Image*, const void* pixels, GC3Denum format, GC3Denum type, bool flipY, AlphaOp, DataFormat sourceFormat, unsigned width, unsigned height, unsigned sourceUnpackAlignment, Vector<uint8_t>& data);
-
- // Extracts the contents of the given ImageData into the passed Vector,
- // packing the pixel data according to the given format and type,
- // and obeying the flipY and premultiplyAlpha flags. Returns true
- // upon success.
- static bool extractImageData(ImageData*, GC3Denum format, GC3Denum type, bool flipY, bool premultiplyAlpha, Vector<uint8_t>& data);
-
- // Helper function which extracts the user-supplied texture
- // data, applying the flipY and premultiplyAlpha parameters.
- // If the data is not tightly packed according to the passed
- // unpackAlignment, the output data will be tightly packed.
- // Returns true if successful, false if any error occurred.
- static bool extractTextureData(unsigned width, unsigned height, GC3Denum format, GC3Denum type, unsigned unpackAlignment, bool flipY, bool premultiplyAlpha, const void* pixels, Vector<uint8_t>& data);
-
- // End GraphicsContext3DImagePacking.cpp functions
-
- // This is the order of bytes to use when doing a readback.
- enum ReadbackOrder {
- ReadbackRGBA,
- ReadbackSkia
- };
-
- // Helper function which does a readback from the currently-bound
- // framebuffer into a buffer of a certain size with 4-byte pixels.
- void readBackFramebuffer(unsigned char* pixels, int width, int height, ReadbackOrder, AlphaOp);
-
-private:
- friend class Extensions3D;
-
- GraphicsContext3D(PassOwnPtr<WebKit::WebGraphicsContext3D>, bool preserveDrawingBuffer);
- GraphicsContext3D(PassOwnPtr<WebKit::WebGraphicsContext3DProvider>, bool preserveDrawingBuffer);
-
- // Helper for packImageData/extractImageData/extractTextureData which implement packing of pixel
- // data into the specified OpenGL destination format and type.
- // A sourceUnpackAlignment of zero indicates that the source
- // data is tightly packed. Non-zero values may take a slow path.
- // Destination data will have no gaps between rows.
- // Implemented in GraphicsContext3DImagePacking.cpp
- static bool packPixels(const uint8_t* sourceData, DataFormat sourceDataFormat, unsigned width, unsigned height, unsigned sourceUnpackAlignment, unsigned destinationFormat, unsigned destinationType, AlphaOp, void* destinationData, bool flipY);
-
- void paintFramebufferToCanvas(int framebuffer, int width, int height, bool premultiplyAlpha, ImageBuffer*);
- // Helper function to flip a bitmap vertically.
- void flipVertically(uint8_t* data, int width, int height);
-
- // Extensions3D support.
- bool supportsExtension(const String& name);
- bool ensureExtensionEnabled(const String& name);
- bool isExtensionEnabled(const String& name);
-
- void initializeExtensions();
-
- bool preserveDrawingBuffer() const { return m_preserveDrawingBuffer; }
-
- OwnPtr<WebKit::WebGraphicsContext3DProvider> m_provider;
- WebKit::WebGraphicsContext3D* m_impl;
- OwnPtr<GraphicsContext3DContextLostCallbackAdapter> m_contextLostCallbackAdapter;
- OwnPtr<GraphicsContext3DErrorMessageCallbackAdapter> m_errorMessageCallbackAdapter;
- OwnPtr<WebKit::WebGraphicsContext3D> m_ownedWebContext;
- OwnPtr<Extensions3D> m_extensions;
- OwnPtr<GrMemoryAllocationChangedCallbackAdapter> m_grContextMemoryAllocationCallbackAdapter;
- bool m_initializedAvailableExtensions;
- HashSet<String> m_enabledExtensions;
- HashSet<String> m_requestableExtensions;
- bool m_layerComposited;
- bool m_preserveDrawingBuffer;
- int m_packAlignment;
-
- enum ResourceSafety {
- ResourceSafetyUnknown,
- ResourceSafe,
- ResourceUnsafe
- };
- ResourceSafety m_resourceSafety;
-
- // If the width and height of the Canvas's backing store don't
- // match those that we were given in the most recent call to
- // reshape(), then we need an intermediate bitmap to read back the
- // frame buffer into. This seems to happen when CSS styles are
- // used to resize the Canvas.
- SkBitmap m_resizingBitmap;
-
- GrContext* m_grContext;
- SkAutoTUnref<GrContext> m_ownedGrContext;
-
- // Used to flip a bitmap vertically.
- Vector<uint8_t> m_scanline;
-};
-
-} // namespace WebCore
-
-#endif // GraphicsContext3D_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsContext3DImagePacking.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsContext3DImagePacking.cpp
deleted file mode 100644
index fdcbfb02966..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsContext3DImagePacking.cpp
+++ /dev/null
@@ -1,1589 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- * Copyright (C) 2010 Mozilla Corporation. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/GraphicsContext3D.h"
-
-#include "core/html/ImageData.h"
-#include "core/html/canvas/CheckedInt.h"
-#include "core/platform/graphics/ImageObserver.h"
-#include "core/platform/graphics/cpu/arm/GraphicsContext3DNEON.h"
-#include "core/platform/image-decoders/ImageDecoder.h"
-
-namespace WebCore {
-
-namespace {
-
-GraphicsContext3D::DataFormat getDataFormat(GC3Denum destinationFormat, GC3Denum destinationType)
-{
- GraphicsContext3D::DataFormat dstFormat = GraphicsContext3D::DataFormatRGBA8;
- switch (destinationType) {
- case GraphicsContext3D::UNSIGNED_BYTE:
- switch (destinationFormat) {
- case GraphicsContext3D::RGB:
- dstFormat = GraphicsContext3D::DataFormatRGB8;
- break;
- case GraphicsContext3D::RGBA:
- dstFormat = GraphicsContext3D::DataFormatRGBA8;
- break;
- case GraphicsContext3D::ALPHA:
- dstFormat = GraphicsContext3D::DataFormatA8;
- break;
- case GraphicsContext3D::LUMINANCE:
- dstFormat = GraphicsContext3D::DataFormatR8;
- break;
- case GraphicsContext3D::LUMINANCE_ALPHA:
- dstFormat = GraphicsContext3D::DataFormatRA8;
- break;
- default:
- ASSERT_NOT_REACHED();
- }
- break;
- case GraphicsContext3D::UNSIGNED_SHORT_4_4_4_4:
- dstFormat = GraphicsContext3D::DataFormatRGBA4444;
- break;
- case GraphicsContext3D::UNSIGNED_SHORT_5_5_5_1:
- dstFormat = GraphicsContext3D::DataFormatRGBA5551;
- break;
- case GraphicsContext3D::UNSIGNED_SHORT_5_6_5:
- dstFormat = GraphicsContext3D::DataFormatRGB565;
- break;
- case GraphicsContext3D::HALF_FLOAT_OES: // OES_texture_half_float
- switch (destinationFormat) {
- case GraphicsContext3D::RGB:
- dstFormat = GraphicsContext3D::DataFormatRGB16F;
- break;
- case GraphicsContext3D::RGBA:
- dstFormat = GraphicsContext3D::DataFormatRGBA16F;
- break;
- case GraphicsContext3D::ALPHA:
- dstFormat = GraphicsContext3D::DataFormatA16F;
- break;
- case GraphicsContext3D::LUMINANCE:
- dstFormat = GraphicsContext3D::DataFormatR16F;
- break;
- case GraphicsContext3D::LUMINANCE_ALPHA:
- dstFormat = GraphicsContext3D::DataFormatRA16F;
- break;
- default:
- ASSERT_NOT_REACHED();
- }
- break;
- case GraphicsContext3D::FLOAT: // OES_texture_float
- switch (destinationFormat) {
- case GraphicsContext3D::RGB:
- dstFormat = GraphicsContext3D::DataFormatRGB32F;
- break;
- case GraphicsContext3D::RGBA:
- dstFormat = GraphicsContext3D::DataFormatRGBA32F;
- break;
- case GraphicsContext3D::ALPHA:
- dstFormat = GraphicsContext3D::DataFormatA32F;
- break;
- case GraphicsContext3D::LUMINANCE:
- dstFormat = GraphicsContext3D::DataFormatR32F;
- break;
- case GraphicsContext3D::LUMINANCE_ALPHA:
- dstFormat = GraphicsContext3D::DataFormatRA32F;
- break;
- default:
- ASSERT_NOT_REACHED();
- }
- break;
- default:
- ASSERT_NOT_REACHED();
- }
- return dstFormat;
-}
-
-// Following Float to Half-Float converion code is from the implementation of ftp://www.fox-toolkit.org/pub/fasthalffloatconversion.pdf,
-// "Fast Half Float Conversions" by Jeroen van der Zijp, November 2008 (Revised September 2010).
-// Specially, the basetable[512] and shifttable[512] are generated as follows:
-/*
-unsigned short basetable[512];
-unsigned char shifttable[512];
-
-void generatetables(){
- unsigned int i;
- int e;
- for (i = 0; i < 256; ++i){
- e = i - 127;
- if (e < -24){ // Very small numbers map to zero
- basetable[i | 0x000] = 0x0000;
- basetable[i | 0x100] = 0x8000;
- shifttable[i | 0x000] = 24;
- shifttable[i | 0x100] = 24;
- }
- else if (e < -14) { // Small numbers map to denorms
- basetable[i | 0x000] = (0x0400>>(-e-14));
- basetable[i | 0x100] = (0x0400>>(-e-14)) | 0x8000;
- shifttable[i | 0x000] = -e-1;
- shifttable[i | 0x100] = -e-1;
- }
- else if (e <= 15){ // Normal numbers just lose precision
- basetable[i | 0x000] = ((e+15)<<10);
- basetable[i| 0x100] = ((e+15)<<10) | 0x8000;
- shifttable[i|0x000] = 13;
- shifttable[i|0x100] = 13;
- }
- else if (e<128){ // Large numbers map to Infinity
- basetable[i|0x000] = 0x7C00;
- basetable[i|0x100] = 0xFC00;
- shifttable[i|0x000] = 24;
- shifttable[i|0x100] = 24;
- }
- else { // Infinity and NaN's stay Infinity and NaN's
- basetable[i|0x000] = 0x7C00;
- basetable[i|0x100] = 0xFC00;
- shifttable[i|0x000] = 13;
- shifttable[i|0x100] = 13;
- }
- }
-}
-*/
-
-unsigned short baseTable[512] = {
-0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-0, 0, 0, 0, 0, 0, 0, 1, 2, 4, 8, 16, 32, 64, 128, 256,
-512, 1024, 2048, 3072, 4096, 5120, 6144, 7168, 8192, 9216, 10240, 11264, 12288, 13312, 14336, 15360,
-16384, 17408, 18432, 19456, 20480, 21504, 22528, 23552, 24576, 25600, 26624, 27648, 28672, 29696, 30720, 31744,
-31744, 31744, 31744, 31744, 31744, 31744, 31744, 31744, 31744, 31744, 31744, 31744, 31744, 31744, 31744, 31744,
-31744, 31744, 31744, 31744, 31744, 31744, 31744, 31744, 31744, 31744, 31744, 31744, 31744, 31744, 31744, 31744,
-31744, 31744, 31744, 31744, 31744, 31744, 31744, 31744, 31744, 31744, 31744, 31744, 31744, 31744, 31744, 31744,
-31744, 31744, 31744, 31744, 31744, 31744, 31744, 31744, 31744, 31744, 31744, 31744, 31744, 31744, 31744, 31744,
-31744, 31744, 31744, 31744, 31744, 31744, 31744, 31744, 31744, 31744, 31744, 31744, 31744, 31744, 31744, 31744,
-31744, 31744, 31744, 31744, 31744, 31744, 31744, 31744, 31744, 31744, 31744, 31744, 31744, 31744, 31744, 31744,
-31744, 31744, 31744, 31744, 31744, 31744, 31744, 31744, 31744, 31744, 31744, 31744, 31744, 31744, 31744, 31744,
-32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768,
-32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768,
-32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768,
-32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768,
-32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768,
-32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768, 32768,
-32768, 32768, 32768, 32768, 32768, 32768, 32768, 32769, 32770, 32772, 32776, 32784, 32800, 32832, 32896, 33024,
-33280, 33792, 34816, 35840, 36864, 37888, 38912, 39936, 40960, 41984, 43008, 44032, 45056, 46080, 47104, 48128,
-49152, 50176, 51200, 52224, 53248, 54272, 55296, 56320, 57344, 58368, 59392, 60416, 61440, 62464, 63488, 64512,
-64512, 64512, 64512, 64512, 64512, 64512, 64512, 64512, 64512, 64512, 64512, 64512, 64512, 64512, 64512, 64512,
-64512, 64512, 64512, 64512, 64512, 64512, 64512, 64512, 64512, 64512, 64512, 64512, 64512, 64512, 64512, 64512,
-64512, 64512, 64512, 64512, 64512, 64512, 64512, 64512, 64512, 64512, 64512, 64512, 64512, 64512, 64512, 64512,
-64512, 64512, 64512, 64512, 64512, 64512, 64512, 64512, 64512, 64512, 64512, 64512, 64512, 64512, 64512, 64512,
-64512, 64512, 64512, 64512, 64512, 64512, 64512, 64512, 64512, 64512, 64512, 64512, 64512, 64512, 64512, 64512,
-64512, 64512, 64512, 64512, 64512, 64512, 64512, 64512, 64512, 64512, 64512, 64512, 64512, 64512, 64512, 64512,
-64512, 64512, 64512, 64512, 64512, 64512, 64512, 64512, 64512, 64512, 64512, 64512, 64512, 64512, 64512, 64512
-};
-
-unsigned char shiftTable[512] = {
-24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
-24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
-24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
-24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
-24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
-24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
-24, 24, 24, 24, 24, 24, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15,
-14, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
-13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 24,
-24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
-24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
-24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
-24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
-24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
-24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
-24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 13,
-24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
-24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
-24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
-24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
-24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
-24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
-24, 24, 24, 24, 24, 24, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15,
-14, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
-13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 24,
-24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
-24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
-24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
-24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
-24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
-24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
-24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 13
-};
-
-unsigned short convertFloatToHalfFloat(float f)
-{
- unsigned temp = *(reinterpret_cast<unsigned *>(&f));
- unsigned signexp = (temp >> 23) & 0x1ff;
- return baseTable[signexp] + ((temp & 0x007fffff) >> shiftTable[signexp]);
-}
-
-/* BEGIN CODE SHARED WITH MOZILLA FIREFOX */
-
-// The following packing and unpacking routines are expressed in terms of function templates and inline functions to achieve generality and speedup.
-// Explicit template specializations correspond to the cases that would occur.
-// Some code are merged back from Mozilla code in http://mxr.mozilla.org/mozilla-central/source/content/canvas/src/WebGLTexelConversions.h
-
-//----------------------------------------------------------------------
-// Pixel unpacking routines.
-template<int format, typename SourceType, typename DstType>
-void unpack(const SourceType*, DstType*, unsigned)
-{
- ASSERT_NOT_REACHED();
-}
-
-template<> void unpack<GraphicsContext3D::DataFormatRGB8, uint8_t, uint8_t>(const uint8_t* source, uint8_t* destination, unsigned pixelsPerRow)
-{
- for (unsigned int i = 0; i < pixelsPerRow; ++i) {
- destination[0] = source[0];
- destination[1] = source[1];
- destination[2] = source[2];
- destination[3] = 0xFF;
- source += 3;
- destination += 4;
- }
-}
-
-template<> void unpack<GraphicsContext3D::DataFormatBGR8, uint8_t, uint8_t>(const uint8_t* source, uint8_t* destination, unsigned pixelsPerRow)
-{
- for (unsigned int i = 0; i < pixelsPerRow; ++i) {
- destination[0] = source[2];
- destination[1] = source[1];
- destination[2] = source[0];
- destination[3] = 0xFF;
- source += 3;
- destination += 4;
- }
-}
-
-template<> void unpack<GraphicsContext3D::DataFormatARGB8, uint8_t, uint8_t>(const uint8_t* source, uint8_t* destination, unsigned pixelsPerRow)
-{
- for (unsigned int i = 0; i < pixelsPerRow; ++i) {
- destination[0] = source[1];
- destination[1] = source[2];
- destination[2] = source[3];
- destination[3] = source[0];
- source += 4;
- destination += 4;
- }
-}
-
-template<> void unpack<GraphicsContext3D::DataFormatABGR8, uint8_t, uint8_t>(const uint8_t* source, uint8_t* destination, unsigned pixelsPerRow)
-{
- for (unsigned int i = 0; i < pixelsPerRow; ++i) {
- destination[0] = source[3];
- destination[1] = source[2];
- destination[2] = source[1];
- destination[3] = source[0];
- source += 4;
- destination += 4;
- }
-}
-
-template<> void unpack<GraphicsContext3D::DataFormatBGRA8, uint8_t, uint8_t>(const uint8_t* source, uint8_t* destination, unsigned pixelsPerRow)
-{
- const uint32_t* source32 = reinterpret_cast_ptr<const uint32_t*>(source);
- uint32_t* destination32 = reinterpret_cast_ptr<uint32_t*>(destination);
- for (unsigned int i = 0; i < pixelsPerRow; ++i) {
- uint32_t bgra = source32[i];
-#if CPU(BIG_ENDIAN)
- uint32_t brMask = 0xff00ff00;
- uint32_t gaMask = 0x00ff00ff;
-#else
- uint32_t brMask = 0x00ff00ff;
- uint32_t gaMask = 0xff00ff00;
-#endif
- uint32_t rgba = (((bgra >> 16) | (bgra << 16)) & brMask) | (bgra & gaMask);
- destination32[i] = rgba;
- }
-}
-
-template<> void unpack<GraphicsContext3D::DataFormatRGBA5551, uint16_t, uint8_t>(const uint16_t* source, uint8_t* destination, unsigned pixelsPerRow)
-{
-#if HAVE(ARM_NEON_INTRINSICS)
- SIMD::unpackOneRowOfRGBA5551ToRGBA8(source, destination, pixelsPerRow);
-#endif
- for (unsigned int i = 0; i < pixelsPerRow; ++i) {
- uint16_t packedValue = source[0];
- uint8_t r = packedValue >> 11;
- uint8_t g = (packedValue >> 6) & 0x1F;
- uint8_t b = (packedValue >> 1) & 0x1F;
- destination[0] = (r << 3) | (r & 0x7);
- destination[1] = (g << 3) | (g & 0x7);
- destination[2] = (b << 3) | (b & 0x7);
- destination[3] = (packedValue & 0x1) ? 0xFF : 0x0;
- source += 1;
- destination += 4;
- }
-}
-
-template<> void unpack<GraphicsContext3D::DataFormatRGBA4444, uint16_t, uint8_t>(const uint16_t* source, uint8_t* destination, unsigned pixelsPerRow)
-{
-#if HAVE(ARM_NEON_INTRINSICS)
- SIMD::unpackOneRowOfRGBA4444ToRGBA8(source, destination, pixelsPerRow);
-#endif
- for (unsigned int i = 0; i < pixelsPerRow; ++i) {
- uint16_t packedValue = source[0];
- uint8_t r = packedValue >> 12;
- uint8_t g = (packedValue >> 8) & 0x0F;
- uint8_t b = (packedValue >> 4) & 0x0F;
- uint8_t a = packedValue & 0x0F;
- destination[0] = r << 4 | r;
- destination[1] = g << 4 | g;
- destination[2] = b << 4 | b;
- destination[3] = a << 4 | a;
- source += 1;
- destination += 4;
- }
-}
-
-template<> void unpack<GraphicsContext3D::DataFormatRGB565, uint16_t, uint8_t>(const uint16_t* source, uint8_t* destination, unsigned pixelsPerRow)
-{
-#if HAVE(ARM_NEON_INTRINSICS)
- SIMD::unpackOneRowOfRGB565ToRGBA8(source, destination, pixelsPerRow);
-#endif
- for (unsigned int i = 0; i < pixelsPerRow; ++i) {
- uint16_t packedValue = source[0];
- uint8_t r = packedValue >> 11;
- uint8_t g = (packedValue >> 5) & 0x3F;
- uint8_t b = packedValue & 0x1F;
- destination[0] = (r << 3) | (r & 0x7);
- destination[1] = (g << 2) | (g & 0x3);
- destination[2] = (b << 3) | (b & 0x7);
- destination[3] = 0xFF;
- source += 1;
- destination += 4;
- }
-}
-
-template<> void unpack<GraphicsContext3D::DataFormatR8, uint8_t, uint8_t>(const uint8_t* source, uint8_t* destination, unsigned pixelsPerRow)
-{
- for (unsigned int i = 0; i < pixelsPerRow; ++i) {
- destination[0] = source[0];
- destination[1] = source[0];
- destination[2] = source[0];
- destination[3] = 0xFF;
- source += 1;
- destination += 4;
- }
-}
-
-template<> void unpack<GraphicsContext3D::DataFormatRA8, uint8_t, uint8_t>(const uint8_t* source, uint8_t* destination, unsigned pixelsPerRow)
-{
- for (unsigned int i = 0; i < pixelsPerRow; ++i) {
- destination[0] = source[0];
- destination[1] = source[0];
- destination[2] = source[0];
- destination[3] = source[1];
- source += 2;
- destination += 4;
- }
-}
-
-template<> void unpack<GraphicsContext3D::DataFormatAR8, uint8_t, uint8_t>(const uint8_t* source, uint8_t* destination, unsigned pixelsPerRow)
-{
- for (unsigned int i = 0; i < pixelsPerRow; ++i) {
- destination[0] = source[1];
- destination[1] = source[1];
- destination[2] = source[1];
- destination[3] = source[0];
- source += 2;
- destination += 4;
- }
-}
-
-template<> void unpack<GraphicsContext3D::DataFormatA8, uint8_t, uint8_t>(const uint8_t* source, uint8_t* destination, unsigned pixelsPerRow)
-{
- for (unsigned int i = 0; i < pixelsPerRow; ++i) {
- destination[0] = 0x0;
- destination[1] = 0x0;
- destination[2] = 0x0;
- destination[3] = source[0];
- source += 1;
- destination += 4;
- }
-}
-
-template<> void unpack<GraphicsContext3D::DataFormatRGBA8, uint8_t, float>(const uint8_t* source, float* destination, unsigned pixelsPerRow)
-{
- const float scaleFactor = 1.0f / 255.0f;
- for (unsigned int i = 0; i < pixelsPerRow; ++i) {
- destination[0] = source[0] * scaleFactor;
- destination[1] = source[1] * scaleFactor;
- destination[2] = source[2] * scaleFactor;
- destination[3] = source[3] * scaleFactor;
- source += 4;
- destination += 4;
- }
-}
-
-template<> void unpack<GraphicsContext3D::DataFormatBGRA8, uint8_t, float>(const uint8_t* source, float* destination, unsigned pixelsPerRow)
-{
- const float scaleFactor = 1.0f / 255.0f;
- for (unsigned int i = 0; i < pixelsPerRow; ++i) {
- destination[0] = source[2] * scaleFactor;
- destination[1] = source[1] * scaleFactor;
- destination[2] = source[0] * scaleFactor;
- destination[3] = source[3] * scaleFactor;
- source += 4;
- destination += 4;
- }
-}
-
-template<> void unpack<GraphicsContext3D::DataFormatABGR8, uint8_t, float>(const uint8_t* source, float* destination, unsigned pixelsPerRow)
-{
- const float scaleFactor = 1.0f / 255.0f;
- for (unsigned i = 0; i < pixelsPerRow; ++i) {
- destination[0] = source[3] * scaleFactor;
- destination[1] = source[2] * scaleFactor;
- destination[2] = source[1] * scaleFactor;
- destination[3] = source[0] * scaleFactor;
- source += 4;
- destination += 4;
- }
-}
-
-template<> void unpack<GraphicsContext3D::DataFormatARGB8, uint8_t, float>(const uint8_t* source, float* destination, unsigned pixelsPerRow)
-{
- const float scaleFactor = 1.0f / 255.0f;
- for (unsigned i = 0; i < pixelsPerRow; ++i) {
- destination[0] = source[1] * scaleFactor;
- destination[1] = source[2] * scaleFactor;
- destination[2] = source[3] * scaleFactor;
- destination[3] = source[0] * scaleFactor;
- source += 4;
- destination += 4;
- }
-}
-
-template<> void unpack<GraphicsContext3D::DataFormatRGB8, uint8_t, float>(const uint8_t* source, float* destination, unsigned pixelsPerRow)
-{
- const float scaleFactor = 1.0f / 255.0f;
- for (unsigned i = 0; i < pixelsPerRow; ++i) {
- destination[0] = source[0] * scaleFactor;
- destination[1] = source[1] * scaleFactor;
- destination[2] = source[2] * scaleFactor;
- destination[3] = 1;
- source += 3;
- destination += 4;
- }
-}
-
-template<> void unpack<GraphicsContext3D::DataFormatBGR8, uint8_t, float>(const uint8_t* source, float* destination, unsigned pixelsPerRow)
-{
- const float scaleFactor = 1.0f / 255.0f;
- for (unsigned i = 0; i < pixelsPerRow; ++i) {
- destination[0] = source[2] * scaleFactor;
- destination[1] = source[1] * scaleFactor;
- destination[2] = source[0] * scaleFactor;
- destination[3] = 1;
- source += 3;
- destination += 4;
- }
-}
-
-template<> void unpack<GraphicsContext3D::DataFormatRGB32F, float, float>(const float* source, float* destination, unsigned pixelsPerRow)
-{
- for (unsigned int i = 0; i < pixelsPerRow; ++i) {
- destination[0] = source[0];
- destination[1] = source[1];
- destination[2] = source[2];
- destination[3] = 1;
- source += 3;
- destination += 4;
- }
-}
-
-template<> void unpack<GraphicsContext3D::DataFormatR32F, float, float>(const float* source, float* destination, unsigned pixelsPerRow)
-{
- for (unsigned int i = 0; i < pixelsPerRow; ++i) {
- destination[0] = source[0];
- destination[1] = source[0];
- destination[2] = source[0];
- destination[3] = 1;
- source += 1;
- destination += 4;
- }
-}
-
-template<> void unpack<GraphicsContext3D::DataFormatRA32F, float, float>(const float* source, float* destination, unsigned pixelsPerRow)
-{
- for (unsigned int i = 0; i < pixelsPerRow; ++i) {
- destination[0] = source[0];
- destination[1] = source[0];
- destination[2] = source[0];
- destination[3] = source[1];
- source += 2;
- destination += 4;
- }
-}
-
-template<> void unpack<GraphicsContext3D::DataFormatA32F, float, float>(const float* source, float* destination, unsigned pixelsPerRow)
-{
- for (unsigned int i = 0; i < pixelsPerRow; ++i) {
- destination[0] = 0;
- destination[1] = 0;
- destination[2] = 0;
- destination[3] = source[0];
- source += 1;
- destination += 4;
- }
-}
-
-//----------------------------------------------------------------------
-// Pixel packing routines.
-//
-
-template<int format, int alphaOp, typename SourceType, typename DstType>
-void pack(const SourceType*, DstType*, unsigned)
-{
- ASSERT_NOT_REACHED();
-}
-
-template<> void pack<GraphicsContext3D::DataFormatA8, GraphicsContext3D::AlphaDoNothing, uint8_t, uint8_t>(const uint8_t* source, uint8_t* destination, unsigned pixelsPerRow)
-{
- for (unsigned int i = 0; i < pixelsPerRow; ++i) {
- destination[0] = source[3];
- source += 4;
- destination += 1;
- }
-}
-
-template<> void pack<GraphicsContext3D::DataFormatR8, GraphicsContext3D::AlphaDoNothing, uint8_t, uint8_t>(const uint8_t* source, uint8_t* destination, unsigned pixelsPerRow)
-{
- for (unsigned int i = 0; i < pixelsPerRow; ++i) {
- destination[0] = source[0];
- source += 4;
- destination += 1;
- }
-}
-
-template<> void pack<GraphicsContext3D::DataFormatR8, GraphicsContext3D::AlphaDoPremultiply, uint8_t, uint8_t>(const uint8_t* source, uint8_t* destination, unsigned pixelsPerRow)
-{
- for (unsigned int i = 0; i < pixelsPerRow; ++i) {
- float scaleFactor = source[3] / 255.0f;
- uint8_t sourceR = static_cast<uint8_t>(static_cast<float>(source[0]) * scaleFactor);
- destination[0] = sourceR;
- source += 4;
- destination += 1;
- }
-}
-
-// FIXME: this routine is lossy and must be removed.
-template<> void pack<GraphicsContext3D::DataFormatR8, GraphicsContext3D::AlphaDoUnmultiply, uint8_t, uint8_t>(const uint8_t* source, uint8_t* destination, unsigned pixelsPerRow)
-{
- for (unsigned int i = 0; i < pixelsPerRow; ++i) {
- float scaleFactor = source[3] ? 255.0f / source[3] : 1.0f;
- uint8_t sourceR = static_cast<uint8_t>(static_cast<float>(source[0]) * scaleFactor);
- destination[0] = sourceR;
- source += 4;
- destination += 1;
- }
-}
-
-template<> void pack<GraphicsContext3D::DataFormatRA8, GraphicsContext3D::AlphaDoNothing, uint8_t, uint8_t>(const uint8_t* source, uint8_t* destination, unsigned pixelsPerRow)
-{
- for (unsigned int i = 0; i < pixelsPerRow; ++i) {
- destination[0] = source[0];
- destination[1] = source[3];
- source += 4;
- destination += 2;
- }
-}
-
-template<> void pack<GraphicsContext3D::DataFormatRA8, GraphicsContext3D::AlphaDoPremultiply, uint8_t, uint8_t>(const uint8_t* source, uint8_t* destination, unsigned pixelsPerRow)
-{
- for (unsigned int i = 0; i < pixelsPerRow; ++i) {
- float scaleFactor = source[3] / 255.0f;
- uint8_t sourceR = static_cast<uint8_t>(static_cast<float>(source[0]) * scaleFactor);
- destination[0] = sourceR;
- destination[1] = source[3];
- source += 4;
- destination += 2;
- }
-}
-
-// FIXME: this routine is lossy and must be removed.
-template<> void pack<GraphicsContext3D::DataFormatRA8, GraphicsContext3D::AlphaDoUnmultiply, uint8_t, uint8_t>(const uint8_t* source, uint8_t* destination, unsigned pixelsPerRow)
-{
- for (unsigned int i = 0; i < pixelsPerRow; ++i) {
- float scaleFactor = source[3] ? 255.0f / source[3] : 1.0f;
- uint8_t sourceR = static_cast<uint8_t>(static_cast<float>(source[0]) * scaleFactor);
- destination[0] = sourceR;
- destination[1] = source[3];
- source += 4;
- destination += 2;
- }
-}
-
-template<> void pack<GraphicsContext3D::DataFormatRGB8, GraphicsContext3D::AlphaDoNothing, uint8_t, uint8_t>(const uint8_t* source, uint8_t* destination, unsigned pixelsPerRow)
-{
- for (unsigned int i = 0; i < pixelsPerRow; ++i) {
- destination[0] = source[0];
- destination[1] = source[1];
- destination[2] = source[2];
- source += 4;
- destination += 3;
- }
-}
-
-template<> void pack<GraphicsContext3D::DataFormatRGB8, GraphicsContext3D::AlphaDoPremultiply, uint8_t, uint8_t>(const uint8_t* source, uint8_t* destination, unsigned pixelsPerRow)
-{
- for (unsigned int i = 0; i < pixelsPerRow; ++i) {
- float scaleFactor = source[3] / 255.0f;
- uint8_t sourceR = static_cast<uint8_t>(static_cast<float>(source[0]) * scaleFactor);
- uint8_t sourceG = static_cast<uint8_t>(static_cast<float>(source[1]) * scaleFactor);
- uint8_t sourceB = static_cast<uint8_t>(static_cast<float>(source[2]) * scaleFactor);
- destination[0] = sourceR;
- destination[1] = sourceG;
- destination[2] = sourceB;
- source += 4;
- destination += 3;
- }
-}
-
-// FIXME: this routine is lossy and must be removed.
-template<> void pack<GraphicsContext3D::DataFormatRGB8, GraphicsContext3D::AlphaDoUnmultiply, uint8_t, uint8_t>(const uint8_t* source, uint8_t* destination, unsigned pixelsPerRow)
-{
- for (unsigned int i = 0; i < pixelsPerRow; ++i) {
- float scaleFactor = source[3] ? 255.0f / source[3] : 1.0f;
- uint8_t sourceR = static_cast<uint8_t>(static_cast<float>(source[0]) * scaleFactor);
- uint8_t sourceG = static_cast<uint8_t>(static_cast<float>(source[1]) * scaleFactor);
- uint8_t sourceB = static_cast<uint8_t>(static_cast<float>(source[2]) * scaleFactor);
- destination[0] = sourceR;
- destination[1] = sourceG;
- destination[2] = sourceB;
- source += 4;
- destination += 3;
- }
-}
-
-
-template<> void pack<GraphicsContext3D::DataFormatRGBA8, GraphicsContext3D::AlphaDoNothing, uint8_t, uint8_t>(const uint8_t* source, uint8_t* destination, unsigned pixelsPerRow)
-{
- memcpy(destination, source, pixelsPerRow * 4);
-}
-
-template<> void pack<GraphicsContext3D::DataFormatRGBA8, GraphicsContext3D::AlphaDoPremultiply, uint8_t, uint8_t>(const uint8_t* source, uint8_t* destination, unsigned pixelsPerRow)
-{
- for (unsigned int i = 0; i < pixelsPerRow; ++i) {
- float scaleFactor = source[3] / 255.0f;
- uint8_t sourceR = static_cast<uint8_t>(static_cast<float>(source[0]) * scaleFactor);
- uint8_t sourceG = static_cast<uint8_t>(static_cast<float>(source[1]) * scaleFactor);
- uint8_t sourceB = static_cast<uint8_t>(static_cast<float>(source[2]) * scaleFactor);
- destination[0] = sourceR;
- destination[1] = sourceG;
- destination[2] = sourceB;
- destination[3] = source[3];
- source += 4;
- destination += 4;
- }
-}
-
-// FIXME: this routine is lossy and must be removed.
-template<> void pack<GraphicsContext3D::DataFormatRGBA8, GraphicsContext3D::AlphaDoUnmultiply, uint8_t, uint8_t>(const uint8_t* source, uint8_t* destination, unsigned pixelsPerRow)
-{
- for (unsigned int i = 0; i < pixelsPerRow; ++i) {
- float scaleFactor = source[3] ? 255.0f / source[3] : 1.0f;
- uint8_t sourceR = static_cast<uint8_t>(static_cast<float>(source[0]) * scaleFactor);
- uint8_t sourceG = static_cast<uint8_t>(static_cast<float>(source[1]) * scaleFactor);
- uint8_t sourceB = static_cast<uint8_t>(static_cast<float>(source[2]) * scaleFactor);
- destination[0] = sourceR;
- destination[1] = sourceG;
- destination[2] = sourceB;
- destination[3] = source[3];
- source += 4;
- destination += 4;
- }
-}
-
-template<> void pack<GraphicsContext3D::DataFormatRGBA4444, GraphicsContext3D::AlphaDoNothing, uint8_t, uint16_t>(const uint8_t* source, uint16_t* destination, unsigned pixelsPerRow)
-{
-#if HAVE(ARM_NEON_INTRINSICS)
- SIMD::packOneRowOfRGBA8ToUnsignedShort4444(source, destination, pixelsPerRow);
-#endif
- for (unsigned int i = 0; i < pixelsPerRow; ++i) {
- *destination = (((source[0] & 0xF0) << 8)
- | ((source[1] & 0xF0) << 4)
- | (source[2] & 0xF0)
- | (source[3] >> 4));
- source += 4;
- destination += 1;
- }
-}
-
-template<> void pack<GraphicsContext3D::DataFormatRGBA4444, GraphicsContext3D::AlphaDoPremultiply, uint8_t, uint16_t>(const uint8_t* source, uint16_t* destination, unsigned pixelsPerRow)
-{
- for (unsigned int i = 0; i < pixelsPerRow; ++i) {
- float scaleFactor = source[3] / 255.0f;
- uint8_t sourceR = static_cast<uint8_t>(static_cast<float>(source[0]) * scaleFactor);
- uint8_t sourceG = static_cast<uint8_t>(static_cast<float>(source[1]) * scaleFactor);
- uint8_t sourceB = static_cast<uint8_t>(static_cast<float>(source[2]) * scaleFactor);
- *destination = (((sourceR & 0xF0) << 8)
- | ((sourceG & 0xF0) << 4)
- | (sourceB & 0xF0)
- | (source[3] >> 4));
- source += 4;
- destination += 1;
- }
-}
-
-// FIXME: this routine is lossy and must be removed.
-template<> void pack<GraphicsContext3D::DataFormatRGBA4444, GraphicsContext3D::AlphaDoUnmultiply, uint8_t, uint16_t>(const uint8_t* source, uint16_t* destination, unsigned pixelsPerRow)
-{
- for (unsigned int i = 0; i < pixelsPerRow; ++i) {
- float scaleFactor = source[3] ? 255.0f / source[3] : 1.0f;
- uint8_t sourceR = static_cast<uint8_t>(static_cast<float>(source[0]) * scaleFactor);
- uint8_t sourceG = static_cast<uint8_t>(static_cast<float>(source[1]) * scaleFactor);
- uint8_t sourceB = static_cast<uint8_t>(static_cast<float>(source[2]) * scaleFactor);
- *destination = (((sourceR & 0xF0) << 8)
- | ((sourceG & 0xF0) << 4)
- | (sourceB & 0xF0)
- | (source[3] >> 4));
- source += 4;
- destination += 1;
- }
-}
-
-template<> void pack<GraphicsContext3D::DataFormatRGBA5551, GraphicsContext3D::AlphaDoNothing, uint8_t, uint16_t>(const uint8_t* source, uint16_t* destination, unsigned pixelsPerRow)
-{
-#if HAVE(ARM_NEON_INTRINSICS)
- SIMD::packOneRowOfRGBA8ToUnsignedShort5551(source, destination, pixelsPerRow);
-#endif
- for (unsigned int i = 0; i < pixelsPerRow; ++i) {
- *destination = (((source[0] & 0xF8) << 8)
- | ((source[1] & 0xF8) << 3)
- | ((source[2] & 0xF8) >> 2)
- | (source[3] >> 7));
- source += 4;
- destination += 1;
- }
-}
-
-template<> void pack<GraphicsContext3D::DataFormatRGBA5551, GraphicsContext3D::AlphaDoPremultiply, uint8_t, uint16_t>(const uint8_t* source, uint16_t* destination, unsigned pixelsPerRow)
-{
- for (unsigned int i = 0; i < pixelsPerRow; ++i) {
- float scaleFactor = source[3] / 255.0f;
- uint8_t sourceR = static_cast<uint8_t>(static_cast<float>(source[0]) * scaleFactor);
- uint8_t sourceG = static_cast<uint8_t>(static_cast<float>(source[1]) * scaleFactor);
- uint8_t sourceB = static_cast<uint8_t>(static_cast<float>(source[2]) * scaleFactor);
- *destination = (((sourceR & 0xF8) << 8)
- | ((sourceG & 0xF8) << 3)
- | ((sourceB & 0xF8) >> 2)
- | (source[3] >> 7));
- source += 4;
- destination += 1;
- }
-}
-
-// FIXME: this routine is lossy and must be removed.
-template<> void pack<GraphicsContext3D::DataFormatRGBA5551, GraphicsContext3D::AlphaDoUnmultiply, uint8_t, uint16_t>(const uint8_t* source, uint16_t* destination, unsigned pixelsPerRow)
-{
- for (unsigned int i = 0; i < pixelsPerRow; ++i) {
- float scaleFactor = source[3] ? 255.0f / source[3] : 1.0f;
- uint8_t sourceR = static_cast<uint8_t>(static_cast<float>(source[0]) * scaleFactor);
- uint8_t sourceG = static_cast<uint8_t>(static_cast<float>(source[1]) * scaleFactor);
- uint8_t sourceB = static_cast<uint8_t>(static_cast<float>(source[2]) * scaleFactor);
- *destination = (((sourceR & 0xF8) << 8)
- | ((sourceG & 0xF8) << 3)
- | ((sourceB & 0xF8) >> 2)
- | (source[3] >> 7));
- source += 4;
- destination += 1;
- }
-}
-
-template<> void pack<GraphicsContext3D::DataFormatRGB565, GraphicsContext3D::AlphaDoNothing, uint8_t, uint16_t>(const uint8_t* source, uint16_t* destination, unsigned pixelsPerRow)
-{
-#if HAVE(ARM_NEON_INTRINSICS)
- SIMD::packOneRowOfRGBA8ToUnsignedShort565(source, destination, pixelsPerRow);
-#endif
- for (unsigned int i = 0; i < pixelsPerRow; ++i) {
- *destination = (((source[0] & 0xF8) << 8)
- | ((source[1] & 0xFC) << 3)
- | ((source[2] & 0xF8) >> 3));
- source += 4;
- destination += 1;
- }
-}
-
-template<> void pack<GraphicsContext3D::DataFormatRGB565, GraphicsContext3D::AlphaDoPremultiply, uint8_t, uint16_t>(const uint8_t* source, uint16_t* destination, unsigned pixelsPerRow)
-{
- for (unsigned int i = 0; i < pixelsPerRow; ++i) {
- float scaleFactor = source[3] / 255.0f;
- uint8_t sourceR = static_cast<uint8_t>(static_cast<float>(source[0]) * scaleFactor);
- uint8_t sourceG = static_cast<uint8_t>(static_cast<float>(source[1]) * scaleFactor);
- uint8_t sourceB = static_cast<uint8_t>(static_cast<float>(source[2]) * scaleFactor);
- *destination = (((sourceR & 0xF8) << 8)
- | ((sourceG & 0xFC) << 3)
- | ((sourceB & 0xF8) >> 3));
- source += 4;
- destination += 1;
- }
-}
-
-// FIXME: this routine is lossy and must be removed.
-template<> void pack<GraphicsContext3D::DataFormatRGB565, GraphicsContext3D::AlphaDoUnmultiply, uint8_t, uint16_t>(const uint8_t* source, uint16_t* destination, unsigned pixelsPerRow)
-{
- for (unsigned int i = 0; i < pixelsPerRow; ++i) {
- float scaleFactor = source[3] ? 255.0f / source[3] : 1.0f;
- uint8_t sourceR = static_cast<uint8_t>(static_cast<float>(source[0]) * scaleFactor);
- uint8_t sourceG = static_cast<uint8_t>(static_cast<float>(source[1]) * scaleFactor);
- uint8_t sourceB = static_cast<uint8_t>(static_cast<float>(source[2]) * scaleFactor);
- *destination = (((sourceR & 0xF8) << 8)
- | ((sourceG & 0xFC) << 3)
- | ((sourceB & 0xF8) >> 3));
- source += 4;
- destination += 1;
- }
-}
-
-template<> void pack<GraphicsContext3D::DataFormatRGB32F, GraphicsContext3D::AlphaDoNothing, float, float>(const float* source, float* destination, unsigned pixelsPerRow)
-{
- for (unsigned int i = 0; i < pixelsPerRow; ++i) {
- destination[0] = source[0];
- destination[1] = source[1];
- destination[2] = source[2];
- source += 4;
- destination += 3;
- }
-}
-
-template<> void pack<GraphicsContext3D::DataFormatRGB32F, GraphicsContext3D::AlphaDoPremultiply, float, float>(const float* source, float* destination, unsigned pixelsPerRow)
-{
- for (unsigned int i = 0; i < pixelsPerRow; ++i) {
- float scaleFactor = source[3];
- destination[0] = source[0] * scaleFactor;
- destination[1] = source[1] * scaleFactor;
- destination[2] = source[2] * scaleFactor;
- source += 4;
- destination += 3;
- }
-}
-
-template<> void pack<GraphicsContext3D::DataFormatRGB32F, GraphicsContext3D::AlphaDoUnmultiply, float, float>(const float* source, float* destination, unsigned pixelsPerRow)
-{
- for (unsigned int i = 0; i < pixelsPerRow; ++i) {
- float scaleFactor = source[3] ? 1.0f / source[3] : 1.0f;
- destination[0] = source[0] * scaleFactor;
- destination[1] = source[1] * scaleFactor;
- destination[2] = source[2] * scaleFactor;
- source += 4;
- destination += 3;
- }
-}
-
-// Used only during RGBA8 or BGRA8 -> floating-point uploads.
-template<> void pack<GraphicsContext3D::DataFormatRGBA32F, GraphicsContext3D::AlphaDoNothing, float, float>(const float* source, float* destination, unsigned pixelsPerRow)
-{
- memcpy(destination, source, pixelsPerRow * 4 * sizeof(float));
-}
-
-template<> void pack<GraphicsContext3D::DataFormatRGBA32F, GraphicsContext3D::AlphaDoPremultiply, float, float>(const float* source, float* destination, unsigned pixelsPerRow)
-{
- for (unsigned int i = 0; i < pixelsPerRow; ++i) {
- float scaleFactor = source[3];
- destination[0] = source[0] * scaleFactor;
- destination[1] = source[1] * scaleFactor;
- destination[2] = source[2] * scaleFactor;
- destination[3] = source[3];
- source += 4;
- destination += 4;
- }
-}
-
-template<> void pack<GraphicsContext3D::DataFormatRGBA32F, GraphicsContext3D::AlphaDoUnmultiply, float, float>(const float* source, float* destination, unsigned pixelsPerRow)
-{
- for (unsigned int i = 0; i < pixelsPerRow; ++i) {
- float scaleFactor = source[3] ? 1.0f / source[3] : 1.0f;
- destination[0] = source[0] * scaleFactor;
- destination[1] = source[1] * scaleFactor;
- destination[2] = source[2] * scaleFactor;
- destination[3] = source[3];
- source += 4;
- destination += 4;
- }
-}
-
-template<> void pack<GraphicsContext3D::DataFormatA32F, GraphicsContext3D::AlphaDoNothing, float, float>(const float* source, float* destination, unsigned pixelsPerRow)
-{
- for (unsigned int i = 0; i < pixelsPerRow; ++i) {
- destination[0] = source[3];
- source += 4;
- destination += 1;
- }
-}
-
-template<> void pack<GraphicsContext3D::DataFormatR32F, GraphicsContext3D::AlphaDoNothing, float, float>(const float* source, float* destination, unsigned pixelsPerRow)
-{
- for (unsigned int i = 0; i < pixelsPerRow; ++i) {
- destination[0] = source[0];
- source += 4;
- destination += 1;
- }
-}
-
-template<> void pack<GraphicsContext3D::DataFormatR32F, GraphicsContext3D::AlphaDoPremultiply, float, float>(const float* source, float* destination, unsigned pixelsPerRow)
-{
- for (unsigned int i = 0; i < pixelsPerRow; ++i) {
- float scaleFactor = source[3];
- destination[0] = source[0] * scaleFactor;
- source += 4;
- destination += 1;
- }
-}
-
-template<> void pack<GraphicsContext3D::DataFormatR32F, GraphicsContext3D::AlphaDoUnmultiply, float, float>(const float* source, float* destination, unsigned pixelsPerRow)
-{
- for (unsigned int i = 0; i < pixelsPerRow; ++i) {
- float scaleFactor = source[3] ? 1.0f / source[3] : 1.0f;
- destination[0] = source[0] * scaleFactor;
- source += 4;
- destination += 1;
- }
-}
-
-template<> void pack<GraphicsContext3D::DataFormatRA32F, GraphicsContext3D::AlphaDoNothing, float, float>(const float* source, float* destination, unsigned pixelsPerRow)
-{
- for (unsigned int i = 0; i < pixelsPerRow; ++i) {
- destination[0] = source[0];
- destination[1] = source[3];
- source += 4;
- destination += 2;
- }
-}
-
-template<> void pack<GraphicsContext3D::DataFormatRA32F, GraphicsContext3D::AlphaDoPremultiply, float, float>(const float* source, float* destination, unsigned pixelsPerRow)
-{
- for (unsigned int i = 0; i < pixelsPerRow; ++i) {
- float scaleFactor = source[3];
- destination[0] = source[0] * scaleFactor;
- destination[1] = source[3];
- source += 4;
- destination += 2;
- }
-}
-
-template<> void pack<GraphicsContext3D::DataFormatRA32F, GraphicsContext3D::AlphaDoUnmultiply, float, float>(const float* source, float* destination, unsigned pixelsPerRow)
-{
- for (unsigned int i = 0; i < pixelsPerRow; ++i) {
- float scaleFactor = source[3] ? 1.0f / source[3] : 1.0f;
- destination[0] = source[0] * scaleFactor;
- destination[1] = source[3];
- source += 4;
- destination += 2;
- }
-}
-
-template<> void pack<GraphicsContext3D::DataFormatRGBA16F, GraphicsContext3D::AlphaDoNothing, float, uint16_t>(const float* source, uint16_t* destination, unsigned pixelsPerRow)
-{
- for (unsigned i = 0; i < pixelsPerRow; ++i) {
- destination[0] = convertFloatToHalfFloat(source[0]);
- destination[1] = convertFloatToHalfFloat(source[1]);
- destination[2] = convertFloatToHalfFloat(source[2]);
- destination[3] = convertFloatToHalfFloat(source[3]);
- source += 4;
- destination += 4;
- }
-}
-
-template<> void pack<GraphicsContext3D::DataFormatRGBA16F, GraphicsContext3D::AlphaDoPremultiply, float, uint16_t>(const float* source, uint16_t* destination, unsigned pixelsPerRow)
-{
- for (unsigned i = 0; i < pixelsPerRow; ++i) {
- float scaleFactor = source[3];
- destination[0] = convertFloatToHalfFloat(source[0] * scaleFactor);
- destination[1] = convertFloatToHalfFloat(source[1] * scaleFactor);
- destination[2] = convertFloatToHalfFloat(source[2] * scaleFactor);
- destination[3] = convertFloatToHalfFloat(source[3]);
- source += 4;
- destination += 4;
- }
-}
-
-template<> void pack<GraphicsContext3D::DataFormatRGBA16F, GraphicsContext3D::AlphaDoUnmultiply, float, uint16_t>(const float* source, uint16_t* destination, unsigned pixelsPerRow)
-{
- for (unsigned i = 0; i < pixelsPerRow; ++i) {
- float scaleFactor = source[3] ? 1.0f / source[3] : 1.0f;
- destination[0] = convertFloatToHalfFloat(source[0] * scaleFactor);
- destination[1] = convertFloatToHalfFloat(source[1] * scaleFactor);
- destination[2] = convertFloatToHalfFloat(source[2] * scaleFactor);
- destination[3] = convertFloatToHalfFloat(source[3]);
- source += 4;
- destination += 4;
- }
-}
-
-template<> void pack<GraphicsContext3D::DataFormatRGB16F, GraphicsContext3D::AlphaDoNothing, float, uint16_t>(const float* source, uint16_t* destination, unsigned pixelsPerRow)
-{
- for (unsigned i = 0; i < pixelsPerRow; ++i) {
- destination[0] = convertFloatToHalfFloat(source[0]);
- destination[1] = convertFloatToHalfFloat(source[1]);
- destination[2] = convertFloatToHalfFloat(source[2]);
- source += 4;
- destination += 3;
- }
-}
-
-template<> void pack<GraphicsContext3D::DataFormatRGB16F, GraphicsContext3D::AlphaDoPremultiply, float, uint16_t>(const float* source, uint16_t* destination, unsigned pixelsPerRow)
-{
- for (unsigned i = 0; i < pixelsPerRow; ++i) {
- float scaleFactor = source[3];
- destination[0] = convertFloatToHalfFloat(source[0] * scaleFactor);
- destination[1] = convertFloatToHalfFloat(source[1] * scaleFactor);
- destination[2] = convertFloatToHalfFloat(source[2] * scaleFactor);
- source += 4;
- destination += 3;
- }
-}
-
-template<> void pack<GraphicsContext3D::DataFormatRGB16F, GraphicsContext3D::AlphaDoUnmultiply, float, uint16_t>(const float* source, uint16_t* destination, unsigned pixelsPerRow)
-{
- for (unsigned i = 0; i < pixelsPerRow; ++i) {
- float scaleFactor = source[3] ? 1.0f / source[3] : 1.0f;
- destination[0] = convertFloatToHalfFloat(source[0] * scaleFactor);
- destination[1] = convertFloatToHalfFloat(source[1] * scaleFactor);
- destination[2] = convertFloatToHalfFloat(source[2] * scaleFactor);
- source += 4;
- destination += 3;
- }
-}
-
-template<> void pack<GraphicsContext3D::DataFormatRA16F, GraphicsContext3D::AlphaDoNothing, float, uint16_t>(const float* source, uint16_t* destination, unsigned pixelsPerRow)
-{
- for (unsigned i = 0; i < pixelsPerRow; ++i) {
- destination[0] = convertFloatToHalfFloat(source[0]);
- destination[1] = convertFloatToHalfFloat(source[3]);
- source += 4;
- destination += 2;
- }
-}
-
-template<> void pack<GraphicsContext3D::DataFormatRA16F, GraphicsContext3D::AlphaDoPremultiply, float, uint16_t>(const float* source, uint16_t* destination, unsigned pixelsPerRow)
-{
- for (unsigned i = 0; i < pixelsPerRow; ++i) {
- float scaleFactor = source[3];
- destination[0] = convertFloatToHalfFloat(source[0] * scaleFactor);
- destination[1] = convertFloatToHalfFloat(source[3]);
- source += 4;
- destination += 2;
- }
-}
-
-template<> void pack<GraphicsContext3D::DataFormatRA16F, GraphicsContext3D::AlphaDoUnmultiply, float, uint16_t>(const float* source, uint16_t* destination, unsigned pixelsPerRow)
-{
- for (unsigned i = 0; i < pixelsPerRow; ++i) {
- float scaleFactor = source[3] ? 1.0f / source[3] : 1.0f;
- destination[0] = convertFloatToHalfFloat(source[0] * scaleFactor);
- destination[1] = convertFloatToHalfFloat(source[3]);
- source += 4;
- destination += 2;
- }
-}
-
-template<> void pack<GraphicsContext3D::DataFormatR16F, GraphicsContext3D::AlphaDoNothing, float, uint16_t>(const float* source, uint16_t* destination, unsigned pixelsPerRow)
-{
- for (unsigned i = 0; i < pixelsPerRow; ++i) {
- destination[0] = convertFloatToHalfFloat(source[0]);
- source += 4;
- destination += 1;
- }
-}
-
-template<> void pack<GraphicsContext3D::DataFormatR16F, GraphicsContext3D::AlphaDoPremultiply, float, uint16_t>(const float* source, uint16_t* destination, unsigned pixelsPerRow)
-{
- for (unsigned i = 0; i < pixelsPerRow; ++i) {
- float scaleFactor = source[3];
- destination[0] = convertFloatToHalfFloat(source[0] * scaleFactor);
- source += 4;
- destination += 1;
- }
-}
-
-template<> void pack<GraphicsContext3D::DataFormatR16F, GraphicsContext3D::AlphaDoUnmultiply, float, uint16_t>(const float* source, uint16_t* destination, unsigned pixelsPerRow)
-{
- for (unsigned i = 0; i < pixelsPerRow; ++i) {
- float scaleFactor = source[3] ? 1.0f / source[3] : 1.0f;
- destination[0] = convertFloatToHalfFloat(source[0] * scaleFactor);
- source += 4;
- destination += 1;
- }
-}
-
-template<> void pack<GraphicsContext3D::DataFormatA16F, GraphicsContext3D::AlphaDoNothing, float, uint16_t>(const float* source, uint16_t* destination, unsigned pixelsPerRow)
-{
- for (unsigned i = 0; i < pixelsPerRow; ++i) {
- destination[0] = convertFloatToHalfFloat(source[3]);
- source += 4;
- destination += 1;
- }
-}
-
-bool HasAlpha(int format)
-{
- return format == GraphicsContext3D::DataFormatA8
- || format == GraphicsContext3D::DataFormatA16F
- || format == GraphicsContext3D::DataFormatA32F
- || format == GraphicsContext3D::DataFormatRA8
- || format == GraphicsContext3D::DataFormatAR8
- || format == GraphicsContext3D::DataFormatRA16F
- || format == GraphicsContext3D::DataFormatRA32F
- || format == GraphicsContext3D::DataFormatRGBA8
- || format == GraphicsContext3D::DataFormatBGRA8
- || format == GraphicsContext3D::DataFormatARGB8
- || format == GraphicsContext3D::DataFormatABGR8
- || format == GraphicsContext3D::DataFormatRGBA16F
- || format == GraphicsContext3D::DataFormatRGBA32F
- || format == GraphicsContext3D::DataFormatRGBA4444
- || format == GraphicsContext3D::DataFormatRGBA5551;
-}
-
-bool HasColor(int format)
-{
- return format == GraphicsContext3D::DataFormatRGBA8
- || format == GraphicsContext3D::DataFormatRGBA16F
- || format == GraphicsContext3D::DataFormatRGBA32F
- || format == GraphicsContext3D::DataFormatRGB8
- || format == GraphicsContext3D::DataFormatRGB16F
- || format == GraphicsContext3D::DataFormatRGB32F
- || format == GraphicsContext3D::DataFormatBGR8
- || format == GraphicsContext3D::DataFormatBGRA8
- || format == GraphicsContext3D::DataFormatARGB8
- || format == GraphicsContext3D::DataFormatABGR8
- || format == GraphicsContext3D::DataFormatRGBA5551
- || format == GraphicsContext3D::DataFormatRGBA4444
- || format == GraphicsContext3D::DataFormatRGB565
- || format == GraphicsContext3D::DataFormatR8
- || format == GraphicsContext3D::DataFormatR16F
- || format == GraphicsContext3D::DataFormatR32F
- || format == GraphicsContext3D::DataFormatRA8
- || format == GraphicsContext3D::DataFormatRA16F
- || format == GraphicsContext3D::DataFormatRA32F
- || format == GraphicsContext3D::DataFormatAR8;
-}
-
-template<int Format>
-struct IsFloatFormat {
- static const bool Value =
- Format == GraphicsContext3D::DataFormatRGBA32F
- || Format == GraphicsContext3D::DataFormatRGB32F
- || Format == GraphicsContext3D::DataFormatRA32F
- || Format == GraphicsContext3D::DataFormatR32F
- || Format == GraphicsContext3D::DataFormatA32F;
-};
-
-template<int Format>
-struct IsHalfFloatFormat {
- static const bool Value =
- Format == GraphicsContext3D::DataFormatRGBA16F
- || Format == GraphicsContext3D::DataFormatRGB16F
- || Format == GraphicsContext3D::DataFormatRA16F
- || Format == GraphicsContext3D::DataFormatR16F
- || Format == GraphicsContext3D::DataFormatA16F;
-};
-
-template<int Format>
-struct Is16bppFormat {
- static const bool Value =
- Format == GraphicsContext3D::DataFormatRGBA5551
- || Format == GraphicsContext3D::DataFormatRGBA4444
- || Format == GraphicsContext3D::DataFormatRGB565;
-};
-
-template<int Format, bool IsFloat = IsFloatFormat<Format>::Value, bool IsHalfFloat = IsHalfFloatFormat<Format>::Value, bool Is16bpp = Is16bppFormat<Format>::Value>
-struct DataTypeForFormat {
- typedef uint8_t Type;
-};
-
-template<int Format>
-struct DataTypeForFormat<Format, true, false, false> {
- typedef float Type;
-};
-
-template<int Format>
-struct DataTypeForFormat<Format, false, true, false> {
- typedef uint16_t Type;
-};
-
-template<int Format>
-struct DataTypeForFormat<Format, false, false, true> {
- typedef uint16_t Type;
-};
-
-template<int Format>
-struct IntermediateFormat {
- static const int Value = (IsFloatFormat<Format>::Value || IsHalfFloatFormat<Format>::Value) ? GraphicsContext3D::DataFormatRGBA32F : GraphicsContext3D::DataFormatRGBA8;
-};
-
-unsigned TexelBytesForFormat(GraphicsContext3D::DataFormat format)
-{
- switch (format) {
- case GraphicsContext3D::DataFormatR8:
- case GraphicsContext3D::DataFormatA8:
- return 1;
- case GraphicsContext3D::DataFormatRA8:
- case GraphicsContext3D::DataFormatAR8:
- case GraphicsContext3D::DataFormatRGBA5551:
- case GraphicsContext3D::DataFormatRGBA4444:
- case GraphicsContext3D::DataFormatRGB565:
- case GraphicsContext3D::DataFormatA16F:
- case GraphicsContext3D::DataFormatR16F:
- return 2;
- case GraphicsContext3D::DataFormatRGB8:
- case GraphicsContext3D::DataFormatBGR8:
- return 3;
- case GraphicsContext3D::DataFormatRGBA8:
- case GraphicsContext3D::DataFormatARGB8:
- case GraphicsContext3D::DataFormatABGR8:
- case GraphicsContext3D::DataFormatBGRA8:
- case GraphicsContext3D::DataFormatR32F:
- case GraphicsContext3D::DataFormatA32F:
- case GraphicsContext3D::DataFormatRA16F:
- return 4;
- case GraphicsContext3D::DataFormatRGB16F:
- return 6;
- case GraphicsContext3D::DataFormatRA32F:
- case GraphicsContext3D::DataFormatRGBA16F:
- return 8;
- case GraphicsContext3D::DataFormatRGB32F:
- return 12;
- case GraphicsContext3D::DataFormatRGBA32F:
- return 16;
- default:
- return 0;
- }
-}
-
-/* END CODE SHARED WITH MOZILLA FIREFOX */
-
-class FormatConverter {
-public:
- FormatConverter(unsigned width, unsigned height,
- const void* srcStart, void* dstStart, int srcStride, int dstStride)
- : m_width(width), m_height(height), m_srcStart(srcStart), m_dstStart(dstStart), m_srcStride(srcStride), m_dstStride(dstStride), m_success(false)
- {
- const unsigned MaxNumberOfComponents = 4;
- const unsigned MaxBytesPerComponent = 4;
- m_unpackedIntermediateSrcData = adoptArrayPtr(new uint8_t[m_width * MaxNumberOfComponents *MaxBytesPerComponent]);
- ASSERT(m_unpackedIntermediateSrcData.get());
- }
-
- void convert(GraphicsContext3D::DataFormat srcFormat, GraphicsContext3D::DataFormat dstFormat, GraphicsContext3D::AlphaOp);
- bool Success() const { return m_success; }
-
-private:
- template<GraphicsContext3D::DataFormat SrcFormat>
- void convert(GraphicsContext3D::DataFormat dstFormat, GraphicsContext3D::AlphaOp);
-
- template<GraphicsContext3D::DataFormat SrcFormat, GraphicsContext3D::DataFormat DstFormat>
- void convert(GraphicsContext3D::AlphaOp);
-
- template<GraphicsContext3D::DataFormat SrcFormat, GraphicsContext3D::DataFormat DstFormat, GraphicsContext3D::AlphaOp alphaOp>
- void convert();
-
- const unsigned m_width, m_height;
- const void* const m_srcStart;
- void* const m_dstStart;
- const int m_srcStride, m_dstStride;
- bool m_success;
- OwnArrayPtr<uint8_t> m_unpackedIntermediateSrcData;
-};
-
-void FormatConverter::convert(GraphicsContext3D::DataFormat srcFormat, GraphicsContext3D::DataFormat dstFormat, GraphicsContext3D::AlphaOp alphaOp)
-{
-#define FORMATCONVERTER_CASE_SRCFORMAT(SrcFormat) \
- case SrcFormat: \
- return convert<SrcFormat>(dstFormat, alphaOp);
-
- switch (srcFormat) {
- FORMATCONVERTER_CASE_SRCFORMAT(GraphicsContext3D::DataFormatR8)
- FORMATCONVERTER_CASE_SRCFORMAT(GraphicsContext3D::DataFormatA8)
- FORMATCONVERTER_CASE_SRCFORMAT(GraphicsContext3D::DataFormatR32F)
- FORMATCONVERTER_CASE_SRCFORMAT(GraphicsContext3D::DataFormatA32F)
- FORMATCONVERTER_CASE_SRCFORMAT(GraphicsContext3D::DataFormatRA8)
- FORMATCONVERTER_CASE_SRCFORMAT(GraphicsContext3D::DataFormatRA32F)
- FORMATCONVERTER_CASE_SRCFORMAT(GraphicsContext3D::DataFormatRGB8)
- FORMATCONVERTER_CASE_SRCFORMAT(GraphicsContext3D::DataFormatBGR8)
- FORMATCONVERTER_CASE_SRCFORMAT(GraphicsContext3D::DataFormatRGB565)
- FORMATCONVERTER_CASE_SRCFORMAT(GraphicsContext3D::DataFormatRGB32F)
- FORMATCONVERTER_CASE_SRCFORMAT(GraphicsContext3D::DataFormatRGBA8)
- FORMATCONVERTER_CASE_SRCFORMAT(GraphicsContext3D::DataFormatARGB8)
- FORMATCONVERTER_CASE_SRCFORMAT(GraphicsContext3D::DataFormatABGR8)
- FORMATCONVERTER_CASE_SRCFORMAT(GraphicsContext3D::DataFormatAR8)
- FORMATCONVERTER_CASE_SRCFORMAT(GraphicsContext3D::DataFormatBGRA8)
- FORMATCONVERTER_CASE_SRCFORMAT(GraphicsContext3D::DataFormatRGBA5551)
- FORMATCONVERTER_CASE_SRCFORMAT(GraphicsContext3D::DataFormatRGBA4444)
- FORMATCONVERTER_CASE_SRCFORMAT(GraphicsContext3D::DataFormatRGBA32F)
- default:
- ASSERT_NOT_REACHED();
- }
-#undef FORMATCONVERTER_CASE_SRCFORMAT
-}
-
-template<GraphicsContext3D::DataFormat SrcFormat>
-void FormatConverter::convert(GraphicsContext3D::DataFormat dstFormat, GraphicsContext3D::AlphaOp alphaOp)
-{
-#define FORMATCONVERTER_CASE_DSTFORMAT(DstFormat) \
- case DstFormat: \
- return convert<SrcFormat, DstFormat>(alphaOp);
-
- switch (dstFormat) {
- FORMATCONVERTER_CASE_DSTFORMAT(GraphicsContext3D::DataFormatR8)
- FORMATCONVERTER_CASE_DSTFORMAT(GraphicsContext3D::DataFormatR16F)
- FORMATCONVERTER_CASE_DSTFORMAT(GraphicsContext3D::DataFormatR32F)
- FORMATCONVERTER_CASE_DSTFORMAT(GraphicsContext3D::DataFormatA8)
- FORMATCONVERTER_CASE_DSTFORMAT(GraphicsContext3D::DataFormatA16F)
- FORMATCONVERTER_CASE_DSTFORMAT(GraphicsContext3D::DataFormatA32F)
- FORMATCONVERTER_CASE_DSTFORMAT(GraphicsContext3D::DataFormatRA8)
- FORMATCONVERTER_CASE_DSTFORMAT(GraphicsContext3D::DataFormatRA16F)
- FORMATCONVERTER_CASE_DSTFORMAT(GraphicsContext3D::DataFormatRA32F)
- FORMATCONVERTER_CASE_DSTFORMAT(GraphicsContext3D::DataFormatRGB8)
- FORMATCONVERTER_CASE_DSTFORMAT(GraphicsContext3D::DataFormatRGB565)
- FORMATCONVERTER_CASE_DSTFORMAT(GraphicsContext3D::DataFormatRGB16F)
- FORMATCONVERTER_CASE_DSTFORMAT(GraphicsContext3D::DataFormatRGB32F)
- FORMATCONVERTER_CASE_DSTFORMAT(GraphicsContext3D::DataFormatRGBA8)
- FORMATCONVERTER_CASE_DSTFORMAT(GraphicsContext3D::DataFormatRGBA5551)
- FORMATCONVERTER_CASE_DSTFORMAT(GraphicsContext3D::DataFormatRGBA4444)
- FORMATCONVERTER_CASE_DSTFORMAT(GraphicsContext3D::DataFormatRGBA16F)
- FORMATCONVERTER_CASE_DSTFORMAT(GraphicsContext3D::DataFormatRGBA32F)
- default:
- ASSERT_NOT_REACHED();
- }
-
-#undef FORMATCONVERTER_CASE_DSTFORMAT
-}
-
-template<GraphicsContext3D::DataFormat SrcFormat, GraphicsContext3D::DataFormat DstFormat>
-void FormatConverter::convert(GraphicsContext3D::AlphaOp alphaOp)
-{
-#define FORMATCONVERTER_CASE_ALPHAOP(alphaOp) \
- case alphaOp: \
- return convert<SrcFormat, DstFormat, alphaOp>();
-
- switch (alphaOp) {
- FORMATCONVERTER_CASE_ALPHAOP(GraphicsContext3D::AlphaDoNothing)
- FORMATCONVERTER_CASE_ALPHAOP(GraphicsContext3D::AlphaDoPremultiply)
- FORMATCONVERTER_CASE_ALPHAOP(GraphicsContext3D::AlphaDoUnmultiply)
- default:
- ASSERT_NOT_REACHED();
- }
-#undef FORMATCONVERTER_CASE_ALPHAOP
-}
-
-template<GraphicsContext3D::DataFormat SrcFormat, GraphicsContext3D::DataFormat DstFormat, GraphicsContext3D::AlphaOp alphaOp>
-void FormatConverter::convert()
-{
- // Many instantiations of this template function will never be entered, so we try
- // to return immediately in these cases to avoid the compiler to generate useless code.
- if (SrcFormat == DstFormat && alphaOp == GraphicsContext3D::AlphaDoNothing) {
- ASSERT_NOT_REACHED();
- return;
- }
- if (!IsFloatFormat<DstFormat>::Value && IsFloatFormat<SrcFormat>::Value) {
- ASSERT_NOT_REACHED();
- return;
- }
-
- // Only textures uploaded from DOM elements or ImageData can allow DstFormat != SrcFormat.
- const bool srcFormatComesFromDOMElementOrImageData = GraphicsContext3D::srcFormatComeFromDOMElementOrImageData(SrcFormat);
- if (!srcFormatComesFromDOMElementOrImageData && SrcFormat != DstFormat) {
- ASSERT_NOT_REACHED();
- return;
- }
- // Likewise, only textures uploaded from DOM elements or ImageData can possibly have to be unpremultiplied.
- if (!srcFormatComesFromDOMElementOrImageData && alphaOp == GraphicsContext3D::AlphaDoUnmultiply) {
- ASSERT_NOT_REACHED();
- return;
- }
- if ((!HasAlpha(SrcFormat) || !HasColor(SrcFormat) || !HasColor(DstFormat)) && alphaOp != GraphicsContext3D::AlphaDoNothing) {
- ASSERT_NOT_REACHED();
- return;
- }
-
- typedef typename DataTypeForFormat<SrcFormat>::Type SrcType;
- typedef typename DataTypeForFormat<DstFormat>::Type DstType;
- const int IntermediateSrcFormat = IntermediateFormat<DstFormat>::Value;
- typedef typename DataTypeForFormat<IntermediateSrcFormat>::Type IntermediateSrcType;
- const ptrdiff_t srcStrideInElements = m_srcStride / sizeof(SrcType);
- const ptrdiff_t dstStrideInElements = m_dstStride / sizeof(DstType);
- const bool trivialUnpack = (SrcFormat == GraphicsContext3D::DataFormatRGBA8 && !IsFloatFormat<DstFormat>::Value && !IsHalfFloatFormat<DstFormat>::Value) || SrcFormat == GraphicsContext3D::DataFormatRGBA32F;
- const bool trivialPack = (DstFormat == GraphicsContext3D::DataFormatRGBA8 || DstFormat == GraphicsContext3D::DataFormatRGBA32F) && alphaOp == GraphicsContext3D::AlphaDoNothing && m_dstStride > 0;
- ASSERT(!trivialUnpack || !trivialPack);
-
- const SrcType *srcRowStart = static_cast<const SrcType*>(m_srcStart);
- DstType* dstRowStart = static_cast<DstType*>(m_dstStart);
- if (!trivialUnpack && trivialPack) {
- for (size_t i = 0; i < m_height; ++i) {
- unpack<SrcFormat>(srcRowStart, dstRowStart, m_width);
- srcRowStart += srcStrideInElements;
- dstRowStart += dstStrideInElements;
- }
- } else if (!trivialUnpack && !trivialPack) {
- for (size_t i = 0; i < m_height; ++i) {
- unpack<SrcFormat>(srcRowStart, reinterpret_cast<IntermediateSrcType*>(m_unpackedIntermediateSrcData.get()), m_width);
- pack<DstFormat, alphaOp>(reinterpret_cast<IntermediateSrcType*>(m_unpackedIntermediateSrcData.get()), dstRowStart, m_width);
- srcRowStart += srcStrideInElements;
- dstRowStart += dstStrideInElements;
- }
- } else {
- for (size_t i = 0; i < m_height; ++i) {
- pack<DstFormat, alphaOp>(srcRowStart, dstRowStart, m_width);
- srcRowStart += srcStrideInElements;
- dstRowStart += dstStrideInElements;
- }
- }
- m_success = true;
- return;
-}
-
-} // anonymous namespace
-
-bool GraphicsContext3D::packImageData(
- Image* image,
- const void* pixels,
- GC3Denum format,
- GC3Denum type,
- bool flipY,
- AlphaOp alphaOp,
- DataFormat sourceFormat,
- unsigned width,
- unsigned height,
- unsigned sourceUnpackAlignment,
- Vector<uint8_t>& data)
-{
- if (!pixels)
- return false;
-
- unsigned packedSize;
- // Output data is tightly packed (alignment == 1).
- if (computeImageSizeInBytes(format, type, width, height, 1, &packedSize, 0) != GraphicsContext3D::NO_ERROR)
- return false;
- data.resize(packedSize);
-
- if (!packPixels(reinterpret_cast<const uint8_t*>(pixels), sourceFormat, width, height, sourceUnpackAlignment, format, type, alphaOp, data.data(), flipY))
- return false;
- if (ImageObserver *observer = image->imageObserver())
- observer->didDraw(image);
- return true;
-}
-
-bool GraphicsContext3D::extractImageData(
- ImageData* imageData,
- GC3Denum format,
- GC3Denum type,
- bool flipY,
- bool premultiplyAlpha,
- Vector<uint8_t>& data)
-{
- if (!imageData)
- return false;
- int width = imageData->width();
- int height = imageData->height();
-
- unsigned packedSize;
- // Output data is tightly packed (alignment == 1).
- if (computeImageSizeInBytes(format, type, width, height, 1, &packedSize, 0) != GraphicsContext3D::NO_ERROR)
- return false;
- data.resize(packedSize);
-
- if (!packPixels(imageData->data()->data(), DataFormatRGBA8, width, height, 0, format, type, premultiplyAlpha ? AlphaDoPremultiply : AlphaDoNothing, data.data(), flipY))
- return false;
-
- return true;
-}
-
-bool GraphicsContext3D::extractTextureData(
- unsigned width,
- unsigned height,
- GC3Denum format, GC3Denum type,
- unsigned unpackAlignment,
- bool flipY, bool premultiplyAlpha,
- const void* pixels,
- Vector<uint8_t>& data)
-{
- // Assumes format, type, etc. have already been validated.
- DataFormat sourceDataFormat = getDataFormat(format, type);
-
- // Resize the output buffer.
- unsigned int componentsPerPixel, bytesPerComponent;
- if (!computeFormatAndTypeParameters(format, type, &componentsPerPixel, &bytesPerComponent))
- return false;
- unsigned bytesPerPixel = componentsPerPixel * bytesPerComponent;
- data.resize(width * height * bytesPerPixel);
-
- if (!packPixels(static_cast<const uint8_t*>(pixels), sourceDataFormat, width, height, unpackAlignment, format, type, (premultiplyAlpha ? AlphaDoPremultiply : AlphaDoNothing), data.data(), flipY))
- return false;
-
- return true;
-}
-
-bool GraphicsContext3D::packPixels(
- const uint8_t* sourceData,
- DataFormat sourceDataFormat,
- unsigned width,
- unsigned height,
- unsigned sourceUnpackAlignment,
- unsigned destinationFormat,
- unsigned destinationType,
- AlphaOp alphaOp,
- void* destinationData,
- bool flipY)
-{
- int validSrc = width * TexelBytesForFormat(sourceDataFormat);
- int remainder = sourceUnpackAlignment ? (validSrc % sourceUnpackAlignment) : 0;
- int srcStride = remainder ? (validSrc + sourceUnpackAlignment - remainder) : validSrc;
-
- DataFormat dstDataFormat = getDataFormat(destinationFormat, destinationType);
- int dstStride = width * TexelBytesForFormat(dstDataFormat);
- if (flipY) {
- destinationData = static_cast<uint8_t*>(destinationData) + dstStride*(height - 1);
- dstStride = -dstStride;
- }
- if (!HasAlpha(sourceDataFormat) || !HasColor(sourceDataFormat) || !HasColor(dstDataFormat))
- alphaOp = AlphaDoNothing;
-
- if (sourceDataFormat == dstDataFormat && alphaOp == AlphaDoNothing) {
- const uint8_t* ptr = sourceData;
- const uint8_t* ptrEnd = sourceData + srcStride * height;
- unsigned rowSize = (dstStride > 0) ? dstStride: -dstStride;
- uint8_t* dst = static_cast<uint8_t*>(destinationData);
- while (ptr < ptrEnd) {
- memcpy(dst, ptr, rowSize);
- ptr += srcStride;
- dst += dstStride;
- }
- return true;
- }
-
- FormatConverter converter(width, height, sourceData, destinationData, srcStride, dstStride);
- converter.convert(sourceDataFormat, dstDataFormat, alphaOp);
- if (!converter.Success())
- return false;
- return true;
-}
-
-} // namespace WebCore
-
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsContextAnnotation.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsContextAnnotation.cpp
deleted file mode 100644
index 1ca9824a11d..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsContextAnnotation.cpp
+++ /dev/null
@@ -1,159 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/GraphicsContextAnnotation.h"
-
-#include "core/platform/graphics/GraphicsContext.h"
-#include "core/rendering/PaintInfo.h"
-#include "core/rendering/PaintPhase.h"
-#include "core/rendering/RenderObject.h"
-#include "wtf/text/StringBuilder.h"
-
-namespace {
-
-const char* AnnotationKeyRendererName = "RENDERER";
-const char* AnnotationKeyPaintPhase = "PHASE";
-const char* AnnotationKeyElementId = "ID";
-const char* AnnotationKeyElementClass = "CLASS";
-const char* AnnotationKeyElementTag = "TAG";
-
-static const char* paintPhaseName(WebCore::PaintPhase phase)
-{
- switch (phase) {
- case WebCore::PaintPhaseBlockBackground:
- return "BlockBackground";
- case WebCore::PaintPhaseChildBlockBackground:
- return "ChildBlockBackground";
- case WebCore::PaintPhaseChildBlockBackgrounds:
- return "ChildBlockBackgrounds";
- case WebCore::PaintPhaseFloat:
- return "Float";
- case WebCore::PaintPhaseForeground:
- return "Foreground";
- case WebCore::PaintPhaseOutline:
- return "Outline";
- case WebCore::PaintPhaseChildOutlines:
- return "ChildOutlines";
- case WebCore::PaintPhaseSelfOutline:
- return "SelfOutline";
- case WebCore::PaintPhaseSelection:
- return "Selection";
- case WebCore::PaintPhaseCollapsedTableBorders:
- return "CollapsedTableBorders";
- case WebCore::PaintPhaseTextClip:
- return "TextClip";
- case WebCore::PaintPhaseMask:
- return "Mask";
- default:
- ASSERT_NOT_REACHED();
- return "<unknown>";
- }
-}
-
-}
-
-namespace WebCore {
-
-GraphicsContextAnnotation::GraphicsContextAnnotation(const PaintInfo& paintInfo, const RenderObject* object)
- : m_rendererName(0)
- , m_paintPhase(0)
-{
- ASSERT(paintInfo.context);
- ASSERT(object);
-
- AnnotationModeFlags mode = paintInfo.context->annotationMode();
- Element* element = object->node() && object->node()->isElementNode() ? toElement(object->node()) : 0;
-
- if (mode & AnnotateRendererName)
- m_rendererName = object->renderName();
-
- if (mode & AnnotatePaintPhase)
- m_paintPhase = paintPhaseName(paintInfo.phase);
-
- if ((mode & AnnotateElementId) && element) {
- const AtomicString id = element->getIdAttribute();
- if (!id.isNull() && !id.isEmpty())
- m_elementId = id.string();
- }
-
- if ((mode & AnnotateElementClass) && element && element->hasClass()) {
- SpaceSplitString classes = element->classNames();
- if (!classes.isNull() && classes.size() > 0) {
- StringBuilder classBuilder;
- for (size_t i = 0; i < classes.size(); ++i) {
- if (i > 0)
- classBuilder.append(" ");
- classBuilder.append(classes[i]);
- }
-
- m_elementClass = classBuilder.toString();
- }
- }
-
- if ((mode & AnnotateElementTag) && element)
- m_elementTag = element->tagName();
-}
-
-void GraphicsContextAnnotation::asAnnotationList(AnnotationList &list) const
-{
- list.clear();
-
- if (m_rendererName)
- list.append(std::make_pair(AnnotationKeyRendererName, m_rendererName));
-
- if (m_paintPhase)
- list.append(std::make_pair(AnnotationKeyPaintPhase, m_paintPhase));
-
- if (!m_elementId.isEmpty())
- list.append(std::make_pair(AnnotationKeyElementId, m_elementId));
-
- if (!m_elementClass.isEmpty())
- list.append(std::make_pair(AnnotationKeyElementClass, m_elementClass));
-
- if (!m_elementTag.isEmpty())
- list.append(std::make_pair(AnnotationKeyElementTag, m_elementTag));
-}
-
-void GraphicsContextAnnotator::annotate(const PaintInfo& paintInfo, const RenderObject* object)
-{
- ASSERT(!m_context);
-
- m_context = paintInfo.context;
- m_context->beginAnnotation(GraphicsContextAnnotation(paintInfo, object));
-}
-
-void GraphicsContextAnnotator::finishAnnotation()
-{
- ASSERT(m_context);
- m_context->endAnnotation();
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsContextAnnotation.h b/chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsContextAnnotation.h
deleted file mode 100644
index f30a38d87ca..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsContextAnnotation.h
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "wtf/Vector.h"
-#include "wtf/text/WTFString.h"
-
-#ifndef GraphicsContextAnnotation_h
-#define GraphicsContextAnnotation_h
-
-#define ANNOTATE_GRAPHICS_CONTEXT(paintInfo, renderer) \
- GraphicsContextAnnotator scopedGraphicsContextAnnotator; \
- if (UNLIKELY(paintInfo.context->annotationMode())) \
- scopedGraphicsContextAnnotator.annotate(paintInfo, renderer)
-
-namespace WebCore {
-
-class GraphicsContext;
-class RenderObject;
-struct PaintInfo;
-
-enum AnnotationMode {
- AnnotateRendererName = 1 << 0,
- AnnotatePaintPhase = 1 << 1,
- AnnotateElementId = 1 << 2,
- AnnotateElementClass = 1 << 3,
- AnnotateElementTag = 1 << 4,
-
- AnnotateAll = 0x1f
-};
-
-typedef unsigned AnnotationModeFlags;
-typedef Vector<std::pair<const char*, String> > AnnotationList;
-
-class GraphicsContextAnnotation {
-public:
- GraphicsContextAnnotation(const PaintInfo&, const RenderObject*);
-
- String rendererName() const { return m_rendererName; }
- String paintPhase() const { return m_paintPhase; }
- String elementId() const { return m_elementId; }
- String elementClass() const { return m_elementClass; }
- String elementTag() const { return m_elementTag; }
-
- void asAnnotationList(AnnotationList&) const;
-
-private:
- const char* m_rendererName;
- const char* m_paintPhase;
- String m_elementId;
- String m_elementClass;
- String m_elementTag;
-};
-
-class GraphicsContextAnnotator {
-public:
- GraphicsContextAnnotator()
- : m_context(0)
- { }
-
- ~GraphicsContextAnnotator()
- {
- if (UNLIKELY(m_context != 0))
- finishAnnotation();
- }
-
- void annotate(const PaintInfo&, const RenderObject*);
-
-private:
- void finishAnnotation();
-
- GraphicsContext* m_context;
-};
-
-} // namespace WebCore
-
-#endif // GraphicsContextAnnotation_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsContextState.h b/chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsContextState.h
deleted file mode 100644
index ea27cb770f6..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsContextState.h
+++ /dev/null
@@ -1,149 +0,0 @@
-// Copyright (C) 2013 Google Inc. All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-#ifndef GraphicsContextState_h
-#define GraphicsContextState_h
-
-#include "core/platform/graphics/Gradient.h"
-#include "core/platform/graphics/GraphicsTypes.h"
-#include "core/platform/graphics/Path.h"
-#include "core/platform/graphics/Pattern.h"
-#include "core/platform/graphics/StrokeData.h"
-#include "third_party/skia/include/core/SkColorFilter.h"
-#include "third_party/skia/include/core/SkColorPriv.h"
-#include "third_party/skia/include/core/SkDrawLooper.h"
-#include "third_party/skia/include/effects/SkDashPathEffect.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/RefPtr.h"
-
-namespace WebCore {
-
-// Encapsulates the state information we store for each pushed graphics state.
-// Only GraphicsContext can use this class.
-class GraphicsContextState {
-private:
- friend class GraphicsContext;
-
- GraphicsContextState()
- : m_fillColor(Color::black)
- , m_fillRule(RULE_NONZERO)
- , m_textDrawingMode(TextModeFill)
- , m_alpha(1)
- , m_xferMode(0)
- , m_compositeOperator(CompositeSourceOver)
- , m_blendMode(BlendModeNormal)
-#if USE(LOW_QUALITY_IMAGE_INTERPOLATION)
- , m_interpolationQuality(InterpolationLow)
-#else
- , m_interpolationQuality(InterpolationHigh)
-#endif
- , m_shouldAntialias(true)
- , m_shouldSmoothFonts(true)
- , m_shouldClampToSourceRect(true)
- , m_drawLuminanceMask(false)
- {
- }
-
- GraphicsContextState(const GraphicsContextState& other)
- : m_strokeData(other.m_strokeData)
- , m_fillColor(other.m_fillColor)
- , m_fillRule(other.m_fillRule)
- , m_fillGradient(other.m_fillGradient)
- , m_fillPattern(other.m_fillPattern)
- , m_looper(other.m_looper)
- , m_textDrawingMode(other.m_textDrawingMode)
- , m_alpha(other.m_alpha)
- , m_xferMode(other.m_xferMode)
- , m_colorFilter(other.m_colorFilter)
- , m_compositeOperator(other.m_compositeOperator)
- , m_blendMode(other.m_blendMode)
- , m_interpolationQuality(other.m_interpolationQuality)
- , m_shouldAntialias(other.m_shouldAntialias)
- , m_shouldSmoothFonts(other.m_shouldSmoothFonts)
- , m_shouldClampToSourceRect(other.m_shouldClampToSourceRect)
- , m_drawLuminanceMask(other.m_drawLuminanceMask)
- {
- }
-
- // Helper function for applying the state's alpha value to the given input
- // color to produce a new output color.
- SkColor applyAlpha(SkColor c) const
- {
- int s = roundf(m_alpha * 256);
- if (s >= 256)
- return c;
- if (s < 0)
- return 0;
-
- int a = SkAlphaMul(SkColorGetA(c), s);
- return (c & 0x00FFFFFF) | (a << 24);
- }
-
- // Returns a new State with all of this object's inherited properties copied.
- PassOwnPtr<GraphicsContextState> clone() { return adoptPtr(new GraphicsContextState(*this)); }
-
- // Not supported. No implementations.
- void operator=(const GraphicsContextState&);
-
- // Stroke.
- StrokeData m_strokeData;
-
- // Fill.
- Color m_fillColor;
- WindRule m_fillRule;
- RefPtr<Gradient> m_fillGradient;
- RefPtr<Pattern> m_fillPattern;
-
- // Shadow. (This will need tweaking if we use draw loopers for other things.)
- RefPtr<SkDrawLooper> m_looper;
-
- // Text. (See TextModeFill & friends.)
- TextDrawingModeFlags m_textDrawingMode;
-
- // Common shader state.
- float m_alpha;
- RefPtr<SkXfermode> m_xferMode;
- RefPtr<SkColorFilter> m_colorFilter;
-
- // Compositing control, for the CSS and Canvas compositing spec.
- CompositeOperator m_compositeOperator;
- BlendMode m_blendMode;
-
- // Image interpolation control.
- InterpolationQuality m_interpolationQuality;
-
- bool m_shouldAntialias : 1;
- bool m_shouldSmoothFonts : 1;
- bool m_shouldClampToSourceRect : 1;
- bool m_drawLuminanceMask : 1;
-};
-
-} // namespace WebCore
-
-#endif // GraphicsContextState_h
-
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsContextStateSaver.h b/chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsContextStateSaver.h
deleted file mode 100644
index c4b0be58df3..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsContextStateSaver.h
+++ /dev/null
@@ -1,77 +0,0 @@
-// Copyright (C) 2013 Google Inc. All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-#ifndef GraphicsContextStateSaver_h
-#define GraphicsContextStateSaver_h
-
-#include "core/platform/graphics/GraphicsContext.h"
-
-namespace WebCore {
-
-class GraphicsContextStateSaver {
- WTF_MAKE_FAST_ALLOCATED;
-public:
- GraphicsContextStateSaver(GraphicsContext& context, bool saveAndRestore = true)
- : m_context(context)
- , m_saveAndRestore(saveAndRestore)
- {
- if (m_saveAndRestore)
- m_context.save();
- }
-
- ~GraphicsContextStateSaver()
- {
- if (m_saveAndRestore)
- m_context.restore();
- }
-
- void save()
- {
- ASSERT(!m_saveAndRestore);
- m_context.save();
- m_saveAndRestore = true;
- }
-
- void restore()
- {
- ASSERT(m_saveAndRestore);
- m_context.restore();
- m_saveAndRestore = false;
- }
-
- GraphicsContext* context() const { return &m_context; }
- bool saved() const { return m_saveAndRestore; }
-
-private:
- GraphicsContext& m_context;
- bool m_saveAndRestore;
-};
-
-} // namespace WebCore
-
-#endif // GraphicsContextStateSaver_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsContextTest.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsContextTest.cpp
deleted file mode 100644
index 511e55faddf..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsContextTest.cpp
+++ /dev/null
@@ -1,1091 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/platform/graphics/GraphicsContext.h"
-
-#include "SkCanvas.h"
-#include "core/platform/graphics/BitmapImage.h"
-#include "core/platform/graphics/ImageBuffer.h"
-#include "core/platform/graphics/skia/NativeImageSkia.h"
-#include <gtest/gtest.h>
-
-using namespace WebCore;
-
-namespace {
-
-#define EXPECT_EQ_RECT(a, b) \
- EXPECT_EQ(a.x(), b.x()); \
- EXPECT_EQ(a.y(), b.y()); \
- EXPECT_EQ(a.width(), b.width()); \
- EXPECT_EQ(a.height(), b.height());
-
-#define EXPECT_PIXELS_MATCH(bitmap, opaqueRect) \
-{ \
- SkAutoLockPixels locker(bitmap); \
- for (int y = opaqueRect.y(); y < opaqueRect.maxY(); ++y) \
- for (int x = opaqueRect.x(); x < opaqueRect.maxX(); ++x) { \
- int alpha = *bitmap.getAddr32(x, y) >> 24; \
- EXPECT_EQ(255, alpha); \
- } \
-}
-
-#define EXPECT_PIXELS_MATCH_EXACT(bitmap, opaqueRect) \
-{ \
- SkAutoLockPixels locker(bitmap); \
- for (int y = 0; y < bitmap.height(); ++y) \
- for (int x = 0; x < bitmap.width(); ++x) { \
- int alpha = *bitmap.getAddr32(x, y) >> 24; \
- bool opaque = opaqueRect.contains(x, y); \
- EXPECT_EQ(opaque, alpha == 255); \
- } \
-}
-
-TEST(GraphicsContextTest, trackOpaqueTest)
-{
- SkBitmap bitmap;
- bitmap.setConfig(SkBitmap::kARGB_8888_Config, 400, 400);
- bitmap.allocPixels();
- bitmap.eraseColor(0);
- SkCanvas canvas(bitmap);
-
- GraphicsContext context(&canvas);
- context.setTrackOpaqueRegion(true);
-
- Color opaque(1.0f, 0.0f, 0.0f, 1.0f);
- Color alpha(0.0f, 0.0f, 0.0f, 0.0f);
-
- context.fillRect(FloatRect(10, 10, 90, 90), opaque, CompositeSourceOver);
- EXPECT_EQ_RECT(IntRect(10, 10, 90, 90), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.fillRect(FloatRect(10, 10, 90, 90), alpha, CompositeSourceOver);
- EXPECT_EQ_RECT(IntRect(10, 10, 90, 90), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.fillRect(FloatRect(99, 13, 10, 90), opaque, CompositePlusLighter);
- EXPECT_EQ_RECT(IntRect(10, 10, 90, 90), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.fillRect(FloatRect(99, 13, 10, 90), opaque, CompositeSourceIn);
- EXPECT_EQ_RECT(IntRect(10, 10, 90, 90), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.fillRect(FloatRect(99, 13, 10, 90), alpha, CompositeSourceIn);
- EXPECT_EQ_RECT(IntRect(10, 10, 89, 90), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.fillRect(FloatRect(8, 8, 3, 90), opaque, CompositeSourceOut);
- EXPECT_EQ_RECT(IntRect(11, 10, 88, 90), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.fillRect(FloatRect(30, 30, 290, 290), opaque, CompositeSourceOver);
- EXPECT_EQ_RECT(IntRect(30, 30, 290, 290), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.fillRect(FloatRect(40, 20, 290, 50), opaque, CompositeSourceOver);
- EXPECT_EQ_RECT(IntRect(30, 30, 290, 290), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.fillRect(FloatRect(10, 10, 390, 50), opaque, CompositeSourceIn);
- EXPECT_EQ_RECT(IntRect(30, 30, 290, 290), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.fillRect(FloatRect(10, 10, 390, 50), alpha);
- EXPECT_EQ_RECT(IntRect(30, 30, 290, 290), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.fillRect(FloatRect(10, 10, 390, 50), opaque, CompositeSourceOver);
- EXPECT_EQ_RECT(IntRect(30, 10, 290, 310), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-}
-
-TEST(GraphicsContextTest, trackOpaqueClipTest)
-{
- SkBitmap bitmap;
- bitmap.setConfig(SkBitmap::kARGB_8888_Config, 400, 400);
- bitmap.allocPixels();
- SkCanvas canvas(bitmap);
-
- GraphicsContext context(&canvas);
- context.setTrackOpaqueRegion(true);
-
- Color opaque(1.0f, 0.0f, 0.0f, 1.0f);
- Color alpha(0.0f, 0.0f, 0.0f, 0.0f);
-
- context.fillRect(FloatRect(10, 10, 90, 90), opaque, CompositeSourceOver);
- EXPECT_EQ_RECT(IntRect(10, 10, 90, 90), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.clearRect(FloatRect(10, 10, 90, 90));
- EXPECT_EQ_RECT(IntRect(), context.opaqueRegion().asRect());
-
- context.save();
- context.clip(FloatRect(0, 0, 10, 10));
- context.fillRect(FloatRect(10, 10, 90, 90), opaque, CompositeSourceOver);
- EXPECT_EQ_RECT(IntRect(), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
- context.restore();
-
- context.clearRect(FloatRect(10, 10, 90, 90));
- EXPECT_EQ_RECT(IntRect(), context.opaqueRegion().asRect());
-
- context.save();
- context.clip(FloatRect(20, 20, 10, 10));
- context.fillRect(FloatRect(10, 10, 90, 90), opaque, CompositeSourceOver);
- EXPECT_EQ_RECT(IntRect(20, 20, 10, 10), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.clearRect(FloatRect(10, 10, 90, 90));
- EXPECT_EQ_RECT(IntRect(), context.opaqueRegion().asRect());
-
- // The intersection of the two clips becomes empty.
- context.clip(FloatRect(30, 20, 10, 10));
- context.fillRect(FloatRect(10, 10, 90, 90), opaque, CompositeSourceOver);
- EXPECT_EQ_RECT(IntRect(), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
- context.restore();
-
- context.clearRect(FloatRect(10, 10, 90, 90));
- EXPECT_EQ_RECT(IntRect(), context.opaqueRegion().asRect());
-
- // The transform and the clip need to interact correctly (transform first)
- context.save();
- context.translate(10, 10);
- context.clip(FloatRect(20, 20, 10, 10));
- context.fillRect(FloatRect(10, 10, 90, 90), opaque, CompositeSourceOver);
- EXPECT_EQ_RECT(IntRect(30, 30, 10, 10), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
- context.restore();
-
- context.clearRect(FloatRect(10, 10, 90, 90));
- EXPECT_EQ_RECT(IntRect(), context.opaqueRegion().asRect());
-
- // The transform and the clip need to interact correctly (clip first)
- context.save();
- context.clip(FloatRect(20, 20, 10, 10));
- context.translate(10, 10);
- context.fillRect(FloatRect(10, 10, 90, 90), opaque, CompositeSourceOver);
- EXPECT_EQ_RECT(IntRect(20, 20, 10, 10), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
- context.restore();
-
- context.clearRect(FloatRect(10, 10, 90, 90));
- EXPECT_EQ_RECT(IntRect(), context.opaqueRegion().asRect());
-
- Path path;
- path.moveTo(FloatPoint(0, 0));
- path.addLineTo(FloatPoint(100, 0));
-
- // Non-rectangular clips just cause the paint to be considered non-opaque.
- context.save();
- context.clipPath(path, RULE_EVENODD);
- context.fillRect(FloatRect(10, 10, 90, 90), opaque, CompositeSourceOver);
- EXPECT_EQ_RECT(IntRect(), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
- context.restore();
-
- // Another non-rectangular clip.
- context.save();
- context.clip(IntRect(30, 30, 20, 20));
- context.clipOut(IntRect(30, 30, 10, 10));
- context.fillRect(FloatRect(10, 10, 90, 90), opaque, CompositeSourceOver);
- EXPECT_EQ_RECT(IntRect(), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
- context.restore();
-}
-
-TEST(GraphicsContextTest, trackImageMask)
-{
- SkBitmap bitmap;
- bitmap.setConfig(SkBitmap::kARGB_8888_Config, 400, 400);
- bitmap.allocPixels();
- bitmap.eraseColor(0);
- SkCanvas canvas(bitmap);
-
- GraphicsContext context(&canvas);
- context.setTrackOpaqueRegion(true);
-
- Color opaque(1.0f, 0.0f, 0.0f, 1.0f);
- Color alpha(0.0f, 0.0f, 0.0f, 0.0f);
-
- // Image masks are done by drawing a bitmap into a transparency layer that uses DstIn to mask
- // out a transparency layer below that is filled with the mask color. In the end this should
- // not be marked opaque.
-
- context.setCompositeOperation(CompositeSourceOver);
- context.beginTransparencyLayer(1);
- context.fillRect(FloatRect(10, 10, 10, 10), opaque, CompositeSourceOver);
-
- context.setCompositeOperation(CompositeDestinationIn);
- context.beginTransparencyLayer(1);
-
- OwnPtr<ImageBuffer> alphaImage = ImageBuffer::create(IntSize(100, 100));
- alphaImage->context()->fillRect(IntRect(0, 0, 100, 100), alpha);
-
- context.setCompositeOperation(CompositeSourceOver);
- context.drawImageBuffer(alphaImage.get(), FloatRect(10, 10, 10, 10));
-
- context.endLayer();
- context.endLayer();
-
- EXPECT_EQ_RECT(IntRect(), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH_EXACT(bitmap, context.opaqueRegion().asRect());
-}
-
-TEST(GraphicsContextTest, trackImageMaskWithOpaqueRect)
-{
- SkBitmap bitmap;
- bitmap.setConfig(SkBitmap::kARGB_8888_Config, 400, 400);
- bitmap.allocPixels();
- bitmap.eraseColor(0);
- SkCanvas canvas(bitmap);
-
- GraphicsContext context(&canvas);
- context.setTrackOpaqueRegion(true);
-
- Color opaque(1.0f, 0.0f, 0.0f, 1.0f);
- Color alpha(0.0f, 0.0f, 0.0f, 0.0f);
-
- // Image masks are done by drawing a bitmap into a transparency layer that uses DstIn to mask
- // out a transparency layer below that is filled with the mask color. In the end this should
- // not be marked opaque.
-
- context.setCompositeOperation(CompositeSourceOver);
- context.beginTransparencyLayer(1);
- context.fillRect(FloatRect(10, 10, 10, 10), opaque, CompositeSourceOver);
-
- context.setCompositeOperation(CompositeDestinationIn);
- context.beginTransparencyLayer(1);
-
- OwnPtr<ImageBuffer> alphaImage = ImageBuffer::create(IntSize(100, 100));
- alphaImage->context()->fillRect(IntRect(0, 0, 100, 100), alpha);
-
- context.setCompositeOperation(CompositeSourceOver);
- context.drawImageBuffer(alphaImage.get(), FloatRect(10, 10, 10, 10));
-
- // We can't have an opaque mask actually, but we can pretend here like it would look if we did.
- context.fillRect(FloatRect(12, 12, 3, 3), opaque, CompositeSourceOver);
-
- context.endLayer();
- context.endLayer();
-
- EXPECT_EQ_RECT(IntRect(12, 12, 3, 3), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH_EXACT(bitmap, context.opaqueRegion().asRect());
-}
-
-TEST(GraphicsContextTest, trackOpaqueJoinTest)
-{
- SkBitmap bitmap;
- bitmap.setConfig(SkBitmap::kARGB_8888_Config, 400, 400);
- bitmap.allocPixels();
- SkCanvas canvas(bitmap);
-
- GraphicsContext context(&canvas);
- context.setTrackOpaqueRegion(true);
-
- Color opaque(1.0f, 0.0f, 0.0f, 1.0f);
- Color alpha(0.0f, 0.0f, 0.0f, 0.0f);
-
- context.fillRect(FloatRect(20, 20, 10, 10), opaque, CompositeSourceOver);
- EXPECT_EQ_RECT(IntRect(20, 20, 10, 10), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- // Doesn't join
- context.fillRect(FloatRect(31, 20, 10, 10), opaque, CompositeSourceOver);
- EXPECT_EQ_RECT(IntRect(20, 20, 10, 10), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- // Does join
- context.fillRect(FloatRect(30, 20, 10, 10), opaque, CompositeSourceOver);
- EXPECT_EQ_RECT(IntRect(20, 20, 20, 10), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- // Doesn't join
- context.fillRect(FloatRect(20, 31, 20, 10), opaque, CompositeSourceOver);
- EXPECT_EQ_RECT(IntRect(20, 20, 20, 10), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- // Does join
- context.fillRect(FloatRect(20, 30, 20, 10), opaque, CompositeSourceOver);
- EXPECT_EQ_RECT(IntRect(20, 20, 20, 20), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- // Doesn't join
- context.fillRect(FloatRect(9, 20, 10, 20), opaque, CompositeSourceOver);
- EXPECT_EQ_RECT(IntRect(20, 20, 20, 20), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- // Does join
- context.fillRect(FloatRect(10, 20, 10, 20), opaque, CompositeSourceOver);
- EXPECT_EQ_RECT(IntRect(10, 20, 30, 20), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- // Doesn't join
- context.fillRect(FloatRect(10, 9, 30, 10), opaque, CompositeSourceOver);
- EXPECT_EQ_RECT(IntRect(10, 20, 30, 20), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- // Does join
- context.fillRect(FloatRect(10, 10, 30, 10), opaque, CompositeSourceOver);
- EXPECT_EQ_RECT(IntRect(10, 10, 30, 30), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-}
-
-TEST(GraphicsContextTest, trackOpaqueLineTest)
-{
- SkBitmap bitmap;
- bitmap.setConfig(SkBitmap::kARGB_8888_Config, 200, 200);
- bitmap.allocPixels();
- bitmap.eraseColor(0);
- SkCanvas canvas(bitmap);
-
- GraphicsContext context(&canvas);
- context.setTrackOpaqueRegion(true);
-
- Color opaque(1.0f, 0.0f, 0.0f, 1.0f);
- Color alpha(0.0f, 0.0f, 0.0f, 0.0f);
-
- context.setShouldAntialias(false);
- context.setMiterLimit(0);
- context.setStrokeThickness(4);
- context.setLineCap(SquareCap);
- context.setStrokeStyle(SolidStroke);
- context.setCompositeOperation(CompositeSourceOver);
-
- context.fillRect(FloatRect(10, 10, 90, 90), opaque, CompositeSourceOver);
- EXPECT_EQ_RECT(IntRect(10, 10, 90, 90), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.setCompositeOperation(CompositeSourceIn);
-
- context.save();
- context.setStrokeColor(alpha);
- context.drawLine(IntPoint(0, 0), IntPoint(100, 0));
- context.restore();
- EXPECT_EQ_RECT(IntRect(10, 10, 90, 90), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.save();
- context.setStrokeColor(opaque);
- context.drawLine(IntPoint(0, 10), IntPoint(100, 10));
- context.restore();
- EXPECT_EQ_RECT(IntRect(10, 10, 90, 90), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.save();
- context.setStrokeColor(alpha);
- context.drawLine(IntPoint(0, 10), IntPoint(100, 10));
- context.restore();
- EXPECT_EQ_RECT(IntRect(10, 13, 90, 87), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.save();
- context.setStrokeColor(alpha);
- context.drawLine(IntPoint(0, 11), IntPoint(100, 11));
- context.restore();
- EXPECT_EQ_RECT(IntRect(10, 14, 90, 86), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.setShouldAntialias(true);
- context.setCompositeOperation(CompositeSourceOver);
-
- context.fillRect(FloatRect(10, 10, 90, 90), opaque, CompositeSourceOver);
- EXPECT_EQ_RECT(IntRect(10, 10, 90, 90), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.setCompositeOperation(CompositeSourceIn);
-
- context.save();
- context.setStrokeColor(alpha);
- context.drawLine(IntPoint(0, 0), IntPoint(100, 0));
- context.restore();
- EXPECT_EQ_RECT(IntRect(10, 10, 90, 90), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.setShouldAntialias(false);
- context.save();
- context.setStrokeColor(opaque);
- context.drawLine(IntPoint(0, 10), IntPoint(100, 10));
- context.restore();
- EXPECT_EQ_RECT(IntRect(10, 10, 90, 90), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.setShouldAntialias(true);
- context.save();
- context.setStrokeColor(opaque);
- context.drawLine(IntPoint(0, 10), IntPoint(100, 10));
- context.restore();
- EXPECT_EQ_RECT(IntRect(10, 13, 90, 87), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.save();
- context.setStrokeColor(alpha);
- context.drawLine(IntPoint(0, 11), IntPoint(100, 11));
- context.restore();
- EXPECT_EQ_RECT(IntRect(10, 14, 90, 86), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-}
-
-TEST(GraphicsContextTest, trackOpaquePathTest)
-{
- SkBitmap bitmap;
- bitmap.setConfig(SkBitmap::kARGB_8888_Config, 200, 200);
- bitmap.allocPixels();
- SkCanvas canvas(bitmap);
-
- GraphicsContext context(&canvas);
- context.setTrackOpaqueRegion(true);
-
- Color opaque(1.0f, 0.0f, 0.0f, 1.0f);
- Color alpha(0.0f, 0.0f, 0.0f, 0.0f);
-
- context.fillRect(FloatRect(10, 10, 90, 90), opaque, CompositeSourceOver);
- EXPECT_EQ_RECT(IntRect(10, 10, 90, 90), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.setShouldAntialias(false);
- context.setMiterLimit(1);
- context.setStrokeThickness(5);
- context.setLineCap(SquareCap);
- context.setStrokeStyle(SolidStroke);
- context.setCompositeOperation(CompositeSourceIn);
-
- Path path;
-
- context.setFillColor(alpha);
- path.moveTo(FloatPoint(0, 0));
- path.addLineTo(FloatPoint(100, 0));
- context.fillPath(path);
- EXPECT_EQ_RECT(IntRect(10, 10, 90, 90), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
- path.clear();
-
- context.setFillColor(opaque);
- path.moveTo(FloatPoint(0, 10));
- path.addLineTo(FloatPoint(100, 13));
- context.fillPath(path);
- EXPECT_EQ_RECT(IntRect(10, 10, 90, 90), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
- path.clear();
-
- context.setFillColor(alpha);
- path.moveTo(FloatPoint(0, 10));
- path.addLineTo(FloatPoint(100, 13));
- context.fillPath(path);
- EXPECT_EQ_RECT(IntRect(10, 13, 90, 87), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
- path.clear();
-
- context.setFillColor(alpha);
- path.moveTo(FloatPoint(0, 14));
- path.addLineTo(FloatPoint(100, 10));
- context.fillPath(path);
- EXPECT_EQ_RECT(IntRect(10, 14, 90, 86), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
- path.clear();
-}
-
-TEST(GraphicsContextTest, trackOpaqueImageTest)
-{
- SkBitmap bitmap;
- bitmap.setConfig(SkBitmap::kARGB_8888_Config, 200, 200);
- bitmap.allocPixels();
- SkCanvas canvas(bitmap);
-
- GraphicsContext context(&canvas);
- context.setTrackOpaqueRegion(true);
-
- Color opaque(1.0f, 0.0f, 0.0f, 1.0f);
- Color alpha(0.0f, 0.0f, 0.0f, 0.0f);
-
- SkBitmap opaqueBitmap;
- opaqueBitmap.setConfig(SkBitmap::kARGB_8888_Config, 10, 10);
- opaqueBitmap.allocPixels();
-
- opaqueBitmap.setIsOpaque(true);
- for (int y = 0; y < opaqueBitmap.height(); ++y)
- for (int x = 0; x < opaqueBitmap.width(); ++x)
- *opaqueBitmap.getAddr32(x, y) = 0xFFFFFFFF;
- RefPtr<BitmapImage> opaqueImage = BitmapImage::create(NativeImageSkia::create(opaqueBitmap));
- EXPECT_TRUE(opaqueImage->currentFrameKnownToBeOpaque());
-
- SkBitmap alphaBitmap;
- alphaBitmap.setConfig(SkBitmap::kARGB_8888_Config, 10, 10);
- alphaBitmap.allocPixels();
-
- alphaBitmap.setIsOpaque(false);
- for (int y = 0; y < alphaBitmap.height(); ++y)
- for (int x = 0; x < alphaBitmap.width(); ++x)
- *alphaBitmap.getAddr32(x, y) = 0x00000000;
- RefPtr<BitmapImage> alphaImage = BitmapImage::create(NativeImageSkia::create(alphaBitmap));
- EXPECT_FALSE(alphaImage->currentFrameKnownToBeOpaque());
-
- context.fillRect(FloatRect(10, 10, 90, 90), opaque, CompositeSourceOver);
- EXPECT_EQ_RECT(IntRect(10, 10, 90, 90), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.drawImage(opaqueImage.get(), IntPoint(0, 0));
- EXPECT_EQ_RECT(IntRect(10, 10, 90, 90), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
- context.drawImage(alphaImage.get(), IntPoint(0, 0));
- EXPECT_EQ_RECT(IntRect(10, 10, 90, 90), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.drawImage(opaqueImage.get(), IntPoint(5, 5));
- EXPECT_EQ_RECT(IntRect(10, 10, 90, 90), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
- context.drawImage(alphaImage.get(), IntPoint(5, 5));
- EXPECT_EQ_RECT(IntRect(10, 10, 90, 90), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.drawImage(opaqueImage.get(), IntPoint(10, 10));
- EXPECT_EQ_RECT(IntRect(10, 10, 90, 90), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
- context.drawImage(alphaImage.get(), IntPoint(10, 10));
- EXPECT_EQ_RECT(IntRect(10, 10, 90, 90), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.drawImage(alphaImage.get(), IntPoint(20, 10), CompositeSourceIn);
- EXPECT_EQ_RECT(IntRect(10, 20, 90, 80), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.save();
- context.setAlpha(0.5);
- context.drawImage(opaqueImage.get(), IntPoint(25, 15), CompositeSourceIn);
- context.restore();
- EXPECT_EQ_RECT(IntRect(10, 25, 90, 75), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.fillRect(FloatRect(10, 10, 90, 90), opaque, CompositeSourceOver);
- EXPECT_EQ_RECT(IntRect(10, 10, 90, 90), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.drawImage(alphaImage.get(), IntPoint(10, 20), CompositeSourceIn);
- EXPECT_EQ_RECT(IntRect(20, 10, 80, 90), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.save();
- context.setAlpha(0.5);
- context.drawImage(opaqueImage.get(), IntPoint(15, 25), CompositeSourceIn);
- context.restore();
- EXPECT_EQ_RECT(IntRect(25, 10, 75, 90), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-}
-
-TEST(GraphicsContextTest, trackOpaqueOvalTest)
-{
- SkBitmap bitmap;
- bitmap.setConfig(SkBitmap::kARGB_8888_Config, 200, 200);
- bitmap.allocPixels();
- bitmap.eraseColor(0);
- SkCanvas canvas(bitmap);
-
- GraphicsContext context(&canvas);
- context.setTrackOpaqueRegion(true);
-
- Color opaque(1.0f, 0.0f, 0.0f, 1.0f);
- Color alpha(0.0f, 0.0f, 0.0f, 0.0f);
-
- EXPECT_EQ_RECT(IntRect(0, 0, 0, 0), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.drawEllipse(IntRect(10, 10, 90, 90));
- EXPECT_EQ_RECT(IntRect(0, 0, 0, 0), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.fillRect(FloatRect(10, 10, 90, 90), opaque, CompositeSourceOver);
- EXPECT_EQ_RECT(IntRect(10, 10, 90, 90), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.setCompositeOperation(CompositeSourceIn);
-
- context.setShouldAntialias(false);
-
- context.setFillColor(opaque);
- context.drawEllipse(IntRect(10, 10, 50, 30));
- EXPECT_EQ_RECT(IntRect(10, 10, 90, 90), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.setFillColor(alpha);
- context.drawEllipse(IntRect(10, 10, 30, 50));
- EXPECT_EQ_RECT(IntRect(40, 10, 60, 90), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.setShouldAntialias(true);
-
- context.setFillColor(opaque);
- context.drawEllipse(IntRect(10, 10, 50, 30));
- EXPECT_EQ_RECT(IntRect(40, 41, 60, 59), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.setFillColor(alpha);
- context.drawEllipse(IntRect(20, 10, 30, 50));
- EXPECT_EQ_RECT(IntRect(51, 41, 49, 59), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-}
-
-TEST(GraphicsContextTest, trackOpaqueRoundedRectTest)
-{
- SkBitmap bitmap;
- bitmap.setConfig(SkBitmap::kARGB_8888_Config, 200, 200);
- bitmap.allocPixels();
- bitmap.eraseColor(0);
- SkCanvas canvas(bitmap);
-
- GraphicsContext context(&canvas);
- context.setTrackOpaqueRegion(true);
-
- Color opaque(1.0f, 0.0f, 0.0f, 1.0f);
- Color alpha(0.0f, 0.0f, 0.0f, 0.0f);
- IntSize radii(10, 10);
-
- EXPECT_EQ_RECT(IntRect(0, 0, 0, 0), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.fillRoundedRect(IntRect(10, 10, 90, 90), radii, radii, radii, radii, opaque);
- EXPECT_EQ_RECT(IntRect(0, 0, 0, 0), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.fillRect(FloatRect(10, 10, 90, 90), opaque, CompositeSourceOver);
- EXPECT_EQ_RECT(IntRect(10, 10, 90, 90), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.setCompositeOperation(CompositeSourceIn);
- context.setShouldAntialias(false);
-
- context.fillRoundedRect(IntRect(10, 10, 50, 30), radii, radii, radii, radii, opaque);
- EXPECT_EQ_RECT(IntRect(10, 10, 90, 90), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.fillRoundedRect(IntRect(10, 10, 30, 50), radii, radii, radii, radii, alpha);
- EXPECT_EQ_RECT(IntRect(40, 10, 60, 90), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.fillRoundedRect(IntRect(10, 0, 50, 30), radii, radii, radii, radii, alpha);
- EXPECT_EQ_RECT(IntRect(40, 30, 60, 70), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.fillRoundedRect(IntRect(30, 0, 70, 50), radii, radii, radii, radii, opaque);
- EXPECT_EQ_RECT(IntRect(40, 30, 60, 70), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-}
-
-TEST(GraphicsContextTest, trackOpaqueTextTest)
-{
- int width = 200, height = 200;
- SkBitmap bitmap;
- bitmap.setConfig(SkBitmap::kARGB_8888_Config, width, height);
- bitmap.allocPixels();
- bitmap.eraseColor(0);
- SkCanvas canvas(bitmap);
- SkRect textRect = SkRect::MakeWH(width, height);
-
- GraphicsContext context(&canvas);
- context.setTrackOpaqueRegion(true);
-
- Color opaque(1.0f, 0.0f, 0.0f, 1.0f);
- Color alpha(0.0f, 0.0f, 0.0f, 0.0f);
-
- SkPaint opaquePaint;
- opaquePaint.setColor(opaque.rgb());
- opaquePaint.setXfermodeMode(SkXfermode::kSrc_Mode);
- SkPaint alphaPaint;
- alphaPaint.setColor(alpha.rgb());
- alphaPaint.setXfermodeMode(SkXfermode::kSrc_Mode);
-
- SkPoint point = SkPoint::Make(0, 0);
- SkScalar pointX = 0;
- SkPath path;
- path.moveTo(SkPoint::Make(0, 0));
- path.lineTo(SkPoint::Make(100, 0));
-
- context.fillRect(FloatRect(50, 50, 50, 50), opaque, CompositeSourceOver);
- EXPECT_EQ_RECT(IntRect(50, 50, 50, 50), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.drawPosText("A", 1, &point, textRect, opaquePaint);
- EXPECT_EQ_RECT(IntRect(50, 50, 50, 50), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.drawPosText("A", 1, &point, textRect, alphaPaint);
- EXPECT_EQ_RECT(IntRect(0, 0, 0, 0), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.fillRect(FloatRect(50, 50, 50, 50), opaque, CompositeSourceOver);
- EXPECT_EQ_RECT(IntRect(50, 50, 50, 50), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.drawPosTextH("A", 1, &pointX, 0, textRect, opaquePaint);
- EXPECT_EQ_RECT(IntRect(50, 50, 50, 50), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.drawPosTextH("A", 1, &pointX, 0, textRect, alphaPaint);
- EXPECT_EQ_RECT(IntRect(0, 0, 0, 0), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.fillRect(FloatRect(50, 50, 50, 50), opaque, CompositeSourceOver);
- EXPECT_EQ_RECT(IntRect(50, 50, 50, 50), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.drawTextOnPath("A", 1, path, textRect, 0, opaquePaint);
- EXPECT_EQ_RECT(IntRect(50, 50, 50, 50), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.drawTextOnPath("A", 1, path, textRect, 0, alphaPaint);
- EXPECT_EQ_RECT(IntRect(0, 0, 0, 0), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-}
-
-TEST(GraphicsContextTest, trackOpaqueWritePixelsTest)
-{
- SkBitmap bitmap;
- bitmap.setConfig(SkBitmap::kARGB_8888_Config, 200, 200);
- bitmap.allocPixels();
- bitmap.eraseColor(0);
- SkCanvas canvas(bitmap);
-
- GraphicsContext context(&canvas);
- context.setTrackOpaqueRegion(true);
-
- Color opaque(1.0f, 0.0f, 0.0f, 1.0f);
-
- SkBitmap opaqueBitmap;
- opaqueBitmap.setConfig(SkBitmap::kARGB_8888_Config, 10, 10);
- opaqueBitmap.allocPixels();
- opaqueBitmap.setIsOpaque(true);
- for (int y = 0; y < opaqueBitmap.height(); ++y)
- for (int x = 0; x < opaqueBitmap.width(); ++x)
- *opaqueBitmap.getAddr32(x, y) = 0xFFFFFFFF;
-
- SkBitmap alphaBitmap;
- alphaBitmap.setConfig(SkBitmap::kARGB_8888_Config, 10, 10);
- alphaBitmap.allocPixels();
- alphaBitmap.setIsOpaque(false);
- for (int y = 0; y < alphaBitmap.height(); ++y)
- for (int x = 0; x < alphaBitmap.width(); ++x)
- *alphaBitmap.getAddr32(x, y) = 0x00000000;
-
- SkPaint paint;
- paint.setXfermodeMode(SkXfermode::kSrc_Mode);
-
- context.writePixels(opaqueBitmap, 50, 50);
- EXPECT_EQ_RECT(IntRect(50, 50, 10, 10), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.fillRect(FloatRect(10, 10, 90, 90), opaque, CompositeSourceOver);
- EXPECT_EQ_RECT(IntRect(10, 10, 90, 90), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.writePixels(alphaBitmap, 10, 0);
- EXPECT_EQ_RECT(IntRect(10, 10, 90, 90), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.writePixels(alphaBitmap, 10, 1);
- EXPECT_EQ_RECT(IntRect(10, 11, 90, 89), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.writePixels(alphaBitmap, 0, 10);
- EXPECT_EQ_RECT(IntRect(10, 11, 90, 89), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.writePixels(alphaBitmap, 1, 10);
- EXPECT_EQ_RECT(IntRect(11, 11, 89, 89), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-}
-
-TEST(GraphicsContextTest, trackOpaqueDrawBitmapTest)
-{
- SkBitmap bitmap;
- bitmap.setConfig(SkBitmap::kARGB_8888_Config, 200, 200);
- bitmap.allocPixels();
- bitmap.eraseColor(0);
- SkCanvas canvas(bitmap);
-
- GraphicsContext context(&canvas);
- context.setTrackOpaqueRegion(true);
-
- Color opaque(1.0f, 0.0f, 0.0f, 1.0f);
-
- SkBitmap opaqueBitmap;
- opaqueBitmap.setConfig(SkBitmap::kARGB_8888_Config, 10, 10);
- opaqueBitmap.allocPixels();
- opaqueBitmap.setIsOpaque(true);
- for (int y = 0; y < opaqueBitmap.height(); ++y)
- for (int x = 0; x < opaqueBitmap.width(); ++x)
- *opaqueBitmap.getAddr32(x, y) = 0xFFFFFFFF;
-
- SkBitmap alphaBitmap;
- alphaBitmap.setConfig(SkBitmap::kARGB_8888_Config, 10, 10);
- alphaBitmap.allocPixels();
- alphaBitmap.setIsOpaque(false);
- for (int y = 0; y < alphaBitmap.height(); ++y)
- for (int x = 0; x < alphaBitmap.width(); ++x)
- *alphaBitmap.getAddr32(x, y) = 0x00000000;
-
- SkPaint paint;
- paint.setXfermodeMode(SkXfermode::kSrc_Mode);
-
- context.drawBitmap(opaqueBitmap, 10, 10, &paint);
- EXPECT_EQ_RECT(IntRect(10, 10, 10, 10), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.fillRect(FloatRect(10, 10, 90, 90), opaque, CompositeSourceOver);
- EXPECT_EQ_RECT(IntRect(10, 10, 90, 90), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.drawBitmap(alphaBitmap, 10, 0, &paint);
- EXPECT_EQ_RECT(IntRect(10, 10, 90, 90), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.drawBitmap(alphaBitmap, 10, 1, &paint);
- EXPECT_EQ_RECT(IntRect(10, 11, 90, 89), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.drawBitmap(alphaBitmap, 0, 10, &paint);
- EXPECT_EQ_RECT(IntRect(10, 11, 90, 89), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.drawBitmap(alphaBitmap, 1, 10, &paint);
- EXPECT_EQ_RECT(IntRect(11, 11, 89, 89), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-}
-
-TEST(GraphicsContextTest, trackOpaqueDrawBitmapRectTest)
-{
- SkBitmap bitmap;
- bitmap.setConfig(SkBitmap::kARGB_8888_Config, 200, 200);
- bitmap.allocPixels();
- bitmap.eraseColor(0);
- SkCanvas canvas(bitmap);
-
- GraphicsContext context(&canvas);
- context.setTrackOpaqueRegion(true);
-
- Color opaque(1.0f, 0.0f, 0.0f, 1.0f);
-
- SkBitmap opaqueBitmap;
- opaqueBitmap.setConfig(SkBitmap::kARGB_8888_Config, 10, 10);
- opaqueBitmap.allocPixels();
- opaqueBitmap.setIsOpaque(true);
- for (int y = 0; y < opaqueBitmap.height(); ++y)
- for (int x = 0; x < opaqueBitmap.width(); ++x)
- *opaqueBitmap.getAddr32(x, y) = 0xFFFFFFFF;
-
- SkBitmap alphaBitmap;
- alphaBitmap.setConfig(SkBitmap::kARGB_8888_Config, 10, 10);
- alphaBitmap.allocPixels();
- alphaBitmap.setIsOpaque(false);
- for (int y = 0; y < alphaBitmap.height(); ++y)
- for (int x = 0; x < alphaBitmap.width(); ++x)
- *alphaBitmap.getAddr32(x, y) = 0x00000000;
-
- SkPaint paint;
- paint.setXfermodeMode(SkXfermode::kSrc_Mode);
-
- context.drawBitmapRect(opaqueBitmap, 0, SkRect::MakeXYWH(10, 10, 90, 90), &paint);
- EXPECT_EQ_RECT(IntRect(10, 10, 90, 90), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.drawBitmapRect(alphaBitmap, 0, SkRect::MakeXYWH(10, 0, 10, 10), &paint);
- EXPECT_EQ_RECT(IntRect(10, 10, 90, 90), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.drawBitmapRect(alphaBitmap, 0, SkRect::MakeXYWH(10, 0, 10, 11), &paint);
- EXPECT_EQ_RECT(IntRect(10, 11, 90, 89), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.drawBitmapRect(alphaBitmap, 0, SkRect::MakeXYWH(0, 10, 10, 10), &paint);
- EXPECT_EQ_RECT(IntRect(10, 11, 90, 89), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.drawBitmapRect(alphaBitmap, 0, SkRect::MakeXYWH(0, 10, 11, 10), &paint);
- EXPECT_EQ_RECT(IntRect(11, 11, 89, 89), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-}
-
-TEST(GraphicsContextTest, contextTransparencyLayerTest)
-{
- SkBitmap bitmap;
- bitmap.setConfig(SkBitmap::kARGB_8888_Config, 400, 400);
- bitmap.allocPixels();
- bitmap.eraseColor(0);
- SkCanvas canvas(bitmap);
-
- GraphicsContext context(&canvas);
- context.setTrackOpaqueRegion(true);
-
- Color opaque(1.0f, 0.0f, 0.0f, 1.0f);
- context.fillRect(FloatRect(20, 20, 10, 10), opaque, CompositeSourceOver);
- EXPECT_EQ_RECT(IntRect(20, 20, 10, 10), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-
- context.clearRect(FloatRect(20, 20, 10, 10));
- EXPECT_EQ_RECT(IntRect(), context.opaqueRegion().asRect());
-
- context.beginTransparencyLayer(0.5);
- context.save();
- context.fillRect(FloatRect(20, 20, 10, 10), opaque, CompositeSourceOver);
- context.restore();
- context.endLayer();
- EXPECT_EQ_RECT(IntRect(), context.opaqueRegion().asRect());
-
- context.clearRect(FloatRect(20, 20, 10, 10));
- EXPECT_EQ_RECT(IntRect(), context.opaqueRegion().asRect());
-
- context.beginTransparencyLayer(0.5);
- context.fillRect(FloatRect(20, 20, 10, 10), opaque, CompositeSourceOver);
- context.endLayer();
- EXPECT_EQ_RECT(IntRect(), context.opaqueRegion().asRect());
-}
-
-TEST(GraphicsContextTest, UnboundedDrawsAreClipped)
-{
- SkBitmap bitmap;
- bitmap.setConfig(SkBitmap::kARGB_8888_Config, 400, 400);
- bitmap.allocPixels();
- bitmap.eraseColor(0);
- SkCanvas canvas(bitmap);
-
- GraphicsContext context(&canvas);
- context.setTrackOpaqueRegion(true);
-
- Color opaque(1.0f, 0.0f, 0.0f, 1.0f);
- Color alpha(0.0f, 0.0f, 0.0f, 0.0f);
-
- Path path;
- context.setShouldAntialias(false);
- context.setMiterLimit(1);
- context.setStrokeThickness(5);
- context.setLineCap(SquareCap);
- context.setStrokeStyle(SolidStroke);
-
- // Make skia unable to compute fast bounds for our paths.
- DashArray dashArray;
- dashArray.append(1);
- dashArray.append(0);
- context.setLineDash(dashArray, 0);
-
- // Make the device opaque in 10,10 40x40.
- context.fillRect(FloatRect(10, 10, 40, 40), opaque, CompositeSourceOver);
- EXPECT_EQ_RECT(IntRect(10, 10, 40, 40), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH_EXACT(bitmap, context.opaqueRegion().asRect());
-
- // Clip to the left edge of the opaque area.
- context.clip(IntRect(10, 10, 10, 40));
-
- // Draw a path that gets clipped. This should destroy the opaque area but only inside the clip.
- context.setCompositeOperation(CompositeSourceOut);
- context.setFillColor(alpha);
- path.moveTo(FloatPoint(10, 10));
- path.addLineTo(FloatPoint(40, 40));
- context.strokePath(path);
-
- EXPECT_EQ_RECT(IntRect(20, 10, 30, 40), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH(bitmap, context.opaqueRegion().asRect());
-}
-
-TEST(GraphicsContextTest, PreserveOpaqueOnlyMattersForFirstLayer)
-{
- SkBitmap bitmap;
- bitmap.setConfig(SkBitmap::kARGB_8888_Config, 400, 400);
- bitmap.allocPixels();
- bitmap.eraseColor(0);
- SkCanvas canvas(bitmap);
-
- GraphicsContext context(&canvas);
- context.setTrackOpaqueRegion(true);
-
- Color opaque(1.0f, 0.0f, 0.0f, 1.0f);
- Color alpha(0.0f, 0.0f, 0.0f, 0.0f);
-
- Path path;
- context.setShouldAntialias(false);
- context.setMiterLimit(1);
- context.setStrokeThickness(5);
- context.setLineCap(SquareCap);
- context.setStrokeStyle(SolidStroke);
-
- // Make skia unable to compute fast bounds for our paths.
- DashArray dashArray;
- dashArray.append(1);
- dashArray.append(0);
- context.setLineDash(dashArray, 0);
-
- // Make the device opaque in 10,10 40x40.
- context.fillRect(FloatRect(10, 10, 40, 40), opaque, CompositeSourceOver);
- EXPECT_EQ_RECT(IntRect(10, 10, 40, 40), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH_EXACT(bitmap, context.opaqueRegion().asRect());
-
- // Begin a layer that preserves opaque.
- context.setCompositeOperation(CompositeSourceOver);
- context.beginTransparencyLayer(0.5);
-
- // Begin a layer that does not preserve opaque.
- context.setCompositeOperation(CompositeSourceOut);
- context.beginTransparencyLayer(0.5);
-
- // This should not destroy the device opaqueness.
- context.fillRect(FloatRect(10, 10, 40, 40), opaque, CompositeSourceOver);
-
- // This should not destroy the device opaqueness either.
- context.setFillColor(opaque);
- path.moveTo(FloatPoint(10, 10));
- path.addLineTo(FloatPoint(40, 40));
- context.strokePath(path);
-
- context.endLayer();
- context.endLayer();
- EXPECT_EQ_RECT(IntRect(10, 10, 40, 40), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH_EXACT(bitmap, context.opaqueRegion().asRect());
-
- // Now begin a layer that does not preserve opaque and draw through it to the device.
- context.setCompositeOperation(CompositeSourceOut);
- context.beginTransparencyLayer(0.5);
-
- // This should destroy the device opaqueness.
- context.fillRect(FloatRect(10, 10, 40, 40), opaque, CompositeSourceOver);
-
- context.endLayer();
- EXPECT_EQ_RECT(IntRect(), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH_EXACT(bitmap, context.opaqueRegion().asRect());
-
- // Now we draw with a path for which it cannot compute fast bounds. This should destroy the entire opaque region.
-
- context.setCompositeOperation(CompositeSourceOut);
- context.beginTransparencyLayer(0.5);
-
- // This should nuke the device opaqueness.
- context.setFillColor(opaque);
- path.moveTo(FloatPoint(10, 10));
- path.addLineTo(FloatPoint(40, 40));
- context.strokePath(path);
-
- context.endLayer();
- EXPECT_EQ_RECT(IntRect(), context.opaqueRegion().asRect());
- EXPECT_PIXELS_MATCH_EXACT(bitmap, context.opaqueRegion().asRect());
-}
-
-} // namespace
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsLayer.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsLayer.cpp
deleted file mode 100644
index 6bae3b2b618..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsLayer.cpp
+++ /dev/null
@@ -1,1220 +0,0 @@
-/*
- * Copyright (C) 2009 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/platform/graphics/GraphicsLayer.h"
-
-#include "SkImageFilter.h"
-#include "SkMatrix44.h"
-#include "core/platform/ScrollableArea.h"
-#include "core/platform/graphics/FloatPoint.h"
-#include "core/platform/graphics/FloatRect.h"
-#include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/graphics/GraphicsLayerFactory.h"
-#include "core/platform/graphics/LayoutRect.h"
-#include "core/platform/graphics/chromium/AnimationTranslationUtil.h"
-#include "core/platform/graphics/chromium/TransformSkMatrix44Conversions.h"
-#include "core/platform/graphics/filters/SkiaImageFilterBuilder.h"
-#include "core/platform/graphics/skia/NativeImageSkia.h"
-#include "core/platform/text/TextStream.h"
-
-#include "wtf/CurrentTime.h"
-#include "wtf/HashMap.h"
-#include "wtf/HashSet.h"
-#include "wtf/text/CString.h"
-#include "wtf/text/StringBuilder.h"
-#include "wtf/text/StringHash.h"
-#include "wtf/text/WTFString.h"
-
-#include "public/platform/Platform.h"
-#include "public/platform/WebAnimation.h"
-#include "public/platform/WebCompositorSupport.h"
-#include "public/platform/WebFilterOperations.h"
-#include "public/platform/WebFloatPoint.h"
-#include "public/platform/WebFloatRect.h"
-#include "public/platform/WebLayer.h"
-#include "public/platform/WebPoint.h"
-#include "public/platform/WebSize.h"
-
-#ifndef NDEBUG
-#include <stdio.h>
-#endif
-
-using WebKit::Platform;
-using WebKit::WebAnimation;
-using WebKit::WebFilterOperations;
-using WebKit::WebLayer;
-using WebKit::WebPoint;
-
-namespace WebCore {
-
-typedef HashMap<const GraphicsLayer*, Vector<FloatRect> > RepaintMap;
-static RepaintMap& repaintRectMap()
-{
- DEFINE_STATIC_LOCAL(RepaintMap, map, ());
- return map;
-}
-
-PassOwnPtr<GraphicsLayer> GraphicsLayer::create(GraphicsLayerFactory* factory, GraphicsLayerClient* client)
-{
- return factory->createGraphicsLayer(client);
-}
-
-GraphicsLayer::GraphicsLayer(GraphicsLayerClient* client)
- : m_client(client)
- , m_anchorPoint(0.5f, 0.5f, 0)
- , m_opacity(1)
- , m_zPosition(0)
- , m_contentsOpaque(false)
- , m_preserves3D(false)
- , m_backfaceVisibility(true)
- , m_masksToBounds(false)
- , m_drawsContent(false)
- , m_contentsVisible(true)
- , m_paintingPhase(GraphicsLayerPaintAllWithOverflowClip)
- , m_contentsOrientation(CompositingCoordinatesTopDown)
- , m_parent(0)
- , m_maskLayer(0)
- , m_replicaLayer(0)
- , m_replicatedLayer(0)
- , m_paintCount(0)
- , m_contentsLayer(0)
- , m_contentsLayerId(0)
- , m_contentsLayerPurpose(NoContentsLayer)
- , m_scrollableArea(0)
- , m_compositingReasons(WebKit::CompositingReasonUnknown)
-{
-#ifndef NDEBUG
- if (m_client)
- m_client->verifyNotPainting();
-#endif
-
- m_opaqueRectTrackingContentLayerDelegate = adoptPtr(new OpaqueRectTrackingContentLayerDelegate(this));
- m_layer = adoptPtr(Platform::current()->compositorSupport()->createContentLayer(m_opaqueRectTrackingContentLayerDelegate.get()));
- m_layer->layer()->setDrawsContent(m_drawsContent && m_contentsVisible);
- m_layer->layer()->setWebLayerClient(this);
- m_layer->setAutomaticallyComputeRasterScale(true);
-}
-
-GraphicsLayer::~GraphicsLayer()
-{
- for (size_t i = 0; i < m_linkHighlights.size(); ++i)
- m_linkHighlights[i]->clearCurrentGraphicsLayer();
- m_linkHighlights.clear();
-
-#ifndef NDEBUG
- if (m_client)
- m_client->verifyNotPainting();
-#endif
-
- if (m_replicaLayer)
- m_replicaLayer->setReplicatedLayer(0);
-
- if (m_replicatedLayer)
- m_replicatedLayer->setReplicatedByLayer(0);
-
- removeAllChildren();
- removeFromParent();
-
- resetTrackedRepaints();
- ASSERT(!m_parent);
-}
-
-void GraphicsLayer::setParent(GraphicsLayer* layer)
-{
- ASSERT(!layer || !layer->hasAncestor(this));
- m_parent = layer;
-}
-
-bool GraphicsLayer::hasAncestor(GraphicsLayer* ancestor) const
-{
- for (GraphicsLayer* curr = parent(); curr; curr = curr->parent()) {
- if (curr == ancestor)
- return true;
- }
-
- return false;
-}
-
-bool GraphicsLayer::setChildren(const Vector<GraphicsLayer*>& newChildren)
-{
- // If the contents of the arrays are the same, nothing to do.
- if (newChildren == m_children)
- return false;
-
- removeAllChildren();
-
- size_t listSize = newChildren.size();
- for (size_t i = 0; i < listSize; ++i)
- addChildInternal(newChildren[i]);
-
- updateChildList();
-
- return true;
-}
-
-void GraphicsLayer::addChildInternal(GraphicsLayer* childLayer)
-{
- ASSERT(childLayer != this);
-
- if (childLayer->parent())
- childLayer->removeFromParent();
-
- childLayer->setParent(this);
- m_children.append(childLayer);
-
- // Don't call updateChildList here, this function is used in cases where it
- // should not be called until all children are processed.
-}
-
-void GraphicsLayer::addChild(GraphicsLayer* childLayer)
-{
- addChildInternal(childLayer);
- updateChildList();
-}
-
-void GraphicsLayer::addChildAtIndex(GraphicsLayer* childLayer, int index)
-{
- ASSERT(childLayer != this);
-
- if (childLayer->parent())
- childLayer->removeFromParent();
-
- childLayer->setParent(this);
- m_children.insert(index, childLayer);
-
- updateChildList();
-}
-
-void GraphicsLayer::addChildBelow(GraphicsLayer* childLayer, GraphicsLayer* sibling)
-{
- ASSERT(childLayer != this);
- childLayer->removeFromParent();
-
- bool found = false;
- for (unsigned i = 0; i < m_children.size(); i++) {
- if (sibling == m_children[i]) {
- m_children.insert(i, childLayer);
- found = true;
- break;
- }
- }
-
- childLayer->setParent(this);
-
- if (!found)
- m_children.append(childLayer);
-
- updateChildList();
-}
-
-void GraphicsLayer::addChildAbove(GraphicsLayer* childLayer, GraphicsLayer* sibling)
-{
- childLayer->removeFromParent();
- ASSERT(childLayer != this);
-
- bool found = false;
- for (unsigned i = 0; i < m_children.size(); i++) {
- if (sibling == m_children[i]) {
- m_children.insert(i+1, childLayer);
- found = true;
- break;
- }
- }
-
- childLayer->setParent(this);
-
- if (!found)
- m_children.append(childLayer);
-
- updateChildList();
-}
-
-bool GraphicsLayer::replaceChild(GraphicsLayer* oldChild, GraphicsLayer* newChild)
-{
- ASSERT(!newChild->parent());
- bool found = false;
- for (unsigned i = 0; i < m_children.size(); i++) {
- if (oldChild == m_children[i]) {
- m_children[i] = newChild;
- found = true;
- break;
- }
- }
-
- if (found) {
- oldChild->setParent(0);
-
- newChild->removeFromParent();
- newChild->setParent(this);
-
- updateChildList();
- return true;
- }
-
- return false;
-}
-
-void GraphicsLayer::removeAllChildren()
-{
- while (m_children.size()) {
- GraphicsLayer* curLayer = m_children[0];
- ASSERT(curLayer->parent());
- curLayer->removeFromParent();
- }
-}
-
-void GraphicsLayer::removeFromParent()
-{
- if (m_parent) {
- unsigned i;
- for (i = 0; i < m_parent->m_children.size(); i++) {
- if (this == m_parent->m_children[i]) {
- m_parent->m_children.remove(i);
- break;
- }
- }
-
- setParent(0);
- }
-
- platformLayer()->removeFromParent();
-}
-
-void GraphicsLayer::setReplicatedByLayer(GraphicsLayer* layer)
-{
- // FIXME: this could probably be a full early exit.
- if (m_replicaLayer != layer) {
- if (m_replicaLayer)
- m_replicaLayer->setReplicatedLayer(0);
-
- if (layer)
- layer->setReplicatedLayer(this);
-
- m_replicaLayer = layer;
- }
-
- WebLayer* webReplicaLayer = layer ? layer->platformLayer() : 0;
- platformLayer()->setReplicaLayer(webReplicaLayer);
-}
-
-void GraphicsLayer::setOffsetFromRenderer(const IntSize& offset, ShouldSetNeedsDisplay shouldSetNeedsDisplay)
-{
- if (offset == m_offsetFromRenderer)
- return;
-
- m_offsetFromRenderer = offset;
-
- // If the compositing layer offset changes, we need to repaint.
- if (shouldSetNeedsDisplay == SetNeedsDisplay)
- setNeedsDisplay();
-}
-
-void GraphicsLayer::paintGraphicsLayerContents(GraphicsContext& context, const IntRect& clip)
-{
- if (!m_client)
- return;
- incrementPaintCount();
- m_client->paintContents(this, context, m_paintingPhase, clip);
-}
-
-String GraphicsLayer::animationNameForTransition(AnimatedPropertyID property)
-{
- // | is not a valid identifier character in CSS, so this can never conflict with a keyframe identifier.
- StringBuilder id;
- id.appendLiteral("-|transition");
- id.appendNumber(static_cast<int>(property));
- id.append('-');
- return id.toString();
-}
-
-void GraphicsLayer::setZPosition(float position)
-{
- m_zPosition = position;
-}
-
-float GraphicsLayer::accumulatedOpacity() const
-{
- if (!preserves3D())
- return 1;
-
- return m_opacity * (parent() ? parent()->accumulatedOpacity() : 1);
-}
-
-void GraphicsLayer::distributeOpacity(float accumulatedOpacity)
-{
- // If this is a transform layer we need to distribute our opacity to all our children
-
- // Incoming accumulatedOpacity is the contribution from our parent(s). We mutiply this by our own
- // opacity to get the total contribution
- accumulatedOpacity *= m_opacity;
-
- if (preserves3D()) {
- size_t numChildren = children().size();
- for (size_t i = 0; i < numChildren; ++i)
- children()[i]->distributeOpacity(accumulatedOpacity);
- }
-}
-
-void GraphicsLayer::updateChildList()
-{
- WebLayer* childHost = m_layer->layer();
- childHost->removeAllChildren();
-
- clearContentsLayerIfUnregistered();
-
- if (m_contentsLayer) {
- // FIXME: add the contents layer in the correct order with negative z-order children.
- // This does not cause visible rendering issues because currently contents layers are only used
- // for replaced elements that don't have children.
- childHost->addChild(m_contentsLayer);
- }
-
- const Vector<GraphicsLayer*>& childLayers = children();
- size_t numChildren = childLayers.size();
- for (size_t i = 0; i < numChildren; ++i) {
- GraphicsLayer* curChild = childLayers[i];
-
- childHost->addChild(curChild->platformLayer());
- }
-
- for (size_t i = 0; i < m_linkHighlights.size(); ++i)
- childHost->addChild(m_linkHighlights[i]->layer());
-}
-
-void GraphicsLayer::updateLayerIsDrawable()
-{
- // For the rest of the accelerated compositor code, there is no reason to make a
- // distinction between drawsContent and contentsVisible. So, for m_layer->layer(), these two
- // flags are combined here. m_contentsLayer shouldn't receive the drawsContent flag
- // so it is only given contentsVisible.
-
- m_layer->layer()->setDrawsContent(m_drawsContent && m_contentsVisible);
- if (WebLayer* contentsLayer = contentsLayerIfRegistered())
- contentsLayer->setDrawsContent(m_contentsVisible);
-
- if (m_drawsContent) {
- m_layer->layer()->invalidate();
- for (size_t i = 0; i < m_linkHighlights.size(); ++i)
- m_linkHighlights[i]->invalidate();
- }
-}
-
-void GraphicsLayer::updateContentsRect()
-{
- WebLayer* contentsLayer = contentsLayerIfRegistered();
- if (!contentsLayer)
- return;
-
- contentsLayer->setPosition(FloatPoint(m_contentsRect.x(), m_contentsRect.y()));
- contentsLayer->setBounds(IntSize(m_contentsRect.width(), m_contentsRect.height()));
-}
-
-static HashSet<int>* s_registeredLayerSet;
-
-void GraphicsLayer::registerContentsLayer(WebLayer* layer)
-{
- if (!s_registeredLayerSet)
- s_registeredLayerSet = new HashSet<int>;
- if (s_registeredLayerSet->contains(layer->id()))
- CRASH();
- s_registeredLayerSet->add(layer->id());
-}
-
-void GraphicsLayer::unregisterContentsLayer(WebLayer* layer)
-{
- ASSERT(s_registeredLayerSet);
- if (!s_registeredLayerSet->contains(layer->id()))
- CRASH();
- s_registeredLayerSet->remove(layer->id());
-}
-
-void GraphicsLayer::setContentsTo(ContentsLayerPurpose purpose, WebLayer* layer)
-{
- bool childrenChanged = false;
- if (layer) {
- ASSERT(s_registeredLayerSet);
- if (!s_registeredLayerSet->contains(layer->id()))
- CRASH();
- if (m_contentsLayerId != layer->id()) {
- setupContentsLayer(layer);
- m_contentsLayerPurpose = purpose;
- childrenChanged = true;
- }
- updateContentsRect();
- } else {
- if (m_contentsLayer) {
- childrenChanged = true;
-
- // The old contents layer will be removed via updateChildList.
- m_contentsLayer = 0;
- m_contentsLayerId = 0;
- }
- }
-
- if (childrenChanged)
- updateChildList();
-}
-
-void GraphicsLayer::setupContentsLayer(WebLayer* contentsLayer)
-{
- m_contentsLayer = contentsLayer;
- m_contentsLayerId = m_contentsLayer->id();
-
- if (m_contentsLayer) {
- m_contentsLayer->setWebLayerClient(this);
- m_contentsLayer->setAnchorPoint(FloatPoint(0, 0));
- m_contentsLayer->setUseParentBackfaceVisibility(true);
-
- // It is necessary to call setDrawsContent as soon as we receive the new contentsLayer, for
- // the correctness of early exit conditions in setDrawsContent() and setContentsVisible().
- m_contentsLayer->setDrawsContent(m_contentsVisible);
-
- // Insert the content layer first. Video elements require this, because they have
- // shadow content that must display in front of the video.
- m_layer->layer()->insertChild(m_contentsLayer, 0);
- }
-}
-
-void GraphicsLayer::clearContentsLayerIfUnregistered()
-{
- if (!m_contentsLayerId || s_registeredLayerSet->contains(m_contentsLayerId))
- return;
-
- m_contentsLayer = 0;
- m_contentsLayerId = 0;
-}
-
-WebLayer* GraphicsLayer::contentsLayerIfRegistered()
-{
- clearContentsLayerIfUnregistered();
- return m_contentsLayer;
-}
-
-double GraphicsLayer::backingStoreMemoryEstimate() const
-{
- if (!drawsContent())
- return 0;
-
- // Effects of page and device scale are ignored; subclasses should override to take these into account.
- return static_cast<double>(4 * size().width()) * size().height();
-}
-
-void GraphicsLayer::resetTrackedRepaints()
-{
- repaintRectMap().remove(this);
-}
-
-void GraphicsLayer::addRepaintRect(const FloatRect& repaintRect)
-{
- if (m_client->isTrackingRepaints()) {
- FloatRect largestRepaintRect(FloatPoint(), m_size);
- largestRepaintRect.intersect(repaintRect);
- RepaintMap::iterator repaintIt = repaintRectMap().find(this);
- if (repaintIt == repaintRectMap().end()) {
- Vector<FloatRect> repaintRects;
- repaintRects.append(largestRepaintRect);
- repaintRectMap().set(this, repaintRects);
- } else {
- Vector<FloatRect>& repaintRects = repaintIt->value;
- repaintRects.append(largestRepaintRect);
- }
- }
-}
-
-void GraphicsLayer::writeIndent(TextStream& ts, int indent)
-{
- for (int i = 0; i != indent; ++i)
- ts << " ";
-}
-
-void GraphicsLayer::dumpLayer(TextStream& ts, int indent, LayerTreeFlags flags) const
-{
- writeIndent(ts, indent);
- ts << "(" << "GraphicsLayer";
-
- if (flags & LayerTreeIncludesDebugInfo) {
- ts << " " << static_cast<void*>(const_cast<GraphicsLayer*>(this));
- ts << " \"" << m_client->debugName(this) << "\"";
- }
-
- ts << "\n";
- dumpProperties(ts, indent, flags);
- writeIndent(ts, indent);
- ts << ")\n";
-}
-
-void GraphicsLayer::dumpProperties(TextStream& ts, int indent, LayerTreeFlags flags) const
-{
- if (m_position != FloatPoint()) {
- writeIndent(ts, indent + 1);
- ts << "(position " << m_position.x() << " " << m_position.y() << ")\n";
- }
-
- if (m_boundsOrigin != FloatPoint()) {
- writeIndent(ts, indent + 1);
- ts << "(bounds origin " << m_boundsOrigin.x() << " " << m_boundsOrigin.y() << ")\n";
- }
-
- if (m_anchorPoint != FloatPoint3D(0.5f, 0.5f, 0)) {
- writeIndent(ts, indent + 1);
- ts << "(anchor " << m_anchorPoint.x() << " " << m_anchorPoint.y() << ")\n";
- }
-
- if (m_size != IntSize()) {
- writeIndent(ts, indent + 1);
- ts << "(bounds " << m_size.width() << " " << m_size.height() << ")\n";
- }
-
- if (m_opacity != 1) {
- writeIndent(ts, indent + 1);
- ts << "(opacity " << m_opacity << ")\n";
- }
-
- if (m_contentsOpaque) {
- writeIndent(ts, indent + 1);
- ts << "(contentsOpaque " << m_contentsOpaque << ")\n";
- }
-
- if (m_preserves3D) {
- writeIndent(ts, indent + 1);
- ts << "(preserves3D " << m_preserves3D << ")\n";
- }
-
- if (m_drawsContent) {
- writeIndent(ts, indent + 1);
- ts << "(drawsContent " << m_drawsContent << ")\n";
- }
-
- if (!m_contentsVisible) {
- writeIndent(ts, indent + 1);
- ts << "(contentsVisible " << m_contentsVisible << ")\n";
- }
-
- if (!m_backfaceVisibility) {
- writeIndent(ts, indent + 1);
- ts << "(backfaceVisibility " << (m_backfaceVisibility ? "visible" : "hidden") << ")\n";
- }
-
- if (flags & LayerTreeIncludesDebugInfo) {
- writeIndent(ts, indent + 1);
- ts << "(";
- if (m_client)
- ts << "client " << static_cast<void*>(m_client);
- else
- ts << "no client";
- ts << ")\n";
- }
-
- if (m_backgroundColor.isValid() && m_backgroundColor != Color::transparent) {
- writeIndent(ts, indent + 1);
- ts << "(backgroundColor " << m_backgroundColor.nameForRenderTreeAsText() << ")\n";
- }
-
- if (!m_transform.isIdentity()) {
- writeIndent(ts, indent + 1);
- ts << "(transform ";
- ts << "[" << m_transform.m11() << " " << m_transform.m12() << " " << m_transform.m13() << " " << m_transform.m14() << "] ";
- ts << "[" << m_transform.m21() << " " << m_transform.m22() << " " << m_transform.m23() << " " << m_transform.m24() << "] ";
- ts << "[" << m_transform.m31() << " " << m_transform.m32() << " " << m_transform.m33() << " " << m_transform.m34() << "] ";
- ts << "[" << m_transform.m41() << " " << m_transform.m42() << " " << m_transform.m43() << " " << m_transform.m44() << "])\n";
- }
-
- // Avoid dumping the sublayer transform on the root layer, because it's used for geometry flipping, whose behavior
- // differs between platforms.
- if (parent() && !m_childrenTransform.isIdentity()) {
- writeIndent(ts, indent + 1);
- ts << "(childrenTransform ";
- ts << "[" << m_childrenTransform.m11() << " " << m_childrenTransform.m12() << " " << m_childrenTransform.m13() << " " << m_childrenTransform.m14() << "] ";
- ts << "[" << m_childrenTransform.m21() << " " << m_childrenTransform.m22() << " " << m_childrenTransform.m23() << " " << m_childrenTransform.m24() << "] ";
- ts << "[" << m_childrenTransform.m31() << " " << m_childrenTransform.m32() << " " << m_childrenTransform.m33() << " " << m_childrenTransform.m34() << "] ";
- ts << "[" << m_childrenTransform.m41() << " " << m_childrenTransform.m42() << " " << m_childrenTransform.m43() << " " << m_childrenTransform.m44() << "])\n";
- }
-
- if (m_replicaLayer) {
- writeIndent(ts, indent + 1);
- ts << "(replica layer";
- if (flags & LayerTreeIncludesDebugInfo)
- ts << " " << m_replicaLayer;
- ts << ")\n";
- m_replicaLayer->dumpLayer(ts, indent + 2, flags);
- }
-
- if (m_replicatedLayer) {
- writeIndent(ts, indent + 1);
- ts << "(replicated layer";
- if (flags & LayerTreeIncludesDebugInfo)
- ts << " " << m_replicatedLayer;
- ts << ")\n";
- }
-
- if ((flags & LayerTreeIncludesRepaintRects) && repaintRectMap().contains(this) && !repaintRectMap().get(this).isEmpty()) {
- writeIndent(ts, indent + 1);
- ts << "(repaint rects\n";
- for (size_t i = 0; i < repaintRectMap().get(this).size(); ++i) {
- if (repaintRectMap().get(this)[i].isEmpty())
- continue;
- writeIndent(ts, indent + 2);
- ts << "(rect ";
- ts << repaintRectMap().get(this)[i].x() << " ";
- ts << repaintRectMap().get(this)[i].y() << " ";
- ts << repaintRectMap().get(this)[i].width() << " ";
- ts << repaintRectMap().get(this)[i].height();
- ts << ")\n";
- }
- writeIndent(ts, indent + 1);
- ts << ")\n";
- }
-
- if ((flags & LayerTreeIncludesPaintingPhases) && paintingPhase()) {
- writeIndent(ts, indent + 1);
- ts << "(paintingPhases\n";
- if (paintingPhase() & GraphicsLayerPaintBackground) {
- writeIndent(ts, indent + 2);
- ts << "GraphicsLayerPaintBackground\n";
- }
- if (paintingPhase() & GraphicsLayerPaintForeground) {
- writeIndent(ts, indent + 2);
- ts << "GraphicsLayerPaintForeground\n";
- }
- if (paintingPhase() & GraphicsLayerPaintMask) {
- writeIndent(ts, indent + 2);
- ts << "GraphicsLayerPaintMask\n";
- }
- if (paintingPhase() & GraphicsLayerPaintOverflowContents) {
- writeIndent(ts, indent + 2);
- ts << "GraphicsLayerPaintOverflowContents\n";
- }
- if (paintingPhase() & GraphicsLayerPaintCompositedScroll) {
- writeIndent(ts, indent + 2);
- ts << "GraphicsLayerPaintCompositedScroll\n";
- }
- writeIndent(ts, indent + 1);
- ts << ")\n";
- }
-
- dumpAdditionalProperties(ts, indent, flags);
-
- if (m_children.size()) {
- writeIndent(ts, indent + 1);
- ts << "(children " << m_children.size() << "\n";
-
- unsigned i;
- for (i = 0; i < m_children.size(); i++)
- m_children[i]->dumpLayer(ts, indent + 2, flags);
- writeIndent(ts, indent + 1);
- ts << ")\n";
- }
-}
-
-String GraphicsLayer::layerTreeAsText(LayerTreeFlags flags) const
-{
- TextStream ts;
-
- dumpLayer(ts, 0, flags);
- return ts.release();
-}
-
-WebKit::WebString GraphicsLayer::debugName(WebKit::WebLayer* webLayer)
-{
- String name;
- if (!m_client)
- return name;
-
- String highlightDebugName;
- for (size_t i = 0; i < m_linkHighlights.size(); ++i) {
- if (webLayer == m_linkHighlights[i]->layer()) {
- highlightDebugName = "LinkHighlight[" + String::number(i) + "] for " + m_client->debugName(this);
- break;
- }
- }
-
- if (webLayer == m_contentsLayer) {
- name = "ContentsLayer for " + m_client->debugName(this);
- } else if (!highlightDebugName.isEmpty()) {
- name = highlightDebugName;
- } else if (webLayer == m_layer->layer()) {
- name = m_client->debugName(this);
- } else {
- ASSERT_NOT_REACHED();
- }
- return name;
-}
-
-void GraphicsLayer::setCompositingReasons(WebKit::WebCompositingReasons reasons)
-{
- m_compositingReasons = reasons;
- m_layer->layer()->setCompositingReasons(reasons);
-}
-
-void GraphicsLayer::setPosition(const FloatPoint& point)
-{
- m_position = point;
- platformLayer()->setPosition(m_position);
-}
-
-void GraphicsLayer::setAnchorPoint(const FloatPoint3D& point)
-{
- m_anchorPoint = point;
- platformLayer()->setAnchorPoint(FloatPoint(m_anchorPoint.x(), m_anchorPoint.y()));
- platformLayer()->setAnchorPointZ(m_anchorPoint.z());
-}
-
-void GraphicsLayer::setSize(const FloatSize& size)
-{
- // We are receiving negative sizes here that cause assertions to fail in the compositor. Clamp them to 0 to
- // avoid those assertions.
- // FIXME: This should be an ASSERT instead, as negative sizes should not exist in WebCore.
- FloatSize clampedSize = size;
- if (clampedSize.width() < 0 || clampedSize.height() < 0)
- clampedSize = FloatSize();
-
- if (clampedSize == m_size)
- return;
-
- m_size = clampedSize;
-
- m_layer->layer()->setBounds(flooredIntSize(m_size));
- // Note that we don't resize m_contentsLayer. It's up the caller to do that.
-}
-
-void GraphicsLayer::setTransform(const TransformationMatrix& transform)
-{
- m_transform = transform;
- platformLayer()->setTransform(TransformSkMatrix44Conversions::convert(m_transform));
-}
-
-void GraphicsLayer::setChildrenTransform(const TransformationMatrix& transform)
-{
- m_childrenTransform = transform;
- platformLayer()->setSublayerTransform(TransformSkMatrix44Conversions::convert(m_childrenTransform));
-}
-
-void GraphicsLayer::setPreserves3D(bool preserves3D)
-{
- if (preserves3D == m_preserves3D)
- return;
-
- m_preserves3D = preserves3D;
- m_layer->layer()->setPreserves3D(m_preserves3D);
-}
-
-void GraphicsLayer::setMasksToBounds(bool masksToBounds)
-{
- m_masksToBounds = masksToBounds;
- m_layer->layer()->setMasksToBounds(m_masksToBounds);
-}
-
-void GraphicsLayer::setDrawsContent(bool drawsContent)
-{
- // Note carefully this early-exit is only correct because we also properly call
- // WebLayer::setDrawsContent whenever m_contentsLayer is set to a new layer in setupContentsLayer().
- if (drawsContent == m_drawsContent)
- return;
-
- m_drawsContent = drawsContent;
- updateLayerIsDrawable();
-}
-
-void GraphicsLayer::setContentsVisible(bool contentsVisible)
-{
- // Note carefully this early-exit is only correct because we also properly call
- // WebLayer::setDrawsContent whenever m_contentsLayer is set to a new layer in setupContentsLayer().
- if (contentsVisible == m_contentsVisible)
- return;
-
- m_contentsVisible = contentsVisible;
- updateLayerIsDrawable();
-}
-
-void GraphicsLayer::setBackgroundColor(const Color& color)
-{
- if (color == m_backgroundColor)
- return;
-
- m_backgroundColor = color;
- m_layer->layer()->setBackgroundColor(m_backgroundColor.rgb());
-}
-
-void GraphicsLayer::setContentsOpaque(bool opaque)
-{
- m_contentsOpaque = opaque;
- m_layer->layer()->setOpaque(m_contentsOpaque);
- m_opaqueRectTrackingContentLayerDelegate->setOpaque(m_contentsOpaque);
-}
-
-void GraphicsLayer::setMaskLayer(GraphicsLayer* maskLayer)
-{
- if (maskLayer == m_maskLayer)
- return;
-
- m_maskLayer = maskLayer;
- WebLayer* maskWebLayer = m_maskLayer ? m_maskLayer->platformLayer() : 0;
- m_layer->layer()->setMaskLayer(maskWebLayer);
-}
-
-void GraphicsLayer::setBackfaceVisibility(bool visible)
-{
- m_backfaceVisibility = visible;
- m_layer->setDoubleSided(m_backfaceVisibility);
-}
-
-void GraphicsLayer::setOpacity(float opacity)
-{
- float clampedOpacity = std::max(std::min(opacity, 1.0f), 0.0f);
- m_opacity = clampedOpacity;
- platformLayer()->setOpacity(opacity);
-}
-
-void GraphicsLayer::setContentsNeedsDisplay()
-{
- if (WebLayer* contentsLayer = contentsLayerIfRegistered()) {
- contentsLayer->invalidate();
- addRepaintRect(contentsRect());
- }
-}
-
-void GraphicsLayer::setNeedsDisplay()
-{
- if (drawsContent()) {
- m_layer->layer()->invalidate();
- addRepaintRect(FloatRect(FloatPoint(), m_size));
- for (size_t i = 0; i < m_linkHighlights.size(); ++i)
- m_linkHighlights[i]->invalidate();
- }
-}
-
-void GraphicsLayer::setNeedsDisplayInRect(const FloatRect& rect)
-{
- if (drawsContent()) {
- m_layer->layer()->invalidateRect(rect);
- addRepaintRect(rect);
- for (size_t i = 0; i < m_linkHighlights.size(); ++i)
- m_linkHighlights[i]->invalidate();
- }
-}
-
-void GraphicsLayer::setContentsRect(const IntRect& rect)
-{
- if (rect == m_contentsRect)
- return;
-
- m_contentsRect = rect;
- updateContentsRect();
-}
-
-void GraphicsLayer::setContentsToImage(Image* image)
-{
- bool childrenChanged = false;
- RefPtr<NativeImageSkia> nativeImage = image ? image->nativeImageForCurrentFrame() : 0;
- if (nativeImage) {
- if (m_contentsLayerPurpose != ContentsLayerForImage) {
- m_imageLayer = adoptPtr(Platform::current()->compositorSupport()->createImageLayer());
- registerContentsLayer(m_imageLayer->layer());
-
- setupContentsLayer(m_imageLayer->layer());
- m_contentsLayerPurpose = ContentsLayerForImage;
- childrenChanged = true;
- }
- m_imageLayer->setBitmap(nativeImage->bitmap());
- m_imageLayer->layer()->setOpaque(image->currentFrameKnownToBeOpaque());
- updateContentsRect();
- } else {
- if (m_imageLayer) {
- childrenChanged = true;
-
- unregisterContentsLayer(m_imageLayer->layer());
- m_imageLayer.clear();
- }
- // The old contents layer will be removed via updateChildList.
- m_contentsLayer = 0;
- }
-
- if (childrenChanged)
- updateChildList();
-}
-
-void GraphicsLayer::setContentsToNinePatch(Image* image, const IntRect& aperture)
-{
- if (m_ninePatchLayer) {
- unregisterContentsLayer(m_ninePatchLayer->layer());
- m_ninePatchLayer.clear();
- }
- RefPtr<NativeImageSkia> nativeImage = image ? image->nativeImageForCurrentFrame() : 0;
- if (nativeImage) {
- m_ninePatchLayer = adoptPtr(Platform::current()->compositorSupport()->createNinePatchLayer());
- m_ninePatchLayer->setBitmap(nativeImage->bitmap(), aperture);
- m_ninePatchLayer->layer()->setOpaque(image->currentFrameKnownToBeOpaque());
- registerContentsLayer(m_ninePatchLayer->layer());
- }
- setContentsTo(ContentsLayerForNinePatch, m_ninePatchLayer ? m_ninePatchLayer->layer() : 0);
-}
-
-void GraphicsLayer::setContentsToCanvas(WebLayer* layer)
-{
- setContentsTo(ContentsLayerForCanvas, layer);
-}
-
-void GraphicsLayer::setContentsToMedia(WebLayer* layer)
-{
- setContentsTo(ContentsLayerForVideo, layer);
-}
-
-bool GraphicsLayer::addAnimation(const KeyframeValueList& values, const IntSize& boxSize, const CSSAnimationData* animation, const String& animationName, double timeOffset)
-{
- platformLayer()->setAnimationDelegate(this);
-
- int animationId = 0;
-
- if (m_animationIdMap.contains(animationName))
- animationId = m_animationIdMap.get(animationName);
-
- OwnPtr<WebAnimation> toAdd(createWebAnimation(values, animation, animationId, timeOffset, boxSize));
-
- if (toAdd) {
- animationId = toAdd->id();
- m_animationIdMap.set(animationName, animationId);
-
- // Remove any existing animations with the same animation id and target property.
- platformLayer()->removeAnimation(animationId, toAdd->targetProperty());
- return platformLayer()->addAnimation(toAdd.get());
- }
-
- return false;
-}
-
-void GraphicsLayer::pauseAnimation(const String& animationName, double timeOffset)
-{
- if (m_animationIdMap.contains(animationName))
- platformLayer()->pauseAnimation(m_animationIdMap.get(animationName), timeOffset);
-}
-
-void GraphicsLayer::removeAnimation(const String& animationName)
-{
- if (m_animationIdMap.contains(animationName))
- platformLayer()->removeAnimation(m_animationIdMap.get(animationName));
-}
-
-void GraphicsLayer::suspendAnimations(double wallClockTime)
-{
- // |wallClockTime| is in the wrong time base. Need to convert here.
- // FIXME: find a more reliable way to do this.
- double monotonicTime = wallClockTime + monotonicallyIncreasingTime() - currentTime();
- platformLayer()->suspendAnimations(monotonicTime);
-}
-
-void GraphicsLayer::resumeAnimations()
-{
- platformLayer()->resumeAnimations(monotonicallyIncreasingTime());
-}
-
-WebLayer* GraphicsLayer::platformLayer() const
-{
- return m_layer->layer();
-}
-
-static bool copyWebCoreFilterOperationsToWebFilterOperations(const FilterOperations& filters, WebFilterOperations& webFilters)
-{
- for (size_t i = 0; i < filters.size(); ++i) {
- const FilterOperation& op = *filters.at(i);
- switch (op.getOperationType()) {
- case FilterOperation::REFERENCE:
- return false; // Not supported.
- case FilterOperation::GRAYSCALE:
- case FilterOperation::SEPIA:
- case FilterOperation::SATURATE:
- case FilterOperation::HUE_ROTATE: {
- float amount = static_cast<const BasicColorMatrixFilterOperation*>(&op)->amount();
- switch (op.getOperationType()) {
- case FilterOperation::GRAYSCALE:
- webFilters.appendGrayscaleFilter(amount);
- break;
- case FilterOperation::SEPIA:
- webFilters.appendSepiaFilter(amount);
- break;
- case FilterOperation::SATURATE:
- webFilters.appendSaturateFilter(amount);
- break;
- case FilterOperation::HUE_ROTATE:
- webFilters.appendHueRotateFilter(amount);
- break;
- default:
- ASSERT_NOT_REACHED();
- }
- break;
- }
- case FilterOperation::INVERT:
- case FilterOperation::OPACITY:
- case FilterOperation::BRIGHTNESS:
- case FilterOperation::CONTRAST: {
- float amount = static_cast<const BasicComponentTransferFilterOperation*>(&op)->amount();
- switch (op.getOperationType()) {
- case FilterOperation::INVERT:
- webFilters.appendInvertFilter(amount);
- break;
- case FilterOperation::OPACITY:
- webFilters.appendOpacityFilter(amount);
- break;
- case FilterOperation::BRIGHTNESS:
- webFilters.appendBrightnessFilter(amount);
- break;
- case FilterOperation::CONTRAST:
- webFilters.appendContrastFilter(amount);
- break;
- default:
- ASSERT_NOT_REACHED();
- }
- break;
- }
- case FilterOperation::BLUR: {
- float pixelRadius = static_cast<const BlurFilterOperation*>(&op)->stdDeviation().getFloatValue();
- webFilters.appendBlurFilter(pixelRadius);
- break;
- }
- case FilterOperation::DROP_SHADOW: {
- const DropShadowFilterOperation& dropShadowOp = *static_cast<const DropShadowFilterOperation*>(&op);
- webFilters.appendDropShadowFilter(WebPoint(dropShadowOp.x(), dropShadowOp.y()), dropShadowOp.stdDeviation(), dropShadowOp.color().rgb());
- break;
- }
- case FilterOperation::CUSTOM:
- case FilterOperation::VALIDATED_CUSTOM:
- return false; // Not supported.
- case FilterOperation::PASSTHROUGH:
- case FilterOperation::NONE:
- break;
- }
- }
- return true;
-}
-
-bool GraphicsLayer::setFilters(const FilterOperations& filters)
-{
- // FIXME: For now, we only use SkImageFilters if there is a reference
- // filter in the chain. Once all issues have been ironed out, we should
- // switch all filtering over to this path, and remove setFilters() and
- // WebFilterOperations altogether.
- if (filters.hasReferenceFilter()) {
- if (filters.hasCustomFilter()) {
- // Make sure the filters are removed from the platform layer, as they are
- // going to fallback to software mode.
- m_layer->layer()->setFilter(0);
- m_filters = FilterOperations();
- return false;
- }
- SkiaImageFilterBuilder builder;
- FilterOutsets outsets = filters.outsets();
- builder.setCropOffset(FloatSize(outsets.left(), outsets.top()));
- RefPtr<SkImageFilter> imageFilter = builder.build(filters);
- m_layer->layer()->setFilter(imageFilter.get());
- } else {
- OwnPtr<WebFilterOperations> webFilters = adoptPtr(Platform::current()->compositorSupport()->createFilterOperations());
- if (!copyWebCoreFilterOperationsToWebFilterOperations(filters, *webFilters)) {
- // Make sure the filters are removed from the platform layer, as they are
- // going to fallback to software mode.
- webFilters->clear();
- m_layer->layer()->setFilters(*webFilters);
- m_filters = FilterOperations();
- return false;
- }
- m_layer->layer()->setFilters(*webFilters);
- }
-
- m_filters = filters;
- return true;
-}
-
-void GraphicsLayer::setBackgroundFilters(const FilterOperations& filters)
-{
- OwnPtr<WebFilterOperations> webFilters = adoptPtr(Platform::current()->compositorSupport()->createFilterOperations());
- if (!copyWebCoreFilterOperationsToWebFilterOperations(filters, *webFilters))
- return;
- m_layer->layer()->setBackgroundFilters(*webFilters);
-}
-
-void GraphicsLayer::addLinkHighlight(LinkHighlightClient* linkHighlight)
-{
- ASSERT(linkHighlight && !m_linkHighlights.contains(linkHighlight));
- m_linkHighlights.append(linkHighlight);
- linkHighlight->layer()->setWebLayerClient(this);
- updateChildList();
-}
-
-void GraphicsLayer::removeLinkHighlight(LinkHighlightClient* linkHighlight)
-{
- m_linkHighlights.remove(m_linkHighlights.find(linkHighlight));
- updateChildList();
-}
-
-void GraphicsLayer::setScrollableArea(ScrollableArea* scrollableArea, bool isMainFrame)
-{
- if (m_scrollableArea == scrollableArea)
- return;
-
- m_scrollableArea = scrollableArea;
-
- // Main frame scrolling may involve pinch zoom and gets routed through
- // WebViewImpl explicitly rather than via GraphicsLayer::didScroll.
- if (isMainFrame)
- m_layer->layer()->setScrollClient(0);
- else
- m_layer->layer()->setScrollClient(this);
-}
-
-void GraphicsLayer::paint(GraphicsContext& context, const IntRect& clip)
-{
- paintGraphicsLayerContents(context, clip);
-}
-
-
-void GraphicsLayer::notifyAnimationStarted(double startTime)
-{
- if (m_client)
- m_client->notifyAnimationStarted(this, startTime);
-}
-
-void GraphicsLayer::notifyAnimationFinished(double)
-{
- // Do nothing.
-}
-
-void GraphicsLayer::didScroll()
-{
- if (m_scrollableArea)
- m_scrollableArea->scrollToOffsetWithoutAnimation(m_scrollableArea->minimumScrollPosition() + toIntSize(m_layer->layer()->scrollPosition()));
-}
-
-} // namespace WebCore
-
-#ifndef NDEBUG
-void showGraphicsLayerTree(const WebCore::GraphicsLayer* layer)
-{
- if (!layer)
- return;
-
- String output = layer->layerTreeAsText(WebCore::LayerTreeIncludesDebugInfo);
- fprintf(stderr, "%s\n", output.utf8().data());
-}
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsLayer.h b/chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsLayer.h
deleted file mode 100644
index ddd26099d6b..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsLayer.h
+++ /dev/null
@@ -1,428 +0,0 @@
-/*
- * Copyright (C) 2009 Apple Inc. All rights reserved.
- * Copyright (C) 2013 Intel Corporation. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef GraphicsLayer_h
-#define GraphicsLayer_h
-
-#include "core/platform/animation/CSSAnimationData.h"
-#include "core/platform/animation/KeyframeValueList.h"
-#include "core/platform/graphics/Color.h"
-#include "core/platform/graphics/FloatPoint.h"
-#include "core/platform/graphics/FloatPoint3D.h"
-#include "core/platform/graphics/FloatSize.h"
-#include "core/platform/graphics/GraphicsLayerClient.h"
-#include "core/platform/graphics/IntRect.h"
-#include "core/platform/graphics/chromium/OpaqueRectTrackingContentLayerDelegate.h"
-#include "core/platform/graphics/filters/FilterOperations.h"
-#include "core/platform/graphics/transforms/TransformationMatrix.h"
-
-#include "wtf/HashMap.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/Vector.h"
-
-#include "public/platform/WebAnimationDelegate.h"
-#include "public/platform/WebCompositingReasons.h"
-#include "public/platform/WebContentLayer.h"
-#include "public/platform/WebImageLayer.h"
-#include "public/platform/WebLayerClient.h"
-#include "public/platform/WebLayerScrollClient.h"
-#include "public/platform/WebNinePatchLayer.h"
-#include "public/platform/WebSolidColorLayer.h"
-
-namespace WebKit {
-class GraphicsLayerFactoryChromium;
-class WebLayer;
-}
-
-namespace WebCore {
-
-class FloatRect;
-class GraphicsContext;
-class GraphicsLayerFactory;
-class Image;
-class ScrollableArea;
-class TextStream;
-
-// FIXME: find a better home for this declaration.
-class LinkHighlightClient {
-public:
- virtual void invalidate() = 0;
- virtual void clearCurrentGraphicsLayer() = 0;
- virtual WebKit::WebLayer* layer() = 0;
-
-protected:
- virtual ~LinkHighlightClient() { }
-};
-
-// GraphicsLayer is an abstraction for a rendering surface with backing store,
-// which may have associated transformation and animations.
-
-class GraphicsLayer : public GraphicsContextPainter, public WebKit::WebAnimationDelegate, public WebKit::WebLayerScrollClient, public WebKit::WebLayerClient {
- WTF_MAKE_NONCOPYABLE(GraphicsLayer); WTF_MAKE_FAST_ALLOCATED;
-public:
- enum ContentsLayerPurpose {
- NoContentsLayer = 0,
- ContentsLayerForImage,
- ContentsLayerForNinePatch,
- ContentsLayerForVideo,
- ContentsLayerForCanvas,
- };
-
- static PassOwnPtr<GraphicsLayer> create(GraphicsLayerFactory*, GraphicsLayerClient*);
-
- virtual ~GraphicsLayer();
-
- GraphicsLayerClient* client() const { return m_client; }
-
- // WebKit::WebLayerClient implementation.
- virtual WebKit::WebString debugName(WebKit::WebLayer*) OVERRIDE;
-
- void setCompositingReasons(WebKit::WebCompositingReasons);
- WebKit::WebCompositingReasons compositingReasons() const { return m_compositingReasons; }
-
- GraphicsLayer* parent() const { return m_parent; };
- void setParent(GraphicsLayer*); // Internal use only.
-
- // Returns true if the layer has the given layer as an ancestor (excluding self).
- bool hasAncestor(GraphicsLayer*) const;
-
- const Vector<GraphicsLayer*>& children() const { return m_children; }
- // Returns true if the child list changed.
- bool setChildren(const Vector<GraphicsLayer*>&);
-
- // Add child layers. If the child is already parented, it will be removed from its old parent.
- void addChild(GraphicsLayer*);
- void addChildAtIndex(GraphicsLayer*, int index);
- void addChildAbove(GraphicsLayer*, GraphicsLayer* sibling);
- void addChildBelow(GraphicsLayer*, GraphicsLayer* sibling);
- bool replaceChild(GraphicsLayer* oldChild, GraphicsLayer* newChild);
-
- void removeAllChildren();
- void removeFromParent();
-
- GraphicsLayer* maskLayer() const { return m_maskLayer; }
- void setMaskLayer(GraphicsLayer*);
-
- // The given layer will replicate this layer and its children; the replica renders behind this layer.
- void setReplicatedByLayer(GraphicsLayer*);
- // Whether this layer is being replicated by another layer.
- bool isReplicated() const { return m_replicaLayer; }
- // The layer that replicates this layer (if any).
- GraphicsLayer* replicaLayer() const { return m_replicaLayer; }
- // The layer being replicated.
- GraphicsLayer* replicatedLayer() const { return m_replicatedLayer; }
-
- const FloatPoint& replicatedLayerPosition() const { return m_replicatedLayerPosition; }
- void setReplicatedLayerPosition(const FloatPoint& p) { m_replicatedLayerPosition = p; }
-
- enum ShouldSetNeedsDisplay {
- DontSetNeedsDisplay,
- SetNeedsDisplay
- };
-
- // Offset is origin of the renderer minus origin of the graphics layer (so either zero or negative).
- IntSize offsetFromRenderer() const { return m_offsetFromRenderer; }
- void setOffsetFromRenderer(const IntSize&, ShouldSetNeedsDisplay = SetNeedsDisplay);
-
- // The position of the layer (the location of its top-left corner in its parent)
- const FloatPoint& position() const { return m_position; }
- void setPosition(const FloatPoint&);
-
- // Anchor point: (0, 0) is top left, (1, 1) is bottom right. The anchor point
- // affects the origin of the transforms.
- const FloatPoint3D& anchorPoint() const { return m_anchorPoint; }
- void setAnchorPoint(const FloatPoint3D&);
-
- // The size of the layer.
- const FloatSize& size() const { return m_size; }
- void setSize(const FloatSize&);
-
- // The boundOrigin affects the offset at which content is rendered, and sublayers are positioned.
- const FloatPoint& boundsOrigin() const { return m_boundsOrigin; }
- void setBoundsOrigin(const FloatPoint& origin) { m_boundsOrigin = origin; }
-
- const TransformationMatrix& transform() const { return m_transform; }
- void setTransform(const TransformationMatrix&);
-
- const TransformationMatrix& childrenTransform() const { return m_childrenTransform; }
- void setChildrenTransform(const TransformationMatrix&);
-
- bool preserves3D() const { return m_preserves3D; }
- void setPreserves3D(bool);
-
- bool masksToBounds() const { return m_masksToBounds; }
- void setMasksToBounds(bool);
-
- bool drawsContent() const { return m_drawsContent; }
- void setDrawsContent(bool);
-
- bool contentsAreVisible() const { return m_contentsVisible; }
- void setContentsVisible(bool);
-
- // For special cases, e.g. drawing missing tiles on Android.
- // The compositor should never paint this color in normal cases because the RenderLayer
- // will paint background by itself.
- const Color& backgroundColor() const { return m_backgroundColor; }
- void setBackgroundColor(const Color&);
-
- // opaque means that we know the layer contents have no alpha
- bool contentsOpaque() const { return m_contentsOpaque; }
- void setContentsOpaque(bool);
-
- bool backfaceVisibility() const { return m_backfaceVisibility; }
- void setBackfaceVisibility(bool visible);
-
- float opacity() const { return m_opacity; }
- void setOpacity(float);
-
- const FilterOperations& filters() const { return m_filters; }
-
- // Returns true if filter can be rendered by the compositor
- bool setFilters(const FilterOperations&);
- void setBackgroundFilters(const FilterOperations&);
-
- // Some GraphicsLayers paint only the foreground or the background content
- GraphicsLayerPaintingPhase paintingPhase() const { return m_paintingPhase; }
- void setPaintingPhase(GraphicsLayerPaintingPhase phase) { m_paintingPhase = phase; }
-
- void setNeedsDisplay();
- // mark the given rect (in layer coords) as needing dispay. Never goes deep.
- void setNeedsDisplayInRect(const FloatRect&);
-
- void setContentsNeedsDisplay();
-
- // Set that the position/size of the contents (image or video).
- IntRect contentsRect() const { return m_contentsRect; }
- void setContentsRect(const IntRect&);
-
- // Transitions are identified by a special animation name that cannot clash with a keyframe identifier.
- static String animationNameForTransition(AnimatedPropertyID);
-
- // Return true if the animation is handled by the compositing system. If this returns
- // false, the animation will be run by AnimationController.
- // These methods handle both transitions and keyframe animations.
- bool addAnimation(const KeyframeValueList&, const IntSize& /*boxSize*/, const CSSAnimationData*, const String& /*animationName*/, double /*timeOffset*/);
- void pauseAnimation(const String& /*animationName*/, double /*timeOffset*/);
- void removeAnimation(const String& /*animationName*/);
-
- void suspendAnimations(double time);
- void resumeAnimations();
-
- // Layer contents
- void setContentsToImage(Image*);
- void setContentsToNinePatch(Image*, const IntRect& aperture);
- bool shouldDirectlyCompositeImage(Image*) const { return true; }
- void setContentsToMedia(WebKit::WebLayer*); // video or plug-in
- // Pass an invalid color to remove the contents layer.
- void setContentsToSolidColor(const Color&) { }
- void setContentsToCanvas(WebKit::WebLayer*);
- // FIXME: webkit.org/b/109658
- // Should unify setContentsToMedia and setContentsToCanvas
- void setContentsToPlatformLayer(WebKit::WebLayer* layer) { setContentsToMedia(layer); }
- bool hasContentsLayer() const { return m_contentsLayer; }
-
- // Callback from the underlying graphics system to draw layer contents.
- void paintGraphicsLayerContents(GraphicsContext&, const IntRect& clip);
- // Callback from the underlying graphics system when the layer has been displayed
- void layerDidDisplay(WebKit::WebLayer*) { }
-
- // For hosting this GraphicsLayer in a native layer hierarchy.
- WebKit::WebLayer* platformLayer() const;
-
- enum CompositingCoordinatesOrientation { CompositingCoordinatesTopDown, CompositingCoordinatesBottomUp };
-
- // Flippedness of the contents of this layer. Does not affect sublayer geometry.
- void setContentsOrientation(CompositingCoordinatesOrientation orientation) { m_contentsOrientation = orientation; }
- CompositingCoordinatesOrientation contentsOrientation() const { return m_contentsOrientation; }
-
- void dumpLayer(TextStream&, int indent = 0, LayerTreeFlags = LayerTreeNormal) const;
-
- int paintCount() const { return m_paintCount; }
-
- // z-position is the z-equivalent of position(). It's only used for debugging purposes.
- float zPosition() const { return m_zPosition; }
- void setZPosition(float);
-
- void distributeOpacity(float);
- float accumulatedOpacity() const;
-
- // If the exposed rect of this layer changes, returns true if this or descendant layers need a flush,
- // for example to allocate new tiles.
- bool visibleRectChangeRequiresFlush(const FloatRect& /* clipRect */) const { return false; }
-
- // Return a string with a human readable form of the layer tree, If debug is true
- // pointers for the layers and timing data will be included in the returned string.
- String layerTreeAsText(LayerTreeFlags = LayerTreeNormal) const;
-
- // Return an estimate of the backing store memory cost (in bytes). May be incorrect for tiled layers.
- double backingStoreMemoryEstimate() const;
-
- void resetTrackedRepaints();
- void addRepaintRect(const FloatRect&);
-
- static bool supportsBackgroundColorContent()
- {
- return false;
- }
-
- void addLinkHighlight(LinkHighlightClient*);
- void removeLinkHighlight(LinkHighlightClient*);
- // Exposed for tests
- unsigned numLinkHighlights() { return m_linkHighlights.size(); }
- LinkHighlightClient* linkHighlight(int i) { return m_linkHighlights[i]; }
-
- void setScrollableArea(ScrollableArea*, bool isMainFrame);
- ScrollableArea* scrollableArea() const { return m_scrollableArea; }
-
- WebKit::WebContentLayer* contentLayer() const { return m_layer.get(); }
-
- // Exposed for tests. FIXME - name is too similar to contentLayer(), very error prone.
- WebKit::WebLayer* contentsLayer() const { return m_contentsLayer; }
-
- static void registerContentsLayer(WebKit::WebLayer*);
- static void unregisterContentsLayer(WebKit::WebLayer*);
-
- // GraphicsContextPainter implementation.
- virtual void paint(GraphicsContext&, const IntRect& clip) OVERRIDE;
-
- // WebAnimationDelegate implementation.
- virtual void notifyAnimationStarted(double startTime) OVERRIDE;
- virtual void notifyAnimationFinished(double finishTime) OVERRIDE;
-
- // WebLayerScrollClient implementation.
- virtual void didScroll() OVERRIDE;
-
-protected:
- explicit GraphicsLayer(GraphicsLayerClient*);
- // GraphicsLayerFactoryChromium that wants to create a GraphicsLayer need to be friends.
- friend class WebKit::GraphicsLayerFactoryChromium;
-
-private:
- // Adds a child without calling updateChildList(), so that adding children
- // can be batched before updating.
- void addChildInternal(GraphicsLayer*);
-
- // This method is used by platform GraphicsLayer classes to clear the filters
- // when compositing is not done in hardware. It is not virtual, so the caller
- // needs to notifiy the change to the platform layer as needed.
- void clearFilters() { m_filters.clear(); }
-
- void setReplicatedLayer(GraphicsLayer* layer) { m_replicatedLayer = layer; }
-
- int incrementPaintCount() { return ++m_paintCount; }
-
- static void writeIndent(TextStream&, int indent);
-
- void dumpProperties(TextStream&, int indent, LayerTreeFlags) const;
- void dumpAdditionalProperties(TextStream&, int /*indent*/, LayerTreeFlags) const { }
-
- // Helper functions used by settors to keep layer's the state consistent.
- void updateChildList();
- void updateLayerIsDrawable();
- void updateContentsRect();
-
- void setContentsTo(ContentsLayerPurpose, WebKit::WebLayer*);
- void setupContentsLayer(WebKit::WebLayer*);
- void clearContentsLayerIfUnregistered();
- WebKit::WebLayer* contentsLayerIfRegistered();
-
- GraphicsLayerClient* m_client;
-
- // Offset from the owning renderer
- IntSize m_offsetFromRenderer;
-
- // Position is relative to the parent GraphicsLayer
- FloatPoint m_position;
- FloatPoint3D m_anchorPoint;
- FloatSize m_size;
- FloatPoint m_boundsOrigin;
-
- TransformationMatrix m_transform;
- TransformationMatrix m_childrenTransform;
-
- Color m_backgroundColor;
- float m_opacity;
- float m_zPosition;
-
- FilterOperations m_filters;
-
- bool m_contentsOpaque : 1;
- bool m_preserves3D: 1;
- bool m_backfaceVisibility : 1;
- bool m_masksToBounds : 1;
- bool m_drawsContent : 1;
- bool m_contentsVisible : 1;
-
- GraphicsLayerPaintingPhase m_paintingPhase;
- CompositingCoordinatesOrientation m_contentsOrientation; // affects orientation of layer contents
-
- Vector<GraphicsLayer*> m_children;
- GraphicsLayer* m_parent;
-
- GraphicsLayer* m_maskLayer; // Reference to mask layer. We don't own this.
-
- GraphicsLayer* m_replicaLayer; // A layer that replicates this layer. We only allow one, for now.
- // The replica is not parented; this is the primary reference to it.
- GraphicsLayer* m_replicatedLayer; // For a replica layer, a reference to the original layer.
- FloatPoint m_replicatedLayerPosition; // For a replica layer, the position of the replica.
-
- IntRect m_contentsRect;
-
- int m_paintCount;
-
- OwnPtr<WebKit::WebContentLayer> m_layer;
- OwnPtr<WebKit::WebImageLayer> m_imageLayer;
- OwnPtr<WebKit::WebNinePatchLayer> m_ninePatchLayer;
- WebKit::WebLayer* m_contentsLayer;
- // We don't have ownership of m_contentsLayer, but we do want to know if a given layer is the
- // same as our current layer in setContentsTo(). Since m_contentsLayer may be deleted at this point,
- // we stash an ID away when we know m_contentsLayer is alive and use that for comparisons from that point
- // on.
- int m_contentsLayerId;
-
- Vector<LinkHighlightClient*> m_linkHighlights;
-
- OwnPtr<OpaqueRectTrackingContentLayerDelegate> m_opaqueRectTrackingContentLayerDelegate;
-
- ContentsLayerPurpose m_contentsLayerPurpose;
-
- typedef HashMap<String, int> AnimationIdMap;
- AnimationIdMap m_animationIdMap;
-
- ScrollableArea* m_scrollableArea;
- WebKit::WebCompositingReasons m_compositingReasons;
-};
-
-
-} // namespace WebCore
-
-#ifndef NDEBUG
-// Outside the WebCore namespace for ease of invocation from gdb.
-void showGraphicsLayerTree(const WebCore::GraphicsLayer* layer);
-#endif
-
-#endif // GraphicsLayer_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsLayerClient.h b/chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsLayerClient.h
deleted file mode 100644
index 88915ebbe3e..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsLayerClient.h
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * Copyright (C) 2009 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef GraphicsLayerClient_h
-#define GraphicsLayerClient_h
-
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class FloatPoint;
-class GraphicsContext;
-class GraphicsLayer;
-class IntPoint;
-class IntRect;
-class TransformationMatrix;
-
-enum GraphicsLayerPaintingPhaseFlags {
- GraphicsLayerPaintBackground = (1 << 0),
- GraphicsLayerPaintForeground = (1 << 1),
- GraphicsLayerPaintMask = (1 << 2),
- GraphicsLayerPaintOverflowContents = (1 << 3),
- GraphicsLayerPaintCompositedScroll = (1 << 4),
- GraphicsLayerPaintAllWithOverflowClip = (GraphicsLayerPaintBackground | GraphicsLayerPaintForeground | GraphicsLayerPaintMask)
-};
-typedef unsigned GraphicsLayerPaintingPhase;
-
-enum {
- LayerTreeNormal = 0,
- LayerTreeIncludesDebugInfo = 1 << 0, // Dump extra debugging info like layer addresses.
- LayerTreeIncludesRepaintRects = 1 << 1,
- LayerTreeIncludesPaintingPhases = 1 << 2,
- LayerTreeIncludesRootLayer = 1 << 3
-};
-typedef unsigned LayerTreeFlags;
-
-class GraphicsLayerClient {
-public:
- virtual ~GraphicsLayerClient() {}
-
- // Callback for when hardware-accelerated animation started.
- virtual void notifyAnimationStarted(const GraphicsLayer*, double time) = 0;
-
- virtual void paintContents(const GraphicsLayer*, GraphicsContext&, GraphicsLayerPaintingPhase, const IntRect& inClip) = 0;
- virtual void didCommitChangesForLayer(const GraphicsLayer*) const { }
-
- // Provides current transform (taking transform-origin and animations into account). Input matrix has been
- // initialized to identity already. Returns false if the layer has no transform.
- virtual bool getCurrentTransform(const GraphicsLayer*, TransformationMatrix&) const { return false; }
-
- virtual bool isTrackingRepaints() const { return false; }
-
- virtual String debugName(const GraphicsLayer*) = 0;
-
-#ifndef NDEBUG
- // RenderLayerBacking overrides this to verify that it is not
- // currently painting contents. An ASSERT fails, if it is.
- // This is executed in GraphicsLayer construction and destruction
- // to verify that we don't create or destroy GraphicsLayers
- // while painting.
- virtual void verifyNotPainting() { }
-#endif
-};
-
-} // namespace WebCore
-
-#endif // GraphicsLayerClient_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsLayerFactory.h b/chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsLayerFactory.h
deleted file mode 100644
index da054e84f71..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsLayerFactory.h
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright (C) 2012 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef GraphicsLayerFactory_h
-#define GraphicsLayerFactory_h
-
-#include "wtf/Forward.h"
-
-namespace WebCore {
-
-class GraphicsLayer;
-class GraphicsLayerClient;
-
-class GraphicsLayerFactory {
-public:
- virtual ~GraphicsLayerFactory() { }
-
- virtual PassOwnPtr<GraphicsLayer> createGraphicsLayer(GraphicsLayerClient*) = 0;
-};
-
-} // namespace WebCore
-
-#endif // GraphicsLayerFactory_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsTypes.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsTypes.cpp
deleted file mode 100644
index 62734359354..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsTypes.cpp
+++ /dev/null
@@ -1,226 +0,0 @@
-/*
- * Copyright (C) 2006 Apple Computer, Inc. All rights reserved.
- * Copyright (C) 2012 Rik Cabanier (cabanier@adobe.com)
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/GraphicsTypes.h"
-
-#include "wtf/Assertions.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-static const char* const compositeOperatorNames[] = {
- "clear",
- "copy",
- "source-over",
- "source-in",
- "source-out",
- "source-atop",
- "destination-over",
- "destination-in",
- "destination-out",
- "destination-atop",
- "xor",
- "darker",
- "lighter"
-};
-
-static const char* const blendOperatorNames[] = {
- "multiply",
- "screen",
- "overlay",
- "darken",
- "lighten",
- "color-dodge",
- "color-burn",
- "hard-light",
- "soft-light",
- "difference",
- "exclusion",
- "hue",
- "saturation",
- "color",
- "luminosity"
-};
-const int numCompositeOperatorNames = WTF_ARRAY_LENGTH(compositeOperatorNames);
-const int numBlendOperatorNames = WTF_ARRAY_LENGTH(blendOperatorNames);
-
-bool parseCompositeAndBlendOperator(const String& s, CompositeOperator& op, BlendMode& blendOp)
-{
- for (int i = 0; i < numCompositeOperatorNames; i++) {
- if (s == compositeOperatorNames[i]) {
- op = static_cast<CompositeOperator>(i);
- blendOp = BlendModeNormal;
- return true;
- }
- }
-
- for (int i = 0; i < numBlendOperatorNames; i++) {
- if (s == blendOperatorNames[i]) {
- blendOp = static_cast<BlendMode>(i+1);
- // For now, blending will always assume source-over. This will be fixed in the future
- op = CompositeSourceOver;
- return true;
- }
- }
-
- return false;
-}
-
-// FIXME: when we support blend modes in combination with compositing other than source-over
-// this routine needs to be updated.
-String compositeOperatorName(CompositeOperator op, BlendMode blendOp)
-{
- ASSERT(op >= 0);
- ASSERT(op < numCompositeOperatorNames);
- ASSERT(blendOp >= 0);
- ASSERT(blendOp <= numBlendOperatorNames);
- if (blendOp != BlendModeNormal)
- return blendOperatorNames[blendOp-1];
- return compositeOperatorNames[op];
-}
-
-bool parseLineCap(const String& s, LineCap& cap)
-{
- if (s == "butt") {
- cap = ButtCap;
- return true;
- }
- if (s == "round") {
- cap = RoundCap;
- return true;
- }
- if (s == "square") {
- cap = SquareCap;
- return true;
- }
- return false;
-}
-
-String lineCapName(LineCap cap)
-{
- ASSERT(cap >= 0);
- ASSERT(cap < 3);
- const char* const names[3] = { "butt", "round", "square" };
- return names[cap];
-}
-
-bool parseLineJoin(const String& s, LineJoin& join)
-{
- if (s == "miter") {
- join = MiterJoin;
- return true;
- }
- if (s == "round") {
- join = RoundJoin;
- return true;
- }
- if (s == "bevel") {
- join = BevelJoin;
- return true;
- }
- return false;
-}
-
-String lineJoinName(LineJoin join)
-{
- ASSERT(join >= 0);
- ASSERT(join < 3);
- const char* const names[3] = { "miter", "round", "bevel" };
- return names[join];
-}
-
-String textAlignName(TextAlign align)
-{
- ASSERT(align >= 0);
- ASSERT(align < 5);
- const char* const names[5] = { "start", "end", "left", "center", "right" };
- return names[align];
-}
-
-bool parseTextAlign(const String& s, TextAlign& align)
-{
- if (s == "start") {
- align = StartTextAlign;
- return true;
- }
- if (s == "end") {
- align = EndTextAlign;
- return true;
- }
- if (s == "left") {
- align = LeftTextAlign;
- return true;
- }
- if (s == "center") {
- align = CenterTextAlign;
- return true;
- }
- if (s == "right") {
- align = RightTextAlign;
- return true;
- }
- return false;
-}
-
-String textBaselineName(TextBaseline baseline)
-{
- ASSERT(baseline >= 0);
- ASSERT(baseline < 6);
- const char* const names[6] = { "alphabetic", "top", "middle", "bottom", "ideographic", "hanging" };
- return names[baseline];
-}
-
-bool parseTextBaseline(const String& s, TextBaseline& baseline)
-{
- if (s == "alphabetic") {
- baseline = AlphabeticTextBaseline;
- return true;
- }
- if (s == "top") {
- baseline = TopTextBaseline;
- return true;
- }
- if (s == "middle") {
- baseline = MiddleTextBaseline;
- return true;
- }
- if (s == "bottom") {
- baseline = BottomTextBaseline;
- return true;
- }
- if (s == "ideographic") {
- baseline = IdeographicTextBaseline;
- return true;
- }
- if (s == "hanging") {
- baseline = HangingTextBaseline;
- return true;
- }
- return false;
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsTypes.h b/chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsTypes.h
deleted file mode 100644
index f83697973e9..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsTypes.h
+++ /dev/null
@@ -1,138 +0,0 @@
-/*
- * Copyright (C) 2004, 2005, 2006 Apple Computer, Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef GraphicsTypes_h
-#define GraphicsTypes_h
-
-#include "third_party/skia/include/core/SkPaint.h"
-
-#include "wtf/Forward.h"
-
-namespace WebCore {
-
-enum StrokeStyle {
- NoStroke,
- SolidStroke,
- DottedStroke,
- DashedStroke,
- DoubleStroke,
- WavyStroke,
-};
-
-enum InterpolationQuality {
- InterpolationDefault,
- InterpolationNone,
- InterpolationLow,
- InterpolationMedium,
- InterpolationHigh
-};
-
-enum CompositeOperator {
- CompositeClear,
- CompositeCopy,
- CompositeSourceOver,
- CompositeSourceIn,
- CompositeSourceOut,
- CompositeSourceAtop,
- CompositeDestinationOver,
- CompositeDestinationIn,
- CompositeDestinationOut,
- CompositeDestinationAtop,
- CompositeXOR,
- CompositePlusDarker,
- CompositePlusLighter,
- CompositeDifference
-};
-
-// keep it in sync with gMapBlendOpsToXfermodeModes array in SkiaUtils.h
-enum BlendMode {
- BlendModeNormal,
- BlendModeMultiply,
- BlendModeScreen,
- BlendModeOverlay,
- BlendModeDarken,
- BlendModeLighten,
- BlendModeColorDodge,
- BlendModeColorBurn,
- BlendModeHardLight,
- BlendModeSoftLight,
- BlendModeDifference,
- BlendModeExclusion,
- BlendModeHue,
- BlendModeSaturation,
- BlendModeColor,
- BlendModeLuminosity
-};
-
-enum GradientSpreadMethod {
- SpreadMethodPad,
- SpreadMethodReflect,
- SpreadMethodRepeat
-};
-
-enum LineCap {
- ButtCap = SkPaint::kButt_Cap,
- RoundCap = SkPaint::kRound_Cap,
- SquareCap = SkPaint::kSquare_Cap
-};
-
-enum LineJoin {
- MiterJoin = SkPaint::kMiter_Join,
- RoundJoin = SkPaint::kRound_Join,
- BevelJoin = SkPaint::kBevel_Join
-};
-
-enum HorizontalAlignment { AlignLeft, AlignRight, AlignHCenter };
-
-enum TextBaseline { AlphabeticTextBaseline, TopTextBaseline, MiddleTextBaseline, BottomTextBaseline, IdeographicTextBaseline, HangingTextBaseline };
-
-enum TextAlign { StartTextAlign, EndTextAlign, LeftTextAlign, CenterTextAlign, RightTextAlign };
-
-enum TextDrawingMode {
- TextModeFill = 1 << 0,
- TextModeStroke = 1 << 1,
-};
-typedef unsigned TextDrawingModeFlags;
-
-enum MaskType { AlphaMaskType, LuminanceMaskType };
-
-String compositeOperatorName(CompositeOperator, BlendMode);
-bool parseCompositeAndBlendOperator(const String&, CompositeOperator&, BlendMode&);
-
-String lineCapName(LineCap);
-bool parseLineCap(const String&, LineCap&);
-
-String lineJoinName(LineJoin);
-bool parseLineJoin(const String&, LineJoin&);
-
-String textAlignName(TextAlign);
-bool parseTextAlign(const String&, TextAlign&);
-
-String textBaselineName(TextBaseline);
-bool parseTextBaseline(const String&, TextBaseline&);
-
-} // namespace WebCore
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsTypes3D.h b/chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsTypes3D.h
deleted file mode 100644
index d55f10fe7cc..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/GraphicsTypes3D.h
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef GraphicsTypes3D_h
-#define GraphicsTypes3D_h
-
-#include "wtf/Forward.h"
-#include <stdint.h>
-
-// GC3D types match the corresponding GL types as defined in OpenGL ES 2.0
-// header file gl2.h from khronos.org.
-typedef unsigned int GC3Denum;
-typedef unsigned char GC3Dboolean;
-typedef unsigned int GC3Dbitfield;
-typedef signed char GC3Dbyte;
-typedef unsigned char GC3Dubyte;
-typedef short GC3Dshort;
-typedef unsigned short GC3Dushort;
-typedef int GC3Dint;
-typedef int GC3Dsizei;
-typedef unsigned int GC3Duint;
-typedef float GC3Dfloat;
-typedef unsigned short GC3Dhalffloat;
-typedef float GC3Dclampf;
-typedef intptr_t GC3Dintptr;
-typedef intptr_t GC3Dsizeiptr;
-typedef char GC3Dchar;
-
-typedef GC3Duint Platform3DObject;
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/Image.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/Image.cpp
deleted file mode 100644
index 36a219c0f9a..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/Image.cpp
+++ /dev/null
@@ -1,241 +0,0 @@
-/*
- * Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
- * Copyright (C) 2004, 2005, 2006 Apple Computer, Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/Image.h"
-
-#include "core/platform/Length.h"
-#include "core/platform/MIMETypeRegistry.h"
-#include "core/platform/SharedBuffer.h"
-#include "core/platform/chromium/TraceEvent.h"
-#include "core/platform/graphics/BitmapImage.h"
-#include "core/platform/graphics/FloatPoint.h"
-#include "core/platform/graphics/FloatRect.h"
-#include "core/platform/graphics/FloatSize.h"
-#include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/graphics/GraphicsContextStateSaver.h"
-#include "core/platform/graphics/GraphicsTypes.h"
-#include "core/platform/graphics/IntRect.h"
-#include "public/platform/Platform.h"
-#include "public/platform/WebData.h"
-#include "wtf/MainThread.h"
-#include "wtf/StdLibExtras.h"
-
-#include <math.h>
-
-namespace WebCore {
-
-Image::Image(ImageObserver* observer)
- : m_imageObserver(observer)
-{
-}
-
-Image::~Image()
-{
-}
-
-Image* Image::nullImage()
-{
- ASSERT(isMainThread());
- DEFINE_STATIC_LOCAL(RefPtr<Image>, nullImage, (BitmapImage::create()));;
- return nullImage.get();
-}
-
-PassRefPtr<Image> Image::loadPlatformResource(const char *name)
-{
- const WebKit::WebData& resource = WebKit::Platform::current()->loadResource(name);
- if (resource.isEmpty())
- return Image::nullImage();
-
- RefPtr<Image> image = BitmapImage::create();
- image->setData(resource, true);
- return image.release();
-}
-
-bool Image::supportsType(const String& type)
-{
- return MIMETypeRegistry::isSupportedImageResourceMIMEType(type);
-}
-
-bool Image::setData(PassRefPtr<SharedBuffer> data, bool allDataReceived)
-{
- m_encodedImageData = data;
- if (!m_encodedImageData.get())
- return true;
-
- int length = m_encodedImageData->size();
- if (!length)
- return true;
-
- return dataChanged(allDataReceived);
-}
-
-void Image::fillWithSolidColor(GraphicsContext* ctxt, const FloatRect& dstRect, const Color& color, CompositeOperator op)
-{
- if (!color.alpha())
- return;
-
- CompositeOperator previousOperator = ctxt->compositeOperation();
- ctxt->setCompositeOperation(!color.hasAlpha() && op == CompositeSourceOver ? CompositeCopy : op);
- ctxt->fillRect(dstRect, color);
- ctxt->setCompositeOperation(previousOperator);
-}
-
-FloatRect Image::adjustForNegativeSize(const FloatRect& rect)
-{
- FloatRect norm = rect;
- if (norm.width() < 0) {
- norm.setX(norm.x() + norm.width());
- norm.setWidth(-norm.width());
- }
- if (norm.height() < 0) {
- norm.setY(norm.y() + norm.height());
- norm.setHeight(-norm.height());
- }
- return norm;
-}
-
-void Image::draw(GraphicsContext* ctx, const FloatRect& dstRect, const FloatRect& srcRect, CompositeOperator op, BlendMode blendMode, RespectImageOrientationEnum)
-{
- draw(ctx, dstRect, srcRect, op, blendMode);
-}
-
-void Image::drawTiled(GraphicsContext* ctxt, const FloatRect& destRect, const FloatPoint& srcPoint, const FloatSize& scaledTileSize, CompositeOperator op, BlendMode blendMode)
-{
- if (mayFillWithSolidColor()) {
- fillWithSolidColor(ctxt, destRect, solidColor(), op);
- return;
- }
-
- // See <https://webkit.org/b/59043>.
- ASSERT(!isBitmapImage() || notSolidColor());
-
- FloatSize intrinsicTileSize = size();
- if (hasRelativeWidth())
- intrinsicTileSize.setWidth(scaledTileSize.width());
- if (hasRelativeHeight())
- intrinsicTileSize.setHeight(scaledTileSize.height());
-
- FloatSize scale(scaledTileSize.width() / intrinsicTileSize.width(),
- scaledTileSize.height() / intrinsicTileSize.height());
-
- FloatRect oneTileRect;
- oneTileRect.setX(destRect.x() + fmodf(fmodf(-srcPoint.x(), scaledTileSize.width()) - scaledTileSize.width(), scaledTileSize.width()));
- oneTileRect.setY(destRect.y() + fmodf(fmodf(-srcPoint.y(), scaledTileSize.height()) - scaledTileSize.height(), scaledTileSize.height()));
- oneTileRect.setSize(scaledTileSize);
-
- // Check and see if a single draw of the image can cover the entire area we are supposed to tile.
- if (oneTileRect.contains(destRect)) {
- FloatRect visibleSrcRect;
- visibleSrcRect.setX((destRect.x() - oneTileRect.x()) / scale.width());
- visibleSrcRect.setY((destRect.y() - oneTileRect.y()) / scale.height());
- visibleSrcRect.setWidth(destRect.width() / scale.width());
- visibleSrcRect.setHeight(destRect.height() / scale.height());
- draw(ctxt, destRect, visibleSrcRect, op, blendMode);
- return;
- }
-
- FloatRect tileRect(FloatPoint(), intrinsicTileSize);
- drawPattern(ctxt, tileRect, scale, oneTileRect.location(), op, destRect, blendMode);
-
- startAnimation();
-}
-
-// FIXME: Merge with the other drawTiled eventually, since we need a combination of both for some things.
-void Image::drawTiled(GraphicsContext* ctxt, const FloatRect& dstRect, const FloatRect& srcRect,
- const FloatSize& providedTileScaleFactor, TileRule hRule, TileRule vRule, CompositeOperator op)
-{
- if (mayFillWithSolidColor()) {
- fillWithSolidColor(ctxt, dstRect, solidColor(), op);
- return;
- }
-
- // FIXME: We do not support 'space' yet. For now just map it to 'repeat'.
- if (hRule == SpaceTile)
- hRule = RepeatTile;
- if (vRule == SpaceTile)
- vRule = RepeatTile;
-
- // FIXME: if this code is used for background-repeat: round (in addition to
- // border-image-repeat), then add logic to deal with the background-size: auto
- // special case. The aspect ratio should be maintained in this case.
- FloatSize tileScaleFactor = providedTileScaleFactor;
- bool useLowInterpolationQuality = false;
- if (hRule == RoundTile) {
- float hRepetitions = std::max(1.0f, roundf(dstRect.width() / (tileScaleFactor.width() * srcRect.width())));
- tileScaleFactor.setWidth(dstRect.width() / (srcRect.width() * hRepetitions));
- }
- if (vRule == RoundTile) {
- float vRepetitions = std::max(1.0f, roundf(dstRect.height() / (tileScaleFactor.height() * srcRect.height())));
- tileScaleFactor.setHeight(dstRect.height() / (srcRect.height() * vRepetitions));
- }
- if (hRule == RoundTile || vRule == RoundTile) {
- // High interpolation quality rounds the scaled tile to an integer size (see Image::drawPattern).
- // To avoid causing a visual problem, linear interpolation must be used instead.
- // FIXME: Allow using high-quality interpolation in this case, too.
- useLowInterpolationQuality = true;
- }
-
- // We want to construct the phase such that the pattern is centered (when stretch is not
- // set for a particular rule).
- float hPhase = tileScaleFactor.width() * srcRect.x();
- float vPhase = tileScaleFactor.height() * srcRect.y();
- float scaledTileWidth = tileScaleFactor.width() * srcRect.width();
- float scaledTileHeight = tileScaleFactor.height() * srcRect.height();
- if (hRule == Image::RepeatTile)
- hPhase -= (dstRect.width() - scaledTileWidth) / 2;
- if (vRule == Image::RepeatTile)
- vPhase -= (dstRect.height() - scaledTileHeight) / 2;
- FloatPoint patternPhase(dstRect.x() - hPhase, dstRect.y() - vPhase);
-
- if (useLowInterpolationQuality) {
- InterpolationQuality previousInterpolationQuality = ctxt->imageInterpolationQuality();
- ctxt->setImageInterpolationQuality(InterpolationLow);
- drawPattern(ctxt, srcRect, tileScaleFactor, patternPhase, op, dstRect);
- ctxt->setImageInterpolationQuality(previousInterpolationQuality);
- } else {
- drawPattern(ctxt, srcRect, tileScaleFactor, patternPhase, op, dstRect);
- }
-
- startAnimation();
-}
-
-void Image::drawPattern(GraphicsContext* context, const FloatRect& floatSrcRect, const FloatSize& scale,
- const FloatPoint& phase, CompositeOperator compositeOp, const FloatRect& destRect, BlendMode blendMode)
-{
- TRACE_EVENT0("skia", "Image::drawPattern");
- if (RefPtr<NativeImageSkia> bitmap = nativeImageForCurrentFrame())
- bitmap->drawPattern(context, adjustForNegativeSize(floatSrcRect), scale, phase, compositeOp, destRect, blendMode);
-}
-
-void Image::computeIntrinsicDimensions(Length& intrinsicWidth, Length& intrinsicHeight, FloatSize& intrinsicRatio)
-{
- intrinsicRatio = size();
- intrinsicWidth = Length(intrinsicRatio.width(), Fixed);
- intrinsicHeight = Length(intrinsicRatio.height(), Fixed);
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/Image.h b/chromium/third_party/WebKit/Source/core/platform/graphics/Image.h
deleted file mode 100644
index 222866e933b..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/Image.h
+++ /dev/null
@@ -1,144 +0,0 @@
-/*
- * Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
- * Copyright (C) 2004, 2005, 2006 Apple Computer, Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef Image_h
-#define Image_h
-
-#include "core/platform/graphics/Color.h"
-#include "core/platform/graphics/GraphicsTypes.h"
-#include "core/platform/graphics/ImageOrientation.h"
-#include "core/platform/graphics/IntRect.h"
-#include "core/platform/graphics/skia/NativeImageSkia.h"
-#include "third_party/skia/include/core/SkXfermode.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/RefPtr.h"
-#include "wtf/RetainPtr.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class FloatPoint;
-class FloatRect;
-class FloatSize;
-class GraphicsContext;
-class SharedBuffer;
-struct Length;
-
-// This class gets notified when an image creates or destroys decoded frames and when it advances animation frames.
-class ImageObserver;
-
-class Image : public RefCounted<Image> {
- friend class GeneratedImage;
- friend class CrossfadeGeneratedImage;
- friend class GeneratorGeneratedImage;
- friend class GraphicsContext;
-
-public:
- virtual ~Image();
-
- static PassRefPtr<Image> loadPlatformResource(const char* name);
- static bool supportsType(const String&);
-
- virtual bool isSVGImage() const { return false; }
- virtual bool isBitmapImage() const { return false; }
- virtual bool currentFrameKnownToBeOpaque() = 0;
-
- // Derived classes should override this if they can assure that the current
- // image frame contains only resources from its own security origin.
- virtual bool currentFrameHasSingleSecurityOrigin() const { return false; }
-
- static Image* nullImage();
- bool isNull() const { return size().isEmpty(); }
-
- virtual void setContainerSize(const IntSize&) { }
- virtual bool usesContainerSize() const { return false; }
- virtual bool hasRelativeWidth() const { return false; }
- virtual bool hasRelativeHeight() const { return false; }
- virtual void computeIntrinsicDimensions(Length& intrinsicWidth, Length& intrinsicHeight, FloatSize& intrinsicRatio);
-
- virtual IntSize size() const = 0;
- IntRect rect() const { return IntRect(IntPoint(), size()); }
- int width() const { return size().width(); }
- int height() const { return size().height(); }
- virtual bool getHotSpot(IntPoint&) const { return false; }
-
- bool setData(PassRefPtr<SharedBuffer> data, bool allDataReceived);
- virtual bool dataChanged(bool /*allDataReceived*/) { return false; }
-
- virtual String filenameExtension() const { return String(); } // null string if unknown
-
- virtual void destroyDecodedData(bool destroyAll) = 0;
- virtual unsigned decodedSize() const = 0;
-
- SharedBuffer* data() { return m_encodedImageData.get(); }
-
- // Animation begins whenever someone draws the image, so startAnimation() is not normally called.
- // It will automatically pause once all observers no longer want to render the image anywhere.
- virtual void startAnimation(bool /*catchUpIfNecessary*/ = true) { }
- virtual void stopAnimation() {}
- virtual void resetAnimation() {}
-
- // Typically the ImageResource that owns us.
- ImageObserver* imageObserver() const { return m_imageObserver; }
- void setImageObserver(ImageObserver* observer) { m_imageObserver = observer; }
-
- enum TileRule { StretchTile, RoundTile, SpaceTile, RepeatTile };
-
- virtual PassRefPtr<NativeImageSkia> nativeImageForCurrentFrame() { return 0; }
-
- virtual void drawPattern(GraphicsContext*, const FloatRect&,
- const FloatSize&, const FloatPoint& phase, CompositeOperator,
- const FloatRect&, BlendMode = BlendModeNormal);
-
-#if !ASSERT_DISABLED
- virtual bool notSolidColor() { return true; }
-#endif
-
-protected:
- Image(ImageObserver* = 0);
-
- static void fillWithSolidColor(GraphicsContext*, const FloatRect& dstRect, const Color&, CompositeOperator);
- static FloatRect adjustForNegativeSize(const FloatRect&); // A helper method for translating negative width and height values.
-
- virtual void draw(GraphicsContext*, const FloatRect& dstRect, const FloatRect& srcRect, CompositeOperator, BlendMode) = 0;
- virtual void draw(GraphicsContext*, const FloatRect& dstRect, const FloatRect& srcRect, CompositeOperator, BlendMode, RespectImageOrientationEnum);
- void drawTiled(GraphicsContext*, const FloatRect& dstRect, const FloatPoint& srcPoint, const FloatSize& tileSize,
- CompositeOperator, BlendMode);
- void drawTiled(GraphicsContext*, const FloatRect& dstRect, const FloatRect& srcRect, const FloatSize& tileScaleFactor, TileRule hRule, TileRule vRule, CompositeOperator);
-
- // Supporting tiled drawing
- virtual bool mayFillWithSolidColor() { return false; }
- virtual Color solidColor() const { return Color(); }
-
-private:
- RefPtr<SharedBuffer> m_encodedImageData;
- ImageObserver* m_imageObserver;
-};
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/ImageBuffer.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/ImageBuffer.cpp
deleted file mode 100644
index 8d40ea91abd..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/ImageBuffer.cpp
+++ /dev/null
@@ -1,501 +0,0 @@
-/*
- * Copyright (c) 2008, Google Inc. All rights reserved.
- * Copyright (C) 2009 Dirk Schulze <krit@webkit.org>
- * Copyright (C) 2010 Torch Mobile (Beijing) Co. Ltd. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/ImageBuffer.h"
-
-#include "core/html/ImageData.h"
-#include "core/platform/MIMETypeRegistry.h"
-#include "core/platform/graphics/BitmapImage.h"
-#include "core/platform/graphics/Extensions3D.h"
-#include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/graphics/GraphicsContext3D.h"
-#include "core/platform/graphics/IntRect.h"
-#include "core/platform/graphics/chromium/Canvas2DLayerBridge.h"
-#include "core/platform/graphics/gpu/SharedGraphicsContext3D.h"
-#include "core/platform/graphics/skia/NativeImageSkia.h"
-#include "core/platform/graphics/skia/SkiaUtils.h"
-#include "core/platform/image-encoders/skia/JPEGImageEncoder.h"
-#include "core/platform/image-encoders/skia/PNGImageEncoder.h"
-#include "core/platform/image-encoders/skia/WEBPImageEncoder.h"
-#include "public/platform/Platform.h"
-#include "skia/ext/platform_canvas.h"
-#include "third_party/skia/include/core/SkBitmapDevice.h"
-#include "third_party/skia/include/core/SkColorFilter.h"
-#include "third_party/skia/include/core/SkColorPriv.h"
-#include "third_party/skia/include/core/SkSurface.h"
-#include "third_party/skia/include/effects/SkTableColorFilter.h"
-#include "third_party/skia/include/gpu/GrContext.h"
-#include "third_party/skia/include/gpu/SkGpuDevice.h"
-#include "wtf/MathExtras.h"
-#include "wtf/text/Base64.h"
-#include "wtf/text/WTFString.h"
-
-using namespace std;
-
-namespace WebCore {
-
-static PassRefPtr<SkCanvas> createAcceleratedCanvas(const IntSize& size, Canvas2DLayerBridgePtr* outLayerBridge, OpacityMode opacityMode)
-{
- RefPtr<GraphicsContext3D> context3D = SharedGraphicsContext3D::get();
- if (!context3D)
- return 0;
- Canvas2DLayerBridge::OpacityMode bridgeOpacityMode = opacityMode == Opaque ? Canvas2DLayerBridge::Opaque : Canvas2DLayerBridge::NonOpaque;
- *outLayerBridge = Canvas2DLayerBridge::create(context3D.release(), size, bridgeOpacityMode);
- // If canvas buffer allocation failed, debug build will have asserted
- // For release builds, we must verify whether the device has a render target
- return (*outLayerBridge) ? (*outLayerBridge)->getCanvas() : 0;
-}
-
-static PassRefPtr<SkCanvas> createNonPlatformCanvas(const IntSize& size)
-{
- SkAutoTUnref<SkBaseDevice> device(new SkBitmapDevice(SkBitmap::kARGB_8888_Config, size.width(), size.height()));
- SkPixelRef* pixelRef = device->accessBitmap(false).pixelRef();
- return adoptRef(pixelRef ? new SkCanvas(device) : 0);
-}
-
-PassOwnPtr<ImageBuffer> ImageBuffer::createCompatibleBuffer(const IntSize& size, float resolutionScale, const GraphicsContext* context, bool hasAlpha)
-{
- bool success = false;
- OwnPtr<ImageBuffer> buf = adoptPtr(new ImageBuffer(size, resolutionScale, context, hasAlpha, success));
- if (!success)
- return nullptr;
- return buf.release();
-}
-
-ImageBuffer::ImageBuffer(const IntSize& size, float resolutionScale, const GraphicsContext* compatibleContext, bool hasAlpha, bool& success)
- : m_size(size)
- , m_logicalSize(size)
- , m_resolutionScale(resolutionScale)
-{
- if (!compatibleContext) {
- success = false;
- return;
- }
-
- SkAutoTUnref<SkBaseDevice> device(compatibleContext->createCompatibleDevice(size, hasAlpha));
- if (!device.get()) {
- success = false;
- return;
- }
-
- SkPixelRef* pixelRef = device->accessBitmap(false).pixelRef();
- if (!pixelRef) {
- success = false;
- return;
- }
-
- m_canvas = adoptRef(new SkCanvas(device));
- m_context = adoptPtr(new GraphicsContext(m_canvas.get()));
- m_context->setCertainlyOpaque(!hasAlpha);
- m_context->scale(FloatSize(m_resolutionScale, m_resolutionScale));
-
- success = true;
-}
-
-ImageBuffer::ImageBuffer(const IntSize& size, float resolutionScale, RenderingMode renderingMode, OpacityMode opacityMode, bool& success)
- : m_size(size)
- , m_logicalSize(size)
- , m_resolutionScale(resolutionScale)
-{
- if (renderingMode == Accelerated) {
- m_canvas = createAcceleratedCanvas(size, &m_layerBridge, opacityMode);
- if (!m_canvas)
- renderingMode = UnacceleratedNonPlatformBuffer;
- }
-
- if (renderingMode == UnacceleratedNonPlatformBuffer)
- m_canvas = createNonPlatformCanvas(size);
-
- if (!m_canvas)
- m_canvas = adoptRef(skia::TryCreateBitmapCanvas(size.width(), size.height(), false));
-
- if (!m_canvas) {
- success = false;
- return;
- }
-
- m_context = adoptPtr(new GraphicsContext(m_canvas.get()));
- m_context->setCertainlyOpaque(opacityMode == Opaque);
- m_context->setAccelerated(renderingMode == Accelerated);
- m_context->scale(FloatSize(m_resolutionScale, m_resolutionScale));
-
- // Clear the background transparent or opaque, as required. It would be nice if this wasn't
- // required, but the canvas is currently filled with the magic transparency
- // color. Can we have another way to manage this?
- if (opacityMode == Opaque)
- m_canvas->drawARGB(255, 0, 0, 0, SkXfermode::kSrc_Mode);
- else
- m_canvas->drawARGB(0, 0, 0, 0, SkXfermode::kClear_Mode);
-
- success = true;
-}
-
-ImageBuffer::~ImageBuffer()
-{
-}
-
-GraphicsContext* ImageBuffer::context() const
-{
- if (m_layerBridge) {
- // We're using context acquisition as a signal that someone is about to render into our buffer and we need
- // to be ready. This isn't logically const-correct, hence the cast.
- const_cast<Canvas2DLayerBridge*>(m_layerBridge.get())->contextAcquired();
- }
- return m_context.get();
-}
-
-
-bool ImageBuffer::isValid() const
-{
- if (m_layerBridge)
- return const_cast<Canvas2DLayerBridge*>(m_layerBridge.get())->isValid();
- return true;
-}
-
-static SkBitmap deepSkBitmapCopy(const SkBitmap& bitmap)
-{
- SkBitmap tmp;
- if (!bitmap.deepCopyTo(&tmp, bitmap.config()))
- bitmap.copyTo(&tmp, bitmap.config());
-
- return tmp;
-}
-
-PassRefPtr<Image> ImageBuffer::copyImage(BackingStoreCopy copyBehavior, ScaleBehavior) const
-{
- if (!isValid())
- return BitmapImage::create(NativeImageSkia::create());
-
- const SkBitmap& bitmap = *context()->bitmap();
- // FIXME: Start honoring ScaleBehavior to scale 2x buffers down to 1x.
- return BitmapImage::create(NativeImageSkia::create(copyBehavior == CopyBackingStore ? deepSkBitmapCopy(bitmap) : bitmap, m_resolutionScale));
-}
-
-BackingStoreCopy ImageBuffer::fastCopyImageMode()
-{
- return DontCopyBackingStore;
-}
-
-WebKit::WebLayer* ImageBuffer::platformLayer() const
-{
- return m_layerBridge ? m_layerBridge->layer() : 0;
-}
-
-bool ImageBuffer::copyToPlatformTexture(GraphicsContext3D& context, Platform3DObject texture, GC3Denum internalFormat, GC3Denum destType, GC3Dint level, bool premultiplyAlpha, bool flipY)
-{
- if (!m_layerBridge || !platformLayer() || !isValid())
- return false;
-
- Platform3DObject sourceTexture = m_layerBridge->backBufferTexture();
-
- if (!context.makeContextCurrent())
- return false;
-
- Extensions3D* extensions = context.extensions();
- if (!extensions->supports("GL_CHROMIUM_copy_texture") || !extensions->supports("GL_CHROMIUM_flipy")
- || !extensions->canUseCopyTextureCHROMIUM(internalFormat, destType, level))
- return false;
-
- // The canvas is stored in a premultiplied format, so unpremultiply if necessary.
- context.pixelStorei(Extensions3D::UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM, !premultiplyAlpha);
-
- // The canvas is stored in an inverted position, so the flip semantics are reversed.
- context.pixelStorei(Extensions3D::UNPACK_FLIP_Y_CHROMIUM, !flipY);
-
- extensions->copyTextureCHROMIUM(GraphicsContext3D::TEXTURE_2D, sourceTexture, texture, level, internalFormat, destType);
-
- context.pixelStorei(Extensions3D::UNPACK_FLIP_Y_CHROMIUM, false);
- context.pixelStorei(Extensions3D::UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM, false);
- context.flush();
- return true;
-}
-
-static bool drawNeedsCopy(GraphicsContext* src, GraphicsContext* dst)
-{
- return (src == dst);
-}
-
-void ImageBuffer::draw(GraphicsContext* context, const FloatRect& destRect, const FloatRect& srcRect,
- CompositeOperator op, BlendMode blendMode, bool useLowQualityScale)
-{
- if (!isValid())
- return;
-
- const SkBitmap& bitmap = *m_context->bitmap();
- RefPtr<Image> image = BitmapImage::create(NativeImageSkia::create(drawNeedsCopy(m_context.get(), context) ? deepSkBitmapCopy(bitmap) : bitmap));
- context->drawImage(image.get(), destRect, srcRect, op, blendMode, DoNotRespectImageOrientation, useLowQualityScale);
-}
-
-void ImageBuffer::drawPattern(GraphicsContext* context, const FloatRect& srcRect, const FloatSize& scale,
- const FloatPoint& phase, CompositeOperator op, const FloatRect& destRect, BlendMode blendMode)
-{
- if (!isValid())
- return;
-
- const SkBitmap& bitmap = *m_context->bitmap();
- RefPtr<Image> image = BitmapImage::create(NativeImageSkia::create(drawNeedsCopy(m_context.get(), context) ? deepSkBitmapCopy(bitmap) : bitmap));
- image->drawPattern(context, srcRect, scale, phase, op, destRect, blendMode);
-}
-
-static const Vector<uint8_t>& getLinearRgbLUT()
-{
- DEFINE_STATIC_LOCAL(Vector<uint8_t>, linearRgbLUT, ());
- if (linearRgbLUT.isEmpty()) {
- linearRgbLUT.reserveCapacity(256);
- for (unsigned i = 0; i < 256; i++) {
- float color = i / 255.0f;
- color = (color <= 0.04045f ? color / 12.92f : pow((color + 0.055f) / 1.055f, 2.4f));
- color = std::max(0.0f, color);
- color = std::min(1.0f, color);
- linearRgbLUT.append(static_cast<uint8_t>(round(color * 255)));
- }
- }
- return linearRgbLUT;
-}
-
-static const Vector<uint8_t>& getDeviceRgbLUT()
-{
- DEFINE_STATIC_LOCAL(Vector<uint8_t>, deviceRgbLUT, ());
- if (deviceRgbLUT.isEmpty()) {
- deviceRgbLUT.reserveCapacity(256);
- for (unsigned i = 0; i < 256; i++) {
- float color = i / 255.0f;
- color = (powf(color, 1.0f / 2.4f) * 1.055f) - 0.055f;
- color = std::max(0.0f, color);
- color = std::min(1.0f, color);
- deviceRgbLUT.append(static_cast<uint8_t>(round(color * 255)));
- }
- }
- return deviceRgbLUT;
-}
-
-void ImageBuffer::transformColorSpace(ColorSpace srcColorSpace, ColorSpace dstColorSpace)
-{
- if (srcColorSpace == dstColorSpace)
- return;
-
- // only sRGB <-> linearRGB are supported at the moment
- if ((srcColorSpace != ColorSpaceLinearRGB && srcColorSpace != ColorSpaceDeviceRGB)
- || (dstColorSpace != ColorSpaceLinearRGB && dstColorSpace != ColorSpaceDeviceRGB))
- return;
-
- // FIXME: Disable color space conversions on accelerated canvases (for now).
- if (context()->isAccelerated() || !isValid())
- return;
-
- const SkBitmap& bitmap = *context()->bitmap();
- if (bitmap.isNull())
- return;
-
- const Vector<uint8_t>& lookUpTable = dstColorSpace == ColorSpaceLinearRGB ?
- getLinearRgbLUT() : getDeviceRgbLUT();
-
- ASSERT(bitmap.config() == SkBitmap::kARGB_8888_Config);
- SkAutoLockPixels bitmapLock(bitmap);
- for (int y = 0; y < m_size.height(); ++y) {
- uint32_t* srcRow = bitmap.getAddr32(0, y);
- for (int x = 0; x < m_size.width(); ++x) {
- SkColor color = SkPMColorToColor(srcRow[x]);
- srcRow[x] = SkPreMultiplyARGB(
- SkColorGetA(color),
- lookUpTable[SkColorGetR(color)],
- lookUpTable[SkColorGetG(color)],
- lookUpTable[SkColorGetB(color)]);
- }
- }
-}
-
-PassRefPtr<SkColorFilter> ImageBuffer::createColorSpaceFilter(ColorSpace srcColorSpace,
- ColorSpace dstColorSpace)
-{
- if ((srcColorSpace == dstColorSpace)
- || (srcColorSpace != ColorSpaceLinearRGB && srcColorSpace != ColorSpaceDeviceRGB)
- || (dstColorSpace != ColorSpaceLinearRGB && dstColorSpace != ColorSpaceDeviceRGB))
- return 0;
-
- const uint8_t* lut = 0;
- if (dstColorSpace == ColorSpaceLinearRGB)
- lut = &getLinearRgbLUT()[0];
- else if (dstColorSpace == ColorSpaceDeviceRGB)
- lut = &getDeviceRgbLUT()[0];
- else
- return 0;
-
- return adoptRef(SkTableColorFilter::CreateARGB(0, lut, lut, lut));
-}
-
-template <Multiply multiplied>
-PassRefPtr<Uint8ClampedArray> getImageData(const IntRect& rect, GraphicsContext* context, const IntSize& size)
-{
- float area = 4.0f * rect.width() * rect.height();
- if (area > static_cast<float>(std::numeric_limits<int>::max()))
- return 0;
-
- RefPtr<Uint8ClampedArray> result = Uint8ClampedArray::createUninitialized(rect.width() * rect.height() * 4);
-
- unsigned char* data = result->data();
-
- if (rect.x() < 0
- || rect.y() < 0
- || rect.maxX() > size.width()
- || rect.maxY() > size.height())
- result->zeroFill();
-
- unsigned destBytesPerRow = 4 * rect.width();
- SkBitmap destBitmap;
- destBitmap.setConfig(SkBitmap::kARGB_8888_Config, rect.width(), rect.height(), destBytesPerRow);
- destBitmap.setPixels(data);
-
- SkCanvas::Config8888 config8888;
- if (multiplied == Premultiplied)
- config8888 = SkCanvas::kRGBA_Premul_Config8888;
- else
- config8888 = SkCanvas::kRGBA_Unpremul_Config8888;
-
- context->readPixels(&destBitmap, rect.x(), rect.y(), config8888);
- return result.release();
-}
-
-PassRefPtr<Uint8ClampedArray> ImageBuffer::getUnmultipliedImageData(const IntRect& rect, CoordinateSystem) const
-{
- if (!isValid())
- return Uint8ClampedArray::create(rect.width() * rect.height() * 4);
- return getImageData<Unmultiplied>(rect, context(), m_size);
-}
-
-PassRefPtr<Uint8ClampedArray> ImageBuffer::getPremultipliedImageData(const IntRect& rect, CoordinateSystem) const
-{
- if (!isValid())
- return Uint8ClampedArray::create(rect.width() * rect.height() * 4);
- return getImageData<Premultiplied>(rect, context(), m_size);
-}
-
-void ImageBuffer::putByteArray(Multiply multiplied, Uint8ClampedArray* source, const IntSize& sourceSize, const IntRect& sourceRect, const IntPoint& destPoint, CoordinateSystem)
-{
- if (!isValid())
- return;
-
- ASSERT(sourceRect.width() > 0);
- ASSERT(sourceRect.height() > 0);
-
- int originX = sourceRect.x();
- int destX = destPoint.x() + sourceRect.x();
- ASSERT(destX >= 0);
- ASSERT(destX < m_size.width());
- ASSERT(originX >= 0);
- ASSERT(originX < sourceRect.maxX());
-
- int endX = destPoint.x() + sourceRect.maxX();
- ASSERT(endX <= m_size.width());
-
- int numColumns = endX - destX;
-
- int originY = sourceRect.y();
- int destY = destPoint.y() + sourceRect.y();
- ASSERT(destY >= 0);
- ASSERT(destY < m_size.height());
- ASSERT(originY >= 0);
- ASSERT(originY < sourceRect.maxY());
-
- int endY = destPoint.y() + sourceRect.maxY();
- ASSERT(endY <= m_size.height());
- int numRows = endY - destY;
-
- unsigned srcBytesPerRow = 4 * sourceSize.width();
- SkBitmap srcBitmap;
- srcBitmap.setConfig(SkBitmap::kARGB_8888_Config, numColumns, numRows, srcBytesPerRow);
- srcBitmap.setPixels(source->data() + originY * srcBytesPerRow + originX * 4);
-
- SkCanvas::Config8888 config8888;
- if (multiplied == Premultiplied)
- config8888 = SkCanvas::kRGBA_Premul_Config8888;
- else
- config8888 = SkCanvas::kRGBA_Unpremul_Config8888;
-
- context()->writePixels(srcBitmap, destX, destY, config8888);
-}
-
-template <typename T>
-static bool encodeImage(T& source, const String& mimeType, const double* quality, Vector<char>* output)
-{
- Vector<unsigned char>* encodedImage = reinterpret_cast<Vector<unsigned char>*>(output);
-
- if (mimeType == "image/jpeg") {
- int compressionQuality = JPEGImageEncoder::DefaultCompressionQuality;
- if (quality && *quality >= 0.0 && *quality <= 1.0)
- compressionQuality = static_cast<int>(*quality * 100 + 0.5);
- if (!JPEGImageEncoder::encode(source, compressionQuality, encodedImage))
- return false;
- } else if (mimeType == "image/webp") {
- int compressionQuality = WEBPImageEncoder::DefaultCompressionQuality;
- if (quality && *quality >= 0.0 && *quality <= 1.0)
- compressionQuality = static_cast<int>(*quality * 100 + 0.5);
- if (!WEBPImageEncoder::encode(source, compressionQuality, encodedImage))
- return false;
- } else {
- if (!PNGImageEncoder::encode(source, encodedImage))
- return false;
- ASSERT(mimeType == "image/png");
- }
-
- return true;
-}
-
-String ImageBuffer::toDataURL(const String& mimeType, const double* quality, CoordinateSystem) const
-{
- ASSERT(MIMETypeRegistry::isSupportedImageMIMETypeForEncoding(mimeType));
-
- Vector<char> encodedImage;
- if (!isValid() || !encodeImage(*context()->bitmap(), mimeType, quality, &encodedImage))
- return "data:,";
- Vector<char> base64Data;
- base64Encode(encodedImage, base64Data);
-
- return "data:" + mimeType + ";base64," + base64Data;
-}
-
-String ImageDataToDataURL(const ImageData& imageData, const String& mimeType, const double* quality)
-{
- ASSERT(MIMETypeRegistry::isSupportedImageMIMETypeForEncoding(mimeType));
-
- Vector<char> encodedImage;
- if (!encodeImage(imageData, mimeType, quality, &encodedImage))
- return "data:,";
-
- Vector<char> base64Data;
- base64Encode(encodedImage, base64Data);
-
- return "data:" + mimeType + ";base64," + base64Data;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/ImageBuffer.h b/chromium/third_party/WebKit/Source/core/platform/graphics/ImageBuffer.h
deleted file mode 100644
index 5c2d77112b7..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/ImageBuffer.h
+++ /dev/null
@@ -1,159 +0,0 @@
-/*
- * Copyright (C) 2006 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2007, 2008, 2009 Apple Inc. All rights reserved.
- * Copyright (C) 2010 Torch Mobile (Beijing) Co. Ltd. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ImageBuffer_h
-#define ImageBuffer_h
-
-#include "core/platform/graphics/ColorSpace.h"
-#include "core/platform/graphics/FloatRect.h"
-#include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/graphics/GraphicsTypes.h"
-#include "core/platform/graphics/GraphicsTypes3D.h"
-#include "core/platform/graphics/IntSize.h"
-#include "core/platform/graphics/chromium/Canvas2DLayerBridge.h"
-#include "core/platform/graphics/transforms/AffineTransform.h"
-#include "wtf/Forward.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/Uint8ClampedArray.h"
-#include "wtf/Vector.h"
-
-class SkCanvas;
-
-namespace WebKit { class WebLayer; }
-
-namespace WebCore {
-
-class Image;
-class ImageData;
-class IntPoint;
-class IntRect;
-class GraphicsContext3D;
-
-enum Multiply {
- Premultiplied,
- Unmultiplied
-};
-
-enum RenderingMode {
- Unaccelerated,
- UnacceleratedNonPlatformBuffer, // Use plain memory allocation rather than platform API to allocate backing store.
- Accelerated
-};
-
-enum BackingStoreCopy {
- CopyBackingStore, // Guarantee subsequent draws don't affect the copy.
- DontCopyBackingStore // Subsequent draws may affect the copy.
-};
-
-enum ScaleBehavior {
- Scaled,
- Unscaled
-};
-
-enum OpacityMode {
- NonOpaque,
- Opaque,
-};
-
-class ImageBuffer {
- WTF_MAKE_NONCOPYABLE(ImageBuffer); WTF_MAKE_FAST_ALLOCATED;
-public:
- // Will return a null pointer on allocation failure.
- static PassOwnPtr<ImageBuffer> create(const IntSize& size, float resolutionScale = 1, RenderingMode renderingMode = Unaccelerated, OpacityMode opacityMode = NonOpaque)
- {
- bool success = false;
- OwnPtr<ImageBuffer> buf = adoptPtr(new ImageBuffer(size, resolutionScale, renderingMode, opacityMode, success));
- if (!success)
- return nullptr;
- return buf.release();
- }
-
- static PassOwnPtr<ImageBuffer> createCompatibleBuffer(const IntSize&, float resolutionScale, const GraphicsContext*, bool hasAlpha);
-
- ~ImageBuffer();
-
- // The actual resolution of the backing store
- const IntSize& internalSize() const { return m_size; }
- const IntSize& logicalSize() const { return m_logicalSize; }
-
- GraphicsContext* context() const;
-
- PassRefPtr<Image> copyImage(BackingStoreCopy = CopyBackingStore, ScaleBehavior = Scaled) const;
- // Give hints on the faster copyImage Mode, return DontCopyBackingStore if it supports the DontCopyBackingStore behavior
- // or return CopyBackingStore if it doesn't.
- static BackingStoreCopy fastCopyImageMode();
-
- enum CoordinateSystem { LogicalCoordinateSystem, BackingStoreCoordinateSystem };
-
- PassRefPtr<Uint8ClampedArray> getUnmultipliedImageData(const IntRect&, CoordinateSystem = LogicalCoordinateSystem) const;
- PassRefPtr<Uint8ClampedArray> getPremultipliedImageData(const IntRect&, CoordinateSystem = LogicalCoordinateSystem) const;
-
- void putByteArray(Multiply multiplied, Uint8ClampedArray*, const IntSize& sourceSize, const IntRect& sourceRect, const IntPoint& destPoint, CoordinateSystem = LogicalCoordinateSystem);
-
- String toDataURL(const String& mimeType, const double* quality = 0, CoordinateSystem = LogicalCoordinateSystem) const;
- AffineTransform baseTransform() const { return AffineTransform(); }
- void transformColorSpace(ColorSpace srcColorSpace, ColorSpace dstColorSpace);
- WebKit::WebLayer* platformLayer() const;
-
- // FIXME: current implementations of this method have the restriction that they only work
- // with textures that are RGB or RGBA format, UNSIGNED_BYTE type and level 0, as specified in
- // Extensions3D::canUseCopyTextureCHROMIUM().
- bool copyToPlatformTexture(GraphicsContext3D&, Platform3DObject, GC3Denum, GC3Denum, GC3Dint, bool, bool);
-
-private:
- bool isValid() const;
-
- void draw(GraphicsContext*, const FloatRect&, const FloatRect& = FloatRect(0, 0, -1, -1), CompositeOperator = CompositeSourceOver, BlendMode = BlendModeNormal, bool useLowQualityScale = false);
- void drawPattern(GraphicsContext*, const FloatRect&, const FloatSize&, const FloatPoint&, CompositeOperator, const FloatRect&, BlendMode);
- static PassRefPtr<SkColorFilter> createColorSpaceFilter(ColorSpace srcColorSpace, ColorSpace dstColorSpace);
-
- friend class GraphicsContext;
- friend class GeneratedImage;
- friend class CrossfadeGeneratedImage;
- friend class GeneratorGeneratedImage;
- friend class SkiaImageFilterBuilder;
-
- IntSize m_size;
- IntSize m_logicalSize;
- float m_resolutionScale;
- RefPtr<SkCanvas> m_canvas;
- OwnPtr<GraphicsContext> m_context;
- Canvas2DLayerBridgePtr m_layerBridge;
-
- // This constructor will place its success into the given out-variable
- // so that create() knows when it should return failure.
- ImageBuffer(const IntSize&, float resolutionScale, RenderingMode, OpacityMode, bool& success);
- ImageBuffer(const IntSize&, float resolutionScale, const GraphicsContext*, bool hasAlpha, bool& success);
-};
-
-String ImageDataToDataURL(const ImageData&, const String& mimeType, const double* quality);
-
-} // namespace WebCore
-
-#endif // ImageBuffer_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/ImageObserver.h b/chromium/third_party/WebKit/Source/core/platform/graphics/ImageObserver.h
deleted file mode 100644
index 5db6a9edcd8..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/ImageObserver.h
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Copyright (C) 2004, 2005, 2006 Apple Computer, Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ImageObserver_h
-#define ImageObserver_h
-
-namespace WebCore {
-
-class Image;
-class IntRect;
-
-// Interface for notification about changes to an image, including decoding,
-// drawing, and animating.
-class ImageObserver {
-protected:
- virtual ~ImageObserver() {}
-public:
- virtual void decodedSizeChanged(const Image*, int delta) = 0;
- virtual void didDraw(const Image*) = 0;
-
- virtual bool shouldPauseAnimation(const Image*) = 0;
- virtual void animationAdvanced(const Image*) = 0;
-
- virtual void changedInRect(const Image*, const IntRect&) = 0;
-};
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/ImageOrientation.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/ImageOrientation.cpp
deleted file mode 100644
index ecd998da407..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/ImageOrientation.cpp
+++ /dev/null
@@ -1,62 +0,0 @@
-
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/ImageOrientation.h"
-
-#include "core/platform/graphics/transforms/AffineTransform.h"
-
-namespace WebCore {
-
-AffineTransform ImageOrientation::transformFromDefault(const FloatSize& drawnSize) const
-{
- float w = drawnSize.width();
- float h = drawnSize.height();
-
- switch (m_orientation) {
- case OriginTopLeft:
- return AffineTransform();
- case OriginTopRight:
- return AffineTransform(-1, 0, 0, 1, w, 0);
- case OriginBottomRight:
- return AffineTransform(-1, 0, 0, -1, w, h);
- case OriginBottomLeft:
- return AffineTransform( 1, 0, 0, -1, 0, h);
- case OriginLeftTop:
- return AffineTransform( 0, 1, 1, 0, 0, 0);
- case OriginRightTop:
- return AffineTransform( 0, 1, -1, 0, w, 0);
- case OriginRightBottom:
- return AffineTransform( 0, -1, -1, 0, w, h);
- case OriginLeftBottom:
- return AffineTransform( 0, -1, 1, 0, 0, h);
- }
-
- ASSERT_NOT_REACHED();
- return AffineTransform();
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/ImageOrientation.h b/chromium/third_party/WebKit/Source/core/platform/graphics/ImageOrientation.h
deleted file mode 100644
index b184dc2f70a..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/ImageOrientation.h
+++ /dev/null
@@ -1,92 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ImageOrientation_h
-#define ImageOrientation_h
-
-namespace WebCore {
-
-class AffineTransform;
-class FloatSize;
-
-// This enum intentionally matches the orientation values from the EXIF spec.
-// See JEITA CP-3451, page 18. http://www.exif.org/Exif2-2.PDF
-enum ImageOrientationEnum {
- // "TopLeft" means that the 0 row starts at the Top, the 0 column starts at the Left.
- OriginTopLeft = 1, // default
- OriginTopRight = 2, // mirror along y-axis
- OriginBottomRight = 3, // 180 degree rotation
- OriginBottomLeft = 4, // mirror along the x-axis
- OriginLeftTop = 5, // mirror along x-axis + 270 degree CW rotation
- OriginRightTop = 6, // 90 degree CW rotation
- OriginRightBottom = 7, // mirror along x-axis + 90 degree CW rotation
- OriginLeftBottom = 8, // 270 degree CW rotation
- // All other values are "reserved" as of EXIF 2.2
- DefaultImageOrientation = OriginTopLeft,
-};
-
-enum RespectImageOrientationEnum {
- DoNotRespectImageOrientation = 0,
- RespectImageOrientation = 1
-};
-
-class ImageOrientation {
-public:
- ImageOrientation(ImageOrientationEnum orientation = DefaultImageOrientation)
- : m_orientation(orientation)
- {
- }
-
- bool usesWidthAsHeight() const
- {
- // Values 5 through 8 all flip the width/height.
- return m_orientation >= OriginLeftTop;
- }
-
- // ImageOrientationEnum currently matches EXIF values, however code outside
- // this function should never assume that.
- static ImageOrientation fromEXIFValue(int exifValue)
- {
- // Values direct from images may be invalid, in which case we use the default.
- if (exifValue < OriginTopLeft || exifValue > OriginLeftBottom)
- return DefaultImageOrientation;
- return static_cast<ImageOrientationEnum>(exifValue);
- }
-
- // This transform can be used for drawing an image according to the orientation.
- // It should be used in a right-handed coordinate system.
- AffineTransform transformFromDefault(const FloatSize& drawnSize) const;
-
- inline bool operator==(const ImageOrientation& other) const { return other.m_orientation == m_orientation; }
- inline bool operator!=(const ImageOrientation& other) const { return !(*this == other); }
-
-private:
- // FIXME: This only needs to be one byte.
- ImageOrientationEnum m_orientation;
-};
-
-} // namespace WebCore
-
-#endif // ImageOrientation_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/ImageSource.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/ImageSource.cpp
deleted file mode 100644
index 66b79b07499..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/ImageSource.cpp
+++ /dev/null
@@ -1,175 +0,0 @@
-/*
- * Copyright (C) 2006 Apple Computer, Inc. All rights reserved.
- * Copyright (C) 2007 Alp Toker <alp.toker@collabora.co.uk>
- * Copyright (C) 2008, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/ImageSource.h"
-
-#include "core/platform/graphics/ImageOrientation.h"
-#include "core/platform/graphics/chromium/DeferredImageDecoder.h"
-#include "core/platform/image-decoders/ImageDecoder.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/PassRefPtr.h"
-
-namespace WebCore {
-
-ImageSource::ImageSource(ImageSource::AlphaOption alphaOption, ImageSource::GammaAndColorProfileOption gammaAndColorProfileOption)
- : m_alphaOption(alphaOption)
- , m_gammaAndColorProfileOption(gammaAndColorProfileOption)
-{
-}
-
-ImageSource::~ImageSource()
-{
-}
-
-size_t ImageSource::clearCacheExceptFrame(size_t clearExceptFrame)
-{
- return m_decoder ? m_decoder->clearCacheExceptFrame(clearExceptFrame) : 0;
-}
-
-bool ImageSource::initialized() const
-{
- return m_decoder;
-}
-
-void ImageSource::setData(SharedBuffer* data, bool allDataReceived)
-{
- // Make the decoder by sniffing the bytes.
- // This method will examine the data and instantiate an instance of the appropriate decoder plugin.
- // If insufficient bytes are available to determine the image type, no decoder plugin will be
- // made.
- if (!m_decoder)
- m_decoder = DeferredImageDecoder::create(*data, m_alphaOption, m_gammaAndColorProfileOption);
-
- if (m_decoder)
- m_decoder->setData(data, allDataReceived);
-}
-
-String ImageSource::filenameExtension() const
-{
- return m_decoder ? m_decoder->filenameExtension() : String();
-}
-
-bool ImageSource::isSizeAvailable()
-{
- return m_decoder && m_decoder->isSizeAvailable();
-}
-
-IntSize ImageSource::size(RespectImageOrientationEnum shouldRespectOrientation) const
-{
- return frameSizeAtIndex(0, shouldRespectOrientation);
-}
-
-IntSize ImageSource::frameSizeAtIndex(size_t index, RespectImageOrientationEnum shouldRespectOrientation) const
-{
- if (!m_decoder)
- return IntSize();
-
- IntSize size = m_decoder->frameSizeAtIndex(index);
- if ((shouldRespectOrientation == RespectImageOrientation) && m_decoder->orientation().usesWidthAsHeight())
- return IntSize(size.height(), size.width());
-
- return size;
-}
-
-bool ImageSource::getHotSpot(IntPoint& hotSpot) const
-{
- return m_decoder ? m_decoder->hotSpot(hotSpot) : false;
-}
-
-size_t ImageSource::bytesDecodedToDetermineProperties() const
-{
- return 0;
-}
-
-int ImageSource::repetitionCount()
-{
- return m_decoder ? m_decoder->repetitionCount() : cAnimationNone;
-}
-
-size_t ImageSource::frameCount() const
-{
- return m_decoder ? m_decoder->frameCount() : 0;
-}
-
-PassRefPtr<NativeImageSkia> ImageSource::createFrameAtIndex(size_t index)
-{
- if (!m_decoder)
- return 0;
-
- ImageFrame* buffer = m_decoder->frameBufferAtIndex(index);
- if (!buffer || buffer->status() == ImageFrame::FrameEmpty)
- return 0;
-
- // Zero-height images can cause problems for some ports. If we have an
- // empty image dimension, just bail.
- if (size().isEmpty())
- return 0;
-
- // Return the buffer contents as a native image. For some ports, the data
- // is already in a native container, and this just increments its refcount.
- return buffer->asNewNativeImage();
-}
-
-float ImageSource::frameDurationAtIndex(size_t index) const
-{
- if (!m_decoder)
- return 0;
-
- // Many annoying ads specify a 0 duration to make an image flash as quickly as possible.
- // We follow Firefox's behavior and use a duration of 100 ms for any frames that specify
- // a duration of <= 10 ms. See <rdar://problem/7689300> and <http://webkit.org/b/36082>
- // for more information.
- const float duration = m_decoder->frameDurationAtIndex(index) / 1000.0f;
- if (duration < 0.011f)
- return 0.100f;
- return duration;
-}
-
-ImageOrientation ImageSource::orientationAtIndex(size_t) const
-{
- return m_decoder ? m_decoder->orientation() : DefaultImageOrientation;
-}
-
-bool ImageSource::frameHasAlphaAtIndex(size_t index) const
-{
- return !m_decoder || m_decoder->frameHasAlphaAtIndex(index);
-}
-
-bool ImageSource::frameIsCompleteAtIndex(size_t index) const
-{
- return m_decoder && m_decoder->frameIsCompleteAtIndex(index);
-}
-
-unsigned ImageSource::frameBytesAtIndex(size_t index) const
-{
- if (!m_decoder)
- return 0;
- return m_decoder->frameBytesAtIndex(index);
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/ImageSource.h b/chromium/third_party/WebKit/Source/core/platform/graphics/ImageSource.h
deleted file mode 100644
index 2a78d71e70c..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/ImageSource.h
+++ /dev/null
@@ -1,135 +0,0 @@
-/*
- * Copyright (C) 2004, 2005, 2006 Apple Computer, Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ImageSource_h
-#define ImageSource_h
-
-#include "core/platform/graphics/ImageOrientation.h"
-#include "wtf/Forward.h"
-#include "wtf/Noncopyable.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-class DeferredImageDecoder;
-class ImageOrientation;
-class IntPoint;
-class IntSize;
-class NativeImageSkia;
-class SharedBuffer;
-
-// Right now GIFs are the only recognized image format that supports animation.
-// The animation system and the constants below are designed with this in mind.
-// GIFs have an optional 16-bit unsigned loop count that describes how an
-// animated GIF should be cycled. If the loop count is absent, the animation
-// cycles once; if it is 0, the animation cycles infinitely; otherwise the
-// animation plays n + 1 cycles (where n is the specified loop count). If the
-// GIF decoder defaults to cAnimationLoopOnce in the absence of any loop count
-// and translates an explicit "0" loop count to cAnimationLoopInfinite, then we
-// get a couple of nice side effects:
-// * By making cAnimationLoopOnce be 0, we allow the animation cycling code in
-// BitmapImage.cpp to avoid special-casing it, and simply treat all
-// non-negative loop counts identically.
-// * By making the other two constants negative, we avoid conflicts with any
-// real loop count values.
-const int cAnimationLoopOnce = 0;
-const int cAnimationLoopInfinite = -1;
-const int cAnimationNone = -2;
-
-class ImageSource {
- WTF_MAKE_NONCOPYABLE(ImageSource);
-public:
- enum AlphaOption {
- AlphaPremultiplied,
- AlphaNotPremultiplied
- };
-
- enum GammaAndColorProfileOption {
- GammaAndColorProfileApplied,
- GammaAndColorProfileIgnored
- };
-
- ImageSource(AlphaOption alphaOption = AlphaPremultiplied, GammaAndColorProfileOption gammaAndColorProfileOption = GammaAndColorProfileApplied);
- ~ImageSource();
-
- // Tells the ImageSource that the Image no longer cares about decoded frame
- // data except for the specified frame. Callers may pass WTF::kNotFound to
- // clear all frames.
- //
- // In response, the ImageSource should delete cached decoded data for other
- // frames where possible to keep memory use low. The expectation is that in
- // the future, the caller may call createFrameAtIndex() with an index larger
- // than the one passed to this function, and the implementation may then
- // make use of the preserved frame data here in decoding that frame.
- // By contrast, callers who call this function and then later ask for an
- // earlier frame may require more work to be done, e.g. redecoding the image
- // from the beginning.
- //
- // Implementations may elect to preserve more frames than the one requested
- // here if doing so is likely to save CPU time in the future, but will pay
- // an increased memory cost to do so.
- //
- // Returns the number of bytes of frame data actually cleared.
- size_t clearCacheExceptFrame(size_t);
-
- bool initialized() const;
-
- void setData(SharedBuffer* data, bool allDataReceived);
- String filenameExtension() const;
-
- bool isSizeAvailable();
- IntSize size(RespectImageOrientationEnum = DoNotRespectImageOrientation) const;
- IntSize frameSizeAtIndex(size_t, RespectImageOrientationEnum = DoNotRespectImageOrientation) const;
-
- bool getHotSpot(IntPoint&) const;
-
- size_t bytesDecodedToDetermineProperties() const;
-
- int repetitionCount();
-
- size_t frameCount() const;
-
- PassRefPtr<NativeImageSkia> createFrameAtIndex(size_t);
-
- float frameDurationAtIndex(size_t) const;
- bool frameHasAlphaAtIndex(size_t) const; // Whether or not the frame actually used any alpha.
- bool frameIsCompleteAtIndex(size_t) const; // Whether or not the frame is fully received.
- ImageOrientation orientationAtIndex(size_t) const; // EXIF image orientation
-
- // Return the number of bytes in the decoded frame. If the frame is not yet
- // decoded then return 0.
- unsigned frameBytesAtIndex(size_t) const;
-
-private:
- OwnPtr<DeferredImageDecoder> m_decoder;
-
- AlphaOption m_alphaOption;
- GammaAndColorProfileOption m_gammaAndColorProfileOption;
-};
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/InbandTextTrackPrivate.h b/chromium/third_party/WebKit/Source/core/platform/graphics/InbandTextTrackPrivate.h
deleted file mode 100644
index 9492d8acd21..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/InbandTextTrackPrivate.h
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * Copyright (C) 2012 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef InbandTextTrackPrivate_h
-#define InbandTextTrackPrivate_h
-
-#include "wtf/Forward.h"
-#include "wtf/Noncopyable.h"
-#include "wtf/RefCounted.h"
-#include "wtf/text/AtomicString.h"
-
-namespace WebCore {
-
-class InbandTextTrackPrivateClient;
-
-class InbandTextTrackPrivate : public RefCounted<InbandTextTrackPrivate> {
- WTF_MAKE_NONCOPYABLE(InbandTextTrackPrivate); WTF_MAKE_FAST_ALLOCATED;
-public:
- static PassRefPtr<InbandTextTrackPrivate> create()
- {
- return adoptRef(new InbandTextTrackPrivate());
- }
- virtual ~InbandTextTrackPrivate() { }
-
- void setClient(InbandTextTrackPrivateClient* client) { m_client = client; }
- InbandTextTrackPrivateClient* client() { return m_client; }
-
- enum Mode { Disabled, Hidden, Showing };
- virtual void setMode(Mode mode) { m_mode = mode; };
- virtual InbandTextTrackPrivate::Mode mode() const { return m_mode; }
-
- enum Kind { Subtitles, Captions, Descriptions, Chapters, Metadata, None };
- virtual Kind kind() const { return Subtitles; }
- virtual bool isClosedCaptions() const { return false; }
- virtual bool containsOnlyForcedSubtitles() const { return false; }
- virtual bool isMainProgramContent() const { return true; }
- virtual bool isEasyToRead() const { return false; }
-
- virtual AtomicString label() const { return emptyAtom; }
- virtual AtomicString language() const { return emptyAtom; }
- virtual bool isDefault() const { return false; }
-
- virtual int textTrackIndex() const { return 0; }
-
-protected:
- InbandTextTrackPrivate()
- : m_client(0)
- , m_mode(Disabled)
- {
- }
-
-private:
- InbandTextTrackPrivateClient* m_client;
- Mode m_mode;
-};
-
-} // namespace WebCore
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/InbandTextTrackPrivateClient.h b/chromium/third_party/WebKit/Source/core/platform/graphics/InbandTextTrackPrivateClient.h
deleted file mode 100644
index 4473c8aba8d..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/InbandTextTrackPrivateClient.h
+++ /dev/null
@@ -1,124 +0,0 @@
-/*
- * Copyright (C) 2012, 2013 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef InbandTextTrackPrivateClient_h
-#define InbandTextTrackPrivateClient_h
-
-#include "core/platform/graphics/Color.h"
-#include "wtf/Noncopyable.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class InbandTextTrackPrivate;
-
-class GenericCueData {
- WTF_MAKE_NONCOPYABLE(GenericCueData); WTF_MAKE_FAST_ALLOCATED;
-public:
- GenericCueData()
- : m_startTime(0)
- , m_endTime(0)
- , m_line(-1)
- , m_position(-1)
- , m_size(-1)
- , m_align(None)
- , m_baseFontSize(0)
- , m_relativeFontSize(0)
- {
- }
- virtual ~GenericCueData() { }
-
- double startTime() const { return m_startTime; }
- void setStartTime(double startTime) { m_startTime = startTime; }
-
- double endTime() const { return m_endTime; }
- void setEndTime(double endTime) { m_endTime = endTime; }
-
- String id() const { return m_id; }
- void setId(String id) { m_id = id; }
-
- String content() const { return m_content; }
- void setContent(String content) { m_content = content; }
-
- double line() const { return m_line; }
- void setLine(double line) { m_line = line; }
-
- double position() const { return m_position; }
- void setPosition(double position) { m_position = position; }
-
- double size() const { return m_size; }
- void setSize(double size) { m_size = size; }
-
- enum Alignment {
- None,
- Start,
- Middle,
- End
- };
- Alignment align() const { return m_align; }
- void setAlign(Alignment align) { m_align = align; }
-
- String fontName() const { return m_fontName; }
- void setFontName(String fontName) { m_fontName = fontName; }
-
- double baseFontSize() const { return m_baseFontSize; }
- void setBaseFontSize(double baseFontSize) { m_baseFontSize = baseFontSize; }
-
- double relativeFontSize() const { return m_relativeFontSize; }
- void setRelativeFontSize(double relativeFontSize) { m_relativeFontSize = relativeFontSize; }
-
- Color foregroundColor() const { return m_foregroundColor; }
- void setForegroundColor(RGBA32 color) { m_foregroundColor.setRGB(color); }
-
- Color backgroundColor() const { return m_backgroundColor; }
- void setBackgroundColor(RGBA32 color) { m_backgroundColor.setRGB(color); }
-
-private:
- double m_startTime;
- double m_endTime;
- String m_id;
- String m_content;
- double m_line;
- double m_position;
- double m_size;
- Alignment m_align;
- String m_fontName;
- double m_baseFontSize;
- double m_relativeFontSize;
- Color m_foregroundColor;
- Color m_backgroundColor;
-};
-
-class InbandTextTrackPrivateClient {
-public:
- virtual ~InbandTextTrackPrivateClient() { }
-
- virtual void addWebVTTCue(InbandTextTrackPrivate*, double /*start*/, double /*end*/, const String& /*id*/, const String& /*content*/, const String& /*settings*/) = 0;
- virtual void addGenericCue(InbandTextTrackPrivate*, GenericCueData*) = 0;
-};
-
-} // namespace WebCore
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/IntPoint.h b/chromium/third_party/WebKit/Source/core/platform/graphics/IntPoint.h
deleted file mode 100644
index 80746c4bfb8..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/IntPoint.h
+++ /dev/null
@@ -1,164 +0,0 @@
-/*
- * Copyright (C) 2004, 2005, 2006 Apple Computer, Inc. All rights reserved.
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef IntPoint_h
-#define IntPoint_h
-
-#include "core/platform/graphics/IntSize.h"
-#include "wtf/MathExtras.h"
-
-#if OS(MACOSX)
-typedef struct CGPoint CGPoint;
-#ifdef NSGEOMETRY_TYPES_SAME_AS_CGGEOMETRY_TYPES
-typedef struct CGPoint NSPoint;
-#else
-typedef struct _NSPoint NSPoint;
-#endif
-#endif
-
-namespace WebCore {
-
-class IntPoint {
-public:
- IntPoint() : m_x(0), m_y(0) { }
- IntPoint(int x, int y) : m_x(x), m_y(y) { }
- explicit IntPoint(const IntSize& size) : m_x(size.width()), m_y(size.height()) { }
-
- static IntPoint zero() { return IntPoint(); }
-
- int x() const { return m_x; }
- int y() const { return m_y; }
-
- void setX(int x) { m_x = x; }
- void setY(int y) { m_y = y; }
-
- void move(const IntSize& s) { move(s.width(), s.height()); }
- void moveBy(const IntPoint& offset) { move(offset.x(), offset.y()); }
- void move(int dx, int dy) { m_x += dx; m_y += dy; }
- void scale(float sx, float sy)
- {
- m_x = lroundf(static_cast<float>(m_x * sx));
- m_y = lroundf(static_cast<float>(m_y * sy));
- }
-
- IntPoint expandedTo(const IntPoint& other) const
- {
- return IntPoint(m_x > other.m_x ? m_x : other.m_x,
- m_y > other.m_y ? m_y : other.m_y);
- }
-
- IntPoint shrunkTo(const IntPoint& other) const
- {
- return IntPoint(m_x < other.m_x ? m_x : other.m_x,
- m_y < other.m_y ? m_y : other.m_y);
- }
-
- int distanceSquaredToPoint(const IntPoint&) const;
-
- void clampNegativeToZero()
- {
- *this = expandedTo(zero());
- }
-
- IntPoint transposedPoint() const
- {
- return IntPoint(m_y, m_x);
- }
-
-#if OS(MACOSX)
- explicit IntPoint(const CGPoint&); // don't do this implicitly since it's lossy
- operator CGPoint() const;
-
-#if !defined(NSGEOMETRY_TYPES_SAME_AS_CGGEOMETRY_TYPES)
- explicit IntPoint(const NSPoint&); // don't do this implicitly since it's lossy
- operator NSPoint() const;
-#endif
-#endif
-
-private:
- int m_x, m_y;
-};
-
-inline IntPoint& operator+=(IntPoint& a, const IntSize& b)
-{
- a.move(b.width(), b.height());
- return a;
-}
-
-inline IntPoint& operator-=(IntPoint& a, const IntSize& b)
-{
- a.move(-b.width(), -b.height());
- return a;
-}
-
-inline IntPoint operator+(const IntPoint& a, const IntSize& b)
-{
- return IntPoint(a.x() + b.width(), a.y() + b.height());
-}
-
-inline IntPoint operator+(const IntPoint& a, const IntPoint& b)
-{
- return IntPoint(a.x() + b.x(), a.y() + b.y());
-}
-
-inline IntSize operator-(const IntPoint& a, const IntPoint& b)
-{
- return IntSize(a.x() - b.x(), a.y() - b.y());
-}
-
-inline IntPoint operator-(const IntPoint& a, const IntSize& b)
-{
- return IntPoint(a.x() - b.width(), a.y() - b.height());
-}
-
-inline IntPoint operator-(const IntPoint& point)
-{
- return IntPoint(-point.x(), -point.y());
-}
-
-inline bool operator==(const IntPoint& a, const IntPoint& b)
-{
- return a.x() == b.x() && a.y() == b.y();
-}
-
-inline bool operator!=(const IntPoint& a, const IntPoint& b)
-{
- return a.x() != b.x() || a.y() != b.y();
-}
-
-inline IntSize toIntSize(const IntPoint& a)
-{
- return IntSize(a.x(), a.y());
-}
-
-inline int IntPoint::distanceSquaredToPoint(const IntPoint& point) const
-{
- return ((*this) - point).diagonalLengthSquared();
-}
-
-} // namespace WebCore
-
-#endif // IntPoint_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/IntRect.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/IntRect.cpp
deleted file mode 100644
index d8f2ad0fbad..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/IntRect.cpp
+++ /dev/null
@@ -1,177 +0,0 @@
-/*
- * Copyright (C) 2003, 2006, 2009 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/IntRect.h"
-
-#include "core/platform/graphics/FloatRect.h"
-#include "core/platform/graphics/LayoutRect.h"
-#include "third_party/skia/include/core/SkRect.h"
-
-#include <algorithm>
-
-using std::max;
-using std::min;
-
-namespace WebCore {
-
-IntRect::IntRect(const FloatRect& r)
- : m_location(clampToInteger(r.x()), clampToInteger(r.y()))
- , m_size(clampToInteger(r.width()), clampToInteger(r.height()))
-{
-}
-
-IntRect::IntRect(const LayoutRect& r)
- : m_location(r.x(), r.y())
- , m_size(r.width(), r.height())
-{
-}
-
-bool IntRect::intersects(const IntRect& other) const
-{
- // Checking emptiness handles negative widths as well as zero.
- return !isEmpty() && !other.isEmpty()
- && x() < other.maxX() && other.x() < maxX()
- && y() < other.maxY() && other.y() < maxY();
-}
-
-bool IntRect::contains(const IntRect& other) const
-{
- return x() <= other.x() && maxX() >= other.maxX()
- && y() <= other.y() && maxY() >= other.maxY();
-}
-
-void IntRect::intersect(const IntRect& other)
-{
- int l = max(x(), other.x());
- int t = max(y(), other.y());
- int r = min(maxX(), other.maxX());
- int b = min(maxY(), other.maxY());
-
- // Return a clean empty rectangle for non-intersecting cases.
- if (l >= r || t >= b) {
- l = 0;
- t = 0;
- r = 0;
- b = 0;
- }
-
- m_location.setX(l);
- m_location.setY(t);
- m_size.setWidth(r - l);
- m_size.setHeight(b - t);
-}
-
-void IntRect::unite(const IntRect& other)
-{
- // Handle empty special cases first.
- if (other.isEmpty())
- return;
- if (isEmpty()) {
- *this = other;
- return;
- }
-
- int l = min(x(), other.x());
- int t = min(y(), other.y());
- int r = max(maxX(), other.maxX());
- int b = max(maxY(), other.maxY());
-
- m_location.setX(l);
- m_location.setY(t);
- m_size.setWidth(r - l);
- m_size.setHeight(b - t);
-}
-
-void IntRect::uniteIfNonZero(const IntRect& other)
-{
- // Handle empty special cases first.
- if (!other.width() && !other.height())
- return;
- if (!width() && !height()) {
- *this = other;
- return;
- }
-
- int left = min(x(), other.x());
- int top = min(y(), other.y());
- int right = max(maxX(), other.maxX());
- int bottom = max(maxY(), other.maxY());
-
- m_location.setX(left);
- m_location.setY(top);
- m_size.setWidth(right - left);
- m_size.setHeight(bottom - top);
-}
-
-void IntRect::scale(float s)
-{
- m_location.setX((int)(x() * s));
- m_location.setY((int)(y() * s));
- m_size.setWidth((int)(width() * s));
- m_size.setHeight((int)(height() * s));
-}
-
-static inline int distanceToInterval(int pos, int start, int end)
-{
- if (pos < start)
- return start - pos;
- if (pos > end)
- return end - pos;
- return 0;
-}
-
-IntSize IntRect::differenceToPoint(const IntPoint& point) const
-{
- int xdistance = distanceToInterval(point.x(), x(), maxX());
- int ydistance = distanceToInterval(point.y(), y(), maxY());
- return IntSize(xdistance, ydistance);
-}
-
-IntRect::operator SkIRect() const
-{
- SkIRect rect = { x(), y(), maxX(), maxY() };
- return rect;
-}
-
-IntRect::operator SkRect() const
-{
- SkRect rect;
- rect.set(SkIntToScalar(x()), SkIntToScalar(y()), SkIntToScalar(maxX()), SkIntToScalar(maxY()));
- return rect;
-}
-
-IntRect unionRect(const Vector<IntRect>& rects)
-{
- IntRect result;
-
- size_t count = rects.size();
- for (size_t i = 0; i < count; ++i)
- result.unite(rects[i]);
-
- return result;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/IntRect.h b/chromium/third_party/WebKit/Source/core/platform/graphics/IntRect.h
deleted file mode 100644
index a2e3492356f..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/IntRect.h
+++ /dev/null
@@ -1,205 +0,0 @@
-/*
- * Copyright (C) 2003, 2006, 2009 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef IntRect_h
-#define IntRect_h
-
-#include "core/platform/graphics/IntPoint.h"
-#include "wtf/FastAllocBase.h"
-#include "wtf/Vector.h"
-
-#if OS(MACOSX)
-typedef struct CGRect CGRect;
-
-#ifdef NSGEOMETRY_TYPES_SAME_AS_CGGEOMETRY_TYPES
-typedef struct CGRect NSRect;
-#else
-typedef struct _NSRect NSRect;
-#endif
-#endif
-
-struct SkRect;
-struct SkIRect;
-
-namespace WebCore {
-
-class FloatRect;
-class LayoutRect;
-
-class IntRect {
- WTF_MAKE_FAST_ALLOCATED;
-public:
- IntRect() { }
- IntRect(const IntPoint& location, const IntSize& size)
- : m_location(location), m_size(size) { }
- IntRect(int x, int y, int width, int height)
- : m_location(IntPoint(x, y)), m_size(IntSize(width, height)) { }
-
- explicit IntRect(const FloatRect&); // don't do this implicitly since it's lossy
- explicit IntRect(const LayoutRect&); // don't do this implicitly since it's lossy
-
- IntPoint location() const { return m_location; }
- IntSize size() const { return m_size; }
-
- void setLocation(const IntPoint& location) { m_location = location; }
- void setSize(const IntSize& size) { m_size = size; }
-
- int x() const { return m_location.x(); }
- int y() const { return m_location.y(); }
- int maxX() const { return x() + width(); }
- int maxY() const { return y() + height(); }
- int width() const { return m_size.width(); }
- int height() const { return m_size.height(); }
-
- void setX(int x) { m_location.setX(x); }
- void setY(int y) { m_location.setY(y); }
- void setWidth(int width) { m_size.setWidth(width); }
- void setHeight(int height) { m_size.setHeight(height); }
-
- bool isEmpty() const { return m_size.isEmpty(); }
-
- // NOTE: The result is rounded to integer values, and thus may be not the exact
- // center point.
- IntPoint center() const { return IntPoint(x() + width() / 2, y() + height() / 2); }
-
- void move(const IntSize& size) { m_location += size; }
- void moveBy(const IntPoint& offset) { m_location.move(offset.x(), offset.y()); }
- void move(int dx, int dy) { m_location.move(dx, dy); }
-
- void expand(const IntSize& size) { m_size += size; }
- void expand(int dw, int dh) { m_size.expand(dw, dh); }
- void contract(const IntSize& size) { m_size -= size; }
- void contract(int dw, int dh) { m_size.expand(-dw, -dh); }
-
- void shiftXEdgeTo(int edge)
- {
- int delta = edge - x();
- setX(edge);
- setWidth(std::max(0, width() - delta));
- }
- void shiftMaxXEdgeTo(int edge)
- {
- int delta = edge - maxX();
- setWidth(std::max(0, width() + delta));
- }
- void shiftYEdgeTo(int edge)
- {
- int delta = edge - y();
- setY(edge);
- setHeight(std::max(0, height() - delta));
- }
- void shiftMaxYEdgeTo(int edge)
- {
- int delta = edge - maxY();
- setHeight(std::max(0, height() + delta));
- }
-
- IntPoint minXMinYCorner() const { return m_location; } // typically topLeft
- IntPoint maxXMinYCorner() const { return IntPoint(m_location.x() + m_size.width(), m_location.y()); } // typically topRight
- IntPoint minXMaxYCorner() const { return IntPoint(m_location.x(), m_location.y() + m_size.height()); } // typically bottomLeft
- IntPoint maxXMaxYCorner() const { return IntPoint(m_location.x() + m_size.width(), m_location.y() + m_size.height()); } // typically bottomRight
-
- bool intersects(const IntRect&) const;
- bool contains(const IntRect&) const;
-
- // This checks to see if the rect contains x,y in the traditional sense.
- // Equivalent to checking if the rect contains a 1x1 rect below and to the right of (px,py).
- bool contains(int px, int py) const
- { return px >= x() && px < maxX() && py >= y() && py < maxY(); }
- bool contains(const IntPoint& point) const { return contains(point.x(), point.y()); }
-
- void intersect(const IntRect&);
- void unite(const IntRect&);
- void uniteIfNonZero(const IntRect&);
-
- void inflateX(int dx)
- {
- m_location.setX(m_location.x() - dx);
- m_size.setWidth(m_size.width() + dx + dx);
- }
- void inflateY(int dy)
- {
- m_location.setY(m_location.y() - dy);
- m_size.setHeight(m_size.height() + dy + dy);
- }
- void inflate(int d) { inflateX(d); inflateY(d); }
- void scale(float s);
-
- IntSize differenceToPoint(const IntPoint&) const;
- int distanceSquaredToPoint(const IntPoint& p) const { return differenceToPoint(p).diagonalLengthSquared(); }
-
- IntRect transposedRect() const { return IntRect(m_location.transposedPoint(), m_size.transposedSize()); }
-
-#if OS(MACOSX)
- operator CGRect() const;
-#if !defined(NSGEOMETRY_TYPES_SAME_AS_CGGEOMETRY_TYPES)
- operator NSRect() const;
-#endif
-#endif
-
- operator SkRect() const;
- operator SkIRect() const;
-
-private:
- IntPoint m_location;
- IntSize m_size;
-};
-
-inline IntRect intersection(const IntRect& a, const IntRect& b)
-{
- IntRect c = a;
- c.intersect(b);
- return c;
-}
-
-inline IntRect unionRect(const IntRect& a, const IntRect& b)
-{
- IntRect c = a;
- c.unite(b);
- return c;
-}
-
-IntRect unionRect(const Vector<IntRect>&);
-
-inline bool operator==(const IntRect& a, const IntRect& b)
-{
- return a.location() == b.location() && a.size() == b.size();
-}
-
-inline bool operator!=(const IntRect& a, const IntRect& b)
-{
- return a.location() != b.location() || a.size() != b.size();
-}
-
-#if OS(MACOSX)
-IntRect enclosingIntRect(const CGRect&);
-#if !defined(NSGEOMETRY_TYPES_SAME_AS_CGGEOMETRY_TYPES)
-IntRect enclosingIntRect(const NSRect&);
-#endif
-#endif
-
-} // namespace WebCore
-
-#endif // IntRect_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/IntRectExtent.h b/chromium/third_party/WebKit/Source/core/platform/graphics/IntRectExtent.h
deleted file mode 100644
index 197779a967e..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/IntRectExtent.h
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * Copyright (C) 2013 Adobe Systems Incorporated. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above
- * copyright notice, this list of conditions and the following
- * disclaimer.
- * 2. Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following
- * disclaimer in the documentation and/or other materials
- * provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
- * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
- * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
- * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#ifndef IntRectExtent_h
-#define IntRectExtent_h
-
-#include "core/platform/graphics/LayoutRect.h"
-
-namespace WebCore {
-
-class IntRectExtent {
-public:
- IntRectExtent()
- : m_top(0)
- , m_right(0)
- , m_bottom(0)
- , m_left(0)
- {
- }
-
- IntRectExtent(int top, int right, int bottom, int left)
- : m_top(top)
- , m_right(right)
- , m_bottom(bottom)
- , m_left(left)
- {
- }
-
- int top() const { return m_top; }
- void setTop(int top) { m_top = top; }
-
- int right() const { return m_right; }
- void setRight(int right) { m_right = right; }
-
- int bottom() const { return m_bottom; }
- void setBottom(int bottom) { m_bottom = bottom; }
-
- int left() const { return m_left; }
- void setLeft(int left) { m_left = left; }
-
- bool isZero() const { return !left() && !right() && !top() && !bottom(); }
-
- void expandRect(LayoutRect& rect) const
- {
- if (isZero())
- return;
-
- rect.move(-left(), -top());
- rect.expand(left() + right(), top() + bottom());
- }
-
-private:
- int m_top;
- int m_right;
- int m_bottom;
- int m_left;
-};
-
-inline bool operator==(const IntRectExtent& a, const IntRectExtent& b)
-{
- return a.top() == b.top()
- && a.right() == b.right()
- && a.bottom() == b.bottom()
- && a.left() == b.left();
-}
-
-inline bool operator!=(const IntRectExtent& a, const IntRectExtent& b)
-{
- return !(a == b);
-}
-
-inline void operator+=(IntRectExtent& a, const IntRectExtent& b)
-{
- a.setTop(a.top() + b.top());
- a.setRight(a.right() + b.right());
- a.setBottom(a.bottom() + b.bottom());
- a.setLeft(a.left() + b.left());
-}
-
-} // namespace WebCore
-
-
-#endif // IntRectExtent_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/IntSize.h b/chromium/third_party/WebKit/Source/core/platform/graphics/IntSize.h
deleted file mode 100644
index 44d6c728f12..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/IntSize.h
+++ /dev/null
@@ -1,170 +0,0 @@
-/*
- * Copyright (C) 2003, 2004, 2005, 2006 Apple Computer, Inc. All rights reserved.
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef IntSize_h
-#define IntSize_h
-
-#if OS(MACOSX)
-typedef struct CGSize CGSize;
-
-#ifdef NSGEOMETRY_TYPES_SAME_AS_CGGEOMETRY_TYPES
-typedef struct CGSize NSSize;
-#else
-typedef struct _NSSize NSSize;
-#endif
-#endif
-
-namespace WebCore {
-
-class IntSize {
-public:
- IntSize() : m_width(0), m_height(0) { }
- IntSize(int width, int height) : m_width(width), m_height(height) { }
-
- int width() const { return m_width; }
- int height() const { return m_height; }
-
- void setWidth(int width) { m_width = width; }
- void setHeight(int height) { m_height = height; }
-
- bool isEmpty() const { return m_width <= 0 || m_height <= 0; }
- bool isZero() const { return !m_width && !m_height; }
-
- float aspectRatio() const { return static_cast<float>(m_width) / static_cast<float>(m_height); }
-
- void expand(int width, int height)
- {
- m_width += width;
- m_height += height;
- }
-
- void scale(float widthScale, float heightScale)
- {
- m_width = static_cast<int>(static_cast<float>(m_width) * widthScale);
- m_height = static_cast<int>(static_cast<float>(m_height) * heightScale);
- }
-
- void scale(float scale)
- {
- this->scale(scale, scale);
- }
-
- IntSize expandedTo(const IntSize& other) const
- {
- return IntSize(m_width > other.m_width ? m_width : other.m_width,
- m_height > other.m_height ? m_height : other.m_height);
- }
-
- IntSize shrunkTo(const IntSize& other) const
- {
- return IntSize(m_width < other.m_width ? m_width : other.m_width,
- m_height < other.m_height ? m_height : other.m_height);
- }
-
- void clampNegativeToZero()
- {
- *this = expandedTo(IntSize());
- }
-
- void clampToMinimumSize(const IntSize& minimumSize)
- {
- if (m_width < minimumSize.width())
- m_width = minimumSize.width();
- if (m_height < minimumSize.height())
- m_height = minimumSize.height();
- }
-
- int area() const
- {
- return m_width * m_height;
- }
-
- int diagonalLengthSquared() const
- {
- return m_width * m_width + m_height * m_height;
- }
-
- IntSize transposedSize() const
- {
- return IntSize(m_height, m_width);
- }
-
-#if OS(MACOSX)
- explicit IntSize(const CGSize&); // don't do this implicitly since it's lossy
- operator CGSize() const;
-
-#if !defined(NSGEOMETRY_TYPES_SAME_AS_CGGEOMETRY_TYPES)
- explicit IntSize(const NSSize &); // don't do this implicitly since it's lossy
- operator NSSize() const;
-#endif
-#endif
-
-private:
- int m_width, m_height;
-};
-
-inline IntSize& operator+=(IntSize& a, const IntSize& b)
-{
- a.setWidth(a.width() + b.width());
- a.setHeight(a.height() + b.height());
- return a;
-}
-
-inline IntSize& operator-=(IntSize& a, const IntSize& b)
-{
- a.setWidth(a.width() - b.width());
- a.setHeight(a.height() - b.height());
- return a;
-}
-
-inline IntSize operator+(const IntSize& a, const IntSize& b)
-{
- return IntSize(a.width() + b.width(), a.height() + b.height());
-}
-
-inline IntSize operator-(const IntSize& a, const IntSize& b)
-{
- return IntSize(a.width() - b.width(), a.height() - b.height());
-}
-
-inline IntSize operator-(const IntSize& size)
-{
- return IntSize(-size.width(), -size.height());
-}
-
-inline bool operator==(const IntSize& a, const IntSize& b)
-{
- return a.width() == b.width() && a.height() == b.height();
-}
-
-inline bool operator!=(const IntSize& a, const IntSize& b)
-{
- return a.width() != b.width() || a.height() != b.height();
-}
-
-} // namespace WebCore
-
-#endif // IntSize_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/IntSizeHash.h b/chromium/third_party/WebKit/Source/core/platform/graphics/IntSizeHash.h
deleted file mode 100644
index 71f26405d0a..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/IntSizeHash.h
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Copyright (C) 2006, 2008 Apple Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-#ifndef IntSizeHash_h
-#define IntSizeHash_h
-
-#include "core/platform/graphics/IntSize.h"
-#include "wtf/HashMap.h"
-#include "wtf/HashSet.h"
-
-namespace WTF {
-
-template<> struct IntHash<WebCore::IntSize> {
- static unsigned hash(const WebCore::IntSize& key) { return pairIntHash(key.width(), key.height()); }
- static bool equal(const WebCore::IntSize& a, const WebCore::IntSize& b) { return a == b; }
- static const bool safeToCompareToEmptyOrDeleted = true;
-};
-
-template<> struct DefaultHash<WebCore::IntSize> {
- typedef IntHash<WebCore::IntSize> Hash;
-};
-
-template<> struct HashTraits<WebCore::IntSize> : GenericHashTraits<WebCore::IntSize> {
- static const bool emptyValueIsZero = true;
- static const bool needsDestruction = false;
- static void constructDeletedValue(WebCore::IntSize& slot) { new (NotNull, &slot) WebCore::IntSize(-1, -1); }
- static bool isDeletedValue(const WebCore::IntSize& value) { return value.width() == -1 && value.height() == -1; }
-};
-
-} // namespace WTF
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/Latin1TextIterator.h b/chromium/third_party/WebKit/Source/core/platform/graphics/Latin1TextIterator.h
deleted file mode 100644
index 7b9d6c1f724..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/Latin1TextIterator.h
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Copyright (C) 2012 Apple Inc. All rights reserved.
- * Copyright (C) Research In Motion Limited 2011. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#ifndef Latin1TextIterator_h
-#define Latin1TextIterator_h
-
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class Latin1TextIterator {
-public:
- // The passed in LChar pointer starts at 'currentCharacter'. The iterator operates on the range [currentCharacter, lastCharacter].
- // 'endCharacter' denotes the maximum length of the UChar array, which might exceed 'lastCharacter'.
- Latin1TextIterator(const LChar* characters, int currentCharacter, int lastCharacter, int /*endCharacter*/)
- : m_characters(characters)
- , m_currentCharacter(currentCharacter)
- , m_lastCharacter(lastCharacter)
- {
- }
-
- bool consume(UChar32& character, unsigned& clusterLength)
- {
- if (m_currentCharacter >= m_lastCharacter)
- return false;
-
- character = *m_characters;
- clusterLength = 1;
- return true;
- }
-
- void advance(unsigned advanceLength)
- {
- m_characters += advanceLength;
- m_currentCharacter += advanceLength;
- }
-
- int currentCharacter() const { return m_currentCharacter; }
- const LChar* characters() const { return m_characters; }
-
-private:
- const LChar* m_characters;
- int m_currentCharacter;
- int m_lastCharacter;
-};
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/LayoutBoxExtent.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/LayoutBoxExtent.cpp
deleted file mode 100644
index 2c3422b4e8f..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/LayoutBoxExtent.cpp
+++ /dev/null
@@ -1,198 +0,0 @@
-/*
- * Copyright (c) 2012, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/LayoutBoxExtent.h"
-
-#include "wtf/Assertions.h"
-
-namespace WebCore {
-
-LayoutUnit LayoutBoxExtent::logicalTop(WritingMode writingMode) const
-{
- return isHorizontalWritingMode(writingMode) ? m_top : m_left;
-}
-
-LayoutUnit LayoutBoxExtent::logicalBottom(WritingMode writingMode) const
-{
- return isHorizontalWritingMode(writingMode) ? m_bottom : m_right;
-}
-
-LayoutUnit LayoutBoxExtent::logicalLeft(WritingMode writingMode) const
-{
- return isHorizontalWritingMode(writingMode) ? m_left : m_top;
-}
-
-LayoutUnit LayoutBoxExtent::logicalRight(WritingMode writingMode) const
-{
- return isHorizontalWritingMode(writingMode) ? m_right : m_bottom;
-}
-
-LayoutUnit LayoutBoxExtent::before(WritingMode writingMode) const
-{
- switch (writingMode) {
- case TopToBottomWritingMode:
- return m_top;
- case BottomToTopWritingMode:
- return m_bottom;
- case LeftToRightWritingMode:
- return m_left;
- case RightToLeftWritingMode:
- return m_right;
- }
- ASSERT_NOT_REACHED();
- return m_top;
-}
-
-LayoutUnit LayoutBoxExtent::after(WritingMode writingMode) const
-{
- switch (writingMode) {
- case TopToBottomWritingMode:
- return m_bottom;
- case BottomToTopWritingMode:
- return m_top;
- case LeftToRightWritingMode:
- return m_right;
- case RightToLeftWritingMode:
- return m_left;
- }
- ASSERT_NOT_REACHED();
- return m_bottom;
-}
-
-LayoutUnit LayoutBoxExtent::start(WritingMode writingMode, TextDirection direction) const
-{
- if (isHorizontalWritingMode(writingMode))
- return isLeftToRightDirection(direction) ? m_left : m_right;
- return isLeftToRightDirection(direction) ? m_top : m_bottom;
-}
-
-LayoutUnit LayoutBoxExtent::end(WritingMode writingMode, TextDirection direction) const
-{
- if (isHorizontalWritingMode(writingMode))
- return isLeftToRightDirection(direction) ? m_right : m_left;
- return isLeftToRightDirection(direction) ? m_bottom : m_top;
-}
-
-void LayoutBoxExtent::setBefore(WritingMode writingMode, LayoutUnit value)
-{
- switch (writingMode) {
- case TopToBottomWritingMode:
- m_top = value;
- break;
- case BottomToTopWritingMode:
- m_bottom = value;
- break;
- case LeftToRightWritingMode:
- m_left = value;
- break;
- case RightToLeftWritingMode:
- m_right = value;
- break;
- default:
- ASSERT_NOT_REACHED();
- m_top = value;
- }
-}
-
-void LayoutBoxExtent::setAfter(WritingMode writingMode, LayoutUnit value)
-{
- switch (writingMode) {
- case TopToBottomWritingMode:
- m_bottom = value;
- break;
- case BottomToTopWritingMode:
- m_top = value;
- break;
- case LeftToRightWritingMode:
- m_right = value;
- break;
- case RightToLeftWritingMode:
- m_left = value;
- break;
- default:
- ASSERT_NOT_REACHED();
- m_bottom = value;
- }
-}
-
-void LayoutBoxExtent::setStart(WritingMode writingMode, TextDirection direction, LayoutUnit value)
-{
- if (isHorizontalWritingMode(writingMode)) {
- if (isLeftToRightDirection(direction))
- m_left = value;
- else
- m_right = value;
- } else {
- if (isLeftToRightDirection(direction))
- m_top = value;
- else
- m_bottom = value;
- }
-}
-
-void LayoutBoxExtent::setEnd(WritingMode writingMode, TextDirection direction, LayoutUnit value)
-{
- if (isHorizontalWritingMode(writingMode)) {
- if (isLeftToRightDirection(direction))
- m_right = value;
- else
- m_left = value;
- } else {
- if (isLeftToRightDirection(direction))
- m_bottom = value;
- else
- m_top = value;
- }
-}
-
-LayoutUnit& LayoutBoxExtent::mutableLogicalLeft(WritingMode writingMode)
-{
- return isHorizontalWritingMode(writingMode) ? m_left : m_top;
-}
-
-LayoutUnit& LayoutBoxExtent::mutableLogicalRight(WritingMode writingMode)
-{
- return isHorizontalWritingMode(writingMode) ? m_right : m_bottom;
-}
-
-LayoutUnit& LayoutBoxExtent::mutableBefore(WritingMode writingMode)
-{
- return isHorizontalWritingMode(writingMode) ? (isFlippedBlocksWritingMode(writingMode) ? m_bottom : m_top) :
- (isFlippedBlocksWritingMode(writingMode) ? m_right: m_left);
-}
-
-LayoutUnit& LayoutBoxExtent::mutableAfter(WritingMode writingMode)
-{
- return isHorizontalWritingMode(writingMode) ? (isFlippedBlocksWritingMode(writingMode) ? m_top : m_bottom) :
- (isFlippedBlocksWritingMode(writingMode) ? m_left: m_right);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/LayoutBoxExtent.h b/chromium/third_party/WebKit/Source/core/platform/graphics/LayoutBoxExtent.h
deleted file mode 100644
index c35d2d9f3a3..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/LayoutBoxExtent.h
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * Copyright (c) 2012, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef LayoutBoxExtent_h
-#define LayoutBoxExtent_h
-
-#include "core/platform/LayoutUnit.h"
-#include "core/platform/text/TextDirection.h"
-#include "core/platform/text/WritingMode.h"
-
-namespace WebCore {
-
-class LayoutBoxExtent {
-public:
- LayoutBoxExtent() : m_top(0), m_right(0), m_bottom(0), m_left(0) { }
- LayoutBoxExtent(LayoutUnit top, LayoutUnit right, LayoutUnit bottom, LayoutUnit left)
- : m_top(top), m_right(right), m_bottom(bottom), m_left(left) { }
-
- inline LayoutUnit top() const { return m_top; }
- inline LayoutUnit right() const { return m_right; }
- inline LayoutUnit bottom() const { return m_bottom; }
- inline LayoutUnit left() const { return m_left; }
-
- inline void setTop(LayoutUnit value) { m_top = value; }
- inline void setRight(LayoutUnit value) { m_right = value; }
- inline void setBottom(LayoutUnit value) { m_bottom = value; }
- inline void setLeft(LayoutUnit value) { m_left = value; }
-
- LayoutUnit logicalTop(WritingMode) const;
- LayoutUnit logicalBottom(WritingMode) const;
- LayoutUnit logicalLeft(WritingMode) const;
- LayoutUnit logicalRight(WritingMode) const;
-
- LayoutUnit before(WritingMode) const;
- LayoutUnit after(WritingMode) const;
- LayoutUnit start(WritingMode, TextDirection) const;
- LayoutUnit end(WritingMode, TextDirection) const;
-
- void setBefore(WritingMode, LayoutUnit);
- void setAfter(WritingMode, LayoutUnit);
- void setStart(WritingMode, TextDirection, LayoutUnit);
- void setEnd(WritingMode, TextDirection, LayoutUnit);
-
- LayoutUnit& mutableLogicalLeft(WritingMode);
- LayoutUnit& mutableLogicalRight(WritingMode);
-
- LayoutUnit& mutableBefore(WritingMode);
- LayoutUnit& mutableAfter(WritingMode);
-
-private:
- LayoutUnit m_top;
- LayoutUnit m_right;
- LayoutUnit m_bottom;
- LayoutUnit m_left;
-};
-
-} // namespace WebCore
-
-#endif // LayoutBoxExtent_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/LayoutPoint.h b/chromium/third_party/WebKit/Source/core/platform/graphics/LayoutPoint.h
deleted file mode 100644
index e5de27cfe7a..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/LayoutPoint.h
+++ /dev/null
@@ -1,204 +0,0 @@
-/*
- * Copyright (c) 2012, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef LayoutPoint_h
-#define LayoutPoint_h
-
-#include "core/platform/graphics/FloatPoint.h"
-#include "core/platform/graphics/LayoutSize.h"
-#include "wtf/MathExtras.h"
-
-namespace WebCore {
-
-class LayoutPoint {
-public:
- LayoutPoint() : m_x(0), m_y(0) { }
- LayoutPoint(LayoutUnit x, LayoutUnit y) : m_x(x), m_y(y) { }
- LayoutPoint(const IntPoint& point) : m_x(point.x()), m_y(point.y()) { }
- explicit LayoutPoint(const FloatPoint& size) : m_x(size.x()), m_y(size.y()) { }
- explicit LayoutPoint(const LayoutSize& size) : m_x(size.width()), m_y(size.height()) { }
-
- static LayoutPoint zero() { return LayoutPoint(); }
-
- LayoutUnit x() const { return m_x; }
- LayoutUnit y() const { return m_y; }
-
- void setX(LayoutUnit x) { m_x = x; }
- void setY(LayoutUnit y) { m_y = y; }
-
- void move(const LayoutSize& s) { move(s.width(), s.height()); }
- void moveBy(const LayoutPoint& offset) { move(offset.x(), offset.y()); }
- void move(LayoutUnit dx, LayoutUnit dy) { m_x += dx; m_y += dy; }
- void scale(float sx, float sy)
- {
- m_x *= sx;
- m_y *= sy;
- }
-
- LayoutPoint expandedTo(const LayoutPoint& other) const
- {
- return LayoutPoint(std::max(m_x, other.m_x), std::max(m_y, other.m_y));
- }
-
- LayoutPoint shrunkTo(const LayoutPoint& other) const
- {
- return LayoutPoint(std::min(m_x, other.m_x), std::min(m_y, other.m_y));
- }
-
- void clampNegativeToZero()
- {
- *this = expandedTo(zero());
- }
-
- LayoutPoint transposedPoint() const
- {
- return LayoutPoint(m_y, m_x);
- }
-
-private:
- LayoutUnit m_x, m_y;
-};
-
-inline LayoutPoint& operator+=(LayoutPoint& a, const LayoutSize& b)
-{
- a.move(b.width(), b.height());
- return a;
-}
-
-inline LayoutPoint& operator-=(LayoutPoint& a, const LayoutSize& b)
-{
- a.move(-b.width(), -b.height());
- return a;
-}
-
-inline LayoutPoint operator+(const LayoutPoint& a, const LayoutSize& b)
-{
- return LayoutPoint(a.x() + b.width(), a.y() + b.height());
-}
-
-inline LayoutPoint operator+(const LayoutPoint& a, const LayoutPoint& b)
-{
- return LayoutPoint(a.x() + b.x(), a.y() + b.y());
-}
-
-inline LayoutSize operator-(const LayoutPoint& a, const LayoutPoint& b)
-{
- return LayoutSize(a.x() - b.x(), a.y() - b.y());
-}
-
-inline LayoutPoint operator-(const LayoutPoint& a, const LayoutSize& b)
-{
- return LayoutPoint(a.x() - b.width(), a.y() - b.height());
-}
-
-inline LayoutPoint operator-(const LayoutPoint& point)
-{
- return LayoutPoint(-point.x(), -point.y());
-}
-
-inline bool operator==(const LayoutPoint& a, const LayoutPoint& b)
-{
- return a.x() == b.x() && a.y() == b.y();
-}
-
-inline bool operator!=(const LayoutPoint& a, const LayoutPoint& b)
-{
- return a.x() != b.x() || a.y() != b.y();
-}
-
-inline LayoutPoint toPoint(const LayoutSize& size)
-{
- return LayoutPoint(size.width(), size.height());
-}
-
-inline LayoutPoint toLayoutPoint(const LayoutSize& p)
-{
- return LayoutPoint(p.width(), p.height());
-}
-
-inline LayoutSize toSize(const LayoutPoint& a)
-{
- return LayoutSize(a.x(), a.y());
-}
-
-inline IntPoint flooredIntPoint(const LayoutPoint& point)
-{
- return IntPoint(point.x().floor(), point.y().floor());
-}
-
-inline IntPoint roundedIntPoint(const LayoutPoint& point)
-{
- return IntPoint(point.x().round(), point.y().round());
-}
-
-inline IntPoint roundedIntPoint(const LayoutSize& size)
-{
- return IntPoint(size.width().round(), size.height().round());
-}
-
-inline IntPoint ceiledIntPoint(const LayoutPoint& point)
-{
- return IntPoint(point.x().ceil(), point.y().ceil());
-}
-
-inline LayoutPoint flooredLayoutPoint(const FloatPoint& p)
-{
- return LayoutPoint(LayoutUnit::fromFloatFloor(p.x()), LayoutUnit::fromFloatFloor(p.y()));
-}
-
-inline LayoutPoint ceiledLayoutPoint(const FloatPoint& p)
-{
- return LayoutPoint(LayoutUnit::fromFloatCeil(p.x()), LayoutUnit::fromFloatCeil(p.y()));
-}
-
-inline IntSize pixelSnappedIntSize(const LayoutSize& s, const LayoutPoint& p)
-{
- return IntSize(snapSizeToPixel(s.width(), p.x()), snapSizeToPixel(s.height(), p.y()));
-}
-
-inline LayoutPoint roundedLayoutPoint(const FloatPoint& p)
-{
- return LayoutPoint(p);
-}
-
-inline LayoutSize toLayoutSize(const LayoutPoint& p)
-{
- return LayoutSize(p.x(), p.y());
-}
-
-inline LayoutPoint flooredLayoutPoint(const FloatSize& s)
-{
- return flooredLayoutPoint(FloatPoint(s));
-}
-
-
-} // namespace WebCore
-
-#endif // LayoutPoint_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/LayoutRect.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/LayoutRect.cpp
deleted file mode 100644
index a3c0b009c01..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/LayoutRect.cpp
+++ /dev/null
@@ -1,150 +0,0 @@
-/*
- * Copyright (c) 2012, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/LayoutRect.h"
-
-#include <algorithm>
-#include "core/platform/LayoutUnit.h"
-#include "core/platform/graphics/FloatRect.h"
-
-using std::max;
-using std::min;
-
-namespace WebCore {
-
-LayoutRect::LayoutRect(const FloatRect& r)
- : m_location(LayoutPoint(r.location()))
- , m_size(LayoutSize(r.size()))
-{
-}
-
-bool LayoutRect::intersects(const LayoutRect& other) const
-{
- // Checking emptiness handles negative widths as well as zero.
- return !isEmpty() && !other.isEmpty()
- && x() < other.maxX() && other.x() < maxX()
- && y() < other.maxY() && other.y() < maxY();
-}
-
-bool LayoutRect::contains(const LayoutRect& other) const
-{
- return x() <= other.x() && maxX() >= other.maxX()
- && y() <= other.y() && maxY() >= other.maxY();
-}
-
-void LayoutRect::intersect(const LayoutRect& other)
-{
- LayoutPoint newLocation(max(x(), other.x()), max(y(), other.y()));
- LayoutPoint newMaxPoint(min(maxX(), other.maxX()), min(maxY(), other.maxY()));
-
- // Return a clean empty rectangle for non-intersecting cases.
- if (newLocation.x() >= newMaxPoint.x() || newLocation.y() >= newMaxPoint.y()) {
- newLocation = LayoutPoint(0, 0);
- newMaxPoint = LayoutPoint(0, 0);
- }
-
- m_location = newLocation;
- m_size = newMaxPoint - newLocation;
-}
-
-void LayoutRect::unite(const LayoutRect& other)
-{
- // Handle empty special cases first.
- if (other.isEmpty())
- return;
- if (isEmpty()) {
- *this = other;
- return;
- }
-
- LayoutPoint newLocation(min(x(), other.x()), min(y(), other.y()));
- LayoutPoint newMaxPoint(max(maxX(), other.maxX()), max(maxY(), other.maxY()));
-
- m_location = newLocation;
- m_size = newMaxPoint - newLocation;
-}
-
-void LayoutRect::uniteIfNonZero(const LayoutRect& other)
-{
- // Handle empty special cases first.
- if (!other.width() && !other.height())
- return;
- if (!width() && !height()) {
- *this = other;
- return;
- }
-
- LayoutPoint newLocation(min(x(), other.x()), min(y(), other.y()));
- LayoutPoint newMaxPoint(max(maxX(), other.maxX()), max(maxY(), other.maxY()));
-
- m_location = newLocation;
- m_size = newMaxPoint - newLocation;
-}
-
-void LayoutRect::scale(float s)
-{
- m_location.scale(s, s);
- m_size.scale(s);
-}
-
-void LayoutRect::scale(float xAxisScale, float yAxisScale)
-{
- m_location.scale(xAxisScale, yAxisScale);
- m_size.scale(xAxisScale, yAxisScale);
-}
-
-LayoutRect unionRect(const Vector<LayoutRect>& rects)
-{
- LayoutRect result;
-
- size_t count = rects.size();
- for (size_t i = 0; i < count; ++i)
- result.unite(rects[i]);
-
- return result;
-}
-
-IntRect enclosingIntRect(const LayoutRect& rect)
-{
- IntPoint location = flooredIntPoint(rect.minXMinYCorner());
- IntPoint maxPoint = ceiledIntPoint(rect.maxXMaxYCorner());
-
- return IntRect(location, maxPoint - location);
-}
-
-LayoutRect enclosingLayoutRect(const FloatRect& rect)
-{
- LayoutPoint location = flooredLayoutPoint(rect.minXMinYCorner());
- LayoutPoint maxPoint = ceiledLayoutPoint(rect.maxXMaxYCorner());
- return LayoutRect(location, maxPoint - location);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/LayoutRect.h b/chromium/third_party/WebKit/Source/core/platform/graphics/LayoutRect.h
deleted file mode 100644
index dc46a9b3754..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/LayoutRect.h
+++ /dev/null
@@ -1,230 +0,0 @@
-/*
- * Copyright (c) 2012, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef LayoutRect_h
-#define LayoutRect_h
-
-#include "core/platform/graphics/IntRect.h"
-#include "core/platform/graphics/LayoutBoxExtent.h"
-#include "core/platform/graphics/LayoutPoint.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-class FloatRect;
-
-class LayoutRect {
-public:
- LayoutRect() { }
- LayoutRect(const LayoutPoint& location, const LayoutSize& size)
- : m_location(location), m_size(size) { }
- LayoutRect(LayoutUnit x, LayoutUnit y, LayoutUnit width, LayoutUnit height)
- : m_location(LayoutPoint(x, y)), m_size(LayoutSize(width, height)) { }
- LayoutRect(const FloatPoint& location, const FloatSize& size)
- : m_location(location), m_size(size) { }
- LayoutRect(const IntRect& rect) : m_location(rect.location()), m_size(rect.size()) { }
-
- explicit LayoutRect(const FloatRect&); // don't do this implicitly since it's lossy
-
- LayoutPoint location() const { return m_location; }
- LayoutSize size() const { return m_size; }
-
- IntPoint pixelSnappedLocation() const { return roundedIntPoint(m_location); }
- IntSize pixelSnappedSize() const { return IntSize(snapSizeToPixel(m_size.width(), m_location.x()), snapSizeToPixel(m_size.height(), m_location.y())); }
-
- void setLocation(const LayoutPoint& location) { m_location = location; }
- void setSize(const LayoutSize& size) { m_size = size; }
-
- LayoutUnit x() const { return m_location.x(); }
- LayoutUnit y() const { return m_location.y(); }
- LayoutUnit maxX() const { return x() + width(); }
- LayoutUnit maxY() const { return y() + height(); }
- LayoutUnit width() const { return m_size.width(); }
- LayoutUnit height() const { return m_size.height(); }
-
- int pixelSnappedX() const { return x().round(); }
- int pixelSnappedY() const { return y().round(); }
- int pixelSnappedWidth() const { return snapSizeToPixel(width(), x()); }
- int pixelSnappedHeight() const { return snapSizeToPixel(height(), y()); }
- int pixelSnappedMaxX() const { return (m_location.x() + m_size.width()).round(); }
- int pixelSnappedMaxY() const { return (m_location.y() + m_size.height()).round(); }
-
- void setX(LayoutUnit x) { m_location.setX(x); }
- void setY(LayoutUnit y) { m_location.setY(y); }
- void setWidth(LayoutUnit width) { m_size.setWidth(width); }
- void setHeight(LayoutUnit height) { m_size.setHeight(height); }
-
- bool isEmpty() const { return m_size.isEmpty(); }
-
- // NOTE: The result is rounded to integer values, and thus may be not the exact
- // center point.
- LayoutPoint center() const { return LayoutPoint(x() + width() / 2, y() + height() / 2); }
-
- void move(const LayoutSize& size) { m_location += size; }
- void moveBy(const LayoutPoint& offset) { m_location.move(offset.x(), offset.y()); }
- void move(LayoutUnit dx, LayoutUnit dy) { m_location.move(dx, dy); }
-
- void expand(const LayoutSize& size) { m_size += size; }
- void expand(const LayoutBoxExtent& box)
- {
- m_location.move(-box.left(), -box.top());
- m_size.expand(box.left() + box.right(), box.top() + box.bottom());
- }
- void expand(LayoutUnit dw, LayoutUnit dh) { m_size.expand(dw, dh); }
- void contract(const LayoutSize& size) { m_size -= size; }
- void contract(const LayoutBoxExtent& box)
- {
- m_location.move(box.left(), box.top());
- m_size.shrink(box.left() + box.right(), box.top() + box.bottom());
- }
- void contract(LayoutUnit dw, LayoutUnit dh) { m_size.expand(-dw, -dh); }
-
- void shiftXEdgeTo(LayoutUnit edge)
- {
- LayoutUnit delta = edge - x();
- setX(edge);
- setWidth(std::max<LayoutUnit>(0, width() - delta));
- }
- void shiftMaxXEdgeTo(LayoutUnit edge)
- {
- LayoutUnit delta = edge - maxX();
- setWidth(std::max<LayoutUnit>(0, width() + delta));
- }
- void shiftYEdgeTo(LayoutUnit edge)
- {
- LayoutUnit delta = edge - y();
- setY(edge);
- setHeight(std::max<LayoutUnit>(0, height() - delta));
- }
- void shiftMaxYEdgeTo(LayoutUnit edge)
- {
- LayoutUnit delta = edge - maxY();
- setHeight(std::max<LayoutUnit>(0, height() + delta));
- }
-
- LayoutPoint minXMinYCorner() const { return m_location; } // typically topLeft
- LayoutPoint maxXMinYCorner() const { return LayoutPoint(m_location.x() + m_size.width(), m_location.y()); } // typically topRight
- LayoutPoint minXMaxYCorner() const { return LayoutPoint(m_location.x(), m_location.y() + m_size.height()); } // typically bottomLeft
- LayoutPoint maxXMaxYCorner() const { return LayoutPoint(m_location.x() + m_size.width(), m_location.y() + m_size.height()); } // typically bottomRight
-
- bool intersects(const LayoutRect&) const;
- bool contains(const LayoutRect&) const;
-
- // This checks to see if the rect contains x,y in the traditional sense.
- // Equivalent to checking if the rect contains a 1x1 rect below and to the right of (px,py).
- bool contains(LayoutUnit px, LayoutUnit py) const
- { return px >= x() && px < maxX() && py >= y() && py < maxY(); }
- bool contains(const LayoutPoint& point) const { return contains(point.x(), point.y()); }
-
- void intersect(const LayoutRect&);
- void unite(const LayoutRect&);
- void uniteIfNonZero(const LayoutRect&);
-
- void inflateX(LayoutUnit dx)
- {
- m_location.setX(m_location.x() - dx);
- m_size.setWidth(m_size.width() + dx + dx);
- }
- void inflateY(LayoutUnit dy)
- {
- m_location.setY(m_location.y() - dy);
- m_size.setHeight(m_size.height() + dy + dy);
- }
- void inflate(LayoutUnit d) { inflateX(d); inflateY(d); }
- void scale(float s);
- void scale(float xAxisScale, float yAxisScale);
-
- LayoutRect transposedRect() const { return LayoutRect(m_location.transposedPoint(), m_size.transposedSize()); }
-
- static LayoutRect infiniteRect()
- {
- // Return a rect that is slightly smaller than the true max rect to allow pixelSnapping to round up to the nearest IntRect without overflowing.
- return LayoutRect(LayoutUnit::nearlyMin() / 2, LayoutUnit::nearlyMin() / 2, LayoutUnit::nearlyMax(), LayoutUnit::nearlyMax());
- }
-
-private:
- LayoutPoint m_location;
- LayoutSize m_size;
-};
-
-inline LayoutRect intersection(const LayoutRect& a, const LayoutRect& b)
-{
- LayoutRect c = a;
- c.intersect(b);
- return c;
-}
-
-inline LayoutRect unionRect(const LayoutRect& a, const LayoutRect& b)
-{
- LayoutRect c = a;
- c.unite(b);
- return c;
-}
-
-LayoutRect unionRect(const Vector<LayoutRect>&);
-
-inline bool operator==(const LayoutRect& a, const LayoutRect& b)
-{
- return a.location() == b.location() && a.size() == b.size();
-}
-
-inline bool operator!=(const LayoutRect& a, const LayoutRect& b)
-{
- return a.location() != b.location() || a.size() != b.size();
-}
-
-inline IntRect pixelSnappedIntRect(const LayoutRect& rect)
-{
- return IntRect(roundedIntPoint(rect.location()), IntSize(snapSizeToPixel(rect.width(), rect.x()),
- snapSizeToPixel(rect.height(), rect.y())));
-}
-
-IntRect enclosingIntRect(const LayoutRect&);
-LayoutRect enclosingLayoutRect(const FloatRect&);
-
-
-inline IntRect pixelSnappedIntRect(LayoutUnit left, LayoutUnit top, LayoutUnit width, LayoutUnit height)
-{
- return IntRect(left.round(), top.round(), snapSizeToPixel(width, left), snapSizeToPixel(height, top));
-}
-
-inline IntRect pixelSnappedIntRectFromEdges(LayoutUnit left, LayoutUnit top, LayoutUnit right, LayoutUnit bottom)
-{
- return IntRect(left.round(), top.round(), snapSizeToPixel(right - left, left), snapSizeToPixel(bottom - top, top));
-}
-
-inline IntRect pixelSnappedIntRect(LayoutPoint location, LayoutSize size)
-{
- return IntRect(roundedIntPoint(location), pixelSnappedIntSize(size, location));
-}
-
-} // namespace WebCore
-
-#endif // LayoutRect_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/LayoutSize.h b/chromium/third_party/WebKit/Source/core/platform/graphics/LayoutSize.h
deleted file mode 100644
index 3844e6b66ce..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/LayoutSize.h
+++ /dev/null
@@ -1,189 +0,0 @@
-/*
- * Copyright (c) 2012, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef LayoutSize_h
-#define LayoutSize_h
-
-#include "core/platform/LayoutUnit.h"
-#include "core/platform/graphics/FloatSize.h"
-#include "core/platform/graphics/IntSize.h"
-
-namespace WebCore {
-
-class LayoutPoint;
-
-enum AspectRatioFit {
- AspectRatioFitShrink,
- AspectRatioFitGrow
-};
-
-class LayoutSize {
-public:
- LayoutSize() : m_width(0), m_height(0) { }
- LayoutSize(const IntSize& size) : m_width(size.width()), m_height(size.height()) { }
- LayoutSize(LayoutUnit width, LayoutUnit height) : m_width(width), m_height(height) { }
-
- explicit LayoutSize(const FloatSize& size) : m_width(size.width()), m_height(size.height()) { }
-
- LayoutUnit width() const { return m_width; }
- LayoutUnit height() const { return m_height; }
-
- void setWidth(LayoutUnit width) { m_width = width; }
- void setHeight(LayoutUnit height) { m_height = height; }
-
- bool isEmpty() const { return m_width <= 0 || m_height <= 0; }
- bool isZero() const { return !m_width && !m_height; }
-
- float aspectRatio() const { return static_cast<float>(m_width) / static_cast<float>(m_height); }
-
- void expand(LayoutUnit width, LayoutUnit height)
- {
- m_width += width;
- m_height += height;
- }
-
- void shrink(LayoutUnit width, LayoutUnit height)
- {
- m_width -= width;
- m_height -= height;
- }
-
- void scale(float scale)
- {
- m_width *= scale;
- m_height *= scale;
- }
-
- void scale(float widthScale, float heightScale)
- {
- m_width *= widthScale;
- m_height *= heightScale;
- }
-
- LayoutSize expandedTo(const LayoutSize& other) const
- {
- return LayoutSize(m_width > other.m_width ? m_width : other.m_width,
- m_height > other.m_height ? m_height : other.m_height);
- }
-
- LayoutSize shrunkTo(const LayoutSize& other) const
- {
- return LayoutSize(m_width < other.m_width ? m_width : other.m_width,
- m_height < other.m_height ? m_height : other.m_height);
- }
-
- void clampNegativeToZero()
- {
- *this = expandedTo(LayoutSize());
- }
-
- void clampToMinimumSize(const LayoutSize& minimumSize)
- {
- if (m_width < minimumSize.width())
- m_width = minimumSize.width();
- if (m_height < minimumSize.height())
- m_height = minimumSize.height();
- }
-
- LayoutSize transposedSize() const
- {
- return LayoutSize(m_height, m_width);
- }
-
- LayoutSize fitToAspectRatio(const LayoutSize& aspectRatio, AspectRatioFit fit) const
- {
- float heightScale = height().toFloat() / aspectRatio.height().toFloat();
- float widthScale = width().toFloat() / aspectRatio.width().toFloat();
- if ((widthScale > heightScale) != (fit == AspectRatioFitGrow))
- return LayoutSize(height() * aspectRatio.width() / aspectRatio.height(), height());
- return LayoutSize(width(), width() * aspectRatio.height() / aspectRatio.width());
- }
-
-private:
- LayoutUnit m_width, m_height;
-};
-
-inline LayoutSize& operator+=(LayoutSize& a, const LayoutSize& b)
-{
- a.setWidth(a.width() + b.width());
- a.setHeight(a.height() + b.height());
- return a;
-}
-
-inline LayoutSize& operator-=(LayoutSize& a, const LayoutSize& b)
-{
- a.setWidth(a.width() - b.width());
- a.setHeight(a.height() - b.height());
- return a;
-}
-
-inline LayoutSize operator+(const LayoutSize& a, const LayoutSize& b)
-{
- return LayoutSize(a.width() + b.width(), a.height() + b.height());
-}
-
-inline LayoutSize operator-(const LayoutSize& a, const LayoutSize& b)
-{
- return LayoutSize(a.width() - b.width(), a.height() - b.height());
-}
-
-inline LayoutSize operator-(const LayoutSize& size)
-{
- return LayoutSize(-size.width(), -size.height());
-}
-
-inline bool operator==(const LayoutSize& a, const LayoutSize& b)
-{
- return a.width() == b.width() && a.height() == b.height();
-}
-
-inline bool operator!=(const LayoutSize& a, const LayoutSize& b)
-{
- return a.width() != b.width() || a.height() != b.height();
-}
-
-inline IntSize flooredIntSize(const LayoutSize& s)
-{
- return IntSize(s.width().floor(), s.height().floor());
-}
-
-inline IntSize roundedIntSize(const LayoutSize& s)
-{
- return IntSize(s.width().round(), s.height().round());
-}
-
-inline LayoutSize roundedLayoutSize(const FloatSize& s)
-{
- return LayoutSize(s);
-}
-
-} // namespace WebCore
-
-#endif // LayoutSize_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/MediaPlayer.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/MediaPlayer.cpp
deleted file mode 100644
index 5d5a3795df3..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/MediaPlayer.cpp
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Copyright (C) 2007, 2008, 2009, 2010, 2011, 2012, 2013 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/platform/graphics/MediaPlayer.h"
-#include "wtf/PassOwnPtr.h"
-
-namespace WebCore {
-
-static CreateMediaEnginePlayer createMediaEngineFunction = 0;
-
-void MediaPlayer::setMediaEngineCreateFunction(CreateMediaEnginePlayer createFunction)
-{
- ASSERT(createFunction);
- ASSERT(!createMediaEngineFunction);
- createMediaEngineFunction = createFunction;
-}
-
-PassOwnPtr<MediaPlayer> MediaPlayer::create(MediaPlayerClient* client)
-{
- ASSERT(createMediaEngineFunction);
- return createMediaEngineFunction(client);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/MediaPlayer.h b/chromium/third_party/WebKit/Source/core/platform/graphics/MediaPlayer.h
deleted file mode 100644
index e84467e963c..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/MediaPlayer.h
+++ /dev/null
@@ -1,194 +0,0 @@
-/*
- * Copyright (C) 2007, 2008, 2009, 2010, 2011, 2012, 2013 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef MediaPlayer_h
-#define MediaPlayer_h
-
-#include "core/platform/graphics/GraphicsTypes3D.h"
-#include "wtf/Forward.h"
-#include "wtf/Noncopyable.h"
-
-namespace WebKit { class WebLayer; }
-
-namespace WebCore {
-
-class AudioSourceProvider;
-class GraphicsContext;
-class GraphicsContext3D;
-class InbandTextTrackPrivate;
-class IntRect;
-class IntSize;
-class KURL;
-class MediaPlayer;
-class HTMLMediaSource;
-class TimeRanges;
-
-class MediaPlayerClient {
-public:
- enum CORSMode { Unspecified, Anonymous, UseCredentials };
-
- virtual ~MediaPlayerClient() { }
-
- // the network state has changed
- virtual void mediaPlayerNetworkStateChanged() = 0;
-
- // the ready state has changed
- virtual void mediaPlayerReadyStateChanged() = 0;
-
- // time has jumped, eg. not as a result of normal playback
- virtual void mediaPlayerTimeChanged() = 0;
-
- // the media file duration has changed, or is now known
- virtual void mediaPlayerDurationChanged() = 0;
-
- // the play/pause status changed
- virtual void mediaPlayerPlaybackStateChanged() = 0;
-
- virtual void mediaPlayerRequestSeek(double) = 0;
-
-// Presentation-related methods
- // a new frame of video is available
- virtual void mediaPlayerRepaint() = 0;
-
- // the movie size has changed
- virtual void mediaPlayerSizeChanged() = 0;
-
- virtual void mediaPlayerEngineUpdated() = 0;
-
- enum MediaKeyErrorCode { UnknownError = 1, ClientError, ServiceError, OutputError, HardwareChangeError, DomainError };
- virtual void mediaPlayerKeyAdded(const String& /* keySystem */, const String& /* sessionId */) = 0;
- virtual void mediaPlayerKeyError(const String& /* keySystem */, const String& /* sessionId */, MediaKeyErrorCode, unsigned short /* systemCode */) = 0;
- virtual void mediaPlayerKeyMessage(const String& /* keySystem */, const String& /* sessionId */, const unsigned char* /* message */, unsigned /* messageLength */, const KURL& /* defaultURL */) = 0;
- virtual bool mediaPlayerKeyNeeded(const String& /* keySystem */, const String& /* sessionId */, const unsigned char* /* initData */, unsigned /* initDataLength */) = 0;
-
-#if ENABLE(ENCRYPTED_MEDIA_V2)
- virtual bool mediaPlayerKeyNeeded(Uint8Array*) = 0;
-#endif
-
- virtual CORSMode mediaPlayerCORSMode() const = 0;
-
- virtual void mediaPlayerScheduleLayerUpdate() = 0;
-
- virtual void mediaPlayerDidAddTrack(PassRefPtr<InbandTextTrackPrivate>) = 0;
- virtual void mediaPlayerDidRemoveTrack(PassRefPtr<InbandTextTrackPrivate>) = 0;
-};
-
-typedef PassOwnPtr<MediaPlayer> (*CreateMediaEnginePlayer)(MediaPlayerClient*);
-
-class MediaPlayer {
- WTF_MAKE_NONCOPYABLE(MediaPlayer);
-public:
- static PassOwnPtr<MediaPlayer> create(MediaPlayerClient*);
- static void setMediaEngineCreateFunction(CreateMediaEnginePlayer);
-
- static double invalidTime() { return -1.0; }
-
- MediaPlayer() { }
- virtual ~MediaPlayer() { }
-
- virtual void load(const String& url) = 0;
- virtual void load(const String& url, PassRefPtr<HTMLMediaSource>) = 0;
-
- virtual void prepareToPlay() = 0;
- virtual WebKit::WebLayer* platformLayer() const = 0;
-
- virtual void play() = 0;
- virtual void pause() = 0;
-
- virtual bool supportsFullscreen() const = 0;
- virtual bool supportsSave() const = 0;
- virtual IntSize naturalSize() const = 0;
-
- virtual bool hasVideo() const = 0;
- virtual bool hasAudio() const = 0;
-
- virtual double duration() const = 0;
-
- virtual double currentTime() const = 0;
-
- virtual void seek(double) = 0;
-
- virtual bool seeking() const = 0;
-
- virtual double rate() const = 0;
- virtual void setRate(double) = 0;
-
- virtual bool paused() const = 0;
-
- virtual void setVolume(double) = 0;
- virtual void setMuted(bool) = 0;
-
- enum NetworkState { Empty, Idle, Loading, Loaded, FormatError, NetworkError, DecodeError };
- virtual NetworkState networkState() const = 0;
-
- enum ReadyState { HaveNothing, HaveMetadata, HaveCurrentData, HaveFutureData, HaveEnoughData };
- virtual ReadyState readyState() const = 0;
-
- virtual double maxTimeSeekable() const = 0;
- virtual PassRefPtr<TimeRanges> buffered() const = 0;
-
- virtual bool didLoadingProgress() const = 0;
-
- virtual void paint(GraphicsContext*, const IntRect&) = 0;
-
- virtual void paintCurrentFrameInContext(GraphicsContext*, const IntRect&) = 0;
- virtual bool copyVideoTextureToPlatformTexture(GraphicsContext3D*, Platform3DObject, GC3Dint, GC3Denum, GC3Denum, bool, bool) = 0;
-
- enum Preload { None, MetaData, Auto };
- virtual void setPreload(Preload) = 0;
-
- virtual void showFullscreenOverlay() = 0;
- virtual void hideFullscreenOverlay() = 0;
- virtual bool canShowFullscreenOverlay() const = 0;
-
- // whether accelerated rendering is supported by the media engine for the current media.
- virtual bool supportsAcceleratedRendering() const = 0;
-
- virtual bool hasSingleSecurityOrigin() const = 0;
-
- virtual bool didPassCORSAccessCheck() const = 0;
-
- // Time value in the movie's time scale. It is only necessary to override this if the media
- // engine uses rational numbers to represent media time.
- virtual double mediaTimeForTimeValue(double timeValue) const = 0;
-
- virtual unsigned decodedFrameCount() const = 0;
- virtual unsigned droppedFrameCount() const = 0;
- virtual unsigned audioDecodedByteCount() const = 0;
- virtual unsigned videoDecodedByteCount() const = 0;
-
-#if ENABLE(WEB_AUDIO)
- virtual AudioSourceProvider* audioSourceProvider() = 0;
-#endif
-
- enum MediaKeyException { NoError, InvalidPlayerState, KeySystemNotSupported };
- virtual MediaKeyException addKey(const String&, const unsigned char*, unsigned, const unsigned char*, unsigned, const String&) = 0;
- virtual MediaKeyException generateKeyRequest(const String&, const unsigned char*, unsigned) = 0;
- virtual MediaKeyException cancelKeyRequest(const String&, const String&) = 0;
-};
-
-}
-
-#endif // MediaPlayer_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/MediaSourcePrivate.h b/chromium/third_party/WebKit/Source/core/platform/graphics/MediaSourcePrivate.h
deleted file mode 100644
index e3f606e4248..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/MediaSourcePrivate.h
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-#ifndef MediaSourcePrivate_h
-#define MediaSourcePrivate_h
-
-#include "wtf/Forward.h"
-
-namespace WebCore {
-
-class SourceBufferPrivate;
-
-class MediaSourcePrivate {
-public:
- typedef Vector<String, 0> CodecsArray;
-
- MediaSourcePrivate() { }
- virtual ~MediaSourcePrivate() { }
-
- enum AddStatus { Ok, NotSupported, ReachedIdLimit };
- virtual AddStatus addSourceBuffer(const String& type, const CodecsArray&, OwnPtr<SourceBufferPrivate>*) = 0;
- virtual double duration() = 0;
- virtual void setDuration(double) = 0;
- enum EndOfStreamStatus { EosNoError, EosNetworkError, EosDecodeError };
- virtual void markEndOfStream(EndOfStreamStatus) = 0;
- virtual void unmarkEndOfStream() = 0;
-};
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/OWNERS b/chromium/third_party/WebKit/Source/core/platform/graphics/OWNERS
deleted file mode 100644
index 94e7e0304bc..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/OWNERS
+++ /dev/null
@@ -1,3 +0,0 @@
-per-file BitmapImage.*=pkasting@chromium.org
-per-file Image.*=pkasting@chromium.org
-per-file ImageSource.*=pkasting@chromium.org \ No newline at end of file
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/Path.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/Path.cpp
deleted file mode 100644
index baaa013e807..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/Path.cpp
+++ /dev/null
@@ -1,456 +0,0 @@
-/*
- * Copyright (C) 2003, 2006 Apple Computer, Inc. All rights reserved.
- * 2006 Rob Buis <buis@kde.org>
- * Copyright (C) 2007 Eric Seidel <eric@webkit.org>
- * Copyright (C) 2013 Google Inc. All rights reserved.
- * Copyright (C) 2013 Intel Corporation. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/Path.h"
-
-#include <math.h>
-#include "core/platform/graphics/FloatPoint.h"
-#include "core/platform/graphics/FloatRect.h"
-#include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/graphics/skia/SkiaUtils.h"
-#include "core/platform/graphics/transforms/AffineTransform.h"
-#include "third_party/skia/include/core/SkPath.h"
-#include "third_party/skia/include/core/SkPathMeasure.h"
-#include "third_party/skia/include/pathops/SkPathOps.h"
-#include "wtf/MathExtras.h"
-
-namespace WebCore {
-
-Path::Path()
- : m_path()
-{
-}
-
-Path::Path(const Path& other)
-{
- m_path = SkPath(other.m_path);
-}
-
-Path::~Path()
-{
-}
-
-Path& Path::operator=(const Path& other)
-{
- m_path = SkPath(other.m_path);
- return *this;
-}
-
-bool Path::operator==(const Path& other) const
-{
- return m_path == other.m_path;
-}
-
-bool Path::contains(const FloatPoint& point, WindRule rule) const
-{
- return SkPathContainsPoint(m_path, point, rule == RULE_NONZERO ? SkPath::kWinding_FillType : SkPath::kEvenOdd_FillType);
-}
-
-bool Path::strokeContains(const FloatPoint& point, const StrokeData& strokeData) const
-{
- SkPaint paint;
- strokeData.setupPaint(&paint);
- SkPath strokePath;
- paint.getFillPath(m_path, &strokePath);
-
- return SkPathContainsPoint(strokePath, point, SkPath::kWinding_FillType);
-}
-
-FloatRect Path::boundingRect() const
-{
- return m_path.getBounds();
-}
-
-FloatRect Path::strokeBoundingRect(const StrokeData& strokeData) const
-{
- SkPaint paint;
- strokeData.setupPaint(&paint);
- SkPath boundingPath;
- paint.getFillPath(m_path, &boundingPath);
-
- return boundingPath.getBounds();
-}
-
-static FloatPoint* convertPathPoints(FloatPoint dst[], const SkPoint src[], int count)
-{
- for (int i = 0; i < count; i++) {
- dst[i].setX(SkScalarToFloat(src[i].fX));
- dst[i].setY(SkScalarToFloat(src[i].fY));
- }
- return dst;
-}
-
-void Path::apply(void* info, PathApplierFunction function) const
-{
- SkPath::RawIter iter(m_path);
- SkPoint pts[4];
- PathElement pathElement;
- FloatPoint pathPoints[3];
-
- for (;;) {
- switch (iter.next(pts)) {
- case SkPath::kMove_Verb:
- pathElement.type = PathElementMoveToPoint;
- pathElement.points = convertPathPoints(pathPoints, &pts[0], 1);
- break;
- case SkPath::kLine_Verb:
- pathElement.type = PathElementAddLineToPoint;
- pathElement.points = convertPathPoints(pathPoints, &pts[1], 1);
- break;
- case SkPath::kQuad_Verb:
- pathElement.type = PathElementAddQuadCurveToPoint;
- pathElement.points = convertPathPoints(pathPoints, &pts[1], 2);
- break;
- case SkPath::kCubic_Verb:
- pathElement.type = PathElementAddCurveToPoint;
- pathElement.points = convertPathPoints(pathPoints, &pts[1], 3);
- break;
- case SkPath::kClose_Verb:
- pathElement.type = PathElementCloseSubpath;
- pathElement.points = convertPathPoints(pathPoints, 0, 0);
- break;
- case SkPath::kDone_Verb:
- return;
- default: // place-holder for kConic_Verb, when that lands from skia
- break;
- }
- function(info, &pathElement);
- }
-}
-
-void Path::transform(const AffineTransform& xform)
-{
- m_path.transform(xform);
-}
-
-float Path::length() const
-{
- SkScalar length = 0;
- SkPathMeasure measure(m_path, false);
-
- do {
- length += measure.getLength();
- } while (measure.nextContour());
-
- return SkScalarToFloat(length);
-}
-
-FloatPoint Path::pointAtLength(float length, bool& ok) const
-{
- FloatPoint point;
- float normal;
- ok = pointAndNormalAtLength(length, point, normal);
- return point;
-}
-
-float Path::normalAngleAtLength(float length, bool& ok) const
-{
- FloatPoint point;
- float normal;
- ok = pointAndNormalAtLength(length, point, normal);
- return normal;
-}
-
-bool Path::pointAndNormalAtLength(float length, FloatPoint& point, float& normal) const
-{
- SkPathMeasure measure(m_path, false);
-
- do {
- SkScalar contourLength = measure.getLength();
- if (length <= contourLength) {
- SkVector tangent;
- SkPoint position;
-
- if (measure.getPosTan(length, &position, &tangent)) {
- normal = rad2deg(SkScalarToFloat(SkScalarATan2(tangent.fY, tangent.fX)));
- point = FloatPoint(SkScalarToFloat(position.fX), SkScalarToFloat(position.fY));
- return true;
- }
- }
- length -= contourLength;
- } while (measure.nextContour());
-
- normal = 0;
- point = FloatPoint(0, 0);
- return false;
-}
-
-void Path::clear()
-{
- m_path.reset();
-}
-
-bool Path::isEmpty() const
-{
- return m_path.isEmpty();
-}
-
-bool Path::hasCurrentPoint() const
-{
- return m_path.getPoints(0, 0);
-}
-
-FloatPoint Path::currentPoint() const
-{
- if (m_path.countPoints() > 0) {
- SkPoint skResult;
- m_path.getLastPt(&skResult);
- FloatPoint result;
- result.setX(SkScalarToFloat(skResult.fX));
- result.setY(SkScalarToFloat(skResult.fY));
- return result;
- }
-
- // FIXME: Why does this return quietNaN? Other ports return 0,0.
- float quietNaN = std::numeric_limits<float>::quiet_NaN();
- return FloatPoint(quietNaN, quietNaN);
-}
-
-WindRule Path::windRule() const
-{
- return m_path.getFillType() == SkPath::kEvenOdd_FillType
- ? RULE_EVENODD
- : RULE_NONZERO;
-}
-
-void Path::setWindRule(const WindRule rule)
-{
- m_path.setFillType(rule == RULE_EVENODD
- ? SkPath::kEvenOdd_FillType
- : SkPath::kWinding_FillType);
-}
-
-void Path::moveTo(const FloatPoint& point)
-{
- m_path.moveTo(point);
-}
-
-void Path::addLineTo(const FloatPoint& point)
-{
- m_path.lineTo(point);
-}
-
-void Path::addQuadCurveTo(const FloatPoint& cp, const FloatPoint& ep)
-{
- m_path.quadTo(cp, ep);
-}
-
-void Path::addBezierCurveTo(const FloatPoint& p1, const FloatPoint& p2, const FloatPoint& ep)
-{
- m_path.cubicTo(p1, p2, ep);
-}
-
-void Path::addArcTo(const FloatPoint& p1, const FloatPoint& p2, float radius)
-{
- m_path.arcTo(p1, p2, WebCoreFloatToSkScalar(radius));
-}
-
-void Path::closeSubpath()
-{
- m_path.close();
-}
-
-void Path::addArc(const FloatPoint& p, float radius, float startAngle, float endAngle, bool anticlockwise)
-{
- ASSERT(std::abs(endAngle - startAngle) < 4 * piFloat);
- ASSERT(startAngle >= 0 && startAngle < 2 * piFloat);
- ASSERT((anticlockwise && (startAngle - endAngle) >= 0) || (!anticlockwise && (endAngle - startAngle) >= 0));
-
- SkScalar cx = WebCoreFloatToSkScalar(p.x());
- SkScalar cy = WebCoreFloatToSkScalar(p.y());
- SkScalar radiusScalar = WebCoreFloatToSkScalar(radius);
- SkScalar s360 = SkIntToScalar(360);
-
- SkRect oval;
- oval.set(cx - radiusScalar, cy - radiusScalar, cx + radiusScalar, cy + radiusScalar);
-
- float sweep = endAngle - startAngle;
- SkScalar startDegrees = WebCoreFloatToSkScalar(startAngle * 180 / piFloat);
- SkScalar sweepDegrees = WebCoreFloatToSkScalar(sweep * 180 / piFloat);
-
- // We can't use SkPath::addOval(), because addOval() makes new sub-path. addOval() calls moveTo() and close() internally.
-
- // Use s180, not s360, because SkPath::arcTo(oval, angle, s360, false) draws nothing.
- SkScalar s180 = SkIntToScalar(180);
- if (sweepDegrees >= s360) {
- // SkPath::arcTo can't handle the sweepAngle that is equal to or greater than 2Pi.
- m_path.arcTo(oval, startDegrees, s180, false);
- m_path.arcTo(oval, startDegrees + s180, s180, false);
- m_path.arcTo(oval, startDegrees + s360, sweepDegrees - s360, false);
- return;
- }
- if (sweepDegrees <= -s360) {
- m_path.arcTo(oval, startDegrees, -s180, false);
- m_path.arcTo(oval, startDegrees - s180, -s180, false);
- m_path.arcTo(oval, startDegrees - s360, sweepDegrees + s360, false);
- return;
- }
-
- m_path.arcTo(oval, startDegrees, sweepDegrees, false);
-}
-
-void Path::addRect(const FloatRect& rect)
-{
- m_path.addRect(rect);
-}
-
-void Path::addEllipse(const FloatPoint& p, float radiusX, float radiusY, float rotation, float startAngle, float endAngle, bool anticlockwise)
-{
- ASSERT(std::abs(endAngle - startAngle) < 4 * piFloat);
- ASSERT(startAngle >= 0 && startAngle < 2 * piFloat);
- ASSERT((anticlockwise && (startAngle - endAngle) >= 0) || (!anticlockwise && (endAngle - startAngle) >= 0));
-
- // Optimize the common case of an entire ellipse.
- SkScalar twoPiScalar = WebCoreFloatToSkScalar(2 * piFloat);
- SkScalar endAngleScalar = WebCoreFloatToSkScalar(endAngle);
- if (!rotation && !startAngle && SkScalarNearlyEqual(twoPiScalar, SkScalarAbs(endAngleScalar))) {
- FloatRect boundingRect(p - FloatSize(radiusX, radiusY), FloatSize(2 * radiusX, 2 * radiusY));
- if (anticlockwise && SkScalarNearlyEqual(twoPiScalar, -endAngleScalar)) {
- m_path.addOval(boundingRect, SkPath::kCCW_Direction);
- return;
- }
- if (!anticlockwise && SkScalarNearlyEqual(twoPiScalar, endAngleScalar)) {
- m_path.addOval(boundingRect);
- return;
- }
- }
-
- // Add an arc after the relevant transform.
- AffineTransform ellipseTransform = AffineTransform::translation(p.x(), p.y()).rotate(rad2deg(rotation)).scale(radiusX, radiusY);
- ASSERT(ellipseTransform.isInvertible());
- AffineTransform inverseEllipseTransform = ellipseTransform.inverse();
- transform(inverseEllipseTransform);
- addArc(FloatPoint::zero(), 1 /* unit circle */, startAngle, endAngle, anticlockwise);
- transform(ellipseTransform);
-}
-
-void Path::addEllipse(const FloatRect& rect)
-{
- m_path.addOval(rect);
-}
-
-void Path::addRoundedRect(const RoundedRect& r)
-{
- addRoundedRect(r.rect(), r.radii().topLeft(), r.radii().topRight(), r.radii().bottomLeft(), r.radii().bottomRight());
-}
-
-void Path::addRoundedRect(const FloatRect& rect, const FloatSize& roundingRadii)
-{
- if (rect.isEmpty())
- return;
-
- FloatSize radius(roundingRadii);
- FloatSize halfSize(rect.width() / 2, rect.height() / 2);
-
- // Apply the SVG corner radius constraints, per the rect section of the SVG shapes spec: if
- // one of rx,ry is negative, then the other corner radius value is used. If both values are
- // negative then rx = ry = 0. If rx is greater than half of the width of the rectangle
- // then set rx to half of the width; ry is handled similarly.
-
- if (radius.width() < 0)
- radius.setWidth((radius.height() < 0) ? 0 : radius.height());
-
- if (radius.height() < 0)
- radius.setHeight(radius.width());
-
- if (radius.width() > halfSize.width())
- radius.setWidth(halfSize.width());
-
- if (radius.height() > halfSize.height())
- radius.setHeight(halfSize.height());
-
- addPathForRoundedRect(rect, radius, radius, radius, radius);
-}
-
-void Path::addRoundedRect(const FloatRect& rect, const FloatSize& topLeftRadius, const FloatSize& topRightRadius, const FloatSize& bottomLeftRadius, const FloatSize& bottomRightRadius)
-{
- if (rect.isEmpty())
- return;
-
- if (rect.width() < topLeftRadius.width() + topRightRadius.width()
- || rect.width() < bottomLeftRadius.width() + bottomRightRadius.width()
- || rect.height() < topLeftRadius.height() + bottomLeftRadius.height()
- || rect.height() < topRightRadius.height() + bottomRightRadius.height()) {
- // If all the radii cannot be accommodated, return a rect.
- addRect(rect);
- return;
- }
-
- addPathForRoundedRect(rect, topLeftRadius, topRightRadius, bottomLeftRadius, bottomRightRadius);
-}
-
-void Path::addPathForRoundedRect(const FloatRect& rect, const FloatSize& topLeftRadius, const FloatSize& topRightRadius, const FloatSize& bottomLeftRadius, const FloatSize& bottomRightRadius)
-{
- addBeziersForRoundedRect(rect, topLeftRadius, topRightRadius, bottomLeftRadius, bottomRightRadius);
-}
-
-// Approximation of control point positions on a bezier to simulate a quarter of a circle.
-// This is 1-kappa, where kappa = 4 * (sqrt(2) - 1) / 3
-static const float gCircleControlPoint = 0.447715f;
-
-void Path::addBeziersForRoundedRect(const FloatRect& rect, const FloatSize& topLeftRadius, const FloatSize& topRightRadius, const FloatSize& bottomLeftRadius, const FloatSize& bottomRightRadius)
-{
- moveTo(FloatPoint(rect.x() + topLeftRadius.width(), rect.y()));
-
- addLineTo(FloatPoint(rect.maxX() - topRightRadius.width(), rect.y()));
- if (topRightRadius.width() > 0 || topRightRadius.height() > 0)
- addBezierCurveTo(FloatPoint(rect.maxX() - topRightRadius.width() * gCircleControlPoint, rect.y()),
- FloatPoint(rect.maxX(), rect.y() + topRightRadius.height() * gCircleControlPoint),
- FloatPoint(rect.maxX(), rect.y() + topRightRadius.height()));
- addLineTo(FloatPoint(rect.maxX(), rect.maxY() - bottomRightRadius.height()));
- if (bottomRightRadius.width() > 0 || bottomRightRadius.height() > 0)
- addBezierCurveTo(FloatPoint(rect.maxX(), rect.maxY() - bottomRightRadius.height() * gCircleControlPoint),
- FloatPoint(rect.maxX() - bottomRightRadius.width() * gCircleControlPoint, rect.maxY()),
- FloatPoint(rect.maxX() - bottomRightRadius.width(), rect.maxY()));
- addLineTo(FloatPoint(rect.x() + bottomLeftRadius.width(), rect.maxY()));
- if (bottomLeftRadius.width() > 0 || bottomLeftRadius.height() > 0)
- addBezierCurveTo(FloatPoint(rect.x() + bottomLeftRadius.width() * gCircleControlPoint, rect.maxY()),
- FloatPoint(rect.x(), rect.maxY() - bottomLeftRadius.height() * gCircleControlPoint),
- FloatPoint(rect.x(), rect.maxY() - bottomLeftRadius.height()));
- addLineTo(FloatPoint(rect.x(), rect.y() + topLeftRadius.height()));
- if (topLeftRadius.width() > 0 || topLeftRadius.height() > 0)
- addBezierCurveTo(FloatPoint(rect.x(), rect.y() + topLeftRadius.height() * gCircleControlPoint),
- FloatPoint(rect.x() + topLeftRadius.width() * gCircleControlPoint, rect.y()),
- FloatPoint(rect.x() + topLeftRadius.width(), rect.y()));
-
- closeSubpath();
-}
-
-void Path::translate(const FloatSize& size)
-{
- m_path.offset(WebCoreFloatToSkScalar(size.width()), WebCoreFloatToSkScalar(size.height()));
-}
-
-bool Path::unionPath(const Path& other)
-{
- return Op(m_path, other.m_path, kUnion_PathOp, &m_path);
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/Path.h b/chromium/third_party/WebKit/Source/core/platform/graphics/Path.h
deleted file mode 100644
index 5a1e658334a..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/Path.h
+++ /dev/null
@@ -1,132 +0,0 @@
-/*
- * Copyright (C) 2003, 2006, 2009 Apple Inc. All rights reserved.
- * 2006 Rob Buis <buis@kde.org>
- * Copyright (C) 2007-2008 Torch Mobile, Inc.
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef Path_h
-#define Path_h
-
-#include "core/platform/graphics/RoundedRect.h"
-#include "core/platform/graphics/WindRule.h"
-#include "third_party/skia/include/core/SkPath.h"
-#include "wtf/FastAllocBase.h"
-#include "wtf/Forward.h"
-
-class SkPath;
-
-namespace WebCore {
-
-class AffineTransform;
-class FloatPoint;
-class FloatRect;
-class FloatSize;
-class GraphicsContext;
-class StrokeData;
-
-enum PathElementType {
- PathElementMoveToPoint, // The points member will contain 1 value.
- PathElementAddLineToPoint, // The points member will contain 1 value.
- PathElementAddQuadCurveToPoint, // The points member will contain 2 values.
- PathElementAddCurveToPoint, // The points member will contain 3 values.
- PathElementCloseSubpath // The points member will contain no values.
-};
-
-// The points in the sturcture are the same as those that would be used with the
-// add... method. For example, a line returns the endpoint, while a cubic returns
-// two tangent points and the endpoint.
-struct PathElement {
- PathElementType type;
- FloatPoint* points;
-};
-
-typedef void (*PathApplierFunction)(void* info, const PathElement*);
-
-class Path {
- WTF_MAKE_FAST_ALLOCATED;
-public:
- Path();
- ~Path();
-
- Path(const Path&);
- Path& operator=(const Path&);
- bool operator==(const Path&) const;
-
- bool contains(const FloatPoint&, WindRule = RULE_NONZERO) const;
- bool strokeContains(const FloatPoint&, const StrokeData&) const;
- FloatRect boundingRect() const;
- FloatRect strokeBoundingRect(const StrokeData&) const;
-
- float length() const;
- FloatPoint pointAtLength(float length, bool& ok) const;
- float normalAngleAtLength(float length, bool& ok) const;
- bool pointAndNormalAtLength(float length, FloatPoint&, float&) const;
-
- void clear();
- bool isEmpty() const;
- // Gets the current point of the current path, which is conceptually the final point reached by the path so far.
- // Note the Path can be empty (isEmpty() == true) and still have a current point.
- bool hasCurrentPoint() const;
- FloatPoint currentPoint() const;
-
- WindRule windRule() const;
- void setWindRule(const WindRule);
-
- void moveTo(const FloatPoint&);
- void addLineTo(const FloatPoint&);
- void addQuadCurveTo(const FloatPoint& controlPoint, const FloatPoint& endPoint);
- void addBezierCurveTo(const FloatPoint& controlPoint1, const FloatPoint& controlPoint2, const FloatPoint& endPoint);
- void addArcTo(const FloatPoint&, const FloatPoint&, float radius);
- void closeSubpath();
-
- void addArc(const FloatPoint&, float radius, float startAngle, float endAngle, bool anticlockwise);
- void addRect(const FloatRect&);
- void addEllipse(const FloatPoint&, float radiusX, float radiusY, float rotation, float startAngle, float endAngle, bool anticlockwise);
- void addEllipse(const FloatRect&);
-
- void addRoundedRect(const FloatRect&, const FloatSize& roundingRadii);
- void addRoundedRect(const FloatRect&, const FloatSize& topLeftRadius, const FloatSize& topRightRadius, const FloatSize& bottomLeftRadius, const FloatSize& bottomRightRadius);
- void addRoundedRect(const RoundedRect&);
-
- void translate(const FloatSize&);
-
- const SkPath& skPath() const { return m_path; }
-
- void apply(void* info, PathApplierFunction) const;
- void transform(const AffineTransform&);
-
- void addPathForRoundedRect(const FloatRect&, const FloatSize& topLeftRadius, const FloatSize& topRightRadius, const FloatSize& bottomLeftRadius, const FloatSize& bottomRightRadius);
- void addBeziersForRoundedRect(const FloatRect&, const FloatSize& topLeftRadius, const FloatSize& topRightRadius, const FloatSize& bottomLeftRadius, const FloatSize& bottomRightRadius);
-
- // Updates the path to the union (inclusive-or) of itself with the given argument.
- bool unionPath(const Path& other);
-
-private:
- SkPath m_path;
-};
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/PathTraversalState.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/PathTraversalState.cpp
deleted file mode 100644
index 532fbae555e..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/PathTraversalState.cpp
+++ /dev/null
@@ -1,224 +0,0 @@
-/*
- * Copyright (C) 2006, 2007 Eric Seidel <eric@webkit.org>
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-#include "core/platform/graphics/PathTraversalState.h"
-
-#include "wtf/MathExtras.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-static const float kPathSegmentLengthTolerance = 0.00001f;
-
-static inline FloatPoint midPoint(const FloatPoint& first, const FloatPoint& second)
-{
- return FloatPoint((first.x() + second.x()) / 2.0f, (first.y() + second.y()) / 2.0f);
-}
-
-static inline float distanceLine(const FloatPoint& start, const FloatPoint& end)
-{
- return sqrtf((end.x() - start.x()) * (end.x() - start.x()) + (end.y() - start.y()) * (end.y() - start.y()));
-}
-
-struct QuadraticBezier {
- QuadraticBezier() { }
- QuadraticBezier(const FloatPoint& s, const FloatPoint& c, const FloatPoint& e)
- : start(s)
- , control(c)
- , end(e)
- {
- }
-
- float approximateDistance() const
- {
- return distanceLine(start, control) + distanceLine(control, end);
- }
-
- void split(QuadraticBezier& left, QuadraticBezier& right) const
- {
- left.control = midPoint(start, control);
- right.control = midPoint(control, end);
-
- FloatPoint leftControlToRightControl = midPoint(left.control, right.control);
- left.end = leftControlToRightControl;
- right.start = leftControlToRightControl;
-
- left.start = start;
- right.end = end;
- }
-
- FloatPoint start;
- FloatPoint control;
- FloatPoint end;
-};
-
-struct CubicBezier {
- CubicBezier() { }
- CubicBezier(const FloatPoint& s, const FloatPoint& c1, const FloatPoint& c2, const FloatPoint& e)
- : start(s)
- , control1(c1)
- , control2(c2)
- , end(e)
- {
- }
-
- float approximateDistance() const
- {
- return distanceLine(start, control1) + distanceLine(control1, control2) + distanceLine(control2, end);
- }
-
- void split(CubicBezier& left, CubicBezier& right) const
- {
- FloatPoint startToControl1 = midPoint(control1, control2);
-
- left.start = start;
- left.control1 = midPoint(start, control1);
- left.control2 = midPoint(left.control1, startToControl1);
-
- right.control2 = midPoint(control2, end);
- right.control1 = midPoint(right.control2, startToControl1);
- right.end = end;
-
- FloatPoint leftControl2ToRightControl1 = midPoint(left.control2, right.control1);
- left.end = leftControl2ToRightControl1;
- right.start = leftControl2ToRightControl1;
- }
-
- FloatPoint start;
- FloatPoint control1;
- FloatPoint control2;
- FloatPoint end;
-};
-
-// FIXME: This function is possibly very slow due to the ifs required for proper path measuring
-// A simple speed-up would be to use an additional boolean template parameter to control whether
-// to use the "fast" version of this function with no PathTraversalState updating, vs. the slow
-// version which does update the PathTraversalState. We'll have to shark it to see if that's necessary.
-// Another check which is possible up-front (to send us down the fast path) would be to check if
-// approximateDistance() + current total distance > desired distance
-template<class CurveType>
-static float curveLength(PathTraversalState& traversalState, CurveType curve)
-{
- static const unsigned curveStackDepthLimit = 20;
-
- Vector<CurveType> curveStack;
- curveStack.append(curve);
-
- float totalLength = 0;
- do {
- float length = curve.approximateDistance();
- if ((length - distanceLine(curve.start, curve.end)) > kPathSegmentLengthTolerance && curveStack.size() <= curveStackDepthLimit) {
- CurveType leftCurve;
- CurveType rightCurve;
- curve.split(leftCurve, rightCurve);
- curve = leftCurve;
- curveStack.append(rightCurve);
- } else {
- totalLength += length;
- if (traversalState.m_action == PathTraversalState::TraversalPointAtLength
- || traversalState.m_action == PathTraversalState::TraversalNormalAngleAtLength) {
- traversalState.m_previous = curve.start;
- traversalState.m_current = curve.end;
- if (traversalState.m_totalLength + totalLength > traversalState.m_desiredLength)
- return totalLength;
- }
- curve = curveStack.last();
- curveStack.removeLast();
- }
- } while (!curveStack.isEmpty());
-
- return totalLength;
-}
-
-PathTraversalState::PathTraversalState(PathTraversalAction action)
- : m_action(action)
- , m_success(false)
- , m_totalLength(0)
- , m_segmentIndex(0)
- , m_desiredLength(0)
- , m_normalAngle(0)
-{
-}
-
-float PathTraversalState::closeSubpath()
-{
- float distance = distanceLine(m_current, m_start);
- m_current = m_control1 = m_control2 = m_start;
- return distance;
-}
-
-float PathTraversalState::moveTo(const FloatPoint& point)
-{
- m_current = m_start = m_control1 = m_control2 = point;
- return 0;
-}
-
-float PathTraversalState::lineTo(const FloatPoint& point)
-{
- float distance = distanceLine(m_current, point);
- m_current = m_control1 = m_control2 = point;
- return distance;
-}
-
-float PathTraversalState::quadraticBezierTo(const FloatPoint& newControl, const FloatPoint& newEnd)
-{
- float distance = curveLength<QuadraticBezier>(*this, QuadraticBezier(m_current, newControl, newEnd));
-
- m_control1 = newControl;
- m_control2 = newEnd;
-
- if (m_action != TraversalPointAtLength && m_action != TraversalNormalAngleAtLength)
- m_current = newEnd;
-
- return distance;
-}
-
-float PathTraversalState::cubicBezierTo(const FloatPoint& newControl1, const FloatPoint& newControl2, const FloatPoint& newEnd)
-{
- float distance = curveLength<CubicBezier>(*this, CubicBezier(m_current, newControl1, newControl2, newEnd));
-
- m_control1 = newEnd;
- m_control2 = newControl2;
-
- if (m_action != TraversalPointAtLength && m_action != TraversalNormalAngleAtLength)
- m_current = newEnd;
-
- return distance;
-}
-
-void PathTraversalState::processSegment()
-{
- if (m_action == TraversalSegmentAtLength && m_totalLength >= m_desiredLength)
- m_success = true;
-
- if ((m_action == TraversalPointAtLength || m_action == TraversalNormalAngleAtLength) && m_totalLength >= m_desiredLength) {
- float slope = FloatPoint(m_current - m_previous).slopeAngleRadians();
- if (m_action == TraversalPointAtLength) {
- float offset = m_desiredLength - m_totalLength;
- m_current.move(offset * cosf(slope), offset * sinf(slope));
- } else
- m_normalAngle = rad2deg(slope);
- m_success = true;
- }
- m_previous = m_current;
-}
-
-}
-
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/PathTraversalState.h b/chromium/third_party/WebKit/Source/core/platform/graphics/PathTraversalState.h
deleted file mode 100644
index 19498bee127..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/PathTraversalState.h
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Copyright (C) 2006, 2007 Eric Seidel <eric@webkit.org>
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef PathTraversalState_h
-#define PathTraversalState_h
-
-#include "core/platform/graphics/FloatPoint.h"
-
-namespace WebCore {
-
-class PathTraversalState {
-public:
- enum PathTraversalAction {
- TraversalTotalLength,
- TraversalPointAtLength,
- TraversalSegmentAtLength,
- TraversalNormalAngleAtLength
- };
-
- PathTraversalState(PathTraversalAction);
-
- float closeSubpath();
- float moveTo(const FloatPoint&);
- float lineTo(const FloatPoint&);
- float quadraticBezierTo(const FloatPoint& newControl, const FloatPoint& newEnd);
- float cubicBezierTo(const FloatPoint& newControl1, const FloatPoint& newControl2, const FloatPoint& newEnd);
-
- void processSegment();
-
-public:
- PathTraversalAction m_action;
- bool m_success;
-
- FloatPoint m_current;
- FloatPoint m_start;
- FloatPoint m_control1;
- FloatPoint m_control2;
-
- float m_totalLength;
- unsigned m_segmentIndex;
- float m_desiredLength;
-
- // For normal calculations
- FloatPoint m_previous;
- float m_normalAngle; // degrees
-};
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/Pattern.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/Pattern.cpp
deleted file mode 100644
index 58159fe3371..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/Pattern.cpp
+++ /dev/null
@@ -1,102 +0,0 @@
-/*
- * Copyright (C) 2006, 2007, 2008 Apple Computer, Inc. All rights reserved.
- * Copyright (C) 2008 Eric Seidel <eric@webkit.org>
- * Copyright (C) 2013 Google, Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/Pattern.h"
-
-#include <v8.h>
-#include "SkCanvas.h"
-#include "SkColorShader.h"
-#include "SkShader.h"
-#include "core/platform/graphics/Image.h"
-
-namespace WebCore {
-
-Pattern::Pattern(PassRefPtr<Image> image, bool repeatX, bool repeatY)
- : m_repeatX(repeatX)
- , m_repeatY(repeatY)
- , m_externalMemoryAllocated(0)
-{
- ASSERT(image);
- m_tileImage = image->nativeImageForCurrentFrame();
-}
-
-Pattern::~Pattern()
-{
- if (m_externalMemoryAllocated)
- v8::V8::AdjustAmountOfExternalAllocatedMemory(-m_externalMemoryAllocated);
-}
-
-SkShader* Pattern::shader()
-{
- if (m_pattern)
- return m_pattern.get();
-
- // If we don't have a bitmap, return a transparent shader.
- if (!m_tileImage)
- m_pattern = adoptRef(new SkColorShader(SK_ColorTRANSPARENT));
- else if (m_repeatX && m_repeatY)
- m_pattern = adoptRef(SkShader::CreateBitmapShader(m_tileImage->bitmap(), SkShader::kRepeat_TileMode, SkShader::kRepeat_TileMode));
- else {
- // Skia does not have a "draw the tile only once" option. Clamp_TileMode
- // repeats the last line of the image after drawing one tile. To avoid
- // filling the space with arbitrary pixels, this workaround forces the
- // image to have a line of transparent pixels on the "repeated" edge(s),
- // thus causing extra space to be transparent filled.
- SkShader::TileMode tileModeX = m_repeatX ? SkShader::kRepeat_TileMode : SkShader::kClamp_TileMode;
- SkShader::TileMode tileModeY = m_repeatY ? SkShader::kRepeat_TileMode : SkShader::kClamp_TileMode;
- int expandW = m_repeatX ? 0 : 1;
- int expandH = m_repeatY ? 0 : 1;
-
- // Create a transparent bitmap 1 pixel wider and/or taller than the
- // original, then copy the orignal into it.
- // FIXME: Is there a better way to pad (not scale) an image in skia?
- SkBitmap bm2;
- bm2.setConfig(m_tileImage->bitmap().config(), m_tileImage->bitmap().width() + expandW, m_tileImage->bitmap().height() + expandH);
- bm2.allocPixels();
- bm2.eraseARGB(0x00, 0x00, 0x00, 0x00);
- SkCanvas canvas(bm2);
- canvas.drawBitmap(m_tileImage->bitmap(), 0, 0);
- bm2.setImmutable();
- m_pattern = adoptRef(SkShader::CreateBitmapShader(bm2, tileModeX, tileModeY));
-
- // Clamp to int, since that's what the adjust function takes.
- m_externalMemoryAllocated = static_cast<int>(std::min(static_cast<size_t>(INT_MAX), bm2.getSafeSize()));
- v8::V8::AdjustAmountOfExternalAllocatedMemory(m_externalMemoryAllocated);
- }
- m_pattern->setLocalMatrix(m_patternSpaceTransformation);
- return m_pattern.get();
-}
-
-void Pattern::setPatternSpaceTransform(const AffineTransform& patternSpaceTransformation)
-{
- m_patternSpaceTransformation = patternSpaceTransformation;
- if (m_pattern)
- m_pattern->setLocalMatrix(m_patternSpaceTransformation);
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/Pattern.h b/chromium/third_party/WebKit/Source/core/platform/graphics/Pattern.h
deleted file mode 100644
index 925e91d9f85..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/Pattern.h
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * Copyright (C) 2006, 2007, 2008 Apple Computer, Inc. All rights reserved.
- * Copyright (C) 2008 Eric Seidel <eric@webkit.org>
- * Copyright (C) 2007-2008 Torch Mobile, Inc.
- * Copyright (C) 2013 Google, Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef Pattern_h
-#define Pattern_h
-
-#include "SkShader.h"
-#include "core/platform/graphics/Image.h"
-#include "core/platform/graphics/transforms/AffineTransform.h"
-
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/RefPtr.h"
-
-namespace WebCore {
-
-class AffineTransform;
-
-class Pattern : public RefCounted<Pattern> {
-public:
- static PassRefPtr<Pattern> create(PassRefPtr<Image> tileImage, bool repeatX, bool repeatY)
- {
- return adoptRef(new Pattern(tileImage, repeatX, repeatY));
- }
- ~Pattern();
-
- SkShader* shader();
-
- void setPatternSpaceTransform(const AffineTransform& patternSpaceTransformation);
- const AffineTransform& getPatternSpaceTransform() { return m_patternSpaceTransformation; };
-
- bool repeatX() const { return m_repeatX; }
- bool repeatY() const { return m_repeatY; }
-
-private:
- Pattern(PassRefPtr<Image>, bool repeatX, bool repeatY);
-
- RefPtr<NativeImageSkia> m_tileImage;
- bool m_repeatX;
- bool m_repeatY;
- AffineTransform m_patternSpaceTransformation;
- RefPtr<SkShader> m_pattern;
- int m_externalMemoryAllocated;
-};
-
-} //namespace
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/Region.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/Region.cpp
deleted file mode 100644
index 148e8381a71..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/Region.cpp
+++ /dev/null
@@ -1,611 +0,0 @@
-/*
- * Copyright (C) 2010, 2011 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/Region.h"
-
-#include <stdio.h>
-
-// A region class based on the paper "Scanline Coherent Shape Algebra"
-// by Jonathan E. Steinhart from the book "Graphics Gems II".
-//
-// This implementation uses two vectors instead of linked list, and
-// also compresses regions when possible.
-
-namespace WebCore {
-
-Region::Region()
-{
-}
-
-Region::Region(const IntRect& rect)
- : m_bounds(rect)
- , m_shape(rect)
-{
-}
-
-Vector<IntRect> Region::rects() const
-{
- Vector<IntRect> rects;
-
- for (Shape::SpanIterator span = m_shape.spans_begin(), end = m_shape.spans_end(); span != end && span + 1 != end; ++span) {
- int y = span->y;
- int height = (span + 1)->y - y;
-
- for (Shape::SegmentIterator segment = m_shape.segments_begin(span), end = m_shape.segments_end(span); segment != end && segment + 1 != end; segment += 2) {
- int x = *segment;
- int width = *(segment + 1) - x;
-
- rects.append(IntRect(x, y, width, height));
- }
- }
-
- return rects;
-}
-
-bool Region::contains(const Region& region) const
-{
- if (!m_bounds.contains(region.m_bounds))
- return false;
-
- return Shape::compareShapes<Shape::CompareContainsOperation>(m_shape, region.m_shape);
-}
-
-bool Region::contains(const IntPoint& point) const
-{
- if (!m_bounds.contains(point))
- return false;
-
- for (Shape::SpanIterator span = m_shape.spans_begin(), end = m_shape.spans_end(); span != end && span + 1 != end; ++span) {
- int y = span->y;
- int maxY = (span + 1)->y;
-
- if (y > point.y())
- break;
- if (maxY <= point.y())
- continue;
-
- for (Shape::SegmentIterator segment = m_shape.segments_begin(span), end = m_shape.segments_end(span); segment != end && segment + 1 != end; segment += 2) {
- int x = *segment;
- int maxX = *(segment + 1);
-
- if (x > point.x())
- break;
- if (maxX > point.x())
- return true;
- }
- }
-
- return false;
-}
-
-bool Region::intersects(const Region& region) const
-{
- if (!m_bounds.intersects(region.m_bounds))
- return false;
-
- return Shape::compareShapes<Shape::CompareIntersectsOperation>(m_shape, region.m_shape);
-}
-
-unsigned Region::totalArea() const
-{
- Vector<IntRect> rects = this->rects();
- size_t size = rects.size();
- unsigned totalArea = 0;
-
- for (size_t i = 0; i < size; ++i) {
- IntRect rect = rects[i];
- totalArea += (rect.width() * rect.height());
- }
-
- return totalArea;
-}
-
-template<typename CompareOperation>
-bool Region::Shape::compareShapes(const Shape& aShape, const Shape& bShape)
-{
- bool result = CompareOperation::defaultResult;
-
- Shape::SpanIterator aSpan = aShape.spans_begin();
- Shape::SpanIterator aSpanEnd = aShape.spans_end();
- Shape::SpanIterator bSpan = bShape.spans_begin();
- Shape::SpanIterator bSpanEnd = bShape.spans_end();
-
- bool aHadSegmentInPreviousSpan = false;
- bool bHadSegmentInPreviousSpan = false;
- while (aSpan != aSpanEnd && aSpan + 1 != aSpanEnd && bSpan != bSpanEnd && bSpan + 1 != bSpanEnd) {
- int aY = aSpan->y;
- int aMaxY = (aSpan + 1)->y;
- int bY = bSpan->y;
- int bMaxY = (bSpan + 1)->y;
-
- Shape::SegmentIterator aSegment = aShape.segments_begin(aSpan);
- Shape::SegmentIterator aSegmentEnd = aShape.segments_end(aSpan);
- Shape::SegmentIterator bSegment = bShape.segments_begin(bSpan);
- Shape::SegmentIterator bSegmentEnd = bShape.segments_end(bSpan);
-
- // Look for a non-overlapping part of the spans. If B had a segment in its previous span, then we already tested A against B within that span.
- bool aHasSegmentInSpan = aSegment != aSegmentEnd;
- bool bHasSegmentInSpan = bSegment != bSegmentEnd;
- if (aY < bY && !bHadSegmentInPreviousSpan && aHasSegmentInSpan && CompareOperation::aOutsideB(result))
- return result;
- if (bY < aY && !aHadSegmentInPreviousSpan && bHasSegmentInSpan && CompareOperation::bOutsideA(result))
- return result;
-
- aHadSegmentInPreviousSpan = aHasSegmentInSpan;
- bHadSegmentInPreviousSpan = bHasSegmentInSpan;
-
- bool spansOverlap = bMaxY > aY && bY < aMaxY;
- if (spansOverlap) {
- while (aSegment != aSegmentEnd && bSegment != bSegmentEnd) {
- int aX = *aSegment;
- int aMaxX = *(aSegment + 1);
- int bX = *bSegment;
- int bMaxX = *(bSegment + 1);
-
- bool segmentsOverlap = bMaxX > aX && bX < aMaxX;
- if (segmentsOverlap && CompareOperation::aOverlapsB(result))
- return result;
- if (aX < bX && CompareOperation::aOutsideB(result))
- return result;
- if (bX < aX && CompareOperation::bOutsideA(result))
- return result;
-
- if (aMaxX < bMaxX)
- aSegment += 2;
- else if (bMaxX < aMaxX)
- bSegment += 2;
- else {
- aSegment += 2;
- bSegment += 2;
- }
- }
-
- if (aSegment != aSegmentEnd && CompareOperation::aOutsideB(result))
- return result;
- if (bSegment != bSegmentEnd && CompareOperation::bOutsideA(result))
- return result;
- }
-
- if (aMaxY < bMaxY)
- aSpan += 1;
- else if (bMaxY < aMaxY)
- bSpan += 1;
- else {
- aSpan += 1;
- bSpan += 1;
- }
- }
-
- if (aSpan != aSpanEnd && aSpan + 1 != aSpanEnd && CompareOperation::aOutsideB(result))
- return result;
- if (bSpan != bSpanEnd && bSpan + 1 != bSpanEnd && CompareOperation::bOutsideA(result))
- return result;
-
- return result;
-}
-
-struct Region::Shape::CompareContainsOperation {
- const static bool defaultResult = true;
- inline static bool aOutsideB(bool& /* result */) { return false; }
- inline static bool bOutsideA(bool& result) { result = false; return true; }
- inline static bool aOverlapsB(bool& /* result */) { return false; }
-};
-
-struct Region::Shape::CompareIntersectsOperation {
- const static bool defaultResult = false;
- inline static bool aOutsideB(bool& /* result */) { return false; }
- inline static bool bOutsideA(bool& /* result */) { return false; }
- inline static bool aOverlapsB(bool& result) { result = true; return true; }
-};
-
-Region::Shape::Shape()
-{
-}
-
-Region::Shape::Shape(const IntRect& rect)
-{
- appendSpan(rect.y());
- appendSegment(rect.x());
- appendSegment(rect.maxX());
- appendSpan(rect.maxY());
-}
-
-void Region::Shape::appendSpan(int y)
-{
- m_spans.append(Span(y, m_segments.size()));
-}
-
-bool Region::Shape::canCoalesce(SegmentIterator begin, SegmentIterator end)
-{
- if (m_spans.isEmpty())
- return false;
-
- SegmentIterator lastSpanBegin = m_segments.data() + m_spans.last().segmentIndex;
- SegmentIterator lastSpanEnd = m_segments.data() + m_segments.size();
-
- // Check if both spans have an equal number of segments.
- if (lastSpanEnd - lastSpanBegin != end - begin)
- return false;
-
- // Check if both spans are equal.
- if (!std::equal(begin, end, lastSpanBegin))
- return false;
-
- // Since the segments are equal the second segment can just be ignored.
- return true;
-}
-
-void Region::Shape::appendSpan(int y, SegmentIterator begin, SegmentIterator end)
-{
- if (canCoalesce(begin, end))
- return;
-
- appendSpan(y);
- m_segments.appendRange(begin, end);
-}
-
-void Region::Shape::appendSpans(const Shape& shape, SpanIterator begin, SpanIterator end)
-{
- for (SpanIterator it = begin; it != end; ++it)
- appendSpan(it->y, shape.segments_begin(it), shape.segments_end(it));
-}
-
-void Region::Shape::appendSegment(int x)
-{
- m_segments.append(x);
-}
-
-Region::Shape::SpanIterator Region::Shape::spans_begin() const
-{
- return m_spans.data();
-}
-
-Region::Shape::SpanIterator Region::Shape::spans_end() const
-{
- return m_spans.data() + m_spans.size();
-}
-
-Region::Shape::SegmentIterator Region::Shape::segments_begin(SpanIterator it) const
-{
- ASSERT(it >= m_spans.data());
- ASSERT(it < m_spans.data() + m_spans.size());
-
- // Check if this span has any segments.
- if (it->segmentIndex == m_segments.size())
- return 0;
-
- return &m_segments[it->segmentIndex];
-}
-
-Region::Shape::SegmentIterator Region::Shape::segments_end(SpanIterator it) const
-{
- ASSERT(it >= m_spans.data());
- ASSERT(it < m_spans.data() + m_spans.size());
-
- // Check if this span has any segments.
- if (it->segmentIndex == m_segments.size())
- return 0;
-
- ASSERT(it + 1 < m_spans.data() + m_spans.size());
- size_t segmentIndex = (it + 1)->segmentIndex;
-
- ASSERT_WITH_SECURITY_IMPLICATION(segmentIndex <= m_segments.size());
- return m_segments.data() + segmentIndex;
-}
-
-#ifndef NDEBUG
-void Region::Shape::dump() const
-{
- for (Shape::SpanIterator span = spans_begin(), end = spans_end(); span != end; ++span) {
- printf("%6d: (", span->y);
-
- for (Shape::SegmentIterator segment = segments_begin(span), end = segments_end(span); segment != end; ++segment)
- printf("%d ", *segment);
- printf(")\n");
- }
-
- printf("\n");
-}
-#endif
-
-IntRect Region::Shape::bounds() const
-{
- if (isEmpty())
- return IntRect();
-
- SpanIterator span = spans_begin();
- int minY = span->y;
-
- SpanIterator lastSpan = spans_end() - 1;
- int maxY = lastSpan->y;
-
- int minX = std::numeric_limits<int>::max();
- int maxX = std::numeric_limits<int>::min();
-
- while (span != lastSpan) {
- SegmentIterator firstSegment = segments_begin(span);
- SegmentIterator lastSegment = segments_end(span) - 1;
-
- if (firstSegment && lastSegment) {
- ASSERT(firstSegment != lastSegment);
-
- if (*firstSegment < minX)
- minX = *firstSegment;
-
- if (*lastSegment > maxX)
- maxX = *lastSegment;
- }
-
- ++span;
- }
-
- ASSERT(minX <= maxX);
- ASSERT(minY <= maxY);
-
- return IntRect(minX, minY, maxX - minX, maxY - minY);
-}
-
-void Region::Shape::translate(const IntSize& offset)
-{
- for (size_t i = 0; i < m_segments.size(); ++i)
- m_segments[i] += offset.width();
- for (size_t i = 0; i < m_spans.size(); ++i)
- m_spans[i].y += offset.height();
-}
-
-void Region::Shape::swap(Shape& other)
-{
- m_segments.swap(other.m_segments);
- m_spans.swap(other.m_spans);
-}
-
-enum {
- Shape1,
- Shape2,
-};
-
-template<typename Operation>
-Region::Shape Region::Shape::shapeOperation(const Shape& shape1, const Shape& shape2)
-{
- COMPILE_ASSERT(!(!Operation::shouldAddRemainingSegmentsFromSpan1 && Operation::shouldAddRemainingSegmentsFromSpan2), invalid_segment_combination);
- COMPILE_ASSERT(!(!Operation::shouldAddRemainingSpansFromShape1 && Operation::shouldAddRemainingSpansFromShape2), invalid_span_combination);
-
- Shape result;
- if (Operation::trySimpleOperation(shape1, shape2, result))
- return result;
-
- SpanIterator spans1 = shape1.spans_begin();
- SpanIterator spans1End = shape1.spans_end();
-
- SpanIterator spans2 = shape2.spans_begin();
- SpanIterator spans2End = shape2.spans_end();
-
- SegmentIterator segments1 = 0;
- SegmentIterator segments1End = 0;
-
- SegmentIterator segments2 = 0;
- SegmentIterator segments2End = 0;
-
- // Iterate over all spans.
- while (spans1 != spans1End && spans2 != spans2End) {
- int y = 0;
- int test = spans1->y - spans2->y;
-
- if (test <= 0) {
- y = spans1->y;
-
- segments1 = shape1.segments_begin(spans1);
- segments1End = shape1.segments_end(spans1);
- ++spans1;
- }
- if (test >= 0) {
- y = spans2->y;
-
- segments2 = shape2.segments_begin(spans2);
- segments2End = shape2.segments_end(spans2);
- ++spans2;
- }
-
- int flag = 0;
- int oldFlag = 0;
-
- SegmentIterator s1 = segments1;
- SegmentIterator s2 = segments2;
-
- Vector<int, 32> segments;
-
- // Now iterate over the segments in each span and construct a new vector of segments.
- while (s1 != segments1End && s2 != segments2End) {
- int test = *s1 - *s2;
- int x;
-
- if (test <= 0) {
- x = *s1;
- flag = flag ^ 1;
- ++s1;
- }
- if (test >= 0) {
- x = *s2;
- flag = flag ^ 2;
- ++s2;
- }
-
- if (flag == Operation::opCode || oldFlag == Operation::opCode)
- segments.append(x);
-
- oldFlag = flag;
- }
-
- // Add any remaining segments.
- if (Operation::shouldAddRemainingSegmentsFromSpan1 && s1 != segments1End)
- segments.appendRange(s1, segments1End);
- else if (Operation::shouldAddRemainingSegmentsFromSpan2 && s2 != segments2End)
- segments.appendRange(s2, segments2End);
-
- // Add the span.
- if (!segments.isEmpty() || !result.isEmpty())
- result.appendSpan(y, segments.data(), segments.data() + segments.size());
- }
-
- // Add any remaining spans.
- if (Operation::shouldAddRemainingSpansFromShape1 && spans1 != spans1End)
- result.appendSpans(shape1, spans1, spans1End);
- else if (Operation::shouldAddRemainingSpansFromShape2 && spans2 != spans2End)
- result.appendSpans(shape2, spans2, spans2End);
-
- return result;
-}
-
-struct Region::Shape::UnionOperation {
- static bool trySimpleOperation(const Shape& shape1, const Shape& shape2, Shape& result)
- {
- if (shape1.isEmpty()) {
- result = shape2;
- return true;
- }
-
- return false;
- }
-
- static const int opCode = 0;
-
- static const bool shouldAddRemainingSegmentsFromSpan1 = true;
- static const bool shouldAddRemainingSegmentsFromSpan2 = true;
- static const bool shouldAddRemainingSpansFromShape1 = true;
- static const bool shouldAddRemainingSpansFromShape2 = true;
-};
-
-Region::Shape Region::Shape::unionShapes(const Shape& shape1, const Shape& shape2)
-{
- return shapeOperation<UnionOperation>(shape1, shape2);
-}
-
-struct Region::Shape::IntersectOperation {
- static bool trySimpleOperation(const Shape&, const Shape&, Shape&)
- {
- return false;
- }
-
- static const int opCode = 3;
-
- static const bool shouldAddRemainingSegmentsFromSpan1 = false;
- static const bool shouldAddRemainingSegmentsFromSpan2 = false;
- static const bool shouldAddRemainingSpansFromShape1 = false;
- static const bool shouldAddRemainingSpansFromShape2 = false;
-};
-
-Region::Shape Region::Shape::intersectShapes(const Shape& shape1, const Shape& shape2)
-{
- return shapeOperation<IntersectOperation>(shape1, shape2);
-}
-
-struct Region::Shape::SubtractOperation {
- static bool trySimpleOperation(const Shape&, const Shape&, Region::Shape&)
- {
- return false;
- }
-
- static const int opCode = 1;
-
- static const bool shouldAddRemainingSegmentsFromSpan1 = true;
- static const bool shouldAddRemainingSegmentsFromSpan2 = false;
- static const bool shouldAddRemainingSpansFromShape1 = true;
- static const bool shouldAddRemainingSpansFromShape2 = false;
-};
-
-Region::Shape Region::Shape::subtractShapes(const Shape& shape1, const Shape& shape2)
-{
- return shapeOperation<SubtractOperation>(shape1, shape2);
-}
-
-#ifndef NDEBUG
-void Region::dump() const
-{
- printf("Bounds: (%d, %d, %d, %d)\n",
- m_bounds.x(), m_bounds.y(), m_bounds.width(), m_bounds.height());
- m_shape.dump();
-}
-#endif
-
-void Region::intersect(const Region& region)
-{
- if (m_bounds.isEmpty())
- return;
- if (!m_bounds.intersects(region.m_bounds)) {
- m_shape = Shape();
- m_bounds = IntRect();
- return;
- }
-
- Shape intersectedShape = Shape::intersectShapes(m_shape, region.m_shape);
-
- m_shape.swap(intersectedShape);
- m_bounds = m_shape.bounds();
-}
-
-void Region::unite(const Region& region)
-{
- if (region.isEmpty())
- return;
- if (isRect() && m_bounds.contains(region.m_bounds))
- return;
- if (region.isRect() && region.m_bounds.contains(m_bounds)) {
- m_shape = region.m_shape;
- m_bounds = region.m_bounds;
- return;
- }
- // FIXME: We may want another way to construct a Region without doing this test when we expect it to be false.
- if (!isRect() && contains(region))
- return;
-
- Shape unitedShape = Shape::unionShapes(m_shape, region.m_shape);
-
- m_shape.swap(unitedShape);
- m_bounds.unite(region.m_bounds);
-}
-
-void Region::subtract(const Region& region)
-{
- if (m_bounds.isEmpty())
- return;
- if (region.isEmpty())
- return;
- if (!m_bounds.intersects(region.m_bounds))
- return;
-
- Shape subtractedShape = Shape::subtractShapes(m_shape, region.m_shape);
-
- m_shape.swap(subtractedShape);
- m_bounds = m_shape.bounds();
-}
-
-void Region::translate(const IntSize& offset)
-{
- m_bounds.move(offset);
- m_shape.translate(offset);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/Region.h b/chromium/third_party/WebKit/Source/core/platform/graphics/Region.h
deleted file mode 100644
index 9e8406cb9f1..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/Region.h
+++ /dev/null
@@ -1,180 +0,0 @@
-/*
- * Copyright (C) 2010, 2011 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef Region_h
-#define Region_h
-
-#include "core/platform/graphics/IntRect.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-class Region {
-public:
- Region();
- Region(const IntRect&);
-
- IntRect bounds() const { return m_bounds; }
- bool isEmpty() const { return m_bounds.isEmpty(); }
- bool isRect() const { return m_shape.isRect(); }
-
- Vector<IntRect> rects() const;
-
- void unite(const Region&);
- void intersect(const Region&);
- void subtract(const Region&);
-
- void translate(const IntSize&);
-
- // Returns true if the query region is a subset of this region.
- bool contains(const Region&) const;
-
- bool contains(const IntPoint&) const;
-
- // Returns true if the query region intersects any part of this region.
- bool intersects(const Region&) const;
-
- unsigned totalArea() const;
-
-#ifndef NDEBUG
- void dump() const;
-#endif
-
-private:
- struct Span {
- Span(int y, size_t segmentIndex)
- : y(y), segmentIndex(segmentIndex)
- {
- }
-
- int y;
- size_t segmentIndex;
- };
-
- class Shape {
- public:
- Shape();
- Shape(const IntRect&);
-
- IntRect bounds() const;
- bool isEmpty() const { return m_spans.isEmpty(); }
- bool isRect() const { return m_spans.size() <= 2 && m_segments.size() <= 2; }
-
- typedef const Span* SpanIterator;
- SpanIterator spans_begin() const;
- SpanIterator spans_end() const;
-
- typedef const int* SegmentIterator;
- SegmentIterator segments_begin(SpanIterator) const;
- SegmentIterator segments_end(SpanIterator) const;
-
- static Shape unionShapes(const Shape& shape1, const Shape& shape2);
- static Shape intersectShapes(const Shape& shape1, const Shape& shape2);
- static Shape subtractShapes(const Shape& shape1, const Shape& shape2);
-
- void translate(const IntSize&);
- void swap(Shape&);
-
- struct CompareContainsOperation;
- struct CompareIntersectsOperation;
-
- template<typename CompareOperation>
- static bool compareShapes(const Shape& shape1, const Shape& shape2);
-
-#ifndef NDEBUG
- void dump() const;
-#endif
-
- private:
- struct UnionOperation;
- struct IntersectOperation;
- struct SubtractOperation;
-
- template<typename Operation>
- static Shape shapeOperation(const Shape& shape1, const Shape& shape2);
-
- void appendSegment(int x);
- void appendSpan(int y);
- void appendSpan(int y, SegmentIterator begin, SegmentIterator end);
- void appendSpans(const Shape&, SpanIterator begin, SpanIterator end);
-
- bool canCoalesce(SegmentIterator begin, SegmentIterator end);
-
- Vector<int, 32> m_segments;
- Vector<Span, 16> m_spans;
-
- friend bool operator==(const Shape&, const Shape&);
- };
-
- IntRect m_bounds;
- Shape m_shape;
-
- friend bool operator==(const Region&, const Region&);
- friend bool operator==(const Shape&, const Shape&);
- friend bool operator==(const Span&, const Span&);
-};
-
-static inline Region intersect(const Region& a, const Region& b)
-{
- Region result(a);
- result.intersect(b);
-
- return result;
-}
-
-static inline Region subtract(const Region& a, const Region& b)
-{
- Region result(a);
- result.subtract(b);
-
- return result;
-}
-
-static inline Region translate(const Region& region, const IntSize& offset)
-{
- Region result(region);
- result.translate(offset);
-
- return result;
-}
-
-inline bool operator==(const Region& a, const Region& b)
-{
- return a.m_bounds == b.m_bounds && a.m_shape == b.m_shape;
-}
-
-inline bool operator==(const Region::Shape& a, const Region::Shape& b)
-{
- return a.m_spans == b.m_spans && a.m_segments == b.m_segments;
-}
-
-inline bool operator==(const Region::Span& a, const Region::Span& b)
-{
- return a.y == b.y && a.segmentIndex == b.segmentIndex;
-}
-
-} // namespace WebCore
-
-#endif // Region_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/RoundedRect.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/RoundedRect.cpp
deleted file mode 100644
index 4ef82618f82..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/RoundedRect.cpp
+++ /dev/null
@@ -1,249 +0,0 @@
-/*
- * Copyright (C) 2003, 2006, 2009 Apple Inc. All rights reserved.
- * Copyright (C) 2010 Google Inc. All rights reserved.
- * Copyright (C) 2013 Xidorn Quan (quanxunzhen@gmail.com)
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/RoundedRect.h"
-#include "wtf/Assertions.h"
-
-#include <algorithm>
-
-using namespace std;
-
-namespace WebCore {
-
-bool RoundedRect::Radii::isZero() const
-{
- return m_topLeft.isZero() && m_topRight.isZero() && m_bottomLeft.isZero() && m_bottomRight.isZero();
-}
-
-void RoundedRect::Radii::scale(float factor)
-{
- if (factor == 1)
- return;
-
- // If either radius on a corner becomes zero, reset both radii on that corner.
- m_topLeft.scale(factor);
- if (!m_topLeft.width() || !m_topLeft.height())
- m_topLeft = IntSize();
- m_topRight.scale(factor);
- if (!m_topRight.width() || !m_topRight.height())
- m_topRight = IntSize();
- m_bottomLeft.scale(factor);
- if (!m_bottomLeft.width() || !m_bottomLeft.height())
- m_bottomLeft = IntSize();
- m_bottomRight.scale(factor);
- if (!m_bottomRight.width() || !m_bottomRight.height())
- m_bottomRight = IntSize();
-
-}
-
-void RoundedRect::Radii::expand(int topWidth, int bottomWidth, int leftWidth, int rightWidth)
-{
- if (m_topLeft.width() > 0 && m_topLeft.height() > 0) {
- m_topLeft.setWidth(max<int>(0, m_topLeft.width() + leftWidth));
- m_topLeft.setHeight(max<int>(0, m_topLeft.height() + topWidth));
- }
- if (m_topRight.width() > 0 && m_topRight.height() > 0) {
- m_topRight.setWidth(max<int>(0, m_topRight.width() + rightWidth));
- m_topRight.setHeight(max<int>(0, m_topRight.height() + topWidth));
- }
- if (m_bottomLeft.width() > 0 && m_bottomLeft.height() > 0) {
- m_bottomLeft.setWidth(max<int>(0, m_bottomLeft.width() + leftWidth));
- m_bottomLeft.setHeight(max<int>(0, m_bottomLeft.height() + bottomWidth));
- }
- if (m_bottomRight.width() > 0 && m_bottomRight.height() > 0) {
- m_bottomRight.setWidth(max<int>(0, m_bottomRight.width() + rightWidth));
- m_bottomRight.setHeight(max<int>(0, m_bottomRight.height() + bottomWidth));
- }
-}
-
-void RoundedRect::inflateWithRadii(int size)
-{
- IntRect old = m_rect;
-
- m_rect.inflate(size);
- // Considering the inflation factor of shorter size to scale the radii seems appropriate here
- float factor;
- if (m_rect.width() < m_rect.height())
- factor = old.width() ? (float)m_rect.width() / old.width() : int(0);
- else
- factor = old.height() ? (float)m_rect.height() / old.height() : int(0);
-
- m_radii.scale(factor);
-}
-
-void RoundedRect::Radii::includeLogicalEdges(const RoundedRect::Radii& edges, bool isHorizontal, bool includeLogicalLeftEdge, bool includeLogicalRightEdge)
-{
- if (includeLogicalLeftEdge) {
- if (isHorizontal)
- m_bottomLeft = edges.bottomLeft();
- else
- m_topRight = edges.topRight();
- m_topLeft = edges.topLeft();
- }
-
- if (includeLogicalRightEdge) {
- if (isHorizontal)
- m_topRight = edges.topRight();
- else
- m_bottomLeft = edges.bottomLeft();
- m_bottomRight = edges.bottomRight();
- }
-}
-
-void RoundedRect::Radii::excludeLogicalEdges(bool isHorizontal, bool excludeLogicalLeftEdge, bool excludeLogicalRightEdge)
-{
- if (excludeLogicalLeftEdge) {
- if (isHorizontal)
- m_bottomLeft = IntSize();
- else
- m_topRight = IntSize();
- m_topLeft = IntSize();
- }
-
- if (excludeLogicalRightEdge) {
- if (isHorizontal)
- m_topRight = IntSize();
- else
- m_bottomLeft = IntSize();
- m_bottomRight = IntSize();
- }
-}
-
-RoundedRect::RoundedRect(int x, int y, int width, int height)
- : m_rect(x, y, width, height)
-{
-}
-
-RoundedRect::RoundedRect(const IntRect& rect, const Radii& radii)
- : m_rect(rect)
- , m_radii(radii)
-{
-}
-
-RoundedRect::RoundedRect(const IntRect& rect, const IntSize& topLeft, const IntSize& topRight, const IntSize& bottomLeft, const IntSize& bottomRight)
- : m_rect(rect)
- , m_radii(topLeft, topRight, bottomLeft, bottomRight)
-{
-}
-
-IntRect RoundedRect::radiusCenterRect() const
-{
- ASSERT(isRenderable());
- int minX = m_rect.x() + max(m_radii.topLeft().width(), m_radii.bottomLeft().width());
- int minY = m_rect.y() + max(m_radii.topLeft().height(), m_radii.topRight().height());
- int maxX = m_rect.maxX() - max(m_radii.topRight().width(), m_radii.bottomRight().width());
- int maxY = m_rect.maxY() - max(m_radii.bottomLeft().height(), m_radii.bottomRight().height());
- return IntRect(minX, minY, maxX - minX, maxY - minY);
-}
-
-void RoundedRect::includeLogicalEdges(const Radii& edges, bool isHorizontal, bool includeLogicalLeftEdge, bool includeLogicalRightEdge)
-{
- m_radii.includeLogicalEdges(edges, isHorizontal, includeLogicalLeftEdge, includeLogicalRightEdge);
-}
-
-void RoundedRect::excludeLogicalEdges(bool isHorizontal, bool excludeLogicalLeftEdge, bool excludeLogicalRightEdge)
-{
- m_radii.excludeLogicalEdges(isHorizontal, excludeLogicalLeftEdge, excludeLogicalRightEdge);
-}
-
-bool RoundedRect::isRenderable() const
-{
- return m_radii.topLeft().width() + m_radii.topRight().width() <= m_rect.width()
- && m_radii.bottomLeft().width() + m_radii.bottomRight().width() <= m_rect.width()
- && m_radii.topLeft().height() + m_radii.bottomLeft().height() <= m_rect.height()
- && m_radii.topRight().height() + m_radii.bottomRight().height() <= m_rect.height();
-}
-
-void RoundedRect::adjustRadii()
-{
- int maxRadiusWidth = std::max(m_radii.topLeft().width() + m_radii.topRight().width(), m_radii.bottomLeft().width() + m_radii.bottomRight().width());
- int maxRadiusHeight = std::max(m_radii.topLeft().height() + m_radii.bottomLeft().height(), m_radii.topRight().height() + m_radii.bottomRight().height());
-
- if (maxRadiusWidth <= 0 || maxRadiusHeight <= 0) {
- m_radii.scale(0.0f);
- return;
- }
- float widthRatio = static_cast<float>(m_rect.width()) / maxRadiusWidth;
- float heightRatio = static_cast<float>(m_rect.height()) / maxRadiusHeight;
- m_radii.scale(widthRatio < heightRatio ? widthRatio : heightRatio);
-}
-
-bool RoundedRect::intersectsQuad(const FloatQuad& quad) const
-{
- FloatRect rect(m_rect);
- if (!quad.intersectsRect(rect))
- return false;
-
- const IntSize& topLeft = m_radii.topLeft();
- if (!topLeft.isEmpty()) {
- FloatRect rect(m_rect.x(), m_rect.y(), topLeft.width(), topLeft.height());
- if (quad.intersectsRect(rect)) {
- FloatPoint center(m_rect.x() + topLeft.width(), m_rect.y() + topLeft.height());
- FloatSize size(topLeft.width(), topLeft.height());
- if (!quad.intersectsEllipse(center, size))
- return false;
- }
- }
-
- const IntSize& topRight = m_radii.topRight();
- if (!topRight.isEmpty()) {
- FloatRect rect(m_rect.maxX() - topRight.width(), m_rect.y(), topRight.width(), topRight.height());
- if (quad.intersectsRect(rect)) {
- FloatPoint center(m_rect.maxX() - topRight.width(), m_rect.y() + topRight.height());
- FloatSize size(topRight.width(), topRight.height());
- if (!quad.intersectsEllipse(center, size))
- return false;
- }
- }
-
- const IntSize& bottomLeft = m_radii.bottomLeft();
- if (!bottomLeft.isEmpty()) {
- FloatRect rect(m_rect.x(), m_rect.maxY() - bottomLeft.height(), bottomLeft.width(), bottomLeft.height());
- if (quad.intersectsRect(rect)) {
- FloatPoint center(m_rect.x() + bottomLeft.width(), m_rect.maxY() - bottomLeft.height());
- FloatSize size(bottomLeft.width(), bottomLeft.height());
- if (!quad.intersectsEllipse(center, size))
- return false;
- }
- }
-
- const IntSize& bottomRight = m_radii.bottomRight();
- if (!bottomRight.isEmpty()) {
- FloatRect rect(m_rect.maxX() - bottomRight.width(), m_rect.maxY() - bottomRight.height(), bottomRight.width(), bottomRight.height());
- if (quad.intersectsRect(rect)) {
- FloatPoint center(m_rect.maxX() - bottomRight.width(), m_rect.maxY() - bottomRight.height());
- FloatSize size(bottomRight.width(), bottomRight.height());
- if (!quad.intersectsEllipse(center, size))
- return false;
- }
- }
-
- return true;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/RoundedRect.h b/chromium/third_party/WebKit/Source/core/platform/graphics/RoundedRect.h
deleted file mode 100644
index 80c84f49c73..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/RoundedRect.h
+++ /dev/null
@@ -1,130 +0,0 @@
-/*
- * Copyright (C) 2003, 2006, 2009 Apple Inc. All rights reserved.
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef RoundedRect_h
-#define RoundedRect_h
-
-#include "core/platform/graphics/FloatQuad.h"
-#include "core/platform/graphics/IntRect.h"
-
-namespace WebCore {
-
-
-class RoundedRect {
-public:
- class Radii {
- public:
- Radii() {}
- Radii(const IntSize& topLeft, const IntSize& topRight, const IntSize& bottomLeft, const IntSize& bottomRight)
- : m_topLeft(topLeft)
- , m_topRight(topRight)
- , m_bottomLeft(bottomLeft)
- , m_bottomRight(bottomRight)
- {
- }
-
- void setTopLeft(const IntSize& size) { m_topLeft = size; }
- void setTopRight(const IntSize& size) { m_topRight = size; }
- void setBottomLeft(const IntSize& size) { m_bottomLeft = size; }
- void setBottomRight(const IntSize& size) { m_bottomRight = size; }
- const IntSize& topLeft() const { return m_topLeft; }
- const IntSize& topRight() const { return m_topRight; }
- const IntSize& bottomLeft() const { return m_bottomLeft; }
- const IntSize& bottomRight() const { return m_bottomRight; }
-
- bool isZero() const;
-
- void includeLogicalEdges(const Radii& edges, bool isHorizontal, bool includeLogicalLeftEdge, bool includeLogicalRightEdge);
- void excludeLogicalEdges(bool isHorizontal, bool excludeLogicalLeftEdge, bool excludeLogicalRightEdge);
-
- void scale(float factor);
- void expand(int topWidth, int bottomWidth, int leftWidth, int rightWidth);
- void expand(int size) { expand(size, size, size, size); }
- void shrink(int topWidth, int bottomWidth, int leftWidth, int rightWidth) { expand(-topWidth, -bottomWidth, -leftWidth, -rightWidth); }
- void shrink(int size) { shrink(size, size, size, size); }
-
- private:
- IntSize m_topLeft;
- IntSize m_topRight;
- IntSize m_bottomLeft;
- IntSize m_bottomRight;
- };
-
- explicit RoundedRect(const IntRect&, const Radii& = Radii());
- RoundedRect(int x, int y, int width, int height);
- RoundedRect(const IntRect&, const IntSize& topLeft, const IntSize& topRight, const IntSize& bottomLeft, const IntSize& bottomRight);
-
- const IntRect& rect() const { return m_rect; }
- const Radii& radii() const { return m_radii; }
- bool isRounded() const { return !m_radii.isZero(); }
- bool isEmpty() const { return m_rect.isEmpty(); }
-
- // Returns a quickly computed rect enclosed by the rounded rect.
- IntRect radiusCenterRect() const;
-
- void setRect(const IntRect& rect) { m_rect = rect; }
- void setRadii(const Radii& radii) { m_radii = radii; }
-
- void move(const IntSize& size) { m_rect.move(size); }
- void inflate(int size) { m_rect.inflate(size); }
- void inflateWithRadii(int size);
- void expandRadii(int size) { m_radii.expand(size); }
- void shrinkRadii(int size) { m_radii.shrink(size); }
-
- void includeLogicalEdges(const Radii& edges, bool isHorizontal, bool includeLogicalLeftEdge, bool includeLogicalRightEdge);
- void excludeLogicalEdges(bool isHorizontal, bool excludeLogicalLeftEdge, bool excludeLogicalRightEdge);
-
- bool isRenderable() const;
- void adjustRadii();
-
- // Tests whether the quad intersects any part of this rounded rectangle.
- // This only works for convex quads.
- bool intersectsQuad(const FloatQuad&) const;
-
-private:
- IntRect m_rect;
- Radii m_radii;
-};
-
-inline bool operator==(const RoundedRect::Radii& a, const RoundedRect::Radii& b)
-{
- return a.topLeft() == b.topLeft() && a.topRight() == b.topRight() && a.bottomLeft() == b.bottomLeft() && a.bottomRight() == b.bottomRight();
-}
-
-inline bool operator!=(const RoundedRect::Radii& a, const RoundedRect::Radii& b)
-{
- return !(a == b);
-}
-
-inline bool operator==(const RoundedRect& a, const RoundedRect& b)
-{
- return a.rect() == b.rect() && a.radii() == b.radii();
-}
-
-
-} // namespace WebCore
-
-#endif // RoundedRect_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/RoundedRectTest.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/RoundedRectTest.cpp
deleted file mode 100644
index 2bdccb8e96b..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/RoundedRectTest.cpp
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/RoundedRect.h"
-
-#include "core/platform/graphics/IntRect.h"
-
-#include <gtest/gtest.h>
-
-using namespace WebCore;
-
-namespace WebCore {
-
-// FIXME: Move this somewhere more generic.
-void PrintTo(const IntRect& rect, std::ostream* os)
-{
- *os << "IntRect("
- << rect.x() << ", "
- << rect.y() << ", "
- << rect.width() << ", "
- << rect.height() << ")";
-}
-
-} // namespace WebCore
-
-namespace {
-
-TEST(RoundedRectTest, RadiusCenterRectZeroRadius)
-{
- RoundedRect rr(100, 200, 300, 400);
- EXPECT_TRUE(rr.rect().contains(rr.radiusCenterRect()));
- EXPECT_EQ(IntRect(100, 200, 300, 400), rr.radiusCenterRect());
-}
-
-TEST(RoundedRectTest, RadiusCenterRectEqualRadius)
-{
- RoundedRect rr(IntRect(100, 200, 300, 400), IntSize(10, 10), IntSize(10, 10), IntSize(10, 10), IntSize(10, 10));
- EXPECT_TRUE(rr.rect().contains(rr.radiusCenterRect()));
- EXPECT_EQ(IntRect(110, 210, 280, 380), rr.radiusCenterRect());
-}
-
-TEST(RoundedRectTest, RadiusCenterRectUnequalRadius)
-{
- RoundedRect rr(IntRect(100, 200, 300, 400), IntSize(5, 5), IntSize(10, 10), IntSize(15, 15), IntSize(20, 20));
- EXPECT_TRUE(rr.rect().contains(rr.radiusCenterRect()));
- EXPECT_EQ(IntRect(115, 210, 265, 370), rr.radiusCenterRect());
-}
-
-TEST(RoundedRectTest, RadiusCenterRectElliptical)
-{
- RoundedRect rr(IntRect(100, 200, 300, 400), IntSize(20, 10), IntSize(20, 10), IntSize(10, 20), IntSize(10, 20));
- EXPECT_TRUE(rr.rect().contains(rr.radiusCenterRect()));
- EXPECT_EQ(IntRect(120, 210, 260, 370), rr.radiusCenterRect());
-}
-
-} // namespace
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/SVGGlyph.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/SVGGlyph.cpp
deleted file mode 100644
index 1acfbb1113a..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/SVGGlyph.cpp
+++ /dev/null
@@ -1,191 +0,0 @@
-/*
- * Copyright (C) 2007, 2008 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) Research In Motion Limited 2010-2011. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-
-#if ENABLE(SVG_FONTS)
-#include "core/platform/graphics/SVGGlyph.h"
-
-#include "wtf/unicode/Unicode.h"
-
-using namespace WTF::Unicode;
-
-namespace WebCore {
-
-// Helper functions to determine the arabic character forms (initial, medial, terminal, isolated)
-enum ArabicCharShapingMode {
- SNone = 0,
- SRight = 1,
- SDual = 2
-};
-
-static const ArabicCharShapingMode s_arabicCharShapingMode[222] = {
- SRight, SRight, SRight, SRight, SDual , SRight, SDual , SRight, SDual , SDual , SDual , SDual , SDual , SRight, /* 0x0622 - 0x062F */
- SRight, SRight, SRight, SDual , SDual , SDual , SDual , SDual , SDual , SDual , SDual , SNone , SNone , SNone , SNone , SNone , /* 0x0630 - 0x063F */
- SNone , SDual , SDual , SDual , SDual , SDual , SDual , SRight, SDual , SDual , SNone , SNone , SNone , SNone , SNone , SNone , /* 0x0640 - 0x064F */
- SNone , SNone , SNone , SNone , SNone , SNone , SNone , SNone , SNone , SNone , SNone , SNone , SNone , SNone , SNone , SNone , /* 0x0650 - 0x065F */
- SNone , SNone , SNone , SNone , SNone , SNone , SNone , SNone , SNone , SNone , SNone , SNone , SNone , SNone , SNone , SNone , /* 0x0660 - 0x066F */
- SNone , SRight, SRight, SRight, SNone , SRight, SRight, SRight, SDual , SDual , SDual , SDual , SDual , SDual , SDual , SDual , /* 0x0670 - 0x067F */
- SDual , SDual , SDual , SDual , SDual , SDual , SDual , SDual , SRight, SRight, SRight, SRight, SRight, SRight, SRight, SRight, /* 0x0680 - 0x068F */
- SRight, SRight, SRight, SRight, SRight, SRight, SRight, SRight, SRight, SRight, SDual , SDual , SDual , SDual , SDual , SDual , /* 0x0690 - 0x069F */
- SDual , SDual , SDual , SDual , SDual , SDual , SDual , SDual , SDual , SDual , SDual , SDual , SDual , SDual , SDual , SDual , /* 0x06A0 - 0x06AF */
- SDual , SDual , SDual , SDual , SDual , SDual , SDual , SDual , SDual , SDual , SDual , SDual , SDual , SDual , SDual , SDual , /* 0x06B0 - 0x06BF */
- SRight, SDual , SRight, SRight, SRight, SRight, SRight, SRight, SRight, SRight, SRight, SRight, SDual , SRight, SDual , SRight, /* 0x06C0 - 0x06CF */
- SDual , SDual , SRight, SRight, SNone , SNone , SNone , SNone , SNone , SNone , SNone , SNone , SNone , SNone , SNone , SNone , /* 0x06D0 - 0x06DF */
- SNone , SNone , SNone , SNone , SNone , SNone , SNone , SNone , SNone , SNone , SNone , SNone , SNone , SNone , SNone , SNone , /* 0x06E0 - 0x06EF */
- SNone , SNone , SNone , SNone , SNone , SNone , SNone , SNone , SNone , SNone , SDual , SDual , SDual , SNone , SNone , SNone /* 0x06F0 - 0x06FF */
-};
-
-static inline SVGGlyph::ArabicForm processArabicFormDetection(const UChar& curChar, bool& lastCharShapesRight, SVGGlyph::ArabicForm* prevForm)
-{
- SVGGlyph::ArabicForm curForm;
-
- ArabicCharShapingMode shapingMode = SNone;
- if (curChar >= 0x0622 && curChar <= 0x06FF)
- shapingMode = s_arabicCharShapingMode[curChar - 0x0622];
-
- // Use a simple state machine to identify the actual arabic form
- // It depends on the order of the arabic form enum:
- // enum ArabicForm { None = 0, Isolated, Terminal, Initial, Medial };
-
- if (lastCharShapesRight && shapingMode == SDual) {
- if (prevForm) {
- int correctedForm = (int) *prevForm + 1;
- ASSERT(correctedForm >= SVGGlyph::None && correctedForm <= SVGGlyph::Medial);
- *prevForm = static_cast<SVGGlyph::ArabicForm>(correctedForm);
- }
-
- curForm = SVGGlyph::Initial;
- } else
- curForm = shapingMode == SNone ? SVGGlyph::None : SVGGlyph::Isolated;
-
- lastCharShapesRight = shapingMode != SNone;
- return curForm;
-}
-
-Vector<SVGGlyph::ArabicForm> charactersWithArabicForm(const String& input, bool rtl)
-{
- Vector<SVGGlyph::ArabicForm> forms;
- unsigned length = input.length();
-
- bool containsArabic = false;
- for (unsigned i = 0; i < length; ++i) {
- if (isArabicChar(input[i])) {
- containsArabic = true;
- break;
- }
- }
-
- if (!containsArabic)
- return forms;
-
- bool lastCharShapesRight = false;
-
- // Start identifying arabic forms
- if (rtl) {
- for (int i = length - 1; i >= 0; --i)
- forms.prepend(processArabicFormDetection(input[i], lastCharShapesRight, forms.isEmpty() ? 0 : &forms.first()));
- } else {
- for (unsigned i = 0; i < length; ++i)
- forms.append(processArabicFormDetection(input[i], lastCharShapesRight, forms.isEmpty() ? 0 : &forms.last()));
- }
-
- return forms;
-}
-
-static inline bool isCompatibleArabicForm(const SVGGlyph& identifier, const Vector<SVGGlyph::ArabicForm>& chars, unsigned startPosition, unsigned endPosition)
-{
- if (chars.isEmpty())
- return true;
-
- Vector<SVGGlyph::ArabicForm>::const_iterator realEnd = chars.end();
- Vector<SVGGlyph::ArabicForm>::const_iterator it = chars.begin() + startPosition;
- if (it >= realEnd)
- return true;
-
- Vector<SVGGlyph::ArabicForm>::const_iterator end = chars.begin() + endPosition;
- if (end >= realEnd)
- end = realEnd;
-
- for (; it != end; ++it) {
- if (*it != static_cast<SVGGlyph::ArabicForm>(identifier.arabicForm) && *it != SVGGlyph::None)
- return false;
- }
-
- return true;
-}
-
-bool isCompatibleGlyph(const SVGGlyph& identifier, bool isVerticalText, const String& language,
- const Vector<SVGGlyph::ArabicForm>& chars, unsigned startPosition, unsigned endPosition)
-{
- bool valid = true;
-
- // Check wheter orientation if glyph fits within the request
- switch (identifier.orientation) {
- case SVGGlyph::Vertical:
- valid = isVerticalText;
- break;
- case SVGGlyph::Horizontal:
- valid = !isVerticalText;
- break;
- case SVGGlyph::Both:
- break;
- }
-
- if (!valid)
- return false;
-
- // Check wheter languages are compatible
- if (!identifier.languages.isEmpty()) {
- // This glyph exists only in certain languages, if we're not specifying a
- // language on the referencing element we're unable to use this glyph.
- if (language.isEmpty())
- return false;
-
- // Split subcode from language, if existant.
- String languagePrefix;
-
- size_t subCodeSeparator = language.find('-');
- if (subCodeSeparator != kNotFound)
- languagePrefix = language.left(subCodeSeparator);
-
- Vector<String>::const_iterator it = identifier.languages.begin();
- Vector<String>::const_iterator end = identifier.languages.end();
-
- bool found = false;
- for (; it != end; ++it) {
- const String& cur = *it;
- if (cur == language || cur == languagePrefix) {
- found = true;
- break;
- }
- }
-
- if (!found)
- return false;
- }
-
- // Check wheter arabic form is compatible
- return isCompatibleArabicForm(identifier, chars, startPosition, endPosition);
-}
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/SVGGlyph.h b/chromium/third_party/WebKit/Source/core/platform/graphics/SVGGlyph.h
deleted file mode 100644
index 740faae348f..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/SVGGlyph.h
+++ /dev/null
@@ -1,113 +0,0 @@
-/*
- * Copyright (C) 2007 Eric Seidel <eric@webkit.org>
- * Copyright (C) 2007 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2008 Rob Buis <buis@kde.org>
- * Copyright (C) Research In Motion Limited 2011. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#ifndef SVGGlyph_h
-#define SVGGlyph_h
-
-#if ENABLE(SVG_FONTS)
-#include "core/platform/graphics/Glyph.h"
-#include "core/platform/graphics/Path.h"
-
-#include <limits>
-#include "wtf/text/WTFString.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-// Describe a glyph from a SVG Font.
-struct SVGGlyph {
- enum Orientation {
- Vertical,
- Horizontal,
- Both
- };
-
- // SVG Font depends on exactly this order.
- enum ArabicForm {
- None = 0,
- Isolated,
- Terminal,
- Initial,
- Medial
- };
-
- SVGGlyph()
- : isPartOfLigature(false)
- , orientation(Both)
- , arabicForm(None)
- , priority(0)
- , tableEntry(0)
- , unicodeStringLength(0)
- , horizontalAdvanceX(0)
- , verticalOriginX(0)
- , verticalOriginY(0)
- , verticalAdvanceY(0)
- {
- }
-
- // Used to mark our float properties as "to be inherited from SVGFontData"
- static float inheritedValue()
- {
- static float s_inheritedValue = std::numeric_limits<float>::infinity();
- return s_inheritedValue;
- }
-
- bool operator==(const SVGGlyph& other) const
- {
- return isPartOfLigature == other.isPartOfLigature
- && orientation == other.orientation
- && arabicForm == other.arabicForm
- && tableEntry == other.tableEntry
- && unicodeStringLength == other.unicodeStringLength
- && glyphName == other.glyphName
- && horizontalAdvanceX == other.horizontalAdvanceX
- && verticalOriginX == other.verticalOriginX
- && verticalOriginY == other.verticalOriginY
- && verticalAdvanceY == other.verticalAdvanceY
- && languages == other.languages;
- }
-
- bool isPartOfLigature : 1;
-
- unsigned orientation : 2; // Orientation
- unsigned arabicForm : 3; // ArabicForm
- int priority;
- Glyph tableEntry;
- size_t unicodeStringLength;
- String glyphName;
-
- float horizontalAdvanceX;
- float verticalOriginX;
- float verticalOriginY;
- float verticalAdvanceY;
-
- Path pathData;
- Vector<String> languages;
-};
-
-Vector<SVGGlyph::ArabicForm> charactersWithArabicForm(const String& input, bool rtl);
-bool isCompatibleGlyph(const SVGGlyph&, bool isVerticalText, const String& language, const Vector<SVGGlyph::ArabicForm>&, unsigned startPosition, unsigned endPosition);
-
-} // namespace WebCore
-
-#endif // ENABLE(SVG_FONTS)
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/SegmentedFontData.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/SegmentedFontData.cpp
deleted file mode 100644
index 027208113f8..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/SegmentedFontData.cpp
+++ /dev/null
@@ -1,99 +0,0 @@
-/*
- * Copyright (C) 2008, 2009 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/SegmentedFontData.h"
-
-#include "core/platform/graphics/SimpleFontData.h"
-#include "wtf/Assertions.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-SegmentedFontData::~SegmentedFontData()
-{
- GlyphPageTreeNode::pruneTreeCustomFontData(this);
-}
-
-const SimpleFontData* SegmentedFontData::fontDataForCharacter(UChar32 c) const
-{
- Vector<FontDataRange>::const_iterator end = m_ranges.end();
- for (Vector<FontDataRange>::const_iterator it = m_ranges.begin(); it != end; ++it) {
- if (it->from() <= c && it->to() >= c)
- return it->fontData().get();
- }
- return m_ranges[0].fontData().get();
-}
-
-bool SegmentedFontData::containsCharacter(UChar32 c) const
-{
- Vector<FontDataRange>::const_iterator end = m_ranges.end();
- for (Vector<FontDataRange>::const_iterator it = m_ranges.begin(); it != end; ++it) {
- if (c >= it->from() && c <= it->to())
- return true;
- }
- return false;
-}
-
-bool SegmentedFontData::containsCharacters(const UChar* characters, int length) const
-{
- UChar32 c;
- for (int i = 0; i < length; ) {
- U16_NEXT(characters, i, length, c)
- if (!containsCharacter(c))
- return false;
- }
- return true;
-}
-
-bool SegmentedFontData::isCustomFont() const
-{
- // All segmented fonts are custom fonts.
- return true;
-}
-
-bool SegmentedFontData::isLoading() const
-{
- Vector<FontDataRange>::const_iterator end = m_ranges.end();
- for (Vector<FontDataRange>::const_iterator it = m_ranges.begin(); it != end; ++it) {
- if (it->fontData()->isLoading())
- return true;
- }
- return false;
-}
-
-bool SegmentedFontData::isSegmented() const
-{
- return true;
-}
-
-#ifndef NDEBUG
-String SegmentedFontData::description() const
-{
- return "[segmented font]";
-}
-#endif
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/SegmentedFontData.h b/chromium/third_party/WebKit/Source/core/platform/graphics/SegmentedFontData.h
deleted file mode 100644
index dda296079a7..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/SegmentedFontData.h
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
- * Copyright (C) 2008, 2009 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SegmentedFontData_h
-#define SegmentedFontData_h
-
-#include "core/platform/graphics/FontData.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-class SimpleFontData;
-
-struct FontDataRange {
- FontDataRange(UChar32 from, UChar32 to, PassRefPtr<SimpleFontData> fontData)
- : m_from(from)
- , m_to(to)
- , m_fontData(fontData)
- {
- }
-
- UChar32 from() const { return m_from; }
- UChar32 to() const { return m_to; }
- PassRefPtr<SimpleFontData> fontData() const { return m_fontData; }
-
-private:
- UChar32 m_from;
- UChar32 m_to;
- RefPtr<SimpleFontData> m_fontData;
-};
-
-class SegmentedFontData : public FontData {
-public:
- static PassRefPtr<SegmentedFontData> create() { return adoptRef(new SegmentedFontData); }
-
- virtual ~SegmentedFontData();
-
- void appendRange(const FontDataRange& range) { m_ranges.append(range); }
- unsigned numRanges() const { return m_ranges.size(); }
- const FontDataRange& rangeAt(unsigned i) const { return m_ranges[i]; }
-
-#ifndef NDEBUG
- virtual String description() const;
-#endif
-
-private:
- SegmentedFontData() { }
-
- virtual const SimpleFontData* fontDataForCharacter(UChar32) const;
- virtual bool containsCharacters(const UChar*, int length) const;
-
- virtual bool isCustomFont() const;
- virtual bool isLoading() const;
- virtual bool isSegmented() const;
-
- bool containsCharacter(UChar32) const;
-
- Vector<FontDataRange, 1> m_ranges;
-};
-
-inline SegmentedFontData* toSegmentedFontData(FontData* fontData)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!fontData || fontData->isSegmented());
- return static_cast<SegmentedFontData*>(fontData);
-}
-
-} // namespace WebCore
-
-#endif // SegmentedFontData_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/ShadowBlur.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/ShadowBlur.cpp
deleted file mode 100644
index aa0bf4c0fb9..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/ShadowBlur.cpp
+++ /dev/null
@@ -1,198 +0,0 @@
-/*
- * Copyright (C) 2011 Apple Inc. All rights reserved.
- * Copyright (C) 2010 Sencha, Inc. All rights reserved.
- * Copyright (C) 2010 Igalia S.L. All rights reserved.
- * Copyright (C) Research In Motion Limited 2011. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/ShadowBlur.h"
-
-#include "wtf/MathExtras.h"
-#include <algorithm>
-
-using namespace std;
-
-namespace WebCore {
-
-enum {
- leftLobe = 0,
- rightLobe = 1
-};
-
-ShadowBlur::ShadowBlur(const FloatSize& radius, const FloatSize& offset, const Color& color)
- : m_color(color)
- , m_blurRadius(radius)
- , m_offset(offset)
- , m_shadowsIgnoreTransforms(false)
-{
- updateShadowBlurValues();
-}
-
-void ShadowBlur::updateShadowBlurValues()
-{
- // Limit blur radius to 128 to avoid lots of very expensive blurring.
- m_blurRadius = m_blurRadius.shrunkTo(FloatSize(128, 128));
-
- // The type of shadow is decided by the blur radius, shadow offset, and shadow color.
- if (!m_color.isValid() || !m_color.alpha()) {
- // Can't paint the shadow with invalid or invisible color.
- m_type = NoShadow;
- } else if (m_blurRadius.width() > 0 || m_blurRadius.height() > 0) {
- // Shadow is always blurred, even the offset is zero.
- m_type = BlurShadow;
- } else if (!m_offset.width() && !m_offset.height()) {
- // Without blur and zero offset means the shadow is fully hidden.
- m_type = NoShadow;
- } else
- m_type = SolidShadow;
-}
-
-// Instead of integer division, we use 17.15 for fixed-point division.
-static const int blurSumShift = 15;
-
-// Takes a two dimensional array with three rows and two columns for the lobes.
-static void calculateLobes(int lobes[][2], float blurRadius, bool shadowsIgnoreTransforms)
-{
- int diameter;
- if (shadowsIgnoreTransforms)
- diameter = max(2, static_cast<int>(floorf((2 / 3.f) * blurRadius))); // Canvas shadow. FIXME: we should adjust the blur radius higher up.
- else {
- // http://dev.w3.org/csswg/css3-background/#box-shadow
- // Approximate a Gaussian blur with a standard deviation equal to half the blur radius,
- // which http://www.w3.org/TR/SVG/filters.html#feGaussianBlurElement tell us how to do.
- // However, shadows rendered according to that spec will extend a little further than m_blurRadius,
- // so we apply a fudge factor to bring the radius down slightly.
- float stdDev = blurRadius / 2;
- const float gaussianKernelFactor = 3 / 4.f * sqrtf(2 * piFloat);
- const float fudgeFactor = 0.88f;
- diameter = max(2, static_cast<int>(floorf(stdDev * gaussianKernelFactor * fudgeFactor + 0.5f)));
- }
-
- if (diameter & 1) {
- // if d is odd, use three box-blurs of size 'd', centered on the output pixel.
- int lobeSize = (diameter - 1) / 2;
- lobes[0][leftLobe] = lobeSize;
- lobes[0][rightLobe] = lobeSize;
- lobes[1][leftLobe] = lobeSize;
- lobes[1][rightLobe] = lobeSize;
- lobes[2][leftLobe] = lobeSize;
- lobes[2][rightLobe] = lobeSize;
- } else {
- // if d is even, two box-blurs of size 'd' (the first one centered on the pixel boundary
- // between the output pixel and the one to the left, the second one centered on the pixel
- // boundary between the output pixel and the one to the right) and one box blur of size 'd+1' centered on the output pixel
- int lobeSize = diameter / 2;
- lobes[0][leftLobe] = lobeSize;
- lobes[0][rightLobe] = lobeSize - 1;
- lobes[1][leftLobe] = lobeSize - 1;
- lobes[1][rightLobe] = lobeSize;
- lobes[2][leftLobe] = lobeSize;
- lobes[2][rightLobe] = lobeSize;
- }
-}
-
-void ShadowBlur::blurLayerImage(unsigned char* imageData, const IntSize& size, int rowStride)
-{
- const int channels[4] = { 3, 0, 1, 3 };
-
- int lobes[3][2]; // indexed by pass, and left/right lobe
- calculateLobes(lobes, m_blurRadius.width(), m_shadowsIgnoreTransforms);
-
- // First pass is horizontal.
- int stride = 4;
- int delta = rowStride;
- int final = size.height();
- int dim = size.width();
-
- // Two stages: horizontal and vertical
- for (int pass = 0; pass < 2; ++pass) {
- unsigned char* pixels = imageData;
-
- if (!pass && !m_blurRadius.width())
- final = 0; // Do no work if horizonal blur is zero.
-
- for (int j = 0; j < final; ++j, pixels += delta) {
- // For each step, we blur the alpha in a channel and store the result
- // in another channel for the subsequent step.
- // We use sliding window algorithm to accumulate the alpha values.
- // This is much more efficient than computing the sum of each pixels
- // covered by the box kernel size for each x.
- for (int step = 0; step < 3; ++step) {
- int side1 = lobes[step][leftLobe];
- int side2 = lobes[step][rightLobe];
- int pixelCount = side1 + 1 + side2;
- int invCount = ((1 << blurSumShift) + pixelCount - 1) / pixelCount;
- int ofs = 1 + side2;
- int alpha1 = pixels[channels[step]];
- int alpha2 = pixels[(dim - 1) * stride + channels[step]];
-
- unsigned char* ptr = pixels + channels[step + 1];
- unsigned char* prev = pixels + stride + channels[step];
- unsigned char* next = pixels + ofs * stride + channels[step];
-
- int i;
- int sum = side1 * alpha1 + alpha1;
- int limit = (dim < side2 + 1) ? dim : side2 + 1;
-
- for (i = 1; i < limit; ++i, prev += stride)
- sum += *prev;
-
- if (limit <= side2)
- sum += (side2 - limit + 1) * alpha2;
-
- limit = (side1 < dim) ? side1 : dim;
- for (i = 0; i < limit; ptr += stride, next += stride, ++i, ++ofs) {
- *ptr = (sum * invCount) >> blurSumShift;
- sum += ((ofs < dim) ? *next : alpha2) - alpha1;
- }
-
- prev = pixels + channels[step];
- for (; ofs < dim; ptr += stride, prev += stride, next += stride, ++i, ++ofs) {
- *ptr = (sum * invCount) >> blurSumShift;
- sum += (*next) - (*prev);
- }
-
- for (; i < dim; ptr += stride, prev += stride, ++i) {
- *ptr = (sum * invCount) >> blurSumShift;
- sum += alpha2 - (*prev);
- }
- }
- }
-
- // Last pass is vertical.
- stride = rowStride;
- delta = 4;
- final = size.width();
- dim = size.height();
-
- if (!m_blurRadius.height())
- break;
-
- if (m_blurRadius.width() != m_blurRadius.height())
- calculateLobes(lobes, m_blurRadius.height(), m_shadowsIgnoreTransforms);
- }
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/ShadowBlur.h b/chromium/third_party/WebKit/Source/core/platform/graphics/ShadowBlur.h
deleted file mode 100644
index eb94a05290b..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/ShadowBlur.h
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright (C) 2011 Apple Inc.
- * Copyright (C) 2010 Sencha, Inc.
- * Copyright (C) 2010 Igalia S.L.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ShadowBlur_h
-#define ShadowBlur_h
-
-#include "core/platform/graphics/Color.h"
-#include "core/platform/graphics/FloatSize.h"
-
-#include "wtf/Noncopyable.h"
-
-namespace WebCore {
-
-class ShadowBlur {
- WTF_MAKE_NONCOPYABLE(ShadowBlur);
-public:
- enum ShadowType {
- NoShadow,
- SolidShadow,
- BlurShadow
- };
-
- ShadowBlur(const FloatSize& radius, const FloatSize& offset, const Color&);
-
- void blurLayerImage(unsigned char*, const IntSize&, int stride);
-
-private:
- void updateShadowBlurValues();
-
- ShadowType m_type;
-
- Color m_color;
- FloatSize m_blurRadius;
- FloatSize m_offset;
-
- bool m_shadowsIgnoreTransforms;
-};
-
-} // namespace WebCore
-
-#endif // ShadowBlur_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/SimpleFontData.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/SimpleFontData.cpp
deleted file mode 100644
index 8dcc30f78a7..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/SimpleFontData.cpp
+++ /dev/null
@@ -1,279 +0,0 @@
-/*
- * Copyright (C) 2005, 2008, 2010 Apple Inc. All rights reserved.
- * Copyright (C) 2006 Alexey Proskuryakov
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/SimpleFontData.h"
-
-#include "core/css/CSSFontFaceSource.h"
-#include "core/platform/graphics/opentype/OpenTypeVerticalData.h"
-
-#include "wtf/MathExtras.h"
-#include "wtf/UnusedParam.h"
-
-using namespace std;
-
-namespace WebCore {
-
-const float smallCapsFontSizeMultiplier = 0.7f;
-const float emphasisMarkFontSizeMultiplier = 0.5f;
-
-SimpleFontData::SimpleFontData(const FontPlatformData& platformData, bool isCustomFont, bool isLoadingFallback, bool isTextOrientationFallback)
- : m_maxCharWidth(-1)
- , m_avgCharWidth(-1)
- , m_platformData(platformData)
- , m_treatAsFixedPitch(false)
- , m_isTextOrientationFallback(isTextOrientationFallback)
- , m_isBrokenIdeographFallback(false)
-#if ENABLE(OPENTYPE_VERTICAL)
- , m_verticalData(0)
-#endif
- , m_hasVerticalGlyphs(false)
- , m_customFontData(isCustomFont, isLoadingFallback)
-{
- platformInit();
- platformGlyphInit();
- platformCharWidthInit();
-#if ENABLE(OPENTYPE_VERTICAL)
- if (platformData.orientation() == Vertical && !isTextOrientationFallback) {
- m_verticalData = platformData.verticalData();
- m_hasVerticalGlyphs = m_verticalData.get() && m_verticalData->hasVerticalMetrics();
- }
-#endif
-}
-
-SimpleFontData::SimpleFontData(PassOwnPtr<AdditionalFontData> fontData, float fontSize, bool syntheticBold, bool syntheticItalic)
- : m_platformData(FontPlatformData(fontSize, syntheticBold, syntheticItalic))
- , m_fontData(fontData)
- , m_treatAsFixedPitch(false)
- , m_isTextOrientationFallback(false)
- , m_isBrokenIdeographFallback(false)
-#if ENABLE(OPENTYPE_VERTICAL)
- , m_verticalData(0)
-#endif
- , m_hasVerticalGlyphs(false)
- , m_customFontData(true, false)
-{
- m_fontData->initializeFontData(this, fontSize);
-}
-
-// Estimates of avgCharWidth and maxCharWidth for platforms that don't support accessing these values from the font.
-void SimpleFontData::initCharWidths()
-{
- GlyphPage* glyphPageZero = GlyphPageTreeNode::getRootChild(this, 0)->page();
-
- // Treat the width of a '0' as the avgCharWidth.
- if (m_avgCharWidth <= 0.f && glyphPageZero) {
- static const UChar32 digitZeroChar = '0';
- Glyph digitZeroGlyph = glyphPageZero->glyphForCharacter(digitZeroChar);
- if (digitZeroGlyph)
- m_avgCharWidth = widthForGlyph(digitZeroGlyph);
- }
-
- // If we can't retrieve the width of a '0', fall back to the x height.
- if (m_avgCharWidth <= 0.f)
- m_avgCharWidth = m_fontMetrics.xHeight();
-
- if (m_maxCharWidth <= 0.f)
- m_maxCharWidth = max(m_avgCharWidth, m_fontMetrics.floatAscent());
-}
-
-void SimpleFontData::platformGlyphInit()
-{
- GlyphPage* glyphPageZero = GlyphPageTreeNode::getRootChild(this, 0)->page();
- if (!glyphPageZero) {
- LOG_ERROR("Failed to get glyph page zero.");
- m_spaceGlyph = 0;
- m_spaceWidth = 0;
- m_zeroGlyph = 0;
- m_adjustedSpaceWidth = 0;
- determinePitch();
- m_zeroWidthSpaceGlyph = 0;
- m_missingGlyphData.fontData = this;
- m_missingGlyphData.glyph = 0;
- return;
- }
-
- m_zeroWidthSpaceGlyph = glyphPageZero->glyphForCharacter(0);
-
- // Nasty hack to determine if we should round or ceil space widths.
- // If the font is monospace or fake monospace we ceil to ensure that
- // every character and the space are the same width. Otherwise we round.
- m_spaceGlyph = glyphPageZero->glyphForCharacter(' ');
- float width = widthForGlyph(m_spaceGlyph);
- m_spaceWidth = width;
- m_zeroGlyph = glyphPageZero->glyphForCharacter('0');
- m_fontMetrics.setZeroWidth(widthForGlyph(m_zeroGlyph));
- determinePitch();
- m_adjustedSpaceWidth = m_treatAsFixedPitch ? ceilf(width) : roundf(width);
-
- // Force the glyph for ZERO WIDTH SPACE to have zero width, unless it is shared with SPACE.
- // Helvetica is an example of a non-zero width ZERO WIDTH SPACE glyph.
- // See <http://bugs.webkit.org/show_bug.cgi?id=13178>
- // Ask for the glyph for 0 to avoid paging in ZERO WIDTH SPACE. Control characters, including 0,
- // are mapped to the ZERO WIDTH SPACE glyph.
- if (m_zeroWidthSpaceGlyph == m_spaceGlyph) {
- m_zeroWidthSpaceGlyph = 0;
- LOG_ERROR("Font maps SPACE and ZERO WIDTH SPACE to the same glyph. Glyph width will not be overridden.");
- }
-
- m_missingGlyphData.fontData = this;
- m_missingGlyphData.glyph = 0;
-}
-
-SimpleFontData::~SimpleFontData()
-{
- if (!m_fontData)
- platformDestroy();
-
- if (isCustomFont())
- GlyphPageTreeNode::pruneTreeCustomFontData(this);
- else
- GlyphPageTreeNode::pruneTreeFontData(this);
-}
-
-const SimpleFontData* SimpleFontData::fontDataForCharacter(UChar32) const
-{
- return this;
-}
-
-Glyph SimpleFontData::glyphForCharacter(UChar32 character) const
-{
- GlyphPageTreeNode* node = GlyphPageTreeNode::getRootChild(this, character / GlyphPage::size);
- return node->page() ? node->page()->glyphAt(character % GlyphPage::size) : 0;
-}
-
-bool SimpleFontData::isSegmented() const
-{
- return false;
-}
-
-PassRefPtr<SimpleFontData> SimpleFontData::verticalRightOrientationFontData() const
-{
- if (!m_derivedFontData)
- m_derivedFontData = DerivedFontData::create(isCustomFont());
- if (!m_derivedFontData->verticalRightOrientation) {
- FontPlatformData verticalRightPlatformData(m_platformData);
- verticalRightPlatformData.setOrientation(Horizontal);
- m_derivedFontData->verticalRightOrientation = create(verticalRightPlatformData, isCustomFont(), false, true);
- }
- return m_derivedFontData->verticalRightOrientation;
-}
-
-PassRefPtr<SimpleFontData> SimpleFontData::uprightOrientationFontData() const
-{
- if (!m_derivedFontData)
- m_derivedFontData = DerivedFontData::create(isCustomFont());
- if (!m_derivedFontData->uprightOrientation)
- m_derivedFontData->uprightOrientation = create(m_platformData, isCustomFont(), false, true);
- return m_derivedFontData->uprightOrientation;
-}
-
-PassRefPtr<SimpleFontData> SimpleFontData::smallCapsFontData(const FontDescription& fontDescription) const
-{
- if (!m_derivedFontData)
- m_derivedFontData = DerivedFontData::create(isCustomFont());
- if (!m_derivedFontData->smallCaps)
- m_derivedFontData->smallCaps = createScaledFontData(fontDescription, smallCapsFontSizeMultiplier);
-
- return m_derivedFontData->smallCaps;
-}
-
-PassRefPtr<SimpleFontData> SimpleFontData::emphasisMarkFontData(const FontDescription& fontDescription) const
-{
- if (!m_derivedFontData)
- m_derivedFontData = DerivedFontData::create(isCustomFont());
- if (!m_derivedFontData->emphasisMark)
- m_derivedFontData->emphasisMark = createScaledFontData(fontDescription, emphasisMarkFontSizeMultiplier);
-
- return m_derivedFontData->emphasisMark;
-}
-
-PassRefPtr<SimpleFontData> SimpleFontData::brokenIdeographFontData() const
-{
- if (!m_derivedFontData)
- m_derivedFontData = DerivedFontData::create(isCustomFont());
- if (!m_derivedFontData->brokenIdeograph) {
- m_derivedFontData->brokenIdeograph = create(m_platformData, isCustomFont(), false);
- m_derivedFontData->brokenIdeograph->m_isBrokenIdeographFallback = true;
- }
- return m_derivedFontData->brokenIdeograph;
-}
-
-void SimpleFontData::beginLoadIfNeeded() const
-{
- if (!m_customFontData.isUsed && m_customFontData.isLoadingFallback && m_customFontData.fontFaceSource) {
- m_customFontData.isUsed = true;
- m_customFontData.fontFaceSource->beginLoadingFontSoon();
- }
-}
-
-#ifndef NDEBUG
-String SimpleFontData::description() const
-{
- if (isSVGFont())
- return "[SVG font]";
- if (isCustomFont())
- return "[custom font]";
-
- return platformData().description();
-}
-#endif
-
-PassOwnPtr<SimpleFontData::DerivedFontData> SimpleFontData::DerivedFontData::create(bool forCustomFont)
-{
- return adoptPtr(new DerivedFontData(forCustomFont));
-}
-
-SimpleFontData::DerivedFontData::~DerivedFontData()
-{
- if (!forCustomFont)
- return;
-
- if (smallCaps)
- GlyphPageTreeNode::pruneTreeCustomFontData(smallCaps.get());
- if (emphasisMark)
- GlyphPageTreeNode::pruneTreeCustomFontData(emphasisMark.get());
- if (brokenIdeograph)
- GlyphPageTreeNode::pruneTreeCustomFontData(brokenIdeograph.get());
- if (verticalRightOrientation)
- GlyphPageTreeNode::pruneTreeCustomFontData(verticalRightOrientation.get());
- if (uprightOrientation)
- GlyphPageTreeNode::pruneTreeCustomFontData(uprightOrientation.get());
-}
-
-PassRefPtr<SimpleFontData> SimpleFontData::createScaledFontData(const FontDescription& fontDescription, float scaleFactor) const
-{
- // FIXME: Support scaled fonts that used AdditionalFontData.
- if (m_fontData)
- return 0;
-
- return platformCreateScaledFontData(fontDescription, scaleFactor);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/SimpleFontData.h b/chromium/third_party/WebKit/Source/core/platform/graphics/SimpleFontData.h
deleted file mode 100644
index ebcf8ab2872..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/SimpleFontData.h
+++ /dev/null
@@ -1,338 +0,0 @@
-/*
- * This file is part of the internal font implementation.
- *
- * Copyright (C) 2006, 2008, 2010 Apple Inc. All rights reserved.
- * Copyright (C) 2007-2008 Torch Mobile, Inc.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#ifndef SimpleFontData_h
-#define SimpleFontData_h
-
-#include "core/platform/graphics/FloatRect.h"
-#include "core/platform/graphics/FontBaseline.h"
-#include "core/platform/graphics/FontData.h"
-#include "core/platform/graphics/FontMetrics.h"
-#include "core/platform/graphics/FontPlatformData.h"
-#include "core/platform/graphics/GlyphBuffer.h"
-#include "core/platform/graphics/GlyphMetricsMap.h"
-#include "core/platform/graphics/GlyphPageTreeNode.h"
-#if ENABLE(OPENTYPE_VERTICAL)
-#include "core/platform/graphics/opentype/OpenTypeVerticalData.h"
-#endif
-#include "core/platform/graphics/TypesettingFeatures.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/text/StringHash.h"
-#include "wtf/UnusedParam.h"
-
-#if OS(MACOSX)
-#include "wtf/RetainPtr.h"
-#endif
-
-namespace WebCore {
-
-class CSSFontFaceSource;
-class FontDescription;
-class SharedBuffer;
-struct WidthIterator;
-
-enum FontDataVariant { AutoVariant, NormalVariant, SmallCapsVariant, EmphasisMarkVariant, BrokenIdeographVariant };
-enum Pitch { UnknownPitch, FixedPitch, VariablePitch };
-
-class SimpleFontData : public FontData {
-public:
- class AdditionalFontData {
- WTF_MAKE_FAST_ALLOCATED;
- public:
- virtual ~AdditionalFontData() { }
-
- virtual void initializeFontData(SimpleFontData*, float fontSize) = 0;
- virtual float widthForSVGGlyph(Glyph, float fontSize) const = 0;
- virtual bool fillSVGGlyphPage(GlyphPage*, unsigned offset, unsigned length, UChar* buffer, unsigned bufferLength, const SimpleFontData*) const = 0;
- virtual bool applySVGGlyphSelection(WidthIterator&, GlyphData&, bool mirror, int currentCharacter, unsigned& advanceLength) const = 0;
- };
-
- // Used to create platform fonts.
- static PassRefPtr<SimpleFontData> create(const FontPlatformData& platformData, bool isCustomFont = false, bool isLoadingFallback = false, bool isTextOrientationFallback = false)
- {
- return adoptRef(new SimpleFontData(platformData, isCustomFont, isLoadingFallback, isTextOrientationFallback));
- }
-
- // Used to create SVG Fonts.
- static PassRefPtr<SimpleFontData> create(PassOwnPtr<AdditionalFontData> fontData, float fontSize, bool syntheticBold, bool syntheticItalic)
- {
- return adoptRef(new SimpleFontData(fontData, fontSize, syntheticBold, syntheticItalic));
- }
-
- virtual ~SimpleFontData();
-
- static const SimpleFontData* systemFallback() { return reinterpret_cast<const SimpleFontData*>(-1); }
-
- const FontPlatformData& platformData() const { return m_platformData; }
-#if ENABLE(OPENTYPE_VERTICAL)
- const OpenTypeVerticalData* verticalData() const { return m_verticalData.get(); }
-#endif
-
- PassRefPtr<SimpleFontData> smallCapsFontData(const FontDescription&) const;
- PassRefPtr<SimpleFontData> emphasisMarkFontData(const FontDescription&) const;
- PassRefPtr<SimpleFontData> brokenIdeographFontData() const;
-
- PassRefPtr<SimpleFontData> variantFontData(const FontDescription& description, FontDataVariant variant) const
- {
- switch (variant) {
- case SmallCapsVariant:
- return smallCapsFontData(description);
- case EmphasisMarkVariant:
- return emphasisMarkFontData(description);
- case BrokenIdeographVariant:
- return brokenIdeographFontData();
- case AutoVariant:
- case NormalVariant:
- break;
- }
- ASSERT_NOT_REACHED();
- return const_cast<SimpleFontData*>(this);
- }
-
- PassRefPtr<SimpleFontData> verticalRightOrientationFontData() const;
- PassRefPtr<SimpleFontData> uprightOrientationFontData() const;
-
- bool hasVerticalGlyphs() const { return m_hasVerticalGlyphs; }
- bool isTextOrientationFallback() const { return m_isTextOrientationFallback; }
-
- FontMetrics& fontMetrics() { return m_fontMetrics; }
- const FontMetrics& fontMetrics() const { return m_fontMetrics; }
- float sizePerUnit() const { return platformData().size() / (fontMetrics().unitsPerEm() ? fontMetrics().unitsPerEm() : 1); }
-
- float maxCharWidth() const { return m_maxCharWidth; }
- void setMaxCharWidth(float maxCharWidth) { m_maxCharWidth = maxCharWidth; }
-
- float avgCharWidth() const { return m_avgCharWidth; }
- void setAvgCharWidth(float avgCharWidth) { m_avgCharWidth = avgCharWidth; }
-
- FloatRect boundsForGlyph(Glyph) const;
- float widthForGlyph(Glyph glyph) const;
- FloatRect platformBoundsForGlyph(Glyph) const;
- float platformWidthForGlyph(Glyph) const;
-
- float spaceWidth() const { return m_spaceWidth; }
- float adjustedSpaceWidth() const { return m_adjustedSpaceWidth; }
- void setSpaceWidth(float spaceWidth) { m_spaceWidth = spaceWidth; }
-
-#if OS(MACOSX)
- float syntheticBoldOffset() const { return m_syntheticBoldOffset; }
-#endif
-
- Glyph spaceGlyph() const { return m_spaceGlyph; }
- void setSpaceGlyph(Glyph spaceGlyph) { m_spaceGlyph = spaceGlyph; }
- Glyph zeroWidthSpaceGlyph() const { return m_zeroWidthSpaceGlyph; }
- void setZeroWidthSpaceGlyph(Glyph spaceGlyph) { m_zeroWidthSpaceGlyph = spaceGlyph; }
- bool isZeroWidthSpaceGlyph(Glyph glyph) const { return glyph == m_zeroWidthSpaceGlyph && glyph; }
- Glyph zeroGlyph() const { return m_zeroGlyph; }
- void setZeroGlyph(Glyph zeroGlyph) { m_zeroGlyph = zeroGlyph; }
-
- virtual const SimpleFontData* fontDataForCharacter(UChar32) const;
- virtual bool containsCharacters(const UChar*, int length) const;
-
- Glyph glyphForCharacter(UChar32) const;
-
- void determinePitch();
- Pitch pitch() const { return m_treatAsFixedPitch ? FixedPitch : VariablePitch; }
-
- AdditionalFontData* fontData() const { return m_fontData.get(); }
- bool isSVGFont() const { return m_fontData; }
- bool isLoadingFallback() const { return m_customFontData.isLoadingFallback; }
-
- virtual bool isCustomFont() const { return m_customFontData.isCustomFont; }
- virtual bool isLoading() const { return m_customFontData.isLoadingFallback && m_customFontData.isUsed; }
- virtual bool isSegmented() const;
-
- const GlyphData& missingGlyphData() const { return m_missingGlyphData; }
- void setMissingGlyphData(const GlyphData& glyphData) { m_missingGlyphData = glyphData; }
-
- void beginLoadIfNeeded() const;
-
-#ifndef NDEBUG
- virtual String description() const;
-#endif
-
-#if OS(MACOSX)
- const SimpleFontData* getCompositeFontReferenceFontData(NSFont *key) const;
- NSFont* getNSFont() const { return m_platformData.font(); }
-#endif
-
-#if OS(MACOSX)
- CFDictionaryRef getCFStringAttributes(TypesettingFeatures, FontOrientation) const;
-#endif
-
-#if OS(MACOSX) || USE(HARFBUZZ)
- bool canRenderCombiningCharacterSequence(const UChar*, size_t) const;
-#endif
-
- bool applyTransforms(GlyphBufferGlyph* glyphs, GlyphBufferAdvance* advances, size_t glyphCount, TypesettingFeatures typesettingFeatures) const
- {
- UNUSED_PARAM(glyphs);
- UNUSED_PARAM(advances);
- UNUSED_PARAM(glyphCount);
- UNUSED_PARAM(typesettingFeatures);
- return false;
- }
-
- void setCSSFontFaceSource(CSSFontFaceSource* source) { m_customFontData.fontFaceSource = source; }
- void clearCSSFontFaceSource() { m_customFontData.fontFaceSource = 0; }
-
-private:
- SimpleFontData(const FontPlatformData&, bool isCustomFont = false, bool isLoadingFallback = false, bool isTextOrientationFallback = false);
-
- SimpleFontData(PassOwnPtr<AdditionalFontData> , float fontSize, bool syntheticBold, bool syntheticItalic);
-
- void platformInit();
- void platformGlyphInit();
- void platformCharWidthInit();
- void platformDestroy();
-
- void initCharWidths();
-
- PassRefPtr<SimpleFontData> createScaledFontData(const FontDescription&, float scaleFactor) const;
- PassRefPtr<SimpleFontData> platformCreateScaledFontData(const FontDescription&, float scaleFactor) const;
-
- FontMetrics m_fontMetrics;
- float m_maxCharWidth;
- float m_avgCharWidth;
-
- FontPlatformData m_platformData;
- OwnPtr<AdditionalFontData> m_fontData;
-
- mutable OwnPtr<GlyphMetricsMap<FloatRect> > m_glyphToBoundsMap;
- mutable GlyphMetricsMap<float> m_glyphToWidthMap;
-
- bool m_treatAsFixedPitch;
-
- bool m_isTextOrientationFallback;
- bool m_isBrokenIdeographFallback;
-#if ENABLE(OPENTYPE_VERTICAL)
- RefPtr<OpenTypeVerticalData> m_verticalData;
-#endif
- bool m_hasVerticalGlyphs;
-
- Glyph m_spaceGlyph;
- float m_spaceWidth;
- Glyph m_zeroGlyph;
- float m_adjustedSpaceWidth;
-
- Glyph m_zeroWidthSpaceGlyph;
-
- GlyphData m_missingGlyphData;
-
- struct DerivedFontData {
- static PassOwnPtr<DerivedFontData> create(bool forCustomFont);
- ~DerivedFontData();
-
- bool forCustomFont;
- RefPtr<SimpleFontData> smallCaps;
- RefPtr<SimpleFontData> emphasisMark;
- RefPtr<SimpleFontData> brokenIdeograph;
- RefPtr<SimpleFontData> verticalRightOrientation;
- RefPtr<SimpleFontData> uprightOrientation;
-#if OS(MACOSX)
- mutable RetainPtr<CFMutableDictionaryRef> compositeFontReferences;
-#endif
-
- private:
- DerivedFontData(bool custom)
- : forCustomFont(custom)
- {
- }
- };
-
- mutable OwnPtr<DerivedFontData> m_derivedFontData;
-
- struct CustomFontData {
- CustomFontData(bool isCustomFont, bool isLoadingFallback)
- : isCustomFont(isCustomFont)
- , isLoadingFallback(isLoadingFallback)
- , isUsed(false)
- , fontFaceSource(0)
- {
- }
- bool isCustomFont; // Whether or not we are custom font loaded via @font-face
- bool isLoadingFallback; // Whether or not this is a temporary font data for a custom font which is not yet loaded.
- mutable bool isUsed;
- CSSFontFaceSource* fontFaceSource;
- };
- CustomFontData m_customFontData;
-
-#if OS(MACOSX)
- float m_syntheticBoldOffset;
-
- mutable HashMap<unsigned, RetainPtr<CFDictionaryRef> > m_CFStringAttributes;
-#endif
-
-#if OS(MACOSX) || USE(HARFBUZZ)
- mutable OwnPtr<HashMap<String, bool> > m_combiningCharacterSequenceSupport;
-#endif
-};
-
-ALWAYS_INLINE FloatRect SimpleFontData::boundsForGlyph(Glyph glyph) const
-{
- if (isZeroWidthSpaceGlyph(glyph))
- return FloatRect();
-
- FloatRect bounds;
- if (m_glyphToBoundsMap) {
- bounds = m_glyphToBoundsMap->metricsForGlyph(glyph);
- if (bounds.width() != cGlyphSizeUnknown)
- return bounds;
- }
-
- bounds = platformBoundsForGlyph(glyph);
- if (!m_glyphToBoundsMap)
- m_glyphToBoundsMap = adoptPtr(new GlyphMetricsMap<FloatRect>);
- m_glyphToBoundsMap->setMetricsForGlyph(glyph, bounds);
- return bounds;
-}
-
-ALWAYS_INLINE float SimpleFontData::widthForGlyph(Glyph glyph) const
-{
- if (isZeroWidthSpaceGlyph(glyph))
- return 0;
-
- float width = m_glyphToWidthMap.metricsForGlyph(glyph);
- if (width != cGlyphSizeUnknown)
- return width;
-
- if (m_fontData)
- width = m_fontData->widthForSVGGlyph(glyph, m_platformData.size());
-#if ENABLE(OPENTYPE_VERTICAL)
- else if (m_verticalData)
-#if OS(MACOSX)
- width = m_verticalData->advanceHeight(this, glyph) + m_syntheticBoldOffset;
-#else
- width = m_verticalData->advanceHeight(this, glyph);
-#endif
-#endif
- else
- width = platformWidthForGlyph(glyph);
-
- m_glyphToWidthMap.setMetricsForGlyph(glyph, width);
- return width;
-}
-
-} // namespace WebCore
-#endif // SimpleFontData_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/SourceBufferPrivate.h b/chromium/third_party/WebKit/Source/core/platform/graphics/SourceBufferPrivate.h
deleted file mode 100644
index f3bf4a94449..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/SourceBufferPrivate.h
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-#ifndef SourceBufferPrivate_h
-#define SourceBufferPrivate_h
-
-#include "core/html/TimeRanges.h"
-
-namespace WebCore {
-
-class SourceBufferPrivate {
-public:
- SourceBufferPrivate() { }
- virtual ~SourceBufferPrivate() { }
-
- virtual PassRefPtr<TimeRanges> buffered() = 0;
- virtual void append(const unsigned char* data, unsigned length) = 0;
- virtual void abort() = 0;
- virtual void remove(double start, double end) = 0;
- virtual bool setTimestampOffset(double) = 0;
- virtual void setAppendWindowStart(double) = 0;
- virtual void setAppendWindowEnd(double) = 0;
- virtual void removedFromMediaSource() = 0;
-};
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/StringTruncator.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/StringTruncator.cpp
deleted file mode 100644
index 650db60dd59..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/StringTruncator.cpp
+++ /dev/null
@@ -1,207 +0,0 @@
-/*
- * Copyright (C) 2005, 2006, 2007 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/StringTruncator.h"
-
-#include "core/platform/graphics/Font.h"
-#include "core/platform/graphics/TextRun.h"
-#include "core/platform/text/TextBreakIterator.h"
-#include "wtf/Assertions.h"
-#include "wtf/unicode/CharacterNames.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-#define STRING_BUFFER_SIZE 2048
-
-typedef unsigned TruncationFunction(const String&, unsigned length, unsigned keepCount, UChar* buffer);
-
-static inline int textBreakAtOrPreceding(const NonSharedCharacterBreakIterator& it, int offset)
-{
- if (it.isBreak(offset))
- return offset;
-
- int result = it.preceding(offset);
- return result == TextBreakDone ? 0 : result;
-}
-
-static inline int boundedTextBreakFollowing(const NonSharedCharacterBreakIterator& it, int offset, int length)
-{
- int result = it.following(offset);
- return result == TextBreakDone ? length : result;
-}
-
-static unsigned centerTruncateToBuffer(const String& string, unsigned length, unsigned keepCount, UChar* buffer)
-{
- ASSERT(keepCount < length);
- ASSERT(keepCount < STRING_BUFFER_SIZE);
-
- unsigned omitStart = (keepCount + 1) / 2;
- NonSharedCharacterBreakIterator it(string);
- unsigned omitEnd = boundedTextBreakFollowing(it, omitStart + (length - keepCount) - 1, length);
- omitStart = textBreakAtOrPreceding(it, omitStart);
-
- unsigned truncatedLength = omitStart + 1 + (length - omitEnd);
- ASSERT(truncatedLength <= length);
-
- string.copyTo(buffer, 0, omitStart);
- buffer[omitStart] = horizontalEllipsis;
- string.copyTo(&buffer[omitStart + 1], omitEnd, length - omitEnd);
-
- return truncatedLength;
-}
-
-static unsigned rightTruncateToBuffer(const String& string, unsigned length, unsigned keepCount, UChar* buffer)
-{
- ASSERT(keepCount < length);
- ASSERT(keepCount < STRING_BUFFER_SIZE);
-
- NonSharedCharacterBreakIterator it(string);
- unsigned keepLength = textBreakAtOrPreceding(it, keepCount);
- unsigned truncatedLength = keepLength + 1;
-
- string.copyTo(buffer, 0, keepLength);
- buffer[keepLength] = horizontalEllipsis;
-
- return truncatedLength;
-}
-
-static float stringWidth(const Font& renderer, const String& string, bool disableRoundingHacks)
-{
- TextRun run(string);
- if (disableRoundingHacks)
- run.disableRoundingHacks();
- return renderer.width(run);
-}
-
-static float stringWidth(const Font& renderer, const UChar* characters, unsigned length, bool disableRoundingHacks)
-{
- TextRun run(characters, length);
- if (disableRoundingHacks)
- run.disableRoundingHacks();
- return renderer.width(run);
-}
-
-static String truncateString(const String& string, float maxWidth, const Font& font, TruncationFunction truncateToBuffer, bool disableRoundingHacks)
-{
- if (string.isEmpty())
- return string;
-
- ASSERT(maxWidth >= 0);
-
- float currentEllipsisWidth = stringWidth(font, &horizontalEllipsis, 1, disableRoundingHacks);
-
- UChar stringBuffer[STRING_BUFFER_SIZE];
- unsigned truncatedLength;
- unsigned keepCount;
- unsigned length = string.length();
-
- if (length > STRING_BUFFER_SIZE) {
- keepCount = STRING_BUFFER_SIZE - 1; // need 1 character for the ellipsis
- truncatedLength = centerTruncateToBuffer(string, length, keepCount, stringBuffer);
- } else {
- keepCount = length;
- string.copyTo(stringBuffer, 0, length);
- truncatedLength = length;
- }
-
- float width = stringWidth(font, stringBuffer, truncatedLength, disableRoundingHacks);
- if (width <= maxWidth)
- return string;
-
- unsigned keepCountForLargestKnownToFit = 0;
- float widthForLargestKnownToFit = currentEllipsisWidth;
-
- unsigned keepCountForSmallestKnownToNotFit = keepCount;
- float widthForSmallestKnownToNotFit = width;
-
- if (currentEllipsisWidth >= maxWidth) {
- keepCountForLargestKnownToFit = 1;
- keepCountForSmallestKnownToNotFit = 2;
- }
-
- while (keepCountForLargestKnownToFit + 1 < keepCountForSmallestKnownToNotFit) {
- ASSERT(widthForLargestKnownToFit <= maxWidth);
- ASSERT(widthForSmallestKnownToNotFit > maxWidth);
-
- float ratio = (keepCountForSmallestKnownToNotFit - keepCountForLargestKnownToFit)
- / (widthForSmallestKnownToNotFit - widthForLargestKnownToFit);
- keepCount = static_cast<unsigned>(maxWidth * ratio);
-
- if (keepCount <= keepCountForLargestKnownToFit) {
- keepCount = keepCountForLargestKnownToFit + 1;
- } else if (keepCount >= keepCountForSmallestKnownToNotFit) {
- keepCount = keepCountForSmallestKnownToNotFit - 1;
- }
-
- ASSERT(keepCount < length);
- ASSERT(keepCount > 0);
- ASSERT(keepCount < keepCountForSmallestKnownToNotFit);
- ASSERT(keepCount > keepCountForLargestKnownToFit);
-
- truncatedLength = truncateToBuffer(string, length, keepCount, stringBuffer);
-
- width = stringWidth(font, stringBuffer, truncatedLength, disableRoundingHacks);
- if (width <= maxWidth) {
- keepCountForLargestKnownToFit = keepCount;
- widthForLargestKnownToFit = width;
- } else {
- keepCountForSmallestKnownToNotFit = keepCount;
- widthForSmallestKnownToNotFit = width;
- }
- }
-
- if (keepCountForLargestKnownToFit == 0) {
- keepCountForLargestKnownToFit = 1;
- }
-
- if (keepCount != keepCountForLargestKnownToFit) {
- keepCount = keepCountForLargestKnownToFit;
- truncatedLength = truncateToBuffer(string, length, keepCount, stringBuffer);
- }
-
- return String(stringBuffer, truncatedLength);
-}
-
-String StringTruncator::centerTruncate(const String& string, float maxWidth, const Font& font, EnableRoundingHacksOrNot enableRoundingHacks)
-{
- return truncateString(string, maxWidth, font, centerTruncateToBuffer, !enableRoundingHacks);
-}
-
-String StringTruncator::rightTruncate(const String& string, float maxWidth, const Font& font, EnableRoundingHacksOrNot enableRoundingHacks)
-{
- return truncateString(string, maxWidth, font, rightTruncateToBuffer, !enableRoundingHacks);
-}
-
-float StringTruncator::width(const String& string, const Font& font, EnableRoundingHacksOrNot enableRoundingHacks)
-{
- return stringWidth(font, string, !enableRoundingHacks);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/StringTruncator.h b/chromium/third_party/WebKit/Source/core/platform/graphics/StringTruncator.h
deleted file mode 100644
index 093be308fcd..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/StringTruncator.h
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright (C) 2005, 2006, 2007 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef StringTruncator_h
-#define StringTruncator_h
-
-#include "wtf/Forward.h"
-
-namespace WebCore {
-
-class Font;
-
-class StringTruncator {
-public:
- enum EnableRoundingHacksOrNot { DisableRoundingHacks, EnableRoundingHacks };
-
- static String centerTruncate(const String&, float maxWidth, const Font&, EnableRoundingHacksOrNot = DisableRoundingHacks);
- static String rightTruncate(const String&, float maxWidth, const Font&, EnableRoundingHacksOrNot = DisableRoundingHacks);
- static float width(const String&, const Font&, EnableRoundingHacksOrNot = DisableRoundingHacks);
-};
-
-} // namespace WebCore
-
-#endif // !defined(StringTruncator_h)
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/StrokeData.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/StrokeData.cpp
deleted file mode 100644
index 039df5e7831..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/StrokeData.cpp
+++ /dev/null
@@ -1,111 +0,0 @@
-// Copyright (C) 2013 Google Inc. All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-#include "config.h"
-#include "core/platform/graphics/StrokeData.h"
-#include "wtf/OwnArrayPtr.h"
-#include "wtf/PassOwnArrayPtr.h"
-
-namespace WebCore {
-
-static const int dashRatio = 3; // Ratio of the length of a dash to its width.
-
-void StrokeData::setLineDash(const DashArray& dashes, float dashOffset)
-{
- // FIXME: This is lifted directly off SkiaSupport, lines 49-74
- // so it is not guaranteed to work correctly.
- size_t dashLength = dashes.size();
- if (!dashLength) {
- // If no dash is set, revert to solid stroke
- // FIXME: do we need to set NoStroke in some cases?
- m_style = SolidStroke;
- m_dash.clear();
- return;
- }
-
- size_t count = !(dashLength % 2) ? dashLength : dashLength * 2;
- OwnArrayPtr<SkScalar> intervals = adoptArrayPtr(new SkScalar[count]);
-
- for (unsigned i = 0; i < count; i++)
- intervals[i] = dashes[i % dashLength];
-
- m_dash = adoptRef(new SkDashPathEffect(intervals.get(), count, dashOffset));
-}
-
-float StrokeData::setupPaint(SkPaint* paint, int length) const
-{
- float width = m_thickness;
-
- paint->setStyle(SkPaint::kStroke_Style);
- paint->setStrokeWidth(SkFloatToScalar(width));
- paint->setStrokeCap(m_lineCap);
- paint->setStrokeJoin(m_lineJoin);
- paint->setStrokeMiter(SkFloatToScalar(m_miterLimit));
-
- if (m_dash) {
- paint->setPathEffect(m_dash.get());
- } else {
- switch (m_style) {
- case NoStroke:
- case SolidStroke:
- case DoubleStroke:
- case WavyStroke: // FIXME: https://code.google.com/p/chromium/issues/detail?id=229574
- break;
- case DashedStroke:
- width = dashRatio * width;
- // Fall through.
- case DottedStroke:
- // Truncate the width, since we don't want fuzzy dots or dashes.
- int dashLength = static_cast<int>(width);
- // Subtract off the endcaps, since they're rendered separately.
- int distance = length - 2 * static_cast<int>(m_thickness);
- int phase = 1;
- if (dashLength > 1) {
- // Determine how many dashes or dots we should have.
- int numDashes = distance / dashLength;
- int remainder = distance % dashLength;
- // Adjust the phase to center the dashes within the line.
- if (numDashes % 2) {
- // Odd: shift right a full dash, minus half the remainder.
- phase = dashLength - remainder / 2;
- } else {
- // Even: shift right half a dash, minus half the remainder.
- phase = (dashLength - remainder) / 2;
- }
- }
- SkScalar dashLengthSk = SkIntToScalar(dashLength);
- SkScalar intervals[2] = { dashLengthSk, dashLengthSk };
- RefPtr<SkDashPathEffect> pathEffect = adoptRef(new SkDashPathEffect(intervals, 2, SkIntToScalar(phase)));
- paint->setPathEffect(pathEffect.get());
- }
- }
-
- return width;
-}
-
-} // namespace
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/StrokeData.h b/chromium/third_party/WebKit/Source/core/platform/graphics/StrokeData.h
deleted file mode 100644
index e5904e084e6..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/StrokeData.h
+++ /dev/null
@@ -1,108 +0,0 @@
-// Copyright (C) 2013 Google Inc. All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-#ifndef StrokeData_h
-#define StrokeData_h
-
-#include "core/platform/graphics/DashArray.h"
-#include "core/platform/graphics/Gradient.h"
-#include "core/platform/graphics/GraphicsTypes.h"
-#include "core/platform/graphics/Pattern.h"
-
-#include "third_party/skia/include/core/SkColorPriv.h"
-#include "third_party/skia/include/effects/SkDashPathEffect.h"
-
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefPtr.h"
-
-namespace WebCore {
-
-// Encapsulates stroke painting information.
-// It is pulled out of GraphicsContextState to enable other methods to use it.
-class StrokeData {
-public:
- StrokeData()
- : m_style(SolidStroke)
- , m_thickness(0)
- , m_color(Color::black)
- , m_lineCap(SkPaint::kDefault_Cap)
- , m_lineJoin(SkPaint::kDefault_Join)
- , m_miterLimit(4)
- {
- }
-
- StrokeStyle style() const { return m_style; }
- void setStyle(const StrokeStyle style) { m_style = style; }
-
- float thickness() const { return m_thickness; }
- void setThickness(const float thickness) { m_thickness = thickness; }
-
- Color color() const { return m_color; }
- void setColor(const Color& color) { m_color = color; }
-
- Gradient* gradient() const { return m_gradient.get(); }
- void setGradient(const PassRefPtr<Gradient> gradient) { m_gradient = gradient; }
- void clearGradient() { m_gradient.clear(); }
-
- Pattern* pattern() const { return m_pattern.get(); }
- void setPattern(const PassRefPtr<Pattern> pattern) { m_pattern = pattern; }
- void clearPattern() { m_pattern.clear(); }
-
- LineCap lineCap() const { return (LineCap)m_lineCap; }
- void setLineCap(const LineCap cap) { m_lineCap = (SkPaint::Cap)cap; }
-
- LineJoin lineJoin() const { return (LineJoin)m_lineJoin; }
- void setLineJoin(const LineJoin join) { m_lineJoin = (SkPaint::Join)join; }
-
- float miterLimit() const { return m_miterLimit; }
- void setMiterLimit(const float miterLimit) { m_miterLimit = miterLimit; }
-
- void setLineDash(const DashArray&, const float);
-
- // Sets everything on the paint except the pattern, gradient and color.
- // GraphicsContext::setupShader does that. Returns a float representing the
- // effective width of the pen. If a non-zero length is provided, the
- // number of dashes/dots on a dashed/dotted line will be adjusted to
- // start and end that length with a dash/dot.
- float setupPaint(SkPaint*, int length = 0) const;
-
-private:
- StrokeStyle m_style;
- float m_thickness;
- Color m_color;
- RefPtr<Gradient> m_gradient;
- RefPtr<Pattern> m_pattern;
- SkPaint::Cap m_lineCap;
- SkPaint::Join m_lineJoin;
- float m_miterLimit;
- RefPtr<SkDashPathEffect> m_dash;
-};
-
-} // namespace WebCore
-
-#endif // StrokeData_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/SurrogatePairAwareTextIterator.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/SurrogatePairAwareTextIterator.cpp
deleted file mode 100644
index 39524183b4a..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/SurrogatePairAwareTextIterator.cpp
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * Copyright (C) 2003, 2006, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
- * Copyright (C) 2008 Holger Hans Peter Freyther
- * Copyright (C) Research In Motion Limited 2011. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#include "config.h"
-#include "core/platform/graphics/SurrogatePairAwareTextIterator.h"
-
-#include <unicode/unorm.h>
-
-using namespace WTF;
-using namespace Unicode;
-
-namespace WebCore {
-
-SurrogatePairAwareTextIterator::SurrogatePairAwareTextIterator(const UChar* characters, int currentCharacter, int lastCharacter, int endCharacter)
- : m_characters(characters)
- , m_currentCharacter(currentCharacter)
- , m_lastCharacter(lastCharacter)
- , m_endCharacter(endCharacter)
-{
-}
-
-bool SurrogatePairAwareTextIterator::consumeSlowCase(UChar32& character, unsigned& clusterLength)
-{
- if (character <= 0x30FE) {
- // Deal with Hiragana and Katakana voiced and semi-voiced syllables.
- // Normalize into composed form, and then look for glyph with base + combined mark.
- // Check above for character range to minimize performance impact.
- if (UChar32 normalized = normalizeVoicingMarks()) {
- character = normalized;
- clusterLength = 2;
- }
- return true;
- }
-
- if (!U16_IS_SURROGATE(character))
- return true;
-
- // If we have a surrogate pair, make sure it starts with the high part.
- if (!U16_IS_SURROGATE_LEAD(character))
- return false;
-
- // Do we have a surrogate pair? If so, determine the full Unicode (32 bit) code point before glyph lookup.
- // Make sure we have another character and it's a low surrogate.
- if (m_currentCharacter + 1 >= m_endCharacter)
- return false;
-
- UChar low = m_characters[1];
- if (!U16_IS_TRAIL(low))
- return false;
-
- character = U16_GET_SUPPLEMENTARY(character, low);
- clusterLength = 2;
- return true;
-}
-
-UChar32 SurrogatePairAwareTextIterator::normalizeVoicingMarks()
-{
- // According to http://www.unicode.org/Public/UNIDATA/UCD.html#Canonical_Combining_Class_Values
- static const uint8_t hiraganaKatakanaVoicingMarksCombiningClass = 8;
-
- if (m_currentCharacter + 1 >= m_endCharacter)
- return 0;
-
- if (combiningClass(m_characters[1]) == hiraganaKatakanaVoicingMarksCombiningClass) {
- // Normalize into composed form using 3.2 rules.
- UChar normalizedCharacters[2] = { 0, 0 };
- UErrorCode uStatus = U_ZERO_ERROR;
- int32_t resultLength = unorm_normalize(m_characters, 2, UNORM_NFC, UNORM_UNICODE_3_2, &normalizedCharacters[0], 2, &uStatus);
- if (resultLength == 1 && !uStatus)
- return normalizedCharacters[0];
- }
-
- return 0;
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/SurrogatePairAwareTextIterator.h b/chromium/third_party/WebKit/Source/core/platform/graphics/SurrogatePairAwareTextIterator.h
deleted file mode 100644
index 7cf7340bdd2..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/SurrogatePairAwareTextIterator.h
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * Copyright (C) Research In Motion Limited 2011. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#ifndef SurrogatePairAwareTextIterator_h
-#define SurrogatePairAwareTextIterator_h
-
-#include "wtf/unicode/CharacterNames.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class SurrogatePairAwareTextIterator {
-public:
- // The passed in UChar pointer starts at 'currentCharacter'. The iterator operatoes on the range [currentCharacter, lastCharacter].
- // 'endCharacter' denotes the maximum length of the UChar array, which might exceed 'lastCharacter'.
- SurrogatePairAwareTextIterator(const UChar*, int currentCharacter, int lastCharacter, int endCharacter);
-
- inline bool consume(UChar32& character, unsigned& clusterLength)
- {
- if (m_currentCharacter >= m_lastCharacter)
- return false;
-
- character = *m_characters;
- clusterLength = 1;
-
- if (character < HiraganaLetterSmallA)
- return true;
-
- return consumeSlowCase(character, clusterLength);
- }
-
- void advance(unsigned advanceLength)
- {
- m_characters += advanceLength;
- m_currentCharacter += advanceLength;
- }
-
- int currentCharacter() const { return m_currentCharacter; }
- const UChar* characters() const { return m_characters; }
-
-private:
- bool consumeSlowCase(UChar32&, unsigned&);
- UChar32 normalizeVoicingMarks();
-
- const UChar* m_characters;
- int m_currentCharacter;
- int m_lastCharacter;
- int m_endCharacter;
-};
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/TextRenderingMode.h b/chromium/third_party/WebKit/Source/core/platform/graphics/TextRenderingMode.h
deleted file mode 100644
index 6c36b3aebb9..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/TextRenderingMode.h
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright (C) 2009 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TextRenderingMode_h
-#define TextRenderingMode_h
-
-namespace WebCore {
-
-enum TextRenderingMode { AutoTextRendering, OptimizeSpeed, OptimizeLegibility, GeometricPrecision };
-
-} // namespace WebCore
-
-#endif // TextRenderingMode_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/TextRun.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/TextRun.cpp
deleted file mode 100644
index 03b032b6e61..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/TextRun.cpp
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Copyright (C) 2011 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/TextRun.h"
-
-namespace WebCore {
-
-struct ExpectedTextRunSize {
- const void* pointer;
- int integers[2];
- float float1;
- float float2;
- float float3;
- uint32_t bitfields : 10;
- unsigned anUnsigned;
- RefPtr<TextRun::RenderingContext> renderingContext;
-};
-
-COMPILE_ASSERT(sizeof(TextRun) == sizeof(ExpectedTextRunSize), TextRun_is_not_of_expected_size);
-
-bool TextRun::s_allowsRoundingHacks = false;
-
-void TextRun::setAllowsRoundingHacks(bool allowsRoundingHacks)
-{
- s_allowsRoundingHacks = allowsRoundingHacks;
-}
-
-void TextRun::setText(const String& string)
-{
- m_len = string.length();
- if (!m_len) {
- m_data.characters8 = 0;
- m_is8Bit = true;
- return;
- }
- m_is8Bit = string.is8Bit();
- if (m_is8Bit)
- m_data.characters8 = string.characters8();
- else
- m_data.characters16 = string.characters16();
-}
-
-bool TextRun::allowsRoundingHacks()
-{
- return s_allowsRoundingHacks;
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/TextRun.h b/chromium/third_party/WebKit/Source/core/platform/graphics/TextRun.h
deleted file mode 100644
index 3f2836e7946..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/TextRun.h
+++ /dev/null
@@ -1,282 +0,0 @@
-/*
- * Copyright (C) 2000 Lars Knoll (knoll@kde.org)
- * (C) 2000 Antti Koivisto (koivisto@kde.org)
- * (C) 2000 Dirk Mueller (mueller@kde.org)
- * Copyright (C) 2003, 2006, 2007, 2011 Apple Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#ifndef TextRun_h
-#define TextRun_h
-
-#include "core/platform/graphics/FloatRect.h"
-#include "core/platform/text/TextDirection.h"
-#include "wtf/RefCounted.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class FloatPoint;
-class Font;
-class GraphicsContext;
-class GlyphBuffer;
-class SimpleFontData;
-struct GlyphData;
-struct WidthIterator;
-
-class TextRun {
- WTF_MAKE_FAST_ALLOCATED;
-public:
- enum ExpansionBehaviorFlags {
- ForbidTrailingExpansion = 0 << 0,
- AllowTrailingExpansion = 1 << 0,
- ForbidLeadingExpansion = 0 << 1,
- AllowLeadingExpansion = 1 << 1,
- };
-
- typedef unsigned ExpansionBehavior;
-
- enum RoundingHackFlags {
- NoRounding = 0,
- RunRounding = 1 << 0,
- WordRounding = 1 << 1,
- };
-
- typedef unsigned RoundingHacks;
-
- TextRun(const LChar* c, unsigned len, float xpos = 0, float expansion = 0, ExpansionBehavior expansionBehavior = AllowTrailingExpansion | ForbidLeadingExpansion, TextDirection direction = LTR, bool directionalOverride = false, bool characterScanForCodePath = true, RoundingHacks roundingHacks = RunRounding | WordRounding)
- : m_charactersLength(len)
- , m_len(len)
- , m_xpos(xpos)
- , m_horizontalGlyphStretch(1)
- , m_expansion(expansion)
- , m_expansionBehavior(expansionBehavior)
- , m_is8Bit(true)
- , m_allowTabs(false)
- , m_direction(direction)
- , m_directionalOverride(directionalOverride)
- , m_characterScanForCodePath(characterScanForCodePath)
- , m_applyRunRounding((roundingHacks & RunRounding) && s_allowsRoundingHacks)
- , m_applyWordRounding((roundingHacks & WordRounding) && s_allowsRoundingHacks)
- , m_disableSpacing(false)
- , m_tabSize(0)
- {
- m_data.characters8 = c;
- }
-
- TextRun(const UChar* c, unsigned len, float xpos = 0, float expansion = 0, ExpansionBehavior expansionBehavior = AllowTrailingExpansion | ForbidLeadingExpansion, TextDirection direction = LTR, bool directionalOverride = false, bool characterScanForCodePath = true, RoundingHacks roundingHacks = RunRounding | WordRounding)
- : m_charactersLength(len)
- , m_len(len)
- , m_xpos(xpos)
- , m_horizontalGlyphStretch(1)
- , m_expansion(expansion)
- , m_expansionBehavior(expansionBehavior)
- , m_is8Bit(false)
- , m_allowTabs(false)
- , m_direction(direction)
- , m_directionalOverride(directionalOverride)
- , m_characterScanForCodePath(characterScanForCodePath)
- , m_applyRunRounding((roundingHacks & RunRounding) && s_allowsRoundingHacks)
- , m_applyWordRounding((roundingHacks & WordRounding) && s_allowsRoundingHacks)
- , m_disableSpacing(false)
- , m_tabSize(0)
- {
- m_data.characters16 = c;
- }
-
- TextRun(const String& string, float xpos = 0, float expansion = 0, ExpansionBehavior expansionBehavior = AllowTrailingExpansion | ForbidLeadingExpansion, TextDirection direction = LTR, bool directionalOverride = false, bool characterScanForCodePath = true, RoundingHacks roundingHacks = RunRounding | WordRounding)
- : m_charactersLength(string.length())
- , m_len(string.length())
- , m_xpos(xpos)
- , m_horizontalGlyphStretch(1)
- , m_expansion(expansion)
- , m_expansionBehavior(expansionBehavior)
- , m_allowTabs(false)
- , m_direction(direction)
- , m_directionalOverride(directionalOverride)
- , m_characterScanForCodePath(characterScanForCodePath)
- , m_applyRunRounding((roundingHacks & RunRounding) && s_allowsRoundingHacks)
- , m_applyWordRounding((roundingHacks & WordRounding) && s_allowsRoundingHacks)
- , m_disableSpacing(false)
- , m_tabSize(0)
- {
- if (!m_charactersLength) {
- m_is8Bit = true;
- m_data.characters8 = 0;
- } else if (string.is8Bit()) {
- m_data.characters8 = string.characters8();
- m_is8Bit = true;
- } else {
- m_data.characters16 = string.characters16();
- m_is8Bit = false;
- }
- }
-
- TextRun(const StringView& string, float xpos = 0, float expansion = 0, ExpansionBehavior expansionBehavior = AllowTrailingExpansion | ForbidLeadingExpansion, TextDirection direction = LTR, bool directionalOverride = false, bool characterScanForCodePath = true, RoundingHacks roundingHacks = RunRounding | WordRounding)
- : m_charactersLength(string.length())
- , m_len(string.length())
- , m_xpos(xpos)
- , m_horizontalGlyphStretch(1)
- , m_expansion(expansion)
- , m_expansionBehavior(expansionBehavior)
- , m_allowTabs(false)
- , m_direction(direction)
- , m_directionalOverride(directionalOverride)
- , m_characterScanForCodePath(characterScanForCodePath)
- , m_applyRunRounding((roundingHacks & RunRounding) && s_allowsRoundingHacks)
- , m_applyWordRounding((roundingHacks & WordRounding) && s_allowsRoundingHacks)
- , m_disableSpacing(false)
- , m_tabSize(0)
- {
- if (!m_charactersLength) {
- m_is8Bit = true;
- m_data.characters8 = 0;
- } else if (string.is8Bit()) {
- m_data.characters8 = string.characters8();
- m_is8Bit = true;
- } else {
- m_data.characters16 = string.characters16();
- m_is8Bit = false;
- }
- }
-
- TextRun subRun(unsigned startOffset, unsigned length) const
- {
- ASSERT(startOffset < m_len);
-
- TextRun result = *this;
-
- if (is8Bit()) {
- result.setText(data8(startOffset), length);
- return result;
- }
- result.setText(data16(startOffset), length);
- return result;
- }
-
- UChar operator[](unsigned i) const { ASSERT_WITH_SECURITY_IMPLICATION(i < m_len); return is8Bit() ? m_data.characters8[i] :m_data.characters16[i]; }
- const LChar* data8(unsigned i) const { ASSERT_WITH_SECURITY_IMPLICATION(i < m_len); ASSERT(is8Bit()); return &m_data.characters8[i]; }
- const UChar* data16(unsigned i) const { ASSERT_WITH_SECURITY_IMPLICATION(i < m_len); ASSERT(!is8Bit()); return &m_data.characters16[i]; }
-
- const LChar* characters8() const { ASSERT(is8Bit()); return m_data.characters8; }
- const UChar* characters16() const { ASSERT(!is8Bit()); return m_data.characters16; }
-
- bool is8Bit() const { return m_is8Bit; }
- int length() const { return m_len; }
- int charactersLength() const { return m_charactersLength; }
-
- void setText(const LChar* c, unsigned len) { m_data.characters8 = c; m_len = len; m_is8Bit = true;}
- void setText(const UChar* c, unsigned len) { m_data.characters16 = c; m_len = len; m_is8Bit = false;}
- void setText(const String&);
- void setCharactersLength(unsigned charactersLength) { m_charactersLength = charactersLength; }
-
- float horizontalGlyphStretch() const { return m_horizontalGlyphStretch; }
- void setHorizontalGlyphStretch(float scale) { m_horizontalGlyphStretch = scale; }
-
- bool allowTabs() const { return m_allowTabs; }
- unsigned tabSize() const { return m_tabSize; }
- void setTabSize(bool, unsigned);
-
- float xPos() const { return m_xpos; }
- void setXPos(float xPos) { m_xpos = xPos; }
- float expansion() const { return m_expansion; }
- bool allowsLeadingExpansion() const { return m_expansionBehavior & AllowLeadingExpansion; }
- bool allowsTrailingExpansion() const { return m_expansionBehavior & AllowTrailingExpansion; }
- TextDirection direction() const { return static_cast<TextDirection>(m_direction); }
- bool rtl() const { return m_direction == RTL; }
- bool ltr() const { return m_direction == LTR; }
- bool directionalOverride() const { return m_directionalOverride; }
- bool characterScanForCodePath() const { return m_characterScanForCodePath; }
- bool applyRunRounding() const { return m_applyRunRounding; }
- bool applyWordRounding() const { return m_applyWordRounding; }
- bool spacingDisabled() const { return m_disableSpacing; }
-
- void disableSpacing() { m_disableSpacing = true; }
- void disableRoundingHacks() { m_applyRunRounding = m_applyWordRounding = false; }
- void setDirection(TextDirection direction) { m_direction = direction; }
- void setDirectionalOverride(bool override) { m_directionalOverride = override; }
- void setCharacterScanForCodePath(bool scan) { m_characterScanForCodePath = scan; }
-
- class RenderingContext : public RefCounted<RenderingContext> {
- public:
- virtual ~RenderingContext() { }
-
- virtual GlyphData glyphDataForCharacter(const Font&, const TextRun&, WidthIterator&, UChar32 character, bool mirror, int currentCharacter, unsigned& advanceLength) = 0;
- virtual void drawSVGGlyphs(GraphicsContext*, const TextRun&, const SimpleFontData*, const GlyphBuffer&, int from, int to, const FloatPoint&) const = 0;
- virtual float floatWidthUsingSVGFont(const Font&, const TextRun&, int& charsConsumed, String& glyphName) const = 0;
- };
-
- RenderingContext* renderingContext() const { return m_renderingContext.get(); }
- void setRenderingContext(PassRefPtr<RenderingContext> context) { m_renderingContext = context; }
-
- static void setAllowsRoundingHacks(bool);
- static bool allowsRoundingHacks();
-
-private:
- static bool s_allowsRoundingHacks;
-
- union {
- const LChar* characters8;
- const UChar* characters16;
- } m_data;
- unsigned m_charactersLength; // Marks the end of the characters buffer. Default equals to m_len.
- unsigned m_len;
-
- // m_xpos is the x position relative to the left start of the text line, not relative to the left
- // start of the containing block. In the case of right alignment or center alignment, left start of
- // the text line is not the same as left start of the containing block.
- float m_xpos;
- float m_horizontalGlyphStretch;
-
- float m_expansion;
- ExpansionBehavior m_expansionBehavior : 2;
- unsigned m_is8Bit : 1;
- unsigned m_allowTabs : 1;
- unsigned m_direction : 1;
- unsigned m_directionalOverride : 1; // Was this direction set by an override character.
- unsigned m_characterScanForCodePath : 1;
- unsigned m_applyRunRounding : 1;
- unsigned m_applyWordRounding : 1;
- unsigned m_disableSpacing : 1;
- unsigned m_tabSize;
- RefPtr<RenderingContext> m_renderingContext;
-};
-
-inline void TextRun::setTabSize(bool allow, unsigned size)
-{
- m_allowTabs = allow;
- m_tabSize = size;
-}
-
-// Container for parameters needed to paint TextRun.
-struct TextRunPaintInfo {
- explicit TextRunPaintInfo(const TextRun& r)
- : run(r)
- , from(0)
- , to(r.length())
- {
- }
-
- const TextRun& run;
- int from;
- int to;
- FloatRect bounds;
-};
-
-}
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/TextRunIterator.h b/chromium/third_party/WebKit/Source/core/platform/graphics/TextRunIterator.h
deleted file mode 100644
index 123885cb8c6..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/TextRunIterator.h
+++ /dev/null
@@ -1,77 +0,0 @@
-// Copyright (C) 2013 Google Inc. All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-#ifndef TextRunIterator_h
-#define TextRunIterator_h
-
-#include "core/platform/graphics/TextRun.h"
-
-namespace WebCore {
-
-class TextRunIterator {
-public:
- TextRunIterator()
- : m_textRun(0)
- , m_offset(0)
- {
- }
-
- TextRunIterator(const TextRun* textRun, unsigned offset)
- : m_textRun(textRun)
- , m_offset(offset)
- {
- }
-
- TextRunIterator(const TextRunIterator& other)
- : m_textRun(other.m_textRun)
- , m_offset(other.m_offset)
- {
- }
-
- unsigned offset() const { return m_offset; }
- void increment() { m_offset++; }
- bool atEnd() const { return !m_textRun || m_offset >= m_textRun->length(); }
- UChar current() const { return (*m_textRun)[m_offset]; }
- WTF::Unicode::Direction direction() const { return atEnd() ? WTF::Unicode::OtherNeutral : WTF::Unicode::direction(current()); }
-
- bool operator==(const TextRunIterator& other)
- {
- return m_offset == other.m_offset && m_textRun == other.m_textRun;
- }
-
- bool operator!=(const TextRunIterator& other) { return !operator==(other); }
-
-private:
- const TextRun* m_textRun;
- int m_offset;
-};
-
-
-} // namespace WebCore
-
-#endif // TextRunIterator_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/TypesettingFeatures.h b/chromium/third_party/WebKit/Source/core/platform/graphics/TypesettingFeatures.h
deleted file mode 100644
index 1dec5e4e0df..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/TypesettingFeatures.h
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright (C) 2010 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TypesettingFeatures_h
-#define TypesettingFeatures_h
-
-namespace WebCore {
-
-enum TypesettingFeature {
- Kerning = 1 << 0,
- Ligatures = 1 << 1,
-};
-
-typedef unsigned TypesettingFeatures;
-
-} // namespace WebCore
-
-#endif // TypesettingFeatures_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/UnitBezier.h b/chromium/third_party/WebKit/Source/core/platform/graphics/UnitBezier.h
deleted file mode 100644
index ad7c3a8cbd4..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/UnitBezier.h
+++ /dev/null
@@ -1,130 +0,0 @@
-/*
- * Copyright (C) 2008 Apple Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef UnitBezier_h
-#define UnitBezier_h
-
-#include "wtf/Assertions.h"
-#include <math.h>
-
-namespace WebCore {
-
-struct UnitBezier {
- UnitBezier(double p1x, double p1y, double p2x, double p2y)
- {
- // Calculate the polynomial coefficients, implicit first and last control points are (0,0) and (1,1).
- cx = 3.0 * p1x;
- bx = 3.0 * (p2x - p1x) - cx;
- ax = 1.0 - cx -bx;
-
- cy = 3.0 * p1y;
- by = 3.0 * (p2y - p1y) - cy;
- ay = 1.0 - cy - by;
- }
-
- double sampleCurveX(double t)
- {
- // `ax t^3 + bx t^2 + cx t' expanded using Horner's rule.
- return ((ax * t + bx) * t + cx) * t;
- }
-
- double sampleCurveY(double t)
- {
- return ((ay * t + by) * t + cy) * t;
- }
-
- double sampleCurveDerivativeX(double t)
- {
- return (3.0 * ax * t + 2.0 * bx) * t + cx;
- }
-
- // Given an x value, find a parametric value it came from.
- double solveCurveX(double x, double epsilon)
- {
- ASSERT(x >= 0.0);
- ASSERT(x <= 1.0);
-
- double t0;
- double t1;
- double t2;
- double x2;
- double d2;
- int i;
-
- // First try a few iterations of Newton's method -- normally very fast.
- for (t2 = x, i = 0; i < 8; i++) {
- x2 = sampleCurveX(t2) - x;
- if (fabs (x2) < epsilon)
- return t2;
- d2 = sampleCurveDerivativeX(t2);
- if (fabs(d2) < 1e-6)
- break;
- t2 = t2 - x2 / d2;
- }
-
- // Fall back to the bisection method for reliability.
- t0 = 0.0;
- t1 = 1.0;
- t2 = x;
-
- while (t0 < t1) {
- x2 = sampleCurveX(t2);
- if (fabs(x2 - x) < epsilon)
- return t2;
- if (x > x2)
- t0 = t2;
- else
- t1 = t2;
- t2 = (t1 - t0) * .5 + t0;
- }
-
- // Failure.
- return t2;
- }
-
- // Evaluates y at the given x. The epsilon parameter provides a hint as to the required
- // accuracy and is not guaranteed.
- double solve(double x, double epsilon)
- {
- if (x < 0.0)
- return 0.0;
- if (x > 1.0)
- return 1.0;
- return sampleCurveY(solveCurveX(x, epsilon));
- }
-
-private:
- double ax;
- double bx;
- double cx;
-
- double ay;
- double by;
- double cy;
-};
-
-} // namespace WebCore
-
-#endif // UnitBezier_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/UnitBezierTest.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/UnitBezierTest.cpp
deleted file mode 100644
index 2df0d68b692..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/UnitBezierTest.cpp
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/platform/graphics/UnitBezier.h"
-
-#include <gtest/gtest.h>
-
-using namespace WebCore;
-
-namespace {
-
-TEST(UnitBezierTest, BasicUse)
-{
- UnitBezier bezier(0.5, 1.0, 0.5, 1.0);
- EXPECT_EQ(0.875, bezier.solve(0.5, 0.005));
-}
-
-TEST(UnitBezierTest, Overshoot)
-{
- UnitBezier bezier(0.5, 2.0, 0.5, 2.0);
- EXPECT_EQ(1.625, bezier.solve(0.5, 0.005));
-}
-
-TEST(UnitBezierTest, Undershoot)
-{
- UnitBezier bezier(0.5, -1.0, 0.5, -1.0);
- EXPECT_EQ(-0.625, bezier.solve(0.5, 0.005));
-}
-
-TEST(UnitBezierTest, InputAtEdgeOfRange)
-{
- UnitBezier bezier(0.5, 1.0, 0.5, 1.0);
- EXPECT_EQ(0.0, bezier.solve(0.0, 0.005));
- EXPECT_EQ(1.0, bezier.solve(1.0, 0.005));
-}
-
-TEST(UnitBezierTest, InputOutOfRange)
-{
- UnitBezier bezier(0.5, 1.0, 0.5, 1.0);
- EXPECT_EQ(0.0, bezier.solve(-1.0, 0.005));
- EXPECT_EQ(1.0, bezier.solve(2.0, 0.005));
-}
-
-TEST(UnitBezierTest, InputOutOfRangeLargeEpsilon)
-{
- UnitBezier bezier(0.5, 1.0, 0.5, 1.0);
- EXPECT_EQ(0.0, bezier.solve(-1.0, 1.0));
- EXPECT_EQ(1.0, bezier.solve(2.0, 1.0));
-}
-
-} // namespace
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/WidthCache.h b/chromium/third_party/WebKit/Source/core/platform/graphics/WidthCache.h
deleted file mode 100644
index 65d72f4ea31..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/WidthCache.h
+++ /dev/null
@@ -1,216 +0,0 @@
-/*
- * Copyright (C) 2012 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef WidthCache_h
-#define WidthCache_h
-
-#include "core/platform/graphics/TextRun.h"
-#include "wtf/Forward.h"
-#include "wtf/HashFunctions.h"
-#include "wtf/HashSet.h"
-#include "wtf/HashTableDeletedValueType.h"
-#include "wtf/StringHasher.h"
-
-namespace WebCore {
-
-struct GlyphOverflow;
-
-class WidthCache {
-private:
- // Used to optimize small strings as hash table keys. Avoids malloc'ing an out-of-line StringImpl.
- class SmallStringKey {
- public:
- static unsigned capacity() { return s_capacity; }
-
- SmallStringKey()
- : m_length(s_emptyValueLength)
- {
- }
-
- SmallStringKey(WTF::HashTableDeletedValueType)
- : m_length(s_deletedValueLength)
- {
- }
-
- template<typename CharacterType> SmallStringKey(CharacterType* characters, unsigned short length)
- : m_length(length)
- {
- ASSERT(length <= s_capacity);
-
- StringHasher hasher;
-
- bool remainder = length & 1;
- length >>= 1;
-
- unsigned i = 0;
- while (length--) {
- m_characters[i] = characters[i];
- m_characters[i + 1] = characters[i + 1];
- hasher.addCharactersAssumingAligned(characters[i], characters[i + 1]);
- i += 2;
- }
-
- if (remainder) {
- m_characters[i] = characters[i];
- hasher.addCharacter(characters[i]);
- }
-
- m_hash = hasher.hash();
- }
-
- const UChar* characters() const { return m_characters; }
- unsigned short length() const { return m_length; }
- unsigned hash() const { return m_hash; }
-
- bool isHashTableDeletedValue() const { return m_length == s_deletedValueLength; }
- bool isHashTableEmptyValue() const { return m_length == s_emptyValueLength; }
-
- private:
- static const unsigned s_capacity = 15;
- static const unsigned s_emptyValueLength = s_capacity + 1;
- static const unsigned s_deletedValueLength = s_capacity + 2;
-
- unsigned m_hash;
- unsigned short m_length;
- UChar m_characters[s_capacity];
- };
-
- struct SmallStringKeyHash {
- static unsigned hash(const SmallStringKey& key) { return key.hash(); }
- static bool equal(const SmallStringKey& a, const SmallStringKey& b) { return a == b; }
- static const bool safeToCompareToEmptyOrDeleted = true; // Empty and deleted values have lengths that are not equal to any valid length.
- };
-
- struct SmallStringKeyHashTraits : WTF::SimpleClassHashTraits<SmallStringKey> {
- static const bool hasIsEmptyValueFunction = true;
- static bool isEmptyValue(const SmallStringKey& key) { return key.isHashTableEmptyValue(); }
- static const bool needsDestruction = false;
- static const int minimumTableSize = 16;
- };
-
- friend bool operator==(const SmallStringKey&, const SmallStringKey&);
-
-public:
- WidthCache()
- : m_interval(s_maxInterval)
- , m_countdown(m_interval)
- {
- }
-
- float* add(const TextRun& run, float entry, bool hasKerningOrLigatures, bool hasWordSpacingOrLetterSpacing, GlyphOverflow* glyphOverflow)
- {
- // The width cache is not really profitable unless we're doing expensive glyph transformations.
- if (!hasKerningOrLigatures)
- return 0;
- // Word spacing and letter spacing can change the width of a word.
- if (hasWordSpacingOrLetterSpacing)
- return 0;
- // Since this is just a width cache, we don't have enough information to satisfy glyph queries.
- if (glyphOverflow)
- return 0;
- // If we allow tabs and a tab occurs inside a word, the width of the word varies based on its position on the line.
- if (run.allowTabs())
- return 0;
- if (static_cast<unsigned>(run.length()) > SmallStringKey::capacity())
- return 0;
-
- if (m_countdown > 0) {
- --m_countdown;
- return 0;
- }
-
- return addSlowCase(run, entry);
- }
-
- void clear()
- {
- m_singleCharMap.clear();
- m_map.clear();
- }
-
-private:
- float* addSlowCase(const TextRun& run, float entry)
- {
- int length = run.length();
- bool isNewEntry;
- float *value;
- if (length == 1) {
- SingleCharMap::AddResult addResult = m_singleCharMap.add(run[0], entry);
- isNewEntry = addResult.isNewEntry;
- value = &addResult.iterator->value;
- } else {
- SmallStringKey smallStringKey;
- if (run.is8Bit())
- smallStringKey = SmallStringKey(run.characters8(), length);
- else
- smallStringKey = SmallStringKey(run.characters16(), length);
-
- Map::AddResult addResult = m_map.add(smallStringKey, entry);
- isNewEntry = addResult.isNewEntry;
- value = &addResult.iterator->value;
- }
-
- // Cache hit: ramp up by sampling the next few words.
- if (!isNewEntry) {
- m_interval = s_minInterval;
- return value;
- }
-
- // Cache miss: ramp down by increasing our sampling interval.
- if (m_interval < s_maxInterval)
- ++m_interval;
- m_countdown = m_interval;
-
- if ((m_singleCharMap.size() + m_map.size()) < s_maxSize)
- return value;
-
- // No need to be fancy: we're just trying to avoid pathological growth.
- m_singleCharMap.clear();
- m_map.clear();
- return 0;
- }
-
- typedef HashMap<SmallStringKey, float, SmallStringKeyHash, SmallStringKeyHashTraits> Map;
- typedef HashMap<uint32_t, float, DefaultHash<uint32_t>::Hash, WTF::UnsignedWithZeroKeyHashTraits<uint32_t> > SingleCharMap;
- static const int s_minInterval = -3; // A cache hit pays for about 3 cache misses.
- static const int s_maxInterval = 20; // Sampling at this interval has almost no overhead.
- static const int s_maxSize = 500000; // Just enough to guard against pathological growth.
-
- int m_interval;
- int m_countdown;
- SingleCharMap m_singleCharMap;
- Map m_map;
-};
-
-inline bool operator==(const WidthCache::SmallStringKey& a, const WidthCache::SmallStringKey& b)
-{
- if (a.length() != b.length())
- return false;
- return WTF::equal(a.characters(), b.characters(), a.length());
-}
-
-} // namespace WebCore
-
-#endif // WidthCache_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/WidthIterator.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/WidthIterator.cpp
deleted file mode 100644
index 4e41ebf524a..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/WidthIterator.cpp
+++ /dev/null
@@ -1,347 +0,0 @@
-/*
- * Copyright (C) 2003, 2006, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
- * Copyright (C) 2008 Holger Hans Peter Freyther
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#include "config.h"
-#include "core/platform/graphics/WidthIterator.h"
-
-#include "core/platform/graphics/Font.h"
-#include "core/platform/graphics/GlyphBuffer.h"
-#include "core/platform/graphics/Latin1TextIterator.h"
-#include "core/platform/graphics/SimpleFontData.h"
-#include "core/platform/graphics/SurrogatePairAwareTextIterator.h"
-#include "wtf/MathExtras.h"
-
-using namespace WTF;
-using namespace Unicode;
-using namespace std;
-
-namespace WebCore {
-
-WidthIterator::WidthIterator(const Font* font, const TextRun& run, HashSet<const SimpleFontData*>* fallbackFonts, bool accountForGlyphBounds, bool forTextEmphasis)
- : m_font(font)
- , m_run(run)
- , m_currentCharacter(0)
- , m_runWidthSoFar(0)
- , m_isAfterExpansion(!run.allowsLeadingExpansion())
- , m_finalRoundingWidth(0)
- , m_typesettingFeatures(font->typesettingFeatures())
- , m_fallbackFonts(fallbackFonts)
- , m_accountForGlyphBounds(accountForGlyphBounds)
- , m_maxGlyphBoundingBoxY(numeric_limits<float>::min())
- , m_minGlyphBoundingBoxY(numeric_limits<float>::max())
- , m_firstGlyphOverflow(0)
- , m_lastGlyphOverflow(0)
- , m_forTextEmphasis(forTextEmphasis)
-{
- // If the padding is non-zero, count the number of spaces in the run
- // and divide that by the padding for per space addition.
- m_expansion = m_run.expansion();
- if (!m_expansion)
- m_expansionPerOpportunity = 0;
- else {
- bool isAfterExpansion = m_isAfterExpansion;
- unsigned expansionOpportunityCount = m_run.is8Bit() ? Font::expansionOpportunityCount(m_run.characters8(), m_run.length(), m_run.ltr() ? LTR : RTL, isAfterExpansion) : Font::expansionOpportunityCount(m_run.characters16(), m_run.length(), m_run.ltr() ? LTR : RTL, isAfterExpansion);
- if (isAfterExpansion && !m_run.allowsTrailingExpansion())
- expansionOpportunityCount--;
-
- if (!expansionOpportunityCount)
- m_expansionPerOpportunity = 0;
- else
- m_expansionPerOpportunity = m_expansion / expansionOpportunityCount;
- }
-}
-
-GlyphData WidthIterator::glyphDataForCharacter(UChar32 character, bool mirror, int currentCharacter, unsigned& advanceLength)
-{
- ASSERT(m_font);
-
-#if ENABLE(SVG_FONTS)
- if (TextRun::RenderingContext* renderingContext = m_run.renderingContext())
- return renderingContext->glyphDataForCharacter(*m_font, m_run, *this, character, mirror, currentCharacter, advanceLength);
-#else
- UNUSED_PARAM(currentCharacter);
- UNUSED_PARAM(advanceLength);
-#endif
-
- return m_font->glyphDataForCharacter(character, mirror);
-}
-
-struct OriginalAdvancesForCharacterTreatedAsSpace {
-public:
- OriginalAdvancesForCharacterTreatedAsSpace(bool isSpace, float advanceBefore, float advanceAt)
- : characterIsSpace(isSpace)
- , advanceBeforeCharacter(advanceBefore)
- , advanceAtCharacter(advanceAt)
- {
- }
-
- bool characterIsSpace;
- float advanceBeforeCharacter;
- float advanceAtCharacter;
-};
-
-typedef Vector<pair<int, OriginalAdvancesForCharacterTreatedAsSpace>, 64> CharactersTreatedAsSpace;
-
-static inline float applyFontTransforms(GlyphBuffer* glyphBuffer, bool ltr, int& lastGlyphCount, const SimpleFontData* fontData, TypesettingFeatures typesettingFeatures, CharactersTreatedAsSpace& charactersTreatedAsSpace)
-{
- ASSERT(typesettingFeatures & (Kerning | Ligatures));
-
- if (!glyphBuffer)
- return 0;
-
- int glyphBufferSize = glyphBuffer->size();
- if (glyphBuffer->size() <= lastGlyphCount + 1)
- return 0;
-
- GlyphBufferAdvance* advances = glyphBuffer->advances(0);
- float widthDifference = 0;
- for (int i = lastGlyphCount; i < glyphBufferSize; ++i)
- widthDifference -= advances[i].width();
-
- if (!ltr)
- glyphBuffer->reverse(lastGlyphCount, glyphBufferSize - lastGlyphCount);
-
- fontData->applyTransforms(glyphBuffer->glyphs(lastGlyphCount), advances + lastGlyphCount, glyphBufferSize - lastGlyphCount, typesettingFeatures);
-
- if (!ltr)
- glyphBuffer->reverse(lastGlyphCount, glyphBufferSize - lastGlyphCount);
-
- for (size_t i = 0; i < charactersTreatedAsSpace.size(); ++i) {
- int spaceOffset = charactersTreatedAsSpace[i].first;
- const OriginalAdvancesForCharacterTreatedAsSpace& originalAdvances = charactersTreatedAsSpace[i].second;
- if (spaceOffset && !originalAdvances.characterIsSpace)
- glyphBuffer->advances(spaceOffset - 1)->setWidth(originalAdvances.advanceBeforeCharacter);
- glyphBuffer->advances(spaceOffset)->setWidth(originalAdvances.advanceAtCharacter);
- }
- charactersTreatedAsSpace.clear();
-
- for (int i = lastGlyphCount; i < glyphBufferSize; ++i)
- widthDifference += advances[i].width();
-
- lastGlyphCount = glyphBufferSize;
- return widthDifference;
-}
-
-template <typename TextIterator>
-inline unsigned WidthIterator::advanceInternal(TextIterator& textIterator, GlyphBuffer* glyphBuffer)
-{
- bool rtl = m_run.rtl();
- bool hasExtraSpacing = (m_font->letterSpacing() || m_font->wordSpacing() || m_expansion) && !m_run.spacingDisabled();
-
- float widthSinceLastRounding = m_runWidthSoFar;
- m_runWidthSoFar = floorf(m_runWidthSoFar);
- widthSinceLastRounding -= m_runWidthSoFar;
-
- float lastRoundingWidth = m_finalRoundingWidth;
- FloatRect bounds;
-
- const SimpleFontData* primaryFont = m_font->primaryFont();
- const SimpleFontData* lastFontData = primaryFont;
- int lastGlyphCount = glyphBuffer ? glyphBuffer->size() : 0;
-
- UChar32 character = 0;
- unsigned clusterLength = 0;
- CharactersTreatedAsSpace charactersTreatedAsSpace;
- while (textIterator.consume(character, clusterLength)) {
- unsigned advanceLength = clusterLength;
- const GlyphData& glyphData = glyphDataForCharacter(character, rtl, textIterator.currentCharacter(), advanceLength);
- Glyph glyph = glyphData.glyph;
- const SimpleFontData* fontData = glyphData.fontData;
-
- ASSERT(fontData);
-
- // Now that we have a glyph and font data, get its width.
- float width;
- if (character == '\t' && m_run.allowTabs())
- width = m_font->tabWidth(*fontData, m_run.tabSize(), m_run.xPos() + m_runWidthSoFar + widthSinceLastRounding);
- else {
- width = fontData->widthForGlyph(glyph);
-
- // SVG uses horizontalGlyphStretch(), when textLength is used to stretch/squeeze text.
- width *= m_run.horizontalGlyphStretch();
-
- // We special case spaces in two ways when applying word rounding.
- // First, we round spaces to an adjusted width in all fonts.
- // Second, in fixed-pitch fonts we ensure that all characters that
- // match the width of the space character have the same width as the space character.
- if (m_run.applyWordRounding() && width == fontData->spaceWidth() && (fontData->pitch() == FixedPitch || glyph == fontData->spaceGlyph()))
- width = fontData->adjustedSpaceWidth();
- }
-
- if (fontData != lastFontData && width) {
- if (shouldApplyFontTransforms())
- m_runWidthSoFar += applyFontTransforms(glyphBuffer, m_run.ltr(), lastGlyphCount, lastFontData, m_typesettingFeatures, charactersTreatedAsSpace);
-
- lastFontData = fontData;
- if (m_fallbackFonts && fontData != primaryFont) {
- // FIXME: This does a little extra work that could be avoided if
- // glyphDataForCharacter() returned whether it chose to use a small caps font.
- if (!m_font->isSmallCaps() || character == toUpper(character))
- m_fallbackFonts->add(fontData);
- else {
- const GlyphData& uppercaseGlyphData = m_font->glyphDataForCharacter(toUpper(character), rtl);
- if (uppercaseGlyphData.fontData != primaryFont)
- m_fallbackFonts->add(uppercaseGlyphData.fontData);
- }
- }
- }
-
- if (hasExtraSpacing) {
- // Account for letter-spacing.
- if (width && m_font->letterSpacing())
- width += m_font->letterSpacing();
-
- static bool expandAroundIdeographs = Font::canExpandAroundIdeographsInComplexText();
- bool treatAsSpace = Font::treatAsSpace(character);
- if (treatAsSpace || (expandAroundIdeographs && Font::isCJKIdeographOrSymbol(character))) {
- // Distribute the run's total expansion evenly over all expansion opportunities in the run.
- if (m_expansion) {
- float previousExpansion = m_expansion;
- if (!treatAsSpace && !m_isAfterExpansion) {
- // Take the expansion opportunity before this ideograph.
- m_expansion -= m_expansionPerOpportunity;
- float expansionAtThisOpportunity = !m_run.applyWordRounding() ? m_expansionPerOpportunity : roundf(previousExpansion) - roundf(m_expansion);
- m_runWidthSoFar += expansionAtThisOpportunity;
- if (glyphBuffer) {
- if (glyphBuffer->isEmpty()) {
- if (m_forTextEmphasis)
- glyphBuffer->add(fontData->zeroWidthSpaceGlyph(), fontData, m_expansionPerOpportunity);
- else
- glyphBuffer->add(fontData->spaceGlyph(), fontData, expansionAtThisOpportunity);
- } else
- glyphBuffer->expandLastAdvance(expansionAtThisOpportunity);
- }
- previousExpansion = m_expansion;
- }
- if (m_run.allowsTrailingExpansion() || (m_run.ltr() && textIterator.currentCharacter() + advanceLength < static_cast<size_t>(m_run.length()))
- || (m_run.rtl() && textIterator.currentCharacter())) {
- m_expansion -= m_expansionPerOpportunity;
- width += !m_run.applyWordRounding() ? m_expansionPerOpportunity : roundf(previousExpansion) - roundf(m_expansion);
- m_isAfterExpansion = true;
- }
- } else
- m_isAfterExpansion = false;
-
- // Account for word spacing.
- // We apply additional space between "words" by adding width to the space character.
- if (treatAsSpace && (character != '\t' || !m_run.allowTabs()) && (textIterator.currentCharacter() || character == noBreakSpace) && m_font->wordSpacing())
- width += m_font->wordSpacing();
- } else
- m_isAfterExpansion = false;
- }
-
- if (shouldApplyFontTransforms() && glyphBuffer && Font::treatAsSpace(character))
- charactersTreatedAsSpace.append(make_pair(glyphBuffer->size(),
- OriginalAdvancesForCharacterTreatedAsSpace(character == ' ', glyphBuffer->size() ? glyphBuffer->advanceAt(glyphBuffer->size() - 1) : 0, width)));
-
- if (m_accountForGlyphBounds) {
- bounds = fontData->boundsForGlyph(glyph);
- if (!textIterator.currentCharacter())
- m_firstGlyphOverflow = max<float>(0, -bounds.x());
- }
-
- if (m_forTextEmphasis && !Font::canReceiveTextEmphasis(character))
- glyph = 0;
-
- // Advance past the character we just dealt with.
- textIterator.advance(advanceLength);
-
- float oldWidth = width;
-
- // Force characters that are used to determine word boundaries for the rounding hack
- // to be integer width, so following words will start on an integer boundary.
- if (m_run.applyWordRounding() && Font::isRoundingHackCharacter(character)) {
- width = ceilf(width);
-
- // Since widthSinceLastRounding can lose precision if we include measurements for
- // preceding whitespace, we bypass it here.
- m_runWidthSoFar += width;
-
- // Since this is a rounding hack character, we should have reset this sum on the previous
- // iteration.
- ASSERT(!widthSinceLastRounding);
- } else {
- // Check to see if the next character is a "rounding hack character", if so, adjust
- // width so that the total run width will be on an integer boundary.
- if ((m_run.applyWordRounding() && textIterator.currentCharacter() < m_run.length() && Font::isRoundingHackCharacter(*(textIterator.characters())))
- || (m_run.applyRunRounding() && textIterator.currentCharacter() >= m_run.length())) {
- float totalWidth = widthSinceLastRounding + width;
- widthSinceLastRounding = ceilf(totalWidth);
- width += widthSinceLastRounding - totalWidth;
- m_runWidthSoFar += widthSinceLastRounding;
- widthSinceLastRounding = 0;
- } else
- widthSinceLastRounding += width;
- }
-
- if (glyphBuffer)
- glyphBuffer->add(glyph, fontData, (rtl ? oldWidth + lastRoundingWidth : width));
-
- lastRoundingWidth = width - oldWidth;
-
- if (m_accountForGlyphBounds) {
- m_maxGlyphBoundingBoxY = max(m_maxGlyphBoundingBoxY, bounds.maxY());
- m_minGlyphBoundingBoxY = min(m_minGlyphBoundingBoxY, bounds.y());
- m_lastGlyphOverflow = max<float>(0, bounds.maxX() - width);
- }
- }
-
- if (shouldApplyFontTransforms())
- m_runWidthSoFar += applyFontTransforms(glyphBuffer, m_run.ltr(), lastGlyphCount, lastFontData, m_typesettingFeatures, charactersTreatedAsSpace);
-
- unsigned consumedCharacters = textIterator.currentCharacter() - m_currentCharacter;
- m_currentCharacter = textIterator.currentCharacter();
- m_runWidthSoFar += widthSinceLastRounding;
- m_finalRoundingWidth = lastRoundingWidth;
- return consumedCharacters;
-}
-
-unsigned WidthIterator::advance(int offset, GlyphBuffer* glyphBuffer)
-{
- int length = m_run.length();
-
- if (offset > length)
- offset = length;
-
- if (m_currentCharacter >= static_cast<unsigned>(offset))
- return 0;
-
- if (m_run.is8Bit()) {
- Latin1TextIterator textIterator(m_run.data8(m_currentCharacter), m_currentCharacter, offset, length);
- return advanceInternal(textIterator, glyphBuffer);
- }
-
- SurrogatePairAwareTextIterator textIterator(m_run.data16(m_currentCharacter), m_currentCharacter, offset, length);
- return advanceInternal(textIterator, glyphBuffer);
-}
-
-bool WidthIterator::advanceOneCharacter(float& width, GlyphBuffer& glyphBuffer)
-{
- int oldSize = glyphBuffer.size();
- advance(m_currentCharacter + 1, &glyphBuffer);
- float w = 0;
- for (int i = oldSize; i < glyphBuffer.size(); ++i)
- w += glyphBuffer.advanceAt(i);
- width = w;
- return glyphBuffer.size() > oldSize;
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/WidthIterator.h b/chromium/third_party/WebKit/Source/core/platform/graphics/WidthIterator.h
deleted file mode 100644
index 929fc119611..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/WidthIterator.h
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- * Copyright (C) 2003, 2006, 2008, 2011 Apple Inc. All rights reserved.
- * Copyright (C) 2008 Holger Hans Peter Freyther
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#ifndef WidthIterator_h
-#define WidthIterator_h
-
-#include "core/platform/graphics/Font.h"
-#include "core/platform/graphics/SVGGlyph.h"
-#include "core/platform/graphics/TextRun.h"
-#include "wtf/HashSet.h"
-#include "wtf/unicode/Unicode.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-class Font;
-class GlyphBuffer;
-class SimpleFontData;
-class TextRun;
-struct GlyphData;
-
-struct WidthIterator {
- WTF_MAKE_FAST_ALLOCATED;
-public:
- WidthIterator(const Font*, const TextRun&, HashSet<const SimpleFontData*>* fallbackFonts = 0, bool accountForGlyphBounds = false, bool forTextEmphasis = false);
-
- unsigned advance(int to, GlyphBuffer*);
- bool advanceOneCharacter(float& width, GlyphBuffer&);
-
- float maxGlyphBoundingBoxY() const { ASSERT(m_accountForGlyphBounds); return m_maxGlyphBoundingBoxY; }
- float minGlyphBoundingBoxY() const { ASSERT(m_accountForGlyphBounds); return m_minGlyphBoundingBoxY; }
- float firstGlyphOverflow() const { ASSERT(m_accountForGlyphBounds); return m_firstGlyphOverflow; }
- float lastGlyphOverflow() const { ASSERT(m_accountForGlyphBounds); return m_lastGlyphOverflow; }
-
- const TextRun& run() const { return m_run; }
- float runWidthSoFar() const { return m_runWidthSoFar; }
-
-#if ENABLE(SVG_FONTS)
- String lastGlyphName() const { return m_lastGlyphName; }
- void setLastGlyphName(const String& name) { m_lastGlyphName = name; }
- Vector<SVGGlyph::ArabicForm>& arabicForms() { return m_arabicForms; }
-#endif
-
- static bool supportsTypesettingFeatures(const Font& font)
- {
-
- return !font.typesettingFeatures();
- }
-
- const Font* m_font;
-
- const TextRun& m_run;
-
- unsigned m_currentCharacter;
- float m_runWidthSoFar;
- float m_expansion;
- float m_expansionPerOpportunity;
- bool m_isAfterExpansion;
- float m_finalRoundingWidth;
-
-#if ENABLE(SVG_FONTS)
- String m_lastGlyphName;
- Vector<SVGGlyph::ArabicForm> m_arabicForms;
-#endif
-
-private:
- GlyphData glyphDataForCharacter(UChar32, bool mirror, int currentCharacter, unsigned& advanceLength);
- template <typename TextIterator>
- inline unsigned advanceInternal(TextIterator&, GlyphBuffer*);
-
- bool shouldApplyFontTransforms() const { return m_run.length() > 1 && (m_typesettingFeatures & (Kerning | Ligatures)); }
-
- TypesettingFeatures m_typesettingFeatures;
- HashSet<const SimpleFontData*>* m_fallbackFonts;
- bool m_accountForGlyphBounds;
- float m_maxGlyphBoundingBoxY;
- float m_minGlyphBoundingBoxY;
- float m_firstGlyphOverflow;
- float m_lastGlyphOverflow;
- bool m_forTextEmphasis;
-};
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/WindRule.h b/chromium/third_party/WebKit/Source/core/platform/graphics/WindRule.h
deleted file mode 100644
index d4f123e8132..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/WindRule.h
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright (C) 2003, 2006, 2009 Apple Inc. All rights reserved.
- * 2006 Rob Buis <buis@kde.org>
- * Copyright (C) 2007-2008 Torch Mobile, Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef WindRule_h
-#define WindRule_h
-
-namespace WebCore {
-
-enum WindRule {
- RULE_NONZERO = 0,
- RULE_EVENODD = 1
-};
-
-}
-
-#endif // WindRule_h
-
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/cg/FloatPointCG.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/cg/FloatPointCG.cpp
deleted file mode 100644
index a45fbd8bc57..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/cg/FloatPointCG.cpp
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright (C) 2004, 2006 Apple Computer, Inc. All rights reserved.
- * Copyright (C) 2005 Nokia. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/FloatPoint.h"
-
-#include <ApplicationServices/ApplicationServices.h>
-
-namespace WebCore {
-
-FloatPoint::FloatPoint(const CGPoint& p) : m_x(p.x), m_y(p.y)
-{
-}
-
-FloatPoint::operator CGPoint() const
-{
- return CGPointMake(m_x, m_y);
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/cg/FloatRectCG.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/cg/FloatRectCG.cpp
deleted file mode 100644
index 35bea8874f7..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/cg/FloatRectCG.cpp
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright (C) 2003, 2006 Apple Computer, Inc. All rights reserved.
- * Copyright (C) 2005 Nokia. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/FloatRect.h"
-
-#include <ApplicationServices/ApplicationServices.h>
-
-namespace WebCore {
-
-FloatRect::FloatRect(const CGRect& r) : m_location(r.origin), m_size(r.size)
-{
-}
-
-FloatRect::operator CGRect() const
-{
- return CGRectMake(x(), y(), width(), height());
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/cg/FloatSizeCG.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/cg/FloatSizeCG.cpp
deleted file mode 100644
index 0c198373e49..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/cg/FloatSizeCG.cpp
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright (C) 2003, 2006 Apple Computer, Inc. All rights reserved.
- * Copyright (C) 2005 Nokia. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/FloatSize.h"
-
-#include <ApplicationServices/ApplicationServices.h>
-
-namespace WebCore {
-
-FloatSize::FloatSize(const CGSize& s) : m_width(s.width), m_height(s.height)
-{
-}
-
-FloatSize::operator CGSize() const
-{
- return CGSizeMake(m_width, m_height);
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/cg/GraphicsContextCG.h b/chromium/third_party/WebKit/Source/core/platform/graphics/cg/GraphicsContextCG.h
deleted file mode 100644
index 5f956d2ebd4..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/cg/GraphicsContextCG.h
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright (C) 2006, 2007, 2010 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef GraphicsContextCG_h
-#define GraphicsContextCG_h
-
-#include "core/platform/graphics/GraphicsContext.h"
-
-typedef struct CGColorSpace *CGColorSpaceRef;
-
-namespace WebCore {
-
-CGColorSpaceRef deviceRGBColorSpaceRef();
-CGColorSpaceRef sRGBColorSpaceRef();
-CGColorSpaceRef linearRGBColorSpaceRef();
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/cg/IntPointCG.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/cg/IntPointCG.cpp
deleted file mode 100644
index aca2d8789b0..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/cg/IntPointCG.cpp
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright (C) 2004, 2005, 2006 Apple Computer, Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/IntPoint.h"
-
-#include <ApplicationServices/ApplicationServices.h>
-
-namespace WebCore {
-
-IntPoint::IntPoint(const CGPoint& p) : m_x(static_cast<int>(p.x)), m_y(static_cast<int>(p.y))
-{
-}
-
-IntPoint::operator CGPoint() const
-{
- return CGPointMake(m_x, m_y);
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/cg/IntRectCG.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/cg/IntRectCG.cpp
deleted file mode 100644
index 0044cfac040..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/cg/IntRectCG.cpp
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright (C) 2003, 2006 Apple Computer, Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/IntRect.h"
-
-#include <ApplicationServices/ApplicationServices.h>
-
-namespace WebCore {
-
-IntRect::operator CGRect() const
-{
- return CGRectMake(x(), y(), width(), height());
-}
-
-IntRect enclosingIntRect(const CGRect& rect)
-{
- int l = static_cast<int>(floorf(rect.origin.x));
- int t = static_cast<int>(floorf(rect.origin.y));
- int r = static_cast<int>(ceilf(CGRectGetMaxX(rect)));
- int b = static_cast<int>(ceilf(CGRectGetMaxY(rect)));
- return IntRect(l, t, r - l, b - t);
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/cg/IntSizeCG.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/cg/IntSizeCG.cpp
deleted file mode 100644
index 1a8a548ded0..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/cg/IntSizeCG.cpp
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright (C) 2003, 2004, 2005, 2006 Apple Computer, Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/IntSize.h"
-
-#include <ApplicationServices/ApplicationServices.h>
-
-namespace WebCore {
-
-IntSize::IntSize(const CGSize& s) : m_width(static_cast<int>(s.width)), m_height(static_cast<int>(s.height))
-{
-}
-
-IntSize::operator CGSize() const
-{
- return CGSizeMake(m_width, m_height);
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/AnimationTranslationUtil.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/AnimationTranslationUtil.cpp
deleted file mode 100644
index d798888a0df..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/AnimationTranslationUtil.cpp
+++ /dev/null
@@ -1,303 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/platform/graphics/chromium/AnimationTranslationUtil.h"
-
-#include "core/css/LengthFunctions.h"
-#include "core/platform/animation/CSSAnimationData.h"
-#include "core/platform/animation/KeyframeValueList.h"
-#include "core/platform/graphics/FloatSize.h"
-#include "core/platform/graphics/chromium/TransformSkMatrix44Conversions.h"
-#include "core/platform/graphics/transforms/InterpolatedTransformOperation.h"
-#include "core/platform/graphics/transforms/Matrix3DTransformOperation.h"
-#include "core/platform/graphics/transforms/MatrixTransformOperation.h"
-#include "core/platform/graphics/transforms/PerspectiveTransformOperation.h"
-#include "core/platform/graphics/transforms/RotateTransformOperation.h"
-#include "core/platform/graphics/transforms/ScaleTransformOperation.h"
-#include "core/platform/graphics/transforms/SkewTransformOperation.h"
-#include "core/platform/graphics/transforms/TransformOperations.h"
-#include "core/platform/graphics/transforms/TranslateTransformOperation.h"
-
-#include "public/platform/Platform.h"
-#include "public/platform/WebAnimation.h"
-#include "public/platform/WebAnimationCurve.h"
-#include "public/platform/WebCompositorSupport.h"
-#include "public/platform/WebFloatAnimationCurve.h"
-#include "public/platform/WebTransformAnimationCurve.h"
-#include "public/platform/WebTransformOperations.h"
-
-#include "wtf/OwnPtr.h"
-#include "wtf/text/CString.h"
-
-using namespace std;
-using namespace WebKit;
-
-namespace WebCore {
-
-PassOwnPtr<WebTransformOperations> toWebTransformOperations(const TransformOperations& transformOperations, const FloatSize& boxSize)
-{
- // We need to do a deep copy the transformOperations may contain ref pointers to TransformOperation objects.
- OwnPtr<WebTransformOperations> webTransformOperations = adoptPtr(Platform::current()->compositorSupport()->createTransformOperations());
- if (!webTransformOperations)
- return nullptr;
- for (size_t j = 0; j < transformOperations.size(); ++j) {
- TransformOperation::OperationType operationType = transformOperations.operations()[j]->getOperationType();
- switch (operationType) {
- case TransformOperation::ScaleX:
- case TransformOperation::ScaleY:
- case TransformOperation::ScaleZ:
- case TransformOperation::Scale3D:
- case TransformOperation::Scale: {
- ScaleTransformOperation* transform = static_cast<ScaleTransformOperation*>(transformOperations.operations()[j].get());
- webTransformOperations->appendScale(transform->x(), transform->y(), transform->z());
- break;
- }
- case TransformOperation::TranslateX:
- case TransformOperation::TranslateY:
- case TransformOperation::TranslateZ:
- case TransformOperation::Translate3D:
- case TransformOperation::Translate: {
- TranslateTransformOperation* transform = static_cast<TranslateTransformOperation*>(transformOperations.operations()[j].get());
- webTransformOperations->appendTranslate(floatValueForLength(transform->x(), boxSize.width()), floatValueForLength(transform->y(), boxSize.height()), floatValueForLength(transform->z(), 1));
- break;
- }
- case TransformOperation::RotateX:
- case TransformOperation::RotateY:
- case TransformOperation::Rotate3D:
- case TransformOperation::Rotate: {
- RotateTransformOperation* transform = static_cast<RotateTransformOperation*>(transformOperations.operations()[j].get());
- webTransformOperations->appendRotate(transform->x(), transform->y(), transform->z(), transform->angle());
- break;
- }
- case TransformOperation::SkewX:
- case TransformOperation::SkewY:
- case TransformOperation::Skew: {
- SkewTransformOperation* transform = static_cast<SkewTransformOperation*>(transformOperations.operations()[j].get());
- webTransformOperations->appendSkew(transform->angleX(), transform->angleY());
- break;
- }
- case TransformOperation::Matrix: {
- MatrixTransformOperation* transform = static_cast<MatrixTransformOperation*>(transformOperations.operations()[j].get());
- TransformationMatrix m = transform->matrix();
- webTransformOperations->appendMatrix(TransformSkMatrix44Conversions::convert(m));
- break;
- }
- case TransformOperation::Matrix3D: {
- Matrix3DTransformOperation* transform = static_cast<Matrix3DTransformOperation*>(transformOperations.operations()[j].get());
- TransformationMatrix m = transform->matrix();
- webTransformOperations->appendMatrix(TransformSkMatrix44Conversions::convert(m));
- break;
- }
- case TransformOperation::Perspective: {
- PerspectiveTransformOperation* transform = static_cast<PerspectiveTransformOperation*>(transformOperations.operations()[j].get());
- webTransformOperations->appendPerspective(floatValueForLength(transform->perspective(), 0));
- break;
- }
- case TransformOperation::Interpolated: {
- TransformationMatrix m;
- transformOperations.operations()[j]->apply(m, boxSize);
- webTransformOperations->appendMatrix(TransformSkMatrix44Conversions::convert(m));
- break;
- }
- case TransformOperation::Identity:
- webTransformOperations->appendIdentity();
- break;
- case TransformOperation::None:
- // Do nothing.
- break;
- } // switch
- } // for each operation
-
- return webTransformOperations.release();
-}
-
-template <class Value, class Keyframe, class Curve>
-bool appendKeyframeWithStandardTimingFunction(Curve* curve, double keyTime, const Value* value, const Value* lastValue, WebKit::WebAnimationCurve::TimingFunctionType timingFunctionType, const FloatSize&)
-{
- curve->add(Keyframe(keyTime, value->value()), timingFunctionType);
- return true;
-}
-
-template <class Value, class Keyframe, class Curve>
-bool appendKeyframeWithCustomBezierTimingFunction(Curve* curve, double keyTime, const Value* value, const Value* lastValue, double x1, double y1, double x2, double y2, const FloatSize&)
-{
- curve->add(Keyframe(keyTime, value->value()), x1, y1, x2, y2);
- return true;
-}
-
-bool isRotationType(TransformOperation::OperationType transformType)
-{
- return transformType == TransformOperation::Rotate
- || transformType == TransformOperation::RotateX
- || transformType == TransformOperation::RotateY
- || transformType == TransformOperation::RotateZ
- || transformType == TransformOperation::Rotate3D;
-}
-
-template <>
-bool appendKeyframeWithStandardTimingFunction<TransformAnimationValue, WebTransformKeyframe, WebTransformAnimationCurve>(WebTransformAnimationCurve* curve, double keyTime, const TransformAnimationValue* value, const TransformAnimationValue* lastValue, WebKit::WebAnimationCurve::TimingFunctionType timingFunctionType, const FloatSize& boxSize)
-{
- bool canBlend = !lastValue;
- OwnPtr<WebTransformOperations> operations(toWebTransformOperations(*value->value(), boxSize));
- if (!operations)
- return false;
- if (!canBlend) {
- OwnPtr<WebTransformOperations> lastOperations(toWebTransformOperations(*lastValue->value(), boxSize));
- if (!lastOperations)
- return false;
- canBlend = lastOperations->canBlendWith(*operations);
- }
- if (canBlend) {
- curve->add(WebTransformKeyframe(keyTime, operations.leakPtr()), timingFunctionType);
- return true;
- }
- return false;
-}
-
-template <>
-bool appendKeyframeWithCustomBezierTimingFunction<TransformAnimationValue, WebTransformKeyframe, WebTransformAnimationCurve>(WebTransformAnimationCurve* curve, double keyTime, const TransformAnimationValue* value, const TransformAnimationValue* lastValue, double x1, double y1, double x2, double y2, const FloatSize& boxSize)
-{
- bool canBlend = !lastValue;
- OwnPtr<WebTransformOperations> operations(toWebTransformOperations(*value->value(), boxSize));
- if (!operations)
- return false;
- if (!canBlend) {
- OwnPtr<WebTransformOperations> lastOperations(toWebTransformOperations(*lastValue->value(), boxSize));
- if (!lastOperations)
- return false;
- canBlend = lastOperations->canBlendWith(*operations);
- }
- if (canBlend) {
- curve->add(WebTransformKeyframe(keyTime, operations.leakPtr()), x1, y1, x2, y2);
- return true;
- }
- return false;
-}
-
-template <class Value, class Keyframe, class Curve>
-PassOwnPtr<WebKit::WebAnimation> createWebAnimation(const KeyframeValueList& valueList, const CSSAnimationData* animation, int animationId, double timeOffset, Curve* curve, WebKit::WebAnimation::TargetProperty targetProperty, const FloatSize& boxSize)
-{
- bool alternate = false;
- bool reverse = false;
- if (animation && animation->isDirectionSet()) {
- CSSAnimationData::AnimationDirection direction = animation->direction();
- if (direction == CSSAnimationData::AnimationDirectionAlternate || direction == CSSAnimationData::AnimationDirectionAlternateReverse)
- alternate = true;
- if (direction == CSSAnimationData::AnimationDirectionReverse || direction == CSSAnimationData::AnimationDirectionAlternateReverse)
- reverse = true;
- }
-
- for (size_t i = 0; i < valueList.size(); i++) {
- size_t index = reverse ? valueList.size() - i - 1 : i;
- const Value* originalValue = static_cast<const Value*>(valueList.at(index));
- const Value* lastOriginalValue = 0;
- if (valueList.size() > 1 && ((reverse && index + 1 < valueList.size()) || (!reverse && index > 0)))
- lastOriginalValue = static_cast<const Value*>(valueList.at(reverse ? index + 1 : index - 1));
-
- const TimingFunction* originalTimingFunction = originalValue->timingFunction();
-
- // If there hasn't been a timing function associated with this keyframe, use the
- // animation's timing function, if we have one.
- if (!originalTimingFunction && animation->isTimingFunctionSet())
- originalTimingFunction = animation->timingFunction();
-
- // Ease is the default timing function.
- WebKit::WebAnimationCurve::TimingFunctionType timingFunctionType = WebKit::WebAnimationCurve::TimingFunctionTypeEase;
-
- bool isUsingCustomBezierTimingFunction = false;
- double x1 = 0;
- double y1 = 0;
- double x2 = 1;
- double y2 = 1;
-
- if (originalTimingFunction) {
- switch (originalTimingFunction->type()) {
- case TimingFunction::StepsFunction:
- // FIXME: add support for steps timing function.
- return nullptr;
- case TimingFunction::LinearFunction:
- timingFunctionType = WebKit::WebAnimationCurve::TimingFunctionTypeLinear;
- break;
- case TimingFunction::CubicBezierFunction:
- {
- const CubicBezierTimingFunction* originalBezierTimingFunction = static_cast<const CubicBezierTimingFunction*>(originalTimingFunction);
- isUsingCustomBezierTimingFunction = true;
- x1 = originalBezierTimingFunction->x1();
- y1 = originalBezierTimingFunction->y1();
- x2 = originalBezierTimingFunction->x2();
- y2 = originalBezierTimingFunction->y2();
- break;
- }
- default:
- ASSERT_NOT_REACHED();
- } // switch
- }
-
- double duration = (animation && animation->isDurationSet()) ? animation->duration() : 1;
- double keyTime = originalValue->keyTime() * duration;
-
- if (reverse)
- keyTime = duration - keyTime;
-
- bool addedKeyframe = false;
- if (isUsingCustomBezierTimingFunction)
- addedKeyframe = appendKeyframeWithCustomBezierTimingFunction<Value, Keyframe, Curve>(curve, keyTime, originalValue, lastOriginalValue, x1, y1, x2, y2, boxSize);
- else
- addedKeyframe = appendKeyframeWithStandardTimingFunction<Value, Keyframe, Curve>(curve, keyTime, originalValue, lastOriginalValue, timingFunctionType, boxSize);
- if (!addedKeyframe)
- return nullptr;
- }
-
- OwnPtr<WebKit::WebAnimation> webAnimation = adoptPtr(Platform::current()->compositorSupport()->createAnimation(*curve, targetProperty, animationId));
-
- int iterations = (animation && animation->isIterationCountSet()) ? animation->iterationCount() : 1;
- webAnimation->setIterations(iterations);
- webAnimation->setAlternatesDirection(alternate);
-
- // If timeOffset > 0, then the animation has started in the past.
- webAnimation->setTimeOffset(timeOffset);
-
- return webAnimation.release();
-}
-
-PassOwnPtr<WebKit::WebAnimation> createWebAnimation(const KeyframeValueList& values, const CSSAnimationData* animation, int animationId, double timeOffset, const FloatSize& boxSize)
-{
-
-
- if (values.property() == AnimatedPropertyWebkitTransform) {
- OwnPtr<WebTransformAnimationCurve> curve = adoptPtr(Platform::current()->compositorSupport()->createTransformAnimationCurve());
- return createWebAnimation<TransformAnimationValue, WebTransformKeyframe, WebTransformAnimationCurve>(values, animation, animationId, timeOffset, curve.get(), WebKit::WebAnimation::TargetPropertyTransform, FloatSize(boxSize));
- }
-
- if (values.property() == AnimatedPropertyOpacity) {
- OwnPtr<WebFloatAnimationCurve> curve = adoptPtr(Platform::current()->compositorSupport()->createFloatAnimationCurve());
- return createWebAnimation<FloatAnimationValue, WebFloatKeyframe, WebFloatAnimationCurve>(values, animation, animationId, timeOffset, curve.get(), WebKit::WebAnimation::TargetPropertyOpacity, FloatSize());
- }
-
- return nullptr;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/AnimationTranslationUtil.h b/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/AnimationTranslationUtil.h
deleted file mode 100644
index 95af52a0293..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/AnimationTranslationUtil.h
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef AnimationTranslationUtil_h
-#define AnimationTranslationUtil_h
-
-#include "wtf/PassOwnPtr.h"
-
-namespace WebKit {
-class WebAnimation;
-}
-
-namespace WebCore {
-
-class KeyframeValueList;
-class CSSAnimationData;
-class FloatSize;
-
-
-// Translates WebCore animation data into a WebAnimation. If we are unable
-// to perform this translation, we return nullptr. This can happen if
-// - a steps timing function is used,
-// - a property other than AnimatedPropertyWebkitTransform, or AnimatedPropertyOpacity is animated, or
-// - a transform animation involves a non-invertable transform.
-PassOwnPtr<WebKit::WebAnimation> createWebAnimation(const KeyframeValueList&, const CSSAnimationData*, int animationId, double timeOffset, const FloatSize& boxSize);
-
-} // namespace WebCore
-
-#endif // AnimationTranslationUtil_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/AnimationTranslationUtilTest.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/AnimationTranslationUtilTest.cpp
deleted file mode 100644
index 666204e2771..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/AnimationTranslationUtilTest.cpp
+++ /dev/null
@@ -1,263 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/platform/graphics/chromium/AnimationTranslationUtil.h"
-
-#include "core/platform/animation/CSSAnimationData.h"
-#include "core/platform/animation/KeyframeValueList.h"
-#include "core/platform/graphics/IntSize.h"
-#include "core/platform/graphics/transforms/Matrix3DTransformOperation.h"
-#include "core/platform/graphics/transforms/RotateTransformOperation.h"
-#include "core/platform/graphics/transforms/ScaleTransformOperation.h"
-#include "core/platform/graphics/transforms/TransformOperations.h"
-#include "core/platform/graphics/transforms/TranslateTransformOperation.h"
-#include "wtf/RefPtr.h"
-#include <gtest/gtest.h>
-#include "public/platform/WebAnimation.h"
-
-using namespace WebCore;
-using namespace WebKit;
-
-namespace {
-
-bool animationCanBeTranslated(const KeyframeValueList& values, CSSAnimationData* animation)
-{
- IntSize boxSize;
- return createWebAnimation(values, animation, 0, 0, boxSize);
-}
-
-TEST(AnimationTranslationUtilTest, createOpacityAnimation)
-{
- const double duration = 1;
- WebCore::KeyframeValueList values(AnimatedPropertyOpacity);
- values.insert(adoptPtr(new FloatAnimationValue(0, 0)));
- values.insert(adoptPtr(new FloatAnimationValue(duration, 1)));
-
- RefPtr<CSSAnimationData> animation = CSSAnimationData::create();
- animation->setDuration(duration);
-
- EXPECT_TRUE(animationCanBeTranslated(values, animation.get()));
-}
-
-TEST(AnimationTranslationUtilTest, createTransformAnimation)
-{
- const double duration = 1;
- WebCore::KeyframeValueList values(AnimatedPropertyWebkitTransform);
-
- TransformOperations operations1;
- operations1.operations().append(TranslateTransformOperation::create(Length(2, WebCore::Fixed), Length(0, WebCore::Fixed), TransformOperation::TranslateX));
- values.insert(adoptPtr(new TransformAnimationValue(0, &operations1)));
-
- TransformOperations operations2;
- operations2.operations().append(TranslateTransformOperation::create(Length(4, WebCore::Fixed), Length(0, WebCore::Fixed), TransformOperation::TranslateX));
- values.insert(adoptPtr(new TransformAnimationValue(duration, &operations2)));
-
- RefPtr<CSSAnimationData> animation = CSSAnimationData::create();
- animation->setDuration(duration);
-
- EXPECT_TRUE(animationCanBeTranslated(values, animation.get()));
-}
-
-TEST(AnimationTranslationUtilTest, createTransformAnimationWithBigRotation)
-{
- const double duration = 1;
- WebCore::KeyframeValueList values(AnimatedPropertyWebkitTransform);
-
- TransformOperations operations1;
- operations1.operations().append(RotateTransformOperation::create(0, TransformOperation::Rotate));
- values.insert(adoptPtr(new TransformAnimationValue(0, &operations1)));
-
- TransformOperations operations2;
- operations2.operations().append(RotateTransformOperation::create(270, TransformOperation::Rotate));
- values.insert(adoptPtr(new TransformAnimationValue(duration, &operations2)));
-
- RefPtr<CSSAnimationData> animation = CSSAnimationData::create();
- animation->setDuration(duration);
-
- EXPECT_TRUE(animationCanBeTranslated(values, animation.get()));
-}
-
-TEST(AnimationTranslationUtilTest, createTransformAnimationWithBigRotationAndEmptyTransformOperationList)
-{
- const double duration = 1;
- WebCore::KeyframeValueList values(AnimatedPropertyWebkitTransform);
-
- TransformOperations operations1;
- values.insert(adoptPtr(new TransformAnimationValue(0, &operations1)));
-
- TransformOperations operations2;
- operations2.operations().append(RotateTransformOperation::create(270, TransformOperation::Rotate));
- values.insert(adoptPtr(new TransformAnimationValue(duration, &operations2)));
-
- RefPtr<CSSAnimationData> animation = CSSAnimationData::create();
- animation->setDuration(duration);
-
- EXPECT_TRUE(animationCanBeTranslated(values, animation.get()));
-}
-
-TEST(AnimationTranslationUtilTest, createTransformAnimationWithRotationInvolvingNegativeAngles)
-{
- const double duration = 1;
- WebCore::KeyframeValueList values(AnimatedPropertyWebkitTransform);
-
- TransformOperations operations1;
- operations1.operations().append(RotateTransformOperation::create(-330, TransformOperation::Rotate));
- values.insert(adoptPtr(new TransformAnimationValue(0, &operations1)));
-
- TransformOperations operations2;
- operations2.operations().append(RotateTransformOperation::create(-320, TransformOperation::Rotate));
- values.insert(adoptPtr(new TransformAnimationValue(duration, &operations2)));
-
- RefPtr<CSSAnimationData> animation = CSSAnimationData::create();
- animation->setDuration(duration);
-
- EXPECT_TRUE(animationCanBeTranslated(values, animation.get()));
-}
-
-TEST(AnimationTranslationUtilTest, createTransformAnimationWithSmallRotationInvolvingLargeAngles)
-{
- const double duration = 1;
- WebCore::KeyframeValueList values(AnimatedPropertyWebkitTransform);
-
- TransformOperations operations1;
- operations1.operations().append(RotateTransformOperation::create(270, TransformOperation::Rotate));
- values.insert(adoptPtr(new TransformAnimationValue(0, &operations1)));
-
- TransformOperations operations2;
- operations2.operations().append(RotateTransformOperation::create(360, TransformOperation::Rotate));
- values.insert(adoptPtr(new TransformAnimationValue(duration, &operations2)));
-
- RefPtr<CSSAnimationData> animation = CSSAnimationData::create();
- animation->setDuration(duration);
-
- EXPECT_TRUE(animationCanBeTranslated(values, animation.get()));
-}
-
-TEST(AnimationTranslationUtilTest, createTransformAnimationWithNonDecomposableMatrix)
-{
- const double duration = 1;
- WebCore::KeyframeValueList values(AnimatedPropertyWebkitTransform);
-
- TransformationMatrix matrix1;
- TransformOperations operations1;
- operations1.operations().append(Matrix3DTransformOperation::create(matrix1));
- values.insert(adoptPtr(new TransformAnimationValue(0, &operations1)));
-
- TransformationMatrix matrix2;
- matrix2.setM11(0);
- TransformOperations operations2;
- operations2.operations().append(Matrix3DTransformOperation::create(matrix2));
- values.insert(adoptPtr(new TransformAnimationValue(duration, &operations2)));
-
- RefPtr<CSSAnimationData> animation = CSSAnimationData::create();
- animation->setDuration(duration);
-
- EXPECT_FALSE(animationCanBeTranslated(values, animation.get()));
-}
-
-TEST(AnimationTranslationUtilTest, createTransformAnimationWithNonInvertibleTransform)
-{
- const double duration = 1;
- WebCore::KeyframeValueList values(AnimatedPropertyWebkitTransform);
-
- TransformOperations operations1;
- operations1.operations().append(ScaleTransformOperation::create(1, 1, 1, TransformOperation::Scale3D));
- values.insert(adoptPtr(new TransformAnimationValue(0, &operations1)));
-
- TransformOperations operations2;
- operations2.operations().append(ScaleTransformOperation::create(1, 0, 1, TransformOperation::Scale3D));
- values.insert(adoptPtr(new TransformAnimationValue(duration, &operations2)));
-
- RefPtr<CSSAnimationData> animation = CSSAnimationData::create();
- animation->setDuration(duration);
-
- EXPECT_TRUE(animationCanBeTranslated(values, animation.get()));
-}
-
-TEST(AnimationTranslationUtilTest, createReversedAnimation)
-{
- const double duration = 1;
- WebCore::KeyframeValueList values(AnimatedPropertyWebkitTransform);
-
- TransformOperations operations1;
- operations1.operations().append(TranslateTransformOperation::create(Length(2, WebCore::Fixed), Length(0, WebCore::Fixed), TransformOperation::TranslateX));
- values.insert(adoptPtr(new TransformAnimationValue(0, &operations1)));
-
- TransformOperations operations2;
- operations2.operations().append(TranslateTransformOperation::create(Length(4, WebCore::Fixed), Length(0, WebCore::Fixed), TransformOperation::TranslateX));
- values.insert(adoptPtr(new TransformAnimationValue(duration, &operations2)));
-
- RefPtr<CSSAnimationData> animation = CSSAnimationData::create();
- animation->setDuration(duration);
- animation->setDirection(CSSAnimationData::AnimationDirectionReverse);
-
- EXPECT_TRUE(animationCanBeTranslated(values, animation.get()));
-}
-
-TEST(AnimationTranslationUtilTest, createAlternatingAnimation)
-{
- const double duration = 1;
- WebCore::KeyframeValueList values(AnimatedPropertyWebkitTransform);
-
- TransformOperations operations1;
- operations1.operations().append(TranslateTransformOperation::create(Length(2, WebCore::Fixed), Length(0, WebCore::Fixed), TransformOperation::TranslateX));
- values.insert(adoptPtr(new TransformAnimationValue(0, &operations1)));
-
- TransformOperations operations2;
- operations2.operations().append(TranslateTransformOperation::create(Length(4, WebCore::Fixed), Length(0, WebCore::Fixed), TransformOperation::TranslateX));
- values.insert(adoptPtr(new TransformAnimationValue(duration, &operations2)));
-
- RefPtr<CSSAnimationData> animation = CSSAnimationData::create();
- animation->setDuration(duration);
- animation->setDirection(CSSAnimationData::AnimationDirectionAlternate);
- animation->setIterationCount(2);
-
- EXPECT_TRUE(animationCanBeTranslated(values, animation.get()));
-}
-
-TEST(AnimationTranslationUtilTest, createReversedAlternatingAnimation)
-{
- const double duration = 1;
- WebCore::KeyframeValueList values(AnimatedPropertyWebkitTransform);
-
- TransformOperations operations1;
- operations1.operations().append(TranslateTransformOperation::create(Length(2, WebCore::Fixed), Length(0, WebCore::Fixed), TransformOperation::TranslateX));
- values.insert(adoptPtr(new TransformAnimationValue(0, &operations1)));
-
- TransformOperations operations2;
- operations2.operations().append(TranslateTransformOperation::create(Length(4, WebCore::Fixed), Length(0, WebCore::Fixed), TransformOperation::TranslateX));
- values.insert(adoptPtr(new TransformAnimationValue(duration, &operations2)));
-
- RefPtr<CSSAnimationData> animation = CSSAnimationData::create();
- animation->setDuration(duration);
- animation->setDirection(CSSAnimationData::AnimationDirectionAlternateReverse);
- animation->setIterationCount(2);
-
- EXPECT_TRUE(animationCanBeTranslated(values, animation.get()));
-}
-
-}
-
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/Canvas2DLayerBridge.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/Canvas2DLayerBridge.cpp
deleted file mode 100644
index d68198e997b..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/Canvas2DLayerBridge.cpp
+++ /dev/null
@@ -1,425 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/platform/graphics/chromium/Canvas2DLayerBridge.h"
-
-#include "GrContext.h"
-#include "SkDevice.h"
-#include "SkSurface.h"
-#include "core/platform/chromium/TraceEvent.h"
-#include "core/platform/graphics/GraphicsContext3D.h"
-#include "core/platform/graphics/GraphicsLayer.h"
-#include "core/platform/graphics/chromium/Canvas2DLayerManager.h"
-#include "core/platform/graphics/gpu/SharedGraphicsContext3D.h"
-#include "public/platform/Platform.h"
-#include "public/platform/WebCompositorSupport.h"
-#include "public/platform/WebGraphicsContext3D.h"
-
-using WebKit::WebExternalTextureLayer;
-using WebKit::WebGraphicsContext3D;
-
-namespace WebCore {
-
-void Canvas2DLayerBridgePtr::clear()
-{
- if (m_ptr) {
- m_ptr->destroy();
- m_ptr.clear();
- }
-}
-
-Canvas2DLayerBridgePtr& Canvas2DLayerBridgePtr::operator=(const PassRefPtr<Canvas2DLayerBridge>& other)
-{
- clear();
- m_ptr = other;
- return *this;
-}
-
-static SkSurface* createSurface(GraphicsContext3D* context3D, const IntSize& size)
-{
- ASSERT(!context3D->webContext()->isContextLost());
- GrContext* gr = context3D->grContext();
- if (!gr)
- return 0;
- gr->resetContext();
- SkImage::Info info;
- info.fWidth = size.width();
- info.fHeight = size.height();
- info.fColorType = SkImage::kPMColor_ColorType;
- info.fAlphaType = SkImage::kPremul_AlphaType;
- return SkSurface::NewRenderTarget(gr, info);
-}
-
-PassRefPtr<Canvas2DLayerBridge> Canvas2DLayerBridge::create(PassRefPtr<GraphicsContext3D> context, const IntSize& size, OpacityMode opacityMode)
-{
- TRACE_EVENT_INSTANT0("test_gpu", "Canvas2DLayerBridgeCreation");
- SkAutoTUnref<SkSurface> surface(createSurface(context.get(), size));
- if (!surface.get()) {
- return PassRefPtr<Canvas2DLayerBridge>();
- }
- RefPtr<SkDeferredCanvas> canvas = adoptRef(SkDeferredCanvas::Create(surface.get()));
- RefPtr<Canvas2DLayerBridge> layerBridge = adoptRef(new Canvas2DLayerBridge(context, canvas.release(), opacityMode));
- return layerBridge.release();
-}
-
-Canvas2DLayerBridge::Canvas2DLayerBridge(PassRefPtr<GraphicsContext3D> context, PassRefPtr<SkDeferredCanvas> canvas, OpacityMode opacityMode)
- : m_canvas(canvas)
- , m_context(context)
- , m_bytesAllocated(0)
- , m_didRecordDrawCommand(false)
- , m_surfaceIsValid(true)
- , m_framesPending(0)
- , m_destructionInProgress(false)
- , m_rateLimitingEnabled(false)
- , m_next(0)
- , m_prev(0)
- , m_lastImageId(0)
-{
- ASSERT(m_canvas);
- // Used by browser tests to detect the use of a Canvas2DLayerBridge.
- TRACE_EVENT_INSTANT0("test_gpu", "Canvas2DLayerBridgeCreation");
- m_layer = adoptPtr(WebKit::Platform::current()->compositorSupport()->createExternalTextureLayer(this));
- m_layer->setOpaque(opacityMode == Opaque);
- m_layer->setBlendBackgroundColor(opacityMode != Opaque);
- GraphicsLayer::registerContentsLayer(m_layer->layer());
- m_layer->setRateLimitContext(m_rateLimitingEnabled);
- m_canvas->setNotificationClient(this);
-}
-
-Canvas2DLayerBridge::~Canvas2DLayerBridge()
-{
- ASSERT(m_destructionInProgress);
- m_layer.clear();
- Vector<MailboxInfo>::iterator mailboxInfo;
- for (mailboxInfo = m_mailboxes.begin(); mailboxInfo < m_mailboxes.end(); mailboxInfo++) {
- ASSERT(mailboxInfo->m_status != MailboxInUse);
- if (mailboxInfo->m_status == MailboxReleased) {
- if (mailboxInfo->m_mailbox.syncPoint) {
- context()->waitSyncPoint(mailboxInfo->m_mailbox.syncPoint);
- mailboxInfo->m_mailbox.syncPoint = 0;
- }
- // Invalidate texture state in case the compositor altered it since the copy-on-write.
- mailboxInfo->m_image->getTexture()->invalidateCachedState();
- }
- }
- m_mailboxes.clear();
-}
-
-void Canvas2DLayerBridge::destroy()
-{
- ASSERT(!m_destructionInProgress);
- m_destructionInProgress = true;
- GraphicsLayer::unregisterContentsLayer(m_layer->layer());
- m_canvas->setNotificationClient(0);
- m_layer->clearTexture();
- Canvas2DLayerManager::get().layerToBeDestroyed(this);
- // Orphaning the layer is required to trigger the recration of a new layer
- // in the case where destruction is caused by a canvas resize. Test:
- // virtual/gpu/fast/canvas/canvas-resize-after-paint-without-layout.html
- m_layer->layer()->removeFromParent();
-}
-
-void Canvas2DLayerBridge::limitPendingFrames()
-{
- ASSERT(!m_destructionInProgress);
- if (m_didRecordDrawCommand) {
- m_framesPending++;
- m_didRecordDrawCommand = false;
- if (m_framesPending > 1) {
- // Turn on the rate limiter if this layer tends to accumulate a
- // non-discardable multi-frame backlog of draw commands.
- setRateLimitingEnabled(true);
- }
- if (m_rateLimitingEnabled) {
- flush();
- }
- }
-}
-
-void Canvas2DLayerBridge::prepareForDraw()
-{
- ASSERT(!m_destructionInProgress);
- ASSERT(m_layer);
- if (!isValid()) {
- if (m_canvas) {
- // drop pending commands because there is no surface to draw to
- m_canvas->silentFlush();
- }
- return;
- }
- m_context->makeContextCurrent();
-}
-
-void Canvas2DLayerBridge::storageAllocatedForRecordingChanged(size_t bytesAllocated)
-{
- ASSERT(!m_destructionInProgress);
- intptr_t delta = (intptr_t)bytesAllocated - (intptr_t)m_bytesAllocated;
- m_bytesAllocated = bytesAllocated;
- Canvas2DLayerManager::get().layerAllocatedStorageChanged(this, delta);
-}
-
-size_t Canvas2DLayerBridge::storageAllocatedForRecording()
-{
- ASSERT(!m_destructionInProgress);
- return m_canvas->storageAllocatedForRecording();
-}
-
-void Canvas2DLayerBridge::flushedDrawCommands()
-{
- ASSERT(!m_destructionInProgress);
- storageAllocatedForRecordingChanged(storageAllocatedForRecording());
- m_framesPending = 0;
-}
-
-void Canvas2DLayerBridge::skippedPendingDrawCommands()
-{
- ASSERT(!m_destructionInProgress);
- // Stop triggering the rate limiter if SkDeferredCanvas is detecting
- // and optimizing overdraw.
- setRateLimitingEnabled(false);
- flushedDrawCommands();
-}
-
-void Canvas2DLayerBridge::setRateLimitingEnabled(bool enabled)
-{
- ASSERT(!m_destructionInProgress || !enabled);
- if (m_rateLimitingEnabled != enabled) {
- m_rateLimitingEnabled = enabled;
- m_layer->setRateLimitContext(m_rateLimitingEnabled);
- }
-}
-
-size_t Canvas2DLayerBridge::freeMemoryIfPossible(size_t bytesToFree)
-{
- ASSERT(!m_destructionInProgress);
- size_t bytesFreed = m_canvas->freeMemoryIfPossible(bytesToFree);
- if (bytesFreed)
- Canvas2DLayerManager::get().layerAllocatedStorageChanged(this, -((intptr_t)bytesFreed));
- m_bytesAllocated -= bytesFreed;
- return bytesFreed;
-}
-
-void Canvas2DLayerBridge::flush()
-{
- ASSERT(!m_destructionInProgress);
- if (m_canvas->hasPendingCommands()) {
- TRACE_EVENT0("cc", "Canvas2DLayerBridge::flush");
- m_canvas->flush();
- }
-}
-
-WebGraphicsContext3D* Canvas2DLayerBridge::context()
-{
- // Check on m_layer is necessary because context() may be called during
- // the destruction of m_layer
- if (m_layer) {
- isValid(); // To ensure rate limiter is disabled if context is lost.
- }
- return m_context->webContext();
-}
-
-bool Canvas2DLayerBridge::isValid()
-{
- ASSERT(m_layer);
- if (m_destructionInProgress)
- return false;
- if (m_context->webContext()->isContextLost() || !m_surfaceIsValid) {
- // Attempt to recover.
- m_layer->clearTexture();
- m_mailboxes.clear();
- RefPtr<GraphicsContext3D> sharedContext = SharedGraphicsContext3D::get();
- if (!sharedContext || sharedContext->webContext()->isContextLost()) {
- m_surfaceIsValid = false;
- } else {
- m_context = sharedContext;
- IntSize size(m_canvas->getTopDevice()->width(), m_canvas->getTopDevice()->height());
- SkAutoTUnref<SkSurface> surface(createSurface(m_context.get(), size));
- if (surface.get()) {
- m_canvas->setSurface(surface.get());
- m_surfaceIsValid = true;
- // FIXME: draw sad canvas picture into new buffer crbug.com/243842
- } else {
- // Surface allocation failed. Set m_surfaceIsValid to false to
- // trigger subsequent retry.
- m_surfaceIsValid = false;
- }
- }
- }
- if (!m_surfaceIsValid)
- setRateLimitingEnabled(false);
- return m_surfaceIsValid;
-}
-
-bool Canvas2DLayerBridge::prepareMailbox(WebKit::WebExternalTextureMailbox* outMailbox, WebKit::WebExternalBitmap* bitmap)
-{
- if (bitmap) {
- // Using accelerated 2d canvas with software renderer, which
- // should only happen in tests that use fake graphics contexts.
- // In this case, we do not care about producing any results for
- // compositing.
- m_canvas->silentFlush();
- return false;
- }
- if (!isValid())
- return false;
- // Release to skia textures that were previouosly released by the
- // compositor. We do this before acquiring the next snapshot in
- // order to cap maximum gpu memory consumption.
- m_context->makeContextCurrent();
- flush();
- Vector<MailboxInfo>::iterator mailboxInfo;
- for (mailboxInfo = m_mailboxes.begin(); mailboxInfo < m_mailboxes.end(); mailboxInfo++) {
- if (mailboxInfo->m_status == MailboxReleased) {
- if (mailboxInfo->m_mailbox.syncPoint) {
- context()->waitSyncPoint(mailboxInfo->m_mailbox.syncPoint);
- mailboxInfo->m_mailbox.syncPoint = 0;
- }
- // Invalidate texture state in case the compositor altered it since the copy-on-write.
- mailboxInfo->m_image->getTexture()->invalidateCachedState();
- mailboxInfo->m_image.reset(0);
- mailboxInfo->m_status = MailboxAvailable;
- }
- }
- SkAutoTUnref<SkImage> image(m_canvas->newImageSnapshot());
- // Early exit if canvas was not drawn to since last prepareMailbox
- if (image->uniqueID() == m_lastImageId)
- return false;
- m_lastImageId = image->uniqueID();
-
- mailboxInfo = createMailboxInfo();
- mailboxInfo->m_status = MailboxInUse;
- mailboxInfo->m_image.swap(&image);
- // Because of texture sharing with the compositor, we must invalidate
- // the state cached in skia so that the deferred copy on write
- // in SkSurface_Gpu does not make any false assumptions.
- mailboxInfo->m_image->getTexture()->invalidateCachedState();
-
- ASSERT(mailboxInfo->m_mailbox.syncPoint == 0);
- ASSERT(mailboxInfo->m_image.get());
- ASSERT(mailboxInfo->m_image->getTexture());
-
- m_context->bindTexture(GraphicsContext3D::TEXTURE_2D, mailboxInfo->m_image->getTexture()->getTextureHandle());
- m_context->texParameteri(GraphicsContext3D::TEXTURE_2D, GraphicsContext3D::TEXTURE_MAG_FILTER, GraphicsContext3D::LINEAR);
- m_context->texParameteri(GraphicsContext3D::TEXTURE_2D, GraphicsContext3D::TEXTURE_MIN_FILTER, GraphicsContext3D::LINEAR);
- m_context->texParameteri(GraphicsContext3D::TEXTURE_2D, GraphicsContext3D::TEXTURE_WRAP_S, GraphicsContext3D::CLAMP_TO_EDGE);
- m_context->texParameteri(GraphicsContext3D::TEXTURE_2D, GraphicsContext3D::TEXTURE_WRAP_T, GraphicsContext3D::CLAMP_TO_EDGE);
- context()->produceTextureCHROMIUM(GraphicsContext3D::TEXTURE_2D, mailboxInfo->m_mailbox.name);
- context()->flush();
- mailboxInfo->m_mailbox.syncPoint = context()->insertSyncPoint();
- m_context->bindTexture(GraphicsContext3D::TEXTURE_2D, 0);
- // Because we are changing the texture binding without going through skia,
- // we must dirty the context.
- m_context->grContext()->resetContext(kTextureBinding_GrGLBackendState);
-
- // set m_parentLayerBridge to make sure 'this' stays alive as long as it has
- // live mailboxes
- ASSERT(!mailboxInfo->m_parentLayerBridge);
- mailboxInfo->m_parentLayerBridge = this;
- *outMailbox = mailboxInfo->m_mailbox;
- return true;
-}
-
-Canvas2DLayerBridge::MailboxInfo* Canvas2DLayerBridge::createMailboxInfo() {
- ASSERT(!m_destructionInProgress);
- MailboxInfo* mailboxInfo;
- for (mailboxInfo = m_mailboxes.begin(); mailboxInfo < m_mailboxes.end(); mailboxInfo++) {
- if (mailboxInfo->m_status == MailboxAvailable) {
- return mailboxInfo;
- }
- }
-
- // No available mailbox: create one.
- m_mailboxes.grow(m_mailboxes.size() + 1);
- mailboxInfo = &m_mailboxes.last();
- context()->genMailboxCHROMIUM(mailboxInfo->m_mailbox.name);
- // Worst case, canvas is triple buffered. More than 3 active mailboxes
- // means there is a problem.
- // For the single-threaded case, this value needs to be at least
- // kMaxSwapBuffersPending+1 (in render_widget.h).
- // Because of crbug.com/247874, it needs to be kMaxSwapBuffersPending+2.
- // TODO(piman): fix this.
- ASSERT(m_mailboxes.size() <= 4);
- ASSERT(mailboxInfo < m_mailboxes.end());
- return mailboxInfo;
-}
-
-void Canvas2DLayerBridge::mailboxReleased(const WebKit::WebExternalTextureMailbox& mailbox)
-{
- Vector<MailboxInfo>::iterator mailboxInfo;
- for (mailboxInfo = m_mailboxes.begin(); mailboxInfo < m_mailboxes.end(); mailboxInfo++) {
- if (!memcmp(mailboxInfo->m_mailbox.name, mailbox.name, sizeof(mailbox.name))) {
- mailboxInfo->m_mailbox.syncPoint = mailbox.syncPoint;
- ASSERT(mailboxInfo->m_status == MailboxInUse);
- mailboxInfo->m_status = MailboxReleased;
- // Trigger Canvas2DLayerBridge self-destruction if this is the
- // last live mailbox and the layer bridge is not externally
- // referenced.
- ASSERT(mailboxInfo->m_parentLayerBridge.get() == this);
- mailboxInfo->m_parentLayerBridge.clear();
- return;
- }
- }
-}
-
-WebKit::WebLayer* Canvas2DLayerBridge::layer()
-{
- ASSERT(m_layer);
- return m_layer->layer();
-}
-
-void Canvas2DLayerBridge::contextAcquired()
-{
- ASSERT(!m_destructionInProgress);
- Canvas2DLayerManager::get().layerDidDraw(this);
- m_didRecordDrawCommand = true;
-}
-
-unsigned Canvas2DLayerBridge::backBufferTexture()
-{
- ASSERT(!m_destructionInProgress);
- if (!isValid())
- return 0;
- contextAcquired();
- m_canvas->flush();
- m_context->flush();
- GrRenderTarget* renderTarget = reinterpret_cast<GrRenderTarget*>(m_canvas->getDevice()->accessRenderTarget());
- if (renderTarget) {
- return renderTarget->asTexture()->getTextureHandle();
- }
- return 0;
-}
-
-Canvas2DLayerBridge::MailboxInfo::MailboxInfo(const MailboxInfo& other) {
- // This copy constructor should only be used for Vector reallocation
- // Assuming 'other' is to be destroyed, we swap m_image ownership
- // rather than do a refcount dance.
- memcpy(&m_mailbox, &other.m_mailbox, sizeof(m_mailbox));
- m_image.swap(const_cast<SkAutoTUnref<SkImage>*>(&other.m_image));
- m_status = other.m_status;
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/Canvas2DLayerBridge.h b/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/Canvas2DLayerBridge.h
deleted file mode 100644
index 973f22ff36c..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/Canvas2DLayerBridge.h
+++ /dev/null
@@ -1,143 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef Canvas2DLayerBridge_h
-#define Canvas2DLayerBridge_h
-
-#include "SkDeferredCanvas.h"
-#include "SkImage.h"
-#include "core/platform/graphics/GraphicsContext3D.h"
-#include "core/platform/graphics/IntSize.h"
-#include "public/platform/WebExternalTextureLayer.h"
-#include "public/platform/WebExternalTextureLayerClient.h"
-#include "public/platform/WebExternalTextureMailbox.h"
-#include "wtf/DoublyLinkedList.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/RefPtr.h"
-
-namespace WebKit {
-class WebGraphicsContext3D;
-}
-
-namespace WebCore {
-
-class Canvas2DLayerBridge;
-class PassCanvas2DLayerBridgePtr;
-
-class Canvas2DLayerBridgePtr {
-public:
- Canvas2DLayerBridgePtr() { }
- Canvas2DLayerBridgePtr(const PassRefPtr<Canvas2DLayerBridge>& ptr) { m_ptr = ptr; }
- ~Canvas2DLayerBridgePtr() { clear(); }
- Canvas2DLayerBridge* operator->() const { return m_ptr.get(); }
- Canvas2DLayerBridgePtr& operator=(const PassRefPtr<Canvas2DLayerBridge>&);
- Canvas2DLayerBridge* get() const { return m_ptr.get(); }
- operator bool () const { return m_ptr; }
- void clear();
- PassRefPtr<Canvas2DLayerBridge> release() WARN_UNUSED_RETURN { return m_ptr.release(); }
-private:
- RefPtr<Canvas2DLayerBridge> m_ptr;
-};
-
-class Canvas2DLayerBridge : public WebKit::WebExternalTextureLayerClient, public SkDeferredCanvas::NotificationClient, public DoublyLinkedListNode<Canvas2DLayerBridge>, public RefCounted<Canvas2DLayerBridge> {
- WTF_MAKE_NONCOPYABLE(Canvas2DLayerBridge);
-public:
- enum OpacityMode {
- Opaque,
- NonOpaque
- };
-
- static PassRefPtr<Canvas2DLayerBridge> create(PassRefPtr<GraphicsContext3D>, const IntSize&, OpacityMode);
-
- virtual ~Canvas2DLayerBridge();
-
- // WebKit::WebExternalTextureLayerClient implementation.
- virtual WebKit::WebGraphicsContext3D* context() OVERRIDE;
- virtual bool prepareMailbox(WebKit::WebExternalTextureMailbox*, WebKit::WebExternalBitmap*) OVERRIDE;
- virtual void mailboxReleased(const WebKit::WebExternalTextureMailbox&) OVERRIDE;
-
- // SkDeferredCanvas::NotificationClient implementation
- virtual void prepareForDraw() OVERRIDE;
- virtual void storageAllocatedForRecordingChanged(size_t) OVERRIDE;
- virtual void flushedDrawCommands() OVERRIDE;
- virtual void skippedPendingDrawCommands() OVERRIDE;
-
- // Methods used by Canvas2DLayerManager
- virtual size_t freeMemoryIfPossible(size_t); // virtual for mocking
- virtual void flush(); // virtual for mocking
- virtual size_t storageAllocatedForRecording(); // virtual for faking
- size_t bytesAllocated() const {return m_bytesAllocated;}
- void limitPendingFrames();
-
- WebKit::WebLayer* layer();
- void contextAcquired();
- PassRefPtr<SkCanvas> getCanvas() { return PassRefPtr<SkCanvas>(m_canvas); }
-
- unsigned backBufferTexture();
-
- bool isValid();
-
-protected:
- void destroy();
- friend class Canvas2DLayerBridgePtr;
- Canvas2DLayerBridge(PassRefPtr<GraphicsContext3D>, PassRefPtr<SkDeferredCanvas>, OpacityMode);
- void setRateLimitingEnabled(bool);
-
- RefPtr<SkDeferredCanvas> m_canvas;
- OwnPtr<WebKit::WebExternalTextureLayer> m_layer;
- RefPtr<GraphicsContext3D> m_context;
- size_t m_bytesAllocated;
- bool m_didRecordDrawCommand;
- bool m_surfaceIsValid;
- int m_framesPending;
- bool m_destructionInProgress;
- bool m_rateLimitingEnabled;
-
- friend class WTF::DoublyLinkedListNode<Canvas2DLayerBridge>;
- Canvas2DLayerBridge* m_next;
- Canvas2DLayerBridge* m_prev;
-
- enum MailboxStatus {
- MailboxInUse,
- MailboxReleased,
- MailboxAvailable,
- };
-
- struct MailboxInfo {
- WebKit::WebExternalTextureMailbox m_mailbox;
- SkAutoTUnref<SkImage> m_image;
- MailboxStatus m_status;
- RefPtr<Canvas2DLayerBridge> m_parentLayerBridge;
-
- MailboxInfo(const MailboxInfo&);
- MailboxInfo() {}
- };
- MailboxInfo* createMailboxInfo();
-
- uint32_t m_lastImageId;
- Vector<MailboxInfo> m_mailboxes;
-};
-}
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/Canvas2DLayerBridgeTest.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/Canvas2DLayerBridgeTest.cpp
deleted file mode 100644
index 48cbd7d7fbc..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/Canvas2DLayerBridgeTest.cpp
+++ /dev/null
@@ -1,113 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/platform/graphics/chromium/Canvas2DLayerBridge.h"
-
-#include "SkDeferredCanvas.h"
-#include "SkSurface.h"
-#include "core/platform/graphics/ImageBuffer.h"
-#include "core/tests/FakeWebGraphicsContext3D.h"
-#include "public/platform/Platform.h"
-#include "public/platform/WebThread.h"
-#include "third_party/skia/include/core/SkDevice.h"
-#include "wtf/RefPtr.h"
-
-#include <gmock/gmock.h>
-#include <gtest/gtest.h>
-
-using namespace WebCore;
-using namespace WebKit;
-using testing::InSequence;
-using testing::Return;
-using testing::Test;
-
-namespace {
-
-class MockCanvasContext : public FakeWebGraphicsContext3D {
-public:
- MOCK_METHOD0(flush, void(void));
- MOCK_METHOD0(createTexture, unsigned(void));
- MOCK_METHOD1(deleteTexture, void(unsigned));
-
- virtual GrGLInterface* onCreateGrGLInterface() OVERRIDE { return 0; }
-};
-
-class FakeCanvas2DLayerBridge : public Canvas2DLayerBridge {
-public:
- static PassRefPtr<Canvas2DLayerBridge> create(PassRefPtr<GraphicsContext3D> context, SkDeferredCanvas* canvas, OpacityMode opacityMode)
- {
- return adoptRef(static_cast<Canvas2DLayerBridge*>(new FakeCanvas2DLayerBridge(context, canvas, opacityMode)));
- }
-protected:
- FakeCanvas2DLayerBridge(PassRefPtr<GraphicsContext3D> context, SkDeferredCanvas* canvas, OpacityMode opacityMode) :
- Canvas2DLayerBridge(context, canvas, opacityMode)
- { }
-};
-
-} // namespace
-
-class Canvas2DLayerBridgeTest : public Test {
-protected:
- void fullLifecycleTest()
- {
- RefPtr<GraphicsContext3D> mainContext = GraphicsContext3D::createGraphicsContextFromWebContext(adoptPtr(new MockCanvasContext));
-
- MockCanvasContext& mainMock = *static_cast<MockCanvasContext*>(mainContext->webContext());
-
- SkImage::Info info = {
- 300,
- 150,
- SkImage::kPMColor_ColorType,
- SkImage::kPremul_AlphaType,
- };
- SkAutoTUnref<SkDeferredCanvas> canvas(SkDeferredCanvas::Create(SkSurface::NewRaster(info)));
-
- ::testing::Mock::VerifyAndClearExpectations(&mainMock);
-
- Canvas2DLayerBridgePtr bridge = FakeCanvas2DLayerBridge::create(mainContext.release(), canvas.get(), Canvas2DLayerBridge::NonOpaque);
-
- ::testing::Mock::VerifyAndClearExpectations(&mainMock);
-
- EXPECT_CALL(mainMock, flush());
- unsigned textureId = bridge->backBufferTexture();
- EXPECT_EQ(textureId, 0u);
-
- ::testing::Mock::VerifyAndClearExpectations(&mainMock);
-
- bridge.clear();
-
- ::testing::Mock::VerifyAndClearExpectations(&mainMock);
- }
-};
-
-namespace {
-
-TEST_F(Canvas2DLayerBridgeTest, testFullLifecycleSingleThreaded)
-{
- fullLifecycleTest();
-}
-
-} // namespace
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/Canvas2DLayerManager.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/Canvas2DLayerManager.cpp
deleted file mode 100644
index ed38bd3d4cf..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/Canvas2DLayerManager.cpp
+++ /dev/null
@@ -1,166 +0,0 @@
-/*
-Copyright (C) 2012 Google Inc. All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions
-are met:
-1. Redistributions of source code must retain the above copyright
- notice, this list of conditions and the following disclaimer.
-2. Redistributions in binary form must reproduce the above copyright
- notice, this list of conditions and the following disclaimer in the
- documentation and/or other materials provided with the distribution.
-
-THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
-EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
-DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
-(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
-LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
-ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
-SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-*/
-#include "config.h"
-
-#include "core/platform/graphics/chromium/Canvas2DLayerManager.h"
-
-#include "public/platform/Platform.h"
-#include "wtf/StdLibExtras.h"
-
-using WebKit::WebThread;
-
-namespace {
-enum {
- DefaultMaxBytesAllocated = 64*1024*1024,
- DefaultTargetBytesAllocated = 16*1024*1024,
-};
-}
-
-namespace WebCore {
-
-Canvas2DLayerManager::Canvas2DLayerManager()
- : m_bytesAllocated(0)
- , m_maxBytesAllocated(DefaultMaxBytesAllocated)
- , m_targetBytesAllocated(DefaultTargetBytesAllocated)
- , m_taskObserverActive(false)
-{
-}
-
-Canvas2DLayerManager::~Canvas2DLayerManager()
-{
- ASSERT(!m_bytesAllocated);
- ASSERT(!m_layerList.head());
- ASSERT(!m_taskObserverActive);
-}
-
-void Canvas2DLayerManager::init(size_t maxBytesAllocated, size_t targetBytesAllocated)
-{
- ASSERT(maxBytesAllocated >= targetBytesAllocated);
- m_maxBytesAllocated = maxBytesAllocated;
- m_targetBytesAllocated = targetBytesAllocated;
- if (m_taskObserverActive) {
- WebKit::Platform::current()->currentThread()->removeTaskObserver(this);
- m_taskObserverActive = false;
- }
-}
-
-Canvas2DLayerManager& Canvas2DLayerManager::get()
-{
- DEFINE_STATIC_LOCAL(Canvas2DLayerManager, manager, ());
- return manager;
-}
-
-void Canvas2DLayerManager::willProcessTask()
-{
-}
-
-void Canvas2DLayerManager::didProcessTask()
-{
- // Called after the script action for the current frame has been processed.
- ASSERT(m_taskObserverActive);
- WebKit::Platform::current()->currentThread()->removeTaskObserver(this);
- m_taskObserverActive = false;
- for (Canvas2DLayerBridge* layer = m_layerList.head(); layer; layer = layer->next())
- layer->limitPendingFrames();
-}
-
-void Canvas2DLayerManager::layerDidDraw(Canvas2DLayerBridge* layer)
-{
- if (isInList(layer)) {
- if (layer != m_layerList.head()) {
- m_layerList.remove(layer);
- m_layerList.push(layer); // Set as MRU
- }
- } else
- addLayerToList(layer);
-
- if (!m_taskObserverActive) {
- m_taskObserverActive = true;
- // Schedule a call to didProcessTask() after completion of the current script task.
- WebKit::Platform::current()->currentThread()->addTaskObserver(this);
- }
-}
-
-void Canvas2DLayerManager::addLayerToList(Canvas2DLayerBridge* layer)
-{
- ASSERT(!isInList(layer));
- m_bytesAllocated += layer->bytesAllocated();
- m_layerList.push(layer); // Set as MRU
-}
-
-void Canvas2DLayerManager::layerAllocatedStorageChanged(Canvas2DLayerBridge* layer, intptr_t deltaBytes)
-{
- if (!isInList(layer))
- addLayerToList(layer);
- else {
- ASSERT((intptr_t)m_bytesAllocated + deltaBytes >= 0);
- m_bytesAllocated = (intptr_t)m_bytesAllocated + deltaBytes;
- }
- if (deltaBytes > 0)
- freeMemoryIfNecessary();
-}
-
-void Canvas2DLayerManager::layerToBeDestroyed(Canvas2DLayerBridge* layer)
-{
- if (isInList(layer))
- removeLayerFromList(layer);
-}
-
-void Canvas2DLayerManager::freeMemoryIfNecessary()
-{
- if (m_bytesAllocated > m_maxBytesAllocated) {
- // Pass 1: Free memory from caches
- Canvas2DLayerBridge* layer = m_layerList.tail(); // LRU
- while (m_bytesAllocated > m_targetBytesAllocated && layer) {
- layer->freeMemoryIfPossible(m_bytesAllocated - m_targetBytesAllocated);
- layer = layer->prev();
- }
-
- // Pass 2: Flush canvases
- Canvas2DLayerBridge* leastRecentlyUsedLayer = m_layerList.tail();
- while (m_bytesAllocated > m_targetBytesAllocated && leastRecentlyUsedLayer) {
- leastRecentlyUsedLayer->flush();
- leastRecentlyUsedLayer->freeMemoryIfPossible(~0);
- removeLayerFromList(leastRecentlyUsedLayer);
- leastRecentlyUsedLayer = m_layerList.tail();
- }
- }
-}
-
-void Canvas2DLayerManager::removeLayerFromList(Canvas2DLayerBridge* layer)
-{
- ASSERT(isInList(layer));
- m_bytesAllocated -= layer->bytesAllocated();
- m_layerList.remove(layer);
- layer->setNext(0);
- layer->setPrev(0);
-}
-
-bool Canvas2DLayerManager::isInList(Canvas2DLayerBridge* layer)
-{
- return layer->prev() || m_layerList.head() == layer;
-}
-
-}
-
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/Canvas2DLayerManager.h b/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/Canvas2DLayerManager.h
deleted file mode 100644
index 3379cec730b..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/Canvas2DLayerManager.h
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
-Copyright (C) 2012 Google Inc. All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions
-are met:
-1. Redistributions of source code must retain the above copyright
- notice, this list of conditions and the following disclaimer.
-2. Redistributions in binary form must reproduce the above copyright
- notice, this list of conditions and the following disclaimer in the
- documentation and/or other materials provided with the distribution.
-
-THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
-EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
-DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
-(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
-LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
-ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
-SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-*/
-
-#ifndef Canvas2DLayerManager_h
-#define Canvas2DLayerManager_h
-
-#include "core/platform/graphics/chromium/Canvas2DLayerBridge.h"
-#include "public/platform/WebThread.h"
-
-class Canvas2DLayerManagerTest;
-
-namespace WebCore {
-
-class Canvas2DLayerManager : public WebKit::WebThread::TaskObserver {
-public:
- static Canvas2DLayerManager& get();
- void init(size_t maxBytesAllocated, size_t targetBytesAllocated);
- virtual ~Canvas2DLayerManager();
-
- void layerAllocatedStorageChanged(Canvas2DLayerBridge*, intptr_t deltaBytes);
- void layerDidDraw(Canvas2DLayerBridge*);
- void layerToBeDestroyed(Canvas2DLayerBridge*);
-private:
- Canvas2DLayerManager();
-
- // internal methods
- void freeMemoryIfNecessary();
- bool isInList(Canvas2DLayerBridge*);
- void addLayerToList(Canvas2DLayerBridge*);
- void removeLayerFromList(Canvas2DLayerBridge*);
- virtual void willProcessTask() OVERRIDE;
- virtual void didProcessTask() OVERRIDE;
-
- size_t m_bytesAllocated;
- size_t m_maxBytesAllocated;
- size_t m_targetBytesAllocated;
- bool m_taskObserverActive;
- DoublyLinkedList<Canvas2DLayerBridge> m_layerList;
-
- friend class ::Canvas2DLayerManagerTest; // for unit testing
-};
-
-}
-
-#endif
-
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/Canvas2DLayerManagerTest.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/Canvas2DLayerManagerTest.cpp
deleted file mode 100644
index 7f45ae99a17..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/Canvas2DLayerManagerTest.cpp
+++ /dev/null
@@ -1,268 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/platform/graphics/chromium/Canvas2DLayerManager.h"
-
-#include "SkDevice.h"
-#include "SkSurface.h"
-#include "core/platform/graphics/GraphicsContext3D.h"
-#include "core/tests/FakeWebGraphicsContext3D.h"
-#include "public/platform/Platform.h"
-#include "public/platform/WebThread.h"
-
-#include <gmock/gmock.h>
-#include <gtest/gtest.h>
-
-using namespace WebCore;
-using testing::InSequence;
-using testing::Return;
-using testing::Test;
-
-
-class FakeCanvas2DLayerBridge : public Canvas2DLayerBridge {
-public:
- FakeCanvas2DLayerBridge(PassRefPtr<GraphicsContext3D> context, SkDeferredCanvas* canvas)
- : Canvas2DLayerBridge(context, canvas, NonOpaque)
- , m_freeableBytes(0)
- , m_freeMemoryIfPossibleCount(0)
- , m_flushCount(0)
- {
- }
-
- virtual size_t storageAllocatedForRecording() OVERRIDE
- {
- // Because the fake layer has no canvas to query, just
- // return status quo. Allocation changes that would normally be
- // initiated by the canvas can be faked by invoking
- // storageAllocatedForRecordingChanged directly from the test code.
- return m_bytesAllocated;
- }
-
- void fakeFreeableBytes(size_t size)
- {
- m_freeableBytes = size;
- }
-
- virtual size_t freeMemoryIfPossible(size_t size) OVERRIDE
- {
- m_freeMemoryIfPossibleCount++;
- size_t bytesFreed = size < m_freeableBytes ? size : m_freeableBytes;
- m_freeableBytes -= bytesFreed;
- if (bytesFreed)
- Canvas2DLayerManager::get().layerAllocatedStorageChanged(this, -((intptr_t)bytesFreed));
- m_bytesAllocated -= bytesFreed;
- return bytesFreed;
- }
-
- virtual void flush() OVERRIDE
- {
- flushedDrawCommands();
- m_flushCount++;
- }
-
-public:
- size_t m_freeableBytes;
- int m_freeMemoryIfPossibleCount;
- int m_flushCount;
-};
-
-static PassOwnPtr<SkDeferredCanvas> createCanvas(GraphicsContext3D* context)
-{
- SkImage::Info info = {
- 1,
- 1,
- SkImage::kPMColor_ColorType,
- SkImage::kPremul_AlphaType,
- };
- return adoptPtr(SkDeferredCanvas::Create(SkSurface::NewRaster(info)));
-}
-
-FakeCanvas2DLayerBridge* fake(const Canvas2DLayerBridgePtr& layer)
-{
- return static_cast<FakeCanvas2DLayerBridge*>(layer.get());
-}
-
-class Canvas2DLayerManagerTest : public Test {
-protected:
- void storageAllocationTrackingTest()
- {
- Canvas2DLayerManager& manager = Canvas2DLayerManager::get();
- manager.init(10, 10);
- {
- RefPtr<GraphicsContext3D> context = GraphicsContext3D::createGraphicsContextFromWebContext(adoptPtr(new WebKit::FakeWebGraphicsContext3D));
- OwnPtr<SkDeferredCanvas> canvas1 = createCanvas(context.get());
- Canvas2DLayerBridgePtr layer1(adoptRef(new FakeCanvas2DLayerBridge(context, canvas1.get())));
- EXPECT_EQ((size_t)0, manager.m_bytesAllocated);
- layer1->storageAllocatedForRecordingChanged(1);
- EXPECT_EQ((size_t)1, manager.m_bytesAllocated);
- // Test allocation increase
- layer1->storageAllocatedForRecordingChanged(2);
- EXPECT_EQ((size_t)2, manager.m_bytesAllocated);
- // Test allocation decrease
- layer1->storageAllocatedForRecordingChanged(1);
- EXPECT_EQ((size_t)1, manager.m_bytesAllocated);
- {
- OwnPtr<SkDeferredCanvas> canvas2 = createCanvas(context.get());
- Canvas2DLayerBridgePtr layer2(adoptRef(new FakeCanvas2DLayerBridge(context, canvas2.get())));
- EXPECT_EQ((size_t)1, manager.m_bytesAllocated);
- // verify multi-layer allocation tracking
- layer2->storageAllocatedForRecordingChanged(2);
- EXPECT_EQ((size_t)3, manager.m_bytesAllocated);
- }
- // Verify tracking after destruction
- EXPECT_EQ((size_t)1, manager.m_bytesAllocated);
- }
- }
-
- void evictionTest()
- {
- RefPtr<GraphicsContext3D> context = GraphicsContext3D::createGraphicsContextFromWebContext(adoptPtr(new WebKit::FakeWebGraphicsContext3D));
- Canvas2DLayerManager& manager = Canvas2DLayerManager::get();
- manager.init(10, 5);
- OwnPtr<SkDeferredCanvas> canvas = createCanvas(context.get());
- Canvas2DLayerBridgePtr layer(adoptRef(new FakeCanvas2DLayerBridge(context, canvas.get())));
- fake(layer)->fakeFreeableBytes(10);
- layer->storageAllocatedForRecordingChanged(8); // under the max
- EXPECT_EQ(0, fake(layer)->m_freeMemoryIfPossibleCount);
- layer->storageAllocatedForRecordingChanged(12); // over the max
- EXPECT_EQ(1, fake(layer)->m_freeMemoryIfPossibleCount);
- EXPECT_EQ((size_t)3, fake(layer)->m_freeableBytes);
- EXPECT_EQ(0, fake(layer)->m_flushCount); // eviction succeeded without triggering a flush
- EXPECT_EQ((size_t)5, layer->bytesAllocated());
- }
-
- void flushEvictionTest()
- {
- RefPtr<GraphicsContext3D> context = GraphicsContext3D::createGraphicsContextFromWebContext(adoptPtr(new WebKit::FakeWebGraphicsContext3D));
- Canvas2DLayerManager& manager = Canvas2DLayerManager::get();
- manager.init(10, 5);
- OwnPtr<SkDeferredCanvas> canvas = createCanvas(context.get());
- Canvas2DLayerBridgePtr layer(adoptRef(new FakeCanvas2DLayerBridge(context, canvas.get())));
- fake(layer)->fakeFreeableBytes(1); // Not enough freeable bytes, will cause aggressive eviction by flushing
- layer->storageAllocatedForRecordingChanged(8); // under the max
- EXPECT_EQ(0, fake(layer)->m_freeMemoryIfPossibleCount);
- layer->storageAllocatedForRecordingChanged(12); // over the max
- EXPECT_EQ(2, fake(layer)->m_freeMemoryIfPossibleCount); // Two tries, one before flush, one after flush
- EXPECT_EQ((size_t)0, fake(layer)->m_freeableBytes);
- EXPECT_EQ(1, fake(layer)->m_flushCount); // flush was attempted
- EXPECT_EQ((size_t)11, layer->bytesAllocated()); // flush drops the layer from manager's tracking list
- EXPECT_FALSE(manager.isInList(layer.get()));
- }
-
- void doDeferredFrameTestTask(FakeCanvas2DLayerBridge* layer, bool skipCommands)
- {
- EXPECT_FALSE(Canvas2DLayerManager::get().m_taskObserverActive);
- layer->contextAcquired();
- layer->storageAllocatedForRecordingChanged(1);
- EXPECT_TRUE(Canvas2DLayerManager::get().m_taskObserverActive);
- if (skipCommands) {
- layer->contextAcquired();
- layer->storageAllocatedForRecordingChanged(0);
- layer->skippedPendingDrawCommands();
- }
- WebKit::Platform::current()->currentThread()->exitRunLoop();
- }
-
- class DeferredFrameTestTask : public WebKit::WebThread::Task {
- public:
- DeferredFrameTestTask(Canvas2DLayerManagerTest* test, FakeCanvas2DLayerBridge* layer, bool skipCommands)
- {
- m_test = test;
- m_layer = layer;
- m_skipCommands = skipCommands;
- }
-
- virtual void run() OVERRIDE
- {
- m_test->doDeferredFrameTestTask(m_layer, m_skipCommands);
- }
- private:
- Canvas2DLayerManagerTest* m_test;
- FakeCanvas2DLayerBridge* m_layer;
- bool m_skipCommands;
- };
-
- void deferredFrameTest()
- {
- RefPtr<GraphicsContext3D> context = GraphicsContext3D::createGraphicsContextFromWebContext(adoptPtr(new WebKit::FakeWebGraphicsContext3D));
- Canvas2DLayerManager::get().init(10, 10);
- OwnPtr<SkDeferredCanvas> canvas = createCanvas(context.get());
- Canvas2DLayerBridgePtr layer(adoptRef(new FakeCanvas2DLayerBridge(context, canvas.get())));
- WebKit::Platform::current()->currentThread()->postTask(new DeferredFrameTestTask(this, fake(layer), true));
- WebKit::Platform::current()->currentThread()->enterRunLoop();
- // Verify that didProcessTask was called upon completion
- EXPECT_FALSE(Canvas2DLayerManager::get().m_taskObserverActive);
- // Verify that no flush was performed because frame is fresh
- EXPECT_EQ(0, fake(layer)->m_flushCount);
-
- // Verify that no flushes are triggered as long as frame are fresh
- WebKit::Platform::current()->currentThread()->postTask(new DeferredFrameTestTask(this, fake(layer), true));
- WebKit::Platform::current()->currentThread()->enterRunLoop();
- EXPECT_FALSE(Canvas2DLayerManager::get().m_taskObserverActive);
- EXPECT_EQ(0, fake(layer)->m_flushCount);
-
- WebKit::Platform::current()->currentThread()->postTask(new DeferredFrameTestTask(this, fake(layer), true));
- WebKit::Platform::current()->currentThread()->enterRunLoop();
- EXPECT_FALSE(Canvas2DLayerManager::get().m_taskObserverActive);
- EXPECT_EQ(0, fake(layer)->m_flushCount);
-
- // Verify that a flush is triggered when queue is accumulating a multi-frame backlog.
- WebKit::Platform::current()->currentThread()->postTask(new DeferredFrameTestTask(this, fake(layer), false));
- WebKit::Platform::current()->currentThread()->enterRunLoop();
- EXPECT_FALSE(Canvas2DLayerManager::get().m_taskObserverActive);
- EXPECT_EQ(1, fake(layer)->m_flushCount);
-
- WebKit::Platform::current()->currentThread()->postTask(new DeferredFrameTestTask(this, fake(layer), false));
- WebKit::Platform::current()->currentThread()->enterRunLoop();
- EXPECT_FALSE(Canvas2DLayerManager::get().m_taskObserverActive);
- EXPECT_EQ(2, fake(layer)->m_flushCount);
- }
-};
-
-namespace {
-
-TEST_F(Canvas2DLayerManagerTest, testStorageAllocationTracking)
-{
- storageAllocationTrackingTest();
-}
-
-TEST_F(Canvas2DLayerManagerTest, testEviction)
-{
- evictionTest();
-}
-
-TEST_F(Canvas2DLayerManagerTest, testFlushEviction)
-{
- flushEvictionTest();
-}
-
-TEST_F(Canvas2DLayerManagerTest, testDeferredFrame)
-{
- deferredFrameTest();
-}
-
-} // namespace
-
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/CrossProcessFontLoading.h b/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/CrossProcessFontLoading.h
deleted file mode 100644
index 782c83742a2..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/CrossProcessFontLoading.h
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * Copyright (c) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef CrossProcessFontLoading_h
-#define CrossProcessFontLoading_h
-
-#import <wtf/RefCounted.h>
-#import <wtf/RetainPtr.h>
-#import <wtf/text/WTFString.h>
-
-typedef struct CGFont* CGFontRef;
-
-namespace WebCore {
-
-// MemoryActivatedFont encapsulates a font loaded from another process and
-// activated from memory.
-//
-// Responsibilities:
-// * Holder for the CGFontRef & ATSFontRef belonging to the activated font.
-// * Responsible for unloading the font container when done.
-//
-// Memory Management:
-// The class is reference counted, with each instance of FontPlatformData that
-// uses this class holding a reference to it.
-// Entries are kept track of internally in a hash to allow quick lookup
-// of existing instances for reuse:
-// - fontCacheBySrcFontContainerRef() - key is the ATSFontContainerRef
-// corresponding to the *original in-process NSFont* whose loading was blocked
-// by the sandbox.
-// This is needed to allow lookup of a pre-existing MemoryActivatedFont when
-// creating a new FontPlatformData object.
-//
-// Assumptions:
-// This code assumes that an ATSFontRef is a unique identifier tied to an
-// activated font. i.e. After we activate a font, its ATSFontRef doesn't
-// change.
-// It also assumes that the ATSFoncontainerRef for two in-memory NSFonts that
-// correspond to the same on-disk font file are always the same and don't change
-// with time.
-//
-// Flushing caches:
-// When the system notifies us of a system font cache flush, all FontDataCache
-// objects are destroyed. This should in turn dereference all
-// MemoryActivatedFonts and thus unload all in-memory fonts.
-class MemoryActivatedFont : public RefCounted<MemoryActivatedFont> {
-public:
- // Use to create a new object, see docs on constructor below.
- static PassRefPtr<MemoryActivatedFont> create(uint32_t fontID, NSFont*, CGFontRef);
- ~MemoryActivatedFont();
-
- // Get cached CGFontRef corresponding to the in-memory font.
- CGFontRef cgFont() { return m_cgFont.get(); }
-
-private:
- // srcFontRef - ATSFontRef belonging to the NSFont object that failed to
- // load in-process.
- // container - a font container corresponding to an identical font that
- // we loaded cross-process.
- MemoryActivatedFont(uint32_t fontID, NSFont*, CGFontRef);
-
- WTF::RetainPtr<CGFontRef> m_cgFont;
- uint32_t m_fontID;
- WTF::String m_inSandboxHashKey;
-};
-
-} // namespace WebCore
-
-#endif // CrossProcessFontLoading_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/CrossProcessFontLoading.mm b/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/CrossProcessFontLoading.mm
deleted file mode 100644
index 0394e78536c..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/CrossProcessFontLoading.mm
+++ /dev/null
@@ -1,207 +0,0 @@
-/*
- * This file is part of the internal font implementation.
- *
- * Copyright (c) 2010 Google Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-// This file provides additional functionality to the Mac FontPlatformData class
-// defined in WebCore/platform/cocoa/FontPlatformDataCocoa.mm .
-// Because we want to support loading fonts between processes in the face of
-// font loading being blocked by the sandbox, we need a mechnasim to both
-// do the loading of in-memory fonts and keep track of them.
-
-#import "config.h"
-#import "core/platform/graphics/chromium/CrossProcessFontLoading.h"
-
-#import <AppKit/NSFont.h>
-#import "core/platform/graphics/FontPlatformData.h"
-#include "core/platform/LinkHash.h"
-#import "public/platform/mac/WebSandboxSupport.h"
-#import "public/platform/Platform.h"
-#import "wtf/HashMap.h"
-
-namespace WebCore {
-
-namespace {
-
-typedef HashMap<uint32, MemoryActivatedFont*> FontContainerRefMemoryFontHash;
-typedef HashMap<WTF::String, MemoryActivatedFont*> FontNameMemoryFontHash;
-
-// Caching:
-//
-// Requesting a font from the browser process is expensive and so is
-// "activating" said font. Caching of loaded fonts is complicated by the fact
-// that it's impossible to get a unique identifier for the on-disk font file
-// from inside the sandboxed renderer process.
-// This means that when loading a font we need to round-trip through the browser
-// process in order to get the unique font file identifer which we might already
-// have activated and cached.
-//
-// In order to save as much work as we can, we maintain 2 levels of caching
-// for the font data:
-// 1. A dumb cache keyed by the font name/style (information we can determine
-// from inside the sandbox).
-// 2. A smarter cache keyed by the real "unique font id".
-//
-// In order to perform a lookup in #2 we need to consult with the browser to get
-// us the lookup key. While this doesn't save us the font load, it does save
-// us font activation.
-//
-// It's important to remember that existing FontPlatformData objects are already
-// cached, so a cache miss in the code in this file isn't necessarily so bad.
-
-FontContainerRefMemoryFontHash& fontCacheByFontID()
-{
- DEFINE_STATIC_LOCAL(FontContainerRefMemoryFontHash, srcFontIDCache, ());
- return srcFontIDCache;
-}
-
-
-FontNameMemoryFontHash& fontCacheByFontName()
-{
- DEFINE_STATIC_LOCAL(FontNameMemoryFontHash, srcFontNameCache, ());
- return srcFontNameCache;
-}
-
-// Given a font specified by |srcFont|, use the information we can query in
-// the sandbox to construct a key which we hope will be as unique as possible
-// to the containing font file.
-WTF::String hashKeyFromNSFont(NSFont* srcFont)
-{
- NSFontDescriptor* desc = [srcFont fontDescriptor];
- NSFontSymbolicTraits traits = [desc symbolicTraits];
- return WTF::String::format("%s %x", [[srcFont fontName] UTF8String], traits);
-}
-
-// The only way we can tell that an in-process font has failed to load
-// is if CTFontCopyGraphicsFont() returns the LastResort font.
-bool isLastResortFont(CGFontRef cgFont)
-{
- NSString* fontName = (NSString*)CGFontCopyPostScriptName(cgFont);
- return [fontName isEqualToString:@"LastResort"];
-}
-
-// Given an in-process font which has failed to load, return a
-// MemoryActivatedFont* corresponding to an in-memory representation of the
-// same font loaded from the browser process.
-// On failure this function returns a PassRefPtr pointing to 0.
-PassRefPtr<MemoryActivatedFont> loadFontFromBrowserProcess(NSFont* nsFont)
-{
- // First try to lookup in our cache with the limited information we have.
- WTF::String hashKey = hashKeyFromNSFont(nsFont);
- RefPtr<MemoryActivatedFont> font(fontCacheByFontName().get(hashKey));
- if (font)
- return font;
-
- CGFontRef tmpCGFont;
- uint32_t fontID;
- // Send cross-process request to load font.
- WebKit::WebSandboxSupport* sandboxSupport = WebKit::Platform::current()->sandboxSupport();
- if (!sandboxSupport) {
- // This function should only be called in response to an error loading a
- // font due to being blocked by the sandbox.
- // This by definition shouldn't happen if there is no sandbox support.
- ASSERT_NOT_REACHED();
- return 0;
- }
- if (!sandboxSupport->loadFont(nsFont, &tmpCGFont, &fontID))
- return 0;
-
- RetainPtr<CGFontRef> cgFont(tmpCGFont);
- // Now that we have the fontID from the browser process, we can consult
- // the ID cache.
- font = fontCacheByFontID().get(fontID);
- if (font)
- // FIXME: WebSandboxSupport::loadFont() should consult the id cache
- // before activating the font.
- return font;
-
- return MemoryActivatedFont::create(fontID, nsFont, cgFont.get());
-}
-
-} // namespace
-
-PassRefPtr<MemoryActivatedFont> MemoryActivatedFont::create(uint32_t fontID, NSFont* nsFont, CGFontRef cgFont)
-{
- return adoptRef(new MemoryActivatedFont(fontID, nsFont, cgFont));
-}
-
-MemoryActivatedFont::MemoryActivatedFont(uint32_t fontID, NSFont* nsFont, CGFontRef cgFont)
- : m_cgFont(cgFont)
- , m_fontID(fontID)
- , m_inSandboxHashKey(hashKeyFromNSFont(nsFont))
-{
- // Add ourselves to caches.
- fontCacheByFontID().add(fontID, this);
- fontCacheByFontName().add(m_inSandboxHashKey, this);
-}
-
-// Destructor - Unload font container from memory and remove ourselves
-// from cache.
-MemoryActivatedFont::~MemoryActivatedFont()
-{
- // First remove ourselves from the caches.
- ASSERT(fontCacheByFontID().contains(m_fontID));
- ASSERT(fontCacheByFontName().contains(m_inSandboxHashKey));
-
- fontCacheByFontID().remove(m_fontID);
- fontCacheByFontName().remove(m_inSandboxHashKey);
-}
-
-// Given an NSFont, try to load a representation of that font into the cgFont
-// parameter. If loading is blocked by the sandbox, the font may be loaded
-// cross-process.
-// If sandbox loading also fails, a fallback font is loaded.
-//
-// Considerations:
-// * cgFont must be CFRelease()ed by the caller when done.
-//
-// Parameters:
-// * nsFont - The font we wish to load.
-// * fontSize - point size of the font we wish to load.
-// * outNSFont - The font that was actually loaded or null if loading failed.
-// * cgFont - on output this contains the CGFontRef corresponding to the NSFont
-// that was picked in the end. The caller is responsible for calling
-// CFRelease() on this parameter when done with it.
-// * fontID - on output, the ID corresponding to nsFont.
-void FontPlatformData::loadFont(NSFont* nsFont, float fontSize, NSFont*& outNSFont, CGFontRef& cgFont)
-{
- outNSFont = nsFont;
- cgFont = CTFontCopyGraphicsFont(toCTFontRef(outNSFont), 0);
- if (outNSFont && cgFont && isLastResortFont(cgFont)) {
- // Release old CGFontRef since it points at the LastResort font which we don't want.
- CFRelease(cgFont);
- cgFont = 0;
-
- // Font loading was blocked by the Sandbox.
- m_inMemoryFont = loadFontFromBrowserProcess(outNSFont);
- if (m_inMemoryFont) {
- cgFont = m_inMemoryFont->cgFont();
-
- // Need to add an extra retain so output semantics of this function
- // are consistent.
- CFRetain(cgFont);
- } else {
- // If we still can't load the font, set |outNSFont| to null so that FontPlatformData won't be used.
- outNSFont = 0;
- }
- }
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/DeferredImageDecoder.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/DeferredImageDecoder.cpp
deleted file mode 100644
index 1d4556089e7..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/DeferredImageDecoder.cpp
+++ /dev/null
@@ -1,279 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/chromium/DeferredImageDecoder.h"
-
-#include "core/platform/graphics/chromium/ImageFrameGenerator.h"
-#include "core/platform/graphics/chromium/LazyDecodingPixelRef.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/PassOwnPtr.h"
-
-namespace WebCore {
-
-namespace {
-
-// URI label for a lazily decoded SkPixelRef.
-const char labelLazyDecoded[] = "lazy";
-
-} // namespace
-
-bool DeferredImageDecoder::s_enabled = false;
-
-DeferredImageDecoder::DeferredImageDecoder(PassOwnPtr<ImageDecoder> actualDecoder)
- : m_allDataReceived(false)
- , m_actualDecoder(actualDecoder)
- , m_orientation(DefaultImageOrientation)
- , m_repetitionCount(cAnimationNone)
-{
-}
-
-DeferredImageDecoder::~DeferredImageDecoder()
-{
-}
-
-PassOwnPtr<DeferredImageDecoder> DeferredImageDecoder::create(const SharedBuffer& data, ImageSource::AlphaOption alphaOption, ImageSource::GammaAndColorProfileOption gammaAndColorOption)
-{
- OwnPtr<ImageDecoder> actualDecoder = ImageDecoder::create(data, alphaOption, gammaAndColorOption);
- return actualDecoder ? adoptPtr(new DeferredImageDecoder(actualDecoder.release())) : nullptr;
-}
-
-PassOwnPtr<DeferredImageDecoder> DeferredImageDecoder::createForTesting(PassOwnPtr<ImageDecoder> decoder)
-{
- return adoptPtr(new DeferredImageDecoder(decoder));
-}
-
-bool DeferredImageDecoder::isLazyDecoded(const SkBitmap& bitmap)
-{
- return bitmap.pixelRef()
- && bitmap.pixelRef()->getURI()
- && !memcmp(bitmap.pixelRef()->getURI(), labelLazyDecoded, sizeof(labelLazyDecoded));
-}
-
-SkBitmap DeferredImageDecoder::createResizedLazyDecodingBitmap(const SkBitmap& bitmap, const SkISize& scaledSize, const SkIRect& scaledSubset)
-{
- LazyDecodingPixelRef* pixelRef = static_cast<LazyDecodingPixelRef*>(bitmap.pixelRef());
-
- int rowBytes = 0;
- rowBytes = SkBitmap::ComputeRowBytes(SkBitmap::kARGB_8888_Config, scaledSize.width());
-
- SkBitmap resizedBitmap;
- resizedBitmap.setConfig(SkBitmap::kARGB_8888_Config, scaledSubset.width(), scaledSubset.height(), rowBytes);
-
- // FIXME: This code has the potential problem that multiple
- // LazyDecodingPixelRefs are created even though they share the same
- // scaled size and ImageFrameGenerator.
- resizedBitmap.setPixelRef(new LazyDecodingPixelRef(pixelRef->frameGenerator(), scaledSize, pixelRef->frameIndex(), scaledSubset))->unref();
-
- // See comments in createLazyDecodingBitmap().
- resizedBitmap.setImmutable();
- return resizedBitmap;
-}
-
-void DeferredImageDecoder::setEnabled(bool enabled)
-{
- s_enabled = enabled;
-}
-
-String DeferredImageDecoder::filenameExtension() const
-{
- return m_actualDecoder ? m_actualDecoder->filenameExtension() : m_filenameExtension;
-}
-
-ImageFrame* DeferredImageDecoder::frameBufferAtIndex(size_t index)
-{
- prepareLazyDecodedFrames();
- if (index < m_lazyDecodedFrames.size()) {
- // ImageFrameGenerator has the latest known alpha state. There will
- // be a performance boost if this frame is opaque.
- m_lazyDecodedFrames[index]->setHasAlpha(m_frameGenerator->hasAlpha(index));
- return m_lazyDecodedFrames[index].get();
- }
- if (m_actualDecoder)
- return m_actualDecoder->frameBufferAtIndex(index);
- return 0;
-}
-
-void DeferredImageDecoder::setData(SharedBuffer* data, bool allDataReceived)
-{
- if (m_actualDecoder) {
- m_data = data;
- m_allDataReceived = allDataReceived;
- m_actualDecoder->setData(data, allDataReceived);
- prepareLazyDecodedFrames();
- }
-
- if (m_frameGenerator)
- m_frameGenerator->setData(data, allDataReceived);
-}
-
-bool DeferredImageDecoder::isSizeAvailable()
-{
- // m_actualDecoder is 0 only if image decoding is deferred and that
- // means image header decoded successfully and size is available.
- return m_actualDecoder ? m_actualDecoder->isSizeAvailable() : true;
-}
-
-IntSize DeferredImageDecoder::size() const
-{
- return m_actualDecoder ? m_actualDecoder->size() : m_size;
-}
-
-IntSize DeferredImageDecoder::frameSizeAtIndex(size_t index) const
-{
- // FIXME: Frame size is assumed to be uniform. This might not be true for
- // future supported codecs.
- return m_actualDecoder ? m_actualDecoder->frameSizeAtIndex(index) : m_size;
-}
-
-size_t DeferredImageDecoder::frameCount()
-{
- return m_actualDecoder ? m_actualDecoder->frameCount() : m_lazyDecodedFrames.size();
-}
-
-int DeferredImageDecoder::repetitionCount() const
-{
- return m_actualDecoder ? m_actualDecoder->repetitionCount() : m_repetitionCount;
-}
-
-size_t DeferredImageDecoder::clearCacheExceptFrame(size_t clearExceptFrame)
-{
- // If image decoding is deferred then frame buffer cache is managed by
- // the compositor and this call is ignored.
- return m_actualDecoder ? m_actualDecoder->clearCacheExceptFrame(clearExceptFrame) : 0;
-}
-
-bool DeferredImageDecoder::frameHasAlphaAtIndex(size_t index) const
-{
- if (m_actualDecoder)
- return m_actualDecoder->frameHasAlphaAtIndex(index);
- if (!m_frameGenerator->isMultiFrame())
- return m_frameGenerator->hasAlpha(index);
- return true;
-}
-
-bool DeferredImageDecoder::frameIsCompleteAtIndex(size_t index) const
-{
- if (m_actualDecoder)
- return m_actualDecoder->frameIsCompleteAtIndex(index);
- if (index < m_lazyDecodedFrames.size())
- return m_lazyDecodedFrames[index]->status() == ImageFrame::FrameComplete;
- return false;
-}
-
-float DeferredImageDecoder::frameDurationAtIndex(size_t index) const
-{
- if (m_actualDecoder)
- return m_actualDecoder->frameDurationAtIndex(index);
- if (index < m_lazyDecodedFrames.size())
- return m_lazyDecodedFrames[index]->duration();
- return 0;
-}
-
-unsigned DeferredImageDecoder::frameBytesAtIndex(size_t index) const
-{
- // If frame decoding is deferred then it is not managed by MemoryCache
- // so return 0 here.
- return m_frameGenerator ? 0 : m_actualDecoder->frameBytesAtIndex(index);
-}
-
-ImageOrientation DeferredImageDecoder::orientation() const
-{
- return m_actualDecoder ? m_actualDecoder->orientation() : m_orientation;
-}
-
-void DeferredImageDecoder::activateLazyDecoding()
-{
- if (m_frameGenerator)
- return;
- m_size = m_actualDecoder->size();
- m_orientation = m_actualDecoder->orientation();
- m_filenameExtension = m_actualDecoder->filenameExtension();
- const bool isSingleFrame = m_actualDecoder->repetitionCount() == cAnimationNone || (m_allDataReceived && m_actualDecoder->frameCount() == 1u);
- m_frameGenerator = ImageFrameGenerator::create(SkISize::Make(m_actualDecoder->decodedSize().width(), m_actualDecoder->decodedSize().height()), m_data, m_allDataReceived, !isSingleFrame);
-}
-
-void DeferredImageDecoder::prepareLazyDecodedFrames()
-{
- if (!s_enabled
- || !m_actualDecoder
- || !m_actualDecoder->isSizeAvailable()
- || m_actualDecoder->filenameExtension() == "ico")
- return;
-
- activateLazyDecoding();
-
- const size_t previousSize = m_lazyDecodedFrames.size();
- m_lazyDecodedFrames.resize(m_actualDecoder->frameCount());
- for (size_t i = previousSize; i < m_lazyDecodedFrames.size(); ++i) {
- OwnPtr<ImageFrame> frame(adoptPtr(new ImageFrame()));
- frame->setSkBitmap(createLazyDecodingBitmap(i));
- frame->setDuration(m_actualDecoder->frameDurationAtIndex(i));
- frame->setStatus(m_actualDecoder->frameIsCompleteAtIndex(i) ? ImageFrame::FrameComplete : ImageFrame::FramePartial);
- m_lazyDecodedFrames[i] = frame.release();
- }
-
- // The last lazy decoded frame created from previous call might be
- // incomplete so update its state.
- if (previousSize)
- m_lazyDecodedFrames[previousSize - 1]->setStatus(m_actualDecoder->frameIsCompleteAtIndex(previousSize - 1) ? ImageFrame::FrameComplete : ImageFrame::FramePartial);
-
- if (m_allDataReceived) {
- m_repetitionCount = m_actualDecoder->repetitionCount();
- m_actualDecoder.clear();
- m_data = nullptr;
- }
-}
-
-SkBitmap DeferredImageDecoder::createLazyDecodingBitmap(size_t index)
-{
- SkISize fullSize = SkISize::Make(m_actualDecoder->decodedSize().width(), m_actualDecoder->decodedSize().height());
- ASSERT(!fullSize.isEmpty());
-
- SkIRect fullRect = SkIRect::MakeSize(fullSize);
-
- // Creates a lazily decoded SkPixelRef that references the entire image without scaling.
- SkBitmap bitmap;
- bitmap.setConfig(SkBitmap::kARGB_8888_Config, fullSize.width(), fullSize.height());
- bitmap.setPixelRef(new LazyDecodingPixelRef(m_frameGenerator, fullSize, index, fullRect))->unref();
-
- // Use the URI to identify this as a lazily decoded SkPixelRef of type LazyDecodingPixelRef.
- // FIXME: It would be more useful to give the actual image URI.
- bitmap.pixelRef()->setURI(labelLazyDecoded);
-
- // Inform the bitmap that we will never change the pixels. This is a performance hint
- // subsystems that may try to cache this bitmap (e.g. pictures, pipes, gpu, pdf, etc.)
- bitmap.setImmutable();
-
- return bitmap;
-}
-
-bool DeferredImageDecoder::hotSpot(IntPoint& hotSpot) const
-{
- // TODO: Implement.
- return m_actualDecoder ? m_actualDecoder->hotSpot(hotSpot) : false;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/DeferredImageDecoder.h b/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/DeferredImageDecoder.h
deleted file mode 100644
index 9f3d40e9520..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/DeferredImageDecoder.h
+++ /dev/null
@@ -1,101 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef DeferredImageDecoder_h
-#define DeferredImageDecoder_h
-
-#include "SkBitmap.h"
-#include "core/platform/graphics/ImageSource.h"
-#include "core/platform/graphics/IntSize.h"
-#include "core/platform/image-decoders/ImageDecoder.h"
-#include "wtf/Forward.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-class ImageFrameGenerator;
-class SharedBuffer;
-
-class DeferredImageDecoder {
-public:
- ~DeferredImageDecoder();
- static PassOwnPtr<DeferredImageDecoder> create(const SharedBuffer& data, ImageSource::AlphaOption, ImageSource::GammaAndColorProfileOption);
-
- static PassOwnPtr<DeferredImageDecoder> createForTesting(PassOwnPtr<ImageDecoder>);
-
- static bool isLazyDecoded(const SkBitmap&);
-
- static SkBitmap createResizedLazyDecodingBitmap(const SkBitmap&, const SkISize& scaledSize, const SkIRect& scaledSubset);
-
- static void setEnabled(bool);
-
- String filenameExtension() const;
-
- ImageFrame* frameBufferAtIndex(size_t index);
-
- void setData(SharedBuffer* data, bool allDataReceived);
-
- bool isSizeAvailable();
- IntSize size() const;
- IntSize frameSizeAtIndex(size_t index) const;
- size_t frameCount();
- int repetitionCount() const;
- size_t clearCacheExceptFrame(size_t);
- bool frameHasAlphaAtIndex(size_t index) const;
- bool frameIsCompleteAtIndex(size_t) const;
- float frameDurationAtIndex(size_t) const;
- unsigned frameBytesAtIndex(size_t index) const;
- ImageOrientation orientation() const;
- bool hotSpot(IntPoint&) const;
-
- // For testing.
- ImageFrameGenerator* frameGenerator() { return m_frameGenerator.get(); }
-
-private:
- explicit DeferredImageDecoder(PassOwnPtr<ImageDecoder> actualDecoder);
- void prepareLazyDecodedFrames();
- SkBitmap createLazyDecodingBitmap(size_t index);
- void activateLazyDecoding();
- void setData(PassRefPtr<SharedBuffer>, bool allDataReceived);
-
- RefPtr<SharedBuffer> m_data;
- bool m_allDataReceived;
- OwnPtr<ImageDecoder> m_actualDecoder;
-
- String m_filenameExtension;
- IntSize m_size;
- ImageOrientation m_orientation;
- int m_repetitionCount;
-
- Vector<OwnPtr<ImageFrame> > m_lazyDecodedFrames;
- RefPtr<ImageFrameGenerator> m_frameGenerator;
-
- static bool s_enabled;
-};
-
-} // namespace WebCore
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/DeferredImageDecoderTest.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/DeferredImageDecoderTest.cpp
deleted file mode 100644
index 246e4b8a5cd..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/DeferredImageDecoderTest.cpp
+++ /dev/null
@@ -1,323 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/chromium/DeferredImageDecoder.h"
-
-#include "SkBitmapDevice.h"
-#include "SkCanvas.h"
-#include "SkPicture.h"
-#include "core/platform/SharedBuffer.h"
-#include "core/platform/graphics/chromium/ImageDecodingStore.h"
-#include "core/platform/graphics/chromium/test/MockImageDecoder.h"
-#include "core/platform/graphics/skia/NativeImageSkia.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefPtr.h"
-#include "wtf/Threading.h"
-#include <gtest/gtest.h>
-
-namespace WebCore {
-
-namespace {
-
-// Raw data for a PNG file with 1x1 white pixels.
-const unsigned char whitePNG[] = {
- 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00,
- 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01,
- 0x00, 0x00, 0x00, 0x01, 0x08, 0x02, 0x00, 0x00, 0x00, 0x90,
- 0x77, 0x53, 0xde, 0x00, 0x00, 0x00, 0x01, 0x73, 0x52, 0x47,
- 0x42, 0x00, 0xae, 0xce, 0x1c, 0xe9, 0x00, 0x00, 0x00, 0x09,
- 0x70, 0x48, 0x59, 0x73, 0x00, 0x00, 0x0b, 0x13, 0x00, 0x00,
- 0x0b, 0x13, 0x01, 0x00, 0x9a, 0x9c, 0x18, 0x00, 0x00, 0x00,
- 0x0c, 0x49, 0x44, 0x41, 0x54, 0x08, 0xd7, 0x63, 0xf8, 0xff,
- 0xff, 0x3f, 0x00, 0x05, 0xfe, 0x02, 0xfe, 0xdc, 0xcc, 0x59,
- 0xe7, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae,
- 0x42, 0x60, 0x82,
-};
-
-static SkCanvas* createRasterCanvas(int width, int height)
-{
- SkAutoTUnref<SkBaseDevice> device(new SkBitmapDevice(SkBitmap::kARGB_8888_Config, width, height));
- return new SkCanvas(device);
-}
-
-struct Rasterizer {
- SkCanvas* canvas;
- SkPicture* picture;
-};
-
-} // namespace
-
-class DeferredImageDecoderTest : public ::testing::Test, public MockImageDecoderClient {
-public:
- virtual void SetUp() OVERRIDE
- {
- ImageDecodingStore::initializeOnce();
- DeferredImageDecoder::setEnabled(true);
- m_data = SharedBuffer::create(whitePNG, sizeof(whitePNG));
- OwnPtr<MockImageDecoder> decoder = MockImageDecoder::create(this);
- m_actualDecoder = decoder.get();
- m_actualDecoder->setSize(1, 1);
- m_lazyDecoder = DeferredImageDecoder::createForTesting(decoder.release());
- m_canvas.reset(createRasterCanvas(100, 100));
- m_frameBufferRequestCount = 0;
- m_frameCount = 1;
- m_repetitionCount = cAnimationNone;
- m_status = ImageFrame::FrameComplete;
- m_frameDuration = 0;
- m_decodedSize = m_actualDecoder->size();
- }
-
- virtual void TearDown() OVERRIDE
- {
- ImageDecodingStore::shutdown();
- }
-
- virtual void decoderBeingDestroyed() OVERRIDE
- {
- m_actualDecoder = 0;
- }
-
- virtual void frameBufferRequested() OVERRIDE
- {
- ++m_frameBufferRequestCount;
- }
-
- virtual size_t frameCount() OVERRIDE
- {
- return m_frameCount;
- }
-
- virtual int repetitionCount() const OVERRIDE
- {
- return m_repetitionCount;
- }
-
- virtual ImageFrame::Status status() OVERRIDE
- {
- return m_status;
- }
-
- virtual float frameDuration() const OVERRIDE
- {
- return m_frameDuration;
- }
-
- virtual IntSize decodedSize() const OVERRIDE
- {
- return m_decodedSize;
- }
-
-protected:
- void useMockImageDecoderFactory()
- {
- m_lazyDecoder->frameGenerator()->setImageDecoderFactory(MockImageDecoderFactory::create(this, m_decodedSize));
- }
-
- // Don't own this but saves the pointer to query states.
- MockImageDecoder* m_actualDecoder;
- OwnPtr<DeferredImageDecoder> m_lazyDecoder;
- SkPicture m_picture;
- SkAutoTUnref<SkCanvas> m_canvas;
- int m_frameBufferRequestCount;
- RefPtr<SharedBuffer> m_data;
- size_t m_frameCount;
- int m_repetitionCount;
- ImageFrame::Status m_status;
- float m_frameDuration;
- IntSize m_decodedSize;
-};
-
-TEST_F(DeferredImageDecoderTest, drawIntoSkPicture)
-{
- m_lazyDecoder->setData(m_data.get(), true);
- RefPtr<NativeImageSkia> image = m_lazyDecoder->frameBufferAtIndex(0)->asNewNativeImage();
- EXPECT_EQ(1, image->bitmap().width());
- EXPECT_EQ(1, image->bitmap().height());
- EXPECT_FALSE(image->bitmap().isNull());
- EXPECT_TRUE(image->bitmap().isImmutable());
-
- SkCanvas* tempCanvas = m_picture.beginRecording(100, 100);
- tempCanvas->drawBitmap(image->bitmap(), 0, 0);
- m_picture.endRecording();
- EXPECT_EQ(0, m_frameBufferRequestCount);
-
- m_canvas->drawPicture(m_picture);
- EXPECT_EQ(0, m_frameBufferRequestCount);
-
- SkBitmap canvasBitmap;
- canvasBitmap.setConfig(SkBitmap::kARGB_8888_Config, 100, 100);
- ASSERT_TRUE(m_canvas->readPixels(&canvasBitmap, 0, 0));
- SkAutoLockPixels autoLock(canvasBitmap);
- EXPECT_EQ(SkColorSetARGB(255, 255, 255, 255), canvasBitmap.getColor(0, 0));
-}
-
-TEST_F(DeferredImageDecoderTest, DISABLED_drawScaledIntoSkPicture)
-{
- m_lazyDecoder->setData(m_data.get(), true);
- RefPtr<NativeImageSkia> image = m_lazyDecoder->frameBufferAtIndex(0)->asNewNativeImage();
- SkBitmap scaledBitmap = image->resizedBitmap(SkISize::Make(50, 51), SkIRect::MakeWH(50, 51));
- EXPECT_FALSE(scaledBitmap.isNull());
- EXPECT_TRUE(scaledBitmap.isImmutable());
- EXPECT_EQ(50, scaledBitmap.width());
- EXPECT_EQ(51, scaledBitmap.height());
- EXPECT_EQ(0, m_frameBufferRequestCount);
-
- SkCanvas* tempCanvas = m_picture.beginRecording(100, 100);
- tempCanvas->drawBitmap(scaledBitmap, 0, 0);
- m_picture.endRecording();
- EXPECT_EQ(0, m_frameBufferRequestCount);
-
- m_canvas->drawPicture(m_picture);
- EXPECT_EQ(0, m_frameBufferRequestCount);
-
- SkBitmap canvasBitmap;
- canvasBitmap.setConfig(SkBitmap::kARGB_8888_Config, 100, 100);
- ASSERT_TRUE(m_canvas->readPixels(&canvasBitmap, 0, 0));
- SkAutoLockPixels autoLock(canvasBitmap);
- EXPECT_EQ(SkColorSetARGB(255, 255, 255, 255), canvasBitmap.getColor(0, 0));
- EXPECT_EQ(SkColorSetARGB(255, 255, 255, 255), canvasBitmap.getColor(49, 50));
-}
-
-static void rasterizeMain(void* arg)
-{
- Rasterizer* rasterizer = static_cast<Rasterizer*>(arg);
- rasterizer->canvas->drawPicture(*rasterizer->picture);
-}
-
-TEST_F(DeferredImageDecoderTest, decodeOnOtherThread)
-{
- m_lazyDecoder->setData(m_data.get(), true);
- RefPtr<NativeImageSkia> image = m_lazyDecoder->frameBufferAtIndex(0)->asNewNativeImage();
- EXPECT_EQ(1, image->bitmap().width());
- EXPECT_EQ(1, image->bitmap().height());
- EXPECT_FALSE(image->bitmap().isNull());
- EXPECT_TRUE(image->bitmap().isImmutable());
-
- SkCanvas* tempCanvas = m_picture.beginRecording(100, 100);
- tempCanvas->drawBitmap(image->bitmap(), 0, 0);
- m_picture.endRecording();
- EXPECT_EQ(0, m_frameBufferRequestCount);
-
- // Create a thread to rasterize SkPicture.
- Rasterizer rasterizer;
- rasterizer.canvas = m_canvas;
- rasterizer.picture = &m_picture;
- ThreadIdentifier threadID = createThread(&rasterizeMain, &rasterizer, "RasterThread");
- waitForThreadCompletion(threadID);
- EXPECT_EQ(0, m_frameBufferRequestCount);
-
- SkBitmap canvasBitmap;
- canvasBitmap.setConfig(SkBitmap::kARGB_8888_Config, 100, 100);
- ASSERT_TRUE(m_canvas->readPixels(&canvasBitmap, 0, 0));
- SkAutoLockPixels autoLock(canvasBitmap);
- EXPECT_EQ(SkColorSetARGB(255, 255, 255, 255), canvasBitmap.getColor(0, 0));
-}
-
-TEST_F(DeferredImageDecoderTest, singleFrameImageLoading)
-{
- m_status = ImageFrame::FramePartial;
- m_lazyDecoder->setData(m_data.get(), false);
- EXPECT_FALSE(m_lazyDecoder->frameIsCompleteAtIndex(0));
- ImageFrame* frame = m_lazyDecoder->frameBufferAtIndex(0);
- EXPECT_EQ(ImageFrame::FramePartial, frame->status());
- EXPECT_TRUE(m_actualDecoder);
-
- m_status = ImageFrame::FrameComplete;
- m_lazyDecoder->setData(m_data.get(), true);
- EXPECT_FALSE(m_actualDecoder);
- EXPECT_TRUE(m_lazyDecoder->frameIsCompleteAtIndex(0));
- frame = m_lazyDecoder->frameBufferAtIndex(0);
- EXPECT_EQ(ImageFrame::FrameComplete, frame->status());
- EXPECT_FALSE(m_frameBufferRequestCount);
-}
-
-TEST_F(DeferredImageDecoderTest, multiFrameImageLoading)
-{
- m_repetitionCount = 10;
- m_frameCount = 1;
- m_frameDuration = 10;
- m_status = ImageFrame::FramePartial;
- m_lazyDecoder->setData(m_data.get(), false);
- EXPECT_EQ(ImageFrame::FramePartial, m_lazyDecoder->frameBufferAtIndex(0)->status());
- EXPECT_FALSE(m_lazyDecoder->frameIsCompleteAtIndex(0));
- EXPECT_EQ(10.0f, m_lazyDecoder->frameBufferAtIndex(0)->duration());
- EXPECT_EQ(10.0f, m_lazyDecoder->frameDurationAtIndex(0));
-
- m_frameCount = 2;
- m_frameDuration = 20;
- m_status = ImageFrame::FrameComplete;
- m_lazyDecoder->setData(m_data.get(), false);
- EXPECT_EQ(ImageFrame::FrameComplete, m_lazyDecoder->frameBufferAtIndex(0)->status());
- EXPECT_EQ(ImageFrame::FrameComplete, m_lazyDecoder->frameBufferAtIndex(1)->status());
- EXPECT_TRUE(m_lazyDecoder->frameIsCompleteAtIndex(0));
- EXPECT_TRUE(m_lazyDecoder->frameIsCompleteAtIndex(1));
- EXPECT_EQ(20.0f, m_lazyDecoder->frameDurationAtIndex(1));
- EXPECT_EQ(10.0f, m_lazyDecoder->frameBufferAtIndex(0)->duration());
- EXPECT_EQ(20.0f, m_lazyDecoder->frameBufferAtIndex(1)->duration());
- EXPECT_TRUE(m_actualDecoder);
-
- m_frameCount = 3;
- m_frameDuration = 30;
- m_status = ImageFrame::FrameComplete;
- m_lazyDecoder->setData(m_data.get(), true);
- EXPECT_FALSE(m_actualDecoder);
- EXPECT_EQ(ImageFrame::FrameComplete, m_lazyDecoder->frameBufferAtIndex(0)->status());
- EXPECT_EQ(ImageFrame::FrameComplete, m_lazyDecoder->frameBufferAtIndex(1)->status());
- EXPECT_EQ(ImageFrame::FrameComplete, m_lazyDecoder->frameBufferAtIndex(2)->status());
- EXPECT_TRUE(m_lazyDecoder->frameIsCompleteAtIndex(0));
- EXPECT_TRUE(m_lazyDecoder->frameIsCompleteAtIndex(1));
- EXPECT_TRUE(m_lazyDecoder->frameIsCompleteAtIndex(2));
- EXPECT_EQ(10.0f, m_lazyDecoder->frameDurationAtIndex(0));
- EXPECT_EQ(20.0f, m_lazyDecoder->frameDurationAtIndex(1));
- EXPECT_EQ(30.0f, m_lazyDecoder->frameDurationAtIndex(2));
- EXPECT_EQ(10.0f, m_lazyDecoder->frameBufferAtIndex(0)->duration());
- EXPECT_EQ(20.0f, m_lazyDecoder->frameBufferAtIndex(1)->duration());
- EXPECT_EQ(30.0f, m_lazyDecoder->frameBufferAtIndex(2)->duration());
- EXPECT_EQ(10, m_lazyDecoder->repetitionCount());
-}
-
-TEST_F(DeferredImageDecoderTest, decodedSize)
-{
- m_decodedSize = IntSize(22, 33);
- m_lazyDecoder->setData(m_data.get(), true);
- RefPtr<NativeImageSkia> image = m_lazyDecoder->frameBufferAtIndex(0)->asNewNativeImage();
- EXPECT_EQ(m_decodedSize.width(), image->bitmap().width());
- EXPECT_EQ(m_decodedSize.height(), image->bitmap().height());
- EXPECT_FALSE(image->bitmap().isNull());
- EXPECT_TRUE(image->bitmap().isImmutable());
-
- useMockImageDecoderFactory();
-
- // The following code should not fail any assert.
- SkCanvas* tempCanvas = m_picture.beginRecording(100, 100);
- tempCanvas->drawBitmap(image->bitmap(), 0, 0);
- m_picture.endRecording();
- EXPECT_EQ(0, m_frameBufferRequestCount);
- m_canvas->drawPicture(m_picture);
- EXPECT_EQ(1, m_frameBufferRequestCount);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/DiscardablePixelRef.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/DiscardablePixelRef.cpp
deleted file mode 100644
index eb1fd659631..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/DiscardablePixelRef.cpp
+++ /dev/null
@@ -1,112 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/chromium/DiscardablePixelRef.h"
-
-#include "public/platform/Platform.h"
-#include "wtf/StdLibExtras.h"
-
-namespace WebCore {
-
-namespace {
-
-// URI label for a discardable SkPixelRef.
-const char labelDiscardable[] = "discardable";
-
-} // namespace
-
-
-bool DiscardablePixelRefAllocator::allocPixelRef(SkBitmap* dst, SkColorTable* ctable)
-{
- // It should not be possible to have a non-null color table in Blink.
- ASSERT(!ctable);
-
- Sk64 size = dst->getSize64();
- if (size.isNeg() || !size.is32())
- return false;
-
- SkAutoTUnref<DiscardablePixelRef> pixelRef(new DiscardablePixelRef(adoptPtr(new SkMutex())));
- if (pixelRef->allocAndLockDiscardableMemory(size.get32())) {
- pixelRef->setURI(labelDiscardable);
- dst->setPixelRef(pixelRef.get());
- // This method is only called when a DiscardablePixelRef is created to back a SkBitmap.
- // It is necessary to lock this SkBitmap to have a valid pointer to pixels. Otherwise,
- // this SkBitmap could be assigned to another SkBitmap and locking/unlocking the other
- // SkBitmap will make this one losing its pixels.
- dst->lockPixels();
- return true;
- }
-
- // Fallback to heap allocator if discardable memory is not available.
- return dst->allocPixels();
-}
-
-DiscardablePixelRef::DiscardablePixelRef(PassOwnPtr<SkMutex> mutex)
- : SkPixelRef(mutex.get())
- , m_lockedMemory(0)
- , m_mutex(mutex)
-{
-}
-
-DiscardablePixelRef::~DiscardablePixelRef()
-{
-}
-
-bool DiscardablePixelRef::allocAndLockDiscardableMemory(size_t bytes)
-{
- m_discardable = adoptPtr(WebKit::Platform::current()->allocateAndLockDiscardableMemory(bytes));
- if (m_discardable) {
- m_lockedMemory = m_discardable->data();
- return true;
- }
- return false;
-}
-
-void* DiscardablePixelRef::onLockPixels(SkColorTable** ctable)
-{
- if (!m_lockedMemory && m_discardable->lock())
- m_lockedMemory = m_discardable->data();
-
- *ctable = 0;
- return m_lockedMemory;
-}
-
-void DiscardablePixelRef::onUnlockPixels()
-{
- if (m_lockedMemory)
- m_discardable->unlock();
- m_lockedMemory = 0;
-}
-
-bool DiscardablePixelRef::isDiscardable(SkPixelRef* pixelRef)
-{
- // FIXME: DEFINE_STATIC_LOCAL is not thread safe.
- // ImageDecodingStore provides the synchronization for this.
- DEFINE_STATIC_LOCAL(const SkString, discardable, (labelDiscardable));
- return pixelRef && pixelRef->getURI() && discardable.equals(pixelRef->getURI());
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/DiscardablePixelRef.h b/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/DiscardablePixelRef.h
deleted file mode 100644
index 28449b3b451..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/DiscardablePixelRef.h
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef DiscardablePixelRef_h
-#define DiscardablePixelRef_h
-
-#include "SkBitmap.h"
-#include "SkPixelRef.h"
-
-#include "public/platform/WebDiscardableMemory.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/PassOwnPtr.h"
-
-namespace WebCore {
-
-// Class for allocating the DiscardablePixelRef object.
-class DiscardablePixelRefAllocator : public SkBitmap::Allocator {
- // SkBitmap::Allocator implementation. The discardable memory allocated
- // after this call is locked and will not be purged until next
- // onUnlockPixels().
- virtual bool allocPixelRef(SkBitmap*, SkColorTable*);
-};
-
-// PixelRef object whose memory can be discarded when pixels are unlocked.
-class DiscardablePixelRef : public SkPixelRef {
-public:
- DiscardablePixelRef(PassOwnPtr<SkMutex>);
- ~DiscardablePixelRef();
-
- static bool isDiscardable(SkPixelRef*);
- bool allocAndLockDiscardableMemory(size_t);
-
- SK_DECLARE_UNFLATTENABLE_OBJECT()
-
-protected:
- // SkPixelRef implementation.
- virtual void* onLockPixels(SkColorTable**);
- virtual void onUnlockPixels();
-
-private:
- void* m_lockedMemory;
- OwnPtr<WebKit::WebDiscardableMemory> m_discardable;
- OwnPtr<SkMutex> m_mutex;
-};
-
-} // namespace WebCore
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/FontCacheAndroid.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/FontCacheAndroid.cpp
deleted file mode 100644
index 2cf212a8b02..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/FontCacheAndroid.cpp
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright (c) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/FontCache.h"
-
-#include "core/platform/graphics/Font.h"
-#include "core/platform/graphics/FontDescription.h"
-#include "core/platform/graphics/SimpleFontData.h"
-
-#include "SkTypeface_android.h"
-
-namespace WebCore {
-
-PassRefPtr<SimpleFontData> FontCache::getFontDataForCharacter(const Font& font, UChar32 c)
-{
- SkString skiaFamilyName;
- if (!SkGetFallbackFamilyNameForChar(c, &skiaFamilyName) || skiaFamilyName.isEmpty())
- return 0;
- return getFontResourceData(getFontResourcePlatformData(font.fontDescription(), AtomicString(skiaFamilyName.c_str()), DoNotRetain), DoNotRetain);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/FontCacheChromiumLinux.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/FontCacheChromiumLinux.cpp
deleted file mode 100644
index 17d9af56b7b..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/FontCacheChromiumLinux.cpp
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/platform/graphics/FontCache.h"
-
-#include "public/platform/linux/WebFontFamily.h"
-#include "public/platform/linux/WebFontInfo.h"
-#include "public/platform/linux/WebSandboxSupport.h"
-#include "public/platform/Platform.h"
-#include "wtf/text/CString.h"
-
-namespace WebCore {
-
-void FontCache::getFontFamilyForCharacter(UChar32 c, const char* preferredLocale, FontCache::SimpleFontFamily* family)
-{
- WebKit::WebFontFamily webFamily;
- if (WebKit::Platform::current()->sandboxSupport())
- WebKit::Platform::current()->sandboxSupport()->getFontFamilyForCharacter(c, preferredLocale, &webFamily);
- else
- WebKit::WebFontInfo::familyForChar(c, preferredLocale, &webFamily);
- family->name = String::fromUTF8(CString(webFamily.name));
- family->isBold = webFamily.isBold;
- family->isItalic = webFamily.isItalic;
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/FontCacheChromiumWin.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/FontCacheChromiumWin.cpp
deleted file mode 100644
index 1bd99e940c6..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/FontCacheChromiumWin.cpp
+++ /dev/null
@@ -1,647 +0,0 @@
-/*
- * Copyright (C) 2006, 2007 Apple Computer, Inc.
- * Copyright (c) 2006, 2007, 2008, 2009, 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/FontCache.h"
-
-#include <unicode/uniset.h>
-#include "core/platform/LayoutTestSupport.h"
-#include "core/platform/graphics/Font.h"
-#include "core/platform/graphics/SimpleFontData.h"
-#include "core/platform/graphics/chromium/FontPlatformDataChromiumWin.h"
-#include "core/platform/graphics/chromium/FontUtilsChromiumWin.h"
-#include "core/platform/win/HWndDC.h"
-#include "wtf/HashMap.h"
-#include "wtf/HashSet.h"
-#include "wtf/text/StringHash.h"
-
-#include <windows.h>
-#include <mlang.h>
-#include <objidl.h>
-
-using std::min;
-
-namespace WebCore
-{
-
-// When asked for a CJK font with a native name under a non-CJK locale or
-// asked for a CJK font with a Romanized name under a CJK locale,
-// |GetTextFace| (after |CreateFont*|) returns a 'bogus' value (e.g. Arial).
-// This is not consistent with what MSDN says !!
-// Therefore, before we call |CreateFont*|, we have to map a Romanized name to
-// the corresponding native name under a CJK locale and vice versa
-// under a non-CJK locale.
-// See the corresponding gecko bugs at
-// https://bugzilla.mozilla.org/show_bug.cgi?id=373952
-// https://bugzilla.mozilla.org/show_bug.cgi?id=231426
-static bool LookupAltName(const String& name, String& altName)
-{
- struct FontCodepage {
- const WCHAR* name;
- int codePage;
- };
-
- struct NamePair {
- const WCHAR* name;
- FontCodepage altNameCodepage;
- };
-
- const int japaneseCodepage = 932;
- const int simplifiedChineseCodepage = 936;
- const int koreanCodepage = 949;
- const int traditionalChineseCodepage = 950;
-
- // FIXME(jungshik) : This list probably covers 99% of cases.
- // To cover the remaining 1% and cut down the file size,
- // consider accessing 'NAME' table of a truetype font
- // using |GetFontData| and caching the mapping.
- // In the table below, the ASCII keys are all lower-cased for
- // case-insensitive matching.
- static const NamePair namePairs[] = {
- // MS Pゴシック, MS PGothic
- {L"\xFF2D\xFF33 \xFF30\x30B4\x30B7\x30C3\x30AF", {L"MS PGothic", japaneseCodepage}},
- {L"ms pgothic", {L"\xFF2D\xFF33 \xFF30\x30B4\x30B7\x30C3\x30AF", japaneseCodepage}},
- // MS P明朝, MS PMincho
- {L"\xFF2D\xFF33 \xFF30\x660E\x671D", {L"MS PMincho", japaneseCodepage}},
- {L"ms pmincho", {L"\xFF2D\xFF33 \xFF30\x660E\x671D", japaneseCodepage}},
- // MSゴシック, MS Gothic
- {L"\xFF2D\xFF33 \x30B4\x30B7\x30C3\x30AF", {L"MS Gothic", japaneseCodepage}},
- {L"ms gothic", {L"\xFF2D\xFF33 \x30B4\x30B7\x30C3\x30AF", japaneseCodepage}},
- // MS 明朝, MS Mincho
- {L"\xFF2D\xFF33 \x660E\x671D", {L"MS Mincho", japaneseCodepage}},
- {L"ms mincho", {L"\xFF2D\xFF33 \x660E\x671D", japaneseCodepage}},
- // メイリオ, Meiryo
- {L"\x30E1\x30A4\x30EA\x30AA", {L"Meiryo", japaneseCodepage}},
- {L"meiryo", {L"\x30E1\x30A4\x30EA\x30AA", japaneseCodepage}},
- // 바탕, Batang
- {L"\xBC14\xD0D5", {L"Batang", koreanCodepage}},
- {L"batang", {L"\xBC14\xD0D5", koreanCodepage}},
- // 바탕체, Batangche
- {L"\xBC14\xD0D5\xCCB4", {L"Batangche", koreanCodepage}},
- {L"batangche", {L"\xBC14\xD0D5\xCCB4", koreanCodepage}},
- // 굴림, Gulim
- {L"\xAD74\xB9BC", {L"Gulim", koreanCodepage}},
- {L"gulim", {L"\xAD74\xB9BC", koreanCodepage}},
- // 굴림체, Gulimche
- {L"\xAD74\xB9BC\xCCB4", {L"Gulimche", koreanCodepage}},
- {L"gulimche", {L"\xAD74\xB9BC\xCCB4", koreanCodepage}},
- // 돋움, Dotum
- {L"\xB3CB\xC6C0", {L"Dotum", koreanCodepage}},
- {L"dotum", {L"\xB3CB\xC6C0", koreanCodepage}},
- // 돋움체, Dotumche
- {L"\xB3CB\xC6C0\xCCB4", {L"Dotumche", koreanCodepage}},
- {L"dotumche", {L"\xB3CB\xC6C0\xCCB4", koreanCodepage}},
- // 궁서, Gungsuh
- {L"\xAD81\xC11C", {L"Gungsuh", koreanCodepage}},
- {L"gungsuh", {L"\xAD81\xC11C", koreanCodepage}},
- // 궁서체, Gungsuhche
- {L"\xAD81\xC11C\xCCB4", {L"Gungsuhche", koreanCodepage}},
- {L"gungsuhche", {L"\xAD81\xC11C\xCCB4", koreanCodepage}},
- // 맑은 고딕, Malgun Gothic
- {L"\xB9D1\xC740 \xACE0\xB515", {L"Malgun Gothic", koreanCodepage}},
- {L"malgun gothic", {L"\xB9D1\xC740 \xACE0\xB515", koreanCodepage}},
- // 宋体, SimSun
- {L"\x5B8B\x4F53", {L"SimSun", simplifiedChineseCodepage}},
- {L"simsun", {L"\x5B8B\x4F53", simplifiedChineseCodepage}},
- // 宋体-ExtB, SimSun-ExtB
- {L"\x5B8B\x4F53-ExtB", {L"SimSun-ExtB", simplifiedChineseCodepage}},
- {L"simsun-extb", {L"\x5B8B\x4F53-extb", simplifiedChineseCodepage}},
- // 黑体, SimHei
- {L"\x9ED1\x4F53", {L"SimHei", simplifiedChineseCodepage}},
- {L"simhei", {L"\x9ED1\x4F53", simplifiedChineseCodepage}},
- // 新宋体, NSimSun
- {L"\x65B0\x5B8B\x4F53", {L"NSimSun", simplifiedChineseCodepage}},
- {L"nsimsun", {L"\x65B0\x5B8B\x4F53", simplifiedChineseCodepage}},
- // 微软雅黑, Microsoft Yahei
- {L"\x5FAE\x8F6F\x96C5\x9ED1", {L"Microsoft Yahei", simplifiedChineseCodepage}},
- {L"microsoft yahei", {L"\x5FAE\x8F6F\x96C5\x9ED1", simplifiedChineseCodepage}},
- // 仿宋, FangSong
- {L"\x4EFF\x5B8B", {L"FangSong", simplifiedChineseCodepage}},
- {L"fangsong", {L"\x4EFF\x5B8B", simplifiedChineseCodepage}},
- // 楷体, KaiTi
- {L"\x6977\x4F53", {L"KaiTi", simplifiedChineseCodepage}},
- {L"kaiti", {L"\x6977\x4F53", simplifiedChineseCodepage}},
- // 仿宋_GB2312, FangSong_GB2312
- {L"\x4EFF\x5B8B_GB2312", {L"FangSong_GB2312", simplifiedChineseCodepage}},
- {L"fangsong_gb2312", {L"\x4EFF\x5B8B_gb2312", simplifiedChineseCodepage}},
- // 楷体_GB2312, KaiTi_GB2312
- {L"\x6977\x4F53", {L"KaiTi_GB2312", simplifiedChineseCodepage}},
- {L"kaiti_gb2312", {L"\x6977\x4F53_gb2312", simplifiedChineseCodepage}},
- // 新細明體, PMingLiu
- {L"\x65B0\x7D30\x660E\x9AD4", {L"PMingLiu", traditionalChineseCodepage}},
- {L"pmingliu", {L"\x65B0\x7D30\x660E\x9AD4", traditionalChineseCodepage}},
- // 新細明體-ExtB, PMingLiu-ExtB
- {L"\x65B0\x7D30\x660E\x9AD4-ExtB", {L"PMingLiu-ExtB", traditionalChineseCodepage}},
- {L"pmingliu-extb", {L"\x65B0\x7D30\x660E\x9AD4-extb", traditionalChineseCodepage}},
- // 細明體, MingLiu
- {L"\x7D30\x660E\x9AD4", {L"MingLiu", traditionalChineseCodepage}},
- {L"mingliu", {L"\x7D30\x660E\x9AD4", traditionalChineseCodepage}},
- // 細明體-ExtB, MingLiu-ExtB
- {L"\x7D30\x660E\x9AD4-ExtB", {L"MingLiu-ExtB", traditionalChineseCodepage}},
- {L"mingliu-extb", {L"x65B0\x7D30\x660E\x9AD4-extb", traditionalChineseCodepage}},
- // 微軟正黑體, Microsoft JhengHei
- {L"\x5FAE\x8EDF\x6B63\x9ED1\x9AD4", {L"Microsoft JhengHei", traditionalChineseCodepage}},
- {L"microsoft jhengHei", {L"\x5FAE\x8EDF\x6B63\x9ED1\x9AD4", traditionalChineseCodepage}},
- // 標楷體, DFKai-SB
- {L"\x6A19\x6977\x9AD4", {L"DFKai-SB", traditionalChineseCodepage}},
- {L"dfkai-sb", {L"\x6A19\x6977\x9AD4", traditionalChineseCodepage}},
- // WenQuanYi Zen Hei
- {L"\x6587\x6cc9\x9a5b\x6b63\x9ed1", {L"WenQuanYi Zen Hei", traditionalChineseCodepage}},
- {L"wenquanyi zen hei", {L"\x6587\x6cc9\x9a5b\x6b63\x9ed1", traditionalChineseCodepage}},
- // WenQuanYi Zen Hei
- {L"\x6587\x6cc9\x9a7f\x6b63\x9ed1", {L"WenQuanYi Zen Hei", simplifiedChineseCodepage}},
- {L"wenquanyi zen hei", {L"\x6587\x6cc9\x9a7f\x6b63\x9ed1", simplifiedChineseCodepage}},
- // AR PL ShanHeiSun Uni,
- {L"\x6587\x9f0e\x0050\x004c\x7d30\x4e0a\x6d77\x5b8b\x0055\x006e\x0069",
- {L"AR PL ShanHeiSun Uni", traditionalChineseCodepage}},
- {L"ar pl shanheisun uni",
- {L"\x6587\x9f0e\x0050\x004c\x7d30\x4e0a\x6d77\x5b8b\x0055\x006e\x0069", traditionalChineseCodepage}},
- // AR PL ShanHeiSun Uni,
- {L"\x6587\x9f0e\x0050\x004c\x7ec6\x4e0a\x6d77\x5b8b\x0055\x006e\x0069",
- {L"AR PL ShanHeiSun Uni", simplifiedChineseCodepage}},
- {L"ar pl shanheisun uni",
- {L"\x6587\x9f0e\x0050\x004c\x7ec6\x4e0a\x6d77\x5b8b\x0055\x006e\x0069", simplifiedChineseCodepage}},
- // AR PL ZenKai Uni
- // Traditional Chinese and Simplified Chinese names are
- // identical.
- {L"\x6587\x0050\x004C\x4E2D\x6977\x0055\x006E\x0069", {L"AR PL ZenKai Uni", traditionalChineseCodepage}},
- {L"ar pl zenkai uni", {L"\x6587\x0050\x004C\x4E2D\x6977\x0055\x006E\x0069", traditionalChineseCodepage}},
- {L"\x6587\x0050\x004C\x4E2D\x6977\x0055\x006E\x0069", {L"AR PL ZenKai Uni", simplifiedChineseCodepage}},
- {L"ar pl zenkai uni", {L"\x6587\x0050\x004C\x4E2D\x6977\x0055\x006E\x0069", simplifiedChineseCodepage}},
- };
-
- typedef HashMap<String, const FontCodepage*> NameMap;
- static NameMap* fontNameMap = 0;
-
- if (!fontNameMap) {
- fontNameMap = new NameMap;
- for (size_t i = 0; i < WTF_ARRAY_LENGTH(namePairs); ++i)
- fontNameMap->set(String(namePairs[i].name), &(namePairs[i].altNameCodepage));
- }
-
- bool isAscii = false;
- String n;
- // use |lower| only for ASCII names
- // For non-ASCII names, we don't want to invoke an expensive
- // and unnecessary |lower|.
- if (name.containsOnlyASCII()) {
- isAscii = true;
- n = name.lower();
- } else
- n = name;
-
- NameMap::iterator iter = fontNameMap->find(n);
- if (iter == fontNameMap->end())
- return false;
-
- static int systemCp = ::GetACP();
- int fontCp = iter->value->codePage;
-
- if ((isAscii && systemCp == fontCp) || (!isAscii && systemCp != fontCp)) {
- altName = String(iter->value->name);
- return true;
- }
-
- return false;
-}
-
-static HFONT createFontIndirectAndGetWinName(const String& family, LOGFONT* winfont, String* winName)
-{
- unsigned len = family.copyTo(winfont->lfFaceName, 0, LF_FACESIZE - 1);
- winfont->lfFaceName[len] = '\0';
-
- HFONT hfont = CreateFontIndirect(winfont);
- if (!hfont)
- return 0;
-
- HWndDC dc(0);
- HGDIOBJ oldFont = static_cast<HFONT>(SelectObject(dc, hfont));
- WCHAR name[LF_FACESIZE];
- unsigned resultLength = GetTextFace(dc, LF_FACESIZE, name);
- if (resultLength > 0)
- resultLength--; // ignore the null terminator
-
- SelectObject(dc, oldFont);
- *winName = String(name, resultLength);
- return hfont;
-}
-
-// This maps font family names to their repertoires of supported Unicode
-// characters. Because it's family names rather than font faces we use
-// as keys, there might be edge cases where one face of a font family
-// has a different repertoire from another face of the same family.
-typedef HashMap<const wchar_t*, icu::UnicodeSet*> FontCmapCache;
-
-static bool fontContainsCharacter(const FontPlatformData* fontData,
- const wchar_t* family, UChar32 character)
-{
- // FIXME: For non-BMP characters, GetFontUnicodeRanges is of
- // no use. We have to read directly from the cmap table of a font.
- // Return true for now.
- if (character > 0xFFFF)
- return true;
-
- // This cache is just leaked on shutdown.
- static FontCmapCache* fontCmapCache = 0;
- if (!fontCmapCache)
- fontCmapCache = new FontCmapCache;
-
- HashMap<const wchar_t*, icu::UnicodeSet*>::iterator it = fontCmapCache->find(family);
- if (it != fontCmapCache->end())
- return it->value->contains(character);
-
- HFONT hfont = fontData->hfont();
- HWndDC hdc(0);
- HGDIOBJ oldFont = static_cast<HFONT>(SelectObject(hdc, hfont));
- int count = GetFontUnicodeRanges(hdc, 0);
- if (!count && FontPlatformData::ensureFontLoaded(hfont))
- count = GetFontUnicodeRanges(hdc, 0);
- if (!count) {
- LOG_ERROR("Unable to get the font unicode range after second attempt");
- SelectObject(hdc, oldFont);
- return true;
- }
-
- static Vector<char, 512> glyphsetBuffer;
- glyphsetBuffer.resize(GetFontUnicodeRanges(hdc, 0));
- GLYPHSET* glyphset = reinterpret_cast<GLYPHSET*>(glyphsetBuffer.data());
- // In addition, refering to the OS/2 table and converting the codepage list
- // to the coverage map might be faster.
- count = GetFontUnicodeRanges(hdc, glyphset);
- ASSERT(count > 0);
- SelectObject(hdc, oldFont);
-
- // FIXME: consider doing either of the following two:
- // 1) port back ICU 4.0's faster look-up code for UnicodeSet
- // 2) port Mozilla's CompressedCharMap or gfxSparseBitset
- unsigned i = 0;
- icu::UnicodeSet* cmap = new icu::UnicodeSet;
- while (i < glyphset->cRanges) {
- WCHAR start = glyphset->ranges[i].wcLow;
- cmap->add(start, start + glyphset->ranges[i].cGlyphs - 1);
- i++;
- }
- cmap->freeze();
- // We don't lowercase |family| because all of them are under our control
- // and they're already lowercased.
- fontCmapCache->set(family, cmap);
- return cmap->contains(character);
-}
-
-// Tries the given font and save it |outFontFamilyName| if it succeeds.
-PassRefPtr<SimpleFontData> FontCache::fontDataFromDescriptionAndLogFont(const FontDescription& fontDescription, ShouldRetain shouldRetain, const LOGFONT& font, wchar_t* outFontFamilyName)
-{
- RefPtr<SimpleFontData> fontData = getFontResourceData(fontDescription, font.lfFaceName, false, shouldRetain);
- if (fontData)
- memcpy(outFontFamilyName, font.lfFaceName, sizeof(font.lfFaceName));
- return fontData.release();
-}
-
-static LONG toGDIFontWeight(FontWeight fontWeight)
-{
- static LONG gdiFontWeights[] = {
- FW_THIN, // FontWeight100
- FW_EXTRALIGHT, // FontWeight200
- FW_LIGHT, // FontWeight300
- FW_NORMAL, // FontWeight400
- FW_MEDIUM, // FontWeight500
- FW_SEMIBOLD, // FontWeight600
- FW_BOLD, // FontWeight700
- FW_EXTRABOLD, // FontWeight800
- FW_HEAVY // FontWeight900
- };
- return gdiFontWeights[fontWeight];
-}
-
-static void FillLogFont(const FontDescription& fontDescription, LOGFONT* winfont)
-{
- // The size here looks unusual. The negative number is intentional.
- // Unlike WebKit trunk, we don't multiply the size by 32. That seems to be
- // some kind of artifact of their CG backend, or something.
- winfont->lfHeight = -fontDescription.computedPixelSize();
- winfont->lfWidth = 0;
- winfont->lfEscapement = 0;
- winfont->lfOrientation = 0;
- winfont->lfUnderline = false;
- winfont->lfStrikeOut = false;
- winfont->lfCharSet = DEFAULT_CHARSET;
- winfont->lfOutPrecision = OUT_TT_ONLY_PRECIS;
- winfont->lfQuality = isRunningLayoutTest() ? NONANTIALIASED_QUALITY : DEFAULT_QUALITY; // Honor user's desktop settings.
- winfont->lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
- winfont->lfItalic = fontDescription.italic();
- winfont->lfWeight = toGDIFontWeight(fontDescription.weight());
-}
-
-struct TraitsInFamilyProcData {
- TraitsInFamilyProcData(const AtomicString& familyName)
- : m_familyName(familyName)
- {
- }
-
- const AtomicString& m_familyName;
- HashSet<unsigned> m_traitsMasks;
-};
-
-static int CALLBACK traitsInFamilyEnumProc(CONST LOGFONT* logFont, CONST TEXTMETRIC* metrics, DWORD fontType, LPARAM lParam)
-{
- TraitsInFamilyProcData* procData = reinterpret_cast<TraitsInFamilyProcData*>(lParam);
-
- unsigned traitsMask = 0;
- traitsMask |= logFont->lfItalic ? FontStyleItalicMask : FontStyleNormalMask;
- traitsMask |= FontVariantNormalMask;
- LONG weight = logFont->lfWeight;
- traitsMask |= weight == FW_THIN ? FontWeight100Mask :
- weight == FW_EXTRALIGHT ? FontWeight200Mask :
- weight == FW_LIGHT ? FontWeight300Mask :
- weight == FW_NORMAL ? FontWeight400Mask :
- weight == FW_MEDIUM ? FontWeight500Mask :
- weight == FW_SEMIBOLD ? FontWeight600Mask :
- weight == FW_BOLD ? FontWeight700Mask :
- weight == FW_EXTRABOLD ? FontWeight800Mask :
- FontWeight900Mask;
- procData->m_traitsMasks.add(traitsMask);
- return 1;
-}
-
-struct GetLastResortFallbackFontProcData {
- GetLastResortFallbackFontProcData(FontCache* fontCache, const FontDescription* fontDescription, FontCache::ShouldRetain shouldRetain, wchar_t* fontName)
- : m_fontCache(fontCache)
- , m_fontDescription(fontDescription)
- , m_shouldRetain(shouldRetain)
- , m_fontName(fontName)
- , m_fontData(0)
- {
- }
-
- FontCache* m_fontCache;
- const FontDescription* m_fontDescription;
- FontCache::ShouldRetain m_shouldRetain;
- wchar_t* m_fontName;
- RefPtr<SimpleFontData> m_fontData;
-};
-
-static int CALLBACK getLastResortFallbackFontProc(const LOGFONT* logFont, const TEXTMETRIC* metrics, DWORD fontType, LPARAM lParam)
-{
- GetLastResortFallbackFontProcData* procData = reinterpret_cast<GetLastResortFallbackFontProcData*>(lParam);
- procData->m_fontData = procData->m_fontCache->fontDataFromDescriptionAndLogFont(*procData->m_fontDescription, procData->m_shouldRetain, *logFont, procData->m_fontName);
- return !procData->m_fontData;
-}
-
-void FontCache::platformInit()
-{
- // Not needed on Windows.
-}
-
-// Given the desired base font, this will create a SimpleFontData for a specific
-// font that can be used to render the given range of characters.
-PassRefPtr<SimpleFontData> FontCache::getFontDataForCharacter(const Font& font, UChar32 inputC)
-{
- // FIXME: We should fix getFallbackFamily to take a UChar32
- // and remove this split-to-UChar16 code.
- UChar codeUnits[2];
- int codeUnitsLength;
- if (inputC <= 0xFFFF) {
- codeUnits[0] = inputC;
- codeUnitsLength = 1;
- } else {
- codeUnits[0] = U16_LEAD(inputC);
- codeUnits[1] = U16_TRAIL(inputC);
- codeUnitsLength = 2;
- }
-
- // FIXME: Consider passing fontDescription.dominantScript()
- // to GetFallbackFamily here.
- FontDescription fontDescription = font.fontDescription();
- UChar32 c;
- UScriptCode script;
- const wchar_t* family = getFallbackFamily(codeUnits, codeUnitsLength, fontDescription.genericFamily(), &c, &script);
- FontPlatformData* data = 0;
- if (family)
- data = getFontResourcePlatformData(font.fontDescription(), AtomicString(family, wcslen(family)), false);
-
- // Last resort font list : PanUnicode. CJK fonts have a pretty
- // large repertoire. Eventually, we need to scan all the fonts
- // on the system to have a Firefox-like coverage.
- // Make sure that all of them are lowercased.
- const static wchar_t* const cjkFonts[] = {
- L"arial unicode ms",
- L"ms pgothic",
- L"simsun",
- L"gulim",
- L"pmingliu",
- L"wenquanyi zen hei", // partial CJK Ext. A coverage but more
- // widely known to Chinese users.
- L"ar pl shanheisun uni",
- L"ar pl zenkai uni",
- L"han nom a", // Complete CJK Ext. A coverage
- L"code2000", // Complete CJK Ext. A coverage
- // CJK Ext. B fonts are not listed here because it's of no use
- // with our current non-BMP character handling because we use
- // Uniscribe for it and that code path does not go through here.
- };
-
- const static wchar_t* const commonFonts[] = {
- L"tahoma",
- L"arial unicode ms",
- L"lucida sans unicode",
- L"microsoft sans serif",
- L"palatino linotype",
- // Six fonts below (and code2000 at the end) are not from MS, but
- // once installed, cover a very wide range of characters.
- L"dejavu serif",
- L"dejavu sasns",
- L"freeserif",
- L"freesans",
- L"gentium",
- L"gentiumalt",
- L"ms pgothic",
- L"simsun",
- L"gulim",
- L"pmingliu",
- L"code2000",
- };
-
- const wchar_t* const* panUniFonts = 0;
- int numFonts = 0;
- if (script == USCRIPT_HAN) {
- panUniFonts = cjkFonts;
- numFonts = WTF_ARRAY_LENGTH(cjkFonts);
- } else {
- panUniFonts = commonFonts;
- numFonts = WTF_ARRAY_LENGTH(commonFonts);
- }
- // Font returned from GetFallbackFamily may not cover |characters|
- // because it's based on script to font mapping. This problem is
- // critical enough for non-Latin scripts (especially Han) to
- // warrant an additional (real coverage) check with fontCotainsCharacter.
- int i;
- for (i = 0; (!data || !fontContainsCharacter(data, family, c)) && i < numFonts; ++i) {
- family = panUniFonts[i];
- data = getFontResourcePlatformData(font.fontDescription(), AtomicString(family, wcslen(family)));
- }
- // When i-th font (0-base) in |panUniFonts| contains a character and
- // we get out of the loop, |i| will be |i + 1|. That is, if only the
- // last font in the array covers the character, |i| will be numFonts.
- // So, we have to use '<=" rather than '<' to see if we found a font
- // covering the character.
- if (i <= numFonts)
- return getFontResourceData(data, DoNotRetain);
-
- return 0;
-
-}
-
-PassRefPtr<SimpleFontData> FontCache::getSimilarFontPlatformData(const Font& font)
-{
- return 0;
-}
-
-PassRefPtr<SimpleFontData> FontCache::getLastResortFallbackFont(const FontDescription& description, ShouldRetain shouldRetain)
-{
- FontDescription::GenericFamilyType generic = description.genericFamily();
-
- // FIXME: Would be even better to somehow get the user's default font here.
- // For now we'll pick the default that the user would get without changing
- // any prefs.
- static AtomicString timesStr("Times New Roman");
- static AtomicString courierStr("Courier New");
- static AtomicString arialStr("Arial");
-
- AtomicString& fontStr = timesStr;
- if (generic == FontDescription::SansSerifFamily)
- fontStr = arialStr;
- else if (generic == FontDescription::MonospaceFamily)
- fontStr = courierStr;
-
- RefPtr<SimpleFontData> simpleFont = getFontResourceData(description, fontStr, false, shouldRetain);
- if (simpleFont)
- return simpleFont.release();
-
- // Fall back to system fonts as Win Safari does because this function must
- // return a valid font. Once we find a valid system font, we save its name
- // to a static variable and use it to prevent trying system fonts again.
- static wchar_t fallbackFontName[LF_FACESIZE] = {0};
- if (fallbackFontName[0])
- return getFontResourceData(description, fallbackFontName, false, shouldRetain);
-
- // Fall back to the DEFAULT_GUI_FONT if no known Unicode fonts are available.
- if (HFONT defaultGUIFont = static_cast<HFONT>(GetStockObject(DEFAULT_GUI_FONT))) {
- LOGFONT defaultGUILogFont;
- GetObject(defaultGUIFont, sizeof(defaultGUILogFont), &defaultGUILogFont);
- if (simpleFont = fontDataFromDescriptionAndLogFont(description, shouldRetain, defaultGUILogFont, fallbackFontName))
- return simpleFont.release();
- }
-
- // Fall back to Non-client metrics fonts.
- NONCLIENTMETRICS nonClientMetrics = {0};
- nonClientMetrics.cbSize = sizeof(nonClientMetrics);
- if (SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(nonClientMetrics), &nonClientMetrics, 0)) {
- if (simpleFont = fontDataFromDescriptionAndLogFont(description, shouldRetain, nonClientMetrics.lfMessageFont, fallbackFontName))
- return simpleFont.release();
- if (simpleFont = fontDataFromDescriptionAndLogFont(description, shouldRetain, nonClientMetrics.lfMenuFont, fallbackFontName))
- return simpleFont.release();
- if (simpleFont = fontDataFromDescriptionAndLogFont(description, shouldRetain, nonClientMetrics.lfStatusFont, fallbackFontName))
- return simpleFont.release();
- if (simpleFont = fontDataFromDescriptionAndLogFont(description, shouldRetain, nonClientMetrics.lfCaptionFont, fallbackFontName))
- return simpleFont.release();
- if (simpleFont = fontDataFromDescriptionAndLogFont(description, shouldRetain, nonClientMetrics.lfSmCaptionFont, fallbackFontName))
- return simpleFont.release();
- }
-
- // Fall back to all the fonts installed in this PC. When a font has a
- // localized name according to the system locale as well as an English name,
- // both GetTextFace() and EnumFontFamilies() return the localized name. So,
- // FontCache::createFontPlatformData() does not filter out the fonts
- // returned by this EnumFontFamilies() call.
- HWndDC dc(0);
- if (dc) {
- GetLastResortFallbackFontProcData procData(this, &description, shouldRetain, fallbackFontName);
- EnumFontFamilies(dc, 0, getLastResortFallbackFontProc, reinterpret_cast<LPARAM>(&procData));
-
- if (procData.m_fontData)
- return procData.m_fontData.release();
- }
-
- ASSERT_NOT_REACHED();
- return 0;
-}
-
-void FontCache::getTraitsInFamily(const AtomicString& familyName, Vector<unsigned>& traitsMasks)
-{
- HWndDC hdc(0);
-
- LOGFONT logFont;
- logFont.lfCharSet = DEFAULT_CHARSET;
- unsigned familyLength = min(familyName.length(), static_cast<unsigned>(LF_FACESIZE - 1));
- familyName.string().copyTo(logFont.lfFaceName, 0, familyLength);
- logFont.lfFaceName[familyLength] = 0;
- logFont.lfPitchAndFamily = 0;
-
- TraitsInFamilyProcData procData(familyName);
- EnumFontFamiliesEx(hdc, &logFont, traitsInFamilyEnumProc, reinterpret_cast<LPARAM>(&procData), 0);
- copyToVector(procData.m_traitsMasks, traitsMasks);
-}
-
-FontPlatformData* FontCache::createFontPlatformData(const FontDescription& fontDescription, const AtomicString& family)
-{
- LOGFONT winfont = {0};
- FillLogFont(fontDescription, &winfont);
-
- // Windows will always give us a valid pointer here, even if the face name
- // is non-existent. We have to double-check and see if the family name was
- // really used.
- String winName;
- HFONT hfont = createFontIndirectAndGetWinName(family, &winfont, &winName);
- if (!hfont)
- return 0;
-
- // FIXME: Do we need to use predefined fonts "guaranteed" to exist
- // when we're running in layout-test mode?
- if (!equalIgnoringCase(family, winName)) {
- // For CJK fonts with both English and native names,
- // GetTextFace returns a native name under the font's "locale"
- // and an English name under other locales regardless of
- // lfFaceName field of LOGFONT. As a result, we need to check
- // if a font has an alternate name. If there is, we need to
- // compare it with what's requested in the first place.
- String altName;
- if (!LookupAltName(family, altName) || !equalIgnoringCase(altName, winName)) {
- DeleteObject(hfont);
- return 0;
- }
- }
-
- return new FontPlatformData(hfont,
- fontDescription.computedPixelSize(),
- fontDescription.orientation());
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/FontChromiumWin.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/FontChromiumWin.cpp
deleted file mode 100644
index 814ff39aa70..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/FontChromiumWin.cpp
+++ /dev/null
@@ -1,227 +0,0 @@
-/*
- * Copyright (C) 2006, 2007 Apple Computer, Inc.
- * Copyright (c) 2006, 2007, 2008, 2009, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/Font.h"
-
-#include "core/platform/NotImplemented.h"
-#include "core/platform/graphics/FontFallbackList.h"
-#include "core/platform/graphics/GlyphBuffer.h"
-#include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/graphics/SimpleFontData.h"
-#include "core/platform/graphics/chromium/FontPlatformDataChromiumWin.h"
-#include "core/platform/graphics/chromium/UniscribeHelperTextRun.h"
-#include "core/platform/graphics/skia/SkiaFontWin.h"
-
-#include <windows.h>
-
-using namespace std;
-
-namespace WebCore {
-
-bool Font::canReturnFallbackFontsForComplexText()
-{
- return false;
-}
-
-bool Font::canExpandAroundIdeographsInComplexText()
-{
- return false;
-}
-
-void Font::drawGlyphs(GraphicsContext* graphicsContext,
- const SimpleFontData* font,
- const GlyphBuffer& glyphBuffer,
- int from,
- int numGlyphs,
- const FloatPoint& point,
- const FloatRect& textRect) const
-{
- SkColor color = graphicsContext->effectiveFillColor();
- unsigned char alpha = SkColorGetA(color);
- // Skip 100% transparent text; no need to draw anything.
- if (!alpha && graphicsContext->strokeStyle() == NoStroke && !graphicsContext->hasShadow())
- return;
-
- // We draw the glyphs in chunks to avoid having to do a heap allocation for
- // the arrays of characters and advances.
- const int kMaxBufferLength = 256;
- Vector<int, kMaxBufferLength> advances;
- int glyphIndex = 0; // The starting glyph of the current chunk.
-
- float horizontalOffset = point.x(); // The floating point offset of the left side of the current glyph.
-
-#if ENABLE(OPENTYPE_VERTICAL)
- const OpenTypeVerticalData* verticalData = font->verticalData();
- if (verticalData) {
- Vector<FloatPoint, kMaxBufferLength> translations;
- Vector<GOFFSET, kMaxBufferLength> offsets;
-
- // Skia doesn't have matrix for glyph coordinate space, so we rotate back the CTM.
- AffineTransform savedMatrix = graphicsContext->getCTM();
- graphicsContext->concatCTM(AffineTransform(0, -1, 1, 0, point.x(), point.y()));
- graphicsContext->concatCTM(AffineTransform(1, 0, 0, 1, -point.x(), -point.y()));
-
- const FontMetrics& metrics = font->fontMetrics();
- SkScalar verticalOriginX = SkFloatToScalar(point.x() + metrics.floatAscent() - metrics.floatAscent(IdeographicBaseline));
- while (glyphIndex < numGlyphs) {
- // How many chars will be in this chunk?
- int curLen = std::min(kMaxBufferLength, numGlyphs - glyphIndex);
-
- const Glyph* glyphs = glyphBuffer.glyphs(from + glyphIndex);
- translations.resize(curLen);
- verticalData->getVerticalTranslationsForGlyphs(font, &glyphs[0], curLen, reinterpret_cast<float*>(&translations[0]));
- // To position glyphs vertically, we use offsets instead of advances.
- advances.resize(curLen);
- advances.fill(0);
- offsets.resize(curLen);
- float currentWidth = 0;
- for (int i = 0; i < curLen; ++i, ++glyphIndex) {
- offsets[i].du = lroundf(translations[i].x());
- offsets[i].dv = -lroundf(currentWidth - translations[i].y());
- currentWidth += glyphBuffer.advanceAt(from + glyphIndex);
- }
- SkPoint origin;
- origin.set(verticalOriginX, SkFloatToScalar(point.y() + horizontalOffset - point.x()));
- horizontalOffset += currentWidth;
- paintSkiaText(graphicsContext, font->platformData(), curLen, &glyphs[0], &advances[0], &offsets[0], origin, SkRect(textRect));
- }
-
- graphicsContext->setCTM(savedMatrix);
- return;
- }
-#endif
-
- // In order to round all offsets to the correct pixel boundary, this code keeps track of the absolute position
- // of each glyph in floating point units and rounds to integer advances at the last possible moment.
-
- int lastHorizontalOffsetRounded = lroundf(horizontalOffset); // The rounded offset of the left side of the last glyph rendered.
- Vector<WORD, kMaxBufferLength> glyphs;
- while (glyphIndex < numGlyphs) {
- // How many chars will be in this chunk?
- int curLen = std::min(kMaxBufferLength, numGlyphs - glyphIndex);
- glyphs.resize(curLen);
- advances.resize(curLen);
-
- float currentWidth = 0;
- for (int i = 0; i < curLen; ++i, ++glyphIndex) {
- glyphs[i] = glyphBuffer.glyphAt(from + glyphIndex);
- horizontalOffset += glyphBuffer.advanceAt(from + glyphIndex);
- advances[i] = lroundf(horizontalOffset) - lastHorizontalOffsetRounded;
- lastHorizontalOffsetRounded += advances[i];
- currentWidth += glyphBuffer.advanceAt(from + glyphIndex);
-
- // Bug 26088 - very large positive or negative runs can fail to
- // render so we clamp the size here. In the specs, negative
- // letter-spacing is implementation-defined, so this should be
- // fine, and it matches Safari's implementation. The call actually
- // seems to crash if kMaxNegativeRun is set to somewhere around
- // -32830, so we give ourselves a little breathing room.
- const int maxNegativeRun = -32768;
- const int maxPositiveRun = 32768;
- if ((currentWidth + advances[i] < maxNegativeRun) || (currentWidth + advances[i] > maxPositiveRun))
- advances[i] = 0;
- }
-
- SkPoint origin = point;
- origin.fX += SkFloatToScalar(horizontalOffset - point.x() - currentWidth);
- paintSkiaText(graphicsContext, font->platformData(), curLen, &glyphs[0], &advances[0], 0, origin, SkRect(textRect));
- }
-}
-
-FloatRect Font::selectionRectForComplexText(const TextRun& run,
- const FloatPoint& point,
- int h,
- int from,
- int to) const
-{
- UniscribeHelperTextRun state(run, *this);
- float left = static_cast<float>(point.x() + state.characterToX(from));
- float right = static_cast<float>(point.x() + state.characterToX(to));
-
- // If the text is RTL, left will actually be after right.
- if (left < right)
- return FloatRect(left, point.y(),
- right - left, static_cast<float>(h));
-
- return FloatRect(right, point.y(),
- left - right, static_cast<float>(h));
-}
-
-void Font::drawComplexText(GraphicsContext* graphicsContext,
- const TextRunPaintInfo& runInfo,
- const FloatPoint& point) const
-{
- UniscribeHelperTextRun state(runInfo.run, *this);
-
- SkColor color = graphicsContext->effectiveFillColor();
- unsigned char alpha = SkColorGetA(color);
- // Skip 100% transparent text; no need to draw anything.
- if (!alpha && graphicsContext->strokeStyle() == NoStroke)
- return;
-
- HDC hdc = 0;
- // Uniscribe counts the coordinates from the upper left, while WebKit uses
- // the baseline, so we have to subtract off the ascent.
- state.draw(graphicsContext, hdc, lroundf(point.x()), lroundf(point.y() - fontMetrics().ascent()), runInfo.bounds, runInfo.from, runInfo.to);
-}
-
-void Font::drawEmphasisMarksForComplexText(GraphicsContext* /* context */, const TextRunPaintInfo& /* runInfo */, const AtomicString& /* mark */, const FloatPoint& /* point */) const
-{
- notImplemented();
-}
-
-float Font::floatWidthForComplexText(const TextRun& run, HashSet<const SimpleFontData*>* /* fallbackFonts */, GlyphOverflow* /* glyphOverflow */) const
-{
- UniscribeHelperTextRun state(run, *this);
- return static_cast<float>(state.width());
-}
-
-int Font::offsetForPositionForComplexText(const TextRun& run, float xFloat,
- bool includePartialGlyphs) const
-{
- // FIXME: This truncation is not a problem for HTML, but only affects SVG, which passes floating-point numbers
- // to Font::offsetForPosition(). Bug http://webkit.org/b/40673 tracks fixing this problem.
- int x = static_cast<int>(xFloat);
-
- // Mac code ignores includePartialGlyphs, and they don't know what it's
- // supposed to do, so we just ignore it as well.
- UniscribeHelperTextRun state(run, *this);
- int charIndex = state.xToCharacter(x);
-
- // XToCharacter will return -1 if the position is before the first
- // character (we get called like this sometimes).
- if (charIndex < 0)
- charIndex = 0;
- return charIndex;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/FontPlatformDataChromiumWin.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/FontPlatformDataChromiumWin.cpp
deleted file mode 100644
index 30f96c67ca6..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/FontPlatformDataChromiumWin.cpp
+++ /dev/null
@@ -1,342 +0,0 @@
-/*
- * Copyright (C) 2006, 2007 Apple Computer, Inc.
- * Copyright (c) 2006, 2007, 2008, 2009, 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/FontPlatformData.h"
-
-#include <windows.h>
-#include <mlang.h>
-#include <objidl.h>
-#include "core/platform/LayoutTestSupport.h"
-#include "core/platform/SharedBuffer.h"
-#include "core/platform/graphics/FontCache.h"
-#include "core/platform/graphics/skia/SkiaFontWin.h"
-#include "core/platform/win/HWndDC.h"
-#include "public/platform/Platform.h"
-#include "public/platform/win/WebSandboxSupport.h"
-#include "third_party/skia/include/core/SkPaint.h"
-#include "third_party/skia/include/core/SkTypeface.h"
-#include "third_party/skia/include/ports/SkTypeface_win.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/StdLibExtras.h"
-
-namespace WebCore {
-
-#if !ENABLE(GDI_FONTS_ON_WINDOWS)
-void FontPlatformData::setupPaint(SkPaint* paint) const
-{
- const float ts = m_size >= 0 ? m_size : 12;
- paint->setTextSize(SkFloatToScalar(m_size));
- paint->setTypeface(typeface());
-}
-#endif
-
-// Lookup the current system settings for font smoothing.
-// We cache these values for performance, but if the browser has a way to be
-// notified when these change, we could re-query them at that time.
-static uint32_t getDefaultGDITextFlags()
-{
- static bool gInited;
- static uint32_t gFlags;
- if (!gInited) {
- BOOL enabled;
- gFlags = 0;
- if (SystemParametersInfo(SPI_GETFONTSMOOTHING, 0, &enabled, 0) && enabled) {
- gFlags |= SkPaint::kAntiAlias_Flag;
-
- UINT smoothType;
- if (SystemParametersInfo(SPI_GETFONTSMOOTHINGTYPE, 0, &smoothType, 0)) {
- if (FE_FONTSMOOTHINGCLEARTYPE == smoothType)
- gFlags |= SkPaint::kLCDRenderText_Flag;
- }
- }
- gInited = true;
- }
- return gFlags;
-}
-
-static bool isWebFont(const LOGFONT& lf)
-{
- // web-fonts have artifical names constructed to always be
- // 1. 24 characters, followed by a '\0'
- // 2. the last two characters are '=='
- return '=' == lf.lfFaceName[22] && '=' == lf.lfFaceName[23] && '\0' == lf.lfFaceName[24];
-}
-
-static int computePaintTextFlags(const LOGFONT& lf)
-{
- int textFlags = 0;
- switch (lf.lfQuality) {
- case NONANTIALIASED_QUALITY:
- textFlags = 0;
- break;
- case ANTIALIASED_QUALITY:
- textFlags = SkPaint::kAntiAlias_Flag;
- break;
- case CLEARTYPE_QUALITY:
- textFlags = (SkPaint::kAntiAlias_Flag | SkPaint::kLCDRenderText_Flag);
- break;
- default:
- textFlags = getDefaultGDITextFlags();
- break;
- }
-
- // only allow features that SystemParametersInfo allows
- textFlags &= getDefaultGDITextFlags();
-
- /*
- * FontPlatformData(...) will read our logfont, and try to honor the the lfQuality
- * setting (computing the corresponding SkPaint flags for AA and LCD). However, it
- * will limit the quality based on its query of SPI_GETFONTSMOOTHING. This could mean
- * we end up drawing the text in BW, even though our lfQuality requested antialiasing.
- *
- * Many web-fonts are so poorly hinted that they are terrible to read when drawn in BW.
- * In these cases, we have decided to FORCE these fonts to be drawn with at least grayscale AA,
- * even when the System (getDefaultGDITextFlags) tells us to draw only in BW.
- */
- if (isWebFont(lf) && !isRunningLayoutTest())
- textFlags |= SkPaint::kAntiAlias_Flag;
- return textFlags;
-}
-
-PassRefPtr<SkTypeface> CreateTypefaceFromHFont(HFONT hfont, int* size, int* paintTextFlags)
-{
- LOGFONT info;
- GetObject(hfont, sizeof(info), &info);
- if (size) {
- int height = info.lfHeight;
- if (height < 0)
- height = -height;
- *size = height;
- }
- if (paintTextFlags)
- *paintTextFlags = computePaintTextFlags(info);
- return adoptRef(SkCreateTypefaceFromLOGFONT(info));
-}
-
-FontPlatformData::FontPlatformData(WTF::HashTableDeletedValueType)
- : m_font(0)
- , m_size(-1)
- , m_orientation(Horizontal)
- , m_scriptCache(0)
- , m_typeface(SkTypeface::RefDefault())
- , m_paintTextFlags(0)
- , m_isHashTableDeletedValue(true)
-{
-}
-
-FontPlatformData::FontPlatformData()
- : m_font(0)
- , m_size(0)
- , m_orientation(Horizontal)
- , m_scriptCache(0)
- , m_typeface(SkTypeface::RefDefault())
- , m_paintTextFlags(0)
- , m_isHashTableDeletedValue(false)
-{
-}
-
-FontPlatformData::FontPlatformData(HFONT font, float size, FontOrientation orientation)
- : m_font(RefCountedHFONT::create(font))
- , m_size(size)
- , m_orientation(orientation)
- , m_scriptCache(0)
- , m_typeface(CreateTypefaceFromHFont(font, 0, &m_paintTextFlags))
- , m_isHashTableDeletedValue(false)
-{
-}
-
-// FIXME: this constructor is needed for SVG fonts but doesn't seem to do much
-FontPlatformData::FontPlatformData(float size, bool bold, bool oblique)
- : m_font(0)
- , m_size(size)
- , m_orientation(Horizontal)
- , m_scriptCache(0)
- , m_typeface(SkTypeface::RefDefault())
- , m_paintTextFlags(0)
- , m_isHashTableDeletedValue(false)
-{
-}
-
-FontPlatformData::FontPlatformData(const FontPlatformData& data)
- : m_font(data.m_font)
- , m_size(data.m_size)
- , m_orientation(data.m_orientation)
- , m_scriptCache(0)
- , m_typeface(data.m_typeface)
- , m_paintTextFlags(data.m_paintTextFlags)
- , m_isHashTableDeletedValue(false)
-{
-}
-
-FontPlatformData::FontPlatformData(const FontPlatformData& data, float textSize)
- : m_font(data.m_font)
- , m_size(textSize)
- , m_orientation(data.m_orientation)
- , m_scriptCache(0)
- , m_typeface(data.m_typeface)
- , m_paintTextFlags(data.m_paintTextFlags)
- , m_isHashTableDeletedValue(false)
-{
-}
-
-FontPlatformData::FontPlatformData(SkTypeface* tf, const char* family, float textSize, bool fakeBold, bool fakeItalic, FontOrientation orientation)
- : m_font(0)
- , m_size(textSize)
- , m_orientation(orientation)
- , m_scriptCache(0)
- , m_typeface(tf)
- , m_isHashTableDeletedValue(false)
-{
- // FIXME: This can be removed together with m_font once the last few
- // uses of hfont() has been eliminated.
- LOGFONT logFont;
- SkLOGFONTFromTypeface(tf, &logFont);
- logFont.lfHeight = -textSize;
- HFONT hFont = CreateFontIndirect(&logFont);
- if (hFont)
- m_font = RefCountedHFONT::create(hFont);
- m_paintTextFlags = computePaintTextFlags(logFont);
-}
-
-FontPlatformData& FontPlatformData::operator=(const FontPlatformData& data)
-{
- if (this != &data) {
- m_font = data.m_font;
- m_size = data.m_size;
- m_orientation = data.m_orientation;
- m_typeface = data.m_typeface;
- m_paintTextFlags = data.m_paintTextFlags;
-
- // The following fields will get re-computed if necessary.
- ScriptFreeCache(&m_scriptCache);
- m_scriptCache = 0;
- m_scriptFontProperties.clear();
- }
- return *this;
-}
-
-FontPlatformData::~FontPlatformData()
-{
- ScriptFreeCache(&m_scriptCache);
- m_scriptCache = 0;
-}
-
-String FontPlatformData::fontFamilyName() const
-{
- HWndDC dc(0);
- HGDIOBJ oldFont = static_cast<HFONT>(SelectObject(dc, hfont()));
- WCHAR name[LF_FACESIZE];
- unsigned resultLength = GetTextFace(dc, LF_FACESIZE, name);
- if (resultLength > 0)
- resultLength--; // ignore the null terminator
- SelectObject(dc, oldFont);
- return String(name, resultLength);
-}
-
-bool FontPlatformData::isFixedPitch() const
-{
-#if ENABLE(GDI_FONTS_ON_WINDOWS)
- // TEXTMETRICS have this. Set m_treatAsFixedPitch based off that.
- HWndDC dc(0);
- HGDIOBJ oldFont = SelectObject(dc, hfont());
-
- // Yes, this looks backwards, but the fixed pitch bit is actually set if the font
- // is *not* fixed pitch. Unbelievable but true.
- TEXTMETRIC textMetric = { 0 };
- if (!GetTextMetrics(dc, &textMetric)) {
- if (ensureFontLoaded(hfont())) {
- // Retry GetTextMetrics.
- // FIXME: Handle gracefully the error if this call also fails.
- // See http://crbug.com/6401.
- if (!GetTextMetrics(dc, &textMetric))
- LOG_ERROR("Unable to get the text metrics after second attempt");
- }
- }
-
- bool treatAsFixedPitch = !(textMetric.tmPitchAndFamily & TMPF_FIXED_PITCH);
-
- SelectObject(dc, oldFont);
-
- return treatAsFixedPitch;
-#else
- return typeface() && typeface()->isFixedPitch();
-#endif
-}
-
-FontPlatformData::RefCountedHFONT::~RefCountedHFONT()
-{
- DeleteObject(m_hfont);
-}
-
-SCRIPT_FONTPROPERTIES* FontPlatformData::scriptFontProperties() const
-{
- if (!m_scriptFontProperties) {
- m_scriptFontProperties = adoptPtr(new SCRIPT_FONTPROPERTIES);
- memset(m_scriptFontProperties.get(), 0, sizeof(SCRIPT_FONTPROPERTIES));
- m_scriptFontProperties->cBytes = sizeof(SCRIPT_FONTPROPERTIES);
- HRESULT result = ScriptGetFontProperties(0, scriptCache(), m_scriptFontProperties.get());
- if (result == E_PENDING) {
- HWndDC dc(0);
- HGDIOBJ oldFont = SelectObject(dc, hfont());
- HRESULT hr = ScriptGetFontProperties(dc, scriptCache(), m_scriptFontProperties.get());
- if (S_OK != hr) {
- if (FontPlatformData::ensureFontLoaded(hfont())) {
- // FIXME: Handle gracefully the error if this call also fails.
- hr = ScriptGetFontProperties(dc, scriptCache(), m_scriptFontProperties.get());
- if (S_OK != hr) {
- LOG_ERROR("Unable to get the font properties after second attempt");
- }
- }
- }
-
- SelectObject(dc, oldFont);
- }
- }
- return m_scriptFontProperties.get();
-}
-
-#ifndef NDEBUG
-String FontPlatformData::description() const
-{
- return String();
-}
-#endif
-
-bool FontPlatformData::ensureFontLoaded(HFONT font)
-{
- WebKit::WebSandboxSupport* sandboxSupport = WebKit::Platform::current()->sandboxSupport();
- // if there is no sandbox, then we can assume the font
- // was able to be loaded successfully already
- return sandboxSupport ? sandboxSupport->ensureFontLoaded(font) : true;
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/FontPlatformDataChromiumWin.h b/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/FontPlatformDataChromiumWin.h
deleted file mode 100644
index e2a5c05ba5f..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/FontPlatformDataChromiumWin.h
+++ /dev/null
@@ -1,173 +0,0 @@
-/*
- * Copyright (C) 2006, 2007 Apple Computer, Inc.
- * Copyright (c) 2006, 2007, 2008, 2009, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef FontPlatformDataChromiumWin_h
-#define FontPlatformDataChromiumWin_h
-
-#include "config.h"
-
-#include "../ports/SkTypeface_win.h"
-#include "SkPaint.h"
-#include "SkTypeface.h"
-#include "core/platform/SharedBuffer.h"
-#include "core/platform/graphics/FontOrientation.h"
-#include "core/platform/graphics/opentype/OpenTypeVerticalData.h"
-#include "wtf/Forward.h"
-#include "wtf/HashTableDeletedValueType.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/RefPtr.h"
-#include "wtf/text/StringImpl.h"
-
-#include <usp10.h>
-
-typedef struct HFONT__ *HFONT;
-
-namespace WebCore {
-
-// Return a typeface associated with the hfont, and return its size and
-// lfQuality from the hfont's LOGFONT.
-PassRefPtr<SkTypeface> CreateTypefaceFromHFont(HFONT, int* size, int* paintTextFlags);
-
-class FontDescription;
-
-class FontPlatformData {
-public:
- // Used for deleted values in the font cache's hash tables. The hash table
- // will create us with this structure, and it will compare other values
- // to this "Deleted" one. It expects the Deleted one to be differentiable
- // from the NULL one (created with the empty constructor), so we can't just
- // set everything to NULL.
- FontPlatformData(WTF::HashTableDeletedValueType);
- FontPlatformData();
- // This constructor takes ownership of the HFONT
- FontPlatformData(HFONT, float size, FontOrientation);
- FontPlatformData(float size, bool bold, bool oblique);
- FontPlatformData(const FontPlatformData&);
- FontPlatformData(const FontPlatformData&, float textSize);
- FontPlatformData(SkTypeface*, const char* name, float textSize, bool fakeBold, bool fakeItalic, FontOrientation = Horizontal);
-
-#if !ENABLE(GDI_FONTS_ON_WINDOWS)
- void setupPaint(SkPaint*) const;
-#endif
-
- FontPlatformData& operator=(const FontPlatformData&);
-
- bool isHashTableDeletedValue() const { return m_isHashTableDeletedValue; }
-
- ~FontPlatformData();
-
- bool isFixedPitch() const;
- HFONT hfont() const { return m_font ? m_font->hfont() : 0; }
- float size() const { return m_size; }
- SkTypeface* typeface() const { return m_typeface.get(); }
- int paintTextFlags() const { return m_paintTextFlags; }
-
- String fontFamilyName() const;
-
- FontOrientation orientation() const { return m_orientation; }
- void setOrientation(FontOrientation orientation) { m_orientation = orientation; }
-
- unsigned hash() const
- {
- return m_font ? m_font->hash() : NULL;
- }
-
- bool operator==(const FontPlatformData& other) const
- {
- return m_font == other.m_font && m_size == other.m_size && m_orientation == other.m_orientation;
- }
-
-#if ENABLE(OPENTYPE_VERTICAL)
- PassRefPtr<OpenTypeVerticalData> verticalData() const;
- PassRefPtr<SharedBuffer> openTypeTable(uint32_t table) const;
-#endif
-
-#ifndef NDEBUG
- String description() const;
-#endif
-
- SCRIPT_FONTPROPERTIES* scriptFontProperties() const;
- SCRIPT_CACHE* scriptCache() const { return &m_scriptCache; }
-
- static bool ensureFontLoaded(HFONT);
-
-private:
- // We refcount the internal HFONT so that FontPlatformData can be
- // efficiently copied. WebKit depends on being able to copy it, and we
- // don't really want to re-create the HFONT.
- class RefCountedHFONT : public RefCounted<RefCountedHFONT> {
- public:
- static PassRefPtr<RefCountedHFONT> create(HFONT hfont)
- {
- return adoptRef(new RefCountedHFONT(hfont));
- }
-
- ~RefCountedHFONT();
-
- HFONT hfont() const { return m_hfont; }
- unsigned hash() const
- {
- return StringHasher::hashMemory<sizeof(HFONT)>(&m_hfont);
- }
-
- bool operator==(const RefCountedHFONT& other) const
- {
- return m_hfont == other.m_hfont;
- }
-
- private:
- // The create() function assumes there is already a refcount of one
- // so it can do adoptRef.
- RefCountedHFONT(HFONT hfont) : m_hfont(hfont)
- {
- }
-
- HFONT m_hfont;
- };
-
- RefPtr<RefCountedHFONT> m_font;
- float m_size; // Point size of the font in pixels.
- FontOrientation m_orientation;
-
- RefPtr<SkTypeface> m_typeface; // cached from m_font
- int m_paintTextFlags; // cached from m_font
-
- mutable SCRIPT_CACHE m_scriptCache;
- mutable OwnPtr<SCRIPT_FONTPROPERTIES> m_scriptFontProperties;
-
- bool m_isHashTableDeletedValue;
-};
-
-} // WebCore
-
-#endif // FontPlatformDataChromiumWin_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/FontRenderStyle.h b/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/FontRenderStyle.h
deleted file mode 100644
index e44abb44782..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/FontRenderStyle.h
+++ /dev/null
@@ -1,77 +0,0 @@
-/* Copyright (c) 2010, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef FontRenderStyle_h
-#define FontRenderStyle_h
-
-namespace WebCore {
-
-// FontRenderStyle describes the user's preferences for rendering a font at a
-// given size.
-struct FontRenderStyle {
- enum {
- NoPreference = 2,
- };
-
- FontRenderStyle()
- : useBitmaps(0)
- , useAutoHint(0)
- , useHinting(0)
- , hintStyle(0)
- , useAntiAlias(0)
- , useSubpixelRendering(0)
- , useSubpixelPositioning(0) { }
-
- bool operator==(const FontRenderStyle& a) const
- {
- return useBitmaps == a.useBitmaps
- && useAutoHint == a.useAutoHint
- && useHinting == a.useHinting
- && hintStyle == a.hintStyle
- && useAntiAlias == a.useAntiAlias
- && useSubpixelRendering == a.useSubpixelRendering
- && useSubpixelPositioning == a.useSubpixelPositioning;
- }
-
- // Each of the use* members below can take one of three values:
- // 0: off
- // 1: on
- // NoPreference: no preference expressed
- char useBitmaps; // use embedded bitmap strike if possible
- char useAutoHint; // use 'auto' hinting (FreeType specific)
- char useHinting; // hint glyphs to the pixel grid
- char hintStyle; // level of hinting, 0..3
- char useAntiAlias; // antialias glyph shapes
- char useSubpixelRendering; // use subpixel rendering (partially-filled pixels)
- char useSubpixelPositioning; // use subpixel positioning (fractional X positions for glyphs)
-};
-
-}
-
-#endif // FontRenderStyle_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/FontUtilsChromiumWin.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/FontUtilsChromiumWin.cpp
deleted file mode 100644
index a73198a5f76..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/FontUtilsChromiumWin.cpp
+++ /dev/null
@@ -1,457 +0,0 @@
-/*
- * Copyright (c) 2006, 2007, 2008, 2009, 2010, 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/chromium/FontUtilsChromiumWin.h"
-
-#include <limits>
-
-#include <unicode/locid.h>
-#include <unicode/uchar.h>
-#include "core/platform/graphics/chromium/UniscribeHelper.h"
-#include "core/platform/win/HWndDC.h"
-#include "wtf/HashMap.h"
-#include "wtf/text/StringHash.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-namespace {
-
-bool isFontPresent(const UChar* fontName)
-{
- HFONT hfont = CreateFont(12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- fontName);
- if (!hfont)
- return false;
- HWndDC dc(0);
- HGDIOBJ oldFont = static_cast<HFONT>(SelectObject(dc, hfont));
- WCHAR actualFontName[LF_FACESIZE];
- GetTextFace(dc, LF_FACESIZE, actualFontName);
- actualFontName[LF_FACESIZE - 1] = 0;
- SelectObject(dc, oldFont);
- DeleteObject(hfont);
- // We don't have to worry about East Asian fonts with locale-dependent
- // names here for now.
- return !wcscmp(fontName, actualFontName);
-}
-
-// A simple mapping from UScriptCode to family name. This is a sparse array,
-// which works well since the range of UScriptCode values is small.
-typedef const UChar* ScriptToFontMap[USCRIPT_CODE_LIMIT];
-
-void initializeScriptFontMap(ScriptToFontMap& scriptFontMap)
-{
- struct FontMap {
- UScriptCode script;
- const UChar* family;
- };
-
- static const FontMap fontMap[] = {
- {USCRIPT_LATIN, L"times new roman"},
- {USCRIPT_GREEK, L"times new roman"},
- {USCRIPT_CYRILLIC, L"times new roman"},
- // FIXME: Consider trying new Vista fonts before XP fonts for CJK.
- // Some Vista users do want to use Vista cleartype CJK fonts. If we
- // did, the results of tests with CJK characters would have to be
- // regenerated for Vista.
- {USCRIPT_SIMPLIFIED_HAN, L"simsun"},
- {USCRIPT_TRADITIONAL_HAN, L"pmingliu"},
- {USCRIPT_HIRAGANA, L"ms pgothic"},
- {USCRIPT_KATAKANA, L"ms pgothic"},
- {USCRIPT_KATAKANA_OR_HIRAGANA, L"ms pgothic"},
- {USCRIPT_HANGUL, L"gulim"},
- {USCRIPT_THAI, L"tahoma"},
- {USCRIPT_HEBREW, L"david"},
- {USCRIPT_ARABIC, L"tahoma"},
- {USCRIPT_DEVANAGARI, L"mangal"},
- {USCRIPT_BENGALI, L"vrinda"},
- {USCRIPT_GURMUKHI, L"raavi"},
- {USCRIPT_GUJARATI, L"shruti"},
- {USCRIPT_TAMIL, L"latha"},
- {USCRIPT_TELUGU, L"gautami"},
- {USCRIPT_KANNADA, L"tunga"},
- {USCRIPT_GEORGIAN, L"sylfaen"},
- {USCRIPT_ARMENIAN, L"sylfaen"},
- {USCRIPT_THAANA, L"mv boli"},
- {USCRIPT_CANADIAN_ABORIGINAL, L"euphemia"},
- {USCRIPT_CHEROKEE, L"plantagenet cherokee"},
- {USCRIPT_MONGOLIAN, L"mongolian balti"},
- // For USCRIPT_COMMON, we map blocks to scripts when
- // that makes sense.
- };
-
- struct ScriptToFontFamilies {
- UScriptCode script;
- const UChar** families;
- };
-
- // Kartika on Vista or earlier lacks the support for Chillu
- // letters added to Unicode 5.1.
- // Try AnjaliOldLipi (a very widely used Malaylalam font with the full
- // Unicode 5.x support) before falling back to Kartika.
- static const UChar* malayalamFonts[] = {L"AnjaliOldLipi", L"Lohit Malayalam", L"Kartika", L"Rachana", 0};
- // Try Khmer OS before Vista fonts because 'Khmer OS' goes along better
- // with Latin and looks better/larger for the same size.
- static const UChar* khmerFonts[] = {L"Khmer OS", L"MoolBoran", L"DaunPenh", L"Code2000", 0};
- // For the following 6 scripts, two or fonts are listed. The fonts in
- // the 1st slot are not available on Windows XP. To support these
- // scripts on XP, listed in the rest of slots are widely used
- // fonts.
- static const UChar* ethiopicFonts[] = {L"Nyala", L"Abyssinica SIL", L"Ethiopia Jiret", L"Visual Geez Unicode", L"GF Zemen Unicode", 0};
- static const UChar* oriyaFonts[] = {L"Kalinga", L"ori1Uni", L"Lohit Oriya", 0};
- static const UChar* laoFonts[] = {L"DokChampa", L"Saysettha OT", L"Phetsarath OT", L"Code2000", 0};
- static const UChar* tibetanFonts[] = {L"Microsoft Himalaya", L"Jomolhari", L"Tibetan Machine Uni", 0};
- static const UChar* sinhalaFonts[] = {L"Iskoola Pota", L"AksharUnicode", 0};
- static const UChar* yiFonts[] = {L"Microsoft Yi Balti", L"Nuosu SIL", L"Code2000", 0};
- // http://www.bethmardutho.org/support/meltho/download/index.php
- static const UChar* syriacFonts[] = {L"Estrangelo Edessa", L"Estrangelo Nisibin", L"Code2000", 0};
- // No Myanmar/Burmese font is shipped with Windows, yet. Try a few
- // widely available/used ones that supports Unicode 5.1 or later.
- static const UChar* myanmarFonts[] = {L"Padauk", L"Parabaik", L"Myanmar3", L"Code2000", 0};
-
- static const ScriptToFontFamilies scriptToFontFamilies[] = {
- {USCRIPT_MALAYALAM, malayalamFonts},
- {USCRIPT_KHMER, khmerFonts},
- {USCRIPT_ETHIOPIC, ethiopicFonts},
- {USCRIPT_ORIYA, oriyaFonts},
- {USCRIPT_LAO, laoFonts},
- {USCRIPT_TIBETAN, tibetanFonts},
- {USCRIPT_SINHALA, sinhalaFonts},
- {USCRIPT_YI, yiFonts},
- {USCRIPT_SYRIAC, syriacFonts},
- {USCRIPT_MYANMAR, myanmarFonts},
- };
-
- for (size_t i = 0; i < WTF_ARRAY_LENGTH(fontMap); ++i)
- scriptFontMap[fontMap[i].script] = fontMap[i].family;
-
- // FIXME: Instead of scanning the hard-coded list, we have to
- // use EnumFont* to 'inspect' fonts to pick up fonts covering scripts
- // when it's possible (e.g. using OS/2 table). If we do that, this
- // had better be pulled out of here.
- for (size_t i = 0; i < WTF_ARRAY_LENGTH(scriptToFontFamilies); ++i) {
- UScriptCode script = scriptToFontFamilies[i].script;
- scriptFontMap[script] = 0;
- const UChar** familyPtr = scriptToFontFamilies[i].families;
- while (*familyPtr) {
- if (isFontPresent(*familyPtr)) {
- scriptFontMap[script] = *familyPtr;
- break;
- }
- ++familyPtr;
- }
- }
-
- // Initialize the locale-dependent mapping.
- // Since Chrome synchronizes the ICU default locale with its UI locale,
- // this ICU locale tells the current UI locale of Chrome.
- icu::Locale locale = icu::Locale::getDefault();
- const UChar* localeFamily = 0;
- if (locale == icu::Locale::getJapanese())
- localeFamily = scriptFontMap[USCRIPT_HIRAGANA];
- else if (locale == icu::Locale::getKorean())
- localeFamily = scriptFontMap[USCRIPT_HANGUL];
- else if (locale == icu::Locale::getTraditionalChinese())
- localeFamily = scriptFontMap[USCRIPT_TRADITIONAL_HAN];
- else {
- // For other locales, use the simplified Chinese font for Han.
- localeFamily = scriptFontMap[USCRIPT_SIMPLIFIED_HAN];
- }
- if (localeFamily)
- scriptFontMap[USCRIPT_HAN] = localeFamily;
-}
-
-// There are a lot of characters in USCRIPT_COMMON that can be covered
-// by fonts for scripts closely related to them. See
-// http://unicode.org/cldr/utility/list-unicodeset.jsp?a=[:Script=Common:]
-// FIXME: make this more efficient with a wider coverage
-UScriptCode getScriptBasedOnUnicodeBlock(int ucs4)
-{
- UBlockCode block = ublock_getCode(ucs4);
- switch (block) {
- case UBLOCK_CJK_SYMBOLS_AND_PUNCTUATION:
- return USCRIPT_HAN;
- case UBLOCK_HIRAGANA:
- case UBLOCK_KATAKANA:
- return USCRIPT_HIRAGANA;
- case UBLOCK_ARABIC:
- return USCRIPT_ARABIC;
- case UBLOCK_THAI:
- return USCRIPT_THAI;
- case UBLOCK_GREEK:
- return USCRIPT_GREEK;
- case UBLOCK_DEVANAGARI:
- // For Danda and Double Danda (U+0964, U+0965), use a Devanagari
- // font for now although they're used by other scripts as well.
- // Without a context, we can't do any better.
- return USCRIPT_DEVANAGARI;
- case UBLOCK_ARMENIAN:
- return USCRIPT_ARMENIAN;
- case UBLOCK_GEORGIAN:
- return USCRIPT_GEORGIAN;
- case UBLOCK_KANNADA:
- return USCRIPT_KANNADA;
- default:
- return USCRIPT_COMMON;
- }
-}
-
-UScriptCode getScript(int ucs4)
-{
- UErrorCode err = U_ZERO_ERROR;
- UScriptCode script = uscript_getScript(ucs4, &err);
- // If script is invalid, common or inherited or there's an error,
- // infer a script based on the unicode block of a character.
- if (script <= USCRIPT_INHERITED || U_FAILURE(err))
- script = getScriptBasedOnUnicodeBlock(ucs4);
- return script;
-}
-
-const int kUndefinedAscent = std::numeric_limits<int>::min();
-
-// Given an HFONT, return the ascent. If GetTextMetrics fails,
-// kUndefinedAscent is returned, instead.
-int getAscent(HFONT hfont)
-{
- HWndDC dc(0);
- HGDIOBJ oldFont = SelectObject(dc, hfont);
- TEXTMETRIC tm;
- BOOL gotMetrics = GetTextMetrics(dc, &tm);
- SelectObject(dc, oldFont);
- return gotMetrics ? tm.tmAscent : kUndefinedAscent;
-}
-
-const WORD kUnsupportedGlyph = 0xffff;
-
-WORD getSpaceGlyph(HFONT hfont)
-{
- HWndDC dc(0);
- HGDIOBJ oldFont = SelectObject(dc, hfont);
- WCHAR space = L' ';
- WORD spaceGlyph = kUnsupportedGlyph;
- GetGlyphIndices(dc, &space, 1, &spaceGlyph, GGI_MARK_NONEXISTING_GLYPHS);
- SelectObject(dc, oldFont);
- return spaceGlyph;
-}
-
-struct FontData {
- FontData()
- : hfont(0)
- , ascent(kUndefinedAscent)
- , scriptCache(0)
- , spaceGlyph(0)
- {
- }
-
- HFONT hfont;
- int ascent;
- mutable SCRIPT_CACHE scriptCache;
- WORD spaceGlyph;
-};
-
-// Again, using hash_map does not earn us much here. page_cycler_test intl2
-// gave us a 'better' result with map than with hash_map even though they're
-// well-within 1-sigma of each other so that the difference is not significant.
-// On the other hand, some pages in intl2 seem to take longer to load with map
-// in the 1st pass. Need to experiment further.
-typedef HashMap<String, FontData> FontDataCache;
-
-} // namespace
-
-// FIXME: this is font fallback code version 0.1
-// - Cover all the scripts
-// - Get the default font for each script/generic family from the
-// preference instead of hardcoding in the source.
-// (at least, read values from the registry for IE font settings).
-// - Support generic families (from FontDescription)
-// - If the default font for a script is not available,
-// try some more fonts known to support it. Finally, we can
-// use EnumFontFamilies or similar APIs to come up with a list of
-// fonts supporting the script and cache the result.
-// - Consider using UnicodeSet (or UnicodeMap) converted from
-// GLYPHSET (BMP) or directly read from truetype cmap tables to
-// keep track of which character is supported by which font
-// - Update script_font_cache in response to WM_FONTCHANGE
-
-const UChar* getFontFamilyForScript(UScriptCode script,
- FontDescription::GenericFamilyType generic)
-{
- static ScriptToFontMap scriptFontMap;
- static bool initialized = false;
- if (!initialized) {
- initializeScriptFontMap(scriptFontMap);
- initialized = true;
- }
- if (script == USCRIPT_INVALID_CODE)
- return 0;
- ASSERT(script < USCRIPT_CODE_LIMIT);
- return scriptFontMap[script];
-}
-
-// FIXME:
-// - Handle 'Inherited', 'Common' and 'Unknown'
-// (see http://www.unicode.org/reports/tr24/#Usage_Model )
-// For 'Inherited' and 'Common', perhaps we need to
-// accept another parameter indicating the previous family
-// and just return it.
-// - All the characters (or characters up to the point a single
-// font can cover) need to be taken into account
-const UChar* getFallbackFamily(const UChar* characters,
- int length,
- FontDescription::GenericFamilyType generic,
- UChar32* charChecked,
- UScriptCode* scriptChecked)
-{
- ASSERT(characters && characters[0] && length > 0);
- UScriptCode script = USCRIPT_COMMON;
-
- // Sometimes characters common to script (e.g. space) is at
- // the beginning of a string so that we need to skip them
- // to get a font required to render the string.
- int i = 0;
- UChar32 ucs4 = 0;
- while (i < length && script == USCRIPT_COMMON) {
- U16_NEXT(characters, i, length, ucs4);
- script = getScript(ucs4);
- }
-
- // For the full-width ASCII characters (U+FF00 - U+FF5E), use the font for
- // Han (determined in a locale-dependent way above). Full-width ASCII
- // characters are rather widely used in Japanese and Chinese documents and
- // they're fully covered by Chinese, Japanese and Korean fonts.
- if (0xFF00 < ucs4 && ucs4 < 0xFF5F)
- script = USCRIPT_HAN;
-
- if (script == USCRIPT_COMMON)
- script = getScriptBasedOnUnicodeBlock(ucs4);
-
- const UChar* family = getFontFamilyForScript(script, generic);
- // Another lame work-around to cover non-BMP characters.
- // If the font family for script is not found or the character is
- // not in BMP (> U+FFFF), we resort to the hard-coded list of
- // fallback fonts for now.
- if (!family || ucs4 > 0xFFFF) {
- int plane = ucs4 >> 16;
- switch (plane) {
- case 1:
- family = L"code2001";
- break;
- case 2:
- // Use a Traditional Chinese ExtB font if in Traditional Chinese locale.
- // Otherwise, use a Simplified Chinese ExtB font. Windows Japanese
- // fonts do support a small subset of ExtB (that are included in JIS X 0213),
- // but its coverage is rather sparse.
- // Eventually, this should be controlled by lang/xml:lang.
- if (icu::Locale::getDefault() == icu::Locale::getTraditionalChinese())
- family = L"pmingliu-extb";
- else
- family = L"simsun-extb";
- break;
- default:
- family = L"lucida sans unicode";
- }
- }
-
- if (charChecked)
- *charChecked = ucs4;
- if (scriptChecked)
- *scriptChecked = script;
- return family;
-}
-
-// Be aware that this is not thread-safe.
-bool getDerivedFontData(const UChar* family,
- int style,
- LOGFONT* logfont,
- int* ascent,
- HFONT* hfont,
- SCRIPT_CACHE** scriptCache,
- WORD* spaceGlyph)
-{
- ASSERT(logfont);
- ASSERT(family);
- ASSERT(*family);
-
- // It does not matter that we leak font data when we exit.
- static FontDataCache fontDataCache;
-
- // FIXME: This comes up pretty high in the profile so that
- // we need to measure whether using SHA256 (after coercing all the
- // fields to char*) is faster than String::format.
- String fontKey = String::format("%1d:%d:%ls", style, logfont->lfHeight, family);
- FontDataCache::iterator iter = fontDataCache.find(fontKey);
- FontData* derived;
- if (iter == fontDataCache.end()) {
- ASSERT(wcslen(family) < LF_FACESIZE);
- wcscpy_s(logfont->lfFaceName, LF_FACESIZE, family);
- // FIXME: CreateFontIndirect always comes up with
- // a font even if there's no font matching the name. Need to
- // check it against what we actually want (as is done in
- // FontCacheWin.cpp)
- FontDataCache::AddResult entry = fontDataCache.add(fontKey, FontData());
- derived = &entry.iterator->value;
- derived->hfont = CreateFontIndirect(logfont);
- // GetAscent may return kUndefinedAscent, but we still want to
- // cache it so that we won't have to call CreateFontIndirect once
- // more for HFONT next time.
- derived->ascent = getAscent(derived->hfont);
- derived->spaceGlyph = getSpaceGlyph(derived->hfont);
- } else {
- derived = &iter->value;
- // Last time, getAscent or getSpaceGlyph failed so that only HFONT was
- // cached. Try once more assuming that TryPreloadFont
- // was called by a caller between calls.
- if (kUndefinedAscent == derived->ascent)
- derived->ascent = getAscent(derived->hfont);
- if (kUnsupportedGlyph == derived->spaceGlyph)
- derived->spaceGlyph = getSpaceGlyph(derived->hfont);
- }
- *hfont = derived->hfont;
- *ascent = derived->ascent;
- *scriptCache = &(derived->scriptCache);
- *spaceGlyph = derived->spaceGlyph;
- return *ascent != kUndefinedAscent && *spaceGlyph != kUnsupportedGlyph;
-}
-
-int getStyleFromLogfont(const LOGFONT* logfont)
-{
- // FIXME: consider defining UNDEFINED or INVALID for style and
- // returning it when logfont is 0
- if (!logfont) {
- ASSERT_NOT_REACHED();
- return FontStyleNormal;
- }
- return (logfont->lfItalic ? FontStyleItalic : FontStyleNormal) |
- (logfont->lfUnderline ? FontStyleUnderlined : FontStyleNormal) |
- (logfont->lfWeight >= 700 ? FontStyleBold : FontStyleNormal);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/FontUtilsChromiumWin.h b/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/FontUtilsChromiumWin.h
deleted file mode 100644
index ef2eea2710d..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/FontUtilsChromiumWin.h
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * Copyright (c) 2006, 2007, 2008, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-// A collection of utilities for font handling.
-
-// FIXME: Move all methods to the files that have their callsites and remove this file.
-// *Utils files are not very WebKit-ty.
-
-#ifndef FontUtilsChromiumWin_h
-#define FontUtilsChromiumWin_h
-
-#include <windows.h>
-#include <usp10.h>
-#include <wchar.h>
-
-#include <unicode/uscript.h>
-#include "core/platform/graphics/FontDescription.h"
-
-namespace WebCore {
-
-// Return a font family that supports a script and belongs to |generic| font
-// family. It can return NULL and a caller has to implement its own fallback.
-const UChar* getFontFamilyForScript(UScriptCode, FontDescription::GenericFamilyType);
-
-// Return a font family that can render |characters| based on
-// what script characters belong to. When char_checked is non-NULL,
-// it's filled with the character used to determine the script.
-// When script_checked is non-NULL, the script used to determine
-// the family is returned.
-// FIXME: This function needs a total overhaul.
-const UChar* getFallbackFamily(const UChar* characters, int length,
- FontDescription::GenericFamilyType,
- UChar32* charChecked,
- UScriptCode* scriptChecked);
-
-// Derive a new HFONT by replacing lfFaceName of LOGFONT with |family|,
-// calculate the ascent for the derived HFONT, and initialize SCRIPT_CACHE
-// in FontData.
-// |style| is only used for cache key generation. |style| is
-// bit-wise OR of BOLD(1), UNDERLINED(2) and ITALIC(4) and
-// should match what's contained in LOGFONT. It should be calculated
-// by calling GetStyleFromLogFont.
-// Returns false if the font is not accessible, in which case |ascent| field
-// of |fontdata| is set to kUndefinedAscent.
-// Be aware that this is not thread-safe.
-// FIXME: Instead of having three out params, we'd better have one
-// (|*FontData|), but somehow it mysteriously messes up the layout for
-// certain complex script pages (e.g. hi.wikipedia.org) and also crashes
-// at the start-up if recently visited page list includes pages with complex
-// scripts in their title. Moreover, somehow the very first-pass of
-// intl2 page-cycler test is noticeably slower with one out param than
-// the current version although the subsequent 9 passes take about the
-// same time.
-bool getDerivedFontData(const UChar* family, int style, LOGFONT*, int* ascent, HFONT*, SCRIPT_CACHE**, WORD* spaceGlyph);
-
-enum {
- FontStyleNormal = 0,
- FontStyleBold = 1,
- FontStyleItalic = 2,
- FontStyleUnderlined = 4
-};
-
-// Derive style (bit-wise OR of FONT_STYLE_BOLD, FONT_STYLE_UNDERLINED, and
-// FONT_STYLE_ITALIC) from LOGFONT. Returns 0 if |*logfont| is NULL.
-int getStyleFromLogfont(const LOGFONT*);
-
-} // namespace WebCore
-
-#endif // FontUtilsChromiumWin_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/GlyphPageTreeNodeChromiumWin.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/GlyphPageTreeNodeChromiumWin.cpp
deleted file mode 100644
index cd9eb6b6aa7..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/GlyphPageTreeNodeChromiumWin.cpp
+++ /dev/null
@@ -1,258 +0,0 @@
-/*
- * Copyright (c) 2008, 2009, 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <windows.h>
-#include "config.h"
-#include <vector>
-
-#include "core/platform/graphics/Font.h"
-#include "core/platform/graphics/GlyphPageTreeNode.h"
-#include "core/platform/graphics/SimpleFontData.h"
-#include "core/platform/graphics/chromium/FontPlatformDataChromiumWin.h"
-#include "core/platform/graphics/chromium/UniscribeHelperTextRun.h"
-#include "core/platform/win/HWndDC.h"
-#include "core/platform/win/SystemInfo.h"
-
-namespace WebCore {
-
-// Fills one page of font data pointers with 0 to indicate that there
-// are no glyphs for the characters.
-static void fillEmptyGlyphs(GlyphPage* page)
-{
- for (int i = 0; i < GlyphPage::size; ++i)
- page->setGlyphDataForIndex(i, 0, 0);
-}
-
-// Convert characters to glyph ids by GetGlyphIndices(), during which, we
-// ensure the font is loaded in memory to make it work in a sandboxed process.
-static bool getGlyphIndices(HFONT font, HDC dc, const UChar* characters, unsigned charactersLength, WORD* glyphBuffer, DWORD flag)
-{
- if (GetGlyphIndices(dc, characters, charactersLength, glyphBuffer, flag) != GDI_ERROR)
- return true;
- if (FontPlatformData::ensureFontLoaded(font)) {
- if (GetGlyphIndices(dc, characters, charactersLength, glyphBuffer, flag) != GDI_ERROR)
- return true;
- // FIXME: Handle gracefully the error if this call also fails.
- // See http://crbug.com/6401
- LOG_ERROR("Unable to get the glyph indices after second attempt");
- }
- return false;
-}
-
-// Initializes space glyph
-static bool initSpaceGlyph(HFONT font, HDC dc, Glyph* spaceGlyph)
-{
- static wchar_t space = ' ';
- return getGlyphIndices(font, dc, &space, 1, spaceGlyph, 0);
-}
-
-// Fills |length| glyphs starting at |offset| in a |page| in the Basic
-// Multilingual Plane (<= U+FFFF). The input buffer size should be the
-// same as |length|. We can use the standard Windows GDI functions here.
-// Returns true if any glyphs were found.
-static bool fillBMPGlyphs(unsigned offset,
- unsigned length,
- UChar* buffer,
- GlyphPage* page,
- const SimpleFontData* fontData)
-{
- HWndDC dc(0);
- HGDIOBJ oldFont = SelectObject(dc, fontData->platformData().hfont());
-
- TEXTMETRIC tm = {0};
- if (!GetTextMetrics(dc, &tm)) {
- if (FontPlatformData::ensureFontLoaded(fontData->platformData().hfont())) {
- if (!GetTextMetrics(dc, &tm)) {
- // FIXME: Handle gracefully the error if this call also fails.
- // See http://crbug.com/6401
- LOG_ERROR("Unable to get the text metrics after second attempt");
-
- SelectObject(dc, oldFont);
- fillEmptyGlyphs(page);
- return false;
- }
- } else {
- SelectObject(dc, oldFont);
- fillEmptyGlyphs(page);
- return false;
- }
- }
-
- // FIXME: GetGlyphIndices() sets each item of localGlyphBuffer[]
- // with the one of the values listed below.
- // * With the GGI_MARK_NONEXISTING_GLYPHS flag
- // + If the font has a glyph available for the character,
- // localGlyphBuffer[i] > 0x0.
- // + If the font does not have glyphs available for the character,
- // localGlyphBuffer[i] = 0x1F (TrueType Collection?) or
- // 0xFFFF (OpenType?).
- // * Without the GGI_MARK_NONEXISTING_GLYPHS flag
- // + If the font has a glyph available for the character,
- // localGlyphBuffer[i] > 0x0.
- // + If the font does not have glyphs available for the character,
- // localGlyphBuffer[i] = 0x80.
- // (Windows automatically assigns the glyph for a box character to
- // prevent ExtTextOut() from returning errors.)
- // To avoid from hurting the rendering performance, this code just
- // tells WebKit whether or not the all glyph indices for the given
- // characters are 0x80 (i.e. a possibly-invalid glyph) and let it
- // use alternative fonts for the characters.
- // Although this may cause a problem, it seems to work fine as far as I
- // have tested. (Obviously, I need more tests.)
- WORD localGlyphBuffer[GlyphPage::size];
-
- // FIXME: I find some Chinese characters can not be correctly displayed
- // when call GetGlyphIndices without flag GGI_MARK_NONEXISTING_GLYPHS,
- // because the corresponding glyph index is set as 0x20 when current font
- // does not have glyphs available for the character. According a blog post
- // http://blogs.msdn.com/michkap/archive/2006/06/28/649791.aspx
- // I think we should switch to the way about calling GetGlyphIndices with
- // flag GGI_MARK_NONEXISTING_GLYPHS, it should be OK according the
- // description of MSDN.
- // Also according to Jungshik and Hironori's suggestion and modification
- // we treat turetype and raster Font as different way when windows version
- // is less than Vista.
- if (!getGlyphIndices(fontData->platformData().hfont(), dc, buffer, length, localGlyphBuffer, GGI_MARK_NONEXISTING_GLYPHS)) {
- SelectObject(dc, oldFont);
- fillEmptyGlyphs(page);
- return false;
- }
-
- // Copy the output to the GlyphPage
- bool haveGlyphs = false;
- int invalidGlyph = 0xFFFF;
- const DWORD cffTableTag = 0x20464643; // 4-byte identifier for OpenType CFF table ('CFF ').
- if ((windowsVersion() < WindowsVista) && !(tm.tmPitchAndFamily & TMPF_TRUETYPE) && (GetFontData(dc, cffTableTag, 0, 0, 0) == GDI_ERROR))
- invalidGlyph = 0x1F;
-
- Glyph spaceGlyph = 0; // Glyph for a space. Lazily filled.
- bool spaceGlyphInitialized = false;
-
- for (unsigned i = 0; i < length; i++) {
- UChar c = buffer[i];
- Glyph glyph = localGlyphBuffer[i];
- const SimpleFontData* glyphFontData = fontData;
- // When this character should be a space, we ignore whatever the font
- // says and use a space. Otherwise, if fonts don't map one of these
- // space or zero width glyphs, we will get a box.
- if (Font::treatAsSpace(c)) {
- // Hard code the glyph indices for characters that should be
- // treated like spaces.
- if (!spaceGlyphInitialized) {
- // If initSpaceGlyph fails, spaceGlyph stays 0 (= glyph is not present).
- initSpaceGlyph(fontData->platformData().hfont(), dc, &spaceGlyph);
- spaceGlyphInitialized = true;
- }
- glyph = spaceGlyph;
- } else if (glyph == invalidGlyph) {
- // WebKit expects both the glyph index and FontData
- // pointer to be 0 if the glyph is not present
- glyph = 0;
- glyphFontData = 0;
- } else
- haveGlyphs = true;
- page->setGlyphDataForCharacter(offset + i, glyph, glyphFontData);
- }
-
- SelectObject(dc, oldFont);
- return haveGlyphs;
-}
-
-// For non-BMP characters, each is two words (UTF-16) and the input buffer
-// size is 2 * |length|. Since GDI doesn't know how to handle non-BMP
-// characters, we must use Uniscribe to tell us the glyph indices.
-//
-// We don't want to call this in the case of "regular" characters since some
-// fonts may not have the correct combining rules for accents. See the notes
-// at the bottom of ScriptGetCMap. We can't use ScriptGetCMap, though, since
-// it doesn't seem to support UTF-16, despite what this blog post says:
-// http://blogs.msdn.com/michkap/archive/2006/06/29/650680.aspx
-//
-// So we fire up the full Uniscribe doohicky, give it our string, and it will
-// correctly handle the UTF-16 for us. The hard part is taking this and getting
-// the glyph indices back out that correspond to the correct input characters,
-// since they may be missing.
-//
-// Returns true if any glyphs were found.
-static bool fillNonBMPGlyphs(unsigned offset,
- unsigned length,
- UChar* buffer,
- GlyphPage* page,
- const SimpleFontData* fontData)
-{
- bool haveGlyphs = false;
-
- UniscribeHelperTextRun state(buffer, length * 2, false,
- fontData->platformData().hfont(),
- fontData->platformData().scriptCache(),
- fontData->platformData().scriptFontProperties());
- state.setInhibitLigate(true);
- state.setDisableFontFallback(true);
- state.init();
-
- for (unsigned i = 0; i < length; i++) {
- // Each character in this input buffer is a surrogate pair, which
- // consists of two UChars. So, the offset for its i-th character is
- // (i * 2).
- WORD glyph = state.firstGlyphForCharacter(i * 2);
- if (glyph) {
- haveGlyphs = true;
- page->setGlyphDataForIndex(offset + i, glyph, fontData);
- } else
- // Clear both glyph and fontData fields.
- page->setGlyphDataForIndex(offset + i, 0, 0);
- }
- return haveGlyphs;
-}
-
-// We're supposed to return true if there are any glyphs in the range
-// specified by |offset| and |length| in our font,
-// false if there are none.
-bool GlyphPage::fill(unsigned offset, unsigned length, UChar* characterBuffer,
- unsigned bufferLength, const SimpleFontData* fontData)
-{
- // We have to handle BMP and non-BMP characters differently.
- // FIXME: Add assertions to make sure that buffer is entirely in BMP
- // or entirely in non-BMP.
- if (bufferLength == length)
- return fillBMPGlyphs(offset, length, characterBuffer, this, fontData);
-
- if (bufferLength == 2 * length) {
- // A non-BMP input buffer will be twice as long as output glyph buffer
- // because each character in the non-BMP input buffer will be
- // represented by a surrogate pair (two UChar's).
- return fillNonBMPGlyphs(offset, length, characterBuffer, this, fontData);
- }
-
- ASSERT_NOT_REACHED();
- return false;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/ImageDecodingStore.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/ImageDecodingStore.cpp
deleted file mode 100644
index e827e56e70e..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/ImageDecodingStore.cpp
+++ /dev/null
@@ -1,409 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/chromium/ImageDecodingStore.h"
-
-#include "core/platform/chromium/TraceEvent.h"
-#include "core/platform/graphics/chromium/ScaledImageFragment.h"
-
-namespace WebCore {
-
-namespace {
-
-// 32MB memory limit for cache.
-static const size_t defaultCacheLimitInBytes = 32768 * 1024;
-static ImageDecodingStore* s_instance = 0;
-
-static void setInstance(ImageDecodingStore* imageDecodingStore)
-{
- delete s_instance;
- s_instance = imageDecodingStore;
-}
-
-} // namespace
-
-ImageDecodingStore::ImageDecodingStore()
- : m_cacheLimitInBytes(defaultCacheLimitInBytes)
- , m_memoryUsageInBytes(0)
-{
-}
-
-ImageDecodingStore::~ImageDecodingStore()
-{
-#ifndef NDEBUG
- setCacheLimitInBytes(0);
- ASSERT(!m_imageCacheMap.size());
- ASSERT(!m_decoderCacheMap.size());
- ASSERT(!m_orderedCacheList.size());
- ASSERT(!m_imageCacheKeyMap.size());
- ASSERT(!m_decoderCacheKeyMap.size());
-#endif
-}
-
-ImageDecodingStore* ImageDecodingStore::instance()
-{
- return s_instance;
-}
-
-void ImageDecodingStore::initializeOnce()
-{
- setInstance(ImageDecodingStore::create().leakPtr());
-}
-
-void ImageDecodingStore::shutdown()
-{
- setInstance(0);
-}
-
-bool ImageDecodingStore::lockCache(const ImageFrameGenerator* generator, const SkISize& scaledSize, size_t index, const ScaledImageFragment** cachedImage)
-{
- ASSERT(cachedImage);
-
- Vector<OwnPtr<CacheEntry> > cacheEntriesToDelete;
- {
- MutexLocker lock(m_mutex);
- // Public access is restricted to complete images only.
- ImageCacheMap::iterator iter = m_imageCacheMap.find(ImageCacheEntry::makeCacheKey(generator, scaledSize, index, ScaledImageFragment::CompleteImage));
- if (iter == m_imageCacheMap.end())
- return false;
- return lockCacheEntryInternal(iter->value.get(), cachedImage, &cacheEntriesToDelete);
- }
-}
-
-void ImageDecodingStore::unlockCache(const ImageFrameGenerator* generator, const ScaledImageFragment* cachedImage)
-{
- MutexLocker lock(m_mutex);
- cachedImage->bitmap().unlockPixels();
- ImageCacheMap::iterator iter = m_imageCacheMap.find(ImageCacheEntry::makeCacheKey(generator, cachedImage->scaledSize(), cachedImage->index(), cachedImage->generation()));
- ASSERT(iter != m_imageCacheMap.end());
-
- CacheEntry* cacheEntry = iter->value.get();
- cacheEntry->decrementUseCount();
-
- // Put the entry to the end of list.
- m_orderedCacheList.remove(cacheEntry);
- m_orderedCacheList.append(cacheEntry);
-}
-
-const ScaledImageFragment* ImageDecodingStore::insertAndLockCache(const ImageFrameGenerator* generator, PassOwnPtr<ScaledImageFragment> image)
-{
- // Prune old cache entries to give space for the new one.
- prune();
-
- ScaledImageFragment* newImage = image.get();
- OwnPtr<ImageCacheEntry> newCacheEntry = ImageCacheEntry::createAndUse(generator, image);
- Vector<OwnPtr<CacheEntry> > cacheEntriesToDelete;
- {
- MutexLocker lock(m_mutex);
-
- ImageCacheMap::iterator iter = m_imageCacheMap.find(newCacheEntry->cacheKey());
-
- // It is rare but possible that the key of a new cache entry is found.
- // This happens if the generation ID of the image object wraps around.
- // In this case we will try to return the existing cached object and
- // discard the new cache object.
- if (iter != m_imageCacheMap.end()) {
- const ScaledImageFragment* oldImage;
- if (lockCacheEntryInternal(iter->value.get(), &oldImage, &cacheEntriesToDelete)) {
- newCacheEntry->decrementUseCount();
- return oldImage;
- }
- }
-
- // The new image is not locked yet so do it here.
- newImage->bitmap().lockPixels();
- insertCacheInternal(newCacheEntry.release(), &m_imageCacheMap, &m_imageCacheKeyMap);
- }
- return newImage;
-}
-
-bool ImageDecodingStore::lockDecoder(const ImageFrameGenerator* generator, const SkISize& scaledSize, ImageDecoder** decoder)
-{
- ASSERT(decoder);
-
- MutexLocker lock(m_mutex);
- DecoderCacheMap::iterator iter = m_decoderCacheMap.find(DecoderCacheEntry::makeCacheKey(generator, scaledSize));
- if (iter == m_decoderCacheMap.end())
- return false;
-
- DecoderCacheEntry* cacheEntry = iter->value.get();
-
- // There can only be one user of a decoder at a time.
- ASSERT(!cacheEntry->useCount());
- cacheEntry->incrementUseCount();
- *decoder = cacheEntry->cachedDecoder();
- return true;
-}
-
-void ImageDecodingStore::unlockDecoder(const ImageFrameGenerator* generator, const ImageDecoder* decoder)
-{
- MutexLocker lock(m_mutex);
- DecoderCacheMap::iterator iter = m_decoderCacheMap.find(DecoderCacheEntry::makeCacheKey(generator, decoder));
- ASSERT(iter != m_decoderCacheMap.end());
-
- CacheEntry* cacheEntry = iter->value.get();
- cacheEntry->decrementUseCount();
-
- // Put the entry to the end of list.
- m_orderedCacheList.remove(cacheEntry);
- m_orderedCacheList.append(cacheEntry);
-}
-
-void ImageDecodingStore::insertDecoder(const ImageFrameGenerator* generator, PassOwnPtr<ImageDecoder> decoder, bool isDiscardable)
-{
- // Prune old cache entries to give space for the new one.
- prune();
-
- OwnPtr<DecoderCacheEntry> newCacheEntry = DecoderCacheEntry::create(generator, decoder, isDiscardable);
-
- MutexLocker lock(m_mutex);
- ASSERT(!m_decoderCacheMap.contains(newCacheEntry->cacheKey()));
- insertCacheInternal(newCacheEntry.release(), &m_decoderCacheMap, &m_decoderCacheKeyMap);
-}
-
-void ImageDecodingStore::removeDecoder(const ImageFrameGenerator* generator, const ImageDecoder* decoder)
-{
- Vector<OwnPtr<CacheEntry> > cacheEntriesToDelete;
- {
- MutexLocker lock(m_mutex);
- DecoderCacheMap::iterator iter = m_decoderCacheMap.find(DecoderCacheEntry::makeCacheKey(generator, decoder));
- ASSERT(iter != m_decoderCacheMap.end());
-
- CacheEntry* cacheEntry = iter->value.get();
- ASSERT(cacheEntry->useCount());
- cacheEntry->decrementUseCount();
-
- // Delete only one decoder cache entry. Ownership of the cache entry
- // is transfered to cacheEntriesToDelete such that object can be deleted
- // outside of the lock.
- removeFromCacheInternal(cacheEntry, &cacheEntriesToDelete);
-
- // Remove from LRU list.
- removeFromCacheListInternal(cacheEntriesToDelete);
- }
-}
-
-bool ImageDecodingStore::isCached(const ImageFrameGenerator* generator, const SkISize& scaledSize, size_t index)
-{
- MutexLocker lock(m_mutex);
- ImageCacheMap::iterator iter = m_imageCacheMap.find(ImageCacheEntry::makeCacheKey(generator, scaledSize, index, ScaledImageFragment::CompleteImage));
- if (iter == m_imageCacheMap.end())
- return false;
- return true;
-}
-
-void ImageDecodingStore::removeCacheIndexedByGenerator(const ImageFrameGenerator* generator)
-{
- Vector<OwnPtr<CacheEntry> > cacheEntriesToDelete;
- {
- MutexLocker lock(m_mutex);
-
- // Remove image cache objects and decoder cache objects associated
- // with a ImageFrameGenerator.
- removeCacheIndexedByGeneratorInternal(&m_imageCacheMap, &m_imageCacheKeyMap, generator, &cacheEntriesToDelete);
- removeCacheIndexedByGeneratorInternal(&m_decoderCacheMap, &m_decoderCacheKeyMap, generator, &cacheEntriesToDelete);
-
- // Remove from LRU list as well.
- removeFromCacheListInternal(cacheEntriesToDelete);
- }
-}
-
-void ImageDecodingStore::clear()
-{
- size_t cacheLimitInBytes;
- {
- MutexLocker lock(m_mutex);
- cacheLimitInBytes = m_cacheLimitInBytes;
- m_cacheLimitInBytes = 0;
- }
-
- prune();
-
- {
- MutexLocker lock(m_mutex);
- m_cacheLimitInBytes = cacheLimitInBytes;
- }
-}
-
-void ImageDecodingStore::setCacheLimitInBytes(size_t cacheLimit)
-{
- {
- MutexLocker lock(m_mutex);
- m_cacheLimitInBytes = cacheLimit;
- }
- prune();
-}
-
-size_t ImageDecodingStore::memoryUsageInBytes()
-{
- MutexLocker lock(m_mutex);
- return m_memoryUsageInBytes;
-}
-
-unsigned ImageDecodingStore::cacheEntries()
-{
- MutexLocker lock(m_mutex);
- return m_imageCacheMap.size() + m_decoderCacheMap.size();
-}
-
-unsigned ImageDecodingStore::imageCacheEntries()
-{
- MutexLocker lock(m_mutex);
- return m_imageCacheMap.size();
-}
-
-unsigned ImageDecodingStore::decoderCacheEntries()
-{
- MutexLocker lock(m_mutex);
- return m_decoderCacheMap.size();
-}
-
-void ImageDecodingStore::prune()
-{
- TRACE_EVENT0("webkit", "ImageDecodingStore::prune");
-
- Vector<OwnPtr<CacheEntry> > cacheEntriesToDelete;
- {
- MutexLocker lock(m_mutex);
-
- // Head of the list is the least recently used entry.
- const CacheEntry* cacheEntry = m_orderedCacheList.head();
-
- // Walk the list of cache entries starting from the least recently used
- // and then keep them for deletion later.
- while (cacheEntry && (m_memoryUsageInBytes > m_cacheLimitInBytes || !m_cacheLimitInBytes)) {
- // Cache is not used; Remove it.
- if (!cacheEntry->useCount())
- removeFromCacheInternal(cacheEntry, &cacheEntriesToDelete);
- cacheEntry = cacheEntry->next();
- }
-
- // Remove from cache list as well.
- removeFromCacheListInternal(cacheEntriesToDelete);
- }
-}
-
-bool ImageDecodingStore::lockCacheEntryInternal(ImageCacheEntry* cacheEntry, const ScaledImageFragment** cachedImage, Vector<OwnPtr<CacheEntry> >* deletionList)
-{
- ScaledImageFragment* image = cacheEntry->cachedImage();
-
- image->bitmap().lockPixels();
-
- // Memory for this image entry might be discarded already.
- // In this case remove the entry.
- if (!image->bitmap().getPixels()) {
- image->bitmap().unlockPixels();
- removeFromCacheInternal(cacheEntry, &m_imageCacheMap, &m_imageCacheKeyMap, deletionList);
- removeFromCacheListInternal(*deletionList);
- return false;
- }
- cacheEntry->incrementUseCount();
- *cachedImage = image;
- return true;
-}
-
-template<class T, class U, class V>
-void ImageDecodingStore::insertCacheInternal(PassOwnPtr<T> cacheEntry, U* cacheMap, V* identifierMap)
-{
- // Usage of discardable memory is not counted because we want to use more
- // than the cache limit allows. Cache limit only applies to non-discardable
- // objects.
- if (!cacheEntry->isDiscardable())
- incrementMemoryUsage(cacheEntry->memoryUsageInBytes());
-
- // m_orderedCacheList is used to support LRU operations to reorder cache
- // entries quickly.
- m_orderedCacheList.append(cacheEntry.get());
-
- typename U::KeyType key = cacheEntry->cacheKey();
- typename V::AddResult result = identifierMap->add(cacheEntry->generator(), typename V::MappedType());
- result.iterator->value.add(key);
- cacheMap->add(key, cacheEntry);
-
- TRACE_COUNTER1("webkit", "ImageDecodingStoreMemoryUsageBytes", m_memoryUsageInBytes);
- TRACE_COUNTER1("webkit", "ImageDecodingStoreNumOfImages", m_imageCacheMap.size());
- TRACE_COUNTER1("webkit", "ImageDecodingStoreNumOfDecoders", m_decoderCacheMap.size());
-}
-
-template<class T, class U, class V>
-void ImageDecodingStore::removeFromCacheInternal(const T* cacheEntry, U* cacheMap, V* identifierMap, Vector<OwnPtr<CacheEntry> >* deletionList)
-{
- if (!cacheEntry->isDiscardable())
- decrementMemoryUsage(cacheEntry->memoryUsageInBytes());
-
- // Remove entry from identifier map.
- typename V::iterator iter = identifierMap->find(cacheEntry->generator());
- ASSERT(iter != identifierMap->end());
- iter->value.remove(cacheEntry->cacheKey());
- if (!iter->value.size())
- identifierMap->remove(iter);
-
- // Remove entry from cache map.
- deletionList->append(cacheMap->take(cacheEntry->cacheKey()));
-
- TRACE_COUNTER1("webkit", "ImageDecodingStoreMemoryUsageBytes", m_memoryUsageInBytes);
- TRACE_COUNTER1("webkit", "ImageDecodingStoreNumOfImages", m_imageCacheMap.size());
- TRACE_COUNTER1("webkit", "ImageDecodingStoreNumOfDecoders", m_decoderCacheMap.size());
-}
-
-void ImageDecodingStore::removeFromCacheInternal(const CacheEntry* cacheEntry, Vector<OwnPtr<CacheEntry> >* deletionList)
-{
- if (cacheEntry->type() == CacheEntry::TypeImage) {
- removeFromCacheInternal(static_cast<const ImageCacheEntry*>(cacheEntry), &m_imageCacheMap, &m_imageCacheKeyMap, deletionList);
- } else if (cacheEntry->type() == CacheEntry::TypeDecoder) {
- removeFromCacheInternal(static_cast<const DecoderCacheEntry*>(cacheEntry), &m_decoderCacheMap, &m_decoderCacheKeyMap, deletionList);
- } else {
- ASSERT(false);
- }
-}
-
-template<class U, class V>
-void ImageDecodingStore::removeCacheIndexedByGeneratorInternal(U* cacheMap, V* identifierMap, const ImageFrameGenerator* generator, Vector<OwnPtr<CacheEntry> >* deletionList)
-{
- typename V::iterator iter = identifierMap->find(generator);
- if (iter == identifierMap->end())
- return;
-
- // Get all cache identifiers associated with generator.
- Vector<typename U::KeyType> cacheIdentifierList;
- copyToVector(iter->value, cacheIdentifierList);
-
- // For each cache identifier find the corresponding CacheEntry and remove it.
- for (size_t i = 0; i < cacheIdentifierList.size(); ++i) {
- ASSERT(cacheMap->contains(cacheIdentifierList[i]));
- const typename U::MappedType::PtrType cacheEntry = cacheMap->get(cacheIdentifierList[i]);
- ASSERT(!cacheEntry->useCount());
- removeFromCacheInternal(cacheEntry, cacheMap, identifierMap, deletionList);
- }
-}
-
-void ImageDecodingStore::removeFromCacheListInternal(const Vector<OwnPtr<CacheEntry> >& deletionList)
-{
- for (size_t i = 0; i < deletionList.size(); ++i)
- m_orderedCacheList.remove(deletionList[i].get());
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/ImageDecodingStore.h b/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/ImageDecodingStore.h
deleted file mode 100644
index 9e0d25e9a71..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/ImageDecodingStore.h
+++ /dev/null
@@ -1,323 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ImageDecodingStore_h
-#define ImageDecodingStore_h
-
-#include "SkSize.h"
-#include "SkTypes.h"
-#include "core/platform/graphics/chromium/DiscardablePixelRef.h"
-#include "core/platform/graphics/chromium/ScaledImageFragment.h"
-#include "core/platform/graphics/chromium/SkSizeHash.h"
-#include "core/platform/image-decoders/ImageDecoder.h"
-
-#include "wtf/DoublyLinkedList.h"
-#include "wtf/HashSet.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/ThreadingPrimitives.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-class ImageFrameGenerator;
-class SharedBuffer;
-
-// FUNCTION
-//
-// ImageDecodingStore is a class used to manage image cache objects. There are two
-// types of cache objects stored:
-//
-// 1. Image objects
-// Each image object belongs to one frame decoded and/or resampled from an image
-// file. The image object can be complete or partial. Complete means the image
-// is fully decoded and will not mutate in future decoding passes. It can have
-// multiple concurrent users. A partial image object has only one user.
-//
-// 2. Decoder objects
-// A decoder object contains an image decoder. This allows decoding to resume
-// from previous states. There can be one user per one decoder object at any
-// time.
-//
-// EXTERNAL OBJECTS
-//
-// ScaledImageFragment
-// A cached image object. Contains the bitmap and information about the bitmap
-// image.
-//
-// ImageDecoder
-// A decoder object. It is used to decode raw data into bitmap images.
-//
-// ImageFrameGenerator
-// This is a direct user of this cache. Responsible for generating bitmap images
-// using an ImageDecoder. It contains encoded image data and is used to represent
-// one image file. It is used to index image and decoder objects in the cache.
-//
-// LazyDecodingPixelRef
-// A read only user of this cache.
-//
-// THREAD SAFETY
-//
-// All public methods can be used on any thread.
-
-class ImageDecodingStore {
-public:
- static PassOwnPtr<ImageDecodingStore> create() { return adoptPtr(new ImageDecodingStore); }
- ~ImageDecodingStore();
-
- static ImageDecodingStore* instance();
- static void initializeOnce();
- static void shutdown();
-
- // Access a complete cached image object. A complete cached image object is
- // indexed by the origin (ImageFrameGenerator), scaled size and frame index
- // within the image file.
- // Return true if the cache object is found.
- // Return false if the cache object cannot be found or it is incomplete.
- bool lockCache(const ImageFrameGenerator*, const SkISize& scaledSize, size_t index, const ScaledImageFragment**);
- void unlockCache(const ImageFrameGenerator*, const ScaledImageFragment*);
- const ScaledImageFragment* insertAndLockCache(const ImageFrameGenerator*, PassOwnPtr<ScaledImageFragment>);
-
- // Access a cached decoder object. A decoder is indexed by origin (ImageFrameGenerator)
- // and scaled size. Return true if the cached object is found.
- bool lockDecoder(const ImageFrameGenerator*, const SkISize& scaledSize, ImageDecoder**);
- void unlockDecoder(const ImageFrameGenerator*, const ImageDecoder*);
- void insertDecoder(const ImageFrameGenerator*, PassOwnPtr<ImageDecoder>, bool isDiscardable);
- void removeDecoder(const ImageFrameGenerator*, const ImageDecoder*);
-
- // Locks the cache for safety, but does not attempt to lock the object we're checking for.
- bool isCached(const ImageFrameGenerator*, const SkISize& scaledSize, size_t index);
-
- // Remove all cache entries indexed by ImageFrameGenerator.
- void removeCacheIndexedByGenerator(const ImageFrameGenerator*);
-
- void clear();
- void setCacheLimitInBytes(size_t);
- size_t memoryUsageInBytes();
- unsigned cacheEntries();
- unsigned imageCacheEntries();
- unsigned decoderCacheEntries();
-
-private:
- // Image cache entry is identified by:
- // 1. Pointer to ImageFrameGenerator.
- // 2. Size of the image.
- // 3. Frame index.
- // 4. Frame generation. Increments on each progressive decode.
- //
- // The use of generation ID is to allow multiple versions of an image frame
- // be stored in the cache. Each generation comes from a progressive decode.
- //
- // Decoder entries are identified by (1) and (2) only.
- typedef std::pair<const ImageFrameGenerator*, SkISize> DecoderCacheKey;
- typedef std::pair<size_t, size_t> IndexAndGeneration;
- typedef std::pair<DecoderCacheKey, IndexAndGeneration> ImageCacheKey;
-
- // Base class for all cache entries.
- class CacheEntry : public DoublyLinkedListNode<CacheEntry> {
- friend class WTF::DoublyLinkedListNode<CacheEntry>;
- public:
- enum CacheType {
- TypeImage,
- TypeDecoder,
- };
-
- CacheEntry(const ImageFrameGenerator* generator, int useCount, bool isDiscardable)
- : m_generator(generator)
- , m_useCount(useCount)
- , m_isDiscardable(isDiscardable)
- , m_prev(0)
- , m_next(0)
- {
- }
-
- virtual ~CacheEntry()
- {
- ASSERT(!m_useCount);
- }
-
- const ImageFrameGenerator* generator() const { return m_generator; }
- int useCount() const { return m_useCount; }
- void incrementUseCount() { ++m_useCount; }
- void decrementUseCount() { --m_useCount; ASSERT(m_useCount >= 0); }
- bool isDiscardable() const { return m_isDiscardable; }
-
- // FIXME: getSafeSize() returns size in bytes truncated to a 32-bits integer.
- // Find a way to get the size in 64-bits.
- virtual size_t memoryUsageInBytes() const = 0;
- virtual CacheType type() const = 0;
-
- protected:
- const ImageFrameGenerator* m_generator;
- int m_useCount;
- bool m_isDiscardable;
-
- private:
- CacheEntry* m_prev;
- CacheEntry* m_next;
- };
-
- class ImageCacheEntry : public CacheEntry {
- public:
- static PassOwnPtr<ImageCacheEntry> createAndUse(const ImageFrameGenerator* generator, PassOwnPtr<ScaledImageFragment> image)
- {
- return adoptPtr(new ImageCacheEntry(generator, 1, image));
- }
-
- ImageCacheEntry(const ImageFrameGenerator* generator, int count, PassOwnPtr<ScaledImageFragment> image)
- : CacheEntry(generator, count, DiscardablePixelRef::isDiscardable(image->bitmap().pixelRef()))
- , m_cachedImage(image)
- {
- }
-
- // FIXME: getSafeSize() returns size in bytes truncated to a 32-bits integer.
- // Find a way to get the size in 64-bits.
- virtual size_t memoryUsageInBytes() const { return cachedImage()->bitmap().getSafeSize(); }
- virtual CacheType type() const { return TypeImage; }
-
- static ImageCacheKey makeCacheKey(const ImageFrameGenerator* generator, const SkISize& size, size_t index, size_t generation)
- {
- return std::make_pair(std::make_pair(generator, size), std::make_pair(index, generation));
- }
- ImageCacheKey cacheKey() const { return makeCacheKey(m_generator, m_cachedImage->scaledSize(), m_cachedImage->index(), m_cachedImage->generation()); }
- const ScaledImageFragment* cachedImage() const { return m_cachedImage.get(); }
- ScaledImageFragment* cachedImage() { return m_cachedImage.get(); }
-
- private:
- OwnPtr<ScaledImageFragment> m_cachedImage;
- };
-
- class DecoderCacheEntry : public CacheEntry {
- public:
- static PassOwnPtr<DecoderCacheEntry> create(const ImageFrameGenerator* generator, PassOwnPtr<ImageDecoder> decoder, bool isDiscardable)
- {
- return adoptPtr(new DecoderCacheEntry(generator, 0, decoder, isDiscardable));
- }
-
- DecoderCacheEntry(const ImageFrameGenerator* generator, int count, PassOwnPtr<ImageDecoder> decoder, bool isDiscardable)
- : CacheEntry(generator, count, isDiscardable)
- , m_cachedDecoder(decoder)
- , m_size(SkISize::Make(m_cachedDecoder->decodedSize().width(), m_cachedDecoder->decodedSize().height()))
- {
- }
-
- virtual size_t memoryUsageInBytes() const { return m_size.width() * m_size.height() * 4; }
- virtual CacheType type() const { return TypeDecoder; }
-
- static DecoderCacheKey makeCacheKey(const ImageFrameGenerator* generator, const SkISize& size)
- {
- return std::make_pair(generator, size);
- }
- static DecoderCacheKey makeCacheKey(const ImageFrameGenerator* generator, const ImageDecoder* decoder)
- {
- return std::make_pair(generator, SkISize::Make(decoder->decodedSize().width(), decoder->decodedSize().height()));
- }
- DecoderCacheKey cacheKey() const { return makeCacheKey(m_generator, m_size); }
- ImageDecoder* cachedDecoder() const { return m_cachedDecoder.get(); }
-
- private:
- OwnPtr<ImageDecoder> m_cachedDecoder;
- SkISize m_size;
- };
-
- ImageDecodingStore();
-
- void prune();
-
- // These helper methods are called while m_mutex is locked.
-
- // Find and lock a cache entry, and return true on success.
- // Memory of the cache entry can be discarded, in which case it is saved in
- // deletionList.
- bool lockCacheEntryInternal(ImageCacheEntry*, const ScaledImageFragment**, Vector<OwnPtr<CacheEntry> >* deletionList);
-
- template<class T, class U, class V> void insertCacheInternal(PassOwnPtr<T> cacheEntry, U* cacheMap, V* identifierMap);
-
- // Helper method to remove a cache entry. Ownership is transferred to
- // deletionList. Use of Vector<> is handy when removing multiple entries.
- template<class T, class U, class V> void removeFromCacheInternal(const T* cacheEntry, U* cacheMap, V* identifierMap, Vector<OwnPtr<CacheEntry> >* deletionList);
-
- // Helper method to remove a cache entry. Uses the templated version base on
- // the type of cache entry.
- void removeFromCacheInternal(const CacheEntry*, Vector<OwnPtr<CacheEntry> >* deletionList);
-
- // Helper method to remove all cache entries associated with a ImageFraneGenerator.
- // Ownership of cache entries is transferred to deletionList.
- template<class U, class V> void removeCacheIndexedByGeneratorInternal(U* cacheMap, V* identifierMap, const ImageFrameGenerator*, Vector<OwnPtr<CacheEntry> >* deletionList);
-
- // Helper method to remove cache entry pointers from the LRU list.
- void removeFromCacheListInternal(const Vector<OwnPtr<CacheEntry> >& deletionList);
-
- void incrementMemoryUsage(size_t size) { m_memoryUsageInBytes += size; }
- void decrementMemoryUsage(size_t size)
- {
- ASSERT(m_memoryUsageInBytes >= size);
- m_memoryUsageInBytes -= size;
- }
-
- // A doubly linked list that maintains usage history of cache entries.
- // This is used for eviction of old entries.
- // Head of this list is the least recently used cache entry.
- // Tail of this list is the most recently used cache entry.
- DoublyLinkedList<CacheEntry> m_orderedCacheList;
-
- // A lookup table for all image cache objects. Owns all image cache objects.
- typedef HashMap<ImageCacheKey, OwnPtr<ImageCacheEntry> > ImageCacheMap;
- ImageCacheMap m_imageCacheMap;
-
- // A lookup table for all decoder cache objects. Owns all decoder cache objects.
- typedef HashMap<DecoderCacheKey, OwnPtr<DecoderCacheEntry> > DecoderCacheMap;
- DecoderCacheMap m_decoderCacheMap;
-
- // A lookup table to map ImageFrameGenerator to all associated image
- // cache keys.
- typedef HashSet<ImageCacheKey> ImageCacheKeySet;
- typedef HashMap<const ImageFrameGenerator*, ImageCacheKeySet> ImageCacheKeyMap;
- ImageCacheKeyMap m_imageCacheKeyMap;
-
- // A lookup table to map ImageFrameGenerator to all associated
- // decoder cache keys.
- typedef HashSet<DecoderCacheKey> DecoderCacheKeySet;
- typedef HashMap<const ImageFrameGenerator*, DecoderCacheKeySet> DecoderCacheKeyMap;
- DecoderCacheKeyMap m_decoderCacheKeyMap;
-
- size_t m_cacheLimitInBytes;
- size_t m_memoryUsageInBytes;
-
- // Protect concurrent access to these members:
- // m_orderedCacheList
- // m_imageCacheMap, m_decoderCacheMap and all CacheEntrys stored in it
- // m_imageCacheKeyMap
- // m_decoderCacheKeyMap
- // m_cacheLimitInBytes
- // m_memoryUsageInBytes
- // This mutex also protects calls to underlying skBitmap's
- // lockPixels()/unlockPixels() as they are not threadsafe.
- Mutex m_mutex;
-};
-
-} // namespace WebCore
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/ImageDecodingStoreTest.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/ImageDecodingStoreTest.cpp
deleted file mode 100644
index 4a7d7d5bd1c..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/ImageDecodingStoreTest.cpp
+++ /dev/null
@@ -1,460 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/platform/graphics/chromium/ImageDecodingStore.h"
-
-#include "core/platform/SharedBuffer.h"
-#include "core/platform/graphics/chromium/ImageFrameGenerator.h"
-#include "core/platform/graphics/chromium/test/MockDiscardablePixelRef.h"
-#include "core/platform/graphics/chromium/test/MockImageDecoder.h"
-#include <gtest/gtest.h>
-
-using namespace WebCore;
-
-namespace {
-
-class ImageDecodingStoreTest : public ::testing::Test, public MockImageDecoderClient {
-public:
- virtual void SetUp()
- {
- ImageDecodingStore::initializeOnce();
- m_data = SharedBuffer::create();
- m_generator = ImageFrameGenerator::create(SkISize::Make(100, 100), m_data, true);
- m_decodersDestroyed = 0;
- }
-
- virtual void TearDown()
- {
- ImageDecodingStore::shutdown();
- }
-
- virtual void decoderBeingDestroyed()
- {
- ++m_decodersDestroyed;
- }
-
- virtual void frameBufferRequested()
- {
- // Decoder is never used by ImageDecodingStore.
- ASSERT_TRUE(false);
- }
-
- virtual ImageFrame::Status status()
- {
- return ImageFrame::FramePartial;
- }
-
- virtual size_t frameCount() { return 1; }
- virtual int repetitionCount() const { return cAnimationNone; }
- virtual float frameDuration() const { return 0; }
-
-protected:
- PassOwnPtr<ScaledImageFragment> createCompleteImage(const SkISize& size, bool discardable = false, size_t index = 0)
- {
- SkBitmap bitmap;
- bitmap.setConfig(SkBitmap::kARGB_8888_Config, size.width(), size.height());
- if (!discardable)
- bitmap.allocPixels();
- else
- bitmap.setPixelRef(new MockDiscardablePixelRef())->unref();
- return ScaledImageFragment::createComplete(size, index, bitmap);
- }
-
- PassOwnPtr<ScaledImageFragment> createIncompleteImage(const SkISize& size, bool discardable = false, size_t generation = 0)
- {
- SkBitmap bitmap;
- bitmap.setConfig(SkBitmap::kARGB_8888_Config, size.width(), size.height());
- if (!discardable)
- bitmap.allocPixels();
- else
- bitmap.setPixelRef(new MockDiscardablePixelRef())->unref();
- return ScaledImageFragment::createPartial(size, 0, generation, bitmap);
- }
-
- void insertCache(const SkISize& size)
- {
- const ScaledImageFragment* image = ImageDecodingStore::instance()->insertAndLockCache(
- m_generator.get(), createCompleteImage(size));
- unlockCache(image);
- }
-
- const ScaledImageFragment* lockCache(const SkISize& size, size_t index = 0)
- {
- const ScaledImageFragment* cachedImage = 0;
- if (ImageDecodingStore::instance()->lockCache(m_generator.get(), size, index, &cachedImage))
- return cachedImage;
- return 0;
- }
-
- void unlockCache(const ScaledImageFragment* cachedImage)
- {
- ImageDecodingStore::instance()->unlockCache(m_generator.get(), cachedImage);
- }
-
- void evictOneCache()
- {
- size_t memoryUsageInBytes = ImageDecodingStore::instance()->memoryUsageInBytes();
- if (memoryUsageInBytes)
- ImageDecodingStore::instance()->setCacheLimitInBytes(memoryUsageInBytes - 1);
- else
- ImageDecodingStore::instance()->setCacheLimitInBytes(0);
- }
-
- bool isCacheAlive(const SkISize& size)
- {
- const ScaledImageFragment* cachedImage = lockCache(size);
- if (!cachedImage)
- return false;
- ImageDecodingStore::instance()->unlockCache(m_generator.get(), cachedImage);
- return true;
- }
-
- RefPtr<SharedBuffer> m_data;
- RefPtr<ImageFrameGenerator> m_generator;
- int m_decodersDestroyed;
-};
-
-TEST_F(ImageDecodingStoreTest, evictOneCache)
-{
- insertCache(SkISize::Make(1, 1));
- insertCache(SkISize::Make(2, 2));
- insertCache(SkISize::Make(3, 3));
- EXPECT_EQ(3u, ImageDecodingStore::instance()->cacheEntries());
-
- evictOneCache();
- EXPECT_EQ(2u, ImageDecodingStore::instance()->cacheEntries());
-
- evictOneCache();
- EXPECT_EQ(1u, ImageDecodingStore::instance()->cacheEntries());
-}
-
-TEST_F(ImageDecodingStoreTest, pruneOrderIsLeastRecentlyUsed)
-{
- insertCache(SkISize::Make(1, 1));
- insertCache(SkISize::Make(2, 2));
- insertCache(SkISize::Make(3, 3));
- insertCache(SkISize::Make(4, 4));
- insertCache(SkISize::Make(5, 5));
- EXPECT_EQ(5u, ImageDecodingStore::instance()->cacheEntries());
-
- // Use cache in the order 3, 2, 4, 1, 5.
- EXPECT_TRUE(isCacheAlive(SkISize::Make(3, 3)));
- EXPECT_TRUE(isCacheAlive(SkISize::Make(2, 2)));
- EXPECT_TRUE(isCacheAlive(SkISize::Make(4, 4)));
- EXPECT_TRUE(isCacheAlive(SkISize::Make(1, 1)));
- EXPECT_TRUE(isCacheAlive(SkISize::Make(5, 5)));
-
- // Evict 3.
- evictOneCache();
- EXPECT_FALSE(isCacheAlive(SkISize::Make(3, 3)));
- EXPECT_EQ(4u, ImageDecodingStore::instance()->cacheEntries());
-
- // Evict 2.
- evictOneCache();
- EXPECT_FALSE(isCacheAlive(SkISize::Make(2, 2)));
- EXPECT_EQ(3u, ImageDecodingStore::instance()->cacheEntries());
-
- // Evict 4.
- evictOneCache();
- EXPECT_FALSE(isCacheAlive(SkISize::Make(4, 4)));
- EXPECT_EQ(2u, ImageDecodingStore::instance()->cacheEntries());
-
- // Evict 1.
- evictOneCache();
- EXPECT_FALSE(isCacheAlive(SkISize::Make(1, 1)));
- EXPECT_EQ(1u, ImageDecodingStore::instance()->cacheEntries());
-
- // Evict 5.
- evictOneCache();
- EXPECT_FALSE(isCacheAlive(SkISize::Make(5, 5)));
- EXPECT_EQ(0u, ImageDecodingStore::instance()->cacheEntries());
-}
-
-TEST_F(ImageDecodingStoreTest, pruneCausedByInsertion)
-{
- ImageDecodingStore::instance()->setCacheLimitInBytes(100);
-
- // Insert 100 entries.
- // Cache entries stored should increase and eventually decrease to 1.
- insertCache(SkISize::Make(1, 1));
- insertCache(SkISize::Make(2, 2));
- insertCache(SkISize::Make(3, 3));
- EXPECT_EQ(3u, ImageDecodingStore::instance()->cacheEntries());
-
- for (int i = 4; i <= 100; ++i)
- insertCache(SkISize::Make(i, i));
-
- EXPECT_EQ(1u, ImageDecodingStore::instance()->cacheEntries());
- for (int i = 1; i <= 99; ++i)
- EXPECT_FALSE(isCacheAlive(SkISize::Make(i, i)));
- EXPECT_TRUE(isCacheAlive(SkISize::Make(100, 100)));
-}
-
-TEST_F(ImageDecodingStoreTest, cacheInUseNotEvicted)
-{
- insertCache(SkISize::Make(1, 1));
- insertCache(SkISize::Make(2, 2));
- insertCache(SkISize::Make(3, 3));
- EXPECT_EQ(3u, ImageDecodingStore::instance()->cacheEntries());
-
- const ScaledImageFragment* cachedImage = lockCache(SkISize::Make(1, 1));
- ASSERT_TRUE(cachedImage);
-
- // Cache 2 is evicted because cache 1 is in use.
- evictOneCache();
- EXPECT_TRUE(isCacheAlive(SkISize::Make(1, 1)));
- EXPECT_FALSE(isCacheAlive(SkISize::Make(2, 2)));
- EXPECT_TRUE(isCacheAlive(SkISize::Make(3, 3)));
-
- EXPECT_EQ(2u, ImageDecodingStore::instance()->cacheEntries());
- unlockCache(cachedImage);
-}
-
-TEST_F(ImageDecodingStoreTest, destroyImageFrameGenerator)
-{
- insertCache(SkISize::Make(1, 1));
- insertCache(SkISize::Make(2, 2));
- insertCache(SkISize::Make(3, 3));
- OwnPtr<ImageDecoder> decoder = MockImageDecoder::create(this);
- decoder->setSize(1, 1);
- ImageDecodingStore::instance()->insertDecoder(m_generator.get(), decoder.release(), false);
- EXPECT_EQ(4u, ImageDecodingStore::instance()->cacheEntries());
-
- m_generator.clear();
- EXPECT_FALSE(ImageDecodingStore::instance()->cacheEntries());
-}
-
-TEST_F(ImageDecodingStoreTest, insertDecoder)
-{
- const SkISize size = SkISize::Make(1, 1);
- OwnPtr<ImageDecoder> decoder = MockImageDecoder::create(this);
- decoder->setSize(1, 1);
- const ImageDecoder* refDecoder = decoder.get();
- ImageDecodingStore::instance()->insertDecoder(m_generator.get(), decoder.release(), false);
- EXPECT_EQ(1u, ImageDecodingStore::instance()->cacheEntries());
- EXPECT_EQ(4u, ImageDecodingStore::instance()->memoryUsageInBytes());
-
- ImageDecoder* testDecoder;
- EXPECT_TRUE(ImageDecodingStore::instance()->lockDecoder(m_generator.get(), size, &testDecoder));
- EXPECT_TRUE(testDecoder);
- EXPECT_EQ(refDecoder, testDecoder);
- ImageDecodingStore::instance()->unlockDecoder(m_generator.get(), testDecoder);
- EXPECT_EQ(1u, ImageDecodingStore::instance()->cacheEntries());
-}
-
-TEST_F(ImageDecodingStoreTest, evictDecoder)
-{
- OwnPtr<ImageDecoder> decoder1 = MockImageDecoder::create(this);
- OwnPtr<ImageDecoder> decoder2 = MockImageDecoder::create(this);
- OwnPtr<ImageDecoder> decoder3 = MockImageDecoder::create(this);
- decoder1->setSize(1, 1);
- decoder2->setSize(2, 2);
- decoder3->setSize(3, 3);
- ImageDecodingStore::instance()->insertDecoder(m_generator.get(), decoder1.release(), false);
- ImageDecodingStore::instance()->insertDecoder(m_generator.get(), decoder2.release(), false);
- ImageDecodingStore::instance()->insertDecoder(m_generator.get(), decoder3.release(), false);
- EXPECT_EQ(3u, ImageDecodingStore::instance()->cacheEntries());
- EXPECT_EQ(56u, ImageDecodingStore::instance()->memoryUsageInBytes());
-
- evictOneCache();
- EXPECT_EQ(2u, ImageDecodingStore::instance()->cacheEntries());
- EXPECT_EQ(52u, ImageDecodingStore::instance()->memoryUsageInBytes());
-
- evictOneCache();
- EXPECT_EQ(1u, ImageDecodingStore::instance()->cacheEntries());
- EXPECT_EQ(36u, ImageDecodingStore::instance()->memoryUsageInBytes());
-
- evictOneCache();
- EXPECT_FALSE(ImageDecodingStore::instance()->cacheEntries());
- EXPECT_FALSE(ImageDecodingStore::instance()->memoryUsageInBytes());
-}
-
-TEST_F(ImageDecodingStoreTest, decoderInUseNotEvicted)
-{
- OwnPtr<ImageDecoder> decoder1 = MockImageDecoder::create(this);
- OwnPtr<ImageDecoder> decoder2 = MockImageDecoder::create(this);
- OwnPtr<ImageDecoder> decoder3 = MockImageDecoder::create(this);
- decoder1->setSize(1, 1);
- decoder2->setSize(2, 2);
- decoder3->setSize(3, 3);
- ImageDecodingStore::instance()->insertDecoder(m_generator.get(), decoder1.release(), false);
- ImageDecodingStore::instance()->insertDecoder(m_generator.get(), decoder2.release(), false);
- ImageDecodingStore::instance()->insertDecoder(m_generator.get(), decoder3.release(), false);
- EXPECT_EQ(3u, ImageDecodingStore::instance()->cacheEntries());
-
- ImageDecoder* testDecoder;
- EXPECT_TRUE(ImageDecodingStore::instance()->lockDecoder(m_generator.get(), SkISize::Make(2, 2), &testDecoder));
-
- evictOneCache();
- evictOneCache();
- evictOneCache();
- EXPECT_EQ(1u, ImageDecodingStore::instance()->cacheEntries());
- EXPECT_EQ(16u, ImageDecodingStore::instance()->memoryUsageInBytes());
-
- ImageDecodingStore::instance()->unlockDecoder(m_generator.get(), testDecoder);
- evictOneCache();
- EXPECT_FALSE(ImageDecodingStore::instance()->cacheEntries());
- EXPECT_FALSE(ImageDecodingStore::instance()->memoryUsageInBytes());
-}
-
-TEST_F(ImageDecodingStoreTest, removeDecoder)
-{
- const SkISize size = SkISize::Make(1, 1);
- OwnPtr<ImageDecoder> decoder = MockImageDecoder::create(this);
- decoder->setSize(1, 1);
- const ImageDecoder* refDecoder = decoder.get();
- ImageDecodingStore::instance()->insertDecoder(m_generator.get(), decoder.release(), false);
- EXPECT_EQ(1u, ImageDecodingStore::instance()->cacheEntries());
- EXPECT_EQ(4u, ImageDecodingStore::instance()->memoryUsageInBytes());
-
- ImageDecoder* testDecoder;
- EXPECT_TRUE(ImageDecodingStore::instance()->lockDecoder(m_generator.get(), size, &testDecoder));
- EXPECT_TRUE(testDecoder);
- EXPECT_EQ(refDecoder, testDecoder);
- ImageDecodingStore::instance()->removeDecoder(m_generator.get(), testDecoder);
- EXPECT_FALSE(ImageDecodingStore::instance()->cacheEntries());
-
- EXPECT_FALSE(ImageDecodingStore::instance()->lockDecoder(m_generator.get(), size, &testDecoder));
-}
-
-TEST_F(ImageDecodingStoreTest, multipleIndex)
-{
- const SkISize size = SkISize::Make(1, 1);
- const ScaledImageFragment* refImage = ImageDecodingStore::instance()->insertAndLockCache(
- m_generator.get(), createCompleteImage(size, false, 0));
- unlockCache(refImage);
- const ScaledImageFragment* testImage = ImageDecodingStore::instance()->insertAndLockCache(
- m_generator.get(), createCompleteImage(size, false, 1));
- unlockCache(testImage);
- EXPECT_NE(refImage, testImage);
- EXPECT_EQ(2u, ImageDecodingStore::instance()->cacheEntries());
-
- EXPECT_TRUE(ImageDecodingStore::instance()->lockCache(m_generator.get(), size, 1, &refImage));
- EXPECT_EQ(refImage, testImage);
- unlockCache(refImage);
-}
-
-TEST_F(ImageDecodingStoreTest, finalAndPartialImage)
-{
- const SkISize size = SkISize::Make(1, 1);
- const ScaledImageFragment* refImage = ImageDecodingStore::instance()->insertAndLockCache(
- m_generator.get(), createCompleteImage(size, false, 0));
- unlockCache(refImage);
- const ScaledImageFragment* testImage = ImageDecodingStore::instance()->insertAndLockCache(
- m_generator.get(), createIncompleteImage(size, false, 1));
- unlockCache(testImage);
- EXPECT_NE(refImage, testImage);
- EXPECT_EQ(2u, ImageDecodingStore::instance()->cacheEntries());
-
- EXPECT_TRUE(ImageDecodingStore::instance()->lockCache(m_generator.get(), size, 0, &refImage));
- EXPECT_NE(refImage, testImage);
- unlockCache(refImage);
-}
-
-TEST_F(ImageDecodingStoreTest, insertNoGenerationCollision)
-{
- const SkISize size = SkISize::Make(1, 1);
- const ScaledImageFragment* refImage = ImageDecodingStore::instance()->insertAndLockCache(
- m_generator.get(), createIncompleteImage(size, false, 1));
- unlockCache(refImage);
- const ScaledImageFragment* testImage = ImageDecodingStore::instance()->insertAndLockCache(
- m_generator.get(), createIncompleteImage(size, false, 2));
- unlockCache(testImage);
- EXPECT_NE(refImage, testImage);
- EXPECT_EQ(2u, ImageDecodingStore::instance()->cacheEntries());
-}
-
-TEST_F(ImageDecodingStoreTest, insertGenerationCollision)
-{
- const SkISize size = SkISize::Make(1, 1);
- const ScaledImageFragment* refImage = ImageDecodingStore::instance()->insertAndLockCache(
- m_generator.get(), createIncompleteImage(size, false, 1));
- unlockCache(refImage);
- const ScaledImageFragment* testImage = ImageDecodingStore::instance()->insertAndLockCache(
- m_generator.get(), createIncompleteImage(size, false, 1));
- unlockCache(testImage);
- EXPECT_EQ(refImage, testImage);
- EXPECT_EQ(1u, ImageDecodingStore::instance()->cacheEntries());
-}
-
-TEST_F(ImageDecodingStoreTest, insertGenerationCollisionAfterMemoryDiscarded)
-{
- const SkISize size = SkISize::Make(1, 1);
- const ScaledImageFragment* refImage = ImageDecodingStore::instance()->insertAndLockCache(
- m_generator.get(), createIncompleteImage(size, true, 1));
- unlockCache(refImage);
- MockDiscardablePixelRef* pixelRef = static_cast<MockDiscardablePixelRef*>(refImage->bitmap().pixelRef());
- pixelRef->discard();
- const ScaledImageFragment* testImage = ImageDecodingStore::instance()->insertAndLockCache(
- m_generator.get(), createIncompleteImage(size, false, 1));
- unlockCache(testImage);
- EXPECT_NE(refImage, testImage);
- EXPECT_EQ(1u, ImageDecodingStore::instance()->cacheEntries());
-}
-
-TEST_F(ImageDecodingStoreTest, lockCacheFailedAfterMemoryDiscarded)
-{
- const ScaledImageFragment* cachedImage = ImageDecodingStore::instance()->insertAndLockCache(
- m_generator.get(), createCompleteImage(SkISize::Make(1, 1), true));
- unlockCache(cachedImage);
- MockDiscardablePixelRef* pixelRef = static_cast<MockDiscardablePixelRef*>(cachedImage->bitmap().pixelRef());
- pixelRef->discard();
- EXPECT_EQ(0, lockCache(SkISize::Make(1, 1)));
- EXPECT_EQ(0u, ImageDecodingStore::instance()->cacheEntries());
-}
-
-TEST_F(ImageDecodingStoreTest, clear)
-{
- insertCache(SkISize::Make(1, 1));
- insertCache(SkISize::Make(2, 2));
- EXPECT_EQ(2u, ImageDecodingStore::instance()->cacheEntries());
-
- OwnPtr<ImageDecoder> decoder = MockImageDecoder::create(this);
- decoder->setSize(1, 1);
- ImageDecodingStore::instance()->insertDecoder(m_generator.get(), decoder.release(), false);
- EXPECT_EQ(3u, ImageDecodingStore::instance()->cacheEntries());
-
- ImageDecodingStore::instance()->clear();
- EXPECT_EQ(0u, ImageDecodingStore::instance()->cacheEntries());
-}
-
-TEST_F(ImageDecodingStoreTest, clearInUse)
-{
- insertCache(SkISize::Make(1, 1));
- insertCache(SkISize::Make(2, 2));
- EXPECT_EQ(2u, ImageDecodingStore::instance()->cacheEntries());
-
- const ScaledImageFragment* cachedImage = lockCache(SkISize::Make(1, 1));
- ASSERT_TRUE(cachedImage);
- ImageDecodingStore::instance()->clear();
- EXPECT_EQ(1u, ImageDecodingStore::instance()->cacheEntries());
-
- unlockCache(cachedImage);
- EXPECT_EQ(1u, ImageDecodingStore::instance()->cacheEntries());
-}
-
-} // namespace
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/ImageFrameGenerator.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/ImageFrameGenerator.cpp
deleted file mode 100644
index 85b1d9e089f..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/ImageFrameGenerator.cpp
+++ /dev/null
@@ -1,267 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/platform/graphics/chromium/ImageFrameGenerator.h"
-
-#include "core/platform/SharedBuffer.h"
-#include "core/platform/chromium/TraceEvent.h"
-#include "core/platform/graphics/chromium/DiscardablePixelRef.h"
-#include "core/platform/graphics/chromium/ImageDecodingStore.h"
-#include "core/platform/graphics/chromium/ScaledImageFragment.h"
-#include "core/platform/image-decoders/ImageDecoder.h"
-
-#include "skia/ext/image_operations.h"
-
-namespace WebCore {
-
-namespace {
-
-skia::ImageOperations::ResizeMethod resizeMethod()
-{
- return skia::ImageOperations::RESIZE_LANCZOS3;
-}
-
-} // namespace
-
-ImageFrameGenerator::ImageFrameGenerator(const SkISize& fullSize, PassRefPtr<SharedBuffer> data, bool allDataReceived, bool isMultiFrame)
- : m_fullSize(fullSize)
- , m_isMultiFrame(isMultiFrame)
- , m_decodeFailedAndEmpty(false)
- , m_decodeCount(ScaledImageFragment::FirstPartialImage)
- , m_allocator(adoptPtr(new DiscardablePixelRefAllocator()))
-{
- setData(data.get(), allDataReceived);
-}
-
-ImageFrameGenerator::~ImageFrameGenerator()
-{
- // FIXME: This check is not really thread-safe. This should be changed to:
- // ImageDecodingStore::removeCacheFromInstance(this);
- // Which uses a lock internally.
- if (ImageDecodingStore::instance())
- ImageDecodingStore::instance()->removeCacheIndexedByGenerator(this);
-}
-
-void ImageFrameGenerator::setData(PassRefPtr<SharedBuffer> data, bool allDataReceived)
-{
- m_data.setData(data.get(), allDataReceived);
-}
-
-void ImageFrameGenerator::copyData(RefPtr<SharedBuffer>* data, bool* allDataReceived)
-{
- SharedBuffer* buffer = 0;
- m_data.data(&buffer, allDataReceived);
- if (buffer)
- *data = buffer->copy();
-}
-
-const ScaledImageFragment* ImageFrameGenerator::decodeAndScale(const SkISize& scaledSize, size_t index)
-{
- // Prevents concurrent decode or scale operations on the same image data.
- // Multiple LazyDecodingPixelRefs can call this method at the same time.
- MutexLocker lock(m_decodeMutex);
- if (m_decodeFailedAndEmpty)
- return 0;
-
- const ScaledImageFragment* cachedImage = 0;
-
- cachedImage = tryToLockCompleteCache(scaledSize, index);
- if (cachedImage)
- return cachedImage;
-
- TRACE_EVENT2("webkit", "ImageFrameGenerator::decodeAndScale", "generator", this, "decodeCount", static_cast<int>(m_decodeCount));
-
- cachedImage = tryToScale(0, scaledSize, index);
- if (cachedImage)
- return cachedImage;
-
- cachedImage = tryToResumeDecodeAndScale(scaledSize, index);
- if (cachedImage)
- return cachedImage;
- return 0;
-}
-
-const ScaledImageFragment* ImageFrameGenerator::tryToLockCompleteCache(const SkISize& scaledSize, size_t index)
-{
- const ScaledImageFragment* cachedImage = 0;
- if (ImageDecodingStore::instance()->lockCache(this, scaledSize, index, &cachedImage))
- return cachedImage;
- return 0;
-}
-
-const ScaledImageFragment* ImageFrameGenerator::tryToScale(const ScaledImageFragment* fullSizeImage, const SkISize& scaledSize, size_t index)
-{
- TRACE_EVENT0("webkit", "ImageFrameGenerator::tryToScale");
-
- // If the requested scaled size is the same as the full size then exit
- // early. This saves a cache lookup.
- if (scaledSize == m_fullSize)
- return 0;
-
- if (!fullSizeImage && !ImageDecodingStore::instance()->lockCache(this, m_fullSize, index, &fullSizeImage))
- return 0;
-
- // This call allocates the DiscardablePixelRef and lock/unlocks it
- // afterwards. So the memory allocated to the scaledBitmap can be
- // discarded after this call. Need to lock the scaledBitmap and
- // check the pixels before using it next time.
- SkBitmap scaledBitmap = skia::ImageOperations::Resize(fullSizeImage->bitmap(), resizeMethod(), scaledSize.width(), scaledSize.height(), m_allocator.get());
-
- OwnPtr<ScaledImageFragment> scaledImage;
- if (fullSizeImage->isComplete())
- scaledImage = ScaledImageFragment::createComplete(scaledSize, fullSizeImage->index(), scaledBitmap);
- else
- scaledImage = ScaledImageFragment::createPartial(scaledSize, fullSizeImage->index(), nextGenerationId(), scaledBitmap);
- ImageDecodingStore::instance()->unlockCache(this, fullSizeImage);
- return ImageDecodingStore::instance()->insertAndLockCache(this, scaledImage.release());
-}
-
-const ScaledImageFragment* ImageFrameGenerator::tryToResumeDecodeAndScale(const SkISize& scaledSize, size_t index)
-{
- TRACE_EVENT1("webkit", "ImageFrameGenerator::tryToResumeDecodeAndScale", "index", static_cast<int>(index));
-
- ImageDecoder* decoder = 0;
- const bool resumeDecoding = ImageDecodingStore::instance()->lockDecoder(this, m_fullSize, &decoder);
- ASSERT(!resumeDecoding || decoder);
-
- OwnPtr<ScaledImageFragment> fullSizeImage = decode(index, &decoder);
-
- if (!decoder)
- return 0;
-
- // If we are not resuming decoding that means the decoder is freshly
- // created and we have ownership. If we are resuming decoding then
- // the decoder is owned by ImageDecodingStore.
- OwnPtr<ImageDecoder> decoderContainer;
- if (!resumeDecoding)
- decoderContainer = adoptPtr(decoder);
-
- if (!fullSizeImage) {
- // If decode has failed and resulted an empty image we can save work
- // in the future by returning early.
- m_decodeFailedAndEmpty = !m_isMultiFrame && decoder->failed();
-
- if (resumeDecoding)
- ImageDecodingStore::instance()->unlockDecoder(this, decoder);
- return 0;
- }
-
- const ScaledImageFragment* cachedImage = ImageDecodingStore::instance()->insertAndLockCache(this, fullSizeImage.release());
-
- // If the image generated is complete then there is no need to keep
- // the decoder. The exception is multi-frame decoder which can generate
- // multiple complete frames.
- const bool removeDecoder = cachedImage->isComplete() && !m_isMultiFrame;
-
- if (resumeDecoding) {
- if (removeDecoder)
- ImageDecodingStore::instance()->removeDecoder(this, decoder);
- else
- ImageDecodingStore::instance()->unlockDecoder(this, decoder);
- } else if (!removeDecoder) {
- ImageDecodingStore::instance()->insertDecoder(this, decoderContainer.release(), DiscardablePixelRef::isDiscardable(cachedImage->bitmap().pixelRef()));
- }
-
- if (m_fullSize == scaledSize)
- return cachedImage;
- return tryToScale(cachedImage, scaledSize, index);
-}
-
-PassOwnPtr<ScaledImageFragment> ImageFrameGenerator::decode(size_t index, ImageDecoder** decoder)
-{
- TRACE_EVENT2("webkit", "ImageFrameGenerator::decode", "width", m_fullSize.width(), "height", m_fullSize.height());
-
- ASSERT(decoder);
- SharedBuffer* data = 0;
- bool allDataReceived = false;
- m_data.data(&data, &allDataReceived);
-
- // Try to create an ImageDecoder if we are not given one.
- if (!*decoder) {
- if (m_imageDecoderFactory)
- *decoder = m_imageDecoderFactory->create().leakPtr();
-
- if (!*decoder)
- *decoder = ImageDecoder::create(*data, ImageSource::AlphaPremultiplied, ImageSource::GammaAndColorProfileApplied).leakPtr();
-
- if (!*decoder)
- return nullptr;
- }
-
- // TODO: this is very ugly. We need to refactor the way how we can pass a
- // memory allocator to image decoders.
- if (!m_isMultiFrame)
- (*decoder)->setMemoryAllocator(m_allocator.get());
- (*decoder)->setData(data, allDataReceived);
- // If this call returns a newly allocated DiscardablePixelRef, then
- // ImageFrame::m_bitmap and the contained DiscardablePixelRef are locked.
- // They will be unlocked when ImageDecoder is destroyed since ImageDecoder
- // owns the ImageFrame. Partially decoded SkBitmap is thus inserted into the
- // ImageDecodingStore while locked.
- ImageFrame* frame = (*decoder)->frameBufferAtIndex(index);
- (*decoder)->setData(0, false); // Unref SharedBuffer from ImageDecoder.
- (*decoder)->clearCacheExceptFrame(index);
-
- if (!frame || frame->status() == ImageFrame::FrameEmpty)
- return nullptr;
-
- const bool isComplete = frame->status() == ImageFrame::FrameComplete;
- SkBitmap fullSizeBitmap = frame->getSkBitmap();
- if (fullSizeBitmap.isNull())
- return nullptr;
-
- {
- MutexLocker lock(m_alphaMutex);
- if (index >= m_hasAlpha.size()) {
- const size_t oldSize = m_hasAlpha.size();
- m_hasAlpha.resize(index + 1);
- for (size_t i = oldSize; i < m_hasAlpha.size(); ++i)
- m_hasAlpha[i] = true;
- }
- m_hasAlpha[index] = !fullSizeBitmap.isOpaque();
- }
- ASSERT(fullSizeBitmap.width() == m_fullSize.width() && fullSizeBitmap.height() == m_fullSize.height());
-
- if (isComplete)
- return ScaledImageFragment::createComplete(m_fullSize, index, fullSizeBitmap);
-
- // If the image is partial we need to return a copy. This is to avoid future
- // decode operations writing to the same bitmap.
- SkBitmap copyBitmap;
- return fullSizeBitmap.copyTo(&copyBitmap, fullSizeBitmap.config(), m_allocator.get()) ?
- ScaledImageFragment::createPartial(m_fullSize, index, nextGenerationId(), copyBitmap) : nullptr;
-}
-
-bool ImageFrameGenerator::hasAlpha(size_t index)
-{
- MutexLocker lock(m_alphaMutex);
- if (index < m_hasAlpha.size())
- return m_hasAlpha[index];
- return true;
-}
-
-} // namespace
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/ImageFrameGenerator.h b/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/ImageFrameGenerator.h
deleted file mode 100644
index 8b53ef76eb4..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/ImageFrameGenerator.h
+++ /dev/null
@@ -1,118 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ImageFrameGenerator_h
-#define ImageFrameGenerator_h
-
-#include "SkBitmap.h"
-#include "SkSize.h"
-#include "SkTypes.h"
-#include "core/platform/graphics/chromium/ThreadSafeDataTransport.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/RefPtr.h"
-#include "wtf/ThreadingPrimitives.h"
-#include "wtf/ThreadSafeRefCounted.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-class ImageDecoder;
-class ScaledImageFragment;
-class SharedBuffer;
-
-class ImageDecoderFactory {
-public:
- virtual ~ImageDecoderFactory() { }
- virtual PassOwnPtr<ImageDecoder> create() = 0;
-};
-
-class ImageFrameGenerator : public ThreadSafeRefCounted<ImageFrameGenerator> {
-public:
- static PassRefPtr<ImageFrameGenerator> create(const SkISize& fullSize, PassRefPtr<SharedBuffer> data, bool allDataReceived, bool isMultiFrame = false)
- {
- return adoptRef(new ImageFrameGenerator(fullSize, data, allDataReceived, isMultiFrame));
- }
-
- ImageFrameGenerator(const SkISize& fullSize, PassRefPtr<SharedBuffer>, bool allDataReceived, bool isMultiFrame);
- ~ImageFrameGenerator();
-
- const ScaledImageFragment* decodeAndScale(const SkISize& scaledSize, size_t index = 0);
-
- void setData(PassRefPtr<SharedBuffer>, bool allDataReceived);
-
- // Creates a new SharedBuffer containing the data received so far.
- void copyData(RefPtr<SharedBuffer>*, bool* allDataReceived);
-
- SkISize getFullSize() const { return m_fullSize; }
-
- bool isMultiFrame() const { return m_isMultiFrame; }
-
- // FIXME: Return alpha state for each frame.
- bool hasAlpha(size_t);
-
-private:
- friend class ImageFrameGeneratorTest;
- friend class DeferredImageDecoderTest;
- // For testing. |factory| will overwrite the default ImageDecoder creation logic if |factory->create()| returns non-zero.
- void setImageDecoderFactory(PassOwnPtr<ImageDecoderFactory> factory) { m_imageDecoderFactory = factory; }
- // For testing.
- SkBitmap::Allocator* allocator() const { return m_allocator.get(); }
- void setAllocator(PassOwnPtr<SkBitmap::Allocator> allocator) { m_allocator = allocator; }
-
- // These methods are called while m_decodeMutex is locked.
- const ScaledImageFragment* tryToLockCompleteCache(const SkISize& scaledSize, size_t index);
- const ScaledImageFragment* tryToScale(const ScaledImageFragment* fullSizeImage, const SkISize& scaledSize, size_t index);
- const ScaledImageFragment* tryToResumeDecodeAndScale(const SkISize& scaledSize, size_t index);
-
- // Use the given decoder to decode. If a decoder is not given then try to create one.
- PassOwnPtr<ScaledImageFragment> decode(size_t index, ImageDecoder**);
-
- // Return the next generation ID of a new image object. This is used
- // to identify images of the same frame from different stages of
- // progressive decode.
- size_t nextGenerationId() { return m_decodeCount++; }
-
- SkISize m_fullSize;
- ThreadSafeDataTransport m_data;
- bool m_isMultiFrame;
- bool m_decodeFailedAndEmpty;
- Vector<bool> m_hasAlpha;
- size_t m_decodeCount;
- OwnPtr<SkBitmap::Allocator> m_allocator;
-
- OwnPtr<ImageDecoderFactory> m_imageDecoderFactory;
-
- // Prevents multiple decode operations on the same data.
- Mutex m_decodeMutex;
-
- // Protect concurrent access to m_hasAlpha.
- Mutex m_alphaMutex;
-};
-
-} // namespace WebCore
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/ImageFrameGeneratorTest.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/ImageFrameGeneratorTest.cpp
deleted file mode 100644
index 16278ce135e..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/ImageFrameGeneratorTest.cpp
+++ /dev/null
@@ -1,467 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/chromium/ImageFrameGenerator.h"
-
-#include "core/platform/SharedBuffer.h"
-#include "core/platform/graphics/chromium/ImageDecodingStore.h"
-#include "core/platform/graphics/chromium/test/MockImageDecoder.h"
-#include "wtf/Threading.h"
-#include <gtest/gtest.h>
-
-namespace WebCore {
-
-namespace {
-
-// Helper methods to generate standard sizes.
-SkISize fullSize() { return SkISize::Make(100, 100); }
-SkISize scaledSize() { return SkISize::Make(50, 50); }
-
-} // namespace
-
-class ImageFrameGeneratorTest : public ::testing::Test, public MockImageDecoderClient {
-public:
- virtual void SetUp() OVERRIDE
- {
- ImageDecodingStore::initializeOnce();
- m_data = SharedBuffer::create();
- m_generator = ImageFrameGenerator::create(fullSize(), m_data, true);
- useMockImageDecoderFactory();
- m_decodersDestroyed = 0;
- m_frameBufferRequestCount = 0;
- m_status = ImageFrame::FrameEmpty;
- }
-
- virtual void TearDown() OVERRIDE
- {
- ImageDecodingStore::shutdown();
- }
-
- virtual void decoderBeingDestroyed() OVERRIDE
- {
- ++m_decodersDestroyed;
- }
-
- virtual void frameBufferRequested() OVERRIDE
- {
- ++m_frameBufferRequestCount;
- }
-
- virtual ImageFrame::Status status() OVERRIDE
- {
- ImageFrame::Status currentStatus = m_status;
- m_status = m_nextFrameStatus;
- return currentStatus;
- }
-
- virtual size_t frameCount() OVERRIDE { return 1; }
- virtual int repetitionCount() const OVERRIDE { return cAnimationNone; }
- virtual float frameDuration() const OVERRIDE { return 0; }
-
-protected:
- void useMockImageDecoderFactory()
- {
- m_generator->setImageDecoderFactory(MockImageDecoderFactory::create(this, fullSize()));
- }
-
- PassOwnPtr<ScaledImageFragment> createCompleteImage(const SkISize& size)
- {
- SkBitmap bitmap;
- bitmap.setConfig(SkBitmap::kARGB_8888_Config, size.width(), size.height());
- bitmap.allocPixels();
- return ScaledImageFragment::createComplete(size, 0, bitmap);
- }
-
- void addNewData()
- {
- m_data->append("g", 1);
- m_generator->setData(m_data, false);
- }
-
- void setFrameStatus(ImageFrame::Status status) { m_status = m_nextFrameStatus = status; }
- void setNextFrameStatus(ImageFrame::Status status) { m_nextFrameStatus = status; }
-
- SkBitmap::Allocator* allocator() const { return m_generator->allocator(); }
- void setAllocator(PassOwnPtr<SkBitmap::Allocator> allocator)
- {
- m_generator->setAllocator(allocator);
- }
-
- PassOwnPtr<ScaledImageFragment> decode(size_t index)
- {
- ImageDecoder* decoder = 0;
- return m_generator->decode(index, &decoder);
- }
-
- RefPtr<SharedBuffer> m_data;
- RefPtr<ImageFrameGenerator> m_generator;
- int m_decodersDestroyed;
- int m_frameBufferRequestCount;
- ImageFrame::Status m_status;
- ImageFrame::Status m_nextFrameStatus;
-};
-
-TEST_F(ImageFrameGeneratorTest, cacheHit)
-{
- const ScaledImageFragment* fullImage = ImageDecodingStore::instance()->insertAndLockCache(
- m_generator.get(), createCompleteImage(fullSize()));
- EXPECT_EQ(fullSize(), fullImage->scaledSize());
- ImageDecodingStore::instance()->unlockCache(m_generator.get(), fullImage);
-
- const ScaledImageFragment* tempImage = m_generator->decodeAndScale(fullSize());
- EXPECT_EQ(fullImage, tempImage);
- EXPECT_EQ(fullSize(), tempImage->scaledSize());
- EXPECT_TRUE(m_generator->hasAlpha(0));
- ImageDecodingStore::instance()->unlockCache(m_generator.get(), tempImage);
- EXPECT_EQ(0, m_frameBufferRequestCount);
-}
-
-TEST_F(ImageFrameGeneratorTest, cacheMissWithScale)
-{
- const ScaledImageFragment* fullImage = ImageDecodingStore::instance()->insertAndLockCache(
- m_generator.get(), createCompleteImage(fullSize()));
- EXPECT_EQ(fullSize(), fullImage->scaledSize());
- ImageDecodingStore::instance()->unlockCache(m_generator.get(), fullImage);
-
- // Cache miss because of scaled size not found.
- const ScaledImageFragment* scaledImage = m_generator->decodeAndScale(scaledSize());
- EXPECT_NE(fullImage, scaledImage);
- EXPECT_EQ(scaledSize(), scaledImage->scaledSize());
- EXPECT_TRUE(m_generator->hasAlpha(0));
- ImageDecodingStore::instance()->unlockCache(m_generator.get(), scaledImage);
-
- // Cache hit.
- const ScaledImageFragment* tempImage = m_generator->decodeAndScale(scaledSize());
- EXPECT_EQ(scaledImage, tempImage);
- EXPECT_EQ(scaledSize(), tempImage->scaledSize());
- EXPECT_TRUE(m_generator->hasAlpha(0));
- ImageDecodingStore::instance()->unlockCache(m_generator.get(), tempImage);
- EXPECT_EQ(0, m_frameBufferRequestCount);
-}
-
-TEST_F(ImageFrameGeneratorTest, cacheMissWithDecodeAndScale)
-{
- setFrameStatus(ImageFrame::FrameComplete);
-
- // Cache miss.
- const ScaledImageFragment* scaledImage = m_generator->decodeAndScale(scaledSize());
- EXPECT_EQ(1, m_frameBufferRequestCount);
- EXPECT_EQ(scaledSize(), scaledImage->scaledSize());
- EXPECT_FALSE(m_generator->hasAlpha(0));
- ImageDecodingStore::instance()->unlockCache(m_generator.get(), scaledImage);
- EXPECT_EQ(1, m_decodersDestroyed);
-
- // Cache hit.
- const ScaledImageFragment* fullImage = m_generator->decodeAndScale(fullSize());
- EXPECT_NE(scaledImage, fullImage);
- EXPECT_EQ(fullSize(), fullImage->scaledSize());
- EXPECT_FALSE(m_generator->hasAlpha(0));
- ImageDecodingStore::instance()->unlockCache(m_generator.get(), fullImage);
-
- // Cache hit.
- const ScaledImageFragment* tempImage = m_generator->decodeAndScale(scaledSize());
- EXPECT_EQ(scaledImage, tempImage);
- EXPECT_EQ(scaledSize(), tempImage->scaledSize());
- EXPECT_FALSE(m_generator->hasAlpha(0));
- ImageDecodingStore::instance()->unlockCache(m_generator.get(), tempImage);
- EXPECT_EQ(1, m_frameBufferRequestCount);
-}
-
-TEST_F(ImageFrameGeneratorTest, cacheMissWithIncompleteDecode)
-{
- setFrameStatus(ImageFrame::FramePartial);
-
- const ScaledImageFragment* tempImage= m_generator->decodeAndScale(fullSize());
- EXPECT_FALSE(tempImage->isComplete());
- EXPECT_EQ(1, m_frameBufferRequestCount);
- ImageDecodingStore::instance()->unlockCache(m_generator.get(), tempImage);
- EXPECT_EQ(2u, ImageDecodingStore::instance()->cacheEntries());
- EXPECT_EQ(1u, ImageDecodingStore::instance()->imageCacheEntries());
- EXPECT_EQ(1u, ImageDecodingStore::instance()->decoderCacheEntries());
-
- addNewData();
- tempImage = m_generator->decodeAndScale(fullSize());
- EXPECT_FALSE(tempImage->isComplete());
- EXPECT_EQ(2, m_frameBufferRequestCount);
- ImageDecodingStore::instance()->unlockCache(m_generator.get(), tempImage);
- EXPECT_EQ(3u, ImageDecodingStore::instance()->cacheEntries());
- EXPECT_EQ(2u, ImageDecodingStore::instance()->imageCacheEntries());
- EXPECT_EQ(1u, ImageDecodingStore::instance()->decoderCacheEntries());
- EXPECT_EQ(0, m_decodersDestroyed);
-}
-
-TEST_F(ImageFrameGeneratorTest, cacheMissWithIncompleteDecodeAndScale)
-{
- setFrameStatus(ImageFrame::FramePartial);
-
- const ScaledImageFragment* tempImage= m_generator->decodeAndScale(scaledSize());
- EXPECT_FALSE(tempImage->isComplete());
- EXPECT_EQ(1, m_frameBufferRequestCount);
- ImageDecodingStore::instance()->unlockCache(m_generator.get(), tempImage);
- EXPECT_EQ(3u, ImageDecodingStore::instance()->cacheEntries());
- EXPECT_EQ(2u, ImageDecodingStore::instance()->imageCacheEntries());
- EXPECT_EQ(1u, ImageDecodingStore::instance()->decoderCacheEntries());
-
- addNewData();
- tempImage = m_generator->decodeAndScale(scaledSize());
- EXPECT_FALSE(tempImage->isComplete());
- EXPECT_EQ(2, m_frameBufferRequestCount);
- ImageDecodingStore::instance()->unlockCache(m_generator.get(), tempImage);
- EXPECT_EQ(5u, ImageDecodingStore::instance()->cacheEntries());
- EXPECT_EQ(4u, ImageDecodingStore::instance()->imageCacheEntries());
- EXPECT_EQ(1u, ImageDecodingStore::instance()->decoderCacheEntries());
- EXPECT_EQ(0, m_decodersDestroyed);
-}
-
-TEST_F(ImageFrameGeneratorTest, incompleteDecodeBecomesComplete)
-{
- setFrameStatus(ImageFrame::FramePartial);
-
- const ScaledImageFragment* tempImage = m_generator->decodeAndScale(fullSize());
- EXPECT_FALSE(tempImage->isComplete());
- EXPECT_EQ(1, m_frameBufferRequestCount);
- EXPECT_EQ(0, m_decodersDestroyed);
- ImageDecodingStore::instance()->unlockCache(m_generator.get(), tempImage);
- EXPECT_EQ(2u, ImageDecodingStore::instance()->cacheEntries());
- EXPECT_EQ(1u, ImageDecodingStore::instance()->imageCacheEntries());
- EXPECT_EQ(1u, ImageDecodingStore::instance()->decoderCacheEntries());
-
- setFrameStatus(ImageFrame::FrameComplete);
- addNewData();
-
- tempImage = m_generator->decodeAndScale(fullSize());
- EXPECT_TRUE(tempImage->isComplete());
- EXPECT_EQ(2, m_frameBufferRequestCount);
- EXPECT_EQ(1, m_decodersDestroyed);
- ImageDecodingStore::instance()->unlockCache(m_generator.get(), tempImage);
- EXPECT_EQ(2u, ImageDecodingStore::instance()->cacheEntries());
- EXPECT_EQ(2u, ImageDecodingStore::instance()->imageCacheEntries());
- EXPECT_EQ(0u, ImageDecodingStore::instance()->decoderCacheEntries());
-
- tempImage = m_generator->decodeAndScale(fullSize());
- EXPECT_TRUE(tempImage->isComplete());
- EXPECT_EQ(2, m_frameBufferRequestCount);
- ImageDecodingStore::instance()->unlockCache(m_generator.get(), tempImage);
-}
-
-TEST_F(ImageFrameGeneratorTest, incompleteDecodeAndScaleBecomesComplete)
-{
- setFrameStatus(ImageFrame::FramePartial);
-
- const ScaledImageFragment* tempImage = m_generator->decodeAndScale(scaledSize());
- EXPECT_FALSE(tempImage->isComplete());
- EXPECT_EQ(1, m_frameBufferRequestCount);
- EXPECT_EQ(0, m_decodersDestroyed);
- ImageDecodingStore::instance()->unlockCache(m_generator.get(), tempImage);
- EXPECT_EQ(3u, ImageDecodingStore::instance()->cacheEntries());
- EXPECT_EQ(2u, ImageDecodingStore::instance()->imageCacheEntries());
- EXPECT_EQ(1u, ImageDecodingStore::instance()->decoderCacheEntries());
-
- setFrameStatus(ImageFrame::FrameComplete);
- addNewData();
-
- tempImage = m_generator->decodeAndScale(scaledSize());
- EXPECT_TRUE(tempImage->isComplete());
- EXPECT_EQ(2, m_frameBufferRequestCount);
- EXPECT_EQ(1, m_decodersDestroyed);
- ImageDecodingStore::instance()->unlockCache(m_generator.get(), tempImage);
- EXPECT_EQ(4u, ImageDecodingStore::instance()->cacheEntries());
- EXPECT_EQ(4u, ImageDecodingStore::instance()->imageCacheEntries());
- EXPECT_EQ(0u, ImageDecodingStore::instance()->decoderCacheEntries());
-
- tempImage = m_generator->decodeAndScale(scaledSize());
- EXPECT_TRUE(tempImage->isComplete());
- ImageDecodingStore::instance()->unlockCache(m_generator.get(), tempImage);
-
- tempImage = m_generator->decodeAndScale(fullSize());
- EXPECT_TRUE(tempImage->isComplete());
- ImageDecodingStore::instance()->unlockCache(m_generator.get(), tempImage);
-
- EXPECT_EQ(2, m_frameBufferRequestCount);
-}
-
-static void decodeThreadMain(void* arg)
-{
- ImageFrameGenerator* generator = reinterpret_cast<ImageFrameGenerator*>(arg);
- const ScaledImageFragment* tempImage = generator->decodeAndScale(fullSize());
- ImageDecodingStore::instance()->unlockCache(generator, tempImage);
-}
-
-TEST_F(ImageFrameGeneratorTest, incompleteDecodeBecomesCompleteMultiThreaded)
-{
- setFrameStatus(ImageFrame::FramePartial);
-
- const ScaledImageFragment* tempImage = m_generator->decodeAndScale(fullSize());
- EXPECT_FALSE(tempImage->isComplete());
- EXPECT_EQ(1, m_frameBufferRequestCount);
- EXPECT_EQ(0, m_decodersDestroyed);
- ImageDecodingStore::instance()->unlockCache(m_generator.get(), tempImage);
- EXPECT_EQ(2u, ImageDecodingStore::instance()->cacheEntries());
- EXPECT_EQ(1u, ImageDecodingStore::instance()->imageCacheEntries());
- EXPECT_EQ(1u, ImageDecodingStore::instance()->decoderCacheEntries());
-
- // Frame can now be decoded completely.
- setFrameStatus(ImageFrame::FrameComplete);
- addNewData();
- ThreadIdentifier threadID = createThread(&decodeThreadMain, m_generator.get(), "DecodeThread");
- waitForThreadCompletion(threadID);
-
- EXPECT_EQ(2, m_frameBufferRequestCount);
- EXPECT_EQ(1, m_decodersDestroyed);
- EXPECT_EQ(2u, ImageDecodingStore::instance()->cacheEntries());
- EXPECT_EQ(2u, ImageDecodingStore::instance()->imageCacheEntries());
- EXPECT_EQ(0u, ImageDecodingStore::instance()->decoderCacheEntries());
-
- tempImage = m_generator->decodeAndScale(fullSize());
- EXPECT_TRUE(tempImage->isComplete());
- EXPECT_EQ(2, m_frameBufferRequestCount);
- ImageDecodingStore::instance()->unlockCache(m_generator.get(), tempImage);
-}
-
-TEST_F(ImageFrameGeneratorTest, concurrentIncompleteDecodeAndScale)
-{
- setFrameStatus(ImageFrame::FramePartial);
-
- const ScaledImageFragment* fullImage = m_generator->decodeAndScale(fullSize());
- const ScaledImageFragment* scaledImage = m_generator->decodeAndScale(scaledSize());
- EXPECT_FALSE(fullImage->isComplete());
- EXPECT_FALSE(scaledImage->isComplete());
- EXPECT_EQ(2, m_frameBufferRequestCount);
- ImageDecodingStore::instance()->unlockCache(m_generator.get(), fullImage);
- ImageDecodingStore::instance()->unlockCache(m_generator.get(), scaledImage);
- EXPECT_EQ(4u, ImageDecodingStore::instance()->cacheEntries());
- EXPECT_EQ(3u, ImageDecodingStore::instance()->imageCacheEntries());
- EXPECT_EQ(1u, ImageDecodingStore::instance()->decoderCacheEntries());
- EXPECT_EQ(0, m_decodersDestroyed);
-
- addNewData();
- setFrameStatus(ImageFrame::FrameComplete);
- scaledImage = m_generator->decodeAndScale(scaledSize());
- EXPECT_TRUE(scaledImage->isComplete());
- EXPECT_EQ(3, m_frameBufferRequestCount);
- ImageDecodingStore::instance()->unlockCache(m_generator.get(), scaledImage);
- EXPECT_EQ(5u, ImageDecodingStore::instance()->cacheEntries());
- EXPECT_EQ(5u, ImageDecodingStore::instance()->imageCacheEntries());
- EXPECT_EQ(0u, ImageDecodingStore::instance()->decoderCacheEntries());
- EXPECT_EQ(1, m_decodersDestroyed);
-}
-
-TEST_F(ImageFrameGeneratorTest, incompleteBitmapCopied)
-{
- setFrameStatus(ImageFrame::FramePartial);
-
- const ScaledImageFragment* tempImage= m_generator->decodeAndScale(fullSize());
- EXPECT_FALSE(tempImage->isComplete());
- EXPECT_EQ(1, m_frameBufferRequestCount);
-
- ImageDecoder* tempDecoder = 0;
- EXPECT_TRUE(ImageDecodingStore::instance()->lockDecoder(m_generator.get(), fullSize(), &tempDecoder));
- ASSERT_TRUE(tempDecoder);
- EXPECT_NE(tempDecoder->frameBufferAtIndex(0)->getSkBitmap().getPixels(), tempImage->bitmap().getPixels());
- ImageDecodingStore::instance()->unlockCache(m_generator.get(), tempImage);
- ImageDecodingStore::instance()->unlockDecoder(m_generator.get(), tempDecoder);
-}
-
-TEST_F(ImageFrameGeneratorTest, resumeDecodeEmptyFrameTurnsComplete)
-{
- m_generator = ImageFrameGenerator::create(fullSize(), m_data, false, true);
- useMockImageDecoderFactory();
- setFrameStatus(ImageFrame::FrameComplete);
-
- const ScaledImageFragment* tempImage = m_generator->decodeAndScale(fullSize(), 0);
- EXPECT_TRUE(tempImage->isComplete());
- ImageDecodingStore::instance()->unlockCache(m_generator.get(), tempImage);
-
- setFrameStatus(ImageFrame::FrameEmpty);
- setNextFrameStatus(ImageFrame::FrameComplete);
- EXPECT_FALSE(m_generator->decodeAndScale(fullSize(), 1));
-}
-
-TEST_F(ImageFrameGeneratorTest, frameHasAlpha)
-{
- setFrameStatus(ImageFrame::FramePartial);
- ImageDecodingStore::instance()->unlockCache(m_generator.get(), m_generator->decodeAndScale(fullSize(), 1));
- EXPECT_TRUE(m_generator->hasAlpha(1));
-
- ImageDecoder* tempDecoder = 0;
- EXPECT_TRUE(ImageDecodingStore::instance()->lockDecoder(m_generator.get(), fullSize(), &tempDecoder));
- ASSERT_TRUE(tempDecoder);
- static_cast<MockImageDecoder*>(tempDecoder)->setFrameHasAlpha(false);
- ImageDecodingStore::instance()->unlockDecoder(m_generator.get(), tempDecoder);
-
- setFrameStatus(ImageFrame::FrameComplete);
- ImageDecodingStore::instance()->unlockCache(m_generator.get(), m_generator->decodeAndScale(fullSize(), 1));
- EXPECT_FALSE(m_generator->hasAlpha(1));
-}
-
-namespace {
-
-class MockAllocator : public SkBitmap::Allocator {
-public:
- // N starts from 0.
- MockAllocator(int failAtNthCall)
- : m_callCount(0)
- , m_failAtNthCall(failAtNthCall)
- , m_defaultAllocator(adoptPtr(new DiscardablePixelRefAllocator()))
- {
- }
-
- virtual bool allocPixelRef(SkBitmap* bitmap, SkColorTable* colorTable) OVERRIDE
- {
- if (m_callCount++ == m_failAtNthCall)
- return false;
- return m_defaultAllocator->allocPixelRef(bitmap, colorTable);
- }
-
- int m_callCount;
- int m_failAtNthCall;
- OwnPtr<SkBitmap::Allocator> m_defaultAllocator;
-};
-
-} // namespace
-
-TEST_F(ImageFrameGeneratorTest, decodingAllocatorFailure)
-{
- // Try to emulate allocation failures at different stages. For now, the
- // first allocation is for the bitmap in ImageFrame, the second is for the
- // copy of partial bitmap. The loop will still work if the number or purpose
- // of allocations change in the future.
- for (int i = 0; ; ++i) {
- SCOPED_TRACE(testing::Message() << "Allocation failure at call " << i);
- setFrameStatus(ImageFrame::FramePartial);
- setAllocator(adoptPtr(new MockAllocator(i)));
- OwnPtr<ScaledImageFragment> image = decode(0);
- if (i >= static_cast<MockAllocator*>(allocator())->m_callCount) {
- // We have tested failures of all stages. This time all allocations
- // were successful.
- EXPECT_TRUE(image);
- break;
- }
- EXPECT_FALSE(image);
- }
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/LayerPainterChromium.h b/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/LayerPainterChromium.h
deleted file mode 100644
index a526f8335e5..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/LayerPainterChromium.h
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-
-#ifndef LayerPainterChromium_h
-#define LayerPainterChromium_h
-
-class SkCanvas;
-
-namespace WebCore {
-
-class FloatRect;
-class IntRect;
-
-class LayerPainterChromium {
-public:
- virtual ~LayerPainterChromium() { }
- virtual void paint(SkCanvas*, const IntRect& contentRect, FloatRect& opaque) = 0;
-};
-
-} // namespace WebCore
-
-#endif // LayerPainterChromium_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/LazyDecodingPixelRef.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/LazyDecodingPixelRef.cpp
deleted file mode 100644
index 88fc7a56ce7..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/LazyDecodingPixelRef.cpp
+++ /dev/null
@@ -1,130 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/chromium/LazyDecodingPixelRef.h"
-
-#include "SkData.h"
-#include "core/platform/chromium/TraceEvent.h"
-#include "core/platform/graphics/chromium/ImageDecodingStore.h"
-#include "core/platform/graphics/chromium/ImageFrameGenerator.h"
-
-namespace WebCore {
-
-LazyDecodingPixelRef::LazyDecodingPixelRef(PassRefPtr<ImageFrameGenerator> frameGenerator, const SkISize& scaledSize, size_t index, const SkIRect& scaledSubset)
- : m_frameGenerator(frameGenerator)
- , m_frameIndex(index)
- , m_scaledSize(scaledSize)
- , m_scaledSubset(scaledSubset)
- , m_lockedImageResource(0)
-{
-}
-
-LazyDecodingPixelRef::~LazyDecodingPixelRef()
-{
-}
-
-bool LazyDecodingPixelRef::isScaled(const SkISize& fullSize) const
-{
- return fullSize != m_scaledSize;
-}
-
-bool LazyDecodingPixelRef::isClipped() const
-{
- return m_scaledSize.width() != m_scaledSubset.width() || m_scaledSize.height() != m_scaledSubset.height();
-}
-
-SkData* LazyDecodingPixelRef::onRefEncodedData()
-{
- // If the image has been clipped or scaled, do not return the original encoded data, since
- // on playback it will not be known how the clipping/scaling was done.
- if (isClipped() || isScaled(m_frameGenerator->getFullSize()))
- return 0;
- RefPtr<SharedBuffer> buffer = 0;
- bool allDataReceived = false;
- m_frameGenerator->copyData(&buffer, &allDataReceived);
- if (buffer && allDataReceived) {
- SkData* skdata = SkData::NewWithCopy((void*)buffer->data(), buffer->size());
- return skdata;
- }
- return 0;
-}
-
-void* LazyDecodingPixelRef::onLockPixels(SkColorTable**)
-{
- TRACE_EVENT_ASYNC_BEGIN0("webkit", "LazyDecodingPixelRef::lockPixels", this);
-
- ASSERT(!m_lockedImageResource);
-
- if (!ImageDecodingStore::instance()->lockCache(m_frameGenerator.get(), m_scaledSize, m_frameIndex, &m_lockedImageResource))
- m_lockedImageResource = 0;
-
- // Use ImageFrameGenerator to generate the image. It will lock the cache
- // entry for us.
- if (!m_lockedImageResource)
- m_lockedImageResource = m_frameGenerator->decodeAndScale(m_scaledSize, m_frameIndex);
-
- if (!m_lockedImageResource)
- return 0;
-
- ASSERT(!m_lockedImageResource->bitmap().isNull());
- ASSERT(m_lockedImageResource->scaledSize() == m_scaledSize);
- return m_lockedImageResource->bitmap().getAddr(m_scaledSubset.x(), m_scaledSubset.y());
-}
-
-void LazyDecodingPixelRef::onUnlockPixels()
-{
- if (m_lockedImageResource) {
- ImageDecodingStore::instance()->unlockCache(m_frameGenerator.get(), m_lockedImageResource);
- m_lockedImageResource = 0;
- }
-
- TRACE_EVENT_ASYNC_END0("webkit", "LazyDecodingPixelRef::lockPixels", this);
-}
-
-bool LazyDecodingPixelRef::onLockPixelsAreWritable() const
-{
- return false;
-}
-
-bool LazyDecodingPixelRef::MaybeDecoded()
-{
- return ImageDecodingStore::instance()->isCached(m_frameGenerator.get(), m_scaledSize, m_frameIndex);
-}
-
-bool LazyDecodingPixelRef::PrepareToDecode(const LazyPixelRef::PrepareParams& params)
-{
- ASSERT(false);
- return false;
-}
-
-void LazyDecodingPixelRef::Decode()
-{
- lockPixels();
- unlockPixels();
-}
-
-
-} // namespace WebKit
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/LazyDecodingPixelRef.h b/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/LazyDecodingPixelRef.h
deleted file mode 100644
index 0ceb7da4bda..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/LazyDecodingPixelRef.h
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef LazyDecodingPixelRef_h
-#define LazyDecodingPixelRef_h
-
-#include "SkFlattenableBuffers.h"
-#include "SkPixelRef.h"
-#include "SkRect.h"
-#include "SkSize.h"
-#include "SkTypes.h"
-#include "skia/ext/lazy_pixel_ref.h"
-
-#include "wtf/RefPtr.h"
-
-using skia::LazyPixelRef;
-
-class SkData;
-
-namespace WebCore {
-
-class ImageFrameGenerator;
-class ScaledImageFragment;
-
-class LazyDecodingPixelRef : public LazyPixelRef {
-public:
- LazyDecodingPixelRef(PassRefPtr<ImageFrameGenerator>, const SkISize& scaledSize, size_t index, const SkIRect& scaledSubset);
- virtual ~LazyDecodingPixelRef();
-
- SK_DECLARE_UNFLATTENABLE_OBJECT()
-
- PassRefPtr<ImageFrameGenerator> frameGenerator() const { return m_frameGenerator; }
- size_t frameIndex() const { return m_frameIndex; }
- bool isScaled(const SkISize& fullSize) const;
- bool isClipped() const;
-
- // Returns true if the image might already be decoded in the cache.
- // Optimistic version of PrepareToDecode; requires less locking.
- virtual bool MaybeDecoded();
- virtual bool PrepareToDecode(const LazyPixelRef::PrepareParams&);
- virtual void Decode();
-
-protected:
- // SkPixelRef implementation.
- virtual void* onLockPixels(SkColorTable**);
- virtual void onUnlockPixels();
- virtual bool onLockPixelsAreWritable() const;
-
- virtual SkData* onRefEncodedData() SK_OVERRIDE;
-
-private:
- RefPtr<ImageFrameGenerator> m_frameGenerator;
- size_t m_frameIndex;
- SkISize m_scaledSize;
- SkIRect m_scaledSubset;
-
- const ScaledImageFragment* m_lockedImageResource;
-};
-
-} // namespace WebCore
-
-#endif // LazyDecodingPixelRef_h_
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/OpaqueRectTrackingContentLayerDelegate.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/OpaqueRectTrackingContentLayerDelegate.cpp
deleted file mode 100644
index dc10374e7f9..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/OpaqueRectTrackingContentLayerDelegate.cpp
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/platform/graphics/chromium/OpaqueRectTrackingContentLayerDelegate.h"
-
-#include "core/platform/EventTracer.h"
-#include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/graphics/IntRect.h"
-#include "core/platform/graphics/transforms/AffineTransform.h"
-#include "public/platform/WebFloatRect.h"
-#include "public/platform/WebRect.h"
-
-using WebKit::WebFloatRect;
-using WebKit::WebRect;
-
-namespace WebCore {
-
-OpaqueRectTrackingContentLayerDelegate::OpaqueRectTrackingContentLayerDelegate(GraphicsContextPainter* painter)
- : m_painter(painter)
- , m_opaque(false)
-{
-}
-
-OpaqueRectTrackingContentLayerDelegate::~OpaqueRectTrackingContentLayerDelegate()
-{
-}
-
-void OpaqueRectTrackingContentLayerDelegate::paintContents(SkCanvas* canvas, const WebRect& clip, bool canPaintLCDText, WebFloatRect& opaque)
-{
- GraphicsContext context(canvas);
- context.setTrackOpaqueRegion(!m_opaque);
- context.setCertainlyOpaque(m_opaque);
- context.setShouldSmoothFonts(canPaintLCDText);
-
- if (*EventTracer::getTraceCategoryEnabledFlag(TRACE_DISABLED_BY_DEFAULT("blink.graphics_context_annotations")))
- context.setAnnotationMode(AnnotateAll);
-
- // Record transform prior to painting, as all opaque tracking will be
- // relative to this current value.
- AffineTransform canvasToContentTransform = context.getCTM().inverse();
-
- m_painter->paint(context, clip);
-
- // Transform tracked opaque paints back to our layer's content space.
- ASSERT(canvasToContentTransform.isInvertible());
- ASSERT(canvasToContentTransform.preservesAxisAlignment());
- opaque = canvasToContentTransform.mapRect(context.opaqueRegion().asRect());
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/OpaqueRectTrackingContentLayerDelegate.h b/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/OpaqueRectTrackingContentLayerDelegate.h
deleted file mode 100644
index e83ce93978e..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/OpaqueRectTrackingContentLayerDelegate.h
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef OpaqueRectTrackingContentLayerDelegate_h
-#define OpaqueRectTrackingContentLayerDelegate_h
-
-#include "public/platform/WebContentLayerClient.h"
-#include "wtf/Noncopyable.h"
-#include "wtf/PassOwnPtr.h"
-
-class SkCanvas;
-
-namespace WebCore {
-
-class GraphicsContext;
-class IntRect;
-
-class GraphicsContextPainter {
-public:
- virtual void paint(GraphicsContext&, const IntRect& clip) = 0;
-
-protected:
- virtual ~GraphicsContextPainter() { }
-};
-
-class OpaqueRectTrackingContentLayerDelegate : public WebKit::WebContentLayerClient {
- WTF_MAKE_NONCOPYABLE(OpaqueRectTrackingContentLayerDelegate);
-public:
- explicit OpaqueRectTrackingContentLayerDelegate(GraphicsContextPainter*);
- virtual ~OpaqueRectTrackingContentLayerDelegate();
-
- // If we know that everything that will be painted through this delegate, then we don't bother
- // tracking opaqueness.
- void setOpaque(bool opaque) { m_opaque = opaque; }
-
- // WebKit::WebContentLayerClient implementation.
- virtual void paintContents(SkCanvas*, const WebKit::WebRect& clip, bool canPaintLCDText, WebKit::WebFloatRect& opaque) OVERRIDE;
-
-private:
- GraphicsContextPainter* m_painter;
- bool m_opaque;
-};
-
-}
-
-#endif // OpaqueRectTrackingContentLayerDelegate_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/ScaledImageFragment.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/ScaledImageFragment.cpp
deleted file mode 100644
index fb9c2c4431c..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/ScaledImageFragment.cpp
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/platform/graphics/chromium/ScaledImageFragment.h"
-
-namespace WebCore {
-
-ScaledImageFragment::~ScaledImageFragment()
-{
-}
-
-ScaledImageFragment::ScaledImageFragment(const SkISize& scaledSize, size_t index, size_t generation, const SkBitmap& bitmap)
- : m_scaledSize(scaledSize)
- , m_index(index)
- , m_generation(generation)
- , m_bitmap(bitmap)
-{
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/ScaledImageFragment.h b/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/ScaledImageFragment.h
deleted file mode 100644
index 0bfdea1162b..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/ScaledImageFragment.h
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ScaledImageFragment_h
-#define ScaledImageFragment_h
-
-#include "SkBitmap.h"
-#include "SkRect.h"
-#include "SkSize.h"
-
-#include "wtf/PassOwnPtr.h"
-
-namespace WebCore {
-
-// ScaledImageFragment is a scaled version of an image.
-class ScaledImageFragment {
-public:
- enum ImageGeneration {
- CompleteImage = 0,
- FirstPartialImage = 1,
- };
-
- static PassOwnPtr<ScaledImageFragment> createComplete(const SkISize& scaledSize, size_t index, const SkBitmap& bitmap)
- {
- return adoptPtr(new ScaledImageFragment(scaledSize, index, CompleteImage, bitmap));
- }
-
- static PassOwnPtr<ScaledImageFragment> createPartial(const SkISize& scaledSize, size_t index, size_t generation, const SkBitmap& bitmap)
- {
- return adoptPtr(new ScaledImageFragment(scaledSize, index, generation, bitmap));
- }
-
- ScaledImageFragment(const SkISize&, size_t index, size_t generation, const SkBitmap&);
- ~ScaledImageFragment();
-
- const SkISize& scaledSize() const { return m_scaledSize; }
- size_t index() const { return m_index; }
- size_t generation() const { return m_generation; }
- bool isComplete() const { return m_generation == CompleteImage; }
- const SkBitmap& bitmap() const { return m_bitmap; }
- SkBitmap& bitmap() { return m_bitmap; }
-
-private:
- SkISize m_scaledSize;
- size_t m_index;
- size_t m_generation;
- SkBitmap m_bitmap;
-};
-
-} // namespace WebCore
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/SimpleFontDataChromiumWin.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/SimpleFontDataChromiumWin.cpp
deleted file mode 100644
index 07125c28c46..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/SimpleFontDataChromiumWin.cpp
+++ /dev/null
@@ -1,181 +0,0 @@
-/*
- * Copyright (C) 2006, 2007 Apple Inc. All Rights Reserved.
- * Copyright (c) 2008, 2009, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/SimpleFontData.h"
-
-#include <mlang.h>
-#include <objidl.h>
-#include <unicode/uchar.h>
-#include <unicode/unorm.h>
-#include "core/platform/graphics/FloatRect.h"
-#include "core/platform/graphics/Font.h"
-#include "core/platform/graphics/FontCache.h"
-#include "core/platform/graphics/FontDescription.h"
-#include "core/platform/graphics/chromium/FontPlatformDataChromiumWin.h"
-#include "core/platform/win/HWndDC.h"
-#include "wtf/MathExtras.h"
-
-namespace WebCore {
-
-void SimpleFontData::platformInit()
-{
- if (!m_platformData.size()) {
- m_fontMetrics.reset();
- m_avgCharWidth = 0;
- m_maxCharWidth = 0;
- return;
- }
-
- HWndDC dc(0);
- HGDIOBJ oldFont = SelectObject(dc, m_platformData.hfont());
-
- TEXTMETRIC textMetric = {0};
- if (!GetTextMetrics(dc, &textMetric)) {
- if (FontPlatformData::ensureFontLoaded(m_platformData.hfont())) {
- // Retry GetTextMetrics.
- // FIXME: Handle gracefully the error if this call also fails.
- // See http://crbug.com/6401.
- if (!GetTextMetrics(dc, &textMetric))
- LOG_ERROR("Unable to get the text metrics after second attempt");
- }
- }
-
- m_avgCharWidth = textMetric.tmAveCharWidth;
- m_maxCharWidth = textMetric.tmMaxCharWidth;
-
- // FIXME: Access ascent/descent/lineGap with floating point precision.
- float ascent = textMetric.tmAscent;
- float descent = textMetric.tmDescent;
- float lineGap = textMetric.tmExternalLeading;
- float xHeight = ascent * 0.56f; // Best guess for xHeight for non-Truetype fonts.
-
- OUTLINETEXTMETRIC outlineTextMetric;
- if (GetOutlineTextMetrics(dc, sizeof(outlineTextMetric), &outlineTextMetric) > 0) {
- m_fontMetrics.setUnitsPerEm(outlineTextMetric.otmEMSquare);
-
- // This is a TrueType font. We might be able to get an accurate xHeight.
- GLYPHMETRICS glyphMetrics = {0};
- MAT2 identityMatrix = {{0, 1}, {0, 0}, {0, 0}, {0, 1}};
- DWORD len = GetGlyphOutlineW(dc, 'x', GGO_METRICS, &glyphMetrics, 0, 0, &identityMatrix);
- if (len != GDI_ERROR && glyphMetrics.gmBlackBoxY > 0)
- xHeight = static_cast<float>(glyphMetrics.gmBlackBoxY);
- }
-
- m_fontMetrics.setAscent(ascent);
- m_fontMetrics.setDescent(descent);
- m_fontMetrics.setLineGap(lineGap);
- m_fontMetrics.setXHeight(xHeight);
- m_fontMetrics.setLineSpacing(ascent + descent + lineGap);
-
- SelectObject(dc, oldFont);
-}
-
-void SimpleFontData::platformCharWidthInit()
-{
- // charwidths are set in platformInit.
-}
-
-void SimpleFontData::platformDestroy()
-{
-}
-
-PassRefPtr<SimpleFontData> SimpleFontData::platformCreateScaledFontData(const FontDescription& fontDescription, float scaleFactor) const
-{
- LOGFONT winFont;
- GetObject(m_platformData.hfont(), sizeof(LOGFONT), &winFont);
- float scaledSize = scaleFactor * fontDescription.computedSize();
- winFont.lfHeight = -lroundf(scaledSize);
- HFONT hfont = CreateFontIndirect(&winFont);
- return SimpleFontData::create(FontPlatformData(hfont, scaledSize, m_platformData.orientation()), isCustomFont(), false);
-}
-
-bool SimpleFontData::containsCharacters(const UChar* characters, int length) const
-{
- // This used to be implemented with IMLangFontLink2, but since that code has
- // been disabled, this would always return false anyway.
- return false;
-}
-
-void SimpleFontData::determinePitch()
-{
- m_treatAsFixedPitch = platformData().isFixedPitch();
-}
-
-FloatRect SimpleFontData::platformBoundsForGlyph(Glyph glyph) const
-{
- HWndDC hdc(0);
- SetGraphicsMode(hdc, GM_ADVANCED);
- HGDIOBJ oldFont = SelectObject(hdc, m_platformData.hfont());
-
- GLYPHMETRICS gdiMetrics;
- static const MAT2 identity = { 0, 1, 0, 0, 0, 0, 0, 1 };
- if (GetGlyphOutline(hdc, glyph, GGO_METRICS | GGO_GLYPH_INDEX, &gdiMetrics, 0, 0, &identity) == -1) {
- if (FontPlatformData::ensureFontLoaded(m_platformData.hfont())) {
- // Retry GetTextMetrics.
- // FIXME: Handle gracefully the error if this call also fails.
- // See http://crbug.com/6401.
- if (GetGlyphOutline(hdc, glyph, GGO_METRICS | GGO_GLYPH_INDEX, &gdiMetrics, 0, 0, &identity) == -1)
- LOG_ERROR("Unable to get the glyph metrics after second attempt");
- }
- }
-
- SelectObject(hdc, oldFont);
-
- return FloatRect(gdiMetrics.gmptGlyphOrigin.x, -gdiMetrics.gmptGlyphOrigin.y,
- gdiMetrics.gmBlackBoxX, gdiMetrics.gmBlackBoxY);
-}
-
-float SimpleFontData::platformWidthForGlyph(Glyph glyph) const
-{
- if (!m_platformData.size())
- return 0;
-
- HWndDC dc(0);
- HGDIOBJ oldFont = SelectObject(dc, m_platformData.hfont());
-
- int width = 0;
- if (!GetCharWidthI(dc, glyph, 1, 0, &width)) {
- // Ask the browser to preload the font and retry.
- if (FontPlatformData::ensureFontLoaded(m_platformData.hfont())) {
- // FIXME: Handle gracefully the error if this call also fails.
- // See http://crbug.com/6401.
- if (!GetCharWidthI(dc, glyph, 1, 0, &width))
- LOG_ERROR("Unable to get the char width after second attempt");
- }
- }
-
- SelectObject(dc, oldFont);
-
- return static_cast<float>(width);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/SkSizeHash.h b/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/SkSizeHash.h
deleted file mode 100644
index dd95c825ceb..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/SkSizeHash.h
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SkSizeHash_h
-#define SkSizeHash_h
-
-#include "SkScalar.h"
-#include "SkSize.h"
-
-#include "wtf/HashMap.h"
-
-namespace WTF {
-
-template<> struct IntHash<SkSize> {
- static unsigned hash(const SkSize& key) { return pairIntHash(key.width(), key.height()); }
- static bool equal(const SkSize& a, const SkSize& b) { return a == b; }
- static const bool safeToCompareToEmptyOrDeleted = true;
-};
-
-template<> struct DefaultHash<SkSize> {
- typedef IntHash<SkSize> Hash;
-};
-
-template<> struct HashTraits<SkSize> : GenericHashTraits<SkSize> {
- static const bool emptyValueIsZero = true;
- static const bool needsDestruction = false;
- static SkSize emptyValue() { return SkSize::Make(0, 0); }
- static void constructDeletedValue(SkSize& slot)
- {
- slot = SkSize::Make(-1, -1);
- }
- static bool isDeletedValue(const SkSize& value)
- {
- return value.width() == -1 && value.height() == -1;
- }
-};
-
-template<> struct IntHash<SkISize> {
- static unsigned hash(const SkISize& key) { return pairIntHash(key.width(), key.height()); }
- static bool equal(const SkISize& a, const SkISize& b) { return a == b; }
- static const bool safeToCompareToEmptyOrDeleted = true;
-};
-
-template<> struct DefaultHash<SkISize> {
- typedef IntHash<SkISize> Hash;
-};
-
-template<> struct HashTraits<SkISize> : GenericHashTraits<SkISize> {
- static const bool emptyValueIsZero = true;
- static const bool needsDestruction = false;
- static SkISize emptyValue() { return SkISize::Make(0, 0); }
- static void constructDeletedValue(SkISize& slot)
- {
- slot = SkISize::Make(-1, -1);
- }
- static bool isDeletedValue(const SkISize& value)
- {
- return value.width() == -1 && value.height() == -1;
- }
-};
-
-} // namespace WTF
-
-#endif // SkSizeHash_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/TextureUploader.h b/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/TextureUploader.h
deleted file mode 100644
index 0a861612e35..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/TextureUploader.h
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright (C) 2012, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TextureUploader_h
-#define TextureUploader_h
-
-#include "LayerTextureUpdater.h"
-
-namespace WebCore {
-
-class TextureUploader {
-public:
- struct Parameters {
- LayerTextureUpdater::Texture* texture;
- IntRect sourceRect;
- IntSize destOffset;
- };
-
- virtual ~TextureUploader() { }
-
- virtual bool isBusy() = 0;
- virtual void beginUploads() = 0;
- virtual void endUploads() = 0;
- virtual void uploadTexture(CCResourceProvider*, Parameters) = 0;
-};
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/ThreadSafeDataTransport.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/ThreadSafeDataTransport.cpp
deleted file mode 100644
index aebad67fd0a..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/ThreadSafeDataTransport.cpp
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/platform/graphics/chromium/ThreadSafeDataTransport.h"
-
-#include "core/platform/SharedBuffer.h"
-
-namespace WebCore {
-
-ThreadSafeDataTransport::ThreadSafeDataTransport()
- : m_readBuffer(SharedBuffer::create())
- , m_readPosition(0)
-{
-}
-
-ThreadSafeDataTransport::~ThreadSafeDataTransport()
-{
-}
-
-void ThreadSafeDataTransport::setData(SharedBuffer* buffer, bool allDataReceived)
-{
- ASSERT(buffer->size() >= m_readPosition);
- Vector<RefPtr<SharedBuffer> > newBufferQueue;
-
- const char* segment = 0;
- while (size_t length = buffer->getSomeData(segment, m_readPosition)) {
- m_readPosition += length;
- newBufferQueue.append(SharedBuffer::create(segment, length));
- }
-
- MutexLocker locker(m_mutex);
- m_newBufferQueue.append(newBufferQueue);
- m_allDataReceived = allDataReceived;
-}
-
-void ThreadSafeDataTransport::data(SharedBuffer** buffer, bool* allDataReceived)
-{
- Vector<RefPtr<SharedBuffer> > newBufferQueue;
- {
- MutexLocker lock(m_mutex);
- m_newBufferQueue.swap(newBufferQueue);
- }
- for (size_t i = 0; i < newBufferQueue.size(); ++i)
- m_readBuffer->append(newBufferQueue[i].get());
- ASSERT(buffer);
- ASSERT(allDataReceived);
- *buffer = m_readBuffer.get();
- *allDataReceived = m_allDataReceived;
-}
-
-bool ThreadSafeDataTransport::hasNewData()
-{
- MutexLocker lock(m_mutex);
- return !m_newBufferQueue.isEmpty();
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/ThreadSafeDataTransport.h b/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/ThreadSafeDataTransport.h
deleted file mode 100644
index 431f545313a..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/ThreadSafeDataTransport.h
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ThreadSafeDataTransport_h
-#define ThreadSafeDataTransport_h
-
-#include "wtf/OwnPtr.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/RefPtr.h"
-#include "wtf/ThreadingPrimitives.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-class SharedBuffer;
-
-// The purpose of this class is to allow the transfer of data stored in
-// SharedBuffer in a thread-safe manner, and to minimize memory copies
-// and thread contention.
-//
-// This class is designed such that there is only one producer and
-// one consumer.
-class ThreadSafeDataTransport {
-public:
- ThreadSafeDataTransport();
- ~ThreadSafeDataTransport();
-
- // This method is being called subsequently with an expanding
- // SharedBuffer.
- void setData(SharedBuffer*, bool allDataReceived);
-
- // Get the data submitted to this class so far.
- void data(SharedBuffer**, bool* allDataReceived);
-
- // Return true of there is new data submitted to this class
- // since last time data() was called.
- bool hasNewData();
-
-private:
- Mutex m_mutex;
-
- Vector<RefPtr<SharedBuffer> > m_newBufferQueue;
- RefPtr<SharedBuffer> m_readBuffer;
- bool m_allDataReceived;
- size_t m_readPosition;
-};
-
-} // namespace WebCore
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/ThreadSafeDataTransportTest.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/ThreadSafeDataTransportTest.cpp
deleted file mode 100644
index f1ad89cca05..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/ThreadSafeDataTransportTest.cpp
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/platform/graphics/chromium/ThreadSafeDataTransport.h"
-
-#include "core/platform/SharedBuffer.h"
-#include <gtest/gtest.h>
-
-using namespace WebCore;
-
-namespace {
-
-TEST(ThreadSafeDataTransportTest, hasNewData)
-{
- ThreadSafeDataTransport transport;
-
- const char testString[] = "123456789";
- RefPtr<SharedBuffer> buffer = SharedBuffer::create(testString, sizeof(testString));
-
- transport.setData(buffer.get(), false);
- EXPECT_TRUE(transport.hasNewData());
-
- SharedBuffer* tempBuffer = 0;
- bool allDataReceived = false;
- transport.data(&tempBuffer, &allDataReceived);
- EXPECT_FALSE(transport.hasNewData());
-
- transport.setData(buffer.get(), false);
- EXPECT_FALSE(transport.hasNewData());
-}
-
-TEST(ThreadSafeDataTransportTest, setData)
-{
- ThreadSafeDataTransport transport;
-
- const char testString1[] = "123";
- RefPtr<SharedBuffer> buffer1 = SharedBuffer::create(testString1, sizeof(testString1) - 1);
- const char testString2[] = "12345";
- RefPtr<SharedBuffer> buffer2 = SharedBuffer::create(testString2, sizeof(testString2) - 1);
- const char testString3[] = "1234567890";
- RefPtr<SharedBuffer> buffer3 = SharedBuffer::create(testString3, sizeof(testString3) - 1);
-
- transport.setData(buffer1.get(), false);
- transport.setData(buffer2.get(), false);
- transport.setData(buffer3.get(), true);
- EXPECT_TRUE(transport.hasNewData());
-
- SharedBuffer* tempBuffer = 0;
- bool allDataReceived = false;
- transport.data(&tempBuffer, &allDataReceived);
- EXPECT_TRUE(allDataReceived);
- EXPECT_FALSE(memcmp(testString3, tempBuffer->data(), tempBuffer->size()));
-}
-
-} // namespace
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/TransformSkMatrix44Conversions.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/TransformSkMatrix44Conversions.cpp
deleted file mode 100644
index 1972d2cf96e..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/TransformSkMatrix44Conversions.cpp
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/platform/graphics/chromium/TransformSkMatrix44Conversions.h"
-
-#include "core/platform/graphics/transforms/TransformationMatrix.h"
-
-namespace WebCore {
-
-SkMatrix44 TransformSkMatrix44Conversions::convert(const TransformationMatrix& matrix)
-{
- SkMatrix44 ret(SkMatrix44::kUninitialized_Constructor);
- ret.setDouble(0, 0, matrix.m11());
- ret.setDouble(0, 1, matrix.m21());
- ret.setDouble(0, 2, matrix.m31());
- ret.setDouble(0, 3, matrix.m41());
- ret.setDouble(1, 0, matrix.m12());
- ret.setDouble(1, 1, matrix.m22());
- ret.setDouble(1, 2, matrix.m32());
- ret.setDouble(1, 3, matrix.m42());
- ret.setDouble(2, 0, matrix.m13());
- ret.setDouble(2, 1, matrix.m23());
- ret.setDouble(2, 2, matrix.m33());
- ret.setDouble(2, 3, matrix.m43());
- ret.setDouble(3, 0, matrix.m14());
- ret.setDouble(3, 1, matrix.m24());
- ret.setDouble(3, 2, matrix.m34());
- ret.setDouble(3, 3, matrix.m44());
- return ret;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/TransformSkMatrix44Conversions.h b/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/TransformSkMatrix44Conversions.h
deleted file mode 100644
index 78b9234d2c7..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/TransformSkMatrix44Conversions.h
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "SkMatrix44.h"
-
-namespace WebCore {
-
-class TransformationMatrix;
-
-class TransformSkMatrix44Conversions {
-public:
- static SkMatrix44 convert(const TransformationMatrix&);
-};
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/TransparencyWin.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/TransparencyWin.cpp
deleted file mode 100644
index 539cde4f931..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/TransparencyWin.cpp
+++ /dev/null
@@ -1,516 +0,0 @@
-/*
- * Copyright (C) 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <windows.h>
-#include "config.h"
-
-#include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/graphics/ImageBuffer.h"
-#include "core/platform/graphics/SimpleFontData.h"
-#include "core/platform/graphics/chromium/TransparencyWin.h"
-#include "core/platform/graphics/transforms/AffineTransform.h"
-
-#include "SkColorPriv.h"
-#include "skia/ext/platform_canvas.h"
-
-namespace WebCore {
-
-namespace {
-
-// The maximum size in pixels of the buffer we'll keep around for drawing text
-// into. Buffers larger than this will be destroyed when we're done with them.
-const int maxCachedBufferPixelSize = 65536;
-
-inline const SkBitmap& bitmapForContext(const GraphicsContext& context)
-{
- return context.layerBitmap();
-}
-
-void compositeToCopy(GraphicsContext& sourceLayers,
- GraphicsContext& destContext,
- const AffineTransform& matrix)
-{
- // Make a list of all devices. The iterator goes top-down, and we want
- // bottom-up. Note that each layer can also have an offset in canvas
- // coordinates, which is the (x, y) position.
- struct DeviceInfo {
- DeviceInfo(SkBaseDevice* d, int lx, int ly)
- : device(d)
- , x(lx)
- , y(ly) {}
- SkBaseDevice* device;
- int x;
- int y;
- };
- Vector<DeviceInfo> devices;
- SkCanvas* sourceCanvas = sourceLayers.canvas();
- SkCanvas::LayerIter iter(sourceCanvas, false);
- while (!iter.done()) {
- devices.append(DeviceInfo(iter.device(), iter.x(), iter.y()));
- iter.next();
- }
-
- // Create a temporary canvas for the compositing into the destination.
- SkBitmap* destBmp = const_cast<SkBitmap*>(&bitmapForContext(destContext));
- SkCanvas destCanvas(*destBmp);
- destCanvas.setMatrix(matrix);
-
- for (int i = devices.size() - 1; i >= 0; i--) {
- const SkBitmap& srcBmp = devices[i].device->accessBitmap(false);
-
- SkRect destRect;
- destRect.fLeft = devices[i].x;
- destRect.fTop = devices[i].y;
- destRect.fRight = destRect.fLeft + srcBmp.width();
- destRect.fBottom = destRect.fTop + srcBmp.height();
-
- destCanvas.drawBitmapRect(srcBmp, 0, destRect);
- }
-}
-
-} // namespace
-
-// If either of these pointers is non-null, both must be valid and point to
-// bitmaps of the same size.
-class TransparencyWin::OwnedBuffers {
-public:
- OwnedBuffers(const IntSize& size, bool needReferenceBuffer)
- {
- m_destBitmap = ImageBuffer::create(size, 1);
-
- if (needReferenceBuffer) {
- m_referenceBitmap.setConfig(SkBitmap::kARGB_8888_Config, size.width(), size.height());
- m_referenceBitmap.allocPixels();
- m_referenceBitmap.eraseARGB(0, 0, 0, 0);
- }
- }
-
- ImageBuffer* destBitmap() { return m_destBitmap.get(); }
-
- // This bitmap will be empty if you don't specify needReferenceBuffer to the
- // constructor.
- SkBitmap* referenceBitmap() { return &m_referenceBitmap; }
-
- // Returns whether the current layer will fix a buffer of the given size.
- bool canHandleSize(const IntSize& size) const
- {
- return m_destBitmap->internalSize().width() >= size.width() && m_destBitmap->internalSize().height() >= size.height();
- }
-
-private:
- // The destination bitmap we're drawing into.
- OwnPtr<ImageBuffer> m_destBitmap;
-
- // This could be an ImageBuffer but this is an optimization. Since this is
- // only ever used as a reference, we don't need to make a full
- // PlatformCanvas using Skia on Windows. Just allocating a regular SkBitmap
- // is much faster since it's just a Malloc rather than a GDI call.
- SkBitmap m_referenceBitmap;
-};
-
-TransparencyWin::OwnedBuffers* TransparencyWin::m_cachedBuffers = 0;
-
-TransparencyWin::TransparencyWin()
- : m_destContext(0)
- , m_orgTransform()
- , m_layerMode(NoLayer)
- , m_transformMode(KeepTransform)
- , m_drawContext(0)
- , m_savedOnDrawContext(false)
- , m_layerBuffer(0)
- , m_referenceBitmap(0)
- , m_validLayer(false)
-{
-}
-
-TransparencyWin::~TransparencyWin()
-{
- // This should be false, since calling composite() is mandatory.
- ASSERT(!m_savedOnDrawContext);
-}
-
-void TransparencyWin::composite()
-{
- // Matches the save() in initializeNewTextContext (or the constructor for
- // SCALE) to put the context back into the same state we found it.
- if (m_savedOnDrawContext) {
- m_drawContext->restore();
- m_savedOnDrawContext = false;
- }
-
- switch (m_layerMode) {
- case NoLayer:
- break;
- case OpaqueCompositeLayer:
- case WhiteLayer:
- compositeOpaqueComposite();
- break;
- case TextComposite:
- compositeTextComposite();
- break;
- }
-}
-
-void TransparencyWin::init(GraphicsContext* dest,
- LayerMode layerMode,
- TransformMode transformMode,
- const IntRect& region)
-{
- m_destContext = dest;
- m_orgTransform = dest->getCTM();
- m_layerMode = layerMode;
- m_transformMode = transformMode;
- m_sourceRect = region;
-
- computeLayerSize();
- setupLayer();
- setupTransform(region);
-}
-
-void TransparencyWin::computeLayerSize()
-{
- if (m_transformMode == Untransform) {
- // The meaning of the "transformed" source rect is a little ambigous
- // here. The rest of the code doesn't care about it in the Untransform
- // case since we're using our own happy coordinate system. So we set it
- // to be the source rect since that matches how the code below actually
- // uses the variable: to determine how to translate things to account
- // for the offset of the layer.
- m_transformedSourceRect = m_sourceRect;
- } else if (m_transformMode == KeepTransform && m_layerMode != TextComposite) {
- // FIXME: support clipping for other modes
- IntRect clippedSourceRect = m_sourceRect;
- SkRect clipBounds;
- if (m_destContext->getClipBounds(&clipBounds)) {
- FloatRect clipRect(clipBounds.left(), clipBounds.top(), clipBounds.width(), clipBounds.height());
- clippedSourceRect.intersect(enclosingIntRect(clipRect));
- }
- m_transformedSourceRect = m_orgTransform.mapRect(clippedSourceRect);
- } else
- m_transformedSourceRect = m_orgTransform.mapRect(m_sourceRect);
-
- m_layerSize = IntSize(m_transformedSourceRect.width(), m_transformedSourceRect.height());
-}
-
-void TransparencyWin::setupLayer()
-{
- switch (m_layerMode) {
- case NoLayer:
- setupLayerForNoLayer();
- break;
- case OpaqueCompositeLayer:
- setupLayerForOpaqueCompositeLayer();
- break;
- case TextComposite:
- setupLayerForTextComposite();
- break;
- case WhiteLayer:
- setupLayerForWhiteLayer();
- break;
- }
-}
-
-void TransparencyWin::setupLayerForNoLayer()
-{
- m_drawContext = m_destContext; // Draw to the source context.
- m_validLayer = true;
-}
-
-void TransparencyWin::setupLayerForOpaqueCompositeLayer()
-{
- initializeNewContext();
- if (!m_validLayer)
- return;
-
- AffineTransform mapping;
- mapping.translate(-m_transformedSourceRect.x(), -m_transformedSourceRect.y());
- if (m_transformMode == Untransform){
- // Compute the inverse mapping from the canvas space to the
- // coordinate space of our bitmap.
- mapping *= m_orgTransform.inverse();
- }
- compositeToCopy(*m_destContext, *m_drawContext, mapping);
-
- // Save the reference layer so we can tell what changed.
- SkCanvas referenceCanvas(*m_referenceBitmap);
- referenceCanvas.drawBitmap(bitmapForContext(*m_drawContext), 0, 0);
- // Layer rect represents the part of the original layer.
-}
-
-void TransparencyWin::setupLayerForTextComposite()
-{
- ASSERT(m_transformMode == KeepTransform);
- // Fall through to filling with white.
- setupLayerForWhiteLayer();
-}
-
-void TransparencyWin::setupLayerForWhiteLayer()
-{
- initializeNewContext();
- if (!m_validLayer)
- return;
-
- m_drawContext->fillRect(IntRect(IntPoint(0, 0), m_layerSize), Color::white);
- // Layer rect represents the part of the original layer.
-}
-
-void TransparencyWin::setupTransform(const IntRect& region)
-{
- switch (m_transformMode) {
- case KeepTransform:
- setupTransformForKeepTransform(region);
- break;
- case Untransform:
- setupTransformForUntransform();
- break;
- case ScaleTransform:
- setupTransformForScaleTransform();
- break;
- }
-}
-
-void TransparencyWin::setupTransformForKeepTransform(const IntRect& region)
-{
- if (!m_validLayer)
- return;
-
- if (m_layerMode != NoLayer) {
- // Need to save things since we're modifying the transform.
- m_drawContext->save();
- m_savedOnDrawContext = true;
-
- // Account for the fact that the layer may be offset from the
- // original. This only happens when we create a layer that has the
- // same coordinate space as the parent.
- AffineTransform xform;
- xform.translate(-m_transformedSourceRect.x(), -m_transformedSourceRect.y());
-
- // We're making a layer, so apply the old transform to the new one
- // so it's maintained. We know the new layer has the identity
- // transform now, we we can just multiply it.
- xform *= m_orgTransform;
- m_drawContext->concatCTM(xform);
- }
- m_drawRect = m_sourceRect;
-}
-
-void TransparencyWin::setupTransformForUntransform()
-{
- ASSERT(m_layerMode != NoLayer);
- // We now have a new layer with the identity transform, which is the
- // Untransformed space we'll use for drawing.
- m_drawRect = IntRect(IntPoint(0, 0), m_layerSize);
-}
-
-void TransparencyWin::setupTransformForScaleTransform()
-{
- if (!m_validLayer)
- return;
-
- if (m_layerMode == NoLayer) {
- // Need to save things since we're modifying the layer.
- m_drawContext->save();
- m_savedOnDrawContext = true;
-
- // Undo the transform on the current layer when we're re-using the
- // current one.
- m_drawContext->concatCTM(m_drawContext->getCTM().inverse());
-
- // We're drawing to the original layer with just a different size.
- m_drawRect = m_transformedSourceRect;
- } else {
- // Just go ahead and use the layer's coordinate space to draw into.
- // It will have the scaled size, and an identity transform loaded.
- m_drawRect = IntRect(IntPoint(0, 0), m_layerSize);
- }
-}
-
-void TransparencyWin::setTextCompositeColor(Color color)
-{
- m_textCompositeColor = color;
-}
-
-void TransparencyWin::initializeNewContext()
-{
- int pixelSize = m_layerSize.width() * m_layerSize.height();
- if (pixelSize <= 0)
- return;
-
- if (pixelSize > maxCachedBufferPixelSize) {
- // Create a 1-off buffer for drawing into. We only need the reference
- // buffer if we're making an OpaqueCompositeLayer.
- bool needReferenceBitmap = m_layerMode == OpaqueCompositeLayer;
- m_ownedBuffers = adoptPtr(new OwnedBuffers(m_layerSize, needReferenceBitmap));
- m_layerBuffer = m_ownedBuffers->destBitmap();
- if (!m_layerBuffer)
- return;
-
- m_drawContext = m_layerBuffer->context();
- if (needReferenceBitmap) {
- m_referenceBitmap = m_ownedBuffers->referenceBitmap();
- if (!m_referenceBitmap || !m_referenceBitmap->getPixels())
- return;
- }
- m_validLayer = true;
- return;
- }
-
- if (m_cachedBuffers && m_cachedBuffers->canHandleSize(m_layerSize)) {
- // We can re-use the existing buffer. We don't need to clear it since
- // all layer modes will clear it in their initialization.
- m_layerBuffer = m_cachedBuffers->destBitmap();
- m_drawContext = m_cachedBuffers->destBitmap()->context();
- bitmapForContext(*m_drawContext).eraseARGB(0, 0, 0, 0);
- m_referenceBitmap = m_cachedBuffers->referenceBitmap();
- m_referenceBitmap->eraseARGB(0, 0, 0, 0);
- m_validLayer = true;
- return;
- }
-
- // Create a new cached buffer.
- if (m_cachedBuffers)
- delete m_cachedBuffers;
- m_cachedBuffers = new OwnedBuffers(m_layerSize, true);
-
- m_layerBuffer = m_cachedBuffers->destBitmap();
- m_drawContext = m_cachedBuffers->destBitmap()->context();
- m_referenceBitmap = m_cachedBuffers->referenceBitmap();
- m_validLayer = true;
-}
-
-void TransparencyWin::compositeOpaqueComposite()
-{
- if (!m_validLayer)
- return;
-
- m_destContext->save();
-
- SkBitmap* bitmap = const_cast<SkBitmap*>(
- &bitmapForContext(*m_layerBuffer->context()));
-
- // This function will be called for WhiteLayer as well, which we don't want
- // to change.
- if (m_layerMode == OpaqueCompositeLayer) {
- // Fix up our bitmap, making it contain only the pixels which changed
- // and transparent everywhere else.
- SkAutoLockPixels sourceLock(*m_referenceBitmap);
- SkAutoLockPixels lock(*bitmap);
- for (int y = 0; y < bitmap->height(); y++) {
- uint32_t* source = m_referenceBitmap->getAddr32(0, y);
- uint32_t* dest = bitmap->getAddr32(0, y);
- for (int x = 0; x < bitmap->width(); x++) {
- // Clear out any pixels that were untouched.
- if (dest[x] == source[x])
- dest[x] = 0;
- else
- dest[x] |= (0xFF << SK_A32_SHIFT);
- }
- }
- } else
- makeLayerOpaque();
-
- SkRect destRect;
- if (m_transformMode != Untransform) {
- // We want to use Untransformed space.
- //
- // Note that we DON'T call m_layerBuffer->image() here. This actually
- // makes a copy of the image, which is unnecessary and slow. Instead, we
- // just draw the image from inside the destination context.
- SkMatrix identity;
- identity.reset();
- m_destContext->setMatrix(identity);
-
- destRect.set(m_transformedSourceRect.x(), m_transformedSourceRect.y(), m_transformedSourceRect.maxX(), m_transformedSourceRect.maxY());
- } else
- destRect.set(m_sourceRect.x(), m_sourceRect.y(), m_sourceRect.maxX(), m_sourceRect.maxY());
-
- SkPaint paint;
- paint.setFilterBitmap(true);
- paint.setAntiAlias(true);
-
- // Note that we need to specify the source layer subset, since the bitmap
- // may have been cached and it could be larger than what we're using.
- SkRect sourceRect = SkRect::MakeWH(
- SkIntToScalar(m_layerSize.width()),
- SkIntToScalar(m_layerSize.height()));
- m_destContext->drawBitmapRect(*bitmap, &sourceRect, destRect, &paint);
- m_destContext->restore();
-}
-
-void TransparencyWin::compositeTextComposite()
-{
- if (!m_validLayer)
- return;
-
- const SkBitmap& bitmap = m_layerBuffer->context()->layerBitmap(GraphicsContext::ReadWrite);
- SkColor textColor = m_textCompositeColor.rgb();
- for (int y = 0; y < m_layerSize.height(); y++) {
- uint32_t* row = bitmap.getAddr32(0, y);
- for (int x = 0; x < m_layerSize.width(); x++) {
- // The alpha is the average of the R, G, and B channels.
- int alpha = (SkGetPackedR32(row[x]) + SkGetPackedG32(row[x]) + SkGetPackedB32(row[x])) / 3;
-
- // Apply that alpha to the text color and write the result.
- row[x] = SkAlphaMulQ(textColor, SkAlpha255To256(255 - alpha));
- }
- }
-
- // Now the layer has text with the proper color and opacity.
- m_destContext->save();
-
- // We want to use Untransformed space (see above)
- SkMatrix identity;
- identity.reset();
- m_destContext->setMatrix(identity);
- SkRect destRect = { m_transformedSourceRect.x(), m_transformedSourceRect.y(), m_transformedSourceRect.maxX(), m_transformedSourceRect.maxY() };
-
- // Note that we need to specify the source layer subset, since the bitmap
- // may have been cached and it could be larger than what we're using.
- SkRect sourceRect = SkRect::MakeWH(
- SkIntToScalar(m_layerSize.width()),
- SkIntToScalar(m_layerSize.height()));
- m_destContext->drawBitmapRect(bitmap, &sourceRect, destRect, 0);
- m_destContext->restore();
-}
-
-void TransparencyWin::makeLayerOpaque()
-{
- if (!m_validLayer)
- return;
-
- SkBitmap& bitmap = const_cast<SkBitmap&>(m_drawContext->layerBitmap(GraphicsContext::ReadWrite));
- for (int y = 0; y < m_layerSize.height(); y++) {
- uint32_t* row = bitmap.getAddr32(0, y);
- for (int x = 0; x < m_layerSize.width(); x++)
- row[x] |= 0xFF000000;
- }
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/TransparencyWin.h b/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/TransparencyWin.h
deleted file mode 100644
index ab5bbfe7b9f..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/TransparencyWin.h
+++ /dev/null
@@ -1,261 +0,0 @@
-/*
- * Copyright (C) 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TransparencyWin_h
-#define TransparencyWin_h
-
-#include <windows.h>
-
-#include "core/platform/graphics/ImageBuffer.h"
-#include "core/platform/graphics/transforms/AffineTransform.h"
-
-#include "wtf/Noncopyable.h"
-#include "wtf/OwnPtr.h"
-
-class SkBitmap;
-class SkCanvas;
-
-namespace WebCore {
-
-class GraphicsContext;
-class TransparencyWin_NoLayer_Test;
-class TransparencyWin_WhiteLayer_Test;
-class TransparencyWin_TextComposite_Test;
-class TransparencyWin_OpaqueCompositeLayer_Test;
-
-// Helper class that abstracts away drawing ClearType text and Windows form
-// controls either to the original context directly, or to an offscreen context
-// that is composited later manually. This is to get around Windows' inability
-// to handle the alpha channel, semitransparent text, and transformed form
-// controls.
-class TransparencyWin {
- WTF_MAKE_NONCOPYABLE(TransparencyWin);
-public:
- enum LayerMode {
- // No extra layer is created. Drawing will happen to the source.
- // Valid only with KeepTransform and ScaleTransform. The region being
- // drawn onto must be opaque, since the modified region will be forced
- // to opaque when drawing is complete.
- NoLayer,
-
- // Makes a temporary layer consisting of the composited layers below
- // it. This result must be opaque. When complete, the result will be
- // compared to the original, and the difference will be added to a thee
- // destination layer.
- //
- // This mode only works if the lower layers are opque (normally the
- // case for a web page) and layers are only drawn in the stack order,
- // meaning you can never draw underneath a layer.
- //
- // This doesn't technically produce the correct answer in all cases. If
- // you have an opaque base, a transparency layer, than a semitransparent
- // drawing on top, the result will actually be blended in twice. But
- // this isn't a very important case. This mode is used for form
- // controls which are always opaque except for occationally some
- // antialiasing. It means form control antialiasing will be too light in
- // some cases, but only if you have extra layers.
- OpaqueCompositeLayer,
-
- // Allows semitransparent text to be drawn on any background (even if it
- // is itself semitransparent), but disables ClearType.
- //
- // It makes a trmporary layer filled with white. This is composited with
- // the lower layer with a custom color applied to produce the result.
- // The caller must draw the text in black, and set the desired final
- // text color by calling setTextCompositeColor().
- //
- // Only valid with KeepTransform, which is the only mode where drawing
- // text in this fashion makes sense.
- TextComposite,
-
- // Makes a temporary layer filled with white. When complete, the layer
- // will be forced to be opqaue (since Windows may have messed up the
- // alpha channel) and composited down. Any areas not drawn into will
- // remain white.
- //
- // This is the mode of last resort. If the opacity of the final image
- // is unknown and we can't do the text trick (since we know its color),
- // then we have to live with potential white halos. This is used for
- // form control drawing, for example.
- WhiteLayer,
- };
-
- enum TransformMode {
- // There are no changes to the transform. Use this when drawing
- // horizontal text. The current transform must not have rotation.
- KeepTransform,
-
- // Drawing happens in an Untransformed space, and then that bitmap is
- // transformed according to the current context when it is copied down.
- // Requires that a layer be created (layer mode is not NoLayer).
- Untransform,
-
- // When the current transform only has a scaling factor applied and
- // you're drawing form elements, use this parameter. This will unscale
- // the coordinate space, so the OS will just draw the form controls
- // larger or smaller depending on the destination size.
- ScaleTransform,
- };
-
- // You MUST call init() below.
- // |region| is expressed relative to the current transformation.
- TransparencyWin();
- ~TransparencyWin();
-
- // Initializes the members if you use the 0-argument constructor. Don't call
- // this if you use the multiple-argument constructor.
- void init(GraphicsContext* dest,
- LayerMode layerMode,
- TransformMode transformMode,
- const IntRect& region);
-
- // Combines the source and destination bitmaps using the given mode.
- // Calling this function before the destructor runs is mandatory in most
- // cases, and harmless otherwise. The mandatory cases are:
- // (m_layerMode != NoLayer) || (m_transformMode == ScaleTransform)
- void composite();
-
- // Returns the context for drawing into, which may be the destination
- // context, or a temporary one.
- GraphicsContext* context() const { return m_drawContext; }
-
- // When the mode is TextComposite, this sets the color that the text will
- // get. See the enum above for more.
- void setTextCompositeColor(Color color);
-
- // Returns the input bounds translated into the destination space. This is
- // not necessary for KeepTransform since the rectangle will be unchanged.
- const IntRect& drawRect() { return m_drawRect; }
-
-private:
- friend TransparencyWin_NoLayer_Test;
- friend TransparencyWin_WhiteLayer_Test;
- friend TransparencyWin_TextComposite_Test;
- friend TransparencyWin_OpaqueCompositeLayer_Test;
-
- class OwnedBuffers;
-
- void computeLayerSize();
-
- // Sets up a new layer, if any. setupLayer() will call the appopriate layer-
- // specific helper. Must be called after computeLayerSize();
- void setupLayer();
- void setupLayerForNoLayer();
- void setupLayerForOpaqueCompositeLayer();
- void setupLayerForTextComposite();
- void setupLayerForWhiteLayer();
-
- // Sets up the transformation on the newly created layer. setupTransform()
- // will call the appropriate transform-specific helper. Must be called after
- // setupLayer().
- void setupTransform(const IntRect& region);
- void setupTransformForKeepTransform(const IntRect& region);
- void setupTransformForUntransform();
- void setupTransformForScaleTransform();
-
- void initializeNewContext();
-
- void compositeOpaqueComposite();
- void compositeTextComposite();
-
- // Fixes the alpha channel to make the region inside m_transformedRect
- // opaque.
- void makeLayerOpaque();
-
- // The context our drawing will eventually end up in.
- GraphicsContext* m_destContext;
-
- // The original transform from the destination context.
- AffineTransform m_orgTransform;
-
- LayerMode m_layerMode;
- TransformMode m_transformMode;
-
- // The rectangle we're drawing in the destination's coordinate space
- IntRect m_sourceRect;
-
- // The source rectangle transformed into pixels in the final image. For
- // Untransform this has no meaning, since the destination might not be a
- // rectangle.
- IntRect m_transformedSourceRect;
-
- // The size of the layer we created. If there's no layer, this is the size
- // of the region we're using in the source.
- IntSize m_layerSize;
-
- // The rectangle we're drawing to in the draw context's coordinate space.
- // This will be the same as the source rectangle except for ScaleTransform
- // where we create a new virtual coordinate space for the layer.
- IntRect m_drawRect;
-
- // Points to the graphics context to draw text to, which will either be
- // the original context or the copy, depending on our mode.
- GraphicsContext* m_drawContext;
-
- // This flag is set when we call save() on the draw context during
- // initialization. It allows us to avoid doing an extra save()/restore()
- // when one is unnecessary.
- bool m_savedOnDrawContext;
-
- // Used only when m_mode = TextComposite, this is the color that the text
- // will end up being once we figure out the transparency.
- Color m_textCompositeColor;
-
- // Layer we're drawing to.
- ImageBuffer* m_layerBuffer;
-
- // When the layer type is OpaqueCompositeLayer, this will contain a copy
- // of the original contents of the m_layerBuffer before Windows drew on it.
- // It allows us to re-create what Windows did to the layer. It is an
- // SkBitmap instead of an ImageBuffer because an SkBitmap is lighter-weight
- // (ImageBuffers are also GDI surfaces, which we don't need here).
- SkBitmap* m_referenceBitmap;
-
- // If the given size of bitmap can be cached, they will be stored here. Both
- // the bitmap and the reference are guaranteed to be allocated if this
- // member is non-null.
- static OwnedBuffers* m_cachedBuffers;
-
- // If a buffer was too big to be cached, it will be created temporarily, and
- // this member tracks its scope to make sure it gets deleted. Always use
- // m_layerBuffer, which will either point to this object, or the statically
- // cached one. Don't access directly.
- OwnPtr<OwnedBuffers> m_ownedBuffers;
-
- // Sometimes we're asked to create layers that have negative dimensions.
- // This API is not designed to fail to initialize, so we hide the fact
- // that they are illegal and can't be rendered (failing silently, drawing
- // nothing).
- bool m_validLayer;
-};
-
-} // namespace WebCore
-
-#endif // TransaprencyWin_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/UniscribeHelper.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/UniscribeHelper.cpp
deleted file mode 100644
index 1794a02a62d..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/UniscribeHelper.cpp
+++ /dev/null
@@ -1,1070 +0,0 @@
-/*
- * Copyright (c) 2006, 2007, 2008, 2009, 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/chromium/UniscribeHelper.h"
-
-#include <windows.h>
-#include "core/platform/graphics/Font.h"
-#include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/graphics/chromium/FontUtilsChromiumWin.h"
-#include "core/platform/graphics/skia/SkiaFontWin.h"
-#include "core/platform/win/HWndDC.h"
-#include "third_party/skia/include/core/SkPoint.h"
-#include "wtf/Assertions.h"
-
-namespace WebCore {
-
-// The function types for ScriptItemizeOpenType() and ScriptShapeOpenType().
-// We want to use these functions for OpenType feature support, but we can't
-// call them directly because usp10.dll does not always have them.
-// Instead, we use GetProcAddress() to check whether we can actually use these
-// function. If we can't use these functions, we substitute ScriptItemze() and
-// ScriptShape().
-typedef HRESULT (WINAPI *ScriptItemizeOpenTypeFunc)(const WCHAR*, int, int,
- const SCRIPT_CONTROL*,
- const SCRIPT_STATE*,
- SCRIPT_ITEM*,
- OPENTYPE_TAG*, int*);
-typedef HRESULT (WINAPI *ScriptShapeOpenTypeFunc)(HDC, SCRIPT_CACHE*,
- SCRIPT_ANALYSIS*,
- OPENTYPE_TAG, OPENTYPE_TAG,
- int*, TEXTRANGE_PROPERTIES**,
- int, const WCHAR*, int, int,
- WORD*, SCRIPT_CHARPROP*,
- WORD*, SCRIPT_GLYPHPROP*,
- int*);
-
-static ScriptItemizeOpenTypeFunc gScriptItemizeOpenTypeFunc = 0;
-static ScriptShapeOpenTypeFunc gScriptShapeOpenTypeFunc = 0;
-static bool gOpenTypeFunctionsLoaded = false;
-
-static void loadOpenTypeFunctions()
-{
- HMODULE hModule = GetModuleHandle(L"usp10");
- if (hModule) {
- gScriptItemizeOpenTypeFunc = reinterpret_cast<ScriptItemizeOpenTypeFunc>(GetProcAddress(hModule, "ScriptItemizeOpenType"));
- gScriptShapeOpenTypeFunc = reinterpret_cast<ScriptShapeOpenTypeFunc>(GetProcAddress(hModule, "ScriptShapeOpenType"));
- }
- if (!gScriptItemizeOpenTypeFunc || !gScriptShapeOpenTypeFunc) {
- gScriptItemizeOpenTypeFunc = 0;
- gScriptShapeOpenTypeFunc = 0;
- }
- gOpenTypeFunctionsLoaded = true;
-}
-
-// HFONT is the 'incarnation' of 'everything' about font, but it's an opaque
-// handle and we can't directly query it to make a new HFONT sharing
-// its characteristics (height, style, etc) except for family name.
-// This function uses GetObject to convert HFONT back to LOGFONT,
-// resets the fields of LOGFONT and calculates style to use later
-// for the creation of a font identical to HFONT other than family name.
-static void setLogFontAndStyle(HFONT hfont, LOGFONT *logfont, int *style)
-{
- ASSERT(hfont && logfont);
- if (!hfont || !logfont)
- return;
-
- GetObject(hfont, sizeof(LOGFONT), logfont);
- // We reset these fields to values appropriate for CreateFontIndirect.
- // while keeping lfHeight, which is the most important value in creating
- // a new font similar to hfont.
- logfont->lfWidth = 0;
- logfont->lfEscapement = 0;
- logfont->lfOrientation = 0;
- logfont->lfCharSet = DEFAULT_CHARSET;
- logfont->lfOutPrecision = OUT_TT_ONLY_PRECIS;
- logfont->lfQuality = DEFAULT_QUALITY; // Honor user's desktop settings.
- logfont->lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
- if (style)
- *style = getStyleFromLogfont(logfont);
-}
-
-// This memory DC will NOT be released but it's OK
-// since we want to keep it for the whole life span of the process.
-HDC UniscribeHelper::m_cachedDC = 0;
-
-static bool canUseGlyphIndex(const SCRIPT_ITEM& run)
-{
- // On early version of Uniscribe, ScriptShape() sets run.a.fNoGlyphIndex
- // to TRUE when it can't shape the run with glyph indexes. This could
- // occur when we use CFF webfonts(See http://crbug.com/39017).
- // We don't use the font in that case and try to use fallback fonts.
- return !run.a.fNoGlyphIndex;
-}
-
-UniscribeHelper::UniscribeHelper(const UChar* input,
- int inputLength,
- bool isRtl,
- HFONT hfont,
- SCRIPT_CACHE* scriptCache,
- SCRIPT_FONTPROPERTIES* fontProperties,
- WORD spaceGlyph)
- : m_input(input)
- , m_inputLength(inputLength)
- , m_isRtl(isRtl)
- , m_hfont(hfont)
- , m_scriptCache(scriptCache)
- , m_fontProperties(fontProperties)
- , m_spaceGlyph(spaceGlyph)
- , m_directionalOverride(false)
- , m_inhibitLigate(false)
- , m_letterSpacing(0)
- , m_spaceWidth(0)
- , m_wordSpacing(0)
- , m_ascent(0)
- , m_disableFontFallback(false)
-
-{
- m_logfont.lfFaceName[0] = 0;
- if (!gOpenTypeFunctionsLoaded)
- loadOpenTypeFunctions();
-}
-
-UniscribeHelper::~UniscribeHelper()
-{
-}
-
-void UniscribeHelper::initWithOptionalLengthProtection(bool lengthProtection)
-{
- // We cap the input length and just don't do anything. We'll allocate a lot
- // of things of the size of the number of characters, so the allocated
- // memory will be several times the input length. Plus shaping such a large
- // buffer may be a form of denial of service. No legitimate text should be
- // this long. It also appears that Uniscribe flatly rejects very long
- // strings, so we don't lose anything by doing this.
- //
- // The input length protection may be disabled by the unit tests to cause
- // an error condition.
- static const int kMaxInputLength = 65535;
- if (m_inputLength == 0 || (lengthProtection && m_inputLength > kMaxInputLength))
- return;
-
- fillRuns();
- fillShapes();
- fillScreenOrder();
-}
-
-int UniscribeHelper::width() const
-{
- int width = 0;
- for (int itemIndex = 0; itemIndex < static_cast<int>(m_runs.size()); itemIndex++)
- width += advanceForItem(itemIndex);
- return width;
-}
-
-void UniscribeHelper::justify(int additionalSpace)
-{
- // Count the total number of glyphs we have so we know how big to make the
- // buffers below.
- int totalGlyphs = 0;
- for (size_t run = 0; run < m_runs.size(); run++) {
- int runIndex = m_screenOrder[run];
- totalGlyphs += static_cast<int>(m_shapes[runIndex].glyphLength());
- }
- if (totalGlyphs == 0)
- return; // Nothing to do.
-
- // We make one big buffer in screen order of all the glyphs we are drawing
- // across runs so that the justification function will adjust evenly across
- // all glyphs.
- Vector<SCRIPT_VISATTR, 64> visualAttributes;
- visualAttributes.resize(totalGlyphs);
- Vector<int, 64> advances;
- advances.resize(totalGlyphs);
- Vector<int, 64> justify;
- justify.resize(totalGlyphs);
-
- // Build the packed input.
- int destIndex = 0;
- for (size_t run = 0; run < m_runs.size(); run++) {
- int runIndex = m_screenOrder[run];
- const Shaping& shaping = m_shapes[runIndex];
-
- for (int i = 0; i < shaping.glyphLength(); i++, destIndex++) {
- memcpy(&visualAttributes[destIndex], &shaping.m_visualAttributes[i],
- sizeof(SCRIPT_VISATTR));
- advances[destIndex] = shaping.m_advance[i];
- }
- }
-
- // The documentation for Scriptjustify is wrong, the parameter is the space
- // to add and not the width of the column you want.
- int minKashida;
- // Disable kashida justification based on
- // http://blogs.msdn.com/b/michkap/archive/2010/08/31/10056140.aspx.
- for (int i = 0; i < totalGlyphs; ++i) {
- if (visualAttributes[i].uJustification == SCRIPT_JUSTIFY_ARABIC_KASHIDA)
- visualAttributes[i].uJustification = SCRIPT_JUSTIFY_NONE;
- }
- minKashida = 0;
- ScriptJustify(&visualAttributes[0], &advances[0], totalGlyphs,
- additionalSpace, minKashida, &justify[0]);
-
- // Now we have to unpack the justification amounts back into the runs so
- // the glyph indices match.
- int globalGlyphIndex = 0;
- for (size_t run = 0; run < m_runs.size(); run++) {
- int runIndex = m_screenOrder[run];
- Shaping& shaping = m_shapes[runIndex];
-
- shaping.m_justify.resize(shaping.glyphLength());
- for (int i = 0; i < shaping.glyphLength(); i++, globalGlyphIndex++)
- shaping.m_justify[i] = justify[globalGlyphIndex];
- }
-}
-
-int UniscribeHelper::characterToX(int offset) const
-{
- HRESULT hr;
- ASSERT(offset <= m_inputLength);
-
- // Our algorithm is to traverse the items in screen order from left to
- // right, adding in each item's screen width until we find the item with
- // the requested character in it.
- int width = 0;
- for (size_t screenIndex = 0; screenIndex < m_runs.size(); screenIndex++) {
- // Compute the length of this run.
- int itemIndex = m_screenOrder[screenIndex];
- const SCRIPT_ITEM& item = m_runs[itemIndex];
- const Shaping& shaping = m_shapes[itemIndex];
- int itemLength = shaping.charLength();
-
- if (offset >= item.iCharPos && offset <= item.iCharPos + itemLength) {
- // Character offset is in this run.
- int charLength = offset - item.iCharPos;
-
- int curX = 0;
- hr = ScriptCPtoX(charLength, FALSE, itemLength,
- shaping.glyphLength(),
- &shaping.m_logs[0], &shaping.m_visualAttributes[0],
- shaping.effectiveAdvances(), &item.a, &curX);
- if (FAILED(hr))
- return 0;
-
- width += curX + shaping.m_prePadding;
- ASSERT(width >= 0);
- return width;
- }
-
- // Move to the next item.
- width += advanceForItem(itemIndex);
- }
- ASSERT(width >= 0);
- return width;
-}
-
-int UniscribeHelper::xToCharacter(int x) const
-{
- // We iterate in screen order until we find the item with the given pixel
- // position in it. When we find that guy, we ask Uniscribe for the
- // character index.
- HRESULT hr;
- for (size_t screenIndex = 0; screenIndex < m_runs.size(); screenIndex++) {
- int itemIndex = m_screenOrder[screenIndex];
- int itemAdvance = advanceForItem(itemIndex);
-
- // Note that the run may be empty if shaping failed, so we want to skip
- // over it.
- const Shaping& shaping = m_shapes[itemIndex];
- int itemLength = shaping.charLength();
- if (x <= itemAdvance && itemLength > 0) {
- // The requested offset is within this item.
- const SCRIPT_ITEM& item = m_runs[itemIndex];
-
- // Account for the leading space we've added to this run that
- // Uniscribe doesn't know about.
- x -= shaping.m_prePadding;
-
- int charX = 0;
- int trailing;
- hr = ScriptXtoCP(x, itemLength, shaping.glyphLength(),
- &shaping.m_logs[0], &shaping.m_visualAttributes[0],
- shaping.effectiveAdvances(), &item.a, &charX,
- &trailing);
-
- // The character offset is within the item. We need to add the
- // item's offset to transform it into the space of the TextRun
- return charX + item.iCharPos;
- }
-
- // The offset is beyond this item, account for its length and move on.
- x -= itemAdvance;
- }
-
- // Error condition, we don't know what to do if we don't have that X
- // position in any of our items.
- return 0;
-}
-
-void UniscribeHelper::draw(GraphicsContext* graphicsContext, HDC dc,
- int x, int y,
- const FloatRect& textRect,
- int from, int to)
-{
- HGDIOBJ oldFont = 0;
- int curX = x;
- bool firstRun = true;
-
- for (size_t screenIndex = 0; screenIndex < m_runs.size(); screenIndex++) {
- int itemIndex = m_screenOrder[screenIndex];
- const SCRIPT_ITEM& item = m_runs[itemIndex];
- const Shaping& shaping = m_shapes[itemIndex];
-
- // Character offsets within this run. THESE MAY NOT BE IN RANGE and may
- // be negative, etc. The code below handles this.
- int fromChar = from - item.iCharPos;
- int toChar = to - item.iCharPos;
-
- // See if we need to draw any characters in this item.
- if (shaping.charLength() == 0 ||
- fromChar >= shaping.charLength() || toChar <= 0) {
- // No chars in this item to display.
- curX += advanceForItem(itemIndex);
- continue;
- }
-
- // Compute the starting glyph within this span. |from| and |to| are
- // global offsets that may intersect arbitrarily with our local run.
- int fromGlyph, afterGlyph;
- if (item.a.fRTL) {
- // To compute the first glyph when going RTL, we use |to|.
- if (toChar >= shaping.charLength())
- // The end of the text is after (to the left) of us.
- fromGlyph = 0;
- else {
- // Since |to| is exclusive, the first character we draw on the
- // left is actually the one right before (to the right) of
- // |to|.
- fromGlyph = shaping.m_logs[toChar - 1];
- }
-
- // The last glyph is actually the first character in the range.
- if (fromChar <= 0) {
- // The first character to draw is before (to the right) of this
- // span, so draw all the way to the end.
- afterGlyph = shaping.glyphLength();
- } else {
- // We want to draw everything up until the character to the
- // right of |from|. To the right is - 1, so we look that up
- // (remember our character could be more than one glyph, so we
- // can't look up our glyph and add one).
- afterGlyph = shaping.m_logs[fromChar - 1];
- }
- } else {
- // Easy case, everybody agrees about directions. We only need to
- // handle boundary conditions to get a range inclusive at the
- // beginning, and exclusive at the ending. We have to do some
- // computation to see the glyph one past the end.
- fromGlyph = shaping.m_logs[fromChar < 0 ? 0 : fromChar];
- if (toChar >= shaping.charLength())
- afterGlyph = shaping.glyphLength();
- else
- afterGlyph = shaping.m_logs[toChar];
- }
-
- // Account for the characters that were skipped in this run. When
- // WebKit asks us to draw a subset of the run, it actually tells us
- // to draw at the X offset of the beginning of the run, since it
- // doesn't know the internal position of any of our characters.
- const int* effectiveAdvances = shaping.effectiveAdvances();
- int innerOffset = 0;
- for (int i = 0; i < fromGlyph; i++)
- innerOffset += effectiveAdvances[i];
-
- // Actually draw the glyphs we found.
- int glyphCount = afterGlyph - fromGlyph;
- if (fromGlyph >= 0 && glyphCount > 0) {
- // Account for the preceding space we need to add to this run. We
- // don't need to count for the following space because that will be
- // counted in advanceForItem below when we move to the next run.
- innerOffset += shaping.m_prePadding;
-
- // Pass 0 in when there is no justification.
- const int* justify = shaping.m_justify.size() == 0 ? 0 : &shaping.m_justify[fromGlyph];
-
- const int* advances = shaping.m_justify.size() ?
- &shaping.m_justify[fromGlyph]
- : &shaping.m_advance[fromGlyph];
-
- // Fonts with different ascents can be used to render different
- // runs. 'Across-runs' y-coordinate correction needs to be
- // adjusted for each font.
- bool textOutOk = false;
- for (int executions = 0; executions < 2; ++executions) {
- SkPoint origin;
- origin.fX = curX + + innerOffset;
- origin.fY = y + m_ascent;
- paintSkiaText(graphicsContext,
- shaping.m_hfont,
- glyphCount,
- &shaping.m_glyphs[fromGlyph],
- advances,
- &shaping.m_offsets[fromGlyph],
- origin,
- textRect);
- textOutOk = true;
-
- if (!textOutOk && 0 == executions) {
- // If TextOut is called from the renderer it might fail
- // because the sandbox is preventing it from opening the
- // font files. If we are running in the renderer,
- // TryToPreloadFont is overridden to ask the browser to
- // preload the font for us so we can access it.
- tryToPreloadFont(shaping.m_hfont);
- continue;
- }
- break;
- }
- }
-
- curX += advanceForItem(itemIndex);
- }
-
- if (oldFont)
- SelectObject(dc, oldFont);
-}
-
-WORD UniscribeHelper::firstGlyphForCharacter(int charOffset) const
-{
- // Find the run for the given character.
- for (int i = 0; i < static_cast<int>(m_runs.size()); i++) {
- int firstChar = m_runs[i].iCharPos;
- const Shaping& shaping = m_shapes[i];
- int localOffset = charOffset - firstChar;
- if (localOffset >= 0 && localOffset < shaping.charLength()) {
- // The character is in this run, return the first glyph for it
- // (should generally be the only glyph). It seems Uniscribe gives
- // glyph 0 for empty, which is what we want to return in the
- // "missing" case.
- size_t glyphIndex = shaping.m_logs[localOffset];
- if (glyphIndex >= shaping.m_glyphs.size()) {
- // The glyph should be in this run, but the run has too few
- // actual characters. This can happen when shaping the run
- // fails, in which case, we should have no data in the logs at
- // all.
- ASSERT(shaping.m_glyphs.size() == 0);
- return 0;
- }
- return shaping.m_glyphs[glyphIndex];
- }
- }
-
- return 0;
-}
-
-void UniscribeHelper::fillRuns()
-{
- HRESULT hr;
- m_runs.resize(cUniscribeHelperStackRuns);
- m_scriptTags.resize(cUniscribeHelperStackRuns);
-
- SCRIPT_STATE inputState;
- inputState.uBidiLevel = m_isRtl;
- inputState.fOverrideDirection = m_directionalOverride;
- inputState.fInhibitSymSwap = false;
- inputState.fCharShape = false; // Not implemented in Uniscribe
- inputState.fDigitSubstitute = false; // Do we want this for Arabic?
- inputState.fInhibitLigate = m_inhibitLigate;
- inputState.fDisplayZWG = false; // Don't draw control characters.
- inputState.fArabicNumContext = m_isRtl; // Do we want this for Arabic?
- inputState.fGcpClusters = false;
- inputState.fReserved = 0;
- inputState.fEngineReserved = 0;
- // The psControl argument to ScriptItemize should be non-0 for RTL text,
- // per http://msdn.microsoft.com/en-us/library/ms776532.aspx . So use a
- // SCRIPT_CONTROL that is set to all zeros. Zero as a locale ID means the
- // neutral locale per http://msdn.microsoft.com/en-us/library/ms776294.aspx
- static SCRIPT_CONTROL inputControl = {0, // uDefaultLanguage :16;
- 0, // fContextDigits :1;
- 0, // fInvertPreBoundDir :1;
- 0, // fInvertPostBoundDir :1;
- 0, // fLinkStringBefore :1;
- 0, // fLinkStringAfter :1;
- 0, // fNeutralOverride :1;
- 0, // fNumericOverride :1;
- 0, // fLegacyBidiClass :1;
- 0, // fMergeNeutralItems :1;
- 0};// fReserved :7;
- // Calling ScriptApplyDigitSubstitution( 0, &inputControl, &inputState)
- // here would be appropriate if we wanted to set the language ID, and get
- // local digit substitution behavior. For now, don't do it.
-
- while (true) {
- int numberOfItems = 0;
-
- // Ideally, we would have a way to know the runs before and after this
- // one, and put them into the control parameter of ScriptItemize. This
- // would allow us to shape characters properly that cross style
- // boundaries (WebKit bug 6148).
- //
- // We tell ScriptItemize that the output list of items is one smaller
- // than it actually is. According to Mozilla bug 366643, if there is
- // not enough room in the array on pre-SP2 systems, ScriptItemize will
- // write one past the end of the buffer.
- //
- // ScriptItemize is very strange. It will often require a much larger
- // ITEM buffer internally than it will give us as output. For example,
- // it will say a 16-item buffer is not big enough, and will write
- // interesting numbers into all those items. But when we give it a 32
- // item buffer and it succeeds, it only has one item output.
- //
- // It seems to be doing at least two passes, the first where it puts a
- // lot of intermediate data into our items, and the second where it
- // collates them.
- if (gScriptItemizeOpenTypeFunc) {
- hr = gScriptItemizeOpenTypeFunc(m_input, m_inputLength,
- static_cast<int>(m_runs.size()) - 1,
- &inputControl, &inputState,
- &m_runs[0], &m_scriptTags[0],
- &numberOfItems);
-
- if (SUCCEEDED(hr)) {
- // Pack consecutive runs, the script tag of which are
- // SCRIPT_TAG_UNKNOWN, to reduce the number of runs.
- for (int i = 0; i < numberOfItems; ++i) {
- // Do not pack with whitespace characters at the head.
- // Otherwise whole the run is rendered as a whitespace.
- WCHAR ch = m_input[m_runs[i].iCharPos];
- if (m_scriptTags[i] == SCRIPT_TAG_UNKNOWN && !Font::treatAsSpace(ch) && !Font::treatAsZeroWidthSpace(ch)) {
- int j = 1;
- while (i + j < numberOfItems && m_scriptTags[i + j] == SCRIPT_TAG_UNKNOWN)
- ++j;
- if (--j) {
- m_runs.remove(i + 1, j);
- m_scriptTags.remove(i + 1, j);
- numberOfItems -= j;
- }
- }
- }
- m_scriptTags.resize(numberOfItems);
- }
- } else {
- hr = ScriptItemize(m_input, m_inputLength,
- static_cast<int>(m_runs.size()) - 1,
- &inputControl, &inputState, &m_runs[0],
- &numberOfItems);
- }
- if (SUCCEEDED(hr)) {
- m_runs.resize(numberOfItems);
- break;
- }
- if (hr != E_OUTOFMEMORY) {
- // Some kind of unexpected error.
- m_runs.resize(0);
- break;
- }
- // There was not enough items for it to write into, expand.
- m_runs.resize(m_runs.size() * 2);
- m_scriptTags.resize(m_runs.size());
- }
-}
-
-bool UniscribeHelper::shape(const UChar* input,
- int itemLength,
- int numGlyphs,
- SCRIPT_ITEM& run,
- OPENTYPE_TAG scriptTag,
- Shaping& shaping)
-{
- HFONT hfont = m_hfont;
- SCRIPT_CACHE* scriptCache = m_scriptCache;
- SCRIPT_FONTPROPERTIES* fontProperties = m_fontProperties;
- Vector<SCRIPT_CHARPROP, cUniscribeHelperStackChars> charProps;
- Vector<SCRIPT_GLYPHPROP, cUniscribeHelperStackChars> glyphProps;
- int ascent = m_ascent;
- WORD spaceGlyph = m_spaceGlyph;
- HRESULT hr;
- // When used to fill up glyph pages for simple scripts in non-BMP,
- // we don't want any font fallback in this class. The simple script
- // font path can take care of font fallback.
- bool lastFallbackTried = m_disableFontFallback;
- bool result;
-
- int generatedGlyphs = 0;
-
- // In case HFONT passed in ctor cannot render this run, we have to scan
- // other fonts from the beginning of the font list.
- resetFontIndex();
-
- // Compute shapes.
- while (true) {
- shaping.m_logs.resize(itemLength);
- shaping.m_glyphs.resize(numGlyphs);
- shaping.m_visualAttributes.resize(numGlyphs);
- charProps.resize(itemLength);
- glyphProps.resize(numGlyphs);
- run.a.fNoGlyphIndex = FALSE;
-
-#ifdef PURIFY
- // http://code.google.com/p/chromium/issues/detail?id=5309
- // Purify isn't able to track the assignments that ScriptShape makes to
- // shaping.m_glyphs. Consequently, any bytes with value 0xCD that it
- // writes, will be considered un-initialized data.
- //
- // This hack avoid the false-positive UMRs by marking the buffer as
- // initialized.
- //
- // FIXME: A better solution would be to use Purify's API and mark only
- // the populated range as initialized:
- //
- // PurifyMarkAsInitialized(
- // &shaping.m_glyphs[0],
- // sizeof(shaping.m_glyphs[0] * generatedGlyphs);
-
- ZeroMemory(&shaping.m_glyphs[0],
- sizeof(shaping.m_glyphs[0]) * shaping.m_glyphs.size());
-#endif
- // If our DC is already created, select the font in it so we can use it now.
- // Otherwise, we'll create it as needed afterward...
- if (m_cachedDC)
- SelectObject(m_cachedDC, hfont);
-
- // Firefox sets SCRIPT_ANALYSIS.SCRIPT_STATE.fDisplayZWG to true
- // here. Is that what we want? It will display control characters.
- if (gScriptShapeOpenTypeFunc) {
- TEXTRANGE_PROPERTIES* rangeProps = m_featureRecords.size() ? &m_rangeProperties : 0;
- hr = gScriptShapeOpenTypeFunc(m_cachedDC, scriptCache, &run.a,
- scriptTag, 0, &itemLength,
- &rangeProps, rangeProps ? 1 : 0,
- input, itemLength, numGlyphs,
- &shaping.m_logs[0], &charProps[0],
- &shaping.m_glyphs[0], &glyphProps[0],
- &generatedGlyphs);
- if (SUCCEEDED(hr)) {
- // If we use ScriptShapeOpenType(), visual attributes
- // information for each characters are stored in
- // |glyphProps[i].sva|.
- for (int i = 0; i < generatedGlyphs; ++i)
- memcpy(&shaping.m_visualAttributes[i], &glyphProps[i].sva, sizeof(SCRIPT_VISATTR));
- }
- } else {
- hr = ScriptShape(m_cachedDC, scriptCache, input, itemLength,
- numGlyphs, &run.a,
- &shaping.m_glyphs[0], &shaping.m_logs[0],
- &shaping.m_visualAttributes[0], &generatedGlyphs);
- }
- // We receive E_PENDING when we need to try again with a Drawing Context,
- // but we don't want to retry again if we already tried with non-zero DC.
- if (hr == E_PENDING && !m_cachedDC) {
- EnsureCachedDCCreated();
- continue;
- }
- if (hr == E_OUTOFMEMORY) {
- numGlyphs *= 2;
- continue;
- }
- if (SUCCEEDED(hr) && (lastFallbackTried || !containsMissingGlyphs(shaping, run, fontProperties) && canUseGlyphIndex(run)))
- break;
-
- // The current font can't render this run, try next font.
- if (!m_disableFontFallback &&
- nextWinFontData(hfont, scriptCache, fontProperties, ascent, spaceGlyph)) {
- // The primary font does not support this run. Try next font.
- // In case of web page rendering, they come from fonts specified in
- // CSS stylesheets.
- continue;
- } else if (!lastFallbackTried) {
- lastFallbackTried = true;
-
- // Generate a last fallback font based on the script of
- // a character to draw while inheriting size and styles
- // from the primary font
- if (!m_logfont.lfFaceName[0])
- setLogFontAndStyle(m_hfont, &m_logfont, &m_style);
-
- // TODO(jungshik): generic type should come from webkit for
- // UniscribeHelperTextRun (a derived class used in webkit).
- const UChar *family = getFallbackFamily(input, itemLength,
- FontDescription::StandardFamily, 0, 0);
- bool fontOk = getDerivedFontData(family, m_style, &m_logfont,
- &ascent, &hfont, &scriptCache,
- &spaceGlyph);
-
-
- if (!fontOk) {
- // If this GetDerivedFontData is called from the renderer it
- // might fail because the sandbox is preventing it from opening
- // the font files. If we are running in the renderer,
- // TryToPreloadFont is overridden to ask the browser to preload
- // the font for us so we can access it.
- tryToPreloadFont(hfont);
-
- // Try again.
- fontOk = getDerivedFontData(family, m_style, &m_logfont,
- &ascent, &hfont, &scriptCache,
- &spaceGlyph);
- ASSERT(fontOk);
- }
-
- // TODO(jungshik) : Currently GetDerivedHFont always returns a
- // a valid HFONT, but in the future, I may change it to return 0.
- ASSERT(hfont);
-
- // We don't need a font_properties for the last resort fallback font
- // because we don't have anything more to try and are forced to
- // accept empty glyph boxes. If we tried a series of fonts as
- // 'last-resort fallback', we'd need it, but currently, we don't.
- continue;
- } else if (hr == USP_E_SCRIPT_NOT_IN_FONT) {
- run.a.eScript = SCRIPT_UNDEFINED;
- continue;
- } else if (FAILED(hr)) {
- // Error shaping.
- generatedGlyphs = 0;
- result = false;
- goto cleanup;
- }
- }
-
- // Sets Windows font data for this run to those corresponding to
- // a font supporting this run. we don't need to store font_properties
- // because it's not used elsewhere.
- shaping.m_hfont = hfont;
- shaping.m_scriptCache = scriptCache;
- shaping.m_spaceGlyph = spaceGlyph;
-
- // The ascent of a font for this run can be different from
- // that of the primary font so that we need to keep track of
- // the difference per run and take that into account when calling
- // ScriptTextOut in |draw|. Otherwise, different runs rendered by
- // different fonts would not be aligned vertically.
- shaping.m_ascentOffset = m_ascent ? ascent - m_ascent : 0;
- result = true;
-
- cleanup:
- shaping.m_glyphs.resize(generatedGlyphs);
- shaping.m_visualAttributes.resize(generatedGlyphs);
- shaping.m_advance.resize(generatedGlyphs);
- shaping.m_offsets.resize(generatedGlyphs);
-
- // On failure, our logs don't mean anything, so zero those out.
- if (!result)
- shaping.m_logs.clear();
-
- return result;
-}
-
-void UniscribeHelper::EnsureCachedDCCreated()
-{
- if (m_cachedDC)
- return;
- // Allocate a memory DC that is compatible with the Desktop DC since we don't have any window,
- // and we don't want to use the Desktop DC directly since it can have nasty side effects
- // as identified in Chrome Issue http://crbug.com/59315.
- HWndDC screenDC(0);
- m_cachedDC = ::CreateCompatibleDC(screenDC);
- ASSERT(m_cachedDC);
-}
-
-void UniscribeHelper::fillShapes()
-{
- m_shapes.resize(m_runs.size());
- for (size_t i = 0; i < m_runs.size(); i++) {
- int startItem = m_runs[i].iCharPos;
- int itemLength = m_inputLength - startItem;
- if (i < m_runs.size() - 1)
- itemLength = m_runs[i + 1].iCharPos - startItem;
-
- int numGlyphs;
- if (itemLength < cUniscribeHelperStackChars) {
- // We'll start our buffer sizes with the current stack space
- // available in our buffers if the current input fits. As long as
- // it doesn't expand past that we'll save a lot of time mallocing.
- numGlyphs = cUniscribeHelperStackChars;
- } else {
- // When the input doesn't fit, give up with the stack since it will
- // almost surely not be enough room (unless the input actually
- // shrinks, which is unlikely) and just start with the length
- // recommended by the Uniscribe documentation as a "usually fits"
- // size.
- numGlyphs = itemLength * 3 / 2 + 16;
- }
-
- // Convert a string to a glyph string trying the primary font, fonts in
- // the fallback list and then script-specific last resort font.
- Shaping& shaping = m_shapes[i];
- if (!shape(&m_input[startItem], itemLength, numGlyphs, m_runs[i], m_scriptTags[i], shaping))
- continue;
-
- // At the moment, the only time m_disableFontFallback is set is
- // when we look up glyph indices for non-BMP code ranges. So,
- // we can skip the glyph placement. When that becomes not the case
- // any more, we have to add a new flag to control glyph placement.
- if (m_disableFontFallback)
- continue;
-
- // Compute placements. Note that offsets is documented incorrectly
- // and is actually an array.
- EnsureCachedDCCreated();
- SelectObject(m_cachedDC, shaping.m_hfont);
- shaping.m_prePadding = 0;
- if (FAILED(ScriptPlace(m_cachedDC, shaping.m_scriptCache,
- &shaping.m_glyphs[0],
- static_cast<int>(shaping.m_glyphs.size()),
- &shaping.m_visualAttributes[0], &m_runs[i].a,
- &shaping.m_advance[0], &shaping.m_offsets[0],
- &shaping.m_abc))) {
- // Some error we don't know how to handle. Nuke all of our data
- // since we can't deal with partially valid data later.
- m_runs.clear();
- m_scriptTags.clear();
- m_shapes.clear();
- m_screenOrder.clear();
- }
- }
-
- adjustSpaceAdvances();
-
- if (m_letterSpacing != 0 || m_wordSpacing != 0)
- applySpacing();
-}
-
-void UniscribeHelper::fillScreenOrder()
-{
- m_screenOrder.resize(m_runs.size());
-
- // We assume that the input has only one text direction in it.
- // TODO(brettw) are we sure we want to keep this restriction?
- if (m_isRtl) {
- for (int i = 0; i < static_cast<int>(m_screenOrder.size()); i++)
- m_screenOrder[static_cast<int>(m_screenOrder.size()) - i - 1] = i;
- } else {
- for (int i = 0; i < static_cast<int>(m_screenOrder.size()); i++)
- m_screenOrder[i] = i;
- }
-}
-
-void UniscribeHelper::adjustSpaceAdvances()
-{
- if (m_spaceWidth == 0)
- return;
-
- int spaceWidthWithoutLetterSpacing = m_spaceWidth - m_letterSpacing;
-
- // This mostly matches what WebKit's UniscribeController::shapeAndPlaceItem.
- for (size_t run = 0; run < m_runs.size(); run++) {
- Shaping& shaping = m_shapes[run];
-
- // FIXME: This loop is not UTF-16-safe. Unicode 6.0 has a couple
- // of complex script blocks in Plane 1.
- for (int i = 0; i < shaping.charLength(); i++) {
- UChar c = m_input[m_runs[run].iCharPos + i];
- bool treatAsSpace = Font::treatAsSpace(c);
- if (!treatAsSpace && !Font::treatAsZeroWidthSpaceInComplexScript(c))
- continue;
-
- int glyphIndex = shaping.m_logs[i];
- int currentAdvance = shaping.m_advance[glyphIndex];
-
- shaping.m_glyphs[glyphIndex] = shaping.m_spaceGlyph;
-
- if (treatAsSpace) {
- // currentAdvance does not include additional letter-spacing,
- // but m_spaceWidth does. Here we find out how off we are from
- // the correct width (spaceWidthWithoutLetterSpacing) and
- // just subtract that diff.
- int diff = currentAdvance - spaceWidthWithoutLetterSpacing;
- // The shaping can consist of a run of text, so only subtract
- // the difference in the width of the glyph.
- shaping.m_advance[glyphIndex] -= diff;
- shaping.m_abc.abcB -= diff;
- continue;
- }
-
- // For characters treated as zero-width space in complex
- // scripts, set the advance width to zero, adjust
- // |abcB| of the current run accordingly and set
- // the glyph to m_spaceGlyph (invisible).
- shaping.m_advance[glyphIndex] = 0;
- shaping.m_abc.abcB -= currentAdvance;
- shaping.m_offsets[glyphIndex].du = 0;
- shaping.m_offsets[glyphIndex].dv = 0;
- }
- }
-}
-
-void UniscribeHelper::applySpacing()
-{
- for (size_t run = 0; run < m_runs.size(); run++) {
- Shaping& shaping = m_shapes[run];
- bool isRtl = m_runs[run].a.fRTL;
-
- if (m_letterSpacing != 0) {
- // RTL text gets padded to the left of each character. We increment
- // the run's advance to make this happen. This will be balanced out
- // by NOT adding additional advance to the last glyph in the run.
- if (isRtl)
- shaping.m_prePadding += m_letterSpacing;
-
- // Go through all the glyphs in this run and increase the "advance"
- // to account for letter spacing. We adjust letter spacing only on
- // cluster boundaries.
- //
- // This works for most scripts, but may have problems with some
- // indic scripts. This behavior is better than Firefox or IE for
- // Hebrew.
- for (int i = 0; i < shaping.glyphLength(); i++) {
- if (shaping.m_visualAttributes[i].fClusterStart) {
- // Ick, we need to assign the extra space so that the glyph
- // comes first, then is followed by the space. This is
- // opposite for RTL.
- if (isRtl) {
- if (i != shaping.glyphLength() - 1) {
- // All but the last character just get the spacing
- // applied to their advance. The last character
- // doesn't get anything,
- shaping.m_advance[i] += m_letterSpacing;
- shaping.m_abc.abcB += m_letterSpacing;
- }
- } else {
- // LTR case is easier, we just add to the advance.
- shaping.m_advance[i] += m_letterSpacing;
- shaping.m_abc.abcB += m_letterSpacing;
- }
- }
- }
- }
-
- // Go through all the characters to find whitespace and insert the
- // extra wordspacing amount for the glyphs they correspond to.
- if (m_wordSpacing != 0) {
- for (int i = 0; i < shaping.charLength(); i++) {
- if (!Font::treatAsSpace(m_input[m_runs[run].iCharPos + i]))
- continue;
-
- // The char in question is a word separator...
- int glyphIndex = shaping.m_logs[i];
-
- // Spaces will not have a glyph in Uniscribe, it will just add
- // additional advance to the character to the left of the
- // space. The space's corresponding glyph will be the character
- // following it in reading order.
- if (isRtl) {
- // In RTL, the glyph to the left of the space is the same
- // as the first glyph of the following character, so we can
- // just increment it.
- shaping.m_advance[glyphIndex] += m_wordSpacing;
- shaping.m_abc.abcB += m_wordSpacing;
- } else {
- // LTR is actually more complex here, we apply it to the
- // previous character if there is one, otherwise we have to
- // apply it to the leading space of the run.
- if (glyphIndex == 0)
- shaping.m_prePadding += m_wordSpacing;
- else {
- shaping.m_advance[glyphIndex - 1] += m_wordSpacing;
- shaping.m_abc.abcB += m_wordSpacing;
- }
- }
- }
- } // m_wordSpacing != 0
-
- // Loop for next run...
- }
-}
-
-// The advance is the ABC width of the run
-int UniscribeHelper::advanceForItem(int itemIndex) const
-{
- int accum = 0;
- const Shaping& shaping = m_shapes[itemIndex];
-
- if (shaping.m_justify.size() == 0) {
- // Easy case with no justification, the width is just the ABC width of
- // the run. (The ABC width is the sum of the advances).
- return shaping.m_abc.abcA + shaping.m_abc.abcB +
- shaping.m_abc.abcC + shaping.m_prePadding;
- }
-
- // With justification, we use the justified amounts instead. The
- // justification array contains both the advance and the extra space
- // added for justification, so is the width we want.
- int justification = 0;
- for (size_t i = 0; i < shaping.m_justify.size(); i++)
- justification += shaping.m_justify[i];
-
- return shaping.m_prePadding + justification;
-}
-
-// SCRIPT_FONTPROPERTIES contains glyph indices for default, invalid
-// and blank glyphs. Just because ScriptShape succeeds does not mean
-// that a text run is rendered correctly. Some characters may be rendered
-// with default/invalid/blank glyphs. Therefore, we need to check if the glyph
-// array returned by ScriptShape contains any of those glyphs to make
-// sure that the text run is rendered successfully.
-// However, we should not subject zero-width characters to this test.
-
-bool UniscribeHelper::containsMissingGlyphs(const Shaping& shaping,
- const SCRIPT_ITEM& run,
- const SCRIPT_FONTPROPERTIES* properties) const
-{
- for (int i = 0; i < shaping.charLength(); i++) {
- UChar c = m_input[run.iCharPos + i];
- // Skip zero-width space characters because they're not considered to
- // be missing in a font.
- if (Font::treatAsZeroWidthSpaceInComplexScript(c))
- continue;
- int glyphIndex = shaping.m_logs[i];
- WORD glyph = shaping.m_glyphs[glyphIndex];
- // Note on the thrid condition: Windows Vista sometimes returns glyphs
- // equal to wgBlank (instead of wgDefault), with fZeroWidth set. Treat
- // such cases as having missing glyphs if the corresponding character
- // is not a zero width whitespace.
- if (glyph == properties->wgDefault
- || (glyph == properties->wgInvalid && glyph != properties->wgBlank)
- || (glyph == properties->wgBlank && shaping.m_visualAttributes[glyphIndex].fZeroWidth && !Font::treatAsZeroWidthSpace(c)))
- return true;
- }
- return false;
-}
-
-static OPENTYPE_TAG convertFeatureTag(const String& tag)
-{
- return ((tag[0] & 0xFF) | ((tag[1] & 0xFF) << 8) | ((tag[2] & 0xFF) << 16) | ((tag[3] & 0xFF) << 24));
-}
-
-void UniscribeHelper::setRangeProperties(const FontFeatureSettings* featureSettings)
-{
- if (!featureSettings || !featureSettings->size()) {
- m_featureRecords.resize(0);
- return;
- }
-
- m_featureRecords.resize(featureSettings->size());
- for (unsigned i = 0; i < featureSettings->size(); ++i) {
- m_featureRecords[i].lParameter = featureSettings->at(i).value();
- m_featureRecords[i].tagFeature = convertFeatureTag(featureSettings->at(i).tag());
- }
- m_rangeProperties.potfRecords = &m_featureRecords[0];
- m_rangeProperties.cotfRecords = m_featureRecords.size();
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/UniscribeHelper.h b/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/UniscribeHelper.h
deleted file mode 100644
index 66826adfed1..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/UniscribeHelper.h
+++ /dev/null
@@ -1,449 +0,0 @@
-/*
- * Copyright (c) 2006, 2007, 2008, 2009, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-// A wrapper around Uniscribe that provides a reasonable API.
-
-#ifndef UniscribeHelper_h
-#define UniscribeHelper_h
-
-#include <windows.h>
-#include <usp10.h>
-#include <map>
-
-#include <unicode/uchar.h>
-#include "wtf/Vector.h"
-
-class UniscribeTest_TooBig_Test; // A gunit test for UniscribeHelper.
-
-namespace WebCore {
-
-class FloatRect;
-class FontFeatureSettings;
-class GraphicsContext;
-
-const unsigned cUniscribeHelperStackRuns = 8;
-const unsigned cUniscribeHelperStackChars = 32;
-const unsigned cUniscribeHelperFeatures = 4;
-
-// This object should be safe to create & destroy frequently, as long as the
-// caller preserves the script_cache when possible (this data may be slow to
-// compute).
-//
-// This object is "kind of large" (~1K) because it reserves a lot of space for
-// working with to avoid expensive heap operations. Therefore, not only should
-// you not worry about creating and destroying it, you should try to not keep
-// them around.
-class UniscribeHelper {
-public:
- // Initializes this Uniscribe run with the text pointed to by |run| with
- // |length|. The input is NOT null terminated.
- //
- // The is_rtl flag should be set if the input script is RTL. It is assumed
- // that the caller has already divided up the input text (using ICU, for
- // example) into runs of the same direction of script. This avoids
- // disagreements between the caller and Uniscribe later (see FillItems).
- //
- // A script cache should be provided by the caller that is initialized to
- // NULL. When the caller is done with the cache (it may be stored between
- // runs as long as it is used consistently with the same HFONT), it should
- // call ScriptFreeCache().
- UniscribeHelper(const UChar* input,
- int inputLength,
- bool isRtl,
- HFONT,
- SCRIPT_CACHE*,
- SCRIPT_FONTPROPERTIES*,
- WORD);
-
- virtual ~UniscribeHelper();
-
- // Sets Uniscribe's directional override flag. False by default.
- bool directionalOverride() const
- {
- return m_directionalOverride;
- }
- void setDirectionalOverride(bool override)
- {
- m_directionalOverride = override;
- }
-
- // Set's Uniscribe's no-ligate override flag. False by default.
- bool inhibitLigate() const
- {
- return m_inhibitLigate;
- }
- void setInhibitLigate(bool inhibit)
- {
- m_inhibitLigate = inhibit;
- }
-
- // Set letter spacing. We will try to insert this much space between
- // graphemes (one or more glyphs perceived as a single unit by ordinary
- // users of a script). Positive values increase letter spacing, negative
- // values decrease it. 0 by default.
- int letterSpacing() const
- {
- return m_letterSpacing;
- }
- void setLetterSpacing(int letterSpacing)
- {
- m_letterSpacing = letterSpacing;
- }
-
- // Set the width of a standard space character. We use this to normalize
- // space widths. Windows will make spaces after Hindi characters larger than
- // other spaces. A space_width of 0 means to use the default space width.
- //
- // Must be set before Init() is called.
- int spaceWidth() const
- {
- return m_spaceWidth;
- }
- void setSpaceWidth(int spaceWidth)
- {
- m_spaceWidth = spaceWidth;
- }
-
- // Set word spacing. We will try to insert this much extra space between
- // each word in the input (beyond whatever whitespace character separates
- // words). Positive values lead to increased letter spacing, negative values
- // decrease it. 0 by default.
- //
- // Must be set before Init() is called.
- int wordSpacing() const
- {
- return m_wordSpacing;
- }
- void setWordSpacing(int wordSpacing)
- {
- m_wordSpacing = wordSpacing;
- }
-
- void setAscent(int ascent)
- {
- m_ascent = ascent;
- }
-
- // When set to true, this class is used only to look up glyph
- // indices for a range of Unicode characters without glyph placement.
- // By default, it's false. This should be set to true when this
- // class is used for glyph index look-up for non-BMP characters
- // in GlyphPageNodeChromiumWin.cpp.
- void setDisableFontFallback(bool disableFontFallback)
- {
- m_disableFontFallback = true;
- }
-
- // Set TEXTRANGE_PROPERTIES structure which contains
- // OpenType feature records generated from FontFeatureSettings.
- void setRangeProperties(const FontFeatureSettings*);
-
- // You must call this after setting any options but before doing any
- // other calls like asking for widths or drawing.
- void init()
- {
- initWithOptionalLengthProtection(true);
- }
-
- // Returns the total width in pixels of the text run.
- int width() const;
-
- // Call to justify the text, with the amount of space that should be ADDED
- // to get the desired width that the column should be justified to.
- // Normally, spaces are inserted, but for Arabic there will be kashidas
- // (extra strokes) inserted instead.
- //
- // This function MUST be called AFTER Init().
- void justify(int additionalSpace);
-
- // Computes the given character offset into a pixel offset of the beginning
- // of that character.
- int characterToX(int offset) const;
-
- // Converts the given pixel X position into a logical character offset into
- // the run. For positions appearing before the first character, this will
- // return -1.
- int xToCharacter(int x) const;
-
- // Draws the given characters to (x, y) in the given DC. The font will be
- // handled by this function, but the font color and other attributes should
- // be pre-set.
- //
- // The y position is the upper left corner, NOT the baseline.
- void draw(GraphicsContext* graphicsContext, HDC dc,
- int x, int y,
- const FloatRect& textRect,
- int from, int to);
-
- // Returns the first glyph assigned to the character at the given offset.
- // This function is used to retrieve glyph information when Uniscribe is
- // being used to generate glyphs for non-complex, non-BMP (above U+FFFF)
- // characters. These characters are not otherwise special and have no
- // complex shaping rules, so we don't otherwise need Uniscribe, except
- // Uniscribe is the only way to get glyphs for non-BMP characters.
- //
- // Returns 0 if there is no glyph for the given character.
- WORD firstGlyphForCharacter(int charOffset) const;
-
-protected:
- // Backend for init. The flag allows the unit test to specify whether we
- // should fail early for very long strings like normal, or try to pass the
- // long string to Uniscribe. The latter provides a way to force failure of
- // shaping.
- void initWithOptionalLengthProtection(bool lengthProtection);
-
- // Tries to preload the font when the it is not accessible.
- // This is the default implementation and it does not do anything.
- virtual void tryToPreloadFont(HFONT) {}
-
- // Let our subclasses provide the input lazily in case they can't compute
- // it in their constructors. Once we have input, however, we don't let
- // our subclasses change it.
- void setInput(const UChar* input) { ASSERT(!m_input); m_input = input; }
-
-private:
- friend class UniscribeTest_TooBig_Test;
-
- // An array corresponding to each item in runs_ containing information
- // on each of the glyphs that were generated. Like runs_, this is in
- // reading order. However, for rtl text, the characters within each
- // item will be reversed.
- struct Shaping {
- Shaping()
- : m_prePadding(0)
- , m_hfont(NULL)
- , m_scriptCache(NULL)
- , m_ascentOffset(0)
- , m_spaceGlyph(0)
- {
- m_abc.abcA = 0;
- m_abc.abcB = 0;
- m_abc.abcC = 0;
- }
-
- // Returns the number of glyphs (which will be drawn to the screen)
- // in this run.
- int glyphLength() const
- {
- return static_cast<int>(m_glyphs.size());
- }
-
- // Returns the number of characters (that we started with) in this run.
- int charLength() const
- {
- return static_cast<int>(m_logs.size());
- }
-
- // Returns the advance array that should be used when measuring glyphs.
- // The returned pointer will indicate an array with glyph_length()
- // elements and the advance that should be used for each one. This is
- // either the real advance, or the justified advances if there is one,
- // and is the array we want to use for measurement.
- const int* effectiveAdvances() const
- {
- if (m_advance.size() == 0)
- return 0;
- if (m_justify.size() == 0)
- return &m_advance[0];
- return &m_justify[0];
- }
-
- // This is the advance amount of space that we have added to the
- // beginning of the run. It is like the ABC's |A| advance but one that
- // we create and must handle internally whenever computing with pixel
- // offsets.
- int m_prePadding;
-
- // Glyph indices in the font used to display this item. These indices
- // are in screen order.
- Vector<WORD, cUniscribeHelperStackChars> m_glyphs;
-
- // For each input character, this tells us the first glyph index it
- // generated. This is the only array with size of the input chars.
- //
- // All offsets are from the beginning of this run. Multiple characters
- // can generate one glyph, in which case there will be adjacent
- // duplicates in this list. One character can also generate multiple
- // glyphs, in which case there will be skipped indices in this list.
- Vector<WORD, cUniscribeHelperStackChars> m_logs;
-
- // Flags and such for each glyph.
- Vector<SCRIPT_VISATTR, cUniscribeHelperStackChars> m_visualAttributes;
-
- // Horizontal advances for each glyph listed above, this is basically
- // how wide each glyph is.
- Vector<int, cUniscribeHelperStackChars> m_advance;
-
- // This contains glyph offsets, from the nominal position of a glyph.
- // It is used to adjust the positions of multiple combining characters
- // around/above/below base characters in a context-sensitive manner so
- // that they don't bump against each other and the base character.
- Vector<GOFFSET, cUniscribeHelperStackChars> m_offsets;
-
- // Filled by a call to Justify, this is empty for nonjustified text.
- // If nonempty, this contains the array of justify characters for each
- // character as returned by ScriptJustify.
- //
- // This is the same as the advance array, but with extra space added
- // for some characters. The difference between a glyph's |justify|
- // width and it's |advance| width is the extra space added.
- Vector<int, cUniscribeHelperStackChars> m_justify;
-
- // Sizing information for this run. This treats the entire run as a
- // character with a preceeding advance, width, and ending advance. The
- // B width is the sum of the |advance| array, and the A and C widths
- // are any extra spacing applied to each end.
- //
- // It is unclear from the documentation what this actually means. From
- // experimentation, it seems that the sum of the character advances is
- // always the sum of the ABC values, and I'm not sure what you're
- // supposed to do with the ABC values.
- ABC m_abc;
-
- // Pointers to windows font data used to render this run.
- HFONT m_hfont;
- SCRIPT_CACHE* m_scriptCache;
-
- // Ascent offset between the ascent of the primary font
- // and that of the fallback font. The offset needs to be applied,
- // when drawing a string, to align multiple runs rendered with
- // different fonts.
- int m_ascentOffset;
-
- WORD m_spaceGlyph;
- };
-
- // Computes the runs_ array from the text run.
- void fillRuns();
-
- // Computes the shapes_ array given an runs_ array already filled in.
- void fillShapes();
-
- // Fills in the screen_order_ array (see below).
- void fillScreenOrder();
-
- // Called to update the glyph positions based on the current spacing
- // options that are set.
- void applySpacing();
-
- // Normalizes all advances for spaces to the same width. This keeps windows
- // from making spaces after Hindi characters larger, which is then
- // inconsistent with our meaure of the width since WebKit doesn't include
- // spaces in text-runs sent to uniscribe unless white-space:pre.
- void adjustSpaceAdvances();
-
- // Returns the total width of a single item.
- int advanceForItem(int) const;
-
- bool containsMissingGlyphs(const Shaping&,
- const SCRIPT_ITEM&,
- const SCRIPT_FONTPROPERTIES*) const;
-
- // Shapes a run (pointed to by |input|) using |hfont| first.
- // Tries a series of fonts specified retrieved with NextWinFontData
- // and finally a font covering characters in |*input|. A string pointed
- // by |input| comes from ScriptItemize and is supposed to contain
- // characters belonging to a single script aside from characters common to
- // all scripts (e.g. space).
- bool shape(const UChar* input, int itemLength, int numGlyphs, SCRIPT_ITEM& run, OPENTYPE_TAG, Shaping&);
-
- // Gets Windows font data for the next best font to try in the list
- // of fonts. When there's no more font available, returns false
- // without touching any of out params. Need to call ResetFontIndex
- // to start scanning of the font list from the beginning.
- virtual bool nextWinFontData(HFONT&, SCRIPT_CACHE*&, SCRIPT_FONTPROPERTIES*&, int&, WORD&)
- {
- return false;
- }
-
- // Resets the font index to the first in the list of fonts to try after the
- // primaryFont turns out not to work. With fontIndex reset,
- // NextWinFontData scans fallback fonts from the beginning.
- virtual void resetFontIndex() {}
-
- // If m_cachedDC is 0, creates one that is compatible with the screen DC.
- void EnsureCachedDCCreated();
-
- // The input data for this run of Uniscribe. See the constructor.
- const UChar* m_input;
- const int m_inputLength;
- const bool m_isRtl;
-
- // Windows font data for the primary font. In a sense, m_logfont and m_style
- // are redundant because m_hfont contains all the information. However,
- // invoking GetObject, everytime we need the height and the style, is rather
- // expensive so that we cache them. Would it be better to add getter and
- // (virtual) setter for the height and the style of the primary font,
- // instead of m_logfont? Then, a derived class ctor can set m_ascent,
- // m_height and m_style if they're known. Getters for them would have to
- // 'infer' their values from m_hfont ONLY when they're not set.
- HFONT m_hfont;
- // We cache the DC to use with ScriptShape/ScriptPlace.
- static HDC m_cachedDC;
- SCRIPT_CACHE* m_scriptCache;
- SCRIPT_FONTPROPERTIES* m_fontProperties;
- int m_ascent;
- LOGFONT m_logfont;
- int m_style;
- WORD m_spaceGlyph;
-
- // Options, see the getters/setters above.
- bool m_directionalOverride;
- bool m_inhibitLigate;
- int m_letterSpacing;
- int m_spaceWidth;
- int m_wordSpacing;
- bool m_disableFontFallback;
-
- // Uniscribe breaks the text into Runs. These are one length of text that is
- // in one script and one direction. This array is in reading order.
- Vector<SCRIPT_ITEM, cUniscribeHelperStackRuns> m_runs;
-
- Vector<Shaping, cUniscribeHelperStackRuns> m_shapes;
- Vector<OPENTYPE_TAG, cUniscribeHelperStackRuns> m_scriptTags;
-
- // This is a mapping between reading order and screen order for the items.
- // Uniscribe's items array are in reading order. For right-to-left text,
- // or mixed (although WebKit's |TextRun| should really be only one
- // direction), this makes it very difficult to compute character offsets
- // and positions. This list is in screen order from left to right, and
- // gives the index into the |m_runs| and |m_shapes| arrays of each
- // subsequent item.
- Vector<int, cUniscribeHelperStackRuns> m_screenOrder;
-
- // This contains Uniscribe's OpenType feature settings. This structure
- // is filled by using WebKit's |FontFeatureSettings|.
- TEXTRANGE_PROPERTIES m_rangeProperties;
- Vector<OPENTYPE_FEATURE_RECORD, cUniscribeHelperFeatures> m_featureRecords;
-};
-
-} // namespace WebCore
-
-#endif // UniscribeHelper_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/UniscribeHelperTextRun.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/UniscribeHelperTextRun.cpp
deleted file mode 100644
index 1733f8e390a..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/UniscribeHelperTextRun.cpp
+++ /dev/null
@@ -1,151 +0,0 @@
-/*
- * Copyright (c) 2006, 2007, 2008, 2009, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/chromium/UniscribeHelperTextRun.h"
-
-#include "core/platform/graphics/Font.h"
-#include "core/platform/graphics/SimpleFontData.h"
-#include "core/platform/graphics/TextRun.h"
-#include "core/platform/graphics/chromium/FontPlatformDataChromiumWin.h"
-
-namespace WebCore {
-
-UniscribeHelperTextRun::UniscribeHelperTextRun(const TextRun& run,
- const Font& font)
- : UniscribeHelper(0, run.length(), run.rtl(),
- font.primaryFont()->platformData().hfont(),
- font.primaryFont()->platformData().scriptCache(),
- font.primaryFont()->platformData().scriptFontProperties(),
- font.primaryFont()->spaceGlyph())
- , m_font(&font)
- , m_fontIndex(0)
-{
- if (run.is8Bit()) {
- m_stringFor8BitRun = String::make16BitFrom8BitSource(run.characters8(), run.length());
- setInput(m_stringFor8BitRun.characters16());
- } else {
- setInput(run.characters16());
- }
-
- setDirectionalOverride(run.directionalOverride());
- setLetterSpacing(font.letterSpacing());
- setSpaceWidth(font.spaceWidth());
- setWordSpacing(font.wordSpacing());
- setAscent(font.fontMetrics().ascent());
- setRangeProperties(font.fontDescription().featureSettings());
-
- init();
-
- // Expansion is the amount to add to make justification happen. This
- // should be done after Init() so all the runs are already measured.
- if (run.expansion() > 0)
- justify(run.expansion());
-}
-
-UniscribeHelperTextRun::UniscribeHelperTextRun(
- const wchar_t* input,
- int inputLength,
- bool isRtl,
- HFONT hfont,
- SCRIPT_CACHE* scriptCache,
- SCRIPT_FONTPROPERTIES* fontProperties)
- : UniscribeHelper(input, inputLength, isRtl, hfont,
- scriptCache, fontProperties, 0)
- , m_font(0)
- , m_fontIndex(-1)
-{
-}
-
-void UniscribeHelperTextRun::tryToPreloadFont(HFONT font)
-{
- // Ask the browser to get the font metrics for this font.
- // That will preload the font and it should now be accessible
- // from the renderer.
- FontPlatformData::ensureFontLoaded(font);
-}
-
-bool UniscribeHelperTextRun::nextWinFontData(
- HFONT& hfont,
- SCRIPT_CACHE*& scriptCache,
- SCRIPT_FONTPROPERTIES*& fontProperties,
- int& ascent,
- WORD& spaceGlyph)
-{
- // This check is necessary because NextWinFontData can be called again
- // after we already ran out of fonts. fontDataAt behaves in a strange
- // manner when the difference between param passed and # of fonts stored in
- // WebKit::Font is larger than one. We can avoid this check by setting
- // font_index_ to # of elements in hfonts_ when we run out of font. In that
- // case, we'd have to go through a couple of more checks before returning
- // false.
- if (m_fontIndex == -1 || !m_font)
- return false;
-
- // If the font data for a fallback font requested is not yet retrieved, add
- // them to our vectors. Note that '>' rather than '>=' is used to test that
- // condition. primaryFont is not stored in hfonts_, and friends so that
- // indices for fontDataAt and our vectors for font data are 1 off from each
- // other. That is, when fully populated, hfonts_ and friends have one font
- // fewer than what's contained in font_.
- if (static_cast<size_t>(++m_fontIndex) > m_hfonts.size()) {
- const FontData *fontData = m_font->fontDataAt(m_fontIndex);
- if (!fontData) {
- // Ran out of fonts.
- m_fontIndex = -1;
- return false;
- }
-
- // FIXME: this won't work for SegmentedFontData
- // http://crbug.com/6425
- const SimpleFontData* simpleFontData =
- fontData->fontDataForCharacter(' ');
-
- m_hfonts.append(simpleFontData->platformData().hfont());
- m_scriptCaches.append(simpleFontData->platformData().scriptCache());
- m_fontProperties.append(simpleFontData->platformData().scriptFontProperties());
- m_ascents.append(simpleFontData->fontMetrics().ascent());
- m_spaceGlyphs.append(simpleFontData->spaceGlyph());
- }
-
- hfont = m_hfonts[m_fontIndex - 1];
- scriptCache = m_scriptCaches[m_fontIndex - 1];
- fontProperties = m_fontProperties[m_fontIndex - 1];
- ascent = m_ascents[m_fontIndex - 1];
- spaceGlyph = m_spaceGlyphs[m_fontIndex - 1];
- return true;
-}
-
-void UniscribeHelperTextRun::resetFontIndex()
-{
- m_fontIndex = 0;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/UniscribeHelperTextRun.h b/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/UniscribeHelperTextRun.h
deleted file mode 100644
index 0bac52ebd95..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/UniscribeHelperTextRun.h
+++ /dev/null
@@ -1,102 +0,0 @@
-/*
- * Copyright (c) 2006, 2007, 2008, 2009, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef UniscribeHelperTextRun_h
-#define UniscribeHelperTextRun_h
-
-#include "core/platform/graphics/chromium/UniscribeHelper.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class Font;
-class TextRun;
-
-// Wrapper around the Uniscribe helper that automatically sets it up with the
-// WebKit types we supply.
-class UniscribeHelperTextRun : public UniscribeHelper {
-public:
- // Regular constructor used for WebCore text run processing.
- UniscribeHelperTextRun(const TextRun&, const Font&);
-
- // Constructor with the same interface as the gfx::UniscribeState. Using
- // this constructor will not give you font fallback, but it will provide
- // the ability to load fonts that may not be in the OS cache
- // ("TryToPreloadFont") if the caller does not have a TextRun/Font.
- UniscribeHelperTextRun(const wchar_t* input,
- int inputLength,
- bool isRtl,
- HFONT hfont,
- SCRIPT_CACHE*,
- SCRIPT_FONTPROPERTIES*);
-
-protected:
- virtual void tryToPreloadFont(HFONT);
-
-private:
- // This function retrieves the Windows font data (HFONT, etc) for the next
- // WebKit font in the list. If the font data corresponding to font_index_
- // has been obtained before, returns the values stored in our internal
- // vectors (hfonts_, etc). Otherwise, it gets next SimpleFontData from
- // WebKit and adds them to in hfonts_ and friends so that font data can be
- // returned quickly next time they're requested.
- virtual bool nextWinFontData(HFONT&, SCRIPT_CACHE*&, SCRIPT_FONTPROPERTIES*&, int& ascent, WORD& spaceGlyph);
- virtual void resetFontIndex();
-
- // Reference to WebKit::Font that contains all the information about fonts
- // we can use to render this input run of text. It is used in
- // NextWinFontData to retrieve Windows font data for a series of
- // non-primary fonts.
- //
- // This pointer can be NULL for no font fallback handling.
- const Font* m_font;
-
- // When we have an 8 bit TestRun, we store the buffer of upconverted characters
- // in this string.
- String m_stringFor8BitRun;
-
- // It's rare that many fonts are listed in stylesheets.
- // Four would be large enough in most cases.
- const static size_t kNumberOfFonts = 4;
-
- // These vectors are used to store Windows font data for non-primary fonts.
- Vector<HFONT, kNumberOfFonts> m_hfonts;
- Vector<SCRIPT_CACHE*, kNumberOfFonts> m_scriptCaches;
- Vector<SCRIPT_FONTPROPERTIES*, kNumberOfFonts> m_fontProperties;
- Vector<int, kNumberOfFonts> m_ascents;
- Vector<WORD> m_spaceGlyphs;
-
- // Index of the fallback font we're currently using for NextWinFontData.
- int m_fontIndex;
-};
-
-} // namespace WebCore
-
-#endif // UniscribeHelperTextRun_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/VDMXParser.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/VDMXParser.cpp
deleted file mode 100644
index 5966ca77764..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/VDMXParser.cpp
+++ /dev/null
@@ -1,203 +0,0 @@
-/*
- * Copyright (c) 2008, 2009, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "VDMXParser.h"
-
-#include <stdlib.h>
-#include <string.h>
-
-#include "wtf/ByteOrder.h"
-
-// Buffer helper class
-//
-// This class perform some trival buffer operations while checking for
-// out-of-bounds errors. As a family they return false if anything is amiss,
-// updating the current offset otherwise.
-class Buffer {
-public:
- Buffer(const uint8_t* buffer, size_t length)
- : m_buffer(buffer)
- , m_length(length)
- , m_offset(0) { }
-
- bool skip(size_t numBytes)
- {
- if (m_offset + numBytes > m_length)
- return false;
- m_offset += numBytes;
- return true;
- }
-
- bool readU8(uint8_t* value)
- {
- if (m_offset + sizeof(uint8_t) > m_length)
- return false;
- *value = m_buffer[m_offset];
- m_offset += sizeof(uint8_t);
- return true;
- }
-
- bool readU16(uint16_t* value)
- {
- if (m_offset + sizeof(uint16_t) > m_length)
- return false;
- memcpy(value, m_buffer + m_offset, sizeof(uint16_t));
- *value = ntohs(*value);
- m_offset += sizeof(uint16_t);
- return true;
- }
-
- bool readS16(int16_t* value)
- {
- return readU16(reinterpret_cast<uint16_t*>(value));
- }
-
- size_t offset() const
- {
- return m_offset;
- }
-
- void setOffset(size_t newoffset)
- {
- m_offset = newoffset;
- }
-
-private:
- const uint8_t *const m_buffer;
- const size_t m_length;
- size_t m_offset;
-};
-
-// VDMX parsing code.
-//
-// VDMX tables are found in some TrueType/OpenType fonts and contain
-// ascender/descender overrides for certain (usually small) sizes. This is
-// needed in order to match font metrics on Windows.
-//
-// Freetype does not parse these tables so we do so here.
-
-namespace WebCore {
-
-// Parse a TrueType VDMX table.
-// yMax: (output) the ascender value from the table
-// yMin: (output) the descender value from the table (negative!)
-// vdmx: the table bytes
-// vdmxLength: length of @vdmx, in bytes
-// targetPixelSize: the pixel size of the font (e.g. 16)
-//
-// Returns true iff a suitable match are found. Otherwise, *yMax and *yMin are
-// untouched. size_t must be 32-bits to avoid overflow.
-//
-// See http://www.microsoft.com/opentype/otspec/vdmx.htm
-bool parseVDMX(int* yMax, int* yMin,
- const uint8_t* vdmx, size_t vdmxLength,
- unsigned targetPixelSize)
-{
- Buffer buf(vdmx, vdmxLength);
-
- // We ignore the version. Future tables should be backwards compatible with
- // this layout.
- uint16_t numRatios;
- if (!buf.skip(4) || !buf.readU16(&numRatios))
- return false;
-
- // Now we have two tables. Firstly we have @numRatios Ratio records, then a
- // matching array of @numRatios offsets. We save the offset of the beginning
- // of this second table.
- //
- // Range 6 <= x <= 262146
- unsigned long offsetTableOffset =
- buf.offset() + 4 /* sizeof struct ratio */ * numRatios;
-
- unsigned desiredRatio = 0xffffffff;
- // We read 4 bytes per record, so the offset range is
- // 6 <= x <= 524286
- for (unsigned i = 0; i < numRatios; ++i) {
- uint8_t xRatio, yRatio1, yRatio2;
-
- if (!buf.skip(1)
- || !buf.readU8(&xRatio)
- || !buf.readU8(&yRatio1)
- || !buf.readU8(&yRatio2))
- return false;
-
- // This either covers 1:1, or this is the default entry (0, 0, 0)
- if ((xRatio == 1 && yRatio1 <= 1 && yRatio2 >= 1)
- || (xRatio == 0 && yRatio1 == 0 && yRatio2 == 0)) {
- desiredRatio = i;
- break;
- }
- }
-
- if (desiredRatio == 0xffffffff) // no ratio found
- return false;
-
- // Range 10 <= x <= 393216
- buf.setOffset(offsetTableOffset + sizeof(uint16_t) * desiredRatio);
-
- // Now we read from the offset table to get the offset of another array
- uint16_t groupOffset;
- if (!buf.readU16(&groupOffset))
- return false;
- // Range 0 <= x <= 65535
- buf.setOffset(groupOffset);
-
- uint16_t numRecords;
- if (!buf.readU16(&numRecords) || !buf.skip(sizeof(uint16_t)))
- return false;
-
- // We read 6 bytes per record, so the offset range is
- // 4 <= x <= 458749
- for (unsigned i = 0; i < numRecords; ++i) {
- uint16_t pixelSize;
- if (!buf.readU16(&pixelSize))
- return false;
- // the entries are sorted, so we can abort early if need be
- if (pixelSize > targetPixelSize)
- return false;
-
- if (pixelSize == targetPixelSize) {
- int16_t tempYMax, tempYMin;
- if (!buf.readS16(&tempYMax)
- || !buf.readS16(&tempYMin))
- return false;
- *yMin = tempYMin;
- *yMax = tempYMax;
- return true;
- }
- if (!buf.skip(2 * sizeof(int16_t)))
- return false;
- }
-
- return false;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/VDMXParser.h b/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/VDMXParser.h
deleted file mode 100644
index 90ac952d412..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/chromium/VDMXParser.h
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright (c) 2009, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef VDMXParser_h
-#define VDMXParser_h
-
-#include <stdint.h>
-
-namespace WebCore {
- bool parseVDMX(int* ymax, int* ymin,
- const uint8_t* vdmx, size_t vdmxLength,
- unsigned targetPixelSize);
-} // namespace WebCore
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/cocoa/FontPlatformDataCocoa.mm b/chromium/third_party/WebKit/Source/core/platform/graphics/cocoa/FontPlatformDataCocoa.mm
deleted file mode 100644
index 2faaf2ba714..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/cocoa/FontPlatformDataCocoa.mm
+++ /dev/null
@@ -1,321 +0,0 @@
-/*
- * This file is part of the internal font implementation.
- *
- * Copyright (C) 2006, 2007, 2008, 2009, 2010 Apple Inc. All rights reserved.
- * Copyright (c) 2010 Google Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#import "config.h"
-#import "core/platform/graphics/FontPlatformData.h"
-
-#import <AppKit/NSFont.h>
-#import <AvailabilityMacros.h>
-#import <wtf/text/WTFString.h>
-
-#if OS(MACOSX)
-#import "core/platform/graphics/harfbuzz/HarfBuzzFace.h"
-#endif
-
-namespace WebCore {
-
-// These CoreText Text Spacing feature selectors are not defined in CoreText.
-enum TextSpacingCTFeatureSelector { TextSpacingProportional, TextSpacingFullWidth, TextSpacingHalfWidth, TextSpacingThirdWidth, TextSpacingQuarterWidth };
-
-FontPlatformData::FontPlatformData(NSFont *nsFont, float size, bool isPrinterFont, bool syntheticBold, bool syntheticOblique, FontOrientation orientation, FontWidthVariant widthVariant)
- : m_syntheticBold(syntheticBold)
- , m_syntheticOblique(syntheticOblique)
- , m_orientation(orientation)
- , m_size(size)
- , m_widthVariant(widthVariant)
- , m_font(nsFont)
- , m_isColorBitmapFont(false)
- , m_isCompositeFontReference(false)
- , m_isPrinterFont(isPrinterFont)
-{
- ASSERT_ARG(nsFont, nsFont);
-
- CGFontRef cgFont = 0;
- loadFont(nsFont, size, m_font, cgFont);
-
-#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
- // FIXME: Chromium: The following code isn't correct for the Chromium port since the sandbox might
- // have blocked font loading, in which case we'll only have the real loaded font file after the call to loadFont().
- {
- CTFontSymbolicTraits traits = CTFontGetSymbolicTraits(toCTFontRef(m_font));
- m_isColorBitmapFont = traits & kCTFontColorGlyphsTrait;
-#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080
- m_isCompositeFontReference = traits & kCTFontCompositeTrait;
-#endif
- }
-#endif
-
- if (m_font)
- CFRetain(m_font);
-
- m_cgFont.adoptCF(cgFont);
-}
-
-FontPlatformData:: ~FontPlatformData()
-{
- if (m_font && m_font != reinterpret_cast<NSFont *>(-1))
- CFRelease(m_font);
-}
-
-void FontPlatformData::platformDataInit(const FontPlatformData& f)
-{
- m_font = f.m_font && f.m_font != reinterpret_cast<NSFont *>(-1) ? [f.m_font retain] : f.m_font;
-
- m_cgFont = f.m_cgFont;
- m_CTFont = f.m_CTFont;
-
-#if OS(MACOSX)
- m_inMemoryFont = f.m_inMemoryFont;
- m_harfBuzzFace = f.m_harfBuzzFace;
-#endif
-}
-
-const FontPlatformData& FontPlatformData::platformDataAssign(const FontPlatformData& f)
-{
- m_cgFont = f.m_cgFont;
- if (m_font == f.m_font)
- return *this;
- if (f.m_font && f.m_font != reinterpret_cast<NSFont *>(-1))
- CFRetain(f.m_font);
- if (m_font && m_font != reinterpret_cast<NSFont *>(-1))
- CFRelease(m_font);
- m_font = f.m_font;
- m_CTFont = f.m_CTFont;
-#if OS(MACOSX)
- m_inMemoryFont = f.m_inMemoryFont;
- m_harfBuzzFace = f.m_harfBuzzFace;
-#endif
- return *this;
-}
-
-bool FontPlatformData::platformIsEqual(const FontPlatformData& other) const
-{
- if (m_font || other.m_font)
- return m_font == other.m_font;
- return m_cgFont == other.m_cgFont;
-}
-
-void FontPlatformData::setFont(NSFont *font)
-{
- ASSERT_ARG(font, font);
- ASSERT(m_font != reinterpret_cast<NSFont *>(-1));
-
- if (m_font == font)
- return;
-
- CFRetain(font);
- if (m_font)
- CFRelease(m_font);
- m_font = font;
- m_size = [font pointSize];
-
- CGFontRef cgFont = 0;
- NSFont* loadedFont = 0;
- loadFont(m_font, m_size, loadedFont, cgFont);
-
-#if OS(MACOSX)
- // If loadFont replaced m_font with a fallback font, then release the
- // previous font to counter the retain above. Then retain the new font.
- if (loadedFont != m_font) {
- CFRelease(m_font);
- CFRetain(loadedFont);
- m_font = loadedFont;
- }
-#endif
-
- m_cgFont.adoptCF(cgFont);
-#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
- {
- CTFontSymbolicTraits traits = CTFontGetSymbolicTraits(toCTFontRef(m_font));
- m_isColorBitmapFont = traits & kCTFontColorGlyphsTrait;
-#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080
- m_isCompositeFontReference = traits & kCTFontCompositeTrait;
-#endif
- }
-#endif
- m_CTFont = 0;
-}
-
-bool FontPlatformData::roundsGlyphAdvances() const
-{
- return [m_font renderingMode] == NSFontAntialiasedIntegerAdvancementsRenderingMode;
-}
-
-bool FontPlatformData::allowsLigatures() const
-{
- return ![[m_font coveredCharacterSet] characterIsMember:'a'];
-}
-
-inline int mapFontWidthVariantToCTFeatureSelector(FontWidthVariant variant)
-{
- switch(variant) {
- case RegularWidth:
- return TextSpacingProportional;
-
- case HalfWidth:
- return TextSpacingHalfWidth;
-
- case ThirdWidth:
- return TextSpacingThirdWidth;
-
- case QuarterWidth:
- return TextSpacingQuarterWidth;
- }
-
- ASSERT_NOT_REACHED();
- return TextSpacingProportional;
-}
-
-static CFDictionaryRef createFeatureSettingDictionary(int featureTypeIdentifier, int featureSelectorIdentifier)
-{
- RetainPtr<CFNumberRef> featureTypeIdentifierNumber(AdoptCF, CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &featureTypeIdentifier));
- RetainPtr<CFNumberRef> featureSelectorIdentifierNumber(AdoptCF, CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &featureSelectorIdentifier));
-
- const void* settingKeys[] = { kCTFontFeatureTypeIdentifierKey, kCTFontFeatureSelectorIdentifierKey };
- const void* settingValues[] = { featureTypeIdentifierNumber.get(), featureSelectorIdentifierNumber.get() };
-
- return CFDictionaryCreate(kCFAllocatorDefault, settingKeys, settingValues, WTF_ARRAY_LENGTH(settingKeys), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
-}
-
-static CTFontDescriptorRef cascadeToLastResortFontDescriptor()
-{
- static CTFontDescriptorRef descriptor;
- if (descriptor)
- return descriptor;
-
- const void* keys[] = { kCTFontCascadeListAttribute };
- const void* descriptors[] = { CTFontDescriptorCreateWithNameAndSize(CFSTR("LastResort"), 0) };
- const void* values[] = { CFArrayCreate(kCFAllocatorDefault, descriptors, WTF_ARRAY_LENGTH(descriptors), &kCFTypeArrayCallBacks) };
- RetainPtr<CFDictionaryRef> attributes(AdoptCF, CFDictionaryCreate(kCFAllocatorDefault, keys, values, WTF_ARRAY_LENGTH(keys), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
-
- descriptor = CTFontDescriptorCreateWithAttributes(attributes.get());
-
- return descriptor;
-}
-
-static CTFontDescriptorRef cascadeToLastResortAndDisableSwashesFontDescriptor()
-{
- static CTFontDescriptorRef descriptor;
- if (descriptor)
- return descriptor;
-
- RetainPtr<CFDictionaryRef> lineInitialSwashesOffSetting(AdoptCF, createFeatureSettingDictionary(kSmartSwashType, kLineInitialSwashesOffSelector));
- RetainPtr<CFDictionaryRef> lineFinalSwashesOffSetting(AdoptCF, createFeatureSettingDictionary(kSmartSwashType, kLineFinalSwashesOffSelector));
-
- const void* settingDictionaries[] = { lineInitialSwashesOffSetting.get(), lineFinalSwashesOffSetting.get() };
- RetainPtr<CFArrayRef> featureSettings(AdoptCF, CFArrayCreate(kCFAllocatorDefault, settingDictionaries, WTF_ARRAY_LENGTH(settingDictionaries), &kCFTypeArrayCallBacks));
-
- const void* keys[] = { kCTFontFeatureSettingsAttribute };
- const void* values[] = { featureSettings.get() };
- RetainPtr<CFDictionaryRef> attributes(AdoptCF, CFDictionaryCreate(kCFAllocatorDefault, keys, values, WTF_ARRAY_LENGTH(keys), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
-
- descriptor = CTFontDescriptorCreateCopyWithAttributes(cascadeToLastResortFontDescriptor(), attributes.get());
-
- return descriptor;
-}
-
-String FontPlatformData::fontFamilyName() const
-{
- return String(CTFontCopyDisplayName(ctFont()));
-}
-
-CTFontRef FontPlatformData::ctFont() const
-{
- if (m_CTFont)
- return m_CTFont.get();
-
- if (m_inMemoryFont) {
- m_CTFont.adoptCF(CTFontCreateWithGraphicsFont(m_inMemoryFont->cgFont(), m_size, 0, cascadeToLastResortFontDescriptor()));
- return m_CTFont.get();
- }
-
- m_CTFont = toCTFontRef(m_font);
- if (m_CTFont) {
- CTFontDescriptorRef fontDescriptor;
- RetainPtr<CFStringRef> postScriptName(AdoptCF, CTFontCopyPostScriptName(m_CTFont.get()));
- // Hoefler Text Italic has line-initial and -final swashes enabled by default, so disable them.
- if (CFEqual(postScriptName.get(), CFSTR("HoeflerText-Italic")) || CFEqual(postScriptName.get(), CFSTR("HoeflerText-BlackItalic")))
- fontDescriptor = cascadeToLastResortAndDisableSwashesFontDescriptor();
- else
- fontDescriptor = cascadeToLastResortFontDescriptor();
- m_CTFont.adoptCF(CTFontCreateCopyWithAttributes(m_CTFont.get(), m_size, 0, fontDescriptor));
- } else
- m_CTFont.adoptCF(CTFontCreateWithGraphicsFont(m_cgFont.get(), m_size, 0, cascadeToLastResortFontDescriptor()));
-
- if (m_widthVariant != RegularWidth) {
- int featureTypeValue = kTextSpacingType;
- int featureSelectorValue = mapFontWidthVariantToCTFeatureSelector(m_widthVariant);
- RetainPtr<CTFontDescriptorRef> sourceDescriptor(AdoptCF, CTFontCopyFontDescriptor(m_CTFont.get()));
- RetainPtr<CFNumberRef> featureType(AdoptCF, CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &featureTypeValue));
- RetainPtr<CFNumberRef> featureSelector(AdoptCF, CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &featureSelectorValue));
- RetainPtr<CTFontDescriptorRef> newDescriptor(AdoptCF, CTFontDescriptorCreateCopyWithFeature(sourceDescriptor.get(), featureType.get(), featureSelector.get()));
- RetainPtr<CTFontRef> newFont(AdoptCF, CTFontCreateWithFontDescriptor(newDescriptor.get(), m_size, 0));
-
- if (newFont)
- m_CTFont = newFont;
- }
-
- return m_CTFont.get();
-}
-
-#if OS(MACOSX)
-static bool isAATFont(CTFontRef ctFont)
-{
- CFDataRef table = CTFontCopyTable(ctFont, kCTFontTableMort, 0);
- if (table) {
- CFRelease(table);
- return true;
- }
- table = CTFontCopyTable(ctFont, kCTFontTableMorx, 0);
- if (table) {
- CFRelease(table);
- return true;
- }
- return false;
-}
-
-HarfBuzzFace* FontPlatformData::harfBuzzFace()
-{
- CTFontRef font = ctFont();
- // HarfBuzz can't handle AAT font
- if (isAATFont(font))
- return 0;
-
- if (!m_harfBuzzFace) {
- uint64_t uniqueID = reinterpret_cast<uintptr_t>(font);
- m_harfBuzzFace = HarfBuzzFace::create(const_cast<FontPlatformData*>(this), uniqueID);
- }
- return m_harfBuzzFace.get();
-}
-#endif
-
-#ifndef NDEBUG
-String FontPlatformData::description() const
-{
- RetainPtr<CFStringRef> cgFontDescription(AdoptCF, CFCopyDescription(cgFont()));
- return String(cgFontDescription.get()) + " " + String::number(m_size)
- + (m_syntheticBold ? " synthetic bold" : "") + (m_syntheticOblique ? " synthetic oblique" : "") + (m_orientation ? " vertical orientation" : "");
-}
-#endif
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/cpu/arm/GraphicsContext3DNEON.h b/chromium/third_party/WebKit/Source/core/platform/graphics/cpu/arm/GraphicsContext3DNEON.h
deleted file mode 100644
index c043fedd4a9..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/cpu/arm/GraphicsContext3DNEON.h
+++ /dev/null
@@ -1,304 +0,0 @@
-/*
- * Copyright (C) 2012 Gabor Rapcsanyi (rgabor@inf.u-szeged.hu), University of Szeged
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY UNIVERSITY OF SZEGED ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL UNIVERSITY OF SZEGED OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef GraphicsContext3DNEON_h
-#define GraphicsContext3DNEON_h
-
-#if HAVE(ARM_NEON_INTRINSICS)
-
-#include <arm_neon.h>
-
-namespace WebCore {
-
-namespace SIMD {
-
-ALWAYS_INLINE void unpackOneRowOfRGBA16LittleToRGBA8(const uint16_t*& source, uint8_t*& destination, unsigned& pixelsPerRow)
-{
- unsigned componentsPerRow = pixelsPerRow * 4;
- unsigned tailComponents = componentsPerRow % 16;
- unsigned componentsSize = componentsPerRow - tailComponents;
- const uint8_t* src = reinterpret_cast<const uint8_t*>(source);
-
- for (unsigned i = 0; i < componentsSize; i += 16) {
- uint8x16x2_t components = vld2q_u8(src + i * 2);
- vst1q_u8(destination + i, components.val[1]);
- }
-
- source += componentsSize;
- destination += componentsSize;
- pixelsPerRow = tailComponents / 4;
-}
-
-ALWAYS_INLINE void unpackOneRowOfRGB16LittleToRGBA8(const uint16_t*& source, uint8_t*& destination, unsigned& pixelsPerRow)
-{
- unsigned componentsPerRow = pixelsPerRow * 3;
- unsigned tailComponents = componentsPerRow % 24;
- unsigned componentsSize = componentsPerRow - tailComponents;
-
- uint8x8_t componentA = vdup_n_u8(0xFF);
- for (unsigned i = 0; i < componentsSize; i += 24) {
- uint16x8x3_t RGB16 = vld3q_u16(source + i);
- uint8x8_t componentR = vqmovn_u16(vshrq_n_u16(RGB16.val[0], 8));
- uint8x8_t componentG = vqmovn_u16(vshrq_n_u16(RGB16.val[1], 8));
- uint8x8_t componentB = vqmovn_u16(vshrq_n_u16(RGB16.val[2], 8));
- uint8x8x4_t RGBA8 = {{componentR, componentG, componentB, componentA}};
- vst4_u8(destination, RGBA8);
- destination += 32;
- }
-
- source += componentsSize;
- pixelsPerRow = tailComponents / 3;
-}
-
-ALWAYS_INLINE void unpackOneRowOfARGB16LittleToRGBA8(const uint16_t*& source, uint8_t*& destination, unsigned& pixelsPerRow)
-{
- unsigned componentsPerRow = pixelsPerRow * 4;
- unsigned tailComponents = componentsPerRow % 32;
- unsigned componentsSize = componentsPerRow - tailComponents;
-
- for (unsigned i = 0; i < componentsSize; i += 32) {
- uint16x8x4_t ARGB16 = vld4q_u16(source + i);
- uint8x8_t componentA = vqmovn_u16(vshrq_n_u16(ARGB16.val[0], 8));
- uint8x8_t componentR = vqmovn_u16(vshrq_n_u16(ARGB16.val[1], 8));
- uint8x8_t componentG = vqmovn_u16(vshrq_n_u16(ARGB16.val[2], 8));
- uint8x8_t componentB = vqmovn_u16(vshrq_n_u16(ARGB16.val[3], 8));
- uint8x8x4_t RGBA8 = {{componentR, componentG, componentB, componentA}};
- vst4_u8(destination + i, RGBA8);
- }
-
- source += componentsSize;
- destination += componentsSize;
- pixelsPerRow = tailComponents / 4;
-}
-
-ALWAYS_INLINE void unpackOneRowOfBGRA16LittleToRGBA8(const uint16_t*& source, uint8_t*& destination, unsigned& pixelsPerRow)
-{
- unsigned componentsPerRow = pixelsPerRow * 4;
- unsigned tailComponents = componentsPerRow % 32;
- unsigned componentsSize = componentsPerRow - tailComponents;
-
- for (unsigned i = 0; i < componentsSize; i += 32) {
- uint16x8x4_t ARGB16 = vld4q_u16(source + i);
- uint8x8_t componentB = vqmovn_u16(vshrq_n_u16(ARGB16.val[0], 8));
- uint8x8_t componentG = vqmovn_u16(vshrq_n_u16(ARGB16.val[1], 8));
- uint8x8_t componentR = vqmovn_u16(vshrq_n_u16(ARGB16.val[2], 8));
- uint8x8_t componentA = vqmovn_u16(vshrq_n_u16(ARGB16.val[3], 8));
- uint8x8x4_t RGBA8 = {{componentR, componentG, componentB, componentA}};
- vst4_u8(destination + i, RGBA8);
- }
-
- source += componentsSize;
- destination += componentsSize;
- pixelsPerRow = tailComponents / 4;
-}
-
-ALWAYS_INLINE void unpackOneRowOfRGBA4444ToRGBA8(const uint16_t*& source, uint8_t*& destination, unsigned& pixelsPerRow)
-{
- unsigned tailPixels = pixelsPerRow % 8;
- unsigned pixelSize = pixelsPerRow - tailPixels;
-
- uint16x8_t immediate0x0f = vdupq_n_u16(0x0F);
- for (unsigned i = 0; i < pixelSize; i += 8) {
- uint16x8_t eightPixels = vld1q_u16(source + i);
-
- uint8x8_t componentR = vqmovn_u16(vshrq_n_u16(eightPixels, 12));
- uint8x8_t componentG = vqmovn_u16(vandq_u16(vshrq_n_u16(eightPixels, 8), immediate0x0f));
- uint8x8_t componentB = vqmovn_u16(vandq_u16(vshrq_n_u16(eightPixels, 4), immediate0x0f));
- uint8x8_t componentA = vqmovn_u16(vandq_u16(eightPixels, immediate0x0f));
-
- componentR = vorr_u8(vshl_n_u8(componentR, 4), componentR);
- componentG = vorr_u8(vshl_n_u8(componentG, 4), componentG);
- componentB = vorr_u8(vshl_n_u8(componentB, 4), componentB);
- componentA = vorr_u8(vshl_n_u8(componentA, 4), componentA);
-
- uint8x8x4_t destComponents = {{componentR, componentG, componentB, componentA}};
- vst4_u8(destination, destComponents);
- destination += 32;
- }
-
- source += pixelSize;
- pixelsPerRow = tailPixels;
-}
-
-ALWAYS_INLINE void packOneRowOfRGBA8ToUnsignedShort4444(const uint8_t*& source, uint16_t*& destination, unsigned& pixelsPerRow)
-{
- unsigned componentsPerRow = pixelsPerRow * 4;
- unsigned tailComponents = componentsPerRow % 32;
- unsigned componentsSize = componentsPerRow - tailComponents;
-
- uint8_t* dst = reinterpret_cast<uint8_t*>(destination);
- uint8x8_t immediate0xf0 = vdup_n_u8(0xF0);
- for (unsigned i = 0; i < componentsSize; i += 32) {
- uint8x8x4_t RGBA8 = vld4_u8(source + i);
-
- uint8x8_t componentR = vand_u8(RGBA8.val[0], immediate0xf0);
- uint8x8_t componentG = vshr_n_u8(vand_u8(RGBA8.val[1], immediate0xf0), 4);
- uint8x8_t componentB = vand_u8(RGBA8.val[2], immediate0xf0);
- uint8x8_t componentA = vshr_n_u8(vand_u8(RGBA8.val[3], immediate0xf0), 4);
-
- uint8x8x2_t RGBA4;
- RGBA4.val[0] = vorr_u8(componentB, componentA);
- RGBA4.val[1] = vorr_u8(componentR, componentG);
- vst2_u8(dst, RGBA4);
- dst += 16;
- }
-
- source += componentsSize;
- destination += componentsSize / 4;
- pixelsPerRow = tailComponents / 4;
-}
-
-ALWAYS_INLINE void unpackOneRowOfRGBA5551ToRGBA8(const uint16_t*& source, uint8_t*& destination, unsigned& pixelsPerRow)
-{
- unsigned tailPixels = pixelsPerRow % 8;
- unsigned pixelSize = pixelsPerRow - tailPixels;
-
- uint8x8_t immediate0x7 = vdup_n_u8(0x7);
- uint8x8_t immediate0xff = vdup_n_u8(0xFF);
- uint16x8_t immediate0x1f = vdupq_n_u16(0x1F);
- uint16x8_t immediate0x1 = vdupq_n_u16(0x1);
-
- for (unsigned i = 0; i < pixelSize; i += 8) {
- uint16x8_t eightPixels = vld1q_u16(source + i);
-
- uint8x8_t componentR = vqmovn_u16(vshrq_n_u16(eightPixels, 11));
- uint8x8_t componentG = vqmovn_u16(vandq_u16(vshrq_n_u16(eightPixels, 6), immediate0x1f));
- uint8x8_t componentB = vqmovn_u16(vandq_u16(vshrq_n_u16(eightPixels, 1), immediate0x1f));
- uint8x8_t componentA = vqmovn_u16(vandq_u16(eightPixels, immediate0x1));
-
- componentR = vorr_u8(vshl_n_u8(componentR, 3), vand_u8(componentR, immediate0x7));
- componentG = vorr_u8(vshl_n_u8(componentG, 3), vand_u8(componentG, immediate0x7));
- componentB = vorr_u8(vshl_n_u8(componentB, 3), vand_u8(componentB, immediate0x7));
- componentA = vmul_u8(componentA, immediate0xff);
-
- uint8x8x4_t destComponents = {{componentR, componentG, componentB, componentA}};
- vst4_u8(destination, destComponents);
- destination += 32;
- }
-
- source += pixelSize;
- pixelsPerRow = tailPixels;
-}
-
-ALWAYS_INLINE void packOneRowOfRGBA8ToUnsignedShort5551(const uint8_t*& source, uint16_t*& destination, unsigned& pixelsPerRow)
-{
- unsigned componentsPerRow = pixelsPerRow * 4;
- unsigned tailComponents = componentsPerRow % 32;
- unsigned componentsSize = componentsPerRow - tailComponents;
-
- uint8_t* dst = reinterpret_cast<uint8_t*>(destination);
-
- uint8x8_t immediate0xf8 = vdup_n_u8(0xF8);
- uint8x8_t immediate0x18 = vdup_n_u8(0x18);
- for (unsigned i = 0; i < componentsSize; i += 32) {
- uint8x8x4_t RGBA8 = vld4_u8(source + i);
-
- uint8x8_t componentR = vand_u8(RGBA8.val[0], immediate0xf8);
- uint8x8_t componentG3bit = vshr_n_u8(RGBA8.val[1], 5);
-
- uint8x8_t componentG2bit = vshl_n_u8(vand_u8(RGBA8.val[1], immediate0x18), 3);
- uint8x8_t componentB = vshr_n_u8(vand_u8(RGBA8.val[2], immediate0xf8), 2);
- uint8x8_t componentA = vshr_n_u8(RGBA8.val[3], 7);
-
- uint8x8x2_t RGBA5551;
- RGBA5551.val[0] = vorr_u8(vorr_u8(componentG2bit, componentB), componentA);
- RGBA5551.val[1] = vorr_u8(componentR, componentG3bit);
- vst2_u8(dst, RGBA5551);
- dst += 16;
- }
-
- source += componentsSize;
- destination += componentsSize / 4;
- pixelsPerRow = tailComponents / 4;
-}
-
-ALWAYS_INLINE void unpackOneRowOfRGB565ToRGBA8(const uint16_t*& source, uint8_t*& destination, unsigned& pixelsPerRow)
-{
- unsigned tailPixels = pixelsPerRow % 8;
- unsigned pixelSize = pixelsPerRow - tailPixels;
-
- uint16x8_t immediate0x3f = vdupq_n_u16(0x3F);
- uint16x8_t immediate0x1f = vdupq_n_u16(0x1F);
- uint8x8_t immediate0x3 = vdup_n_u8(0x3);
- uint8x8_t immediate0x7 = vdup_n_u8(0x7);
-
- uint8x8_t componentA = vdup_n_u8(0xFF);
-
- for (unsigned i = 0; i < pixelSize; i += 8) {
- uint16x8_t eightPixels = vld1q_u16(source + i);
-
- uint8x8_t componentR = vqmovn_u16(vshrq_n_u16(eightPixels, 11));
- uint8x8_t componentG = vqmovn_u16(vandq_u16(vshrq_n_u16(eightPixels, 5), immediate0x3f));
- uint8x8_t componentB = vqmovn_u16(vandq_u16(eightPixels, immediate0x1f));
-
- componentR = vorr_u8(vshl_n_u8(componentR, 3), vand_u8(componentR, immediate0x7));
- componentG = vorr_u8(vshl_n_u8(componentG, 2), vand_u8(componentG, immediate0x3));
- componentB = vorr_u8(vshl_n_u8(componentB, 3), vand_u8(componentB, immediate0x7));
-
- uint8x8x4_t destComponents = {{componentR, componentG, componentB, componentA}};
- vst4_u8(destination, destComponents);
- destination += 32;
- }
-
- source += pixelSize;
- pixelsPerRow = tailPixels;
-}
-
-ALWAYS_INLINE void packOneRowOfRGBA8ToUnsignedShort565(const uint8_t*& source, uint16_t*& destination, unsigned& pixelsPerRow)
-{
- unsigned componentsPerRow = pixelsPerRow * 4;
- unsigned tailComponents = componentsPerRow % 32;
- unsigned componentsSize = componentsPerRow - tailComponents;
- uint8_t* dst = reinterpret_cast<uint8_t*>(destination);
-
- uint8x8_t immediate0xf8 = vdup_n_u8(0xF8);
- uint8x8_t immediate0x1c = vdup_n_u8(0x1C);
- for (unsigned i = 0; i < componentsSize; i += 32) {
- uint8x8x4_t RGBA8 = vld4_u8(source + i);
-
- uint8x8_t componentR = vand_u8(RGBA8.val[0], immediate0xf8);
- uint8x8_t componentGLeft = vshr_n_u8(RGBA8.val[1], 5);
- uint8x8_t componentGRight = vshl_n_u8(vand_u8(RGBA8.val[1], immediate0x1c), 3);
- uint8x8_t componentB = vshr_n_u8(vand_u8(RGBA8.val[2], immediate0xf8), 3);
-
- uint8x8x2_t RGB565;
- RGB565.val[0] = vorr_u8(componentGRight, componentB);
- RGB565.val[1] = vorr_u8(componentR, componentGLeft);
- vst2_u8(dst, RGB565);
- dst += 16;
- }
-
- source += componentsSize;
- destination += componentsSize / 4;
- pixelsPerRow = tailComponents / 4;
-}
-
-} // namespace SIMD
-
-} // namespace WebCore
-
-#endif // HAVE(ARM_NEON_INTRINSICS)
-
-#endif // GraphicsContext3DNEON_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/cpu/arm/filters/FEBlendNEON.h b/chromium/third_party/WebKit/Source/core/platform/graphics/cpu/arm/filters/FEBlendNEON.h
deleted file mode 100644
index 4c84f716ecf..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/cpu/arm/filters/FEBlendNEON.h
+++ /dev/null
@@ -1,174 +0,0 @@
-/*
- * Copyright (C) 2012 University of Szeged
- * Copyright (C) 2012 Gabor Rapcsanyi
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY UNIVERSITY OF SZEGED ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL UNIVERSITY OF SZEGED OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef FEBlendNEON_h
-#define FEBlendNEON_h
-
-#include "core/platform/graphics/filters/FEBlend.h"
-
-#if HAVE(ARM_NEON_INTRINSICS)
-
-#include <arm_neon.h>
-
-namespace WebCore {
-
-class FEBlendUtilitiesNEON {
-public:
- static inline uint16x8_t div255(uint16x8_t num, uint16x8_t sixteenConst255, uint16x8_t sixteenConstOne)
- {
- uint16x8_t quotient = vshrq_n_u16(num, 8);
- uint16x8_t remainder = vaddq_u16(vsubq_u16(num, vmulq_u16(sixteenConst255, quotient)), sixteenConstOne);
- return vaddq_u16(quotient, vshrq_n_u16(remainder, 8));
- }
-
- static inline uint16x8_t normal(uint16x8_t pixelA, uint16x8_t pixelB, uint16x8_t alphaA, uint16x8_t,
- uint16x8_t sixteenConst255, uint16x8_t sixteenConstOne)
- {
- uint16x8_t tmp1 = vsubq_u16(sixteenConst255, alphaA);
- uint16x8_t tmp2 = vmulq_u16(tmp1, pixelB);
- uint16x8_t tmp3 = div255(tmp2, sixteenConst255, sixteenConstOne);
- return vaddq_u16(tmp3, pixelA);
- }
-
- static inline uint16x8_t multiply(uint16x8_t pixelA, uint16x8_t pixelB, uint16x8_t alphaA, uint16x8_t alphaB,
- uint16x8_t sixteenConst255, uint16x8_t sixteenConstOne)
- {
- uint16x8_t tmp1 = vsubq_u16(sixteenConst255, alphaA);
- uint16x8_t tmp2 = vmulq_u16(tmp1, pixelB);
- uint16x8_t tmp3 = vaddq_u16(vsubq_u16(sixteenConst255, alphaB), pixelB);
- uint16x8_t tmp4 = vmulq_u16(tmp3, pixelA);
- uint16x8_t tmp5 = vaddq_u16(tmp2, tmp4);
- return div255(tmp5, sixteenConst255, sixteenConstOne);
- }
-
- static inline uint16x8_t screen(uint16x8_t pixelA, uint16x8_t pixelB, uint16x8_t, uint16x8_t,
- uint16x8_t sixteenConst255, uint16x8_t sixteenConstOne)
- {
- uint16x8_t tmp1 = vaddq_u16(pixelA, pixelB);
- uint16x8_t tmp2 = vmulq_u16(pixelA, pixelB);
- uint16x8_t tmp3 = div255(tmp2, sixteenConst255, sixteenConstOne);
- return vsubq_u16(tmp1, tmp3);
- }
-
- static inline uint16x8_t darken(uint16x8_t pixelA, uint16x8_t pixelB, uint16x8_t alphaA, uint16x8_t alphaB,
- uint16x8_t sixteenConst255, uint16x8_t sixteenConstOne)
- {
- uint16x8_t tmp1 = vsubq_u16(sixteenConst255, alphaA);
- uint16x8_t tmp2 = vmulq_u16(tmp1, pixelB);
- uint16x8_t tmp3 = div255(tmp2, sixteenConst255, sixteenConstOne);
- uint16x8_t tmp4 = vaddq_u16(tmp3, pixelA);
-
- uint16x8_t tmp5 = vsubq_u16(sixteenConst255, alphaB);
- uint16x8_t tmp6 = vmulq_u16(tmp5, pixelA);
- uint16x8_t tmp7 = div255(tmp6, sixteenConst255, sixteenConstOne);
- uint16x8_t tmp8 = vaddq_u16(tmp7, pixelB);
-
- return vminq_u16(tmp4, tmp8);
- }
-
- static inline uint16x8_t lighten(uint16x8_t pixelA, uint16x8_t pixelB, uint16x8_t alphaA, uint16x8_t alphaB,
- uint16x8_t sixteenConst255, uint16x8_t sixteenConstOne)
- {
- uint16x8_t tmp1 = vsubq_u16(sixteenConst255, alphaA);
- uint16x8_t tmp2 = vmulq_u16(tmp1, pixelB);
- uint16x8_t tmp3 = div255(tmp2, sixteenConst255, sixteenConstOne);
- uint16x8_t tmp4 = vaddq_u16(tmp3, pixelA);
-
- uint16x8_t tmp5 = vsubq_u16(sixteenConst255, alphaB);
- uint16x8_t tmp6 = vmulq_u16(tmp5, pixelA);
- uint16x8_t tmp7 = div255(tmp6, sixteenConst255, sixteenConstOne);
- uint16x8_t tmp8 = vaddq_u16(tmp7, pixelB);
-
- return vmaxq_u16(tmp4, tmp8);
- }
-};
-
-void FEBlend::platformApplyNEON(unsigned char* srcPixelArrayA, unsigned char* srcPixelArrayB, unsigned char* dstPixelArray,
- unsigned colorArrayLength)
-{
- uint8_t* sourcePixelA = reinterpret_cast<uint8_t*>(srcPixelArrayA);
- uint8_t* sourcePixelB = reinterpret_cast<uint8_t*>(srcPixelArrayB);
- uint8_t* destinationPixel = reinterpret_cast<uint8_t*>(dstPixelArray);
-
- uint16x8_t sixteenConst255 = vdupq_n_u16(255);
- uint16x8_t sixteenConstOne = vdupq_n_u16(1);
-
- unsigned colorOffset = 0;
- while (colorOffset < colorArrayLength) {
- unsigned char alphaA1 = srcPixelArrayA[colorOffset + 3];
- unsigned char alphaB1 = srcPixelArrayB[colorOffset + 3];
- unsigned char alphaA2 = srcPixelArrayA[colorOffset + 7];
- unsigned char alphaB2 = srcPixelArrayB[colorOffset + 7];
-
- uint16x8_t doubblePixelA = vmovl_u8(vld1_u8(sourcePixelA + colorOffset));
- uint16x8_t doubblePixelB = vmovl_u8(vld1_u8(sourcePixelB + colorOffset));
- uint16x8_t alphaA = vcombine_u16(vdup_n_u16(alphaA1), vdup_n_u16(alphaA2));
- uint16x8_t alphaB = vcombine_u16(vdup_n_u16(alphaB1), vdup_n_u16(alphaB2));
-
- uint16x8_t result;
- switch (m_mode) {
- case FEBLEND_MODE_NORMAL:
- result = FEBlendUtilitiesNEON::normal(doubblePixelA, doubblePixelB, alphaA, alphaB, sixteenConst255, sixteenConstOne);
- break;
- case FEBLEND_MODE_MULTIPLY:
- result = FEBlendUtilitiesNEON::multiply(doubblePixelA, doubblePixelB, alphaA, alphaB, sixteenConst255, sixteenConstOne);
- break;
- case FEBLEND_MODE_SCREEN:
- result = FEBlendUtilitiesNEON::screen(doubblePixelA, doubblePixelB, alphaA, alphaB, sixteenConst255, sixteenConstOne);
- break;
- case FEBLEND_MODE_DARKEN:
- result = FEBlendUtilitiesNEON::darken(doubblePixelA, doubblePixelB, alphaA, alphaB, sixteenConst255, sixteenConstOne);
- break;
- case FEBLEND_MODE_LIGHTEN:
- result = FEBlendUtilitiesNEON::lighten(doubblePixelA, doubblePixelB, alphaA, alphaB, sixteenConst255, sixteenConstOne);
- break;
- case FEBLEND_MODE_UNKNOWN:
- default:
- result = vdupq_n_u16(0);
- break;
- }
-
- vst1_u8(destinationPixel + colorOffset, vmovn_u16(result));
-
- unsigned char alphaR1 = 255 - ((255 - alphaA1) * (255 - alphaB1)) / 255;
- unsigned char alphaR2 = 255 - ((255 - alphaA2) * (255 - alphaB2)) / 255;
-
- dstPixelArray[colorOffset + 3] = alphaR1;
- dstPixelArray[colorOffset + 7] = alphaR2;
-
- colorOffset += 8;
- if (colorOffset > colorArrayLength) {
- ASSERT(colorOffset - 4 == colorArrayLength);
- colorOffset = colorArrayLength - 8;
- }
- }
-}
-
-} // namespace WebCore
-
-#endif // HAVE(ARM_NEON_INTRINSICS)
-
-#endif // FEBlendNEON_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/cpu/arm/filters/FECompositeArithmeticNEON.h b/chromium/third_party/WebKit/Source/core/platform/graphics/cpu/arm/filters/FECompositeArithmeticNEON.h
deleted file mode 100644
index 4ff3d0b3d5d..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/cpu/arm/filters/FECompositeArithmeticNEON.h
+++ /dev/null
@@ -1,99 +0,0 @@
-/*
- * Copyright (C) 2011 University of Szeged
- * Copyright (C) 2011 Felician Marton
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY UNIVERSITY OF SZEGED ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL UNIVERSITY OF SZEGED OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef FECompositeArithmeticNEON_h
-#define FECompositeArithmeticNEON_h
-
-#if HAVE(ARM_NEON_INTRINSICS)
-
-#include <arm_neon.h>
-#include "core/platform/graphics/filters/FEComposite.h"
-
-namespace WebCore {
-
-template <int b1, int b4>
-inline void FEComposite::computeArithmeticPixelsNeon(unsigned char* source, unsigned char* destination,
- unsigned pixelArrayLength, float k1, float k2, float k3, float k4)
-{
- float32x4_t k1x4 = vdupq_n_f32(k1 / 255);
- float32x4_t k2x4 = vdupq_n_f32(k2);
- float32x4_t k3x4 = vdupq_n_f32(k3);
- float32x4_t k4x4 = vdupq_n_f32(k4 * 255);
- uint32x4_t max255 = vdupq_n_u32(255);
-
- uint32_t* sourcePixel = reinterpret_cast<uint32_t*>(source);
- uint32_t* destinationPixel = reinterpret_cast<uint32_t*>(destination);
- uint32_t* destinationEndPixel = destinationPixel + (pixelArrayLength >> 2);
-
- while (destinationPixel < destinationEndPixel) {
- uint32x2_t temporary1 = vset_lane_u32(*sourcePixel, temporary1, 0);
- uint16x4_t temporary2 = vget_low_u16(vmovl_u8(vreinterpret_u8_u32(temporary1)));
- float32x4_t sourcePixelAsFloat = vcvtq_f32_u32(vmovl_u16(temporary2));
-
- temporary1 = vset_lane_u32(*destinationPixel, temporary1, 0);
- temporary2 = vget_low_u16(vmovl_u8(vreinterpret_u8_u32(temporary1)));
- float32x4_t destinationPixelAsFloat = vcvtq_f32_u32(vmovl_u16(temporary2));
-
- float32x4_t result = vmulq_f32(sourcePixelAsFloat, k2x4);
- result = vmlaq_f32(result, destinationPixelAsFloat, k3x4);
- if (b1)
- result = vmlaq_f32(result, vmulq_f32(sourcePixelAsFloat, destinationPixelAsFloat), k1x4);
- if (b4)
- result = vaddq_f32(result, k4x4);
-
- // Convert result to uint so negative values are converted to zero.
- uint16x4_t temporary3 = vmovn_u32(vminq_u32(vcvtq_u32_f32(result), max255));
- uint8x8_t temporary4 = vmovn_u16(vcombine_u16(temporary3, temporary3));
- *destinationPixel++ = vget_lane_u32(vreinterpret_u32_u8(temporary4), 0);
- ++sourcePixel;
- }
-}
-
-inline void FEComposite::platformArithmeticNeon(unsigned char* source, unsigned char* destination,
- unsigned pixelArrayLength, float k1, float k2, float k3, float k4)
-{
- if (!k4) {
- if (!k1) {
- computeArithmeticPixelsNeon<0, 0>(source, destination, pixelArrayLength, k1, k2, k3, k4);
- return;
- }
-
- computeArithmeticPixelsNeon<1, 0>(source, destination, pixelArrayLength, k1, k2, k3, k4);
- return;
- }
-
- if (!k1) {
- computeArithmeticPixelsNeon<0, 1>(source, destination, pixelArrayLength, k1, k2, k3, k4);
- return;
- }
- computeArithmeticPixelsNeon<1, 1>(source, destination, pixelArrayLength, k1, k2, k3, k4);
-}
-
-} // namespace WebCore
-
-#endif // HAVE(ARM_NEON_INTRINSICS)
-
-#endif // FECompositeArithmeticNEON_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/cpu/arm/filters/FEGaussianBlurNEON.h b/chromium/third_party/WebKit/Source/core/platform/graphics/cpu/arm/filters/FEGaussianBlurNEON.h
deleted file mode 100644
index d1cd4d7abe2..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/cpu/arm/filters/FEGaussianBlurNEON.h
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * Copyright (C) 2011 University of Szeged
- * Copyright (C) 2011 Zoltan Herczeg
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY UNIVERSITY OF SZEGED ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL UNIVERSITY OF SZEGED OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef FEGaussianBlurNEON_h
-#define FEGaussianBlurNEON_h
-
-#if HAVE(ARM_NEON_INTRINSICS)
-
-#include "core/platform/graphics/cpu/arm/filters/NEONHelpers.h"
-#include "core/platform/graphics/filters/FEGaussianBlur.h"
-
-namespace WebCore {
-
-inline void boxBlurNEON(Uint8ClampedArray* srcPixelArray, Uint8ClampedArray* dstPixelArray,
- unsigned dx, int dxLeft, int dxRight, int stride, int strideLine, int effectWidth, int effectHeight)
-{
- uint32_t* sourcePixel = reinterpret_cast<uint32_t*>(srcPixelArray->data());
- uint32_t* destinationPixel = reinterpret_cast<uint32_t*>(dstPixelArray->data());
-
- float32x4_t deltaX = vdupq_n_f32(1.0 / dx);
- int pixelLine = strideLine / 4;
- int pixelStride = stride / 4;
-
- for (int y = 0; y < effectHeight; ++y) {
- int line = y * pixelLine;
- float32x4_t sum = vdupq_n_f32(0);
- // Fill the kernel
- int maxKernelSize = std::min(dxRight, effectWidth);
- for (int i = 0; i < maxKernelSize; ++i) {
- float32x4_t sourcePixelAsFloat = loadRGBA8AsFloat(sourcePixel + line + i * pixelStride);
- sum = vaddq_f32(sum, sourcePixelAsFloat);
- }
-
- // Blurring
- for (int x = 0; x < effectWidth; ++x) {
- int pixelOffset = line + x * pixelStride;
- float32x4_t result = vmulq_f32(sum, deltaX);
- storeFloatAsRGBA8(result, destinationPixel + pixelOffset);
- if (x >= dxLeft) {
- float32x4_t sourcePixelAsFloat = loadRGBA8AsFloat(sourcePixel + pixelOffset - dxLeft * pixelStride);
- sum = vsubq_f32(sum, sourcePixelAsFloat);
- }
- if (x + dxRight < effectWidth) {
- float32x4_t sourcePixelAsFloat = loadRGBA8AsFloat(sourcePixel + pixelOffset + dxRight * pixelStride);
- sum = vaddq_f32(sum, sourcePixelAsFloat);
- }
- }
- }
-}
-
-} // namespace WebCore
-
-#endif // HAVE(ARM_NEON_INTRINSICS)
-
-#endif // FEGaussianBlurNEON_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/cpu/arm/filters/FELightingNEON.h b/chromium/third_party/WebKit/Source/core/platform/graphics/cpu/arm/filters/FELightingNEON.h
deleted file mode 100644
index b255fd39aa2..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/cpu/arm/filters/FELightingNEON.h
+++ /dev/null
@@ -1,202 +0,0 @@
-/*
- * Copyright (C) 2011 University of Szeged
- * Copyright (C) 2011 Zoltan Herczeg
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY UNIVERSITY OF SZEGED ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL UNIVERSITY OF SZEGED OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef FELightingNEON_h
-#define FELightingNEON_h
-
-#if CPU(ARM_NEON) && CPU(ARM_TRADITIONAL) && COMPILER(GCC)
-
-#include "core/platform/graphics/filters/FELighting.h"
-#include "wtf/Alignment.h"
-#include "wtf/CPU.h"
-#include "wtf/ParallelJobs.h"
-
-namespace WebCore {
-
-// Otherwise: Distant Light.
-#define FLAG_POINT_LIGHT 0x01
-#define FLAG_SPOT_LIGHT 0x02
-#define FLAG_CONE_EXPONENT_IS_1 0x04
-
-// Otherwise: Diffuse light.
-#define FLAG_SPECULAR_LIGHT 0x10
-#define FLAG_DIFFUSE_CONST_IS_1 0x20
-#define FLAG_SPECULAR_EXPONENT_IS_1 0x40
-
-// Must be aligned to 16 bytes.
-struct FELightingFloatArgumentsForNeon {
- float surfaceScale;
- float minusSurfaceScaleDividedByFour;
- float diffuseConstant;
- float padding1;
-
- float coneCutOffLimit;
- float coneFullLight;
- float coneCutOffRange;
- float constOne;
-
- float lightX;
- float lightY;
- float lightZ;
- float padding2;
-
- float directionX;
- float directionY;
- float directionZ;
- float padding3;
-
- float colorRed;
- float colorGreen;
- float colorBlue;
- float padding4;
-};
-
-struct FELightingPaintingDataForNeon {
- unsigned char* pixels;
- float yStart;
- int widthDecreasedByTwo;
- int absoluteHeight;
- // Combination of FLAG constants above.
- int flags;
- int specularExponent;
- int coneExponent;
- FELightingFloatArgumentsForNeon* floatArguments;
- short* paintingConstants;
-};
-
-short* feLightingConstantsForNeon();
-
-extern "C" {
-void neonDrawLighting(FELightingPaintingDataForNeon*);
-}
-
-inline void FELighting::platformApplyNeon(LightingData& data, LightSource::PaintingData& paintingData)
-{
- WTF_ALIGNED(FELightingFloatArgumentsForNeon, floatArguments, 16);
-
- FELightingPaintingDataForNeon neonData = {
- data.pixels->data(),
- 1,
- data.widthDecreasedByOne - 1,
- data.heightDecreasedByOne - 1,
- 0,
- 0,
- 0,
- &floatArguments,
- feLightingConstantsForNeon()
- };
-
- // Set light source arguments.
- floatArguments.constOne = 1;
-
- floatArguments.colorRed = m_lightingColor.red();
- floatArguments.colorGreen = m_lightingColor.green();
- floatArguments.colorBlue = m_lightingColor.blue();
- floatArguments.padding4 = 0;
-
- if (m_lightSource->type() == LS_POINT) {
- neonData.flags |= FLAG_POINT_LIGHT;
- PointLightSource* pointLightSource = static_cast<PointLightSource*>(m_lightSource.get());
- floatArguments.lightX = pointLightSource->position().x();
- floatArguments.lightY = pointLightSource->position().y();
- floatArguments.lightZ = pointLightSource->position().z();
- floatArguments.padding2 = 0;
- } else if (m_lightSource->type() == LS_SPOT) {
- neonData.flags |= FLAG_SPOT_LIGHT;
- SpotLightSource* spotLightSource = static_cast<SpotLightSource*>(m_lightSource.get());
- floatArguments.lightX = spotLightSource->position().x();
- floatArguments.lightY = spotLightSource->position().y();
- floatArguments.lightZ = spotLightSource->position().z();
- floatArguments.padding2 = 0;
-
- floatArguments.directionX = paintingData.directionVector.x();
- floatArguments.directionY = paintingData.directionVector.y();
- floatArguments.directionZ = paintingData.directionVector.z();
- floatArguments.padding3 = 0;
-
- floatArguments.coneCutOffLimit = paintingData.coneCutOffLimit;
- floatArguments.coneFullLight = paintingData.coneFullLight;
- floatArguments.coneCutOffRange = paintingData.coneCutOffLimit - paintingData.coneFullLight;
- neonData.coneExponent = getPowerCoefficients(spotLightSource->specularExponent());
- if (spotLightSource->specularExponent() == 1)
- neonData.flags |= FLAG_CONE_EXPONENT_IS_1;
- } else {
- ASSERT(m_lightSource->type() == LS_DISTANT);
- floatArguments.lightX = paintingData.lightVector.x();
- floatArguments.lightY = paintingData.lightVector.y();
- floatArguments.lightZ = paintingData.lightVector.z();
- floatArguments.padding2 = 1;
- }
-
- // Set lighting arguments.
- floatArguments.surfaceScale = data.surfaceScale;
- floatArguments.minusSurfaceScaleDividedByFour = -data.surfaceScale / 4;
- if (m_lightingType == FELighting::DiffuseLighting)
- floatArguments.diffuseConstant = m_diffuseConstant;
- else {
- neonData.flags |= FLAG_SPECULAR_LIGHT;
- floatArguments.diffuseConstant = m_specularConstant;
- neonData.specularExponent = getPowerCoefficients(m_specularExponent);
- if (m_specularExponent == 1)
- neonData.flags |= FLAG_SPECULAR_EXPONENT_IS_1;
- }
- if (floatArguments.diffuseConstant == 1)
- neonData.flags |= FLAG_DIFFUSE_CONST_IS_1;
-
- int optimalThreadNumber = ((data.widthDecreasedByOne - 1) * (data.heightDecreasedByOne - 1)) / s_minimalRectDimension;
- if (optimalThreadNumber > 1) {
- // Initialize parallel jobs
- ParallelJobs<FELightingPaintingDataForNeon> parallelJobs(&WebCore::FELighting::platformApplyNeonWorker, optimalThreadNumber);
-
- // Fill the parameter array
- int job = parallelJobs.numberOfJobs();
- if (job > 1) {
- int yStart = 1;
- int yStep = (data.heightDecreasedByOne - 1) / job;
- for (--job; job >= 0; --job) {
- FELightingPaintingDataForNeon& params = parallelJobs.parameter(job);
- params = neonData;
- params.yStart = yStart;
- params.pixels += (yStart - 1) * (data.widthDecreasedByOne + 1) * 4;
- if (job > 0) {
- params.absoluteHeight = yStep;
- yStart += yStep;
- } else
- params.absoluteHeight = data.heightDecreasedByOne - yStart;
- }
- parallelJobs.execute();
- return;
- }
- }
-
- neonDrawLighting(&neonData);
-}
-
-} // namespace WebCore
-
-#endif // CPU(ARM_NEON) && COMPILER(GCC)
-
-#endif // FELightingNEON_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/cpu/arm/filters/NEONHelpers.h b/chromium/third_party/WebKit/Source/core/platform/graphics/cpu/arm/filters/NEONHelpers.h
deleted file mode 100644
index 3a13e4a4b94..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/cpu/arm/filters/NEONHelpers.h
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Copyright (C) 2012 University of Szeged
- * Copyright (C) 2012 Gabor Rapcsanyi
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY UNIVERSITY OF SZEGED ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL UNIVERSITY OF SZEGED OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef NEONHelpers_h
-#define NEONHelpers_h
-
-#if HAVE(ARM_NEON_INTRINSICS)
-
-#include <arm_neon.h>
-
-namespace WebCore {
-
-inline float32x4_t loadRGBA8AsFloat(uint32_t* source)
-{
- uint32x2_t temporary1 = {0, 0};
- temporary1 = vset_lane_u32(*source, temporary1, 0);
- uint16x4_t temporary2 = vget_low_u16(vmovl_u8(vreinterpret_u8_u32(temporary1)));
- return vcvtq_f32_u32(vmovl_u16(temporary2));
-}
-
-inline void storeFloatAsRGBA8(float32x4_t data, uint32_t* destination)
-{
- uint16x4_t temporary1 = vmovn_u32(vcvtq_u32_f32(data));
- uint8x8_t temporary2 = vmovn_u16(vcombine_u16(temporary1, temporary1));
- *destination = vget_lane_u32(vreinterpret_u32_u8(temporary2), 0);
-}
-
-} // namespace WebCore
-
-#endif // HAVE(ARM_NEON_INTRINSICS)
-
-#endif // NEONHelpers_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/DistantLightSource.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/DistantLightSource.cpp
deleted file mode 100644
index 25864af8699..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/DistantLightSource.cpp
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * Copyright (C) 2004, 2005, 2006, 2007 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2004, 2005 Rob Buis <buis@kde.org>
- * Copyright (C) 2005 Eric Seidel <eric@webkit.org>
- * Copyright (C) 2010 Zoltan Herczeg <zherczeg@webkit.org>
- * Copyright (C) 2011 University of Szeged
- * Copyright (C) 2011 Renata Hodovan <reni@webkit.org>
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY UNIVERSITY OF SZEGED ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL UNIVERSITY OF SZEGED OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/platform/graphics/filters/DistantLightSource.h"
-
-#include "core/rendering/RenderTreeAsText.h"
-
-namespace WebCore {
-
-void DistantLightSource::initPaintingData(PaintingData& paintingData)
-{
- float azimuth = deg2rad(m_azimuth);
- float elevation = deg2rad(m_elevation);
- paintingData.lightVector.setX(cosf(azimuth) * cosf(elevation));
- paintingData.lightVector.setY(sinf(azimuth) * cosf(elevation));
- paintingData.lightVector.setZ(sinf(elevation));
- paintingData.lightVectorLength = 1;
-}
-
-void DistantLightSource::updatePaintingData(PaintingData&, int, int, float)
-{
-}
-
-bool DistantLightSource::setAzimuth(float azimuth)
-{
- if (m_azimuth == azimuth)
- return false;
- m_azimuth = azimuth;
- return true;
-}
-
-bool DistantLightSource::setElevation(float elevation)
-{
- if (m_elevation == elevation)
- return false;
- m_elevation = elevation;
- return true;
-}
-
-TextStream& DistantLightSource::externalRepresentation(TextStream& ts) const
-{
- ts << "[type=DISTANT-LIGHT] ";
- ts << "[azimuth=\"" << azimuth() << "\"]";
- ts << "[elevation=\"" << elevation() << "\"]";
- return ts;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/DistantLightSource.h b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/DistantLightSource.h
deleted file mode 100644
index 8999bf5b425..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/DistantLightSource.h
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * Copyright (C) 2008 Alex Mathews <possessedpenguinbob@gmail.com>
- * Copyright (C) 2004, 2005, 2006, 2007 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2004, 2005 Rob Buis <buis@kde.org>
- * Copyright (C) 2005 Eric Seidel <eric@webkit.org>
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#ifndef DistantLightSource_h
-#define DistantLightSource_h
-
-#include "core/platform/graphics/filters/LightSource.h"
-
-namespace WebCore {
-
-class DistantLightSource : public LightSource {
-public:
- static PassRefPtr<DistantLightSource> create(float azimuth, float elevation)
- {
- return adoptRef(new DistantLightSource(azimuth, elevation));
- }
-
- float azimuth() const { return m_azimuth; }
- float elevation() const { return m_elevation; }
-
- virtual bool setAzimuth(float) OVERRIDE;
- virtual bool setElevation(float) OVERRIDE;
-
- virtual void initPaintingData(PaintingData&);
- virtual void updatePaintingData(PaintingData&, int x, int y, float z);
-
- virtual TextStream& externalRepresentation(TextStream&) const;
-
-private:
- DistantLightSource(float azimuth, float elevation)
- : LightSource(LS_DISTANT)
- , m_azimuth(azimuth)
- , m_elevation(elevation)
- {
- }
-
- float m_azimuth;
- float m_elevation;
-};
-
-} // namespace WebCore
-
-#endif // DistantLightSource_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEBlend.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEBlend.cpp
deleted file mode 100644
index 78d2bec24dc..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEBlend.cpp
+++ /dev/null
@@ -1,289 +0,0 @@
-/*
- * Copyright (C) 2004, 2005, 2006, 2007 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2004, 2005 Rob Buis <buis@kde.org>
- * Copyright (C) 2005 Eric Seidel <eric@webkit.org>
- * Copyright (C) 2009 Dirk Schulze <krit@webkit.org>
- * Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies)
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-
-#include "core/platform/graphics/cpu/arm/filters/FEBlendNEON.h"
-#include "core/platform/graphics/filters/FEBlend.h"
-
-#include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/graphics/filters/Filter.h"
-#include "core/platform/text/TextStream.h"
-#include "core/rendering/RenderTreeAsText.h"
-
-#include "wtf/Uint8ClampedArray.h"
-
-#include "SkBitmapSource.h"
-#include "SkXfermodeImageFilter.h"
-#include "core/platform/graphics/filters/SkiaImageFilterBuilder.h"
-#include "core/platform/graphics/skia/NativeImageSkia.h"
-
-typedef unsigned char (*BlendType)(unsigned char colorA, unsigned char colorB, unsigned char alphaA, unsigned char alphaB);
-
-namespace WebCore {
-
-FEBlend::FEBlend(Filter* filter, BlendModeType mode)
- : FilterEffect(filter)
- , m_mode(mode)
-{
-}
-
-PassRefPtr<FEBlend> FEBlend::create(Filter* filter, BlendModeType mode)
-{
- return adoptRef(new FEBlend(filter, mode));
-}
-
-BlendModeType FEBlend::blendMode() const
-{
- return m_mode;
-}
-
-bool FEBlend::setBlendMode(BlendModeType mode)
-{
- if (m_mode == mode)
- return false;
- m_mode = mode;
- return true;
-}
-
-static inline unsigned char fastDivideBy255(uint16_t value)
-{
- // This is an approximate algorithm for division by 255, but it gives accurate results for 16bit values.
- uint16_t quotient = value >> 8;
- uint16_t remainder = value - (quotient * 255) + 1;
- return quotient + (remainder >> 8);
-}
-
-inline unsigned char feBlendNormal(unsigned char colorA, unsigned char colorB, unsigned char alphaA, unsigned char)
-{
- return fastDivideBy255((255 - alphaA) * colorB + colorA * 255);
-}
-
-inline unsigned char feBlendMultiply(unsigned char colorA, unsigned char colorB, unsigned char alphaA, unsigned char alphaB)
-{
- return fastDivideBy255((255 - alphaA) * colorB + (255 - alphaB + colorB) * colorA);
-}
-
-inline unsigned char feBlendScreen(unsigned char colorA, unsigned char colorB, unsigned char, unsigned char)
-{
- return fastDivideBy255((colorB + colorA) * 255 - colorA * colorB);
-}
-
-inline unsigned char feBlendDarken(unsigned char colorA, unsigned char colorB, unsigned char alphaA, unsigned char alphaB)
-{
- return fastDivideBy255(std::min((255 - alphaA) * colorB + colorA * 255, (255 - alphaB) * colorA + colorB * 255));
-}
-
-inline unsigned char feBlendLighten(unsigned char colorA, unsigned char colorB, unsigned char alphaA, unsigned char alphaB)
-{
- return fastDivideBy255(std::max((255 - alphaA) * colorB + colorA * 255, (255 - alphaB) * colorA + colorB * 255));
-}
-
-inline unsigned char feBlendUnknown(unsigned char, unsigned char, unsigned char, unsigned char)
-{
- return 0;
-}
-
-template<BlendType BlendFunction>
-static void platformApply(unsigned char* sourcePixelA, unsigned char* sourcePixelB,
- unsigned char* destinationPixel, unsigned pixelArrayLength)
-{
- unsigned len = pixelArrayLength / 4;
- for (unsigned pixelOffset = 0; pixelOffset < len; pixelOffset++) {
- unsigned char alphaA = sourcePixelA[3];
- unsigned char alphaB = sourcePixelB[3];
- destinationPixel[0] = BlendFunction(sourcePixelA[0], sourcePixelB[0], alphaA, alphaB);
- destinationPixel[1] = BlendFunction(sourcePixelA[1], sourcePixelB[1], alphaA, alphaB);
- destinationPixel[2] = BlendFunction(sourcePixelA[2], sourcePixelB[2], alphaA, alphaB);
- destinationPixel[3] = 255 - fastDivideBy255((255 - alphaA) * (255 - alphaB));
- sourcePixelA += 4;
- sourcePixelB += 4;
- destinationPixel += 4;
- }
-}
-
-void FEBlend::platformApplyGeneric(unsigned char* sourcePixelA, unsigned char* sourcePixelB,
- unsigned char* destinationPixel, unsigned pixelArrayLength)
-{
- switch (m_mode) {
- case FEBLEND_MODE_NORMAL:
- platformApply<feBlendNormal>(sourcePixelA, sourcePixelB, destinationPixel, pixelArrayLength);
- break;
- case FEBLEND_MODE_MULTIPLY:
- platformApply<feBlendMultiply>(sourcePixelA, sourcePixelB, destinationPixel, pixelArrayLength);
- break;
- case FEBLEND_MODE_SCREEN:
- platformApply<feBlendScreen>(sourcePixelA, sourcePixelB, destinationPixel, pixelArrayLength);
- break;
- case FEBLEND_MODE_DARKEN:
- platformApply<feBlendDarken>(sourcePixelA, sourcePixelB, destinationPixel, pixelArrayLength);
- break;
- case FEBLEND_MODE_LIGHTEN:
- platformApply<feBlendLighten>(sourcePixelA, sourcePixelB, destinationPixel, pixelArrayLength);
- break;
- case FEBLEND_MODE_UNKNOWN:
- platformApply<feBlendUnknown>(sourcePixelA, sourcePixelB, destinationPixel, pixelArrayLength);
- break;
- }
-}
-
-void FEBlend::applySoftware()
-{
- FilterEffect* in = inputEffect(0);
- FilterEffect* in2 = inputEffect(1);
-
- ASSERT(m_mode > FEBLEND_MODE_UNKNOWN);
- ASSERT(m_mode <= FEBLEND_MODE_LIGHTEN);
-
- Uint8ClampedArray* dstPixelArray = createPremultipliedImageResult();
- if (!dstPixelArray)
- return;
-
- IntRect effectADrawingRect = requestedRegionOfInputImageData(in->absolutePaintRect());
- RefPtr<Uint8ClampedArray> srcPixelArrayA = in->asPremultipliedImage(effectADrawingRect);
-
- IntRect effectBDrawingRect = requestedRegionOfInputImageData(in2->absolutePaintRect());
- RefPtr<Uint8ClampedArray> srcPixelArrayB = in2->asPremultipliedImage(effectBDrawingRect);
-
- unsigned pixelArrayLength = srcPixelArrayA->length();
- ASSERT(pixelArrayLength == srcPixelArrayB->length());
-
-#if HAVE(ARM_NEON_INTRINSICS)
- if (pixelArrayLength >= 8)
- platformApplyNEON(srcPixelArrayA->data(), srcPixelArrayB->data(), dstPixelArray->data(), pixelArrayLength);
- else { // If there is just one pixel we expand it to two.
- ASSERT(pixelArrayLength > 0);
- uint32_t sourceA[2] = {0, 0};
- uint32_t sourceBAndDest[2] = {0, 0};
-
- sourceA[0] = reinterpret_cast<uint32_t*>(srcPixelArrayA->data())[0];
- sourceBAndDest[0] = reinterpret_cast<uint32_t*>(srcPixelArrayB->data())[0];
- platformApplyNEON(reinterpret_cast<uint8_t*>(sourceA), reinterpret_cast<uint8_t*>(sourceBAndDest), reinterpret_cast<uint8_t*>(sourceBAndDest), 8);
- reinterpret_cast<uint32_t*>(dstPixelArray->data())[0] = sourceBAndDest[0];
- }
-#else
- platformApplyGeneric(srcPixelArrayA->data(), srcPixelArrayB->data(), dstPixelArray->data(), pixelArrayLength);
-#endif
-}
-
-static SkXfermode::Mode toSkiaMode(BlendModeType mode)
-{
- switch (mode) {
- case FEBLEND_MODE_NORMAL:
- return SkXfermode::kSrcOver_Mode;
- case FEBLEND_MODE_MULTIPLY:
- return SkXfermode::kMultiply_Mode;
- case FEBLEND_MODE_SCREEN:
- return SkXfermode::kScreen_Mode;
- case FEBLEND_MODE_DARKEN:
- return SkXfermode::kDarken_Mode;
- case FEBLEND_MODE_LIGHTEN:
- return SkXfermode::kLighten_Mode;
- default:
- return SkXfermode::kSrcOver_Mode;
- }
-}
-
-bool FEBlend::applySkia()
-{
- // For now, only use the skia implementation for accelerated rendering.
- if (filter()->renderingMode() != Accelerated)
- return false;
-
- FilterEffect* in = inputEffect(0);
- FilterEffect* in2 = inputEffect(1);
-
- if (!in || !in2)
- return false;
-
- ImageBuffer* resultImage = createImageBufferResult();
- if (!resultImage)
- return false;
-
- RefPtr<Image> foreground = in->asImageBuffer()->copyImage(DontCopyBackingStore);
- RefPtr<Image> background = in2->asImageBuffer()->copyImage(DontCopyBackingStore);
-
- RefPtr<NativeImageSkia> foregroundNativeImage = foreground->nativeImageForCurrentFrame();
- RefPtr<NativeImageSkia> backgroundNativeImage = background->nativeImageForCurrentFrame();
-
- if (!foregroundNativeImage || !backgroundNativeImage)
- return false;
-
- SkBitmap foregroundBitmap = foregroundNativeImage->bitmap();
- SkBitmap backgroundBitmap = backgroundNativeImage->bitmap();
-
- SkAutoTUnref<SkImageFilter> backgroundSource(new SkBitmapSource(backgroundBitmap));
- SkAutoTUnref<SkXfermode> mode(SkXfermode::Create(toSkiaMode(m_mode)));
- SkAutoTUnref<SkImageFilter> blend(new SkXfermodeImageFilter(mode, backgroundSource));
- SkPaint paint;
- paint.setImageFilter(blend);
- resultImage->context()->drawBitmap(foregroundBitmap, 0, 0, &paint);
- return true;
-}
-
-PassRefPtr<SkImageFilter> FEBlend::createImageFilter(SkiaImageFilterBuilder* builder)
-{
- RefPtr<SkImageFilter> foreground(builder->build(inputEffect(0), operatingColorSpace()));
- RefPtr<SkImageFilter> background(builder->build(inputEffect(1), operatingColorSpace()));
- SkAutoTUnref<SkXfermode> mode(SkXfermode::Create(toSkiaMode(m_mode)));
- return adoptRef(new SkXfermodeImageFilter(mode, background.get(), foreground.get()));
-}
-
-static TextStream& operator<<(TextStream& ts, const BlendModeType& type)
-{
- switch (type) {
- case FEBLEND_MODE_UNKNOWN:
- ts << "UNKNOWN";
- break;
- case FEBLEND_MODE_NORMAL:
- ts << "NORMAL";
- break;
- case FEBLEND_MODE_MULTIPLY:
- ts << "MULTIPLY";
- break;
- case FEBLEND_MODE_SCREEN:
- ts << "SCREEN";
- break;
- case FEBLEND_MODE_DARKEN:
- ts << "DARKEN";
- break;
- case FEBLEND_MODE_LIGHTEN:
- ts << "LIGHTEN";
- break;
- }
- return ts;
-}
-
-TextStream& FEBlend::externalRepresentation(TextStream& ts, int indent) const
-{
- writeIndent(ts, indent);
- ts << "[feBlend";
- FilterEffect::externalRepresentation(ts);
- ts << " mode=\"" << m_mode << "\"]\n";
- inputEffect(0)->externalRepresentation(ts, indent + 1);
- inputEffect(1)->externalRepresentation(ts, indent + 1);
- return ts;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEBlend.h b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEBlend.h
deleted file mode 100644
index 5185beb02e8..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEBlend.h
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Copyright (C) 2004, 2005, 2006, 2007 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2004, 2005 Rob Buis <buis@kde.org>
- * Copyright (C) 2005 Eric Seidel <eric@webkit.org>
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#ifndef FEBlend_h
-#define FEBlend_h
-
-#include "core/platform/graphics/filters/FilterEffect.h"
-
-#include "core/platform/graphics/filters/Filter.h"
-
-namespace WebCore {
-
-enum BlendModeType {
- FEBLEND_MODE_UNKNOWN = 0,
- FEBLEND_MODE_NORMAL = 1,
- FEBLEND_MODE_MULTIPLY = 2,
- FEBLEND_MODE_SCREEN = 3,
- FEBLEND_MODE_DARKEN = 4,
- FEBLEND_MODE_LIGHTEN = 5
-};
-
-class FEBlend : public FilterEffect {
-public:
- static PassRefPtr<FEBlend> create(Filter*, BlendModeType);
-
- BlendModeType blendMode() const;
- bool setBlendMode(BlendModeType);
-
- void platformApplyGeneric(unsigned char* srcPixelArrayA, unsigned char* srcPixelArrayB, unsigned char* dstPixelArray,
- unsigned colorArrayLength);
- void platformApplyNEON(unsigned char* srcPixelArrayA, unsigned char* srcPixelArrayB, unsigned char* dstPixelArray,
- unsigned colorArrayLength);
- virtual PassRefPtr<SkImageFilter> createImageFilter(SkiaImageFilterBuilder*) OVERRIDE;
-
- virtual TextStream& externalRepresentation(TextStream&, int indention) const;
-
-private:
- FEBlend(Filter*, BlendModeType);
-
- virtual void applySoftware() OVERRIDE;
- virtual bool applySkia() OVERRIDE;
-
- BlendModeType m_mode;
-};
-
-} // namespace WebCore
-
-#endif // FEBlend_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEColorMatrix.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEColorMatrix.cpp
deleted file mode 100644
index 4d8c45afaee..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEColorMatrix.cpp
+++ /dev/null
@@ -1,337 +0,0 @@
-/*
- * Copyright (C) 2004, 2005, 2006, 2007 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2004, 2005 Rob Buis <buis@kde.org>
- * Copyright (C) 2005 Eric Seidel <eric@webkit.org>
- * Copyright (C) 2009 Dirk Schulze <krit@webkit.org>
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-
-#include "core/platform/graphics/filters/FEColorMatrix.h"
-
-#include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/graphics/filters/Filter.h"
-#include "core/platform/graphics/filters/SkiaImageFilterBuilder.h"
-#include "core/platform/graphics/skia/NativeImageSkia.h"
-#include "core/platform/text/TextStream.h"
-#include "core/rendering/RenderTreeAsText.h"
-
-#include "wtf/MathExtras.h"
-#include "wtf/Uint8ClampedArray.h"
-
-#include "SkColorFilterImageFilter.h"
-#include "SkColorMatrixFilter.h"
-
-namespace WebCore {
-
-FEColorMatrix::FEColorMatrix(Filter* filter, ColorMatrixType type, const Vector<float>& values)
- : FilterEffect(filter)
- , m_type(type)
- , m_values(values)
-{
-}
-
-PassRefPtr<FEColorMatrix> FEColorMatrix::create(Filter* filter, ColorMatrixType type, const Vector<float>& values)
-{
- return adoptRef(new FEColorMatrix(filter, type, values));
-}
-
-ColorMatrixType FEColorMatrix::type() const
-{
- return m_type;
-}
-
-bool FEColorMatrix::setType(ColorMatrixType type)
-{
- if (m_type == type)
- return false;
- m_type = type;
- return true;
-}
-
-const Vector<float>& FEColorMatrix::values() const
-{
- return m_values;
-}
-
-bool FEColorMatrix::setValues(const Vector<float> &values)
-{
- if (m_values == values)
- return false;
- m_values = values;
- return true;
-}
-
-inline void matrix(float& red, float& green, float& blue, float& alpha, const Vector<float>& values)
-{
- float r = values[0] * red + values[1] * green + values[2] * blue + values[3] * alpha + values[4] * 255;
- float g = values[5] * red + values[6] * green + values[7] * blue + values[8] * alpha + values[9] * 255;
- float b = values[10] * red + values[11] * green + values[12] * blue + values[13] * alpha + values[14] * 255;
- float a = values[15] * red + values[16] * green + values[17] * blue + values[18] * alpha + values[19] * 255;
-
- red = r;
- green = g;
- blue = b;
- alpha = a;
-}
-
-inline void saturateAndHueRotate(float& red, float& green, float& blue, const float* components)
-{
- float r = red * components[0] + green * components[1] + blue * components[2];
- float g = red * components[3] + green * components[4] + blue * components[5];
- float b = red * components[6] + green * components[7] + blue * components[8];
-
- red = r;
- green = g;
- blue = b;
-}
-
-inline void luminance(float& red, float& green, float& blue, float& alpha)
-{
- alpha = 0.2125 * red + 0.7154 * green + 0.0721 * blue;
- red = 0;
- green = 0;
- blue = 0;
-}
-
-template<ColorMatrixType filterType>
-void effectType(Uint8ClampedArray* pixelArray, const Vector<float>& values)
-{
- unsigned pixelArrayLength = pixelArray->length();
- float components[9];
-
- if (filterType == FECOLORMATRIX_TYPE_SATURATE)
- FEColorMatrix::calculateSaturateComponents(components, values[0]);
- else if (filterType == FECOLORMATRIX_TYPE_HUEROTATE)
- FEColorMatrix::calculateHueRotateComponents(components, values[0]);
-
- for (unsigned pixelByteOffset = 0; pixelByteOffset < pixelArrayLength; pixelByteOffset += 4) {
- float red = pixelArray->item(pixelByteOffset);
- float green = pixelArray->item(pixelByteOffset + 1);
- float blue = pixelArray->item(pixelByteOffset + 2);
- float alpha = pixelArray->item(pixelByteOffset + 3);
-
- switch (filterType) {
- case FECOLORMATRIX_TYPE_MATRIX:
- matrix(red, green, blue, alpha, values);
- break;
- case FECOLORMATRIX_TYPE_SATURATE:
- case FECOLORMATRIX_TYPE_HUEROTATE:
- saturateAndHueRotate(red, green, blue, components);
- break;
- case FECOLORMATRIX_TYPE_LUMINANCETOALPHA:
- luminance(red, green, blue, alpha);
- break;
- }
-
- pixelArray->set(pixelByteOffset, red);
- pixelArray->set(pixelByteOffset + 1, green);
- pixelArray->set(pixelByteOffset + 2, blue);
- pixelArray->set(pixelByteOffset + 3, alpha);
- }
-}
-
-void FEColorMatrix::applySoftware()
-{
- FilterEffect* in = inputEffect(0);
-
- ImageBuffer* resultImage = createImageBufferResult();
- if (!resultImage)
- return;
-
- resultImage->context()->drawImageBuffer(in->asImageBuffer(), drawingRegionOfInputImage(in->absolutePaintRect()));
-
- IntRect imageRect(IntPoint(), absolutePaintRect().size());
- RefPtr<Uint8ClampedArray> pixelArray = resultImage->getUnmultipliedImageData(imageRect);
-
- switch (m_type) {
- case FECOLORMATRIX_TYPE_UNKNOWN:
- break;
- case FECOLORMATRIX_TYPE_MATRIX:
- effectType<FECOLORMATRIX_TYPE_MATRIX>(pixelArray.get(), m_values);
- break;
- case FECOLORMATRIX_TYPE_SATURATE:
- effectType<FECOLORMATRIX_TYPE_SATURATE>(pixelArray.get(), m_values);
- break;
- case FECOLORMATRIX_TYPE_HUEROTATE:
- effectType<FECOLORMATRIX_TYPE_HUEROTATE>(pixelArray.get(), m_values);
- break;
- case FECOLORMATRIX_TYPE_LUMINANCETOALPHA:
- effectType<FECOLORMATRIX_TYPE_LUMINANCETOALPHA>(pixelArray.get(), m_values);
- setIsAlphaImage(true);
- break;
- }
-
- resultImage->putByteArray(Unmultiplied, pixelArray.get(), imageRect.size(), imageRect, IntPoint());
-}
-
-static void saturateMatrix(float s, SkScalar matrix[20])
-{
- matrix[0] = 0.213f + 0.787f * s;
- matrix[1] = 0.715f - 0.715f * s;
- matrix[2] = 0.072f - 0.072f * s;
- matrix[3] = matrix[4] = 0;
- matrix[5] = 0.213f - 0.213f * s;
- matrix[6] = 0.715f + 0.285f * s;
- matrix[7] = 0.072f - 0.072f * s;
- matrix[8] = matrix[9] = 0;
- matrix[10] = 0.213f - 0.213f * s;
- matrix[11] = 0.715f - 0.715f * s;
- matrix[12] = 0.072f + 0.928f * s;
- matrix[13] = matrix[14] = 0;
- matrix[15] = matrix[16] = matrix[17] = 0;
- matrix[18] = 1;
- matrix[19] = 0;
-}
-
-static void hueRotateMatrix(float hue, SkScalar matrix[20])
-{
- float cosHue = cosf(hue * piFloat / 180);
- float sinHue = sinf(hue * piFloat / 180);
- matrix[0] = 0.213f + cosHue * 0.787f - sinHue * 0.213f;
- matrix[1] = 0.715f - cosHue * 0.715f - sinHue * 0.715f;
- matrix[2] = 0.072f - cosHue * 0.072f + sinHue * 0.928f;
- matrix[3] = matrix[4] = 0;
- matrix[5] = 0.213f - cosHue * 0.213f + sinHue * 0.143f;
- matrix[6] = 0.715f + cosHue * 0.285f + sinHue * 0.140f;
- matrix[7] = 0.072f - cosHue * 0.072f - sinHue * 0.283f;
- matrix[8] = matrix[9] = 0;
- matrix[10] = 0.213f - cosHue * 0.213f - sinHue * 0.787f;
- matrix[11] = 0.715f - cosHue * 0.715f + sinHue * 0.715f;
- matrix[12] = 0.072f + cosHue * 0.928f + sinHue * 0.072f;
- matrix[13] = matrix[14] = 0;
- matrix[15] = matrix[16] = matrix[17] = 0;
- matrix[18] = 1;
- matrix[19] = 0;
-}
-
-static void luminanceToAlphaMatrix(SkScalar matrix[20])
-{
- memset(matrix, 0, 20 * sizeof(SkScalar));
- matrix[15] = 0.2125f;
- matrix[16] = 0.7154f;
- matrix[17] = 0.0721f;
-}
-
-static SkColorFilter* createColorFilter(ColorMatrixType type, const float* values)
-{
- SkScalar matrix[20];
- switch (type) {
- case FECOLORMATRIX_TYPE_UNKNOWN:
- break;
- case FECOLORMATRIX_TYPE_MATRIX:
- for (int i = 0; i < 20; ++i)
- matrix[i] = values[i];
-
- matrix[4] *= SkScalar(255);
- matrix[9] *= SkScalar(255);
- matrix[14] *= SkScalar(255);
- matrix[19] *= SkScalar(255);
- break;
- case FECOLORMATRIX_TYPE_SATURATE:
- saturateMatrix(values[0], matrix);
- break;
- case FECOLORMATRIX_TYPE_HUEROTATE:
- hueRotateMatrix(values[0], matrix);
- break;
- case FECOLORMATRIX_TYPE_LUMINANCETOALPHA:
- luminanceToAlphaMatrix(matrix);
- break;
- }
- return new SkColorMatrixFilter(matrix);
-}
-
-bool FEColorMatrix::applySkia()
-{
- ImageBuffer* resultImage = createImageBufferResult();
- if (!resultImage)
- return false;
-
- FilterEffect* in = inputEffect(0);
-
- SkRect drawingRegion = drawingRegionOfInputImage(in->absolutePaintRect());
-
- SkAutoTUnref<SkColorFilter> filter(createColorFilter(m_type, m_values.data()));
-
- RefPtr<Image> image = in->asImageBuffer()->copyImage(DontCopyBackingStore);
- RefPtr<NativeImageSkia> nativeImage = image->nativeImageForCurrentFrame();
- if (!nativeImage)
- return false;
-
- SkPaint paint;
- paint.setColorFilter(filter);
- paint.setXfermodeMode(SkXfermode::kSrc_Mode);
- resultImage->context()->drawBitmap(nativeImage->bitmap(), drawingRegion.fLeft, drawingRegion.fTop, &paint);
- return true;
-}
-
-PassRefPtr<SkImageFilter> FEColorMatrix::createImageFilter(SkiaImageFilterBuilder* builder)
-{
- RefPtr<SkImageFilter> input(builder->build(inputEffect(0), operatingColorSpace()));
- SkAutoTUnref<SkColorFilter> filter(createColorFilter(m_type, m_values.data()));
- SkIRect rect = getCropRect(builder->cropOffset());
- return adoptRef(SkColorFilterImageFilter::Create(filter, input.get(), &rect));
-}
-
-static TextStream& operator<<(TextStream& ts, const ColorMatrixType& type)
-{
- switch (type) {
- case FECOLORMATRIX_TYPE_UNKNOWN:
- ts << "UNKNOWN";
- break;
- case FECOLORMATRIX_TYPE_MATRIX:
- ts << "MATRIX";
- break;
- case FECOLORMATRIX_TYPE_SATURATE:
- ts << "SATURATE";
- break;
- case FECOLORMATRIX_TYPE_HUEROTATE:
- ts << "HUEROTATE";
- break;
- case FECOLORMATRIX_TYPE_LUMINANCETOALPHA:
- ts << "LUMINANCETOALPHA";
- break;
- }
- return ts;
-}
-
-TextStream& FEColorMatrix::externalRepresentation(TextStream& ts, int indent) const
-{
- writeIndent(ts, indent);
- ts << "[feColorMatrix";
- FilterEffect::externalRepresentation(ts);
- ts << " type=\"" << m_type << "\"";
- if (!m_values.isEmpty()) {
- ts << " values=\"";
- Vector<float>::const_iterator ptr = m_values.begin();
- const Vector<float>::const_iterator end = m_values.end();
- while (ptr < end) {
- ts << *ptr;
- ++ptr;
- if (ptr < end)
- ts << " ";
- }
- ts << "\"";
- }
- ts << "]\n";
- inputEffect(0)->externalRepresentation(ts, indent + 1);
- return ts;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEColorMatrix.h b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEColorMatrix.h
deleted file mode 100644
index 718817bc751..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEColorMatrix.h
+++ /dev/null
@@ -1,99 +0,0 @@
-/*
- * Copyright (C) 2004, 2005, 2006, 2007 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2004, 2005 Rob Buis <buis@kde.org>
- * Copyright (C) 2005 Eric Seidel <eric@webkit.org>
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#ifndef FEColorMatrix_h
-#define FEColorMatrix_h
-
-#include "core/platform/graphics/filters/FilterEffect.h"
-
-#include "core/platform/graphics/filters/Filter.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-enum ColorMatrixType {
- FECOLORMATRIX_TYPE_UNKNOWN = 0,
- FECOLORMATRIX_TYPE_MATRIX = 1,
- FECOLORMATRIX_TYPE_SATURATE = 2,
- FECOLORMATRIX_TYPE_HUEROTATE = 3,
- FECOLORMATRIX_TYPE_LUMINANCETOALPHA = 4
-};
-
-class FEColorMatrix : public FilterEffect {
-public:
- static PassRefPtr<FEColorMatrix> create(Filter*, ColorMatrixType, const Vector<float>&);
-
- ColorMatrixType type() const;
- bool setType(ColorMatrixType);
-
- const Vector<float>& values() const;
- bool setValues(const Vector<float>&);
-
- virtual PassRefPtr<SkImageFilter> createImageFilter(SkiaImageFilterBuilder*) OVERRIDE;
-
- virtual TextStream& externalRepresentation(TextStream&, int indention) const;
-
- static inline void calculateSaturateComponents(float* components, float value);
- static inline void calculateHueRotateComponents(float* components, float value);
-
-private:
- FEColorMatrix(Filter*, ColorMatrixType, const Vector<float>&);
-
- virtual void applySoftware() OVERRIDE;
- virtual bool applySkia() OVERRIDE;
-
- ColorMatrixType m_type;
- Vector<float> m_values;
-};
-
-inline void FEColorMatrix::calculateSaturateComponents(float* components, float value)
-{
- components[0] = (0.213 + 0.787 * value);
- components[1] = (0.715 - 0.715 * value);
- components[2] = (0.072 - 0.072 * value);
- components[3] = (0.213 - 0.213 * value);
- components[4] = (0.715 + 0.285 * value);
- components[5] = (0.072 - 0.072 * value);
- components[6] = (0.213 - 0.213 * value);
- components[7] = (0.715 - 0.715 * value);
- components[8] = (0.072 + 0.928 * value);
-}
-
-inline void FEColorMatrix::calculateHueRotateComponents(float* components, float value)
-{
- float cosHue = cos(value * piFloat / 180);
- float sinHue = sin(value * piFloat / 180);
- components[0] = 0.213 + cosHue * 0.787 - sinHue * 0.213;
- components[1] = 0.715 - cosHue * 0.715 - sinHue * 0.715;
- components[2] = 0.072 - cosHue * 0.072 + sinHue * 0.928;
- components[3] = 0.213 - cosHue * 0.213 + sinHue * 0.143;
- components[4] = 0.715 + cosHue * 0.285 + sinHue * 0.140;
- components[5] = 0.072 - cosHue * 0.072 - sinHue * 0.283;
- components[6] = 0.213 - cosHue * 0.213 - sinHue * 0.787;
- components[7] = 0.715 - cosHue * 0.715 + sinHue * 0.715;
- components[8] = 0.072 + cosHue * 0.928 + sinHue * 0.072;
-}
-
-
-} // namespace WebCore
-
-#endif // FEColorMatrix_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEComponentTransfer.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEComponentTransfer.cpp
deleted file mode 100644
index 18f783a03d4..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEComponentTransfer.cpp
+++ /dev/null
@@ -1,286 +0,0 @@
-/*
- * Copyright (C) 2004, 2005, 2006, 2007 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2004, 2005 Rob Buis <buis@kde.org>
- * Copyright (C) 2005 Eric Seidel <eric@webkit.org>
- * Copyright (C) 2009 Dirk Schulze <krit@webkit.org>
- * Copyright (C) Research In Motion Limited 2010. All rights reserved.
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-
-#include "core/platform/graphics/filters/FEComponentTransfer.h"
-
-#include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/graphics/filters/Filter.h"
-#include "core/platform/text/TextStream.h"
-#include "core/rendering/RenderTreeAsText.h"
-
-#include "wtf/MathExtras.h"
-#include "wtf/StdLibExtras.h"
-#include "wtf/Uint8ClampedArray.h"
-
-#include "SkColorFilterImageFilter.h"
-#include "SkTableColorFilter.h"
-#include "core/platform/graphics/filters/SkiaImageFilterBuilder.h"
-#include "core/platform/graphics/skia/NativeImageSkia.h"
-
-namespace WebCore {
-
-typedef void (*TransferType)(unsigned char*, const ComponentTransferFunction&);
-
-FEComponentTransfer::FEComponentTransfer(Filter* filter, const ComponentTransferFunction& redFunc, const ComponentTransferFunction& greenFunc,
- const ComponentTransferFunction& blueFunc, const ComponentTransferFunction& alphaFunc)
- : FilterEffect(filter)
- , m_redFunc(redFunc)
- , m_greenFunc(greenFunc)
- , m_blueFunc(blueFunc)
- , m_alphaFunc(alphaFunc)
-{
-}
-
-PassRefPtr<FEComponentTransfer> FEComponentTransfer::create(Filter* filter, const ComponentTransferFunction& redFunc,
- const ComponentTransferFunction& greenFunc, const ComponentTransferFunction& blueFunc, const ComponentTransferFunction& alphaFunc)
-{
- return adoptRef(new FEComponentTransfer(filter, redFunc, greenFunc, blueFunc, alphaFunc));
-}
-
-ComponentTransferFunction FEComponentTransfer::redFunction() const
-{
- return m_redFunc;
-}
-
-void FEComponentTransfer::setRedFunction(const ComponentTransferFunction& func)
-{
- m_redFunc = func;
-}
-
-ComponentTransferFunction FEComponentTransfer::greenFunction() const
-{
- return m_greenFunc;
-}
-
-void FEComponentTransfer::setGreenFunction(const ComponentTransferFunction& func)
-{
- m_greenFunc = func;
-}
-
-ComponentTransferFunction FEComponentTransfer::blueFunction() const
-{
- return m_blueFunc;
-}
-
-void FEComponentTransfer::setBlueFunction(const ComponentTransferFunction& func)
-{
- m_blueFunc = func;
-}
-
-ComponentTransferFunction FEComponentTransfer::alphaFunction() const
-{
- return m_alphaFunc;
-}
-
-void FEComponentTransfer::setAlphaFunction(const ComponentTransferFunction& func)
-{
- m_alphaFunc = func;
-}
-
-static void identity(unsigned char*, const ComponentTransferFunction&)
-{
-}
-
-static void table(unsigned char* values, const ComponentTransferFunction& transferFunction)
-{
- const Vector<float>& tableValues = transferFunction.tableValues;
- unsigned n = tableValues.size();
- if (n < 1)
- return;
- for (unsigned i = 0; i < 256; ++i) {
- double c = i / 255.0;
- unsigned k = static_cast<unsigned>(c * (n - 1));
- double v1 = tableValues[k];
- double v2 = tableValues[std::min((k + 1), (n - 1))];
- double val = 255.0 * (v1 + (c * (n - 1) - k) * (v2 - v1));
- val = std::max(0.0, std::min(255.0, val));
- values[i] = static_cast<unsigned char>(val);
- }
-}
-
-static void discrete(unsigned char* values, const ComponentTransferFunction& transferFunction)
-{
- const Vector<float>& tableValues = transferFunction.tableValues;
- unsigned n = tableValues.size();
- if (n < 1)
- return;
- for (unsigned i = 0; i < 256; ++i) {
- unsigned k = static_cast<unsigned>((i * n) / 255.0);
- k = std::min(k, n - 1);
- double val = 255 * tableValues[k];
- val = std::max(0.0, std::min(255.0, val));
- values[i] = static_cast<unsigned char>(val);
- }
-}
-
-static void linear(unsigned char* values, const ComponentTransferFunction& transferFunction)
-{
- for (unsigned i = 0; i < 256; ++i) {
- double val = transferFunction.slope * i + 255 * transferFunction.intercept;
- val = std::max(0.0, std::min(255.0, val));
- values[i] = static_cast<unsigned char>(val);
- }
-}
-
-static void gamma(unsigned char* values, const ComponentTransferFunction& transferFunction)
-{
- for (unsigned i = 0; i < 256; ++i) {
- double exponent = transferFunction.exponent; // RCVT doesn't like passing a double and a float to pow, so promote this to double
- double val = 255.0 * (transferFunction.amplitude * pow((i / 255.0), exponent) + transferFunction.offset);
- val = std::max(0.0, std::min(255.0, val));
- values[i] = static_cast<unsigned char>(val);
- }
-}
-
-void FEComponentTransfer::applySoftware()
-{
- FilterEffect* in = inputEffect(0);
-
- Uint8ClampedArray* pixelArray = createUnmultipliedImageResult();
- if (!pixelArray)
- return;
-
- unsigned char rValues[256], gValues[256], bValues[256], aValues[256];
- getValues(rValues, gValues, bValues, aValues);
- unsigned char* tables[] = { rValues, gValues, bValues, aValues };
-
- IntRect drawingRect = requestedRegionOfInputImageData(in->absolutePaintRect());
- in->copyUnmultipliedImage(pixelArray, drawingRect);
-
- unsigned pixelArrayLength = pixelArray->length();
- for (unsigned pixelOffset = 0; pixelOffset < pixelArrayLength; pixelOffset += 4) {
- for (unsigned channel = 0; channel < 4; ++channel) {
- unsigned char c = pixelArray->item(pixelOffset + channel);
- pixelArray->set(pixelOffset + channel, tables[channel][c]);
- }
- }
-}
-
-bool FEComponentTransfer::applySkia()
-{
- FilterEffect* in = inputEffect(0);
- ImageBuffer* resultImage = createImageBufferResult();
- if (!resultImage)
- return false;
-
- RefPtr<Image> image = in->asImageBuffer()->copyImage(DontCopyBackingStore);
- RefPtr<NativeImageSkia> nativeImage = image->nativeImageForCurrentFrame();
- if (!nativeImage)
- return false;
-
- unsigned char rValues[256], gValues[256], bValues[256], aValues[256];
- getValues(rValues, gValues, bValues, aValues);
-
- SkPaint paint;
- paint.setColorFilter(SkTableColorFilter::CreateARGB(aValues, rValues, gValues, bValues))->unref();
- paint.setXfermodeMode(SkXfermode::kSrc_Mode);
- resultImage->context()->drawBitmap(nativeImage->bitmap(), 0, 0, &paint);
-
- return true;
-}
-
-PassRefPtr<SkImageFilter> FEComponentTransfer::createImageFilter(SkiaImageFilterBuilder* builder)
-{
- RefPtr<SkImageFilter> input(builder->build(inputEffect(0), operatingColorSpace()));
-
- unsigned char rValues[256], gValues[256], bValues[256], aValues[256];
- getValues(rValues, gValues, bValues, aValues);
-
- SkAutoTUnref<SkColorFilter> colorFilter(SkTableColorFilter::CreateARGB(aValues, rValues, gValues, bValues));
-
- SkIRect cropRect = getCropRect(builder->cropOffset());
- return adoptRef(SkColorFilterImageFilter::Create(colorFilter, input.get(), &cropRect));
-}
-
-void FEComponentTransfer::getValues(unsigned char rValues[256], unsigned char gValues[256], unsigned char bValues[256], unsigned char aValues[256])
-{
- for (unsigned i = 0; i < 256; ++i)
- rValues[i] = gValues[i] = bValues[i] = aValues[i] = i;
- unsigned char* tables[] = { rValues, gValues, bValues, aValues };
- ComponentTransferFunction transferFunction[] = {m_redFunc, m_greenFunc, m_blueFunc, m_alphaFunc};
- TransferType callEffect[] = {identity, identity, table, discrete, linear, gamma};
-
- for (unsigned channel = 0; channel < 4; channel++) {
- ASSERT_WITH_SECURITY_IMPLICATION(static_cast<size_t>(transferFunction[channel].type) < WTF_ARRAY_LENGTH(callEffect));
- (*callEffect[transferFunction[channel].type])(tables[channel], transferFunction[channel]);
- }
-}
-
-static TextStream& operator<<(TextStream& ts, const ComponentTransferType& type)
-{
- switch (type) {
- case FECOMPONENTTRANSFER_TYPE_UNKNOWN:
- ts << "UNKNOWN";
- break;
- case FECOMPONENTTRANSFER_TYPE_IDENTITY:
- ts << "IDENTITY";
- break;
- case FECOMPONENTTRANSFER_TYPE_TABLE:
- ts << "TABLE";
- break;
- case FECOMPONENTTRANSFER_TYPE_DISCRETE:
- ts << "DISCRETE";
- break;
- case FECOMPONENTTRANSFER_TYPE_LINEAR:
- ts << "LINEAR";
- break;
- case FECOMPONENTTRANSFER_TYPE_GAMMA:
- ts << "GAMMA";
- break;
- }
- return ts;
-}
-
-static TextStream& operator<<(TextStream& ts, const ComponentTransferFunction& function)
-{
- ts << "type=\"" << function.type
- << "\" slope=\"" << function.slope
- << "\" intercept=\"" << function.intercept
- << "\" amplitude=\"" << function.amplitude
- << "\" exponent=\"" << function.exponent
- << "\" offset=\"" << function.offset << "\"";
- return ts;
-}
-
-TextStream& FEComponentTransfer::externalRepresentation(TextStream& ts, int indent) const
-{
- writeIndent(ts, indent);
- ts << "[feComponentTransfer";
- FilterEffect::externalRepresentation(ts);
- ts << " \n";
- writeIndent(ts, indent + 2);
- ts << "{red: " << m_redFunc << "}\n";
- writeIndent(ts, indent + 2);
- ts << "{green: " << m_greenFunc << "}\n";
- writeIndent(ts, indent + 2);
- ts << "{blue: " << m_blueFunc << "}\n";
- writeIndent(ts, indent + 2);
- ts << "{alpha: " << m_alphaFunc << "}]\n";
- inputEffect(0)->externalRepresentation(ts, indent + 1);
- return ts;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEComponentTransfer.h b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEComponentTransfer.h
deleted file mode 100644
index 2b7d4cbba18..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEComponentTransfer.h
+++ /dev/null
@@ -1,102 +0,0 @@
-/*
- * Copyright (C) 2004, 2005, 2006, 2007 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2004, 2005 Rob Buis <buis@kde.org>
- * Copyright (C) 2005 Eric Seidel <eric@webkit.org>
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#ifndef FEComponentTransfer_h
-#define FEComponentTransfer_h
-
-#include "core/platform/graphics/filters/FilterEffect.h"
-
-#include "core/platform/graphics/filters/Filter.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-enum ComponentTransferType {
- FECOMPONENTTRANSFER_TYPE_UNKNOWN = 0,
- FECOMPONENTTRANSFER_TYPE_IDENTITY = 1,
- FECOMPONENTTRANSFER_TYPE_TABLE = 2,
- FECOMPONENTTRANSFER_TYPE_DISCRETE = 3,
- FECOMPONENTTRANSFER_TYPE_LINEAR = 4,
- FECOMPONENTTRANSFER_TYPE_GAMMA = 5
-};
-
-struct ComponentTransferFunction {
- ComponentTransferFunction()
- : type(FECOMPONENTTRANSFER_TYPE_UNKNOWN)
- , slope(0)
- , intercept(0)
- , amplitude(0)
- , exponent(0)
- , offset(0)
- {
- }
-
- ComponentTransferType type;
-
- float slope;
- float intercept;
- float amplitude;
- float exponent;
- float offset;
-
- Vector<float> tableValues;
-};
-
-class FEComponentTransfer : public FilterEffect {
-public:
- static PassRefPtr<FEComponentTransfer> create(Filter*, const ComponentTransferFunction& redFunc, const ComponentTransferFunction& greenFunc,
- const ComponentTransferFunction& blueFunc, const ComponentTransferFunction& alphaFunc);
-
- ComponentTransferFunction redFunction() const;
- void setRedFunction(const ComponentTransferFunction&);
-
- ComponentTransferFunction greenFunction() const;
- void setGreenFunction(const ComponentTransferFunction&);
-
- ComponentTransferFunction blueFunction() const;
- void setBlueFunction(const ComponentTransferFunction&);
-
- ComponentTransferFunction alphaFunction() const;
- void setAlphaFunction(const ComponentTransferFunction&);
-
- virtual PassRefPtr<SkImageFilter> createImageFilter(SkiaImageFilterBuilder*) OVERRIDE;
-
- virtual TextStream& externalRepresentation(TextStream&, int indention) const;
-
-private:
- FEComponentTransfer(Filter*, const ComponentTransferFunction& redFunc, const ComponentTransferFunction& greenFunc,
- const ComponentTransferFunction& blueFunc, const ComponentTransferFunction& alphaFunc);
-
- virtual void applySoftware() OVERRIDE;
- virtual bool applySkia() OVERRIDE;
-
- void getValues(unsigned char rValues[256], unsigned char gValues[256], unsigned char bValues[256], unsigned char aValues[256]);
-
- ComponentTransferFunction m_redFunc;
- ComponentTransferFunction m_greenFunc;
- ComponentTransferFunction m_blueFunc;
- ComponentTransferFunction m_alphaFunc;
-};
-
-} // namespace WebCore
-
-#endif // FEComponentTransfer_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEComposite.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEComposite.cpp
deleted file mode 100644
index c8d996acd5c..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEComposite.cpp
+++ /dev/null
@@ -1,461 +0,0 @@
-/*
- * Copyright (C) 2004, 2005, 2006, 2007 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2004, 2005 Rob Buis <buis@kde.org>
- * Copyright (C) 2005 Eric Seidel <eric@webkit.org>
- * Copyright (C) 2009 Dirk Schulze <krit@webkit.org>
- * Copyright (C) Research In Motion Limited 2010. All rights reserved.
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-
-#include "core/platform/graphics/filters/FEComposite.h"
-
-#include "SkArithmeticMode.h"
-#include "SkFlattenableBuffers.h"
-#include "SkXfermodeImageFilter.h"
-
-#include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/graphics/cpu/arm/filters/FECompositeArithmeticNEON.h"
-#include "core/platform/graphics/filters/Filter.h"
-#include "core/platform/text/TextStream.h"
-#include "core/rendering/RenderTreeAsText.h"
-#include "third_party/skia/include/core/SkDevice.h"
-
-#include "wtf/Uint8ClampedArray.h"
-
-#include "core/platform/graphics/filters/SkiaImageFilterBuilder.h"
-
-namespace WebCore {
-
-class CompositeImageFilter : public SkImageFilter {
-public:
- CompositeImageFilter(SkXfermode::Mode mode, SkImageFilter* background, SkImageFilter* foreground, const SkIRect* cropRect) : SkImageFilter(background, foreground, cropRect), m_mode(mode)
- {
- }
-
- virtual bool onFilterImage(Proxy* proxy, const SkBitmap& src, const SkMatrix& ctm, SkBitmap* dst, SkIPoint* offset)
- {
- SkBitmap background = src;
- SkBitmap foreground = src;
- SkImageFilter* backgroundInput = getInput(0);
- SkImageFilter* foregroundInput = getInput(1);
- SkIPoint backgroundOffset = SkIPoint::Make(0, 0), foregroundOffset = SkIPoint::Make(0, 0);
- if (backgroundInput && !backgroundInput->filterImage(proxy, src, ctm, &background, &backgroundOffset))
- return false;
-
- if (foregroundInput && !foregroundInput->filterImage(proxy, src, ctm, &foreground, &foregroundOffset))
- return false;
-
- SkIRect bounds;
- background.getBounds(&bounds);
- if (!applyCropRect(&bounds, ctm)) {
- return false;
- }
- backgroundOffset.fX -= bounds.left();
- backgroundOffset.fY -= bounds.top();
- foregroundOffset.fX -= bounds.left();
- foregroundOffset.fY -= bounds.top();
-
- SkAutoTUnref<SkBaseDevice> device(proxy->createDevice(bounds.width(), bounds.height()));
- SkCanvas canvas(device);
- SkPaint paint;
- paint.setXfermodeMode(SkXfermode::kSrc_Mode);
- canvas.drawBitmap(background, backgroundOffset.fX, backgroundOffset.fY, &paint);
- paint.setXfermodeMode(m_mode);
- canvas.drawBitmap(foreground, foregroundOffset.fX, foregroundOffset.fY, &paint);
- *dst = device->accessBitmap(false);
- offset->fX += bounds.left();
- offset->fY += bounds.top();
- return true;
- }
-
- SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(CompositeImageFilter)
-
-protected:
- explicit CompositeImageFilter(SkFlattenableReadBuffer& buffer)
- : SkImageFilter(buffer)
- {
- m_mode = (SkXfermode::Mode) buffer.readInt();
- }
-
- virtual void flatten(SkFlattenableWriteBuffer& buffer) const
- {
- this->SkImageFilter::flatten(buffer);
- buffer.writeInt((int) m_mode);
- }
-
-private:
- SkXfermode::Mode m_mode;
-};
-
-FEComposite::FEComposite(Filter* filter, const CompositeOperationType& type, float k1, float k2, float k3, float k4)
- : FilterEffect(filter)
- , m_type(type)
- , m_k1(k1)
- , m_k2(k2)
- , m_k3(k3)
- , m_k4(k4)
-{
-}
-
-PassRefPtr<FEComposite> FEComposite::create(Filter* filter, const CompositeOperationType& type, float k1, float k2, float k3, float k4)
-{
- return adoptRef(new FEComposite(filter, type, k1, k2, k3, k4));
-}
-
-CompositeOperationType FEComposite::operation() const
-{
- return m_type;
-}
-
-bool FEComposite::setOperation(CompositeOperationType type)
-{
- if (m_type == type)
- return false;
- m_type = type;
- return true;
-}
-
-float FEComposite::k1() const
-{
- return m_k1;
-}
-
-bool FEComposite::setK1(float k1)
-{
- if (m_k1 == k1)
- return false;
- m_k1 = k1;
- return true;
-}
-
-float FEComposite::k2() const
-{
- return m_k2;
-}
-
-bool FEComposite::setK2(float k2)
-{
- if (m_k2 == k2)
- return false;
- m_k2 = k2;
- return true;
-}
-
-float FEComposite::k3() const
-{
- return m_k3;
-}
-
-bool FEComposite::setK3(float k3)
-{
- if (m_k3 == k3)
- return false;
- m_k3 = k3;
- return true;
-}
-
-float FEComposite::k4() const
-{
- return m_k4;
-}
-
-bool FEComposite::setK4(float k4)
-{
- if (m_k4 == k4)
- return false;
- m_k4 = k4;
- return true;
-}
-
-void FEComposite::correctFilterResultIfNeeded()
-{
- if (m_type != FECOMPOSITE_OPERATOR_ARITHMETIC)
- return;
-
- forceValidPreMultipliedPixels();
-}
-
-template <int b1, int b4>
-static inline void computeArithmeticPixels(unsigned char* source, unsigned char* destination, int pixelArrayLength,
- float k1, float k2, float k3, float k4)
-{
- float scaledK1;
- float scaledK4;
- if (b1)
- scaledK1 = k1 / 255.0f;
- if (b4)
- scaledK4 = k4 * 255.0f;
-
- while (--pixelArrayLength >= 0) {
- unsigned char i1 = *source;
- unsigned char i2 = *destination;
- float result = k2 * i1 + k3 * i2;
- if (b1)
- result += scaledK1 * i1 * i2;
- if (b4)
- result += scaledK4;
-
- if (result <= 0)
- *destination = 0;
- else if (result >= 255)
- *destination = 255;
- else
- *destination = result;
- ++source;
- ++destination;
- }
-}
-
-// computeArithmeticPixelsUnclamped is a faster version of computeArithmeticPixels for the common case where clamping
-// is not necessary. This enables aggresive compiler optimizations such as auto-vectorization.
-template <int b1, int b4>
-static inline void computeArithmeticPixelsUnclamped(unsigned char* source, unsigned char* destination, int pixelArrayLength, float k1, float k2, float k3, float k4)
-{
- float scaledK1;
- float scaledK4;
- if (b1)
- scaledK1 = k1 / 255.0f;
- if (b4)
- scaledK4 = k4 * 255.0f;
-
- while (--pixelArrayLength >= 0) {
- unsigned char i1 = *source;
- unsigned char i2 = *destination;
- float result = k2 * i1 + k3 * i2;
- if (b1)
- result += scaledK1 * i1 * i2;
- if (b4)
- result += scaledK4;
-
- *destination = result;
- ++source;
- ++destination;
- }
-}
-
-static inline void arithmeticSoftware(unsigned char* source, unsigned char* destination, int pixelArrayLength, float k1, float k2, float k3, float k4)
-{
- float upperLimit = std::max(0.0f, k1) + std::max(0.0f, k2) + std::max(0.0f, k3) + k4;
- float lowerLimit = std::min(0.0f, k1) + std::min(0.0f, k2) + std::min(0.0f, k3) + k4;
- if ((k4 >= 0.0f && k4 <= 1.0f) && (upperLimit >= 0.0f && upperLimit <= 1.0f) && (lowerLimit >= 0.0f && lowerLimit <= 1.0f)) {
- if (k4) {
- if (k1)
- computeArithmeticPixelsUnclamped<1, 1>(source, destination, pixelArrayLength, k1, k2, k3, k4);
- else
- computeArithmeticPixelsUnclamped<0, 1>(source, destination, pixelArrayLength, k1, k2, k3, k4);
- } else {
- if (k1)
- computeArithmeticPixelsUnclamped<1, 0>(source, destination, pixelArrayLength, k1, k2, k3, k4);
- else
- computeArithmeticPixelsUnclamped<0, 0>(source, destination, pixelArrayLength, k1, k2, k3, k4);
- }
- return;
- }
-
- if (k4) {
- if (k1)
- computeArithmeticPixels<1, 1>(source, destination, pixelArrayLength, k1, k2, k3, k4);
- else
- computeArithmeticPixels<0, 1>(source, destination, pixelArrayLength, k1, k2, k3, k4);
- } else {
- if (k1)
- computeArithmeticPixels<1, 0>(source, destination, pixelArrayLength, k1, k2, k3, k4);
- else
- computeArithmeticPixels<0, 0>(source, destination, pixelArrayLength, k1, k2, k3, k4);
- }
-}
-
-inline void FEComposite::platformArithmeticSoftware(Uint8ClampedArray* source, Uint8ClampedArray* destination,
- float k1, float k2, float k3, float k4)
-{
- int length = source->length();
- ASSERT(length == static_cast<int>(destination->length()));
- // The selection here eventually should happen dynamically.
-#if HAVE(ARM_NEON_INTRINSICS)
- ASSERT(!(length & 0x3));
- platformArithmeticNeon(source->data(), destination->data(), length, k1, k2, k3, k4);
-#else
- arithmeticSoftware(source->data(), destination->data(), length, k1, k2, k3, k4);
-#endif
-}
-
-void FEComposite::determineAbsolutePaintRect()
-{
- switch (m_type) {
- case FECOMPOSITE_OPERATOR_IN:
- case FECOMPOSITE_OPERATOR_ATOP:
- // For In and Atop the first effect just influences the result of
- // the second effect. So just use the absolute paint rect of the second effect here.
- setAbsolutePaintRect(inputEffect(1)->absolutePaintRect());
- return;
- case FECOMPOSITE_OPERATOR_ARITHMETIC:
- // Arithmetic may influnce the compele filter primitive region. So we can't
- // optimize the paint region here.
- setAbsolutePaintRect(enclosingIntRect(maxEffectRect()));
- return;
- default:
- // Take the union of both input effects.
- FilterEffect::determineAbsolutePaintRect();
- return;
- }
-}
-
-void FEComposite::applySoftware()
-{
- FilterEffect* in = inputEffect(0);
- FilterEffect* in2 = inputEffect(1);
-
- if (m_type == FECOMPOSITE_OPERATOR_ARITHMETIC) {
- Uint8ClampedArray* dstPixelArray = createPremultipliedImageResult();
- if (!dstPixelArray)
- return;
-
- IntRect effectADrawingRect = requestedRegionOfInputImageData(in->absolutePaintRect());
- RefPtr<Uint8ClampedArray> srcPixelArray = in->asPremultipliedImage(effectADrawingRect);
-
- IntRect effectBDrawingRect = requestedRegionOfInputImageData(in2->absolutePaintRect());
- in2->copyPremultipliedImage(dstPixelArray, effectBDrawingRect);
-
- platformArithmeticSoftware(srcPixelArray.get(), dstPixelArray, m_k1, m_k2, m_k3, m_k4);
- return;
- }
-
- ImageBuffer* resultImage = createImageBufferResult();
- if (!resultImage)
- return;
- GraphicsContext* filterContext = resultImage->context();
-
- ImageBuffer* imageBuffer = in->asImageBuffer();
- ImageBuffer* imageBuffer2 = in2->asImageBuffer();
- ASSERT(imageBuffer);
- ASSERT(imageBuffer2);
-
- switch (m_type) {
- case FECOMPOSITE_OPERATOR_OVER:
- filterContext->drawImageBuffer(imageBuffer2, drawingRegionOfInputImage(in2->absolutePaintRect()));
- filterContext->drawImageBuffer(imageBuffer, drawingRegionOfInputImage(in->absolutePaintRect()));
- break;
- case FECOMPOSITE_OPERATOR_IN: {
- // Applies only to the intersected region.
- IntRect destinationRect = in->absolutePaintRect();
- destinationRect.intersect(in2->absolutePaintRect());
- destinationRect.intersect(absolutePaintRect());
- if (destinationRect.isEmpty())
- break;
- IntPoint destinationPoint(destinationRect.x() - absolutePaintRect().x(), destinationRect.y() - absolutePaintRect().y());
- IntRect sourceRect(IntPoint(destinationRect.x() - in->absolutePaintRect().x(),
- destinationRect.y() - in->absolutePaintRect().y()), destinationRect.size());
- IntRect source2Rect(IntPoint(destinationRect.x() - in2->absolutePaintRect().x(),
- destinationRect.y() - in2->absolutePaintRect().y()), destinationRect.size());
- filterContext->drawImageBuffer(imageBuffer2, destinationPoint, source2Rect);
- filterContext->drawImageBuffer(imageBuffer, destinationPoint, sourceRect, CompositeSourceIn);
- break;
- }
- case FECOMPOSITE_OPERATOR_OUT:
- filterContext->drawImageBuffer(imageBuffer, drawingRegionOfInputImage(in->absolutePaintRect()));
- filterContext->drawImageBuffer(imageBuffer2, drawingRegionOfInputImage(in2->absolutePaintRect()), IntRect(IntPoint(), imageBuffer2->logicalSize()), CompositeDestinationOut);
- break;
- case FECOMPOSITE_OPERATOR_ATOP:
- filterContext->drawImageBuffer(imageBuffer2, drawingRegionOfInputImage(in2->absolutePaintRect()));
- filterContext->drawImageBuffer(imageBuffer, drawingRegionOfInputImage(in->absolutePaintRect()), IntRect(IntPoint(), imageBuffer->logicalSize()), CompositeSourceAtop);
- break;
- case FECOMPOSITE_OPERATOR_XOR:
- filterContext->drawImageBuffer(imageBuffer2, drawingRegionOfInputImage(in2->absolutePaintRect()));
- filterContext->drawImageBuffer(imageBuffer, drawingRegionOfInputImage(in->absolutePaintRect()), IntRect(IntPoint(), imageBuffer->logicalSize()), CompositeXOR);
- break;
- default:
- break;
- }
-}
-
-SkXfermode::Mode toXfermode(WebCore::CompositeOperationType mode)
-{
- switch (mode) {
- case WebCore::FECOMPOSITE_OPERATOR_OVER:
- return SkXfermode::kSrcOver_Mode;
- case WebCore::FECOMPOSITE_OPERATOR_IN:
- return SkXfermode::kSrcIn_Mode;
- case WebCore::FECOMPOSITE_OPERATOR_OUT:
- return SkXfermode::kSrcOut_Mode;
- case WebCore::FECOMPOSITE_OPERATOR_ATOP:
- return SkXfermode::kSrcATop_Mode;
- case WebCore::FECOMPOSITE_OPERATOR_XOR:
- return SkXfermode::kXor_Mode;
- default:
- ASSERT_NOT_REACHED();
- return SkXfermode::kSrcOver_Mode;
- }
-}
-
-PassRefPtr<SkImageFilter> FEComposite::createImageFilter(SkiaImageFilterBuilder* builder)
-{
- RefPtr<SkImageFilter> foreground(builder->build(inputEffect(0), operatingColorSpace()));
- RefPtr<SkImageFilter> background(builder->build(inputEffect(1), operatingColorSpace()));
- if (m_type == FECOMPOSITE_OPERATOR_ARITHMETIC) {
- SkAutoTUnref<SkXfermode> mode(SkArithmeticMode::Create(SkFloatToScalar(m_k1), SkFloatToScalar(m_k2), SkFloatToScalar(m_k3), SkFloatToScalar(m_k4)));
- return adoptRef(new SkXfermodeImageFilter(mode, background.get(), foreground.get()));
- }
- SkIRect cropRect = getCropRect(builder->cropOffset());
- return adoptRef(new CompositeImageFilter(toXfermode(m_type), background.get(), foreground.get(), &cropRect));
-}
-
-static TextStream& operator<<(TextStream& ts, const CompositeOperationType& type)
-{
- switch (type) {
- case FECOMPOSITE_OPERATOR_UNKNOWN:
- ts << "UNKNOWN";
- break;
- case FECOMPOSITE_OPERATOR_OVER:
- ts << "OVER";
- break;
- case FECOMPOSITE_OPERATOR_IN:
- ts << "IN";
- break;
- case FECOMPOSITE_OPERATOR_OUT:
- ts << "OUT";
- break;
- case FECOMPOSITE_OPERATOR_ATOP:
- ts << "ATOP";
- break;
- case FECOMPOSITE_OPERATOR_XOR:
- ts << "XOR";
- break;
- case FECOMPOSITE_OPERATOR_ARITHMETIC:
- ts << "ARITHMETIC";
- break;
- }
- return ts;
-}
-
-TextStream& FEComposite::externalRepresentation(TextStream& ts, int indent) const
-{
- writeIndent(ts, indent);
- ts << "[feComposite";
- FilterEffect::externalRepresentation(ts);
- ts << " operation=\"" << m_type << "\"";
- if (m_type == FECOMPOSITE_OPERATOR_ARITHMETIC)
- ts << " k1=\"" << m_k1 << "\" k2=\"" << m_k2 << "\" k3=\"" << m_k3 << "\" k4=\"" << m_k4 << "\"";
- ts << "]\n";
- inputEffect(0)->externalRepresentation(ts, indent + 1);
- inputEffect(1)->externalRepresentation(ts, indent + 1);
- return ts;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEComposite.h b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEComposite.h
deleted file mode 100644
index cd364c3b1b8..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEComposite.h
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * Copyright (C) 2004, 2005, 2006, 2007 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2004, 2005 Rob Buis <buis@kde.org>
- * Copyright (C) 2005 Eric Seidel <eric@webkit.org>
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#ifndef FEComposite_h
-#define FEComposite_h
-
-#include "core/platform/graphics/filters/FilterEffect.h"
-
-#include "core/platform/graphics/filters/Filter.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-enum CompositeOperationType {
- FECOMPOSITE_OPERATOR_UNKNOWN = 0,
- FECOMPOSITE_OPERATOR_OVER = 1,
- FECOMPOSITE_OPERATOR_IN = 2,
- FECOMPOSITE_OPERATOR_OUT = 3,
- FECOMPOSITE_OPERATOR_ATOP = 4,
- FECOMPOSITE_OPERATOR_XOR = 5,
- FECOMPOSITE_OPERATOR_ARITHMETIC = 6
-};
-
-class FEComposite : public FilterEffect {
-public:
- static PassRefPtr<FEComposite> create(Filter*, const CompositeOperationType&, float, float, float, float);
-
- CompositeOperationType operation() const;
- bool setOperation(CompositeOperationType);
-
- float k1() const;
- bool setK1(float);
-
- float k2() const;
- bool setK2(float);
-
- float k3() const;
- bool setK3(float);
-
- float k4() const;
- bool setK4(float);
-
- virtual void correctFilterResultIfNeeded() OVERRIDE;
-
- virtual void determineAbsolutePaintRect();
-
- virtual TextStream& externalRepresentation(TextStream&, int indention) const;
-
- virtual PassRefPtr<SkImageFilter> createImageFilter(SkiaImageFilterBuilder*) OVERRIDE;
-
-protected:
- virtual bool requiresValidPreMultipliedPixels() OVERRIDE { return m_type != FECOMPOSITE_OPERATOR_ARITHMETIC; }
-
-private:
- FEComposite(Filter*, const CompositeOperationType&, float, float, float, float);
-
- virtual void applySoftware() OVERRIDE;
-
- inline void platformArithmeticSoftware(Uint8ClampedArray* source, Uint8ClampedArray* destination,
- float k1, float k2, float k3, float k4);
- template <int b1, int b4>
- static inline void computeArithmeticPixelsNeon(unsigned char* source, unsigned char* destination,
- unsigned pixelArrayLength, float k1, float k2, float k3, float k4);
- static inline void platformArithmeticNeon(unsigned char* source, unsigned char* destination,
- unsigned pixelArrayLength, float k1, float k2, float k3, float k4);
-
- CompositeOperationType m_type;
- float m_k1;
- float m_k2;
- float m_k3;
- float m_k4;
-};
-
-} // namespace WebCore
-
-#endif // FEComposite_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEConvolveMatrix.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEConvolveMatrix.cpp
deleted file mode 100644
index 27535554f66..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEConvolveMatrix.cpp
+++ /dev/null
@@ -1,572 +0,0 @@
-/*
- * Copyright (C) 2004, 2005, 2006, 2007 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2004, 2005 Rob Buis <buis@kde.org>
- * Copyright (C) 2005 Eric Seidel <eric@webkit.org>
- * Copyright (C) 2009 Dirk Schulze <krit@webkit.org>
- * Copyright (C) 2010 Zoltan Herczeg <zherczeg@webkit.org>
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-
-#include "core/platform/graphics/filters/FEConvolveMatrix.h"
-
-#include "core/platform/graphics/filters/Filter.h"
-#include "core/platform/text/TextStream.h"
-#include "core/rendering/RenderTreeAsText.h"
-
-#include "wtf/OwnArrayPtr.h"
-#include "wtf/ParallelJobs.h"
-#include "wtf/Uint8ClampedArray.h"
-
-#include "SkMatrixConvolutionImageFilter.h"
-#include "core/platform/graphics/filters/SkiaImageFilterBuilder.h"
-
-namespace WebCore {
-
-FEConvolveMatrix::FEConvolveMatrix(Filter* filter, const IntSize& kernelSize,
- float divisor, float bias, const IntPoint& targetOffset, EdgeModeType edgeMode,
- const FloatPoint& kernelUnitLength, bool preserveAlpha, const Vector<float>& kernelMatrix)
- : FilterEffect(filter)
- , m_kernelSize(kernelSize)
- , m_divisor(divisor)
- , m_bias(bias)
- , m_targetOffset(targetOffset)
- , m_edgeMode(edgeMode)
- , m_kernelUnitLength(kernelUnitLength)
- , m_preserveAlpha(preserveAlpha)
- , m_kernelMatrix(kernelMatrix)
-{
- ASSERT(m_kernelSize.width() > 0);
- ASSERT(m_kernelSize.height() > 0);
-}
-
-PassRefPtr<FEConvolveMatrix> FEConvolveMatrix::create(Filter* filter, const IntSize& kernelSize,
- float divisor, float bias, const IntPoint& targetOffset, EdgeModeType edgeMode,
- const FloatPoint& kernelUnitLength, bool preserveAlpha, const Vector<float>& kernelMatrix)
-{
- return adoptRef(new FEConvolveMatrix(filter, kernelSize, divisor, bias, targetOffset, edgeMode, kernelUnitLength,
- preserveAlpha, kernelMatrix));
-}
-
-
-IntSize FEConvolveMatrix::kernelSize() const
-{
- return m_kernelSize;
-}
-
-void FEConvolveMatrix::setKernelSize(const IntSize& kernelSize)
-{
- ASSERT(kernelSize.width() > 0);
- ASSERT(kernelSize.height() > 0);
- m_kernelSize = kernelSize;
-}
-
-const Vector<float>& FEConvolveMatrix::kernel() const
-{
- return m_kernelMatrix;
-}
-
-void FEConvolveMatrix::setKernel(const Vector<float>& kernel)
-{
- m_kernelMatrix = kernel;
-}
-
-float FEConvolveMatrix::divisor() const
-{
- return m_divisor;
-}
-
-bool FEConvolveMatrix::setDivisor(float divisor)
-{
- ASSERT(divisor);
- if (m_divisor == divisor)
- return false;
- m_divisor = divisor;
- return true;
-}
-
-float FEConvolveMatrix::bias() const
-{
- return m_bias;
-}
-
-bool FEConvolveMatrix::setBias(float bias)
-{
- if (m_bias == bias)
- return false;
- m_bias = bias;
- return true;
-}
-
-IntPoint FEConvolveMatrix::targetOffset() const
-{
- return m_targetOffset;
-}
-
-bool FEConvolveMatrix::setTargetOffset(const IntPoint& targetOffset)
-{
- if (m_targetOffset == targetOffset)
- return false;
- m_targetOffset = targetOffset;
- return true;
-}
-
-EdgeModeType FEConvolveMatrix::edgeMode() const
-{
- return m_edgeMode;
-}
-
-bool FEConvolveMatrix::setEdgeMode(EdgeModeType edgeMode)
-{
- if (m_edgeMode == edgeMode)
- return false;
- m_edgeMode = edgeMode;
- return true;
-}
-
-FloatPoint FEConvolveMatrix::kernelUnitLength() const
-{
- return m_kernelUnitLength;
-}
-
-bool FEConvolveMatrix::setKernelUnitLength(const FloatPoint& kernelUnitLength)
-{
- ASSERT(kernelUnitLength.x() > 0);
- ASSERT(kernelUnitLength.y() > 0);
- if (m_kernelUnitLength == kernelUnitLength)
- return false;
- m_kernelUnitLength = kernelUnitLength;
- return true;
-}
-
-bool FEConvolveMatrix::preserveAlpha() const
-{
- return m_preserveAlpha;
-}
-
-bool FEConvolveMatrix::setPreserveAlpha(bool preserveAlpha)
-{
- if (m_preserveAlpha == preserveAlpha)
- return false;
- m_preserveAlpha = preserveAlpha;
- return true;
-}
-
-/*
- -----------------------------------
- ConvolveMatrix implementation
- -----------------------------------
-
- The image rectangle is split in the following way:
-
- +---------------------+
- | A |
- +---------------------+
- | | | |
- | B | C | D |
- | | | |
- +---------------------+
- | E |
- +---------------------+
-
- Where region C contains those pixels, whose values
- can be calculated without crossing the edge of the rectangle.
-
- Example:
- Image size: width: 10, height: 10
-
- Order (kernel matrix size): width: 3, height 4
- Target: x:1, y:3
-
- The following figure shows the target inside the kernel matrix:
-
- ...
- ...
- ...
- .X.
-
- The regions in this case are the following:
- Note: (x1, y1) top-left and (x2, y2) is the bottom-right corner
- Note: row x2 and column y2 is not part of the region
- only those (x, y) pixels, where x1 <= x < x2 and y1 <= y < y2
-
- Region A: x1: 0, y1: 0, x2: 10, y2: 3
- Region B: x1: 0, y1: 3, x2: 1, y2: 10
- Region C: x1: 1, y1: 3, x2: 9, y2: 10
- Region D: x1: 9, y1: 3, x2: 10, y2: 10
- Region E: x1: 0, y1: 10, x2: 10, y2: 10 (empty region)
-
- Since region C (often) contains most of the pixels, we implemented
- a fast algoritm to calculate these values, called fastSetInteriorPixels.
- For other regions, fastSetOuterPixels is used, which calls getPixelValue,
- to handle pixels outside of the image. In a rare situations, when
- kernel matrix is bigger than the image, all pixels are calculated by this
- function.
-
- Although these two functions have lot in common, I decided not to make
- common a template for them, since there are key differences as well,
- and would make it really hard to understand.
-*/
-
-static ALWAYS_INLINE unsigned char clampRGBAValue(float channel, unsigned char max = 255)
-{
- if (channel <= 0)
- return 0;
- if (channel >= max)
- return max;
- return channel;
-}
-
-template<bool preserveAlphaValues>
-ALWAYS_INLINE void setDestinationPixels(Uint8ClampedArray* image, int& pixel, float* totals, float divisor, float bias, Uint8ClampedArray* src)
-{
- unsigned char maxAlpha = preserveAlphaValues ? 255 : clampRGBAValue(totals[3] / divisor + bias);
- for (int i = 0; i < 3; ++i)
- image->set(pixel++, clampRGBAValue(totals[i] / divisor + bias, maxAlpha));
-
- if (preserveAlphaValues) {
- image->set(pixel, src->item(pixel));
- ++pixel;
- } else
- image->set(pixel++, maxAlpha);
-}
-
-#if defined(_MSC_VER) && (_MSC_VER >= 1700)
-// Incorrectly diagnosing overwrite of stack in |totals| due to |preserveAlphaValues|.
-#pragma warning(push)
-#pragma warning(disable: 4789)
-#endif
-
-// Only for region C
-template<bool preserveAlphaValues>
-ALWAYS_INLINE void FEConvolveMatrix::fastSetInteriorPixels(PaintingData& paintingData, int clipRight, int clipBottom, int yStart, int yEnd)
-{
- // edge mode does not affect these pixels
- int pixel = (m_targetOffset.y() * paintingData.width + m_targetOffset.x()) * 4;
- int kernelIncrease = clipRight * 4;
- int xIncrease = (m_kernelSize.width() - 1) * 4;
- // Contains the sum of rgb(a) components
- float totals[3 + (preserveAlphaValues ? 0 : 1)];
-
- // m_divisor cannot be 0, SVGFEConvolveMatrixElement ensures this
- ASSERT(m_divisor);
-
- // Skip the first '(clipBottom - yEnd)' lines
- pixel += (clipBottom - yEnd) * (xIncrease + (clipRight + 1) * 4);
- int startKernelPixel = (clipBottom - yEnd) * (xIncrease + (clipRight + 1) * 4);
-
- for (int y = yEnd + 1; y > yStart; --y) {
- for (int x = clipRight + 1; x > 0; --x) {
- int kernelValue = m_kernelMatrix.size() - 1;
- int kernelPixel = startKernelPixel;
- int width = m_kernelSize.width();
-
- totals[0] = 0;
- totals[1] = 0;
- totals[2] = 0;
- if (!preserveAlphaValues)
- totals[3] = 0;
-
- while (kernelValue >= 0) {
- totals[0] += m_kernelMatrix[kernelValue] * static_cast<float>(paintingData.srcPixelArray->item(kernelPixel++));
- totals[1] += m_kernelMatrix[kernelValue] * static_cast<float>(paintingData.srcPixelArray->item(kernelPixel++));
- totals[2] += m_kernelMatrix[kernelValue] * static_cast<float>(paintingData.srcPixelArray->item(kernelPixel++));
- if (!preserveAlphaValues)
- totals[3] += m_kernelMatrix[kernelValue] * static_cast<float>(paintingData.srcPixelArray->item(kernelPixel));
- ++kernelPixel;
- --kernelValue;
- if (!--width) {
- kernelPixel += kernelIncrease;
- width = m_kernelSize.width();
- }
- }
-
- setDestinationPixels<preserveAlphaValues>(paintingData.dstPixelArray, pixel, totals, m_divisor, paintingData.bias, paintingData.srcPixelArray);
- startKernelPixel += 4;
- }
- pixel += xIncrease;
- startKernelPixel += xIncrease;
- }
-}
-
-ALWAYS_INLINE int FEConvolveMatrix::getPixelValue(PaintingData& paintingData, int x, int y)
-{
- if (x >= 0 && x < paintingData.width && y >= 0 && y < paintingData.height)
- return (y * paintingData.width + x) << 2;
-
- switch (m_edgeMode) {
- default: // EDGEMODE_NONE
- return -1;
- case EDGEMODE_DUPLICATE:
- if (x < 0)
- x = 0;
- else if (x >= paintingData.width)
- x = paintingData.width - 1;
- if (y < 0)
- y = 0;
- else if (y >= paintingData.height)
- y = paintingData.height - 1;
- return (y * paintingData.width + x) << 2;
- case EDGEMODE_WRAP:
- while (x < 0)
- x += paintingData.width;
- x %= paintingData.width;
- while (y < 0)
- y += paintingData.height;
- y %= paintingData.height;
- return (y * paintingData.width + x) << 2;
- }
-}
-
-// For other regions than C
-template<bool preserveAlphaValues>
-void FEConvolveMatrix::fastSetOuterPixels(PaintingData& paintingData, int x1, int y1, int x2, int y2)
-{
- int pixel = (y1 * paintingData.width + x1) * 4;
- int height = y2 - y1;
- int width = x2 - x1;
- int beginKernelPixelX = x1 - m_targetOffset.x();
- int startKernelPixelX = beginKernelPixelX;
- int startKernelPixelY = y1 - m_targetOffset.y();
- int xIncrease = (paintingData.width - width) * 4;
- // Contains the sum of rgb(a) components
- float totals[3 + (preserveAlphaValues ? 0 : 1)];
-
- // m_divisor cannot be 0, SVGFEConvolveMatrixElement ensures this
- ASSERT(m_divisor);
-
- for (int y = height; y > 0; --y) {
- for (int x = width; x > 0; --x) {
- int kernelValue = m_kernelMatrix.size() - 1;
- int kernelPixelX = startKernelPixelX;
- int kernelPixelY = startKernelPixelY;
- int width = m_kernelSize.width();
-
- totals[0] = 0;
- totals[1] = 0;
- totals[2] = 0;
- if (!preserveAlphaValues)
- totals[3] = 0;
-
- while (kernelValue >= 0) {
- int pixelIndex = getPixelValue(paintingData, kernelPixelX, kernelPixelY);
- if (pixelIndex >= 0) {
- totals[0] += m_kernelMatrix[kernelValue] * static_cast<float>(paintingData.srcPixelArray->item(pixelIndex));
- totals[1] += m_kernelMatrix[kernelValue] * static_cast<float>(paintingData.srcPixelArray->item(pixelIndex + 1));
- totals[2] += m_kernelMatrix[kernelValue] * static_cast<float>(paintingData.srcPixelArray->item(pixelIndex + 2));
- }
- if (!preserveAlphaValues && pixelIndex >= 0)
- totals[3] += m_kernelMatrix[kernelValue] * static_cast<float>(paintingData.srcPixelArray->item(pixelIndex + 3));
- ++kernelPixelX;
- --kernelValue;
- if (!--width) {
- kernelPixelX = startKernelPixelX;
- ++kernelPixelY;
- width = m_kernelSize.width();
- }
- }
-
- setDestinationPixels<preserveAlphaValues>(paintingData.dstPixelArray, pixel, totals, m_divisor, paintingData.bias, paintingData.srcPixelArray);
- ++startKernelPixelX;
- }
- pixel += xIncrease;
- startKernelPixelX = beginKernelPixelX;
- ++startKernelPixelY;
- }
-}
-
-#if defined(_MSC_VER) && (_MSC_VER >= 1700)
-#pragma warning(pop) // Disable of 4789
-#endif
-
-ALWAYS_INLINE void FEConvolveMatrix::setInteriorPixels(PaintingData& paintingData, int clipRight, int clipBottom, int yStart, int yEnd)
-{
- // Must be implemented here, since it refers another ALWAYS_INLINE
- // function, which defined in this C++ source file as well
- if (m_preserveAlpha)
- fastSetInteriorPixels<true>(paintingData, clipRight, clipBottom, yStart, yEnd);
- else
- fastSetInteriorPixels<false>(paintingData, clipRight, clipBottom, yStart, yEnd);
-}
-
-ALWAYS_INLINE void FEConvolveMatrix::setOuterPixels(PaintingData& paintingData, int x1, int y1, int x2, int y2)
-{
- // Although this function can be moved to the header, it is implemented here
- // because setInteriorPixels is also implemented here
- if (m_preserveAlpha)
- fastSetOuterPixels<true>(paintingData, x1, y1, x2, y2);
- else
- fastSetOuterPixels<false>(paintingData, x1, y1, x2, y2);
-}
-
-void FEConvolveMatrix::setInteriorPixelsWorker(InteriorPixelParameters* param)
-{
- param->filter->setInteriorPixels(*param->paintingData, param->clipRight, param->clipBottom, param->yStart, param->yEnd);
-}
-
-void FEConvolveMatrix::applySoftware()
-{
- FilterEffect* in = inputEffect(0);
-
- Uint8ClampedArray* resultImage;
- if (m_preserveAlpha)
- resultImage = createUnmultipliedImageResult();
- else
- resultImage = createPremultipliedImageResult();
- if (!resultImage)
- return;
-
- IntRect effectDrawingRect = requestedRegionOfInputImageData(in->absolutePaintRect());
-
- RefPtr<Uint8ClampedArray> srcPixelArray;
- if (m_preserveAlpha)
- srcPixelArray = in->asUnmultipliedImage(effectDrawingRect);
- else
- srcPixelArray = in->asPremultipliedImage(effectDrawingRect);
-
- IntSize paintSize = absolutePaintRect().size();
- PaintingData paintingData;
- paintingData.srcPixelArray = srcPixelArray.get();
- paintingData.dstPixelArray = resultImage;
- paintingData.width = paintSize.width();
- paintingData.height = paintSize.height();
- paintingData.bias = m_bias * 255;
-
- // Drawing fully covered pixels
- int clipRight = paintSize.width() - m_kernelSize.width();
- int clipBottom = paintSize.height() - m_kernelSize.height();
-
- if (clipRight >= 0 && clipBottom >= 0) {
-
- int optimalThreadNumber = (absolutePaintRect().width() * absolutePaintRect().height()) / s_minimalRectDimension;
- if (optimalThreadNumber > 1) {
- WTF::ParallelJobs<InteriorPixelParameters> parallelJobs(&WebCore::FEConvolveMatrix::setInteriorPixelsWorker, optimalThreadNumber);
- const int numOfThreads = parallelJobs.numberOfJobs();
-
- // Split the job into "heightPerThread" jobs but there a few jobs that need to be slightly larger since
- // heightPerThread * jobs < total size. These extras are handled by the remainder "jobsWithExtra".
- const int heightPerThread = clipBottom / numOfThreads;
- const int jobsWithExtra = clipBottom % numOfThreads;
-
- int startY = 0;
- for (int job = 0; job < numOfThreads; ++job) {
- InteriorPixelParameters& param = parallelJobs.parameter(job);
- param.filter = this;
- param.paintingData = &paintingData;
- param.clipRight = clipRight;
- param.clipBottom = clipBottom;
- param.yStart = startY;
- startY += job < jobsWithExtra ? heightPerThread + 1 : heightPerThread;
- param.yEnd = startY;
- }
-
- parallelJobs.execute();
- } else {
- // Fallback to single threaded mode.
- setInteriorPixels(paintingData, clipRight, clipBottom, 0, clipBottom);
- }
-
- clipRight += m_targetOffset.x() + 1;
- clipBottom += m_targetOffset.y() + 1;
- if (m_targetOffset.y() > 0)
- setOuterPixels(paintingData, 0, 0, paintSize.width(), m_targetOffset.y());
- if (clipBottom < paintSize.height())
- setOuterPixels(paintingData, 0, clipBottom, paintSize.width(), paintSize.height());
- if (m_targetOffset.x() > 0)
- setOuterPixels(paintingData, 0, m_targetOffset.y(), m_targetOffset.x(), clipBottom);
- if (clipRight < paintSize.width())
- setOuterPixels(paintingData, clipRight, m_targetOffset.y(), paintSize.width(), clipBottom);
- } else {
- // Rare situation, not optimizied for speed
- setOuterPixels(paintingData, 0, 0, paintSize.width(), paintSize.height());
- }
-}
-
-SkMatrixConvolutionImageFilter::TileMode toSkiaTileMode(WebCore::EdgeModeType edgeMode)
-{
- switch (edgeMode) {
- case WebCore::EDGEMODE_DUPLICATE:
- return SkMatrixConvolutionImageFilter::kClamp_TileMode;
- case WebCore::EDGEMODE_WRAP:
- return SkMatrixConvolutionImageFilter::kRepeat_TileMode;
- case WebCore::EDGEMODE_NONE:
- return SkMatrixConvolutionImageFilter::kClampToBlack_TileMode;
- default:
- return SkMatrixConvolutionImageFilter::kClamp_TileMode;
- }
-}
-
-}; // unnamed namespace
-
-namespace WebCore {
-
-PassRefPtr<SkImageFilter> FEConvolveMatrix::createImageFilter(SkiaImageFilterBuilder* builder)
-{
- RefPtr<SkImageFilter> input(builder->build(inputEffect(0), operatingColorSpace()));
-
- SkISize kernelSize(SkISize::Make(m_kernelSize.width(), m_kernelSize.height()));
- int numElements = kernelSize.width() * kernelSize.height();
- SkScalar gain = SkFloatToScalar(1.0f / m_divisor);
- SkScalar bias = SkFloatToScalar(m_bias);
- SkIPoint target = SkIPoint::Make(m_targetOffset.x(), m_targetOffset.y());
- SkMatrixConvolutionImageFilter::TileMode tileMode = toSkiaTileMode(m_edgeMode);
- bool convolveAlpha = !m_preserveAlpha;
- OwnArrayPtr<SkScalar> kernel = adoptArrayPtr(new SkScalar[numElements]);
- for (int i = 0; i < numElements; ++i)
- kernel[i] = SkFloatToScalar(m_kernelMatrix[numElements - 1 - i]);
- return adoptRef(new SkMatrixConvolutionImageFilter(kernelSize, kernel.get(), gain, bias, target, tileMode, convolveAlpha, input.get()));
-}
-
-static TextStream& operator<<(TextStream& ts, const EdgeModeType& type)
-{
- switch (type) {
- case EDGEMODE_UNKNOWN:
- ts << "UNKNOWN";
- break;
- case EDGEMODE_DUPLICATE:
- ts << "DUPLICATE";
- break;
- case EDGEMODE_WRAP:
- ts << "WRAP";
- break;
- case EDGEMODE_NONE:
- ts << "NONE";
- break;
- }
- return ts;
-}
-
-TextStream& FEConvolveMatrix::externalRepresentation(TextStream& ts, int indent) const
-{
- writeIndent(ts, indent);
- ts << "[feConvolveMatrix";
- FilterEffect::externalRepresentation(ts);
- ts << " order=\"" << m_kernelSize << "\" "
- << "kernelMatrix=\"" << m_kernelMatrix << "\" "
- << "divisor=\"" << m_divisor << "\" "
- << "bias=\"" << m_bias << "\" "
- << "target=\"" << m_targetOffset << "\" "
- << "edgeMode=\"" << m_edgeMode << "\" "
- << "kernelUnitLength=\"" << m_kernelUnitLength << "\" "
- << "preserveAlpha=\"" << m_preserveAlpha << "\"]\n";
- inputEffect(0)->externalRepresentation(ts, indent + 1);
- return ts;
-}
-
-}; // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEConvolveMatrix.h b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEConvolveMatrix.h
deleted file mode 100644
index d9f0ca6e318..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEConvolveMatrix.h
+++ /dev/null
@@ -1,134 +0,0 @@
-/*
- * Copyright (C) 2004, 2005, 2006, 2007 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2004, 2005 Rob Buis <buis@kde.org>
- * Copyright (C) 2005 Eric Seidel <eric@webkit.org>
- * Copyright (C) 2010 Zoltan Herczeg <zherczeg@webkit.org>
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#ifndef FEConvolveMatrix_h
-#define FEConvolveMatrix_h
-
-#include "core/platform/graphics/FloatPoint.h"
-#include "core/platform/graphics/FloatSize.h"
-#include "core/platform/graphics/filters/Filter.h"
-#include "core/platform/graphics/filters/FilterEffect.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-enum EdgeModeType {
- EDGEMODE_UNKNOWN = 0,
- EDGEMODE_DUPLICATE = 1,
- EDGEMODE_WRAP = 2,
- EDGEMODE_NONE = 3
-};
-
-class FEConvolveMatrix : public FilterEffect {
-public:
- static PassRefPtr<FEConvolveMatrix> create(Filter*, const IntSize&,
- float, float, const IntPoint&, EdgeModeType, const FloatPoint&,
- bool, const Vector<float>&);
-
- IntSize kernelSize() const;
- void setKernelSize(const IntSize&);
-
- const Vector<float>& kernel() const;
- void setKernel(const Vector<float>&);
-
- float divisor() const;
- bool setDivisor(float);
-
- float bias() const;
- bool setBias(float);
-
- IntPoint targetOffset() const;
- bool setTargetOffset(const IntPoint&);
-
- EdgeModeType edgeMode() const;
- bool setEdgeMode(EdgeModeType);
-
- FloatPoint kernelUnitLength() const;
- bool setKernelUnitLength(const FloatPoint&);
-
- bool preserveAlpha() const;
- bool setPreserveAlpha(bool);
-
- virtual PassRefPtr<SkImageFilter> createImageFilter(SkiaImageFilterBuilder*) OVERRIDE;
-
- virtual void determineAbsolutePaintRect() { setAbsolutePaintRect(enclosingIntRect(maxEffectRect())); }
-
- virtual TextStream& externalRepresentation(TextStream&, int indention) const;
-
-private:
-
- struct PaintingData {
- Uint8ClampedArray* srcPixelArray;
- Uint8ClampedArray* dstPixelArray;
- int width;
- int height;
- float bias;
- };
-
- FEConvolveMatrix(Filter*, const IntSize&, float, float,
- const IntPoint&, EdgeModeType, const FloatPoint&, bool, const Vector<float>&);
-
- virtual void applySoftware() OVERRIDE;
-
- template<bool preserveAlphaValues>
- ALWAYS_INLINE void fastSetInteriorPixels(PaintingData&, int clipRight, int clipBottom, int yStart, int yEnd);
-
- ALWAYS_INLINE int getPixelValue(PaintingData&, int x, int y);
-
- template<bool preserveAlphaValues>
- void fastSetOuterPixels(PaintingData&, int x1, int y1, int x2, int y2);
-
- // Wrapper functions
- ALWAYS_INLINE void setInteriorPixels(PaintingData&, int clipRight, int clipBottom, int yStart, int yEnd);
- ALWAYS_INLINE void setOuterPixels(PaintingData&, int x1, int y1, int x2, int y2);
-
- // Parallelization parts
- static const int s_minimalRectDimension = (100 * 100); // Empirical data limit for parallel jobs
-
- template<typename Type>
- friend class ParallelJobs;
-
- struct InteriorPixelParameters {
- FEConvolveMatrix* filter;
- PaintingData* paintingData;
- int clipBottom;
- int clipRight;
- int yStart;
- int yEnd;
- };
-
- static void setInteriorPixelsWorker(InteriorPixelParameters*);
-
- IntSize m_kernelSize;
- float m_divisor;
- float m_bias;
- IntPoint m_targetOffset;
- EdgeModeType m_edgeMode;
- FloatPoint m_kernelUnitLength;
- bool m_preserveAlpha;
- Vector<float> m_kernelMatrix;
-};
-
-} // namespace WebCore
-
-#endif // FEConvolveMatrix_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEDiffuseLighting.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEDiffuseLighting.cpp
deleted file mode 100644
index 0333f484010..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEDiffuseLighting.cpp
+++ /dev/null
@@ -1,137 +0,0 @@
-/*
- * Copyright (C) 2004, 2005, 2006, 2007 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2004, 2005 Rob Buis <buis@kde.org>
- * Copyright (C) 2005 Eric Seidel <eric@webkit.org>
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-
-#include "core/platform/graphics/filters/FEDiffuseLighting.h"
-
-#include "core/platform/graphics/filters/LightSource.h"
-#include "core/platform/text/TextStream.h"
-#include "core/rendering/RenderTreeAsText.h"
-
-namespace WebCore {
-
-FEDiffuseLighting::FEDiffuseLighting(Filter* filter, const Color& lightingColor, float surfaceScale,
- float diffuseConstant, float kernelUnitLengthX, float kernelUnitLengthY, PassRefPtr<LightSource> lightSource)
- : FELighting(filter, DiffuseLighting, lightingColor, surfaceScale, diffuseConstant, 0, 0, kernelUnitLengthX, kernelUnitLengthY, lightSource)
-{
-}
-
-PassRefPtr<FEDiffuseLighting> FEDiffuseLighting::create(Filter* filter, const Color& lightingColor,
- float surfaceScale, float diffuseConstant, float kernelUnitLengthX,
- float kernelUnitLengthY, PassRefPtr<LightSource> lightSource)
-{
- return adoptRef(new FEDiffuseLighting(filter, lightingColor, surfaceScale, diffuseConstant, kernelUnitLengthX, kernelUnitLengthY, lightSource));
-}
-
-FEDiffuseLighting::~FEDiffuseLighting()
-{
-}
-
-Color FEDiffuseLighting::lightingColor() const
-{
- return m_lightingColor;
-}
-
-bool FEDiffuseLighting::setLightingColor(const Color& lightingColor)
-{
- if (m_lightingColor == lightingColor)
- return false;
- m_lightingColor = lightingColor;
- return true;
-}
-
-float FEDiffuseLighting::surfaceScale() const
-{
- return m_surfaceScale;
-}
-
-bool FEDiffuseLighting::setSurfaceScale(float surfaceScale)
-{
- if (m_surfaceScale == surfaceScale)
- return false;
- m_surfaceScale = surfaceScale;
- return true;
-}
-
-float FEDiffuseLighting::diffuseConstant() const
-{
- return m_diffuseConstant;
-}
-
-bool FEDiffuseLighting::setDiffuseConstant(float diffuseConstant)
-{
- if (m_diffuseConstant == diffuseConstant)
- return false;
- m_diffuseConstant = diffuseConstant;
- return true;
-}
-
-float FEDiffuseLighting::kernelUnitLengthX() const
-{
- return m_kernelUnitLengthX;
-}
-
-bool FEDiffuseLighting::setKernelUnitLengthX(float kernelUnitLengthX)
-{
- if (m_kernelUnitLengthX == kernelUnitLengthX)
- return false;
- m_kernelUnitLengthX = kernelUnitLengthX;
- return true;
-}
-
-float FEDiffuseLighting::kernelUnitLengthY() const
-{
- return m_kernelUnitLengthY;
-}
-
-bool FEDiffuseLighting::setKernelUnitLengthY(float kernelUnitLengthY)
-{
- if (m_kernelUnitLengthY == kernelUnitLengthY)
- return false;
- m_kernelUnitLengthY = kernelUnitLengthY;
- return true;
-}
-
-const LightSource* FEDiffuseLighting::lightSource() const
-{
- return m_lightSource.get();
-}
-
-void FEDiffuseLighting::setLightSource(PassRefPtr<LightSource> lightSource)
-{
- m_lightSource = lightSource;
-}
-
-TextStream& FEDiffuseLighting::externalRepresentation(TextStream& ts, int indent) const
-{
- writeIndent(ts, indent);
- ts << "[feDiffuseLighting";
- FilterEffect::externalRepresentation(ts);
- ts << " surfaceScale=\"" << m_surfaceScale << "\" "
- << "diffuseConstant=\"" << m_diffuseConstant << "\" "
- << "kernelUnitLength=\"" << m_kernelUnitLengthX << ", " << m_kernelUnitLengthY << "\"]\n";
- inputEffect(0)->externalRepresentation(ts, indent + 1);
- return ts;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEDiffuseLighting.h b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEDiffuseLighting.h
deleted file mode 100644
index 44622a4206e..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEDiffuseLighting.h
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Copyright (C) 2004, 2005, 2006, 2007 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2004, 2005 Rob Buis <buis@kde.org>
- * Copyright (C) 2005 Eric Seidel <eric@webkit.org>
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#ifndef FEDiffuseLighting_h
-#define FEDiffuseLighting_h
-
-#include "core/platform/graphics/filters/FELighting.h"
-
-namespace WebCore {
-
-class LightSource;
-
-class FEDiffuseLighting : public FELighting {
-public:
- static PassRefPtr<FEDiffuseLighting> create(Filter*, const Color&, float, float,
- float, float, PassRefPtr<LightSource>);
- virtual ~FEDiffuseLighting();
-
- Color lightingColor() const;
- bool setLightingColor(const Color&);
-
- float surfaceScale() const;
- bool setSurfaceScale(float);
-
- float diffuseConstant() const;
- bool setDiffuseConstant(float);
-
- float kernelUnitLengthX() const;
- bool setKernelUnitLengthX(float);
-
- float kernelUnitLengthY() const;
- bool setKernelUnitLengthY(float);
-
- const LightSource* lightSource() const;
- void setLightSource(PassRefPtr<LightSource>);
-
- virtual TextStream& externalRepresentation(TextStream&, int indention) const;
-
-private:
- FEDiffuseLighting(Filter*, const Color&, float, float, float, float, PassRefPtr<LightSource>);
-};
-
-} // namespace WebCore
-
-#endif // FEDiffuseLighting_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEDisplacementMap.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEDisplacementMap.cpp
deleted file mode 100644
index 67853d82f7a..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEDisplacementMap.cpp
+++ /dev/null
@@ -1,264 +0,0 @@
-/*
- * Copyright (C) 2004, 2005, 2006, 2007 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2004, 2005 Rob Buis <buis@kde.org>
- * Copyright (C) 2005 Eric Seidel <eric@webkit.org>
- * Copyright (C) 2009 Dirk Schulze <krit@webkit.org>
- * Copyright (C) Research In Motion Limited 2010. All rights reserved.
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-
-#include "core/platform/graphics/filters/FEDisplacementMap.h"
-
-#include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/graphics/filters/Filter.h"
-#include "core/platform/text/TextStream.h"
-#include "core/rendering/RenderTreeAsText.h"
-
-#include "wtf/Uint8ClampedArray.h"
-
-#include "SkBitmapSource.h"
-#include "SkDisplacementMapEffect.h"
-#include "core/platform/graphics/filters/SkiaImageFilterBuilder.h"
-#include "core/platform/graphics/skia/NativeImageSkia.h"
-
-namespace WebCore {
-
-FEDisplacementMap::FEDisplacementMap(Filter* filter, ChannelSelectorType xChannelSelector, ChannelSelectorType yChannelSelector, float scale)
- : FilterEffect(filter)
- , m_xChannelSelector(xChannelSelector)
- , m_yChannelSelector(yChannelSelector)
- , m_scale(scale)
-{
-}
-
-PassRefPtr<FEDisplacementMap> FEDisplacementMap::create(Filter* filter, ChannelSelectorType xChannelSelector,
- ChannelSelectorType yChannelSelector, float scale)
-{
- return adoptRef(new FEDisplacementMap(filter, xChannelSelector, yChannelSelector, scale));
-}
-
-ChannelSelectorType FEDisplacementMap::xChannelSelector() const
-{
- return m_xChannelSelector;
-}
-
-bool FEDisplacementMap::setXChannelSelector(const ChannelSelectorType xChannelSelector)
-{
- if (m_xChannelSelector == xChannelSelector)
- return false;
- m_xChannelSelector = xChannelSelector;
- return true;
-}
-
-ChannelSelectorType FEDisplacementMap::yChannelSelector() const
-{
- return m_yChannelSelector;
-}
-
-bool FEDisplacementMap::setYChannelSelector(const ChannelSelectorType yChannelSelector)
-{
- if (m_yChannelSelector == yChannelSelector)
- return false;
- m_yChannelSelector = yChannelSelector;
- return true;
-}
-
-float FEDisplacementMap::scale() const
-{
- return m_scale;
-}
-
-bool FEDisplacementMap::setScale(float scale)
-{
- if (m_scale == scale)
- return false;
- m_scale = scale;
- return true;
-}
-
-void FEDisplacementMap::setResultColorSpace(ColorSpace)
-{
- // Spec: The 'color-interpolation-filters' property only applies to the 'in2' source image
- // and does not apply to the 'in' source image. The 'in' source image must remain in its
- // current color space.
- // The result is in that smae color space because it is a displacement of the 'in' image.
- FilterEffect::setResultColorSpace(inputEffect(0)->resultColorSpace());
-}
-
-void FEDisplacementMap::transformResultColorSpace(FilterEffect* in, const int index)
-{
- // Do not transform the first primitive input, as per the spec.
- if (index)
- in->transformResultColorSpace(operatingColorSpace());
-}
-
-void FEDisplacementMap::applySoftware()
-{
- FilterEffect* in = inputEffect(0);
- FilterEffect* in2 = inputEffect(1);
-
- ASSERT(m_xChannelSelector != CHANNEL_UNKNOWN);
- ASSERT(m_yChannelSelector != CHANNEL_UNKNOWN);
-
- Uint8ClampedArray* dstPixelArray = createPremultipliedImageResult();
- if (!dstPixelArray)
- return;
-
- IntRect effectADrawingRect = requestedRegionOfInputImageData(in->absolutePaintRect());
- RefPtr<Uint8ClampedArray> srcPixelArrayA = in->asPremultipliedImage(effectADrawingRect);
-
- IntRect effectBDrawingRect = requestedRegionOfInputImageData(in2->absolutePaintRect());
- RefPtr<Uint8ClampedArray> srcPixelArrayB = in2->asUnmultipliedImage(effectBDrawingRect);
-
- ASSERT(srcPixelArrayA->length() == srcPixelArrayB->length());
-
- Filter* filter = this->filter();
- IntSize paintSize = absolutePaintRect().size();
- float scaleX = filter->applyHorizontalScale(m_scale);
- float scaleY = filter->applyVerticalScale(m_scale);
- float scaleForColorX = scaleX / 255.0;
- float scaleForColorY = scaleY / 255.0;
- float scaledOffsetX = 0.5 - scaleX * 0.5;
- float scaledOffsetY = 0.5 - scaleY * 0.5;
- int stride = paintSize.width() * 4;
- for (int y = 0; y < paintSize.height(); ++y) {
- int line = y * stride;
- for (int x = 0; x < paintSize.width(); ++x) {
- int dstIndex = line + x * 4;
- int srcX = x + static_cast<int>(scaleForColorX * srcPixelArrayB->item(dstIndex + m_xChannelSelector - 1) + scaledOffsetX);
- int srcY = y + static_cast<int>(scaleForColorY * srcPixelArrayB->item(dstIndex + m_yChannelSelector - 1) + scaledOffsetY);
- for (unsigned channel = 0; channel < 4; ++channel) {
- if (srcX < 0 || srcX >= paintSize.width() || srcY < 0 || srcY >= paintSize.height())
- dstPixelArray->set(dstIndex + channel, static_cast<unsigned char>(0));
- else {
- unsigned char pixelValue = srcPixelArrayA->item(srcY * stride + srcX * 4 + channel);
- dstPixelArray->set(dstIndex + channel, pixelValue);
- }
- }
- }
- }
-}
-
-static SkDisplacementMapEffect::ChannelSelectorType toSkiaMode(ChannelSelectorType type)
-{
- switch (type) {
- case CHANNEL_R:
- return SkDisplacementMapEffect::kR_ChannelSelectorType;
- case CHANNEL_G:
- return SkDisplacementMapEffect::kG_ChannelSelectorType;
- case CHANNEL_B:
- return SkDisplacementMapEffect::kB_ChannelSelectorType;
- case CHANNEL_A:
- return SkDisplacementMapEffect::kA_ChannelSelectorType;
- case CHANNEL_UNKNOWN:
- default:
- return SkDisplacementMapEffect::kUnknown_ChannelSelectorType;
- }
-}
-
-bool FEDisplacementMap::applySkia()
-{
- // For now, only use the skia implementation for accelerated rendering.
- if (filter()->renderingMode() != Accelerated)
- return false;
-
- FilterEffect* in = inputEffect(0);
- FilterEffect* in2 = inputEffect(1);
-
- if (!in || !in2)
- return false;
-
- ImageBuffer* resultImage = createImageBufferResult();
- if (!resultImage)
- return false;
-
- RefPtr<Image> color = in->asImageBuffer()->copyImage(DontCopyBackingStore);
- RefPtr<Image> displ = in2->asImageBuffer()->copyImage(DontCopyBackingStore);
-
- RefPtr<NativeImageSkia> colorNativeImage = color->nativeImageForCurrentFrame();
- RefPtr<NativeImageSkia> displNativeImage = displ->nativeImageForCurrentFrame();
-
- if (!colorNativeImage || !displNativeImage)
- return false;
-
- SkBitmap colorBitmap = colorNativeImage->bitmap();
- SkBitmap displBitmap = displNativeImage->bitmap();
-
- SkAutoTUnref<SkImageFilter> colorSource(new SkBitmapSource(colorBitmap));
- SkAutoTUnref<SkImageFilter> displSource(new SkBitmapSource(displBitmap));
- SkDisplacementMapEffect::ChannelSelectorType typeX = toSkiaMode(m_xChannelSelector);
- SkDisplacementMapEffect::ChannelSelectorType typeY = toSkiaMode(m_yChannelSelector);
- // FIXME : Only applyHorizontalScale is used and applyVerticalScale is ignored
- // This can be fixed by adding a 2nd scale parameter to SkDisplacementMapEffect
- SkAutoTUnref<SkImageFilter> displEffect(new SkDisplacementMapEffect(
- typeX, typeY, SkFloatToScalar(filter()->applyHorizontalScale(m_scale)), displSource, colorSource));
- SkPaint paint;
- paint.setImageFilter(displEffect);
- resultImage->context()->drawBitmap(colorBitmap, 0, 0, &paint);
- return true;
-}
-
-PassRefPtr<SkImageFilter> FEDisplacementMap::createImageFilter(SkiaImageFilterBuilder* builder)
-{
- RefPtr<SkImageFilter> color = builder->build(inputEffect(0), operatingColorSpace());
- RefPtr<SkImageFilter> displ = builder->build(inputEffect(1), operatingColorSpace());
- SkDisplacementMapEffect::ChannelSelectorType typeX = toSkiaMode(m_xChannelSelector);
- SkDisplacementMapEffect::ChannelSelectorType typeY = toSkiaMode(m_yChannelSelector);
- // FIXME : Only applyHorizontalScale is used and applyVerticalScale is ignored
- // This can be fixed by adding a 2nd scale parameter to SkDisplacementMapEffect
- return adoptRef(new SkDisplacementMapEffect(typeX, typeY, SkFloatToScalar(filter()->applyHorizontalScale(m_scale)), displ.get(), color.get()));
-}
-
-static TextStream& operator<<(TextStream& ts, const ChannelSelectorType& type)
-{
- switch (type) {
- case CHANNEL_UNKNOWN:
- ts << "UNKNOWN";
- break;
- case CHANNEL_R:
- ts << "RED";
- break;
- case CHANNEL_G:
- ts << "GREEN";
- break;
- case CHANNEL_B:
- ts << "BLUE";
- break;
- case CHANNEL_A:
- ts << "ALPHA";
- break;
- }
- return ts;
-}
-
-TextStream& FEDisplacementMap::externalRepresentation(TextStream& ts, int indent) const
-{
- writeIndent(ts, indent);
- ts << "[feDisplacementMap";
- FilterEffect::externalRepresentation(ts);
- ts << " scale=\"" << m_scale << "\" "
- << "xChannelSelector=\"" << m_xChannelSelector << "\" "
- << "yChannelSelector=\"" << m_yChannelSelector << "\"]\n";
- inputEffect(0)->externalRepresentation(ts, indent + 1);
- inputEffect(1)->externalRepresentation(ts, indent + 1);
- return ts;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEDisplacementMap.h b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEDisplacementMap.h
deleted file mode 100644
index 3ac54a13cc6..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEDisplacementMap.h
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * Copyright (C) 2004, 2005, 2006, 2007 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2004, 2005 Rob Buis <buis@kde.org>
- * Copyright (C) 2005 Eric Seidel <eric@webkit.org>
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#ifndef FEDisplacementMap_h
-#define FEDisplacementMap_h
-
-#include "core/platform/graphics/filters/Filter.h"
-#include "core/platform/graphics/filters/FilterEffect.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-enum ChannelSelectorType {
- CHANNEL_UNKNOWN = 0,
- CHANNEL_R = 1,
- CHANNEL_G = 2,
- CHANNEL_B = 3,
- CHANNEL_A = 4
-};
-
-class FEDisplacementMap : public FilterEffect {
-public:
- static PassRefPtr<FEDisplacementMap> create(Filter*, ChannelSelectorType xChannelSelector, ChannelSelectorType yChannelSelector, float);
-
- ChannelSelectorType xChannelSelector() const;
- bool setXChannelSelector(const ChannelSelectorType);
-
- ChannelSelectorType yChannelSelector() const;
- bool setYChannelSelector(const ChannelSelectorType);
-
- float scale() const;
- bool setScale(float);
-
- void setResultColorSpace(ColorSpace) OVERRIDE;
- virtual void transformResultColorSpace(FilterEffect*, const int) OVERRIDE;
-
- virtual void determineAbsolutePaintRect() { setAbsolutePaintRect(enclosingIntRect(maxEffectRect())); }
-
- virtual TextStream& externalRepresentation(TextStream&, int indention) const;
-
-private:
- FEDisplacementMap(Filter*, ChannelSelectorType xChannelSelector, ChannelSelectorType yChannelSelector, float);
-
- virtual void applySoftware() OVERRIDE;
- virtual bool applySkia() OVERRIDE;
-
- virtual PassRefPtr<SkImageFilter> createImageFilter(SkiaImageFilterBuilder*) OVERRIDE;
-
- ChannelSelectorType m_xChannelSelector;
- ChannelSelectorType m_yChannelSelector;
- float m_scale;
-};
-
-} // namespace WebCore
-
-#endif // FEDisplacementMap_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEDropShadow.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEDropShadow.cpp
deleted file mode 100644
index 4f77df3065b..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEDropShadow.cpp
+++ /dev/null
@@ -1,134 +0,0 @@
-/*
- * Copyright (C) Research In Motion Limited 2011. All rights reserved.
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-
-#include "core/platform/graphics/filters/FEDropShadow.h"
-
-#include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/graphics/filters/FEGaussianBlur.h"
-#include "core/platform/graphics/filters/Filter.h"
-#include "core/platform/text/TextStream.h"
-#include "core/rendering/RenderTreeAsText.h"
-#include "third_party/skia/include/core/SkColorFilter.h"
-#include "third_party/skia/include/effects/SkBlurImageFilter.h"
-
-using namespace std;
-
-namespace WebCore {
-
-FEDropShadow::FEDropShadow(Filter* filter, float stdX, float stdY, float dx, float dy, const Color& shadowColor, float shadowOpacity)
- : FilterEffect(filter)
- , m_stdX(stdX)
- , m_stdY(stdY)
- , m_dx(dx)
- , m_dy(dy)
- , m_shadowColor(shadowColor)
- , m_shadowOpacity(shadowOpacity)
-{
-}
-
-PassRefPtr<FEDropShadow> FEDropShadow::create(Filter* filter, float stdX, float stdY, float dx, float dy, const Color& shadowColor, float shadowOpacity)
-{
- return adoptRef(new FEDropShadow(filter, stdX, stdY, dx, dy, shadowColor, shadowOpacity));
-}
-
-void FEDropShadow::determineAbsolutePaintRect()
-{
- Filter* filter = this->filter();
- ASSERT(filter);
-
- FloatRect absolutePaintRect = mapRect(inputEffect(0)->absolutePaintRect());
-
- if (clipsToBounds())
- absolutePaintRect.intersect(maxEffectRect());
- else
- absolutePaintRect.unite(maxEffectRect());
-
- setAbsolutePaintRect(enclosingIntRect(absolutePaintRect));
-}
-
-FloatRect FEDropShadow::mapRect(const FloatRect& rect, bool forward)
-{
- FloatRect result = rect;
- Filter* filter = this->filter();
- ASSERT(filter);
-
- FloatRect offsetRect = rect;
- if (forward)
- offsetRect.move(filter->applyHorizontalScale(m_dx), filter->applyVerticalScale(m_dy));
- else
- offsetRect.move(-filter->applyHorizontalScale(m_dx), -filter->applyVerticalScale(m_dy));
- result.unite(offsetRect);
-
- unsigned kernelSizeX = 0;
- unsigned kernelSizeY = 0;
- FEGaussianBlur::calculateKernelSize(filter, kernelSizeX, kernelSizeY, m_stdX, m_stdY);
-
- // We take the half kernel size and multiply it with three, because we run box blur three times.
- result.inflateX(3 * kernelSizeX * 0.5f);
- result.inflateY(3 * kernelSizeY * 0.5f);
- return result;
-}
-
-void FEDropShadow::applySoftware()
-{
- FilterEffect* in = inputEffect(0);
-
- ImageBuffer* resultImage = createImageBufferResult();
- if (!resultImage)
- return;
-
- Filter* filter = this->filter();
- FloatSize blurRadius(filter->applyHorizontalScale(m_stdX), filter->applyVerticalScale(m_stdY));
- FloatSize offset(filter->applyHorizontalScale(m_dx), filter->applyVerticalScale(m_dy));
-
- FloatRect drawingRegion = drawingRegionOfInputImage(in->absolutePaintRect());
- GraphicsContext* resultContext = resultImage->context();
- ASSERT(resultContext);
-
- SkAutoTUnref<SkImageFilter> blurFilter(new SkBlurImageFilter(blurRadius.width(), blurRadius.height()));
- SkAutoTUnref<SkColorFilter> colorFilter(SkColorFilter::CreateModeFilter(m_shadowColor.rgb(), SkXfermode::kSrcIn_Mode));
- SkPaint paint;
- paint.setImageFilter(blurFilter.get());
- paint.setColorFilter(colorFilter.get());
- paint.setXfermodeMode(SkXfermode::kSrcOver_Mode);
- RefPtr<Image> image = in->asImageBuffer()->copyImage(DontCopyBackingStore);
-
- RefPtr<NativeImageSkia> nativeImage = image->nativeImageForCurrentFrame();
-
- if (!nativeImage)
- return;
-
- resultContext->drawBitmap(nativeImage->bitmap(), drawingRegion.x() + offset.width(), drawingRegion.y() + offset.height(), &paint);
- resultContext->drawBitmap(nativeImage->bitmap(), drawingRegion.x(), drawingRegion.y());
-}
-
-TextStream& FEDropShadow::externalRepresentation(TextStream& ts, int indent) const
-{
- writeIndent(ts, indent);
- ts << "[feDropShadow";
- FilterEffect::externalRepresentation(ts);
- ts << " stdDeviation=\"" << m_stdX << ", " << m_stdY << "\" dx=\"" << m_dx << "\" dy=\"" << m_dy << "\" flood-color=\"" << m_shadowColor.nameForRenderTreeAsText() <<"\" flood-opacity=\"" << m_shadowOpacity << "]\n";
- inputEffect(0)->externalRepresentation(ts, indent + 1);
- return ts;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEDropShadow.h b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEDropShadow.h
deleted file mode 100644
index 36cd2b1cd2d..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEDropShadow.h
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * Copyright (C) Research In Motion Limited 2011. All rights reserved.
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#ifndef FEDropShadow_h
-#define FEDropShadow_h
-
-#include "core/platform/graphics/Color.h"
-#include "core/platform/graphics/filters/Filter.h"
-#include "core/platform/graphics/filters/FilterEffect.h"
-
-namespace WebCore {
-
-class FEDropShadow : public FilterEffect {
-public:
- static PassRefPtr<FEDropShadow> create(Filter*, float, float, float, float, const Color&, float);
-
- float stdDeviationX() const { return m_stdX; }
- void setStdDeviationX(float stdX) { m_stdX = stdX; }
-
- float stdDeviationY() const { return m_stdY; }
- void setStdDeviationY(float stdY) { m_stdY = stdY; }
-
- float dx() const { return m_dx; }
- void setDx(float dx) { m_dx = dx; }
-
- float dy() const { return m_dy; }
- void setDy(float dy) { m_dy = dy; }
-
- Color shadowColor() const { return m_shadowColor; }
- void setShadowColor(const Color& shadowColor) { m_shadowColor = shadowColor; }
-
- float shadowOpacity() const { return m_shadowOpacity; }
- void setShadowOpacity(float shadowOpacity) { m_shadowOpacity = shadowOpacity; }
-
- static float calculateStdDeviation(float);
-
- virtual void determineAbsolutePaintRect();
- virtual FloatRect mapRect(const FloatRect&, bool forward = true) OVERRIDE FINAL;
-
- virtual TextStream& externalRepresentation(TextStream&, int indention) const;
-
-private:
- FEDropShadow(Filter*, float, float, float, float, const Color&, float);
-
- virtual void applySoftware() OVERRIDE;
-
- float m_stdX;
- float m_stdY;
- float m_dx;
- float m_dy;
- Color m_shadowColor;
- float m_shadowOpacity;
-};
-
-} // namespace WebCore
-
-#endif // FEDropShadow_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEFlood.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEFlood.cpp
deleted file mode 100644
index ce8cc993be5..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEFlood.cpp
+++ /dev/null
@@ -1,156 +0,0 @@
-/*
- * Copyright (C) 2004, 2005, 2006, 2007 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2004, 2005 Rob Buis <buis@kde.org>
- * Copyright (C) 2005 Eric Seidel <eric@webkit.org>
- * Copyright (C) 2009 Dirk Schulze <krit@webkit.org>
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-
-#include "core/platform/graphics/filters/FEFlood.h"
-
-#include "SkFlattenableBuffers.h"
-#include "SkImageFilter.h"
-#include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/graphics/filters/Filter.h"
-#include "core/platform/graphics/filters/SkiaImageFilterBuilder.h"
-#include "core/platform/text/TextStream.h"
-#include "core/rendering/RenderTreeAsText.h"
-#include "third_party/skia/include/core/SkDevice.h"
-
-namespace {
-
-class FloodImageFilter : public SkImageFilter {
-public:
- FloodImageFilter(const SkColor& color, const SkIRect* cropRect)
- : SkImageFilter(0, 0, cropRect)
- , m_color(color)
- {
- }
- SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(FloodImageFilter)
-
- FloodImageFilter(SkFlattenableReadBuffer& buffer) : SkImageFilter(buffer)
- {
- m_color = buffer.readColor();
- }
-
- virtual void flatten(SkFlattenableWriteBuffer& buffer) const
- {
- this->SkImageFilter::flatten(buffer);
- buffer.writeColor(m_color);
- }
-
- virtual bool onFilterImage(Proxy* proxy, const SkBitmap& src, const SkMatrix& ctm, SkBitmap* result, SkIPoint* offset)
- {
- if (!src.width() || !src.height())
- return false;
-
- SkIRect bounds;
- src.getBounds(&bounds);
- if (!applyCropRect(&bounds, ctm)) {
- return false;
- }
-
- SkAutoTUnref<SkBaseDevice> device(proxy->createDevice(bounds.width(), bounds.height()));
- SkCanvas canvas(device.get());
- SkPaint paint;
- paint.setColor(m_color);
- canvas.drawRect(SkRect::MakeWH(src.width(), src.height()), paint);
- *result = device->accessBitmap(false);
- offset->fX += bounds.left();
- offset->fY += bounds.top();
- return true;
- }
-private:
- SkColor m_color;
-};
-
-}; // unnamed namespace
-
-namespace WebCore {
-
-FEFlood::FEFlood(Filter* filter, const Color& floodColor, float floodOpacity)
- : FilterEffect(filter)
- , m_floodColor(floodColor)
- , m_floodOpacity(floodOpacity)
-{
- FilterEffect::setOperatingColorSpace(ColorSpaceDeviceRGB);
- FilterEffect::setResultColorSpace(ColorSpaceDeviceRGB);
-}
-
-PassRefPtr<FEFlood> FEFlood::create(Filter* filter, const Color& floodColor, float floodOpacity)
-{
- return adoptRef(new FEFlood(filter, floodColor, floodOpacity));
-}
-
-Color FEFlood::floodColor() const
-{
- return m_floodColor;
-}
-
-bool FEFlood::setFloodColor(const Color& color)
-{
- if (m_floodColor == color)
- return false;
- m_floodColor = color;
- return true;
-}
-
-float FEFlood::floodOpacity() const
-{
- return m_floodOpacity;
-}
-
-bool FEFlood::setFloodOpacity(float floodOpacity)
-{
- if (m_floodOpacity == floodOpacity)
- return false;
- m_floodOpacity = floodOpacity;
- return true;
-}
-
-void FEFlood::applySoftware()
-{
- ImageBuffer* resultImage = createImageBufferResult();
- if (!resultImage)
- return;
-
- Color color = colorWithOverrideAlpha(floodColor().rgb(), floodOpacity());
- resultImage->context()->fillRect(FloatRect(FloatPoint(), absolutePaintRect().size()), color);
-}
-
-PassRefPtr<SkImageFilter> FEFlood::createImageFilter(SkiaImageFilterBuilder* builder)
-{
- Color color = colorWithOverrideAlpha(floodColor().rgb(), floodOpacity());
-
- SkIRect rect = getCropRect(builder->cropOffset());
- return adoptRef(new FloodImageFilter(color.rgb(), &rect));
-}
-
-TextStream& FEFlood::externalRepresentation(TextStream& ts, int indent) const
-{
- writeIndent(ts, indent);
- ts << "[feFlood";
- FilterEffect::externalRepresentation(ts);
- ts << " flood-color=\"" << floodColor().nameForRenderTreeAsText() << "\" "
- << "flood-opacity=\"" << floodOpacity() << "\"]\n";
- return ts;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEFlood.h b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEFlood.h
deleted file mode 100644
index 633fc98d056..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEFlood.h
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Copyright (C) 2004, 2005, 2006, 2007 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2004, 2005 Rob Buis <buis@kde.org>
- * Copyright (C) 2005 Eric Seidel <eric@webkit.org>
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#ifndef FEFlood_h
-#define FEFlood_h
-
-#include "core/platform/graphics/Color.h"
-#include "core/platform/graphics/filters/Filter.h"
-#include "core/platform/graphics/filters/FilterEffect.h"
-
-namespace WebCore {
-
-class FEFlood : public FilterEffect {
-public:
- static PassRefPtr<FEFlood> create(Filter* filter, const Color&, float);
-
- Color floodColor() const;
- bool setFloodColor(const Color &);
-
- float floodOpacity() const;
- bool setFloodOpacity(float);
-
- // feFlood does not perform color interpolation of any kind, so the result is always in the current
- // color space regardless of the value of color-interpolation-filters.
- void setOperatingColorSpace(ColorSpace) OVERRIDE { }
- void setResultColorSpace(ColorSpace) OVERRIDE { }
-
- virtual PassRefPtr<SkImageFilter> createImageFilter(SkiaImageFilterBuilder*) OVERRIDE;
-
- virtual void determineAbsolutePaintRect() { setAbsolutePaintRect(enclosingIntRect(maxEffectRect())); }
-
- virtual TextStream& externalRepresentation(TextStream&, int indention) const;
-
-private:
- FEFlood(Filter*, const Color&, float);
-
- virtual void applySoftware() OVERRIDE;
-
- Color m_floodColor;
- float m_floodOpacity;
-};
-
-} // namespace WebCore
-
-#endif // FEFlood_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEGaussianBlur.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEGaussianBlur.cpp
deleted file mode 100644
index 8c6318548fc..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEGaussianBlur.cpp
+++ /dev/null
@@ -1,366 +0,0 @@
-/*
- * Copyright (C) 2004, 2005, 2006, 2007 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2004, 2005 Rob Buis <buis@kde.org>
- * Copyright (C) 2005 Eric Seidel <eric@webkit.org>
- * Copyright (C) 2009 Dirk Schulze <krit@webkit.org>
- * Copyright (C) 2010 Igalia, S.L.
- * Copyright (C) Research In Motion Limited 2010. All rights reserved.
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-
-#include "core/platform/graphics/filters/FEGaussianBlur.h"
-
-#include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/graphics/cpu/arm/filters/FEGaussianBlurNEON.h"
-#include "core/platform/graphics/filters/Filter.h"
-#include "core/platform/graphics/filters/SkiaImageFilterBuilder.h"
-#include "core/platform/text/TextStream.h"
-#include "core/rendering/RenderTreeAsText.h"
-
-#include "wtf/MathExtras.h"
-#include "wtf/ParallelJobs.h"
-#include "wtf/Uint8ClampedArray.h"
-
-#include "SkBlurImageFilter.h"
-
-using namespace std;
-
-static inline float gaussianKernelFactor()
-{
- return 3 / 4.f * sqrtf(2 * piFloat);
-}
-
-static const unsigned gMaxKernelSize = 1000;
-
-namespace WebCore {
-
-FEGaussianBlur::FEGaussianBlur(Filter* filter, float x, float y)
- : FilterEffect(filter)
- , m_stdX(x)
- , m_stdY(y)
-{
-}
-
-PassRefPtr<FEGaussianBlur> FEGaussianBlur::create(Filter* filter, float x, float y)
-{
- return adoptRef(new FEGaussianBlur(filter, x, y));
-}
-
-float FEGaussianBlur::stdDeviationX() const
-{
- return m_stdX;
-}
-
-void FEGaussianBlur::setStdDeviationX(float x)
-{
- m_stdX = x;
-}
-
-float FEGaussianBlur::stdDeviationY() const
-{
- return m_stdY;
-}
-
-void FEGaussianBlur::setStdDeviationY(float y)
-{
- m_stdY = y;
-}
-
-inline void boxBlur(Uint8ClampedArray* srcPixelArray, Uint8ClampedArray* dstPixelArray,
- unsigned dx, int dxLeft, int dxRight, int stride, int strideLine, int effectWidth, int effectHeight, bool alphaImage)
-{
- for (int y = 0; y < effectHeight; ++y) {
- int line = y * strideLine;
- for (int channel = 3; channel >= 0; --channel) {
- int sum = 0;
- // Fill the kernel
- int maxKernelSize = min(dxRight, effectWidth);
- for (int i = 0; i < maxKernelSize; ++i)
- sum += srcPixelArray->item(line + i * stride + channel);
-
- // Blurring
- for (int x = 0; x < effectWidth; ++x) {
- int pixelByteOffset = line + x * stride + channel;
- dstPixelArray->set(pixelByteOffset, static_cast<unsigned char>(sum / dx));
- if (x >= dxLeft)
- sum -= srcPixelArray->item(pixelByteOffset - dxLeft * stride);
- if (x + dxRight < effectWidth)
- sum += srcPixelArray->item(pixelByteOffset + dxRight * stride);
- }
- if (alphaImage) // Source image is black, it just has different alpha values
- break;
- }
- }
-}
-
-inline void FEGaussianBlur::platformApplyGeneric(Uint8ClampedArray* srcPixelArray, Uint8ClampedArray* tmpPixelArray, unsigned kernelSizeX, unsigned kernelSizeY, IntSize& paintSize)
-{
- int stride = 4 * paintSize.width();
- int dxLeft = 0;
- int dxRight = 0;
- int dyLeft = 0;
- int dyRight = 0;
- Uint8ClampedArray* src = srcPixelArray;
- Uint8ClampedArray* dst = tmpPixelArray;
-
- for (int i = 0; i < 3; ++i) {
- if (kernelSizeX) {
- kernelPosition(i, kernelSizeX, dxLeft, dxRight);
-#if HAVE(ARM_NEON_INTRINSICS)
- if (!isAlphaImage())
- boxBlurNEON(src, dst, kernelSizeX, dxLeft, dxRight, 4, stride, paintSize.width(), paintSize.height());
- else
- boxBlur(src, dst, kernelSizeX, dxLeft, dxRight, 4, stride, paintSize.width(), paintSize.height(), true);
-#else
- boxBlur(src, dst, kernelSizeX, dxLeft, dxRight, 4, stride, paintSize.width(), paintSize.height(), isAlphaImage());
-#endif
- swap(src, dst);
- }
-
- if (kernelSizeY) {
- kernelPosition(i, kernelSizeY, dyLeft, dyRight);
-#if HAVE(ARM_NEON_INTRINSICS)
- if (!isAlphaImage())
- boxBlurNEON(src, dst, kernelSizeY, dyLeft, dyRight, stride, 4, paintSize.height(), paintSize.width());
- else
- boxBlur(src, dst, kernelSizeY, dyLeft, dyRight, stride, 4, paintSize.height(), paintSize.width(), true);
-#else
- boxBlur(src, dst, kernelSizeY, dyLeft, dyRight, stride, 4, paintSize.height(), paintSize.width(), isAlphaImage());
-#endif
- swap(src, dst);
- }
- }
-
- // The final result should be stored in srcPixelArray.
- if (dst == srcPixelArray) {
- ASSERT(src->length() == dst->length());
- memcpy(dst->data(), src->data(), src->length());
- }
-
-}
-
-void FEGaussianBlur::platformApplyWorker(PlatformApplyParameters* parameters)
-{
- IntSize paintSize(parameters->width, parameters->height);
- parameters->filter->platformApplyGeneric(parameters->srcPixelArray.get(), parameters->dstPixelArray.get(),
- parameters->kernelSizeX, parameters->kernelSizeY, paintSize);
-}
-
-inline void FEGaussianBlur::platformApply(Uint8ClampedArray* srcPixelArray, Uint8ClampedArray* tmpPixelArray, unsigned kernelSizeX, unsigned kernelSizeY, IntSize& paintSize)
-{
- int scanline = 4 * paintSize.width();
- int extraHeight = 3 * kernelSizeY * 0.5f;
- int optimalThreadNumber = (paintSize.width() * paintSize.height()) / (s_minimalRectDimension + extraHeight * paintSize.width());
-
- if (optimalThreadNumber > 1) {
- WTF::ParallelJobs<PlatformApplyParameters> parallelJobs(&platformApplyWorker, optimalThreadNumber);
-
- int jobs = parallelJobs.numberOfJobs();
- if (jobs > 1) {
- // Split the job into "blockHeight"-sized jobs but there a few jobs that need to be slightly larger since
- // blockHeight * jobs < total size. These extras are handled by the remainder "jobsWithExtra".
- const int blockHeight = paintSize.height() / jobs;
- const int jobsWithExtra = paintSize.height() % jobs;
-
- int currentY = 0;
- for (int job = 0; job < jobs; job++) {
- PlatformApplyParameters& params = parallelJobs.parameter(job);
- params.filter = this;
-
- int startY = !job ? 0 : currentY - extraHeight;
- currentY += job < jobsWithExtra ? blockHeight + 1 : blockHeight;
- int endY = job == jobs - 1 ? currentY : currentY + extraHeight;
-
- int blockSize = (endY - startY) * scanline;
- if (!job) {
- params.srcPixelArray = srcPixelArray;
- params.dstPixelArray = tmpPixelArray;
- } else {
- params.srcPixelArray = Uint8ClampedArray::createUninitialized(blockSize);
- params.dstPixelArray = Uint8ClampedArray::createUninitialized(blockSize);
- memcpy(params.srcPixelArray->data(), srcPixelArray->data() + startY * scanline, blockSize);
- }
-
- params.width = paintSize.width();
- params.height = endY - startY;
- params.kernelSizeX = kernelSizeX;
- params.kernelSizeY = kernelSizeY;
- }
-
- parallelJobs.execute();
-
- // Copy together the parts of the image.
- currentY = 0;
- for (int job = 1; job < jobs; job++) {
- PlatformApplyParameters& params = parallelJobs.parameter(job);
- int sourceOffset;
- int destinationOffset;
- int size;
- int adjustedBlockHeight = job < jobsWithExtra ? blockHeight + 1 : blockHeight;
-
- currentY += adjustedBlockHeight;
- sourceOffset = extraHeight * scanline;
- destinationOffset = currentY * scanline;
- size = adjustedBlockHeight * scanline;
-
- memcpy(srcPixelArray->data() + destinationOffset, params.srcPixelArray->data() + sourceOffset, size);
- }
- return;
- }
- // Fallback to single threaded mode.
- }
-
- // The selection here eventually should happen dynamically on some platforms.
- platformApplyGeneric(srcPixelArray, tmpPixelArray, kernelSizeX, kernelSizeY, paintSize);
-}
-
-void FEGaussianBlur::calculateUnscaledKernelSize(unsigned& kernelSizeX, unsigned& kernelSizeY, float stdX, float stdY)
-{
- ASSERT(stdX >= 0 && stdY >= 0);
-
- kernelSizeX = 0;
- if (stdX)
- kernelSizeX = max<unsigned>(2, static_cast<unsigned>(floorf(stdX * gaussianKernelFactor() + 0.5f)));
- kernelSizeY = 0;
- if (stdY)
- kernelSizeY = max<unsigned>(2, static_cast<unsigned>(floorf(stdY * gaussianKernelFactor() + 0.5f)));
-
- // Limit the kernel size to 1000. A bigger radius won't make a big difference for the result image but
- // inflates the absolute paint rect to much. This is compatible with Firefox' behavior.
- if (kernelSizeX > gMaxKernelSize)
- kernelSizeX = gMaxKernelSize;
- if (kernelSizeY > gMaxKernelSize)
- kernelSizeY = gMaxKernelSize;
-}
-
-void FEGaussianBlur::calculateKernelSize(Filter* filter, unsigned& kernelSizeX, unsigned& kernelSizeY, float stdX, float stdY)
-{
- stdX = filter->applyHorizontalScale(stdX);
- stdY = filter->applyVerticalScale(stdY);
-
- calculateUnscaledKernelSize(kernelSizeX, kernelSizeY, stdX, stdY);
-}
-
-void FEGaussianBlur::determineAbsolutePaintRect()
-{
- FloatRect absolutePaintRect = mapRect(inputEffect(0)->absolutePaintRect());
-
- if (clipsToBounds())
- absolutePaintRect.intersect(maxEffectRect());
- else
- absolutePaintRect.unite(maxEffectRect());
-
- setAbsolutePaintRect(enclosingIntRect(absolutePaintRect));
-}
-
-FloatRect FEGaussianBlur::mapRect(const FloatRect& rect, bool)
-{
- FloatRect result = rect;
- unsigned kernelSizeX = 0;
- unsigned kernelSizeY = 0;
- calculateKernelSize(filter(), kernelSizeX, kernelSizeY, m_stdX, m_stdY);
-
- // We take the half kernel size and multiply it with three, because we run box blur three times.
- result.inflateX(3 * kernelSizeX * 0.5f);
- result.inflateY(3 * kernelSizeY * 0.5f);
- return result;
-}
-
-void FEGaussianBlur::applySoftware()
-{
- FilterEffect* in = inputEffect(0);
-
- Uint8ClampedArray* srcPixelArray = createPremultipliedImageResult();
- if (!srcPixelArray)
- return;
-
- setIsAlphaImage(in->isAlphaImage());
-
- IntRect effectDrawingRect = requestedRegionOfInputImageData(in->absolutePaintRect());
- in->copyPremultipliedImage(srcPixelArray, effectDrawingRect);
-
- if (!m_stdX && !m_stdY)
- return;
-
- unsigned kernelSizeX = 0;
- unsigned kernelSizeY = 0;
- calculateKernelSize(filter(), kernelSizeX, kernelSizeY, m_stdX, m_stdY);
-
- IntSize paintSize = absolutePaintRect().size();
- RefPtr<Uint8ClampedArray> tmpImageData = Uint8ClampedArray::createUninitialized(paintSize.width() * paintSize.height() * 4);
- Uint8ClampedArray* tmpPixelArray = tmpImageData.get();
-
- platformApply(srcPixelArray, tmpPixelArray, kernelSizeX, kernelSizeY, paintSize);
-}
-
-bool FEGaussianBlur::applySkia()
-{
- ImageBuffer* resultImage = createImageBufferResult();
- if (!resultImage)
- return false;
-
- FilterEffect* in = inputEffect(0);
-
- IntRect drawingRegion = drawingRegionOfInputImage(in->absolutePaintRect());
-
- setIsAlphaImage(in->isAlphaImage());
-
- float stdX = filter()->applyHorizontalScale(m_stdX);
- float stdY = filter()->applyVerticalScale(m_stdY);
-
- RefPtr<Image> image = in->asImageBuffer()->copyImage(DontCopyBackingStore);
-
- SkPaint paint;
- GraphicsContext* dstContext = resultImage->context();
- paint.setImageFilter(new SkBlurImageFilter(stdX, stdY))->unref();
-
- dstContext->saveLayer(0, &paint);
- paint.setColor(0xFFFFFFFF);
- dstContext->drawImage(image.get(), drawingRegion.location(), CompositeCopy);
- dstContext->restoreLayer();
- return true;
-}
-
-PassRefPtr<SkImageFilter> FEGaussianBlur::createImageFilter(SkiaImageFilterBuilder* builder)
-{
- RefPtr<SkImageFilter> input(builder->build(inputEffect(0), operatingColorSpace()));
- float stdX = filter()->applyHorizontalScale(m_stdX);
- float stdY = filter()->applyVerticalScale(m_stdY);
- SkIRect rect = getCropRect(builder->cropOffset());
- return adoptRef(new SkBlurImageFilter(SkFloatToScalar(stdX), SkFloatToScalar(stdY), input.get(), &rect));
-}
-
-TextStream& FEGaussianBlur::externalRepresentation(TextStream& ts, int indent) const
-{
- writeIndent(ts, indent);
- ts << "[feGaussianBlur";
- FilterEffect::externalRepresentation(ts);
- ts << " stdDeviation=\"" << m_stdX << ", " << m_stdY << "\"]\n";
- inputEffect(0)->externalRepresentation(ts, indent + 1);
- return ts;
-}
-
-float FEGaussianBlur::calculateStdDeviation(float radius)
-{
- // Blur radius represents 2/3 times the kernel size, the dest pixel is half of the radius applied 3 times
- return max((radius * 2 / 3.f - 0.5f) / gaussianKernelFactor(), 0.f);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEGaussianBlur.h b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEGaussianBlur.h
deleted file mode 100644
index ed26fe87bc5..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEGaussianBlur.h
+++ /dev/null
@@ -1,113 +0,0 @@
-/*
- * Copyright (C) 2004, 2005, 2006, 2007 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2004, 2005 Rob Buis <buis@kde.org>
- * Copyright (C) 2005 Eric Seidel <eric@webkit.org>
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#ifndef FEGaussianBlur_h
-#define FEGaussianBlur_h
-
-#include "core/platform/graphics/filters/Filter.h"
-#include "core/platform/graphics/filters/FilterEffect.h"
-
-namespace WebCore {
-
-class FEGaussianBlur : public FilterEffect {
-public:
- static PassRefPtr<FEGaussianBlur> create(Filter*, float, float);
-
- float stdDeviationX() const;
- void setStdDeviationX(float);
-
- float stdDeviationY() const;
- void setStdDeviationY(float);
-
- static float calculateStdDeviation(float);
-
- virtual void determineAbsolutePaintRect();
- virtual FloatRect mapRect(const FloatRect&, bool forward = true) OVERRIDE FINAL;
- static void calculateKernelSize(Filter*, unsigned& kernelSizeX, unsigned& kernelSizeY, float stdX, float stdY);
- static void calculateUnscaledKernelSize(unsigned& kernelSizeX, unsigned& kernelSizeY, float stdX, float stdY);
-
- virtual TextStream& externalRepresentation(TextStream&, int indention) const;
-
-private:
- static const int s_minimalRectDimension = 100 * 100; // Empirical data limit for parallel jobs
-
- template<typename Type>
- friend class ParallelJobs;
-
- struct PlatformApplyParameters {
- FEGaussianBlur* filter;
- RefPtr<Uint8ClampedArray> srcPixelArray;
- RefPtr<Uint8ClampedArray> dstPixelArray;
- int width;
- int height;
- unsigned kernelSizeX;
- unsigned kernelSizeY;
- };
-
- static void platformApplyWorker(PlatformApplyParameters*);
-
- FEGaussianBlur(Filter*, float, float);
-
- virtual void applySoftware() OVERRIDE;
- virtual bool applySkia() OVERRIDE;
-
- static inline void kernelPosition(int boxBlur, unsigned& std, int& dLeft, int& dRight);
- inline void platformApply(Uint8ClampedArray* srcPixelArray, Uint8ClampedArray* tmpPixelArray, unsigned kernelSizeX, unsigned kernelSizeY, IntSize& paintSize);
-
- inline void platformApplyGeneric(Uint8ClampedArray* srcPixelArray, Uint8ClampedArray* tmpPixelArray, unsigned kernelSizeX, unsigned kernelSizeY, IntSize& paintSize);
- virtual PassRefPtr<SkImageFilter> createImageFilter(SkiaImageFilterBuilder*) OVERRIDE;
-
- float m_stdX;
- float m_stdY;
-};
-
-inline void FEGaussianBlur::kernelPosition(int boxBlur, unsigned& std, int& dLeft, int& dRight)
-{
- // check http://www.w3.org/TR/SVG/filters.html#feGaussianBlurElement for details
- switch (boxBlur) {
- case 0:
- if (!(std % 2)) {
- dLeft = std / 2 - 1;
- dRight = std - dLeft;
- } else {
- dLeft = std / 2;
- dRight = std - dLeft;
- }
- break;
- case 1:
- if (!(std % 2)) {
- dLeft++;
- dRight--;
- }
- break;
- case 2:
- if (!(std % 2)) {
- dRight++;
- std++;
- }
- break;
- }
-}
-
-} // namespace WebCore
-
-#endif // FEGaussianBlur_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FELighting.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FELighting.cpp
deleted file mode 100644
index 7482550021c..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FELighting.cpp
+++ /dev/null
@@ -1,492 +0,0 @@
-/*
- * Copyright (C) 2010 University of Szeged
- * Copyright (C) 2010 Zoltan Herczeg
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY UNIVERSITY OF SZEGED ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL UNIVERSITY OF SZEGED OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/platform/graphics/filters/FELighting.h"
-
-#include "core/platform/graphics/cpu/arm/filters/FELightingNEON.h"
-#include "wtf/ParallelJobs.h"
-
-#include "SkLightingImageFilter.h"
-#include "core/platform/graphics/filters/DistantLightSource.h"
-#include "core/platform/graphics/filters/PointLightSource.h"
-#include "core/platform/graphics/filters/SkiaImageFilterBuilder.h"
-#include "core/platform/graphics/filters/SpotLightSource.h"
-#include "core/platform/graphics/skia/NativeImageSkia.h"
-
-namespace WebCore {
-
-FELighting::FELighting(Filter* filter, LightingType lightingType, const Color& lightingColor, float surfaceScale,
- float diffuseConstant, float specularConstant, float specularExponent,
- float kernelUnitLengthX, float kernelUnitLengthY, PassRefPtr<LightSource> lightSource)
- : FilterEffect(filter)
- , m_lightingType(lightingType)
- , m_lightSource(lightSource)
- , m_lightingColor(lightingColor)
- , m_surfaceScale(surfaceScale)
- , m_diffuseConstant(diffuseConstant)
- , m_specularConstant(specularConstant)
- , m_specularExponent(specularExponent)
- , m_kernelUnitLengthX(kernelUnitLengthX)
- , m_kernelUnitLengthY(kernelUnitLengthY)
-{
-}
-
-const static int cPixelSize = 4;
-const static int cAlphaChannelOffset = 3;
-const static unsigned char cOpaqueAlpha = static_cast<unsigned char>(0xff);
-const static float cFactor1div2 = -1 / 2.f;
-const static float cFactor1div3 = -1 / 3.f;
-const static float cFactor1div4 = -1 / 4.f;
-const static float cFactor2div3 = -2 / 3.f;
-
-// << 1 is signed multiply by 2
-inline void FELighting::LightingData::topLeft(int offset, IntPoint& normalVector)
-{
- int center = static_cast<int>(pixels->item(offset + cAlphaChannelOffset));
- int right = static_cast<int>(pixels->item(offset + cPixelSize + cAlphaChannelOffset));
- offset += widthMultipliedByPixelSize;
- int bottom = static_cast<int>(pixels->item(offset + cAlphaChannelOffset));
- int bottomRight = static_cast<int>(pixels->item(offset + cPixelSize + cAlphaChannelOffset));
- normalVector.setX(-(center << 1) + (right << 1) - bottom + bottomRight);
- normalVector.setY(-(center << 1) - right + (bottom << 1) + bottomRight);
-}
-
-inline void FELighting::LightingData::topRow(int offset, IntPoint& normalVector)
-{
- int left = static_cast<int>(pixels->item(offset - cPixelSize + cAlphaChannelOffset));
- int center = static_cast<int>(pixels->item(offset + cAlphaChannelOffset));
- int right = static_cast<int>(pixels->item(offset + cPixelSize + cAlphaChannelOffset));
- offset += widthMultipliedByPixelSize;
- int bottomLeft = static_cast<int>(pixels->item(offset - cPixelSize + cAlphaChannelOffset));
- int bottom = static_cast<int>(pixels->item(offset + cAlphaChannelOffset));
- int bottomRight = static_cast<int>(pixels->item(offset + cPixelSize + cAlphaChannelOffset));
- normalVector.setX(-(left << 1) + (right << 1) - bottomLeft + bottomRight);
- normalVector.setY(-left - (center << 1) - right + bottomLeft + (bottom << 1) + bottomRight);
-}
-
-inline void FELighting::LightingData::topRight(int offset, IntPoint& normalVector)
-{
- int left = static_cast<int>(pixels->item(offset - cPixelSize + cAlphaChannelOffset));
- int center = static_cast<int>(pixels->item(offset + cAlphaChannelOffset));
- offset += widthMultipliedByPixelSize;
- int bottomLeft = static_cast<int>(pixels->item(offset - cPixelSize + cAlphaChannelOffset));
- int bottom = static_cast<int>(pixels->item(offset + cAlphaChannelOffset));
- normalVector.setX(-(left << 1) + (center << 1) - bottomLeft + bottom);
- normalVector.setY(-left - (center << 1) + bottomLeft + (bottom << 1));
-}
-
-inline void FELighting::LightingData::leftColumn(int offset, IntPoint& normalVector)
-{
- int center = static_cast<int>(pixels->item(offset + cAlphaChannelOffset));
- int right = static_cast<int>(pixels->item(offset + cPixelSize + cAlphaChannelOffset));
- offset -= widthMultipliedByPixelSize;
- int top = static_cast<int>(pixels->item(offset + cAlphaChannelOffset));
- int topRight = static_cast<int>(pixels->item(offset + cPixelSize + cAlphaChannelOffset));
- offset += widthMultipliedByPixelSize << 1;
- int bottom = static_cast<int>(pixels->item(offset + cAlphaChannelOffset));
- int bottomRight = static_cast<int>(pixels->item(offset + cPixelSize + cAlphaChannelOffset));
- normalVector.setX(-top + topRight - (center << 1) + (right << 1) - bottom + bottomRight);
- normalVector.setY(-(top << 1) - topRight + (bottom << 1) + bottomRight);
-}
-
-inline void FELighting::LightingData::interior(int offset, IntPoint& normalVector)
-{
- int left = static_cast<int>(pixels->item(offset - cPixelSize + cAlphaChannelOffset));
- int right = static_cast<int>(pixels->item(offset + cPixelSize + cAlphaChannelOffset));
- offset -= widthMultipliedByPixelSize;
- int topLeft = static_cast<int>(pixels->item(offset - cPixelSize + cAlphaChannelOffset));
- int top = static_cast<int>(pixels->item(offset + cAlphaChannelOffset));
- int topRight = static_cast<int>(pixels->item(offset + cPixelSize + cAlphaChannelOffset));
- offset += widthMultipliedByPixelSize << 1;
- int bottomLeft = static_cast<int>(pixels->item(offset - cPixelSize + cAlphaChannelOffset));
- int bottom = static_cast<int>(pixels->item(offset + cAlphaChannelOffset));
- int bottomRight = static_cast<int>(pixels->item(offset + cPixelSize + cAlphaChannelOffset));
- normalVector.setX(-topLeft + topRight - (left << 1) + (right << 1) - bottomLeft + bottomRight);
- normalVector.setY(-topLeft - (top << 1) - topRight + bottomLeft + (bottom << 1) + bottomRight);
-}
-
-inline void FELighting::LightingData::rightColumn(int offset, IntPoint& normalVector)
-{
- int left = static_cast<int>(pixels->item(offset - cPixelSize + cAlphaChannelOffset));
- int center = static_cast<int>(pixels->item(offset + cAlphaChannelOffset));
- offset -= widthMultipliedByPixelSize;
- int topLeft = static_cast<int>(pixels->item(offset - cPixelSize + cAlphaChannelOffset));
- int top = static_cast<int>(pixels->item(offset + cAlphaChannelOffset));
- offset += widthMultipliedByPixelSize << 1;
- int bottomLeft = static_cast<int>(pixels->item(offset - cPixelSize + cAlphaChannelOffset));
- int bottom = static_cast<int>(pixels->item(offset + cAlphaChannelOffset));
- normalVector.setX(-topLeft + top - (left << 1) + (center << 1) - bottomLeft + bottom);
- normalVector.setY(-topLeft - (top << 1) + bottomLeft + (bottom << 1));
-}
-
-inline void FELighting::LightingData::bottomLeft(int offset, IntPoint& normalVector)
-{
- int center = static_cast<int>(pixels->item(offset + cAlphaChannelOffset));
- int right = static_cast<int>(pixels->item(offset + cPixelSize + cAlphaChannelOffset));
- offset -= widthMultipliedByPixelSize;
- int top = static_cast<int>(pixels->item(offset + cAlphaChannelOffset));
- int topRight = static_cast<int>(pixels->item(offset + cPixelSize + cAlphaChannelOffset));
- normalVector.setX(-top + topRight - (center << 1) + (right << 1));
- normalVector.setY(-(top << 1) - topRight + (center << 1) + right);
-}
-
-inline void FELighting::LightingData::bottomRow(int offset, IntPoint& normalVector)
-{
- int left = static_cast<int>(pixels->item(offset - cPixelSize + cAlphaChannelOffset));
- int center = static_cast<int>(pixels->item(offset + cAlphaChannelOffset));
- int right = static_cast<int>(pixels->item(offset + cPixelSize + cAlphaChannelOffset));
- offset -= widthMultipliedByPixelSize;
- int topLeft = static_cast<int>(pixels->item(offset - cPixelSize + cAlphaChannelOffset));
- int top = static_cast<int>(pixels->item(offset + cAlphaChannelOffset));
- int topRight = static_cast<int>(pixels->item(offset + cPixelSize + cAlphaChannelOffset));
- normalVector.setX(-topLeft + topRight - (left << 1) + (right << 1));
- normalVector.setY(-topLeft - (top << 1) - topRight + left + (center << 1) + right);
-}
-
-inline void FELighting::LightingData::bottomRight(int offset, IntPoint& normalVector)
-{
- int left = static_cast<int>(pixels->item(offset - cPixelSize + cAlphaChannelOffset));
- int center = static_cast<int>(pixels->item(offset + cAlphaChannelOffset));
- offset -= widthMultipliedByPixelSize;
- int topLeft = static_cast<int>(pixels->item(offset - cPixelSize + cAlphaChannelOffset));
- int top = static_cast<int>(pixels->item(offset + cAlphaChannelOffset));
- normalVector.setX(-topLeft + top - (left << 1) + (center << 1));
- normalVector.setY(-topLeft - (top << 1) + left + (center << 1));
-}
-
-inline void FELighting::inlineSetPixel(int offset, LightingData& data, LightSource::PaintingData& paintingData,
- int lightX, int lightY, float factorX, float factorY, IntPoint& normal2DVector)
-{
- m_lightSource->updatePaintingData(paintingData, lightX, lightY, static_cast<float>(data.pixels->item(offset + cAlphaChannelOffset)) * data.surfaceScale);
-
- float lightStrength;
- if (!normal2DVector.x() && !normal2DVector.y()) {
- // Normal vector is (0, 0, 1). This is a quite frequent case.
- if (m_lightingType == FELighting::DiffuseLighting)
- lightStrength = m_diffuseConstant * paintingData.lightVector.z() / paintingData.lightVectorLength;
- else {
- FloatPoint3D halfwayVector = paintingData.lightVector;
- halfwayVector.setZ(halfwayVector.z() + paintingData.lightVectorLength);
- float halfwayVectorLength = halfwayVector.length();
- if (m_specularExponent == 1)
- lightStrength = m_specularConstant * halfwayVector.z() / halfwayVectorLength;
- else
- lightStrength = m_specularConstant * powf(halfwayVector.z() / halfwayVectorLength, m_specularExponent);
- }
- } else {
- FloatPoint3D normalVector;
- normalVector.setX(factorX * static_cast<float>(normal2DVector.x()) * data.surfaceScale);
- normalVector.setY(factorY * static_cast<float>(normal2DVector.y()) * data.surfaceScale);
- normalVector.setZ(1);
- float normalVectorLength = normalVector.length();
-
- if (m_lightingType == FELighting::DiffuseLighting)
- lightStrength = m_diffuseConstant * (normalVector * paintingData.lightVector) / (normalVectorLength * paintingData.lightVectorLength);
- else {
- FloatPoint3D halfwayVector = paintingData.lightVector;
- halfwayVector.setZ(halfwayVector.z() + paintingData.lightVectorLength);
- float halfwayVectorLength = halfwayVector.length();
- if (m_specularExponent == 1)
- lightStrength = m_specularConstant * (normalVector * halfwayVector) / (normalVectorLength * halfwayVectorLength);
- else
- lightStrength = m_specularConstant * powf((normalVector * halfwayVector) / (normalVectorLength * halfwayVectorLength), m_specularExponent);
- }
- }
-
- if (lightStrength > 1)
- lightStrength = 1;
- if (lightStrength < 0)
- lightStrength = 0;
-
- data.pixels->set(offset, static_cast<unsigned char>(lightStrength * paintingData.colorVector.x()));
- data.pixels->set(offset + 1, static_cast<unsigned char>(lightStrength * paintingData.colorVector.y()));
- data.pixels->set(offset + 2, static_cast<unsigned char>(lightStrength * paintingData.colorVector.z()));
-}
-
-void FELighting::setPixel(int offset, LightingData& data, LightSource::PaintingData& paintingData,
- int lightX, int lightY, float factorX, float factorY, IntPoint& normalVector)
-{
- inlineSetPixel(offset, data, paintingData, lightX, lightY, factorX, factorY, normalVector);
-}
-
-inline void FELighting::platformApplyGenericPaint(LightingData& data, LightSource::PaintingData& paintingData, int startY, int endY)
-{
- IntPoint normalVector;
- int offset = 0;
-
- for (int y = startY; y < endY; ++y) {
- offset = y * data.widthMultipliedByPixelSize + cPixelSize;
- for (int x = 1; x < data.widthDecreasedByOne; ++x, offset += cPixelSize) {
- data.interior(offset, normalVector);
- inlineSetPixel(offset, data, paintingData, x, y, cFactor1div4, cFactor1div4, normalVector);
- }
- }
-}
-
-void FELighting::platformApplyGenericWorker(PlatformApplyGenericParameters* parameters)
-{
- parameters->filter->platformApplyGenericPaint(parameters->data, parameters->paintingData, parameters->yStart, parameters->yEnd);
-}
-
-inline void FELighting::platformApplyGeneric(LightingData& data, LightSource::PaintingData& paintingData)
-{
- int optimalThreadNumber = ((data.widthDecreasedByOne - 1) * (data.heightDecreasedByOne - 1)) / s_minimalRectDimension;
- if (optimalThreadNumber > 1) {
- // Initialize parallel jobs
- WTF::ParallelJobs<PlatformApplyGenericParameters> parallelJobs(&platformApplyGenericWorker, optimalThreadNumber);
-
- // Fill the parameter array
- int job = parallelJobs.numberOfJobs();
- if (job > 1) {
- // Split the job into "yStep"-sized jobs but there a few jobs that need to be slightly larger since
- // yStep * jobs < total size. These extras are handled by the remainder "jobsWithExtra".
- const int yStep = (data.heightDecreasedByOne - 1) / job;
- const int jobsWithExtra = (data.heightDecreasedByOne - 1) % job;
-
- int yStart = 1;
- for (--job; job >= 0; --job) {
- PlatformApplyGenericParameters& params = parallelJobs.parameter(job);
- params.filter = this;
- params.data = data;
- params.paintingData = paintingData;
- params.yStart = yStart;
- yStart += job < jobsWithExtra ? yStep + 1 : yStep;
- params.yEnd = yStart;
- }
- parallelJobs.execute();
- return;
- }
- // Fallback to single threaded mode.
- }
-
- platformApplyGenericPaint(data, paintingData, 1, data.heightDecreasedByOne);
-}
-
-inline void FELighting::platformApply(LightingData& data, LightSource::PaintingData& paintingData)
-{
- // The selection here eventually should happen dynamically on some platforms.
-#if CPU(ARM_NEON) && CPU(ARM_TRADITIONAL) && COMPILER(GCC)
- platformApplyNeon(data, paintingData);
-#else
- platformApplyGeneric(data, paintingData);
-#endif
-}
-
-bool FELighting::drawLighting(Uint8ClampedArray* pixels, int width, int height)
-{
- LightSource::PaintingData paintingData;
- LightingData data;
-
- if (!m_lightSource)
- return false;
-
- // FIXME: do something if width or height (or both) is 1 pixel.
- // The W3 spec does not define this case. Now the filter just returns.
- if (width <= 2 || height <= 2)
- return false;
-
- data.pixels = pixels;
- data.surfaceScale = m_surfaceScale / 255.0f;
- data.widthMultipliedByPixelSize = width * cPixelSize;
- data.widthDecreasedByOne = width - 1;
- data.heightDecreasedByOne = height - 1;
- paintingData.colorVector = FloatPoint3D(m_lightingColor.red(), m_lightingColor.green(), m_lightingColor.blue());
- m_lightSource->initPaintingData(paintingData);
-
- // Top/Left corner.
- IntPoint normalVector;
- int offset = 0;
- data.topLeft(offset, normalVector);
- setPixel(offset, data, paintingData, 0, 0, cFactor2div3, cFactor2div3, normalVector);
-
- // Top/Right pixel.
- offset = data.widthMultipliedByPixelSize - cPixelSize;
- data.topRight(offset, normalVector);
- setPixel(offset, data, paintingData, data.widthDecreasedByOne, 0, cFactor2div3, cFactor2div3, normalVector);
-
- // Bottom/Left pixel.
- offset = data.heightDecreasedByOne * data.widthMultipliedByPixelSize;
- data.bottomLeft(offset, normalVector);
- setPixel(offset, data, paintingData, 0, data.heightDecreasedByOne, cFactor2div3, cFactor2div3, normalVector);
-
- // Bottom/Right pixel.
- offset = height * data.widthMultipliedByPixelSize - cPixelSize;
- data.bottomRight(offset, normalVector);
- setPixel(offset, data, paintingData, data.widthDecreasedByOne, data.heightDecreasedByOne, cFactor2div3, cFactor2div3, normalVector);
-
- if (width >= 3) {
- // Top row.
- offset = cPixelSize;
- for (int x = 1; x < data.widthDecreasedByOne; ++x, offset += cPixelSize) {
- data.topRow(offset, normalVector);
- inlineSetPixel(offset, data, paintingData, x, 0, cFactor1div3, cFactor1div2, normalVector);
- }
- // Bottom row.
- offset = data.heightDecreasedByOne * data.widthMultipliedByPixelSize + cPixelSize;
- for (int x = 1; x < data.widthDecreasedByOne; ++x, offset += cPixelSize) {
- data.bottomRow(offset, normalVector);
- inlineSetPixel(offset, data, paintingData, x, data.heightDecreasedByOne, cFactor1div3, cFactor1div2, normalVector);
- }
- }
-
- if (height >= 3) {
- // Left column.
- offset = data.widthMultipliedByPixelSize;
- for (int y = 1; y < data.heightDecreasedByOne; ++y, offset += data.widthMultipliedByPixelSize) {
- data.leftColumn(offset, normalVector);
- inlineSetPixel(offset, data, paintingData, 0, y, cFactor1div2, cFactor1div3, normalVector);
- }
- // Right column.
- offset = (data.widthMultipliedByPixelSize << 1) - cPixelSize;
- for (int y = 1; y < data.heightDecreasedByOne; ++y, offset += data.widthMultipliedByPixelSize) {
- data.rightColumn(offset, normalVector);
- inlineSetPixel(offset, data, paintingData, data.widthDecreasedByOne, y, cFactor1div2, cFactor1div3, normalVector);
- }
- }
-
- if (width >= 3 && height >= 3) {
- // Interior pixels.
- platformApply(data, paintingData);
- }
-
- int lastPixel = data.widthMultipliedByPixelSize * height;
- if (m_lightingType == DiffuseLighting) {
- for (int i = cAlphaChannelOffset; i < lastPixel; i += cPixelSize)
- data.pixels->set(i, cOpaqueAlpha);
- } else {
- for (int i = 0; i < lastPixel; i += cPixelSize) {
- unsigned char a1 = data.pixels->item(i);
- unsigned char a2 = data.pixels->item(i + 1);
- unsigned char a3 = data.pixels->item(i + 2);
- // alpha set to set to max(a1, a2, a3)
- data.pixels->set(i + 3, a1 >= a2 ? (a1 >= a3 ? a1 : a3) : (a2 >= a3 ? a2 : a3));
- }
- }
-
- return true;
-}
-
-void FELighting::applySoftware()
-{
- FilterEffect* in = inputEffect(0);
-
- Uint8ClampedArray* srcPixelArray = createPremultipliedImageResult();
- if (!srcPixelArray)
- return;
-
- setIsAlphaImage(false);
-
- IntRect effectDrawingRect = requestedRegionOfInputImageData(in->absolutePaintRect());
- in->copyPremultipliedImage(srcPixelArray, effectDrawingRect);
-
- // FIXME: support kernelUnitLengths other than (1,1). The issue here is that the W3
- // standard has no test case for them, and other browsers (like Firefox) has strange
- // output for various kernelUnitLengths, and I am not sure they are reliable.
- // Anyway, feConvolveMatrix should also use the implementation
-
- IntSize absolutePaintSize = absolutePaintRect().size();
- drawLighting(srcPixelArray, absolutePaintSize.width(), absolutePaintSize.height());
-}
-
-PassRefPtr<SkImageFilter> FELighting::createImageFilter(SkiaImageFilterBuilder* builder)
-{
- SkIRect rect = getCropRect(builder->cropOffset());
- RefPtr<SkImageFilter> input(builder ? builder->build(inputEffect(0), operatingColorSpace()) : 0);
- switch (m_lightSource->type()) {
- case LS_DISTANT: {
- DistantLightSource* distantLightSource = static_cast<DistantLightSource*>(m_lightSource.get());
- float azimuthRad = deg2rad(distantLightSource->azimuth());
- float elevationRad = deg2rad(distantLightSource->elevation());
- SkPoint3 direction(cosf(azimuthRad) * cosf(elevationRad),
- sinf(azimuthRad) * cosf(elevationRad),
- sinf(elevationRad));
- if (m_specularConstant > 0)
- return adoptRef(SkLightingImageFilter::CreateDistantLitSpecular(direction, m_lightingColor.rgb(), m_surfaceScale, m_specularConstant, m_specularExponent, input.get(), &rect));
- else
- return adoptRef(SkLightingImageFilter::CreateDistantLitDiffuse(direction, m_lightingColor.rgb(), m_surfaceScale, m_diffuseConstant, input.get(), &rect));
- }
- case LS_POINT: {
- PointLightSource* pointLightSource = static_cast<PointLightSource*>(m_lightSource.get());
- FloatPoint3D position = pointLightSource->position();
- SkPoint3 skPosition(position.x(), position.y(), position.z());
- if (m_specularConstant > 0)
- return adoptRef(SkLightingImageFilter::CreatePointLitSpecular(skPosition, m_lightingColor.rgb(), m_surfaceScale, m_specularConstant, m_specularExponent, input.get(), &rect));
- else
- return adoptRef(SkLightingImageFilter::CreatePointLitDiffuse(skPosition, m_lightingColor.rgb(), m_surfaceScale, m_diffuseConstant, input.get(), &rect));
- }
- case LS_SPOT: {
- SpotLightSource* spotLightSource = static_cast<SpotLightSource*>(m_lightSource.get());
- SkPoint3 location(spotLightSource->position().x(), spotLightSource->position().y(), spotLightSource->position().z());
- SkPoint3 target(spotLightSource->direction().x(), spotLightSource->direction().y(), spotLightSource->direction().z());
- float specularExponent = spotLightSource->specularExponent();
- float limitingConeAngle = spotLightSource->limitingConeAngle();
- if (!limitingConeAngle || limitingConeAngle > 90 || limitingConeAngle < -90)
- limitingConeAngle = 90;
- if (m_specularConstant > 0)
- return adoptRef(SkLightingImageFilter::CreateSpotLitSpecular(location, target, specularExponent, limitingConeAngle, m_lightingColor.rgb(), m_surfaceScale, m_specularConstant, m_specularExponent, input.get(), &rect));
- else
- return adoptRef(SkLightingImageFilter::CreateSpotLitDiffuse(location, target, specularExponent, limitingConeAngle, m_lightingColor.rgb(), m_surfaceScale, m_diffuseConstant, input.get(), &rect));
- }
- default:
- ASSERT_NOT_REACHED();
- return 0;
- }
-}
-
-bool FELighting::applySkia()
-{
- // For now, only use the skia implementation for accelerated rendering.
- if (filter()->renderingMode() != Accelerated)
- return false;
-
- ImageBuffer* resultImage = createImageBufferResult();
- if (!resultImage)
- return false;
-
- FilterEffect* in = inputEffect(0);
-
- IntRect drawingRegion = drawingRegionOfInputImage(in->absolutePaintRect());
-
- setIsAlphaImage(in->isAlphaImage());
-
- RefPtr<Image> image = in->asImageBuffer()->copyImage(DontCopyBackingStore);
- RefPtr<NativeImageSkia> nativeImage = image->nativeImageForCurrentFrame();
- if (!nativeImage)
- return false;
-
- GraphicsContext* dstContext = resultImage->context();
-
- SkPaint paint;
- RefPtr<SkImageFilter> filter = createImageFilter(0);
- paint.setImageFilter(filter.get());
- dstContext->drawBitmap(nativeImage->bitmap(), drawingRegion.location().x(), drawingRegion.location().y(), &paint);
- return true;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FELighting.h b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FELighting.h
deleted file mode 100644
index de73e8329c0..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FELighting.h
+++ /dev/null
@@ -1,128 +0,0 @@
-/*
- * Copyright (C) 2010 University of Szeged
- * Copyright (C) 2010 Zoltan Herczeg
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY UNIVERSITY OF SZEGED ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL UNIVERSITY OF SZEGED OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef FELighting_h
-#define FELighting_h
-
-#include "core/platform/graphics/Color.h"
-#include "core/platform/graphics/filters/Filter.h"
-#include "core/platform/graphics/filters/FilterEffect.h"
-#include "core/platform/graphics/filters/LightSource.h"
-#include "core/platform/graphics/filters/PointLightSource.h"
-#include "core/platform/graphics/filters/SpotLightSource.h"
-#include "wtf/Uint8ClampedArray.h"
-
-// Common base class for FEDiffuseLighting and FESpecularLighting
-
-namespace WebCore {
-
-struct FELightingPaintingDataForNeon;
-
-class FELighting : public FilterEffect {
-public:
- virtual PassRefPtr<SkImageFilter> createImageFilter(SkiaImageFilterBuilder*) OVERRIDE;
-
- virtual void determineAbsolutePaintRect() { setAbsolutePaintRect(enclosingIntRect(maxEffectRect())); }
-
-protected:
- static const int s_minimalRectDimension = 100 * 100; // Empirical data limit for parallel jobs
-
- enum LightingType {
- DiffuseLighting,
- SpecularLighting
- };
-
- struct LightingData {
- // This structure contains only read-only (SMP safe) data
- Uint8ClampedArray* pixels;
- float surfaceScale;
- int widthMultipliedByPixelSize;
- int widthDecreasedByOne;
- int heightDecreasedByOne;
-
- inline void topLeft(int offset, IntPoint& normalVector);
- inline void topRow(int offset, IntPoint& normalVector);
- inline void topRight(int offset, IntPoint& normalVector);
- inline void leftColumn(int offset, IntPoint& normalVector);
- inline void interior(int offset, IntPoint& normalVector);
- inline void rightColumn(int offset, IntPoint& normalVector);
- inline void bottomLeft(int offset, IntPoint& normalVector);
- inline void bottomRow(int offset, IntPoint& normalVector);
- inline void bottomRight(int offset, IntPoint& normalVector);
- };
-
- template<typename Type>
- friend class ParallelJobs;
-
- struct PlatformApplyGenericParameters {
- FELighting* filter;
- LightingData data;
- LightSource::PaintingData paintingData;
- int yStart;
- int yEnd;
- };
-
- static void platformApplyGenericWorker(PlatformApplyGenericParameters*);
- static void platformApplyNeonWorker(FELightingPaintingDataForNeon*);
-
- FELighting(Filter*, LightingType, const Color&, float, float, float, float, float, float, PassRefPtr<LightSource>);
-
- bool drawLighting(Uint8ClampedArray*, int, int);
- inline void inlineSetPixel(int offset, LightingData&, LightSource::PaintingData&,
- int lightX, int lightY, float factorX, float factorY, IntPoint& normalVector);
-
- // Not worth to inline every occurence of setPixel.
- void setPixel(int offset, LightingData&, LightSource::PaintingData&,
- int lightX, int lightY, float factorX, float factorY, IntPoint& normalVector);
-
- inline void platformApply(LightingData&, LightSource::PaintingData&);
-
- inline void platformApplyGenericPaint(LightingData&, LightSource::PaintingData&, int startX, int startY);
- inline void platformApplyGeneric(LightingData&, LightSource::PaintingData&);
-
- static int getPowerCoefficients(float exponent);
- inline void platformApplyNeon(LightingData&, LightSource::PaintingData&);
-
- LightingType m_lightingType;
- RefPtr<LightSource> m_lightSource;
-
- Color m_lightingColor;
- float m_surfaceScale;
- float m_diffuseConstant;
- float m_specularConstant;
- float m_specularExponent;
- float m_kernelUnitLengthX;
- float m_kernelUnitLengthY;
-
-private:
- virtual void applySoftware() OVERRIDE;
- virtual bool applySkia() OVERRIDE;
-};
-
-} // namespace WebCore
-
-#endif // FELighting_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEMerge.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEMerge.cpp
deleted file mode 100644
index 2dd3bbfad11..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEMerge.cpp
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * Copyright (C) 2004, 2005, 2006, 2007 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2004, 2005 Rob Buis <buis@kde.org>
- * Copyright (C) 2005 Eric Seidel <eric@webkit.org>
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-
-#include "core/platform/graphics/filters/FEMerge.h"
-
-#include "SkMergeImageFilter.h"
-#include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/graphics/filters/Filter.h"
-#include "core/platform/graphics/filters/SkiaImageFilterBuilder.h"
-#include "core/platform/text/TextStream.h"
-#include "core/rendering/RenderTreeAsText.h"
-#include "wtf/OwnArrayPtr.h"
-
-namespace WebCore {
-
-FEMerge::FEMerge(Filter* filter)
- : FilterEffect(filter)
-{
-}
-
-PassRefPtr<FEMerge> FEMerge::create(Filter* filter)
-{
- return adoptRef(new FEMerge(filter));
-}
-
-void FEMerge::applySoftware()
-{
- unsigned size = numberOfEffectInputs();
- ASSERT(size > 0);
-
- ImageBuffer* resultImage = createImageBufferResult();
- if (!resultImage)
- return;
-
- GraphicsContext* filterContext = resultImage->context();
- for (unsigned i = 0; i < size; ++i) {
- FilterEffect* in = inputEffect(i);
- filterContext->drawImageBuffer(in->asImageBuffer(), drawingRegionOfInputImage(in->absolutePaintRect()));
- }
-}
-
-PassRefPtr<SkImageFilter> FEMerge::createImageFilter(SkiaImageFilterBuilder* builder)
-{
- unsigned size = numberOfEffectInputs();
-
- OwnArrayPtr<RefPtr<SkImageFilter> > inputRefs = adoptArrayPtr(new RefPtr<SkImageFilter>[size]);
- OwnArrayPtr<SkImageFilter*> inputs = adoptArrayPtr(new SkImageFilter*[size]);
- for (unsigned i = 0; i < size; ++i) {
- inputRefs[i] = builder->build(inputEffect(i), operatingColorSpace());
- inputs[i] = inputRefs[i].get();
- }
- return adoptRef(new SkMergeImageFilter(inputs.get(), size));
-}
-
-TextStream& FEMerge::externalRepresentation(TextStream& ts, int indent) const
-{
- writeIndent(ts, indent);
- ts << "[feMerge";
- FilterEffect::externalRepresentation(ts);
- unsigned size = numberOfEffectInputs();
- ASSERT(size > 0);
- ts << " mergeNodes=\"" << size << "\"]\n";
- for (unsigned i = 0; i < size; ++i)
- inputEffect(i)->externalRepresentation(ts, indent + 1);
- return ts;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEMerge.h b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEMerge.h
deleted file mode 100644
index 83f37c74f97..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEMerge.h
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Copyright (C) 2004, 2005, 2006, 2007 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2004, 2005 Rob Buis <buis@kde.org>
- * Copyright (C) 2005 Eric Seidel <eric@webkit.org>
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#ifndef FEMerge_h
-#define FEMerge_h
-
-#include "core/platform/graphics/filters/Filter.h"
-#include "core/platform/graphics/filters/FilterEffect.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-class FEMerge : public FilterEffect {
-public:
- static PassRefPtr<FEMerge> create(Filter*);
-
- virtual PassRefPtr<SkImageFilter> createImageFilter(SkiaImageFilterBuilder*) OVERRIDE;
-
- virtual TextStream& externalRepresentation(TextStream&, int indention) const;
-
-private:
- FEMerge(Filter*);
-
- virtual void applySoftware() OVERRIDE;
-};
-
-} // namespace WebCore
-
-#endif // FEMerge_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEMorphology.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEMorphology.cpp
deleted file mode 100644
index 5ccbe693e5c..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEMorphology.cpp
+++ /dev/null
@@ -1,307 +0,0 @@
-/*
- * Copyright (C) 2004, 2005, 2006, 2007 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2004, 2005 Rob Buis <buis@kde.org>
- * Copyright (C) 2005 Eric Seidel <eric@webkit.org>
- * Copyright (C) 2009 Dirk Schulze <krit@webkit.org>
- * Copyright (C) Research In Motion Limited 2010. All rights reserved.
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-
-#include "core/platform/graphics/filters/FEMorphology.h"
-
-#include "core/platform/graphics/filters/Filter.h"
-#include "core/platform/graphics/filters/SkiaImageFilterBuilder.h"
-
-#include "core/platform/text/TextStream.h"
-#include "core/rendering/RenderTreeAsText.h"
-
-#include "wtf/ParallelJobs.h"
-#include "wtf/Uint8ClampedArray.h"
-#include "wtf/Vector.h"
-
-#include "SkMorphologyImageFilter.h"
-
-using std::min;
-using std::max;
-
-namespace WebCore {
-
-FEMorphology::FEMorphology(Filter* filter, MorphologyOperatorType type, float radiusX, float radiusY)
- : FilterEffect(filter)
- , m_type(type)
- , m_radiusX(radiusX)
- , m_radiusY(radiusY)
-{
-}
-
-PassRefPtr<FEMorphology> FEMorphology::create(Filter* filter, MorphologyOperatorType type, float radiusX, float radiusY)
-{
- return adoptRef(new FEMorphology(filter, type, radiusX, radiusY));
-}
-
-MorphologyOperatorType FEMorphology::morphologyOperator() const
-{
- return m_type;
-}
-
-bool FEMorphology::setMorphologyOperator(MorphologyOperatorType type)
-{
- if (m_type == type)
- return false;
- m_type = type;
- return true;
-}
-
-float FEMorphology::radiusX() const
-{
- return m_radiusX;
-}
-
-bool FEMorphology::setRadiusX(float radiusX)
-{
- if (m_radiusX == radiusX)
- return false;
- m_radiusX = radiusX;
- return true;
-}
-
-float FEMorphology::radiusY() const
-{
- return m_radiusY;
-}
-
-void FEMorphology::determineAbsolutePaintRect()
-{
- FloatRect paintRect = mapRect(inputEffect(0)->absolutePaintRect());
- if (clipsToBounds())
- paintRect.intersect(maxEffectRect());
- else
- paintRect.unite(maxEffectRect());
- setAbsolutePaintRect(enclosingIntRect(paintRect));
-}
-
-FloatRect FEMorphology::mapRect(const FloatRect& rect, bool)
-{
- FloatRect result = rect;
- result.inflateX(filter()->applyHorizontalScale(m_radiusX));
- result.inflateY(filter()->applyVerticalScale(m_radiusY));
- return result;
-}
-
-bool FEMorphology::setRadiusY(float radiusY)
-{
- if (m_radiusY == radiusY)
- return false;
- m_radiusY = radiusY;
- return true;
-}
-
-void FEMorphology::platformApplyGeneric(PaintingData* paintingData, int yStart, int yEnd)
-{
- Uint8ClampedArray* srcPixelArray = paintingData->srcPixelArray;
- Uint8ClampedArray* dstPixelArray = paintingData->dstPixelArray;
- const int width = paintingData->width;
- const int height = paintingData->height;
- const int effectWidth = width * 4;
- const int radiusX = paintingData->radiusX;
- const int radiusY = paintingData->radiusY;
-
- Vector<unsigned char> extrema;
- for (int y = yStart; y < yEnd; ++y) {
- int extremaStartY = max(0, y - radiusY);
- int extremaEndY = min(height - 1, y + radiusY);
- for (unsigned int clrChannel = 0; clrChannel < 4; ++clrChannel) {
- extrema.clear();
- // Compute extremas for each columns
- for (int x = 0; x <= radiusX; ++x) {
- unsigned char columnExtrema = srcPixelArray->item(extremaStartY * effectWidth + 4 * x + clrChannel);
- for (int eY = extremaStartY + 1; eY < extremaEndY; ++eY) {
- unsigned char pixel = srcPixelArray->item(eY * effectWidth + 4 * x + clrChannel);
- if ((m_type == FEMORPHOLOGY_OPERATOR_ERODE && pixel <= columnExtrema)
- || (m_type == FEMORPHOLOGY_OPERATOR_DILATE && pixel >= columnExtrema)) {
- columnExtrema = pixel;
- }
- }
-
- extrema.append(columnExtrema);
- }
-
- // Kernel is filled, get extrema of next column
- for (int x = 0; x < width; ++x) {
- const int endX = min(x + radiusX, width - 1);
- unsigned char columnExtrema = srcPixelArray->item(extremaStartY * effectWidth + endX * 4 + clrChannel);
- for (int i = extremaStartY + 1; i <= extremaEndY; ++i) {
- unsigned char pixel = srcPixelArray->item(i * effectWidth + endX * 4 + clrChannel);
- if ((m_type == FEMORPHOLOGY_OPERATOR_ERODE && pixel <= columnExtrema)
- || (m_type == FEMORPHOLOGY_OPERATOR_DILATE && pixel >= columnExtrema))
- columnExtrema = pixel;
- }
- if (x - radiusX >= 0)
- extrema.remove(0);
- if (x + radiusX <= width)
- extrema.append(columnExtrema);
-
- unsigned char entireExtrema = extrema[0];
- for (unsigned kernelIndex = 1; kernelIndex < extrema.size(); ++kernelIndex) {
- if ((m_type == FEMORPHOLOGY_OPERATOR_ERODE && extrema[kernelIndex] <= entireExtrema)
- || (m_type == FEMORPHOLOGY_OPERATOR_DILATE && extrema[kernelIndex] >= entireExtrema))
- entireExtrema = extrema[kernelIndex];
- }
- dstPixelArray->set(y * effectWidth + 4 * x + clrChannel, entireExtrema);
- }
- }
- }
-}
-
-void FEMorphology::platformApplyWorker(PlatformApplyParameters* param)
-{
- param->filter->platformApplyGeneric(param->paintingData, param->startY, param->endY);
-}
-
-void FEMorphology::platformApply(PaintingData* paintingData)
-{
- int optimalThreadNumber = (paintingData->width * paintingData->height) / s_minimalArea;
- if (optimalThreadNumber > 1) {
- ParallelJobs<PlatformApplyParameters> parallelJobs(&WebCore::FEMorphology::platformApplyWorker, optimalThreadNumber);
- int numOfThreads = parallelJobs.numberOfJobs();
- if (numOfThreads > 1) {
- // Split the job into "jobSize"-sized jobs but there a few jobs that need to be slightly larger since
- // jobSize * jobs < total size. These extras are handled by the remainder "jobsWithExtra".
- const int jobSize = paintingData->height / numOfThreads;
- const int jobsWithExtra = paintingData->height % numOfThreads;
- int currentY = 0;
- for (int job = numOfThreads - 1; job >= 0; --job) {
- PlatformApplyParameters& param = parallelJobs.parameter(job);
- param.filter = this;
- param.startY = currentY;
- currentY += job < jobsWithExtra ? jobSize + 1 : jobSize;
- param.endY = currentY;
- param.paintingData = paintingData;
- }
- parallelJobs.execute();
- return;
- }
- // Fallback to single thread model
- }
-
- platformApplyGeneric(paintingData, 0, paintingData->height);
-}
-
-
-void FEMorphology::applySoftware()
-{
- FilterEffect* in = inputEffect(0);
-
- Uint8ClampedArray* dstPixelArray = createPremultipliedImageResult();
- if (!dstPixelArray)
- return;
-
- setIsAlphaImage(in->isAlphaImage());
- if (m_radiusX <= 0 || m_radiusY <= 0) {
- dstPixelArray->zeroFill();
- return;
- }
-
- Filter* filter = this->filter();
- int radiusX = static_cast<int>(floorf(filter->applyHorizontalScale(m_radiusX)));
- int radiusY = static_cast<int>(floorf(filter->applyVerticalScale(m_radiusY)));
-
- IntRect effectDrawingRect = requestedRegionOfInputImageData(in->absolutePaintRect());
- RefPtr<Uint8ClampedArray> srcPixelArray = in->asPremultipliedImage(effectDrawingRect);
-
- PaintingData paintingData;
- paintingData.srcPixelArray = srcPixelArray.get();
- paintingData.dstPixelArray = dstPixelArray;
- paintingData.width = effectDrawingRect.width();
- paintingData.height = effectDrawingRect.height();
- paintingData.radiusX = min(effectDrawingRect.width() - 1, radiusX);
- paintingData.radiusY = min(effectDrawingRect.height() - 1, radiusY);
-
- platformApply(&paintingData);
-}
-
-bool FEMorphology::applySkia()
-{
- ImageBuffer* resultImage = createImageBufferResult();
- if (!resultImage)
- return false;
-
- FilterEffect* in = inputEffect(0);
-
- IntRect drawingRegion = drawingRegionOfInputImage(in->absolutePaintRect());
-
- setIsAlphaImage(in->isAlphaImage());
-
- float radiusX = filter()->applyHorizontalScale(m_radiusX);
- float radiusY = filter()->applyVerticalScale(m_radiusY);
-
- RefPtr<Image> image = in->asImageBuffer()->copyImage(DontCopyBackingStore);
-
- SkPaint paint;
- GraphicsContext* dstContext = resultImage->context();
- if (m_type == FEMORPHOLOGY_OPERATOR_DILATE)
- paint.setImageFilter(new SkDilateImageFilter(radiusX, radiusY))->unref();
- else if (m_type == FEMORPHOLOGY_OPERATOR_ERODE)
- paint.setImageFilter(new SkErodeImageFilter(radiusX, radiusY))->unref();
-
- dstContext->saveLayer(0, &paint);
- dstContext->drawImage(image.get(), drawingRegion.location(), CompositeCopy);
- dstContext->restoreLayer();
- return true;
-}
-
-PassRefPtr<SkImageFilter> FEMorphology::createImageFilter(SkiaImageFilterBuilder* builder)
-{
- RefPtr<SkImageFilter> input(builder->build(inputEffect(0), operatingColorSpace()));
- SkScalar radiusX = SkFloatToScalar(filter()->applyHorizontalScale(m_radiusX));
- SkScalar radiusY = SkFloatToScalar(filter()->applyVerticalScale(m_radiusY));
- if (m_type == FEMORPHOLOGY_OPERATOR_DILATE)
- return adoptRef(new SkDilateImageFilter(radiusX, radiusY, input.get()));
- return adoptRef(new SkErodeImageFilter(radiusX, radiusY, input.get()));
-}
-
-static TextStream& operator<<(TextStream& ts, const MorphologyOperatorType& type)
-{
- switch (type) {
- case FEMORPHOLOGY_OPERATOR_UNKNOWN:
- ts << "UNKNOWN";
- break;
- case FEMORPHOLOGY_OPERATOR_ERODE:
- ts << "ERODE";
- break;
- case FEMORPHOLOGY_OPERATOR_DILATE:
- ts << "DILATE";
- break;
- }
- return ts;
-}
-
-TextStream& FEMorphology::externalRepresentation(TextStream& ts, int indent) const
-{
- writeIndent(ts, indent);
- ts << "[feMorphology";
- FilterEffect::externalRepresentation(ts);
- ts << " operator=\"" << morphologyOperator() << "\" "
- << "radius=\"" << radiusX() << ", " << radiusY() << "\"]\n";
- inputEffect(0)->externalRepresentation(ts, indent + 1);
- return ts;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEMorphology.h b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEMorphology.h
deleted file mode 100644
index 8a9a57a91d8..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEMorphology.h
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
- * Copyright (C) 2004, 2005, 2006, 2007 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2004, 2005 Rob Buis <buis@kde.org>
- * Copyright (C) 2005 Eric Seidel <eric@webkit.org>
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#ifndef FEMorphology_h
-#define FEMorphology_h
-
-#include "core/platform/graphics/filters/Filter.h"
-#include "core/platform/graphics/filters/FilterEffect.h"
-
-namespace WebCore {
-
-enum MorphologyOperatorType {
- FEMORPHOLOGY_OPERATOR_UNKNOWN = 0,
- FEMORPHOLOGY_OPERATOR_ERODE = 1,
- FEMORPHOLOGY_OPERATOR_DILATE = 2
-};
-
-class FEMorphology : public FilterEffect {
-public:
- static PassRefPtr<FEMorphology> create(Filter*, MorphologyOperatorType, float radiusX, float radiusY);
- MorphologyOperatorType morphologyOperator() const;
- bool setMorphologyOperator(MorphologyOperatorType);
-
- float radiusX() const;
- bool setRadiusX(float);
-
- float radiusY() const;
- bool setRadiusY(float);
-
- virtual PassRefPtr<SkImageFilter> createImageFilter(SkiaImageFilterBuilder*) OVERRIDE;
-
- virtual void determineAbsolutePaintRect();
- virtual FloatRect mapRect(const FloatRect&, bool forward = true) OVERRIDE FINAL;
-
- virtual TextStream& externalRepresentation(TextStream&, int indention) const;
-
- struct PaintingData {
- Uint8ClampedArray* srcPixelArray;
- Uint8ClampedArray* dstPixelArray;
- int width;
- int height;
- int radiusX;
- int radiusY;
- };
-
- static const int s_minimalArea = (300 * 300); // Empirical data limit for parallel jobs
-
- struct PlatformApplyParameters {
- FEMorphology* filter;
- int startY;
- int endY;
- PaintingData* paintingData;
- };
-
- static void platformApplyWorker(PlatformApplyParameters*);
-
- inline void platformApply(PaintingData*);
- inline void platformApplyGeneric(PaintingData*, const int yStart, const int yEnd);
-private:
- FEMorphology(Filter*, MorphologyOperatorType, float radiusX, float radiusY);
-
- virtual void applySoftware() OVERRIDE;
- virtual bool applySkia() OVERRIDE;
-
- MorphologyOperatorType m_type;
- float m_radiusX;
- float m_radiusY;
-};
-
-} // namespace WebCore
-
-#endif // FEMorphology_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEOffset.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEOffset.cpp
deleted file mode 100644
index c89f4daab11..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEOffset.cpp
+++ /dev/null
@@ -1,182 +0,0 @@
-/*
- * Copyright (C) 2004, 2005, 2006, 2007 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2004, 2005 Rob Buis <buis@kde.org>
- * Copyright (C) 2005 Eric Seidel <eric@webkit.org>
- * Copyright (C) 2009 Dirk Schulze <krit@webkit.org>
- * Copyright (C) Research In Motion Limited 2010. All rights reserved.
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-
-#include "core/platform/graphics/filters/FEOffset.h"
-
-#include "SkFlattenableBuffers.h"
-#include "SkImageFilter.h"
-
-#include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/graphics/filters/Filter.h"
-#include "core/platform/graphics/filters/SkiaImageFilterBuilder.h"
-#include "core/platform/text/TextStream.h"
-#include "core/rendering/RenderTreeAsText.h"
-#include "third_party/skia/include/core/SkDevice.h"
-
-namespace WebCore {
-
-class OffsetImageFilter : public SkImageFilter {
-public:
- OffsetImageFilter(SkScalar dx, SkScalar dy, SkImageFilter* input, const SkIRect* cropRect = 0) : SkImageFilter(input, cropRect), m_dx(dx), m_dy(dy)
- {
- }
-
- virtual bool onFilterImage(Proxy* proxy, const SkBitmap& src, const SkMatrix& ctm, SkBitmap* dst, SkIPoint* offset)
- {
- SkBitmap source = src;
- SkImageFilter* input = getInput(0);
- SkIPoint srcOffset = SkIPoint::Make(0, 0);
- if (input && !input->filterImage(proxy, src, ctm, &source, &srcOffset))
- return false;
-
- SkIRect bounds;
- source.getBounds(&bounds);
-
- if (!applyCropRect(&bounds, ctm)) {
- return false;
- }
-
- SkAutoTUnref<SkBaseDevice> device(proxy->createDevice(bounds.width(), bounds.height()));
- SkCanvas canvas(device);
- SkPaint paint;
- paint.setXfermodeMode(SkXfermode::kSrc_Mode);
- canvas.drawBitmap(source, m_dx - bounds.left(), m_dy - bounds.top(), &paint);
- *dst = device->accessBitmap(false);
- offset->fX += bounds.left();
- offset->fY += bounds.top();
- return true;
- }
-
- SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(OffsetImageFilter)
-
-protected:
- explicit OffsetImageFilter(SkFlattenableReadBuffer& buffer)
- : SkImageFilter(buffer)
- {
- m_dx = buffer.readScalar();
- m_dy = buffer.readScalar();
- }
-
- virtual void flatten(SkFlattenableWriteBuffer& buffer) const
- {
- this->SkImageFilter::flatten(buffer);
- buffer.writeScalar(m_dx);
- buffer.writeScalar(m_dy);
- }
-
-private:
- SkScalar m_dx, m_dy;
-};
-
-FEOffset::FEOffset(Filter* filter, float dx, float dy)
- : FilterEffect(filter)
- , m_dx(dx)
- , m_dy(dy)
-{
-}
-
-PassRefPtr<FEOffset> FEOffset::create(Filter* filter, float dx, float dy)
-{
- return adoptRef(new FEOffset(filter, dx, dy));
-}
-
-float FEOffset::dx() const
-{
- return m_dx;
-}
-
-void FEOffset::setDx(float dx)
-{
- m_dx = dx;
-}
-
-float FEOffset::dy() const
-{
- return m_dy;
-}
-
-void FEOffset::setDy(float dy)
-{
- m_dy = dy;
-}
-
-void FEOffset::determineAbsolutePaintRect()
-{
- FloatRect paintRect = inputEffect(0)->absolutePaintRect();
- Filter* filter = this->filter();
- paintRect.move(filter->applyHorizontalScale(m_dx), filter->applyVerticalScale(m_dy));
- if (clipsToBounds())
- paintRect.intersect(maxEffectRect());
- else
- paintRect.unite(maxEffectRect());
- setAbsolutePaintRect(enclosingIntRect(paintRect));
-}
-
-FloatRect FEOffset::mapRect(const FloatRect& rect, bool forward)
-{
- FloatRect result = rect;
- if (forward)
- result.move(filter()->applyHorizontalScale(m_dx), filter()->applyHorizontalScale(m_dy));
- else
- result.move(-filter()->applyHorizontalScale(m_dx), -filter()->applyHorizontalScale(m_dy));
- return result;
-}
-
-void FEOffset::applySoftware()
-{
- FilterEffect* in = inputEffect(0);
-
- ImageBuffer* resultImage = createImageBufferResult();
- if (!resultImage)
- return;
-
- setIsAlphaImage(in->isAlphaImage());
-
- FloatRect drawingRegion = drawingRegionOfInputImage(in->absolutePaintRect());
- Filter* filter = this->filter();
- drawingRegion.move(filter->applyHorizontalScale(m_dx), filter->applyVerticalScale(m_dy));
- resultImage->context()->drawImageBuffer(in->asImageBuffer(), drawingRegion);
-}
-
-PassRefPtr<SkImageFilter> FEOffset::createImageFilter(SkiaImageFilterBuilder* builder)
-{
- RefPtr<SkImageFilter> input(builder->build(inputEffect(0), operatingColorSpace()));
- Filter* filter = this->filter();
- SkIRect cropRect = getCropRect(builder->cropOffset());
- return adoptRef(new OffsetImageFilter(SkFloatToScalar(filter->applyHorizontalScale(m_dx)), SkFloatToScalar(filter->applyVerticalScale(m_dy)), input.get(), &cropRect));
-}
-
-TextStream& FEOffset::externalRepresentation(TextStream& ts, int indent) const
-{
- writeIndent(ts, indent);
- ts << "[feOffset";
- FilterEffect::externalRepresentation(ts);
- ts << " dx=\"" << dx() << "\" dy=\"" << dy() << "\"]\n";
- inputEffect(0)->externalRepresentation(ts, indent + 1);
- return ts;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEOffset.h b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEOffset.h
deleted file mode 100644
index 31f08cca2af..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FEOffset.h
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Copyright (C) 2004, 2005, 2006, 2007 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2004, 2005 Rob Buis <buis@kde.org>
- * Copyright (C) 2005 Eric Seidel <eric@webkit.org>
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#ifndef FEOffset_h
-#define FEOffset_h
-
-#include "core/platform/graphics/filters/Filter.h"
-#include "core/platform/graphics/filters/FilterEffect.h"
-
-namespace WebCore {
-
-class FEOffset : public FilterEffect {
-public:
- static PassRefPtr<FEOffset> create(Filter*, float dx, float dy);
-
- float dx() const;
- void setDx(float);
-
- float dy() const;
- void setDy(float);
-
- virtual void determineAbsolutePaintRect();
- virtual FloatRect mapRect(const FloatRect&, bool forward = true) OVERRIDE FINAL;
-
- virtual TextStream& externalRepresentation(TextStream&, int indention) const;
-
- virtual PassRefPtr<SkImageFilter> createImageFilter(SkiaImageFilterBuilder*) OVERRIDE;
-
-private:
- FEOffset(Filter*, float dx, float dy);
-
- virtual void applySoftware() OVERRIDE;
-
- float m_dx;
- float m_dy;
-};
-
-} // namespace WebCore
-
-#endif // FEOffset_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FESpecularLighting.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FESpecularLighting.cpp
deleted file mode 100644
index 7c450e5b7ce..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FESpecularLighting.cpp
+++ /dev/null
@@ -1,152 +0,0 @@
-/*
- * Copyright (C) 2004, 2005, 2006, 2007 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2004, 2005 Rob Buis <buis@kde.org>
- * Copyright (C) 2005 Eric Seidel <eric@webkit.org>
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-
-#include "core/platform/graphics/filters/FESpecularLighting.h"
-
-#include "core/platform/graphics/filters/LightSource.h"
-#include "core/platform/text/TextStream.h"
-#include "core/rendering/RenderTreeAsText.h"
-
-namespace WebCore {
-
-FESpecularLighting::FESpecularLighting(Filter* filter, const Color& lightingColor, float surfaceScale,
- float specularConstant, float specularExponent, float kernelUnitLengthX,
- float kernelUnitLengthY, PassRefPtr<LightSource> lightSource)
- : FELighting(filter, SpecularLighting, lightingColor, surfaceScale, 0, specularConstant, specularExponent, kernelUnitLengthX, kernelUnitLengthY, lightSource)
-{
-}
-
-PassRefPtr<FESpecularLighting> FESpecularLighting::create(Filter* filter, const Color& lightingColor,
- float surfaceScale, float specularConstant, float specularExponent,
- float kernelUnitLengthX, float kernelUnitLengthY, PassRefPtr<LightSource> lightSource)
-{
- return adoptRef(new FESpecularLighting(filter, lightingColor, surfaceScale, specularConstant, specularExponent,
- kernelUnitLengthX, kernelUnitLengthY, lightSource));
-}
-
-FESpecularLighting::~FESpecularLighting()
-{
-}
-
-Color FESpecularLighting::lightingColor() const
-{
- return m_lightingColor;
-}
-
-bool FESpecularLighting::setLightingColor(const Color& lightingColor)
-{
- if (m_lightingColor == lightingColor)
- return false;
- m_lightingColor = lightingColor;
- return true;
-}
-
-float FESpecularLighting::surfaceScale() const
-{
- return m_surfaceScale;
-}
-
-bool FESpecularLighting::setSurfaceScale(float surfaceScale)
-{
- if (m_surfaceScale == surfaceScale)
- return false;
- m_surfaceScale = surfaceScale;
- return true;
-}
-
-float FESpecularLighting::specularConstant() const
-{
- return m_specularConstant;
-}
-
-bool FESpecularLighting::setSpecularConstant(float specularConstant)
-{
- if (m_specularConstant == specularConstant)
- return false;
- m_specularConstant = specularConstant;
- return true;
-}
-
-float FESpecularLighting::specularExponent() const
-{
- return m_specularExponent;
-}
-
-bool FESpecularLighting::setSpecularExponent(float specularExponent)
-{
- if (m_specularExponent == specularExponent)
- return false;
- m_specularExponent = specularExponent;
- return true;
-}
-
-float FESpecularLighting::kernelUnitLengthX() const
-{
- return m_kernelUnitLengthX;
-}
-
-bool FESpecularLighting::setKernelUnitLengthX(float kernelUnitLengthX)
-{
- if (m_kernelUnitLengthX == kernelUnitLengthX)
- return false;
- m_kernelUnitLengthX = kernelUnitLengthX;
- return true;
-}
-
-float FESpecularLighting::kernelUnitLengthY() const
-{
- return m_kernelUnitLengthY;
-}
-
-bool FESpecularLighting::setKernelUnitLengthY(float kernelUnitLengthY)
-{
- if (m_kernelUnitLengthY == kernelUnitLengthY)
- return false;
- m_kernelUnitLengthY = kernelUnitLengthY;
- return true;
-}
-
-const LightSource* FESpecularLighting::lightSource() const
-{
- return m_lightSource.get();
-}
-
-void FESpecularLighting::setLightSource(PassRefPtr<LightSource> lightSource)
-{
- m_lightSource = lightSource;
-}
-
-TextStream& FESpecularLighting::externalRepresentation(TextStream& ts, int indent) const
-{
- writeIndent(ts, indent);
- ts << "[feSpecularLighting";
- FilterEffect::externalRepresentation(ts);
- ts << " surfaceScale=\"" << m_surfaceScale << "\" "
- << "specualConstant=\"" << m_specularConstant << "\" "
- << "specularExponent=\"" << m_specularExponent << "\"]\n";
- inputEffect(0)->externalRepresentation(ts, indent + 1);
- return ts;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FESpecularLighting.h b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FESpecularLighting.h
deleted file mode 100644
index 617366ffb09..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FESpecularLighting.h
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * Copyright (C) 2004, 2005, 2006, 2007 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2004, 2005 Rob Buis <buis@kde.org>
- * Copyright (C) 2005 Eric Seidel <eric@webkit.org>
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#ifndef FESpecularLighting_h
-#define FESpecularLighting_h
-
-#include "core/platform/graphics/filters/FELighting.h"
-
-namespace WebCore {
-
-class FESpecularLighting : public FELighting {
-public:
- static PassRefPtr<FESpecularLighting> create(Filter*, const Color&, float, float,
- float, float, float, PassRefPtr<LightSource>);
- virtual ~FESpecularLighting();
-
- Color lightingColor() const;
- bool setLightingColor(const Color&);
-
- float surfaceScale() const;
- bool setSurfaceScale(float);
-
- float specularConstant() const;
- bool setSpecularConstant(float);
-
- float specularExponent() const;
- bool setSpecularExponent(float);
-
- float kernelUnitLengthX() const;
- bool setKernelUnitLengthX(float);
-
- float kernelUnitLengthY() const;
- bool setKernelUnitLengthY(float);
-
- const LightSource* lightSource() const;
- void setLightSource(PassRefPtr<LightSource>);
-
- virtual TextStream& externalRepresentation(TextStream&, int indention) const;
-
-private:
- FESpecularLighting(Filter*, const Color&, float, float, float, float, float, PassRefPtr<LightSource>);
-};
-
-} // namespace WebCore
-
-#endif // FESpecularLighting_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FETile.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FETile.cpp
deleted file mode 100644
index 14b647c22a9..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FETile.cpp
+++ /dev/null
@@ -1,172 +0,0 @@
-/*
- * Copyright (C) 2008 Alex Mathews <possessedpenguinbob@gmail.com>
- * Copyright (C) 2009 Dirk Schulze <krit@webkit.org>
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-
-#include "core/platform/graphics/filters/FETile.h"
-
-#include "SkFlattenableBuffers.h"
-#include "SkImageFilter.h"
-
-#include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/graphics/Pattern.h"
-#include "core/platform/graphics/filters/Filter.h"
-#include "core/platform/graphics/filters/SkiaImageFilterBuilder.h"
-#include "core/platform/graphics/transforms/AffineTransform.h"
-#include "core/platform/text/TextStream.h"
-#include "core/rendering/RenderTreeAsText.h"
-#include "core/rendering/svg/SVGRenderingContext.h"
-#include "third_party/skia/include/core/SkDevice.h"
-
-namespace WebCore {
-
-class TileImageFilter : public SkImageFilter {
-public:
- TileImageFilter(const SkRect& srcRect, const SkRect& dstRect, SkImageFilter* input)
- : SkImageFilter(input)
- , m_srcRect(srcRect)
- , m_dstRect(dstRect)
- {
- }
-
- virtual bool onFilterImage(Proxy* proxy, const SkBitmap& src, const SkMatrix& ctm, SkBitmap* dst, SkIPoint* offset)
- {
- SkBitmap source = src;
- SkImageFilter* input = getInput(0);
- SkIPoint localOffset = SkIPoint::Make(0, 0);
- if (input && !input->filterImage(proxy, src, ctm, &source, &localOffset))
- return false;
-
- if (!m_srcRect.width() || !m_srcRect.height() || !m_dstRect.width() || !m_dstRect.height())
- return false;
-
- SkIRect srcRect;
- m_srcRect.roundOut(&srcRect);
- SkBitmap subset;
- if (!source.extractSubset(&subset, srcRect))
- return false;
-
- SkAutoTUnref<SkBaseDevice> device(proxy->createDevice(m_dstRect.width(), m_dstRect.height()));
- SkIRect bounds;
- source.getBounds(&bounds);
- SkCanvas canvas(device);
- SkPaint paint;
- paint.setXfermodeMode(SkXfermode::kSrc_Mode);
-
- SkAutoTUnref<SkShader> shader(SkShader::CreateBitmapShader(subset, SkShader::kRepeat_TileMode, SkShader::kRepeat_TileMode));
- paint.setShader(shader);
- SkRect dstRect = m_dstRect;
- dstRect.offset(localOffset.fX, localOffset.fY);
- canvas.drawRect(dstRect, paint);
- *dst = device->accessBitmap(false);
- return true;
- }
-
- SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(TileImageFilter)
-
-protected:
- explicit TileImageFilter(SkFlattenableReadBuffer& buffer)
- : SkImageFilter(buffer)
- {
- buffer.readRect(&m_srcRect);
- buffer.readRect(&m_dstRect);
- }
-
- virtual void flatten(SkFlattenableWriteBuffer& buffer) const
- {
- this->SkImageFilter::flatten(buffer);
- buffer.writeRect(m_srcRect);
- buffer.writeRect(m_dstRect);
- }
-
-private:
- SkRect m_srcRect;
- SkRect m_dstRect;
-};
-
-FETile::FETile(Filter* filter)
- : FilterEffect(filter)
-{
-}
-
-PassRefPtr<FETile> FETile::create(Filter* filter)
-{
- return adoptRef(new FETile(filter));
-}
-
-void FETile::applySoftware()
-{
- FilterEffect* in = inputEffect(0);
-
- ImageBuffer* resultImage = createImageBufferResult();
- if (!resultImage)
- return;
-
- setIsAlphaImage(in->isAlphaImage());
-
- // Source input needs more attention. It has the size of the filterRegion but gives the
- // size of the cutted sourceImage back. This is part of the specification and optimization.
- FloatRect tileRect = in->maxEffectRect();
- FloatPoint inMaxEffectLocation = tileRect.location();
- FloatPoint maxEffectLocation = maxEffectRect().location();
- if (in->filterEffectType() == FilterEffectTypeSourceInput) {
- Filter* filter = this->filter();
- tileRect = filter->absoluteFilterRegion();
- tileRect.scale(filter->filterResolution().width(), filter->filterResolution().height());
- }
-
- OwnPtr<ImageBuffer> tileImage;
- if (!SVGRenderingContext::createImageBufferForPattern(tileRect, tileRect, tileImage, filter()->renderingMode()))
- return;
-
- GraphicsContext* tileImageContext = tileImage->context();
- tileImageContext->translate(-inMaxEffectLocation.x(), -inMaxEffectLocation.y());
- tileImageContext->drawImageBuffer(in->asImageBuffer(), in->absolutePaintRect().location());
-
- RefPtr<Pattern> pattern = Pattern::create(tileImage->copyImage(CopyBackingStore), true, true);
-
- AffineTransform patternTransform;
- patternTransform.translate(inMaxEffectLocation.x() - maxEffectLocation.x(), inMaxEffectLocation.y() - maxEffectLocation.y());
- pattern->setPatternSpaceTransform(patternTransform);
- GraphicsContext* filterContext = resultImage->context();
- filterContext->setFillPattern(pattern);
- filterContext->fillRect(FloatRect(FloatPoint(), absolutePaintRect().size()));
-}
-
-PassRefPtr<SkImageFilter> FETile::createImageFilter(SkiaImageFilterBuilder* builder)
-{
- RefPtr<SkImageFilter> input(builder->build(inputEffect(0), operatingColorSpace()));
- FloatRect srcRect = inputEffect(0) ? inputEffect(0)->effectBoundaries() : FloatRect();
- return adoptRef(new TileImageFilter(srcRect, effectBoundaries(), input.get()));
-}
-
-TextStream& FETile::externalRepresentation(TextStream& ts, int indent) const
-{
- writeIndent(ts, indent);
- ts << "[feTile";
- FilterEffect::externalRepresentation(ts);
- ts << "]\n";
- inputEffect(0)->externalRepresentation(ts, indent + 1);
-
- return ts;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FETile.h b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FETile.h
deleted file mode 100644
index 6f697efb857..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FETile.h
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Copyright (C) 2004, 2005, 2006, 2007 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2004, 2005 Rob Buis <buis@kde.org>
- * Copyright (C) 2005 Eric Seidel <eric@webkit.org>
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#ifndef FETile_h
-#define FETile_h
-
-#include "core/platform/graphics/filters/Filter.h"
-#include "core/platform/graphics/filters/FilterEffect.h"
-
-namespace WebCore {
-
-class FETile : public FilterEffect {
-public:
- static PassRefPtr<FETile> create(Filter* filter);
-
- virtual PassRefPtr<SkImageFilter> createImageFilter(SkiaImageFilterBuilder*) OVERRIDE;
-
- virtual void determineAbsolutePaintRect() { setAbsolutePaintRect(enclosingIntRect(maxEffectRect())); }
-
- virtual FilterEffectType filterEffectType() const { return FilterEffectTypeTile; }
-
- virtual TextStream& externalRepresentation(TextStream&, int indention) const;
-
-private:
- FETile(Filter*);
-
- virtual void applySoftware() OVERRIDE;
-};
-
-} // namespace WebCore
-
-#endif // FETile_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FETurbulence.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FETurbulence.cpp
deleted file mode 100644
index 29e0779c528..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FETurbulence.cpp
+++ /dev/null
@@ -1,475 +0,0 @@
-/*
- * Copyright (C) 2004, 2005, 2006, 2007 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2004, 2005 Rob Buis <buis@kde.org>
- * Copyright (C) 2005 Eric Seidel <eric@webkit.org>
- * Copyright (C) 2009 Dirk Schulze <krit@webkit.org>
- * Copyright (C) 2010 Renata Hodovan <reni@inf.u-szeged.hu>
- * Copyright (C) 2011 Gabor Loki <loki@webkit.org>
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-
-#include "core/platform/graphics/filters/FETurbulence.h"
-#include "SkPerlinNoiseShader.h"
-#include "SkRectShaderImageFilter.h"
-#include "core/platform/graphics/filters/Filter.h"
-#include "core/platform/text/TextStream.h"
-#include "core/rendering/RenderTreeAsText.h"
-
-#include "wtf/MathExtras.h"
-#include "wtf/ParallelJobs.h"
-#include "wtf/Uint8ClampedArray.h"
-
-namespace WebCore {
-
-/*
- Produces results in the range [1, 2**31 - 2]. Algorithm is:
- r = (a * r) mod m where a = randAmplitude = 16807 and
- m = randMaximum = 2**31 - 1 = 2147483647, r = seed.
- See [Park & Miller], CACM vol. 31 no. 10 p. 1195, Oct. 1988
- To test: the algorithm should produce the result 1043618065
- as the 10,000th generated number if the original seed is 1.
-*/
-static const int s_perlinNoise = 4096;
-static const long s_randMaximum = 2147483647; // 2**31 - 1
-static const int s_randAmplitude = 16807; // 7**5; primitive root of m
-static const int s_randQ = 127773; // m / a
-static const int s_randR = 2836; // m % a
-
-FETurbulence::FETurbulence(Filter* filter, TurbulenceType type, float baseFrequencyX, float baseFrequencyY, int numOctaves, float seed, bool stitchTiles)
- : FilterEffect(filter)
- , m_type(type)
- , m_baseFrequencyX(baseFrequencyX)
- , m_baseFrequencyY(baseFrequencyY)
- , m_numOctaves(numOctaves)
- , m_seed(seed)
- , m_stitchTiles(stitchTiles)
-{
-}
-
-PassRefPtr<FETurbulence> FETurbulence::create(Filter* filter, TurbulenceType type, float baseFrequencyX, float baseFrequencyY, int numOctaves, float seed, bool stitchTiles)
-{
- return adoptRef(new FETurbulence(filter, type, baseFrequencyX, baseFrequencyY, numOctaves, seed, stitchTiles));
-}
-
-TurbulenceType FETurbulence::type() const
-{
- return m_type;
-}
-
-bool FETurbulence::setType(TurbulenceType type)
-{
- if (m_type == type)
- return false;
- m_type = type;
- return true;
-}
-
-float FETurbulence::baseFrequencyY() const
-{
- return m_baseFrequencyY;
-}
-
-bool FETurbulence::setBaseFrequencyY(float baseFrequencyY)
-{
- if (m_baseFrequencyY == baseFrequencyY)
- return false;
- m_baseFrequencyY = baseFrequencyY;
- return true;
-}
-
-float FETurbulence::baseFrequencyX() const
-{
- return m_baseFrequencyX;
-}
-
-bool FETurbulence::setBaseFrequencyX(float baseFrequencyX)
-{
- if (m_baseFrequencyX == baseFrequencyX)
- return false;
- m_baseFrequencyX = baseFrequencyX;
- return true;
-}
-
-float FETurbulence::seed() const
-{
- return m_seed;
-}
-
-bool FETurbulence::setSeed(float seed)
-{
- if (m_seed == seed)
- return false;
- m_seed = seed;
- return true;
-}
-
-int FETurbulence::numOctaves() const
-{
- return m_numOctaves;
-}
-
-bool FETurbulence::setNumOctaves(int numOctaves)
-{
- if (m_numOctaves == numOctaves)
- return false;
- m_numOctaves = numOctaves;
- return true;
-}
-
-bool FETurbulence::stitchTiles() const
-{
- return m_stitchTiles;
-}
-
-bool FETurbulence::setStitchTiles(bool stitch)
-{
- if (m_stitchTiles == stitch)
- return false;
- m_stitchTiles = stitch;
- return true;
-}
-
-// The turbulence calculation code is an adapted version of what appears in the SVG 1.1 specification:
-// http://www.w3.org/TR/SVG11/filters.html#feTurbulence
-
-// Compute pseudo random number.
-inline long FETurbulence::PaintingData::random()
-{
- long result = s_randAmplitude * (seed % s_randQ) - s_randR * (seed / s_randQ);
- if (result <= 0)
- result += s_randMaximum;
- seed = result;
- return result;
-}
-
-inline float smoothCurve(float t)
-{
- return t * t * (3 - 2 * t);
-}
-
-inline float linearInterpolation(float t, float a, float b)
-{
- return a + t * (b - a);
-}
-
-inline void FETurbulence::initPaint(PaintingData& paintingData)
-{
- float normalizationFactor;
-
- // The seed value clamp to the range [1, s_randMaximum - 1].
- if (paintingData.seed <= 0)
- paintingData.seed = -(paintingData.seed % (s_randMaximum - 1)) + 1;
- if (paintingData.seed > s_randMaximum - 1)
- paintingData.seed = s_randMaximum - 1;
-
- float* gradient;
- for (int channel = 0; channel < 4; ++channel) {
- for (int i = 0; i < s_blockSize; ++i) {
- paintingData.latticeSelector[i] = i;
- gradient = paintingData.gradient[channel][i];
- gradient[0] = static_cast<float>((paintingData.random() % (2 * s_blockSize)) - s_blockSize) / s_blockSize;
- gradient[1] = static_cast<float>((paintingData.random() % (2 * s_blockSize)) - s_blockSize) / s_blockSize;
- normalizationFactor = sqrtf(gradient[0] * gradient[0] + gradient[1] * gradient[1]);
- gradient[0] /= normalizationFactor;
- gradient[1] /= normalizationFactor;
- }
- }
- for (int i = s_blockSize - 1; i > 0; --i) {
- int k = paintingData.latticeSelector[i];
- int j = paintingData.random() % s_blockSize;
- ASSERT(j >= 0);
- ASSERT(j < 2 * s_blockSize + 2);
- paintingData.latticeSelector[i] = paintingData.latticeSelector[j];
- paintingData.latticeSelector[j] = k;
- }
- for (int i = 0; i < s_blockSize + 2; ++i) {
- paintingData.latticeSelector[s_blockSize + i] = paintingData.latticeSelector[i];
- for (int channel = 0; channel < 4; ++channel) {
- paintingData.gradient[channel][s_blockSize + i][0] = paintingData.gradient[channel][i][0];
- paintingData.gradient[channel][s_blockSize + i][1] = paintingData.gradient[channel][i][1];
- }
- }
-}
-
-inline void checkNoise(int& noiseValue, int limitValue, int newValue)
-{
- if (noiseValue >= limitValue)
- noiseValue -= newValue;
- if (noiseValue >= limitValue - 1)
- noiseValue -= newValue - 1;
-}
-
-float FETurbulence::noise2D(int channel, PaintingData& paintingData, StitchData& stitchData, const FloatPoint& noiseVector)
-{
- struct Noise {
- int noisePositionIntegerValue;
- float noisePositionFractionValue;
-
- Noise(float component)
- {
- float position = component + s_perlinNoise;
- noisePositionIntegerValue = static_cast<int>(position);
- noisePositionFractionValue = position - noisePositionIntegerValue;
- }
- };
-
- Noise noiseX(noiseVector.x());
- Noise noiseY(noiseVector.y());
- float* q;
- float sx, sy, a, b, u, v;
-
- // If stitching, adjust lattice points accordingly.
- if (m_stitchTiles) {
- checkNoise(noiseX.noisePositionIntegerValue, stitchData.wrapX, stitchData.width);
- checkNoise(noiseY.noisePositionIntegerValue, stitchData.wrapY, stitchData.height);
- }
-
- noiseX.noisePositionIntegerValue &= s_blockMask;
- noiseY.noisePositionIntegerValue &= s_blockMask;
- int latticeIndex = paintingData.latticeSelector[noiseX.noisePositionIntegerValue];
- int nextLatticeIndex = paintingData.latticeSelector[(noiseX.noisePositionIntegerValue + 1) & s_blockMask];
-
- sx = smoothCurve(noiseX.noisePositionFractionValue);
- sy = smoothCurve(noiseY.noisePositionFractionValue);
-
- // This is taken 1:1 from SVG spec: http://www.w3.org/TR/SVG11/filters.html#feTurbulenceElement.
- int temp = paintingData.latticeSelector[latticeIndex + noiseY.noisePositionIntegerValue];
- q = paintingData.gradient[channel][temp];
- u = noiseX.noisePositionFractionValue * q[0] + noiseY.noisePositionFractionValue * q[1];
- temp = paintingData.latticeSelector[nextLatticeIndex + noiseY.noisePositionIntegerValue];
- q = paintingData.gradient[channel][temp];
- v = (noiseX.noisePositionFractionValue - 1) * q[0] + noiseY.noisePositionFractionValue * q[1];
- a = linearInterpolation(sx, u, v);
- temp = paintingData.latticeSelector[latticeIndex + noiseY.noisePositionIntegerValue + 1];
- q = paintingData.gradient[channel][temp];
- u = noiseX.noisePositionFractionValue * q[0] + (noiseY.noisePositionFractionValue - 1) * q[1];
- temp = paintingData.latticeSelector[nextLatticeIndex + noiseY.noisePositionIntegerValue + 1];
- q = paintingData.gradient[channel][temp];
- v = (noiseX.noisePositionFractionValue - 1) * q[0] + (noiseY.noisePositionFractionValue - 1) * q[1];
- b = linearInterpolation(sx, u, v);
- return linearInterpolation(sy, a, b);
-}
-
-unsigned char FETurbulence::calculateTurbulenceValueForPoint(int channel, PaintingData& paintingData, StitchData& stitchData, const FloatPoint& point, float baseFrequencyX, float baseFrequencyY)
-{
- float tileWidth = paintingData.filterSize.width();
- float tileHeight = paintingData.filterSize.height();
- ASSERT(tileWidth > 0 && tileHeight > 0);
- // Adjust the base frequencies if necessary for stitching.
- if (m_stitchTiles) {
- // When stitching tiled turbulence, the frequencies must be adjusted
- // so that the tile borders will be continuous.
- if (baseFrequencyX) {
- float lowFrequency = floorf(tileWidth * baseFrequencyX) / tileWidth;
- float highFrequency = ceilf(tileWidth * baseFrequencyX) / tileWidth;
- // BaseFrequency should be non-negative according to the standard.
- if (baseFrequencyX / lowFrequency < highFrequency / baseFrequencyX)
- baseFrequencyX = lowFrequency;
- else
- baseFrequencyX = highFrequency;
- }
- if (baseFrequencyY) {
- float lowFrequency = floorf(tileHeight * baseFrequencyY) / tileHeight;
- float highFrequency = ceilf(tileHeight * baseFrequencyY) / tileHeight;
- if (baseFrequencyY / lowFrequency < highFrequency / baseFrequencyY)
- baseFrequencyY = lowFrequency;
- else
- baseFrequencyY = highFrequency;
- }
- // Set up TurbulenceInitial stitch values.
- stitchData.width = roundf(tileWidth * baseFrequencyX);
- stitchData.wrapX = s_perlinNoise + stitchData.width;
- stitchData.height = roundf(tileHeight * baseFrequencyY);
- stitchData.wrapY = s_perlinNoise + stitchData.height;
- }
- float turbulenceFunctionResult = 0;
- FloatPoint noiseVector(point.x() * baseFrequencyX, point.y() * baseFrequencyY);
- float ratio = 1;
- for (int octave = 0; octave < m_numOctaves; ++octave) {
- if (m_type == FETURBULENCE_TYPE_FRACTALNOISE)
- turbulenceFunctionResult += noise2D(channel, paintingData, stitchData, noiseVector) / ratio;
- else
- turbulenceFunctionResult += fabsf(noise2D(channel, paintingData, stitchData, noiseVector)) / ratio;
- noiseVector.setX(noiseVector.x() * 2);
- noiseVector.setY(noiseVector.y() * 2);
- ratio *= 2;
- if (m_stitchTiles) {
- // Update stitch values. Subtracting s_perlinNoiseoise before the multiplication and
- // adding it afterward simplifies to subtracting it once.
- stitchData.width *= 2;
- stitchData.wrapX = 2 * stitchData.wrapX - s_perlinNoise;
- stitchData.height *= 2;
- stitchData.wrapY = 2 * stitchData.wrapY - s_perlinNoise;
- }
- }
-
- // The value of turbulenceFunctionResult comes from ((turbulenceFunctionResult * 255) + 255) / 2 by fractalNoise
- // and (turbulenceFunctionResult * 255) by turbulence.
- if (m_type == FETURBULENCE_TYPE_FRACTALNOISE)
- turbulenceFunctionResult = turbulenceFunctionResult * 0.5f + 0.5f;
- // Clamp result
- turbulenceFunctionResult = std::max(std::min(turbulenceFunctionResult, 1.f), 0.f);
- return static_cast<unsigned char>(turbulenceFunctionResult * 255);
-}
-
-inline void FETurbulence::fillRegion(Uint8ClampedArray* pixelArray, PaintingData& paintingData, int startY, int endY, float baseFrequencyX, float baseFrequencyY)
-{
- IntRect filterRegion = absolutePaintRect();
- IntPoint point(0, filterRegion.y() + startY);
- int indexOfPixelChannel = startY * (filterRegion.width() << 2);
- int channel;
- StitchData stitchData;
-
- for (int y = startY; y < endY; ++y) {
- point.setY(point.y() + 1);
- point.setX(filterRegion.x());
- for (int x = 0; x < filterRegion.width(); ++x) {
- point.setX(point.x() + 1);
- for (channel = 0; channel < 4; ++channel, ++indexOfPixelChannel)
- pixelArray->set(indexOfPixelChannel, calculateTurbulenceValueForPoint(channel, paintingData, stitchData, filter()->mapAbsolutePointToLocalPoint(point), baseFrequencyX, baseFrequencyY));
- }
- }
-}
-
-void FETurbulence::fillRegionWorker(FillRegionParameters* parameters)
-{
- parameters->filter->fillRegion(parameters->pixelArray, *parameters->paintingData, parameters->startY, parameters->endY, parameters->baseFrequencyX, parameters->baseFrequencyY);
-}
-
-void FETurbulence::applySoftware()
-{
- Uint8ClampedArray* pixelArray = createUnmultipliedImageResult();
- if (!pixelArray)
- return;
-
- if (absolutePaintRect().isEmpty()) {
- pixelArray->zeroFill();
- return;
- }
-
- PaintingData paintingData(m_seed, roundedIntSize(filterPrimitiveSubregion().size()));
- initPaint(paintingData);
- float baseFrequencyX = 1.0f / filter()->applyHorizontalScale(1.0f / m_baseFrequencyX);
- float baseFrequencyY = 1.0f / filter()->applyVerticalScale(1.0f / m_baseFrequencyY);
-
- int optimalThreadNumber = (absolutePaintRect().width() * absolutePaintRect().height()) / s_minimalRectDimension;
- if (optimalThreadNumber > 1) {
- // Initialize parallel jobs
- WTF::ParallelJobs<FillRegionParameters> parallelJobs(&WebCore::FETurbulence::fillRegionWorker, optimalThreadNumber);
-
- // Fill the parameter array
- int i = parallelJobs.numberOfJobs();
- if (i > 1) {
- // Split the job into "stepY"-sized jobs but there a few jobs that need to be slightly larger since
- // stepY * jobs < total size. These extras are handled by the remainder "jobsWithExtra".
- const int stepY = absolutePaintRect().height() / i;
- const int jobsWithExtra = absolutePaintRect().height() % i;
-
- int startY = 0;
- for (; i > 0; --i) {
- FillRegionParameters& params = parallelJobs.parameter(i-1);
- params.filter = this;
- params.pixelArray = pixelArray;
- params.paintingData = &paintingData;
- params.startY = startY;
- startY += i < jobsWithExtra ? stepY + 1 : stepY;
- params.endY = startY;
- params.baseFrequencyX = baseFrequencyX;
- params.baseFrequencyY = baseFrequencyY;
- }
-
- // Execute parallel jobs
- parallelJobs.execute();
- return;
- }
- }
-
- // Fallback to single threaded mode if there is no room for a new thread or the paint area is too small.
- fillRegion(pixelArray, paintingData, 0, absolutePaintRect().height(), baseFrequencyX, baseFrequencyY);
-}
-
-SkShader* FETurbulence::createShader(const IntRect& filterRegion)
-{
- const SkISize size = SkISize::Make(filterRegion.width(), filterRegion.height());
- float baseFrequencyX = 1.0f / filter()->applyHorizontalScale(1.0f / m_baseFrequencyX);
- const float baseFrequencyY = 1.0f / filter()->applyVerticalScale(1.0f / m_baseFrequencyY);
- return (type() == FETURBULENCE_TYPE_FRACTALNOISE) ?
- SkPerlinNoiseShader::CreateFractalNoise(SkFloatToScalar(baseFrequencyX),
- SkFloatToScalar(baseFrequencyY), numOctaves(), SkFloatToScalar(seed()),
- stitchTiles() ? &size : 0) :
- SkPerlinNoiseShader::CreateTubulence(SkFloatToScalar(baseFrequencyX),
- SkFloatToScalar(baseFrequencyY), numOctaves(), SkFloatToScalar(seed()),
- stitchTiles() ? &size : 0);
-}
-
-bool FETurbulence::applySkia()
-{
- // For now, only use the skia implementation for accelerated rendering.
- if (filter()->renderingMode() != Accelerated)
- return false;
-
- ImageBuffer* resultImage = createImageBufferResult();
- if (!resultImage)
- return false;
-
- const IntRect filterRegion = absolutePaintRect();
-
- SkPaint paint;
- paint.setShader(createShader(filterRegion))->unref();
- resultImage->context()->drawRect((SkRect)filterRegion, paint);
- return true;
-}
-
-PassRefPtr<SkImageFilter> FETurbulence::createImageFilter(SkiaImageFilterBuilder* builder)
-{
- SkAutoTUnref<SkShader> shader(createShader(IntRect()));
- return adoptRef(SkRectShaderImageFilter::Create(shader, SkRect()));
-}
-
-static TextStream& operator<<(TextStream& ts, const TurbulenceType& type)
-{
- switch (type) {
- case FETURBULENCE_TYPE_UNKNOWN:
- ts << "UNKNOWN";
- break;
- case FETURBULENCE_TYPE_TURBULENCE:
- ts << "TURBULENCE";
- break;
- case FETURBULENCE_TYPE_FRACTALNOISE:
- ts << "NOISE";
- break;
- }
- return ts;
-}
-
-TextStream& FETurbulence::externalRepresentation(TextStream& ts, int indent) const
-{
- writeIndent(ts, indent);
- ts << "[feTurbulence";
- FilterEffect::externalRepresentation(ts);
- ts << " type=\"" << type() << "\" "
- << "baseFrequency=\"" << baseFrequencyX() << ", " << baseFrequencyY() << "\" "
- << "seed=\"" << seed() << "\" "
- << "numOctaves=\"" << numOctaves() << "\" "
- << "stitchTiles=\"" << stitchTiles() << "\"]\n";
- return ts;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FETurbulence.h b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FETurbulence.h
deleted file mode 100644
index a294666dd9d..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FETurbulence.h
+++ /dev/null
@@ -1,140 +0,0 @@
-/*
- * Copyright (C) 2004, 2005, 2006, 2007 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2004, 2005 Rob Buis <buis@kde.org>
- * Copyright (C) 2005 Eric Seidel <eric@webkit.org>
- * Copyright (C) 2009 Dirk Schulze <krit@webkit.org>
- * Copyright (C) 2010 Renata Hodovan <reni@inf.u-szeged.hu>
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#ifndef FETurbulence_h
-#define FETurbulence_h
-
-#include "core/platform/graphics/filters/Filter.h"
-#include "core/platform/graphics/filters/FilterEffect.h"
-
-namespace WebCore {
-
-enum TurbulenceType {
- FETURBULENCE_TYPE_UNKNOWN = 0,
- FETURBULENCE_TYPE_FRACTALNOISE = 1,
- FETURBULENCE_TYPE_TURBULENCE = 2
-};
-
-class FETurbulence : public FilterEffect {
-public:
- static PassRefPtr<FETurbulence> create(Filter*, TurbulenceType, float, float, int, float, bool);
-
- TurbulenceType type() const;
- bool setType(TurbulenceType);
-
- float baseFrequencyY() const;
- bool setBaseFrequencyY(float);
-
- float baseFrequencyX() const;
- bool setBaseFrequencyX(float);
-
- float seed() const;
- bool setSeed(float);
-
- int numOctaves() const;
- bool setNumOctaves(int);
-
- bool stitchTiles() const;
- bool setStitchTiles(bool);
-
- static void fillRegionWorker(void*);
-
- virtual void determineAbsolutePaintRect() { setAbsolutePaintRect(enclosingIntRect(maxEffectRect())); }
-
- virtual TextStream& externalRepresentation(TextStream&, int indention) const;
-
-private:
- static const int s_blockSize = 256;
- static const int s_blockMask = s_blockSize - 1;
-
- static const int s_minimalRectDimension = (100 * 100); // Empirical data limit for parallel jobs.
-
- struct PaintingData {
- PaintingData(long paintingSeed, const IntSize& paintingSize)
- : seed(paintingSeed)
- , filterSize(paintingSize)
- {
- }
-
- long seed;
- int latticeSelector[2 * s_blockSize + 2];
- float gradient[4][2 * s_blockSize + 2][2];
- IntSize filterSize;
-
- inline long random();
- };
-
- struct StitchData {
- StitchData()
- : width(0)
- , wrapX(0)
- , height(0)
- , wrapY(0)
- {
- }
-
- int width; // How much to subtract to wrap for stitching.
- int wrapX; // Minimum value to wrap.
- int height;
- int wrapY;
- };
-
- template<typename Type>
- friend class ParallelJobs;
-
- struct FillRegionParameters {
- FETurbulence* filter;
- Uint8ClampedArray* pixelArray;
- PaintingData* paintingData;
- int startY;
- int endY;
- float baseFrequencyX;
- float baseFrequencyY;
- };
-
- static void fillRegionWorker(FillRegionParameters*);
-
- FETurbulence(Filter*, TurbulenceType, float, float, int, float, bool);
-
- virtual void applySoftware() OVERRIDE;
- virtual bool applySkia() OVERRIDE;
- virtual PassRefPtr<SkImageFilter> createImageFilter(SkiaImageFilterBuilder*) OVERRIDE;
- SkShader* createShader(const IntRect& filterRegion);
-
- inline void initPaint(PaintingData&);
- float noise2D(int channel, PaintingData&, StitchData&, const FloatPoint&);
- unsigned char calculateTurbulenceValueForPoint(int channel, PaintingData&, StitchData&, const FloatPoint&, float, float);
- inline void fillRegion(Uint8ClampedArray*, PaintingData&, int, int, float, float);
-
- TurbulenceType m_type;
- float m_baseFrequencyX;
- float m_baseFrequencyY;
- int m_numOctaves;
- float m_seed;
- bool m_stitchTiles;
-};
-
-} // namespace WebCore
-
-#endif // FETurbulence_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/Filter.h b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/Filter.h
deleted file mode 100644
index 1ac9e1c3903..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/Filter.h
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * Copyright (C) 2009 Dirk Schulze <krit@webkit.org>
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#ifndef Filter_h
-#define Filter_h
-
-#include "core/platform/graphics/FloatRect.h"
-#include "core/platform/graphics/FloatSize.h"
-#include "core/platform/graphics/ImageBuffer.h"
-#include "wtf/RefCounted.h"
-
-namespace WebCore {
-
-class FilterEffect;
-
-class Filter : public RefCounted<Filter> {
-public:
- Filter(const AffineTransform& absoluteTransform) : m_renderingMode(Unaccelerated), m_absoluteTransform(absoluteTransform) { }
- virtual ~Filter() { }
-
- void setSourceImage(PassOwnPtr<ImageBuffer> sourceImage) { m_sourceImage = sourceImage; }
- ImageBuffer* sourceImage() { return m_sourceImage.get(); }
-
- FloatSize filterResolution() const { return m_filterResolution; }
- void setFilterResolution(const FloatSize& filterResolution) { m_filterResolution = filterResolution; }
-
- const AffineTransform& absoluteTransform() const { return m_absoluteTransform; }
- void setAbsoluteTransform(const AffineTransform& absoluteTransform) { m_absoluteTransform = absoluteTransform; }
- FloatPoint mapAbsolutePointToLocalPoint(const FloatPoint& point) const { return m_absoluteTransform.inverse().mapPoint(point); }
-
- RenderingMode renderingMode() const { return m_renderingMode; }
- void setRenderingMode(RenderingMode renderingMode) { m_renderingMode = renderingMode; }
-
- virtual float applyHorizontalScale(float value) const
- {
- float filterRegionScale = absoluteFilterRegion().isEmpty() || filterRegion().isEmpty() ?
- 1.0f : absoluteFilterRegion().width() / filterRegion().width();
- return value * m_filterResolution.width() * filterRegionScale;
- }
- virtual float applyVerticalScale(float value) const
- {
- float filterRegionScale = absoluteFilterRegion().isEmpty() || filterRegion().isEmpty() ?
- 1.0f : absoluteFilterRegion().height() / filterRegion().height();
- return value * m_filterResolution.height() * filterRegionScale;
- }
-
- virtual FloatRect sourceImageRect() const = 0;
-
- FloatRect absoluteFilterRegion() const { return m_absoluteFilterRegion; }
- void setAbsoluteFilterRegion(const FloatRect& rect) { m_absoluteFilterRegion = rect; }
-
- FloatRect filterRegion() const { return m_filterRegion; }
- void setFilterRegion(const FloatRect& rect) { m_filterRegion = rect; }
-
-private:
- OwnPtr<ImageBuffer> m_sourceImage;
- FloatSize m_filterResolution;
- RenderingMode m_renderingMode;
- AffineTransform m_absoluteTransform;
- FloatRect m_absoluteFilterRegion;
- FloatRect m_filterRegion;
-};
-
-} // namespace WebCore
-
-#endif // Filter_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FilterEffect.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FilterEffect.cpp
deleted file mode 100644
index 5972bcddcc1..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FilterEffect.cpp
+++ /dev/null
@@ -1,497 +0,0 @@
-/*
- * Copyright (C) 2008 Alex Mathews <possessedpenguinbob@gmail.com>
- * Copyright (C) 2009 Dirk Schulze <krit@webkit.org>
- * Copyright (C) Research In Motion Limited 2010. All rights reserved.
- * Copyright (C) 2012 University of Szeged
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-
-#include "core/platform/graphics/filters/FilterEffect.h"
-
-#include "core/platform/graphics/ImageBuffer.h"
-#include "core/platform/graphics/filters/Filter.h"
-#include "third_party/skia/include/core/SkImageFilter.h"
-#include "wtf/Uint8ClampedArray.h"
-
-#if HAVE(ARM_NEON_INTRINSICS)
-#include <arm_neon.h>
-#endif
-
-namespace WebCore {
-
-FilterEffect::FilterEffect(Filter* filter)
- : m_alphaImage(false)
- , m_filter(filter)
- , m_hasX(false)
- , m_hasY(false)
- , m_hasWidth(false)
- , m_hasHeight(false)
- , m_clipsToBounds(true)
- , m_operatingColorSpace(ColorSpaceLinearRGB)
- , m_resultColorSpace(ColorSpaceDeviceRGB)
-{
- ASSERT(m_filter);
-}
-
-FilterEffect::~FilterEffect()
-{
-}
-
-inline bool isFilterSizeValid(IntRect rect)
-{
- if (rect.width() < 0 || rect.width() > kMaxFilterSize
- || rect.height() < 0 || rect.height() > kMaxFilterSize)
- return false;
- return true;
-}
-
-void FilterEffect::determineAbsolutePaintRect()
-{
- m_absolutePaintRect = IntRect();
- unsigned size = m_inputEffects.size();
- for (unsigned i = 0; i < size; ++i)
- m_absolutePaintRect.unite(m_inputEffects.at(i)->absolutePaintRect());
-
- // Filters in SVG clip to primitive subregion, while CSS doesn't.
- if (m_clipsToBounds)
- m_absolutePaintRect.intersect(enclosingIntRect(m_maxEffectRect));
- else
- m_absolutePaintRect.unite(enclosingIntRect(m_maxEffectRect));
-
-}
-
-FloatRect FilterEffect::mapRectRecursive(const FloatRect& rect)
-{
- FloatRect result;
- if (m_inputEffects.size() > 0) {
- result = m_inputEffects.at(0)->mapRectRecursive(rect);
- for (unsigned i = 1; i < m_inputEffects.size(); ++i)
- result.unite(m_inputEffects.at(i)->mapRectRecursive(rect));
- } else
- result = rect;
- return mapRect(result);
-}
-
-FloatRect FilterEffect::getSourceRect(const FloatRect& destRect, const FloatRect& destClipRect)
-{
- FloatRect sourceRect = mapRect(destRect, false);
- FloatRect sourceClipRect = mapRect(destClipRect, false);
-
- FloatRect boundaries = effectBoundaries();
- if (hasX())
- sourceClipRect.setX(boundaries.x());
- if (hasY())
- sourceClipRect.setY(boundaries.y());
- if (hasWidth())
- sourceClipRect.setWidth(boundaries.width());
- if (hasHeight())
- sourceClipRect.setHeight(boundaries.height());
-
- FloatRect result;
- if (m_inputEffects.size() > 0) {
- result = m_inputEffects.at(0)->getSourceRect(sourceRect, sourceClipRect);
- for (unsigned i = 1; i < m_inputEffects.size(); ++i)
- result.unite(m_inputEffects.at(i)->getSourceRect(sourceRect, sourceClipRect));
- } else {
- result = sourceRect;
- result.intersect(sourceClipRect);
- }
- return result;
-}
-
-IntRect FilterEffect::requestedRegionOfInputImageData(const IntRect& effectRect) const
-{
- ASSERT(hasResult());
- IntPoint location = m_absolutePaintRect.location();
- location.moveBy(-effectRect.location());
- return IntRect(location, m_absolutePaintRect.size());
-}
-
-IntRect FilterEffect::drawingRegionOfInputImage(const IntRect& srcRect) const
-{
- return IntRect(IntPoint(srcRect.x() - m_absolutePaintRect.x(),
- srcRect.y() - m_absolutePaintRect.y()), srcRect.size());
-}
-
-FilterEffect* FilterEffect::inputEffect(unsigned number) const
-{
- ASSERT_WITH_SECURITY_IMPLICATION(number < m_inputEffects.size());
- return m_inputEffects.at(number).get();
-}
-
-void FilterEffect::apply()
-{
- if (hasResult())
- return;
- unsigned size = m_inputEffects.size();
- for (unsigned i = 0; i < size; ++i) {
- FilterEffect* in = m_inputEffects.at(i).get();
- in->apply();
- if (!in->hasResult())
- return;
-
- // Convert input results to the current effect's color space.
- transformResultColorSpace(in, i);
- }
-
- determineAbsolutePaintRect();
- setResultColorSpace(m_operatingColorSpace);
-
- if (!isFilterSizeValid(m_absolutePaintRect))
- return;
-
- if (requiresValidPreMultipliedPixels()) {
- for (unsigned i = 0; i < size; ++i)
- inputEffect(i)->correctFilterResultIfNeeded();
- }
-
- if (applySkia())
- return;
-
- applySoftware();
-}
-
-void FilterEffect::forceValidPreMultipliedPixels()
-{
- // Must operate on pre-multiplied results; other formats cannot have invalid pixels.
- if (!m_premultipliedImageResult)
- return;
-
- Uint8ClampedArray* imageArray = m_premultipliedImageResult.get();
- unsigned char* pixelData = imageArray->data();
- int pixelArrayLength = imageArray->length();
-
- // We must have four bytes per pixel, and complete pixels
- ASSERT(!(pixelArrayLength % 4));
-
-#if HAVE(ARM_NEON_INTRINSICS)
- if (pixelArrayLength >= 64) {
- unsigned char* lastPixel = pixelData + (pixelArrayLength & ~0x3f);
- do {
- // Increments pixelData by 64.
- uint8x16x4_t sixteenPixels = vld4q_u8(pixelData);
- sixteenPixels.val[0] = vminq_u8(sixteenPixels.val[0], sixteenPixels.val[3]);
- sixteenPixels.val[1] = vminq_u8(sixteenPixels.val[1], sixteenPixels.val[3]);
- sixteenPixels.val[2] = vminq_u8(sixteenPixels.val[2], sixteenPixels.val[3]);
- vst4q_u8(pixelData, sixteenPixels);
- pixelData += 64;
- } while (pixelData < lastPixel);
-
- pixelArrayLength &= 0x3f;
- if (!pixelArrayLength)
- return;
- }
-#endif
-
- int numPixels = pixelArrayLength / 4;
-
- // Iterate over each pixel, checking alpha and adjusting color components if necessary
- while (--numPixels >= 0) {
- // Alpha is the 4th byte in a pixel
- unsigned char a = *(pixelData + 3);
- // Clamp each component to alpha, and increment the pixel location
- for (int i = 0; i < 3; ++i) {
- if (*pixelData > a)
- *pixelData = a;
- ++pixelData;
- }
- // Increment for alpha
- ++pixelData;
- }
-}
-
-void FilterEffect::clearResult()
-{
- if (m_imageBufferResult)
- m_imageBufferResult.clear();
- if (m_unmultipliedImageResult)
- m_unmultipliedImageResult.clear();
- if (m_premultipliedImageResult)
- m_premultipliedImageResult.clear();
-}
-
-void FilterEffect::clearResultsRecursive()
-{
- // Clear all results, regardless that the current effect has
- // a result. Can be used if an effect is in an erroneous state.
- if (hasResult())
- clearResult();
-
- unsigned size = m_inputEffects.size();
- for (unsigned i = 0; i < size; ++i)
- m_inputEffects.at(i).get()->clearResultsRecursive();
-}
-
-ImageBuffer* FilterEffect::asImageBuffer()
-{
- if (!hasResult())
- return 0;
- if (m_imageBufferResult)
- return m_imageBufferResult.get();
- m_imageBufferResult = ImageBuffer::create(m_absolutePaintRect.size(), 1, m_filter->renderingMode());
- IntRect destinationRect(IntPoint(), m_absolutePaintRect.size());
- if (m_premultipliedImageResult)
- m_imageBufferResult->putByteArray(Premultiplied, m_premultipliedImageResult.get(), destinationRect.size(), destinationRect, IntPoint());
- else
- m_imageBufferResult->putByteArray(Unmultiplied, m_unmultipliedImageResult.get(), destinationRect.size(), destinationRect, IntPoint());
- return m_imageBufferResult.get();
-}
-
-PassRefPtr<Uint8ClampedArray> FilterEffect::asUnmultipliedImage(const IntRect& rect)
-{
- ASSERT(isFilterSizeValid(rect));
- RefPtr<Uint8ClampedArray> imageData = Uint8ClampedArray::createUninitialized(rect.width() * rect.height() * 4);
- copyUnmultipliedImage(imageData.get(), rect);
- return imageData.release();
-}
-
-PassRefPtr<Uint8ClampedArray> FilterEffect::asPremultipliedImage(const IntRect& rect)
-{
- ASSERT(isFilterSizeValid(rect));
- RefPtr<Uint8ClampedArray> imageData = Uint8ClampedArray::createUninitialized(rect.width() * rect.height() * 4);
- copyPremultipliedImage(imageData.get(), rect);
- return imageData.release();
-}
-
-inline void FilterEffect::copyImageBytes(Uint8ClampedArray* source, Uint8ClampedArray* destination, const IntRect& rect)
-{
- // Initialize the destination to transparent black, if not entirely covered by the source.
- if (rect.x() < 0 || rect.y() < 0 || rect.maxX() > m_absolutePaintRect.width() || rect.maxY() > m_absolutePaintRect.height())
- memset(destination->data(), 0, destination->length());
-
- // Early return if the rect does not intersect with the source.
- if (rect.maxX() <= 0 || rect.maxY() <= 0 || rect.x() >= m_absolutePaintRect.width() || rect.y() >= m_absolutePaintRect.height())
- return;
-
- int xOrigin = rect.x();
- int xDest = 0;
- if (xOrigin < 0) {
- xDest = -xOrigin;
- xOrigin = 0;
- }
- int xEnd = rect.maxX();
- if (xEnd > m_absolutePaintRect.width())
- xEnd = m_absolutePaintRect.width();
-
- int yOrigin = rect.y();
- int yDest = 0;
- if (yOrigin < 0) {
- yDest = -yOrigin;
- yOrigin = 0;
- }
- int yEnd = rect.maxY();
- if (yEnd > m_absolutePaintRect.height())
- yEnd = m_absolutePaintRect.height();
-
- int size = (xEnd - xOrigin) * 4;
- int destinationScanline = rect.width() * 4;
- int sourceScanline = m_absolutePaintRect.width() * 4;
- unsigned char *destinationPixel = destination->data() + ((yDest * rect.width()) + xDest) * 4;
- unsigned char *sourcePixel = source->data() + ((yOrigin * m_absolutePaintRect.width()) + xOrigin) * 4;
-
- while (yOrigin < yEnd) {
- memcpy(destinationPixel, sourcePixel, size);
- destinationPixel += destinationScanline;
- sourcePixel += sourceScanline;
- ++yOrigin;
- }
-}
-
-void FilterEffect::copyUnmultipliedImage(Uint8ClampedArray* destination, const IntRect& rect)
-{
- ASSERT(hasResult());
-
- if (!m_unmultipliedImageResult) {
- // We prefer a conversion from the image buffer.
- if (m_imageBufferResult)
- m_unmultipliedImageResult = m_imageBufferResult->getUnmultipliedImageData(IntRect(IntPoint(), m_absolutePaintRect.size()));
- else {
- ASSERT(isFilterSizeValid(m_absolutePaintRect));
- m_unmultipliedImageResult = Uint8ClampedArray::createUninitialized(m_absolutePaintRect.width() * m_absolutePaintRect.height() * 4);
- unsigned char* sourceComponent = m_premultipliedImageResult->data();
- unsigned char* destinationComponent = m_unmultipliedImageResult->data();
- unsigned char* end = sourceComponent + (m_absolutePaintRect.width() * m_absolutePaintRect.height() * 4);
- while (sourceComponent < end) {
- int alpha = sourceComponent[3];
- if (alpha) {
- destinationComponent[0] = static_cast<int>(sourceComponent[0]) * 255 / alpha;
- destinationComponent[1] = static_cast<int>(sourceComponent[1]) * 255 / alpha;
- destinationComponent[2] = static_cast<int>(sourceComponent[2]) * 255 / alpha;
- } else {
- destinationComponent[0] = 0;
- destinationComponent[1] = 0;
- destinationComponent[2] = 0;
- }
- destinationComponent[3] = alpha;
- sourceComponent += 4;
- destinationComponent += 4;
- }
- }
- }
- copyImageBytes(m_unmultipliedImageResult.get(), destination, rect);
-}
-
-void FilterEffect::copyPremultipliedImage(Uint8ClampedArray* destination, const IntRect& rect)
-{
- ASSERT(hasResult());
-
- if (!m_premultipliedImageResult) {
- // We prefer a conversion from the image buffer.
- if (m_imageBufferResult)
- m_premultipliedImageResult = m_imageBufferResult->getPremultipliedImageData(IntRect(IntPoint(), m_absolutePaintRect.size()));
- else {
- ASSERT(isFilterSizeValid(m_absolutePaintRect));
- m_premultipliedImageResult = Uint8ClampedArray::createUninitialized(m_absolutePaintRect.width() * m_absolutePaintRect.height() * 4);
- unsigned char* sourceComponent = m_unmultipliedImageResult->data();
- unsigned char* destinationComponent = m_premultipliedImageResult->data();
- unsigned char* end = sourceComponent + (m_absolutePaintRect.width() * m_absolutePaintRect.height() * 4);
- while (sourceComponent < end) {
- int alpha = sourceComponent[3];
- destinationComponent[0] = static_cast<int>(sourceComponent[0]) * alpha / 255;
- destinationComponent[1] = static_cast<int>(sourceComponent[1]) * alpha / 255;
- destinationComponent[2] = static_cast<int>(sourceComponent[2]) * alpha / 255;
- destinationComponent[3] = alpha;
- sourceComponent += 4;
- destinationComponent += 4;
- }
- }
- }
- copyImageBytes(m_premultipliedImageResult.get(), destination, rect);
-}
-
-ImageBuffer* FilterEffect::createImageBufferResult()
-{
- // Only one result type is allowed.
- ASSERT(!hasResult());
- if (m_absolutePaintRect.isEmpty())
- return 0;
- m_imageBufferResult = ImageBuffer::create(m_absolutePaintRect.size(), 1, m_filter->renderingMode());
- if (!m_imageBufferResult)
- return 0;
- ASSERT(m_imageBufferResult->context());
- return m_imageBufferResult.get();
-}
-
-Uint8ClampedArray* FilterEffect::createUnmultipliedImageResult()
-{
- // Only one result type is allowed.
- ASSERT(!hasResult());
- ASSERT(isFilterSizeValid(m_absolutePaintRect));
-
- if (m_absolutePaintRect.isEmpty())
- return 0;
- m_unmultipliedImageResult = Uint8ClampedArray::createUninitialized(m_absolutePaintRect.width() * m_absolutePaintRect.height() * 4);
- return m_unmultipliedImageResult.get();
-}
-
-Uint8ClampedArray* FilterEffect::createPremultipliedImageResult()
-{
- // Only one result type is allowed.
- ASSERT(!hasResult());
- ASSERT(isFilterSizeValid(m_absolutePaintRect));
-
- if (m_absolutePaintRect.isEmpty())
- return 0;
- m_premultipliedImageResult = Uint8ClampedArray::createUninitialized(m_absolutePaintRect.width() * m_absolutePaintRect.height() * 4);
- return m_premultipliedImageResult.get();
-}
-
-void FilterEffect::transformResultColorSpace(ColorSpace dstColorSpace)
-{
- if (!hasResult() || dstColorSpace == m_resultColorSpace)
- return;
-
- // FIXME: We can avoid this potentially unnecessary ImageBuffer conversion by adding
- // color space transform support for the {pre,un}multiplied arrays.
- asImageBuffer()->transformColorSpace(m_resultColorSpace, dstColorSpace);
-
- m_resultColorSpace = dstColorSpace;
-
- if (m_unmultipliedImageResult)
- m_unmultipliedImageResult.clear();
- if (m_premultipliedImageResult)
- m_premultipliedImageResult.clear();
-}
-
-TextStream& FilterEffect::externalRepresentation(TextStream& ts, int) const
-{
- // FIXME: We should dump the subRegions of the filter primitives here later. This isn't
- // possible at the moment, because we need more detailed informations from the target object.
- return ts;
-}
-
-FloatRect FilterEffect::determineFilterPrimitiveSubregion()
-{
- ASSERT(filter());
-
- // FETile, FETurbulence, FEFlood don't have input effects, take the filter region as unite rect.
- FloatRect subregion;
- if (unsigned numberOfInputEffects = inputEffects().size()) {
- subregion = inputEffect(0)->determineFilterPrimitiveSubregion();
- for (unsigned i = 1; i < numberOfInputEffects; ++i)
- subregion.unite(inputEffect(i)->determineFilterPrimitiveSubregion());
- } else
- subregion = filter()->filterRegion();
-
- // After calling determineFilterPrimitiveSubregion on the target effect, reset the subregion again for <feTile>.
- if (filterEffectType() == FilterEffectTypeTile)
- subregion = filter()->filterRegion();
-
- subregion = mapRect(subregion);
-
- FloatRect boundaries = effectBoundaries();
- if (hasX())
- subregion.setX(boundaries.x());
- if (hasY())
- subregion.setY(boundaries.y());
- if (hasWidth())
- subregion.setWidth(boundaries.width());
- if (hasHeight())
- subregion.setHeight(boundaries.height());
-
- setFilterPrimitiveSubregion(subregion);
-
- FloatRect absoluteSubregion = filter()->absoluteTransform().mapRect(subregion);
- FloatSize filterResolution = filter()->filterResolution();
- absoluteSubregion.scale(filterResolution.width(), filterResolution.height());
-
- setMaxEffectRect(absoluteSubregion);
- return subregion;
-}
-
-PassRefPtr<SkImageFilter> FilterEffect::createImageFilter(SkiaImageFilterBuilder* builder)
-{
- return 0;
-}
-
-SkIRect FilterEffect::getCropRect(const FloatSize& cropOffset) const
-{
- SkIRect rect;
- FloatRect boundaries = effectBoundaries();
- FloatSize resolution = filter()->filterResolution();
- boundaries.scale(resolution.width(), resolution.height());
- rect.fLeft = hasX() ? static_cast<int>(boundaries.x()) + cropOffset.width() : 0;
- rect.fTop = hasY() ? static_cast<int>(boundaries.y()) + cropOffset.height() : 0;
- rect.fRight = hasWidth() ? rect.fLeft + static_cast<int>(boundaries.width()) : SK_MaxS32;
- rect.fBottom = hasHeight() ? rect.fTop + static_cast<int>(boundaries.height()) : SK_MaxS32;
- return rect;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FilterEffect.h b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FilterEffect.h
deleted file mode 100644
index 2aabe06acf4..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FilterEffect.h
+++ /dev/null
@@ -1,219 +0,0 @@
-/*
- * Copyright (C) 2008 Alex Mathews <possessedpenguinbob@gmail.com>
- * Copyright (C) 2009 Dirk Schulze <krit@webkit.org>
- * Copyright (C) Research In Motion Limited 2010. All rights reserved.
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#ifndef FilterEffect_h
-#define FilterEffect_h
-
-#include "core/platform/graphics/ColorSpace.h"
-#include "core/platform/graphics/FloatRect.h"
-#include "core/platform/graphics/IntRect.h"
-
-#include "wtf/PassOwnPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/RefPtr.h"
-#include "wtf/Uint8ClampedArray.h"
-#include "wtf/Vector.h"
-
-static const float kMaxFilterSize = 5000.0f;
-
-class SkImageFilter;
-
-namespace WebCore {
-
-class Filter;
-class FilterEffect;
-class ImageBuffer;
-class TextStream;
-
-class SkiaImageFilterBuilder;
-
-typedef Vector<RefPtr<FilterEffect> > FilterEffectVector;
-
-enum FilterEffectType {
- FilterEffectTypeUnknown,
- FilterEffectTypeImage,
- FilterEffectTypeTile,
- FilterEffectTypeSourceInput
-};
-
-class FilterEffect : public RefCounted<FilterEffect> {
-public:
- virtual ~FilterEffect();
-
- void clearResult();
- void clearResultsRecursive();
-
- ImageBuffer* asImageBuffer();
- PassRefPtr<Uint8ClampedArray> asUnmultipliedImage(const IntRect&);
- PassRefPtr<Uint8ClampedArray> asPremultipliedImage(const IntRect&);
- void copyUnmultipliedImage(Uint8ClampedArray* destination, const IntRect&);
- void copyPremultipliedImage(Uint8ClampedArray* destination, const IntRect&);
-
- FilterEffectVector& inputEffects() { return m_inputEffects; }
- FilterEffect* inputEffect(unsigned) const;
- unsigned numberOfEffectInputs() const { return m_inputEffects.size(); }
-
- inline bool hasResult() const
- {
- // This function needs platform specific checks, if the memory managment is not done by FilterEffect.
- return m_imageBufferResult
- || m_unmultipliedImageResult
- || m_premultipliedImageResult;
- }
-
- IntRect drawingRegionOfInputImage(const IntRect&) const;
- IntRect requestedRegionOfInputImageData(const IntRect&) const;
-
- // Solid black image with different alpha values.
- bool isAlphaImage() const { return m_alphaImage; }
- void setIsAlphaImage(bool alphaImage) { m_alphaImage = alphaImage; }
-
- IntRect absolutePaintRect() const { return m_absolutePaintRect; }
- void setAbsolutePaintRect(const IntRect& absolutePaintRect) { m_absolutePaintRect = absolutePaintRect; }
-
- FloatRect maxEffectRect() const { return m_maxEffectRect; }
- void setMaxEffectRect(const FloatRect& maxEffectRect) { m_maxEffectRect = maxEffectRect; }
-
- void apply();
-
- // Correct any invalid pixels, if necessary, in the result of a filter operation.
- // This method is used to ensure valid pixel values on filter inputs and the final result.
- // Only the arithmetic composite filter ever needs to perform correction.
- virtual void correctFilterResultIfNeeded() { }
-
- virtual PassRefPtr<SkImageFilter> createImageFilter(SkiaImageFilterBuilder*);
-
- virtual void determineAbsolutePaintRect();
-
- // Mapping a rect forwards determines which which destination pixels a
- // given source rect would affect. Mapping a rect backwards determines
- // which pixels from the source rect would be required to fill a given
- // destination rect. Note that these are not necessarily the inverse of
- // each other. For example, for FEGaussianBlur, they are the same
- // transformation.
- virtual FloatRect mapRect(const FloatRect& rect, bool forward = true) { return rect; }
- FloatRect mapRectRecursive(const FloatRect&);
-
- // This is a recursive version of a backwards mapRect(), which also takes
- // into account the filter primitive subregion of each effect.
- FloatRect getSourceRect(const FloatRect& destRect, const FloatRect& clipRect);
-
- virtual FilterEffectType filterEffectType() const { return FilterEffectTypeUnknown; }
-
- virtual TextStream& externalRepresentation(TextStream&, int indention = 0) const;
-
- // The following functions are SVG specific and will move to RenderSVGResourceFilterPrimitive.
- // See bug https://bugs.webkit.org/show_bug.cgi?id=45614.
- bool hasX() const { return m_hasX; }
- void setHasX(bool value) { m_hasX = value; }
-
- bool hasY() const { return m_hasY; }
- void setHasY(bool value) { m_hasY = value; }
-
- bool hasWidth() const { return m_hasWidth; }
- void setHasWidth(bool value) { m_hasWidth = value; }
-
- bool hasHeight() const { return m_hasHeight; }
- void setHasHeight(bool value) { m_hasHeight = value; }
-
- FloatRect filterPrimitiveSubregion() const { return m_filterPrimitiveSubregion; }
- void setFilterPrimitiveSubregion(const FloatRect& filterPrimitiveSubregion) { m_filterPrimitiveSubregion = filterPrimitiveSubregion; }
-
- FloatRect effectBoundaries() const { return m_effectBoundaries; }
- void setEffectBoundaries(const FloatRect& effectBoundaries) { m_effectBoundaries = effectBoundaries; }
-
- Filter* filter() { return m_filter; }
- const Filter* filter() const { return m_filter; }
-
- bool clipsToBounds() const { return m_clipsToBounds; }
- void setClipsToBounds(bool value) { m_clipsToBounds = value; }
-
- ColorSpace operatingColorSpace() const { return m_operatingColorSpace; }
- virtual void setOperatingColorSpace(ColorSpace colorSpace) { m_operatingColorSpace = colorSpace; }
- ColorSpace resultColorSpace() const { return m_resultColorSpace; }
- virtual void setResultColorSpace(ColorSpace colorSpace) { m_resultColorSpace = colorSpace; }
-
- virtual void transformResultColorSpace(FilterEffect* in, const int) { in->transformResultColorSpace(m_operatingColorSpace); }
- void transformResultColorSpace(ColorSpace);
-
- FloatRect determineFilterPrimitiveSubregion();
-
-protected:
- FilterEffect(Filter*);
-
- ImageBuffer* createImageBufferResult();
- Uint8ClampedArray* createUnmultipliedImageResult();
- Uint8ClampedArray* createPremultipliedImageResult();
-
- // Return true if the filter will only operate correctly on valid RGBA values, with
- // alpha in [0,255] and each color component in [0, alpha].
- virtual bool requiresValidPreMultipliedPixels() { return true; }
-
- // If a pre-multiplied image, check every pixel for validity and correct if necessary.
- void forceValidPreMultipliedPixels();
- SkIRect getCropRect(const FloatSize& cropOffset) const;
-
-private:
- virtual void applySoftware() = 0;
- virtual bool applySkia() { return false; }
-
- inline void copyImageBytes(Uint8ClampedArray* source, Uint8ClampedArray* destination, const IntRect&);
-
- OwnPtr<ImageBuffer> m_imageBufferResult;
- RefPtr<Uint8ClampedArray> m_unmultipliedImageResult;
- RefPtr<Uint8ClampedArray> m_premultipliedImageResult;
- FilterEffectVector m_inputEffects;
-
- bool m_alphaImage;
-
- IntRect m_absolutePaintRect;
-
- // The maximum size of a filter primitive. In SVG this is the primitive subregion in absolute coordinate space.
- // The absolute paint rect should never be bigger than m_maxEffectRect.
- FloatRect m_maxEffectRect;
- Filter* m_filter;
-
- // The following member variables are SVG specific and will move to RenderSVGResourceFilterPrimitive.
- // See bug https://bugs.webkit.org/show_bug.cgi?id=45614.
-
- // The subregion of a filter primitive according to the SVG Filter specification in local coordinates.
- // This is SVG specific and needs to move to RenderSVGResourceFilterPrimitive.
- FloatRect m_filterPrimitiveSubregion;
-
- // x, y, width and height of the actual SVGFE*Element. Is needed to determine the subregion of the
- // filter primitive on a later step.
- FloatRect m_effectBoundaries;
- bool m_hasX;
- bool m_hasY;
- bool m_hasWidth;
- bool m_hasHeight;
-
- // Should the effect clip to its primitive region, or expand to use the combined region of its inputs.
- bool m_clipsToBounds;
-
- ColorSpace m_operatingColorSpace;
- ColorSpace m_resultColorSpace;
-};
-
-} // namespace WebCore
-
-#endif // FilterEffect_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FilterOperation.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FilterOperation.cpp
deleted file mode 100644
index 8b0696432a4..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FilterOperation.cpp
+++ /dev/null
@@ -1,152 +0,0 @@
-/*
- * Copyright (C) 2011 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/platform/graphics/filters/FilterOperation.h"
-
-#include "core/platform/animation/AnimationUtilities.h"
-
-namespace WebCore {
-
-PassRefPtr<FilterOperation> BasicColorMatrixFilterOperation::blend(const FilterOperation* from, double progress, bool blendToPassthrough)
-{
- if (from && !from->isSameType(*this))
- return this;
-
- if (blendToPassthrough)
- return BasicColorMatrixFilterOperation::create(WebCore::blend(m_amount, passthroughAmount(), progress), m_type);
-
- const BasicColorMatrixFilterOperation* fromOp = static_cast<const BasicColorMatrixFilterOperation*>(from);
- double fromAmount = fromOp ? fromOp->amount() : passthroughAmount();
- return BasicColorMatrixFilterOperation::create(WebCore::blend(fromAmount, m_amount, progress), m_type);
-}
-
-double BasicColorMatrixFilterOperation::passthroughAmount() const
-{
- switch (m_type) {
- case GRAYSCALE:
- case SEPIA:
- case HUE_ROTATE:
- return 0;
- case SATURATE:
- return 1;
- default:
- ASSERT_NOT_REACHED();
- return 0;
- }
-}
-
-PassRefPtr<FilterOperation> BasicComponentTransferFilterOperation::blend(const FilterOperation* from, double progress, bool blendToPassthrough)
-{
- if (from && !from->isSameType(*this))
- return this;
-
- if (blendToPassthrough)
- return BasicComponentTransferFilterOperation::create(WebCore::blend(m_amount, passthroughAmount(), progress), m_type);
-
- const BasicComponentTransferFilterOperation* fromOp = static_cast<const BasicComponentTransferFilterOperation*>(from);
- double fromAmount = fromOp ? fromOp->amount() : passthroughAmount();
- return BasicComponentTransferFilterOperation::create(WebCore::blend(fromAmount, m_amount, progress), m_type);
-}
-
-double BasicComponentTransferFilterOperation::passthroughAmount() const
-{
- switch (m_type) {
- case OPACITY:
- return 1;
- case INVERT:
- return 0;
- case CONTRAST:
- return 1;
- case BRIGHTNESS:
- return 1;
- default:
- ASSERT_NOT_REACHED();
- return 0;
- }
-}
-
-PassRefPtr<FilterOperation> GammaFilterOperation::blend(const FilterOperation* from, double progress, bool blendToPassthrough)
-{
- if (from && !from->isSameType(*this))
- return this;
-
- if (blendToPassthrough)
- return GammaFilterOperation::create(
- WebCore::blend(m_amplitude, 1.0, progress),
- WebCore::blend(m_exponent, 1.0, progress),
- WebCore::blend(m_offset, 0.0, progress), m_type);
-
- const GammaFilterOperation* fromOp = static_cast<const GammaFilterOperation*>(from);
- double fromAmplitude = fromOp ? fromOp->amplitude() : 1;
- double fromExponent = fromOp ? fromOp->exponent() : 1;
- double fromOffset = fromOp ? fromOp->offset() : 0;
- return GammaFilterOperation::create(
- WebCore::blend(fromAmplitude, m_amplitude, progress),
- WebCore::blend(fromExponent, m_exponent, progress),
- WebCore::blend(fromOffset, m_offset, progress), m_type);
-}
-
-PassRefPtr<FilterOperation> BlurFilterOperation::blend(const FilterOperation* from, double progress, bool blendToPassthrough)
-{
- if (from && !from->isSameType(*this))
- return this;
-
- LengthType lengthType = m_stdDeviation.type();
-
- if (blendToPassthrough)
- return BlurFilterOperation::create(Length(lengthType).blend(m_stdDeviation, progress), m_type);
-
- const BlurFilterOperation* fromOp = static_cast<const BlurFilterOperation*>(from);
- Length fromLength = fromOp ? fromOp->m_stdDeviation : Length(lengthType);
- return BlurFilterOperation::create(m_stdDeviation.blend(fromLength, progress), m_type);
-}
-
-PassRefPtr<FilterOperation> DropShadowFilterOperation::blend(const FilterOperation* from, double progress, bool blendToPassthrough)
-{
- if (from && !from->isSameType(*this))
- return this;
-
- if (blendToPassthrough)
- return DropShadowFilterOperation::create(
- WebCore::blend(m_location, IntPoint(), progress),
- WebCore::blend(m_stdDeviation, 0, progress),
- WebCore::blend(m_color, Color(Color::transparent), progress),
- m_type);
-
- const DropShadowFilterOperation* fromOp = static_cast<const DropShadowFilterOperation*>(from);
- IntPoint fromLocation = fromOp ? fromOp->location() : IntPoint();
- int fromStdDeviation = fromOp ? fromOp->stdDeviation() : 0;
- Color fromColor = fromOp ? fromOp->color() : Color(Color::transparent);
-
- return DropShadowFilterOperation::create(
- WebCore::blend(fromLocation, m_location, progress),
- WebCore::blend(fromStdDeviation, m_stdDeviation, progress),
- WebCore::blend(fromColor, m_color, progress), m_type);
-}
-
-} // namespace WebCore
-
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FilterOperation.h b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FilterOperation.h
deleted file mode 100644
index 4e4a31a49c5..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FilterOperation.h
+++ /dev/null
@@ -1,359 +0,0 @@
-/*
- * Copyright (C) 2011 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef FilterOperation_h
-#define FilterOperation_h
-
-#include "core/fetch/DocumentResourceReference.h"
-#include "core/platform/Length.h"
-#include "core/platform/graphics/Color.h"
-#include "core/platform/graphics/filters/Filter.h"
-#include "core/platform/graphics/filters/ReferenceFilter.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/text/WTFString.h"
-
-// Annoyingly, wingdi.h #defines this.
-#ifdef PASSTHROUGH
-#undef PASSTHROUGH
-#endif
-
-namespace WebCore {
-
-// CSS Filters
-
-class FilterOperation : public RefCounted<FilterOperation> {
-public:
- enum OperationType {
- REFERENCE, // url(#somefilter)
- GRAYSCALE,
- SEPIA,
- SATURATE,
- HUE_ROTATE,
- INVERT,
- OPACITY,
- BRIGHTNESS,
- CONTRAST,
- BLUR,
- DROP_SHADOW,
- CUSTOM,
- VALIDATED_CUSTOM,
- PASSTHROUGH,
- NONE
- };
-
- virtual ~FilterOperation() { }
-
- virtual bool operator==(const FilterOperation&) const = 0;
- bool operator!=(const FilterOperation& o) const { return !(*this == o); }
-
- virtual PassRefPtr<FilterOperation> blend(const FilterOperation* /*from*/, double /*progress*/, bool /*blendToPassthrough*/ = false)
- {
- return 0;
- }
-
- virtual OperationType getOperationType() const { return m_type; }
- virtual bool isSameType(const FilterOperation& o) const { return o.getOperationType() == m_type; }
-
- virtual bool isDefault() const { return false; }
-
- // True if the alpha channel of any pixel can change under this operation.
- virtual bool affectsOpacity() const { return false; }
- // True if the the value of one pixel can affect the value of another pixel under this operation, such as blur.
- virtual bool movesPixels() const { return false; }
-
-protected:
- FilterOperation(OperationType type)
- : m_type(type)
- {
- }
-
- OperationType m_type;
-};
-
-class DefaultFilterOperation : public FilterOperation {
-public:
- static PassRefPtr<DefaultFilterOperation> create(OperationType type)
- {
- return adoptRef(new DefaultFilterOperation(type));
- }
-
-private:
-
- virtual bool operator==(const FilterOperation& o) const
- {
- return isSameType(o);
- }
-
- virtual bool isDefault() const { return true; }
-
- DefaultFilterOperation(OperationType type)
- : FilterOperation(type)
- {
- }
-};
-
-class PassthroughFilterOperation : public FilterOperation {
-public:
- static PassRefPtr<PassthroughFilterOperation> create()
- {
- return adoptRef(new PassthroughFilterOperation());
- }
-
-private:
-
- virtual bool operator==(const FilterOperation& o) const
- {
- return isSameType(o);
- }
-
- PassthroughFilterOperation()
- : FilterOperation(PASSTHROUGH)
- {
- }
-};
-
-class ReferenceFilterOperation : public FilterOperation {
-public:
- static PassRefPtr<ReferenceFilterOperation> create(const String& url, const String& fragment, OperationType type)
- {
- return adoptRef(new ReferenceFilterOperation(url, fragment, type));
- }
-
- virtual bool affectsOpacity() const { return true; }
- virtual bool movesPixels() const { return true; }
-
- const String& url() const { return m_url; }
- const String& fragment() const { return m_fragment; }
-
- DocumentResourceReference* documentResourceReference() const { return m_documentResourceReference.get(); }
- void setDocumentResourceReference(PassOwnPtr<DocumentResourceReference> documentResourceReference) { m_documentResourceReference = documentResourceReference; }
-
- ReferenceFilter* filter() const { return m_filter.get(); }
- void setFilter(PassRefPtr<ReferenceFilter> filter) { m_filter = filter; }
-
-private:
-
- virtual bool operator==(const FilterOperation& o) const
- {
- if (!isSameType(o))
- return false;
- const ReferenceFilterOperation* other = static_cast<const ReferenceFilterOperation*>(&o);
- return m_url == other->m_url;
- }
-
- ReferenceFilterOperation(const String& url, const String& fragment, OperationType type)
- : FilterOperation(type)
- , m_url(url)
- , m_fragment(fragment)
- {
- }
-
- String m_url;
- String m_fragment;
- OwnPtr<DocumentResourceReference> m_documentResourceReference;
- RefPtr<ReferenceFilter> m_filter;
-};
-
-// GRAYSCALE, SEPIA, SATURATE and HUE_ROTATE are variations on a basic color matrix effect.
-// For HUE_ROTATE, the angle of rotation is stored in m_amount.
-class BasicColorMatrixFilterOperation : public FilterOperation {
-public:
- static PassRefPtr<BasicColorMatrixFilterOperation> create(double amount, OperationType type)
- {
- return adoptRef(new BasicColorMatrixFilterOperation(amount, type));
- }
-
- double amount() const { return m_amount; }
-
- virtual PassRefPtr<FilterOperation> blend(const FilterOperation* from, double progress, bool blendToPassthrough = false);
-
-private:
- virtual bool operator==(const FilterOperation& o) const
- {
- if (!isSameType(o))
- return false;
- const BasicColorMatrixFilterOperation* other = static_cast<const BasicColorMatrixFilterOperation*>(&o);
- return m_amount == other->m_amount;
- }
-
- double passthroughAmount() const;
-
- BasicColorMatrixFilterOperation(double amount, OperationType type)
- : FilterOperation(type)
- , m_amount(amount)
- {
- }
-
- double m_amount;
-};
-
-// INVERT, BRIGHTNESS, CONTRAST and OPACITY are variations on a basic component transfer effect.
-class BasicComponentTransferFilterOperation : public FilterOperation {
-public:
- static PassRefPtr<BasicComponentTransferFilterOperation> create(double amount, OperationType type)
- {
- return adoptRef(new BasicComponentTransferFilterOperation(amount, type));
- }
-
- double amount() const { return m_amount; }
-
- virtual bool affectsOpacity() const { return m_type == OPACITY; }
-
- virtual PassRefPtr<FilterOperation> blend(const FilterOperation* from, double progress, bool blendToPassthrough = false);
-
-private:
- virtual bool operator==(const FilterOperation& o) const
- {
- if (!isSameType(o))
- return false;
- const BasicComponentTransferFilterOperation* other = static_cast<const BasicComponentTransferFilterOperation*>(&o);
- return m_amount == other->m_amount;
- }
-
- double passthroughAmount() const;
-
- BasicComponentTransferFilterOperation(double amount, OperationType type)
- : FilterOperation(type)
- , m_amount(amount)
- {
- }
-
- double m_amount;
-};
-
-class GammaFilterOperation : public FilterOperation {
-public:
- static PassRefPtr<GammaFilterOperation> create(double amplitude, double exponent, double offset, OperationType type)
- {
- return adoptRef(new GammaFilterOperation(amplitude, exponent, offset, type));
- }
-
- double amplitude() const { return m_amplitude; }
- double exponent() const { return m_exponent; }
- double offset() const { return m_offset; }
-
- virtual PassRefPtr<FilterOperation> blend(const FilterOperation* from, double progress, bool blendToPassthrough = false);
-
-private:
- virtual bool operator==(const FilterOperation& o) const
- {
- if (!isSameType(o))
- return false;
- const GammaFilterOperation* other = static_cast<const GammaFilterOperation*>(&o);
- return m_amplitude == other->m_amplitude && m_exponent == other->m_exponent && m_offset == other->m_offset;
- }
-
- GammaFilterOperation(double amplitude, double exponent, double offset, OperationType type)
- : FilterOperation(type)
- , m_amplitude(amplitude)
- , m_exponent(exponent)
- , m_offset(offset)
- {
- }
-
- double m_amplitude;
- double m_exponent;
- double m_offset;
-};
-
-class BlurFilterOperation : public FilterOperation {
-public:
- static PassRefPtr<BlurFilterOperation> create(Length stdDeviation, OperationType type)
- {
- return adoptRef(new BlurFilterOperation(stdDeviation, type));
- }
-
- Length stdDeviation() const { return m_stdDeviation; }
-
- virtual bool affectsOpacity() const { return true; }
- virtual bool movesPixels() const { return true; }
-
- virtual PassRefPtr<FilterOperation> blend(const FilterOperation* from, double progress, bool blendToPassthrough = false);
-
-private:
- virtual bool operator==(const FilterOperation& o) const
- {
- if (!isSameType(o))
- return false;
- const BlurFilterOperation* other = static_cast<const BlurFilterOperation*>(&o);
- return m_stdDeviation == other->m_stdDeviation;
- }
-
- BlurFilterOperation(Length stdDeviation, OperationType type)
- : FilterOperation(type)
- , m_stdDeviation(stdDeviation)
- {
- }
-
- Length m_stdDeviation;
-};
-
-class DropShadowFilterOperation : public FilterOperation {
-public:
- static PassRefPtr<DropShadowFilterOperation> create(const IntPoint& location, int stdDeviation, Color color, OperationType type)
- {
- return adoptRef(new DropShadowFilterOperation(location, stdDeviation, color, type));
- }
-
- int x() const { return m_location.x(); }
- int y() const { return m_location.y(); }
- IntPoint location() const { return m_location; }
- int stdDeviation() const { return m_stdDeviation; }
- Color color() const { return m_color; }
-
- virtual bool affectsOpacity() const { return true; }
- virtual bool movesPixels() const { return true; }
-
- virtual PassRefPtr<FilterOperation> blend(const FilterOperation* from, double progress, bool blendToPassthrough = false);
-
-private:
-
- virtual bool operator==(const FilterOperation& o) const
- {
- if (!isSameType(o))
- return false;
- const DropShadowFilterOperation* other = static_cast<const DropShadowFilterOperation*>(&o);
- return m_location == other->m_location && m_stdDeviation == other->m_stdDeviation && m_color == other->m_color;
- }
-
- DropShadowFilterOperation(const IntPoint& location, int stdDeviation, Color color, OperationType type)
- : FilterOperation(type)
- , m_location(location)
- , m_stdDeviation(stdDeviation)
- , m_color(color)
- {
- }
-
- IntPoint m_location; // FIXME: should location be in Lengths?
- int m_stdDeviation;
- Color m_color;
-};
-
-} // namespace WebCore
-
-
-#endif // FilterOperation_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FilterOperations.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FilterOperations.cpp
deleted file mode 100644
index 8857a2368db..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FilterOperations.cpp
+++ /dev/null
@@ -1,188 +0,0 @@
-/*
- * Copyright (C) 2011 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/filters/FilterOperations.h"
-
-#include "core/css/LengthFunctions.h"
-#include "core/platform/graphics/IntSize.h"
-#include "core/platform/graphics/filters/FEGaussianBlur.h"
-
-namespace WebCore {
-
-static inline IntSize outsetSizeForBlur(float stdDeviation)
-{
- unsigned kernelSizeX = 0;
- unsigned kernelSizeY = 0;
- FEGaussianBlur::calculateUnscaledKernelSize(kernelSizeX, kernelSizeY, stdDeviation, stdDeviation);
-
- IntSize outset;
- // We take the half kernel size and multiply it with three, because we run box blur three times.
- outset.setWidth(3 * kernelSizeX * 0.5f);
- outset.setHeight(3 * kernelSizeY * 0.5f);
-
- return outset;
-}
-
-FilterOperations::FilterOperations()
-{
-}
-
-FilterOperations& FilterOperations::operator=(const FilterOperations& other)
-{
- m_operations = other.m_operations;
- return *this;
-}
-
-bool FilterOperations::operator==(const FilterOperations& o) const
-{
- if (m_operations.size() != o.m_operations.size())
- return false;
-
- unsigned s = m_operations.size();
- for (unsigned i = 0; i < s; i++) {
- if (*m_operations[i] != *o.m_operations[i])
- return false;
- }
-
- return true;
-}
-
-bool FilterOperations::operationsMatch(const FilterOperations& other) const
-{
- size_t numOperations = operations().size();
- // If the sizes of the function lists don't match, the lists don't match
- if (numOperations != other.operations().size())
- return false;
-
- // If the types of each function are not the same, the lists don't match
- for (size_t i = 0; i < numOperations; ++i) {
- if (!operations()[i]->isSameType(*other.operations()[i]))
- return false;
- }
- return true;
-}
-
-bool FilterOperations::hasCustomFilter() const
-{
- for (size_t i = 0; i < m_operations.size(); ++i) {
- FilterOperation::OperationType type = m_operations.at(i)->getOperationType();
- if (type == FilterOperation::CUSTOM || type == FilterOperation::VALIDATED_CUSTOM)
- return true;
- }
- return false;
-}
-
-bool FilterOperations::hasReferenceFilter() const
-{
- for (size_t i = 0; i < m_operations.size(); ++i) {
- if (m_operations.at(i)->getOperationType() == FilterOperation::REFERENCE)
- return true;
- }
- return false;
-}
-
-bool FilterOperations::hasOutsets() const
-{
- for (size_t i = 0; i < m_operations.size(); ++i) {
- FilterOperation::OperationType operationType = m_operations.at(i).get()->getOperationType();
- if (operationType == FilterOperation::BLUR || operationType == FilterOperation::DROP_SHADOW || operationType == FilterOperation::REFERENCE)
- return true;
- }
- return false;
-}
-
-FilterOutsets FilterOperations::outsets() const
-{
- FilterOutsets totalOutsets;
- for (size_t i = 0; i < m_operations.size(); ++i) {
- FilterOperation* filterOperation = m_operations.at(i).get();
- switch (filterOperation->getOperationType()) {
- case FilterOperation::BLUR: {
- BlurFilterOperation* blurOperation = static_cast<BlurFilterOperation*>(filterOperation);
- float stdDeviation = floatValueForLength(blurOperation->stdDeviation(), 0);
- IntSize outsetSize = outsetSizeForBlur(stdDeviation);
- FilterOutsets outsets(outsetSize.height(), outsetSize.width(), outsetSize.height(), outsetSize.width());
- totalOutsets += outsets;
- break;
- }
- case FilterOperation::DROP_SHADOW: {
- DropShadowFilterOperation* dropShadowOperation = static_cast<DropShadowFilterOperation*>(filterOperation);
- IntSize outsetSize = outsetSizeForBlur(dropShadowOperation->stdDeviation());
- FilterOutsets outsets(
- std::max(0, outsetSize.height() - dropShadowOperation->y()),
- std::max(0, outsetSize.width() + dropShadowOperation->x()),
- std::max(0, outsetSize.height() + dropShadowOperation->y()),
- std::max(0, outsetSize.width() - dropShadowOperation->x())
- );
- totalOutsets += outsets;
- break;
- }
- case FilterOperation::REFERENCE: {
- ReferenceFilterOperation* referenceOperation = static_cast<ReferenceFilterOperation*>(filterOperation);
- if (referenceOperation->filter() && referenceOperation->filter()->lastEffect()) {
- FloatRect outsetRect(0, 0, 1, 1);
- outsetRect = referenceOperation->filter()->lastEffect()->mapRectRecursive(outsetRect);
- FilterOutsets outsets(
- std::max(0.0f, -outsetRect.y()),
- std::max(0.0f, outsetRect.x() + outsetRect.width() - 1),
- std::max(0.0f, outsetRect.y() + outsetRect.height() - 1),
- std::max(0.0f, -outsetRect.x())
- );
- totalOutsets += outsets;
- }
- break;
- }
- case FilterOperation::CUSTOM:
- case FilterOperation::VALIDATED_CUSTOM: {
- // FIXME: Need to include the filter margins here.
- // https://bugs.webkit.org/show_bug.cgi?id=71400
- break;
- }
- default:
- break;
- }
- }
- return totalOutsets;
-}
-
-bool FilterOperations::hasFilterThatAffectsOpacity() const
-{
- for (size_t i = 0; i < m_operations.size(); ++i)
- if (m_operations[i]->affectsOpacity())
- return true;
- return false;
-}
-
-bool FilterOperations::hasFilterThatMovesPixels() const
-{
- for (size_t i = 0; i < m_operations.size(); ++i)
- if (m_operations[i]->movesPixels())
- return true;
- return false;
-}
-
-} // namespace WebCore
-
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FilterOperations.h b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FilterOperations.h
deleted file mode 100644
index a1f0cfc1bad..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/FilterOperations.h
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * Copyright (C) 2011 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef FilterOperations_h
-#define FilterOperations_h
-
-#include "core/platform/graphics/IntRectExtent.h"
-#include "core/platform/graphics/filters/FilterOperation.h"
-#include "wtf/RefPtr.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-typedef IntRectExtent FilterOutsets;
-
-class FilterOperations {
- WTF_MAKE_FAST_ALLOCATED;
-public:
- FilterOperations();
- FilterOperations(const FilterOperations& other) { *this = other; }
-
- FilterOperations& operator=(const FilterOperations&);
-
- bool operator==(const FilterOperations&) const;
- bool operator!=(const FilterOperations& o) const
- {
- return !(*this == o);
- }
-
- void clear()
- {
- m_operations.clear();
- }
-
- Vector<RefPtr<FilterOperation> >& operations() { return m_operations; }
- const Vector<RefPtr<FilterOperation> >& operations() const { return m_operations; }
-
- bool isEmpty() const { return !m_operations.size(); }
- size_t size() const { return m_operations.size(); }
- const FilterOperation* at(size_t index) const { return index < m_operations.size() ? m_operations.at(index).get() : 0; }
-
- bool operationsMatch(const FilterOperations&) const;
-
- bool hasOutsets() const;
- FilterOutsets outsets() const;
-
- bool hasFilterThatAffectsOpacity() const;
- bool hasFilterThatMovesPixels() const;
-
- bool hasCustomFilter() const;
- bool hasReferenceFilter() const;
-private:
- Vector<RefPtr<FilterOperation> > m_operations;
-};
-
-} // namespace WebCore
-
-
-#endif // FilterOperations_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/LightSource.h b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/LightSource.h
deleted file mode 100644
index e47e850338f..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/LightSource.h
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
- * Copyright (C) 2008 Alex Mathews <possessedpenguinbob@gmail.com>
- * Copyright (C) 2004, 2005, 2006, 2007 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2004, 2005 Rob Buis <buis@kde.org>
- * Copyright (C) 2005 Eric Seidel <eric@webkit.org>
- * Copyright (C) 2010 Zoltan Herczeg <zherczeg@webkit.org>
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#ifndef LightSource_h
-#define LightSource_h
-
-#include "core/platform/graphics/FloatPoint3D.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-
-namespace WebCore {
-
-enum LightType {
- LS_DISTANT,
- LS_POINT,
- LS_SPOT
-};
-
-class TextStream;
-
-class LightSource : public RefCounted<LightSource> {
-public:
-
- // Light vectors must be calculated for every pixel during
- // painting. It is expensive to pass all these arguments to
- // a frequently called function, especially because not all
- // light sources require all of them. Instead, we just pass
- // a reference to the following structure
- struct PaintingData {
- // SVGFELighting also use them
- FloatPoint3D lightVector;
- FloatPoint3D colorVector;
- float lightVectorLength;
- // Private members
- FloatPoint3D directionVector;
- FloatPoint3D privateColorVector;
- float coneCutOffLimit;
- float coneFullLight;
- int specularExponent;
- };
-
- LightSource(LightType type)
- : m_type(type)
- { }
-
- virtual ~LightSource() { }
-
- LightType type() const { return m_type; }
- virtual TextStream& externalRepresentation(TextStream&) const = 0;
-
- virtual void initPaintingData(PaintingData&) = 0;
- // z is a float number, since it is the alpha value scaled by a user
- // specified "surfaceScale" constant, which type is <number> in the SVG standard
- virtual void updatePaintingData(PaintingData&, int x, int y, float z) = 0;
-
- virtual bool setAzimuth(float) { return false; }
- virtual bool setElevation(float) { return false; }
- virtual bool setX(float) { return false; }
- virtual bool setY(float) { return false; }
- virtual bool setZ(float) { return false; }
- virtual bool setPointsAtX(float) { return false; }
- virtual bool setPointsAtY(float) { return false; }
- virtual bool setPointsAtZ(float) { return false; }
- virtual bool setSpecularExponent(float) { return false; }
- virtual bool setLimitingConeAngle(float) { return false; }
-
-private:
- LightType m_type;
-};
-
-} // namespace WebCore
-
-#endif // LightSource_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/PointLightSource.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/PointLightSource.cpp
deleted file mode 100644
index 232787ca53b..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/PointLightSource.cpp
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
- * Copyright (C) 2004, 2005, 2006, 2007 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2004, 2005 Rob Buis <buis@kde.org>
- * Copyright (C) 2005 Eric Seidel <eric@webkit.org>
- * Copyright (C) 2010 Zoltan Herczeg <zherczeg@webkit.org>
- * Copyright (C) 2011 University of Szeged
- * Copyright (C) 2011 Renata Hodovan <reni@webkit.org>
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY UNIVERSITY OF SZEGED ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL UNIVERSITY OF SZEGED OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/platform/graphics/filters/PointLightSource.h"
-
-#include "core/platform/text/TextStream.h"
-
-namespace WebCore {
-
-void PointLightSource::initPaintingData(PaintingData&)
-{
-}
-
-void PointLightSource::updatePaintingData(PaintingData& paintingData, int x, int y, float z)
-{
- paintingData.lightVector.setX(m_position.x() - x);
- paintingData.lightVector.setY(m_position.y() - y);
- paintingData.lightVector.setZ(m_position.z() - z);
- paintingData.lightVectorLength = paintingData.lightVector.length();
-}
-
-bool PointLightSource::setX(float x)
-{
- if (m_position.x() == x)
- return false;
- m_position.setX(x);
- return true;
-}
-
-bool PointLightSource::setY(float y)
-{
- if (m_position.y() == y)
- return false;
- m_position.setY(y);
- return true;
-}
-
-bool PointLightSource::setZ(float z)
-{
- if (m_position.z() == z)
- return false;
- m_position.setZ(z);
- return true;
-}
-
-static TextStream& operator<<(TextStream& ts, const FloatPoint3D& p)
-{
- ts << "x=" << p.x() << " y=" << p.y() << " z=" << p.z();
- return ts;
-}
-
-TextStream& PointLightSource::externalRepresentation(TextStream& ts) const
-{
- ts << "[type=POINT-LIGHT] ";
- ts << "[position=\"" << position() << "\"]";
- return ts;
-}
-
-}; // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/PointLightSource.h b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/PointLightSource.h
deleted file mode 100644
index c27de27c72e..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/PointLightSource.h
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Copyright (C) 2008 Alex Mathews <possessedpenguinbob@gmail.com>
- * Copyright (C) 2004, 2005, 2006, 2007 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2004, 2005 Rob Buis <buis@kde.org>
- * Copyright (C) 2005 Eric Seidel <eric@webkit.org>
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#ifndef PointLightSource_h
-#define PointLightSource_h
-
-#include "core/platform/graphics/filters/LightSource.h"
-
-namespace WebCore {
-
-class PointLightSource : public LightSource {
-public:
- static PassRefPtr<PointLightSource> create(const FloatPoint3D& position)
- {
- return adoptRef(new PointLightSource(position));
- }
-
- const FloatPoint3D& position() const { return m_position; }
- virtual bool setX(float) OVERRIDE;
- virtual bool setY(float) OVERRIDE;
- virtual bool setZ(float) OVERRIDE;
-
- virtual void initPaintingData(PaintingData&);
- virtual void updatePaintingData(PaintingData&, int x, int y, float z);
-
- virtual TextStream& externalRepresentation(TextStream&) const;
-
-private:
- PointLightSource(const FloatPoint3D& position)
- : LightSource(LS_POINT)
- , m_position(position)
- {
- }
-
- FloatPoint3D m_position;
-};
-
-} // namespace WebCore
-
-#endif // PointLightSource_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/ReferenceFilter.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/ReferenceFilter.cpp
deleted file mode 100644
index 2b84dd5a963..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/ReferenceFilter.cpp
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Copyright (C) 2013 Adobe Systems Incorporated. All rights reserved.
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above
- * copyright notice, this list of conditions and the following
- * disclaimer.
- * 2. Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following
- * disclaimer in the documentation and/or other materials
- * provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
- * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
- * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
- * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/platform/graphics/filters/ReferenceFilter.h"
-
-#include "core/platform/graphics/filters/FilterEffect.h"
-#include "core/platform/graphics/filters/SourceGraphic.h"
-
-namespace WebCore {
-
-ReferenceFilter::ReferenceFilter()
- : Filter(AffineTransform())
- , m_sourceGraphic(SourceGraphic::create(this))
-{
- // FIXME: This should come from the filter DOM node's filterRes attribute.
- setFilterResolution(FloatSize(1, 1));
-}
-
-void ReferenceFilter::setLastEffect(PassRefPtr<FilterEffect> effect)
-{
- m_lastEffect = effect;
-}
-
-ReferenceFilter::~ReferenceFilter()
-{
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/ReferenceFilter.h b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/ReferenceFilter.h
deleted file mode 100644
index 7bc87dcc4b3..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/ReferenceFilter.h
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Copyright (C) 2013 Adobe Systems Incorporated. All rights reserved.
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above
- * copyright notice, this list of conditions and the following
- * disclaimer.
- * 2. Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following
- * disclaimer in the documentation and/or other materials
- * provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
- * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
- * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
- * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#ifndef ReferenceFilter_h
-#define ReferenceFilter_h
-
-#include "core/platform/graphics/FloatRect.h"
-#include "core/platform/graphics/filters/Filter.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefPtr.h"
-
-namespace WebCore {
-
-class SourceGraphic;
-class FilterEffect;
-
-class ReferenceFilter: public Filter {
-public:
- static PassRefPtr<ReferenceFilter> create()
- {
- return adoptRef(new ReferenceFilter());
- }
-
- virtual FloatRect sourceImageRect() const { return FloatRect(); };
-
- void setLastEffect(PassRefPtr<FilterEffect>);
- FilterEffect* lastEffect() const { return m_lastEffect.get(); }
-
- SourceGraphic* sourceGraphic() const { return m_sourceGraphic.get(); }
-
-private:
- ReferenceFilter();
- ~ReferenceFilter();
-
- RefPtr<SourceGraphic> m_sourceGraphic;
- RefPtr<FilterEffect> m_lastEffect;
-};
-
-}
-
-#endif // ReferenceFilter_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/SkiaImageFilterBuilder.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/SkiaImageFilterBuilder.cpp
deleted file mode 100644
index 49a686a414c..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/SkiaImageFilterBuilder.cpp
+++ /dev/null
@@ -1,305 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-#include "config.h"
-
-#include "core/platform/graphics/filters/SkiaImageFilterBuilder.h"
-
-#include "SkBlurImageFilter.h"
-#include "SkColorFilterImageFilter.h"
-#include "SkColorMatrixFilter.h"
-#include "SkDropShadowImageFilter.h"
-#include "SkTableColorFilter.h"
-#include "core/platform/graphics/ImageBuffer.h"
-#include "core/platform/graphics/filters/FilterEffect.h"
-#include "core/platform/graphics/filters/FilterOperations.h"
-#include "core/platform/graphics/filters/SourceGraphic.h"
-
-namespace {
-
-void getBrightnessMatrix(float amount, SkScalar matrix[20])
-{
- memset(matrix, 0, 20 * sizeof(SkScalar));
- matrix[0] = matrix[6] = matrix[12] = amount;
- matrix[18] = 1;
-}
-
-void getContrastMatrix(float amount, SkScalar matrix[20])
-{
- memset(matrix, 0, 20 * sizeof(SkScalar));
- matrix[0] = matrix[6] = matrix[12] = amount;
- matrix[4] = matrix[9] = matrix[14] = (-0.5f * amount + 0.5f) * 255;
- matrix[18] = 1;
-}
-
-void getSaturateMatrix(float amount, SkScalar matrix[20])
-{
- // Note, these values are computed to ensure matrixNeedsClamping is false
- // for amount in [0..1]
- matrix[0] = 0.213f + 0.787f * amount;
- matrix[1] = 0.715f - 0.715f * amount;
- matrix[2] = 1.f - (matrix[0] + matrix[1]);
- matrix[3] = matrix[4] = 0;
- matrix[5] = 0.213f - 0.213f * amount;
- matrix[6] = 0.715f + 0.285f * amount;
- matrix[7] = 1.f - (matrix[5] + matrix[6]);
- matrix[8] = matrix[9] = 0;
- matrix[10] = 0.213f - 0.213f * amount;
- matrix[11] = 0.715f - 0.715f * amount;
- matrix[12] = 1.f - (matrix[10] + matrix[11]);
- matrix[13] = matrix[14] = 0;
- matrix[15] = matrix[16] = matrix[17] = matrix[19] = 0;
- matrix[18] = 1;
-}
-
-void getHueRotateMatrix(float hue, SkScalar matrix[20])
-{
- float cosHue = cosf(hue * piFloat / 180);
- float sinHue = sinf(hue * piFloat / 180);
- matrix[0] = 0.213f + cosHue * 0.787f - sinHue * 0.213f;
- matrix[1] = 0.715f - cosHue * 0.715f - sinHue * 0.715f;
- matrix[2] = 0.072f - cosHue * 0.072f + sinHue * 0.928f;
- matrix[3] = matrix[4] = 0;
- matrix[5] = 0.213f - cosHue * 0.213f + sinHue * 0.143f;
- matrix[6] = 0.715f + cosHue * 0.285f + sinHue * 0.140f;
- matrix[7] = 0.072f - cosHue * 0.072f - sinHue * 0.283f;
- matrix[8] = matrix[9] = 0;
- matrix[10] = 0.213f - cosHue * 0.213f - sinHue * 0.787f;
- matrix[11] = 0.715f - cosHue * 0.715f + sinHue * 0.715f;
- matrix[12] = 0.072f + cosHue * 0.928f + sinHue * 0.072f;
- matrix[13] = matrix[14] = 0;
- matrix[15] = matrix[16] = matrix[17] = 0;
- matrix[18] = 1;
- matrix[19] = 0;
-}
-
-void getInvertMatrix(float amount, SkScalar matrix[20])
-{
- memset(matrix, 0, 20 * sizeof(SkScalar));
- matrix[0] = matrix[6] = matrix[12] = 1 - 2 * amount;
- matrix[4] = matrix[9] = matrix[14] = amount * 255;
- matrix[18] = 1;
-}
-
-void getOpacityMatrix(float amount, SkScalar matrix[20])
-{
- memset(matrix, 0, 20 * sizeof(SkScalar));
- matrix[0] = matrix[6] = matrix[12] = 1;
- matrix[18] = amount;
-}
-
-void getGrayscaleMatrix(float amount, SkScalar matrix[20])
-{
- // Note, these values are computed to ensure matrixNeedsClamping is false
- // for amount in [0..1]
- matrix[0] = 0.2126f + 0.7874f * amount;
- matrix[1] = 0.7152f - 0.7152f * amount;
- matrix[2] = 1.f - (matrix[0] + matrix[1]);
- matrix[3] = matrix[4] = 0;
-
- matrix[5] = 0.2126f - 0.2126f * amount;
- matrix[6] = 0.7152f + 0.2848f * amount;
- matrix[7] = 1.f - (matrix[5] + matrix[6]);
- matrix[8] = matrix[9] = 0;
-
- matrix[10] = 0.2126f - 0.2126f * amount;
- matrix[11] = 0.7152f - 0.7152f * amount;
- matrix[12] = 1.f - (matrix[10] + matrix[11]);
- matrix[13] = matrix[14] = 0;
-
- matrix[15] = matrix[16] = matrix[17] = matrix[19] = 0;
- matrix[18] = 1;
-}
-
-void getSepiaMatrix(float amount, SkScalar matrix[20])
-{
- matrix[0] = 0.393f + 0.607f * amount;
- matrix[1] = 0.769f - 0.769f * amount;
- matrix[2] = 0.189f - 0.189f * amount;
- matrix[3] = matrix[4] = 0;
-
- matrix[5] = 0.349f - 0.349f * amount;
- matrix[6] = 0.686f + 0.314f * amount;
- matrix[7] = 0.168f - 0.168f * amount;
- matrix[8] = matrix[9] = 0;
-
- matrix[10] = 0.272f - 0.272f * amount;
- matrix[11] = 0.534f - 0.534f * amount;
- matrix[12] = 0.131f + 0.869f * amount;
- matrix[13] = matrix[14] = 0;
-
- matrix[15] = matrix[16] = matrix[17] = matrix[19] = 0;
- matrix[18] = 1;
-}
-
-PassRefPtr<SkImageFilter> createMatrixImageFilter(SkScalar matrix[20], SkImageFilter* input)
-{
- RefPtr<SkColorFilter> colorFilter(adoptRef(new SkColorMatrixFilter(matrix)));
- return adoptRef(SkColorFilterImageFilter::Create(colorFilter.get(), input));
-}
-
-};
-
-namespace WebCore {
-
-SkiaImageFilterBuilder::SkiaImageFilterBuilder()
-{
-}
-
-SkiaImageFilterBuilder::~SkiaImageFilterBuilder()
-{
-}
-
-PassRefPtr<SkImageFilter> SkiaImageFilterBuilder::build(FilterEffect* effect, ColorSpace colorSpace)
-{
- if (!effect)
- return 0;
-
- FilterColorSpacePair key(effect, colorSpace);
- FilterBuilderHashMap::iterator it = m_map.find(key);
- if (it != m_map.end()) {
- return it->value;
- } else {
- // Note that we may still need the color transform even if the filter is null
- RefPtr<SkImageFilter> origFilter = effect->createImageFilter(this);
- RefPtr<SkImageFilter> filter = transformColorSpace(origFilter.get(), effect->operatingColorSpace(), colorSpace);
- m_map.set(key, filter);
- return filter.release();
- }
-}
-
-PassRefPtr<SkImageFilter> SkiaImageFilterBuilder::transformColorSpace(
- SkImageFilter* input, ColorSpace srcColorSpace, ColorSpace dstColorSpace) {
-
- RefPtr<SkColorFilter> colorFilter = ImageBuffer::createColorSpaceFilter(srcColorSpace, dstColorSpace);
- if (!colorFilter)
- return input;
-
- return adoptRef(SkColorFilterImageFilter::Create(colorFilter.get(), input));
-}
-
-PassRefPtr<SkImageFilter> SkiaImageFilterBuilder::build(const FilterOperations& operations)
-{
- RefPtr<SkImageFilter> filter;
- SkScalar matrix[20];
- ColorSpace currentColorSpace = ColorSpaceDeviceRGB;
- for (size_t i = 0; i < operations.size(); ++i) {
- const FilterOperation& op = *operations.at(i);
- switch (op.getOperationType()) {
- case FilterOperation::REFERENCE: {
- const ReferenceFilterOperation* referenceFilterOperation = static_cast<const ReferenceFilterOperation*>(&op);
- ReferenceFilter* referenceFilter = referenceFilterOperation->filter();
- if (referenceFilter && referenceFilter->lastEffect()) {
- FilterEffect* filterEffect = referenceFilter->lastEffect();
- // Link SourceGraphic to the previous filter in the chain.
- // We don't know what color space the interior nodes will request, so we have to populate the map with both options.
- // (Only one of these will actually have a color transform on it.)
- FilterColorSpacePair deviceKey(referenceFilter->sourceGraphic(), ColorSpaceDeviceRGB);
- FilterColorSpacePair linearKey(referenceFilter->sourceGraphic(), ColorSpaceLinearRGB);
- m_map.set(deviceKey, transformColorSpace(filter.get(), currentColorSpace, ColorSpaceDeviceRGB));
- m_map.set(linearKey, transformColorSpace(filter.get(), currentColorSpace, ColorSpaceLinearRGB));
-
- currentColorSpace = filterEffect->operatingColorSpace();
- filter = SkiaImageFilterBuilder::build(filterEffect, currentColorSpace);
- // We might have no reference to the SourceGraphic's Skia filter now, so make
- // sure we don't keep it in the map anymore.
- m_map.remove(deviceKey);
- m_map.remove(linearKey);
- }
- break;
- }
- case FilterOperation::GRAYSCALE: {
- float amount = static_cast<const BasicColorMatrixFilterOperation*>(&op)->amount();
- getGrayscaleMatrix(1 - amount, matrix);
- filter = createMatrixImageFilter(matrix, filter.get());
- break;
- }
- case FilterOperation::SEPIA: {
- float amount = static_cast<const BasicColorMatrixFilterOperation*>(&op)->amount();
- getSepiaMatrix(1 - amount, matrix);
- filter = createMatrixImageFilter(matrix, filter.get());
- break;
- }
- case FilterOperation::SATURATE: {
- float amount = static_cast<const BasicColorMatrixFilterOperation*>(&op)->amount();
- getSaturateMatrix(amount, matrix);
- filter = createMatrixImageFilter(matrix, filter.get());
- break;
- }
- case FilterOperation::HUE_ROTATE: {
- float amount = static_cast<const BasicColorMatrixFilterOperation*>(&op)->amount();
- getHueRotateMatrix(amount, matrix);
- filter = createMatrixImageFilter(matrix, filter.get());
- break;
- }
- case FilterOperation::INVERT: {
- float amount = static_cast<const BasicComponentTransferFilterOperation*>(&op)->amount();
- getInvertMatrix(amount, matrix);
- filter = createMatrixImageFilter(matrix, filter.get());
- break;
- }
- case FilterOperation::OPACITY: {
- float amount = static_cast<const BasicComponentTransferFilterOperation*>(&op)->amount();
- getOpacityMatrix(amount, matrix);
- filter = createMatrixImageFilter(matrix, filter.get());
- break;
- }
- case FilterOperation::BRIGHTNESS: {
- float amount = static_cast<const BasicComponentTransferFilterOperation*>(&op)->amount();
- getBrightnessMatrix(amount, matrix);
- filter = createMatrixImageFilter(matrix, filter.get());
- break;
- }
- case FilterOperation::CONTRAST: {
- float amount = static_cast<const BasicComponentTransferFilterOperation*>(&op)->amount();
- getContrastMatrix(amount, matrix);
- filter = createMatrixImageFilter(matrix, filter.get());
- break;
- }
- case FilterOperation::BLUR: {
- float pixelRadius = static_cast<const BlurFilterOperation*>(&op)->stdDeviation().getFloatValue();
- filter = adoptRef(new SkBlurImageFilter(pixelRadius, pixelRadius, filter.get()));
- break;
- }
- case FilterOperation::DROP_SHADOW: {
- const DropShadowFilterOperation* drop = static_cast<const DropShadowFilterOperation*>(&op);
- filter = adoptRef(new SkDropShadowImageFilter(SkIntToScalar(drop->x()), SkIntToScalar(drop->y()), SkIntToScalar(drop->stdDeviation()), drop->color().rgb(), filter.get()));
- break;
- }
- case FilterOperation::VALIDATED_CUSTOM:
- case FilterOperation::CUSTOM:
- // Not supported.
- case FilterOperation::PASSTHROUGH:
- case FilterOperation::NONE:
- break;
- }
- }
- if (currentColorSpace != ColorSpaceDeviceRGB) {
- // Transform to device color space at the end of processing, if required
- filter = transformColorSpace(filter.get(), currentColorSpace, ColorSpaceDeviceRGB);
- }
- return filter.release();
-}
-
-};
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/SkiaImageFilterBuilder.h b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/SkiaImageFilterBuilder.h
deleted file mode 100644
index f16dc2277c2..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/SkiaImageFilterBuilder.h
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SkiaImageFilterBuilder_h
-#define SkiaImageFilterBuilder_h
-
-#include "core/platform/graphics/ColorSpace.h"
-#include "core/platform/graphics/FloatSize.h"
-#include "wtf/HashMap.h"
-
-class SkImageFilter;
-
-namespace WebCore {
-class FilterEffect;
-class FilterOperations;
-
-class SkiaImageFilterBuilder {
-public:
- SkiaImageFilterBuilder();
- ~SkiaImageFilterBuilder();
-
- PassRefPtr<SkImageFilter> build(FilterEffect*, ColorSpace);
- PassRefPtr<SkImageFilter> build(const FilterOperations&);
-
- PassRefPtr<SkImageFilter> transformColorSpace(
- SkImageFilter* input, ColorSpace srcColorSpace, ColorSpace dstColorSpace);
-
- void setCropOffset(const FloatSize& cropOffset) { m_cropOffset = cropOffset; };
- FloatSize cropOffset() { return m_cropOffset; }
-
-private:
- typedef std::pair<FilterEffect*, ColorSpace> FilterColorSpacePair;
- typedef HashMap<FilterColorSpacePair, RefPtr<SkImageFilter> > FilterBuilderHashMap;
- FilterBuilderHashMap m_map;
- FloatSize m_cropOffset;
-};
-
-} // namespace WebCore
-
-namespace WTF {
-
-template<> struct DefaultHash<WebCore::FilterEffect*> {
- typedef PtrHash<WebCore::FilterEffect*> Hash;
-};
-template<> struct DefaultHash<WebCore::ColorSpace> {
- typedef IntHash<unsigned> Hash;
-};
-
-} // namespace WTF
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/SourceAlpha.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/SourceAlpha.cpp
deleted file mode 100644
index 3eb1228149b..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/SourceAlpha.cpp
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * Copyright (C) 2009 Dirk Schulze <krit@webkit.org>
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-
-#include "core/platform/graphics/filters/SourceAlpha.h"
-
-#include "core/platform/graphics/Color.h"
-#include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/graphics/filters/Filter.h"
-#include "core/platform/text/TextStream.h"
-#include "core/rendering/RenderTreeAsText.h"
-#include "wtf/StdLibExtras.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-PassRefPtr<SourceAlpha> SourceAlpha::create(Filter* filter)
-{
- return adoptRef(new SourceAlpha(filter));
-}
-
-const AtomicString& SourceAlpha::effectName()
-{
- DEFINE_STATIC_LOCAL(const AtomicString, s_effectName, ("SourceAlpha", AtomicString::ConstructFromLiteral));
- return s_effectName;
-}
-
-void SourceAlpha::determineAbsolutePaintRect()
-{
- Filter* filter = this->filter();
- FloatRect paintRect = filter->sourceImageRect();
- paintRect.scale(filter->filterResolution().width(), filter->filterResolution().height());
- setAbsolutePaintRect(enclosingIntRect(paintRect));
-}
-
-void SourceAlpha::applySoftware()
-{
- ImageBuffer* resultImage = createImageBufferResult();
- Filter* filter = this->filter();
- if (!resultImage || !filter->sourceImage())
- return;
-
- setIsAlphaImage(true);
-
- FloatRect imageRect(FloatPoint(), absolutePaintRect().size());
- GraphicsContext* filterContext = resultImage->context();
- filterContext->fillRect(imageRect, Color::black);
- filterContext->drawImageBuffer(filter->sourceImage(), IntPoint(), CompositeDestinationIn);
-}
-
-TextStream& SourceAlpha::externalRepresentation(TextStream& ts, int indent) const
-{
- writeIndent(ts, indent);
- ts << "[SourceAlpha]\n";
- return ts;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/SourceAlpha.h b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/SourceAlpha.h
deleted file mode 100644
index 6a089c6db96..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/SourceAlpha.h
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Copyright (C) 2009 Dirk Schulze <krit@webkit.org>
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#ifndef SourceAlpha_h
-#define SourceAlpha_h
-
-#include "core/platform/graphics/filters/Filter.h"
-#include "core/platform/graphics/filters/FilterEffect.h"
-
-namespace WebCore {
-
-class SourceAlpha : public FilterEffect {
-public:
- static PassRefPtr<SourceAlpha> create(Filter*);
-
- static const AtomicString& effectName();
-
- virtual void determineAbsolutePaintRect();
-
- virtual FilterEffectType filterEffectType() const { return FilterEffectTypeSourceInput; }
-
- virtual TextStream& externalRepresentation(TextStream&, int indention) const;
-
-private:
- SourceAlpha(Filter* filter)
- : FilterEffect(filter)
- {
- }
-
- virtual void applySoftware() OVERRIDE;
-};
-
-} //namespace WebCore
-
-#endif // SourceAlpha_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/SourceGraphic.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/SourceGraphic.cpp
deleted file mode 100644
index 2a1ced8ec13..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/SourceGraphic.cpp
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * Copyright (C) 2009 Dirk Schulze <krit@webkit.org>
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-
-#include "core/platform/graphics/filters/SourceGraphic.h"
-
-#include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/graphics/filters/Filter.h"
-#include "core/platform/text/TextStream.h"
-#include "core/rendering/RenderTreeAsText.h"
-#include "wtf/StdLibExtras.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-PassRefPtr<SourceGraphic> SourceGraphic::create(Filter* filter)
-{
- return adoptRef(new SourceGraphic(filter));
-}
-
-const AtomicString& SourceGraphic::effectName()
-{
- DEFINE_STATIC_LOCAL(const AtomicString, s_effectName, ("SourceGraphic", AtomicString::ConstructFromLiteral));
- return s_effectName;
-}
-
-void SourceGraphic::determineAbsolutePaintRect()
-{
- Filter* filter = this->filter();
- FloatRect paintRect = filter->sourceImageRect();
- paintRect.scale(filter->filterResolution().width(), filter->filterResolution().height());
- setAbsolutePaintRect(enclosingIntRect(paintRect));
-}
-
-void SourceGraphic::applySoftware()
-{
- ImageBuffer* resultImage = createImageBufferResult();
- Filter* filter = this->filter();
- if (!resultImage || !filter->sourceImage())
- return;
-
- resultImage->context()->drawImageBuffer(filter->sourceImage(), IntPoint());
-}
-
-TextStream& SourceGraphic::externalRepresentation(TextStream& ts, int indent) const
-{
- writeIndent(ts, indent);
- ts << "[SourceGraphic]\n";
- return ts;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/SourceGraphic.h b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/SourceGraphic.h
deleted file mode 100644
index 0a84f16e5b6..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/SourceGraphic.h
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright (C) 2008 Alex Mathews <possessedpenguinbob@gmail.com>
- * Copyright (C) 2009 Dirk Schulze <krit@webkit.org>
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#ifndef SourceGraphic_h
-#define SourceGraphic_h
-
-#include "core/platform/graphics/filters/Filter.h"
-#include "core/platform/graphics/filters/FilterEffect.h"
-
-namespace WebCore {
-
-class SourceGraphic : public FilterEffect {
-public:
- static PassRefPtr<SourceGraphic> create(Filter*);
-
- static const AtomicString& effectName();
-
- virtual void determineAbsolutePaintRect();
-
- virtual FilterEffectType filterEffectType() const { return FilterEffectTypeSourceInput; }
-
- virtual TextStream& externalRepresentation(TextStream&, int indention) const;
-
-private:
- SourceGraphic(Filter* filter)
- : FilterEffect(filter)
- {
- setOperatingColorSpace(ColorSpaceDeviceRGB);
- }
-
- virtual void applySoftware() OVERRIDE;
-};
-
-} //namespace WebCore
-
-#endif // SourceGraphic_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/SpotLightSource.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/SpotLightSource.cpp
deleted file mode 100644
index 7ffe7507d2a..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/SpotLightSource.cpp
+++ /dev/null
@@ -1,195 +0,0 @@
-/*
- * Copyright (C) 2008 Alex Mathews <possessedpenguinbob@gmail.com>
- * Copyright (C) 2004, 2005, 2006, 2007 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2004, 2005 Rob Buis <buis@kde.org>
- * Copyright (C) 2005 Eric Seidel <eric@webkit.org>
- * Copyright (C) 2010 Zoltan Herczeg <zherczeg@webkit.org>
- * Copyright (C) 2011 University of Szeged
- * Copyright (C) 2011 Renata Hodovan <reni@webkit.org>
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY UNIVERSITY OF SZEGED ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL UNIVERSITY OF SZEGED OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/platform/graphics/filters/SpotLightSource.h"
-
-#include "core/platform/text/TextStream.h"
-
-namespace WebCore {
-
-// spot-light edge darkening depends on an absolute treshold
-// according to the SVG 1.1 SE light regression tests
-static const float antiAliasTreshold = 0.016f;
-
-void SpotLightSource::initPaintingData(PaintingData& paintingData)
-{
- paintingData.privateColorVector = paintingData.colorVector;
- paintingData.directionVector.setX(m_direction.x() - m_position.x());
- paintingData.directionVector.setY(m_direction.y() - m_position.y());
- paintingData.directionVector.setZ(m_direction.z() - m_position.z());
- paintingData.directionVector.normalize();
-
- if (!m_limitingConeAngle) {
- paintingData.coneCutOffLimit = 0.0f;
- paintingData.coneFullLight = -antiAliasTreshold;
- } else {
- float limitingConeAngle = m_limitingConeAngle;
- if (limitingConeAngle < 0.0f)
- limitingConeAngle = -limitingConeAngle;
- if (limitingConeAngle > 90.0f)
- limitingConeAngle = 90.0f;
- paintingData.coneCutOffLimit = cosf(deg2rad(180.0f - limitingConeAngle));
- paintingData.coneFullLight = paintingData.coneCutOffLimit - antiAliasTreshold;
- }
-
- // Optimization for common specularExponent values
- if (!m_specularExponent)
- paintingData.specularExponent = 0;
- else if (m_specularExponent == 1.0f)
- paintingData.specularExponent = 1;
- else // It is neither 0.0f nor 1.0f
- paintingData.specularExponent = 2;
-}
-
-void SpotLightSource::updatePaintingData(PaintingData& paintingData, int x, int y, float z)
-{
- paintingData.lightVector.setX(m_position.x() - x);
- paintingData.lightVector.setY(m_position.y() - y);
- paintingData.lightVector.setZ(m_position.z() - z);
- paintingData.lightVectorLength = paintingData.lightVector.length();
-
- float cosineOfAngle = (paintingData.lightVector * paintingData.directionVector) / paintingData.lightVectorLength;
- if (cosineOfAngle > paintingData.coneCutOffLimit) {
- // No light is produced, scanlines are not updated
- paintingData.colorVector.setX(0.0f);
- paintingData.colorVector.setY(0.0f);
- paintingData.colorVector.setZ(0.0f);
- return;
- }
-
- // Set the color of the pixel
- float lightStrength;
- switch (paintingData.specularExponent) {
- case 0:
- lightStrength = 1.0f; // -cosineOfAngle ^ 0 == 1
- break;
- case 1:
- lightStrength = -cosineOfAngle; // -cosineOfAngle ^ 1 == -cosineOfAngle
- break;
- default:
- lightStrength = powf(-cosineOfAngle, m_specularExponent);
- break;
- }
-
- if (cosineOfAngle > paintingData.coneFullLight)
- lightStrength *= (paintingData.coneCutOffLimit - cosineOfAngle) / (paintingData.coneCutOffLimit - paintingData.coneFullLight);
-
- if (lightStrength > 1.0f)
- lightStrength = 1.0f;
-
- paintingData.colorVector.setX(paintingData.privateColorVector.x() * lightStrength);
- paintingData.colorVector.setY(paintingData.privateColorVector.y() * lightStrength);
- paintingData.colorVector.setZ(paintingData.privateColorVector.z() * lightStrength);
-}
-
-bool SpotLightSource::setX(float x)
-{
- if (m_position.x() == x)
- return false;
- m_position.setX(x);
- return true;
-}
-
-bool SpotLightSource::setY(float y)
-{
- if (m_position.y() == y)
- return false;
- m_position.setY(y);
- return true;
-}
-
-bool SpotLightSource::setZ(float z)
-{
- if (m_position.z() == z)
- return false;
- m_position.setZ(z);
- return true;
-}
-
-bool SpotLightSource::setPointsAtX(float pointsAtX)
-{
- if (m_direction.x() == pointsAtX)
- return false;
- m_direction.setX(pointsAtX);
- return true;
-}
-
-bool SpotLightSource::setPointsAtY(float pointsAtY)
-{
- if (m_direction.y() == pointsAtY)
- return false;
- m_direction.setY(pointsAtY);
- return true;
-}
-
-bool SpotLightSource::setPointsAtZ(float pointsAtZ)
-{
- if (m_direction.z() == pointsAtZ)
- return false;
- m_direction.setZ(pointsAtZ);
- return true;
-}
-
-bool SpotLightSource::setSpecularExponent(float specularExponent)
-{
- if (m_specularExponent == specularExponent)
- return false;
- m_specularExponent = specularExponent;
- return true;
-}
-
-bool SpotLightSource::setLimitingConeAngle(float limitingConeAngle)
-{
- if (m_limitingConeAngle == limitingConeAngle)
- return false;
- m_limitingConeAngle = limitingConeAngle;
- return true;
-}
-
-static TextStream& operator<<(TextStream& ts, const FloatPoint3D& p)
-{
- ts << "x=" << p.x() << " y=" << p.y() << " z=" << p.z();
- return ts;
-}
-
-TextStream& SpotLightSource::externalRepresentation(TextStream& ts) const
-{
- ts << "[type=SPOT-LIGHT] ";
- ts << "[position=\"" << position() << "\"]";
- ts << "[direction=\"" << direction() << "\"]";
- ts << "[specularExponent=\"" << specularExponent() << "\"]";
- ts << "[limitingConeAngle=\"" << limitingConeAngle() << "\"]";
- return ts;
-}
-
-}; // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/SpotLightSource.h b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/SpotLightSource.h
deleted file mode 100644
index 7379e66c4d5..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/SpotLightSource.h
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * Copyright (C) 2008 Alex Mathews <possessedpenguinbob@gmail.com>
- * Copyright (C) 2004, 2005, 2006, 2007 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2004, 2005 Rob Buis <buis@kde.org>
- * Copyright (C) 2005 Eric Seidel <eric@webkit.org>
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#ifndef SpotLightSource_h
-#define SpotLightSource_h
-
-#include "core/platform/graphics/filters/LightSource.h"
-
-namespace WebCore {
-
-class SpotLightSource : public LightSource {
-public:
- static PassRefPtr<SpotLightSource> create(const FloatPoint3D& position,
- const FloatPoint3D& direction, float specularExponent, float limitingConeAngle)
- {
- return adoptRef(new SpotLightSource(position, direction, specularExponent, limitingConeAngle));
- }
-
- const FloatPoint3D& position() const { return m_position; }
- const FloatPoint3D& direction() const { return m_direction; }
- float specularExponent() const { return m_specularExponent; }
- float limitingConeAngle() const { return m_limitingConeAngle; }
-
- virtual bool setX(float) OVERRIDE;
- virtual bool setY(float) OVERRIDE;
- virtual bool setZ(float) OVERRIDE;
- virtual bool setPointsAtX(float) OVERRIDE;
- virtual bool setPointsAtY(float) OVERRIDE;
- virtual bool setPointsAtZ(float) OVERRIDE;
-
- virtual bool setSpecularExponent(float) OVERRIDE;
- virtual bool setLimitingConeAngle(float) OVERRIDE;
-
- virtual void initPaintingData(PaintingData&);
- virtual void updatePaintingData(PaintingData&, int x, int y, float z);
-
- virtual TextStream& externalRepresentation(TextStream&) const;
-
-private:
- SpotLightSource(const FloatPoint3D& position, const FloatPoint3D& direction,
- float specularExponent, float limitingConeAngle)
- : LightSource(LS_SPOT)
- , m_position(position)
- , m_direction(direction)
- , m_specularExponent(specularExponent)
- , m_limitingConeAngle(limitingConeAngle)
- {
- }
-
- FloatPoint3D m_position;
- FloatPoint3D m_direction;
-
- float m_specularExponent;
- float m_limitingConeAngle;
-};
-
-} // namespace WebCore
-
-#endif // SpotLightSource_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterArrayParameter.h b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterArrayParameter.h
deleted file mode 100644
index ccaaf207384..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterArrayParameter.h
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * Copyright (C) 2012 Adobe Systems Incorporated. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above
- * copyright notice, this list of conditions and the following
- * disclaimer.
- * 2. Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following
- * disclaimer in the documentation and/or other materials
- * provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
- * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
- * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
- * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#ifndef CustomFilterArrayParameter_h
-#define CustomFilterArrayParameter_h
-
-#include "core/platform/animation/AnimationUtilities.h"
-#include "core/platform/graphics/filters/custom/CustomFilterParameter.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-class CustomFilterArrayParameter : public CustomFilterParameter {
-public:
- static PassRefPtr<CustomFilterArrayParameter> create(const String& name)
- {
- return adoptRef(new CustomFilterArrayParameter(name));
- }
-
- unsigned size() const { return m_data.size(); }
- double valueAt(unsigned index) const { return m_data.at(index); }
-
- void addValue(double value) { m_data.append(value); }
-
- virtual PassRefPtr<CustomFilterParameter> blend(const CustomFilterParameter* from, double progress)
- {
- if (!from || !isSameType(*from))
- return this;
-
- const CustomFilterArrayParameter* fromArray = static_cast<const CustomFilterArrayParameter*>(from);
-
- if (size() != fromArray->size())
- return this;
-
- RefPtr<CustomFilterArrayParameter> result = CustomFilterArrayParameter::create(name());
- for (size_t i = 0; i < size(); ++i)
- result->addValue(WebCore::blend(fromArray->valueAt(i), valueAt(i), progress));
-
- return result.release();
- }
-
- virtual bool operator==(const CustomFilterParameter& o) const
- {
- if (!isSameType(o))
- return false;
-
- const CustomFilterArrayParameter* other = static_cast<const CustomFilterArrayParameter*>(&o);
- return m_data == other->m_data;
- }
-
-private:
- CustomFilterArrayParameter(const String& name)
- : CustomFilterParameter(ARRAY, name)
- {
- }
-
- Vector<double> m_data;
-};
-
-} // namespace WebCore
-
-
-#endif // CustomFilterArrayParameter_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterCompiledProgram.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterCompiledProgram.cpp
deleted file mode 100644
index b9fd89d06af..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterCompiledProgram.cpp
+++ /dev/null
@@ -1,150 +0,0 @@
-/*
- * Copyright (C) 2012 Adobe Systems Incorporated. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above
- * copyright notice, this list of conditions and the following
- * disclaimer.
- * 2. Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following
- * disclaimer in the documentation and/or other materials
- * provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
- * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
- * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
- * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/platform/graphics/filters/custom/CustomFilterCompiledProgram.h"
-
-namespace WebCore {
-
-CustomFilterCompiledProgram::CustomFilterCompiledProgram(PassRefPtr<GraphicsContext3D> context, const String& validatedVertexShader, const String& validatedFragmentShader, CustomFilterProgramType programType)
- : m_context(context)
- , m_program(0)
- , m_positionAttribLocation(-1)
- , m_texAttribLocation(-1)
- , m_meshAttribLocation(-1)
- , m_triangleAttribLocation(-1)
- , m_meshBoxLocation(-1)
- , m_projectionMatrixLocation(-1)
- , m_tileSizeLocation(-1)
- , m_meshSizeLocation(-1)
- , m_samplerLocation(-1)
- , m_samplerSizeLocation(-1)
- , m_contentSamplerLocation(-1)
- , m_isInitialized(false)
-{
- m_context->makeContextCurrent();
-
- Platform3DObject vertexShader = compileShader(GraphicsContext3D::VERTEX_SHADER, validatedVertexShader);
- if (!vertexShader)
- return;
-
- Platform3DObject fragmentShader = compileShader(GraphicsContext3D::FRAGMENT_SHADER, validatedFragmentShader);
- if (!fragmentShader) {
- m_context->deleteShader(vertexShader);
- return;
- }
-
- m_program = linkProgram(vertexShader, fragmentShader);
-
- m_context->deleteShader(vertexShader);
- m_context->deleteShader(fragmentShader);
-
- if (!m_program)
- return;
-
- initializeParameterLocations(programType);
-
- m_isInitialized = true;
-}
-
-Platform3DObject CustomFilterCompiledProgram::compileShader(GC3Denum shaderType, const String& shaderString)
-{
- ASSERT(!shaderString.isNull());
-
- Platform3DObject shader = m_context->createShader(shaderType);
- m_context->shaderSource(shader, shaderString);
- m_context->compileShader(shader);
-
- int compiled = 0;
- m_context->getShaderiv(shader, GraphicsContext3D::COMPILE_STATUS, &compiled);
- if (!compiled) {
- // FIXME: This is an invalid shader. Throw some errors.
- // https://bugs.webkit.org/show_bug.cgi?id=74416
- m_context->deleteShader(shader);
- return 0;
- }
-
- return shader;
-}
-
-Platform3DObject CustomFilterCompiledProgram::linkProgram(Platform3DObject vertexShader, Platform3DObject fragmentShader)
-{
- Platform3DObject program = m_context->createProgram();
- m_context->attachShader(program, vertexShader);
- m_context->attachShader(program, fragmentShader);
- m_context->linkProgram(program);
-
- int linked = 0;
- m_context->getProgramiv(program, GraphicsContext3D::LINK_STATUS, &linked);
- if (!linked) {
- // FIXME: Invalid vertex/fragment shader combination. Throw some errors here.
- // https://bugs.webkit.org/show_bug.cgi?id=74416
- m_context->deleteProgram(program);
- return 0;
- }
-
- return program;
-}
-
-void CustomFilterCompiledProgram::initializeParameterLocations(CustomFilterProgramType programType)
-{
- m_positionAttribLocation = m_context->getAttribLocation(m_program, "a_position");
- m_texAttribLocation = m_context->getAttribLocation(m_program, "a_texCoord");
- m_meshAttribLocation = m_context->getAttribLocation(m_program, "a_meshCoord");
- m_triangleAttribLocation = m_context->getAttribLocation(m_program, "a_triangleCoord");
- m_meshBoxLocation = m_context->getUniformLocation(m_program, "u_meshBox");
- m_tileSizeLocation = m_context->getUniformLocation(m_program, "u_tileSize");
- m_meshSizeLocation = m_context->getUniformLocation(m_program, "u_meshSize");
- m_projectionMatrixLocation = m_context->getUniformLocation(m_program, "u_projectionMatrix");
- m_samplerSizeLocation = m_context->getUniformLocation(m_program, "u_textureSize");
- m_contentSamplerLocation = m_context->getUniformLocation(m_program, "u_contentTexture");
- if (programType == PROGRAM_TYPE_BLENDS_ELEMENT_TEXTURE) {
- // When the author uses the CSS mix function in a custom filter, WebKit adds the internal
- // symbol css_u_texture to the shader code, which references the texture of the element.
- m_samplerLocation = m_context->getUniformLocation(m_program, "css_u_texture");
- }
-}
-
-int CustomFilterCompiledProgram::uniformLocationByName(const String& name)
-{
- ASSERT(m_isInitialized);
- // FIXME: Improve this by caching the uniform locations.
- return m_context->getUniformLocation(m_program, name);
-}
-
-CustomFilterCompiledProgram::~CustomFilterCompiledProgram()
-{
- if (m_program) {
- m_context->makeContextCurrent();
- m_context->deleteProgram(m_program);
- }
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterCompiledProgram.h b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterCompiledProgram.h
deleted file mode 100644
index c5a5d42dcd2..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterCompiledProgram.h
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * Copyright (C) 2012 Adobe Systems Incorporated. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above
- * copyright notice, this list of conditions and the following
- * disclaimer.
- * 2. Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following
- * disclaimer in the documentation and/or other materials
- * provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
- * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
- * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
- * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#ifndef CustomFilterCompiledProgram_h
-#define CustomFilterCompiledProgram_h
-
-#include "core/platform/graphics/GraphicsContext3D.h"
-#include "core/platform/graphics/filters/custom/CustomFilterProgramInfo.h"
-#include "wtf/RefCounted.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class CustomFilterGlobalContext;
-
-class CustomFilterCompiledProgram: public RefCounted<CustomFilterCompiledProgram> {
-public:
- static PassRefPtr<CustomFilterCompiledProgram> create(PassRefPtr<GraphicsContext3D> context, const String& validatedVertexShader, const String& validatedFragmentShader, CustomFilterProgramType programType)
- {
- return adoptRef(new CustomFilterCompiledProgram(context, validatedVertexShader, validatedFragmentShader, programType));
- }
-
- ~CustomFilterCompiledProgram();
-
- int positionAttribLocation() const { return m_positionAttribLocation; }
- int texAttribLocation() const { return m_texAttribLocation; }
- int meshAttribLocation() const { return m_meshAttribLocation; }
- int triangleAttribLocation() const { return m_triangleAttribLocation; }
- int meshBoxLocation() const { return m_meshBoxLocation; }
- int projectionMatrixLocation() const { return m_projectionMatrixLocation; }
- int tileSizeLocation() const { return m_tileSizeLocation; }
- int meshSizeLocation() const { return m_meshSizeLocation; }
- int samplerLocation() const { return m_samplerLocation; }
- int contentSamplerLocation() const { return m_contentSamplerLocation; }
- int samplerSizeLocation() const { return m_samplerSizeLocation; }
-
- int uniformLocationByName(const String&);
-
- bool isInitialized() const { return m_isInitialized; }
-
- Platform3DObject program() const { return m_program; }
-private:
- CustomFilterCompiledProgram(PassRefPtr<GraphicsContext3D>, const String& validatedVertexShader, const String& validatedFragmentShader, CustomFilterProgramType);
-
- Platform3DObject compileShader(GC3Denum shaderType, const String& shaderString);
- Platform3DObject linkProgram(Platform3DObject vertexShader, Platform3DObject fragmentShader);
- void initializeParameterLocations(CustomFilterProgramType);
-
- RefPtr<GraphicsContext3D> m_context;
- Platform3DObject m_program;
-
- int m_positionAttribLocation;
- int m_texAttribLocation;
- int m_meshAttribLocation;
- int m_triangleAttribLocation;
- int m_meshBoxLocation;
- int m_projectionMatrixLocation;
- int m_tileSizeLocation;
- int m_meshSizeLocation;
- int m_samplerLocation;
- int m_samplerSizeLocation;
- int m_contentSamplerLocation;
-
- bool m_isInitialized;
-};
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterConstants.h b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterConstants.h
deleted file mode 100644
index 559dbc8750f..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterConstants.h
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * Copyright (C) 2012 Adobe Systems Incorporated. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above
- * copyright notice, this list of conditions and the following
- * disclaimer.
- * 2. Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following
- * disclaimer in the documentation and/or other materials
- * provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
- * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
- * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
- * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#ifndef CustomFilterConstants_h
-#define CustomFilterConstants_h
-
-namespace WebCore {
-
-enum CustomFilterMeshConstants {
- // Vertex attribute sizes
- PositionAttribSize = 4,
- TexAttribSize = 2,
- MeshAttribSize = 2,
- TriangleAttribSize = 3,
- // Vertex attribute offsets
- PositionAttribOffset = 0,
- TexAttribOffset = PositionAttribOffset + PositionAttribSize * sizeof(float),
- MeshAttribOffset = TexAttribOffset + TexAttribSize * sizeof(float),
- TriangleAttribOffset = MeshAttribOffset + MeshAttribSize * sizeof(float)
-};
-
-enum CustomFilterMeshType {
- MeshTypeAttached,
- MeshTypeDetached
-};
-
-enum CustomFilterProgramType {
- PROGRAM_TYPE_NO_ELEMENT_TEXTURE,
- PROGRAM_TYPE_BLENDS_ELEMENT_TEXTURE
-};
-
-} // namespace WebCore
-
-#endif // CustomFilterConstants_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterGlobalContext.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterGlobalContext.cpp
deleted file mode 100644
index 07b0aa0cec4..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterGlobalContext.cpp
+++ /dev/null
@@ -1,113 +0,0 @@
-/*
- * Copyright (C) 2012 Adobe Systems Incorporated. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above
- * copyright notice, this list of conditions and the following
- * disclaimer.
- * 2. Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following
- * disclaimer in the documentation and/or other materials
- * provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
- * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
- * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
- * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/platform/graphics/filters/custom/CustomFilterGlobalContext.h"
-
-#include "core/platform/graphics/GraphicsContext3D.h"
-#include "core/platform/graphics/filters/custom/CustomFilterValidatedProgram.h"
-
-namespace WebCore {
-
-CustomFilterGlobalContext::CustomFilterGlobalContext()
-{
-}
-
-CustomFilterGlobalContext::~CustomFilterGlobalContext()
-{
- for (CustomFilterValidatedProgramsMap::iterator iter = m_programs.begin(); iter != m_programs.end(); ++iter)
- iter->value->detachFromGlobalContext();
-}
-
-ANGLEWebKitBridge* CustomFilterGlobalContext::webglShaderValidator()
-{
- if (!m_webglShaderValidator)
- m_webglShaderValidator = createShaderValidator(SH_WEBGL_SPEC);
- return m_webglShaderValidator.get();
-}
-
-ANGLEWebKitBridge* CustomFilterGlobalContext::mixShaderValidator()
-{
- if (!m_mixShaderValidator)
- m_mixShaderValidator = createShaderValidator(SH_CSS_SHADERS_SPEC);
- return m_mixShaderValidator.get();
-}
-
-PassOwnPtr<ANGLEWebKitBridge> CustomFilterGlobalContext::createShaderValidator(ShShaderSpec shaderSpec)
-{
- OwnPtr<ANGLEWebKitBridge> validator = adoptPtr(new ANGLEWebKitBridge(SH_ESSL_OUTPUT, shaderSpec));
- ShBuiltInResources resources;
- ShInitBuiltInResources(&resources);
- validator->setResources(resources);
- return validator.release();
-}
-
-void CustomFilterGlobalContext::prepareContextIfNeeded()
-{
- if (m_context.get())
- return;
-
- GraphicsContext3D::Attributes attributes;
- attributes.preserveDrawingBuffer = true;
- attributes.premultipliedAlpha = false;
- attributes.shareResources = true;
- attributes.preferDiscreteGPU = true;
- m_context = GraphicsContext3D::create(attributes);
- if (!m_context)
- return;
- m_context->makeContextCurrent();
- m_context->enable(GraphicsContext3D::DEPTH_TEST);
-}
-
-PassRefPtr<CustomFilterValidatedProgram> CustomFilterGlobalContext::getValidatedProgram(const CustomFilterProgramInfo& programInfo)
-{
- CustomFilterValidatedProgramsMap::iterator iter = m_programs.find(programInfo);
- if (iter != m_programs.end())
- return iter->value;
-
- RefPtr<CustomFilterValidatedProgram> validatedProgram = CustomFilterValidatedProgram::create(this, programInfo);
- m_programs.set(programInfo, validatedProgram.get());
- return validatedProgram.release();
-}
-
-void CustomFilterGlobalContext::removeValidatedProgram(const CustomFilterValidatedProgram* program)
-{
- CustomFilterValidatedProgramsMap::iterator iter = m_programs.find(program->programInfo());
- ASSERT(iter != m_programs.end());
- m_programs.remove(iter);
-
-#ifndef NDEBUG
- // Check that there's no way we could have the same program under a different key.
- for (iter = m_programs.begin(); iter != m_programs.end(); ++iter)
- ASSERT(iter->value != program);
-#endif
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterGlobalContext.h b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterGlobalContext.h
deleted file mode 100644
index 8d4d0f25790..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterGlobalContext.h
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * Copyright (C) 2012 Adobe Systems Incorporated. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above
- * copyright notice, this list of conditions and the following
- * disclaimer.
- * 2. Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following
- * disclaimer in the documentation and/or other materials
- * provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
- * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
- * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
- * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#ifndef CustomFilterGlobalContext_h
-#define CustomFilterGlobalContext_h
-
-#include "core/platform/graphics/ANGLEWebKitBridge.h"
-#include "core/platform/graphics/filters/custom/CustomFilterProgramInfo.h"
-#include "wtf/HashMap.h"
-#include "wtf/RefPtr.h"
-
-namespace WebCore {
-
-class CustomFilterValidatedProgram;
-class GraphicsContext3D;
-
-typedef HashMap<CustomFilterProgramInfo, CustomFilterValidatedProgram*> CustomFilterValidatedProgramsMap;
-
-class CustomFilterGlobalContext {
-public:
- CustomFilterGlobalContext();
- ~CustomFilterGlobalContext();
-
- GraphicsContext3D* context() const { return m_context.get(); }
-
- // CSS shaders not referenced from the CSS mix function should be validated just like regular WebGL shaders.
- // This ANGLE validator uses the SH_WEBGL_SPEC flag.
- ANGLEWebKitBridge* webglShaderValidator();
-
- // CSS shaders referenced from the CSS mix function should be validated slightly differently than WebGL shaders.
- // This ANGLE validator uses the SH_CSS_SHADERS_SPEC flag.
- // Under this flag, most notably:
- // - The "gl_FragColor" built-in is not available.
- // - Instead, the "css_MixColor" and "css_ColorMatrix" built-ins are available.
- // - The "css_" prefix is reserved.
- // - In the translated source that ANGLE returns, ANGLE renames the author's "main" function to "css_main".
- // The complete details are documented in ANGLE/ShaderLang.h.
- ANGLEWebKitBridge* mixShaderValidator();
-
- void prepareContextIfNeeded();
-
- PassRefPtr<CustomFilterValidatedProgram> getValidatedProgram(const CustomFilterProgramInfo&);
- void removeValidatedProgram(const CustomFilterValidatedProgram*);
-private:
- static PassOwnPtr<ANGLEWebKitBridge> createShaderValidator(ShShaderSpec);
-
- RefPtr<GraphicsContext3D> m_context;
- OwnPtr<ANGLEWebKitBridge> m_webglShaderValidator;
- OwnPtr<ANGLEWebKitBridge> m_mixShaderValidator;
- CustomFilterValidatedProgramsMap m_programs;
-};
-
-} // namespace WebCore
-
-#endif // CustomFilterGlobalContext_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterMesh.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterMesh.cpp
deleted file mode 100644
index 9d6894e6890..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterMesh.cpp
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Copyright (C) 2011 Adobe Systems Incorporated. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above
- * copyright notice, this list of conditions and the following
- * disclaimer.
- * 2. Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following
- * disclaimer in the documentation and/or other materials
- * provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
- * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
- * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
- * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/platform/graphics/GraphicsContext3D.h"
-#include "core/platform/graphics/filters/custom/CustomFilterMesh.h"
-#include "core/platform/graphics/filters/custom/CustomFilterMeshGenerator.h"
-
-namespace WebCore {
-
-CustomFilterMesh::CustomFilterMesh(GraphicsContext3D* context, unsigned columns, unsigned rows,
- const FloatRect& meshBox, CustomFilterMeshType meshType)
- : m_context(context)
- , m_verticesBufferObject(0)
- , m_elementsBufferObject(0)
- , m_meshBox(meshBox)
- , m_meshType(meshType)
-{
- CustomFilterMeshGenerator generator(columns, rows, meshBox, meshType);
- m_indicesCount = generator.indicesCount();
- m_bytesPerVertex = generator.floatsPerVertex() * sizeof(float);
-
- m_context->makeContextCurrent();
-
- m_verticesBufferObject = m_context->createBuffer();
- m_context->bindBuffer(GraphicsContext3D::ARRAY_BUFFER, m_verticesBufferObject);
- m_context->bufferData(GraphicsContext3D::ARRAY_BUFFER, generator.vertices().size() * sizeof(float), generator.vertices().data(), GraphicsContext3D::STATIC_DRAW);
-
- m_elementsBufferObject = m_context->createBuffer();
- m_context->bindBuffer(GraphicsContext3D::ELEMENT_ARRAY_BUFFER, m_elementsBufferObject);
- m_context->bufferData(GraphicsContext3D::ELEMENT_ARRAY_BUFFER, generator.indices().size() * sizeof(uint16_t), generator.indices().data(), GraphicsContext3D::STATIC_DRAW);
-}
-
-CustomFilterMesh::~CustomFilterMesh()
-{
- m_context->makeContextCurrent();
- m_context->deleteBuffer(m_verticesBufferObject);
- m_context->deleteBuffer(m_elementsBufferObject);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterMesh.h b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterMesh.h
deleted file mode 100644
index 022479f14a8..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterMesh.h
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * Copyright (C) 2011 Adobe Systems Incorporated. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above
- * copyright notice, this list of conditions and the following
- * disclaimer.
- * 2. Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following
- * disclaimer in the documentation and/or other materials
- * provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
- * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
- * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
- * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#ifndef CustomFilterMesh_h
-#define CustomFilterMesh_h
-
-#include "core/platform/graphics/FloatRect.h"
-#include "core/platform/graphics/GraphicsTypes3D.h"
-#include "core/platform/graphics/filters/custom/CustomFilterOperation.h"
-#include "wtf/RefCounted.h"
-
-namespace WebCore {
-
-class GraphicsContext3D;
-
-class CustomFilterMesh : public RefCounted<CustomFilterMesh> {
-public:
- static PassRefPtr<CustomFilterMesh> create(GraphicsContext3D* context, unsigned cols, unsigned rows, const FloatRect& meshBox, CustomFilterMeshType meshType)
- {
- return adoptRef(new CustomFilterMesh(context, cols, rows, meshBox, meshType));
- }
- ~CustomFilterMesh();
-
- Platform3DObject verticesBufferObject() const { return m_verticesBufferObject; }
- unsigned bytesPerVertex() const { return m_bytesPerVertex; }
-
- Platform3DObject elementsBufferObject() const { return m_elementsBufferObject; }
- unsigned indicesCount() const { return m_indicesCount; }
-
- const FloatRect& meshBox() const { return m_meshBox; }
- CustomFilterMeshType meshType() const { return m_meshType; }
-
-private:
- CustomFilterMesh(GraphicsContext3D*, unsigned cols, unsigned rows, const FloatRect& meshBox, CustomFilterMeshType);
-
- GraphicsContext3D* m_context;
-
- Platform3DObject m_verticesBufferObject;
- unsigned m_bytesPerVertex;
-
- Platform3DObject m_elementsBufferObject;
- unsigned m_indicesCount;
-
- FloatRect m_meshBox;
- CustomFilterMeshType m_meshType;
-};
-
-} // namespace WebCore
-
-#endif // CustomFilterMesh_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterMeshGenerator.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterMeshGenerator.cpp
deleted file mode 100644
index ff191c592f7..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterMeshGenerator.cpp
+++ /dev/null
@@ -1,173 +0,0 @@
-/*
- * Copyright (C) 2011 Adobe Systems Incorporated. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above
- * copyright notice, this list of conditions and the following
- * disclaimer.
- * 2. Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following
- * disclaimer in the documentation and/or other materials
- * provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
- * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
- * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
- * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/platform/graphics/filters/custom/CustomFilterMeshGenerator.h"
-
-#ifndef NDEBUG
-#include <stdio.h> // Needed for printf used in dumpBuffers.
-#endif
-
-namespace WebCore {
-
-#ifndef NDEBUG
-// Use "call 'WebCore::s_dumpCustomFilterMeshBuffers' = 1" in GDB to activate printing of the mesh buffers.
-static bool s_dumpCustomFilterMeshBuffers = false;
-#endif
-
-CustomFilterMeshGenerator::CustomFilterMeshGenerator(unsigned columns, unsigned rows, const FloatRect& meshBox, CustomFilterMeshType meshType)
- : m_meshType(meshType)
- , m_points(columns + 1, rows + 1)
- , m_tiles(columns, rows)
- , m_tileSizeInPixels(meshBox.width() / m_tiles.width(), meshBox.height() / m_tiles.height())
- , m_tileSizeInDeviceSpace(1.0f / m_tiles.width(), 1.0f / m_tiles.height())
- , m_meshBox(meshBox)
-{
- // Build the two buffers needed to draw triangles:
- // * m_vertices has a number of float attributes that will be passed to the vertex shader
- // for each computed vertex. This number is calculated in floatsPerVertex() based on the meshType.
- // * m_indices is a buffer that will have 3 indices per triangle. Each index will point inside
- // the m_vertices buffer.
- m_vertices.reserveCapacity(verticesCount() * floatsPerVertex());
- m_indices.reserveCapacity(indicesCount());
-
- // Based on the meshType there can be two types of meshes.
- // * attached: each triangle uses vertices from the neighbor triangles. This is useful to save some GPU memory
- // when there's no need to explode the tiles.
- // * detached: each triangle has its own vertices. This means each triangle can be moved independently and a vec3
- // attribute is passed, so that each vertex can be uniquely identified.
- if (m_meshType == MeshTypeAttached)
- generateAttachedMesh();
- else
- generateDetachedMesh();
-
-#ifndef NDEBUG
- if (s_dumpCustomFilterMeshBuffers)
- dumpBuffers();
-#endif
-}
-
-void CustomFilterMeshGenerator::addAttachedMeshIndex(int quadX, int quadY, int triangleX, int triangleY, int triangle)
-{
- UNUSED_PARAM(triangle);
- m_indices.append((quadY + triangleY) * m_points.width() + (quadX + triangleX));
-}
-
-void CustomFilterMeshGenerator::generateAttachedMesh()
-{
- for (int j = 0; j < m_points.height(); ++j) {
- for (int i = 0; i < m_points.width(); ++i)
- addAttachedMeshVertexAttributes(i, j);
- }
-
- for (int j = 0; j < m_tiles.height(); ++j) {
- for (int i = 0; i < m_tiles.width(); ++i)
- addTile<&CustomFilterMeshGenerator::addAttachedMeshIndex>(i, j);
- }
-}
-
-void CustomFilterMeshGenerator::addDetachedMeshVertexAndIndex(int quadX, int quadY, int triangleX, int triangleY, int triangle)
-{
- addDetachedMeshVertexAttributes(quadX, quadY, triangleX, triangleY, triangle);
- m_indices.append(m_indices.size());
-}
-
-void CustomFilterMeshGenerator::generateDetachedMesh()
-{
- for (int j = 0; j < m_tiles.height(); ++j) {
- for (int i = 0; i < m_tiles.width(); ++i)
- addTile<&CustomFilterMeshGenerator::addDetachedMeshVertexAndIndex>(i, j);
- }
-}
-
-void CustomFilterMeshGenerator::addPositionAttribute(int quadX, int quadY)
-{
- // vec4 a_position
- m_vertices.append(m_tileSizeInPixels.width() * quadX - 0.5f + m_meshBox.x());
- m_vertices.append(m_tileSizeInPixels.height() * quadY - 0.5f + m_meshBox.y());
- m_vertices.append(0.0f); // z
- m_vertices.append(1.0f);
-}
-
-void CustomFilterMeshGenerator::addTexCoordAttribute(int quadX, int quadY)
-{
- // vec2 a_texCoord
- m_vertices.append(m_tileSizeInPixels.width() * quadX + m_meshBox.x());
- m_vertices.append(m_tileSizeInPixels.height() * quadY + m_meshBox.y());
-}
-
-void CustomFilterMeshGenerator::addMeshCoordAttribute(int quadX, int quadY)
-{
- // vec2 a_meshCoord
- m_vertices.append(m_tileSizeInDeviceSpace.width() * quadX);
- m_vertices.append(m_tileSizeInDeviceSpace.height() * quadY);
-}
-
-void CustomFilterMeshGenerator::addTriangleCoordAttribute(int quadX, int quadY, int triangle)
-{
- // vec3 a_triangleCoord
- m_vertices.append(quadX);
- m_vertices.append(quadY);
- m_vertices.append(triangle);
-}
-
-void CustomFilterMeshGenerator::addAttachedMeshVertexAttributes(int quadX, int quadY)
-{
- addPositionAttribute(quadX, quadY);
- addTexCoordAttribute(quadX, quadY);
- addMeshCoordAttribute(quadX, quadY);
-}
-
-void CustomFilterMeshGenerator::addDetachedMeshVertexAttributes(int quadX, int quadY, int triangleX, int triangleY, int triangle)
-{
- addAttachedMeshVertexAttributes(quadX + triangleX, quadY + triangleY);
- addTriangleCoordAttribute(quadX, quadY, triangle);
-}
-
-#ifndef NDEBUG
-void CustomFilterMeshGenerator::dumpBuffers() const
-{
- printf("Mesh buffers: Points.width(): %d, Points.height(): %d meshBox: %f, %f, %f, %f, type: %s\n",
- m_points.width(), m_points.height(), m_meshBox.x(), m_meshBox.y(), m_meshBox.width(), m_meshBox.height(),
- (m_meshType == MeshTypeAttached) ? "Attached" : "Detached");
- printf("---Vertex:\n\t");
- for (unsigned i = 0; i < m_vertices.size(); ++i) {
- printf("%f ", m_vertices.at(i));
- if (!((i + 1) % floatsPerVertex()))
- printf("\n\t");
- }
- printf("\n---Indices: ");
- for (unsigned i = 0; i < m_indices.size(); ++i)
- printf("%d ", m_indices.at(i));
- printf("\n");
-}
-#endif
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterMeshGenerator.h b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterMeshGenerator.h
deleted file mode 100644
index 2928a80c546..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterMeshGenerator.h
+++ /dev/null
@@ -1,121 +0,0 @@
-/*
- * Copyright (C) 2011 Adobe Systems Incorporated. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above
- * copyright notice, this list of conditions and the following
- * disclaimer.
- * 2. Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following
- * disclaimer in the documentation and/or other materials
- * provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
- * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
- * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
- * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#ifndef CustomFilterMeshGenerator_h
-#define CustomFilterMeshGenerator_h
-
-#include "core/platform/graphics/FloatRect.h"
-#include "core/platform/graphics/filters/custom/CustomFilterConstants.h"
-#include "core/platform/graphics/filters/custom/CustomFilterOperation.h"
-
-namespace WebCore {
-
-class CustomFilterMeshGenerator {
-public:
- // Lines and columns are the values passed in CSS. The result is vertex mesh that has 'rows' numbers of rows
- // and 'columns' number of columns with a total of 'rows + 1' * 'columns + 1' vertices.
- // MeshBox is the filtered area calculated defined using the border-box, padding-box, content-box or filter-box
- // attributes. A value of (0, 0, 1, 1) will cover the entire output surface.
- CustomFilterMeshGenerator(unsigned columns, unsigned rows, const FloatRect& meshBox, CustomFilterMeshType);
-
- const Vector<float>& vertices() const { return m_vertices; }
- const Vector<uint16_t>& indices() const { return m_indices; }
-
- const IntSize& points() const { return m_points; }
- unsigned pointsCount() const { return m_points.width() * m_points.height(); }
-
- const IntSize& tiles() const { return m_tiles; }
- unsigned tilesCount() const { return m_tiles.width() * m_tiles.height(); }
-
- unsigned indicesCount() const
- {
- const unsigned trianglesPerTile = 2;
- const unsigned indicesPerTriangle = 3;
- return tilesCount() * trianglesPerTile * indicesPerTriangle;
- }
-
- unsigned floatsPerVertex() const
- {
- static const unsigned AttachedMeshVertexSize = PositionAttribSize + TexAttribSize + MeshAttribSize;
- static const unsigned DetachedMeshVertexSize = AttachedMeshVertexSize + TriangleAttribSize;
- return m_meshType == MeshTypeAttached ? AttachedMeshVertexSize : DetachedMeshVertexSize;
- }
-
- unsigned verticesCount() const
- {
- return m_meshType == MeshTypeAttached ? pointsCount() : indicesCount();
- }
-
-private:
- typedef void (CustomFilterMeshGenerator::*AddTriangleVertexFunction)(int quadX, int quadY, int triangleX, int triangleY, int triangle);
-
- template <AddTriangleVertexFunction addTriangleVertex>
- void addTile(int quadX, int quadY)
- {
- ((*this).*(addTriangleVertex))(quadX, quadY, 0, 0, 1);
- ((*this).*(addTriangleVertex))(quadX, quadY, 1, 0, 2);
- ((*this).*(addTriangleVertex))(quadX, quadY, 1, 1, 3);
- ((*this).*(addTriangleVertex))(quadX, quadY, 0, 0, 4);
- ((*this).*(addTriangleVertex))(quadX, quadY, 1, 1, 5);
- ((*this).*(addTriangleVertex))(quadX, quadY, 0, 1, 6);
- }
-
- void addAttachedMeshIndex(int quadX, int quadY, int triangleX, int triangleY, int triangle);
-
- void generateAttachedMesh();
-
- void addDetachedMeshVertexAndIndex(int quadX, int quadY, int triangleX, int triangleY, int triangle);
-
- void generateDetachedMesh();
- void addPositionAttribute(int quadX, int quadY);
- void addTexCoordAttribute(int quadX, int quadY);
- void addMeshCoordAttribute(int quadX, int quadY);
- void addTriangleCoordAttribute(int quadX, int quadY, int triangle);
- void addAttachedMeshVertexAttributes(int quadX, int quadY);
- void addDetachedMeshVertexAttributes(int quadX, int quadY, int triangleX, int triangleY, int triangle);
-
-#ifndef NDEBUG
- void dumpBuffers() const;
-#endif
-
-private:
- Vector<float> m_vertices;
- Vector<uint16_t> m_indices;
-
- CustomFilterMeshType m_meshType;
- IntSize m_points;
- IntSize m_tiles;
- FloatSize m_tileSizeInPixels;
- FloatSize m_tileSizeInDeviceSpace;
- FloatRect m_meshBox;
-};
-
-} // namespace WebCore
-
-#endif // CustomFilterMeshGenerator_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterNumberParameter.h b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterNumberParameter.h
deleted file mode 100644
index b26349555bd..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterNumberParameter.h
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * Copyright (C) 2012 Adobe Systems Incorporated. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above
- * copyright notice, this list of conditions and the following
- * disclaimer.
- * 2. Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following
- * disclaimer in the documentation and/or other materials
- * provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
- * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
- * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
- * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#ifndef CustomFilterNumberParameter_h
-#define CustomFilterNumberParameter_h
-
-#include "core/platform/animation/AnimationUtilities.h"
-#include "core/platform/graphics/filters/custom/CustomFilterParameter.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-class CustomFilterNumberParameter : public CustomFilterParameter {
-public:
- static PassRefPtr<CustomFilterNumberParameter> create(const String& name)
- {
- return adoptRef(new CustomFilterNumberParameter(name));
- }
-
- unsigned size() const { return m_data.size(); }
- double valueAt(unsigned index) const { return m_data.at(index); }
-
- void addValue(double value) { m_data.append(value); }
-
- virtual PassRefPtr<CustomFilterParameter> blend(const CustomFilterParameter* from, double progress)
- {
- if (!from || !isSameType(*from))
- return this;
- const CustomFilterNumberParameter* fromNumber = static_cast<const CustomFilterNumberParameter*>(from);
- if (size() != fromNumber->size())
- return this;
- RefPtr<CustomFilterNumberParameter> result = CustomFilterNumberParameter::create(name());
- for (size_t i = 0; i < size(); ++i)
- result->addValue(WebCore::blend(fromNumber->valueAt(i), valueAt(i), progress));
- return result.release();
- }
-
- virtual bool operator==(const CustomFilterParameter& o) const
- {
- if (!isSameType(o))
- return false;
- const CustomFilterNumberParameter* other = static_cast<const CustomFilterNumberParameter*>(&o);
- return m_data == other->m_data;
- }
-
-private:
- CustomFilterNumberParameter(const String& name)
- : CustomFilterParameter(NUMBER, name)
- {
- }
-
- Vector<double, 4> m_data;
-};
-
-} // namespace WebCore
-
-
-#endif // CustomFilterNumberParameter_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterOperation.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterOperation.cpp
deleted file mode 100644
index 99aa9dbd07f..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterOperation.cpp
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * Copyright (C) 2012 Adobe Systems Incorporated. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above
- * copyright notice, this list of conditions and the following
- * disclaimer.
- * 2. Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following
- * disclaimer in the documentation and/or other materials
- * provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
- * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
- * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
- * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/platform/graphics/filters/custom/CustomFilterOperation.h"
-
-#include "core/platform/graphics/filters/FilterOperation.h"
-#include "core/platform/graphics/filters/custom/CustomFilterParameter.h"
-#include "core/platform/graphics/filters/custom/CustomFilterProgram.h"
-
-namespace WebCore {
-
-CustomFilterOperation::CustomFilterOperation(PassRefPtr<CustomFilterProgram> program, const CustomFilterParameterList& sortedParameters, unsigned meshRows, unsigned meshColumns, CustomFilterMeshType meshType)
- : FilterOperation(CUSTOM)
- , m_program(program)
- , m_parameters(sortedParameters)
- , m_meshRows(meshRows)
- , m_meshColumns(meshColumns)
- , m_meshType(meshType)
-{
- // Make sure that the parameters are alwyas sorted by name. We use that to merge two CustomFilterOperations in animations.
- ASSERT(m_parameters.checkAlphabeticalOrder());
-}
-
-CustomFilterOperation::~CustomFilterOperation()
-{
-}
-
-PassRefPtr<FilterOperation> CustomFilterOperation::blend(const FilterOperation* from, double progress, bool blendToPassthrough)
-{
- // FIXME: There's no way to decide what is the "passthrough filter" for shaders using the current CSS Syntax.
- // https://bugs.webkit.org/show_bug.cgi?id=84903
- // https://www.w3.org/Bugs/Public/show_bug.cgi?id=16861
- if (blendToPassthrough || !from || !from->isSameType(*this))
- return this;
-
- const CustomFilterOperation* fromOp = static_cast<const CustomFilterOperation*>(from);
- if (m_program.get() != fromOp->m_program.get()
- || m_meshRows != fromOp->m_meshRows
- || m_meshColumns != fromOp->m_meshColumns
- || m_meshType != fromOp->m_meshType)
- return this;
-
- CustomFilterParameterList animatedParameters;
- m_parameters.blend(fromOp->m_parameters, progress, animatedParameters);
- return CustomFilterOperation::create(m_program, animatedParameters, m_meshRows, m_meshColumns, m_meshType);
-}
-
-} // namespace WebCore
-
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterOperation.h b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterOperation.h
deleted file mode 100644
index 1ef7d709893..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterOperation.h
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * Copyright (C) 2012 Adobe Systems Incorporated. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above
- * copyright notice, this list of conditions and the following
- * disclaimer.
- * 2. Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following
- * disclaimer in the documentation and/or other materials
- * provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
- * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
- * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
- * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#ifndef CustomFilterOperation_h
-#define CustomFilterOperation_h
-
-#include "core/platform/graphics/LayoutSize.h"
-#include "core/platform/graphics/filters/FilterOperation.h"
-#include "core/platform/graphics/filters/custom/CustomFilterConstants.h"
-#include "core/platform/graphics/filters/custom/CustomFilterParameterList.h"
-#include "core/platform/graphics/filters/custom/CustomFilterProgram.h"
-
-namespace WebCore {
-
-// CSS Shaders
-
-class CustomFilterOperation : public FilterOperation {
-public:
- static PassRefPtr<CustomFilterOperation> create(PassRefPtr<CustomFilterProgram> program, const CustomFilterParameterList& sortedParameters, unsigned meshRows, unsigned meshColumns, CustomFilterMeshType meshType)
- {
- return adoptRef(new CustomFilterOperation(program, sortedParameters, meshRows, meshColumns, meshType));
- }
-
- CustomFilterProgram* program() const { return m_program.get(); }
- void setProgram(PassRefPtr<CustomFilterProgram> program) { m_program = program; }
-
- const CustomFilterParameterList& parameters() const { return m_parameters; }
-
- unsigned meshRows() const { return m_meshRows; }
- unsigned meshColumns() const { return m_meshColumns; }
-
- CustomFilterMeshType meshType() const { return m_meshType; }
-
- virtual ~CustomFilterOperation();
-
- virtual bool affectsOpacity() const { return true; }
- virtual bool movesPixels() const { return true; }
-
- virtual PassRefPtr<FilterOperation> blend(const FilterOperation* from, double progress, bool blendToPassthrough = false);
-
-protected:
- CustomFilterOperation(PassRefPtr<CustomFilterProgram>, const CustomFilterParameterList&, unsigned meshRows, unsigned meshColumns, CustomFilterMeshType);
-
-private:
- virtual bool operator==(const FilterOperation& o) const
- {
- if (!isSameType(o))
- return false;
-
- const CustomFilterOperation* other = static_cast<const CustomFilterOperation*>(&o);
- return m_program.get() == other->m_program.get()
- && m_meshRows == other->m_meshRows
- && m_meshColumns == other->m_meshColumns
- && m_meshType == other->m_meshType
- && m_parameters == other->m_parameters;
- }
-
- RefPtr<CustomFilterProgram> m_program;
- CustomFilterParameterList m_parameters;
-
- unsigned m_meshRows;
- unsigned m_meshColumns;
- CustomFilterMeshType m_meshType;
-};
-
-} // namespace WebCore
-
-
-#endif // CustomFilterOperation_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterParameter.h b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterParameter.h
deleted file mode 100644
index dd468f157f3..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterParameter.h
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * Copyright (C) 2012 Adobe Systems Incorporated. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above
- * copyright notice, this list of conditions and the following
- * disclaimer.
- * 2. Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following
- * disclaimer in the documentation and/or other materials
- * provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
- * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
- * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
- * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#ifndef CustomFilterParameter_h
-#define CustomFilterParameter_h
-
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class CustomFilterParameter : public RefCounted<CustomFilterParameter> {
-public:
- // FIXME: Implement other parameters types:
- // booleans: https://bugs.webkit.org/show_bug.cgi?id=76438
- // textures: https://bugs.webkit.org/show_bug.cgi?id=71442
- // 3d-transforms: https://bugs.webkit.org/show_bug.cgi?id=71443
- // mat2, mat3, mat4: https://bugs.webkit.org/show_bug.cgi?id=71444
- enum ParameterType {
- ARRAY,
- NUMBER,
- TRANSFORM
- };
-
- virtual ~CustomFilterParameter() { }
-
- ParameterType parameterType() const { return m_type; }
- const String& name() const { return m_name; }
-
- bool isSameType(const CustomFilterParameter& other) const { return parameterType() == other.parameterType(); }
-
- virtual PassRefPtr<CustomFilterParameter> blend(const CustomFilterParameter*, double progress) = 0;
- virtual bool operator==(const CustomFilterParameter&) const = 0;
- bool operator!=(const CustomFilterParameter& o) const { return !(*this == o); }
-protected:
- CustomFilterParameter(ParameterType type, const String& name)
- : m_name(name)
- , m_type(type)
- {
- }
-
-private:
- String m_name;
- ParameterType m_type;
-};
-
-} // namespace WebCore
-
-
-#endif // CustomFilterParameter_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterParameterList.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterParameterList.cpp
deleted file mode 100644
index bc3e4047e82..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterParameterList.cpp
+++ /dev/null
@@ -1,102 +0,0 @@
-/*
- * Copyright (C) 2012 Adobe Systems Incorporated. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above
- * copyright notice, this list of conditions and the following
- * disclaimer.
- * 2. Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following
- * disclaimer in the documentation and/or other materials
- * provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
- * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
- * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
- * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/platform/graphics/filters/custom/CustomFilterParameterList.h"
-
-#include "core/platform/graphics/filters/custom/CustomFilterParameter.h"
-#include "wtf/text/StringHash.h"
-
-namespace WebCore {
-
-CustomFilterParameterList::CustomFilterParameterList()
-{
-}
-
-CustomFilterParameterList::CustomFilterParameterList(size_t size)
- : CustomFilterParameterListBase(size)
-{
-}
-
-bool CustomFilterParameterList::operator==(const CustomFilterParameterList& other) const
-{
- if (size() != other.size())
- return false;
- for (size_t i = 0; i < size(); ++i) {
- if (at(i).get() != other.at(i).get()
- && *at(i).get() != *other.at(i).get())
- return false;
- }
- return true;
-}
-
-bool CustomFilterParameterList::checkAlphabeticalOrder() const
-{
- for (unsigned i = 1; i < size(); ++i) {
- // Break for equal or not-sorted parameters.
- if (!codePointCompareLessThan(at(i - 1)->name(), at(i)->name()))
- return false;
- }
- return true;
-}
-
-void CustomFilterParameterList::blend(const CustomFilterParameterList& fromList,
- double progress, CustomFilterParameterList& resultList) const
-{
- // This method expects both lists to be sorted by parameter name and the result list is also sorted.
- ASSERT(checkAlphabeticalOrder());
- ASSERT(fromList.checkAlphabeticalOrder());
- size_t fromListIndex = 0, toListIndex = 0;
- while (fromListIndex < fromList.size() && toListIndex < size()) {
- CustomFilterParameter* paramFrom = fromList.at(fromListIndex).get();
- CustomFilterParameter* paramTo = at(toListIndex).get();
- if (paramFrom->name() == paramTo->name()) {
- resultList.append(paramTo->blend(paramFrom, progress));
- ++fromListIndex;
- ++toListIndex;
- continue;
- }
- if (codePointCompareLessThan(paramFrom->name(), paramTo->name())) {
- resultList.append(paramFrom);
- ++fromListIndex;
- continue;
- }
- resultList.append(paramTo);
- ++toListIndex;
- }
- for (; fromListIndex < fromList.size(); ++fromListIndex)
- resultList.append(fromList.at(fromListIndex));
- for (; toListIndex < size(); ++toListIndex)
- resultList.append(at(toListIndex));
- ASSERT(resultList.checkAlphabeticalOrder());
-}
-
-} // namespace WebCore
-
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterParameterList.h b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterParameterList.h
deleted file mode 100644
index f9e72707390..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterParameterList.h
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright (C) 2012 Adobe Systems Incorporated. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above
- * copyright notice, this list of conditions and the following
- * disclaimer.
- * 2. Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following
- * disclaimer in the documentation and/or other materials
- * provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
- * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
- * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
- * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#ifndef CustomFilterParameterList_h
-#define CustomFilterParameterList_h
-
-#include "core/platform/graphics/LayoutSize.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-class CustomFilterParameter;
-typedef Vector<RefPtr<CustomFilterParameter> > CustomFilterParameterListBase;
-
-class CustomFilterParameterList : public CustomFilterParameterListBase {
-public:
- CustomFilterParameterList();
- explicit CustomFilterParameterList(size_t);
-
- bool checkAlphabeticalOrder() const;
- void blend(const CustomFilterParameterList& from, double progress, CustomFilterParameterList& resultList) const;
- bool operator==(const CustomFilterParameterList&) const;
-};
-
-} // namespace WebCore
-
-
-#endif // CustomFilterParameterList_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterProgram.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterProgram.cpp
deleted file mode 100644
index a164b3ef57f..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterProgram.cpp
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * Copyright (C) 2012 Adobe Systems Incorporated. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above
- * copyright notice, this list of conditions and the following
- * disclaimer.
- * 2. Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following
- * disclaimer in the documentation and/or other materials
- * provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
- * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
- * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
- * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/platform/graphics/filters/custom/CustomFilterProgram.h"
-
-#include "core/platform/graphics/filters/custom/CustomFilterProgramClient.h"
-#include "core/platform/graphics/filters/custom/CustomFilterProgramInfo.h"
-
-namespace WebCore {
-
-CustomFilterProgram::CustomFilterProgram(CustomFilterProgramType programType, const CustomFilterProgramMixSettings& mixSettings, CustomFilterMeshType meshType)
- : m_programType(programType)
- , m_mixSettings(mixSettings)
- , m_meshType(meshType)
-{
- // Keep the constructor protected to prevent creating this object directly.
-}
-
-CustomFilterProgram::~CustomFilterProgram()
-{
- // All the clients should keep a reference to this object.
- ASSERT(m_clients.isEmpty());
-}
-
-void CustomFilterProgram::addClient(CustomFilterProgramClient* client)
-{
- if (m_clients.isEmpty()) {
- // Notify the StyleCustomFilterProgram that we now have at least a client
- // and the loading can begin.
- // Note: If the shader is already cached the first client will be notified,
- // even if the filter was already built. Add the client only after notifying
- // the cache about them, so that we avoid a useless recreation of the filters chain.
- willHaveClients();
- }
- m_clients.add(client);
-}
-
-void CustomFilterProgram::removeClient(CustomFilterProgramClient* client)
-{
- m_clients.remove(client);
- if (m_clients.isEmpty()) {
- // We have no clients anymore, the cached resources can be purged from memory.
- didRemoveLastClient();
- }
-}
-
-void CustomFilterProgram::notifyClients()
-{
- for (CustomFilterProgramClientList::iterator iter = m_clients.begin(), end = m_clients.end(); iter != end; ++iter)
- iter->key->notifyCustomFilterProgramLoaded(this);
-}
-
-CustomFilterProgramInfo CustomFilterProgram::programInfo() const
-{
- ASSERT(isLoaded());
- return CustomFilterProgramInfo(vertexShaderString(), fragmentShaderString(), m_programType, m_mixSettings, m_meshType);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterProgram.h b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterProgram.h
deleted file mode 100644
index e8b62b24052..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterProgram.h
+++ /dev/null
@@ -1,92 +0,0 @@
-/*
- * Copyright (C) 2012 Adobe Systems Incorporated. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above
- * copyright notice, this list of conditions and the following
- * disclaimer.
- * 2. Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following
- * disclaimer in the documentation and/or other materials
- * provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
- * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
- * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
- * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#ifndef CustomFilterProgram_h
-#define CustomFilterProgram_h
-
-#include "core/platform/graphics/filters/custom/CustomFilterProgramInfo.h"
-
-#include "wtf/HashCountedSet.h"
-#include "wtf/RefCounted.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class GraphicsContext3D;
-class CustomFilterCompiledProgram;
-class CustomFilterProgramClient;
-
-// This is the base class for the StyleCustomFilterProgram class which knows how to keep
-// references to the cached shaders.
-class CustomFilterProgram: public RefCounted<CustomFilterProgram> {
-public:
- virtual ~CustomFilterProgram();
-
- virtual bool isLoaded() const = 0;
-
- void addClient(CustomFilterProgramClient*);
- void removeClient(CustomFilterProgramClient*);
-
- CustomFilterProgramInfo programInfo() const;
-
- virtual String vertexShaderString() const = 0;
- virtual String fragmentShaderString() const = 0;
- CustomFilterProgramType programType() const { return m_programType; }
- CustomFilterProgramMixSettings mixSettings() const { return m_mixSettings; }
- CustomFilterMeshType meshType() const { return m_meshType; }
-
-protected:
- // StyleCustomFilterProgram can notify the clients that the cached resources are
- // loaded and it is ready to create CustomFilterCompiledProgram objects.
- void notifyClients();
-
- virtual void willHaveClients() = 0;
- virtual void didRemoveLastClient() = 0;
-
- // Keep the constructor protected to prevent creating this object directly.
- CustomFilterProgram(CustomFilterProgramType, const CustomFilterProgramMixSettings&, CustomFilterMeshType);
-
-private:
- // CustomFilterPrograms are unique combinations of shaders and can be
- // compared using just the pointer value instead.
- // These will catch anyone doing a value equal comparison.
- bool operator==(const CustomFilterProgram&) const;
- bool operator!=(const CustomFilterProgram&) const;
-
- typedef HashCountedSet<CustomFilterProgramClient*> CustomFilterProgramClientList;
- CustomFilterProgramClientList m_clients;
- CustomFilterProgramType m_programType;
- CustomFilterProgramMixSettings m_mixSettings;
- CustomFilterMeshType m_meshType;
-};
-
-}
-
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterProgramClient.h b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterProgramClient.h
deleted file mode 100644
index cc97bfe1a9f..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterProgramClient.h
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright (C) 2012 Adobe Systems Incorporated. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above
- * copyright notice, this list of conditions and the following
- * disclaimer.
- * 2. Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following
- * disclaimer in the documentation and/or other materials
- * provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
- * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
- * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
- * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#ifndef CustomFilterProgramClient_h
-#define CustomFilterProgramClient_h
-
-namespace WebCore {
-
-class CustomFilterProgram;
-
-class CustomFilterProgramClient {
-public:
- virtual ~CustomFilterProgramClient()
- {
- }
-
- virtual void notifyCustomFilterProgramLoaded(CustomFilterProgram*) = 0;
-};
-
-}
-
-
-#endif // CustomFilterProgramClient_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterProgramInfo.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterProgramInfo.cpp
deleted file mode 100644
index b2578e73841..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterProgramInfo.cpp
+++ /dev/null
@@ -1,107 +0,0 @@
-/*
- * Copyright (C) 2012 Adobe Systems Incorporated. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above
- * copyright notice, this list of conditions and the following
- * disclaimer.
- * 2. Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following
- * disclaimer in the documentation and/or other materials
- * provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
- * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
- * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
- * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/platform/graphics/filters/custom/CustomFilterProgramInfo.h"
-
-#include "wtf/HashFunctions.h"
-#include "wtf/text/StringHash.h"
-
-namespace WebCore {
-
-static unsigned hashPossiblyNullString(const String& string)
-{
- return string.isNull() ? 0 : DefaultHash<String>::Hash::hash(string);
-}
-
-CustomFilterProgramInfo::CustomFilterProgramInfo()
-{
-}
-
-bool CustomFilterProgramInfo::isEmptyValue() const
-{
- return m_vertexShaderString.isNull()
- && m_fragmentShaderString.isNull();
-}
-
-CustomFilterProgramInfo::CustomFilterProgramInfo(WTF::HashTableDeletedValueType)
- : m_vertexShaderString(WTF::HashTableDeletedValue)
- , m_fragmentShaderString(WTF::HashTableDeletedValue)
-{
-}
-
-bool CustomFilterProgramInfo::isHashTableDeletedValue() const
-{
- return m_vertexShaderString.isHashTableDeletedValue()
- && m_fragmentShaderString.isHashTableDeletedValue();
-}
-
-CustomFilterProgramInfo::CustomFilterProgramInfo(const String& vertexShader, const String& fragmentShader, CustomFilterProgramType programType, const CustomFilterProgramMixSettings& mixSettings, CustomFilterMeshType meshType)
- : m_vertexShaderString(vertexShader)
- , m_fragmentShaderString(fragmentShader)
- , m_programType(programType)
- , m_mixSettings(mixSettings)
- , m_meshType(meshType)
-{
- // At least one of the shaders needs to be non-null.
- ASSERT(!m_vertexShaderString.isNull() || !m_fragmentShaderString.isNull());
-}
-
-unsigned CustomFilterProgramInfo::hash() const
-{
- // At least one of the shaders needs to be non-null.
- ASSERT(!m_vertexShaderString.isNull() || !m_fragmentShaderString.isNull());
-
- bool blendsElementTexture = (m_programType == PROGRAM_TYPE_BLENDS_ELEMENT_TEXTURE);
- uintptr_t hashCodes[6] = {
- hashPossiblyNullString(m_vertexShaderString),
- hashPossiblyNullString(m_fragmentShaderString),
- blendsElementTexture,
- static_cast<uintptr_t>(blendsElementTexture ? m_mixSettings.blendMode : 0),
- static_cast<uintptr_t>(blendsElementTexture ? m_mixSettings.compositeOperator : 0),
- m_meshType
- };
- return StringHasher::hashMemory<sizeof(hashCodes)>(&hashCodes);
-}
-
-bool CustomFilterProgramInfo::operator==(const CustomFilterProgramInfo& o) const
-{
- ASSERT(!isHashTableDeletedValue());
- ASSERT(!o.isHashTableDeletedValue());
-
- return m_programType == o.m_programType
- && (m_programType != PROGRAM_TYPE_BLENDS_ELEMENT_TEXTURE || m_mixSettings == o.m_mixSettings)
- && m_meshType == o.m_meshType
- && m_vertexShaderString == o.m_vertexShaderString
- && m_fragmentShaderString == o.m_fragmentShaderString;
-}
-
-} // namespace WebCore
-
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterProgramInfo.h b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterProgramInfo.h
deleted file mode 100644
index 60f34c8a060..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterProgramInfo.h
+++ /dev/null
@@ -1,110 +0,0 @@
-/*
- * Copyright (C) 2012 Adobe Systems Incorporated. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above
- * copyright notice, this list of conditions and the following
- * disclaimer.
- * 2. Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following
- * disclaimer in the documentation and/or other materials
- * provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
- * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
- * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
- * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#ifndef CustomFilterProgramInfo_h
-#define CustomFilterProgramInfo_h
-
-#include "core/platform/graphics/GraphicsTypes.h"
-#include "core/platform/graphics/filters/custom/CustomFilterConstants.h"
-
-#include "wtf/HashTableDeletedValueType.h"
-#include "wtf/HashTraits.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-
-struct CustomFilterProgramMixSettings {
- CustomFilterProgramMixSettings()
- : blendMode(BlendModeNormal)
- , compositeOperator(CompositeSourceAtop)
- {
- }
-
- bool operator==(const CustomFilterProgramMixSettings& o) const
- {
- return blendMode == o.blendMode && compositeOperator == o.compositeOperator;
- }
-
- BlendMode blendMode;
- CompositeOperator compositeOperator;
-};
-
-// CustomFilterProgramInfo is the key used to link CustomFilterProgram with CustomFilterCompiledProgram.
-// It can be used as a key in a HashMap, with the note that at least one of Strings needs to be non-null.
-// Null strings are placeholders for the default shader.
-class CustomFilterProgramInfo {
-public:
- CustomFilterProgramInfo(const String&, const String&, CustomFilterProgramType, const CustomFilterProgramMixSettings&, CustomFilterMeshType);
-
- CustomFilterProgramInfo();
- bool isEmptyValue() const;
-
- CustomFilterProgramInfo(WTF::HashTableDeletedValueType);
- bool isHashTableDeletedValue() const;
-
- unsigned hash() const;
- bool operator==(const CustomFilterProgramInfo&) const;
-
- const String& vertexShaderString() const { return m_vertexShaderString; }
- const String& fragmentShaderString() const { return m_fragmentShaderString; }
- CustomFilterProgramType programType() const { return m_programType; }
- const CustomFilterProgramMixSettings& mixSettings() const { return m_mixSettings; }
- CustomFilterMeshType meshType() const { return m_meshType; }
-private:
- String m_vertexShaderString;
- String m_fragmentShaderString;
- CustomFilterProgramType m_programType;
- CustomFilterProgramMixSettings m_mixSettings;
- CustomFilterMeshType m_meshType;
-};
-
-struct CustomFilterProgramInfoHash {
- static unsigned hash(const CustomFilterProgramInfo& programInfo) { return programInfo.hash(); }
- static bool equal(const CustomFilterProgramInfo& a, const CustomFilterProgramInfo& b) { return a == b; }
- static const bool safeToCompareToEmptyOrDeleted = false;
-};
-
-struct CustomFilterProgramInfoHashTraits : WTF::SimpleClassHashTraits<CustomFilterProgramInfo> {
- static const bool hasIsEmptyValueFunction = true;
- static bool isEmptyValue(const CustomFilterProgramInfo& info) { return info.isEmptyValue(); }
-};
-
-} // namespace WebCore
-
-namespace WTF {
-
-template<> struct HashTraits<WebCore::CustomFilterProgramInfo> : WebCore::CustomFilterProgramInfoHashTraits { };
-template<> struct DefaultHash<WebCore::CustomFilterProgramInfo> {
- typedef WebCore::CustomFilterProgramInfoHash Hash;
-};
-
-}
-
-#endif // CustomFilterProgramInfo_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterRenderer.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterRenderer.cpp
deleted file mode 100644
index 108822594e3..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterRenderer.cpp
+++ /dev/null
@@ -1,294 +0,0 @@
-/*
- * Copyright (C) 2012 Adobe Systems Incorporated. All rights reserved.
- * Copyright (C) 2011 Adobe Systems Incorporated. All rights reserved.
- * Copyright (C) 2012 Company 100, Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above
- * copyright notice, this list of conditions and the following
- * disclaimer.
- * 2. Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following
- * disclaimer in the documentation and/or other materials
- * provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
- * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
- * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
- * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/platform/graphics/filters/custom/CustomFilterRenderer.h"
-
-#include "core/platform/graphics/GraphicsContext3D.h"
-#include "core/platform/graphics/filters/custom/CustomFilterArrayParameter.h"
-#include "core/platform/graphics/filters/custom/CustomFilterCompiledProgram.h"
-#include "core/platform/graphics/filters/custom/CustomFilterConstants.h"
-#include "core/platform/graphics/filters/custom/CustomFilterMesh.h"
-#include "core/platform/graphics/filters/custom/CustomFilterNumberParameter.h"
-#include "core/platform/graphics/filters/custom/CustomFilterParameter.h"
-#include "core/platform/graphics/filters/custom/CustomFilterTransformParameter.h"
-#include "core/platform/graphics/transforms/TransformationMatrix.h"
-
-namespace WebCore {
-
-static void orthogonalProjectionMatrix(TransformationMatrix& matrix, float left, float right, float bottom, float top)
-{
- ASSERT(matrix.isIdentity());
-
- float deltaX = right - left;
- float deltaY = top - bottom;
- if (!deltaX || !deltaY)
- return;
- matrix.setM11(2.0f / deltaX);
- matrix.setM41(-(right + left) / deltaX);
- matrix.setM22(2.0f / deltaY);
- matrix.setM42(-(top + bottom) / deltaY);
-
- // Use big enough near/far values, so that simple rotations of rather large objects will not
- // get clipped. 10000 should cover most of the screen resolutions.
- const float farValue = 10000;
- const float nearValue = -10000;
- matrix.setM33(-2.0f / (farValue - nearValue));
- matrix.setM43(- (farValue + nearValue) / (farValue - nearValue));
- matrix.setM44(1.0f);
-}
-
-PassRefPtr<CustomFilterRenderer> CustomFilterRenderer::create(PassRefPtr<GraphicsContext3D> context, CustomFilterProgramType programType, const CustomFilterParameterList& parameters,
- unsigned meshRows, unsigned meshColumns, CustomFilterMeshType meshType)
-{
- return adoptRef(new CustomFilterRenderer(context, programType, parameters, meshRows, meshColumns, meshType));
-}
-
-CustomFilterRenderer::CustomFilterRenderer(PassRefPtr<GraphicsContext3D> context, CustomFilterProgramType programType, const CustomFilterParameterList& parameters,
- unsigned meshRows, unsigned meshColumns, CustomFilterMeshType meshType)
- : m_context(context)
- , m_programType(programType)
- , m_parameters(parameters)
- , m_meshRows(meshRows)
- , m_meshColumns(meshColumns)
- , m_meshType(meshType)
-{
-}
-
-CustomFilterRenderer::~CustomFilterRenderer()
-{
-}
-
-bool CustomFilterRenderer::premultipliedAlpha() const
-{
- return m_programType == PROGRAM_TYPE_BLENDS_ELEMENT_TEXTURE;
-}
-
-bool CustomFilterRenderer::programNeedsInputTexture() const
-{
- ASSERT(m_compiledProgram.get());
- return m_compiledProgram->samplerLocation() != -1;
-}
-
-void CustomFilterRenderer::draw(Platform3DObject inputTexture, const IntSize& size)
-{
- // FIXME: We would need something like CustomFilterRendererState that will contain the size and other parameters in the future. We should pass that to bindProgramBuffers instead of storing it.
- // https://bugs.webkit.org/show_bug.cgi?id=100107
- m_contextSize = size;
-
- bindProgramAndBuffers(inputTexture);
- m_context->drawElements(GraphicsContext3D::TRIANGLES, m_mesh->indicesCount(), GraphicsContext3D::UNSIGNED_SHORT, 0);
- unbindVertexAttributes();
-}
-
-void CustomFilterRenderer::setCompiledProgram(PassRefPtr<CustomFilterCompiledProgram> compiledProgram)
-{
- m_compiledProgram = compiledProgram;
-}
-
-bool CustomFilterRenderer::prepareForDrawing()
-{
- m_context->makeContextCurrent();
- if (!m_compiledProgram || !m_compiledProgram->isInitialized())
- return false;
- initializeMeshIfNeeded();
- return true;
-}
-
-void CustomFilterRenderer::initializeMeshIfNeeded()
-{
- if (m_mesh.get())
- return;
-
- // FIXME: Sharing the mesh would just save the time needed to upload it to the GPU, so I assume we could
- // benchmark that for performance.
- // https://bugs.webkit.org/show_bug.cgi?id=88429
- m_mesh = CustomFilterMesh::create(m_context.get(), m_meshColumns, m_meshRows, FloatRect(0, 0, 1, 1), m_meshType);
-}
-
-void CustomFilterRenderer::bindVertexAttribute(int attributeLocation, unsigned size, unsigned offset)
-{
- if (attributeLocation != -1) {
- m_context->vertexAttribPointer(attributeLocation, size, GraphicsContext3D::FLOAT, false, m_mesh->bytesPerVertex(), offset);
- m_context->enableVertexAttribArray(attributeLocation);
- }
-}
-
-void CustomFilterRenderer::unbindVertexAttribute(int attributeLocation)
-{
- if (attributeLocation != -1)
- m_context->disableVertexAttribArray(attributeLocation);
-}
-
-void CustomFilterRenderer::bindProgramArrayParameters(int uniformLocation, CustomFilterArrayParameter* arrayParameter)
-{
- unsigned parameterSize = arrayParameter->size();
- Vector<GC3Dfloat> floatVector;
-
- for (unsigned i = 0; i < parameterSize; ++i)
- floatVector.append(arrayParameter->valueAt(i));
-
- m_context->uniform1fv(uniformLocation, parameterSize, floatVector.data());
-}
-
-void CustomFilterRenderer::bindProgramNumberParameters(int uniformLocation, CustomFilterNumberParameter* numberParameter)
-{
- switch (numberParameter->size()) {
- case 1:
- m_context->uniform1f(uniformLocation, numberParameter->valueAt(0));
- break;
- case 2:
- m_context->uniform2f(uniformLocation, numberParameter->valueAt(0), numberParameter->valueAt(1));
- break;
- case 3:
- m_context->uniform3f(uniformLocation, numberParameter->valueAt(0), numberParameter->valueAt(1), numberParameter->valueAt(2));
- break;
- case 4:
- m_context->uniform4f(uniformLocation, numberParameter->valueAt(0), numberParameter->valueAt(1), numberParameter->valueAt(2), numberParameter->valueAt(3));
- break;
- default:
- ASSERT_NOT_REACHED();
- }
-}
-
-void CustomFilterRenderer::bindProgramTransformParameter(int uniformLocation, CustomFilterTransformParameter* transformParameter)
-{
- TransformationMatrix matrix;
- if (m_contextSize.width() && m_contextSize.height()) {
- // The viewport is a box with the size of 1 unit, so we are scaling up here to make sure that translations happen using real pixel
- // units. At the end we scale back down in order to map it back to the original box. Note that transforms come in reverse order, because it is
- // supposed to multiply to the left of the coordinates of the vertices.
- // Note that the origin (0, 0) of the viewport is in the middle of the context, so there's no need to change the origin of the transform
- // in order to rotate around the middle of mesh.
- matrix.scale3d(1.0 / m_contextSize.width(), 1.0 / m_contextSize.height(), 1);
- transformParameter->applyTransform(matrix, m_contextSize);
- matrix.scale3d(m_contextSize.width(), m_contextSize.height(), 1);
- }
- float glMatrix[16];
- matrix.toColumnMajorFloatArray(glMatrix);
- m_context->uniformMatrix4fv(uniformLocation, 1, false, &glMatrix[0]);
-}
-
-void CustomFilterRenderer::bindProgramParameters()
-{
- // FIXME: Find a way to reset uniforms that are not specified in CSS. This is needed to avoid using values
- // set by other previous rendered filters.
- // https://bugs.webkit.org/show_bug.cgi?id=76440
-
- size_t parametersSize = m_parameters.size();
- for (size_t i = 0; i < parametersSize; ++i) {
- CustomFilterParameter* parameter = m_parameters.at(i).get();
- int uniformLocation = m_compiledProgram->uniformLocationByName(parameter->name());
- if (uniformLocation == -1)
- continue;
- switch (parameter->parameterType()) {
- case CustomFilterParameter::ARRAY:
- bindProgramArrayParameters(uniformLocation, static_cast<CustomFilterArrayParameter*>(parameter));
- break;
- case CustomFilterParameter::NUMBER:
- bindProgramNumberParameters(uniformLocation, static_cast<CustomFilterNumberParameter*>(parameter));
- break;
- case CustomFilterParameter::TRANSFORM:
- bindProgramTransformParameter(uniformLocation, static_cast<CustomFilterTransformParameter*>(parameter));
- break;
- }
- }
-}
-
-void CustomFilterRenderer::bindProgramAndBuffers(Platform3DObject inputTexture)
-{
- ASSERT(m_compiledProgram->isInitialized());
-
- m_context->useProgram(m_compiledProgram->program());
-
- if (programNeedsInputTexture()) {
- // We should be binding the DOM element texture sampler only if the author is using the CSS mix function.
- ASSERT(m_programType == PROGRAM_TYPE_BLENDS_ELEMENT_TEXTURE);
- ASSERT(m_compiledProgram->samplerLocation() != -1);
-
- m_context->activeTexture(GraphicsContext3D::TEXTURE0);
- m_context->uniform1i(m_compiledProgram->samplerLocation(), 0);
- m_context->bindTexture(GraphicsContext3D::TEXTURE_2D, inputTexture);
- m_context->texParameteri(GraphicsContext3D::TEXTURE_2D, GraphicsContext3D::TEXTURE_MIN_FILTER, GraphicsContext3D::LINEAR);
- m_context->texParameteri(GraphicsContext3D::TEXTURE_2D, GraphicsContext3D::TEXTURE_MAG_FILTER, GraphicsContext3D::LINEAR);
- m_context->texParameteri(GraphicsContext3D::TEXTURE_2D, GraphicsContext3D::TEXTURE_WRAP_S, GraphicsContext3D::CLAMP_TO_EDGE);
- m_context->texParameteri(GraphicsContext3D::TEXTURE_2D, GraphicsContext3D::TEXTURE_WRAP_T, GraphicsContext3D::CLAMP_TO_EDGE);
- }
-
- if (m_compiledProgram->projectionMatrixLocation() != -1) {
- TransformationMatrix projectionMatrix;
- orthogonalProjectionMatrix(projectionMatrix, -0.5, 0.5, -0.5, 0.5);
- float glProjectionMatrix[16];
- projectionMatrix.toColumnMajorFloatArray(glProjectionMatrix);
- m_context->uniformMatrix4fv(m_compiledProgram->projectionMatrixLocation(), 1, false, &glProjectionMatrix[0]);
- }
-
- ASSERT(m_meshColumns);
- ASSERT(m_meshRows);
-
- if (m_compiledProgram->meshSizeLocation() != -1)
- m_context->uniform2f(m_compiledProgram->meshSizeLocation(), m_meshColumns, m_meshRows);
-
- if (m_compiledProgram->tileSizeLocation() != -1)
- m_context->uniform2f(m_compiledProgram->tileSizeLocation(), 1.0 / m_meshColumns, 1.0 / m_meshRows);
-
- if (m_compiledProgram->meshBoxLocation() != -1) {
- // FIXME: This will change when filter margins will be implemented,
- // see https://bugs.webkit.org/show_bug.cgi?id=71400
- m_context->uniform4f(m_compiledProgram->meshBoxLocation(), -0.5, -0.5, 1.0, 1.0);
- }
-
- if (m_compiledProgram->samplerSizeLocation() != -1)
- m_context->uniform2f(m_compiledProgram->samplerSizeLocation(), m_contextSize.width(), m_contextSize.height());
-
- m_context->bindBuffer(GraphicsContext3D::ARRAY_BUFFER, m_mesh->verticesBufferObject());
- m_context->bindBuffer(GraphicsContext3D::ELEMENT_ARRAY_BUFFER, m_mesh->elementsBufferObject());
-
- bindVertexAttribute(m_compiledProgram->positionAttribLocation(), PositionAttribSize, PositionAttribOffset);
- bindVertexAttribute(m_compiledProgram->texAttribLocation(), TexAttribSize, TexAttribOffset);
- bindVertexAttribute(m_compiledProgram->meshAttribLocation(), MeshAttribSize, MeshAttribOffset);
- if (m_meshType == MeshTypeDetached)
- bindVertexAttribute(m_compiledProgram->triangleAttribLocation(), TriangleAttribSize, TriangleAttribOffset);
-
- bindProgramParameters();
-}
-
-void CustomFilterRenderer::unbindVertexAttributes()
-{
- unbindVertexAttribute(m_compiledProgram->positionAttribLocation());
- unbindVertexAttribute(m_compiledProgram->texAttribLocation());
- unbindVertexAttribute(m_compiledProgram->meshAttribLocation());
- if (m_meshType == MeshTypeDetached)
- unbindVertexAttribute(m_compiledProgram->triangleAttribLocation());
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterRenderer.h b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterRenderer.h
deleted file mode 100644
index eeb6808c05b..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterRenderer.h
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
- * Copyright (C) 2012 Adobe Systems Incorporated. All rights reserved.
- * Copyright (C) 2011 Adobe Systems Incorporated. All rights reserved.
- * Copyright (C) 2012 Company 100, Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above
- * copyright notice, this list of conditions and the following
- * disclaimer.
- * 2. Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following
- * disclaimer in the documentation and/or other materials
- * provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
- * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
- * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
- * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#ifndef CustomFilterRenderer_h
-#define CustomFilterRenderer_h
-
-#include "core/platform/graphics/GraphicsTypes3D.h"
-#include "core/platform/graphics/IntSize.h"
-#include "core/platform/graphics/filters/custom/CustomFilterConstants.h"
-#include "core/platform/graphics/filters/custom/CustomFilterParameterList.h"
-#include "wtf/RefCounted.h"
-#include "wtf/RefPtr.h"
-
-namespace WebCore {
-
-class CustomFilterArrayParameter;
-class CustomFilterCompiledProgram;
-class CustomFilterMesh;
-class CustomFilterNumberParameter;
-class CustomFilterTransformParameter;
-class GraphicsContext3D;
-
-class CustomFilterRenderer : public RefCounted<CustomFilterRenderer> {
-public:
- static PassRefPtr<CustomFilterRenderer> create(PassRefPtr<GraphicsContext3D>, CustomFilterProgramType, const CustomFilterParameterList&,
- unsigned meshRows, unsigned meshColumns, CustomFilterMeshType);
- ~CustomFilterRenderer();
-
- bool premultipliedAlpha() const;
- bool programNeedsInputTexture() const;
-
- bool prepareForDrawing();
-
- void draw(Platform3DObject, const IntSize&);
-
- CustomFilterCompiledProgram* compiledProgram() const { return m_compiledProgram.get(); }
- void setCompiledProgram(PassRefPtr<CustomFilterCompiledProgram>);
-
-private:
- CustomFilterRenderer(PassRefPtr<GraphicsContext3D>, CustomFilterProgramType, const CustomFilterParameterList&,
- unsigned meshRows, unsigned meshColumns, CustomFilterMeshType);
-
- void initializeCompiledProgramIfNeeded();
- void initializeMeshIfNeeded();
-
- void bindVertexAttribute(int attributeLocation, unsigned size, unsigned offset);
- void unbindVertexAttribute(int attributeLocation);
- void bindProgramArrayParameters(int uniformLocation, CustomFilterArrayParameter*);
- void bindProgramNumberParameters(int uniformLocation, CustomFilterNumberParameter*);
- void bindProgramTransformParameter(int uniformLocation, CustomFilterTransformParameter*);
- void bindProgramParameters();
- void bindProgramAndBuffers(Platform3DObject inputTexture);
- void unbindVertexAttributes();
-
- RefPtr<GraphicsContext3D> m_context;
- RefPtr<CustomFilterCompiledProgram> m_compiledProgram;
- CustomFilterProgramType m_programType;
- RefPtr<CustomFilterMesh> m_mesh;
- IntSize m_contextSize;
-
- CustomFilterParameterList m_parameters;
-
- unsigned m_meshRows;
- unsigned m_meshColumns;
- CustomFilterMeshType m_meshType;
-};
-
-} // namespace WebCore
-
-#endif // CustomFilterRenderer_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterTransformParameter.h b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterTransformParameter.h
deleted file mode 100644
index 71abf756666..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterTransformParameter.h
+++ /dev/null
@@ -1,100 +0,0 @@
-/*
- * Copyright (C) 2012 Adobe Systems Incorporated. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above
- * copyright notice, this list of conditions and the following
- * disclaimer.
- * 2. Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following
- * disclaimer in the documentation and/or other materials
- * provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
- * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
- * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
- * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#ifndef CustomFilterTransformParameter_h
-#define CustomFilterTransformParameter_h
-
-#include "core/platform/graphics/FloatSize.h"
-#include "core/platform/graphics/filters/custom/CustomFilterParameter.h"
-#include "core/platform/graphics/transforms/TransformOperations.h"
-
-namespace WebCore {
-
-class FloatRect;
-class TransformationMatrix;
-
-class CustomFilterTransformParameter : public CustomFilterParameter {
-public:
- static PassRefPtr<CustomFilterTransformParameter> create(const String& name)
- {
- return adoptRef(new CustomFilterTransformParameter(name));
- }
-
- virtual PassRefPtr<CustomFilterParameter> blend(const CustomFilterParameter* fromParameter, double progress)
- {
- if (!fromParameter || !isSameType(*fromParameter))
- return this;
-
- const CustomFilterTransformParameter* fromTransformParameter = static_cast<const CustomFilterTransformParameter*>(fromParameter);
- const TransformOperations& from = fromTransformParameter->operations();
- const TransformOperations& to = operations();
- if (from == to)
- return this;
-
- RefPtr<CustomFilterTransformParameter> result = CustomFilterTransformParameter::create(name());
- if (from.size() && to.size())
- result->setOperations(to.blend(from, progress));
- else
- result->setOperations(progress > 0.5 ? to : from);
- return result;
- }
-
- virtual bool operator==(const CustomFilterParameter& o) const
- {
- if (!isSameType(o))
- return false;
- const CustomFilterTransformParameter* other = static_cast<const CustomFilterTransformParameter*>(&o);
- return m_operations == other->m_operations;
- }
-
- void applyTransform(TransformationMatrix& transform, const FloatSize& boxSize) const
- {
- for (unsigned i = 0, size = m_operations.size(); i < size; ++i)
- m_operations.at(i)->apply(transform, boxSize);
- }
-
- const TransformOperations& operations() const { return m_operations; }
- void setOperations(const TransformOperations& value) { m_operations = value; }
-
-private:
- CustomFilterTransformParameter(const String& name)
- : CustomFilterParameter(TRANSFORM, name)
- {
- }
- virtual ~CustomFilterTransformParameter()
- {
- }
-
- TransformOperations m_operations;
-};
-
-} // namespace WebCore
-
-
-#endif // CustomFilterTransformParameter_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterValidatedProgram.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterValidatedProgram.cpp
deleted file mode 100644
index 35aa68e770e..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterValidatedProgram.cpp
+++ /dev/null
@@ -1,618 +0,0 @@
-/*
- * Copyright (C) 2012 Adobe Systems Incorporated. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above
- * copyright notice, this list of conditions and the following
- * disclaimer.
- * 2. Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following
- * disclaimer in the documentation and/or other materials
- * provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
- * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
- * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
- * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/platform/graphics/filters/custom/CustomFilterValidatedProgram.h"
-
-#include "core/platform/NotImplemented.h"
-#include "core/platform/graphics/ANGLEWebKitBridge.h"
-#include "core/platform/graphics/filters/custom/CustomFilterConstants.h"
-#include "core/platform/graphics/filters/custom/CustomFilterGlobalContext.h"
-#include "core/platform/graphics/filters/custom/CustomFilterProgramInfo.h"
-#include "wtf/HashMap.h"
-#include "wtf/text/StringBuilder.h"
-#include "wtf/text/StringHash.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-#define SHADER(Src) (#Src)
-
-typedef HashMap<String, ShDataType> SymbolNameToTypeMap;
-
-static SymbolNameToTypeMap* builtInAttributeNameToTypeMap()
-{
- static SymbolNameToTypeMap* nameToTypeMap = 0;
- if (!nameToTypeMap) {
- nameToTypeMap = new SymbolNameToTypeMap;
- nameToTypeMap->set("a_meshCoord", SH_FLOAT_VEC2);
- nameToTypeMap->set("a_position", SH_FLOAT_VEC4);
- nameToTypeMap->set("a_texCoord", SH_FLOAT_VEC2);
- nameToTypeMap->set("a_triangleCoord", SH_FLOAT_VEC3);
- }
- return nameToTypeMap;
-}
-
-static SymbolNameToTypeMap* builtInUniformNameToTypeMap()
-{
- static SymbolNameToTypeMap* nameToTypeMap = 0;
- if (!nameToTypeMap) {
- nameToTypeMap = new SymbolNameToTypeMap;
- nameToTypeMap->set("u_meshBox", SH_FLOAT_VEC4);
- nameToTypeMap->set("u_meshSize", SH_FLOAT_VEC2);
- nameToTypeMap->set("u_projectionMatrix", SH_FLOAT_MAT4);
- nameToTypeMap->set("u_textureSize", SH_FLOAT_VEC2);
- nameToTypeMap->set("u_tileSize", SH_FLOAT_VEC2);
- }
- return nameToTypeMap;
-}
-
-static bool validateSymbols(const Vector<ANGLEShaderSymbol>& symbols, CustomFilterMeshType meshType)
-{
- for (size_t i = 0; i < symbols.size(); ++i) {
- const ANGLEShaderSymbol& symbol = symbols[i];
- switch (symbol.symbolType) {
- case SHADER_SYMBOL_TYPE_ATTRIBUTE: {
- SymbolNameToTypeMap* attributeNameToTypeMap = builtInAttributeNameToTypeMap();
- SymbolNameToTypeMap::iterator builtInAttribute = attributeNameToTypeMap->find(symbol.name);
- if (builtInAttribute == attributeNameToTypeMap->end()) {
- // The author defined a custom attribute.
- // FIXME: Report the validation error.
- // https://bugs.webkit.org/show_bug.cgi?id=74416
- return false;
- }
- if (meshType == MeshTypeAttached && symbol.name == "a_triangleCoord") {
- // a_triangleCoord is only available for detached meshes.
- // FIXME: Report the validation error.
- // https://bugs.webkit.org/show_bug.cgi?id=74416
- return false;
- }
- if (symbol.dataType != builtInAttribute->value) {
- // The author defined one of the built-in attributes with the wrong type.
- // FIXME: Report the validation error.
- // https://bugs.webkit.org/show_bug.cgi?id=74416
- return false;
- }
- break;
- }
- case SHADER_SYMBOL_TYPE_UNIFORM: {
- if (symbol.isSampler()) {
- // FIXME: For now, we restrict shaders with any sampler defined.
- // When we implement texture parameters, we will allow shaders whose samplers are bound to valid textures.
- // We must not allow OpenGL to give unbound samplers a default value of 0 because that references the element texture,
- // which should be inaccessible to the author's shader code.
- // https://bugs.webkit.org/show_bug.cgi?id=96230
- return false;
- }
-
- SymbolNameToTypeMap* uniformNameToTypeMap = builtInUniformNameToTypeMap();
- SymbolNameToTypeMap::iterator builtInUniform = uniformNameToTypeMap->find(symbol.name);
- if (builtInUniform != uniformNameToTypeMap->end() && (symbol.isArray || symbol.dataType != builtInUniform->value)) {
- // The author defined one of the built-in uniforms with the wrong type.
- // FIXME: Report the validation error.
- // https://bugs.webkit.org/show_bug.cgi?id=74416
- return false;
- }
- break;
- }
- default:
- ASSERT_NOT_REACHED();
- break;
- }
- }
-
- return true;
-}
-
-String CustomFilterValidatedProgram::defaultVertexShaderString()
-{
- DEFINE_STATIC_LOCAL(String, vertexShaderString, (SHADER(
- attribute mediump vec4 a_position;
- uniform mediump mat4 u_projectionMatrix;
-
- void main()
- {
- gl_Position = u_projectionMatrix * a_position;
- }
- )));
- return vertexShaderString;
-}
-
-String CustomFilterValidatedProgram::defaultFragmentShaderString()
-{
- DEFINE_STATIC_LOCAL(String, fragmentShaderString, (SHADER(
- void main()
- {
- }
- )));
- return fragmentShaderString;
-}
-
-CustomFilterValidatedProgram::CustomFilterValidatedProgram(CustomFilterGlobalContext* globalContext, const CustomFilterProgramInfo& programInfo)
- : m_globalContext(globalContext)
- , m_programInfo(programInfo)
- , m_isInitialized(false)
-{
- platformInit();
-
- String originalVertexShader = programInfo.vertexShaderString();
- if (originalVertexShader.isNull())
- originalVertexShader = defaultVertexShaderString();
-
- String originalFragmentShader = programInfo.fragmentShaderString();
- if (originalFragmentShader.isNull())
- originalFragmentShader = defaultFragmentShaderString();
-
- // Shaders referenced from the CSS mix function use a different validator than regular WebGL shaders. See core/platform/graphics/filters/custom/CustomFilterGlobalContext.h for more details.
- bool blendsElementTexture = (programInfo.programType() == PROGRAM_TYPE_BLENDS_ELEMENT_TEXTURE);
- ANGLEWebKitBridge* validator = blendsElementTexture ? m_globalContext->mixShaderValidator() : m_globalContext->webglShaderValidator();
- String vertexShaderLog, fragmentShaderLog;
- Vector<ANGLEShaderSymbol> symbols;
- bool vertexShaderValid = validator->compileShaderSource(originalVertexShader.utf8().data(), SHADER_TYPE_VERTEX, m_validatedVertexShader, vertexShaderLog, symbols);
- bool fragmentShaderValid = validator->compileShaderSource(originalFragmentShader.utf8().data(), SHADER_TYPE_FRAGMENT, m_validatedFragmentShader, fragmentShaderLog, symbols);
- if (!vertexShaderValid || !fragmentShaderValid) {
- // FIXME: Report the validation errors.
- // https://bugs.webkit.org/show_bug.cgi?id=74416
- return;
- }
-
- if (!validateSymbols(symbols, m_programInfo.meshType())) {
- // FIXME: Report validation errors.
- // https://bugs.webkit.org/show_bug.cgi?id=74416
- return;
- }
-
- // We need to add texture access, blending, and compositing code to shaders that are referenced from the CSS mix function.
- if (blendsElementTexture) {
- rewriteMixVertexShader(symbols);
- rewriteMixFragmentShader();
- }
-
- m_isInitialized = true;
-}
-
-PassRefPtr<CustomFilterCompiledProgram> CustomFilterValidatedProgram::compiledProgram()
-{
- ASSERT(m_isInitialized && m_globalContext && !m_validatedVertexShader.isNull() && !m_validatedFragmentShader.isNull());
- if (!m_compiledProgram) {
- m_compiledProgram = CustomFilterCompiledProgram::create(m_globalContext->context(), m_validatedVertexShader, m_validatedFragmentShader, m_programInfo.programType());
- ASSERT(m_compiledProgram->isInitialized());
- ASSERT(m_compiledProgram->samplerLocation() != -1 || !needsInputTexture());
- }
- return m_compiledProgram;
-}
-
-bool CustomFilterValidatedProgram::needsInputTexture() const
-{
- return m_programInfo.programType() == PROGRAM_TYPE_BLENDS_ELEMENT_TEXTURE
- && m_programInfo.mixSettings().compositeOperator != CompositeClear
- && m_programInfo.mixSettings().compositeOperator != CompositeCopy;
-}
-
-void CustomFilterValidatedProgram::rewriteMixVertexShader(const Vector<ANGLEShaderSymbol>& symbols)
-{
- ASSERT(m_programInfo.programType() == PROGRAM_TYPE_BLENDS_ELEMENT_TEXTURE);
-
- // If the author defined a_texCoord, we can use it to shuttle the texture coordinate to the fragment shader.
- // Note that vertex attributes are read-only in GLSL, so the author could not have changed a_texCoord's value.
- // Also, note that we would have already rejected the shader if the author defined a_texCoord with the wrong type.
- bool texCoordAttributeDefined = false;
- for (size_t i = 0; i < symbols.size(); ++i) {
- if (symbols[i].name == "a_texCoord")
- texCoordAttributeDefined = true;
- }
-
- if (!texCoordAttributeDefined)
- m_validatedVertexShader.append("attribute mediump vec2 a_texCoord;");
-
- // During validation, ANGLE renamed the author's "main" function to "css_main".
- // We write our own "main" function and call "css_main" from it.
- // This makes rewriting easy and ensures that our code runs after all author code.
- m_validatedVertexShader.append(SHADER(
- varying mediump vec2 css_v_texCoord;
-
- void main()
- {
- css_main();
- css_v_texCoord = a_texCoord;
- }
- ));
-}
-
-void CustomFilterValidatedProgram::rewriteMixFragmentShader()
-{
- ASSERT(m_programInfo.programType() == PROGRAM_TYPE_BLENDS_ELEMENT_TEXTURE);
-
- StringBuilder builder;
- // ANGLE considered these symbols as built-ins during validation under the SH_CSS_SHADERS_SPEC flag.
- // Now, we have to define these symbols in order to make this shader valid GLSL.
- // We define these symbols before the author's shader code, which makes them accessible to author code.
- builder.append(SHADER(
- mediump vec4 css_MixColor = vec4(0.0);
- mediump mat4 css_ColorMatrix = mat4(1.0);
- ));
- builder.append(m_validatedFragmentShader);
- builder.append(blendFunctionString(m_programInfo.mixSettings().blendMode));
- builder.append(compositeFunctionString(m_programInfo.mixSettings().compositeOperator));
- // We define symbols like "css_u_texture" after the author's shader code, which makes them inaccessible to author code.
- // In particular, "css_u_texture" represents the DOM element texture, so it's important to keep it inaccessible to
- // author code for security reasons.
- builder.append(SHADER(
- uniform sampler2D css_u_texture;
- varying mediump vec2 css_v_texCoord;
-
- void main()
- {
- css_main();
- mediump vec4 originalColor = texture2D(css_u_texture, css_v_texCoord);
- mediump vec4 multipliedColor = clamp(css_ColorMatrix * originalColor, 0.0, 1.0);
- mediump vec4 clampedMixColor = clamp(css_MixColor, 0.0, 1.0);
- mediump vec3 blendedColor = css_BlendColor(multipliedColor.rgb, clampedMixColor.rgb);
- mediump vec3 weightedColor = (1.0 - multipliedColor.a) * clampedMixColor.rgb + multipliedColor.a * blendedColor;
- gl_FragColor = css_Composite(multipliedColor.rgb, multipliedColor.a, weightedColor.rgb, clampedMixColor.a);
- }
- ));
- m_validatedFragmentShader = builder.toString();
-}
-
-String CustomFilterValidatedProgram::blendFunctionString(BlendMode blendMode)
-{
- // Implemented using the same symbol names as the Compositing and Blending spec:
- // https://dvcs.w3.org/hg/FXTF/rawfile/tip/compositing/index.html#blendingnormal
- // Cs: is the source color in css_BlendColor() and the source color component in css_BlendComponent()
- // Cb: is the backdrop color in css_BlendColor() and the backdrop color component in css_BlendComponent()
- const char* blendColorExpression = "vec3(css_BlendComponent(Cb.r, Cs.r), css_BlendComponent(Cb.g, Cs.g), css_BlendComponent(Cb.b, Cs.b))";
- const char* blendComponentExpression = "Co = 0.0;";
- bool needsLuminosityHelperFunctions = false;
- bool needsSaturationHelperFunctions = false;
- String blendFunctionString;
- switch (blendMode) {
- case BlendModeNormal:
- blendColorExpression = "Cs";
- break;
- case BlendModeMultiply:
- blendColorExpression = "Cs * Cb";
- break;
- case BlendModeScreen:
- blendColorExpression = "Cb + Cs - (Cb * Cs)";
- break;
- case BlendModeDarken:
- blendColorExpression = "min(Cb, Cs)";
- break;
- case BlendModeLighten:
- blendColorExpression = "max(Cb, Cs)";
- break;
- case BlendModeDifference:
- blendColorExpression = "abs(Cb - Cs)";
- break;
- case BlendModeExclusion:
- blendColorExpression = "Cb + Cs - 2.0 * Cb * Cs";
- break;
- case BlendModeOverlay:
- /*
- Co = HardLight(Cs, Cb)
- = if(Cb <= 0.5)
- Multiply(Cs, 2 x Cb)
- else
- Screen(Cs, 2 x Cb - 1)
- = if(Cb <= 0.5)
- Cs x (2 x Cb)
- else
- Cs + (2 x Cb - 1) - (Cs x (2 x Cb - 1))
- */
- blendComponentExpression = SHADER(
- if (Cb <= 0.5)
- Co = Cs * (2.0 * Cb);
- else
- Co = Cs + (2.0 * Cb - 1.0) - (Cs * (2.0 * Cb - 1.0));
- );
- break;
- case BlendModeColorDodge:
- /*
- Co = if(Cs < 1)
- min(1, Cb / (1 - Cs))
- else
- 1
- */
- blendComponentExpression = SHADER(
- if (Cs < 1.0)
- Co = min(1.0, Cb / (1.0 - Cs));
- else
- Co = 1.0;
- );
- break;
- case BlendModeColorBurn:
- /*
- Co = if(Cs > 0)
- 1 - min(1, (1 - Cb) / Cs)
- else
- 0
- */
- blendComponentExpression = SHADER(
- if (Cs > 0.0)
- Co = 1.0 - min(1.0, (1.0 - Cb) / Cs);
- else
- Co = 0.0;
- );
- break;
- case BlendModeHardLight:
- /*
- Co = if(Cs <= 0.5)
- Multiply(Cb, 2 x Cs)
- else
- Screen(Cb, 2 x Cs -1)
- = if(Cs <= 0.5)
- Cb x (2 x Cs)
- else
- Cb + (2 x Cs - 1) - (Cb x (2 x Cs - 1))
- */
- blendComponentExpression = SHADER(
- if (Cs <= 0.5)
- Co = Cb * (2.0 * Cs);
- else
- Co = Cb + (2.0 * Cs - 1.0) - (Cb * (2.0 * Cs - 1.0));
- );
- break;
- case BlendModeSoftLight:
- /*
- Co = if(Cs <= 0.5)
- Cb - (1 - 2 x Cs) x Cb x (1 - Cb)
- else
- Cb + (2 x Cs - 1) x (D(Cb) - Cb)
-
- with
-
- D(Cb) = if(Cb <= 0.25)
- (16 * Cb - 12) x Cb + 4) x Cb
- else
- sqrt(Cb)
- */
- blendComponentExpression = SHADER(
- mediump float D;
- if (Cb <= 0.25)
- D = ((16.0 * Cb - 12.0) * Cb + 4.0) * Cb;
- else
- D = sqrt(Cb);
-
- if (Cs <= 0.5)
- Co = Cb - (1.0 - 2.0 * Cs) * Cb * (1.0 - Cb);
- else
- Co = Cb + (2.0 * Cs - 1.0) * (D - Cb);
- );
- break;
- case BlendModeColor:
- needsLuminosityHelperFunctions = true;
- blendColorExpression = "css_SetLum(Cs, css_Lum(Cb))";
- break;
- case BlendModeLuminosity:
- needsLuminosityHelperFunctions = true;
- blendColorExpression = "css_SetLum(Cb, css_Lum(Cs))";
- break;
- case BlendModeHue:
- needsLuminosityHelperFunctions = true;
- needsSaturationHelperFunctions = true;
- blendColorExpression = "css_SetLum(css_SetSat(Cs, css_Sat(Cb)), css_Lum(Cb))";
- break;
- case BlendModeSaturation:
- needsLuminosityHelperFunctions = true;
- needsSaturationHelperFunctions = true;
- blendColorExpression = "css_SetLum(css_SetSat(Cb, css_Sat(Cs)), css_Lum(Cb))";
- break;
- default:
- ASSERT_NOT_REACHED();
- }
-
- if (needsLuminosityHelperFunctions) {
- blendFunctionString.append(SHADER(
- mediump float css_Lum(mediump vec3 C)
- {
- return 0.3 * C.r + 0.59 * C.g + 0.11 * C.b;
- }
- mediump vec3 css_ClipColor(mediump vec3 C)
- {
- mediump float L = css_Lum(C);
- mediump float n = min(min(C.r, C.g), C.b);
- mediump float x = max(max(C.r, C.g), C.b);
- if (n < 0.0)
- C = L + (((C - L) * L) / (L - n));
- if (x > 1.0)
- C = L + (((C - L) * (1.0 - L) / (x - L)));
- return C;
- }
- mediump vec3 css_SetLum(mediump vec3 C, mediump float l)
- {
- C += l - css_Lum(C);
- return css_ClipColor(C);
- }
- ));
- }
-
- if (needsSaturationHelperFunctions) {
- blendFunctionString.append(SHADER(
- mediump float css_Sat(mediump vec3 C)
- {
- mediump float cMin = min(min(C.r, C.g), C.b);
- mediump float cMax = max(max(C.r, C.g), C.b);
- return cMax - cMin;
- }
- void css_SetSatHelper(inout mediump float cMin, inout mediump float cMid, inout mediump float cMax, mediump float s)
- {
- if (cMax > cMin) {
- cMid = (((cMid - cMin) * s) / (cMax - cMin));
- cMax = s;
- } else
- cMid = cMax = 0.0;
- cMin = 0.0;
- }
- mediump vec3 css_SetSat(mediump vec3 C, mediump float s)
- {
- if (C.r <= C.g) {
- if (C.g <= C.b)
- css_SetSatHelper(C.r, C.g, C.b, s);
- else {
- if (C.r <= C.b)
- css_SetSatHelper(C.r, C.b, C.g, s);
- else
- css_SetSatHelper(C.b, C.r, C.g, s);
- }
- } else {
- if (C.r <= C.b)
- css_SetSatHelper(C.g, C.r, C.b, s);
- else {
- if (C.g <= C.b)
- css_SetSatHelper(C.g, C.b, C.r, s);
- else
- css_SetSatHelper(C.b, C.g, C.r, s);
- }
- }
- return C;
- }
- ));
- }
-
- blendFunctionString.append(String::format(SHADER(
- mediump float css_BlendComponent(mediump float Cb, mediump float Cs)
- {
- mediump float Co;
- %s
- return Co;
- }
- mediump vec3 css_BlendColor(mediump vec3 Cb, mediump vec3 Cs)
- {
- return %s;
- }
- ), blendComponentExpression, blendColorExpression));
-
- return blendFunctionString;
-}
-
-String CustomFilterValidatedProgram::compositeFunctionString(CompositeOperator compositeOperator)
-{
- // Use the same symbol names as the Compositing and Blending spec:
- // https://dvcs.w3.org/hg/FXTF/rawfile/tip/compositing/index.html#blendingnormal
- // Cs: is the source color
- // Cb: is the backdrop color
- // as: is the source alpha
- // ab: is the backdrop alpha
- // Fa: is defined by the Porter Duff operator in use
- // Fb: is defined by the Porter Duff operator in use
- const char* Fa = 0;
- const char* Fb = 0;
- switch (compositeOperator) {
- case CompositeSourceAtop:
- Fa = "ab";
- Fb = "1.0 - as";
- break;
- case CompositeClear:
- Fa = "0.0";
- Fb = "0.0";
- break;
- case CompositeCopy:
- Fa = "1.0";
- Fb = "0.0";
- break;
- case CompositeSourceOver:
- Fa = "1.0";
- Fb = "1.0 - as";
- break;
- case CompositeSourceIn:
- Fa = "ab";
- Fb = "0.0";
- break;
- case CompositeSourceOut:
- Fa = "1.0 - ab";
- Fb = "0.0";
- break;
- case CompositeDestinationOver:
- Fa = "1.0 - ab";
- Fb = "1.0";
- break;
- case CompositeDestinationIn:
- Fa = "0.0";
- Fb = "as";
- break;
- case CompositeDestinationOut:
- Fa = "0.0";
- Fb = "1.0 - as";
- break;
- case CompositeDestinationAtop:
- Fa = "1.0 - ab";
- Fb = "as";
- break;
- case CompositeXOR:
- Fa = "1.0 - ab";
- Fb = "1.0 - as";
- break;
- case CompositePlusLighter:
- notImplemented();
- return String();
- default:
- // The CSS parser should not have accepted any other composite operators.
- ASSERT_NOT_REACHED();
- return String();
- }
-
- ASSERT(Fa && Fb);
- // Use the general formula for compositing, lifted from the spec:
- // https://dvcs.w3.org/hg/FXTF/rawfile/tip/compositing/index.html#generalformula
- return String::format(SHADER(
- mediump vec4 css_Composite(mediump vec3 Cb, mediump float ab, mediump vec3 Cs, mediump float as)
- {
- mediump float Fa = %s;
- mediump float Fb = %s;
- return vec4(as * Fa * Cs + ab * Fb * Cb, as * Fa + ab * Fb);
- }
- ), Fa, Fb);
-}
-
-CustomFilterValidatedProgram::~CustomFilterValidatedProgram()
-{
- platformDestroy();
-
- if (m_globalContext)
- m_globalContext->removeValidatedProgram(this);
-}
-
-CustomFilterProgramInfo CustomFilterValidatedProgram::validatedProgramInfo() const
-{
- ASSERT(m_isInitialized);
- return CustomFilterProgramInfo(m_validatedVertexShader, m_validatedFragmentShader, m_programInfo.programType(), m_programInfo.mixSettings(), m_programInfo.meshType());
-}
-
-void CustomFilterValidatedProgram::platformInit()
-{
-}
-
-void CustomFilterValidatedProgram::platformDestroy()
-{
-}
-
-} // namespace WebCore
-
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterValidatedProgram.h b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterValidatedProgram.h
deleted file mode 100644
index 91557093753..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/CustomFilterValidatedProgram.h
+++ /dev/null
@@ -1,123 +0,0 @@
-/*
- * Copyright (C) 2012 Adobe Systems Incorporated. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above
- * copyright notice, this list of conditions and the following
- * disclaimer.
- * 2. Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following
- * disclaimer in the documentation and/or other materials
- * provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
- * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
- * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
- * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#ifndef CustomFilterValidatedProgram_h
-#define CustomFilterValidatedProgram_h
-
-#include "core/platform/graphics/filters/custom/CustomFilterCompiledProgram.h"
-#include "core/platform/graphics/filters/custom/CustomFilterProgramInfo.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/RefPtr.h"
-#include "wtf/text/WTFString.h"
-
-// PlatformCompiledProgram defines a type that is compatible with the framework used to implement accelerated compositing on a particular platform.
-namespace WebCore {
-
-struct ANGLEShaderSymbol;
-class CustomFilterCompiledProgram;
-class CustomFilterGlobalContext;
-
-//
-// A unique combination of vertex shader and fragment shader is only validated and compiled once.
-// All shaders are validated through ANGLE in CustomFilterValidatedProgram before being compiled by the GraphicsContext3D in CustomFilterCompiledProgram.
-// For shaders that use the CSS mix function, CustomFilterValidatedProgram adds shader code to perform DOM texture access, blending, and compositing.
-//
-// The CustomFilterGlobalContext caches the validated programs.
-// CustomFilterValidatedProgram owns a CustomFilterCompiledProgram if validation and compilation succeeds.
-// Thus, compiled programs are cached via their validated program owners.
-//
-// CustomFilterGlobalContext has a weak reference to the CustomFilterValidatedProgram.
-// Thus, the CustomFilterValidatedProgram destructor needs to notify the CustomFilterGlobalContext to remove the program from the cache.
-// FECustomFilter is the reference owner of the CustomFilterValidatedProgram.
-// Thus, a validated and compiled shader is only kept alive as long as there is at least one visible layer that applies the shader.
-//
-class CustomFilterValidatedProgram : public RefCounted<CustomFilterValidatedProgram> {
-public:
- static PassRefPtr<CustomFilterValidatedProgram> create(CustomFilterGlobalContext* globalContext, const CustomFilterProgramInfo& programInfo)
- {
- return adoptRef(new CustomFilterValidatedProgram(globalContext, programInfo));
- }
-
- ~CustomFilterValidatedProgram();
-
- const CustomFilterProgramInfo& programInfo() const { return m_programInfo; }
- CustomFilterProgramInfo validatedProgramInfo() const;
-
- PassRefPtr<CustomFilterCompiledProgram> compiledProgram();
-
- const String& validatedVertexShader() const
- {
- ASSERT(m_isInitialized);
- return m_validatedVertexShader;
- }
-
- const String& validatedFragmentShader() const
- {
- ASSERT(m_isInitialized);
- return m_validatedFragmentShader;
- }
-
- bool isInitialized() const { return m_isInitialized; }
-
- // 'detachFromGlobalContext' is called when the CustomFilterGlobalContext is deleted, and there's no need for the callback anymore.
- // Note that CustomFilterGlobalContext does not keep a strong reference to the CustomFilterValidatedProgram.
- void detachFromGlobalContext() { m_globalContext = 0; }
-private:
- CustomFilterValidatedProgram(CustomFilterGlobalContext*, const CustomFilterProgramInfo&);
-
- void platformInit();
- void platformDestroy();
-
- static String defaultVertexShaderString();
- static String defaultFragmentShaderString();
-
- static String blendFunctionString(BlendMode);
- static String compositeFunctionString(CompositeOperator);
-
- void rewriteMixVertexShader(const Vector<ANGLEShaderSymbol>& symbols);
- void rewriteMixFragmentShader();
-
- bool needsInputTexture() const;
-
- CustomFilterGlobalContext* m_globalContext;
- CustomFilterProgramInfo m_programInfo;
-
- String m_validatedVertexShader;
- String m_validatedFragmentShader;
-
- RefPtr<CustomFilterCompiledProgram> m_compiledProgram;
-
- bool m_isInitialized;
-};
-
-}
-
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/FECustomFilter.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/FECustomFilter.cpp
deleted file mode 100644
index 23f68e166b4..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/FECustomFilter.cpp
+++ /dev/null
@@ -1,370 +0,0 @@
-/*
- * Copyright (C) 2012 Adobe Systems Incorporated. All rights reserved.
- * Copyright (C) 2011 Adobe Systems Incorporated. All rights reserved.
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above
- * copyright notice, this list of conditions and the following
- * disclaimer.
- * 2. Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following
- * disclaimer in the documentation and/or other materials
- * provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
- * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
- * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
- * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/platform/graphics/filters/custom/FECustomFilter.h"
-
-#include "core/platform/graphics/Extensions3D.h"
-#include "core/platform/graphics/GraphicsContext3D.h"
-#include "core/platform/graphics/filters/custom/CustomFilterRenderer.h"
-#include "core/platform/graphics/filters/custom/CustomFilterValidatedProgram.h"
-#include "core/platform/text/TextStream.h"
-#include "core/rendering/RenderTreeAsText.h"
-
-#include "wtf/Uint8ClampedArray.h"
-
-namespace WebCore {
-
-FECustomFilter::FECustomFilter(Filter* filter, PassRefPtr<GraphicsContext3D> context, PassRefPtr<CustomFilterValidatedProgram> validatedProgram, const CustomFilterParameterList& parameters,
- unsigned meshRows, unsigned meshColumns, CustomFilterMeshType meshType)
- : FilterEffect(filter)
- , m_context(context)
- , m_validatedProgram(validatedProgram)
- , m_inputTexture(0)
- , m_frameBuffer(0)
- , m_depthBuffer(0)
- , m_destTexture(0)
- , m_triedMultisampleBuffer(false)
- , m_multisampleFrameBuffer(0)
- , m_multisampleRenderBuffer(0)
- , m_multisampleDepthBuffer(0)
-{
- // We will not pass a CustomFilterCompiledProgram here, as we only want to compile it when we actually need it in the first paint.
- m_customFilterRenderer = CustomFilterRenderer::create(m_context, m_validatedProgram->programInfo().programType(), parameters, meshRows, meshColumns, meshType);
-}
-
-PassRefPtr<FECustomFilter> FECustomFilter::create(Filter* filter, PassRefPtr<GraphicsContext3D> context, PassRefPtr<CustomFilterValidatedProgram> validatedProgram, const CustomFilterParameterList& parameters,
- unsigned meshRows, unsigned meshColumns, CustomFilterMeshType meshType)
-{
- return adoptRef(new FECustomFilter(filter, context, validatedProgram, parameters, meshRows, meshColumns, meshType));
-}
-
-FECustomFilter::~FECustomFilter()
-{
- deleteRenderBuffers();
-}
-
-void FECustomFilter::deleteRenderBuffers()
-{
- ASSERT(m_context);
- m_context->makeContextCurrent();
- if (m_inputTexture) {
- m_context->deleteTexture(m_inputTexture);
- m_inputTexture = 0;
- }
- if (m_frameBuffer) {
- // Make sure to unbind any framebuffer from the context first, otherwise
- // some platforms might refuse to bind the same buffer id again.
- m_context->bindFramebuffer(GraphicsContext3D::FRAMEBUFFER, 0);
- m_context->deleteFramebuffer(m_frameBuffer);
- m_frameBuffer = 0;
- }
- if (m_depthBuffer) {
- m_context->deleteRenderbuffer(m_depthBuffer);
- m_depthBuffer = 0;
- }
- if (m_destTexture) {
- m_context->deleteTexture(m_destTexture);
- m_destTexture = 0;
- }
- deleteMultisampleRenderBuffers();
-}
-
-void FECustomFilter::deleteMultisampleRenderBuffers()
-{
- if (m_multisampleFrameBuffer) {
- // Make sure to unbind any framebuffer from the context first, otherwise
- // some platforms might refuse to bind the same buffer id again.
- m_context->bindFramebuffer(GraphicsContext3D::FRAMEBUFFER, 0);
- m_context->deleteFramebuffer(m_multisampleFrameBuffer);
- m_multisampleFrameBuffer = 0;
- }
- if (m_multisampleRenderBuffer) {
- m_context->deleteRenderbuffer(m_multisampleRenderBuffer);
- m_multisampleRenderBuffer = 0;
- }
- if (m_multisampleDepthBuffer) {
- m_context->deleteRenderbuffer(m_multisampleDepthBuffer);
- m_multisampleDepthBuffer = 0;
- }
-}
-
-void FECustomFilter::applySoftware()
-{
- if (!applyShader())
- clearShaderResult();
-}
-
-void FECustomFilter::clearShaderResult()
-{
- clearResult();
- Uint8ClampedArray* dstPixelArray = createUnmultipliedImageResult();
- if (!dstPixelArray)
- return;
-
- FilterEffect* in = inputEffect(0);
- setIsAlphaImage(in->isAlphaImage());
- IntRect effectDrawingRect = requestedRegionOfInputImageData(in->absolutePaintRect());
- in->copyUnmultipliedImage(dstPixelArray, effectDrawingRect);
-}
-
-void FECustomFilter::drawFilterMesh(Platform3DObject inputTexture)
-{
- bool multisample = canUseMultisampleBuffers();
- m_context->bindFramebuffer(GraphicsContext3D::FRAMEBUFFER, multisample ? m_multisampleFrameBuffer : m_frameBuffer);
- m_context->viewport(0, 0, m_contextSize.width(), m_contextSize.height());
-
- m_context->clearColor(0, 0, 0, 0);
- m_context->clear(GraphicsContext3D::COLOR_BUFFER_BIT | GraphicsContext3D::DEPTH_BUFFER_BIT);
-
- m_customFilterRenderer->draw(inputTexture, m_contextSize);
-
- if (multisample)
- resolveMultisampleBuffer();
-}
-
-bool FECustomFilter::prepareForDrawing()
-{
- m_context->makeContextCurrent();
-
- // Lazily inject the compiled program into the CustomFilterRenderer.
- if (!m_customFilterRenderer->compiledProgram())
- m_customFilterRenderer->setCompiledProgram(m_validatedProgram->compiledProgram());
-
- if (!m_customFilterRenderer->prepareForDrawing())
- return false;
-
- // Only allocate a texture if the program needs one and the caller doesn't allocate one by itself.
- if ((m_customFilterRenderer->programNeedsInputTexture() && !ensureInputTexture()) || !ensureFrameBuffer())
- return false;
-
- return true;
-}
-
-bool FECustomFilter::applyShader()
-{
- Uint8ClampedArray* dstPixelArray = m_customFilterRenderer->premultipliedAlpha() ? createPremultipliedImageResult() : createUnmultipliedImageResult();
- if (!dstPixelArray)
- return false;
-
- if (!prepareForDrawing())
- return false;
-
- FilterEffect* in = inputEffect(0);
- IntRect effectDrawingRect = requestedRegionOfInputImageData(in->absolutePaintRect());
- IntSize newContextSize(effectDrawingRect.size());
- if (!resizeContextIfNeeded(newContextSize))
- return false;
-
- bool needsInputTexture = m_customFilterRenderer->programNeedsInputTexture();
- if (needsInputTexture) {
- RefPtr<Uint8ClampedArray> srcPixelArray = in->asUnmultipliedImage(effectDrawingRect);
- uploadInputTexture(srcPixelArray.get());
- }
- drawFilterMesh(needsInputTexture ? m_inputTexture : 0);
-
- ASSERT(static_cast<size_t>(newContextSize.width() * newContextSize.height() * 4) == dstPixelArray->length());
- m_context->readPixels(0, 0, newContextSize.width(), newContextSize.height(), GraphicsContext3D::RGBA, GraphicsContext3D::UNSIGNED_BYTE, dstPixelArray->data());
-
- return true;
-}
-
-bool FECustomFilter::ensureInputTexture()
-{
- if (!m_inputTexture)
- m_inputTexture = m_context->createTexture();
- return m_inputTexture;
-}
-
-void FECustomFilter::uploadInputTexture(Uint8ClampedArray* srcPixelArray)
-{
- m_context->bindTexture(GraphicsContext3D::TEXTURE_2D, m_inputTexture);
- m_context->texImage2D(GraphicsContext3D::TEXTURE_2D, 0, GraphicsContext3D::RGBA, m_contextSize.width(), m_contextSize.height(), 0, GraphicsContext3D::RGBA, GraphicsContext3D::UNSIGNED_BYTE, srcPixelArray->data());
-}
-
-bool FECustomFilter::ensureFrameBuffer()
-{
- if (!m_frameBuffer)
- m_frameBuffer = m_context->createFramebuffer();
- if (!m_depthBuffer)
- m_depthBuffer = m_context->createRenderbuffer();
- if (!m_destTexture)
- m_destTexture = m_context->createTexture();
- return m_frameBuffer && m_depthBuffer && m_destTexture;
-}
-
-bool FECustomFilter::createMultisampleBuffer()
-{
- ASSERT(!m_triedMultisampleBuffer);
- m_triedMultisampleBuffer = true;
-
- Extensions3D* extensions = m_context->extensions();
- if (!extensions
- || !extensions->supports("GL_ANGLE_framebuffer_multisample")
- || !extensions->supports("GL_ANGLE_framebuffer_blit")
- || !extensions->supports("GL_OES_rgb8_rgba8"))
- return false;
-
- extensions->ensureEnabled("GL_ANGLE_framebuffer_blit");
- extensions->ensureEnabled("GL_ANGLE_framebuffer_multisample");
- extensions->ensureEnabled("GL_OES_rgb8_rgba8");
-
- if (!m_multisampleFrameBuffer)
- m_multisampleFrameBuffer = m_context->createFramebuffer();
- if (!m_multisampleRenderBuffer)
- m_multisampleRenderBuffer = m_context->createRenderbuffer();
- if (!m_multisampleDepthBuffer)
- m_multisampleDepthBuffer = m_context->createRenderbuffer();
-
- return true;
-}
-
-void FECustomFilter::resolveMultisampleBuffer()
-{
- ASSERT(m_triedMultisampleBuffer && m_multisampleFrameBuffer && m_multisampleRenderBuffer && m_multisampleDepthBuffer);
- m_context->bindFramebuffer(Extensions3D::READ_FRAMEBUFFER, m_multisampleFrameBuffer);
- m_context->bindFramebuffer(Extensions3D::DRAW_FRAMEBUFFER, m_frameBuffer);
-
- ASSERT(m_context->extensions());
- m_context->extensions()->blitFramebuffer(0, 0, m_contextSize.width(), m_contextSize.height(), 0, 0, m_contextSize.width(), m_contextSize.height(), GraphicsContext3D::COLOR_BUFFER_BIT, GraphicsContext3D::NEAREST);
-
- m_context->bindFramebuffer(Extensions3D::READ_FRAMEBUFFER, 0);
- m_context->bindFramebuffer(Extensions3D::DRAW_FRAMEBUFFER, 0);
-
- m_context->bindFramebuffer(GraphicsContext3D::FRAMEBUFFER, m_frameBuffer);
-}
-
-bool FECustomFilter::canUseMultisampleBuffers() const
-{
- return m_triedMultisampleBuffer && m_multisampleFrameBuffer && m_multisampleRenderBuffer && m_multisampleDepthBuffer;
-}
-
-bool FECustomFilter::resizeMultisampleBuffers(const IntSize& newContextSize)
-{
- if (!m_triedMultisampleBuffer && !createMultisampleBuffer())
- return false;
-
- if (!canUseMultisampleBuffers())
- return false;
-
- static const int kMaxSampleCount = 4;
- int maxSupportedSampleCount = 0;
- m_context->getIntegerv(Extensions3D::MAX_SAMPLES, &maxSupportedSampleCount);
- int sampleCount = std::min(kMaxSampleCount, maxSupportedSampleCount);
- if (!sampleCount) {
- deleteMultisampleRenderBuffers();
- return false;
- }
-
- Extensions3D* extensions = m_context->extensions();
- ASSERT(extensions);
-
- m_context->bindFramebuffer(GraphicsContext3D::FRAMEBUFFER, m_multisampleFrameBuffer);
-
- m_context->bindRenderbuffer(GraphicsContext3D::RENDERBUFFER, m_multisampleRenderBuffer);
- extensions->renderbufferStorageMultisample(GraphicsContext3D::RENDERBUFFER, sampleCount, Extensions3D::RGBA8_OES, newContextSize.width(), newContextSize.height());
- m_context->framebufferRenderbuffer(GraphicsContext3D::FRAMEBUFFER, GraphicsContext3D::COLOR_ATTACHMENT0, GraphicsContext3D::RENDERBUFFER, m_multisampleRenderBuffer);
-
- m_context->bindRenderbuffer(GraphicsContext3D::RENDERBUFFER, m_multisampleDepthBuffer);
- extensions->renderbufferStorageMultisample(GraphicsContext3D::RENDERBUFFER, sampleCount, GraphicsContext3D::DEPTH_COMPONENT16, newContextSize.width(), newContextSize.height());
- m_context->framebufferRenderbuffer(GraphicsContext3D::FRAMEBUFFER, GraphicsContext3D::DEPTH_ATTACHMENT, GraphicsContext3D::RENDERBUFFER, m_multisampleDepthBuffer);
-
- m_context->bindRenderbuffer(GraphicsContext3D::RENDERBUFFER, 0);
-
- if (m_context->checkFramebufferStatus(GraphicsContext3D::FRAMEBUFFER) != GraphicsContext3D::FRAMEBUFFER_COMPLETE) {
- deleteMultisampleRenderBuffers();
- return false;
- }
-
- return true;
-}
-
-bool FECustomFilter::resizeContextIfNeeded(const IntSize& newContextSize)
-{
- if (newContextSize.isEmpty())
- return false;
- if (m_contextSize == newContextSize)
- return true;
-
- int maxTextureSize = 0;
- m_context->getIntegerv(GraphicsContext3D::MAX_TEXTURE_SIZE, &maxTextureSize);
- if (newContextSize.height() > maxTextureSize || newContextSize.width() > maxTextureSize)
- return false;
-
- return resizeContext(newContextSize);
-}
-
-bool FECustomFilter::resizeContext(const IntSize& newContextSize)
-{
- bool multisample = resizeMultisampleBuffers(newContextSize);
-
- m_context->bindFramebuffer(GraphicsContext3D::FRAMEBUFFER, m_frameBuffer);
- m_context->bindTexture(GraphicsContext3D::TEXTURE_2D, m_destTexture);
- // We are going to clear the output buffer anyway, so we can safely initialize the destination texture with garbage data.
- // FIXME: GraphicsContext3D::texImage2DDirect is not implemented on Chromium.
- m_context->texImage2D(GraphicsContext3D::TEXTURE_2D, 0, GraphicsContext3D::RGBA, newContextSize.width(), newContextSize.height(), 0, GraphicsContext3D::RGBA, GraphicsContext3D::UNSIGNED_BYTE, 0);
- m_context->framebufferTexture2D(GraphicsContext3D::FRAMEBUFFER, GraphicsContext3D::COLOR_ATTACHMENT0, GraphicsContext3D::TEXTURE_2D, m_destTexture, 0);
-
- // We don't need the depth buffer for the texture framebuffer, if we already
- // have a multisample buffer.
- if (!multisample) {
- m_context->bindRenderbuffer(GraphicsContext3D::RENDERBUFFER, m_depthBuffer);
- m_context->renderbufferStorage(GraphicsContext3D::RENDERBUFFER, GraphicsContext3D::DEPTH_COMPONENT16, newContextSize.width(), newContextSize.height());
- m_context->framebufferRenderbuffer(GraphicsContext3D::FRAMEBUFFER, GraphicsContext3D::DEPTH_ATTACHMENT, GraphicsContext3D::RENDERBUFFER, m_depthBuffer);
- }
-
- if (m_context->checkFramebufferStatus(GraphicsContext3D::FRAMEBUFFER) != GraphicsContext3D::FRAMEBUFFER_COMPLETE)
- return false;
-
- if (multisample) {
- // Clear the framebuffer first, otherwise the first blit will fail.
- m_context->clearColor(0, 0, 0, 0);
- m_context->clear(GraphicsContext3D::COLOR_BUFFER_BIT);
- }
-
- m_context->bindRenderbuffer(GraphicsContext3D::RENDERBUFFER, 0);
-
- m_contextSize = newContextSize;
- return true;
-}
-
-TextStream& FECustomFilter::externalRepresentation(TextStream& ts, int indent) const
-{
- writeIndent(ts, indent);
- ts << "[feCustomFilter";
- FilterEffect::externalRepresentation(ts);
- ts << "]\n";
- inputEffect(0)->externalRepresentation(ts, indent + 1);
- return ts;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/FECustomFilter.h b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/FECustomFilter.h
deleted file mode 100644
index e3d42b2d72d..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/FECustomFilter.h
+++ /dev/null
@@ -1,101 +0,0 @@
-/*
- * Copyright (C) 2011 Adobe Systems Incorporated. All rights reserved.
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above
- * copyright notice, this list of conditions and the following
- * disclaimer.
- * 2. Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following
- * disclaimer in the documentation and/or other materials
- * provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
- * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
- * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
- * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#ifndef FECustomFilter_h
-#define FECustomFilter_h
-
-#include "core/platform/graphics/GraphicsTypes3D.h"
-#include "core/platform/graphics/filters/Filter.h"
-#include "core/platform/graphics/filters/FilterEffect.h"
-#include "core/platform/graphics/filters/custom/CustomFilterConstants.h"
-#include "core/platform/graphics/filters/custom/CustomFilterOperation.h"
-#include "wtf/RefPtr.h"
-
-namespace WebCore {
-
-class CustomFilterRenderer;
-class CustomFilterValidatedProgram;
-class GraphicsContext3D;
-class IntSize;
-
-class FECustomFilter : public FilterEffect {
-public:
- static PassRefPtr<FECustomFilter> create(Filter*, PassRefPtr<GraphicsContext3D>, PassRefPtr<CustomFilterValidatedProgram>, const CustomFilterParameterList&,
- unsigned meshRows, unsigned meshColumns, CustomFilterMeshType);
-
- virtual TextStream& externalRepresentation(TextStream&, int indention) const;
-
-private:
- FECustomFilter(Filter*, PassRefPtr<GraphicsContext3D>, PassRefPtr<CustomFilterValidatedProgram>, const CustomFilterParameterList&,
- unsigned meshRows, unsigned meshColumns, CustomFilterMeshType);
- ~FECustomFilter();
-
- virtual void applySoftware() OVERRIDE;
-
- bool applyShader();
- void clearShaderResult();
- bool initializeContext();
-
- bool prepareForDrawing();
-
- void drawFilterMesh(Platform3DObject inputTexture);
- bool ensureInputTexture();
- void uploadInputTexture(Uint8ClampedArray* srcPixelArray);
- bool resizeContextIfNeeded(const IntSize&);
- bool resizeContext(const IntSize&);
-
- bool canUseMultisampleBuffers() const;
- bool createMultisampleBuffer();
- bool resizeMultisampleBuffers(const IntSize&);
- void resolveMultisampleBuffer();
- void deleteMultisampleRenderBuffers();
-
- bool ensureFrameBuffer();
- void deleteRenderBuffers();
-
- RefPtr<GraphicsContext3D> m_context;
- RefPtr<CustomFilterValidatedProgram> m_validatedProgram;
- RefPtr<CustomFilterRenderer> m_customFilterRenderer;
- IntSize m_contextSize;
-
- Platform3DObject m_inputTexture;
- Platform3DObject m_frameBuffer;
- Platform3DObject m_depthBuffer;
- Platform3DObject m_destTexture;
-
- bool m_triedMultisampleBuffer;
- Platform3DObject m_multisampleFrameBuffer;
- Platform3DObject m_multisampleRenderBuffer;
- Platform3DObject m_multisampleDepthBuffer;
-};
-
-} // namespace WebCore
-
-#endif // FECustomFilter_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/ValidatedCustomFilterOperation.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/ValidatedCustomFilterOperation.cpp
deleted file mode 100644
index c2859471044..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/ValidatedCustomFilterOperation.cpp
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * Copyright (C) 2012 Adobe Systems Incorporated. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above
- * copyright notice, this list of conditions and the following
- * disclaimer.
- * 2. Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following
- * disclaimer in the documentation and/or other materials
- * provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
- * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
- * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
- * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/platform/graphics/filters/custom/ValidatedCustomFilterOperation.h"
-
-#include "core/platform/graphics/filters/custom/CustomFilterParameter.h"
-#include "core/platform/graphics/filters/custom/CustomFilterValidatedProgram.h"
-#include "wtf/UnusedParam.h"
-
-namespace WebCore {
-
-ValidatedCustomFilterOperation::ValidatedCustomFilterOperation(PassRefPtr<CustomFilterValidatedProgram> validatedProgram,
- const CustomFilterParameterList& sortedParameters, unsigned meshRows, unsigned meshColumns, CustomFilterMeshType meshType)
- : FilterOperation(VALIDATED_CUSTOM)
- , m_validatedProgram(validatedProgram)
- , m_parameters(sortedParameters)
- , m_meshRows(meshRows)
- , m_meshColumns(meshColumns)
- , m_meshType(meshType)
-{
-}
-
-ValidatedCustomFilterOperation::~ValidatedCustomFilterOperation()
-{
-}
-
-PassRefPtr<FilterOperation> ValidatedCustomFilterOperation::blend(const FilterOperation*, double progress, bool blendToPassthrough)
-{
- UNUSED_PARAM(progress);
- UNUSED_PARAM(blendToPassthrough);
-
- ASSERT_NOT_REACHED();
- return this;
-}
-
-} // namespace WebCore
-
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/ValidatedCustomFilterOperation.h b/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/ValidatedCustomFilterOperation.h
deleted file mode 100644
index 60b180127ad..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/filters/custom/ValidatedCustomFilterOperation.h
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
- * Copyright (C) 2012 Adobe Systems Incorporated. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above
- * copyright notice, this list of conditions and the following
- * disclaimer.
- * 2. Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following
- * disclaimer in the documentation and/or other materials
- * provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
- * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
- * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
- * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#ifndef ValidatedCustomFilterOperation_h
-#define ValidatedCustomFilterOperation_h
-
-#include "core/platform/graphics/filters/FilterOperation.h"
-#include "core/platform/graphics/filters/custom/CustomFilterConstants.h"
-#include "core/platform/graphics/filters/custom/CustomFilterParameterList.h"
-
-namespace WebCore {
-
-class CustomFilterValidatedProgram;
-
-class ValidatedCustomFilterOperation : public FilterOperation {
-public:
- static PassRefPtr<ValidatedCustomFilterOperation> create(PassRefPtr<CustomFilterValidatedProgram> validatedProgram,
- const CustomFilterParameterList& sortedParameters, unsigned meshRows, unsigned meshColumns, CustomFilterMeshType meshType)
- {
- return adoptRef(new ValidatedCustomFilterOperation(validatedProgram, sortedParameters, meshRows, meshColumns, meshType));
- }
-
- virtual ~ValidatedCustomFilterOperation();
-
- virtual bool affectsOpacity() const { return true; }
- virtual bool movesPixels() const { return true; }
-
- virtual PassRefPtr<FilterOperation> blend(const FilterOperation* from, double progress, bool blendToPassthrough = false);
-
- CustomFilterValidatedProgram* validatedProgram() const { return m_validatedProgram.get(); }
- const CustomFilterParameterList& parameters() const { return m_parameters; }
-
- unsigned meshRows() const { return m_meshRows; }
- unsigned meshColumns() const { return m_meshColumns; }
-
- CustomFilterMeshType meshType() const { return m_meshType; }
-
-private:
- virtual bool operator==(const FilterOperation& o) const
- {
- if (!isSameType(o))
- return false;
-
- const ValidatedCustomFilterOperation* other = static_cast<const ValidatedCustomFilterOperation*>(&o);
- return m_validatedProgram.get() == other->m_validatedProgram.get()
- && m_meshRows == other->m_meshRows
- && m_meshColumns == other->m_meshColumns
- && m_meshType == other->m_meshType
- && m_parameters == other->m_parameters;
- }
-
- ValidatedCustomFilterOperation(PassRefPtr<CustomFilterValidatedProgram>, const CustomFilterParameterList&, unsigned meshRows, unsigned meshColumns, CustomFilterMeshType);
-
- RefPtr<CustomFilterValidatedProgram> m_validatedProgram;
-
- CustomFilterParameterList m_parameters;
- unsigned m_meshRows;
- unsigned m_meshColumns;
- CustomFilterMeshType m_meshType;
-};
-
-} // namespace WebCore
-
-
-#endif // ValidatedCustomFilterOperation_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/gpu/DrawingBuffer.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/gpu/DrawingBuffer.cpp
deleted file mode 100644
index 8155797074c..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/gpu/DrawingBuffer.cpp
+++ /dev/null
@@ -1,703 +0,0 @@
-/*
- * Copyright (c) 2010, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/platform/graphics/gpu/DrawingBuffer.h"
-
-#include <algorithm>
-#include "core/platform/chromium/TraceEvent.h"
-#include "core/platform/graphics/Extensions3D.h"
-#include "core/platform/graphics/GraphicsContext3D.h"
-#include "core/platform/graphics/GraphicsLayer.h"
-#include "public/platform/Platform.h"
-#include "public/platform/WebCompositorSupport.h"
-#include "public/platform/WebExternalBitmap.h"
-#include "public/platform/WebExternalTextureLayer.h"
-#include "public/platform/WebGraphicsContext3D.h"
-
-using namespace std;
-
-namespace WebCore {
-
-// Global resource ceiling (expressed in terms of pixels) for DrawingBuffer creation and resize.
-// When this limit is set, DrawingBuffer::create() and DrawingBuffer::reset() calls that would
-// exceed the global cap will instead clear the buffer.
-static const int s_maximumResourceUsePixels = 16 * 1024 * 1024;
-static int s_currentResourceUsePixels = 0;
-static const float s_resourceAdjustedRatio = 0.5;
-
-static const bool s_allowContextEvictionOnCreate = true;
-static const int s_maxScaleAttempts = 3;
-
-class ScopedTextureUnit0BindingRestorer {
-public:
- ScopedTextureUnit0BindingRestorer(GraphicsContext3D* context, GC3Denum activeTextureUnit, Platform3DObject textureUnitZeroId)
- : m_context(context)
- , m_oldActiveTextureUnit(activeTextureUnit)
- , m_oldTextureUnitZeroId(textureUnitZeroId)
- {
- m_context->activeTexture(GraphicsContext3D::TEXTURE0);
- }
- ~ScopedTextureUnit0BindingRestorer()
- {
- m_context->bindTexture(GraphicsContext3D::TEXTURE_2D, m_oldTextureUnitZeroId);
- m_context->activeTexture(m_oldActiveTextureUnit);
- }
-
-private:
- GraphicsContext3D* m_context;
- GC3Denum m_oldActiveTextureUnit;
- Platform3DObject m_oldTextureUnitZeroId;
-};
-
-PassRefPtr<DrawingBuffer> DrawingBuffer::create(GraphicsContext3D* context, const IntSize& size, PreserveDrawingBuffer preserve, PassRefPtr<ContextEvictionManager> contextEvictionManager)
-{
- Extensions3D* extensions = context->extensions();
- bool multisampleSupported = extensions->supports("GL_ANGLE_framebuffer_blit")
- && extensions->supports("GL_ANGLE_framebuffer_multisample")
- && extensions->supports("GL_OES_rgb8_rgba8");
- if (multisampleSupported) {
- extensions->ensureEnabled("GL_ANGLE_framebuffer_blit");
- extensions->ensureEnabled("GL_ANGLE_framebuffer_multisample");
- extensions->ensureEnabled("GL_OES_rgb8_rgba8");
- }
- bool packedDepthStencilSupported = extensions->supports("GL_OES_packed_depth_stencil");
- if (packedDepthStencilSupported)
- extensions->ensureEnabled("GL_OES_packed_depth_stencil");
-
- RefPtr<DrawingBuffer> drawingBuffer = adoptRef(new DrawingBuffer(context, size, multisampleSupported, packedDepthStencilSupported, preserve, contextEvictionManager));
- return drawingBuffer.release();
-}
-
-DrawingBuffer::DrawingBuffer(GraphicsContext3D* context,
- const IntSize& size,
- bool multisampleExtensionSupported,
- bool packedDepthStencilExtensionSupported,
- PreserveDrawingBuffer preserve,
- PassRefPtr<ContextEvictionManager> contextEvictionManager)
- : m_preserveDrawingBuffer(preserve)
- , m_scissorEnabled(false)
- , m_texture2DBinding(0)
- , m_framebufferBinding(0)
- , m_activeTextureUnit(GraphicsContext3D::TEXTURE0)
- , m_context(context)
- , m_size(-1, -1)
- , m_multisampleExtensionSupported(multisampleExtensionSupported)
- , m_packedDepthStencilExtensionSupported(packedDepthStencilExtensionSupported)
- , m_fbo(0)
- , m_colorBuffer(0)
- , m_frontColorBuffer(0)
- , m_depthStencilBuffer(0)
- , m_depthBuffer(0)
- , m_stencilBuffer(0)
- , m_multisampleFBO(0)
- , m_multisampleColorBuffer(0)
- , m_contentsChanged(true)
- , m_internalColorFormat(0)
- , m_colorFormat(0)
- , m_internalRenderbufferFormat(0)
- , m_maxTextureSize(0)
- , m_contextEvictionManager(contextEvictionManager)
-{
- // Used by browser tests to detect the use of a DrawingBuffer.
- TRACE_EVENT_INSTANT0("test_gpu", "DrawingBufferCreation");
- initialize(size);
-}
-
-DrawingBuffer::~DrawingBuffer()
-{
- releaseResources();
-}
-
-WebKit::WebGraphicsContext3D* DrawingBuffer::context()
-{
- if (!m_context)
- return 0;
- return m_context->webContext();
-}
-
-bool DrawingBuffer::prepareMailbox(WebKit::WebExternalTextureMailbox* outMailbox, WebKit::WebExternalBitmap* bitmap)
-{
- if (!m_context || !m_contentsChanged || !m_lastColorBuffer)
- return false;
-
- m_context->makeContextCurrent();
-
- // Resolve the multisampled buffer into the texture referenced by m_lastColorBuffer mailbox.
- if (multisample())
- commit();
-
- if (bitmap) {
- bitmap->setSize(size());
-
- unsigned char* pixels = bitmap->pixels();
- bool needPremultiply = m_attributes.alpha && !m_attributes.premultipliedAlpha;
- GraphicsContext3D::AlphaOp op = needPremultiply ? GraphicsContext3D::AlphaDoPremultiply : GraphicsContext3D::AlphaDoNothing;
- if (pixels)
- m_context->readBackFramebuffer(pixels, size().width(), size().height(), GraphicsContext3D::ReadbackSkia, op);
- }
-
- // We must restore the texture binding since creating new textures,
- // consuming and producing mailboxes changes it.
- ScopedTextureUnit0BindingRestorer restorer(m_context.get(), m_activeTextureUnit, m_texture2DBinding);
-
- // First try to recycle an old buffer.
- RefPtr<MailboxInfo> nextFrontColorBuffer = recycledMailbox();
-
- // No buffer available to recycle, create a new one.
- if (!nextFrontColorBuffer) {
- unsigned newColorBuffer = createColorTexture(m_size);
- // Bad things happened, abandon ship.
- if (!newColorBuffer)
- return false;
-
- nextFrontColorBuffer = createNewMailbox(newColorBuffer);
- }
-
- if (m_preserveDrawingBuffer == Discard) {
- m_colorBuffer = nextFrontColorBuffer->textureId;
- swap(nextFrontColorBuffer, m_lastColorBuffer);
- // It appears safe to overwrite the context's framebuffer binding in the Discard case since there will always be a
- // WebGLRenderingContext::clearIfComposited() call made before the next draw call which restores the framebuffer binding.
- // If this stops being true at some point, we should track the current framebuffer binding in the DrawingBuffer and restore
- // it after attaching the new back buffer here.
- m_context->bindFramebuffer(GraphicsContext3D::FRAMEBUFFER, m_fbo);
- m_context->framebufferTexture2D(GraphicsContext3D::FRAMEBUFFER, GraphicsContext3D::COLOR_ATTACHMENT0, GraphicsContext3D::TEXTURE_2D, m_colorBuffer, 0);
- } else {
- Extensions3D* extensions = m_context->extensions();
- extensions->copyTextureCHROMIUM(GraphicsContext3D::TEXTURE_2D, m_colorBuffer, nextFrontColorBuffer->textureId, 0, GraphicsContext3D::RGBA, GraphicsContext3D::UNSIGNED_BYTE);
- }
-
- if (multisample() && !m_framebufferBinding)
- bind();
- else
- restoreFramebufferBinding();
-
- m_contentsChanged = false;
-
- context()->bindTexture(GraphicsContext3D::TEXTURE_2D, nextFrontColorBuffer->textureId);
- context()->produceTextureCHROMIUM(GraphicsContext3D::TEXTURE_2D, nextFrontColorBuffer->mailbox.name);
- context()->flush();
- m_context->markLayerComposited();
-
- *outMailbox = nextFrontColorBuffer->mailbox;
- m_frontColorBuffer = nextFrontColorBuffer->textureId;
- return true;
-}
-
-void DrawingBuffer::mailboxReleased(const WebKit::WebExternalTextureMailbox& mailbox)
-{
- for (size_t i = 0; i < m_textureMailboxes.size(); i++) {
- RefPtr<MailboxInfo> mailboxInfo = m_textureMailboxes[i];
- if (!memcmp(mailboxInfo->mailbox.name, mailbox.name, sizeof(mailbox.name))) {
- mailboxInfo->mailbox.syncPoint = mailbox.syncPoint;
- m_recycledMailboxes.append(mailboxInfo.release());
- return;
- }
- }
- ASSERT_NOT_REACHED();
-}
-
-PassRefPtr<DrawingBuffer::MailboxInfo> DrawingBuffer::recycledMailbox()
-{
- if (!m_context || m_recycledMailboxes.isEmpty())
- return PassRefPtr<MailboxInfo>();
-
- RefPtr<MailboxInfo> mailboxInfo = m_recycledMailboxes.last().release();
- m_recycledMailboxes.removeLast();
-
- if (mailboxInfo->mailbox.syncPoint) {
- context()->waitSyncPoint(mailboxInfo->mailbox.syncPoint);
- mailboxInfo->mailbox.syncPoint = 0;
- }
-
- context()->bindTexture(GraphicsContext3D::TEXTURE_2D, mailboxInfo->textureId);
- context()->consumeTextureCHROMIUM(GraphicsContext3D::TEXTURE_2D, mailboxInfo->mailbox.name);
-
- if (mailboxInfo->size != m_size) {
- m_context->texImage2DResourceSafe(GraphicsContext3D::TEXTURE_2D, 0, m_internalColorFormat, m_size.width(), m_size.height(), 0, m_colorFormat, GraphicsContext3D::UNSIGNED_BYTE);
- mailboxInfo->size = m_size;
- }
-
- return mailboxInfo.release();
-}
-
-PassRefPtr<DrawingBuffer::MailboxInfo> DrawingBuffer::createNewMailbox(unsigned textureId)
-{
- RefPtr<MailboxInfo> returnMailbox = adoptRef(new MailboxInfo());
- context()->genMailboxCHROMIUM(returnMailbox->mailbox.name);
- returnMailbox->textureId = textureId;
- returnMailbox->size = m_size;
- m_textureMailboxes.append(returnMailbox);
- return returnMailbox.release();
-}
-
-void DrawingBuffer::initialize(const IntSize& size)
-{
- ASSERT(m_context);
- m_attributes = m_context->getContextAttributes();
-
- if (m_attributes.alpha) {
- m_internalColorFormat = GraphicsContext3D::RGBA;
- m_colorFormat = GraphicsContext3D::RGBA;
- m_internalRenderbufferFormat = Extensions3D::RGBA8_OES;
- } else {
- m_internalColorFormat = GraphicsContext3D::RGB;
- m_colorFormat = GraphicsContext3D::RGB;
- m_internalRenderbufferFormat = Extensions3D::RGB8_OES;
- }
-
- m_context->getIntegerv(GraphicsContext3D::MAX_TEXTURE_SIZE, &m_maxTextureSize);
-
- m_fbo = m_context->createFramebuffer();
-
- m_context->bindFramebuffer(GraphicsContext3D::FRAMEBUFFER, m_fbo);
- m_colorBuffer = createColorTexture();
- m_context->framebufferTexture2D(GraphicsContext3D::FRAMEBUFFER, GraphicsContext3D::COLOR_ATTACHMENT0, GraphicsContext3D::TEXTURE_2D, m_colorBuffer, 0);
- createSecondaryBuffers();
- reset(size);
- m_lastColorBuffer = createNewMailbox(m_colorBuffer);
-}
-
-unsigned DrawingBuffer::frontColorBuffer() const
-{
- return m_colorBuffer;
-}
-
-Platform3DObject DrawingBuffer::framebuffer() const
-{
- return m_fbo;
-}
-
-WebKit::WebLayer* DrawingBuffer::platformLayer()
-{
- if (!m_context)
- return 0;
-
- if (!m_layer) {
- m_layer = adoptPtr(WebKit::Platform::current()->compositorSupport()->createExternalTextureLayer(this));
-
- m_layer->setOpaque(!m_attributes.alpha);
- m_layer->setBlendBackgroundColor(m_attributes.alpha);
- m_layer->setPremultipliedAlpha(m_attributes.premultipliedAlpha);
- GraphicsLayer::registerContentsLayer(m_layer->layer());
- }
-
- return m_layer->layer();
-}
-
-void DrawingBuffer::paintCompositedResultsToCanvas(ImageBuffer* imageBuffer)
-{
- if (!m_context || !m_context->makeContextCurrent() || m_context->extensions()->getGraphicsResetStatusARB() != GraphicsContext3D::NO_ERROR)
- return;
-
- Extensions3D* extensions = m_context->extensions();
- // Since the m_frontColorBuffer was produced and sent to the compositor, it cannot be bound to an fbo.
- // We have to make a copy of it here and bind that copy instead.
- // FIXME: That's not true any more, provided we don't change texture
- // parameters.
- unsigned sourceTexture = createColorTexture(m_size);
- extensions->copyTextureCHROMIUM(GraphicsContext3D::TEXTURE_2D, m_frontColorBuffer, sourceTexture, 0, GraphicsContext3D::RGBA, GraphicsContext3D::UNSIGNED_BYTE);
-
- // Since we're using the same context as WebGL, we have to restore any state we change (in this case, just the framebuffer binding).
- // FIXME: The WebGLRenderingContext tracks the current framebuffer binding, it would be slightly more efficient to use this value
- // rather than querying it off of the context.
- GC3Dint previousFramebuffer = 0;
- m_context->getIntegerv(GraphicsContext3D::FRAMEBUFFER_BINDING, &previousFramebuffer);
-
- Platform3DObject framebuffer = m_context->createFramebuffer();
- m_context->bindFramebuffer(GraphicsContext3D::FRAMEBUFFER, framebuffer);
- m_context->framebufferTexture2D(GraphicsContext3D::FRAMEBUFFER, GraphicsContext3D::COLOR_ATTACHMENT0, GraphicsContext3D::TEXTURE_2D, sourceTexture, 0);
-
- extensions->paintFramebufferToCanvas(framebuffer, size().width(), size().height(), !m_attributes.premultipliedAlpha, imageBuffer);
- m_context->deleteFramebuffer(framebuffer);
- m_context->deleteTexture(sourceTexture);
-
- m_context->bindFramebuffer(GraphicsContext3D::FRAMEBUFFER, previousFramebuffer);
-}
-
-void DrawingBuffer::clearPlatformLayer()
-{
- if (m_layer)
- m_layer->clearTexture();
-
- if (m_context)
- m_context->flush();
-}
-
-void DrawingBuffer::releaseResources()
-{
- if (m_context) {
- m_context->makeContextCurrent();
-
- clearPlatformLayer();
-
- for (size_t i = 0; i < m_textureMailboxes.size(); i++)
- m_context->deleteTexture(m_textureMailboxes[i]->textureId);
-
- if (m_multisampleColorBuffer)
- m_context->deleteRenderbuffer(m_multisampleColorBuffer);
-
- if (m_depthStencilBuffer)
- m_context->deleteRenderbuffer(m_depthStencilBuffer);
-
- if (m_depthBuffer)
- m_context->deleteRenderbuffer(m_depthBuffer);
-
- if (m_stencilBuffer)
- m_context->deleteRenderbuffer(m_stencilBuffer);
-
- if (m_multisampleFBO)
- m_context->deleteFramebuffer(m_multisampleFBO);
-
- if (m_fbo)
- m_context->deleteFramebuffer(m_fbo);
-
- m_context.clear();
- }
-
- setSize(IntSize());
-
- m_colorBuffer = 0;
- m_frontColorBuffer = 0;
- m_multisampleColorBuffer = 0;
- m_depthStencilBuffer = 0;
- m_depthBuffer = 0;
- m_stencilBuffer = 0;
- m_multisampleFBO = 0;
- m_fbo = 0;
- m_contextEvictionManager.clear();
-
- m_lastColorBuffer.clear();
- m_recycledMailboxes.clear();
- m_textureMailboxes.clear();
-
- if (m_layer) {
- GraphicsLayer::unregisterContentsLayer(m_layer->layer());
- m_layer.clear();
- }
-}
-
-unsigned DrawingBuffer::createColorTexture(const IntSize& size)
-{
- if (!m_context)
- return 0;
-
- unsigned offscreenColorTexture = m_context->createTexture();
- if (!offscreenColorTexture)
- return 0;
-
- m_context->bindTexture(GraphicsContext3D::TEXTURE_2D, offscreenColorTexture);
- m_context->texParameteri(GraphicsContext3D::TEXTURE_2D, GraphicsContext3D::TEXTURE_MAG_FILTER, GraphicsContext3D::LINEAR);
- m_context->texParameteri(GraphicsContext3D::TEXTURE_2D, GraphicsContext3D::TEXTURE_MIN_FILTER, GraphicsContext3D::LINEAR);
- m_context->texParameteri(GraphicsContext3D::TEXTURE_2D, GraphicsContext3D::TEXTURE_WRAP_S, GraphicsContext3D::CLAMP_TO_EDGE);
- m_context->texParameteri(GraphicsContext3D::TEXTURE_2D, GraphicsContext3D::TEXTURE_WRAP_T, GraphicsContext3D::CLAMP_TO_EDGE);
- if (!size.isEmpty())
- m_context->texImage2DResourceSafe(GraphicsContext3D::TEXTURE_2D, 0, m_internalColorFormat, size.width(), size.height(), 0, m_colorFormat, GraphicsContext3D::UNSIGNED_BYTE);
-
- return offscreenColorTexture;
-}
-
-void DrawingBuffer::createSecondaryBuffers()
-{
- // create a multisample FBO
- if (multisample()) {
- m_multisampleFBO = m_context->createFramebuffer();
- m_context->bindFramebuffer(GraphicsContext3D::FRAMEBUFFER, m_multisampleFBO);
- m_multisampleColorBuffer = m_context->createRenderbuffer();
- }
-}
-
-bool DrawingBuffer::resizeFramebuffer(const IntSize& size)
-{
- // resize regular FBO
- m_context->bindFramebuffer(GraphicsContext3D::FRAMEBUFFER, m_fbo);
-
- m_context->bindTexture(GraphicsContext3D::TEXTURE_2D, m_colorBuffer);
- m_context->texImage2DResourceSafe(GraphicsContext3D::TEXTURE_2D, 0, m_internalColorFormat, size.width(), size.height(), 0, m_colorFormat, GraphicsContext3D::UNSIGNED_BYTE);
- if (m_lastColorBuffer)
- m_lastColorBuffer->size = m_size;
-
- m_context->framebufferTexture2D(GraphicsContext3D::FRAMEBUFFER, GraphicsContext3D::COLOR_ATTACHMENT0, GraphicsContext3D::TEXTURE_2D, m_colorBuffer, 0);
-
- m_context->bindTexture(GraphicsContext3D::TEXTURE_2D, 0);
-
- if (!multisample())
- resizeDepthStencil(size, 0);
- if (m_context->checkFramebufferStatus(GraphicsContext3D::FRAMEBUFFER) != GraphicsContext3D::FRAMEBUFFER_COMPLETE)
- return false;
-
- return true;
-}
-
-bool DrawingBuffer::resizeMultisampleFramebuffer(const IntSize& size)
-{
- if (multisample()) {
- int maxSampleCount = 0;
-
- m_context->getIntegerv(Extensions3D::MAX_SAMPLES, &maxSampleCount);
- int sampleCount = std::min(4, maxSampleCount);
-
- m_context->bindFramebuffer(GraphicsContext3D::FRAMEBUFFER, m_multisampleFBO);
-
- m_context->bindRenderbuffer(GraphicsContext3D::RENDERBUFFER, m_multisampleColorBuffer);
- m_context->extensions()->renderbufferStorageMultisample(GraphicsContext3D::RENDERBUFFER, sampleCount, m_internalRenderbufferFormat, size.width(), size.height());
-
- if (m_context->getError() == GraphicsContext3D::OUT_OF_MEMORY)
- return false;
-
- m_context->framebufferRenderbuffer(GraphicsContext3D::FRAMEBUFFER, GraphicsContext3D::COLOR_ATTACHMENT0, GraphicsContext3D::RENDERBUFFER, m_multisampleColorBuffer);
- resizeDepthStencil(size, sampleCount);
- if (m_context->checkFramebufferStatus(GraphicsContext3D::FRAMEBUFFER) != GraphicsContext3D::FRAMEBUFFER_COMPLETE)
- return false;
- }
-
- return true;
-}
-
-void DrawingBuffer::resizeDepthStencil(const IntSize& size, int sampleCount)
-{
- if (m_attributes.depth && m_attributes.stencil && m_packedDepthStencilExtensionSupported) {
- if (!m_depthStencilBuffer)
- m_depthStencilBuffer = m_context->createRenderbuffer();
- m_context->bindRenderbuffer(GraphicsContext3D::RENDERBUFFER, m_depthStencilBuffer);
- if (multisample())
- m_context->extensions()->renderbufferStorageMultisample(GraphicsContext3D::RENDERBUFFER, sampleCount, Extensions3D::DEPTH24_STENCIL8, size.width(), size.height());
- else
- m_context->renderbufferStorage(GraphicsContext3D::RENDERBUFFER, Extensions3D::DEPTH24_STENCIL8, size.width(), size.height());
- m_context->framebufferRenderbuffer(GraphicsContext3D::FRAMEBUFFER, GraphicsContext3D::STENCIL_ATTACHMENT, GraphicsContext3D::RENDERBUFFER, m_depthStencilBuffer);
- m_context->framebufferRenderbuffer(GraphicsContext3D::FRAMEBUFFER, GraphicsContext3D::DEPTH_ATTACHMENT, GraphicsContext3D::RENDERBUFFER, m_depthStencilBuffer);
- } else {
- if (m_attributes.depth) {
- if (!m_depthBuffer)
- m_depthBuffer = m_context->createRenderbuffer();
- m_context->bindRenderbuffer(GraphicsContext3D::RENDERBUFFER, m_depthBuffer);
- if (multisample())
- m_context->extensions()->renderbufferStorageMultisample(GraphicsContext3D::RENDERBUFFER, sampleCount, GraphicsContext3D::DEPTH_COMPONENT16, size.width(), size.height());
- else
- m_context->renderbufferStorage(GraphicsContext3D::RENDERBUFFER, GraphicsContext3D::DEPTH_COMPONENT16, size.width(), size.height());
- m_context->framebufferRenderbuffer(GraphicsContext3D::FRAMEBUFFER, GraphicsContext3D::DEPTH_ATTACHMENT, GraphicsContext3D::RENDERBUFFER, m_depthBuffer);
- }
- if (m_attributes.stencil) {
- if (!m_stencilBuffer)
- m_stencilBuffer = m_context->createRenderbuffer();
- m_context->bindRenderbuffer(GraphicsContext3D::RENDERBUFFER, m_stencilBuffer);
- if (multisample())
- m_context->extensions()->renderbufferStorageMultisample(GraphicsContext3D::RENDERBUFFER, sampleCount, GraphicsContext3D::STENCIL_INDEX8, size.width(), size.height());
- else
- m_context->renderbufferStorage(GraphicsContext3D::RENDERBUFFER, GraphicsContext3D::STENCIL_INDEX8, size.width(), size.height());
- m_context->framebufferRenderbuffer(GraphicsContext3D::FRAMEBUFFER, GraphicsContext3D::STENCIL_ATTACHMENT, GraphicsContext3D::RENDERBUFFER, m_stencilBuffer);
- }
- }
- m_context->bindRenderbuffer(GraphicsContext3D::RENDERBUFFER, 0);
-}
-
-
-
-void DrawingBuffer::clearFramebuffers(GC3Dbitfield clearMask)
-{
- if (!m_context)
- return;
-
- m_context->bindFramebuffer(GraphicsContext3D::FRAMEBUFFER, m_multisampleFBO ? m_multisampleFBO : m_fbo);
-
- m_context->clear(clearMask);
-
- // The multisample fbo was just cleared, but we also need to clear the non-multisampled buffer too.
- if (m_multisampleFBO) {
- m_context->bindFramebuffer(GraphicsContext3D::FRAMEBUFFER, m_fbo);
- m_context->clear(GraphicsContext3D::COLOR_BUFFER_BIT);
- m_context->bindFramebuffer(GraphicsContext3D::FRAMEBUFFER, m_multisampleFBO);
- }
-}
-
-void DrawingBuffer::setSize(const IntSize& size) {
- if (m_size == size)
- return;
-
- s_currentResourceUsePixels += pixelDelta(size);
- m_size = size;
-}
-
-int DrawingBuffer::pixelDelta(const IntSize& size) {
- return (max(0, size.width()) * max(0, size.height())) - (max(0, m_size.width()) * max(0, m_size.height()));
-}
-
-IntSize DrawingBuffer::adjustSize(const IntSize& size) {
- IntSize adjustedSize = size;
-
- // Clamp if the desired size is greater than the maximum texture size for the device.
- if (adjustedSize.height() > m_maxTextureSize)
- adjustedSize.setHeight(m_maxTextureSize);
-
- if (adjustedSize.width() > m_maxTextureSize)
- adjustedSize.setWidth(m_maxTextureSize);
-
- // Try progressively smaller sizes until we find a size that fits or reach a scale limit.
- int scaleAttempts = 0;
- while ((s_currentResourceUsePixels + pixelDelta(adjustedSize)) > s_maximumResourceUsePixels) {
- scaleAttempts++;
- if (scaleAttempts > s_maxScaleAttempts)
- return IntSize();
-
- adjustedSize.scale(s_resourceAdjustedRatio);
-
- if (adjustedSize.isEmpty())
- return IntSize();
- }
-
- return adjustedSize;
-}
-
-IntSize DrawingBuffer::adjustSizeWithContextEviction(const IntSize& size, bool& evictContext) {
- IntSize adjustedSize = adjustSize(size);
- if (!adjustedSize.isEmpty()) {
- evictContext = false;
- return adjustedSize; // Buffer fits without evicting a context.
- }
-
- // Speculatively adjust the pixel budget to see if the buffer would fit should the oldest context be evicted.
- IntSize oldestSize = m_contextEvictionManager->oldestContextSize();
- int pixelDelta = oldestSize.width() * oldestSize.height();
-
- s_currentResourceUsePixels -= pixelDelta;
- adjustedSize = adjustSize(size);
- s_currentResourceUsePixels += pixelDelta;
-
- evictContext = !adjustedSize.isEmpty();
- return adjustedSize;
-}
-
-void DrawingBuffer::reset(const IntSize& newSize)
-{
- if (!m_context)
- return;
-
- IntSize adjustedSize;
- bool evictContext = false;
- bool isNewContext = m_size.isEmpty();
- if (s_allowContextEvictionOnCreate && isNewContext)
- adjustedSize = adjustSizeWithContextEviction(newSize, evictContext);
- else
- adjustedSize = adjustSize(newSize);
-
- if (adjustedSize.isEmpty())
- return;
-
- if (evictContext)
- m_contextEvictionManager->forciblyLoseOldestContext("WARNING: WebGL contexts have exceeded the maximum allowed backbuffer area. Oldest context will be lost.");
-
- if (adjustedSize != m_size) {
- do {
- // resize multisample FBO
- if (!resizeMultisampleFramebuffer(adjustedSize) || !resizeFramebuffer(adjustedSize)) {
- adjustedSize.scale(s_resourceAdjustedRatio);
- continue;
- }
- break;
- } while (!adjustedSize.isEmpty());
-
- setSize(adjustedSize);
-
- if (adjustedSize.isEmpty())
- return;
- }
-
- m_context->disable(GraphicsContext3D::SCISSOR_TEST);
- m_context->clearColor(0, 0, 0, 0);
- m_context->colorMask(true, true, true, true);
-
- GC3Dbitfield clearMask = GraphicsContext3D::COLOR_BUFFER_BIT;
- if (m_attributes.depth) {
- m_context->clearDepth(1.0f);
- clearMask |= GraphicsContext3D::DEPTH_BUFFER_BIT;
- m_context->depthMask(true);
- }
- if (m_attributes.stencil) {
- m_context->clearStencil(0);
- clearMask |= GraphicsContext3D::STENCIL_BUFFER_BIT;
- m_context->stencilMaskSeparate(GraphicsContext3D::FRONT, 0xFFFFFFFF);
- }
-
- clearFramebuffers(clearMask);
-}
-
-void DrawingBuffer::commit(long x, long y, long width, long height)
-{
- if (!m_context)
- return;
-
- if (width < 0)
- width = m_size.width();
- if (height < 0)
- height = m_size.height();
-
- m_context->makeContextCurrent();
-
- if (m_multisampleFBO) {
- m_context->bindFramebuffer(Extensions3D::READ_FRAMEBUFFER, m_multisampleFBO);
- m_context->bindFramebuffer(Extensions3D::DRAW_FRAMEBUFFER, m_fbo);
-
- if (m_scissorEnabled)
- m_context->disable(GraphicsContext3D::SCISSOR_TEST);
-
- // Use NEAREST, because there is no scale performed during the blit.
- m_context->extensions()->blitFramebuffer(x, y, width, height, x, y, width, height, GraphicsContext3D::COLOR_BUFFER_BIT, GraphicsContext3D::NEAREST);
-
- if (m_scissorEnabled)
- m_context->enable(GraphicsContext3D::SCISSOR_TEST);
- }
-
- m_context->bindFramebuffer(GraphicsContext3D::FRAMEBUFFER, m_fbo);
-}
-
-void DrawingBuffer::restoreFramebufferBinding()
-{
- if (!m_context || !m_framebufferBinding)
- return;
-
- m_context->bindFramebuffer(GraphicsContext3D::FRAMEBUFFER, m_framebufferBinding);
-}
-
-bool DrawingBuffer::multisample() const
-{
- return m_attributes.antialias && m_multisampleExtensionSupported;
-}
-
-void DrawingBuffer::bind()
-{
- if (!m_context)
- return;
-
- m_context->bindFramebuffer(GraphicsContext3D::FRAMEBUFFER, m_multisampleFBO ? m_multisampleFBO : m_fbo);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/gpu/DrawingBuffer.h b/chromium/third_party/WebKit/Source/core/platform/graphics/gpu/DrawingBuffer.h
deleted file mode 100644
index a6f11d8f243..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/gpu/DrawingBuffer.h
+++ /dev/null
@@ -1,213 +0,0 @@
-/*
- * Copyright (c) 2010, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef DrawingBuffer_h
-#define DrawingBuffer_h
-
-#include "core/platform/graphics/GraphicsContext3D.h"
-#include "core/platform/graphics/GraphicsTypes3D.h"
-#include "core/platform/graphics/IntSize.h"
-
-#include "public/platform/WebExternalTextureLayerClient.h"
-#include "public/platform/WebExternalTextureMailbox.h"
-#include "wtf/Noncopyable.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/PassOwnPtr.h"
-
-namespace WebKit {
-class WebExternalBitmap;
-class WebExternalTextureLayer;
-class WebGraphicsContext3D;
-class WebLayer;
-}
-
-namespace WebCore {
-class GraphicsContext3D;
-class ImageData;
-
-// Abstract interface to allow basic context eviction management
-class ContextEvictionManager : public RefCounted<ContextEvictionManager> {
-public:
- virtual ~ContextEvictionManager() {};
-
- virtual void forciblyLoseOldestContext(const String& reason) = 0;
- virtual IntSize oldestContextSize() = 0;
-};
-
-// Manages a rendering target (framebuffer + attachment) for a canvas. Can publish its rendering
-// results to a WebKit::WebLayer for compositing.
-class DrawingBuffer : public RefCounted<DrawingBuffer>, public WebKit::WebExternalTextureLayerClient {
- struct MailboxInfo : public RefCounted<MailboxInfo> {
- WebKit::WebExternalTextureMailbox mailbox;
- unsigned textureId;
- IntSize size;
- };
-public:
- enum PreserveDrawingBuffer {
- Preserve,
- Discard
- };
-
- static PassRefPtr<DrawingBuffer> create(GraphicsContext3D*, const IntSize&, PreserveDrawingBuffer, PassRefPtr<ContextEvictionManager>);
-
- ~DrawingBuffer();
-
- // Clear all resources from this object, as well as context. Called when context is destroyed
- // to prevent invalid accesses to the resources.
- void releaseResources();
-
- // Issues a glClear() on all framebuffers associated with this DrawingBuffer. The caller is responsible for
- // making the context current and setting the clear values and masks. Modifies the framebuffer binding.
- void clearFramebuffers(GC3Dbitfield clearMask);
-
- // Given the desired buffer size, provides the largest dimensions that will fit in the pixel budget.
- IntSize adjustSize(const IntSize&);
- void reset(const IntSize&);
- void bind();
- IntSize size() const { return m_size; }
- bool isZeroSized() const { return m_size.isEmpty(); }
-
- // Copies the multisample color buffer to the normal color buffer and leaves m_fbo bound.
- void commit(long x = 0, long y = 0, long width = -1, long height = -1);
-
- // commit should copy the full multisample buffer, and not respect the
- // current scissor bounds. Track the state of the scissor test so that it
- // can be disabled during calls to commit.
- void setScissorEnabled(bool scissorEnabled) { m_scissorEnabled = scissorEnabled; }
-
- // The DrawingBuffer needs to track the texture bound to texture unit 0.
- // The bound texture is tracked to avoid costly queries during rendering.
- void setTexture2DBinding(Platform3DObject texture) { m_texture2DBinding = texture; }
-
- // The DrawingBuffer needs to track the currently bound framebuffer so it
- // restore the binding when needed.
- void setFramebufferBinding(Platform3DObject fbo) { m_framebufferBinding = fbo; }
-
- // Track the currently active texture unit. Texture unit 0 is used as host for a scratch
- // texture.
- void setActiveTextureUnit(GC3Dint textureUnit) { m_activeTextureUnit = textureUnit; }
-
- bool multisample() const;
-
- Platform3DObject framebuffer() const;
-
- void markContentsChanged() { m_contentsChanged = true; }
-
- WebKit::WebLayer* platformLayer();
- void paintCompositedResultsToCanvas(ImageBuffer*);
-
- // WebExternalTextureLayerClient implementation.
- virtual WebKit::WebGraphicsContext3D* context() OVERRIDE;
- virtual bool prepareMailbox(WebKit::WebExternalTextureMailbox*, WebKit::WebExternalBitmap*) OVERRIDE;
- virtual void mailboxReleased(const WebKit::WebExternalTextureMailbox&) OVERRIDE;
-
-private:
- DrawingBuffer(GraphicsContext3D*, const IntSize&, bool multisampleExtensionSupported,
- bool packedDepthStencilExtensionSupported, PreserveDrawingBuffer, PassRefPtr<ContextEvictionManager>);
-
- void initialize(const IntSize&);
-
- Platform3DObject frontColorBuffer() const;
- Platform3DObject colorBuffer() const { return m_colorBuffer; }
-
- unsigned createColorTexture(const IntSize& size = IntSize());
- // Create the depth/stencil and multisample buffers, if needed.
- void createSecondaryBuffers();
- bool resizeFramebuffer(const IntSize&);
- bool resizeMultisampleFramebuffer(const IntSize&);
- void resizeDepthStencil(const IntSize&, int sampleCount);
-
- // Bind to the m_framebufferBinding if it's not 0.
- void restoreFramebufferBinding();
-
- void clearPlatformLayer();
-
- PassRefPtr<MailboxInfo> recycledMailbox();
- PassRefPtr<MailboxInfo> createNewMailbox(unsigned);
-
- // Updates the current size of the buffer, ensuring that s_currentResourceUsePixels is updated.
- void setSize(const IntSize& size);
-
- // Calculates the difference in pixels between the current buffer size and the proposed size.
- int pixelDelta(const IntSize& size);
-
- // Given the desired buffer size, provides the largest dimensions that will fit in the pixel budget
- // Returns true if the buffer will only fit if the oldest WebGL context is forcibly lost
- IntSize adjustSizeWithContextEviction(const IntSize&, bool& evictContext);
-
- PreserveDrawingBuffer m_preserveDrawingBuffer;
- bool m_scissorEnabled;
- Platform3DObject m_texture2DBinding;
- Platform3DObject m_framebufferBinding;
- GC3Denum m_activeTextureUnit;
-
- RefPtr<GraphicsContext3D> m_context;
- IntSize m_size;
- bool m_multisampleExtensionSupported;
- bool m_packedDepthStencilExtensionSupported;
- Platform3DObject m_fbo;
- Platform3DObject m_colorBuffer;
- Platform3DObject m_frontColorBuffer;
- bool m_separateFrontTexture;
-
- // This is used when we have OES_packed_depth_stencil.
- Platform3DObject m_depthStencilBuffer;
-
- // These are used when we don't.
- Platform3DObject m_depthBuffer;
- Platform3DObject m_stencilBuffer;
-
- // For multisampling.
- Platform3DObject m_multisampleFBO;
- Platform3DObject m_multisampleColorBuffer;
-
- // True if our contents have been modified since the last presentation of this buffer.
- bool m_contentsChanged;
-
- GraphicsContext3D::Attributes m_attributes;
- unsigned m_internalColorFormat;
- unsigned m_colorFormat;
- unsigned m_internalRenderbufferFormat;
- int m_maxTextureSize;
-
- OwnPtr<WebKit::WebExternalTextureLayer> m_layer;
-
- // All of the mailboxes that this DrawingBuffer has ever created.
- Vector<RefPtr<MailboxInfo> > m_textureMailboxes;
- // Mailboxes that were released by the compositor and can be used again by this DrawingBuffer.
- Vector<RefPtr<MailboxInfo> > m_recycledMailboxes;
- RefPtr<MailboxInfo> m_lastColorBuffer;
-
- RefPtr<ContextEvictionManager> m_contextEvictionManager;
-};
-
-} // namespace WebCore
-
-#endif // DrawingBuffer_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/gpu/DrawingBufferTest.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/gpu/DrawingBufferTest.cpp
deleted file mode 100644
index 7b393101989..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/gpu/DrawingBufferTest.cpp
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/platform/graphics/gpu/DrawingBuffer.h"
-
-#include "core/platform/graphics/GraphicsContext3D.h"
-#include "core/tests/FakeWebGraphicsContext3D.h"
-#include "public/platform/Platform.h"
-#include "wtf/RefPtr.h"
-
-#include <gmock/gmock.h>
-#include <gtest/gtest.h>
-
-using namespace WebCore;
-using namespace WebKit;
-using testing::Test;
-using testing::_;
-
-namespace {
-
-class FakeContextEvictionManager : public ContextEvictionManager {
-public:
- void forciblyLoseOldestContext(const String& reason) { }
- IntSize oldestContextSize() { return IntSize(); }
-};
-
-} // namespace
-
-class DrawingBufferTest : public Test {
-protected:
- virtual void SetUp()
- {
- RefPtr<FakeContextEvictionManager> contextEvictionManager = adoptRef(new FakeContextEvictionManager());
- RefPtr<GraphicsContext3D> context = GraphicsContext3D::createGraphicsContextFromWebContext(adoptPtr(new FakeWebGraphicsContext3D));
- const IntSize size(100, 100);
- m_drawingBuffer = DrawingBuffer::create(context.get(), size, DrawingBuffer::Discard, contextEvictionManager.release());
- }
-
- RefPtr<DrawingBuffer> m_drawingBuffer;
-};
-
-namespace {
-
-TEST_F(DrawingBufferTest, verifyNoNewBuffersAfterContextLostWithMailboxes)
-{
- // Tell the buffer its contents changed and context was lost.
- m_drawingBuffer->markContentsChanged();
- m_drawingBuffer->releaseResources();
-
- WebKit::WebExternalTextureMailbox mailbox;
- EXPECT_FALSE(m_drawingBuffer->prepareMailbox(&mailbox, 0));
-}
-
-} // namespace
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/gpu/SharedGraphicsContext3D.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/gpu/SharedGraphicsContext3D.cpp
deleted file mode 100644
index 11af84b3451..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/gpu/SharedGraphicsContext3D.cpp
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-
-#include "config.h"
-
-#include "core/platform/graphics/gpu/SharedGraphicsContext3D.h"
-
-#include "core/platform/graphics/Extensions3D.h"
-#include "core/platform/graphics/GraphicsContext3D.h"
-#include "public/platform/Platform.h"
-#include "public/platform/WebGraphicsContext3D.h"
-#include "public/platform/WebGraphicsContext3DProvider.h"
-#include "wtf/MainThread.h"
-
-namespace WebCore {
-
-class SharedGraphicsContext3DImpl {
-public:
- SharedGraphicsContext3DImpl() : m_context(0) { }
-
- PassRefPtr<GraphicsContext3D> getOrCreateContext()
- {
- bool wasCreated = false;
-
- OwnPtr<WebKit::WebGraphicsContext3DProvider> provider = adoptPtr(WebKit::Platform::current()->createSharedOffscreenGraphicsContext3DProvider());
-
- WebKit::WebGraphicsContext3D* webContext = 0;
- GrContext* grContext = 0;
-
- if (provider) {
- webContext = provider->context3d();
- grContext = provider->grContext();
- }
-
- if (webContext && grContext) {
- WebKit::WebGraphicsContext3D* oldWebContext = m_context ? m_context->webContext() : 0;
- GrContext* oldGrContext = m_context ? m_context->grContext() : 0;
- if (webContext != oldWebContext || grContext != oldGrContext)
- m_context.clear();
-
- if (!m_context) {
- m_context = GraphicsContext3D::createGraphicsContextFromProvider(provider.release());
- wasCreated = true;
- }
- }
-
- if (m_context && wasCreated)
- m_context->extensions()->pushGroupMarkerEXT("SharedGraphicsContext");
- return m_context;
- }
-
-private:
- RefPtr<GraphicsContext3D> m_context;
-};
-
-PassRefPtr<GraphicsContext3D> SharedGraphicsContext3D::get()
-{
- DEFINE_STATIC_LOCAL(SharedGraphicsContext3DImpl, impl, ());
- return impl.getOrCreateContext();
-}
-
-} // namespace WebCore
-
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/gpu/SharedGraphicsContext3D.h b/chromium/third_party/WebKit/Source/core/platform/graphics/gpu/SharedGraphicsContext3D.h
deleted file mode 100644
index 4525ee80cd0..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/gpu/SharedGraphicsContext3D.h
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SharedGraphicsContext3D_h
-#define SharedGraphicsContext3D_h
-
-#include "core/platform/graphics/GraphicsContext3D.h"
-#include "wtf/RefCounted.h"
-#include "wtf/RefPtr.h"
-
-namespace WebCore {
-
-class SharedGraphicsContext3D {
-public:
- // The caller may ref this pointer, and hang onto it as long as they like.
- // However, the context should be checked periodically to determine if it
- // has been lost. The easiest way to do that is to simply call this
- // function again. Note that the return value may be 0 if the
- // GPU is unavailable.
- static PassRefPtr<GraphicsContext3D> get();
-};
-
-}
-
-#endif // SharedGraphicsContext3D_h
-
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/harfbuzz/FontHarfBuzz.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/harfbuzz/FontHarfBuzz.cpp
deleted file mode 100644
index f5ab6736f0c..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/harfbuzz/FontHarfBuzz.cpp
+++ /dev/null
@@ -1,200 +0,0 @@
-/*
- * Copyright (c) 2007, 2008, 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/Font.h"
-
-#include "core/platform/NotImplemented.h"
-#include "core/platform/graphics/FloatRect.h"
-#include "core/platform/graphics/GlyphBuffer.h"
-#include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/graphics/SimpleFontData.h"
-#include "core/platform/graphics/harfbuzz/HarfBuzzShaper.h"
-
-#include "SkPaint.h"
-#include "SkTemplates.h"
-
-#include "wtf/unicode/Unicode.h"
-
-namespace WebCore {
-
-bool Font::canReturnFallbackFontsForComplexText()
-{
- return false;
-}
-
-bool Font::canExpandAroundIdeographsInComplexText()
-{
- return false;
-}
-
-void Font::drawGlyphs(GraphicsContext* gc, const SimpleFontData* font,
- const GlyphBuffer& glyphBuffer, int from, int numGlyphs,
- const FloatPoint& point, const FloatRect& textRect) const {
- SkASSERT(sizeof(GlyphBufferGlyph) == sizeof(uint16_t)); // compile-time assert
-
- const GlyphBufferGlyph* glyphs = glyphBuffer.glyphs(from);
- SkScalar x = SkFloatToScalar(point.x());
- SkScalar y = SkFloatToScalar(point.y());
-
- // FIXME: text rendering speed:
- // Android has code in their WebCore fork to special case when the
- // GlyphBuffer has no advances other than the defaults. In that case the
- // text drawing can proceed faster. However, it's unclear when those
- // patches may be upstreamed to WebKit so we always use the slower path
- // here.
- const GlyphBufferAdvance* adv = glyphBuffer.advances(from);
- SkAutoSTMalloc<32, SkPoint> storage(numGlyphs), storage2(numGlyphs), storage3(numGlyphs);
- SkPoint* pos = storage.get();
- SkPoint* vPosBegin = storage2.get();
- SkPoint* vPosEnd = storage3.get();
-
- bool isVertical = font->platformData().orientation() == Vertical;
- for (int i = 0; i < numGlyphs; i++) {
- SkScalar myWidth = SkFloatToScalar(adv[i].width());
- pos[i].set(x, y);
- if (isVertical) {
- vPosBegin[i].set(x + myWidth, y);
- vPosEnd[i].set(x + myWidth, y - myWidth);
- }
- x += myWidth;
- y += SkFloatToScalar(adv[i].height());
- }
-
- TextDrawingModeFlags textMode = gc->textDrawingMode();
-
- // We draw text up to two times (once for fill, once for stroke).
- if (textMode & TextModeFill) {
- SkPaint paint;
- gc->setupPaintForFilling(&paint);
- font->platformData().setupPaint(&paint);
- gc->adjustTextRenderMode(&paint);
- paint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
-
- if (isVertical) {
- SkPath path;
- for (int i = 0; i < numGlyphs; ++i) {
- path.reset();
- path.moveTo(vPosBegin[i]);
- path.lineTo(vPosEnd[i]);
- gc->drawTextOnPath(glyphs + i, 2, path, textRect, 0, paint);
- }
- } else
- gc->drawPosText(glyphs, numGlyphs << 1, pos, textRect, paint);
- }
-
- if ((textMode & TextModeStroke)
- && gc->strokeStyle() != NoStroke
- && gc->strokeThickness() > 0) {
-
- SkPaint paint;
- gc->setupPaintForStroking(&paint);
- font->platformData().setupPaint(&paint);
- gc->adjustTextRenderMode(&paint);
- paint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
-
- if (textMode & TextModeFill) {
- // If we also filled, we don't want to draw shadows twice.
- // See comment in FontChromiumWin.cpp::paintSkiaText() for more details.
- // Since we use the looper for shadows, we remove it (if any) now.
- paint.setLooper(0);
- }
-
- if (isVertical) {
- SkPath path;
- for (int i = 0; i < numGlyphs; ++i) {
- path.reset();
- path.moveTo(vPosBegin[i]);
- path.lineTo(vPosEnd[i]);
- gc->drawTextOnPath(glyphs + i, 2, path, textRect, 0, paint);
- }
- } else
- gc->drawPosText(glyphs, numGlyphs << 1, pos, textRect, paint);
- }
-}
-
-void Font::drawComplexText(GraphicsContext* gc, const TextRunPaintInfo& runInfo, const FloatPoint& point) const
-{
- if (!runInfo.run.length())
- return;
-
- TextDrawingModeFlags textMode = gc->textDrawingMode();
- bool fill = textMode & TextModeFill;
- bool stroke = (textMode & TextModeStroke)
- && gc->strokeStyle() != NoStroke
- && gc->strokeThickness() > 0;
-
- if (!fill && !stroke)
- return;
-
- GlyphBuffer glyphBuffer;
- HarfBuzzShaper shaper(this, runInfo.run);
- shaper.setDrawRange(runInfo.from, runInfo.to);
- if (!shaper.shape(&glyphBuffer))
- return;
- FloatPoint adjustedPoint = shaper.adjustStartPoint(point);
- drawGlyphBuffer(gc, runInfo, glyphBuffer, adjustedPoint);
-}
-
-void Font::drawEmphasisMarksForComplexText(GraphicsContext* /* context */, const TextRunPaintInfo& /* runInfo */, const AtomicString& /* mark */, const FloatPoint& /* point */) const
-{
- notImplemented();
-}
-
-float Font::floatWidthForComplexText(const TextRun& run, HashSet<const SimpleFontData*>* /* fallbackFonts */, GlyphOverflow* /* glyphOverflow */) const
-{
- HarfBuzzShaper shaper(this, run);
- if (!shaper.shape())
- return 0;
- return shaper.totalWidth();
-}
-
-// Return the code point index for the given |x| offset into the text run.
-int Font::offsetForPositionForComplexText(const TextRun& run, float xFloat,
- bool includePartialGlyphs) const
-{
- HarfBuzzShaper shaper(this, run);
- if (!shaper.shape())
- return 0;
- return shaper.offsetForPosition(xFloat);
-}
-
-// Return the rectangle for selecting the given range of code-points in the TextRun.
-FloatRect Font::selectionRectForComplexText(const TextRun& run,
- const FloatPoint& point, int height,
- int from, int to) const
-{
- HarfBuzzShaper shaper(this, run);
- if (!shaper.shape())
- return FloatRect();
- return shaper.selectionRect(point, height, from, to);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/harfbuzz/FontPlatformDataHarfBuzz.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/harfbuzz/FontPlatformDataHarfBuzz.cpp
deleted file mode 100644
index e86b3416a04..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/harfbuzz/FontPlatformDataHarfBuzz.cpp
+++ /dev/null
@@ -1,315 +0,0 @@
-/*
- * Copyright (c) 2006, 2007, 2008, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/harfbuzz/FontPlatformDataHarfBuzz.h"
-
-#include "RuntimeEnabledFeatures.h"
-#include "SkPaint.h"
-#include "SkTypeface.h"
-#include "core/platform/NotImplemented.h"
-#include "core/platform/graphics/FontCache.h"
-#include "core/platform/graphics/harfbuzz/HarfBuzzFace.h"
-
-#include "public/platform/linux/WebFontInfo.h"
-#include "public/platform/linux/WebFontRenderStyle.h"
-#include "public/platform/linux/WebSandboxSupport.h"
-#include "public/platform/Platform.h"
-#include "wtf/text/StringImpl.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-static SkPaint::Hinting skiaHinting = SkPaint::kNormal_Hinting;
-static bool useSkiaAutoHint = true;
-static bool useSkiaBitmaps = true;
-static bool useSkiaAntiAlias = true;
-static bool useSkiaSubpixelRendering = false;
-static bool useSkiaSubpixelPositioning = false;
-
-void FontPlatformData::setHinting(SkPaint::Hinting hinting)
-{
- skiaHinting = hinting;
-}
-
-void FontPlatformData::setAutoHint(bool useAutoHint)
-{
- useSkiaAutoHint = useAutoHint;
-}
-
-void FontPlatformData::setUseBitmaps(bool useBitmaps)
-{
- useSkiaBitmaps = useBitmaps;
-}
-
-void FontPlatformData::setAntiAlias(bool useAntiAlias)
-{
- useSkiaAntiAlias = useAntiAlias;
-}
-
-void FontPlatformData::setSubpixelRendering(bool useSubpixelRendering)
-{
- useSkiaSubpixelRendering = useSubpixelRendering;
-}
-
-void FontPlatformData::setSubpixelPositioning(bool useSubpixelPositioning)
-{
- useSkiaSubpixelPositioning = useSubpixelPositioning;
-}
-
-FontPlatformData::FontPlatformData(WTF::HashTableDeletedValueType)
- : m_textSize(0)
- , m_emSizeInFontUnits(0)
- , m_fakeBold(false)
- , m_fakeItalic(false)
- , m_orientation(Horizontal)
- , m_isHashTableDeletedValue(true)
-{
-}
-
-FontPlatformData::FontPlatformData()
- : m_textSize(0)
- , m_emSizeInFontUnits(0)
- , m_fakeBold(false)
- , m_fakeItalic(false)
- , m_orientation(Horizontal)
- , m_isHashTableDeletedValue(false)
-{
-}
-
-FontPlatformData::FontPlatformData(float textSize, bool fakeBold, bool fakeItalic)
- : m_textSize(textSize)
- , m_emSizeInFontUnits(0)
- , m_fakeBold(fakeBold)
- , m_fakeItalic(fakeItalic)
- , m_orientation(Horizontal)
- , m_isHashTableDeletedValue(false)
-{
-}
-
-FontPlatformData::FontPlatformData(const FontPlatformData& src)
- : m_typeface(src.m_typeface)
- , m_family(src.m_family)
- , m_textSize(src.m_textSize)
- , m_emSizeInFontUnits(src.m_emSizeInFontUnits)
- , m_fakeBold(src.m_fakeBold)
- , m_fakeItalic(src.m_fakeItalic)
- , m_orientation(src.m_orientation)
- , m_style(src.m_style)
- , m_harfBuzzFace(src.m_harfBuzzFace)
- , m_isHashTableDeletedValue(false)
-{
-}
-
-FontPlatformData::FontPlatformData(SkTypeface* tf, const char* family, float textSize, bool fakeBold, bool fakeItalic, FontOrientation orientation)
- : m_typeface(tf)
- , m_family(family)
- , m_textSize(textSize)
- , m_emSizeInFontUnits(0)
- , m_fakeBold(fakeBold)
- , m_fakeItalic(fakeItalic)
- , m_orientation(orientation)
- , m_isHashTableDeletedValue(false)
-{
- querySystemForRenderStyle();
-}
-
-FontPlatformData::FontPlatformData(const FontPlatformData& src, float textSize)
- : m_typeface(src.m_typeface)
- , m_family(src.m_family)
- , m_textSize(textSize)
- , m_emSizeInFontUnits(src.m_emSizeInFontUnits)
- , m_fakeBold(src.m_fakeBold)
- , m_fakeItalic(src.m_fakeItalic)
- , m_orientation(src.m_orientation)
- , m_harfBuzzFace(src.m_harfBuzzFace)
- , m_isHashTableDeletedValue(false)
-{
- querySystemForRenderStyle();
-}
-
-FontPlatformData::~FontPlatformData()
-{
-}
-
-int FontPlatformData::emSizeInFontUnits() const
-{
- if (m_emSizeInFontUnits)
- return m_emSizeInFontUnits;
-
- m_emSizeInFontUnits = m_typeface->getUnitsPerEm();
- return m_emSizeInFontUnits;
-}
-
-FontPlatformData& FontPlatformData::operator=(const FontPlatformData& src)
-{
- m_typeface = src.m_typeface;
- m_family = src.m_family;
- m_textSize = src.m_textSize;
- m_fakeBold = src.m_fakeBold;
- m_fakeItalic = src.m_fakeItalic;
- m_harfBuzzFace = src.m_harfBuzzFace;
- m_orientation = src.m_orientation;
- m_style = src.m_style;
- m_emSizeInFontUnits = src.m_emSizeInFontUnits;
-
- return *this;
-}
-
-#ifndef NDEBUG
-String FontPlatformData::description() const
-{
- return String();
-}
-#endif
-
-void FontPlatformData::setupPaint(SkPaint* paint) const
-{
- paint->setAntiAlias(m_style.useAntiAlias);
- paint->setHinting(static_cast<SkPaint::Hinting>(m_style.hintStyle));
- paint->setEmbeddedBitmapText(m_style.useBitmaps);
- paint->setAutohinted(m_style.useAutoHint);
- paint->setSubpixelText(m_style.useSubpixelPositioning || RuntimeEnabledFeatures::subpixelFontScalingEnabled());
- if (m_style.useAntiAlias)
- paint->setLCDRenderText(m_style.useSubpixelRendering);
-
- const float ts = m_textSize >= 0 ? m_textSize : 12;
- paint->setTextSize(SkFloatToScalar(ts));
- paint->setTypeface(m_typeface.get());
- paint->setFakeBoldText(m_fakeBold);
- paint->setTextSkewX(m_fakeItalic ? -SK_Scalar1 / 4 : 0);
-}
-
-SkFontID FontPlatformData::uniqueID() const
-{
- return m_typeface->uniqueID();
-}
-
-String FontPlatformData::fontFamilyName() const
-{
- SkTypeface::LocalizedStrings* fontFamilyIterator = this->typeface()->createFamilyNameIterator();
- SkTypeface::LocalizedString localizedString;
- while (fontFamilyIterator->next(&localizedString) && !localizedString.fString.size()) { }
- fontFamilyIterator->unref();
- return String(localizedString.fString.c_str());
-}
-
-bool FontPlatformData::operator==(const FontPlatformData& a) const
-{
- // If either of the typeface pointers are null then we test for pointer
- // equality. Otherwise, we call SkTypeface::Equal on the valid pointers.
- bool typefacesEqual;
- if (!m_typeface || !a.m_typeface)
- typefacesEqual = m_typeface == a.m_typeface;
- else
- typefacesEqual = SkTypeface::Equal(m_typeface.get(), a.m_typeface.get());
-
- return typefacesEqual
- && m_textSize == a.m_textSize
- && m_fakeBold == a.m_fakeBold
- && m_fakeItalic == a.m_fakeItalic
- && m_orientation == a.m_orientation
- && m_style == a.m_style
- && m_isHashTableDeletedValue == a.m_isHashTableDeletedValue;
-}
-
-unsigned FontPlatformData::hash() const
-{
- unsigned h = SkTypeface::UniqueID(m_typeface.get());
- h ^= 0x01010101 * ((static_cast<int>(m_orientation) << 2) | (static_cast<int>(m_fakeBold) << 1) | static_cast<int>(m_fakeItalic));
-
- // This memcpy is to avoid a reinterpret_cast that breaks strict-aliasing
- // rules. Memcpy is generally optimized enough so that performance doesn't
- // matter here.
- uint32_t textSizeBytes;
- memcpy(&textSizeBytes, &m_textSize, sizeof(uint32_t));
- h ^= textSizeBytes;
-
- return h;
-}
-
-bool FontPlatformData::isFixedPitch() const
-{
- notImplemented();
- return false;
-}
-
-HarfBuzzFace* FontPlatformData::harfBuzzFace() const
-{
- if (!m_harfBuzzFace)
- m_harfBuzzFace = HarfBuzzFace::create(const_cast<FontPlatformData*>(this), uniqueID());
-
- return m_harfBuzzFace.get();
-}
-
-void FontPlatformData::getRenderStyleForStrike(const char* font, int sizeAndStyle)
-{
- WebKit::WebFontRenderStyle style;
-
-#if OS(ANDROID)
- style.setDefaults();
-#else
- if (!font || !*font)
- style.setDefaults(); // It's probably a webfont. Take the system defaults.
- else if (WebKit::Platform::current()->sandboxSupport())
- WebKit::Platform::current()->sandboxSupport()->getRenderStyleForStrike(font, sizeAndStyle, &style);
- else
- WebKit::WebFontInfo::renderStyleForStrike(font, sizeAndStyle, &style);
-#endif
-
- style.toFontRenderStyle(&m_style);
-}
-
-void FontPlatformData::querySystemForRenderStyle()
-{
- getRenderStyleForStrike(m_family.data(), (((int)m_textSize) << 2) | (m_typeface->style() & 3));
-
- // Fix FontRenderStyle::NoPreference to actual styles.
- if (m_style.useAntiAlias == FontRenderStyle::NoPreference)
- m_style.useAntiAlias = useSkiaAntiAlias;
-
- if (!m_style.useHinting)
- m_style.hintStyle = SkPaint::kNo_Hinting;
- else if (m_style.useHinting == FontRenderStyle::NoPreference)
- m_style.hintStyle = skiaHinting;
-
- if (m_style.useBitmaps == FontRenderStyle::NoPreference)
- m_style.useBitmaps = useSkiaBitmaps;
- if (m_style.useAutoHint == FontRenderStyle::NoPreference)
- m_style.useAutoHint = useSkiaAutoHint;
- if (m_style.useSubpixelPositioning == FontRenderStyle::NoPreference)
- m_style.useSubpixelPositioning = useSkiaSubpixelPositioning;
- if (m_style.useAntiAlias == FontRenderStyle::NoPreference)
- m_style.useAntiAlias = useSkiaAntiAlias;
- if (m_style.useSubpixelRendering == FontRenderStyle::NoPreference)
- m_style.useSubpixelRendering = useSkiaSubpixelRendering;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/harfbuzz/FontPlatformDataHarfBuzz.h b/chromium/third_party/WebKit/Source/core/platform/graphics/harfbuzz/FontPlatformDataHarfBuzz.h
deleted file mode 100644
index 7f94d604ea1..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/harfbuzz/FontPlatformDataHarfBuzz.h
+++ /dev/null
@@ -1,147 +0,0 @@
-/*
- * Copyright (c) 2006, 2007, 2008, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef FontPlatformDataHarfBuzz_h
-#define FontPlatformDataHarfBuzz_h
-
-#include "SkPaint.h"
-#include "core/platform/SharedBuffer.h"
-#include "core/platform/graphics/FontOrientation.h"
-#include "core/platform/graphics/chromium/FontRenderStyle.h"
-#include "core/platform/graphics/opentype/OpenTypeVerticalData.h"
-#include "wtf/Forward.h"
-#include "wtf/HashTableDeletedValueType.h"
-#include "wtf/RefPtr.h"
-#include "wtf/text/CString.h"
-#include "wtf/text/StringImpl.h"
-
-class SkTypeface;
-typedef uint32_t SkFontID;
-
-namespace WebCore {
-
-class FontDescription;
-class HarfBuzzFace;
-
-// -----------------------------------------------------------------------------
-// FontPlatformData is the handle which WebKit has on a specific face. A face
-// is the tuple of (font, size, ...etc). Here we are just wrapping a Skia
-// SkTypeface pointer and dealing with the reference counting etc.
-// -----------------------------------------------------------------------------
-class FontPlatformData {
-public:
- // Used for deleted values in the font cache's hash tables. The hash table
- // will create us with this structure, and it will compare other values
- // to this "Deleted" one. It expects the Deleted one to be differentiable
- // from the 0 one (created with the empty constructor), so we can't just
- // set everything to 0.
- FontPlatformData(WTF::HashTableDeletedValueType);
- FontPlatformData();
- FontPlatformData(float textSize, bool fakeBold, bool fakeItalic);
- FontPlatformData(const FontPlatformData&);
- FontPlatformData(SkTypeface*, const char* name, float textSize, bool fakeBold, bool fakeItalic, FontOrientation = Horizontal);
- FontPlatformData(const FontPlatformData& src, float textSize);
- ~FontPlatformData();
-
- String fontFamilyName() const;
-
- // -------------------------------------------------------------------------
- // Return true iff this font is monospaced (i.e. every glyph has an equal x
- // advance)
- // -------------------------------------------------------------------------
- bool isFixedPitch() const;
-
- // -------------------------------------------------------------------------
- // Setup a Skia painting context to use this font.
- // -------------------------------------------------------------------------
- void setupPaint(SkPaint*) const;
-
- // -------------------------------------------------------------------------
- // Return Skia's unique id for this font. This encodes both the style and
- // the font's file name so refers to a single face.
- // -------------------------------------------------------------------------
- SkFontID uniqueID() const;
- SkTypeface* typeface() const { return m_typeface.get(); }
-
- unsigned hash() const;
- float size() const { return m_textSize; }
- int emSizeInFontUnits() const;
-
- FontOrientation orientation() const { return m_orientation; }
- void setOrientation(FontOrientation orientation) { m_orientation = orientation; }
- void setFakeBold(bool fakeBold) { m_fakeBold = fakeBold; }
- void setFakeItalic(bool fakeItalic) { m_fakeItalic = fakeItalic; }
- bool operator==(const FontPlatformData&) const;
- FontPlatformData& operator=(const FontPlatformData&);
- bool isHashTableDeletedValue() const { return m_isHashTableDeletedValue; }
-
-#if ENABLE(OPENTYPE_VERTICAL)
- PassRefPtr<OpenTypeVerticalData> verticalData() const;
- PassRefPtr<SharedBuffer> openTypeTable(uint32_t table) const;
-#endif
-
-#ifndef NDEBUG
- String description() const;
-#endif
-
- HarfBuzzFace* harfBuzzFace() const;
-
- // The returned styles are all actual styles without FontRenderStyle::NoPreference.
- const FontRenderStyle& fontRenderStyle() const { return m_style; }
-
- // -------------------------------------------------------------------------
- // Global font preferences...
-
- static void setHinting(SkPaint::Hinting);
- static void setAutoHint(bool);
- static void setUseBitmaps(bool);
- static void setAntiAlias(bool);
- static void setSubpixelRendering(bool);
- static void setSubpixelPositioning(bool);
-
-private:
- void getRenderStyleForStrike(const char*, int);
- void querySystemForRenderStyle();
-
- RefPtr<SkTypeface> m_typeface;
- CString m_family;
- float m_textSize;
- mutable int m_emSizeInFontUnits;
- bool m_fakeBold;
- bool m_fakeItalic;
- FontOrientation m_orientation;
- FontRenderStyle m_style;
- mutable RefPtr<HarfBuzzFace> m_harfBuzzFace;
- bool m_isHashTableDeletedValue;
-};
-
-} // namespace WebCore
-
-#endif // ifdef FontPlatformDataHarfBuzz_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/harfbuzz/HarfBuzzFace.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/harfbuzz/HarfBuzzFace.cpp
deleted file mode 100644
index 88f67cb66d8..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/harfbuzz/HarfBuzzFace.cpp
+++ /dev/null
@@ -1,131 +0,0 @@
-/*
- * Copyright (c) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/harfbuzz/HarfBuzzFace.h"
-
-#include "core/platform/graphics/FontPlatformData.h"
-#include "hb-ot.h"
-#include "hb.h"
-
-namespace WebCore {
-
-const hb_tag_t HarfBuzzFace::vertTag = HB_TAG('v', 'e', 'r', 't');
-const hb_tag_t HarfBuzzFace::vrt2Tag = HB_TAG('v', 'r', 't', '2');
-
-// Though we have FontCache class, which provides the cache mechanism for
-// WebKit's font objects, we also need additional caching layer for HarfBuzz
-// to reduce the memory consumption because hb_face_t should be associated with
-// underling font data (e.g. CTFontRef, FTFace).
-
-class FaceCacheEntry : public RefCounted<FaceCacheEntry> {
-public:
- static PassRefPtr<FaceCacheEntry> create(hb_face_t* face)
- {
- ASSERT(face);
- return adoptRef(new FaceCacheEntry(face));
- }
- ~FaceCacheEntry()
- {
- hb_face_destroy(m_face);
- }
-
- hb_face_t* face() { return m_face; }
- HashMap<uint32_t, uint16_t>* glyphCache() { return &m_glyphCache; }
-
-private:
- explicit FaceCacheEntry(hb_face_t* face)
- : m_face(face)
- { }
-
- hb_face_t* m_face;
- HashMap<uint32_t, uint16_t> m_glyphCache;
-};
-
-typedef HashMap<uint64_t, RefPtr<FaceCacheEntry>, WTF::IntHash<uint64_t>, WTF::UnsignedWithZeroKeyHashTraits<uint64_t> > HarfBuzzFaceCache;
-
-static HarfBuzzFaceCache* harfBuzzFaceCache()
-{
- DEFINE_STATIC_LOCAL(HarfBuzzFaceCache, s_harfBuzzFaceCache, ());
- return &s_harfBuzzFaceCache;
-}
-
-HarfBuzzFace::HarfBuzzFace(FontPlatformData* platformData, uint64_t uniqueID)
- : m_platformData(platformData)
- , m_uniqueID(uniqueID)
- , m_scriptForVerticalText(HB_SCRIPT_INVALID)
-{
- HarfBuzzFaceCache::AddResult result = harfBuzzFaceCache()->add(m_uniqueID, 0);
- if (result.isNewEntry)
- result.iterator->value = FaceCacheEntry::create(createFace());
- result.iterator->value->ref();
- m_face = result.iterator->value->face();
- m_glyphCacheForFaceCacheEntry = result.iterator->value->glyphCache();
-}
-
-HarfBuzzFace::~HarfBuzzFace()
-{
- HarfBuzzFaceCache::iterator result = harfBuzzFaceCache()->find(m_uniqueID);
- ASSERT(result != harfBuzzFaceCache()->end());
- ASSERT(result.get()->value->refCount() > 1);
- result.get()->value->deref();
- if (result.get()->value->refCount() == 1)
- harfBuzzFaceCache()->remove(m_uniqueID);
-}
-
-static hb_script_t findScriptForVerticalGlyphSubstitution(hb_face_t* face)
-{
- static const unsigned maxCount = 32;
-
- unsigned scriptCount = maxCount;
- hb_tag_t scriptTags[maxCount];
- hb_ot_layout_table_get_script_tags(face, HB_OT_TAG_GSUB, 0, &scriptCount, scriptTags);
- for (unsigned scriptIndex = 0; scriptIndex < scriptCount; ++scriptIndex) {
- unsigned languageCount = maxCount;
- hb_tag_t languageTags[maxCount];
- hb_ot_layout_script_get_language_tags(face, HB_OT_TAG_GSUB, scriptIndex, 0, &languageCount, languageTags);
- for (unsigned languageIndex = 0; languageIndex < languageCount; ++languageIndex) {
- unsigned featureIndex;
- if (hb_ot_layout_language_find_feature(face, HB_OT_TAG_GSUB, scriptIndex, languageIndex, HarfBuzzFace::vertTag, &featureIndex)
- || hb_ot_layout_language_find_feature(face, HB_OT_TAG_GSUB, scriptIndex, languageIndex, HarfBuzzFace::vrt2Tag, &featureIndex))
- return hb_ot_tag_to_script(scriptTags[scriptIndex]);
- }
- }
- return HB_SCRIPT_INVALID;
-}
-
-void HarfBuzzFace::setScriptForVerticalGlyphSubstitution(hb_buffer_t* buffer)
-{
- if (m_scriptForVerticalText == HB_SCRIPT_INVALID)
- m_scriptForVerticalText = findScriptForVerticalGlyphSubstitution(m_face);
- hb_buffer_set_script(buffer, m_scriptForVerticalText);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/harfbuzz/HarfBuzzFace.h b/chromium/third_party/WebKit/Source/core/platform/graphics/harfbuzz/HarfBuzzFace.h
deleted file mode 100644
index cf16c33225b..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/harfbuzz/HarfBuzzFace.h
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * Copyright (c) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef HarfBuzzFace_h
-#define HarfBuzzFace_h
-
-#include <hb.h>
-
-#include "wtf/HashMap.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/RefPtr.h"
-
-namespace WebCore {
-
-class FontPlatformData;
-
-class HarfBuzzFace : public RefCounted<HarfBuzzFace> {
-public:
- static const hb_tag_t vertTag;
- static const hb_tag_t vrt2Tag;
-
- static PassRefPtr<HarfBuzzFace> create(FontPlatformData* platformData, uint64_t uniqueID)
- {
- return adoptRef(new HarfBuzzFace(platformData, uniqueID));
- }
- ~HarfBuzzFace();
-
- hb_font_t* createFont();
-
- void setScriptForVerticalGlyphSubstitution(hb_buffer_t*);
-
-private:
- HarfBuzzFace(FontPlatformData*, uint64_t);
-
- hb_face_t* createFace();
-
- FontPlatformData* m_platformData;
- uint64_t m_uniqueID;
- hb_face_t* m_face;
- WTF::HashMap<uint32_t, uint16_t>* m_glyphCacheForFaceCacheEntry;
-
- hb_script_t m_scriptForVerticalText;
-};
-
-}
-
-#endif // HarfBuzzFace_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/harfbuzz/HarfBuzzFaceCoreText.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/harfbuzz/HarfBuzzFaceCoreText.cpp
deleted file mode 100644
index e81ba594af5..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/harfbuzz/HarfBuzzFaceCoreText.cpp
+++ /dev/null
@@ -1,149 +0,0 @@
-/*
- * Copyright (c) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/harfbuzz/HarfBuzzFace.h"
-
-#include "core/platform/graphics/FontPlatformData.h"
-#include "core/platform/graphics/SimpleFontData.h"
-#include "core/platform/graphics/harfbuzz/HarfBuzzShaper.h"
-
-#include <ApplicationServices/ApplicationServices.h>
-#include "hb.h"
-
-namespace WebCore {
-
-static hb_position_t floatToHarfBuzzPosition(CGFloat value)
-{
- return static_cast<hb_position_t>(value * (1 << 16));
-}
-
-static hb_bool_t getGlyph(hb_font_t* hbFont, void* fontData, hb_codepoint_t unicode, hb_codepoint_t variationSelector, hb_codepoint_t* glyph, void* userData)
-{
- CTFontRef ctFont = reinterpret_cast<FontPlatformData*>(fontData)->ctFont();
- UniChar characters[4];
- CGGlyph cgGlyphs[4];
- size_t length = 0;
- U16_APPEND_UNSAFE(characters, length, unicode);
- if (!CTFontGetGlyphsForCharacters(ctFont, characters, cgGlyphs, length))
- return false;
- *glyph = cgGlyphs[0];
- return true;
-}
-
-static hb_position_t getGlyphHorizontalAdvance(hb_font_t* hbFont, void* fontData, hb_codepoint_t glyph, void* userData)
-{
- CTFontRef ctFont = reinterpret_cast<FontPlatformData*>(fontData)->ctFont();
- CGGlyph cgGlyph = glyph;
- CGFloat advance = CTFontGetAdvancesForGlyphs(ctFont, kCTFontHorizontalOrientation, &cgGlyph, 0, 1);
- return floatToHarfBuzzPosition(advance);
-}
-
-static hb_bool_t getGlyphHorizontalOrigin(hb_font_t* hbFont, void* fontData, hb_codepoint_t glyph, hb_position_t* x, hb_position_t* y, void* userData)
-{
- return true;
-}
-
-static hb_bool_t getGlyphExtents(hb_font_t* hbFont, void* fontData, hb_codepoint_t glyph, hb_glyph_extents_t* extents, void* userData)
-{
- CTFontRef ctFont = reinterpret_cast<FontPlatformData*>(fontData)->ctFont();
- CGRect cgRect;
- CGGlyph cgGlyph = glyph;
- if (CTFontGetBoundingRectsForGlyphs(ctFont, kCTFontDefaultOrientation, &cgGlyph, &cgRect, 1) == CGRectNull)
- return false;
- extents->x_bearing = floatToHarfBuzzPosition(cgRect.origin.x);
- extents->y_bearing = -floatToHarfBuzzPosition(cgRect.origin.y);
- extents->width = floatToHarfBuzzPosition(cgRect.size.width);
- extents->height = floatToHarfBuzzPosition(cgRect.size.height);
- return true;
-}
-
-static hb_font_funcs_t* harfBuzzCoreTextGetFontFuncs()
-{
- static hb_font_funcs_t* harfBuzzCoreTextFontFuncs = 0;
-
- if (!harfBuzzCoreTextFontFuncs) {
- harfBuzzCoreTextFontFuncs = hb_font_funcs_create();
- hb_font_funcs_set_glyph_func(harfBuzzCoreTextFontFuncs, getGlyph, 0, 0);
- hb_font_funcs_set_glyph_h_advance_func(harfBuzzCoreTextFontFuncs, getGlyphHorizontalAdvance, 0, 0);
- hb_font_funcs_set_glyph_h_origin_func(harfBuzzCoreTextFontFuncs, getGlyphHorizontalOrigin, 0, 0);
- hb_font_funcs_set_glyph_extents_func(harfBuzzCoreTextFontFuncs, getGlyphExtents, 0, 0);
- hb_font_funcs_make_immutable(harfBuzzCoreTextFontFuncs);
- }
- return harfBuzzCoreTextFontFuncs;
-}
-
-static void releaseTableData(void* userData)
-{
- CFDataRef cfData = reinterpret_cast<CFDataRef>(userData);
- CFRelease(cfData);
-}
-
-static hb_blob_t* harfBuzzCoreTextGetTable(hb_face_t* face, hb_tag_t tag, void* userData)
-{
- CGFontRef cgFont = reinterpret_cast<CGFontRef>(userData);
- CFDataRef cfData = CGFontCopyTableForTag(cgFont, tag);
- if (!cfData)
- return 0;
-
- const char* data = reinterpret_cast<const char*>(CFDataGetBytePtr(cfData));
- const size_t length = CFDataGetLength(cfData);
- if (!data || !length)
- return 0;
- return hb_blob_create(data, length, HB_MEMORY_MODE_READONLY, reinterpret_cast<void*>(const_cast<__CFData*>(cfData)), releaseTableData);
-}
-
-hb_face_t* HarfBuzzFace::createFace()
-{
- // It seems that CTFontCopyTable of MacOSX10.5 sdk doesn't work for
- // OpenType layout tables(GDEF, GSUB, GPOS). Use CGFontCopyTableForTag instead.
- hb_face_t* face = hb_face_create_for_tables(harfBuzzCoreTextGetTable, m_platformData->cgFont(), 0);
- ASSERT(face);
- return face;
-}
-
-hb_font_t* HarfBuzzFace::createFont()
-{
- hb_font_t* font = hb_font_create(m_face);
- hb_font_set_funcs(font, harfBuzzCoreTextGetFontFuncs(), m_platformData, 0);
- const float size = m_platformData->m_size;
- hb_font_set_ppem(font, size, size);
- const int scale = (1 << 16) * static_cast<int>(size);
- hb_font_set_scale(font, scale, scale);
- hb_font_make_immutable(font);
- return font;
-}
-
-GlyphBufferAdvance HarfBuzzShaper::createGlyphBufferAdvance(float width, float height)
-{
- return CGSizeMake(width, height);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/harfbuzz/HarfBuzzFaceSkia.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/harfbuzz/HarfBuzzFaceSkia.cpp
deleted file mode 100644
index f6899914428..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/harfbuzz/HarfBuzzFaceSkia.cpp
+++ /dev/null
@@ -1,196 +0,0 @@
-/*
- * Copyright (c) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/harfbuzz/HarfBuzzFace.h"
-
-#include "SkPaint.h"
-#include "SkPath.h"
-#include "SkPoint.h"
-#include "SkRect.h"
-#include "SkTypeface.h"
-#include "SkUtils.h"
-#include "core/platform/graphics/FontPlatformData.h"
-#include "core/platform/graphics/GlyphBuffer.h"
-#include "core/platform/graphics/SimpleFontData.h"
-#include "core/platform/graphics/harfbuzz/HarfBuzzShaper.h"
-
-#include "hb.h"
-#include "wtf/HashMap.h"
-
-namespace WebCore {
-
-// Our implementation of the callbacks which HarfBuzz requires by using Skia
-// calls. See the HarfBuzz source for references about what these callbacks do.
-
-struct HarfBuzzFontData {
- HarfBuzzFontData(WTF::HashMap<uint32_t, uint16_t>* glyphCacheForFaceCacheEntry)
- : m_glyphCacheForFaceCacheEntry(glyphCacheForFaceCacheEntry)
- { }
- SkPaint m_paint;
- WTF::HashMap<uint32_t, uint16_t>* m_glyphCacheForFaceCacheEntry;
-};
-
-static hb_position_t SkiaScalarToHarfBuzzPosition(SkScalar value)
-{
- return SkScalarToFixed(value);
-}
-
-static void SkiaGetGlyphWidthAndExtents(SkPaint* paint, hb_codepoint_t codepoint, hb_position_t* width, hb_glyph_extents_t* extents)
-{
- ASSERT(codepoint <= 0xFFFF);
- paint->setTextEncoding(SkPaint::kGlyphID_TextEncoding);
-
- SkScalar skWidth;
- SkRect skBounds;
- uint16_t glyph = codepoint;
-
- paint->getTextWidths(&glyph, sizeof(glyph), &skWidth, &skBounds);
- if (width)
- *width = SkiaScalarToHarfBuzzPosition(skWidth);
- if (extents) {
- // Invert y-axis because Skia is y-grows-down but we set up HarfBuzz to be y-grows-up.
- extents->x_bearing = SkiaScalarToHarfBuzzPosition(skBounds.fLeft);
- extents->y_bearing = SkiaScalarToHarfBuzzPosition(-skBounds.fTop);
- extents->width = SkiaScalarToHarfBuzzPosition(skBounds.width());
- extents->height = SkiaScalarToHarfBuzzPosition(-skBounds.height());
- }
-}
-
-static hb_bool_t harfBuzzGetGlyph(hb_font_t* hbFont, void* fontData, hb_codepoint_t unicode, hb_codepoint_t variationSelector, hb_codepoint_t* glyph, void* userData)
-{
- HarfBuzzFontData* hbFontData = reinterpret_cast<HarfBuzzFontData*>(fontData);
-
- WTF::HashMap<uint32_t, uint16_t>::AddResult result = hbFontData->m_glyphCacheForFaceCacheEntry->add(unicode, 0);
- if (result.isNewEntry) {
- SkPaint* paint = &hbFontData->m_paint;
- paint->setTextEncoding(SkPaint::kUTF32_TextEncoding);
- uint16_t glyph16;
- paint->textToGlyphs(&unicode, sizeof(hb_codepoint_t), &glyph16);
- result.iterator->value = glyph16;
- *glyph = glyph16;
- }
- *glyph = result.iterator->value;
- return !!*glyph;
-}
-
-static hb_position_t harfBuzzGetGlyphHorizontalAdvance(hb_font_t* hbFont, void* fontData, hb_codepoint_t glyph, void* userData)
-{
- HarfBuzzFontData* hbFontData = reinterpret_cast<HarfBuzzFontData*>(fontData);
- hb_position_t advance = 0;
-
- SkiaGetGlyphWidthAndExtents(&hbFontData->m_paint, glyph, &advance, 0);
- return advance;
-}
-
-static hb_bool_t harfBuzzGetGlyphHorizontalOrigin(hb_font_t* hbFont, void* fontData, hb_codepoint_t glyph, hb_position_t* x, hb_position_t* y, void* userData)
-{
- // Just return true, following the way that HarfBuzz-FreeType
- // implementation does.
- return true;
-}
-
-static hb_bool_t harfBuzzGetGlyphExtents(hb_font_t* hbFont, void* fontData, hb_codepoint_t glyph, hb_glyph_extents_t* extents, void* userData)
-{
- HarfBuzzFontData* hbFontData = reinterpret_cast<HarfBuzzFontData*>(fontData);
-
- SkiaGetGlyphWidthAndExtents(&hbFontData->m_paint, glyph, 0, extents);
- return true;
-}
-
-static hb_font_funcs_t* harfBuzzSkiaGetFontFuncs()
-{
- static hb_font_funcs_t* harfBuzzSkiaFontFuncs = 0;
-
- // We don't set callback functions which we can't support.
- // HarfBuzz will use the fallback implementation if they aren't set.
- if (!harfBuzzSkiaFontFuncs) {
- harfBuzzSkiaFontFuncs = hb_font_funcs_create();
- hb_font_funcs_set_glyph_func(harfBuzzSkiaFontFuncs, harfBuzzGetGlyph, 0, 0);
- hb_font_funcs_set_glyph_h_advance_func(harfBuzzSkiaFontFuncs, harfBuzzGetGlyphHorizontalAdvance, 0, 0);
- hb_font_funcs_set_glyph_h_origin_func(harfBuzzSkiaFontFuncs, harfBuzzGetGlyphHorizontalOrigin, 0, 0);
- hb_font_funcs_set_glyph_extents_func(harfBuzzSkiaFontFuncs, harfBuzzGetGlyphExtents, 0, 0);
- hb_font_funcs_make_immutable(harfBuzzSkiaFontFuncs);
- }
- return harfBuzzSkiaFontFuncs;
-}
-
-static hb_blob_t* harfBuzzSkiaGetTable(hb_face_t* face, hb_tag_t tag, void* userData)
-{
- SkTypeface* typeface = reinterpret_cast<SkTypeface*>(userData);
-
- const size_t tableSize = typeface->getTableSize(tag);
- if (!tableSize)
- return 0;
-
- char* buffer = reinterpret_cast<char*>(fastMalloc(tableSize));
- if (!buffer)
- return 0;
- size_t actualSize = typeface->getTableData(tag, 0, tableSize, buffer);
- if (tableSize != actualSize) {
- fastFree(buffer);
- return 0;
- }
-
- return hb_blob_create(const_cast<char*>(buffer), tableSize, HB_MEMORY_MODE_WRITABLE, buffer, fastFree);
-}
-
-static void destroyHarfBuzzFontData(void* userData)
-{
- HarfBuzzFontData* hbFontData = reinterpret_cast<HarfBuzzFontData*>(userData);
- delete hbFontData;
-}
-
-hb_face_t* HarfBuzzFace::createFace()
-{
- hb_face_t* face = hb_face_create_for_tables(harfBuzzSkiaGetTable, m_platformData->typeface(), 0);
- ASSERT(face);
- return face;
-}
-
-hb_font_t* HarfBuzzFace::createFont()
-{
- HarfBuzzFontData* hbFontData = new HarfBuzzFontData(m_glyphCacheForFaceCacheEntry);
- m_platformData->setupPaint(&hbFontData->m_paint);
- hb_font_t* font = hb_font_create(m_face);
- hb_font_set_funcs(font, harfBuzzSkiaGetFontFuncs(), hbFontData, destroyHarfBuzzFontData);
- float size = m_platformData->size();
- int scale = SkiaScalarToHarfBuzzPosition(size);
- hb_font_set_scale(font, scale, scale);
- hb_font_make_immutable(font);
- return font;
-}
-
-GlyphBufferAdvance HarfBuzzShaper::createGlyphBufferAdvance(float width, float height)
-{
- return GlyphBufferAdvance(width, height);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/harfbuzz/HarfBuzzShaper.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/harfbuzz/HarfBuzzShaper.cpp
deleted file mode 100644
index aebb282cfbb..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/harfbuzz/HarfBuzzShaper.cpp
+++ /dev/null
@@ -1,878 +0,0 @@
-/*
- * Copyright (c) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/harfbuzz/HarfBuzzShaper.h"
-
-#include "RuntimeEnabledFeatures.h"
-#include "core/platform/graphics/Font.h"
-#include "core/platform/graphics/SurrogatePairAwareTextIterator.h"
-#include "core/platform/graphics/TextRun.h"
-#include "core/platform/graphics/harfbuzz/HarfBuzzFace.h"
-#include "hb-icu.h"
-#include "wtf/MathExtras.h"
-#include "wtf/unicode/Unicode.h"
-#include "wtf/Vector.h"
-#include <unicode/normlzr.h>
-#include <unicode/uchar.h>
-
-#include <list>
-#include <map>
-#include <string>
-
-namespace WebCore {
-
-template<typename T>
-class HarfBuzzScopedPtr {
-public:
- typedef void (*DestroyFunction)(T*);
-
- HarfBuzzScopedPtr(T* ptr, DestroyFunction destroy)
- : m_ptr(ptr)
- , m_destroy(destroy)
- {
- ASSERT(m_destroy);
- }
- ~HarfBuzzScopedPtr()
- {
- if (m_ptr)
- (*m_destroy)(m_ptr);
- }
-
- T* get() { return m_ptr; }
- void set(T* ptr) { m_ptr = ptr; }
-private:
- T* m_ptr;
- DestroyFunction m_destroy;
-};
-
-
-static const int cHarfBuzzCacheMaxSize = 256;
-
-struct CachedShapingResultsLRUNode;
-struct CachedShapingResults;
-typedef std::map<std::wstring, CachedShapingResults*> CachedShapingResultsMap;
-typedef std::list<CachedShapingResultsLRUNode*> CachedShapingResultsLRU;
-
-struct CachedShapingResults {
- CachedShapingResults(hb_buffer_t* harfBuzzBuffer, const Font* runFont, hb_direction_t runDir);
- ~CachedShapingResults();
-
- hb_buffer_t* buffer;
- Font font;
- hb_direction_t dir;
- CachedShapingResultsLRU::iterator lru;
-};
-
-struct CachedShapingResultsLRUNode {
- CachedShapingResultsLRUNode(const CachedShapingResultsMap::iterator& cacheEntry);
- ~CachedShapingResultsLRUNode();
-
- CachedShapingResultsMap::iterator entry;
-};
-
-CachedShapingResults::CachedShapingResults(hb_buffer_t* harfBuzzBuffer, const Font* fontData, hb_direction_t dirData)
- : buffer(harfBuzzBuffer)
- , font(*fontData)
- , dir(dirData)
-{
-}
-
-CachedShapingResults::~CachedShapingResults()
-{
- hb_buffer_destroy(buffer);
-}
-
-CachedShapingResultsLRUNode::CachedShapingResultsLRUNode(const CachedShapingResultsMap::iterator& cacheEntry)
- : entry(cacheEntry)
-{
-}
-
-CachedShapingResultsLRUNode::~CachedShapingResultsLRUNode()
-{
-}
-
-class HarfBuzzRunCache {
-public:
- HarfBuzzRunCache();
- ~HarfBuzzRunCache();
-
- CachedShapingResults* find(const std::wstring& key) const;
- void remove(CachedShapingResults* node);
- void moveToBack(CachedShapingResults* node);
- bool insert(const std::wstring& key, CachedShapingResults* run);
-
-private:
- CachedShapingResultsMap m_harfBuzzRunMap;
- CachedShapingResultsLRU m_harfBuzzRunLRU;
-};
-
-
-HarfBuzzRunCache::HarfBuzzRunCache()
-{
-}
-
-HarfBuzzRunCache::~HarfBuzzRunCache()
-{
- for (CachedShapingResultsMap::iterator it = m_harfBuzzRunMap.begin(); it != m_harfBuzzRunMap.end(); ++it)
- delete it->second;
- for (CachedShapingResultsLRU::iterator it = m_harfBuzzRunLRU.begin(); it != m_harfBuzzRunLRU.end(); ++it)
- delete *it;
-}
-
-bool HarfBuzzRunCache::insert(const std::wstring& key, CachedShapingResults* data)
-{
- std::pair<CachedShapingResultsMap::iterator, bool> results =
- m_harfBuzzRunMap.insert(CachedShapingResultsMap::value_type(key, data));
-
- if (!results.second)
- return false;
-
- CachedShapingResultsLRUNode* node = new CachedShapingResultsLRUNode(results.first);
-
- m_harfBuzzRunLRU.push_back(node);
- data->lru = --m_harfBuzzRunLRU.end();
-
- if (m_harfBuzzRunMap.size() > cHarfBuzzCacheMaxSize) {
- CachedShapingResultsLRUNode* lru = m_harfBuzzRunLRU.front();
- CachedShapingResults* foo = lru->entry->second;
- m_harfBuzzRunMap.erase(lru->entry);
- m_harfBuzzRunLRU.pop_front();
- delete foo;
- delete lru;
- }
-
- return true;
-}
-
-inline CachedShapingResults* HarfBuzzRunCache::find(const std::wstring& key) const
-{
- CachedShapingResultsMap::const_iterator it = m_harfBuzzRunMap.find(key);
-
- return it != m_harfBuzzRunMap.end() ? it->second : 0;
-}
-
-inline void HarfBuzzRunCache::remove(CachedShapingResults* node)
-{
- CachedShapingResultsLRUNode* lruNode = *node->lru;
-
- m_harfBuzzRunLRU.erase(node->lru);
- m_harfBuzzRunMap.erase(lruNode->entry);
- delete lruNode;
- delete node;
-}
-
-inline void HarfBuzzRunCache::moveToBack(CachedShapingResults* node)
-{
- CachedShapingResultsLRUNode* lruNode = *node->lru;
- m_harfBuzzRunLRU.erase(node->lru);
- m_harfBuzzRunLRU.push_back(lruNode);
- node->lru = --m_harfBuzzRunLRU.end();
-}
-
-HarfBuzzRunCache& harfBuzzRunCache()
-{
- DEFINE_STATIC_LOCAL(HarfBuzzRunCache, globalHarfBuzzRunCache, ());
- return globalHarfBuzzRunCache;
-}
-
-static inline float harfBuzzPositionToFloat(hb_position_t value)
-{
- return static_cast<float>(value) / (1 << 16);
-}
-
-inline HarfBuzzShaper::HarfBuzzRun::HarfBuzzRun(const SimpleFontData* fontData, unsigned startIndex, unsigned numCharacters, TextDirection direction, hb_script_t script)
- : m_fontData(fontData)
- , m_startIndex(startIndex)
- , m_numCharacters(numCharacters)
- , m_direction(direction)
- , m_script(script)
- , m_numGlyphs(0)
- , m_width(0)
-{
-}
-
-inline HarfBuzzShaper::HarfBuzzRun::HarfBuzzRun(const HarfBuzzRun& rhs)
- : m_fontData(rhs.m_fontData)
- , m_startIndex(rhs.m_startIndex)
- , m_numCharacters(rhs.m_numCharacters)
- , m_numGlyphs(rhs.m_numGlyphs)
- , m_direction(rhs.m_direction)
- , m_script(rhs.m_script)
- , m_glyphs(rhs.m_glyphs)
- , m_advances(rhs.m_advances)
- , m_glyphToCharacterIndexes(rhs.m_glyphToCharacterIndexes)
- , m_offsets(rhs.m_offsets)
- , m_width(rhs.m_width)
-{
-}
-
-HarfBuzzShaper::HarfBuzzRun::~HarfBuzzRun()
-{
-}
-
-inline void HarfBuzzShaper::HarfBuzzRun::applyShapeResult(hb_buffer_t* harfBuzzBuffer)
-{
- m_numGlyphs = hb_buffer_get_length(harfBuzzBuffer);
- m_glyphs.resize(m_numGlyphs);
- m_advances.resize(m_numGlyphs);
- m_glyphToCharacterIndexes.resize(m_numGlyphs);
- m_offsets.resize(m_numGlyphs);
-}
-
-inline void HarfBuzzShaper::HarfBuzzRun::copyShapeResultAndGlyphPositions(const HarfBuzzRun& run)
-{
- m_numGlyphs = run.m_numGlyphs;
- m_glyphs = run.m_glyphs;
- m_advances = run.m_advances;
- m_glyphToCharacterIndexes = run.m_glyphToCharacterIndexes;
- m_offsets = run.m_offsets;
- m_width = run.m_width;
-}
-
-inline void HarfBuzzShaper::HarfBuzzRun::setGlyphAndPositions(unsigned index, uint16_t glyphId, float advance, float offsetX, float offsetY)
-{
- m_glyphs[index] = glyphId;
- m_advances[index] = advance;
- m_offsets[index] = FloatPoint(offsetX, offsetY);
-}
-
-int HarfBuzzShaper::HarfBuzzRun::characterIndexForXPosition(float targetX)
-{
- ASSERT(targetX <= m_width);
- float currentX = 0;
- float currentAdvance = m_advances[0];
- unsigned glyphIndex = 0;
-
- // Sum up advances that belong to a character.
- while (glyphIndex < m_numGlyphs - 1 && m_glyphToCharacterIndexes[glyphIndex] == m_glyphToCharacterIndexes[glyphIndex + 1])
- currentAdvance += m_advances[++glyphIndex];
- currentAdvance = currentAdvance / 2.0;
- if (targetX <= currentAdvance)
- return rtl() ? m_numCharacters : 0;
-
- ++glyphIndex;
- while (glyphIndex < m_numGlyphs) {
- unsigned prevCharacterIndex = m_glyphToCharacterIndexes[glyphIndex - 1];
- float prevAdvance = currentAdvance;
- currentAdvance = m_advances[glyphIndex];
- while (glyphIndex < m_numGlyphs - 1 && m_glyphToCharacterIndexes[glyphIndex] == m_glyphToCharacterIndexes[glyphIndex + 1])
- currentAdvance += m_advances[++glyphIndex];
- currentAdvance = currentAdvance / 2.0;
- float nextX = currentX + prevAdvance + currentAdvance;
- if (currentX <= targetX && targetX <= nextX)
- return rtl() ? prevCharacterIndex : m_glyphToCharacterIndexes[glyphIndex];
- currentX = nextX;
- prevAdvance = currentAdvance;
- ++glyphIndex;
- }
-
- return rtl() ? 0 : m_numCharacters;
-}
-
-float HarfBuzzShaper::HarfBuzzRun::xPositionForOffset(unsigned offset)
-{
- ASSERT(offset < m_numCharacters);
- unsigned glyphIndex = 0;
- float position = 0;
- if (rtl()) {
- while (glyphIndex < m_numGlyphs && m_glyphToCharacterIndexes[glyphIndex] > offset) {
- position += m_advances[glyphIndex];
- ++glyphIndex;
- }
- // For RTL, we need to return the right side boundary of the character.
- // Add advance of glyphs which are part of the character.
- while (glyphIndex < m_numGlyphs - 1 && m_glyphToCharacterIndexes[glyphIndex] == m_glyphToCharacterIndexes[glyphIndex + 1]) {
- position += m_advances[glyphIndex];
- ++glyphIndex;
- }
- position += m_advances[glyphIndex];
- } else {
- while (glyphIndex < m_numGlyphs && m_glyphToCharacterIndexes[glyphIndex] < offset) {
- position += m_advances[glyphIndex];
- ++glyphIndex;
- }
- }
- return position;
-}
-
-static void normalizeCharacters(const TextRun& run, unsigned length, UChar* destination, unsigned* destinationLength)
-{
- unsigned position = 0;
- bool error = false;
- const UChar* source;
- String stringFor8BitRun;
- if (run.is8Bit()) {
- stringFor8BitRun = String::make16BitFrom8BitSource(run.characters8(), run.length());
- source = stringFor8BitRun.characters16();
- } else
- source = run.characters16();
-
- *destinationLength = 0;
- while (position < length) {
- UChar32 character;
- U16_NEXT(source, position, length, character);
- // Don't normalize tabs as they are not treated as spaces for word-end.
- if (Font::treatAsSpace(character) && character != '\t')
- character = ' ';
- else if (Font::treatAsZeroWidthSpaceInComplexScript(character))
- character = zeroWidthSpace;
- U16_APPEND(destination, *destinationLength, length, character, error);
- ASSERT_UNUSED(error, !error);
- }
-}
-
-HarfBuzzShaper::HarfBuzzShaper(const Font* font, const TextRun& run)
- : m_font(font)
- , m_normalizedBufferLength(0)
- , m_run(run)
- , m_wordSpacingAdjustment(font->wordSpacing())
- , m_padding(0)
- , m_padPerWordBreak(0)
- , m_padError(0)
- , m_letterSpacing(font->letterSpacing())
- , m_fromIndex(0)
- , m_toIndex(m_run.length())
-{
- m_normalizedBuffer = adoptArrayPtr(new UChar[m_run.length() + 1]);
- normalizeCharacters(m_run, m_run.length(), m_normalizedBuffer.get(), &m_normalizedBufferLength);
- setPadding(m_run.expansion());
- setFontFeatures();
-}
-
-HarfBuzzShaper::~HarfBuzzShaper()
-{
-}
-
-static void normalizeSpacesAndMirrorChars(const UChar* source, unsigned length, UChar* destination, unsigned* destinationLength, HarfBuzzShaper::NormalizeMode normalizeMode)
-{
- int position = 0;
- bool error = false;
- // Iterate characters in source and mirror character if needed.
- *destinationLength = 0;
- while (position < length) {
- UChar32 character;
- U16_NEXT(source, position, length, character);
- // Don't normalize tabs as they are not treated as spaces for word-end
- if (Font::treatAsSpace(character) && character != '\t')
- character = ' ';
- else if (Font::treatAsZeroWidthSpace(character))
- character = zeroWidthSpace;
- else if (normalizeMode == HarfBuzzShaper::NormalizeMirrorChars)
- character = u_charMirror(character);
- U16_APPEND(destination, *destinationLength, length, character, error);
- ASSERT_UNUSED(error, !error);
- }
-}
-
-void HarfBuzzShaper::setNormalizedBuffer(NormalizeMode normalizeMode)
-{
- // Normalize the text run in three ways:
- // 1) Convert the |originalRun| to NFC normalized form if combining diacritical marks
- // (U+0300..) are used in the run. This conversion is necessary since most OpenType
- // fonts (e.g., Arial) don't have substitution rules for the diacritical marks in
- // their GSUB tables.
- //
- // Note that we don't use the icu::Normalizer::isNormalized(UNORM_NFC) API here since
- // the API returns FALSE (= not normalized) for complex runs that don't require NFC
- // normalization (e.g., Arabic text). Unless the run contains the diacritical marks,
- // HarfBuzz will do the same thing for us using the GSUB table.
- // 2) Convert spacing characters into plain spaces, as some fonts will provide glyphs
- // for characters like '\n' otherwise.
- // 3) Convert mirrored characters such as parenthesis for rtl text.
-
- // Convert to NFC form if the text has diacritical marks.
- icu::UnicodeString normalizedString;
- UErrorCode error = U_ZERO_ERROR;
-
- const UChar* runCharacters;
- String stringFor8BitRun;
- if (m_run.is8Bit()) {
- stringFor8BitRun = String::make16BitFrom8BitSource(m_run.characters8(), m_run.length());
- runCharacters = stringFor8BitRun.characters16();
- } else
- runCharacters = m_run.characters16();
-
- for (int i = 0; i < m_run.length(); ++i) {
- UChar ch = runCharacters[i];
- if (::ublock_getCode(ch) == UBLOCK_COMBINING_DIACRITICAL_MARKS) {
- icu::Normalizer::normalize(icu::UnicodeString(runCharacters,
- m_run.length()), UNORM_NFC, 0 /* no options */,
- normalizedString, error);
- if (U_FAILURE(error))
- normalizedString.remove();
- break;
- }
- }
-
- const UChar* sourceText;
- unsigned sourceLength;
- if (normalizedString.isEmpty()) {
- sourceLength = m_run.length();
- sourceText = runCharacters;
- } else {
- sourceLength = normalizedString.length();
- sourceText = normalizedString.getBuffer();
- }
-
- m_normalizedBuffer = adoptArrayPtr(new UChar[sourceLength + 1]);
- normalizeSpacesAndMirrorChars(sourceText, sourceLength, m_normalizedBuffer.get(), &m_normalizedBufferLength, normalizeMode);
-}
-
-bool HarfBuzzShaper::isWordEnd(unsigned index)
-{
- // This could refer a high-surrogate, but should work.
- return index && isCodepointSpace(m_normalizedBuffer[index]);
-}
-
-int HarfBuzzShaper::determineWordBreakSpacing()
-{
- int wordBreakSpacing = m_wordSpacingAdjustment;
-
- if (m_padding > 0) {
- int toPad = roundf(m_padPerWordBreak + m_padError);
- m_padError += m_padPerWordBreak - toPad;
-
- if (m_padding < toPad)
- toPad = m_padding;
- m_padding -= toPad;
- wordBreakSpacing += toPad;
- }
- return wordBreakSpacing;
-}
-
-// setPadding sets a number of pixels to be distributed across the TextRun.
-// WebKit uses this to justify text.
-void HarfBuzzShaper::setPadding(int padding)
-{
- m_padding = padding;
- m_padError = 0;
- if (!m_padding)
- return;
-
- // If we have padding to distribute, then we try to give an equal
- // amount to each space. The last space gets the smaller amount, if
- // any.
- unsigned numWordEnds = 0;
-
- for (unsigned i = 0; i < m_normalizedBufferLength; i++) {
- if (isWordEnd(i))
- numWordEnds++;
- }
-
- if (numWordEnds)
- m_padPerWordBreak = m_padding / numWordEnds;
- else
- m_padPerWordBreak = 0;
-}
-
-
-void HarfBuzzShaper::setDrawRange(int from, int to)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(from >= 0);
- ASSERT_WITH_SECURITY_IMPLICATION(to <= m_run.length());
- m_fromIndex = from;
- m_toIndex = to;
-}
-
-void HarfBuzzShaper::setFontFeatures()
-{
- const FontDescription& description = m_font->fontDescription();
- if (description.orientation() == Vertical) {
- static hb_feature_t vert = { HarfBuzzFace::vertTag, 1, 0, static_cast<unsigned>(-1) };
- static hb_feature_t vrt2 = { HarfBuzzFace::vrt2Tag, 1, 0, static_cast<unsigned>(-1) };
- m_features.append(vert);
- m_features.append(vrt2);
- }
-
- FontFeatureSettings* settings = description.featureSettings();
- if (!settings)
- return;
-
- unsigned numFeatures = settings->size();
- for (unsigned i = 0; i < numFeatures; ++i) {
- hb_feature_t feature;
- String tag = settings->at(i).tag();
- feature.tag = HB_TAG(tag[0], tag[1], tag[2], tag[3]);
- feature.value = settings->at(i).value();
- feature.start = 0;
- feature.end = static_cast<unsigned>(-1);
- m_features.append(feature);
- }
-}
-
-bool HarfBuzzShaper::shape(GlyphBuffer* glyphBuffer)
-{
- if (!collectHarfBuzzRuns())
- return false;
-
- m_totalWidth = 0;
- // WebKit doesn't set direction when calulating widths. Leave the direction setting to
- // HarfBuzz when we are calculating widths (except when directionalOverride() is set).
- if (!shapeHarfBuzzRuns(glyphBuffer || m_run.directionalOverride()))
- return false;
-
- if (!RuntimeEnabledFeatures::subpixelFontScalingEnabled())
- m_totalWidth = roundf(m_totalWidth);
-
- if (glyphBuffer && !fillGlyphBuffer(glyphBuffer))
- return false;
-
- return true;
-}
-
-FloatPoint HarfBuzzShaper::adjustStartPoint(const FloatPoint& point)
-{
- return point + m_startOffset;
-}
-
-bool HarfBuzzShaper::collectHarfBuzzRuns()
-{
- const UChar* normalizedBufferEnd = m_normalizedBuffer.get() + m_normalizedBufferLength;
- SurrogatePairAwareTextIterator iterator(m_normalizedBuffer.get(), 0, m_normalizedBufferLength, m_normalizedBufferLength);
- UChar32 character;
- unsigned clusterLength = 0;
- unsigned startIndexOfCurrentRun = 0;
- if (!iterator.consume(character, clusterLength))
- return false;
-
- const SimpleFontData* nextFontData = m_font->glyphDataForCharacter(character, false).fontData;
- UErrorCode errorCode = U_ZERO_ERROR;
- UScriptCode nextScript = uscript_getScript(character, &errorCode);
- if (U_FAILURE(errorCode))
- return false;
-
- do {
- const UChar* currentCharacterPosition = iterator.characters();
- const SimpleFontData* currentFontData = nextFontData;
- UScriptCode currentScript = nextScript;
-
- for (iterator.advance(clusterLength); iterator.consume(character, clusterLength); iterator.advance(clusterLength)) {
- if (Font::treatAsZeroWidthSpace(character))
- continue;
-
- if (U_GET_GC_MASK(character) & U_GC_M_MASK) {
- int markLength = clusterLength;
- const UChar* markCharactersEnd = iterator.characters() + clusterLength;
- while (markCharactersEnd < normalizedBufferEnd) {
- UChar32 nextCharacter;
- int nextCharacterLength = 0;
- U16_NEXT(markCharactersEnd, nextCharacterLength, normalizedBufferEnd - markCharactersEnd, nextCharacter);
- if (!(U_GET_GC_MASK(nextCharacter) & U_GC_M_MASK))
- break;
- markLength += nextCharacterLength;
- markCharactersEnd += nextCharacterLength;
- }
-
- if (currentFontData->canRenderCombiningCharacterSequence(currentCharacterPosition, markCharactersEnd - currentCharacterPosition)) {
- clusterLength = markLength;
- continue;
- }
- }
-
- nextFontData = m_font->glyphDataForCharacter(character, false).fontData;
- nextScript = uscript_getScript(character, &errorCode);
- if (U_FAILURE(errorCode))
- return false;
- if ((nextFontData != currentFontData) || ((currentScript != nextScript) && (nextScript != USCRIPT_INHERITED) && (!uscript_hasScript(character, currentScript))))
- break;
- if (nextScript == USCRIPT_INHERITED)
- nextScript = currentScript;
- currentCharacterPosition = iterator.characters();
- }
- unsigned numCharactersOfCurrentRun = iterator.currentCharacter() - startIndexOfCurrentRun;
- hb_script_t script = hb_icu_script_to_script(currentScript);
- m_harfBuzzRuns.append(HarfBuzzRun::create(currentFontData, startIndexOfCurrentRun, numCharactersOfCurrentRun, m_run.direction(), script));
- currentFontData = nextFontData;
- startIndexOfCurrentRun = iterator.currentCharacter();
- } while (iterator.consume(character, clusterLength));
-
- return !m_harfBuzzRuns.isEmpty();
-}
-
-bool HarfBuzzShaper::shapeHarfBuzzRuns(bool shouldSetDirection)
-{
- HarfBuzzScopedPtr<hb_buffer_t> harfBuzzBuffer(hb_buffer_create(), hb_buffer_destroy);
-
- hb_buffer_set_unicode_funcs(harfBuzzBuffer.get(), hb_icu_get_unicode_funcs());
- HarfBuzzRunCache& runCache = harfBuzzRunCache();
-
- for (unsigned i = 0; i < m_harfBuzzRuns.size(); ++i) {
- unsigned runIndex = m_run.rtl() ? m_harfBuzzRuns.size() - i - 1 : i;
- HarfBuzzRun* currentRun = m_harfBuzzRuns[runIndex].get();
- const SimpleFontData* currentFontData = currentRun->fontData();
- if (currentFontData->isSVGFont())
- return false;
-
- FontPlatformData* platformData = const_cast<FontPlatformData*>(&currentFontData->platformData());
- HarfBuzzFace* face = platformData->harfBuzzFace();
- if (!face)
- return false;
-
- hb_buffer_set_script(harfBuzzBuffer.get(), currentRun->script());
- if (shouldSetDirection)
- hb_buffer_set_direction(harfBuzzBuffer.get(), currentRun->rtl() ? HB_DIRECTION_RTL : HB_DIRECTION_LTR);
- else
- // Leaving direction to HarfBuzz to guess is *really* bad, but will do for now.
- hb_buffer_guess_segment_properties(harfBuzzBuffer.get());
-
- hb_segment_properties_t props;
- hb_buffer_get_segment_properties(harfBuzzBuffer.get(), &props);
-
- const UChar* src = m_normalizedBuffer.get() + currentRun->startIndex();
- std::wstring key(src, src + currentRun->numCharacters());
-
- CachedShapingResults* cachedResults = runCache.find(key);
- if (cachedResults) {
- if (cachedResults->dir == props.direction && cachedResults->font == *m_font) {
- currentRun->applyShapeResult(cachedResults->buffer);
- setGlyphPositionsForHarfBuzzRun(currentRun, cachedResults->buffer);
-
- hb_buffer_reset(harfBuzzBuffer.get());
-
- runCache.moveToBack(cachedResults);
-
- continue;
- }
-
- runCache.remove(cachedResults);
- }
-
- // Add a space as pre-context to the buffer. This prevents showing dotted-circle
- // for combining marks at the beginning of runs.
- static const uint16_t preContext = ' ';
- hb_buffer_add_utf16(harfBuzzBuffer.get(), &preContext, 1, 1, 0);
-
- if (m_font->isSmallCaps() && u_islower(m_normalizedBuffer[currentRun->startIndex()])) {
- String upperText = String(m_normalizedBuffer.get() + currentRun->startIndex(), currentRun->numCharacters());
- upperText.makeUpper();
- currentFontData = m_font->glyphDataForCharacter(upperText[0], false, SmallCapsVariant).fontData;
- ASSERT(!upperText.is8Bit()); // m_normalizedBuffer is 16 bit, therefore upperText is 16 bit, even after we call makeUpper().
- hb_buffer_add_utf16(harfBuzzBuffer.get(), upperText.characters16(), currentRun->numCharacters(), 0, currentRun->numCharacters());
- } else
- hb_buffer_add_utf16(harfBuzzBuffer.get(), m_normalizedBuffer.get() + currentRun->startIndex(), currentRun->numCharacters(), 0, currentRun->numCharacters());
-
- if (m_font->fontDescription().orientation() == Vertical)
- face->setScriptForVerticalGlyphSubstitution(harfBuzzBuffer.get());
-
- HarfBuzzScopedPtr<hb_font_t> harfBuzzFont(face->createFont(), hb_font_destroy);
-
- hb_shape(harfBuzzFont.get(), harfBuzzBuffer.get(), m_features.isEmpty() ? 0 : m_features.data(), m_features.size());
- currentRun->applyShapeResult(harfBuzzBuffer.get());
- setGlyphPositionsForHarfBuzzRun(currentRun, harfBuzzBuffer.get());
-
- runCache.insert(key, new CachedShapingResults(harfBuzzBuffer.get(), m_font, props.direction));
-
- harfBuzzBuffer.set(hb_buffer_create());
- hb_buffer_set_unicode_funcs(harfBuzzBuffer.get(), hb_icu_get_unicode_funcs());
- }
-
- return true;
-}
-
-void HarfBuzzShaper::setGlyphPositionsForHarfBuzzRun(HarfBuzzRun* currentRun, hb_buffer_t* harfBuzzBuffer)
-{
- const SimpleFontData* currentFontData = currentRun->fontData();
- hb_glyph_info_t* glyphInfos = hb_buffer_get_glyph_infos(harfBuzzBuffer, 0);
- hb_glyph_position_t* glyphPositions = hb_buffer_get_glyph_positions(harfBuzzBuffer, 0);
-
- unsigned numGlyphs = currentRun->numGlyphs();
- uint16_t* glyphToCharacterIndexes = currentRun->glyphToCharacterIndexes();
- float totalAdvance = 0;
-
- // HarfBuzz returns the shaping result in visual order. We need not to flip for RTL.
- for (size_t i = 0; i < numGlyphs; ++i) {
- bool runEnd = i + 1 == numGlyphs;
- uint16_t glyph = glyphInfos[i].codepoint;
- float offsetX = harfBuzzPositionToFloat(glyphPositions[i].x_offset);
- float offsetY = -harfBuzzPositionToFloat(glyphPositions[i].y_offset);
- float advance = harfBuzzPositionToFloat(glyphPositions[i].x_advance);
-
- unsigned currentCharacterIndex = currentRun->startIndex() + glyphInfos[i].cluster;
- bool isClusterEnd = runEnd || glyphInfos[i].cluster != glyphInfos[i + 1].cluster;
- float spacing = 0;
-
- glyphToCharacterIndexes[i] = glyphInfos[i].cluster;
-
- if (isClusterEnd && !Font::treatAsZeroWidthSpace(m_normalizedBuffer[currentCharacterIndex]))
- spacing += m_letterSpacing;
-
- if (isClusterEnd && isWordEnd(currentCharacterIndex))
- spacing += determineWordBreakSpacing();
-
- if (currentFontData->isZeroWidthSpaceGlyph(glyph)) {
- currentRun->setGlyphAndPositions(i, glyph, 0, 0, 0);
- continue;
- }
-
- advance += spacing;
- if (m_run.rtl()) {
- // In RTL, spacing should be added to left side of glyphs.
- offsetX += spacing;
- if (!isClusterEnd)
- offsetX += m_letterSpacing;
- }
-
- currentRun->setGlyphAndPositions(i, glyph, advance, offsetX, offsetY);
-
- totalAdvance += advance;
- }
- currentRun->setWidth(totalAdvance > 0.0 ? totalAdvance : 0.0);
- m_totalWidth += currentRun->width();
-}
-
-void HarfBuzzShaper::fillGlyphBufferFromHarfBuzzRun(GlyphBuffer* glyphBuffer, HarfBuzzRun* currentRun, FloatPoint& firstOffsetOfNextRun)
-{
- FloatPoint* offsets = currentRun->offsets();
- uint16_t* glyphs = currentRun->glyphs();
- float* advances = currentRun->advances();
- unsigned numGlyphs = currentRun->numGlyphs();
- uint16_t* glyphToCharacterIndexes = currentRun->glyphToCharacterIndexes();
-
- for (unsigned i = 0; i < numGlyphs; ++i) {
- uint16_t currentCharacterIndex = currentRun->startIndex() + glyphToCharacterIndexes[i];
- FloatPoint& currentOffset = offsets[i];
- FloatPoint& nextOffset = (i == numGlyphs - 1) ? firstOffsetOfNextRun : offsets[i + 1];
- float glyphAdvanceX = advances[i] + nextOffset.x() - currentOffset.x();
- float glyphAdvanceY = nextOffset.y() - currentOffset.y();
- if (m_run.rtl()) {
- if (currentCharacterIndex > m_toIndex)
- m_startOffset.move(glyphAdvanceX, glyphAdvanceY);
- else if (currentCharacterIndex >= m_fromIndex)
- glyphBuffer->add(glyphs[i], currentRun->fontData(), createGlyphBufferAdvance(glyphAdvanceX, glyphAdvanceY));
- } else {
- if (currentCharacterIndex < m_fromIndex)
- m_startOffset.move(glyphAdvanceX, glyphAdvanceY);
- else if (currentCharacterIndex < m_toIndex)
- glyphBuffer->add(glyphs[i], currentRun->fontData(), createGlyphBufferAdvance(glyphAdvanceX, glyphAdvanceY));
- }
- }
-}
-
-bool HarfBuzzShaper::fillGlyphBuffer(GlyphBuffer* glyphBuffer)
-{
- unsigned numRuns = m_harfBuzzRuns.size();
- if (m_run.rtl()) {
- m_startOffset = m_harfBuzzRuns.last()->offsets()[0];
- for (int runIndex = numRuns - 1; runIndex >= 0; --runIndex) {
- HarfBuzzRun* currentRun = m_harfBuzzRuns[runIndex].get();
- FloatPoint firstOffsetOfNextRun = !runIndex ? FloatPoint() : m_harfBuzzRuns[runIndex - 1]->offsets()[0];
- fillGlyphBufferFromHarfBuzzRun(glyphBuffer, currentRun, firstOffsetOfNextRun);
- }
- } else {
- m_startOffset = m_harfBuzzRuns.first()->offsets()[0];
- for (unsigned runIndex = 0; runIndex < numRuns; ++runIndex) {
- HarfBuzzRun* currentRun = m_harfBuzzRuns[runIndex].get();
- FloatPoint firstOffsetOfNextRun = runIndex == numRuns - 1 ? FloatPoint() : m_harfBuzzRuns[runIndex + 1]->offsets()[0];
- fillGlyphBufferFromHarfBuzzRun(glyphBuffer, currentRun, firstOffsetOfNextRun);
- }
- }
- return glyphBuffer->size();
-}
-
-int HarfBuzzShaper::offsetForPosition(float targetX)
-{
- int charactersSoFar = 0;
- float currentX = 0;
-
- if (m_run.rtl()) {
- charactersSoFar = m_normalizedBufferLength;
- for (int i = m_harfBuzzRuns.size() - 1; i >= 0; --i) {
- charactersSoFar -= m_harfBuzzRuns[i]->numCharacters();
- float nextX = currentX + m_harfBuzzRuns[i]->width();
- float offsetForRun = targetX - currentX;
- if (offsetForRun >= 0 && offsetForRun <= m_harfBuzzRuns[i]->width()) {
- // The x value in question is within this script run.
- const unsigned index = m_harfBuzzRuns[i]->characterIndexForXPosition(offsetForRun);
- return charactersSoFar + index;
- }
- currentX = nextX;
- }
- } else {
- for (unsigned i = 0; i < m_harfBuzzRuns.size(); ++i) {
- float nextX = currentX + m_harfBuzzRuns[i]->width();
- float offsetForRun = targetX - currentX;
- if (offsetForRun >= 0 && offsetForRun <= m_harfBuzzRuns[i]->width()) {
- const unsigned index = m_harfBuzzRuns[i]->characterIndexForXPosition(offsetForRun);
- return charactersSoFar + index;
- }
- charactersSoFar += m_harfBuzzRuns[i]->numCharacters();
- currentX = nextX;
- }
- }
-
- return charactersSoFar;
-}
-
-FloatRect HarfBuzzShaper::selectionRect(const FloatPoint& point, int height, int from, int to)
-{
- float currentX = 0;
- float fromX = 0;
- float toX = 0;
- bool foundFromX = false;
- bool foundToX = false;
-
- if (m_run.rtl())
- currentX = m_totalWidth;
- for (unsigned i = 0; i < m_harfBuzzRuns.size(); ++i) {
- if (m_run.rtl())
- currentX -= m_harfBuzzRuns[i]->width();
- int numCharacters = m_harfBuzzRuns[i]->numCharacters();
- if (!foundFromX && from >= 0 && from < numCharacters) {
- fromX = m_harfBuzzRuns[i]->xPositionForOffset(from) + currentX;
- foundFromX = true;
- } else
- from -= numCharacters;
-
- if (!foundToX && to >= 0 && to < numCharacters) {
- toX = m_harfBuzzRuns[i]->xPositionForOffset(to) + currentX;
- foundToX = true;
- } else
- to -= numCharacters;
-
- if (foundFromX && foundToX)
- break;
- if (!m_run.rtl())
- currentX += m_harfBuzzRuns[i]->width();
- }
-
- // The position in question might be just after the text.
- if (!foundFromX)
- fromX = 0;
- if (!foundToX)
- toX = m_run.rtl() ? 0 : m_totalWidth;
-
- // Using floorf() and roundf() as the same as mac port.
- if (fromX < toX)
- return FloatRect(floorf(point.x() + fromX), point.y(), roundf(toX - fromX), height);
- return FloatRect(floorf(point.x() + toX), point.y(), roundf(fromX - toX), height);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/harfbuzz/HarfBuzzShaper.h b/chromium/third_party/WebKit/Source/core/platform/graphics/harfbuzz/HarfBuzzShaper.h
deleted file mode 100644
index c9062625519..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/harfbuzz/HarfBuzzShaper.h
+++ /dev/null
@@ -1,161 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef HarfBuzzShaper_h
-#define HarfBuzzShaper_h
-
-#include "core/platform/graphics/FloatPoint.h"
-#include "core/platform/graphics/GlyphBuffer.h"
-#include "core/platform/graphics/TextRun.h"
-#include "hb.h"
-#include "wtf/HashSet.h"
-#include "wtf/OwnArrayPtr.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/unicode/CharacterNames.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-class Font;
-class SimpleFontData;
-
-class HarfBuzzShaper {
-public:
- enum NormalizeMode {
- DoNotNormalizeMirrorChars,
- NormalizeMirrorChars
- };
-
- HarfBuzzShaper(const Font*, const TextRun&);
- virtual ~HarfBuzzShaper();
-
- void setDrawRange(int from, int to);
- bool shape(GlyphBuffer* = 0);
- FloatPoint adjustStartPoint(const FloatPoint&);
- float totalWidth() { return m_totalWidth; }
- int offsetForPosition(float targetX);
- FloatRect selectionRect(const FloatPoint&, int height, int from, int to);
-
-private:
- class HarfBuzzRun {
- public:
- HarfBuzzRun(const HarfBuzzRun&);
- ~HarfBuzzRun();
-
- static PassOwnPtr<HarfBuzzRun> create(const SimpleFontData* fontData, unsigned startIndex, unsigned numCharacters, TextDirection direction, hb_script_t script)
- {
- return adoptPtr(new HarfBuzzRun(fontData, startIndex, numCharacters, direction, script));
- }
-
- void applyShapeResult(hb_buffer_t*);
- void copyShapeResultAndGlyphPositions(const HarfBuzzRun&);
- void setGlyphAndPositions(unsigned index, uint16_t glyphId, float advance, float offsetX, float offsetY);
- void setWidth(float width) { m_width = width; }
-
- int characterIndexForXPosition(float targetX);
- float xPositionForOffset(unsigned offset);
-
- const SimpleFontData* fontData() { return m_fontData; }
- unsigned startIndex() const { return m_startIndex; }
- unsigned numCharacters() const { return m_numCharacters; }
- unsigned numGlyphs() const { return m_numGlyphs; }
- uint16_t* glyphs() { return &m_glyphs[0]; }
- float* advances() { return &m_advances[0]; }
- FloatPoint* offsets() { return &m_offsets[0]; }
- uint16_t* glyphToCharacterIndexes() { return &m_glyphToCharacterIndexes[0]; }
- float width() { return m_width; }
- bool rtl() { return m_direction == RTL; }
- hb_script_t script() { return m_script; }
-
- private:
- HarfBuzzRun(const SimpleFontData*, unsigned startIndex, unsigned numCharacters, TextDirection, hb_script_t);
-
- const SimpleFontData* m_fontData;
- unsigned m_startIndex;
- size_t m_numCharacters;
- unsigned m_numGlyphs;
- TextDirection m_direction;
- hb_script_t m_script;
- Vector<uint16_t, 256> m_glyphs;
- Vector<float, 256> m_advances;
- Vector<uint16_t, 256> m_glyphToCharacterIndexes;
- Vector<FloatPoint, 256> m_offsets;
- float m_width;
- };
-
- void setNormalizedBuffer(NormalizeMode = DoNotNormalizeMirrorChars);
-
- bool isWordEnd(unsigned);
- int determineWordBreakSpacing();
- // setPadding sets a number of pixels to be distributed across the TextRun.
- // WebKit uses this to justify text.
- void setPadding(int);
-
- // In complex text word-spacing affects each line-break, space (U+0020) and non-breaking space (U+00A0).
- static bool isCodepointSpace(UChar c) { return c == ' ' || c == noBreakSpace || c == '\n'; }
-
- void setFontFeatures();
-
- bool collectHarfBuzzRuns();
- bool shapeHarfBuzzRuns(bool shouldSetDirection);
- bool fillGlyphBuffer(GlyphBuffer*);
- void fillGlyphBufferFromHarfBuzzRun(GlyphBuffer*, HarfBuzzRun*, FloatPoint& firstOffsetOfNextRun);
- void setGlyphPositionsForHarfBuzzRun(HarfBuzzRun*, hb_buffer_t*);
-
- GlyphBufferAdvance createGlyphBufferAdvance(float, float);
-
- const Font* m_font;
- OwnArrayPtr<UChar> m_normalizedBuffer;
- unsigned m_normalizedBufferLength;
- const TextRun& m_run;
-
- int m_wordSpacingAdjustment; // Delta adjustment (pixels) for each word break.
- float m_padding; // Pixels to be distributed over the line at word breaks.
- float m_padPerWordBreak; // Pixels to be added to each word break.
- float m_padError; // m_padPerWordBreak might have a fractional component. Since we only add a whole number of padding pixels at each word break we accumulate error. This is the number of pixels that we are behind so far.
- int m_letterSpacing; // Pixels to be added after each glyph.
-
- Vector<hb_feature_t, 4> m_features;
- Vector<OwnPtr<HarfBuzzRun>, 16> m_harfBuzzRuns;
-
- FloatPoint m_startOffset;
-
- int m_fromIndex;
- int m_toIndex;
-
- float m_totalWidth;
-
- friend struct CachedShapingResults;
-};
-
-} // namespace WebCore
-
-#endif // HarfBuzzShaper_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/mac/ColorMac.h b/chromium/third_party/WebKit/Source/core/platform/graphics/mac/ColorMac.h
deleted file mode 100644
index da14b972ab9..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/mac/ColorMac.h
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright (C) 2007 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ColorMac_h
-#define ColorMac_h
-
-#include "core/platform/graphics/Color.h"
-
-OBJC_CLASS NSColor;
-
-namespace WebCore {
-
- // These functions assume NSColors are in DeviceRGB colorspace
- Color colorFromNSColor(NSColor *);
- NSColor *nsColor(const Color&);
-
- bool usesTestModeFocusRingColor();
- void setUsesTestModeFocusRingColor(bool);
-
- // Focus ring color used for testing purposes.
- RGBA32 oldAquaFocusRingColor();
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/mac/ColorMac.mm b/chromium/third_party/WebKit/Source/core/platform/graphics/mac/ColorMac.mm
deleted file mode 100644
index 48ff8e47f78..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/mac/ColorMac.mm
+++ /dev/null
@@ -1,112 +0,0 @@
-/*
- * Copyright (C) 2003, 2004, 2005, 2006 Apple Computer, Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#import "config.h"
-#import "core/platform/graphics/mac/ColorMac.h"
-
-#import <wtf/RetainPtr.h>
-#import <wtf/StdLibExtras.h>
-
-namespace WebCore {
-
-// NSColor calls don't throw, so no need to block Cocoa exceptions in this file
-
-static bool useOldAquaFocusRingColor;
-
-RGBA32 oldAquaFocusRingColor()
-{
- return 0xFF7DADD9;
-}
-
-void setUsesTestModeFocusRingColor(bool newValue)
-{
- useOldAquaFocusRingColor = newValue;
-}
-
-bool usesTestModeFocusRingColor()
-{
- return useOldAquaFocusRingColor;
-}
-
-static RGBA32 makeRGBAFromNSColor(NSColor *c)
-{
- CGFloat redComponent;
- CGFloat greenComponent;
- CGFloat blueComponent;
- CGFloat alpha;
- [c getRed:&redComponent green:&greenComponent blue:&blueComponent alpha:&alpha];
-
- return makeRGBA(255 * redComponent, 255 * greenComponent, 255 * blueComponent, 255 * alpha);
-}
-
-Color colorFromNSColor(NSColor *c)
-{
- return Color(makeRGBAFromNSColor(c));
-}
-
-NSColor *nsColor(const Color& color)
-{
- RGBA32 c = color.rgb();
- switch (c) {
- case 0: {
- // Need this to avoid returning nil because cachedRGBAValues will default to 0.
- DEFINE_STATIC_LOCAL(RetainPtr<NSColor>, clearColor, ([NSColor colorWithDeviceRed:0 green:0 blue:0 alpha:0]));
- return clearColor.get();
- }
- case Color::black: {
- DEFINE_STATIC_LOCAL(RetainPtr<NSColor>, blackColor, ([NSColor colorWithDeviceRed:0 green:0 blue:0 alpha:1]));
- return blackColor.get();
- }
- case Color::white: {
- DEFINE_STATIC_LOCAL(RetainPtr<NSColor>, whiteColor, ([NSColor colorWithDeviceRed:1 green:1 blue:1 alpha:1]));
- return whiteColor.get();
- }
- default: {
- const int cacheSize = 32;
- static unsigned cachedRGBAValues[cacheSize];
- static RetainPtr<NSColor>* cachedColors = new RetainPtr<NSColor>[cacheSize];
-
- for (int i = 0; i != cacheSize; ++i) {
- if (cachedRGBAValues[i] == c)
- return cachedColors[i].get();
- }
-
- NSColor *result = [NSColor colorWithDeviceRed:static_cast<CGFloat>(color.red()) / 255
- green:static_cast<CGFloat>(color.green()) / 255
- blue:static_cast<CGFloat>(color.blue()) / 255
- alpha:static_cast<CGFloat>(color.alpha()) / 255];
-
- static int cursor;
- cachedRGBAValues[cursor] = c;
- cachedColors[cursor] = result;
- if (++cursor == cacheSize)
- cursor = 0;
- return result;
- }
- }
-}
-
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/mac/ComplexTextController.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/mac/ComplexTextController.cpp
deleted file mode 100644
index 8811f4b9812..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/mac/ComplexTextController.cpp
+++ /dev/null
@@ -1,730 +0,0 @@
-/*
- * Copyright (C) 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/mac/ComplexTextController.h"
-
-#include <ApplicationServices/ApplicationServices.h>
-#include "core/platform/graphics/FloatSize.h"
-#include "core/platform/graphics/Font.h"
-#include "core/platform/graphics/TextRun.h"
-#include "core/platform/text/TextBreakIterator.h"
-#include "core/rendering/RenderBlock.h"
-#include "core/rendering/RenderText.h"
-#include "wtf/StdLibExtras.h"
-#include "wtf/unicode/CharacterNames.h"
-
-using namespace std;
-
-namespace WebCore {
-
-class TextLayout {
-public:
- static bool isNeeded(RenderText* text, const Font& font)
- {
- TextRun run = RenderBlock::constructTextRun(text, font, text, text->style());
- return font.codePath(run) == Font::Complex;
- }
-
- TextLayout(RenderText* text, const Font& font, float xPos)
- : m_font(font)
- , m_run(constructTextRun(text, font, xPos))
- , m_controller(adoptPtr(new ComplexTextController(&m_font, m_run, true)))
- {
- }
-
- float width(unsigned from, unsigned len, HashSet<const SimpleFontData*>* fallbackFonts)
- {
- m_controller->advance(from, 0, ByWholeGlyphs, fallbackFonts);
- float beforeWidth = m_controller->runWidthSoFar();
- if (m_font.wordSpacing() && from && Font::treatAsSpace(m_run[from]))
- beforeWidth += m_font.wordSpacing();
- m_controller->advance(from + len, 0, ByWholeGlyphs, fallbackFonts);
- float afterWidth = m_controller->runWidthSoFar();
- return afterWidth - beforeWidth;
- }
-
-private:
- static TextRun constructTextRun(RenderText* text, const Font& font, float xPos)
- {
- TextRun run = RenderBlock::constructTextRun(text, font, text, text->style());
- run.setCharactersLength(text->textLength());
- ASSERT(run.charactersLength() >= run.length());
-
- run.setXPos(xPos);
- return run;
- }
-
- // ComplexTextController has only references to its Font and TextRun so they must be kept alive here.
- Font m_font;
- TextRun m_run;
- OwnPtr<ComplexTextController> m_controller;
-};
-
-PassOwnPtr<TextLayout> Font::createLayout(RenderText* text, float xPos, bool collapseWhiteSpace) const
-{
- if (!collapseWhiteSpace || !TextLayout::isNeeded(text, *this))
- return nullptr;
- return adoptPtr(new TextLayout(text, *this, xPos));
-}
-
-void Font::deleteLayout(TextLayout* layout)
-{
- delete layout;
-}
-
-float Font::width(TextLayout& layout, unsigned from, unsigned len, HashSet<const SimpleFontData*>* fallbackFonts)
-{
- return layout.width(from, len, fallbackFonts);
-}
-
-static inline CGFloat roundCGFloat(CGFloat f)
-{
- if (sizeof(CGFloat) == sizeof(float))
- return roundf(static_cast<float>(f));
- return static_cast<CGFloat>(round(f));
-}
-
-static inline CGFloat ceilCGFloat(CGFloat f)
-{
- if (sizeof(CGFloat) == sizeof(float))
- return ceilf(static_cast<float>(f));
- return static_cast<CGFloat>(ceil(f));
-}
-
-ComplexTextController::ComplexTextController(const Font* font, const TextRun& run, bool mayUseNaturalWritingDirection, HashSet<const SimpleFontData*>* fallbackFonts, bool forTextEmphasis)
- : m_font(*font)
- , m_run(run)
- , m_isLTROnly(true)
- , m_mayUseNaturalWritingDirection(mayUseNaturalWritingDirection)
- , m_forTextEmphasis(forTextEmphasis)
- , m_currentCharacter(0)
- , m_end(run.length())
- , m_totalWidth(0)
- , m_runWidthSoFar(0)
- , m_numGlyphsSoFar(0)
- , m_currentRun(0)
- , m_glyphInCurrentRun(0)
- , m_characterInCurrentGlyph(0)
- , m_finalRoundingWidth(0)
- , m_expansion(run.expansion())
- , m_leadingExpansion(0)
- , m_afterExpansion(!run.allowsLeadingExpansion())
- , m_fallbackFonts(fallbackFonts)
- , m_minGlyphBoundingBoxX(numeric_limits<float>::max())
- , m_maxGlyphBoundingBoxX(numeric_limits<float>::min())
- , m_minGlyphBoundingBoxY(numeric_limits<float>::max())
- , m_maxGlyphBoundingBoxY(numeric_limits<float>::min())
- , m_lastRoundingGlyph(0)
-{
- if (!m_expansion)
- m_expansionPerOpportunity = 0;
- else {
- bool isAfterExpansion = m_afterExpansion;
- unsigned expansionOpportunityCount;
- if (m_run.is8Bit())
- expansionOpportunityCount = Font::expansionOpportunityCount(m_run.characters8(), m_end, m_run.ltr() ? LTR : RTL, isAfterExpansion);
- else
- expansionOpportunityCount = Font::expansionOpportunityCount(m_run.characters16(), m_end, m_run.ltr() ? LTR : RTL, isAfterExpansion);
- if (isAfterExpansion && !m_run.allowsTrailingExpansion())
- expansionOpportunityCount--;
-
- if (!expansionOpportunityCount)
- m_expansionPerOpportunity = 0;
- else
- m_expansionPerOpportunity = m_expansion / expansionOpportunityCount;
- }
-
- collectComplexTextRuns();
- adjustGlyphsAndAdvances();
-
- if (!m_isLTROnly) {
- m_runIndices.reserveInitialCapacity(m_complexTextRuns.size());
-
- m_glyphCountFromStartToIndex.reserveInitialCapacity(m_complexTextRuns.size());
- unsigned glyphCountSoFar = 0;
- for (unsigned i = 0; i < m_complexTextRuns.size(); ++i) {
- m_glyphCountFromStartToIndex.uncheckedAppend(glyphCountSoFar);
- glyphCountSoFar += m_complexTextRuns[i]->glyphCount();
- }
- }
-
- m_runWidthSoFar = m_leadingExpansion;
-}
-
-int ComplexTextController::offsetForPosition(float h, bool includePartialGlyphs)
-{
- if (h >= m_totalWidth)
- return m_run.ltr() ? m_end : 0;
-
- h -= m_leadingExpansion;
- if (h < 0)
- return m_run.ltr() ? 0 : m_end;
-
- CGFloat x = h;
-
- size_t runCount = m_complexTextRuns.size();
- size_t offsetIntoAdjustedGlyphs = 0;
-
- for (size_t r = 0; r < runCount; ++r) {
- const ComplexTextRun& complexTextRun = *m_complexTextRuns[r];
- for (unsigned j = 0; j < complexTextRun.glyphCount(); ++j) {
- CGFloat adjustedAdvance = m_adjustedAdvances[offsetIntoAdjustedGlyphs + j].width;
- if (x < adjustedAdvance) {
- CFIndex hitGlyphStart = complexTextRun.indexAt(j);
- CFIndex hitGlyphEnd;
- if (m_run.ltr())
- hitGlyphEnd = max<CFIndex>(hitGlyphStart, j + 1 < complexTextRun.glyphCount() ? complexTextRun.indexAt(j + 1) : static_cast<CFIndex>(complexTextRun.indexEnd()));
- else
- hitGlyphEnd = max<CFIndex>(hitGlyphStart, j > 0 ? complexTextRun.indexAt(j - 1) : static_cast<CFIndex>(complexTextRun.indexEnd()));
-
- // FIXME: Instead of dividing the glyph's advance equally between the characters, this
- // could use the glyph's "ligature carets". However, there is no Core Text API to get the
- // ligature carets.
- CFIndex hitIndex = hitGlyphStart + (hitGlyphEnd - hitGlyphStart) * (m_run.ltr() ? x / adjustedAdvance : 1 - x / adjustedAdvance);
- int stringLength = complexTextRun.stringLength();
- TextBreakIterator* cursorPositionIterator = cursorMovementIterator(complexTextRun.characters(), stringLength);
- int clusterStart;
- if (isTextBreak(cursorPositionIterator, hitIndex))
- clusterStart = hitIndex;
- else {
- clusterStart = textBreakPreceding(cursorPositionIterator, hitIndex);
- if (clusterStart == TextBreakDone)
- clusterStart = 0;
- }
-
- if (!includePartialGlyphs)
- return complexTextRun.stringLocation() + clusterStart;
-
- int clusterEnd = textBreakFollowing(cursorPositionIterator, hitIndex);
- if (clusterEnd == TextBreakDone)
- clusterEnd = stringLength;
-
- CGFloat clusterWidth;
- // FIXME: The search stops at the boundaries of complexTextRun. In theory, it should go on into neighboring ComplexTextRuns
- // derived from the same CTLine. In practice, we do not expect there to be more than one CTRun in a CTLine, as no
- // reordering and no font fallback should occur within a CTLine.
- if (clusterEnd - clusterStart > 1) {
- clusterWidth = adjustedAdvance;
- int firstGlyphBeforeCluster = j - 1;
- while (firstGlyphBeforeCluster >= 0 && complexTextRun.indexAt(firstGlyphBeforeCluster) >= clusterStart && complexTextRun.indexAt(firstGlyphBeforeCluster) < clusterEnd) {
- CGFloat width = m_adjustedAdvances[offsetIntoAdjustedGlyphs + firstGlyphBeforeCluster].width;
- clusterWidth += width;
- x += width;
- firstGlyphBeforeCluster--;
- }
- unsigned firstGlyphAfterCluster = j + 1;
- while (firstGlyphAfterCluster < complexTextRun.glyphCount() && complexTextRun.indexAt(firstGlyphAfterCluster) >= clusterStart && complexTextRun.indexAt(firstGlyphAfterCluster) < clusterEnd) {
- clusterWidth += m_adjustedAdvances[offsetIntoAdjustedGlyphs + firstGlyphAfterCluster].width;
- firstGlyphAfterCluster++;
- }
- } else {
- clusterWidth = adjustedAdvance / (hitGlyphEnd - hitGlyphStart);
- x -= clusterWidth * (m_run.ltr() ? hitIndex - hitGlyphStart : hitGlyphEnd - hitIndex - 1);
- }
- if (x <= clusterWidth / 2)
- return complexTextRun.stringLocation() + (m_run.ltr() ? clusterStart : clusterEnd);
- else
- return complexTextRun.stringLocation() + (m_run.ltr() ? clusterEnd : clusterStart);
- }
- x -= adjustedAdvance;
- }
- offsetIntoAdjustedGlyphs += complexTextRun.glyphCount();
- }
-
- ASSERT_NOT_REACHED();
- return 0;
-}
-
-static bool advanceByCombiningCharacterSequence(const UChar*& iterator, const UChar* end, UChar32& baseCharacter, unsigned& markCount)
-{
- ASSERT(iterator < end);
-
- markCount = 0;
-
- baseCharacter = *iterator++;
-
- if (U16_IS_SURROGATE(baseCharacter)) {
- if (!U16_IS_LEAD(baseCharacter))
- return false;
- if (iterator == end)
- return false;
- UChar trail = *iterator++;
- if (!U16_IS_TRAIL(trail))
- return false;
- baseCharacter = U16_GET_SUPPLEMENTARY(baseCharacter, trail);
- }
-
- // Consume marks.
- while (iterator < end) {
- UChar32 nextCharacter;
- int markLength = 0;
- U16_NEXT(iterator, markLength, end - iterator, nextCharacter);
- if (!(U_GET_GC_MASK(nextCharacter) & U_GC_M_MASK))
- break;
- markCount += markLength;
- iterator += markLength;
- }
-
- return true;
-}
-
-void ComplexTextController::collectComplexTextRuns()
-{
- if (!m_end)
- return;
-
- // We break up glyph run generation for the string by FontData.
- const UChar* cp;
-
- if (m_run.is8Bit()) {
- String stringFor8BitRun = String::make16BitFrom8BitSource(m_run.characters8(), m_run.length());
- cp = stringFor8BitRun.characters16();
- m_stringsFor8BitRuns.append(stringFor8BitRun);
- } else
- cp = m_run.characters16();
-
- if (m_font.isSmallCaps())
- m_smallCapsBuffer.resize(m_end);
-
- unsigned indexOfFontTransition = 0;
- const UChar* curr = cp;
- const UChar* end = cp + m_end;
-
- const SimpleFontData* fontData;
- bool isMissingGlyph;
- const SimpleFontData* nextFontData;
- bool nextIsMissingGlyph;
-
- unsigned markCount;
- const UChar* sequenceStart = curr;
- UChar32 baseCharacter;
- if (!advanceByCombiningCharacterSequence(curr, end, baseCharacter, markCount))
- return;
-
- UChar uppercaseCharacter = 0;
-
- bool isSmallCaps;
- bool nextIsSmallCaps = m_font.isSmallCaps() && !(U_GET_GC_MASK(baseCharacter) & U_GC_M_MASK) && (uppercaseCharacter = u_toupper(baseCharacter)) != baseCharacter;
-
- if (nextIsSmallCaps) {
- m_smallCapsBuffer[sequenceStart - cp] = uppercaseCharacter;
- for (unsigned i = 0; i < markCount; ++i)
- m_smallCapsBuffer[sequenceStart - cp + i + 1] = sequenceStart[i + 1];
- }
-
- nextIsMissingGlyph = false;
- nextFontData = m_font.fontDataForCombiningCharacterSequence(sequenceStart, curr - sequenceStart, nextIsSmallCaps ? SmallCapsVariant : NormalVariant);
- if (!nextFontData)
- nextIsMissingGlyph = true;
-
- while (curr < end) {
- fontData = nextFontData;
- isMissingGlyph = nextIsMissingGlyph;
- isSmallCaps = nextIsSmallCaps;
- int index = curr - cp;
-
- if (!advanceByCombiningCharacterSequence(curr, end, baseCharacter, markCount))
- return;
-
- if (m_font.isSmallCaps()) {
- nextIsSmallCaps = (uppercaseCharacter = u_toupper(baseCharacter)) != baseCharacter;
- if (nextIsSmallCaps) {
- m_smallCapsBuffer[index] = uppercaseCharacter;
- for (unsigned i = 0; i < markCount; ++i)
- m_smallCapsBuffer[index + i + 1] = cp[index + i + 1];
- }
- }
-
- nextIsMissingGlyph = false;
- if (baseCharacter == zeroWidthJoiner)
- nextFontData = fontData;
- else {
- nextFontData = m_font.fontDataForCombiningCharacterSequence(cp + index, curr - cp - index, nextIsSmallCaps ? SmallCapsVariant : NormalVariant);
- if (!nextFontData)
- nextIsMissingGlyph = true;
- }
-
- if (nextFontData != fontData || nextIsMissingGlyph != isMissingGlyph) {
- int itemStart = static_cast<int>(indexOfFontTransition);
- int itemLength = index - indexOfFontTransition;
- collectComplexTextRunsForCharacters((isSmallCaps ? m_smallCapsBuffer.data() : cp) + itemStart, itemLength, itemStart, !isMissingGlyph ? fontData : 0);
- indexOfFontTransition = index;
- }
- }
-
- int itemLength = m_end - indexOfFontTransition;
- if (itemLength) {
- int itemStart = indexOfFontTransition;
- collectComplexTextRunsForCharacters((nextIsSmallCaps ? m_smallCapsBuffer.data() : cp) + itemStart, itemLength, itemStart, !nextIsMissingGlyph ? nextFontData : 0);
- }
-
- if (!m_run.ltr())
- m_complexTextRuns.reverse();
-}
-
-CFIndex ComplexTextController::ComplexTextRun::indexAt(size_t i) const
-{
- return m_coreTextIndices[i];
-}
-
-void ComplexTextController::ComplexTextRun::setIsNonMonotonic()
-{
- ASSERT(m_isMonotonic);
- m_isMonotonic = false;
-
- Vector<bool, 64> mappedIndices(m_stringLength);
- for (size_t i = 0; i < m_glyphCount; ++i) {
- ASSERT(indexAt(i) < static_cast<CFIndex>(m_stringLength));
- mappedIndices[indexAt(i)] = true;
- }
-
- m_glyphEndOffsets.grow(m_glyphCount);
- for (size_t i = 0; i < m_glyphCount; ++i) {
- CFIndex nextMappedIndex = m_indexEnd;
- for (size_t j = indexAt(i) + 1; j < m_stringLength; ++j) {
- if (mappedIndices[j]) {
- nextMappedIndex = j;
- break;
- }
- }
- m_glyphEndOffsets[i] = nextMappedIndex;
- }
-}
-
-unsigned ComplexTextController::findNextRunIndex(unsigned runIndex) const
-{
- const unsigned runOffset = stringEnd(*m_complexTextRuns[runIndex]);
-
- // Finds the run with the lowest stringBegin() offset that starts at or
- // after |runOffset|.
- //
- // Note that this can't just find a run whose stringBegin() equals the
- // stringEnd() of the previous run because CoreText on Mac OS X 10.6 does
- // not return runs covering BiDi control chars, so this has to handle the
- // resulting gaps.
- unsigned result = 0;
- unsigned lowestOffset = UINT_MAX;
- for (unsigned i = 0; i < m_complexTextRuns.size(); ++i) {
- unsigned offset = stringBegin(*m_complexTextRuns[i]);
- if (i != runIndex && offset >= runOffset && offset < lowestOffset) {
- lowestOffset = offset;
- result = i;
- }
- }
-
- ASSERT(lowestOffset != UINT_MAX);
- return result;
-}
-
-unsigned ComplexTextController::indexOfCurrentRun(unsigned& leftmostGlyph)
-{
- leftmostGlyph = 0;
-
- size_t runCount = m_complexTextRuns.size();
- if (m_currentRun >= runCount)
- return runCount;
-
- if (m_isLTROnly) {
- for (unsigned i = 0; i < m_currentRun; ++i)
- leftmostGlyph += m_complexTextRuns[i]->glyphCount();
- return m_currentRun;
- }
-
- if (m_runIndices.isEmpty()) {
- unsigned firstRun = 0;
- unsigned firstRunOffset = stringBegin(*m_complexTextRuns[0]);
- for (unsigned i = 1; i < runCount; ++i) {
- unsigned offset = stringBegin(*m_complexTextRuns[i]);
- if (offset < firstRunOffset) {
- firstRun = i;
- firstRunOffset = offset;
- }
- }
- m_runIndices.uncheckedAppend(firstRun);
- }
-
- while (m_runIndices.size() <= m_currentRun) {
- m_runIndices.uncheckedAppend(findNextRunIndex(m_runIndices.last()));
- }
-
- unsigned currentRunIndex = m_runIndices[m_currentRun];
- leftmostGlyph = m_glyphCountFromStartToIndex[currentRunIndex];
- return currentRunIndex;
-}
-
-unsigned ComplexTextController::incrementCurrentRun(unsigned& leftmostGlyph)
-{
- if (m_isLTROnly) {
- leftmostGlyph += m_complexTextRuns[m_currentRun++]->glyphCount();
- return m_currentRun;
- }
-
- m_currentRun++;
- leftmostGlyph = 0;
- return indexOfCurrentRun(leftmostGlyph);
-}
-
-void ComplexTextController::advance(unsigned offset, GlyphBuffer* glyphBuffer, GlyphIterationStyle iterationStyle, HashSet<const SimpleFontData*>* fallbackFonts)
-{
- if (static_cast<int>(offset) > m_end)
- offset = m_end;
-
- if (offset <= m_currentCharacter) {
- m_runWidthSoFar = m_leadingExpansion;
- m_numGlyphsSoFar = 0;
- m_currentRun = 0;
- m_glyphInCurrentRun = 0;
- m_characterInCurrentGlyph = 0;
- }
-
- m_currentCharacter = offset;
-
- size_t runCount = m_complexTextRuns.size();
-
- unsigned leftmostGlyph = 0;
- unsigned currentRunIndex = indexOfCurrentRun(leftmostGlyph);
- while (m_currentRun < runCount) {
- const ComplexTextRun& complexTextRun = *m_complexTextRuns[currentRunIndex];
- bool ltr = complexTextRun.isLTR();
- size_t glyphCount = complexTextRun.glyphCount();
- unsigned g = ltr ? m_glyphInCurrentRun : glyphCount - 1 - m_glyphInCurrentRun;
- unsigned k = leftmostGlyph + g;
- if (fallbackFonts && complexTextRun.fontData() != m_font.primaryFont())
- fallbackFonts->add(complexTextRun.fontData());
-
- while (m_glyphInCurrentRun < glyphCount) {
- unsigned glyphStartOffset = complexTextRun.indexAt(g);
- unsigned glyphEndOffset;
- if (complexTextRun.isMonotonic()) {
- if (ltr)
- glyphEndOffset = max<unsigned>(glyphStartOffset, static_cast<unsigned>(g + 1 < glyphCount ? complexTextRun.indexAt(g + 1) : complexTextRun.indexEnd()));
- else
- glyphEndOffset = max<unsigned>(glyphStartOffset, static_cast<unsigned>(g > 0 ? complexTextRun.indexAt(g - 1) : complexTextRun.indexEnd()));
- } else
- glyphEndOffset = complexTextRun.endOffsetAt(g);
-
- CGSize adjustedAdvance = m_adjustedAdvances[k];
-
- if (glyphStartOffset + complexTextRun.stringLocation() >= m_currentCharacter)
- return;
-
- if (glyphBuffer && !m_characterInCurrentGlyph)
- glyphBuffer->add(m_adjustedGlyphs[k], complexTextRun.fontData(), adjustedAdvance);
-
- unsigned oldCharacterInCurrentGlyph = m_characterInCurrentGlyph;
- m_characterInCurrentGlyph = min(m_currentCharacter - complexTextRun.stringLocation(), glyphEndOffset) - glyphStartOffset;
- // FIXME: Instead of dividing the glyph's advance equally between the characters, this
- // could use the glyph's "ligature carets". However, there is no Core Text API to get the
- // ligature carets.
- if (glyphStartOffset == glyphEndOffset) {
- // When there are multiple glyphs per character we need to advance by the full width of the glyph.
- ASSERT(m_characterInCurrentGlyph == oldCharacterInCurrentGlyph);
- m_runWidthSoFar += adjustedAdvance.width;
- } else if (iterationStyle == ByWholeGlyphs) {
- if (!oldCharacterInCurrentGlyph)
- m_runWidthSoFar += adjustedAdvance.width;
- } else
- m_runWidthSoFar += adjustedAdvance.width * (m_characterInCurrentGlyph - oldCharacterInCurrentGlyph) / (glyphEndOffset - glyphStartOffset);
-
- if (glyphEndOffset + complexTextRun.stringLocation() > m_currentCharacter)
- return;
-
- m_numGlyphsSoFar++;
- m_glyphInCurrentRun++;
- m_characterInCurrentGlyph = 0;
- if (ltr) {
- g++;
- k++;
- } else {
- g--;
- k--;
- }
- }
- currentRunIndex = incrementCurrentRun(leftmostGlyph);
- m_glyphInCurrentRun = 0;
- }
- if (!m_run.ltr() && m_numGlyphsSoFar == m_adjustedAdvances.size())
- m_runWidthSoFar += m_finalRoundingWidth;
-}
-
-void ComplexTextController::adjustGlyphsAndAdvances()
-{
- CGFloat widthSinceLastCommit = 0;
- size_t runCount = m_complexTextRuns.size();
- bool hasExtraSpacing = (m_font.letterSpacing() || m_font.wordSpacing() || m_expansion) && !m_run.spacingDisabled();
- for (size_t r = 0; r < runCount; ++r) {
- ComplexTextRun& complexTextRun = *m_complexTextRuns[r];
- unsigned glyphCount = complexTextRun.glyphCount();
- const SimpleFontData* fontData = complexTextRun.fontData();
-
- if (!complexTextRun.isLTR())
- m_isLTROnly = false;
-
- const CGGlyph* glyphs = complexTextRun.glyphs();
- const CGSize* advances = complexTextRun.advances();
-
- bool lastRun = r + 1 == runCount;
- bool roundsAdvances = !m_font.isPrinterFont() && fontData->platformData().roundsGlyphAdvances();
- float spaceWidth = fontData->spaceWidth() - fontData->syntheticBoldOffset();
- CGFloat roundedSpaceWidth = roundCGFloat(spaceWidth);
- const UChar* cp = complexTextRun.characters();
- CGPoint glyphOrigin = CGPointZero;
- CFIndex lastCharacterIndex = m_run.ltr() ? numeric_limits<CFIndex>::min() : numeric_limits<CFIndex>::max();
- bool isMonotonic = true;
-
- for (unsigned i = 0; i < glyphCount; i++) {
- CFIndex characterIndex = complexTextRun.indexAt(i);
- if (m_run.ltr()) {
- if (characterIndex < lastCharacterIndex)
- isMonotonic = false;
- } else {
- if (characterIndex > lastCharacterIndex)
- isMonotonic = false;
- }
- UChar ch = *(cp + characterIndex);
- bool lastGlyph = lastRun && i + 1 == glyphCount;
- UChar nextCh;
- if (lastGlyph)
- nextCh = ' ';
- else if (i + 1 < glyphCount)
- nextCh = *(cp + complexTextRun.indexAt(i + 1));
- else
- nextCh = *(m_complexTextRuns[r + 1]->characters() + m_complexTextRuns[r + 1]->indexAt(0));
-
- bool treatAsSpace = Font::treatAsSpace(ch);
- CGGlyph glyph = treatAsSpace ? fontData->spaceGlyph() : glyphs[i];
- CGSize advance = treatAsSpace ? CGSizeMake(spaceWidth, advances[i].height) : advances[i];
-
- if (ch == '\t' && m_run.allowTabs())
- advance.width = m_font.tabWidth(*fontData, m_run.tabSize(), m_run.xPos() + m_totalWidth + widthSinceLastCommit);
- else if (Font::treatAsZeroWidthSpace(ch) && !treatAsSpace) {
- advance.width = 0;
- glyph = fontData->spaceGlyph();
- }
-
- float roundedAdvanceWidth = roundf(advance.width);
- if (roundsAdvances)
- advance.width = roundedAdvanceWidth;
-
- advance.width += fontData->syntheticBoldOffset();
-
-
- // We special case spaces in two ways when applying word rounding.
- // First, we round spaces to an adjusted width in all fonts.
- // Second, in fixed-pitch fonts we ensure that all glyphs that
- // match the width of the space glyph have the same width as the space glyph.
- if (m_run.applyWordRounding() && roundedAdvanceWidth == roundedSpaceWidth && (fontData->pitch() == FixedPitch || glyph == fontData->spaceGlyph()))
- advance.width = fontData->adjustedSpaceWidth();
-
- if (hasExtraSpacing) {
- // If we're a glyph with an advance, go ahead and add in letter-spacing.
- // That way we weed out zero width lurkers. This behavior matches the fast text code path.
- if (advance.width && m_font.letterSpacing())
- advance.width += m_font.letterSpacing();
-
- // Handle justification and word-spacing.
- if (treatAsSpace || Font::isCJKIdeographOrSymbol(ch)) {
- // Distribute the run's total expansion evenly over all expansion opportunities in the run.
- if (m_expansion) {
- float previousExpansion = m_expansion;
- if (!treatAsSpace && !m_afterExpansion) {
- // Take the expansion opportunity before this ideograph.
- m_expansion -= m_expansionPerOpportunity;
- float expansionAtThisOpportunity = !m_run.applyWordRounding() ? m_expansionPerOpportunity : roundf(previousExpansion) - roundf(m_expansion);
- m_totalWidth += expansionAtThisOpportunity;
- if (m_adjustedAdvances.isEmpty())
- m_leadingExpansion = expansionAtThisOpportunity;
- else
- m_adjustedAdvances.last().width += expansionAtThisOpportunity;
- previousExpansion = m_expansion;
- }
- if (!lastGlyph || m_run.allowsTrailingExpansion()) {
- m_expansion -= m_expansionPerOpportunity;
- advance.width += !m_run.applyWordRounding() ? m_expansionPerOpportunity : roundf(previousExpansion) - roundf(m_expansion);
- m_afterExpansion = true;
- }
- } else
- m_afterExpansion = false;
-
- // Account for word-spacing.
- if (treatAsSpace && (ch != '\t' || !m_run.allowTabs()) && (characterIndex > 0 || r > 0) && m_font.wordSpacing())
- advance.width += m_font.wordSpacing();
- } else
- m_afterExpansion = false;
- }
-
- // Apply rounding hacks if needed.
- // We adjust the width of the last character of a "word" to ensure an integer width.
- // Force characters that are used to determine word boundaries for the rounding hack
- // to be integer width, so the following words will start on an integer boundary.
- if (m_run.applyWordRounding() && Font::isRoundingHackCharacter(ch))
- advance.width = ceilCGFloat(advance.width);
-
- // Check to see if the next character is a "rounding hack character", if so, adjust the
- // width so that the total run width will be on an integer boundary.
- if ((m_run.applyWordRounding() && !lastGlyph && Font::isRoundingHackCharacter(nextCh)) || (m_run.applyRunRounding() && lastGlyph)) {
- CGFloat totalWidth = widthSinceLastCommit + advance.width;
- widthSinceLastCommit = ceilCGFloat(totalWidth);
- CGFloat extraWidth = widthSinceLastCommit - totalWidth;
- if (m_run.ltr())
- advance.width += extraWidth;
- else {
- if (m_lastRoundingGlyph)
- m_adjustedAdvances[m_lastRoundingGlyph - 1].width += extraWidth;
- else
- m_finalRoundingWidth = extraWidth;
- m_lastRoundingGlyph = m_adjustedAdvances.size() + 1;
- }
- m_totalWidth += widthSinceLastCommit;
- widthSinceLastCommit = 0;
- } else
- widthSinceLastCommit += advance.width;
-
- // FIXME: Combining marks should receive a text emphasis mark if they are combine with a space.
- if (m_forTextEmphasis && (!Font::canReceiveTextEmphasis(ch) || (U_GET_GC_MASK(ch) & U_GC_M_MASK)))
- glyph = 0;
-
- advance.height *= -1;
- m_adjustedAdvances.append(advance);
- m_adjustedGlyphs.append(glyph);
-
- FloatRect glyphBounds = fontData->boundsForGlyph(glyph);
- glyphBounds.move(glyphOrigin.x, glyphOrigin.y);
- m_minGlyphBoundingBoxX = min(m_minGlyphBoundingBoxX, glyphBounds.x());
- m_maxGlyphBoundingBoxX = max(m_maxGlyphBoundingBoxX, glyphBounds.maxX());
- m_minGlyphBoundingBoxY = min(m_minGlyphBoundingBoxY, glyphBounds.y());
- m_maxGlyphBoundingBoxY = max(m_maxGlyphBoundingBoxY, glyphBounds.maxY());
- glyphOrigin.x += advance.width;
- glyphOrigin.y += advance.height;
-
- lastCharacterIndex = characterIndex;
- }
- if (!isMonotonic)
- complexTextRun.setIsNonMonotonic();
- }
- m_totalWidth += widthSinceLastCommit;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/mac/ComplexTextController.h b/chromium/third_party/WebKit/Source/core/platform/graphics/mac/ComplexTextController.h
deleted file mode 100644
index fdc100d5052..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/mac/ComplexTextController.h
+++ /dev/null
@@ -1,184 +0,0 @@
-/*
- * Copyright (C) 2007, 2008, 2009, 2011 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ComplexTextController_h
-#define ComplexTextController_h
-
-#include "core/platform/graphics/GlyphBuffer.h"
-#include "wtf/HashSet.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/RetainPtr.h"
-#include "wtf/text/WTFString.h"
-#include "wtf/unicode/Unicode.h"
-#include "wtf/Vector.h"
-
-typedef unsigned short CGGlyph;
-
-typedef const struct __CTRun * CTRunRef;
-typedef const struct __CTLine * CTLineRef;
-
-namespace WebCore {
-
-class Font;
-class SimpleFontData;
-class TextRun;
-
-enum GlyphIterationStyle { IncludePartialGlyphs, ByWholeGlyphs };
-
-// ComplexTextController is responsible for rendering and measuring glyphs for
-// complex scripts on OS X.
-class ComplexTextController {
-public:
- ComplexTextController(const Font*, const TextRun&, bool mayUseNaturalWritingDirection = false, HashSet<const SimpleFontData*>* fallbackFonts = 0, bool forTextEmphasis = false);
-
- // Advance and emit glyphs up to the specified character.
- void advance(unsigned to, GlyphBuffer* = 0, GlyphIterationStyle = IncludePartialGlyphs, HashSet<const SimpleFontData*>* fallbackFonts = 0);
-
- // Compute the character offset for a given x coordinate.
- int offsetForPosition(float x, bool includePartialGlyphs);
-
- // Returns the width of everything we've consumed so far.
- float runWidthSoFar() const { return m_runWidthSoFar; }
-
- float totalWidth() const { return m_totalWidth; }
-
- float finalRoundingWidth() const { return m_finalRoundingWidth; }
-
- float minGlyphBoundingBoxX() const { return m_minGlyphBoundingBoxX; }
- float maxGlyphBoundingBoxX() const { return m_maxGlyphBoundingBoxX; }
- float minGlyphBoundingBoxY() const { return m_minGlyphBoundingBoxY; }
- float maxGlyphBoundingBoxY() const { return m_maxGlyphBoundingBoxY; }
-
-private:
- class ComplexTextRun : public RefCounted<ComplexTextRun> {
- public:
- static PassRefPtr<ComplexTextRun> create(CTRunRef ctRun, const SimpleFontData* fontData, const UChar* characters, unsigned stringLocation, size_t stringLength, CFRange runRange)
- {
- return adoptRef(new ComplexTextRun(ctRun, fontData, characters, stringLocation, stringLength, runRange));
- }
-
- static PassRefPtr<ComplexTextRun> create(const SimpleFontData* fontData, const UChar* characters, unsigned stringLocation, size_t stringLength, bool ltr)
- {
- return adoptRef(new ComplexTextRun(fontData, characters, stringLocation, stringLength, ltr));
- }
-
- unsigned glyphCount() const { return m_glyphCount; }
- const SimpleFontData* fontData() const { return m_fontData; }
- const UChar* characters() const { return m_characters; }
- unsigned stringLocation() const { return m_stringLocation; }
- size_t stringLength() const { return m_stringLength; }
- ALWAYS_INLINE CFIndex indexAt(size_t i) const;
- CFIndex indexBegin() const { return m_indexBegin; }
- CFIndex indexEnd() const { return m_indexEnd; }
- CFIndex endOffsetAt(size_t i) const { ASSERT(!m_isMonotonic); return m_glyphEndOffsets[i]; }
- const CGGlyph* glyphs() const { return m_glyphs; }
- const CGSize* advances() const { return m_advances; }
- bool isLTR() const { return m_isLTR; }
- bool isMonotonic() const { return m_isMonotonic; }
- void setIsNonMonotonic();
-
- private:
- ComplexTextRun(CTRunRef, const SimpleFontData*, const UChar* characters, unsigned stringLocation, size_t stringLength, CFRange runRange);
- ComplexTextRun(const SimpleFontData*, const UChar* characters, unsigned stringLocation, size_t stringLength, bool ltr);
-
- unsigned m_glyphCount;
- const SimpleFontData* m_fontData;
- const UChar* m_characters;
- unsigned m_stringLocation;
- size_t m_stringLength;
- Vector<CFIndex, 64> m_coreTextIndicesVector;
- const CFIndex* m_coreTextIndices;
- CFIndex m_indexBegin;
- CFIndex m_indexEnd;
- Vector<CFIndex, 64> m_glyphEndOffsets;
- Vector<CGGlyph, 64> m_glyphsVector;
- const CGGlyph* m_glyphs;
- Vector<CGSize, 64> m_advancesVector;
- const CGSize* m_advances;
- bool m_isLTR;
- bool m_isMonotonic;
- };
-
- static unsigned stringBegin(const ComplexTextRun& run) { return run.stringLocation() + run.indexBegin(); }
- static unsigned stringEnd(const ComplexTextRun& run) { return run.stringLocation() + run.indexEnd(); }
-
- void collectComplexTextRuns();
-
- void collectComplexTextRunsForCharacters(const UChar*, unsigned length, unsigned stringLocation, const SimpleFontData*);
- void adjustGlyphsAndAdvances();
-
- unsigned findNextRunIndex(unsigned runIndex) const;
- unsigned indexOfCurrentRun(unsigned& leftmostGlyph);
- unsigned incrementCurrentRun(unsigned& leftmostGlyph);
-
- // The initial capacity of these vectors was selected as being the smallest power of two greater than
- // the average (3.5) plus one standard deviation (7.5) of nonzero sizes used on Arabic Wikipedia.
- Vector<unsigned, 16> m_runIndices;
- Vector<unsigned, 16> m_glyphCountFromStartToIndex;
-
- const Font& m_font;
- const TextRun& m_run;
- bool m_isLTROnly;
- bool m_mayUseNaturalWritingDirection;
- bool m_forTextEmphasis;
-
- Vector<String> m_stringsFor8BitRuns;
- Vector<UChar, 256> m_smallCapsBuffer;
-
- // Retain lines rather than their runs for better performance.
- Vector<RetainPtr<CTLineRef> > m_coreTextLines;
- Vector<RefPtr<ComplexTextRun>, 16> m_complexTextRuns;
- Vector<CGSize, 256> m_adjustedAdvances;
- Vector<CGGlyph, 256> m_adjustedGlyphs;
-
- unsigned m_currentCharacter;
- int m_end;
-
- CGFloat m_totalWidth;
-
- float m_runWidthSoFar;
- unsigned m_numGlyphsSoFar;
- size_t m_currentRun;
- unsigned m_glyphInCurrentRun;
- unsigned m_characterInCurrentGlyph;
- float m_finalRoundingWidth;
- float m_expansion;
- float m_expansionPerOpportunity;
- float m_leadingExpansion;
- bool m_afterExpansion;
-
- HashSet<const SimpleFontData*>* m_fallbackFonts;
-
- float m_minGlyphBoundingBoxX;
- float m_maxGlyphBoundingBoxX;
- float m_minGlyphBoundingBoxY;
- float m_maxGlyphBoundingBoxY;
-
- unsigned m_lastRoundingGlyph;
-};
-
-} // namespace WebCore
-
-#endif // ComplexTextController_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/mac/ComplexTextControllerCoreText.mm b/chromium/third_party/WebKit/Source/core/platform/graphics/mac/ComplexTextControllerCoreText.mm
deleted file mode 100644
index 5882bcdaf9f..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/mac/ComplexTextControllerCoreText.mm
+++ /dev/null
@@ -1,292 +0,0 @@
-/*
- * Copyright (C) 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/platform/graphics/mac/ComplexTextController.h"
-
-#include "core/platform/graphics/Font.h"
-#include "core/platform/graphics/FontCache.h"
-#include "core/platform/graphics/TextRun.h"
-
-#include <ApplicationServices/ApplicationServices.h>
-#import <AvailabilityMacros.h>
-
-// Forward declare Mac SPIs.
-extern "C" {
-// Request for public API: rdar://13803619
-CTLineRef CTLineCreateWithUniCharProvider(const UniChar* (*provide)(CFIndex stringIndex, CFIndex* charCount, CFDictionaryRef* attributes, void* context), void (*dispose)(const UniChar* chars, void* context), void* context);
-}
-
-@interface WebCascadeList : NSArray {
- @private
- const WebCore::Font* _font;
- UChar32 _character;
- NSUInteger _count;
- Vector<RetainPtr<CTFontDescriptorRef>, 16> _fontDescriptors;
-}
-
-- (id)initWithFont:(const WebCore::Font*)font character:(UChar32)character;
-
-@end
-
-@implementation WebCascadeList
-
-- (id)initWithFont:(const WebCore::Font*)font character:(UChar32)character
-{
- if (!(self = [super init]))
- return nil;
-
- _font = font;
- _character = character;
-
- // By the time a WebCascadeList is used, the Font has already been asked to realize all of its
- // FontData, so this loop does not hit the FontCache.
- while (_font->fontDataAt(_count))
- _count++;
-
- return self;
-}
-
-- (NSUInteger)count
-{
- return _count;
-}
-
-- (id)objectAtIndex:(NSUInteger)index
-{
- CTFontDescriptorRef fontDescriptor;
- if (index < _fontDescriptors.size()) {
- if ((fontDescriptor = _fontDescriptors[index].get()))
- return (id)fontDescriptor;
- } else
- _fontDescriptors.grow(index + 1);
-
- const WebCore::SimpleFontData* fontData = _font->fontDataAt(index)->fontDataForCharacter(_character);
- fontDescriptor = CTFontCopyFontDescriptor(fontData->platformData().ctFont());
- _fontDescriptors[index] = RetainPtr<CTFontDescriptorRef>(AdoptCF, fontDescriptor);
- return (id)fontDescriptor;
-}
-
-@end
-
-namespace WebCore {
-
-ComplexTextController::ComplexTextRun::ComplexTextRun(CTRunRef ctRun, const SimpleFontData* fontData, const UChar* characters, unsigned stringLocation, size_t stringLength, CFRange runRange)
- : m_fontData(fontData)
- , m_characters(characters)
- , m_stringLocation(stringLocation)
- , m_stringLength(stringLength)
- , m_indexBegin(runRange.location)
- , m_indexEnd(runRange.location + runRange.length)
- , m_isLTR(!(CTRunGetStatus(ctRun) & kCTRunStatusRightToLeft))
- , m_isMonotonic(true)
-{
- m_glyphCount = CTRunGetGlyphCount(ctRun);
- m_coreTextIndices = CTRunGetStringIndicesPtr(ctRun);
- if (!m_coreTextIndices) {
- m_coreTextIndicesVector.grow(m_glyphCount);
- CTRunGetStringIndices(ctRun, CFRangeMake(0, 0), m_coreTextIndicesVector.data());
- m_coreTextIndices = m_coreTextIndicesVector.data();
- }
-
- m_glyphs = CTRunGetGlyphsPtr(ctRun);
- if (!m_glyphs) {
- m_glyphsVector.grow(m_glyphCount);
- CTRunGetGlyphs(ctRun, CFRangeMake(0, 0), m_glyphsVector.data());
- m_glyphs = m_glyphsVector.data();
- }
-
- m_advances = CTRunGetAdvancesPtr(ctRun);
- if (!m_advances) {
- m_advancesVector.grow(m_glyphCount);
- CTRunGetAdvances(ctRun, CFRangeMake(0, 0), m_advancesVector.data());
- m_advances = m_advancesVector.data();
- }
-}
-
-// Missing glyphs run constructor. Core Text will not generate a run of missing glyphs, instead falling back on
-// glyphs from LastResort. We want to use the primary font's missing glyph in order to match the fast text code path.
-ComplexTextController::ComplexTextRun::ComplexTextRun(const SimpleFontData* fontData, const UChar* characters, unsigned stringLocation, size_t stringLength, bool ltr)
- : m_fontData(fontData)
- , m_characters(characters)
- , m_stringLocation(stringLocation)
- , m_stringLength(stringLength)
- , m_indexBegin(0)
- , m_indexEnd(stringLength)
- , m_isLTR(ltr)
- , m_isMonotonic(true)
-{
- m_coreTextIndicesVector.reserveInitialCapacity(m_stringLength);
- unsigned r = 0;
- while (r < m_stringLength) {
- m_coreTextIndicesVector.uncheckedAppend(r);
- if (U_IS_SURROGATE(m_characters[r])) {
- ASSERT(r + 1 < m_stringLength);
- ASSERT(U_IS_SURROGATE_LEAD(m_characters[r]));
- ASSERT(U_IS_TRAIL(m_characters[r + 1]));
- r += 2;
- } else
- r++;
- }
- m_glyphCount = m_coreTextIndicesVector.size();
- if (!ltr) {
- for (unsigned r = 0, end = m_glyphCount - 1; r < m_glyphCount / 2; ++r, --end)
- std::swap(m_coreTextIndicesVector[r], m_coreTextIndicesVector[end]);
- }
- m_coreTextIndices = m_coreTextIndicesVector.data();
-
- // Synthesize a run of missing glyphs.
- m_glyphsVector.fill(0, m_glyphCount);
- m_glyphs = m_glyphsVector.data();
- m_advancesVector.fill(CGSizeMake(m_fontData->widthForGlyph(0), 0), m_glyphCount);
- m_advances = m_advancesVector.data();
-}
-
-struct ProviderInfo {
- const UChar* cp;
- unsigned length;
- CFDictionaryRef attributes;
-};
-
-static const UniChar* provideStringAndAttributes(CFIndex stringIndex, CFIndex* charCount, CFDictionaryRef* attributes, void* refCon)
-{
- ProviderInfo* info = static_cast<struct ProviderInfo*>(refCon);
- if (stringIndex < 0 || static_cast<unsigned>(stringIndex) >= info->length)
- return 0;
-
- *charCount = info->length - stringIndex;
- *attributes = info->attributes;
- return info->cp + stringIndex;
-}
-
-void ComplexTextController::collectComplexTextRunsForCharacters(const UChar* cp, unsigned length, unsigned stringLocation, const SimpleFontData* fontData)
-{
- if (!fontData) {
- // Create a run of missing glyphs from the primary font.
- m_complexTextRuns.append(ComplexTextRun::create(m_font.primaryFont(), cp, stringLocation, length, m_run.ltr()));
- return;
- }
-
- bool isSystemFallback = false;
-
- UChar32 baseCharacter = 0;
- RetainPtr<CFDictionaryRef> stringAttributes;
- if (fontData == SimpleFontData::systemFallback()) {
- // FIXME: This code path does not support small caps.
- isSystemFallback = true;
-
- U16_GET(cp, 0, 0, length, baseCharacter);
- fontData = m_font.fontDataAt(0)->fontDataForCharacter(baseCharacter);
-
- RetainPtr<WebCascadeList> cascadeList(AdoptNS, [[WebCascadeList alloc] initWithFont:&m_font character:baseCharacter]);
-
- stringAttributes.adoptCF(CFDictionaryCreateMutableCopy(kCFAllocatorDefault, 0, fontData->getCFStringAttributes(m_font.typesettingFeatures(), fontData->platformData().orientation())));
- static const void* attributeKeys[] = { kCTFontCascadeListAttribute };
- const void* values[] = { cascadeList.get() };
- RetainPtr<CFDictionaryRef> attributes(AdoptCF, CFDictionaryCreate(kCFAllocatorDefault, attributeKeys, values, sizeof(attributeKeys) / sizeof(*attributeKeys), &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
- RetainPtr<CTFontDescriptorRef> fontDescriptor(AdoptCF, CTFontDescriptorCreateWithAttributes(attributes.get()));
- RetainPtr<CTFontRef> fontWithCascadeList(AdoptCF, CTFontCreateCopyWithAttributes(fontData->platformData().ctFont(), m_font.pixelSize(), 0, fontDescriptor.get()));
- CFDictionarySetValue(const_cast<CFMutableDictionaryRef>(stringAttributes.get()), kCTFontAttributeName, fontWithCascadeList.get());
- } else
- stringAttributes = fontData->getCFStringAttributes(m_font.typesettingFeatures(), fontData->platformData().orientation());
-
- RetainPtr<CTLineRef> line;
-
- if (!m_mayUseNaturalWritingDirection || m_run.directionalOverride()) {
- static const void* optionKeys[] = { kCTTypesetterOptionForcedEmbeddingLevel };
- const short ltrForcedEmbeddingLevelValue = 0;
- const short rtlForcedEmbeddingLevelValue = 1;
- static const void* ltrOptionValues[] = { CFNumberCreate(kCFAllocatorDefault, kCFNumberShortType, &ltrForcedEmbeddingLevelValue) };
- static const void* rtlOptionValues[] = { CFNumberCreate(kCFAllocatorDefault, kCFNumberShortType, &rtlForcedEmbeddingLevelValue) };
- static CFDictionaryRef ltrTypesetterOptions = CFDictionaryCreate(kCFAllocatorDefault, optionKeys, ltrOptionValues, WTF_ARRAY_LENGTH(optionKeys), &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
- static CFDictionaryRef rtlTypesetterOptions = CFDictionaryCreate(kCFAllocatorDefault, optionKeys, rtlOptionValues, WTF_ARRAY_LENGTH(optionKeys), &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
-
- RetainPtr<CFStringRef> string(AdoptCF, CFStringCreateWithCharactersNoCopy(kCFAllocatorDefault, cp, length, kCFAllocatorNull));
- RetainPtr<CFAttributedStringRef> attributedString(AdoptCF, CFAttributedStringCreate(kCFAllocatorDefault, string.get(), stringAttributes.get()));
- RetainPtr<CTTypesetterRef> typesetter(AdoptCF, CTTypesetterCreateWithAttributedStringAndOptions(attributedString.get(), m_run.ltr() ? ltrTypesetterOptions : rtlTypesetterOptions));
-
- line.adoptCF(CTTypesetterCreateLine(typesetter.get(), CFRangeMake(0, 0)));
- } else {
- ProviderInfo info = { cp, length, stringAttributes.get() };
-
- line.adoptCF(CTLineCreateWithUniCharProvider(&provideStringAndAttributes, 0, &info));
- }
-
- m_coreTextLines.append(line.get());
-
- CFArrayRef runArray = CTLineGetGlyphRuns(line.get());
-
- CFIndex runCount = CFArrayGetCount(runArray);
-
- for (CFIndex r = 0; r < runCount; r++) {
- CTRunRef ctRun = static_cast<CTRunRef>(CFArrayGetValueAtIndex(runArray, m_run.ltr() ? r : runCount - 1 - r));
- ASSERT(CFGetTypeID(ctRun) == CTRunGetTypeID());
- CFRange runRange = CTRunGetStringRange(ctRun);
- const SimpleFontData* runFontData = fontData;
- if (isSystemFallback) {
- CFDictionaryRef runAttributes = CTRunGetAttributes(ctRun);
- CTFontRef runFont = static_cast<CTFontRef>(CFDictionaryGetValue(runAttributes, kCTFontAttributeName));
- ASSERT(CFGetTypeID(runFont) == CTFontGetTypeID());
- if (!CFEqual(runFont, fontData->platformData().ctFont())) {
- // Begin trying to see if runFont matches any of the fonts in the fallback list.
- RetainPtr<CGFontRef> runCGFont(AdoptCF, CTFontCopyGraphicsFont(runFont, 0));
- unsigned i = 0;
- for (const FontData* candidateFontData = m_font.fontDataAt(i); candidateFontData; candidateFontData = m_font.fontDataAt(++i)) {
- runFontData = candidateFontData->fontDataForCharacter(baseCharacter);
- RetainPtr<CGFontRef> cgFont(AdoptCF, CTFontCopyGraphicsFont(runFontData->platformData().ctFont(), 0));
- if (CFEqual(cgFont.get(), runCGFont.get()))
- break;
- runFontData = 0;
- }
- // If there is no matching font, look up by name in the font cache.
- if (!runFontData) {
- // Rather than using runFont as an NSFont and wrapping it in a FontPlatformData, go through
- // the font cache and ultimately through NSFontManager in order to get an NSFont with the right
- // NSFontRenderingMode.
- RetainPtr<CFStringRef> fontName(AdoptCF, CTFontCopyPostScriptName(runFont));
- if (CFEqual(fontName.get(), CFSTR("LastResort"))) {
- m_complexTextRuns.append(ComplexTextRun::create(m_font.primaryFont(), cp, stringLocation + runRange.location, runRange.length, m_run.ltr()));
- continue;
- }
- runFontData = fontCache()->getFontResourceData(m_font.fontDescription(), fontName.get(), false, FontCache::DoNotRetain).get();
- // Core Text may have used a font that is not known to NSFontManager. In that case, fall back on
- // using the font as returned, even though it may not have the best NSFontRenderingMode.
- if (!runFontData) {
- FontPlatformData runFontPlatformData((NSFont *)runFont, CTFontGetSize(runFont), m_font.fontDescription().usePrinterFont());
- runFontData = fontCache()->getFontResourceData(&runFontPlatformData, FontCache::DoNotRetain).get();
- }
- }
- if (m_fallbackFonts && runFontData != m_font.primaryFont())
- m_fallbackFonts->add(runFontData);
- }
- }
- if (m_fallbackFonts && runFontData != m_font.primaryFont())
- m_fallbackFonts->add(fontData);
-
- m_complexTextRuns.append(ComplexTextRun::create(ctRun, runFontData, cp, stringLocation, length, runRange));
- }
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/mac/FloatPointMac.mm b/chromium/third_party/WebKit/Source/core/platform/graphics/mac/FloatPointMac.mm
deleted file mode 100644
index 35ae7b01d3c..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/mac/FloatPointMac.mm
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright (C) 2004, 2006 Apple Computer, Inc. All rights reserved.
- * Copyright (C) 2005 Nokia. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/FloatPoint.h"
-
-namespace WebCore {
-
-#ifndef NSGEOMETRY_TYPES_SAME_AS_CGGEOMETRY_TYPES
-
-FloatPoint::FloatPoint(const NSPoint& p) : m_x(p.x), m_y(p.y)
-{
-}
-
-FloatPoint::operator NSPoint() const
-{
- return NSMakePoint(m_x, m_y);
-}
-
-#endif
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/mac/FloatRectMac.mm b/chromium/third_party/WebKit/Source/core/platform/graphics/mac/FloatRectMac.mm
deleted file mode 100644
index 869f107a960..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/mac/FloatRectMac.mm
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright (C) 2003, 2006 Apple Computer, Inc. All rights reserved.
- * Copyright (C) 2005 Nokia. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/FloatRect.h"
-
-namespace WebCore {
-
-#ifndef NSGEOMETRY_TYPES_SAME_AS_CGGEOMETRY_TYPES
-
-FloatRect::FloatRect(const NSRect& r) : m_location(r.origin), m_size(r.size)
-{
-}
-
-FloatRect::operator NSRect() const
-{
- return NSMakeRect(x(), y(), width(), height());
-}
-
-#endif
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/mac/FloatSizeMac.mm b/chromium/third_party/WebKit/Source/core/platform/graphics/mac/FloatSizeMac.mm
deleted file mode 100644
index fe638136129..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/mac/FloatSizeMac.mm
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright (C) 2003, 2006 Apple Computer, Inc. All rights reserved.
- * Copyright (C) 2005 Nokia. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/FloatSize.h"
-
-namespace WebCore {
-
-#ifndef NSGEOMETRY_TYPES_SAME_AS_CGGEOMETRY_TYPES
-
-FloatSize::FloatSize(const NSSize& s) : m_width(s.width), m_height(s.height)
-{
-}
-
-FloatSize::operator NSSize() const
-{
- return NSMakeSize(m_width, m_height);
-}
-
-#endif
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/mac/FontCacheMac.mm b/chromium/third_party/WebKit/Source/core/platform/graphics/mac/FontCacheMac.mm
deleted file mode 100644
index 78c410ebff5..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/mac/FontCacheMac.mm
+++ /dev/null
@@ -1,248 +0,0 @@
-/*
- * Copyright (C) 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
- * Copyright (C) 2007 Nicholas Shanks <webkit@nickshanks.com>
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#import "config.h"
-#import "core/platform/graphics/FontCache.h"
-
-#import <AppKit/AppKit.h>
-#import "core/platform/graphics/Font.h"
-#import "core/platform/graphics/FontPlatformData.h"
-#import "core/platform/graphics/SimpleFontData.h"
-#import "core/platform/mac/WebFontCache.h"
-#import <wtf/MainThread.h>
-#import <wtf/StdLibExtras.h>
-
-// Forward declare Mac SPIs.
-// Request for public API: rdar://13803570
-@interface NSFont (WebKitSPI)
-+ (NSFont*)findFontLike:(NSFont*)font forString:(NSString*)string withRange:(NSRange)range inLanguage:(id)useNil;
-+ (NSFont*)findFontLike:(NSFont*)font forCharacter:(UniChar)uc inLanguage:(id)useNil;
-@end
-
-namespace WebCore {
-
-// The "void*" parameter makes the function match the prototype for callbacks from callOnMainThread.
-static void invalidateFontCache(void*)
-{
- if (!isMainThread()) {
- callOnMainThread(&invalidateFontCache, 0);
- return;
- }
- fontCache()->invalidate();
-}
-
-static void fontCacheRegisteredFontsChangedNotificationCallback(CFNotificationCenterRef, void* observer, CFStringRef name, const void *, CFDictionaryRef)
-{
- ASSERT_UNUSED(observer, observer == fontCache());
- ASSERT_UNUSED(name, CFEqual(name, kCTFontManagerRegisteredFontsChangedNotification));
- invalidateFontCache(0);
-}
-
-void FontCache::platformInit()
-{
- CFNotificationCenterAddObserver(CFNotificationCenterGetLocalCenter(), this, fontCacheRegisteredFontsChangedNotificationCallback, kCTFontManagerRegisteredFontsChangedNotification, 0, CFNotificationSuspensionBehaviorDeliverImmediately);
-}
-
-static int toAppKitFontWeight(FontWeight fontWeight)
-{
- static int appKitFontWeights[] = {
- 2, // FontWeight100
- 3, // FontWeight200
- 4, // FontWeight300
- 5, // FontWeight400
- 6, // FontWeight500
- 8, // FontWeight600
- 9, // FontWeight700
- 10, // FontWeight800
- 12, // FontWeight900
- };
- return appKitFontWeights[fontWeight];
-}
-
-static inline bool isAppKitFontWeightBold(NSInteger appKitFontWeight)
-{
- return appKitFontWeight >= 7;
-}
-
-PassRefPtr<SimpleFontData> FontCache::getFontDataForCharacter(const Font& font, UChar32 character)
-{
- // FIXME: We should fix getFallbackFamily to take a UChar32
- // and remove this split-to-UChar16 code.
- UChar codeUnits[2];
- int codeUnitsLength;
- if (character <= 0xFFFF) {
- codeUnits[0] = character;
- codeUnitsLength = 1;
- } else {
- codeUnits[0] = U16_LEAD(character);
- codeUnits[1] = U16_TRAIL(character);
- codeUnitsLength = 2;
- }
-
- const FontPlatformData& platformData = font.fontDataAt(0)->fontDataForCharacter(character)->platformData();
- NSFont *nsFont = platformData.font();
-
- NSString *string = [[NSString alloc] initWithCharactersNoCopy:codeUnits length:codeUnitsLength freeWhenDone:NO];
- NSFont *substituteFont = [NSFont findFontLike:nsFont forString:string withRange:NSMakeRange(0, codeUnitsLength) inLanguage:nil];
- [string release];
-
- // FIXME: Remove this SPI usage: http://crbug.com/255122
- if (!substituteFont && codeUnitsLength == 1)
- substituteFont = [NSFont findFontLike:nsFont forCharacter:codeUnits[0] inLanguage:nil];
- if (!substituteFont)
- return 0;
-
- // Chromium can't render AppleColorEmoji.
- if ([[substituteFont familyName] isEqual:@"Apple Color Emoji"])
- return 0;
-
- // Use the family name from the AppKit-supplied substitute font, requesting the
- // traits, weight, and size we want. One way this does better than the original
- // AppKit request is that it takes synthetic bold and oblique into account.
- // But it does create the possibility that we could end up with a font that
- // doesn't actually cover the characters we need.
-
- NSFontManager *fontManager = [NSFontManager sharedFontManager];
-
- NSFontTraitMask traits;
- NSInteger weight;
- CGFloat size;
-
- if (nsFont) {
- traits = [fontManager traitsOfFont:nsFont];
- if (platformData.m_syntheticBold)
- traits |= NSBoldFontMask;
- if (platformData.m_syntheticOblique)
- traits |= NSFontItalicTrait;
- weight = [fontManager weightOfFont:nsFont];
- size = [nsFont pointSize];
- } else {
- // For custom fonts nsFont is nil.
- traits = font.italic() ? NSFontItalicTrait : 0;
- weight = toAppKitFontWeight(font.weight());
- size = font.pixelSize();
- }
-
- NSFontTraitMask substituteFontTraits = [fontManager traitsOfFont:substituteFont];
- NSInteger substituteFontWeight = [fontManager weightOfFont:substituteFont];
-
- if (traits != substituteFontTraits || weight != substituteFontWeight || !nsFont) {
- if (NSFont *bestVariation = [fontManager fontWithFamily:[substituteFont familyName] traits:traits weight:weight size:size]) {
- if (!nsFont || (([fontManager traitsOfFont:bestVariation] != substituteFontTraits || [fontManager weightOfFont:bestVariation] != substituteFontWeight)
- && [[bestVariation coveredCharacterSet] longCharacterIsMember:character]))
- substituteFont = bestVariation;
- }
- }
-
- substituteFont = font.fontDescription().usePrinterFont() ? [substituteFont printerFont] : [substituteFont screenFont];
-
- substituteFontTraits = [fontManager traitsOfFont:substituteFont];
- substituteFontWeight = [fontManager weightOfFont:substituteFont];
-
- FontPlatformData alternateFont(substituteFont, platformData.size(), platformData.isPrinterFont(),
- !font.isPlatformFont() && isAppKitFontWeightBold(weight) && !isAppKitFontWeightBold(substituteFontWeight),
- !font.isPlatformFont() && (traits & NSFontItalicTrait) && !(substituteFontTraits & NSFontItalicTrait),
- platformData.m_orientation);
-
- return getFontResourceData(&alternateFont, DoNotRetain);
-}
-
-PassRefPtr<SimpleFontData> FontCache::getSimilarFontPlatformData(const Font& font)
-{
- // Attempt to find an appropriate font using a match based on
- // the presence of keywords in the the requested names. For example, we'll
- // match any name that contains "Arabic" to Geeza Pro.
- RefPtr<SimpleFontData> simpleFontData;
- const FontFamily* currFamily = &font.fontDescription().family();
- while (currFamily && !simpleFontData) {
- if (currFamily->family().length()) {
- static String* matchWords[3] = { new String("Arabic"), new String("Pashto"), new String("Urdu") };
- DEFINE_STATIC_LOCAL(AtomicString, geezaStr, ("Geeza Pro", AtomicString::ConstructFromLiteral));
- for (int j = 0; j < 3 && !simpleFontData; ++j)
- if (currFamily->family().contains(*matchWords[j], false))
- simpleFontData = getFontResourceData(font.fontDescription(), geezaStr);
- }
- currFamily = currFamily->next();
- }
-
- return simpleFontData.release();
-}
-
-PassRefPtr<SimpleFontData> FontCache::getLastResortFallbackFont(const FontDescription& fontDescription, ShouldRetain shouldRetain)
-{
- DEFINE_STATIC_LOCAL(AtomicString, timesStr, ("Times", AtomicString::ConstructFromLiteral));
-
- // FIXME: Would be even better to somehow get the user's default font here. For now we'll pick
- // the default that the user would get without changing any prefs.
- RefPtr<SimpleFontData> simpleFontData = getFontResourceData(fontDescription, timesStr, false, shouldRetain);
- if (simpleFontData)
- return simpleFontData.release();
-
- // The Times fallback will almost always work, but in the highly unusual case where
- // the user doesn't have it, we fall back on Lucida Grande because that's
- // guaranteed to be there, according to Nathan Taylor. This is good enough
- // to avoid a crash at least.
- DEFINE_STATIC_LOCAL(AtomicString, lucidaGrandeStr, ("Lucida Grande", AtomicString::ConstructFromLiteral));
- return getFontResourceData(fontDescription, lucidaGrandeStr, false, shouldRetain);
-}
-
-void FontCache::getTraitsInFamily(const AtomicString& familyName, Vector<unsigned>& traitsMasks)
-{
- [WebFontCache getTraits:traitsMasks inFamily:familyName];
-}
-
-FontPlatformData* FontCache::createFontPlatformData(const FontDescription& fontDescription, const AtomicString& family)
-{
- NSFontTraitMask traits = fontDescription.italic() ? NSFontItalicTrait : 0;
- NSInteger weight = toAppKitFontWeight(fontDescription.weight());
- float size = fontDescription.computedPixelSize();
-
- NSFont *nsFont = [WebFontCache fontWithFamily:family traits:traits weight:weight size:size];
- if (!nsFont)
- return 0;
-
- NSFontManager *fontManager = [NSFontManager sharedFontManager];
- NSFontTraitMask actualTraits = 0;
- if (fontDescription.italic())
- actualTraits = [fontManager traitsOfFont:nsFont];
- NSInteger actualWeight = [fontManager weightOfFont:nsFont];
-
- NSFont *platformFont = fontDescription.usePrinterFont() ? [nsFont printerFont] : [nsFont screenFont];
- bool syntheticBold = isAppKitFontWeightBold(weight) && !isAppKitFontWeightBold(actualWeight);
- bool syntheticOblique = (traits & NSFontItalicTrait) && !(actualTraits & NSFontItalicTrait);
-
- // FontPlatformData::font() can be null for the case of Chromium out-of-process font loading.
- // In that case, we don't want to use the platformData.
- OwnPtr<FontPlatformData> platformData = adoptPtr(new FontPlatformData(platformFont, size, fontDescription.usePrinterFont(), syntheticBold, syntheticOblique, fontDescription.orientation(), fontDescription.widthVariant()));
- if (!platformData->font())
- return 0;
- return platformData.leakPtr();
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/mac/FontComplexTextMac.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/mac/FontComplexTextMac.cpp
deleted file mode 100644
index 00235e65779..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/mac/FontComplexTextMac.cpp
+++ /dev/null
@@ -1,213 +0,0 @@
-/*
- * Copyright (C) 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/Font.h"
-
-#include "core/platform/graphics/FontFallbackList.h"
-#include "core/platform/graphics/GlyphBuffer.h"
-#include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/graphics/IntRect.h"
-#include "core/platform/graphics/SimpleFontData.h"
-#include "core/platform/graphics/TextRun.h"
-#include "core/platform/graphics/mac/ComplexTextController.h"
-#include "wtf/MathExtras.h"
-
-#include "core/platform/graphics/harfbuzz/HarfBuzzShaper.h"
-
-using namespace std;
-
-namespace WebCore {
-
-static bool preferHarfBuzz(const Font* font)
-{
- const FontDescription& description = font->fontDescription();
- return description.featureSettings() && description.featureSettings()->size() > 0;
-}
-
-FloatRect Font::selectionRectForComplexText(const TextRun& run, const FloatPoint& point, int h,
- int from, int to) const
-{
- if (preferHarfBuzz(this)) {
- HarfBuzzShaper shaper(this, run);
- if (shaper.shape())
- return shaper.selectionRect(point, h, from, to);
- }
- ComplexTextController controller(this, run);
- controller.advance(from);
- float beforeWidth = controller.runWidthSoFar();
- controller.advance(to);
- float afterWidth = controller.runWidthSoFar();
-
- // Using roundf() rather than ceilf() for the right edge as a compromise to ensure correct caret positioning
- if (run.rtl()) {
- float totalWidth = controller.totalWidth();
- return FloatRect(floorf(point.x() + totalWidth - afterWidth), point.y(), roundf(point.x() + totalWidth - beforeWidth) - floorf(point.x() + totalWidth - afterWidth), h);
- }
-
- return FloatRect(floorf(point.x() + beforeWidth), point.y(), roundf(point.x() + afterWidth) - floorf(point.x() + beforeWidth), h);
-}
-
-float Font::getGlyphsAndAdvancesForComplexText(const TextRun& run, int from, int to, GlyphBuffer& glyphBuffer, ForTextEmphasisOrNot forTextEmphasis) const
-{
- float initialAdvance;
-
- ComplexTextController controller(this, run, false, 0, forTextEmphasis);
- controller.advance(from);
- float beforeWidth = controller.runWidthSoFar();
- controller.advance(to, &glyphBuffer);
-
- if (glyphBuffer.isEmpty())
- return 0;
-
- float afterWidth = controller.runWidthSoFar();
-
- if (run.rtl()) {
- initialAdvance = controller.totalWidth() + controller.finalRoundingWidth() - afterWidth;
- glyphBuffer.reverse(0, glyphBuffer.size());
- } else
- initialAdvance = beforeWidth;
-
- return initialAdvance;
-}
-
-void Font::drawComplexText(GraphicsContext* context, const TextRunPaintInfo& runInfo, const FloatPoint& point) const
-{
- if (preferHarfBuzz(this)) {
- GlyphBuffer glyphBuffer;
- HarfBuzzShaper shaper(this, runInfo.run);
- shaper.setDrawRange(runInfo.from, runInfo.to);
- if (shaper.shape(&glyphBuffer)) {
- drawGlyphBuffer(context, runInfo, glyphBuffer, point);
- return;
- }
- }
- // This glyph buffer holds our glyphs + advances + font data for each glyph.
- GlyphBuffer glyphBuffer;
-
- float startX = point.x() + getGlyphsAndAdvancesForComplexText(runInfo.run, runInfo.from, runInfo.to, glyphBuffer);
-
- // We couldn't generate any glyphs for the run. Give up.
- if (glyphBuffer.isEmpty())
- return;
-
- // Draw the glyph buffer now at the starting point returned in startX.
- FloatPoint startPoint(startX, point.y());
- drawGlyphBuffer(context, runInfo, glyphBuffer, startPoint);
-}
-
-void Font::drawEmphasisMarksForComplexText(GraphicsContext* context, const TextRunPaintInfo& runInfo, const AtomicString& mark, const FloatPoint& point) const
-{
- GlyphBuffer glyphBuffer;
- float initialAdvance = getGlyphsAndAdvancesForComplexText(runInfo.run, runInfo.from, runInfo.to, glyphBuffer, ForTextEmphasis);
-
- if (glyphBuffer.isEmpty())
- return;
-
- drawEmphasisMarks(context, runInfo, glyphBuffer, mark, FloatPoint(point.x() + initialAdvance, point.y()));
-}
-
-float Font::floatWidthForComplexText(const TextRun& run, HashSet<const SimpleFontData*>* fallbackFonts, GlyphOverflow* glyphOverflow) const
-{
- if (preferHarfBuzz(this)) {
- HarfBuzzShaper shaper(this, run);
- if (shaper.shape())
- return shaper.totalWidth();
- }
- ComplexTextController controller(this, run, true, fallbackFonts);
- if (glyphOverflow) {
- glyphOverflow->top = max<int>(glyphOverflow->top, ceilf(-controller.minGlyphBoundingBoxY()) - (glyphOverflow->computeBounds ? 0 : fontMetrics().ascent()));
- glyphOverflow->bottom = max<int>(glyphOverflow->bottom, ceilf(controller.maxGlyphBoundingBoxY()) - (glyphOverflow->computeBounds ? 0 : fontMetrics().descent()));
- glyphOverflow->left = max<int>(0, ceilf(-controller.minGlyphBoundingBoxX()));
- glyphOverflow->right = max<int>(0, ceilf(controller.maxGlyphBoundingBoxX() - controller.totalWidth()));
- }
- return controller.totalWidth();
-}
-
-int Font::offsetForPositionForComplexText(const TextRun& run, float x, bool includePartialGlyphs) const
-{
- if (preferHarfBuzz(this)) {
- HarfBuzzShaper shaper(this, run);
- if (shaper.shape())
- return shaper.offsetForPosition(x);
- }
- ComplexTextController controller(this, run);
- return controller.offsetForPosition(x, includePartialGlyphs);
-}
-
-const SimpleFontData* Font::fontDataForCombiningCharacterSequence(const UChar* characters, size_t length, FontDataVariant variant) const
-{
- UChar32 baseCharacter;
- size_t baseCharacterLength = 0;
- U16_NEXT(characters, baseCharacterLength, length, baseCharacter);
-
- GlyphData baseCharacterGlyphData = glyphDataForCharacter(baseCharacter, false, variant);
-
- if (!baseCharacterGlyphData.glyph)
- return 0;
-
- if (length == baseCharacterLength)
- return baseCharacterGlyphData.fontData;
-
- bool triedBaseCharacterFontData = false;
-
- unsigned i = 0;
- for (const FontData* fontData = fontDataAt(0); fontData; fontData = fontDataAt(++i)) {
- const SimpleFontData* simpleFontData = fontData->fontDataForCharacter(baseCharacter);
- if (variant == NormalVariant) {
- if (simpleFontData->platformData().orientation() == Vertical) {
- if (isCJKIdeographOrSymbol(baseCharacter) && !simpleFontData->hasVerticalGlyphs()) {
- variant = BrokenIdeographVariant;
- simpleFontData = simpleFontData->brokenIdeographFontData().get();
- } else if (m_fontDescription.nonCJKGlyphOrientation() == NonCJKGlyphOrientationVerticalRight) {
- SimpleFontData* verticalRightFontData = simpleFontData->verticalRightOrientationFontData().get();
- Glyph verticalRightGlyph = verticalRightFontData->glyphForCharacter(baseCharacter);
- if (verticalRightGlyph == baseCharacterGlyphData.glyph)
- simpleFontData = verticalRightFontData;
- } else {
- SimpleFontData* uprightFontData = simpleFontData->uprightOrientationFontData().get();
- Glyph uprightGlyph = uprightFontData->glyphForCharacter(baseCharacter);
- if (uprightGlyph != baseCharacterGlyphData.glyph)
- simpleFontData = uprightFontData;
- }
- }
- } else {
- if (const SimpleFontData* variantFontData = simpleFontData->variantFontData(m_fontDescription, variant).get())
- simpleFontData = variantFontData;
- }
-
- if (simpleFontData == baseCharacterGlyphData.fontData)
- triedBaseCharacterFontData = true;
-
- if (simpleFontData->canRenderCombiningCharacterSequence(characters, length))
- return simpleFontData;
- }
-
- if (!triedBaseCharacterFontData && baseCharacterGlyphData.fontData && baseCharacterGlyphData.fontData->canRenderCombiningCharacterSequence(characters, length))
- return baseCharacterGlyphData.fontData;
-
- return SimpleFontData::systemFallback();
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/mac/FontCustomPlatformDataMac.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/mac/FontCustomPlatformDataMac.cpp
deleted file mode 100644
index add70032bcc..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/mac/FontCustomPlatformDataMac.cpp
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * Copyright (C) 2007, 2008, 2010 Apple Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#include "config.h"
-#include "core/platform/graphics/FontCustomPlatformData.h"
-
-#include "core/platform/SharedBuffer.h"
-#include "core/platform/graphics/FontPlatformData.h"
-#include "core/platform/graphics/opentype/OpenTypeSanitizer.h"
-#include "core/platform/graphics/skia/SkiaSharedBufferStream.h"
-#include "third_party/skia/include/core/SkStream.h"
-#include "third_party/skia/include/core/SkTypeface.h"
-#include "wtf/PassOwnPtr.h"
-
-#include <ApplicationServices/ApplicationServices.h>
-
-namespace WebCore {
-
-FontCustomPlatformData::FontCustomPlatformData(CGFontRef cgFont, PassRefPtr<SkTypeface> typeface)
- : m_cgFont(AdoptCF, cgFont)
- , m_typeface(typeface)
-{
-}
-
-FontCustomPlatformData::~FontCustomPlatformData()
-{
-}
-
-FontPlatformData FontCustomPlatformData::fontPlatformData(int size, bool bold, bool italic, FontOrientation orientation, FontWidthVariant widthVariant)
-{
- return FontPlatformData(m_cgFont.get(), size, bold, italic, orientation, widthVariant);
-}
-
-PassOwnPtr<FontCustomPlatformData> FontCustomPlatformData::create(SharedBuffer* buffer)
-{
- ASSERT_ARG(buffer, buffer);
-
- OpenTypeSanitizer sanitizer(buffer);
- RefPtr<SharedBuffer> transcodeBuffer = sanitizer.sanitize();
- if (!transcodeBuffer)
- return nullptr; // validation failed.
- buffer = transcodeBuffer.get();
-
- RetainPtr<CFDataRef> bufferData(AdoptCF, CFDataCreate(0, reinterpret_cast<const UInt8*>(buffer->data()), buffer->size()));
- RetainPtr<CGDataProviderRef> dataProvider(AdoptCF, CGDataProviderCreateWithCFData(bufferData.get()));
- RetainPtr<CGFontRef> cgFontRef(AdoptCF, CGFontCreateWithDataProvider(dataProvider.get()));
- if (!cgFontRef)
- return nullptr;
-
- // It's unclear whether this is used. It seems like it has the effect of priming the cache.
- // Since we store this anyways, it might be worthwhile just plumbing this to FontMac.cpp in
- // a more obvious way.
- // FIXME: Remove this, add an explicit use, or add a comment explaining why this exists.
- RefPtr<SkiaSharedBufferStream> stream = SkiaSharedBufferStream::create(buffer);
- RefPtr<SkTypeface> typeface = adoptRef(SkTypeface::CreateFromStream(stream.get()));
- if (!typeface)
- return nullptr;
-
- return adoptPtr(new FontCustomPlatformData(cgFontRef.leakRef(), typeface.release()));
-}
-
-bool FontCustomPlatformData::supportsFormat(const String& format)
-{
- return equalIgnoringCase(format, "truetype") || equalIgnoringCase(format, "opentype") || OpenTypeSanitizer::supportsFormat(format);
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/mac/FontMac.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/mac/FontMac.cpp
deleted file mode 100644
index eb349caadf9..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/mac/FontMac.cpp
+++ /dev/null
@@ -1,182 +0,0 @@
-/*
- * Copyright (c) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/Font.h"
-
-#include "core/platform/LayoutTestSupport.h"
-#include "core/platform/graphics/FontSmoothingMode.h"
-#include "core/platform/graphics/GlyphBuffer.h"
-#include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/graphics/SimpleFontData.h"
-
-#include "third_party/skia/include/core/SkCanvas.h"
-#include "third_party/skia/include/core/SkPaint.h"
-#include "third_party/skia/include/core/SkTypeface.h"
-#include "third_party/skia/include/ports/SkTypeface_mac.h"
-
-namespace WebCore {
-
-bool Font::canReturnFallbackFontsForComplexText()
-{
- return true;
-}
-
-bool Font::canExpandAroundIdeographsInComplexText()
-{
- return true;
-}
-
-static void setupPaint(SkPaint* paint, const SimpleFontData* fontData, const Font* font, bool shouldAntialias, bool shouldSmoothFonts)
-{
- const FontPlatformData& platformData = fontData->platformData();
- const float textSize = platformData.m_size >= 0 ? platformData.m_size : 12;
-
- paint->setAntiAlias(shouldAntialias);
- paint->setEmbeddedBitmapText(false);
- paint->setTextSize(SkFloatToScalar(textSize));
- paint->setVerticalText(platformData.orientation() == Vertical);
- SkTypeface* typeface = SkCreateTypefaceFromCTFont(platformData.ctFont());
- SkAutoUnref autoUnref(typeface);
- paint->setTypeface(typeface);
- paint->setFakeBoldText(platformData.m_syntheticBold);
- paint->setTextSkewX(platformData.m_syntheticOblique ? -SK_Scalar1 / 4 : 0);
- paint->setAutohinted(false); // freetype specific
- paint->setLCDRenderText(shouldSmoothFonts);
- paint->setSubpixelText(true);
-
-#if OS(MACOSX)
- // When using CoreGraphics, disable hinting when webkit-font-smoothing:antialiased is used.
- // See crbug.com/152304
- if (font->fontDescription().fontSmoothing() == Antialiased)
- paint->setHinting(SkPaint::kNo_Hinting);
-#endif
-
- if (font->fontDescription().textRenderingMode() == GeometricPrecision)
- paint->setHinting(SkPaint::kNo_Hinting);
-}
-
-// TODO: This needs to be split into helper functions to better scope the
-// inputs/outputs, and reduce duplicate code.
-// This issue is tracked in https://bugs.webkit.org/show_bug.cgi?id=62989
-void Font::drawGlyphs(GraphicsContext* gc, const SimpleFontData* font,
- const GlyphBuffer& glyphBuffer, int from, int numGlyphs,
- const FloatPoint& point, const FloatRect& textRect) const {
- COMPILE_ASSERT(sizeof(GlyphBufferGlyph) == sizeof(uint16_t), GlyphBufferGlyphSize_equals_uint16_t);
-
- bool shouldSmoothFonts = true;
- bool shouldAntialias = true;
-
- switch (fontDescription().fontSmoothing()) {
- case Antialiased:
- shouldSmoothFonts = false;
- break;
- case SubpixelAntialiased:
- break;
- case NoSmoothing:
- shouldAntialias = false;
- shouldSmoothFonts = false;
- break;
- case AutoSmoothing:
- // For the AutoSmooth case, don't do anything! Keep the default settings.
- break;
- }
-
- if (!shouldUseSmoothing() || isRunningLayoutTest()) {
- shouldSmoothFonts = false;
- shouldAntialias = false;
- }
-
- const GlyphBufferGlyph* glyphs = glyphBuffer.glyphs(from);
- SkScalar x = SkFloatToScalar(point.x());
- SkScalar y = SkFloatToScalar(point.y());
-
- if (font->platformData().orientation() == Vertical)
- y += SkFloatToScalar(font->fontMetrics().floatAscent(IdeographicBaseline) - font->fontMetrics().floatAscent());
- // FIXME: text rendering speed:
- // Android has code in their WebCore fork to special case when the
- // GlyphBuffer has no advances other than the defaults. In that case the
- // text drawing can proceed faster. However, it's unclear when those
- // patches may be upstreamed to WebKit so we always use the slower path
- // here.
- const GlyphBufferAdvance* adv = glyphBuffer.advances(from);
- SkAutoSTMalloc<32, SkPoint> storage(numGlyphs);
- SkPoint* pos = storage.get();
-
- for (int i = 0; i < numGlyphs; i++) {
- pos[i].set(x, y);
- x += SkFloatToScalar(adv[i].width());
- y += SkFloatToScalar(adv[i].height());
- }
-
- if (font->platformData().orientation() == Vertical) {
- gc->save();
- gc->rotate(-0.5 * SK_ScalarPI);
- SkMatrix rotator;
- rotator.reset();
- rotator.setRotate(90);
- rotator.mapPoints(pos, numGlyphs);
- }
- TextDrawingModeFlags textMode = gc->textDrawingMode();
-
- // We draw text up to two times (once for fill, once for stroke).
- if (textMode & TextModeFill) {
- SkPaint paint;
- gc->setupPaintForFilling(&paint);
- setupPaint(&paint, font, this, shouldAntialias, shouldSmoothFonts);
- gc->adjustTextRenderMode(&paint);
- paint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
-
- gc->drawPosText(glyphs, numGlyphs * sizeof(uint16_t), pos, textRect, paint);
- }
-
- if ((textMode & TextModeStroke)
- && gc->strokeStyle() != NoStroke
- && gc->strokeThickness() > 0) {
-
- SkPaint paint;
- gc->setupPaintForStroking(&paint);
- setupPaint(&paint, font, this, shouldAntialias, shouldSmoothFonts);
- gc->adjustTextRenderMode(&paint);
- paint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
-
- if (textMode & TextModeFill) {
- // If we also filled, we don't want to draw shadows twice.
- // See comment in FontChromiumWin.cpp::paintSkiaText() for more details.
- paint.setLooper(0);
- }
-
- gc->drawPosText(glyphs, numGlyphs * sizeof(uint16_t), pos, textRect, paint);
- }
- if (font->platformData().orientation() == Vertical)
- gc->restore();
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/mac/GlyphPageTreeNodeMac.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/mac/GlyphPageTreeNodeMac.cpp
deleted file mode 100644
index dc6b9843224..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/mac/GlyphPageTreeNodeMac.cpp
+++ /dev/null
@@ -1,168 +0,0 @@
-/*
- * Copyright (C) 2006, 2007 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/GlyphPageTreeNode.h"
-
-#include <ApplicationServices/ApplicationServices.h>
-#include "core/platform/graphics/Font.h"
-#include "core/platform/graphics/SimpleFontData.h"
-
-// Forward declare Mac SPIs.
-// Request for public API: rdar://13787589
-extern "C" {
-void CGFontGetGlyphsForUnichars(CGFontRef font, const UniChar chars[], CGGlyph glyphs[], size_t length);
-}
-
-namespace WebCore {
-
-static bool shouldUseCoreText(UChar* buffer, unsigned bufferLength, const SimpleFontData* fontData)
-{
- if (fontData->platformData().isCompositeFontReference())
- return true;
- if (fontData->platformData().widthVariant() != RegularWidth || fontData->hasVerticalGlyphs()) {
- // Ideographs don't have a vertical variant or width variants.
- for (unsigned i = 0; i < bufferLength; ++i) {
- if (!Font::isCJKIdeograph(buffer[i]))
- return true;
- }
- }
-
- return false;
-}
-
-bool GlyphPage::fill(unsigned offset, unsigned length, UChar* buffer, unsigned bufferLength, const SimpleFontData* fontData)
-{
- bool haveGlyphs = false;
-
- Vector<CGGlyph, 512> glyphs(bufferLength);
- if (!shouldUseCoreText(buffer, bufferLength, fontData)) {
- CGFontGetGlyphsForUnichars(fontData->platformData().cgFont(), buffer, glyphs.data(), bufferLength);
- for (unsigned i = 0; i < length; ++i) {
- if (!glyphs[i])
- setGlyphDataForIndex(offset + i, 0, 0);
- else {
- setGlyphDataForIndex(offset + i, glyphs[i], fontData);
- haveGlyphs = true;
- }
- }
- } else if (!fontData->platformData().isCompositeFontReference() && fontData->platformData().widthVariant() != RegularWidth
- && CTFontGetGlyphsForCharacters(fontData->platformData().ctFont(), buffer, glyphs.data(), bufferLength)) {
- // When buffer consists of surrogate pairs, CTFontGetGlyphsForCharacters
- // places the glyphs at indices corresponding to the first character of each pair.
- unsigned glyphStep = bufferLength / length;
- for (unsigned i = 0; i < length; ++i) {
- if (!glyphs[i * glyphStep])
- setGlyphDataForIndex(offset + i, 0, 0);
- else {
- setGlyphDataForIndex(offset + i, glyphs[i * glyphStep], fontData);
- haveGlyphs = true;
- }
- }
- } else {
- // We ask CoreText for possible vertical variant glyphs
- RetainPtr<CFStringRef> string(AdoptCF, CFStringCreateWithCharactersNoCopy(kCFAllocatorDefault, buffer, bufferLength, kCFAllocatorNull));
- RetainPtr<CFAttributedStringRef> attributedString(AdoptCF, CFAttributedStringCreate(kCFAllocatorDefault, string.get(), fontData->getCFStringAttributes(0, fontData->hasVerticalGlyphs() ? Vertical : Horizontal)));
- RetainPtr<CTLineRef> line(AdoptCF, CTLineCreateWithAttributedString(attributedString.get()));
-
- CFArrayRef runArray = CTLineGetGlyphRuns(line.get());
- CFIndex runCount = CFArrayGetCount(runArray);
-
- // Initialize glyph entries
- for (unsigned index = 0; index < length; ++index)
- setGlyphDataForIndex(offset + index, 0, 0);
-
- Vector<CGGlyph, 512> glyphVector;
- Vector<CFIndex, 512> indexVector;
- bool done = false;
-
- // For the CGFont comparison in the loop, use the CGFont that Core Text assigns to the CTFont. This may
- // be non-CFEqual to fontData->platformData().cgFont().
- RetainPtr<CGFontRef> cgFont(AdoptCF, CTFontCopyGraphicsFont(fontData->platformData().ctFont(), 0));
-
- for (CFIndex r = 0; r < runCount && !done ; ++r) {
- // CTLine could map characters over multiple fonts using its own font fallback list.
- // We need to pick runs that use the exact font we need, i.e., fontData->platformData().ctFont().
- CTRunRef ctRun = static_cast<CTRunRef>(CFArrayGetValueAtIndex(runArray, r));
- ASSERT(CFGetTypeID(ctRun) == CTRunGetTypeID());
-
- CFDictionaryRef attributes = CTRunGetAttributes(ctRun);
- CTFontRef runFont = static_cast<CTFontRef>(CFDictionaryGetValue(attributes, kCTFontAttributeName));
- RetainPtr<CGFontRef> runCGFont(AdoptCF, CTFontCopyGraphicsFont(runFont, 0));
- // Use CGFont here as CFEqual for CTFont counts all attributes for font.
- bool gotBaseFont = CFEqual(cgFont.get(), runCGFont.get());
- if (gotBaseFont || fontData->platformData().isCompositeFontReference()) {
- // This run uses the font we want. Extract glyphs.
- CFIndex glyphCount = CTRunGetGlyphCount(ctRun);
- const CGGlyph* glyphs = CTRunGetGlyphsPtr(ctRun);
- if (!glyphs) {
- glyphVector.resize(glyphCount);
- CTRunGetGlyphs(ctRun, CFRangeMake(0, 0), glyphVector.data());
- glyphs = glyphVector.data();
- }
- const CFIndex* stringIndices = CTRunGetStringIndicesPtr(ctRun);
- if (!stringIndices) {
- indexVector.resize(glyphCount);
- CTRunGetStringIndices(ctRun, CFRangeMake(0, 0), indexVector.data());
- stringIndices = indexVector.data();
- }
-
- if (gotBaseFont) {
- for (CFIndex i = 0; i < glyphCount; ++i) {
- if (stringIndices[i] >= static_cast<CFIndex>(length)) {
- done = true;
- break;
- }
- if (glyphs[i]) {
- setGlyphDataForIndex(offset + stringIndices[i], glyphs[i], fontData);
- haveGlyphs = true;
- }
- }
- } else {
- const SimpleFontData* runSimple = fontData->getCompositeFontReferenceFontData((NSFont *)runFont);
- if (runSimple) {
- for (CFIndex i = 0; i < glyphCount; ++i) {
- if (stringIndices[i] >= static_cast<CFIndex>(length)) {
- done = true;
- break;
- }
- if (glyphs[i]) {
- setGlyphDataForIndex(offset + stringIndices[i], glyphs[i], runSimple);
- haveGlyphs = true;
- }
- }
- }
- }
- }
- }
- }
-
- return haveGlyphs;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/mac/IntPointMac.mm b/chromium/third_party/WebKit/Source/core/platform/graphics/mac/IntPointMac.mm
deleted file mode 100644
index 9955770f09f..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/mac/IntPointMac.mm
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright (C) 2004, 2005, 2006 Apple Computer, Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/IntPoint.h"
-
-namespace WebCore {
-
-#ifndef NSGEOMETRY_TYPES_SAME_AS_CGGEOMETRY_TYPES
-
-IntPoint::IntPoint(const NSPoint& p) : m_x(static_cast<int>(p.x)), m_y(static_cast<int>(p.y))
-{
-}
-
-IntPoint::operator NSPoint() const
-{
- return NSMakePoint(m_x, m_y);
-}
-
-#endif
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/mac/IntRectMac.mm b/chromium/third_party/WebKit/Source/core/platform/graphics/mac/IntRectMac.mm
deleted file mode 100644
index b42147056e4..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/mac/IntRectMac.mm
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright (C) 2003, 2006 Apple Computer, Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/IntRect.h"
-
-namespace WebCore {
-
-#ifndef NSGEOMETRY_TYPES_SAME_AS_CGGEOMETRY_TYPES
-
-IntRect::operator NSRect() const
-{
- return NSMakeRect(x(), y(), width(), height());
-}
-
-IntRect enclosingIntRect(const NSRect& rect)
-{
- int l = static_cast<int>(floorf(rect.origin.x));
- int t = static_cast<int>(floorf(rect.origin.y));
- int r = static_cast<int>(ceilf(NSMaxX(rect)));
- int b = static_cast<int>(ceilf(NSMaxY(rect)));
- return IntRect(l, t, r - l, b - t);
-}
-
-#endif
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/mac/IntSizeMac.mm b/chromium/third_party/WebKit/Source/core/platform/graphics/mac/IntSizeMac.mm
deleted file mode 100644
index 06f07f80abb..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/mac/IntSizeMac.mm
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright (C) 2003, 2004, 2005, 2006 Apple Computer, Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/IntSize.h"
-
-namespace WebCore {
-
-#ifndef NSGEOMETRY_TYPES_SAME_AS_CGGEOMETRY_TYPES
-
-IntSize::IntSize(const NSSize& s) : m_width(static_cast<int>(s.width)), m_height(static_cast<int>(s.height))
-{
-}
-
-IntSize::operator NSSize() const
-{
- return NSMakeSize(m_width, m_height);
-}
-
-#endif
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/mac/SimpleFontDataCoreText.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/mac/SimpleFontDataCoreText.cpp
deleted file mode 100644
index 0ef1f6a99da..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/mac/SimpleFontDataCoreText.cpp
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright (C) 2005, 2006, 2012 Apple Inc. All rights reserved.
- * Copyright (C) 2006 Alexey Proskuryakov
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/SimpleFontData.h"
-
-#include <ApplicationServices/ApplicationServices.h>
-
-namespace WebCore {
-
-CFDictionaryRef SimpleFontData::getCFStringAttributes(TypesettingFeatures typesettingFeatures, FontOrientation orientation) const
-{
- unsigned key = typesettingFeatures + 1;
- HashMap<unsigned, RetainPtr<CFDictionaryRef> >::AddResult addResult = m_CFStringAttributes.add(key, RetainPtr<CFDictionaryRef>());
- RetainPtr<CFDictionaryRef>& attributesDictionary = addResult.iterator->value;
- if (!addResult.isNewEntry)
- return attributesDictionary.get();
-
- attributesDictionary.adoptCF(CFDictionaryCreateMutable(kCFAllocatorDefault, 4, &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
- CFMutableDictionaryRef mutableAttributes = (CFMutableDictionaryRef)attributesDictionary.get();
-
- CFDictionarySetValue(mutableAttributes, kCTFontAttributeName, platformData().ctFont());
-
- if (!(typesettingFeatures & Kerning)) {
- const float zero = 0;
- static CFNumberRef zeroKerningValue = CFNumberCreate(kCFAllocatorDefault, kCFNumberFloatType, &zero);
- CFDictionarySetValue(mutableAttributes, kCTKernAttributeName, zeroKerningValue);
- }
-
- bool allowLigatures = (orientation == Horizontal && platformData().allowsLigatures()) || (typesettingFeatures & Ligatures);
- if (!allowLigatures) {
- const int zero = 0;
- static CFNumberRef essentialLigaturesValue = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &zero);
- CFDictionarySetValue(mutableAttributes, kCTLigatureAttributeName, essentialLigaturesValue);
- }
-
- if (orientation == Vertical)
- CFDictionarySetValue(mutableAttributes, kCTVerticalFormsAttributeName, kCFBooleanTrue);
-
- return attributesDictionary.get();
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/mac/SimpleFontDataMac.mm b/chromium/third_party/WebKit/Source/core/platform/graphics/mac/SimpleFontDataMac.mm
deleted file mode 100644
index 01f4d39e185..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/mac/SimpleFontDataMac.mm
+++ /dev/null
@@ -1,453 +0,0 @@
-/*
- * Copyright (C) 2005, 2006, 2010, 2011 Apple Inc. All rights reserved.
- * Copyright (C) 2006 Alexey Proskuryakov
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#import "config.h"
-#import "core/platform/graphics/SimpleFontData.h"
-
-#import <AppKit/AppKit.h>
-#import <ApplicationServices/ApplicationServices.h>
-#import <float.h>
-#import <unicode/uchar.h>
-#import "core/platform/SharedBuffer.h"
-#import "core/platform/graphics/Color.h"
-#import "core/platform/graphics/FloatRect.h"
-#import "core/platform/graphics/Font.h"
-#import "core/platform/graphics/FontCache.h"
-#import "core/platform/graphics/FontDescription.h"
-#import "core/platform/mac/BlockExceptions.h"
-#import <wtf/Assertions.h>
-#import <wtf/RetainPtr.h>
-#import <wtf/StdLibExtras.h>
-#import <wtf/UnusedParam.h>
-
-@interface NSFont (WebAppKitSecretAPI)
-- (BOOL)_isFakeFixedPitch;
-@end
-
-// The names of these constants were taken from history
-// /trunk/WebKit/WebCoreSupport.subproj/WebTextRenderer.m@9311. The values
-// were derived from the assembly of libWebKitSystemInterfaceLeopard.a.
-enum CGFontRenderingMode {
- kCGFontRenderingMode1BitPixelAligned = 0x0,
- kCGFontRenderingModeAntialiasedPixelAligned = 0x1,
- kCGFontRenderingModeAntialiased = 0xd
-};
-
-// Forward declare Mac SPIs.
-extern "C" {
-// Request for public API: rdar://13803586
-bool CGFontGetGlyphAdvancesForStyle(CGFontRef font, CGAffineTransform* transform, CGFontRenderingMode renderingMode, ATSGlyphRef* glyph, size_t count, CGSize* advance);
-
-// Request for public API: rdar://13803619
-CTLineRef CTLineCreateWithUniCharProvider(const UniChar* (*provide)(CFIndex stringIndex, CFIndex* charCount, CFDictionaryRef* attributes, void* context), void (*dispose)(const UniChar* chars, void* context), void* context);
-}
-
-static CGFontRenderingMode cgFontRenderingModeForNSFont(NSFont* font) {
- if (!font)
- return kCGFontRenderingModeAntialiasedPixelAligned;
-
- switch ([font renderingMode]) {
- case NSFontIntegerAdvancementsRenderingMode: return kCGFontRenderingMode1BitPixelAligned;
- case NSFontAntialiasedIntegerAdvancementsRenderingMode: return kCGFontRenderingModeAntialiasedPixelAligned;
- default: return kCGFontRenderingModeAntialiased;
- }
-}
-
-using namespace std;
-
-namespace WebCore {
-
-static bool fontHasVerticalGlyphs(CTFontRef ctFont)
-{
- // The check doesn't look neat but this is what AppKit does for vertical writing...
- RetainPtr<CFArrayRef> tableTags(AdoptCF, CTFontCopyAvailableTables(ctFont, kCTFontTableOptionNoOptions));
- CFIndex numTables = CFArrayGetCount(tableTags.get());
- for (CFIndex index = 0; index < numTables; ++index) {
- CTFontTableTag tag = (CTFontTableTag)(uintptr_t)CFArrayGetValueAtIndex(tableTags.get(), index);
- if (tag == kCTFontTableVhea || tag == kCTFontTableVORG)
- return true;
- }
- return false;
-}
-
-static bool initFontData(SimpleFontData* fontData)
-{
- if (!fontData->platformData().cgFont())
- return false;
-
- return true;
-}
-
-static NSString *webFallbackFontFamily(void)
-{
- DEFINE_STATIC_LOCAL(RetainPtr<NSString>, webFallbackFontFamily, ([[NSFont systemFontOfSize:16.0f] familyName]));
- return webFallbackFontFamily.get();
-}
-
-const SimpleFontData* SimpleFontData::getCompositeFontReferenceFontData(NSFont *key) const
-{
- if (key && !CFEqual(RetainPtr<CFStringRef>(AdoptCF, CTFontCopyPostScriptName(CTFontRef(key))).get(), CFSTR("LastResort"))) {
- if (!m_derivedFontData)
- m_derivedFontData = DerivedFontData::create(isCustomFont());
- if (!m_derivedFontData->compositeFontReferences)
- m_derivedFontData->compositeFontReferences.adoptCF(CFDictionaryCreateMutable(kCFAllocatorDefault, 1, &kCFTypeDictionaryKeyCallBacks, NULL));
- else {
- const SimpleFontData* found = static_cast<const SimpleFontData*>(CFDictionaryGetValue(m_derivedFontData->compositeFontReferences.get(), static_cast<const void *>(key)));
- if (found)
- return found;
- }
- if (CFMutableDictionaryRef dictionary = m_derivedFontData->compositeFontReferences.get()) {
- bool isUsingPrinterFont = platformData().isPrinterFont();
- NSFont *substituteFont = isUsingPrinterFont ? [key printerFont] : [key screenFont];
-
- CTFontSymbolicTraits traits = CTFontGetSymbolicTraits(toCTFontRef(substituteFont));
- bool syntheticBold = platformData().syntheticBold() && !(traits & kCTFontBoldTrait);
- bool syntheticOblique = platformData().syntheticOblique() && !(traits & kCTFontItalicTrait);
-
- FontPlatformData substitutePlatform(substituteFont, platformData().size(), isUsingPrinterFont, syntheticBold, syntheticOblique, platformData().orientation(), platformData().widthVariant());
- SimpleFontData* value = new SimpleFontData(substitutePlatform, isCustomFont());
- if (value) {
- CFDictionaryAddValue(dictionary, key, value);
- return value;
- }
- }
- }
- return 0;
-}
-
-void SimpleFontData::platformInit()
-{
- m_syntheticBoldOffset = m_platformData.m_syntheticBold ? 1.0f : 0.f;
-
- bool failedSetup = false;
- if (!initFontData(this)) {
- // Ack! Something very bad happened, like a corrupt font.
- // Try looking for an alternate 'base' font for this renderer.
-
- // Special case hack to use "Times New Roman" in place of "Times".
- // "Times RO" is a common font whose family name is "Times".
- // It overrides the normal "Times" family font.
- // It also appears to have a corrupt regular variant.
- NSString *fallbackFontFamily;
- if ([[m_platformData.font() familyName] isEqual:@"Times"])
- fallbackFontFamily = @"Times New Roman";
- else
- fallbackFontFamily = webFallbackFontFamily();
-
- // Try setting up the alternate font.
- // This is a last ditch effort to use a substitute font when something has gone wrong.
-#if !ERROR_DISABLED
- RetainPtr<NSFont> initialFont = m_platformData.font();
-#endif
- if (m_platformData.font())
- m_platformData.setFont([[NSFontManager sharedFontManager] convertFont:m_platformData.font() toFamily:fallbackFontFamily]);
- else
- m_platformData.setFont([NSFont fontWithName:fallbackFontFamily size:m_platformData.size()]);
-
- if (!initFontData(this)) {
- if ([fallbackFontFamily isEqual:@"Times New Roman"]) {
- // OK, couldn't setup Times New Roman as an alternate to Times, fallback
- // on the system font. If this fails we have no alternative left.
- m_platformData.setFont([[NSFontManager sharedFontManager] convertFont:m_platformData.font() toFamily:webFallbackFontFamily()]);
- if (!initFontData(this)) {
- // We tried, Times, Times New Roman, and the system font. No joy. We have to give up.
- LOG_ERROR("unable to initialize with font %@", initialFont.get());
- failedSetup = true;
- }
- } else {
- // We tried the requested font and the system font. No joy. We have to give up.
- LOG_ERROR("unable to initialize with font %@", initialFont.get());
- failedSetup = true;
- }
- }
-
- // Report the problem.
- LOG_ERROR("Corrupt font detected, using %@ in place of %@.",
- [m_platformData.font() familyName], [initialFont.get() familyName]);
- }
-
- // If all else fails, try to set up using the system font.
- // This is probably because Times and Times New Roman are both unavailable.
- if (failedSetup) {
- m_platformData.setFont([NSFont systemFontOfSize:[m_platformData.font() pointSize]]);
- LOG_ERROR("failed to set up font, using system font %s", m_platformData.font());
- initFontData(this);
- }
-
- int iAscent;
- int iDescent;
- int iLineGap;
- unsigned unitsPerEm;
- iAscent = CGFontGetAscent(m_platformData.cgFont());
- // Some fonts erroneously specify a positive descender value. We follow Core Text in assuming that
- // such fonts meant the same distance, but in the reverse direction.
- iDescent = -abs(CGFontGetDescent(m_platformData.cgFont()));
- iLineGap = CGFontGetLeading(m_platformData.cgFont());
- unitsPerEm = CGFontGetUnitsPerEm(m_platformData.cgFont());
-
- float pointSize = m_platformData.m_size;
- float ascent = scaleEmToUnits(iAscent, unitsPerEm) * pointSize;
- float descent = -scaleEmToUnits(iDescent, unitsPerEm) * pointSize;
- float lineGap = scaleEmToUnits(iLineGap, unitsPerEm) * pointSize;
-
- // We need to adjust Times, Helvetica, and Courier to closely match the
- // vertical metrics of their Microsoft counterparts that are the de facto
- // web standard. The AppKit adjustment of 20% is too big and is
- // incorrectly added to line spacing, so we use a 15% adjustment instead
- // and add it to the ascent.
- NSString *familyName = [m_platformData.font() familyName];
- if ([familyName isEqualToString:@"Times"] || [familyName isEqualToString:@"Helvetica"] || [familyName isEqualToString:@"Courier"])
- ascent += floorf(((ascent + descent) * 0.15f) + 0.5f);
-
- // Compute and store line spacing, before the line metrics hacks are applied.
- m_fontMetrics.setLineSpacing(lroundf(ascent) + lroundf(descent) + lroundf(lineGap));
-
- // Hack Hiragino line metrics to allow room for marked text underlines.
- // <rdar://problem/5386183>
- if (descent < 3 && lineGap >= 3 && [familyName hasPrefix:@"Hiragino"]) {
- lineGap -= 3 - descent;
- descent = 3;
- }
-
- if (platformData().orientation() == Vertical && !isTextOrientationFallback())
- m_hasVerticalGlyphs = fontHasVerticalGlyphs(m_platformData.ctFont());
-
- float xHeight;
-
- if (platformData().orientation() == Horizontal) {
- // Measure the actual character "x", since it's possible for it to extend below the baseline, and we need the
- // reported x-height to only include the portion of the glyph that is above the baseline.
- GlyphPage* glyphPageZero = GlyphPageTreeNode::getRootChild(this, 0)->page();
- NSGlyph xGlyph = glyphPageZero ? glyphPageZero->glyphForCharacter('x') : 0;
- if (xGlyph)
- xHeight = -CGRectGetMinY(platformBoundsForGlyph(xGlyph));
- else
- xHeight = scaleEmToUnits(CGFontGetXHeight(m_platformData.cgFont()), unitsPerEm) * pointSize;
- } else
- xHeight = verticalRightOrientationFontData()->fontMetrics().xHeight();
-
- m_fontMetrics.setUnitsPerEm(unitsPerEm);
- m_fontMetrics.setAscent(ascent);
- m_fontMetrics.setDescent(descent);
- m_fontMetrics.setLineGap(lineGap);
- m_fontMetrics.setXHeight(xHeight);
-}
-
-static CFDataRef copyFontTableForTag(FontPlatformData& platformData, FourCharCode tableName)
-{
- return CGFontCopyTableForTag(platformData.cgFont(), tableName);
-}
-
-void SimpleFontData::platformCharWidthInit()
-{
- m_avgCharWidth = 0;
- m_maxCharWidth = 0;
-
- RetainPtr<CFDataRef> os2Table(AdoptCF, copyFontTableForTag(m_platformData, 'OS/2'));
- if (os2Table && CFDataGetLength(os2Table.get()) >= 4) {
- const UInt8* os2 = CFDataGetBytePtr(os2Table.get());
- SInt16 os2AvgCharWidth = os2[2] * 256 + os2[3];
- m_avgCharWidth = scaleEmToUnits(os2AvgCharWidth, m_fontMetrics.unitsPerEm()) * m_platformData.m_size;
- }
-
- RetainPtr<CFDataRef> headTable(AdoptCF, copyFontTableForTag(m_platformData, 'head'));
- if (headTable && CFDataGetLength(headTable.get()) >= 42) {
- const UInt8* head = CFDataGetBytePtr(headTable.get());
- ushort uxMin = head[36] * 256 + head[37];
- ushort uxMax = head[40] * 256 + head[41];
- SInt16 xMin = static_cast<SInt16>(uxMin);
- SInt16 xMax = static_cast<SInt16>(uxMax);
- float diff = static_cast<float>(xMax - xMin);
- m_maxCharWidth = scaleEmToUnits(diff, m_fontMetrics.unitsPerEm()) * m_platformData.m_size;
- }
-
- // Fallback to a cross-platform estimate, which will populate these values if they are non-positive.
- initCharWidths();
-}
-
-void SimpleFontData::platformDestroy()
-{
- if (!isCustomFont() && m_derivedFontData) {
- // These come from the cache.
- if (m_derivedFontData->smallCaps)
- fontCache()->releaseFontData(m_derivedFontData->smallCaps.get());
-
- if (m_derivedFontData->emphasisMark)
- fontCache()->releaseFontData(m_derivedFontData->emphasisMark.get());
- }
-}
-
-PassRefPtr<SimpleFontData> SimpleFontData::platformCreateScaledFontData(const FontDescription& fontDescription, float scaleFactor) const
-{
- if (isCustomFont()) {
- FontPlatformData scaledFontData(m_platformData);
- scaledFontData.m_size = scaledFontData.m_size * scaleFactor;
- return SimpleFontData::create(scaledFontData, true, false);
- }
-
- BEGIN_BLOCK_OBJC_EXCEPTIONS;
- float size = m_platformData.size() * scaleFactor;
- FontPlatformData scaledFontData([[NSFontManager sharedFontManager] convertFont:m_platformData.font() toSize:size], size, m_platformData.isPrinterFont(), false, false, m_platformData.orientation());
-
- // AppKit resets the type information (screen/printer) when you convert a font to a different size.
- // We have to fix up the font that we're handed back.
- scaledFontData.setFont(fontDescription.usePrinterFont() ? [scaledFontData.font() printerFont] : [scaledFontData.font() screenFont]);
-
- if (scaledFontData.font()) {
- NSFontManager *fontManager = [NSFontManager sharedFontManager];
- NSFontTraitMask fontTraits = [fontManager traitsOfFont:m_platformData.font()];
-
- if (m_platformData.m_syntheticBold)
- fontTraits |= NSBoldFontMask;
- if (m_platformData.m_syntheticOblique)
- fontTraits |= NSItalicFontMask;
-
- NSFontTraitMask scaledFontTraits = [fontManager traitsOfFont:scaledFontData.font()];
- scaledFontData.m_syntheticBold = (fontTraits & NSBoldFontMask) && !(scaledFontTraits & NSBoldFontMask);
- scaledFontData.m_syntheticOblique = (fontTraits & NSItalicFontMask) && !(scaledFontTraits & NSItalicFontMask);
-
- // SimpleFontData::platformDestroy() takes care of not deleting the cached font data twice.
- return fontCache()->getFontResourceData(&scaledFontData);
- }
- END_BLOCK_OBJC_EXCEPTIONS;
-
- return 0;
-}
-
-bool SimpleFontData::containsCharacters(const UChar* characters, int length) const
-{
- NSString *string = [[NSString alloc] initWithCharactersNoCopy:const_cast<unichar*>(characters) length:length freeWhenDone:NO];
- NSCharacterSet *set = [[m_platformData.font() coveredCharacterSet] invertedSet];
- bool result = set && [string rangeOfCharacterFromSet:set].location == NSNotFound;
- [string release];
- return result;
-}
-
-void SimpleFontData::determinePitch()
-{
- NSFont* f = m_platformData.font();
- // Special case Osaka-Mono.
- // According to <rdar://problem/3999467>, we should treat Osaka-Mono as fixed pitch.
- // Note that the AppKit does not report Osaka-Mono as fixed pitch.
-
- // Special case MS-PGothic.
- // According to <rdar://problem/4032938>, we should not treat MS-PGothic as fixed pitch.
- // Note that AppKit does report MS-PGothic as fixed pitch.
-
- // Special case MonotypeCorsiva
- // According to <rdar://problem/5454704>, we should not treat MonotypeCorsiva as fixed pitch.
- // Note that AppKit does report MonotypeCorsiva as fixed pitch.
-
- NSString *name = [f fontName];
- m_treatAsFixedPitch = ([f isFixedPitch] || [f _isFakeFixedPitch] ||
- [name caseInsensitiveCompare:@"Osaka-Mono"] == NSOrderedSame) &&
- [name caseInsensitiveCompare:@"MS-PGothic"] != NSOrderedSame &&
- [name caseInsensitiveCompare:@"MonotypeCorsiva"] != NSOrderedSame;
-}
-
-FloatRect SimpleFontData::platformBoundsForGlyph(Glyph glyph) const
-{
- FloatRect boundingBox;
- boundingBox = CTFontGetBoundingRectsForGlyphs(m_platformData.ctFont(), platformData().orientation() == Vertical ? kCTFontVerticalOrientation : kCTFontHorizontalOrientation, &glyph, 0, 1);
- boundingBox.setY(-boundingBox.maxY());
- if (m_syntheticBoldOffset)
- boundingBox.setWidth(boundingBox.width() + m_syntheticBoldOffset);
-
- return boundingBox;
-}
-
-float SimpleFontData::platformWidthForGlyph(Glyph glyph) const
-{
- CGSize advance = CGSizeZero;
- if (platformData().orientation() == Horizontal || m_isBrokenIdeographFallback) {
- NSFont *font = platformData().font();
- if (font && platformData().isColorBitmapFont())
- advance = NSSizeToCGSize([font advancementForGlyph:glyph]);
- else {
- float pointSize = platformData().m_size;
- CGAffineTransform m = CGAffineTransformMakeScale(pointSize, pointSize);
- if (!CGFontGetGlyphAdvancesForStyle(platformData().cgFont(), &m, cgFontRenderingModeForNSFont(font), &glyph, 1, &advance)) {
- LOG_ERROR("Unable to cache glyph widths for %@ %f", [font displayName], pointSize);
- advance.width = 0;
- }
- }
- } else
- CTFontGetAdvancesForGlyphs(m_platformData.ctFont(), kCTFontVerticalOrientation, &glyph, &advance, 1);
-
- return advance.width + m_syntheticBoldOffset;
-}
-
-struct ProviderInfo {
- const UChar* characters;
- size_t length;
- CFDictionaryRef attributes;
-};
-
-static const UniChar* provideStringAndAttributes(CFIndex stringIndex, CFIndex* count, CFDictionaryRef* attributes, void* context)
-{
- ProviderInfo* info = static_cast<struct ProviderInfo*>(context);
- if (stringIndex < 0 || static_cast<size_t>(stringIndex) >= info->length)
- return 0;
-
- *count = info->length - stringIndex;
- *attributes = info->attributes;
- return info->characters + stringIndex;
-}
-
-bool SimpleFontData::canRenderCombiningCharacterSequence(const UChar* characters, size_t length) const
-{
- ASSERT(isMainThread());
-
- if (!m_combiningCharacterSequenceSupport)
- m_combiningCharacterSequenceSupport = adoptPtr(new HashMap<String, bool>);
-
- WTF::HashMap<String, bool>::AddResult addResult = m_combiningCharacterSequenceSupport->add(String(characters, length), false);
- if (!addResult.isNewEntry)
- return addResult.iterator->value;
-
- RetainPtr<CGFontRef> cgFont(AdoptCF, CTFontCopyGraphicsFont(platformData().ctFont(), 0));
-
- ProviderInfo info = { characters, length, getCFStringAttributes(0, platformData().orientation()) };
- RetainPtr<CTLineRef> line(AdoptCF, CTLineCreateWithUniCharProvider(&provideStringAndAttributes, 0, &info));
-
- CFArrayRef runArray = CTLineGetGlyphRuns(line.get());
- CFIndex runCount = CFArrayGetCount(runArray);
-
- for (CFIndex r = 0; r < runCount; r++) {
- CTRunRef ctRun = static_cast<CTRunRef>(CFArrayGetValueAtIndex(runArray, r));
- ASSERT(CFGetTypeID(ctRun) == CTRunGetTypeID());
- CFDictionaryRef runAttributes = CTRunGetAttributes(ctRun);
- CTFontRef runFont = static_cast<CTFontRef>(CFDictionaryGetValue(runAttributes, kCTFontAttributeName));
- RetainPtr<CGFontRef> runCGFont(AdoptCF, CTFontCopyGraphicsFont(runFont, 0));
- if (!CFEqual(runCGFont.get(), cgFont.get()))
- return false;
- }
-
- addResult.iterator->value = true;
- return true;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/opentype/OpenTypeSanitizer.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/opentype/OpenTypeSanitizer.cpp
deleted file mode 100644
index 20d4442177f..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/opentype/OpenTypeSanitizer.cpp
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * Copyright (C) 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/opentype/OpenTypeSanitizer.h"
-
-#include "RuntimeEnabledFeatures.h"
-#include "core/platform/SharedBuffer.h"
-#include "opentype-sanitiser.h"
-#include "ots-memory-stream.h"
-#include "wtf/OwnArrayPtr.h"
-
-namespace WebCore {
-
-PassRefPtr<SharedBuffer> OpenTypeSanitizer::sanitize()
-{
- if (!m_buffer)
- return 0;
-
- // This is the largest web font size which we'll try to transcode.
- static const size_t maxWebFontSize = 30 * 1024 * 1024; // 30 MB
- if (m_buffer->size() > maxWebFontSize)
- return 0;
-
- if (RuntimeEnabledFeatures::woff2Enabled())
- ots::EnableWOFF2();
-
- // A transcoded font is usually smaller than an original font.
- // However, it can be slightly bigger than the original one due to
- // name table replacement and/or padding for glyf table.
- //
- // With WOFF fonts, however, we'll be decompressing, so the result can be
- // much larger than the original.
-
- ots::ExpandingMemoryStream output(m_buffer->size(), maxWebFontSize);
- if (!ots::Process(&output, reinterpret_cast<const uint8_t*>(m_buffer->data()), m_buffer->size()))
- return 0;
-
- const size_t transcodeLen = output.Tell();
- return SharedBuffer::create(static_cast<unsigned char*>(output.get()), transcodeLen);
-}
-
-bool OpenTypeSanitizer::supportsFormat(const String& format)
-{
- return equalIgnoringCase(format, "woff")
- || (RuntimeEnabledFeatures::woff2Enabled() && equalIgnoringCase(format, "woff2"));
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/opentype/OpenTypeSanitizer.h b/chromium/third_party/WebKit/Source/core/platform/graphics/opentype/OpenTypeSanitizer.h
deleted file mode 100644
index 90daf028f17..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/opentype/OpenTypeSanitizer.h
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Copyright (C) 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef OpenTypeSanitizer_h
-#define OpenTypeSanitizer_h
-
-#include "wtf/Forward.h"
-
-namespace WebCore {
-
-class SharedBuffer;
-
-class OpenTypeSanitizer {
-public:
- explicit OpenTypeSanitizer(SharedBuffer* buffer)
- : m_buffer(buffer)
- {
- }
-
- PassRefPtr<SharedBuffer> sanitize();
-
- static bool supportsFormat(const String&);
-
-private:
- SharedBuffer* const m_buffer;
-};
-
-} // namespace WebCore
-
-#endif // OpenTypeSanitizer_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/opentype/OpenTypeTypes.h b/chromium/third_party/WebKit/Source/core/platform/graphics/opentype/OpenTypeTypes.h
deleted file mode 100644
index c4a945bbe8b..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/opentype/OpenTypeTypes.h
+++ /dev/null
@@ -1,101 +0,0 @@
-/*
- * Copyright (C) 2012 Koji Ishii <kojiishi@gmail.com>
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef OpenTypeTypes_h
-#define OpenTypeTypes_h
-
-#include "core/platform/SharedBuffer.h"
-#include "wtf/ByteOrder.h"
-
-namespace WebCore {
-namespace OpenType {
-
-struct Int16 {
- Int16(int16_t u) : v(htons(static_cast<uint16_t>(u))) { }
- operator int16_t() const { return static_cast<int16_t>(ntohs(v)); }
- uint16_t v; // in BigEndian
-};
-
-struct UInt16 {
- UInt16(uint16_t u) : v(htons(u)) { }
- operator uint16_t() const { return ntohs(v); }
- uint16_t v; // in BigEndian
-};
-
-struct Int32 {
- Int32(int32_t u) : v(htonl(static_cast<uint32_t>(u))) { }
- operator int32_t() const { return static_cast<int32_t>(ntohl(v)); }
- uint32_t v; // in BigEndian
-};
-
-struct UInt32 {
- UInt32(uint32_t u) : v(htonl(u)) { }
- operator uint32_t() const { return ntohl(v); }
- uint32_t v; // in BigEndian
-};
-
-typedef UInt32 Fixed;
-typedef UInt16 Offset;
-typedef UInt16 GlyphID;
-
-// OTTag is native because it's only compared against constants, so we don't
-// do endian conversion here but make sure constants are in big-endian order.
-// Note that multi-character literal is implementation-defined in C++0x.
-typedef uint32_t Tag;
-#define OT_MAKE_TAG(ch1, ch2, ch3, ch4) ((((uint32_t)(ch4)) << 24) | (((uint32_t)(ch3)) << 16) | (((uint32_t)(ch2)) << 8) | ((uint32_t)(ch1)))
-
-template <typename T> static const T* validateTable(const RefPtr<SharedBuffer>& buffer, size_t count = 1)
-{
- if (!buffer || buffer->size() < sizeof(T) * count)
- return 0;
- return reinterpret_cast<const T*>(buffer->data());
-}
-
-struct TableBase {
-protected:
- static bool isValidEnd(const SharedBuffer& buffer, const void* position)
- {
- if (position < buffer.data())
- return false;
- size_t offset = reinterpret_cast<const char*>(position) - buffer.data();
- return offset <= buffer.size(); // "<=" because end is included as valid
- }
-
- template <typename T> static const T* validatePtr(const SharedBuffer& buffer, const void* position)
- {
- const T* casted = reinterpret_cast<const T*>(position);
- if (!isValidEnd(buffer, &casted[1]))
- return 0;
- return casted;
- }
-
- template <typename T> const T* validateOffset(const SharedBuffer& buffer, uint16_t offset) const
- {
- return validatePtr<T>(buffer, reinterpret_cast<const int8_t*>(this) + offset);
- }
-};
-
-} // namespace OpenType
-} // namespace WebCore
-#endif // OpenTypeTypes_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/opentype/OpenTypeUtilities.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/opentype/OpenTypeUtilities.cpp
deleted file mode 100644
index f16410d409e..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/opentype/OpenTypeUtilities.cpp
+++ /dev/null
@@ -1,224 +0,0 @@
-/*
- * Copyright (C) 2008, 2009 Apple Inc. All rights reserved.
- * Copyright (C) 2009 Torch Mobile, Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/opentype/OpenTypeUtilities.h"
-
-#include "core/platform/SharedBuffer.h"
-
-namespace WebCore {
-
-struct BigEndianUShort {
- operator unsigned short() const { return (v & 0x00ff) << 8 | v >> 8; }
- BigEndianUShort(unsigned short u) : v((u & 0x00ff) << 8 | u >> 8) { }
- unsigned short v;
-};
-
-struct BigEndianULong {
- operator unsigned() const { return (v & 0xff) << 24 | (v & 0xff00) << 8 | (v & 0xff0000) >> 8 | v >> 24; }
- BigEndianULong(unsigned u) : v((u & 0xff) << 24 | (u & 0xff00) << 8 | (u & 0xff0000) >> 8 | u >> 24) { }
- unsigned v;
-};
-
-#pragma pack(1)
-
-struct TableDirectoryEntry {
- BigEndianULong tag;
- BigEndianULong checkSum;
- BigEndianULong offset;
- BigEndianULong length;
-};
-
-// Fixed type is not defined on non-CG and Windows platforms. |version| in sfntHeader
-// and headTable and |fontRevision| in headTable are of Fixed, but they're
-// not actually refered to anywhere. Therefore, we just have to match
-// the size (4 bytes). For the definition of Fixed type, see
-// http://developer.apple.com/documentation/mac/Legacy/GXEnvironment/GXEnvironment-356.html#HEADING356-6.
-typedef int32_t Fixed;
-
-struct sfntHeader {
- Fixed version;
- BigEndianUShort numTables;
- BigEndianUShort searchRange;
- BigEndianUShort entrySelector;
- BigEndianUShort rangeShift;
- TableDirectoryEntry tables[1];
-};
-
-struct OS2Table {
- BigEndianUShort version;
- BigEndianUShort avgCharWidth;
- BigEndianUShort weightClass;
- BigEndianUShort widthClass;
- BigEndianUShort fsType;
- BigEndianUShort subscriptXSize;
- BigEndianUShort subscriptYSize;
- BigEndianUShort subscriptXOffset;
- BigEndianUShort subscriptYOffset;
- BigEndianUShort superscriptXSize;
- BigEndianUShort superscriptYSize;
- BigEndianUShort superscriptXOffset;
- BigEndianUShort superscriptYOffset;
- BigEndianUShort strikeoutSize;
- BigEndianUShort strikeoutPosition;
- BigEndianUShort familyClass;
- uint8_t panose[10];
- BigEndianULong unicodeRange[4];
- uint8_t vendID[4];
- BigEndianUShort fsSelection;
- BigEndianUShort firstCharIndex;
- BigEndianUShort lastCharIndex;
- BigEndianUShort typoAscender;
- BigEndianUShort typoDescender;
- BigEndianUShort typoLineGap;
- BigEndianUShort winAscent;
- BigEndianUShort winDescent;
- BigEndianULong codePageRange[2];
- BigEndianUShort xHeight;
- BigEndianUShort capHeight;
- BigEndianUShort defaultChar;
- BigEndianUShort breakChar;
- BigEndianUShort maxContext;
-};
-
-struct headTable {
- Fixed version;
- Fixed fontRevision;
- BigEndianULong checkSumAdjustment;
- BigEndianULong magicNumber;
- BigEndianUShort flags;
- BigEndianUShort unitsPerEm;
- long long created;
- long long modified;
- BigEndianUShort xMin;
- BigEndianUShort xMax;
- BigEndianUShort yMin;
- BigEndianUShort yMax;
- BigEndianUShort macStyle;
- BigEndianUShort lowestRectPPEM;
- BigEndianUShort fontDirectionHint;
- BigEndianUShort indexToLocFormat;
- BigEndianUShort glyphDataFormat;
-};
-
-struct nameRecord {
- BigEndianUShort platformID;
- BigEndianUShort encodingID;
- BigEndianUShort languageID;
- BigEndianUShort nameID;
- BigEndianUShort length;
- BigEndianUShort offset;
-};
-
-struct nameTable {
- BigEndianUShort format;
- BigEndianUShort count;
- BigEndianUShort stringOffset;
- nameRecord nameRecords[1];
-};
-
-#pragma pack()
-
-// adds fontName to the font table in fontData, and writes the new font table to rewrittenFontTable
-// returns the size of the name table (which is used by renameAndActivateFont), or 0 on early abort
-static size_t renameFont(SharedBuffer* fontData, const String& fontName, Vector<char> &rewrittenFontData)
-{
- size_t originalDataSize = fontData->size();
- const sfntHeader* sfnt = reinterpret_cast<const sfntHeader*>(fontData->data());
-
- unsigned t;
- for (t = 0; t < sfnt->numTables; ++t) {
- if (sfnt->tables[t].tag == 'name')
- break;
- }
- if (t == sfnt->numTables)
- return 0;
-
- const int nameRecordCount = 5;
-
- // Rounded up to a multiple of 4 to simplify the checksum calculation.
- size_t nameTableSize = ((offsetof(nameTable, nameRecords) + nameRecordCount * sizeof(nameRecord) + fontName.length() * sizeof(UChar)) & ~3) + 4;
-
- rewrittenFontData.resize(fontData->size() + nameTableSize);
- char* data = rewrittenFontData.data();
- memcpy(data, fontData->data(), originalDataSize);
-
- // Make the table directory entry point to the new 'name' table.
- sfntHeader* rewrittenSfnt = reinterpret_cast<sfntHeader*>(data);
- rewrittenSfnt->tables[t].length = nameTableSize;
- rewrittenSfnt->tables[t].offset = originalDataSize;
-
- // Write the new 'name' table after the original font data.
- nameTable* name = reinterpret_cast<nameTable*>(data + originalDataSize);
- name->format = 0;
- name->count = nameRecordCount;
- name->stringOffset = offsetof(nameTable, nameRecords) + nameRecordCount * sizeof(nameRecord);
- for (unsigned i = 0; i < nameRecordCount; ++i) {
- name->nameRecords[i].platformID = 3;
- name->nameRecords[i].encodingID = 1;
- name->nameRecords[i].languageID = 0x0409;
- name->nameRecords[i].offset = 0;
- name->nameRecords[i].length = fontName.length() * sizeof(UChar);
- }
-
- // The required 'name' record types: Family, Style, Unique, Full and PostScript.
- name->nameRecords[0].nameID = 1;
- name->nameRecords[1].nameID = 2;
- name->nameRecords[2].nameID = 3;
- name->nameRecords[3].nameID = 4;
- name->nameRecords[4].nameID = 6;
-
- for (unsigned i = 0; i < fontName.length(); ++i)
- reinterpret_cast<BigEndianUShort*>(data + originalDataSize + name->stringOffset)[i] = fontName[i];
-
- // Update the table checksum in the directory entry.
- rewrittenSfnt->tables[t].checkSum = 0;
- for (unsigned i = 0; i * sizeof(BigEndianULong) < nameTableSize; ++i)
- rewrittenSfnt->tables[t].checkSum = rewrittenSfnt->tables[t].checkSum + reinterpret_cast<BigEndianULong*>(name)[i];
-
- return nameTableSize;
-}
-
-// Rename the font and install the new font data into the system
-HANDLE renameAndActivateFont(SharedBuffer* fontData, const String& fontName)
-{
- Vector<char> rewrittenFontData;
- size_t nameTableSize = renameFont(fontData, fontName, rewrittenFontData);
- if (!nameTableSize)
- return 0;
-
- DWORD numFonts = 0;
- HANDLE fontHandle = AddFontMemResourceEx(rewrittenFontData.data(), fontData->size() + nameTableSize, 0, &numFonts);
-
- if (fontHandle && numFonts < 1) {
- RemoveFontMemResourceEx(fontHandle);
- return 0;
- }
-
- return fontHandle;
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/opentype/OpenTypeUtilities.h b/chromium/third_party/WebKit/Source/core/platform/graphics/opentype/OpenTypeUtilities.h
deleted file mode 100644
index 0bb69f98a0b..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/opentype/OpenTypeUtilities.h
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright (C) 2008, 2009 Apple Inc. All rights reserved.
- * Copyright (C) 2009 Torch Mobile, Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef OpenTypeUtilities_h
-#define OpenTypeUtilities_h
-
-#include <windows.h>
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class SharedBuffer;
-
-HANDLE renameAndActivateFont(SharedBuffer*, const String&);
-
-} // namespace WebCore
-
-#endif // OpenTypeUtilities_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/opentype/OpenTypeVerticalData.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/opentype/OpenTypeVerticalData.cpp
deleted file mode 100644
index d60fbd7063a..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/opentype/OpenTypeVerticalData.cpp
+++ /dev/null
@@ -1,574 +0,0 @@
-/*
- * Copyright (C) 2012 Koji Ishii <kojiishi@gmail.com>
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#if ENABLE(OPENTYPE_VERTICAL)
-#include "core/platform/graphics/opentype/OpenTypeVerticalData.h"
-
-#include "core/platform/SharedBuffer.h"
-#include "core/platform/graphics/FloatRect.h"
-#include "core/platform/graphics/GlyphPage.h"
-#include "core/platform/graphics/SimpleFontData.h"
-#include "core/platform/graphics/opentype/OpenTypeTypes.h"
-#include "wtf/RefPtr.h"
-
-using namespace std;
-
-namespace WebCore {
-namespace OpenType {
-
-const uint32_t GSUBTag = OT_MAKE_TAG('G', 'S', 'U', 'B');
-const uint32_t HheaTag = OT_MAKE_TAG('h', 'h', 'e', 'a');
-const uint32_t HmtxTag = OT_MAKE_TAG('h', 'm', 't', 'x');
-const uint32_t VheaTag = OT_MAKE_TAG('v', 'h', 'e', 'a');
-const uint32_t VmtxTag = OT_MAKE_TAG('v', 'm', 't', 'x');
-const uint32_t VORGTag = OT_MAKE_TAG('V', 'O', 'R', 'G');
-
-const uint32_t DefaultScriptTag = OT_MAKE_TAG('D', 'F', 'L', 'T');
-
-const uint32_t VertFeatureTag = OT_MAKE_TAG('v', 'e', 'r', 't');
-
-#pragma pack(1)
-
-struct HheaTable {
- OpenType::Fixed version;
- OpenType::Int16 ascender;
- OpenType::Int16 descender;
- OpenType::Int16 lineGap;
- OpenType::Int16 advanceWidthMax;
- OpenType::Int16 minLeftSideBearing;
- OpenType::Int16 minRightSideBearing;
- OpenType::Int16 xMaxExtent;
- OpenType::Int16 caretSlopeRise;
- OpenType::Int16 caretSlopeRun;
- OpenType::Int16 caretOffset;
- OpenType::Int16 reserved[4];
- OpenType::Int16 metricDataFormat;
- OpenType::UInt16 numberOfHMetrics;
-};
-
-struct VheaTable {
- OpenType::Fixed version;
- OpenType::Int16 ascent;
- OpenType::Int16 descent;
- OpenType::Int16 lineGap;
- OpenType::Int16 advanceHeightMax;
- OpenType::Int16 minTopSideBearing;
- OpenType::Int16 minBottomSideBearing;
- OpenType::Int16 yMaxExtent;
- OpenType::Int16 caretSlopeRise;
- OpenType::Int16 caretSlopeRun;
- OpenType::Int16 caretOffset;
- OpenType::Int16 reserved[4];
- OpenType::Int16 metricDataFormat;
- OpenType::UInt16 numOfLongVerMetrics;
-};
-
-struct HmtxTable {
- struct Entry {
- OpenType::UInt16 advanceWidth;
- OpenType::Int16 lsb;
- } entries[1];
-};
-
-struct VmtxTable {
- struct Entry {
- OpenType::UInt16 advanceHeight;
- OpenType::Int16 topSideBearing;
- } entries[1];
-};
-
-struct VORGTable {
- OpenType::UInt16 majorVersion;
- OpenType::UInt16 minorVersion;
- OpenType::Int16 defaultVertOriginY;
- OpenType::UInt16 numVertOriginYMetrics;
- struct VertOriginYMetrics {
- OpenType::UInt16 glyphIndex;
- OpenType::Int16 vertOriginY;
- } vertOriginYMetrics[1];
-
- size_t requiredSize() const { return sizeof(*this) + sizeof(VertOriginYMetrics) * (numVertOriginYMetrics - 1); }
-};
-
-struct CoverageTable : TableBase {
- OpenType::UInt16 coverageFormat;
-};
-
-struct Coverage1Table : CoverageTable {
- OpenType::UInt16 glyphCount;
- OpenType::GlyphID glyphArray[1];
-};
-
-struct Coverage2Table : CoverageTable {
- OpenType::UInt16 rangeCount;
- struct RangeRecord {
- OpenType::GlyphID start;
- OpenType::GlyphID end;
- OpenType::UInt16 startCoverageIndex;
- } ranges[1];
-};
-
-struct SubstitutionSubTable : TableBase {
- OpenType::UInt16 substFormat;
- OpenType::Offset coverageOffset;
-
- const CoverageTable* coverage(const SharedBuffer& buffer) const { return validateOffset<CoverageTable>(buffer, coverageOffset); }
-};
-
-struct SingleSubstitution2SubTable : SubstitutionSubTable {
- OpenType::UInt16 glyphCount;
- OpenType::GlyphID substitute[1];
-};
-
-struct LookupTable : TableBase {
- OpenType::UInt16 lookupType;
- OpenType::UInt16 lookupFlag;
- OpenType::UInt16 subTableCount;
- OpenType::Offset subTableOffsets[1];
- // OpenType::UInt16 markFilteringSet; this field comes after variable length, so offset is determined dynamically.
-
- bool getSubstitutions(HashMap<Glyph, Glyph>* map, const SharedBuffer& buffer) const
- {
- uint16_t countSubTable = subTableCount;
- if (!isValidEnd(buffer, &subTableOffsets[countSubTable]))
- return false;
- if (lookupType != 1) // "Single Substitution Subtable" is all what we support
- return false;
- for (uint16_t i = 0; i < countSubTable; ++i) {
- const SubstitutionSubTable* substitution = validateOffset<SubstitutionSubTable>(buffer, subTableOffsets[i]);
- if (!substitution)
- return false;
- const CoverageTable* coverage = substitution->coverage(buffer);
- if (!coverage)
- return false;
- if (substitution->substFormat != 2) // "Single Substitution Format 2" is all what we support
- return false;
- const SingleSubstitution2SubTable* singleSubstitution2 = validatePtr<SingleSubstitution2SubTable>(buffer, substitution);
- if (!singleSubstitution2)
- return false;
- uint16_t countTo = singleSubstitution2->glyphCount;
- if (!isValidEnd(buffer, &singleSubstitution2->substitute[countTo]))
- return false;
- switch (coverage->coverageFormat) {
- case 1: { // Coverage Format 1 (e.g., MS Gothic)
- const Coverage1Table* coverage1 = validatePtr<Coverage1Table>(buffer, coverage);
- if (!coverage1)
- return false;
- uint16_t countFrom = coverage1->glyphCount;
- if (!isValidEnd(buffer, &coverage1->glyphArray[countFrom]) || countTo != countFrom)
- return false;
- for (uint16_t i = 0; i < countTo; ++i)
- map->set(coverage1->glyphArray[i], singleSubstitution2->substitute[i]);
- break;
- }
- case 2: { // Coverage Format 2 (e.g., Adobe Kozuka Gothic)
- const Coverage2Table* coverage2 = validatePtr<Coverage2Table>(buffer, coverage);
- if (!coverage2)
- return false;
- uint16_t countRange = coverage2->rangeCount;
- if (!isValidEnd(buffer, &coverage2->ranges[countRange]))
- return false;
- for (uint16_t i = 0, indexTo = 0; i < countRange; ++i) {
- uint16_t from = coverage2->ranges[i].start;
- uint16_t fromEnd = coverage2->ranges[i].end + 1; // OpenType "end" is inclusive
- if (indexTo + (fromEnd - from) > countTo)
- return false;
- for (; from != fromEnd; ++from, ++indexTo)
- map->set(from, singleSubstitution2->substitute[indexTo]);
- }
- break;
- }
- default:
- return false;
- }
- }
- return true;
- }
-};
-
-struct LookupList : TableBase {
- OpenType::UInt16 lookupCount;
- OpenType::Offset lookupOffsets[1];
-
- const LookupTable* lookup(uint16_t index, const SharedBuffer& buffer) const
- {
- uint16_t count = lookupCount;
- if (index >= count || !isValidEnd(buffer, &lookupOffsets[count]))
- return 0;
- return validateOffset<LookupTable>(buffer, lookupOffsets[index]);
- }
-};
-
-struct FeatureTable : TableBase {
- OpenType::Offset featureParams;
- OpenType::UInt16 lookupCount;
- OpenType::UInt16 lookupListIndex[1];
-
- bool getGlyphSubstitutions(const LookupList* lookups, HashMap<Glyph, Glyph>* map, const SharedBuffer& buffer) const
- {
- uint16_t count = lookupCount;
- if (!isValidEnd(buffer, &lookupListIndex[count]))
- return false;
- for (uint16_t i = 0; i < count; ++i) {
- const LookupTable* lookup = lookups->lookup(lookupListIndex[i], buffer);
- if (!lookup || !lookup->getSubstitutions(map, buffer))
- return false;
- }
- return true;
- }
-};
-
-struct FeatureList : TableBase {
- OpenType::UInt16 featureCount;
- struct FeatureRecord {
- OpenType::Tag featureTag;
- OpenType::Offset featureOffset;
- } features[1];
-
- const FeatureTable* feature(uint16_t index, OpenType::Tag tag, const SharedBuffer& buffer) const
- {
- uint16_t count = featureCount;
- if (index >= count || !isValidEnd(buffer, &features[count]))
- return 0;
- if (features[index].featureTag == tag)
- return validateOffset<FeatureTable>(buffer, features[index].featureOffset);
- return 0;
- }
-
- const FeatureTable* findFeature(OpenType::Tag tag, const SharedBuffer& buffer) const
- {
- for (uint16_t i = 0; i < featureCount; ++i) {
- if (isValidEnd(buffer, &features[i]) && features[i].featureTag == tag)
- return validateOffset<FeatureTable>(buffer, features[i].featureOffset);
- }
- return 0;
- }
-};
-
-struct LangSysTable : TableBase {
- OpenType::Offset lookupOrder;
- OpenType::UInt16 reqFeatureIndex;
- OpenType::UInt16 featureCount;
- OpenType::UInt16 featureIndex[1];
-
- const FeatureTable* feature(OpenType::Tag featureTag, const FeatureList* features, const SharedBuffer& buffer) const
- {
- uint16_t count = featureCount;
- if (!isValidEnd(buffer, &featureIndex[count]))
- return 0;
- for (uint16_t i = 0; i < count; ++i) {
- const FeatureTable* featureTable = features->feature(featureIndex[i], featureTag, buffer);
- if (featureTable)
- return featureTable;
- }
- return 0;
- }
-};
-
-struct ScriptTable : TableBase {
- OpenType::Offset defaultLangSysOffset;
- OpenType::UInt16 langSysCount;
- struct LangSysRecord {
- OpenType::Tag langSysTag;
- OpenType::Offset langSysOffset;
- } langSysRecords[1];
-
- const LangSysTable* defaultLangSys(const SharedBuffer& buffer) const
- {
- uint16_t count = langSysCount;
- if (!isValidEnd(buffer, &langSysRecords[count]))
- return 0;
- uint16_t offset = defaultLangSysOffset;
- if (offset)
- return validateOffset<LangSysTable>(buffer, offset);
- if (count)
- return validateOffset<LangSysTable>(buffer, langSysRecords[0].langSysOffset);
- return 0;
- }
-};
-
-struct ScriptList : TableBase {
- OpenType::UInt16 scriptCount;
- struct ScriptRecord {
- OpenType::Tag scriptTag;
- OpenType::Offset scriptOffset;
- } scripts[1];
-
- const ScriptTable* script(OpenType::Tag tag, const SharedBuffer& buffer) const
- {
- uint16_t count = scriptCount;
- if (!isValidEnd(buffer, &scripts[count]))
- return 0;
- for (uint16_t i = 0; i < count; ++i) {
- if (scripts[i].scriptTag == tag)
- return validateOffset<ScriptTable>(buffer, scripts[i].scriptOffset);
- }
- return 0;
- }
-
- const ScriptTable* defaultScript(const SharedBuffer& buffer) const
- {
- uint16_t count = scriptCount;
- if (!count || !isValidEnd(buffer, &scripts[count]))
- return 0;
- const ScriptTable* scriptOfDefaultTag = script(OpenType::DefaultScriptTag, buffer);
- if (scriptOfDefaultTag)
- return scriptOfDefaultTag;
- return validateOffset<ScriptTable>(buffer, scripts[0].scriptOffset);
- }
-
- const LangSysTable* defaultLangSys(const SharedBuffer& buffer) const
- {
- const ScriptTable* scriptTable = defaultScript(buffer);
- if (!scriptTable)
- return 0;
- return scriptTable->defaultLangSys(buffer);
- }
-};
-
-struct GSUBTable : TableBase {
- OpenType::Fixed version;
- OpenType::Offset scriptListOffset;
- OpenType::Offset featureListOffset;
- OpenType::Offset lookupListOffset;
-
- const ScriptList* scriptList(const SharedBuffer& buffer) const { return validateOffset<ScriptList>(buffer, scriptListOffset); }
- const FeatureList* featureList(const SharedBuffer& buffer) const { return validateOffset<FeatureList>(buffer, featureListOffset); }
- const LookupList* lookupList(const SharedBuffer& buffer) const { return validateOffset<LookupList>(buffer, lookupListOffset); }
-
- const LangSysTable* defaultLangSys(const SharedBuffer& buffer) const
- {
- const ScriptList* scripts = scriptList(buffer);
- if (!scripts)
- return 0;
- return scripts->defaultLangSys(buffer);
- }
-
- const FeatureTable* feature(OpenType::Tag featureTag, const SharedBuffer& buffer) const
- {
- const LangSysTable* langSys = defaultLangSys(buffer);
- const FeatureList* features = featureList(buffer);
- if (!features)
- return 0;
- const FeatureTable* feature = 0;
- if (langSys)
- feature = langSys->feature(featureTag, features, buffer);
- if (!feature) {
- // If the font has no langSys table, or has no default script and the first script doesn't
- // have the requested feature, then use the first matching feature directly.
- feature = features->findFeature(featureTag, buffer);
- }
- return feature;
- }
-
- bool getVerticalGlyphSubstitutions(HashMap<Glyph, Glyph>* map, const SharedBuffer& buffer) const
- {
- const FeatureTable* verticalFeatureTable = feature(OpenType::VertFeatureTag, buffer);
- if (!verticalFeatureTable)
- return false;
- const LookupList* lookups = lookupList(buffer);
- return lookups && verticalFeatureTable->getGlyphSubstitutions(lookups, map, buffer);
- }
-};
-
-#pragma pack()
-
-} // namespace OpenType
-
-OpenTypeVerticalData::OpenTypeVerticalData(const FontPlatformData& platformData)
- : m_defaultVertOriginY(0)
-{
- loadMetrics(platformData);
- loadVerticalGlyphSubstitutions(platformData);
-}
-
-void OpenTypeVerticalData::loadMetrics(const FontPlatformData& platformData)
-{
- // Load hhea and hmtx to get x-component of vertical origins.
- // If these tables are missing, it's not an OpenType font.
- RefPtr<SharedBuffer> buffer = platformData.openTypeTable(OpenType::HheaTag);
- const OpenType::HheaTable* hhea = OpenType::validateTable<OpenType::HheaTable>(buffer);
- if (!hhea)
- return;
- uint16_t countHmtxEntries = hhea->numberOfHMetrics;
- if (!countHmtxEntries) {
- LOG_ERROR("Invalid numberOfHMetrics");
- return;
- }
-
- buffer = platformData.openTypeTable(OpenType::HmtxTag);
- const OpenType::HmtxTable* hmtx = OpenType::validateTable<OpenType::HmtxTable>(buffer, countHmtxEntries);
- if (!hmtx) {
- LOG_ERROR("hhea exists but hmtx does not (or broken)");
- return;
- }
- m_advanceWidths.resize(countHmtxEntries);
- for (uint16_t i = 0; i < countHmtxEntries; ++i)
- m_advanceWidths[i] = hmtx->entries[i].advanceWidth;
-
- // Load vhea first. This table is required for fonts that support vertical flow.
- buffer = platformData.openTypeTable(OpenType::VheaTag);
- const OpenType::VheaTable* vhea = OpenType::validateTable<OpenType::VheaTable>(buffer);
- if (!vhea)
- return;
- uint16_t countVmtxEntries = vhea->numOfLongVerMetrics;
- if (!countVmtxEntries) {
- LOG_ERROR("Invalid numOfLongVerMetrics");
- return;
- }
-
- // Load VORG. This table is optional.
- buffer = platformData.openTypeTable(OpenType::VORGTag);
- const OpenType::VORGTable* vorg = OpenType::validateTable<OpenType::VORGTable>(buffer);
- if (vorg && buffer->size() >= vorg->requiredSize()) {
- m_defaultVertOriginY = vorg->defaultVertOriginY;
- uint16_t countVertOriginYMetrics = vorg->numVertOriginYMetrics;
- if (!countVertOriginYMetrics) {
- // Add one entry so that hasVORG() becomes true
- m_vertOriginY.set(0, m_defaultVertOriginY);
- } else {
- for (uint16_t i = 0; i < countVertOriginYMetrics; ++i) {
- const OpenType::VORGTable::VertOriginYMetrics& metrics = vorg->vertOriginYMetrics[i];
- m_vertOriginY.set(metrics.glyphIndex, metrics.vertOriginY);
- }
- }
- }
-
- // Load vmtx then. This table is required for fonts that support vertical flow.
- buffer = platformData.openTypeTable(OpenType::VmtxTag);
- const OpenType::VmtxTable* vmtx = OpenType::validateTable<OpenType::VmtxTable>(buffer, countVmtxEntries);
- if (!vmtx) {
- LOG_ERROR("vhea exists but vmtx does not (or broken)");
- return;
- }
- m_advanceHeights.resize(countVmtxEntries);
- for (uint16_t i = 0; i < countVmtxEntries; ++i)
- m_advanceHeights[i] = vmtx->entries[i].advanceHeight;
-
- // VORG is preferred way to calculate vertical origin than vmtx,
- // so load topSideBearing from vmtx only if VORG is missing.
- if (hasVORG())
- return;
-
- size_t sizeExtra = buffer->size() - sizeof(OpenType::VmtxTable::Entry) * countVmtxEntries;
- if (sizeExtra % sizeof(OpenType::Int16)) {
- LOG_ERROR("vmtx has incorrect tsb count");
- return;
- }
- size_t countTopSideBearings = countVmtxEntries + sizeExtra / sizeof(OpenType::Int16);
- m_topSideBearings.resize(countTopSideBearings);
- size_t i;
- for (i = 0; i < countVmtxEntries; ++i)
- m_topSideBearings[i] = vmtx->entries[i].topSideBearing;
- if (i < countTopSideBearings) {
- const OpenType::Int16* pTopSideBearingsExtra = reinterpret_cast<const OpenType::Int16*>(&vmtx->entries[countVmtxEntries]);
- for (; i < countTopSideBearings; ++i, ++pTopSideBearingsExtra)
- m_topSideBearings[i] = *pTopSideBearingsExtra;
- }
-}
-
-void OpenTypeVerticalData::loadVerticalGlyphSubstitutions(const FontPlatformData& platformData)
-{
- RefPtr<SharedBuffer> buffer = platformData.openTypeTable(OpenType::GSUBTag);
- const OpenType::GSUBTable* gsub = OpenType::validateTable<OpenType::GSUBTable>(buffer);
- if (gsub)
- gsub->getVerticalGlyphSubstitutions(&m_verticalGlyphMap, *buffer.get());
-}
-
-float OpenTypeVerticalData::advanceHeight(const SimpleFontData* font, Glyph glyph) const
-{
- size_t countHeights = m_advanceHeights.size();
- if (countHeights) {
- uint16_t advanceFUnit = m_advanceHeights[glyph < countHeights ? glyph : countHeights - 1];
- float advance = advanceFUnit * font->sizePerUnit();
- return advance;
- }
-
- // No vertical info in the font file; use height as advance.
- return font->fontMetrics().height();
-}
-
-void OpenTypeVerticalData::getVerticalTranslationsForGlyphs(const SimpleFontData* font, const Glyph* glyphs, size_t count, float* outXYArray) const
-{
- size_t countWidths = m_advanceWidths.size();
- ASSERT(countWidths > 0);
- const FontMetrics& metrics = font->fontMetrics();
- float sizePerUnit = font->sizePerUnit();
- float ascent = metrics.ascent();
- bool useVORG = hasVORG();
- size_t countTopSideBearings = m_topSideBearings.size();
- float defaultVertOriginY = std::numeric_limits<float>::quiet_NaN();
- for (float* end = &(outXYArray[count * 2]); outXYArray != end; ++glyphs, outXYArray += 2) {
- Glyph glyph = *glyphs;
- uint16_t widthFUnit = m_advanceWidths[glyph < countWidths ? glyph : countWidths - 1];
- float width = widthFUnit * sizePerUnit;
- outXYArray[0] = -width / 2;
-
- // For Y, try VORG first.
- if (useVORG) {
- int16_t vertOriginYFUnit = m_vertOriginY.get(glyph);
- if (vertOriginYFUnit) {
- outXYArray[1] = -vertOriginYFUnit * sizePerUnit;
- continue;
- }
- if (std::isnan(defaultVertOriginY))
- defaultVertOriginY = -m_defaultVertOriginY * sizePerUnit;
- outXYArray[1] = defaultVertOriginY;
- continue;
- }
-
- // If no VORG, try vmtx next.
- if (countTopSideBearings) {
- int16_t topSideBearingFUnit = m_topSideBearings[glyph < countTopSideBearings ? glyph : countTopSideBearings - 1];
- float topSideBearing = topSideBearingFUnit * sizePerUnit;
- FloatRect bounds = font->boundsForGlyph(glyph);
- outXYArray[1] = bounds.y() - topSideBearing;
- continue;
- }
-
- // No vertical info in the font file; use ascent as vertical origin.
- outXYArray[1] = -ascent;
- }
-}
-
-void OpenTypeVerticalData::substituteWithVerticalGlyphs(const SimpleFontData* font, GlyphPage* glyphPage, unsigned offset, unsigned length) const
-{
- const HashMap<Glyph, Glyph>& map = m_verticalGlyphMap;
- if (map.isEmpty())
- return;
-
- for (unsigned index = offset, end = offset + length; index < end; ++index) {
- Glyph glyph = glyphPage->glyphAt(index);
- if (glyph) {
- ASSERT(glyphPage->glyphDataForIndex(index).fontData == font);
- Glyph to = map.get(glyph);
- if (to)
- glyphPage->setGlyphDataForIndex(index, to, font);
- }
- }
-}
-
-} // namespace WebCore
-#endif // ENABLE(OPENTYPE_VERTICAL)
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/opentype/OpenTypeVerticalData.h b/chromium/third_party/WebKit/Source/core/platform/graphics/opentype/OpenTypeVerticalData.h
deleted file mode 100644
index bad593edc3d..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/opentype/OpenTypeVerticalData.h
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * Copyright (C) 2012 Koji Ishii <kojiishi@gmail.com>
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef OpenTypeVerticalData_h
-#define OpenTypeVerticalData_h
-
-#if ENABLE(OPENTYPE_VERTICAL)
-
-#include "core/platform/graphics/Glyph.h"
-#include "wtf/HashMap.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-class FontPlatformData;
-class GlyphPage;
-class SimpleFontData;
-
-class OpenTypeVerticalData : public RefCounted<OpenTypeVerticalData> {
-public:
- static PassRefPtr<OpenTypeVerticalData> create(const FontPlatformData& platformData)
- {
- return adoptRef(new OpenTypeVerticalData(platformData));
- }
-
- bool isOpenType() const { return !m_advanceWidths.isEmpty(); }
- bool hasVerticalMetrics() const { return !m_advanceHeights.isEmpty(); }
- float advanceHeight(const SimpleFontData*, Glyph) const;
- void getVerticalTranslationsForGlyphs(const SimpleFontData*, const Glyph*, size_t, float* outXYArray) const;
- void substituteWithVerticalGlyphs(const SimpleFontData*, GlyphPage*, unsigned offset, unsigned length) const;
-
-private:
- explicit OpenTypeVerticalData(const FontPlatformData&);
-
- void loadMetrics(const FontPlatformData&);
- void loadVerticalGlyphSubstitutions(const FontPlatformData&);
- bool hasVORG() const { return !m_vertOriginY.isEmpty(); }
-
- HashMap<Glyph, Glyph> m_verticalGlyphMap;
- Vector<uint16_t> m_advanceWidths;
- Vector<uint16_t> m_advanceHeights;
- Vector<int16_t> m_topSideBearings;
- int16_t m_defaultVertOriginY;
- HashMap<Glyph, int16_t> m_vertOriginY;
-
- friend class FontCache;
- bool m_inFontCache; // for mark & sweep in FontCache::purgeInactiveFontData()
-};
-
-} // namespace WebCore
-
-#endif // ENABLE(OPENTYPE_VERTICAL)
-
-#endif // OpenTypeVerticalData_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/skia/FontCacheSkia.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/skia/FontCacheSkia.cpp
deleted file mode 100644
index 958b60d1aca..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/skia/FontCacheSkia.cpp
+++ /dev/null
@@ -1,179 +0,0 @@
-/*
- * Copyright (c) 2006, 2007, 2008, 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "SkFontMgr.h"
-#include "SkTypeface.h"
-#include "core/platform/NotImplemented.h"
-#include "core/platform/graphics/Font.h"
-#include "core/platform/graphics/FontCache.h"
-#include "core/platform/graphics/FontDescription.h"
-#include "core/platform/graphics/SimpleFontData.h"
-#include "wtf/Assertions.h"
-#include "wtf/text/AtomicString.h"
-#include "wtf/text/CString.h"
-#include <unicode/locid.h>
-
-namespace WebCore {
-
-void FontCache::platformInit()
-{
-}
-
-#if !OS(WIN) && !OS(ANDROID)
-PassRefPtr<SimpleFontData> FontCache::getFontDataForCharacter(const Font& font, UChar32 c)
-{
- icu::Locale locale = icu::Locale::getDefault();
- FontCache::SimpleFontFamily family;
- FontCache::getFontFamilyForCharacter(c, locale.getLanguage(), &family);
- if (family.name.isEmpty())
- return 0;
-
- AtomicString atomicFamily(family.name);
- // Changes weight and/or italic of given FontDescription depends on
- // the result of fontconfig so that keeping the correct font mapping
- // of the given character. See http://crbug.com/32109 for details.
- bool shouldSetFakeBold = false;
- bool shouldSetFakeItalic = false;
- FontDescription description(font.fontDescription());
- if (family.isBold && description.weight() < FontWeightBold)
- description.setWeight(FontWeightBold);
- if (!family.isBold && description.weight() >= FontWeightBold) {
- shouldSetFakeBold = true;
- description.setWeight(FontWeightNormal);
- }
- if (family.isItalic && description.italic() == FontItalicOff)
- description.setItalic(FontItalicOn);
- if (!family.isItalic && description.italic() == FontItalicOn) {
- shouldSetFakeItalic = true;
- description.setItalic(FontItalicOff);
- }
-
- FontPlatformData* substitutePlatformData = getFontResourcePlatformData(description, atomicFamily, DoNotRetain);
- if (!substitutePlatformData)
- return 0;
- FontPlatformData platformData = FontPlatformData(*substitutePlatformData);
- platformData.setFakeBold(shouldSetFakeBold);
- platformData.setFakeItalic(shouldSetFakeItalic);
- return getFontResourceData(&platformData, DoNotRetain);
-}
-
-#endif // !OS(WINDOWNS) && !OS(ANDROID)
-
-PassRefPtr<SimpleFontData> FontCache::getSimilarFontPlatformData(const Font& font)
-{
- return 0;
-}
-
-PassRefPtr<SimpleFontData> FontCache::getLastResortFallbackFont(const FontDescription& description, ShouldRetain shouldRetain)
-{
- const FontPlatformData* fontPlatformData = getFallbackFontData(description);
- if (!fontPlatformData) {
- // we should at least have Arial; this is the SkFontHost_fontconfig last resort fallback
- DEFINE_STATIC_LOCAL(const AtomicString, arialStr, ("Arial", AtomicString::ConstructFromLiteral));
- fontPlatformData = getFontResourcePlatformData(description, arialStr);
- }
-
- ASSERT(fontPlatformData);
- return getFontResourceData(fontPlatformData, shouldRetain);
-}
-
-void FontCache::getTraitsInFamily(const AtomicString& familyName,
- Vector<unsigned>& traitsMasks)
-{
- notImplemented();
-}
-
-SkTypeface* FontCache::createTypeface(const FontDescription& fontDescription, const AtomicString& family, CString& name)
-{
- name = "";
-
- // If we're creating a fallback font (e.g. "-webkit-monospace"), convert the name into
- // the fallback name (like "monospace") that fontconfig understands.
- if (!family.length() || family.startsWith("-webkit-")) {
- static const struct {
- FontDescription::GenericFamilyType mType;
- const char* mName;
- } fontDescriptions[] = {
- { FontDescription::SerifFamily, "serif" },
- { FontDescription::SansSerifFamily, "sans-serif" },
- { FontDescription::MonospaceFamily, "monospace" },
- { FontDescription::CursiveFamily, "cursive" },
- { FontDescription::FantasyFamily, "fantasy" }
- };
-
- FontDescription::GenericFamilyType type = fontDescription.genericFamily();
- for (unsigned i = 0; i < SK_ARRAY_COUNT(fontDescriptions); i++) {
- if (type == fontDescriptions[i].mType) {
- name = fontDescriptions[i].mName;
- break;
- }
- }
- } else {
- // convert the name to utf8
- name = family.string().utf8();
- }
-
- int style = SkTypeface::kNormal;
- if (fontDescription.weight() >= FontWeightBold)
- style |= SkTypeface::kBold;
- if (fontDescription.italic())
- style |= SkTypeface::kItalic;
-
- // FIXME: Use SkFontStyle and matchFamilyStyle instead of legacyCreateTypeface.
-#if OS(WIN) && !ENABLE(GDI_FONTS_ON_WINDOWS)
- if (m_fontManager)
- return m_fontManager->legacyCreateTypeface(name.data(), style);
-#endif
-
- return SkTypeface::CreateFromName(name.data(), static_cast<SkTypeface::Style>(style));
-}
-
-#if !OS(WIN)
-FontPlatformData* FontCache::createFontPlatformData(const FontDescription& fontDescription, const AtomicString& family)
-{
- CString name;
- SkTypeface* tf = createTypeface(fontDescription, family, name);
- if (!tf)
- return 0;
-
- FontPlatformData* result = new FontPlatformData(tf,
- name.data(),
- fontDescription.computedSize(),
- fontDescription.weight() >= FontWeightBold && !tf->isBold(),
- fontDescription.italic() && !tf->isItalic(),
- fontDescription.orientation());
- tf->unref();
- return result;
-}
-#endif // !OS(WINDOWNS)
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/skia/FontCacheSkiaWin.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/skia/FontCacheSkiaWin.cpp
deleted file mode 100644
index 35cb9208f4c..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/skia/FontCacheSkiaWin.cpp
+++ /dev/null
@@ -1,219 +0,0 @@
-/*
- * Copyright (C) 2006, 2007 Apple Computer, Inc.
- * Copyright (c) 2006, 2007, 2008, 2009, 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/FontCache.h"
-
-#include "SkFontMgr.h"
-#include "SkTypeface_win.h"
-#include "core/platform/NotImplemented.h"
-#include "core/platform/graphics/Font.h"
-#include "core/platform/graphics/SimpleFontData.h"
-#include "core/platform/graphics/chromium/FontPlatformDataChromiumWin.h"
-#include "core/platform/graphics/chromium/FontUtilsChromiumWin.h"
-
-namespace WebCore {
-
-FontCache::FontCache()
- : m_purgePreventCount(0)
-{
- m_fontManager = adoptPtr(SkFontMgr_New_GDI());
-}
-
-
-static bool fontContainsCharacter(const FontPlatformData* fontData, const wchar_t* family, UChar32 character)
-{
- SkPaint paint;
- fontData->setupPaint(&paint);
- paint.setTextEncoding(SkPaint::kUTF32_TextEncoding);
-
- uint16_t glyph;
- paint.textToGlyphs(&character, sizeof(character), &glyph);
- return glyph != 0;
-}
-
-// Given the desired base font, this will create a SimpleFontData for a specific
-// font that can be used to render the given range of characters.
-PassRefPtr<SimpleFontData> FontCache::getFontDataForCharacter(const Font& font, UChar32 inputC)
-{
- // FIXME: We should fix getFallbackFamily to take a UChar32
- // and remove this split-to-UChar16 code.
- UChar codeUnits[2];
- int codeUnitsLength;
- if (inputC <= 0xFFFF) {
- codeUnits[0] = inputC;
- codeUnitsLength = 1;
- } else {
- codeUnits[0] = U16_LEAD(inputC);
- codeUnits[1] = U16_TRAIL(inputC);
- codeUnitsLength = 2;
- }
-
- // FIXME: Consider passing fontDescription.dominantScript()
- // to GetFallbackFamily here.
- FontDescription fontDescription = font.fontDescription();
- UChar32 c;
- UScriptCode script;
- const wchar_t* family = getFallbackFamily(codeUnits, codeUnitsLength, fontDescription.genericFamily(), &c, &script);
- FontPlatformData* data = 0;
- if (family)
- data = getFontResourcePlatformData(font.fontDescription(), AtomicString(family, wcslen(family)), false);
-
- // Last resort font list : PanUnicode. CJK fonts have a pretty
- // large repertoire. Eventually, we need to scan all the fonts
- // on the system to have a Firefox-like coverage.
- // Make sure that all of them are lowercased.
- const static wchar_t* const cjkFonts[] = {
- L"arial unicode ms",
- L"ms pgothic",
- L"simsun",
- L"gulim",
- L"pmingliu",
- L"wenquanyi zen hei", // Partial CJK Ext. A coverage but more widely known to Chinese users.
- L"ar pl shanheisun uni",
- L"ar pl zenkai uni",
- L"han nom a", // Complete CJK Ext. A coverage.
- L"code2000" // Complete CJK Ext. A coverage.
- // CJK Ext. B fonts are not listed here because it's of no use
- // with our current non-BMP character handling because we use
- // Uniscribe for it and that code path does not go through here.
- };
-
- const static wchar_t* const commonFonts[] = {
- L"tahoma",
- L"arial unicode ms",
- L"lucida sans unicode",
- L"microsoft sans serif",
- L"palatino linotype",
- // Six fonts below (and code2000 at the end) are not from MS, but
- // once installed, cover a very wide range of characters.
- L"dejavu serif",
- L"dejavu sasns",
- L"freeserif",
- L"freesans",
- L"gentium",
- L"gentiumalt",
- L"ms pgothic",
- L"simsun",
- L"gulim",
- L"pmingliu",
- L"code2000"
- };
-
- const wchar_t* const* panUniFonts = 0;
- int numFonts = 0;
- if (script == USCRIPT_HAN) {
- panUniFonts = cjkFonts;
- numFonts = WTF_ARRAY_LENGTH(cjkFonts);
- } else {
- panUniFonts = commonFonts;
- numFonts = WTF_ARRAY_LENGTH(commonFonts);
- }
- // Font returned from GetFallbackFamily may not cover |characters|
- // because it's based on script to font mapping. This problem is
- // critical enough for non-Latin scripts (especially Han) to
- // warrant an additional (real coverage) check with fontCotainsCharacter.
- int i;
- for (i = 0; (!data || !fontContainsCharacter(data, family, c)) && i < numFonts; ++i) {
- family = panUniFonts[i];
- data = getFontResourcePlatformData(font.fontDescription(), AtomicString(family, wcslen(family)));
- }
- // When i-th font (0-base) in |panUniFonts| contains a character and
- // we get out of the loop, |i| will be |i + 1|. That is, if only the
- // last font in the array covers the character, |i| will be numFonts.
- // So, we have to use '<=" rather than '<' to see if we found a font
- // covering the character.
- if (i <= numFonts)
- return getFontResourceData(data, DoNotRetain);
-
- return 0;
-}
-
-static inline bool equalIgnoringCase(const AtomicString& a, const SkString& b)
-{
- return equalIgnoringCase(a, AtomicString::fromUTF8(b.c_str()));
-}
-
-static bool typefacesMatchesFamily(const SkTypeface* tf, const AtomicString& family)
-{
- SkTypeface::LocalizedStrings* actualFamilies = tf->createFamilyNameIterator();
- bool matchesRequestedFamily = false;
- SkTypeface::LocalizedString actualFamily;
-
- while (actualFamilies->next(&actualFamily)) {
- if (equalIgnoringCase(family, actualFamily.fString)) {
- matchesRequestedFamily = true;
- break;
- }
- }
- actualFamilies->unref();
-
- // getFamilyName may return a name not returned by the createFamilyNameIterator.
- // Specifically in cases where Windows substitutes the font based on the
- // HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\FontSubstitutes registry entries.
- if (!matchesRequestedFamily) {
- SkString familyName;
- tf->getFamilyName(&familyName);
- if (equalIgnoringCase(family, familyName))
- matchesRequestedFamily = true;
- }
-
- return matchesRequestedFamily;
-}
-
-FontPlatformData* FontCache::createFontPlatformData(const FontDescription& fontDescription, const AtomicString& family)
-{
- CString name;
- SkTypeface* tf = createTypeface(fontDescription, family, name);
- if (!tf)
- return 0;
-
- // Windows will always give us a valid pointer here, even if the face name
- // is non-existent. We have to double-check and see if the family name was
- // really used.
- // FIXME: Do we need to use predefined fonts "guaranteed" to exist
- // when we're running in layout-test mode?
- if (!typefacesMatchesFamily(tf, family)) {
- tf->unref();
- return 0;
- }
-
- FontPlatformData* result = new FontPlatformData(tf,
- name.data(),
- fontDescription.computedSize(),
- fontDescription.weight() >= FontWeightBold && !tf->isBold(),
- fontDescription.italic() && !tf->isItalic(),
- fontDescription.orientation());
- tf->unref();
- return result;
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/skia/FontCustomPlatformDataSkia.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/skia/FontCustomPlatformDataSkia.cpp
deleted file mode 100644
index 0794a9c7e0d..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/skia/FontCustomPlatformDataSkia.cpp
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * Copyright (C) 2007 Apple Computer, Inc.
- * Copyright (c) 2007, 2008, 2009, Google Inc. All rights reserved.
- * Copyright (C) 2010 Company 100, Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/FontCustomPlatformData.h"
-
-#include "core/platform/LayoutTestSupport.h"
-#include "core/platform/NotImplemented.h"
-#include "core/platform/SharedBuffer.h"
-#include "core/platform/graphics/FontPlatformData.h"
-#include "core/platform/graphics/opentype/OpenTypeSanitizer.h"
-#include "core/platform/graphics/skia/SkiaSharedBufferStream.h"
-#include "third_party/skia/include/core/SkStream.h"
-#include "third_party/skia/include/core/SkTypeface.h"
-#include "wtf/PassOwnPtr.h"
-
-namespace WebCore {
-
-FontCustomPlatformData::FontCustomPlatformData(PassRefPtr<SkTypeface> typeface)
- : m_typeface(typeface)
-{
-}
-
-FontCustomPlatformData::~FontCustomPlatformData()
-{
-}
-
-FontPlatformData FontCustomPlatformData::fontPlatformData(int size, bool bold, bool italic, FontOrientation orientation, FontWidthVariant)
-{
- ASSERT(m_typeface);
- return FontPlatformData(m_typeface.get(), "", size, bold && !m_typeface->isBold(), italic && !m_typeface->isItalic(), orientation);
-}
-
-PassOwnPtr<FontCustomPlatformData> FontCustomPlatformData::create(SharedBuffer* buffer)
-{
- ASSERT_ARG(buffer, buffer);
-
- OpenTypeSanitizer sanitizer(buffer);
- RefPtr<SharedBuffer> transcodeBuffer = sanitizer.sanitize();
- if (!transcodeBuffer)
- return nullptr; // validation failed.
- buffer = transcodeBuffer.get();
-
- RefPtr<SkiaSharedBufferStream> stream = SkiaSharedBufferStream::create(buffer);
- RefPtr<SkTypeface> typeface = adoptRef(SkTypeface::CreateFromStream(stream.get()));
- if (!typeface)
- return nullptr;
-
- return adoptPtr(new FontCustomPlatformData(typeface.release()));
-}
-
-bool FontCustomPlatformData::supportsFormat(const String& format)
-{
- return equalIgnoringCase(format, "truetype") || equalIgnoringCase(format, "opentype") || OpenTypeSanitizer::supportsFormat(format);
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/skia/FontPlatformDataSkia.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/skia/FontPlatformDataSkia.cpp
deleted file mode 100644
index 33c5662efae..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/skia/FontPlatformDataSkia.cpp
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Copyright (c) 2006, 2007, 2008, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/FontPlatformData.h"
-
-#include "SkEndian.h"
-#include "SkTypeface.h"
-#include "core/platform/graphics/FontCache.h"
-
-namespace WebCore {
-
-#if ENABLE(OPENTYPE_VERTICAL)
-PassRefPtr<OpenTypeVerticalData> FontPlatformData::verticalData() const
-{
- return fontCache()->getVerticalData(typeface()->uniqueID(), *this);
-}
-
-PassRefPtr<SharedBuffer> FontPlatformData::openTypeTable(uint32_t table) const
-{
- RefPtr<SharedBuffer> buffer;
-
- SkFontTableTag tag = SkEndianSwap32(table);
- const size_t tableSize = m_typeface->getTableSize(tag);
- if (tableSize) {
- Vector<char> tableBuffer(tableSize);
- m_typeface->getTableData(tag, 0, tableSize, &tableBuffer[0]);
- buffer = SharedBuffer::adoptVector(tableBuffer);
- }
- return buffer.release();
-}
-#endif
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/skia/GlyphPageTreeNodeSkia.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/skia/GlyphPageTreeNodeSkia.cpp
deleted file mode 100644
index e6f19151e54..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/skia/GlyphPageTreeNodeSkia.cpp
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * Copyright (c) 2008, 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/GlyphPageTreeNode.h"
-
-#include "core/platform/graphics/SimpleFontData.h"
-
-#include "SkPaint.h"
-#include "SkTemplates.h"
-#include "SkUtils.h"
-
-namespace WebCore {
-
-bool GlyphPage::fill(unsigned offset, unsigned length, UChar* buffer, unsigned bufferLength, const SimpleFontData* fontData)
-{
- if (SkUTF16_IsHighSurrogate(buffer[bufferLength-1])) {
- SkDebugf("%s last char is high-surrogate", __FUNCTION__);
- return false;
- }
-
- SkPaint paint;
- fontData->platformData().setupPaint(&paint);
- paint.setTextEncoding(SkPaint::kUTF16_TextEncoding);
-
-#if OS(WIN)
- // FIXME: For some reason SkAutoSTMalloc fails to link on Windows.
- // SkAutoSTArray works fine though...
- SkAutoSTArray<GlyphPage::size, uint16_t> glyphStorage(length);
-#else
- SkAutoSTMalloc<GlyphPage::size, uint16_t> glyphStorage(length);
-#endif
-
- uint16_t* glyphs = glyphStorage.get();
- // textToGlyphs takes a byte count, not a glyph count so we multiply by two.
- unsigned count = paint.textToGlyphs(buffer, bufferLength * 2, glyphs);
- if (count != length) {
- SkDebugf("%s count != length\n", __FUNCTION__);
- return false;
- }
-
- unsigned allGlyphs = 0; // track if any of the glyphIDs are non-zero
- for (unsigned i = 0; i < length; i++) {
- setGlyphDataForIndex(offset + i, glyphs[i], glyphs[i] ? fontData : NULL);
- allGlyphs |= glyphs[i];
- }
-
- return allGlyphs != 0;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/skia/NativeImageSkia.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/skia/NativeImageSkia.cpp
deleted file mode 100644
index 9f774f1ec91..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/skia/NativeImageSkia.cpp
+++ /dev/null
@@ -1,554 +0,0 @@
-/*
- * Copyright (c) 2008, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/skia/NativeImageSkia.h"
-
-#include "core/platform/PlatformInstrumentation.h"
-#include "core/platform/chromium/TraceEvent.h"
-#include "core/platform/graphics/FloatPoint.h"
-#include "core/platform/graphics/FloatRect.h"
-#include "core/platform/graphics/FloatSize.h"
-#include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/graphics/Image.h"
-#include "core/platform/graphics/chromium/DeferredImageDecoder.h"
-#include "core/platform/graphics/skia/SkiaUtils.h"
-#include "skia/ext/image_operations.h"
-#include "third_party/skia/include/core/SkMatrix.h"
-#include "third_party/skia/include/core/SkPaint.h"
-#include "third_party/skia/include/core/SkScalar.h"
-#include "third_party/skia/include/core/SkShader.h"
-#include "third_party/skia/include/effects/SkLumaXfermode.h"
-
-#include <limits>
-#include <math.h>
-
-namespace WebCore {
-
-static bool nearlyIntegral(float value)
-{
- return fabs(value - floorf(value)) < std::numeric_limits<float>::epsilon();
-}
-
-ResamplingMode NativeImageSkia::computeResamplingMode(const SkMatrix& matrix, float srcWidth, float srcHeight, float destWidth, float destHeight) const
-{
- // The percent change below which we will not resample. This usually means
- // an off-by-one error on the web page, and just doing nearest neighbor
- // sampling is usually good enough.
- const float kFractionalChangeThreshold = 0.025f;
-
- // Images smaller than this in either direction are considered "small" and
- // are not resampled ever (see below).
- const int kSmallImageSizeThreshold = 8;
-
- // The amount an image can be stretched in a single direction before we
- // say that it is being stretched so much that it must be a line or
- // background that doesn't need resampling.
- const float kLargeStretch = 3.0f;
-
- // Figure out if we should resample this image. We try to prune out some
- // common cases where resampling won't give us anything, since it is much
- // slower than drawing stretched.
- float diffWidth = fabs(destWidth - srcWidth);
- float diffHeight = fabs(destHeight - srcHeight);
- bool widthNearlyEqual = diffWidth < std::numeric_limits<float>::epsilon();
- bool heightNearlyEqual = diffHeight < std::numeric_limits<float>::epsilon();
- // We don't need to resample if the source and destination are the same.
- if (widthNearlyEqual && heightNearlyEqual)
- return NoResampling;
-
- if (srcWidth <= kSmallImageSizeThreshold
- || srcHeight <= kSmallImageSizeThreshold
- || destWidth <= kSmallImageSizeThreshold
- || destHeight <= kSmallImageSizeThreshold) {
- // Small image detected.
-
- // Resample in the case where the new size would be non-integral.
- // This can cause noticeable breaks in repeating patterns, except
- // when the source image is only one pixel wide in that dimension.
- if ((!nearlyIntegral(destWidth) && srcWidth > 1 + std::numeric_limits<float>::epsilon())
- || (!nearlyIntegral(destHeight) && srcHeight > 1 + std::numeric_limits<float>::epsilon()))
- return LinearResampling;
-
- // Otherwise, don't resample small images. These are often used for
- // borders and rules (think 1x1 images used to make lines).
- return NoResampling;
- }
-
- if (srcHeight * kLargeStretch <= destHeight || srcWidth * kLargeStretch <= destWidth) {
- // Large image detected.
-
- // Don't resample if it is being stretched a lot in only one direction.
- // This is trying to catch cases where somebody has created a border
- // (which might be large) and then is stretching it to fill some part
- // of the page.
- if (widthNearlyEqual || heightNearlyEqual)
- return NoResampling;
-
- // The image is growing a lot and in more than one direction. Resampling
- // is slow and doesn't give us very much when growing a lot.
- return LinearResampling;
- }
-
- if ((diffWidth / srcWidth < kFractionalChangeThreshold)
- && (diffHeight / srcHeight < kFractionalChangeThreshold)) {
- // It is disappointingly common on the web for image sizes to be off by
- // one or two pixels. We don't bother resampling if the size difference
- // is a small fraction of the original size.
- return NoResampling;
- }
-
- // When the image is not yet done loading, use linear. We don't cache the
- // partially resampled images, and as they come in incrementally, it causes
- // us to have to resample the whole thing every time.
- if (!isDataComplete())
- return LinearResampling;
-
- // Everything else gets resampled.
- // High quality interpolation only enabled for scaling and translation.
- if (!(matrix.getType() & (SkMatrix::kAffine_Mask | SkMatrix::kPerspective_Mask)))
- return AwesomeResampling;
-
- return LinearResampling;
-}
-
-static ResamplingMode limitResamplingMode(GraphicsContext* context, ResamplingMode resampling)
-{
- switch (context->imageInterpolationQuality()) {
- case InterpolationNone:
- return NoResampling;
- case InterpolationMedium:
- // For now we treat InterpolationMedium and InterpolationLow the same.
- case InterpolationLow:
- if (resampling == AwesomeResampling)
- return LinearResampling;
- break;
- case InterpolationHigh:
- case InterpolationDefault:
- break;
- }
-
- return resampling;
-}
-
-// This function is used to scale an image and extract a scaled fragment.
-//
-// ALGORITHM
-//
-// Because the scaled image size has to be integers, we approximate the real
-// scale with the following formula (only X direction is shown):
-//
-// scaledImageWidth = round(scaleX * imageRect.width())
-// approximateScaleX = scaledImageWidth / imageRect.width()
-//
-// With this method we maintain a constant scale factor among fragments in
-// the scaled image. This allows fragments to stitch together to form the
-// full scaled image. The downside is there will be a small difference
-// between |scaleX| and |approximateScaleX|.
-//
-// A scaled image fragment is identified by:
-//
-// - Scaled image size
-// - Scaled image fragment rectangle (IntRect)
-//
-// Scaled image size has been determined and the next step is to compute the
-// rectangle for the scaled image fragment which needs to be an IntRect.
-//
-// scaledSrcRect = srcRect * (approximateScaleX, approximateScaleY)
-// enclosingScaledSrcRect = enclosingIntRect(scaledSrcRect)
-//
-// Finally we extract the scaled image fragment using
-// (scaledImageSize, enclosingScaledSrcRect).
-//
-SkBitmap NativeImageSkia::extractScaledImageFragment(const SkRect& srcRect, float scaleX, float scaleY, SkRect* scaledSrcRect) const
-{
- SkISize imageSize = SkISize::Make(bitmap().width(), bitmap().height());
- SkISize scaledImageSize = SkISize::Make(clampToInteger(roundf(imageSize.width() * scaleX)),
- clampToInteger(roundf(imageSize.height() * scaleY)));
-
- SkRect imageRect = SkRect::MakeWH(imageSize.width(), imageSize.height());
- SkRect scaledImageRect = SkRect::MakeWH(scaledImageSize.width(), scaledImageSize.height());
-
- SkMatrix scaleTransform;
- scaleTransform.setRectToRect(imageRect, scaledImageRect, SkMatrix::kFill_ScaleToFit);
- scaleTransform.mapRect(scaledSrcRect, srcRect);
-
- scaledSrcRect->intersect(scaledImageRect);
- SkIRect enclosingScaledSrcRect = enclosingIntRect(*scaledSrcRect);
-
- // |enclosingScaledSrcRect| can be larger than |scaledImageSize| because
- // of float inaccuracy so clip to get inside.
- enclosingScaledSrcRect.intersect(SkIRect::MakeSize(scaledImageSize));
-
- // scaledSrcRect is relative to the pixel snapped fragment we're extracting.
- scaledSrcRect->offset(-enclosingScaledSrcRect.x(), -enclosingScaledSrcRect.y());
-
- return resizedBitmap(scaledImageSize, enclosingScaledSrcRect);
-}
-
-// This does a lot of computation to resample only the portion of the bitmap
-// that will only be drawn. This is critical for performance since when we are
-// scrolling, for example, we are only drawing a small strip of the image.
-// Resampling the whole image every time is very slow, so this speeds up things
-// dramatically.
-//
-// Note: this code is only used when the canvas transformation is limited to
-// scaling or translation.
-void NativeImageSkia::drawResampledBitmap(GraphicsContext* context, SkPaint& paint, const SkRect& srcRect, const SkRect& destRect) const
-{
- TRACE_EVENT0("skia", "drawResampledBitmap");
- // We want to scale |destRect| with transformation in the canvas to obtain
- // the final scale. The final scale is a combination of scale transform
- // in canvas and explicit scaling (srcRect and destRect).
- SkRect screenRect;
- context->getTotalMatrix().mapRect(&screenRect, destRect);
- float realScaleX = screenRect.width() / srcRect.width();
- float realScaleY = screenRect.height() / srcRect.height();
-
- // This part of code limits scaling only to visible portion in the
- SkRect destRectVisibleSubset;
- ClipRectToCanvas(context, destRect, &destRectVisibleSubset);
-
- // ClipRectToCanvas often overshoots, resulting in a larger region than our
- // original destRect. Intersecting gets us back inside.
- if (!destRectVisibleSubset.intersect(destRect))
- return; // Nothing visible in destRect.
-
- // Find the corresponding rect in the source image.
- SkMatrix destToSrcTransform;
- SkRect srcRectVisibleSubset;
- destToSrcTransform.setRectToRect(destRect, srcRect, SkMatrix::kFill_ScaleToFit);
- destToSrcTransform.mapRect(&srcRectVisibleSubset, destRectVisibleSubset);
-
- SkRect scaledSrcRect;
- SkBitmap scaledImageFragment = extractScaledImageFragment(srcRectVisibleSubset, realScaleX, realScaleY, &scaledSrcRect);
-
- context->drawBitmapRect(scaledImageFragment, &scaledSrcRect, destRectVisibleSubset, &paint);
-}
-
-NativeImageSkia::NativeImageSkia()
- : m_resolutionScale(1)
- , m_resizeRequests(0)
-{
-}
-
-NativeImageSkia::NativeImageSkia(const SkBitmap& other, float resolutionScale)
- : m_image(other)
- , m_resolutionScale(resolutionScale)
- , m_resizeRequests(0)
-{
-}
-
-NativeImageSkia::NativeImageSkia(const SkBitmap& image, float resolutionScale, const SkBitmap& resizedImage, const ImageResourceInfo& cachedImageInfo, int resizeRequests)
- : m_image(image)
- , m_resolutionScale(resolutionScale)
- , m_resizedImage(resizedImage)
- , m_cachedImageInfo(cachedImageInfo)
- , m_resizeRequests(resizeRequests)
-{
-}
-
-NativeImageSkia::~NativeImageSkia()
-{
-}
-
-int NativeImageSkia::decodedSize() const
-{
- return m_image.getSize() + m_resizedImage.getSize();
-}
-
-bool NativeImageSkia::hasResizedBitmap(const SkISize& scaledImageSize, const SkIRect& scaledImageSubset) const
-{
- bool imageScaleEqual = m_cachedImageInfo.scaledImageSize == scaledImageSize;
- bool scaledImageSubsetAvailable = m_cachedImageInfo.scaledImageSubset.contains(scaledImageSubset);
- return imageScaleEqual && scaledImageSubsetAvailable && !m_resizedImage.empty();
-}
-
-SkBitmap NativeImageSkia::resizedBitmap(const SkISize& scaledImageSize, const SkIRect& scaledImageSubset) const
-{
- ASSERT(!DeferredImageDecoder::isLazyDecoded(m_image));
-
- if (!hasResizedBitmap(scaledImageSize, scaledImageSubset)) {
- bool shouldCache = isDataComplete()
- && shouldCacheResampling(scaledImageSize, scaledImageSubset);
-
- PlatformInstrumentation::willResizeImage(shouldCache);
- SkBitmap resizedImage = skia::ImageOperations::Resize(m_image, skia::ImageOperations::RESIZE_LANCZOS3, scaledImageSize.width(), scaledImageSize.height(), scaledImageSubset);
- resizedImage.setImmutable();
- PlatformInstrumentation::didResizeImage();
-
- if (!shouldCache)
- return resizedImage;
-
- m_resizedImage = resizedImage;
- }
-
- SkBitmap resizedSubset;
- SkIRect resizedSubsetRect = m_cachedImageInfo.rectInSubset(scaledImageSubset);
- m_resizedImage.extractSubset(&resizedSubset, resizedSubsetRect);
- return resizedSubset;
-}
-
-static bool hasNon90rotation(GraphicsContext* context)
-{
- return !context->getTotalMatrix().rectStaysRect();
-}
-
-void NativeImageSkia::draw(GraphicsContext* context, const SkRect& srcRect, const SkRect& destRect, PassRefPtr<SkXfermode> compOp) const
-{
- TRACE_EVENT0("skia", "NativeImageSkia::draw");
- SkPaint paint;
- if (context->drawLuminanceMask()) {
- paint.setXfermode(SkLumaMaskXfermode::Create(SkXfermode::kSrcOver_Mode));
- } else {
- paint.setXfermode(compOp.get());
- }
- paint.setAlpha(context->getNormalizedAlpha());
- paint.setLooper(context->drawLooper());
- // only antialias if we're rotated or skewed
- paint.setAntiAlias(hasNon90rotation(context));
-
- ResamplingMode resampling;
- if (context->isAccelerated()) {
- resampling = LinearResampling;
- } else if (context->printing()) {
- resampling = NoResampling;
- } else {
- // Take into account scale applied to the canvas when computing sampling mode (e.g. CSS scale or page scale).
- SkRect destRectTarget = destRect;
- if (!(context->getTotalMatrix().getType() & (SkMatrix::kAffine_Mask | SkMatrix::kPerspective_Mask)))
- context->getTotalMatrix().mapRect(&destRectTarget, destRect);
-
- resampling = computeResamplingMode(context->getTotalMatrix(),
- SkScalarToFloat(srcRect.width()), SkScalarToFloat(srcRect.height()),
- SkScalarToFloat(destRectTarget.width()), SkScalarToFloat(destRectTarget.height()));
- }
-
- if (resampling == NoResampling) {
- // FIXME: This is to not break tests (it results in the filter bitmap flag
- // being set to true). We need to decide if we respect NoResampling
- // being returned from computeResamplingMode.
- resampling = LinearResampling;
- }
- resampling = limitResamplingMode(context, resampling);
- paint.setFilterBitmap(resampling == LinearResampling);
-
- // FIXME: Bicubic filtering in Skia is only applied to defer-decoded images
- // as an experiment. Once this filtering code path becomes stable we should
- // turn this on for all cases, including non-defer-decoded images.
- bool useBicubicFilter = resampling == AwesomeResampling
- && DeferredImageDecoder::isLazyDecoded(bitmap());
- if (useBicubicFilter)
- paint.setFilterLevel(SkPaint::kHigh_FilterLevel);
-
- if (resampling == AwesomeResampling && !useBicubicFilter) {
- // Resample the image and then draw the result to canvas with bilinear
- // filtering.
- drawResampledBitmap(context, paint, srcRect, destRect);
- } else {
- // We want to filter it if we decided to do interpolation above, or if
- // there is something interesting going on with the matrix (like a rotation).
- // Note: for serialization, we will want to subset the bitmap first so we
- // don't send extra pixels.
- context->drawBitmapRect(bitmap(), &srcRect, destRect, &paint);
- }
- context->didDrawRect(destRect, paint, &bitmap());
-}
-
-void NativeImageSkia::drawPattern(
- GraphicsContext* context,
- const FloatRect& floatSrcRect,
- const FloatSize& scale,
- const FloatPoint& phase,
- CompositeOperator compositeOp,
- const FloatRect& destRect,
- BlendMode blendMode) const
-{
- FloatRect normSrcRect = floatSrcRect;
- normSrcRect.intersect(FloatRect(0, 0, bitmap().width(), bitmap().height()));
- if (destRect.isEmpty() || normSrcRect.isEmpty())
- return; // nothing to draw
-
- SkMatrix totalMatrix = context->getTotalMatrix();
- SkScalar ctmScaleX = totalMatrix.getScaleX();
- SkScalar ctmScaleY = totalMatrix.getScaleY();
- totalMatrix.preScale(scale.width(), scale.height());
-
- // Figure out what size the bitmap will be in the destination. The
- // destination rect is the bounds of the pattern, we need to use the
- // matrix to see how big it will be.
- SkRect destRectTarget;
- totalMatrix.mapRect(&destRectTarget, normSrcRect);
-
- float destBitmapWidth = SkScalarToFloat(destRectTarget.width());
- float destBitmapHeight = SkScalarToFloat(destRectTarget.height());
-
- // Compute the resampling mode.
- ResamplingMode resampling;
- if (context->isAccelerated() || context->printing())
- resampling = LinearResampling;
- else
- resampling = computeResamplingMode(totalMatrix, normSrcRect.width(), normSrcRect.height(), destBitmapWidth, destBitmapHeight);
- resampling = limitResamplingMode(context, resampling);
-
- SkMatrix shaderTransform;
- RefPtr<SkShader> shader;
-
- // Bicubic filter is only applied to defer-decoded images, see
- // NativeImageSkia::draw for details.
- bool useBicubicFilter = resampling == AwesomeResampling && DeferredImageDecoder::isLazyDecoded(bitmap());
-
- if (resampling == AwesomeResampling && !useBicubicFilter) {
- // Do nice resampling.
- float scaleX = destBitmapWidth / normSrcRect.width();
- float scaleY = destBitmapHeight / normSrcRect.height();
- SkRect scaledSrcRect;
-
- // The image fragment generated here is not exactly what is
- // requested. The scale factor used is approximated and image
- // fragment is slightly larger to align to integer
- // boundaries.
- SkBitmap resampled = extractScaledImageFragment(normSrcRect, scaleX, scaleY, &scaledSrcRect);
- shader = adoptRef(SkShader::CreateBitmapShader(resampled, SkShader::kRepeat_TileMode, SkShader::kRepeat_TileMode));
-
- // Since we just resized the bitmap, we need to remove the scale
- // applied to the pixels in the bitmap shader. This means we need
- // CTM * shaderTransform to have identity scale. Since we
- // can't modify CTM (or the rectangle will be drawn in the wrong
- // place), we must set shaderTransform's scale to the inverse of
- // CTM scale.
- shaderTransform.setScale(ctmScaleX ? 1 / ctmScaleX : 1, ctmScaleY ? 1 / ctmScaleY : 1);
- } else {
- // No need to resample before drawing.
- SkBitmap srcSubset;
- bitmap().extractSubset(&srcSubset, enclosingIntRect(normSrcRect));
- shader = adoptRef(SkShader::CreateBitmapShader(srcSubset, SkShader::kRepeat_TileMode, SkShader::kRepeat_TileMode));
- // Because no resizing occurred, the shader transform should be
- // set to the pattern's transform, which just includes scale.
- shaderTransform.setScale(scale.width(), scale.height());
- }
-
- // We also need to translate it such that the origin of the pattern is the
- // origin of the destination rect, which is what WebKit expects. Skia uses
- // the coordinate system origin as the base for the pattern. If WebKit wants
- // a shifted image, it will shift it from there using the shaderTransform.
- float adjustedX = phase.x() + normSrcRect.x() * scale.width();
- float adjustedY = phase.y() + normSrcRect.y() * scale.height();
- shaderTransform.postTranslate(SkFloatToScalar(adjustedX), SkFloatToScalar(adjustedY));
- shader->setLocalMatrix(shaderTransform);
-
- SkPaint paint;
- paint.setShader(shader.get());
- if (context->drawLuminanceMask()) {
- paint.setXfermode(SkLumaMaskXfermode::Create(SkXfermode::kSrcOver_Mode));
- } else {
- paint.setXfermode(WebCoreCompositeToSkiaComposite(compositeOp, blendMode).get());
- }
-
- paint.setFilterBitmap(resampling == LinearResampling);
- if (useBicubicFilter)
- paint.setFilterLevel(SkPaint::kHigh_FilterLevel);
-
- context->drawRect(destRect, paint);
-}
-
-bool NativeImageSkia::shouldCacheResampling(const SkISize& scaledImageSize, const SkIRect& scaledImageSubset) const
-{
- // Check whether the requested dimensions match previous request.
- bool matchesPreviousRequest = m_cachedImageInfo.isEqual(scaledImageSize, scaledImageSubset);
- if (matchesPreviousRequest)
- ++m_resizeRequests;
- else {
- m_cachedImageInfo.set(scaledImageSize, scaledImageSubset);
- m_resizeRequests = 0;
- // Reset m_resizedImage now, because we don't distinguish
- // between the last requested resize info and m_resizedImage's
- // resize info.
- m_resizedImage.reset();
- }
-
- // We can not cache incomplete frames. This might be a good optimization in
- // the future, were we know how much of the frame has been decoded, so when
- // we incrementally draw more of the image, we only have to resample the
- // parts that are changed.
- if (!isDataComplete())
- return false;
-
- // If the destination bitmap is excessively large, we'll never allow caching.
- static const unsigned long long kLargeBitmapSize = 4096ULL * 4096ULL;
- unsigned long long fullSize = static_cast<unsigned long long>(scaledImageSize.width()) * static_cast<unsigned long long>(scaledImageSize.height());
- unsigned long long fragmentSize = static_cast<unsigned long long>(scaledImageSubset.width()) * static_cast<unsigned long long>(scaledImageSubset.height());
-
- if (fragmentSize > kLargeBitmapSize)
- return false;
-
- // If the destination bitmap is small, we'll always allow caching, since
- // there is not very much penalty for computing it and it may come in handy.
- static const unsigned kSmallBitmapSize = 4096;
- if (fragmentSize <= kSmallBitmapSize)
- return true;
-
- // If "too many" requests have been made for this bitmap, we assume that
- // many more will be made as well, and we'll go ahead and cache it.
- static const int kManyRequestThreshold = 4;
- if (m_resizeRequests >= kManyRequestThreshold)
- return true;
-
- // If more than 1/4 of the resized image is requested, it's worth caching.
- return fragmentSize > fullSize / 4;
-}
-
-NativeImageSkia::ImageResourceInfo::ImageResourceInfo()
-{
- scaledImageSize.setEmpty();
- scaledImageSubset.setEmpty();
-}
-
-bool NativeImageSkia::ImageResourceInfo::isEqual(const SkISize& otherScaledImageSize, const SkIRect& otherScaledImageSubset) const
-{
- return scaledImageSize == otherScaledImageSize && scaledImageSubset == otherScaledImageSubset;
-}
-
-void NativeImageSkia::ImageResourceInfo::set(const SkISize& otherScaledImageSize, const SkIRect& otherScaledImageSubset)
-{
- scaledImageSize = otherScaledImageSize;
- scaledImageSubset = otherScaledImageSubset;
-}
-
-SkIRect NativeImageSkia::ImageResourceInfo::rectInSubset(const SkIRect& otherScaledImageSubset)
-{
- if (!scaledImageSubset.contains(otherScaledImageSubset))
- return SkIRect::MakeEmpty();
- SkIRect subsetRect = otherScaledImageSubset;
- subsetRect.offset(-scaledImageSubset.x(), -scaledImageSubset.y());
- return subsetRect;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/skia/NativeImageSkia.h b/chromium/third_party/WebKit/Source/core/platform/graphics/skia/NativeImageSkia.h
deleted file mode 100644
index 683e91e6d12..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/skia/NativeImageSkia.h
+++ /dev/null
@@ -1,205 +0,0 @@
-/*
- * Copyright (c) 2008, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef NativeImageSkia_h
-#define NativeImageSkia_h
-
-#include "SkBitmap.h"
-#include "SkRect.h"
-#include "SkSize.h"
-#include "SkXfermode.h"
-#include "core/platform/graphics/GraphicsTypes.h"
-#include "wtf/Forward.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-
-class SkMatrix;
-class SkPaint;
-
-namespace WebCore {
-
-class FloatPoint;
-class FloatRect;
-class FloatSize;
-class GraphicsContext;
-
-// Used by computeResamplingMode to tell how bitmaps should be resampled.
-enum ResamplingMode {
- // Nearest neighbor resampling. Used when we detect that the page is
- // trying to make a pattern by stretching a small bitmap very large.
- NoResampling,
-
- // Default skia resampling. Used for large growing of images where high
- // quality resampling doesn't get us very much except a slowdown.
- LinearResampling,
-
- // High quality resampling.
- AwesomeResampling,
-};
-
-// This object is used as the "native image" in our port. When WebKit uses
-// PassNativeImagePtr / NativeImagePtr, it is a smart pointer to this type.
-// It has an SkBitmap, and also stores a cached resized image.
-class NativeImageSkia : public RefCounted<NativeImageSkia> {
-public:
- static PassRefPtr<NativeImageSkia> create()
- {
- return adoptRef(new NativeImageSkia());
- }
-
- // This factory method does a shallow copy of the passed-in SkBitmap
- // (ie., it references the same pixel data and bumps the refcount). Use
- // only when you want sharing semantics.
- static PassRefPtr<NativeImageSkia> create(const SkBitmap& bitmap, float resolutionScale = 1)
- {
- return adoptRef(new NativeImageSkia(bitmap, resolutionScale));
- }
-
- // This method does a shallow copy of the internal SkBitmap (ie., it
- // references the same pixel data and bumps the refcount). Use only when
- // you want sharing semantics.
- PassRefPtr<NativeImageSkia> clone() const
- {
- return adoptRef(new NativeImageSkia(m_image, m_resolutionScale, m_resizedImage, m_cachedImageInfo, m_resizeRequests));
- }
-
- ~NativeImageSkia();
-
- // Returns the number of bytes of image data. This includes the cached
- // resized version if there is one.
- int decodedSize() const;
-
- // Sets the immutable flag on the bitmap, indicating that the image data
- // will not be modified any further. This is called by the image decoder
- // when all data is complete, used by us to know whether we can cache
- // resized images, and used by Skia for various optimizations.
- void setDataComplete() { m_image.setImmutable(); }
-
- // Returns true if the entire image has been decoded.
- bool isDataComplete() const { return m_image.isImmutable(); }
-
- // Get reference to the internal SkBitmap representing this image.
- const SkBitmap& bitmap() const { return m_image; }
- SkBitmap& bitmap() { return m_image; }
-
- float resolutionScale() const { return m_resolutionScale; }
-
- // We can keep a resized version of the bitmap cached on this object.
- // This function will return true if there is a cached version of the given
- // scale and subset.
- bool hasResizedBitmap(const SkISize& scaledImageSize, const SkIRect& scaledImageSubset) const;
-
- // This will return an existing resized image subset, or generate a new one
- // of the specified size and subset and possibly cache it.
- //
- // scaledImageSize
- // Dimensions of the scaled full image.
- //
- // scaledImageSubset
- // Rectangle of the subset in the scaled image.
- SkBitmap resizedBitmap(const SkISize& scaledImageSize, const SkIRect& scaledImageSubset) const;
-
- void draw(GraphicsContext*, const SkRect& srcRect, const SkRect& destRect, PassRefPtr<SkXfermode>) const;
- void drawPattern(
- GraphicsContext*,
- const FloatRect& srcRect,
- const FloatSize& scale,
- const FloatPoint& phase,
- CompositeOperator,
- const FloatRect& destRect,
- BlendMode) const;
-
-private:
- NativeImageSkia();
-
- NativeImageSkia(const SkBitmap&, float resolutionScale);
-
- // ImageResourceInfo is used to uniquely identify cached or requested image
- // resizes.
- // Image resize is identified by the scaled image size and scaled image subset.
- struct ImageResourceInfo {
- SkISize scaledImageSize;
- SkIRect scaledImageSubset;
-
- ImageResourceInfo();
-
- bool isEqual(const SkISize& otherScaledImageSize, const SkIRect& otherScaledImageSubset) const;
- void set(const SkISize& otherScaledImageSize, const SkIRect& otherScaledImageSubset);
- SkIRect rectInSubset(const SkIRect& otherScaledImageRect);
- };
-
- NativeImageSkia(const SkBitmap& image, float resolutionScale, const SkBitmap& resizedImage, const ImageResourceInfo&, int resizeRequests);
-
- // Returns true if the given resize operation should either resize the whole
- // image and cache it, or resize just the part it needs and throw the result
- // away.
- //
- // Calling this function may increment a request count that can change the
- // result of subsequent calls.
- //
- // On the one hand, if only a small subset is desired, then we will waste a
- // lot of time resampling the entire thing, so we only want to do exactly
- // what's required. On the other hand, resampling the entire bitmap is
- // better if we're going to be using it more than once (like a bitmap
- // scrolling on and off the screen. Since we only cache when doing the
- // entire thing, it's best to just do it up front.
- bool shouldCacheResampling(const SkISize& scaledImageSize, const SkIRect& scaledImageSubset) const;
-
- ResamplingMode computeResamplingMode(const SkMatrix&, float srcWidth, float srcHeight, float destWidth, float destHeight) const;
- SkBitmap extractScaledImageFragment(const SkRect& srcRect, float scaleX, float scaleY, SkRect* scaledSrcRect) const;
- void drawResampledBitmap(GraphicsContext*, SkPaint&, const SkRect& srcRect, const SkRect& destRect) const;
-
- // The original image.
- SkBitmap m_image;
- float m_resolutionScale;
-
- // The cached bitmap fragment. This is a subset of the scaled version of
- // |m_image|. empty() returns true if there is no cached image.
- mutable SkBitmap m_resizedImage;
-
- // References how many times that the image size has been requested for
- // the last size.
- //
- // Every time we get a call to shouldCacheResampling, if it matches the
- // m_cachedImageInfo, we'll increment the counter, and if not, we'll reset
- // the counter and save the dimensions.
- //
- // This allows us to see if many requests have been made for the same
- // resized image, we know that we should probably cache it, even if all of
- // those requests individually are small and would not otherwise be cached.
- //
- // We also track scaling information and destination subset for the scaled
- // image. See comments for ImageResourceInfo.
- mutable ImageResourceInfo m_cachedImageInfo;
- mutable int m_resizeRequests;
-};
-
-}
-#endif // NativeImageSkia_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/skia/OpaqueRegionSkia.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/skia/OpaqueRegionSkia.cpp
deleted file mode 100644
index 11e145406f8..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/skia/OpaqueRegionSkia.cpp
+++ /dev/null
@@ -1,437 +0,0 @@
-/*
- * Copyright (c) 2012, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/platform/graphics/skia/OpaqueRegionSkia.h"
-
-#include "core/platform/graphics/GraphicsContext.h"
-
-#include "SkCanvas.h"
-#include "SkColorFilter.h"
-#include "SkShader.h"
-
-namespace WebCore {
-
-OpaqueRegionSkia::OpaqueRegionSkia()
- : m_opaqueRect(SkRect::MakeEmpty())
-{
-}
-
-OpaqueRegionSkia::~OpaqueRegionSkia()
-{
-}
-
-IntRect OpaqueRegionSkia::asRect() const
-{
- // Returns the largest enclosed rect.
- int left = SkScalarCeil(m_opaqueRect.fLeft);
- int top = SkScalarCeil(m_opaqueRect.fTop);
- int right = SkScalarFloor(m_opaqueRect.fRight);
- int bottom = SkScalarFloor(m_opaqueRect.fBottom);
- return IntRect(left, top, right-left, bottom-top);
-}
-
-// Returns true if the xfermode will force the dst to be opaque, regardless of the current dst.
-static inline bool xfermodeIsOpaque(const SkPaint& paint, bool srcIsOpaque)
-{
- if (!srcIsOpaque)
- return false;
-
- SkXfermode* xfermode = paint.getXfermode();
- if (!xfermode)
- return true; // default to kSrcOver_Mode
- SkXfermode::Mode mode;
- if (!xfermode->asMode(&mode))
- return false;
-
- switch (mode) {
- case SkXfermode::kSrc_Mode: // source
- case SkXfermode::kSrcOver_Mode: // source + dest - source*dest
- case SkXfermode::kDstOver_Mode: // source + dest - source*dest
- case SkXfermode::kDstATop_Mode: // source
- case SkXfermode::kPlus_Mode: // source+dest
- default: // the rest are all source + dest - source*dest
- return true;
- case SkXfermode::kClear_Mode: // 0
- case SkXfermode::kDst_Mode: // dest
- case SkXfermode::kSrcIn_Mode: // source * dest
- case SkXfermode::kDstIn_Mode: // dest * source
- case SkXfermode::kSrcOut_Mode: // source * (1-dest)
- case SkXfermode::kDstOut_Mode: // dest * (1-source)
- case SkXfermode::kSrcATop_Mode: // dest
- case SkXfermode::kXor_Mode: // source + dest - 2*(source*dest)
- return false;
- }
-}
-
-// Returns true if the xfermode will keep the dst opaque, assuming the dst is already opaque.
-static inline bool xfermodePreservesOpaque(const SkPaint& paint, bool srcIsOpaque)
-{
- SkXfermode* xfermode = paint.getXfermode();
- if (!xfermode)
- return true; // default to kSrcOver_Mode
- SkXfermode::Mode mode;
- if (!xfermode->asMode(&mode))
- return false;
-
- switch (mode) {
- case SkXfermode::kDst_Mode: // dest
- case SkXfermode::kSrcOver_Mode: // source + dest - source*dest
- case SkXfermode::kDstOver_Mode: // source + dest - source*dest
- case SkXfermode::kSrcATop_Mode: // dest
- case SkXfermode::kPlus_Mode: // source+dest
- default: // the rest are all source + dest - source*dest
- return true;
- case SkXfermode::kClear_Mode: // 0
- case SkXfermode::kSrcOut_Mode: // source * (1-dest)
- case SkXfermode::kDstOut_Mode: // dest * (1-source)
- case SkXfermode::kXor_Mode: // source + dest - 2*(source*dest)
- return false;
- case SkXfermode::kSrc_Mode: // source
- case SkXfermode::kSrcIn_Mode: // source * dest
- case SkXfermode::kDstIn_Mode: // dest * source
- case SkXfermode::kDstATop_Mode: // source
- return srcIsOpaque;
- }
-}
-
-// Returns true if all pixels painted will be opaque.
-static inline bool paintIsOpaque(const SkPaint& paint, OpaqueRegionSkia::DrawType drawType, const SkBitmap* bitmap)
-{
- if (paint.getAlpha() < 0xFF)
- return false;
- bool checkFillOnly = drawType != OpaqueRegionSkia::FillOrStroke;
- if (!checkFillOnly && paint.getStyle() != SkPaint::kFill_Style && paint.isAntiAlias())
- return false;
- SkShader* shader = paint.getShader();
- if (shader && !shader->isOpaque())
- return false;
- if (bitmap && !bitmap->isOpaque())
- return false;
- if (paint.getLooper())
- return false;
- if (paint.getImageFilter())
- return false;
- if (paint.getMaskFilter())
- return false;
- SkColorFilter* colorFilter = paint.getColorFilter();
- if (colorFilter && !(colorFilter->getFlags() & SkColorFilter::kAlphaUnchanged_Flag))
- return false;
- return true;
-}
-
-// Returns true if there is a rectangular clip, with the result in |deviceClipRect|.
-static inline bool getDeviceClipAsRect(const GraphicsContext* context, SkRect& deviceClipRect)
-{
- // Get the current clip in device coordinate space.
- if (context->canvas()->getClipType() != SkCanvas::kRect_ClipType)
- return false;
-
- SkIRect deviceClipIRect;
- if (context->canvas()->getClipDeviceBounds(&deviceClipIRect))
- deviceClipRect.set(deviceClipIRect);
- else
- deviceClipRect.setEmpty();
-
- return true;
-}
-
-void OpaqueRegionSkia::pushCanvasLayer(const SkPaint* paint)
-{
- CanvasLayerState state;
- if (paint)
- state.paint = *paint;
- m_canvasLayerStack.append(state);
-}
-
-void OpaqueRegionSkia::popCanvasLayer(const GraphicsContext* context)
-{
- ASSERT(!m_canvasLayerStack.isEmpty());
- if (m_canvasLayerStack.isEmpty())
- return;
-
- const CanvasLayerState& canvasLayer = m_canvasLayerStack.last();
- SkRect layerOpaqueRect = canvasLayer.opaqueRect;
- SkPaint layerPaint = canvasLayer.paint;
-
- // Apply the image mask.
- if (canvasLayer.hasImageMask && !layerOpaqueRect.intersect(canvasLayer.imageOpaqueRect))
- layerOpaqueRect.setEmpty();
-
- m_canvasLayerStack.removeLast();
-
- applyOpaqueRegionFromLayer(context, layerOpaqueRect, layerPaint);
-}
-
-void OpaqueRegionSkia::setImageMask(const SkRect& imageOpaqueRect)
-{
- ASSERT(!m_canvasLayerStack.isEmpty());
- m_canvasLayerStack.last().hasImageMask = true;
- m_canvasLayerStack.last().imageOpaqueRect = imageOpaqueRect;
-}
-
-void OpaqueRegionSkia::didDrawRect(const GraphicsContext* context, const SkRect& fillRect, const SkPaint& paint, const SkBitmap* sourceBitmap)
-{
- // Any stroking may put alpha in pixels even if the filling part does not.
- if (paint.getStyle() != SkPaint::kFill_Style) {
- bool fillsBounds = false;
-
- if (!paint.canComputeFastBounds())
- didDrawUnbounded(context, paint, FillOrStroke);
- else {
- SkRect strokeRect;
- strokeRect = paint.computeFastBounds(fillRect, &strokeRect);
- didDraw(context, strokeRect, paint, sourceBitmap, fillsBounds, FillOrStroke);
- }
- }
-
- bool fillsBounds = paint.getStyle() != SkPaint::kStroke_Style;
- didDraw(context, fillRect, paint, sourceBitmap, fillsBounds, FillOnly);
-}
-
-void OpaqueRegionSkia::didDrawPath(const GraphicsContext* context, const SkPath& path, const SkPaint& paint)
-{
- SkRect rect;
- if (path.isRect(&rect)) {
- didDrawRect(context, rect, paint, 0);
- return;
- }
-
- bool fillsBounds = false;
-
- if (!paint.canComputeFastBounds())
- didDrawUnbounded(context, paint, FillOrStroke);
- else {
- rect = paint.computeFastBounds(path.getBounds(), &rect);
- didDraw(context, rect, paint, 0, fillsBounds, FillOrStroke);
- }
-}
-
-void OpaqueRegionSkia::didDrawPoints(const GraphicsContext* context, SkCanvas::PointMode mode, int numPoints, const SkPoint points[], const SkPaint& paint)
-{
- if (!numPoints)
- return;
-
- SkRect rect;
- rect.fLeft = points[0].fX;
- rect.fRight = points[0].fX + 1;
- rect.fTop = points[0].fY;
- rect.fBottom = points[0].fY + 1;
-
- for (int i = 1; i < numPoints; ++i) {
- rect.fLeft = std::min(rect.fLeft, points[i].fX);
- rect.fRight = std::max(rect.fRight, points[i].fX + 1);
- rect.fTop = std::min(rect.fTop, points[i].fY);
- rect.fBottom = std::max(rect.fBottom, points[i].fY + 1);
- }
-
- bool fillsBounds = false;
-
- if (!paint.canComputeFastBounds())
- didDrawUnbounded(context, paint, FillOrStroke);
- else {
- rect = paint.computeFastBounds(rect, &rect);
- didDraw(context, rect, paint, 0, fillsBounds, FillOrStroke);
- }
-}
-
-void OpaqueRegionSkia::didDrawBounded(const GraphicsContext* context, const SkRect& bounds, const SkPaint& paint)
-{
- bool fillsBounds = false;
-
- if (!paint.canComputeFastBounds())
- didDrawUnbounded(context, paint, FillOrStroke);
- else {
- SkRect rect;
- rect = paint.computeFastBounds(bounds, &rect);
- didDraw(context, rect, paint, 0, fillsBounds, FillOrStroke);
- }
-}
-
-void OpaqueRegionSkia::didDraw(const GraphicsContext* context, const SkRect& rect, const SkPaint& paint, const SkBitmap* sourceBitmap, bool fillsBounds, DrawType drawType)
-{
- SkRect targetRect = rect;
-
- // Apply the transform to device coordinate space.
- SkMatrix canvasTransform = context->canvas()->getTotalMatrix();
- if (!canvasTransform.mapRect(&targetRect))
- fillsBounds = false;
-
- // Apply the current clip.
- SkRect deviceClipRect;
- if (!getDeviceClipAsRect(context, deviceClipRect))
- fillsBounds = false;
- else if (!targetRect.intersect(deviceClipRect))
- return;
-
- bool drawsOpaque = paintIsOpaque(paint, drawType, sourceBitmap);
- bool xfersOpaque = xfermodeIsOpaque(paint, drawsOpaque);
- bool preservesOpaque = xfermodePreservesOpaque(paint, drawsOpaque);
-
- if (fillsBounds && xfersOpaque)
- markRectAsOpaque(targetRect);
- else if (!preservesOpaque)
- markRectAsNonOpaque(targetRect);
-}
-
-void OpaqueRegionSkia::didDrawUnbounded(const GraphicsContext* context, const SkPaint& paint, DrawType drawType)
-{
- bool drawsOpaque = paintIsOpaque(paint, drawType, 0);
- bool preservesOpaque = xfermodePreservesOpaque(paint, drawsOpaque);
-
- if (preservesOpaque)
- return;
-
- SkRect deviceClipRect;
- getDeviceClipAsRect(context, deviceClipRect);
- markRectAsNonOpaque(deviceClipRect);
-}
-
-void OpaqueRegionSkia::applyOpaqueRegionFromLayer(const GraphicsContext* context, const SkRect& layerOpaqueRect, const SkPaint& paint)
-{
- SkRect deviceClipRect;
- bool deviceClipIsARect = getDeviceClipAsRect(context, deviceClipRect);
-
- if (deviceClipRect.isEmpty())
- return;
-
- SkRect sourceOpaqueRect = layerOpaqueRect;
- // Save the opaque area in the destination, so we can preserve the parts of it under the source opaque area if possible.
- SkRect destinationOpaqueRect = currentTrackingOpaqueRect();
-
- bool outsideSourceOpaqueRectPreservesOpaque = xfermodePreservesOpaque(paint, false);
- if (!outsideSourceOpaqueRectPreservesOpaque)
- markRectAsNonOpaque(deviceClipRect);
-
- if (!deviceClipIsARect)
- return;
- if (!sourceOpaqueRect.intersect(deviceClipRect))
- return;
-
- bool sourceOpaqueRectDrawsOpaque = paintIsOpaque(paint, FillOnly, 0);
- bool sourceOpaqueRectXfersOpaque = xfermodeIsOpaque(paint, sourceOpaqueRectDrawsOpaque);
- bool sourceOpaqueRectPreservesOpaque = xfermodePreservesOpaque(paint, sourceOpaqueRectDrawsOpaque);
-
- // If the layer's opaque area is being drawn opaque in the layer below, then mark it opaque. Otherwise,
- // if it preserves opaque then keep the intersection of the two.
- if (sourceOpaqueRectXfersOpaque)
- markRectAsOpaque(sourceOpaqueRect);
- else if (sourceOpaqueRectPreservesOpaque && sourceOpaqueRect.intersect(destinationOpaqueRect))
- markRectAsOpaque(sourceOpaqueRect);
-}
-
-void OpaqueRegionSkia::markRectAsOpaque(const SkRect& rect)
-{
- // We want to keep track of an opaque region but bound its complexity at a constant size.
- // We keep track of the largest rectangle seen by area. If we can add the new rect to this
- // rectangle then we do that, as that is the cheapest way to increase the area returned
- // without increasing the complexity.
-
- SkRect& opaqueRect = currentTrackingOpaqueRect();
-
- if (rect.isEmpty())
- return;
- if (opaqueRect.contains(rect))
- return;
- if (rect.contains(opaqueRect)) {
- opaqueRect = rect;
- return;
- }
-
- if (rect.fTop <= opaqueRect.fTop && rect.fBottom >= opaqueRect.fBottom) {
- if (rect.fLeft < opaqueRect.fLeft && rect.fRight >= opaqueRect.fLeft)
- opaqueRect.fLeft = rect.fLeft;
- if (rect.fRight > opaqueRect.fRight && rect.fLeft <= opaqueRect.fRight)
- opaqueRect.fRight = rect.fRight;
- } else if (rect.fLeft <= opaqueRect.fLeft && rect.fRight >= opaqueRect.fRight) {
- if (rect.fTop < opaqueRect.fTop && rect.fBottom >= opaqueRect.fTop)
- opaqueRect.fTop = rect.fTop;
- if (rect.fBottom > opaqueRect.fBottom && rect.fTop <= opaqueRect.fBottom)
- opaqueRect.fBottom = rect.fBottom;
- }
-
- long opaqueArea = (long)opaqueRect.width() * (long)opaqueRect.height();
- long area = (long)rect.width() * (long)rect.height();
- if (area > opaqueArea)
- opaqueRect = rect;
-}
-
-void OpaqueRegionSkia::markRectAsNonOpaque(const SkRect& rect)
-{
- // We want to keep as much of the current opaque rectangle as we can, so find the one largest
- // rectangle inside m_opaqueRect that does not intersect with |rect|.
-
- SkRect& opaqueRect = currentTrackingOpaqueRect();
-
- if (!SkRect::Intersects(rect, opaqueRect))
- return;
- if (rect.contains(opaqueRect)) {
- markAllAsNonOpaque();
- return;
- }
-
- int deltaLeft = rect.fLeft - opaqueRect.fLeft;
- int deltaRight = opaqueRect.fRight - rect.fRight;
- int deltaTop = rect.fTop - opaqueRect.fTop;
- int deltaBottom = opaqueRect.fBottom - rect.fBottom;
-
- // horizontal is the larger of the two rectangles to the left or to the right of |rect| and inside opaqueRect.
- // vertical is the larger of the two rectangles above or below |rect| and inside opaqueRect.
- SkRect horizontal = opaqueRect;
- if (deltaTop > deltaBottom)
- horizontal.fBottom = rect.fTop;
- else
- horizontal.fTop = rect.fBottom;
- SkRect vertical = opaqueRect;
- if (deltaLeft > deltaRight)
- vertical.fRight = rect.fLeft;
- else
- vertical.fLeft = rect.fRight;
-
- if ((long)horizontal.width() * (long)horizontal.height() > (long)vertical.width() * (long)vertical.height())
- opaqueRect = horizontal;
- else
- opaqueRect = vertical;
-}
-
-void OpaqueRegionSkia::markAllAsNonOpaque()
-{
- SkRect& opaqueRect = currentTrackingOpaqueRect();
- opaqueRect.setEmpty();
-}
-
-SkRect& OpaqueRegionSkia::currentTrackingOpaqueRect()
-{
- // If we are drawing into a canvas layer, then track the opaque rect in that layer.
- return m_canvasLayerStack.isEmpty() ? m_opaqueRect : m_canvasLayerStack.last().opaqueRect;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/skia/OpaqueRegionSkia.h b/chromium/third_party/WebKit/Source/core/platform/graphics/skia/OpaqueRegionSkia.h
deleted file mode 100644
index 34a2277c44f..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/skia/OpaqueRegionSkia.h
+++ /dev/null
@@ -1,102 +0,0 @@
-/*
- * Copyright (c) 2012, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef OpaqueRegionSkia_h
-#define OpaqueRegionSkia_h
-
-#include "core/platform/graphics/IntRect.h"
-
-#include "SkBitmap.h"
-#include "SkCanvas.h"
-#include "SkPaint.h"
-#include "SkPoint.h"
-#include "SkRect.h"
-
-namespace WebCore {
-class GraphicsContext;
-
-// This class is an encapsulation of functionality for GraphicsContext, and its methods are mirrored
-// there for the outside world. It tracks paints and computes what area will be opaque.
-class OpaqueRegionSkia {
-public:
- OpaqueRegionSkia();
- virtual ~OpaqueRegionSkia();
-
- // The resulting opaque region as a single rect.
- IntRect asRect() const;
-
- void pushCanvasLayer(const SkPaint*);
- void popCanvasLayer(const GraphicsContext*);
-
- void setImageMask(const SkRect& imageOpaqueRect);
-
- enum DrawType {
- FillOnly,
- FillOrStroke
- };
-
- void didDrawRect(const GraphicsContext*, const SkRect&, const SkPaint&, const SkBitmap* sourceBitmap);
- void didDrawPath(const GraphicsContext*, const SkPath&, const SkPaint&);
- void didDrawPoints(const GraphicsContext*, SkCanvas::PointMode, int numPoints, const SkPoint[], const SkPaint&);
- void didDrawBounded(const GraphicsContext*, const SkRect&, const SkPaint&);
- void didDrawUnbounded(const GraphicsContext*, const SkPaint&, DrawType);
-
- struct CanvasLayerState {
- CanvasLayerState()
- : hasImageMask(false)
- , opaqueRect(SkRect::MakeEmpty())
- { }
-
- SkPaint paint;
-
- // An image mask is being applied to the layer.
- bool hasImageMask;
- // The opaque area in the image mask.
- SkRect imageOpaqueRect;
-
- SkRect opaqueRect;
- };
-
-private:
- void didDraw(const GraphicsContext*, const SkRect&, const SkPaint&, const SkBitmap* sourceBitmap, bool fillsBounds, DrawType);
- void applyOpaqueRegionFromLayer(const GraphicsContext*, const SkRect& layerOpaqueRect, const SkPaint&);
- void markRectAsOpaque(const SkRect&);
- void markRectAsNonOpaque(const SkRect&);
- void markAllAsNonOpaque();
-
- SkRect& currentTrackingOpaqueRect();
-
- SkRect m_opaqueRect;
-
- Vector<CanvasLayerState, 3> m_canvasLayerStack;
-};
-
-}
-#endif // OpaqueRegionSkia_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/skia/SimpleFontDataSkia.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/skia/SimpleFontDataSkia.cpp
deleted file mode 100644
index 6a89201f7ec..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/skia/SimpleFontDataSkia.cpp
+++ /dev/null
@@ -1,284 +0,0 @@
-/*
- * Copyright (c) 2008, 2009, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/SimpleFontData.h"
-
-#include <unicode/normlzr.h>
-#include "SkPaint.h"
-#include "SkTypeface.h"
-#include "SkTypes.h"
-#include "core/platform/graphics/FloatRect.h"
-#include "core/platform/graphics/FontDescription.h"
-#include "core/platform/graphics/chromium/VDMXParser.h"
-#include "wtf/unicode/Unicode.h"
-
-#if OS(WIN)
-#include "core/platform/win/HWndDC.h"
-#endif
-
-namespace WebCore {
-
-// This is the largest VDMX table which we'll try to load and parse.
-static const size_t maxVDMXTableSize = 1024 * 1024; // 1 MB
-
-void SimpleFontData::platformInit()
-{
- if (!m_platformData.size()) {
- m_fontMetrics.reset();
- m_avgCharWidth = 0;
- m_maxCharWidth = 0;
- return;
- }
-
- SkPaint paint;
- SkPaint::FontMetrics metrics;
-
- m_platformData.setupPaint(&paint);
- paint.getFontMetrics(&metrics);
- SkTypeface* face = paint.getTypeface();
-
- static const uint32_t vdmxTag = SkSetFourByteTag('V', 'D', 'M', 'X');
- int pixelSize = m_platformData.size() + 0.5;
- int vdmxAscent, vdmxDescent;
- bool isVDMXValid = false;
-
- size_t vdmxSize = face->getTableSize(vdmxTag);
- if (vdmxSize && vdmxSize < maxVDMXTableSize) {
- uint8_t* vdmxTable = (uint8_t*) fastMalloc(vdmxSize);
- if (vdmxTable
- && face->getTableData(vdmxTag, 0, vdmxSize, vdmxTable) == vdmxSize
- && parseVDMX(&vdmxAscent, &vdmxDescent, vdmxTable, vdmxSize, pixelSize))
- isVDMXValid = true;
- fastFree(vdmxTable);
- }
-
- float ascent;
- float descent;
-
- // Beware those who step here: This code is designed to match Win32 font
- // metrics *exactly* (except the adjustment of ascent/descent on Linux/Android).
- if (isVDMXValid) {
- ascent = vdmxAscent;
- descent = -vdmxDescent;
- } else {
- ascent = SkScalarRound(-metrics.fAscent);
- descent = SkScalarRound(metrics.fDescent);
-#if OS(LINUX) || OS(ANDROID)
- // When subpixel positioning is enabled, if the descent is rounded down, the descent part
- // of the glyph may be truncated when displayed in a 'overflow: hidden' container.
- // To avoid that, borrow 1 unit from the ascent when possible.
- // FIXME: This can be removed if sub-pixel ascent/descent is supported.
- if (platformData().fontRenderStyle().useSubpixelPositioning && descent < SkScalarToFloat(metrics.fDescent) && ascent >= 1) {
- ++descent;
- --ascent;
- }
-#endif
- }
-
- m_fontMetrics.setAscent(ascent);
- m_fontMetrics.setDescent(descent);
-
- float xHeight;
- if (metrics.fXHeight) {
- xHeight = metrics.fXHeight;
- m_fontMetrics.setXHeight(xHeight);
- } else {
- xHeight = ascent * 0.56; // Best guess from Windows font metrics.
- m_fontMetrics.setXHeight(xHeight);
- m_fontMetrics.setHasXHeight(false);
- }
-
- float lineGap = SkScalarToFloat(metrics.fLeading);
- m_fontMetrics.setLineGap(lineGap);
- m_fontMetrics.setLineSpacing(lroundf(ascent) + lroundf(descent) + lroundf(lineGap));
-
- if (platformData().orientation() == Vertical && !isTextOrientationFallback()) {
- static const uint32_t vheaTag = SkSetFourByteTag('v', 'h', 'e', 'a');
- static const uint32_t vorgTag = SkSetFourByteTag('V', 'O', 'R', 'G');
- size_t vheaSize = face->getTableSize(vheaTag);
- size_t vorgSize = face->getTableSize(vorgTag);
- if ((vheaSize > 0) || (vorgSize > 0))
- m_hasVerticalGlyphs = true;
- }
-
- // In WebKit/WebCore/platform/graphics/SimpleFontData.cpp, m_spaceWidth is
- // calculated for us, but we need to calculate m_maxCharWidth and
- // m_avgCharWidth in order for text entry widgets to be sized correctly.
-#if OS(WIN)
- m_maxCharWidth = SkScalarRound(metrics.fMaxCharWidth);
-#else
- // FIXME: This seems incorrect and should probably use fMaxCharWidth as
- // the code path above.
- SkScalar xRange = metrics.fXMax - metrics.fXMin;
- m_maxCharWidth = SkScalarRound(xRange * SkScalarRound(m_platformData.size()));
-#endif
-
- if (metrics.fAvgCharWidth)
- m_avgCharWidth = SkScalarRound(metrics.fAvgCharWidth);
- else {
- m_avgCharWidth = xHeight;
-
- GlyphPage* glyphPageZero = GlyphPageTreeNode::getRootChild(this, 0)->page();
-
- if (glyphPageZero) {
- static const UChar32 xChar = 'x';
- const Glyph xGlyph = glyphPageZero->glyphForCharacter(xChar);
-
- if (xGlyph) {
- // In widthForGlyph(), xGlyph will be compared with
- // m_zeroWidthSpaceGlyph, which isn't initialized yet here.
- // Initialize it with zero to make sure widthForGlyph() returns
- // the right width.
- m_zeroWidthSpaceGlyph = 0;
- m_avgCharWidth = widthForGlyph(xGlyph);
- }
- }
- }
-
- if (int unitsPerEm = face->getUnitsPerEm())
- m_fontMetrics.setUnitsPerEm(unitsPerEm);
-}
-
-void SimpleFontData::platformCharWidthInit()
-{
- // charwidths are set in platformInit.
-}
-
-void SimpleFontData::platformDestroy()
-{
-}
-
-PassRefPtr<SimpleFontData> SimpleFontData::platformCreateScaledFontData(const FontDescription& fontDescription, float scaleFactor) const
-{
- const float scaledSize = lroundf(fontDescription.computedSize() * scaleFactor);
- return SimpleFontData::create(FontPlatformData(m_platformData, scaledSize), isCustomFont(), false);
-}
-
-bool SimpleFontData::containsCharacters(const UChar* characters, int length) const
-{
- SkPaint paint;
- static const unsigned maxBufferCount = 64;
- uint16_t glyphs[maxBufferCount];
-
- m_platformData.setupPaint(&paint);
- paint.setTextEncoding(SkPaint::kUTF16_TextEncoding);
-
- while (length > 0) {
- int n = SkMin32(length, SK_ARRAY_COUNT(glyphs));
-
- // textToGlyphs takes a byte count so we double the character count.
- int count = paint.textToGlyphs(characters, n * 2, glyphs);
- for (int i = 0; i < count; i++) {
- if (!glyphs[i])
- return false; // missing glyph
- }
-
- characters += n;
- length -= n;
- }
-
- return true;
-}
-
-void SimpleFontData::determinePitch()
-{
- m_treatAsFixedPitch = platformData().isFixedPitch();
-}
-
-FloatRect SimpleFontData::platformBoundsForGlyph(Glyph glyph) const
-{
- if (!m_platformData.size())
- return FloatRect();
-
- SkASSERT(sizeof(glyph) == 2); // compile-time assert
-
- SkPaint paint;
-
- m_platformData.setupPaint(&paint);
-
- paint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
- SkRect bounds;
- paint.measureText(&glyph, 2, &bounds);
- if (!paint.isSubpixelText()) {
- SkIRect ir;
- bounds.round(&ir);
- bounds.set(ir);
- }
- return FloatRect(bounds);
-}
-
-float SimpleFontData::platformWidthForGlyph(Glyph glyph) const
-{
- if (!m_platformData.size())
- return 0;
-
- SkASSERT(sizeof(glyph) == 2); // compile-time assert
-
- SkPaint paint;
-
- m_platformData.setupPaint(&paint);
-
- paint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
- SkScalar width = paint.measureText(&glyph, 2);
- if (!paint.isSubpixelText())
- width = SkScalarRound(width);
- return SkScalarToFloat(width);
-}
-
-#if USE(HARFBUZZ)
-bool SimpleFontData::canRenderCombiningCharacterSequence(const UChar* characters, size_t length) const
-{
- if (!m_combiningCharacterSequenceSupport)
- m_combiningCharacterSequenceSupport = adoptPtr(new HashMap<String, bool>);
-
- WTF::HashMap<String, bool>::AddResult addResult = m_combiningCharacterSequenceSupport->add(String(characters, length), false);
- if (!addResult.isNewEntry)
- return addResult.iterator->value;
-
- UErrorCode error = U_ZERO_ERROR;
- Vector<UChar, 4> normalizedCharacters(length);
- int32_t normalizedLength = unorm_normalize(characters, length, UNORM_NFC, UNORM_UNICODE_3_2, &normalizedCharacters[0], length, &error);
- // Can't render if we have an error or no composition occurred.
- if (U_FAILURE(error) || (static_cast<size_t>(normalizedLength) == length))
- return false;
-
- SkPaint paint;
- m_platformData.setupPaint(&paint);
- paint.setTextEncoding(SkPaint::kUTF16_TextEncoding);
- if (paint.textToGlyphs(&normalizedCharacters[0], normalizedLength * 2, 0)) {
- addResult.iterator->value = true;
- return true;
- }
- return false;
-}
-#endif
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/skia/SkiaFontWin.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/skia/SkiaFontWin.cpp
deleted file mode 100644
index 6622321d65f..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/skia/SkiaFontWin.cpp
+++ /dev/null
@@ -1,200 +0,0 @@
-/*
- * Copyright (c) 2008, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/skia/SkiaFontWin.h"
-
-#include "core/platform/graphics/Gradient.h"
-#include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/graphics/Pattern.h"
-#include "core/platform/graphics/SimpleFontData.h"
-#include "core/platform/graphics/chromium/FontPlatformDataChromiumWin.h"
-#include "core/platform/graphics/transforms/AffineTransform.h"
-#include "third_party/skia/include/core/SkCanvas.h"
-#include "third_party/skia/include/core/SkDevice.h"
-#include "third_party/skia/include/core/SkPaint.h"
-#include "third_party/skia/include/core/SkShader.h"
-#include "third_party/skia/include/core/SkTemplates.h"
-#include "wtf/RefPtr.h"
-
-namespace WebCore {
-
-static void skiaDrawText(GraphicsContext* context,
- const SkPoint& point,
- const SkRect& textRect,
- SkPaint* paint,
- const WORD* glyphs,
- const int* advances,
- const GOFFSET* offsets,
- int numGlyphs)
-{
- // Reserve space for 64 SkPoints on the stack. If numGlyphs is larger, the array
- // will dynamically allocate it space for numGlyph glyphs. This is used to store
- // the computed x,y locations. In the case where offsets==null, then we use it
- // to store (twice as many) SkScalars for x[]
- static const size_t kLocalGlyphMax = 64;
-
- SkScalar x = point.fX;
- SkScalar y = point.fY;
- if (offsets) {
- SkAutoSTArray<kLocalGlyphMax, SkPoint> storage(numGlyphs);
- SkPoint* pos = storage.get();
- for (int i = 0; i < numGlyphs; i++) {
- // GDI has dv go up, so we negate it
- pos[i].set(x + SkIntToScalar(offsets[i].du),
- y + -SkIntToScalar(offsets[i].dv));
- x += SkIntToScalar(advances[i]);
- }
- context->drawPosText(glyphs, numGlyphs * sizeof(uint16_t), pos, textRect, *paint);
- } else {
- SkAutoSTArray<kLocalGlyphMax * 2, SkScalar> storage(numGlyphs);
- SkScalar* xpos = storage.get();
- for (int i = 0; i < numGlyphs; i++) {
- xpos[i] = x;
- x += SkIntToScalar(advances[i]);
- }
- context->drawPosTextH(glyphs, numGlyphs * sizeof(uint16_t),
- xpos, y, textRect, *paint);
- }
-}
-
-static void setupPaintForFont(SkPaint* paint, GraphicsContext* context,
- SkTypeface* face, float size, uint32_t textFlags)
-{
- paint->setTextSize(SkFloatToScalar(size));
- paint->setTypeface(face);
-
- if (!context->couldUseLCDRenderedText()) {
- textFlags &= ~SkPaint::kLCDRenderText_Flag;
- // If we *just* clear our request for LCD, then GDI seems to
- // sometimes give us AA text, and sometimes give us BW text. Since the
- // original intent was LCD, we want to force AA (rather than BW), so we
- // add a special bit to tell Skia to do its best to avoid the BW: by
- // drawing LCD offscreen and downsampling that to AA.
- textFlags |= SkPaint::kGenA8FromLCD_Flag;
- }
-
- static const uint32_t textFlagsMask = SkPaint::kAntiAlias_Flag |
- SkPaint::kLCDRenderText_Flag |
- SkPaint::kGenA8FromLCD_Flag;
-
- // now copy in just the text flags
- SkASSERT(!(textFlags & ~textFlagsMask));
- uint32_t flags = paint->getFlags();
- flags &= ~textFlagsMask;
- flags |= textFlags;
- paint->setFlags(flags);
-}
-
-static void paintSkiaText(GraphicsContext* context, HFONT hfont,
- SkTypeface* face, float size, uint32_t textFlags,
- int numGlyphs,
- const WORD* glyphs,
- const int* advances,
- const GOFFSET* offsets,
- const SkPoint& origin,
- const SkRect& textRect)
-{
- TextDrawingModeFlags textMode = context->textDrawingMode();
- // Ensure font load for printing, because PDF device needs it.
- if (context->isPrintingDevice())
- FontPlatformData::ensureFontLoaded(hfont);
-
- // Filling (if necessary). This is the common case.
- SkPaint paint;
- context->setupPaintForFilling(&paint);
- paint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
- setupPaintForFont(&paint, context, face, size, textFlags);
-
- bool didFill = false;
-
- if ((textMode & TextModeFill) && (SkColorGetA(paint.getColor()) || paint.getLooper())) {
- skiaDrawText(context, origin, textRect, &paint, &glyphs[0], &advances[0], &offsets[0], numGlyphs);
- didFill = true;
- }
-
- // Stroking on top (if necessary).
- if ((textMode & TextModeStroke)
- && context->strokeStyle() != NoStroke
- && context->strokeThickness() > 0) {
-
- paint.reset();
- context->setupPaintForStroking(&paint);
- paint.setTextEncoding(SkPaint::kGlyphID_TextEncoding);
- setupPaintForFont(&paint, context, face, size, textFlags);
-
- if (didFill) {
- // If there is a shadow and we filled above, there will already be
- // a shadow. We don't want to draw it again or it will be too dark
- // and it will go on top of the fill.
- //
- // Note that this isn't strictly correct, since the stroke could be
- // very thick and the shadow wouldn't account for this. The "right"
- // thing would be to draw to a new layer and then draw that layer
- // with a shadow. But this is a lot of extra work for something
- // that isn't normally an issue.
- paint.setLooper(0);
- }
-
- skiaDrawText(context, origin, textRect, &paint, &glyphs[0], &advances[0], &offsets[0], numGlyphs);
- }
-}
-
-///////////////////////////////////////////////////////////////////////////////////////////
-
-void paintSkiaText(GraphicsContext* context,
- const FontPlatformData& data,
- int numGlyphs,
- const WORD* glyphs,
- const int* advances,
- const GOFFSET* offsets,
- const SkPoint& origin,
- const SkRect& textRect)
-{
- paintSkiaText(context, data.hfont(), data.typeface(), data.size(), data.paintTextFlags(),
- numGlyphs, glyphs, advances, offsets, origin, textRect);
-}
-
-void paintSkiaText(GraphicsContext* context,
- HFONT hfont,
- int numGlyphs,
- const WORD* glyphs,
- const int* advances,
- const GOFFSET* offsets,
- const SkPoint& origin,
- const SkRect& textRect)
-{
- int size;
- int paintTextFlags;
- RefPtr<SkTypeface> face = CreateTypefaceFromHFont(hfont, &size, &paintTextFlags);
- paintSkiaText(context, hfont, face.get(), size, paintTextFlags, numGlyphs, glyphs, advances, offsets, origin, textRect);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/skia/SkiaFontWin.h b/chromium/third_party/WebKit/Source/core/platform/graphics/skia/SkiaFontWin.h
deleted file mode 100644
index 5e41a0d091a..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/skia/SkiaFontWin.h
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Copyright (c) 2008, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SkiaFontWin_h
-#define SkiaFontWin_h
-
-#include <windows.h>
-#include <usp10.h>
-
-struct SkPoint;
-struct SkRect;
-
-namespace WebCore {
-
-class FontPlatformData;
-class GraphicsContext;
-
-// Note that the offsets parameter is optional. If not null it represents a
-// per glyph offset (such as returned by ScriptPlace Windows API function).
-void paintSkiaText(GraphicsContext*,
- const FontPlatformData&,
- int numGlyphs,
- const WORD* glyphs,
- const int* advances,
- const GOFFSET* offsets,
- const SkPoint& origin,
- const SkRect& textRect);
-
-// Note that the offsets parameter is optional. If not null it represents a
-// per glyph offset (such as returned by ScriptPlace Windows API function).
-// Note: this is less efficient than calling the version with FontPlatformData,
-// as that caches the SkTypeface object.
-void paintSkiaText(GraphicsContext*,
- HFONT,
- int numGlyphs,
- const WORD* glyphs,
- const int* advances,
- const GOFFSET* offsets,
- const SkPoint& origin,
- const SkRect& textRect);
-
-} // namespace WebCore
-
-#endif // SkiaFontWin_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/skia/SkiaSharedBufferStream.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/skia/SkiaSharedBufferStream.cpp
deleted file mode 100644
index 6c28b8532dd..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/skia/SkiaSharedBufferStream.cpp
+++ /dev/null
@@ -1,120 +0,0 @@
-/*
- * Copyright (c) 2013, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/skia/SkiaSharedBufferStream.h"
-
-#include "third_party/skia/include/core/SkStream.h"
-#include "core/platform/SharedBuffer.h"
-#include <algorithm>
-#include <cstring>
-
-namespace WebCore {
-
-size_t SkiaSharedBufferStream::read(void* buffer, size_t bytesRequested)
-{
- const size_t bytesLeft = m_buffer->size() - m_offset;
- const size_t bytesToConsume = std::min(bytesLeft, bytesRequested);
-
- if (buffer) {
- char* byteBuffer = reinterpret_cast<char*>(buffer);
- unsigned byteOffset = m_offset;
- unsigned bytesLeftToConsume = bytesToConsume;
- while (bytesLeftToConsume > 0) {
- const char* segment;
- unsigned bytesInSegment = m_buffer->getSomeData(segment, byteOffset);
- if (!bytesInSegment) {
- unsigned bytesRead = bytesToConsume - bytesLeftToConsume;
- m_offset += bytesRead;
- return bytesRead;
- }
- unsigned bytesToCopy = std::min(bytesInSegment, bytesLeftToConsume);
- std::memcpy(byteBuffer, segment, bytesToCopy);
- bytesLeftToConsume -= bytesToCopy;
- byteBuffer += bytesToCopy;
- byteOffset += bytesToCopy;
- }
- }
- m_offset += bytesToConsume;
- return bytesToConsume;
-}
-
-bool SkiaSharedBufferStream::isAtEnd() const
-{
- return this->getLength() == m_offset;
-}
-
-bool SkiaSharedBufferStream::rewind()
-{
- m_offset = 0;
- return true;
-}
-
-SkiaSharedBufferStream* SkiaSharedBufferStream::duplicate() const
-{
- return new SkiaSharedBufferStream(m_buffer);
-}
-
-size_t SkiaSharedBufferStream::getPosition() const
-{
- return m_offset;
-}
-
-bool SkiaSharedBufferStream::seek(size_t position)
-{
- m_offset = std::min(position, static_cast<size_t>(m_buffer->size()));
- return true;
-}
-
-bool SkiaSharedBufferStream::move(long offset)
-{
- return this->seek(m_offset + offset);
-}
-
-SkiaSharedBufferStream* SkiaSharedBufferStream::fork() const
-{
- SkiaSharedBufferStream* that = this->duplicate();
- that->m_offset = this->m_offset;
- return that;
-}
-
-size_t SkiaSharedBufferStream::getLength() const
-{
- return m_buffer->size();
-}
-
-const void* SkiaSharedBufferStream::getMemoryBase()
-{
- const char* segment;
- unsigned bytesInSegment = m_buffer->getSomeData(segment);
- return (bytesInSegment != m_buffer->size()) ? 0 : segment;
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/skia/SkiaSharedBufferStream.h b/chromium/third_party/WebKit/Source/core/platform/graphics/skia/SkiaSharedBufferStream.h
deleted file mode 100644
index 4ffe2035b1f..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/skia/SkiaSharedBufferStream.h
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * Copyright (c) 2013, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SkiaSharedBufferStream_h
-#define SkiaSharedBufferStream_h
-
-#include "core/platform/SharedBuffer.h"
-#include "third_party/skia/include/core/SkStream.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefPtr.h"
-
-namespace WebCore {
-
-class SkiaSharedBufferStream : public SkStreamAsset {
-public:
- static PassRefPtr<SkiaSharedBufferStream> create(PassRefPtr<SharedBuffer> buffer)
- {
- return adoptRef(new SkiaSharedBufferStream(buffer));
- }
-
- virtual ~SkiaSharedBufferStream()
- {
- }
-
- virtual size_t read(void* buffer, size_t bytesRequested) OVERRIDE;
- virtual bool isAtEnd() const OVERRIDE;
-
- virtual bool rewind() OVERRIDE;
- virtual SkiaSharedBufferStream* duplicate() const OVERRIDE;
-
- virtual size_t getPosition() const OVERRIDE;
- virtual bool seek(size_t position) OVERRIDE;
- virtual bool move(long offset) OVERRIDE;
- virtual SkiaSharedBufferStream* fork() const OVERRIDE;
-
- virtual size_t getLength() const OVERRIDE;
-
- virtual const void* getMemoryBase() OVERRIDE;
-
-private:
- explicit SkiaSharedBufferStream(PassRefPtr<SharedBuffer> buffer)
- : m_buffer(buffer)
- , m_offset(0)
- {
- }
-
- RefPtr<SharedBuffer> m_buffer;
- size_t m_offset;
-};
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/skia/SkiaUtils.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/skia/SkiaUtils.cpp
deleted file mode 100644
index b094167369d..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/skia/SkiaUtils.cpp
+++ /dev/null
@@ -1,184 +0,0 @@
-/*
- * Copyright (c) 2006,2007,2008, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/platform/graphics/skia/SkiaUtils.h"
-
-#include "SkColorPriv.h"
-#include "SkMatrix.h"
-#include "SkRegion.h"
-#include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/graphics/ImageBuffer.h"
-
-namespace WebCore {
-
-static const struct CompositOpToXfermodeMode {
- uint8_t mCompositOp;
- uint8_t m_xfermodeMode;
-} gMapCompositOpsToXfermodeModes[] = {
- { CompositeClear, SkXfermode::kClear_Mode },
- { CompositeCopy, SkXfermode::kSrc_Mode },
- { CompositeSourceOver, SkXfermode::kSrcOver_Mode },
- { CompositeSourceIn, SkXfermode::kSrcIn_Mode },
- { CompositeSourceOut, SkXfermode::kSrcOut_Mode },
- { CompositeSourceAtop, SkXfermode::kSrcATop_Mode },
- { CompositeDestinationOver, SkXfermode::kDstOver_Mode },
- { CompositeDestinationIn, SkXfermode::kDstIn_Mode },
- { CompositeDestinationOut, SkXfermode::kDstOut_Mode },
- { CompositeDestinationAtop, SkXfermode::kDstATop_Mode },
- { CompositeXOR, SkXfermode::kXor_Mode },
- { CompositePlusDarker, SkXfermode::kDarken_Mode },
- { CompositePlusLighter, SkXfermode::kPlus_Mode }
-};
-
-// keep this array in sync with BlendMode enum in GraphicsTypes.h
-static const uint8_t gMapBlendOpsToXfermodeModes[] = {
- SkXfermode::kClear_Mode, // BlendModeNormal
- SkXfermode::kMultiply_Mode, // BlendModeMultiply
- SkXfermode::kScreen_Mode, // BlendModeScreen
- SkXfermode::kOverlay_Mode, // BlendModeOverlay
- SkXfermode::kDarken_Mode, // BlendModeDarken
- SkXfermode::kLighten_Mode, // BlendModeLighten
- SkXfermode::kColorDodge_Mode, // BlendModeColorDodge
- SkXfermode::kColorBurn_Mode, // BlendModeColorBurn
- SkXfermode::kHardLight_Mode, // BlendModeHardLight
- SkXfermode::kSoftLight_Mode, // BlendModeSoftLight
- SkXfermode::kDifference_Mode, // BlendModeDifference
- SkXfermode::kExclusion_Mode, // BlendModeExclusion
- SkXfermode::kHue_Mode, // BlendModeHue
- SkXfermode::kSaturation_Mode, // BlendModeSaturation
- SkXfermode::kColor_Mode, // BlendModeColor
- SkXfermode::kLuminosity_Mode // BlendModeLuminosity
-};
-
-PassRefPtr<SkXfermode> WebCoreCompositeToSkiaComposite(CompositeOperator op, BlendMode blendMode)
-{
- if (blendMode != BlendModeNormal) {
- if ((uint8_t)blendMode >= SK_ARRAY_COUNT(gMapBlendOpsToXfermodeModes)) {
- SkDEBUGF(("GraphicsContext::setPlatformCompositeOperation unknown BlendMode %d\n", blendMode));
- return adoptRef(SkXfermode::Create(SkXfermode::kSrcOver_Mode));
- }
- SkXfermode::Mode mode = (SkXfermode::Mode)gMapBlendOpsToXfermodeModes[(uint8_t)blendMode];
- return adoptRef(SkXfermode::Create(mode));
- }
-
- const CompositOpToXfermodeMode* table = gMapCompositOpsToXfermodeModes;
-
- for (unsigned i = 0; i < SK_ARRAY_COUNT(gMapCompositOpsToXfermodeModes); i++) {
- if (table[i].mCompositOp == op)
- return adoptRef(SkXfermode::Create((SkXfermode::Mode)table[i].m_xfermodeMode));
- }
-
- SkDEBUGF(("GraphicsContext::setPlatformCompositeOperation unknown CompositeOperator %d\n", op));
- return adoptRef(SkXfermode::Create(SkXfermode::kSrcOver_Mode)); // fall-back
-}
-
-static U8CPU InvScaleByte(U8CPU component, uint32_t scale)
-{
- SkASSERT(component == (uint8_t)component);
- return (component * scale + 0x8000) >> 16;
-}
-
-SkColor SkPMColorToColor(SkPMColor pm)
-{
- if (!pm)
- return 0;
- unsigned a = SkGetPackedA32(pm);
- if (!a) {
- // A zero alpha value when there are non-zero R, G, or B channels is an
- // invalid premultiplied color (since all channels should have been
- // multiplied by 0 if a=0).
- SkASSERT(false);
- // In production, return 0 to protect against division by zero.
- return 0;
- }
-
- uint32_t scale = (255 << 16) / a;
-
- return SkColorSetARGB(a,
- InvScaleByte(SkGetPackedR32(pm), scale),
- InvScaleByte(SkGetPackedG32(pm), scale),
- InvScaleByte(SkGetPackedB32(pm), scale));
-}
-
-Color SkPMColorToWebCoreColor(SkPMColor pm)
-{
- return SkPMColorToColor(pm);
-}
-
-void ClipRectToCanvas(const GraphicsContext* context, const SkRect& srcRect, SkRect* destRect)
-{
- if (!context->getClipBounds(destRect) || !destRect->intersect(srcRect))
- destRect->setEmpty();
-}
-
-bool SkPathContainsPoint(const SkPath& originalPath, const FloatPoint& point, SkPath::FillType ft)
-{
- SkRect bounds = originalPath.getBounds();
-
- // We can immediately return false if the point is outside the bounding
- // rect. We don't use bounds.contains() here, since it would exclude
- // points on the right and bottom edges of the bounding rect, and we want
- // to include them.
- SkScalar fX = SkFloatToScalar(point.x());
- SkScalar fY = SkFloatToScalar(point.y());
- if (fX < bounds.fLeft || fX > bounds.fRight || fY < bounds.fTop || fY > bounds.fBottom)
- return false;
-
- // Scale the path to a large size before hit testing for two reasons:
- // 1) Skia has trouble with coordinates close to the max signed 16-bit values, so we scale larger paths down.
- // TODO: when Skia is patched to work properly with large values, this will not be necessary.
- // 2) Skia does not support analytic hit testing, so we scale paths up to do raster hit testing with subpixel accuracy.
- SkScalar biggestCoord = std::max(std::max(std::max(bounds.fRight, bounds.fBottom), -bounds.fLeft), -bounds.fTop);
- if (SkScalarNearlyZero(biggestCoord))
- return false;
- biggestCoord = std::max(std::max(biggestCoord, fX + 1), fY + 1);
-
- const SkScalar kMaxCoordinate = SkIntToScalar(1 << 15);
- SkScalar scale = SkScalarDiv(kMaxCoordinate, biggestCoord);
-
- SkRegion rgn;
- SkRegion clip;
- SkMatrix m;
- SkPath scaledPath(originalPath);
-
- scaledPath.setFillType(ft);
- m.setScale(scale, scale);
- scaledPath.transform(m, 0);
-
- int x = static_cast<int>(floorf(0.5f + point.x() * scale));
- int y = static_cast<int>(floorf(0.5f + point.y() * scale));
- clip.setRect(x - 1, y - 1, x + 1, y + 1);
-
- return rgn.setPath(scaledPath, clip);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/skia/SkiaUtils.h b/chromium/third_party/WebKit/Source/core/platform/graphics/skia/SkiaUtils.h
deleted file mode 100644
index be27592d524..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/skia/SkiaUtils.h
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * Copyright (c) 2006,2007,2008, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-// All of the functions in this file should move to new homes and this file should be deleted.
-
-#ifndef SkiaUtils_h
-#define SkiaUtils_h
-
-#include "SkPath.h"
-#include "SkXfermode.h"
-#include "core/platform/graphics/GraphicsContext.h"
-#include "wtf/MathExtras.h"
-
-class SkCanvas;
-class SkRegion;
-
-namespace WebCore {
-
-PassRefPtr<SkXfermode> WebCoreCompositeToSkiaComposite(CompositeOperator, BlendMode = BlendModeNormal);
-
-// move this guy into SkColor.h
-SkColor SkPMColorToColor(SkPMColor);
-
-// This should be an operator on Color
-Color SkPMColorToWebCoreColor(SkPMColor);
-
-// Skia has problems when passed infinite, etc floats, filter them to 0.
-inline SkScalar WebCoreFloatToSkScalar(float f)
-{
- return SkFloatToScalar(std::isfinite(f) ? f : 0);
-}
-
-inline SkScalar WebCoreDoubleToSkScalar(double d)
-{
- return SkDoubleToScalar(std::isfinite(d) ? d : 0);
-}
-
-inline SkRect WebCoreFloatRectToSKRect(const FloatRect& rect)
-{
- return SkRect::MakeLTRB(SkFloatToScalar(rect.x()), SkFloatToScalar(rect.y()),
- SkFloatToScalar(rect.maxX()), SkFloatToScalar(rect.maxY()));
-}
-
-// Computes the smallest rectangle that, which when drawn to the given canvas,
-// will cover the same area as the source rectangle. It will clip to the canvas'
-// clip, doing the necessary coordinate transforms.
-//
-// srcRect and destRect can be the same.
-void ClipRectToCanvas(const GraphicsContext*, const SkRect& srcRect, SkRect* destRect);
-
-// Determine if a given WebKit point is contained in a path
-bool SkPathContainsPoint(const SkPath&, const FloatPoint&, SkPath::FillType);
-
-} // namespace WebCore
-
-#endif // SkiaUtils_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/AffineTransform.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/AffineTransform.cpp
deleted file mode 100644
index 277018f75ff..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/AffineTransform.cpp
+++ /dev/null
@@ -1,425 +0,0 @@
-/*
- * Copyright (C) 2005, 2006 Apple Computer, Inc. All rights reserved.
- * 2010 Dirk Schulze <krit@webkit.org>
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/transforms/AffineTransform.h"
-
-#include "core/platform/FloatConversion.h"
-#include "core/platform/graphics/FloatQuad.h"
-#include "core/platform/graphics/FloatRect.h"
-#include "core/platform/graphics/IntRect.h"
-#include "core/platform/graphics/skia/SkiaUtils.h"
-
-#include "wtf/MathExtras.h"
-
-namespace WebCore {
-
-AffineTransform::AffineTransform()
-{
- setMatrix(1, 0, 0, 1, 0, 0);
-}
-
-AffineTransform::AffineTransform(double a, double b, double c, double d, double e, double f)
-{
- setMatrix(a, b, c, d, e, f);
-}
-
-void AffineTransform::makeIdentity()
-{
- setMatrix(1, 0, 0, 1, 0, 0);
-}
-
-void AffineTransform::setMatrix(double a, double b, double c, double d, double e, double f)
-{
- m_transform[0] = a;
- m_transform[1] = b;
- m_transform[2] = c;
- m_transform[3] = d;
- m_transform[4] = e;
- m_transform[5] = f;
-}
-
-bool AffineTransform::isIdentity() const
-{
- return (m_transform[0] == 1 && m_transform[1] == 0
- && m_transform[2] == 0 && m_transform[3] == 1
- && m_transform[4] == 0 && m_transform[5] == 0);
-}
-
-double AffineTransform::xScale() const
-{
- return sqrt(m_transform[0] * m_transform[0] + m_transform[1] * m_transform[1]);
-}
-
-double AffineTransform::yScale() const
-{
- return sqrt(m_transform[2] * m_transform[2] + m_transform[3] * m_transform[3]);
-}
-
-double AffineTransform::det() const
-{
- return m_transform[0] * m_transform[3] - m_transform[1] * m_transform[2];
-}
-
-bool AffineTransform::isInvertible() const
-{
- return det() != 0.0;
-}
-
-AffineTransform AffineTransform::inverse() const
-{
- double determinant = det();
- if (determinant == 0.0)
- return AffineTransform();
-
- AffineTransform result;
- if (isIdentityOrTranslation()) {
- result.m_transform[4] = -m_transform[4];
- result.m_transform[5] = -m_transform[5];
- return result;
- }
-
- result.m_transform[0] = m_transform[3] / determinant;
- result.m_transform[1] = -m_transform[1] / determinant;
- result.m_transform[2] = -m_transform[2] / determinant;
- result.m_transform[3] = m_transform[0] / determinant;
- result.m_transform[4] = (m_transform[2] * m_transform[5]
- - m_transform[3] * m_transform[4]) / determinant;
- result.m_transform[5] = (m_transform[1] * m_transform[4]
- - m_transform[0] * m_transform[5]) / determinant;
-
- return result;
-}
-
-
-// Multiplies this AffineTransform by the provided AffineTransform - i.e.
-// this = this * other;
-AffineTransform& AffineTransform::multiply(const AffineTransform& other)
-{
- AffineTransform trans;
-
- trans.m_transform[0] = other.m_transform[0] * m_transform[0] + other.m_transform[1] * m_transform[2];
- trans.m_transform[1] = other.m_transform[0] * m_transform[1] + other.m_transform[1] * m_transform[3];
- trans.m_transform[2] = other.m_transform[2] * m_transform[0] + other.m_transform[3] * m_transform[2];
- trans.m_transform[3] = other.m_transform[2] * m_transform[1] + other.m_transform[3] * m_transform[3];
- trans.m_transform[4] = other.m_transform[4] * m_transform[0] + other.m_transform[5] * m_transform[2] + m_transform[4];
- trans.m_transform[5] = other.m_transform[4] * m_transform[1] + other.m_transform[5] * m_transform[3] + m_transform[5];
-
- setMatrix(trans.m_transform);
- return *this;
-}
-
-AffineTransform& AffineTransform::rotate(double a)
-{
- // angle is in degree. Switch to radian
- a = deg2rad(a);
- double cosAngle = cos(a);
- double sinAngle = sin(a);
- AffineTransform rot(cosAngle, sinAngle, -sinAngle, cosAngle, 0, 0);
-
- multiply(rot);
- return *this;
-}
-
-AffineTransform& AffineTransform::scale(double s)
-{
- return scale(s, s);
-}
-
-AffineTransform& AffineTransform::scale(double sx, double sy)
-{
- m_transform[0] *= sx;
- m_transform[1] *= sx;
- m_transform[2] *= sy;
- m_transform[3] *= sy;
- return *this;
-}
-
-// *this = *this * translation
-AffineTransform& AffineTransform::translate(double tx, double ty)
-{
- if (isIdentityOrTranslation()) {
- m_transform[4] += tx;
- m_transform[5] += ty;
- return *this;
- }
-
- m_transform[4] += tx * m_transform[0] + ty * m_transform[2];
- m_transform[5] += tx * m_transform[1] + ty * m_transform[3];
- return *this;
-}
-
-AffineTransform& AffineTransform::scaleNonUniform(double sx, double sy)
-{
- return scale(sx, sy);
-}
-
-AffineTransform& AffineTransform::rotateFromVector(double x, double y)
-{
- return rotate(rad2deg(atan2(y, x)));
-}
-
-AffineTransform& AffineTransform::flipX()
-{
- return scale(-1, 1);
-}
-
-AffineTransform& AffineTransform::flipY()
-{
- return scale(1, -1);
-}
-
-AffineTransform& AffineTransform::shear(double sx, double sy)
-{
- double a = m_transform[0];
- double b = m_transform[1];
-
- m_transform[0] += sy * m_transform[2];
- m_transform[1] += sy * m_transform[3];
- m_transform[2] += sx * a;
- m_transform[3] += sx * b;
-
- return *this;
-}
-
-AffineTransform& AffineTransform::skew(double angleX, double angleY)
-{
- return shear(tan(deg2rad(angleX)), tan(deg2rad(angleY)));
-}
-
-AffineTransform& AffineTransform::skewX(double angle)
-{
- return shear(tan(deg2rad(angle)), 0);
-}
-
-AffineTransform& AffineTransform::skewY(double angle)
-{
- return shear(0, tan(deg2rad(angle)));
-}
-
-AffineTransform makeMapBetweenRects(const FloatRect& source, const FloatRect& dest)
-{
- AffineTransform transform;
- transform.translate(dest.x() - source.x(), dest.y() - source.y());
- transform.scale(dest.width() / source.width(), dest.height() / source.height());
- return transform;
-}
-
-void AffineTransform::map(double x, double y, double& x2, double& y2) const
-{
- x2 = (m_transform[0] * x + m_transform[2] * y + m_transform[4]);
- y2 = (m_transform[1] * x + m_transform[3] * y + m_transform[5]);
-}
-
-IntPoint AffineTransform::mapPoint(const IntPoint& point) const
-{
- double x2, y2;
- map(point.x(), point.y(), x2, y2);
-
- // Round the point.
- return IntPoint(lround(x2), lround(y2));
-}
-
-FloatPoint AffineTransform::mapPoint(const FloatPoint& point) const
-{
- double x2, y2;
- map(point.x(), point.y(), x2, y2);
-
- return FloatPoint(narrowPrecisionToFloat(x2), narrowPrecisionToFloat(y2));
-}
-
-IntSize AffineTransform::mapSize(const IntSize& size) const
-{
- double width2 = size.width() * xScale();
- double height2 = size.height() * yScale();
-
- return IntSize(lround(width2), lround(height2));
-}
-
-FloatSize AffineTransform::mapSize(const FloatSize& size) const
-{
- double width2 = size.width() * xScale();
- double height2 = size.height() * yScale();
-
- return FloatSize(narrowPrecisionToFloat(width2), narrowPrecisionToFloat(height2));
-}
-
-IntRect AffineTransform::mapRect(const IntRect &rect) const
-{
- return enclosingIntRect(mapRect(FloatRect(rect)));
-}
-
-FloatRect AffineTransform::mapRect(const FloatRect& rect) const
-{
- if (isIdentityOrTranslation()) {
- FloatRect mappedRect(rect);
- mappedRect.move(narrowPrecisionToFloat(m_transform[4]), narrowPrecisionToFloat(m_transform[5]));
- return mappedRect;
- }
-
- FloatQuad result;
- result.setP1(mapPoint(rect.location()));
- result.setP2(mapPoint(FloatPoint(rect.maxX(), rect.y())));
- result.setP3(mapPoint(FloatPoint(rect.maxX(), rect.maxY())));
- result.setP4(mapPoint(FloatPoint(rect.x(), rect.maxY())));
- return result.boundingBox();
-}
-
-FloatQuad AffineTransform::mapQuad(const FloatQuad& q) const
-{
- if (isIdentityOrTranslation()) {
- FloatQuad mappedQuad(q);
- mappedQuad.move(narrowPrecisionToFloat(m_transform[4]), narrowPrecisionToFloat(m_transform[5]));
- return mappedQuad;
- }
-
- FloatQuad result;
- result.setP1(mapPoint(q.p1()));
- result.setP2(mapPoint(q.p2()));
- result.setP3(mapPoint(q.p3()));
- result.setP4(mapPoint(q.p4()));
- return result;
-}
-
-void AffineTransform::blend(const AffineTransform& from, double progress)
-{
- DecomposedType srA, srB;
-
- from.decompose(srA);
- this->decompose(srB);
-
- // If x-axis of one is flipped, and y-axis of the other, convert to an unflipped rotation.
- if ((srA.scaleX < 0 && srB.scaleY < 0) || (srA.scaleY < 0 && srB.scaleX < 0)) {
- srA.scaleX = -srA.scaleX;
- srA.scaleY = -srA.scaleY;
- srA.angle += srA.angle < 0 ? piDouble : -piDouble;
- }
-
- // Don't rotate the long way around.
- srA.angle = fmod(srA.angle, 2 * piDouble);
- srB.angle = fmod(srB.angle, 2 * piDouble);
-
- if (fabs(srA.angle - srB.angle) > piDouble) {
- if (srA.angle > srB.angle)
- srA.angle -= piDouble * 2;
- else
- srB.angle -= piDouble * 2;
- }
-
- srA.scaleX += progress * (srB.scaleX - srA.scaleX);
- srA.scaleY += progress * (srB.scaleY - srA.scaleY);
- srA.angle += progress * (srB.angle - srA.angle);
- srA.remainderA += progress * (srB.remainderA - srA.remainderA);
- srA.remainderB += progress * (srB.remainderB - srA.remainderB);
- srA.remainderC += progress * (srB.remainderC - srA.remainderC);
- srA.remainderD += progress * (srB.remainderD - srA.remainderD);
- srA.translateX += progress * (srB.translateX - srA.translateX);
- srA.translateY += progress * (srB.translateY - srA.translateY);
-
- this->recompose(srA);
-}
-
-TransformationMatrix AffineTransform::toTransformationMatrix() const
-{
- return TransformationMatrix(m_transform[0], m_transform[1], m_transform[2],
- m_transform[3], m_transform[4], m_transform[5]);
-}
-
-AffineTransform::operator SkMatrix() const
-{
- SkMatrix result;
-
- result.setScaleX(WebCoreDoubleToSkScalar(a()));
- result.setSkewX(WebCoreDoubleToSkScalar(c()));
- result.setTranslateX(WebCoreDoubleToSkScalar(e()));
-
- result.setScaleY(WebCoreDoubleToSkScalar(d()));
- result.setSkewY(WebCoreDoubleToSkScalar(b()));
- result.setTranslateY(WebCoreDoubleToSkScalar(f()));
-
- // FIXME: Set perspective properly.
- result.setPerspX(0);
- result.setPerspY(0);
- result.set(SkMatrix::kMPersp2, SK_Scalar1);
-
- return result;
-}
-
-bool AffineTransform::decompose(DecomposedType& decomp) const
-{
- AffineTransform m(*this);
-
- // Compute scaling factors
- double sx = xScale();
- double sy = yScale();
-
- // Compute cross product of transformed unit vectors. If negative,
- // one axis was flipped.
- if (m.a() * m.d() - m.c() * m.b() < 0) {
- // Flip axis with minimum unit vector dot product
- if (m.a() < m.d())
- sx = -sx;
- else
- sy = -sy;
- }
-
- // Remove scale from matrix
- m.scale(1 / sx, 1 / sy);
-
- // Compute rotation
- double angle = atan2(m.b(), m.a());
-
- // Remove rotation from matrix
- m.rotate(rad2deg(-angle));
-
- // Return results
- decomp.scaleX = sx;
- decomp.scaleY = sy;
- decomp.angle = angle;
- decomp.remainderA = m.a();
- decomp.remainderB = m.b();
- decomp.remainderC = m.c();
- decomp.remainderD = m.d();
- decomp.translateX = m.e();
- decomp.translateY = m.f();
-
- return true;
-}
-
-void AffineTransform::recompose(const DecomposedType& decomp)
-{
- this->setA(decomp.remainderA);
- this->setB(decomp.remainderB);
- this->setC(decomp.remainderC);
- this->setD(decomp.remainderD);
- this->setE(decomp.translateX);
- this->setF(decomp.translateY);
- this->rotate(rad2deg(decomp.angle));
- this->scale(decomp.scaleX, decomp.scaleY);
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/AffineTransform.h b/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/AffineTransform.h
deleted file mode 100644
index 536fa669f90..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/AffineTransform.h
+++ /dev/null
@@ -1,189 +0,0 @@
-/*
- * Copyright (C) 2005, 2006 Apple Computer, Inc. All rights reserved.
- * 2010 Dirk Schulze <krit@webkit.org>
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef AffineTransform_h
-#define AffineTransform_h
-
-#include "core/platform/graphics/transforms/TransformationMatrix.h"
-
-#include <string.h> // for memcpy
-#include "wtf/FastAllocBase.h"
-
-#include <SkMatrix.h>
-
-namespace WebCore {
-
-class FloatPoint;
-class FloatQuad;
-class FloatRect;
-class IntPoint;
-class IntRect;
-class TransformationMatrix;
-
-class AffineTransform {
- WTF_MAKE_FAST_ALLOCATED;
-public:
- typedef double Transform[6];
-
- AffineTransform();
- AffineTransform(double a, double b, double c, double d, double e, double f);
-
- void setMatrix(double a, double b, double c, double d, double e, double f);
-
- void map(double x, double y, double& x2, double& y2) const;
-
- // Rounds the mapped point to the nearest integer value.
- IntPoint mapPoint(const IntPoint&) const;
-
- FloatPoint mapPoint(const FloatPoint&) const;
-
- IntSize mapSize(const IntSize&) const;
-
- FloatSize mapSize(const FloatSize&) const;
-
- // Rounds the resulting mapped rectangle out. This is helpful for bounding
- // box computations but may not be what is wanted in other contexts.
- IntRect mapRect(const IntRect&) const;
-
- FloatRect mapRect(const FloatRect&) const;
- FloatQuad mapQuad(const FloatQuad&) const;
-
- bool isIdentity() const;
-
- double a() const { return m_transform[0]; }
- void setA(double a) { m_transform[0] = a; }
- double b() const { return m_transform[1]; }
- void setB(double b) { m_transform[1] = b; }
- double c() const { return m_transform[2]; }
- void setC(double c) { m_transform[2] = c; }
- double d() const { return m_transform[3]; }
- void setD(double d) { m_transform[3] = d; }
- double e() const { return m_transform[4]; }
- void setE(double e) { m_transform[4] = e; }
- double f() const { return m_transform[5]; }
- void setF(double f) { m_transform[5] = f; }
-
- void makeIdentity();
-
- AffineTransform& multiply(const AffineTransform& other);
- AffineTransform& scale(double);
- AffineTransform& scale(double sx, double sy);
- AffineTransform& scaleNonUniform(double sx, double sy);
- AffineTransform& rotate(double d);
- AffineTransform& rotateFromVector(double x, double y);
- AffineTransform& translate(double tx, double ty);
- AffineTransform& shear(double sx, double sy);
- AffineTransform& flipX();
- AffineTransform& flipY();
- AffineTransform& skew(double angleX, double angleY);
- AffineTransform& skewX(double angle);
- AffineTransform& skewY(double angle);
-
- double xScale() const;
- double yScale() const;
-
- double det() const;
- bool isInvertible() const;
- AffineTransform inverse() const;
-
- void blend(const AffineTransform& from, double progress);
-
- TransformationMatrix toTransformationMatrix() const;
-
- bool isIdentityOrTranslation() const
- {
- return m_transform[0] == 1 && m_transform[1] == 0 && m_transform[2] == 0 && m_transform[3] == 1;
- }
-
- bool isIdentityOrTranslationOrFlipped() const
- {
- return m_transform[0] == 1 && m_transform[1] == 0 && m_transform[2] == 0 && (m_transform[3] == 1 || m_transform[3] == -1);
- }
-
- bool preservesAxisAlignment() const
- {
- return (m_transform[1] == 0 && m_transform[2] == 0) || (m_transform[0] == 0 && m_transform[3] == 0);
- }
-
- bool operator== (const AffineTransform& m2) const
- {
- return (m_transform[0] == m2.m_transform[0]
- && m_transform[1] == m2.m_transform[1]
- && m_transform[2] == m2.m_transform[2]
- && m_transform[3] == m2.m_transform[3]
- && m_transform[4] == m2.m_transform[4]
- && m_transform[5] == m2.m_transform[5]);
- }
-
- bool operator!=(const AffineTransform& other) const { return !(*this == other); }
-
- // *this = *this * t (i.e., a multRight)
- AffineTransform& operator*=(const AffineTransform& t)
- {
- return multiply(t);
- }
-
- // result = *this * t (i.e., a multRight)
- AffineTransform operator*(const AffineTransform& t) const
- {
- AffineTransform result = *this;
- result *= t;
- return result;
- }
-
- operator SkMatrix() const;
-
- static AffineTransform translation(double x, double y)
- {
- return AffineTransform(1, 0, 0, 1, x, y);
- }
-
- // decompose the matrix into its component parts
- typedef struct {
- double scaleX, scaleY;
- double angle;
- double remainderA, remainderB, remainderC, remainderD;
- double translateX, translateY;
- } DecomposedType;
-
- bool decompose(DecomposedType&) const;
- void recompose(const DecomposedType&);
-
-private:
- void setMatrix(const Transform m)
- {
- if (m && m != m_transform)
- memcpy(m_transform, m, sizeof(Transform));
- }
-
- Transform m_transform;
-};
-
-AffineTransform makeMapBetweenRects(const FloatRect& source, const FloatRect& dest);
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/IdentityTransformOperation.h b/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/IdentityTransformOperation.h
deleted file mode 100644
index 3f70d9acdd6..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/IdentityTransformOperation.h
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Copyright (C) 2000 Lars Knoll (knoll@kde.org)
- * (C) 2000 Antti Koivisto (koivisto@kde.org)
- * (C) 2000 Dirk Mueller (mueller@kde.org)
- * Copyright (C) 2003, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
- * Copyright (C) 2006 Graham Dennis (graham.dennis@gmail.com)
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#ifndef IdentityTransformOperation_h
-#define IdentityTransformOperation_h
-
-#include "core/platform/graphics/transforms/TransformOperation.h"
-
-namespace WebCore {
-
-class IdentityTransformOperation : public TransformOperation {
-public:
- static PassRefPtr<IdentityTransformOperation> create()
- {
- return adoptRef(new IdentityTransformOperation());
- }
-
-private:
- virtual bool isIdentity() const { return true; }
- virtual OperationType getOperationType() const { return Identity; }
- virtual bool isSameType(const TransformOperation& o) const { return o.getOperationType() == Identity; }
-
- virtual bool operator==(const TransformOperation& o) const
- {
- return isSameType(o);
- }
-
- virtual bool apply(TransformationMatrix&, const FloatSize&) const
- {
- return false;
- }
-
- virtual PassRefPtr<TransformOperation> blend(const TransformOperation*, double, bool = false)
- {
- return this;
- }
-
- IdentityTransformOperation()
- {
- }
-
-};
-
-} // namespace WebCore
-
-#endif // IdentityTransformOperation_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/InterpolatedTransformOperation.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/InterpolatedTransformOperation.cpp
deleted file mode 100644
index 8f0e2b0e3e7..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/InterpolatedTransformOperation.cpp
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/transforms/InterpolatedTransformOperation.h"
-
-#include "core/platform/graphics/transforms/IdentityTransformOperation.h"
-
-namespace WebCore {
-
-bool InterpolatedTransformOperation::operator==(const TransformOperation& o) const
-{
- if (!isSameType(o))
- return false;
- const InterpolatedTransformOperation* t = static_cast<const InterpolatedTransformOperation*>(&o);
- return progress == t->progress && from == t->from && to == t->to;
-}
-
-bool InterpolatedTransformOperation::apply(TransformationMatrix& transform, const FloatSize& borderBoxSize) const
-{
- TransformationMatrix fromTransform;
- TransformationMatrix toTransform;
- from.apply(borderBoxSize, fromTransform);
- to.apply(borderBoxSize, toTransform);
-
- toTransform.blend(fromTransform, progress);
- transform.multiply(toTransform);
- return true;
-}
-
-PassRefPtr<TransformOperation> InterpolatedTransformOperation::blend(const TransformOperation* from, double progress, bool blendToIdentity)
-{
- if (from && !from->isSameType(*this))
- return this;
-
- TransformOperations thisOperations;
- thisOperations.operations().append(this);
- TransformOperations fromOperations;
- if (blendToIdentity)
- fromOperations.operations().append(IdentityTransformOperation::create());
- else
- fromOperations.operations().append(const_cast<TransformOperation*>(from));
- return InterpolatedTransformOperation::create(thisOperations, fromOperations, progress);
-}
-
-} // namespace WebCore
-
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/InterpolatedTransformOperation.h b/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/InterpolatedTransformOperation.h
deleted file mode 100644
index 97ef8d5d08d..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/InterpolatedTransformOperation.h
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef InterpolatedTransformOperation_h
-#define InterpolatedTransformOperation_h
-
-#include "core/platform/graphics/transforms/TransformOperation.h"
-#include "core/platform/graphics/transforms/TransformOperations.h"
-
-namespace WebCore {
-
-// This class is an implementation detail for deferred interpolations.
-class InterpolatedTransformOperation : public TransformOperation {
-public:
- static PassRefPtr<InterpolatedTransformOperation> create(const TransformOperations& from, const TransformOperations& to, double progress)
- {
- return adoptRef(new InterpolatedTransformOperation(from, to, progress));
- }
-
-private:
- virtual bool isIdentity() const { return false; }
-
- virtual OperationType getOperationType() const { return Interpolated; }
- virtual bool isSameType(const TransformOperation& o) const { return o.getOperationType() == Interpolated; }
-
- virtual bool operator==(const TransformOperation&) const;
- virtual bool apply(TransformationMatrix&, const FloatSize& borderBoxSize) const;
-
- virtual PassRefPtr<TransformOperation> blend(const TransformOperation* from, double progress, bool blendToIdentity = false);
-
- InterpolatedTransformOperation(const TransformOperations& from, const TransformOperations& to, double progress)
- : from(from)
- , to(to)
- , progress(progress)
- { }
-
- const TransformOperations from;
- const TransformOperations to;
- double progress;
-};
-
-} // namespace WebCore
-
-#endif // InterpolatedTransformOperation_h
-
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/Matrix3DTransformOperation.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/Matrix3DTransformOperation.cpp
deleted file mode 100644
index b8732b2e292..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/Matrix3DTransformOperation.cpp
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright (C) 2009 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/transforms/Matrix3DTransformOperation.h"
-
-#include <algorithm>
-
-using namespace std;
-
-namespace WebCore {
-
-PassRefPtr<TransformOperation> Matrix3DTransformOperation::blend(const TransformOperation* from, double progress, bool blendToIdentity)
-{
- if (from && !from->isSameType(*this))
- return this;
-
- // Convert the TransformOperations into matrices
- FloatSize size;
- TransformationMatrix fromT;
- TransformationMatrix toT;
- if (from)
- from->apply(fromT, size);
-
- apply(toT, size);
-
- if (blendToIdentity)
- std::swap(fromT, toT);
-
- toT.blend(fromT, progress);
- return Matrix3DTransformOperation::create(toT);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/Matrix3DTransformOperation.h b/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/Matrix3DTransformOperation.h
deleted file mode 100644
index 5a8e7320968..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/Matrix3DTransformOperation.h
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * Copyright (C) 2009 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef Matrix3DTransformOperation_h
-#define Matrix3DTransformOperation_h
-
-#include "core/platform/graphics/transforms/TransformOperation.h"
-
-namespace WebCore {
-
-class Matrix3DTransformOperation : public TransformOperation {
-public:
- static PassRefPtr<Matrix3DTransformOperation> create(const TransformationMatrix& matrix)
- {
- return adoptRef(new Matrix3DTransformOperation(matrix));
- }
-
- TransformationMatrix matrix() const {return m_matrix; }
-
-private:
- virtual bool isIdentity() const { return m_matrix.isIdentity(); }
-
- virtual OperationType getOperationType() const { return Matrix3D; }
- virtual bool isSameType(const TransformOperation& o) const { return o.getOperationType() == Matrix3D; }
-
- virtual bool operator==(const TransformOperation& o) const
- {
- if (!isSameType(o))
- return false;
- const Matrix3DTransformOperation* m = static_cast<const Matrix3DTransformOperation*>(&o);
- return m_matrix == m->m_matrix;
- }
-
- virtual bool apply(TransformationMatrix& transform, const FloatSize&) const
- {
- transform.multiply(TransformationMatrix(m_matrix));
- return false;
- }
-
- virtual PassRefPtr<TransformOperation> blend(const TransformOperation* from, double progress, bool blendToIdentity = false);
-
- Matrix3DTransformOperation(const TransformationMatrix& mat)
- {
- m_matrix = mat;
- }
-
- TransformationMatrix m_matrix;
-};
-
-} // namespace WebCore
-
-#endif // Matrix3DTransformOperation_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/MatrixTransformOperation.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/MatrixTransformOperation.cpp
deleted file mode 100644
index d14c7bf1458..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/MatrixTransformOperation.cpp
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Copyright (C) 1999 Antti Koivisto (koivisto@kde.org)
- * Copyright (C) 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#include "config.h"
-#include "core/platform/graphics/transforms/MatrixTransformOperation.h"
-
-#include <algorithm>
-
-using namespace std;
-
-namespace WebCore {
-
-PassRefPtr<TransformOperation> MatrixTransformOperation::blend(const TransformOperation* from, double progress, bool blendToIdentity)
-{
- if (from && !from->isSameType(*this))
- return this;
-
- // convert the TransformOperations into matrices
- FloatSize size;
- TransformationMatrix fromT;
- TransformationMatrix toT(m_a, m_b, m_c, m_d, m_e, m_f);
- if (from) {
- const MatrixTransformOperation* m = static_cast<const MatrixTransformOperation*>(from);
- fromT.setMatrix(m->m_a, m->m_b, m->m_c, m->m_d, m->m_e, m->m_f);
- }
-
- if (blendToIdentity)
- std::swap(fromT, toT);
-
- toT.blend(fromT, progress);
- return MatrixTransformOperation::create(toT.a(), toT.b(), toT.c(), toT.d(), toT.e(), toT.f());
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/MatrixTransformOperation.h b/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/MatrixTransformOperation.h
deleted file mode 100644
index 4dc125ab633..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/MatrixTransformOperation.h
+++ /dev/null
@@ -1,101 +0,0 @@
-/*
- * Copyright (C) 2000 Lars Knoll (knoll@kde.org)
- * (C) 2000 Antti Koivisto (koivisto@kde.org)
- * (C) 2000 Dirk Mueller (mueller@kde.org)
- * Copyright (C) 2003, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
- * Copyright (C) 2006 Graham Dennis (graham.dennis@gmail.com)
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#ifndef MatrixTransformOperation_h
-#define MatrixTransformOperation_h
-
-#include "core/platform/graphics/transforms/TransformOperation.h"
-#include "core/platform/graphics/transforms/TransformationMatrix.h"
-
-namespace WebCore {
-
-class MatrixTransformOperation : public TransformOperation {
-public:
- static PassRefPtr<MatrixTransformOperation> create(double a, double b, double c, double d, double e, double f)
- {
- return adoptRef(new MatrixTransformOperation(a, b, c, d, e, f));
- }
-
- static PassRefPtr<MatrixTransformOperation> create(const TransformationMatrix& t)
- {
- return adoptRef(new MatrixTransformOperation(t));
- }
-
- TransformationMatrix matrix() const { return TransformationMatrix(m_a, m_b, m_c, m_d, m_e, m_f); }
-
-private:
- virtual bool isIdentity() const { return m_a == 1 && m_b == 0 && m_c == 0 && m_d == 1 && m_e == 0 && m_f == 0; }
-
- virtual OperationType getOperationType() const { return Matrix; }
- virtual bool isSameType(const TransformOperation& o) const { return o.getOperationType() == Matrix; }
-
- virtual bool operator==(const TransformOperation& o) const
- {
- if (!isSameType(o))
- return false;
-
- const MatrixTransformOperation* m = static_cast<const MatrixTransformOperation*>(&o);
- return m_a == m->m_a && m_b == m->m_b && m_c == m->m_c && m_d == m->m_d && m_e == m->m_e && m_f == m->m_f;
- }
-
- virtual bool apply(TransformationMatrix& transform, const FloatSize&) const
- {
- TransformationMatrix matrix(m_a, m_b, m_c, m_d, m_e, m_f);
- transform.multiply(matrix);
- return false;
- }
-
- virtual PassRefPtr<TransformOperation> blend(const TransformOperation* from, double progress, bool blendToIdentity = false);
-
- MatrixTransformOperation(double a, double b, double c, double d, double e, double f)
- : m_a(a)
- , m_b(b)
- , m_c(c)
- , m_d(d)
- , m_e(e)
- , m_f(f)
- {
- }
-
- MatrixTransformOperation(const TransformationMatrix& t)
- : m_a(t.a())
- , m_b(t.b())
- , m_c(t.c())
- , m_d(t.d())
- , m_e(t.e())
- , m_f(t.f())
- {
- }
-
- double m_a;
- double m_b;
- double m_c;
- double m_d;
- double m_e;
- double m_f;
-};
-
-} // namespace WebCore
-
-#endif // MatrixTransformOperation_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/PerspectiveTransformOperation.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/PerspectiveTransformOperation.cpp
deleted file mode 100644
index 5d5b9005ef2..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/PerspectiveTransformOperation.cpp
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright (C) 2009 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/transforms/PerspectiveTransformOperation.h"
-
-#include "core/platform/animation/AnimationUtilities.h"
-#include "wtf/MathExtras.h"
-
-using namespace std;
-
-namespace WebCore {
-
-PassRefPtr<TransformOperation> PerspectiveTransformOperation::blend(const TransformOperation* from, double progress, bool blendToIdentity)
-{
- if (from && !from->isSameType(*this))
- return this;
-
- if (blendToIdentity) {
- double p = floatValueForLength(m_p, 1);
- p = WebCore::blend(p, 1.0, progress); // FIXME: this seems wrong. https://bugs.webkit.org/show_bug.cgi?id=52700
- return PerspectiveTransformOperation::create(Length(clampToPositiveInteger(p), Fixed));
- }
-
- const PerspectiveTransformOperation* fromOp = static_cast<const PerspectiveTransformOperation*>(from);
- Length fromP = fromOp ? fromOp->m_p : Length(m_p.type());
- Length toP = m_p;
-
- TransformationMatrix fromT;
- TransformationMatrix toT;
- fromT.applyPerspective(floatValueForLength(fromP, 1));
- toT.applyPerspective(floatValueForLength(toP, 1));
- toT.blend(fromT, progress);
- TransformationMatrix::DecomposedType decomp;
- toT.decompose(decomp);
-
- if (decomp.perspectiveZ) {
- double val = -1.0 / decomp.perspectiveZ;
- return PerspectiveTransformOperation::create(Length(clampToPositiveInteger(val), Fixed));
- }
- return PerspectiveTransformOperation::create(Length(0, Fixed));
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/PerspectiveTransformOperation.h b/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/PerspectiveTransformOperation.h
deleted file mode 100644
index bca1b8e78c4..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/PerspectiveTransformOperation.h
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * Copyright (C) 2009 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef PerspectiveTransformOperation_h
-#define PerspectiveTransformOperation_h
-
-#include "core/css/LengthFunctions.h"
-#include "core/platform/Length.h"
-#include "core/platform/graphics/transforms/TransformOperation.h"
-
-namespace WebCore {
-
-class PerspectiveTransformOperation : public TransformOperation {
-public:
- static PassRefPtr<PerspectiveTransformOperation> create(const Length& p)
- {
- return adoptRef(new PerspectiveTransformOperation(p));
- }
-
- Length perspective() const { return m_p; }
-
-private:
- virtual bool isIdentity() const { return !floatValueForLength(m_p, 1); }
- virtual OperationType getOperationType() const { return Perspective; }
- virtual bool isSameType(const TransformOperation& o) const { return o.getOperationType() == Perspective; }
-
- virtual bool operator==(const TransformOperation& o) const
- {
- if (!isSameType(o))
- return false;
- const PerspectiveTransformOperation* p = static_cast<const PerspectiveTransformOperation*>(&o);
- return m_p == p->m_p;
- }
-
- virtual bool apply(TransformationMatrix& transform, const FloatSize&) const
- {
- transform.applyPerspective(floatValueForLength(m_p, 1));
- return false;
- }
-
- virtual PassRefPtr<TransformOperation> blend(const TransformOperation* from, double progress, bool blendToIdentity = false);
-
- PerspectiveTransformOperation(const Length& p)
- : m_p(p)
- {
- ASSERT(p.isFixed());
- }
-
- Length m_p;
-};
-
-} // namespace WebCore
-
-#endif // PerspectiveTransformOperation_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/RotateTransformOperation.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/RotateTransformOperation.cpp
deleted file mode 100644
index 6b3dc46a073..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/RotateTransformOperation.cpp
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * Copyright (C) 1999 Antti Koivisto (koivisto@kde.org)
- * Copyright (C) 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#include "config.h"
-#include "core/platform/graphics/transforms/RotateTransformOperation.h"
-
-#include <algorithm>
-#include "core/platform/animation/AnimationUtilities.h"
-#include "wtf/MathExtras.h"
-
-using namespace std;
-
-namespace WebCore {
-
-PassRefPtr<TransformOperation> RotateTransformOperation::blend(const TransformOperation* from, double progress, bool blendToIdentity)
-{
- if (from && !from->isSameType(*this))
- return this;
-
- if (blendToIdentity)
- return RotateTransformOperation::create(m_x, m_y, m_z, m_angle - m_angle * progress, m_type);
-
- const RotateTransformOperation* fromOp = static_cast<const RotateTransformOperation*>(from);
-
- // Optimize for single axis rotation
- if (!fromOp || (fromOp->m_x == 0 && fromOp->m_y == 0 && fromOp->m_z == 1) ||
- (fromOp->m_x == 0 && fromOp->m_y == 1 && fromOp->m_z == 0) ||
- (fromOp->m_x == 1 && fromOp->m_y == 0 && fromOp->m_z == 0)) {
- double fromAngle = fromOp ? fromOp->m_angle : 0;
- return RotateTransformOperation::create(fromOp ? fromOp->m_x : m_x,
- fromOp ? fromOp->m_y : m_y,
- fromOp ? fromOp->m_z : m_z,
- WebCore::blend(fromAngle, m_angle, progress), m_type);
- }
-
- const RotateTransformOperation* toOp = this;
-
- // Create the 2 rotation matrices
- TransformationMatrix fromT;
- TransformationMatrix toT;
- fromT.rotate3d((fromOp ? fromOp->m_x : 0),
- (fromOp ? fromOp->m_y : 0),
- (fromOp ? fromOp->m_z : 1),
- (fromOp ? fromOp->m_angle : 0));
-
- toT.rotate3d((toOp ? toOp->m_x : 0),
- (toOp ? toOp->m_y : 0),
- (toOp ? toOp->m_z : 1),
- (toOp ? toOp->m_angle : 0));
-
- // Blend them
- toT.blend(fromT, progress);
-
- // Extract the result as a quaternion
- TransformationMatrix::DecomposedType decomp;
- toT.decompose(decomp);
-
- // Convert that to Axis/Angle form
- double x = -decomp.quaternionX;
- double y = -decomp.quaternionY;
- double z = -decomp.quaternionZ;
- double length = sqrt(x * x + y * y + z * z);
- double angle = 0;
-
- if (length > 0.00001) {
- x /= length;
- y /= length;
- z /= length;
- angle = rad2deg(acos(decomp.quaternionW) * 2);
- } else {
- x = 0;
- y = 0;
- z = 1;
- }
- return RotateTransformOperation::create(x, y, z, angle, Rotate3D);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/RotateTransformOperation.h b/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/RotateTransformOperation.h
deleted file mode 100644
index 00d79830f7a..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/RotateTransformOperation.h
+++ /dev/null
@@ -1,90 +0,0 @@
-/*
- * Copyright (C) 2000 Lars Knoll (knoll@kde.org)
- * (C) 2000 Antti Koivisto (koivisto@kde.org)
- * (C) 2000 Dirk Mueller (mueller@kde.org)
- * Copyright (C) 2003, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
- * Copyright (C) 2006 Graham Dennis (graham.dennis@gmail.com)
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#ifndef RotateTransformOperation_h
-#define RotateTransformOperation_h
-
-#include "core/platform/graphics/transforms/TransformOperation.h"
-
-namespace WebCore {
-
-class RotateTransformOperation : public TransformOperation {
-public:
- static PassRefPtr<RotateTransformOperation> create(double angle, OperationType type)
- {
- return adoptRef(new RotateTransformOperation(0, 0, 1, angle, type));
- }
-
- static PassRefPtr<RotateTransformOperation> create(double x, double y, double z, double angle, OperationType type)
- {
- return adoptRef(new RotateTransformOperation(x, y, z, angle, type));
- }
-
- double x() const { return m_x; }
- double y() const { return m_y; }
- double z() const { return m_z; }
- double angle() const { return m_angle; }
-
-private:
- virtual bool isIdentity() const { return m_angle == 0; }
-
- virtual OperationType getOperationType() const { return m_type; }
- virtual bool isSameType(const TransformOperation& o) const { return o.getOperationType() == m_type; }
-
- virtual bool operator==(const TransformOperation& o) const
- {
- if (!isSameType(o))
- return false;
- const RotateTransformOperation* r = static_cast<const RotateTransformOperation*>(&o);
- return m_x == r->m_x && m_y == r->m_y && m_z == r->m_z && m_angle == r->m_angle;
- }
-
- virtual bool apply(TransformationMatrix& transform, const FloatSize& /*borderBoxSize*/) const
- {
- transform.rotate3d(m_x, m_y, m_z, m_angle);
- return false;
- }
-
- virtual PassRefPtr<TransformOperation> blend(const TransformOperation* from, double progress, bool blendToIdentity = false);
-
- RotateTransformOperation(double x, double y, double z, double angle, OperationType type)
- : m_x(x)
- , m_y(y)
- , m_z(z)
- , m_angle(angle)
- , m_type(type)
- {
- ASSERT(type == RotateX || type == RotateY || type == RotateZ || type == Rotate3D);
- }
-
- double m_x;
- double m_y;
- double m_z;
- double m_angle;
- OperationType m_type;
-};
-
-} // namespace WebCore
-
-#endif // RotateTransformOperation_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/ScaleTransformOperation.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/ScaleTransformOperation.cpp
deleted file mode 100644
index f19e8aeeac6..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/ScaleTransformOperation.cpp
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Copyright (C) 1999 Antti Koivisto (koivisto@kde.org)
- * Copyright (C) 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#include "config.h"
-#include "core/platform/graphics/transforms/ScaleTransformOperation.h"
-
-#include "core/platform/animation/AnimationUtilities.h"
-
-namespace WebCore {
-
-PassRefPtr<TransformOperation> ScaleTransformOperation::blend(const TransformOperation* from, double progress, bool blendToIdentity)
-{
- if (from && !from->isSameType(*this))
- return this;
-
- if (blendToIdentity)
- return ScaleTransformOperation::create(WebCore::blend(m_x, 1.0, progress),
- WebCore::blend(m_y, 1.0, progress),
- WebCore::blend(m_z, 1.0, progress), m_type);
-
- const ScaleTransformOperation* fromOp = static_cast<const ScaleTransformOperation*>(from);
- double fromX = fromOp ? fromOp->m_x : 1.0;
- double fromY = fromOp ? fromOp->m_y : 1.0;
- double fromZ = fromOp ? fromOp->m_z : 1.0;
- return ScaleTransformOperation::create(WebCore::blend(fromX, m_x, progress),
- WebCore::blend(fromY, m_y, progress),
- WebCore::blend(fromZ, m_z, progress), m_type);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/ScaleTransformOperation.h b/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/ScaleTransformOperation.h
deleted file mode 100644
index c380416cb60..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/ScaleTransformOperation.h
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * Copyright (C) 2000 Lars Knoll (knoll@kde.org)
- * (C) 2000 Antti Koivisto (koivisto@kde.org)
- * (C) 2000 Dirk Mueller (mueller@kde.org)
- * Copyright (C) 2003, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
- * Copyright (C) 2006 Graham Dennis (graham.dennis@gmail.com)
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#ifndef ScaleTransformOperation_h
-#define ScaleTransformOperation_h
-
-#include "core/platform/graphics/transforms/TransformOperation.h"
-
-namespace WebCore {
-
-class ScaleTransformOperation : public TransformOperation {
-public:
- static PassRefPtr<ScaleTransformOperation> create(double sx, double sy, OperationType type)
- {
- return adoptRef(new ScaleTransformOperation(sx, sy, 1, type));
- }
-
- static PassRefPtr<ScaleTransformOperation> create(double sx, double sy, double sz, OperationType type)
- {
- return adoptRef(new ScaleTransformOperation(sx, sy, sz, type));
- }
-
- double x() const { return m_x; }
- double y() const { return m_y; }
- double z() const { return m_z; }
-
-private:
- virtual bool isIdentity() const { return m_x == 1 && m_y == 1 && m_z == 1; }
-
- virtual OperationType getOperationType() const { return m_type; }
- virtual bool isSameType(const TransformOperation& o) const { return o.getOperationType() == m_type; }
-
- virtual bool operator==(const TransformOperation& o) const
- {
- if (!isSameType(o))
- return false;
- const ScaleTransformOperation* s = static_cast<const ScaleTransformOperation*>(&o);
- return m_x == s->m_x && m_y == s->m_y && m_z == s->m_z;
- }
-
- virtual bool apply(TransformationMatrix& transform, const FloatSize&) const
- {
- transform.scale3d(m_x, m_y, m_z);
- return false;
- }
-
- virtual PassRefPtr<TransformOperation> blend(const TransformOperation* from, double progress, bool blendToIdentity = false);
-
- ScaleTransformOperation(double sx, double sy, double sz, OperationType type)
- : m_x(sx)
- , m_y(sy)
- , m_z(sz)
- , m_type(type)
- {
- ASSERT(type == ScaleX || type == ScaleY || type == ScaleZ || type == Scale || type == Scale3D);
- }
-
- double m_x;
- double m_y;
- double m_z;
- OperationType m_type;
-};
-
-} // namespace WebCore
-
-#endif // ScaleTransformOperation_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/SkewTransformOperation.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/SkewTransformOperation.cpp
deleted file mode 100644
index e620ea1441c..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/SkewTransformOperation.cpp
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright (C) 1999 Antti Koivisto (koivisto@kde.org)
- * Copyright (C) 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#include "config.h"
-#include "core/platform/graphics/transforms/SkewTransformOperation.h"
-
-#include "core/platform/animation/AnimationUtilities.h"
-
-namespace WebCore {
-
-PassRefPtr<TransformOperation> SkewTransformOperation::blend(const TransformOperation* from, double progress, bool blendToIdentity)
-{
- if (from && !from->isSameType(*this))
- return this;
-
- if (blendToIdentity)
- return SkewTransformOperation::create(WebCore::blend(m_angleX, 0.0, progress), WebCore::blend(m_angleY, 0.0, progress), m_type);
-
- const SkewTransformOperation* fromOp = static_cast<const SkewTransformOperation*>(from);
- double fromAngleX = fromOp ? fromOp->m_angleX : 0;
- double fromAngleY = fromOp ? fromOp->m_angleY : 0;
- return SkewTransformOperation::create(WebCore::blend(fromAngleX, m_angleX, progress), WebCore::blend(fromAngleY, m_angleY, progress), m_type);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/SkewTransformOperation.h b/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/SkewTransformOperation.h
deleted file mode 100644
index c64f8c85f0d..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/SkewTransformOperation.h
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * Copyright (C) 2000 Lars Knoll (knoll@kde.org)
- * (C) 2000 Antti Koivisto (koivisto@kde.org)
- * (C) 2000 Dirk Mueller (mueller@kde.org)
- * Copyright (C) 2003, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
- * Copyright (C) 2006 Graham Dennis (graham.dennis@gmail.com)
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#ifndef SkewTransformOperation_h
-#define SkewTransformOperation_h
-
-#include "core/platform/graphics/transforms/TransformOperation.h"
-
-namespace WebCore {
-
-class SkewTransformOperation : public TransformOperation {
-public:
- static PassRefPtr<SkewTransformOperation> create(double angleX, double angleY, OperationType type)
- {
- return adoptRef(new SkewTransformOperation(angleX, angleY, type));
- }
-
- double angleX() const { return m_angleX; }
- double angleY() const { return m_angleY; }
-
-private:
- virtual bool isIdentity() const { return m_angleX == 0 && m_angleY == 0; }
- virtual OperationType getOperationType() const { return m_type; }
- virtual bool isSameType(const TransformOperation& o) const { return o.getOperationType() == m_type; }
-
- virtual bool operator==(const TransformOperation& o) const
- {
- if (!isSameType(o))
- return false;
- const SkewTransformOperation* s = static_cast<const SkewTransformOperation*>(&o);
- return m_angleX == s->m_angleX && m_angleY == s->m_angleY;
- }
-
- virtual bool apply(TransformationMatrix& transform, const FloatSize&) const
- {
- transform.skew(m_angleX, m_angleY);
- return false;
- }
-
- virtual PassRefPtr<TransformOperation> blend(const TransformOperation* from, double progress, bool blendToIdentity = false);
-
- SkewTransformOperation(double angleX, double angleY, OperationType type)
- : m_angleX(angleX)
- , m_angleY(angleY)
- , m_type(type)
- {
- }
-
- double m_angleX;
- double m_angleY;
- OperationType m_type;
-};
-
-} // namespace WebCore
-
-#endif // SkewTransformOperation_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/TransformOperation.h b/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/TransformOperation.h
deleted file mode 100644
index 5223964b36d..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/TransformOperation.h
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
- * Copyright (C) 2000 Lars Knoll (knoll@kde.org)
- * (C) 2000 Antti Koivisto (koivisto@kde.org)
- * (C) 2000 Dirk Mueller (mueller@kde.org)
- * Copyright (C) 2003, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
- * Copyright (C) 2006 Graham Dennis (graham.dennis@gmail.com)
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#ifndef TransformOperation_h
-#define TransformOperation_h
-
-#include "core/platform/graphics/FloatSize.h"
-#include "core/platform/graphics/transforms/TransformationMatrix.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-
-namespace WebCore {
-
-// CSS Transforms (may become part of CSS3)
-
-class TransformOperation : public RefCounted<TransformOperation> {
-public:
- enum OperationType {
- ScaleX, ScaleY, Scale,
- TranslateX, TranslateY, Translate,
- Rotate,
- RotateZ = Rotate,
- SkewX, SkewY, Skew,
- Matrix,
- ScaleZ, Scale3D,
- TranslateZ, Translate3D,
- RotateX, RotateY, Rotate3D,
- Matrix3D,
- Perspective,
- Interpolated,
- Identity, None
- };
-
- virtual ~TransformOperation() { }
-
- virtual bool operator==(const TransformOperation&) const = 0;
- bool operator!=(const TransformOperation& o) const { return !(*this == o); }
-
- virtual bool isIdentity() const = 0;
-
- // Return true if the borderBoxSize was used in the computation, false otherwise.
- virtual bool apply(TransformationMatrix&, const FloatSize& borderBoxSize) const = 0;
-
- virtual PassRefPtr<TransformOperation> blend(const TransformOperation* from, double progress, bool blendToIdentity = false) = 0;
-
- virtual OperationType getOperationType() const = 0;
- virtual bool isSameType(const TransformOperation&) const { return false; }
-
- bool is3DOperation() const
- {
- OperationType opType = getOperationType();
- return opType == ScaleZ
- || opType == Scale3D
- || opType == TranslateZ
- || opType == Translate3D
- || opType == RotateX
- || opType == RotateY
- || opType == Rotate3D
- || opType == Matrix3D
- || opType == Perspective
- || opType == Interpolated;
- }
-};
-
-} // namespace WebCore
-
-#endif // TransformOperation_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/TransformOperations.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/TransformOperations.cpp
deleted file mode 100644
index 3ca3d7f462f..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/TransformOperations.cpp
+++ /dev/null
@@ -1,119 +0,0 @@
-/*
- * Copyright (C) 1999 Antti Koivisto (koivisto@kde.org)
- * Copyright (C) 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#include "config.h"
-#include "core/platform/graphics/transforms/TransformOperations.h"
-
-#include <algorithm>
-#include "core/platform/graphics/transforms/IdentityTransformOperation.h"
-#include "core/platform/graphics/transforms/InterpolatedTransformOperation.h"
-
-using namespace std;
-
-namespace WebCore {
-
-TransformOperations::TransformOperations(bool makeIdentity)
-{
- if (makeIdentity)
- m_operations.append(IdentityTransformOperation::create());
-}
-
-bool TransformOperations::operator==(const TransformOperations& o) const
-{
- if (m_operations.size() != o.m_operations.size())
- return false;
-
- unsigned s = m_operations.size();
- for (unsigned i = 0; i < s; i++) {
- if (*m_operations[i] != *o.m_operations[i])
- return false;
- }
-
- return true;
-}
-
-bool TransformOperations::operationsMatch(const TransformOperations& other) const
-{
- size_t numOperations = operations().size();
- // If the sizes of the function lists don't match, the lists don't match
- if (numOperations != other.operations().size())
- return false;
-
- // If the types of each function are not the same, the lists don't match
- for (size_t i = 0; i < numOperations; ++i) {
- if (!operations()[i]->isSameType(*other.operations()[i]))
- return false;
- }
- return true;
-}
-
-TransformOperations TransformOperations::blendByMatchingOperations(const TransformOperations& from, const double& progress) const
-{
- TransformOperations result;
-
- unsigned fromSize = from.operations().size();
- unsigned toSize = operations().size();
- unsigned size = max(fromSize, toSize);
- for (unsigned i = 0; i < size; i++) {
- RefPtr<TransformOperation> fromOperation = (i < fromSize) ? from.operations()[i].get() : 0;
- RefPtr<TransformOperation> toOperation = (i < toSize) ? operations()[i].get() : 0;
- RefPtr<TransformOperation> blendedOperation = toOperation ? toOperation->blend(fromOperation.get(), progress) : (fromOperation ? fromOperation->blend(0, progress, true) : 0);
- if (blendedOperation)
- result.operations().append(blendedOperation);
- else {
- RefPtr<TransformOperation> identityOperation = IdentityTransformOperation::create();
- if (progress > 0.5)
- result.operations().append(toOperation ? toOperation : identityOperation);
- else
- result.operations().append(fromOperation ? fromOperation : identityOperation);
- }
- }
-
- return result;
-}
-
-TransformOperations TransformOperations::blendByUsingMatrixInterpolation(const TransformOperations& from, double progress) const
-{
- TransformOperations result;
- result.operations().append(InterpolatedTransformOperation::create(from, *this, progress));
- return result;
-}
-
-TransformOperations TransformOperations::blend(const TransformOperations& from, double progress) const
-{
- if (from == *this)
- return *this;
-
- if (from.size() && from.operationsMatch(*this))
- return blendByMatchingOperations(from, progress);
-
- return blendByUsingMatrixInterpolation(from, progress);
-}
-
-TransformOperations TransformOperations::add(const TransformOperations& addend) const
-{
- TransformOperations result;
- result.m_operations = operations();
- result.m_operations.append(addend.operations());
- return result;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/TransformOperations.h b/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/TransformOperations.h
deleted file mode 100644
index 2f650126189..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/TransformOperations.h
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * Copyright (C) 2000 Lars Knoll (knoll@kde.org)
- * (C) 2000 Antti Koivisto (koivisto@kde.org)
- * (C) 2000 Dirk Mueller (mueller@kde.org)
- * Copyright (C) 2003, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
- * Copyright (C) 2006 Graham Dennis (graham.dennis@gmail.com)
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#ifndef TransformOperations_h
-#define TransformOperations_h
-
-#include "core/platform/graphics/LayoutSize.h"
-#include "core/platform/graphics/transforms/TransformOperation.h"
-#include "wtf/RefPtr.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-class TransformOperations {
- WTF_MAKE_FAST_ALLOCATED;
-public:
- explicit TransformOperations(bool makeIdentity = false);
-
- bool operator==(const TransformOperations& o) const;
- bool operator!=(const TransformOperations& o) const
- {
- return !(*this == o);
- }
-
- void apply(const FloatSize& sz, TransformationMatrix& t) const
- {
- for (unsigned i = 0; i < m_operations.size(); ++i)
- m_operations[i]->apply(t, sz);
- }
-
- // Return true if any of the operation types are 3D operation types (even if the
- // values describe affine transforms)
- bool has3DOperation() const
- {
- for (unsigned i = 0; i < m_operations.size(); ++i)
- if (m_operations[i]->is3DOperation())
- return true;
- return false;
- }
-
- bool operationsMatch(const TransformOperations&) const;
-
- void clear()
- {
- m_operations.clear();
- }
-
- Vector<RefPtr<TransformOperation> >& operations() { return m_operations; }
- const Vector<RefPtr<TransformOperation> >& operations() const { return m_operations; }
-
- size_t size() const { return m_operations.size(); }
- const TransformOperation* at(size_t index) const { return index < m_operations.size() ? m_operations.at(index).get() : 0; }
-
- TransformOperations blendByMatchingOperations(const TransformOperations& from, const double& progress) const;
- TransformOperations blendByUsingMatrixInterpolation(const TransformOperations& from, double progress) const;
- TransformOperations blend(const TransformOperations& from, double progress) const;
- TransformOperations add(const TransformOperations& addend) const;
-
-private:
- Vector<RefPtr<TransformOperation> > m_operations;
-};
-
-} // namespace WebCore
-
-#endif // TransformOperations_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/TransformState.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/TransformState.cpp
deleted file mode 100644
index 5f9e6bc7e33..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/TransformState.cpp
+++ /dev/null
@@ -1,209 +0,0 @@
-/*
- * Copyright (C) 2011 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/transforms/TransformState.h"
-
-#include "wtf/PassOwnPtr.h"
-
-namespace WebCore {
-
-TransformState& TransformState::operator=(const TransformState& other)
-{
- m_accumulatedOffset = other.m_accumulatedOffset;
- m_mapPoint = other.m_mapPoint;
- m_mapQuad = other.m_mapQuad;
- if (m_mapPoint)
- m_lastPlanarPoint = other.m_lastPlanarPoint;
- if (m_mapQuad)
- m_lastPlanarQuad = other.m_lastPlanarQuad;
- m_accumulatingTransform = other.m_accumulatingTransform;
- m_direction = other.m_direction;
-
- m_accumulatedTransform.clear();
-
- if (other.m_accumulatedTransform)
- m_accumulatedTransform = adoptPtr(new TransformationMatrix(*other.m_accumulatedTransform));
-
- return *this;
-}
-
-void TransformState::translateTransform(const LayoutSize& offset)
-{
- if (m_direction == ApplyTransformDirection)
- m_accumulatedTransform->translateRight(offset.width(), offset.height());
- else
- m_accumulatedTransform->translate(offset.width(), offset.height());
-}
-
-void TransformState::translateMappedCoordinates(const LayoutSize& offset)
-{
- LayoutSize adjustedOffset = (m_direction == ApplyTransformDirection) ? offset : -offset;
- if (m_mapPoint)
- m_lastPlanarPoint.move(adjustedOffset);
- if (m_mapQuad)
- m_lastPlanarQuad.move(adjustedOffset);
-}
-
-void TransformState::move(const LayoutSize& offset, TransformAccumulation accumulate)
-{
- if (accumulate == FlattenTransform || !m_accumulatedTransform)
- m_accumulatedOffset += offset;
- else {
- applyAccumulatedOffset();
- if (m_accumulatingTransform && m_accumulatedTransform) {
- // If we're accumulating into an existing transform, apply the translation.
- translateTransform(offset);
-
- // Then flatten if necessary.
- if (accumulate == FlattenTransform)
- flatten();
- } else
- // Just move the point and/or quad.
- translateMappedCoordinates(offset);
- }
- m_accumulatingTransform = accumulate == AccumulateTransform;
-}
-
-void TransformState::applyAccumulatedOffset()
-{
- LayoutSize offset = m_accumulatedOffset;
- m_accumulatedOffset = LayoutSize();
- if (!offset.isZero()) {
- if (m_accumulatedTransform) {
- translateTransform(offset);
- flatten();
- } else
- translateMappedCoordinates(offset);
- }
-}
-
-// FIXME: We transform AffineTransform to TransformationMatrix. This is rather inefficient.
-void TransformState::applyTransform(const AffineTransform& transformFromContainer, TransformAccumulation accumulate, bool* wasClamped)
-{
- applyTransform(transformFromContainer.toTransformationMatrix(), accumulate, wasClamped);
-}
-
-void TransformState::applyTransform(const TransformationMatrix& transformFromContainer, TransformAccumulation accumulate, bool* wasClamped)
-{
- if (wasClamped)
- *wasClamped = false;
-
- if (transformFromContainer.isIntegerTranslation()) {
- move(LayoutSize(transformFromContainer.e(), transformFromContainer.f()), accumulate);
- return;
- }
-
- applyAccumulatedOffset();
-
- // If we have an accumulated transform from last time, multiply in this transform
- if (m_accumulatedTransform) {
- if (m_direction == ApplyTransformDirection)
- m_accumulatedTransform = adoptPtr(new TransformationMatrix(transformFromContainer * *m_accumulatedTransform));
- else
- m_accumulatedTransform->multiply(transformFromContainer);
- } else if (accumulate == AccumulateTransform) {
- // Make one if we started to accumulate
- m_accumulatedTransform = adoptPtr(new TransformationMatrix(transformFromContainer));
- }
-
- if (accumulate == FlattenTransform) {
- const TransformationMatrix* finalTransform = m_accumulatedTransform ? m_accumulatedTransform.get() : &transformFromContainer;
- flattenWithTransform(*finalTransform, wasClamped);
- }
- m_accumulatingTransform = accumulate == AccumulateTransform;
-}
-
-void TransformState::flatten(bool* wasClamped)
-{
- if (wasClamped)
- *wasClamped = false;
-
- applyAccumulatedOffset();
-
- if (!m_accumulatedTransform) {
- m_accumulatingTransform = false;
- return;
- }
-
- flattenWithTransform(*m_accumulatedTransform, wasClamped);
-}
-
-FloatPoint TransformState::mappedPoint(bool* wasClamped) const
-{
- if (wasClamped)
- *wasClamped = false;
-
- FloatPoint point = m_lastPlanarPoint;
- point.move((m_direction == ApplyTransformDirection) ? m_accumulatedOffset : -m_accumulatedOffset);
- if (!m_accumulatedTransform)
- return point;
-
- if (m_direction == ApplyTransformDirection)
- return m_accumulatedTransform->mapPoint(point);
-
- return m_accumulatedTransform->inverse().projectPoint(point, wasClamped);
-}
-
-FloatQuad TransformState::mappedQuad(bool* wasClamped) const
-{
- if (wasClamped)
- *wasClamped = false;
-
- FloatQuad quad = m_lastPlanarQuad;
- quad.move((m_direction == ApplyTransformDirection) ? m_accumulatedOffset : -m_accumulatedOffset);
- if (!m_accumulatedTransform)
- return quad;
-
- if (m_direction == ApplyTransformDirection)
- return m_accumulatedTransform->mapQuad(quad);
-
- return m_accumulatedTransform->inverse().projectQuad(quad, wasClamped);
-}
-
-void TransformState::flattenWithTransform(const TransformationMatrix& t, bool* wasClamped)
-{
- if (m_direction == ApplyTransformDirection) {
- if (m_mapPoint)
- m_lastPlanarPoint = t.mapPoint(m_lastPlanarPoint);
- if (m_mapQuad)
- m_lastPlanarQuad = t.mapQuad(m_lastPlanarQuad);
- } else {
- TransformationMatrix inverseTransform = t.inverse();
- if (m_mapPoint)
- m_lastPlanarPoint = inverseTransform.projectPoint(m_lastPlanarPoint);
- if (m_mapQuad)
- m_lastPlanarQuad = inverseTransform.projectQuad(m_lastPlanarQuad, wasClamped);
- }
-
- // We could throw away m_accumulatedTransform if we wanted to here, but that
- // would cause thrash when traversing hierarchies with alternating
- // preserve-3d and flat elements.
- if (m_accumulatedTransform)
- m_accumulatedTransform->makeIdentity();
- m_accumulatingTransform = false;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/TransformState.h b/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/TransformState.h
deleted file mode 100644
index 638e417bf17..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/TransformState.h
+++ /dev/null
@@ -1,122 +0,0 @@
-/*
- * Copyright (C) 2011 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TransformState_h
-#define TransformState_h
-
-#include "core/platform/graphics/FloatPoint.h"
-#include "core/platform/graphics/FloatQuad.h"
-#include "core/platform/graphics/IntSize.h"
-#include "core/platform/graphics/LayoutSize.h"
-#include "core/platform/graphics/transforms/AffineTransform.h"
-#include "core/platform/graphics/transforms/TransformationMatrix.h"
-#include "wtf/OwnPtr.h"
-
-namespace WebCore {
-
-class TransformState {
-public:
- enum TransformDirection { ApplyTransformDirection, UnapplyInverseTransformDirection };
- enum TransformAccumulation { FlattenTransform, AccumulateTransform };
-
- TransformState(TransformDirection mappingDirection, const FloatPoint& p, const FloatQuad& quad)
- : m_lastPlanarPoint(p)
- , m_lastPlanarQuad(quad)
- , m_accumulatingTransform(false)
- , m_mapPoint(true)
- , m_mapQuad(true)
- , m_direction(mappingDirection)
- {
- }
-
- TransformState(TransformDirection mappingDirection, const FloatPoint& p)
- : m_lastPlanarPoint(p)
- , m_accumulatingTransform(false)
- , m_mapPoint(true)
- , m_mapQuad(false)
- , m_direction(mappingDirection)
- {
- }
-
- TransformState(TransformDirection mappingDirection, const FloatQuad& quad)
- : m_lastPlanarQuad(quad)
- , m_accumulatingTransform(false)
- , m_mapPoint(false)
- , m_mapQuad(true)
- , m_direction(mappingDirection)
- {
- }
-
- TransformState(const TransformState& other) { *this = other; }
-
- TransformState& operator=(const TransformState&);
-
- void setQuad(const FloatQuad& quad)
- {
- // FIXME: this assumes that the quad being added is in the coordinate system of the current state.
- // This breaks if we're simultaneously mapping a point. https://bugs.webkit.org/show_bug.cgi?id=106680
- ASSERT(!m_mapPoint);
- m_accumulatedOffset = LayoutSize();
- m_lastPlanarQuad = quad;
- }
-
- void move(LayoutUnit x, LayoutUnit y, TransformAccumulation accumulate = FlattenTransform)
- {
- move(LayoutSize(x, y), accumulate);
- }
-
- void move(const LayoutSize&, TransformAccumulation = FlattenTransform);
- void applyTransform(const AffineTransform& transformFromContainer, TransformAccumulation = FlattenTransform, bool* wasClamped = 0);
- void applyTransform(const TransformationMatrix& transformFromContainer, TransformAccumulation = FlattenTransform, bool* wasClamped = 0);
- void flatten(bool* wasClamped = 0);
-
- // Return the coords of the point or quad in the last flattened layer
- FloatPoint lastPlanarPoint() const { return m_lastPlanarPoint; }
- FloatQuad lastPlanarQuad() const { return m_lastPlanarQuad; }
-
- // Return the point or quad mapped through the current transform
- FloatPoint mappedPoint(bool* wasClamped = 0) const;
- FloatQuad mappedQuad(bool* wasClamped = 0) const;
-
-private:
- void translateTransform(const LayoutSize&);
- void translateMappedCoordinates(const LayoutSize&);
- void flattenWithTransform(const TransformationMatrix&, bool* wasClamped);
- void applyAccumulatedOffset();
-
- FloatPoint m_lastPlanarPoint;
- FloatQuad m_lastPlanarQuad;
-
- // We only allocate the transform if we need to
- OwnPtr<TransformationMatrix> m_accumulatedTransform;
- LayoutSize m_accumulatedOffset;
- bool m_accumulatingTransform;
- bool m_mapPoint, m_mapQuad;
- TransformDirection m_direction;
-};
-
-} // namespace WebCore
-
-#endif // TransformState_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/TransformationMatrix.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/TransformationMatrix.cpp
deleted file mode 100644
index e95936b0da8..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/TransformationMatrix.cpp
+++ /dev/null
@@ -1,1531 +0,0 @@
-/*
- * Copyright (C) 2005, 2006 Apple Computer, Inc. All rights reserved.
- * Copyright (C) 2009 Torch Mobile, Inc.
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/transforms/TransformationMatrix.h"
-
-#include "core/platform/graphics/FloatQuad.h"
-#include "core/platform/graphics/FloatRect.h"
-#include "core/platform/graphics/IntRect.h"
-#include "core/platform/graphics/LayoutRect.h"
-#include "core/platform/graphics/skia/SkiaUtils.h"
-#include "core/platform/graphics/transforms/AffineTransform.h"
-
-#include "wtf/Assertions.h"
-#include "wtf/MathExtras.h"
-
-#if CPU(X86_64)
-#include <emmintrin.h>
-#endif
-
-using namespace std;
-
-namespace WebCore {
-
-//
-// Supporting Math Functions
-//
-// This is a set of function from various places (attributed inline) to do things like
-// inversion and decomposition of a 4x4 matrix. They are used throughout the code
-//
-
-//
-// Adapted from Matrix Inversion by Richard Carling, Graphics Gems <http://tog.acm.org/GraphicsGems/index.html>.
-
-// EULA: The Graphics Gems code is copyright-protected. In other words, you cannot claim the text of the code
-// as your own and resell it. Using the code is permitted in any program, product, or library, non-commercial
-// or commercial. Giving credit is not required, though is a nice gesture. The code comes as-is, and if there
-// are any flaws or problems with any Gems code, nobody involved with Gems - authors, editors, publishers, or
-// webmasters - are to be held responsible. Basically, don't be a jerk, and remember that anything free comes
-// with no guarantee.
-
-// A clarification about the storage of matrix elements
-//
-// This class uses a 2 dimensional array internally to store the elements of the matrix. The first index into
-// the array refers to the column that the element lies in; the second index refers to the row.
-//
-// In other words, this is the layout of the matrix:
-//
-// | m_matrix[0][0] m_matrix[1][0] m_matrix[2][0] m_matrix[3][0] |
-// | m_matrix[0][1] m_matrix[1][1] m_matrix[2][1] m_matrix[3][1] |
-// | m_matrix[0][2] m_matrix[1][2] m_matrix[2][2] m_matrix[3][2] |
-// | m_matrix[0][3] m_matrix[1][3] m_matrix[2][3] m_matrix[3][3] |
-
-typedef double Vector4[4];
-typedef double Vector3[3];
-
-const double SMALL_NUMBER = 1.e-8;
-
-// inverse(original_matrix, inverse_matrix)
-//
-// calculate the inverse of a 4x4 matrix
-//
-// -1
-// A = ___1__ adjoint A
-// det A
-
-// double = determinant2x2(double a, double b, double c, double d)
-//
-// calculate the determinant of a 2x2 matrix.
-
-static double determinant2x2(double a, double b, double c, double d)
-{
- return a * d - b * c;
-}
-
-// double = determinant3x3(a1, a2, a3, b1, b2, b3, c1, c2, c3)
-//
-// Calculate the determinant of a 3x3 matrix
-// in the form
-//
-// | a1, b1, c1 |
-// | a2, b2, c2 |
-// | a3, b3, c3 |
-
-static double determinant3x3(double a1, double a2, double a3, double b1, double b2, double b3, double c1, double c2, double c3)
-{
- return a1 * determinant2x2(b2, b3, c2, c3)
- - b1 * determinant2x2(a2, a3, c2, c3)
- + c1 * determinant2x2(a2, a3, b2, b3);
-}
-
-// double = determinant4x4(matrix)
-//
-// calculate the determinant of a 4x4 matrix.
-
-static double determinant4x4(const TransformationMatrix::Matrix4& m)
-{
- // Assign to individual variable names to aid selecting
- // correct elements
-
- double a1 = m[0][0];
- double b1 = m[0][1];
- double c1 = m[0][2];
- double d1 = m[0][3];
-
- double a2 = m[1][0];
- double b2 = m[1][1];
- double c2 = m[1][2];
- double d2 = m[1][3];
-
- double a3 = m[2][0];
- double b3 = m[2][1];
- double c3 = m[2][2];
- double d3 = m[2][3];
-
- double a4 = m[3][0];
- double b4 = m[3][1];
- double c4 = m[3][2];
- double d4 = m[3][3];
-
- return a1 * determinant3x3(b2, b3, b4, c2, c3, c4, d2, d3, d4)
- - b1 * determinant3x3(a2, a3, a4, c2, c3, c4, d2, d3, d4)
- + c1 * determinant3x3(a2, a3, a4, b2, b3, b4, d2, d3, d4)
- - d1 * determinant3x3(a2, a3, a4, b2, b3, b4, c2, c3, c4);
-}
-
-// adjoint( original_matrix, inverse_matrix )
-//
-// calculate the adjoint of a 4x4 matrix
-//
-// Let a denote the minor determinant of matrix A obtained by
-// ij
-//
-// deleting the ith row and jth column from A.
-//
-// i+j
-// Let b = (-1) a
-// ij ji
-//
-// The matrix B = (b ) is the adjoint of A
-// ij
-
-static void adjoint(const TransformationMatrix::Matrix4& matrix, TransformationMatrix::Matrix4& result)
-{
- // Assign to individual variable names to aid
- // selecting correct values
- double a1 = matrix[0][0];
- double b1 = matrix[0][1];
- double c1 = matrix[0][2];
- double d1 = matrix[0][3];
-
- double a2 = matrix[1][0];
- double b2 = matrix[1][1];
- double c2 = matrix[1][2];
- double d2 = matrix[1][3];
-
- double a3 = matrix[2][0];
- double b3 = matrix[2][1];
- double c3 = matrix[2][2];
- double d3 = matrix[2][3];
-
- double a4 = matrix[3][0];
- double b4 = matrix[3][1];
- double c4 = matrix[3][2];
- double d4 = matrix[3][3];
-
- // Row column labeling reversed since we transpose rows & columns
- result[0][0] = determinant3x3(b2, b3, b4, c2, c3, c4, d2, d3, d4);
- result[1][0] = - determinant3x3(a2, a3, a4, c2, c3, c4, d2, d3, d4);
- result[2][0] = determinant3x3(a2, a3, a4, b2, b3, b4, d2, d3, d4);
- result[3][0] = - determinant3x3(a2, a3, a4, b2, b3, b4, c2, c3, c4);
-
- result[0][1] = - determinant3x3(b1, b3, b4, c1, c3, c4, d1, d3, d4);
- result[1][1] = determinant3x3(a1, a3, a4, c1, c3, c4, d1, d3, d4);
- result[2][1] = - determinant3x3(a1, a3, a4, b1, b3, b4, d1, d3, d4);
- result[3][1] = determinant3x3(a1, a3, a4, b1, b3, b4, c1, c3, c4);
-
- result[0][2] = determinant3x3(b1, b2, b4, c1, c2, c4, d1, d2, d4);
- result[1][2] = - determinant3x3(a1, a2, a4, c1, c2, c4, d1, d2, d4);
- result[2][2] = determinant3x3(a1, a2, a4, b1, b2, b4, d1, d2, d4);
- result[3][2] = - determinant3x3(a1, a2, a4, b1, b2, b4, c1, c2, c4);
-
- result[0][3] = - determinant3x3(b1, b2, b3, c1, c2, c3, d1, d2, d3);
- result[1][3] = determinant3x3(a1, a2, a3, c1, c2, c3, d1, d2, d3);
- result[2][3] = - determinant3x3(a1, a2, a3, b1, b2, b3, d1, d2, d3);
- result[3][3] = determinant3x3(a1, a2, a3, b1, b2, b3, c1, c2, c3);
-}
-
-// Returns false if the matrix is not invertible
-static bool inverse(const TransformationMatrix::Matrix4& matrix, TransformationMatrix::Matrix4& result)
-{
- // Calculate the adjoint matrix
- adjoint(matrix, result);
-
- // Calculate the 4x4 determinant
- // If the determinant is zero,
- // then the inverse matrix is not unique.
- double det = determinant4x4(matrix);
-
- if (fabs(det) < SMALL_NUMBER)
- return false;
-
- // Scale the adjoint matrix to get the inverse
-
- for (int i = 0; i < 4; i++)
- for (int j = 0; j < 4; j++)
- result[i][j] = result[i][j] / det;
-
- return true;
-}
-
-// End of code adapted from Matrix Inversion by Richard Carling
-
-// Perform a decomposition on the passed matrix, return false if unsuccessful
-// From Graphics Gems: unmatrix.c
-
-// Transpose rotation portion of matrix a, return b
-static void transposeMatrix4(const TransformationMatrix::Matrix4& a, TransformationMatrix::Matrix4& b)
-{
- for (int i = 0; i < 4; i++)
- for (int j = 0; j < 4; j++)
- b[i][j] = a[j][i];
-}
-
-// Multiply a homogeneous point by a matrix and return the transformed point
-static void v4MulPointByMatrix(const Vector4 p, const TransformationMatrix::Matrix4& m, Vector4 result)
-{
- result[0] = (p[0] * m[0][0]) + (p[1] * m[1][0]) +
- (p[2] * m[2][0]) + (p[3] * m[3][0]);
- result[1] = (p[0] * m[0][1]) + (p[1] * m[1][1]) +
- (p[2] * m[2][1]) + (p[3] * m[3][1]);
- result[2] = (p[0] * m[0][2]) + (p[1] * m[1][2]) +
- (p[2] * m[2][2]) + (p[3] * m[3][2]);
- result[3] = (p[0] * m[0][3]) + (p[1] * m[1][3]) +
- (p[2] * m[2][3]) + (p[3] * m[3][3]);
-}
-
-static double v3Length(Vector3 a)
-{
- return sqrt((a[0] * a[0]) + (a[1] * a[1]) + (a[2] * a[2]));
-}
-
-static void v3Scale(Vector3 v, double desiredLength)
-{
- double len = v3Length(v);
- if (len != 0) {
- double l = desiredLength / len;
- v[0] *= l;
- v[1] *= l;
- v[2] *= l;
- }
-}
-
-static double v3Dot(const Vector3 a, const Vector3 b)
-{
- return (a[0] * b[0]) + (a[1] * b[1]) + (a[2] * b[2]);
-}
-
-// Make a linear combination of two vectors and return the result.
-// result = (a * ascl) + (b * bscl)
-static void v3Combine(const Vector3 a, const Vector3 b, Vector3 result, double ascl, double bscl)
-{
- result[0] = (ascl * a[0]) + (bscl * b[0]);
- result[1] = (ascl * a[1]) + (bscl * b[1]);
- result[2] = (ascl * a[2]) + (bscl * b[2]);
-}
-
-// Return the cross product result = a cross b */
-static void v3Cross(const Vector3 a, const Vector3 b, Vector3 result)
-{
- result[0] = (a[1] * b[2]) - (a[2] * b[1]);
- result[1] = (a[2] * b[0]) - (a[0] * b[2]);
- result[2] = (a[0] * b[1]) - (a[1] * b[0]);
-}
-
-static bool decompose(const TransformationMatrix::Matrix4& mat, TransformationMatrix::DecomposedType& result)
-{
- TransformationMatrix::Matrix4 localMatrix;
- memcpy(localMatrix, mat, sizeof(TransformationMatrix::Matrix4));
-
- // Normalize the matrix.
- if (localMatrix[3][3] == 0)
- return false;
-
- int i, j;
- for (i = 0; i < 4; i++)
- for (j = 0; j < 4; j++)
- localMatrix[i][j] /= localMatrix[3][3];
-
- // perspectiveMatrix is used to solve for perspective, but it also provides
- // an easy way to test for singularity of the upper 3x3 component.
- TransformationMatrix::Matrix4 perspectiveMatrix;
- memcpy(perspectiveMatrix, localMatrix, sizeof(TransformationMatrix::Matrix4));
- for (i = 0; i < 3; i++)
- perspectiveMatrix[i][3] = 0;
- perspectiveMatrix[3][3] = 1;
-
- if (determinant4x4(perspectiveMatrix) == 0)
- return false;
-
- // First, isolate perspective. This is the messiest.
- if (localMatrix[0][3] != 0 || localMatrix[1][3] != 0 || localMatrix[2][3] != 0) {
- // rightHandSide is the right hand side of the equation.
- Vector4 rightHandSide;
- rightHandSide[0] = localMatrix[0][3];
- rightHandSide[1] = localMatrix[1][3];
- rightHandSide[2] = localMatrix[2][3];
- rightHandSide[3] = localMatrix[3][3];
-
- // Solve the equation by inverting perspectiveMatrix and multiplying
- // rightHandSide by the inverse. (This is the easiest way, not
- // necessarily the best.)
- TransformationMatrix::Matrix4 inversePerspectiveMatrix, transposedInversePerspectiveMatrix;
- inverse(perspectiveMatrix, inversePerspectiveMatrix);
- transposeMatrix4(inversePerspectiveMatrix, transposedInversePerspectiveMatrix);
-
- Vector4 perspectivePoint;
- v4MulPointByMatrix(rightHandSide, transposedInversePerspectiveMatrix, perspectivePoint);
-
- result.perspectiveX = perspectivePoint[0];
- result.perspectiveY = perspectivePoint[1];
- result.perspectiveZ = perspectivePoint[2];
- result.perspectiveW = perspectivePoint[3];
-
- // Clear the perspective partition
- localMatrix[0][3] = localMatrix[1][3] = localMatrix[2][3] = 0;
- localMatrix[3][3] = 1;
- } else {
- // No perspective.
- result.perspectiveX = result.perspectiveY = result.perspectiveZ = 0;
- result.perspectiveW = 1;
- }
-
- // Next take care of translation (easy).
- result.translateX = localMatrix[3][0];
- localMatrix[3][0] = 0;
- result.translateY = localMatrix[3][1];
- localMatrix[3][1] = 0;
- result.translateZ = localMatrix[3][2];
- localMatrix[3][2] = 0;
-
- // Vector4 type and functions need to be added to the common set.
- Vector3 row[3], pdum3;
-
- // Now get scale and shear.
- for (i = 0; i < 3; i++) {
- row[i][0] = localMatrix[i][0];
- row[i][1] = localMatrix[i][1];
- row[i][2] = localMatrix[i][2];
- }
-
- // Compute X scale factor and normalize first row.
- result.scaleX = v3Length(row[0]);
- v3Scale(row[0], 1.0);
-
- // Compute XY shear factor and make 2nd row orthogonal to 1st.
- result.skewXY = v3Dot(row[0], row[1]);
- v3Combine(row[1], row[0], row[1], 1.0, -result.skewXY);
-
- // Now, compute Y scale and normalize 2nd row.
- result.scaleY = v3Length(row[1]);
- v3Scale(row[1], 1.0);
- result.skewXY /= result.scaleY;
-
- // Compute XZ and YZ shears, orthogonalize 3rd row.
- result.skewXZ = v3Dot(row[0], row[2]);
- v3Combine(row[2], row[0], row[2], 1.0, -result.skewXZ);
- result.skewYZ = v3Dot(row[1], row[2]);
- v3Combine(row[2], row[1], row[2], 1.0, -result.skewYZ);
-
- // Next, get Z scale and normalize 3rd row.
- result.scaleZ = v3Length(row[2]);
- v3Scale(row[2], 1.0);
- result.skewXZ /= result.scaleZ;
- result.skewYZ /= result.scaleZ;
-
- // At this point, the matrix (in rows[]) is orthonormal.
- // Check for a coordinate system flip. If the determinant
- // is -1, then negate the matrix and the scaling factors.
- v3Cross(row[1], row[2], pdum3);
- if (v3Dot(row[0], pdum3) < 0) {
-
- result.scaleX *= -1;
- result.scaleY *= -1;
- result.scaleZ *= -1;
-
- for (i = 0; i < 3; i++) {
- row[i][0] *= -1;
- row[i][1] *= -1;
- row[i][2] *= -1;
- }
- }
-
- // Now, get the rotations out, as described in the gem.
-
- // FIXME - Add the ability to return either quaternions (which are
- // easier to recompose with) or Euler angles (rx, ry, rz), which
- // are easier for authors to deal with. The latter will only be useful
- // when we fix https://bugs.webkit.org/show_bug.cgi?id=23799, so I
- // will leave the Euler angle code here for now.
-
- // ret.rotateY = asin(-row[0][2]);
- // if (cos(ret.rotateY) != 0) {
- // ret.rotateX = atan2(row[1][2], row[2][2]);
- // ret.rotateZ = atan2(row[0][1], row[0][0]);
- // } else {
- // ret.rotateX = atan2(-row[2][0], row[1][1]);
- // ret.rotateZ = 0;
- // }
-
- double s, t, x, y, z, w;
-
- t = row[0][0] + row[1][1] + row[2][2] + 1.0;
-
- if (t > 1e-4) {
- s = 0.5 / sqrt(t);
- w = 0.25 / s;
- x = (row[2][1] - row[1][2]) * s;
- y = (row[0][2] - row[2][0]) * s;
- z = (row[1][0] - row[0][1]) * s;
- } else if (row[0][0] > row[1][1] && row[0][0] > row[2][2]) {
- s = sqrt (1.0 + row[0][0] - row[1][1] - row[2][2]) * 2.0; // S=4*qx
- x = 0.25 * s;
- y = (row[0][1] + row[1][0]) / s;
- z = (row[0][2] + row[2][0]) / s;
- w = (row[2][1] - row[1][2]) / s;
- } else if (row[1][1] > row[2][2]) {
- s = sqrt (1.0 + row[1][1] - row[0][0] - row[2][2]) * 2.0; // S=4*qy
- x = (row[0][1] + row[1][0]) / s;
- y = 0.25 * s;
- z = (row[1][2] + row[2][1]) / s;
- w = (row[0][2] - row[2][0]) / s;
- } else {
- s = sqrt(1.0 + row[2][2] - row[0][0] - row[1][1]) * 2.0; // S=4*qz
- x = (row[0][2] + row[2][0]) / s;
- y = (row[1][2] + row[2][1]) / s;
- z = 0.25 * s;
- w = (row[1][0] - row[0][1]) / s;
- }
-
- result.quaternionX = x;
- result.quaternionY = y;
- result.quaternionZ = z;
- result.quaternionW = w;
-
- return true;
-}
-
-// Perform a spherical linear interpolation between the two
-// passed quaternions with 0 <= t <= 1
-static void slerp(double qa[4], const double qb[4], double t)
-{
- double ax, ay, az, aw;
- double bx, by, bz, bw;
- double cx, cy, cz, cw;
- double angle;
- double th, invth, scale, invscale;
-
- ax = qa[0]; ay = qa[1]; az = qa[2]; aw = qa[3];
- bx = qb[0]; by = qb[1]; bz = qb[2]; bw = qb[3];
-
- angle = ax * bx + ay * by + az * bz + aw * bw;
-
- if (angle < 0.0) {
- ax = -ax; ay = -ay;
- az = -az; aw = -aw;
- angle = -angle;
- }
-
- if (angle + 1.0 > .05) {
- if (1.0 - angle >= .05) {
- th = acos (angle);
- invth = 1.0 / sin (th);
- scale = sin (th * (1.0 - t)) * invth;
- invscale = sin (th * t) * invth;
- } else {
- scale = 1.0 - t;
- invscale = t;
- }
- } else {
- bx = -ay;
- by = ax;
- bz = -aw;
- bw = az;
- scale = sin(piDouble * (.5 - t));
- invscale = sin (piDouble * t);
- }
-
- cx = ax * scale + bx * invscale;
- cy = ay * scale + by * invscale;
- cz = az * scale + bz * invscale;
- cw = aw * scale + bw * invscale;
-
- qa[0] = cx; qa[1] = cy; qa[2] = cz; qa[3] = cw;
-}
-
-// End of Supporting Math Functions
-
-TransformationMatrix::TransformationMatrix(const AffineTransform& t)
-{
- setMatrix(t.a(), t.b(), t.c(), t.d(), t.e(), t.f());
-}
-
-TransformationMatrix& TransformationMatrix::scale(double s)
-{
- return scaleNonUniform(s, s);
-}
-
-TransformationMatrix& TransformationMatrix::rotateFromVector(double x, double y)
-{
- return rotate(rad2deg(atan2(y, x)));
-}
-
-TransformationMatrix& TransformationMatrix::flipX()
-{
- return scaleNonUniform(-1.0, 1.0);
-}
-
-TransformationMatrix& TransformationMatrix::flipY()
-{
- return scaleNonUniform(1.0, -1.0);
-}
-
-FloatPoint TransformationMatrix::projectPoint(const FloatPoint& p, bool* clamped) const
-{
- // This is basically raytracing. We have a point in the destination
- // plane with z=0, and we cast a ray parallel to the z-axis from that
- // point to find the z-position at which it intersects the z=0 plane
- // with the transform applied. Once we have that point we apply the
- // inverse transform to find the corresponding point in the source
- // space.
- //
- // Given a plane with normal Pn, and a ray starting at point R0 and
- // with direction defined by the vector Rd, we can find the
- // intersection point as a distance d from R0 in units of Rd by:
- //
- // d = -dot (Pn', R0) / dot (Pn', Rd)
- if (clamped)
- *clamped = false;
-
- if (m33() == 0) {
- // In this case, the projection plane is parallel to the ray we are trying to
- // trace, and there is no well-defined value for the projection.
- return FloatPoint();
- }
-
- double x = p.x();
- double y = p.y();
- double z = -(m13() * x + m23() * y + m43()) / m33();
-
- // FIXME: use multVecMatrix()
- double outX = x * m11() + y * m21() + z * m31() + m41();
- double outY = x * m12() + y * m22() + z * m32() + m42();
-
- double w = x * m14() + y * m24() + z * m34() + m44();
- if (w <= 0) {
- // Using int max causes overflow when other code uses the projected point. To
- // represent infinity yet reduce the risk of overflow, we use a large but
- // not-too-large number here when clamping.
- const int largeNumber = 100000000 / kFixedPointDenominator;
- outX = copysign(largeNumber, outX);
- outY = copysign(largeNumber, outY);
- if (clamped)
- *clamped = true;
- } else if (w != 1) {
- outX /= w;
- outY /= w;
- }
-
- return FloatPoint(static_cast<float>(outX), static_cast<float>(outY));
-}
-
-FloatQuad TransformationMatrix::projectQuad(const FloatQuad& q, bool* clamped) const
-{
- FloatQuad projectedQuad;
-
- bool clamped1 = false;
- bool clamped2 = false;
- bool clamped3 = false;
- bool clamped4 = false;
-
- projectedQuad.setP1(projectPoint(q.p1(), &clamped1));
- projectedQuad.setP2(projectPoint(q.p2(), &clamped2));
- projectedQuad.setP3(projectPoint(q.p3(), &clamped3));
- projectedQuad.setP4(projectPoint(q.p4(), &clamped4));
-
- if (clamped)
- *clamped = clamped1 || clamped2 || clamped3 || clamped4;
-
- // If all points on the quad had w < 0, then the entire quad would not be visible to the projected surface.
- bool everythingWasClipped = clamped1 && clamped2 && clamped3 && clamped4;
- if (everythingWasClipped)
- return FloatQuad();
-
- return projectedQuad;
-}
-
-static float clampEdgeValue(float f)
-{
- ASSERT(!std::isnan(f));
- return min<float>(max<float>(f, -LayoutUnit::max() / 2), LayoutUnit::max() / 2);
-}
-
-LayoutRect TransformationMatrix::clampedBoundsOfProjectedQuad(const FloatQuad& q) const
-{
- FloatRect mappedQuadBounds = projectQuad(q).boundingBox();
-
- float left = clampEdgeValue(floorf(mappedQuadBounds.x()));
- float top = clampEdgeValue(floorf(mappedQuadBounds.y()));
-
- float right;
- if (std::isinf(mappedQuadBounds.x()) && std::isinf(mappedQuadBounds.width()))
- right = LayoutUnit::max() / 2;
- else
- right = clampEdgeValue(ceilf(mappedQuadBounds.maxX()));
-
- float bottom;
- if (std::isinf(mappedQuadBounds.y()) && std::isinf(mappedQuadBounds.height()))
- bottom = LayoutUnit::max() / 2;
- else
- bottom = clampEdgeValue(ceilf(mappedQuadBounds.maxY()));
-
- return LayoutRect(LayoutUnit::clamp(left), LayoutUnit::clamp(top), LayoutUnit::clamp(right - left), LayoutUnit::clamp(bottom - top));
-}
-
-FloatPoint TransformationMatrix::mapPoint(const FloatPoint& p) const
-{
- if (isIdentityOrTranslation())
- return FloatPoint(p.x() + static_cast<float>(m_matrix[3][0]), p.y() + static_cast<float>(m_matrix[3][1]));
-
- return internalMapPoint(p);
-}
-
-FloatPoint3D TransformationMatrix::mapPoint(const FloatPoint3D& p) const
-{
- if (isIdentityOrTranslation())
- return FloatPoint3D(p.x() + static_cast<float>(m_matrix[3][0]),
- p.y() + static_cast<float>(m_matrix[3][1]),
- p.z() + static_cast<float>(m_matrix[3][2]));
-
- return internalMapPoint(p);
-}
-
-IntRect TransformationMatrix::mapRect(const IntRect &rect) const
-{
- return enclosingIntRect(mapRect(FloatRect(rect)));
-}
-
-LayoutRect TransformationMatrix::mapRect(const LayoutRect& r) const
-{
- return enclosingLayoutRect(mapRect(FloatRect(r)));
-}
-
-FloatRect TransformationMatrix::mapRect(const FloatRect& r) const
-{
- if (isIdentityOrTranslation()) {
- FloatRect mappedRect(r);
- mappedRect.move(static_cast<float>(m_matrix[3][0]), static_cast<float>(m_matrix[3][1]));
- return mappedRect;
- }
-
- FloatQuad result;
-
- float maxX = r.maxX();
- float maxY = r.maxY();
- result.setP1(internalMapPoint(FloatPoint(r.x(), r.y())));
- result.setP2(internalMapPoint(FloatPoint(maxX, r.y())));
- result.setP3(internalMapPoint(FloatPoint(maxX, maxY)));
- result.setP4(internalMapPoint(FloatPoint(r.x(), maxY)));
-
- return result.boundingBox();
-}
-
-FloatQuad TransformationMatrix::mapQuad(const FloatQuad& q) const
-{
- if (isIdentityOrTranslation()) {
- FloatQuad mappedQuad(q);
- mappedQuad.move(static_cast<float>(m_matrix[3][0]), static_cast<float>(m_matrix[3][1]));
- return mappedQuad;
- }
-
- FloatQuad result;
- result.setP1(internalMapPoint(q.p1()));
- result.setP2(internalMapPoint(q.p2()));
- result.setP3(internalMapPoint(q.p3()));
- result.setP4(internalMapPoint(q.p4()));
- return result;
-}
-
-TransformationMatrix& TransformationMatrix::scaleNonUniform(double sx, double sy)
-{
- m_matrix[0][0] *= sx;
- m_matrix[0][1] *= sx;
- m_matrix[0][2] *= sx;
- m_matrix[0][3] *= sx;
-
- m_matrix[1][0] *= sy;
- m_matrix[1][1] *= sy;
- m_matrix[1][2] *= sy;
- m_matrix[1][3] *= sy;
- return *this;
-}
-
-TransformationMatrix& TransformationMatrix::scale3d(double sx, double sy, double sz)
-{
- scaleNonUniform(sx, sy);
-
- m_matrix[2][0] *= sz;
- m_matrix[2][1] *= sz;
- m_matrix[2][2] *= sz;
- m_matrix[2][3] *= sz;
- return *this;
-}
-
-TransformationMatrix& TransformationMatrix::rotate3d(double x, double y, double z, double angle)
-{
- // Normalize the axis of rotation
- double length = sqrt(x * x + y * y + z * z);
- if (length == 0) {
- // A direction vector that cannot be normalized, such as [0, 0, 0], will cause the rotation to not be applied.
- return *this;
- } else if (length != 1) {
- x /= length;
- y /= length;
- z /= length;
- }
-
- // Angles are in degrees. Switch to radians.
- angle = deg2rad(angle);
-
- double sinTheta = sin(angle);
- double cosTheta = cos(angle);
-
- TransformationMatrix mat;
-
- // Optimize cases where the axis is along a major axis
- if (x == 1.0 && y == 0.0 && z == 0.0) {
- mat.m_matrix[0][0] = 1.0;
- mat.m_matrix[0][1] = 0.0;
- mat.m_matrix[0][2] = 0.0;
- mat.m_matrix[1][0] = 0.0;
- mat.m_matrix[1][1] = cosTheta;
- mat.m_matrix[1][2] = sinTheta;
- mat.m_matrix[2][0] = 0.0;
- mat.m_matrix[2][1] = -sinTheta;
- mat.m_matrix[2][2] = cosTheta;
- mat.m_matrix[0][3] = mat.m_matrix[1][3] = mat.m_matrix[2][3] = 0.0;
- mat.m_matrix[3][0] = mat.m_matrix[3][1] = mat.m_matrix[3][2] = 0.0;
- mat.m_matrix[3][3] = 1.0;
- } else if (x == 0.0 && y == 1.0 && z == 0.0) {
- mat.m_matrix[0][0] = cosTheta;
- mat.m_matrix[0][1] = 0.0;
- mat.m_matrix[0][2] = -sinTheta;
- mat.m_matrix[1][0] = 0.0;
- mat.m_matrix[1][1] = 1.0;
- mat.m_matrix[1][2] = 0.0;
- mat.m_matrix[2][0] = sinTheta;
- mat.m_matrix[2][1] = 0.0;
- mat.m_matrix[2][2] = cosTheta;
- mat.m_matrix[0][3] = mat.m_matrix[1][3] = mat.m_matrix[2][3] = 0.0;
- mat.m_matrix[3][0] = mat.m_matrix[3][1] = mat.m_matrix[3][2] = 0.0;
- mat.m_matrix[3][3] = 1.0;
- } else if (x == 0.0 && y == 0.0 && z == 1.0) {
- mat.m_matrix[0][0] = cosTheta;
- mat.m_matrix[0][1] = sinTheta;
- mat.m_matrix[0][2] = 0.0;
- mat.m_matrix[1][0] = -sinTheta;
- mat.m_matrix[1][1] = cosTheta;
- mat.m_matrix[1][2] = 0.0;
- mat.m_matrix[2][0] = 0.0;
- mat.m_matrix[2][1] = 0.0;
- mat.m_matrix[2][2] = 1.0;
- mat.m_matrix[0][3] = mat.m_matrix[1][3] = mat.m_matrix[2][3] = 0.0;
- mat.m_matrix[3][0] = mat.m_matrix[3][1] = mat.m_matrix[3][2] = 0.0;
- mat.m_matrix[3][3] = 1.0;
- } else {
- // This case is the rotation about an arbitrary unit vector.
- //
- // Formula is adapted from Wikipedia article on Rotation matrix,
- // http://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle
- //
- // An alternate resource with the same matrix: http://www.fastgraph.com/makegames/3drotation/
- //
- double oneMinusCosTheta = 1 - cosTheta;
- mat.m_matrix[0][0] = cosTheta + x * x * oneMinusCosTheta;
- mat.m_matrix[0][1] = y * x * oneMinusCosTheta + z * sinTheta;
- mat.m_matrix[0][2] = z * x * oneMinusCosTheta - y * sinTheta;
- mat.m_matrix[1][0] = x * y * oneMinusCosTheta - z * sinTheta;
- mat.m_matrix[1][1] = cosTheta + y * y * oneMinusCosTheta;
- mat.m_matrix[1][2] = z * y * oneMinusCosTheta + x * sinTheta;
- mat.m_matrix[2][0] = x * z * oneMinusCosTheta + y * sinTheta;
- mat.m_matrix[2][1] = y * z * oneMinusCosTheta - x * sinTheta;
- mat.m_matrix[2][2] = cosTheta + z * z * oneMinusCosTheta;
- mat.m_matrix[0][3] = mat.m_matrix[1][3] = mat.m_matrix[2][3] = 0.0;
- mat.m_matrix[3][0] = mat.m_matrix[3][1] = mat.m_matrix[3][2] = 0.0;
- mat.m_matrix[3][3] = 1.0;
- }
- multiply(mat);
- return *this;
-}
-
-TransformationMatrix& TransformationMatrix::rotate3d(double rx, double ry, double rz)
-{
- // Angles are in degrees. Switch to radians.
- rx = deg2rad(rx);
- ry = deg2rad(ry);
- rz = deg2rad(rz);
-
- TransformationMatrix mat;
-
- double sinTheta = sin(rz);
- double cosTheta = cos(rz);
-
- mat.m_matrix[0][0] = cosTheta;
- mat.m_matrix[0][1] = sinTheta;
- mat.m_matrix[0][2] = 0.0;
- mat.m_matrix[1][0] = -sinTheta;
- mat.m_matrix[1][1] = cosTheta;
- mat.m_matrix[1][2] = 0.0;
- mat.m_matrix[2][0] = 0.0;
- mat.m_matrix[2][1] = 0.0;
- mat.m_matrix[2][2] = 1.0;
- mat.m_matrix[0][3] = mat.m_matrix[1][3] = mat.m_matrix[2][3] = 0.0;
- mat.m_matrix[3][0] = mat.m_matrix[3][1] = mat.m_matrix[3][2] = 0.0;
- mat.m_matrix[3][3] = 1.0;
-
- TransformationMatrix rmat(mat);
-
- sinTheta = sin(ry);
- cosTheta = cos(ry);
-
- mat.m_matrix[0][0] = cosTheta;
- mat.m_matrix[0][1] = 0.0;
- mat.m_matrix[0][2] = -sinTheta;
- mat.m_matrix[1][0] = 0.0;
- mat.m_matrix[1][1] = 1.0;
- mat.m_matrix[1][2] = 0.0;
- mat.m_matrix[2][0] = sinTheta;
- mat.m_matrix[2][1] = 0.0;
- mat.m_matrix[2][2] = cosTheta;
- mat.m_matrix[0][3] = mat.m_matrix[1][3] = mat.m_matrix[2][3] = 0.0;
- mat.m_matrix[3][0] = mat.m_matrix[3][1] = mat.m_matrix[3][2] = 0.0;
- mat.m_matrix[3][3] = 1.0;
-
- rmat.multiply(mat);
-
- sinTheta = sin(rx);
- cosTheta = cos(rx);
-
- mat.m_matrix[0][0] = 1.0;
- mat.m_matrix[0][1] = 0.0;
- mat.m_matrix[0][2] = 0.0;
- mat.m_matrix[1][0] = 0.0;
- mat.m_matrix[1][1] = cosTheta;
- mat.m_matrix[1][2] = sinTheta;
- mat.m_matrix[2][0] = 0.0;
- mat.m_matrix[2][1] = -sinTheta;
- mat.m_matrix[2][2] = cosTheta;
- mat.m_matrix[0][3] = mat.m_matrix[1][3] = mat.m_matrix[2][3] = 0.0;
- mat.m_matrix[3][0] = mat.m_matrix[3][1] = mat.m_matrix[3][2] = 0.0;
- mat.m_matrix[3][3] = 1.0;
-
- rmat.multiply(mat);
-
- multiply(rmat);
- return *this;
-}
-
-TransformationMatrix& TransformationMatrix::translate(double tx, double ty)
-{
- m_matrix[3][0] += tx * m_matrix[0][0] + ty * m_matrix[1][0];
- m_matrix[3][1] += tx * m_matrix[0][1] + ty * m_matrix[1][1];
- m_matrix[3][2] += tx * m_matrix[0][2] + ty * m_matrix[1][2];
- m_matrix[3][3] += tx * m_matrix[0][3] + ty * m_matrix[1][3];
- return *this;
-}
-
-TransformationMatrix& TransformationMatrix::translate3d(double tx, double ty, double tz)
-{
- m_matrix[3][0] += tx * m_matrix[0][0] + ty * m_matrix[1][0] + tz * m_matrix[2][0];
- m_matrix[3][1] += tx * m_matrix[0][1] + ty * m_matrix[1][1] + tz * m_matrix[2][1];
- m_matrix[3][2] += tx * m_matrix[0][2] + ty * m_matrix[1][2] + tz * m_matrix[2][2];
- m_matrix[3][3] += tx * m_matrix[0][3] + ty * m_matrix[1][3] + tz * m_matrix[2][3];
- return *this;
-}
-
-TransformationMatrix& TransformationMatrix::translateRight(double tx, double ty)
-{
- if (tx != 0) {
- m_matrix[0][0] += m_matrix[0][3] * tx;
- m_matrix[1][0] += m_matrix[1][3] * tx;
- m_matrix[2][0] += m_matrix[2][3] * tx;
- m_matrix[3][0] += m_matrix[3][3] * tx;
- }
-
- if (ty != 0) {
- m_matrix[0][1] += m_matrix[0][3] * ty;
- m_matrix[1][1] += m_matrix[1][3] * ty;
- m_matrix[2][1] += m_matrix[2][3] * ty;
- m_matrix[3][1] += m_matrix[3][3] * ty;
- }
-
- return *this;
-}
-
-TransformationMatrix& TransformationMatrix::translateRight3d(double tx, double ty, double tz)
-{
- translateRight(tx, ty);
- if (tz != 0) {
- m_matrix[0][2] += m_matrix[0][3] * tz;
- m_matrix[1][2] += m_matrix[1][3] * tz;
- m_matrix[2][2] += m_matrix[2][3] * tz;
- m_matrix[3][2] += m_matrix[3][3] * tz;
- }
-
- return *this;
-}
-
-TransformationMatrix& TransformationMatrix::skew(double sx, double sy)
-{
- // angles are in degrees. Switch to radians
- sx = deg2rad(sx);
- sy = deg2rad(sy);
-
- TransformationMatrix mat;
- mat.m_matrix[0][1] = tan(sy); // note that the y shear goes in the first row
- mat.m_matrix[1][0] = tan(sx); // and the x shear in the second row
-
- multiply(mat);
- return *this;
-}
-
-TransformationMatrix& TransformationMatrix::applyPerspective(double p)
-{
- TransformationMatrix mat;
- if (p != 0)
- mat.m_matrix[2][3] = -1/p;
-
- multiply(mat);
- return *this;
-}
-
-TransformationMatrix TransformationMatrix::rectToRect(const FloatRect& from, const FloatRect& to)
-{
- ASSERT(!from.isEmpty());
- return TransformationMatrix(to.width() / from.width(),
- 0, 0,
- to.height() / from.height(),
- to.x() - from.x(),
- to.y() - from.y());
-}
-
-// this = mat * this.
-TransformationMatrix& TransformationMatrix::multiply(const TransformationMatrix& mat)
-{
-#if CPU(APPLE_ARMV7S)
- double* leftMatrix = &(m_matrix[0][0]);
- const double* rightMatrix = &(mat.m_matrix[0][0]);
- asm volatile (// First row of leftMatrix.
- "mov r3, %[leftMatrix]\n\t"
- "vld1.64 { d16-d19 }, [%[leftMatrix], :128]!\n\t"
- "vld1.64 { d0-d3}, [%[rightMatrix], :128]!\n\t"
- "vmul.f64 d4, d0, d16\n\t"
- "vld1.64 { d20-d23 }, [%[leftMatrix], :128]!\n\t"
- "vmla.f64 d4, d1, d20\n\t"
- "vld1.64 { d24-d27 }, [%[leftMatrix], :128]!\n\t"
- "vmla.f64 d4, d2, d24\n\t"
- "vld1.64 { d28-d31 }, [%[leftMatrix], :128]!\n\t"
- "vmla.f64 d4, d3, d28\n\t"
-
- "vmul.f64 d5, d0, d17\n\t"
- "vmla.f64 d5, d1, d21\n\t"
- "vmla.f64 d5, d2, d25\n\t"
- "vmla.f64 d5, d3, d29\n\t"
-
- "vmul.f64 d6, d0, d18\n\t"
- "vmla.f64 d6, d1, d22\n\t"
- "vmla.f64 d6, d2, d26\n\t"
- "vmla.f64 d6, d3, d30\n\t"
-
- "vmul.f64 d7, d0, d19\n\t"
- "vmla.f64 d7, d1, d23\n\t"
- "vmla.f64 d7, d2, d27\n\t"
- "vmla.f64 d7, d3, d31\n\t"
- "vld1.64 { d0-d3}, [%[rightMatrix], :128]!\n\t"
- "vst1.64 { d4-d7 }, [r3, :128]!\n\t"
-
- // Second row of leftMatrix.
- "vmul.f64 d4, d0, d16\n\t"
- "vmla.f64 d4, d1, d20\n\t"
- "vmla.f64 d4, d2, d24\n\t"
- "vmla.f64 d4, d3, d28\n\t"
-
- "vmul.f64 d5, d0, d17\n\t"
- "vmla.f64 d5, d1, d21\n\t"
- "vmla.f64 d5, d2, d25\n\t"
- "vmla.f64 d5, d3, d29\n\t"
-
- "vmul.f64 d6, d0, d18\n\t"
- "vmla.f64 d6, d1, d22\n\t"
- "vmla.f64 d6, d2, d26\n\t"
- "vmla.f64 d6, d3, d30\n\t"
-
- "vmul.f64 d7, d0, d19\n\t"
- "vmla.f64 d7, d1, d23\n\t"
- "vmla.f64 d7, d2, d27\n\t"
- "vmla.f64 d7, d3, d31\n\t"
- "vld1.64 { d0-d3}, [%[rightMatrix], :128]!\n\t"
- "vst1.64 { d4-d7 }, [r3, :128]!\n\t"
-
- // Third row of leftMatrix.
- "vmul.f64 d4, d0, d16\n\t"
- "vmla.f64 d4, d1, d20\n\t"
- "vmla.f64 d4, d2, d24\n\t"
- "vmla.f64 d4, d3, d28\n\t"
-
- "vmul.f64 d5, d0, d17\n\t"
- "vmla.f64 d5, d1, d21\n\t"
- "vmla.f64 d5, d2, d25\n\t"
- "vmla.f64 d5, d3, d29\n\t"
-
- "vmul.f64 d6, d0, d18\n\t"
- "vmla.f64 d6, d1, d22\n\t"
- "vmla.f64 d6, d2, d26\n\t"
- "vmla.f64 d6, d3, d30\n\t"
-
- "vmul.f64 d7, d0, d19\n\t"
- "vmla.f64 d7, d1, d23\n\t"
- "vmla.f64 d7, d2, d27\n\t"
- "vmla.f64 d7, d3, d31\n\t"
- "vld1.64 { d0-d3}, [%[rightMatrix], :128]\n\t"
- "vst1.64 { d4-d7 }, [r3, :128]!\n\t"
-
- // Fourth and last row of leftMatrix.
- "vmul.f64 d4, d0, d16\n\t"
- "vmla.f64 d4, d1, d20\n\t"
- "vmla.f64 d4, d2, d24\n\t"
- "vmla.f64 d4, d3, d28\n\t"
-
- "vmul.f64 d5, d0, d17\n\t"
- "vmla.f64 d5, d1, d21\n\t"
- "vmla.f64 d5, d2, d25\n\t"
- "vmla.f64 d5, d3, d29\n\t"
-
- "vmul.f64 d6, d0, d18\n\t"
- "vmla.f64 d6, d1, d22\n\t"
- "vmla.f64 d6, d2, d26\n\t"
- "vmla.f64 d6, d3, d30\n\t"
-
- "vmul.f64 d7, d0, d19\n\t"
- "vmla.f64 d7, d1, d23\n\t"
- "vmla.f64 d7, d2, d27\n\t"
- "vmla.f64 d7, d3, d31\n\t"
- "vst1.64 { d4-d7 }, [r3, :128]\n\t"
- : [leftMatrix]"+r"(leftMatrix), [rightMatrix]"+r"(rightMatrix)
- :
- : "memory", "r3", "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7", "d16", "d17", "d18", "d19", "d20", "d21", "d22", "d23", "d24", "d25", "d26", "d27", "d28", "d29", "d30", "d31");
-#elif defined(TRANSFORMATION_MATRIX_USE_X86_64_SSE2)
- // x86_64 has 16 XMM registers which is enough to do the multiplication fully in registers.
- __m128d matrixBlockA = _mm_load_pd(&(m_matrix[0][0]));
- __m128d matrixBlockC = _mm_load_pd(&(m_matrix[1][0]));
- __m128d matrixBlockE = _mm_load_pd(&(m_matrix[2][0]));
- __m128d matrixBlockG = _mm_load_pd(&(m_matrix[3][0]));
-
- // First row.
- __m128d otherMatrixFirstParam = _mm_set1_pd(mat.m_matrix[0][0]);
- __m128d otherMatrixSecondParam = _mm_set1_pd(mat.m_matrix[0][1]);
- __m128d otherMatrixThirdParam = _mm_set1_pd(mat.m_matrix[0][2]);
- __m128d otherMatrixFourthParam = _mm_set1_pd(mat.m_matrix[0][3]);
-
- // output00 and output01.
- __m128d accumulator = _mm_mul_pd(matrixBlockA, otherMatrixFirstParam);
- __m128d temp1 = _mm_mul_pd(matrixBlockC, otherMatrixSecondParam);
- __m128d temp2 = _mm_mul_pd(matrixBlockE, otherMatrixThirdParam);
- __m128d temp3 = _mm_mul_pd(matrixBlockG, otherMatrixFourthParam);
-
- __m128d matrixBlockB = _mm_load_pd(&(m_matrix[0][2]));
- __m128d matrixBlockD = _mm_load_pd(&(m_matrix[1][2]));
- __m128d matrixBlockF = _mm_load_pd(&(m_matrix[2][2]));
- __m128d matrixBlockH = _mm_load_pd(&(m_matrix[3][2]));
-
- accumulator = _mm_add_pd(accumulator, temp1);
- accumulator = _mm_add_pd(accumulator, temp2);
- accumulator = _mm_add_pd(accumulator, temp3);
- _mm_store_pd(&m_matrix[0][0], accumulator);
-
- // output02 and output03.
- accumulator = _mm_mul_pd(matrixBlockB, otherMatrixFirstParam);
- temp1 = _mm_mul_pd(matrixBlockD, otherMatrixSecondParam);
- temp2 = _mm_mul_pd(matrixBlockF, otherMatrixThirdParam);
- temp3 = _mm_mul_pd(matrixBlockH, otherMatrixFourthParam);
-
- accumulator = _mm_add_pd(accumulator, temp1);
- accumulator = _mm_add_pd(accumulator, temp2);
- accumulator = _mm_add_pd(accumulator, temp3);
- _mm_store_pd(&m_matrix[0][2], accumulator);
-
- // Second row.
- otherMatrixFirstParam = _mm_set1_pd(mat.m_matrix[1][0]);
- otherMatrixSecondParam = _mm_set1_pd(mat.m_matrix[1][1]);
- otherMatrixThirdParam = _mm_set1_pd(mat.m_matrix[1][2]);
- otherMatrixFourthParam = _mm_set1_pd(mat.m_matrix[1][3]);
-
- // output10 and output11.
- accumulator = _mm_mul_pd(matrixBlockA, otherMatrixFirstParam);
- temp1 = _mm_mul_pd(matrixBlockC, otherMatrixSecondParam);
- temp2 = _mm_mul_pd(matrixBlockE, otherMatrixThirdParam);
- temp3 = _mm_mul_pd(matrixBlockG, otherMatrixFourthParam);
-
- accumulator = _mm_add_pd(accumulator, temp1);
- accumulator = _mm_add_pd(accumulator, temp2);
- accumulator = _mm_add_pd(accumulator, temp3);
- _mm_store_pd(&m_matrix[1][0], accumulator);
-
- // output12 and output13.
- accumulator = _mm_mul_pd(matrixBlockB, otherMatrixFirstParam);
- temp1 = _mm_mul_pd(matrixBlockD, otherMatrixSecondParam);
- temp2 = _mm_mul_pd(matrixBlockF, otherMatrixThirdParam);
- temp3 = _mm_mul_pd(matrixBlockH, otherMatrixFourthParam);
-
- accumulator = _mm_add_pd(accumulator, temp1);
- accumulator = _mm_add_pd(accumulator, temp2);
- accumulator = _mm_add_pd(accumulator, temp3);
- _mm_store_pd(&m_matrix[1][2], accumulator);
-
- // Third row.
- otherMatrixFirstParam = _mm_set1_pd(mat.m_matrix[2][0]);
- otherMatrixSecondParam = _mm_set1_pd(mat.m_matrix[2][1]);
- otherMatrixThirdParam = _mm_set1_pd(mat.m_matrix[2][2]);
- otherMatrixFourthParam = _mm_set1_pd(mat.m_matrix[2][3]);
-
- // output20 and output21.
- accumulator = _mm_mul_pd(matrixBlockA, otherMatrixFirstParam);
- temp1 = _mm_mul_pd(matrixBlockC, otherMatrixSecondParam);
- temp2 = _mm_mul_pd(matrixBlockE, otherMatrixThirdParam);
- temp3 = _mm_mul_pd(matrixBlockG, otherMatrixFourthParam);
-
- accumulator = _mm_add_pd(accumulator, temp1);
- accumulator = _mm_add_pd(accumulator, temp2);
- accumulator = _mm_add_pd(accumulator, temp3);
- _mm_store_pd(&m_matrix[2][0], accumulator);
-
- // output22 and output23.
- accumulator = _mm_mul_pd(matrixBlockB, otherMatrixFirstParam);
- temp1 = _mm_mul_pd(matrixBlockD, otherMatrixSecondParam);
- temp2 = _mm_mul_pd(matrixBlockF, otherMatrixThirdParam);
- temp3 = _mm_mul_pd(matrixBlockH, otherMatrixFourthParam);
-
- accumulator = _mm_add_pd(accumulator, temp1);
- accumulator = _mm_add_pd(accumulator, temp2);
- accumulator = _mm_add_pd(accumulator, temp3);
- _mm_store_pd(&m_matrix[2][2], accumulator);
-
- // Fourth row.
- otherMatrixFirstParam = _mm_set1_pd(mat.m_matrix[3][0]);
- otherMatrixSecondParam = _mm_set1_pd(mat.m_matrix[3][1]);
- otherMatrixThirdParam = _mm_set1_pd(mat.m_matrix[3][2]);
- otherMatrixFourthParam = _mm_set1_pd(mat.m_matrix[3][3]);
-
- // output30 and output31.
- accumulator = _mm_mul_pd(matrixBlockA, otherMatrixFirstParam);
- temp1 = _mm_mul_pd(matrixBlockC, otherMatrixSecondParam);
- temp2 = _mm_mul_pd(matrixBlockE, otherMatrixThirdParam);
- temp3 = _mm_mul_pd(matrixBlockG, otherMatrixFourthParam);
-
- accumulator = _mm_add_pd(accumulator, temp1);
- accumulator = _mm_add_pd(accumulator, temp2);
- accumulator = _mm_add_pd(accumulator, temp3);
- _mm_store_pd(&m_matrix[3][0], accumulator);
-
- // output32 and output33.
- accumulator = _mm_mul_pd(matrixBlockB, otherMatrixFirstParam);
- temp1 = _mm_mul_pd(matrixBlockD, otherMatrixSecondParam);
- temp2 = _mm_mul_pd(matrixBlockF, otherMatrixThirdParam);
- temp3 = _mm_mul_pd(matrixBlockH, otherMatrixFourthParam);
-
- accumulator = _mm_add_pd(accumulator, temp1);
- accumulator = _mm_add_pd(accumulator, temp2);
- accumulator = _mm_add_pd(accumulator, temp3);
- _mm_store_pd(&m_matrix[3][2], accumulator);
-#else
- Matrix4 tmp;
-
- tmp[0][0] = (mat.m_matrix[0][0] * m_matrix[0][0] + mat.m_matrix[0][1] * m_matrix[1][0]
- + mat.m_matrix[0][2] * m_matrix[2][0] + mat.m_matrix[0][3] * m_matrix[3][0]);
- tmp[0][1] = (mat.m_matrix[0][0] * m_matrix[0][1] + mat.m_matrix[0][1] * m_matrix[1][1]
- + mat.m_matrix[0][2] * m_matrix[2][1] + mat.m_matrix[0][3] * m_matrix[3][1]);
- tmp[0][2] = (mat.m_matrix[0][0] * m_matrix[0][2] + mat.m_matrix[0][1] * m_matrix[1][2]
- + mat.m_matrix[0][2] * m_matrix[2][2] + mat.m_matrix[0][3] * m_matrix[3][2]);
- tmp[0][3] = (mat.m_matrix[0][0] * m_matrix[0][3] + mat.m_matrix[0][1] * m_matrix[1][3]
- + mat.m_matrix[0][2] * m_matrix[2][3] + mat.m_matrix[0][3] * m_matrix[3][3]);
-
- tmp[1][0] = (mat.m_matrix[1][0] * m_matrix[0][0] + mat.m_matrix[1][1] * m_matrix[1][0]
- + mat.m_matrix[1][2] * m_matrix[2][0] + mat.m_matrix[1][3] * m_matrix[3][0]);
- tmp[1][1] = (mat.m_matrix[1][0] * m_matrix[0][1] + mat.m_matrix[1][1] * m_matrix[1][1]
- + mat.m_matrix[1][2] * m_matrix[2][1] + mat.m_matrix[1][3] * m_matrix[3][1]);
- tmp[1][2] = (mat.m_matrix[1][0] * m_matrix[0][2] + mat.m_matrix[1][1] * m_matrix[1][2]
- + mat.m_matrix[1][2] * m_matrix[2][2] + mat.m_matrix[1][3] * m_matrix[3][2]);
- tmp[1][3] = (mat.m_matrix[1][0] * m_matrix[0][3] + mat.m_matrix[1][1] * m_matrix[1][3]
- + mat.m_matrix[1][2] * m_matrix[2][3] + mat.m_matrix[1][3] * m_matrix[3][3]);
-
- tmp[2][0] = (mat.m_matrix[2][0] * m_matrix[0][0] + mat.m_matrix[2][1] * m_matrix[1][0]
- + mat.m_matrix[2][2] * m_matrix[2][0] + mat.m_matrix[2][3] * m_matrix[3][0]);
- tmp[2][1] = (mat.m_matrix[2][0] * m_matrix[0][1] + mat.m_matrix[2][1] * m_matrix[1][1]
- + mat.m_matrix[2][2] * m_matrix[2][1] + mat.m_matrix[2][3] * m_matrix[3][1]);
- tmp[2][2] = (mat.m_matrix[2][0] * m_matrix[0][2] + mat.m_matrix[2][1] * m_matrix[1][2]
- + mat.m_matrix[2][2] * m_matrix[2][2] + mat.m_matrix[2][3] * m_matrix[3][2]);
- tmp[2][3] = (mat.m_matrix[2][0] * m_matrix[0][3] + mat.m_matrix[2][1] * m_matrix[1][3]
- + mat.m_matrix[2][2] * m_matrix[2][3] + mat.m_matrix[2][3] * m_matrix[3][3]);
-
- tmp[3][0] = (mat.m_matrix[3][0] * m_matrix[0][0] + mat.m_matrix[3][1] * m_matrix[1][0]
- + mat.m_matrix[3][2] * m_matrix[2][0] + mat.m_matrix[3][3] * m_matrix[3][0]);
- tmp[3][1] = (mat.m_matrix[3][0] * m_matrix[0][1] + mat.m_matrix[3][1] * m_matrix[1][1]
- + mat.m_matrix[3][2] * m_matrix[2][1] + mat.m_matrix[3][3] * m_matrix[3][1]);
- tmp[3][2] = (mat.m_matrix[3][0] * m_matrix[0][2] + mat.m_matrix[3][1] * m_matrix[1][2]
- + mat.m_matrix[3][2] * m_matrix[2][2] + mat.m_matrix[3][3] * m_matrix[3][2]);
- tmp[3][3] = (mat.m_matrix[3][0] * m_matrix[0][3] + mat.m_matrix[3][1] * m_matrix[1][3]
- + mat.m_matrix[3][2] * m_matrix[2][3] + mat.m_matrix[3][3] * m_matrix[3][3]);
-
- setMatrix(tmp);
-#endif
- return *this;
-}
-
-void TransformationMatrix::multVecMatrix(double x, double y, double& resultX, double& resultY) const
-{
- resultX = m_matrix[3][0] + x * m_matrix[0][0] + y * m_matrix[1][0];
- resultY = m_matrix[3][1] + x * m_matrix[0][1] + y * m_matrix[1][1];
- double w = m_matrix[3][3] + x * m_matrix[0][3] + y * m_matrix[1][3];
- if (w != 1 && w != 0) {
- resultX /= w;
- resultY /= w;
- }
-}
-
-void TransformationMatrix::multVecMatrix(double x, double y, double z, double& resultX, double& resultY, double& resultZ) const
-{
- resultX = m_matrix[3][0] + x * m_matrix[0][0] + y * m_matrix[1][0] + z * m_matrix[2][0];
- resultY = m_matrix[3][1] + x * m_matrix[0][1] + y * m_matrix[1][1] + z * m_matrix[2][1];
- resultZ = m_matrix[3][2] + x * m_matrix[0][2] + y * m_matrix[1][2] + z * m_matrix[2][2];
- double w = m_matrix[3][3] + x * m_matrix[0][3] + y * m_matrix[1][3] + z * m_matrix[2][3];
- if (w != 1 && w != 0) {
- resultX /= w;
- resultY /= w;
- resultZ /= w;
- }
-}
-
-bool TransformationMatrix::isInvertible() const
-{
- if (isIdentityOrTranslation())
- return true;
-
- double det = WebCore::determinant4x4(m_matrix);
-
- if (fabs(det) < SMALL_NUMBER)
- return false;
-
- return true;
-}
-
-TransformationMatrix TransformationMatrix::inverse() const
-{
- if (isIdentityOrTranslation()) {
- // identity matrix
- if (m_matrix[3][0] == 0 && m_matrix[3][1] == 0 && m_matrix[3][2] == 0)
- return TransformationMatrix();
-
- // translation
- return TransformationMatrix(1, 0, 0, 0,
- 0, 1, 0, 0,
- 0, 0, 1, 0,
- -m_matrix[3][0], -m_matrix[3][1], -m_matrix[3][2], 1);
- }
-
- TransformationMatrix invMat;
- bool inverted = WebCore::inverse(m_matrix, invMat.m_matrix);
- if (!inverted)
- return TransformationMatrix();
-
- return invMat;
-}
-
-void TransformationMatrix::makeAffine()
-{
- m_matrix[0][2] = 0;
- m_matrix[0][3] = 0;
-
- m_matrix[1][2] = 0;
- m_matrix[1][3] = 0;
-
- m_matrix[2][0] = 0;
- m_matrix[2][1] = 0;
- m_matrix[2][2] = 1;
- m_matrix[2][3] = 0;
-
- m_matrix[3][2] = 0;
- m_matrix[3][3] = 1;
-}
-
-AffineTransform TransformationMatrix::toAffineTransform() const
-{
- return AffineTransform(m_matrix[0][0], m_matrix[0][1], m_matrix[1][0],
- m_matrix[1][1], m_matrix[3][0], m_matrix[3][1]);
-}
-
-TransformationMatrix::operator SkMatrix() const
-{
- SkMatrix result;
-
- result.setScaleX(WebCoreDoubleToSkScalar(a()));
- result.setSkewX(WebCoreDoubleToSkScalar(c()));
- result.setTranslateX(WebCoreDoubleToSkScalar(e()));
-
- result.setScaleY(WebCoreDoubleToSkScalar(d()));
- result.setSkewY(WebCoreDoubleToSkScalar(b()));
- result.setTranslateY(WebCoreDoubleToSkScalar(f()));
-
- // FIXME: Set perspective properly.
- result.setPerspX(0);
- result.setPerspY(0);
- result.set(SkMatrix::kMPersp2, SK_Scalar1);
-
- return result;
-}
-
-static inline void blendFloat(double& from, double to, double progress)
-{
- if (from != to)
- from = from + (to - from) * progress;
-}
-
-void TransformationMatrix::blend(const TransformationMatrix& from, double progress)
-{
- if (from.isIdentity() && isIdentity())
- return;
-
- // decompose
- DecomposedType fromDecomp;
- DecomposedType toDecomp;
- from.decompose(fromDecomp);
- decompose(toDecomp);
-
- // interpolate
- blendFloat(fromDecomp.scaleX, toDecomp.scaleX, progress);
- blendFloat(fromDecomp.scaleY, toDecomp.scaleY, progress);
- blendFloat(fromDecomp.scaleZ, toDecomp.scaleZ, progress);
- blendFloat(fromDecomp.skewXY, toDecomp.skewXY, progress);
- blendFloat(fromDecomp.skewXZ, toDecomp.skewXZ, progress);
- blendFloat(fromDecomp.skewYZ, toDecomp.skewYZ, progress);
- blendFloat(fromDecomp.translateX, toDecomp.translateX, progress);
- blendFloat(fromDecomp.translateY, toDecomp.translateY, progress);
- blendFloat(fromDecomp.translateZ, toDecomp.translateZ, progress);
- blendFloat(fromDecomp.perspectiveX, toDecomp.perspectiveX, progress);
- blendFloat(fromDecomp.perspectiveY, toDecomp.perspectiveY, progress);
- blendFloat(fromDecomp.perspectiveZ, toDecomp.perspectiveZ, progress);
- blendFloat(fromDecomp.perspectiveW, toDecomp.perspectiveW, progress);
-
- slerp(&fromDecomp.quaternionX, &toDecomp.quaternionX, progress);
-
- // recompose
- recompose(fromDecomp);
-}
-
-bool TransformationMatrix::decompose(DecomposedType& decomp) const
-{
- if (isIdentity()) {
- memset(&decomp, 0, sizeof(decomp));
- decomp.perspectiveW = 1;
- decomp.scaleX = 1;
- decomp.scaleY = 1;
- decomp.scaleZ = 1;
- }
-
- if (!WebCore::decompose(m_matrix, decomp))
- return false;
- return true;
-}
-
-void TransformationMatrix::recompose(const DecomposedType& decomp)
-{
- makeIdentity();
-
- // first apply perspective
- m_matrix[0][3] = decomp.perspectiveX;
- m_matrix[1][3] = decomp.perspectiveY;
- m_matrix[2][3] = decomp.perspectiveZ;
- m_matrix[3][3] = decomp.perspectiveW;
-
- // now translate
- translate3d(decomp.translateX, decomp.translateY, decomp.translateZ);
-
- // apply rotation
- double xx = decomp.quaternionX * decomp.quaternionX;
- double xy = decomp.quaternionX * decomp.quaternionY;
- double xz = decomp.quaternionX * decomp.quaternionZ;
- double xw = decomp.quaternionX * decomp.quaternionW;
- double yy = decomp.quaternionY * decomp.quaternionY;
- double yz = decomp.quaternionY * decomp.quaternionZ;
- double yw = decomp.quaternionY * decomp.quaternionW;
- double zz = decomp.quaternionZ * decomp.quaternionZ;
- double zw = decomp.quaternionZ * decomp.quaternionW;
-
- // Construct a composite rotation matrix from the quaternion values
- TransformationMatrix rotationMatrix(1 - 2 * (yy + zz), 2 * (xy - zw), 2 * (xz + yw), 0,
- 2 * (xy + zw), 1 - 2 * (xx + zz), 2 * (yz - xw), 0,
- 2 * (xz - yw), 2 * (yz + xw), 1 - 2 * (xx + yy), 0,
- 0, 0, 0, 1);
-
- multiply(rotationMatrix);
-
- // now apply skew
- if (decomp.skewYZ) {
- TransformationMatrix tmp;
- tmp.setM32(decomp.skewYZ);
- multiply(tmp);
- }
-
- if (decomp.skewXZ) {
- TransformationMatrix tmp;
- tmp.setM31(decomp.skewXZ);
- multiply(tmp);
- }
-
- if (decomp.skewXY) {
- TransformationMatrix tmp;
- tmp.setM21(decomp.skewXY);
- multiply(tmp);
- }
-
- // finally, apply scale
- scale3d(decomp.scaleX, decomp.scaleY, decomp.scaleZ);
-}
-
-bool TransformationMatrix::isIntegerTranslation() const
-{
- if (!isIdentityOrTranslation())
- return false;
-
- // Check for translate Z.
- if (m_matrix[3][2])
- return false;
-
- // Check for non-integer translate X/Y.
- if (static_cast<int>(m_matrix[3][0]) != m_matrix[3][0] || static_cast<int>(m_matrix[3][1]) != m_matrix[3][1])
- return false;
-
- return true;
-}
-
-TransformationMatrix TransformationMatrix::to2dTransform() const
-{
- return TransformationMatrix(m_matrix[0][0], m_matrix[0][1], 0, m_matrix[0][3],
- m_matrix[1][0], m_matrix[1][1], 0, m_matrix[1][3],
- 0, 0, 1, 0,
- m_matrix[3][0], m_matrix[3][1], 0, m_matrix[3][3]);
-}
-
-void TransformationMatrix::toColumnMajorFloatArray(FloatMatrix4& result) const
-{
- result[0] = m11();
- result[1] = m12();
- result[2] = m13();
- result[3] = m14();
- result[4] = m21();
- result[5] = m22();
- result[6] = m23();
- result[7] = m24();
- result[8] = m31();
- result[9] = m32();
- result[10] = m33();
- result[11] = m34();
- result[12] = m41();
- result[13] = m42();
- result[14] = m43();
- result[15] = m44();
-}
-
-bool TransformationMatrix::isBackFaceVisible() const
-{
- // Back-face visibility is determined by transforming the normal vector (0, 0, 1) and
- // checking the sign of the resulting z component. However, normals cannot be
- // transformed by the original matrix, they require being transformed by the
- // inverse-transpose.
- //
- // Since we know we will be using (0, 0, 1), and we only care about the z-component of
- // the transformed normal, then we only need the m33() element of the
- // inverse-transpose. Therefore we do not need the transpose.
- //
- // Additionally, if we only need the m33() element, we do not need to compute a full
- // inverse. Instead, knowing the inverse of a matrix is adjoint(matrix) / determinant,
- // we can simply compute the m33() of the adjoint (adjugate) matrix, without computing
- // the full adjoint.
-
- double determinant = WebCore::determinant4x4(m_matrix);
-
- // If the matrix is not invertible, then we assume its backface is not visible.
- if (fabs(determinant) < SMALL_NUMBER)
- return false;
-
- double cofactor33 = determinant3x3(m11(), m12(), m14(), m21(), m22(), m24(), m41(), m42(), m44());
- double zComponentOfTransformedNormal = cofactor33 / determinant;
-
- return zComponentOfTransformedNormal < 0;
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/TransformationMatrix.h b/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/TransformationMatrix.h
deleted file mode 100644
index c28546bf804..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/TransformationMatrix.h
+++ /dev/null
@@ -1,364 +0,0 @@
-/*
- * Copyright (C) 2005, 2006 Apple Computer, Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TransformationMatrix_h
-#define TransformationMatrix_h
-
-#include <SkMatrix.h>
-#include <string.h> //for memcpy
-#include "core/platform/graphics/FloatPoint.h"
-#include "core/platform/graphics/FloatPoint3D.h"
-#include "core/platform/graphics/IntPoint.h"
-#include "wtf/CPU.h"
-#include "wtf/FastAllocBase.h"
-
-namespace WebCore {
-
-class AffineTransform;
-class IntRect;
-class LayoutRect;
-class FloatRect;
-class FloatQuad;
-
-#if CPU(X86_64)
-#define TRANSFORMATION_MATRIX_USE_X86_64_SSE2
-#endif
-
-class TransformationMatrix {
- WTF_MAKE_FAST_ALLOCATED;
-public:
-
-#if CPU(APPLE_ARMV7S) || defined(TRANSFORMATION_MATRIX_USE_X86_64_SSE2)
-#if COMPILER(MSVC)
- __declspec(align(16)) typedef double Matrix4[4][4];
-#else
- typedef double Matrix4[4][4] __attribute__((aligned (16)));
-#endif
-#else
- typedef double Matrix4[4][4];
-#endif
-
- TransformationMatrix() { makeIdentity(); }
- TransformationMatrix(const AffineTransform& t);
- TransformationMatrix(const TransformationMatrix& t) { *this = t; }
- TransformationMatrix(double a, double b, double c, double d, double e, double f) { setMatrix(a, b, c, d, e, f); }
- TransformationMatrix(double m11, double m12, double m13, double m14,
- double m21, double m22, double m23, double m24,
- double m31, double m32, double m33, double m34,
- double m41, double m42, double m43, double m44)
- {
- setMatrix(m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, m41, m42, m43, m44);
- }
-
- void setMatrix(double a, double b, double c, double d, double e, double f)
- {
- m_matrix[0][0] = a; m_matrix[0][1] = b; m_matrix[0][2] = 0; m_matrix[0][3] = 0;
- m_matrix[1][0] = c; m_matrix[1][1] = d; m_matrix[1][2] = 0; m_matrix[1][3] = 0;
- m_matrix[2][0] = 0; m_matrix[2][1] = 0; m_matrix[2][2] = 1; m_matrix[2][3] = 0;
- m_matrix[3][0] = e; m_matrix[3][1] = f; m_matrix[3][2] = 0; m_matrix[3][3] = 1;
- }
-
- void setMatrix(double m11, double m12, double m13, double m14,
- double m21, double m22, double m23, double m24,
- double m31, double m32, double m33, double m34,
- double m41, double m42, double m43, double m44)
- {
- m_matrix[0][0] = m11; m_matrix[0][1] = m12; m_matrix[0][2] = m13; m_matrix[0][3] = m14;
- m_matrix[1][0] = m21; m_matrix[1][1] = m22; m_matrix[1][2] = m23; m_matrix[1][3] = m24;
- m_matrix[2][0] = m31; m_matrix[2][1] = m32; m_matrix[2][2] = m33; m_matrix[2][3] = m34;
- m_matrix[3][0] = m41; m_matrix[3][1] = m42; m_matrix[3][2] = m43; m_matrix[3][3] = m44;
- }
-
- TransformationMatrix& operator =(const TransformationMatrix &t)
- {
- setMatrix(t.m_matrix);
- return *this;
- }
-
- TransformationMatrix& makeIdentity()
- {
- setMatrix(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
- return *this;
- }
-
- bool isIdentity() const
- {
- return m_matrix[0][0] == 1 && m_matrix[0][1] == 0 && m_matrix[0][2] == 0 && m_matrix[0][3] == 0 &&
- m_matrix[1][0] == 0 && m_matrix[1][1] == 1 && m_matrix[1][2] == 0 && m_matrix[1][3] == 0 &&
- m_matrix[2][0] == 0 && m_matrix[2][1] == 0 && m_matrix[2][2] == 1 && m_matrix[2][3] == 0 &&
- m_matrix[3][0] == 0 && m_matrix[3][1] == 0 && m_matrix[3][2] == 0 && m_matrix[3][3] == 1;
- }
-
- // This form preserves the double math from input to output
- void map(double x, double y, double& x2, double& y2) const { multVecMatrix(x, y, x2, y2); }
-
- // Map a 3D point through the transform, returning a 3D point.
- FloatPoint3D mapPoint(const FloatPoint3D&) const;
-
- // Map a 2D point through the transform, returning a 2D point.
- // Note that this ignores the z component, effectively projecting the point into the z=0 plane.
- FloatPoint mapPoint(const FloatPoint&) const;
-
- // Like the version above, except that it rounds the mapped point to the nearest integer value.
- IntPoint mapPoint(const IntPoint& p) const
- {
- return roundedIntPoint(mapPoint(FloatPoint(p)));
- }
-
- // If the matrix has 3D components, the z component of the result is
- // dropped, effectively projecting the rect into the z=0 plane
- FloatRect mapRect(const FloatRect&) const;
-
- // Rounds the resulting mapped rectangle out. This is helpful for bounding
- // box computations but may not be what is wanted in other contexts.
- IntRect mapRect(const IntRect&) const;
- LayoutRect mapRect(const LayoutRect&) const;
-
- // If the matrix has 3D components, the z component of the result is
- // dropped, effectively projecting the quad into the z=0 plane
- FloatQuad mapQuad(const FloatQuad&) const;
-
- // Map a point on the z=0 plane into a point on
- // the plane with with the transform applied, by extending
- // a ray perpendicular to the source plane and computing
- // the local x,y position of the point where that ray intersects
- // with the destination plane.
- FloatPoint projectPoint(const FloatPoint&, bool* clamped = 0) const;
- // Projects the four corners of the quad
- FloatQuad projectQuad(const FloatQuad&, bool* clamped = 0) const;
- // Projects the four corners of the quad and takes a bounding box,
- // while sanitizing values created when the w component is negative.
- LayoutRect clampedBoundsOfProjectedQuad(const FloatQuad&) const;
-
- double m11() const { return m_matrix[0][0]; }
- void setM11(double f) { m_matrix[0][0] = f; }
- double m12() const { return m_matrix[0][1]; }
- void setM12(double f) { m_matrix[0][1] = f; }
- double m13() const { return m_matrix[0][2]; }
- void setM13(double f) { m_matrix[0][2] = f; }
- double m14() const { return m_matrix[0][3]; }
- void setM14(double f) { m_matrix[0][3] = f; }
- double m21() const { return m_matrix[1][0]; }
- void setM21(double f) { m_matrix[1][0] = f; }
- double m22() const { return m_matrix[1][1]; }
- void setM22(double f) { m_matrix[1][1] = f; }
- double m23() const { return m_matrix[1][2]; }
- void setM23(double f) { m_matrix[1][2] = f; }
- double m24() const { return m_matrix[1][3]; }
- void setM24(double f) { m_matrix[1][3] = f; }
- double m31() const { return m_matrix[2][0]; }
- void setM31(double f) { m_matrix[2][0] = f; }
- double m32() const { return m_matrix[2][1]; }
- void setM32(double f) { m_matrix[2][1] = f; }
- double m33() const { return m_matrix[2][2]; }
- void setM33(double f) { m_matrix[2][2] = f; }
- double m34() const { return m_matrix[2][3]; }
- void setM34(double f) { m_matrix[2][3] = f; }
- double m41() const { return m_matrix[3][0]; }
- void setM41(double f) { m_matrix[3][0] = f; }
- double m42() const { return m_matrix[3][1]; }
- void setM42(double f) { m_matrix[3][1] = f; }
- double m43() const { return m_matrix[3][2]; }
- void setM43(double f) { m_matrix[3][2] = f; }
- double m44() const { return m_matrix[3][3]; }
- void setM44(double f) { m_matrix[3][3] = f; }
-
- double a() const { return m_matrix[0][0]; }
- void setA(double a) { m_matrix[0][0] = a; }
-
- double b() const { return m_matrix[0][1]; }
- void setB(double b) { m_matrix[0][1] = b; }
-
- double c() const { return m_matrix[1][0]; }
- void setC(double c) { m_matrix[1][0] = c; }
-
- double d() const { return m_matrix[1][1]; }
- void setD(double d) { m_matrix[1][1] = d; }
-
- double e() const { return m_matrix[3][0]; }
- void setE(double e) { m_matrix[3][0] = e; }
-
- double f() const { return m_matrix[3][1]; }
- void setF(double f) { m_matrix[3][1] = f; }
-
- // this = mat * this.
- TransformationMatrix& multiply(const TransformationMatrix&);
-
- TransformationMatrix& scale(double);
- TransformationMatrix& scaleNonUniform(double sx, double sy);
- TransformationMatrix& scale3d(double sx, double sy, double sz);
-
- TransformationMatrix& rotate(double d) { return rotate3d(0, 0, d); }
- TransformationMatrix& rotateFromVector(double x, double y);
- TransformationMatrix& rotate3d(double rx, double ry, double rz);
-
- // The vector (x,y,z) is normalized if it's not already. A vector of
- // (0,0,0) uses a vector of (0,0,1).
- TransformationMatrix& rotate3d(double x, double y, double z, double angle);
-
- TransformationMatrix& translate(double tx, double ty);
- TransformationMatrix& translate3d(double tx, double ty, double tz);
-
- // translation added with a post-multiply
- TransformationMatrix& translateRight(double tx, double ty);
- TransformationMatrix& translateRight3d(double tx, double ty, double tz);
-
- TransformationMatrix& flipX();
- TransformationMatrix& flipY();
- TransformationMatrix& skew(double angleX, double angleY);
- TransformationMatrix& skewX(double angle) { return skew(angle, 0); }
- TransformationMatrix& skewY(double angle) { return skew(0, angle); }
-
- TransformationMatrix& applyPerspective(double p);
- bool hasPerspective() const { return m_matrix[2][3] != 0.0f; }
-
- // returns a transformation that maps a rect to a rect
- static TransformationMatrix rectToRect(const FloatRect&, const FloatRect&);
-
- bool isInvertible() const;
-
- // This method returns the identity matrix if it is not invertible.
- // Use isInvertible() before calling this if you need to know.
- TransformationMatrix inverse() const;
-
- // decompose the matrix into its component parts
- typedef struct {
- double scaleX, scaleY, scaleZ;
- double skewXY, skewXZ, skewYZ;
- double quaternionX, quaternionY, quaternionZ, quaternionW;
- double translateX, translateY, translateZ;
- double perspectiveX, perspectiveY, perspectiveZ, perspectiveW;
- } DecomposedType;
-
- bool decompose(DecomposedType& decomp) const;
- void recompose(const DecomposedType& decomp);
-
- void blend(const TransformationMatrix& from, double progress);
-
- bool isAffine() const
- {
- return (m13() == 0 && m14() == 0 && m23() == 0 && m24() == 0 &&
- m31() == 0 && m32() == 0 && m33() == 1 && m34() == 0 && m43() == 0 && m44() == 1);
- }
-
- // Throw away the non-affine parts of the matrix (lossy!)
- void makeAffine();
-
- AffineTransform toAffineTransform() const;
-
- bool operator==(const TransformationMatrix& m2) const
- {
- return (m_matrix[0][0] == m2.m_matrix[0][0] &&
- m_matrix[0][1] == m2.m_matrix[0][1] &&
- m_matrix[0][2] == m2.m_matrix[0][2] &&
- m_matrix[0][3] == m2.m_matrix[0][3] &&
- m_matrix[1][0] == m2.m_matrix[1][0] &&
- m_matrix[1][1] == m2.m_matrix[1][1] &&
- m_matrix[1][2] == m2.m_matrix[1][2] &&
- m_matrix[1][3] == m2.m_matrix[1][3] &&
- m_matrix[2][0] == m2.m_matrix[2][0] &&
- m_matrix[2][1] == m2.m_matrix[2][1] &&
- m_matrix[2][2] == m2.m_matrix[2][2] &&
- m_matrix[2][3] == m2.m_matrix[2][3] &&
- m_matrix[3][0] == m2.m_matrix[3][0] &&
- m_matrix[3][1] == m2.m_matrix[3][1] &&
- m_matrix[3][2] == m2.m_matrix[3][2] &&
- m_matrix[3][3] == m2.m_matrix[3][3]);
- }
-
- bool operator!=(const TransformationMatrix& other) const { return !(*this == other); }
-
- // *this = *this * t
- TransformationMatrix& operator*=(const TransformationMatrix& t)
- {
- return multiply(t);
- }
-
- // result = *this * t
- TransformationMatrix operator*(const TransformationMatrix& t) const
- {
- TransformationMatrix result = *this;
- result.multiply(t);
- return result;
- }
-
- operator SkMatrix() const;
-
- bool isIdentityOrTranslation() const
- {
- return m_matrix[0][0] == 1 && m_matrix[0][1] == 0 && m_matrix[0][2] == 0 && m_matrix[0][3] == 0
- && m_matrix[1][0] == 0 && m_matrix[1][1] == 1 && m_matrix[1][2] == 0 && m_matrix[1][3] == 0
- && m_matrix[2][0] == 0 && m_matrix[2][1] == 0 && m_matrix[2][2] == 1 && m_matrix[2][3] == 0
- && m_matrix[3][3] == 1;
- }
-
- bool isIntegerTranslation() const;
-
- // This method returns the matrix without 3D components.
- TransformationMatrix to2dTransform() const;
-
- typedef float FloatMatrix4[16];
- void toColumnMajorFloatArray(FloatMatrix4& result) const;
-
- // A local-space layer is implicitly defined at the z = 0 plane, with its front side
- // facing the positive z-axis (i.e. a camera looking along the negative z-axis sees
- // the front side of the layer). This function checks if the transformed layer's back
- // face would be visible to a camera looking along the negative z-axis in the target space.
- bool isBackFaceVisible() const;
-
-private:
- // multiply passed 2D point by matrix (assume z=0)
- void multVecMatrix(double x, double y, double& dstX, double& dstY) const;
- FloatPoint internalMapPoint(const FloatPoint& sourcePoint) const
- {
- double resultX;
- double resultY;
- multVecMatrix(sourcePoint.x(), sourcePoint.y(), resultX, resultY);
- return FloatPoint(static_cast<float>(resultX), static_cast<float>(resultY));
- }
-
- // multiply passed 3D point by matrix
- void multVecMatrix(double x, double y, double z, double& dstX, double& dstY, double& dstZ) const;
- FloatPoint3D internalMapPoint(const FloatPoint3D& sourcePoint) const
- {
- double resultX;
- double resultY;
- double resultZ;
- multVecMatrix(sourcePoint.x(), sourcePoint.y(), sourcePoint.z(), resultX, resultY, resultZ);
- return FloatPoint3D(static_cast<float>(resultX), static_cast<float>(resultY), static_cast<float>(resultZ));
- }
-
- void setMatrix(const Matrix4 m)
- {
- if (m && m != m_matrix)
- memcpy(m_matrix, m, sizeof(Matrix4));
- }
-
- Matrix4 m_matrix;
-};
-
-} // namespace WebCore
-
-#endif // TransformationMatrix_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/TranslateTransformOperation.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/TranslateTransformOperation.cpp
deleted file mode 100644
index ba53b875fc7..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/TranslateTransformOperation.cpp
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright (C) 1999 Antti Koivisto (koivisto@kde.org)
- * Copyright (C) 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#include "config.h"
-#include "core/platform/graphics/transforms/TranslateTransformOperation.h"
-
-namespace WebCore {
-
-PassRefPtr<TransformOperation> TranslateTransformOperation::blend(const TransformOperation* from, double progress, bool blendToIdentity)
-{
- if (from && !from->isSameType(*this))
- return this;
-
- const Length zeroLength(0, Fixed);
- if (blendToIdentity)
- return TranslateTransformOperation::create(zeroLength.blend(m_x, progress), zeroLength.blend(m_y, progress), zeroLength.blend(m_z, progress), m_type);
-
- const TranslateTransformOperation* fromOp = static_cast<const TranslateTransformOperation*>(from);
- Length fromX = fromOp ? fromOp->m_x : zeroLength;
- Length fromY = fromOp ? fromOp->m_y : zeroLength;
- Length fromZ = fromOp ? fromOp->m_z : zeroLength;
- return TranslateTransformOperation::create(m_x.blend(fromX, progress), m_y.blend(fromY, progress), m_z.blend(fromZ, progress), m_type);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/TranslateTransformOperation.h b/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/TranslateTransformOperation.h
deleted file mode 100644
index 8db8971046c..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/transforms/TranslateTransformOperation.h
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
- * Copyright (C) 2000 Lars Knoll (knoll@kde.org)
- * (C) 2000 Antti Koivisto (koivisto@kde.org)
- * (C) 2000 Dirk Mueller (mueller@kde.org)
- * Copyright (C) 2003, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
- * Copyright (C) 2006 Graham Dennis (graham.dennis@gmail.com)
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#ifndef TranslateTransformOperation_h
-#define TranslateTransformOperation_h
-
-#include "core/css/LengthFunctions.h"
-#include "core/platform/Length.h"
-#include "core/platform/graphics/transforms/TransformOperation.h"
-
-namespace WebCore {
-
-class TranslateTransformOperation : public TransformOperation {
-public:
- static PassRefPtr<TranslateTransformOperation> create(const Length& tx, const Length& ty, OperationType type)
- {
- return adoptRef(new TranslateTransformOperation(tx, ty, Length(0, Fixed), type));
- }
-
- static PassRefPtr<TranslateTransformOperation> create(const Length& tx, const Length& ty, const Length& tz, OperationType type)
- {
- return adoptRef(new TranslateTransformOperation(tx, ty, tz, type));
- }
-
- double x(const FloatSize& borderBoxSize) const { return floatValueForLength(m_x, borderBoxSize.width()); }
- double y(const FloatSize& borderBoxSize) const { return floatValueForLength(m_y, borderBoxSize.height()); }
- double z(const FloatSize&) const { return floatValueForLength(m_z, 1); }
-
- Length x() const { return m_x; }
- Length y() const { return m_y; }
- Length z() const { return m_z; }
-
-private:
- virtual bool isIdentity() const { return !floatValueForLength(m_x, 1) && !floatValueForLength(m_y, 1) && !floatValueForLength(m_z, 1); }
-
- virtual OperationType getOperationType() const { return m_type; }
- virtual bool isSameType(const TransformOperation& o) const { return o.getOperationType() == m_type; }
-
- virtual bool operator==(const TransformOperation& o) const
- {
- if (!isSameType(o))
- return false;
- const TranslateTransformOperation* t = static_cast<const TranslateTransformOperation*>(&o);
- return m_x == t->m_x && m_y == t->m_y && m_z == t->m_z;
- }
-
- virtual bool apply(TransformationMatrix& transform, const FloatSize& borderBoxSize) const
- {
- transform.translate3d(x(borderBoxSize), y(borderBoxSize), z(borderBoxSize));
- return m_x.type() == Percent || m_y.type() == Percent;
- }
-
- virtual PassRefPtr<TransformOperation> blend(const TransformOperation* from, double progress, bool blendToIdentity = false);
-
- TranslateTransformOperation(const Length& tx, const Length& ty, const Length& tz, OperationType type)
- : m_x(tx)
- , m_y(ty)
- , m_z(tz)
- , m_type(type)
- {
- ASSERT(type == TranslateX || type == TranslateY || type == TranslateZ || type == Translate || type == Translate3D);
- }
-
- Length m_x;
- Length m_y;
- Length m_z;
- OperationType m_type;
-};
-
-} // namespace WebCore
-
-#endif // TranslateTransformOperation_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/graphics/win/FontCustomPlatformDataWin.cpp b/chromium/third_party/WebKit/Source/core/platform/graphics/win/FontCustomPlatformDataWin.cpp
deleted file mode 100644
index 004b9e22a63..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/graphics/win/FontCustomPlatformDataWin.cpp
+++ /dev/null
@@ -1,136 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/FontCustomPlatformData.h"
-
-#include "core/platform/LayoutTestSupport.h"
-#include "core/platform/NotImplemented.h"
-#include "core/platform/SharedBuffer.h"
-#include "core/platform/graphics/FontPlatformData.h"
-#include "core/platform/graphics/opentype/OpenTypeSanitizer.h"
-#include "core/platform/graphics/opentype/OpenTypeUtilities.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/RefPtr.h"
-#include "wtf/text/Base64.h"
-
-#include <objbase.h>
-
-namespace {
-
-// Creates a unique and unpredictable font name, in order to avoid collisions and to
-// not allow access from CSS.
-String createUniqueFontName()
-{
- GUID fontUuid;
- CoCreateGuid(&fontUuid);
-
- String fontName = base64Encode(reinterpret_cast<char*>(&fontUuid), sizeof(fontUuid));
- ASSERT(fontName.length() < LF_FACESIZE);
- return fontName;
-}
-
-} // namespace
-
-namespace WebCore {
-
-FontCustomPlatformData::FontCustomPlatformData(HANDLE fontReference, const String& name)
- : m_fontReference(fontReference)
- , m_name(name)
-{
-}
-
-FontCustomPlatformData::~FontCustomPlatformData()
-{
- if (m_fontReference)
- RemoveFontMemResourceEx(m_fontReference);
-}
-
-FontPlatformData FontCustomPlatformData::fontPlatformData(int size, bool bold, bool italic, FontOrientation orientation, FontWidthVariant)
-{
- ASSERT(m_fontReference);
-
- LOGFONT logFont;
- // m_name comes from createUniqueFontName, which, in turn, gets
- // it from base64-encoded uuid (128-bit). So, m_name
- // can never be longer than LF_FACESIZE (32).
- if (m_name.length() + 1 >= LF_FACESIZE) {
- ASSERT_NOT_REACHED();
- return FontPlatformData();
- }
- unsigned len = m_name.copyTo(logFont.lfFaceName, 0, LF_FACESIZE - 1);
- logFont.lfFaceName[len] = '\0';
-
- // FIXME: almost identical to FillLogFont in FontCacheWin.cpp.
- // Need to refactor.
- logFont.lfHeight = -size;
- logFont.lfWidth = 0;
- logFont.lfEscapement = 0;
- logFont.lfOrientation = 0;
- logFont.lfUnderline = false;
- logFont.lfStrikeOut = false;
- logFont.lfCharSet = DEFAULT_CHARSET;
- logFont.lfOutPrecision = OUT_TT_ONLY_PRECIS;
- logFont.lfQuality = isRunningLayoutTest() ? NONANTIALIASED_QUALITY : DEFAULT_QUALITY; // Honor user's desktop settings.
- logFont.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
- logFont.lfItalic = italic;
- logFont.lfWeight = bold ? FW_BOLD : FW_DONTCARE;
-
- HFONT hfont = CreateFontIndirect(&logFont);
- return FontPlatformData(hfont, size, orientation);
-}
-
-PassOwnPtr<FontCustomPlatformData> FontCustomPlatformData::create(SharedBuffer* buffer)
-{
- ASSERT_ARG(buffer, buffer);
-
- OpenTypeSanitizer sanitizer(buffer);
- RefPtr<SharedBuffer> transcodeBuffer = sanitizer.sanitize();
- if (!transcodeBuffer)
- return nullptr; // validation failed.
- buffer = transcodeBuffer.get();
-
- // Introduce the font to GDI. AddFontMemResourceEx should be used with care, because it will pollute the process's
- // font namespace (Windows has no API for creating an HFONT from data without exposing the font to the
- // entire process first).
- String fontName = createUniqueFontName();
- HANDLE fontReference = renameAndActivateFont(buffer, fontName);
- if (!fontReference)
- return nullptr;
-
- return adoptPtr(new FontCustomPlatformData(fontReference, fontName));
-}
-
-bool FontCustomPlatformData::supportsFormat(const String& format)
-{
- return equalIgnoringCase(format, "truetype") || equalIgnoringCase(format, "opentype") || OpenTypeSanitizer::supportsFormat(format);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/image-decoders/ImageDecoder.cpp b/chromium/third_party/WebKit/Source/core/platform/image-decoders/ImageDecoder.cpp
deleted file mode 100644
index 7bae661473b..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/image-decoders/ImageDecoder.cpp
+++ /dev/null
@@ -1,203 +0,0 @@
-/*
- * Copyright (C) Research In Motion Limited 2009-2010. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#include "config.h"
-#include "core/platform/image-decoders/ImageDecoder.h"
-
-#include "core/platform/SharedBuffer.h"
-#include "core/platform/image-decoders/bmp/BMPImageDecoder.h"
-#include "core/platform/image-decoders/gif/GIFImageDecoder.h"
-#include "core/platform/image-decoders/ico/ICOImageDecoder.h"
-#include "core/platform/image-decoders/jpeg/JPEGImageDecoder.h"
-#include "core/platform/image-decoders/png/PNGImageDecoder.h"
-#include "core/platform/image-decoders/webp/WEBPImageDecoder.h"
-#include "public/platform/Platform.h"
-#include "wtf/PassOwnPtr.h"
-
-namespace WebCore {
-
-static unsigned copyFromSharedBuffer(char* buffer, unsigned bufferLength, const SharedBuffer& sharedBuffer, unsigned offset)
-{
- unsigned bytesExtracted = 0;
- const char* moreData;
- while (unsigned moreDataLength = sharedBuffer.getSomeData(moreData, offset)) {
- unsigned bytesToCopy = std::min(bufferLength - bytesExtracted, moreDataLength);
- memcpy(buffer + bytesExtracted, moreData, bytesToCopy);
- bytesExtracted += bytesToCopy;
- if (bytesExtracted == bufferLength)
- break;
- offset += bytesToCopy;
- }
- return bytesExtracted;
-}
-
-inline bool matchesGIFSignature(char* contents)
-{
- return !memcmp(contents, "GIF87a", 6) || !memcmp(contents, "GIF89a", 6);
-}
-
-inline bool matchesPNGSignature(char* contents)
-{
- return !memcmp(contents, "\x89\x50\x4E\x47\x0D\x0A\x1A\x0A", 8);
-}
-
-inline bool matchesJPEGSignature(char* contents)
-{
- return !memcmp(contents, "\xFF\xD8\xFF", 3);
-}
-
-inline bool matchesWebPSignature(char* contents)
-{
- return !memcmp(contents, "RIFF", 4) && !memcmp(contents + 8, "WEBPVP", 6);
-}
-
-inline bool matchesBMPSignature(char* contents)
-{
- return !memcmp(contents, "BM", 2);
-}
-
-inline bool matchesICOSignature(char* contents)
-{
- return !memcmp(contents, "\x00\x00\x01\x00", 4);
-}
-
-inline bool matchesCURSignature(char* contents)
-{
- return !memcmp(contents, "\x00\x00\x02\x00", 4);
-}
-
-PassOwnPtr<ImageDecoder> ImageDecoder::create(const SharedBuffer& data, ImageSource::AlphaOption alphaOption, ImageSource::GammaAndColorProfileOption gammaAndColorProfileOption)
-{
- static const unsigned longestSignatureLength = sizeof("RIFF????WEBPVP") - 1;
- ASSERT(longestSignatureLength == 14);
-
- size_t maxDecodedBytes = WebKit::Platform::current()->maxDecodedImageBytes();
-
- char contents[longestSignatureLength];
- if (copyFromSharedBuffer(contents, longestSignatureLength, data, 0) < longestSignatureLength)
- return nullptr;
-
- if (matchesJPEGSignature(contents))
- return adoptPtr(new JPEGImageDecoder(alphaOption, gammaAndColorProfileOption, maxDecodedBytes));
-
- if (matchesPNGSignature(contents))
- return adoptPtr(new PNGImageDecoder(alphaOption, gammaAndColorProfileOption, maxDecodedBytes));
-
- if (matchesGIFSignature(contents))
- return adoptPtr(new GIFImageDecoder(alphaOption, gammaAndColorProfileOption, maxDecodedBytes));
-
- if (matchesICOSignature(contents) || matchesCURSignature(contents))
- return adoptPtr(new ICOImageDecoder(alphaOption, gammaAndColorProfileOption, maxDecodedBytes));
-
- if (matchesWebPSignature(contents))
- return adoptPtr(new WEBPImageDecoder(alphaOption, gammaAndColorProfileOption, maxDecodedBytes));
-
- if (matchesBMPSignature(contents))
- return adoptPtr(new BMPImageDecoder(alphaOption, gammaAndColorProfileOption, maxDecodedBytes));
-
- return nullptr;
-}
-
-bool ImageDecoder::frameHasAlphaAtIndex(size_t index) const
-{
- return !frameIsCompleteAtIndex(index) || m_frameBufferCache[index].hasAlpha();
-}
-
-bool ImageDecoder::frameIsCompleteAtIndex(size_t index) const
-{
- return (index < m_frameBufferCache.size()) &&
- (m_frameBufferCache[index].status() == ImageFrame::FrameComplete);
-}
-
-unsigned ImageDecoder::frameBytesAtIndex(size_t index) const
-{
- if (m_frameBufferCache.size() <= index || m_frameBufferCache[index].status() == ImageFrame::FrameEmpty)
- return 0;
- // FIXME: Use the dimension of the requested frame.
- return m_size.area() * sizeof(ImageFrame::PixelData);
-}
-
-size_t ImageDecoder::clearCacheExceptFrame(size_t clearExceptFrame)
-{
- // Don't clear if there are no frames or only one frame.
- if (m_frameBufferCache.size() <= 1)
- return 0;
-
- size_t frameBytesCleared = 0;
- for (size_t i = 0; i < m_frameBufferCache.size(); ++i) {
- if (i != clearExceptFrame) {
- frameBytesCleared += frameBytesAtIndex(i);
- clearFrameBuffer(i);
- }
- }
- return frameBytesCleared;
-}
-
-void ImageDecoder::clearFrameBuffer(size_t frameIndex)
-{
- m_frameBufferCache[frameIndex].clearPixelData();
-}
-
-size_t ImageDecoder::findRequiredPreviousFrame(size_t frameIndex, bool frameRectIsOpaque)
-{
- ASSERT(frameIndex <= m_frameBufferCache.size());
- if (!frameIndex) {
- // The first frame doesn't rely on any previous data.
- return kNotFound;
- }
-
- const ImageFrame* currBuffer = &m_frameBufferCache[frameIndex];
- if ((frameRectIsOpaque || currBuffer->alphaBlendSource() == ImageFrame::BlendAtopBgcolor)
- && currBuffer->originalFrameRect().contains(IntRect(IntPoint(), size())))
- return kNotFound;
-
- // The starting state for this frame depends on the previous frame's
- // disposal method.
- size_t prevFrame = frameIndex - 1;
- const ImageFrame* prevBuffer = &m_frameBufferCache[prevFrame];
- ASSERT(prevBuffer->requiredPreviousFrameIndexValid());
-
- switch (prevBuffer->disposalMethod()) {
- case ImageFrame::DisposeNotSpecified:
- case ImageFrame::DisposeKeep:
- // prevFrame will be used as the starting state for this frame.
- // FIXME: Be even smarter by checking the frame sizes and/or alpha-containing regions.
- return prevFrame;
- case ImageFrame::DisposeOverwritePrevious:
- // Frames that use the DisposeOverwritePrevious method are effectively
- // no-ops in terms of changing the starting state of a frame compared to
- // the starting state of the previous frame, so skip over them and
- // return the required previous frame of it.
- return prevBuffer->requiredPreviousFrameIndex();
- case ImageFrame::DisposeOverwriteBgcolor:
- // If the previous frame fills the whole image, then the current frame
- // can be decoded alone. Likewise, if the previous frame could be
- // decoded without reference to any prior frame, the starting state for
- // this frame is a blank frame, so it can again be decoded alone.
- // Otherwise, the previous frame contributes to this frame.
- return (prevBuffer->originalFrameRect().contains(IntRect(IntPoint(), size()))
- || (prevBuffer->requiredPreviousFrameIndex() == kNotFound)) ? kNotFound : prevFrame;
- default:
- ASSERT_NOT_REACHED();
- return kNotFound;
- }
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/image-decoders/ImageDecoder.h b/chromium/third_party/WebKit/Source/core/platform/image-decoders/ImageDecoder.h
deleted file mode 100644
index 99f926c1205..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/image-decoders/ImageDecoder.h
+++ /dev/null
@@ -1,476 +0,0 @@
-/*
- * Copyright (C) 2006 Apple Computer, Inc. All rights reserved.
- * Copyright (C) Research In Motion Limited 2009-2010. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ImageDecoder_h
-#define ImageDecoder_h
-
-#include "SkColorPriv.h"
-#include "core/platform/PlatformScreen.h"
-#include "core/platform/SharedBuffer.h"
-#include "core/platform/graphics/ImageSource.h"
-#include "core/platform/graphics/IntRect.h"
-#include "core/platform/graphics/skia/NativeImageSkia.h"
-#include "public/platform/Platform.h"
-#include "wtf/Assertions.h"
-#include "wtf/RefPtr.h"
-#include "wtf/text/WTFString.h"
-#include "wtf/Vector.h"
-
-#if USE(QCMSLIB)
-#include "qcms.h"
-#if OS(MACOSX)
-#include <ApplicationServices/ApplicationServices.h>
-#include "core/platform/graphics/cg/GraphicsContextCG.h"
-#include "wtf/RetainPtr.h"
-#endif
-#endif
-
-namespace WebCore {
-
- // ImageFrame represents the decoded image data. This buffer is what all
- // decoders write a single frame into.
- class ImageFrame {
- public:
- enum Status { FrameEmpty, FramePartial, FrameComplete };
- enum DisposalMethod {
- // If you change the numeric values of these, make sure you audit
- // all users, as some users may cast raw values to/from these
- // constants.
- DisposeNotSpecified, // Leave frame in framebuffer
- DisposeKeep, // Leave frame in framebuffer
- DisposeOverwriteBgcolor, // Clear frame to fully transparent
- DisposeOverwritePrevious // Clear frame to previous framebuffer contents
- };
- // Indicates how non-opaque pixels in the current frame rectangle
- // are blended with those in the previous frame.
- // Notes:
- // * GIF always uses 'BlendAtopPreviousFrame'.
- // * WebP also uses the 'BlendAtopBgcolor' option. This is useful for
- // cases where one wants to transform a few opaque pixels of the
- // previous frame into non-opaque pixels in the current frame.
- enum AlphaBlendSource {
- // Blend non-opaque pixels atop the corresponding pixels in the
- // initial buffer state (i.e. any previous frame buffer after having
- // been properly disposed).
- BlendAtopPreviousFrame,
-
- // Blend non-opaque pixels against fully transparent (i.e. simply
- // overwrite the corresponding pixels).
- BlendAtopBgcolor,
- };
- typedef uint32_t PixelData;
-
- ImageFrame();
-
- ImageFrame(const ImageFrame& other) { operator=(other); }
-
- // For backends which refcount their data, this operator doesn't need to
- // create a new copy of the image data, only increase the ref count.
- ImageFrame& operator=(const ImageFrame& other);
-
- // These do not touch other metadata, only the raw pixel data.
- void clearPixelData();
- void zeroFillPixelData();
- void zeroFillFrameRect(const IntRect&);
-
- // Makes this frame have an independent copy of the provided image's
- // pixel data, so that modifications in one frame are not reflected in
- // the other. Returns whether the copy succeeded.
- bool copyBitmapData(const ImageFrame&);
-
- // Copies the pixel data at [(startX, startY), (endX, startY)) to the
- // same X-coordinates on each subsequent row up to but not including
- // endY.
- void copyRowNTimes(int startX, int endX, int startY, int endY)
- {
- ASSERT(startX < width());
- ASSERT(endX <= width());
- ASSERT(startY < height());
- ASSERT(endY <= height());
- const int rowBytes = (endX - startX) * sizeof(PixelData);
- const PixelData* const startAddr = getAddr(startX, startY);
- for (int destY = startY + 1; destY < endY; ++destY)
- memcpy(getAddr(startX, destY), startAddr, rowBytes);
- }
-
- // Allocates space for the pixel data. Must be called before any pixels
- // are written. Must only be called once. Returns whether allocation
- // succeeded.
- bool setSize(int newWidth, int newHeight);
-
- // Returns a caller-owned pointer to the underlying native image data.
- // (Actual use: This pointer will be owned by BitmapImage and freed in
- // FrameData::clear()).
- PassRefPtr<NativeImageSkia> asNewNativeImage() const;
-
- bool hasAlpha() const;
- const IntRect& originalFrameRect() const { return m_originalFrameRect; }
- Status status() const { return m_status; }
- unsigned duration() const { return m_duration; }
- DisposalMethod disposalMethod() const { return m_disposalMethod; }
- AlphaBlendSource alphaBlendSource() const { return m_alphaBlendSource; }
- bool premultiplyAlpha() const { return m_premultiplyAlpha; }
- SkBitmap::Allocator* allocator() const { return m_allocator; }
- const SkBitmap& getSkBitmap() const { return m_bitmap->bitmap(); }
-
- size_t requiredPreviousFrameIndex() const
- {
- ASSERT(m_requiredPreviousFrameIndexValid);
- return m_requiredPreviousFrameIndex;
- }
-#if !ASSERT_DISABLED
- bool requiredPreviousFrameIndexValid() const { return m_requiredPreviousFrameIndexValid; }
-#endif
- void setHasAlpha(bool alpha);
- void setOriginalFrameRect(const IntRect& r) { m_originalFrameRect = r; }
- void setStatus(Status);
- void setDuration(unsigned duration) { m_duration = duration; }
- void setDisposalMethod(DisposalMethod disposalMethod) { m_disposalMethod = disposalMethod; }
- void setAlphaBlendSource(AlphaBlendSource alphaBlendSource) { m_alphaBlendSource = alphaBlendSource; }
- void setPremultiplyAlpha(bool premultiplyAlpha) { m_premultiplyAlpha = premultiplyAlpha; }
- void setMemoryAllocator(SkBitmap::Allocator* allocator) { m_allocator = allocator; }
- void setSkBitmap(const SkBitmap& bitmap) { m_bitmap = NativeImageSkia::create(bitmap); }
-
- void setRequiredPreviousFrameIndex(size_t previousFrameIndex)
- {
- m_requiredPreviousFrameIndex = previousFrameIndex;
-#if !ASSERT_DISABLED
- m_requiredPreviousFrameIndexValid = true;
-#endif
- }
-
- inline PixelData* getAddr(int x, int y)
- {
- return m_bitmap->bitmap().getAddr32(x, y);
- }
-
- inline void setRGBA(int x, int y, unsigned r, unsigned g, unsigned b, unsigned a)
- {
- setRGBA(getAddr(x, y), r, g, b, a);
- }
-
- static const unsigned div255 = static_cast<unsigned>(1.0 / 255 * (1 << 24)) + 1;
-
- inline void setRGBA(PixelData* dest, unsigned r, unsigned g, unsigned b, unsigned a)
- {
- if (m_premultiplyAlpha && a < 255) {
- if (!a) {
- *dest = 0;
- return;
- }
-
- unsigned alpha = a * div255;
- r = (r * alpha) >> 24;
- g = (g * alpha) >> 24;
- b = (b * alpha) >> 24;
- }
-
- // Call the "NoCheck" version since we may deliberately pass non-premultiplied
- // values, and we don't want an assert.
- *dest = SkPackARGB32NoCheck(a, r, g, b);
- }
-
- inline void setRGBARaw(PixelData* dest, unsigned r, unsigned g, unsigned b, unsigned a)
- {
- *dest = SkPackARGB32NoCheck(a, r, g, b);
- }
-
- private:
- int width() const
- {
- return m_bitmap->bitmap().width();
- }
-
- int height() const
- {
- return m_bitmap->bitmap().height();
- }
-
- RefPtr<NativeImageSkia> m_bitmap;
- SkBitmap::Allocator* m_allocator;
- bool m_hasAlpha;
- // This will always just be the entire buffer except for GIF or WebP
- // frames whose original rect was smaller than the overall image size.
- IntRect m_originalFrameRect;
- Status m_status;
- unsigned m_duration;
- DisposalMethod m_disposalMethod;
- AlphaBlendSource m_alphaBlendSource;
- bool m_premultiplyAlpha;
-
- // The frame that must be decoded before this frame can be decoded.
- // WTF::kNotFound if this frame doesn't require any previous frame.
- // This is used by ImageDecoder::clearCacheExceptFrame(), and will never
- // be read for image formats that do not have multiple frames.
- size_t m_requiredPreviousFrameIndex;
-#if !ASSERT_DISABLED
- bool m_requiredPreviousFrameIndexValid;
-#endif
- };
-
- // ImageDecoder is a base for all format-specific decoders
- // (e.g. JPEGImageDecoder). This base manages the ImageFrame cache.
- //
- class ImageDecoder {
- WTF_MAKE_NONCOPYABLE(ImageDecoder); WTF_MAKE_FAST_ALLOCATED;
- public:
- static const size_t noDecodedImageByteLimit = WebKit::Platform::noDecodedImageByteLimit;
-
- ImageDecoder(ImageSource::AlphaOption alphaOption, ImageSource::GammaAndColorProfileOption gammaAndColorProfileOption, size_t maxDecodedBytes)
- : m_premultiplyAlpha(alphaOption == ImageSource::AlphaPremultiplied)
- , m_ignoreGammaAndColorProfile(gammaAndColorProfileOption == ImageSource::GammaAndColorProfileIgnored)
- , m_maxDecodedBytes(maxDecodedBytes)
- , m_sizeAvailable(false)
- , m_isAllDataReceived(false)
- , m_failed(false) { }
-
- virtual ~ImageDecoder() { }
-
- // Returns a caller-owned decoder of the appropriate type. Returns 0 if
- // we can't sniff a supported type from the provided data (possibly
- // because there isn't enough data yet).
- // Sets m_maxDecodedBytes to Platform::maxImageDecodedBytes().
- static PassOwnPtr<ImageDecoder> create(const SharedBuffer& data, ImageSource::AlphaOption, ImageSource::GammaAndColorProfileOption);
-
- // Returns a decoder with custom maxDecodedSize.
- static PassOwnPtr<ImageDecoder> create(const SharedBuffer& data, ImageSource::AlphaOption, ImageSource::GammaAndColorProfileOption, size_t maxDecodedSize);
-
- virtual String filenameExtension() const = 0;
-
- bool isAllDataReceived() const { return m_isAllDataReceived; }
-
- virtual void setData(SharedBuffer* data, bool allDataReceived)
- {
- if (m_failed)
- return;
- m_data = data;
- m_isAllDataReceived = allDataReceived;
- }
-
- // Lazily-decodes enough of the image to get the size (if possible).
- // FIXME: Right now that has to be done by each subclass; factor the
- // decode call out and use it here.
- virtual bool isSizeAvailable()
- {
- return !m_failed && m_sizeAvailable;
- }
-
- virtual IntSize size() const { return m_size; }
-
- // Decoders which downsample images should override this method to
- // return the actual decoded size.
- virtual IntSize decodedSize() const { return size(); }
-
- // This will only differ from size() for ICO (where each frame is a
- // different icon) or other formats where different frames are different
- // sizes. This does NOT differ from size() for GIF or WebP, since
- // decoding GIF or WebP composites any smaller frames against previous
- // frames to create full-size frames.
- virtual IntSize frameSizeAtIndex(size_t) const
- {
- return size();
- }
-
- // Returns whether the size is legal (i.e. not going to result in
- // overflow elsewhere). If not, marks decoding as failed.
- virtual bool setSize(unsigned width, unsigned height)
- {
- if (sizeCalculationMayOverflow(width, height))
- return setFailed();
- m_size = IntSize(width, height);
- m_sizeAvailable = true;
- return true;
- }
-
- // Lazily-decodes enough of the image to get the frame count (if
- // possible), without decoding the individual frames.
- // FIXME: Right now that has to be done by each subclass; factor the
- // decode call out and use it here.
- virtual size_t frameCount() { return 1; }
-
- virtual int repetitionCount() const { return cAnimationNone; }
-
- // Decodes as much of the requested frame as possible, and returns an
- // ImageDecoder-owned pointer.
- virtual ImageFrame* frameBufferAtIndex(size_t) = 0;
-
- // Make the best effort guess to check if the requested frame has alpha channel.
- virtual bool frameHasAlphaAtIndex(size_t) const;
-
- // Whether or not the frame is fully received.
- virtual bool frameIsCompleteAtIndex(size_t) const;
-
- // Duration for displaying a frame in seconds. This method is used by animated images only.
- virtual float frameDurationAtIndex(size_t) const { return 0; }
-
- // Number of bytes in the decoded frame requested. Return 0 if not yet decoded.
- virtual unsigned frameBytesAtIndex(size_t) const;
-
- void setIgnoreGammaAndColorProfile(bool flag) { m_ignoreGammaAndColorProfile = flag; }
- bool ignoresGammaAndColorProfile() const { return m_ignoreGammaAndColorProfile; }
-
- ImageOrientation orientation() const { return m_orientation; }
-
- enum { iccColorProfileHeaderLength = 128 };
-
- static bool rgbColorProfile(const char* profileData, unsigned profileLength)
- {
- ASSERT_UNUSED(profileLength, profileLength >= iccColorProfileHeaderLength);
-
- return !memcmp(&profileData[16], "RGB ", 4);
- }
-
- static bool inputDeviceColorProfile(const char* profileData, unsigned profileLength)
- {
- ASSERT_UNUSED(profileLength, profileLength >= iccColorProfileHeaderLength);
-
- return !memcmp(&profileData[12], "mntr", 4) || !memcmp(&profileData[12], "scnr", 4);
- }
-
-#if USE(QCMSLIB)
- static qcms_profile* qcmsOutputDeviceProfile()
- {
- static qcms_profile* outputDeviceProfile = 0;
-
- static bool qcmsInitialized = false;
- if (!qcmsInitialized) {
- qcmsInitialized = true;
- // FIXME: Add optional ICCv4 support.
-#if OS(MACOSX)
- RetainPtr<CGColorSpaceRef> monitorColorSpace(AdoptCF, CGDisplayCopyColorSpace(CGMainDisplayID()));
- CFDataRef iccProfile(CGColorSpaceCopyICCProfile(monitorColorSpace.get()));
- if (iccProfile) {
- size_t length = CFDataGetLength(iccProfile);
- const unsigned char* systemProfile = CFDataGetBytePtr(iccProfile);
- outputDeviceProfile = qcms_profile_from_memory(systemProfile, length);
- }
-#else
- // FIXME: add support for multiple monitors.
- ColorProfile profile;
- screenColorProfile(profile);
- if (!profile.isEmpty())
- outputDeviceProfile = qcms_profile_from_memory(profile.data(), profile.size());
-#endif
- if (outputDeviceProfile && qcms_profile_is_bogus(outputDeviceProfile)) {
- qcms_profile_release(outputDeviceProfile);
- outputDeviceProfile = 0;
- }
- if (!outputDeviceProfile)
- outputDeviceProfile = qcms_profile_sRGB();
- if (outputDeviceProfile)
- qcms_profile_precache_output_transform(outputDeviceProfile);
- }
- return outputDeviceProfile;
- }
-#endif
-
- // Sets the "decode failure" flag. For caller convenience (since so
- // many callers want to return false after calling this), returns false
- // to enable easy tailcalling. Subclasses may override this to also
- // clean up any local data.
- virtual bool setFailed()
- {
- m_failed = true;
- return false;
- }
-
- bool failed() const { return m_failed; }
-
- // Clears decoded pixel data from all frames except the provided frame.
- // Callers may pass WTF::kNotFound to clear all frames.
- // Note: If |m_frameBufferCache| contains only one frame, it won't be cleared.
- // Returns the number of bytes of frame data actually cleared.
- virtual size_t clearCacheExceptFrame(size_t);
-
- // If the image has a cursor hot-spot, stores it in the argument
- // and returns true. Otherwise returns false.
- virtual bool hotSpot(IntPoint&) const { return false; }
-
- virtual void setMemoryAllocator(SkBitmap::Allocator* allocator)
- {
- // FIXME: this doesn't work for images with multiple frames.
- if (m_frameBufferCache.isEmpty()) {
- m_frameBufferCache.resize(1);
- m_frameBufferCache[0].setRequiredPreviousFrameIndex(
- findRequiredPreviousFrame(0, false));
- }
- m_frameBufferCache[0].setMemoryAllocator(allocator);
- }
-
- protected:
- // Calculates the most recent frame whose image data may be needed in
- // order to decode frame |frameIndex|, based on frame disposal methods
- // and |frameRectIsOpaque|, where |frameRectIsOpaque| signifies whether
- // the rectangle of frame at |frameIndex| is known to be opaque.
- // If no previous frame's data is required, returns WTF::kNotFound.
- //
- // This function requires that the previous frame's
- // |m_requiredPreviousFrameIndex| member has been set correctly. The
- // easiest way to ensure this is for subclasses to call this method and
- // store the result on the frame via setRequiredPreviousFrameIndex()
- // as soon as the frame has been created and parsed sufficiently to
- // determine the disposal method; assuming this happens for all frames
- // in order, the required invariant will hold.
- //
- // Image formats which do not use more than one frame do not need to
- // worry about this; see comments on
- // ImageFrame::m_requiredPreviousFrameIndex.
- size_t findRequiredPreviousFrame(size_t frameIndex, bool frameRectIsOpaque);
-
- virtual void clearFrameBuffer(size_t frameIndex);
-
- RefPtr<SharedBuffer> m_data; // The encoded data.
- Vector<ImageFrame, 1> m_frameBufferCache;
- bool m_premultiplyAlpha;
- bool m_ignoreGammaAndColorProfile;
- ImageOrientation m_orientation;
-
- // The maximum amount of memory a decoded image should require. Ideally,
- // image decoders should downsample large images to fit under this limit
- // (and then return the downsampled size from decodedSize()). Ignoring
- // this limit can cause excessive memory use or even crashes on low-
- // memory devices.
- size_t m_maxDecodedBytes;
-
- private:
- // Some code paths compute the size of the image as "width * height * 4"
- // and return it as a (signed) int. Avoid overflow.
- static bool sizeCalculationMayOverflow(unsigned width, unsigned height)
- {
- unsigned long long total_size = static_cast<unsigned long long>(width)
- * static_cast<unsigned long long>(height);
- return total_size > ((1 << 29) - 1);
- }
-
- IntSize m_size;
- bool m_sizeAvailable;
- bool m_isAllDataReceived;
- bool m_failed;
- };
-
-} // namespace WebCore
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/image-decoders/ImageDecoderTest.cpp b/chromium/third_party/WebKit/Source/core/platform/image-decoders/ImageDecoderTest.cpp
deleted file mode 100644
index 7227f5ff8a6..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/image-decoders/ImageDecoderTest.cpp
+++ /dev/null
@@ -1,248 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/platform/image-decoders/ImageDecoder.h"
-
-#include "wtf/OwnPtr.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/Vector.h"
-#include <gtest/gtest.h>
-
-using namespace WebCore;
-
-class TestImageDecoder : public ImageDecoder {
-public:
- TestImageDecoder()
- : ImageDecoder(ImageSource::AlphaNotPremultiplied, ImageSource::GammaAndColorProfileApplied, noDecodedImageByteLimit)
- {
- }
-
- virtual String filenameExtension() const OVERRIDE { return ""; }
- virtual ImageFrame* frameBufferAtIndex(size_t) OVERRIDE { return 0; }
-
- Vector<ImageFrame, 1>& frameBufferCache()
- {
- return m_frameBufferCache;
- }
-
- void resetRequiredPreviousFrames(bool knownOpaque = false)
- {
- for (size_t i = 0; i < m_frameBufferCache.size(); ++i)
- m_frameBufferCache[i].setRequiredPreviousFrameIndex(findRequiredPreviousFrame(i, knownOpaque));
- }
-
- void initFrames(size_t numFrames, unsigned width = 100, unsigned height = 100)
- {
- setSize(width, height);
- m_frameBufferCache.resize(numFrames);
- for (size_t i = 0; i < numFrames; ++i)
- m_frameBufferCache[i].setOriginalFrameRect(IntRect(0, 0, width, height));
- }
-};
-
-TEST(ImageDecoderTest, sizeCalculationMayOverflow)
-{
- OwnPtr<TestImageDecoder> decoder(adoptPtr(new TestImageDecoder()));
- EXPECT_FALSE(decoder->setSize(1 << 29, 1));
- EXPECT_FALSE(decoder->setSize(1, 1 << 29));
- EXPECT_FALSE(decoder->setSize(1 << 15, 1 << 15));
- EXPECT_TRUE(decoder->setSize(1 << 28, 1));
- EXPECT_TRUE(decoder->setSize(1, 1 << 28));
- EXPECT_TRUE(decoder->setSize(1 << 14, 1 << 14));
-}
-
-TEST(ImageDecoderTest, requiredPreviousFrameIndex)
-{
- OwnPtr<TestImageDecoder> decoder(adoptPtr(new TestImageDecoder()));
- decoder->initFrames(6);
- Vector<ImageFrame, 1>& frameBuffers = decoder->frameBufferCache();
-
- frameBuffers[1].setDisposalMethod(ImageFrame::DisposeKeep);
- frameBuffers[2].setDisposalMethod(ImageFrame::DisposeOverwritePrevious);
- frameBuffers[3].setDisposalMethod(ImageFrame::DisposeOverwritePrevious);
- frameBuffers[4].setDisposalMethod(ImageFrame::DisposeKeep);
-
- decoder->resetRequiredPreviousFrames();
-
- // The first frame doesn't require any previous frame.
- EXPECT_EQ(kNotFound, frameBuffers[0].requiredPreviousFrameIndex());
- // The previous DisposeNotSpecified frame is required.
- EXPECT_EQ(0u, frameBuffers[1].requiredPreviousFrameIndex());
- // DisposeKeep is treated as DisposeNotSpecified.
- EXPECT_EQ(1u, frameBuffers[2].requiredPreviousFrameIndex());
- // Previous DisposeOverwritePrevious frames are skipped.
- EXPECT_EQ(1u, frameBuffers[3].requiredPreviousFrameIndex());
- EXPECT_EQ(1u, frameBuffers[4].requiredPreviousFrameIndex());
- EXPECT_EQ(4u, frameBuffers[5].requiredPreviousFrameIndex());
-}
-
-TEST(ImageDecoderTest, requiredPreviousFrameIndexDisposeOverwriteBgcolor)
-{
- OwnPtr<TestImageDecoder> decoder(adoptPtr(new TestImageDecoder()));
- decoder->initFrames(3);
- Vector<ImageFrame, 1>& frameBuffers = decoder->frameBufferCache();
-
- // Fully covering DisposeOverwriteBgcolor previous frame resets the starting state.
- frameBuffers[1].setDisposalMethod(ImageFrame::DisposeOverwriteBgcolor);
- decoder->resetRequiredPreviousFrames();
- EXPECT_EQ(kNotFound, frameBuffers[2].requiredPreviousFrameIndex());
-
- // Partially covering DisposeOverwriteBgcolor previous frame is required by this frame.
- frameBuffers[1].setOriginalFrameRect(IntRect(50, 50, 50, 50));
- decoder->resetRequiredPreviousFrames();
- EXPECT_EQ(1u, frameBuffers[2].requiredPreviousFrameIndex());
-}
-
-TEST(ImageDecoderTest, requiredPreviousFrameIndexForFrame1)
-{
- OwnPtr<TestImageDecoder> decoder(adoptPtr(new TestImageDecoder()));
- decoder->initFrames(2);
- Vector<ImageFrame, 1>& frameBuffers = decoder->frameBufferCache();
-
- decoder->resetRequiredPreviousFrames();
- EXPECT_EQ(0u, frameBuffers[1].requiredPreviousFrameIndex());
-
- // The first frame with DisposeOverwritePrevious or DisposeOverwriteBgcolor
- // resets the starting state.
- frameBuffers[0].setDisposalMethod(ImageFrame::DisposeOverwritePrevious);
- decoder->resetRequiredPreviousFrames();
- EXPECT_EQ(kNotFound, frameBuffers[1].requiredPreviousFrameIndex());
- frameBuffers[0].setDisposalMethod(ImageFrame::DisposeOverwriteBgcolor);
- decoder->resetRequiredPreviousFrames();
- EXPECT_EQ(kNotFound, frameBuffers[1].requiredPreviousFrameIndex());
-
- // ... even if it partially covers.
- frameBuffers[0].setOriginalFrameRect(IntRect(50, 50, 50, 50));
-
- frameBuffers[0].setDisposalMethod(ImageFrame::DisposeOverwritePrevious);
- decoder->resetRequiredPreviousFrames();
- EXPECT_EQ(kNotFound, frameBuffers[1].requiredPreviousFrameIndex());
- frameBuffers[0].setDisposalMethod(ImageFrame::DisposeOverwriteBgcolor);
- decoder->resetRequiredPreviousFrames();
- EXPECT_EQ(kNotFound, frameBuffers[1].requiredPreviousFrameIndex());
-}
-
-TEST(ImageDecoderTest, requiredPreviousFrameIndexBlendAtopBgcolor)
-{
- OwnPtr<TestImageDecoder> decoder(adoptPtr(new TestImageDecoder()));
- decoder->initFrames(3);
- Vector<ImageFrame, 1>& frameBuffers = decoder->frameBufferCache();
-
- frameBuffers[1].setOriginalFrameRect(IntRect(25, 25, 50, 50));
- frameBuffers[2].setAlphaBlendSource(ImageFrame::BlendAtopBgcolor);
-
- // A full frame with 'blending method == BlendAtopBgcolor' doesn't depend on any prior frames.
- for (int disposeMethod = ImageFrame::DisposeNotSpecified; disposeMethod <= ImageFrame::DisposeOverwritePrevious; ++disposeMethod) {
- frameBuffers[1].setDisposalMethod(static_cast<ImageFrame::DisposalMethod>(disposeMethod));
- decoder->resetRequiredPreviousFrames();
- EXPECT_EQ(kNotFound, frameBuffers[2].requiredPreviousFrameIndex());
- }
-
- // A non-full frame with 'blending method == BlendAtopBgcolor' does depend on a prior frame.
- frameBuffers[2].setOriginalFrameRect(IntRect(50, 50, 50, 50));
- for (int disposeMethod = ImageFrame::DisposeNotSpecified; disposeMethod <= ImageFrame::DisposeOverwritePrevious; ++disposeMethod) {
- frameBuffers[1].setDisposalMethod(static_cast<ImageFrame::DisposalMethod>(disposeMethod));
- decoder->resetRequiredPreviousFrames();
- EXPECT_NE(kNotFound, frameBuffers[2].requiredPreviousFrameIndex());
- }
-}
-
-TEST(ImageDecoderTest, requiredPreviousFrameIndexKnownOpaque)
-{
- OwnPtr<TestImageDecoder> decoder(adoptPtr(new TestImageDecoder()));
- decoder->initFrames(3);
- Vector<ImageFrame, 1>& frameBuffers = decoder->frameBufferCache();
-
- frameBuffers[1].setOriginalFrameRect(IntRect(25, 25, 50, 50));
-
- // A full frame that is known to be opaque doesn't depend on any prior frames.
- for (int disposeMethod = ImageFrame::DisposeNotSpecified; disposeMethod <= ImageFrame::DisposeOverwritePrevious; ++disposeMethod) {
- frameBuffers[1].setDisposalMethod(static_cast<ImageFrame::DisposalMethod>(disposeMethod));
- decoder->resetRequiredPreviousFrames(true);
- EXPECT_EQ(kNotFound, frameBuffers[2].requiredPreviousFrameIndex());
- }
-
- // A non-full frame that is known to be opaque does depend on a prior frame.
- frameBuffers[2].setOriginalFrameRect(IntRect(50, 50, 50, 50));
- for (int disposeMethod = ImageFrame::DisposeNotSpecified; disposeMethod <= ImageFrame::DisposeOverwritePrevious; ++disposeMethod) {
- frameBuffers[1].setDisposalMethod(static_cast<ImageFrame::DisposalMethod>(disposeMethod));
- decoder->resetRequiredPreviousFrames(true);
- EXPECT_NE(kNotFound, frameBuffers[2].requiredPreviousFrameIndex());
- }
-}
-
-TEST(ImageDecoderTest, clearCacheExceptFrameDoNothing)
-{
- OwnPtr<TestImageDecoder> decoder(adoptPtr(new TestImageDecoder()));
- decoder->clearCacheExceptFrame(0);
-
- // This should not crash.
- decoder->initFrames(20);
- decoder->clearCacheExceptFrame(kNotFound);
-}
-
-TEST(ImageDecoderTest, clearCacheExceptFrameAll)
-{
- const size_t numFrames = 10;
- OwnPtr<TestImageDecoder> decoder(adoptPtr(new TestImageDecoder()));
- decoder->initFrames(numFrames);
- Vector<ImageFrame, 1>& frameBuffers = decoder->frameBufferCache();
- for (size_t i = 0; i < numFrames; ++i)
- frameBuffers[i].setStatus(i % 2 ? ImageFrame::FramePartial : ImageFrame::FrameComplete);
-
- decoder->clearCacheExceptFrame(kNotFound);
-
- for (size_t i = 0; i < numFrames; ++i) {
- SCOPED_TRACE(testing::Message() << i);
- EXPECT_EQ(ImageFrame::FrameEmpty, frameBuffers[i].status());
- }
-}
-
-TEST(ImageDecoderTest, clearCacheExceptFramePreverveClearExceptFrame)
-{
- const size_t numFrames = 10;
- OwnPtr<TestImageDecoder> decoder(adoptPtr(new TestImageDecoder()));
- decoder->initFrames(numFrames);
- Vector<ImageFrame, 1>& frameBuffers = decoder->frameBufferCache();
- for (size_t i = 0; i < numFrames; ++i)
- frameBuffers[i].setStatus(ImageFrame::FrameComplete);
-
- decoder->resetRequiredPreviousFrames();
- decoder->clearCacheExceptFrame(5);
- for (size_t i = 0; i < numFrames; ++i) {
- SCOPED_TRACE(testing::Message() << i);
- if (i == 5)
- EXPECT_EQ(ImageFrame::FrameComplete, frameBuffers[i].status());
- else
- EXPECT_EQ(ImageFrame::FrameEmpty, frameBuffers[i].status());
- }
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/image-decoders/ImageFrame.cpp b/chromium/third_party/WebKit/Source/core/platform/image-decoders/ImageFrame.cpp
deleted file mode 100644
index f3252344f29..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/image-decoders/ImageFrame.cpp
+++ /dev/null
@@ -1,159 +0,0 @@
-/*
- * Copyright (C) 2006 Apple Computer, Inc. All rights reserved.
- * Copyright (C) 2008, 2009 Google, Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/image-decoders/ImageDecoder.h"
-
-#include "core/platform/graphics/skia/NativeImageSkia.h"
-#include "wtf/PassRefPtr.h"
-
-namespace WebCore {
-
-ImageFrame::ImageFrame()
- : m_bitmap(NativeImageSkia::create())
- , m_allocator(0)
- , m_hasAlpha(false)
- , m_status(FrameEmpty)
- , m_duration(0)
- , m_disposalMethod(DisposeNotSpecified)
- , m_alphaBlendSource(BlendAtopPreviousFrame)
- , m_premultiplyAlpha(true)
- , m_requiredPreviousFrameIndex(kNotFound)
-#if !ASSERT_DISABLED
- , m_requiredPreviousFrameIndexValid(false)
-#endif
-{
-}
-
-ImageFrame& ImageFrame::operator=(const ImageFrame& other)
-{
- if (this == &other)
- return *this;
-
- m_bitmap = other.m_bitmap->clone();
- // Keep the pixels locked since we will be writing directly into the
- // bitmap throughout this object's lifetime.
- m_bitmap->bitmap().lockPixels();
- setMemoryAllocator(other.allocator());
- setOriginalFrameRect(other.originalFrameRect());
- setStatus(other.status());
- setDuration(other.duration());
- setDisposalMethod(other.disposalMethod());
- setAlphaBlendSource(other.alphaBlendSource());
- setPremultiplyAlpha(other.premultiplyAlpha());
- // Be sure that this is called after we've called setStatus(), since we
- // look at our status to know what to do with the alpha value.
- setHasAlpha(other.hasAlpha());
- // Copy raw fields to avoid ASSERT failure in requiredPreviousFrameIndex().
- m_requiredPreviousFrameIndex = other.m_requiredPreviousFrameIndex;
-#if !ASSERT_DISABLED
- m_requiredPreviousFrameIndexValid = other.m_requiredPreviousFrameIndexValid;
-#endif
- return *this;
-}
-
-void ImageFrame::clearPixelData()
-{
- m_bitmap->bitmap().reset();
- m_status = FrameEmpty;
- // NOTE: Do not reset other members here; clearFrameBufferCache()
- // calls this to free the bitmap data, but other functions like
- // initFrameBuffer() and frameComplete() may still need to read
- // other metadata out of this frame later.
-}
-
-void ImageFrame::zeroFillPixelData()
-{
- m_bitmap->bitmap().eraseARGB(0, 0, 0, 0);
- m_hasAlpha = true;
-}
-
-bool ImageFrame::copyBitmapData(const ImageFrame& other)
-{
- if (this == &other)
- return true;
-
- m_hasAlpha = other.m_hasAlpha;
- m_bitmap->bitmap().reset();
- const NativeImageSkia* otherBitmap = other.m_bitmap.get();
- return otherBitmap->bitmap().copyTo(&m_bitmap->bitmap(), otherBitmap->bitmap().config());
-}
-
-bool ImageFrame::setSize(int newWidth, int newHeight)
-{
- // setSize() should only be called once, it leaks memory otherwise.
- ASSERT(!width() && !height());
-
- m_bitmap->bitmap().setConfig(SkBitmap::kARGB_8888_Config, newWidth, newHeight);
- if (!m_bitmap->bitmap().allocPixels(m_allocator, 0))
- return false;
-
- zeroFillPixelData();
- return true;
-}
-
-PassRefPtr<NativeImageSkia> ImageFrame::asNewNativeImage() const
-{
- return m_bitmap->clone();
-}
-
-bool ImageFrame::hasAlpha() const
-{
- return m_hasAlpha;
-}
-
-void ImageFrame::setHasAlpha(bool alpha)
-{
- m_hasAlpha = alpha;
-
- // If the frame is not fully loaded, there will be transparent pixels,
- // so we can't tell skia we're opaque, even for image types that logically
- // always are (e.g. jpeg).
- bool isOpaque = !m_hasAlpha;
- if (m_status != FrameComplete)
- isOpaque = false;
- m_bitmap->bitmap().setIsOpaque(isOpaque);
-}
-
-void ImageFrame::setStatus(Status status)
-{
- m_status = status;
- if (m_status == FrameComplete) {
- m_bitmap->bitmap().setIsOpaque(!m_hasAlpha);
- m_bitmap->setDataComplete(); // Tell the bitmap it's done.
- }
-}
-
-void ImageFrame::zeroFillFrameRect(const IntRect& rect)
-{
- if (rect.isEmpty())
- return;
-
- m_bitmap->bitmap().eraseArea(rect, SkColorSetARGB(0, 0, 0, 0));
- setHasAlpha(true);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/image-decoders/OWNERS b/chromium/third_party/WebKit/Source/core/platform/image-decoders/OWNERS
deleted file mode 100644
index bf426d601e0..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/image-decoders/OWNERS
+++ /dev/null
@@ -1 +0,0 @@
-pkasting@chromium.org
diff --git a/chromium/third_party/WebKit/Source/core/platform/image-decoders/bmp/BMPImageDecoder.cpp b/chromium/third_party/WebKit/Source/core/platform/image-decoders/bmp/BMPImageDecoder.cpp
deleted file mode 100644
index 3afdcbcc9dc..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/image-decoders/bmp/BMPImageDecoder.cpp
+++ /dev/null
@@ -1,157 +0,0 @@
-/*
- * Copyright (c) 2008, 2009, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/image-decoders/bmp/BMPImageDecoder.h"
-
-#include "core/platform/PlatformInstrumentation.h"
-#include "core/platform/image-decoders/bmp/BMPImageReader.h"
-#include "wtf/PassOwnPtr.h"
-
-namespace WebCore {
-
-// Number of bits in .BMP used to store the file header (doesn't match
-// "sizeof(BMPImageDecoder::BitmapFileHeader)" since we omit some fields and
-// don't pack).
-static const size_t sizeOfFileHeader = 14;
-
-BMPImageDecoder::BMPImageDecoder(ImageSource::AlphaOption alphaOption,
- ImageSource::GammaAndColorProfileOption gammaAndColorProfileOption,
- size_t maxDecodedBytes)
- : ImageDecoder(alphaOption, gammaAndColorProfileOption, maxDecodedBytes)
- , m_decodedOffset(0)
-{
-}
-
-void BMPImageDecoder::setData(SharedBuffer* data, bool allDataReceived)
-{
- if (failed())
- return;
-
- ImageDecoder::setData(data, allDataReceived);
- if (m_reader)
- m_reader->setData(data);
-}
-
-bool BMPImageDecoder::isSizeAvailable()
-{
- if (!ImageDecoder::isSizeAvailable())
- decode(true);
-
- return ImageDecoder::isSizeAvailable();
-}
-
-ImageFrame* BMPImageDecoder::frameBufferAtIndex(size_t index)
-{
- if (index)
- return 0;
-
- if (m_frameBufferCache.isEmpty()) {
- m_frameBufferCache.resize(1);
- m_frameBufferCache.first().setPremultiplyAlpha(m_premultiplyAlpha);
- }
-
- ImageFrame* buffer = &m_frameBufferCache.first();
- if (buffer->status() != ImageFrame::FrameComplete) {
- PlatformInstrumentation::willDecodeImage("BMP");
- decode(false);
- PlatformInstrumentation::didDecodeImage();
- }
- return buffer;
-}
-
-bool BMPImageDecoder::setFailed()
-{
- m_reader.clear();
- return ImageDecoder::setFailed();
-}
-
-void BMPImageDecoder::decode(bool onlySize)
-{
- if (failed())
- return;
-
- // If we couldn't decode the image but we've received all the data, decoding
- // has failed.
- if (!decodeHelper(onlySize) && isAllDataReceived())
- setFailed();
- // If we're done decoding the image, we don't need the BMPImageReader
- // anymore. (If we failed, |m_reader| has already been cleared.)
- else if (!m_frameBufferCache.isEmpty() && (m_frameBufferCache.first().status() == ImageFrame::FrameComplete))
- m_reader.clear();
-}
-
-bool BMPImageDecoder::decodeHelper(bool onlySize)
-{
- size_t imgDataOffset = 0;
- if ((m_decodedOffset < sizeOfFileHeader) && !processFileHeader(&imgDataOffset))
- return false;
-
- if (!m_reader) {
- m_reader = adoptPtr(new BMPImageReader(this, m_decodedOffset, imgDataOffset, false));
- m_reader->setData(m_data.get());
- }
-
- if (!m_frameBufferCache.isEmpty())
- m_reader->setBuffer(&m_frameBufferCache.first());
-
- return m_reader->decodeBMP(onlySize);
-}
-
-bool BMPImageDecoder::processFileHeader(size_t* imgDataOffset)
-{
- ASSERT(imgDataOffset);
-
- // Read file header.
- ASSERT(!m_decodedOffset);
- if (m_data->size() < sizeOfFileHeader)
- return false;
- const uint16_t fileType = (m_data->data()[0] << 8) | static_cast<uint8_t>(m_data->data()[1]);
- *imgDataOffset = readUint32(10);
- m_decodedOffset = sizeOfFileHeader;
-
- // See if this is a bitmap filetype we understand.
- enum {
- BMAP = 0x424D, // "BM"
- // The following additional OS/2 2.x header values (see
- // http://www.fileformat.info/format/os2bmp/egff.htm ) aren't widely
- // decoded, and are unlikely to be in much use.
- /*
- ICON = 0x4943, // "IC"
- POINTER = 0x5054, // "PT"
- COLORICON = 0x4349, // "CI"
- COLORPOINTER = 0x4350, // "CP"
- BITMAPARRAY = 0x4241, // "BA"
- */
- };
- return (fileType == BMAP) || setFailed();
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/image-decoders/bmp/BMPImageDecoder.h b/chromium/third_party/WebKit/Source/core/platform/image-decoders/bmp/BMPImageDecoder.h
deleted file mode 100644
index 44dfb3e002c..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/image-decoders/bmp/BMPImageDecoder.h
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- * Copyright (c) 2008, 2009, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef BMPImageDecoder_h
-#define BMPImageDecoder_h
-
-#include "core/platform/image-decoders/bmp/BMPImageReader.h"
-#include "wtf/OwnPtr.h"
-
-namespace WebCore {
-
- // This class decodes the BMP image format.
- class BMPImageDecoder : public ImageDecoder {
- public:
- BMPImageDecoder(ImageSource::AlphaOption, ImageSource::GammaAndColorProfileOption, size_t maxDecodedBytes);
-
- // ImageDecoder
- virtual String filenameExtension() const { return "bmp"; }
- virtual void setData(SharedBuffer*, bool allDataReceived);
- virtual bool isSizeAvailable();
- virtual ImageFrame* frameBufferAtIndex(size_t);
- // CAUTION: setFailed() deletes |m_reader|. Be careful to avoid
- // accessing deleted memory, especially when calling this from inside
- // BMPImageReader!
- virtual bool setFailed();
-
- private:
- inline uint32_t readUint32(int offset) const
- {
- return BMPImageReader::readUint32(m_data.get(), m_decodedOffset + offset);
- }
-
- // Decodes the image. If |onlySize| is true, stops decoding after
- // calculating the image size. If decoding fails but there is no more
- // data coming, sets the "decode failure" flag.
- void decode(bool onlySize);
-
- // Decodes the image. If |onlySize| is true, stops decoding after
- // calculating the image size. Returns whether decoding succeeded.
- bool decodeHelper(bool onlySize);
-
- // Processes the file header at the beginning of the data. Sets
- // |*imgDataOffset| based on the header contents. Returns true if the
- // file header could be decoded.
- bool processFileHeader(size_t* imgDataOffset);
-
- // An index into |m_data| representing how much we've already decoded.
- // Note that this only tracks data _this_ class decodes; once the
- // BMPImageReader takes over this will not be updated further.
- size_t m_decodedOffset;
-
- // The reader used to do most of the BMP decoding.
- OwnPtr<BMPImageReader> m_reader;
- };
-
-} // namespace WebCore
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/image-decoders/bmp/BMPImageReader.cpp b/chromium/third_party/WebKit/Source/core/platform/image-decoders/bmp/BMPImageReader.cpp
deleted file mode 100644
index e062eb00b77..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/image-decoders/bmp/BMPImageReader.cpp
+++ /dev/null
@@ -1,737 +0,0 @@
-/*
- * Copyright (c) 2008, 2009, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/image-decoders/bmp/BMPImageReader.h"
-
-namespace WebCore {
-
-BMPImageReader::BMPImageReader(ImageDecoder* parent, size_t decodedAndHeaderOffset, size_t imgDataOffset, bool usesAndMask)
- : m_parent(parent)
- , m_buffer(0)
- , m_decodedOffset(decodedAndHeaderOffset)
- , m_headerOffset(decodedAndHeaderOffset)
- , m_imgDataOffset(imgDataOffset)
- , m_isOS21x(false)
- , m_isOS22x(false)
- , m_isTopDown(false)
- , m_needToProcessBitmasks(false)
- , m_needToProcessColorTable(false)
- , m_tableSizeInBytes(0)
- , m_seenNonZeroAlphaPixel(false)
- , m_seenZeroAlphaPixel(false)
- , m_andMaskState(usesAndMask ? NotYetDecoded : None)
-{
- // Clue-in decodeBMP() that we need to detect the correct info header size.
- memset(&m_infoHeader, 0, sizeof(m_infoHeader));
-}
-
-bool BMPImageReader::decodeBMP(bool onlySize)
-{
- // Calculate size of info header.
- if (!m_infoHeader.biSize && !readInfoHeaderSize())
- return false;
-
- // Read and process info header.
- if ((m_decodedOffset < (m_headerOffset + m_infoHeader.biSize)) && !processInfoHeader())
- return false;
-
- // processInfoHeader() set the size, so if that's all we needed, we're done.
- if (onlySize)
- return true;
-
- // Read and process the bitmasks, if needed.
- if (m_needToProcessBitmasks && !processBitmasks())
- return false;
-
- // Read and process the color table, if needed.
- if (m_needToProcessColorTable && !processColorTable())
- return false;
-
- // Initialize the framebuffer if needed.
- ASSERT(m_buffer); // Parent should set this before asking us to decode!
- if (m_buffer->status() == ImageFrame::FrameEmpty) {
- if (!m_buffer->setSize(m_parent->size().width(), m_parent->size().height()))
- return m_parent->setFailed(); // Unable to allocate.
- m_buffer->setStatus(ImageFrame::FramePartial);
- // setSize() calls eraseARGB(), which resets the alpha flag, so we force
- // it back to false here. We'll set it true below in all cases where
- // these 0s could actually show through.
- m_buffer->setHasAlpha(false);
-
- // For BMPs, the frame always fills the entire image.
- m_buffer->setOriginalFrameRect(IntRect(IntPoint(), m_parent->size()));
-
- if (!m_isTopDown)
- m_coord.setY(m_parent->size().height() - 1);
- }
-
- // Decode the data.
- if ((m_andMaskState != Decoding) && !pastEndOfImage(0)) {
- if ((m_infoHeader.biCompression != RLE4) && (m_infoHeader.biCompression != RLE8) && (m_infoHeader.biCompression != RLE24)) {
- const ProcessingResult result = processNonRLEData(false, 0);
- if (result != Success)
- return (result == Failure) ? m_parent->setFailed() : false;
- } else if (!processRLEData())
- return false;
- }
-
- // If the image has an AND mask and there was no alpha data, process the
- // mask.
- if ((m_andMaskState == NotYetDecoded) && !m_buffer->hasAlpha()) {
- // Reset decoding coordinates to start of image.
- m_coord.setX(0);
- m_coord.setY(m_isTopDown ? 0 : (m_parent->size().height() - 1));
-
- // The AND mask is stored as 1-bit data.
- m_infoHeader.biBitCount = 1;
-
- m_andMaskState = Decoding;
- }
- if (m_andMaskState == Decoding) {
- const ProcessingResult result = processNonRLEData(false, 0);
- if (result != Success)
- return (result == Failure) ? m_parent->setFailed() : false;
- }
-
- // Done!
- m_buffer->setStatus(ImageFrame::FrameComplete);
- return true;
-}
-
-bool BMPImageReader::readInfoHeaderSize()
-{
- // Get size of info header.
- ASSERT(m_decodedOffset == m_headerOffset);
- if ((m_decodedOffset > m_data->size()) || ((m_data->size() - m_decodedOffset) < 4))
- return false;
- m_infoHeader.biSize = readUint32(0);
- // Don't increment m_decodedOffset here, it just makes the code in
- // processInfoHeader() more confusing.
-
- // Don't allow the header to overflow (which would be harmless here, but
- // problematic or at least confusing in other places), or to overrun the
- // image data.
- if (((m_headerOffset + m_infoHeader.biSize) < m_headerOffset) || (m_imgDataOffset && (m_imgDataOffset < (m_headerOffset + m_infoHeader.biSize))))
- return m_parent->setFailed();
-
- // See if this is a header size we understand:
- // OS/2 1.x: 12
- if (m_infoHeader.biSize == 12)
- m_isOS21x = true;
- // Windows V3: 40
- else if ((m_infoHeader.biSize == 40) || isWindowsV4Plus())
- ;
- // OS/2 2.x: any multiple of 4 between 16 and 64, inclusive, or 42 or 46
- else if ((m_infoHeader.biSize >= 16) && (m_infoHeader.biSize <= 64) && (!(m_infoHeader.biSize & 3) || (m_infoHeader.biSize == 42) || (m_infoHeader.biSize == 46)))
- m_isOS22x = true;
- else
- return m_parent->setFailed();
-
- return true;
-}
-
-bool BMPImageReader::processInfoHeader()
-{
- // Read info header.
- ASSERT(m_decodedOffset == m_headerOffset);
- if ((m_decodedOffset > m_data->size()) || ((m_data->size() - m_decodedOffset) < m_infoHeader.biSize) || !readInfoHeader())
- return false;
- m_decodedOffset += m_infoHeader.biSize;
-
- // Sanity-check header values.
- if (!isInfoHeaderValid())
- return m_parent->setFailed();
-
- // Set our size.
- if (!m_parent->setSize(m_infoHeader.biWidth, m_infoHeader.biHeight))
- return false;
-
- // For paletted images, bitmaps can set biClrUsed to 0 to mean "all
- // colors", so set it to the maximum number of colors for this bit depth.
- // Also do this for bitmaps that put too large a value here.
- if (m_infoHeader.biBitCount < 16) {
- const uint32_t maxColors = static_cast<uint32_t>(1) << m_infoHeader.biBitCount;
- if (!m_infoHeader.biClrUsed || (m_infoHeader.biClrUsed > maxColors))
- m_infoHeader.biClrUsed = maxColors;
- }
-
- // For any bitmaps that set their BitCount to the wrong value, reset the
- // counts now that we've calculated the number of necessary colors, since
- // other code relies on this value being correct.
- if (m_infoHeader.biCompression == RLE8)
- m_infoHeader.biBitCount = 8;
- else if (m_infoHeader.biCompression == RLE4)
- m_infoHeader.biBitCount = 4;
-
- // Tell caller what still needs to be processed.
- if (m_infoHeader.biBitCount >= 16)
- m_needToProcessBitmasks = true;
- else if (m_infoHeader.biBitCount)
- m_needToProcessColorTable = true;
-
- return true;
-}
-
-bool BMPImageReader::readInfoHeader()
-{
- // Pre-initialize some fields that not all headers set.
- m_infoHeader.biCompression = RGB;
- m_infoHeader.biClrUsed = 0;
-
- if (m_isOS21x) {
- m_infoHeader.biWidth = readUint16(4);
- m_infoHeader.biHeight = readUint16(6);
- ASSERT(m_andMaskState == None); // ICO is a Windows format, not OS/2!
- m_infoHeader.biBitCount = readUint16(10);
- return true;
- }
-
- m_infoHeader.biWidth = readUint32(4);
- m_infoHeader.biHeight = readUint32(8);
- if (m_andMaskState != None)
- m_infoHeader.biHeight /= 2;
- m_infoHeader.biBitCount = readUint16(14);
-
- // Read compression type, if present.
- if (m_infoHeader.biSize >= 20) {
- uint32_t biCompression = readUint32(16);
-
- // Detect OS/2 2.x-specific compression types.
- if ((biCompression == 3) && (m_infoHeader.biBitCount == 1)) {
- m_infoHeader.biCompression = HUFFMAN1D;
- m_isOS22x = true;
- } else if ((biCompression == 4) && (m_infoHeader.biBitCount == 24)) {
- m_infoHeader.biCompression = RLE24;
- m_isOS22x = true;
- } else if (biCompression > 5)
- return m_parent->setFailed(); // Some type we don't understand.
- else
- m_infoHeader.biCompression = static_cast<CompressionType>(biCompression);
- }
-
- // Read colors used, if present.
- if (m_infoHeader.biSize >= 36)
- m_infoHeader.biClrUsed = readUint32(32);
-
- // Windows V4+ can safely read the four bitmasks from 40-56 bytes in, so do
- // that here. If the bit depth is less than 16, these values will be
- // ignored by the image data decoders. If the bit depth is at least 16 but
- // the compression format isn't BITFIELDS, these values will be ignored and
- // overwritten* in processBitmasks().
- // NOTE: We allow alpha here. Microsoft doesn't really document this well,
- // but some BMPs appear to use it.
- //
- // For non-Windows V4+, m_bitMasks[] et. al will be initialized later
- // during processBitmasks().
- //
- // *Except the alpha channel. Bizarrely, some RGB bitmaps expect decoders
- // to pay attention to the alpha mask here, so there's a special case in
- // processBitmasks() that doesn't always overwrite that value.
- if (isWindowsV4Plus()) {
- m_bitMasks[0] = readUint32(40);
- m_bitMasks[1] = readUint32(44);
- m_bitMasks[2] = readUint32(48);
- m_bitMasks[3] = readUint32(52);
- }
-
- // Detect top-down BMPs.
- if (m_infoHeader.biHeight < 0) {
- m_isTopDown = true;
- m_infoHeader.biHeight = -m_infoHeader.biHeight;
- }
-
- return true;
-}
-
-bool BMPImageReader::isInfoHeaderValid() const
-{
- // Non-positive widths/heights are invalid. (We've already flipped the
- // sign of the height for top-down bitmaps.)
- if ((m_infoHeader.biWidth <= 0) || !m_infoHeader.biHeight)
- return false;
-
- // Only Windows V3+ has top-down bitmaps.
- if (m_isTopDown && (m_isOS21x || m_isOS22x))
- return false;
-
- // Only bit depths of 1, 4, 8, or 24 are universally supported.
- if ((m_infoHeader.biBitCount != 1) && (m_infoHeader.biBitCount != 4) && (m_infoHeader.biBitCount != 8) && (m_infoHeader.biBitCount != 24)) {
- // Windows V3+ additionally supports bit depths of 0 (for embedded
- // JPEG/PNG images), 16, and 32.
- if (m_isOS21x || m_isOS22x || (m_infoHeader.biBitCount && (m_infoHeader.biBitCount != 16) && (m_infoHeader.biBitCount != 32)))
- return false;
- }
-
- // Each compression type is only valid with certain bit depths (except RGB,
- // which can be used with any bit depth). Also, some formats do not
- // some compression types.
- switch (m_infoHeader.biCompression) {
- case RGB:
- if (!m_infoHeader.biBitCount)
- return false;
- break;
-
- case RLE8:
- // Supposedly there are undocumented formats like "BitCount = 1,
- // Compression = RLE4" (which means "4 bit, but with a 2-color table"),
- // so also allow the paletted RLE compression types to have too low a
- // bit count; we'll correct this later.
- if (!m_infoHeader.biBitCount || (m_infoHeader.biBitCount > 8))
- return false;
- break;
-
- case RLE4:
- // See comments in RLE8.
- if (!m_infoHeader.biBitCount || (m_infoHeader.biBitCount > 4))
- return false;
- break;
-
- case BITFIELDS:
- // Only valid for Windows V3+.
- if (m_isOS21x || m_isOS22x || ((m_infoHeader.biBitCount != 16) && (m_infoHeader.biBitCount != 32)))
- return false;
- break;
-
- case JPEG:
- case PNG:
- // Only valid for Windows V3+.
- if (m_isOS21x || m_isOS22x || m_infoHeader.biBitCount)
- return false;
- break;
-
- case HUFFMAN1D:
- // Only valid for OS/2 2.x.
- if (!m_isOS22x || (m_infoHeader.biBitCount != 1))
- return false;
- break;
-
- case RLE24:
- // Only valid for OS/2 2.x.
- if (!m_isOS22x || (m_infoHeader.biBitCount != 24))
- return false;
- break;
-
- default:
- // Some type we don't understand. This should have been caught in
- // readInfoHeader().
- ASSERT_NOT_REACHED();
- return false;
- }
-
- // Top-down bitmaps cannot be compressed; they must be RGB or BITFIELDS.
- if (m_isTopDown && (m_infoHeader.biCompression != RGB) && (m_infoHeader.biCompression != BITFIELDS))
- return false;
-
- // Reject the following valid bitmap types that we don't currently bother
- // decoding. Few other people decode these either, they're unlikely to be
- // in much use.
- // TODO(pkasting): Consider supporting these someday.
- // * Bitmaps larger than 2^16 pixels in either dimension (Windows
- // probably doesn't draw these well anyway, and the decoded data would
- // take a lot of memory).
- if ((m_infoHeader.biWidth >= (1 << 16)) || (m_infoHeader.biHeight >= (1 << 16)))
- return false;
- // * Windows V3+ JPEG-in-BMP and PNG-in-BMP bitmaps (supposedly not found
- // in the wild, only used to send data to printers?).
- if ((m_infoHeader.biCompression == JPEG) || (m_infoHeader.biCompression == PNG))
- return false;
- // * OS/2 2.x Huffman-encoded monochrome bitmaps (see
- // http://www.fileformat.info/mirror/egff/ch09_05.htm , re: "G31D"
- // algorithm).
- if (m_infoHeader.biCompression == HUFFMAN1D)
- return false;
-
- return true;
-}
-
-bool BMPImageReader::processBitmasks()
-{
- // Create m_bitMasks[] values.
- if (m_infoHeader.biCompression != BITFIELDS) {
- // The format doesn't actually use bitmasks. To simplify the decode
- // logic later, create bitmasks for the RGB data. For Windows V4+,
- // this overwrites the masks we read from the header, which are
- // supposed to be ignored in non-BITFIELDS cases.
- // 16 bits: MSB <- xRRRRRGG GGGBBBBB -> LSB
- // 24/32 bits: MSB <- [AAAAAAAA] RRRRRRRR GGGGGGGG BBBBBBBB -> LSB
- const int numBits = (m_infoHeader.biBitCount == 16) ? 5 : 8;
- for (int i = 0; i <= 2; ++i)
- m_bitMasks[i] = ((static_cast<uint32_t>(1) << (numBits * (3 - i))) - 1) ^ ((static_cast<uint32_t>(1) << (numBits * (2 - i))) - 1);
-
- // For Windows V4+ 32-bit RGB, don't overwrite the alpha mask from the
- // header (see note in readInfoHeader()).
- if (m_infoHeader.biBitCount < 32)
- m_bitMasks[3] = 0;
- else if (!isWindowsV4Plus())
- m_bitMasks[3] = static_cast<uint32_t>(0xff000000);
- } else if (!isWindowsV4Plus()) {
- // For Windows V4+ BITFIELDS mode bitmaps, this was already done when
- // we read the info header.
-
- // Fail if we don't have enough file space for the bitmasks.
- static const size_t SIZEOF_BITMASKS = 12;
- if (((m_headerOffset + m_infoHeader.biSize + SIZEOF_BITMASKS) < (m_headerOffset + m_infoHeader.biSize)) || (m_imgDataOffset && (m_imgDataOffset < (m_headerOffset + m_infoHeader.biSize + SIZEOF_BITMASKS))))
- return m_parent->setFailed();
-
- // Read bitmasks.
- if ((m_data->size() - m_decodedOffset) < SIZEOF_BITMASKS)
- return false;
- m_bitMasks[0] = readUint32(0);
- m_bitMasks[1] = readUint32(4);
- m_bitMasks[2] = readUint32(8);
- // No alpha in anything other than Windows V4+.
- m_bitMasks[3] = 0;
-
- m_decodedOffset += SIZEOF_BITMASKS;
- }
-
- // We've now decoded all the non-image data we care about. Skip anything
- // else before the actual raster data.
- if (m_imgDataOffset)
- m_decodedOffset = m_imgDataOffset;
- m_needToProcessBitmasks = false;
-
- // Check masks and set shift values.
- for (int i = 0; i < 4; ++i) {
- // Trim the mask to the allowed bit depth. Some Windows V4+ BMPs
- // specify a bogus alpha channel in bits that don't exist in the pixel
- // data (for example, bits 25-31 in a 24-bit RGB format).
- if (m_infoHeader.biBitCount < 32)
- m_bitMasks[i] &= ((static_cast<uint32_t>(1) << m_infoHeader.biBitCount) - 1);
-
- // For empty masks (common on the alpha channel, especially after the
- // trimming above), quickly clear the shifts and continue, to avoid an
- // infinite loop in the counting code below.
- uint32_t tempMask = m_bitMasks[i];
- if (!tempMask) {
- m_bitShiftsRight[i] = m_bitShiftsLeft[i] = 0;
- continue;
- }
-
- // Make sure bitmask does not overlap any other bitmasks.
- for (int j = 0; j < i; ++j) {
- if (tempMask & m_bitMasks[j])
- return m_parent->setFailed();
- }
-
- // Count offset into pixel data.
- for (m_bitShiftsRight[i] = 0; !(tempMask & 1); tempMask >>= 1)
- ++m_bitShiftsRight[i];
-
- // Count size of mask.
- for (m_bitShiftsLeft[i] = 8; tempMask & 1; tempMask >>= 1)
- --m_bitShiftsLeft[i];
-
- // Make sure bitmask is contiguous.
- if (tempMask)
- return m_parent->setFailed();
-
- // Since RGBABuffer tops out at 8 bits per channel, adjust the shift
- // amounts to use the most significant 8 bits of the channel.
- if (m_bitShiftsLeft[i] < 0) {
- m_bitShiftsRight[i] -= m_bitShiftsLeft[i];
- m_bitShiftsLeft[i] = 0;
- }
- }
-
- return true;
-}
-
-bool BMPImageReader::processColorTable()
-{
- m_tableSizeInBytes = m_infoHeader.biClrUsed * (m_isOS21x ? 3 : 4);
-
- // Fail if we don't have enough file space for the color table.
- if (((m_headerOffset + m_infoHeader.biSize + m_tableSizeInBytes) < (m_headerOffset + m_infoHeader.biSize)) || (m_imgDataOffset && (m_imgDataOffset < (m_headerOffset + m_infoHeader.biSize + m_tableSizeInBytes))))
- return m_parent->setFailed();
-
- // Read color table.
- if ((m_decodedOffset > m_data->size()) || ((m_data->size() - m_decodedOffset) < m_tableSizeInBytes))
- return false;
- m_colorTable.resize(m_infoHeader.biClrUsed);
- for (size_t i = 0; i < m_infoHeader.biClrUsed; ++i) {
- m_colorTable[i].rgbBlue = m_data->data()[m_decodedOffset++];
- m_colorTable[i].rgbGreen = m_data->data()[m_decodedOffset++];
- m_colorTable[i].rgbRed = m_data->data()[m_decodedOffset++];
- // Skip padding byte (not present on OS/2 1.x).
- if (!m_isOS21x)
- ++m_decodedOffset;
- }
-
- // We've now decoded all the non-image data we care about. Skip anything
- // else before the actual raster data.
- if (m_imgDataOffset)
- m_decodedOffset = m_imgDataOffset;
- m_needToProcessColorTable = false;
-
- return true;
-}
-
-bool BMPImageReader::processRLEData()
-{
- if (m_decodedOffset > m_data->size())
- return false;
-
- // RLE decoding is poorly specified. Two main problems:
- // (1) Are EOL markers necessary? What happens when we have too many
- // pixels for one row?
- // http://www.fileformat.info/format/bmp/egff.htm says extra pixels
- // should wrap to the next line. Real BMPs I've encountered seem to
- // instead expect extra pixels to be ignored until the EOL marker is
- // seen, although this has only happened in a few cases and I suspect
- // those BMPs may be invalid. So we only change lines on EOL (or Delta
- // with dy > 0), and fail in most cases when pixels extend past the end
- // of the line.
- // (2) When Delta, EOL, or EOF are seen, what happens to the "skipped"
- // pixels?
- // http://www.daubnet.com/formats/BMP.html says these should be filled
- // with color 0. However, the "do nothing" and "don't care" comments
- // of other references suggest leaving these alone, i.e. letting them
- // be transparent to the background behind the image. This seems to
- // match how MSPAINT treats BMPs, so we do that. Note that when we
- // actually skip pixels for a case like this, we need to note on the
- // framebuffer that we have alpha.
-
- // Impossible to decode row-at-a-time, so just do things as a stream of
- // bytes.
- while (true) {
- // Every entry takes at least two bytes; bail if there isn't enough
- // data.
- if ((m_data->size() - m_decodedOffset) < 2)
- return false;
-
- // For every entry except EOF, we'd better not have reached the end of
- // the image.
- const uint8_t count = m_data->data()[m_decodedOffset];
- const uint8_t code = m_data->data()[m_decodedOffset + 1];
- if ((count || (code != 1)) && pastEndOfImage(0))
- return m_parent->setFailed();
-
- // Decode.
- if (!count) {
- switch (code) {
- case 0: // Magic token: EOL
- // Skip any remaining pixels in this row.
- if (m_coord.x() < m_parent->size().width())
- m_buffer->setHasAlpha(true);
- moveBufferToNextRow();
-
- m_decodedOffset += 2;
- break;
-
- case 1: // Magic token: EOF
- // Skip any remaining pixels in the image.
- if ((m_coord.x() < m_parent->size().width()) || (m_isTopDown ? (m_coord.y() < (m_parent->size().height() - 1)) : (m_coord.y() > 0)))
- m_buffer->setHasAlpha(true);
- return true;
-
- case 2: { // Magic token: Delta
- // The next two bytes specify dx and dy. Bail if there isn't
- // enough data.
- if ((m_data->size() - m_decodedOffset) < 4)
- return false;
-
- // Fail if this takes us past the end of the desired row or
- // past the end of the image.
- const uint8_t dx = m_data->data()[m_decodedOffset + 2];
- const uint8_t dy = m_data->data()[m_decodedOffset + 3];
- if (dx || dy)
- m_buffer->setHasAlpha(true);
- if (((m_coord.x() + dx) > m_parent->size().width()) || pastEndOfImage(dy))
- return m_parent->setFailed();
-
- // Skip intervening pixels.
- m_coord.move(dx, m_isTopDown ? dy : -dy);
-
- m_decodedOffset += 4;
- break;
- }
-
- default: { // Absolute mode
- // |code| pixels specified as in BI_RGB, zero-padded at the end
- // to a multiple of 16 bits.
- // Because processNonRLEData() expects m_decodedOffset to
- // point to the beginning of the pixel data, bump it past
- // the escape bytes and then reset if decoding failed.
- m_decodedOffset += 2;
- const ProcessingResult result = processNonRLEData(true, code);
- if (result == Failure)
- return m_parent->setFailed();
- if (result == InsufficientData) {
- m_decodedOffset -= 2;
- return false;
- }
- break;
- }
- }
- } else { // Encoded mode
- // The following color data is repeated for |count| total pixels.
- // Strangely, some BMPs seem to specify excessively large counts
- // here; ignore pixels past the end of the row.
- const int endX = std::min(m_coord.x() + count, m_parent->size().width());
-
- if (m_infoHeader.biCompression == RLE24) {
- // Bail if there isn't enough data.
- if ((m_data->size() - m_decodedOffset) < 4)
- return false;
-
- // One BGR triple that we copy |count| times.
- fillRGBA(endX, m_data->data()[m_decodedOffset + 3], m_data->data()[m_decodedOffset + 2], code, 0xff);
- m_decodedOffset += 4;
- } else {
- // RLE8 has one color index that gets repeated; RLE4 has two
- // color indexes in the upper and lower 4 bits of the byte,
- // which are alternated.
- size_t colorIndexes[2] = {code, code};
- if (m_infoHeader.biCompression == RLE4) {
- colorIndexes[0] = (colorIndexes[0] >> 4) & 0xf;
- colorIndexes[1] &= 0xf;
- }
- if ((colorIndexes[0] >= m_infoHeader.biClrUsed) || (colorIndexes[1] >= m_infoHeader.biClrUsed))
- return m_parent->setFailed();
- for (int which = 0; m_coord.x() < endX; ) {
- setI(colorIndexes[which]);
- which = !which;
- }
-
- m_decodedOffset += 2;
- }
- }
- }
-}
-
-BMPImageReader::ProcessingResult BMPImageReader::processNonRLEData(bool inRLE, int numPixels)
-{
- if (m_decodedOffset > m_data->size())
- return InsufficientData;
-
- if (!inRLE)
- numPixels = m_parent->size().width();
-
- // Fail if we're being asked to decode more pixels than remain in the row.
- const int endX = m_coord.x() + numPixels;
- if (endX > m_parent->size().width())
- return Failure;
-
- // Determine how many bytes of data the requested number of pixels
- // requires.
- const size_t pixelsPerByte = 8 / m_infoHeader.biBitCount;
- const size_t bytesPerPixel = m_infoHeader.biBitCount / 8;
- const size_t unpaddedNumBytes = (m_infoHeader.biBitCount < 16) ? ((numPixels + pixelsPerByte - 1) / pixelsPerByte) : (numPixels * bytesPerPixel);
- // RLE runs are zero-padded at the end to a multiple of 16 bits. Non-RLE
- // data is in rows and is zero-padded to a multiple of 32 bits.
- const size_t alignBits = inRLE ? 1 : 3;
- const size_t paddedNumBytes = (unpaddedNumBytes + alignBits) & ~alignBits;
-
- // Decode as many rows as we can. (For RLE, where we only want to decode
- // one row, we've already checked that this condition is true.)
- while (!pastEndOfImage(0)) {
- // Bail if we don't have enough data for the desired number of pixels.
- if ((m_data->size() - m_decodedOffset) < paddedNumBytes)
- return InsufficientData;
-
- if (m_infoHeader.biBitCount < 16) {
- // Paletted data. Pixels are stored little-endian within bytes.
- // Decode pixels one byte at a time, left to right (so, starting at
- // the most significant bits in the byte).
- const uint8_t mask = (1 << m_infoHeader.biBitCount) - 1;
- for (size_t byte = 0; byte < unpaddedNumBytes; ++byte) {
- uint8_t pixelData = m_data->data()[m_decodedOffset + byte];
- for (size_t pixel = 0; (pixel < pixelsPerByte) && (m_coord.x() < endX); ++pixel) {
- const size_t colorIndex = (pixelData >> (8 - m_infoHeader.biBitCount)) & mask;
- if (m_andMaskState == Decoding) {
- // There's no way to accurately represent an AND + XOR
- // operation as an RGBA image, so where the AND values
- // are 1, we simply set the framebuffer pixels to fully
- // transparent, on the assumption that most ICOs on the
- // web will not be doing a lot of inverting.
- if (colorIndex) {
- setRGBA(0, 0, 0, 0);
- m_buffer->setHasAlpha(true);
- } else
- m_coord.move(1, 0);
- } else {
- if (colorIndex >= m_infoHeader.biClrUsed)
- return Failure;
- setI(colorIndex);
- }
- pixelData <<= m_infoHeader.biBitCount;
- }
- }
- } else {
- // RGB data. Decode pixels one at a time, left to right.
- while (m_coord.x() < endX) {
- const uint32_t pixel = readCurrentPixel(bytesPerPixel);
-
- // Some BMPs specify an alpha channel but don't actually use it
- // (it contains all 0s). To avoid displaying these images as
- // fully-transparent, decode as if images are fully opaque
- // until we actually see a non-zero alpha value; at that point,
- // reset any previously-decoded pixels to fully transparent and
- // continue decoding based on the real alpha channel values.
- // As an optimization, avoid setting "hasAlpha" to true for
- // images where all alpha values are 255; opaque images are
- // faster to draw.
- int alpha = getAlpha(pixel);
- if (!m_seenNonZeroAlphaPixel && !alpha) {
- m_seenZeroAlphaPixel = true;
- alpha = 255;
- } else {
- m_seenNonZeroAlphaPixel = true;
- if (m_seenZeroAlphaPixel) {
- m_buffer->zeroFillPixelData();
- m_seenZeroAlphaPixel = false;
- } else if (alpha != 255)
- m_buffer->setHasAlpha(true);
- }
-
- setRGBA(getComponent(pixel, 0), getComponent(pixel, 1),
- getComponent(pixel, 2), alpha);
- }
- }
-
- // Success, keep going.
- m_decodedOffset += paddedNumBytes;
- if (inRLE)
- return Success;
- moveBufferToNextRow();
- }
-
- // Finished decoding whole image.
- return Success;
-}
-
-void BMPImageReader::moveBufferToNextRow()
-{
- m_coord.move(-m_coord.x(), m_isTopDown ? 1 : -1);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/image-decoders/bmp/BMPImageReader.h b/chromium/third_party/WebKit/Source/core/platform/image-decoders/bmp/BMPImageReader.h
deleted file mode 100644
index 066a26c2e91..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/image-decoders/bmp/BMPImageReader.h
+++ /dev/null
@@ -1,356 +0,0 @@
-/*
- * Copyright (c) 2008, 2009, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef BMPImageReader_h
-#define BMPImageReader_h
-
-#include <stdint.h>
-#include "core/platform/image-decoders/ImageDecoder.h"
-#include "wtf/CPU.h"
-
-namespace WebCore {
-
- // This class decodes a BMP image. It is used in the BMP and ICO decoders,
- // which wrap it in the appropriate code to read file headers, etc.
- class BMPImageReader {
- WTF_MAKE_FAST_ALLOCATED;
- public:
- // Read a value from |data[offset]|, converting from little to native
- // endianness.
- static inline uint16_t readUint16(SharedBuffer* data, int offset)
- {
- uint16_t result;
- memcpy(&result, &data->data()[offset], 2);
- #if CPU(BIG_ENDIAN)
- result = ((result & 0xff) << 8) | ((result & 0xff00) >> 8);
- #endif
- return result;
- }
-
- static inline uint32_t readUint32(SharedBuffer* data, int offset)
- {
- uint32_t result;
- memcpy(&result, &data->data()[offset], 4);
- #if CPU(BIG_ENDIAN)
- result = ((result & 0xff) << 24) | ((result & 0xff00) << 8) | ((result & 0xff0000) >> 8) | ((result & 0xff000000) >> 24);
- #endif
- return result;
- }
-
- // |parent| is the decoder that owns us.
- // |startOffset| points to the start of the BMP within the file.
- // |buffer| points at an empty ImageFrame that we'll initialize and
- // fill with decoded data.
- BMPImageReader(ImageDecoder* parent, size_t decodedAndHeaderOffset, size_t imgDataOffset, bool usesAndMask);
-
- void setBuffer(ImageFrame* buffer) { m_buffer = buffer; }
- void setData(SharedBuffer* data) { m_data = data; }
-
- // Does the actual decoding. If |onlySize| is true, decoding only
- // progresses as far as necessary to get the image size. Returns
- // whether decoding succeeded.
- bool decodeBMP(bool onlySize);
-
- private:
- // The various BMP compression types. We don't currently decode all
- // these.
- enum CompressionType {
- // Universal types
- RGB = 0,
- RLE8 = 1,
- RLE4 = 2,
- // Windows V3+ only
- BITFIELDS = 3,
- JPEG = 4,
- PNG = 5,
- // OS/2 2.x-only
- HUFFMAN1D, // Stored in file as 3
- RLE24, // Stored in file as 4
- };
- enum AndMaskState {
- None,
- NotYetDecoded,
- Decoding,
- };
- enum ProcessingResult {
- Success,
- Failure,
- InsufficientData,
- };
-
- // These are based on the Windows BITMAPINFOHEADER and RGBTRIPLE
- // structs, but with unnecessary entries removed.
- struct BitmapInfoHeader {
- uint32_t biSize;
- int32_t biWidth;
- int32_t biHeight;
- uint16_t biBitCount;
- CompressionType biCompression;
- uint32_t biClrUsed;
- };
- struct RGBTriple {
- uint8_t rgbBlue;
- uint8_t rgbGreen;
- uint8_t rgbRed;
- };
-
- inline uint16_t readUint16(int offset) const
- {
- return readUint16(m_data.get(), m_decodedOffset + offset);
- }
-
- inline uint32_t readUint32(int offset) const
- {
- return readUint32(m_data.get(), m_decodedOffset + offset);
- }
-
- // Determines the size of the BMP info header. Returns true if the size
- // is valid.
- bool readInfoHeaderSize();
-
- // Processes the BMP info header. Returns true if the info header could
- // be decoded.
- bool processInfoHeader();
-
- // Helper function for processInfoHeader() which does the actual reading
- // of header values from the byte stream. Returns false on error.
- bool readInfoHeader();
-
- // Returns true if this is a Windows V4+ BMP.
- inline bool isWindowsV4Plus() const
- {
- // Windows V4 info header is 108 bytes. V5 is 124 bytes.
- return (m_infoHeader.biSize == 108) || (m_infoHeader.biSize == 124);
- }
-
- // Returns false if consistency errors are found in the info header.
- bool isInfoHeaderValid() const;
-
- // For BI_BITFIELDS images, initializes the m_bitMasks[] and
- // m_bitOffsets[] arrays. processInfoHeader() will initialize these for
- // other compression types where needed.
- bool processBitmasks();
-
- // For paletted images, allocates and initializes the m_colorTable[]
- // array.
- bool processColorTable();
-
- // Processes an RLE-encoded image. Returns true if the entire image was
- // decoded.
- bool processRLEData();
-
- // Processes a set of non-RLE-compressed pixels. Two cases:
- // * inRLE = true: the data is inside an RLE-encoded bitmap. Tries to
- // process |numPixels| pixels on the current row.
- // * inRLE = false: the data is inside a non-RLE-encoded bitmap.
- // |numPixels| is ignored. Expects |m_coord| to point at the
- // beginning of the next row to be decoded. Tries to process as
- // many complete rows as possible. Returns InsufficientData if
- // there wasn't enough data to decode the whole image.
- //
- // This function returns a ProcessingResult instead of a bool so that it
- // can avoid calling m_parent->setFailed(), which could lead to memory
- // corruption since that will delete |this| but some callers still want
- // to access member variables after this returns.
- ProcessingResult processNonRLEData(bool inRLE, int numPixels);
-
- // Returns true if the current y-coordinate plus |numRows| would be past
- // the end of the image. Here "plus" means "toward the end of the
- // image", so downwards for m_isTopDown images and upwards otherwise.
- inline bool pastEndOfImage(int numRows)
- {
- return m_isTopDown ? ((m_coord.y() + numRows) >= m_parent->size().height()) : ((m_coord.y() - numRows) < 0);
- }
-
- // Returns the pixel data for the current X coordinate in a uint32_t.
- // Assumes m_decodedOffset has been set to the beginning of the current
- // row.
- // NOTE: Only as many bytes of the return value as are needed to hold
- // the pixel data will actually be set.
- inline uint32_t readCurrentPixel(int bytesPerPixel) const
- {
- const int offset = m_coord.x() * bytesPerPixel;
- switch (bytesPerPixel) {
- case 2:
- return readUint16(offset);
-
- case 3: {
- // It doesn't matter that we never set the most significant byte
- // of the return value here in little-endian mode, the caller
- // won't read it.
- uint32_t pixel;
- memcpy(&pixel, &m_data->data()[m_decodedOffset + offset], 3);
- #if CPU(BIG_ENDIAN)
- pixel = ((pixel & 0xff00) << 8) | ((pixel & 0xff0000) >> 8) | ((pixel & 0xff000000) >> 24);
- #endif
- return pixel;
- }
-
- case 4:
- return readUint32(offset);
-
- default:
- ASSERT_NOT_REACHED();
- return 0;
- }
- }
-
- // Returns the value of the desired component (0, 1, 2, 3 == R, G, B, A)
- // in the given pixel data.
- inline unsigned getComponent(uint32_t pixel, int component) const
- {
- return ((pixel & m_bitMasks[component]) >> m_bitShiftsRight[component]) << m_bitShiftsLeft[component];
- }
-
- inline unsigned getAlpha(uint32_t pixel) const
- {
- // For images without alpha, return alpha of 0xff.
- return m_bitMasks[3] ? getComponent(pixel, 3) : 0xff;
- }
-
- // Sets the current pixel to the color given by |colorIndex|. This also
- // increments the relevant local variables to move the current pixel
- // right by one.
- inline void setI(size_t colorIndex)
- {
- setRGBA(m_colorTable[colorIndex].rgbRed, m_colorTable[colorIndex].rgbGreen, m_colorTable[colorIndex].rgbBlue, 0xff);
- }
-
- // Like setI(), but with the individual component values specified.
- inline void setRGBA(unsigned red,
- unsigned green,
- unsigned blue,
- unsigned alpha)
- {
- m_buffer->setRGBA(m_coord.x(), m_coord.y(), red, green, blue, alpha);
- m_coord.move(1, 0);
- }
-
- // Fills pixels from the current X-coordinate up to, but not including,
- // |endCoord| with the color given by the individual components. This
- // also increments the relevant local variables to move the current
- // pixel right to |endCoord|.
- inline void fillRGBA(int endCoord,
- unsigned red,
- unsigned green,
- unsigned blue,
- unsigned alpha)
- {
- while (m_coord.x() < endCoord)
- setRGBA(red, green, blue, alpha);
- }
-
- // Resets the relevant local variables to start drawing at the left edge
- // of the "next" row, where "next" is above or below the current row
- // depending on the value of |m_isTopDown|.
- void moveBufferToNextRow();
-
- // The decoder that owns us.
- ImageDecoder* m_parent;
-
- // The destination for the pixel data.
- ImageFrame* m_buffer;
-
- // The file to decode.
- RefPtr<SharedBuffer> m_data;
-
- // An index into |m_data| representing how much we've already decoded.
- size_t m_decodedOffset;
-
- // The file offset at which the BMP info header starts.
- size_t m_headerOffset;
-
- // The file offset at which the actual image bits start. When decoding
- // ICO files, this is set to 0, since it's not stored anywhere in a
- // header; the reader functions expect the image data to start
- // immediately after the header and (if necessary) color table.
- size_t m_imgDataOffset;
-
- // The BMP info header.
- BitmapInfoHeader m_infoHeader;
-
- // True if this is an OS/2 1.x (aka Windows 2.x) BMP. The struct
- // layouts for this type of BMP are slightly different from the later,
- // more common formats.
- bool m_isOS21x;
-
- // True if this is an OS/2 2.x BMP. The meanings of compression types 3
- // and 4 for this type of BMP differ from Windows V3+ BMPs.
- //
- // This will be falsely negative in some cases, but only ones where the
- // way we misinterpret the data is irrelevant.
- bool m_isOS22x;
-
- // True if the BMP is not vertically flipped, that is, the first line of
- // raster data in the file is the top line of the image.
- bool m_isTopDown;
-
- // These flags get set to false as we finish each processing stage.
- bool m_needToProcessBitmasks;
- bool m_needToProcessColorTable;
-
- // Masks/offsets for the color values for non-palette formats. These
- // are bitwise, with array entries 0, 1, 2, 3 corresponding to R, G, B,
- // A.
- //
- // The right/left shift values are meant to be applied after the masks.
- // We need to right shift to compensate for the bitfields' offsets into
- // the 32 bits of pixel data, and left shift to scale the color values
- // up for fields with less than 8 bits of precision. Sadly, we can't
- // just combine these into one shift value because the net shift amount
- // could go either direction. (If only "<< -x" were equivalent to
- // ">> x"...)
- uint32_t m_bitMasks[4];
- int m_bitShiftsRight[4];
- int m_bitShiftsLeft[4];
-
- // The color palette, for paletted formats.
- size_t m_tableSizeInBytes;
- Vector<RGBTriple> m_colorTable;
-
- // The coordinate to which we've decoded the image.
- IntPoint m_coord;
-
- // Variables that track whether we've seen pixels with alpha values != 0
- // and == 0, respectively. See comments in processNonRLEData() on how
- // these are used.
- bool m_seenNonZeroAlphaPixel;
- bool m_seenZeroAlphaPixel;
-
- // ICOs store a 1bpp "mask" immediately after the main bitmap image data
- // (and, confusingly, add its height to the biHeight value in the info
- // header, thus doubling it). This variable tracks whether we have such
- // a mask and if we've started decoding it yet.
- AndMaskState m_andMaskState;
- };
-
-} // namespace WebCore
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/image-decoders/gif/GIFImageDecoder.cpp b/chromium/third_party/WebKit/Source/core/platform/image-decoders/gif/GIFImageDecoder.cpp
deleted file mode 100644
index 9a69d6605e4..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/image-decoders/gif/GIFImageDecoder.cpp
+++ /dev/null
@@ -1,386 +0,0 @@
-/*
- * Copyright (C) 2006 Apple Computer, Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/image-decoders/gif/GIFImageDecoder.h"
-
-#include <limits>
-#include "core/platform/PlatformInstrumentation.h"
-#include "core/platform/image-decoders/gif/GIFImageReader.h"
-#include "wtf/NotFound.h"
-#include "wtf/PassOwnPtr.h"
-
-namespace WebCore {
-
-GIFImageDecoder::GIFImageDecoder(ImageSource::AlphaOption alphaOption,
- ImageSource::GammaAndColorProfileOption gammaAndColorProfileOption,
- size_t maxDecodedBytes)
- : ImageDecoder(alphaOption, gammaAndColorProfileOption, maxDecodedBytes)
- , m_repetitionCount(cAnimationLoopOnce)
-{
-}
-
-GIFImageDecoder::~GIFImageDecoder()
-{
-}
-
-void GIFImageDecoder::setData(SharedBuffer* data, bool allDataReceived)
-{
- if (failed())
- return;
-
- ImageDecoder::setData(data, allDataReceived);
- if (m_reader)
- m_reader->setData(data);
-}
-
-bool GIFImageDecoder::isSizeAvailable()
-{
- if (!ImageDecoder::isSizeAvailable())
- parse(GIFSizeQuery);
-
- return ImageDecoder::isSizeAvailable();
-}
-
-size_t GIFImageDecoder::frameCount()
-{
- parse(GIFFrameCountQuery);
- return m_frameBufferCache.size();
-}
-
-int GIFImageDecoder::repetitionCount() const
-{
- // This value can arrive at any point in the image data stream. Most GIFs
- // in the wild declare it near the beginning of the file, so it usually is
- // set by the time we've decoded the size, but (depending on the GIF and the
- // packets sent back by the webserver) not always. If the reader hasn't
- // seen a loop count yet, it will return cLoopCountNotSeen, in which case we
- // should default to looping once (the initial value for
- // |m_repetitionCount|).
- //
- // There are some additional wrinkles here. First, ImageSource::clear()
- // may destroy the reader, making the result from the reader _less_
- // authoritative on future calls if the recreated reader hasn't seen the
- // loop count. We don't need to special-case this because in this case the
- // new reader will once again return cLoopCountNotSeen, and we won't
- // overwrite the cached correct value.
- //
- // Second, a GIF might never set a loop count at all, in which case we
- // should continue to treat it as a "loop once" animation. We don't need
- // special code here either, because in this case we'll never change
- // |m_repetitionCount| from its default value.
- //
- // Third, we use the same GIFImageReader for counting frames and we might
- // see the loop count and then encounter a decoding error which happens
- // later in the stream. It is also possible that no frames are in the
- // stream. In these cases we should just loop once.
- if (failed() || (m_reader && (!m_reader->imagesCount())))
- m_repetitionCount = cAnimationLoopOnce;
- else if (m_reader && m_reader->loopCount() != cLoopCountNotSeen)
- m_repetitionCount = m_reader->loopCount();
- return m_repetitionCount;
-}
-
-ImageFrame* GIFImageDecoder::frameBufferAtIndex(size_t index)
-{
- if (index >= frameCount())
- return 0;
-
- ImageFrame& frame = m_frameBufferCache[index];
- if (frame.status() != ImageFrame::FrameComplete) {
- PlatformInstrumentation::willDecodeImage("GIF");
- decode(index);
- PlatformInstrumentation::didDecodeImage();
- }
- return &frame;
-}
-
-bool GIFImageDecoder::frameIsCompleteAtIndex(size_t index) const
-{
- return m_reader && (index < m_reader->imagesCount()) && m_reader->frameContext(index)->isComplete();
-}
-
-float GIFImageDecoder::frameDurationAtIndex(size_t index) const
-{
- return (m_reader && (index < m_reader->imagesCount()) &&
- m_reader->frameContext(index)->isHeaderDefined()) ?
- m_reader->frameContext(index)->delayTime() : 0;
-}
-
-bool GIFImageDecoder::setFailed()
-{
- m_reader.clear();
- return ImageDecoder::setFailed();
-}
-
-// FIXME: Can the intermediate |rowBuffer| be avoided?
-bool GIFImageDecoder::haveDecodedRow(size_t frameIndex, const Vector<unsigned char>& rowBuffer, size_t width, size_t rowNumber, unsigned repeatCount, bool writeTransparentPixels)
-{
- const GIFFrameContext* frameContext = m_reader->frameContext(frameIndex);
- // The pixel data and coordinates supplied to us are relative to the frame's
- // origin within the entire image size, i.e.
- // (frameContext->xOffset, frameContext->yOffset). There is no guarantee
- // that width == (size().width() - frameContext->xOffset), so
- // we must ensure we don't run off the end of either the source data or the
- // row's X-coordinates.
- const int xBegin = frameContext->xOffset();
- const int yBegin = frameContext->yOffset() + rowNumber;
- const int xEnd = std::min(static_cast<int>(frameContext->xOffset() + width), size().width());
- const int yEnd = std::min(static_cast<int>(frameContext->yOffset() + rowNumber + repeatCount), size().height());
- if (rowBuffer.isEmpty() || (xBegin < 0) || (yBegin < 0) || (xEnd <= xBegin) || (yEnd <= yBegin))
- return true;
-
- const GIFColorMap::Table& colorTable = frameContext->localColorMap().isDefined() ? frameContext->localColorMap().table() : m_reader->globalColorMap().table();
-
- if (colorTable.isEmpty())
- return true;
-
- GIFColorMap::Table::const_iterator colorTableIter = colorTable.begin();
-
- // Initialize the frame if necessary.
- ImageFrame& buffer = m_frameBufferCache[frameIndex];
- if ((buffer.status() == ImageFrame::FrameEmpty) && !initFrameBuffer(frameIndex))
- return false;
-
- const size_t transparentPixel = frameContext->transparentPixel();
- Vector<unsigned char>::const_iterator rowBegin = rowBuffer.begin();
- Vector<unsigned char>::const_iterator rowEnd = rowBegin + (xEnd - xBegin);
- ImageFrame::PixelData* currentAddress = buffer.getAddr(xBegin, yBegin);
-
- // We may or may not need to write transparent pixels to the buffer.
- // If we're compositing against a previous image, it's wrong, and if
- // we're writing atop a cleared, fully transparent buffer, it's
- // unnecessary; but if we're decoding an interlaced gif and
- // displaying it "Haeberli"-style, we must write these for passes
- // beyond the first, or the initial passes will "show through" the
- // later ones.
- //
- // The loops below are almost identical. One writes a transparent pixel
- // and one doesn't based on the value of |writeTransparentPixels|.
- // The condition check is taken out of the loop to enhance performance.
- // This optimization reduces decoding time by about 15% for a 3MB image.
- if (writeTransparentPixels) {
- for (; rowBegin != rowEnd; ++rowBegin, ++currentAddress) {
- const size_t sourceValue = *rowBegin;
- if ((sourceValue != transparentPixel) && (sourceValue < colorTable.size())) {
- *currentAddress = colorTableIter[sourceValue];
- } else {
- *currentAddress = 0;
- m_currentBufferSawAlpha = true;
- }
- }
- } else {
- for (; rowBegin != rowEnd; ++rowBegin, ++currentAddress) {
- const size_t sourceValue = *rowBegin;
- if ((sourceValue != transparentPixel) && (sourceValue < colorTable.size()))
- *currentAddress = colorTableIter[sourceValue];
- else
- m_currentBufferSawAlpha = true;
- }
- }
-
- // Tell the frame to copy the row data if need be.
- if (repeatCount > 1)
- buffer.copyRowNTimes(xBegin, xEnd, yBegin, yEnd);
-
- return true;
-}
-
-bool GIFImageDecoder::parseCompleted() const
-{
- return m_reader && m_reader->parseCompleted();
-}
-
-bool GIFImageDecoder::frameComplete(size_t frameIndex)
-{
- // Initialize the frame if necessary. Some GIFs insert do-nothing frames,
- // in which case we never reach haveDecodedRow() before getting here.
- ImageFrame& buffer = m_frameBufferCache[frameIndex];
- if ((buffer.status() == ImageFrame::FrameEmpty) && !initFrameBuffer(frameIndex))
- return false; // initFrameBuffer() has already called setFailed().
-
- buffer.setStatus(ImageFrame::FrameComplete);
-
- if (!m_currentBufferSawAlpha) {
- // The whole frame was non-transparent, so it's possible that the entire
- // resulting buffer was non-transparent, and we can setHasAlpha(false).
- if (buffer.originalFrameRect().contains(IntRect(IntPoint(), size()))) {
- buffer.setHasAlpha(false);
- buffer.setRequiredPreviousFrameIndex(kNotFound);
- } else if (buffer.requiredPreviousFrameIndex() != kNotFound) {
- // Tricky case. This frame does not have alpha only if everywhere
- // outside its rect doesn't have alpha. To know whether this is
- // true, we check the start state of the frame -- if it doesn't have
- // alpha, we're safe.
- const ImageFrame* prevBuffer = &m_frameBufferCache[buffer.requiredPreviousFrameIndex()];
- ASSERT(prevBuffer->disposalMethod() != ImageFrame::DisposeOverwritePrevious);
-
- // Now, if we're at a DisposeNotSpecified or DisposeKeep frame, then
- // we can say we have no alpha if that frame had no alpha. But
- // since in initFrameBuffer() we already copied that frame's alpha
- // state into the current frame's, we need do nothing at all here.
- //
- // The only remaining case is a DisposeOverwriteBgcolor frame. If
- // it had no alpha, and its rect is contained in the current frame's
- // rect, we know the current frame has no alpha.
- if ((prevBuffer->disposalMethod() == ImageFrame::DisposeOverwriteBgcolor) && !prevBuffer->hasAlpha() && buffer.originalFrameRect().contains(prevBuffer->originalFrameRect()))
- buffer.setHasAlpha(false);
- }
- }
-
- return true;
-}
-
-size_t GIFImageDecoder::clearCacheExceptFrame(size_t clearExceptFrame)
-{
- // We need to preserve frames such that:
- // 1. We don't clear |clearExceptFrame|;
- // 2. We don't clear any frame from which a future initFrameBuffer() call
- // will copy bitmap data.
- // All other frames can be cleared.
- while ((clearExceptFrame < m_frameBufferCache.size()) && (m_frameBufferCache[clearExceptFrame].status() == ImageFrame::FrameEmpty))
- clearExceptFrame = m_frameBufferCache[clearExceptFrame].requiredPreviousFrameIndex();
-
- return ImageDecoder::clearCacheExceptFrame(clearExceptFrame);
-}
-
-void GIFImageDecoder::clearFrameBuffer(size_t frameIndex)
-{
- if (m_reader && m_frameBufferCache[frameIndex].status() == ImageFrame::FramePartial) {
- // Reset the state of the partial frame in the reader so that the frame
- // can be decoded again when requested.
- m_reader->clearDecodeState(frameIndex);
- }
- ImageDecoder::clearFrameBuffer(frameIndex);
-}
-
-void GIFImageDecoder::parse(GIFParseQuery query)
-{
- if (failed())
- return;
-
- if (!m_reader) {
- m_reader = adoptPtr(new GIFImageReader(this));
- m_reader->setData(m_data);
- }
-
- if (!m_reader->parse(query)) {
- setFailed();
- return;
- }
-
- const size_t oldSize = m_frameBufferCache.size();
- m_frameBufferCache.resize(m_reader->imagesCount());
-
- for (size_t i = oldSize; i < m_reader->imagesCount(); ++i) {
- ImageFrame& buffer = m_frameBufferCache[i];
- const GIFFrameContext* frameContext = m_reader->frameContext(i);
- buffer.setPremultiplyAlpha(m_premultiplyAlpha);
- buffer.setRequiredPreviousFrameIndex(findRequiredPreviousFrame(i, false));
- buffer.setDuration(frameContext->delayTime());
- buffer.setDisposalMethod(frameContext->disposalMethod());
-
- // Initialize the frame rect in our buffer.
- IntRect frameRect = frameContext->frameRect();
-
- // Make sure the frameRect doesn't extend outside the buffer.
- if (frameRect.maxX() > size().width())
- frameRect.setWidth(size().width() - frameRect.x());
- if (frameRect.maxY() > size().height())
- frameRect.setHeight(size().height() - frameRect.y());
-
- buffer.setOriginalFrameRect(frameRect);
- }
-}
-
-void GIFImageDecoder::decode(size_t frameIndex)
-{
- parse(GIFFrameCountQuery);
-
- if (failed())
- return;
-
- Vector<size_t> framesToDecode;
- size_t frameToDecode = frameIndex;
- do {
- framesToDecode.append(frameToDecode);
- frameToDecode = m_frameBufferCache[frameToDecode].requiredPreviousFrameIndex();
- } while (frameToDecode != kNotFound && m_frameBufferCache[frameToDecode].status() != ImageFrame::FrameComplete);
-
- for (size_t i = framesToDecode.size(); i > 0; --i) {
- size_t frameIndex = framesToDecode[i - 1];
- if (!m_reader->decode(frameIndex)) {
- setFailed();
- return;
- }
-
- // We need more data to continue decoding.
- if (m_frameBufferCache[frameIndex].status() != ImageFrame::FrameComplete)
- break;
- }
-
- // It is also a fatal error if all data is received and we have decoded all
- // frames available but the file is truncated.
- if (frameIndex >= m_frameBufferCache.size() - 1 && isAllDataReceived() && m_reader && !m_reader->parseCompleted())
- setFailed();
-}
-
-bool GIFImageDecoder::initFrameBuffer(size_t frameIndex)
-{
- // Initialize the frame rect in our buffer.
- const GIFFrameContext* frameContext = m_reader->frameContext(frameIndex);
- ImageFrame* const buffer = &m_frameBufferCache[frameIndex];
-
- size_t requiredPreviousFrameIndex = buffer->requiredPreviousFrameIndex();
- if (requiredPreviousFrameIndex == kNotFound) {
- // This frame doesn't rely on any previous data.
- if (!buffer->setSize(size().width(), size().height()))
- return setFailed();
- } else {
- const ImageFrame* prevBuffer = &m_frameBufferCache[requiredPreviousFrameIndex];
- ASSERT(prevBuffer->status() == ImageFrame::FrameComplete);
-
- // Preserve the last frame as the starting state for this frame.
- if (!buffer->copyBitmapData(*prevBuffer))
- return setFailed();
-
- if (prevBuffer->disposalMethod() == ImageFrame::DisposeOverwriteBgcolor) {
- // We want to clear the previous frame to transparent, without
- // affecting pixels in the image outside of the frame.
- const IntRect& prevRect = prevBuffer->originalFrameRect();
- ASSERT(!prevRect.contains(IntRect(IntPoint(), size())));
- buffer->zeroFillFrameRect(prevRect);
- }
- }
-
- // Update our status to be partially complete.
- buffer->setStatus(ImageFrame::FramePartial);
-
- // Reset the alpha pixel tracker for this frame.
- m_currentBufferSawAlpha = false;
- return true;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/image-decoders/gif/GIFImageDecoder.h b/chromium/third_party/WebKit/Source/core/platform/image-decoders/gif/GIFImageDecoder.h
deleted file mode 100644
index 5c946a21875..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/image-decoders/gif/GIFImageDecoder.h
+++ /dev/null
@@ -1,90 +0,0 @@
-/*
- * Copyright (C) 2006 Apple Computer, Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef GIFImageDecoder_h
-#define GIFImageDecoder_h
-
-#include "core/platform/image-decoders/ImageDecoder.h"
-#include "wtf/OwnPtr.h"
-
-class GIFImageReader;
-
-namespace WebCore {
-
- // This class decodes the GIF image format.
- class GIFImageDecoder : public ImageDecoder {
- public:
- GIFImageDecoder(ImageSource::AlphaOption, ImageSource::GammaAndColorProfileOption, size_t maxDecodedBytes);
- virtual ~GIFImageDecoder();
-
- enum GIFParseQuery { GIFSizeQuery, GIFFrameCountQuery };
-
- // ImageDecoder
- virtual String filenameExtension() const OVERRIDE { return "gif"; }
- virtual void setData(SharedBuffer* data, bool allDataReceived) OVERRIDE;
- virtual bool isSizeAvailable() OVERRIDE;
- virtual size_t frameCount() OVERRIDE;
- virtual int repetitionCount() const OVERRIDE;
- virtual ImageFrame* frameBufferAtIndex(size_t) OVERRIDE;
- virtual bool frameIsCompleteAtIndex(size_t) const OVERRIDE;
- virtual float frameDurationAtIndex(size_t) const OVERRIDE;
- virtual size_t clearCacheExceptFrame(size_t) OVERRIDE;
- // CAUTION: setFailed() deletes |m_reader|. Be careful to avoid
- // accessing deleted memory, especially when calling this from inside
- // GIFImageReader!
- virtual bool setFailed() OVERRIDE;
-
- // Callbacks from the GIF reader.
- bool haveDecodedRow(size_t frameIndex, const Vector<unsigned char>& rowBuffer, size_t width, size_t rowNumber, unsigned repeatCount, bool writeTransparentPixels);
- bool frameComplete(size_t frameIndex);
-
- // For testing.
- bool parseCompleted() const;
-
- private:
- virtual void clearFrameBuffer(size_t frameIndex) OVERRIDE;
-
- // Parses as much as is needed to answer the query, ignoring bitmap
- // data. If parsing fails, sets the "decode failure" flag.
- void parse(GIFParseQuery);
-
- // Decodes bitmap data of the frame. Depending on the disposal method
- // of prior frames, also decodes all required prior frames. If decoding
- // fails, sets the "decode failure" flag.
- void decode(size_t frameIndex);
-
- // Called to initialize the frame buffer with the given index, based on
- // the previous frame's disposal method. Returns true on success. On
- // failure, this will mark the image as failed.
- bool initFrameBuffer(size_t frameIndex);
-
- bool m_currentBufferSawAlpha;
- mutable int m_repetitionCount;
- OwnPtr<GIFImageReader> m_reader;
- };
-
-} // namespace WebCore
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/image-decoders/gif/GIFImageDecoderTest.cpp b/chromium/third_party/WebKit/Source/core/platform/image-decoders/gif/GIFImageDecoderTest.cpp
deleted file mode 100644
index a38879b2887..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/image-decoders/gif/GIFImageDecoderTest.cpp
+++ /dev/null
@@ -1,453 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/platform/image-decoders/gif/GIFImageDecoder.h"
-
-#include "core/platform/SharedBuffer.h"
-#include "public/platform/Platform.h"
-#include "public/platform/WebData.h"
-#include "public/platform/WebSize.h"
-#include "public/platform/WebUnitTestSupport.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/StringHasher.h"
-#include "wtf/Vector.h"
-#include <gtest/gtest.h>
-
-using namespace WebCore;
-using namespace WebKit;
-
-namespace {
-
-PassRefPtr<SharedBuffer> readFile(const char* fileName)
-{
- String filePath = Platform::current()->unitTestSupport()->webKitRootDir();
- filePath.append(fileName);
-
- return Platform::current()->unitTestSupport()->readFromFile(filePath);
-}
-
-PassOwnPtr<GIFImageDecoder> createDecoder()
-{
- return adoptPtr(new GIFImageDecoder(ImageSource::AlphaNotPremultiplied, ImageSource::GammaAndColorProfileApplied, ImageDecoder::noDecodedImageByteLimit));
-}
-
-unsigned hashSkBitmap(const SkBitmap& bitmap)
-{
- return StringHasher::hashMemory(bitmap.getPixels(), bitmap.getSize());
-}
-
-void createDecodingBaseline(SharedBuffer* data, Vector<unsigned>* baselineHashes)
-{
- OwnPtr<GIFImageDecoder> decoder = createDecoder();
- decoder->setData(data, true);
- size_t frameCount = decoder->frameCount();
- for (size_t i = 0; i < frameCount; ++i) {
- ImageFrame* frame = decoder->frameBufferAtIndex(i);
- baselineHashes->append(hashSkBitmap(frame->getSkBitmap()));
- }
-}
-
-void testRandomFrameDecode(const char* gifFile)
-{
- SCOPED_TRACE(gifFile);
-
- RefPtr<SharedBuffer> fullData = readFile(gifFile);
- ASSERT_TRUE(fullData.get());
- Vector<unsigned> baselineHashes;
- createDecodingBaseline(fullData.get(), &baselineHashes);
- size_t frameCount = baselineHashes.size();
-
- // Random decoding should get the same results as sequential decoding.
- OwnPtr<GIFImageDecoder> decoder = createDecoder();
- decoder->setData(fullData.get(), true);
- const size_t skippingStep = 5;
- for (size_t i = 0; i < skippingStep; ++i) {
- for (size_t j = i; j < frameCount; j += skippingStep) {
- SCOPED_TRACE(testing::Message() << "Random i:" << i << " j:" << j);
- ImageFrame* frame = decoder->frameBufferAtIndex(j);
- EXPECT_EQ(baselineHashes[j], hashSkBitmap(frame->getSkBitmap()));
- }
- }
-
- // Decoding in reverse order.
- decoder = createDecoder();
- decoder->setData(fullData.get(), true);
- for (size_t i = frameCount; i; --i) {
- SCOPED_TRACE(testing::Message() << "Reverse i:" << i);
- ImageFrame* frame = decoder->frameBufferAtIndex(i - 1);
- EXPECT_EQ(baselineHashes[i - 1], hashSkBitmap(frame->getSkBitmap()));
- }
-}
-
-void testRandomDecodeAfterClearFrameBufferCache(const char* gifFile)
-{
- SCOPED_TRACE(gifFile);
-
- RefPtr<SharedBuffer> data = readFile(gifFile);
- ASSERT_TRUE(data.get());
- Vector<unsigned> baselineHashes;
- createDecodingBaseline(data.get(), &baselineHashes);
- size_t frameCount = baselineHashes.size();
-
- OwnPtr<GIFImageDecoder> decoder = createDecoder();
- decoder->setData(data.get(), true);
- for (size_t clearExceptFrame = 0; clearExceptFrame < frameCount; ++clearExceptFrame) {
- decoder->clearCacheExceptFrame(clearExceptFrame);
- const size_t skippingStep = 5;
- for (size_t i = 0; i < skippingStep; ++i) {
- for (size_t j = 0; j < frameCount; j += skippingStep) {
- SCOPED_TRACE(testing::Message() << "Random i:" << i << " j:" << j);
- ImageFrame* frame = decoder->frameBufferAtIndex(j);
- EXPECT_EQ(baselineHashes[j], hashSkBitmap(frame->getSkBitmap()));
- }
- }
- }
-}
-
-} // namespace
-
-TEST(GIFImageDecoderTest, decodeTwoFrames)
-{
- OwnPtr<GIFImageDecoder> decoder = createDecoder();
-
- RefPtr<SharedBuffer> data = readFile("/LayoutTests/fast/images/resources/animated.gif");
- ASSERT_TRUE(data.get());
- decoder->setData(data.get(), true);
- EXPECT_EQ(cAnimationLoopOnce, decoder->repetitionCount());
-
- ImageFrame* frame = decoder->frameBufferAtIndex(0);
- EXPECT_EQ(ImageFrame::FrameComplete, frame->status());
- EXPECT_EQ(16, frame->getSkBitmap().width());
- EXPECT_EQ(16, frame->getSkBitmap().height());
-
- frame = decoder->frameBufferAtIndex(1);
- EXPECT_EQ(ImageFrame::FrameComplete, frame->status());
- EXPECT_EQ(16, frame->getSkBitmap().width());
- EXPECT_EQ(16, frame->getSkBitmap().height());
-
- EXPECT_EQ(2u, decoder->frameCount());
- EXPECT_EQ(cAnimationLoopInfinite, decoder->repetitionCount());
-}
-
-TEST(GIFImageDecoderTest, parseAndDecode)
-{
- OwnPtr<GIFImageDecoder> decoder = createDecoder();
-
- RefPtr<SharedBuffer> data = readFile("/LayoutTests/fast/images/resources/animated.gif");
- ASSERT_TRUE(data.get());
- decoder->setData(data.get(), true);
- EXPECT_EQ(cAnimationLoopOnce, decoder->repetitionCount());
-
- // This call will parse the entire file.
- EXPECT_EQ(2u, decoder->frameCount());
-
- ImageFrame* frame = decoder->frameBufferAtIndex(0);
- EXPECT_EQ(ImageFrame::FrameComplete, frame->status());
- EXPECT_EQ(16, frame->getSkBitmap().width());
- EXPECT_EQ(16, frame->getSkBitmap().height());
-
- frame = decoder->frameBufferAtIndex(1);
- EXPECT_EQ(ImageFrame::FrameComplete, frame->status());
- EXPECT_EQ(16, frame->getSkBitmap().width());
- EXPECT_EQ(16, frame->getSkBitmap().height());
- EXPECT_EQ(cAnimationLoopInfinite, decoder->repetitionCount());
-}
-
-TEST(GIFImageDecoderTest, parseByteByByte)
-{
- OwnPtr<GIFImageDecoder> decoder = createDecoder();
-
- RefPtr<SharedBuffer> data = readFile("/LayoutTests/fast/images/resources/animated.gif");
- ASSERT_TRUE(data.get());
-
- size_t frameCount = 0;
-
- // Pass data to decoder byte by byte.
- for (size_t length = 1; length <= data->size(); ++length) {
- RefPtr<SharedBuffer> tempData = SharedBuffer::create(data->data(), length);
- decoder->setData(tempData.get(), length == data->size());
-
- EXPECT_LE(frameCount, decoder->frameCount());
- frameCount = decoder->frameCount();
- }
-
- EXPECT_EQ(2u, decoder->frameCount());
-
- decoder->frameBufferAtIndex(0);
- decoder->frameBufferAtIndex(1);
- EXPECT_EQ(cAnimationLoopInfinite, decoder->repetitionCount());
-}
-
-TEST(GIFImageDecoderTest, parseAndDecodeByteByByte)
-{
- OwnPtr<GIFImageDecoder> decoder = createDecoder();
-
- RefPtr<SharedBuffer> data = readFile("/LayoutTests/fast/images/resources/animated-gif-with-offsets.gif");
- ASSERT_TRUE(data.get());
-
- size_t frameCount = 0;
- size_t framesDecoded = 0;
-
- // Pass data to decoder byte by byte.
- for (size_t length = 1; length <= data->size(); ++length) {
- RefPtr<SharedBuffer> tempData = SharedBuffer::create(data->data(), length);
- decoder->setData(tempData.get(), length == data->size());
-
- EXPECT_LE(frameCount, decoder->frameCount());
- frameCount = decoder->frameCount();
-
- ImageFrame* frame = decoder->frameBufferAtIndex(frameCount - 1);
- if (frame && frame->status() == ImageFrame::FrameComplete && framesDecoded < frameCount)
- ++framesDecoded;
- }
-
- EXPECT_EQ(5u, decoder->frameCount());
- EXPECT_EQ(5u, framesDecoded);
- EXPECT_EQ(cAnimationLoopInfinite, decoder->repetitionCount());
-}
-
-TEST(GIFImageDecoderTest, brokenSecondFrame)
-{
- OwnPtr<GIFImageDecoder> decoder = createDecoder();
-
- RefPtr<SharedBuffer> data = readFile("/Source/web/tests/data/broken.gif");
- ASSERT_TRUE(data.get());
- decoder->setData(data.get(), true);
-
- // One frame is detected but cannot be decoded.
- EXPECT_EQ(1u, decoder->frameCount());
- ImageFrame* frame = decoder->frameBufferAtIndex(1);
- EXPECT_FALSE(frame);
-}
-
-TEST(GIFImageDecoderTest, progressiveDecode)
-{
- RefPtr<SharedBuffer> fullData = readFile("/Source/web/tests/data/radient.gif");
- ASSERT_TRUE(fullData.get());
- const size_t fullLength = fullData->size();
-
- OwnPtr<GIFImageDecoder> decoder;
- ImageFrame* frame;
-
- Vector<unsigned> truncatedHashes;
- Vector<unsigned> progressiveHashes;
-
- // Compute hashes when the file is truncated.
- const size_t increment = 1;
- for (size_t i = 1; i <= fullLength; i += increment) {
- decoder = createDecoder();
- RefPtr<SharedBuffer> data = SharedBuffer::create(fullData->data(), i);
- decoder->setData(data.get(), i == fullLength);
- frame = decoder->frameBufferAtIndex(0);
- if (!frame) {
- truncatedHashes.append(0);
- continue;
- }
- truncatedHashes.append(hashSkBitmap(frame->getSkBitmap()));
- }
-
- // Compute hashes when the file is progressively decoded.
- decoder = createDecoder();
- for (size_t i = 1; i <= fullLength; i += increment) {
- RefPtr<SharedBuffer> data = SharedBuffer::create(fullData->data(), i);
- decoder->setData(data.get(), i == fullLength);
- frame = decoder->frameBufferAtIndex(0);
- if (!frame) {
- progressiveHashes.append(0);
- continue;
- }
- progressiveHashes.append(hashSkBitmap(frame->getSkBitmap()));
- }
-
- bool match = true;
- for (size_t i = 0; i < truncatedHashes.size(); ++i) {
- if (truncatedHashes[i] != progressiveHashes[i]) {
- match = false;
- break;
- }
- }
- EXPECT_TRUE(match);
-}
-
-TEST(GIFImageDecoderTest, allDataReceivedTruncation)
-{
- OwnPtr<GIFImageDecoder> decoder = createDecoder();
-
- RefPtr<SharedBuffer> data = readFile("/LayoutTests/fast/images/resources/animated.gif");
- ASSERT_TRUE(data.get());
-
- ASSERT_GE(data->size(), 10u);
- RefPtr<SharedBuffer> tempData = SharedBuffer::create(data->data(), data->size() - 10);
- decoder->setData(tempData.get(), true);
-
- EXPECT_EQ(2u, decoder->frameCount());
- EXPECT_FALSE(decoder->failed());
-
- decoder->frameBufferAtIndex(0);
- EXPECT_FALSE(decoder->failed());
- decoder->frameBufferAtIndex(1);
- EXPECT_TRUE(decoder->failed());
-}
-
-TEST(GIFImageDecoderTest, frameIsComplete)
-{
- OwnPtr<GIFImageDecoder> decoder = createDecoder();
-
- RefPtr<SharedBuffer> data = readFile("/LayoutTests/fast/images/resources/animated.gif");
- ASSERT_TRUE(data.get());
- decoder->setData(data.get(), true);
-
- EXPECT_EQ(2u, decoder->frameCount());
- EXPECT_FALSE(decoder->failed());
- EXPECT_TRUE(decoder->frameIsCompleteAtIndex(0));
- EXPECT_TRUE(decoder->frameIsCompleteAtIndex(1));
-}
-
-TEST(GIFImageDecoderTest, frameIsCompleteLoading)
-{
- OwnPtr<GIFImageDecoder> decoder = createDecoder();
-
- RefPtr<SharedBuffer> data = readFile("/LayoutTests/fast/images/resources/animated.gif");
- ASSERT_TRUE(data.get());
-
- ASSERT_GE(data->size(), 10u);
- RefPtr<SharedBuffer> tempData = SharedBuffer::create(data->data(), data->size() - 10);
- decoder->setData(tempData.get(), false);
-
- EXPECT_EQ(2u, decoder->frameCount());
- EXPECT_FALSE(decoder->failed());
- EXPECT_TRUE(decoder->frameIsCompleteAtIndex(0));
- EXPECT_FALSE(decoder->frameIsCompleteAtIndex(1));
-
- decoder->setData(data.get(), true);
- EXPECT_EQ(2u, decoder->frameCount());
- EXPECT_TRUE(decoder->frameIsCompleteAtIndex(0));
- EXPECT_TRUE(decoder->frameIsCompleteAtIndex(1));
-}
-
-TEST(GIFImageDecoderTest, badTerminator)
-{
- RefPtr<SharedBuffer> referenceData = readFile("/Source/web/tests/data/radient.gif");
- RefPtr<SharedBuffer> testData = readFile("/Source/web/tests/data/radient-bad-terminator.gif");
- ASSERT_TRUE(referenceData.get());
- ASSERT_TRUE(testData.get());
-
- OwnPtr<GIFImageDecoder> referenceDecoder(createDecoder());
- referenceDecoder->setData(referenceData.get(), true);
- EXPECT_EQ(1u, referenceDecoder->frameCount());
- ImageFrame* referenceFrame = referenceDecoder->frameBufferAtIndex(0);
- ASSERT(referenceFrame);
-
- OwnPtr<GIFImageDecoder> testDecoder(createDecoder());
- testDecoder->setData(testData.get(), true);
- EXPECT_EQ(1u, testDecoder->frameCount());
- ImageFrame* testFrame = testDecoder->frameBufferAtIndex(0);
- ASSERT(testFrame);
-
- EXPECT_EQ(hashSkBitmap(referenceFrame->getSkBitmap()), hashSkBitmap(testFrame->getSkBitmap()));
-}
-
-TEST(GIFImageDecoderTest, updateRequiredPreviousFrameAfterFirstDecode)
-{
- OwnPtr<GIFImageDecoder> decoder = createDecoder();
-
- RefPtr<SharedBuffer> fullData = readFile("/LayoutTests/fast/images/resources/animated-10color.gif");
- ASSERT_TRUE(fullData.get());
-
- // Give it data that is enough to parse but not decode in order to check the status
- // of requiredPreviousFrameIndex before decoding.
- size_t partialSize = 1;
- do {
- RefPtr<SharedBuffer> data = SharedBuffer::create(fullData->data(), partialSize);
- decoder->setData(data.get(), false);
- ++partialSize;
- } while (!decoder->frameCount() || decoder->frameBufferAtIndex(0)->status() == ImageFrame::FrameEmpty);
-
- EXPECT_EQ(kNotFound, decoder->frameBufferAtIndex(0)->requiredPreviousFrameIndex());
- unsigned frameCount = decoder->frameCount();
- for (size_t i = 1; i < frameCount; ++i)
- EXPECT_EQ(i - 1, decoder->frameBufferAtIndex(i)->requiredPreviousFrameIndex());
-
- decoder->setData(fullData.get(), true);
- for (size_t i = 0; i < frameCount; ++i)
- EXPECT_EQ(kNotFound, decoder->frameBufferAtIndex(i)->requiredPreviousFrameIndex());
-}
-
-TEST(GIFImageDecoderTest, randomFrameDecode)
-{
- // Single frame image.
- testRandomFrameDecode("/Source/web/tests/data/radient.gif");
- // Multiple frame images.
- testRandomFrameDecode("/LayoutTests/fast/images/resources/animated-gif-with-offsets.gif");
- testRandomFrameDecode("/LayoutTests/fast/images/resources/animated-10color.gif");
-}
-
-TEST(GIFImageDecoderTest, randomDecodeAfterClearFrameBufferCache)
-{
- // Single frame image.
- testRandomDecodeAfterClearFrameBufferCache("/Source/web/tests/data/radient.gif");
- // Multiple frame images.
- testRandomDecodeAfterClearFrameBufferCache("/LayoutTests/fast/images/resources/animated-gif-with-offsets.gif");
- testRandomDecodeAfterClearFrameBufferCache("/LayoutTests/fast/images/resources/animated-10color.gif");
-}
-
-TEST(GIFImageDecoderTest, resumePartialDecodeAfterClearFrameBufferCache)
-{
- RefPtr<SharedBuffer> fullData = readFile("/LayoutTests/fast/images/resources/animated-10color.gif");
- ASSERT_TRUE(fullData.get());
- Vector<unsigned> baselineHashes;
- createDecodingBaseline(fullData.get(), &baselineHashes);
- size_t frameCount = baselineHashes.size();
-
- OwnPtr<GIFImageDecoder> decoder = createDecoder();
-
- // Let frame 0 be partially decoded.
- size_t partialSize = 1;
- do {
- RefPtr<SharedBuffer> data = SharedBuffer::create(fullData->data(), partialSize);
- decoder->setData(data.get(), false);
- ++partialSize;
- } while (!decoder->frameCount() || decoder->frameBufferAtIndex(0)->status() == ImageFrame::FrameEmpty);
-
- // Skip to the last frame and clear.
- decoder->setData(fullData.get(), true);
- EXPECT_EQ(frameCount, decoder->frameCount());
- ImageFrame* lastFrame = decoder->frameBufferAtIndex(frameCount - 1);
- EXPECT_EQ(baselineHashes[frameCount - 1], hashSkBitmap(lastFrame->getSkBitmap()));
- decoder->clearCacheExceptFrame(kNotFound);
-
- // Resume decoding of the first frame.
- ImageFrame* firstFrame = decoder->frameBufferAtIndex(0);
- EXPECT_EQ(ImageFrame::FrameComplete, firstFrame->status());
- EXPECT_EQ(baselineHashes[0], hashSkBitmap(firstFrame->getSkBitmap()));
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/image-decoders/gif/GIFImageReader.cpp b/chromium/third_party/WebKit/Source/core/platform/image-decoders/gif/GIFImageReader.cpp
deleted file mode 100644
index 7716cedef36..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/image-decoders/gif/GIFImageReader.cpp
+++ /dev/null
@@ -1,791 +0,0 @@
-/* -*- Mode: C; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* ***** BEGIN LICENSE BLOCK *****
- * Version: MPL 1.1/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Mozilla Public License Version
- * 1.1 (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- * http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS IS" basis,
- * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
- * for the specific language governing rights and limitations under the
- * License.
- *
- * The Original Code is mozilla.org code.
- *
- * The Initial Developer of the Original Code is
- * Netscape Communications Corporation.
- * Portions created by the Initial Developer are Copyright (C) 1998
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- * Chris Saari <saari@netscape.com>
- * Apple Computer
- *
- * Alternatively, the contents of this file may be used under the terms of
- * either the GNU General Public License Version 2 or later (the "GPL"), or
- * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
- * in which case the provisions of the GPL or the LGPL are applicable instead
- * of those above. If you wish to allow use of your version of this file only
- * under the terms of either the GPL or the LGPL, and not to allow others to
- * use your version of this file under the terms of the MPL, indicate your
- * decision by deleting the provisions above and replace them with the notice
- * and other provisions required by the GPL or the LGPL. If you do not delete
- * the provisions above, a recipient may use your version of this file under
- * the terms of any one of the MPL, the GPL or the LGPL.
- *
- * ***** END LICENSE BLOCK ***** */
-
-/*
-The Graphics Interchange Format(c) is the copyright property of CompuServe
-Incorporated. Only CompuServe Incorporated is authorized to define, redefine,
-enhance, alter, modify or change in any way the definition of the format.
-
-CompuServe Incorporated hereby grants a limited, non-exclusive, royalty-free
-license for the use of the Graphics Interchange Format(sm) in computer
-software; computer software utilizing GIF(sm) must acknowledge ownership of the
-Graphics Interchange Format and its Service Mark by CompuServe Incorporated, in
-User and Technical Documentation. Computer software utilizing GIF, which is
-distributed or may be distributed without User or Technical Documentation must
-display to the screen or printer a message acknowledging ownership of the
-Graphics Interchange Format and the Service Mark by CompuServe Incorporated; in
-this case, the acknowledgement may be displayed in an opening screen or leading
-banner, or a closing screen or trailing banner. A message such as the following
-may be used:
-
- "The Graphics Interchange Format(c) is the Copyright property of
- CompuServe Incorporated. GIF(sm) is a Service Mark property of
- CompuServe Incorporated."
-
-For further information, please contact :
-
- CompuServe Incorporated
- Graphics Technology Department
- 5000 Arlington Center Boulevard
- Columbus, Ohio 43220
- U. S. A.
-
-CompuServe Incorporated maintains a mailing list with all those individuals and
-organizations who wish to receive copies of this document when it is corrected
-or revised. This service is offered free of charge; please provide us with your
-mailing address.
-*/
-
-#include "config.h"
-#include "core/platform/image-decoders/gif/GIFImageReader.h"
-
-#include <string.h>
-#include "core/platform/graphics/ImageSource.h"
-#include "core/platform/image-decoders/gif/GIFImageDecoder.h"
-
-using WebCore::GIFImageDecoder;
-
-// GETN(n, s) requests at least 'n' bytes available from 'q', at start of state 's'.
-//
-// Note, the hold will never need to be bigger than 256 bytes to gather up in the hold,
-// as each GIF block (except colormaps) can never be bigger than 256 bytes.
-// Colormaps are directly copied in the resp. global_colormap or dynamically allocated local_colormap.
-// So a fixed buffer in GIFImageReader is good enough.
-// This buffer is only needed to copy left-over data from one GifWrite call to the next
-#define GETN(n, s) \
- do { \
- m_bytesToConsume = (n); \
- m_state = (s); \
- } while (0)
-
-// Get a 16-bit value stored in little-endian format.
-#define GETINT16(p) ((p)[1]<<8|(p)[0])
-
-// Send the data to the display front-end.
-bool GIFLZWContext::outputRow()
-{
- int drowStart = irow;
- int drowEnd = irow;
-
- // Haeberli-inspired hack for interlaced GIFs: Replicate lines while
- // displaying to diminish the "venetian-blind" effect as the image is
- // loaded. Adjust pixel vertical positions to avoid the appearance of the
- // image crawling up the screen as successive passes are drawn.
- if (m_frameContext->progressiveDisplay() && m_frameContext->interlaced() && ipass < 4) {
- unsigned rowDup = 0;
- unsigned rowShift = 0;
-
- switch (ipass) {
- case 1:
- rowDup = 7;
- rowShift = 3;
- break;
- case 2:
- rowDup = 3;
- rowShift = 1;
- break;
- case 3:
- rowDup = 1;
- rowShift = 0;
- break;
- default:
- break;
- }
-
- drowStart -= rowShift;
- drowEnd = drowStart + rowDup;
-
- // Extend if bottom edge isn't covered because of the shift upward.
- if (((m_frameContext->height() - 1) - drowEnd) <= rowShift)
- drowEnd = m_frameContext->height() - 1;
-
- // Clamp first and last rows to upper and lower edge of image.
- if (drowStart < 0)
- drowStart = 0;
-
- if ((unsigned)drowEnd >= m_frameContext->height())
- drowEnd = m_frameContext->height() - 1;
- }
-
- // Protect against too much image data.
- if ((unsigned)drowStart >= m_frameContext->height())
- return true;
-
- // CALLBACK: Let the client know we have decoded a row.
- if (!m_client->haveDecodedRow(m_frameContext->frameId(), rowBuffer, m_frameContext->width(),
- drowStart, drowEnd - drowStart + 1, m_frameContext->progressiveDisplay() && m_frameContext->interlaced() && ipass > 1))
- return false;
-
- if (!m_frameContext->interlaced())
- irow++;
- else {
- do {
- switch (ipass) {
- case 1:
- irow += 8;
- if (irow >= m_frameContext->height()) {
- ipass++;
- irow = 4;
- }
- break;
-
- case 2:
- irow += 8;
- if (irow >= m_frameContext->height()) {
- ipass++;
- irow = 2;
- }
- break;
-
- case 3:
- irow += 4;
- if (irow >= m_frameContext->height()) {
- ipass++;
- irow = 1;
- }
- break;
-
- case 4:
- irow += 2;
- if (irow >= m_frameContext->height()) {
- ipass++;
- irow = 0;
- }
- break;
-
- default:
- break;
- }
- } while (irow > (m_frameContext->height() - 1));
- }
- return true;
-}
-
-// Perform Lempel-Ziv-Welch decoding.
-// Returns true if decoding was successful. In this case the block will have been completely consumed and/or rowsRemaining will be 0.
-// Otherwise, decoding failed; returns false in this case, which will always cause the GIFImageReader to set the "decode failed" flag.
-bool GIFLZWContext::doLZW(const unsigned char* block, size_t bytesInBlock)
-{
- int code;
- int incode;
- const unsigned char *ch;
-
- if (rowIter == rowBuffer.end())
- return true;
-
-#define OUTPUT_ROW \
- do { \
- if (!outputRow()) \
- return false; \
- rowsRemaining--; \
- rowIter = rowBuffer.begin(); \
- if (!rowsRemaining) \
- return true; \
- } while (0)
-
- for (ch = block; bytesInBlock-- > 0; ch++) {
- // Feed the next byte into the decoder's 32-bit input buffer.
- datum += ((int) *ch) << bits;
- bits += 8;
-
- // Check for underflow of decoder's 32-bit input buffer.
- while (bits >= codesize) {
- // Get the leading variable-length symbol from the data stream.
- code = datum & codemask;
- datum >>= codesize;
- bits -= codesize;
-
- // Reset the dictionary to its original state, if requested.
- if (code == clearCode) {
- codesize = m_frameContext->dataSize() + 1;
- codemask = (1 << codesize) - 1;
- avail = clearCode + 2;
- oldcode = -1;
- continue;
- }
-
- // Check for explicit end-of-stream code.
- if (code == (clearCode + 1)) {
- // end-of-stream should only appear after all image data.
- if (!rowsRemaining)
- return true;
- return false;
- }
-
- if (oldcode == -1) {
- *rowIter++ = suffix[code];
- if (rowIter == rowBuffer.end())
- OUTPUT_ROW;
-
- firstchar = oldcode = code;
- continue;
- }
-
- incode = code;
- if (code >= avail) {
- stack[stackp++] = firstchar;
- code = oldcode;
-
- if (stackp == MAX_BYTES)
- return false;
- }
-
- while (code >= clearCode) {
- if (code >= MAX_BYTES || code == prefix[code])
- return false;
-
- // Even though suffix[] only holds characters through suffix[avail - 1],
- // allowing code >= avail here lets us be more tolerant of malformed
- // data. As long as code < MAX_BYTES, the only risk is a garbled image,
- // which is no worse than refusing to display it.
- stack[stackp++] = suffix[code];
- code = prefix[code];
-
- if (stackp == MAX_BYTES)
- return false;
- }
-
- stack[stackp++] = firstchar = suffix[code];
-
- // Define a new codeword in the dictionary.
- if (avail < 4096) {
- prefix[avail] = oldcode;
- suffix[avail] = firstchar;
- avail++;
-
- // If we've used up all the codewords of a given length
- // increase the length of codewords by one bit, but don't
- // exceed the specified maximum codeword size of 12 bits.
- if ((!(avail & codemask)) && (avail < 4096)) {
- codesize++;
- codemask += avail;
- }
- }
- oldcode = incode;
-
- // Copy the decoded data out to the scanline buffer.
- do {
- *rowIter++ = stack[--stackp];
- if (rowIter == rowBuffer.end())
- OUTPUT_ROW;
- } while (stackp > 0);
- }
- }
-
- return true;
-}
-
-void GIFColorMap::buildTable(const unsigned char* data, size_t length)
-{
- if (!m_isDefined || !m_table.isEmpty())
- return;
-
- RELEASE_ASSERT(m_position + m_colors * GIF_COLORS <= length);
- const unsigned char* srcColormap = data + m_position;
- m_table.resize(m_colors);
- for (Table::iterator iter = m_table.begin(); iter != m_table.end(); ++iter) {
- *iter = SkPackARGB32NoCheck(255, srcColormap[0], srcColormap[1], srcColormap[2]);
- srcColormap += GIF_COLORS;
- }
-}
-
-// Perform decoding for this frame. frameDecoded will be true if the entire frame is decoded.
-// Returns false if a decoding error occurred. This is a fatal error and causes the GIFImageReader to set the "decode failed" flag.
-// Otherwise, either not enough data is available to decode further than before, or the new data has been decoded successfully; returns true in this case.
-bool GIFFrameContext::decode(const unsigned char* data, size_t length, WebCore::GIFImageDecoder* client, bool* frameDecoded)
-{
- m_localColorMap.buildTable(data, length);
-
- *frameDecoded = false;
- if (!m_lzwContext) {
- // Wait for more data to properly initialize GIFLZWContext.
- if (!isDataSizeDefined() || !isHeaderDefined())
- return true;
-
- m_lzwContext = adoptPtr(new GIFLZWContext(client, this));
- if (!m_lzwContext->prepareToDecode()) {
- m_lzwContext.clear();
- return false;
- }
-
- m_currentLzwBlock = 0;
- }
-
- // Some bad GIFs have extra blocks beyond the last row, which we don't want to decode.
- while (m_currentLzwBlock < m_lzwBlocks.size() && m_lzwContext->hasRemainingRows()) {
- size_t blockPosition = m_lzwBlocks[m_currentLzwBlock].blockPosition;
- size_t blockSize = m_lzwBlocks[m_currentLzwBlock].blockSize;
- if (blockPosition + blockSize > length)
- return false;
- if (!m_lzwContext->doLZW(data + blockPosition, blockSize))
- return false;
- ++m_currentLzwBlock;
- }
-
- // If this frame is data complete then the previous loop must have completely decoded all LZW blocks.
- // There will be no more decoding for this frame so it's time to cleanup.
- if (isComplete()) {
- *frameDecoded = true;
- m_lzwContext.clear();
- }
- return true;
-}
-
-// Decode a frame.
-// This method uses GIFFrameContext:decode() to decode the frame; decoding error is reported to client as a critical failure.
-// Return true if decoding has progressed. Return false if an error has occurred.
-bool GIFImageReader::decode(size_t frameIndex)
-{
- m_globalColorMap.buildTable(data(0), m_data->size());
-
- bool frameDecoded = false;
- GIFFrameContext* currentFrame = m_frames[frameIndex].get();
-
- return currentFrame->decode(data(0), m_data->size(), m_client, &frameDecoded)
- && (!frameDecoded || m_client->frameComplete(frameIndex));
-}
-
-bool GIFImageReader::parse(GIFImageDecoder::GIFParseQuery query)
-{
- ASSERT(m_bytesRead <= m_data->size());
-
- return parseData(m_bytesRead, m_data->size() - m_bytesRead, query);
-}
-
-// Parse incoming GIF data stream into internal data structures.
-// Return true if parsing has progressed or there is not enough data.
-// Return false if a fatal error is encountered.
-bool GIFImageReader::parseData(size_t dataPosition, size_t len, GIFImageDecoder::GIFParseQuery query)
-{
- if (!len) {
- // No new data has come in since the last call, just ignore this call.
- return true;
- }
-
- if (len < m_bytesToConsume)
- return true;
-
- // This loop reads as many components from |m_data| as possible.
- // At the beginning of each iteration, dataPosition will be advanced by m_bytesToConsume to
- // point to the next component. len will be decremented accordingly.
- while (len >= m_bytesToConsume) {
- const size_t currentComponentPosition = dataPosition;
- const unsigned char* currentComponent = data(dataPosition);
-
- // Mark the current component as consumed. Note that currentComponent will remain pointed at this
- // component until the next loop iteration.
- dataPosition += m_bytesToConsume;
- len -= m_bytesToConsume;
-
- switch (m_state) {
- case GIFLZW:
- ASSERT(!m_frames.isEmpty());
- // m_bytesToConsume is the current component size because it hasn't been updated.
- m_frames.last()->addLzwBlock(currentComponentPosition, m_bytesToConsume);
- GETN(1, GIFSubBlock);
- break;
-
- case GIFLZWStart: {
- ASSERT(!m_frames.isEmpty());
- m_frames.last()->setDataSize(*currentComponent);
- GETN(1, GIFSubBlock);
- break;
- }
-
- case GIFType: {
- // All GIF files begin with "GIF87a" or "GIF89a".
- if (!strncmp((char*)currentComponent, "GIF89a", 6))
- m_version = 89;
- else if (!strncmp((char*)currentComponent, "GIF87a", 6))
- m_version = 87;
- else
- return false;
- GETN(7, GIFGlobalHeader);
- break;
- }
-
- case GIFGlobalHeader: {
- // This is the height and width of the "screen" or frame into which images are rendered. The
- // individual images can be smaller than the screen size and located with an origin anywhere
- // within the screen.
- m_screenWidth = GETINT16(currentComponent);
- m_screenHeight = GETINT16(currentComponent + 2);
-
- // CALLBACK: Inform the decoderplugin of our size.
- // Note: A subsequent frame might have dimensions larger than the "screen" dimensions.
- if (m_client && !m_client->setSize(m_screenWidth, m_screenHeight))
- return false;
-
- const size_t globalColorMapColors = 2 << (currentComponent[4] & 0x07);
-
- if ((currentComponent[4] & 0x80) && globalColorMapColors > 0) { /* global map */
- m_globalColorMap.setTablePositionAndSize(dataPosition, globalColorMapColors);
- GETN(GIF_COLORS * globalColorMapColors, GIFGlobalColormap);
- break;
- }
-
- GETN(1, GIFImageStart);
- break;
- }
-
- case GIFGlobalColormap: {
- m_globalColorMap.setDefined();
- GETN(1, GIFImageStart);
- break;
- }
-
- case GIFImageStart: {
- if (*currentComponent == '!') { // extension.
- GETN(2, GIFExtension);
- break;
- }
-
- if (*currentComponent == ',') { // image separator.
- GETN(9, GIFImageHeader);
- break;
- }
-
- // If we get anything other than ',' (image separator), '!'
- // (extension), or ';' (trailer), there is extraneous data
- // between blocks. The GIF87a spec tells us to keep reading
- // until we find an image separator, but GIF89a says such
- // a file is corrupt. We follow Mozilla's implementation and
- // proceed as if the file were correctly terminated, so the
- // GIF will display.
- GETN(0, GIFDone);
- break;
- }
-
- case GIFExtension: {
- size_t bytesInBlock = currentComponent[1];
- GIFState es = GIFSkipBlock;
-
- switch (*currentComponent) {
- case 0xf9:
- es = GIFControlExtension;
- // The GIF spec mandates that the GIFControlExtension header block length is 4 bytes,
- // and the parser for this block reads 4 bytes, so we must enforce that the buffer
- // contains at least this many bytes. If the GIF specifies a different length, we
- // allow that, so long as it's larger; the additional data will simply be ignored.
- bytesInBlock = std::max(bytesInBlock, static_cast<size_t>(4));
- break;
-
- // The GIF spec also specifies the lengths of the following two extensions' headers
- // (as 12 and 11 bytes, respectively). Because we ignore the plain text extension entirely
- // and sanity-check the actual length of the application extension header before reading it,
- // we allow GIFs to deviate from these values in either direction. This is important for
- // real-world compatibility, as GIFs in the wild exist with application extension headers
- // that are both shorter and longer than 11 bytes.
- case 0x01:
- // ignoring plain text extension
- break;
-
- case 0xff:
- es = GIFApplicationExtension;
- break;
-
- case 0xfe:
- es = GIFConsumeComment;
- break;
- }
-
- if (bytesInBlock)
- GETN(bytesInBlock, es);
- else
- GETN(1, GIFImageStart);
- break;
- }
-
- case GIFConsumeBlock: {
- if (!*currentComponent)
- GETN(1, GIFImageStart);
- else
- GETN(*currentComponent, GIFSkipBlock);
- break;
- }
-
- case GIFSkipBlock: {
- GETN(1, GIFConsumeBlock);
- break;
- }
-
- case GIFControlExtension: {
- addFrameIfNecessary();
- GIFFrameContext* currentFrame = m_frames.last().get();
- if (*currentComponent & 0x1)
- currentFrame->setTransparentPixel(currentComponent[3]);
-
- // We ignore the "user input" bit.
-
- // NOTE: This relies on the values in the FrameDisposalMethod enum
- // matching those in the GIF spec!
- int disposalMethod = ((*currentComponent) >> 2) & 0x7;
- currentFrame->setDisposalMethod(static_cast<WebCore::ImageFrame::DisposalMethod>(disposalMethod));
- // Some specs say that disposal method 3 is "overwrite previous", others that setting
- // the third bit of the field (i.e. method 4) is. We map both to the same value.
- if (disposalMethod == 4)
- currentFrame->setDisposalMethod(WebCore::ImageFrame::DisposeOverwritePrevious);
- currentFrame->setDelayTime(GETINT16(currentComponent + 1) * 10);
- GETN(1, GIFConsumeBlock);
- break;
- }
-
- case GIFCommentExtension: {
- if (*currentComponent)
- GETN(*currentComponent, GIFConsumeComment);
- else
- GETN(1, GIFImageStart);
- break;
- }
-
- case GIFConsumeComment: {
- GETN(1, GIFCommentExtension);
- break;
- }
-
- case GIFApplicationExtension: {
- // Check for netscape application extension.
- if (m_bytesToConsume == 11
- && (!strncmp((char*)currentComponent, "NETSCAPE2.0", 11) || !strncmp((char*)currentComponent, "ANIMEXTS1.0", 11)))
- GETN(1, GIFNetscapeExtensionBlock);
- else
- GETN(1, GIFConsumeBlock);
- break;
- }
-
- // Netscape-specific GIF extension: animation looping.
- case GIFNetscapeExtensionBlock: {
- // GIFConsumeNetscapeExtension always reads 3 bytes from the stream; we should at least wait for this amount.
- if (*currentComponent)
- GETN(std::max(3, static_cast<int>(*currentComponent)), GIFConsumeNetscapeExtension);
- else
- GETN(1, GIFImageStart);
- break;
- }
-
- // Parse netscape-specific application extensions
- case GIFConsumeNetscapeExtension: {
- int netscapeExtension = currentComponent[0] & 7;
-
- // Loop entire animation specified # of times. Only read the loop count during the first iteration.
- if (netscapeExtension == 1) {
- m_loopCount = GETINT16(currentComponent + 1);
-
- // Zero loop count is infinite animation loop request.
- if (!m_loopCount)
- m_loopCount = WebCore::cAnimationLoopInfinite;
-
- GETN(1, GIFNetscapeExtensionBlock);
- } else if (netscapeExtension == 2) {
- // Wait for specified # of bytes to enter buffer.
-
- // Don't do this, this extension doesn't exist (isn't used at all)
- // and doesn't do anything, as our streaming/buffering takes care of it all...
- // See: http://semmix.pl/color/exgraf/eeg24.htm
- GETN(1, GIFNetscapeExtensionBlock);
- } else {
- // 0,3-7 are yet to be defined netscape extension codes
- return false;
- }
- break;
- }
-
- case GIFImageHeader: {
- unsigned height, width, xOffset, yOffset;
-
- /* Get image offsets, with respect to the screen origin */
- xOffset = GETINT16(currentComponent);
- yOffset = GETINT16(currentComponent + 2);
-
- /* Get image width and height. */
- width = GETINT16(currentComponent + 4);
- height = GETINT16(currentComponent + 6);
-
- /* Work around broken GIF files where the logical screen
- * size has weird width or height. We assume that GIF87a
- * files don't contain animations.
- */
- if (currentFrameIsFirstFrame()
- && ((m_screenHeight < height) || (m_screenWidth < width) || (m_version == 87))) {
- m_screenHeight = height;
- m_screenWidth = width;
- xOffset = 0;
- yOffset = 0;
-
- // CALLBACK: Inform the decoderplugin of our size.
- if (m_client && !m_client->setSize(m_screenWidth, m_screenHeight))
- return false;
- }
-
- // Work around more broken GIF files that have zero image width or height
- if (!height || !width) {
- height = m_screenHeight;
- width = m_screenWidth;
- if (!height || !width)
- return false;
- }
-
- if (query == GIFImageDecoder::GIFSizeQuery) {
- // The decoder needs to stop. Hand back the number of bytes we consumed from
- // buffer minus 9 (the amount we consumed to read the header).
- setRemainingBytes(len + 9);
- GETN(9, GIFImageHeader);
- return true;
- }
-
- addFrameIfNecessary();
- GIFFrameContext* currentFrame = m_frames.last().get();
-
- currentFrame->setHeaderDefined();
- currentFrame->setRect(xOffset, yOffset, width, height);
- m_screenWidth = std::max(m_screenWidth, width);
- m_screenHeight = std::max(m_screenHeight, height);
- currentFrame->setInterlaced(currentComponent[8] & 0x40);
-
- // Overlaying interlaced, transparent GIFs over
- // existing image data using the Haeberli display hack
- // requires saving the underlying image in order to
- // avoid jaggies at the transparency edges. We are
- // unprepared to deal with that, so don't display such
- // images progressively. Which means only the first
- // frame can be progressively displayed.
- // FIXME: It is possible that a non-transparent frame
- // can be interlaced and progressively displayed.
- currentFrame->setProgressiveDisplay(currentFrameIsFirstFrame());
-
- const bool isLocalColormapDefined = currentComponent[8] & 0x80;
- if (isLocalColormapDefined) {
- // The three low-order bits of currentComponent[8] specify the bits per pixel.
- const size_t numColors = 2 << (currentComponent[8] & 0x7);
- currentFrame->localColorMap().setTablePositionAndSize(dataPosition, numColors);
- GETN(GIF_COLORS * numColors, GIFImageColormap);
- break;
- }
-
- GETN(1, GIFLZWStart);
- break;
- }
-
- case GIFImageColormap: {
- ASSERT(!m_frames.isEmpty());
- m_frames.last()->localColorMap().setDefined();
- GETN(1, GIFLZWStart);
- break;
- }
-
- case GIFSubBlock: {
- const size_t bytesInBlock = *currentComponent;
- if (bytesInBlock)
- GETN(bytesInBlock, GIFLZW);
- else {
- // Finished parsing one frame; Process next frame.
- ASSERT(!m_frames.isEmpty());
- // Note that some broken GIF files do not have enough LZW blocks to fully
- // decode all rows but we treat it as frame complete.
- m_frames.last()->setComplete();
- GETN(1, GIFImageStart);
- }
- break;
- }
-
- case GIFDone: {
- m_parseCompleted = true;
- return true;
- }
-
- default:
- // We shouldn't ever get here.
- return false;
- break;
- }
- }
-
- setRemainingBytes(len);
- return true;
-}
-
-void GIFImageReader::setRemainingBytes(size_t remainingBytes)
-{
- ASSERT(remainingBytes <= m_data->size());
- m_bytesRead = m_data->size() - remainingBytes;
-}
-
-void GIFImageReader::addFrameIfNecessary()
-{
- if (m_frames.isEmpty() || m_frames.last()->isComplete())
- m_frames.append(adoptPtr(new GIFFrameContext(m_frames.size())));
-}
-
-// FIXME: Move this method to close to doLZW().
-bool GIFLZWContext::prepareToDecode()
-{
- ASSERT(m_frameContext->isDataSizeDefined() && m_frameContext->isHeaderDefined());
-
- // Since we use a codesize of 1 more than the datasize, we need to ensure
- // that our datasize is strictly less than the MAX_LZW_BITS value (12).
- // This sets the largest possible codemask correctly at 4095.
- if (m_frameContext->dataSize() >= MAX_LZW_BITS)
- return false;
- clearCode = 1 << m_frameContext->dataSize();
- if (clearCode >= MAX_BYTES)
- return false;
-
- avail = clearCode + 2;
- oldcode = -1;
- codesize = m_frameContext->dataSize() + 1;
- codemask = (1 << codesize) - 1;
- datum = bits = 0;
- ipass = m_frameContext->interlaced() ? 1 : 0;
- irow = 0;
-
- // Initialize output row buffer.
- rowBuffer.resize(m_frameContext->width());
- rowIter = rowBuffer.begin();
- rowsRemaining = m_frameContext->height();
-
- // Clearing the whole suffix table lets us be more tolerant of bad data.
- memset(suffix, 0, sizeof(suffix));
-
- // Clearing the whole prefix table to prevent uninitialized access.
- memset(prefix, 0, sizeof(prefix));
- for (int i = 0; i < clearCode; i++)
- suffix[i] = i;
- stackp = 0;
- return true;
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/image-decoders/gif/GIFImageReader.h b/chromium/third_party/WebKit/Source/core/platform/image-decoders/gif/GIFImageReader.h
deleted file mode 100644
index 1197dd3e443..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/image-decoders/gif/GIFImageReader.h
+++ /dev/null
@@ -1,367 +0,0 @@
-/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
-/* ***** BEGIN LICENSE BLOCK *****
- * Version: MPL 1.1/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Mozilla Public License Version
- * 1.1 (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- * http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS IS" basis,
- * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
- * for the specific language governing rights and limitations under the
- * License.
- *
- * The Original Code is Mozilla Communicator client code.
- *
- * The Initial Developer of the Original Code is
- * Netscape Communications Corporation.
- * Portions created by the Initial Developer are Copyright (C) 1998
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *
- * Alternatively, the contents of this file may be used under the terms of
- * either the GNU General Public License Version 2 or later (the "GPL"), or
- * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
- * in which case the provisions of the GPL or the LGPL are applicable instead
- * of those above. If you wish to allow use of your version of this file only
- * under the terms of either the GPL or the LGPL, and not to allow others to
- * use your version of this file under the terms of the MPL, indicate your
- * decision by deleting the provisions above and replace them with the notice
- * and other provisions required by the GPL or the LGPL. If you do not delete
- * the provisions above, a recipient may use your version of this file under
- * the terms of any one of the MPL, the GPL or the LGPL.
- *
- * ***** END LICENSE BLOCK ***** */
-
-#ifndef GIFImageReader_h
-#define GIFImageReader_h
-
-// Define ourselves as the clientPtr. Mozilla just hacked their C++ callback class into this old C decoder,
-// so we will too.
-#include "core/platform/SharedBuffer.h"
-#include "core/platform/image-decoders/gif/GIFImageDecoder.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/Vector.h"
-
-#define MAX_LZW_BITS 12
-#define MAX_BYTES 4097 /* 2^MAX_LZW_BITS+1 */
-#define MAX_COLORS 256
-#define GIF_COLORS 3
-
-const int cLoopCountNotSeen = -2;
-
-// List of possible parsing states.
-enum GIFState {
- GIFType,
- GIFGlobalHeader,
- GIFGlobalColormap,
- GIFImageStart,
- GIFImageHeader,
- GIFImageColormap,
- GIFImageBody,
- GIFLZWStart,
- GIFLZW,
- GIFSubBlock,
- GIFExtension,
- GIFControlExtension,
- GIFConsumeBlock,
- GIFSkipBlock,
- GIFDone,
- GIFCommentExtension,
- GIFApplicationExtension,
- GIFNetscapeExtensionBlock,
- GIFConsumeNetscapeExtension,
- GIFConsumeComment
-};
-
-struct GIFFrameContext;
-
-// LZW decoder state machine.
-class GIFLZWContext {
- WTF_MAKE_FAST_ALLOCATED;
-public:
- GIFLZWContext(WebCore::GIFImageDecoder* client, const GIFFrameContext* frameContext)
- : codesize(0)
- , codemask(0)
- , clearCode(0)
- , avail(0)
- , oldcode(0)
- , firstchar(0)
- , bits(0)
- , datum(0)
- , ipass(0)
- , irow(0)
- , rowsRemaining(0)
- , stackp(0)
- , rowIter(0)
- , m_client(client)
- , m_frameContext(frameContext)
- { }
-
- bool prepareToDecode();
- bool outputRow();
- bool doLZW(const unsigned char* block, size_t bytesInBlock);
- bool hasRemainingRows() { return rowsRemaining; }
-
-private:
- // LZW decoding states and output states.
- int codesize;
- int codemask;
- int clearCode; // Codeword used to trigger dictionary reset.
- int avail; // Index of next available slot in dictionary.
- int oldcode;
- unsigned char firstchar;
- int bits; // Number of unread bits in "datum".
- int datum; // 32-bit input buffer.
- int ipass; // Interlace pass; Ranges 1-4 if interlaced.
- size_t irow; // Current output row, starting at zero.
- size_t rowsRemaining; // Rows remaining to be output.
-
- unsigned short prefix[MAX_BYTES];
- unsigned char suffix[MAX_BYTES];
- unsigned char stack[MAX_BYTES];
- Vector<unsigned char> rowBuffer; // Single scanline temporary buffer.
-
- size_t stackp; // Current stack pointer.
- Vector<unsigned char>::iterator rowIter;
-
- // Initialized during construction and read-only.
- WebCore::GIFImageDecoder* m_client;
- const GIFFrameContext* m_frameContext;
-};
-
-// Data structure for one LZW block.
-struct GIFLZWBlock {
- WTF_MAKE_FAST_ALLOCATED;
-public:
- GIFLZWBlock(size_t position, size_t size)
- : blockPosition(position)
- , blockSize(size)
- {
- }
-
- size_t blockPosition;
- size_t blockSize;
-};
-
-class GIFColorMap {
- WTF_MAKE_FAST_ALLOCATED;
-public:
- typedef Vector<WebCore::ImageFrame::PixelData> Table;
-
- GIFColorMap()
- : m_isDefined(false)
- , m_position(0)
- , m_colors(0)
- {
- }
-
- // Set position and number of colors for the RGB table in the data stream.
- void setTablePositionAndSize(size_t position, size_t colors)
- {
- m_position = position;
- m_colors = colors;
- }
- void setDefined() { m_isDefined = true; }
- bool isDefined() const { return m_isDefined; }
-
- // Build RGBA table using the data stream.
- void buildTable(const unsigned char* data, size_t length);
- const Table& table() const { return m_table; }
-
-private:
- bool m_isDefined;
- size_t m_position;
- size_t m_colors;
- Table m_table;
-};
-
-// Frame output state machine.
-struct GIFFrameContext {
- WTF_MAKE_FAST_ALLOCATED;
-public:
- GIFFrameContext(int id)
- : m_frameId(id)
- , m_xOffset(0)
- , m_yOffset(0)
- , m_width(0)
- , m_height(0)
- , m_transparentPixel(kNotFound)
- , m_disposalMethod(WebCore::ImageFrame::DisposeNotSpecified)
- , m_dataSize(0)
- , m_progressiveDisplay(false)
- , m_interlaced(false)
- , m_delayTime(0)
- , m_currentLzwBlock(0)
- , m_isComplete(false)
- , m_isHeaderDefined(false)
- , m_isDataSizeDefined(false)
- {
- }
-
- ~GIFFrameContext()
- {
- }
-
- void addLzwBlock(size_t position, size_t size)
- {
- m_lzwBlocks.append(GIFLZWBlock(position, size));
- }
-
- bool decode(const unsigned char* data, size_t length, WebCore::GIFImageDecoder* client, bool* frameDecoded);
-
- int frameId() const { return m_frameId; }
- void setRect(unsigned x, unsigned y, unsigned width, unsigned height)
- {
- m_xOffset = x;
- m_yOffset = y;
- m_width = width;
- m_height = height;
- }
- WebCore::IntRect frameRect() const { return WebCore::IntRect(m_xOffset, m_yOffset, m_width, m_height); }
- unsigned xOffset() const { return m_xOffset; }
- unsigned yOffset() const { return m_yOffset; }
- unsigned width() const { return m_width; }
- unsigned height() const { return m_height; }
- size_t transparentPixel() const { return m_transparentPixel; }
- void setTransparentPixel(size_t pixel) { m_transparentPixel = pixel; }
- WebCore::ImageFrame::DisposalMethod disposalMethod() const { return m_disposalMethod; }
- void setDisposalMethod(WebCore::ImageFrame::DisposalMethod disposalMethod) { m_disposalMethod = disposalMethod; }
- unsigned delayTime() const { return m_delayTime; }
- void setDelayTime(unsigned delay) { m_delayTime = delay; }
- bool isComplete() const { return m_isComplete; }
- void setComplete() { m_isComplete = true; }
- bool isHeaderDefined() const { return m_isHeaderDefined; }
- void setHeaderDefined() { m_isHeaderDefined = true; }
- bool isDataSizeDefined() const { return m_isDataSizeDefined; }
- int dataSize() const { return m_dataSize; }
- void setDataSize(int size)
- {
- m_dataSize = size;
- m_isDataSizeDefined = true;
- }
- bool progressiveDisplay() const { return m_progressiveDisplay; }
- void setProgressiveDisplay(bool progressiveDisplay) { m_progressiveDisplay = progressiveDisplay; }
- bool interlaced() const { return m_interlaced; }
- void setInterlaced(bool interlaced) { m_interlaced = interlaced; }
-
- void clearDecodeState() { m_lzwContext.clear(); }
- const GIFColorMap& localColorMap() const { return m_localColorMap; }
- GIFColorMap& localColorMap() { return m_localColorMap; }
-
-private:
- int m_frameId;
- unsigned m_xOffset;
- unsigned m_yOffset; // With respect to "screen" origin.
- unsigned m_width;
- unsigned m_height;
- size_t m_transparentPixel; // Index of transparent pixel. Value is kNotFound if there is no transparent pixel.
- WebCore::ImageFrame::DisposalMethod m_disposalMethod; // Restore to background, leave in place, etc.
- int m_dataSize;
-
- bool m_progressiveDisplay; // If true, do Haeberli interlace hack.
- bool m_interlaced; // True, if scanlines arrive interlaced order.
-
- unsigned m_delayTime; // Display time, in milliseconds, for this image in a multi-image GIF.
-
- OwnPtr<GIFLZWContext> m_lzwContext;
- Vector<GIFLZWBlock> m_lzwBlocks; // LZW blocks for this frame.
- GIFColorMap m_localColorMap;
-
- size_t m_currentLzwBlock;
- bool m_isComplete;
- bool m_isHeaderDefined;
- bool m_isDataSizeDefined;
-};
-
-class GIFImageReader {
- WTF_MAKE_FAST_ALLOCATED;
-public:
- GIFImageReader(WebCore::GIFImageDecoder* client = 0)
- : m_client(client)
- , m_state(GIFType)
- , m_bytesToConsume(6) // Number of bytes for GIF type, either "GIF87a" or "GIF89a".
- , m_bytesRead(0)
- , m_version(0)
- , m_screenWidth(0)
- , m_screenHeight(0)
- , m_isGlobalColormapDefined(false)
- , m_loopCount(cLoopCountNotSeen)
- , m_parseCompleted(false)
- {
- }
-
- ~GIFImageReader()
- {
- }
-
- void setData(PassRefPtr<WebCore::SharedBuffer> data) { m_data = data; }
- bool parse(WebCore::GIFImageDecoder::GIFParseQuery);
- bool decode(size_t frameIndex);
-
- size_t imagesCount() const
- {
- if (m_frames.isEmpty())
- return 0;
-
- // This avoids counting an empty frame when the file is truncated right after
- // GIFControlExtension but before GIFImageHeader.
- // FIXME: This extra complexity is not necessary and we should just report m_frames.size().
- return m_frames.last()->isHeaderDefined() ? m_frames.size() : m_frames.size() - 1;
- }
- int loopCount() const { return m_loopCount; }
-
- const GIFColorMap& globalColorMap() const
- {
- return m_globalColorMap;
- }
-
- const GIFFrameContext* frameContext(size_t index) const
- {
- return index < m_frames.size() ? m_frames[index].get() : 0;
- }
-
- bool parseCompleted() const { return m_parseCompleted; }
-
- void clearDecodeState(size_t index) { m_frames[index]->clearDecodeState(); }
-
-private:
- bool parseData(size_t dataPosition, size_t len, WebCore::GIFImageDecoder::GIFParseQuery);
- void setRemainingBytes(size_t);
-
- const unsigned char* data(size_t dataPosition) const
- {
- return reinterpret_cast<const unsigned char*>(m_data->data()) + dataPosition;
- }
-
- void addFrameIfNecessary();
- bool currentFrameIsFirstFrame() const
- {
- return m_frames.isEmpty() || (m_frames.size() == 1u && !m_frames[0]->isComplete());
- }
-
- WebCore::GIFImageDecoder* m_client;
-
- // Parsing state machine.
- GIFState m_state; // Current decoder master state.
- size_t m_bytesToConsume; // Number of bytes to consume for next stage of parsing.
- size_t m_bytesRead; // Number of bytes processed.
-
- // Global (multi-image) state.
- int m_version; // Either 89 for GIF89 or 87 for GIF87.
- unsigned m_screenWidth; // Logical screen width & height.
- unsigned m_screenHeight;
- bool m_isGlobalColormapDefined;
- GIFColorMap m_globalColorMap;
- int m_loopCount; // Netscape specific extension block to control the number of animation loops a GIF renders.
-
- Vector<OwnPtr<GIFFrameContext> > m_frames;
-
- RefPtr<WebCore::SharedBuffer> m_data;
- bool m_parseCompleted;
-};
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/image-decoders/ico/ICOImageDecoder.cpp b/chromium/third_party/WebKit/Source/core/platform/image-decoders/ico/ICOImageDecoder.cpp
deleted file mode 100644
index 6367662490d..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/image-decoders/ico/ICOImageDecoder.cpp
+++ /dev/null
@@ -1,347 +0,0 @@
-/*
- * Copyright (c) 2008, 2009, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/image-decoders/ico/ICOImageDecoder.h"
-
-#include <algorithm>
-
-#include "core/platform/PlatformInstrumentation.h"
-#include "core/platform/image-decoders/bmp/BMPImageReader.h"
-#include "core/platform/image-decoders/png/PNGImageDecoder.h"
-#include "wtf/PassOwnPtr.h"
-
-namespace WebCore {
-
-// Number of bits in .ICO/.CUR used to store the directory and its entries,
-// respectively (doesn't match sizeof values for member structs since we omit
-// some fields).
-static const size_t sizeOfDirectory = 6;
-static const size_t sizeOfDirEntry = 16;
-
-ICOImageDecoder::ICOImageDecoder(ImageSource::AlphaOption alphaOption,
- ImageSource::GammaAndColorProfileOption gammaAndColorProfileOption,
- size_t maxDecodedBytes)
- : ImageDecoder(alphaOption, gammaAndColorProfileOption, maxDecodedBytes)
- , m_decodedOffset(0)
-{
-}
-
-ICOImageDecoder::~ICOImageDecoder()
-{
-}
-
-void ICOImageDecoder::setData(SharedBuffer* data, bool allDataReceived)
-{
- if (failed())
- return;
-
- ImageDecoder::setData(data, allDataReceived);
-
- for (BMPReaders::iterator i(m_bmpReaders.begin()); i != m_bmpReaders.end(); ++i) {
- if (*i)
- (*i)->setData(data);
- }
- for (size_t i = 0; i < m_pngDecoders.size(); ++i)
- setDataForPNGDecoderAtIndex(i);
-}
-
-bool ICOImageDecoder::isSizeAvailable()
-{
- if (!ImageDecoder::isSizeAvailable())
- decode(0, true);
-
- return ImageDecoder::isSizeAvailable();
-}
-
-IntSize ICOImageDecoder::size() const
-{
- return m_frameSize.isEmpty() ? ImageDecoder::size() : m_frameSize;
-}
-
-IntSize ICOImageDecoder::frameSizeAtIndex(size_t index) const
-{
- return (index && (index < m_dirEntries.size())) ? m_dirEntries[index].m_size : size();
-}
-
-bool ICOImageDecoder::setSize(unsigned width, unsigned height)
-{
- // The size calculated inside the BMPImageReader had better match the one in
- // the icon directory.
- return m_frameSize.isEmpty() ? ImageDecoder::setSize(width, height) : ((IntSize(width, height) == m_frameSize) || setFailed());
-}
-
-size_t ICOImageDecoder::frameCount()
-{
- decode(0, true);
- if (m_frameBufferCache.isEmpty()) {
- m_frameBufferCache.resize(m_dirEntries.size());
- for (size_t i = 0; i < m_dirEntries.size(); ++i) {
- m_frameBufferCache[i].setPremultiplyAlpha(m_premultiplyAlpha);
- m_frameBufferCache[i].setRequiredPreviousFrameIndex(kNotFound);
- }
- }
- // CAUTION: We must not resize m_frameBufferCache again after this, as
- // decodeAtIndex() may give a BMPImageReader a pointer to one of the
- // entries.
- return m_frameBufferCache.size();
-}
-
-ImageFrame* ICOImageDecoder::frameBufferAtIndex(size_t index)
-{
- // Ensure |index| is valid.
- if (index >= frameCount())
- return 0;
-
- ImageFrame* buffer = &m_frameBufferCache[index];
- if (buffer->status() != ImageFrame::FrameComplete) {
- PlatformInstrumentation::willDecodeImage("ICO");
- decode(index, false);
- PlatformInstrumentation::didDecodeImage();
- }
- return buffer;
-}
-
-bool ICOImageDecoder::setFailed()
-{
- m_bmpReaders.clear();
- m_pngDecoders.clear();
- return ImageDecoder::setFailed();
-}
-
-bool ICOImageDecoder::hotSpot(IntPoint& hotSpot) const
-{
- // When unspecified, the default frame is always frame 0. This is consistent with
- // BitmapImage where currentFrame() starts at 0 and only increases when animation is
- // requested.
- return hotSpotAtIndex(0, hotSpot);
-}
-
-bool ICOImageDecoder::hotSpotAtIndex(size_t index, IntPoint& hotSpot) const
-{
- if (index >= m_dirEntries.size() || m_fileType != CURSOR)
- return false;
-
- hotSpot = m_dirEntries[index].m_hotSpot;
- return true;
-}
-
-
-// static
-bool ICOImageDecoder::compareEntries(const IconDirectoryEntry& a, const IconDirectoryEntry& b)
-{
- // Larger icons are better. After that, higher bit-depth icons are better.
- const int aEntryArea = a.m_size.width() * a.m_size.height();
- const int bEntryArea = b.m_size.width() * b.m_size.height();
- return (aEntryArea == bEntryArea) ? (a.m_bitCount > b.m_bitCount) : (aEntryArea > bEntryArea);
-}
-
-void ICOImageDecoder::setDataForPNGDecoderAtIndex(size_t index)
-{
- if (!m_pngDecoders[index])
- return;
-
- const IconDirectoryEntry& dirEntry = m_dirEntries[index];
- // Copy out PNG data to a separate vector and send to the PNG decoder.
- // FIXME: Save this copy by making the PNG decoder able to take an
- // optional offset.
- RefPtr<SharedBuffer> pngData(SharedBuffer::create(&m_data->data()[dirEntry.m_imageOffset], m_data->size() - dirEntry.m_imageOffset));
- m_pngDecoders[index]->setData(pngData.get(), isAllDataReceived());
-}
-
-void ICOImageDecoder::decode(size_t index, bool onlySize)
-{
- if (failed())
- return;
-
- // If we couldn't decode the image but we've received all the data, decoding
- // has failed.
- if ((!decodeDirectory() || (!onlySize && !decodeAtIndex(index))) && isAllDataReceived())
- setFailed();
- // If we're done decoding this frame, we don't need the BMPImageReader or
- // PNGImageDecoder anymore. (If we failed, these have already been
- // cleared.)
- else if ((m_frameBufferCache.size() > index) && (m_frameBufferCache[index].status() == ImageFrame::FrameComplete)) {
- m_bmpReaders[index].clear();
- m_pngDecoders[index].clear();
- }
-}
-
-bool ICOImageDecoder::decodeDirectory()
-{
- // Read and process directory.
- if ((m_decodedOffset < sizeOfDirectory) && !processDirectory())
- return false;
-
- // Read and process directory entries.
- return (m_decodedOffset >= (sizeOfDirectory + (m_dirEntries.size() * sizeOfDirEntry))) || processDirectoryEntries();
-}
-
-bool ICOImageDecoder::decodeAtIndex(size_t index)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(index < m_dirEntries.size());
- const IconDirectoryEntry& dirEntry = m_dirEntries[index];
- const ImageType imageType = imageTypeAtIndex(index);
- if (imageType == Unknown)
- return false; // Not enough data to determine image type yet.
-
- if (imageType == BMP) {
- if (!m_bmpReaders[index]) {
- // We need to have already sized m_frameBufferCache before this, and
- // we must not resize it again later (see caution in frameCount()).
- ASSERT(m_frameBufferCache.size() == m_dirEntries.size());
- m_bmpReaders[index] = adoptPtr(new BMPImageReader(this, dirEntry.m_imageOffset, 0, true));
- m_bmpReaders[index]->setData(m_data.get());
- m_bmpReaders[index]->setBuffer(&m_frameBufferCache[index]);
- }
- m_frameSize = dirEntry.m_size;
- bool result = m_bmpReaders[index]->decodeBMP(false);
- m_frameSize = IntSize();
- return result;
- }
-
- if (!m_pngDecoders[index]) {
- m_pngDecoders[index] = adoptPtr(
- new PNGImageDecoder(m_premultiplyAlpha ? ImageSource::AlphaPremultiplied : ImageSource::AlphaNotPremultiplied,
- m_ignoreGammaAndColorProfile ? ImageSource::GammaAndColorProfileIgnored : ImageSource::GammaAndColorProfileApplied, m_maxDecodedBytes));
- setDataForPNGDecoderAtIndex(index);
- }
- // Fail if the size the PNGImageDecoder calculated does not match the size
- // in the directory.
- if (m_pngDecoders[index]->isSizeAvailable() && (m_pngDecoders[index]->size() != dirEntry.m_size))
- return setFailed();
- m_frameBufferCache[index] = *m_pngDecoders[index]->frameBufferAtIndex(0);
- m_frameBufferCache[index].setPremultiplyAlpha(m_premultiplyAlpha);
- m_frameBufferCache[index].setRequiredPreviousFrameIndex(kNotFound);
- return !m_pngDecoders[index]->failed() || setFailed();
-}
-
-bool ICOImageDecoder::processDirectory()
-{
- // Read directory.
- ASSERT(!m_decodedOffset);
- if (m_data->size() < sizeOfDirectory)
- return false;
- const uint16_t fileType = readUint16(2);
- const uint16_t idCount = readUint16(4);
- m_decodedOffset = sizeOfDirectory;
-
- // See if this is an icon filetype we understand, and make sure we have at
- // least one entry in the directory.
- if (((fileType != ICON) && (fileType != CURSOR)) || (!idCount))
- return setFailed();
-
- m_fileType = static_cast<FileType>(fileType);
-
- // Enlarge member vectors to hold all the entries.
- m_dirEntries.resize(idCount);
- m_bmpReaders.resize(idCount);
- m_pngDecoders.resize(idCount);
- return true;
-}
-
-bool ICOImageDecoder::processDirectoryEntries()
-{
- // Read directory entries.
- ASSERT(m_decodedOffset == sizeOfDirectory);
- if ((m_decodedOffset > m_data->size()) || ((m_data->size() - m_decodedOffset) < (m_dirEntries.size() * sizeOfDirEntry)))
- return false;
- for (IconDirectoryEntries::iterator i(m_dirEntries.begin()); i != m_dirEntries.end(); ++i)
- *i = readDirectoryEntry(); // Updates m_decodedOffset.
-
- // Make sure the specified image offsets are past the end of the directory
- // entries.
- for (IconDirectoryEntries::iterator i(m_dirEntries.begin()); i != m_dirEntries.end(); ++i) {
- if (i->m_imageOffset < m_decodedOffset)
- return setFailed();
- }
-
- // Arrange frames in decreasing quality order.
- std::sort(m_dirEntries.begin(), m_dirEntries.end(), compareEntries);
-
- // The image size is the size of the largest entry.
- const IconDirectoryEntry& dirEntry = m_dirEntries.first();
- // Technically, this next call shouldn't be able to fail, since the width
- // and height here are each <= 256, and |m_frameSize| is empty.
- return setSize(dirEntry.m_size.width(), dirEntry.m_size.height());
-}
-
-ICOImageDecoder::IconDirectoryEntry ICOImageDecoder::readDirectoryEntry()
-{
- // Read icon data.
- // The casts to uint8_t in the next few lines are because that's the on-disk
- // type of the width and height values. Storing them in ints (instead of
- // matching uint8_ts) is so we can record dimensions of size 256 (which is
- // what a zero byte really means).
- int width = static_cast<uint8_t>(m_data->data()[m_decodedOffset]);
- if (!width)
- width = 256;
- int height = static_cast<uint8_t>(m_data->data()[m_decodedOffset + 1]);
- if (!height)
- height = 256;
- IconDirectoryEntry entry;
- entry.m_size = IntSize(width, height);
- if (m_fileType == CURSOR) {
- entry.m_bitCount = 0;
- entry.m_hotSpot = IntPoint(readUint16(4), readUint16(6));
- } else {
- entry.m_bitCount = readUint16(6);
- entry.m_hotSpot = IntPoint();
- }
- entry.m_imageOffset = readUint32(12);
-
- // Some icons don't have a bit depth, only a color count. Convert the
- // color count to the minimum necessary bit depth. It doesn't matter if
- // this isn't quite what the bitmap info header says later, as we only use
- // this value to determine which icon entry is best.
- if (!entry.m_bitCount) {
- int colorCount = static_cast<uint8_t>(m_data->data()[m_decodedOffset + 2]);
- if (!colorCount)
- colorCount = 256; // Vague in the spec, needed by real-world icons.
- for (--colorCount; colorCount; colorCount >>= 1)
- ++entry.m_bitCount;
- }
-
- m_decodedOffset += sizeOfDirEntry;
- return entry;
-}
-
-ICOImageDecoder::ImageType ICOImageDecoder::imageTypeAtIndex(size_t index)
-{
- // Check if this entry is a BMP or a PNG; we need 4 bytes to check the magic
- // number.
- ASSERT_WITH_SECURITY_IMPLICATION(index < m_dirEntries.size());
- const uint32_t imageOffset = m_dirEntries[index].m_imageOffset;
- if ((imageOffset > m_data->size()) || ((m_data->size() - imageOffset) < 4))
- return Unknown;
- return strncmp(&m_data->data()[imageOffset], "\x89PNG", 4) ? BMP : PNG;
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/image-decoders/ico/ICOImageDecoder.h b/chromium/third_party/WebKit/Source/core/platform/image-decoders/ico/ICOImageDecoder.h
deleted file mode 100644
index 422a8cb8dd2..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/image-decoders/ico/ICOImageDecoder.h
+++ /dev/null
@@ -1,156 +0,0 @@
-/*
- * Copyright (c) 2008, 2009, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ICOImageDecoder_h
-#define ICOImageDecoder_h
-
-#include "core/platform/image-decoders/bmp/BMPImageReader.h"
-
-namespace WebCore {
-
- class PNGImageDecoder;
-
- // This class decodes the ICO and CUR image formats.
- class ICOImageDecoder : public ImageDecoder {
- public:
- ICOImageDecoder(ImageSource::AlphaOption, ImageSource::GammaAndColorProfileOption, size_t maxDecodedBytes);
- virtual ~ICOImageDecoder();
-
- // ImageDecoder
- virtual String filenameExtension() const { return "ico"; }
- virtual void setData(SharedBuffer*, bool allDataReceived);
- virtual bool isSizeAvailable();
- virtual IntSize size() const;
- virtual IntSize frameSizeAtIndex(size_t) const;
- virtual bool setSize(unsigned width, unsigned height);
- virtual size_t frameCount();
- virtual ImageFrame* frameBufferAtIndex(size_t);
- // CAUTION: setFailed() deletes all readers and decoders. Be careful to
- // avoid accessing deleted memory, especially when calling this from
- // inside BMPImageReader!
- virtual bool setFailed();
- virtual bool hotSpot(IntPoint&) const;
-
- private:
- enum ImageType {
- Unknown,
- BMP,
- PNG,
- };
-
- enum FileType {
- ICON = 1,
- CURSOR = 2,
- };
-
- struct IconDirectoryEntry {
- IntSize m_size;
- uint16_t m_bitCount;
- IntPoint m_hotSpot;
- uint32_t m_imageOffset;
- };
-
- // Returns true if |a| is a preferable icon entry to |b|.
- // Larger sizes, or greater bitdepths at the same size, are preferable.
- static bool compareEntries(const IconDirectoryEntry& a, const IconDirectoryEntry& b);
-
- inline uint16_t readUint16(int offset) const
- {
- return BMPImageReader::readUint16(m_data.get(), m_decodedOffset + offset);
- }
-
- inline uint32_t readUint32(int offset) const
- {
- return BMPImageReader::readUint32(m_data.get(), m_decodedOffset + offset);
- }
-
- // If the desired PNGImageDecoder exists, gives it the appropriate data.
- void setDataForPNGDecoderAtIndex(size_t);
-
- // Decodes the entry at |index|. If |onlySize| is true, stops decoding
- // after calculating the image size. If decoding fails but there is no
- // more data coming, sets the "decode failure" flag.
- void decode(size_t index, bool onlySize);
-
- // Decodes the directory and directory entries at the beginning of the
- // data, and initializes members. Returns true if all decoding
- // succeeded. Once this returns true, all entries' sizes are known.
- bool decodeDirectory();
-
- // Decodes the specified entry.
- bool decodeAtIndex(size_t);
-
- // Processes the ICONDIR at the beginning of the data. Returns true if
- // the directory could be decoded.
- bool processDirectory();
-
- // Processes the ICONDIRENTRY records after the directory. Keeps the
- // "best" entry as the one we'll decode. Returns true if the entries
- // could be decoded.
- bool processDirectoryEntries();
-
- // Stores the hot-spot for |index| in |hotSpot| and returns true,
- // or returns false if there is none.
- bool hotSpotAtIndex(size_t index, IntPoint& hotSpot) const;
-
- // Reads and returns a directory entry from the current offset into
- // |data|.
- IconDirectoryEntry readDirectoryEntry();
-
- // Determines whether the desired entry is a BMP or PNG. Returns true
- // if the type could be determined.
- ImageType imageTypeAtIndex(size_t);
-
- // An index into |m_data| representing how much we've already decoded.
- // Note that this only tracks data _this_ class decodes; once the
- // BMPImageReader takes over this will not be updated further.
- size_t m_decodedOffset;
-
- // Which type of file (ICO/CUR) this is.
- FileType m_fileType;
-
- // The headers for the ICO.
- typedef Vector<IconDirectoryEntry> IconDirectoryEntries;
- IconDirectoryEntries m_dirEntries;
-
- // The image decoders for the various frames.
- typedef Vector<OwnPtr<BMPImageReader> > BMPReaders;
- BMPReaders m_bmpReaders;
- typedef Vector<OwnPtr<PNGImageDecoder> > PNGDecoders;
- PNGDecoders m_pngDecoders;
-
- // Valid only while a BMPImageReader is decoding, this holds the size
- // for the particular entry being decoded.
- IntSize m_frameSize;
- };
-
-} // namespace WebCore
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/image-decoders/jpeg/JPEGImageDecoder.cpp b/chromium/third_party/WebKit/Source/core/platform/image-decoders/jpeg/JPEGImageDecoder.cpp
deleted file mode 100644
index 4a19be5880a..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/image-decoders/jpeg/JPEGImageDecoder.cpp
+++ /dev/null
@@ -1,801 +0,0 @@
-/*
- * Copyright (C) 2006 Apple Computer, Inc.
- *
- * Portions are Copyright (C) 2001-6 mozilla.org
- *
- * Other contributors:
- * Stuart Parmenter <stuart@mozilla.com>
- *
- * Copyright (C) 2007-2009 Torch Mobile, Inc.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- *
- * Alternatively, the contents of this file may be used under the terms
- * of either the Mozilla Public License Version 1.1, found at
- * http://www.mozilla.org/MPL/ (the "MPL") or the GNU General Public
- * License Version 2.0, found at http://www.fsf.org/copyleft/gpl.html
- * (the "GPL"), in which case the provisions of the MPL or the GPL are
- * applicable instead of those above. If you wish to allow use of your
- * version of this file only under the terms of one of those two
- * licenses (the MPL or the GPL) and not to allow others to use your
- * version of this file under the LGPL, indicate your decision by
- * deletingthe provisions above and replace them with the notice and
- * other provisions required by the MPL or the GPL, as the case may be.
- * If you do not delete the provisions above, a recipient may use your
- * version of this file under any of the LGPL, the MPL or the GPL.
- */
-
-#include "config.h"
-#include "core/platform/image-decoders/jpeg/JPEGImageDecoder.h"
-
-#include "core/platform/PlatformInstrumentation.h"
-#include "wtf/CPU.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/dtoa/utils.h"
-
-extern "C" {
-#include <stdio.h> // jpeglib.h needs stdio FILE.
-#include "jpeglib.h"
-#if USE(ICCJPEG)
-#include "iccjpeg.h"
-#endif
-#if USE(QCMSLIB)
-#include "qcms.h"
-#endif
-#include <setjmp.h>
-}
-
-#if CPU(BIG_ENDIAN) || CPU(MIDDLE_ENDIAN)
-#define ASSUME_LITTLE_ENDIAN 0
-#else
-#define ASSUME_LITTLE_ENDIAN 1
-#endif
-
-#if defined(JCS_ALPHA_EXTENSIONS) && ASSUME_LITTLE_ENDIAN
-#define TURBO_JPEG_RGB_SWIZZLE
-#if !SK_R32_SHIFT && SK_G32_SHIFT == 8 && SK_B32_SHIFT == 16
-inline J_COLOR_SPACE rgbOutputColorSpace() { return JCS_EXT_RGBA; }
-#else
-inline J_COLOR_SPACE rgbOutputColorSpace() { return JCS_EXT_BGRA; }
-#endif
-inline bool turboSwizzled(J_COLOR_SPACE colorSpace) { return colorSpace == JCS_EXT_RGBA || colorSpace == JCS_EXT_BGRA; }
-inline bool colorSpaceHasAlpha(J_COLOR_SPACE colorSpace) { return turboSwizzled(colorSpace); }
-#else
-inline J_COLOR_SPACE rgbOutputColorSpace() { return JCS_RGB; }
-inline bool colorSpaceHasAlpha(J_COLOR_SPACE) { return false; }
-#endif
-
-#if USE(LOW_QUALITY_IMAGE_NO_JPEG_DITHERING)
-inline J_DCT_METHOD dctMethod() { return JDCT_IFAST; }
-inline J_DITHER_MODE ditherMode() { return JDITHER_NONE; }
-#else
-inline J_DCT_METHOD dctMethod() { return JDCT_ISLOW; }
-inline J_DITHER_MODE ditherMode() { return JDITHER_FS; }
-#endif
-
-#if USE(LOW_QUALITY_IMAGE_NO_JPEG_FANCY_UPSAMPLING)
-inline bool doFancyUpsampling() { return false; }
-#else
-inline bool doFancyUpsampling() { return true; }
-#endif
-
-namespace {
-
-const int exifMarker = JPEG_APP0 + 1;
-
-// JPEG only supports a denominator of 8.
-const unsigned scaleDenominator = 8;
-
-} // namespace
-
-namespace WebCore {
-
-struct decoder_error_mgr {
- struct jpeg_error_mgr pub; // "public" fields for IJG library
- jmp_buf setjmp_buffer; // For handling catastropic errors
-};
-
-enum jstate {
- JPEG_HEADER, // Reading JFIF headers
- JPEG_START_DECOMPRESS,
- JPEG_DECOMPRESS_PROGRESSIVE, // Output progressive pixels
- JPEG_DECOMPRESS_SEQUENTIAL, // Output sequential pixels
- JPEG_DONE,
- JPEG_ERROR
-};
-
-void init_source(j_decompress_ptr jd);
-boolean fill_input_buffer(j_decompress_ptr jd);
-void skip_input_data(j_decompress_ptr jd, long num_bytes);
-void term_source(j_decompress_ptr jd);
-void error_exit(j_common_ptr cinfo);
-
-// Implementation of a JPEG src object that understands our state machine
-struct decoder_source_mgr {
- // public fields; must be first in this struct!
- struct jpeg_source_mgr pub;
-
- JPEGImageReader* decoder;
-};
-
-static unsigned readUint16(JOCTET* data, bool isBigEndian)
-{
- if (isBigEndian)
- return (GETJOCTET(data[0]) << 8) | GETJOCTET(data[1]);
- return (GETJOCTET(data[1]) << 8) | GETJOCTET(data[0]);
-}
-
-static unsigned readUint32(JOCTET* data, bool isBigEndian)
-{
- if (isBigEndian)
- return (GETJOCTET(data[0]) << 24) | (GETJOCTET(data[1]) << 16) | (GETJOCTET(data[2]) << 8) | GETJOCTET(data[3]);
- return (GETJOCTET(data[3]) << 24) | (GETJOCTET(data[2]) << 16) | (GETJOCTET(data[1]) << 8) | GETJOCTET(data[0]);
-}
-
-static bool checkExifHeader(jpeg_saved_marker_ptr marker, bool& isBigEndian, unsigned& ifdOffset)
-{
- // For exif data, the APP1 block is followed by 'E', 'x', 'i', 'f', '\0',
- // then a fill byte, and then a tiff file that contains the metadata.
- // A tiff file starts with 'I', 'I' (intel / little endian byte order) or
- // 'M', 'M' (motorola / big endian byte order), followed by (uint16_t)42,
- // followed by an uint32_t with the offset to the tag block, relative to the
- // tiff file start.
- const unsigned exifHeaderSize = 14;
- if (!(marker->marker == exifMarker
- && marker->data_length >= exifHeaderSize
- && marker->data[0] == 'E'
- && marker->data[1] == 'x'
- && marker->data[2] == 'i'
- && marker->data[3] == 'f'
- && marker->data[4] == '\0'
- // data[5] is a fill byte
- && ((marker->data[6] == 'I' && marker->data[7] == 'I')
- || (marker->data[6] == 'M' && marker->data[7] == 'M'))))
- return false;
-
- isBigEndian = marker->data[6] == 'M';
- if (readUint16(marker->data + 8, isBigEndian) != 42)
- return false;
-
- ifdOffset = readUint32(marker->data + 10, isBigEndian);
- return true;
-}
-
-static ImageOrientation readImageOrientation(jpeg_decompress_struct* info)
-{
- // The JPEG decoder looks at EXIF metadata.
- // FIXME: Possibly implement XMP and IPTC support.
- const unsigned orientationTag = 0x112;
- const unsigned shortType = 3;
- for (jpeg_saved_marker_ptr marker = info->marker_list; marker; marker = marker->next) {
- bool isBigEndian;
- unsigned ifdOffset;
- if (!checkExifHeader(marker, isBigEndian, ifdOffset))
- continue;
- const unsigned offsetToTiffData = 6; // Account for 'Exif\0<fill byte>' header.
- if (marker->data_length < offsetToTiffData || ifdOffset >= marker->data_length - offsetToTiffData)
- continue;
- ifdOffset += offsetToTiffData;
-
- // The jpeg exif container format contains a tiff block for metadata.
- // A tiff image file directory (ifd) consists of a uint16_t describing
- // the number of ifd entries, followed by that many entries.
- // When touching this code, it's useful to look at the tiff spec:
- // http://partners.adobe.com/public/developer/en/tiff/TIFF6.pdf
- JOCTET* ifd = marker->data + ifdOffset;
- JOCTET* end = marker->data + marker->data_length;
- if (end - ifd < 2)
- continue;
- unsigned tagCount = readUint16(ifd, isBigEndian);
- ifd += 2; // Skip over the uint16 that was just read.
-
- // Every ifd entry is 2 bytes of tag, 2 bytes of contents datatype,
- // 4 bytes of number-of-elements, and 4 bytes of either offset to the
- // tag data, or if the data is small enough, the inlined data itself.
- const int ifdEntrySize = 12;
- for (unsigned i = 0; i < tagCount && end - ifd >= ifdEntrySize; ++i, ifd += ifdEntrySize) {
- unsigned tag = readUint16(ifd, isBigEndian);
- unsigned type = readUint16(ifd + 2, isBigEndian);
- unsigned count = readUint32(ifd + 4, isBigEndian);
- if (tag == orientationTag && type == shortType && count == 1)
- return ImageOrientation::fromEXIFValue(readUint16(ifd + 8, isBigEndian));
- }
- }
-
- return ImageOrientation();
-}
-
-static void readColorProfile(jpeg_decompress_struct* info, ColorProfile& colorProfile)
-{
-#if USE(ICCJPEG)
- JOCTET* profile;
- unsigned int profileLength;
-
- if (!read_icc_profile(info, &profile, &profileLength))
- return;
-
- // Only accept RGB color profiles from input class devices.
- bool ignoreProfile = false;
- char* profileData = reinterpret_cast<char*>(profile);
- if (profileLength < ImageDecoder::iccColorProfileHeaderLength)
- ignoreProfile = true;
- else if (!ImageDecoder::rgbColorProfile(profileData, profileLength))
- ignoreProfile = true;
- else if (!ImageDecoder::inputDeviceColorProfile(profileData, profileLength))
- ignoreProfile = true;
-
- ASSERT(colorProfile.isEmpty());
- if (!ignoreProfile)
- colorProfile.append(profileData, profileLength);
- free(profile);
-#else
- UNUSED_PARAM(info);
- UNUSED_PARAM(colorProfile);
-#endif
-}
-
-class JPEGImageReader {
- WTF_MAKE_FAST_ALLOCATED;
-public:
- JPEGImageReader(JPEGImageDecoder* decoder)
- : m_decoder(decoder)
- , m_bufferLength(0)
- , m_bytesToSkip(0)
- , m_state(JPEG_HEADER)
- , m_samples(0)
-#if USE(QCMSLIB)
- , m_transform(0)
-#endif
- {
- memset(&m_info, 0, sizeof(jpeg_decompress_struct));
-
- // We set up the normal JPEG error routines, then override error_exit.
- m_info.err = jpeg_std_error(&m_err.pub);
- m_err.pub.error_exit = error_exit;
-
- // Allocate and initialize JPEG decompression object.
- jpeg_create_decompress(&m_info);
-
- decoder_source_mgr* src = 0;
- if (!m_info.src) {
- src = (decoder_source_mgr*)fastCalloc(sizeof(decoder_source_mgr), 1);
- if (!src) {
- m_state = JPEG_ERROR;
- return;
- }
- }
-
- m_info.src = (jpeg_source_mgr*)src;
-
- // Set up callback functions.
- src->pub.init_source = init_source;
- src->pub.fill_input_buffer = fill_input_buffer;
- src->pub.skip_input_data = skip_input_data;
- src->pub.resync_to_restart = jpeg_resync_to_restart;
- src->pub.term_source = term_source;
- src->decoder = this;
-
-#if USE(ICCJPEG)
- // Retain ICC color profile markers for color management.
- setup_read_icc_profile(&m_info);
-#endif
-
- // Keep APP1 blocks, for obtaining exif data.
- jpeg_save_markers(&m_info, exifMarker, 0xFFFF);
- }
-
- ~JPEGImageReader()
- {
- close();
- }
-
- void close()
- {
- decoder_source_mgr* src = (decoder_source_mgr*)m_info.src;
- if (src)
- fastFree(src);
- m_info.src = 0;
-
-#if USE(QCMSLIB)
- if (m_transform)
- qcms_transform_release(m_transform);
- m_transform = 0;
-#endif
- jpeg_destroy_decompress(&m_info);
- }
-
- void skipBytes(long numBytes)
- {
- decoder_source_mgr* src = (decoder_source_mgr*)m_info.src;
- long bytesToSkip = std::min(numBytes, (long)src->pub.bytes_in_buffer);
- src->pub.bytes_in_buffer -= (size_t)bytesToSkip;
- src->pub.next_input_byte += bytesToSkip;
-
- m_bytesToSkip = std::max(numBytes - bytesToSkip, static_cast<long>(0));
- }
-
- bool decode(const SharedBuffer& data, bool onlySize)
- {
- unsigned newByteCount = data.size() - m_bufferLength;
- unsigned readOffset = m_bufferLength - m_info.src->bytes_in_buffer;
-
- m_info.src->bytes_in_buffer += newByteCount;
- m_info.src->next_input_byte = (JOCTET*)(data.data()) + readOffset;
-
- // If we still have bytes to skip, try to skip those now.
- if (m_bytesToSkip)
- skipBytes(m_bytesToSkip);
-
- m_bufferLength = data.size();
-
- // We need to do the setjmp here. Otherwise bad things will happen
- if (setjmp(m_err.setjmp_buffer))
- return m_decoder->setFailed();
-
- switch (m_state) {
- case JPEG_HEADER:
- // Read file parameters with jpeg_read_header().
- if (jpeg_read_header(&m_info, true) == JPEG_SUSPENDED)
- return false; // I/O suspension.
-
- switch (m_info.jpeg_color_space) {
- case JCS_GRAYSCALE:
- case JCS_RGB:
- case JCS_YCbCr:
- // libjpeg can convert GRAYSCALE and YCbCr image pixels to RGB.
- m_info.out_color_space = rgbOutputColorSpace();
-#if defined(TURBO_JPEG_RGB_SWIZZLE)
- if (m_info.saw_JFIF_marker)
- break;
- // FIXME: Swizzle decoding does not support Adobe transform=0
- // images (yet), so revert to using JSC_RGB in that case.
- if (m_info.saw_Adobe_marker && !m_info.Adobe_transform)
- m_info.out_color_space = JCS_RGB;
-#endif
- break;
- case JCS_CMYK:
- case JCS_YCCK:
- // libjpeg can convert YCCK to CMYK, but neither to RGB, so we
- // manually convert CMKY to RGB.
- m_info.out_color_space = JCS_CMYK;
- break;
- default:
- return m_decoder->setFailed();
- }
-
- m_state = JPEG_START_DECOMPRESS;
-
- // We can fill in the size now that the header is available.
- if (!m_decoder->setSize(m_info.image_width, m_info.image_height))
- return false;
-
- m_decoder->setOrientation(readImageOrientation(info()));
-
-#if USE(QCMSLIB)
- // Allow color management of the decoded RGBA pixels if possible.
- if (!m_decoder->ignoresGammaAndColorProfile()) {
- ColorProfile colorProfile;
- readColorProfile(info(), colorProfile);
- createColorTransform(colorProfile, colorSpaceHasAlpha(m_info.out_color_space));
-#if defined(TURBO_JPEG_RGB_SWIZZLE)
- // Input RGBA data to qcms. Note: restored to BGRA on output.
- if (m_transform && m_info.out_color_space == JCS_EXT_BGRA)
- m_info.out_color_space = JCS_EXT_RGBA;
-#endif
- }
-#endif
- // Don't allocate a giant and superfluous memory buffer when the
- // image is a sequential JPEG.
- m_info.buffered_image = jpeg_has_multiple_scans(&m_info);
-
- if (onlySize) {
- // We can stop here. Reduce our buffer length and available data.
- m_bufferLength -= m_info.src->bytes_in_buffer;
- m_info.src->bytes_in_buffer = 0;
- return true;
- }
- // FALL THROUGH
-
- case JPEG_START_DECOMPRESS:
- // Set parameters for decompression.
- // FIXME -- Should reset dct_method and dither mode for final pass
- // of progressive JPEG.
- m_info.dct_method = dctMethod();
- m_info.dither_mode = ditherMode();
- m_info.do_fancy_upsampling = doFancyUpsampling();
- m_info.enable_2pass_quant = false;
- m_info.do_block_smoothing = true;
-
- if (m_decoder->size() != m_decoder->decodedSize()) {
- m_info.scale_denom = scaleDenominator;
- m_info.scale_num = m_decoder->decodedSize().width() * scaleDenominator / m_info.image_width;
- }
-
- // Used to set up image size so arrays can be allocated.
- jpeg_calc_output_dimensions(&m_info);
-
- // Make a one-row-high sample array that will go away when done with
- // image. Always make it big enough to hold an RGB row. Since this
- // uses the IJG memory manager, it must be allocated before the call
- // to jpeg_start_compress().
- // FIXME: note that some output color spaces do not need the samples
- // buffer. Remove this allocation for those color spaces.
- m_samples = (*m_info.mem->alloc_sarray)(reinterpret_cast<j_common_ptr>(&m_info), JPOOL_IMAGE, m_info.output_width * 4, 1);
-
- // Start decompressor.
- if (!jpeg_start_decompress(&m_info))
- return false; // I/O suspension.
-
- // If this is a progressive JPEG ...
- m_state = (m_info.buffered_image) ? JPEG_DECOMPRESS_PROGRESSIVE : JPEG_DECOMPRESS_SEQUENTIAL;
- // FALL THROUGH
-
- case JPEG_DECOMPRESS_SEQUENTIAL:
- if (m_state == JPEG_DECOMPRESS_SEQUENTIAL) {
-
- if (!m_decoder->outputScanlines())
- return false; // I/O suspension.
-
- // If we've completed image output...
- ASSERT(m_info.output_scanline == m_info.output_height);
- m_state = JPEG_DONE;
- }
- // FALL THROUGH
-
- case JPEG_DECOMPRESS_PROGRESSIVE:
- if (m_state == JPEG_DECOMPRESS_PROGRESSIVE) {
- int status;
- do {
- status = jpeg_consume_input(&m_info);
- } while ((status != JPEG_SUSPENDED) && (status != JPEG_REACHED_EOI));
-
- for (;;) {
- if (!m_info.output_scanline) {
- int scan = m_info.input_scan_number;
-
- // If we haven't displayed anything yet
- // (output_scan_number == 0) and we have enough data for
- // a complete scan, force output of the last full scan.
- if (!m_info.output_scan_number && (scan > 1) && (status != JPEG_REACHED_EOI))
- --scan;
-
- if (!jpeg_start_output(&m_info, scan))
- return false; // I/O suspension.
- }
-
- if (m_info.output_scanline == 0xffffff)
- m_info.output_scanline = 0;
-
- // If outputScanlines() fails, it deletes |this|. Therefore,
- // copy the decoder pointer and use it to check for failure
- // to avoid member access in the failure case.
- JPEGImageDecoder* decoder = m_decoder;
- if (!decoder->outputScanlines()) {
- if (decoder->failed()) // Careful; |this| is deleted.
- return false;
- if (!m_info.output_scanline)
- // Didn't manage to read any lines - flag so we
- // don't call jpeg_start_output() multiple times for
- // the same scan.
- m_info.output_scanline = 0xffffff;
- return false; // I/O suspension.
- }
-
- if (m_info.output_scanline == m_info.output_height) {
- if (!jpeg_finish_output(&m_info))
- return false; // I/O suspension.
-
- if (jpeg_input_complete(&m_info) && (m_info.input_scan_number == m_info.output_scan_number))
- break;
-
- m_info.output_scanline = 0;
- }
- }
-
- m_state = JPEG_DONE;
- }
- // FALL THROUGH
-
- case JPEG_DONE:
- // Finish decompression.
- return jpeg_finish_decompress(&m_info);
-
- case JPEG_ERROR:
- // We can get here if the constructor failed.
- return m_decoder->setFailed();
- }
-
- return true;
- }
-
- jpeg_decompress_struct* info() { return &m_info; }
- JSAMPARRAY samples() const { return m_samples; }
- JPEGImageDecoder* decoder() { return m_decoder; }
-#if USE(QCMSLIB)
- qcms_transform* colorTransform() const { return m_transform; }
-
- void createColorTransform(const ColorProfile& colorProfile, bool hasAlpha)
- {
- if (m_transform)
- qcms_transform_release(m_transform);
- m_transform = 0;
-
- if (colorProfile.isEmpty())
- return;
- qcms_profile* deviceProfile = ImageDecoder::qcmsOutputDeviceProfile();
- if (!deviceProfile)
- return;
- qcms_profile* inputProfile = qcms_profile_from_memory(colorProfile.data(), colorProfile.size());
- if (!inputProfile)
- return;
- // We currently only support color profiles for RGB profiled images.
- ASSERT(icSigRgbData == qcms_profile_get_color_space(inputProfile));
- qcms_data_type dataFormat = hasAlpha ? QCMS_DATA_RGBA_8 : QCMS_DATA_RGB_8;
- // FIXME: Don't force perceptual intent if the image profile contains an intent.
- m_transform = qcms_transform_create(inputProfile, dataFormat, deviceProfile, dataFormat, QCMS_INTENT_PERCEPTUAL);
- qcms_profile_release(inputProfile);
- }
-#endif
-
-private:
- JPEGImageDecoder* m_decoder;
- unsigned m_bufferLength;
- int m_bytesToSkip;
-
- jpeg_decompress_struct m_info;
- decoder_error_mgr m_err;
- jstate m_state;
-
- JSAMPARRAY m_samples;
-
-#if USE(QCMSLIB)
- qcms_transform* m_transform;
-#endif
-};
-
-// Override the standard error method in the IJG JPEG decoder code.
-void error_exit(j_common_ptr cinfo)
-{
- // Return control to the setjmp point.
- decoder_error_mgr *err = reinterpret_cast_ptr<decoder_error_mgr *>(cinfo->err);
- longjmp(err->setjmp_buffer, -1);
-}
-
-void init_source(j_decompress_ptr)
-{
-}
-
-void skip_input_data(j_decompress_ptr jd, long num_bytes)
-{
- decoder_source_mgr *src = (decoder_source_mgr *)jd->src;
- src->decoder->skipBytes(num_bytes);
-}
-
-boolean fill_input_buffer(j_decompress_ptr)
-{
- // Our decode step always sets things up properly, so if this method is ever
- // called, then we have hit the end of the buffer. A return value of false
- // indicates that we have no data to supply yet.
- return false;
-}
-
-void term_source(j_decompress_ptr jd)
-{
- decoder_source_mgr *src = (decoder_source_mgr *)jd->src;
- src->decoder->decoder()->jpegComplete();
-}
-
-JPEGImageDecoder::JPEGImageDecoder(ImageSource::AlphaOption alphaOption,
- ImageSource::GammaAndColorProfileOption gammaAndColorProfileOption,
- size_t maxDecodedBytes)
- : ImageDecoder(alphaOption, gammaAndColorProfileOption, maxDecodedBytes)
-{
-}
-
-JPEGImageDecoder::~JPEGImageDecoder()
-{
-}
-
-bool JPEGImageDecoder::isSizeAvailable()
-{
- if (!ImageDecoder::isSizeAvailable())
- decode(true);
-
- return ImageDecoder::isSizeAvailable();
-}
-
-bool JPEGImageDecoder::setSize(unsigned width, unsigned height)
-{
- if (!ImageDecoder::setSize(width, height))
- return false;
-
- size_t originalBytes = width * height * 4;
- if (originalBytes <= m_maxDecodedBytes) {
- m_decodedSize = IntSize(width, height);
- return true;
- }
-
- // Downsample according to the maximum decoded size.
- unsigned scaleNumerator = static_cast<unsigned>(floor(sqrt(
- // MSVC needs explicit parameter type for sqrt().
- static_cast<float>(m_maxDecodedBytes * scaleDenominator * scaleDenominator / originalBytes))));
- m_decodedSize = IntSize((scaleNumerator * width + scaleDenominator - 1) / scaleDenominator,
- (scaleNumerator * height + scaleDenominator - 1) / scaleDenominator);
-
- // The image is too big to be downsampled by libjpeg.
- // FIXME: Post-process to downsample the image.
- if (m_decodedSize.isEmpty())
- return setFailed();
-
- return true;
-}
-
-ImageFrame* JPEGImageDecoder::frameBufferAtIndex(size_t index)
-{
- if (index)
- return 0;
-
- if (m_frameBufferCache.isEmpty()) {
- m_frameBufferCache.resize(1);
- m_frameBufferCache[0].setPremultiplyAlpha(m_premultiplyAlpha);
- }
-
- ImageFrame& frame = m_frameBufferCache[0];
- if (frame.status() != ImageFrame::FrameComplete) {
- PlatformInstrumentation::willDecodeImage("JPEG");
- decode(false);
- PlatformInstrumentation::didDecodeImage();
- }
- return &frame;
-}
-
-bool JPEGImageDecoder::setFailed()
-{
- m_reader.clear();
- return ImageDecoder::setFailed();
-}
-
-template <J_COLOR_SPACE colorSpace> void setPixel(ImageFrame& buffer, ImageFrame::PixelData* pixel, JSAMPARRAY samples, int column)
-{
- JSAMPLE* jsample = *samples + column * (colorSpace == JCS_RGB ? 3 : 4);
-
- switch (colorSpace) {
- case JCS_RGB:
- buffer.setRGBARaw(pixel, jsample[0], jsample[1], jsample[2], 255);
- break;
- case JCS_CMYK:
- // Source is 'Inverted CMYK', output is RGB.
- // See: http://www.easyrgb.com/math.php?MATH=M12#text12
- // Or: http://www.ilkeratalay.com/colorspacesfaq.php#rgb
- // From CMYK to CMY:
- // X = X * (1 - K ) + K [for X = C, M, or Y]
- // Thus, from Inverted CMYK to CMY is:
- // X = (1-iX) * (1 - (1-iK)) + (1-iK) => 1 - iX*iK
- // From CMY (0..1) to RGB (0..1):
- // R = 1 - C => 1 - (1 - iC*iK) => iC*iK [G and B similar]
- unsigned k = jsample[3];
- buffer.setRGBARaw(pixel, jsample[0] * k / 255, jsample[1] * k / 255, jsample[2] * k / 255, 255);
- break;
- }
-}
-
-template <J_COLOR_SPACE colorSpace> bool outputRows(JPEGImageReader* reader, ImageFrame& buffer)
-{
- JSAMPARRAY samples = reader->samples();
- jpeg_decompress_struct* info = reader->info();
- int width = info->output_width;
-
- while (info->output_scanline < info->output_height) {
- // jpeg_read_scanlines will increase the scanline counter, so we
- // save the scanline before calling it.
- int y = info->output_scanline;
- // Request one scanline: returns 0 or 1 scanlines.
- if (jpeg_read_scanlines(info, samples, 1) != 1)
- return false;
-#if USE(QCMSLIB)
- if (reader->colorTransform() && colorSpace == JCS_RGB)
- qcms_transform_data(reader->colorTransform(), *samples, *samples, width);
-#endif
- ImageFrame::PixelData* pixel = buffer.getAddr(0, y);
- for (int x = 0; x < width; ++pixel, ++x)
- setPixel<colorSpace>(buffer, pixel, samples, x);
- }
-
- return true;
-}
-
-bool JPEGImageDecoder::outputScanlines()
-{
- if (m_frameBufferCache.isEmpty())
- return false;
-
- jpeg_decompress_struct* info = m_reader->info();
-
- // Initialize the framebuffer if needed.
- ImageFrame& buffer = m_frameBufferCache[0];
- if (buffer.status() == ImageFrame::FrameEmpty) {
- ASSERT(info->output_width == m_decodedSize.width());
- ASSERT(info->output_height == m_decodedSize.height());
-
- if (!buffer.setSize(info->output_width, info->output_height))
- return setFailed();
- buffer.setStatus(ImageFrame::FramePartial);
- // The buffer is transparent outside the decoded area while the image is
- // loading. The completed image will be marked fully opaque in jpegComplete().
- buffer.setHasAlpha(true);
-
- // For JPEGs, the frame always fills the entire image.
- buffer.setOriginalFrameRect(IntRect(IntPoint(), size()));
- }
-
-#if defined(TURBO_JPEG_RGB_SWIZZLE)
- if (turboSwizzled(info->out_color_space)) {
- while (info->output_scanline < info->output_height) {
- unsigned char* row = reinterpret_cast<unsigned char*>(buffer.getAddr(0, info->output_scanline));
- if (jpeg_read_scanlines(info, &row, 1) != 1)
- return false;
-#if USE(QCMSLIB)
- if (qcms_transform* transform = m_reader->colorTransform())
- qcms_transform_data_type(transform, row, row, info->output_width, rgbOutputColorSpace() == JCS_EXT_BGRA ? QCMS_OUTPUT_BGRX : QCMS_OUTPUT_RGBX);
-#endif
- }
- return true;
- }
-#endif
-
- switch (info->out_color_space) {
- case JCS_RGB:
- return outputRows<JCS_RGB>(m_reader.get(), buffer);
- case JCS_CMYK:
- return outputRows<JCS_CMYK>(m_reader.get(), buffer);
- default:
- ASSERT_NOT_REACHED();
- }
-
- return setFailed();
-}
-
-void JPEGImageDecoder::jpegComplete()
-{
- if (m_frameBufferCache.isEmpty())
- return;
-
- // Hand back an appropriately sized buffer, even if the image ended up being
- // empty.
- ImageFrame& buffer = m_frameBufferCache[0];
- buffer.setHasAlpha(false);
- buffer.setStatus(ImageFrame::FrameComplete);
-}
-
-void JPEGImageDecoder::decode(bool onlySize)
-{
- if (failed())
- return;
-
- if (!m_reader) {
- m_reader = adoptPtr(new JPEGImageReader(this));
- }
-
- // If we couldn't decode the image but we've received all the data, decoding
- // has failed.
- if (!m_reader->decode(*m_data, onlySize) && isAllDataReceived())
- setFailed();
- // If we're done decoding the image, we don't need the JPEGImageReader
- // anymore. (If we failed, |m_reader| has already been cleared.)
- else if (!m_frameBufferCache.isEmpty() && (m_frameBufferCache[0].status() == ImageFrame::FrameComplete))
- m_reader.clear();
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/image-decoders/jpeg/JPEGImageDecoder.h b/chromium/third_party/WebKit/Source/core/platform/image-decoders/jpeg/JPEGImageDecoder.h
deleted file mode 100644
index 3c603c0258a..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/image-decoders/jpeg/JPEGImageDecoder.h
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Copyright (C) 2006 Apple Computer, Inc. All rights reserved.
- * Copyright (C) 2008-2009 Torch Mobile, Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef JPEGImageDecoder_h
-#define JPEGImageDecoder_h
-
-#include "core/platform/image-decoders/ImageDecoder.h"
-
-#include "wtf/OwnPtr.h"
-
-namespace WebCore {
-
- class JPEGImageReader;
-
- // This class decodes the JPEG image format.
- class JPEGImageDecoder : public ImageDecoder {
- public:
- JPEGImageDecoder(ImageSource::AlphaOption, ImageSource::GammaAndColorProfileOption, size_t maxDecodedBytes);
- virtual ~JPEGImageDecoder();
-
- // ImageDecoder
- virtual String filenameExtension() const OVERRIDE { return "jpg"; }
- virtual bool isSizeAvailable() OVERRIDE;
- virtual IntSize decodedSize() const OVERRIDE { return m_decodedSize; }
- virtual bool setSize(unsigned width, unsigned height) OVERRIDE;
- virtual ImageFrame* frameBufferAtIndex(size_t) OVERRIDE;
- // CAUTION: setFailed() deletes |m_reader|. Be careful to avoid
- // accessing deleted memory, especially when calling this from inside
- // JPEGImageReader!
- virtual bool setFailed() OVERRIDE;
-
- bool outputScanlines();
- void jpegComplete();
-
- void setOrientation(ImageOrientation orientation) { m_orientation = orientation; }
-
- private:
- // Decodes the image. If |onlySize| is true, stops decoding after
- // calculating the image size. If decoding fails but there is no more
- // data coming, sets the "decode failure" flag.
- void decode(bool onlySize);
-
- OwnPtr<JPEGImageReader> m_reader;
- IntSize m_decodedSize;
- };
-
-} // namespace WebCore
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/image-decoders/jpeg/JPEGImageDecoderTest.cpp b/chromium/third_party/WebKit/Source/core/platform/image-decoders/jpeg/JPEGImageDecoderTest.cpp
deleted file mode 100644
index 540ae30cf1e..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/image-decoders/jpeg/JPEGImageDecoderTest.cpp
+++ /dev/null
@@ -1,185 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/platform/image-decoders/jpeg/JPEGImageDecoder.h"
-
-#include "core/platform/SharedBuffer.h"
-#include "public/platform/Platform.h"
-#include "public/platform/WebData.h"
-#include "public/platform/WebSize.h"
-#include "public/platform/WebUnitTestSupport.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/StringHasher.h"
-#include "wtf/Vector.h"
-
-#include <gtest/gtest.h>
-
-using namespace WebCore;
-using namespace WebKit;
-
-namespace {
-
-PassRefPtr<SharedBuffer> readFile(const char* fileName)
-{
- String filePath = Platform::current()->unitTestSupport()->webKitRootDir();
- filePath.append(fileName);
-
- return Platform::current()->unitTestSupport()->readFromFile(filePath);
-}
-
-PassOwnPtr<JPEGImageDecoder> createDecoder(size_t maxDecodedBytes)
-{
- return adoptPtr(new JPEGImageDecoder(ImageSource::AlphaNotPremultiplied, ImageSource::GammaAndColorProfileApplied, maxDecodedBytes));
-}
-
-} // namespace
-
-void downsample(size_t maxDecodedBytes, unsigned* outputWidth, unsigned* outputHeight, const char* imageFilePath)
-{
- RefPtr<SharedBuffer> data = readFile(imageFilePath);
- ASSERT_TRUE(data.get());
-
- OwnPtr<JPEGImageDecoder> decoder = createDecoder(maxDecodedBytes);
- decoder->setData(data.get(), true);
-
- ImageFrame* frame = decoder->frameBufferAtIndex(0);
- ASSERT_TRUE(frame);
- *outputWidth = frame->getSkBitmap().width();
- *outputHeight = frame->getSkBitmap().height();
- EXPECT_EQ(IntSize(*outputWidth, *outputHeight), decoder->decodedSize());
-}
-
-// Tests failure on a too big image.
-TEST(JPEGImageDecoderTest, tooBig)
-{
- OwnPtr<JPEGImageDecoder> decoder = createDecoder(100);
- EXPECT_FALSE(decoder->setSize(10000, 10000));
- EXPECT_TRUE(decoder->failed());
-}
-
-// Tests that JPEG decoder can downsample image whose width and height are multiple of 8,
-// to ensure we compute the correct decodedSize and pass correct parameters to libjpeg to
-// output image with the expected size.
-TEST(JPEGImageDecoderTest, downsampleImageSizeMultipleOf8)
-{
- const char* jpegFile = "/LayoutTests/fast/images/resources/lenna.jpg"; // 256x256
- unsigned outputWidth, outputHeight;
-
- // 1/8 downsample.
- downsample(40 * 40 * 4, &outputWidth, &outputHeight, jpegFile);
- EXPECT_EQ(32u, outputWidth);
- EXPECT_EQ(32u, outputHeight);
-
- // 2/8 downsample.
- downsample(70 * 70 * 4, &outputWidth, &outputHeight, jpegFile);
- EXPECT_EQ(64u, outputWidth);
- EXPECT_EQ(64u, outputHeight);
-
- // 3/8 downsample.
- downsample(100 * 100 * 4, &outputWidth, &outputHeight, jpegFile);
- EXPECT_EQ(96u, outputWidth);
- EXPECT_EQ(96u, outputHeight);
-
- // 4/8 downsample.
- downsample(130 * 130 * 4, &outputWidth, &outputHeight, jpegFile);
- EXPECT_EQ(128u, outputWidth);
- EXPECT_EQ(128u, outputHeight);
-
- // 5/8 downsample.
- downsample(170 * 170 * 4, &outputWidth, &outputHeight, jpegFile);
- EXPECT_EQ(160u, outputWidth);
- EXPECT_EQ(160u, outputHeight);
-
- // 6/8 downsample.
- downsample(200 * 200 * 4, &outputWidth, &outputHeight, jpegFile);
- EXPECT_EQ(192u, outputWidth);
- EXPECT_EQ(192u, outputHeight);
-
- // 7/8 downsample.
- downsample(230 * 230 * 4, &outputWidth, &outputHeight, jpegFile);
- EXPECT_EQ(224u, outputWidth);
- EXPECT_EQ(224u, outputHeight);
-}
-
-// Tests that JPEG decoder can downsample image whose width and height are not multiple of 8.
-// Ensures that we round decodedSize and scale_num using the same algorithm as that of libjpeg.
-TEST(JPEGImageDecoderTest, downsampleImageSizeNotMultipleOf8)
-{
- const char* jpegFile = "/LayoutTests/fast/images/resources/icc-v2-gbr.jpg"; // 275x207
- unsigned outputWidth, outputHeight;
-
- // 1/8 downsample.
- downsample(40 * 40 * 4, &outputWidth, &outputHeight, jpegFile);
- EXPECT_EQ(35u, outputWidth);
- EXPECT_EQ(26u, outputHeight);
-
- // 2/8 downsample.
- downsample(70 * 70 * 4, &outputWidth, &outputHeight, jpegFile);
- EXPECT_EQ(69u, outputWidth);
- EXPECT_EQ(52u, outputHeight);
-
- // 3/8 downsample.
- downsample(100 * 100 * 4, &outputWidth, &outputHeight, jpegFile);
- EXPECT_EQ(104u, outputWidth);
- EXPECT_EQ(78u, outputHeight);
-
- // 4/8 downsample.
- downsample(130 * 130 * 4, &outputWidth, &outputHeight, jpegFile);
- EXPECT_EQ(138u, outputWidth);
- EXPECT_EQ(104u, outputHeight);
-
- // 5/8 downsample.
- downsample(170 * 170 * 4, &outputWidth, &outputHeight, jpegFile);
- EXPECT_EQ(172u, outputWidth);
- EXPECT_EQ(130u, outputHeight);
-
- // 6/8 downsample.
- downsample(200 * 200 * 4, &outputWidth, &outputHeight, jpegFile);
- EXPECT_EQ(207u, outputWidth);
- EXPECT_EQ(156u, outputHeight);
-
- // 7/8 downsample.
- downsample(230 * 230 * 4, &outputWidth, &outputHeight, jpegFile);
- EXPECT_EQ(241u, outputWidth);
- EXPECT_EQ(182u, outputHeight);
-}
-
-// Tests that upsampling is not allowed.
-TEST(JPEGImageDecoderTest, upsample)
-{
- const char* jpegFile = "/LayoutTests/fast/images/resources/lenna.jpg"; // 256x256
- unsigned outputWidth, outputHeight;
- downsample(1000 * 1000, &outputWidth, &outputHeight, jpegFile);
- EXPECT_EQ(256u, outputWidth);
- EXPECT_EQ(256u, outputHeight);
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/image-decoders/png/PNGImageDecoder.cpp b/chromium/third_party/WebKit/Source/core/platform/image-decoders/png/PNGImageDecoder.cpp
deleted file mode 100644
index c695afb799d..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/image-decoders/png/PNGImageDecoder.cpp
+++ /dev/null
@@ -1,531 +0,0 @@
-/*
- * Copyright (C) 2006 Apple Computer, Inc.
- * Copyright (C) Research In Motion Limited 2009-2010. All rights reserved.
- *
- * Portions are Copyright (C) 2001 mozilla.org
- *
- * Other contributors:
- * Stuart Parmenter <stuart@mozilla.com>
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- *
- * Alternatively, the contents of this file may be used under the terms
- * of either the Mozilla Public License Version 1.1, found at
- * http://www.mozilla.org/MPL/ (the "MPL") or the GNU General Public
- * License Version 2.0, found at http://www.fsf.org/copyleft/gpl.html
- * (the "GPL"), in which case the provisions of the MPL or the GPL are
- * applicable instead of those above. If you wish to allow use of your
- * version of this file only under the terms of one of those two
- * licenses (the MPL or the GPL) and not to allow others to use your
- * version of this file under the LGPL, indicate your decision by
- * deletingthe provisions above and replace them with the notice and
- * other provisions required by the MPL or the GPL, as the case may be.
- * If you do not delete the provisions above, a recipient may use your
- * version of this file under any of the LGPL, the MPL or the GPL.
- */
-
-#include "config.h"
-#include "core/platform/image-decoders/png/PNGImageDecoder.h"
-
-#include "core/platform/PlatformInstrumentation.h"
-#include "wtf/OwnArrayPtr.h"
-#include "wtf/PassOwnPtr.h"
-
-#include "png.h"
-#if USE(QCMSLIB)
-#include "qcms.h"
-#endif
-
-#if defined(PNG_LIBPNG_VER_MAJOR) && defined(PNG_LIBPNG_VER_MINOR) && (PNG_LIBPNG_VER_MAJOR > 1 || (PNG_LIBPNG_VER_MAJOR == 1 && PNG_LIBPNG_VER_MINOR >= 4))
-#define JMPBUF(png_ptr) png_jmpbuf(png_ptr)
-#else
-#define JMPBUF(png_ptr) png_ptr->jmpbuf
-#endif
-
-namespace WebCore {
-
-// Gamma constants.
-const double cMaxGamma = 21474.83;
-const double cDefaultGamma = 2.2;
-const double cInverseGamma = 0.45455;
-
-// Protect against large PNGs. See Mozilla's bug #251381 for more info.
-const unsigned long cMaxPNGSize = 1000000UL;
-
-// Called if the decoding of the image fails.
-static void PNGAPI decodingFailed(png_structp png, png_const_charp)
-{
- longjmp(JMPBUF(png), 1);
-}
-
-// Callbacks given to the read struct. The first is for warnings (we want to
-// treat a particular warning as an error, which is why we have to register this
-// callback).
-static void PNGAPI decodingWarning(png_structp png, png_const_charp warningMsg)
-{
- // Mozilla did this, so we will too.
- // Convert a tRNS warning to be an error (see
- // http://bugzilla.mozilla.org/show_bug.cgi?id=251381 )
- if (!strncmp(warningMsg, "Missing PLTE before tRNS", 24))
- png_error(png, warningMsg);
-}
-
-// Called when we have obtained the header information (including the size).
-static void PNGAPI headerAvailable(png_structp png, png_infop)
-{
- static_cast<PNGImageDecoder*>(png_get_progressive_ptr(png))->headerAvailable();
-}
-
-// Called when a row is ready.
-static void PNGAPI rowAvailable(png_structp png, png_bytep rowBuffer, png_uint_32 rowIndex, int interlacePass)
-{
- static_cast<PNGImageDecoder*>(png_get_progressive_ptr(png))->rowAvailable(rowBuffer, rowIndex, interlacePass);
-}
-
-// Called when we have completely finished decoding the image.
-static void PNGAPI pngComplete(png_structp png, png_infop)
-{
- static_cast<PNGImageDecoder*>(png_get_progressive_ptr(png))->pngComplete();
-}
-
-class PNGImageReader {
- WTF_MAKE_FAST_ALLOCATED;
-public:
- PNGImageReader(PNGImageDecoder* decoder)
- : m_readOffset(0)
- , m_currentBufferSize(0)
- , m_decodingSizeOnly(false)
- , m_hasAlpha(false)
- , m_interlaceBuffer(0)
-#if USE(QCMSLIB)
- , m_transform(0)
- , m_rowBuffer()
-#endif
- {
- m_png = png_create_read_struct(PNG_LIBPNG_VER_STRING, 0, decodingFailed, decodingWarning);
- m_info = png_create_info_struct(m_png);
- png_set_progressive_read_fn(m_png, decoder, headerAvailable, rowAvailable, pngComplete);
- }
-
- ~PNGImageReader()
- {
- close();
- }
-
- void close()
- {
- if (m_png && m_info)
- // This will zero the pointers.
- png_destroy_read_struct(&m_png, &m_info, 0);
-#if USE(QCMSLIB)
- if (m_transform)
- qcms_transform_release(m_transform);
- m_transform = 0;
-#endif
- delete[] m_interlaceBuffer;
- m_interlaceBuffer = 0;
- m_readOffset = 0;
- }
-
- bool decode(const SharedBuffer& data, bool sizeOnly)
- {
- m_decodingSizeOnly = sizeOnly;
- PNGImageDecoder* decoder = static_cast<PNGImageDecoder*>(png_get_progressive_ptr(m_png));
-
- // We need to do the setjmp here. Otherwise bad things will happen.
- if (setjmp(JMPBUF(m_png)))
- return decoder->setFailed();
-
- const char* segment;
- while (unsigned segmentLength = data.getSomeData(segment, m_readOffset)) {
- m_readOffset += segmentLength;
- m_currentBufferSize = m_readOffset;
- png_process_data(m_png, m_info, reinterpret_cast<png_bytep>(const_cast<char*>(segment)), segmentLength);
- // We explicitly specify the superclass isSizeAvailable() because we
- // merely want to check if we've managed to set the size, not
- // (recursively) trigger additional decoding if we haven't.
- if (sizeOnly ? decoder->ImageDecoder::isSizeAvailable() : decoder->isComplete())
- return true;
- }
- return false;
- }
-
- png_structp pngPtr() const { return m_png; }
- png_infop infoPtr() const { return m_info; }
-
- void setReadOffset(unsigned offset) { m_readOffset = offset; }
- unsigned currentBufferSize() const { return m_currentBufferSize; }
- bool decodingSizeOnly() const { return m_decodingSizeOnly; }
- void setHasAlpha(bool hasAlpha) { m_hasAlpha = hasAlpha; }
- bool hasAlpha() const { return m_hasAlpha; }
-
- png_bytep interlaceBuffer() const { return m_interlaceBuffer; }
- void createInterlaceBuffer(int size) { m_interlaceBuffer = new png_byte[size]; }
-#if USE(QCMSLIB)
- png_bytep rowBuffer() const { return m_rowBuffer.get(); }
- void createRowBuffer(int size) { m_rowBuffer = adoptArrayPtr(new png_byte[size]); }
- qcms_transform* colorTransform() const { return m_transform; }
-
- void createColorTransform(const ColorProfile& colorProfile, bool hasAlpha)
- {
- if (m_transform)
- qcms_transform_release(m_transform);
- m_transform = 0;
-
- if (colorProfile.isEmpty())
- return;
- qcms_profile* deviceProfile = ImageDecoder::qcmsOutputDeviceProfile();
- if (!deviceProfile)
- return;
- qcms_profile* inputProfile = qcms_profile_from_memory(colorProfile.data(), colorProfile.size());
- if (!inputProfile)
- return;
- // We currently only support color profiles for RGB and RGBA images.
- ASSERT(icSigRgbData == qcms_profile_get_color_space(inputProfile));
- qcms_data_type dataFormat = hasAlpha ? QCMS_DATA_RGBA_8 : QCMS_DATA_RGB_8;
- // FIXME: Don't force perceptual intent if the image profile contains an intent.
- m_transform = qcms_transform_create(inputProfile, dataFormat, deviceProfile, dataFormat, QCMS_INTENT_PERCEPTUAL);
- qcms_profile_release(inputProfile);
- }
-#endif
-
-private:
- png_structp m_png;
- png_infop m_info;
- unsigned m_readOffset;
- unsigned m_currentBufferSize;
- bool m_decodingSizeOnly;
- bool m_hasAlpha;
- png_bytep m_interlaceBuffer;
-#if USE(QCMSLIB)
- qcms_transform* m_transform;
- OwnArrayPtr<png_byte> m_rowBuffer;
-#endif
-};
-
-PNGImageDecoder::PNGImageDecoder(ImageSource::AlphaOption alphaOption,
- ImageSource::GammaAndColorProfileOption gammaAndColorProfileOption,
- size_t maxDecodedBytes)
- : ImageDecoder(alphaOption, gammaAndColorProfileOption, maxDecodedBytes)
- , m_doNothingOnFailure(false)
-{
-}
-
-PNGImageDecoder::~PNGImageDecoder()
-{
-}
-
-bool PNGImageDecoder::isSizeAvailable()
-{
- if (!ImageDecoder::isSizeAvailable())
- decode(true);
-
- return ImageDecoder::isSizeAvailable();
-}
-
-ImageFrame* PNGImageDecoder::frameBufferAtIndex(size_t index)
-{
- if (index)
- return 0;
-
- if (m_frameBufferCache.isEmpty()) {
- m_frameBufferCache.resize(1);
- m_frameBufferCache[0].setPremultiplyAlpha(m_premultiplyAlpha);
- }
-
- ImageFrame& frame = m_frameBufferCache[0];
- if (frame.status() != ImageFrame::FrameComplete) {
- PlatformInstrumentation::willDecodeImage("PNG");
- decode(false);
- PlatformInstrumentation::didDecodeImage();
- }
- return &frame;
-}
-
-bool PNGImageDecoder::setFailed()
-{
- if (m_doNothingOnFailure)
- return false;
- m_reader.clear();
- return ImageDecoder::setFailed();
-}
-
-static void readColorProfile(png_structp png, png_infop info, ColorProfile& colorProfile)
-{
-#ifdef PNG_iCCP_SUPPORTED
- char* profileName;
- int compressionType;
-#if (PNG_LIBPNG_VER < 10500)
- png_charp profile;
-#else
- png_bytep profile;
-#endif
- png_uint_32 profileLength;
- if (!png_get_iCCP(png, info, &profileName, &compressionType, &profile, &profileLength))
- return;
-
- // Only accept RGB color profiles from input class devices.
- bool ignoreProfile = false;
- char* profileData = reinterpret_cast<char*>(profile);
- if (profileLength < ImageDecoder::iccColorProfileHeaderLength)
- ignoreProfile = true;
- else if (!ImageDecoder::rgbColorProfile(profileData, profileLength))
- ignoreProfile = true;
- else if (!ImageDecoder::inputDeviceColorProfile(profileData, profileLength))
- ignoreProfile = true;
-
- ASSERT(colorProfile.isEmpty());
- if (!ignoreProfile)
- colorProfile.append(profileData, profileLength);
-#else
- UNUSED_PARAM(png);
- UNUSED_PARAM(info);
- UNUSED_PARAM(colorProfile);
-#endif
-}
-
-void PNGImageDecoder::headerAvailable()
-{
- png_structp png = m_reader->pngPtr();
- png_infop info = m_reader->infoPtr();
- png_uint_32 width = png_get_image_width(png, info);
- png_uint_32 height = png_get_image_height(png, info);
-
- // Protect against large images.
- if (width > cMaxPNGSize || height > cMaxPNGSize) {
- longjmp(JMPBUF(png), 1);
- return;
- }
-
- // We can fill in the size now that the header is available. Avoid memory
- // corruption issues by neutering setFailed() during this call; if we don't
- // do this, failures will cause |m_reader| to be deleted, and our jmpbuf
- // will cease to exist. Note that we'll still properly set the failure flag
- // in this case as soon as we longjmp().
- m_doNothingOnFailure = true;
- bool result = setSize(width, height);
- m_doNothingOnFailure = false;
- if (!result) {
- longjmp(JMPBUF(png), 1);
- return;
- }
-
- int bitDepth, colorType, interlaceType, compressionType, filterType, channels;
- png_get_IHDR(png, info, &width, &height, &bitDepth, &colorType, &interlaceType, &compressionType, &filterType);
-
- // The options we set here match what Mozilla does.
-
- // Expand to ensure we use 24-bit for RGB and 32-bit for RGBA.
- if (colorType == PNG_COLOR_TYPE_PALETTE || (colorType == PNG_COLOR_TYPE_GRAY && bitDepth < 8))
- png_set_expand(png);
-
- png_bytep trns = 0;
- int trnsCount = 0;
- if (png_get_valid(png, info, PNG_INFO_tRNS)) {
- png_get_tRNS(png, info, &trns, &trnsCount, 0);
- png_set_expand(png);
- }
-
- if (bitDepth == 16)
- png_set_strip_16(png);
-
- if (colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA)
- png_set_gray_to_rgb(png);
-
-#if USE(QCMSLIB)
- if ((colorType & PNG_COLOR_MASK_COLOR) && !m_ignoreGammaAndColorProfile) {
- // We only support color profiles for color PALETTE and RGB[A] PNG. Supporting
- // color profiles for gray-scale images is slightly tricky, at least using the
- // CoreGraphics ICC library, because we expand gray-scale images to RGB but we
- // do not similarly transform the color profile. We'd either need to transform
- // the color profile or we'd need to decode into a gray-scale image buffer and
- // hand that to CoreGraphics.
- ColorProfile colorProfile;
- readColorProfile(png, info, colorProfile);
- bool decodedImageHasAlpha = (colorType & PNG_COLOR_MASK_ALPHA) || trnsCount;
- m_reader->createColorTransform(colorProfile, decodedImageHasAlpha);
- }
-#endif
-
- // Deal with gamma and keep it under our control.
- double gamma;
- if (!m_ignoreGammaAndColorProfile && png_get_gAMA(png, info, &gamma)) {
- if ((gamma <= 0.0) || (gamma > cMaxGamma)) {
- gamma = cInverseGamma;
- png_set_gAMA(png, info, gamma);
- }
- png_set_gamma(png, cDefaultGamma, gamma);
- } else
- png_set_gamma(png, cDefaultGamma, cInverseGamma);
-
- // Tell libpng to send us rows for interlaced pngs.
- if (interlaceType == PNG_INTERLACE_ADAM7)
- png_set_interlace_handling(png);
-
- // Update our info now.
- png_read_update_info(png, info);
- channels = png_get_channels(png, info);
- ASSERT(channels == 3 || channels == 4);
-
- m_reader->setHasAlpha(channels == 4);
-
- if (m_reader->decodingSizeOnly()) {
- // If we only needed the size, halt the reader.
-#if defined(PNG_LIBPNG_VER_MAJOR) && defined(PNG_LIBPNG_VER_MINOR) && (PNG_LIBPNG_VER_MAJOR > 1 || (PNG_LIBPNG_VER_MAJOR == 1 && PNG_LIBPNG_VER_MINOR >= 5))
- // '0' argument to png_process_data_pause means: Do not cache unprocessed data.
- m_reader->setReadOffset(m_reader->currentBufferSize() - png_process_data_pause(png, 0));
-#else
- m_reader->setReadOffset(m_reader->currentBufferSize() - png->buffer_size);
- png->buffer_size = 0;
-#endif
- }
-}
-
-void PNGImageDecoder::rowAvailable(unsigned char* rowBuffer, unsigned rowIndex, int)
-{
- if (m_frameBufferCache.isEmpty())
- return;
-
- // Initialize the framebuffer if needed.
- ImageFrame& buffer = m_frameBufferCache[0];
- if (buffer.status() == ImageFrame::FrameEmpty) {
- png_structp png = m_reader->pngPtr();
- if (!buffer.setSize(size().width(), size().height())) {
- longjmp(JMPBUF(png), 1);
- return;
- }
-
- unsigned colorChannels = m_reader->hasAlpha() ? 4 : 3;
- if (PNG_INTERLACE_ADAM7 == png_get_interlace_type(png, m_reader->infoPtr())) {
- m_reader->createInterlaceBuffer(colorChannels * size().width() * size().height());
- if (!m_reader->interlaceBuffer()) {
- longjmp(JMPBUF(png), 1);
- return;
- }
- }
-
-#if USE(QCMSLIB)
- if (m_reader->colorTransform()) {
- m_reader->createRowBuffer(colorChannels * size().width());
- if (!m_reader->rowBuffer()) {
- longjmp(JMPBUF(png), 1);
- return;
- }
- }
-#endif
- buffer.setStatus(ImageFrame::FramePartial);
- buffer.setHasAlpha(false);
-
- // For PNGs, the frame always fills the entire image.
- buffer.setOriginalFrameRect(IntRect(IntPoint(), size()));
- }
-
- /* libpng comments (here to explain what follows).
- *
- * this function is called for every row in the image. If the
- * image is interlacing, and you turned on the interlace handler,
- * this function will be called for every row in every pass.
- * Some of these rows will not be changed from the previous pass.
- * When the row is not changed, the new_row variable will be NULL.
- * The rows and passes are called in order, so you don't really
- * need the row_num and pass, but I'm supplying them because it
- * may make your life easier.
- */
-
- // Nothing to do if the row is unchanged, or the row is outside
- // the image bounds: libpng may send extra rows, ignore them to
- // make our lives easier.
- if (!rowBuffer)
- return;
- int y = rowIndex;
- if (y < 0 || y >= size().height())
- return;
-
- /* libpng comments (continued).
- *
- * For the non-NULL rows of interlaced images, you must call
- * png_progressive_combine_row() passing in the row and the
- * old row. You can call this function for NULL rows (it will
- * just return) and for non-interlaced images (it just does the
- * memcpy for you) if it will make the code easier. Thus, you
- * can just do this for all cases:
- *
- * png_progressive_combine_row(png_ptr, old_row, new_row);
- *
- * where old_row is what was displayed for previous rows. Note
- * that the first pass (pass == 0 really) will completely cover
- * the old row, so the rows do not have to be initialized. After
- * the first pass (and only for interlaced images), you will have
- * to pass the current row, and the function will combine the
- * old row and the new row.
- */
-
- bool hasAlpha = m_reader->hasAlpha();
- unsigned colorChannels = hasAlpha ? 4 : 3;
- png_bytep row = rowBuffer;
-
- if (png_bytep interlaceBuffer = m_reader->interlaceBuffer()) {
- row = interlaceBuffer + (rowIndex * colorChannels * size().width());
- png_progressive_combine_row(m_reader->pngPtr(), row, rowBuffer);
- }
-
-#if USE(QCMSLIB)
- if (qcms_transform* transform = m_reader->colorTransform()) {
- qcms_transform_data(transform, row, m_reader->rowBuffer(), size().width());
- row = m_reader->rowBuffer();
- }
-#endif
-
- // Write the decoded row pixels to the frame buffer.
- ImageFrame::PixelData* address = buffer.getAddr(0, y);
- bool nonTrivialAlpha = false;
- int width = size().width();
-
- png_bytep pixel = row;
- for (int x = 0; x < width; ++x, pixel += colorChannels) {
- unsigned alpha = hasAlpha ? pixel[3] : 255;
- buffer.setRGBA(address++, pixel[0], pixel[1], pixel[2], alpha);
- nonTrivialAlpha |= alpha < 255;
- }
-
- if (nonTrivialAlpha && !buffer.hasAlpha())
- buffer.setHasAlpha(nonTrivialAlpha);
-}
-
-void PNGImageDecoder::pngComplete()
-{
- if (!m_frameBufferCache.isEmpty())
- m_frameBufferCache.first().setStatus(ImageFrame::FrameComplete);
-}
-
-void PNGImageDecoder::decode(bool onlySize)
-{
- if (failed())
- return;
-
- if (!m_reader)
- m_reader = adoptPtr(new PNGImageReader(this));
-
- // If we couldn't decode the image but we've received all the data, decoding
- // has failed.
- if (!m_reader->decode(*m_data, onlySize) && isAllDataReceived())
- setFailed();
- // If we're done decoding the image, we don't need the PNGImageReader
- // anymore. (If we failed, |m_reader| has already been cleared.)
- else if (isComplete())
- m_reader.clear();
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/image-decoders/png/PNGImageDecoder.h b/chromium/third_party/WebKit/Source/core/platform/image-decoders/png/PNGImageDecoder.h
deleted file mode 100644
index ca09b6d2a44..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/image-decoders/png/PNGImageDecoder.h
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * Copyright (C) 2006 Apple Computer, Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef PNGImageDecoder_h
-#define PNGImageDecoder_h
-
-#include "core/platform/image-decoders/ImageDecoder.h"
-#include "wtf/OwnPtr.h"
-
-namespace WebCore {
-
- class PNGImageReader;
-
- // This class decodes the PNG image format.
- class PNGImageDecoder : public ImageDecoder {
- public:
- PNGImageDecoder(ImageSource::AlphaOption, ImageSource::GammaAndColorProfileOption, size_t maxDecodedBytes);
- virtual ~PNGImageDecoder();
-
- // ImageDecoder
- virtual String filenameExtension() const { return "png"; }
- virtual bool isSizeAvailable();
- virtual ImageFrame* frameBufferAtIndex(size_t);
- // CAUTION: setFailed() deletes |m_reader|. Be careful to avoid
- // accessing deleted memory, especially when calling this from inside
- // PNGImageReader!
- virtual bool setFailed();
-
- // Callbacks from libpng
- void headerAvailable();
- void rowAvailable(unsigned char* rowBuffer, unsigned rowIndex, int interlacePass);
- void pngComplete();
-
- bool isComplete() const
- {
- return !m_frameBufferCache.isEmpty() && (m_frameBufferCache.first().status() == ImageFrame::FrameComplete);
- }
-
- private:
- // Decodes the image. If |onlySize| is true, stops decoding after
- // calculating the image size. If decoding fails but there is no more
- // data coming, sets the "decode failure" flag.
- void decode(bool onlySize);
-
- OwnPtr<PNGImageReader> m_reader;
- bool m_doNothingOnFailure;
- };
-
-} // namespace WebCore
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/image-decoders/webp/WEBPImageDecoder.cpp b/chromium/third_party/WebKit/Source/core/platform/image-decoders/webp/WEBPImageDecoder.cpp
deleted file mode 100644
index 84bfd9d1061..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/image-decoders/webp/WEBPImageDecoder.cpp
+++ /dev/null
@@ -1,535 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/image-decoders/webp/WEBPImageDecoder.h"
-
-#include "core/platform/PlatformInstrumentation.h"
-
-#if USE(QCMSLIB)
-#include "qcms.h"
-#endif
-
-#include "RuntimeEnabledFeatures.h"
-
-#if CPU(BIG_ENDIAN) || CPU(MIDDLE_ENDIAN)
-inline WEBP_CSP_MODE outputMode(bool hasAlpha) { return hasAlpha ? MODE_rgbA : MODE_RGBA; }
-#elif SK_B32_SHIFT
-inline WEBP_CSP_MODE outputMode(bool hasAlpha) { return hasAlpha ? MODE_rgbA : MODE_RGBA; }
-#else // LITTLE_ENDIAN, output BGRA pixels.
-inline WEBP_CSP_MODE outputMode(bool hasAlpha) { return hasAlpha ? MODE_bgrA : MODE_BGRA; }
-#endif
-
-namespace WebCore {
-
-WEBPImageDecoder::WEBPImageDecoder(ImageSource::AlphaOption alphaOption,
- ImageSource::GammaAndColorProfileOption gammaAndColorProfileOption,
- size_t maxDecodedBytes)
- : ImageDecoder(alphaOption, gammaAndColorProfileOption, maxDecodedBytes)
- , m_decoder(0)
- , m_formatFlags(0)
- , m_frameBackgroundHasAlpha(false)
-#if USE(QCMSLIB)
- , m_haveReadProfile(false)
- , m_transform(0)
-#endif
- , m_demux(0)
- , m_demuxState(WEBP_DEMUX_PARSING_HEADER)
- , m_haveAlreadyParsedThisData(false)
- , m_haveReadAnimationParameters(false)
- , m_repetitionCount(cAnimationLoopOnce)
- , m_decodedHeight(0)
-{
-}
-
-WEBPImageDecoder::~WEBPImageDecoder()
-{
- clear();
-}
-
-void WEBPImageDecoder::clear()
-{
-#if USE(QCMSLIB)
- if (m_transform)
- qcms_transform_release(m_transform);
- m_transform = 0;
-#endif
- WebPDemuxDelete(m_demux);
- m_demux = 0;
- clearDecoder();
-}
-
-void WEBPImageDecoder::clearDecoder()
-{
- WebPIDelete(m_decoder);
- m_decoder = 0;
- m_decodedHeight = 0;
- m_frameBackgroundHasAlpha = false;
-}
-
-bool WEBPImageDecoder::isSizeAvailable()
-{
- if (!ImageDecoder::isSizeAvailable())
- updateDemuxer();
-
- return ImageDecoder::isSizeAvailable();
-}
-
-size_t WEBPImageDecoder::frameCount()
-{
- if (!updateDemuxer())
- return 0;
-
- return m_frameBufferCache.size();
-}
-
-ImageFrame* WEBPImageDecoder::frameBufferAtIndex(size_t index)
-{
- if (index >= frameCount())
- return 0;
-
- ImageFrame& frame = m_frameBufferCache[index];
- if (frame.status() == ImageFrame::FrameComplete)
- return &frame;
-
- if (RuntimeEnabledFeatures::animatedWebPEnabled()) {
- Vector<size_t> framesToDecode;
- size_t frameToDecode = index;
- do {
- framesToDecode.append(frameToDecode);
- frameToDecode = m_frameBufferCache[frameToDecode].requiredPreviousFrameIndex();
- } while (frameToDecode != kNotFound && m_frameBufferCache[frameToDecode].status() != ImageFrame::FrameComplete);
-
- ASSERT(m_demux);
- for (size_t i = framesToDecode.size(); i > 0; --i) {
- size_t frameIndex = framesToDecode[i - 1];
- if ((m_formatFlags & ANIMATION_FLAG) && !initFrameBuffer(frameIndex))
- return 0;
- WebPIterator webpFrame;
- if (!WebPDemuxGetFrame(m_demux, frameIndex + 1, &webpFrame))
- return 0;
- PlatformInstrumentation::willDecodeImage("WEBP");
- decode(webpFrame.fragment.bytes, webpFrame.fragment.size, false, frameIndex);
- PlatformInstrumentation::didDecodeImage();
- WebPDemuxReleaseIterator(&webpFrame);
-
- // We need more data to continue decoding.
- if (m_frameBufferCache[frameIndex].status() != ImageFrame::FrameComplete)
- break;
- }
-
- // It is also a fatal error if all data is received and we have decoded all
- // frames available but the file is truncated.
- if (index >= m_frameBufferCache.size() - 1 && isAllDataReceived() && m_demux && m_demuxState != WEBP_DEMUX_DONE)
- setFailed();
-
- return &frame;
- }
-
- ASSERT(!index);
- PlatformInstrumentation::willDecodeImage("WEBP");
- decode(reinterpret_cast<const uint8_t*>(m_data->data()), m_data->size(), false, index);
- PlatformInstrumentation::didDecodeImage();
- return &frame;
-}
-
-void WEBPImageDecoder::setData(SharedBuffer* data, bool allDataReceived)
-{
- if (failed())
- return;
- ImageDecoder::setData(data, allDataReceived);
- m_haveAlreadyParsedThisData = false;
-}
-
-int WEBPImageDecoder::repetitionCount() const
-{
- return failed() ? cAnimationLoopOnce : m_repetitionCount;
-}
-
-bool WEBPImageDecoder::frameIsCompleteAtIndex(size_t index) const
-{
- if (!RuntimeEnabledFeatures::animatedWebPEnabled())
- return ImageDecoder::frameIsCompleteAtIndex(index);
- if (!m_demux || m_demuxState <= WEBP_DEMUX_PARSING_HEADER)
- return false;
- if (!(m_formatFlags & ANIMATION_FLAG))
- return ImageDecoder::frameIsCompleteAtIndex(index);
- bool frameIsLoadedAtIndex = index < m_frameBufferCache.size();
- return frameIsLoadedAtIndex;
-}
-
-float WEBPImageDecoder::frameDurationAtIndex(size_t index) const
-{
- return index < m_frameBufferCache.size() ? m_frameBufferCache[index].duration() : 0;
-}
-
-bool WEBPImageDecoder::updateDemuxer()
-{
- if (m_haveAlreadyParsedThisData)
- return true;
-
- m_haveAlreadyParsedThisData = true;
-
- const unsigned webpHeaderSize = 20;
- if (m_data->size() < webpHeaderSize)
- return false; // Wait for headers so that WebPDemuxPartial doesn't return null.
-
- WebPDemuxDelete(m_demux);
- WebPData inputData = { reinterpret_cast<const uint8_t*>(m_data->data()), m_data->size() };
- m_demux = WebPDemuxPartial(&inputData, &m_demuxState);
- if (!m_demux)
- return setFailed();
-
- if (m_demuxState <= WEBP_DEMUX_PARSING_HEADER)
- return false; // Not enough data for parsing canvas width/height yet.
-
- bool hasAnimation = (m_formatFlags & ANIMATION_FLAG);
- if (!ImageDecoder::isSizeAvailable()) {
- m_formatFlags = WebPDemuxGetI(m_demux, WEBP_FF_FORMAT_FLAGS);
- hasAnimation = (m_formatFlags & ANIMATION_FLAG);
- if (hasAnimation && !RuntimeEnabledFeatures::animatedWebPEnabled())
- return setFailed();
- if (!setSize(WebPDemuxGetI(m_demux, WEBP_FF_CANVAS_WIDTH), WebPDemuxGetI(m_demux, WEBP_FF_CANVAS_HEIGHT)))
- return setFailed();
- }
-
- ASSERT(ImageDecoder::isSizeAvailable());
- const size_t newFrameCount = WebPDemuxGetI(m_demux, WEBP_FF_FRAME_COUNT);
- if (hasAnimation && !m_haveReadAnimationParameters && newFrameCount) {
- // As we have parsed at least one frame (even if partially),
- // we must already have parsed the animation properties.
- // This is because ANIM chunk always precedes ANMF chunks.
- m_repetitionCount = WebPDemuxGetI(m_demux, WEBP_FF_LOOP_COUNT);
- ASSERT(m_repetitionCount == (m_repetitionCount & 0xffff)); // Loop count is always <= 16 bits.
- if (!m_repetitionCount)
- m_repetitionCount = cAnimationLoopInfinite;
- m_haveReadAnimationParameters = true;
- }
-
- const size_t oldFrameCount = m_frameBufferCache.size();
- if (newFrameCount > oldFrameCount) {
- m_frameBufferCache.resize(newFrameCount);
- for (size_t i = oldFrameCount; i < newFrameCount; ++i) {
- m_frameBufferCache[i].setPremultiplyAlpha(m_premultiplyAlpha);
- if (!hasAnimation) {
- ASSERT(!i);
- m_frameBufferCache[i].setRequiredPreviousFrameIndex(kNotFound);
- continue;
- }
- WebPIterator animatedFrame;
- WebPDemuxGetFrame(m_demux, i + 1, &animatedFrame);
- ASSERT(animatedFrame.complete == 1);
- m_frameBufferCache[i].setDuration(animatedFrame.duration);
- m_frameBufferCache[i].setDisposalMethod(animatedFrame.dispose_method == WEBP_MUX_DISPOSE_BACKGROUND ? ImageFrame::DisposeOverwriteBgcolor : ImageFrame::DisposeKeep);
- m_frameBufferCache[i].setAlphaBlendSource(animatedFrame.blend_method == WEBP_MUX_BLEND ? ImageFrame::BlendAtopPreviousFrame : ImageFrame::BlendAtopBgcolor);
- IntRect frameRect(animatedFrame.x_offset, animatedFrame.y_offset, animatedFrame.width, animatedFrame.height);
- // Make sure the frameRect doesn't extend outside the buffer.
- if (frameRect.maxX() > size().width())
- frameRect.setWidth(size().width() - animatedFrame.x_offset);
- if (frameRect.maxY() > size().height())
- frameRect.setHeight(size().height() - animatedFrame.y_offset);
- m_frameBufferCache[i].setOriginalFrameRect(frameRect);
- m_frameBufferCache[i].setRequiredPreviousFrameIndex(findRequiredPreviousFrame(i, !animatedFrame.has_alpha));
- WebPDemuxReleaseIterator(&animatedFrame);
- }
- }
-
- return true;
-}
-
-bool WEBPImageDecoder::initFrameBuffer(size_t frameIndex)
-{
- ImageFrame& buffer = m_frameBufferCache[frameIndex];
- if (buffer.status() != ImageFrame::FrameEmpty) // Already initialized.
- return true;
-
- const size_t requiredPreviousFrameIndex = buffer.requiredPreviousFrameIndex();
- if (requiredPreviousFrameIndex == kNotFound) {
- // This frame doesn't rely on any previous data.
- if (!buffer.setSize(size().width(), size().height()))
- return setFailed();
- m_frameBackgroundHasAlpha = !buffer.originalFrameRect().contains(IntRect(IntPoint(), size()));
- } else {
- const ImageFrame& prevBuffer = m_frameBufferCache[requiredPreviousFrameIndex];
- ASSERT(prevBuffer.status() == ImageFrame::FrameComplete);
-
- // Preserve the last frame as the starting state for this frame.
- if (!buffer.copyBitmapData(prevBuffer))
- return setFailed();
-
- if (prevBuffer.disposalMethod() == ImageFrame::DisposeOverwriteBgcolor) {
- // We want to clear the previous frame to transparent, without
- // affecting pixels in the image outside of the frame.
- const IntRect& prevRect = prevBuffer.originalFrameRect();
- ASSERT(!prevRect.contains(IntRect(IntPoint(), size())));
- buffer.zeroFillFrameRect(prevRect);
- }
-
- m_frameBackgroundHasAlpha = prevBuffer.hasAlpha() || (prevBuffer.disposalMethod() == ImageFrame::DisposeOverwriteBgcolor);
- }
-
- buffer.setStatus(ImageFrame::FramePartial);
- // The buffer is transparent outside the decoded area while the image is loading.
- // The correct value of 'hasAlpha' for the frame will be set when it is fully decoded.
- buffer.setHasAlpha(true);
- return true;
-}
-
-size_t WEBPImageDecoder::clearCacheExceptFrame(size_t clearExceptFrame)
-{
- // If |clearExceptFrame| has status FrameComplete, we preserve that frame.
- // Otherwise, we preserve a previous frame with status FrameComplete whose data is required
- // to decode |clearExceptFrame|, either in initFrameBuffer() or ApplyPostProcessing().
- // All other frames can be cleared.
- while ((clearExceptFrame < m_frameBufferCache.size()) && (m_frameBufferCache[clearExceptFrame].status() != ImageFrame::FrameComplete))
- clearExceptFrame = m_frameBufferCache[clearExceptFrame].requiredPreviousFrameIndex();
-
- return ImageDecoder::clearCacheExceptFrame(clearExceptFrame);
-}
-
-void WEBPImageDecoder::clearFrameBuffer(size_t frameIndex)
-{
- if (m_demux && m_demuxState >= WEBP_DEMUX_PARSED_HEADER && m_frameBufferCache[frameIndex].status() == ImageFrame::FramePartial) {
- // Clear the decoder state so that this partial frame can be decoded again when requested.
- clearDecoder();
- }
- ImageDecoder::clearFrameBuffer(frameIndex);
-}
-
-#if USE(QCMSLIB)
-
-void WEBPImageDecoder::createColorTransform(const char* data, size_t size)
-{
- if (m_transform)
- qcms_transform_release(m_transform);
- m_transform = 0;
-
- qcms_profile* deviceProfile = ImageDecoder::qcmsOutputDeviceProfile();
- if (!deviceProfile)
- return;
- qcms_profile* inputProfile = qcms_profile_from_memory(data, size);
- if (!inputProfile)
- return;
-
- // We currently only support color profiles for RGB profiled images.
- ASSERT(icSigRgbData == qcms_profile_get_color_space(inputProfile));
- // The input image pixels are RGBA format.
- qcms_data_type format = QCMS_DATA_RGBA_8;
- // FIXME: Don't force perceptual intent if the image profile contains an intent.
- m_transform = qcms_transform_create(inputProfile, format, deviceProfile, QCMS_DATA_RGBA_8, QCMS_INTENT_PERCEPTUAL);
-
- qcms_profile_release(inputProfile);
-}
-
-void WEBPImageDecoder::readColorProfile()
-{
- WebPChunkIterator chunkIterator;
- if (!WebPDemuxGetChunk(m_demux, "ICCP", 1, &chunkIterator)) {
- WebPDemuxReleaseChunkIterator(&chunkIterator);
- return;
- }
-
- const char* profileData = reinterpret_cast<const char*>(chunkIterator.chunk.bytes);
- size_t profileSize = chunkIterator.chunk.size;
-
- // Only accept RGB color profiles from input class devices.
- bool ignoreProfile = false;
- if (profileSize < ImageDecoder::iccColorProfileHeaderLength)
- ignoreProfile = true;
- else if (!ImageDecoder::rgbColorProfile(profileData, profileSize))
- ignoreProfile = true;
- else if (!ImageDecoder::inputDeviceColorProfile(profileData, profileSize))
- ignoreProfile = true;
-
- if (!ignoreProfile)
- createColorTransform(profileData, profileSize);
-
- WebPDemuxReleaseChunkIterator(&chunkIterator);
-}
-
-#endif // USE(QCMSLIB)
-
-void WEBPImageDecoder::applyPostProcessing(size_t frameIndex)
-{
- ImageFrame& buffer = m_frameBufferCache[frameIndex];
- int width;
- int decodedHeight;
- if (!WebPIDecGetRGB(m_decoder, &decodedHeight, &width, 0, 0))
- return; // See also https://bugs.webkit.org/show_bug.cgi?id=74062
- if (decodedHeight <= 0)
- return;
-
- const IntRect& frameRect = buffer.originalFrameRect();
- ASSERT_WITH_SECURITY_IMPLICATION(width == frameRect.width());
- ASSERT_WITH_SECURITY_IMPLICATION(decodedHeight <= frameRect.height());
- const int left = frameRect.x();
- const int top = frameRect.y();
-
-#if USE(QCMSLIB)
- if ((m_formatFlags & ICCP_FLAG) && !ignoresGammaAndColorProfile()) {
- if (!m_haveReadProfile) {
- readColorProfile();
- m_haveReadProfile = true;
- }
- for (int y = m_decodedHeight; y < decodedHeight; ++y) {
- const int canvasY = top + y;
- uint8_t* row = reinterpret_cast<uint8_t*>(buffer.getAddr(left, canvasY));
- if (qcms_transform* transform = colorTransform())
- qcms_transform_data_type(transform, row, row, width, QCMS_OUTPUT_RGBX);
- uint8_t* pixel = row;
- for (int x = 0; x < width; ++x, pixel += 4) {
- const int canvasX = left + x;
- buffer.setRGBA(canvasX, canvasY, pixel[0], pixel[1], pixel[2], pixel[3]);
- }
- }
- }
-#endif // USE(QCMSLIB)
-
- // During the decoding of current frame, we may have set some pixels to be transparent (i.e. alpha < 255).
- // However, the value of each of these pixels should have been determined by blending it against the value
- // of that pixel in the previous frame if alpha blend source was 'BlendAtopPreviousFrame'. So, we correct these
- // pixels based on disposal method of the previous frame and the previous frame buffer.
- // FIXME: This could be avoided if libwebp decoder had an API that used the previous required frame
- // to do the alpha-blending by itself.
- if ((m_formatFlags & ANIMATION_FLAG) && frameIndex && buffer.alphaBlendSource() == ImageFrame::BlendAtopPreviousFrame && buffer.requiredPreviousFrameIndex() != kNotFound) {
- ImageFrame& prevBuffer = m_frameBufferCache[frameIndex - 1];
- ASSERT(prevBuffer.status() == ImageFrame::FrameComplete);
- ImageFrame::DisposalMethod prevDisposalMethod = prevBuffer.disposalMethod();
- if (prevDisposalMethod == ImageFrame::DisposeKeep) { // Restore transparent pixels to pixels in previous canvas.
- for (int y = m_decodedHeight; y < decodedHeight; ++y) {
- const int canvasY = top + y;
- for (int x = 0; x < width; ++x) {
- const int canvasX = left + x;
- ImageFrame::PixelData& pixel = *buffer.getAddr(canvasX, canvasY);
- // FIXME: Use alpha-blending when alpha is between 0 and 255.
- // Alpha-blending is being implemented in: https://bugs.webkit.org/show_bug.cgi?id=17022
- if (!((pixel >> SK_A32_SHIFT) & 0xff)) {
- ImageFrame::PixelData prevPixel = *prevBuffer.getAddr(canvasX, canvasY);
- pixel = prevPixel;
- }
- }
- }
- } else if (prevDisposalMethod == ImageFrame::DisposeOverwriteBgcolor) {
- const IntRect& prevRect = prevBuffer.originalFrameRect();
- // We need to restore transparent pixels to as they were just after initFrame() call. That is:
- // * Transparent if it belongs to prevRect <-- This is a no-op.
- // * Pixel in the previous canvas otherwise <-- Need to restore.
- for (int y = m_decodedHeight; y < decodedHeight; ++y) {
- const int canvasY = top + y;
- for (int x = 0; x < width; ++x) {
- const int canvasX = left + x;
- ImageFrame::PixelData& pixel = *buffer.getAddr(canvasX, canvasY);
- // FIXME: Use alpha-blending when alpha is between 0 and 255.
- if (!((pixel >> SK_A32_SHIFT) & 0xff) && !prevRect.contains(IntPoint(canvasX, canvasY))) {
- ImageFrame::PixelData prevPixel = *prevBuffer.getAddr(canvasX, canvasY);
- pixel = prevPixel;
- }
- }
- }
- }
- }
-
- m_decodedHeight = decodedHeight;
-}
-
-bool WEBPImageDecoder::decode(const uint8_t* dataBytes, size_t dataSize, bool onlySize, size_t frameIndex)
-{
- if (failed())
- return false;
-
- if (!ImageDecoder::isSizeAvailable()) {
- static const size_t imageHeaderSize = 30;
- if (dataSize < imageHeaderSize)
- return false;
- int width, height;
- WebPBitstreamFeatures features;
- if (WebPGetFeatures(dataBytes, dataSize, &features) != VP8_STATUS_OK)
- return setFailed();
- width = features.width;
- height = features.height;
- m_formatFlags = features.has_alpha ? ALPHA_FLAG : 0;
- if (!setSize(width, height))
- return setFailed();
- }
-
- ASSERT(ImageDecoder::isSizeAvailable());
- if (onlySize)
- return true;
-
- ASSERT(m_frameBufferCache.size() > frameIndex);
- ImageFrame& buffer = m_frameBufferCache[frameIndex];
- ASSERT(buffer.status() != ImageFrame::FrameComplete);
-
- if (buffer.status() == ImageFrame::FrameEmpty) {
- if (!buffer.setSize(size().width(), size().height()))
- return setFailed();
- buffer.setStatus(ImageFrame::FramePartial);
- // The buffer is transparent outside the decoded area while the image is loading.
- // The correct value of 'hasAlpha' for the frame will be set when it is fully decoded.
- buffer.setHasAlpha(true);
- buffer.setOriginalFrameRect(IntRect(IntPoint(), size()));
- }
-
- const IntRect& frameRect = buffer.originalFrameRect();
- if (!m_decoder) {
- WEBP_CSP_MODE mode = outputMode(m_formatFlags & ALPHA_FLAG);
- if (!m_premultiplyAlpha)
- mode = outputMode(false);
-#if USE(QCMSLIB)
- if ((m_formatFlags & ICCP_FLAG) && !ignoresGammaAndColorProfile())
- mode = MODE_RGBA; // Decode to RGBA for input to libqcms.
-#endif
- WebPInitDecBuffer(&m_decoderBuffer);
- m_decoderBuffer.colorspace = mode;
- m_decoderBuffer.u.RGBA.stride = size().width() * sizeof(ImageFrame::PixelData);
- m_decoderBuffer.u.RGBA.size = m_decoderBuffer.u.RGBA.stride * frameRect.height();
- m_decoderBuffer.is_external_memory = 1;
- m_decoder = WebPINewDecoder(&m_decoderBuffer);
- if (!m_decoder)
- return setFailed();
- }
-
- m_decoderBuffer.u.RGBA.rgba = reinterpret_cast<uint8_t*>(buffer.getAddr(frameRect.x(), frameRect.y()));
-
- switch (WebPIUpdate(m_decoder, dataBytes, dataSize)) {
- case VP8_STATUS_OK:
- applyPostProcessing(frameIndex);
- buffer.setHasAlpha((m_formatFlags & ALPHA_FLAG) || m_frameBackgroundHasAlpha);
- buffer.setStatus(ImageFrame::FrameComplete);
- clearDecoder();
- return true;
- case VP8_STATUS_SUSPENDED:
- applyPostProcessing(frameIndex);
- return false;
- default:
- clear();
- return setFailed();
- }
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/image-decoders/webp/WEBPImageDecoder.h b/chromium/third_party/WebKit/Source/core/platform/image-decoders/webp/WEBPImageDecoder.h
deleted file mode 100644
index 2a165cd0329..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/image-decoders/webp/WEBPImageDecoder.h
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef WEBPImageDecoder_h
-#define WEBPImageDecoder_h
-
-#include "core/platform/image-decoders/ImageDecoder.h"
-
-#include "webp/decode.h"
-#include "webp/demux.h"
-
-namespace WebCore {
-
-class WEBPImageDecoder : public ImageDecoder {
-public:
- WEBPImageDecoder(ImageSource::AlphaOption, ImageSource::GammaAndColorProfileOption, size_t maxDecodedBytes);
- virtual ~WEBPImageDecoder();
-
- virtual String filenameExtension() const OVERRIDE { return "webp"; }
- virtual bool isSizeAvailable() OVERRIDE;
- virtual size_t frameCount() OVERRIDE;
- virtual ImageFrame* frameBufferAtIndex(size_t) OVERRIDE;
- virtual void setData(SharedBuffer* data, bool allDataReceived) OVERRIDE;
- virtual int repetitionCount() const OVERRIDE;
- virtual bool frameIsCompleteAtIndex(size_t) const OVERRIDE;
- virtual float frameDurationAtIndex(size_t) const OVERRIDE;
- virtual size_t clearCacheExceptFrame(size_t) OVERRIDE;
-
-private:
- bool decode(const uint8_t* dataBytes, size_t dataSize, bool onlySize, size_t frameIndex);
-
- WebPIDecoder* m_decoder;
- WebPDecBuffer m_decoderBuffer;
- int m_formatFlags;
- bool m_frameBackgroundHasAlpha;
-
-#if USE(QCMSLIB)
- qcms_transform* colorTransform() const { return m_transform; }
- void createColorTransform(const char* data, size_t);
- void readColorProfile();
-
- bool m_haveReadProfile;
- qcms_transform* m_transform;
-#endif
-
- bool updateDemuxer();
- bool initFrameBuffer(size_t frameIndex);
- void applyPostProcessing(size_t frameIndex);
- virtual void clearFrameBuffer(size_t frameIndex) OVERRIDE;
-
- WebPDemuxer* m_demux;
- WebPDemuxState m_demuxState;
- bool m_haveAlreadyParsedThisData;
- bool m_haveReadAnimationParameters;
- int m_repetitionCount;
- int m_decodedHeight;
-
- void clear();
- void clearDecoder();
-};
-
-} // namespace WebCore
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/image-decoders/webp/WEBPImageDecoderTest.cpp b/chromium/third_party/WebKit/Source/core/platform/image-decoders/webp/WEBPImageDecoderTest.cpp
deleted file mode 100644
index 54db2d5eae0..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/image-decoders/webp/WEBPImageDecoderTest.cpp
+++ /dev/null
@@ -1,506 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/platform/image-decoders/webp/WEBPImageDecoder.h"
-
-#include "RuntimeEnabledFeatures.h"
-#include "core/platform/SharedBuffer.h"
-#include "public/platform/Platform.h"
-#include "public/platform/WebData.h"
-#include "public/platform/WebSize.h"
-#include "public/platform/WebUnitTestSupport.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/StringHasher.h"
-#include "wtf/Vector.h"
-#include "wtf/dtoa/utils.h"
-#include <gtest/gtest.h>
-
-using namespace WebCore;
-using namespace WebKit;
-
-namespace {
-
-PassRefPtr<SharedBuffer> readFile(const char* fileName)
-{
- String filePath = Platform::current()->unitTestSupport()->webKitRootDir();
- filePath.append(fileName);
-
- return Platform::current()->unitTestSupport()->readFromFile(filePath);
-}
-
-PassOwnPtr<WEBPImageDecoder> createDecoder()
-{
- return adoptPtr(new WEBPImageDecoder(ImageSource::AlphaNotPremultiplied, ImageSource::GammaAndColorProfileApplied, ImageDecoder::noDecodedImageByteLimit));
-}
-
-unsigned hashSkBitmap(const SkBitmap& bitmap)
-{
- return StringHasher::hashMemory(bitmap.getPixels(), bitmap.getSize());
-}
-
-void createDecodingBaseline(SharedBuffer* data, Vector<unsigned>* baselineHashes)
-{
- OwnPtr<WEBPImageDecoder> decoder = createDecoder();
- decoder->setData(data, true);
- size_t frameCount = decoder->frameCount();
- for (size_t i = 0; i < frameCount; ++i) {
- ImageFrame* frame = decoder->frameBufferAtIndex(i);
- baselineHashes->append(hashSkBitmap(frame->getSkBitmap()));
- }
-}
-
-void testRandomFrameDecode(const char* webpFile)
-{
- SCOPED_TRACE(webpFile);
-
- RefPtr<SharedBuffer> fullData = readFile(webpFile);
- ASSERT_TRUE(fullData.get());
- Vector<unsigned> baselineHashes;
- createDecodingBaseline(fullData.get(), &baselineHashes);
- size_t frameCount = baselineHashes.size();
-
- // Random decoding should get the same results as sequential decoding.
- OwnPtr<WEBPImageDecoder> decoder = createDecoder();
- decoder->setData(fullData.get(), true);
- const size_t skippingStep = 5;
- for (size_t i = 0; i < skippingStep; ++i) {
- for (size_t j = i; j < frameCount; j += skippingStep) {
- SCOPED_TRACE(testing::Message() << "Random i:" << i << " j:" << j);
- ImageFrame* frame = decoder->frameBufferAtIndex(j);
- EXPECT_EQ(baselineHashes[j], hashSkBitmap(frame->getSkBitmap()));
- }
- }
-
- // Decoding in reverse order.
- decoder = createDecoder();
- decoder->setData(fullData.get(), true);
- for (size_t i = frameCount; i; --i) {
- SCOPED_TRACE(testing::Message() << "Reverse i:" << i);
- ImageFrame* frame = decoder->frameBufferAtIndex(i - 1);
- EXPECT_EQ(baselineHashes[i - 1], hashSkBitmap(frame->getSkBitmap()));
- }
-}
-
-void testRandomDecodeAfterClearFrameBufferCache(const char* webpFile)
-{
- SCOPED_TRACE(webpFile);
-
- RefPtr<SharedBuffer> data = readFile(webpFile);
- ASSERT_TRUE(data.get());
- Vector<unsigned> baselineHashes;
- createDecodingBaseline(data.get(), &baselineHashes);
- size_t frameCount = baselineHashes.size();
-
- OwnPtr<WEBPImageDecoder> decoder = createDecoder();
- decoder->setData(data.get(), true);
- for (size_t clearExceptFrame = 0; clearExceptFrame < frameCount; ++clearExceptFrame) {
- decoder->clearCacheExceptFrame(clearExceptFrame);
- const size_t skippingStep = 5;
- for (size_t i = 0; i < skippingStep; ++i) {
- for (size_t j = 0; j < frameCount; j += skippingStep) {
- SCOPED_TRACE(testing::Message() << "Random i:" << i << " j:" << j);
- ImageFrame* frame = decoder->frameBufferAtIndex(j);
- EXPECT_EQ(baselineHashes[j], hashSkBitmap(frame->getSkBitmap()));
- }
- }
- }
-}
-
-void testDecodeAfterReallocatingData(const char* webpFile)
-{
- OwnPtr<WEBPImageDecoder> decoder = createDecoder();
- RefPtr<SharedBuffer> data = readFile(webpFile);
- ASSERT_TRUE(data.get());
-
- // Parse from 'data'.
- decoder->setData(data.get(), true);
- size_t frameCount = decoder->frameCount();
-
- // ... and then decode frames from 'reallocatedData'.
- RefPtr<SharedBuffer> reallocatedData = data.get()->copy();
- ASSERT_TRUE(reallocatedData.get());
- data.clear();
- decoder->setData(reallocatedData.get(), true);
-
- for (size_t i = 0; i < frameCount; ++i) {
- const ImageFrame* const frame = decoder->frameBufferAtIndex(i);
- EXPECT_EQ(ImageFrame::FrameComplete, frame->status());
- }
-}
-
-} // namespace
-
-class AnimatedWebPTests : public ::testing::Test {
-protected:
- virtual void SetUp()
- {
- // Enable animated WebP for all the tests.
- WebCore::RuntimeEnabledFeatures::setAnimatedWebPEnabled(true);
- }
-};
-
-TEST_F(AnimatedWebPTests, verifyAnimationParametersTransparentImage)
-{
- OwnPtr<WEBPImageDecoder> decoder = createDecoder();
- EXPECT_EQ(cAnimationLoopOnce, decoder->repetitionCount());
-
- RefPtr<SharedBuffer> data = readFile("/LayoutTests/fast/images/resources/webp-animated.webp");
- ASSERT_TRUE(data.get());
- decoder->setData(data.get(), true);
-
- const int canvasWidth = 11;
- const int canvasHeight = 29;
- const struct AnimParam {
- int xOffset, yOffset, width, height;
- ImageFrame::DisposalMethod disposalMethod;
- ImageFrame::AlphaBlendSource alphaBlendSource;
- unsigned duration;
- bool hasAlpha;
- } frameParameters[] = {
- { 0, 0, 11, 29, ImageFrame::DisposeKeep, ImageFrame::BlendAtopPreviousFrame, 1000u, true },
- { 2, 10, 7, 17, ImageFrame::DisposeKeep, ImageFrame::BlendAtopPreviousFrame, 500u, true },
- { 2, 2, 7, 16, ImageFrame::DisposeKeep, ImageFrame::BlendAtopPreviousFrame, 1000u, true },
- };
-
- for (size_t i = 0; i < ARRAY_SIZE(frameParameters); ++i) {
- const ImageFrame* const frame = decoder->frameBufferAtIndex(i);
- EXPECT_EQ(ImageFrame::FrameComplete, frame->status());
- EXPECT_EQ(canvasWidth, frame->getSkBitmap().width());
- EXPECT_EQ(canvasHeight, frame->getSkBitmap().height());
- EXPECT_EQ(frameParameters[i].xOffset, frame->originalFrameRect().x());
- EXPECT_EQ(frameParameters[i].yOffset, frame->originalFrameRect().y());
- EXPECT_EQ(frameParameters[i].width, frame->originalFrameRect().width());
- EXPECT_EQ(frameParameters[i].height, frame->originalFrameRect().height());
- EXPECT_EQ(frameParameters[i].disposalMethod, frame->disposalMethod());
- EXPECT_EQ(frameParameters[i].alphaBlendSource, frame->alphaBlendSource());
- EXPECT_EQ(frameParameters[i].duration, frame->duration());
- EXPECT_EQ(frameParameters[i].hasAlpha, frame->hasAlpha());
- }
-
- EXPECT_EQ(ARRAY_SIZE(frameParameters), decoder->frameCount());
- EXPECT_EQ(cAnimationLoopInfinite, decoder->repetitionCount());
-}
-
-TEST_F(AnimatedWebPTests, verifyAnimationParametersOpaqueFramesTransparentBackground)
-{
- OwnPtr<WEBPImageDecoder> decoder = createDecoder();
- EXPECT_EQ(cAnimationLoopOnce, decoder->repetitionCount());
-
- RefPtr<SharedBuffer> data = readFile("/LayoutTests/fast/images/resources/webp-animated-opaque.webp");
- ASSERT_TRUE(data.get());
- decoder->setData(data.get(), true);
-
- const int canvasWidth = 94;
- const int canvasHeight = 87;
- const struct AnimParam {
- int xOffset, yOffset, width, height;
- ImageFrame::DisposalMethod disposalMethod;
- ImageFrame::AlphaBlendSource alphaBlendSource;
- unsigned duration;
- bool hasAlpha;
- } frameParameters[] = {
- { 4, 10, 33, 32, ImageFrame::DisposeOverwriteBgcolor, ImageFrame::BlendAtopPreviousFrame, 1000u, true },
- { 34, 30, 33, 32, ImageFrame::DisposeOverwriteBgcolor, ImageFrame::BlendAtopPreviousFrame, 1000u, true },
- { 62, 50, 32, 32, ImageFrame::DisposeOverwriteBgcolor, ImageFrame::BlendAtopPreviousFrame, 1000u, true },
- { 10, 54, 32, 33, ImageFrame::DisposeOverwriteBgcolor, ImageFrame::BlendAtopPreviousFrame, 1000u, true },
- };
-
- for (size_t i = 0; i < ARRAY_SIZE(frameParameters); ++i) {
- const ImageFrame* const frame = decoder->frameBufferAtIndex(i);
- EXPECT_EQ(ImageFrame::FrameComplete, frame->status());
- EXPECT_EQ(canvasWidth, frame->getSkBitmap().width());
- EXPECT_EQ(canvasHeight, frame->getSkBitmap().height());
- EXPECT_EQ(frameParameters[i].xOffset, frame->originalFrameRect().x());
- EXPECT_EQ(frameParameters[i].yOffset, frame->originalFrameRect().y());
- EXPECT_EQ(frameParameters[i].width, frame->originalFrameRect().width());
- EXPECT_EQ(frameParameters[i].height, frame->originalFrameRect().height());
- EXPECT_EQ(frameParameters[i].disposalMethod, frame->disposalMethod());
- EXPECT_EQ(frameParameters[i].alphaBlendSource, frame->alphaBlendSource());
- EXPECT_EQ(frameParameters[i].duration, frame->duration());
- EXPECT_EQ(frameParameters[i].hasAlpha, frame->hasAlpha());
- }
-
- EXPECT_EQ(ARRAY_SIZE(frameParameters), decoder->frameCount());
- EXPECT_EQ(cAnimationLoopInfinite, decoder->repetitionCount());
-}
-
-TEST_F(AnimatedWebPTests, verifyAnimationParametersBlendOverwrite)
-{
- OwnPtr<WEBPImageDecoder> decoder = createDecoder();
- EXPECT_EQ(cAnimationLoopOnce, decoder->repetitionCount());
-
- RefPtr<SharedBuffer> data = readFile("/LayoutTests/fast/images/resources/webp-animated-no-blend.webp");
- ASSERT_TRUE(data.get());
- decoder->setData(data.get(), true);
-
- const int canvasWidth = 94;
- const int canvasHeight = 87;
- const struct AnimParam {
- int xOffset, yOffset, width, height;
- ImageFrame::DisposalMethod disposalMethod;
- ImageFrame::AlphaBlendSource alphaBlendSource;
- unsigned duration;
- bool hasAlpha;
- } frameParameters[] = {
- { 4, 10, 33, 32, ImageFrame::DisposeOverwriteBgcolor, ImageFrame::BlendAtopBgcolor, 1000u, true },
- { 34, 30, 33, 32, ImageFrame::DisposeOverwriteBgcolor, ImageFrame::BlendAtopBgcolor, 1000u, true },
- { 62, 50, 32, 32, ImageFrame::DisposeOverwriteBgcolor, ImageFrame::BlendAtopBgcolor, 1000u, true },
- { 10, 54, 32, 33, ImageFrame::DisposeOverwriteBgcolor, ImageFrame::BlendAtopBgcolor, 1000u, true },
- };
-
- for (size_t i = 0; i < ARRAY_SIZE(frameParameters); ++i) {
- const ImageFrame* const frame = decoder->frameBufferAtIndex(i);
- EXPECT_EQ(ImageFrame::FrameComplete, frame->status());
- EXPECT_EQ(canvasWidth, frame->getSkBitmap().width());
- EXPECT_EQ(canvasHeight, frame->getSkBitmap().height());
- EXPECT_EQ(frameParameters[i].xOffset, frame->originalFrameRect().x());
- EXPECT_EQ(frameParameters[i].yOffset, frame->originalFrameRect().y());
- EXPECT_EQ(frameParameters[i].width, frame->originalFrameRect().width());
- EXPECT_EQ(frameParameters[i].height, frame->originalFrameRect().height());
- EXPECT_EQ(frameParameters[i].disposalMethod, frame->disposalMethod());
- EXPECT_EQ(frameParameters[i].alphaBlendSource, frame->alphaBlendSource());
- EXPECT_EQ(frameParameters[i].duration, frame->duration());
- EXPECT_EQ(frameParameters[i].hasAlpha, frame->hasAlpha());
- }
-
- EXPECT_EQ(ARRAY_SIZE(frameParameters), decoder->frameCount());
- EXPECT_EQ(cAnimationLoopInfinite, decoder->repetitionCount());
-}
-
-TEST_F(AnimatedWebPTests, parseAndDecodeByteByByte)
-{
- const struct TestImage {
- const char* filename;
- unsigned frameCount;
- int repetitionCount;
- } testImages[] = {
- { "/LayoutTests/fast/images/resources/webp-animated.webp", 3u, cAnimationLoopInfinite },
- { "/LayoutTests/fast/images/resources/webp-animated-icc-xmp.webp", 13u, 32000 },
- };
-
- for (size_t i = 0; i < ARRAY_SIZE(testImages); ++i) {
- OwnPtr<WEBPImageDecoder> decoder = createDecoder();
- RefPtr<SharedBuffer> data = readFile(testImages[i].filename);
- ASSERT_TRUE(data.get());
-
- size_t frameCount = 0;
- size_t framesDecoded = 0;
-
- // Pass data to decoder byte by byte.
- for (size_t length = 1; length <= data->size(); ++length) {
- RefPtr<SharedBuffer> tempData = SharedBuffer::create(data->data(), length);
- decoder->setData(tempData.get(), length == data->size());
-
- EXPECT_LE(frameCount, decoder->frameCount());
- frameCount = decoder->frameCount();
-
- ImageFrame* frame = decoder->frameBufferAtIndex(frameCount - 1);
- if (frame && frame->status() == ImageFrame::FrameComplete && framesDecoded < frameCount)
- ++framesDecoded;
- }
-
- EXPECT_EQ(testImages[i].frameCount, decoder->frameCount());
- EXPECT_EQ(testImages[i].frameCount, framesDecoded);
- EXPECT_EQ(testImages[i].repetitionCount, decoder->repetitionCount());
- }
-}
-
-TEST_F(AnimatedWebPTests, invalidImage)
-{
- OwnPtr<WEBPImageDecoder> decoder = createDecoder();
-
- RefPtr<SharedBuffer> data = readFile("/LayoutTests/fast/images/resources/invalid-animated-webp.webp");
- ASSERT_TRUE(data.get());
- decoder->setData(data.get(), true);
-
- EXPECT_EQ(0u, decoder->frameCount());
- ImageFrame* frame = decoder->frameBufferAtIndex(0);
- EXPECT_FALSE(frame);
- EXPECT_EQ(cAnimationLoopOnce, decoder->repetitionCount());
-}
-
-TEST_F(AnimatedWebPTests, progressiveDecode)
-{
- RefPtr<SharedBuffer> fullData = readFile("/LayoutTests/fast/images/resources/webp-animated.webp");
- ASSERT_TRUE(fullData.get());
- const size_t fullLength = fullData->size();
-
- OwnPtr<WEBPImageDecoder> decoder;
- ImageFrame* frame;
-
- Vector<unsigned> truncatedHashes;
- Vector<unsigned> progressiveHashes;
-
- // Compute hashes when the file is truncated.
- const size_t increment = 1;
- for (size_t i = 1; i <= fullLength; i += increment) {
- decoder = createDecoder();
- RefPtr<SharedBuffer> data = SharedBuffer::create(fullData->data(), i);
- decoder->setData(data.get(), i == fullLength);
- frame = decoder->frameBufferAtIndex(0);
- if (!frame) {
- truncatedHashes.append(0);
- continue;
- }
- truncatedHashes.append(hashSkBitmap(frame->getSkBitmap()));
- }
-
- // Compute hashes when the file is progressively decoded.
- decoder = createDecoder();
- for (size_t i = 1; i <= fullLength; i += increment) {
- RefPtr<SharedBuffer> data = SharedBuffer::create(fullData->data(), i);
- decoder->setData(data.get(), i == fullLength);
- frame = decoder->frameBufferAtIndex(0);
- if (!frame) {
- progressiveHashes.append(0);
- continue;
- }
- progressiveHashes.append(hashSkBitmap(frame->getSkBitmap()));
- }
-
- bool match = true;
- for (size_t i = 0; i < truncatedHashes.size(); ++i) {
- if (truncatedHashes[i] != progressiveHashes[i]) {
- match = false;
- break;
- }
- }
- EXPECT_TRUE(match);
-}
-
-TEST_F(AnimatedWebPTests, frameIsCompleteAndDuration)
-{
- OwnPtr<WEBPImageDecoder> decoder = createDecoder();
-
- RefPtr<SharedBuffer> data = readFile("/LayoutTests/fast/images/resources/webp-animated.webp");
- ASSERT_TRUE(data.get());
-
- ASSERT_GE(data->size(), 10u);
- RefPtr<SharedBuffer> tempData = SharedBuffer::create(data->data(), data->size() - 10);
- decoder->setData(tempData.get(), false);
-
- EXPECT_EQ(2u, decoder->frameCount());
- EXPECT_FALSE(decoder->failed());
- EXPECT_TRUE(decoder->frameIsCompleteAtIndex(0));
- EXPECT_EQ(1000, decoder->frameDurationAtIndex(0));
- EXPECT_TRUE(decoder->frameIsCompleteAtIndex(1));
- EXPECT_EQ(500, decoder->frameDurationAtIndex(1));
-
- decoder->setData(data.get(), true);
- EXPECT_EQ(3u, decoder->frameCount());
- EXPECT_TRUE(decoder->frameIsCompleteAtIndex(0));
- EXPECT_EQ(1000, decoder->frameDurationAtIndex(0));
- EXPECT_TRUE(decoder->frameIsCompleteAtIndex(1));
- EXPECT_EQ(500, decoder->frameDurationAtIndex(1));
- EXPECT_TRUE(decoder->frameIsCompleteAtIndex(2));
- EXPECT_EQ(1000.0, decoder->frameDurationAtIndex(2));
-}
-
-TEST_F(AnimatedWebPTests, updateRequiredPreviousFrameAfterFirstDecode)
-{
- OwnPtr<WEBPImageDecoder> decoder = createDecoder();
-
- RefPtr<SharedBuffer> fullData = readFile("/LayoutTests/fast/images/resources/webp-animated.webp");
- ASSERT_TRUE(fullData.get());
-
- // Give it data that is enough to parse but not decode in order to check the status
- // of requiredPreviousFrameIndex before decoding.
- size_t partialSize = 1;
- do {
- RefPtr<SharedBuffer> data = SharedBuffer::create(fullData->data(), partialSize);
- decoder->setData(data.get(), false);
- ++partialSize;
- } while (!decoder->frameCount() || decoder->frameBufferAtIndex(0)->status() == ImageFrame::FrameEmpty);
-
- EXPECT_EQ(kNotFound, decoder->frameBufferAtIndex(0)->requiredPreviousFrameIndex());
- unsigned frameCount = decoder->frameCount();
- for (size_t i = 1; i < frameCount; ++i)
- EXPECT_EQ(i - 1, decoder->frameBufferAtIndex(i)->requiredPreviousFrameIndex());
-
- decoder->setData(fullData.get(), true);
- for (size_t i = 0; i < frameCount; ++i)
- EXPECT_EQ(kNotFound, decoder->frameBufferAtIndex(i)->requiredPreviousFrameIndex());
-}
-
-TEST_F(AnimatedWebPTests, randomFrameDecode)
-{
- testRandomFrameDecode("/LayoutTests/fast/images/resources/webp-animated.webp");
- testRandomFrameDecode("/LayoutTests/fast/images/resources/webp-animated-opaque.webp");
- testRandomFrameDecode("/LayoutTests/fast/images/resources/webp-animated-large.webp");
- testRandomFrameDecode("/LayoutTests/fast/images/resources/webp-animated-icc-xmp.webp");
-}
-
-TEST_F(AnimatedWebPTests, randomDecodeAfterClearFrameBufferCache)
-{
- testRandomDecodeAfterClearFrameBufferCache("/LayoutTests/fast/images/resources/webp-animated.webp");
- testRandomDecodeAfterClearFrameBufferCache("/LayoutTests/fast/images/resources/webp-animated-opaque.webp");
- testRandomDecodeAfterClearFrameBufferCache("/LayoutTests/fast/images/resources/webp-animated-large.webp");
- testRandomDecodeAfterClearFrameBufferCache("/LayoutTests/fast/images/resources/webp-animated-icc-xmp.webp");
-}
-
-TEST_F(AnimatedWebPTests, resumePartialDecodeAfterClearFrameBufferCache)
-{
- RefPtr<SharedBuffer> fullData = readFile("/LayoutTests/fast/images/resources/webp-animated-large.webp");
- ASSERT_TRUE(fullData.get());
- Vector<unsigned> baselineHashes;
- createDecodingBaseline(fullData.get(), &baselineHashes);
- size_t frameCount = baselineHashes.size();
-
- OwnPtr<WEBPImageDecoder> decoder = createDecoder();
-
- // Let frame 0 be partially decoded.
- size_t partialSize = 1;
- do {
- RefPtr<SharedBuffer> data = SharedBuffer::create(fullData->data(), partialSize);
- decoder->setData(data.get(), false);
- ++partialSize;
- } while (!decoder->frameCount() || decoder->frameBufferAtIndex(0)->status() == ImageFrame::FrameEmpty);
-
- // Skip to the last frame and clear.
- decoder->setData(fullData.get(), true);
- EXPECT_EQ(frameCount, decoder->frameCount());
- ImageFrame* lastFrame = decoder->frameBufferAtIndex(frameCount - 1);
- EXPECT_EQ(baselineHashes[frameCount - 1], hashSkBitmap(lastFrame->getSkBitmap()));
- decoder->clearCacheExceptFrame(kNotFound);
-
- // Resume decoding of the first frame.
- ImageFrame* firstFrame = decoder->frameBufferAtIndex(0);
- EXPECT_EQ(ImageFrame::FrameComplete, firstFrame->status());
- EXPECT_EQ(baselineHashes[0], hashSkBitmap(firstFrame->getSkBitmap()));
-}
-
-TEST_F(AnimatedWebPTests, decodeAfterReallocatingData)
-{
- testDecodeAfterReallocatingData("/LayoutTests/fast/images/resources/webp-animated.webp");
- testDecodeAfterReallocatingData("/LayoutTests/fast/images/resources/webp-animated-icc-xmp.webp");
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/image-encoders/skia/JPEGImageEncoder.cpp b/chromium/third_party/WebKit/Source/core/platform/image-encoders/skia/JPEGImageEncoder.cpp
deleted file mode 100644
index f19c5c14222..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/image-encoders/skia/JPEGImageEncoder.cpp
+++ /dev/null
@@ -1,202 +0,0 @@
-/*
- * Copyright (c) 2010, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/image-encoders/skia/JPEGImageEncoder.h"
-
-#include "SkBitmap.h"
-#include "SkColorPriv.h"
-#include "core/html/ImageData.h"
-#include "core/platform/graphics/IntSize.h"
-extern "C" {
-#include <setjmp.h>
-#include <stdio.h> // jpeglib.h needs stdio.h FILE
-#include "jpeglib.h"
-}
-
-namespace WebCore {
-
-struct JPEGOutputBuffer : public jpeg_destination_mgr {
- Vector<unsigned char>* output;
- Vector<unsigned char> buffer;
-};
-
-static void prepareOutput(j_compress_ptr cinfo)
-{
- JPEGOutputBuffer* out = static_cast<JPEGOutputBuffer*>(cinfo->dest);
- const size_t internalBufferSize = 8192;
- out->buffer.resize(internalBufferSize);
- out->next_output_byte = out->buffer.data();
- out->free_in_buffer = out->buffer.size();
-}
-
-static boolean writeOutput(j_compress_ptr cinfo)
-{
- JPEGOutputBuffer* out = static_cast<JPEGOutputBuffer*>(cinfo->dest);
- out->output->append(out->buffer.data(), out->buffer.size());
- out->next_output_byte = out->buffer.data();
- out->free_in_buffer = out->buffer.size();
- return TRUE;
-}
-
-static void finishOutput(j_compress_ptr cinfo)
-{
- JPEGOutputBuffer* out = static_cast<JPEGOutputBuffer*>(cinfo->dest);
- const size_t size = out->buffer.size() - out->free_in_buffer;
- out->output->append(out->buffer.data(), size);
-}
-
-static void handleError(j_common_ptr common)
-{
- jmp_buf* jumpBufferPtr = static_cast<jmp_buf*>(common->client_data);
- longjmp(*jumpBufferPtr, -1);
-}
-
-static void preMultipliedBGRAtoRGB(const unsigned char* pixels, unsigned int pixelCount, unsigned char* output)
-{
- const SkPMColor* input = reinterpret_cast_ptr<const SkPMColor*>(pixels);
- for (; pixelCount-- > 0; ++input) {
- *output++ = SkGetPackedR32(*input);
- *output++ = SkGetPackedG32(*input);
- *output++ = SkGetPackedB32(*input);
- }
-}
-
-static void RGBAtoRGB(const unsigned char* pixels, unsigned int pixelCount, unsigned char* output)
-{
- for (; pixelCount-- > 0; pixels += 4) {
- // Do source-over composition on black.
- unsigned char alpha = pixels[3];
- if (alpha != 255) {
- *output++ = SkMulDiv255Round(pixels[0], alpha);
- *output++ = SkMulDiv255Round(pixels[1], alpha);
- *output++ = SkMulDiv255Round(pixels[2], alpha);
- } else {
- *output++ = pixels[0];
- *output++ = pixels[1];
- *output++ = pixels[2];
- }
- }
-}
-
-static bool encodePixels(IntSize imageSize, unsigned char* inputPixels, bool premultiplied, int quality, Vector<unsigned char>* output)
-{
- JPEGOutputBuffer destination;
- destination.output = output;
- Vector<JSAMPLE> row;
-
- jpeg_compress_struct cinfo;
- jpeg_error_mgr error;
- cinfo.err = jpeg_std_error(&error);
- error.error_exit = handleError;
- jmp_buf jumpBuffer;
- cinfo.client_data = &jumpBuffer;
-
- if (setjmp(jumpBuffer)) {
- jpeg_destroy_compress(&cinfo);
- return false;
- }
-
- jpeg_create_compress(&cinfo);
- cinfo.dest = &destination;
- cinfo.dest->init_destination = prepareOutput;
- cinfo.dest->empty_output_buffer = writeOutput;
- cinfo.dest->term_destination = finishOutput;
-
- imageSize.clampNegativeToZero();
- cinfo.image_height = imageSize.height();
- cinfo.image_width = imageSize.width();
-
-#if defined(JCS_EXTENSIONS)
- if (premultiplied) {
- cinfo.in_color_space = SK_B32_SHIFT ? JCS_EXT_RGBX : JCS_EXT_BGRX;
-
- cinfo.input_components = 4;
-
- jpeg_set_defaults(&cinfo);
- jpeg_set_quality(&cinfo, quality, TRUE);
- jpeg_start_compress(&cinfo, TRUE);
-
- unsigned char* pixels = inputPixels;
- const size_t pixelRowStride = cinfo.image_width * 4;
- while (cinfo.next_scanline < cinfo.image_height) {
- jpeg_write_scanlines(&cinfo, &pixels, 1);
- pixels += pixelRowStride;
- }
-
- jpeg_finish_compress(&cinfo);
- jpeg_destroy_compress(&cinfo);
- return true;
- }
-#endif
-
- cinfo.in_color_space = JCS_RGB;
- cinfo.input_components = 3;
-
- void (*extractRowRGB)(const unsigned char*, unsigned int, unsigned char* output);
- extractRowRGB = &RGBAtoRGB;
- if (premultiplied)
- extractRowRGB = &preMultipliedBGRAtoRGB;
-
- jpeg_set_defaults(&cinfo);
- jpeg_set_quality(&cinfo, quality, TRUE);
- jpeg_start_compress(&cinfo, TRUE);
-
- unsigned char* pixels = inputPixels;
- row.resize(cinfo.image_width * cinfo.input_components);
- const size_t pixelRowStride = cinfo.image_width * 4;
- while (cinfo.next_scanline < cinfo.image_height) {
- JSAMPLE* rowData = row.data();
- extractRowRGB(pixels, cinfo.image_width, rowData);
- jpeg_write_scanlines(&cinfo, &rowData, 1);
- pixels += pixelRowStride;
- }
-
- jpeg_finish_compress(&cinfo);
- jpeg_destroy_compress(&cinfo);
- return true;
-}
-
-bool JPEGImageEncoder::encode(const SkBitmap& bitmap, int quality, Vector<unsigned char>* output)
-{
- SkAutoLockPixels bitmapLock(bitmap);
-
- if (bitmap.config() != SkBitmap::kARGB_8888_Config || !bitmap.getPixels())
- return false; // Only support 32 bit/pixel skia bitmaps.
-
- return encodePixels(IntSize(bitmap.width(), bitmap.height()), static_cast<unsigned char *>(bitmap.getPixels()), true, quality, output);
-}
-
-bool JPEGImageEncoder::encode(const ImageData& imageData, int quality, Vector<unsigned char>* output)
-{
- return encodePixels(imageData.size(), imageData.data()->data(), false, quality, output);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/image-encoders/skia/JPEGImageEncoder.h b/chromium/third_party/WebKit/Source/core/platform/image-encoders/skia/JPEGImageEncoder.h
deleted file mode 100644
index ca3ef4886ea..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/image-encoders/skia/JPEGImageEncoder.h
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright (c) 2010, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef JPEGImageEncoder_h
-#define JPEGImageEncoder_h
-
-#include "wtf/Vector.h"
-
-class SkBitmap;
-
-namespace WebCore {
-
-class ImageData;
-
-class JPEGImageEncoder {
-public:
- // Encode the input data with a compression quality in [0-100].
- static bool encode(const SkBitmap&, int quality, Vector<unsigned char>*);
- static bool encode(const ImageData&, int quality, Vector<unsigned char>*);
-
- // For callers: provide a reasonable compression quality default.
- enum Quality { DefaultCompressionQuality = 92 };
-};
-
-} // namespace WebCore
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/image-encoders/skia/PNGImageEncoder.cpp b/chromium/third_party/WebKit/Source/core/platform/image-encoders/skia/PNGImageEncoder.cpp
deleted file mode 100644
index 31e13221c8b..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/image-encoders/skia/PNGImageEncoder.cpp
+++ /dev/null
@@ -1,132 +0,0 @@
-/*
- * Copyright (c) 2010, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/image-encoders/skia/PNGImageEncoder.h"
-
-#include "SkBitmap.h"
-#include "SkColorPriv.h"
-#include "SkUnPreMultiply.h"
-#include "core/html/ImageData.h"
-#include "core/platform/graphics/IntSize.h"
-extern "C" {
-#include "png.h"
-}
-
-namespace WebCore {
-
-static void writeOutput(png_structp png, png_bytep data, png_size_t size)
-{
- static_cast<Vector<unsigned char>*>(png_get_io_ptr(png))->append(data, size);
-}
-
-static void preMultipliedBGRAtoRGBA(const void* pixels, int pixelCount, unsigned char* output)
-{
- static const SkUnPreMultiply::Scale* scale = SkUnPreMultiply::GetScaleTable();
- const SkPMColor* input = static_cast<const SkPMColor*>(pixels);
-
- for (; pixelCount-- > 0; ++input) {
- const unsigned alpha = SkGetPackedA32(*input);
- if ((alpha != 0) && (alpha != 255)) {
- *output++ = SkUnPreMultiply::ApplyScale(scale[alpha], SkGetPackedR32(*input));
- *output++ = SkUnPreMultiply::ApplyScale(scale[alpha], SkGetPackedG32(*input));
- *output++ = SkUnPreMultiply::ApplyScale(scale[alpha], SkGetPackedB32(*input));
- *output++ = alpha;
- } else {
- *output++ = SkGetPackedR32(*input);
- *output++ = SkGetPackedG32(*input);
- *output++ = SkGetPackedB32(*input);
- *output++ = alpha;
- }
- }
-}
-
-static bool encodePixels(IntSize imageSize, unsigned char* inputPixels, bool premultiplied, Vector<unsigned char>* output)
-{
- imageSize.clampNegativeToZero();
- Vector<unsigned char> row;
-
- png_struct* png = png_create_write_struct(PNG_LIBPNG_VER_STRING, 0, 0, 0);
- png_info* info = png_create_info_struct(png);
- if (!png || !info || setjmp(png_jmpbuf(png))) {
- png_destroy_write_struct(png ? &png : 0, info ? &info : 0);
- return false;
- }
-
- // Optimize compression for speed.
- // The parameters are the same as what libpng uses by default for RGB and RGBA images, except:
- // - the zlib compression level is 3 instead of 6, to avoid the lazy Ziv-Lempel match searching;
- // - the delta filter is 1 ("sub") instead of 5 ("all"), to reduce the filter computations.
- // The zlib memory level (8) and strategy (Z_FILTERED) will be set inside libpng.
- //
- // Avoid the zlib strategies Z_HUFFMAN_ONLY or Z_RLE.
- // Although they are the fastest for poorly-compressible images (e.g. photographs),
- // they are very slow for highly-compressible images (e.g. text, drawings or business graphics).
- png_set_compression_level(png, 3);
- png_set_filter(png, PNG_FILTER_TYPE_BASE, PNG_FILTER_SUB);
-
- png_set_write_fn(png, output, writeOutput, 0);
- png_set_IHDR(png, info, imageSize.width(), imageSize.height(),
- 8, PNG_COLOR_TYPE_RGB_ALPHA, 0, 0, 0);
- png_write_info(png, info);
-
- unsigned char* pixels = inputPixels;
- row.resize(imageSize.width() * sizeof(SkPMColor));
- const size_t pixelRowStride = imageSize.width() * 4;
- for (int y = 0; y < imageSize.height(); ++y) {
- if (premultiplied) {
- preMultipliedBGRAtoRGBA(pixels, imageSize.width(), row.data());
- png_write_row(png, row.data());
- } else
- png_write_row(png, pixels);
- pixels += pixelRowStride;
- }
-
- png_write_end(png, info);
- png_destroy_write_struct(&png, &info);
- return true;
-}
-
-bool PNGImageEncoder::encode(const SkBitmap& bitmap, Vector<unsigned char>* output)
-{
- SkAutoLockPixels bitmapLock(bitmap);
-
- if (bitmap.config() != SkBitmap::kARGB_8888_Config || !bitmap.getPixels())
- return false; // Only support 32 bit/pixel skia bitmaps.
-
- return encodePixels(IntSize(bitmap.width(), bitmap.height()), static_cast<unsigned char*>(bitmap.getPixels()), true, output);
-}
-
-bool PNGImageEncoder::encode(const ImageData& imageData, Vector<unsigned char>* output)
-{
- return encodePixels(imageData.size(), imageData.data()->data(), false, output);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/image-encoders/skia/PNGImageEncoder.h b/chromium/third_party/WebKit/Source/core/platform/image-encoders/skia/PNGImageEncoder.h
deleted file mode 100644
index a8f0ea53d0e..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/image-encoders/skia/PNGImageEncoder.h
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Copyright (c) 2010, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef PNGImageEncoder_h
-#define PNGImageEncoder_h
-
-#include "wtf/Vector.h"
-
-class SkBitmap;
-
-namespace WebCore {
-
-class ImageData;
-
-// Interface for encoding PNG data. This is a wrapper around libpng.
-class PNGImageEncoder {
-public:
- static bool encode(const SkBitmap&, Vector<unsigned char>* output);
- static bool encode(const ImageData&, Vector<unsigned char>* output);
-};
-
-} // namespace WebCore
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/image-encoders/skia/WEBPImageEncoder.cpp b/chromium/third_party/WebKit/Source/core/platform/image-encoders/skia/WEBPImageEncoder.cpp
deleted file mode 100644
index 78cb5aad90e..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/image-encoders/skia/WEBPImageEncoder.cpp
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
- * Copyright (c) 2011, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/image-encoders/skia/WEBPImageEncoder.h"
-
-#include "SkBitmap.h"
-#include "core/html/ImageData.h"
-#include "core/platform/graphics/IntSize.h"
-#include "webp/encode.h"
-
-typedef int (*WebPImporter)(WebPPicture* const, const uint8_t* const data, int rowStride);
-
-namespace WebCore {
-
-static int writeOutput(const uint8_t* data, size_t size, const WebPPicture* const picture)
-{
- static_cast<Vector<unsigned char>*>(picture->custom_ptr)->append(data, size);
- return 1;
-}
-
-static bool rgbPictureImport(const unsigned char* pixels, bool premultiplied, WebPImporter importRGBX, WebPImporter importRGB, WebPPicture* picture)
-{
- if (premultiplied)
- return importRGBX(picture, pixels, picture->width * 4);
-
- // Write the RGB pixels to an rgb data buffer, alpha premultiplied, then import the rgb data.
-
- Vector<unsigned char> rgb;
- size_t pixelCount = picture->height * picture->width;
- rgb.reserveInitialCapacity(pixelCount * 3);
-
- for (unsigned char* data = rgb.data(); pixelCount-- > 0; pixels += 4) {
- unsigned char alpha = pixels[3];
- if (alpha != 255) {
- *data++ = SkMulDiv255Round(pixels[0], alpha);
- *data++ = SkMulDiv255Round(pixels[1], alpha);
- *data++ = SkMulDiv255Round(pixels[2], alpha);
- } else {
- *data++ = pixels[0];
- *data++ = pixels[1];
- *data++ = pixels[2];
- }
- }
-
- return importRGB(picture, rgb.data(), picture->width * 3);
-}
-
-template <bool Premultiplied> inline bool importPictureBGRX(const unsigned char* pixels, WebPPicture* picture)
-{
- return rgbPictureImport(pixels, Premultiplied, &WebPPictureImportBGRX, &WebPPictureImportBGR, picture);
-}
-
-template <bool Premultiplied> inline bool importPictureRGBX(const unsigned char* pixels, WebPPicture* picture)
-{
- return rgbPictureImport(pixels, Premultiplied, &WebPPictureImportRGBX, &WebPPictureImportRGB, picture);
-}
-
-static bool encodePixels(IntSize imageSize, const unsigned char* pixels, bool premultiplied, int quality, Vector<unsigned char>* output)
-{
- WebPConfig config;
- if (!WebPConfigInit(&config))
- return false;
- WebPPicture picture;
- if (!WebPPictureInit(&picture))
- return false;
-
- imageSize.clampNegativeToZero();
- if (!imageSize.width() || imageSize.width() > WEBP_MAX_DIMENSION)
- return false;
- picture.width = imageSize.width();
- if (!imageSize.height() || imageSize.height() > WEBP_MAX_DIMENSION)
- return false;
- picture.height = imageSize.height();
-
- if (premultiplied && !importPictureBGRX<true>(pixels, &picture))
- return false;
- if (!premultiplied && !importPictureRGBX<false>(pixels, &picture))
- return false;
-
- picture.custom_ptr = output;
- picture.writer = &writeOutput;
- config.quality = quality;
- config.method = 3;
-
- bool success = WebPEncode(&config, &picture);
- WebPPictureFree(&picture);
- return success;
-}
-
-bool WEBPImageEncoder::encode(const SkBitmap& bitmap, int quality, Vector<unsigned char>* output)
-{
- SkAutoLockPixels bitmapLock(bitmap);
-
- if (bitmap.config() != SkBitmap::kARGB_8888_Config || !bitmap.getPixels())
- return false; // Only support 32 bit/pixel skia bitmaps.
-
- return encodePixels(IntSize(bitmap.width(), bitmap.height()), static_cast<unsigned char *>(bitmap.getPixels()), true, quality, output);
-}
-
-bool WEBPImageEncoder::encode(const ImageData& imageData, int quality, Vector<unsigned char>* output)
-{
- return encodePixels(imageData.size(), imageData.data()->data(), false, quality, output);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/image-encoders/skia/WEBPImageEncoder.h b/chromium/third_party/WebKit/Source/core/platform/image-encoders/skia/WEBPImageEncoder.h
deleted file mode 100644
index e04c7023082..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/image-encoders/skia/WEBPImageEncoder.h
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright (c) 2011, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef WEBPImageEncoder_h
-#define WEBPImageEncoder_h
-
-#include "wtf/Vector.h"
-
-class SkBitmap;
-
-namespace WebCore {
-
-class ImageData;
-
-class WEBPImageEncoder {
-public:
- // Encode the input data with a compression quality in [0-100].
- static bool encode(const SkBitmap&, int quality, Vector<unsigned char>*);
- static bool encode(const ImageData&, int quality, Vector<unsigned char>*);
-
- // For callers: provide a reasonable compression quality default.
- enum Quality { DefaultCompressionQuality = 80 };
-};
-
-} // namespace WebCore
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/mac/BlockExceptions.h b/chromium/third_party/WebKit/Source/core/platform/mac/BlockExceptions.h
deleted file mode 100644
index 3968a55cb04..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/mac/BlockExceptions.h
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Copyright (C) 2003 Apple Computer, Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#import <Foundation/NSException.h>
-#import <wtf/Assertions.h>
-
-NO_RETURN_DUE_TO_ASSERT void ReportBlockedObjCException(NSException *);
-
-#define BEGIN_BLOCK_OBJC_EXCEPTIONS @try {
-#define END_BLOCK_OBJC_EXCEPTIONS } @catch(NSException *localException) { ReportBlockedObjCException(localException); }
-
diff --git a/chromium/third_party/WebKit/Source/core/platform/mac/BlockExceptions.mm b/chromium/third_party/WebKit/Source/core/platform/mac/BlockExceptions.mm
deleted file mode 100644
index 66dca3f4628..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/mac/BlockExceptions.mm
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright (C) 2003, 2007 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#import "config.h"
-#import "core/platform/mac/BlockExceptions.h"
-
-#import <wtf/Assertions.h>
-
-void ReportBlockedObjCException(NSException *exception)
-{
-#if ASSERT_DISABLED
- NSLog(@"*** WebKit discarding exception: <%@> %@", [exception name], [exception reason]);
-#else
- ASSERT_WITH_MESSAGE(0, "Uncaught exception - %@", exception);
-#endif
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/mac/EmptyProtocolDefinitions.h b/chromium/third_party/WebKit/Source/core/platform/mac/EmptyProtocolDefinitions.h
deleted file mode 100644
index 46e265b8599..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/mac/EmptyProtocolDefinitions.h
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright (C) 2008, 2010 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#if defined(__OBJC__)
-
-#import <AvailabilityMacros.h>
-
-#define EMPTY_PROTOCOL(NAME) \
-@protocol NAME <NSObject> \
-@end
-
-#if __MAC_OS_X_VERSION_MAX_ALLOWED == 1060
-
-EMPTY_PROTOCOL(NSURLConnectionDelegate)
-EMPTY_PROTOCOL(NSURLDownloadDelegate)
-
-#endif
-
-#undef EMPTY_PROTOCOL
-
-#endif /* defined(__OBJC__) */
diff --git a/chromium/third_party/WebKit/Source/core/platform/mac/FoundationExtras.h b/chromium/third_party/WebKit/Source/core/platform/mac/FoundationExtras.h
deleted file mode 100644
index 39b12ea9e01..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/mac/FoundationExtras.h
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright (C) 2004 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#import <CoreFoundation/CFBase.h>
-#import <Foundation/NSObject.h>
-
-// Use HardAutorelease to return an object made by a CoreFoundation
-// "create" or "copy" function as an autoreleased and garbage collected
-// object. CF objects need to be "made collectable" for autorelease to work
-// properly under GC.
-
-static inline id HardAutorelease(CFTypeRef object)
-{
- if (object)
- CFMakeCollectable(object);
- [(id)object autorelease];
- return (id)object;
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/mac/KillRingMac.mm b/chromium/third_party/WebKit/Source/core/platform/mac/KillRingMac.mm
deleted file mode 100644
index 6213569d1ec..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/mac/KillRingMac.mm
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#import "config.h"
-#import "core/platform/KillRing.h"
-
-namespace WebCore {
-
-extern "C" {
-
-// Kill ring calls. Would be better to use NSKillRing.h, but that's not available as API or SPI.
-
-void _NSInitializeKillRing();
-void _NSAppendToKillRing(NSString *);
-void _NSPrependToKillRing(NSString *);
-NSString *_NSYankFromKillRing();
-void _NSNewKillRingSequence();
-void _NSSetKillRingToYankedState();
-
-}
-
-static void initializeKillRingIfNeeded()
-{
- static bool initializedKillRing = false;
- if (!initializedKillRing) {
- initializedKillRing = true;
- _NSInitializeKillRing();
- }
-}
-
-void KillRing::append(const String& string)
-{
- initializeKillRingIfNeeded();
- _NSAppendToKillRing(string);
-}
-
-void KillRing::prepend(const String& string)
-{
- initializeKillRingIfNeeded();
- _NSPrependToKillRing(string);
-}
-
-String KillRing::yank()
-{
- initializeKillRingIfNeeded();
- return _NSYankFromKillRing();
-}
-
-void KillRing::startNewSequence()
-{
- initializeKillRingIfNeeded();
- _NSNewKillRingSequence();
-}
-
-void KillRing::setToYankedState()
-{
- initializeKillRingIfNeeded();
- _NSSetKillRingToYankedState();
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/mac/LocalCurrentGraphicsContext.h b/chromium/third_party/WebKit/Source/core/platform/mac/LocalCurrentGraphicsContext.h
deleted file mode 100644
index 72780e38cff..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/mac/LocalCurrentGraphicsContext.h
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Copyright (C) 2006 Apple Computer, Inc.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "core/platform/graphics/GraphicsContext.h"
-#include "wtf/Noncopyable.h"
-
-#include "skia/ext/skia_utils_mac.h"
-
-OBJC_CLASS NSGraphicsContext;
-
-namespace WebCore {
-
-// This class automatically saves and restores the current NSGraphicsContext for
-// functions which call out into AppKit and rely on the currentContext being set
-class LocalCurrentGraphicsContext {
- WTF_MAKE_NONCOPYABLE(LocalCurrentGraphicsContext);
-public:
- LocalCurrentGraphicsContext(GraphicsContext* graphicsContext);
- ~LocalCurrentGraphicsContext();
- CGContextRef cgContext();
-private:
- GraphicsContext* m_savedGraphicsContext;
- NSGraphicsContext* m_savedNSGraphicsContext;
- bool m_didSetGraphicsContext;
- gfx::SkiaBitLocker m_skiaBitLocker;
-};
-
-class ContextContainer {
- WTF_MAKE_NONCOPYABLE(ContextContainer);
-public:
- ContextContainer(GraphicsContext*);
-
- // This synchronizes the CGContext to reflect the current SkCanvas state.
- // The implementation may not return the same CGContext each time.
- CGContextRef context() { return m_skiaBitLocker.cgContext(); }
-
-private:
- gfx::SkiaBitLocker m_skiaBitLocker;
-};
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/mac/LocalCurrentGraphicsContext.mm b/chromium/third_party/WebKit/Source/core/platform/mac/LocalCurrentGraphicsContext.mm
deleted file mode 100644
index 131386ad09e..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/mac/LocalCurrentGraphicsContext.mm
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Copyright (C) 2006 Apple Computer, Inc.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-#include "core/platform/mac/LocalCurrentGraphicsContext.h"
-
-#include <AppKit/NSGraphicsContext.h>
-#include "core/platform/graphics/GraphicsContext.h"
-#include "platform_canvas.h"
-
-namespace WebCore {
-
-LocalCurrentGraphicsContext::LocalCurrentGraphicsContext(GraphicsContext* graphicsContext)
- : m_didSetGraphicsContext(false)
- , m_skiaBitLocker(graphicsContext->canvas())
-{
- m_savedGraphicsContext = graphicsContext;
- graphicsContext->save();
-
- CGContextRef cgContext = this->cgContext();
- if (cgContext == [[NSGraphicsContext currentContext] graphicsPort]) {
- m_savedNSGraphicsContext = 0;
- return;
- }
-
- m_savedNSGraphicsContext = [[NSGraphicsContext currentContext] retain];
- NSGraphicsContext* newContext = [NSGraphicsContext graphicsContextWithGraphicsPort:cgContext flipped:YES];
- [NSGraphicsContext setCurrentContext:newContext];
- m_didSetGraphicsContext = true;
-}
-
-LocalCurrentGraphicsContext::~LocalCurrentGraphicsContext()
-{
- if (m_didSetGraphicsContext) {
- [NSGraphicsContext setCurrentContext:m_savedNSGraphicsContext];
- [m_savedNSGraphicsContext release];
- }
-
- m_savedGraphicsContext->restore();
-}
-
-CGContextRef LocalCurrentGraphicsContext::cgContext()
-{
- // This synchronizes the CGContext to reflect the current SkCanvas state.
- // The implementation may not return the same CGContext each time.
- CGContextRef cgContext = m_skiaBitLocker.cgContext();
-
- return cgContext;
-}
-
-ContextContainer::ContextContainer(GraphicsContext* graphicsContext)
- : m_skiaBitLocker(graphicsContext->canvas())
-{
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/mac/NSScrollerImpDetails.h b/chromium/third_party/WebKit/Source/core/platform/mac/NSScrollerImpDetails.h
deleted file mode 100644
index bc260f07cdd..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/mac/NSScrollerImpDetails.h
+++ /dev/null
@@ -1,120 +0,0 @@
-/*
- * Copyright (C) 2011 Apple Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef WebCore_NSScrollerImpDetails_h
-#define WebCore_NSScrollerImpDetails_h
-
-#include "config.h"
-#import <AvailabilityMacros.h>
-
-// Public APIs not available on versions of Mac on which we build
-#if __MAC_OS_X_VERSION_MAX_ALLOWED == 1060
-enum {
- NSScrollerStyleLegacy = 0,
- NSScrollerStyleOverlay = 1
-};
-typedef NSInteger NSScrollerStyle;
-
-enum {
- NSScrollerKnobStyleDefault = 0,
- NSScrollerKnobStyleDark = 1,
- NSScrollerKnobStyleLight = 2
-};
-typedef NSInteger NSScrollerKnobStyle;
-#endif
-
-#if __MAC_OS_X_VERSION_MAX_ALLOWED == 1060
-@interface NSScroller(NSObject)
-+ (NSScrollerStyle)preferredScrollerStyle;
-@end
-#endif
-
-@interface NSObject (ScrollbarPainter)
-+ (id)scrollerImpWithStyle:(NSScrollerStyle)newScrollerStyle controlSize:(NSControlSize)newControlSize horizontal:(BOOL)horizontal replacingScrollerImp:(id)previous;
-- (CGFloat)knobAlpha;
-- (void)setKnobAlpha:(CGFloat)knobAlpha;
-- (CGFloat)trackAlpha;
-- (void)setTrackAlpha:(CGFloat)trackAlpha;
-- (void)setEnabled:(BOOL)enabled;
-- (void)setBoundsSize:(NSSize)boundsSize;
-- (void)setDoubleValue:(double)doubleValue;
-- (void)setKnobProportion:(CGFloat)proportion;
-- (void)setKnobStyle:(NSScrollerKnobStyle)knobStyle;
-- (void)setExpanded:(BOOL)expanded;
-- (BOOL)isExpanded;
-- (void)setDelegate:(id)delegate;
-- (void)setUiStateTransitionProgress:(CGFloat)uiStateTransitionProgress;
-- (void)setExpansionTransitionProgress:(CGFloat)expansionTransitionProgress;
-- (BOOL)isHorizontal;
-- (CGFloat)trackWidth;
-- (CGFloat)trackBoxWidth;
-- (CGFloat)knobMinLength;
-- (CGFloat)trackOverlapEndInset;
-- (CGFloat)knobOverlapEndInset;
-- (CGFloat)trackEndInset;
-- (CGFloat)knobEndInset;
-- (CGFloat)uiStateTransitionProgress;
-- (CGFloat)expansionTransitionProgress;
-- (NSRect)rectForPart:(NSScrollerPart)partCode;
-- (void)drawKnobSlotInRect:(NSRect)slotRect highlight:(BOOL)flag alpha:(CGFloat)alpha;
-- (void)drawKnob;
-- (void)mouseEnteredScroller;
-- (void)mouseExitedScroller;
-@end
-
-@interface NSObject (ScrollbarPainterController)
-- (void)setDelegate:(id)delegate;
-- (void)hideOverlayScrollers;
-- (void)flashScrollers;
-- (id)horizontalScrollerImp;
-- (void)setHorizontalScrollerImp:(id)horizontal;
-- (id)verticalScrollerImp;
-- (void)setVerticalScrollerImp:(id)vertical;
-- (NSScrollerStyle)scrollerStyle;
-- (void)setScrollerStyle:(NSScrollerStyle)scrollerStyle;
-- (void)contentAreaScrolled;
-- (void)contentAreaScrolledInDirection:(NSPoint)direction;
-- (void)contentAreaWillDraw;
-- (void)mouseEnteredContentArea;
-- (void)mouseExitedContentArea;
-- (void)mouseMovedInContentArea;
-- (void)startLiveResize;
-- (void)contentAreaDidResize;
-- (void)endLiveResize;
-- (void)windowOrderedIn;
-- (void)windowOrderedOut;
-- (void)beginScrollGesture;
-- (void)endScrollGesture;
-@end
-
-namespace WebCore {
-
-bool isScrollbarOverlayAPIAvailable();
-
-NSScrollerStyle recommendedScrollerStyle();
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/mac/NSScrollerImpDetails.mm b/chromium/third_party/WebKit/Source/core/platform/mac/NSScrollerImpDetails.mm
deleted file mode 100644
index 7556d766eda..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/mac/NSScrollerImpDetails.mm
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Copyright (C) 2011 Apple Inc. All Rights Reserved.
- * Copyright (C) 2011 Google Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-
-#include "config.h"
-#include "RuntimeEnabledFeatures.h"
-#include "core/page/Settings.h"
-#include "core/platform/mac/NSScrollerImpDetails.h"
-
-namespace WebCore {
-
-bool isScrollbarOverlayAPIAvailable()
-{
- static bool apiAvailable;
- static bool shouldInitialize = true;
- if (shouldInitialize) {
- shouldInitialize = false;
- Class scrollerImpClass = NSClassFromString(@"NSScrollerImp");
- Class scrollerImpPairClass = NSClassFromString(@"NSScrollerImpPair");
- apiAvailable = [scrollerImpClass respondsToSelector:@selector(scrollerImpWithStyle:controlSize:horizontal:replacingScrollerImp:)]
- && [scrollerImpPairClass instancesRespondToSelector:@selector(scrollerStyle)];
- }
- return apiAvailable;
-}
-
-NSScrollerStyle recommendedScrollerStyle() {
- if (RuntimeEnabledFeatures::overlayScrollbarsEnabled())
- return NSScrollerStyleOverlay;
- if ([NSScroller respondsToSelector:@selector(preferredScrollerStyle)])
- return [NSScroller preferredScrollerStyle];
- return NSScrollerStyleLegacy;
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/mac/ScrollAnimatorMac.h b/chromium/third_party/WebKit/Source/core/platform/mac/ScrollAnimatorMac.h
deleted file mode 100644
index 4d03966b7ff..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/mac/ScrollAnimatorMac.h
+++ /dev/null
@@ -1,162 +0,0 @@
-/*
- * Copyright (C) 2010, 2011 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ScrollAnimatorMac_h
-#define ScrollAnimatorMac_h
-
-#include "core/platform/ScrollAnimator.h"
-#include "core/platform/Timer.h"
-#include "core/platform/graphics/FloatPoint.h"
-#include "core/platform/graphics/FloatSize.h"
-#include "core/platform/graphics/IntRect.h"
-#include "core/platform/mac/ScrollElasticityController.h"
-#include "wtf/RetainPtr.h"
-
-OBJC_CLASS WebScrollAnimationHelperDelegate;
-OBJC_CLASS WebScrollbarPainterControllerDelegate;
-OBJC_CLASS WebScrollbarPainterDelegate;
-
-typedef id ScrollbarPainterController;
-
-#if !USE(RUBBER_BANDING)
-class ScrollElasticityControllerClient { };
-#endif
-
-namespace WebCore {
-
-class Scrollbar;
-
-class ScrollAnimatorMac : public ScrollAnimator, private ScrollElasticityControllerClient {
-
-public:
- ScrollAnimatorMac(ScrollableArea*);
- virtual ~ScrollAnimatorMac();
-
- void immediateScrollToPointForScrollAnimation(const FloatPoint& newPosition);
- bool haveScrolledSincePageLoad() const { return m_haveScrolledSincePageLoad; }
-
- void updateScrollerStyle();
-
- bool scrollbarPaintTimerIsActive() const;
- void startScrollbarPaintTimer();
- void stopScrollbarPaintTimer();
-
- void sendContentAreaScrolledSoon(const FloatSize& scrollDelta);
-
- void setVisibleScrollerThumbRect(const IntRect&);
-
- static bool canUseCoordinatedScrollbar();
-
-private:
- RetainPtr<id> m_scrollAnimationHelper;
- RetainPtr<WebScrollAnimationHelperDelegate> m_scrollAnimationHelperDelegate;
-
- RetainPtr<ScrollbarPainterController> m_scrollbarPainterController;
- RetainPtr<WebScrollbarPainterControllerDelegate> m_scrollbarPainterControllerDelegate;
- RetainPtr<WebScrollbarPainterDelegate> m_horizontalScrollbarPainterDelegate;
- RetainPtr<WebScrollbarPainterDelegate> m_verticalScrollbarPainterDelegate;
-
- void initialScrollbarPaintTimerFired(Timer<ScrollAnimatorMac>*);
- Timer<ScrollAnimatorMac> m_initialScrollbarPaintTimer;
-
- void sendContentAreaScrolledTimerFired(Timer<ScrollAnimatorMac>*);
- Timer<ScrollAnimatorMac> m_sendContentAreaScrolledTimer;
- FloatSize m_contentAreaScrolledTimerScrollDelta;
-
- virtual bool scroll(ScrollbarOrientation, ScrollGranularity, float step, float multiplier);
- virtual void scrollToOffsetWithoutAnimation(const FloatPoint&);
-
-#if USE(RUBBER_BANDING)
- virtual bool handleWheelEvent(const PlatformWheelEvent&) OVERRIDE;
-#endif
-
- virtual void handleWheelEventPhase(PlatformWheelEventPhase) OVERRIDE;
-
- virtual void cancelAnimations();
- virtual void setIsActive();
-
- virtual void notifyPositionChanged(const FloatSize& delta);
- virtual void contentAreaWillPaint() const;
- virtual void mouseEnteredContentArea() const;
- virtual void mouseExitedContentArea() const;
- virtual void mouseMovedInContentArea() const;
- virtual void mouseEnteredScrollbar(Scrollbar*) const;
- virtual void mouseExitedScrollbar(Scrollbar*) const;
- virtual void willStartLiveResize();
- virtual void contentsResized() const;
- virtual void willEndLiveResize();
- virtual void contentAreaDidShow() const;
- virtual void contentAreaDidHide() const;
- void didBeginScrollGesture() const;
- void didEndScrollGesture() const;
- void mayBeginScrollGesture() const;
-
- virtual void finishCurrentScrollAnimations();
-
- virtual void didAddVerticalScrollbar(Scrollbar*);
- virtual void willRemoveVerticalScrollbar(Scrollbar*);
- virtual void didAddHorizontalScrollbar(Scrollbar*);
- virtual void willRemoveHorizontalScrollbar(Scrollbar*);
-
- virtual bool shouldScrollbarParticipateInHitTesting(Scrollbar*);
-
- virtual void notifyContentAreaScrolled(const FloatSize& delta) OVERRIDE;
-
- FloatPoint adjustScrollPositionIfNecessary(const FloatPoint&) const;
-
- void immediateScrollTo(const FloatPoint&);
-
- virtual bool isRubberBandInProgress() const OVERRIDE;
-
-#if USE(RUBBER_BANDING)
- /// ScrollElasticityControllerClient member functions.
- virtual IntSize stretchAmount() OVERRIDE;
- virtual bool allowsHorizontalStretching() OVERRIDE;
- virtual bool allowsVerticalStretching() OVERRIDE;
- virtual bool pinnedInDirection(const FloatSize&) OVERRIDE;
- virtual bool canScrollHorizontally() OVERRIDE;
- virtual bool canScrollVertically() OVERRIDE;
- virtual bool shouldRubberBandInDirection(ScrollDirection) OVERRIDE;
- virtual WebCore::IntPoint absoluteScrollPosition() OVERRIDE;
- virtual void immediateScrollByWithoutContentEdgeConstraints(const FloatSize&) OVERRIDE;
- virtual void immediateScrollBy(const FloatSize&) OVERRIDE;
- virtual void startSnapRubberbandTimer() OVERRIDE;
- virtual void stopSnapRubberbandTimer() OVERRIDE;
-
- bool pinnedInDirection(float deltaX, float deltaY);
- void snapRubberBandTimerFired(Timer<ScrollAnimatorMac>*);
-
- ScrollElasticityController m_scrollElasticityController;
- Timer<ScrollAnimatorMac> m_snapRubberBandTimer;
-#endif
-
- bool m_haveScrolledSincePageLoad;
- bool m_needsScrollerStyleUpdate;
- IntRect m_visibleScrollerThumbRect;
-};
-
-} // namespace WebCore
-
-#endif // ScrollAnimatorMac_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/mac/ScrollAnimatorMac.mm b/chromium/third_party/WebKit/Source/core/platform/mac/ScrollAnimatorMac.mm
deleted file mode 100644
index a03cc70788d..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/mac/ScrollAnimatorMac.mm
+++ /dev/null
@@ -1,1303 +0,0 @@
-/*
- * Copyright (C) 2010, 2011 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/platform/mac/ScrollAnimatorMac.h"
-
-#include "core/platform/PlatformGestureEvent.h"
-#include "core/platform/PlatformWheelEvent.h"
-#include "core/platform/ScrollView.h"
-#include "core/platform/ScrollableArea.h"
-#include "core/platform/ScrollbarTheme.h"
-#include "core/platform/ScrollbarThemeMacCommon.h"
-#include "core/platform/ScrollbarThemeMacOverlayAPI.h"
-#include "core/platform/graphics/FloatPoint.h"
-#include "core/platform/mac/BlockExceptions.h"
-#include "core/platform/mac/EmptyProtocolDefinitions.h"
-#include "core/platform/mac/NSScrollerImpDetails.h"
-#include "wtf/MainThread.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/UnusedParam.h"
-
-using namespace WebCore;
-using namespace std;
-
-static bool supportsUIStateTransitionProgress()
-{
- // FIXME: This is temporary until all platforms that support ScrollbarPainter support this part of the API.
- static bool globalSupportsUIStateTransitionProgress = [NSClassFromString(@"NSScrollerImp") instancesRespondToSelector:@selector(mouseEnteredScroller)];
- return globalSupportsUIStateTransitionProgress;
-}
-
-static bool supportsExpansionTransitionProgress()
-{
- static bool globalSupportsExpansionTransitionProgress = [NSClassFromString(@"NSScrollerImp") instancesRespondToSelector:@selector(expansionTransitionProgress)];
- return globalSupportsExpansionTransitionProgress;
-}
-
-static bool supportsContentAreaScrolledInDirection()
-{
- static bool globalSupportsContentAreaScrolledInDirection = [NSClassFromString(@"NSScrollerImpPair") instancesRespondToSelector:@selector(contentAreaScrolledInDirection:)];
- return globalSupportsContentAreaScrolledInDirection;
-}
-
-static ScrollbarThemeMacOverlayAPI* macOverlayScrollbarTheme()
-{
- RELEASE_ASSERT_WITH_SECURITY_IMPLICATION(isScrollbarOverlayAPIAvailable());
- ScrollbarTheme* scrollbarTheme = ScrollbarTheme::theme();
- return !scrollbarTheme->isMockTheme() ? static_cast<ScrollbarThemeMacOverlayAPI*>(scrollbarTheme) : 0;
-}
-
-static ScrollbarPainter scrollbarPainterForScrollbar(Scrollbar* scrollbar)
-{
- if (ScrollbarThemeMacOverlayAPI* scrollbarTheme = macOverlayScrollbarTheme())
- return scrollbarTheme->painterForScrollbar(scrollbar);
-
- return nil;
-}
-
-@interface NSObject (ScrollAnimationHelperDetails)
-- (id)initWithDelegate:(id)delegate;
-- (void)_stopRun;
-- (BOOL)_isAnimating;
-- (NSPoint)targetOrigin;
-- (CGFloat)_progress;
-@end
-
-@interface WebScrollAnimationHelperDelegate : NSObject
-{
- WebCore::ScrollAnimatorMac* _animator;
-}
-- (id)initWithScrollAnimator:(WebCore::ScrollAnimatorMac*)scrollAnimator;
-@end
-
-static NSSize abs(NSSize size)
-{
- NSSize finalSize = size;
- if (finalSize.width < 0)
- finalSize.width = -finalSize.width;
- if (finalSize.height < 0)
- finalSize.height = -finalSize.height;
- return finalSize;
-}
-
-@implementation WebScrollAnimationHelperDelegate
-
-- (id)initWithScrollAnimator:(WebCore::ScrollAnimatorMac*)scrollAnimator
-{
- self = [super init];
- if (!self)
- return nil;
-
- _animator = scrollAnimator;
- return self;
-}
-
-- (void)invalidate
-{
- _animator = 0;
-}
-
-- (NSRect)bounds
-{
- if (!_animator)
- return NSZeroRect;
-
- WebCore::FloatPoint currentPosition = _animator->currentPosition();
- return NSMakeRect(currentPosition.x(), currentPosition.y(), 0, 0);
-}
-
-- (void)_immediateScrollToPoint:(NSPoint)newPosition
-{
- if (!_animator)
- return;
- _animator->immediateScrollToPointForScrollAnimation(newPosition);
-}
-
-- (NSPoint)_pixelAlignProposedScrollPosition:(NSPoint)newOrigin
-{
- return newOrigin;
-}
-
-- (NSSize)convertSizeToBase:(NSSize)size
-{
- return abs(size);
-}
-
-- (NSSize)convertSizeFromBase:(NSSize)size
-{
- return abs(size);
-}
-
-- (NSSize)convertSizeToBacking:(NSSize)size
-{
- return abs(size);
-}
-
-- (NSSize)convertSizeFromBacking:(NSSize)size
-{
- return abs(size);
-}
-
-- (id)superview
-{
- return nil;
-}
-
-- (id)documentView
-{
- return nil;
-}
-
-- (id)window
-{
- return nil;
-}
-
-- (void)_recursiveRecomputeToolTips
-{
-}
-
-@end
-
-@interface WebScrollbarPainterControllerDelegate : NSObject
-{
- ScrollableArea* _scrollableArea;
-}
-- (id)initWithScrollableArea:(ScrollableArea*)scrollableArea;
-@end
-
-@implementation WebScrollbarPainterControllerDelegate
-
-- (id)initWithScrollableArea:(ScrollableArea*)scrollableArea
-{
- self = [super init];
- if (!self)
- return nil;
-
- _scrollableArea = scrollableArea;
- return self;
-}
-
-- (void)invalidate
-{
- _scrollableArea = 0;
-}
-
-- (NSRect)contentAreaRectForScrollerImpPair:(id)scrollerImpPair
-{
- UNUSED_PARAM(scrollerImpPair);
- if (!_scrollableArea)
- return NSZeroRect;
-
- WebCore::IntSize contentsSize = _scrollableArea->contentsSize();
- return NSMakeRect(0, 0, contentsSize.width(), contentsSize.height());
-}
-
-- (BOOL)inLiveResizeForScrollerImpPair:(id)scrollerImpPair
-{
- UNUSED_PARAM(scrollerImpPair);
- if (!_scrollableArea)
- return NO;
-
- return _scrollableArea->inLiveResize();
-}
-
-- (NSPoint)mouseLocationInContentAreaForScrollerImpPair:(id)scrollerImpPair
-{
- UNUSED_PARAM(scrollerImpPair);
- if (!_scrollableArea)
- return NSZeroPoint;
-
- return _scrollableArea->lastKnownMousePosition();
-}
-
-- (NSPoint)scrollerImpPair:(id)scrollerImpPair convertContentPoint:(NSPoint)pointInContentArea toScrollerImp:(id)scrollerImp
-{
- UNUSED_PARAM(scrollerImpPair);
-
- if (!_scrollableArea || !scrollerImp)
- return NSZeroPoint;
-
- WebCore::Scrollbar* scrollbar = 0;
- if ([scrollerImp isHorizontal])
- scrollbar = _scrollableArea->horizontalScrollbar();
- else
- scrollbar = _scrollableArea->verticalScrollbar();
-
- // It is possible to have a null scrollbar here since it is possible for this delegate
- // method to be called between the moment when a scrollbar has been set to 0 and the
- // moment when its destructor has been called. We should probably de-couple some
- // of the clean-up work in ScrollbarThemeMac::unregisterScrollbar() to avoid this
- // issue.
- if (!scrollbar)
- return NSZeroPoint;
-
- ASSERT(scrollerImp == scrollbarPainterForScrollbar(scrollbar));
-
- return scrollbar->convertFromContainingView(WebCore::IntPoint(pointInContentArea));
-}
-
-- (void)scrollerImpPair:(id)scrollerImpPair setContentAreaNeedsDisplayInRect:(NSRect)rect
-{
- UNUSED_PARAM(scrollerImpPair);
- UNUSED_PARAM(rect);
-
- if (!_scrollableArea)
- return;
-
- if (!_scrollableArea->scrollbarsCanBeActive())
- return;
-
- _scrollableArea->scrollAnimator()->contentAreaWillPaint();
-}
-
-- (void)scrollerImpPair:(id)scrollerImpPair updateScrollerStyleForNewRecommendedScrollerStyle:(NSScrollerStyle)newRecommendedScrollerStyle
-{
- // Chrome has a single process mode which is used for testing on Mac. In that mode, WebKit runs on a thread in the
- // browser process. This notification is called by the OS on the main thread in the browser process, and not on the
- // the WebKit thread. Better to not update the style than crash.
- // http://crbug.com/126514
- if (!isMainThread())
- return;
-
- if (!_scrollableArea)
- return;
-
- [scrollerImpPair setScrollerStyle:newRecommendedScrollerStyle];
-
- static_cast<ScrollAnimatorMac*>(_scrollableArea->scrollAnimator())->updateScrollerStyle();
-}
-
-@end
-
-enum FeatureToAnimate {
- ThumbAlpha,
- TrackAlpha,
- UIStateTransition,
- ExpansionTransition
-};
-
-@interface WebScrollbarPartAnimation : NSAnimation
-{
- Scrollbar* _scrollbar;
- RetainPtr<ScrollbarPainter> _scrollbarPainter;
- FeatureToAnimate _featureToAnimate;
- CGFloat _startValue;
- CGFloat _endValue;
-}
-- (id)initWithScrollbar:(Scrollbar*)scrollbar featureToAnimate:(FeatureToAnimate)featureToAnimate animateFrom:(CGFloat)startValue animateTo:(CGFloat)endValue duration:(NSTimeInterval)duration;
-@end
-
-@implementation WebScrollbarPartAnimation
-
-- (id)initWithScrollbar:(Scrollbar*)scrollbar featureToAnimate:(FeatureToAnimate)featureToAnimate animateFrom:(CGFloat)startValue animateTo:(CGFloat)endValue duration:(NSTimeInterval)duration
-{
- self = [super initWithDuration:duration animationCurve:NSAnimationEaseInOut];
- if (!self)
- return nil;
-
- _scrollbar = scrollbar;
- _featureToAnimate = featureToAnimate;
- _startValue = startValue;
- _endValue = endValue;
-
- [self setAnimationBlockingMode:NSAnimationNonblocking];
-
- return self;
-}
-
-- (void)startAnimation
-{
- ASSERT(_scrollbar);
-
- _scrollbarPainter = scrollbarPainterForScrollbar(_scrollbar);
-
- [super startAnimation];
-}
-
-- (void)setStartValue:(CGFloat)startValue
-{
- _startValue = startValue;
-}
-
-- (void)setEndValue:(CGFloat)endValue
-{
- _endValue = endValue;
-}
-
-- (void)setCurrentProgress:(NSAnimationProgress)progress
-{
- [super setCurrentProgress:progress];
-
- ASSERT(_scrollbar);
-
- CGFloat currentValue;
- if (_startValue > _endValue)
- currentValue = 1 - progress;
- else
- currentValue = progress;
-
- switch (_featureToAnimate) {
- case ThumbAlpha:
- [_scrollbarPainter.get() setKnobAlpha:currentValue];
- break;
- case TrackAlpha:
- [_scrollbarPainter.get() setTrackAlpha:currentValue];
- break;
- case UIStateTransition:
- [_scrollbarPainter.get() setUiStateTransitionProgress:currentValue];
- break;
- case ExpansionTransition:
- [_scrollbarPainter.get() setExpansionTransitionProgress:currentValue];
- break;
- }
-
- _scrollbar->invalidate();
-}
-
-- (void)invalidate
-{
- BEGIN_BLOCK_OBJC_EXCEPTIONS;
- [self stopAnimation];
- END_BLOCK_OBJC_EXCEPTIONS;
- _scrollbar = 0;
-}
-
-@end
-
-@interface WebScrollbarPainterDelegate : NSObject<NSAnimationDelegate>
-{
- WebCore::Scrollbar* _scrollbar;
-
- RetainPtr<WebScrollbarPartAnimation> _knobAlphaAnimation;
- RetainPtr<WebScrollbarPartAnimation> _trackAlphaAnimation;
- RetainPtr<WebScrollbarPartAnimation> _uiStateTransitionAnimation;
- RetainPtr<WebScrollbarPartAnimation> _expansionTransitionAnimation;
-}
-- (id)initWithScrollbar:(WebCore::Scrollbar*)scrollbar;
-- (void)cancelAnimations;
-@end
-
-@implementation WebScrollbarPainterDelegate
-
-- (id)initWithScrollbar:(WebCore::Scrollbar*)scrollbar
-{
- self = [super init];
- if (!self)
- return nil;
-
- _scrollbar = scrollbar;
- return self;
-}
-
-- (void)cancelAnimations
-{
- BEGIN_BLOCK_OBJC_EXCEPTIONS;
- [_knobAlphaAnimation.get() stopAnimation];
- [_trackAlphaAnimation.get() stopAnimation];
- [_uiStateTransitionAnimation.get() stopAnimation];
- [_expansionTransitionAnimation.get() stopAnimation];
- END_BLOCK_OBJC_EXCEPTIONS;
-}
-
-- (ScrollAnimatorMac*)scrollAnimator
-{
- return static_cast<ScrollAnimatorMac*>(_scrollbar->scrollableArea()->scrollAnimator());
-}
-
-- (NSRect)convertRectToBacking:(NSRect)aRect
-{
- return aRect;
-}
-
-- (NSRect)convertRectFromBacking:(NSRect)aRect
-{
- return aRect;
-}
-
-- (NSPoint)mouseLocationInScrollerForScrollerImp:(id)scrollerImp
-{
- if (!_scrollbar)
- return NSZeroPoint;
-
- ASSERT_UNUSED(scrollerImp, scrollerImp == scrollbarPainterForScrollbar(_scrollbar));
-
- return _scrollbar->convertFromContainingView(_scrollbar->scrollableArea()->lastKnownMousePosition());
-}
-
-- (void)setUpAlphaAnimation:(RetainPtr<WebScrollbarPartAnimation>&)scrollbarPartAnimation scrollerPainter:(ScrollbarPainter)scrollerPainter part:(WebCore::ScrollbarPart)part animateAlphaTo:(CGFloat)newAlpha duration:(NSTimeInterval)duration
-{
- // If the user has scrolled the page, then the scrollbars must be animated here.
- // This overrides the early returns.
- bool mustAnimate = [self scrollAnimator]->haveScrolledSincePageLoad();
-
- if ([self scrollAnimator]->scrollbarPaintTimerIsActive() && !mustAnimate)
- return;
-
- if (_scrollbar->scrollableArea()->shouldSuspendScrollAnimations() && !mustAnimate) {
- [self scrollAnimator]->startScrollbarPaintTimer();
- return;
- }
-
- // At this point, we are definitely going to animate now, so stop the timer.
- [self scrollAnimator]->stopScrollbarPaintTimer();
-
- // If we are currently animating, stop
- if (scrollbarPartAnimation) {
- [scrollbarPartAnimation.get() stopAnimation];
- scrollbarPartAnimation = nil;
- }
-
- if (part == WebCore::ThumbPart && _scrollbar->orientation() == VerticalScrollbar) {
- if (newAlpha == 1) {
- IntRect thumbRect = IntRect([scrollerPainter rectForPart:NSScrollerKnob]);
- [self scrollAnimator]->setVisibleScrollerThumbRect(thumbRect);
- } else
- [self scrollAnimator]->setVisibleScrollerThumbRect(IntRect());
- }
-
- scrollbarPartAnimation.adoptNS([[WebScrollbarPartAnimation alloc] initWithScrollbar:_scrollbar
- featureToAnimate:part == ThumbPart ? ThumbAlpha : TrackAlpha
- animateFrom:part == ThumbPart ? [scrollerPainter knobAlpha] : [scrollerPainter trackAlpha]
- animateTo:newAlpha
- duration:duration]);
- [scrollbarPartAnimation.get() startAnimation];
-}
-
-- (void)scrollerImp:(id)scrollerImp animateKnobAlphaTo:(CGFloat)newKnobAlpha duration:(NSTimeInterval)duration
-{
- if (!_scrollbar)
- return;
-
- ASSERT(scrollerImp == scrollbarPainterForScrollbar(_scrollbar));
-
- ScrollbarPainter scrollerPainter = (ScrollbarPainter)scrollerImp;
- [self setUpAlphaAnimation:_knobAlphaAnimation scrollerPainter:scrollerPainter part:WebCore::ThumbPart animateAlphaTo:newKnobAlpha duration:duration];
-}
-
-- (void)scrollerImp:(id)scrollerImp animateTrackAlphaTo:(CGFloat)newTrackAlpha duration:(NSTimeInterval)duration
-{
- if (!_scrollbar)
- return;
-
- ASSERT(scrollerImp == scrollbarPainterForScrollbar(_scrollbar));
-
- ScrollbarPainter scrollerPainter = (ScrollbarPainter)scrollerImp;
- [self setUpAlphaAnimation:_trackAlphaAnimation scrollerPainter:scrollerPainter part:WebCore::BackTrackPart animateAlphaTo:newTrackAlpha duration:duration];
-}
-
-- (void)scrollerImp:(id)scrollerImp animateUIStateTransitionWithDuration:(NSTimeInterval)duration
-{
- if (!_scrollbar)
- return;
-
- if (!supportsUIStateTransitionProgress())
- return;
-
- ASSERT(scrollerImp == scrollbarPainterForScrollbar(_scrollbar));
-
- ScrollbarPainter scrollbarPainter = (ScrollbarPainter)scrollerImp;
-
- // UIStateTransition always animates to 1. In case an animation is in progress this avoids a hard transition.
- [scrollbarPainter setUiStateTransitionProgress:1 - [scrollerImp uiStateTransitionProgress]];
-
- if (!_uiStateTransitionAnimation)
- _uiStateTransitionAnimation.adoptNS([[WebScrollbarPartAnimation alloc] initWithScrollbar:_scrollbar
- featureToAnimate:UIStateTransition
- animateFrom:[scrollbarPainter uiStateTransitionProgress]
- animateTo:1.0
- duration:duration]);
- else {
- // If we don't need to initialize the animation, just reset the values in case they have changed.
- [_uiStateTransitionAnimation.get() setStartValue:[scrollbarPainter uiStateTransitionProgress]];
- [_uiStateTransitionAnimation.get() setEndValue:1.0];
- [_uiStateTransitionAnimation.get() setDuration:duration];
- }
- [_uiStateTransitionAnimation.get() startAnimation];
-}
-
-- (void)scrollerImp:(id)scrollerImp animateExpansionTransitionWithDuration:(NSTimeInterval)duration
-{
- if (!_scrollbar)
- return;
-
- if (!supportsExpansionTransitionProgress())
- return;
-
- ASSERT(scrollerImp == scrollbarPainterForScrollbar(_scrollbar));
-
- ScrollbarPainter scrollbarPainter = (ScrollbarPainter)scrollerImp;
-
- // ExpansionTransition always animates to 1. In case an animation is in progress this avoids a hard transition.
- [scrollbarPainter setExpansionTransitionProgress:1 - [scrollerImp expansionTransitionProgress]];
-
- if (!_expansionTransitionAnimation) {
- _expansionTransitionAnimation.adoptNS([[WebScrollbarPartAnimation alloc] initWithScrollbar:_scrollbar
- featureToAnimate:ExpansionTransition
- animateFrom:[scrollbarPainter expansionTransitionProgress]
- animateTo:1.0
- duration:duration]);
- } else {
- // If we don't need to initialize the animation, just reset the values in case they have changed.
- [_expansionTransitionAnimation.get() setStartValue:[scrollbarPainter uiStateTransitionProgress]];
- [_expansionTransitionAnimation.get() setEndValue:1.0];
- [_expansionTransitionAnimation.get() setDuration:duration];
- }
- [_expansionTransitionAnimation.get() startAnimation];
-}
-
-- (void)scrollerImp:(id)scrollerImp overlayScrollerStateChangedTo:(NSUInteger)newOverlayScrollerState
-{
- UNUSED_PARAM(scrollerImp);
- UNUSED_PARAM(newOverlayScrollerState);
-}
-
-- (void)invalidate
-{
- _scrollbar = 0;
- BEGIN_BLOCK_OBJC_EXCEPTIONS;
- [_knobAlphaAnimation.get() invalidate];
- [_trackAlphaAnimation.get() invalidate];
- [_uiStateTransitionAnimation.get() invalidate];
- [_expansionTransitionAnimation.get() invalidate];
- END_BLOCK_OBJC_EXCEPTIONS;
-}
-
-@end
-
-namespace WebCore {
-
-PassOwnPtr<ScrollAnimator> ScrollAnimator::create(ScrollableArea* scrollableArea)
-{
- return adoptPtr(new ScrollAnimatorMac(scrollableArea));
-}
-
-ScrollAnimatorMac::ScrollAnimatorMac(ScrollableArea* scrollableArea)
- : ScrollAnimator(scrollableArea)
- , m_initialScrollbarPaintTimer(this, &ScrollAnimatorMac::initialScrollbarPaintTimerFired)
- , m_sendContentAreaScrolledTimer(this, &ScrollAnimatorMac::sendContentAreaScrolledTimerFired)
-#if USE(RUBBER_BANDING)
- , m_scrollElasticityController(this)
- , m_snapRubberBandTimer(this, &ScrollAnimatorMac::snapRubberBandTimerFired)
-#endif
- , m_haveScrolledSincePageLoad(false)
- , m_needsScrollerStyleUpdate(false)
-{
- m_scrollAnimationHelperDelegate.adoptNS([[WebScrollAnimationHelperDelegate alloc] initWithScrollAnimator:this]);
- m_scrollAnimationHelper.adoptNS([[NSClassFromString(@"NSScrollAnimationHelper") alloc] initWithDelegate:m_scrollAnimationHelperDelegate.get()]);
-
- if (isScrollbarOverlayAPIAvailable()) {
- m_scrollbarPainterControllerDelegate.adoptNS([[WebScrollbarPainterControllerDelegate alloc] initWithScrollableArea:scrollableArea]);
- m_scrollbarPainterController = [[[NSClassFromString(@"NSScrollerImpPair") alloc] init] autorelease];
- [m_scrollbarPainterController.get() setDelegate:m_scrollbarPainterControllerDelegate.get()];
- [m_scrollbarPainterController.get() setScrollerStyle:recommendedScrollerStyle()];
- }
-}
-
-ScrollAnimatorMac::~ScrollAnimatorMac()
-{
- if (isScrollbarOverlayAPIAvailable()) {
- BEGIN_BLOCK_OBJC_EXCEPTIONS;
- [m_scrollbarPainterControllerDelegate.get() invalidate];
- [m_scrollbarPainterController.get() setDelegate:nil];
- [m_horizontalScrollbarPainterDelegate.get() invalidate];
- [m_verticalScrollbarPainterDelegate.get() invalidate];
- [m_scrollAnimationHelperDelegate.get() invalidate];
- END_BLOCK_OBJC_EXCEPTIONS;
- }
-}
-
-static bool scrollAnimationEnabledForSystem()
-{
- NSString* scrollAnimationDefaultsKey =
- @"AppleScrollAnimationEnabled";
- static bool enabled = [[NSUserDefaults standardUserDefaults] boolForKey:scrollAnimationDefaultsKey];
- return enabled;
-}
-
-#if USE(RUBBER_BANDING)
-static bool rubberBandingEnabledForSystem()
-{
- static bool initialized = false;
- static bool enabled = true;
- // Caches the result, which is consistent with other apps like the Finder, which all
- // require a restart after changing this default.
- if (!initialized) {
- // Uses -objectForKey: and not -boolForKey: in order to default to true if the value wasn't set.
- id value = [[NSUserDefaults standardUserDefaults] objectForKey:@"NSScrollViewRubberbanding"];
- if ([value isKindOfClass:[NSNumber class]])
- enabled = [value boolValue];
- initialized = true;
- }
- return enabled;
-}
-#endif
-
-bool ScrollAnimatorMac::scroll(ScrollbarOrientation orientation, ScrollGranularity granularity, float step, float multiplier)
-{
- m_haveScrolledSincePageLoad = true;
-
- if (!scrollAnimationEnabledForSystem() || !m_scrollableArea->scrollAnimatorEnabled())
- return ScrollAnimator::scroll(orientation, granularity, step, multiplier);
-
- if (granularity == ScrollByPixel)
- return ScrollAnimator::scroll(orientation, granularity, step, multiplier);
-
- float currentPos = orientation == HorizontalScrollbar ? m_currentPosX : m_currentPosY;
- float newPos = std::max<float>(std::min<float>(currentPos + (step * multiplier), m_scrollableArea->maximumScrollPosition(orientation)), m_scrollableArea->minimumScrollPosition(orientation));
- if (currentPos == newPos)
- return false;
-
- NSPoint newPoint;
- if ([m_scrollAnimationHelper.get() _isAnimating]) {
- NSPoint targetOrigin = [m_scrollAnimationHelper.get() targetOrigin];
- newPoint = orientation == HorizontalScrollbar ? NSMakePoint(newPos, targetOrigin.y) : NSMakePoint(targetOrigin.x, newPos);
- } else
- newPoint = orientation == HorizontalScrollbar ? NSMakePoint(newPos, m_currentPosY) : NSMakePoint(m_currentPosX, newPos);
-
- [m_scrollAnimationHelper.get() scrollToPoint:newPoint];
- return true;
-}
-
-void ScrollAnimatorMac::scrollToOffsetWithoutAnimation(const FloatPoint& offset)
-{
- [m_scrollAnimationHelper.get() _stopRun];
- immediateScrollTo(offset);
-}
-
-FloatPoint ScrollAnimatorMac::adjustScrollPositionIfNecessary(const FloatPoint& position) const
-{
- if (!m_scrollableArea->constrainsScrollingToContentEdge())
- return position;
-
- IntPoint minPos = m_scrollableArea->minimumScrollPosition();
- IntPoint maxPos = m_scrollableArea->maximumScrollPosition();
-
- float newX = max<float>(min<float>(position.x(), maxPos.x()), minPos.x());
- float newY = max<float>(min<float>(position.y(), maxPos.y()), minPos.y());
-
- return FloatPoint(newX, newY);
-}
-
-void ScrollAnimatorMac::immediateScrollTo(const FloatPoint& newPosition)
-{
- FloatPoint adjustedPosition = adjustScrollPositionIfNecessary(newPosition);
-
- bool positionChanged = adjustedPosition.x() != m_currentPosX || adjustedPosition.y() != m_currentPosY;
- if (!positionChanged && !scrollableArea()->scrollOriginChanged())
- return;
-
- FloatSize delta = FloatSize(adjustedPosition.x() - m_currentPosX, adjustedPosition.y() - m_currentPosY);
-
- m_currentPosX = adjustedPosition.x();
- m_currentPosY = adjustedPosition.y();
- notifyPositionChanged(delta);
-}
-
-bool ScrollAnimatorMac::isRubberBandInProgress() const
-{
-#if !USE(RUBBER_BANDING)
- return false;
-#else
- return m_scrollElasticityController.isRubberBandInProgress();
-#endif
-}
-
-void ScrollAnimatorMac::immediateScrollToPointForScrollAnimation(const FloatPoint& newPosition)
-{
- ASSERT(m_scrollAnimationHelper);
- immediateScrollTo(newPosition);
-}
-
-void ScrollAnimatorMac::notifyPositionChanged(const FloatSize& delta)
-{
- notifyContentAreaScrolled(delta);
- ScrollAnimator::notifyPositionChanged(delta);
-}
-
-void ScrollAnimatorMac::contentAreaWillPaint() const
-{
- if (!scrollableArea()->scrollbarsCanBeActive())
- return;
- if (isScrollbarOverlayAPIAvailable())
- [m_scrollbarPainterController.get() contentAreaWillDraw];
-}
-
-void ScrollAnimatorMac::mouseEnteredContentArea() const
-{
- if (!scrollableArea()->scrollbarsCanBeActive())
- return;
- if (isScrollbarOverlayAPIAvailable())
- [m_scrollbarPainterController.get() mouseEnteredContentArea];
-}
-
-void ScrollAnimatorMac::mouseExitedContentArea() const
-{
- if (!scrollableArea()->scrollbarsCanBeActive())
- return;
- if (isScrollbarOverlayAPIAvailable())
- [m_scrollbarPainterController.get() mouseExitedContentArea];
-}
-
-void ScrollAnimatorMac::mouseMovedInContentArea() const
-{
- if (!scrollableArea()->scrollbarsCanBeActive())
- return;
- if (isScrollbarOverlayAPIAvailable())
- [m_scrollbarPainterController.get() mouseMovedInContentArea];
-}
-
-void ScrollAnimatorMac::mouseEnteredScrollbar(Scrollbar* scrollbar) const
-{
- // At this time, only legacy scrollbars needs to send notifications here.
- if (recommendedScrollerStyle() != NSScrollerStyleLegacy)
- return;
-
- if (!scrollableArea()->scrollbarsCanBeActive())
- return;
-
- if (isScrollbarOverlayAPIAvailable()) {
- if (!supportsUIStateTransitionProgress())
- return;
- if (ScrollbarPainter painter = scrollbarPainterForScrollbar(scrollbar))
- [painter mouseEnteredScroller];
- }
-}
-
-void ScrollAnimatorMac::mouseExitedScrollbar(Scrollbar* scrollbar) const
-{
- // At this time, only legacy scrollbars needs to send notifications here.
- if (recommendedScrollerStyle() != NSScrollerStyleLegacy)
- return;
-
- if (!scrollableArea()->scrollbarsCanBeActive())
- return;
-
- if (isScrollbarOverlayAPIAvailable()) {
- if (!supportsUIStateTransitionProgress())
- return;
- if (ScrollbarPainter painter = scrollbarPainterForScrollbar(scrollbar))
- [painter mouseExitedScroller];
- }
-}
-
-void ScrollAnimatorMac::willStartLiveResize()
-{
- if (!scrollableArea()->scrollbarsCanBeActive())
- return;
- if (isScrollbarOverlayAPIAvailable())
- [m_scrollbarPainterController.get() startLiveResize];
-}
-
-void ScrollAnimatorMac::contentsResized() const
-{
- if (!scrollableArea()->scrollbarsCanBeActive())
- return;
- if (isScrollbarOverlayAPIAvailable())
- [m_scrollbarPainterController.get() contentAreaDidResize];
-}
-
-void ScrollAnimatorMac::willEndLiveResize()
-{
- if (!scrollableArea()->scrollbarsCanBeActive())
- return;
- if (isScrollbarOverlayAPIAvailable())
- [m_scrollbarPainterController.get() endLiveResize];
-}
-
-void ScrollAnimatorMac::contentAreaDidShow() const
-{
- if (!scrollableArea()->scrollbarsCanBeActive())
- return;
- if (isScrollbarOverlayAPIAvailable())
- [m_scrollbarPainterController.get() windowOrderedIn];
-}
-
-void ScrollAnimatorMac::contentAreaDidHide() const
-{
- if (!scrollableArea()->scrollbarsCanBeActive())
- return;
- if (isScrollbarOverlayAPIAvailable())
- [m_scrollbarPainterController.get() windowOrderedOut];
-}
-
-void ScrollAnimatorMac::didBeginScrollGesture() const
-{
- if (!scrollableArea()->scrollbarsCanBeActive())
- return;
- if (isScrollbarOverlayAPIAvailable())
- [m_scrollbarPainterController.get() beginScrollGesture];
-}
-
-void ScrollAnimatorMac::didEndScrollGesture() const
-{
- if (!scrollableArea()->scrollbarsCanBeActive())
- return;
- if (isScrollbarOverlayAPIAvailable())
- [m_scrollbarPainterController.get() endScrollGesture];
-}
-
-void ScrollAnimatorMac::mayBeginScrollGesture() const
-{
- if (!scrollableArea()->scrollbarsCanBeActive())
- return;
- if (!isScrollbarOverlayAPIAvailable())
- return;
-
- [m_scrollbarPainterController.get() beginScrollGesture];
- [m_scrollbarPainterController.get() contentAreaScrolled];
-}
-
-void ScrollAnimatorMac::finishCurrentScrollAnimations()
-{
- if (isScrollbarOverlayAPIAvailable()) {
- [m_scrollbarPainterController.get() hideOverlayScrollers];
- }
-}
-
-void ScrollAnimatorMac::didAddVerticalScrollbar(Scrollbar* scrollbar)
-{
- if (!isScrollbarOverlayAPIAvailable())
- return;
-
- ScrollbarPainter painter = scrollbarPainterForScrollbar(scrollbar);
- if (!painter)
- return;
-
- ASSERT(!m_verticalScrollbarPainterDelegate);
- m_verticalScrollbarPainterDelegate.adoptNS([[WebScrollbarPainterDelegate alloc] initWithScrollbar:scrollbar]);
-
- [painter setDelegate:m_verticalScrollbarPainterDelegate.get()];
- [m_scrollbarPainterController.get() setVerticalScrollerImp:painter];
- if (scrollableArea()->inLiveResize())
- [painter setKnobAlpha:1];
-}
-
-void ScrollAnimatorMac::willRemoveVerticalScrollbar(Scrollbar* scrollbar)
-{
- if (!isScrollbarOverlayAPIAvailable())
- return;
-
- ScrollbarPainter painter = scrollbarPainterForScrollbar(scrollbar);
- if (!painter)
- return;
-
- ASSERT(m_verticalScrollbarPainterDelegate);
- [m_verticalScrollbarPainterDelegate.get() invalidate];
- m_verticalScrollbarPainterDelegate = nullptr;
-
- [painter setDelegate:nil];
- [m_scrollbarPainterController.get() setVerticalScrollerImp:nil];
-}
-
-void ScrollAnimatorMac::didAddHorizontalScrollbar(Scrollbar* scrollbar)
-{
- if (!isScrollbarOverlayAPIAvailable())
- return;
-
- ScrollbarPainter painter = scrollbarPainterForScrollbar(scrollbar);
- if (!painter)
- return;
-
- ASSERT(!m_horizontalScrollbarPainterDelegate);
- m_horizontalScrollbarPainterDelegate.adoptNS([[WebScrollbarPainterDelegate alloc] initWithScrollbar:scrollbar]);
-
- [painter setDelegate:m_horizontalScrollbarPainterDelegate.get()];
- [m_scrollbarPainterController.get() setHorizontalScrollerImp:painter];
- if (scrollableArea()->inLiveResize())
- [painter setKnobAlpha:1];
-}
-
-void ScrollAnimatorMac::willRemoveHorizontalScrollbar(Scrollbar* scrollbar)
-{
- if (!isScrollbarOverlayAPIAvailable())
- return;
-
- ScrollbarPainter painter = scrollbarPainterForScrollbar(scrollbar);
- if (!painter)
- return;
-
- ASSERT(m_horizontalScrollbarPainterDelegate);
- [m_horizontalScrollbarPainterDelegate.get() invalidate];
- m_horizontalScrollbarPainterDelegate = nullptr;
-
- [painter setDelegate:nil];
- [m_scrollbarPainterController.get() setHorizontalScrollerImp:nil];
-}
-
-bool ScrollAnimatorMac::shouldScrollbarParticipateInHitTesting(Scrollbar* scrollbar)
-{
- // Non-overlay scrollbars should always participate in hit testing.
- if (recommendedScrollerStyle() != NSScrollerStyleOverlay)
- return true;
-
- if (!isScrollbarOverlayAPIAvailable())
- return true;
-
- if (scrollbar->isAlphaLocked())
- return true;
-
- // Overlay scrollbars should participate in hit testing whenever they are at all visible.
- ScrollbarPainter painter = scrollbarPainterForScrollbar(scrollbar);
- if (!painter)
- return false;
- return [painter knobAlpha] > 0;
-}
-
-void ScrollAnimatorMac::notifyContentAreaScrolled(const FloatSize& delta)
-{
- if (!isScrollbarOverlayAPIAvailable())
- return;
-
- // This function is called when a page is going into the page cache, but the page
- // isn't really scrolling in that case. We should only pass the message on to the
- // ScrollbarPainterController when we're really scrolling on an active page.
- if (scrollableArea()->scrollbarsCanBeActive())
- sendContentAreaScrolledSoon(delta);
-}
-
-void ScrollAnimatorMac::cancelAnimations()
-{
- m_haveScrolledSincePageLoad = false;
-
- if (isScrollbarOverlayAPIAvailable()) {
- if (scrollbarPaintTimerIsActive())
- stopScrollbarPaintTimer();
- [m_horizontalScrollbarPainterDelegate.get() cancelAnimations];
- [m_verticalScrollbarPainterDelegate.get() cancelAnimations];
- }
-}
-
-void ScrollAnimatorMac::handleWheelEventPhase(PlatformWheelEventPhase phase)
-{
- // This may not have been set to true yet if the wheel event was handled by the ScrollingTree,
- // So set it to true here.
- m_haveScrolledSincePageLoad = true;
-
- if (phase == PlatformWheelEventPhaseBegan)
- didBeginScrollGesture();
- else if (phase == PlatformWheelEventPhaseEnded || phase == PlatformWheelEventPhaseCancelled)
- didEndScrollGesture();
- else if (phase == PlatformWheelEventPhaseMayBegin)
- mayBeginScrollGesture();
-}
-
-#if USE(RUBBER_BANDING)
-bool ScrollAnimatorMac::handleWheelEvent(const PlatformWheelEvent& wheelEvent)
-{
- m_haveScrolledSincePageLoad = true;
-
- if (!wheelEvent.hasPreciseScrollingDeltas() || !rubberBandingEnabledForSystem())
- return ScrollAnimator::handleWheelEvent(wheelEvent);
-
- // FIXME: This is somewhat roundabout hack to allow forwarding wheel events
- // up to the parent scrollable area. It takes advantage of the fact that
- // the base class implementation of handleWheelEvent will not accept the
- // wheel event if there is nowhere to scroll.
- if (fabsf(wheelEvent.deltaY()) >= fabsf(wheelEvent.deltaX())) {
- if (!allowsVerticalStretching())
- return ScrollAnimator::handleWheelEvent(wheelEvent);
- } else {
- if (!allowsHorizontalStretching())
- return ScrollAnimator::handleWheelEvent(wheelEvent);
- }
-
- bool didHandleEvent = m_scrollElasticityController.handleWheelEvent(wheelEvent);
-
- // The elasticity controller can return false on a phase end event if rubber banding wasn't in progress.
- // In this case, the wheel phase must still be handled so that that overlay scroll bars get hidden.
- if (didHandleEvent || wheelEvent.phase() == PlatformWheelEventPhaseEnded || wheelEvent.phase() == PlatformWheelEventPhaseCancelled)
- handleWheelEventPhase(wheelEvent.phase());
-
- return didHandleEvent;
-}
-
-bool ScrollAnimatorMac::pinnedInDirection(float deltaX, float deltaY)
-{
- FloatSize limitDelta;
- if (fabsf(deltaY) >= fabsf(deltaX)) {
- if (deltaY < 0) {
- // We are trying to scroll up. Make sure we are not pinned to the top
- limitDelta.setHeight(m_scrollableArea->visibleContentRect().y() + + m_scrollableArea->scrollOrigin().y());
- } else {
- // We are trying to scroll down. Make sure we are not pinned to the bottom
- limitDelta.setHeight(m_scrollableArea->contentsSize().height() - (m_scrollableArea->visibleContentRect().maxY() + m_scrollableArea->scrollOrigin().y()));
- }
- } else if (deltaX != 0) {
- if (deltaX < 0) {
- // We are trying to scroll left. Make sure we are not pinned to the left
- limitDelta.setWidth(m_scrollableArea->visibleContentRect().x() + m_scrollableArea->scrollOrigin().x());
- } else {
- // We are trying to scroll right. Make sure we are not pinned to the right
- limitDelta.setWidth(m_scrollableArea->contentsSize().width() - (m_scrollableArea->visibleContentRect().maxX() + m_scrollableArea->scrollOrigin().x()));
- }
- }
-
- if ((deltaX != 0 || deltaY != 0) && (limitDelta.width() < 1 && limitDelta.height() < 1))
- return true;
- return false;
-}
-
-bool ScrollAnimatorMac::allowsVerticalStretching()
-{
- switch (m_scrollableArea->verticalScrollElasticity()) {
- case ScrollElasticityAutomatic: {
- Scrollbar* hScroller = m_scrollableArea->horizontalScrollbar();
- Scrollbar* vScroller = m_scrollableArea->verticalScrollbar();
- return (((vScroller && vScroller->enabled()) || (!hScroller || !hScroller->enabled())));
- }
- case ScrollElasticityNone:
- return false;
- case ScrollElasticityAllowed:
- return true;
- }
-
- ASSERT_NOT_REACHED();
- return false;
-}
-
-bool ScrollAnimatorMac::allowsHorizontalStretching()
-{
- switch (m_scrollableArea->horizontalScrollElasticity()) {
- case ScrollElasticityAutomatic: {
- Scrollbar* hScroller = m_scrollableArea->horizontalScrollbar();
- Scrollbar* vScroller = m_scrollableArea->verticalScrollbar();
- return (((hScroller && hScroller->enabled()) || (!vScroller || !vScroller->enabled())));
- }
- case ScrollElasticityNone:
- return false;
- case ScrollElasticityAllowed:
- return true;
- }
-
- ASSERT_NOT_REACHED();
- return false;
-}
-
-IntSize ScrollAnimatorMac::stretchAmount()
-{
- return m_scrollableArea->overhangAmount();
-}
-
-bool ScrollAnimatorMac::pinnedInDirection(const FloatSize& direction)
-{
- return pinnedInDirection(direction.width(), direction.height());
-}
-
-bool ScrollAnimatorMac::canScrollHorizontally()
-{
- Scrollbar* scrollbar = m_scrollableArea->horizontalScrollbar();
- if (!scrollbar)
- return false;
- return scrollbar->enabled();
-}
-
-bool ScrollAnimatorMac::canScrollVertically()
-{
- Scrollbar* scrollbar = m_scrollableArea->verticalScrollbar();
- if (!scrollbar)
- return false;
- return scrollbar->enabled();
-}
-
-bool ScrollAnimatorMac::shouldRubberBandInDirection(ScrollDirection direction)
-{
- return m_scrollableArea->shouldRubberBandInDirection(direction);
-}
-
-IntPoint ScrollAnimatorMac::absoluteScrollPosition()
-{
- return m_scrollableArea->visibleContentRect().location() + m_scrollableArea->scrollOrigin();
-}
-
-void ScrollAnimatorMac::immediateScrollByWithoutContentEdgeConstraints(const FloatSize& delta)
-{
- m_scrollableArea->setConstrainsScrollingToContentEdge(false);
- immediateScrollBy(delta);
- m_scrollableArea->setConstrainsScrollingToContentEdge(true);
-}
-
-void ScrollAnimatorMac::immediateScrollBy(const FloatSize& delta)
-{
- FloatPoint newPos = adjustScrollPositionIfNecessary(FloatPoint(m_currentPosX, m_currentPosY) + delta);
- if (newPos.x() == m_currentPosX && newPos.y() == m_currentPosY)
- return;
-
- FloatSize adjustedDelta = FloatSize(newPos.x() - m_currentPosX, newPos.y() - m_currentPosY);
-
- m_currentPosX = newPos.x();
- m_currentPosY = newPos.y();
- notifyPositionChanged(adjustedDelta);
-}
-
-void ScrollAnimatorMac::startSnapRubberbandTimer()
-{
- m_snapRubberBandTimer.startRepeating(1.0 / 60.0);
-}
-
-void ScrollAnimatorMac::stopSnapRubberbandTimer()
-{
- m_snapRubberBandTimer.stop();
-}
-
-void ScrollAnimatorMac::snapRubberBandTimerFired(Timer<ScrollAnimatorMac>*)
-{
- m_scrollElasticityController.snapRubberBandTimerFired();
-}
-#endif
-
-void ScrollAnimatorMac::setIsActive()
-{
- if (!isScrollbarOverlayAPIAvailable())
- return;
-
- if (!m_needsScrollerStyleUpdate)
- return;
-
- updateScrollerStyle();
-}
-
-void ScrollAnimatorMac::updateScrollerStyle()
-{
- if (!isScrollbarOverlayAPIAvailable())
- return;
-
- if (!scrollableArea()->scrollbarsCanBeActive()) {
- m_needsScrollerStyleUpdate = true;
- return;
- }
-
- ScrollbarThemeMacOverlayAPI* macTheme = macOverlayScrollbarTheme();
- if (!macTheme) {
- m_needsScrollerStyleUpdate = false;
- return;
- }
-
- NSScrollerStyle newStyle = [m_scrollbarPainterController.get() scrollerStyle];
-
- if (Scrollbar* verticalScrollbar = scrollableArea()->verticalScrollbar()) {
- verticalScrollbar->invalidate();
-
- ScrollbarPainter oldVerticalPainter = [m_scrollbarPainterController.get() verticalScrollerImp];
- ScrollbarPainter newVerticalPainter = [NSClassFromString(@"NSScrollerImp") scrollerImpWithStyle:newStyle
- controlSize:(NSControlSize)verticalScrollbar->controlSize()
- horizontal:NO
- replacingScrollerImp:oldVerticalPainter];
- [m_scrollbarPainterController.get() setVerticalScrollerImp:newVerticalPainter];
- macTheme->setNewPainterForScrollbar(verticalScrollbar, newVerticalPainter);
-
- // The different scrollbar styles have different thicknesses, so we must re-set the
- // frameRect to the new thickness, and the re-layout below will ensure the position
- // and length are properly updated.
- int thickness = macTheme->scrollbarThickness(verticalScrollbar->controlSize());
- verticalScrollbar->setFrameRect(IntRect(0, 0, thickness, thickness));
- }
-
- if (Scrollbar* horizontalScrollbar = scrollableArea()->horizontalScrollbar()) {
- horizontalScrollbar->invalidate();
-
- ScrollbarPainter oldHorizontalPainter = [m_scrollbarPainterController.get() horizontalScrollerImp];
- ScrollbarPainter newHorizontalPainter = [NSClassFromString(@"NSScrollerImp") scrollerImpWithStyle:newStyle
- controlSize:(NSControlSize)horizontalScrollbar->controlSize()
- horizontal:YES
- replacingScrollerImp:oldHorizontalPainter];
- [m_scrollbarPainterController.get() setHorizontalScrollerImp:newHorizontalPainter];
- macTheme->setNewPainterForScrollbar(horizontalScrollbar, newHorizontalPainter);
-
- // The different scrollbar styles have different thicknesses, so we must re-set the
- // frameRect to the new thickness, and the re-layout below will ensure the position
- // and length are properly updated.
- int thickness = macTheme->scrollbarThickness(horizontalScrollbar->controlSize());
- horizontalScrollbar->setFrameRect(IntRect(0, 0, thickness, thickness));
- }
-
- // If m_needsScrollerStyleUpdate is true, then the page is restoring from the page cache, and
- // a relayout will happen on its own. Otherwise, we must initiate a re-layout ourselves.
- scrollableArea()->scrollbarStyleChanged(newStyle, !m_needsScrollerStyleUpdate);
-
- m_needsScrollerStyleUpdate = false;
-}
-
-void ScrollAnimatorMac::startScrollbarPaintTimer()
-{
- m_initialScrollbarPaintTimer.startOneShot(0.1);
-}
-
-bool ScrollAnimatorMac::scrollbarPaintTimerIsActive() const
-{
- return m_initialScrollbarPaintTimer.isActive();
-}
-
-void ScrollAnimatorMac::stopScrollbarPaintTimer()
-{
- m_initialScrollbarPaintTimer.stop();
-}
-
-void ScrollAnimatorMac::initialScrollbarPaintTimerFired(Timer<ScrollAnimatorMac>*)
-{
- if (isScrollbarOverlayAPIAvailable()) {
- // To force the scrollbars to flash, we have to call hide first. Otherwise, the ScrollbarPainterController
- // might think that the scrollbars are already showing and bail early.
- [m_scrollbarPainterController.get() hideOverlayScrollers];
- [m_scrollbarPainterController.get() flashScrollers];
- }
-}
-
-void ScrollAnimatorMac::sendContentAreaScrolledSoon(const FloatSize& delta)
-{
- m_contentAreaScrolledTimerScrollDelta = delta;
-
- if (!m_sendContentAreaScrolledTimer.isActive())
- m_sendContentAreaScrolledTimer.startOneShot(0);
-}
-
-void ScrollAnimatorMac::sendContentAreaScrolledTimerFired(Timer<ScrollAnimatorMac>*)
-{
- if (supportsContentAreaScrolledInDirection()) {
- [m_scrollbarPainterController.get() contentAreaScrolledInDirection:NSMakePoint(m_contentAreaScrolledTimerScrollDelta.width(), m_contentAreaScrolledTimerScrollDelta.height())];
- m_contentAreaScrolledTimerScrollDelta = FloatSize();
- } else
- [m_scrollbarPainterController.get() contentAreaScrolled];
-}
-
-void ScrollAnimatorMac::setVisibleScrollerThumbRect(const IntRect& scrollerThumb)
-{
- IntRect rectInViewCoordinates = scrollerThumb;
- if (Scrollbar* verticalScrollbar = m_scrollableArea->verticalScrollbar())
- rectInViewCoordinates = verticalScrollbar->convertToContainingView(scrollerThumb);
-
- if (rectInViewCoordinates == m_visibleScrollerThumbRect)
- return;
-
- m_visibleScrollerThumbRect = rectInViewCoordinates;
-}
-
-bool ScrollAnimatorMac::canUseCoordinatedScrollbar() {
- return isScrollbarOverlayAPIAvailable();
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/mac/ScrollElasticityController.h b/chromium/third_party/WebKit/Source/core/platform/mac/ScrollElasticityController.h
deleted file mode 100644
index 7fde5e9ff56..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/mac/ScrollElasticityController.h
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- * Copyright (C) 2011 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ScrollElasticityController_h
-#define ScrollElasticityController_h
-
-#if USE(RUBBER_BANDING)
-
-#include "core/platform/ScrollTypes.h"
-#include "core/platform/graphics/FloatPoint.h"
-#include "core/platform/graphics/FloatSize.h"
-#include "wtf/Noncopyable.h"
-
-namespace WebCore {
-
-class PlatformWheelEvent;
-
-class ScrollElasticityControllerClient {
-protected:
- virtual ~ScrollElasticityControllerClient() { }
-
-public:
- virtual bool allowsHorizontalStretching() = 0;
- virtual bool allowsVerticalStretching() = 0;
- virtual IntSize stretchAmount() = 0;
- virtual bool pinnedInDirection(const FloatSize&) = 0;
- virtual bool canScrollHorizontally() = 0;
- virtual bool canScrollVertically() = 0;
- virtual bool shouldRubberBandInDirection(ScrollDirection) = 0;
-
- // Return the absolute scroll position, not relative to the scroll origin.
- virtual WebCore::IntPoint absoluteScrollPosition() = 0;
-
- virtual void immediateScrollBy(const FloatSize&) = 0;
- virtual void immediateScrollByWithoutContentEdgeConstraints(const FloatSize&) = 0;
- virtual void startSnapRubberbandTimer() = 0;
- virtual void stopSnapRubberbandTimer() = 0;
-};
-
-class ScrollElasticityController {
- WTF_MAKE_NONCOPYABLE(ScrollElasticityController);
-
-public:
- explicit ScrollElasticityController(ScrollElasticityControllerClient*);
-
- bool handleWheelEvent(const PlatformWheelEvent&);
- void snapRubberBandTimerFired();
-
- bool isRubberBandInProgress() const;
-
-private:
- void stopSnapRubberbandTimer();
- void snapRubberBand();
-
- bool shouldRubberBandInHorizontalDirection(const PlatformWheelEvent&);
-
- ScrollElasticityControllerClient* m_client;
-
- bool m_inScrollGesture;
- bool m_momentumScrollInProgress;
- bool m_ignoreMomentumScrolls;
-
- CFTimeInterval m_lastMomentumScrollTimestamp;
- FloatSize m_overflowScrollDelta;
- FloatSize m_stretchScrollForce;
- FloatSize m_momentumVelocity;
-
- // Rubber band state.
- CFTimeInterval m_startTime;
- FloatSize m_startStretch;
- FloatPoint m_origOrigin;
- FloatSize m_origVelocity;
-
- bool m_snapRubberbandTimerIsActive;
-};
-
-} // namespace WebCore
-
-#endif // USE(RUBBER_BANDING)
-
-#endif // ScrollElasticityController_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/mac/ScrollElasticityController.mm b/chromium/third_party/WebKit/Source/core/platform/mac/ScrollElasticityController.mm
deleted file mode 100644
index b7d768a9b85..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/mac/ScrollElasticityController.mm
+++ /dev/null
@@ -1,428 +0,0 @@
-/*
- * Copyright (C) 2011 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/mac/ScrollElasticityController.h"
-
-#include <sys/sysctl.h>
-#include <sys/time.h>
-#include "core/platform/PlatformWheelEvent.h"
-
-#if USE(RUBBER_BANDING)
-
-static NSTimeInterval systemUptime()
-{
- if ([[NSProcessInfo processInfo] respondsToSelector:@selector(systemUptime)])
- return [[NSProcessInfo processInfo] systemUptime];
-
- // Get how long system has been up. Found by looking getting "boottime" from the kernel.
- static struct timeval boottime = {0, 0};
- if (!boottime.tv_sec) {
- int mib[2] = {CTL_KERN, KERN_BOOTTIME};
- size_t size = sizeof(boottime);
- if (-1 == sysctl(mib, 2, &boottime, &size, 0, 0))
- boottime.tv_sec = 0;
- }
- struct timeval now;
- if (boottime.tv_sec && -1 != gettimeofday(&now, 0)) {
- struct timeval uptime;
- timersub(&now, &boottime, &uptime);
- NSTimeInterval result = uptime.tv_sec + (uptime.tv_usec / 1E+6);
- return result;
- }
- return 0;
-}
-
-namespace WebCore {
-
-static const float scrollVelocityZeroingTimeout = 0.10f;
-static const float rubberbandDirectionLockStretchRatio = 1;
-static const float rubberbandMinimumRequiredDeltaBeforeStretch = 10;
-
-static const float rubberbandStiffness = 20;
-static const float rubberbandAmplitude = 0.31f;
-static const float rubberbandPeriod = 1.6f;
-
-static float elasticDeltaForTimeDelta(float initialPosition, float initialVelocity, float elapsedTime)
-{
- float amplitude = rubberbandAmplitude;
- float period = rubberbandPeriod;
- float criticalDampeningFactor = expf((-elapsedTime * rubberbandStiffness) / period);
-
- return (initialPosition + (-initialVelocity * elapsedTime * amplitude)) * criticalDampeningFactor;
-}
-
-static float elasticDeltaForReboundDelta(float delta)
-{
- float stiffness = std::max(rubberbandStiffness, 1.0f);
- return delta / stiffness;
-}
-
-static float reboundDeltaForElasticDelta(float delta)
-{
- return delta * rubberbandStiffness;
-}
-
-static float scrollWheelMultiplier()
-{
- static float multiplier = -1;
- if (multiplier < 0) {
- multiplier = [[NSUserDefaults standardUserDefaults] floatForKey:@"NSScrollWheelMultiplier"];
- if (multiplier <= 0)
- multiplier = 1;
- }
- return multiplier;
-}
-
-ScrollElasticityController::ScrollElasticityController(ScrollElasticityControllerClient* client)
- : m_client(client)
- , m_inScrollGesture(false)
- , m_momentumScrollInProgress(false)
- , m_ignoreMomentumScrolls(false)
- , m_lastMomentumScrollTimestamp(0)
- , m_startTime(0)
- , m_snapRubberbandTimerIsActive(false)
-{
-}
-
-bool ScrollElasticityController::handleWheelEvent(const PlatformWheelEvent& wheelEvent)
-{
- if (wheelEvent.phase() == PlatformWheelEventPhaseBegan) {
- // First, check if we should rubber-band at all.
- if (m_client->pinnedInDirection(FloatSize(-wheelEvent.deltaX(), 0)) &&
- !shouldRubberBandInHorizontalDirection(wheelEvent))
- return false;
-
- m_inScrollGesture = true;
- m_momentumScrollInProgress = false;
- m_ignoreMomentumScrolls = false;
- m_lastMomentumScrollTimestamp = 0;
- m_momentumVelocity = FloatSize();
-
- IntSize stretchAmount = m_client->stretchAmount();
- m_stretchScrollForce.setWidth(reboundDeltaForElasticDelta(stretchAmount.width()));
- m_stretchScrollForce.setHeight(reboundDeltaForElasticDelta(stretchAmount.height()));
- m_overflowScrollDelta = FloatSize();
-
- stopSnapRubberbandTimer();
-
- return true;
- }
-
- if (wheelEvent.phase() == PlatformWheelEventPhaseEnded) {
- bool wasRubberBandInProgress = isRubberBandInProgress();
- // Call snapRubberBand() even if isRubberBandInProgress() is false. For example,
- // m_inScrollGesture may be true (and needs to be reset on a phase end) even if
- // isRubberBandInProgress() is not (e.g. the overhang area is empty).
- snapRubberBand();
- return wasRubberBandInProgress;
- }
-
- bool isMomentumScrollEvent = (wheelEvent.momentumPhase() != PlatformWheelEventPhaseNone);
- if (m_ignoreMomentumScrolls && (isMomentumScrollEvent || m_snapRubberbandTimerIsActive)) {
- if (wheelEvent.momentumPhase() == PlatformWheelEventPhaseEnded) {
- m_ignoreMomentumScrolls = false;
- return true;
- }
- return false;
- }
-
- float deltaX = m_overflowScrollDelta.width();
- float deltaY = m_overflowScrollDelta.height();
-
- // Reset overflow values because we may decide to remove delta at various points and put it into overflow.
- m_overflowScrollDelta = FloatSize();
-
- IntSize stretchAmount = m_client->stretchAmount();
- bool isVerticallyStretched = stretchAmount.height();
- bool isHorizontallyStretched = stretchAmount.width();
-
- float eventCoalescedDeltaX;
- float eventCoalescedDeltaY;
-
- if (isVerticallyStretched || isHorizontallyStretched) {
- eventCoalescedDeltaX = -wheelEvent.unacceleratedScrollingDeltaX();
- eventCoalescedDeltaY = -wheelEvent.unacceleratedScrollingDeltaY();
- } else {
- eventCoalescedDeltaX = -wheelEvent.deltaX();
- eventCoalescedDeltaY = -wheelEvent.deltaY();
- }
-
- deltaX += eventCoalescedDeltaX;
- deltaY += eventCoalescedDeltaY;
-
- // Slightly prefer scrolling vertically by applying the = case to deltaY
- if (fabsf(deltaY) >= fabsf(deltaX))
- deltaX = 0;
- else
- deltaY = 0;
-
- bool shouldStretch = false;
-
- PlatformWheelEventPhase momentumPhase = wheelEvent.momentumPhase();
-
- // If we are starting momentum scrolling then do some setup.
- if (!m_momentumScrollInProgress && (momentumPhase == PlatformWheelEventPhaseBegan || momentumPhase == PlatformWheelEventPhaseChanged)) {
- m_momentumScrollInProgress = true;
- // Start the snap rubber band timer if it's not running. This is needed to
- // snap back from the over scroll caused by momentum events.
- if (!m_snapRubberbandTimerIsActive && m_startTime == 0)
- snapRubberBand();
- }
-
- CFTimeInterval timeDelta = wheelEvent.timestamp() - m_lastMomentumScrollTimestamp;
- if (m_inScrollGesture || m_momentumScrollInProgress) {
- if (m_lastMomentumScrollTimestamp && timeDelta > 0 && timeDelta < scrollVelocityZeroingTimeout) {
- m_momentumVelocity.setWidth(eventCoalescedDeltaX / (float)timeDelta);
- m_momentumVelocity.setHeight(eventCoalescedDeltaY / (float)timeDelta);
- m_lastMomentumScrollTimestamp = wheelEvent.timestamp();
- } else {
- m_lastMomentumScrollTimestamp = wheelEvent.timestamp();
- m_momentumVelocity = FloatSize();
- }
-
- if (isVerticallyStretched) {
- if (!isHorizontallyStretched && m_client->pinnedInDirection(FloatSize(deltaX, 0))) {
- // Stretching only in the vertical.
- if (deltaY != 0 && (fabsf(deltaX / deltaY) < rubberbandDirectionLockStretchRatio))
- deltaX = 0;
- else if (fabsf(deltaX) < rubberbandMinimumRequiredDeltaBeforeStretch) {
- m_overflowScrollDelta.setWidth(m_overflowScrollDelta.width() + deltaX);
- deltaX = 0;
- } else
- m_overflowScrollDelta.setWidth(m_overflowScrollDelta.width() + deltaX);
- }
- } else if (isHorizontallyStretched) {
- // Stretching only in the horizontal.
- if (m_client->pinnedInDirection(FloatSize(0, deltaY))) {
- if (deltaX != 0 && (fabsf(deltaY / deltaX) < rubberbandDirectionLockStretchRatio))
- deltaY = 0;
- else if (fabsf(deltaY) < rubberbandMinimumRequiredDeltaBeforeStretch) {
- m_overflowScrollDelta.setHeight(m_overflowScrollDelta.height() + deltaY);
- deltaY = 0;
- } else
- m_overflowScrollDelta.setHeight(m_overflowScrollDelta.height() + deltaY);
- }
- } else {
- // Not stretching at all yet.
- if (m_client->pinnedInDirection(FloatSize(deltaX, deltaY))) {
- if (fabsf(deltaY) >= fabsf(deltaX)) {
- if (fabsf(deltaX) < rubberbandMinimumRequiredDeltaBeforeStretch) {
- m_overflowScrollDelta.setWidth(m_overflowScrollDelta.width() + deltaX);
- deltaX = 0;
- } else
- m_overflowScrollDelta.setWidth(m_overflowScrollDelta.width() + deltaX);
- }
- shouldStretch = true;
- }
- }
- }
-
- if (deltaX != 0 || deltaY != 0) {
- if (!(shouldStretch || isVerticallyStretched || isHorizontallyStretched)) {
- if (deltaY != 0) {
- deltaY *= scrollWheelMultiplier();
- m_client->immediateScrollBy(FloatSize(0, deltaY));
- }
- if (deltaX != 0) {
- deltaX *= scrollWheelMultiplier();
- m_client->immediateScrollBy(FloatSize(deltaX, 0));
- }
- } else {
- if (!m_client->allowsHorizontalStretching()) {
- deltaX = 0;
- eventCoalescedDeltaX = 0;
- } else if ((deltaX != 0) && !isHorizontallyStretched && !m_client->pinnedInDirection(FloatSize(deltaX, 0))) {
- deltaX *= scrollWheelMultiplier();
-
- m_client->immediateScrollByWithoutContentEdgeConstraints(FloatSize(deltaX, 0));
- deltaX = 0;
- }
-
- if (!m_client->allowsVerticalStretching()) {
- deltaY = 0;
- eventCoalescedDeltaY = 0;
- } else if ((deltaY != 0) && !isVerticallyStretched && !m_client->pinnedInDirection(FloatSize(0, deltaY))) {
- deltaY *= scrollWheelMultiplier();
-
- m_client->immediateScrollByWithoutContentEdgeConstraints(FloatSize(0, deltaY));
- deltaY = 0;
- }
-
- IntSize stretchAmount = m_client->stretchAmount();
-
- if (m_momentumScrollInProgress) {
- if ((m_client->pinnedInDirection(FloatSize(eventCoalescedDeltaX, eventCoalescedDeltaY)) || (fabsf(eventCoalescedDeltaX) + fabsf(eventCoalescedDeltaY) <= 0)) && m_lastMomentumScrollTimestamp) {
- m_ignoreMomentumScrolls = true;
- m_momentumScrollInProgress = false;
- snapRubberBand();
- }
- }
-
- m_stretchScrollForce.setWidth(m_stretchScrollForce.width() + deltaX);
- m_stretchScrollForce.setHeight(m_stretchScrollForce.height() + deltaY);
-
- FloatSize dampedDelta(ceilf(elasticDeltaForReboundDelta(m_stretchScrollForce.width())), ceilf(elasticDeltaForReboundDelta(m_stretchScrollForce.height())));
-
- m_client->immediateScrollByWithoutContentEdgeConstraints(dampedDelta - stretchAmount);
- }
- }
-
- if (m_momentumScrollInProgress && momentumPhase == PlatformWheelEventPhaseEnded) {
- m_momentumScrollInProgress = false;
- m_ignoreMomentumScrolls = false;
- m_lastMomentumScrollTimestamp = 0;
- }
-
- return true;
-}
-
-static inline float roundTowardZero(float num)
-{
- return num > 0 ? ceilf(num - 0.5f) : floorf(num + 0.5f);
-}
-
-static inline float roundToDevicePixelTowardZero(float num)
-{
- float roundedNum = roundf(num);
- if (fabs(num - roundedNum) < 0.125)
- num = roundedNum;
-
- return roundTowardZero(num);
-}
-
-void ScrollElasticityController::snapRubberBandTimerFired()
-{
- if (!m_momentumScrollInProgress || m_ignoreMomentumScrolls) {
- CFTimeInterval timeDelta = [NSDate timeIntervalSinceReferenceDate] - m_startTime;
-
- if (m_startStretch == FloatSize()) {
- m_startStretch = m_client->stretchAmount();
- if (m_startStretch == FloatSize()) {
- stopSnapRubberbandTimer();
-
- m_stretchScrollForce = FloatSize();
- m_startTime = 0;
- m_origOrigin = FloatPoint();
- m_origVelocity = FloatSize();
- return;
- }
-
- m_origOrigin = m_client->absoluteScrollPosition() - m_startStretch;
- m_origVelocity = m_momentumVelocity;
-
- // Just like normal scrolling, prefer vertical rubberbanding
- if (fabsf(m_origVelocity.height()) >= fabsf(m_origVelocity.width()))
- m_origVelocity.setWidth(0);
-
- // Don't rubber-band horizontally if it's not possible to scroll horizontally
- if (!m_client->canScrollHorizontally())
- m_origVelocity.setWidth(0);
-
- // Don't rubber-band vertically if it's not possible to scroll vertically
- if (!m_client->canScrollVertically())
- m_origVelocity.setHeight(0);
- }
-
- FloatPoint delta(roundToDevicePixelTowardZero(elasticDeltaForTimeDelta(m_startStretch.width(), -m_origVelocity.width(), (float)timeDelta)),
- roundToDevicePixelTowardZero(elasticDeltaForTimeDelta(m_startStretch.height(), -m_origVelocity.height(), (float)timeDelta)));
-
- if (fabs(delta.x()) >= 1 || fabs(delta.y()) >= 1) {
- m_client->immediateScrollByWithoutContentEdgeConstraints(FloatSize(delta.x(), delta.y()) - m_client->stretchAmount());
-
- FloatSize newStretch = m_client->stretchAmount();
-
- m_stretchScrollForce.setWidth(reboundDeltaForElasticDelta(newStretch.width()));
- m_stretchScrollForce.setHeight(reboundDeltaForElasticDelta(newStretch.height()));
- } else {
- m_client->immediateScrollBy(m_origOrigin - m_client->absoluteScrollPosition());
-
- stopSnapRubberbandTimer();
- m_stretchScrollForce = FloatSize();
- m_startTime = 0;
- m_startStretch = FloatSize();
- m_origOrigin = FloatPoint();
- m_origVelocity = FloatSize();
- }
- } else {
- m_startTime = [NSDate timeIntervalSinceReferenceDate];
- m_startStretch = FloatSize();
- }
-}
-
-bool ScrollElasticityController::isRubberBandInProgress() const
-{
- if (!m_inScrollGesture && !m_momentumScrollInProgress && !m_snapRubberbandTimerIsActive)
- return false;
-
- return !m_client->stretchAmount().isZero();
-}
-
-void ScrollElasticityController::stopSnapRubberbandTimer()
-{
- m_client->stopSnapRubberbandTimer();
- m_snapRubberbandTimerIsActive = false;
-}
-
-void ScrollElasticityController::snapRubberBand()
-{
- CFTimeInterval timeDelta = systemUptime() - m_lastMomentumScrollTimestamp;
- if (m_lastMomentumScrollTimestamp && timeDelta >= scrollVelocityZeroingTimeout)
- m_momentumVelocity = FloatSize();
-
- m_inScrollGesture = false;
-
- if (m_snapRubberbandTimerIsActive)
- return;
-
- m_startStretch = FloatSize();
- m_origOrigin = FloatPoint();
- m_origVelocity = FloatSize();
-
- // If there's no momentum scroll or stretch amount, no need to start the timer.
- if (!m_momentumScrollInProgress && m_client->stretchAmount() == FloatSize()) {
- m_startTime = 0;
- m_stretchScrollForce = FloatSize();
- return;
- }
-
- m_startTime = [NSDate timeIntervalSinceReferenceDate];
- m_client->startSnapRubberbandTimer();
- m_snapRubberbandTimerIsActive = true;
-}
-
-bool ScrollElasticityController::shouldRubberBandInHorizontalDirection(const PlatformWheelEvent& wheelEvent)
-{
- if (wheelEvent.deltaX() > 0)
- return m_client->shouldRubberBandInDirection(ScrollLeft);
- if (wheelEvent.deltaX() < 0)
- return m_client->shouldRubberBandInDirection(ScrollRight);
-
- return true;
-}
-
-} // namespace WebCore
-
-#endif // USE(RUBBER_BANDING)
diff --git a/chromium/third_party/WebKit/Source/core/platform/mac/ThemeMac.h b/chromium/third_party/WebKit/Source/core/platform/mac/ThemeMac.h
index dd342a06014..3e4d44b2934 100644
--- a/chromium/third_party/WebKit/Source/core/platform/mac/ThemeMac.h
+++ b/chromium/third_party/WebKit/Source/core/platform/mac/ThemeMac.h
@@ -26,7 +26,7 @@
#ifndef ThemeMac_h
#define ThemeMac_h
-#include "core/platform/Theme.h"
+#include "platform/Theme.h"
@interface NSFont(WebCoreTheme)
- (NSString*)webCoreFamilyName;
@@ -41,13 +41,13 @@ public:
virtual int baselinePositionAdjustment(ControlPart) const;
- virtual FontDescription controlFont(ControlPart, const Font&, float zoomFactor) const;
+ virtual FontDescription controlFont(ControlPart, const FontDescription&, float zoomFactor) const;
- virtual LengthSize controlSize(ControlPart, const Font&, const LengthSize&, float zoomFactor) const;
- virtual LengthSize minimumControlSize(ControlPart, const Font&, float zoomFactor) const;
+ virtual LengthSize controlSize(ControlPart, const FontDescription&, const LengthSize&, float zoomFactor) const;
+ virtual LengthSize minimumControlSize(ControlPart, const FontDescription&, float zoomFactor) const;
- virtual LengthBox controlPadding(ControlPart, const Font&, const LengthBox& zoomedBox, float zoomFactor) const;
- virtual LengthBox controlBorder(ControlPart, const Font&, const LengthBox& zoomedBox, float zoomFactor) const;
+ virtual LengthBox controlPadding(ControlPart, const FontDescription&, const LengthBox& zoomedBox, float zoomFactor) const;
+ virtual LengthBox controlBorder(ControlPart, const FontDescription&, const LengthBox& zoomedBox, float zoomFactor) const;
virtual bool controlRequiresPreWhiteSpace(ControlPart part) const { return part == PushButtonPart; }
diff --git a/chromium/third_party/WebKit/Source/core/platform/mac/ThemeMac.mm b/chromium/third_party/WebKit/Source/core/platform/mac/ThemeMac.mm
index 152e4e6fe83..e24ee65a2ae 100644
--- a/chromium/third_party/WebKit/Source/core/platform/mac/ThemeMac.mm
+++ b/chromium/third_party/WebKit/Source/core/platform/mac/ThemeMac.mm
@@ -27,11 +27,11 @@
#import "core/platform/mac/ThemeMac.h"
#import <Carbon/Carbon.h>
-#import "core/platform/ScrollView.h"
-#include "core/platform/graphics/GraphicsContextStateSaver.h"
-#import "core/platform/mac/BlockExceptions.h"
-#import "core/platform/mac/LocalCurrentGraphicsContext.h"
-#import "core/platform/mac/WebCoreNSCellExtras.h"
+#import "platform/graphics/GraphicsContextStateSaver.h"
+#import "platform/mac/BlockExceptions.h"
+#import "platform/mac/LocalCurrentGraphicsContext.h"
+#import "platform/mac/WebCoreNSCellExtras.h"
+#import "platform/scroll/ScrollView.h"
#include "wtf/StdLibExtras.h"
using namespace std;
@@ -106,9 +106,9 @@ Theme* platformTheme()
// Helper functions used by a bunch of different control parts.
-static NSControlSize controlSizeForFont(const Font& font)
+static NSControlSize controlSizeForFont(const FontDescription& fontDescription)
{
- int fontSize = font.pixelSize();
+ int fontSize = fontDescription.computedPixelSize();
if (fontSize >= 16)
return NSRegularControlSize;
if (fontSize >= 11)
@@ -129,9 +129,9 @@ static LengthSize sizeFromNSControlSize(NSControlSize nsControlSize, const Lengt
return result;
}
-static LengthSize sizeFromFont(const Font& font, const LengthSize& zoomedSize, float zoomFactor, const IntSize* sizes)
+static LengthSize sizeFromFont(const FontDescription& fontDescription, const LengthSize& zoomedSize, float zoomFactor, const IntSize* sizes)
{
- return sizeFromNSControlSize(controlSizeForFont(font), zoomedSize, zoomFactor, sizes);
+ return sizeFromNSControlSize(controlSizeForFont(fontDescription), zoomedSize, zoomFactor, sizes);
}
static ControlSize controlSizeFromPixelSize(const IntSize* sizes, const IntSize& minZoomedSize, float zoomFactor)
@@ -241,14 +241,14 @@ static const int* checkboxMargins(NSControlSize controlSize)
return margins[controlSize];
}
-static LengthSize checkboxSize(const Font& font, const LengthSize& zoomedSize, float zoomFactor)
+static LengthSize checkboxSize(const FontDescription& fontDescription, const LengthSize& zoomedSize, float zoomFactor)
{
// If the width and height are both specified, then we have nothing to do.
if (!zoomedSize.width().isIntrinsicOrAuto() && !zoomedSize.height().isIntrinsicOrAuto())
return zoomedSize;
// Use the font size to determine the intrinsic width of the control.
- return sizeFromFont(font, zoomedSize, zoomFactor, checkboxSizes());
+ return sizeFromFont(fontDescription, zoomedSize, zoomFactor, checkboxSizes());
}
static NSButtonCell *checkbox(ControlStates states, const IntRect& zoomedRect, float zoomFactor)
@@ -325,14 +325,14 @@ static const int* radioMargins(NSControlSize controlSize)
return margins[controlSize];
}
-static LengthSize radioSize(const Font& font, const LengthSize& zoomedSize, float zoomFactor)
+static LengthSize radioSize(const FontDescription& fontDescription, const LengthSize& zoomedSize, float zoomFactor)
{
// If the width and height are both specified, then we have nothing to do.
if (!zoomedSize.width().isIntrinsicOrAuto() && !zoomedSize.height().isIntrinsicOrAuto())
return zoomedSize;
// Use the font size to determine the intrinsic width of the control.
- return sizeFromFont(font, zoomedSize, zoomFactor, radioSizes());
+ return sizeFromFont(fontDescription, zoomedSize, zoomFactor, radioSizes());
}
static NSButtonCell *radio(ControlStates states, const IntRect& zoomedRect, float zoomFactor)
@@ -469,7 +469,6 @@ static void paintButton(ControlPart part, ControlStates states, GraphicsContext*
LocalCurrentGraphicsContext localContext(context);
NSView *view = ThemeMac::ensuredView(scrollView);
- NSWindow *window = [view window];
[buttonCell drawWithFrame:NSRect(inflatedRect) inView:view];
#if !BUTTON_CELL_DRAW_WITH_FRAME_DRAWS_FOCUS_RING
@@ -491,9 +490,9 @@ static const IntSize* stepperSizes()
// We don't use controlSizeForFont() for steppers because the stepper height
// should be equal to or less than the corresponding text field height,
-static NSControlSize stepperControlSizeForFont(const Font& font)
+static NSControlSize stepperControlSizeForFont(const FontDescription& fontDescription)
{
- int fontSize = font.pixelSize();
+ int fontSize = fontDescription.computedPixelSize();
if (fontSize >= 18)
return NSRegularControlSize;
if (fontSize >= 13)
@@ -567,45 +566,45 @@ int ThemeMac::baselinePositionAdjustment(ControlPart part) const
return Theme::baselinePositionAdjustment(part);
}
-FontDescription ThemeMac::controlFont(ControlPart part, const Font& font, float zoomFactor) const
+FontDescription ThemeMac::controlFont(ControlPart part, const FontDescription& fontDescription, float zoomFactor) const
{
switch (part) {
case PushButtonPart: {
- FontDescription fontDescription;
- fontDescription.setIsAbsoluteSize(true);
- fontDescription.setGenericFamily(FontDescription::SerifFamily);
-
- NSFont* nsFont = [NSFont systemFontOfSize:[NSFont systemFontSizeForControlSize:controlSizeForFont(font)]];
- fontDescription.firstFamily().setFamily([nsFont webCoreFamilyName]);
- fontDescription.setComputedSize([nsFont pointSize] * zoomFactor);
- fontDescription.setSpecifiedSize([nsFont pointSize] * zoomFactor);
- return fontDescription;
+ FontDescription result;
+ result.setIsAbsoluteSize(true);
+ result.setGenericFamily(FontDescription::SerifFamily);
+
+ NSFont* nsFont = [NSFont systemFontOfSize:[NSFont systemFontSizeForControlSize:controlSizeForFont(fontDescription)]];
+ result.firstFamily().setFamily([nsFont webCoreFamilyName]);
+ result.setComputedSize([nsFont pointSize] * zoomFactor);
+ result.setSpecifiedSize([nsFont pointSize] * zoomFactor);
+ return result;
}
default:
- return Theme::controlFont(part, font, zoomFactor);
+ return Theme::controlFont(part, fontDescription, zoomFactor);
}
}
-LengthSize ThemeMac::controlSize(ControlPart part, const Font& font, const LengthSize& zoomedSize, float zoomFactor) const
+LengthSize ThemeMac::controlSize(ControlPart part, const FontDescription& fontDescription, const LengthSize& zoomedSize, float zoomFactor) const
{
switch (part) {
case CheckboxPart:
- return checkboxSize(font, zoomedSize, zoomFactor);
+ return checkboxSize(fontDescription, zoomedSize, zoomFactor);
case RadioPart:
- return radioSize(font, zoomedSize, zoomFactor);
+ return radioSize(fontDescription, zoomedSize, zoomFactor);
case PushButtonPart:
// Height is reset to auto so that specified heights can be ignored.
- return sizeFromFont(font, LengthSize(zoomedSize.width(), Length()), zoomFactor, buttonSizes());
+ return sizeFromFont(fontDescription, LengthSize(zoomedSize.width(), Length()), zoomFactor, buttonSizes());
case InnerSpinButtonPart:
if (!zoomedSize.width().isIntrinsicOrAuto() && !zoomedSize.height().isIntrinsicOrAuto())
return zoomedSize;
- return sizeFromNSControlSize(stepperControlSizeForFont(font), zoomedSize, zoomFactor, stepperSizes());
+ return sizeFromNSControlSize(stepperControlSizeForFont(fontDescription), zoomedSize, zoomFactor, stepperSizes());
default:
return zoomedSize;
}
}
-LengthSize ThemeMac::minimumControlSize(ControlPart part, const Font& font, float zoomFactor) const
+LengthSize ThemeMac::minimumControlSize(ControlPart part, const FontDescription& fontDescription, float zoomFactor) const
{
switch (part) {
case SquareButtonPart:
@@ -617,22 +616,22 @@ LengthSize ThemeMac::minimumControlSize(ControlPart part, const Font& font, floa
Length(static_cast<int>(base.height() * zoomFactor), Fixed));
}
default:
- return Theme::minimumControlSize(part, font, zoomFactor);
+ return Theme::minimumControlSize(part, fontDescription, zoomFactor);
}
}
-LengthBox ThemeMac::controlBorder(ControlPart part, const Font& font, const LengthBox& zoomedBox, float zoomFactor) const
+LengthBox ThemeMac::controlBorder(ControlPart part, const FontDescription& fontDescription, const LengthBox& zoomedBox, float zoomFactor) const
{
switch (part) {
case SquareButtonPart:
case ButtonPart:
return LengthBox(0, zoomedBox.right().value(), 0, zoomedBox.left().value());
default:
- return Theme::controlBorder(part, font, zoomedBox, zoomFactor);
+ return Theme::controlBorder(part, fontDescription, zoomedBox, zoomFactor);
}
}
-LengthBox ThemeMac::controlPadding(ControlPart part, const Font& font, const LengthBox& zoomedBox, float zoomFactor) const
+LengthBox ThemeMac::controlPadding(ControlPart part, const FontDescription& fontDescription, const LengthBox& zoomedBox, float zoomFactor) const
{
switch (part) {
case PushButtonPart: {
@@ -645,7 +644,7 @@ LengthBox ThemeMac::controlPadding(ControlPart part, const Font& font, const Len
return LengthBox(0, padding, 0, padding);
}
default:
- return Theme::controlPadding(part, font, zoomedBox, zoomFactor);
+ return Theme::controlPadding(part, fontDescription, zoomedBox, zoomFactor);
}
}
diff --git a/chromium/third_party/WebKit/Source/core/platform/mac/WebCoreNSCellExtras.h b/chromium/third_party/WebKit/Source/core/platform/mac/WebCoreNSCellExtras.h
deleted file mode 100644
index 030c0008f4c..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/mac/WebCoreNSCellExtras.h
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Copyright (C) 2011, 2012 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#import <AppKit/AppKit.h>
-
-#define BUTTON_CELL_DRAW_WITH_FRAME_DRAWS_FOCUS_RING 1
-
-#if !BUTTON_CELL_DRAW_WITH_FRAME_DRAWS_FOCUS_RING
-
-// FIXME: Might want to use this on Mac once we only support OS X 10.8+
-@interface NSCell (WebCoreFocusRingDrawing)
-- (void)_web_drawFocusRingWithFrame:(NSRect)cellFrame inView:(NSView *)controlView;
-@end
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/mac/WebFontCache.h b/chromium/third_party/WebKit/Source/core/platform/mac/WebFontCache.h
deleted file mode 100644
index 822c1b51b28..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/mac/WebFontCache.h
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Copyright (C) 2006, 2008 Apple Inc. All rights reserved.
- * Copyright (C) 2007 Nicholas Shanks <webkit@nickshanks.com>
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#import <AppKit/NSFontManager.h>
-#import <wtf/Vector.h>
-
-// This interface exists so that third party products (like Silk) can patch in to an Obj-C method to manipulate WebKit's font caching/substitution.
-@interface WebFontCache : NSObject
-+ (NSFont *)fontWithFamily:(NSString *)desiredFamily traits:(NSFontTraitMask)desiredTraits weight:(int)desiredWeight size:(float)size;
-+ (void)getTraits:(Vector<unsigned>&)traitsMasks inFamily:(NSString *)desiredFamily;
-
-// This older version of the interface is relied upon by some clients. WebCore doesn't use it.
-+ (NSFont *)fontWithFamily:(NSString *)desiredFamily traits:(NSFontTraitMask)desiredTraits size:(float)size;
-@end
diff --git a/chromium/third_party/WebKit/Source/core/platform/mac/WebFontCache.mm b/chromium/third_party/WebKit/Source/core/platform/mac/WebFontCache.mm
deleted file mode 100644
index 6f85e7b341e..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/mac/WebFontCache.mm
+++ /dev/null
@@ -1,294 +0,0 @@
-/*
- * Copyright (C) 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
- * Copyright (C) 2007 Nicholas Shanks <webkit@nickshanks.com>
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#import "config.h"
-#import "core/platform/mac/WebFontCache.h"
-
-#import <AppKit/AppKit.h>
-#import <Foundation/Foundation.h>
-#import <math.h>
-#import "core/platform/graphics/FontTraitsMask.h"
-#import <wtf/UnusedParam.h>
-
-using namespace WebCore;
-
-
-#define SYNTHESIZED_FONT_TRAITS (NSBoldFontMask | NSItalicFontMask)
-
-#define IMPORTANT_FONT_TRAITS (0 \
- | NSCompressedFontMask \
- | NSCondensedFontMask \
- | NSExpandedFontMask \
- | NSItalicFontMask \
- | NSNarrowFontMask \
- | NSPosterFontMask \
- | NSSmallCapsFontMask \
-)
-
-static BOOL acceptableChoice(NSFontTraitMask desiredTraits, NSFontTraitMask candidateTraits)
-{
- desiredTraits &= ~SYNTHESIZED_FONT_TRAITS;
- return (candidateTraits & desiredTraits) == desiredTraits;
-}
-
-static BOOL betterChoice(NSFontTraitMask desiredTraits, int desiredWeight,
- NSFontTraitMask chosenTraits, int chosenWeight,
- NSFontTraitMask candidateTraits, int candidateWeight)
-{
- if (!acceptableChoice(desiredTraits, candidateTraits))
- return NO;
-
- // A list of the traits we care about.
- // The top item in the list is the worst trait to mismatch; if a font has this
- // and we didn't ask for it, we'd prefer any other font in the family.
- const NSFontTraitMask masks[] = {
- NSPosterFontMask,
- NSSmallCapsFontMask,
- NSItalicFontMask,
- NSCompressedFontMask,
- NSCondensedFontMask,
- NSExpandedFontMask,
- NSNarrowFontMask,
- 0
- };
-
- int i = 0;
- NSFontTraitMask mask;
- while ((mask = masks[i++])) {
- BOOL desired = (desiredTraits & mask) != 0;
- BOOL chosenHasUnwantedTrait = desired != ((chosenTraits & mask) != 0);
- BOOL candidateHasUnwantedTrait = desired != ((candidateTraits & mask) != 0);
- if (!candidateHasUnwantedTrait && chosenHasUnwantedTrait)
- return YES;
- if (!chosenHasUnwantedTrait && candidateHasUnwantedTrait)
- return NO;
- }
-
- int chosenWeightDeltaMagnitude = abs(chosenWeight - desiredWeight);
- int candidateWeightDeltaMagnitude = abs(candidateWeight - desiredWeight);
-
- // If both are the same distance from the desired weight, prefer the candidate if it is further from medium.
- if (chosenWeightDeltaMagnitude == candidateWeightDeltaMagnitude)
- return abs(candidateWeight - 6) > abs(chosenWeight - 6);
-
- // Otherwise, prefer the one closer to the desired weight.
- return candidateWeightDeltaMagnitude < chosenWeightDeltaMagnitude;
-}
-
-static inline FontTraitsMask toTraitsMask(NSFontTraitMask appKitTraits, NSInteger appKitWeight)
-{
- return static_cast<FontTraitsMask>(((appKitTraits & NSFontItalicTrait) ? FontStyleItalicMask : FontStyleNormalMask)
- | FontVariantNormalMask
- | (appKitWeight == 1 ? FontWeight100Mask :
- appKitWeight == 2 ? FontWeight200Mask :
- appKitWeight <= 4 ? FontWeight300Mask :
- appKitWeight == 5 ? FontWeight400Mask :
- appKitWeight == 6 ? FontWeight500Mask :
- appKitWeight <= 8 ? FontWeight600Mask :
- appKitWeight == 9 ? FontWeight700Mask :
- appKitWeight <= 11 ? FontWeight800Mask :
- FontWeight900Mask));
-}
-
-@implementation WebFontCache
-
-+ (void)getTraits:(Vector<unsigned>&)traitsMasks inFamily:(NSString *)desiredFamily
-{
- NSFontManager *fontManager = [NSFontManager sharedFontManager];
-
- NSEnumerator *e = [[fontManager availableFontFamilies] objectEnumerator];
- NSString *availableFamily;
- while ((availableFamily = [e nextObject])) {
- if ([desiredFamily caseInsensitiveCompare:availableFamily] == NSOrderedSame)
- break;
- }
-
- if (!availableFamily) {
- // Match by PostScript name.
- NSEnumerator *availableFonts = [[fontManager availableFonts] objectEnumerator];
- NSString *availableFont;
- while ((availableFont = [availableFonts nextObject])) {
- if ([desiredFamily caseInsensitiveCompare:availableFont] == NSOrderedSame) {
- NSFont *font = [NSFont fontWithName:availableFont size:10];
- NSInteger weight = [fontManager weightOfFont:font];
- traitsMasks.append(toTraitsMask([fontManager traitsOfFont:font], weight));
- break;
- }
- }
- return;
- }
-
- NSArray *fonts = [fontManager availableMembersOfFontFamily:availableFamily];
- unsigned n = [fonts count];
- unsigned i;
- for (i = 0; i < n; i++) {
- NSArray *fontInfo = [fonts objectAtIndex:i];
- // Array indices must be hard coded because of lame AppKit API.
- NSInteger fontWeight = [[fontInfo objectAtIndex:2] intValue];
-
- NSFontTraitMask fontTraits = [[fontInfo objectAtIndex:3] unsignedIntValue];
- traitsMasks.append(toTraitsMask(fontTraits, fontWeight));
- }
-}
-
-// Family name is somewhat of a misnomer here. We first attempt to find an exact match
-// comparing the desiredFamily to the PostScript name of the installed fonts. If that fails
-// we then do a search based on the family names of the installed fonts.
-+ (NSFont *)internalFontWithFamily:(NSString *)desiredFamily traits:(NSFontTraitMask)desiredTraits weight:(int)desiredWeight size:(float)size
-{
- NSFontManager *fontManager = [NSFontManager sharedFontManager];
-
- // Do a simple case insensitive search for a matching font family.
- // NSFontManager requires exact name matches.
- // This addresses the problem of matching arial to Arial, etc., but perhaps not all the issues.
- NSEnumerator *e = [[fontManager availableFontFamilies] objectEnumerator];
- NSString *availableFamily;
- while ((availableFamily = [e nextObject])) {
- if ([desiredFamily caseInsensitiveCompare:availableFamily] == NSOrderedSame)
- break;
- }
-
- if (!availableFamily) {
- // Match by PostScript name.
- NSEnumerator *availableFonts = [[fontManager availableFonts] objectEnumerator];
- NSString *availableFont;
- NSFont *nameMatchedFont = nil;
- NSFontTraitMask desiredTraitsForNameMatch = desiredTraits | (desiredWeight >= 7 ? NSBoldFontMask : 0);
- while ((availableFont = [availableFonts nextObject])) {
- if ([desiredFamily caseInsensitiveCompare:availableFont] == NSOrderedSame) {
- nameMatchedFont = [NSFont fontWithName:availableFont size:size];
-
- // Special case Osaka-Mono. According to <rdar://problem/3999467>, we need to
- // treat Osaka-Mono as fixed pitch.
- if ([desiredFamily caseInsensitiveCompare:@"Osaka-Mono"] == NSOrderedSame && desiredTraitsForNameMatch == 0)
- return nameMatchedFont;
-
- NSFontTraitMask traits = [fontManager traitsOfFont:nameMatchedFont];
- if ((traits & desiredTraitsForNameMatch) == desiredTraitsForNameMatch)
- return [fontManager convertFont:nameMatchedFont toHaveTrait:desiredTraitsForNameMatch];
-
- availableFamily = [nameMatchedFont familyName];
- break;
- }
- }
- }
-
- // Found a family, now figure out what weight and traits to use.
- BOOL choseFont = false;
- int chosenWeight = 0;
- NSFontTraitMask chosenTraits = 0;
- NSString *chosenFullName = 0;
-
- NSArray *fonts = [fontManager availableMembersOfFontFamily:availableFamily];
- unsigned n = [fonts count];
- unsigned i;
- for (i = 0; i < n; i++) {
- NSArray *fontInfo = [fonts objectAtIndex:i];
-
- // Array indices must be hard coded because of lame AppKit API.
- NSString *fontFullName = [fontInfo objectAtIndex:0];
- NSInteger fontWeight = [[fontInfo objectAtIndex:2] intValue];
-
- NSFontTraitMask fontTraits = [[fontInfo objectAtIndex:3] unsignedIntValue];
-
- BOOL newWinner;
- if (!choseFont)
- newWinner = acceptableChoice(desiredTraits, fontTraits);
- else
- newWinner = betterChoice(desiredTraits, desiredWeight, chosenTraits, chosenWeight, fontTraits, fontWeight);
-
- if (newWinner) {
- choseFont = YES;
- chosenWeight = fontWeight;
- chosenTraits = fontTraits;
- chosenFullName = fontFullName;
-
- if (chosenWeight == desiredWeight && (chosenTraits & IMPORTANT_FONT_TRAITS) == (desiredTraits & IMPORTANT_FONT_TRAITS))
- break;
- }
- }
-
- if (!choseFont)
- return nil;
-
- NSFont *font = [NSFont fontWithName:chosenFullName size:size];
-
- if (!font)
- return nil;
-
- NSFontTraitMask actualTraits = 0;
- if (desiredTraits & NSFontItalicTrait)
- actualTraits = [fontManager traitsOfFont:font];
- int actualWeight = [fontManager weightOfFont:font];
-
- bool syntheticBold = desiredWeight >= 7 && actualWeight < 7;
- bool syntheticOblique = (desiredTraits & NSFontItalicTrait) && !(actualTraits & NSFontItalicTrait);
-
- // There are some malformed fonts that will be correctly returned by -fontWithFamily:traits:weight:size: as a match for a particular trait,
- // though -[NSFontManager traitsOfFont:] incorrectly claims the font does not have the specified trait. This could result in applying
- // synthetic bold on top of an already-bold font, as reported in <http://bugs.webkit.org/show_bug.cgi?id=6146>. To work around this
- // problem, if we got an apparent exact match, but the requested traits aren't present in the matched font, we'll try to get a font from
- // the same family without those traits (to apply the synthetic traits to later).
- NSFontTraitMask nonSyntheticTraits = desiredTraits;
-
- if (syntheticBold)
- nonSyntheticTraits &= ~NSBoldFontMask;
-
- if (syntheticOblique)
- nonSyntheticTraits &= ~NSItalicFontMask;
-
- if (nonSyntheticTraits != desiredTraits) {
- NSFont *fontWithoutSyntheticTraits = [fontManager fontWithFamily:availableFamily traits:nonSyntheticTraits weight:chosenWeight size:size];
- if (fontWithoutSyntheticTraits)
- font = fontWithoutSyntheticTraits;
- }
-
- return font;
-}
-
-+ (NSFont *)fontWithFamily:(NSString *)desiredFamily traits:(NSFontTraitMask)desiredTraits weight:(int)desiredWeight size:(float)size
-{
- NSFont *font = [self internalFontWithFamily:desiredFamily traits:desiredTraits weight:desiredWeight size:size];
- if (font)
- return font;
-
- // Auto activate the font before looking for it a second time.
- // Ignore the result because we want to use our own algorithm to actually find the font.
- [NSFont fontWithName:desiredFamily size:size];
-
- return [self internalFontWithFamily:desiredFamily traits:desiredTraits weight:desiredWeight size:size];
-}
-
-+ (NSFont *)fontWithFamily:(NSString *)desiredFamily traits:(NSFontTraitMask)desiredTraits size:(float)size
-{
- int desiredWeight = (desiredTraits & NSBoldFontMask) ? 9 : 5;
- return [self fontWithFamily:desiredFamily traits:desiredTraits weight:desiredWeight size:size];
-}
-
-@end
diff --git a/chromium/third_party/WebKit/Source/core/platform/mediastream/MediaConstraints.h b/chromium/third_party/WebKit/Source/core/platform/mediastream/MediaConstraints.h
deleted file mode 100644
index cb4d2643826..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/mediastream/MediaConstraints.h
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * 3. Neither the name of Google Inc. nor the names of its contributors
- * may be used to endorse or promote products derived from this
- * software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef MediaConstraints_h
-#define MediaConstraints_h
-
-#include "wtf/RefCounted.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-struct MediaConstraint {
- MediaConstraint(String name, String value)
- : m_name(name)
- , m_value(value)
- {
- }
-
- String m_name;
- String m_value;
-};
-
-class MediaConstraints : public RefCounted<MediaConstraints> {
-public:
- virtual ~MediaConstraints() { }
-
- virtual void getMandatoryConstraints(Vector<MediaConstraint>&) const = 0;
- virtual void getOptionalConstraints(Vector<MediaConstraint>&) const = 0;
-
- virtual bool getMandatoryConstraintValue(const String& name, String& value) const = 0;
- virtual bool getOptionalConstraintValue(const String& name, String& value) const = 0;
-
-protected:
- MediaConstraints() { }
-};
-
-} // namespace WebCore
-
-#endif // MediaConstraints_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/mediastream/MediaStreamCenter.cpp b/chromium/third_party/WebKit/Source/core/platform/mediastream/MediaStreamCenter.cpp
index 08180822729..3baadb439b6 100644
--- a/chromium/third_party/WebKit/Source/core/platform/mediastream/MediaStreamCenter.cpp
+++ b/chromium/third_party/WebKit/Source/core/platform/mediastream/MediaStreamCenter.cpp
@@ -53,7 +53,7 @@ MediaStreamCenter& MediaStreamCenter::instance()
}
MediaStreamCenter::MediaStreamCenter()
- : m_private(adoptPtr(WebKit::Platform::current()->createMediaStreamCenter(this)))
+ : m_private(adoptPtr(blink::Platform::current()->createMediaStreamCenter(this)))
{
}
@@ -69,10 +69,13 @@ bool MediaStreamCenter::getMediaStreamTrackSources(PassRefPtr<MediaStreamTrackSo
void MediaStreamCenter::didSetMediaStreamTrackEnabled(MediaStreamDescriptor* stream, MediaStreamComponent* component)
{
if (m_private) {
- if (component->enabled())
+ if (component->enabled()) {
m_private->didEnableMediaStreamTrack(stream, component);
- else
+ m_private->didEnableMediaStreamTrack(component);
+ } else {
m_private->didDisableMediaStreamTrack(stream, component);
+ m_private->didDisableMediaStreamTrack(component);
+ }
}
}
@@ -88,24 +91,30 @@ bool MediaStreamCenter::didRemoveMediaStreamTrack(MediaStreamDescriptor* stream,
void MediaStreamCenter::didStopLocalMediaStream(MediaStreamDescriptor* stream)
{
- if (m_private) {
+ if (m_private)
m_private->didStopLocalMediaStream(stream);
- for (unsigned i = 0; i < stream->numberOfAudioComponents(); i++)
- stream->audioComponent(i)->source()->setReadyState(MediaStreamSource::ReadyStateEnded);
- for (unsigned i = 0; i < stream->numberOfVideoComponents(); i++)
- stream->videoComponent(i)->source()->setReadyState(MediaStreamSource::ReadyStateEnded);
- }
+}
+
+bool MediaStreamCenter::didStopMediaStreamTrack(MediaStreamComponent* track)
+{
+ return m_private && m_private->didStopMediaStreamTrack(track);
}
void MediaStreamCenter::didCreateMediaStream(MediaStreamDescriptor* stream)
{
if (m_private) {
- WebKit::WebMediaStream webStream(stream);
+ blink::WebMediaStream webStream(stream);
m_private->didCreateMediaStream(webStream);
}
}
-void MediaStreamCenter::stopLocalMediaStream(const WebKit::WebMediaStream& webStream)
+void MediaStreamCenter::didCreateMediaStreamTrack(MediaStreamComponent* track)
+{
+ if (m_private)
+ m_private->didCreateMediaStreamTrack(track);
+}
+
+void MediaStreamCenter::stopLocalMediaStream(const blink::WebMediaStream& webStream)
{
MediaStreamDescriptor* stream = webStream;
MediaStreamDescriptorClient* client = stream->client();
diff --git a/chromium/third_party/WebKit/Source/core/platform/mediastream/MediaStreamCenter.h b/chromium/third_party/WebKit/Source/core/platform/mediastream/MediaStreamCenter.h
index b215dec4e78..7a3630b1adb 100644
--- a/chromium/third_party/WebKit/Source/core/platform/mediastream/MediaStreamCenter.h
+++ b/chromium/third_party/WebKit/Source/core/platform/mediastream/MediaStreamCenter.h
@@ -32,14 +32,13 @@
#ifndef MediaStreamCenter_h
#define MediaStreamCenter_h
-#include "modules/mediastream/SourceInfo.h"
#include "public/platform/WebMediaStreamCenterClient.h"
#include "public/platform/WebVector.h"
#include "wtf/OwnPtr.h"
#include "wtf/PassRefPtr.h"
#include "wtf/text/WTFString.h"
-namespace WebKit {
+namespace blink {
class WebMediaStream;
class WebMediaStreamCenter;
class WebMediaStreamTrack;
@@ -51,26 +50,30 @@ class MediaStreamComponent;
class MediaStreamDescriptor;
class MediaStreamTrackSourcesRequest;
-class MediaStreamCenter : public WebKit::WebMediaStreamCenterClient {
+class MediaStreamCenter : public blink::WebMediaStreamCenterClient {
public:
~MediaStreamCenter();
static MediaStreamCenter& instance();
bool getMediaStreamTrackSources(PassRefPtr<MediaStreamTrackSourcesRequest>);
+
+ void didCreateMediaStreamTrack(MediaStreamComponent*);
void didSetMediaStreamTrackEnabled(MediaStreamDescriptor*, MediaStreamComponent*);
+ bool didStopMediaStreamTrack(MediaStreamComponent*);
+
+ void didCreateMediaStream(MediaStreamDescriptor*);
bool didAddMediaStreamTrack(MediaStreamDescriptor*, MediaStreamComponent*);
bool didRemoveMediaStreamTrack(MediaStreamDescriptor*, MediaStreamComponent*);
void didStopLocalMediaStream(MediaStreamDescriptor*);
- void didCreateMediaStream(MediaStreamDescriptor*);
- // WebKit::WebMediaStreamCenterClient
- virtual void stopLocalMediaStream(const WebKit::WebMediaStream&) OVERRIDE;
+ // blink::WebMediaStreamCenterClient
+ virtual void stopLocalMediaStream(const blink::WebMediaStream&) OVERRIDE;
private:
MediaStreamCenter();
- OwnPtr<WebKit::WebMediaStreamCenter> m_private;
+ OwnPtr<blink::WebMediaStreamCenter> m_private;
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/mediastream/MediaStreamComponent.cpp b/chromium/third_party/WebKit/Source/core/platform/mediastream/MediaStreamComponent.cpp
deleted file mode 100644
index 722366e76d8..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/mediastream/MediaStreamComponent.cpp
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- * Copyright (C) 2011 Ericsson AB. All rights reserved.
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/platform/mediastream/MediaStreamComponent.h"
-
-#include "core/platform/UUID.h"
-#include "core/platform/audio/AudioBus.h"
-#include "core/platform/mediastream/MediaStreamSource.h"
-#include "public/web/WebAudioSourceProvider.h"
-
-namespace WebCore {
-
-PassRefPtr<MediaStreamComponent> MediaStreamComponent::create(PassRefPtr<MediaStreamSource> source)
-{
- return adoptRef(new MediaStreamComponent(createCanonicalUUIDString(), 0, source));
-}
-
-PassRefPtr<MediaStreamComponent> MediaStreamComponent::create(const String& id, PassRefPtr<MediaStreamSource> source)
-{
- return adoptRef(new MediaStreamComponent(id, 0, source));
-}
-
-PassRefPtr<MediaStreamComponent> MediaStreamComponent::create(MediaStreamDescriptor* stream, PassRefPtr<MediaStreamSource> source)
-{
- return adoptRef(new MediaStreamComponent(createCanonicalUUIDString(), stream, source));
-}
-
-MediaStreamComponent::MediaStreamComponent(const String& id, MediaStreamDescriptor* stream, PassRefPtr<MediaStreamSource> source)
- : m_stream(stream)
- , m_source(source)
- , m_id(id)
- , m_enabled(true)
-{
- ASSERT(m_id.length());
-}
-
-#if ENABLE(WEB_AUDIO)
-void MediaStreamComponent::AudioSourceProviderImpl::wrap(WebKit::WebAudioSourceProvider* provider)
-{
- MutexLocker locker(m_provideInputLock);
- m_webAudioSourceProvider = provider;
-}
-
-void MediaStreamComponent::AudioSourceProviderImpl::provideInput(AudioBus* bus, size_t framesToProcess)
-{
- ASSERT(bus);
- if (!bus)
- return;
-
- MutexTryLocker tryLocker(m_provideInputLock);
- if (!tryLocker.locked() || !m_webAudioSourceProvider) {
- bus->zero();
- return;
- }
-
- // Wrap the AudioBus channel data using WebVector.
- size_t n = bus->numberOfChannels();
- WebKit::WebVector<float*> webAudioData(n);
- for (size_t i = 0; i < n; ++i)
- webAudioData[i] = bus->channel(i)->mutableData();
-
- m_webAudioSourceProvider->provideInput(webAudioData, framesToProcess);
-}
-#endif // #if ENABLE(WEB_AUDIO)
-
-} // namespace WebCore
-
diff --git a/chromium/third_party/WebKit/Source/core/platform/mediastream/MediaStreamComponent.h b/chromium/third_party/WebKit/Source/core/platform/mediastream/MediaStreamComponent.h
deleted file mode 100644
index 90a9deecd35..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/mediastream/MediaStreamComponent.h
+++ /dev/null
@@ -1,110 +0,0 @@
-/*
- * Copyright (C) 2011 Ericsson AB. All rights reserved.
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * 3. Neither the name of Ericsson nor the names of its contributors
- * may be used to endorse or promote products derived from this
- * software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef MediaStreamComponent_h
-#define MediaStreamComponent_h
-
-#include "core/platform/audio/AudioSourceProvider.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/ThreadingPrimitives.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebKit {
-class WebAudioSourceProvider;
-}
-
-namespace WebCore {
-
-class MediaStreamDescriptor;
-class MediaStreamSource;
-
-class MediaStreamComponent : public RefCounted<MediaStreamComponent> {
-public:
- static PassRefPtr<MediaStreamComponent> create(PassRefPtr<MediaStreamSource>);
- static PassRefPtr<MediaStreamComponent> create(const String& id, PassRefPtr<MediaStreamSource>);
- static PassRefPtr<MediaStreamComponent> create(MediaStreamDescriptor*, PassRefPtr<MediaStreamSource>);
-
- MediaStreamDescriptor* stream() const { return m_stream; }
- void setStream(MediaStreamDescriptor* stream) { ASSERT(!m_stream && stream); m_stream = stream; }
-
- MediaStreamSource* source() const { return m_source.get(); }
-
- String id() const { return m_id; }
- bool enabled() const { return m_enabled; }
- void setEnabled(bool enabled) { m_enabled = enabled; }
-
-#if ENABLE(WEB_AUDIO)
- AudioSourceProvider* audioSourceProvider() { return &m_sourceProvider; }
- void setSourceProvider(WebKit::WebAudioSourceProvider* provider) { m_sourceProvider.wrap(provider); }
-#endif // ENABLE(WEB_AUDIO)
-
-private:
- MediaStreamComponent(const String& id, MediaStreamDescriptor*, PassRefPtr<MediaStreamSource>);
-
-#if ENABLE(WEB_AUDIO)
- // AudioSourceProviderImpl wraps a WebAudioSourceProvider::provideInput()
- // calls into chromium to get a rendered audio stream.
-
- class AudioSourceProviderImpl : public AudioSourceProvider {
- public:
- AudioSourceProviderImpl()
- : m_webAudioSourceProvider(0)
- {
- }
-
- virtual ~AudioSourceProviderImpl() { }
-
- // Wraps the given WebKit::WebAudioSourceProvider to WebCore::AudioSourceProvider.
- void wrap(WebKit::WebAudioSourceProvider*);
-
- // WebCore::AudioSourceProvider
- virtual void provideInput(WebCore::AudioBus*, size_t framesToProcess);
-
- private:
- WebKit::WebAudioSourceProvider* m_webAudioSourceProvider;
- Mutex m_provideInputLock;
- };
-
- AudioSourceProviderImpl m_sourceProvider;
-#endif // ENABLE(WEB_AUDIO)
-
- MediaStreamDescriptor* m_stream;
- RefPtr<MediaStreamSource> m_source;
- String m_id;
- bool m_enabled;
-};
-
-typedef Vector<RefPtr<MediaStreamComponent> > MediaStreamComponentVector;
-
-} // namespace WebCore
-
-#endif // MediaStreamComponent_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/mediastream/MediaStreamDescriptor.cpp b/chromium/third_party/WebKit/Source/core/platform/mediastream/MediaStreamDescriptor.cpp
index cb1ae44d366..7ec27a3a3c7 100644
--- a/chromium/third_party/WebKit/Source/core/platform/mediastream/MediaStreamDescriptor.cpp
+++ b/chromium/third_party/WebKit/Source/core/platform/mediastream/MediaStreamDescriptor.cpp
@@ -33,11 +33,7 @@
#include "core/platform/mediastream/MediaStreamDescriptor.h"
-#include "core/platform/UUID.h"
-#include "core/platform/mediastream/MediaStreamComponent.h"
-#include "core/platform/mediastream/MediaStreamSource.h"
-#include "wtf/RefCounted.h"
-#include "wtf/Vector.h"
+#include "platform/UUID.h"
namespace WebCore {
@@ -127,5 +123,14 @@ MediaStreamDescriptor::MediaStreamDescriptor(const String& id, const MediaStream
}
}
+MediaStreamDescriptor::~MediaStreamDescriptor()
+{
+ for (MediaStreamComponentVector::iterator iter = m_audioComponents.begin(); iter != m_audioComponents.end(); ++iter)
+ (*iter)->setStream(0);
+
+ for (MediaStreamComponentVector::iterator iter = m_videoComponents.begin(); iter != m_videoComponents.end(); ++iter)
+ (*iter)->setStream(0);
+}
+
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/mediastream/MediaStreamDescriptor.h b/chromium/third_party/WebKit/Source/core/platform/mediastream/MediaStreamDescriptor.h
index 0da128e0f63..383602b1f18 100644
--- a/chromium/third_party/WebKit/Source/core/platform/mediastream/MediaStreamDescriptor.h
+++ b/chromium/third_party/WebKit/Source/core/platform/mediastream/MediaStreamDescriptor.h
@@ -32,8 +32,8 @@
#ifndef MediaStreamDescriptor_h
#define MediaStreamDescriptor_h
-#include "core/platform/mediastream/MediaStreamComponent.h"
-#include "core/platform/mediastream/MediaStreamSource.h"
+#include "platform/mediastream/MediaStreamComponent.h"
+#include "platform/mediastream/MediaStreamSource.h"
#include "wtf/RefCounted.h"
#include "wtf/Vector.h"
@@ -49,7 +49,7 @@ public:
virtual void removeRemoteTrack(MediaStreamComponent*) = 0;
};
-class MediaStreamDescriptor : public RefCounted<MediaStreamDescriptor> {
+class MediaStreamDescriptor FINAL : public RefCounted<MediaStreamDescriptor> {
public:
class ExtraData : public RefCounted<ExtraData> {
public:
@@ -60,6 +60,8 @@ public:
static PassRefPtr<MediaStreamDescriptor> create(const String& id, const MediaStreamComponentVector& audioComponents, const MediaStreamComponentVector& videoComponents);
+ ~MediaStreamDescriptor();
+
MediaStreamDescriptorClient* client() const { return m_client; }
void setClient(MediaStreamDescriptorClient* client) { m_client = client; }
diff --git a/chromium/third_party/WebKit/Source/core/platform/mediastream/MediaStreamSource.cpp b/chromium/third_party/WebKit/Source/core/platform/mediastream/MediaStreamSource.cpp
deleted file mode 100644
index ea2e03400fe..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/mediastream/MediaStreamSource.cpp
+++ /dev/null
@@ -1,108 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * 3. Neither the name of Google Inc. nor the names of its contributors
- * may be used to endorse or promote products derived from this
- * software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/platform/mediastream/MediaStreamSource.h"
-#include "wtf/PassOwnPtr.h"
-
-namespace WebCore {
-
-PassRefPtr<MediaStreamSource> MediaStreamSource::create(const String& id, Type type, const String& name, ReadyState readyState, bool requiresConsumer)
-{
- return adoptRef(new MediaStreamSource(id, type, name, readyState, requiresConsumer));
-}
-
-MediaStreamSource::MediaStreamSource(const String& id, Type type, const String& name, ReadyState readyState, bool requiresConsumer)
- : m_id(id)
- , m_type(type)
- , m_name(name)
- , m_readyState(readyState)
- , m_requiresConsumer(requiresConsumer)
-{
-}
-
-void MediaStreamSource::setReadyState(ReadyState readyState)
-{
- if (m_readyState != ReadyStateEnded && m_readyState != readyState) {
- m_readyState = readyState;
- for (Vector<Observer*>::iterator i = m_observers.begin(); i != m_observers.end(); ++i)
- (*i)->sourceChangedState();
- }
-}
-
-void MediaStreamSource::addObserver(MediaStreamSource::Observer* observer)
-{
- m_observers.append(observer);
-}
-
-void MediaStreamSource::removeObserver(MediaStreamSource::Observer* observer)
-{
- size_t pos = m_observers.find(observer);
- if (pos != kNotFound)
- m_observers.remove(pos);
-}
-
-void MediaStreamSource::addAudioConsumer(PassRefPtr<AudioDestinationConsumer> consumer)
-{
- ASSERT(m_requiresConsumer);
- MutexLocker locker(m_audioConsumersLock);
- m_audioConsumers.append(consumer);
-}
-
-bool MediaStreamSource::removeAudioConsumer(AudioDestinationConsumer* consumer)
-{
- ASSERT(m_requiresConsumer);
- MutexLocker locker(m_audioConsumersLock);
- size_t pos = m_audioConsumers.find(consumer);
- if (pos != kNotFound) {
- m_audioConsumers.remove(pos);
- return true;
- }
- return false;
-}
-
-void MediaStreamSource::setAudioFormat(size_t numberOfChannels, float sampleRate)
-{
- ASSERT(m_requiresConsumer);
- MutexLocker locker(m_audioConsumersLock);
- for (Vector<RefPtr<AudioDestinationConsumer> >::iterator it = m_audioConsumers.begin(); it != m_audioConsumers.end(); ++it)
- (*it)->setFormat(numberOfChannels, sampleRate);
-}
-
-void MediaStreamSource::consumeAudio(AudioBus* bus, size_t numberOfFrames)
-{
- ASSERT(m_requiresConsumer);
- MutexLocker locker(m_audioConsumersLock);
- for (Vector<RefPtr<AudioDestinationConsumer> >::iterator it = m_audioConsumers.begin(); it != m_audioConsumers.end(); ++it)
- (*it)->consumeAudio(bus, numberOfFrames);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/mediastream/MediaStreamSource.h b/chromium/third_party/WebKit/Source/core/platform/mediastream/MediaStreamSource.h
deleted file mode 100644
index 5fdeed59720..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/mediastream/MediaStreamSource.h
+++ /dev/null
@@ -1,119 +0,0 @@
-/*
- * Copyright (C) 2011 Ericsson AB. All rights reserved.
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * 3. Neither the name of Ericsson nor the names of its contributors
- * may be used to endorse or promote products derived from this
- * software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef MediaStreamSource_h
-#define MediaStreamSource_h
-
-#include "core/platform/audio/AudioDestinationConsumer.h"
-#include "core/platform/mediastream/MediaConstraints.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/ThreadingPrimitives.h"
-#include "wtf/Vector.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class MediaStreamSource : public RefCounted<MediaStreamSource> {
-public:
- class Observer {
- public:
- virtual ~Observer() { }
- virtual void sourceChangedState() = 0;
- };
-
- class ExtraData {
- public:
- virtual ~ExtraData() { }
- };
-
- enum Type {
- TypeAudio,
- TypeVideo
- };
-
- enum ReadyState {
- ReadyStateLive = 0,
- ReadyStateMuted = 1,
- ReadyStateEnded = 2
- };
-
- static PassRefPtr<MediaStreamSource> create(const String& id, Type, const String& name, ReadyState = ReadyStateLive, bool requiresConsumer = false);
-
- const String& id() const { return m_id; }
- Type type() const { return m_type; }
- const String& name() const { return m_name; }
-
- void setReadyState(ReadyState);
- ReadyState readyState() const { return m_readyState; }
-
- void addObserver(Observer*);
- void removeObserver(Observer*);
-
- ExtraData* extraData() const { return m_extraData.get(); }
- void setExtraData(ExtraData* extraData) { m_extraData = adoptPtr(extraData); }
-
- void setConstraints(PassRefPtr<MediaConstraints> constraints) { m_constraints = constraints; }
- MediaConstraints* constraints() { return m_constraints.get(); }
-
- const String& deviceId() { return m_deviceId; }
- void setDeviceId(const String& deviceId) { m_deviceId = deviceId; }
-
- void setAudioFormat(size_t numberOfChannels, float sampleRate);
- void consumeAudio(AudioBus*, size_t numberOfFrames);
-
- bool requiresAudioConsumer() const { return m_requiresConsumer; }
- void addAudioConsumer(PassRefPtr<AudioDestinationConsumer>);
- bool removeAudioConsumer(AudioDestinationConsumer*);
- const Vector<RefPtr<AudioDestinationConsumer> >& audioConsumers() { return m_audioConsumers; }
-
-private:
- MediaStreamSource(const String& id, Type, const String& name, ReadyState, bool requiresConsumer);
-
- String m_id;
- Type m_type;
- String m_name;
- ReadyState m_readyState;
- String m_deviceId;
- bool m_requiresConsumer;
- Vector<Observer*> m_observers;
- Mutex m_audioConsumersLock;
- Vector<RefPtr<AudioDestinationConsumer> > m_audioConsumers;
- OwnPtr<ExtraData> m_extraData;
- RefPtr<MediaConstraints> m_constraints;
-};
-
-typedef Vector<RefPtr<MediaStreamSource> > MediaStreamSourceVector;
-
-} // namespace WebCore
-
-#endif // MediaStreamSource_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/mediastream/RTCConfiguration.h b/chromium/third_party/WebKit/Source/core/platform/mediastream/RTCConfiguration.h
deleted file mode 100644
index ddb5adbdfae..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/mediastream/RTCConfiguration.h
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * 3. Neither the name of Google Inc. nor the names of its contributors
- * may be used to endorse or promote products derived from this
- * software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef RTCConfiguration_h
-#define RTCConfiguration_h
-
-#include "weborigin/KURL.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/Vector.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class RTCIceServer : public RefCounted<RTCIceServer> {
-public:
- static PassRefPtr<RTCIceServer> create(const KURL& uri, const String& username, const String& credential)
- {
- return adoptRef(new RTCIceServer(uri, username, credential));
- }
- virtual ~RTCIceServer() { }
-
- const KURL& uri() { return m_uri; }
- const String& username() { return m_username; }
- const String& credential() { return m_credential; }
-
-private:
- RTCIceServer(const KURL& uri, const String& username, const String& credential)
- : m_uri(uri)
- , m_username(username)
- , m_credential(credential)
- {
- }
-
- KURL m_uri;
- String m_username;
- String m_credential;
-};
-
-class RTCConfiguration : public RefCounted<RTCConfiguration> {
-public:
- static PassRefPtr<RTCConfiguration> create() { return adoptRef(new RTCConfiguration()); }
- virtual ~RTCConfiguration() { }
-
- void appendServer(PassRefPtr<RTCIceServer> server) { m_servers.append(server); }
- size_t numberOfServers() { return m_servers.size(); }
- RTCIceServer* server(size_t index) { return m_servers[index].get(); }
-
- private:
- RTCConfiguration() { }
-
- Vector<RefPtr<RTCIceServer> > m_servers;
-};
-
-} // namespace WebCore
-
-#endif // RTCConfiguration_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/mediastream/RTCDTMFSenderHandler.cpp b/chromium/third_party/WebKit/Source/core/platform/mediastream/RTCDTMFSenderHandler.cpp
deleted file mode 100644
index ca3d5bcbc51..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/mediastream/RTCDTMFSenderHandler.cpp
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY GOOGLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GOOGLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/platform/mediastream/RTCDTMFSenderHandler.h"
-
-#include "core/platform/mediastream/RTCDTMFSenderHandlerClient.h"
-#include "public/platform/WebRTCDTMFSenderHandler.h"
-#include "wtf/PassOwnPtr.h"
-
-using namespace WebKit;
-
-namespace WebCore {
-
-PassOwnPtr<RTCDTMFSenderHandler> RTCDTMFSenderHandler::create(WebRTCDTMFSenderHandler* webHandler)
-{
- return adoptPtr(new RTCDTMFSenderHandler(webHandler));
-}
-
-RTCDTMFSenderHandler::RTCDTMFSenderHandler(WebRTCDTMFSenderHandler* webHandler)
- : m_webHandler(adoptPtr(webHandler))
- , m_client(0)
-{
-}
-
-RTCDTMFSenderHandler::~RTCDTMFSenderHandler()
-{
-}
-
-void RTCDTMFSenderHandler::setClient(RTCDTMFSenderHandlerClient* client)
-{
- m_client = client;
- m_webHandler->setClient(m_client ? this : 0);
-}
-
-String RTCDTMFSenderHandler::currentToneBuffer()
-{
- return m_webHandler->currentToneBuffer();
-}
-
-bool RTCDTMFSenderHandler::canInsertDTMF()
-{
- return m_webHandler->canInsertDTMF();
-}
-
-bool RTCDTMFSenderHandler::insertDTMF(const String& tones, long duration, long interToneGap)
-{
- return m_webHandler->insertDTMF(tones, duration, interToneGap);
-}
-
-void RTCDTMFSenderHandler::didPlayTone(const WebString& tone) const
-{
- if (m_client)
- m_client->didPlayTone(tone);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/mediastream/RTCDTMFSenderHandler.h b/chromium/third_party/WebKit/Source/core/platform/mediastream/RTCDTMFSenderHandler.h
deleted file mode 100644
index f9ef7fbc787..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/mediastream/RTCDTMFSenderHandler.h
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY GOOGLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GOOGLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef RTCDTMFSenderHandler_h
-#define RTCDTMFSenderHandler_h
-
-#include "core/platform/mediastream/RTCDTMFSenderHandler.h"
-#include "core/platform/mediastream/RTCDTMFSenderHandlerClient.h"
-#include "public/platform/WebRTCDTMFSenderHandler.h"
-#include "public/platform/WebRTCDTMFSenderHandlerClient.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/PassOwnPtr.h"
-
-namespace WebCore {
-
-class RTCDTMFSenderHandlerClient;
-
-class RTCDTMFSenderHandler : public WebKit::WebRTCDTMFSenderHandlerClient {
-public:
- static PassOwnPtr<RTCDTMFSenderHandler> create(WebKit::WebRTCDTMFSenderHandler*);
- virtual ~RTCDTMFSenderHandler();
-
- void setClient(RTCDTMFSenderHandlerClient*);
-
- String currentToneBuffer();
-
- bool canInsertDTMF();
- bool insertDTMF(const String& tones, long duration, long interToneGap);
-
- // WebKit::WebRTCDTMFSenderHandlerClient implementation.
- virtual void didPlayTone(const WebKit::WebString& tone) const OVERRIDE;
-
-private:
- explicit RTCDTMFSenderHandler(WebKit::WebRTCDTMFSenderHandler*);
-
- OwnPtr<WebKit::WebRTCDTMFSenderHandler> m_webHandler;
- RTCDTMFSenderHandlerClient* m_client;
-};
-
-} // namespace WebCore
-
-#endif // RTCDTMFSenderHandler_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/mediastream/RTCDTMFSenderHandlerClient.h b/chromium/third_party/WebKit/Source/core/platform/mediastream/RTCDTMFSenderHandlerClient.h
deleted file mode 100644
index 3a3f18b2f94..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/mediastream/RTCDTMFSenderHandlerClient.h
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY GOOGLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GOOGLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef RTCDTMFSenderHandlerClient_h
-#define RTCDTMFSenderHandlerClient_h
-
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class RTCDTMFSenderHandlerClient {
-public:
- virtual ~RTCDTMFSenderHandlerClient() { }
-
- virtual void didPlayTone(const String&) = 0;
-};
-
-} // namespace WebCore
-
-#endif // RTCDTMFSenderHandlerClient_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/mediastream/RTCDataChannelHandler.cpp b/chromium/third_party/WebKit/Source/core/platform/mediastream/RTCDataChannelHandler.cpp
index cd3d749b7ec..7c91a118140 100644
--- a/chromium/third_party/WebKit/Source/core/platform/mediastream/RTCDataChannelHandler.cpp
+++ b/chromium/third_party/WebKit/Source/core/platform/mediastream/RTCDataChannelHandler.cpp
@@ -23,21 +23,16 @@
*/
#include "config.h"
-
#include "core/platform/mediastream/RTCDataChannelHandler.h"
-#include "core/platform/mediastream/RTCDataChannelHandlerClient.h"
-#include "public/platform/WebRTCDataChannelHandler.h"
-#include "wtf/PassOwnPtr.h"
-
namespace WebCore {
-PassOwnPtr<RTCDataChannelHandler> RTCDataChannelHandler::create(WebKit::WebRTCDataChannelHandler* webHandler)
+PassOwnPtr<RTCDataChannelHandler> RTCDataChannelHandler::create(blink::WebRTCDataChannelHandler* webHandler)
{
return adoptPtr(new RTCDataChannelHandler(webHandler));
}
-RTCDataChannelHandler::RTCDataChannelHandler(WebKit::WebRTCDataChannelHandler* webHandler)
+RTCDataChannelHandler::RTCDataChannelHandler(blink::WebRTCDataChannelHandler* webHandler)
: m_webHandler(adoptPtr(webHandler))
, m_client(0)
{
@@ -119,7 +114,7 @@ void RTCDataChannelHandler::didChangeReadyState(WebRTCDataChannelHandlerClient::
m_client->didChangeReadyState(static_cast<RTCDataChannelHandlerClient::ReadyState>(state));
}
-void RTCDataChannelHandler::didReceiveStringData(const WebKit::WebString& data) const
+void RTCDataChannelHandler::didReceiveStringData(const blink::WebString& data) const
{
if (m_client)
m_client->didReceiveStringData(data);
diff --git a/chromium/third_party/WebKit/Source/core/platform/mediastream/RTCDataChannelHandler.h b/chromium/third_party/WebKit/Source/core/platform/mediastream/RTCDataChannelHandler.h
index 70a3076f860..d860dad83bb 100644
--- a/chromium/third_party/WebKit/Source/core/platform/mediastream/RTCDataChannelHandler.h
+++ b/chromium/third_party/WebKit/Source/core/platform/mediastream/RTCDataChannelHandler.h
@@ -25,7 +25,6 @@
#ifndef RTCDataChannelHandler_h
#define RTCDataChannelHandler_h
-#include "core/platform/mediastream/RTCDataChannelHandler.h"
#include "core/platform/mediastream/RTCDataChannelHandlerClient.h"
#include "public/platform/WebRTCDataChannelHandler.h"
#include "public/platform/WebRTCDataChannelHandlerClient.h"
@@ -36,9 +35,9 @@ namespace WebCore {
class RTCDataChannelHandlerClient;
-class RTCDataChannelHandler : public WebKit::WebRTCDataChannelHandlerClient {
+class RTCDataChannelHandler : public blink::WebRTCDataChannelHandlerClient {
public:
- static PassOwnPtr<RTCDataChannelHandler> create(WebKit::WebRTCDataChannelHandler*);
+ static PassOwnPtr<RTCDataChannelHandler> create(blink::WebRTCDataChannelHandler*);
virtual ~RTCDataChannelHandler();
void setClient(RTCDataChannelHandlerClient*);
@@ -60,16 +59,16 @@ public:
bool sendRawData(const char*, size_t);
void close();
- // WebKit::WebRTCDataChannelHandlerClient implementation.
+ // blink::WebRTCDataChannelHandlerClient implementation.
virtual void didChangeReadyState(ReadyState) const OVERRIDE;
- virtual void didReceiveStringData(const WebKit::WebString&) const OVERRIDE;
+ virtual void didReceiveStringData(const blink::WebString&) const OVERRIDE;
virtual void didReceiveRawData(const char*, size_t) const OVERRIDE;
virtual void didDetectError() const OVERRIDE;
private:
- explicit RTCDataChannelHandler(WebKit::WebRTCDataChannelHandler*);
+ explicit RTCDataChannelHandler(blink::WebRTCDataChannelHandler*);
- OwnPtr<WebKit::WebRTCDataChannelHandler> m_webHandler;
+ OwnPtr<blink::WebRTCDataChannelHandler> m_webHandler;
RTCDataChannelHandlerClient* m_client;
};
diff --git a/chromium/third_party/WebKit/Source/core/platform/mediastream/RTCPeerConnectionHandler.cpp b/chromium/third_party/WebKit/Source/core/platform/mediastream/RTCPeerConnectionHandler.cpp
index 4ade634aa5c..b27cabbe192 100644
--- a/chromium/third_party/WebKit/Source/core/platform/mediastream/RTCPeerConnectionHandler.cpp
+++ b/chromium/third_party/WebKit/Source/core/platform/mediastream/RTCPeerConnectionHandler.cpp
@@ -29,18 +29,17 @@
*/
#include "config.h"
-
#include "core/platform/mediastream/RTCPeerConnectionHandler.h"
-#include "core/platform/mediastream/MediaConstraints.h"
-#include "core/platform/mediastream/MediaStreamComponent.h"
-#include "core/platform/mediastream/RTCConfiguration.h"
-#include "core/platform/mediastream/RTCDTMFSenderHandler.h"
#include "core/platform/mediastream/RTCDataChannelHandler.h"
#include "core/platform/mediastream/RTCPeerConnectionHandlerClient.h"
-#include "core/platform/mediastream/RTCSessionDescriptionRequest.h"
#include "core/platform/mediastream/RTCStatsRequest.h"
-#include "core/platform/mediastream/RTCVoidRequest.h"
+#include "platform/mediastream/MediaConstraints.h"
+#include "platform/mediastream/MediaStreamComponent.h"
+#include "platform/mediastream/RTCConfiguration.h"
+#include "platform/mediastream/RTCDTMFSenderHandler.h"
+#include "platform/mediastream/RTCSessionDescriptionRequest.h"
+#include "platform/mediastream/RTCVoidRequest.h"
#include "public/platform/Platform.h"
#include "public/platform/WebMediaConstraints.h"
#include "public/platform/WebMediaStream.h"
@@ -57,7 +56,7 @@
namespace WebCore {
-WebKit::WebRTCPeerConnectionHandler* RTCPeerConnectionHandler::toWebRTCPeerConnectionHandler(RTCPeerConnectionHandler* handler)
+blink::WebRTCPeerConnectionHandler* RTCPeerConnectionHandler::toWebRTCPeerConnectionHandler(RTCPeerConnectionHandler* handler)
{
return static_cast<RTCPeerConnectionHandler*>(handler)->m_webHandler.get();
}
@@ -84,7 +83,7 @@ RTCPeerConnectionHandler::~RTCPeerConnectionHandler()
bool RTCPeerConnectionHandler::createWebHandler()
{
- m_webHandler = adoptPtr(WebKit::Platform::current()->createRTCPeerConnectionHandler(this));
+ m_webHandler = adoptPtr(blink::Platform::current()->createRTCPeerConnectionHandler(this));
return m_webHandler;
}
@@ -103,12 +102,12 @@ void RTCPeerConnectionHandler::createAnswer(PassRefPtr<RTCSessionDescriptionRequ
m_webHandler->createAnswer(request, constraints);
}
-void RTCPeerConnectionHandler::setLocalDescription(PassRefPtr<RTCVoidRequest> request, WebKit::WebRTCSessionDescription sessionDescription)
+void RTCPeerConnectionHandler::setLocalDescription(PassRefPtr<RTCVoidRequest> request, blink::WebRTCSessionDescription sessionDescription)
{
m_webHandler->setLocalDescription(request, sessionDescription);
}
-void RTCPeerConnectionHandler::setRemoteDescription(PassRefPtr<RTCVoidRequest> request, WebKit::WebRTCSessionDescription sessionDescription)
+void RTCPeerConnectionHandler::setRemoteDescription(PassRefPtr<RTCVoidRequest> request, blink::WebRTCSessionDescription sessionDescription)
{
m_webHandler->setRemoteDescription(request, sessionDescription);
}
@@ -118,22 +117,22 @@ bool RTCPeerConnectionHandler::updateIce(PassRefPtr<RTCConfiguration> configurat
return m_webHandler->updateICE(configuration, constraints);
}
-bool RTCPeerConnectionHandler::addIceCandidate(WebKit::WebRTCICECandidate iceCandidate)
+bool RTCPeerConnectionHandler::addIceCandidate(blink::WebRTCICECandidate iceCandidate)
{
return m_webHandler->addICECandidate(iceCandidate);
}
-bool RTCPeerConnectionHandler::addIceCandidate(PassRefPtr<RTCVoidRequest> request, WebKit::WebRTCICECandidate iceCandidate)
+bool RTCPeerConnectionHandler::addIceCandidate(PassRefPtr<RTCVoidRequest> request, blink::WebRTCICECandidate iceCandidate)
{
return m_webHandler->addICECandidate(request, iceCandidate);
}
-WebKit::WebRTCSessionDescription RTCPeerConnectionHandler::localDescription()
+blink::WebRTCSessionDescription RTCPeerConnectionHandler::localDescription()
{
return m_webHandler->localDescription();
}
-WebKit::WebRTCSessionDescription RTCPeerConnectionHandler::remoteDescription()
+blink::WebRTCSessionDescription RTCPeerConnectionHandler::remoteDescription()
{
return m_webHandler->remoteDescription();
}
@@ -153,9 +152,9 @@ void RTCPeerConnectionHandler::getStats(PassRefPtr<RTCStatsRequest> request)
m_webHandler->getStats(request);
}
-PassOwnPtr<RTCDataChannelHandler> RTCPeerConnectionHandler::createDataChannel(const String& label, const WebKit::WebRTCDataChannelInit& init)
+PassOwnPtr<RTCDataChannelHandler> RTCPeerConnectionHandler::createDataChannel(const String& label, const blink::WebRTCDataChannelInit& init)
{
- WebKit::WebRTCDataChannelHandler* webHandler = m_webHandler->createDataChannel(label, init);
+ blink::WebRTCDataChannelHandler* webHandler = m_webHandler->createDataChannel(label, init);
if (!webHandler)
return nullptr;
@@ -164,7 +163,7 @@ PassOwnPtr<RTCDataChannelHandler> RTCPeerConnectionHandler::createDataChannel(co
PassOwnPtr<RTCDTMFSenderHandler> RTCPeerConnectionHandler::createDTMFSender(PassRefPtr<MediaStreamComponent> track)
{
- WebKit::WebRTCDTMFSenderHandler* webHandler = m_webHandler->createDTMFSender(track);
+ blink::WebRTCDTMFSenderHandler* webHandler = m_webHandler->createDTMFSender(track);
if (!webHandler)
return nullptr;
@@ -181,37 +180,37 @@ void RTCPeerConnectionHandler::negotiationNeeded()
m_client->negotiationNeeded();
}
-void RTCPeerConnectionHandler::didGenerateICECandidate(const WebKit::WebRTCICECandidate& iceCandidate)
+void RTCPeerConnectionHandler::didGenerateICECandidate(const blink::WebRTCICECandidate& iceCandidate)
{
m_client->didGenerateIceCandidate(iceCandidate);
}
-void RTCPeerConnectionHandler::didChangeSignalingState(WebKit::WebRTCPeerConnectionHandlerClient::SignalingState state)
+void RTCPeerConnectionHandler::didChangeSignalingState(blink::WebRTCPeerConnectionHandlerClient::SignalingState state)
{
m_client->didChangeSignalingState(static_cast<RTCPeerConnectionHandlerClient::SignalingState>(state));
}
-void RTCPeerConnectionHandler::didChangeICEGatheringState(WebKit::WebRTCPeerConnectionHandlerClient::ICEGatheringState state)
+void RTCPeerConnectionHandler::didChangeICEGatheringState(blink::WebRTCPeerConnectionHandlerClient::ICEGatheringState state)
{
m_client->didChangeIceGatheringState(static_cast<RTCPeerConnectionHandlerClient::IceGatheringState>(state));
}
-void RTCPeerConnectionHandler::didChangeICEConnectionState(WebKit::WebRTCPeerConnectionHandlerClient::ICEConnectionState state)
+void RTCPeerConnectionHandler::didChangeICEConnectionState(blink::WebRTCPeerConnectionHandlerClient::ICEConnectionState state)
{
m_client->didChangeIceConnectionState(static_cast<RTCPeerConnectionHandlerClient::IceConnectionState>(state));
}
-void RTCPeerConnectionHandler::didAddRemoteStream(const WebKit::WebMediaStream& webMediaStreamDescriptor)
+void RTCPeerConnectionHandler::didAddRemoteStream(const blink::WebMediaStream& webMediaStreamDescriptor)
{
m_client->didAddRemoteStream(webMediaStreamDescriptor);
}
-void RTCPeerConnectionHandler::didRemoveRemoteStream(const WebKit::WebMediaStream& webMediaStreamDescriptor)
+void RTCPeerConnectionHandler::didRemoveRemoteStream(const blink::WebMediaStream& webMediaStreamDescriptor)
{
m_client->didRemoveRemoteStream(webMediaStreamDescriptor);
}
-void RTCPeerConnectionHandler::didAddRemoteDataChannel(WebKit::WebRTCDataChannelHandler* webHandler)
+void RTCPeerConnectionHandler::didAddRemoteDataChannel(blink::WebRTCDataChannelHandler* webHandler)
{
ASSERT(webHandler);
m_client->didAddRemoteDataChannel(RTCDataChannelHandler::create(webHandler));
diff --git a/chromium/third_party/WebKit/Source/core/platform/mediastream/RTCPeerConnectionHandler.h b/chromium/third_party/WebKit/Source/core/platform/mediastream/RTCPeerConnectionHandler.h
index 5b0d689c458..9510a60d297 100644
--- a/chromium/third_party/WebKit/Source/core/platform/mediastream/RTCPeerConnectionHandler.h
+++ b/chromium/third_party/WebKit/Source/core/platform/mediastream/RTCPeerConnectionHandler.h
@@ -32,13 +32,12 @@
#define RTCPeerConnectionHandler_h
#include "core/platform/mediastream/MediaStreamDescriptor.h"
-#include "core/platform/mediastream/RTCPeerConnectionHandler.h"
#include "public/platform/WebRTCPeerConnectionHandler.h"
#include "public/platform/WebRTCPeerConnectionHandlerClient.h"
#include "wtf/OwnPtr.h"
#include "wtf/PassRefPtr.h"
-namespace WebKit {
+namespace blink {
class WebMediaStream;
class WebRTCICECandidate;
class WebRTCSessionDescription;
@@ -57,7 +56,7 @@ class RTCSessionDescriptionRequest;
class RTCStatsRequest;
class RTCVoidRequest;
-class RTCPeerConnectionHandler : public WebKit::WebRTCPeerConnectionHandlerClient {
+class RTCPeerConnectionHandler : public blink::WebRTCPeerConnectionHandlerClient {
public:
static PassOwnPtr<RTCPeerConnectionHandler> create(RTCPeerConnectionHandlerClient*);
virtual ~RTCPeerConnectionHandler();
@@ -68,39 +67,39 @@ public:
void createOffer(PassRefPtr<RTCSessionDescriptionRequest>, PassRefPtr<MediaConstraints>);
void createAnswer(PassRefPtr<RTCSessionDescriptionRequest>, PassRefPtr<MediaConstraints>);
- void setLocalDescription(PassRefPtr<RTCVoidRequest>, WebKit::WebRTCSessionDescription);
- void setRemoteDescription(PassRefPtr<RTCVoidRequest>, WebKit::WebRTCSessionDescription);
- WebKit::WebRTCSessionDescription localDescription();
- WebKit::WebRTCSessionDescription remoteDescription();
+ void setLocalDescription(PassRefPtr<RTCVoidRequest>, blink::WebRTCSessionDescription);
+ void setRemoteDescription(PassRefPtr<RTCVoidRequest>, blink::WebRTCSessionDescription);
+ blink::WebRTCSessionDescription localDescription();
+ blink::WebRTCSessionDescription remoteDescription();
bool updateIce(PassRefPtr<RTCConfiguration>, PassRefPtr<MediaConstraints>);
// DEPRECATED
- bool addIceCandidate(WebKit::WebRTCICECandidate);
+ bool addIceCandidate(blink::WebRTCICECandidate);
- bool addIceCandidate(PassRefPtr<RTCVoidRequest>, WebKit::WebRTCICECandidate);
+ bool addIceCandidate(PassRefPtr<RTCVoidRequest>, blink::WebRTCICECandidate);
bool addStream(PassRefPtr<MediaStreamDescriptor>, PassRefPtr<MediaConstraints>);
void removeStream(PassRefPtr<MediaStreamDescriptor>);
void getStats(PassRefPtr<RTCStatsRequest>);
- PassOwnPtr<RTCDataChannelHandler> createDataChannel(const String& label, const WebKit::WebRTCDataChannelInit&);
+ PassOwnPtr<RTCDataChannelHandler> createDataChannel(const String& label, const blink::WebRTCDataChannelInit&);
PassOwnPtr<RTCDTMFSenderHandler> createDTMFSender(PassRefPtr<MediaStreamComponent>);
void stop();
- // WebKit::WebRTCPeerConnectionHandlerClient implementation.
+ // blink::WebRTCPeerConnectionHandlerClient implementation.
virtual void negotiationNeeded() OVERRIDE;
- virtual void didGenerateICECandidate(const WebKit::WebRTCICECandidate&) OVERRIDE;
- virtual void didChangeSignalingState(WebKit::WebRTCPeerConnectionHandlerClient::SignalingState) OVERRIDE;
- virtual void didChangeICEGatheringState(WebKit::WebRTCPeerConnectionHandlerClient::ICEGatheringState) OVERRIDE;
- virtual void didChangeICEConnectionState(WebKit::WebRTCPeerConnectionHandlerClient::ICEConnectionState) OVERRIDE;
- virtual void didAddRemoteStream(const WebKit::WebMediaStream&) OVERRIDE;
- virtual void didRemoveRemoteStream(const WebKit::WebMediaStream&) OVERRIDE;
- virtual void didAddRemoteDataChannel(WebKit::WebRTCDataChannelHandler*) OVERRIDE;
+ virtual void didGenerateICECandidate(const blink::WebRTCICECandidate&) OVERRIDE;
+ virtual void didChangeSignalingState(blink::WebRTCPeerConnectionHandlerClient::SignalingState) OVERRIDE;
+ virtual void didChangeICEGatheringState(blink::WebRTCPeerConnectionHandlerClient::ICEGatheringState) OVERRIDE;
+ virtual void didChangeICEConnectionState(blink::WebRTCPeerConnectionHandlerClient::ICEConnectionState) OVERRIDE;
+ virtual void didAddRemoteStream(const blink::WebMediaStream&) OVERRIDE;
+ virtual void didRemoveRemoteStream(const blink::WebMediaStream&) OVERRIDE;
+ virtual void didAddRemoteDataChannel(blink::WebRTCDataChannelHandler*) OVERRIDE;
- static WebKit::WebRTCPeerConnectionHandler* toWebRTCPeerConnectionHandler(RTCPeerConnectionHandler*);
+ static blink::WebRTCPeerConnectionHandler* toWebRTCPeerConnectionHandler(RTCPeerConnectionHandler*);
private:
explicit RTCPeerConnectionHandler(RTCPeerConnectionHandlerClient*);
- OwnPtr<WebKit::WebRTCPeerConnectionHandler> m_webHandler;
+ OwnPtr<blink::WebRTCPeerConnectionHandler> m_webHandler;
RTCPeerConnectionHandlerClient* m_client;
};
diff --git a/chromium/third_party/WebKit/Source/core/platform/mediastream/RTCPeerConnectionHandlerClient.h b/chromium/third_party/WebKit/Source/core/platform/mediastream/RTCPeerConnectionHandlerClient.h
index e78e44c71f7..46f276fb3bd 100644
--- a/chromium/third_party/WebKit/Source/core/platform/mediastream/RTCPeerConnectionHandlerClient.h
+++ b/chromium/third_party/WebKit/Source/core/platform/mediastream/RTCPeerConnectionHandlerClient.h
@@ -33,7 +33,7 @@
#include "wtf/PassRefPtr.h"
-namespace WebKit {
+namespace blink {
class WebRTCICECandidate;
}
@@ -72,7 +72,7 @@ public:
virtual ~RTCPeerConnectionHandlerClient() { }
virtual void negotiationNeeded() = 0;
- virtual void didGenerateIceCandidate(WebKit::WebRTCICECandidate) = 0;
+ virtual void didGenerateIceCandidate(blink::WebRTCICECandidate) = 0;
virtual void didChangeSignalingState(SignalingState) = 0;
virtual void didChangeIceGatheringState(IceGatheringState) = 0;
virtual void didChangeIceConnectionState(IceConnectionState) = 0;
diff --git a/chromium/third_party/WebKit/Source/core/platform/mediastream/RTCSessionDescriptionRequest.h b/chromium/third_party/WebKit/Source/core/platform/mediastream/RTCSessionDescriptionRequest.h
deleted file mode 100644
index 0c7b7be38f6..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/mediastream/RTCSessionDescriptionRequest.h
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * 3. Neither the name of Google Inc. nor the names of its contributors
- * may be used to endorse or promote products derived from this
- * software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef RTCSessionDescriptionRequest_h
-#define RTCSessionDescriptionRequest_h
-
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/RefPtr.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebKit {
-class WebRTCSessionDescription;
-}
-
-namespace WebCore {
-
-class RTCSessionDescriptionRequest : public RefCounted<RTCSessionDescriptionRequest> {
-public:
- class ExtraData : public RefCounted<ExtraData> {
- public:
- virtual ~ExtraData() { }
- };
-
- virtual ~RTCSessionDescriptionRequest() { }
-
- virtual void requestSucceeded(const WebKit::WebRTCSessionDescription&) = 0;
- virtual void requestFailed(const String& error) = 0;
-
- PassRefPtr<ExtraData> extraData() const { return m_extraData; }
- void setExtraData(PassRefPtr<ExtraData> extraData) { m_extraData = extraData; }
-
-protected:
- RTCSessionDescriptionRequest() { }
-
-private:
- RefPtr<ExtraData> m_extraData;
-};
-
-} // namespace WebCore
-
-#endif // RTCSessionDescriptionRequest_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/mediastream/RTCStatsResponseBase.h b/chromium/third_party/WebKit/Source/core/platform/mediastream/RTCStatsResponseBase.h
deleted file mode 100644
index dee70fbd5bf..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/mediastream/RTCStatsResponseBase.h
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef RTCStatsResponseBase_h
-#define RTCStatsResponseBase_h
-
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class RTCStatsResponseBase : public RefCounted<RTCStatsResponseBase> {
-public:
- virtual ~RTCStatsResponseBase() { }
-
- virtual size_t addReport(String id, String type, double timestamp) = 0;
- virtual void addStatistic(size_t report, String name, String value) = 0;
-};
-
-} // namespace WebCore
-
-#endif // RTCStatsResponseBase_h
-
diff --git a/chromium/third_party/WebKit/Source/core/platform/mediastream/RTCVoidRequest.h b/chromium/third_party/WebKit/Source/core/platform/mediastream/RTCVoidRequest.h
deleted file mode 100644
index fe3b4511b29..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/mediastream/RTCVoidRequest.h
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * 3. Neither the name of Google Inc. nor the names of its contributors
- * may be used to endorse or promote products derived from this
- * software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef RTCVoidRequest_h
-#define RTCVoidRequest_h
-
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/RefPtr.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class RTCVoidRequest : public RefCounted<RTCVoidRequest> {
-public:
- class ExtraData : public RefCounted<ExtraData> {
- public:
- virtual ~ExtraData() { }
- };
-
- virtual ~RTCVoidRequest() { }
-
- virtual void requestSucceeded() = 0;
- virtual void requestFailed(const String& error) = 0;
-
- PassRefPtr<ExtraData> extraData() const { return m_extraData; }
- void setExtraData(PassRefPtr<ExtraData> extraData) { m_extraData = extraData; }
-
-protected:
- RTCVoidRequest() { }
-
-private:
- RefPtr<ExtraData> m_extraData;
-};
-
-} // namespace WebCore
-
-#endif // RTCVoidRequest_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/midi/MIDIAccessor.cpp b/chromium/third_party/WebKit/Source/core/platform/midi/MIDIAccessor.cpp
deleted file mode 100644
index 83fc83a051c..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/midi/MIDIAccessor.cpp
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/midi/MIDIAccessor.h"
-
-#include "core/platform/midi/MIDIAccessorClient.h"
-#include "public/platform/Platform.h"
-#include "public/platform/WebMIDIAccessor.h"
-#include "wtf/text/WTFString.h"
-
-using WebKit::WebString;
-
-namespace WebCore {
-
-// Factory method
-PassOwnPtr<MIDIAccessor> MIDIAccessor::create(MIDIAccessorClient* client)
-{
- return adoptPtr(new MIDIAccessor(client));
-}
-
-MIDIAccessor::MIDIAccessor(MIDIAccessorClient* client)
- : m_client(client)
-{
- ASSERT(client);
-
- m_accessor = adoptPtr(WebKit::Platform::current()->createMIDIAccessor(this));
-
- ASSERT(m_accessor);
-}
-
-void MIDIAccessor::startSession()
-{
- m_accessor->startSession();
-}
-
-void MIDIAccessor::sendMIDIData(unsigned portIndex, const unsigned char* data, size_t length, double timeStamp)
-{
- m_accessor->sendMIDIData(portIndex, data, length, timeStamp);
-}
-
-void MIDIAccessor::didAddInputPort(const WebString& id, const WebString& manufacturer, const WebString& name, const WebString& version)
-{
- m_client->didAddInputPort(id, manufacturer, name, version);
-}
-
-void MIDIAccessor::didAddOutputPort(const WebString& id, const WebString& manufacturer, const WebString& name, const WebString& version)
-{
- m_client->didAddOutputPort(id, manufacturer, name, version);
-}
-
-void MIDIAccessor::didStartSession(bool success)
-{
- m_client->didStartSession(success);
-}
-
-void MIDIAccessor::didReceiveMIDIData(unsigned portIndex, const unsigned char* data, size_t length, double timeStamp)
-{
- m_client->didReceiveMIDIData(portIndex, data, length, timeStamp);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/midi/MIDIAccessor.h b/chromium/third_party/WebKit/Source/core/platform/midi/MIDIAccessor.h
deleted file mode 100644
index 2204afeb5d3..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/midi/MIDIAccessor.h
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef MIDIAccessor_h
-#define MIDIAccessor_h
-
-#include "public/platform/WebMIDIAccessor.h"
-#include "public/platform/WebMIDIAccessorClient.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/PassOwnPtr.h"
-
-namespace WebCore {
-
-class MIDIAccessorClient;
-
-class MIDIAccessor : public WebKit::WebMIDIAccessorClient {
-public:
- static PassOwnPtr<MIDIAccessor> create(MIDIAccessorClient*);
-
- virtual ~MIDIAccessor() { }
-
- void startSession();
- void sendMIDIData(unsigned portIndex, const unsigned char* data, size_t length, double timeStamp);
-
- // WebKit::WebMIDIAccessorClient
- virtual void didAddInputPort(const WebKit::WebString& id, const WebKit::WebString& manufacturer, const WebKit::WebString& name, const WebKit::WebString& version) OVERRIDE;
- virtual void didAddOutputPort(const WebKit::WebString& id, const WebKit::WebString& manufacturer, const WebKit::WebString& name, const WebKit::WebString& version) OVERRIDE;
- virtual void didStartSession(bool success) OVERRIDE;
- virtual void didReceiveMIDIData(unsigned portIndex, const unsigned char* data, size_t length, double timeStamp) OVERRIDE;
-
-private:
- explicit MIDIAccessor(MIDIAccessorClient*);
-
- MIDIAccessorClient* m_client;
- OwnPtr<WebKit::WebMIDIAccessor> m_accessor;
-};
-
-} // namespace WebCore
-
-#endif // MIDIAccessor_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/midi/MIDIAccessorClient.h b/chromium/third_party/WebKit/Source/core/platform/midi/MIDIAccessorClient.h
deleted file mode 100644
index 450b8f60c0a..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/midi/MIDIAccessorClient.h
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef MIDIAccessorClient_h
-#define MIDIAccessorClient_h
-
-#include "wtf/Forward.h"
-
-namespace WebCore {
-
-class MIDIAccessorClient {
-public:
- virtual void didAddInputPort(const String& id, const String& manufacturer, const String& name, const String& version) = 0;
- virtual void didAddOutputPort(const String& id, const String& manufacturer, const String& name, const String& version) = 0;
-
- virtual void didStartSession(bool success) = 0;
- virtual void didReceiveMIDIData(unsigned portIndex, const unsigned char* data, size_t length, double timeStamp) = 0;
-};
-
-} // namespace WebCore
-
-#endif // MIDIAccessorClient_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/midi/OWNERS b/chromium/third_party/WebKit/Source/core/platform/midi/OWNERS
deleted file mode 100644
index 88c0a7fa556..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/midi/OWNERS
+++ /dev/null
@@ -1,2 +0,0 @@
-kouhei@chromium.org
-toyoshim@chromium.org
diff --git a/chromium/third_party/WebKit/Source/core/platform/mock/DeviceOrientationClientMock.cpp b/chromium/third_party/WebKit/Source/core/platform/mock/DeviceOrientationClientMock.cpp
deleted file mode 100644
index 9156629e64f..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/mock/DeviceOrientationClientMock.cpp
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/mock/DeviceOrientationClientMock.h"
-
-#include "core/dom/DeviceOrientationController.h"
-
-namespace WebCore {
-
-DeviceOrientationClientMock::DeviceOrientationClientMock()
- : m_controller(0)
- , m_timer(this, &DeviceOrientationClientMock::timerFired)
- , m_isUpdating(false)
-{
-}
-
-void DeviceOrientationClientMock::setController(DeviceOrientationController* controller)
-{
- ASSERT(!m_controller);
- m_controller = controller;
- ASSERT(m_controller);
-}
-
-void DeviceOrientationClientMock::startUpdating()
-{
- m_isUpdating = true;
-}
-
-void DeviceOrientationClientMock::stopUpdating()
-{
- m_isUpdating = false;
- m_timer.stop();
-}
-
-void DeviceOrientationClientMock::setOrientation(PassRefPtr<DeviceOrientationData> orientation)
-{
- m_orientation = orientation;
- if (m_isUpdating && !m_timer.isActive())
- m_timer.startOneShot(0);
-}
-
-void DeviceOrientationClientMock::timerFired(Timer<DeviceOrientationClientMock>* timer)
-{
- ASSERT_UNUSED(timer, timer == &m_timer);
- m_timer.stop();
- m_controller->didChangeDeviceOrientation(m_orientation.get());
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/mock/DeviceOrientationClientMock.h b/chromium/third_party/WebKit/Source/core/platform/mock/DeviceOrientationClientMock.h
deleted file mode 100644
index e532f17cb1a..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/mock/DeviceOrientationClientMock.h
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef DeviceOrientationClientMock_h
-#define DeviceOrientationClientMock_h
-
-#include "core/dom/DeviceOrientationClient.h"
-#include "core/platform/Timer.h"
-#include "modules/device_orientation/DeviceOrientationData.h"
-
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefPtr.h"
-
-namespace WebCore {
-
-class DeviceOrientationController;
-
-// A mock implementation of DeviceOrientationClient used to test the feature in
-// DumpRenderTree. Embedders should should configure the Page object to use this
-// client when running DumpRenderTree.
-class DeviceOrientationClientMock : public DeviceOrientationClient {
-public:
- DeviceOrientationClientMock();
-
- // DeviceOrientationClient
- virtual void setController(DeviceOrientationController*) OVERRIDE;
- virtual void startUpdating() OVERRIDE;
- virtual void stopUpdating() OVERRIDE;
- virtual DeviceOrientationData* lastOrientation() const OVERRIDE { return m_orientation.get(); }
- virtual void deviceOrientationControllerDestroyed() OVERRIDE { }
-
- void setOrientation(PassRefPtr<DeviceOrientationData>);
-
-private:
- void timerFired(Timer<DeviceOrientationClientMock>*);
-
- RefPtr<DeviceOrientationData> m_orientation;
- DeviceOrientationController* m_controller;
- Timer<DeviceOrientationClientMock> m_timer;
- bool m_isUpdating;
-};
-
-} // namespace WebCore
-
-#endif // DeviceOrientationClientMock_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/mock/GeolocationClientMock.h b/chromium/third_party/WebKit/Source/core/platform/mock/GeolocationClientMock.h
index b3eec876f87..884184d7741 100644
--- a/chromium/third_party/WebKit/Source/core/platform/mock/GeolocationClientMock.h
+++ b/chromium/third_party/WebKit/Source/core/platform/mock/GeolocationClientMock.h
@@ -32,8 +32,8 @@
#ifndef GeolocationClientMock_h
#define GeolocationClientMock_h
-#include "core/platform/Timer.h"
#include "modules/geolocation/GeolocationClient.h"
+#include "platform/Timer.h"
#include "wtf/HashSet.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefPtr.h"
diff --git a/chromium/third_party/WebKit/Source/core/platform/mock/MIDIClientMock.cpp b/chromium/third_party/WebKit/Source/core/platform/mock/MIDIClientMock.cpp
deleted file mode 100644
index b5c603cb893..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/mock/MIDIClientMock.cpp
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/mock/MIDIClientMock.h"
-
-#include "modules/webmidi/MIDIAccess.h"
-
-namespace WebCore {
-
-MIDIClientMock::MIDIClientMock()
- : m_allowed(false)
-{
-}
-
-MIDIClientMock::~MIDIClientMock()
-{
-}
-
-void MIDIClientMock::setSysExPermission(bool allowed)
-{
- m_allowed = allowed;
-}
-
-void MIDIClientMock::resetMock()
-{
- m_allowed = false;
-}
-
-void MIDIClientMock::requestSysExPermission(PassRefPtr<MIDIAccess> access)
-{
- access->setSysExEnabled(m_allowed);
-}
-
-void MIDIClientMock::cancelSysExPermissionRequest(MIDIAccess*)
-{
-}
-
-} // WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/mock/MIDIClientMock.h b/chromium/third_party/WebKit/Source/core/platform/mock/MIDIClientMock.h
deleted file mode 100644
index 7276c858ef6..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/mock/MIDIClientMock.h
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef MIDIClientMock_h
-#define MIDIClientMock_h
-
-#include "modules/webmidi/MIDIClient.h"
-
-namespace WebCore {
-
-class MIDIClientMock : public MIDIClient {
-public:
- MIDIClientMock();
- virtual ~MIDIClientMock();
-
- void setSysExPermission(bool);
- void resetMock();
-
- // MIDIClient
- virtual void requestSysExPermission(PassRefPtr<MIDIAccess>) OVERRIDE;
- virtual void cancelSysExPermissionRequest(MIDIAccess*) OVERRIDE;
-
-private:
- bool m_allowed;
-};
-
-} // namespace WebCore
-
-#endif // MIDIClient_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/mock/PlatformSpeechSynthesizerMock.cpp b/chromium/third_party/WebKit/Source/core/platform/mock/PlatformSpeechSynthesizerMock.cpp
deleted file mode 100644
index 2c4928a8bd0..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/mock/PlatformSpeechSynthesizerMock.cpp
+++ /dev/null
@@ -1,100 +0,0 @@
-/*
- * Copyright (C) 2013 Apple Computer, Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/PlatformSpeechSynthesisUtterance.h"
-#include "core/platform/mock/PlatformSpeechSynthesizerMock.h"
-
-namespace WebCore {
-
-PassOwnPtr<PlatformSpeechSynthesizerMock> PlatformSpeechSynthesizerMock::create(PlatformSpeechSynthesizerClient* client)
-{
- OwnPtr<PlatformSpeechSynthesizerMock> synthesizer = adoptPtr(new PlatformSpeechSynthesizerMock(client));
- synthesizer->initializeVoiceList();
- return synthesizer.release();
-}
-
-PlatformSpeechSynthesizerMock::PlatformSpeechSynthesizerMock(PlatformSpeechSynthesizerClient* client)
- : PlatformSpeechSynthesizer(client)
- , m_speakingFinishedTimer(this, &PlatformSpeechSynthesizerMock::speakingFinished)
-{
-}
-
-PlatformSpeechSynthesizerMock::~PlatformSpeechSynthesizerMock()
-{
- m_speakingFinishedTimer.stop();
-}
-
-void PlatformSpeechSynthesizerMock::speakingFinished(Timer<PlatformSpeechSynthesizerMock>*)
-{
- ASSERT(m_utterance.get());
- client()->didFinishSpeaking(m_utterance);
- m_utterance = 0;
-}
-
-void PlatformSpeechSynthesizerMock::initializeVoiceList()
-{
- m_voiceList.clear();
- m_voiceList.append(PlatformSpeechSynthesisVoice::create(String("mock.voice.bruce"), String("bruce"), String("en-US"), true, true));
- m_voiceList.append(PlatformSpeechSynthesisVoice::create(String("mock.voice.clark"), String("clark"), String("en-US"), true, false));
- m_voiceList.append(PlatformSpeechSynthesisVoice::create(String("mock.voice.logan"), String("logan"), String("fr-CA"), true, true));
-}
-
-void PlatformSpeechSynthesizerMock::speak(PassRefPtr<PlatformSpeechSynthesisUtterance> utterance)
-{
- ASSERT(!m_utterance);
- m_utterance = utterance;
- client()->didStartSpeaking(m_utterance);
-
- // Fire a fake word and then sentence boundary event.
- client()->boundaryEventOccurred(m_utterance, SpeechWordBoundary, 0);
- client()->boundaryEventOccurred(m_utterance, SpeechSentenceBoundary, m_utterance->text().length());
-
- // Give the fake speech job some time so that pause and other functions have time to be called.
- m_speakingFinishedTimer.startOneShot(.1);
-}
-
-void PlatformSpeechSynthesizerMock::cancel()
-{
- if (!m_utterance)
- return;
-
- m_speakingFinishedTimer.stop();
- client()->speakingErrorOccurred(m_utterance);
- m_utterance = 0;
-}
-
-void PlatformSpeechSynthesizerMock::pause()
-{
- client()->didPauseSpeaking(m_utterance);
-}
-
-void PlatformSpeechSynthesizerMock::resume()
-{
- client()->didResumeSpeaking(m_utterance);
-}
-
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/mock/PlatformSpeechSynthesizerMock.h b/chromium/third_party/WebKit/Source/core/platform/mock/PlatformSpeechSynthesizerMock.h
deleted file mode 100644
index 7dada05e31a..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/mock/PlatformSpeechSynthesizerMock.h
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright (C) 2013 Apple Computer, Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef PlatformSpeechSynthesizerMock_h
-#define PlatformSpeechSynthesizerMock_h
-
-#include "core/platform/PlatformSpeechSynthesizer.h"
-#include "core/platform/Timer.h"
-#include "wtf/PassOwnPtr.h"
-
-namespace WebCore {
-
-class PlatformSpeechSynthesizerMock : public PlatformSpeechSynthesizer {
-public:
- static PassOwnPtr<PlatformSpeechSynthesizerMock> create(PlatformSpeechSynthesizerClient*);
-
- virtual ~PlatformSpeechSynthesizerMock();
- virtual void speak(PassRefPtr<PlatformSpeechSynthesisUtterance>);
- virtual void pause();
- virtual void resume();
- virtual void cancel();
-
-private:
- explicit PlatformSpeechSynthesizerMock(PlatformSpeechSynthesizerClient*);
- virtual void initializeVoiceList();
- void speakingFinished(Timer<PlatformSpeechSynthesizerMock>*);
-
- Timer<PlatformSpeechSynthesizerMock> m_speakingFinishedTimer;
- RefPtr<PlatformSpeechSynthesisUtterance> m_utterance;
-};
-
-} // namespace WebCore
-
-#endif // PlatformSpeechSynthesizer_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/mock/ScrollbarThemeMock.cpp b/chromium/third_party/WebKit/Source/core/platform/mock/ScrollbarThemeMock.cpp
deleted file mode 100644
index 28f9ce6d5e5..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/mock/ScrollbarThemeMock.cpp
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Copyright (C) 2011 Apple Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/mock/ScrollbarThemeMock.h"
-
-#include "RuntimeEnabledFeatures.h"
-#include "core/platform/Scrollbar.h"
-
-namespace WebCore {
-
-static int cScrollbarThickness[] = { 15, 11 };
-
-IntRect ScrollbarThemeMock::trackRect(ScrollbarThemeClient* scrollbar, bool)
-{
- return scrollbar->frameRect();
-}
-
-int ScrollbarThemeMock::scrollbarThickness(ScrollbarControlSize controlSize)
-{
- return cScrollbarThickness[controlSize];
-}
-
-bool ScrollbarThemeMock::usesOverlayScrollbars() const
-{
- return RuntimeEnabledFeatures::overlayScrollbarsEnabled();
-}
-
-void ScrollbarThemeMock::paintTrackBackground(GraphicsContext* context, ScrollbarThemeClient* scrollbar, const IntRect& trackRect)
-{
- context->fillRect(trackRect, scrollbar->enabled() ? Color::lightGray : Color(0xFFE0E0E0));
-}
-
-void ScrollbarThemeMock::paintThumb(GraphicsContext* context, ScrollbarThemeClient* scrollbar, const IntRect& thumbRect)
-{
- if (scrollbar->enabled())
- context->fillRect(thumbRect, Color::darkGray);
-}
-
-}
-
diff --git a/chromium/third_party/WebKit/Source/core/platform/mock/ScrollbarThemeMock.h b/chromium/third_party/WebKit/Source/core/platform/mock/ScrollbarThemeMock.h
deleted file mode 100644
index 3ddf0268b78..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/mock/ScrollbarThemeMock.h
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Copyright (C) 2011 Apple Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ScrollbarThemeMock_h
-#define ScrollbarThemeMock_h
-
-#include "core/platform/ScrollbarTheme.h"
-
-namespace WebCore {
-
-// Scrollbar theme used in image snapshots, to eliminate appearance differences between platforms.
-class ScrollbarThemeMock : public ScrollbarTheme {
-public:
- virtual int scrollbarThickness(ScrollbarControlSize = RegularScrollbar) OVERRIDE;
- virtual bool usesOverlayScrollbars() const OVERRIDE;
-
-protected:
- virtual bool hasButtons(ScrollbarThemeClient*) OVERRIDE { return false; }
- virtual bool hasThumb(ScrollbarThemeClient*) OVERRIDE { return true; }
-
- virtual IntRect backButtonRect(ScrollbarThemeClient*, ScrollbarPart, bool /*painting*/ = false) OVERRIDE { return IntRect(); }
- virtual IntRect forwardButtonRect(ScrollbarThemeClient*, ScrollbarPart, bool /*painting*/ = false) OVERRIDE { return IntRect(); }
- virtual IntRect trackRect(ScrollbarThemeClient*, bool painting = false) OVERRIDE;
-
- virtual void paintTrackBackground(GraphicsContext*, ScrollbarThemeClient*, const IntRect&) OVERRIDE;
- virtual void paintThumb(GraphicsContext*, ScrollbarThemeClient*, const IntRect&) OVERRIDE;
-
-private:
- virtual bool isMockTheme() const OVERRIDE FINAL { return true; }
-};
-
-}
-#endif // ScrollbarThemeMock_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/mock/ScrollbarThemeOverlayMock.h b/chromium/third_party/WebKit/Source/core/platform/mock/ScrollbarThemeOverlayMock.h
deleted file mode 100644
index 0a9a862dd85..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/mock/ScrollbarThemeOverlayMock.h
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ScrollbarThemeOverlayMock_h
-#define ScrollbarThemeOverlayMock_h
-
-#include "core/platform/ScrollbarThemeOverlay.h"
-
-namespace WebCore {
-
-class ScrollbarThemeOverlayMock : public ScrollbarThemeOverlay {
-public:
- ScrollbarThemeOverlayMock() : ScrollbarThemeOverlay(3, 4, DisallowHitTest, Color(128, 128, 128)) { }
-
-private:
- virtual bool isMockTheme() const OVERRIDE FINAL { return true; }
-};
-
-} // namespace WebCore
-#endif // ScrollbarThemeOverlayMock_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/network/BlobData.cpp b/chromium/third_party/WebKit/Source/core/platform/network/BlobData.cpp
deleted file mode 100644
index 9b9ab907064..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/network/BlobData.cpp
+++ /dev/null
@@ -1,117 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/network/BlobData.h"
-
-#include "core/fileapi/BlobRegistry.h"
-#include "core/fileapi/BlobURL.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefPtr.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-const long long BlobDataItem::toEndOfFile = -1;
-
-RawData::RawData()
-{
-}
-
-void RawData::detachFromCurrentThread()
-{
-}
-
-void BlobDataItem::detachFromCurrentThread()
-{
- data->detachFromCurrentThread();
- path = path.isolatedCopy();
- url = url.copy();
-}
-
-PassOwnPtr<BlobData> BlobData::create()
-{
- return adoptPtr(new BlobData());
-}
-
-void BlobData::detachFromCurrentThread()
-{
- m_contentType = m_contentType.isolatedCopy();
- m_contentDisposition = m_contentDisposition.isolatedCopy();
- for (size_t i = 0; i < m_items.size(); ++i)
- m_items.at(i).detachFromCurrentThread();
-}
-
-void BlobData::appendData(PassRefPtr<RawData> data, long long offset, long long length)
-{
- m_items.append(BlobDataItem(data, offset, length));
-}
-
-void BlobData::appendFile(const String& path)
-{
- m_items.append(BlobDataItem(path));
-}
-
-void BlobData::appendFile(const String& path, long long offset, long long length, double expectedModificationTime)
-{
- m_items.append(BlobDataItem(path, offset, length, expectedModificationTime));
-}
-
-void BlobData::appendBlob(const KURL& url, long long offset, long long length)
-{
- m_items.append(BlobDataItem(url, offset, length));
-}
-
-void BlobData::appendURL(const KURL& url, long long offset, long long length, double expectedModificationTime)
-{
- m_items.append(BlobDataItem(url, offset, length, expectedModificationTime));
-}
-
-void BlobData::swapItems(BlobDataItemList& items)
-{
- m_items.swap(items);
-}
-
-
-BlobDataHandle::BlobDataHandle(PassOwnPtr<BlobData> data, long long size)
-{
- UNUSED_PARAM(size);
- m_internalURL = BlobURL::createInternalURL();
- BlobRegistry::registerBlobURL(m_internalURL, data);
-}
-
-BlobDataHandle::~BlobDataHandle()
-{
- BlobRegistry::unregisterBlobURL(m_internalURL);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/network/BlobData.h b/chromium/third_party/WebKit/Source/core/platform/network/BlobData.h
deleted file mode 100644
index 11ed658d6dd..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/network/BlobData.h
+++ /dev/null
@@ -1,219 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef BlobData_h
-#define BlobData_h
-
-#include "core/platform/FileSystem.h"
-#include "weborigin/KURL.h"
-#include "wtf/Forward.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/ThreadSafeRefCounted.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class RawData : public ThreadSafeRefCounted<RawData> {
-public:
- static PassRefPtr<RawData> create()
- {
- return adoptRef(new RawData());
- }
-
- void detachFromCurrentThread();
-
- const char* data() const { return m_data.data(); }
- size_t length() const { return m_data.size(); }
- Vector<char>* mutableData() { return &m_data; }
-
-private:
- RawData();
-
- Vector<char> m_data;
-};
-
-struct BlobDataItem {
- static const long long toEndOfFile;
-
- // Default constructor.
- BlobDataItem()
- : type(Data)
- , offset(0)
- , length(toEndOfFile)
- , expectedModificationTime(invalidFileTime())
- {
- }
-
- // Constructor for String type (complete string).
- explicit BlobDataItem(PassRefPtr<RawData> data)
- : type(Data)
- , data(data)
- , offset(0)
- , length(toEndOfFile)
- , expectedModificationTime(invalidFileTime())
- {
- }
-
- // Constructor for File type (complete file).
- explicit BlobDataItem(const String& path)
- : type(File)
- , path(path)
- , offset(0)
- , length(toEndOfFile)
- , expectedModificationTime(invalidFileTime())
- {
- }
-
- // Constructor for File type (partial file).
- BlobDataItem(const String& path, long long offset, long long length, double expectedModificationTime)
- : type(File)
- , path(path)
- , offset(offset)
- , length(length)
- , expectedModificationTime(expectedModificationTime)
- {
- }
-
- // Constructor for Blob type.
- BlobDataItem(const KURL& url, long long offset, long long length)
- : type(Blob)
- , url(url)
- , offset(offset)
- , length(length)
- , expectedModificationTime(invalidFileTime())
- {
- }
-
- // Constructor for URL type (e.g. FileSystem files).
- BlobDataItem(const KURL& url, long long offset, long long length, double expectedModificationTime)
- : type(URL)
- , url(url)
- , offset(offset)
- , length(length)
- , expectedModificationTime(expectedModificationTime)
- {
- }
-
- // Detaches from current thread so that it can be passed to another thread.
- void detachFromCurrentThread();
-
- enum {
- Data,
- File,
- Blob,
- URL
- } type;
-
- // For Data type.
- RefPtr<RawData> data;
-
- // For File type.
- String path;
-
- // For Blob or URL type.
- KURL url;
-
- long long offset;
- long long length;
- double expectedModificationTime;
-
-private:
- friend class BlobData;
-
- // Constructor for String type (partial string).
- BlobDataItem(PassRefPtr<RawData> data, long long offset, long long length)
- : type(Data)
- , data(data)
- , offset(offset)
- , length(length)
- , expectedModificationTime(invalidFileTime())
- {
- }
-};
-
-typedef Vector<BlobDataItem> BlobDataItemList;
-
-class BlobData {
- WTF_MAKE_FAST_ALLOCATED;
-public:
- static PassOwnPtr<BlobData> create();
-
- // Detaches from current thread so that it can be passed to another thread.
- void detachFromCurrentThread();
-
- const String& contentType() const { return m_contentType; }
- void setContentType(const String& contentType) { m_contentType = contentType; }
-
- const String& contentDisposition() const { return m_contentDisposition; }
- void setContentDisposition(const String& contentDisposition) { m_contentDisposition = contentDisposition; }
-
- const BlobDataItemList& items() const { return m_items; }
- void swapItems(BlobDataItemList&);
-
- void appendData(PassRefPtr<RawData>, long long offset, long long length);
- void appendFile(const String& path);
- void appendFile(const String& path, long long offset, long long length, double expectedModificationTime);
- void appendBlob(const KURL&, long long offset, long long length);
- void appendURL(const KURL&, long long offset, long long length, double expectedModificationTime);
-
-private:
- friend class BlobRegistryImpl;
- friend class BlobStorageData;
-
- BlobData() { }
-
- // This is only exposed to BlobStorageData.
- void appendData(const RawData&, long long offset, long long length);
-
- String m_contentType;
- String m_contentDisposition;
- BlobDataItemList m_items;
-};
-
-// FIXME: This class is mostly place holder until I get farther along with
-// https://bugs.webkit.org/show_bug.cgi?id=108733 and more specifically with landing
-// https://codereview.chromium.org/11192017/.
-class BlobDataHandle : public ThreadSafeRefCounted<BlobDataHandle> {
-public:
- static PassRefPtr<BlobDataHandle> create(PassOwnPtr<BlobData> data, long long size)
- {
- return adoptRef(new BlobDataHandle(data, size));
- }
-
- ~BlobDataHandle();
-
-private:
- BlobDataHandle(PassOwnPtr<BlobData>, long long size);
- KURL m_internalURL;
-};
-
-} // namespace WebCore
-
-#endif // BlobData_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/network/DNS.cpp b/chromium/third_party/WebKit/Source/core/platform/network/DNS.cpp
deleted file mode 100644
index 7c18e419598..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/network/DNS.cpp
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright (C) 2008 Collin Jackson <collinj@webkit.org>
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/network/DNS.h"
-
-#include "public/platform/Platform.h"
-#include "public/platform/WebPrescientNetworking.h"
-
-namespace WebCore {
-
-void prefetchDNS(const String& hostname)
-{
- WebKit::WebPrescientNetworking* prescientNetworking = WebKit::Platform::current()->prescientNetworking();
-
- if (!prescientNetworking)
- return;
-
- prescientNetworking->prefetchDNS(hostname);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/network/DNS.h b/chromium/third_party/WebKit/Source/core/platform/network/DNS.h
deleted file mode 100644
index 7d05e5c7333..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/network/DNS.h
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright (C) 2008 Collin Jackson <collinj@webkit.org>
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef DNS_h
-#define DNS_h
-
-#include "wtf/Forward.h"
-
-namespace WebCore {
-
-void prefetchDNS(const String& hostname);
-
-} // namespace WebCore
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/network/FormData.cpp b/chromium/third_party/WebKit/Source/core/platform/network/FormData.cpp
deleted file mode 100644
index 6967f83bfec..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/network/FormData.cpp
+++ /dev/null
@@ -1,263 +0,0 @@
-/*
- * Copyright (C) 2004, 2006, 2008, 2011 Apple Inc. All rights reserved.
- * Copyright (C) 2009 Google Inc. All rights reserved.
- * Copyright (C) 2012 Digia Plc. and/or its subsidiary(-ies)
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-#include "core/platform/network/FormData.h"
-
-#include "core/fileapi/File.h"
-#include "core/html/FormDataList.h"
-#include "core/platform/FileSystem.h"
-#include "core/platform/network/BlobData.h"
-#include "core/platform/network/FormDataBuilder.h"
-#include "wtf/text/TextEncoding.h"
-
-namespace WebCore {
-
-inline FormData::FormData()
- : m_identifier(0)
- , m_alwaysStream(false)
- , m_containsPasswordData(false)
-{
-}
-
-inline FormData::FormData(const FormData& data)
- : RefCounted<FormData>()
- , m_elements(data.m_elements)
- , m_identifier(data.m_identifier)
- , m_alwaysStream(false)
- , m_containsPasswordData(data.m_containsPasswordData)
-{
-}
-
-FormData::~FormData()
-{
-}
-
-PassRefPtr<FormData> FormData::create()
-{
- return adoptRef(new FormData);
-}
-
-PassRefPtr<FormData> FormData::create(const void* data, size_t size)
-{
- RefPtr<FormData> result = create();
- result->appendData(data, size);
- return result.release();
-}
-
-PassRefPtr<FormData> FormData::create(const CString& string)
-{
- RefPtr<FormData> result = create();
- result->appendData(string.data(), string.length());
- return result.release();
-}
-
-PassRefPtr<FormData> FormData::create(const Vector<char>& vector)
-{
- RefPtr<FormData> result = create();
- result->appendData(vector.data(), vector.size());
- return result.release();
-}
-
-PassRefPtr<FormData> FormData::create(const FormDataList& list, const WTF::TextEncoding& encoding, EncodingType encodingType)
-{
- RefPtr<FormData> result = create();
- result->appendKeyValuePairItems(list, encoding, false, 0, encodingType);
- return result.release();
-}
-
-PassRefPtr<FormData> FormData::createMultiPart(const FormDataList& list, const WTF::TextEncoding& encoding, Document* document)
-{
- RefPtr<FormData> result = create();
- result->appendKeyValuePairItems(list, encoding, true, document);
- return result.release();
-}
-
-PassRefPtr<FormData> FormData::copy() const
-{
- return adoptRef(new FormData(*this));
-}
-
-PassRefPtr<FormData> FormData::deepCopy() const
-{
- RefPtr<FormData> formData(create());
-
- formData->m_alwaysStream = m_alwaysStream;
-
- size_t n = m_elements.size();
- formData->m_elements.reserveInitialCapacity(n);
- for (size_t i = 0; i < n; ++i) {
- const FormDataElement& e = m_elements[i];
- switch (e.m_type) {
- case FormDataElement::data:
- formData->m_elements.uncheckedAppend(FormDataElement(e.m_data));
- break;
- case FormDataElement::encodedFile:
- formData->m_elements.uncheckedAppend(FormDataElement(e.m_filename, e.m_fileStart, e.m_fileLength, e.m_expectedFileModificationTime));
- break;
- case FormDataElement::encodedBlob:
- formData->m_elements.uncheckedAppend(FormDataElement(e.m_url));
- break;
- case FormDataElement::encodedURL:
- formData->m_elements.uncheckedAppend(FormDataElement(e.m_url, e.m_fileStart, e.m_fileLength, e.m_expectedFileModificationTime));
- break;
- }
- }
- return formData.release();
-}
-
-void FormData::appendData(const void* data, size_t size)
-{
- if (m_elements.isEmpty() || m_elements.last().m_type != FormDataElement::data)
- m_elements.append(FormDataElement());
- FormDataElement& e = m_elements.last();
- size_t oldSize = e.m_data.size();
- e.m_data.grow(oldSize + size);
- memcpy(e.m_data.data() + oldSize, data, size);
-}
-
-void FormData::appendFile(const String& filename)
-{
- m_elements.append(FormDataElement(filename, 0, BlobDataItem::toEndOfFile, invalidFileTime()));
-}
-
-void FormData::appendFileRange(const String& filename, long long start, long long length, double expectedModificationTime)
-{
- m_elements.append(FormDataElement(filename, start, length, expectedModificationTime));
-}
-
-void FormData::appendBlob(const KURL& blobURL)
-{
- m_elements.append(FormDataElement(blobURL));
-}
-
-void FormData::appendURL(const KURL& url)
-{
- m_elements.append(FormDataElement(url, 0, BlobDataItem::toEndOfFile, invalidFileTime()));
-}
-
-void FormData::appendURLRange(const KURL& url, long long start, long long length, double expectedModificationTime)
-{
- m_elements.append(FormDataElement(url, start, length, expectedModificationTime));
-}
-
-void FormData::appendKeyValuePairItems(const FormDataList& list, const WTF::TextEncoding& encoding, bool isMultiPartForm, Document* document, EncodingType encodingType)
-{
- if (isMultiPartForm)
- m_boundary = FormDataBuilder::generateUniqueBoundaryString();
-
- Vector<char> encodedData;
-
- const Vector<FormDataList::Item>& items = list.items();
- size_t formDataListSize = items.size();
- ASSERT(!(formDataListSize % 2));
- for (size_t i = 0; i < formDataListSize; i += 2) {
- const FormDataList::Item& key = items[i];
- const FormDataList::Item& value = items[i + 1];
- if (isMultiPartForm) {
- Vector<char> header;
- FormDataBuilder::beginMultiPartHeader(header, m_boundary.data(), key.data());
-
- // If the current type is blob, then we also need to include the filename
- if (value.blob()) {
- String name;
- if (value.blob()->isFile()) {
- File* file = toFile(value.blob());
- // For file blob, use the filename (or relative path if it is present) as the name.
- name = file->webkitRelativePath().isEmpty() ? file->name() : file->webkitRelativePath();
-
- // If a filename is passed in FormData.append(), use it instead of the file blob's name.
- if (!value.filename().isNull())
- name = value.filename();
- } else {
- // For non-file blob, use the filename if it is passed in FormData.append().
- if (!value.filename().isNull())
- name = value.filename();
- else
- name = "blob";
- }
-
- // We have to include the filename=".." part in the header, even if the filename is empty
- FormDataBuilder::addFilenameToMultiPartHeader(header, encoding, name);
-
- // Add the content type if available, or "application/octet-stream" otherwise (RFC 1867).
- String contentType;
- if (value.blob()->type().isEmpty())
- contentType = "application/octet-stream";
- else
- contentType = value.blob()->type();
- FormDataBuilder::addContentTypeToMultiPartHeader(header, contentType.latin1());
- }
-
- FormDataBuilder::finishMultiPartHeader(header);
-
- // Append body
- appendData(header.data(), header.size());
- if (value.blob()) {
- if (value.blob()->isFile()) {
- File* file = toFile(value.blob());
- // Do not add the file if the path is empty.
- if (!file->path().isEmpty())
- appendFile(file->path());
- if (!file->fileSystemURL().isEmpty())
- appendURL(file->fileSystemURL());
- }
- else
- appendBlob(value.blob()->url());
- } else
- appendData(value.data().data(), value.data().length());
- appendData("\r\n", 2);
- } else {
- // Omit the name "isindex" if it's the first form data element.
- // FIXME: Why is this a good rule? Is this obsolete now?
- if (encodedData.isEmpty() && key.data() == "isindex")
- FormDataBuilder::encodeStringAsFormData(encodedData, value.data());
- else
- FormDataBuilder::addKeyValuePairAsFormData(encodedData, key.data(), value.data(), encodingType);
- }
- }
-
- if (isMultiPartForm)
- FormDataBuilder::addBoundaryToMultiPartHeader(encodedData, m_boundary.data(), true);
-
- appendData(encodedData.data(), encodedData.size());
-}
-
-void FormData::flatten(Vector<char>& data) const
-{
- // Concatenate all the byte arrays, but omit any files.
- data.clear();
- size_t n = m_elements.size();
- for (size_t i = 0; i < n; ++i) {
- const FormDataElement& e = m_elements[i];
- if (e.m_type == FormDataElement::data)
- data.append(e.m_data.data(), static_cast<size_t>(e.m_data.size()));
- }
-}
-
-String FormData::flattenToString() const
-{
- Vector<char> bytes;
- flatten(bytes);
- return Latin1Encoding().decode(reinterpret_cast<const char*>(bytes.data()), bytes.size());
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/network/FormData.h b/chromium/third_party/WebKit/Source/core/platform/network/FormData.h
deleted file mode 100644
index d524a7300a7..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/network/FormData.h
+++ /dev/null
@@ -1,163 +0,0 @@
-/*
- * Copyright (C) 2004, 2006, 2008, 2011 Apple Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#ifndef FormData_h
-#define FormData_h
-
-#include "weborigin/KURL.h"
-#include "wtf/Forward.h"
-#include "wtf/RefCounted.h"
-#include "wtf/Vector.h"
-#include "wtf/text/WTFString.h"
-
-namespace WTF{
-class TextEncoding;
-}
-
-namespace WebCore {
-
-class Document;
-class FormDataList;
-
-class FormDataElement {
-public:
- FormDataElement() : m_type(data) { }
- explicit FormDataElement(const Vector<char>& array) : m_type(data), m_data(array) { }
-
- FormDataElement(const String& filename, long long fileStart, long long fileLength, double expectedFileModificationTime) : m_type(encodedFile), m_filename(filename), m_fileStart(fileStart), m_fileLength(fileLength), m_expectedFileModificationTime(expectedFileModificationTime) { }
- explicit FormDataElement(const KURL& blobURL) : m_type(encodedBlob), m_url(blobURL) { }
- FormDataElement(const KURL& url, long long start, long long length, double expectedFileModificationTime) : m_type(encodedURL), m_url(url), m_fileStart(start), m_fileLength(length), m_expectedFileModificationTime(expectedFileModificationTime) { }
-
- enum Type {
- data,
- encodedFile
- , encodedBlob
- , encodedURL
- } m_type;
- Vector<char> m_data;
- String m_filename;
- KURL m_url; // For Blob or URL.
- long long m_fileStart;
- long long m_fileLength;
- double m_expectedFileModificationTime;
-};
-
-inline bool operator==(const FormDataElement& a, const FormDataElement& b)
-{
- if (&a == &b)
- return true;
-
- if (a.m_type != b.m_type)
- return false;
- if (a.m_type == FormDataElement::data)
- return a.m_data == b.m_data;
- if (a.m_type == FormDataElement::encodedFile)
- return a.m_filename == b.m_filename && a.m_fileStart == b.m_fileStart && a.m_fileLength == b.m_fileLength && a.m_expectedFileModificationTime == b.m_expectedFileModificationTime;
- if (a.m_type == FormDataElement::encodedBlob)
- return a.m_url == b.m_url;
- if (a.m_type == FormDataElement::encodedURL)
- return a.m_url == b.m_url;
-
- return true;
-}
-
-inline bool operator!=(const FormDataElement& a, const FormDataElement& b)
-{
- return !(a == b);
-}
-
-class FormData : public RefCounted<FormData> {
-public:
- enum EncodingType {
- FormURLEncoded, // for application/x-www-form-urlencoded
- TextPlain, // for text/plain
- MultipartFormData // for multipart/form-data
- };
-
- static PassRefPtr<FormData> create();
- static PassRefPtr<FormData> create(const void*, size_t);
- static PassRefPtr<FormData> create(const CString&);
- static PassRefPtr<FormData> create(const Vector<char>&);
- static PassRefPtr<FormData> create(const FormDataList&, const WTF::TextEncoding&, EncodingType = FormURLEncoded);
- static PassRefPtr<FormData> createMultiPart(const FormDataList&, const WTF::TextEncoding&, Document*);
- PassRefPtr<FormData> copy() const;
- PassRefPtr<FormData> deepCopy() const;
- ~FormData();
-
- void appendData(const void* data, size_t);
- void appendFile(const String& filePath);
- void appendFileRange(const String& filename, long long start, long long length, double expectedModificationTime);
- void appendBlob(const KURL& blobURL);
- void appendURL(const KURL&);
- void appendURLRange(const KURL&, long long start, long long length, double expectedModificationTime);
-
- void flatten(Vector<char>&) const; // omits files
- String flattenToString() const; // omits files
-
- bool isEmpty() const { return m_elements.isEmpty(); }
- const Vector<FormDataElement>& elements() const { return m_elements; }
- const Vector<char>& boundary() const { return m_boundary; }
-
- bool alwaysStream() const { return m_alwaysStream; }
- void setAlwaysStream(bool alwaysStream) { m_alwaysStream = alwaysStream; }
-
- // Identifies a particular form submission instance. A value of 0 is used
- // to indicate an unspecified identifier.
- void setIdentifier(int64_t identifier) { m_identifier = identifier; }
- int64_t identifier() const { return m_identifier; }
-
- bool containsPasswordData() const { return m_containsPasswordData; }
- void setContainsPasswordData(bool containsPasswordData) { m_containsPasswordData = containsPasswordData; }
-
- static EncodingType parseEncodingType(const String& type)
- {
- if (equalIgnoringCase(type, "text/plain"))
- return TextPlain;
- if (equalIgnoringCase(type, "multipart/form-data"))
- return MultipartFormData;
- return FormURLEncoded;
- }
-
-private:
- FormData();
- FormData(const FormData&);
-
- void appendKeyValuePairItems(const FormDataList&, const WTF::TextEncoding&, bool isMultiPartForm, Document*, EncodingType = FormURLEncoded);
-
- Vector<FormDataElement> m_elements;
-
- int64_t m_identifier;
- bool m_alwaysStream;
- Vector<char> m_boundary;
- bool m_containsPasswordData;
-};
-
-inline bool operator==(const FormData& a, const FormData& b)
-{
- return a.elements() == b.elements();
-}
-
-inline bool operator!=(const FormData& a, const FormData& b)
-{
- return !(a == b);
-}
-
-} // namespace WebCore
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/network/FormDataBuilder.cpp b/chromium/third_party/WebKit/Source/core/platform/network/FormDataBuilder.cpp
deleted file mode 100644
index 3dbcd3af89c..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/network/FormDataBuilder.cpp
+++ /dev/null
@@ -1,220 +0,0 @@
-/*
- * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
- * (C) 1999 Antti Koivisto (koivisto@kde.org)
- * (C) 2001 Dirk Mueller (mueller@kde.org)
- * Copyright (C) 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
- * (C) 2006 Alexey Proskuryakov (ap@nypop.com)
- * Copyright (C) 2008 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-#include "core/platform/network/FormDataBuilder.h"
-
-#include "core/dom/Document.h"
-#include "wtf/HexNumber.h"
-#include "wtf/RandomNumber.h"
-#include "wtf/text/CString.h"
-#include "wtf/text/TextEncoding.h"
-#include <limits>
-
-namespace WebCore {
-
-// Helper functions
-static inline void append(Vector<char>& buffer, char string)
-{
- buffer.append(string);
-}
-
-static inline void append(Vector<char>& buffer, const char* string)
-{
- buffer.append(string, strlen(string));
-}
-
-static inline void append(Vector<char>& buffer, const CString& string)
-{
- buffer.append(string.data(), string.length());
-}
-
-static void appendQuotedString(Vector<char>& buffer, const CString& string)
-{
- // Append a string as a quoted value, escaping quotes and line breaks.
- // FIXME: Is it correct to use percent escaping here? Other browsers do not encode these characters yet,
- // so we should test popular servers to find out if there is an encoding form they can handle.
- size_t length = string.length();
- for (size_t i = 0; i < length; ++i) {
- char c = string.data()[i];
-
- switch (c) {
- case 0x0a:
- append(buffer, "%0A");
- break;
- case 0x0d:
- append(buffer, "%0D");
- break;
- case '"':
- append(buffer, "%22");
- break;
- default:
- append(buffer, c);
- }
- }
-}
-
-WTF::TextEncoding FormDataBuilder::encodingFromAcceptCharset(const String& acceptCharset, Document* document)
-{
- String normalizedAcceptCharset = acceptCharset;
- normalizedAcceptCharset.replace(',', ' ');
-
- Vector<String> charsets;
- normalizedAcceptCharset.split(' ', charsets);
-
- WTF::TextEncoding encoding;
-
- Vector<String>::const_iterator end = charsets.end();
- for (Vector<String>::const_iterator it = charsets.begin(); it != end; ++it) {
- if ((encoding = WTF::TextEncoding(*it)).isValid())
- return encoding;
- }
-
- return document->inputEncoding();
-}
-
-Vector<char> FormDataBuilder::generateUniqueBoundaryString()
-{
- Vector<char> boundary;
-
- // The RFC 2046 spec says the alphanumeric characters plus the
- // following characters are legal for boundaries: '()+_,-./:=?
- // However the following characters, though legal, cause some sites
- // to fail: (),./:=+
- // Note that our algorithm makes it twice as much likely for 'A' or 'B'
- // to appear in the boundary string, because 0x41 and 0x42 are present in
- // the below array twice.
- static const char alphaNumericEncodingMap[64] = {
- 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
- 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50,
- 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
- 0x59, 0x5A, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66,
- 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E,
- 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76,
- 0x77, 0x78, 0x79, 0x7A, 0x30, 0x31, 0x32, 0x33,
- 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x41, 0x42
- };
-
- // Start with an informative prefix.
- append(boundary, "----WebKitFormBoundary");
-
- // Append 16 random 7bit ascii AlphaNumeric characters.
- Vector<char> randomBytes;
-
- for (unsigned i = 0; i < 4; ++i) {
- unsigned randomness = static_cast<unsigned>(randomNumber() * (std::numeric_limits<unsigned>::max() + 1.0));
- randomBytes.append(alphaNumericEncodingMap[(randomness >> 24) & 0x3F]);
- randomBytes.append(alphaNumericEncodingMap[(randomness >> 16) & 0x3F]);
- randomBytes.append(alphaNumericEncodingMap[(randomness >> 8) & 0x3F]);
- randomBytes.append(alphaNumericEncodingMap[randomness & 0x3F]);
- }
-
- boundary.append(randomBytes);
- boundary.append(0); // Add a 0 at the end so we can use this as a C-style string.
- return boundary;
-}
-
-void FormDataBuilder::beginMultiPartHeader(Vector<char>& buffer, const CString& boundary, const CString& name)
-{
- addBoundaryToMultiPartHeader(buffer, boundary);
-
- // FIXME: This loses data irreversibly if the input name includes characters you can't encode
- // in the website's character set.
- append(buffer, "Content-Disposition: form-data; name=\"");
- appendQuotedString(buffer, name);
- append(buffer, '"');
-}
-
-void FormDataBuilder::addBoundaryToMultiPartHeader(Vector<char>& buffer, const CString& boundary, bool isLastBoundary)
-{
- append(buffer, "--");
- append(buffer, boundary);
-
- if (isLastBoundary)
- append(buffer, "--");
-
- append(buffer, "\r\n");
-}
-
-void FormDataBuilder::addFilenameToMultiPartHeader(Vector<char>& buffer, const WTF::TextEncoding& encoding, const String& filename)
-{
- // FIXME: This loses data irreversibly if the filename includes characters you can't encode
- // in the website's character set.
- append(buffer, "; filename=\"");
- appendQuotedString(buffer, encoding.normalizeAndEncode(filename, WTF::QuestionMarksForUnencodables));
- append(buffer, '"');
-}
-
-void FormDataBuilder::addContentTypeToMultiPartHeader(Vector<char>& buffer, const CString& mimeType)
-{
- append(buffer, "\r\nContent-Type: ");
- append(buffer, mimeType);
-}
-
-void FormDataBuilder::finishMultiPartHeader(Vector<char>& buffer)
-{
- append(buffer, "\r\n\r\n");
-}
-
-void FormDataBuilder::addKeyValuePairAsFormData(Vector<char>& buffer, const CString& key, const CString& value, FormData::EncodingType encodingType)
-{
- if (encodingType == FormData::TextPlain) {
- if (!buffer.isEmpty())
- append(buffer, "\r\n");
- append(buffer, key);
- append(buffer, '=');
- append(buffer, value);
- } else {
- if (!buffer.isEmpty())
- append(buffer, '&');
- encodeStringAsFormData(buffer, key);
- append(buffer, '=');
- encodeStringAsFormData(buffer, value);
- }
-}
-
-void FormDataBuilder::encodeStringAsFormData(Vector<char>& buffer, const CString& string)
-{
- // Same safe characters as Netscape for compatibility.
- static const char safeCharacters[] = "-._*";
-
- // http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.1
- unsigned length = string.length();
- for (unsigned i = 0; i < length; ++i) {
- unsigned char c = string.data()[i];
-
- if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || strchr(safeCharacters, c))
- append(buffer, c);
- else if (c == ' ')
- append(buffer, '+');
- else if (c == '\n' || (c == '\r' && (i + 1 >= length || string.data()[i + 1] != '\n')))
- append(buffer, "%0D%0A");
- else if (c != '\r') {
- append(buffer, '%');
- appendByteAsHex(c, buffer);
- }
- }
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/network/FormDataBuilder.h b/chromium/third_party/WebKit/Source/core/platform/network/FormDataBuilder.h
deleted file mode 100644
index ef9786e2a6f..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/network/FormDataBuilder.h
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * Copyright (C) 2008 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#ifndef FormDataBuilder_h
-#define FormDataBuilder_h
-
-#include "core/platform/network/FormData.h"
-#include "wtf/Forward.h"
-
-namespace WTF{
-class TextEncoding;
-}
-
-namespace WebCore {
-
-class Document;
-
-class FormDataBuilder {
- WTF_MAKE_NONCOPYABLE(FormDataBuilder);
-public:
- static WTF::TextEncoding encodingFromAcceptCharset(const String& acceptCharset, Document* document);
-
- // Helper functions used by HTMLFormElement for multi-part form data
- static Vector<char> generateUniqueBoundaryString();
- static void beginMultiPartHeader(Vector<char>&, const CString& boundary, const CString& name);
- static void addBoundaryToMultiPartHeader(Vector<char>&, const CString& boundary, bool isLastBoundary = false);
- static void addFilenameToMultiPartHeader(Vector<char>&, const WTF::TextEncoding&, const String& filename);
- static void addContentTypeToMultiPartHeader(Vector<char>&, const CString& mimeType);
- static void finishMultiPartHeader(Vector<char>&);
-
- // Helper functions used by HTMLFormElement for non multi-part form data
- static void addKeyValuePairAsFormData(Vector<char>&, const CString& key, const CString& value, FormData::EncodingType = FormData::FormURLEncoded);
- static void encodeStringAsFormData(Vector<char>&, const CString&);
-
-private:
- FormDataBuilder() {}
-};
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/network/HTTPHeaderMap.cpp b/chromium/third_party/WebKit/Source/core/platform/network/HTTPHeaderMap.cpp
deleted file mode 100644
index 3ca4299c7a8..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/network/HTTPHeaderMap.cpp
+++ /dev/null
@@ -1,116 +0,0 @@
-/*
- * Copyright (C) 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/network/HTTPHeaderMap.h"
-
-#include <utility>
-
-using namespace std;
-
-namespace WebCore {
-
-HTTPHeaderMap::HTTPHeaderMap()
-{
-}
-
-HTTPHeaderMap::~HTTPHeaderMap()
-{
-}
-
-PassOwnPtr<CrossThreadHTTPHeaderMapData> HTTPHeaderMap::copyData() const
-{
- OwnPtr<CrossThreadHTTPHeaderMapData> data = adoptPtr(new CrossThreadHTTPHeaderMapData());
- data->reserveInitialCapacity(size());
-
- HTTPHeaderMap::const_iterator end_it = end();
- for (HTTPHeaderMap::const_iterator it = begin(); it != end_it; ++it)
- data->uncheckedAppend(make_pair(it->key.string().isolatedCopy(), it->value.string().isolatedCopy()));
-
- return data.release();
-}
-
-void HTTPHeaderMap::adopt(PassOwnPtr<CrossThreadHTTPHeaderMapData> data)
-{
- clear();
- size_t dataSize = data->size();
- for (size_t index = 0; index < dataSize; ++index) {
- pair<String, String>& header = (*data)[index];
- set(header.first, header.second);
- }
-}
-
-AtomicString HTTPHeaderMap::get(const AtomicString& name) const
-{
- return HashMap<AtomicString, AtomicString, CaseFoldingHash>::get(name);
-}
-
-HTTPHeaderMap::AddResult HTTPHeaderMap::add(const AtomicString& name, const AtomicString& value)
-{
- return HashMap<AtomicString, AtomicString, CaseFoldingHash>::add(name, value);
-}
-
-// Adapter that allows the HashMap to take C strings as keys.
-struct CaseFoldingCStringTranslator {
- static unsigned hash(const char* cString)
- {
- return CaseFoldingHash::hash(cString, strlen(cString));
- }
-
- static bool equal(const AtomicString& key, const char* cString)
- {
- return equalIgnoringCase(key, cString);
- }
-
- static void translate(AtomicString& location, const char* cString, unsigned /*hash*/)
- {
- location = AtomicString(cString);
- }
-};
-
-AtomicString HTTPHeaderMap::get(const char* name) const
-{
- const_iterator i = find<CaseFoldingCStringTranslator>(name);
- if (i == end())
- return nullAtom;
- return i->value;
-}
-
-bool HTTPHeaderMap::contains(const char* name) const
-{
- return find<CaseFoldingCStringTranslator>(name) != end();
-}
-
-HTTPHeaderMap::AddResult HTTPHeaderMap::add(const char* name, const AtomicString& value)
-{
- return HashMap<AtomicString, AtomicString, CaseFoldingHash>::add<CaseFoldingCStringTranslator>(name, value);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/network/HTTPHeaderMap.h b/chromium/third_party/WebKit/Source/core/platform/network/HTTPHeaderMap.h
deleted file mode 100644
index cbf798d9f40..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/network/HTTPHeaderMap.h
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright (C) 2006 Apple Computer, Inc. All rights reserved.
- * Copyright (C) 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef HTTPHeaderMap_h
-#define HTTPHeaderMap_h
-
-#include <utility>
-#include "wtf/HashMap.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/Vector.h"
-#include "wtf/text/AtomicString.h"
-#include "wtf/text/AtomicStringHash.h"
-#include "wtf/text/StringHash.h"
-
-namespace WebCore {
-
- typedef Vector<std::pair<String, String> > CrossThreadHTTPHeaderMapData;
-
- // FIXME: Not every header fits into a map. Notably, multiple Set-Cookie header fields are needed to set multiple cookies.
- class HTTPHeaderMap : public HashMap<AtomicString, AtomicString, CaseFoldingHash> {
- public:
- HTTPHeaderMap();
- ~HTTPHeaderMap();
-
- // Gets a copy of the data suitable for passing to another thread.
- PassOwnPtr<CrossThreadHTTPHeaderMapData> copyData() const;
-
- void adopt(PassOwnPtr<CrossThreadHTTPHeaderMapData>);
-
- AtomicString get(const AtomicString& name) const;
-
- AddResult add(const AtomicString& name, const AtomicString& value);
-
- // Alternate accessors that are faster than converting the char* to AtomicString first.
- bool contains(const char*) const;
- AtomicString get(const char*) const;
- AddResult add(const char* name, const AtomicString& value);
-
- };
-
-} // namespace WebCore
-
-#endif // HTTPHeaderMap_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/network/HTTPParsers.cpp b/chromium/third_party/WebKit/Source/core/platform/network/HTTPParsers.cpp
deleted file mode 100644
index cc2b296921d..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/network/HTTPParsers.cpp
+++ /dev/null
@@ -1,687 +0,0 @@
-/*
- * Copyright (C) 2006 Alexey Proskuryakov (ap@webkit.org)
- * Copyright (C) 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
- * Copyright (C) 2009 Torch Mobile Inc. http://www.torchmobile.com/
- * Copyright (C) 2009 Google Inc. All rights reserved.
- * Copyright (C) 2011 Apple Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/network/HTTPParsers.h"
-
-#include "core/page/ContentSecurityPolicy.h"
-#include "wtf/DateMath.h"
-#include "wtf/text/CString.h"
-#include "wtf/text/StringBuilder.h"
-#include "wtf/text/WTFString.h"
-#include "wtf/unicode/CharacterNames.h"
-
-using namespace WTF;
-
-namespace WebCore {
-
-// true if there is more to parse, after incrementing pos past whitespace.
-// Note: Might return pos == str.length()
-static inline bool skipWhiteSpace(const String& str, unsigned& pos, bool fromHttpEquivMeta)
-{
- unsigned len = str.length();
-
- if (fromHttpEquivMeta) {
- while (pos < len && str[pos] <= ' ')
- ++pos;
- } else {
- while (pos < len && (str[pos] == '\t' || str[pos] == ' '))
- ++pos;
- }
-
- return pos < len;
-}
-
-// Returns true if the function can match the whole token (case insensitive)
-// incrementing pos on match, otherwise leaving pos unchanged.
-// Note: Might return pos == str.length()
-static inline bool skipToken(const String& str, unsigned& pos, const char* token)
-{
- unsigned len = str.length();
- unsigned current = pos;
-
- while (current < len && *token) {
- if (toASCIILower(str[current]) != *token++)
- return false;
- ++current;
- }
-
- if (*token)
- return false;
-
- pos = current;
- return true;
-}
-
-// True if the expected equals sign is seen and there is more to follow.
-static inline bool skipEquals(const String& str, unsigned &pos)
-{
- return skipWhiteSpace(str, pos, false) && str[pos++] == '=' && skipWhiteSpace(str, pos, false);
-}
-
-// True if a value present, incrementing pos to next space or semicolon, if any.
-// Note: might return pos == str.length().
-static inline bool skipValue(const String& str, unsigned& pos)
-{
- unsigned start = pos;
- unsigned len = str.length();
- while (pos < len) {
- if (str[pos] == ' ' || str[pos] == '\t' || str[pos] == ';')
- break;
- ++pos;
- }
- return pos != start;
-}
-
-bool isValidHTTPHeaderValue(const String& name)
-{
- // FIXME: This should really match name against
- // field-value in section 4.2 of RFC 2616.
-
- return name.containsOnlyLatin1() && !name.contains('\r') && !name.contains('\n');
-}
-
-// See RFC 2616, Section 2.2.
-bool isValidHTTPToken(const String& characters)
-{
- if (characters.isEmpty())
- return false;
- for (unsigned i = 0; i < characters.length(); ++i) {
- UChar c = characters[i];
- if (c <= 0x20 || c >= 0x7F
- || c == '(' || c == ')' || c == '<' || c == '>' || c == '@'
- || c == ',' || c == ';' || c == ':' || c == '\\' || c == '"'
- || c == '/' || c == '[' || c == ']' || c == '?' || c == '='
- || c == '{' || c == '}')
- return false;
- }
- return true;
-}
-
-static const size_t maxInputSampleSize = 128;
-static String trimInputSample(const char* p, size_t length)
-{
- String s = String(p, std::min<size_t>(length, maxInputSampleSize));
- if (length > maxInputSampleSize)
- s.append(horizontalEllipsis);
- return s;
-}
-
-ContentDispositionType contentDispositionType(const String& contentDisposition)
-{
- if (contentDisposition.isEmpty())
- return ContentDispositionNone;
-
- Vector<String> parameters;
- contentDisposition.split(';', parameters);
-
- if (parameters.isEmpty())
- return ContentDispositionNone;
-
- String dispositionType = parameters[0];
- dispositionType.stripWhiteSpace();
-
- if (equalIgnoringCase(dispositionType, "inline"))
- return ContentDispositionInline;
-
- // Some broken sites just send bogus headers like
- //
- // Content-Disposition: ; filename="file"
- // Content-Disposition: filename="file"
- // Content-Disposition: name="file"
- //
- // without a disposition token... screen those out.
- if (!isValidHTTPToken(dispositionType))
- return ContentDispositionNone;
-
- // We have a content-disposition of "attachment" or unknown.
- // RFC 2183, section 2.8 says that an unknown disposition
- // value should be treated as "attachment"
- return ContentDispositionAttachment;
-}
-
-bool parseHTTPRefresh(const String& refresh, bool fromHttpEquivMeta, double& delay, String& url)
-{
- unsigned len = refresh.length();
- unsigned pos = 0;
-
- if (!skipWhiteSpace(refresh, pos, fromHttpEquivMeta))
- return false;
-
- while (pos != len && refresh[pos] != ',' && refresh[pos] != ';')
- ++pos;
-
- if (pos == len) { // no URL
- url = String();
- bool ok;
- delay = refresh.stripWhiteSpace().toDouble(&ok);
- return ok;
- } else {
- bool ok;
- delay = refresh.left(pos).stripWhiteSpace().toDouble(&ok);
- if (!ok)
- return false;
-
- ++pos;
- skipWhiteSpace(refresh, pos, fromHttpEquivMeta);
- unsigned urlStartPos = pos;
- if (refresh.find("url", urlStartPos, false) == urlStartPos) {
- urlStartPos += 3;
- skipWhiteSpace(refresh, urlStartPos, fromHttpEquivMeta);
- if (refresh[urlStartPos] == '=') {
- ++urlStartPos;
- skipWhiteSpace(refresh, urlStartPos, fromHttpEquivMeta);
- } else
- urlStartPos = pos; // e.g. "Refresh: 0; url.html"
- }
-
- unsigned urlEndPos = len;
-
- if (refresh[urlStartPos] == '"' || refresh[urlStartPos] == '\'') {
- UChar quotationMark = refresh[urlStartPos];
- urlStartPos++;
- while (urlEndPos > urlStartPos) {
- urlEndPos--;
- if (refresh[urlEndPos] == quotationMark)
- break;
- }
-
- // https://bugs.webkit.org/show_bug.cgi?id=27868
- // Sometimes there is no closing quote for the end of the URL even though there was an opening quote.
- // If we looped over the entire alleged URL string back to the opening quote, just go ahead and use everything
- // after the opening quote instead.
- if (urlEndPos == urlStartPos)
- urlEndPos = len;
- }
-
- url = refresh.substring(urlStartPos, urlEndPos - urlStartPos).stripWhiteSpace();
- return true;
- }
-}
-
-double parseDate(const String& value)
-{
- return parseDateFromNullTerminatedCharacters(value.utf8().data());
-}
-
-// FIXME: This function doesn't comply with RFC 6266.
-// For example, this function doesn't handle the interaction between " and ;
-// that arises from quoted-string, nor does this function properly unquote
-// attribute values. Further this function appears to process parameter names
-// in a case-sensitive manner. (There are likely other bugs as well.)
-String filenameFromHTTPContentDisposition(const String& value)
-{
- Vector<String> keyValuePairs;
- value.split(';', keyValuePairs);
-
- unsigned length = keyValuePairs.size();
- for (unsigned i = 0; i < length; i++) {
- size_t valueStartPos = keyValuePairs[i].find('=');
- if (valueStartPos == kNotFound)
- continue;
-
- String key = keyValuePairs[i].left(valueStartPos).stripWhiteSpace();
-
- if (key.isEmpty() || key != "filename")
- continue;
-
- String value = keyValuePairs[i].substring(valueStartPos + 1).stripWhiteSpace();
-
- // Remove quotes if there are any
- if (value[0] == '\"')
- value = value.substring(1, value.length() - 2);
-
- return value;
- }
-
- return String();
-}
-
-String extractMIMETypeFromMediaType(const String& mediaType)
-{
- StringBuilder mimeType;
- unsigned length = mediaType.length();
- mimeType.reserveCapacity(length);
- for (unsigned i = 0; i < length; i++) {
- UChar c = mediaType[i];
-
- if (c == ';')
- break;
-
- // While RFC 2616 does not allow it, other browsers allow multiple values in the HTTP media
- // type header field, Content-Type. In such cases, the media type string passed here may contain
- // the multiple values separated by commas. For now, this code ignores text after the first comma,
- // which prevents it from simply failing to parse such types altogether. Later for better
- // compatibility we could consider using the first or last valid MIME type instead.
- // See https://bugs.webkit.org/show_bug.cgi?id=25352 for more discussion.
- if (c == ',')
- break;
-
- // FIXME: The following is not correct. RFC 2616 allows linear white space before and
- // after the MIME type, but not within the MIME type itself. And linear white space
- // includes only a few specific ASCII characters; a small subset of isSpaceOrNewline.
- // See https://bugs.webkit.org/show_bug.cgi?id=8644 for a bug tracking part of this.
- if (isSpaceOrNewline(c))
- continue;
-
- mimeType.append(c);
- }
-
- if (mimeType.length() == length)
- return mediaType;
- return mimeType.toString();
-}
-
-String extractCharsetFromMediaType(const String& mediaType)
-{
- unsigned int pos, len;
- findCharsetInMediaType(mediaType, pos, len);
- return mediaType.substring(pos, len);
-}
-
-void findCharsetInMediaType(const String& mediaType, unsigned int& charsetPos, unsigned int& charsetLen, unsigned int start)
-{
- charsetPos = start;
- charsetLen = 0;
-
- size_t pos = start;
- unsigned length = mediaType.length();
-
- while (pos < length) {
- pos = mediaType.find("charset", pos, false);
- if (pos == kNotFound || !pos) {
- charsetLen = 0;
- return;
- }
-
- // is what we found a beginning of a word?
- if (mediaType[pos-1] > ' ' && mediaType[pos-1] != ';') {
- pos += 7;
- continue;
- }
-
- pos += 7;
-
- // skip whitespace
- while (pos != length && mediaType[pos] <= ' ')
- ++pos;
-
- if (mediaType[pos++] != '=') // this "charset" substring wasn't a parameter name, but there may be others
- continue;
-
- while (pos != length && (mediaType[pos] <= ' ' || mediaType[pos] == '"' || mediaType[pos] == '\''))
- ++pos;
-
- // we don't handle spaces within quoted parameter values, because charset names cannot have any
- unsigned endpos = pos;
- while (pos != length && mediaType[endpos] > ' ' && mediaType[endpos] != '"' && mediaType[endpos] != '\'' && mediaType[endpos] != ';')
- ++endpos;
-
- charsetPos = pos;
- charsetLen = endpos - pos;
- return;
- }
-}
-
-ContentSecurityPolicy::ReflectedXSSDisposition parseXSSProtectionHeader(const String& header, String& failureReason, unsigned& failurePosition, String& reportURL)
-{
- DEFINE_STATIC_LOCAL(String, failureReasonInvalidToggle, ("expected 0 or 1"));
- DEFINE_STATIC_LOCAL(String, failureReasonInvalidSeparator, ("expected semicolon"));
- DEFINE_STATIC_LOCAL(String, failureReasonInvalidEquals, ("expected equals sign"));
- DEFINE_STATIC_LOCAL(String, failureReasonInvalidMode, ("invalid mode directive"));
- DEFINE_STATIC_LOCAL(String, failureReasonInvalidReport, ("invalid report directive"));
- DEFINE_STATIC_LOCAL(String, failureReasonDuplicateMode, ("duplicate mode directive"));
- DEFINE_STATIC_LOCAL(String, failureReasonDuplicateReport, ("duplicate report directive"));
- DEFINE_STATIC_LOCAL(String, failureReasonInvalidDirective, ("unrecognized directive"));
-
- unsigned pos = 0;
-
- if (!skipWhiteSpace(header, pos, false))
- return ContentSecurityPolicy::ReflectedXSSUnset;
-
- if (header[pos] == '0')
- return ContentSecurityPolicy::AllowReflectedXSS;
-
- if (header[pos++] != '1') {
- failureReason = failureReasonInvalidToggle;
- return ContentSecurityPolicy::ReflectedXSSInvalid;
- }
-
- ContentSecurityPolicy::ReflectedXSSDisposition result = ContentSecurityPolicy::FilterReflectedXSS;
- bool modeDirectiveSeen = false;
- bool reportDirectiveSeen = false;
-
- while (1) {
- // At end of previous directive: consume whitespace, semicolon, and whitespace.
- if (!skipWhiteSpace(header, pos, false))
- return result;
-
- if (header[pos++] != ';') {
- failureReason = failureReasonInvalidSeparator;
- failurePosition = pos;
- return ContentSecurityPolicy::ReflectedXSSInvalid;
- }
-
- if (!skipWhiteSpace(header, pos, false))
- return result;
-
- // At start of next directive.
- if (skipToken(header, pos, "mode")) {
- if (modeDirectiveSeen) {
- failureReason = failureReasonDuplicateMode;
- failurePosition = pos;
- return ContentSecurityPolicy::ReflectedXSSInvalid;
- }
- modeDirectiveSeen = true;
- if (!skipEquals(header, pos)) {
- failureReason = failureReasonInvalidEquals;
- failurePosition = pos;
- return ContentSecurityPolicy::ReflectedXSSInvalid;
- }
- if (!skipToken(header, pos, "block")) {
- failureReason = failureReasonInvalidMode;
- failurePosition = pos;
- return ContentSecurityPolicy::ReflectedXSSInvalid;
- }
- result = ContentSecurityPolicy::BlockReflectedXSS;
- } else if (skipToken(header, pos, "report")) {
- if (reportDirectiveSeen) {
- failureReason = failureReasonDuplicateReport;
- failurePosition = pos;
- return ContentSecurityPolicy::ReflectedXSSInvalid;
- }
- reportDirectiveSeen = true;
- if (!skipEquals(header, pos)) {
- failureReason = failureReasonInvalidEquals;
- failurePosition = pos;
- return ContentSecurityPolicy::ReflectedXSSInvalid;
- }
- size_t startPos = pos;
- if (!skipValue(header, pos)) {
- failureReason = failureReasonInvalidReport;
- failurePosition = pos;
- return ContentSecurityPolicy::ReflectedXSSInvalid;
- }
- reportURL = header.substring(startPos, pos - startPos);
- failurePosition = startPos; // If later semantic check deems unacceptable.
- } else {
- failureReason = failureReasonInvalidDirective;
- failurePosition = pos;
- return ContentSecurityPolicy::ReflectedXSSInvalid;
- }
- }
-}
-
-ContentTypeOptionsDisposition parseContentTypeOptionsHeader(const String& header)
-{
- if (header.stripWhiteSpace().lower() == "nosniff")
- return ContentTypeOptionsNosniff;
- return ContentTypeOptionsNone;
-}
-
-String extractReasonPhraseFromHTTPStatusLine(const String& statusLine)
-{
- size_t spacePos = statusLine.find(' ');
- // Remove status code from the status line.
- spacePos = statusLine.find(' ', spacePos + 1);
- return statusLine.substring(spacePos + 1);
-}
-
-XFrameOptionsDisposition parseXFrameOptionsHeader(const String& header)
-{
- XFrameOptionsDisposition result = XFrameOptionsNone;
-
- if (header.isEmpty())
- return result;
-
- Vector<String> headers;
- header.split(',', headers);
-
- for (size_t i = 0; i < headers.size(); i++) {
- String currentHeader = headers[i].stripWhiteSpace();
- XFrameOptionsDisposition currentValue = XFrameOptionsNone;
- if (equalIgnoringCase(currentHeader, "deny"))
- currentValue = XFrameOptionsDeny;
- else if (equalIgnoringCase(currentHeader, "sameorigin"))
- currentValue = XFrameOptionsSameOrigin;
- else if (equalIgnoringCase(currentHeader, "allowall"))
- currentValue = XFrameOptionsAllowAll;
- else
- currentValue = XFrameOptionsInvalid;
-
- if (result == XFrameOptionsNone)
- result = currentValue;
- else if (result != currentValue)
- return XFrameOptionsConflict;
- }
- return result;
-}
-
-bool parseRange(const String& range, long long& rangeOffset, long long& rangeEnd, long long& rangeSuffixLength)
-{
- // The format of "Range" header is defined in RFC 2616 Section 14.35.1.
- // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35.1
- // We don't support multiple range requests.
-
- rangeOffset = rangeEnd = rangeSuffixLength = -1;
-
- // The "bytes" unit identifier should be present.
- static const char bytesStart[] = "bytes=";
- if (!range.startsWith(bytesStart, false))
- return false;
- String byteRange = range.substring(sizeof(bytesStart) - 1);
-
- // The '-' character needs to be present.
- int index = byteRange.find('-');
- if (index == -1)
- return false;
-
- // If the '-' character is at the beginning, the suffix length, which specifies the last N bytes, is provided.
- // Example:
- // -500
- if (!index) {
- String suffixLengthString = byteRange.substring(index + 1).stripWhiteSpace();
- bool ok;
- long long value = suffixLengthString.toInt64Strict(&ok);
- if (ok)
- rangeSuffixLength = value;
- return true;
- }
-
- // Otherwise, the first-byte-position and the last-byte-position are provied.
- // Examples:
- // 0-499
- // 500-
- String firstBytePosStr = byteRange.left(index).stripWhiteSpace();
- bool ok;
- long long firstBytePos = firstBytePosStr.toInt64Strict(&ok);
- if (!ok)
- return false;
-
- String lastBytePosStr = byteRange.substring(index + 1).stripWhiteSpace();
- long long lastBytePos = -1;
- if (!lastBytePosStr.isEmpty()) {
- lastBytePos = lastBytePosStr.toInt64Strict(&ok);
- if (!ok)
- return false;
- }
-
- if (firstBytePos < 0 || !(lastBytePos == -1 || lastBytePos >= firstBytePos))
- return false;
-
- rangeOffset = firstBytePos;
- rangeEnd = lastBytePos;
- return true;
-}
-
-// HTTP/1.1 - RFC 2616
-// http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1
-// Request-Line = Method SP Request-URI SP HTTP-Version CRLF
-size_t parseHTTPRequestLine(const char* data, size_t length, String& failureReason, String& method, String& url, HTTPVersion& httpVersion)
-{
- method = String();
- url = String();
- httpVersion = Unknown;
-
- const char* space1 = 0;
- const char* space2 = 0;
- const char* p;
- size_t consumedLength;
-
- for (p = data, consumedLength = 0; consumedLength < length; p++, consumedLength++) {
- if (*p == ' ') {
- if (!space1)
- space1 = p;
- else if (!space2)
- space2 = p;
- } else if (*p == '\n')
- break;
- }
-
- // Haven't finished header line.
- if (consumedLength == length) {
- failureReason = "Incomplete Request Line";
- return 0;
- }
-
- // RequestLine does not contain 3 parts.
- if (!space1 || !space2) {
- failureReason = "Request Line does not appear to contain: <Method> <Url> <HTTPVersion>.";
- return 0;
- }
-
- // The line must end with "\r\n".
- const char* end = p + 1;
- if (*(end - 2) != '\r') {
- failureReason = "Request line does not end with CRLF";
- return 0;
- }
-
- // Request Method.
- method = String(data, space1 - data); // For length subtract 1 for space, but add 1 for data being the first character.
-
- // Request URI.
- url = String(space1 + 1, space2 - space1 - 1); // For length subtract 1 for space.
-
- // HTTP Version.
- String httpVersionString(space2 + 1, end - space2 - 3); // For length subtract 1 for space, and 2 for "\r\n".
- if (httpVersionString.length() != 8 || !httpVersionString.startsWith("HTTP/1."))
- httpVersion = Unknown;
- else if (httpVersionString[7] == '0')
- httpVersion = HTTP_1_0;
- else if (httpVersionString[7] == '1')
- httpVersion = HTTP_1_1;
- else
- httpVersion = Unknown;
-
- return end - data;
-}
-
-size_t parseHTTPHeader(const char* start, size_t length, String& failureReason, AtomicString& nameStr, String& valueStr)
-{
- const char* p = start;
- const char* end = start + length;
-
- Vector<char> name;
- Vector<char> value;
- nameStr = AtomicString();
- valueStr = String();
-
- for (; p < end; p++) {
- switch (*p) {
- case '\r':
- if (name.isEmpty()) {
- if (p + 1 < end && *(p + 1) == '\n')
- return (p + 2) - start;
- failureReason = "CR doesn't follow LF at " + trimInputSample(p, end - p);
- return 0;
- }
- failureReason = "Unexpected CR in name at " + trimInputSample(name.data(), name.size());
- return 0;
- case '\n':
- failureReason = "Unexpected LF in name at " + trimInputSample(name.data(), name.size());
- return 0;
- case ':':
- break;
- default:
- name.append(*p);
- continue;
- }
- if (*p == ':') {
- ++p;
- break;
- }
- }
-
- for (; p < end && *p == 0x20; p++) { }
-
- for (; p < end; p++) {
- switch (*p) {
- case '\r':
- break;
- case '\n':
- failureReason = "Unexpected LF in value at " + trimInputSample(value.data(), value.size());
- return 0;
- default:
- value.append(*p);
- }
- if (*p == '\r') {
- ++p;
- break;
- }
- }
- if (p >= end || *p != '\n') {
- failureReason = "CR doesn't follow LF after value at " + trimInputSample(p, end - p);
- return 0;
- }
- nameStr = AtomicString::fromUTF8(name.data(), name.size());
- valueStr = String::fromUTF8(value.data(), value.size());
- if (nameStr.isNull()) {
- failureReason = "Invalid UTF-8 sequence in header name";
- return 0;
- }
- if (valueStr.isNull()) {
- failureReason = "Invalid UTF-8 sequence in header value";
- return 0;
- }
- return p - start;
-}
-
-size_t parseHTTPRequestBody(const char* data, size_t length, Vector<unsigned char>& body)
-{
- body.clear();
- body.append(data, length);
-
- return length;
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/network/HTTPParsers.h b/chromium/third_party/WebKit/Source/core/platform/network/HTTPParsers.h
deleted file mode 100644
index c705f896438..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/network/HTTPParsers.h
+++ /dev/null
@@ -1,90 +0,0 @@
-/*
- * Copyright (C) 2006 Alexey Proskuryakov (ap@webkit.org)
- * Copyright (C) 2009 Google Inc. All rights reserved.
- * Copyright (C) 2011 Apple Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef HTTPParsers_h
-#define HTTPParsers_h
-
-#include "core/page/ContentSecurityPolicy.h"
-#include "wtf/Forward.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-class HTTPHeaderMap;
-class ResourceResponseBase;
-
-typedef enum {
- ContentDispositionNone,
- ContentDispositionInline,
- ContentDispositionAttachment,
- ContentDispositionOther
-} ContentDispositionType;
-
-enum ContentTypeOptionsDisposition {
- ContentTypeOptionsNone,
- ContentTypeOptionsNosniff
-};
-
-enum XFrameOptionsDisposition {
- XFrameOptionsNone,
- XFrameOptionsDeny,
- XFrameOptionsSameOrigin,
- XFrameOptionsAllowAll,
- XFrameOptionsInvalid,
- XFrameOptionsConflict
-};
-
-ContentDispositionType contentDispositionType(const String&);
-bool isValidHTTPHeaderValue(const String&);
-bool isValidHTTPToken(const String&);
-bool parseHTTPRefresh(const String& refresh, bool fromHttpEquivMeta, double& delay, String& url);
-double parseDate(const String&);
-String filenameFromHTTPContentDisposition(const String&);
-String extractMIMETypeFromMediaType(const String&);
-String extractCharsetFromMediaType(const String&);
-void findCharsetInMediaType(const String& mediaType, unsigned int& charsetPos, unsigned int& charsetLen, unsigned int start = 0);
-ContentSecurityPolicy::ReflectedXSSDisposition parseXSSProtectionHeader(const String& header, String& failureReason, unsigned& failurePosition, String& reportURL);
-String extractReasonPhraseFromHTTPStatusLine(const String&);
-XFrameOptionsDisposition parseXFrameOptionsHeader(const String&);
-
-// -1 could be set to one of the return parameters to indicate the value is not specified.
-bool parseRange(const String&, long long& rangeOffset, long long& rangeEnd, long long& rangeSuffixLength);
-
-ContentTypeOptionsDisposition parseContentTypeOptionsHeader(const String& header);
-
-// Parsing Complete HTTP Messages.
-enum HTTPVersion { Unknown, HTTP_1_0, HTTP_1_1 };
-size_t parseHTTPRequestLine(const char* data, size_t length, String& failureReason, String& method, String& url, HTTPVersion&);
-size_t parseHTTPHeader(const char* data, size_t length, String& failureReason, AtomicString& nameStr, String& valueStr);
-size_t parseHTTPRequestBody(const char* data, size_t length, Vector<unsigned char>& body);
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/network/HTTPRequest.cpp b/chromium/third_party/WebKit/Source/core/platform/network/HTTPRequest.cpp
deleted file mode 100644
index a61fa89a139..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/network/HTTPRequest.cpp
+++ /dev/null
@@ -1,118 +0,0 @@
-/*
- * Copyright (C) 2011 Apple Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/network/HTTPRequest.h"
-
-#include "wtf/text/CString.h"
-
-namespace WebCore {
-
-PassRefPtr<HTTPRequest> HTTPRequest::parseHTTPRequestFromBuffer(const char* data, size_t length, String& failureReason)
-{
- if (!length) {
- failureReason = "No data to parse.";
- return 0;
- }
-
- // Request we will be building.
- RefPtr<HTTPRequest> request = HTTPRequest::create();
-
- // Advance a pointer through the data as needed.
- const char* pos = data;
- size_t remainingLength = length;
-
- // 1. Parse Method + URL.
- size_t requestLineLength = request->parseRequestLine(pos, remainingLength, failureReason);
- if (!requestLineLength)
- return 0;
- pos += requestLineLength;
- remainingLength -= requestLineLength;
-
- // 2. Parse HTTP Headers.
- size_t headersLength = request->parseHeaders(pos, remainingLength, failureReason);
- if (!headersLength)
- return 0;
- pos += headersLength;
- remainingLength -= headersLength;
-
- // 3. Parse HTTP Data.
- size_t dataLength = request->parseRequestBody(pos, remainingLength);
- pos += dataLength;
- remainingLength -= dataLength;
-
- // We should have processed the entire input.
- ASSERT(!remainingLength);
- return request.release();
-}
-
-size_t HTTPRequest::parseRequestLine(const char* data, size_t length, String& failureReason)
-{
- String url;
- size_t result = parseHTTPRequestLine(data, length, failureReason, m_requestMethod, url, m_httpVersion);
- m_url = KURL(KURL(), url);
- return result;
-}
-
-size_t HTTPRequest::parseHeaders(const char* data, size_t length, String& failureReason)
-{
- const char* p = data;
- const char* end = data + length;
- AtomicString name;
- String value;
- for (; p < data + length; p++) {
- size_t consumedLength = parseHTTPHeader(p, end - p, failureReason, name, value);
- if (!consumedLength)
- return 0;
- p += consumedLength;
- if (name.isEmpty())
- break;
- m_headerFields.add(name, value);
- }
- return p - data;
-}
-
-size_t HTTPRequest::parseRequestBody(const char* data, size_t length)
-{
- return parseHTTPRequestBody(data, length, m_body);
-}
-
-HTTPRequest::HTTPRequest()
- : m_httpVersion(Unknown)
-{
-}
-
-HTTPRequest::HTTPRequest(const String& requestMethod, const KURL& url, HTTPVersion version)
- : m_url(url)
- , m_httpVersion(version)
- , m_requestMethod(requestMethod)
-{
-}
-
-HTTPRequest::~HTTPRequest()
-{
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/network/HTTPRequest.h b/chromium/third_party/WebKit/Source/core/platform/network/HTTPRequest.h
deleted file mode 100644
index b1e5d333dce..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/network/HTTPRequest.h
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- * Copyright (C) 2011 Apple Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef HTTPRequest_h
-#define HTTPRequest_h
-
-#include "core/platform/network/HTTPHeaderMap.h"
-#include "core/platform/network/HTTPParsers.h"
-#include "weborigin/KURL.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class HTTPRequest : public RefCounted<HTTPRequest> {
-public:
- static PassRefPtr<HTTPRequest> create() { return adoptRef(new HTTPRequest()); }
- static PassRefPtr<HTTPRequest> create(const String& requestMethod, const KURL& url, HTTPVersion version) { return adoptRef(new HTTPRequest(requestMethod, url, version)); }
- static PassRefPtr<HTTPRequest> parseHTTPRequestFromBuffer(const char* data, size_t length, String& failureReason);
- virtual ~HTTPRequest();
-
- String requestMethod() const { return m_requestMethod; }
- void setRequestMethod(const String& method) { m_requestMethod = method; }
-
- KURL url() const { return m_url; }
- void setURL(const KURL& url) { m_url = url; }
-
- const Vector<unsigned char>& body() const { return m_body; }
-
- const HTTPHeaderMap& headerFields() const { return m_headerFields; }
- void addHeaderField(const AtomicString& name, const String& value) { m_headerFields.add(name, value); }
- void addHeaderField(const char* name, const String& value) { m_headerFields.add(name, value); }
-
-protected:
- HTTPRequest();
- HTTPRequest(const String& requestMethod, const KURL&, HTTPVersion);
-
- // Parsing helpers.
- size_t parseRequestLine(const char* data, size_t length, String& failureReason);
- size_t parseHeaders(const char* data, size_t length, String& failureReason);
- size_t parseRequestBody(const char* data, size_t length);
-
- KURL m_url;
- HTTPVersion m_httpVersion;
- String m_requestMethod;
- HTTPHeaderMap m_headerFields;
- Vector<unsigned char> m_body;
-};
-
-} // namespace WebCore
-
-#endif // HTTPRequest_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/network/MIMEHeader.cpp b/chromium/third_party/WebKit/Source/core/platform/network/MIMEHeader.cpp
deleted file mode 100644
index 168db899fb6..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/network/MIMEHeader.cpp
+++ /dev/null
@@ -1,138 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/network/MIMEHeader.h"
-
-#include "core/platform/SharedBufferChunkReader.h"
-#include "core/platform/network/ParsedContentType.h"
-#include "wtf/HashMap.h"
-#include "wtf/text/CString.h"
-#include "wtf/text/StringBuilder.h"
-#include "wtf/text/StringConcatenate.h"
-#include "wtf/text/StringHash.h"
-
-namespace WebCore {
-
-typedef HashMap<String, String> KeyValueMap;
-
-static KeyValueMap retrieveKeyValuePairs(WebCore::SharedBufferChunkReader* buffer)
-{
- KeyValueMap keyValuePairs;
- String line;
- String key;
- StringBuilder value;
- while (!(line = buffer->nextChunkAsUTF8StringWithLatin1Fallback()).isNull()) {
- if (line.isEmpty())
- break; // Empty line means end of key/value section.
- if (line[0] == '\t') {
- ASSERT(!key.isEmpty());
- value.append(line.substring(1));
- continue;
- }
- // New key/value, store the previous one if any.
- if (!key.isEmpty()) {
- if (keyValuePairs.find(key) != keyValuePairs.end())
- LOG_ERROR("Key duplicate found in MIME header. Key is '%s', previous value replaced.", key.ascii().data());
- keyValuePairs.add(key, value.toString().stripWhiteSpace());
- key = String();
- value.clear();
- }
- size_t semiColonIndex = line.find(':');
- if (semiColonIndex == kNotFound) {
- // This is not a key value pair, ignore.
- continue;
- }
- key = line.substring(0, semiColonIndex).lower().stripWhiteSpace();
- value.append(line.substring(semiColonIndex + 1));
- }
- // Store the last property if there is one.
- if (!key.isEmpty())
- keyValuePairs.set(key, value.toString().stripWhiteSpace());
- return keyValuePairs;
-}
-
-PassRefPtr<MIMEHeader> MIMEHeader::parseHeader(SharedBufferChunkReader* buffer)
-{
- RefPtr<MIMEHeader> mimeHeader = adoptRef(new MIMEHeader);
- KeyValueMap keyValuePairs = retrieveKeyValuePairs(buffer);
- KeyValueMap::iterator mimeParametersIterator = keyValuePairs.find("content-type");
- if (mimeParametersIterator != keyValuePairs.end()) {
- ParsedContentType parsedContentType(mimeParametersIterator->value);
- mimeHeader->m_contentType = parsedContentType.mimeType();
- if (!mimeHeader->isMultipart())
- mimeHeader->m_charset = parsedContentType.charset().stripWhiteSpace();
- else {
- mimeHeader->m_multipartType = parsedContentType.parameterValueForName("type");
- mimeHeader->m_endOfPartBoundary = parsedContentType.parameterValueForName("boundary");
- if (mimeHeader->m_endOfPartBoundary.isNull()) {
- LOG_ERROR("No boundary found in multipart MIME header.");
- return 0;
- }
- mimeHeader->m_endOfPartBoundary.insert("--", 0);
- mimeHeader->m_endOfDocumentBoundary = mimeHeader->m_endOfPartBoundary;
- mimeHeader->m_endOfDocumentBoundary.append("--");
- }
- }
-
- mimeParametersIterator = keyValuePairs.find("content-transfer-encoding");
- if (mimeParametersIterator != keyValuePairs.end())
- mimeHeader->m_contentTransferEncoding = parseContentTransferEncoding(mimeParametersIterator->value);
-
- mimeParametersIterator = keyValuePairs.find("content-location");
- if (mimeParametersIterator != keyValuePairs.end())
- mimeHeader->m_contentLocation = mimeParametersIterator->value;
-
- return mimeHeader.release();
-}
-
-MIMEHeader::Encoding MIMEHeader::parseContentTransferEncoding(const String& text)
-{
- String encoding = text.stripWhiteSpace().lower();
- if (encoding == "base64")
- return Base64;
- if (encoding == "quoted-printable")
- return QuotedPrintable;
- if (encoding == "8bit")
- return EightBit;
- if (encoding == "7bit")
- return SevenBit;
- if (encoding == "binary")
- return Binary;
- LOG_ERROR("Unknown encoding '%s' found in MIME header.", text.ascii().data());
- return Unknown;
-}
-
-MIMEHeader::MIMEHeader()
- : m_contentTransferEncoding(Unknown)
-{
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/network/MIMEHeader.h b/chromium/third_party/WebKit/Source/core/platform/network/MIMEHeader.h
deleted file mode 100644
index 2a724c3d4ba..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/network/MIMEHeader.h
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef MIMEHeader_h
-#define MIMEHeader_h
-
-#include "wtf/HashMap.h"
-#include "wtf/RefCounted.h"
-#include "wtf/RefPtr.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class SharedBufferChunkReader;
-
-// FIXME: This class is a limited MIME parser used to parse the MIME headers of MHTML files.
-class MIMEHeader : public RefCounted<MIMEHeader> {
-public:
- enum Encoding {
- QuotedPrintable,
- Base64,
- EightBit,
- SevenBit,
- Binary,
- Unknown
- };
-
- static PassRefPtr<MIMEHeader> parseHeader(SharedBufferChunkReader* crLFLineReader);
-
- bool isMultipart() const { return m_contentType.startsWith("multipart/"); }
-
- String contentType() const { return m_contentType; }
- String charset() const { return m_charset; }
- Encoding contentTransferEncoding() const { return m_contentTransferEncoding; }
- String contentLocation() const { return m_contentLocation; }
-
- // Multi-part type and boundaries are only valid for multipart MIME headers.
- String multiPartType() const { return m_multipartType; }
- String endOfPartBoundary() const { return m_endOfPartBoundary; }
- String endOfDocumentBoundary() const { return m_endOfDocumentBoundary; }
-
-private:
- MIMEHeader();
-
- static Encoding parseContentTransferEncoding(const String&);
-
- String m_contentType;
- String m_charset;
- Encoding m_contentTransferEncoding;
- String m_contentLocation;
- String m_multipartType;
- String m_endOfPartBoundary;
- String m_endOfDocumentBoundary;
-};
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/network/NetworkStateNotifier.cpp b/chromium/third_party/WebKit/Source/core/platform/network/NetworkStateNotifier.cpp
deleted file mode 100644
index 94cb9d02407..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/network/NetworkStateNotifier.cpp
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * Copyright (C) 2008 Apple Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/network/NetworkStateNotifier.h"
-
-#include "wtf/Assertions.h"
-#include "wtf/StdLibExtras.h"
-#include "wtf/Threading.h"
-
-namespace WebCore {
-
-NetworkStateNotifier& networkStateNotifier()
-{
- AtomicallyInitializedStatic(NetworkStateNotifier*, networkStateNotifier = new NetworkStateNotifier);
-
- return *networkStateNotifier;
-}
-
-void NetworkStateNotifier::setNetworkStateChangedFunction(void(*function)())
-{
- ASSERT(!m_networkStateChangedFunction);
-
- m_networkStateChangedFunction = function;
-}
-
-void NetworkStateNotifier::setOnLine(bool onLine)
-{
- if (m_isOnLine == onLine)
- return;
-
- m_isOnLine = onLine;
-
- if (m_networkStateChangedFunction)
- m_networkStateChangedFunction();
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/network/NetworkStateNotifier.h b/chromium/third_party/WebKit/Source/core/platform/network/NetworkStateNotifier.h
deleted file mode 100644
index f5af3082b53..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/network/NetworkStateNotifier.h
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * Copyright (C) 2008 Apple Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef NetworkStateNotifier_h
-#define NetworkStateNotifier_h
-
-#include "wtf/FastAllocBase.h"
-#include "wtf/Noncopyable.h"
-
-namespace WebCore {
-
-class NetworkStateNotifier {
- WTF_MAKE_NONCOPYABLE(NetworkStateNotifier); WTF_MAKE_FAST_ALLOCATED;
-public:
- NetworkStateNotifier();
- void setNetworkStateChangedFunction(void (*)());
-
- bool onLine() const { return m_isOnLine; }
- void setOnLine(bool);
-
-private:
- bool m_isOnLine;
- void (*m_networkStateChangedFunction)();
-
- void updateState();
-};
-
-inline NetworkStateNotifier::NetworkStateNotifier()
- : m_isOnLine(true)
- , m_networkStateChangedFunction(0)
-{
-}
-
-inline void NetworkStateNotifier::updateState() { }
-
-NetworkStateNotifier& networkStateNotifier();
-
-};
-
-#endif // NetworkStateNotifier_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/network/ParsedContentType.cpp b/chromium/third_party/WebKit/Source/core/platform/network/ParsedContentType.cpp
deleted file mode 100644
index 58ee9d40163..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/network/ParsedContentType.cpp
+++ /dev/null
@@ -1,255 +0,0 @@
- /*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- * Copyright (C) 2012 Intel Corporation. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/network/ParsedContentType.h"
-
-#include "wtf/text/CString.h"
-#include "wtf/text/StringBuilder.h"
-
-namespace WebCore {
-
-class DummyParsedContentType {
-public:
- void setContentType(const SubstringRange&) const { }
- void setContentTypeParameter(const SubstringRange&, const SubstringRange&) const { }
-};
-
-static void skipSpaces(const String& input, unsigned& startIndex)
-{
- while (startIndex < input.length() && input[startIndex] == ' ')
- ++startIndex;
-}
-
-static bool isTokenCharacter(char c)
-{
- return isASCII(c) && c > ' ' && c != '"' && c != '(' && c != ')' && c != ',' && c != '/' && (c < ':' || c > '@') && (c < '[' || c > ']');
-}
-
-static SubstringRange parseToken(const String& input, unsigned& startIndex)
-{
- unsigned inputLength = input.length();
- unsigned tokenStart = startIndex;
- unsigned& tokenEnd = startIndex;
-
- if (tokenEnd >= inputLength)
- return SubstringRange();
-
- while (tokenEnd < inputLength) {
- if (!isTokenCharacter(input[tokenEnd]))
- return SubstringRange(tokenStart, tokenEnd - tokenStart);
- ++tokenEnd;
- }
-
- return SubstringRange(tokenStart, tokenEnd - tokenStart);
-}
-
-static SubstringRange parseQuotedString(const String& input, unsigned& startIndex)
-{
- unsigned inputLength = input.length();
- unsigned quotedStringStart = startIndex + 1;
- unsigned& quotedStringEnd = startIndex;
-
- if (quotedStringEnd >= inputLength)
- return SubstringRange();
-
- if (input[quotedStringEnd++] != '"' || quotedStringEnd >= inputLength)
- return SubstringRange();
-
- bool lastCharacterWasBackslash = false;
- char currentCharacter;
- while ((currentCharacter = input[quotedStringEnd++]) != '"' || lastCharacterWasBackslash) {
- if (quotedStringEnd >= inputLength)
- return SubstringRange();
- if (currentCharacter == '\\' && !lastCharacterWasBackslash) {
- lastCharacterWasBackslash = true;
- continue;
- }
- if (lastCharacterWasBackslash)
- lastCharacterWasBackslash = false;
- }
- return SubstringRange(quotedStringStart, quotedStringEnd - quotedStringStart - 1);
-}
-
-static String substringForRange(const String& string, const SubstringRange& range)
-{
- return string.substring(range.first, range.second);
-}
-
-// From http://tools.ietf.org/html/rfc2045#section-5.1:
-//
-// content := "Content-Type" ":" type "/" subtype
-// *(";" parameter)
-// ; Matching of media type and subtype
-// ; is ALWAYS case-insensitive.
-//
-// type := discrete-type / composite-type
-//
-// discrete-type := "text" / "image" / "audio" / "video" /
-// "application" / extension-token
-//
-// composite-type := "message" / "multipart" / extension-token
-//
-// extension-token := ietf-token / x-token
-//
-// ietf-token := <An extension token defined by a
-// standards-track RFC and registered
-// with IANA.>
-//
-// x-token := <The two characters "X-" or "x-" followed, with
-// no intervening white space, by any token>
-//
-// subtype := extension-token / iana-token
-//
-// iana-token := <A publicly-defined extension token. Tokens
-// of this form must be registered with IANA
-// as specified in RFC 2048.>
-//
-// parameter := attribute "=" value
-//
-// attribute := token
-// ; Matching of attributes
-// ; is ALWAYS case-insensitive.
-//
-// value := token / quoted-string
-//
-// token := 1*<any (US-ASCII) CHAR except SPACE, CTLs,
-// or tspecials>
-//
-// tspecials := "(" / ")" / "<" / ">" / "@" /
-// "," / ";" / ":" / "\" / <">
-// "/" / "[" / "]" / "?" / "="
-// ; Must be in quoted-string,
-// ; to use within parameter values
-
-template <class ReceiverType>
-bool parseContentType(const String& contentType, ReceiverType& receiver)
-{
- unsigned index = 0;
- unsigned contentTypeLength = contentType.length();
- skipSpaces(contentType, index);
- if (index >= contentTypeLength) {
- LOG_ERROR("Invalid Content-Type string '%s'", contentType.ascii().data());
- return false;
- }
-
- // There should not be any quoted strings until we reach the parameters.
- size_t semiColonIndex = contentType.find(';', index);
- if (semiColonIndex == kNotFound) {
- receiver.setContentType(SubstringRange(index, contentTypeLength - index));
- return true;
- }
-
- receiver.setContentType(SubstringRange(index, semiColonIndex - index));
- index = semiColonIndex + 1;
- while (true) {
- skipSpaces(contentType, index);
- SubstringRange keyRange = parseToken(contentType, index);
- if (!keyRange.second || index >= contentTypeLength) {
- LOG_ERROR("Invalid Content-Type parameter name.");
- return false;
- }
-
- // Should we tolerate spaces here?
- if (contentType[index++] != '=' || index >= contentTypeLength) {
- LOG_ERROR("Invalid Content-Type malformed parameter.");
- return false;
- }
-
- // Should we tolerate spaces here?
- String value;
- SubstringRange valueRange;
- if (contentType[index] == '"')
- valueRange = parseQuotedString(contentType, index);
- else
- valueRange = parseToken(contentType, index);
-
- if (!valueRange.second) {
- LOG_ERROR("Invalid Content-Type, invalid parameter value.");
- return false;
- }
-
- // Should we tolerate spaces here?
- if (index < contentTypeLength && contentType[index++] != ';') {
- LOG_ERROR("Invalid Content-Type, invalid character at the end of key/value parameter.");
- return false;
- }
-
- receiver.setContentTypeParameter(keyRange, valueRange);
-
- if (index >= contentTypeLength)
- return true;
- }
-
- return true;
-}
-
-bool isValidContentType(const String& contentType)
-{
- if (contentType.contains('\r') || contentType.contains('\n'))
- return false;
-
- DummyParsedContentType parsedContentType = DummyParsedContentType();
- return parseContentType<DummyParsedContentType>(contentType, parsedContentType);
-}
-
-ParsedContentType::ParsedContentType(const String& contentType)
- : m_contentType(contentType.stripWhiteSpace())
-{
- parseContentType<ParsedContentType>(m_contentType, *this);
-}
-
-String ParsedContentType::charset() const
-{
- return parameterValueForName("charset");
-}
-
-String ParsedContentType::parameterValueForName(const String& name) const
-{
- return m_parameters.get(name);
-}
-
-size_t ParsedContentType::parameterCount() const
-{
- return m_parameters.size();
-}
-
-void ParsedContentType::setContentType(const SubstringRange& contentRange)
-{
- m_mimeType = substringForRange(m_contentType, contentRange).stripWhiteSpace();
-}
-
-void ParsedContentType::setContentTypeParameter(const SubstringRange& key, const SubstringRange& value)
-{
- m_parameters.set(substringForRange(m_contentType, key), substringForRange(m_contentType, value));
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/network/ParsedContentType.h b/chromium/third_party/WebKit/Source/core/platform/network/ParsedContentType.h
deleted file mode 100644
index c463c19571c..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/network/ParsedContentType.h
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- * Copyright (C) 2012 Intel Corporation. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ParsedContentType_h
-#define ParsedContentType_h
-
-#include "wtf/HashMap.h"
-#include "wtf/text/StringHash.h"
-
-namespace WebCore {
-
-// <index, length>
-typedef std::pair<unsigned, unsigned> SubstringRange;
-bool isValidContentType(const String&);
-
-// FIXME: add support for comments.
-class ParsedContentType {
-public:
- explicit ParsedContentType(const String&);
-
- String mimeType() const { return m_mimeType; }
- String charset() const;
-
- // Note that in the case of multiple values for the same name, the last value is returned.
- String parameterValueForName(const String&) const;
- size_t parameterCount() const;
-
-private:
- template<class ReceiverType>
- friend bool parseContentType(const String&, ReceiverType&);
- void setContentType(const SubstringRange&);
- void setContentTypeParameter(const SubstringRange&, const SubstringRange&);
-
- typedef HashMap<String, String> KeyValuePairs;
- String m_contentType;
- KeyValuePairs m_parameters;
- String m_mimeType;
-};
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/network/ProxyServer.cpp b/chromium/third_party/WebKit/Source/core/platform/network/ProxyServer.cpp
deleted file mode 100644
index e9b589b15cf..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/network/ProxyServer.cpp
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * Copyright (C) 2010 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/network/ProxyServer.h"
-
-#include "wtf/text/StringBuilder.h"
-
-namespace WebCore {
-
-static void appendProxyServerString(StringBuilder& builder, const ProxyServer& proxyServer)
-{
- switch (proxyServer.type()) {
- case ProxyServer::Direct:
- builder.append("DIRECT");
- return;
- case ProxyServer::HTTP:
- case ProxyServer::HTTPS:
- builder.append("PROXY");
- break;
- case ProxyServer::SOCKS:
- builder.append("SOCKS");
- break;
- }
-
- builder.append(' ');
-
- ASSERT(!proxyServer.hostName().isNull());
- builder.append(proxyServer.hostName());
-
- builder.append(':');
- ASSERT(proxyServer.port() != -1);
- builder.appendNumber(proxyServer.port());
-}
-
-String toString(const Vector<ProxyServer>& proxyServers)
-{
- if (proxyServers.isEmpty())
- return "DIRECT";
-
- StringBuilder stringBuilder;
- for (size_t i = 0; i < proxyServers.size(); ++i) {
- if (i)
- stringBuilder.append("; ");
-
- appendProxyServerString(stringBuilder, proxyServers[i]);
- }
-
- return stringBuilder.toString();
-}
-
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/network/ProxyServer.h b/chromium/third_party/WebKit/Source/core/platform/network/ProxyServer.h
deleted file mode 100644
index d46a8837d53..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/network/ProxyServer.h
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * Copyright (C) 2010 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ProxyServer_h
-#define ProxyServer_h
-
-#include "wtf/Vector.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class KURL;
-class NetworkingContext;
-
-// Represents a single proxy server.
-class ProxyServer {
-public:
- enum Type {
- Direct,
- HTTP,
- HTTPS,
- SOCKS,
- };
-
- ProxyServer()
- : m_type(Direct)
- , m_port(-1)
- {
- }
-
- ProxyServer(Type type, const String& hostName, int port)
- : m_type(type)
- , m_hostName(hostName)
- , m_port(port)
- {
- }
-
- Type type() const { return m_type; }
- const String& hostName() const { return m_hostName; }
- int port() const { return m_port; }
-
-private:
- Type m_type;
- String m_hostName;
- int m_port;
-};
-
-// Return a vector of proxy servers for the given URL.
-Vector<ProxyServer> proxyServersForURL(const KURL&, const NetworkingContext*);
-
-// Converts the given vector of proxy servers to a PAC string, as described in
-// http://web.archive.org/web/20060424005037/wp.netscape.com/eng/mozilla/2.0/relnotes/demo/proxy-live.html
-String toString(const Vector<ProxyServer>&);
-
-} // namespace WebCore
-
-#endif // ProxyServer_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/network/ResourceError.cpp b/chromium/third_party/WebKit/Source/core/platform/network/ResourceError.cpp
deleted file mode 100644
index 0ee01b3b29b..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/network/ResourceError.cpp
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * Copyright (C) 2006 Apple Computer, Inc. All rights reserved.
- * Copyright (C) 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/network/ResourceError.h"
-
-#include "public/platform/Platform.h"
-#include "public/platform/WebURL.h"
-#include "public/platform/WebURLError.h"
-#include "weborigin/KURL.h"
-
-namespace WebCore {
-
-const char* const errorDomainWebKitInternal = "WebKitInternal";
-
-ResourceError ResourceError::cancelledError(const String& failingURL)
-{
- return WebKit::Platform::current()->cancelledError(KURL(ParsedURLString, failingURL));
-}
-
-ResourceError ResourceError::copy() const
-{
- ResourceError errorCopy;
- errorCopy.m_domain = m_domain.isolatedCopy();
- errorCopy.m_errorCode = m_errorCode;
- errorCopy.m_failingURL = m_failingURL.isolatedCopy();
- errorCopy.m_localizedDescription = m_localizedDescription.isolatedCopy();
- errorCopy.m_isNull = m_isNull;
- errorCopy.m_isCancellation = m_isCancellation;
- errorCopy.m_isTimeout = m_isTimeout;
- return errorCopy;
-}
-
-bool ResourceError::compare(const ResourceError& a, const ResourceError& b)
-{
- if (a.isNull() && b.isNull())
- return true;
-
- if (a.isNull() || b.isNull())
- return false;
-
- if (a.domain() != b.domain())
- return false;
-
- if (a.errorCode() != b.errorCode())
- return false;
-
- if (a.failingURL() != b.failingURL())
- return false;
-
- if (a.localizedDescription() != b.localizedDescription())
- return false;
-
- if (a.isCancellation() != b.isCancellation())
- return false;
-
- if (a.isTimeout() != b.isTimeout())
- return false;
-
- return true;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/network/ResourceError.h b/chromium/third_party/WebKit/Source/core/platform/network/ResourceError.h
deleted file mode 100644
index ec1d3a888b8..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/network/ResourceError.h
+++ /dev/null
@@ -1,92 +0,0 @@
-/*
- * Copyright (C) 2006 Apple Computer, Inc. All rights reserved.
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ResourceError_h
-#define ResourceError_h
-
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-extern const char* const errorDomainWebKitInternal; // Used for errors that won't be exposed to clients.
-
-class ResourceError {
-public:
- static ResourceError cancelledError(const String& failingURL);
-
- ResourceError()
- : m_errorCode(0)
- , m_isNull(true)
- , m_isCancellation(false)
- , m_isTimeout(false)
- {
- }
-
- ResourceError(const String& domain, int errorCode, const String& failingURL, const String& localizedDescription)
- : m_domain(domain)
- , m_errorCode(errorCode)
- , m_failingURL(failingURL)
- , m_localizedDescription(localizedDescription)
- , m_isNull(false)
- , m_isCancellation(false)
- , m_isTimeout(false)
- {
- }
-
- // Makes a deep copy. Useful for when you need to use a ResourceError on another thread.
- ResourceError copy() const;
-
- bool isNull() const { return m_isNull; }
-
- const String& domain() const { return m_domain; }
- int errorCode() const { return m_errorCode; }
- const String& failingURL() const { return m_failingURL; }
- const String& localizedDescription() const { return m_localizedDescription; }
-
- void setIsCancellation(bool isCancellation) { m_isCancellation = isCancellation; }
- bool isCancellation() const { return m_isCancellation; }
-
- void setIsTimeout(bool isTimeout) { m_isTimeout = isTimeout; }
- bool isTimeout() const { return m_isTimeout; }
-
- static bool compare(const ResourceError&, const ResourceError&);
-
-private:
- String m_domain;
- int m_errorCode;
- String m_failingURL;
- String m_localizedDescription;
- bool m_isNull;
- bool m_isCancellation;
- bool m_isTimeout;
-};
-
-inline bool operator==(const ResourceError& a, const ResourceError& b) { return ResourceError::compare(a, b); }
-inline bool operator!=(const ResourceError& a, const ResourceError& b) { return !(a == b); }
-
-} // namespace WebCore
-
-#endif // ResourceError_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/network/ResourceLoadInfo.h b/chromium/third_party/WebKit/Source/core/platform/network/ResourceLoadInfo.h
deleted file mode 100644
index 0e9926c8333..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/network/ResourceLoadInfo.h
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Copyright (C) 2010 Google, Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-
-#ifndef ResourceLoadInfo_h
-#define ResourceLoadInfo_h
-
-#include "core/platform/network/HTTPHeaderMap.h"
-#include "wtf/RefCounted.h"
-
-namespace WebCore {
-
-struct ResourceLoadInfo : RefCounted<ResourceLoadInfo> {
- ResourceLoadInfo()
- : httpStatusCode(0)
- , encodedDataLength(-1) { }
-
- int httpStatusCode;
- String httpStatusText;
- long long encodedDataLength;
- HTTPHeaderMap requestHeaders;
- HTTPHeaderMap responseHeaders;
- String requestHeadersText;
- String responseHeadersText;
-};
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/network/ResourceLoadPriority.h b/chromium/third_party/WebKit/Source/core/platform/network/ResourceLoadPriority.h
deleted file mode 100644
index 5a7104f97b1..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/network/ResourceLoadPriority.h
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Copyright (C) 2010 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ResourceLoadPriority_h
-#define ResourceLoadPriority_h
-
-namespace WebCore {
-
-enum ResourceLoadPriority {
- // The unresolved priority is here for the convenience of the clients. It should not be passed to the ResourceLoadScheduler.
- ResourceLoadPriorityUnresolved = -1,
- ResourceLoadPriorityVeryLow = 0,
- ResourceLoadPriorityLow,
- ResourceLoadPriorityMedium,
- ResourceLoadPriorityHigh,
- ResourceLoadPriorityVeryHigh,
- ResourceLoadPriorityLowest = ResourceLoadPriorityVeryLow,
- ResourceLoadPriorityHighest = ResourceLoadPriorityVeryHigh,
-};
-
-}
-
-#endif
-
diff --git a/chromium/third_party/WebKit/Source/core/platform/network/ResourceLoadTiming.h b/chromium/third_party/WebKit/Source/core/platform/network/ResourceLoadTiming.h
deleted file mode 100644
index 56025d1101d..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/network/ResourceLoadTiming.h
+++ /dev/null
@@ -1,123 +0,0 @@
-/*
- * Copyright (C) 2010 Google, Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ResourceLoadTiming_h
-#define ResourceLoadTiming_h
-
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/RefPtr.h"
-
-namespace WebCore {
-
-class DocumentLoadTiming;
-
-class ResourceLoadTiming : public RefCounted<ResourceLoadTiming> {
-public:
- static PassRefPtr<ResourceLoadTiming> create()
- {
- return adoptRef(new ResourceLoadTiming);
- }
-
- PassRefPtr<ResourceLoadTiming> deepCopy()
- {
- RefPtr<ResourceLoadTiming> timing = create();
- timing->requestTime = requestTime;
- timing->proxyStart = proxyStart;
- timing->proxyEnd = proxyEnd;
- timing->dnsStart = dnsStart;
- timing->dnsEnd = dnsEnd;
- timing->connectStart = connectStart;
- timing->connectEnd = connectEnd;
- timing->sendStart = sendStart;
- timing->sendEnd = sendEnd;
- timing->receiveHeadersEnd = receiveHeadersEnd;
- timing->sslStart = sslStart;
- timing->sslEnd = sslEnd;
- return timing.release();
- }
-
- bool operator==(const ResourceLoadTiming& other) const
- {
- return requestTime == other.requestTime
- && proxyStart == other.proxyStart
- && proxyEnd == other.proxyEnd
- && dnsStart == other.dnsStart
- && dnsEnd == other.dnsEnd
- && connectStart == other.connectStart
- && connectEnd == other.connectEnd
- && sendStart == other.sendStart
- && sendEnd == other.sendEnd
- && receiveHeadersEnd == other.receiveHeadersEnd
- && sslStart == other.sslStart
- && sslEnd == other.sslEnd;
- }
-
- bool operator!=(const ResourceLoadTiming& other) const
- {
- return !(*this == other);
- }
-
- // We want to present a unified timeline to Javascript. Using walltime is problematic, because the clock may skew while resources
- // load. To prevent that skew, we record a single reference walltime when root document navigation begins. All other times are
- // recorded using monotonicallyIncreasingTime(). When a time needs to be presented to Javascript, we build a pseudo-walltime
- // using the following equation (requestTime as example):
- // pseudo time = document wall reference + (requestTime - document monotonic reference).
- double requestTime; // All monotonicallyIncreasingTime() in seconds
- double proxyStart;
- double proxyEnd;
- double dnsStart;
- double dnsEnd;
- double connectStart;
- double connectEnd;
- double sendStart;
- double sendEnd;
- double receiveHeadersEnd;
- double sslStart;
- double sslEnd;
-
- double calculateMillisecondDelta(double time) const { return time ? (time - requestTime) * 1000 : -1; }
-
-private:
- ResourceLoadTiming()
- : requestTime(0)
- , proxyStart(0)
- , proxyEnd(0)
- , dnsStart(0)
- , dnsEnd(0)
- , connectStart(0)
- , connectEnd(0)
- , sendStart(0)
- , sendEnd(0)
- , receiveHeadersEnd(0)
- , sslStart(0)
- , sslEnd(0)
- {
- }
-};
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/network/ResourceRequest.cpp b/chromium/third_party/WebKit/Source/core/platform/network/ResourceRequest.cpp
deleted file mode 100644
index 670d1faaacd..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/network/ResourceRequest.cpp
+++ /dev/null
@@ -1,345 +0,0 @@
-/*
- * Copyright (C) 2003, 2006 Apple Computer, Inc. All rights reserved.
- * Copyright (C) 2009, 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/network/ResourceRequest.h"
-
-#include "core/platform/network/ResourceRequest.h"
-
-namespace WebCore {
-
-double ResourceRequest::s_defaultTimeoutInterval = INT_MAX;
-
-PassOwnPtr<ResourceRequest> ResourceRequest::adopt(PassOwnPtr<CrossThreadResourceRequestData> data)
-{
- OwnPtr<ResourceRequest> request = adoptPtr(new ResourceRequest());
- request->setURL(data->m_url);
- request->setCachePolicy(data->m_cachePolicy);
- request->setTimeoutInterval(data->m_timeoutInterval);
- request->setFirstPartyForCookies(data->m_firstPartyForCookies);
- request->setHTTPMethod(data->m_httpMethod);
- request->setPriority(data->m_priority);
-
- request->m_httpHeaderFields.adopt(data->m_httpHeaders.release());
-
- request->setHTTPBody(data->m_httpBody);
- request->setAllowCookies(data->m_allowCookies);
- request->setHasUserGesture(data->m_hasUserGesture);
- request->setDownloadToFile(data->m_downloadToFile);
- request->setRequestorID(data->m_requestorID);
- request->setRequestorProcessID(data->m_requestorProcessID);
- request->setAppCacheHostID(data->m_appCacheHostID);
- request->setTargetType(data->m_targetType);
- return request.release();
-}
-
-PassOwnPtr<CrossThreadResourceRequestData> ResourceRequest::copyData() const
-{
- OwnPtr<CrossThreadResourceRequestData> data = adoptPtr(new CrossThreadResourceRequestData());
- data->m_url = url().copy();
- data->m_cachePolicy = cachePolicy();
- data->m_timeoutInterval = timeoutInterval();
- data->m_firstPartyForCookies = firstPartyForCookies().copy();
- data->m_httpMethod = httpMethod().isolatedCopy();
- data->m_httpHeaders = httpHeaderFields().copyData();
- data->m_priority = priority();
-
- if (m_httpBody)
- data->m_httpBody = m_httpBody->deepCopy();
- data->m_allowCookies = m_allowCookies;
- data->m_hasUserGesture = m_hasUserGesture;
- data->m_downloadToFile = m_downloadToFile;
- data->m_requestorID = m_requestorID;
- data->m_requestorProcessID = m_requestorProcessID;
- data->m_appCacheHostID = m_appCacheHostID;
- data->m_targetType = m_targetType;
- return data.release();
-}
-
-bool ResourceRequest::isEmpty() const
-{
- return m_url.isEmpty();
-}
-
-bool ResourceRequest::isNull() const
-{
- return m_url.isNull();
-}
-
-const KURL& ResourceRequest::url() const
-{
- return m_url;
-}
-
-void ResourceRequest::setURL(const KURL& url)
-{
- m_url = url;
-}
-
-void ResourceRequest::removeCredentials()
-{
- if (m_url.user().isEmpty() && m_url.pass().isEmpty())
- return;
-
- m_url.setUser(String());
- m_url.setPass(String());
-}
-
-ResourceRequestCachePolicy ResourceRequest::cachePolicy() const
-{
- return m_cachePolicy;
-}
-
-void ResourceRequest::setCachePolicy(ResourceRequestCachePolicy cachePolicy)
-{
- m_cachePolicy = cachePolicy;
-}
-
-double ResourceRequest::timeoutInterval() const
-{
- return m_timeoutInterval;
-}
-
-void ResourceRequest::setTimeoutInterval(double timeoutInterval)
-{
- m_timeoutInterval = timeoutInterval;
-}
-
-const KURL& ResourceRequest::firstPartyForCookies() const
-{
- return m_firstPartyForCookies;
-}
-
-void ResourceRequest::setFirstPartyForCookies(const KURL& firstPartyForCookies)
-{
- m_firstPartyForCookies = firstPartyForCookies;
-}
-
-const String& ResourceRequest::httpMethod() const
-{
- return m_httpMethod;
-}
-
-void ResourceRequest::setHTTPMethod(const String& httpMethod)
-{
- m_httpMethod = httpMethod;
-}
-
-const HTTPHeaderMap& ResourceRequest::httpHeaderFields() const
-{
- return m_httpHeaderFields;
-}
-
-String ResourceRequest::httpHeaderField(const AtomicString& name) const
-{
- return m_httpHeaderFields.get(name);
-}
-
-String ResourceRequest::httpHeaderField(const char* name) const
-{
- return m_httpHeaderFields.get(name);
-}
-
-void ResourceRequest::setHTTPHeaderField(const AtomicString& name, const String& value)
-{
- m_httpHeaderFields.set(name, value);
-}
-
-void ResourceRequest::setHTTPHeaderField(const char* name, const String& value)
-{
- setHTTPHeaderField(AtomicString(name), value);
-}
-
-void ResourceRequest::clearHTTPAuthorization()
-{
- m_httpHeaderFields.remove("Authorization");
-}
-
-void ResourceRequest::clearHTTPContentType()
-{
- m_httpHeaderFields.remove("Content-Type");
-}
-
-void ResourceRequest::clearHTTPReferrer()
-{
- m_httpHeaderFields.remove("Referer");
-}
-
-void ResourceRequest::clearHTTPOrigin()
-{
- m_httpHeaderFields.remove("Origin");
-}
-
-void ResourceRequest::clearHTTPUserAgent()
-{
- m_httpHeaderFields.remove("User-Agent");
-}
-
-void ResourceRequest::clearHTTPAccept()
-{
- m_httpHeaderFields.remove("Accept");
-}
-
-FormData* ResourceRequest::httpBody() const
-{
- return m_httpBody.get();
-}
-
-void ResourceRequest::setHTTPBody(PassRefPtr<FormData> httpBody)
-{
- m_httpBody = httpBody;
-}
-
-bool ResourceRequest::allowCookies() const
-{
- return m_allowCookies;
-}
-
-void ResourceRequest::setAllowCookies(bool allowCookies)
-{
- m_allowCookies = allowCookies;
-}
-
-ResourceLoadPriority ResourceRequest::priority() const
-{
- return m_priority;
-}
-
-void ResourceRequest::setPriority(ResourceLoadPriority priority)
-{
- m_priority = priority;
-}
-
-void ResourceRequest::addHTTPHeaderField(const AtomicString& name, const String& value)
-{
- HTTPHeaderMap::AddResult result = m_httpHeaderFields.add(name, value);
- if (!result.isNewEntry)
- result.iterator->value = result.iterator->value + ',' + value;
-}
-
-void ResourceRequest::addHTTPHeaderFields(const HTTPHeaderMap& headerFields)
-{
- HTTPHeaderMap::const_iterator end = headerFields.end();
- for (HTTPHeaderMap::const_iterator it = headerFields.begin(); it != end; ++it)
- addHTTPHeaderField(it->key, it->value);
-}
-
-bool equalIgnoringHeaderFields(const ResourceRequest& a, const ResourceRequest& b)
-{
- if (a.url() != b.url())
- return false;
-
- if (a.cachePolicy() != b.cachePolicy())
- return false;
-
- if (a.timeoutInterval() != b.timeoutInterval())
- return false;
-
- if (a.firstPartyForCookies() != b.firstPartyForCookies())
- return false;
-
- if (a.httpMethod() != b.httpMethod())
- return false;
-
- if (a.allowCookies() != b.allowCookies())
- return false;
-
- if (a.priority() != b.priority())
- return false;
-
- FormData* formDataA = a.httpBody();
- FormData* formDataB = b.httpBody();
-
- if (!formDataA)
- return !formDataB;
- if (!formDataB)
- return !formDataA;
-
- if (*formDataA != *formDataB)
- return false;
-
- return true;
-}
-
-bool ResourceRequest::compare(const ResourceRequest& a, const ResourceRequest& b)
-{
- if (!equalIgnoringHeaderFields(a, b))
- return false;
-
- if (a.httpHeaderFields() != b.httpHeaderFields())
- return false;
-
- return true;
-}
-
-bool ResourceRequest::isConditional() const
-{
- return (m_httpHeaderFields.contains("If-Match") ||
- m_httpHeaderFields.contains("If-Modified-Since") ||
- m_httpHeaderFields.contains("If-None-Match") ||
- m_httpHeaderFields.contains("If-Range") ||
- m_httpHeaderFields.contains("If-Unmodified-Since"));
-}
-
-double ResourceRequest::defaultTimeoutInterval()
-{
- return s_defaultTimeoutInterval;
-}
-
-void ResourceRequest::setDefaultTimeoutInterval(double timeoutInterval)
-{
- s_defaultTimeoutInterval = timeoutInterval;
-}
-
-void ResourceRequest::initialize(const KURL& url, ResourceRequestCachePolicy cachePolicy)
-{
- m_url = url;
- m_cachePolicy = cachePolicy;
- m_timeoutInterval = s_defaultTimeoutInterval;
- m_httpMethod = "GET";
- m_allowCookies = true;
- m_reportUploadProgress = false;
- m_reportLoadTiming = false;
- m_reportRawHeaders = false;
- m_hasUserGesture = false;
- m_downloadToFile = false;
- m_priority = ResourceLoadPriorityLow;
- m_requestorID = 0;
- m_requestorProcessID = 0;
- m_appCacheHostID = 0;
- m_targetType = TargetIsUnspecified;
-}
-
-// This is used by the loader to control the number of issued parallel load requests.
-unsigned initializeMaximumHTTPConnectionCountPerHost()
-{
- // The chromium network stack already handles limiting the number of
- // parallel requests per host, so there's no need to do it here. Therefore,
- // this is set to a high value that should never be hit in practice.
- return 10000;
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/network/ResourceRequest.h b/chromium/third_party/WebKit/Source/core/platform/network/ResourceRequest.h
deleted file mode 100644
index d54305a2619..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/network/ResourceRequest.h
+++ /dev/null
@@ -1,271 +0,0 @@
-/*
- * Copyright (C) 2003, 2006 Apple Computer, Inc. All rights reserved.
- * Copyright (C) 2006 Samuel Weinig <sam.weinig@gmail.com>
- * Copyright (C) 2009, 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ResourceRequest_h
-#define ResourceRequest_h
-
-#include "core/platform/network/FormData.h"
-#include "core/platform/network/HTTPHeaderMap.h"
-#include "core/platform/network/ResourceLoadPriority.h"
-#include "weborigin/KURL.h"
-#include "wtf/OwnPtr.h"
-
-namespace WebCore {
-
- enum ResourceRequestCachePolicy {
- UseProtocolCachePolicy, // normal load
- ReloadIgnoringCacheData, // reload
- ReturnCacheDataElseLoad, // back/forward or encoding change - allow stale data
- ReturnCacheDataDontLoad // results of a post - allow stale data and only use cache
- };
-
- struct CrossThreadResourceRequestData;
-
- // Do not use this type directly. Use ResourceRequest instead.
- class ResourceRequest {
- WTF_MAKE_FAST_ALLOCATED;
- public:
- // The type of this ResourceRequest, based on how the resource will be used.
- enum TargetType {
- TargetIsMainFrame,
- TargetIsSubframe,
- TargetIsSubresource, // Resource is a generic subresource. (Generally a specific type should be specified)
- TargetIsStyleSheet,
- TargetIsScript,
- TargetIsFont,
- TargetIsImage,
- TargetIsObject,
- TargetIsMedia,
- TargetIsWorker,
- TargetIsSharedWorker,
- TargetIsPrefetch,
- TargetIsFavicon,
- TargetIsXHR,
- TargetIsTextTrack,
- TargetIsUnspecified,
- };
-
- class ExtraData : public RefCounted<ExtraData> {
- public:
- virtual ~ExtraData() { }
- };
-
- ResourceRequest()
- {
- initialize(KURL(), UseProtocolCachePolicy);
- }
-
- ResourceRequest(const String& urlString)
- {
- initialize(KURL(ParsedURLString, urlString), UseProtocolCachePolicy);
- }
-
- ResourceRequest(const KURL& url)
- {
- initialize(url, UseProtocolCachePolicy);
- }
-
- ResourceRequest(const KURL& url, const String& referrer, ResourceRequestCachePolicy cachePolicy = UseProtocolCachePolicy)
- {
- initialize(url, cachePolicy);
- setHTTPReferrer(referrer);
- }
-
- static PassOwnPtr<ResourceRequest> adopt(PassOwnPtr<CrossThreadResourceRequestData>);
-
- // Gets a copy of the data suitable for passing to another thread.
- PassOwnPtr<CrossThreadResourceRequestData> copyData() const;
-
- bool isNull() const;
- bool isEmpty() const;
-
- const KURL& url() const;
- void setURL(const KURL& url);
-
- void removeCredentials();
-
- ResourceRequestCachePolicy cachePolicy() const;
- void setCachePolicy(ResourceRequestCachePolicy cachePolicy);
-
- double timeoutInterval() const; // May return 0 when using platform default.
- void setTimeoutInterval(double timeoutInterval);
-
- const KURL& firstPartyForCookies() const;
- void setFirstPartyForCookies(const KURL& firstPartyForCookies);
-
- const String& httpMethod() const;
- void setHTTPMethod(const String& httpMethod);
-
- const HTTPHeaderMap& httpHeaderFields() const;
- String httpHeaderField(const AtomicString& name) const;
- String httpHeaderField(const char* name) const;
- void setHTTPHeaderField(const AtomicString& name, const String& value);
- void setHTTPHeaderField(const char* name, const String& value);
- void addHTTPHeaderField(const AtomicString& name, const String& value);
- void addHTTPHeaderFields(const HTTPHeaderMap& headerFields);
-
- void clearHTTPAuthorization();
-
- String httpContentType() const { return httpHeaderField("Content-Type"); }
- void setHTTPContentType(const String& httpContentType) { setHTTPHeaderField("Content-Type", httpContentType); }
- void clearHTTPContentType();
-
- String httpReferrer() const { return httpHeaderField("Referer"); }
- void setHTTPReferrer(const String& httpReferrer) { setHTTPHeaderField("Referer", httpReferrer); }
- void clearHTTPReferrer();
-
- String httpOrigin() const { return httpHeaderField("Origin"); }
- void setHTTPOrigin(const String& httpOrigin) { setHTTPHeaderField("Origin", httpOrigin); }
- void clearHTTPOrigin();
-
- String httpUserAgent() const { return httpHeaderField("User-Agent"); }
- void setHTTPUserAgent(const String& httpUserAgent) { setHTTPHeaderField("User-Agent", httpUserAgent); }
- void clearHTTPUserAgent();
-
- String httpAccept() const { return httpHeaderField("Accept"); }
- void setHTTPAccept(const String& httpAccept) { setHTTPHeaderField("Accept", httpAccept); }
- void clearHTTPAccept();
-
- FormData* httpBody() const;
- void setHTTPBody(PassRefPtr<FormData> httpBody);
-
- bool allowCookies() const;
- void setAllowCookies(bool allowCookies);
-
- ResourceLoadPriority priority() const;
- void setPriority(ResourceLoadPriority);
-
- bool isConditional() const;
-
- // Whether the associated ResourceHandleClient needs to be notified of
- // upload progress made for that resource.
- bool reportUploadProgress() const { return m_reportUploadProgress; }
- void setReportUploadProgress(bool reportUploadProgress) { m_reportUploadProgress = reportUploadProgress; }
-
- // Whether the timing information should be collected for the request.
- bool reportLoadTiming() const { return m_reportLoadTiming; }
- void setReportLoadTiming(bool reportLoadTiming) { m_reportLoadTiming = reportLoadTiming; }
-
- // Whether actual headers being sent/received should be collected and reported for the request.
- bool reportRawHeaders() const { return m_reportRawHeaders; }
- void setReportRawHeaders(bool reportRawHeaders) { m_reportRawHeaders = reportRawHeaders; }
-
- // Allows the request to be matched up with its requestor.
- int requestorID() const { return m_requestorID; }
- void setRequestorID(int requestorID) { m_requestorID = requestorID; }
-
- // The process id of the process from which this request originated. In
- // the case of out-of-process plugins, this allows to link back the
- // request to the plugin process (as it is processed through a render
- // view process).
- int requestorProcessID() const { return m_requestorProcessID; }
- void setRequestorProcessID(int requestorProcessID) { m_requestorProcessID = requestorProcessID; }
-
- // Allows the request to be matched up with its app cache host.
- int appCacheHostID() const { return m_appCacheHostID; }
- void setAppCacheHostID(int id) { m_appCacheHostID = id; }
-
- // True if request was user initiated.
- bool hasUserGesture() const { return m_hasUserGesture; }
- void setHasUserGesture(bool hasUserGesture) { m_hasUserGesture = hasUserGesture; }
-
- // True if request should be downloaded to file.
- bool downloadToFile() const { return m_downloadToFile; }
- void setDownloadToFile(bool downloadToFile) { m_downloadToFile = downloadToFile; }
-
- // Extra data associated with this request.
- ExtraData* extraData() const { return m_extraData.get(); }
- void setExtraData(PassRefPtr<ExtraData> extraData) { m_extraData = extraData; }
-
- // What this request is for.
- TargetType targetType() const { return m_targetType; }
- void setTargetType(TargetType type) { m_targetType = type; }
-
- static double defaultTimeoutInterval(); // May return 0 when using platform default.
- static void setDefaultTimeoutInterval(double);
-
- static bool compare(const ResourceRequest&, const ResourceRequest&);
-
- private:
- void initialize(const KURL& url, ResourceRequestCachePolicy cachePolicy);
-
- KURL m_url;
- ResourceRequestCachePolicy m_cachePolicy;
- double m_timeoutInterval; // 0 is a magic value for platform default on platforms that have one.
- KURL m_firstPartyForCookies;
- AtomicString m_httpMethod;
- HTTPHeaderMap m_httpHeaderFields;
- RefPtr<FormData> m_httpBody;
- bool m_allowCookies : 1;
- bool m_reportUploadProgress : 1;
- bool m_reportLoadTiming : 1;
- bool m_reportRawHeaders : 1;
- bool m_hasUserGesture : 1;
- bool m_downloadToFile : 1;
- ResourceLoadPriority m_priority;
- int m_requestorID;
- int m_requestorProcessID;
- int m_appCacheHostID;
- RefPtr<ExtraData> m_extraData;
- TargetType m_targetType;
-
- static double s_defaultTimeoutInterval;
- };
-
- bool equalIgnoringHeaderFields(const ResourceRequest&, const ResourceRequest&);
-
- inline bool operator==(const ResourceRequest& a, const ResourceRequest& b) { return ResourceRequest::compare(a, b); }
- inline bool operator!=(ResourceRequest& a, const ResourceRequest& b) { return !(a == b); }
-
- struct CrossThreadResourceRequestData {
- WTF_MAKE_NONCOPYABLE(CrossThreadResourceRequestData); WTF_MAKE_FAST_ALLOCATED;
- public:
- CrossThreadResourceRequestData() { }
- KURL m_url;
-
- ResourceRequestCachePolicy m_cachePolicy;
- double m_timeoutInterval;
- KURL m_firstPartyForCookies;
-
- String m_httpMethod;
- OwnPtr<CrossThreadHTTPHeaderMapData> m_httpHeaders;
- RefPtr<FormData> m_httpBody;
- bool m_allowCookies;
- bool m_hasUserGesture;
- bool m_downloadToFile;
- ResourceLoadPriority m_priority;
- int m_requestorID;
- int m_requestorProcessID;
- int m_appCacheHostID;
- ResourceRequest::TargetType m_targetType;
- };
-
- unsigned initializeMaximumHTTPConnectionCountPerHost();
-
-} // namespace WebCore
-
-#endif // ResourceRequest_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/network/ResourceResponse.cpp b/chromium/third_party/WebKit/Source/core/platform/network/ResourceResponse.cpp
deleted file mode 100644
index 2b27a6427d4..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/network/ResourceResponse.cpp
+++ /dev/null
@@ -1,679 +0,0 @@
-/*
- * Copyright (C) 2006, 2008 Apple Inc. All rights reserved.
- * Copyright (C) 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/network/ResourceResponse.h"
-
-#include "core/platform/network/HTTPParsers.h"
-#include "core/platform/network/ResourceResponse.h"
-#include "wtf/CurrentTime.h"
-#include "wtf/MathExtras.h"
-#include "wtf/StdLibExtras.h"
-
-namespace WebCore {
-
-static void parseCacheHeader(const String& header, Vector<pair<String, String> >& result);
-
-ResourceResponse::ResourceResponse()
- : m_expectedContentLength(0)
- , m_httpStatusCode(0)
- , m_lastModifiedDate(0)
- , m_wasCached(false)
- , m_connectionID(0)
- , m_connectionReused(false)
- , m_isNull(true)
- , m_haveParsedCacheControlHeader(false)
- , m_haveParsedAgeHeader(false)
- , m_haveParsedDateHeader(false)
- , m_haveParsedExpiresHeader(false)
- , m_haveParsedLastModifiedHeader(false)
- , m_cacheControlContainsNoCache(false)
- , m_cacheControlContainsNoStore(false)
- , m_cacheControlContainsMustRevalidate(false)
- , m_cacheControlMaxAge(0.0)
- , m_age(0.0)
- , m_date(0.0)
- , m_expires(0.0)
- , m_lastModified(0.0)
- , m_httpVersion(Unknown)
- , m_appCacheID(0)
- , m_isMultipartPayload(false)
- , m_wasFetchedViaSPDY(false)
- , m_wasNpnNegotiated(false)
- , m_wasAlternateProtocolAvailable(false)
- , m_wasFetchedViaProxy(false)
- , m_responseTime(0)
- , m_remotePort(0)
-{
-}
-
-ResourceResponse::ResourceResponse(const KURL& url, const AtomicString& mimeType, long long expectedLength, const AtomicString& textEncodingName, const String& filename)
- : m_url(url)
- , m_mimeType(mimeType)
- , m_expectedContentLength(expectedLength)
- , m_textEncodingName(textEncodingName)
- , m_suggestedFilename(filename)
- , m_httpStatusCode(0)
- , m_lastModifiedDate(0)
- , m_wasCached(false)
- , m_connectionID(0)
- , m_connectionReused(false)
- , m_isNull(false)
- , m_haveParsedCacheControlHeader(false)
- , m_haveParsedAgeHeader(false)
- , m_haveParsedDateHeader(false)
- , m_haveParsedExpiresHeader(false)
- , m_haveParsedLastModifiedHeader(false)
- , m_cacheControlContainsNoCache(false)
- , m_cacheControlContainsNoStore(false)
- , m_cacheControlContainsMustRevalidate(false)
- , m_cacheControlMaxAge(0.0)
- , m_age(0.0)
- , m_date(0.0)
- , m_expires(0.0)
- , m_lastModified(0.0)
- , m_httpVersion(Unknown)
- , m_appCacheID(0)
- , m_isMultipartPayload(false)
- , m_wasFetchedViaSPDY(false)
- , m_wasNpnNegotiated(false)
- , m_wasAlternateProtocolAvailable(false)
- , m_wasFetchedViaProxy(false)
- , m_responseTime(0)
- , m_remotePort(0)
-{
-}
-
-PassOwnPtr<ResourceResponse> ResourceResponse::adopt(PassOwnPtr<CrossThreadResourceResponseData> data)
-{
- OwnPtr<ResourceResponse> response = adoptPtr(new ResourceResponse);
- response->setURL(data->m_url);
- response->setMimeType(data->m_mimeType);
- response->setExpectedContentLength(data->m_expectedContentLength);
- response->setTextEncodingName(data->m_textEncodingName);
- response->setSuggestedFilename(data->m_suggestedFilename);
-
- response->setHTTPStatusCode(data->m_httpStatusCode);
- response->setHTTPStatusText(data->m_httpStatusText);
-
- response->m_httpHeaderFields.adopt(data->m_httpHeaders.release());
- response->setLastModifiedDate(data->m_lastModifiedDate);
- response->setResourceLoadTiming(data->m_resourceLoadTiming.release());
- response->m_securityInfo = data->m_securityInfo;
- response->m_httpVersion = data->m_httpVersion;
- response->m_appCacheID = data->m_appCacheID;
- response->m_appCacheManifestURL = data->m_appCacheManifestURL.copy();
- response->m_isMultipartPayload = data->m_isMultipartPayload;
- response->m_wasFetchedViaSPDY = data->m_wasFetchedViaSPDY;
- response->m_wasNpnNegotiated = data->m_wasNpnNegotiated;
- response->m_wasAlternateProtocolAvailable = data->m_wasAlternateProtocolAvailable;
- response->m_wasFetchedViaProxy = data->m_wasFetchedViaProxy;
- response->m_responseTime = data->m_responseTime;
- response->m_remoteIPAddress = data->m_remoteIPAddress;
- response->m_remotePort = data->m_remotePort;
- response->m_downloadedFilePath = data->m_downloadedFilePath;
- response->m_downloadedFileHandle = data->m_downloadedFileHandle;
-
- // Bug https://bugs.webkit.org/show_bug.cgi?id=60397 this doesn't support
- // whatever values may be present in the opaque m_extraData structure.
-
- return response.release();
-}
-
-PassOwnPtr<CrossThreadResourceResponseData> ResourceResponse::copyData() const
-{
- OwnPtr<CrossThreadResourceResponseData> data = adoptPtr(new CrossThreadResourceResponseData);
- data->m_url = url().copy();
- data->m_mimeType = mimeType().string().isolatedCopy();
- data->m_expectedContentLength = expectedContentLength();
- data->m_textEncodingName = textEncodingName().string().isolatedCopy();
- data->m_suggestedFilename = suggestedFilename().isolatedCopy();
- data->m_httpStatusCode = httpStatusCode();
- data->m_httpStatusText = httpStatusText().string().isolatedCopy();
- data->m_httpHeaders = httpHeaderFields().copyData();
- data->m_lastModifiedDate = lastModifiedDate();
- if (m_resourceLoadTiming)
- data->m_resourceLoadTiming = m_resourceLoadTiming->deepCopy();
- data->m_securityInfo = CString(m_securityInfo.data(), m_securityInfo.length());
- data->m_httpVersion = m_httpVersion;
- data->m_appCacheID = m_appCacheID;
- data->m_appCacheManifestURL = m_appCacheManifestURL.copy();
- data->m_isMultipartPayload = m_isMultipartPayload;
- data->m_wasFetchedViaSPDY = m_wasFetchedViaSPDY;
- data->m_wasNpnNegotiated = m_wasNpnNegotiated;
- data->m_wasAlternateProtocolAvailable = m_wasAlternateProtocolAvailable;
- data->m_wasFetchedViaProxy = m_wasFetchedViaProxy;
- data->m_responseTime = m_responseTime;
- data->m_remoteIPAddress = m_remoteIPAddress.string().isolatedCopy();
- data->m_remotePort = m_remotePort;
- data->m_downloadedFilePath = m_downloadedFilePath.isolatedCopy();
- data->m_downloadedFileHandle = m_downloadedFileHandle;
-
- // Bug https://bugs.webkit.org/show_bug.cgi?id=60397 this doesn't support
- // whatever values may be present in the opaque m_extraData structure.
-
- return data.release();
-}
-
-bool ResourceResponse::isHTTP() const
-{
- return m_url.protocolIsInHTTPFamily();
-}
-
-const KURL& ResourceResponse::url() const
-{
- return m_url;
-}
-
-void ResourceResponse::setURL(const KURL& url)
-{
- m_isNull = false;
-
- m_url = url;
-}
-
-const AtomicString& ResourceResponse::mimeType() const
-{
- return m_mimeType;
-}
-
-void ResourceResponse::setMimeType(const AtomicString& mimeType)
-{
- m_isNull = false;
-
- // FIXME: MIME type is determined by HTTP Content-Type header. We should update the header, so that it doesn't disagree with m_mimeType.
- m_mimeType = mimeType;
-}
-
-long long ResourceResponse::expectedContentLength() const
-{
- return m_expectedContentLength;
-}
-
-void ResourceResponse::setExpectedContentLength(long long expectedContentLength)
-{
- m_isNull = false;
-
- // FIXME: Content length is determined by HTTP Content-Length header. We should update the header, so that it doesn't disagree with m_expectedContentLength.
- m_expectedContentLength = expectedContentLength;
-}
-
-const AtomicString& ResourceResponse::textEncodingName() const
-{
- return m_textEncodingName;
-}
-
-void ResourceResponse::setTextEncodingName(const AtomicString& encodingName)
-{
- m_isNull = false;
-
- // FIXME: Text encoding is determined by HTTP Content-Type header. We should update the header, so that it doesn't disagree with m_textEncodingName.
- m_textEncodingName = encodingName;
-}
-
-// FIXME should compute this on the fly
-const String& ResourceResponse::suggestedFilename() const
-{
- return m_suggestedFilename;
-}
-
-void ResourceResponse::setSuggestedFilename(const String& suggestedName)
-{
- m_isNull = false;
-
- // FIXME: Suggested file name is calculated based on other headers. There should not be a setter for it.
- m_suggestedFilename = suggestedName;
-}
-
-int ResourceResponse::httpStatusCode() const
-{
- return m_httpStatusCode;
-}
-
-void ResourceResponse::setHTTPStatusCode(int statusCode)
-{
- m_httpStatusCode = statusCode;
-}
-
-const AtomicString& ResourceResponse::httpStatusText() const
-{
- return m_httpStatusText;
-}
-
-void ResourceResponse::setHTTPStatusText(const AtomicString& statusText)
-{
- m_httpStatusText = statusText;
-}
-
-String ResourceResponse::httpHeaderField(const AtomicString& name) const
-{
- return m_httpHeaderFields.get(name);
-}
-
-String ResourceResponse::httpHeaderField(const char* name) const
-{
- return m_httpHeaderFields.get(name);
-}
-
-void ResourceResponse::updateHeaderParsedState(const AtomicString& name)
-{
- DEFINE_STATIC_LOCAL(const AtomicString, ageHeader, ("age", AtomicString::ConstructFromLiteral));
- DEFINE_STATIC_LOCAL(const AtomicString, cacheControlHeader, ("cache-control", AtomicString::ConstructFromLiteral));
- DEFINE_STATIC_LOCAL(const AtomicString, dateHeader, ("date", AtomicString::ConstructFromLiteral));
- DEFINE_STATIC_LOCAL(const AtomicString, expiresHeader, ("expires", AtomicString::ConstructFromLiteral));
- DEFINE_STATIC_LOCAL(const AtomicString, lastModifiedHeader, ("last-modified", AtomicString::ConstructFromLiteral));
- DEFINE_STATIC_LOCAL(const AtomicString, pragmaHeader, ("pragma", AtomicString::ConstructFromLiteral));
-
- if (equalIgnoringCase(name, ageHeader))
- m_haveParsedAgeHeader = false;
- else if (equalIgnoringCase(name, cacheControlHeader) || equalIgnoringCase(name, pragmaHeader))
- m_haveParsedCacheControlHeader = false;
- else if (equalIgnoringCase(name, dateHeader))
- m_haveParsedDateHeader = false;
- else if (equalIgnoringCase(name, expiresHeader))
- m_haveParsedExpiresHeader = false;
- else if (equalIgnoringCase(name, lastModifiedHeader))
- m_haveParsedLastModifiedHeader = false;
-}
-
-void ResourceResponse::setHTTPHeaderField(const AtomicString& name, const String& value)
-{
- updateHeaderParsedState(name);
-
- m_httpHeaderFields.set(name, value);
-}
-
-void ResourceResponse::addHTTPHeaderField(const AtomicString& name, const String& value)
-{
- updateHeaderParsedState(name);
-
- HTTPHeaderMap::AddResult result = m_httpHeaderFields.add(name, value);
- if (!result.isNewEntry)
- result.iterator->value = result.iterator->value + ", " + value;
-}
-
-const HTTPHeaderMap& ResourceResponse::httpHeaderFields() const
-{
- return m_httpHeaderFields;
-}
-
-void ResourceResponse::parseCacheControlDirectives() const
-{
- ASSERT(!m_haveParsedCacheControlHeader);
-
- m_haveParsedCacheControlHeader = true;
-
- m_cacheControlContainsMustRevalidate = false;
- m_cacheControlContainsNoCache = false;
- m_cacheControlMaxAge = std::numeric_limits<double>::quiet_NaN();
-
- DEFINE_STATIC_LOCAL(const AtomicString, cacheControlString, ("cache-control", AtomicString::ConstructFromLiteral));
- DEFINE_STATIC_LOCAL(const AtomicString, noCacheDirective, ("no-cache", AtomicString::ConstructFromLiteral));
- DEFINE_STATIC_LOCAL(const AtomicString, noStoreDirective, ("no-store", AtomicString::ConstructFromLiteral));
- DEFINE_STATIC_LOCAL(const AtomicString, mustRevalidateDirective, ("must-revalidate", AtomicString::ConstructFromLiteral));
- DEFINE_STATIC_LOCAL(const AtomicString, maxAgeDirective, ("max-age", AtomicString::ConstructFromLiteral));
-
- String cacheControlValue = m_httpHeaderFields.get(cacheControlString);
- if (!cacheControlValue.isEmpty()) {
- Vector<pair<String, String> > directives;
- parseCacheHeader(cacheControlValue, directives);
-
- size_t directivesSize = directives.size();
- for (size_t i = 0; i < directivesSize; ++i) {
- // RFC2616 14.9.1: A no-cache directive with a value is only meaningful for proxy caches.
- // It should be ignored by a browser level cache.
- if (equalIgnoringCase(directives[i].first, noCacheDirective) && directives[i].second.isEmpty())
- m_cacheControlContainsNoCache = true;
- else if (equalIgnoringCase(directives[i].first, noStoreDirective))
- m_cacheControlContainsNoStore = true;
- else if (equalIgnoringCase(directives[i].first, mustRevalidateDirective))
- m_cacheControlContainsMustRevalidate = true;
- else if (equalIgnoringCase(directives[i].first, maxAgeDirective)) {
- if (!std::isnan(m_cacheControlMaxAge)) {
- // First max-age directive wins if there are multiple ones.
- continue;
- }
- bool ok;
- double maxAge = directives[i].second.toDouble(&ok);
- if (ok)
- m_cacheControlMaxAge = maxAge;
- }
- }
- }
-
- if (!m_cacheControlContainsNoCache) {
- // Handle Pragma: no-cache
- // This is deprecated and equivalent to Cache-control: no-cache
- // Don't bother tokenizing the value, it is not important
- DEFINE_STATIC_LOCAL(const AtomicString, pragmaHeader, ("pragma", AtomicString::ConstructFromLiteral));
- String pragmaValue = m_httpHeaderFields.get(pragmaHeader);
-
- m_cacheControlContainsNoCache = pragmaValue.lower().contains(noCacheDirective);
- }
-}
-
-bool ResourceResponse::cacheControlContainsNoCache() const
-{
- if (!m_haveParsedCacheControlHeader)
- parseCacheControlDirectives();
- return m_cacheControlContainsNoCache;
-}
-
-bool ResourceResponse::cacheControlContainsNoStore() const
-{
- if (!m_haveParsedCacheControlHeader)
- parseCacheControlDirectives();
- return m_cacheControlContainsNoStore;
-}
-
-bool ResourceResponse::cacheControlContainsMustRevalidate() const
-{
- if (!m_haveParsedCacheControlHeader)
- parseCacheControlDirectives();
- return m_cacheControlContainsMustRevalidate;
-}
-
-bool ResourceResponse::hasCacheValidatorFields() const
-{
- DEFINE_STATIC_LOCAL(const AtomicString, lastModifiedHeader, ("last-modified", AtomicString::ConstructFromLiteral));
- DEFINE_STATIC_LOCAL(const AtomicString, eTagHeader, ("etag", AtomicString::ConstructFromLiteral));
- return !m_httpHeaderFields.get(lastModifiedHeader).isEmpty() || !m_httpHeaderFields.get(eTagHeader).isEmpty();
-}
-
-double ResourceResponse::cacheControlMaxAge() const
-{
- if (!m_haveParsedCacheControlHeader)
- parseCacheControlDirectives();
- return m_cacheControlMaxAge;
-}
-
-static double parseDateValueInHeader(const HTTPHeaderMap& headers, const AtomicString& headerName)
-{
- String headerValue = headers.get(headerName);
- if (headerValue.isEmpty())
- return std::numeric_limits<double>::quiet_NaN();
- // This handles all date formats required by RFC2616:
- // Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
- // Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
- // Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
- double dateInMilliseconds = parseDate(headerValue);
- if (!std::isfinite(dateInMilliseconds))
- return std::numeric_limits<double>::quiet_NaN();
- return dateInMilliseconds / 1000;
-}
-
-double ResourceResponse::date() const
-{
- if (!m_haveParsedDateHeader) {
- DEFINE_STATIC_LOCAL(const AtomicString, headerName, ("date", AtomicString::ConstructFromLiteral));
- m_date = parseDateValueInHeader(m_httpHeaderFields, headerName);
- m_haveParsedDateHeader = true;
- }
- return m_date;
-}
-
-double ResourceResponse::age() const
-{
- if (!m_haveParsedAgeHeader) {
- DEFINE_STATIC_LOCAL(const AtomicString, headerName, ("age", AtomicString::ConstructFromLiteral));
- String headerValue = m_httpHeaderFields.get(headerName);
- bool ok;
- m_age = headerValue.toDouble(&ok);
- if (!ok)
- m_age = std::numeric_limits<double>::quiet_NaN();
- m_haveParsedAgeHeader = true;
- }
- return m_age;
-}
-
-double ResourceResponse::expires() const
-{
- if (!m_haveParsedExpiresHeader) {
- DEFINE_STATIC_LOCAL(const AtomicString, headerName, ("expires", AtomicString::ConstructFromLiteral));
- m_expires = parseDateValueInHeader(m_httpHeaderFields, headerName);
- m_haveParsedExpiresHeader = true;
- }
- return m_expires;
-}
-
-double ResourceResponse::lastModified() const
-{
- if (!m_haveParsedLastModifiedHeader) {
- DEFINE_STATIC_LOCAL(const AtomicString, headerName, ("last-modified", AtomicString::ConstructFromLiteral));
- m_lastModified = parseDateValueInHeader(m_httpHeaderFields, headerName);
- m_haveParsedLastModifiedHeader = true;
- }
- return m_lastModified;
-}
-
-bool ResourceResponse::isAttachment() const
-{
- DEFINE_STATIC_LOCAL(const AtomicString, headerName, ("content-disposition", AtomicString::ConstructFromLiteral));
- String value = m_httpHeaderFields.get(headerName);
- size_t loc = value.find(';');
- if (loc != kNotFound)
- value = value.left(loc);
- value = value.stripWhiteSpace();
- DEFINE_STATIC_LOCAL(const AtomicString, attachmentString, ("attachment", AtomicString::ConstructFromLiteral));
- return equalIgnoringCase(value, attachmentString);
-}
-
-void ResourceResponse::setLastModifiedDate(time_t lastModifiedDate)
-{
- m_lastModifiedDate = lastModifiedDate;
-}
-
-time_t ResourceResponse::lastModifiedDate() const
-{
- return m_lastModifiedDate;
-}
-
-bool ResourceResponse::wasCached() const
-{
- return m_wasCached;
-}
-
-void ResourceResponse::setWasCached(bool value)
-{
- m_wasCached = value;
-}
-
-bool ResourceResponse::connectionReused() const
-{
- return m_connectionReused;
-}
-
-void ResourceResponse::setConnectionReused(bool connectionReused)
-{
- m_connectionReused = connectionReused;
-}
-
-unsigned ResourceResponse::connectionID() const
-{
- return m_connectionID;
-}
-
-void ResourceResponse::setConnectionID(unsigned connectionID)
-{
- m_connectionID = connectionID;
-}
-
-ResourceLoadTiming* ResourceResponse::resourceLoadTiming() const
-{
- return m_resourceLoadTiming.get();
-}
-
-void ResourceResponse::setResourceLoadTiming(PassRefPtr<ResourceLoadTiming> resourceLoadTiming)
-{
- m_resourceLoadTiming = resourceLoadTiming;
-}
-
-PassRefPtr<ResourceLoadInfo> ResourceResponse::resourceLoadInfo() const
-{
- return m_resourceLoadInfo.get();
-}
-
-void ResourceResponse::setResourceLoadInfo(PassRefPtr<ResourceLoadInfo> loadInfo)
-{
- m_resourceLoadInfo = loadInfo;
-}
-
-void ResourceResponse::setDownloadedFilePath(const String& downloadedFilePath)
-{
- m_downloadedFilePath = downloadedFilePath;
- if (m_downloadedFilePath.isEmpty()) {
- m_downloadedFileHandle.clear();
- return;
- }
- OwnPtr<BlobData> blobData = BlobData::create();
- blobData->appendFile(m_downloadedFilePath);
- blobData->detachFromCurrentThread();
- m_downloadedFileHandle = BlobDataHandle::create(blobData.release(), -1);
-}
-
-bool ResourceResponse::compare(const ResourceResponse& a, const ResourceResponse& b)
-{
- if (a.isNull() != b.isNull())
- return false;
- if (a.url() != b.url())
- return false;
- if (a.mimeType() != b.mimeType())
- return false;
- if (a.expectedContentLength() != b.expectedContentLength())
- return false;
- if (a.textEncodingName() != b.textEncodingName())
- return false;
- if (a.suggestedFilename() != b.suggestedFilename())
- return false;
- if (a.httpStatusCode() != b.httpStatusCode())
- return false;
- if (a.httpStatusText() != b.httpStatusText())
- return false;
- if (a.httpHeaderFields() != b.httpHeaderFields())
- return false;
- if (a.resourceLoadTiming() && b.resourceLoadTiming() && *a.resourceLoadTiming() == *b.resourceLoadTiming())
- return true;
- if (a.resourceLoadTiming() != b.resourceLoadTiming())
- return false;
- return true;
-}
-
-static bool isCacheHeaderSeparator(UChar c)
-{
- // See RFC 2616, Section 2.2
- switch (c) {
- case '(':
- case ')':
- case '<':
- case '>':
- case '@':
- case ',':
- case ';':
- case ':':
- case '\\':
- case '"':
- case '/':
- case '[':
- case ']':
- case '?':
- case '=':
- case '{':
- case '}':
- case ' ':
- case '\t':
- return true;
- default:
- return false;
- }
-}
-
-static bool isControlCharacter(UChar c)
-{
- return c < ' ' || c == 127;
-}
-
-static inline String trimToNextSeparator(const String& str)
-{
- return str.substring(0, str.find(isCacheHeaderSeparator));
-}
-
-static void parseCacheHeader(const String& header, Vector<pair<String, String> >& result)
-{
- const String safeHeader = header.removeCharacters(isControlCharacter);
- unsigned max = safeHeader.length();
- for (unsigned pos = 0; pos < max; /* pos incremented in loop */) {
- size_t nextCommaPosition = safeHeader.find(',', pos);
- size_t nextEqualSignPosition = safeHeader.find('=', pos);
- if (nextEqualSignPosition != kNotFound && (nextEqualSignPosition < nextCommaPosition || nextCommaPosition == kNotFound)) {
- // Get directive name, parse right hand side of equal sign, then add to map
- String directive = trimToNextSeparator(safeHeader.substring(pos, nextEqualSignPosition - pos).stripWhiteSpace());
- pos += nextEqualSignPosition - pos + 1;
-
- String value = safeHeader.substring(pos, max - pos).stripWhiteSpace();
- if (value[0] == '"') {
- // The value is a quoted string
- size_t nextDoubleQuotePosition = value.find('"', 1);
- if (nextDoubleQuotePosition != kNotFound) {
- // Store the value as a quoted string without quotes
- result.append(pair<String, String>(directive, value.substring(1, nextDoubleQuotePosition - 1).stripWhiteSpace()));
- pos += (safeHeader.find('"', pos) - pos) + nextDoubleQuotePosition + 1;
- // Move past next comma, if there is one
- size_t nextCommaPosition2 = safeHeader.find(',', pos);
- if (nextCommaPosition2 != kNotFound)
- pos += nextCommaPosition2 - pos + 1;
- else
- return; // Parse error if there is anything left with no comma
- } else {
- // Parse error; just use the rest as the value
- result.append(pair<String, String>(directive, trimToNextSeparator(value.substring(1, value.length() - 1).stripWhiteSpace())));
- return;
- }
- } else {
- // The value is a token until the next comma
- size_t nextCommaPosition2 = value.find(',');
- if (nextCommaPosition2 != kNotFound) {
- // The value is delimited by the next comma
- result.append(pair<String, String>(directive, trimToNextSeparator(value.substring(0, nextCommaPosition2).stripWhiteSpace())));
- pos += (safeHeader.find(',', pos) - pos) + 1;
- } else {
- // The rest is the value; no change to value needed
- result.append(pair<String, String>(directive, trimToNextSeparator(value)));
- return;
- }
- }
- } else if (nextCommaPosition != kNotFound && (nextCommaPosition < nextEqualSignPosition || nextEqualSignPosition == kNotFound)) {
- // Add directive to map with empty string as value
- result.append(pair<String, String>(trimToNextSeparator(safeHeader.substring(pos, nextCommaPosition - pos).stripWhiteSpace()), ""));
- pos += nextCommaPosition - pos + 1;
- } else {
- // Add last directive to map with empty string as value
- result.append(pair<String, String>(trimToNextSeparator(safeHeader.substring(pos, max - pos).stripWhiteSpace()), ""));
- return;
- }
- }
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/network/ResourceResponse.h b/chromium/third_party/WebKit/Source/core/platform/network/ResourceResponse.h
deleted file mode 100644
index 7ce23ae19fe..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/network/ResourceResponse.h
+++ /dev/null
@@ -1,312 +0,0 @@
-/*
- * Copyright (C) 2006, 2008 Apple Inc. All rights reserved.
- * Copyright (C) 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ResourceResponse_h
-#define ResourceResponse_h
-
-#include "core/platform/network/BlobData.h"
-#include "core/platform/network/HTTPHeaderMap.h"
-#include "core/platform/network/ResourceLoadInfo.h"
-#include "core/platform/network/ResourceLoadTiming.h"
-#include "weborigin/KURL.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/RefPtr.h"
-#include "wtf/text/CString.h"
-
-namespace WebCore {
-
-struct CrossThreadResourceResponseData;
-
-class ResourceResponse {
- WTF_MAKE_FAST_ALLOCATED;
-public:
- enum HTTPVersion { Unknown, HTTP_0_9, HTTP_1_0, HTTP_1_1 };
-
- class ExtraData : public RefCounted<ExtraData> {
- public:
- virtual ~ExtraData() { }
- };
-
- static PassOwnPtr<ResourceResponse> adopt(PassOwnPtr<CrossThreadResourceResponseData>);
-
- // Gets a copy of the data suitable for passing to another thread.
- PassOwnPtr<CrossThreadResourceResponseData> copyData() const;
-
- ResourceResponse();
- ResourceResponse(const KURL&, const AtomicString& mimeType, long long expectedLength, const AtomicString& textEncodingName, const String& filename);
-
- bool isNull() const { return m_isNull; }
- bool isHTTP() const;
-
- const KURL& url() const;
- void setURL(const KURL&);
-
- const AtomicString& mimeType() const;
- void setMimeType(const AtomicString&);
-
- long long expectedContentLength() const;
- void setExpectedContentLength(long long);
-
- const AtomicString& textEncodingName() const;
- void setTextEncodingName(const AtomicString&);
-
- // FIXME: Should compute this on the fly.
- // There should not be a setter exposed, as suggested file name is determined based on other headers in a manner that WebCore does not necessarily know about.
- const String& suggestedFilename() const;
- void setSuggestedFilename(const String&);
-
- int httpStatusCode() const;
- void setHTTPStatusCode(int);
-
- const AtomicString& httpStatusText() const;
- void setHTTPStatusText(const AtomicString&);
-
- String httpHeaderField(const AtomicString& name) const;
- String httpHeaderField(const char* name) const;
- void setHTTPHeaderField(const AtomicString& name, const String& value);
- void addHTTPHeaderField(const AtomicString& name, const String& value);
- const HTTPHeaderMap& httpHeaderFields() const;
-
- bool isMultipart() const { return mimeType() == "multipart/x-mixed-replace"; }
-
- bool isAttachment() const;
-
- // FIXME: These are used by PluginStream on some platforms. Calculations may differ from just returning plain Last-Modified header.
- // Leaving it for now but this should go away in favor of generic solution.
- void setLastModifiedDate(time_t);
- time_t lastModifiedDate() const;
-
- // These functions return parsed values of the corresponding response headers.
- // NaN means that the header was not present or had invalid value.
- bool cacheControlContainsNoCache() const;
- bool cacheControlContainsNoStore() const;
- bool cacheControlContainsMustRevalidate() const;
- bool hasCacheValidatorFields() const;
- double cacheControlMaxAge() const;
- double date() const;
- double age() const;
- double expires() const;
- double lastModified() const;
-
- unsigned connectionID() const;
- void setConnectionID(unsigned);
-
- bool connectionReused() const;
- void setConnectionReused(bool);
-
- bool wasCached() const;
- void setWasCached(bool);
-
- ResourceLoadTiming* resourceLoadTiming() const;
- void setResourceLoadTiming(PassRefPtr<ResourceLoadTiming>);
-
- PassRefPtr<ResourceLoadInfo> resourceLoadInfo() const;
- void setResourceLoadInfo(PassRefPtr<ResourceLoadInfo>);
-
- HTTPVersion httpVersion() const { return m_httpVersion; }
- void setHTTPVersion(HTTPVersion version) { m_httpVersion = version; }
-
- const CString& getSecurityInfo() const { return m_securityInfo; }
- void setSecurityInfo(const CString& securityInfo) { m_securityInfo = securityInfo; }
-
- long long appCacheID() const { return m_appCacheID; }
- void setAppCacheID(long long id) { m_appCacheID = id; }
-
- const KURL& appCacheManifestURL() const { return m_appCacheManifestURL; }
- void setAppCacheManifestURL(const KURL& url) { m_appCacheManifestURL = url; }
-
- bool wasFetchedViaSPDY() const { return m_wasFetchedViaSPDY; }
- void setWasFetchedViaSPDY(bool value) { m_wasFetchedViaSPDY = value; }
-
- bool wasNpnNegotiated() const { return m_wasNpnNegotiated; }
- void setWasNpnNegotiated(bool value) { m_wasNpnNegotiated = value; }
-
- bool wasAlternateProtocolAvailable() const
- {
- return m_wasAlternateProtocolAvailable;
- }
- void setWasAlternateProtocolAvailable(bool value)
- {
- m_wasAlternateProtocolAvailable = value;
- }
-
- bool wasFetchedViaProxy() const { return m_wasFetchedViaProxy; }
- void setWasFetchedViaProxy(bool value) { m_wasFetchedViaProxy = value; }
-
- bool isMultipartPayload() const { return m_isMultipartPayload; }
- void setIsMultipartPayload(bool value) { m_isMultipartPayload = value; }
-
- double responseTime() const { return m_responseTime; }
- void setResponseTime(double responseTime) { m_responseTime = responseTime; }
-
- const AtomicString& remoteIPAddress() const { return m_remoteIPAddress; }
- void setRemoteIPAddress(const AtomicString& value) { m_remoteIPAddress = value; }
-
- unsigned short remotePort() const { return m_remotePort; }
- void setRemotePort(unsigned short value) { m_remotePort = value; }
-
- const String& downloadedFilePath() const { return m_downloadedFilePath; }
- void setDownloadedFilePath(const String&);
-
- // Extra data associated with this response.
- ExtraData* extraData() const { return m_extraData.get(); }
- void setExtraData(PassRefPtr<ExtraData> extraData) { m_extraData = extraData; }
-
- // The ResourceResponse subclass may "shadow" this method to provide platform-specific memory usage information
- unsigned memoryUsage() const
- {
- // average size, mostly due to URL and Header Map strings
- return 1280;
- }
-
- static bool compare(const ResourceResponse&, const ResourceResponse&);
-
-private:
- void parseCacheControlDirectives() const;
- void updateHeaderParsedState(const AtomicString& name);
-
- KURL m_url;
- AtomicString m_mimeType;
- long long m_expectedContentLength;
- AtomicString m_textEncodingName;
- String m_suggestedFilename;
- int m_httpStatusCode;
- AtomicString m_httpStatusText;
- HTTPHeaderMap m_httpHeaderFields;
- time_t m_lastModifiedDate;
- bool m_wasCached : 1;
- unsigned m_connectionID;
- bool m_connectionReused : 1;
- RefPtr<ResourceLoadTiming> m_resourceLoadTiming;
- RefPtr<ResourceLoadInfo> m_resourceLoadInfo;
-
- bool m_isNull : 1;
-
- mutable bool m_haveParsedCacheControlHeader : 1;
- mutable bool m_haveParsedAgeHeader : 1;
- mutable bool m_haveParsedDateHeader : 1;
- mutable bool m_haveParsedExpiresHeader : 1;
- mutable bool m_haveParsedLastModifiedHeader : 1;
-
- mutable bool m_cacheControlContainsNoCache : 1;
- mutable bool m_cacheControlContainsNoStore : 1;
- mutable bool m_cacheControlContainsMustRevalidate : 1;
- mutable double m_cacheControlMaxAge;
-
- mutable double m_age;
- mutable double m_date;
- mutable double m_expires;
- mutable double m_lastModified;
-
- // An opaque value that contains some information regarding the security of
- // the connection for this request, such as SSL connection info (empty
- // string if not over HTTPS).
- CString m_securityInfo;
-
- // HTTP version used in the response, if known.
- HTTPVersion m_httpVersion;
-
- // The id of the appcache this response was retrieved from, or zero if
- // the response was not retrieved from an appcache.
- long long m_appCacheID;
-
- // The manifest url of the appcache this response was retrieved from, if any.
- // Note: only valid for main resource responses.
- KURL m_appCacheManifestURL;
-
- // Set to true if this is part of a multipart response.
- bool m_isMultipartPayload;
-
- // Was the resource fetched over SPDY. See http://dev.chromium.org/spdy
- bool m_wasFetchedViaSPDY;
-
- // Was the resource fetched over a channel which used TLS/Next-Protocol-Negotiation (also SPDY related).
- bool m_wasNpnNegotiated;
-
- // Was the resource fetched over a channel which specified "Alternate-Protocol"
- // (e.g.: Alternate-Protocol: 443:npn-spdy/1).
- bool m_wasAlternateProtocolAvailable;
-
- // Was the resource fetched over an explicit proxy (HTTP, SOCKS, etc).
- bool m_wasFetchedViaProxy;
-
- // The time at which the response headers were received. For cached
- // responses, this time could be "far" in the past.
- double m_responseTime;
-
- // Remote IP address of the socket which fetched this resource.
- AtomicString m_remoteIPAddress;
-
- // Remote port number of the socket which fetched this resource.
- unsigned short m_remotePort;
-
- // The downloaded file path if the load streamed to a file.
- String m_downloadedFilePath;
-
- // The handle to the downloaded file to ensure the underlying file will not
- // be deleted.
- RefPtr<BlobDataHandle> m_downloadedFileHandle;
-
- // ExtraData associated with the response.
- RefPtr<ExtraData> m_extraData;
-};
-
-inline bool operator==(const ResourceResponse& a, const ResourceResponse& b) { return ResourceResponse::compare(a, b); }
-inline bool operator!=(const ResourceResponse& a, const ResourceResponse& b) { return !(a == b); }
-
-struct CrossThreadResourceResponseData {
- WTF_MAKE_NONCOPYABLE(CrossThreadResourceResponseData); WTF_MAKE_FAST_ALLOCATED;
-public:
- CrossThreadResourceResponseData() { }
- KURL m_url;
- String m_mimeType;
- long long m_expectedContentLength;
- String m_textEncodingName;
- String m_suggestedFilename;
- int m_httpStatusCode;
- String m_httpStatusText;
- OwnPtr<CrossThreadHTTPHeaderMapData> m_httpHeaders;
- time_t m_lastModifiedDate;
- RefPtr<ResourceLoadTiming> m_resourceLoadTiming;
- CString m_securityInfo;
- ResourceResponse::HTTPVersion m_httpVersion;
- long long m_appCacheID;
- KURL m_appCacheManifestURL;
- bool m_isMultipartPayload;
- bool m_wasFetchedViaSPDY;
- bool m_wasNpnNegotiated;
- bool m_wasAlternateProtocolAvailable;
- bool m_wasFetchedViaProxy;
- double m_responseTime;
- String m_remoteIPAddress;
- unsigned short m_remotePort;
- String m_downloadedFilePath;
- RefPtr<BlobDataHandle> m_downloadedFileHandle;
-};
-
-} // namespace WebCore
-
-#endif // ResourceResponse_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/network/SocketStreamError.cpp b/chromium/third_party/WebKit/Source/core/platform/network/SocketStreamError.cpp
deleted file mode 100644
index 7f746c843fb..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/network/SocketStreamError.cpp
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright (C) 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/network/SocketStreamError.h"
-
-namespace WebCore {
-
-bool SocketStreamError::compare(const SocketStreamError& a, const SocketStreamError& b)
-{
- if (a.isNull() && b.isNull())
- return true;
-
- if (a.isNull() || b.isNull())
- return false;
-
- if (a.errorCode() != b.errorCode())
- return false;
-
- if (a.failingURL() != b.failingURL())
- return false;
-
- if (a.localizedDescription() != b.localizedDescription())
- return false;
-
- return true;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/network/SocketStreamError.h b/chromium/third_party/WebKit/Source/core/platform/network/SocketStreamError.h
deleted file mode 100644
index d4554c6c1fe..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/network/SocketStreamError.h
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * Copyright (C) 2009 Apple Inc. All rights reserved.
- * Copyright (C) 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SocketStreamError_h
-#define SocketStreamError_h
-
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class SocketStreamError : public RefCounted<SocketStreamError> {
-public:
- static PassRefPtr<SocketStreamError> create(int errorCode, const String& errorMessage)
- {
- return adoptRef(new SocketStreamError(errorCode, errorMessage));
- }
-
- bool isNull() const { return m_isNull; }
-
- int errorCode() const { return m_errorCode; }
- const String& failingURL() const { return m_failingURL; }
- const String& localizedDescription() const { return m_localizedDescription; }
-
- static bool compare(const SocketStreamError&, const SocketStreamError&);
-
-private:
- explicit SocketStreamError(int errorCode, const String& errorMessage)
- : m_errorCode(errorCode)
- , m_localizedDescription(errorMessage)
- , m_isNull(false)
- {
- }
-
- int m_errorCode;
- String m_failingURL; // FIXME: Can this be deleted since it is always empty?
- String m_localizedDescription;
- bool m_isNull;
-};
-
-inline bool operator==(const SocketStreamError& a, const SocketStreamError& b) { return SocketStreamError::compare(a, b); }
-inline bool operator!=(const SocketStreamError& a, const SocketStreamError& b) { return !(a == b); }
-
-} // namespace WebCore
-
-#endif // SocketStreamError_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/network/SocketStreamHandle.cpp b/chromium/third_party/WebKit/Source/core/platform/network/SocketStreamHandle.cpp
deleted file mode 100644
index 47b3eaebf79..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/network/SocketStreamHandle.cpp
+++ /dev/null
@@ -1,281 +0,0 @@
-/*
- * Copyright (C) 2009, 2011, 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/network/SocketStreamHandle.h"
-
-#include "core/platform/Logging.h"
-#include "core/platform/NotImplemented.h"
-#include "core/platform/network/SocketStreamError.h"
-#include "core/platform/network/SocketStreamHandleClient.h"
-#include "core/platform/network/SocketStreamHandleInternal.h"
-#include "public/platform/Platform.h"
-#include "public/platform/WebData.h"
-#include "public/platform/WebSocketStreamError.h"
-#include "public/platform/WebSocketStreamHandle.h"
-#include "wtf/PassOwnPtr.h"
-
-namespace WebCore {
-
-static const unsigned int bufferSize = 100 * 1024 * 1024;
-
-SocketStreamHandleInternal::SocketStreamHandleInternal(SocketStreamHandle* handle)
- : m_handle(handle)
- , m_maxPendingSendAllowed(0)
- , m_pendingAmountSent(0)
-{
-}
-
-SocketStreamHandleInternal::~SocketStreamHandleInternal()
-{
- m_handle = 0;
-}
-
-void SocketStreamHandleInternal::connect(const KURL& url)
-{
- m_socket = adoptPtr(WebKit::Platform::current()->createSocketStreamHandle());
- LOG(Network, "SocketStreamHandleInternal %p connect()", this);
- ASSERT(m_socket);
- ASSERT(m_handle);
- if (m_handle->m_client)
- m_handle->m_client->willOpenSocketStream(m_handle);
- m_socket->connect(url, this);
-}
-
-int SocketStreamHandleInternal::send(const char* data, int len)
-{
- LOG(Network, "SocketStreamHandleInternal %p send() len=%d", this, len);
- // FIXME: |m_socket| should not be null here, but it seems that there is the
- // case. We should figure out such a path and fix it rather than checking
- // null here.
- if (!m_socket) {
- LOG(Network, "SocketStreamHandleInternal %p send() m_socket is NULL", this);
- return 0;
- }
- if (m_pendingAmountSent + len > m_maxPendingSendAllowed)
- len = m_maxPendingSendAllowed - m_pendingAmountSent;
-
- if (len <= 0)
- return len;
- WebKit::WebData webdata(data, len);
- if (m_socket->send(webdata)) {
- m_pendingAmountSent += len;
- LOG(Network, "SocketStreamHandleInternal %p send() Sent %d bytes", this, len);
- return len;
- }
- LOG(Network, "SocketStreamHandleInternal %p send() m_socket->send() failed", this);
- return 0;
-}
-
-void SocketStreamHandleInternal::close()
-{
- LOG(Network, "SocketStreamHandleInternal %p close()", this);
- if (m_socket)
- m_socket->close();
-}
-
-void SocketStreamHandleInternal::didOpenStream(WebKit::WebSocketStreamHandle* socketHandle, int maxPendingSendAllowed)
-{
- LOG(Network, "SocketStreamHandleInternal %p didOpenStream() maxPendingSendAllowed=%d", this, maxPendingSendAllowed);
- ASSERT(maxPendingSendAllowed > 0);
- if (m_handle && m_socket) {
- ASSERT(socketHandle == m_socket.get());
- m_maxPendingSendAllowed = maxPendingSendAllowed;
- m_handle->m_state = SocketStreamHandle::Open;
- if (m_handle->m_client) {
- m_handle->m_client->didOpenSocketStream(m_handle);
- return;
- }
- }
- LOG(Network, "SocketStreamHandleInternal %p didOpenStream() m_handle or m_socket is NULL", this);
-}
-
-void SocketStreamHandleInternal::didSendData(WebKit::WebSocketStreamHandle* socketHandle, int amountSent)
-{
- LOG(Network, "SocketStreamHandleInternal %p didSendData() amountSent=%d", this, amountSent);
- ASSERT(amountSent > 0);
- if (m_handle && m_socket) {
- ASSERT(socketHandle == m_socket.get());
- m_pendingAmountSent -= amountSent;
- ASSERT(m_pendingAmountSent >= 0);
- m_handle->sendPendingData();
- }
-}
-
-void SocketStreamHandleInternal::didReceiveData(WebKit::WebSocketStreamHandle* socketHandle, const WebKit::WebData& data)
-{
- LOG(Network, "SocketStreamHandleInternal %p didReceiveData() Received %lu bytes", this, static_cast<unsigned long>(data.size()));
- if (m_handle && m_socket) {
- ASSERT(socketHandle == m_socket.get());
- if (m_handle->m_client)
- m_handle->m_client->didReceiveSocketStreamData(m_handle, data.data(), data.size());
- }
-}
-
-void SocketStreamHandleInternal::didClose(WebKit::WebSocketStreamHandle* socketHandle)
-{
- LOG(Network, "SocketStreamHandleInternal %p didClose()", this);
- if (m_handle && m_socket) {
- ASSERT(socketHandle == m_socket.get());
- m_socket.clear();
- SocketStreamHandle* h = m_handle;
- m_handle = 0;
- if (h->m_client)
- h->m_client->didCloseSocketStream(h);
- }
-}
-
-void SocketStreamHandleInternal::didFail(WebKit::WebSocketStreamHandle* socketHandle, const WebKit::WebSocketStreamError& err)
-{
- LOG(Network, "SocketStreamHandleInternal %p didFail()", this);
- if (m_handle && m_socket) {
- ASSERT(socketHandle == m_socket.get());
- if (m_handle->m_client)
- m_handle->m_client->didFailSocketStream(m_handle, *(PassRefPtr<SocketStreamError>(err)));
- }
-}
-
-// SocketStreamHandle ----------------------------------------------------------
-
-SocketStreamHandle::SocketStreamHandle(const KURL& url, SocketStreamHandleClient* client)
- : m_url(url)
- , m_client(client)
- , m_state(Connecting)
-{
- m_internal = SocketStreamHandleInternal::create(this);
- m_internal->connect(m_url);
-}
-
-SocketStreamHandle::~SocketStreamHandle()
-{
- setClient(0);
- m_internal.clear();
-}
-
-SocketStreamHandle::SocketStreamState SocketStreamHandle::state() const
-{
- return m_state;
-}
-
-bool SocketStreamHandle::send(const char* data, int length)
-{
- if (m_state == Connecting || m_state == Closing)
- return false;
- if (!m_buffer.isEmpty()) {
- if (m_buffer.size() + length > bufferSize) {
- // FIXME: report error to indicate that buffer has no more space.
- return false;
- }
- m_buffer.append(data, length);
- if (m_client)
- m_client->didUpdateBufferedAmount(static_cast<SocketStreamHandle*>(this), bufferedAmount());
- return true;
- }
- int bytesWritten = 0;
- if (m_state == Open)
- bytesWritten = sendInternal(data, length);
- if (bytesWritten < 0)
- return false;
- if (m_buffer.size() + length - bytesWritten > bufferSize) {
- // FIXME: report error to indicate that buffer has no more space.
- return false;
- }
- if (bytesWritten < length) {
- m_buffer.append(data + bytesWritten, length - bytesWritten);
- if (m_client)
- m_client->didUpdateBufferedAmount(static_cast<SocketStreamHandle*>(this), bufferedAmount());
- }
- return true;
-}
-
-void SocketStreamHandle::close()
-{
- if (m_state == Closed)
- return;
- m_state = Closing;
- if (!m_buffer.isEmpty())
- return;
- disconnect();
-}
-
-void SocketStreamHandle::disconnect()
-{
- RefPtr<SocketStreamHandle> protect(static_cast<SocketStreamHandle*>(this)); // closeInternal calls the client, which may make the handle get deallocated immediately.
-
- closeInternal();
- m_state = Closed;
-}
-
-void SocketStreamHandle::setClient(SocketStreamHandleClient* client)
-{
- ASSERT(!client || (!m_client && m_state == Connecting));
- m_client = client;
-}
-
-bool SocketStreamHandle::sendPendingData()
-{
- if (m_state != Open && m_state != Closing)
- return false;
- if (m_buffer.isEmpty()) {
- if (m_state == Open)
- return false;
- if (m_state == Closing) {
- disconnect();
- return false;
- }
- }
- bool pending;
- do {
- int bytesWritten = sendInternal(m_buffer.firstBlockData(), m_buffer.firstBlockSize());
- pending = bytesWritten != static_cast<int>(m_buffer.firstBlockSize());
- if (bytesWritten <= 0)
- return false;
- ASSERT(m_buffer.size() - bytesWritten <= bufferSize);
- m_buffer.consume(bytesWritten);
- } while (!pending && !m_buffer.isEmpty());
- if (m_client)
- m_client->didUpdateBufferedAmount(static_cast<SocketStreamHandle*>(this), bufferedAmount());
- return true;
-}
-
-int SocketStreamHandle::sendInternal(const char* buf, int len)
-{
- if (!m_internal)
- return 0;
- return m_internal->send(buf, len);
-}
-
-void SocketStreamHandle::closeInternal()
-{
- if (m_internal)
- m_internal->close();
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/network/SocketStreamHandle.h b/chromium/third_party/WebKit/Source/core/platform/network/SocketStreamHandle.h
deleted file mode 100644
index 091027b5d15..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/network/SocketStreamHandle.h
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * Copyright (C) 2009 Apple Inc. All rights reserved.
- * Copyright (C) 2009, 2011, 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SocketStreamHandle_h
-#define SocketStreamHandle_h
-
-#include "weborigin/KURL.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/StreamBuffer.h"
-
-namespace WebCore {
-
-class SocketStreamHandleClient;
-class SocketStreamHandleInternal;
-
-class SocketStreamHandle : public RefCounted<SocketStreamHandle> {
-public:
- enum SocketStreamState { Connecting, Open, Closing, Closed };
-
- static PassRefPtr<SocketStreamHandle> create(const KURL& url, SocketStreamHandleClient* client) { return adoptRef(new SocketStreamHandle(url, client)); }
-
- virtual ~SocketStreamHandle();
- SocketStreamState state() const;
-
- bool send(const char* data, int length);
- void close(); // Disconnect after all data in buffer are sent.
- void disconnect();
- size_t bufferedAmount() const { return m_buffer.size(); }
-
- SocketStreamHandleClient* client() const { return m_client; }
- void setClient(SocketStreamHandleClient*);
-
-private:
- SocketStreamHandle(const KURL&, SocketStreamHandleClient*);
-
- bool sendPendingData();
-
- int sendInternal(const char* data, int length);
- void closeInternal();
-
- KURL m_url;
- SocketStreamHandleClient* m_client;
- StreamBuffer<char, 1024 * 1024> m_buffer;
- SocketStreamState m_state;
-
- friend class SocketStreamHandleInternal;
- OwnPtr<SocketStreamHandleInternal> m_internal;
-};
-
-} // namespace WebCore
-
-#endif // SocketStreamHandle_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/network/SocketStreamHandleClient.h b/chromium/third_party/WebKit/Source/core/platform/network/SocketStreamHandleClient.h
deleted file mode 100644
index 6958fb576fa..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/network/SocketStreamHandleClient.h
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright (C) 2009 Apple Inc. All rights reserved.
- * Copyright (C) 2009, 2011, 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SocketStreamHandleClient_h
-#define SocketStreamHandleClient_h
-
-namespace WebCore {
-
- class KURL;
- class SocketStreamError;
- class SocketStreamHandle;
-
- class SocketStreamHandleClient {
- public:
- virtual ~SocketStreamHandleClient() { }
-
- virtual void willOpenSocketStream(SocketStreamHandle*) { }
- virtual void didOpenSocketStream(SocketStreamHandle*) { }
- virtual void didCloseSocketStream(SocketStreamHandle*) { }
- virtual void didReceiveSocketStreamData(SocketStreamHandle*, const char* /*data*/, int /*length*/) { }
- virtual void didUpdateBufferedAmount(SocketStreamHandle*, size_t /*bufferedAmount*/) { }
-
- virtual void didFailSocketStream(SocketStreamHandle*, const SocketStreamError&) { }
- };
-
-} // namespace WebCore
-
-#endif // SocketStreamHandleClient_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/network/SocketStreamHandleInternal.h b/chromium/third_party/WebKit/Source/core/platform/network/SocketStreamHandleInternal.h
deleted file mode 100644
index 55f5de02672..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/network/SocketStreamHandleInternal.h
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SocketStreamHandleInternal_h
-#define SocketStreamHandleInternal_h
-
-#include "core/platform/network/SocketStreamHandle.h"
-#include "public/platform/WebSocketStreamHandleClient.h"
-#include "public/platform/WebURL.h"
-#include "wtf/PassOwnPtr.h"
-
-namespace WebKit {
-
-class WebData;
-class WebSocketStreamError;
-class WebSocketStreamHandle;
-
-}
-
-namespace WebCore {
-
-class SocketStreamHandleInternal : public WebKit::WebSocketStreamHandleClient {
-public:
- static PassOwnPtr<SocketStreamHandleInternal> create(SocketStreamHandle* handle)
- {
- return adoptPtr(new SocketStreamHandleInternal(handle));
- }
- virtual ~SocketStreamHandleInternal();
-
- void connect(const KURL&);
- int send(const char*, int);
- void close();
-
- virtual void didOpenStream(WebKit::WebSocketStreamHandle*, int);
- virtual void didSendData(WebKit::WebSocketStreamHandle*, int);
- virtual void didReceiveData(WebKit::WebSocketStreamHandle*, const WebKit::WebData&);
- virtual void didClose(WebKit::WebSocketStreamHandle*);
- virtual void didFail(WebKit::WebSocketStreamHandle*, const WebKit::WebSocketStreamError&);
-
- static WebKit::WebSocketStreamHandle* toWebSocketStreamHandle(SocketStreamHandle* handle)
- {
- if (handle && handle->m_internal)
- return handle->m_internal->m_socket.get();
- return 0;
- }
-
-private:
- explicit SocketStreamHandleInternal(SocketStreamHandle*);
-
- SocketStreamHandle* m_handle;
- OwnPtr<WebKit::WebSocketStreamHandle> m_socket;
- int m_maxPendingSendAllowed;
- int m_pendingAmountSent;
-};
-
-} // namespace WebCore
-
-#endif // SocketStreamHandleInternal_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/sql/SQLValue.cpp b/chromium/third_party/WebKit/Source/core/platform/sql/SQLValue.cpp
deleted file mode 100644
index bba0b4e1638..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/sql/SQLValue.cpp
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright (C) 2007 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following condition
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/sql/SQLValue.h"
-
-namespace WebCore {
-
-SQLValue::SQLValue(const SQLValue& val)
- : m_type(val.m_type)
- , m_number(val.m_number)
- , m_string(val.m_string.isolatedCopy())
-{
-}
-
-String SQLValue::string() const
-{
- ASSERT(m_type == StringValue);
-
- // Must return a copy since ref-shared Strings are not thread safe
- return m_string.isolatedCopy();
-}
-
-double SQLValue::number() const
-{
- ASSERT(m_type == NumberValue);
-
- return m_number;
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/sql/SQLValue.h b/chromium/third_party/WebKit/Source/core/platform/sql/SQLValue.h
deleted file mode 100644
index e0069d07ddc..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/sql/SQLValue.h
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * Copyright (C) 2007 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following condition
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SQLValue_h
-#define SQLValue_h
-
-#include "wtf/Threading.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
- class SQLValue {
- public:
- enum Type { NullValue, NumberValue, StringValue };
-
- SQLValue() : m_type(NullValue), m_number(0.0) { }
- SQLValue(double number) : m_type(NumberValue), m_number(number) { }
- SQLValue(const String& s) : m_type(StringValue), m_number(0.0), m_string(s) { }
- SQLValue(const SQLValue&);
-
- Type type() const { return m_type; }
-
- String string() const;
- double number() const;
-
- private:
- Type m_type;
- double m_number;
- String m_string;
- };
-};
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/sql/SQLiteAuthorizer.cpp b/chromium/third_party/WebKit/Source/core/platform/sql/SQLiteAuthorizer.cpp
deleted file mode 100644
index 37db87ffb26..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/sql/SQLiteAuthorizer.cpp
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright (C) 2007 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following condition
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- * its contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "modules/webdatabase/DatabaseAuthorizer.h"
-
-#include <sqlite3.h>
-
-namespace WebCore {
-
-const int SQLAuthAllow = SQLITE_OK;
-const int SQLAuthIgnore = SQLITE_IGNORE;
-const int SQLAuthDeny = SQLITE_DENY;
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/sql/SQLiteDatabase.cpp b/chromium/third_party/WebKit/Source/core/platform/sql/SQLiteDatabase.cpp
deleted file mode 100644
index 8aa66890a6d..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/sql/SQLiteDatabase.cpp
+++ /dev/null
@@ -1,499 +0,0 @@
-/*
- * Copyright (C) 2006, 2007, 2008 Apple Inc. All rights reserved.
- * Copyright (C) 2007 Justin Haygood (jhaygood@reaktix.com)
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/sql/SQLiteDatabase.h"
-
-#include <sqlite3.h>
-#include "core/platform/Logging.h"
-#include "core/platform/sql/SQLiteFileSystem.h"
-#include "core/platform/sql/SQLiteStatement.h"
-#include "modules/webdatabase/DatabaseAuthorizer.h"
-#include "wtf/text/CString.h"
-#include "wtf/text/WTFString.h"
-#include "wtf/Threading.h"
-
-namespace WebCore {
-
-const int SQLResultDone = SQLITE_DONE;
-const int SQLResultError = SQLITE_ERROR;
-const int SQLResultOk = SQLITE_OK;
-const int SQLResultRow = SQLITE_ROW;
-const int SQLResultSchema = SQLITE_SCHEMA;
-const int SQLResultFull = SQLITE_FULL;
-const int SQLResultInterrupt = SQLITE_INTERRUPT;
-const int SQLResultConstraint = SQLITE_CONSTRAINT;
-
-static const char notOpenErrorMessage[] = "database is not open";
-
-SQLiteDatabase::SQLiteDatabase()
- : m_db(0)
- , m_pageSize(-1)
- , m_transactionInProgress(false)
- , m_sharable(false)
- , m_openingThread(0)
- , m_interrupted(false)
- , m_openError(SQLITE_ERROR)
- , m_openErrorMessage()
- , m_lastChangesCount(0)
-{
-}
-
-SQLiteDatabase::~SQLiteDatabase()
-{
- close();
-}
-
-bool SQLiteDatabase::open(const String& filename, bool forWebSQLDatabase)
-{
- close();
-
- m_openError = SQLiteFileSystem::openDatabase(filename, &m_db, forWebSQLDatabase);
- if (m_openError != SQLITE_OK) {
- m_openErrorMessage = m_db ? sqlite3_errmsg(m_db) : "sqlite_open returned null";
- LOG_ERROR("SQLite database failed to load from %s\nCause - %s", filename.ascii().data(),
- m_openErrorMessage.data());
- sqlite3_close(m_db);
- m_db = 0;
- return false;
- }
-
- m_openError = sqlite3_extended_result_codes(m_db, 1);
- if (m_openError != SQLITE_OK) {
- m_openErrorMessage = sqlite3_errmsg(m_db);
- LOG_ERROR("SQLite database error when enabling extended errors - %s", m_openErrorMessage.data());
- sqlite3_close(m_db);
- m_db = 0;
- return false;
- }
-
- if (isOpen())
- m_openingThread = currentThread();
- else
- m_openErrorMessage = "sqlite_open returned null";
-
- if (!SQLiteStatement(*this, "PRAGMA temp_store = MEMORY;").executeCommand())
- LOG_ERROR("SQLite database could not set temp_store to memory");
-
- return isOpen();
-}
-
-void SQLiteDatabase::close()
-{
- if (m_db) {
- // FIXME: This is being called on the main thread during JS GC. <rdar://problem/5739818>
- // ASSERT(currentThread() == m_openingThread);
- sqlite3* db = m_db;
- {
- MutexLocker locker(m_databaseClosingMutex);
- m_db = 0;
- }
- sqlite3_close(db);
- }
-
- m_openingThread = 0;
- m_openError = SQLITE_ERROR;
- m_openErrorMessage = CString();
-}
-
-void SQLiteDatabase::interrupt()
-{
- m_interrupted = true;
- while (!m_lockingMutex.tryLock()) {
- MutexLocker locker(m_databaseClosingMutex);
- if (!m_db)
- return;
- sqlite3_interrupt(m_db);
- yield();
- }
-
- m_lockingMutex.unlock();
-}
-
-bool SQLiteDatabase::isInterrupted()
-{
- ASSERT(!m_lockingMutex.tryLock());
- return m_interrupted;
-}
-
-void SQLiteDatabase::setFullsync(bool fsync)
-{
- if (fsync)
- executeCommand("PRAGMA fullfsync = 1;");
- else
- executeCommand("PRAGMA fullfsync = 0;");
-}
-
-int64_t SQLiteDatabase::maximumSize()
-{
- int64_t maxPageCount = 0;
-
- {
- MutexLocker locker(m_authorizerLock);
- enableAuthorizer(false);
- SQLiteStatement statement(*this, "PRAGMA max_page_count");
- maxPageCount = statement.getColumnInt64(0);
- enableAuthorizer(true);
- }
-
- return maxPageCount * pageSize();
-}
-
-void SQLiteDatabase::setMaximumSize(int64_t size)
-{
- if (size < 0)
- size = 0;
-
- int currentPageSize = pageSize();
-
- ASSERT(currentPageSize || !m_db);
- int64_t newMaxPageCount = currentPageSize ? size / currentPageSize : 0;
-
- MutexLocker locker(m_authorizerLock);
- enableAuthorizer(false);
-
- SQLiteStatement statement(*this, "PRAGMA max_page_count = " + String::number(newMaxPageCount));
- statement.prepare();
- if (statement.step() != SQLResultRow)
-#if OS(WIN)
- LOG_ERROR("Failed to set maximum size of database to %I64i bytes", static_cast<long long>(size));
-#else
- LOG_ERROR("Failed to set maximum size of database to %lli bytes", static_cast<long long>(size));
-#endif
-
- enableAuthorizer(true);
-
-}
-
-int SQLiteDatabase::pageSize()
-{
- // Since the page size of a database is locked in at creation and therefore cannot be dynamic,
- // we can cache the value for future use
- if (m_pageSize == -1) {
- MutexLocker locker(m_authorizerLock);
- enableAuthorizer(false);
-
- SQLiteStatement statement(*this, "PRAGMA page_size");
- m_pageSize = statement.getColumnInt(0);
-
- enableAuthorizer(true);
- }
-
- return m_pageSize;
-}
-
-int64_t SQLiteDatabase::freeSpaceSize()
-{
- int64_t freelistCount = 0;
-
- {
- MutexLocker locker(m_authorizerLock);
- enableAuthorizer(false);
- // Note: freelist_count was added in SQLite 3.4.1.
- SQLiteStatement statement(*this, "PRAGMA freelist_count");
- freelistCount = statement.getColumnInt64(0);
- enableAuthorizer(true);
- }
-
- return freelistCount * pageSize();
-}
-
-int64_t SQLiteDatabase::totalSize()
-{
- int64_t pageCount = 0;
-
- {
- MutexLocker locker(m_authorizerLock);
- enableAuthorizer(false);
- SQLiteStatement statement(*this, "PRAGMA page_count");
- pageCount = statement.getColumnInt64(0);
- enableAuthorizer(true);
- }
-
- return pageCount * pageSize();
-}
-
-void SQLiteDatabase::setSynchronous(SynchronousPragma sync)
-{
- executeCommand("PRAGMA synchronous = " + String::number(sync));
-}
-
-void SQLiteDatabase::setBusyTimeout(int ms)
-{
- if (m_db)
- sqlite3_busy_timeout(m_db, ms);
- else
- LOG(SQLDatabase, "BusyTimeout set on non-open database");
-}
-
-void SQLiteDatabase::setBusyHandler(int(*handler)(void*, int))
-{
- if (m_db)
- sqlite3_busy_handler(m_db, handler, NULL);
- else
- LOG(SQLDatabase, "Busy handler set on non-open database");
-}
-
-bool SQLiteDatabase::executeCommand(const String& sql)
-{
- return SQLiteStatement(*this, sql).executeCommand();
-}
-
-bool SQLiteDatabase::returnsAtLeastOneResult(const String& sql)
-{
- return SQLiteStatement(*this, sql).returnsAtLeastOneResult();
-}
-
-bool SQLiteDatabase::tableExists(const String& tablename)
-{
- if (!isOpen())
- return false;
-
- String statement = "SELECT name FROM sqlite_master WHERE type = 'table' AND name = '" + tablename + "';";
-
- SQLiteStatement sql(*this, statement);
- sql.prepare();
- return sql.step() == SQLITE_ROW;
-}
-
-void SQLiteDatabase::clearAllTables()
-{
- String query = "SELECT name FROM sqlite_master WHERE type='table';";
- Vector<String> tables;
- if (!SQLiteStatement(*this, query).returnTextResults(0, tables)) {
- LOG(SQLDatabase, "Unable to retrieve list of tables from database");
- return;
- }
-
- for (Vector<String>::iterator table = tables.begin(); table != tables.end(); ++table ) {
- if (*table == "sqlite_sequence")
- continue;
- if (!executeCommand("DROP TABLE " + *table))
- LOG(SQLDatabase, "Unable to drop table %s", (*table).ascii().data());
- }
-}
-
-int SQLiteDatabase::runVacuumCommand()
-{
- if (!executeCommand("VACUUM;"))
- LOG(SQLDatabase, "Unable to vacuum database - %s", lastErrorMsg());
- return lastError();
-}
-
-int SQLiteDatabase::runIncrementalVacuumCommand()
-{
- MutexLocker locker(m_authorizerLock);
- enableAuthorizer(false);
-
- if (!executeCommand("PRAGMA incremental_vacuum"))
- LOG(SQLDatabase, "Unable to run incremental vacuum - %s", lastErrorMsg());
-
- enableAuthorizer(true);
- return lastError();
-}
-
-int64_t SQLiteDatabase::lastInsertRowID()
-{
- if (!m_db)
- return 0;
- return sqlite3_last_insert_rowid(m_db);
-}
-
-void SQLiteDatabase::updateLastChangesCount()
-{
- if (!m_db)
- return;
-
- m_lastChangesCount = sqlite3_total_changes(m_db);
-}
-
-int SQLiteDatabase::lastChanges()
-{
- if (!m_db)
- return 0;
-
- return sqlite3_total_changes(m_db) - m_lastChangesCount;
-}
-
-int SQLiteDatabase::lastError()
-{
- return m_db ? sqlite3_errcode(m_db) : m_openError;
-}
-
-const char* SQLiteDatabase::lastErrorMsg()
-{
- if (m_db)
- return sqlite3_errmsg(m_db);
- return m_openErrorMessage.isNull() ? notOpenErrorMessage : m_openErrorMessage.data();
-}
-
-#ifndef NDEBUG
-void SQLiteDatabase::disableThreadingChecks()
-{
- // This doesn't guarantee that SQList was compiled with -DTHREADSAFE, or that you haven't turned off the mutexes.
-#if SQLITE_VERSION_NUMBER >= 3003001
- m_sharable = true;
-#else
- ASSERT(0); // Your SQLite doesn't support sharing handles across threads.
-#endif
-}
-#endif
-
-int SQLiteDatabase::authorizerFunction(void* userData, int actionCode, const char* parameter1, const char* parameter2, const char* /*databaseName*/, const char* /*trigger_or_view*/)
-{
- DatabaseAuthorizer* auth = static_cast<DatabaseAuthorizer*>(userData);
- ASSERT(auth);
-
- switch (actionCode) {
- case SQLITE_CREATE_INDEX:
- return auth->createIndex(parameter1, parameter2);
- case SQLITE_CREATE_TABLE:
- return auth->createTable(parameter1);
- case SQLITE_CREATE_TEMP_INDEX:
- return auth->createTempIndex(parameter1, parameter2);
- case SQLITE_CREATE_TEMP_TABLE:
- return auth->createTempTable(parameter1);
- case SQLITE_CREATE_TEMP_TRIGGER:
- return auth->createTempTrigger(parameter1, parameter2);
- case SQLITE_CREATE_TEMP_VIEW:
- return auth->createTempView(parameter1);
- case SQLITE_CREATE_TRIGGER:
- return auth->createTrigger(parameter1, parameter2);
- case SQLITE_CREATE_VIEW:
- return auth->createView(parameter1);
- case SQLITE_DELETE:
- return auth->allowDelete(parameter1);
- case SQLITE_DROP_INDEX:
- return auth->dropIndex(parameter1, parameter2);
- case SQLITE_DROP_TABLE:
- return auth->dropTable(parameter1);
- case SQLITE_DROP_TEMP_INDEX:
- return auth->dropTempIndex(parameter1, parameter2);
- case SQLITE_DROP_TEMP_TABLE:
- return auth->dropTempTable(parameter1);
- case SQLITE_DROP_TEMP_TRIGGER:
- return auth->dropTempTrigger(parameter1, parameter2);
- case SQLITE_DROP_TEMP_VIEW:
- return auth->dropTempView(parameter1);
- case SQLITE_DROP_TRIGGER:
- return auth->dropTrigger(parameter1, parameter2);
- case SQLITE_DROP_VIEW:
- return auth->dropView(parameter1);
- case SQLITE_INSERT:
- return auth->allowInsert(parameter1);
- case SQLITE_PRAGMA:
- return auth->allowPragma(parameter1, parameter2);
- case SQLITE_READ:
- return auth->allowRead(parameter1, parameter2);
- case SQLITE_SELECT:
- return auth->allowSelect();
- case SQLITE_TRANSACTION:
- return auth->allowTransaction();
- case SQLITE_UPDATE:
- return auth->allowUpdate(parameter1, parameter2);
- case SQLITE_ATTACH:
- return auth->allowAttach(parameter1);
- case SQLITE_DETACH:
- return auth->allowDetach(parameter1);
- case SQLITE_ALTER_TABLE:
- return auth->allowAlterTable(parameter1, parameter2);
- case SQLITE_REINDEX:
- return auth->allowReindex(parameter1);
-#if SQLITE_VERSION_NUMBER >= 3003013
- case SQLITE_ANALYZE:
- return auth->allowAnalyze(parameter1);
- case SQLITE_CREATE_VTABLE:
- return auth->createVTable(parameter1, parameter2);
- case SQLITE_DROP_VTABLE:
- return auth->dropVTable(parameter1, parameter2);
- case SQLITE_FUNCTION:
- return auth->allowFunction(parameter2);
-#endif
- default:
- ASSERT_NOT_REACHED();
- return SQLAuthDeny;
- }
-}
-
-void SQLiteDatabase::setAuthorizer(PassRefPtr<DatabaseAuthorizer> auth)
-{
- if (!m_db) {
- LOG_ERROR("Attempt to set an authorizer on a non-open SQL database");
- ASSERT_NOT_REACHED();
- return;
- }
-
- MutexLocker locker(m_authorizerLock);
-
- m_authorizer = auth;
-
- enableAuthorizer(true);
-}
-
-void SQLiteDatabase::enableAuthorizer(bool enable)
-{
- if (m_authorizer && enable)
- sqlite3_set_authorizer(m_db, SQLiteDatabase::authorizerFunction, m_authorizer.get());
- else
- sqlite3_set_authorizer(m_db, NULL, 0);
-}
-
-bool SQLiteDatabase::isAutoCommitOn() const
-{
- return sqlite3_get_autocommit(m_db);
-}
-
-bool SQLiteDatabase::turnOnIncrementalAutoVacuum()
-{
- SQLiteStatement statement(*this, "PRAGMA auto_vacuum");
- int autoVacuumMode = statement.getColumnInt(0);
- int error = lastError();
-
- // Check if we got an error while trying to get the value of the auto_vacuum flag.
- // If we got a SQLITE_BUSY error, then there's probably another transaction in
- // progress on this database. In this case, keep the current value of the
- // auto_vacuum flag and try to set it to INCREMENTAL the next time we open this
- // database. If the error is not SQLITE_BUSY, then we probably ran into a more
- // serious problem and should return false (to log an error message).
- if (error != SQLITE_ROW)
- return false;
-
- switch (autoVacuumMode) {
- case AutoVacuumIncremental:
- return true;
- case AutoVacuumFull:
- return executeCommand("PRAGMA auto_vacuum = 2");
- case AutoVacuumNone:
- default:
- if (!executeCommand("PRAGMA auto_vacuum = 2"))
- return false;
- runVacuumCommand();
- error = lastError();
- return (error == SQLITE_OK);
- }
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/sql/SQLiteDatabase.h b/chromium/third_party/WebKit/Source/core/platform/sql/SQLiteDatabase.h
deleted file mode 100644
index e2d52ee0b93..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/sql/SQLiteDatabase.h
+++ /dev/null
@@ -1,170 +0,0 @@
-/*
- * Copyright (C) 2006, 2007, 2008 Apple Inc. All rights reserved.
- * Copyright (C) 2007 Justin Haygood (jhaygood@reaktix.com)
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SQLiteDatabase_h
-#define SQLiteDatabase_h
-
-#include "wtf/Threading.h"
-#include "wtf/ThreadingPrimitives.h"
-#include "wtf/text/CString.h"
-#include "wtf/text/WTFString.h"
-
-#if COMPILER(MSVC)
-#pragma warning(disable: 4800)
-#endif
-
-struct sqlite3;
-
-namespace WebCore {
-
-class DatabaseAuthorizer;
-class SQLiteStatement;
-class SQLiteTransaction;
-
-extern const int SQLResultDone;
-extern const int SQLResultError;
-extern const int SQLResultOk;
-extern const int SQLResultRow;
-extern const int SQLResultSchema;
-extern const int SQLResultFull;
-extern const int SQLResultInterrupt;
-extern const int SQLResultConstraint;
-
-class SQLiteDatabase {
- WTF_MAKE_NONCOPYABLE(SQLiteDatabase);
- friend class SQLiteTransaction;
-public:
- SQLiteDatabase();
- ~SQLiteDatabase();
-
- bool open(const String& filename, bool forWebSQLDatabase = false);
- bool isOpen() const { return m_db; }
- void close();
- void interrupt();
- bool isInterrupted();
-
- void updateLastChangesCount();
-
- bool executeCommand(const String&);
- bool returnsAtLeastOneResult(const String&);
-
- bool tableExists(const String&);
- void clearAllTables();
- int runVacuumCommand();
- int runIncrementalVacuumCommand();
-
- bool transactionInProgress() const { return m_transactionInProgress; }
-
- int64_t lastInsertRowID();
- int lastChanges();
-
- void setBusyTimeout(int ms);
- void setBusyHandler(int(*)(void*, int));
-
- void setFullsync(bool);
-
- // Gets/sets the maximum size in bytes
- // Depending on per-database attributes, the size will only be settable in units that are the page size of the database, which is established at creation
- // These chunks will never be anything other than 512, 1024, 2048, 4096, 8192, 16384, or 32768 bytes in size.
- // setMaximumSize() will round the size down to the next smallest chunk if the passed size doesn't align.
- int64_t maximumSize();
- void setMaximumSize(int64_t);
-
- // Gets the number of unused bytes in the database file.
- int64_t freeSpaceSize();
- int64_t totalSize();
-
- // The SQLite SYNCHRONOUS pragma can be either FULL, NORMAL, or OFF
- // FULL - Any writing calls to the DB block until the data is actually on the disk surface
- // NORMAL - SQLite pauses at some critical moments when writing, but much less than FULL
- // OFF - Calls return immediately after the data has been passed to disk
- enum SynchronousPragma { SyncOff = 0, SyncNormal = 1, SyncFull = 2 };
- void setSynchronous(SynchronousPragma);
-
- int lastError();
- const char* lastErrorMsg();
-
- sqlite3* sqlite3Handle() const {
- ASSERT(m_sharable || currentThread() == m_openingThread || !m_db);
- return m_db;
- }
-
- void setAuthorizer(PassRefPtr<DatabaseAuthorizer>);
-
- Mutex& databaseMutex() { return m_lockingMutex; }
- bool isAutoCommitOn() const;
-
- // The SQLite AUTO_VACUUM pragma can be either NONE, FULL, or INCREMENTAL.
- // NONE - SQLite does not do any vacuuming
- // FULL - SQLite moves all empty pages to the end of the DB file and truncates
- // the file to remove those pages after every transaction. This option
- // requires SQLite to store additional information about each page in
- // the database file.
- // INCREMENTAL - SQLite stores extra information for each page in the database
- // file, but removes the empty pages only when PRAGMA INCREMANTAL_VACUUM
- // is called.
- enum AutoVacuumPragma { AutoVacuumNone = 0, AutoVacuumFull = 1, AutoVacuumIncremental = 2 };
- bool turnOnIncrementalAutoVacuum();
-
- // Set this flag to allow access from multiple threads. Not all multi-threaded accesses are safe!
- // See http://www.sqlite.org/cvstrac/wiki?p=MultiThreading for more info.
-#ifndef NDEBUG
- void disableThreadingChecks();
-#else
- void disableThreadingChecks() {}
-#endif
-
-private:
- static int authorizerFunction(void*, int, const char*, const char*, const char*, const char*);
-
- void enableAuthorizer(bool enable);
-
- int pageSize();
-
- sqlite3* m_db;
- int m_pageSize;
-
- bool m_transactionInProgress;
- bool m_sharable;
-
- Mutex m_authorizerLock;
- RefPtr<DatabaseAuthorizer> m_authorizer;
-
- Mutex m_lockingMutex;
- ThreadIdentifier m_openingThread;
-
- Mutex m_databaseClosingMutex;
- bool m_interrupted;
-
- int m_openError;
- CString m_openErrorMessage;
-
- int m_lastChangesCount;
-};
-
-} // namespace WebCore
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/sql/SQLiteFileSystem.h b/chromium/third_party/WebKit/Source/core/platform/sql/SQLiteFileSystem.h
deleted file mode 100644
index f3b1b596bd8..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/sql/SQLiteFileSystem.h
+++ /dev/null
@@ -1,117 +0,0 @@
-/*
- * Copyright (C) 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SQLiteFileSystem_h
-#define SQLiteFileSystem_h
-
-#include "wtf/Threading.h"
-#include "wtf/text/WTFString.h"
-
-struct sqlite3;
-
-namespace WebCore {
-
-class SQLiteDatabase;
-
-// A class that abstracts the file system related operations required
-// by the WebKit database code.
-class SQLiteFileSystem {
-public:
- // Registers a user-defined SQLite VFS.
- static void registerSQLiteVFS();
-
- // Opens a database file.
- //
- // filemame - The name of the database file.
- // database - The SQLite structure that represents the database stored
- // in the given file.
- // forWebSQLDatabase - True, if and only if we're opening a Web SQL Database file.
- // Used by Chromium to determine if the DB file needs to be opened
- // using a custom VFS.
- static int openDatabase(const String& filename, sqlite3** database, bool forWebSQLDatabase);
-
- // Returns the file name for a database.
- //
- // dbDir - The directory where all databases are stored.
- // dbName - The name of the database.
- // originIdentifier - The origin that wants to use this database.
- // db - A database with a number generator used to create unique file names.
- static String getFileNameForNewDatabase(const String& dbDir, const String& dbName,
- const String& originIdentifier, SQLiteDatabase* db);
-
- // Creates an absolute file path given a directory and a file name.
- //
- // path - The directory.
- // fileName - The file name.
- static String appendDatabaseFileNameToPath(const String& path, const String& fileName);
-
- // Makes sure the given directory exists, by creating all missing directories
- // on the given path.
- //
- // path - The directory.
- static bool ensureDatabaseDirectoryExists(const String& path);
-
- // If 'checkPathOnly' is false, then this method only checks if the given file exists.
- // If 'checkPathOnly' is true, then this method makes sure all directories on the
- // given path exist by creating the missing ones, and does not check if the file
- // itself exists.
- //
- // Sometimes we expect a DB file to exist; other times, we're OK with creating a new
- // DB file, but we want to make sure that the directory in which we want to put the
- // new DB file exists. This method covers both cases.
- //
- // fileName - The file name.
- // checkPathOnly - If true, we only make sure that the given directory exists.
- // If false, we only check if the file exists.
- static bool ensureDatabaseFileExists(const String& fileName, bool checkPathOnly);
-
- // Deletes an empty database directory.
- //
- // path - The directory.
- static bool deleteEmptyDatabaseDirectory(const String& path);
-
- // Deletes a database file.
- //
- // fileName - The file name.
- static bool deleteDatabaseFile(const String& fileName);
-
- // Returns the size of the database file.
- //
- // fileName - The file name.
- static long long getDatabaseFileSize(const String& fileName);
-
-private:
- // do not instantiate this class
- SQLiteFileSystem();
-}; // class SQLiteFileSystem
-
-} // namespace WebCore
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/sql/SQLiteStatement.cpp b/chromium/third_party/WebKit/Source/core/platform/sql/SQLiteStatement.cpp
deleted file mode 100644
index 137d8a46195..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/sql/SQLiteStatement.cpp
+++ /dev/null
@@ -1,534 +0,0 @@
-/*
- * Copyright (C) 2006, 2007, 2008 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/sql/SQLiteStatement.h"
-
-#include <sqlite3.h>
-#include "core/platform/Logging.h"
-#include "core/platform/sql/SQLValue.h"
-#include "wtf/Assertions.h"
-#include "wtf/text/CString.h"
-
-// SQLite 3.6.16 makes sqlite3_prepare_v2 automatically retry preparing the statement
-// once if the database scheme has changed. We rely on this behavior.
-#if SQLITE_VERSION_NUMBER < 3006016
-#error SQLite version 3.6.16 or newer is required
-#endif
-
-namespace WebCore {
-
-SQLiteStatement::SQLiteStatement(SQLiteDatabase& db, const String& sql)
- : m_database(db)
- , m_query(sql)
- , m_statement(0)
-#ifndef NDEBUG
- , m_isPrepared(false)
-#endif
-{
-}
-
-SQLiteStatement::~SQLiteStatement()
-{
- finalize();
-}
-
-int SQLiteStatement::prepare()
-{
- ASSERT(!m_isPrepared);
-
- MutexLocker databaseLock(m_database.databaseMutex());
- if (m_database.isInterrupted())
- return SQLITE_INTERRUPT;
-
- CString query = m_query.stripWhiteSpace().utf8();
-
- LOG(SQLDatabase, "SQL - prepare - %s", query.data());
-
- // Pass the length of the string including the null character to sqlite3_prepare_v2;
- // this lets SQLite avoid an extra string copy.
- size_t lengthIncludingNullCharacter = query.length() + 1;
-
- const char* tail;
- int error = sqlite3_prepare_v2(m_database.sqlite3Handle(), query.data(), lengthIncludingNullCharacter, &m_statement, &tail);
-
- if (error != SQLITE_OK)
- LOG(SQLDatabase, "sqlite3_prepare16 failed (%i)\n%s\n%s", error, query.data(), sqlite3_errmsg(m_database.sqlite3Handle()));
-
- if (tail && *tail)
- error = SQLITE_ERROR;
-
-#ifndef NDEBUG
- m_isPrepared = error == SQLITE_OK;
-#endif
- return error;
-}
-
-int SQLiteStatement::step()
-{
- MutexLocker databaseLock(m_database.databaseMutex());
- if (m_database.isInterrupted())
- return SQLITE_INTERRUPT;
- //ASSERT(m_isPrepared);
-
- if (!m_statement)
- return SQLITE_OK;
-
- // The database needs to update its last changes count before each statement
- // in order to compute properly the lastChanges() return value.
- m_database.updateLastChangesCount();
-
- LOG(SQLDatabase, "SQL - step - %s", m_query.ascii().data());
- int error = sqlite3_step(m_statement);
- if (error != SQLITE_DONE && error != SQLITE_ROW) {
- LOG(SQLDatabase, "sqlite3_step failed (%i)\nQuery - %s\nError - %s",
- error, m_query.ascii().data(), sqlite3_errmsg(m_database.sqlite3Handle()));
- }
-
- return error;
-}
-
-int SQLiteStatement::finalize()
-{
-#ifndef NDEBUG
- m_isPrepared = false;
-#endif
- if (!m_statement)
- return SQLITE_OK;
- LOG(SQLDatabase, "SQL - finalize - %s", m_query.ascii().data());
- int result = sqlite3_finalize(m_statement);
- m_statement = 0;
- return result;
-}
-
-int SQLiteStatement::reset()
-{
- ASSERT(m_isPrepared);
- if (!m_statement)
- return SQLITE_OK;
- LOG(SQLDatabase, "SQL - reset - %s", m_query.ascii().data());
- return sqlite3_reset(m_statement);
-}
-
-bool SQLiteStatement::executeCommand()
-{
- if (!m_statement && prepare() != SQLITE_OK)
- return false;
- ASSERT(m_isPrepared);
- if (step() != SQLITE_DONE) {
- finalize();
- return false;
- }
- finalize();
- return true;
-}
-
-bool SQLiteStatement::returnsAtLeastOneResult()
-{
- if (!m_statement && prepare() != SQLITE_OK)
- return false;
- ASSERT(m_isPrepared);
- if (step() != SQLITE_ROW) {
- finalize();
- return false;
- }
- finalize();
- return true;
-
-}
-
-int SQLiteStatement::bindBlob(int index, const void* blob, int size)
-{
- ASSERT(m_isPrepared);
- ASSERT(index > 0);
- ASSERT(static_cast<unsigned>(index) <= bindParameterCount());
- ASSERT(blob);
- ASSERT(size >= 0);
-
- if (!m_statement)
- return SQLITE_ERROR;
-
- return sqlite3_bind_blob(m_statement, index, blob, size, SQLITE_TRANSIENT);
-}
-
-int SQLiteStatement::bindBlob(int index, const String& text)
-{
- // SQLite treats uses zero pointers to represent null strings, which means we need to make sure to map null WTFStrings to zero pointers.
- ASSERT(!String().charactersWithNullTermination().data());
- return bindBlob(index, text.charactersWithNullTermination().data(), text.length() * sizeof(UChar));
-}
-
-int SQLiteStatement::bindText(int index, const String& text)
-{
- ASSERT(m_isPrepared);
- ASSERT(index > 0);
- ASSERT(static_cast<unsigned>(index) <= bindParameterCount());
-
- // SQLite treats uses zero pointers to represent null strings, which means we need to make sure to map null WTFStrings to zero pointers.
- ASSERT(!String().charactersWithNullTermination().data());
- return sqlite3_bind_text16(m_statement, index, text.charactersWithNullTermination().data(), sizeof(UChar) * text.length(), SQLITE_TRANSIENT);
-}
-
-int SQLiteStatement::bindInt(int index, int integer)
-{
- ASSERT(m_isPrepared);
- ASSERT(index > 0);
- ASSERT(static_cast<unsigned>(index) <= bindParameterCount());
-
- return sqlite3_bind_int(m_statement, index, integer);
-}
-
-int SQLiteStatement::bindInt64(int index, int64_t integer)
-{
- ASSERT(m_isPrepared);
- ASSERT(index > 0);
- ASSERT(static_cast<unsigned>(index) <= bindParameterCount());
-
- return sqlite3_bind_int64(m_statement, index, integer);
-}
-
-int SQLiteStatement::bindDouble(int index, double number)
-{
- ASSERT(m_isPrepared);
- ASSERT(index > 0);
- ASSERT(static_cast<unsigned>(index) <= bindParameterCount());
-
- return sqlite3_bind_double(m_statement, index, number);
-}
-
-int SQLiteStatement::bindNull(int index)
-{
- ASSERT(m_isPrepared);
- ASSERT(index > 0);
- ASSERT(static_cast<unsigned>(index) <= bindParameterCount());
-
- return sqlite3_bind_null(m_statement, index);
-}
-
-int SQLiteStatement::bindValue(int index, const SQLValue& value)
-{
- switch (value.type()) {
- case SQLValue::StringValue:
- return bindText(index, value.string());
- case SQLValue::NumberValue:
- return bindDouble(index, value.number());
- case SQLValue::NullValue:
- return bindNull(index);
- }
-
- ASSERT_NOT_REACHED();
- return SQLITE_ERROR;
-}
-
-unsigned SQLiteStatement::bindParameterCount() const
-{
- ASSERT(m_isPrepared);
- if (!m_statement)
- return 0;
- return sqlite3_bind_parameter_count(m_statement);
-}
-
-int SQLiteStatement::columnCount()
-{
- ASSERT(m_isPrepared);
- if (!m_statement)
- return 0;
- return sqlite3_data_count(m_statement);
-}
-
-bool SQLiteStatement::isColumnNull(int col)
-{
- ASSERT(col >= 0);
- if (!m_statement)
- if (prepareAndStep() != SQLITE_ROW)
- return false;
- if (columnCount() <= col)
- return false;
-
- return sqlite3_column_type(m_statement, col) == SQLITE_NULL;
-}
-
-bool SQLiteStatement::isColumnDeclaredAsBlob(int col)
-{
- ASSERT(col >= 0);
- if (!m_statement) {
- if (prepare() != SQLITE_OK)
- return false;
- }
-
- return equalIgnoringCase(String("BLOB"), String(reinterpret_cast<const UChar*>(sqlite3_column_decltype16(m_statement, col))));
-}
-
-String SQLiteStatement::getColumnName(int col)
-{
- ASSERT(col >= 0);
- if (!m_statement)
- if (prepareAndStep() != SQLITE_ROW)
- return String();
- if (columnCount() <= col)
- return String();
- return String(reinterpret_cast<const UChar*>(sqlite3_column_name16(m_statement, col)));
-}
-
-SQLValue SQLiteStatement::getColumnValue(int col)
-{
- ASSERT(col >= 0);
- if (!m_statement)
- if (prepareAndStep() != SQLITE_ROW)
- return SQLValue();
- if (columnCount() <= col)
- return SQLValue();
-
- // SQLite is typed per value. optional column types are
- // "(mostly) ignored"
- sqlite3_value* value = sqlite3_column_value(m_statement, col);
- switch (sqlite3_value_type(value)) {
- case SQLITE_INTEGER: // SQLValue and JS don't represent integers, so use FLOAT -case
- case SQLITE_FLOAT:
- return SQLValue(sqlite3_value_double(value));
- case SQLITE_BLOB: // SQLValue and JS don't represent blobs, so use TEXT -case
- case SQLITE_TEXT: {
- const UChar* string = reinterpret_cast<const UChar*>(sqlite3_value_text16(value));
- unsigned length = WTF::lengthOfNullTerminatedString(string);
- return SQLValue(StringImpl::create8BitIfPossible(string, length));
- }
- case SQLITE_NULL:
- return SQLValue();
- default:
- break;
- }
- ASSERT_NOT_REACHED();
- return SQLValue();
-}
-
-String SQLiteStatement::getColumnText(int col)
-{
- ASSERT(col >= 0);
- if (!m_statement)
- if (prepareAndStep() != SQLITE_ROW)
- return String();
- if (columnCount() <= col)
- return String();
- const UChar* string = reinterpret_cast<const UChar*>(sqlite3_column_text16(m_statement, col));
- return StringImpl::create8BitIfPossible(string, sqlite3_column_bytes16(m_statement, col) / sizeof(UChar));
-}
-
-double SQLiteStatement::getColumnDouble(int col)
-{
- ASSERT(col >= 0);
- if (!m_statement)
- if (prepareAndStep() != SQLITE_ROW)
- return 0.0;
- if (columnCount() <= col)
- return 0.0;
- return sqlite3_column_double(m_statement, col);
-}
-
-int SQLiteStatement::getColumnInt(int col)
-{
- ASSERT(col >= 0);
- if (!m_statement)
- if (prepareAndStep() != SQLITE_ROW)
- return 0;
- if (columnCount() <= col)
- return 0;
- return sqlite3_column_int(m_statement, col);
-}
-
-int64_t SQLiteStatement::getColumnInt64(int col)
-{
- ASSERT(col >= 0);
- if (!m_statement)
- if (prepareAndStep() != SQLITE_ROW)
- return 0;
- if (columnCount() <= col)
- return 0;
- return sqlite3_column_int64(m_statement, col);
-}
-
-String SQLiteStatement::getColumnBlobAsString(int col)
-{
- ASSERT(col >= 0);
-
- if (!m_statement && prepareAndStep() != SQLITE_ROW)
- return String();
-
- if (columnCount() <= col)
- return String();
-
- const void* blob = sqlite3_column_blob(m_statement, col);
- if (!blob)
- return String();
-
- int size = sqlite3_column_bytes(m_statement, col);
- if (size < 0)
- return String();
-
- ASSERT(!(size % sizeof(UChar)));
- return String(static_cast<const UChar*>(blob), size / sizeof(UChar));
-}
-
-void SQLiteStatement::getColumnBlobAsVector(int col, Vector<char>& result)
-{
- ASSERT(col >= 0);
-
- if (!m_statement && prepareAndStep() != SQLITE_ROW) {
- result.clear();
- return;
- }
-
- if (columnCount() <= col) {
- result.clear();
- return;
- }
-
- const void* blob = sqlite3_column_blob(m_statement, col);
- if (!blob) {
- result.clear();
- return;
- }
-
- int size = sqlite3_column_bytes(m_statement, col);
- result.resize((size_t)size);
- for (int i = 0; i < size; ++i)
- result[i] = (static_cast<const unsigned char*>(blob))[i];
-}
-
-const void* SQLiteStatement::getColumnBlob(int col, int& size)
-{
- ASSERT(col >= 0);
-
- size = 0;
-
- if (finalize() != SQLITE_OK)
- LOG(SQLDatabase, "Finalize failed");
- if (prepare() != SQLITE_OK) {
- LOG(SQLDatabase, "Prepare failed");
- return 0;
- }
- if (step() != SQLITE_ROW) {
- LOG(SQLDatabase, "Step wasn't a row");
- return 0;
- }
-
- if (columnCount() <= col)
- return 0;
-
- const void* blob = sqlite3_column_blob(m_statement, col);
- if (!blob)
- return 0;
-
- size = sqlite3_column_bytes(m_statement, col);
- return blob;
-}
-
-bool SQLiteStatement::returnTextResults(int col, Vector<String>& v)
-{
- ASSERT(col >= 0);
-
- v.clear();
-
- if (m_statement)
- finalize();
- if (prepare() != SQLITE_OK)
- return false;
-
- while (step() == SQLITE_ROW)
- v.append(getColumnText(col));
- bool result = true;
- if (m_database.lastError() != SQLITE_DONE) {
- result = false;
- LOG(SQLDatabase, "Error reading results from database query %s", m_query.ascii().data());
- }
- finalize();
- return result;
-}
-
-bool SQLiteStatement::returnIntResults(int col, Vector<int>& v)
-{
- v.clear();
-
- if (m_statement)
- finalize();
- if (prepare() != SQLITE_OK)
- return false;
-
- while (step() == SQLITE_ROW)
- v.append(getColumnInt(col));
- bool result = true;
- if (m_database.lastError() != SQLITE_DONE) {
- result = false;
- LOG(SQLDatabase, "Error reading results from database query %s", m_query.ascii().data());
- }
- finalize();
- return result;
-}
-
-bool SQLiteStatement::returnInt64Results(int col, Vector<int64_t>& v)
-{
- v.clear();
-
- if (m_statement)
- finalize();
- if (prepare() != SQLITE_OK)
- return false;
-
- while (step() == SQLITE_ROW)
- v.append(getColumnInt64(col));
- bool result = true;
- if (m_database.lastError() != SQLITE_DONE) {
- result = false;
- LOG(SQLDatabase, "Error reading results from database query %s", m_query.ascii().data());
- }
- finalize();
- return result;
-}
-
-bool SQLiteStatement::returnDoubleResults(int col, Vector<double>& v)
-{
- v.clear();
-
- if (m_statement)
- finalize();
- if (prepare() != SQLITE_OK)
- return false;
-
- while (step() == SQLITE_ROW)
- v.append(getColumnDouble(col));
- bool result = true;
- if (m_database.lastError() != SQLITE_DONE) {
- result = false;
- LOG(SQLDatabase, "Error reading results from database query %s", m_query.ascii().data());
- }
- finalize();
- return result;
-}
-
-bool SQLiteStatement::isExpired()
-{
- return !m_statement || sqlite3_expired(m_statement);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/sql/SQLiteStatement.h b/chromium/third_party/WebKit/Source/core/platform/sql/SQLiteStatement.h
deleted file mode 100644
index e8b5c1ec48d..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/sql/SQLiteStatement.h
+++ /dev/null
@@ -1,108 +0,0 @@
-/*
- * Copyright (C) 2006, 2007, 2008 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SQLiteStatement_h
-#define SQLiteStatement_h
-
-#include "core/platform/sql/SQLiteDatabase.h"
-
-struct sqlite3_stmt;
-
-namespace WebCore {
-
-class SQLValue;
-
-class SQLiteStatement {
- WTF_MAKE_NONCOPYABLE(SQLiteStatement); WTF_MAKE_FAST_ALLOCATED;
-public:
- SQLiteStatement(SQLiteDatabase&, const String&);
- ~SQLiteStatement();
-
- int prepare();
- int bindBlob(int index, const void* blob, int size);
- int bindBlob(int index, const String&);
- int bindText(int index, const String&);
- int bindInt(int index, int);
- int bindInt64(int index, int64_t);
- int bindDouble(int index, double);
- int bindNull(int index);
- int bindValue(int index, const SQLValue&);
- unsigned bindParameterCount() const;
-
- int step();
- int finalize();
- int reset();
-
- int prepareAndStep() { if (int error = prepare()) return error; return step(); }
-
- // prepares, steps, and finalizes the query.
- // returns true if all 3 steps succeed with step() returning SQLITE_DONE
- // returns false otherwise
- bool executeCommand();
-
- // prepares, steps, and finalizes.
- // returns true is step() returns SQLITE_ROW
- // returns false otherwise
- bool returnsAtLeastOneResult();
-
- bool isExpired();
-
- // Returns -1 on last-step failing. Otherwise, returns number of rows
- // returned in the last step()
- int columnCount();
-
- bool isColumnNull(int col);
- bool isColumnDeclaredAsBlob(int col);
- String getColumnName(int col);
- SQLValue getColumnValue(int col);
- String getColumnText(int col);
- double getColumnDouble(int col);
- int getColumnInt(int col);
- int64_t getColumnInt64(int col);
- const void* getColumnBlob(int col, int& size);
- String getColumnBlobAsString(int col);
- void getColumnBlobAsVector(int col, Vector<char>&);
-
- bool returnTextResults(int col, Vector<String>&);
- bool returnIntResults(int col, Vector<int>&);
- bool returnInt64Results(int col, Vector<int64_t>&);
- bool returnDoubleResults(int col, Vector<double>&);
-
- SQLiteDatabase* database() { return &m_database; }
-
- const String& query() const { return m_query; }
-
-private:
- SQLiteDatabase& m_database;
- String m_query;
- sqlite3_stmt* m_statement;
-#ifndef NDEBUG
- bool m_isPrepared;
-#endif
-};
-
-} // namespace WebCore
-
-#endif // SQLiteStatement_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/sql/SQLiteTransaction.cpp b/chromium/third_party/WebKit/Source/core/platform/sql/SQLiteTransaction.cpp
deleted file mode 100644
index c319d47810e..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/sql/SQLiteTransaction.cpp
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- * Copyright (C) 2006 Apple Computer, Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/sql/SQLiteTransaction.h"
-
-#include "core/platform/sql/SQLiteDatabase.h"
-
-namespace WebCore {
-
-SQLiteTransaction::SQLiteTransaction(SQLiteDatabase& db, bool readOnly)
- : m_db(db)
- , m_inProgress(false)
- , m_readOnly(readOnly)
-{
-}
-
-SQLiteTransaction::~SQLiteTransaction()
-{
- if (m_inProgress)
- rollback();
-}
-
-void SQLiteTransaction::begin()
-{
- if (!m_inProgress) {
- ASSERT(!m_db.m_transactionInProgress);
- // Call BEGIN IMMEDIATE for a write transaction to acquire
- // a RESERVED lock on the DB file. Otherwise, another write
- // transaction (on another connection) could make changes
- // to the same DB file before this transaction gets to execute
- // any statements. If that happens, this transaction will fail.
- // http://www.sqlite.org/lang_transaction.html
- // http://www.sqlite.org/lockingv3.html#locking
- if (m_readOnly)
- m_inProgress = m_db.executeCommand("BEGIN");
- else
- m_inProgress = m_db.executeCommand("BEGIN IMMEDIATE");
- m_db.m_transactionInProgress = m_inProgress;
- }
-}
-
-void SQLiteTransaction::commit()
-{
- if (m_inProgress) {
- ASSERT(m_db.m_transactionInProgress);
- m_inProgress = !m_db.executeCommand("COMMIT");
- m_db.m_transactionInProgress = m_inProgress;
- }
-}
-
-void SQLiteTransaction::rollback()
-{
- // We do not use the 'm_inProgress = m_db.executeCommand("ROLLBACK")' construct here,
- // because m_inProgress should always be set to false after a ROLLBACK, and
- // m_db.executeCommand("ROLLBACK") can sometimes harmlessly fail, thus returning
- // a non-zero/true result (http://www.sqlite.org/lang_transaction.html).
- if (m_inProgress) {
- ASSERT(m_db.m_transactionInProgress);
- m_db.executeCommand("ROLLBACK");
- m_inProgress = false;
- m_db.m_transactionInProgress = false;
- }
-}
-
-void SQLiteTransaction::stop()
-{
- if (m_inProgress) {
- m_inProgress = false;
- m_db.m_transactionInProgress = false;
- }
-}
-
-bool SQLiteTransaction::wasRolledBackBySqlite() const
-{
- // According to http://www.sqlite.org/c3ref/get_autocommit.html,
- // the auto-commit flag should be off in the middle of a transaction
- return m_inProgress && m_db.isAutoCommitOn();
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/sql/SQLiteTransaction.h b/chromium/third_party/WebKit/Source/core/platform/sql/SQLiteTransaction.h
deleted file mode 100644
index 9a9bf7157aa..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/sql/SQLiteTransaction.h
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Copyright (C) 2006 Apple Computer, Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SQLiteTransaction_h
-#define SQLiteTransaction_h
-
-#include "wtf/FastAllocBase.h"
-#include "wtf/Noncopyable.h"
-
-namespace WebCore {
-
-class SQLiteDatabase;
-
-class SQLiteTransaction {
- WTF_MAKE_NONCOPYABLE(SQLiteTransaction); WTF_MAKE_FAST_ALLOCATED;
-public:
- SQLiteTransaction(SQLiteDatabase& db, bool readOnly = false);
- ~SQLiteTransaction();
-
- void begin();
- void commit();
- void rollback();
- void stop();
-
- bool inProgress() const { return m_inProgress; }
- bool wasRolledBackBySqlite() const;
-private:
- SQLiteDatabase& m_db;
- bool m_inProgress;
- bool m_readOnly;
-};
-
-} // namespace WebCore
-
-#endif // SQLiteTransation_H
diff --git a/chromium/third_party/WebKit/Source/core/platform/sql/chromium/SQLiteFileSystemChromium.cpp b/chromium/third_party/WebKit/Source/core/platform/sql/chromium/SQLiteFileSystemChromium.cpp
deleted file mode 100644
index 0673127a903..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/sql/chromium/SQLiteFileSystemChromium.cpp
+++ /dev/null
@@ -1,100 +0,0 @@
-/*
- * Copyright (C) 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/sql/SQLiteFileSystem.h"
-
-#include <sqlite3.h>
-#include "public/platform/Platform.h"
-#include "wtf/text/CString.h"
-
-// SQLiteFileSystem::registerSQLiteVFS() is implemented in the
-// platform-specific files SQLiteFileSystemChromium{Win|Posix}.cpp
-namespace WebCore {
-
-SQLiteFileSystem::SQLiteFileSystem()
-{
-}
-
-int SQLiteFileSystem::openDatabase(const String& filename, sqlite3** database, bool forWebSQLDatabase)
-{
- if (!forWebSQLDatabase)
- return sqlite3_open(filename.utf8().data(), database);
-
- return sqlite3_open_v2(filename.utf8().data(), database, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, "chromium_vfs");
-}
-
-String SQLiteFileSystem::getFileNameForNewDatabase(
- const String&, const String& dbName, const String &originIdentifier, SQLiteDatabase*)
-{
- // Not used by Chromium's DatabaseTracker implementation
- ASSERT_NOT_REACHED();
- return String();
-}
-
-String SQLiteFileSystem::appendDatabaseFileNameToPath(const String&, const String& fileName)
-{
- // Not used by Chromium's DatabaseTracker implementation
- ASSERT_NOT_REACHED();
- return String();
-}
-
-bool SQLiteFileSystem::ensureDatabaseDirectoryExists(const String&)
-{
- // Not used by Chromium's DatabaseTracker implementation
- ASSERT_NOT_REACHED();
- return false;
-}
-
-bool SQLiteFileSystem::ensureDatabaseFileExists(const String&, bool)
-{
- // Not used by Chromium's DatabaseTracker implementation
- ASSERT_NOT_REACHED();
- return false;
-}
-
-bool SQLiteFileSystem::deleteEmptyDatabaseDirectory(const String&)
-{
- // Not used by Chromium's DatabaseTracker implementation
- ASSERT_NOT_REACHED();
- return false;
-}
-
-bool SQLiteFileSystem::deleteDatabaseFile(const String& fileName)
-{
- return (WebKit::Platform::current()->databaseDeleteFile(fileName, false) == SQLITE_OK);
-}
-
-long long SQLiteFileSystem::getDatabaseFileSize(const String& fileName)
-{
- return WebKit::Platform::current()->databaseGetFileSize(fileName);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/sql/chromium/SQLiteFileSystemChromiumPosix.cpp b/chromium/third_party/WebKit/Source/core/platform/sql/chromium/SQLiteFileSystemChromiumPosix.cpp
deleted file mode 100644
index 2500230d571..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/sql/chromium/SQLiteFileSystemChromiumPosix.cpp
+++ /dev/null
@@ -1,197 +0,0 @@
-/*
- * Copyright (C) 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/sql/SQLiteFileSystem.h"
-
-#include <sqlite3.h>
-#include "public/platform/Platform.h"
-
-#include <fcntl.h>
-#include <string.h>
-#include <unistd.h>
-
-using namespace WebCore;
-
-// Defined in Chromium's codebase in third_party/sqlite/src/os_unix.c
-extern "C" {
-void chromium_sqlite3_initialize_unix_sqlite3_file(sqlite3_file* file);
-int chromium_sqlite3_fill_in_unix_sqlite3_file(sqlite3_vfs* vfs, int fd, int dirfd, sqlite3_file* file, const char* fileName, int noLock);
-int chromium_sqlite3_get_reusable_file_handle(sqlite3_file* file, const char* fileName, int flags, int* fd);
-void chromium_sqlite3_update_reusable_file_handle(sqlite3_file* file, int fd, int flags);
-void chromium_sqlite3_destroy_reusable_file_handle(sqlite3_file* file);
-}
-
-// Chromium's Posix implementation of SQLite VFS
-namespace {
-
-// Opens a file.
-//
-// vfs - pointer to the sqlite3_vfs object.
-// fileName - the name of the file.
-// id - the structure that will manipulate the newly opened file.
-// desiredFlags - the desired open mode flags.
-// usedFlags - the actual open mode flags that were used.
-int chromiumOpen(sqlite3_vfs* vfs, const char* fileName,
- sqlite3_file* id, int desiredFlags, int* usedFlags)
-{
- chromium_sqlite3_initialize_unix_sqlite3_file(id);
- int fd = -1;
- int result = chromium_sqlite3_get_reusable_file_handle(id, fileName, desiredFlags, &fd);
- if (result != SQLITE_OK)
- return result;
-
- if (fd < 0) {
- fd = WebKit::Platform::current()->databaseOpenFile(String(fileName), desiredFlags);
- if ((fd < 0) && (desiredFlags & SQLITE_OPEN_READWRITE)) {
- int newFlags = (desiredFlags & ~(SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE)) | SQLITE_OPEN_READONLY;
- fd = WebKit::Platform::current()->databaseOpenFile(String(fileName), newFlags);
- }
- }
- if (fd < 0) {
- chromium_sqlite3_destroy_reusable_file_handle(id);
- return SQLITE_CANTOPEN;
- }
-
- if (usedFlags)
- *usedFlags = desiredFlags;
- chromium_sqlite3_update_reusable_file_handle(id, fd, desiredFlags);
-
- fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC);
-
- // The mask 0x00007F00 gives us the 7 bits that determine the type of the file SQLite is trying to open.
- int fileType = desiredFlags & 0x00007F00;
- int noLock = (fileType != SQLITE_OPEN_MAIN_DB);
- result = chromium_sqlite3_fill_in_unix_sqlite3_file(vfs, fd, -1, id, fileName, noLock);
- if (result != SQLITE_OK)
- chromium_sqlite3_destroy_reusable_file_handle(id);
- return result;
-}
-
-// Deletes the given file.
-//
-// vfs - pointer to the sqlite3_vfs object.
-// fileName - the name of the file.
-// syncDir - determines if the directory to which this file belongs
-// should be synched after the file is deleted.
-int chromiumDelete(sqlite3_vfs*, const char* fileName, int syncDir)
-{
- return WebKit::Platform::current()->databaseDeleteFile(String(fileName), syncDir);
-}
-
-// Check the existance and status of the given file.
-//
-// vfs - pointer to the sqlite3_vfs object.
-// fileName - the name of the file.
-// flag - the type of test to make on this file.
-// res - the result.
-int chromiumAccess(sqlite3_vfs*, const char* fileName, int flag, int* res)
-{
- int attr = static_cast<int>(WebKit::Platform::current()->databaseGetFileAttributes(String(fileName)));
- if (attr < 0) {
- *res = 0;
- return SQLITE_OK;
- }
-
- switch (flag) {
- case SQLITE_ACCESS_EXISTS:
- *res = 1; // if the file doesn't exist, attr < 0
- break;
- case SQLITE_ACCESS_READWRITE:
- *res = (attr & W_OK) && (attr & R_OK);
- break;
- case SQLITE_ACCESS_READ:
- *res = (attr & R_OK);
- break;
- default:
- return SQLITE_ERROR;
- }
-
- return SQLITE_OK;
-}
-
-// Turns a relative pathname into a full pathname.
-//
-// vfs - pointer to the sqlite3_vfs object.
-// relativePath - the relative path.
-// bufSize - the size of the output buffer in bytes.
-// absolutePath - the output buffer where the absolute path will be stored.
-int chromiumFullPathname(sqlite3_vfs* vfs, const char* relativePath,
- int, char* absolutePath)
-{
- // The renderer process doesn't need to know the absolute path of the file
- sqlite3_snprintf(vfs->mxPathname, absolutePath, "%s", relativePath);
- return SQLITE_OK;
-}
-
-#ifndef SQLITE_OMIT_LOAD_EXTENSION
-// Returns NULL, thus disallowing loading libraries in the renderer process.
-//
-// vfs - pointer to the sqlite3_vfs object.
-// fileName - the name of the shared library file.
-void* chromiumDlOpen(sqlite3_vfs*, const char*)
-{
- return 0;
-}
-#else
-#define chromiumDlOpen 0
-#endif // SQLITE_OMIT_LOAD_EXTENSION
-
-} // namespace
-
-namespace WebCore {
-
-void SQLiteFileSystem::registerSQLiteVFS()
-{
- sqlite3_vfs* unix_vfs = sqlite3_vfs_find("unix");
- static sqlite3_vfs chromium_vfs = {
- 1,
- unix_vfs->szOsFile,
- unix_vfs->mxPathname,
- 0,
- "chromium_vfs",
- unix_vfs->pAppData,
- chromiumOpen,
- chromiumDelete,
- chromiumAccess,
- chromiumFullPathname,
- chromiumDlOpen,
- unix_vfs->xDlError,
- unix_vfs->xDlSym,
- unix_vfs->xDlClose,
- unix_vfs->xRandomness,
- unix_vfs->xSleep,
- unix_vfs->xCurrentTime,
- unix_vfs->xGetLastError
- };
- sqlite3_vfs_register(&chromium_vfs, 0);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/sql/chromium/SQLiteFileSystemChromiumWin.cpp b/chromium/third_party/WebKit/Source/core/platform/sql/chromium/SQLiteFileSystemChromiumWin.cpp
deleted file mode 100644
index 5487018ead7..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/sql/chromium/SQLiteFileSystemChromiumWin.cpp
+++ /dev/null
@@ -1,169 +0,0 @@
-/*
- * Copyright (C) 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/sql/SQLiteFileSystem.h"
-
-#include <windows.h>
-#include <sqlite3.h>
-#include "public/platform/Platform.h"
-
-using namespace WebCore;
-
-// Defined in Chromium's codebase in third_party/sqlite/src/os_win.c
-extern "C" {
-int chromium_sqlite3_initialize_win_sqlite3_file(sqlite3_file* file, HANDLE handle);
-}
-
-// Chromium's Windows implementation of SQLite VFS
-namespace {
-
-// Opens a file.
-//
-// vfs - pointer to the sqlite3_vfs object.
-// fileName - the name of the file.
-// id - the structure that will manipulate the newly opened file.
-// desiredFlags - the desired open mode flags.
-// usedFlags - the actual open mode flags that were used.
-int chromiumOpen(sqlite3_vfs*, const char* fileName,
- sqlite3_file* id, int desiredFlags, int* usedFlags)
-{
- HANDLE h = WebKit::Platform::current()->databaseOpenFile(String(fileName), desiredFlags);
- if (h == INVALID_HANDLE_VALUE) {
- if (desiredFlags & SQLITE_OPEN_READWRITE) {
- int newFlags = (desiredFlags | SQLITE_OPEN_READONLY) & ~SQLITE_OPEN_READWRITE;
- return chromiumOpen(0, fileName, id, newFlags, usedFlags);
- } else
- return SQLITE_CANTOPEN;
- }
- if (usedFlags) {
- if (desiredFlags & SQLITE_OPEN_READWRITE)
- *usedFlags = SQLITE_OPEN_READWRITE;
- else
- *usedFlags = SQLITE_OPEN_READONLY;
- }
-
- chromium_sqlite3_initialize_win_sqlite3_file(id, h);
- return SQLITE_OK;
-}
-
-// Deletes the given file.
-//
-// vfs - pointer to the sqlite3_vfs object.
-// fileName - the name of the file.
-// syncDir - determines if the directory to which this file belongs
-// should be synched after the file is deleted.
-int chromiumDelete(sqlite3_vfs*, const char* fileName, int)
-{
- return WebKit::Platform::current()->databaseDeleteFile(String(fileName), false);
-}
-
-// Check the existance and status of the given file.
-//
-// vfs - pointer to the sqlite3_vfs object.
-// fileName - the name of the file.
-// flag - the type of test to make on this file.
-// res - the result.
-int chromiumAccess(sqlite3_vfs*, const char* fileName, int flag, int* res)
-{
- DWORD attr = WebKit::Platform::current()->databaseGetFileAttributes(String(fileName));
- switch (flag) {
- case SQLITE_ACCESS_READ:
- case SQLITE_ACCESS_EXISTS:
- *res = (attr != INVALID_FILE_ATTRIBUTES);
- break;
- case SQLITE_ACCESS_READWRITE:
- *res = ((attr & FILE_ATTRIBUTE_READONLY) == 0);
- break;
- default:
- return SQLITE_ERROR;
- }
-
- return SQLITE_OK;
-}
-
-// Turns a relative pathname into a full pathname.
-//
-// vfs - pointer to the sqlite3_vfs object.
-// relativePath - the relative path.
-// bufSize - the size of the output buffer in bytes.
-// absolutePath - the output buffer where the absolute path will be stored.
-int chromiumFullPathname(sqlite3_vfs* vfs, const char* relativePath,
- int, char* absolutePath)
-{
- // The renderer process doesn't need to know the absolute path of the file
- sqlite3_snprintf(vfs->mxPathname, absolutePath, "%s", relativePath);
- return SQLITE_OK;
-}
-
-#ifndef SQLITE_OMIT_LOAD_EXTENSION
-// Returns NULL, thus disallowing loading libraries in the renderer process.
-//
-// vfs - pointer to the sqlite3_vfs object.
-// fileName - the name of the shared library file.
-void* chromiumDlOpen(sqlite3_vfs*, const char*)
-{
- return 0;
-}
-#else
-#define chromiumDlOpen 0
-#endif // SQLITE_OMIT_LOAD_EXTENSION
-
-} // namespace
-
-namespace WebCore {
-
-void SQLiteFileSystem::registerSQLiteVFS()
-{
- sqlite3_vfs* win32_vfs = sqlite3_vfs_find("win32");
- static sqlite3_vfs chromium_vfs = {
- 1,
- win32_vfs->szOsFile,
- win32_vfs->mxPathname,
- 0,
- "chromium_vfs",
- win32_vfs->pAppData,
- chromiumOpen,
- chromiumDelete,
- chromiumAccess,
- chromiumFullPathname,
- chromiumDlOpen,
- win32_vfs->xDlError,
- win32_vfs->xDlSym,
- win32_vfs->xDlClose,
- win32_vfs->xRandomness,
- win32_vfs->xSleep,
- win32_vfs->xCurrentTime,
- win32_vfs->xGetLastError
- };
- sqlite3_vfs_register(&chromium_vfs, 0);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/text/AtomicStringKeyedMRUCache.h b/chromium/third_party/WebKit/Source/core/platform/text/AtomicStringKeyedMRUCache.h
deleted file mode 100644
index 5b734e98c01..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/text/AtomicStringKeyedMRUCache.h
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * Copyright (C) 2010 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef AtomicStringKeyedMRUCache_h
-#define AtomicStringKeyedMRUCache_h
-
-#include "wtf/text/AtomicString.h"
-
-namespace WebCore {
-
-template<typename T, size_t capacity = 4>
-class AtomicStringKeyedMRUCache {
-public:
- T get(const AtomicString& key)
- {
- if (key.isNull()) {
- DEFINE_STATIC_LOCAL(T, valueForNull, (createValueForNullKey()));
- return valueForNull;
- }
-
- for (size_t i = 0; i < m_cache.size(); ++i) {
- if (m_cache[i].first == key) {
- size_t foundIndex = i;
- if (foundIndex + 1 < m_cache.size()) {
- Entry entry = m_cache[foundIndex];
- m_cache.remove(foundIndex);
- foundIndex = m_cache.size();
- m_cache.append(entry);
- }
- return m_cache[foundIndex].second;
- }
- }
- if (m_cache.size() == capacity)
- m_cache.remove(0);
-
- m_cache.append(std::make_pair(key, createValueForKey(key)));
- return m_cache.last().second;
- }
-
-private:
- T createValueForNullKey();
- T createValueForKey(const AtomicString&);
-
- typedef pair<AtomicString, T> Entry;
- typedef Vector<Entry, capacity> Cache;
- Cache m_cache;
-};
-
-}
-
-#endif // AtomicStringKeyedMRUCache_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/text/BidiContext.cpp b/chromium/third_party/WebKit/Source/core/platform/text/BidiContext.cpp
deleted file mode 100644
index fa12626a680..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/text/BidiContext.cpp
+++ /dev/null
@@ -1,111 +0,0 @@
-/*
- * Copyright (C) 2000 Lars Knoll (knoll@kde.org)
- * Copyright (C) 2003, 2004, 2006, 2007, 2009, 2010 Apple Inc. All right reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#include "config.h"
-#include "core/platform/text/BidiContext.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-using namespace WTF::Unicode;
-
-struct SameSizeAsBidiContext : public RefCounted<SameSizeAsBidiContext> {
- uint32_t bitfields : 16;
- void* parent;
-};
-
-COMPILE_ASSERT(sizeof(BidiContext) == sizeof(SameSizeAsBidiContext), BidiContext_should_stay_small);
-
-inline PassRefPtr<BidiContext> BidiContext::createUncached(unsigned char level, Direction direction, bool override, BidiEmbeddingSource source, BidiContext* parent)
-{
- return adoptRef(new BidiContext(level, direction, override, source, parent));
-}
-
-PassRefPtr<BidiContext> BidiContext::create(unsigned char level, Direction direction, bool override, BidiEmbeddingSource source, BidiContext* parent)
-{
- ASSERT(direction == (level % 2 ? RightToLeft : LeftToRight));
-
- if (parent)
- return createUncached(level, direction, override, source, parent);
-
- ASSERT(level <= 1);
- if (!level) {
- if (!override) {
- static BidiContext* ltrContext = createUncached(0, LeftToRight, false, FromStyleOrDOM, 0).leakRef();
- return ltrContext;
- }
-
- static BidiContext* ltrOverrideContext = createUncached(0, LeftToRight, true, FromStyleOrDOM, 0).leakRef();
- return ltrOverrideContext;
- }
-
- if (!override) {
- static BidiContext* rtlContext = createUncached(1, RightToLeft, false, FromStyleOrDOM, 0).leakRef();
- return rtlContext;
- }
-
- static BidiContext* rtlOverrideContext = createUncached(1, RightToLeft, true, FromStyleOrDOM, 0).leakRef();
- return rtlOverrideContext;
-}
-
-static inline PassRefPtr<BidiContext> copyContextAndRebaselineLevel(BidiContext* context, BidiContext* parent)
-{
- ASSERT(context);
- unsigned char newLevel = parent ? parent->level() : 0;
- if (context->dir() == RightToLeft)
- newLevel = nextGreaterOddLevel(newLevel);
- else if (parent)
- newLevel = nextGreaterEvenLevel(newLevel);
-
- return BidiContext::create(newLevel, context->dir(), context->override(), context->source(), parent);
-}
-
-// The BidiContext stack must be immutable -- they're re-used for re-layout after
-// DOM modification/editing -- so we copy all the non-unicode contexts, and
-// recalculate their levels.
-PassRefPtr<BidiContext> BidiContext::copyStackRemovingUnicodeEmbeddingContexts()
-{
- Vector<BidiContext*, 64> contexts;
- for (BidiContext* iter = this; iter; iter = iter->parent()) {
- if (iter->source() != FromUnicode)
- contexts.append(iter);
- }
- ASSERT(contexts.size());
-
- RefPtr<BidiContext> topContext = copyContextAndRebaselineLevel(contexts.last(), 0);
- for (int i = contexts.size() - 1; i > 0; --i)
- topContext = copyContextAndRebaselineLevel(contexts[i - 1], topContext.get());
-
- return topContext.release();
-}
-
-bool operator==(const BidiContext& c1, const BidiContext& c2)
-{
- if (&c1 == &c2)
- return true;
- if (c1.level() != c2.level() || c1.override() != c2.override() || c1.dir() != c2.dir() || c1.source() != c2.source())
- return false;
- if (!c1.parent())
- return !c2.parent();
- return c2.parent() && *c1.parent() == *c2.parent();
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/text/BidiContext.h b/chromium/third_party/WebKit/Source/core/platform/text/BidiContext.h
deleted file mode 100644
index c701e88ad4d..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/text/BidiContext.h
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * Copyright (C) 2000 Lars Knoll (knoll@kde.org)
- * Copyright (C) 2003, 2004, 2006, 2007, 2009, 2010 Apple Inc. All right reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#ifndef BidiContext_h
-#define BidiContext_h
-
-#include "wtf/Assertions.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/RefPtr.h"
-#include "wtf/unicode/Unicode.h"
-
-namespace WebCore {
-
-enum BidiEmbeddingSource {
- FromStyleOrDOM,
- FromUnicode
-};
-
-// Used to keep track of explicit embeddings.
-class BidiContext : public RefCounted<BidiContext> {
-public:
- static PassRefPtr<BidiContext> create(unsigned char level, WTF::Unicode::Direction, bool override = false, BidiEmbeddingSource = FromStyleOrDOM, BidiContext* parent = 0);
-
- BidiContext* parent() const { return m_parent.get(); }
- unsigned char level() const { return m_level; }
- WTF::Unicode::Direction dir() const { return static_cast<WTF::Unicode::Direction>(m_direction); }
- bool override() const { return m_override; }
- BidiEmbeddingSource source() const { return static_cast<BidiEmbeddingSource>(m_source); }
-
- PassRefPtr<BidiContext> copyStackRemovingUnicodeEmbeddingContexts();
-private:
- BidiContext(unsigned char level, WTF::Unicode::Direction direction, bool override, BidiEmbeddingSource source, BidiContext* parent)
- : m_level(level)
- , m_direction(direction)
- , m_override(override)
- , m_source(source)
- , m_parent(parent)
- {
- }
-
- static PassRefPtr<BidiContext> createUncached(unsigned char level, WTF::Unicode::Direction, bool override, BidiEmbeddingSource, BidiContext* parent);
-
- unsigned m_level : 6; // The maximium bidi level is 62: http://unicode.org/reports/tr9/#Explicit_Levels_and_Directions
- unsigned m_direction : 5; // Direction
- unsigned m_override : 1;
- unsigned m_source : 1; // BidiEmbeddingSource
- RefPtr<BidiContext> m_parent;
-};
-
-inline unsigned char nextGreaterOddLevel(unsigned char level)
-{
- return (level + 1) | 1;
-}
-
-inline unsigned char nextGreaterEvenLevel(unsigned char level)
-{
- return (level + 2) & ~1;
-}
-
-bool operator==(const BidiContext&, const BidiContext&);
-
-} // namespace WebCore
-
-#endif // BidiContext_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/text/BidiResolver.h b/chromium/third_party/WebKit/Source/core/platform/text/BidiResolver.h
deleted file mode 100644
index dc5ee34fa25..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/text/BidiResolver.h
+++ /dev/null
@@ -1,928 +0,0 @@
-/*
- * Copyright (C) 2000 Lars Knoll (knoll@kde.org)
- * Copyright (C) 2003, 2004, 2006, 2007, 2008 Apple Inc. All right reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#ifndef BidiResolver_h
-#define BidiResolver_h
-
-#include "core/platform/text/BidiContext.h"
-#include "core/platform/text/BidiRunList.h"
-#include "core/platform/text/TextDirection.h"
-#include "wtf/Noncopyable.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-template <class Iterator> struct MidpointState {
- MidpointState()
- {
- reset();
- }
-
- void reset()
- {
- numMidpoints = 0;
- currentMidpoint = 0;
- betweenMidpoints = false;
- }
-
- // The goal is to reuse the line state across multiple
- // lines so we just keep an array around for midpoints and never clear it across multiple
- // lines. We track the number of items and position using the two other variables.
- Vector<Iterator> midpoints;
- unsigned numMidpoints;
- unsigned currentMidpoint;
- bool betweenMidpoints;
-};
-
-// The BidiStatus at a given position (typically the end of a line) can
-// be cached and then used to restart bidi resolution at that position.
-struct BidiStatus {
- BidiStatus()
- : eor(WTF::Unicode::OtherNeutral)
- , lastStrong(WTF::Unicode::OtherNeutral)
- , last(WTF::Unicode::OtherNeutral)
- {
- }
-
- // Creates a BidiStatus representing a new paragraph root with a default direction.
- // Uses TextDirection as it only has two possibilities instead of WTF::Unicode::Direction which has 19.
- BidiStatus(TextDirection textDirection, bool isOverride)
- {
- WTF::Unicode::Direction direction = textDirection == LTR ? WTF::Unicode::LeftToRight : WTF::Unicode::RightToLeft;
- eor = lastStrong = last = direction;
- context = BidiContext::create(textDirection == LTR ? 0 : 1, direction, isOverride);
- }
-
- BidiStatus(WTF::Unicode::Direction eorDir, WTF::Unicode::Direction lastStrongDir, WTF::Unicode::Direction lastDir, PassRefPtr<BidiContext> bidiContext)
- : eor(eorDir)
- , lastStrong(lastStrongDir)
- , last(lastDir)
- , context(bidiContext)
- {
- }
-
- WTF::Unicode::Direction eor;
- WTF::Unicode::Direction lastStrong;
- WTF::Unicode::Direction last;
- RefPtr<BidiContext> context;
-};
-
-class BidiEmbedding {
-public:
- BidiEmbedding(WTF::Unicode::Direction direction, BidiEmbeddingSource source)
- : m_direction(direction)
- , m_source(source)
- {
- }
-
- WTF::Unicode::Direction direction() const { return m_direction; }
- BidiEmbeddingSource source() const { return m_source; }
-private:
- WTF::Unicode::Direction m_direction;
- BidiEmbeddingSource m_source;
-};
-
-inline bool operator==(const BidiStatus& status1, const BidiStatus& status2)
-{
- return status1.eor == status2.eor && status1.last == status2.last && status1.lastStrong == status2.lastStrong && *(status1.context) == *(status2.context);
-}
-
-inline bool operator!=(const BidiStatus& status1, const BidiStatus& status2)
-{
- return !(status1 == status2);
-}
-
-struct BidiCharacterRun {
- BidiCharacterRun(int start, int stop, BidiContext* context, WTF::Unicode::Direction dir)
- : m_override(context->override())
- , m_next(0)
- , m_start(start)
- , m_stop(stop)
- {
- if (dir == WTF::Unicode::OtherNeutral)
- dir = context->dir();
-
- m_level = context->level();
-
- // add level of run (cases I1 & I2)
- if (m_level % 2) {
- if (dir == WTF::Unicode::LeftToRight || dir == WTF::Unicode::ArabicNumber || dir == WTF::Unicode::EuropeanNumber)
- m_level++;
- } else {
- if (dir == WTF::Unicode::RightToLeft)
- m_level++;
- else if (dir == WTF::Unicode::ArabicNumber || dir == WTF::Unicode::EuropeanNumber)
- m_level += 2;
- }
- }
-
- int start() const { return m_start; }
- int stop() const { return m_stop; }
- unsigned char level() const { return m_level; }
- bool reversed(bool visuallyOrdered) { return m_level % 2 && !visuallyOrdered; }
- bool dirOverride(bool visuallyOrdered) { return m_override || visuallyOrdered; }
-
- BidiCharacterRun* next() const { return m_next; }
- void setNext(BidiCharacterRun* next) { m_next = next; }
-
- // Do not add anything apart from bitfields until after m_next. See https://bugs.webkit.org/show_bug.cgi?id=100173
- bool m_override : 1;
- bool m_hasHyphen : 1; // Used by BidiRun subclass which is a layering violation but enables us to save 8 bytes per object on 64-bit.
- bool m_startsSegment : 1; // Same comment as m_hasHyphen.
- unsigned char m_level;
- BidiCharacterRun* m_next;
- int m_start;
- int m_stop;
-};
-
-enum VisualDirectionOverride {
- NoVisualOverride,
- VisualLeftToRightOverride,
- VisualRightToLeftOverride
-};
-
-// BidiResolver is WebKit's implementation of the Unicode Bidi Algorithm
-// http://unicode.org/reports/tr9
-template <class Iterator, class Run> class BidiResolver {
- WTF_MAKE_NONCOPYABLE(BidiResolver);
-public:
- BidiResolver()
- : m_direction(WTF::Unicode::OtherNeutral)
- , m_reachedEndOfLine(false)
- , m_emptyRun(true)
- , m_nestedIsolateCount(0)
- {
- }
-
-#ifndef NDEBUG
- ~BidiResolver();
-#endif
-
- const Iterator& position() const { return m_current; }
- Iterator& position() { return m_current; }
- void setPositionIgnoringNestedIsolates(const Iterator& position) { m_current = position; }
- void setPosition(const Iterator& position, unsigned nestedIsolatedCount)
- {
- m_current = position;
- m_nestedIsolateCount = nestedIsolatedCount;
- }
-
- BidiContext* context() const { return m_status.context.get(); }
- void setContext(PassRefPtr<BidiContext> c) { m_status.context = c; }
-
- void setLastDir(WTF::Unicode::Direction lastDir) { m_status.last = lastDir; }
- void setLastStrongDir(WTF::Unicode::Direction lastStrongDir) { m_status.lastStrong = lastStrongDir; }
- void setEorDir(WTF::Unicode::Direction eorDir) { m_status.eor = eorDir; }
-
- WTF::Unicode::Direction dir() const { return m_direction; }
- void setDir(WTF::Unicode::Direction d) { m_direction = d; }
-
- const BidiStatus& status() const { return m_status; }
- void setStatus(const BidiStatus s) { m_status = s; }
-
- MidpointState<Iterator>& midpointState() { return m_midpointState; }
-
- // The current algorithm handles nested isolates one layer of nesting at a time.
- // But when we layout each isolated span, we will walk into (and ignore) all
- // child isolated spans.
- void enterIsolate() { m_nestedIsolateCount++; }
- void exitIsolate() { ASSERT(m_nestedIsolateCount >= 1); m_nestedIsolateCount--; }
- bool inIsolate() const { return m_nestedIsolateCount; }
-
- void embed(WTF::Unicode::Direction, BidiEmbeddingSource);
- bool commitExplicitEmbedding();
-
- void createBidiRunsForLine(const Iterator& end, VisualDirectionOverride = NoVisualOverride, bool hardLineBreak = false);
-
- BidiRunList<Run>& runs() { return m_runs; }
-
- // FIXME: This used to be part of deleteRuns() but was a layering violation.
- // It's unclear if this is still needed.
- void markCurrentRunEmpty() { m_emptyRun = true; }
-
- Vector<Run*>& isolatedRuns() { return m_isolatedRuns; }
-
- bool isEndOfParagraph(const Iterator& end) { return m_current == end || m_current.atEnd(); }
-
-protected:
- void increment() { m_current.increment(); }
- // FIXME: Instead of InlineBidiResolvers subclassing this method, we should
- // pass in some sort of Traits object which knows how to create runs for appending.
- void appendRun();
-
- Iterator m_current;
- // sor and eor are "start of run" and "end of run" respectively and correpond
- // to abreviations used in UBA spec: http://unicode.org/reports/tr9/#BD7
- Iterator m_sor; // Points to the first character in the current run.
- Iterator m_eor; // Points to the last character in the current run.
- Iterator m_last;
- BidiStatus m_status;
- WTF::Unicode::Direction m_direction;
- Iterator endOfLine;
- bool m_reachedEndOfLine;
- Iterator m_lastBeforeET; // Before a EuropeanNumberTerminator
- bool m_emptyRun;
-
- // FIXME: This should not belong to the resolver, but rather be passed
- // into createBidiRunsForLine by the caller.
- BidiRunList<Run> m_runs;
-
- MidpointState<Iterator> m_midpointState;
-
- unsigned m_nestedIsolateCount;
- Vector<Run*> m_isolatedRuns;
-
-private:
- void raiseExplicitEmbeddingLevel(WTF::Unicode::Direction from, WTF::Unicode::Direction to);
- void lowerExplicitEmbeddingLevel(WTF::Unicode::Direction from);
- void checkDirectionInLowerRaiseEmbeddingLevel();
-
- void updateStatusLastFromCurrentDirection(WTF::Unicode::Direction);
- void reorderRunsFromLevels();
-
- Vector<BidiEmbedding, 8> m_currentExplicitEmbeddingSequence;
-};
-
-#ifndef NDEBUG
-template <class Iterator, class Run>
-BidiResolver<Iterator, Run>::~BidiResolver()
-{
- // The owner of this resolver should have handled the isolated runs.
- ASSERT(m_isolatedRuns.isEmpty());
-}
-#endif
-
-template <class Iterator, class Run>
-void BidiResolver<Iterator, Run>::appendRun()
-{
- if (!m_emptyRun && !m_eor.atEnd()) {
- unsigned startOffset = m_sor.offset();
- unsigned endOffset = m_eor.offset();
-
- if (!endOfLine.atEnd() && endOffset >= endOfLine.offset()) {
- m_reachedEndOfLine = true;
- endOffset = endOfLine.offset();
- }
-
- if (endOffset >= startOffset)
- m_runs.addRun(new Run(startOffset, endOffset + 1, context(), m_direction));
-
- m_eor.increment();
- m_sor = m_eor;
- }
-
- m_direction = WTF::Unicode::OtherNeutral;
- m_status.eor = WTF::Unicode::OtherNeutral;
-}
-
-template <class Iterator, class Run>
-void BidiResolver<Iterator, Run>::embed(WTF::Unicode::Direction dir, BidiEmbeddingSource source)
-{
- // Isolated spans compute base directionality during their own UBA run.
- // Do not insert fake embed characters once we enter an isolated span.
- ASSERT(!inIsolate());
- using namespace WTF::Unicode;
-
- ASSERT(dir == PopDirectionalFormat || dir == LeftToRightEmbedding || dir == LeftToRightOverride || dir == RightToLeftEmbedding || dir == RightToLeftOverride);
- m_currentExplicitEmbeddingSequence.append(BidiEmbedding(dir, source));
-}
-
-template <class Iterator, class Run>
-void BidiResolver<Iterator, Run>::checkDirectionInLowerRaiseEmbeddingLevel()
-{
- using namespace WTF::Unicode;
-
- ASSERT(m_status.eor != OtherNeutral || m_eor.atEnd());
- ASSERT(m_status.last != NonSpacingMark
- && m_status.last != BoundaryNeutral
- && m_status.last != RightToLeftEmbedding
- && m_status.last != LeftToRightEmbedding
- && m_status.last != RightToLeftOverride
- && m_status.last != LeftToRightOverride
- && m_status.last != PopDirectionalFormat);
- if (m_direction == OtherNeutral)
- m_direction = m_status.lastStrong == LeftToRight ? LeftToRight : RightToLeft;
-}
-
-template <class Iterator, class Run>
-void BidiResolver<Iterator, Run>::lowerExplicitEmbeddingLevel(WTF::Unicode::Direction from)
-{
- using namespace WTF::Unicode;
-
- if (!m_emptyRun && m_eor != m_last) {
- checkDirectionInLowerRaiseEmbeddingLevel();
- // bidi.sor ... bidi.eor ... bidi.last eor; need to append the bidi.sor-bidi.eor run or extend it through bidi.last
- if (from == LeftToRight) {
- // bidi.sor ... bidi.eor ... bidi.last L
- if (m_status.eor == EuropeanNumber) {
- if (m_status.lastStrong != LeftToRight) {
- m_direction = EuropeanNumber;
- appendRun();
- }
- } else if (m_status.eor == ArabicNumber) {
- m_direction = ArabicNumber;
- appendRun();
- } else if (m_status.lastStrong != LeftToRight) {
- appendRun();
- m_direction = LeftToRight;
- }
- } else if (m_status.eor == EuropeanNumber || m_status.eor == ArabicNumber || m_status.lastStrong == LeftToRight) {
- appendRun();
- m_direction = RightToLeft;
- }
- m_eor = m_last;
- }
-
- appendRun();
- m_emptyRun = true;
-
- // sor for the new run is determined by the higher level (rule X10)
- setLastDir(from);
- setLastStrongDir(from);
- m_eor = Iterator();
-}
-
-template <class Iterator, class Run>
-void BidiResolver<Iterator, Run>::raiseExplicitEmbeddingLevel(WTF::Unicode::Direction from, WTF::Unicode::Direction to)
-{
- using namespace WTF::Unicode;
-
- if (!m_emptyRun && m_eor != m_last) {
- checkDirectionInLowerRaiseEmbeddingLevel();
- // bidi.sor ... bidi.eor ... bidi.last eor; need to append the bidi.sor-bidi.eor run or extend it through bidi.last
- if (to == LeftToRight) {
- // bidi.sor ... bidi.eor ... bidi.last L
- if (m_status.eor == EuropeanNumber) {
- if (m_status.lastStrong != LeftToRight) {
- m_direction = EuropeanNumber;
- appendRun();
- }
- } else if (m_status.eor == ArabicNumber) {
- m_direction = ArabicNumber;
- appendRun();
- } else if (m_status.lastStrong != LeftToRight && from == LeftToRight) {
- appendRun();
- m_direction = LeftToRight;
- }
- } else if (m_status.eor == ArabicNumber
- || (m_status.eor == EuropeanNumber && (m_status.lastStrong != LeftToRight || from == RightToLeft))
- || (m_status.eor != EuropeanNumber && m_status.lastStrong == LeftToRight && from == RightToLeft)) {
- appendRun();
- m_direction = RightToLeft;
- }
- m_eor = m_last;
- }
-
- appendRun();
- m_emptyRun = true;
-
- setLastDir(to);
- setLastStrongDir(to);
- m_eor = Iterator();
-}
-
-template <class Iterator, class Run>
-bool BidiResolver<Iterator, Run>::commitExplicitEmbedding()
-{
- // When we're "inIsolate()" we're resolving the parent context which
- // ignores (skips over) the isolated content, including embedding levels.
- // We should never accrue embedding levels while skipping over isolated content.
- ASSERT(!inIsolate() || m_currentExplicitEmbeddingSequence.isEmpty());
-
- using namespace WTF::Unicode;
-
- unsigned char fromLevel = context()->level();
- RefPtr<BidiContext> toContext = context();
-
- for (size_t i = 0; i < m_currentExplicitEmbeddingSequence.size(); ++i) {
- BidiEmbedding embedding = m_currentExplicitEmbeddingSequence[i];
- if (embedding.direction() == PopDirectionalFormat) {
- if (BidiContext* parentContext = toContext->parent())
- toContext = parentContext;
- } else {
- Direction direction = (embedding.direction() == RightToLeftEmbedding || embedding.direction() == RightToLeftOverride) ? RightToLeft : LeftToRight;
- bool override = embedding.direction() == LeftToRightOverride || embedding.direction() == RightToLeftOverride;
- unsigned char level = toContext->level();
- if (direction == RightToLeft)
- level = nextGreaterOddLevel(level);
- else
- level = nextGreaterEvenLevel(level);
- if (level < 61)
- toContext = BidiContext::create(level, direction, override, embedding.source(), toContext.get());
- }
- }
-
- unsigned char toLevel = toContext->level();
-
- if (toLevel > fromLevel)
- raiseExplicitEmbeddingLevel(fromLevel % 2 ? RightToLeft : LeftToRight, toLevel % 2 ? RightToLeft : LeftToRight);
- else if (toLevel < fromLevel)
- lowerExplicitEmbeddingLevel(fromLevel % 2 ? RightToLeft : LeftToRight);
-
- setContext(toContext);
-
- m_currentExplicitEmbeddingSequence.clear();
-
- return fromLevel != toLevel;
-}
-
-template <class Iterator, class Run>
-inline void BidiResolver<Iterator, Run>::updateStatusLastFromCurrentDirection(WTF::Unicode::Direction dirCurrent)
-{
- using namespace WTF::Unicode;
- switch (dirCurrent) {
- case EuropeanNumberTerminator:
- if (m_status.last != EuropeanNumber)
- m_status.last = EuropeanNumberTerminator;
- break;
- case EuropeanNumberSeparator:
- case CommonNumberSeparator:
- case SegmentSeparator:
- case WhiteSpaceNeutral:
- case OtherNeutral:
- switch (m_status.last) {
- case LeftToRight:
- case RightToLeft:
- case RightToLeftArabic:
- case EuropeanNumber:
- case ArabicNumber:
- m_status.last = dirCurrent;
- break;
- default:
- m_status.last = OtherNeutral;
- }
- break;
- case NonSpacingMark:
- case BoundaryNeutral:
- case RightToLeftEmbedding:
- case LeftToRightEmbedding:
- case RightToLeftOverride:
- case LeftToRightOverride:
- case PopDirectionalFormat:
- // ignore these
- break;
- case EuropeanNumber:
- // fall through
- default:
- m_status.last = dirCurrent;
- }
-}
-
-template <class Iterator, class Run>
-inline void BidiResolver<Iterator, Run>::reorderRunsFromLevels()
-{
- unsigned char levelLow = 128;
- unsigned char levelHigh = 0;
- for (Run* run = m_runs.firstRun(); run; run = run->next()) {
- levelHigh = std::max(run->level(), levelHigh);
- levelLow = std::min(run->level(), levelLow);
- }
-
- // This implements reordering of the line (L2 according to Bidi spec):
- // http://unicode.org/reports/tr9/#L2
- // L2. From the highest level found in the text to the lowest odd level on each line,
- // reverse any contiguous sequence of characters that are at that level or higher.
-
- // Reversing is only done up to the lowest odd level.
- if (!(levelLow % 2))
- levelLow++;
-
- unsigned count = m_runs.runCount() - 1;
-
- while (levelHigh >= levelLow) {
- unsigned i = 0;
- Run* run = m_runs.firstRun();
- while (i < count) {
- for (;i < count && run && run->level() < levelHigh; i++)
- run = run->next();
- unsigned start = i;
- for (;i <= count && run && run->level() >= levelHigh; i++)
- run = run->next();
- unsigned end = i - 1;
- m_runs.reverseRuns(start, end);
- }
- levelHigh--;
- }
-}
-
-template <class Iterator, class Run>
-void BidiResolver<Iterator, Run>::createBidiRunsForLine(const Iterator& end, VisualDirectionOverride override, bool hardLineBreak)
-{
- using namespace WTF::Unicode;
-
- ASSERT(m_direction == OtherNeutral);
-
- if (override != NoVisualOverride) {
- m_emptyRun = false;
- m_sor = m_current;
- m_eor = Iterator();
- while (m_current != end && !m_current.atEnd()) {
- m_eor = m_current;
- increment();
- }
- m_direction = override == VisualLeftToRightOverride ? LeftToRight : RightToLeft;
- appendRun();
- m_runs.setLogicallyLastRun(m_runs.lastRun());
- if (override == VisualRightToLeftOverride)
- m_runs.reverseRuns(0, m_runs.runCount() - 1);
- return;
- }
-
- m_emptyRun = true;
-
- m_eor = Iterator();
-
- m_last = m_current;
- bool lastParagraphEnded = false;
- BidiResolver<Iterator, Run> stateAtEnd;
-
- while (true) {
- if (inIsolate() && m_emptyRun) {
- m_sor = m_current;
- m_emptyRun = false;
- }
-
- if (!lastParagraphEnded && isEndOfParagraph(end)) {
- if (m_emptyRun)
- break;
-
- stateAtEnd.m_status = m_status;
- stateAtEnd.m_sor = m_sor;
- stateAtEnd.m_eor = m_eor;
- stateAtEnd.m_last = m_last;
- stateAtEnd.m_reachedEndOfLine = m_reachedEndOfLine;
- stateAtEnd.m_lastBeforeET = m_lastBeforeET;
- stateAtEnd.m_emptyRun = m_emptyRun;
- endOfLine = m_last;
- lastParagraphEnded = true;
- }
- Direction dirCurrent;
- if (lastParagraphEnded && (hardLineBreak || m_current.atEnd())) {
- BidiContext* c = context();
- if (hardLineBreak) {
- // A deviation from the Unicode Bidi Algorithm in order to match
- // WinIE and user expectations: hard line breaks reset bidi state
- // coming from unicode bidi control characters, but not those from
- // DOM nodes with specified directionality
- stateAtEnd.setContext(c->copyStackRemovingUnicodeEmbeddingContexts());
-
- dirCurrent = stateAtEnd.context()->dir();
- stateAtEnd.setEorDir(dirCurrent);
- stateAtEnd.setLastDir(dirCurrent);
- stateAtEnd.setLastStrongDir(dirCurrent);
- } else {
- while (c->parent())
- c = c->parent();
- dirCurrent = c->dir();
- }
- } else {
- dirCurrent = m_current.direction();
- if (context()->override()
- && dirCurrent != RightToLeftEmbedding
- && dirCurrent != LeftToRightEmbedding
- && dirCurrent != RightToLeftOverride
- && dirCurrent != LeftToRightOverride
- && dirCurrent != PopDirectionalFormat)
- dirCurrent = context()->dir();
- else if (dirCurrent == NonSpacingMark)
- dirCurrent = m_status.last;
- }
-
- // We ignore all character directionality while in unicode-bidi: isolate spans.
- // We'll handle ordering the isolated characters in a second pass.
- if (inIsolate())
- dirCurrent = OtherNeutral;
-
- ASSERT(m_status.eor != OtherNeutral || m_eor.atEnd());
- switch (dirCurrent) {
-
- // embedding and overrides (X1-X9 in the Bidi specs)
- case RightToLeftEmbedding:
- case LeftToRightEmbedding:
- case RightToLeftOverride:
- case LeftToRightOverride:
- case PopDirectionalFormat:
- embed(dirCurrent, FromUnicode);
- commitExplicitEmbedding();
- break;
-
- // strong types
- case LeftToRight:
- switch(m_status.last) {
- case RightToLeft:
- case RightToLeftArabic:
- case EuropeanNumber:
- case ArabicNumber:
- if (m_status.last != EuropeanNumber || m_status.lastStrong != LeftToRight)
- appendRun();
- break;
- case LeftToRight:
- break;
- case EuropeanNumberSeparator:
- case EuropeanNumberTerminator:
- case CommonNumberSeparator:
- case BoundaryNeutral:
- case BlockSeparator:
- case SegmentSeparator:
- case WhiteSpaceNeutral:
- case OtherNeutral:
- if (m_status.eor == EuropeanNumber) {
- if (m_status.lastStrong != LeftToRight) {
- // the numbers need to be on a higher embedding level, so let's close that run
- m_direction = EuropeanNumber;
- appendRun();
- if (context()->dir() != LeftToRight) {
- // the neutrals take the embedding direction, which is R
- m_eor = m_last;
- m_direction = RightToLeft;
- appendRun();
- }
- }
- } else if (m_status.eor == ArabicNumber) {
- // Arabic numbers are always on a higher embedding level, so let's close that run
- m_direction = ArabicNumber;
- appendRun();
- if (context()->dir() != LeftToRight) {
- // the neutrals take the embedding direction, which is R
- m_eor = m_last;
- m_direction = RightToLeft;
- appendRun();
- }
- } else if (m_status.lastStrong != LeftToRight) {
- //last stuff takes embedding dir
- if (context()->dir() == RightToLeft) {
- m_eor = m_last;
- m_direction = RightToLeft;
- }
- appendRun();
- }
- default:
- break;
- }
- m_eor = m_current;
- m_status.eor = LeftToRight;
- m_status.lastStrong = LeftToRight;
- m_direction = LeftToRight;
- break;
- case RightToLeftArabic:
- case RightToLeft:
- switch (m_status.last) {
- case LeftToRight:
- case EuropeanNumber:
- case ArabicNumber:
- appendRun();
- case RightToLeft:
- case RightToLeftArabic:
- break;
- case EuropeanNumberSeparator:
- case EuropeanNumberTerminator:
- case CommonNumberSeparator:
- case BoundaryNeutral:
- case BlockSeparator:
- case SegmentSeparator:
- case WhiteSpaceNeutral:
- case OtherNeutral:
- if (m_status.eor == EuropeanNumber) {
- if (m_status.lastStrong == LeftToRight && context()->dir() == LeftToRight)
- m_eor = m_last;
- appendRun();
- } else if (m_status.eor == ArabicNumber)
- appendRun();
- else if (m_status.lastStrong == LeftToRight) {
- if (context()->dir() == LeftToRight)
- m_eor = m_last;
- appendRun();
- }
- default:
- break;
- }
- m_eor = m_current;
- m_status.eor = RightToLeft;
- m_status.lastStrong = dirCurrent;
- m_direction = RightToLeft;
- break;
-
- // weak types:
-
- case EuropeanNumber:
- if (m_status.lastStrong != RightToLeftArabic) {
- // if last strong was AL change EN to AN
- switch (m_status.last) {
- case EuropeanNumber:
- case LeftToRight:
- break;
- case RightToLeft:
- case RightToLeftArabic:
- case ArabicNumber:
- m_eor = m_last;
- appendRun();
- m_direction = EuropeanNumber;
- break;
- case EuropeanNumberSeparator:
- case CommonNumberSeparator:
- if (m_status.eor == EuropeanNumber)
- break;
- case EuropeanNumberTerminator:
- case BoundaryNeutral:
- case BlockSeparator:
- case SegmentSeparator:
- case WhiteSpaceNeutral:
- case OtherNeutral:
- if (m_status.eor == EuropeanNumber) {
- if (m_status.lastStrong == RightToLeft) {
- // ENs on both sides behave like Rs, so the neutrals should be R.
- // Terminate the EN run.
- appendRun();
- // Make an R run.
- m_eor = m_status.last == EuropeanNumberTerminator ? m_lastBeforeET : m_last;
- m_direction = RightToLeft;
- appendRun();
- // Begin a new EN run.
- m_direction = EuropeanNumber;
- }
- } else if (m_status.eor == ArabicNumber) {
- // Terminate the AN run.
- appendRun();
- if (m_status.lastStrong == RightToLeft || context()->dir() == RightToLeft) {
- // Make an R run.
- m_eor = m_status.last == EuropeanNumberTerminator ? m_lastBeforeET : m_last;
- m_direction = RightToLeft;
- appendRun();
- // Begin a new EN run.
- m_direction = EuropeanNumber;
- }
- } else if (m_status.lastStrong == RightToLeft) {
- // Extend the R run to include the neutrals.
- m_eor = m_status.last == EuropeanNumberTerminator ? m_lastBeforeET : m_last;
- m_direction = RightToLeft;
- appendRun();
- // Begin a new EN run.
- m_direction = EuropeanNumber;
- }
- default:
- break;
- }
- m_eor = m_current;
- m_status.eor = EuropeanNumber;
- if (m_direction == OtherNeutral)
- m_direction = LeftToRight;
- break;
- }
- case ArabicNumber:
- dirCurrent = ArabicNumber;
- switch (m_status.last) {
- case LeftToRight:
- if (context()->dir() == LeftToRight)
- appendRun();
- break;
- case ArabicNumber:
- break;
- case RightToLeft:
- case RightToLeftArabic:
- case EuropeanNumber:
- m_eor = m_last;
- appendRun();
- break;
- case CommonNumberSeparator:
- if (m_status.eor == ArabicNumber)
- break;
- case EuropeanNumberSeparator:
- case EuropeanNumberTerminator:
- case BoundaryNeutral:
- case BlockSeparator:
- case SegmentSeparator:
- case WhiteSpaceNeutral:
- case OtherNeutral:
- if (m_status.eor == ArabicNumber
- || (m_status.eor == EuropeanNumber && (m_status.lastStrong == RightToLeft || context()->dir() == RightToLeft))
- || (m_status.eor != EuropeanNumber && m_status.lastStrong == LeftToRight && context()->dir() == RightToLeft)) {
- // Terminate the run before the neutrals.
- appendRun();
- // Begin an R run for the neutrals.
- m_direction = RightToLeft;
- } else if (m_direction == OtherNeutral)
- m_direction = m_status.lastStrong == LeftToRight ? LeftToRight : RightToLeft;
- m_eor = m_last;
- appendRun();
- default:
- break;
- }
- m_eor = m_current;
- m_status.eor = ArabicNumber;
- if (m_direction == OtherNeutral)
- m_direction = ArabicNumber;
- break;
- case EuropeanNumberSeparator:
- case CommonNumberSeparator:
- break;
- case EuropeanNumberTerminator:
- if (m_status.last == EuropeanNumber) {
- dirCurrent = EuropeanNumber;
- m_eor = m_current;
- m_status.eor = dirCurrent;
- } else if (m_status.last != EuropeanNumberTerminator)
- m_lastBeforeET = m_emptyRun ? m_eor : m_last;
- break;
-
- // boundary neutrals should be ignored
- case BoundaryNeutral:
- if (m_eor == m_last)
- m_eor = m_current;
- break;
- // neutrals
- case BlockSeparator:
- // ### what do we do with newline and paragraph seperators that come to here?
- break;
- case SegmentSeparator:
- // ### implement rule L1
- break;
- case WhiteSpaceNeutral:
- break;
- case OtherNeutral:
- break;
- default:
- break;
- }
-
- if (lastParagraphEnded && m_eor == m_current) {
- if (!m_reachedEndOfLine) {
- m_eor = endOfLine;
- switch (m_status.eor) {
- case LeftToRight:
- case RightToLeft:
- case ArabicNumber:
- m_direction = m_status.eor;
- break;
- case EuropeanNumber:
- m_direction = m_status.lastStrong == LeftToRight ? LeftToRight : EuropeanNumber;
- break;
- default:
- ASSERT_NOT_REACHED();
- }
- appendRun();
- }
- m_current = end;
- m_status = stateAtEnd.m_status;
- m_sor = stateAtEnd.m_sor;
- m_eor = stateAtEnd.m_eor;
- m_last = stateAtEnd.m_last;
- m_reachedEndOfLine = stateAtEnd.m_reachedEndOfLine;
- m_lastBeforeET = stateAtEnd.m_lastBeforeET;
- m_emptyRun = stateAtEnd.m_emptyRun;
- m_direction = OtherNeutral;
- break;
- }
-
- updateStatusLastFromCurrentDirection(dirCurrent);
- m_last = m_current;
-
- if (m_emptyRun) {
- m_sor = m_current;
- m_emptyRun = false;
- }
-
- increment();
- if (!m_currentExplicitEmbeddingSequence.isEmpty()) {
- bool committed = commitExplicitEmbedding();
- if (committed && lastParagraphEnded) {
- m_current = end;
- m_status = stateAtEnd.m_status;
- m_sor = stateAtEnd.m_sor;
- m_eor = stateAtEnd.m_eor;
- m_last = stateAtEnd.m_last;
- m_reachedEndOfLine = stateAtEnd.m_reachedEndOfLine;
- m_lastBeforeET = stateAtEnd.m_lastBeforeET;
- m_emptyRun = stateAtEnd.m_emptyRun;
- m_direction = OtherNeutral;
- break;
- }
- }
- }
-
- m_runs.setLogicallyLastRun(m_runs.lastRun());
- reorderRunsFromLevels();
- endOfLine = Iterator();
-}
-
-} // namespace WebCore
-
-#endif // BidiResolver_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/text/BidiRunList.h b/chromium/third_party/WebKit/Source/core/platform/text/BidiRunList.h
deleted file mode 100644
index e4d701e0527..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/text/BidiRunList.h
+++ /dev/null
@@ -1,253 +0,0 @@
-/*
- * Copyright (C) 2000 Lars Knoll (knoll@kde.org)
- * Copyright (C) 2003, 2004, 2006, 2007, 2008 Apple Inc. All right reserved.
- * Copyright (C) 2011 Google, Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#ifndef BidiRunList_h
-#define BidiRunList_h
-
-#include "wtf/Noncopyable.h"
-
-namespace WebCore {
-
-template <class Run>
-class BidiRunList {
- WTF_MAKE_NONCOPYABLE(BidiRunList);
-public:
- BidiRunList()
- : m_firstRun(0)
- , m_lastRun(0)
- , m_logicallyLastRun(0)
- , m_runCount(0)
- {
- }
-
- // FIXME: Once BidiResolver no longer owns the BidiRunList,
- // then ~BidiRunList should call deleteRuns() automatically.
-
- Run* firstRun() const { return m_firstRun; }
- Run* lastRun() const { return m_lastRun; }
- Run* logicallyLastRun() const { return m_logicallyLastRun; }
- unsigned runCount() const { return m_runCount; }
-
- void addRun(Run*);
- void prependRun(Run*);
-
- void moveRunToEnd(Run*);
- void moveRunToBeginning(Run*);
-
- void deleteRuns();
- void reverseRuns(unsigned start, unsigned end);
- void reorderRunsFromLevels();
-
- void setLogicallyLastRun(Run* run) { m_logicallyLastRun = run; }
-
- void replaceRunWithRuns(Run* toReplace, BidiRunList<Run>& newRuns);
-
-private:
- void clearWithoutDestroyingRuns();
-
- Run* m_firstRun;
- Run* m_lastRun;
- Run* m_logicallyLastRun;
- unsigned m_runCount;
-};
-
-template <class Run>
-inline void BidiRunList<Run>::addRun(Run* run)
-{
- if (!m_firstRun)
- m_firstRun = run;
- else
- m_lastRun->m_next = run;
- m_lastRun = run;
- m_runCount++;
-}
-
-template <class Run>
-inline void BidiRunList<Run>::prependRun(Run* run)
-{
- ASSERT(!run->m_next);
-
- if (!m_lastRun)
- m_lastRun = run;
- else
- run->m_next = m_firstRun;
- m_firstRun = run;
- m_runCount++;
-}
-
-template <class Run>
-inline void BidiRunList<Run>::moveRunToEnd(Run* run)
-{
- ASSERT(m_firstRun);
- ASSERT(m_lastRun);
- ASSERT(run->m_next);
-
- Run* current = 0;
- Run* next = m_firstRun;
- while (next != run) {
- current = next;
- next = current->next();
- }
-
- if (!current)
- m_firstRun = run->next();
- else
- current->m_next = run->m_next;
-
- run->m_next = 0;
- m_lastRun->m_next = run;
- m_lastRun = run;
-}
-
-template <class Run>
-inline void BidiRunList<Run>::moveRunToBeginning(Run* run)
-{
- ASSERT(m_firstRun);
- ASSERT(m_lastRun);
- ASSERT(run != m_firstRun);
-
- Run* current = m_firstRun;
- Run* next = current->next();
- while (next != run) {
- current = next;
- next = current->next();
- }
-
- current->m_next = run->m_next;
- if (run == m_lastRun)
- m_lastRun = current;
-
- run->m_next = m_firstRun;
- m_firstRun = run;
-}
-
-template <class Run>
-void BidiRunList<Run>::replaceRunWithRuns(Run* toReplace, BidiRunList<Run>& newRuns)
-{
- ASSERT(newRuns.runCount());
- ASSERT(m_firstRun);
- ASSERT(toReplace);
-
- if (m_firstRun == toReplace)
- m_firstRun = newRuns.firstRun();
- else {
- // Find the run just before "toReplace" in the list of runs.
- Run* previousRun = m_firstRun;
- while (previousRun->next() != toReplace)
- previousRun = previousRun->next();
- ASSERT(previousRun);
- previousRun->setNext(newRuns.firstRun());
- }
-
- newRuns.lastRun()->setNext(toReplace->next());
-
- // Fix up any of other pointers which may now be stale.
- if (m_lastRun == toReplace)
- m_lastRun = newRuns.lastRun();
- if (m_logicallyLastRun == toReplace)
- m_logicallyLastRun = newRuns.logicallyLastRun();
- m_runCount += newRuns.runCount() - 1; // We added the new runs and removed toReplace.
-
- delete toReplace;
- newRuns.clearWithoutDestroyingRuns();
-}
-
-template <class Run>
-void BidiRunList<Run>::clearWithoutDestroyingRuns()
-{
- m_firstRun = 0;
- m_lastRun = 0;
- m_logicallyLastRun = 0;
- m_runCount = 0;
-}
-
-template <class Run>
-void BidiRunList<Run>::deleteRuns()
-{
- if (!m_firstRun)
- return;
-
- Run* curr = m_firstRun;
- while (curr) {
- Run* s = curr->next();
- delete curr;
- curr = s;
- }
-
- m_firstRun = 0;
- m_lastRun = 0;
- m_runCount = 0;
-}
-
-template <class Run>
-void BidiRunList<Run>::reverseRuns(unsigned start, unsigned end)
-{
- if (start >= end)
- return;
-
- ASSERT(end < m_runCount);
-
- // Get the item before the start of the runs to reverse and put it in
- // |beforeStart|. |curr| should point to the first run to reverse.
- Run* curr = m_firstRun;
- Run* beforeStart = 0;
- unsigned i = 0;
- while (i < start) {
- i++;
- beforeStart = curr;
- curr = curr->next();
- }
-
- Run* startRun = curr;
- while (i < end) {
- i++;
- curr = curr->next();
- }
- Run* endRun = curr;
- Run* afterEnd = curr->next();
-
- i = start;
- curr = startRun;
- Run* newNext = afterEnd;
- while (i <= end) {
- // Do the reversal.
- Run* next = curr->next();
- curr->m_next = newNext;
- newNext = curr;
- curr = next;
- i++;
- }
-
- // Now hook up beforeStart and afterEnd to the startRun and endRun.
- if (beforeStart)
- beforeStart->m_next = endRun;
- else
- m_firstRun = endRun;
-
- startRun->m_next = afterEnd;
- if (!afterEnd)
- m_lastRun = startRun;
-}
-
-} // namespace WebCore
-
-#endif // BidiRunList
diff --git a/chromium/third_party/WebKit/Source/core/platform/text/DateTimeFormat.cpp b/chromium/third_party/WebKit/Source/core/platform/text/DateTimeFormat.cpp
deleted file mode 100644
index 0a02cdc0bdb..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/text/DateTimeFormat.cpp
+++ /dev/null
@@ -1,279 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
- * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/text/DateTimeFormat.h"
-
-#include "wtf/ASCIICType.h"
-#include "wtf/text/StringBuilder.h"
-
-namespace WebCore {
-
-static const DateTimeFormat::FieldType lowerCaseToFieldTypeMap[26] = {
- DateTimeFormat::FieldTypePeriod, // a
- DateTimeFormat::FieldTypeInvalid, // b
- DateTimeFormat::FieldTypeLocalDayOfWeekStandAlon, // c
- DateTimeFormat::FieldTypeDayOfMonth, // d
- DateTimeFormat::FieldTypeLocalDayOfWeek, // e
- DateTimeFormat::FieldTypeInvalid, // f
- DateTimeFormat::FieldTypeModifiedJulianDay, // g
- DateTimeFormat::FieldTypeHour12, // h
- DateTimeFormat::FieldTypeInvalid, // i
- DateTimeFormat::FieldTypeInvalid, // j
- DateTimeFormat::FieldTypeHour24, // k
- DateTimeFormat::FieldTypeInvalid, // l
- DateTimeFormat::FieldTypeMinute, // m
- DateTimeFormat::FieldTypeInvalid, // n
- DateTimeFormat::FieldTypeInvalid, // o
- DateTimeFormat::FieldTypeInvalid, // p
- DateTimeFormat::FieldTypeQuaterStandAlone, // q
- DateTimeFormat::FieldTypeInvalid, // r
- DateTimeFormat::FieldTypeSecond, // s
- DateTimeFormat::FieldTypeInvalid, // t
- DateTimeFormat::FieldTypeExtendedYear, // u
- DateTimeFormat::FieldTypeNonLocationZone, // v
- DateTimeFormat::FieldTypeWeekOfYear, // w
- DateTimeFormat::FieldTypeInvalid, // x
- DateTimeFormat::FieldTypeYear, // y
- DateTimeFormat::FieldTypeZone, // z
-};
-
-static const DateTimeFormat::FieldType upperCaseToFieldTypeMap[26] = {
- DateTimeFormat::FieldTypeMillisecondsInDay, // A
- DateTimeFormat::FieldTypeInvalid, // B
- DateTimeFormat::FieldTypeInvalid, // C
- DateTimeFormat::FieldTypeDayOfYear, // D
- DateTimeFormat::FieldTypeDayOfWeek, // E
- DateTimeFormat::FieldTypeDayOfWeekInMonth, // F
- DateTimeFormat::FieldTypeEra, // G
- DateTimeFormat::FieldTypeHour23, // H
- DateTimeFormat::FieldTypeInvalid, // I
- DateTimeFormat::FieldTypeInvalid, // J
- DateTimeFormat::FieldTypeHour11, // K
- DateTimeFormat::FieldTypeMonthStandAlone, // L
- DateTimeFormat::FieldTypeMonth, // M
- DateTimeFormat::FieldTypeInvalid, // N
- DateTimeFormat::FieldTypeInvalid, // O
- DateTimeFormat::FieldTypeInvalid, // P
- DateTimeFormat::FieldTypeQuater, // Q
- DateTimeFormat::FieldTypeInvalid, // R
- DateTimeFormat::FieldTypeFractionalSecond, // S
- DateTimeFormat::FieldTypeInvalid, // T
- DateTimeFormat::FieldTypeInvalid, // U
- DateTimeFormat::FieldTypeInvalid, // V
- DateTimeFormat::FieldTypeWeekOfMonth, // W
- DateTimeFormat::FieldTypeInvalid, // X
- DateTimeFormat::FieldTypeYearOfWeekOfYear, // Y
- DateTimeFormat::FieldTypeRFC822Zone, // Z
-};
-
-static DateTimeFormat::FieldType mapCharacterToFieldType(const UChar ch)
-{
- if (isASCIIUpper(ch))
- return upperCaseToFieldTypeMap[ch - 'A'];
-
- if (isASCIILower(ch))
- return lowerCaseToFieldTypeMap[ch - 'a'];
-
- return DateTimeFormat::FieldTypeLiteral;
-}
-
-bool DateTimeFormat::parse(const String& source, TokenHandler& tokenHandler)
-{
- enum State {
- StateInQuote,
- StateInQuoteQuote,
- StateLiteral,
- StateQuote,
- StateSymbol,
- } state = StateLiteral;
-
- FieldType fieldType = FieldTypeLiteral;
- StringBuilder literalBuffer;
- int fieldCounter = 0;
-
- for (unsigned int index = 0; index < source.length(); ++index) {
- const UChar ch = source[index];
- switch (state) {
- case StateInQuote:
- if (ch == '\'') {
- state = StateInQuoteQuote;
- break;
- }
-
- literalBuffer.append(ch);
- break;
-
- case StateInQuoteQuote:
- if (ch == '\'') {
- literalBuffer.append('\'');
- state = StateInQuote;
- break;
- }
-
- fieldType = mapCharacterToFieldType(ch);
- if (fieldType == FieldTypeInvalid)
- return false;
-
- if (fieldType == FieldTypeLiteral) {
- literalBuffer.append(ch);
- state = StateLiteral;
- break;
- }
-
- if (literalBuffer.length()) {
- tokenHandler.visitLiteral(literalBuffer.toString());
- literalBuffer.clear();
- }
-
- fieldCounter = 1;
- state = StateSymbol;
- break;
-
- case StateLiteral:
- if (ch == '\'') {
- state = StateQuote;
- break;
- }
-
- fieldType = mapCharacterToFieldType(ch);
- if (fieldType == FieldTypeInvalid)
- return false;
-
- if (fieldType == FieldTypeLiteral) {
- literalBuffer.append(ch);
- break;
- }
-
- if (literalBuffer.length()) {
- tokenHandler.visitLiteral(literalBuffer.toString());
- literalBuffer.clear();
- }
-
- fieldCounter = 1;
- state = StateSymbol;
- break;
-
- case StateQuote:
- literalBuffer.append(ch);
- state = ch == '\'' ? StateLiteral : StateInQuote;
- break;
-
- case StateSymbol: {
- ASSERT(fieldType != FieldTypeInvalid);
- ASSERT(fieldType != FieldTypeLiteral);
- ASSERT(literalBuffer.isEmpty());
-
- FieldType fieldType2 = mapCharacterToFieldType(ch);
- if (fieldType2 == FieldTypeInvalid)
- return false;
-
- if (fieldType == fieldType2) {
- ++fieldCounter;
- break;
- }
-
- tokenHandler.visitField(fieldType, fieldCounter);
-
- if (fieldType2 == FieldTypeLiteral) {
- if (ch == '\'')
- state = StateQuote;
- else {
- literalBuffer.append(ch);
- state = StateLiteral;
- }
- break;
- }
-
- fieldCounter = 1;
- fieldType = fieldType2;
- break;
- }
- }
- }
-
- ASSERT(fieldType != FieldTypeInvalid);
-
- switch (state) {
- case StateLiteral:
- case StateInQuoteQuote:
- if (literalBuffer.length())
- tokenHandler.visitLiteral(literalBuffer.toString());
- return true;
-
- case StateQuote:
- case StateInQuote:
- if (literalBuffer.length())
- tokenHandler.visitLiteral(literalBuffer.toString());
- return false;
-
- case StateSymbol:
- ASSERT(fieldType != FieldTypeLiteral);
- ASSERT(!literalBuffer.length());
- tokenHandler.visitField(fieldType, fieldCounter);
- return true;
- }
-
- ASSERT_NOT_REACHED();
- return false;
-}
-
-static bool isASCIIAlphabetOrQuote(UChar ch)
-{
- return isASCIIAlpha(ch) || ch == '\'';
-}
-
-void DateTimeFormat::quoteAndAppendLiteral(const String& literal, StringBuilder& buffer)
-{
- if (literal.length() <= 0)
- return;
-
- if (literal.find(isASCIIAlphabetOrQuote) == kNotFound) {
- buffer.append(literal);
- return;
- }
-
- if (literal.find('\'') == kNotFound) {
- buffer.append("'");
- buffer.append(literal);
- buffer.append("'");
- return;
- }
-
- for (unsigned i = 0; i < literal.length(); ++i) {
- if (literal[i] == '\'')
- buffer.append("''");
- else {
- String escaped = literal.substring(i);
- escaped.replace("'", "''");
- buffer.append("'");
- buffer.append(escaped);
- buffer.append("'");
- return;
- }
- }
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/text/DateTimeFormat.h b/chromium/third_party/WebKit/Source/core/platform/text/DateTimeFormat.h
deleted file mode 100644
index 729212a2704..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/text/DateTimeFormat.h
+++ /dev/null
@@ -1,110 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
- * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
- * DAMAGE.
- */
-
-#ifndef DateTimeFormat_h
-#define DateTimeFormat_h
-
-#include "wtf/Forward.h"
-
-namespace WebCore {
-
-// DateTimeFormat parses date time format defined in Unicode Technical
-// standard 35, Locale Data Markup Language (LDML)[1].
-// [1] LDML http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns
-class DateTimeFormat {
-public:
- enum FieldType {
- FieldTypeInvalid,
- FieldTypeLiteral,
-
- // Era: AD
- FieldTypeEra = 'G',
-
- // Year: 1996
- FieldTypeYear = 'y',
- FieldTypeYearOfWeekOfYear = 'Y',
- FieldTypeExtendedYear = 'u',
-
- // Quater: Q2
- FieldTypeQuater = 'Q',
- FieldTypeQuaterStandAlone = 'q',
-
- // Month: September
- FieldTypeMonth = 'M',
- FieldTypeMonthStandAlone = 'L',
-
- // Week: 42
- FieldTypeWeekOfYear = 'w',
- FieldTypeWeekOfMonth = 'W',
-
- // Day: 12
- FieldTypeDayOfMonth = 'd',
- FieldTypeDayOfYear = 'D',
- FieldTypeDayOfWeekInMonth = 'F',
- FieldTypeModifiedJulianDay = 'g',
-
- // Week Day: Tuesday
- FieldTypeDayOfWeek = 'E',
- FieldTypeLocalDayOfWeek = 'e',
- FieldTypeLocalDayOfWeekStandAlon = 'c',
-
- // Period: AM or PM
- FieldTypePeriod = 'a',
-
- // Hour: 7
- FieldTypeHour12 = 'h',
- FieldTypeHour23 = 'H',
- FieldTypeHour11 = 'K',
- FieldTypeHour24 = 'k',
-
- // Minute: 59
- FieldTypeMinute = 'm',
-
- // Second: 12
- FieldTypeSecond = 's',
- FieldTypeFractionalSecond = 'S',
- FieldTypeMillisecondsInDay = 'A',
-
- // Zone: PDT
- FieldTypeZone = 'z',
- FieldTypeRFC822Zone = 'Z',
- FieldTypeNonLocationZone = 'v',
- };
-
- class TokenHandler {
- public:
- virtual ~TokenHandler() { }
- virtual void visitField(FieldType, int numberOfPatternCharacters) = 0;
- virtual void visitLiteral(const String&) = 0;
- };
-
- // Returns true if succeeded, false if failed.
- static bool parse(const String&, TokenHandler&);
- static void quoteAndAppendLiteral(const String&, StringBuilder&);
-};
-
-} // namespace WebCore
-
-#endif // DateTimeFormat_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/text/DateTimeFormatTest.cpp b/chromium/third_party/WebKit/Source/core/platform/text/DateTimeFormatTest.cpp
deleted file mode 100644
index aeccc80250f..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/text/DateTimeFormatTest.cpp
+++ /dev/null
@@ -1,337 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
- * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/text/DateTimeFormat.h"
-
-#if ENABLE(INPUT_MULTIPLE_FIELDS_UI)
-#include "wtf/text/CString.h"
-#include "wtf/text/StringBuilder.h"
-#include <gtest/gtest.h>
-
-using namespace WebCore;
-
-class DateTimeFormatTest : public ::testing::Test {
-public:
- typedef DateTimeFormat::FieldType FieldType;
-
- struct Token {
- String string;
- int count;
- FieldType fieldType;
-
- Token(FieldType fieldType, int count = 1)
- : count(count)
- , fieldType(fieldType)
- {
- ASSERT(fieldType != DateTimeFormat::FieldTypeLiteral);
- }
-
- Token(const String& string)
- : string(string)
- , count(0)
- , fieldType(DateTimeFormat::FieldTypeLiteral)
- {
- }
-
- bool operator==(const Token& other) const
- {
- return fieldType == other.fieldType && count == other.count && string == other.string;
- }
-
- String toString() const
- {
- switch (fieldType) {
- case DateTimeFormat::FieldTypeInvalid:
- return "*invalid*";
- case DateTimeFormat::FieldTypeLiteral: {
- StringBuilder builder;
- builder.append('"');
- builder.append(string);
- builder.append('"');
- return builder.toString();
- }
- default:
- return String::format("Token(%d, %d)", fieldType, count);
- }
- }
- };
-
- class Tokens {
- public:
- Tokens() { }
-
- explicit Tokens(const Vector<Token> tokens)
- : m_tokens(tokens)
- {
- }
-
- explicit Tokens(const String& string)
- {
- m_tokens.append(Token(string));
- }
-
- explicit Tokens(Token token1)
- {
- m_tokens.append(token1);
- }
-
- Tokens(Token token1, Token token2)
- {
- m_tokens.append(token1);
- m_tokens.append(token2);
- }
-
- Tokens(Token token1, Token token2, Token token3)
- {
- m_tokens.append(token1);
- m_tokens.append(token2);
- m_tokens.append(token3);
- }
-
- Tokens(Token token1, Token token2, Token token3, Token token4)
- {
- m_tokens.append(token1);
- m_tokens.append(token2);
- m_tokens.append(token3);
- m_tokens.append(token4);
- }
-
- Tokens(Token token1, Token token2, Token token3, Token token4, Token token5)
- {
- m_tokens.append(token1);
- m_tokens.append(token2);
- m_tokens.append(token3);
- m_tokens.append(token4);
- m_tokens.append(token5);
- }
-
- Tokens(Token token1, Token token2, Token token3, Token token4, Token token5, Token token6)
- {
- m_tokens.append(token1);
- m_tokens.append(token2);
- m_tokens.append(token3);
- m_tokens.append(token4);
- m_tokens.append(token5);
- m_tokens.append(token6);
- }
-
- bool operator==(const Tokens& other) const
- {
- return m_tokens == other.m_tokens;
- }
-
- String toString() const
- {
- StringBuilder builder;
- builder.append("Tokens(");
- for (unsigned index = 0; index < m_tokens.size(); ++index) {
- if (index)
- builder.append(",");
- builder.append(m_tokens[index].toString());
- }
- builder.append(")");
- return builder.toString();
- }
-
- private:
- Vector<Token> m_tokens;
- };
-
-protected:
- Tokens parse(const String& formatString)
- {
- TokenHandler handler;
- if (!DateTimeFormat::parse(formatString, handler))
- return Tokens(Token("*failed*"));
- return handler.tokens();
- }
-
- FieldType single(const char ch)
- {
- char formatString[2];
- formatString[0] = ch;
- formatString[1] = 0;
- TokenHandler handler;
- if (!DateTimeFormat::parse(formatString, handler))
- return DateTimeFormat::FieldTypeInvalid;
- return handler.fieldType(0);
- }
-
-private:
- class TokenHandler : public DateTimeFormat::TokenHandler {
- public:
- virtual ~TokenHandler() { }
-
- FieldType fieldType(int index) const
- {
- return index >=0 && index < static_cast<int>(m_tokens.size()) ? m_tokens[index].fieldType : DateTimeFormat::FieldTypeInvalid;
- }
-
- Tokens tokens() const { return Tokens(m_tokens); }
-
- private:
- virtual void visitField(FieldType fieldType, int count) OVERRIDE
- {
- m_tokens.append(Token(fieldType, count));
- }
-
- virtual void visitLiteral(const String& string) OVERRIDE
- {
- m_tokens.append(Token(string));
- }
-
- Vector<Token> m_tokens;
- };
-};
-
-std::ostream& operator<<(std::ostream& os, const DateTimeFormatTest::Tokens& tokens)
-{
- return os << tokens.toString().ascii().data();
-}
-
-TEST_F(DateTimeFormatTest, CommonPattern)
-{
- EXPECT_EQ(Tokens(), parse(""));
-
- EXPECT_EQ(
- Tokens(
- Token(DateTimeFormat::FieldTypeYear, 4), Token("-"),
- Token(DateTimeFormat::FieldTypeMonth, 2), Token("-"),
- Token(DateTimeFormat::FieldTypeDayOfMonth, 2)),
- parse("yyyy-MM-dd"));
-
- EXPECT_EQ(
- Tokens(
- Token(DateTimeFormat::FieldTypeHour24, 2), Token(":"),
- Token(DateTimeFormat::FieldTypeMinute, 2), Token(":"),
- Token(DateTimeFormat::FieldTypeSecond, 2)),
- parse("kk:mm:ss"));
-
- EXPECT_EQ(
- Tokens(
- Token(DateTimeFormat::FieldTypeHour12), Token(":"),
- Token(DateTimeFormat::FieldTypeMinute), Token(" "),
- Token(DateTimeFormat::FieldTypePeriod)),
- parse("h:m a"));
-
- EXPECT_EQ(
- Tokens(
- Token(DateTimeFormat::FieldTypeYear), Token("Nen "),
- Token(DateTimeFormat::FieldTypeMonth), Token("Getsu "),
- Token(DateTimeFormat::FieldTypeDayOfMonth), Token("Nichi")),
- parse("y'Nen' M'Getsu' d'Nichi'"));
-}
-
-TEST_F(DateTimeFormatTest, MissingClosingQuote)
-{
- EXPECT_EQ(Tokens("*failed*"), parse("'foo"));
- EXPECT_EQ(Tokens("*failed*"), parse("fo'o"));
- EXPECT_EQ(Tokens("*failed*"), parse("foo'"));
-}
-
-TEST_F(DateTimeFormatTest, Quote)
-{
- EXPECT_EQ(Tokens("FooBar"), parse("'FooBar'"));
- EXPECT_EQ(Tokens("'"), parse("''"));
- EXPECT_EQ(Tokens("'-'"), parse("''-''"));
- EXPECT_EQ(Tokens("Foo'Bar"), parse("'Foo''Bar'"));
- EXPECT_EQ(
- Tokens(Token(DateTimeFormat::FieldTypeEra), Token("'s")),
- parse("G'''s'"));
- EXPECT_EQ(
- Tokens(Token(DateTimeFormat::FieldTypeEra), Token("'"), Token(DateTimeFormat::FieldTypeSecond)),
- parse("G''s"));
-}
-
-TEST_F(DateTimeFormatTest, SingleLowerCaseCharacter)
-{
- EXPECT_EQ(DateTimeFormat::FieldTypeInvalid, single('b'));
- EXPECT_EQ(DateTimeFormat::FieldTypeLocalDayOfWeekStandAlon, single('c'));
- EXPECT_EQ(DateTimeFormat::FieldTypeDayOfMonth, single('d'));
- EXPECT_EQ(DateTimeFormat::FieldTypeLocalDayOfWeek, single('e'));
- EXPECT_EQ(DateTimeFormat::FieldTypeModifiedJulianDay, single('g'));
- EXPECT_EQ(DateTimeFormat::FieldTypeHour12, single('h'));
- EXPECT_EQ(DateTimeFormat::FieldTypeHour24, single('k'));
- EXPECT_EQ(DateTimeFormat::FieldTypeMinute, single('m'));
- EXPECT_EQ(DateTimeFormat::FieldTypeQuaterStandAlone, single('q'));
- EXPECT_EQ(DateTimeFormat::FieldTypeSecond, single('s'));
- EXPECT_EQ(DateTimeFormat::FieldTypeExtendedYear, single('u'));
- EXPECT_EQ(DateTimeFormat::FieldTypeNonLocationZone, single('v'));
- EXPECT_EQ(DateTimeFormat::FieldTypeWeekOfMonth, single('W'));
- EXPECT_EQ(DateTimeFormat::FieldTypeYear, single('y'));
- EXPECT_EQ(DateTimeFormat::FieldTypeZone, single('z'));
-}
-
-TEST_F(DateTimeFormatTest, SingleLowerCaseInvalid)
-{
- EXPECT_EQ(DateTimeFormat::FieldTypePeriod, single('a'));
- EXPECT_EQ(DateTimeFormat::FieldTypeInvalid, single('f'));
- EXPECT_EQ(DateTimeFormat::FieldTypeInvalid, single('i'));
- EXPECT_EQ(DateTimeFormat::FieldTypeInvalid, single('j'));
- EXPECT_EQ(DateTimeFormat::FieldTypeInvalid, single('l'));
- EXPECT_EQ(DateTimeFormat::FieldTypeInvalid, single('n'));
- EXPECT_EQ(DateTimeFormat::FieldTypeInvalid, single('o'));
- EXPECT_EQ(DateTimeFormat::FieldTypeInvalid, single('p'));
- EXPECT_EQ(DateTimeFormat::FieldTypeInvalid, single('r'));
- EXPECT_EQ(DateTimeFormat::FieldTypeInvalid, single('t'));
- EXPECT_EQ(DateTimeFormat::FieldTypeInvalid, single('x'));
-}
-
-TEST_F(DateTimeFormatTest, SingleUpperCaseCharacter)
-{
- EXPECT_EQ(DateTimeFormat::FieldTypeMillisecondsInDay, single('A'));
- EXPECT_EQ(DateTimeFormat::FieldTypeDayOfYear, single('D'));
- EXPECT_EQ(DateTimeFormat::FieldTypeDayOfWeek, single('E'));
- EXPECT_EQ(DateTimeFormat::FieldTypeDayOfWeekInMonth, single('F'));
- EXPECT_EQ(DateTimeFormat::FieldTypeEra, single('G'));
- EXPECT_EQ(DateTimeFormat::FieldTypeHour23, single('H'));
- EXPECT_EQ(DateTimeFormat::FieldTypeHour11, single('K'));
- EXPECT_EQ(DateTimeFormat::FieldTypeMonthStandAlone, single('L'));
- EXPECT_EQ(DateTimeFormat::FieldTypeMonth, single('M'));
- EXPECT_EQ(DateTimeFormat::FieldTypeQuater, single('Q'));
- EXPECT_EQ(DateTimeFormat::FieldTypeFractionalSecond, single('S'));
- EXPECT_EQ(DateTimeFormat::FieldTypeWeekOfYear, single('w'));
- EXPECT_EQ(DateTimeFormat::FieldTypeYearOfWeekOfYear, single('Y'));
- EXPECT_EQ(DateTimeFormat::FieldTypeRFC822Zone, single('Z'));
-}
-
-TEST_F(DateTimeFormatTest, SingleUpperCaseInvalid)
-{
- EXPECT_EQ(DateTimeFormat::FieldTypeInvalid, single('B'));
- EXPECT_EQ(DateTimeFormat::FieldTypeInvalid, single('C'));
- EXPECT_EQ(DateTimeFormat::FieldTypeInvalid, single('I'));
- EXPECT_EQ(DateTimeFormat::FieldTypeInvalid, single('J'));
- EXPECT_EQ(DateTimeFormat::FieldTypeInvalid, single('N'));
- EXPECT_EQ(DateTimeFormat::FieldTypeInvalid, single('O'));
- EXPECT_EQ(DateTimeFormat::FieldTypeInvalid, single('P'));
- EXPECT_EQ(DateTimeFormat::FieldTypeInvalid, single('R'));
- EXPECT_EQ(DateTimeFormat::FieldTypeInvalid, single('T'));
- EXPECT_EQ(DateTimeFormat::FieldTypeInvalid, single('U'));
- EXPECT_EQ(DateTimeFormat::FieldTypeInvalid, single('V'));
- EXPECT_EQ(DateTimeFormat::FieldTypeInvalid, single('X'));
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/text/DecodeEscapeSequences.h b/chromium/third_party/WebKit/Source/core/platform/text/DecodeEscapeSequences.h
deleted file mode 100644
index 81b43e3c388..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/text/DecodeEscapeSequences.h
+++ /dev/null
@@ -1,158 +0,0 @@
-/*
- * Copyright (C) 2011 Daniel Bates (dbates@intudata.com). All Rights Reserved.
- * Copyright (c) 2012 Google, inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef DecodeEscapeSequences_h
-#define DecodeEscapeSequences_h
-
-#include "wtf/ASCIICType.h"
-#include "wtf/Assertions.h"
-#include "wtf/text/StringBuilder.h"
-#include "wtf/text/TextEncoding.h"
-
-namespace WebCore {
-
-// See <http://en.wikipedia.org/wiki/Percent-encoding#Non-standard_implementations>.
-struct Unicode16BitEscapeSequence {
- enum { sequenceSize = 6 }; // e.g. %u26C4
- static size_t findInString(const String& string, size_t startPosition) { return string.find("%u", startPosition); }
- static size_t findEndOfRun(const String& string, size_t startPosition, size_t endPosition)
- {
- size_t runEnd = startPosition;
- while (endPosition - runEnd >= sequenceSize && string[runEnd] == '%' && string[runEnd + 1] == 'u'
- && isASCIIHexDigit(string[runEnd + 2]) && isASCIIHexDigit(string[runEnd + 3])
- && isASCIIHexDigit(string[runEnd + 4]) && isASCIIHexDigit(string[runEnd + 5])) {
- runEnd += sequenceSize;
- }
- return runEnd;
- }
-
- template<typename CharType>
- static String decodeRun(const CharType* run, size_t runLength, const WTF::TextEncoding&)
- {
- // Each %u-escape sequence represents a UTF-16 code unit.
- // See <http://www.w3.org/International/iri-edit/draft-duerst-iri.html#anchor29>.
- // For 16-bit escape sequences, we know that findEndOfRun() has given us a contiguous run of sequences
- // without any intervening characters, so decode the run without additional checks.
- size_t numberOfSequences = runLength / sequenceSize;
- StringBuilder builder;
- builder.reserveCapacity(numberOfSequences);
- while (numberOfSequences--) {
- UChar codeUnit = (toASCIIHexValue(run[2]) << 12) | (toASCIIHexValue(run[3]) << 8) | (toASCIIHexValue(run[4]) << 4) | toASCIIHexValue(run[5]);
- builder.append(codeUnit);
- run += sequenceSize;
- }
- return builder.toString();
- }
-};
-
-struct URLEscapeSequence {
- enum { sequenceSize = 3 }; // e.g. %41
- static size_t findInString(const String& string, size_t startPosition) { return string.find('%', startPosition); }
- static size_t findEndOfRun(const String& string, size_t startPosition, size_t endPosition)
- {
- // Make the simplifying assumption that supported encodings may have up to two unescaped characters
- // in the range 0x40 - 0x7F as the trailing bytes of their sequences which need to be passed into the
- // decoder as part of the run. In other words, we end the run at the first value outside of the
- // 0x40 - 0x7F range, after two values in this range, or at a %-sign that does not introduce a valid
- // escape sequence.
- size_t runEnd = startPosition;
- int numberOfTrailingCharacters = 0;
- while (runEnd < endPosition) {
- if (string[runEnd] == '%') {
- if (endPosition - runEnd >= sequenceSize && isASCIIHexDigit(string[runEnd + 1]) && isASCIIHexDigit(string[runEnd + 2])) {
- runEnd += sequenceSize;
- numberOfTrailingCharacters = 0;
- } else
- break;
- } else if (string[runEnd] >= 0x40 && string[runEnd] <= 0x7F && numberOfTrailingCharacters < 2) {
- runEnd += 1;
- numberOfTrailingCharacters += 1;
- } else
- break;
- }
- return runEnd;
- }
-
- template<typename CharType>
- static String decodeRun(const CharType* run, size_t runLength, const WTF::TextEncoding& encoding)
- {
- // For URL escape sequences, we know that findEndOfRun() has given us a run where every %-sign introduces
- // a valid escape sequence, but there may be characters between the sequences.
- Vector<char, 512> buffer;
- buffer.resize(runLength); // Unescaping hex sequences only makes the length smaller.
- char* p = buffer.data();
- const CharType* runEnd = run + runLength;
- while (run < runEnd) {
- if (run[0] == '%') {
- *p++ = (toASCIIHexValue(run[1]) << 4) | toASCIIHexValue(run[2]);
- run += sequenceSize;
- } else {
- *p++ = run[0];
- run += 1;
- }
- }
- ASSERT(buffer.size() >= static_cast<size_t>(p - buffer.data())); // Prove buffer not overrun.
- return (encoding.isValid() ? encoding : UTF8Encoding()).decode(buffer.data(), p - buffer.data());
- }
-};
-
-template<typename EscapeSequence>
-String decodeEscapeSequences(const String& string, const WTF::TextEncoding& encoding)
-{
- StringBuilder result;
- size_t length = string.length();
- size_t decodedPosition = 0;
- size_t searchPosition = 0;
- size_t encodedRunPosition;
- while ((encodedRunPosition = EscapeSequence::findInString(string, searchPosition)) != kNotFound) {
- size_t encodedRunEnd = EscapeSequence::findEndOfRun(string, encodedRunPosition, length);
- searchPosition = encodedRunEnd;
- if (encodedRunEnd == encodedRunPosition) {
- ++searchPosition;
- continue;
- }
-
- String decoded = string.is8Bit() ?
- EscapeSequence::decodeRun(string.characters8() + encodedRunPosition, encodedRunEnd - encodedRunPosition, encoding) :
- EscapeSequence::decodeRun(string.characters16() + encodedRunPosition, encodedRunEnd - encodedRunPosition, encoding);
-
- if (decoded.isEmpty())
- continue;
-
- result.append(string, decodedPosition, encodedRunPosition - decodedPosition);
- result.append(decoded);
- decodedPosition = encodedRunEnd;
- }
- result.append(string, decodedPosition, length - decodedPosition);
- return result.toString();
-}
-
-} // namespace WebCore
-
-#endif // DecodeEscapeSequences_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/text/LineBreakIteratorPoolICU.h b/chromium/third_party/WebKit/Source/core/platform/text/LineBreakIteratorPoolICU.h
deleted file mode 100644
index b7a0f0b16be..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/text/LineBreakIteratorPoolICU.h
+++ /dev/null
@@ -1,111 +0,0 @@
-/*
- * Copyright (C) 2011 Apple Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef LineBreakIteratorPoolICU_h
-#define LineBreakIteratorPoolICU_h
-
-#include <unicode/ubrk.h>
-#include "core/platform/text/TextBreakIteratorInternalICU.h"
-#include "wtf/Assertions.h"
-#include "wtf/HashMap.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/text/AtomicString.h"
-#include "wtf/text/CString.h"
-#include "wtf/ThreadSpecific.h"
-
-namespace WebCore {
-
-class LineBreakIteratorPool {
- WTF_MAKE_NONCOPYABLE(LineBreakIteratorPool);
-public:
- static LineBreakIteratorPool& sharedPool()
- {
- static WTF::ThreadSpecific<LineBreakIteratorPool>* pool = new WTF::ThreadSpecific<LineBreakIteratorPool>;
- return **pool;
- }
-
- static PassOwnPtr<LineBreakIteratorPool> create() { return adoptPtr(new LineBreakIteratorPool); }
-
- UBreakIterator* take(const AtomicString& locale)
- {
- UBreakIterator* iterator = 0;
- for (size_t i = 0; i < m_pool.size(); ++i) {
- if (m_pool[i].first == locale) {
- iterator = m_pool[i].second;
- m_pool.remove(i);
- break;
- }
- }
-
- if (!iterator) {
- UErrorCode openStatus = U_ZERO_ERROR;
- bool localeIsEmpty = locale.isEmpty();
- iterator = ubrk_open(UBRK_LINE, localeIsEmpty ? currentTextBreakLocaleID() : locale.string().utf8().data(), 0, 0, &openStatus);
- // locale comes from a web page and it can be invalid, leading ICU
- // to fail, in which case we fall back to the default locale.
- if (!localeIsEmpty && U_FAILURE(openStatus)) {
- openStatus = U_ZERO_ERROR;
- iterator = ubrk_open(UBRK_LINE, currentTextBreakLocaleID(), 0, 0, &openStatus);
- }
-
- if (U_FAILURE(openStatus)) {
- LOG_ERROR("ubrk_open failed with status %d", openStatus);
- return 0;
- }
- }
-
- ASSERT(!m_vendedIterators.contains(iterator));
- m_vendedIterators.set(iterator, locale);
- return iterator;
- }
-
- void put(UBreakIterator* iterator)
- {
- ASSERT_ARG(iterator, m_vendedIterators.contains(iterator));
-
- if (m_pool.size() == capacity) {
- ubrk_close(m_pool[0].second);
- m_pool.remove(0);
- }
-
- m_pool.append(Entry(m_vendedIterators.take(iterator), iterator));
- }
-
-private:
- LineBreakIteratorPool() { }
-
- static const size_t capacity = 4;
-
- typedef pair<AtomicString, UBreakIterator*> Entry;
- typedef Vector<Entry, capacity> Pool;
- Pool m_pool;
- HashMap<UBreakIterator*, AtomicString> m_vendedIterators;
-
- friend WTF::ThreadSpecific<LineBreakIteratorPool>::operator LineBreakIteratorPool*();
-};
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/text/LineEnding.cpp b/chromium/third_party/WebKit/Source/core/platform/text/LineEnding.cpp
deleted file mode 100644
index a13de5d1613..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/text/LineEnding.cpp
+++ /dev/null
@@ -1,233 +0,0 @@
-/*
- * Copyright (C) 2005, 2006, 2008 Apple Inc. All rights reserved.
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/text/LineEnding.h"
-
-#include "wtf/text/CString.h"
-#include "wtf/text/WTFString.h"
-
-namespace {
-
-class OutputBuffer {
-public:
- virtual char* allocate(size_t size) = 0;
- virtual void copy(const CString&) = 0;
- virtual ~OutputBuffer() { }
-};
-
-class CStringBuffer : public OutputBuffer {
-public:
- CStringBuffer(CString& buffer)
- : m_buffer(buffer)
- {
- }
- virtual ~CStringBuffer() { }
-
- virtual char* allocate(size_t size)
- {
- char* ptr;
- m_buffer = CString::newUninitialized(size, ptr);
- return ptr;
- }
-
- virtual void copy(const CString& source)
- {
- m_buffer = source;
- }
-
- const CString& buffer() const { return m_buffer; }
-
-private:
- CString m_buffer;
-};
-
-class VectorCharAppendBuffer : public OutputBuffer {
-public:
- VectorCharAppendBuffer(Vector<char>& buffer)
- : m_buffer(buffer)
- {
- }
- virtual ~VectorCharAppendBuffer() { }
-
- virtual char* allocate(size_t size)
- {
- size_t oldSize = m_buffer.size();
- m_buffer.grow(oldSize + size);
- return m_buffer.data() + oldSize;
- }
-
- virtual void copy(const CString& source)
- {
- m_buffer.append(source.data(), source.length());
- }
-
-private:
- Vector<char>& m_buffer;
-};
-
-void internalNormalizeLineEndingsToCRLF(const CString& from, OutputBuffer& buffer)
-{
- // Compute the new length.
- size_t newLen = 0;
- const char* p = from.data();
- while (char c = *p++) {
- if (c == '\r') {
- // Safe to look ahead because of trailing '\0'.
- if (*p != '\n') {
- // Turn CR into CRLF.
- newLen += 2;
- }
- } else if (c == '\n') {
- // Turn LF into CRLF.
- newLen += 2;
- } else {
- // Leave other characters alone.
- newLen += 1;
- }
- }
- if (newLen < from.length())
- return;
-
- if (newLen == from.length()) {
- buffer.copy(from);
- return;
- }
-
- p = from.data();
- char* q = buffer.allocate(newLen);
-
- // Make a copy of the string.
- while (char c = *p++) {
- if (c == '\r') {
- // Safe to look ahead because of trailing '\0'.
- if (*p != '\n') {
- // Turn CR into CRLF.
- *q++ = '\r';
- *q++ = '\n';
- }
- } else if (c == '\n') {
- // Turn LF into CRLF.
- *q++ = '\r';
- *q++ = '\n';
- } else {
- // Leave other characters alone.
- *q++ = c;
- }
- }
-}
-
-};
-
-namespace WebCore {
-
-void normalizeToCROrLF(const CString& from, Vector<char>& result, bool toCR);
-
-// Normalize all line-endings to CR or LF.
-void normalizeToCROrLF(const CString& from, Vector<char>& result, bool toCR)
-{
- // Compute the new length.
- size_t newLen = 0;
- bool needFix = false;
- const char* p = from.data();
- char fromEndingChar = toCR ? '\n' : '\r';
- char toEndingChar = toCR ? '\r' : '\n';
- while (char c = *p++) {
- if (c == '\r' && *p == '\n') {
- // Turn CRLF into CR or LF.
- p++;
- needFix = true;
- } else if (c == fromEndingChar) {
- // Turn CR/LF into LF/CR.
- needFix = true;
- }
- newLen += 1;
- }
-
- // Grow the result buffer.
- p = from.data();
- size_t oldResultSize = result.size();
- result.grow(oldResultSize + newLen);
- char* q = result.data() + oldResultSize;
-
- // If no need to fix the string, just copy the string over.
- if (!needFix) {
- memcpy(q, p, from.length());
- return;
- }
-
- // Make a copy of the string.
- while (char c = *p++) {
- if (c == '\r' && *p == '\n') {
- // Turn CRLF or CR into CR or LF.
- p++;
- *q++ = toEndingChar;
- } else if (c == fromEndingChar) {
- // Turn CR/LF into LF/CR.
- *q++ = toEndingChar;
- } else {
- // Leave other characters alone.
- *q++ = c;
- }
- }
-}
-
-CString normalizeLineEndingsToCRLF(const CString& from)
-{
- if (!from.length())
- return from;
- CString result;
- CStringBuffer buffer(result);
- internalNormalizeLineEndingsToCRLF(from, buffer);
- return buffer.buffer();
-}
-
-void normalizeLineEndingsToCR(const CString& from, Vector<char>& result)
-{
- normalizeToCROrLF(from, result, true);
-}
-
-void normalizeLineEndingsToLF(const CString& from, Vector<char>& result)
-{
- normalizeToCROrLF(from, result, false);
-}
-
-void normalizeLineEndingsToNative(const CString& from, Vector<char>& result)
-{
-#if OS(WIN)
- VectorCharAppendBuffer buffer(result);
- internalNormalizeLineEndingsToCRLF(from, buffer);
-#else
- normalizeLineEndingsToLF(from, result);
-#endif
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/text/LineEnding.h b/chromium/third_party/WebKit/Source/core/platform/text/LineEnding.h
deleted file mode 100644
index e49912d0f4f..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/text/LineEnding.h
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Copyright (C) 2005, 2006, 2008 Apple Inc. All rights reserved.
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef LineEnding_h
-#define LineEnding_h
-
-#include "wtf/Forward.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-// Normalize all line-endings in the given string to CRLF.
-CString normalizeLineEndingsToCRLF(const CString& from);
-
-// Normalize all line-endings in the given string to CR and append the result to the given buffer.
-void normalizeLineEndingsToCR(const CString& from, Vector<char>& result);
-
-// Normalize all line-endings in the given string to LF and append the result to the given buffer.
-void normalizeLineEndingsToLF(const CString& from, Vector<char>& result);
-
-// Normalize all line-endings in the given string to the native line-endings and append the result to the given buffer.
-// (Normalize to CRLF on Windows and normalize to LF on all other platforms.)
-void normalizeLineEndingsToNative(const CString& from, Vector<char>& result);
-
-} // namespace WebCore
-
-#endif // LineEnding_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/text/LocaleICU.cpp b/chromium/third_party/WebKit/Source/core/platform/text/LocaleICU.cpp
deleted file mode 100644
index 7b5efcd142c..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/text/LocaleICU.cpp
+++ /dev/null
@@ -1,434 +0,0 @@
-/*
- * Copyright (C) 2011,2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/text/LocaleICU.h"
-
-#include <unicode/udatpg.h>
-#include <unicode/uloc.h>
-#include <limits>
-#include "wtf/DateMath.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/text/StringBuffer.h"
-#include "wtf/text/StringBuilder.h"
-
-using namespace icu;
-using namespace std;
-
-namespace WebCore {
-
-PassOwnPtr<Locale> Locale::create(const AtomicString& locale)
-{
- return LocaleICU::create(locale.string().utf8().data());
-}
-
-LocaleICU::LocaleICU(const char* locale)
- : m_locale(locale)
- , m_numberFormat(0)
- , m_shortDateFormat(0)
- , m_didCreateDecimalFormat(false)
- , m_didCreateShortDateFormat(false)
-#if ENABLE(CALENDAR_PICKER)
- , m_firstDayOfWeek(0)
-#endif
- , m_mediumTimeFormat(0)
- , m_shortTimeFormat(0)
- , m_didCreateTimeFormat(false)
-{
-}
-
-LocaleICU::~LocaleICU()
-{
- unum_close(m_numberFormat);
- udat_close(m_shortDateFormat);
- udat_close(m_mediumTimeFormat);
- udat_close(m_shortTimeFormat);
-}
-
-PassOwnPtr<LocaleICU> LocaleICU::create(const char* localeString)
-{
- return adoptPtr(new LocaleICU(localeString));
-}
-
-String LocaleICU::decimalSymbol(UNumberFormatSymbol symbol)
-{
- UErrorCode status = U_ZERO_ERROR;
- int32_t bufferLength = unum_getSymbol(m_numberFormat, symbol, 0, 0, &status);
- ASSERT(U_SUCCESS(status) || status == U_BUFFER_OVERFLOW_ERROR);
- if (U_FAILURE(status) && status != U_BUFFER_OVERFLOW_ERROR)
- return String();
- StringBuffer<UChar> buffer(bufferLength);
- status = U_ZERO_ERROR;
- unum_getSymbol(m_numberFormat, symbol, buffer.characters(), bufferLength, &status);
- if (U_FAILURE(status))
- return String();
- return String::adopt(buffer);
-}
-
-String LocaleICU::decimalTextAttribute(UNumberFormatTextAttribute tag)
-{
- UErrorCode status = U_ZERO_ERROR;
- int32_t bufferLength = unum_getTextAttribute(m_numberFormat, tag, 0, 0, &status);
- ASSERT(U_SUCCESS(status) || status == U_BUFFER_OVERFLOW_ERROR);
- if (U_FAILURE(status) && status != U_BUFFER_OVERFLOW_ERROR)
- return String();
- StringBuffer<UChar> buffer(bufferLength);
- status = U_ZERO_ERROR;
- unum_getTextAttribute(m_numberFormat, tag, buffer.characters(), bufferLength, &status);
- ASSERT(U_SUCCESS(status));
- if (U_FAILURE(status))
- return String();
- return String::adopt(buffer);
-}
-
-void LocaleICU::initializeLocaleData()
-{
- if (m_didCreateDecimalFormat)
- return;
- m_didCreateDecimalFormat = true;
- UErrorCode status = U_ZERO_ERROR;
- m_numberFormat = unum_open(UNUM_DECIMAL, 0, 0, m_locale.data(), 0, &status);
- if (!U_SUCCESS(status))
- return;
-
- Vector<String, DecimalSymbolsSize> symbols;
- symbols.append(decimalSymbol(UNUM_ZERO_DIGIT_SYMBOL));
- symbols.append(decimalSymbol(UNUM_ONE_DIGIT_SYMBOL));
- symbols.append(decimalSymbol(UNUM_TWO_DIGIT_SYMBOL));
- symbols.append(decimalSymbol(UNUM_THREE_DIGIT_SYMBOL));
- symbols.append(decimalSymbol(UNUM_FOUR_DIGIT_SYMBOL));
- symbols.append(decimalSymbol(UNUM_FIVE_DIGIT_SYMBOL));
- symbols.append(decimalSymbol(UNUM_SIX_DIGIT_SYMBOL));
- symbols.append(decimalSymbol(UNUM_SEVEN_DIGIT_SYMBOL));
- symbols.append(decimalSymbol(UNUM_EIGHT_DIGIT_SYMBOL));
- symbols.append(decimalSymbol(UNUM_NINE_DIGIT_SYMBOL));
- symbols.append(decimalSymbol(UNUM_DECIMAL_SEPARATOR_SYMBOL));
- symbols.append(decimalSymbol(UNUM_GROUPING_SEPARATOR_SYMBOL));
- ASSERT(symbols.size() == DecimalSymbolsSize);
- setLocaleData(symbols, decimalTextAttribute(UNUM_POSITIVE_PREFIX), decimalTextAttribute(UNUM_POSITIVE_SUFFIX), decimalTextAttribute(UNUM_NEGATIVE_PREFIX), decimalTextAttribute(UNUM_NEGATIVE_SUFFIX));
-}
-
-bool LocaleICU::initializeShortDateFormat()
-{
- if (m_didCreateShortDateFormat)
- return m_shortDateFormat;
- m_shortDateFormat = openDateFormat(UDAT_NONE, UDAT_SHORT);
- m_didCreateShortDateFormat = true;
- return m_shortDateFormat;
-}
-
-UDateFormat* LocaleICU::openDateFormat(UDateFormatStyle timeStyle, UDateFormatStyle dateStyle) const
-{
- const UChar gmtTimezone[3] = {'G', 'M', 'T'};
- UErrorCode status = U_ZERO_ERROR;
- return udat_open(timeStyle, dateStyle, m_locale.data(), gmtTimezone, WTF_ARRAY_LENGTH(gmtTimezone), 0, -1, &status);
-}
-
-static String getDateFormatPattern(const UDateFormat* dateFormat)
-{
- if (!dateFormat)
- return emptyString();
-
- UErrorCode status = U_ZERO_ERROR;
- int32_t length = udat_toPattern(dateFormat, TRUE, 0, 0, &status);
- if (status != U_BUFFER_OVERFLOW_ERROR || !length)
- return emptyString();
- StringBuffer<UChar> buffer(length);
- status = U_ZERO_ERROR;
- udat_toPattern(dateFormat, TRUE, buffer.characters(), length, &status);
- if (U_FAILURE(status))
- return emptyString();
- return String::adopt(buffer);
-}
-
-PassOwnPtr<Vector<String> > LocaleICU::createLabelVector(const UDateFormat* dateFormat, UDateFormatSymbolType type, int32_t startIndex, int32_t size)
-{
- if (!dateFormat)
- return PassOwnPtr<Vector<String> >();
- if (udat_countSymbols(dateFormat, type) != startIndex + size)
- return PassOwnPtr<Vector<String> >();
-
- OwnPtr<Vector<String> > labels = adoptPtr(new Vector<String>());
- labels->reserveCapacity(size);
- for (int32_t i = 0; i < size; ++i) {
- UErrorCode status = U_ZERO_ERROR;
- int32_t length = udat_getSymbols(dateFormat, type, startIndex + i, 0, 0, &status);
- if (status != U_BUFFER_OVERFLOW_ERROR)
- return PassOwnPtr<Vector<String> >();
- StringBuffer<UChar> buffer(length);
- status = U_ZERO_ERROR;
- udat_getSymbols(dateFormat, type, startIndex + i, buffer.characters(), length, &status);
- if (U_FAILURE(status))
- return PassOwnPtr<Vector<String> >();
- labels->append(String::adopt(buffer));
- }
- return labels.release();
-}
-
-#if ENABLE(CALENDAR_PICKER)
-static PassOwnPtr<Vector<String> > createFallbackWeekDayShortLabels()
-{
- OwnPtr<Vector<String> > labels = adoptPtr(new Vector<String>());
- labels->reserveCapacity(7);
- labels->append("Sun");
- labels->append("Mon");
- labels->append("Tue");
- labels->append("Wed");
- labels->append("Thu");
- labels->append("Fri");
- labels->append("Sat");
- return labels.release();
-}
-
-void LocaleICU::initializeCalendar()
-{
- if (m_weekDayShortLabels)
- return;
-
- if (!initializeShortDateFormat()) {
- m_firstDayOfWeek = 0;
- m_weekDayShortLabels = createFallbackWeekDayShortLabels();
- return;
- }
- m_firstDayOfWeek = ucal_getAttribute(udat_getCalendar(m_shortDateFormat), UCAL_FIRST_DAY_OF_WEEK) - UCAL_SUNDAY;
-
- m_weekDayShortLabels = createLabelVector(m_shortDateFormat, UDAT_SHORT_WEEKDAYS, UCAL_SUNDAY, 7);
- if (!m_weekDayShortLabels)
- m_weekDayShortLabels = createFallbackWeekDayShortLabels();
-}
-#endif
-
-static PassOwnPtr<Vector<String> > createFallbackMonthLabels()
-{
- OwnPtr<Vector<String> > labels = adoptPtr(new Vector<String>());
- labels->reserveCapacity(WTF_ARRAY_LENGTH(WTF::monthFullName));
- for (unsigned i = 0; i < WTF_ARRAY_LENGTH(WTF::monthFullName); ++i)
- labels->append(WTF::monthFullName[i]);
- return labels.release();
-}
-
-const Vector<String>& LocaleICU::monthLabels()
-{
- if (m_monthLabels)
- return *m_monthLabels;
- if (initializeShortDateFormat()) {
- m_monthLabels = createLabelVector(m_shortDateFormat, UDAT_MONTHS, UCAL_JANUARY, 12);
- if (m_monthLabels)
- return *m_monthLabels;
- }
- m_monthLabels = createFallbackMonthLabels();
- return *m_monthLabels;
-}
-
-#if ENABLE(CALENDAR_PICKER)
-const Vector<String>& LocaleICU::weekDayShortLabels()
-{
- initializeCalendar();
- return *m_weekDayShortLabels;
-}
-
-unsigned LocaleICU::firstDayOfWeek()
-{
- initializeCalendar();
- return m_firstDayOfWeek;
-}
-
-bool LocaleICU::isRTL()
-{
- UErrorCode status = U_ZERO_ERROR;
- return uloc_getCharacterOrientation(m_locale.data(), &status) == ULOC_LAYOUT_RTL;
-}
-#endif
-
-static PassOwnPtr<Vector<String> > createFallbackAMPMLabels()
-{
- OwnPtr<Vector<String> > labels = adoptPtr(new Vector<String>());
- labels->reserveCapacity(2);
- labels->append("AM");
- labels->append("PM");
- return labels.release();
-}
-
-void LocaleICU::initializeDateTimeFormat()
-{
- if (m_didCreateTimeFormat)
- return;
-
- // We assume ICU medium time pattern and short time pattern are compatible
- // with LDML, because ICU specific pattern character "V" doesn't appear
- // in both medium and short time pattern.
- m_mediumTimeFormat = openDateFormat(UDAT_MEDIUM, UDAT_NONE);
- m_timeFormatWithSeconds = getDateFormatPattern(m_mediumTimeFormat);
-
- m_shortTimeFormat = openDateFormat(UDAT_SHORT, UDAT_NONE);
- m_timeFormatWithoutSeconds = getDateFormatPattern(m_shortTimeFormat);
-
- UDateFormat* dateTimeFormatWithSeconds = openDateFormat(UDAT_MEDIUM, UDAT_SHORT);
- m_dateTimeFormatWithSeconds = getDateFormatPattern(dateTimeFormatWithSeconds);
- udat_close(dateTimeFormatWithSeconds);
-
- UDateFormat* dateTimeFormatWithoutSeconds = openDateFormat(UDAT_SHORT, UDAT_SHORT);
- m_dateTimeFormatWithoutSeconds = getDateFormatPattern(dateTimeFormatWithoutSeconds);
- udat_close(dateTimeFormatWithoutSeconds);
-
- OwnPtr<Vector<String> > timeAMPMLabels = createLabelVector(m_mediumTimeFormat, UDAT_AM_PMS, UCAL_AM, 2);
- if (!timeAMPMLabels)
- timeAMPMLabels = createFallbackAMPMLabels();
- m_timeAMPMLabels = *timeAMPMLabels;
-
- m_didCreateTimeFormat = true;
-}
-
-String LocaleICU::dateFormat()
-{
- if (!m_dateFormat.isNull())
- return m_dateFormat;
- if (!initializeShortDateFormat())
- return "yyyy-MM-dd";
- m_dateFormat = getDateFormatPattern(m_shortDateFormat);
- return m_dateFormat;
-}
-
-static String getFormatForSkeleton(const char* locale, const String& skeleton)
-{
- String format = "yyyy-MM";
- UErrorCode status = U_ZERO_ERROR;
- UDateTimePatternGenerator* patternGenerator = udatpg_open(locale, &status);
- if (!patternGenerator)
- return format;
- status = U_ZERO_ERROR;
- Vector<UChar> skeletonCharacters;
- skeleton.appendTo(skeletonCharacters);
- int32_t length = udatpg_getBestPattern(patternGenerator, skeletonCharacters.data(), skeletonCharacters.size(), 0, 0, &status);
- if (status == U_BUFFER_OVERFLOW_ERROR && length) {
- StringBuffer<UChar> buffer(length);
- status = U_ZERO_ERROR;
- udatpg_getBestPattern(patternGenerator, skeletonCharacters.data(), skeletonCharacters.size(), buffer.characters(), length, &status);
- if (U_SUCCESS(status))
- format = String::adopt(buffer);
- }
- udatpg_close(patternGenerator);
- return format;
-}
-
-String LocaleICU::monthFormat()
-{
- if (!m_monthFormat.isNull())
- return m_monthFormat;
- // Gets a format for "MMMM" because Windows API always provides formats for
- // "MMMM" in some locales.
- m_monthFormat = getFormatForSkeleton(m_locale.data(), "yyyyMMMM");
- return m_monthFormat;
-}
-
-String LocaleICU::shortMonthFormat()
-{
- if (!m_shortMonthFormat.isNull())
- return m_shortMonthFormat;
- m_shortMonthFormat = getFormatForSkeleton(m_locale.data(), "yyyyMMM");
- return m_shortMonthFormat;
-}
-
-String LocaleICU::timeFormat()
-{
- initializeDateTimeFormat();
- return m_timeFormatWithSeconds;
-}
-
-String LocaleICU::shortTimeFormat()
-{
- initializeDateTimeFormat();
- return m_timeFormatWithoutSeconds;
-}
-
-String LocaleICU::dateTimeFormatWithSeconds()
-{
- initializeDateTimeFormat();
- return m_dateTimeFormatWithSeconds;
-}
-
-String LocaleICU::dateTimeFormatWithoutSeconds()
-{
- initializeDateTimeFormat();
- return m_dateTimeFormatWithoutSeconds;
-}
-
-const Vector<String>& LocaleICU::shortMonthLabels()
-{
- if (!m_shortMonthLabels.isEmpty())
- return m_shortMonthLabels;
- if (initializeShortDateFormat()) {
- if (OwnPtr<Vector<String> > labels = createLabelVector(m_shortDateFormat, UDAT_SHORT_MONTHS, UCAL_JANUARY, 12)) {
- m_shortMonthLabels = *labels;
- return m_shortMonthLabels;
- }
- }
- m_shortMonthLabels.reserveCapacity(WTF_ARRAY_LENGTH(WTF::monthName));
- for (unsigned i = 0; i < WTF_ARRAY_LENGTH(WTF::monthName); ++i)
- m_shortMonthLabels.append(WTF::monthName[i]);
- return m_shortMonthLabels;
-}
-
-const Vector<String>& LocaleICU::standAloneMonthLabels()
-{
- if (!m_standAloneMonthLabels.isEmpty())
- return m_standAloneMonthLabels;
- if (initializeShortDateFormat()) {
- if (OwnPtr<Vector<String> > labels = createLabelVector(m_shortDateFormat, UDAT_STANDALONE_MONTHS, UCAL_JANUARY, 12)) {
- m_standAloneMonthLabels = *labels;
- return m_standAloneMonthLabels;
- }
- }
- m_standAloneMonthLabels = monthLabels();
- return m_standAloneMonthLabels;
-}
-
-const Vector<String>& LocaleICU::shortStandAloneMonthLabels()
-{
- if (!m_shortStandAloneMonthLabels.isEmpty())
- return m_shortStandAloneMonthLabels;
- if (initializeShortDateFormat()) {
- if (OwnPtr<Vector<String> > labels = createLabelVector(m_shortDateFormat, UDAT_STANDALONE_SHORT_MONTHS, UCAL_JANUARY, 12)) {
- m_shortStandAloneMonthLabels = *labels;
- return m_shortStandAloneMonthLabels;
- }
- }
- m_shortStandAloneMonthLabels = shortMonthLabels();
- return m_shortStandAloneMonthLabels;
-}
-
-const Vector<String>& LocaleICU::timeAMPMLabels()
-{
- initializeDateTimeFormat();
- return m_timeAMPMLabels;
-}
-
-} // namespace WebCore
-
diff --git a/chromium/third_party/WebKit/Source/core/platform/text/LocaleICU.h b/chromium/third_party/WebKit/Source/core/platform/text/LocaleICU.h
deleted file mode 100644
index 772992c955c..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/text/LocaleICU.h
+++ /dev/null
@@ -1,117 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef LocaleICU_h
-#define LocaleICU_h
-
-#include <unicode/udat.h>
-#include <unicode/unum.h>
-#include "core/platform/DateComponents.h"
-#include "core/platform/text/PlatformLocale.h"
-#include "wtf/Forward.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/text/CString.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-// We should use this class only for LocalizedNumberICU.cpp, LocalizedDateICU.cpp,
-// and LocalizedNumberICUTest.cpp.
-class LocaleICU : public Locale {
-public:
- static PassOwnPtr<LocaleICU> create(const char* localeString);
- virtual ~LocaleICU();
-
-#if ENABLE(CALENDAR_PICKER)
- virtual const Vector<String>& weekDayShortLabels() OVERRIDE;
- virtual unsigned firstDayOfWeek() OVERRIDE;
- virtual bool isRTL() OVERRIDE;
-#endif
- virtual String dateFormat() OVERRIDE;
- virtual String monthFormat() OVERRIDE;
- virtual String shortMonthFormat() OVERRIDE;
- virtual String timeFormat() OVERRIDE;
- virtual String shortTimeFormat() OVERRIDE;
- virtual String dateTimeFormatWithSeconds() OVERRIDE;
- virtual String dateTimeFormatWithoutSeconds() OVERRIDE;
- virtual const Vector<String>& monthLabels() OVERRIDE;
- virtual const Vector<String>& shortMonthLabels() OVERRIDE;
- virtual const Vector<String>& standAloneMonthLabels() OVERRIDE;
- virtual const Vector<String>& shortStandAloneMonthLabels() OVERRIDE;
- virtual const Vector<String>& timeAMPMLabels() OVERRIDE;
-
-private:
- explicit LocaleICU(const char*);
- String decimalSymbol(UNumberFormatSymbol);
- String decimalTextAttribute(UNumberFormatTextAttribute);
- virtual void initializeLocaleData() OVERRIDE;
-
- bool detectSignAndGetDigitRange(const String& input, bool& isNegative, unsigned& startIndex, unsigned& endIndex);
- unsigned matchedDecimalSymbolIndex(const String& input, unsigned& position);
-
- bool initializeShortDateFormat();
- UDateFormat* openDateFormat(UDateFormatStyle timeStyle, UDateFormatStyle dateStyle) const;
-
-#if ENABLE(CALENDAR_PICKER)
- void initializeCalendar();
-#endif
-
- PassOwnPtr<Vector<String> > createLabelVector(const UDateFormat*, UDateFormatSymbolType, int32_t startIndex, int32_t size);
- void initializeDateTimeFormat();
-
- CString m_locale;
- UNumberFormat* m_numberFormat;
- UDateFormat* m_shortDateFormat;
- bool m_didCreateDecimalFormat;
- bool m_didCreateShortDateFormat;
-
-#if ENABLE(CALENDAR_PICKER)
- OwnPtr<Vector<String> > m_weekDayShortLabels;
- unsigned m_firstDayOfWeek;
-#endif
- OwnPtr<Vector<String> > m_monthLabels;
- String m_dateFormat;
- String m_monthFormat;
- String m_shortMonthFormat;
- String m_timeFormatWithSeconds;
- String m_timeFormatWithoutSeconds;
- String m_dateTimeFormatWithSeconds;
- String m_dateTimeFormatWithoutSeconds;
- UDateFormat* m_mediumTimeFormat;
- UDateFormat* m_shortTimeFormat;
- Vector<String> m_shortMonthLabels;
- Vector<String> m_standAloneMonthLabels;
- Vector<String> m_shortStandAloneMonthLabels;
- Vector<String> m_timeAMPMLabels;
- bool m_didCreateTimeFormat;
-};
-
-} // namespace WebCore
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/text/LocaleToScriptMapping.h b/chromium/third_party/WebKit/Source/core/platform/text/LocaleToScriptMapping.h
deleted file mode 100644
index 2d270ecb5eb..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/text/LocaleToScriptMapping.h
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef LocaleToScriptMapping_h
-#define LocaleToScriptMapping_h
-
-#include "wtf/Forward.h"
-#include "wtf/unicode/Unicode.h"
-
-namespace WebCore {
-
-UScriptCode localeToScriptCodeForFontSelection(const String&);
-UScriptCode scriptNameToCode(const String&);
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/text/LocaleToScriptMappingDefault.cpp b/chromium/third_party/WebKit/Source/core/platform/text/LocaleToScriptMappingDefault.cpp
deleted file mode 100644
index 197d87a9966..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/text/LocaleToScriptMappingDefault.cpp
+++ /dev/null
@@ -1,404 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/text/LocaleToScriptMapping.h"
-
-#include "wtf/HashMap.h"
-#include "wtf/HashSet.h"
-#include "wtf/text/StringHash.h"
-
-namespace WebCore {
-
-UScriptCode scriptNameToCode(const String& scriptName)
-{
- struct ScriptNameCode {
- const char* name;
- UScriptCode code;
- };
-
- // This generally maps an ISO 15924 script code to its UScriptCode, but certain families of script codes are
- // treated as a single script for assigning a per-script font in Settings. For example, "hira" is mapped to
- // USCRIPT_KATAKANA_OR_HIRAGANA instead of USCRIPT_HIRAGANA, since we want all Japanese scripts to be rendered
- // using the same font setting.
- static const ScriptNameCode scriptNameCodeList[] = {
- { "zyyy", USCRIPT_COMMON },
- { "qaai", USCRIPT_INHERITED },
- { "arab", USCRIPT_ARABIC },
- { "armn", USCRIPT_ARMENIAN },
- { "beng", USCRIPT_BENGALI },
- { "bopo", USCRIPT_BOPOMOFO },
- { "cher", USCRIPT_CHEROKEE },
- { "copt", USCRIPT_COPTIC },
- { "cyrl", USCRIPT_CYRILLIC },
- { "dsrt", USCRIPT_DESERET },
- { "deva", USCRIPT_DEVANAGARI },
- { "ethi", USCRIPT_ETHIOPIC },
- { "geor", USCRIPT_GEORGIAN },
- { "goth", USCRIPT_GOTHIC },
- { "grek", USCRIPT_GREEK },
- { "gujr", USCRIPT_GUJARATI },
- { "guru", USCRIPT_GURMUKHI },
- { "hani", USCRIPT_HAN },
- { "hang", USCRIPT_HANGUL },
- { "hebr", USCRIPT_HEBREW },
- { "hira", USCRIPT_KATAKANA_OR_HIRAGANA },
- { "knda", USCRIPT_KANNADA },
- { "kana", USCRIPT_KATAKANA_OR_HIRAGANA },
- { "khmr", USCRIPT_KHMER },
- { "laoo", USCRIPT_LAO },
- { "latn", USCRIPT_LATIN },
- { "mlym", USCRIPT_MALAYALAM },
- { "mong", USCRIPT_MONGOLIAN },
- { "mymr", USCRIPT_MYANMAR },
- { "ogam", USCRIPT_OGHAM },
- { "ital", USCRIPT_OLD_ITALIC },
- { "orya", USCRIPT_ORIYA },
- { "runr", USCRIPT_RUNIC },
- { "sinh", USCRIPT_SINHALA },
- { "syrc", USCRIPT_SYRIAC },
- { "taml", USCRIPT_TAMIL },
- { "telu", USCRIPT_TELUGU },
- { "thaa", USCRIPT_THAANA },
- { "thai", USCRIPT_THAI },
- { "tibt", USCRIPT_TIBETAN },
- { "cans", USCRIPT_CANADIAN_ABORIGINAL },
- { "yiii", USCRIPT_YI },
- { "tglg", USCRIPT_TAGALOG },
- { "hano", USCRIPT_HANUNOO },
- { "buhd", USCRIPT_BUHID },
- { "tagb", USCRIPT_TAGBANWA },
- { "brai", USCRIPT_BRAILLE },
- { "cprt", USCRIPT_CYPRIOT },
- { "limb", USCRIPT_LIMBU },
- { "linb", USCRIPT_LINEAR_B },
- { "osma", USCRIPT_OSMANYA },
- { "shaw", USCRIPT_SHAVIAN },
- { "tale", USCRIPT_TAI_LE },
- { "ugar", USCRIPT_UGARITIC },
- { "hrkt", USCRIPT_KATAKANA_OR_HIRAGANA },
- { "bugi", USCRIPT_BUGINESE },
- { "glag", USCRIPT_GLAGOLITIC },
- { "khar", USCRIPT_KHAROSHTHI },
- { "sylo", USCRIPT_SYLOTI_NAGRI },
- { "talu", USCRIPT_NEW_TAI_LUE },
- { "tfng", USCRIPT_TIFINAGH },
- { "xpeo", USCRIPT_OLD_PERSIAN },
- { "bali", USCRIPT_BALINESE },
- { "batk", USCRIPT_BATAK },
- { "blis", USCRIPT_BLISSYMBOLS },
- { "brah", USCRIPT_BRAHMI },
- { "cham", USCRIPT_CHAM },
- { "cirt", USCRIPT_CIRTH },
- { "cyrs", USCRIPT_OLD_CHURCH_SLAVONIC_CYRILLIC },
- { "egyd", USCRIPT_DEMOTIC_EGYPTIAN },
- { "egyh", USCRIPT_HIERATIC_EGYPTIAN },
- { "egyp", USCRIPT_EGYPTIAN_HIEROGLYPHS },
- { "geok", USCRIPT_KHUTSURI },
- { "hans", USCRIPT_SIMPLIFIED_HAN },
- { "hant", USCRIPT_TRADITIONAL_HAN },
- { "hmng", USCRIPT_PAHAWH_HMONG },
- { "hung", USCRIPT_OLD_HUNGARIAN },
- { "inds", USCRIPT_HARAPPAN_INDUS },
- { "java", USCRIPT_JAVANESE },
- { "kali", USCRIPT_KAYAH_LI },
- { "latf", USCRIPT_LATIN_FRAKTUR },
- { "latg", USCRIPT_LATIN_GAELIC },
- { "lepc", USCRIPT_LEPCHA },
- { "lina", USCRIPT_LINEAR_A },
- { "mand", USCRIPT_MANDAEAN },
- { "maya", USCRIPT_MAYAN_HIEROGLYPHS },
- { "mero", USCRIPT_MEROITIC },
- { "nkoo", USCRIPT_NKO },
- { "orkh", USCRIPT_ORKHON },
- { "perm", USCRIPT_OLD_PERMIC },
- { "phag", USCRIPT_PHAGS_PA },
- { "phnx", USCRIPT_PHOENICIAN },
- { "plrd", USCRIPT_PHONETIC_POLLARD },
- { "roro", USCRIPT_RONGORONGO },
- { "sara", USCRIPT_SARATI },
- { "syre", USCRIPT_ESTRANGELO_SYRIAC },
- { "syrj", USCRIPT_WESTERN_SYRIAC },
- { "syrn", USCRIPT_EASTERN_SYRIAC },
- { "teng", USCRIPT_TENGWAR },
- { "vaii", USCRIPT_VAI },
- { "visp", USCRIPT_VISIBLE_SPEECH },
- { "xsux", USCRIPT_CUNEIFORM },
- { "jpan", USCRIPT_KATAKANA_OR_HIRAGANA },
- { "kore", USCRIPT_HANGUL },
- { "zxxx", USCRIPT_UNWRITTEN_LANGUAGES },
- { "zzzz", USCRIPT_UNKNOWN }
- };
-
- typedef HashMap<String, UScriptCode> ScriptNameCodeMap;
- DEFINE_STATIC_LOCAL(ScriptNameCodeMap, scriptNameCodeMap, ());
- if (scriptNameCodeMap.isEmpty()) {
- for (size_t i = 0; i < sizeof(scriptNameCodeList) / sizeof(scriptNameCodeList[0]); ++i)
- scriptNameCodeMap.set(scriptNameCodeList[i].name, scriptNameCodeList[i].code);
- }
-
- HashMap<String, UScriptCode>::iterator it = scriptNameCodeMap.find(scriptName.lower());
- if (it != scriptNameCodeMap.end())
- return it->value;
- return USCRIPT_INVALID_CODE;
-}
-
-UScriptCode localeToScriptCodeForFontSelection(const String& locale)
-{
- struct LocaleScript {
- const char* locale;
- UScriptCode script;
- };
-
- static const LocaleScript localeScriptList[] = {
- { "aa", USCRIPT_LATIN },
- { "ab", USCRIPT_CYRILLIC },
- { "ady", USCRIPT_CYRILLIC },
- { "af", USCRIPT_LATIN },
- { "ak", USCRIPT_LATIN },
- { "am", USCRIPT_ETHIOPIC },
- { "ar", USCRIPT_ARABIC },
- { "as", USCRIPT_BENGALI },
- { "ast", USCRIPT_LATIN },
- { "av", USCRIPT_CYRILLIC },
- { "ay", USCRIPT_LATIN },
- { "az", USCRIPT_LATIN },
- { "ba", USCRIPT_CYRILLIC },
- { "be", USCRIPT_CYRILLIC },
- { "bg", USCRIPT_CYRILLIC },
- { "bi", USCRIPT_LATIN },
- { "bn", USCRIPT_BENGALI },
- { "bo", USCRIPT_TIBETAN },
- { "bs", USCRIPT_LATIN },
- { "ca", USCRIPT_LATIN },
- { "ce", USCRIPT_CYRILLIC },
- { "ceb", USCRIPT_LATIN },
- { "ch", USCRIPT_LATIN },
- { "chk", USCRIPT_LATIN },
- { "cs", USCRIPT_LATIN },
- { "cy", USCRIPT_LATIN },
- { "da", USCRIPT_LATIN },
- { "de", USCRIPT_LATIN },
- { "dv", USCRIPT_THAANA },
- { "dz", USCRIPT_TIBETAN },
- { "ee", USCRIPT_LATIN },
- { "efi", USCRIPT_LATIN },
- { "el", USCRIPT_GREEK },
- { "en", USCRIPT_LATIN },
- { "es", USCRIPT_LATIN },
- { "et", USCRIPT_LATIN },
- { "eu", USCRIPT_LATIN },
- { "fa", USCRIPT_ARABIC },
- { "fi", USCRIPT_LATIN },
- { "fil", USCRIPT_LATIN },
- { "fj", USCRIPT_LATIN },
- { "fo", USCRIPT_LATIN },
- { "fr", USCRIPT_LATIN },
- { "fur", USCRIPT_LATIN },
- { "fy", USCRIPT_LATIN },
- { "ga", USCRIPT_LATIN },
- { "gaa", USCRIPT_LATIN },
- { "gd", USCRIPT_LATIN },
- { "gil", USCRIPT_LATIN },
- { "gl", USCRIPT_LATIN },
- { "gn", USCRIPT_LATIN },
- { "gsw", USCRIPT_LATIN },
- { "gu", USCRIPT_GUJARATI },
- { "ha", USCRIPT_LATIN },
- { "haw", USCRIPT_LATIN },
- { "he", USCRIPT_HEBREW },
- { "hi", USCRIPT_DEVANAGARI },
- { "hil", USCRIPT_LATIN },
- { "ho", USCRIPT_LATIN },
- { "hr", USCRIPT_LATIN },
- { "ht", USCRIPT_LATIN },
- { "hu", USCRIPT_LATIN },
- { "hy", USCRIPT_ARMENIAN },
- { "id", USCRIPT_LATIN },
- { "ig", USCRIPT_LATIN },
- { "ii", USCRIPT_YI },
- { "ilo", USCRIPT_LATIN },
- { "inh", USCRIPT_CYRILLIC },
- { "is", USCRIPT_LATIN },
- { "it", USCRIPT_LATIN },
- { "iu", USCRIPT_CANADIAN_ABORIGINAL },
- { "ja", USCRIPT_KATAKANA_OR_HIRAGANA },
- { "jv", USCRIPT_LATIN },
- { "ka", USCRIPT_GEORGIAN },
- { "kaj", USCRIPT_LATIN },
- { "kam", USCRIPT_LATIN },
- { "kbd", USCRIPT_CYRILLIC },
- { "kha", USCRIPT_LATIN },
- { "kk", USCRIPT_CYRILLIC },
- { "kl", USCRIPT_LATIN },
- { "km", USCRIPT_KHMER },
- { "kn", USCRIPT_KANNADA },
- { "ko", USCRIPT_HANGUL },
- { "kok", USCRIPT_DEVANAGARI },
- { "kos", USCRIPT_LATIN },
- { "kpe", USCRIPT_LATIN },
- { "krc", USCRIPT_CYRILLIC },
- { "ks", USCRIPT_ARABIC },
- { "ku", USCRIPT_ARABIC },
- { "kum", USCRIPT_CYRILLIC },
- { "ky", USCRIPT_CYRILLIC },
- { "la", USCRIPT_LATIN },
- { "lah", USCRIPT_ARABIC },
- { "lb", USCRIPT_LATIN },
- { "lez", USCRIPT_CYRILLIC },
- { "ln", USCRIPT_LATIN },
- { "lo", USCRIPT_LAO },
- { "lt", USCRIPT_LATIN },
- { "lv", USCRIPT_LATIN },
- { "mai", USCRIPT_DEVANAGARI },
- { "mdf", USCRIPT_CYRILLIC },
- { "mg", USCRIPT_LATIN },
- { "mh", USCRIPT_LATIN },
- { "mi", USCRIPT_LATIN },
- { "mk", USCRIPT_CYRILLIC },
- { "ml", USCRIPT_MALAYALAM },
- { "mn", USCRIPT_CYRILLIC },
- { "mr", USCRIPT_DEVANAGARI },
- { "ms", USCRIPT_LATIN },
- { "mt", USCRIPT_LATIN },
- { "my", USCRIPT_MYANMAR },
- { "myv", USCRIPT_CYRILLIC },
- { "na", USCRIPT_LATIN },
- { "nb", USCRIPT_LATIN },
- { "ne", USCRIPT_DEVANAGARI },
- { "niu", USCRIPT_LATIN },
- { "nl", USCRIPT_LATIN },
- { "nn", USCRIPT_LATIN },
- { "nr", USCRIPT_LATIN },
- { "nso", USCRIPT_LATIN },
- { "ny", USCRIPT_LATIN },
- { "oc", USCRIPT_LATIN },
- { "om", USCRIPT_LATIN },
- { "or", USCRIPT_ORIYA },
- { "os", USCRIPT_CYRILLIC },
- { "pa", USCRIPT_GURMUKHI },
- { "pag", USCRIPT_LATIN },
- { "pap", USCRIPT_LATIN },
- { "pau", USCRIPT_LATIN },
- { "pl", USCRIPT_LATIN },
- { "pon", USCRIPT_LATIN },
- { "ps", USCRIPT_ARABIC },
- { "pt", USCRIPT_LATIN },
- { "qu", USCRIPT_LATIN },
- { "rm", USCRIPT_LATIN },
- { "rn", USCRIPT_LATIN },
- { "ro", USCRIPT_LATIN },
- { "ru", USCRIPT_CYRILLIC },
- { "rw", USCRIPT_LATIN },
- { "sa", USCRIPT_DEVANAGARI },
- { "sah", USCRIPT_CYRILLIC },
- { "sat", USCRIPT_LATIN },
- { "sd", USCRIPT_ARABIC },
- { "se", USCRIPT_LATIN },
- { "sg", USCRIPT_LATIN },
- { "si", USCRIPT_SINHALA },
- { "sid", USCRIPT_LATIN },
- { "sk", USCRIPT_LATIN },
- { "sl", USCRIPT_LATIN },
- { "sm", USCRIPT_LATIN },
- { "so", USCRIPT_LATIN },
- { "sq", USCRIPT_LATIN },
- { "sr", USCRIPT_CYRILLIC },
- { "ss", USCRIPT_LATIN },
- { "st", USCRIPT_LATIN },
- { "su", USCRIPT_LATIN },
- { "sv", USCRIPT_LATIN },
- { "sw", USCRIPT_LATIN },
- { "ta", USCRIPT_TAMIL },
- { "te", USCRIPT_TELUGU },
- { "tet", USCRIPT_LATIN },
- { "tg", USCRIPT_CYRILLIC },
- { "th", USCRIPT_THAI },
- { "ti", USCRIPT_ETHIOPIC },
- { "tig", USCRIPT_ETHIOPIC },
- { "tk", USCRIPT_LATIN },
- { "tkl", USCRIPT_LATIN },
- { "tl", USCRIPT_LATIN },
- { "tn", USCRIPT_LATIN },
- { "to", USCRIPT_LATIN },
- { "tpi", USCRIPT_LATIN },
- { "tr", USCRIPT_LATIN },
- { "trv", USCRIPT_LATIN },
- { "ts", USCRIPT_LATIN },
- { "tt", USCRIPT_CYRILLIC },
- { "tvl", USCRIPT_LATIN },
- { "tw", USCRIPT_LATIN },
- { "ty", USCRIPT_LATIN },
- { "tyv", USCRIPT_CYRILLIC },
- { "udm", USCRIPT_CYRILLIC },
- { "ug", USCRIPT_ARABIC },
- { "uk", USCRIPT_CYRILLIC },
- { "und", USCRIPT_LATIN },
- { "ur", USCRIPT_ARABIC },
- { "uz", USCRIPT_CYRILLIC },
- { "ve", USCRIPT_LATIN },
- { "vi", USCRIPT_LATIN },
- { "wal", USCRIPT_ETHIOPIC },
- { "war", USCRIPT_LATIN },
- { "wo", USCRIPT_LATIN },
- { "xh", USCRIPT_LATIN },
- { "yap", USCRIPT_LATIN },
- { "yo", USCRIPT_LATIN },
- { "za", USCRIPT_LATIN },
- { "zh", USCRIPT_SIMPLIFIED_HAN },
- { "zh_hk", USCRIPT_TRADITIONAL_HAN },
- { "zh_tw", USCRIPT_TRADITIONAL_HAN },
- { "zu", USCRIPT_LATIN }
- };
-
- typedef HashMap<String, UScriptCode> LocaleScriptMap;
- DEFINE_STATIC_LOCAL(LocaleScriptMap, localeScriptMap, ());
- if (localeScriptMap.isEmpty()) {
- for (size_t i = 0; i < sizeof(localeScriptList) / sizeof(localeScriptList[0]); ++i)
- localeScriptMap.set(localeScriptList[i].locale, localeScriptList[i].script);
- }
-
- String canonicalLocale = locale.lower().replace('-', '_');
- while (!canonicalLocale.isEmpty()) {
- HashMap<String, UScriptCode>::iterator it = localeScriptMap.find(canonicalLocale);
- if (it != localeScriptMap.end())
- return it->value;
- size_t pos = canonicalLocale.reverseFind('_');
- if (pos == kNotFound)
- break;
- UScriptCode code = scriptNameToCode(canonicalLocale.substring(pos + 1));
- if (code != USCRIPT_INVALID_CODE && code != USCRIPT_UNKNOWN)
- return code;
- canonicalLocale = canonicalLocale.substring(0, pos);
- }
- return USCRIPT_COMMON;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/text/NonCJKGlyphOrientation.h b/chromium/third_party/WebKit/Source/core/platform/text/NonCJKGlyphOrientation.h
deleted file mode 100644
index 515c23b8609..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/text/NonCJKGlyphOrientation.h
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright (C) 2011 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef NonCJKGlyphOrientation_h
-#define NonCJKGlyphOrientation_h
-
-namespace WebCore {
-
-enum NonCJKGlyphOrientation { NonCJKGlyphOrientationVerticalRight, NonCJKGlyphOrientationUpright };
-
-}
-
-#endif // NonCJKGlyphOrientation_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/text/ParserUtilities.h b/chromium/third_party/WebKit/Source/core/platform/text/ParserUtilities.h
deleted file mode 100644
index 6548759ccca..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/text/ParserUtilities.h
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Copyright (C) 2008 Apple Inc. All Rights Reserved.
- * Copyright (C) 2002, 2003 The Karbon Developers
- * Copyright (C) 2006, 2007 Rob Buis <buis@kde.org>
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#ifndef ParserUtilities_h
-#define ParserUtilities_h
-
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-template<typename CharType>
-inline bool skipString(const CharType*& ptr, const CharType* end, const CharType* name, int length)
-{
- if (end - ptr < length)
- return false;
- if (memcmp(name, ptr, sizeof(CharType) * length))
- return false;
- ptr += length;
- return true;
-}
-
-inline bool skipString(const UChar*& ptr, const UChar* end, const LChar* name, int length)
-{
- if (end - ptr < length)
- return false;
- for (int i = 0; i < length; ++i) {
- if (ptr[i] != name[i])
- return false;
- }
- ptr += length;
- return true;
-}
-
-template<typename CharType>
-inline bool skipString(const CharType*& ptr, const CharType* end, const char* str)
-{
- int length = strlen(str);
- if (end - ptr < length)
- return false;
- for (int i = 0; i < length; ++i) {
- if (ptr[i] != str[i])
- return false;
- }
- ptr += length;
- return true;
-}
-
-} // namspace WebCore
-
-#endif // ParserUtilities_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/text/PlatformLocale.cpp b/chromium/third_party/WebKit/Source/core/platform/text/PlatformLocale.cpp
deleted file mode 100644
index ef0ad720fea..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/text/PlatformLocale.cpp
+++ /dev/null
@@ -1,390 +0,0 @@
-/*
- * Copyright (C) 2011,2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/text/PlatformLocale.h"
-
-#include "core/platform/LocalizedStrings.h"
-#include "core/platform/text/DateTimeFormat.h"
-#include "public/platform/Platform.h"
-#include "wtf/text/StringBuilder.h"
-
-namespace WebCore {
-
-using WebKit::Platform;
-using WebKit::WebLocalizedString;
-
-class DateTimeStringBuilder : private DateTimeFormat::TokenHandler {
- WTF_MAKE_NONCOPYABLE(DateTimeStringBuilder);
-
-public:
- // The argument objects must be alive until this object dies.
- DateTimeStringBuilder(Locale&, const DateComponents&);
-
- bool build(const String&);
- String toString();
-
-private:
- // DateTimeFormat::TokenHandler functions.
- virtual void visitField(DateTimeFormat::FieldType, int) OVERRIDE FINAL;
- virtual void visitLiteral(const String&) OVERRIDE FINAL;
-
- String zeroPadString(const String&, size_t width);
- void appendNumber(int number, size_t width);
-
- StringBuilder m_builder;
- Locale& m_localizer;
- const DateComponents& m_date;
-};
-
-DateTimeStringBuilder::DateTimeStringBuilder(Locale& localizer, const DateComponents& date)
- : m_localizer(localizer)
- , m_date(date)
-{
-}
-
-bool DateTimeStringBuilder::build(const String& formatString)
-{
- m_builder.reserveCapacity(formatString.length());
- return DateTimeFormat::parse(formatString, *this);
-}
-
-String DateTimeStringBuilder::zeroPadString(const String& string, size_t width)
-{
- if (string.length() >= width)
- return string;
- StringBuilder zeroPaddedStringBuilder;
- zeroPaddedStringBuilder.reserveCapacity(width);
- for (size_t i = string.length(); i < width; ++i)
- zeroPaddedStringBuilder.append("0");
- zeroPaddedStringBuilder.append(string);
- return zeroPaddedStringBuilder.toString();
-}
-
-void DateTimeStringBuilder::appendNumber(int number, size_t width)
-{
- String zeroPaddedNumberString = zeroPadString(String::number(number), width);
- m_builder.append(m_localizer.convertToLocalizedNumber(zeroPaddedNumberString));
-}
-
-void DateTimeStringBuilder::visitField(DateTimeFormat::FieldType fieldType, int numberOfPatternCharacters)
-{
- switch (fieldType) {
- case DateTimeFormat::FieldTypeYear:
- // Always use padding width of 4 so it matches DateTimeEditElement.
- appendNumber(m_date.fullYear(), 4);
- return;
- case DateTimeFormat::FieldTypeMonth:
- if (numberOfPatternCharacters == 3)
- m_builder.append(m_localizer.shortMonthLabels()[m_date.month()]);
- else if (numberOfPatternCharacters == 4)
- m_builder.append(m_localizer.monthLabels()[m_date.month()]);
- else {
- // Always use padding width of 2 so it matches DateTimeEditElement.
- appendNumber(m_date.month() + 1, 2);
- }
- return;
- case DateTimeFormat::FieldTypeMonthStandAlone:
- if (numberOfPatternCharacters == 3)
- m_builder.append(m_localizer.shortStandAloneMonthLabels()[m_date.month()]);
- else if (numberOfPatternCharacters == 4)
- m_builder.append(m_localizer.standAloneMonthLabels()[m_date.month()]);
- else {
- // Always use padding width of 2 so it matches DateTimeEditElement.
- appendNumber(m_date.month() + 1, 2);
- }
- return;
- case DateTimeFormat::FieldTypeDayOfMonth:
- // Always use padding width of 2 so it matches DateTimeEditElement.
- appendNumber(m_date.monthDay(), 2);
- return;
- case DateTimeFormat::FieldTypeWeekOfYear:
- // Always use padding width of 2 so it matches DateTimeEditElement.
- appendNumber(m_date.week(), 2);
- return;
- case DateTimeFormat::FieldTypePeriod:
- m_builder.append(m_localizer.timeAMPMLabels()[(m_date.hour() >= 12 ? 1 : 0)]);
- return;
- case DateTimeFormat::FieldTypeHour12: {
- int hour12 = m_date.hour() % 12;
- if (!hour12)
- hour12 = 12;
- appendNumber(hour12, numberOfPatternCharacters);
- return;
- }
- case DateTimeFormat::FieldTypeHour23:
- appendNumber(m_date.hour(), numberOfPatternCharacters);
- return;
- case DateTimeFormat::FieldTypeHour11:
- appendNumber(m_date.hour() % 12, numberOfPatternCharacters);
- return;
- case DateTimeFormat::FieldTypeHour24: {
- int hour24 = m_date.hour();
- if (!hour24)
- hour24 = 24;
- appendNumber(hour24, numberOfPatternCharacters);
- return;
- }
- case DateTimeFormat::FieldTypeMinute:
- appendNumber(m_date.minute(), numberOfPatternCharacters);
- return;
- case DateTimeFormat::FieldTypeSecond:
- if (!m_date.millisecond())
- appendNumber(m_date.second(), numberOfPatternCharacters);
- else {
- double second = m_date.second() + m_date.millisecond() / 1000.0;
- String zeroPaddedSecondString = zeroPadString(String::format("%.03f", second), numberOfPatternCharacters + 4);
- m_builder.append(m_localizer.convertToLocalizedNumber(zeroPaddedSecondString));
- }
- return;
- default:
- return;
- }
-}
-
-void DateTimeStringBuilder::visitLiteral(const String& text)
-{
- ASSERT(text.length());
- m_builder.append(text);
-}
-
-String DateTimeStringBuilder::toString()
-{
- return m_builder.toString();
-}
-
-Locale::~Locale()
-{
-}
-
-String Locale::queryString(WebLocalizedString::Name name)
-{
- // FIXME: Returns a string locazlied for this locale.
- return Platform::current()->queryLocalizedString(name);
-}
-
-String Locale::queryString(WebLocalizedString::Name name, const String& parameter)
-{
- // FIXME: Returns a string locazlied for this locale.
- return Platform::current()->queryLocalizedString(name, parameter);
-}
-
-String Locale::queryString(WebLocalizedString::Name name, const String& parameter1, const String& parameter2)
-{
- // FIXME: Returns a string locazlied for this locale.
- return Platform::current()->queryLocalizedString(name, parameter1, parameter2);
-}
-
-String Locale::validationMessageTooLongText(unsigned valueLength, int maxLength)
-{
- return queryString(WebLocalizedString::ValidationTooLong, convertToLocalizedNumber(String::number(valueLength)), convertToLocalizedNumber(String::number(maxLength)));
-}
-
-void Locale::setLocaleData(const Vector<String, DecimalSymbolsSize>& symbols, const String& positivePrefix, const String& positiveSuffix, const String& negativePrefix, const String& negativeSuffix)
-{
- for (size_t i = 0; i < symbols.size(); ++i) {
- ASSERT(!symbols[i].isEmpty());
- m_decimalSymbols[i] = symbols[i];
- }
- m_positivePrefix = positivePrefix;
- m_positiveSuffix = positiveSuffix;
- m_negativePrefix = negativePrefix;
- m_negativeSuffix = negativeSuffix;
- ASSERT(!m_positivePrefix.isEmpty() || !m_positiveSuffix.isEmpty() || !m_negativePrefix.isEmpty() || !m_negativeSuffix.isEmpty());
- m_hasLocaleData = true;
-}
-
-String Locale::convertToLocalizedNumber(const String& input)
-{
- initializeLocaleData();
- if (!m_hasLocaleData || input.isEmpty())
- return input;
-
- unsigned i = 0;
- bool isNegative = false;
- StringBuilder builder;
- builder.reserveCapacity(input.length());
-
- if (input[0] == '-') {
- ++i;
- isNegative = true;
- builder.append(m_negativePrefix);
- } else
- builder.append(m_positivePrefix);
-
- for (; i < input.length(); ++i) {
- switch (input[i]) {
- case '0':
- case '1':
- case '2':
- case '3':
- case '4':
- case '5':
- case '6':
- case '7':
- case '8':
- case '9':
- builder.append(m_decimalSymbols[input[i] - '0']);
- break;
- case '.':
- builder.append(m_decimalSymbols[DecimalSeparatorIndex]);
- break;
- default:
- ASSERT_NOT_REACHED();
- }
- }
-
- builder.append(isNegative ? m_negativeSuffix : m_positiveSuffix);
-
- return builder.toString();
-}
-
-static bool matches(const String& text, unsigned position, const String& part)
-{
- if (part.isEmpty())
- return true;
- if (position + part.length() > text.length())
- return false;
- for (unsigned i = 0; i < part.length(); ++i) {
- if (text[position + i] != part[i])
- return false;
- }
- return true;
-}
-
-bool Locale::detectSignAndGetDigitRange(const String& input, bool& isNegative, unsigned& startIndex, unsigned& endIndex)
-{
- startIndex = 0;
- endIndex = input.length();
- if (m_negativePrefix.isEmpty() && m_negativeSuffix.isEmpty()) {
- if (input.startsWith(m_positivePrefix) && input.endsWith(m_positiveSuffix)) {
- isNegative = false;
- startIndex = m_positivePrefix.length();
- endIndex -= m_positiveSuffix.length();
- } else
- isNegative = true;
- } else {
- if (input.startsWith(m_negativePrefix) && input.endsWith(m_negativeSuffix)) {
- isNegative = true;
- startIndex = m_negativePrefix.length();
- endIndex -= m_negativeSuffix.length();
- } else {
- isNegative = false;
- if (input.startsWith(m_positivePrefix) && input.endsWith(m_positiveSuffix)) {
- startIndex = m_positivePrefix.length();
- endIndex -= m_positiveSuffix.length();
- } else
- return false;
- }
- }
- return true;
-}
-
-unsigned Locale::matchedDecimalSymbolIndex(const String& input, unsigned& position)
-{
- for (unsigned symbolIndex = 0; symbolIndex < DecimalSymbolsSize; ++symbolIndex) {
- if (m_decimalSymbols[symbolIndex].length() && matches(input, position, m_decimalSymbols[symbolIndex])) {
- position += m_decimalSymbols[symbolIndex].length();
- return symbolIndex;
- }
- }
- return DecimalSymbolsSize;
-}
-
-String Locale::convertFromLocalizedNumber(const String& localized)
-{
- initializeLocaleData();
- String input = localized.stripWhiteSpace();
- if (!m_hasLocaleData || input.isEmpty())
- return input;
-
- bool isNegative;
- unsigned startIndex;
- unsigned endIndex;
- if (!detectSignAndGetDigitRange(input, isNegative, startIndex, endIndex))
- return input;
-
- StringBuilder builder;
- builder.reserveCapacity(input.length());
- if (isNegative)
- builder.append("-");
- for (unsigned i = startIndex; i < endIndex;) {
- unsigned symbolIndex = matchedDecimalSymbolIndex(input, i);
- if (symbolIndex >= DecimalSymbolsSize)
- return input;
- if (symbolIndex == DecimalSeparatorIndex)
- builder.append('.');
- else if (symbolIndex == GroupSeparatorIndex)
- return input;
- else
- builder.append(static_cast<UChar>('0' + symbolIndex));
- }
- return builder.toString();
-}
-
-#if ENABLE(INPUT_MULTIPLE_FIELDS_UI)
-String Locale::localizedDecimalSeparator()
-{
- initializeLocaleData();
- return m_decimalSymbols[DecimalSeparatorIndex];
-}
-#endif
-
-String Locale::formatDateTime(const DateComponents& date, FormatType formatType)
-{
- if (date.type() == DateComponents::Invalid)
- return String();
-
- DateTimeStringBuilder builder(*this, date);
- switch (date.type()) {
- case DateComponents::Time:
- builder.build(formatType == FormatTypeShort ? shortTimeFormat() : timeFormat());
- break;
- case DateComponents::Date:
- builder.build(dateFormat());
- break;
- case DateComponents::Month:
- builder.build(formatType == FormatTypeShort ? shortMonthFormat() : monthFormat());
- break;
- case DateComponents::Week:
- builder.build(weekFormatInLDML());
- break;
- case DateComponents::DateTime:
- case DateComponents::DateTimeLocal:
- builder.build(formatType == FormatTypeShort ? dateTimeFormatWithoutSeconds() : dateTimeFormatWithSeconds());
- break;
- case DateComponents::Invalid:
- ASSERT_NOT_REACHED();
- break;
- }
- return builder.toString();
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/text/PlatformLocale.h b/chromium/third_party/WebKit/Source/core/platform/text/PlatformLocale.h
deleted file mode 100644
index 45e40e698b7..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/text/PlatformLocale.h
+++ /dev/null
@@ -1,172 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
- * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
- * DAMAGE.
- */
-
-#ifndef PlatformLocale_h
-#define PlatformLocale_h
-
-#include "core/platform/DateComponents.h"
-#include "core/platform/Language.h"
-#include "public/platform/WebLocalizedString.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class Locale {
- WTF_MAKE_NONCOPYABLE(Locale);
-
-public:
- static PassOwnPtr<Locale> create(const AtomicString& localeIdentifier);
- static PassOwnPtr<Locale> createDefault();
-
- String queryString(WebKit::WebLocalizedString::Name);
- String queryString(WebKit::WebLocalizedString::Name, const String& parameter);
- String queryString(WebKit::WebLocalizedString::Name, const String& parameter1, const String& parameter2);
- String validationMessageTooLongText(unsigned valueLength, int maxLength);
-
- // Converts the specified number string to another number string localized
- // for this Locale locale. The input string must conform to HTML
- // floating-point numbers, and is not empty.
- String convertToLocalizedNumber(const String&);
-
- // Converts the specified localized number string to a number string in the
- // HTML floating-point number format. The input string is provided by a end
- // user, and might not be a number string. It's ok that the function returns
- // a string which is not conforms to the HTML floating-point number format,
- // callers of this function are responsible to check the format of the
- // resultant string.
- String convertFromLocalizedNumber(const String&);
-
-#if ENABLE(INPUT_MULTIPLE_FIELDS_UI)
- // Returns localized decimal separator, e.g. "." for English, "," for French.
- String localizedDecimalSeparator();
-#endif
-
- // Returns date format in Unicode TR35 LDML[1] containing day of month,
- // month, and year, e.g. "dd/mm/yyyy"
- // [1] LDML http://unicode.org/reports/tr35/#Date_Format_Patterns
- virtual String dateFormat() = 0;
-
- // Returns a year-month format in Unicode TR35 LDML.
- virtual String monthFormat() = 0;
-
- // Returns a year-month format using short month lanel in Unicode TR35 LDML.
- virtual String shortMonthFormat() = 0;
-
- // Returns time format in Unicode TR35 LDML[1] containing hour, minute, and
- // second with optional period(AM/PM), e.g. "h:mm:ss a"
- // [1] LDML http://unicode.org/reports/tr35/#Date_Format_Patterns
- virtual String timeFormat() = 0;
-
- // Returns time format in Unicode TR35 LDML containing hour, and minute
- // with optional period(AM/PM), e.g. "h:mm a"
- // Note: Some platforms return same value as timeFormat().
- virtual String shortTimeFormat() = 0;
-
- // Returns a date-time format in Unicode TR35 LDML. It should have a seconds
- // field.
- virtual String dateTimeFormatWithSeconds() = 0;
-
- // Returns a date-time format in Unicode TR35 LDML. It should have no seconds
- // field.
- virtual String dateTimeFormatWithoutSeconds() = 0;
-
- // Returns a vector of string of which size is 12. The first item is a
- // localized string of Jan and the last item is a localized string of
- // Dec. These strings should be short.
- virtual const Vector<String>& shortMonthLabels() = 0;
-
- // Returns a vector of string of which size is 12. The first item is a
- // stand-alone localized string of January and the last item is a
- // stand-alone localized string of December. These strings should not be
- // abbreviations.
- virtual const Vector<String>& standAloneMonthLabels() = 0;
-
- // Stand-alone month version of shortMonthLabels.
- virtual const Vector<String>& shortStandAloneMonthLabels() = 0;
-
- // Returns localized period field(AM/PM) strings.
- virtual const Vector<String>& timeAMPMLabels() = 0;
-
- // Returns a vector of string of which size is 12. The first item is a
- // localized string of January, and the last item is a localized string of
- // December. These strings should not be abbreviations.
- virtual const Vector<String>& monthLabels() = 0;
-
-#if ENABLE(CALENDAR_PICKER)
- // Returns a vector of string of which size is 7. The first item is a
- // localized short string of Monday, and the last item is a localized
- // short string of Saturday. These strings should be short.
- virtual const Vector<String>& weekDayShortLabels() = 0;
-
- // The first day of a week. 0 is Sunday, and 6 is Saturday.
- virtual unsigned firstDayOfWeek() = 0;
-
- // Returns true if people use right-to-left writing in the locale for this
- // object.
- virtual bool isRTL() = 0;
-#endif
-
- enum FormatType { FormatTypeUnspecified, FormatTypeShort, FormatTypeMedium };
-
- // Serializes the specified date into a formatted date string to
- // display to the user. If an implementation doesn't support
- // localized dates the function should return an empty string.
- // FormatType can be used to specify if you want the short format.
- String formatDateTime(const DateComponents&, FormatType = FormatTypeUnspecified);
-
- virtual ~Locale();
-
-protected:
- enum {
- // 0-9 for digits.
- DecimalSeparatorIndex = 10,
- GroupSeparatorIndex = 11,
- DecimalSymbolsSize
- };
-
- Locale() : m_hasLocaleData(false) { }
- virtual void initializeLocaleData() = 0;
- void setLocaleData(const Vector<String, DecimalSymbolsSize>&, const String& positivePrefix, const String& positiveSuffix, const String& negativePrefix, const String& negativeSuffix);
-
-private:
- bool detectSignAndGetDigitRange(const String& input, bool& isNegative, unsigned& startIndex, unsigned& endIndex);
- unsigned matchedDecimalSymbolIndex(const String& input, unsigned& position);
-
- String m_decimalSymbols[DecimalSymbolsSize];
- String m_positivePrefix;
- String m_positiveSuffix;
- String m_negativePrefix;
- String m_negativeSuffix;
- bool m_hasLocaleData;
-};
-
-inline PassOwnPtr<Locale> Locale::createDefault()
-{
- return Locale::create(defaultLanguage());
-}
-
-}
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/text/QuotedPrintable.cpp b/chromium/third_party/WebKit/Source/core/platform/text/QuotedPrintable.cpp
deleted file mode 100644
index 547a77cb9cd..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/text/QuotedPrintable.cpp
+++ /dev/null
@@ -1,155 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/text/QuotedPrintable.h"
-
-#include "wtf/ASCIICType.h"
-
-namespace WebCore {
-
-static const size_t maximumLineLength = 76;
-
-static const char crlfLineEnding[] = "\r\n";
-
-static size_t lengthOfLineEndingAtIndex(const char* input, size_t inputLength, size_t index)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(index < inputLength);
- if (input[index] == '\n')
- return 1; // Single LF.
-
- if (input[index] == '\r') {
- if ((index + 1) == inputLength || input[index + 1] != '\n')
- return 1; // Single CR (Classic Mac OS).
- return 2; // CR-LF.
- }
-
- return 0;
-}
-
-void quotedPrintableEncode(const Vector<char>& in, Vector<char>& out)
-{
- quotedPrintableEncode(in.data(), in.size(), out);
-}
-
-void quotedPrintableEncode(const char* input, size_t inputLength, Vector<char>& out)
-{
- out.clear();
- out.reserveCapacity(inputLength);
- size_t currentLineLength = 0;
- for (size_t i = 0; i < inputLength; ++i) {
- bool isLastCharacter = (i == inputLength - 1);
- char currentCharacter = input[i];
- bool requiresEncoding = false;
- // All non-printable ASCII characters and = require encoding.
- if ((currentCharacter < ' ' || currentCharacter > '~' || currentCharacter == '=') && currentCharacter != '\t')
- requiresEncoding = true;
-
- // Space and tab characters have to be encoded if they appear at the end of a line.
- if (!requiresEncoding && (currentCharacter == '\t' || currentCharacter == ' ') && (isLastCharacter || lengthOfLineEndingAtIndex(input, inputLength, i + 1)))
- requiresEncoding = true;
-
- // End of line should be converted to CR-LF sequences.
- if (!isLastCharacter) {
- size_t lengthOfLineEnding = lengthOfLineEndingAtIndex(input, inputLength, i);
- if (lengthOfLineEnding) {
- out.append(crlfLineEnding, strlen(crlfLineEnding));
- currentLineLength = 0;
- i += (lengthOfLineEnding - 1); // -1 because we'll ++ in the for() above.
- continue;
- }
- }
-
- size_t lengthOfEncodedCharacter = 1;
- if (requiresEncoding)
- lengthOfEncodedCharacter += 2;
- if (!isLastCharacter)
- lengthOfEncodedCharacter += 1; // + 1 for the = (soft line break).
-
- // Insert a soft line break if necessary.
- if (currentLineLength + lengthOfEncodedCharacter > maximumLineLength) {
- out.append('=');
- out.append(crlfLineEnding, strlen(crlfLineEnding));
- currentLineLength = 0;
- }
-
- // Finally, insert the actual character(s).
- if (requiresEncoding) {
- out.append('=');
- out.append(upperNibbleToASCIIHexDigit(currentCharacter));
- out.append(lowerNibbleToASCIIHexDigit(currentCharacter));
- currentLineLength += 3;
- } else {
- out.append(currentCharacter);
- currentLineLength++;
- }
- }
-}
-
-void quotedPrintableDecode(const Vector<char>& in, Vector<char>& out)
-{
- quotedPrintableDecode(in.data(), in.size(), out);
-}
-
-void quotedPrintableDecode(const char* data, size_t dataLength, Vector<char>& out)
-{
- out.clear();
- if (!dataLength)
- return;
-
- for (size_t i = 0; i < dataLength; ++i) {
- char currentCharacter = data[i];
- if (currentCharacter != '=') {
- out.append(currentCharacter);
- continue;
- }
- // We are dealing with a '=xx' sequence.
- if (dataLength - i < 3) {
- // Unfinished = sequence, append as is.
- out.append(currentCharacter);
- continue;
- }
- char upperCharacter = data[++i];
- char lowerCharacter = data[++i];
- if (upperCharacter == '\r' && lowerCharacter == '\n')
- continue;
-
- if (!isASCIIHexDigit(upperCharacter) || !isASCIIHexDigit(lowerCharacter)) {
- // Invalid sequence, = followed by non hex digits, just insert the characters as is.
- out.append('=');
- out.append(upperCharacter);
- out.append(lowerCharacter);
- continue;
- }
- out.append(static_cast<char>(toASCIIHexValue(upperCharacter, lowerCharacter)));
- }
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/text/QuotedPrintable.h b/chromium/third_party/WebKit/Source/core/platform/text/QuotedPrintable.h
deleted file mode 100644
index 5cbd85b322c..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/text/QuotedPrintable.h
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef QuotedPrintable_h
-#define QuotedPrintable_h
-
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-void quotedPrintableEncode(const Vector<char>&, Vector<char>&);
-void quotedPrintableEncode(const char*, size_t, Vector<char>&);
-
-void quotedPrintableDecode(const Vector<char>&, Vector<char>&);
-void quotedPrintableDecode(const char*, size_t, Vector<char>&);
-
-} // namespace WebCore
-
-#endif // QuotedPrintable_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/text/RegularExpression.cpp b/chromium/third_party/WebKit/Source/core/platform/text/RegularExpression.cpp
deleted file mode 100644
index 50bd48f736b..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/text/RegularExpression.cpp
+++ /dev/null
@@ -1,110 +0,0 @@
-/*
- * Copyright (C) 2004, 2008, 2009 Apple Inc. All rights reserved.
- * Copyright (C) 2008 Collabora Ltd.
- * Copyright (C) 2011 Peter Varga (pvarga@webkit.org), University of Szeged
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/text/RegularExpression.h"
-
-// FIXME: These seem like a layering violation, but converting the strings manually
-// without v8String is difficult, and calling into v8 without V8RecursionScope will
-// assert. Perhaps v8 basic utilities shouldn't be in bindings, or we should put
-// RegularExpression as some kind of abstract interface that's implemented in bindings.
-#include "bindings/v8/V8Binding.h"
-#include "bindings/v8/V8PerIsolateData.h"
-#include "bindings/v8/V8RecursionScope.h"
-
-namespace WebCore {
-
-RegularExpression::RegularExpression(const String& pattern, TextCaseSensitivity caseSensitivity, MultilineMode multilineMode)
-{
- v8::Isolate* isolate = v8::Isolate::GetCurrent();
- v8::HandleScope handleScope(isolate);
- v8::Local<v8::Context> context = V8PerIsolateData::from(isolate)->ensureRegexContext();
- v8::Context::Scope scope(context);
-
- unsigned flags = v8::RegExp::kNone;
- if (caseSensitivity == TextCaseInsensitive)
- flags |= v8::RegExp::kIgnoreCase;
- if (multilineMode == MultilineEnabled)
- flags |= v8::RegExp::kMultiline;
-
- v8::TryCatch tryCatch;
- v8::Local<v8::RegExp> regex = v8::RegExp::New(v8String(pattern, context->GetIsolate()), static_cast<v8::RegExp::Flags>(flags));
-
- // If the regex failed to compile we'll get an empty handle.
- if (!regex.IsEmpty())
- m_regex.set(isolate, regex);
-}
-
-int RegularExpression::match(const String& string, int startFrom, int* matchLength) const
-{
- if (matchLength)
- *matchLength = 0;
-
- if (m_regex.isEmpty() || string.isNull())
- return -1;
-
- // v8 strings are limited to int.
- if (string.length() > INT_MAX)
- return -1;
-
- v8::Isolate* isolate = v8::Isolate::GetCurrent();
- v8::HandleScope handleScope(isolate);
- v8::Local<v8::Context> context = V8PerIsolateData::current()->ensureRegexContext();
- v8::Context::Scope scope(context);
- v8::TryCatch tryCatch;
-
- V8RecursionScope::MicrotaskSuppression microtaskScope;
-
- v8::Local<v8::RegExp> regex = m_regex.newLocal(isolate);
- v8::Local<v8::Function> exec = regex->Get(v8::String::NewSymbol("exec")).As<v8::Function>();
-
- v8::Handle<v8::Value> argv[] = { v8String(string.substring(startFrom), context->GetIsolate()) };
- v8::Local<v8::Value> returnValue = exec->Call(regex, 1, argv);
-
- // RegExp#exec returns null if there's no match, otherwise it returns an
- // Array of strings with the first being the whole match string and others
- // being subgroups. The Array also has some random properties tacked on like
- // "index" which is the offset of the match.
- //
- // https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/RegExp/exec
-
- if (!returnValue->IsArray())
- return -1;
-
- v8::Local<v8::Array> result = returnValue.As<v8::Array>();
- int matchOffset = result->Get(v8::String::NewSymbol("index"))->ToInt32()->Value();
-
- if (matchLength) {
- v8::Local<v8::String> match = result->Get(0).As<v8::String>();
- *matchLength = match->Length();
- }
-
- return matchOffset + startFrom;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/text/RegularExpression.h b/chromium/third_party/WebKit/Source/core/platform/text/RegularExpression.h
deleted file mode 100644
index e12988c9120..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/text/RegularExpression.h
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Copyright (C) 2003, 2008, 2009 Apple Inc. All rights reserved.
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef RegularExpression_h
-#define RegularExpression_h
-
-#include <v8.h>
-#include "bindings/v8/ScopedPersistent.h"
-#include "wtf/Noncopyable.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-enum MultilineMode {
- MultilineDisabled,
- MultilineEnabled
-};
-
-class RegularExpression {
- WTF_MAKE_FAST_ALLOCATED; WTF_MAKE_NONCOPYABLE(RegularExpression);
-public:
- RegularExpression(const String&, TextCaseSensitivity, MultilineMode = MultilineDisabled);
-
- int match(const String&, int startFrom = 0, int* matchLength = 0) const;
-
- bool isValid() const { return !m_regex.isEmpty(); }
-
-private:
- ScopedPersistent<v8::RegExp> m_regex;
-};
-
-} // namespace WebCore
-
-#endif // RegularExpression_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/text/SegmentedString.cpp b/chromium/third_party/WebKit/Source/core/platform/text/SegmentedString.cpp
deleted file mode 100644
index 628cf92f0de..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/text/SegmentedString.cpp
+++ /dev/null
@@ -1,366 +0,0 @@
-/*
- Copyright (C) 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include "config.h"
-#include "core/platform/text/SegmentedString.h"
-
-namespace WebCore {
-
-SegmentedString::SegmentedString(const SegmentedString& other)
- : m_pushedChar1(other.m_pushedChar1)
- , m_pushedChar2(other.m_pushedChar2)
- , m_currentString(other.m_currentString)
- , m_numberOfCharactersConsumedPriorToCurrentString(other.m_numberOfCharactersConsumedPriorToCurrentString)
- , m_numberOfCharactersConsumedPriorToCurrentLine(other.m_numberOfCharactersConsumedPriorToCurrentLine)
- , m_currentLine(other.m_currentLine)
- , m_substrings(other.m_substrings)
- , m_closed(other.m_closed)
- , m_empty(other.m_empty)
- , m_fastPathFlags(other.m_fastPathFlags)
- , m_advanceFunc(other.m_advanceFunc)
- , m_advanceAndUpdateLineNumberFunc(other.m_advanceAndUpdateLineNumberFunc)
-{
- if (m_pushedChar2)
- m_currentChar = m_pushedChar2;
- else if (m_pushedChar1)
- m_currentChar = m_pushedChar1;
- else
- m_currentChar = m_currentString.m_length ? m_currentString.getCurrentChar() : 0;
-}
-
-const SegmentedString& SegmentedString::operator=(const SegmentedString& other)
-{
- m_pushedChar1 = other.m_pushedChar1;
- m_pushedChar2 = other.m_pushedChar2;
- m_currentString = other.m_currentString;
- m_substrings = other.m_substrings;
- if (m_pushedChar2)
- m_currentChar = m_pushedChar2;
- else if (m_pushedChar1)
- m_currentChar = m_pushedChar1;
- else
- m_currentChar = m_currentString.m_length ? m_currentString.getCurrentChar() : 0;
-
- m_closed = other.m_closed;
- m_empty = other.m_empty;
- m_fastPathFlags = other.m_fastPathFlags;
- m_numberOfCharactersConsumedPriorToCurrentString = other.m_numberOfCharactersConsumedPriorToCurrentString;
- m_numberOfCharactersConsumedPriorToCurrentLine = other.m_numberOfCharactersConsumedPriorToCurrentLine;
- m_currentLine = other.m_currentLine;
-
- m_advanceFunc = other.m_advanceFunc;
- m_advanceAndUpdateLineNumberFunc = other.m_advanceAndUpdateLineNumberFunc;
-
- return *this;
-}
-
-unsigned SegmentedString::length() const
-{
- unsigned length = m_currentString.m_length;
- if (m_pushedChar1) {
- ++length;
- if (m_pushedChar2)
- ++length;
- }
- if (isComposite()) {
- Deque<SegmentedSubstring>::const_iterator it = m_substrings.begin();
- Deque<SegmentedSubstring>::const_iterator e = m_substrings.end();
- for (; it != e; ++it)
- length += it->m_length;
- }
- return length;
-}
-
-void SegmentedString::setExcludeLineNumbers()
-{
- m_currentString.setExcludeLineNumbers();
- if (isComposite()) {
- Deque<SegmentedSubstring>::iterator it = m_substrings.begin();
- Deque<SegmentedSubstring>::iterator e = m_substrings.end();
- for (; it != e; ++it)
- it->setExcludeLineNumbers();
- }
-}
-
-void SegmentedString::clear()
-{
- m_pushedChar1 = 0;
- m_pushedChar2 = 0;
- m_currentChar = 0;
- m_currentString.clear();
- m_numberOfCharactersConsumedPriorToCurrentString = 0;
- m_numberOfCharactersConsumedPriorToCurrentLine = 0;
- m_currentLine = 0;
- m_substrings.clear();
- m_closed = false;
- m_empty = true;
- m_fastPathFlags = NoFastPath;
- m_advanceFunc = &SegmentedString::advanceEmpty;
- m_advanceAndUpdateLineNumberFunc = &SegmentedString::advanceEmpty;
-}
-
-void SegmentedString::append(const SegmentedSubstring& s)
-{
- ASSERT(!m_closed);
- if (!s.m_length)
- return;
-
- if (!m_currentString.m_length) {
- m_numberOfCharactersConsumedPriorToCurrentString += m_currentString.numberOfCharactersConsumed();
- m_currentString = s;
- updateAdvanceFunctionPointers();
- } else
- m_substrings.append(s);
- m_empty = false;
-}
-
-void SegmentedString::prepend(const SegmentedSubstring& s)
-{
- ASSERT(!escaped());
- ASSERT(!s.numberOfCharactersConsumed());
- if (!s.m_length)
- return;
-
- // FIXME: We're assuming that the prepend were originally consumed by
- // this SegmentedString. We're also ASSERTing that s is a fresh
- // SegmentedSubstring. These assumptions are sufficient for our
- // current use, but we might need to handle the more elaborate
- // cases in the future.
- m_numberOfCharactersConsumedPriorToCurrentString += m_currentString.numberOfCharactersConsumed();
- m_numberOfCharactersConsumedPriorToCurrentString -= s.m_length;
- if (!m_currentString.m_length) {
- m_currentString = s;
- updateAdvanceFunctionPointers();
- } else {
- // Shift our m_currentString into our list.
- m_substrings.prepend(m_currentString);
- m_currentString = s;
- updateAdvanceFunctionPointers();
- }
- m_empty = false;
-}
-
-void SegmentedString::close()
-{
- // Closing a stream twice is likely a coding mistake.
- ASSERT(!m_closed);
- m_closed = true;
-}
-
-void SegmentedString::append(const SegmentedString& s)
-{
- ASSERT(!m_closed);
- ASSERT(!s.escaped());
- append(s.m_currentString);
- if (s.isComposite()) {
- Deque<SegmentedSubstring>::const_iterator it = s.m_substrings.begin();
- Deque<SegmentedSubstring>::const_iterator e = s.m_substrings.end();
- for (; it != e; ++it)
- append(*it);
- }
- m_currentChar = m_pushedChar1 ? m_pushedChar1 : (m_currentString.m_length ? m_currentString.getCurrentChar() : 0);
-}
-
-void SegmentedString::prepend(const SegmentedString& s)
-{
- ASSERT(!escaped());
- ASSERT(!s.escaped());
- if (s.isComposite()) {
- Deque<SegmentedSubstring>::const_reverse_iterator it = s.m_substrings.rbegin();
- Deque<SegmentedSubstring>::const_reverse_iterator e = s.m_substrings.rend();
- for (; it != e; ++it)
- prepend(*it);
- }
- prepend(s.m_currentString);
- m_currentChar = m_pushedChar1 ? m_pushedChar1 : (m_currentString.m_length ? m_currentString.getCurrentChar() : 0);
-}
-
-void SegmentedString::advanceSubstring()
-{
- if (isComposite()) {
- m_numberOfCharactersConsumedPriorToCurrentString += m_currentString.numberOfCharactersConsumed();
- m_currentString = m_substrings.takeFirst();
- // If we've previously consumed some characters of the non-current
- // string, we now account for those characters as part of the current
- // string, not as part of "prior to current string."
- m_numberOfCharactersConsumedPriorToCurrentString -= m_currentString.numberOfCharactersConsumed();
- updateAdvanceFunctionPointers();
- } else {
- m_currentString.clear();
- m_empty = true;
- m_fastPathFlags = NoFastPath;
- m_advanceFunc = &SegmentedString::advanceEmpty;
- m_advanceAndUpdateLineNumberFunc = &SegmentedString::advanceEmpty;
- }
-}
-
-String SegmentedString::toString() const
-{
- StringBuilder result;
- if (m_pushedChar1) {
- result.append(m_pushedChar1);
- if (m_pushedChar2)
- result.append(m_pushedChar2);
- }
- m_currentString.appendTo(result);
- if (isComposite()) {
- Deque<SegmentedSubstring>::const_iterator it = m_substrings.begin();
- Deque<SegmentedSubstring>::const_iterator e = m_substrings.end();
- for (; it != e; ++it)
- it->appendTo(result);
- }
- return result.toString();
-}
-
-void SegmentedString::advance(unsigned count, UChar* consumedCharacters)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(count <= length());
- for (unsigned i = 0; i < count; ++i) {
- consumedCharacters[i] = currentChar();
- advance();
- }
-}
-
-void SegmentedString::advance8()
-{
- ASSERT(!m_pushedChar1);
- decrementAndCheckLength();
- m_currentChar = m_currentString.incrementAndGetCurrentChar8();
-}
-
-void SegmentedString::advance16()
-{
- ASSERT(!m_pushedChar1);
- decrementAndCheckLength();
- m_currentChar = m_currentString.incrementAndGetCurrentChar16();
-}
-
-void SegmentedString::advanceAndUpdateLineNumber8()
-{
- ASSERT(!m_pushedChar1);
- ASSERT(m_currentString.getCurrentChar() == m_currentChar);
- if (m_currentChar == '\n') {
- ++m_currentLine;
- m_numberOfCharactersConsumedPriorToCurrentLine = numberOfCharactersConsumed() + 1;
- }
- decrementAndCheckLength();
- m_currentChar = m_currentString.incrementAndGetCurrentChar8();
-}
-
-void SegmentedString::advanceAndUpdateLineNumber16()
-{
- ASSERT(!m_pushedChar1);
- ASSERT(m_currentString.getCurrentChar() == m_currentChar);
- if (m_currentChar == '\n') {
- ++m_currentLine;
- m_numberOfCharactersConsumedPriorToCurrentLine = numberOfCharactersConsumed() + 1;
- }
- decrementAndCheckLength();
- m_currentChar = m_currentString.incrementAndGetCurrentChar16();
-}
-
-void SegmentedString::advanceSlowCase()
-{
- if (m_pushedChar1) {
- m_pushedChar1 = m_pushedChar2;
- m_pushedChar2 = 0;
-
- if (m_pushedChar1) {
- m_currentChar = m_pushedChar1;
- return;
- }
-
- updateAdvanceFunctionPointers();
- } else if (m_currentString.m_length) {
- if (--m_currentString.m_length == 0)
- advanceSubstring();
- } else if (!isComposite()) {
- m_currentString.clear();
- m_empty = true;
- m_fastPathFlags = NoFastPath;
- m_advanceFunc = &SegmentedString::advanceEmpty;
- m_advanceAndUpdateLineNumberFunc = &SegmentedString::advanceEmpty;
- }
- m_currentChar = m_currentString.m_length ? m_currentString.getCurrentChar() : 0;
-}
-
-void SegmentedString::advanceAndUpdateLineNumberSlowCase()
-{
- if (m_pushedChar1) {
- m_pushedChar1 = m_pushedChar2;
- m_pushedChar2 = 0;
-
- if (m_pushedChar1) {
- m_currentChar = m_pushedChar1;
- return;
- }
-
- updateAdvanceFunctionPointers();
- } else if (m_currentString.m_length) {
- if (m_currentString.getCurrentChar() == '\n' && m_currentString.doNotExcludeLineNumbers()) {
- ++m_currentLine;
- // Plus 1 because numberOfCharactersConsumed value hasn't incremented yet; it does with m_length decrement below.
- m_numberOfCharactersConsumedPriorToCurrentLine = numberOfCharactersConsumed() + 1;
- }
- if (--m_currentString.m_length == 0)
- advanceSubstring();
- else
- m_currentString.incrementAndGetCurrentChar(); // Only need the ++
- } else if (!isComposite()) {
- m_currentString.clear();
- m_empty = true;
- m_fastPathFlags = NoFastPath;
- m_advanceFunc = &SegmentedString::advanceEmpty;
- m_advanceAndUpdateLineNumberFunc = &SegmentedString::advanceEmpty;
- }
-
- m_currentChar = m_currentString.m_length ? m_currentString.getCurrentChar() : 0;
-}
-
-void SegmentedString::advanceEmpty()
-{
- ASSERT(!m_currentString.m_length && !isComposite());
- m_currentChar = 0;
-}
-
-void SegmentedString::updateSlowCaseFunctionPointers()
-{
- m_fastPathFlags = NoFastPath;
- m_advanceFunc = &SegmentedString::advanceSlowCase;
- m_advanceAndUpdateLineNumberFunc = &SegmentedString::advanceAndUpdateLineNumberSlowCase;
-}
-
-OrdinalNumber SegmentedString::currentLine() const
-{
- return OrdinalNumber::fromZeroBasedInt(m_currentLine);
-}
-
-OrdinalNumber SegmentedString::currentColumn() const
-{
- int zeroBasedColumn = numberOfCharactersConsumed() - m_numberOfCharactersConsumedPriorToCurrentLine;
- return OrdinalNumber::fromZeroBasedInt(zeroBasedColumn);
-}
-
-void SegmentedString::setCurrentPosition(OrdinalNumber line, OrdinalNumber columnAftreProlog, int prologLength)
-{
- m_currentLine = line.zeroBasedInt();
- m_numberOfCharactersConsumedPriorToCurrentLine = numberOfCharactersConsumed() + prologLength - columnAftreProlog.zeroBasedInt();
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/text/SegmentedString.h b/chromium/third_party/WebKit/Source/core/platform/text/SegmentedString.h
deleted file mode 100644
index 43647f08226..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/text/SegmentedString.h
+++ /dev/null
@@ -1,422 +0,0 @@
-/*
- Copyright (C) 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#ifndef SegmentedString_h
-#define SegmentedString_h
-
-#include "wtf/Deque.h"
-#include "wtf/text/StringBuilder.h"
-#include "wtf/text/TextPosition.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class SegmentedString;
-
-class SegmentedSubstring {
-public:
- SegmentedSubstring()
- : m_length(0)
- , m_doNotExcludeLineNumbers(true)
- , m_is8Bit(false)
- {
- m_data.string16Ptr = 0;
- }
-
- SegmentedSubstring(const String& str)
- : m_length(str.length())
- , m_doNotExcludeLineNumbers(true)
- , m_string(str)
- {
- if (m_length) {
- if (m_string.is8Bit()) {
- m_is8Bit = true;
- m_data.string8Ptr = m_string.characters8();
- } else {
- m_is8Bit = false;
- m_data.string16Ptr = m_string.characters16();
- }
- } else
- m_is8Bit = false;
- }
-
- void clear() { m_length = 0; m_data.string16Ptr = 0; m_is8Bit = false;}
-
- bool is8Bit() { return m_is8Bit; }
-
- bool excludeLineNumbers() const { return !m_doNotExcludeLineNumbers; }
- bool doNotExcludeLineNumbers() const { return m_doNotExcludeLineNumbers; }
-
- void setExcludeLineNumbers() { m_doNotExcludeLineNumbers = false; }
-
- int numberOfCharactersConsumed() const { return m_string.length() - m_length; }
-
- void appendTo(StringBuilder& builder) const
- {
- int offset = m_string.length() - m_length;
-
- if (!offset) {
- if (m_length)
- builder.append(m_string);
- } else
- builder.append(m_string.substring(offset, m_length));
- }
-
- UChar getCurrentChar8()
- {
- return *m_data.string8Ptr;
- }
-
- UChar getCurrentChar16()
- {
- return m_data.string16Ptr ? *m_data.string16Ptr : 0;
- }
-
- UChar incrementAndGetCurrentChar8()
- {
- ASSERT(m_data.string8Ptr);
- return *++m_data.string8Ptr;
- }
-
- UChar incrementAndGetCurrentChar16()
- {
- ASSERT(m_data.string16Ptr);
- return *++m_data.string16Ptr;
- }
-
- String currentSubString(unsigned length)
- {
- int offset = m_string.length() - m_length;
- return m_string.substring(offset, length);
- }
-
- ALWAYS_INLINE UChar getCurrentChar()
- {
- ASSERT(m_length);
- if (is8Bit())
- return getCurrentChar8();
- return getCurrentChar16();
- }
-
- ALWAYS_INLINE UChar incrementAndGetCurrentChar()
- {
- ASSERT(m_length);
- if (is8Bit())
- return incrementAndGetCurrentChar8();
- return incrementAndGetCurrentChar16();
- }
-
-public:
- union {
- const LChar* string8Ptr;
- const UChar* string16Ptr;
- } m_data;
- int m_length;
-
-private:
- bool m_doNotExcludeLineNumbers;
- bool m_is8Bit;
- String m_string;
-};
-
-class SegmentedString {
-public:
- SegmentedString()
- : m_pushedChar1(0)
- , m_pushedChar2(0)
- , m_currentChar(0)
- , m_numberOfCharactersConsumedPriorToCurrentString(0)
- , m_numberOfCharactersConsumedPriorToCurrentLine(0)
- , m_currentLine(0)
- , m_closed(false)
- , m_empty(true)
- , m_fastPathFlags(NoFastPath)
- , m_advanceFunc(&SegmentedString::advanceEmpty)
- , m_advanceAndUpdateLineNumberFunc(&SegmentedString::advanceEmpty)
- {
- }
-
- SegmentedString(const String& str)
- : m_pushedChar1(0)
- , m_pushedChar2(0)
- , m_currentString(str)
- , m_currentChar(0)
- , m_numberOfCharactersConsumedPriorToCurrentString(0)
- , m_numberOfCharactersConsumedPriorToCurrentLine(0)
- , m_currentLine(0)
- , m_closed(false)
- , m_empty(!str.length())
- , m_fastPathFlags(NoFastPath)
- {
- if (m_currentString.m_length)
- m_currentChar = m_currentString.getCurrentChar();
- updateAdvanceFunctionPointers();
- }
-
- SegmentedString(const SegmentedString&);
-
- const SegmentedString& operator=(const SegmentedString&);
-
- void clear();
- void close();
-
- void append(const SegmentedString&);
- void prepend(const SegmentedString&);
-
- bool excludeLineNumbers() const { return m_currentString.excludeLineNumbers(); }
- void setExcludeLineNumbers();
-
- void push(UChar c)
- {
- if (!m_pushedChar1) {
- m_pushedChar1 = c;
- m_currentChar = m_pushedChar1 ? m_pushedChar1 : m_currentString.getCurrentChar();
- updateSlowCaseFunctionPointers();
- } else {
- ASSERT(!m_pushedChar2);
- m_pushedChar2 = c;
- }
- }
-
- bool isEmpty() const { return m_empty; }
- unsigned length() const;
-
- bool isClosed() const { return m_closed; }
-
- enum LookAheadResult {
- DidNotMatch,
- DidMatch,
- NotEnoughCharacters,
- };
-
- LookAheadResult lookAhead(const String& string) { return lookAheadInline(string, true); }
- LookAheadResult lookAheadIgnoringCase(const String& string) { return lookAheadInline(string, false); }
-
- void advance()
- {
- if (m_fastPathFlags & Use8BitAdvance) {
- ASSERT(!m_pushedChar1);
- bool haveOneCharacterLeft = (--m_currentString.m_length == 1);
- m_currentChar = m_currentString.incrementAndGetCurrentChar8();
-
- if (!haveOneCharacterLeft)
- return;
-
- updateSlowCaseFunctionPointers();
-
- return;
- }
-
- (this->*m_advanceFunc)();
- }
-
- inline void advanceAndUpdateLineNumber()
- {
- if (m_fastPathFlags & Use8BitAdvance) {
- ASSERT(!m_pushedChar1);
-
- bool haveNewLine = (m_currentChar == '\n') & !!(m_fastPathFlags & Use8BitAdvanceAndUpdateLineNumbers);
- bool haveOneCharacterLeft = (--m_currentString.m_length == 1);
-
- m_currentChar = m_currentString.incrementAndGetCurrentChar8();
-
- if (!(haveNewLine | haveOneCharacterLeft))
- return;
-
- if (haveNewLine) {
- ++m_currentLine;
- m_numberOfCharactersConsumedPriorToCurrentLine = m_numberOfCharactersConsumedPriorToCurrentString + m_currentString.numberOfCharactersConsumed();
- }
-
- if (haveOneCharacterLeft)
- updateSlowCaseFunctionPointers();
-
- return;
- }
-
- (this->*m_advanceAndUpdateLineNumberFunc)();
- }
-
- void advanceAndASSERT(UChar expectedCharacter)
- {
- ASSERT_UNUSED(expectedCharacter, currentChar() == expectedCharacter);
- advance();
- }
-
- void advanceAndASSERTIgnoringCase(UChar expectedCharacter)
- {
- ASSERT_UNUSED(expectedCharacter, WTF::Unicode::foldCase(currentChar()) == WTF::Unicode::foldCase(expectedCharacter));
- advance();
- }
-
- void advancePastNonNewline()
- {
- ASSERT(currentChar() != '\n');
- advance();
- }
-
- void advancePastNewlineAndUpdateLineNumber()
- {
- ASSERT(currentChar() == '\n');
- if (!m_pushedChar1 && m_currentString.m_length > 1) {
- int newLineFlag = m_currentString.doNotExcludeLineNumbers();
- m_currentLine += newLineFlag;
- if (newLineFlag)
- m_numberOfCharactersConsumedPriorToCurrentLine = numberOfCharactersConsumed() + 1;
- decrementAndCheckLength();
- m_currentChar = m_currentString.incrementAndGetCurrentChar();
- return;
- }
- advanceAndUpdateLineNumberSlowCase();
- }
-
- // Writes the consumed characters into consumedCharacters, which must
- // have space for at least |count| characters.
- void advance(unsigned count, UChar* consumedCharacters);
-
- bool escaped() const { return m_pushedChar1; }
-
- int numberOfCharactersConsumed() const
- {
- int numberOfPushedCharacters = 0;
- if (m_pushedChar1) {
- ++numberOfPushedCharacters;
- if (m_pushedChar2)
- ++numberOfPushedCharacters;
- }
- return m_numberOfCharactersConsumedPriorToCurrentString + m_currentString.numberOfCharactersConsumed() - numberOfPushedCharacters;
- }
-
- String toString() const;
-
- UChar currentChar() const { return m_currentChar; }
-
- // The method is moderately slow, comparing to currentLine method.
- OrdinalNumber currentColumn() const;
- OrdinalNumber currentLine() const;
- // Sets value of line/column variables. Column is specified indirectly by a parameter columnAftreProlog
- // which is a value of column that we should get after a prolog (first prologLength characters) has been consumed.
- void setCurrentPosition(OrdinalNumber line, OrdinalNumber columnAftreProlog, int prologLength);
-
-private:
- enum FastPathFlags {
- NoFastPath = 0,
- Use8BitAdvanceAndUpdateLineNumbers = 1 << 0,
- Use8BitAdvance = 1 << 1,
- };
-
- void append(const SegmentedSubstring&);
- void prepend(const SegmentedSubstring&);
-
- void advance8();
- void advance16();
- void advanceAndUpdateLineNumber8();
- void advanceAndUpdateLineNumber16();
- void advanceSlowCase();
- void advanceAndUpdateLineNumberSlowCase();
- void advanceEmpty();
- void advanceSubstring();
-
- void updateSlowCaseFunctionPointers();
-
- void decrementAndCheckLength()
- {
- ASSERT(m_currentString.m_length > 1);
- if (--m_currentString.m_length == 1)
- updateSlowCaseFunctionPointers();
- }
-
- void updateAdvanceFunctionPointers()
- {
- if ((m_currentString.m_length > 1) && !m_pushedChar1) {
- if (m_currentString.is8Bit()) {
- m_advanceFunc = &SegmentedString::advance8;
- m_fastPathFlags = Use8BitAdvance;
- if (m_currentString.doNotExcludeLineNumbers()) {
- m_advanceAndUpdateLineNumberFunc = &SegmentedString::advanceAndUpdateLineNumber8;
- m_fastPathFlags |= Use8BitAdvanceAndUpdateLineNumbers;
- } else
- m_advanceAndUpdateLineNumberFunc = &SegmentedString::advance8;
- return;
- }
-
- m_advanceFunc = &SegmentedString::advance16;
- m_fastPathFlags = NoFastPath;
- if (m_currentString.doNotExcludeLineNumbers())
- m_advanceAndUpdateLineNumberFunc = &SegmentedString::advanceAndUpdateLineNumber16;
- else
- m_advanceAndUpdateLineNumberFunc = &SegmentedString::advance16;
- return;
- }
-
- if (!m_currentString.m_length && !isComposite()) {
- m_advanceFunc = &SegmentedString::advanceEmpty;
- m_fastPathFlags = NoFastPath;
- m_advanceAndUpdateLineNumberFunc = &SegmentedString::advanceEmpty;
- }
-
- updateSlowCaseFunctionPointers();
- }
-
- inline LookAheadResult lookAheadInline(const String& string, bool caseSensitive)
- {
- if (!m_pushedChar1 && string.length() <= static_cast<unsigned>(m_currentString.m_length)) {
- String currentSubstring = m_currentString.currentSubString(string.length());
- if (currentSubstring.startsWith(string, caseSensitive))
- return DidMatch;
- return DidNotMatch;
- }
- return lookAheadSlowCase(string, caseSensitive);
- }
-
- LookAheadResult lookAheadSlowCase(const String& string, bool caseSensitive)
- {
- unsigned count = string.length();
- if (count > length())
- return NotEnoughCharacters;
- UChar* consumedCharacters;
- String consumedString = String::createUninitialized(count, consumedCharacters);
- advance(count, consumedCharacters);
- LookAheadResult result = DidNotMatch;
- if (consumedString.startsWith(string, caseSensitive))
- result = DidMatch;
- prepend(SegmentedString(consumedString));
- return result;
- }
-
- bool isComposite() const { return !m_substrings.isEmpty(); }
-
- UChar m_pushedChar1;
- UChar m_pushedChar2;
- SegmentedSubstring m_currentString;
- UChar m_currentChar;
- int m_numberOfCharactersConsumedPriorToCurrentString;
- int m_numberOfCharactersConsumedPriorToCurrentLine;
- int m_currentLine;
- Deque<SegmentedSubstring> m_substrings;
- bool m_closed;
- bool m_empty;
- unsigned char m_fastPathFlags;
- void (SegmentedString::*m_advanceFunc)();
- void (SegmentedString::*m_advanceAndUpdateLineNumberFunc)();
-};
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/text/SuffixTree.h b/chromium/third_party/WebKit/Source/core/platform/text/SuffixTree.h
deleted file mode 100644
index cad0a9fcb16..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/text/SuffixTree.h
+++ /dev/null
@@ -1,122 +0,0 @@
-/*
- * Copyright (C) 2010 Adam Barth. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SuffixTree_h
-#define SuffixTree_h
-
-#include "wtf/Vector.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class UnicodeCodebook {
-public:
- static int codeWord(UChar c) { return c; }
- enum { codeSize = 1 << 8 * sizeof(UChar) };
-};
-
-class ASCIICodebook {
-public:
- static int codeWord(UChar c) { return c & (codeSize - 1); }
- enum { codeSize = 1 << (8 * sizeof(char) - 1) };
-};
-
-template<typename Codebook>
-class SuffixTree {
-public:
- SuffixTree(const String& text, unsigned depth)
- : m_depth(depth)
- , m_leaf(true)
- {
- build(text);
- }
-
- bool mightContain(const String& query)
- {
- Node* current = &m_root;
- int limit = std::min(m_depth, query.length());
- for (int i = 0; i < limit; ++i) {
- current = current->at(Codebook::codeWord(query[i]));
- if (!current)
- return false;
- }
- return true;
- }
-
-private:
- class Node {
- public:
- Node(bool isLeaf = false)
- {
- m_children.resize(Codebook::codeSize);
- m_children.fill(0);
- m_isLeaf = isLeaf;
- }
-
- ~Node()
- {
- for (unsigned i = 0; i < m_children.size(); ++i) {
- Node* child = m_children.at(i);
- if (child && !child->m_isLeaf)
- delete child;
- }
- }
-
- Node*& at(int codeWord) { return m_children.at(codeWord); }
-
- private:
- typedef Vector<Node*, Codebook::codeSize> ChildrenVector;
-
- ChildrenVector m_children;
- bool m_isLeaf;
- };
-
- void build(const String& text)
- {
- for (unsigned base = 0; base < text.length(); ++base) {
- Node* current = &m_root;
- unsigned limit = std::min(base + m_depth, text.length());
- for (unsigned offset = 0; base + offset < limit; ++offset) {
- ASSERT(current != &m_leaf);
- Node*& child = current->at(Codebook::codeWord(text[base + offset]));
- if (!child)
- child = base + offset + 1 == limit ? &m_leaf : new Node();
- current = child;
- }
- }
- }
-
- Node m_root;
- unsigned m_depth;
-
- // Instead of allocating a fresh empty leaf node for ever leaf in the tree
- // (there can be a lot of these), we alias all the leaves to this "static"
- // leaf node.
- Node m_leaf;
-};
-
-} // namespace WebCore
-
-#endif // SuffixTree_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/text/TextBoundaries.cpp b/chromium/third_party/WebKit/Source/core/platform/text/TextBoundaries.cpp
deleted file mode 100644
index df638b6f6a7..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/text/TextBoundaries.cpp
+++ /dev/null
@@ -1,104 +0,0 @@
-/*
- * Copyright (C) 2006, 2007 Apple Inc. All rights reserved.
- * Copyright (C) 2009 Dominik Röttsches <dominik.roettsches@access-company.com>
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/text/TextBoundaries.h"
-
-#include "core/platform/text/TextBreakIterator.h"
-#include "wtf/text/StringImpl.h"
-#include "wtf/unicode/Unicode.h"
-
-using namespace WTF;
-using namespace Unicode;
-
-namespace WebCore {
-
-int endOfFirstWordBoundaryContext(const UChar* characters, int length)
-{
- for (int i = 0; i < length; ) {
- int first = i;
- UChar32 ch;
- U16_NEXT(characters, i, length, ch);
- if (!requiresContextForWordBoundary(ch))
- return first;
- }
- return length;
-}
-
-int startOfLastWordBoundaryContext(const UChar* characters, int length)
-{
- for (int i = length; i > 0; ) {
- int last = i;
- UChar32 ch;
- U16_PREV(characters, 0, i, ch);
- if (!requiresContextForWordBoundary(ch))
- return last;
- }
- return 0;
-}
-
-int findNextWordFromIndex(const UChar* chars, int len, int position, bool forward)
-{
- TextBreakIterator* it = wordBreakIterator(chars, len);
-
- if (forward) {
- position = textBreakFollowing(it, position);
- while (position != TextBreakDone) {
- // We stop searching when the character preceeding the break
- // is alphanumeric.
- if (position < len && isAlphanumeric(chars[position - 1]))
- return position;
-
- position = textBreakFollowing(it, position);
- }
-
- return len;
- } else {
- position = textBreakPreceding(it, position);
- while (position != TextBreakDone) {
- // We stop searching when the character following the break
- // is alphanumeric.
- if (position > 0 && isAlphanumeric(chars[position]))
- return position;
-
- position = textBreakPreceding(it, position);
- }
-
- return 0;
- }
-}
-
-void findWordBoundary(const UChar* chars, int len, int position, int* start, int* end)
-{
- TextBreakIterator* it = wordBreakIterator(chars, len);
- *end = textBreakFollowing(it, position);
- if (*end < 0)
- *end = textBreakLast(it);
- *start = textBreakPrevious(it);
-}
-
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/text/TextBoundaries.h b/chromium/third_party/WebKit/Source/core/platform/text/TextBoundaries.h
deleted file mode 100644
index 81613e5416a..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/text/TextBoundaries.h
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Copyright (C) 2004, 2006 Apple Computer, Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TextBoundaries_h
-#define TextBoundaries_h
-
-#include "wtf/unicode/Unicode.h"
-
-namespace WebCore {
-
- inline bool requiresContextForWordBoundary(UChar32 ch)
- {
- return WTF::Unicode::hasLineBreakingPropertyComplexContext(ch);
- }
-
- int endOfFirstWordBoundaryContext(const UChar* characters, int length);
- int startOfLastWordBoundaryContext(const UChar* characters, int length);
-
- void findWordBoundary(const UChar*, int len, int position, int* start, int* end);
- int findNextWordFromIndex(const UChar*, int len, int position, bool forward);
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/text/TextBreakIterator.cpp b/chromium/third_party/WebKit/Source/core/platform/text/TextBreakIterator.cpp
deleted file mode 100644
index 9af8c5c1e87..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/text/TextBreakIterator.cpp
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * (C) 1999 Lars Knoll (knoll@kde.org)
- * Copyright (C) 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
- * Copyright (C) 2007-2009 Torch Mobile, Inc.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-#include "core/platform/text/TextBreakIterator.h"
-
-namespace WebCore {
-
-unsigned numGraphemeClusters(const String& string)
-{
- unsigned stringLength = string.length();
-
- if (!stringLength)
- return 0;
-
- // The only Latin-1 Extended Grapheme Cluster is CR LF
- if (string.is8Bit() && !string.contains('\r'))
- return stringLength;
-
- NonSharedCharacterBreakIterator it(string);
- if (!it)
- return stringLength;
-
- unsigned num = 0;
- while (it.next() != TextBreakDone)
- ++num;
- return num;
-}
-
-unsigned numCharactersInGraphemeClusters(const String& string, unsigned numGraphemeClusters)
-{
- unsigned stringLength = string.length();
-
- if (!stringLength)
- return 0;
-
- // The only Latin-1 Extended Grapheme Cluster is CR LF
- if (string.is8Bit() && !string.contains('\r'))
- return std::min(stringLength, numGraphemeClusters);
-
- NonSharedCharacterBreakIterator it(string);
- if (!it)
- return std::min(stringLength, numGraphemeClusters);
-
- for (unsigned i = 0; i < numGraphemeClusters; ++i) {
- if (it.next() == TextBreakDone)
- return stringLength;
- }
- return it.current();
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/text/TextBreakIterator.h b/chromium/third_party/WebKit/Source/core/platform/text/TextBreakIterator.h
deleted file mode 100644
index d6de5590e0e..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/text/TextBreakIterator.h
+++ /dev/null
@@ -1,242 +0,0 @@
-/*
- * Copyright (C) 2006 Lars Knoll <lars@trolltech.com>
- * Copyright (C) 2007, 2011, 2012 Apple Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#ifndef TextBreakIterator_h
-#define TextBreakIterator_h
-
-#include "wtf/text/AtomicString.h"
-#include "wtf/unicode/Unicode.h"
-
-namespace WebCore {
-
-class TextBreakIterator;
-
-// Note: The returned iterator is good only until you get another iterator, with the exception of acquireLineBreakIterator.
-
-// This is similar to character break iterator in most cases, but is subject to
-// platform UI conventions. One notable example where this can be different
-// from character break iterator is Thai prepend characters, see bug 24342.
-// Use this for insertion point and selection manipulations.
-TextBreakIterator* cursorMovementIterator(const UChar*, int length);
-
-TextBreakIterator* wordBreakIterator(const String&, int start, int length);
-TextBreakIterator* wordBreakIterator(const UChar*, int length);
-TextBreakIterator* acquireLineBreakIterator(const LChar*, int length, const AtomicString& locale, const UChar* priorContext, unsigned priorContextLength);
-TextBreakIterator* acquireLineBreakIterator(const UChar*, int length, const AtomicString& locale, const UChar* priorContext, unsigned priorContextLength);
-void releaseLineBreakIterator(TextBreakIterator*);
-TextBreakIterator* sentenceBreakIterator(const UChar*, int length);
-
-int textBreakFirst(TextBreakIterator*);
-int textBreakLast(TextBreakIterator*);
-int textBreakNext(TextBreakIterator*);
-int textBreakPrevious(TextBreakIterator*);
-int textBreakCurrent(TextBreakIterator*);
-int textBreakPreceding(TextBreakIterator*, int);
-int textBreakFollowing(TextBreakIterator*, int);
-bool isTextBreak(TextBreakIterator*, int);
-bool isWordTextBreak(TextBreakIterator*);
-
-const int TextBreakDone = -1;
-
-class LazyLineBreakIterator {
-public:
- LazyLineBreakIterator()
- : m_iterator(0)
- , m_cachedPriorContext(0)
- , m_cachedPriorContextLength(0)
- {
- resetPriorContext();
- }
-
- LazyLineBreakIterator(String string, const AtomicString& locale = AtomicString())
- : m_string(string)
- , m_locale(locale)
- , m_iterator(0)
- , m_cachedPriorContext(0)
- , m_cachedPriorContextLength(0)
- {
- resetPriorContext();
- }
-
- ~LazyLineBreakIterator()
- {
- if (m_iterator)
- releaseLineBreakIterator(m_iterator);
- }
-
- String string() const { return m_string; }
-
- UChar lastCharacter() const
- {
- COMPILE_ASSERT(WTF_ARRAY_LENGTH(m_priorContext) == 2, TextBreakIterator_unexpected_prior_context_length);
- return m_priorContext[1];
- }
-
- UChar secondToLastCharacter() const
- {
- COMPILE_ASSERT(WTF_ARRAY_LENGTH(m_priorContext) == 2, TextBreakIterator_unexpected_prior_context_length);
- return m_priorContext[0];
- }
-
- void setPriorContext(UChar last, UChar secondToLast)
- {
- COMPILE_ASSERT(WTF_ARRAY_LENGTH(m_priorContext) == 2, TextBreakIterator_unexpected_prior_context_length);
- m_priorContext[0] = secondToLast;
- m_priorContext[1] = last;
- }
-
- void updatePriorContext(UChar last)
- {
- COMPILE_ASSERT(WTF_ARRAY_LENGTH(m_priorContext) == 2, TextBreakIterator_unexpected_prior_context_length);
- m_priorContext[0] = m_priorContext[1];
- m_priorContext[1] = last;
- }
-
- void resetPriorContext()
- {
- COMPILE_ASSERT(WTF_ARRAY_LENGTH(m_priorContext) == 2, TextBreakIterator_unexpected_prior_context_length);
- m_priorContext[0] = 0;
- m_priorContext[1] = 0;
- }
-
- unsigned priorContextLength() const
- {
- unsigned priorContextLength = 0;
- COMPILE_ASSERT(WTF_ARRAY_LENGTH(m_priorContext) == 2, TextBreakIterator_unexpected_prior_context_length);
- if (m_priorContext[1]) {
- ++priorContextLength;
- if (m_priorContext[0])
- ++priorContextLength;
- }
- return priorContextLength;
- }
-
- // Obtain text break iterator, possibly previously cached, where this iterator is (or has been)
- // initialized to use the previously stored string as the primary breaking context and using
- // previously stored prior context if non-empty.
- TextBreakIterator* get(unsigned priorContextLength)
- {
- ASSERT(priorContextLength <= priorContextCapacity);
- const UChar* priorContext = priorContextLength ? &m_priorContext[priorContextCapacity - priorContextLength] : 0;
- if (!m_iterator) {
- if (m_string.is8Bit())
- m_iterator = acquireLineBreakIterator(m_string.characters8(), m_string.length(), m_locale, priorContext, priorContextLength);
- else
- m_iterator = acquireLineBreakIterator(m_string.characters16(), m_string.length(), m_locale, priorContext, priorContextLength);
- m_cachedPriorContext = priorContext;
- m_cachedPriorContextLength = priorContextLength;
- } else if (priorContext != m_cachedPriorContext || priorContextLength != m_cachedPriorContextLength) {
- this->resetStringAndReleaseIterator(m_string, m_locale);
- return this->get(priorContextLength);
- }
- return m_iterator;
- }
-
- void resetStringAndReleaseIterator(String string, const AtomicString& locale)
- {
- if (m_iterator)
- releaseLineBreakIterator(m_iterator);
-
- m_string = string;
- m_locale = locale;
- m_iterator = 0;
- m_cachedPriorContext = 0;
- m_cachedPriorContextLength = 0;
- }
-
-private:
- static const unsigned priorContextCapacity = 2;
- String m_string;
- AtomicString m_locale;
- TextBreakIterator* m_iterator;
- UChar m_priorContext[priorContextCapacity];
- const UChar* m_cachedPriorContext;
- unsigned m_cachedPriorContextLength;
-};
-
-// Iterates over "extended grapheme clusters", as defined in UAX #29.
-// Note that platform implementations may be less sophisticated - e.g. ICU prior to
-// version 4.0 only supports "legacy grapheme clusters".
-// Use this for general text processing, e.g. string truncation.
-
-class NonSharedCharacterBreakIterator {
- WTF_MAKE_NONCOPYABLE(NonSharedCharacterBreakIterator);
-public:
- explicit NonSharedCharacterBreakIterator(const String&);
- NonSharedCharacterBreakIterator(const UChar*, unsigned length);
- ~NonSharedCharacterBreakIterator();
-
- int next();
- int current();
-
- bool isBreak(int offset) const;
- int preceding(int offset) const;
- int following(int offset) const;
-
- bool operator!() const
- {
- return !m_is8Bit && !m_iterator;
- }
-
-private:
- void createIteratorForBuffer(const UChar*, unsigned length);
-
- unsigned clusterLengthStartingAt(unsigned offset) const
- {
- ASSERT(m_is8Bit);
- // The only Latin-1 Extended Grapheme Cluster is CR LF
- return isCRBeforeLF(offset) ? 2 : 1;
- }
-
- bool isCRBeforeLF(unsigned offset) const
- {
- ASSERT(m_is8Bit);
- return m_charaters8[offset] == '\r' && offset + 1 < m_length && m_charaters8[offset + 1] == '\n';
- }
-
- bool isLFAfterCR(unsigned offset) const
- {
- ASSERT(m_is8Bit);
- return m_charaters8[offset] == '\n' && offset >= 1 && m_charaters8[offset - 1] == '\r';
- }
-
- bool m_is8Bit;
-
- // For 8 bit strings, we implement the iterator ourselves.
- const LChar* m_charaters8;
- unsigned m_offset;
- unsigned m_length;
-
- // For 16 bit strings, we use a TextBreakIterator.
- TextBreakIterator* m_iterator;
-};
-
-// Counts the number of grapheme clusters. A surrogate pair or a sequence
-// of a non-combining character and following combining characters is
-// counted as 1 grapheme cluster.
-unsigned numGraphemeClusters(const String&);
-// Returns the number of characters which will be less than or equal to
-// the specified grapheme cluster length.
-unsigned numCharactersInGraphemeClusters(const String&, unsigned);
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/text/TextBreakIteratorICU.cpp b/chromium/third_party/WebKit/Source/core/platform/text/TextBreakIteratorICU.cpp
deleted file mode 100644
index e70b19f5e53..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/text/TextBreakIteratorICU.cpp
+++ /dev/null
@@ -1,829 +0,0 @@
-/*
- * Copyright (C) 2006 Lars Knoll <lars@trolltech.com>
- * Copyright (C) 2007, 2011, 2012 Apple Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#include "config.h"
-#include "core/platform/text/TextBreakIterator.h"
-
-#include "core/platform/text/LineBreakIteratorPoolICU.h"
-#include "wtf/ThreadingPrimitives.h"
-#include "wtf/text/WTFString.h"
-
-using namespace WTF;
-using namespace std;
-
-namespace WebCore {
-
-static TextBreakIterator* ensureIterator(bool& createdIterator, TextBreakIterator*& iterator, UBreakIteratorType type)
-{
- if (!createdIterator) {
- UErrorCode openStatus = U_ZERO_ERROR;
- iterator = reinterpret_cast<TextBreakIterator*>(ubrk_open(type, currentTextBreakLocaleID(), 0, 0, &openStatus));
- createdIterator = true;
- ASSERT_WITH_MESSAGE(U_SUCCESS(openStatus), "ICU could not open a break iterator: %s (%d)", u_errorName(openStatus), openStatus);
- }
- return iterator;
-}
-
-enum TextContext { NoContext, PriorContext, PrimaryContext };
-
-const int textBufferCapacity = 16;
-
-typedef struct {
- UText text;
- UChar buffer[textBufferCapacity];
-} UTextWithBuffer;
-
-static inline int64_t textPinIndex(int64_t& index, int64_t limit)
-{
- if (index < 0)
- index = 0;
- else if (index > limit)
- index = limit;
- return index;
-}
-
-static inline int64_t textNativeLength(UText* text)
-{
- return text->a + text->b;
-}
-
-// Relocate pointer from source into destination as required.
-static void textFixPointer(const UText* source, UText* destination, const void*& pointer)
-{
- if (pointer >= source->pExtra && pointer < static_cast<char*>(source->pExtra) + source->extraSize) {
- // Pointer references source extra buffer.
- pointer = static_cast<char*>(destination->pExtra) + (static_cast<const char*>(pointer) - static_cast<const char*>(source->pExtra));
- } else if (pointer >= source && pointer < reinterpret_cast<const char*>(source) + source->sizeOfStruct) {
- // Pointer references source text structure, but not source extra buffer.
- pointer = reinterpret_cast<char*>(destination) + (static_cast<const char*>(pointer) - reinterpret_cast<const char*>(source));
- }
-}
-
-static UText* textClone(UText* destination, const UText* source, UBool deep, UErrorCode* status)
-{
- ASSERT_UNUSED(deep, !deep);
- if (U_FAILURE(*status))
- return 0;
- int32_t extraSize = source->extraSize;
- destination = utext_setup(destination, extraSize, status);
- if (U_FAILURE(*status))
- return destination;
- void* extraNew = destination->pExtra;
- int32_t flags = destination->flags;
- int sizeToCopy = min(source->sizeOfStruct, destination->sizeOfStruct);
- memcpy(destination, source, sizeToCopy);
- destination->pExtra = extraNew;
- destination->flags = flags;
- memcpy(destination->pExtra, source->pExtra, extraSize);
- textFixPointer(source, destination, destination->context);
- textFixPointer(source, destination, destination->p);
- textFixPointer(source, destination, destination->q);
- ASSERT(!destination->r);
- const void * chunkContents = static_cast<const void*>(destination->chunkContents);
- textFixPointer(source, destination, chunkContents);
- destination->chunkContents = static_cast<const UChar*>(chunkContents);
- return destination;
-}
-
-static int32_t textExtract(UText* text, int64_t start, int64_t limit, UChar* destination, int32_t destinationCapacity, UErrorCode* errorCode)
-{
- UNUSED_PARAM(text);
- UNUSED_PARAM(start);
- UNUSED_PARAM(limit);
- UNUSED_PARAM(destination);
- UNUSED_PARAM(destinationCapacity);
- // In the present context, this text provider is used only with ICU functions
- // that do not perform an extract operation.
- ASSERT_NOT_REACHED();
- *errorCode = U_UNSUPPORTED_ERROR;
- return 0;
-}
-
-static void textClose(UText* text)
-{
- text->context = 0;
-}
-
-static inline TextContext textGetContext(const UText* text, int64_t nativeIndex, UBool forward)
-{
- if (!text->b || nativeIndex > text->b)
- return PrimaryContext;
- if (nativeIndex == text->b)
- return forward ? PrimaryContext : PriorContext;
- return PriorContext;
-}
-
-static inline TextContext textLatin1GetCurrentContext(const UText* text)
-{
- if (!text->chunkContents)
- return NoContext;
- return text->chunkContents == text->pExtra ? PrimaryContext : PriorContext;
-}
-
-static void textLatin1MoveInPrimaryContext(UText* text, int64_t nativeIndex, int64_t nativeLength, UBool forward)
-{
- ASSERT(text->chunkContents == text->pExtra);
- if (forward) {
- ASSERT(nativeIndex >= text->b && nativeIndex < nativeLength);
- text->chunkNativeStart = nativeIndex;
- text->chunkNativeLimit = nativeIndex + text->extraSize / sizeof(UChar);
- if (text->chunkNativeLimit > nativeLength)
- text->chunkNativeLimit = nativeLength;
- } else {
- ASSERT(nativeIndex > text->b && nativeIndex <= nativeLength);
- text->chunkNativeLimit = nativeIndex;
- text->chunkNativeStart = nativeIndex - text->extraSize / sizeof(UChar);
- if (text->chunkNativeStart < text->b)
- text->chunkNativeStart = text->b;
- }
- int64_t length = text->chunkNativeLimit - text->chunkNativeStart;
- // Ensure chunk length is well defined if computed length exceeds int32_t range.
- ASSERT(length <= numeric_limits<int32_t>::max());
- text->chunkLength = length <= numeric_limits<int32_t>::max() ? static_cast<int32_t>(length) : 0;
- text->nativeIndexingLimit = text->chunkLength;
- text->chunkOffset = forward ? 0 : text->chunkLength;
- StringImpl::copyChars(const_cast<UChar*>(text->chunkContents), static_cast<const LChar*>(text->p) + (text->chunkNativeStart - text->b), static_cast<unsigned>(text->chunkLength));
-}
-
-static void textLatin1SwitchToPrimaryContext(UText* text, int64_t nativeIndex, int64_t nativeLength, UBool forward)
-{
- ASSERT(!text->chunkContents || text->chunkContents == text->q);
- text->chunkContents = static_cast<const UChar*>(text->pExtra);
- textLatin1MoveInPrimaryContext(text, nativeIndex, nativeLength, forward);
-}
-
-static void textLatin1MoveInPriorContext(UText* text, int64_t nativeIndex, int64_t nativeLength, UBool forward)
-{
- ASSERT(text->chunkContents == text->q);
- ASSERT(forward ? nativeIndex < text->b : nativeIndex <= text->b);
- ASSERT_UNUSED(nativeLength, forward ? nativeIndex < nativeLength : nativeIndex <= nativeLength);
- ASSERT_UNUSED(forward, forward ? nativeIndex < nativeLength : nativeIndex <= nativeLength);
- text->chunkNativeStart = 0;
- text->chunkNativeLimit = text->b;
- text->chunkLength = text->b;
- text->nativeIndexingLimit = text->chunkLength;
- int64_t offset = nativeIndex - text->chunkNativeStart;
- // Ensure chunk offset is well defined if computed offset exceeds int32_t range or chunk length.
- ASSERT(offset <= numeric_limits<int32_t>::max());
- text->chunkOffset = min(offset <= numeric_limits<int32_t>::max() ? static_cast<int32_t>(offset) : 0, text->chunkLength);
-}
-
-static void textLatin1SwitchToPriorContext(UText* text, int64_t nativeIndex, int64_t nativeLength, UBool forward)
-{
- ASSERT(!text->chunkContents || text->chunkContents == text->pExtra);
- text->chunkContents = static_cast<const UChar*>(text->q);
- textLatin1MoveInPriorContext(text, nativeIndex, nativeLength, forward);
-}
-
-static inline bool textInChunkOrOutOfRange(UText* text, int64_t nativeIndex, int64_t nativeLength, UBool forward, UBool& isAccessible)
-{
- if (forward) {
- if (nativeIndex >= text->chunkNativeStart && nativeIndex < text->chunkNativeLimit) {
- int64_t offset = nativeIndex - text->chunkNativeStart;
- // Ensure chunk offset is well formed if computed offset exceeds int32_t range.
- ASSERT(offset <= numeric_limits<int32_t>::max());
- text->chunkOffset = offset <= numeric_limits<int32_t>::max() ? static_cast<int32_t>(offset) : 0;
- isAccessible = TRUE;
- return true;
- }
- if (nativeIndex >= nativeLength && text->chunkNativeLimit == nativeLength) {
- text->chunkOffset = text->chunkLength;
- isAccessible = FALSE;
- return true;
- }
- } else {
- if (nativeIndex > text->chunkNativeStart && nativeIndex <= text->chunkNativeLimit) {
- int64_t offset = nativeIndex - text->chunkNativeStart;
- // Ensure chunk offset is well formed if computed offset exceeds int32_t range.
- ASSERT(offset <= numeric_limits<int32_t>::max());
- text->chunkOffset = offset <= numeric_limits<int32_t>::max() ? static_cast<int32_t>(offset) : 0;
- isAccessible = TRUE;
- return true;
- }
- if (nativeIndex <= 0 && !text->chunkNativeStart) {
- text->chunkOffset = 0;
- isAccessible = FALSE;
- return true;
- }
- }
- return false;
-}
-
-static UBool textLatin1Access(UText* text, int64_t nativeIndex, UBool forward)
-{
- if (!text->context)
- return FALSE;
- int64_t nativeLength = textNativeLength(text);
- UBool isAccessible;
- if (textInChunkOrOutOfRange(text, nativeIndex, nativeLength, forward, isAccessible))
- return isAccessible;
- nativeIndex = textPinIndex(nativeIndex, nativeLength - 1);
- TextContext currentContext = textLatin1GetCurrentContext(text);
- TextContext newContext = textGetContext(text, nativeIndex, forward);
- ASSERT(newContext != NoContext);
- if (newContext == currentContext) {
- if (currentContext == PrimaryContext) {
- textLatin1MoveInPrimaryContext(text, nativeIndex, nativeLength, forward);
- } else {
- textLatin1MoveInPriorContext(text, nativeIndex, nativeLength, forward);
- }
- } else if (newContext == PrimaryContext) {
- textLatin1SwitchToPrimaryContext(text, nativeIndex, nativeLength, forward);
- } else {
- ASSERT(newContext == PriorContext);
- textLatin1SwitchToPriorContext(text, nativeIndex, nativeLength, forward);
- }
- return TRUE;
-}
-
-static const struct UTextFuncs textLatin1Funcs = {
- sizeof(UTextFuncs),
- 0, 0, 0,
- textClone,
- textNativeLength,
- textLatin1Access,
- textExtract,
- 0, 0, 0, 0,
- textClose,
- 0, 0, 0,
-};
-
-static void textInit(UText* text, const UTextFuncs* funcs, const void* string, unsigned length, const UChar* priorContext, int priorContextLength)
-{
- text->pFuncs = funcs;
- text->providerProperties = 1 << UTEXT_PROVIDER_STABLE_CHUNKS;
- text->context = string;
- text->p = string;
- text->a = length;
- text->q = priorContext;
- text->b = priorContextLength;
-}
-
-static UText* textOpenLatin1(UTextWithBuffer* utWithBuffer, const LChar* string, unsigned length, const UChar* priorContext, int priorContextLength, UErrorCode* status)
-{
- if (U_FAILURE(*status))
- return 0;
-
- if (!string || length > static_cast<unsigned>(numeric_limits<int32_t>::max())) {
- *status = U_ILLEGAL_ARGUMENT_ERROR;
- return 0;
- }
- UText* text = utext_setup(&utWithBuffer->text, sizeof(utWithBuffer->buffer), status);
- if (U_FAILURE(*status)) {
- ASSERT(!text);
- return 0;
- }
- textInit(text, &textLatin1Funcs, string, length, priorContext, priorContextLength);
- return text;
-}
-
-static inline TextContext textUTF16GetCurrentContext(const UText* text)
-{
- if (!text->chunkContents)
- return NoContext;
- return text->chunkContents == text->p ? PrimaryContext : PriorContext;
-}
-
-static void textUTF16MoveInPrimaryContext(UText* text, int64_t nativeIndex, int64_t nativeLength, UBool forward)
-{
- ASSERT(text->chunkContents == text->p);
- ASSERT_UNUSED(forward, forward ? nativeIndex >= text->b : nativeIndex > text->b);
- ASSERT_UNUSED(forward, forward ? nativeIndex < nativeLength : nativeIndex <= nativeLength);
- text->chunkNativeStart = text->b;
- text->chunkNativeLimit = nativeLength;
- int64_t length = text->chunkNativeLimit - text->chunkNativeStart;
- // Ensure chunk length is well defined if computed length exceeds int32_t range.
- ASSERT(length <= numeric_limits<int32_t>::max());
- text->chunkLength = length <= numeric_limits<int32_t>::max() ? static_cast<int32_t>(length) : 0;
- text->nativeIndexingLimit = text->chunkLength;
- int64_t offset = nativeIndex - text->chunkNativeStart;
- // Ensure chunk offset is well defined if computed offset exceeds int32_t range or chunk length.
- ASSERT(offset <= numeric_limits<int32_t>::max());
- text->chunkOffset = min(offset <= numeric_limits<int32_t>::max() ? static_cast<int32_t>(offset) : 0, text->chunkLength);
-}
-
-static void textUTF16SwitchToPrimaryContext(UText* text, int64_t nativeIndex, int64_t nativeLength, UBool forward)
-{
- ASSERT(!text->chunkContents || text->chunkContents == text->q);
- text->chunkContents = static_cast<const UChar*>(text->p);
- textUTF16MoveInPrimaryContext(text, nativeIndex, nativeLength, forward);
-}
-
-static void textUTF16MoveInPriorContext(UText* text, int64_t nativeIndex, int64_t nativeLength, UBool forward)
-{
- ASSERT(text->chunkContents == text->q);
- ASSERT(forward ? nativeIndex < text->b : nativeIndex <= text->b);
- ASSERT_UNUSED(nativeLength, forward ? nativeIndex < nativeLength : nativeIndex <= nativeLength);
- ASSERT_UNUSED(forward, forward ? nativeIndex < nativeLength : nativeIndex <= nativeLength);
- text->chunkNativeStart = 0;
- text->chunkNativeLimit = text->b;
- text->chunkLength = text->b;
- text->nativeIndexingLimit = text->chunkLength;
- int64_t offset = nativeIndex - text->chunkNativeStart;
- // Ensure chunk offset is well defined if computed offset exceeds int32_t range or chunk length.
- ASSERT(offset <= numeric_limits<int32_t>::max());
- text->chunkOffset = min(offset <= numeric_limits<int32_t>::max() ? static_cast<int32_t>(offset) : 0, text->chunkLength);
-}
-
-static void textUTF16SwitchToPriorContext(UText* text, int64_t nativeIndex, int64_t nativeLength, UBool forward)
-{
- ASSERT(!text->chunkContents || text->chunkContents == text->p);
- text->chunkContents = static_cast<const UChar*>(text->q);
- textUTF16MoveInPriorContext(text, nativeIndex, nativeLength, forward);
-}
-
-static UBool textUTF16Access(UText* text, int64_t nativeIndex, UBool forward)
-{
- if (!text->context)
- return FALSE;
- int64_t nativeLength = textNativeLength(text);
- UBool isAccessible;
- if (textInChunkOrOutOfRange(text, nativeIndex, nativeLength, forward, isAccessible))
- return isAccessible;
- nativeIndex = textPinIndex(nativeIndex, nativeLength - 1);
- TextContext currentContext = textUTF16GetCurrentContext(text);
- TextContext newContext = textGetContext(text, nativeIndex, forward);
- ASSERT(newContext != NoContext);
- if (newContext == currentContext) {
- if (currentContext == PrimaryContext) {
- textUTF16MoveInPrimaryContext(text, nativeIndex, nativeLength, forward);
- } else {
- textUTF16MoveInPriorContext(text, nativeIndex, nativeLength, forward);
- }
- } else if (newContext == PrimaryContext) {
- textUTF16SwitchToPrimaryContext(text, nativeIndex, nativeLength, forward);
- } else {
- ASSERT(newContext == PriorContext);
- textUTF16SwitchToPriorContext(text, nativeIndex, nativeLength, forward);
- }
- return TRUE;
-}
-
-static const struct UTextFuncs textUTF16Funcs = {
- sizeof(UTextFuncs),
- 0, 0, 0,
- textClone,
- textNativeLength,
- textUTF16Access,
- textExtract,
- 0, 0, 0, 0,
- textClose,
- 0, 0, 0,
-};
-
-static UText* textOpenUTF16(UText* text, const UChar* string, unsigned length, const UChar* priorContext, int priorContextLength, UErrorCode* status)
-{
- if (U_FAILURE(*status))
- return 0;
-
- if (!string || length > static_cast<unsigned>(numeric_limits<int32_t>::max())) {
- *status = U_ILLEGAL_ARGUMENT_ERROR;
- return 0;
- }
-
- text = utext_setup(text, 0, status);
- if (U_FAILURE(*status)) {
- ASSERT(!text);
- return 0;
- }
- textInit(text, &textUTF16Funcs, string, length, priorContext, priorContextLength);
- return text;
-}
-
-static UText emptyText = UTEXT_INITIALIZER;
-
-static TextBreakIterator* setUpIterator(bool& createdIterator, TextBreakIterator*& iterator, UBreakIteratorType type, const UChar* string, int length)
-{
- if (!string)
- return 0;
-
- iterator = ensureIterator(createdIterator, iterator, type);
- if (!iterator)
- return 0;
-
- UErrorCode setTextStatus = U_ZERO_ERROR;
- ubrk_setText(reinterpret_cast<UBreakIterator*>(iterator), string, length, &setTextStatus);
- if (U_FAILURE(setTextStatus))
- return 0;
-
- return iterator;
-}
-
-static TextBreakIterator* setUpIterator(bool& createdIterator, TextBreakIterator*& iterator, UBreakIteratorType type, const LChar* string, int length)
-{
- if (!string)
- return 0;
-
- iterator = ensureIterator(createdIterator, iterator, type);
- if (!iterator)
- return 0;
-
- UTextWithBuffer textLocal;
- textLocal.text = emptyText;
- textLocal.text.extraSize = sizeof(textLocal.buffer);
- textLocal.text.pExtra = textLocal.buffer;
-
- UErrorCode openStatus = U_ZERO_ERROR;
- UText* text = textOpenLatin1(&textLocal, string, length, 0, 0, &openStatus);
- if (U_FAILURE(openStatus)) {
- LOG_ERROR("textOpenLatin1 failed with status %d", openStatus);
- return 0;
- }
-
- UErrorCode setTextStatus = U_ZERO_ERROR;
- ubrk_setUText(reinterpret_cast<UBreakIterator*>(iterator), text, &setTextStatus);
- if (U_FAILURE(setTextStatus)) {
- LOG_ERROR("ubrk_setUText failed with status %d", setTextStatus);
- // FIXME: Do we need to call utext_close(text) here?
- return 0;
- }
-
- utext_close(text);
-
- return iterator;
-}
-
-static TextBreakIterator* wordBreakIterator(const LChar* string, int length)
-{
- static bool createdWordBreakIterator8 = false;
- static TextBreakIterator* staticWordBreakIterator8;
- return setUpIterator(createdWordBreakIterator8,
- staticWordBreakIterator8, UBRK_WORD, string, length);
-}
-
-TextBreakIterator* wordBreakIterator(const UChar* string, int length)
-{
- static bool createdWordBreakIterator16 = false;
- static TextBreakIterator* staticWordBreakIterator16;
- return setUpIterator(createdWordBreakIterator16,
- staticWordBreakIterator16, UBRK_WORD, string, length);
-}
-
-TextBreakIterator* wordBreakIterator(const String& string, int start, int length)
-{
- if (string.isEmpty())
- return 0;
- if (string.is8Bit())
- return wordBreakIterator(string.characters8() + start, length);
- return wordBreakIterator(string.characters16() + start, length);
-}
-
-TextBreakIterator* acquireLineBreakIterator(const LChar* string, int length, const AtomicString& locale, const UChar* priorContext, unsigned priorContextLength)
-{
- UBreakIterator* iterator = LineBreakIteratorPool::sharedPool().take(locale);
- if (!iterator)
- return 0;
-
- UTextWithBuffer textLocal;
- textLocal.text = emptyText;
- textLocal.text.extraSize = sizeof(textLocal.buffer);
- textLocal.text.pExtra = textLocal.buffer;
-
- UErrorCode openStatus = U_ZERO_ERROR;
- UText* text = textOpenLatin1(&textLocal, string, length, priorContext, priorContextLength, &openStatus);
- if (U_FAILURE(openStatus)) {
- LOG_ERROR("textOpenLatin1 failed with status %d", openStatus);
- return 0;
- }
-
- UErrorCode setTextStatus = U_ZERO_ERROR;
- ubrk_setUText(iterator, text, &setTextStatus);
- if (U_FAILURE(setTextStatus)) {
- // FIXME: Do we need to call utext_close(text) here?
- LOG_ERROR("ubrk_setUText failed with status %d", setTextStatus);
- return 0;
- }
-
- utext_close(text);
-
- return reinterpret_cast<TextBreakIterator*>(iterator);
-}
-
-TextBreakIterator* acquireLineBreakIterator(const UChar* string, int length, const AtomicString& locale, const UChar* priorContext, unsigned priorContextLength)
-{
- UBreakIterator* iterator = LineBreakIteratorPool::sharedPool().take(locale);
- if (!iterator)
- return 0;
-
- UText textLocal = UTEXT_INITIALIZER;
-
- UErrorCode openStatus = U_ZERO_ERROR;
- UText* text = textOpenUTF16(&textLocal, string, length, priorContext, priorContextLength, &openStatus);
- if (U_FAILURE(openStatus)) {
- LOG_ERROR("textOpenUTF16 failed with status %d", openStatus);
- return 0;
- }
-
- UErrorCode setTextStatus = U_ZERO_ERROR;
- ubrk_setUText(iterator, text, &setTextStatus);
- if (U_FAILURE(setTextStatus)) {
- // FIXME: Do we need to call utext_close(text) here?
- LOG_ERROR("ubrk_setUText failed with status %d", setTextStatus);
- return 0;
- }
-
- utext_close(text);
-
- return reinterpret_cast<TextBreakIterator*>(iterator);
-}
-
-void releaseLineBreakIterator(TextBreakIterator* iterator)
-{
- ASSERT_ARG(iterator, iterator);
-
- LineBreakIteratorPool::sharedPool().put(reinterpret_cast<UBreakIterator*>(iterator));
-}
-
-static TextBreakIterator* nonSharedCharacterBreakIterator;
-
-static inline bool compareAndSwapNonSharedCharacterBreakIterator(TextBreakIterator* expected, TextBreakIterator* newValue)
-{
- DEFINE_STATIC_LOCAL(Mutex, nonSharedCharacterBreakIteratorMutex, ());
- MutexLocker locker(nonSharedCharacterBreakIteratorMutex);
- if (nonSharedCharacterBreakIterator != expected)
- return false;
- nonSharedCharacterBreakIterator = newValue;
- return true;
-}
-
-NonSharedCharacterBreakIterator::NonSharedCharacterBreakIterator(const String& string)
- : m_is8Bit(true)
- , m_charaters8(0)
- , m_offset(0)
- , m_length(0)
- , m_iterator(0)
-{
- if (string.isEmpty())
- return;
-
- m_is8Bit = string.is8Bit();
-
- if (m_is8Bit) {
- m_charaters8 = string.characters8();
- m_offset = 0;
- m_length = string.length();
- return;
- }
-
- createIteratorForBuffer(string.characters16(), string.length());
-}
-
-NonSharedCharacterBreakIterator::NonSharedCharacterBreakIterator(const UChar* buffer, unsigned length)
- : m_is8Bit(false)
- , m_charaters8(0)
- , m_offset(0)
- , m_length(0)
- , m_iterator(0)
-{
- createIteratorForBuffer(buffer, length);
-}
-
-void NonSharedCharacterBreakIterator::createIteratorForBuffer(const UChar* buffer, unsigned length)
-{
- m_iterator = nonSharedCharacterBreakIterator;
- bool createdIterator = m_iterator && compareAndSwapNonSharedCharacterBreakIterator(m_iterator, 0);
- m_iterator = setUpIterator(createdIterator, m_iterator, UBRK_CHARACTER, buffer, length);
-}
-
-NonSharedCharacterBreakIterator::~NonSharedCharacterBreakIterator()
-{
- if (m_is8Bit)
- return;
- if (!compareAndSwapNonSharedCharacterBreakIterator(0, m_iterator))
- ubrk_close(reinterpret_cast<UBreakIterator*>(m_iterator));
-}
-
-int NonSharedCharacterBreakIterator::next()
-{
- if (!m_is8Bit)
- return textBreakNext(m_iterator);
-
- if (m_offset >= m_length)
- return TextBreakDone;
-
- m_offset += clusterLengthStartingAt(m_offset);
- return m_offset;
-}
-
-int NonSharedCharacterBreakIterator::current()
-{
- if (!m_is8Bit)
- return textBreakCurrent(m_iterator);
- return m_offset;
-}
-
-bool NonSharedCharacterBreakIterator::isBreak(int offset) const
-{
- if (!m_is8Bit)
- return isTextBreak(m_iterator, offset);
- return !isLFAfterCR(offset);
-}
-
-int NonSharedCharacterBreakIterator::preceding(int offset) const
-{
- if (!m_is8Bit)
- return textBreakPreceding(m_iterator, offset);
- if (offset <= 0)
- return TextBreakDone;
- if (isLFAfterCR(offset))
- return offset - 2;
- return offset - 1;
-}
-
-int NonSharedCharacterBreakIterator::following(int offset) const
-{
- if (!m_is8Bit)
- return textBreakFollowing(m_iterator, offset);
- if (static_cast<unsigned>(offset) >= m_length)
- return TextBreakDone;
- return offset + clusterLengthStartingAt(offset);
-}
-
-TextBreakIterator* sentenceBreakIterator(const UChar* string, int length)
-{
- static bool createdSentenceBreakIterator = false;
- static TextBreakIterator* staticSentenceBreakIterator;
- return setUpIterator(createdSentenceBreakIterator,
- staticSentenceBreakIterator, UBRK_SENTENCE, string, length);
-}
-
-int textBreakFirst(TextBreakIterator* iterator)
-{
- return ubrk_first(reinterpret_cast<UBreakIterator*>(iterator));
-}
-
-int textBreakLast(TextBreakIterator* iterator)
-{
- return ubrk_last(reinterpret_cast<UBreakIterator*>(iterator));
-}
-
-int textBreakNext(TextBreakIterator* iterator)
-{
- return ubrk_next(reinterpret_cast<UBreakIterator*>(iterator));
-}
-
-int textBreakPrevious(TextBreakIterator* iterator)
-{
- return ubrk_previous(reinterpret_cast<UBreakIterator*>(iterator));
-}
-
-int textBreakPreceding(TextBreakIterator* iterator, int pos)
-{
- return ubrk_preceding(reinterpret_cast<UBreakIterator*>(iterator), pos);
-}
-
-int textBreakFollowing(TextBreakIterator* iterator, int pos)
-{
- return ubrk_following(reinterpret_cast<UBreakIterator*>(iterator), pos);
-}
-
-int textBreakCurrent(TextBreakIterator* iterator)
-{
- return ubrk_current(reinterpret_cast<UBreakIterator*>(iterator));
-}
-
-bool isTextBreak(TextBreakIterator* iterator, int position)
-{
- return ubrk_isBoundary(reinterpret_cast<UBreakIterator*>(iterator), position);
-}
-
-bool isWordTextBreak(TextBreakIterator* iterator)
-{
- int ruleStatus = ubrk_getRuleStatus(reinterpret_cast<UBreakIterator*>(iterator));
- return ruleStatus != UBRK_WORD_NONE;
-}
-
-static TextBreakIterator* setUpIteratorWithRules(bool& createdIterator, TextBreakIterator*& iterator,
- const char* breakRules, const UChar* string, int length)
-{
- if (!string)
- return 0;
-
- if (!createdIterator) {
- UParseError parseStatus;
- UErrorCode openStatus = U_ZERO_ERROR;
- Vector<UChar> rules;
- String(breakRules).appendTo(rules);
- iterator = reinterpret_cast<TextBreakIterator*>(ubrk_openRules(rules.data(), rules.size(), 0, 0, &parseStatus, &openStatus));
- createdIterator = true;
- ASSERT_WITH_MESSAGE(U_SUCCESS(openStatus), "ICU could not open a break iterator: %s (%d)", u_errorName(openStatus), openStatus);
- }
- if (!iterator)
- return 0;
-
- UErrorCode setTextStatus = U_ZERO_ERROR;
- ubrk_setText(reinterpret_cast<UBreakIterator*>(iterator), string, length, &setTextStatus);
- if (U_FAILURE(setTextStatus))
- return 0;
-
- return iterator;
-}
-
-TextBreakIterator* cursorMovementIterator(const UChar* string, int length)
-{
- // This rule set is based on character-break iterator rules of ICU 4.0
- // <http://source.icu-project.org/repos/icu/icu/tags/release-4-0/source/data/brkitr/char.txt>.
- // The major differences from the original ones are listed below:
- // * Replaced '[\p{Grapheme_Cluster_Break = SpacingMark}]' with '[\p{General_Category = Spacing Mark} - $Extend]' for ICU 3.8 or earlier;
- // * Removed rules that prevent a cursor from moving after prepend characters (Bug 24342);
- // * Added rules that prevent a cursor from moving after virama signs of Indic languages except Tamil (Bug 15790), and;
- // * Added rules that prevent a cursor from moving before Japanese half-width katakara voiced marks.
- // * Added rules for regional indicator symbols.
- static const char* kRules =
- "$CR = [\\p{Grapheme_Cluster_Break = CR}];"
- "$LF = [\\p{Grapheme_Cluster_Break = LF}];"
- "$Control = [\\p{Grapheme_Cluster_Break = Control}];"
- "$VoiceMarks = [\\uFF9E\\uFF9F];" // Japanese half-width katakana voiced marks
- "$Extend = [\\p{Grapheme_Cluster_Break = Extend} $VoiceMarks - [\\u0E30 \\u0E32 \\u0E45 \\u0EB0 \\u0EB2]];"
- "$SpacingMark = [[\\p{General_Category = Spacing Mark}] - $Extend];"
- "$L = [\\p{Grapheme_Cluster_Break = L}];"
- "$V = [\\p{Grapheme_Cluster_Break = V}];"
- "$T = [\\p{Grapheme_Cluster_Break = T}];"
- "$LV = [\\p{Grapheme_Cluster_Break = LV}];"
- "$LVT = [\\p{Grapheme_Cluster_Break = LVT}];"
- "$Hin0 = [\\u0905-\\u0939];" // Devanagari Letter A,...,Ha
- "$HinV = \\u094D;" // Devanagari Sign Virama
- "$Hin1 = [\\u0915-\\u0939];" // Devanagari Letter Ka,...,Ha
- "$Ben0 = [\\u0985-\\u09B9];" // Bengali Letter A,...,Ha
- "$BenV = \\u09CD;" // Bengali Sign Virama
- "$Ben1 = [\\u0995-\\u09B9];" // Bengali Letter Ka,...,Ha
- "$Pan0 = [\\u0A05-\\u0A39];" // Gurmukhi Letter A,...,Ha
- "$PanV = \\u0A4D;" // Gurmukhi Sign Virama
- "$Pan1 = [\\u0A15-\\u0A39];" // Gurmukhi Letter Ka,...,Ha
- "$Guj0 = [\\u0A85-\\u0AB9];" // Gujarati Letter A,...,Ha
- "$GujV = \\u0ACD;" // Gujarati Sign Virama
- "$Guj1 = [\\u0A95-\\u0AB9];" // Gujarati Letter Ka,...,Ha
- "$Ori0 = [\\u0B05-\\u0B39];" // Oriya Letter A,...,Ha
- "$OriV = \\u0B4D;" // Oriya Sign Virama
- "$Ori1 = [\\u0B15-\\u0B39];" // Oriya Letter Ka,...,Ha
- "$Tel0 = [\\u0C05-\\u0C39];" // Telugu Letter A,...,Ha
- "$TelV = \\u0C4D;" // Telugu Sign Virama
- "$Tel1 = [\\u0C14-\\u0C39];" // Telugu Letter Ka,...,Ha
- "$Kan0 = [\\u0C85-\\u0CB9];" // Kannada Letter A,...,Ha
- "$KanV = \\u0CCD;" // Kannada Sign Virama
- "$Kan1 = [\\u0C95-\\u0CB9];" // Kannada Letter A,...,Ha
- "$Mal0 = [\\u0D05-\\u0D39];" // Malayalam Letter A,...,Ha
- "$MalV = \\u0D4D;" // Malayalam Sign Virama
- "$Mal1 = [\\u0D15-\\u0D39];" // Malayalam Letter A,...,Ha
- "$RI = [\\U0001F1E6-\\U0001F1FF];" // Emoji regional indicators
- "!!chain;"
- "!!forward;"
- "$CR $LF;"
- "$L ($L | $V | $LV | $LVT);"
- "($LV | $V) ($V | $T);"
- "($LVT | $T) $T;"
- "[^$Control $CR $LF] $Extend;"
- "[^$Control $CR $LF] $SpacingMark;"
- "$RI $RI / $RI;"
- "$RI $RI;"
- "$Hin0 $HinV $Hin1;" // Devanagari Virama (forward)
- "$Ben0 $BenV $Ben1;" // Bengali Virama (forward)
- "$Pan0 $PanV $Pan1;" // Gurmukhi Virama (forward)
- "$Guj0 $GujV $Guj1;" // Gujarati Virama (forward)
- "$Ori0 $OriV $Ori1;" // Oriya Virama (forward)
- "$Tel0 $TelV $Tel1;" // Telugu Virama (forward)
- "$Kan0 $KanV $Kan1;" // Kannada Virama (forward)
- "$Mal0 $MalV $Mal1;" // Malayalam Virama (forward)
- "!!reverse;"
- "$LF $CR;"
- "($L | $V | $LV | $LVT) $L;"
- "($V | $T) ($LV | $V);"
- "$T ($LVT | $T);"
- "$Extend [^$Control $CR $LF];"
- "$SpacingMark [^$Control $CR $LF];"
- "$RI $RI / $RI $RI;"
- "$RI $RI;"
- "$Hin1 $HinV $Hin0;" // Devanagari Virama (backward)
- "$Ben1 $BenV $Ben0;" // Bengali Virama (backward)
- "$Pan1 $PanV $Pan0;" // Gurmukhi Virama (backward)
- "$Guj1 $GujV $Guj0;" // Gujarati Virama (backward)
- "$Ori1 $OriV $Ori0;" // Gujarati Virama (backward)
- "$Tel1 $TelV $Tel0;" // Telugu Virama (backward)
- "$Kan1 $KanV $Kan0;" // Kannada Virama (backward)
- "$Mal1 $MalV $Mal0;" // Malayalam Virama (backward)
- "!!safe_reverse;"
- "!!safe_forward;";
- static bool createdCursorMovementIterator = false;
- static TextBreakIterator* staticCursorMovementIterator;
- return setUpIteratorWithRules(createdCursorMovementIterator, staticCursorMovementIterator, kRules, string, length);
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/text/TextBreakIteratorInternalICU.cpp b/chromium/third_party/WebKit/Source/core/platform/text/TextBreakIteratorInternalICU.cpp
deleted file mode 100644
index e70f85252b9..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/text/TextBreakIteratorInternalICU.cpp
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright (C) 2007 Apple Inc. All rights reserved.
- * Copyright (C) 2008, 2009 Google Inc.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
- * Boston, MA 02111-1307, USA.
- *
- */
-
-#include "config.h"
-#include "core/platform/text/TextBreakIteratorInternalICU.h"
-
-#include "core/platform/Language.h"
-#include "wtf/StdLibExtras.h"
-#include "wtf/text/CString.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-static const char* UILanguage()
-{
- // Chrome's UI language can be different from the OS UI language on Windows.
- // We want to return Chrome's UI language here.
- DEFINE_STATIC_LOCAL(CString, locale, (defaultLanguage().latin1()));
- return locale.data();
-}
-
-const char* currentSearchLocaleID()
-{
- return UILanguage();
-}
-
-const char* currentTextBreakLocaleID()
-{
- return UILanguage();
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/text/TextBreakIteratorInternalICU.h b/chromium/third_party/WebKit/Source/core/platform/text/TextBreakIteratorInternalICU.h
deleted file mode 100644
index 68b7003c35f..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/text/TextBreakIteratorInternalICU.h
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Copyright (C) 2007 Apple Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#ifndef TextBreakIteratorInternalICU_h
-#define TextBreakIteratorInternalICU_h
-
-// FIXME: Now that this handles locales for ICU, not just for text breaking,
-// this file and the various implementation files should be renamed.
-
-namespace WebCore {
-
- const char* currentSearchLocaleID();
- const char* currentTextBreakLocaleID();
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/text/TextCheckerClient.h b/chromium/third_party/WebKit/Source/core/platform/text/TextCheckerClient.h
deleted file mode 100644
index 046bb8abb52..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/text/TextCheckerClient.h
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Copyright (C) 2006, 2007 Apple Inc. All rights reserved.
- * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TextCheckerClient_h
-#define TextCheckerClient_h
-
-#include "core/platform/text/TextChecking.h"
-#include "wtf/Forward.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/Vector.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class TextCheckerClient {
-public:
- virtual ~TextCheckerClient() {}
-
- virtual bool shouldEraseMarkersAfterChangeSelection(TextCheckingType) const = 0;
- virtual void checkSpellingOfString(const String&, int* misspellingLocation, int* misspellingLength) = 0;
- virtual String getAutoCorrectSuggestionForMisspelledWord(const String& misspelledWord) = 0;
- virtual void checkGrammarOfString(const String&, Vector<GrammarDetail>&, int* badGrammarLocation, int* badGrammarLength) = 0;
- virtual void requestCheckingOfString(PassRefPtr<TextCheckingRequest>) = 0;
-};
-
-}
-
-#endif // TextCheckerClient_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/text/TextChecking.h b/chromium/third_party/WebKit/Source/core/platform/text/TextChecking.h
deleted file mode 100644
index a3d3f12beda..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/text/TextChecking.h
+++ /dev/null
@@ -1,115 +0,0 @@
-/*
- * Copyright (c) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TextChecking_h
-#define TextChecking_h
-
-#include "wtf/RefCounted.h"
-#include "wtf/Vector.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-enum TextCheckingType {
- TextCheckingTypeNone = 0,
- TextCheckingTypeSpelling = 1 << 1,
- TextCheckingTypeGrammar = 1 << 2,
-};
-
-typedef unsigned TextCheckingTypeMask;
-
-enum TextCheckingProcessType {
- TextCheckingProcessBatch,
- TextCheckingProcessIncremental
-};
-
-struct GrammarDetail {
- int location;
- int length;
- Vector<String> guesses;
- String userDescription;
-};
-
-struct TextCheckingResult {
- TextCheckingType type;
- int location;
- int length;
- Vector<GrammarDetail> details;
- String replacement;
- uint32_t hash;
-};
-
-const int unrequestedTextCheckingSequence = -1;
-
-class TextCheckingRequestData {
- friend class SpellCheckRequest; // For access to m_sequence.
-public:
- TextCheckingRequestData()
- : m_sequence(unrequestedTextCheckingSequence)
- , m_mask(TextCheckingTypeNone)
- , m_processType(TextCheckingProcessIncremental)
- { }
- TextCheckingRequestData(int sequence, const String& text, TextCheckingTypeMask mask, TextCheckingProcessType processType, const Vector<uint32_t>& markers, const Vector<unsigned>& offsets)
- : m_sequence(sequence)
- , m_text(text)
- , m_mask(mask)
- , m_processType(processType)
- , m_markers(markers)
- , m_offsets(offsets)
- { }
-
- int sequence() const { return m_sequence; }
- String text() const { return m_text; }
- TextCheckingTypeMask mask() const { return m_mask; }
- TextCheckingProcessType processType() const { return m_processType; }
- const Vector<uint32_t>& markers() const { return m_markers; }
- const Vector<unsigned>& offsets() const { return m_offsets; }
-
-private:
- int m_sequence;
- String m_text;
- TextCheckingTypeMask m_mask;
- TextCheckingProcessType m_processType;
- Vector<uint32_t> m_markers;
- Vector<unsigned> m_offsets;
-};
-
-class TextCheckingRequest : public RefCounted<TextCheckingRequest> {
-public:
- virtual ~TextCheckingRequest() { }
-
- virtual const TextCheckingRequestData& data() const = 0;
- virtual void didSucceed(const Vector<TextCheckingResult>&) = 0;
- virtual void didCancel() = 0;
-};
-
-}
-
-#endif // TextChecking_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/text/TextDirection.h b/chromium/third_party/WebKit/Source/core/platform/text/TextDirection.h
deleted file mode 100644
index b8a52f7afcd..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/text/TextDirection.h
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Copyright (C) 2003, 2006 Apple Computer, Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TextDirection_h
-#define TextDirection_h
-
-namespace WebCore {
-
-enum TextDirection { RTL, LTR };
-
-inline bool isLeftToRightDirection(TextDirection direction) { return direction == LTR; }
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/text/TextEncodingDetector.h b/chromium/third_party/WebKit/Source/core/platform/text/TextEncodingDetector.h
deleted file mode 100644
index b030040870e..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/text/TextEncodingDetector.h
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright (C) 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TextEncodingDetector_h
-#define TextEncodingDetector_h
-
-namespace WTF{
-class TextEncoding;
-}
-
-namespace WebCore {
-
-// Given a sequence of bytes in |data| of length |len| and an optional
-// hintEncodingName, detect the most likely character encoding.
-// The way hintEncodingName is used is up to an implementation.
-// Currently, the only caller sets it to the parent frame encoding.
-bool detectTextEncoding(const char* data, size_t len,
- const char* hintEncodingName,
- WTF::TextEncoding* detectedEncoding);
-
-} // namespace WebCore
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/text/TextEncodingDetectorICU.cpp b/chromium/third_party/WebKit/Source/core/platform/text/TextEncodingDetectorICU.cpp
deleted file mode 100644
index d0409d642e3..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/text/TextEncodingDetectorICU.cpp
+++ /dev/null
@@ -1,117 +0,0 @@
-/*
- * Copyright (C) 2008, 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/text/TextEncodingDetector.h"
-
-#include "wtf/text/TextEncoding.h"
-#include <unicode/ucnv.h>
-#include <unicode/ucsdet.h>
-
-namespace WebCore {
-
-bool detectTextEncoding(const char* data, size_t len,
- const char* hintEncodingName,
- WTF::TextEncoding* detectedEncoding)
-{
- *detectedEncoding = WTF::TextEncoding();
- int matchesCount = 0;
- UErrorCode status = U_ZERO_ERROR;
- UCharsetDetector* detector = ucsdet_open(&status);
- if (U_FAILURE(status))
- return false;
- ucsdet_enableInputFilter(detector, true);
- ucsdet_setText(detector, data, static_cast<int32_t>(len), &status);
- if (U_FAILURE(status))
- return false;
-
- // FIXME: A few things we can do other than improving
- // the ICU detector itself.
- // 1. Use ucsdet_detectAll and pick the most likely one given
- // "the context" (parent-encoding, referrer encoding, etc).
- // 2. 'Emulate' Firefox/IE's non-Universal detectors (e.g.
- // Chinese, Japanese, Russian, Korean and Hebrew) by picking the
- // encoding with a highest confidence among the detector-specific
- // limited set of candidate encodings.
- // Below is a partial implementation of the first part of what's outlined
- // above.
- const UCharsetMatch** matches = ucsdet_detectAll(detector, &matchesCount, &status);
- if (U_FAILURE(status)) {
- ucsdet_close(detector);
- return false;
- }
-
- const char* encoding = 0;
- if (hintEncodingName) {
- WTF::TextEncoding hintEncoding(hintEncodingName);
- // 10 is the minimum confidence value consistent with the codepoint
- // allocation in a given encoding. The size of a chunk passed to
- // us varies even for the same html file (apparently depending on
- // the network load). When we're given a rather short chunk, we
- // don't have a sufficiently reliable signal other than the fact that
- // the chunk is consistent with a set of encodings. So, instead of
- // setting an arbitrary threshold, we have to scan all the encodings
- // consistent with the data.
- const int32_t kThresold = 10;
- for (int i = 0; i < matchesCount; ++i) {
- int32_t confidence = ucsdet_getConfidence(matches[i], &status);
- if (U_FAILURE(status)) {
- status = U_ZERO_ERROR;
- continue;
- }
- if (confidence < kThresold)
- break;
- const char* matchEncoding = ucsdet_getName(matches[i], &status);
- if (U_FAILURE(status)) {
- status = U_ZERO_ERROR;
- continue;
- }
- if (WTF::TextEncoding(matchEncoding) == hintEncoding) {
- encoding = hintEncodingName;
- break;
- }
- }
- }
- // If no match is found so far, just pick the top match.
- // This can happen, say, when a parent frame in EUC-JP refers to
- // a child frame in Shift_JIS and both frames do NOT specify the encoding
- // making us resort to auto-detection (when it IS turned on).
- if (!encoding && matchesCount > 0)
- encoding = ucsdet_getName(matches[0], &status);
- if (U_SUCCESS(status)) {
- *detectedEncoding = WTF::TextEncoding(encoding);
- ucsdet_close(detector);
- return true;
- }
- ucsdet_close(detector);
- return false;
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/text/TextStream.cpp b/chromium/third_party/WebKit/Source/core/platform/text/TextStream.cpp
deleted file mode 100644
index 7a48eabe13a..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/text/TextStream.cpp
+++ /dev/null
@@ -1,135 +0,0 @@
-/*
- * Copyright (C) 2004, 2008, 2010 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/text/TextStream.h"
-
-#include "wtf/MathExtras.h"
-#include "wtf/StringExtras.h"
-#include "wtf/text/WTFString.h"
-
-using namespace std;
-
-namespace WebCore {
-
-static const size_t printBufferSize = 100; // large enough for any integer or floating point value in string format, including trailing null character
-
-static inline bool hasFractions(double val)
-{
- static const double s_epsilon = 0.0001;
- int ival = static_cast<int>(val);
- double dval = static_cast<double>(ival);
- return fabs(val - dval) > s_epsilon;
-}
-
-TextStream& TextStream::operator<<(bool b)
-{
- return *this << (b ? "1" : "0");
-}
-
-TextStream& TextStream::operator<<(int i)
-{
- m_text.appendNumber(i);
- return *this;
-}
-
-TextStream& TextStream::operator<<(unsigned i)
-{
- m_text.appendNumber(i);
- return *this;
-}
-
-TextStream& TextStream::operator<<(long i)
-{
- m_text.appendNumber(i);
- return *this;
-}
-
-TextStream& TextStream::operator<<(unsigned long i)
-{
- m_text.appendNumber(i);
- return *this;
-}
-
-TextStream& TextStream::operator<<(long long i)
-{
- m_text.appendNumber(i);
- return *this;
-}
-
-TextStream& TextStream::operator<<(unsigned long long i)
-{
- m_text.appendNumber(i);
- return *this;
-}
-
-TextStream& TextStream::operator<<(float f)
-{
- m_text.append(String::numberToStringFixedWidth(f, 2));
- return *this;
-}
-
-TextStream& TextStream::operator<<(double d)
-{
- m_text.append(String::numberToStringFixedWidth(d, 2));
- return *this;
-}
-
-TextStream& TextStream::operator<<(const char* string)
-{
- m_text.append(string);
- return *this;
-}
-
-TextStream& TextStream::operator<<(const void* p)
-{
- char buffer[printBufferSize];
- snprintf(buffer, sizeof(buffer) - 1, "%p", p);
- return *this << buffer;
-}
-
-TextStream& TextStream::operator<<(const String& string)
-{
- m_text.append(string);
- return *this;
-}
-
-TextStream& TextStream::operator<<(const FormatNumberRespectingIntegers& numberToFormat)
-{
- if (hasFractions(numberToFormat.value))
- return *this << numberToFormat.value;
-
- m_text.appendNumber(static_cast<int>(numberToFormat.value));
- return *this;
-}
-
-String TextStream::release()
-{
- String result = m_text.toString();
- m_text.clear();
- return result;
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/text/TextStream.h b/chromium/third_party/WebKit/Source/core/platform/text/TextStream.h
deleted file mode 100644
index fab4d9d6114..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/text/TextStream.h
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Copyright (C) 2004, 2008 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TextStream_h
-#define TextStream_h
-
-#include "wtf/Forward.h"
-#include "wtf/text/StringBuilder.h"
-#include "wtf/unicode/Unicode.h"
-
-namespace WebCore {
-
-class TextStream {
-public:
- struct FormatNumberRespectingIntegers {
- FormatNumberRespectingIntegers(double number) : value(number) { }
- double value;
- };
-
- TextStream& operator<<(bool);
- TextStream& operator<<(int);
- TextStream& operator<<(unsigned);
- TextStream& operator<<(long);
- TextStream& operator<<(unsigned long);
- TextStream& operator<<(long long);
- TextStream& operator<<(unsigned long long);
- TextStream& operator<<(float);
- TextStream& operator<<(double);
- TextStream& operator<<(const char*);
- TextStream& operator<<(const void*);
- TextStream& operator<<(const String&);
- TextStream& operator<<(const FormatNumberRespectingIntegers&);
-
- String release();
-
-private:
- StringBuilder m_text;
-};
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/text/UnicodeBidi.h b/chromium/third_party/WebKit/Source/core/platform/text/UnicodeBidi.h
deleted file mode 100644
index 078527951fe..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/text/UnicodeBidi.h
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Copyright (C) 2011 Google, Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef UnicodeBidi_h
-#define UnicodeBidi_h
-
-namespace WebCore {
-
-enum EUnicodeBidi {
- UBNormal,
- Embed,
- Override,
- Isolate,
- Plaintext,
- IsolateOverride,
-};
-
-inline bool isIsolated(const EUnicodeBidi& unicodeBidi)
-{
- return unicodeBidi == Isolate || unicodeBidi == IsolateOverride || unicodeBidi == Plaintext;
-}
-
-inline bool isOverride(EUnicodeBidi unicodeBidi)
-{
- return unicodeBidi == Override || unicodeBidi == IsolateOverride;
-}
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/text/UnicodeRange.cpp b/chromium/third_party/WebKit/Source/core/platform/text/UnicodeRange.cpp
deleted file mode 100644
index b9897f2579a..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/text/UnicodeRange.cpp
+++ /dev/null
@@ -1,462 +0,0 @@
-/*
- * Copyright (C) 2007 Apple Computer, Inc.
- *
- * Portions are Copyright (C) 1998 Netscape Communications Corporation.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- *
- * Alternatively, the contents of this file may be used under the terms
- * of either the Mozilla Public License Version 1.1, found at
- * http://www.mozilla.org/MPL/ (the "MPL") or the GNU General Public
- * License Version 2.0, found at http://www.fsf.org/copyleft/gpl.html
- * (the "GPL"), in which case the provisions of the MPL or the GPL are
- * applicable instead of those above. If you wish to allow use of your
- * version of this file only under the terms of one of those two
- * licenses (the MPL or the GPL) and not to allow others to use your
- * version of this file under the LGPL, indicate your decision by
- * deletingthe provisions above and replace them with the notice and
- * other provisions required by the MPL or the GPL, as the case may be.
- * If you do not delete the provisions above, a recipient may use your
- * version of this file under any of the LGPL, the MPL or the GPL.
- */
-
-#include "config.h"
-#include "core/platform/text/UnicodeRange.h"
-
-namespace WebCore {
-
-// This table depends on unicode range definitions.
-// Each item's index must correspond to a unicode range value
-// eg. x-cyrillic = LangGroupTable[cRangeCyrillic]
-static const char* gUnicodeRangeToLangGroupTable[] =
-{
- "x-cyrillic",
- "el",
- "tr",
- "he",
- "ar",
- "x-baltic",
- "th",
- "ko",
- "ja",
- "zh-CN",
- "zh-TW",
- "x-devanagari",
- "x-tamil",
- "x-armn",
- "x-beng",
- "x-cans",
- "x-ethi",
- "x-geor",
- "x-gujr",
- "x-guru",
- "x-khmr",
- "x-mlym"
-};
-
-/**********************************************************************
- * Unicode subranges as defined in unicode 3.0
- * x-western, x-central-euro, tr, x-baltic -> latin
- * 0000 - 036f
- * 1e00 - 1eff
- * 2000 - 206f (general punctuation)
- * 20a0 - 20cf (currency symbols)
- * 2100 - 214f (letterlike symbols)
- * 2150 - 218f (Number Forms)
- * el -> greek
- * 0370 - 03ff
- * 1f00 - 1fff
- * x-cyrillic -> cyrillic
- * 0400 - 04ff
- * he -> hebrew
- * 0590 - 05ff
- * ar -> arabic
- * 0600 - 06ff
- * fb50 - fdff (arabic presentation forms)
- * fe70 - feff (arabic presentation forms b)
- * th - thai
- * 0e00 - 0e7f
- * ko -> korean
- * ac00 - d7af (hangul Syllables)
- * 1100 - 11ff (jamo)
- * 3130 - 318f (hangul compatibility jamo)
- * ja
- * 3040 - 309f (hiragana)
- * 30a0 - 30ff (katakana)
- * zh-CN
- * zh-TW
- *
- * CJK
- * 3100 - 312f (bopomofo)
- * 31a0 - 31bf (bopomofo extended)
- * 3000 - 303f (CJK Symbols and Punctuation)
- * 2e80 - 2eff (CJK radicals supplement)
- * 2f00 - 2fdf (Kangxi Radicals)
- * 2ff0 - 2fff (Ideographic Description Characters)
- * 3190 - 319f (kanbun)
- * 3200 - 32ff (Enclosed CJK letters and Months)
- * 3300 - 33ff (CJK compatibility)
- * 3400 - 4dbf (CJK Unified Ideographs Extension A)
- * 4e00 - 9faf (CJK Unified Ideographs)
- * f900 - fa5f (CJK Compatibility Ideographs)
- * fe30 - fe4f (CJK compatibility Forms)
- * ff00 - ffef (halfwidth and fullwidth forms)
- *
- * Armenian
- * 0530 - 058f
- * Sriac
- * 0700 - 074f
- * Thaana
- * 0780 - 07bf
- * Devanagari
- * 0900 - 097f
- * Bengali
- * 0980 - 09ff
- * Gurmukhi
- * 0a00 - 0a7f
- * Gujarati
- * 0a80 - 0aff
- * Oriya
- * 0b00 - 0b7f
- * Tamil
- * 0b80 - 0bff
- * Telugu
- * 0c00 - 0c7f
- * Kannada
- * 0c80 - 0cff
- * Malayalam
- * 0d00 - 0d7f
- * Sinhala
- * 0d80 - 0def
- * Lao
- * 0e80 - 0eff
- * Tibetan
- * 0f00 - 0fbf
- * Myanmar
- * 1000 - 109f
- * Georgian
- * 10a0 - 10ff
- * Ethiopic
- * 1200 - 137f
- * Cherokee
- * 13a0 - 13ff
- * Canadian Aboriginal Syllabics
- * 1400 - 167f
- * Ogham
- * 1680 - 169f
- * Runic
- * 16a0 - 16ff
- * Khmer
- * 1780 - 17ff
- * Mongolian
- * 1800 - 18af
- * Misc - superscripts and subscripts
- * 2070 - 209f
- * Misc - Combining Diacritical Marks for Symbols
- * 20d0 - 20ff
- * Misc - Arrows
- * 2190 - 21ff
- * Misc - Mathematical Operators
- * 2200 - 22ff
- * Misc - Miscellaneous Technical
- * 2300 - 23ff
- * Misc - Control picture
- * 2400 - 243f
- * Misc - Optical character recognition
- * 2440 - 2450
- * Misc - Enclose Alphanumerics
- * 2460 - 24ff
- * Misc - Box Drawing
- * 2500 - 257f
- * Misc - Block Elements
- * 2580 - 259f
- * Misc - Geometric Shapes
- * 25a0 - 25ff
- * Misc - Miscellaneous Symbols
- * 2600 - 267f
- * Misc - Dingbats
- * 2700 - 27bf
- * Misc - Braille Patterns
- * 2800 - 28ff
- * Yi Syllables
- * a000 - a48f
- * Yi radicals
- * a490 - a4cf
- * Alphabetic Presentation Forms
- * fb00 - fb4f
- * Misc - Combining half Marks
- * fe20 - fe2f
- * Misc - small form variants
- * fe50 - fe6f
- * Misc - Specials
- * fff0 - ffff
- *********************************************************************/
-
-static const unsigned cNumSubTables = 9;
-static const unsigned cSubTableSize = 16;
-
-static const unsigned char gUnicodeSubrangeTable[cNumSubTables][cSubTableSize] =
-{
- { // table for X---
- cRangeTableBase+1, //u0xxx
- cRangeTableBase+2, //u1xxx
- cRangeTableBase+3, //u2xxx
- cRangeSetCJK, //u3xxx
- cRangeSetCJK, //u4xxx
- cRangeSetCJK, //u5xxx
- cRangeSetCJK, //u6xxx
- cRangeSetCJK, //u7xxx
- cRangeSetCJK, //u8xxx
- cRangeSetCJK, //u9xxx
- cRangeTableBase+4, //uaxxx
- cRangeKorean, //ubxxx
- cRangeKorean, //ucxxx
- cRangeTableBase+5, //udxxx
- cRangePrivate, //uexxx
- cRangeTableBase+6 //ufxxx
- },
- { //table for 0X--
- cRangeSetLatin, //u00xx
- cRangeSetLatin, //u01xx
- cRangeSetLatin, //u02xx
- cRangeGreek, //u03xx XXX 0300-036f is in fact cRangeCombiningDiacriticalMarks
- cRangeCyrillic, //u04xx
- cRangeTableBase+7, //u05xx, includes Cyrillic supplement, Hebrew, and Armenian
- cRangeArabic, //u06xx
- cRangeTertiaryTable, //u07xx
- cRangeUnassigned, //u08xx
- cRangeTertiaryTable, //u09xx
- cRangeTertiaryTable, //u0axx
- cRangeTertiaryTable, //u0bxx
- cRangeTertiaryTable, //u0cxx
- cRangeTertiaryTable, //u0dxx
- cRangeTertiaryTable, //u0exx
- cRangeTibetan, //u0fxx
- },
- { //table for 1x--
- cRangeTertiaryTable, //u10xx
- cRangeKorean, //u11xx
- cRangeEthiopic, //u12xx
- cRangeTertiaryTable, //u13xx
- cRangeCanadian, //u14xx
- cRangeCanadian, //u15xx
- cRangeTertiaryTable, //u16xx
- cRangeKhmer, //u17xx
- cRangeMongolian, //u18xx
- cRangeUnassigned, //u19xx
- cRangeUnassigned, //u1axx
- cRangeUnassigned, //u1bxx
- cRangeUnassigned, //u1cxx
- cRangeUnassigned, //u1dxx
- cRangeSetLatin, //u1exx
- cRangeGreek, //u1fxx
- },
- { //table for 2x--
- cRangeSetLatin, //u20xx
- cRangeSetLatin, //u21xx
- cRangeMathOperators, //u22xx
- cRangeMiscTechnical, //u23xx
- cRangeControlOpticalEnclose, //u24xx
- cRangeBoxBlockGeometrics, //u25xx
- cRangeMiscSymbols, //u26xx
- cRangeDingbats, //u27xx
- cRangeBraillePattern, //u28xx
- cRangeUnassigned, //u29xx
- cRangeUnassigned, //u2axx
- cRangeUnassigned, //u2bxx
- cRangeUnassigned, //u2cxx
- cRangeUnassigned, //u2dxx
- cRangeSetCJK, //u2exx
- cRangeSetCJK, //u2fxx
- },
- { //table for ax--
- cRangeYi, //ua0xx
- cRangeYi, //ua1xx
- cRangeYi, //ua2xx
- cRangeYi, //ua3xx
- cRangeYi, //ua4xx
- cRangeUnassigned, //ua5xx
- cRangeUnassigned, //ua6xx
- cRangeUnassigned, //ua7xx
- cRangeUnassigned, //ua8xx
- cRangeUnassigned, //ua9xx
- cRangeUnassigned, //uaaxx
- cRangeUnassigned, //uabxx
- cRangeKorean, //uacxx
- cRangeKorean, //uadxx
- cRangeKorean, //uaexx
- cRangeKorean, //uafxx
- },
- { //table for dx--
- cRangeKorean, //ud0xx
- cRangeKorean, //ud1xx
- cRangeKorean, //ud2xx
- cRangeKorean, //ud3xx
- cRangeKorean, //ud4xx
- cRangeKorean, //ud5xx
- cRangeKorean, //ud6xx
- cRangeKorean, //ud7xx
- cRangeSurrogate, //ud8xx
- cRangeSurrogate, //ud9xx
- cRangeSurrogate, //udaxx
- cRangeSurrogate, //udbxx
- cRangeSurrogate, //udcxx
- cRangeSurrogate, //uddxx
- cRangeSurrogate, //udexx
- cRangeSurrogate, //udfxx
- },
- { // table for fx--
- cRangePrivate, //uf0xx
- cRangePrivate, //uf1xx
- cRangePrivate, //uf2xx
- cRangePrivate, //uf3xx
- cRangePrivate, //uf4xx
- cRangePrivate, //uf5xx
- cRangePrivate, //uf6xx
- cRangePrivate, //uf7xx
- cRangePrivate, //uf8xx
- cRangeSetCJK, //uf9xx
- cRangeSetCJK, //ufaxx
- cRangeArabic, //ufbxx, includes alphabic presentation form
- cRangeArabic, //ufcxx
- cRangeArabic, //ufdxx
- cRangeArabic, //ufexx, includes Combining half marks,
- // CJK compatibility forms,
- // CJK compatibility forms,
- // small form variants
- cRangeTableBase+8, //uffxx, halfwidth and fullwidth forms, includes Specials
- },
- { //table for 0x0500 - 0x05ff
- cRangeCyrillic, //u050x
- cRangeCyrillic, //u051x
- cRangeCyrillic, //u052x
- cRangeArmenian, //u053x
- cRangeArmenian, //u054x
- cRangeArmenian, //u055x
- cRangeArmenian, //u056x
- cRangeArmenian, //u057x
- cRangeArmenian, //u058x
- cRangeHebrew, //u059x
- cRangeHebrew, //u05ax
- cRangeHebrew, //u05bx
- cRangeHebrew, //u05cx
- cRangeHebrew, //u05dx
- cRangeHebrew, //u05ex
- cRangeHebrew, //u05fx
- },
- { //table for 0xff00 - 0xffff
- cRangeSetCJK, //uff0x, fullwidth latin
- cRangeSetCJK, //uff1x, fullwidth latin
- cRangeSetCJK, //uff2x, fullwidth latin
- cRangeSetCJK, //uff3x, fullwidth latin
- cRangeSetCJK, //uff4x, fullwidth latin
- cRangeSetCJK, //uff5x, fullwidth latin
- cRangeSetCJK, //uff6x, halfwidth katakana
- cRangeSetCJK, //uff7x, halfwidth katakana
- cRangeSetCJK, //uff8x, halfwidth katakana
- cRangeSetCJK, //uff9x, halfwidth katakana
- cRangeSetCJK, //uffax, halfwidth hangul jamo
- cRangeSetCJK, //uffbx, halfwidth hangul jamo
- cRangeSetCJK, //uffcx, halfwidth hangul jamo
- cRangeSetCJK, //uffdx, halfwidth hangul jamo
- cRangeSetCJK, //uffex, fullwidth symbols
- cRangeSpecials, //ufffx, Specials
- },
-};
-
-// Most scripts between U+0700 and U+16FF are assigned a chunk of 128 (0x80)
-// code points so that the number of entries in the tertiary range
-// table for that range is obtained by dividing (0x1700 - 0x0700) by 128.
-// Exceptions: Ethiopic, Tibetan, Hangul Jamo and Canadian aboriginal
-// syllabaries take multiple chunks and Ogham and Runic share a single chunk.
-static const unsigned cTertiaryTableSize = ((0x1700 - 0x0700) / 0x80);
-
-static const unsigned char gUnicodeTertiaryRangeTable[cTertiaryTableSize] =
-{ //table for 0x0700 - 0x1600
- cRangeSyriac, //u070x
- cRangeThaana, //u078x
- cRangeUnassigned, //u080x place holder(resolved in the 2ndary tab.)
- cRangeUnassigned, //u088x place holder(resolved in the 2ndary tab.)
- cRangeDevanagari, //u090x
- cRangeBengali, //u098x
- cRangeGurmukhi, //u0a0x
- cRangeGujarati, //u0a8x
- cRangeOriya, //u0b0x
- cRangeTamil, //u0b8x
- cRangeTelugu, //u0c0x
- cRangeKannada, //u0c8x
- cRangeMalayalam, //u0d0x
- cRangeSinhala, //u0d8x
- cRangeThai, //u0e0x
- cRangeLao, //u0e8x
- cRangeTibetan, //u0f0x place holder(resolved in the 2ndary tab.)
- cRangeTibetan, //u0f8x place holder(resolved in the 2ndary tab.)
- cRangeMyanmar, //u100x
- cRangeGeorgian, //u108x
- cRangeKorean, //u110x place holder(resolved in the 2ndary tab.)
- cRangeKorean, //u118x place holder(resolved in the 2ndary tab.)
- cRangeEthiopic, //u120x place holder(resolved in the 2ndary tab.)
- cRangeEthiopic, //u128x place holder(resolved in the 2ndary tab.)
- cRangeEthiopic, //u130x
- cRangeCherokee, //u138x
- cRangeCanadian, //u140x place holder(resolved in the 2ndary tab.)
- cRangeCanadian, //u148x place holder(resolved in the 2ndary tab.)
- cRangeCanadian, //u150x place holder(resolved in the 2ndary tab.)
- cRangeCanadian, //u158x place holder(resolved in the 2ndary tab.)
- cRangeCanadian, //u160x
- cRangeOghamRunic, //u168x this contains two scripts, Ogham & Runic
-};
-
-// A two level index is almost enough for locating a range, with the
-// exception of u03xx and u05xx. Since we don't really care about range for
-// combining diacritical marks in our font application, they are
-// not discriminated further. Future adoption of this method for other use
-// should be aware of this limitation. The implementation can be extended if
-// there is such a need.
-// For Indic, Southeast Asian scripts and some other scripts between
-// U+0700 and U+16FF, it's extended to the third level.
-unsigned int findCharUnicodeRange(UChar32 ch)
-{
- if (ch >= 0xFFFF)
- return 0;
-
- unsigned int range;
-
- //search the first table
- range = gUnicodeSubrangeTable[0][ch >> 12];
-
- if (range < cRangeTableBase)
- // we try to get a specific range
- return range;
-
- // otherwise, we have one more table to look at
- range = gUnicodeSubrangeTable[range - cRangeTableBase][(ch & 0x0f00) >> 8];
- if (range < cRangeTableBase)
- return range;
- if (range < cRangeTertiaryTable)
- return gUnicodeSubrangeTable[range - cRangeTableBase][(ch & 0x00f0) >> 4];
-
- // Yet another table to look at : U+0700 - U+16FF : 128 code point blocks
- return gUnicodeTertiaryRangeTable[(ch - 0x0700) >> 7];
-}
-
-const char* langGroupFromUnicodeRange(unsigned char unicodeRange)
-{
- if (cRangeSpecificItemNum > unicodeRange)
- return gUnicodeRangeToLangGroupTable[unicodeRange];
- return 0;
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/text/UnicodeRange.h b/chromium/third_party/WebKit/Source/core/platform/text/UnicodeRange.h
deleted file mode 100644
index 4d06e830147..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/text/UnicodeRange.h
+++ /dev/null
@@ -1,120 +0,0 @@
-/*
- * Copyright (C) 2007 Apple Computer, Inc.
- *
- * Portions are Copyright (C) 1998 Netscape Communications Corporation.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 2.1 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- *
- * Alternatively, the contents of this file may be used under the terms
- * of either the Mozilla Public License Version 1.1, found at
- * http://www.mozilla.org/MPL/ (the "MPL") or the GNU General Public
- * License Version 2.0, found at http://www.fsf.org/copyleft/gpl.html
- * (the "GPL"), in which case the provisions of the MPL or the GPL are
- * applicable instead of those above. If you wish to allow use of your
- * version of this file only under the terms of one of those two
- * licenses (the MPL or the GPL) and not to allow others to use your
- * version of this file under the LGPL, indicate your decision by
- * deletingthe provisions above and replace them with the notice and
- * other provisions required by the MPL or the GPL, as the case may be.
- * If you do not delete the provisions above, a recipient may use your
- * version of this file under any of the LGPL, the MPL or the GPL.
- */
-
-#ifndef UnicodeRange_H
-#define UnicodeRange_H
-
-#include "wtf/unicode/Unicode.h"
-
-namespace WebCore {
-
-// The following constants define unicode subranges
-// values below cRangeNum must be continuous so that we can map to
-// a lang group directly.
-// All ranges we care about should fit within 32 bits.
-
-// Frequently used range definitions
-const unsigned char cRangeCyrillic = 0;
-const unsigned char cRangeGreek = 1;
-const unsigned char cRangeTurkish = 2;
-const unsigned char cRangeHebrew = 3;
-const unsigned char cRangeArabic = 4;
-const unsigned char cRangeBaltic = 5;
-const unsigned char cRangeThai = 6;
-const unsigned char cRangeKorean = 7;
-const unsigned char cRangeJapanese = 8;
-const unsigned char cRangeSChinese = 9;
-const unsigned char cRangeTChinese = 10;
-const unsigned char cRangeDevanagari = 11;
-const unsigned char cRangeTamil = 12;
-const unsigned char cRangeArmenian = 13;
-const unsigned char cRangeBengali = 14;
-const unsigned char cRangeCanadian = 15;
-const unsigned char cRangeEthiopic = 16;
-const unsigned char cRangeGeorgian = 17;
-const unsigned char cRangeGujarati = 18;
-const unsigned char cRangeGurmukhi = 19;
-const unsigned char cRangeKhmer = 20;
-const unsigned char cRangeMalayalam = 21;
-
-const unsigned char cRangeSpecificItemNum = 22;
-
-//range/rangeSet grow to this place 22-29
-
-const unsigned char cRangeSetStart = 30; // range set definition starts from here
-const unsigned char cRangeSetLatin = 30;
-const unsigned char cRangeSetCJK = 31;
-const unsigned char cRangeSetEnd = 31; // range set definition ends here
-
-// less frequently used range definition
-const unsigned char cRangeSurrogate = 32;
-const unsigned char cRangePrivate = 33;
-const unsigned char cRangeMisc = 34;
-const unsigned char cRangeUnassigned = 35;
-const unsigned char cRangeSyriac = 36;
-const unsigned char cRangeThaana = 37;
-const unsigned char cRangeOriya = 38;
-const unsigned char cRangeTelugu = 39;
-const unsigned char cRangeKannada = 40;
-const unsigned char cRangeSinhala = 41;
-const unsigned char cRangeLao = 42;
-const unsigned char cRangeTibetan = 43;
-const unsigned char cRangeMyanmar = 44;
-const unsigned char cRangeCherokee = 45;
-const unsigned char cRangeOghamRunic = 46;
-const unsigned char cRangeMongolian = 47;
-const unsigned char cRangeMathOperators = 48;
-const unsigned char cRangeMiscTechnical = 49;
-const unsigned char cRangeControlOpticalEnclose = 50;
-const unsigned char cRangeBoxBlockGeometrics = 51;
-const unsigned char cRangeMiscSymbols = 52;
-const unsigned char cRangeDingbats = 53;
-const unsigned char cRangeBraillePattern = 54;
-const unsigned char cRangeYi = 55;
-const unsigned char cRangeCombiningDiacriticalMarks = 56;
-const unsigned char cRangeSpecials = 57;
-
-const unsigned char cRangeTableBase = 128; //values over 127 are reserved for internal use only
-const unsigned char cRangeTertiaryTable = 145; // leave room for 16 subtable
- // indices (cRangeTableBase + 1 ..
- // cRangeTableBase + 16)
-
-
-
-unsigned int findCharUnicodeRange(UChar32 ch);
-const char* langGroupFromUnicodeRange(unsigned char unicodeRange);
-
-}
-
-#endif // UnicodeRange_H
diff --git a/chromium/third_party/WebKit/Source/core/platform/text/WritingMode.h b/chromium/third_party/WebKit/Source/core/platform/text/WritingMode.h
deleted file mode 100644
index 9e5d28c7dc2..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/text/WritingMode.h
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * Copyright (c) 2012, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef WritingMode_h
-#define WritingMode_h
-
-namespace WebCore {
-
-enum WritingMode {
- TopToBottomWritingMode, RightToLeftWritingMode, LeftToRightWritingMode, BottomToTopWritingMode
-};
-
-// Lines have horizontal orientation; modes horizontal-tb or horizontal-bt.
-inline bool isHorizontalWritingMode(WritingMode writingMode)
-{
- return writingMode == TopToBottomWritingMode || writingMode == BottomToTopWritingMode;
-}
-
-// Bottom of the line occurs earlier in the block; modes vertical-lr or horizontal-bt.
-inline bool isFlippedLinesWritingMode(WritingMode writingMode)
-{
- return writingMode == LeftToRightWritingMode || writingMode == BottomToTopWritingMode;
-}
-
-// Block progression increases in the opposite direction to normal; modes vertical-rl or horizontal-bt.
-inline bool isFlippedBlocksWritingMode(WritingMode writingMode)
-{
- return writingMode == RightToLeftWritingMode || writingMode == BottomToTopWritingMode;
-}
-
-} // namespace WebCore
-
-#endif // WritingMode_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/text/cf/AtomicStringCF.cpp b/chromium/third_party/WebKit/Source/core/platform/text/cf/AtomicStringCF.cpp
deleted file mode 100644
index 2ba3853084e..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/text/cf/AtomicStringCF.cpp
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright (C) 2012 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "wtf/text/AtomicString.h"
-
-#if USE(CF)
-
-#include <CoreFoundation/CoreFoundation.h>
-#include "wtf/text/CString.h"
-
-namespace WTF {
-
-PassRefPtr<StringImpl> AtomicString::add(CFStringRef string)
-{
- if (!string)
- return 0;
-
- CFIndex length = CFStringGetLength(string);
-
- if (const LChar* ptr = reinterpret_cast<const LChar*>(CFStringGetCStringPtr(string, kCFStringEncodingISOLatin1)))
- return add(ptr, length);
-
- if (const UniChar* ptr = CFStringGetCharactersPtr(string))
- return add(reinterpret_cast<const UChar*>(ptr), length);
-
- Vector<UniChar, 1024> ucharBuffer(length);
- CFStringGetCharacters(string, CFRangeMake(0, length), ucharBuffer.data());
- return add(reinterpret_cast<const UChar*>(ucharBuffer.data()), length);
-}
-
-} // namespace WTF
-
-#endif // USE(CF)
diff --git a/chromium/third_party/WebKit/Source/core/platform/text/cf/StringCF.cpp b/chromium/third_party/WebKit/Source/core/platform/text/cf/StringCF.cpp
deleted file mode 100644
index 2cb4ce7ee6e..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/text/cf/StringCF.cpp
+++ /dev/null
@@ -1,64 +0,0 @@
-/**
- * Copyright (C) 2006, 2012 Apple Computer, Inc.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#include "config.h"
-
-#include "wtf/text/WTFString.h"
-
-#if USE(CF)
-#include <CoreFoundation/CoreFoundation.h>
-#include "wtf/RetainPtr.h"
-
-namespace WTF {
-
-String::String(CFStringRef str)
-{
- if (!str)
- return;
-
- CFIndex size = CFStringGetLength(str);
- if (size == 0)
- m_impl = StringImpl::empty();
- else {
- Vector<LChar, 1024> lcharBuffer(size);
- CFIndex usedBufLen;
- CFIndex convertedsize = CFStringGetBytes(str, CFRangeMake(0, size), kCFStringEncodingISOLatin1, 0, false, lcharBuffer.data(), size, &usedBufLen);
- if ((convertedsize == size) && (usedBufLen == size)) {
- m_impl = StringImpl::create(lcharBuffer.data(), size);
- return;
- }
-
- Vector<UChar, 1024> buffer(size);
- CFStringGetCharacters(str, CFRangeMake(0, size), (UniChar*)buffer.data());
- m_impl = StringImpl::create(buffer.data(), size);
- }
-}
-
-RetainPtr<CFStringRef> String::createCFString() const
-{
- if (!m_impl)
- return CFSTR("");
-
- return m_impl->createCFString();
-}
-
-}
-
-#endif // USE(CF)
diff --git a/chromium/third_party/WebKit/Source/core/platform/text/cf/StringImplCF.cpp b/chromium/third_party/WebKit/Source/core/platform/text/cf/StringImplCF.cpp
deleted file mode 100644
index 2c2ed14cadc..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/text/cf/StringImplCF.cpp
+++ /dev/null
@@ -1,162 +0,0 @@
-/*
- * Copyright (C) 2006, 2009, 2012 Apple Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#include "config.h"
-#include "wtf/text/StringImpl.h"
-
-#if USE(CF)
-
-#include <CoreFoundation/CoreFoundation.h>
-#include "wtf/MainThread.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RetainPtr.h"
-#include "wtf/Threading.h"
-
-namespace WTF {
-
-namespace StringWrapperCFAllocator {
-
- static StringImpl* currentString;
-
- static const void* retain(const void* info)
- {
- return info;
- }
-
- NO_RETURN_DUE_TO_ASSERT
- static void release(const void*)
- {
- ASSERT_NOT_REACHED();
- }
-
- static CFStringRef copyDescription(const void*)
- {
- return CFSTR("WTF::String-based allocator");
- }
-
- static void* allocate(CFIndex size, CFOptionFlags, void*)
- {
- StringImpl* underlyingString = 0;
- if (isMainThread()) {
- underlyingString = currentString;
- if (underlyingString) {
- currentString = 0;
- underlyingString->ref(); // Balanced by call to deref in deallocate below.
- }
- }
- StringImpl** header = static_cast<StringImpl**>(fastMalloc(sizeof(StringImpl*) + size));
- *header = underlyingString;
- return header + 1;
- }
-
- static void* reallocate(void* pointer, CFIndex newSize, CFOptionFlags, void*)
- {
- size_t newAllocationSize = sizeof(StringImpl*) + newSize;
- StringImpl** header = static_cast<StringImpl**>(pointer) - 1;
- ASSERT(!*header);
- header = static_cast<StringImpl**>(fastRealloc(header, newAllocationSize));
- return header + 1;
- }
-
- static void deallocateOnMainThread(void* headerPointer)
- {
- StringImpl** header = static_cast<StringImpl**>(headerPointer);
- StringImpl* underlyingString = *header;
- ASSERT(underlyingString);
- underlyingString->deref(); // Balanced by call to ref in allocate above.
- fastFree(header);
- }
-
- static void deallocate(void* pointer, void*)
- {
- StringImpl** header = static_cast<StringImpl**>(pointer) - 1;
- StringImpl* underlyingString = *header;
- if (!underlyingString)
- fastFree(header);
- else {
- if (!isMainThread())
- callOnMainThread(deallocateOnMainThread, header);
- else {
- underlyingString->deref(); // Balanced by call to ref in allocate above.
- fastFree(header);
- }
- }
- }
-
- static CFIndex preferredSize(CFIndex size, CFOptionFlags, void*)
- {
- // FIXME: If FastMalloc provided a "good size" callback, we'd want to use it here.
- // Note that this optimization would help performance for strings created with the
- // allocator that are mutable, and those typically are only created by callers who
- // make a new string using the old string's allocator, such as some of the call
- // sites in CFURL.
- return size;
- }
-
- static CFAllocatorRef create()
- {
- CFAllocatorContext context = { 0, 0, retain, release, copyDescription, allocate, reallocate, deallocate, preferredSize };
- return CFAllocatorCreate(0, &context);
- }
-
- static CFAllocatorRef allocator()
- {
- static CFAllocatorRef allocator = create();
- return allocator;
- }
-
-}
-
-RetainPtr<CFStringRef> StringImpl::createCFString()
-{
- // Since garbage collection isn't compatible with custom allocators, we
- // can't use the NoCopy variants of CFStringCreate*() when GC is enabled.
- if (!m_length || !isMainThread()) {
- if (is8Bit())
- return adoptCF(CFStringCreateWithBytes(0, reinterpret_cast<const UInt8*>(characters8()), m_length, kCFStringEncodingISOLatin1, false));
- return adoptCF(CFStringCreateWithCharacters(0, reinterpret_cast<const UniChar*>(characters16()), m_length));
- }
- CFAllocatorRef allocator = StringWrapperCFAllocator::allocator();
-
- // Put pointer to the StringImpl in a global so the allocator can store it with the CFString.
- ASSERT(!StringWrapperCFAllocator::currentString);
- StringWrapperCFAllocator::currentString = this;
-
- CFStringRef string;
- if (is8Bit())
- string = CFStringCreateWithBytesNoCopy(allocator, reinterpret_cast<const UInt8*>(characters8()), m_length, kCFStringEncodingISOLatin1, false, kCFAllocatorNull);
- else
- string = CFStringCreateWithCharactersNoCopy(allocator, reinterpret_cast<const UniChar*>(characters16()), m_length, kCFAllocatorNull);
- // CoreFoundation might not have to allocate anything, we clear currentString in case we did not execute allocate().
- StringWrapperCFAllocator::currentString = 0;
-
- return adoptCF(string);
-}
-
-// On StringImpl creation we could check if the allocator is the StringWrapperCFAllocator.
-// If it is, then we could find the original StringImpl and just return that. But to
-// do that we'd have to compute the offset from CFStringRef to the allocated block;
-// the CFStringRef is *not* at the start of an allocated block. Testing shows 1000x
-// more calls to createCFString than calls to the create functions with the appropriate
-// allocator, so it's probably not urgent optimize that case.
-
-}
-
-#endif // USE(CF)
diff --git a/chromium/third_party/WebKit/Source/core/platform/text/mac/LocaleMac.h b/chromium/third_party/WebKit/Source/core/platform/text/mac/LocaleMac.h
deleted file mode 100644
index 3d6055cb3d2..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/text/mac/LocaleMac.h
+++ /dev/null
@@ -1,104 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef LocaleMac_h
-#define LocaleMac_h
-
-#include "core/platform/text/PlatformLocale.h"
-#include "wtf/Forward.h"
-#include "wtf/RetainPtr.h"
-#include "wtf/text/WTFString.h"
-#include "wtf/Vector.h"
-
-OBJC_CLASS NSCalendar;
-OBJC_CLASS NSDateFormatter;
-OBJC_CLASS NSLocale;
-
-namespace WebCore {
-
-class DateComponents;
-
-class LocaleMac : public Locale {
-public:
- static PassOwnPtr<LocaleMac> create(const String&);
- static PassOwnPtr<LocaleMac> create(NSLocale*);
- ~LocaleMac();
-
-#if ENABLE(CALENDAR_PICKER)
- virtual const Vector<String>& weekDayShortLabels() OVERRIDE;
- virtual unsigned firstDayOfWeek() OVERRIDE;
- virtual bool isRTL() OVERRIDE;
-#endif
-
- virtual String dateFormat() OVERRIDE;
- virtual String monthFormat() OVERRIDE;
- virtual String shortMonthFormat() OVERRIDE;
- virtual String timeFormat() OVERRIDE;
- virtual String shortTimeFormat() OVERRIDE;
- virtual String dateTimeFormatWithSeconds() OVERRIDE;
- virtual String dateTimeFormatWithoutSeconds() OVERRIDE;
- virtual const Vector<String>& monthLabels() OVERRIDE;
- virtual const Vector<String>& shortMonthLabels() OVERRIDE;
- virtual const Vector<String>& standAloneMonthLabels() OVERRIDE;
- virtual const Vector<String>& shortStandAloneMonthLabels() OVERRIDE;
- virtual const Vector<String>& timeAMPMLabels() OVERRIDE;
-
-private:
- explicit LocaleMac(NSLocale*);
- RetainPtr<NSDateFormatter> shortDateFormatter();
- virtual void initializeLocaleData() OVERRIDE;
-
- RetainPtr<NSLocale> m_locale;
- RetainPtr<NSCalendar> m_gregorianCalendar;
-#if ENABLE(CALENDAR_PICKER)
- Vector<String> m_weekDayShortLabels;
-#endif
- Vector<String> m_monthLabels;
- RetainPtr<NSDateFormatter> timeFormatter();
- RetainPtr<NSDateFormatter> shortTimeFormatter();
- RetainPtr<NSDateFormatter> dateTimeFormatterWithSeconds();
- RetainPtr<NSDateFormatter> dateTimeFormatterWithoutSeconds();
-
- String m_dateFormat;
- String m_monthFormat;
- String m_shortMonthFormat;
- String m_timeFormatWithSeconds;
- String m_timeFormatWithoutSeconds;
- String m_dateTimeFormatWithSeconds;
- String m_dateTimeFormatWithoutSeconds;
- Vector<String> m_shortMonthLabels;
- Vector<String> m_standAloneMonthLabels;
- Vector<String> m_shortStandAloneMonthLabels;
- Vector<String> m_timeAMPMLabels;
- bool m_didInitializeNumberData;
-};
-
-} // namespace WebCore
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/text/mac/LocaleMac.mm b/chromium/third_party/WebKit/Source/core/platform/text/mac/LocaleMac.mm
deleted file mode 100644
index fdcb3333019..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/text/mac/LocaleMac.mm
+++ /dev/null
@@ -1,332 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/text/mac/LocaleMac.h"
-
-#import <Foundation/NSDateFormatter.h>
-#import <Foundation/NSLocale.h>
-#include "core/platform/Language.h"
-#include "core/platform/LocalizedStrings.h"
-#include "wtf/DateMath.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/RetainPtr.h"
-#include "wtf/text/StringBuilder.h"
-
-using namespace std;
-
-namespace WebCore {
-
-static inline String languageFromLocale(const String& locale)
-{
- String normalizedLocale = locale;
- normalizedLocale.replace('-', '_');
- size_t separatorPosition = normalizedLocale.find('_');
- if (separatorPosition == kNotFound)
- return normalizedLocale;
- return normalizedLocale.left(separatorPosition);
-}
-
-static RetainPtr<NSLocale> determineLocale(const String& locale)
-{
- RetainPtr<NSLocale> currentLocale = [NSLocale currentLocale];
- String currentLocaleLanguage = languageFromLocale(String([currentLocale.get() localeIdentifier]));
- String localeLanguage = languageFromLocale(locale);
- if (equalIgnoringCase(currentLocaleLanguage, localeLanguage))
- return currentLocale;
- // It seems initWithLocaleIdentifier accepts dash-separated locale identifier.
- return RetainPtr<NSLocale>(AdoptNS, [[NSLocale alloc] initWithLocaleIdentifier:locale]);
-}
-
-PassOwnPtr<Locale> Locale::create(const AtomicString& locale)
-{
- return LocaleMac::create(determineLocale(locale.string()).get());
-}
-
-static RetainPtr<NSDateFormatter> createDateTimeFormatter(NSLocale* locale, NSCalendar* calendar, NSDateFormatterStyle dateStyle, NSDateFormatterStyle timeStyle)
-{
- NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
- [formatter setLocale:locale];
- [formatter setDateStyle:dateStyle];
- [formatter setTimeStyle:timeStyle];
- [formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
- [formatter setCalendar:calendar];
- return adoptNS(formatter);
-}
-
-LocaleMac::LocaleMac(NSLocale* locale)
- : m_locale(locale)
- , m_gregorianCalendar(AdoptNS, [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar])
- , m_didInitializeNumberData(false)
-{
- NSArray* availableLanguages = [NSLocale ISOLanguageCodes];
- // NSLocale returns a lower case NSLocaleLanguageCode so we don't have care about case.
- NSString* language = [m_locale.get() objectForKey:NSLocaleLanguageCode];
- if ([availableLanguages indexOfObject:language] == NSNotFound)
- m_locale.adoptNS([[NSLocale alloc] initWithLocaleIdentifier:defaultLanguage()]);
- [m_gregorianCalendar.get() setLocale:m_locale.get()];
-}
-
-LocaleMac::~LocaleMac()
-{
-}
-
-PassOwnPtr<LocaleMac> LocaleMac::create(const String& localeIdentifier)
-{
- RetainPtr<NSLocale> locale = [[NSLocale alloc] initWithLocaleIdentifier:localeIdentifier];
- return adoptPtr(new LocaleMac(locale.get()));
-}
-
-PassOwnPtr<LocaleMac> LocaleMac::create(NSLocale* locale)
-{
- return adoptPtr(new LocaleMac(locale));
-}
-
-RetainPtr<NSDateFormatter> LocaleMac::shortDateFormatter()
-{
- return createDateTimeFormatter(m_locale.get(), m_gregorianCalendar.get(), NSDateFormatterShortStyle, NSDateFormatterNoStyle);
-}
-
-const Vector<String>& LocaleMac::monthLabels()
-{
- if (!m_monthLabels.isEmpty())
- return m_monthLabels;
- m_monthLabels.reserveCapacity(12);
- NSArray *array = [shortDateFormatter().get() monthSymbols];
- if ([array count] == 12) {
- for (unsigned i = 0; i < 12; ++i)
- m_monthLabels.append(String([array objectAtIndex:i]));
- return m_monthLabels;
- }
- for (unsigned i = 0; i < WTF_ARRAY_LENGTH(WTF::monthFullName); ++i)
- m_monthLabels.append(WTF::monthFullName[i]);
- return m_monthLabels;
-}
-
-#if ENABLE(CALENDAR_PICKER)
-const Vector<String>& LocaleMac::weekDayShortLabels()
-{
- if (!m_weekDayShortLabels.isEmpty())
- return m_weekDayShortLabels;
- m_weekDayShortLabels.reserveCapacity(7);
- NSArray *array = [shortDateFormatter().get() shortWeekdaySymbols];
- if ([array count] == 7) {
- for (unsigned i = 0; i < 7; ++i)
- m_weekDayShortLabels.append(String([array objectAtIndex:i]));
- return m_weekDayShortLabels;
- }
- for (unsigned i = 0; i < WTF_ARRAY_LENGTH(WTF::weekdayName); ++i) {
- // weekdayName starts with Monday.
- m_weekDayShortLabels.append(WTF::weekdayName[(i + 6) % 7]);
- }
- return m_weekDayShortLabels;
-}
-
-unsigned LocaleMac::firstDayOfWeek()
-{
- // The document for NSCalendar - firstWeekday doesn't have an explanation of
- // firstWeekday value. We can guess it by the document of NSDateComponents -
- // weekDay, so it can be 1 through 7 and 1 is Sunday.
- return [m_gregorianCalendar.get() firstWeekday] - 1;
-}
-
-bool LocaleMac::isRTL()
-{
- return NSLocaleLanguageDirectionRightToLeft == [NSLocale characterDirectionForLanguage:[NSLocale canonicalLanguageIdentifierFromString:[m_locale.get() localeIdentifier]]];
-}
-#endif
-
-RetainPtr<NSDateFormatter> LocaleMac::timeFormatter()
-{
- return createDateTimeFormatter(m_locale.get(), m_gregorianCalendar.get(), NSDateFormatterNoStyle, NSDateFormatterMediumStyle);
-}
-
-RetainPtr<NSDateFormatter> LocaleMac::shortTimeFormatter()
-{
- return createDateTimeFormatter(m_locale.get(), m_gregorianCalendar.get(), NSDateFormatterNoStyle, NSDateFormatterShortStyle);
-}
-
-RetainPtr<NSDateFormatter> LocaleMac::dateTimeFormatterWithSeconds()
-{
- return createDateTimeFormatter(m_locale.get(), m_gregorianCalendar.get(), NSDateFormatterShortStyle, NSDateFormatterMediumStyle);
-}
-
-RetainPtr<NSDateFormatter> LocaleMac::dateTimeFormatterWithoutSeconds()
-{
- return createDateTimeFormatter(m_locale.get(), m_gregorianCalendar.get(), NSDateFormatterShortStyle, NSDateFormatterShortStyle);
-}
-
-String LocaleMac::dateFormat()
-{
- if (!m_dateFormat.isNull())
- return m_dateFormat;
- m_dateFormat = [shortDateFormatter().get() dateFormat];
- return m_dateFormat;
-}
-
-String LocaleMac::monthFormat()
-{
- if (!m_monthFormat.isNull())
- return m_monthFormat;
- // Gets a format for "MMMM" because Windows API always provides formats for
- // "MMMM" in some locales.
- m_monthFormat = [NSDateFormatter dateFormatFromTemplate:@"yyyyMMMM" options:0 locale:m_locale.get()];
- return m_monthFormat;
-}
-
-String LocaleMac::shortMonthFormat()
-{
- if (!m_shortMonthFormat.isNull())
- return m_shortMonthFormat;
- m_shortMonthFormat = [NSDateFormatter dateFormatFromTemplate:@"yyyyMMM" options:0 locale:m_locale.get()];
- return m_shortMonthFormat;
-}
-
-String LocaleMac::timeFormat()
-{
- if (!m_timeFormatWithSeconds.isNull())
- return m_timeFormatWithSeconds;
- m_timeFormatWithSeconds = [timeFormatter().get() dateFormat];
- return m_timeFormatWithSeconds;
-}
-
-String LocaleMac::shortTimeFormat()
-{
- if (!m_timeFormatWithoutSeconds.isNull())
- return m_timeFormatWithoutSeconds;
- m_timeFormatWithoutSeconds = [shortTimeFormatter().get() dateFormat];
- return m_timeFormatWithoutSeconds;
-}
-
-String LocaleMac::dateTimeFormatWithSeconds()
-{
- if (!m_dateTimeFormatWithSeconds.isNull())
- return m_dateTimeFormatWithSeconds;
- m_dateTimeFormatWithSeconds = [dateTimeFormatterWithSeconds().get() dateFormat];
- return m_dateTimeFormatWithSeconds;
-}
-
-String LocaleMac::dateTimeFormatWithoutSeconds()
-{
- if (!m_dateTimeFormatWithoutSeconds.isNull())
- return m_dateTimeFormatWithoutSeconds;
- m_dateTimeFormatWithoutSeconds = [dateTimeFormatterWithoutSeconds().get() dateFormat];
- return m_dateTimeFormatWithoutSeconds;
-}
-
-const Vector<String>& LocaleMac::shortMonthLabels()
-{
- if (!m_shortMonthLabels.isEmpty())
- return m_shortMonthLabels;
- m_shortMonthLabels.reserveCapacity(12);
- NSArray *array = [shortDateFormatter().get() shortMonthSymbols];
- if ([array count] == 12) {
- for (unsigned i = 0; i < 12; ++i)
- m_shortMonthLabels.append([array objectAtIndex:i]);
- return m_shortMonthLabels;
- }
- for (unsigned i = 0; i < WTF_ARRAY_LENGTH(WTF::monthName); ++i)
- m_shortMonthLabels.append(WTF::monthName[i]);
- return m_shortMonthLabels;
-}
-
-const Vector<String>& LocaleMac::standAloneMonthLabels()
-{
- if (!m_standAloneMonthLabels.isEmpty())
- return m_standAloneMonthLabels;
- NSArray *array = [shortDateFormatter().get() standaloneMonthSymbols];
- if ([array count] == 12) {
- m_standAloneMonthLabels.reserveCapacity(12);
- for (unsigned i = 0; i < 12; ++i)
- m_standAloneMonthLabels.append([array objectAtIndex:i]);
- return m_standAloneMonthLabels;
- }
- m_standAloneMonthLabels = shortMonthLabels();
- return m_standAloneMonthLabels;
-}
-
-const Vector<String>& LocaleMac::shortStandAloneMonthLabels()
-{
- if (!m_shortStandAloneMonthLabels.isEmpty())
- return m_shortStandAloneMonthLabels;
- NSArray *array = [shortDateFormatter().get() shortStandaloneMonthSymbols];
- if ([array count] == 12) {
- m_shortStandAloneMonthLabels.reserveCapacity(12);
- for (unsigned i = 0; i < 12; ++i)
- m_shortStandAloneMonthLabels.append([array objectAtIndex:i]);
- return m_shortStandAloneMonthLabels;
- }
- m_shortStandAloneMonthLabels = shortMonthLabels();
- return m_shortStandAloneMonthLabels;
-}
-
-const Vector<String>& LocaleMac::timeAMPMLabels()
-{
- if (!m_timeAMPMLabels.isEmpty())
- return m_timeAMPMLabels;
- m_timeAMPMLabels.reserveCapacity(2);
- RetainPtr<NSDateFormatter> formatter = shortTimeFormatter();
- m_timeAMPMLabels.append([formatter.get() AMSymbol]);
- m_timeAMPMLabels.append([formatter.get() PMSymbol]);
- return m_timeAMPMLabels;
-}
-
-void LocaleMac::initializeLocaleData()
-{
- if (m_didInitializeNumberData)
- return;
- m_didInitializeNumberData = true;
-
- RetainPtr<NSNumberFormatter> formatter(AdoptNS, [[NSNumberFormatter alloc] init]);
- [formatter.get() setLocale:m_locale.get()];
- [formatter.get() setNumberStyle:NSNumberFormatterDecimalStyle];
- [formatter.get() setUsesGroupingSeparator:NO];
-
- RetainPtr<NSNumber> sampleNumber(AdoptNS, [[NSNumber alloc] initWithDouble:9876543210]);
- String nineToZero([formatter.get() stringFromNumber:sampleNumber.get()]);
- if (nineToZero.length() != 10)
- return;
- Vector<String, DecimalSymbolsSize> symbols;
- for (unsigned i = 0; i < 10; ++i)
- symbols.append(nineToZero.substring(9 - i, 1));
- ASSERT(symbols.size() == DecimalSeparatorIndex);
- symbols.append([formatter.get() decimalSeparator]);
- ASSERT(symbols.size() == GroupSeparatorIndex);
- symbols.append([formatter.get() groupingSeparator]);
- ASSERT(symbols.size() == DecimalSymbolsSize);
-
- String positivePrefix([formatter.get() positivePrefix]);
- String positiveSuffix([formatter.get() positiveSuffix]);
- String negativePrefix([formatter.get() negativePrefix]);
- String negativeSuffix([formatter.get() negativeSuffix]);
- setLocaleData(symbols, positivePrefix, positiveSuffix, negativePrefix, negativeSuffix);
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/text/mac/StringImplMac.mm b/chromium/third_party/WebKit/Source/core/platform/text/mac/StringImplMac.mm
deleted file mode 100644
index d563103e490..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/text/mac/StringImplMac.mm
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Copyright (C) 2006, 2009 Apple Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#include "config.h"
-#include "wtf/text/StringImpl.h"
-
-#include "core/platform/mac/FoundationExtras.h"
-#include "wtf/RetainPtr.h"
-
-namespace WTF {
-
-StringImpl::operator NSString *()
-{
- return HardAutorelease(createCFString().leakRef());
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/text/mac/StringMac.mm b/chromium/third_party/WebKit/Source/core/platform/text/mac/StringMac.mm
deleted file mode 100644
index 046767d2ebb..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/text/mac/StringMac.mm
+++ /dev/null
@@ -1,51 +0,0 @@
-/**
- * Copyright (C) 2006 Apple Computer, Inc.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#include "config.h"
-#include "wtf/text/WTFString.h"
-
-#include <CoreFoundation/CFString.h>
-
-namespace WTF {
-
-String::String(NSString* str)
-{
- if (!str)
- return;
-
- CFIndex size = CFStringGetLength(reinterpret_cast<CFStringRef>(str));
- if (size == 0)
- m_impl = StringImpl::empty();
- else {
- Vector<LChar, 1024> lcharBuffer(size);
- CFIndex usedBufLen;
- CFIndex convertedsize = CFStringGetBytes(reinterpret_cast<CFStringRef>(str), CFRangeMake(0, size), kCFStringEncodingISOLatin1, 0, false, lcharBuffer.data(), size, &usedBufLen);
- if ((convertedsize == size) && (usedBufLen == size)) {
- m_impl = StringImpl::create(lcharBuffer.data(), size);
- return;
- }
-
- Vector<UChar, 1024> ucharBuffer(size);
- CFStringGetCharacters(reinterpret_cast<CFStringRef>(str), CFRangeMake(0, size), ucharBuffer.data());
- m_impl = StringImpl::create(ucharBuffer.data(), size);
- }
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/text/transcoder/FontTranscoder.cpp b/chromium/third_party/WebKit/Source/core/platform/text/transcoder/FontTranscoder.cpp
deleted file mode 100644
index d4d0e322dc0..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/text/transcoder/FontTranscoder.cpp
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- * Copyright (c) 2010, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/text/transcoder/FontTranscoder.h"
-
-#include "core/platform/graphics/FontDescription.h"
-#include "wtf/text/TextEncoding.h"
-#include "wtf/unicode/CharacterNames.h"
-
-namespace WebCore {
-
-FontTranscoder::FontTranscoder()
-{
- m_converterTypes.add("MS PGothic", BackslashToYenSign);
- UChar unicodeNameMSPGothic[] = {0xFF2D, 0xFF33, 0x0020, 0xFF30, 0x30B4, 0x30B7, 0x30C3, 0x30AF};
- m_converterTypes.add(AtomicString(unicodeNameMSPGothic, WTF_ARRAY_LENGTH(unicodeNameMSPGothic)), BackslashToYenSign);
-
- m_converterTypes.add("MS PMincho", BackslashToYenSign);
- UChar unicodeNameMSPMincho[] = {0xFF2D, 0xFF33, 0x0020, 0xFF30, 0x660E, 0x671D};
- m_converterTypes.add(AtomicString(unicodeNameMSPMincho, WTF_ARRAY_LENGTH(unicodeNameMSPMincho)), BackslashToYenSign);
-
- m_converterTypes.add("MS Gothic", BackslashToYenSign);
- UChar unicodeNameMSGothic[] = {0xFF2D, 0xFF33, 0x0020, 0x30B4, 0x30B7, 0x30C3, 0x30AF};
- m_converterTypes.add(AtomicString(unicodeNameMSGothic, WTF_ARRAY_LENGTH(unicodeNameMSGothic)), BackslashToYenSign);
-
- m_converterTypes.add("MS Mincho", BackslashToYenSign);
- UChar unicodeNameMSMincho[] = {0xFF2D, 0xFF33, 0x0020, 0x660E, 0x671D};
- m_converterTypes.add(AtomicString(unicodeNameMSMincho, WTF_ARRAY_LENGTH(unicodeNameMSMincho)), BackslashToYenSign);
-
- m_converterTypes.add("Meiryo", BackslashToYenSign);
- UChar unicodeNameMeiryo[] = {0x30E1, 0x30A4, 0x30EA, 0x30AA};
- m_converterTypes.add(AtomicString(unicodeNameMeiryo, WTF_ARRAY_LENGTH(unicodeNameMeiryo)), BackslashToYenSign);
-}
-
-FontTranscoder::ConverterType FontTranscoder::converterType(const FontDescription& fontDescription, const WTF::TextEncoding* encoding) const
-{
- const AtomicString& fontFamily = fontDescription.family().family().string();
- if (!fontFamily.isNull()) {
- HashMap<AtomicString, ConverterType>::const_iterator found = m_converterTypes.find(fontFamily);
- if (found != m_converterTypes.end())
- return found->value;
- }
-
- // IE's default fonts for Japanese encodings change backslashes into yen signs.
- // We emulate this behavior only when no font is explicitly specified.
- if (encoding && encoding->backslashAsCurrencySymbol() != '\\' && !fontDescription.isSpecifiedFont())
- return BackslashToYenSign;
-
- return NoConversion;
-}
-
-void FontTranscoder::convert(String& text, const FontDescription& fontDescription, const WTF::TextEncoding* encoding) const
-{
- switch (converterType(fontDescription, encoding)) {
- case BackslashToYenSign: {
- // FIXME: wtf/text/TextEncoding.h has similar code. We need to factor them out.
- text.replace('\\', yenSign);
- break;
- }
- case NoConversion:
- default:
- ASSERT_NOT_REACHED();
- }
-}
-
-bool FontTranscoder::needsTranscoding(const FontDescription& fontDescription, const WTF::TextEncoding* encoding) const
-{
- ConverterType type = converterType(fontDescription, encoding);
- return type != NoConversion;
-}
-
-FontTranscoder& fontTranscoder()
-{
- static FontTranscoder* transcoder = new FontTranscoder;
- return *transcoder;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/text/transcoder/FontTranscoder.h b/chromium/third_party/WebKit/Source/core/platform/text/transcoder/FontTranscoder.h
deleted file mode 100644
index 801633649a5..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/text/transcoder/FontTranscoder.h
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Copyright (c) 2010, Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef FontTranscoder_h
-#define FontTranscoder_h
-
-#include "wtf/HashMap.h"
-#include "wtf/Noncopyable.h"
-#include "wtf/text/AtomicStringHash.h"
-
-namespace WTF{
-class TextEncoding;
-}
-
-namespace WebCore {
-
-class FontDescription;
-
-class FontTranscoder {
- WTF_MAKE_NONCOPYABLE(FontTranscoder); WTF_MAKE_FAST_ALLOCATED;
-public:
- void convert(String& text, const FontDescription&, const WTF::TextEncoding* = 0) const;
- bool needsTranscoding(const FontDescription&, const WTF::TextEncoding* = 0) const;
-
-private:
- FontTranscoder();
- ~FontTranscoder(); // Not implemented to make sure nobody accidentally calls delete -- WebCore does not delete singletons.
-
- enum ConverterType {
- NoConversion, BackslashToYenSign,
- };
-
- ConverterType converterType(const FontDescription&, const WTF::TextEncoding*) const;
-
- HashMap<AtomicString, ConverterType> m_converterTypes;
-
- friend FontTranscoder& fontTranscoder();
-};
-
-FontTranscoder& fontTranscoder();
-
-} // namespace WebCore
-
-#endif // FontTranscoder_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/text/win/LocaleWin.cpp b/chromium/third_party/WebKit/Source/core/platform/text/win/LocaleWin.cpp
deleted file mode 100644
index 811fd6d82a2..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/text/win/LocaleWin.cpp
+++ /dev/null
@@ -1,587 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/text/win/LocaleWin.h"
-
-#include <windows.h>
-#include <limits>
-#include "core/platform/DateComponents.h"
-#include "core/platform/Language.h"
-#include "core/platform/LayoutTestSupport.h"
-#include "core/platform/LocalizedStrings.h"
-#include "core/platform/text/DateTimeFormat.h"
-#include "wtf/CurrentTime.h"
-#include "wtf/DateMath.h"
-#include "wtf/HashMap.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/text/StringBuffer.h"
-#include "wtf/text/StringBuilder.h"
-#include "wtf/text/StringHash.h"
-
-using namespace std;
-
-namespace WebCore {
-
-typedef LCID (WINAPI* LocaleNameToLCIDPtr)(LPCWSTR, DWORD);
-typedef HashMap<String, LCID> NameToLCIDMap;
-
-static String extractLanguageCode(const String& locale)
-{
- size_t dashPosition = locale.find('-');
- if (dashPosition == kNotFound)
- return locale;
- return locale.left(dashPosition);
-}
-
-static String removeLastComponent(const String& name)
-{
- size_t lastSeparator = name.reverseFind('-');
- if (lastSeparator == kNotFound)
- return emptyString();
- return name.left(lastSeparator);
-}
-
-static void ensureNameToLCIDMap(NameToLCIDMap& map)
-{
- if (!map.isEmpty())
- return;
- // http://www.microsoft.com/resources/msdn/goglobal/default.mspx
- // We add only locales used in layout tests for now.
- map.add("ar", 0x0001);
- map.add("ar-eg", 0x0C01);
- map.add("de", 0x0007);
- map.add("de-de", 0x0407);
- map.add("el", 0x0008);
- map.add("el-gr", 0x0408);
- map.add("en", 0x0009);
- map.add("en-gb", 0x0809);
- map.add("en-us", 0x0409);
- map.add("fr", 0x000C);
- map.add("fr-fr", 0x040C);
- map.add("he", 0x000D);
- map.add("he-il", 0x040D);
- map.add("hi", 0x0039);
- map.add("hi-in", 0x0439);
- map.add("ja", 0x0011);
- map.add("ja-jp", 0x0411);
- map.add("ko", 0x0012);
- map.add("ko-kr", 0x0412);
- map.add("ru", 0x0019);
- map.add("ru-ru", 0x0419);
- map.add("zh-cn", 0x0804);
- map.add("zh-tw", 0x0404);
-}
-
-// Fallback implementation of LocaleNameToLCID API. This is used for
-// testing on Windows XP.
-// FIXME: Remove this, ensureNameToLCIDMap, and removeLastComponent when we drop
-// Windows XP support.
-static LCID WINAPI convertLocaleNameToLCID(LPCWSTR name, DWORD)
-{
- if (!name || !name[0])
- return LOCALE_USER_DEFAULT;
- DEFINE_STATIC_LOCAL(NameToLCIDMap, map, ());
- ensureNameToLCIDMap(map);
- String localeName = String(name).replace('_', '-');
- localeName.makeLower();
- do {
- NameToLCIDMap::const_iterator iterator = map.find(localeName);
- if (iterator != map.end())
- return iterator->value;
- localeName = removeLastComponent(localeName);
- } while (!localeName.isEmpty());
- return LOCALE_USER_DEFAULT;
-}
-
-static LCID LCIDFromLocaleInternal(LCID userDefaultLCID, const String& userDefaultLanguageCode, LocaleNameToLCIDPtr localeNameToLCID, String& locale)
-{
- String localeLanguageCode = extractLanguageCode(locale);
- if (equalIgnoringCase(localeLanguageCode, userDefaultLanguageCode))
- return userDefaultLCID;
- return localeNameToLCID(locale.charactersWithNullTermination().data(), 0);
-}
-
-static LCID LCIDFromLocale(const AtomicString& locale, bool defaultsForLocale)
-{
- // LocaleNameToLCID() is available since Windows Vista.
- LocaleNameToLCIDPtr localeNameToLCID = reinterpret_cast<LocaleNameToLCIDPtr>(::GetProcAddress(::GetModuleHandle(L"kernel32"), "LocaleNameToLCID"));
- if (!localeNameToLCID)
- localeNameToLCID = convertLocaleNameToLCID;
-
- // According to MSDN, 9 is enough for LOCALE_SISO639LANGNAME.
- const size_t languageCodeBufferSize = 9;
- WCHAR lowercaseLanguageCode[languageCodeBufferSize];
- ::GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_SISO639LANGNAME | (defaultsForLocale ? LOCALE_NOUSEROVERRIDE : 0), lowercaseLanguageCode, languageCodeBufferSize);
- String userDefaultLanguageCode = String(lowercaseLanguageCode);
-
- LCID lcid = LCIDFromLocaleInternal(LOCALE_USER_DEFAULT, userDefaultLanguageCode, localeNameToLCID, String(locale));
- if (!lcid)
- lcid = LCIDFromLocaleInternal(LOCALE_USER_DEFAULT, userDefaultLanguageCode, localeNameToLCID, defaultLanguage());
- return lcid;
-}
-
-PassOwnPtr<Locale> Locale::create(const AtomicString& locale)
-{
- // Whether the default settings for the locale should be used, ignoring user overrides.
- bool defaultsForLocale = isRunningLayoutTest();
- return LocaleWin::create(LCIDFromLocale(locale, defaultsForLocale), defaultsForLocale);
-}
-
-inline LocaleWin::LocaleWin(LCID lcid, bool defaultsForLocale)
- : m_lcid(lcid)
- , m_didInitializeNumberData(false)
- , m_defaultsForLocale(defaultsForLocale)
-{
-#if ENABLE(CALENDAR_PICKER)
- DWORD value = 0;
- getLocaleInfo(LOCALE_IFIRSTDAYOFWEEK | (defaultsForLocale ? LOCALE_NOUSEROVERRIDE : 0), value);
- // 0:Monday, ..., 6:Sunday.
- // We need 1 for Monday, 0 for Sunday.
- m_firstDayOfWeek = (value + 1) % 7;
-#endif
-}
-
-PassOwnPtr<LocaleWin> LocaleWin::create(LCID lcid, bool defaultsForLocale)
-{
- return adoptPtr(new LocaleWin(lcid, defaultsForLocale));
-}
-
-LocaleWin::~LocaleWin()
-{
-}
-
-String LocaleWin::getLocaleInfoString(LCTYPE type)
-{
- int bufferSizeWithNUL = ::GetLocaleInfo(m_lcid, type | (m_defaultsForLocale ? LOCALE_NOUSEROVERRIDE : 0), 0, 0);
- if (bufferSizeWithNUL <= 0)
- return String();
- StringBuffer<UChar> buffer(bufferSizeWithNUL);
- ::GetLocaleInfo(m_lcid, type | (m_defaultsForLocale ? LOCALE_NOUSEROVERRIDE : 0), buffer.characters(), bufferSizeWithNUL);
- buffer.shrink(bufferSizeWithNUL - 1);
- return String::adopt(buffer);
-}
-
-void LocaleWin::getLocaleInfo(LCTYPE type, DWORD& result)
-{
- ::GetLocaleInfo(m_lcid, type | LOCALE_RETURN_NUMBER, reinterpret_cast<LPWSTR>(&result), sizeof(DWORD) / sizeof(TCHAR));
-}
-
-void LocaleWin::ensureShortMonthLabels()
-{
- if (!m_shortMonthLabels.isEmpty())
- return;
- const LCTYPE types[12] = {
- LOCALE_SABBREVMONTHNAME1,
- LOCALE_SABBREVMONTHNAME2,
- LOCALE_SABBREVMONTHNAME3,
- LOCALE_SABBREVMONTHNAME4,
- LOCALE_SABBREVMONTHNAME5,
- LOCALE_SABBREVMONTHNAME6,
- LOCALE_SABBREVMONTHNAME7,
- LOCALE_SABBREVMONTHNAME8,
- LOCALE_SABBREVMONTHNAME9,
- LOCALE_SABBREVMONTHNAME10,
- LOCALE_SABBREVMONTHNAME11,
- LOCALE_SABBREVMONTHNAME12,
- };
- m_shortMonthLabels.reserveCapacity(WTF_ARRAY_LENGTH(types));
- for (unsigned i = 0; i < WTF_ARRAY_LENGTH(types); ++i) {
- m_shortMonthLabels.append(getLocaleInfoString(types[i]));
- if (m_shortMonthLabels.last().isEmpty()) {
- m_shortMonthLabels.shrink(0);
- m_shortMonthLabels.reserveCapacity(WTF_ARRAY_LENGTH(WTF::monthName));
- for (unsigned m = 0; m < WTF_ARRAY_LENGTH(WTF::monthName); ++m)
- m_shortMonthLabels.append(WTF::monthName[m]);
- return;
- }
- }
-}
-
-// -------------------------------- Tokenized date format
-
-static unsigned countContinuousLetters(const String& format, unsigned index)
-{
- unsigned count = 1;
- UChar reference = format[index];
- while (index + 1 < format.length()) {
- if (format[++index] != reference)
- break;
- ++count;
- }
- return count;
-}
-
-static void commitLiteralToken(StringBuilder& literalBuffer, StringBuilder& converted)
-{
- if (literalBuffer.length() <= 0)
- return;
- DateTimeFormat::quoteAndAppendLiteral(literalBuffer.toString(), converted);
- literalBuffer.clear();
-}
-
-// This function converts Windows date/time pattern format [1][2] into LDML date
-// format pattern [3].
-//
-// i.e.
-// We set h, H, m, s, d, dd, M, or y as is. They have same meaning in both of
-// Windows and LDML.
-// We need to convert the following patterns:
-// t -> a
-// tt -> a
-// ddd -> EEE
-// dddd -> EEEE
-// g -> G
-// gg -> ignore
-//
-// [1] http://msdn.microsoft.com/en-us/library/dd317787(v=vs.85).aspx
-// [2] http://msdn.microsoft.com/en-us/library/dd318148(v=vs.85).aspx
-// [3] LDML http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns
-static String convertWindowsDateTimeFormat(const String& format)
-{
- StringBuilder converted;
- StringBuilder literalBuffer;
- bool inQuote = false;
- bool lastQuoteCanBeLiteral = false;
- for (unsigned i = 0; i < format.length(); ++i) {
- UChar ch = format[i];
- if (inQuote) {
- if (ch == '\'') {
- inQuote = false;
- ASSERT(i);
- if (lastQuoteCanBeLiteral && format[i - 1] == '\'') {
- literalBuffer.append('\'');
- lastQuoteCanBeLiteral = false;
- } else
- lastQuoteCanBeLiteral = true;
- } else
- literalBuffer.append(ch);
- continue;
- }
-
- if (ch == '\'') {
- inQuote = true;
- if (lastQuoteCanBeLiteral && i > 0 && format[i - 1] == '\'') {
- literalBuffer.append(ch);
- lastQuoteCanBeLiteral = false;
- } else
- lastQuoteCanBeLiteral = true;
- } else if (isASCIIAlpha(ch)) {
- commitLiteralToken(literalBuffer, converted);
- unsigned symbolStart = i;
- unsigned count = countContinuousLetters(format, i);
- i += count - 1;
- if (ch == 'h' || ch == 'H' || ch == 'm' || ch == 's' || ch == 'M' || ch == 'y')
- converted.append(format, symbolStart, count);
- else if (ch == 'd') {
- if (count <= 2)
- converted.append(format, symbolStart, count);
- else if (count == 3)
- converted.append("EEE");
- else
- converted.append("EEEE");
- } else if (ch == 'g') {
- if (count == 1)
- converted.append('G');
- else {
- // gg means imperial era in Windows.
- // Just ignore it.
- }
- } else if (ch == 't')
- converted.append('a');
- else
- literalBuffer.append(format, symbolStart, count);
- } else
- literalBuffer.append(ch);
- }
- commitLiteralToken(literalBuffer, converted);
- return converted.toString();
-}
-
-void LocaleWin::ensureMonthLabels()
-{
- if (!m_monthLabels.isEmpty())
- return;
- const LCTYPE types[12] = {
- LOCALE_SMONTHNAME1,
- LOCALE_SMONTHNAME2,
- LOCALE_SMONTHNAME3,
- LOCALE_SMONTHNAME4,
- LOCALE_SMONTHNAME5,
- LOCALE_SMONTHNAME6,
- LOCALE_SMONTHNAME7,
- LOCALE_SMONTHNAME8,
- LOCALE_SMONTHNAME9,
- LOCALE_SMONTHNAME10,
- LOCALE_SMONTHNAME11,
- LOCALE_SMONTHNAME12,
- };
- m_monthLabels.reserveCapacity(WTF_ARRAY_LENGTH(types));
- for (unsigned i = 0; i < WTF_ARRAY_LENGTH(types); ++i) {
- m_monthLabels.append(getLocaleInfoString(types[i]));
- if (m_monthLabels.last().isEmpty()) {
- m_monthLabels.shrink(0);
- m_monthLabels.reserveCapacity(WTF_ARRAY_LENGTH(WTF::monthFullName));
- for (unsigned m = 0; m < WTF_ARRAY_LENGTH(WTF::monthFullName); ++m)
- m_monthLabels.append(WTF::monthFullName[m]);
- return;
- }
- }
-}
-
-void LocaleWin::ensureWeekDayShortLabels()
-{
- if (!m_weekDayShortLabels.isEmpty())
- return;
- const LCTYPE types[7] = {
- LOCALE_SABBREVDAYNAME7, // Sunday
- LOCALE_SABBREVDAYNAME1, // Monday
- LOCALE_SABBREVDAYNAME2,
- LOCALE_SABBREVDAYNAME3,
- LOCALE_SABBREVDAYNAME4,
- LOCALE_SABBREVDAYNAME5,
- LOCALE_SABBREVDAYNAME6
- };
- m_weekDayShortLabels.reserveCapacity(WTF_ARRAY_LENGTH(types));
- for (unsigned i = 0; i < WTF_ARRAY_LENGTH(types); ++i) {
- m_weekDayShortLabels.append(getLocaleInfoString(types[i]));
- if (m_weekDayShortLabels.last().isEmpty()) {
- m_weekDayShortLabels.shrink(0);
- m_weekDayShortLabels.reserveCapacity(WTF_ARRAY_LENGTH(WTF::weekdayName));
- for (unsigned w = 0; w < WTF_ARRAY_LENGTH(WTF::weekdayName); ++w) {
- // weekdayName starts with Monday.
- m_weekDayShortLabels.append(WTF::weekdayName[(w + 6) % 7]);
- }
- return;
- }
- }
-}
-
-const Vector<String>& LocaleWin::monthLabels()
-{
- ensureMonthLabels();
- return m_monthLabels;
-}
-
-#if ENABLE(CALENDAR_PICKER)
-const Vector<String>& LocaleWin::weekDayShortLabels()
-{
- ensureWeekDayShortLabels();
- return m_weekDayShortLabels;
-}
-
-unsigned LocaleWin::firstDayOfWeek()
-{
- return m_firstDayOfWeek;
-}
-
-bool LocaleWin::isRTL()
-{
- WTF::Unicode::Direction dir = WTF::Unicode::direction(monthLabels()[0][0]);
- return dir == WTF::Unicode::RightToLeft || dir == WTF::Unicode::RightToLeftArabic;
-}
-#endif
-
-String LocaleWin::dateFormat()
-{
- if (m_dateFormat.isNull())
- m_dateFormat = convertWindowsDateTimeFormat(getLocaleInfoString(LOCALE_SSHORTDATE));
- return m_dateFormat;
-}
-
-String LocaleWin::dateFormat(const String& windowsFormat)
-{
- return convertWindowsDateTimeFormat(windowsFormat);
-}
-
-String LocaleWin::monthFormat()
-{
- if (m_monthFormat.isNull())
- m_monthFormat = convertWindowsDateTimeFormat(getLocaleInfoString(LOCALE_SYEARMONTH));
- return m_monthFormat;
-}
-
-String LocaleWin::shortMonthFormat()
-{
- if (m_shortMonthFormat.isNull())
- m_shortMonthFormat = convertWindowsDateTimeFormat(getLocaleInfoString(LOCALE_SYEARMONTH)).replace("MMMM", "MMM");
- return m_shortMonthFormat;
-}
-
-String LocaleWin::timeFormat()
-{
- if (m_timeFormatWithSeconds.isNull())
- m_timeFormatWithSeconds = convertWindowsDateTimeFormat(getLocaleInfoString(LOCALE_STIMEFORMAT));
- return m_timeFormatWithSeconds;
-}
-
-String LocaleWin::shortTimeFormat()
-{
- if (!m_timeFormatWithoutSeconds.isNull())
- return m_timeFormatWithoutSeconds;
- String format = getLocaleInfoString(LOCALE_SSHORTTIME);
- // Vista or older Windows doesn't support LOCALE_SSHORTTIME.
- if (format.isEmpty()) {
- format = getLocaleInfoString(LOCALE_STIMEFORMAT);
- StringBuilder builder;
- builder.append(getLocaleInfoString(LOCALE_STIME));
- builder.append("ss");
- size_t pos = format.reverseFind(builder.toString());
- if (pos != kNotFound)
- format.remove(pos, builder.length());
- }
- m_timeFormatWithoutSeconds = convertWindowsDateTimeFormat(format);
- return m_timeFormatWithoutSeconds;
-}
-
-String LocaleWin::dateTimeFormatWithSeconds()
-{
- if (!m_dateTimeFormatWithSeconds.isNull())
- return m_dateTimeFormatWithSeconds;
- StringBuilder builder;
- builder.append(dateFormat());
- builder.append(' ');
- builder.append(timeFormat());
- m_dateTimeFormatWithSeconds = builder.toString();
- return m_dateTimeFormatWithSeconds;
-}
-
-String LocaleWin::dateTimeFormatWithoutSeconds()
-{
- if (!m_dateTimeFormatWithoutSeconds.isNull())
- return m_dateTimeFormatWithoutSeconds;
- StringBuilder builder;
- builder.append(dateFormat());
- builder.append(' ');
- builder.append(shortTimeFormat());
- m_dateTimeFormatWithoutSeconds = builder.toString();
- return m_dateTimeFormatWithoutSeconds;
-}
-
-const Vector<String>& LocaleWin::shortMonthLabels()
-{
- ensureShortMonthLabels();
- return m_shortMonthLabels;
-}
-
-const Vector<String>& LocaleWin::standAloneMonthLabels()
-{
- // Windows doesn't provide a way to get stand-alone month labels.
- return monthLabels();
-}
-
-const Vector<String>& LocaleWin::shortStandAloneMonthLabels()
-{
- // Windows doesn't provide a way to get stand-alone month labels.
- return shortMonthLabels();
-}
-
-const Vector<String>& LocaleWin::timeAMPMLabels()
-{
- if (m_timeAMPMLabels.isEmpty()) {
- m_timeAMPMLabels.append(getLocaleInfoString(LOCALE_S1159));
- m_timeAMPMLabels.append(getLocaleInfoString(LOCALE_S2359));
- }
- return m_timeAMPMLabels;
-}
-
-void LocaleWin::initializeLocaleData()
-{
- if (m_didInitializeNumberData)
- return;
-
- Vector<String, DecimalSymbolsSize> symbols;
- enum DigitSubstitution {
- DigitSubstitutionContext = 0,
- DigitSubstitution0to9 = 1,
- DigitSubstitutionNative = 2,
- };
- DWORD digitSubstitution = DigitSubstitution0to9;
- getLocaleInfo(LOCALE_IDIGITSUBSTITUTION, digitSubstitution);
- if (digitSubstitution == DigitSubstitution0to9) {
- symbols.append("0");
- symbols.append("1");
- symbols.append("2");
- symbols.append("3");
- symbols.append("4");
- symbols.append("5");
- symbols.append("6");
- symbols.append("7");
- symbols.append("8");
- symbols.append("9");
- } else {
- String digits = getLocaleInfoString(LOCALE_SNATIVEDIGITS);
- ASSERT(digits.length() >= 10);
- for (unsigned i = 0; i < 10; ++i)
- symbols.append(digits.substring(i, 1));
- }
- ASSERT(symbols.size() == DecimalSeparatorIndex);
- symbols.append(getLocaleInfoString(LOCALE_SDECIMAL));
- ASSERT(symbols.size() == GroupSeparatorIndex);
- symbols.append(getLocaleInfoString(LOCALE_STHOUSAND));
- ASSERT(symbols.size() == DecimalSymbolsSize);
-
- String negativeSign = getLocaleInfoString(LOCALE_SNEGATIVESIGN);
- enum NegativeFormat {
- NegativeFormatParenthesis = 0,
- NegativeFormatSignPrefix = 1,
- NegativeFormatSignSpacePrefix = 2,
- NegativeFormatSignSuffix = 3,
- NegativeFormatSpaceSignSuffix = 4,
- };
- DWORD negativeFormat = NegativeFormatSignPrefix;
- getLocaleInfo(LOCALE_INEGNUMBER, negativeFormat);
- String negativePrefix = emptyString();
- String negativeSuffix = emptyString();
- switch (negativeFormat) {
- case NegativeFormatParenthesis:
- negativePrefix = "(";
- negativeSuffix = ")";
- break;
- case NegativeFormatSignSpacePrefix:
- negativePrefix = negativeSign + " ";
- break;
- case NegativeFormatSignSuffix:
- negativeSuffix = negativeSign;
- break;
- case NegativeFormatSpaceSignSuffix:
- negativeSuffix = " " + negativeSign;
- break;
- case NegativeFormatSignPrefix: // Fall through.
- default:
- negativePrefix = negativeSign;
- break;
- }
- m_didInitializeNumberData = true;
- setLocaleData(symbols, emptyString(), emptyString(), negativePrefix, negativeSuffix);
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/platform/text/win/LocaleWin.h b/chromium/third_party/WebKit/Source/core/platform/text/win/LocaleWin.h
deleted file mode 100644
index cc843ca01db..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/text/win/LocaleWin.h
+++ /dev/null
@@ -1,101 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef LocaleWin_h
-#define LocaleWin_h
-
-#include <windows.h>
-#include "core/platform/text/PlatformLocale.h"
-#include "wtf/Forward.h"
-#include "wtf/text/WTFString.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-class DateComponents;
-struct DateFormatToken;
-
-class LocaleWin : public Locale {
-public:
- static PassOwnPtr<LocaleWin> create(LCID, bool defaultsForLocale);
- ~LocaleWin();
-#if ENABLE(CALENDAR_PICKER)
- virtual const Vector<String>& weekDayShortLabels() OVERRIDE;
- virtual unsigned firstDayOfWeek() OVERRIDE;
- virtual bool isRTL() OVERRIDE;
-#endif
- virtual String dateFormat() OVERRIDE;
- virtual String monthFormat() OVERRIDE;
- virtual String shortMonthFormat() OVERRIDE;
- virtual String timeFormat() OVERRIDE;
- virtual String shortTimeFormat() OVERRIDE;
- virtual String dateTimeFormatWithSeconds() OVERRIDE;
- virtual String dateTimeFormatWithoutSeconds() OVERRIDE;
- virtual const Vector<String>& monthLabels() OVERRIDE;
- virtual const Vector<String>& shortMonthLabels() OVERRIDE;
- virtual const Vector<String>& standAloneMonthLabels() OVERRIDE;
- virtual const Vector<String>& shortStandAloneMonthLabels() OVERRIDE;
- virtual const Vector<String>& timeAMPMLabels() OVERRIDE;
-
- static String dateFormat(const String&);
-
-private:
- explicit LocaleWin(LCID, bool defaultsForLocale);
- String getLocaleInfoString(LCTYPE);
- void getLocaleInfo(LCTYPE, DWORD&);
- void ensureShortMonthLabels();
- void ensureMonthLabels();
-#if ENABLE(CALENDAR_PICKER)
- void ensureWeekDayShortLabels();
-#endif
- // Locale function:
- virtual void initializeLocaleData() OVERRIDE;
-
- LCID m_lcid;
- Vector<String> m_shortMonthLabels;
- Vector<String> m_monthLabels;
- String m_dateFormat;
- String m_monthFormat;
- String m_shortMonthFormat;
- String m_timeFormatWithSeconds;
- String m_timeFormatWithoutSeconds;
- String m_dateTimeFormatWithSeconds;
- String m_dateTimeFormatWithoutSeconds;
- Vector<String> m_timeAMPMLabels;
-#if ENABLE(CALENDAR_PICKER)
- Vector<String> m_weekDayShortLabels;
- unsigned m_firstDayOfWeek;
-#endif
- bool m_didInitializeNumberData;
- bool m_defaultsForLocale;
-};
-
-} // namespace WebCore
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/platform/win/HWndDC.h b/chromium/third_party/WebKit/Source/core/platform/win/HWndDC.h
deleted file mode 100644
index 53cb538177e..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/win/HWndDC.h
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef HWndDC_h
-#define HWndDC_h
-
-#include <windows.h>
-#include "wtf/NonCopyable.h"
-
-namespace WebCore {
-
-class HWndDC {
- WTF_MAKE_NONCOPYABLE(HWndDC);
-public:
- HWndDC()
- : m_hwnd(0)
- , m_hdc(0)
- {
- }
-
- explicit HWndDC(HWND hwnd)
- : m_hwnd(hwnd)
- , m_hdc(::GetDC(hwnd))
- {
- }
-
- HWndDC(HWND hwnd, HRGN hrgnClip, DWORD flags)
- : m_hwnd(hwnd)
- , m_hdc(::GetDCEx(hwnd, hrgnClip, flags))
- {
- }
-
- ~HWndDC()
- {
- clear();
- }
-
- HDC setHWnd(HWND hwnd)
- {
- clear();
- m_hwnd = hwnd;
- m_hdc = ::GetDC(hwnd);
- return m_hdc;
- }
-
- void clear()
- {
- if (!m_hdc)
- return;
- ::ReleaseDC(m_hwnd, m_hdc);
- m_hwnd = 0;
- m_hdc = 0;
- }
-
- operator HDC()
- {
- return m_hdc;
- }
-
-private:
- HWND m_hwnd;
- HDC m_hdc;
-};
-
-} // namespace WebCore
-
-#endif // HWndDC_h
diff --git a/chromium/third_party/WebKit/Source/core/platform/win/SystemInfo.cpp b/chromium/third_party/WebKit/Source/core/platform/win/SystemInfo.cpp
deleted file mode 100644
index b746c81da2b..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/win/SystemInfo.cpp
+++ /dev/null
@@ -1,166 +0,0 @@
-/*
- * Copyright (C) 2009 Apple Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/win/SystemInfo.h"
-
-#include <windows.h>
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-WindowsVersion windowsVersion(int* major, int* minor)
-{
- static bool initialized = false;
- static WindowsVersion version;
- static int majorVersion, minorVersion;
-
- if (!initialized) {
- initialized = true;
- OSVERSIONINFOEX versionInfo;
- ZeroMemory(&versionInfo, sizeof(versionInfo));
- versionInfo.dwOSVersionInfoSize = sizeof(versionInfo);
- GetVersionEx(reinterpret_cast<OSVERSIONINFO*>(&versionInfo));
- majorVersion = versionInfo.dwMajorVersion;
- minorVersion = versionInfo.dwMinorVersion;
-
- if (versionInfo.dwPlatformId == VER_PLATFORM_WIN32s)
- version = Windows3_1;
- else if (versionInfo.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {
- if (!minorVersion)
- version = Windows95;
- else
- version = (minorVersion == 10) ? Windows98 : WindowsME;
- } else {
- if (majorVersion == 5) {
- if (!minorVersion)
- version = Windows2000;
- else
- version = (minorVersion == 1) ? WindowsXP : WindowsServer2003;
- } else if (majorVersion >= 6) {
- if (versionInfo.wProductType == VER_NT_WORKSTATION)
- version = (majorVersion == 6 && !minorVersion) ? WindowsVista : Windows7;
- else
- version = WindowsServer2008;
- } else
- version = (majorVersion == 4) ? WindowsNT4 : WindowsNT3;
- }
- }
-
- if (major)
- *major = majorVersion;
- if (minor)
- *minor = minorVersion;
- return version;
-}
-
-static String osVersionForUAString()
-{
- int major, minor;
- WindowsVersion version = windowsVersion(&major, &minor);
- switch (version) {
- case WindowsCE1:
- case WindowsCE2:
- case WindowsCE3:
- return "Windows CE";
- case WindowsCE4:
- return "Windows CE .NET";
- case Windows3_1:
- return "Windows 3.1";
- case Windows95:
- return "Windows 95";
- case Windows98:
- return "Windows 98";
- case WindowsME:
- return "Windows 98; Win 9x 4.90";
- case WindowsNT4:
- return "WinNT4.0";
- }
-
- const char* familyName = (version >= WindowsNT3) ? "Windows NT " : "Windows CE ";
- return familyName + String::number(major) + '.' + String::number(minor);
-}
-
-static bool isWOW64()
-{
- static bool initialized = false;
- static bool wow64 = false;
-
- if (!initialized) {
- initialized = true;
- HMODULE kernel32Module = GetModuleHandleA("kernel32.dll");
- if (!kernel32Module)
- return wow64;
- typedef BOOL (WINAPI* IsWow64ProcessFunc)(HANDLE, PBOOL);
- IsWow64ProcessFunc isWOW64Process = reinterpret_cast<IsWow64ProcessFunc>(GetProcAddress(kernel32Module, "IsWow64Process"));
- if (isWOW64Process) {
- BOOL result = FALSE;
- wow64 = isWOW64Process(GetCurrentProcess(), &result) && result;
- }
- }
-
- return wow64;
-}
-
-static WORD processorArchitecture()
-{
- static bool initialized = false;
- static WORD architecture = PROCESSOR_ARCHITECTURE_INTEL;
-
- if (!initialized) {
- initialized = true;
- HMODULE kernel32Module = GetModuleHandleA("kernel32.dll");
- if (!kernel32Module)
- return architecture;
- typedef VOID (WINAPI* GetNativeSystemInfoFunc)(LPSYSTEM_INFO);
- GetNativeSystemInfoFunc getNativeSystemInfo = reinterpret_cast<GetNativeSystemInfoFunc>(GetProcAddress(kernel32Module, "GetNativeSystemInfo"));
- if (getNativeSystemInfo) {
- SYSTEM_INFO systemInfo;
- ZeroMemory(&systemInfo, sizeof(systemInfo));
- getNativeSystemInfo(&systemInfo);
- architecture = systemInfo.wProcessorArchitecture;
- }
- }
-
- return architecture;
-}
-
-static String architectureTokenForUAString()
-{
- if (isWOW64())
- return "; WOW64";
- if (processorArchitecture() == PROCESSOR_ARCHITECTURE_AMD64)
- return "; Win64; x64";
- if (processorArchitecture() == PROCESSOR_ARCHITECTURE_IA64)
- return "; Win64; IA64";
- return String();
-}
-
-String windowsVersionForUAString()
-{
- return osVersionForUAString() + architectureTokenForUAString();
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/platform/win/SystemInfo.h b/chromium/third_party/WebKit/Source/core/platform/win/SystemInfo.h
deleted file mode 100644
index f9e79e28503..00000000000
--- a/chromium/third_party/WebKit/Source/core/platform/win/SystemInfo.h
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * Copyright (C) 2009 Apple Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SystemInfo_h
-#define SystemInfo_h
-
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-// NOTE: Keep these in order so callers can do things like
-// "if (windowsVersion() >= WindowsVista) ...". It's OK to change or add values,
-// though.
-enum WindowsVersion {
- // CE-based versions
- WindowsCE1 = 0,
- WindowsCE2,
- WindowsCE3,
- WindowsCE4,
- WindowsCE5,
- WindowsCE6,
- WindowsCE7,
- // 3.x-based versions
- Windows3_1,
- // 9x-based versions
- Windows95,
- Windows98,
- WindowsME,
- // NT-based versions
- WindowsNT3,
- WindowsNT4,
- Windows2000,
- WindowsXP,
- WindowsServer2003,
- WindowsVista,
- WindowsServer2008,
- Windows7,
-};
-
-// If supplied, |major| and |minor| are set to the OSVERSIONINFO::dwMajorVersion
-// and dwMinorVersion field values, respectively.
-WindowsVersion windowsVersion(int* major = 0, int* minor = 0);
-
-String windowsVersionForUAString();
-
-} // namespace WebCore
-
-#endif // SystemInfo_h
diff --git a/chromium/third_party/WebKit/Source/core/plugins/DOMMimeType.cpp b/chromium/third_party/WebKit/Source/core/plugins/DOMMimeType.cpp
index 709ef2ca7d7..ecd812a262e 100644
--- a/chromium/third_party/WebKit/Source/core/plugins/DOMMimeType.cpp
+++ b/chromium/third_party/WebKit/Source/core/plugins/DOMMimeType.cpp
@@ -20,10 +20,9 @@
#include "core/plugins/DOMMimeType.h"
#include "core/loader/FrameLoader.h"
-#include "core/page/Frame.h"
+#include "core/frame/Frame.h"
#include "core/page/Page.h"
#include "core/plugins/DOMPlugin.h"
-#include "core/plugins/PluginData.h"
#include "wtf/text/StringBuilder.h"
namespace WebCore {
@@ -65,7 +64,10 @@ const String &DOMMimeType::description() const
PassRefPtr<DOMPlugin> DOMMimeType::enabledPlugin() const
{
- if (!m_frame || !m_frame->page() || !m_frame->page()->mainFrame()->loader()->allowPlugins(NotAboutToInstantiatePlugin))
+ // FIXME: allowPlugins is just a client call. We should not need
+ // to bounce through the page or mainframe or loader to get there.
+ // Something like: m_frame->host()->client()->allowPlugins().
+ if (!m_frame || !m_frame->page() || !m_frame->page()->mainFrame()->loader().allowPlugins(NotAboutToInstantiatePlugin))
return 0;
return DOMPlugin::create(m_pluginData.get(), m_frame, m_pluginData->mimePluginIndices()[m_index]);
diff --git a/chromium/third_party/WebKit/Source/core/plugins/DOMMimeType.h b/chromium/third_party/WebKit/Source/core/plugins/DOMMimeType.h
index cf8fb89dc7b..8670725b717 100644
--- a/chromium/third_party/WebKit/Source/core/plugins/DOMMimeType.h
+++ b/chromium/third_party/WebKit/Source/core/plugins/DOMMimeType.h
@@ -21,8 +21,8 @@
#define DOMMimeType_h
#include "bindings/v8/ScriptWrappable.h"
-#include "core/page/FrameDestructionObserver.h"
-#include "core/plugins/PluginData.h"
+#include "core/frame/FrameDestructionObserver.h"
+#include "platform/plugins/PluginData.h"
#include "wtf/Forward.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefCounted.h"
diff --git a/chromium/third_party/WebKit/Source/core/plugins/DOMMimeTypeArray.cpp b/chromium/third_party/WebKit/Source/core/plugins/DOMMimeTypeArray.cpp
index 87f9a86e78d..cddfa8326e2 100644
--- a/chromium/third_party/WebKit/Source/core/plugins/DOMMimeTypeArray.cpp
+++ b/chromium/third_party/WebKit/Source/core/plugins/DOMMimeTypeArray.cpp
@@ -20,9 +20,9 @@
#include "config.h"
#include "core/plugins/DOMMimeTypeArray.h"
-#include "core/page/Frame.h"
+#include "core/frame/Frame.h"
#include "core/page/Page.h"
-#include "core/plugins/PluginData.h"
+#include "platform/plugins/PluginData.h"
#include "wtf/text/AtomicString.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/plugins/DOMMimeTypeArray.h b/chromium/third_party/WebKit/Source/core/plugins/DOMMimeTypeArray.h
index d9acd83ea81..651edee0892 100644
--- a/chromium/third_party/WebKit/Source/core/plugins/DOMMimeTypeArray.h
+++ b/chromium/third_party/WebKit/Source/core/plugins/DOMMimeTypeArray.h
@@ -22,7 +22,7 @@
#define DOMMimeTypeArray_h
#include "bindings/v8/ScriptWrappable.h"
-#include "core/page/DOMWindowProperty.h"
+#include "core/frame/DOMWindowProperty.h"
#include "core/plugins/DOMMimeType.h"
#include "wtf/Forward.h"
#include "wtf/PassRefPtr.h"
diff --git a/chromium/third_party/WebKit/Source/core/plugins/DOMPlugin.cpp b/chromium/third_party/WebKit/Source/core/plugins/DOMPlugin.cpp
index 534e04d58a2..eb4b99c94e6 100644
--- a/chromium/third_party/WebKit/Source/core/plugins/DOMPlugin.cpp
+++ b/chromium/third_party/WebKit/Source/core/plugins/DOMPlugin.cpp
@@ -19,7 +19,7 @@
#include "config.h"
#include "core/plugins/DOMPlugin.h"
-#include "core/plugins/PluginData.h"
+#include "platform/plugins/PluginData.h"
#include "wtf/text/AtomicString.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/plugins/DOMPlugin.h b/chromium/third_party/WebKit/Source/core/plugins/DOMPlugin.h
index 7e20be16194..1cc0611a180 100644
--- a/chromium/third_party/WebKit/Source/core/plugins/DOMPlugin.h
+++ b/chromium/third_party/WebKit/Source/core/plugins/DOMPlugin.h
@@ -21,7 +21,7 @@
#define DOMPlugin_h
#include "bindings/v8/ScriptWrappable.h"
-#include "core/page/FrameDestructionObserver.h"
+#include "core/frame/FrameDestructionObserver.h"
#include "core/plugins/DOMMimeType.h"
#include "wtf/Forward.h"
#include "wtf/RefCounted.h"
diff --git a/chromium/third_party/WebKit/Source/core/plugins/DOMPluginArray.cpp b/chromium/third_party/WebKit/Source/core/plugins/DOMPluginArray.cpp
index 11032e3effd..bb2b1695b13 100644
--- a/chromium/third_party/WebKit/Source/core/plugins/DOMPluginArray.cpp
+++ b/chromium/third_party/WebKit/Source/core/plugins/DOMPluginArray.cpp
@@ -20,10 +20,9 @@
#include "config.h"
#include "core/plugins/DOMPluginArray.h"
-#include "core/page/Frame.h"
+#include "core/frame/Frame.h"
#include "core/page/Page.h"
-#include "core/plugins/DOMPlugin.h"
-#include "core/plugins/PluginData.h"
+#include "platform/plugins/PluginData.h"
#include "wtf/text/AtomicString.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/plugins/DOMPluginArray.h b/chromium/third_party/WebKit/Source/core/plugins/DOMPluginArray.h
index 51eff45b1f8..922b777d925 100644
--- a/chromium/third_party/WebKit/Source/core/plugins/DOMPluginArray.h
+++ b/chromium/third_party/WebKit/Source/core/plugins/DOMPluginArray.h
@@ -22,7 +22,7 @@
#define DOMPluginArray_h
#include "bindings/v8/ScriptWrappable.h"
-#include "core/page/DOMWindowProperty.h"
+#include "core/frame/DOMWindowProperty.h"
#include "core/plugins/DOMPlugin.h"
#include "wtf/Forward.h"
#include "wtf/PassRefPtr.h"
diff --git a/chromium/third_party/WebKit/Source/core/plugins/PluginData.cpp b/chromium/third_party/WebKit/Source/core/plugins/PluginData.cpp
deleted file mode 100644
index d941dcababe..00000000000
--- a/chromium/third_party/WebKit/Source/core/plugins/PluginData.cpp
+++ /dev/null
@@ -1,143 +0,0 @@
-/*
- Copyright (C) 2000 Harri Porten (porten@kde.org)
- Copyright (C) 2000 Daniel Molkentin (molkentin@kde.org)
- Copyright (C) 2000 Stefan Schimanski (schimmi@kde.org)
- Copyright (C) 2003, 2004, 2005, 2006, 2007 Apple Inc. All Rights Reserved.
- Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#include "config.h"
-#include "core/plugins/PluginData.h"
-
-#include "core/plugins/PluginListBuilder.h"
-#include "public/platform/Platform.h"
-
-namespace WebCore {
-
-class PluginCache {
-public:
- PluginCache() : m_loaded(false), m_refresh(false) {}
- ~PluginCache() { reset(false); }
-
- void reset(bool refresh)
- {
- m_plugins.clear();
- m_loaded = false;
- m_refresh = refresh;
- }
-
- const Vector<PluginInfo>& plugins()
- {
- if (!m_loaded) {
- PluginListBuilder builder(&m_plugins);
- WebKit::Platform::current()->getPluginList(m_refresh, &builder);
- m_loaded = true;
- m_refresh = false;
- }
- return m_plugins;
- }
-
-private:
- Vector<PluginInfo> m_plugins;
- bool m_loaded;
- bool m_refresh;
-};
-
-static PluginCache& pluginCache()
-{
- DEFINE_STATIC_LOCAL(PluginCache, cache, ());
- return cache;
-}
-
-PluginData::PluginData(const Page* page)
-{
- initPlugins(page);
-
- for (unsigned i = 0; i < m_plugins.size(); ++i) {
- const PluginInfo& plugin = m_plugins[i];
- for (unsigned j = 0; j < plugin.mimes.size(); ++j) {
- m_mimes.append(plugin.mimes[j]);
- m_mimePluginIndices.append(i);
- }
- }
-}
-
-bool PluginData::supportsMimeType(const String& mimeType) const
-{
- for (unsigned i = 0; i < m_mimes.size(); ++i)
- if (m_mimes[i].type == mimeType)
- return true;
- return false;
-}
-
-const PluginInfo* PluginData::pluginInfoForMimeType(const String& mimeType) const
-{
- for (unsigned i = 0; i < m_mimes.size(); ++i) {
- const MimeClassInfo& info = m_mimes[i];
-
- if (info.type == mimeType)
- return &m_plugins[m_mimePluginIndices[i]];
- }
-
- return 0;
-}
-
-String PluginData::pluginNameForMimeType(const String& mimeType) const
-{
- if (const PluginInfo* info = pluginInfoForMimeType(mimeType))
- return info->name;
- return String();
-}
-
-String PluginData::pluginFileForMimeType(const String& mimeType) const
-{
- if (const PluginInfo* info = pluginInfoForMimeType(mimeType))
- return info->file;
- return String();
-}
-
-void PluginData::initPlugins(const Page*)
-{
- const Vector<PluginInfo>& plugins = pluginCache().plugins();
- for (size_t i = 0; i < plugins.size(); ++i)
- m_plugins.append(plugins[i]);
-}
-
-void PluginData::refresh()
-{
- pluginCache().reset(true);
- pluginCache().plugins(); // Force the plugins to be reloaded now.
-}
-
-String getPluginMimeTypeFromExtension(const String& extension)
-{
- const Vector<PluginInfo>& plugins = pluginCache().plugins();
- for (size_t i = 0; i < plugins.size(); ++i) {
- for (size_t j = 0; j < plugins[i].mimes.size(); ++j) {
- const MimeClassInfo& mime = plugins[i].mimes[j];
- const Vector<String>& extensions = mime.extensions;
- for (size_t k = 0; k < extensions.size(); ++k) {
- if (extension == extensions[k])
- return mime.type;
- }
- }
- }
- return String();
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/plugins/PluginData.h b/chromium/third_party/WebKit/Source/core/plugins/PluginData.h
deleted file mode 100644
index d60c127dd5b..00000000000
--- a/chromium/third_party/WebKit/Source/core/plugins/PluginData.h
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
-
- This library is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- Library General Public License for more details.
-
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB. If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
-*/
-
-#ifndef PluginData_h
-#define PluginData_h
-
-#include "wtf/RefCounted.h"
-#include "wtf/Vector.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class Page;
-struct PluginInfo;
-
-struct MimeClassInfo {
- String type;
- String desc;
- Vector<String> extensions;
-};
-
-inline bool operator==(const MimeClassInfo& a, const MimeClassInfo& b)
-{
- return a.type == b.type && a.desc == b.desc && a.extensions == b.extensions;
-}
-
-struct PluginInfo {
- String name;
- String file;
- String desc;
- Vector<MimeClassInfo> mimes;
-};
-
-class PluginData : public RefCounted<PluginData> {
-public:
- static PassRefPtr<PluginData> create(const Page* page) { return adoptRef(new PluginData(page)); }
-
- const Vector<PluginInfo>& plugins() const { return m_plugins; }
- const Vector<MimeClassInfo>& mimes() const { return m_mimes; }
- const Vector<size_t>& mimePluginIndices() const { return m_mimePluginIndices; }
-
- bool supportsMimeType(const String& mimeType) const;
- String pluginNameForMimeType(const String& mimeType) const;
- String pluginFileForMimeType(const String& mimeType) const;
-
- static void refresh();
-
-private:
- explicit PluginData(const Page*);
- void initPlugins(const Page*);
- const PluginInfo* pluginInfoForMimeType(const String& mimeType) const;
-
- Vector<PluginInfo> m_plugins;
- Vector<MimeClassInfo> m_mimes;
- Vector<size_t> m_mimePluginIndices;
-};
-
-// Checks if any of the plugins handle this extension, and if so returns the
-// plugin's mime type for this extension. Otherwise returns an empty string.
-String getPluginMimeTypeFromExtension(const String& extension);
-
-}
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/plugins/PluginListBuilder.cpp b/chromium/third_party/WebKit/Source/core/plugins/PluginListBuilder.cpp
deleted file mode 100644
index 98482fb9fcd..00000000000
--- a/chromium/third_party/WebKit/Source/core/plugins/PluginListBuilder.cpp
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Copyright (C) 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/plugins/PluginListBuilder.h"
-
-#include "core/plugins/PluginData.h"
-#include "public/platform/WebString.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-void PluginListBuilder::addPlugin(const WebKit::WebString& name, const WebKit::WebString& description, const WebKit::WebString& fileName)
-{
- PluginInfo info;
- info.name = name;
- info.desc = description;
- info.file = fileName;
- m_results->append(info);
-}
-
-void PluginListBuilder::addMediaTypeToLastPlugin(const WebKit::WebString& name, const WebKit::WebString& description)
-{
- MimeClassInfo info;
- info.type = name;
- info.desc = description;
- m_results->last().mimes.append(info);
-}
-
-void PluginListBuilder::addFileExtensionToLastMediaType(const WebKit::WebString& extension)
-{
- MimeClassInfo& info = m_results->last().mimes.last();
- info.extensions.append(extension);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/plugins/PluginListBuilder.h b/chromium/third_party/WebKit/Source/core/plugins/PluginListBuilder.h
deleted file mode 100644
index 4ff0b4e253e..00000000000
--- a/chromium/third_party/WebKit/Source/core/plugins/PluginListBuilder.h
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Copyright (C) 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef PluginListBuilder_h
-#define PluginListBuilder_h
-
-#include "core/plugins/PluginData.h"
-#include "public/platform/WebPluginListBuilder.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-class PluginListBuilder : public WebKit::WebPluginListBuilder {
-public:
- PluginListBuilder(Vector<WebCore::PluginInfo>* results) : m_results(results) { }
-
- // WebPluginListBuilder methods:
- virtual void addPlugin(const WebKit::WebString& name, const WebKit::WebString& description, const WebKit::WebString& fileName);
- virtual void addMediaTypeToLastPlugin(const WebKit::WebString& name, const WebKit::WebString& description);
- virtual void addFileExtensionToLastMediaType(const WebKit::WebString& extension);
-
-private:
- Vector<PluginInfo>* m_results;
-};
-
-} // namespace WebCore
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/plugins/PluginOcclusionSupport.cpp b/chromium/third_party/WebKit/Source/core/plugins/PluginOcclusionSupport.cpp
index 3d4b37bbab6..3fab5dcda31 100644
--- a/chromium/third_party/WebKit/Source/core/plugins/PluginOcclusionSupport.cpp
+++ b/chromium/third_party/WebKit/Source/core/plugins/PluginOcclusionSupport.cpp
@@ -35,11 +35,11 @@
#include "core/dom/Element.h"
#include "core/html/HTMLElement.h"
#include "core/html/HTMLFrameOwnerElement.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameView.h"
-#include "core/platform/Widget.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
#include "core/rendering/RenderBox.h"
#include "core/rendering/RenderObject.h"
+#include "platform/Widget.h"
#include "wtf/HashSet.h"
// This file provides a utility function to support rendering certain elements above plugins.
diff --git a/chromium/third_party/WebKit/Source/core/plugins/PluginView.h b/chromium/third_party/WebKit/Source/core/plugins/PluginView.h
index c25d2b1aeb0..14938bdb907 100644
--- a/chromium/third_party/WebKit/Source/core/plugins/PluginView.h
+++ b/chromium/third_party/WebKit/Source/core/plugins/PluginView.h
@@ -26,13 +26,13 @@
#ifndef PluginView_h
#define PluginView_h
-#include "core/platform/ScrollTypes.h"
-#include "core/platform/Widget.h"
+#include "platform/Widget.h"
+#include "platform/scroll/ScrollTypes.h"
#include "wtf/text/WTFString.h"
struct NPObject;
-namespace WebKit { class WebLayer; }
+namespace blink { class WebLayer; }
namespace WebCore {
@@ -44,11 +44,12 @@ class PluginView : public Widget {
public:
virtual bool isPluginView() const { return true; }
- virtual WebKit::WebLayer* platformLayer() const { return 0; }
+ virtual blink::WebLayer* platformLayer() const { return 0; }
virtual NPObject* scriptableObject() { return 0; }
virtual bool getFormValue(String&) { return false; }
virtual bool wantsWheelEvents() { return false; }
virtual bool supportsKeyboardFocus() const { return false; }
+ virtual bool supportsInputMethod() const { return false; }
virtual bool canProcessDrag() const { return false; }
virtual void didReceiveResponse(const ResourceResponse&) { }
@@ -60,20 +61,7 @@ protected:
PluginView() : Widget() { }
};
-inline PluginView* toPluginView(Widget* widget)
-{
- ASSERT(!widget || widget->isPluginView());
- return static_cast<PluginView*>(widget);
-}
-
-inline const PluginView* toPluginView(const Widget* widget)
-{
- ASSERT(!widget || widget->isPluginView());
- return static_cast<const PluginView*>(widget);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toPluginView(const PluginView*);
+DEFINE_TYPE_CASTS(PluginView, Widget, widget, widget->isPluginView(), widget.isPluginView());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/AbstractInlineTextBox.cpp b/chromium/third_party/WebKit/Source/core/rendering/AbstractInlineTextBox.cpp
new file mode 100644
index 00000000000..a14b4a0e876
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/rendering/AbstractInlineTextBox.cpp
@@ -0,0 +1,164 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/rendering/AbstractInlineTextBox.h"
+
+#include "core/editing/TextIterator.h"
+#include "platform/text/TextBreakIterator.h"
+
+namespace WebCore {
+
+AbstractInlineTextBox::InlineToAbstractInlineTextBoxHashMap* AbstractInlineTextBox::gAbstractInlineTextBoxMap = 0;
+
+PassRefPtr<AbstractInlineTextBox> AbstractInlineTextBox::getOrCreate(RenderText* renderText, InlineTextBox* inlineTextBox)
+{
+ if (!inlineTextBox)
+ return 0;
+
+ if (!gAbstractInlineTextBoxMap)
+ gAbstractInlineTextBoxMap = new InlineToAbstractInlineTextBoxHashMap();
+
+ InlineToAbstractInlineTextBoxHashMap::const_iterator it = gAbstractInlineTextBoxMap->find(inlineTextBox);
+ if (it != gAbstractInlineTextBoxMap->end())
+ return it->value;
+
+ RefPtr<AbstractInlineTextBox> obj = adoptRef(new AbstractInlineTextBox(renderText, inlineTextBox));
+ gAbstractInlineTextBoxMap->set(inlineTextBox, obj);
+ return obj;
+}
+
+void AbstractInlineTextBox::willDestroy(InlineTextBox* inlineTextBox)
+{
+ if (!gAbstractInlineTextBoxMap)
+ return;
+
+ InlineToAbstractInlineTextBoxHashMap::const_iterator it = gAbstractInlineTextBoxMap->find(inlineTextBox);
+ if (it != gAbstractInlineTextBoxMap->end()) {
+ it->value->detach();
+ gAbstractInlineTextBoxMap->remove(inlineTextBox);
+ }
+}
+
+void AbstractInlineTextBox::detach()
+{
+ m_renderText = 0;
+ m_inlineTextBox = 0;
+}
+
+PassRefPtr<AbstractInlineTextBox> AbstractInlineTextBox::nextInlineTextBox() const
+{
+ if (!m_inlineTextBox)
+ return 0;
+
+ return getOrCreate(m_renderText, m_inlineTextBox->nextTextBox());
+}
+
+LayoutRect AbstractInlineTextBox::bounds() const
+{
+ if (!m_inlineTextBox || !m_renderText)
+ return LayoutRect();
+
+ FloatRect boundaries = m_inlineTextBox->calculateBoundaries();
+ return m_renderText->localToAbsoluteQuad(boundaries).enclosingBoundingBox();
+}
+
+unsigned AbstractInlineTextBox::start() const
+{
+ if (!m_inlineTextBox)
+ return 0;
+
+ return m_inlineTextBox->start();
+}
+
+unsigned AbstractInlineTextBox::len() const
+{
+ if (!m_inlineTextBox)
+ return 0;
+
+ return m_inlineTextBox->len();
+}
+
+AbstractInlineTextBox::Direction AbstractInlineTextBox::direction() const
+{
+ if (!m_inlineTextBox || !m_renderText)
+ return LeftToRight;
+
+ if (m_renderText->style()->isHorizontalWritingMode())
+ return (m_inlineTextBox->direction() == RTL ? RightToLeft : LeftToRight);
+ return (m_inlineTextBox->direction() == RTL ? BottomToTop : TopToBottom);
+}
+
+void AbstractInlineTextBox::characterWidths(Vector<float>& widths) const
+{
+ if (!m_inlineTextBox)
+ return;
+
+ m_inlineTextBox->characterWidths(widths);
+}
+
+void AbstractInlineTextBox::wordBoundaries(Vector<WordBoundaries>& words) const
+{
+ if (!m_inlineTextBox)
+ return;
+
+ String text = this->text();
+ int len = text.length();
+ TextBreakIterator* iterator = wordBreakIterator(text, 0, len);
+ int pos = iterator->first();
+ while (pos >= 0 && pos < len) {
+ int next = iterator->next();
+ if (isWordTextBreak(iterator))
+ words.append(WordBoundaries(pos, next));
+ pos = next;
+ }
+}
+
+String AbstractInlineTextBox::text() const
+{
+ if (!m_inlineTextBox || !m_renderText)
+ return String();
+
+ unsigned start = m_inlineTextBox->start();
+ unsigned len = m_inlineTextBox->len();
+ if (Node* node = m_renderText->node()) {
+ RefPtr<Range> range = Range::create(node->document());
+ range->setStart(node, start, IGNORE_EXCEPTION);
+ range->setEnd(node, start + len, IGNORE_EXCEPTION);
+ return plainText(range.get(), TextIteratorIgnoresStyleVisibility);
+ }
+
+ String result = m_renderText->text().substring(start, len).simplifyWhiteSpace(WTF::DoNotStripWhiteSpace);
+ if (m_inlineTextBox->nextTextBox() && m_inlineTextBox->nextTextBox()->start() > m_inlineTextBox->end() && result.length() && !result.right(1).containsOnlyWhitespace())
+ return result + " ";
+ return result;
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/AbstractInlineTextBox.h b/chromium/third_party/WebKit/Source/core/rendering/AbstractInlineTextBox.h
new file mode 100644
index 00000000000..0c1c096bec8
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/rendering/AbstractInlineTextBox.h
@@ -0,0 +1,98 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef AbstractInlineTextBox_h
+#define AbstractInlineTextBox_h
+
+#include "core/dom/Range.h"
+#include "core/rendering/InlineTextBox.h"
+#include "core/rendering/RenderText.h"
+#include "wtf/HashMap.h"
+#include "wtf/RefPtr.h"
+
+namespace WebCore {
+
+class InlineTextBox;
+
+// High-level abstraction of InlineTextBox to allow the accessibility module to
+// get information about InlineTextBoxes without tight coupling.
+class AbstractInlineTextBox : public RefCounted<AbstractInlineTextBox> {
+private:
+ AbstractInlineTextBox(RenderText* renderText, InlineTextBox* inlineTextBox)
+ : m_renderText(renderText)
+ , m_inlineTextBox(inlineTextBox)
+ {
+ }
+
+ static PassRefPtr<AbstractInlineTextBox> getOrCreate(RenderText*, InlineTextBox*);
+ static void willDestroy(InlineTextBox*);
+
+ friend class RenderText;
+ friend class InlineTextBox;
+
+public:
+ struct WordBoundaries {
+ WordBoundaries(int startIndex, int endIndex) : startIndex(startIndex), endIndex(endIndex) { }
+ int startIndex;
+ int endIndex;
+ };
+
+ enum Direction {
+ LeftToRight,
+ RightToLeft,
+ TopToBottom,
+ BottomToTop
+ };
+
+ RenderText* renderText() const { return m_renderText; }
+
+ PassRefPtr<AbstractInlineTextBox> nextInlineTextBox() const;
+ LayoutRect bounds() const;
+ unsigned start() const;
+ unsigned len() const;
+ Direction direction() const;
+ void characterWidths(Vector<float>&) const;
+ void wordBoundaries(Vector<WordBoundaries>&) const;
+ String text() const;
+
+private:
+ void detach();
+
+ // Weak ptrs; these are nulled when InlineTextBox::destroy() calls AbstractInlineTextBox::willDestroy.
+ RenderText* m_renderText;
+ InlineTextBox* m_inlineTextBox;
+
+ typedef HashMap<InlineTextBox*, RefPtr<AbstractInlineTextBox> > InlineToAbstractInlineTextBoxHashMap;
+ static InlineToAbstractInlineTextBoxHashMap* gAbstractInlineTextBoxMap;
+};
+
+} // namespace WebCore
+
+#endif // AbstractInlineTextBox_h
diff --git a/chromium/third_party/WebKit/Source/core/rendering/AutoTableLayout.h b/chromium/third_party/WebKit/Source/core/rendering/AutoTableLayout.h
index 4975a962325..dfdd985d842 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/AutoTableLayout.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/AutoTableLayout.h
@@ -21,9 +21,9 @@
#ifndef AutoTableLayout_h
#define AutoTableLayout_h
-#include "core/platform/LayoutUnit.h"
-#include "core/platform/Length.h"
#include "core/rendering/TableLayout.h"
+#include "platform/LayoutUnit.h"
+#include "platform/Length.h"
#include "wtf/Vector.h"
namespace WebCore {
@@ -31,14 +31,15 @@ namespace WebCore {
class RenderTable;
class RenderTableCell;
-class AutoTableLayout : public TableLayout {
+class AutoTableLayout FINAL : public TableLayout {
public:
AutoTableLayout(RenderTable*);
~AutoTableLayout();
virtual void computeIntrinsicLogicalWidths(LayoutUnit& minWidth, LayoutUnit& maxWidth) OVERRIDE;
virtual void applyPreferredLogicalWidthQuirks(LayoutUnit& minWidth, LayoutUnit& maxWidth) const OVERRIDE;
- virtual void layout();
+ virtual void layout() OVERRIDE;
+ virtual void willChangeTableLayout() OVERRIDE { }
private:
void fullRecalc();
diff --git a/chromium/third_party/WebKit/Source/core/rendering/BidiRun.cpp b/chromium/third_party/WebKit/Source/core/rendering/BidiRun.cpp
index 12e83a562e2..4af7881a87e 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/BidiRun.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/BidiRun.cpp
@@ -23,9 +23,8 @@
#include "config.h"
#include "core/rendering/BidiRun.h"
-#include "core/platform/Partitions.h"
+#include "platform/Partitions.h"
#include "wtf/RefCountedLeakCounter.h"
-#include "wtf/StdLibExtras.h"
using namespace WTF;
diff --git a/chromium/third_party/WebKit/Source/core/rendering/BidiRun.h b/chromium/third_party/WebKit/Source/core/rendering/BidiRun.h
index abfe2d1df9b..85f8f4a1a1c 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/BidiRun.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/BidiRun.h
@@ -24,8 +24,8 @@
#ifndef BidiRun_h
#define BidiRun_h
-#include "core/platform/text/BidiResolver.h"
#include "core/rendering/RenderText.h"
+#include "platform/text/BidiResolver.h"
#include "wtf/StdLibExtras.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/rendering/ClipPathOperation.h b/chromium/third_party/WebKit/Source/core/rendering/ClipPathOperation.h
index fcbf07bd3cd..7d50a10e4fd 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/ClipPathOperation.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/ClipPathOperation.h
@@ -30,8 +30,8 @@
#ifndef ClipPathOperation_h
#define ClipPathOperation_h
-#include "core/platform/graphics/Path.h"
#include "core/rendering/style/BasicShapes.h"
+#include "platform/graphics/Path.h"
#include "wtf/OwnPtr.h"
#include "wtf/PassOwnPtr.h"
#include "wtf/RefCounted.h"
@@ -51,8 +51,8 @@ public:
virtual bool operator==(const ClipPathOperation&) const = 0;
bool operator!=(const ClipPathOperation& o) const { return !(*this == o); }
- virtual OperationType getOperationType() const { return m_type; }
- virtual bool isSameType(const ClipPathOperation& o) const { return o.getOperationType() == m_type; }
+ OperationType type() const { return m_type; }
+ bool isSameType(const ClipPathOperation& o) const { return o.type() == m_type; }
protected:
ClipPathOperation(OperationType type)
@@ -74,12 +74,9 @@ public:
const String& fragment() const { return m_fragment; }
private:
- virtual bool operator==(const ClipPathOperation& o) const
+ virtual bool operator==(const ClipPathOperation& o) const OVERRIDE
{
- if (!isSameType(o))
- return false;
- const ReferenceClipPathOperation* other = static_cast<const ReferenceClipPathOperation*>(&o);
- return m_url == other->m_url;
+ return isSameType(o) && m_url == static_cast<const ReferenceClipPathOperation&>(o).m_url;
}
ReferenceClipPathOperation(const String& url, const String& fragment)
@@ -93,6 +90,8 @@ private:
String m_fragment;
};
+DEFINE_TYPE_CASTS(ReferenceClipPathOperation, ClipPathOperation, op, op->type() == ClipPathOperation::REFERENCE, op.type() == ClipPathOperation::REFERENCE);
+
class ShapeClipPathOperation : public ClipPathOperation {
public:
static PassRefPtr<ShapeClipPathOperation> create(PassRefPtr<BasicShape> shape)
@@ -112,12 +111,9 @@ public:
}
private:
- virtual bool operator==(const ClipPathOperation& o) const
+ virtual bool operator==(const ClipPathOperation& o) const OVERRIDE
{
- if (!isSameType(o))
- return false;
- const ShapeClipPathOperation* other = static_cast<const ShapeClipPathOperation*>(&o);
- return m_shape == other->m_shape;
+ return isSameType(o) && m_shape == static_cast<const ShapeClipPathOperation&>(o).m_shape;
}
ShapeClipPathOperation(PassRefPtr<BasicShape> shape)
@@ -129,6 +125,9 @@ private:
RefPtr<BasicShape> m_shape;
OwnPtr<Path> m_path;
};
+
+DEFINE_TYPE_CASTS(ShapeClipPathOperation, ClipPathOperation, op, op->type() == ClipPathOperation::SHAPE, op.type() == ClipPathOperation::SHAPE);
+
}
#endif // ClipPathOperation_h
diff --git a/chromium/third_party/WebKit/Source/core/rendering/ClipRect.h b/chromium/third_party/WebKit/Source/core/rendering/ClipRect.h
index d88eb9a3a6a..8fbcebf90a6 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/ClipRect.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/ClipRect.h
@@ -26,7 +26,7 @@
#ifndef ClipRect_h
#define ClipRect_h
-#include "core/platform/graphics/LayoutRect.h"
+#include "platform/geometry/LayoutRect.h"
#include "wtf/Vector.h"
@@ -138,7 +138,7 @@ public:
return m_overflowClipRect == other.overflowClipRect()
&& m_fixedClipRect == other.fixedClipRect()
&& m_posClipRect == other.posClipRect()
- && m_fixed == other.fixed();
+ && fixed() == other.fixed();
}
ClipRects& operator=(const ClipRects& other)
diff --git a/chromium/third_party/WebKit/Source/core/rendering/ColumnInfo.h b/chromium/third_party/WebKit/Source/core/rendering/ColumnInfo.h
index bb30a165874..39722819249 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/ColumnInfo.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/ColumnInfo.h
@@ -26,7 +26,7 @@
#ifndef ColumnInfo_h
#define ColumnInfo_h
-#include "core/platform/LayoutUnit.h"
+#include "platform/LayoutUnit.h"
#include "wtf/Vector.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/rendering/CompositedLayerMapping.cpp b/chromium/third_party/WebKit/Source/core/rendering/CompositedLayerMapping.cpp
new file mode 100644
index 00000000000..3358f9b4ced
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/rendering/CompositedLayerMapping.cpp
@@ -0,0 +1,2228 @@
+/*
+ * Copyright (C) 2009, 2010, 2011 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+
+#include "core/rendering/CompositedLayerMapping.h"
+
+#include "CSSPropertyNames.h"
+#include "HTMLNames.h"
+#include "RuntimeEnabledFeatures.h"
+#include "core/animation/ActiveAnimations.h"
+#include "core/fetch/ImageResource.h"
+#include "core/html/HTMLIFrameElement.h"
+#include "core/html/HTMLMediaElement.h"
+#include "core/html/canvas/CanvasRenderingContext.h"
+#include "core/inspector/InspectorInstrumentation.h"
+#include "core/page/Chrome.h"
+#include "core/frame/FrameView.h"
+#include "core/frame/Settings.h"
+#include "core/frame/animation/AnimationController.h"
+#include "core/page/scrolling/ScrollingCoordinator.h"
+#include "core/plugins/PluginView.h"
+#include "core/rendering/FilterEffectRenderer.h"
+#include "core/rendering/RenderApplet.h"
+#include "core/rendering/RenderEmbeddedObject.h"
+#include "core/rendering/RenderIFrame.h"
+#include "core/rendering/RenderImage.h"
+#include "core/rendering/RenderLayerCompositor.h"
+#include "core/rendering/RenderLayerStackingNodeIterator.h"
+#include "core/rendering/RenderVideo.h"
+#include "core/rendering/RenderView.h"
+#include "core/rendering/animation/WebAnimationProvider.h"
+#include "core/rendering/style/KeyframeList.h"
+#include "platform/LengthFunctions.h"
+#include "platform/fonts/FontCache.h"
+#include "platform/graphics/GraphicsContext.h"
+#include "platform/graphics/GraphicsContext3D.h"
+#include "platform/graphics/filters/custom/CustomFilterOperation.h"
+#include "wtf/CurrentTime.h"
+#include "wtf/text/StringBuilder.h"
+
+using namespace std;
+
+namespace WebCore {
+
+using namespace HTMLNames;
+
+static IntRect clipBox(RenderBox* renderer);
+
+static IntRect contentsRect(const RenderObject* renderer)
+{
+ if (!renderer->isBox())
+ return IntRect();
+
+ return renderer->isVideo() ?
+ toRenderVideo(renderer)->videoBox() :
+ pixelSnappedIntRect(toRenderBox(renderer)->contentBoxRect());
+}
+
+static IntRect backgroundRect(const RenderObject* renderer)
+{
+ if (!renderer->isBox())
+ return IntRect();
+
+ LayoutRect rect;
+ const RenderBox* box = toRenderBox(renderer);
+ EFillBox clip = box->style()->backgroundClip();
+ switch (clip) {
+ case BorderFillBox:
+ rect = box->borderBoxRect();
+ break;
+ case PaddingFillBox:
+ rect = box->paddingBoxRect();
+ break;
+ case ContentFillBox:
+ rect = box->contentBoxRect();
+ break;
+ case TextFillBox:
+ break;
+ }
+
+ return pixelSnappedIntRect(rect);
+}
+
+static inline bool isAcceleratedCanvas(const RenderObject* renderer)
+{
+ if (renderer->isCanvas()) {
+ HTMLCanvasElement* canvas = toHTMLCanvasElement(renderer->node());
+ if (CanvasRenderingContext* context = canvas->renderingContext())
+ return context->isAccelerated();
+ }
+ return false;
+}
+
+static bool hasBoxDecorations(const RenderStyle* style)
+{
+ return style->hasBorder() || style->hasBorderRadius() || style->hasOutline() || style->hasAppearance() || style->boxShadow() || style->hasFilter();
+}
+
+static bool hasBoxDecorationsOrBackgroundImage(const RenderStyle* style)
+{
+ return hasBoxDecorations(style) || style->hasBackgroundImage();
+}
+
+static bool contentLayerSupportsDirectBackgroundComposition(const RenderObject* renderer)
+{
+ // No support for decorations - border, border-radius or outline.
+ // Only simple background - solid color or transparent.
+ if (hasBoxDecorationsOrBackgroundImage(renderer->style()))
+ return false;
+
+ // If there is no background, there is nothing to support.
+ if (!renderer->style()->hasBackground())
+ return true;
+
+ // Simple background that is contained within the contents rect.
+ return contentsRect(renderer).contains(backgroundRect(renderer));
+}
+
+static inline bool isAcceleratedContents(RenderObject* renderer)
+{
+ return isAcceleratedCanvas(renderer)
+ || (renderer->isEmbeddedObject() && toRenderEmbeddedObject(renderer)->allowsAcceleratedCompositing())
+ || renderer->isVideo();
+}
+
+// Get the scrolling coordinator in a way that works inside CompositedLayerMapping's destructor.
+static ScrollingCoordinator* scrollingCoordinatorFromLayer(RenderLayer* layer)
+{
+ Page* page = layer->renderer()->frame()->page();
+ if (!page)
+ return 0;
+
+ return page->scrollingCoordinator();
+}
+
+CompositedLayerMapping::CompositedLayerMapping(RenderLayer* layer)
+ : m_owningLayer(layer)
+ , m_animationProvider(adoptPtr(new WebAnimationProvider))
+ , m_artificiallyInflatedBounds(false)
+ , m_boundsConstrainedByClipping(false)
+ , m_isMainFrameRenderViewLayer(false)
+ , m_requiresOwnBackingStoreForIntrinsicReasons(true)
+ , m_requiresOwnBackingStoreForAncestorReasons(true)
+ , m_canCompositeFilters(false)
+ , m_backgroundLayerPaintsFixedRootBackground(false)
+{
+ if (layer->isRootLayer() && renderer()->frame()->isMainFrame())
+ m_isMainFrameRenderViewLayer = true;
+
+ createPrimaryGraphicsLayer();
+}
+
+CompositedLayerMapping::~CompositedLayerMapping()
+{
+ // Do not leave the destroyed pointer dangling on any RenderLayers that painted to this mapping's squashing layer.
+ for (size_t i = 0; i < m_squashedLayers.size(); ++i) {
+ if (m_squashedLayers[i].renderLayer->groupedMapping() == this)
+ m_squashedLayers[i].renderLayer->setGroupedMapping(0);
+ }
+
+ updateClippingLayers(false, false);
+ updateOverflowControlsLayers(false, false, false);
+ updateForegroundLayer(false);
+ updateBackgroundLayer(false);
+ updateMaskLayer(false);
+ updateClippingMaskLayers(false);
+ updateScrollingLayers(false);
+ updateSquashingLayers(false);
+ destroyGraphicsLayers();
+}
+
+PassOwnPtr<GraphicsLayer> CompositedLayerMapping::createGraphicsLayer(CompositingReasons reasons)
+{
+ GraphicsLayerFactory* graphicsLayerFactory = 0;
+ if (Page* page = renderer()->frame()->page())
+ graphicsLayerFactory = page->chrome().client().graphicsLayerFactory();
+
+ OwnPtr<GraphicsLayer> graphicsLayer = GraphicsLayer::create(graphicsLayerFactory, this);
+
+ graphicsLayer->setCompositingReasons(reasons);
+
+ return graphicsLayer.release();
+}
+
+void CompositedLayerMapping::createPrimaryGraphicsLayer()
+{
+ m_graphicsLayer = createGraphicsLayer(m_owningLayer->compositingReasons());
+
+#if !OS(ANDROID)
+ if (m_isMainFrameRenderViewLayer)
+ m_graphicsLayer->contentLayer()->setDrawCheckerboardForMissingTiles(true);
+#endif
+
+ updateOpacity(renderer()->style());
+ updateTransform(renderer()->style());
+ updateFilters(renderer()->style());
+
+ if (RuntimeEnabledFeatures::cssCompositingEnabled()) {
+ updateLayerBlendMode(renderer()->style());
+ updateIsRootForIsolatedGroup();
+ }
+}
+
+void CompositedLayerMapping::destroyGraphicsLayers()
+{
+ if (m_graphicsLayer)
+ m_graphicsLayer->removeFromParent();
+
+ m_ancestorClippingLayer = nullptr;
+ m_graphicsLayer = nullptr;
+ m_foregroundLayer = nullptr;
+ m_backgroundLayer = nullptr;
+ m_childContainmentLayer = nullptr;
+ m_maskLayer = nullptr;
+ m_childClippingMaskLayer = nullptr;
+
+ m_scrollingLayer = nullptr;
+ m_scrollingContentsLayer = nullptr;
+}
+
+void CompositedLayerMapping::updateOpacity(const RenderStyle* style)
+{
+ m_graphicsLayer->setOpacity(compositingOpacity(style->opacity()));
+}
+
+void CompositedLayerMapping::updateTransform(const RenderStyle* style)
+{
+ // FIXME: This could use m_owningLayer->transform(), but that currently has transform-origin
+ // baked into it, and we don't want that.
+ TransformationMatrix t;
+ if (m_owningLayer->hasTransform()) {
+ style->applyTransform(t, toRenderBox(renderer())->pixelSnappedBorderBoxRect().size(), RenderStyle::ExcludeTransformOrigin);
+ makeMatrixRenderable(t, compositor()->canRender3DTransforms());
+ }
+
+ m_graphicsLayer->setTransform(t);
+}
+
+void CompositedLayerMapping::updateFilters(const RenderStyle* style)
+{
+ bool didCompositeFilters = m_canCompositeFilters;
+ m_canCompositeFilters = m_graphicsLayer->setFilters(owningLayer()->computeFilterOperations(style));
+ if (didCompositeFilters != m_canCompositeFilters) {
+ //
+ // If filters used to be painted in software and are now painted in the compositor, we need to:
+ // (1) Remove the FilterEffectRenderer, which was used for painting filters in software.
+ // (2) Repaint the layer contents to remove the software-applied filter because the compositor will apply it.
+ //
+ // Similarly, if filters used to be painted in the compositor and are now painted in software, we need to:
+ // (1) Create a FilterEffectRenderer.
+ // (2) Repaint the layer contents to apply a software filter because the compositor won't apply it.
+ //
+ m_owningLayer->updateOrRemoveFilterEffectRenderer();
+ setContentsNeedDisplay();
+ }
+}
+
+void CompositedLayerMapping::updateLayerBlendMode(const RenderStyle* style)
+{
+ setBlendMode(style->blendMode());
+}
+
+void CompositedLayerMapping::updateIsRootForIsolatedGroup()
+{
+ bool isolate = m_owningLayer->shouldIsolateCompositedDescendants();
+
+ // non stacking context layers should never isolate
+ ASSERT(m_owningLayer->stackingNode()->isStackingContext() || !isolate);
+
+ m_graphicsLayer->setIsRootForIsolatedGroup(isolate);
+}
+
+void CompositedLayerMapping::updateContentsOpaque()
+{
+ // For non-root layers, background is always painted by the primary graphics layer.
+ ASSERT(m_isMainFrameRenderViewLayer || !m_backgroundLayer);
+ if (m_backgroundLayer) {
+ m_graphicsLayer->setContentsOpaque(false);
+ m_backgroundLayer->setContentsOpaque(m_owningLayer->backgroundIsKnownToBeOpaqueInRect(compositedBounds()));
+ } else {
+ m_graphicsLayer->setContentsOpaque(m_owningLayer->backgroundIsKnownToBeOpaqueInRect(compositedBounds()));
+ }
+}
+
+static bool hasNonZeroTransformOrigin(const RenderObject* renderer)
+{
+ RenderStyle* style = renderer->style();
+ return (style->transformOriginX().type() == Fixed && style->transformOriginX().value())
+ || (style->transformOriginY().type() == Fixed && style->transformOriginY().value());
+}
+
+static bool layerOrAncestorIsTransformedOrUsingCompositedScrolling(RenderLayer* layer)
+{
+ for (RenderLayer* curr = layer; curr; curr = curr->parent()) {
+ if (curr->hasTransform() || curr->needsCompositedScrolling())
+ return true;
+ }
+
+ return false;
+}
+
+bool CompositedLayerMapping::shouldClipCompositedBounds() const
+{
+ // Scrollbar layers use this layer for relative positioning, so don't clip.
+ if (layerForHorizontalScrollbar() || layerForVerticalScrollbar())
+ return false;
+
+ if (layerOrAncestorIsTransformedOrUsingCompositedScrolling(m_owningLayer))
+ return false;
+
+ // Scrolled composited layers are clipped by their ancestor clipping layer,
+ // so don't clip these, either.
+ bool hasAncestorClippingLayer = compositor()->clippedByAncestor(m_owningLayer);
+ bool clippingAncestorIsScrollParent = m_owningLayer->renderer()->containingBlock()->enclosingLayer() == m_owningLayer->ancestorScrollingLayer();
+ if (hasAncestorClippingLayer && clippingAncestorIsScrollParent)
+ return false;
+
+ return true;
+}
+
+void CompositedLayerMapping::updateCompositedBounds()
+{
+ // We need to know if we draw content in order to update our bounds (this has an effect
+ // on whether or not descendands will paint into our backing). Update this value now.
+ updateDrawsContent(isSimpleContainerCompositingLayer());
+
+ IntRect layerBounds = compositor()->calculateCompositedBounds(m_owningLayer, m_owningLayer);
+
+ // Clip to the size of the document or enclosing overflow-scroll layer.
+ // If this or an ancestor is transformed, we can't currently compute the correct rect to intersect with.
+ // We'd need RenderObject::convertContainerToLocalQuad(), which doesn't yet exist.
+ if (shouldClipCompositedBounds()) {
+ RenderView* view = m_owningLayer->renderer()->view();
+ RenderLayer* rootLayer = view->layer();
+
+ LayoutRect clippingBounds;
+ if (renderer()->style()->position() == FixedPosition && renderer()->container() == view)
+ clippingBounds = view->frameView()->viewportConstrainedVisibleContentRect();
+ else
+ clippingBounds = view->unscaledDocumentRect();
+
+ if (m_owningLayer != rootLayer)
+ clippingBounds.intersect(m_owningLayer->backgroundClipRect(ClipRectsContext(rootLayer, 0, AbsoluteClipRects)).rect()); // FIXME: Incorrect for CSS regions.
+
+ LayoutPoint delta;
+ m_owningLayer->convertToLayerCoords(rootLayer, delta);
+ clippingBounds.move(-delta.x(), -delta.y());
+
+ layerBounds.intersect(pixelSnappedIntRect(clippingBounds));
+ m_boundsConstrainedByClipping = true;
+ } else {
+ m_boundsConstrainedByClipping = false;
+ }
+
+ // If the element has a transform-origin that has fixed lengths, and the renderer has zero size,
+ // then we need to ensure that the compositing layer has non-zero size so that we can apply
+ // the transform-origin via the GraphicsLayer anchorPoint (which is expressed as a fractional value).
+ if (layerBounds.isEmpty() && hasNonZeroTransformOrigin(renderer())) {
+ layerBounds.setWidth(1);
+ layerBounds.setHeight(1);
+ m_artificiallyInflatedBounds = true;
+ } else {
+ m_artificiallyInflatedBounds = false;
+ }
+
+ setCompositedBounds(layerBounds);
+}
+
+void CompositedLayerMapping::updateAfterWidgetResize()
+{
+ if (renderer()->isRenderPart()) {
+ if (RenderLayerCompositor* innerCompositor = RenderLayerCompositor::frameContentsCompositor(toRenderPart(renderer()))) {
+ innerCompositor->frameViewDidChangeSize();
+ innerCompositor->frameViewDidChangeLocation(contentsBox().location());
+ }
+ }
+}
+
+void CompositedLayerMapping::updateCompositingReasons()
+{
+ // All other layers owned by this mapping will have the same compositing reason
+ // for their lifetime, so they are initialized only when created.
+ m_graphicsLayer->setCompositingReasons(m_owningLayer->compositingReasons());
+}
+
+void CompositedLayerMapping::updateAfterLayout(UpdateAfterLayoutFlags flags)
+{
+ RenderLayerCompositor* layerCompositor = compositor();
+ if (!layerCompositor->compositingLayersNeedRebuild()) {
+ // Calling updateGraphicsLayerGeometry() here gives incorrect results, because the
+ // position of this layer's GraphicsLayer depends on the position of our compositing
+ // ancestor's GraphicsLayer. That cannot be determined until all the descendant
+ // RenderLayers of that ancestor have been processed via updateLayerPositions().
+ //
+ // The solution is to update compositing children of this layer here,
+ // via updateCompositingChildrenGeometry().
+ updateCompositedBounds();
+ layerCompositor->updateCompositingDescendantGeometry(m_owningLayer->stackingNode(), m_owningLayer, flags & CompositingChildrenOnly);
+
+ if (flags & IsUpdateRoot) {
+ updateGraphicsLayerGeometry();
+ layerCompositor->updateRootLayerPosition();
+ RenderLayerStackingNode* stackingContainer = m_owningLayer->stackingNode()->enclosingStackingContainerNode();
+ if (!layerCompositor->compositingLayersNeedRebuild() && stackingContainer && (stackingContainer != m_owningLayer->stackingNode()))
+ layerCompositor->updateCompositingDescendantGeometry(stackingContainer, stackingContainer->layer(), flags & CompositingChildrenOnly);
+ }
+ }
+
+ if (flags & NeedsFullRepaint && !paintsIntoCompositedAncestor())
+ setContentsNeedDisplay();
+}
+
+bool CompositedLayerMapping::updateGraphicsLayerConfiguration()
+{
+ RenderLayerCompositor* compositor = this->compositor();
+ RenderObject* renderer = this->renderer();
+
+ m_owningLayer->updateDescendantDependentFlags();
+ m_owningLayer->stackingNode()->updateZOrderLists();
+
+ bool layerConfigChanged = false;
+ setBackgroundLayerPaintsFixedRootBackground(compositor->needsFixedRootBackgroundLayer(m_owningLayer));
+
+ // The background layer is currently only used for fixed root backgrounds.
+ if (updateBackgroundLayer(m_backgroundLayerPaintsFixedRootBackground))
+ layerConfigChanged = true;
+
+ if (updateForegroundLayer(compositor->needsContentsCompositingLayer(m_owningLayer)))
+ layerConfigChanged = true;
+
+ bool needsDescendentsClippingLayer = compositor->clipsCompositingDescendants(m_owningLayer);
+
+ // Our scrolling layer will clip.
+ if (m_owningLayer->needsCompositedScrolling())
+ needsDescendentsClippingLayer = false;
+
+ RenderLayer* scrollParent = m_owningLayer->scrollParent();
+ bool needsAncestorClip = compositor->clippedByAncestor(m_owningLayer);
+ if (scrollParent) {
+ // If our containing block is our ancestor scrolling layer, then we'll already be clipped
+ // to it via our scroll parent and we don't need an ancestor clipping layer.
+ if (m_owningLayer->renderer()->containingBlock()->enclosingLayer() == m_owningLayer->ancestorCompositedScrollingLayer())
+ needsAncestorClip = false;
+ }
+ if (updateClippingLayers(needsAncestorClip, needsDescendentsClippingLayer))
+ layerConfigChanged = true;
+
+ if (updateOverflowControlsLayers(requiresHorizontalScrollbarLayer(), requiresVerticalScrollbarLayer(), requiresScrollCornerLayer()))
+ layerConfigChanged = true;
+
+ if (updateScrollingLayers(m_owningLayer->needsCompositedScrolling()))
+ layerConfigChanged = true;
+
+ updateScrollParent(scrollParent);
+ updateClipParent(m_owningLayer->clipParent());
+
+ if (updateSquashingLayers(!m_squashedLayers.isEmpty()))
+ layerConfigChanged = true;
+
+ if (layerConfigChanged)
+ updateInternalHierarchy();
+
+ if (updateMaskLayer(renderer->hasMask()))
+ m_graphicsLayer->setMaskLayer(m_maskLayer.get());
+
+ bool hasChildClippingLayer = compositor->clipsCompositingDescendants(m_owningLayer) && (hasClippingLayer() || hasScrollingLayer());
+ bool needsChildClippingMask = (renderer->style()->clipPath() || renderer->style()->hasBorderRadius()) && (hasChildClippingLayer || isAcceleratedContents(renderer));
+ if (updateClippingMaskLayers(needsChildClippingMask)) {
+ if (hasClippingLayer())
+ clippingLayer()->setMaskLayer(m_childClippingMaskLayer.get());
+ else if (hasScrollingLayer())
+ scrollingLayer()->setMaskLayer(m_childClippingMaskLayer.get());
+ else if (isAcceleratedContents(renderer))
+ m_graphicsLayer->setContentsClippingMaskLayer(m_childClippingMaskLayer.get());
+ }
+
+ if (m_owningLayer->reflectionInfo()) {
+ if (m_owningLayer->reflectionInfo()->reflectionLayer()->hasCompositedLayerMapping()) {
+ GraphicsLayer* reflectionLayer = m_owningLayer->reflectionInfo()->reflectionLayer()->compositedLayerMapping()->mainGraphicsLayer();
+ m_graphicsLayer->setReplicatedByLayer(reflectionLayer);
+ }
+ } else {
+ m_graphicsLayer->setReplicatedByLayer(0);
+ }
+
+ updateBackgroundColor(isSimpleContainerCompositingLayer());
+
+ if (isDirectlyCompositedImage())
+ updateImageContents();
+
+ if (renderer->isEmbeddedObject() && toRenderEmbeddedObject(renderer)->allowsAcceleratedCompositing()) {
+ PluginView* pluginView = toPluginView(toRenderWidget(renderer)->widget());
+ m_graphicsLayer->setContentsToPlatformLayer(pluginView->platformLayer());
+ } else if (renderer->node() && renderer->node()->isFrameOwnerElement() && toHTMLFrameOwnerElement(renderer->node())->contentFrame()) {
+ blink::WebLayer* layer = toHTMLFrameOwnerElement(renderer->node())->contentFrame()->remotePlatformLayer();
+ if (layer)
+ m_graphicsLayer->setContentsToPlatformLayer(layer);
+ } else if (renderer->isVideo()) {
+ HTMLMediaElement* mediaElement = toHTMLMediaElement(renderer->node());
+ m_graphicsLayer->setContentsToPlatformLayer(mediaElement->platformLayer());
+ } else if (isAcceleratedCanvas(renderer)) {
+ HTMLCanvasElement* canvas = toHTMLCanvasElement(renderer->node());
+ if (CanvasRenderingContext* context = canvas->renderingContext())
+ m_graphicsLayer->setContentsToPlatformLayer(context->platformLayer());
+ layerConfigChanged = true;
+ }
+ if (renderer->isRenderPart())
+ layerConfigChanged = RenderLayerCompositor::parentFrameContentLayers(toRenderPart(renderer));
+
+ return layerConfigChanged;
+}
+
+static IntRect clipBox(RenderBox* renderer)
+{
+ LayoutRect result = PaintInfo::infiniteRect();
+ if (renderer->hasOverflowClip())
+ result = renderer->overflowClipRect(LayoutPoint(), 0); // FIXME: Incorrect for CSS regions.
+
+ if (renderer->hasClip())
+ result.intersect(renderer->clipRect(LayoutPoint(), 0)); // FIXME: Incorrect for CSS regions.
+
+ return pixelSnappedIntRect(result);
+}
+
+void CompositedLayerMapping::updateGraphicsLayerGeometry()
+{
+ // If we haven't built z-order lists yet, wait until later.
+ if (m_owningLayer->stackingNode()->isStackingContainer() && m_owningLayer->stackingNode()->zOrderListsDirty())
+ return;
+
+ // Set transform property, if it is not animating. We have to do this here because the transform
+ // is affected by the layer dimensions.
+ if (RuntimeEnabledFeatures::webAnimationsCSSEnabled()
+ ? !hasActiveAnimationsOnCompositor(*renderer(), CSSPropertyWebkitTransform)
+ : !renderer()->animation().isRunningAcceleratedAnimationOnRenderer(renderer(), CSSPropertyWebkitTransform))
+ updateTransform(renderer()->style());
+
+ // Set opacity, if it is not animating.
+ if (RuntimeEnabledFeatures::webAnimationsCSSEnabled()
+ ? !hasActiveAnimationsOnCompositor(*renderer(), CSSPropertyOpacity)
+ : !renderer()->animation().isRunningAcceleratedAnimationOnRenderer(renderer(), CSSPropertyOpacity))
+ updateOpacity(renderer()->style());
+
+ bool isSimpleContainer = isSimpleContainerCompositingLayer();
+
+ m_owningLayer->updateDescendantDependentFlags();
+
+ // m_graphicsLayer is the corresponding GraphicsLayer for this RenderLayer and its non-compositing
+ // descendants. So, the visibility flag for m_graphicsLayer should be true if there are any
+ // non-compositing visible layers.
+ bool contentsVisible = m_owningLayer->hasVisibleContent() || hasVisibleNonCompositingDescendantLayers();
+ if (RuntimeEnabledFeatures::overlayFullscreenVideoEnabled() && renderer()->isVideo()) {
+ HTMLMediaElement* mediaElement = toHTMLMediaElement(renderer()->node());
+ if (mediaElement->isFullscreen())
+ contentsVisible = false;
+ }
+ m_graphicsLayer->setContentsVisible(contentsVisible);
+
+ RenderStyle* style = renderer()->style();
+ // FIXME: reflections should force transform-style to be flat in the style: https://bugs.webkit.org/show_bug.cgi?id=106959
+ bool preserves3D = style->transformStyle3D() == TransformStyle3DPreserve3D && !renderer()->hasReflection();
+ m_graphicsLayer->setPreserves3D(preserves3D);
+ m_graphicsLayer->setBackfaceVisibility(style->backfaceVisibility() == BackfaceVisibilityVisible);
+
+ RenderLayer* compAncestor = m_owningLayer->ancestorCompositingLayer();
+
+ // We compute everything relative to the enclosing compositing layer.
+ IntRect ancestorCompositingBounds;
+ if (compAncestor) {
+ ASSERT(compAncestor->hasCompositedLayerMapping());
+ ancestorCompositingBounds = pixelSnappedIntRect(compAncestor->compositedLayerMapping()->compositedBounds());
+ }
+
+ IntRect localCompositingBounds = pixelSnappedIntRect(compositedBounds());
+
+ IntRect relativeCompositingBounds(localCompositingBounds);
+ IntPoint delta;
+ m_owningLayer->convertToPixelSnappedLayerCoords(compAncestor, delta);
+ relativeCompositingBounds.moveBy(delta);
+
+ IntPoint graphicsLayerParentLocation;
+ if (compAncestor && compAncestor->compositedLayerMapping()->hasClippingLayer()) {
+ // If the compositing ancestor has a layer to clip children, we parent in that, and therefore
+ // position relative to it.
+ IntRect clippingBox = clipBox(toRenderBox(compAncestor->renderer()));
+ graphicsLayerParentLocation = clippingBox.location();
+ } else if (compAncestor) {
+ graphicsLayerParentLocation = ancestorCompositingBounds.location();
+ } else {
+ graphicsLayerParentLocation = renderer()->view()->documentRect().location();
+ }
+
+ if (compAncestor && compAncestor->needsCompositedScrolling()) {
+ RenderBox* renderBox = toRenderBox(compAncestor->renderer());
+ IntSize scrollOffset = renderBox->scrolledContentOffset();
+ IntPoint scrollOrigin(renderBox->borderLeft(), renderBox->borderTop());
+ graphicsLayerParentLocation = scrollOrigin - scrollOffset;
+ }
+
+ if (compAncestor && m_ancestorClippingLayer) {
+ // Call calculateRects to get the backgroundRect which is what is used to clip the contents of this
+ // layer. Note that we call it with temporaryClipRects = true because normally when computing clip rects
+ // for a compositing layer, rootLayer is the layer itself.
+ ClipRectsContext clipRectsContext(compAncestor, 0, TemporaryClipRects, IgnoreOverlayScrollbarSize, IgnoreOverflowClip);
+ IntRect parentClipRect = pixelSnappedIntRect(m_owningLayer->backgroundClipRect(clipRectsContext).rect()); // FIXME: Incorrect for CSS regions.
+ ASSERT(parentClipRect != PaintInfo::infiniteRect());
+ m_ancestorClippingLayer->setPosition(FloatPoint(parentClipRect.location() - graphicsLayerParentLocation));
+ m_ancestorClippingLayer->setSize(parentClipRect.size());
+
+ // backgroundRect is relative to compAncestor, so subtract deltaX/deltaY to get back to local coords.
+ m_ancestorClippingLayer->setOffsetFromRenderer(parentClipRect.location() - delta);
+
+ // The primary layer is then parented in, and positioned relative to this clipping layer.
+ graphicsLayerParentLocation = parentClipRect.location();
+ }
+
+ FloatSize contentsSize = relativeCompositingBounds.size();
+
+ m_graphicsLayer->setPosition(FloatPoint(relativeCompositingBounds.location() - graphicsLayerParentLocation));
+ m_graphicsLayer->setOffsetFromRenderer(toIntSize(localCompositingBounds.location()));
+
+ FloatSize oldSize = m_graphicsLayer->size();
+ if (oldSize != contentsSize) {
+ m_graphicsLayer->setSize(contentsSize);
+ // Usually invalidation will happen via layout etc, but if we've affected the layer
+ // size by constraining relative to a clipping ancestor or the viewport, we
+ // have to invalidate to avoid showing stretched content.
+ if (m_boundsConstrainedByClipping)
+ m_graphicsLayer->setNeedsDisplay();
+ }
+
+ // If we have a layer that clips children, position it.
+ IntRect clippingBox;
+ if (GraphicsLayer* clipLayer = clippingLayer()) {
+ clippingBox = clipBox(toRenderBox(renderer()));
+ clipLayer->setPosition(FloatPoint(clippingBox.location() - localCompositingBounds.location()));
+ clipLayer->setSize(clippingBox.size());
+ clipLayer->setOffsetFromRenderer(toIntSize(clippingBox.location()));
+ if (m_childClippingMaskLayer && !m_scrollingLayer) {
+ m_childClippingMaskLayer->setPosition(clipLayer->position());
+ m_childClippingMaskLayer->setSize(clipLayer->size());
+ m_childClippingMaskLayer->setOffsetFromRenderer(clipLayer->offsetFromRenderer());
+ }
+ }
+
+ if (m_maskLayer) {
+ if (m_maskLayer->size() != m_graphicsLayer->size()) {
+ m_maskLayer->setSize(m_graphicsLayer->size());
+ m_maskLayer->setNeedsDisplay();
+ }
+ m_maskLayer->setPosition(FloatPoint());
+ m_maskLayer->setOffsetFromRenderer(m_graphicsLayer->offsetFromRenderer());
+ }
+
+ if (m_owningLayer->hasTransform()) {
+ const IntRect borderBox = toRenderBox(renderer())->pixelSnappedBorderBoxRect();
+
+ // Get layout bounds in the coords of compAncestor to match relativeCompositingBounds.
+ IntRect layerBounds = IntRect(delta, borderBox.size());
+
+ // Update properties that depend on layer dimensions
+ FloatPoint3D transformOrigin = computeTransformOrigin(borderBox);
+ // Compute the anchor point, which is in the center of the renderer box unless transform-origin is set.
+ FloatPoint3D anchor(relativeCompositingBounds.width() != 0.0f ? ((layerBounds.x() - relativeCompositingBounds.x()) + transformOrigin.x()) / relativeCompositingBounds.width() : 0.5f,
+ relativeCompositingBounds.height() != 0.0f ? ((layerBounds.y() - relativeCompositingBounds.y()) + transformOrigin.y()) / relativeCompositingBounds.height() : 0.5f,
+ transformOrigin.z());
+ m_graphicsLayer->setAnchorPoint(anchor);
+
+ RenderStyle* style = renderer()->style();
+ GraphicsLayer* clipLayer = clippingLayer();
+ if (style->hasPerspective()) {
+ TransformationMatrix t = owningLayer()->perspectiveTransform();
+
+ if (clipLayer) {
+ clipLayer->setChildrenTransform(t);
+ m_graphicsLayer->setChildrenTransform(TransformationMatrix());
+ } else {
+ m_graphicsLayer->setChildrenTransform(t);
+ }
+ } else {
+ if (clipLayer)
+ clipLayer->setChildrenTransform(TransformationMatrix());
+ else
+ m_graphicsLayer->setChildrenTransform(TransformationMatrix());
+ }
+ } else {
+ m_graphicsLayer->setAnchorPoint(FloatPoint3D(0.5f, 0.5f, 0));
+ }
+
+ if (m_foregroundLayer) {
+ FloatPoint foregroundPosition;
+ FloatSize foregroundSize = contentsSize;
+ IntSize foregroundOffset = m_graphicsLayer->offsetFromRenderer();
+ if (hasClippingLayer()) {
+ // If we have a clipping layer (which clips descendants), then the foreground layer is a child of it,
+ // so that it gets correctly sorted with children. In that case, position relative to the clipping layer.
+ foregroundSize = FloatSize(clippingBox.size());
+ foregroundOffset = toIntSize(clippingBox.location());
+ }
+
+ m_foregroundLayer->setPosition(foregroundPosition);
+ if (foregroundSize != m_foregroundLayer->size()) {
+ m_foregroundLayer->setSize(foregroundSize);
+ m_foregroundLayer->setNeedsDisplay();
+ }
+ m_foregroundLayer->setOffsetFromRenderer(foregroundOffset);
+ }
+
+ if (m_backgroundLayer) {
+ FloatPoint backgroundPosition;
+ FloatSize backgroundSize = contentsSize;
+ if (backgroundLayerPaintsFixedRootBackground()) {
+ FrameView* frameView = toRenderView(renderer())->frameView();
+ backgroundSize = frameView->visibleContentRect().size();
+ }
+ m_backgroundLayer->setPosition(backgroundPosition);
+ if (backgroundSize != m_backgroundLayer->size()) {
+ m_backgroundLayer->setSize(backgroundSize);
+ m_backgroundLayer->setNeedsDisplay();
+ }
+ m_backgroundLayer->setOffsetFromRenderer(m_graphicsLayer->offsetFromRenderer());
+ }
+
+ if (m_owningLayer->reflectionInfo() && m_owningLayer->reflectionInfo()->reflectionLayer()->hasCompositedLayerMapping()) {
+ CompositedLayerMappingPtr reflectionCompositedLayerMapping = m_owningLayer->reflectionInfo()->reflectionLayer()->compositedLayerMapping();
+ reflectionCompositedLayerMapping->updateGraphicsLayerGeometry();
+
+ // The reflection layer has the bounds of m_owningLayer->reflectionLayer(),
+ // but the reflected layer is the bounds of this layer, so we need to position it appropriately.
+ FloatRect layerBounds = compositedBounds();
+ FloatRect reflectionLayerBounds = reflectionCompositedLayerMapping->compositedBounds();
+ reflectionCompositedLayerMapping->mainGraphicsLayer()->setReplicatedLayerPosition(FloatPoint(layerBounds.location() - reflectionLayerBounds.location()));
+ }
+
+ if (m_scrollingLayer) {
+ ASSERT(m_scrollingContentsLayer);
+ RenderBox* renderBox = toRenderBox(renderer());
+ IntRect clientBox = enclosingIntRect(renderBox->clientBoxRect());
+ // FIXME: We should make RenderBox::clientBoxRect consider scrollbar placement.
+ if (style->shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
+ clientBox.move(renderBox->verticalScrollbarWidth(), 0);
+
+ IntSize adjustedScrollOffset = m_owningLayer->scrollableArea()->adjustedScrollOffset();
+ m_scrollingLayer->setPosition(FloatPoint(clientBox.location() - localCompositingBounds.location()));
+ m_scrollingLayer->setSize(clientBox.size());
+
+ IntSize oldScrollingLayerOffset = m_scrollingLayer->offsetFromRenderer();
+ m_scrollingLayer->setOffsetFromRenderer(-toIntSize(clientBox.location()));
+
+ if (m_childClippingMaskLayer) {
+ m_childClippingMaskLayer->setPosition(m_scrollingLayer->position());
+ m_childClippingMaskLayer->setSize(m_scrollingLayer->size());
+ m_childClippingMaskLayer->setOffsetFromRenderer(toIntSize(clientBox.location()));
+ }
+
+ bool clientBoxOffsetChanged = oldScrollingLayerOffset != m_scrollingLayer->offsetFromRenderer();
+
+ IntSize scrollSize(renderBox->scrollWidth(), renderBox->scrollHeight());
+ if (scrollSize != m_scrollingContentsLayer->size() || clientBoxOffsetChanged)
+ m_scrollingContentsLayer->setNeedsDisplay();
+
+ IntSize scrollingContentsOffset = toIntSize(clientBox.location() - adjustedScrollOffset);
+ if (scrollingContentsOffset != m_scrollingContentsLayer->offsetFromRenderer() || scrollSize != m_scrollingContentsLayer->size()) {
+ bool scrollingCoordinatorHandlesOffset = compositor()->scrollingLayerDidChange(m_owningLayer);
+
+ if (scrollingCoordinatorHandlesOffset)
+ m_scrollingContentsLayer->setPosition(-m_owningLayer->scrollableArea()->scrollOrigin());
+ else
+ m_scrollingContentsLayer->setPosition(FloatPoint(-adjustedScrollOffset));
+ }
+
+ m_scrollingContentsLayer->setSize(scrollSize);
+ // FIXME: The paint offset and the scroll offset should really be separate concepts.
+ m_scrollingContentsLayer->setOffsetFromRenderer(scrollingContentsOffset, GraphicsLayer::DontSetNeedsDisplay);
+
+ if (m_foregroundLayer) {
+ if (m_foregroundLayer->size() != m_scrollingContentsLayer->size())
+ m_foregroundLayer->setSize(m_scrollingContentsLayer->size());
+ m_foregroundLayer->setNeedsDisplay();
+ m_foregroundLayer->setOffsetFromRenderer(m_scrollingContentsLayer->offsetFromRenderer());
+ }
+ }
+
+ if (m_squashingLayer) {
+ ASSERT(compositor()->layerSquashingEnabled());
+
+ IntRect totalSquashBounds;
+ for (size_t i = 0; i < m_squashedLayers.size(); ++i) {
+ IntRect squashedBounds = compositor()->calculateCompositedBounds(m_squashedLayers[i].renderLayer, m_squashedLayers[i].renderLayer);
+
+ // Store the composited bounds before applying the offset.
+ // FIXME: consider whether it is more efficient or clarifies the math to store the compositedBounds after applying the offset.
+ m_squashedLayers[i].compositedBounds = squashedBounds;
+
+ squashedBounds.move(m_squashedLayers[i].offsetFromBackingRoot);
+ totalSquashBounds.unite(squashedBounds);
+ }
+
+ IntPoint squashLayerPosition;
+ // FIXME: this logic needs to update depending on what "containment" layers are added to CompositedLayerMapping due to other changes
+ if (m_ancestorClippingLayer) {
+ squashLayerPosition = IntPoint(m_ancestorClippingLayer->position().x() + totalSquashBounds.location().x(),
+ m_ancestorClippingLayer->position().y() + totalSquashBounds.location().y());
+ } else {
+ squashLayerPosition = IntPoint(m_graphicsLayer->position().x() + totalSquashBounds.location().x(),
+ m_graphicsLayer->position().y() + totalSquashBounds.location().y());
+ }
+
+ m_squashingLayer->setPosition(squashLayerPosition);
+ m_squashingLayer->setSize(totalSquashBounds.size());
+
+ // Now that the position of the squashing layer is known, update the offsets for each squashed RenderLayer.
+ for (size_t i = 0; i < m_squashedLayers.size(); ++i) {
+ m_squashedLayers[i].offsetFromRenderer = IntSize(-m_squashedLayers[i].offsetFromBackingRoot.width() - m_graphicsLayer->position().x() + m_squashingLayer->position().x(),
+ -m_squashedLayers[i].offsetFromBackingRoot.height() - m_graphicsLayer->position().y() + m_squashingLayer->position().y());
+
+ // FIXME: find a better design to avoid this redundant value - most likely it will make
+ // sense to move the paint task info into RenderLayer's m_compositingProperties.
+ m_squashedLayers[i].renderLayer->setOffsetFromSquashingLayerOrigin(m_squashedLayers[i].offsetFromRenderer);
+ }
+ }
+
+ if (m_owningLayer->scrollableArea())
+ m_owningLayer->scrollableArea()->positionOverflowControls();
+
+ // We can't make this call in RenderLayerCompositor::allocateOrClearCompositedLayerMapping
+ // since it depends on whether compAncestor draws content, which gets updated later.
+ updateRequiresOwnBackingStoreForAncestorReasons(compAncestor);
+
+ if (RuntimeEnabledFeatures::cssCompositingEnabled()) {
+ updateLayerBlendMode(style);
+ updateIsRootForIsolatedGroup();
+ }
+
+ updateContentsRect(isSimpleContainer);
+ updateBackgroundColor(isSimpleContainer);
+ updateDrawsContent(isSimpleContainer);
+ updateContentsOpaque();
+ updateAfterWidgetResize();
+ registerScrollingLayers();
+
+ updateCompositingReasons();
+}
+
+void CompositedLayerMapping::registerScrollingLayers()
+{
+ // Register fixed position layers and their containers with the scrolling coordinator.
+ ScrollingCoordinator* scrollingCoordinator = scrollingCoordinatorFromLayer(m_owningLayer);
+ if (!scrollingCoordinator)
+ return;
+
+ compositor()->updateViewportConstraintStatus(m_owningLayer);
+
+ scrollingCoordinator->updateLayerPositionConstraint(m_owningLayer);
+
+ // Page scale is applied as a transform on the root render view layer. Because the scroll
+ // layer is further up in the hierarchy, we need to avoid marking the root render view
+ // layer as a container.
+ bool isContainer = m_owningLayer->hasTransform() && !m_owningLayer->isRootLayer();
+ // FIXME: we should make certain that childForSuperLayers will never be the m_squashingContainmentLayer here
+ scrollingCoordinator->setLayerIsContainerForFixedPositionLayers(childForSuperlayers(), isContainer);
+}
+
+void CompositedLayerMapping::updateInternalHierarchy()
+{
+ // m_foregroundLayer has to be inserted in the correct order with child layers,
+ // so it's not inserted here.
+ if (m_ancestorClippingLayer)
+ m_ancestorClippingLayer->removeAllChildren();
+
+ m_graphicsLayer->removeFromParent();
+
+ if (m_ancestorClippingLayer)
+ m_ancestorClippingLayer->addChild(m_graphicsLayer.get());
+
+ if (m_childContainmentLayer) {
+ m_childContainmentLayer->removeFromParent();
+ m_graphicsLayer->addChild(m_childContainmentLayer.get());
+ }
+
+ if (m_scrollingLayer) {
+ GraphicsLayer* superlayer = m_childContainmentLayer ? m_childContainmentLayer.get() : m_graphicsLayer.get();
+ m_scrollingLayer->removeFromParent();
+ superlayer->addChild(m_scrollingLayer.get());
+ }
+
+ // The clip for child layers does not include space for overflow controls, so they exist as
+ // siblings of the clipping layer if we have one. Normal children of this layer are set as
+ // children of the clipping layer.
+ if (m_layerForHorizontalScrollbar) {
+ m_layerForHorizontalScrollbar->removeFromParent();
+ m_graphicsLayer->addChild(m_layerForHorizontalScrollbar.get());
+ }
+ if (m_layerForVerticalScrollbar) {
+ m_layerForVerticalScrollbar->removeFromParent();
+ m_graphicsLayer->addChild(m_layerForVerticalScrollbar.get());
+ }
+ if (m_layerForScrollCorner) {
+ m_layerForScrollCorner->removeFromParent();
+ m_graphicsLayer->addChild(m_layerForScrollCorner.get());
+ }
+
+ // The squashing containment layer, if it exists, becomes a no-op parent.
+ if (m_squashingLayer) {
+ ASSERT(compositor()->layerSquashingEnabled());
+ ASSERT(m_squashingContainmentLayer);
+
+ m_squashingContainmentLayer->removeAllChildren();
+
+ if (m_ancestorClippingLayer)
+ m_squashingContainmentLayer->addChild(m_ancestorClippingLayer.get());
+ else
+ m_squashingContainmentLayer->addChild(m_graphicsLayer.get());
+
+ m_squashingContainmentLayer->addChild(m_squashingLayer.get());
+ }
+}
+
+void CompositedLayerMapping::updateContentsRect(bool isSimpleContainer)
+{
+ IntRect contentsRect;
+ if (isSimpleContainer && renderer()->hasBackground())
+ contentsRect = backgroundBox();
+ else
+ contentsRect = contentsBox();
+
+ m_graphicsLayer->setContentsRect(contentsRect);
+}
+
+void CompositedLayerMapping::updateDrawsContent(bool isSimpleContainer)
+{
+ if (m_scrollingLayer) {
+ // We don't have to consider overflow controls, because we know that the scrollbars are drawn elsewhere.
+ // m_graphicsLayer only needs backing store if the non-scrolling parts (background, outlines, borders, shadows etc) need to paint.
+ // m_scrollingLayer never has backing store.
+ // m_scrollingContentsLayer only needs backing store if the scrolled contents need to paint.
+ bool hasNonScrollingPaintedContent = m_owningLayer->hasVisibleContent() && m_owningLayer->hasBoxDecorationsOrBackground();
+ m_graphicsLayer->setDrawsContent(hasNonScrollingPaintedContent);
+
+ bool hasScrollingPaintedContent = m_owningLayer->hasVisibleContent() && (renderer()->hasBackground() || paintsChildren());
+ m_scrollingContentsLayer->setDrawsContent(hasScrollingPaintedContent);
+ return;
+ }
+
+ bool hasPaintedContent = containsPaintedContent(isSimpleContainer);
+ if (hasPaintedContent && isAcceleratedCanvas(renderer())) {
+ CanvasRenderingContext* context = toHTMLCanvasElement(renderer()->node())->renderingContext();
+ // Content layer may be null if context is lost.
+ if (blink::WebLayer* contentLayer = context->platformLayer()) {
+ Color bgColor;
+ if (contentLayerSupportsDirectBackgroundComposition(renderer())) {
+ bgColor = rendererBackgroundColor();
+ hasPaintedContent = false;
+ }
+ contentLayer->setBackgroundColor(bgColor.rgb());
+ }
+ }
+
+ // FIXME: we could refine this to only allocate backings for one of these layers if possible.
+ m_graphicsLayer->setDrawsContent(hasPaintedContent);
+ if (m_foregroundLayer)
+ m_foregroundLayer->setDrawsContent(hasPaintedContent);
+
+ if (m_backgroundLayer)
+ m_backgroundLayer->setDrawsContent(hasPaintedContent);
+}
+
+// Return true if the layers changed.
+bool CompositedLayerMapping::updateClippingLayers(bool needsAncestorClip, bool needsDescendantClip)
+{
+ bool layersChanged = false;
+
+ if (needsAncestorClip) {
+ if (!m_ancestorClippingLayer) {
+ m_ancestorClippingLayer = createGraphicsLayer(CompositingReasonLayerForClip);
+ m_ancestorClippingLayer->setMasksToBounds(true);
+ layersChanged = true;
+ }
+ } else if (m_ancestorClippingLayer) {
+ m_ancestorClippingLayer->removeFromParent();
+ m_ancestorClippingLayer = nullptr;
+ layersChanged = true;
+ }
+
+ if (needsDescendantClip) {
+ // We don't need a child containment layer if we're the main frame render view
+ // layer. It's redundant as the frame clip above us will handle this clipping.
+ if (!m_childContainmentLayer && !m_isMainFrameRenderViewLayer) {
+ m_childContainmentLayer = createGraphicsLayer(CompositingReasonLayerForClip);
+ m_childContainmentLayer->setMasksToBounds(true);
+ layersChanged = true;
+ }
+ } else if (hasClippingLayer()) {
+ m_childContainmentLayer->removeFromParent();
+ m_childContainmentLayer = nullptr;
+ layersChanged = true;
+ }
+
+ return layersChanged;
+}
+
+void CompositedLayerMapping::setBackgroundLayerPaintsFixedRootBackground(bool backgroundLayerPaintsFixedRootBackground)
+{
+ m_backgroundLayerPaintsFixedRootBackground = backgroundLayerPaintsFixedRootBackground;
+}
+
+bool CompositedLayerMapping::updateOverflowControlsLayers(bool needsHorizontalScrollbarLayer, bool needsVerticalScrollbarLayer, bool needsScrollCornerLayer)
+{
+ bool horizontalScrollbarLayerChanged = false;
+ if (needsHorizontalScrollbarLayer) {
+ if (!m_layerForHorizontalScrollbar) {
+ m_layerForHorizontalScrollbar = createGraphicsLayer(CompositingReasonLayerForScrollbar);
+ horizontalScrollbarLayerChanged = true;
+ }
+ } else if (m_layerForHorizontalScrollbar) {
+ m_layerForHorizontalScrollbar = nullptr;
+ horizontalScrollbarLayerChanged = true;
+ }
+
+ bool verticalScrollbarLayerChanged = false;
+ if (needsVerticalScrollbarLayer) {
+ if (!m_layerForVerticalScrollbar) {
+ m_layerForVerticalScrollbar = createGraphicsLayer(CompositingReasonLayerForScrollbar);
+ verticalScrollbarLayerChanged = true;
+ }
+ } else if (m_layerForVerticalScrollbar) {
+ m_layerForVerticalScrollbar = nullptr;
+ verticalScrollbarLayerChanged = true;
+ }
+
+ bool scrollCornerLayerChanged = false;
+ if (needsScrollCornerLayer) {
+ if (!m_layerForScrollCorner) {
+ m_layerForScrollCorner = createGraphicsLayer(CompositingReasonLayerForScrollbar);
+ scrollCornerLayerChanged = true;
+ }
+ } else if (m_layerForScrollCorner) {
+ m_layerForScrollCorner = nullptr;
+ scrollCornerLayerChanged = true;
+ }
+
+ if (ScrollingCoordinator* scrollingCoordinator = scrollingCoordinatorFromLayer(m_owningLayer)) {
+ if (horizontalScrollbarLayerChanged)
+ scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(m_owningLayer->scrollableArea(), HorizontalScrollbar);
+ if (verticalScrollbarLayerChanged)
+ scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(m_owningLayer->scrollableArea(), VerticalScrollbar);
+ }
+
+ return horizontalScrollbarLayerChanged || verticalScrollbarLayerChanged || scrollCornerLayerChanged;
+}
+
+void CompositedLayerMapping::positionOverflowControlsLayers(const IntSize& offsetFromRoot)
+{
+ IntSize offsetFromRenderer = m_graphicsLayer->offsetFromRenderer();
+ if (GraphicsLayer* layer = layerForHorizontalScrollbar()) {
+ Scrollbar* hBar = m_owningLayer->scrollableArea()->horizontalScrollbar();
+ if (hBar) {
+ layer->setPosition(hBar->frameRect().location() - offsetFromRoot - offsetFromRenderer);
+ layer->setSize(hBar->frameRect().size());
+ if (layer->hasContentsLayer())
+ layer->setContentsRect(IntRect(IntPoint(), hBar->frameRect().size()));
+ }
+ layer->setDrawsContent(hBar && !layer->hasContentsLayer());
+ }
+
+ if (GraphicsLayer* layer = layerForVerticalScrollbar()) {
+ Scrollbar* vBar = m_owningLayer->scrollableArea()->verticalScrollbar();
+ if (vBar) {
+ layer->setPosition(vBar->frameRect().location() - offsetFromRoot - offsetFromRenderer);
+ layer->setSize(vBar->frameRect().size());
+ if (layer->hasContentsLayer())
+ layer->setContentsRect(IntRect(IntPoint(), vBar->frameRect().size()));
+ }
+ layer->setDrawsContent(vBar && !layer->hasContentsLayer());
+ }
+
+ if (GraphicsLayer* layer = layerForScrollCorner()) {
+ const LayoutRect& scrollCornerAndResizer = m_owningLayer->scrollableArea()->scrollCornerAndResizerRect();
+ layer->setPosition(scrollCornerAndResizer.location() - offsetFromRenderer);
+ layer->setSize(scrollCornerAndResizer.size());
+ layer->setDrawsContent(!scrollCornerAndResizer.isEmpty());
+ }
+}
+
+bool CompositedLayerMapping::hasUnpositionedOverflowControlsLayers() const
+{
+ if (GraphicsLayer* layer = layerForHorizontalScrollbar()) {
+ if (!layer->drawsContent())
+ return true;
+ }
+
+ if (GraphicsLayer* layer = layerForVerticalScrollbar()) {
+ if (!layer->drawsContent())
+ return true;
+ }
+
+ if (GraphicsLayer* layer = layerForScrollCorner()) {
+ if (!layer->drawsContent())
+ return true;
+ }
+
+ return false;
+}
+
+bool CompositedLayerMapping::updateForegroundLayer(bool needsForegroundLayer)
+{
+ bool layerChanged = false;
+ if (needsForegroundLayer) {
+ if (!m_foregroundLayer) {
+ m_foregroundLayer = createGraphicsLayer(CompositingReasonLayerForForeground);
+ m_foregroundLayer->setDrawsContent(true);
+ m_foregroundLayer->setPaintingPhase(GraphicsLayerPaintForeground);
+ layerChanged = true;
+ }
+ } else if (m_foregroundLayer) {
+ m_foregroundLayer->removeFromParent();
+ m_foregroundLayer = nullptr;
+ layerChanged = true;
+ }
+
+ if (layerChanged)
+ m_graphicsLayer->setPaintingPhase(paintingPhaseForPrimaryLayer());
+
+ return layerChanged;
+}
+
+bool CompositedLayerMapping::updateBackgroundLayer(bool needsBackgroundLayer)
+{
+ bool layerChanged = false;
+ if (needsBackgroundLayer) {
+ if (!m_backgroundLayer) {
+ m_backgroundLayer = createGraphicsLayer(CompositingReasonLayerForBackground);
+ m_backgroundLayer->setDrawsContent(true);
+ m_backgroundLayer->setAnchorPoint(FloatPoint3D());
+ m_backgroundLayer->setPaintingPhase(GraphicsLayerPaintBackground);
+#if !OS(ANDROID)
+ m_backgroundLayer->contentLayer()->setDrawCheckerboardForMissingTiles(true);
+ m_graphicsLayer->contentLayer()->setDrawCheckerboardForMissingTiles(false);
+#endif
+ layerChanged = true;
+ }
+ } else {
+ if (m_backgroundLayer) {
+ m_backgroundLayer->removeFromParent();
+ m_backgroundLayer = nullptr;
+#if !OS(ANDROID)
+ m_graphicsLayer->contentLayer()->setDrawCheckerboardForMissingTiles(true);
+#endif
+ layerChanged = true;
+ }
+ }
+
+ if (layerChanged && !m_owningLayer->renderer()->documentBeingDestroyed())
+ compositor()->rootFixedBackgroundsChanged();
+
+ return layerChanged;
+}
+
+bool CompositedLayerMapping::updateMaskLayer(bool needsMaskLayer)
+{
+ bool layerChanged = false;
+ if (needsMaskLayer) {
+ if (!m_maskLayer) {
+ m_maskLayer = createGraphicsLayer(CompositingReasonLayerForMask);
+ m_maskLayer->setDrawsContent(true);
+ m_maskLayer->setPaintingPhase(GraphicsLayerPaintMask);
+ layerChanged = true;
+ }
+ } else if (m_maskLayer) {
+ m_maskLayer = nullptr;
+ layerChanged = true;
+ }
+
+ if (layerChanged)
+ m_graphicsLayer->setPaintingPhase(paintingPhaseForPrimaryLayer());
+
+ return layerChanged;
+}
+
+bool CompositedLayerMapping::updateClippingMaskLayers(bool needsChildClippingMaskLayer)
+{
+ bool layerChanged = false;
+ if (needsChildClippingMaskLayer) {
+ if (!m_childClippingMaskLayer) {
+ m_childClippingMaskLayer = createGraphicsLayer(CompositingReasonLayerForMask);
+ m_childClippingMaskLayer->setDrawsContent(true);
+ m_childClippingMaskLayer->setPaintingPhase(GraphicsLayerPaintChildClippingMask);
+ layerChanged = true;
+ }
+ } else if (m_childClippingMaskLayer) {
+ m_childClippingMaskLayer = nullptr;
+ layerChanged = true;
+ }
+ return layerChanged;
+}
+
+bool CompositedLayerMapping::updateScrollingLayers(bool needsScrollingLayers)
+{
+ ScrollingCoordinator* scrollingCoordinator = scrollingCoordinatorFromLayer(m_owningLayer);
+
+ bool layerChanged = false;
+ if (needsScrollingLayers) {
+ if (!m_scrollingLayer) {
+ // Outer layer which corresponds with the scroll view.
+ m_scrollingLayer = createGraphicsLayer(CompositingReasonLayerForClip);
+ m_scrollingLayer->setDrawsContent(false);
+ m_scrollingLayer->setMasksToBounds(true);
+
+ // Inner layer which renders the content that scrolls.
+ m_scrollingContentsLayer = createGraphicsLayer(CompositingReasonLayerForScrollingContainer);
+ m_scrollingContentsLayer->setDrawsContent(true);
+ GraphicsLayerPaintingPhase paintPhase = GraphicsLayerPaintOverflowContents | GraphicsLayerPaintCompositedScroll;
+ if (!m_foregroundLayer)
+ paintPhase |= GraphicsLayerPaintForeground;
+ m_scrollingContentsLayer->setPaintingPhase(paintPhase);
+ m_scrollingLayer->addChild(m_scrollingContentsLayer.get());
+
+ layerChanged = true;
+ if (scrollingCoordinator)
+ scrollingCoordinator->scrollableAreaScrollLayerDidChange(m_owningLayer->scrollableArea());
+ }
+ } else if (m_scrollingLayer) {
+ m_scrollingLayer = nullptr;
+ m_scrollingContentsLayer = nullptr;
+ layerChanged = true;
+ if (scrollingCoordinator)
+ scrollingCoordinator->scrollableAreaScrollLayerDidChange(m_owningLayer->scrollableArea());
+ }
+
+ if (layerChanged) {
+ updateInternalHierarchy();
+ m_graphicsLayer->setPaintingPhase(paintingPhaseForPrimaryLayer());
+ m_graphicsLayer->setNeedsDisplay();
+ if (renderer()->view())
+ compositor()->scrollingLayerDidChange(m_owningLayer);
+ }
+
+ return layerChanged;
+}
+
+static void updateScrollParentForGraphicsLayer(GraphicsLayer* layer, GraphicsLayer* topmostLayer, RenderLayer* scrollParent, ScrollingCoordinator* scrollingCoordinator)
+{
+ if (!layer)
+ return;
+
+ // Only the topmost layer has a scroll parent. All other layers have a null scroll parent.
+ if (layer != topmostLayer)
+ scrollParent = 0;
+
+ scrollingCoordinator->updateScrollParentForGraphicsLayer(layer, scrollParent);
+}
+
+void CompositedLayerMapping::updateScrollParent(RenderLayer* scrollParent)
+{
+
+ if (ScrollingCoordinator* scrollingCoordinator = scrollingCoordinatorFromLayer(m_owningLayer)) {
+ GraphicsLayer* topmostLayer = childForSuperlayers();
+ updateScrollParentForGraphicsLayer(m_squashingContainmentLayer.get(), topmostLayer, scrollParent, scrollingCoordinator);
+ updateScrollParentForGraphicsLayer(m_ancestorClippingLayer.get(), topmostLayer, scrollParent, scrollingCoordinator);
+ updateScrollParentForGraphicsLayer(m_graphicsLayer.get(), topmostLayer, scrollParent, scrollingCoordinator);
+ }
+}
+
+void CompositedLayerMapping::updateClipParent(RenderLayer* clipParent)
+{
+ if (ScrollingCoordinator* scrollingCoordinator = scrollingCoordinatorFromLayer(m_owningLayer))
+ scrollingCoordinator->updateClipParentForGraphicsLayer(m_graphicsLayer.get(), clipParent);
+}
+
+bool CompositedLayerMapping::updateSquashingLayers(bool needsSquashingLayers)
+{
+ bool layersChanged = false;
+
+ if (needsSquashingLayers) {
+ ASSERT(compositor()->layerSquashingEnabled());
+
+ if (!m_squashingLayer) {
+ ASSERT(!m_squashingContainmentLayer);
+
+ m_squashingLayer = createGraphicsLayer(CompositingReasonOverlap);
+ m_squashingLayer->setDrawsContent(true);
+ m_squashingLayer->setNeedsDisplay();
+ layersChanged = true;
+
+ // FIXME: containment layer needs a new CompositingReason, CompositingReasonOverlap is not appropriate.
+ m_squashingContainmentLayer = createGraphicsLayer(CompositingReasonOverlap);
+ // FIXME: reflections should force transform-style to be flat in the style: https://bugs.webkit.org/show_bug.cgi?id=106959
+ bool preserves3D = renderer()->style()->transformStyle3D() == TransformStyle3DPreserve3D && !renderer()->hasReflection();
+ m_squashingContainmentLayer->setPreserves3D(preserves3D);
+ layersChanged = true;
+ }
+
+ ASSERT(m_squashingLayer && m_squashingContainmentLayer);
+ } else {
+ if (m_squashingLayer) {
+ m_squashingLayer->removeFromParent();
+ m_squashingLayer = nullptr;
+ layersChanged = true;
+ // FIXME: do we need to invalidate something here?
+
+ ASSERT(m_squashingContainmentLayer);
+ m_squashingContainmentLayer->removeFromParent();
+ m_squashingContainmentLayer = nullptr;
+ layersChanged = true;
+ }
+
+ ASSERT(!m_squashingLayer && !m_squashingContainmentLayer);
+ }
+
+ return layersChanged;
+}
+
+GraphicsLayerPaintingPhase CompositedLayerMapping::paintingPhaseForPrimaryLayer() const
+{
+ unsigned phase = 0;
+ if (!m_backgroundLayer)
+ phase |= GraphicsLayerPaintBackground;
+ if (!m_foregroundLayer)
+ phase |= GraphicsLayerPaintForeground;
+ if (!m_maskLayer)
+ phase |= GraphicsLayerPaintMask;
+
+ if (m_scrollingContentsLayer) {
+ phase &= ~GraphicsLayerPaintForeground;
+ phase |= GraphicsLayerPaintCompositedScroll;
+ }
+
+ if (m_owningLayer->compositingReasons() & CompositingReasonOverflowScrollingParent)
+ phase |= GraphicsLayerPaintCompositedScroll;
+
+ return static_cast<GraphicsLayerPaintingPhase>(phase);
+}
+
+float CompositedLayerMapping::compositingOpacity(float rendererOpacity) const
+{
+ float finalOpacity = rendererOpacity;
+
+ for (RenderLayer* curr = m_owningLayer->parent(); curr; curr = curr->parent()) {
+ // We only care about parents that are stacking contexts.
+ // Recall that opacity creates stacking context.
+ if (!curr->stackingNode()->isStackingContainer())
+ continue;
+
+ // If we found a composited layer, regardless of whether it actually
+ // paints into it, we want to compute opacity relative to it. So we can
+ // break here.
+ //
+ // FIXME: with grouped backings, a composited descendant will have to
+ // continue past the grouped (squashed) layers that its parents may
+ // contribute to. This whole confusion can be avoided by specifying
+ // explicitly the composited ancestor where we would stop accumulating
+ // opacity.
+ if (curr->compositingState() == PaintsIntoOwnBacking || curr->compositingState() == HasOwnBackingButPaintsIntoAncestor)
+ break;
+
+ finalOpacity *= curr->renderer()->opacity();
+ }
+
+ return finalOpacity;
+}
+
+Color CompositedLayerMapping::rendererBackgroundColor() const
+{
+ RenderObject* backgroundRenderer = renderer();
+ if (backgroundRenderer->isRoot())
+ backgroundRenderer = backgroundRenderer->rendererForRootBackground();
+
+ return backgroundRenderer->resolveColor(CSSPropertyBackgroundColor);
+}
+
+void CompositedLayerMapping::updateBackgroundColor(bool isSimpleContainer)
+{
+ Color backgroundColor = rendererBackgroundColor();
+ if (isSimpleContainer) {
+ m_graphicsLayer->setContentsToSolidColor(backgroundColor);
+ m_graphicsLayer->setBackgroundColor(Color());
+ } else {
+ // An unset (invalid) color will remove the solid color.
+ m_graphicsLayer->setContentsToSolidColor(Color());
+ m_graphicsLayer->setBackgroundColor(backgroundColor);
+ }
+}
+
+static bool supportsDirectBoxDecorationsComposition(const RenderObject* renderer)
+{
+ if (renderer->hasClip())
+ return false;
+
+ if (hasBoxDecorationsOrBackgroundImage(renderer->style()))
+ return false;
+
+ // FIXME: we should be able to allow backgroundComposite; However since this is not a common use case it has been deferred for now.
+ if (renderer->style()->backgroundComposite() != CompositeSourceOver)
+ return false;
+
+ if (renderer->style()->backgroundClip() == TextFillBox)
+ return false;
+
+ return true;
+}
+
+bool CompositedLayerMapping::paintsBoxDecorations() const
+{
+ if (!m_owningLayer->hasVisibleBoxDecorations())
+ return false;
+
+ if (!supportsDirectBoxDecorationsComposition(renderer()))
+ return true;
+
+ return false;
+}
+
+bool CompositedLayerMapping::paintsChildren() const
+{
+ if (m_owningLayer->hasVisibleContent() && m_owningLayer->hasNonEmptyChildRenderers())
+ return true;
+
+ if (hasVisibleNonCompositingDescendantLayers())
+ return true;
+
+ return false;
+}
+
+static bool isCompositedPlugin(RenderObject* renderer)
+{
+ return renderer->isEmbeddedObject() && toRenderEmbeddedObject(renderer)->allowsAcceleratedCompositing();
+}
+
+// A "simple container layer" is a RenderLayer which has no visible content to render.
+// It may have no children, or all its children may be themselves composited.
+// This is a useful optimization, because it allows us to avoid allocating backing store.
+bool CompositedLayerMapping::isSimpleContainerCompositingLayer() const
+{
+ RenderObject* renderObject = renderer();
+ if (renderObject->hasMask()) // masks require special treatment
+ return false;
+
+ if (renderObject->isReplaced() && !isCompositedPlugin(renderObject))
+ return false;
+
+ if (paintsBoxDecorations() || paintsChildren())
+ return false;
+
+ if (renderObject->isRenderRegion())
+ return false;
+
+ if (renderObject->node() && renderObject->node()->isDocumentNode()) {
+ // Look to see if the root object has a non-simple background
+ RenderObject* rootObject = renderObject->document().documentElement() ? renderObject->document().documentElement()->renderer() : 0;
+ if (!rootObject)
+ return false;
+
+ RenderStyle* style = rootObject->style();
+
+ // Reject anything that has a border, a border-radius or outline,
+ // or is not a simple background (no background, or solid color).
+ if (hasBoxDecorationsOrBackgroundImage(style))
+ return false;
+
+ // Now look at the body's renderer.
+ HTMLElement* body = renderObject->document().body();
+ RenderObject* bodyObject = (body && body->hasLocalName(bodyTag)) ? body->renderer() : 0;
+ if (!bodyObject)
+ return false;
+
+ style = bodyObject->style();
+
+ if (hasBoxDecorationsOrBackgroundImage(style))
+ return false;
+ }
+
+ return true;
+}
+
+static bool hasVisibleNonCompositingDescendant(RenderLayer* parent)
+{
+ // FIXME: We shouldn't be called with a stale z-order lists. See bug 85512.
+ parent->stackingNode()->updateLayerListsIfNeeded();
+
+#if !ASSERT_DISABLED
+ LayerListMutationDetector mutationChecker(parent->stackingNode());
+#endif
+
+ RenderLayerStackingNodeIterator normalFlowIterator(*parent->stackingNode(), NormalFlowChildren);
+ while (RenderLayerStackingNode* curNode = normalFlowIterator.next()) {
+ RenderLayer* curLayer = curNode->layer();
+ if (!curLayer->hasCompositedLayerMapping()
+ && (curLayer->hasVisibleContent() || hasVisibleNonCompositingDescendant(curLayer)))
+ return true;
+ }
+
+ if (!parent->hasVisibleDescendant())
+ return false;
+
+ RenderLayerStackingNodeIterator zOrderIterator(*parent->stackingNode(), NegativeZOrderChildren | PositiveZOrderChildren);
+ while (RenderLayerStackingNode* curNode = zOrderIterator.next()) {
+ RenderLayer* curLayer = curNode->layer();
+ if (!curLayer->hasCompositedLayerMapping()
+ && (curLayer->hasVisibleContent() || hasVisibleNonCompositingDescendant(curLayer)))
+ return true;
+ }
+
+ return false;
+}
+
+// FIXME: By name the implementation is correct. But the code that uses this function means something
+// very slightly different - the implementation needs to also include composited descendants that
+// don't paint into their own backing, and instead paint into this backing.
+bool CompositedLayerMapping::hasVisibleNonCompositingDescendantLayers() const
+{
+ return hasVisibleNonCompositingDescendant(m_owningLayer);
+}
+
+bool CompositedLayerMapping::containsPaintedContent(bool isSimpleContainer) const
+{
+ if (isSimpleContainer || paintsIntoCompositedAncestor() || m_artificiallyInflatedBounds || m_owningLayer->isReflection())
+ return false;
+
+ if (isDirectlyCompositedImage())
+ return false;
+
+ // FIXME: we could optimize cases where the image, video or canvas is known to fill the border box entirely,
+ // and set background color on the layer in that case, instead of allocating backing store and painting.
+ if (renderer()->isVideo() && toRenderVideo(renderer())->shouldDisplayVideo())
+ return m_owningLayer->hasBoxDecorationsOrBackground();
+
+ return true;
+}
+
+// An image can be directly compositing if it's the sole content of the layer, and has no box decorations
+// that require painting. Direct compositing saves backing store.
+bool CompositedLayerMapping::isDirectlyCompositedImage() const
+{
+ RenderObject* renderObject = renderer();
+
+ if (!renderObject->isImage() || m_owningLayer->hasBoxDecorationsOrBackground() || renderObject->hasClip())
+ return false;
+
+ RenderImage* imageRenderer = toRenderImage(renderObject);
+ if (ImageResource* cachedImage = imageRenderer->cachedImage()) {
+ if (!cachedImage->hasImage())
+ return false;
+
+ Image* image = cachedImage->imageForRenderer(imageRenderer);
+ return image->isBitmapImage();
+ }
+
+ return false;
+}
+
+void CompositedLayerMapping::contentChanged(ContentChangeType changeType)
+{
+ if ((changeType == ImageChanged) && isDirectlyCompositedImage()) {
+ updateImageContents();
+ return;
+ }
+
+ if ((changeType == MaskImageChanged) && m_maskLayer) {
+ // The composited layer bounds relies on box->maskClipRect(), which changes
+ // when the mask image becomes available.
+ updateAfterLayout(CompositingChildrenOnly | IsUpdateRoot);
+ }
+
+ if ((changeType == CanvasChanged || changeType == CanvasPixelsChanged) && isAcceleratedCanvas(renderer())) {
+ m_graphicsLayer->setContentsNeedsDisplay();
+ return;
+ }
+}
+
+void CompositedLayerMapping::updateImageContents()
+{
+ ASSERT(renderer()->isImage());
+ RenderImage* imageRenderer = toRenderImage(renderer());
+
+ ImageResource* cachedImage = imageRenderer->cachedImage();
+ if (!cachedImage)
+ return;
+
+ Image* image = cachedImage->imageForRenderer(imageRenderer);
+ if (!image)
+ return;
+
+ // We have to wait until the image is fully loaded before setting it on the layer.
+ if (!cachedImage->isLoaded())
+ return;
+
+ // This is a no-op if the layer doesn't have an inner layer for the image.
+ m_graphicsLayer->setContentsToImage(image);
+ bool isSimpleContainer = false;
+ updateDrawsContent(isSimpleContainer);
+
+ // Image animation is "lazy", in that it automatically stops unless someone is drawing
+ // the image. So we have to kick the animation each time; this has the downside that the
+ // image will keep animating, even if its layer is not visible.
+ image->startAnimation();
+}
+
+FloatPoint3D CompositedLayerMapping::computeTransformOrigin(const IntRect& borderBox) const
+{
+ RenderStyle* style = renderer()->style();
+
+ FloatPoint3D origin;
+ origin.setX(floatValueForLength(style->transformOriginX(), borderBox.width()));
+ origin.setY(floatValueForLength(style->transformOriginY(), borderBox.height()));
+ origin.setZ(style->transformOriginZ());
+
+ return origin;
+}
+
+FloatPoint CompositedLayerMapping::computePerspectiveOrigin(const IntRect& borderBox) const
+{
+ RenderStyle* style = renderer()->style();
+
+ float boxWidth = borderBox.width();
+ float boxHeight = borderBox.height();
+
+ FloatPoint origin;
+ origin.setX(floatValueForLength(style->perspectiveOriginX(), boxWidth));
+ origin.setY(floatValueForLength(style->perspectiveOriginY(), boxHeight));
+
+ return origin;
+}
+
+// Return the offset from the top-left of this compositing layer at which the renderer's contents are painted.
+IntSize CompositedLayerMapping::contentOffsetInCompostingLayer() const
+{
+ return IntSize(-m_compositedBounds.x(), -m_compositedBounds.y());
+}
+
+IntRect CompositedLayerMapping::contentsBox() const
+{
+ IntRect contentsBox = contentsRect(renderer());
+ contentsBox.move(contentOffsetInCompostingLayer());
+ return contentsBox;
+}
+
+IntRect CompositedLayerMapping::backgroundBox() const
+{
+ IntRect backgroundBox = backgroundRect(renderer());
+ backgroundBox.move(contentOffsetInCompostingLayer());
+ return backgroundBox;
+}
+
+GraphicsLayer* CompositedLayerMapping::parentForSublayers() const
+{
+ if (m_scrollingContentsLayer)
+ return m_scrollingContentsLayer.get();
+
+ return m_childContainmentLayer ? m_childContainmentLayer.get() : m_graphicsLayer.get();
+}
+
+GraphicsLayer* CompositedLayerMapping::childForSuperlayers() const
+{
+ if (m_squashingContainmentLayer)
+ return m_squashingContainmentLayer.get();
+
+ if (m_ancestorClippingLayer)
+ return m_ancestorClippingLayer.get();
+
+ return m_graphicsLayer.get();
+}
+
+bool CompositedLayerMapping::updateRequiresOwnBackingStoreForAncestorReasons(const RenderLayer* compositingAncestorLayer)
+{
+ bool previousRequiresOwnBackingStoreForAncestorReasons = m_requiresOwnBackingStoreForAncestorReasons;
+ bool previousPaintsIntoCompositedAncestor = paintsIntoCompositedAncestor();
+ bool canPaintIntoAncestor = compositingAncestorLayer
+ && (compositingAncestorLayer->compositedLayerMapping()->mainGraphicsLayer()->drawsContent()
+ || compositingAncestorLayer->compositedLayerMapping()->paintsIntoCompositedAncestor());
+ m_requiresOwnBackingStoreForAncestorReasons = !canPaintIntoAncestor;
+
+ if (paintsIntoCompositedAncestor() != previousPaintsIntoCompositedAncestor)
+ paintsIntoCompositedAncestorChanged();
+ return m_requiresOwnBackingStoreForAncestorReasons != previousRequiresOwnBackingStoreForAncestorReasons;
+}
+
+bool CompositedLayerMapping::updateRequiresOwnBackingStoreForIntrinsicReasons()
+{
+ bool previousRequiresOwnBackingStoreForIntrinsicReasons = m_requiresOwnBackingStoreForIntrinsicReasons;
+ bool previousPaintsIntoCompositedAncestor = paintsIntoCompositedAncestor();
+ RenderObject* renderer = m_owningLayer->renderer();
+ m_requiresOwnBackingStoreForIntrinsicReasons = m_owningLayer->isRootLayer()
+ || (m_owningLayer->compositingReasons() & CompositingReasonComboReasonsThatRequireOwnBacking)
+ || m_owningLayer->transform()
+ || m_owningLayer->clipsCompositingDescendantsWithBorderRadius() // FIXME: Revisit this if the paintsIntoCompositedAncestor state is removed.
+ || renderer->isTransparent()
+ || renderer->hasMask()
+ || renderer->hasReflection()
+ || renderer->hasFilter();
+
+ if (paintsIntoCompositedAncestor() != previousPaintsIntoCompositedAncestor)
+ paintsIntoCompositedAncestorChanged();
+ return m_requiresOwnBackingStoreForIntrinsicReasons != previousRequiresOwnBackingStoreForIntrinsicReasons;
+}
+
+void CompositedLayerMapping::paintsIntoCompositedAncestorChanged()
+{
+ // The answer to paintsIntoCompositedAncestor() affects cached clip rects, so when
+ // it changes we have to clear clip rects on descendants.
+ m_owningLayer->clipper().clearClipRectsIncludingDescendants(PaintingClipRects);
+ m_owningLayer->repainter().computeRepaintRectsIncludingDescendants();
+
+ compositor()->repaintInCompositedAncestor(m_owningLayer, compositedBounds());
+}
+
+void CompositedLayerMapping::setBlendMode(blink::WebBlendMode blendMode)
+{
+ if (m_ancestorClippingLayer) {
+ m_ancestorClippingLayer->setBlendMode(blendMode);
+ m_graphicsLayer->setBlendMode(blink::WebBlendModeNormal);
+ } else {
+ m_graphicsLayer->setBlendMode(blendMode);
+ }
+}
+
+void CompositedLayerMapping::setContentsNeedDisplay()
+{
+ ASSERT(!paintsIntoCompositedAncestor());
+
+ if (m_graphicsLayer && m_graphicsLayer->drawsContent())
+ m_graphicsLayer->setNeedsDisplay();
+
+ if (m_foregroundLayer && m_foregroundLayer->drawsContent())
+ m_foregroundLayer->setNeedsDisplay();
+
+ if (m_backgroundLayer && m_backgroundLayer->drawsContent())
+ m_backgroundLayer->setNeedsDisplay();
+
+ if (m_maskLayer && m_maskLayer->drawsContent())
+ m_maskLayer->setNeedsDisplay();
+
+ if (m_childClippingMaskLayer && m_childClippingMaskLayer->drawsContent())
+ m_childClippingMaskLayer->setNeedsDisplay();
+
+ if (m_scrollingContentsLayer && m_scrollingContentsLayer->drawsContent())
+ m_scrollingContentsLayer->setNeedsDisplay();
+}
+
+// r is in the coordinate space of the layer's render object
+void CompositedLayerMapping::setContentsNeedDisplayInRect(const IntRect& r)
+{
+ ASSERT(!paintsIntoCompositedAncestor());
+
+ if (m_graphicsLayer && m_graphicsLayer->drawsContent()) {
+ IntRect layerDirtyRect = r;
+ layerDirtyRect.move(-m_graphicsLayer->offsetFromRenderer());
+ m_graphicsLayer->setNeedsDisplayInRect(layerDirtyRect);
+ }
+
+ if (m_foregroundLayer && m_foregroundLayer->drawsContent()) {
+ IntRect layerDirtyRect = r;
+ layerDirtyRect.move(-m_foregroundLayer->offsetFromRenderer());
+ m_foregroundLayer->setNeedsDisplayInRect(layerDirtyRect);
+ }
+
+ // FIXME: need to split out repaints for the background.
+ if (m_backgroundLayer && m_backgroundLayer->drawsContent()) {
+ IntRect layerDirtyRect = r;
+ layerDirtyRect.move(-m_backgroundLayer->offsetFromRenderer());
+ m_backgroundLayer->setNeedsDisplayInRect(layerDirtyRect);
+ }
+
+ if (m_maskLayer && m_maskLayer->drawsContent()) {
+ IntRect layerDirtyRect = r;
+ layerDirtyRect.move(-m_maskLayer->offsetFromRenderer());
+ m_maskLayer->setNeedsDisplayInRect(layerDirtyRect);
+ }
+
+ if (m_childClippingMaskLayer && m_childClippingMaskLayer->drawsContent()) {
+ IntRect layerDirtyRect = r;
+ layerDirtyRect.move(-m_childClippingMaskLayer->offsetFromRenderer());
+ m_childClippingMaskLayer->setNeedsDisplayInRect(layerDirtyRect);
+ }
+
+ if (m_scrollingContentsLayer && m_scrollingContentsLayer->drawsContent()) {
+ IntRect layerDirtyRect = r;
+ layerDirtyRect.move(-m_scrollingContentsLayer->offsetFromRenderer());
+ m_scrollingContentsLayer->setNeedsDisplayInRect(layerDirtyRect);
+ }
+}
+
+void CompositedLayerMapping::doPaintTask(GraphicsLayerPaintInfo& paintInfo, GraphicsContext* context,
+ const IntRect& clip) // In the coords of rootLayer.
+{
+ if (paintsIntoCompositedAncestor()) {
+ ASSERT_NOT_REACHED();
+ return;
+ }
+
+ FontCachePurgePreventer fontCachePurgePreventer;
+
+ PaintLayerFlags paintFlags = 0;
+ if (paintInfo.paintingPhase & GraphicsLayerPaintBackground)
+ paintFlags |= PaintLayerPaintingCompositingBackgroundPhase;
+ if (paintInfo.paintingPhase & GraphicsLayerPaintForeground)
+ paintFlags |= PaintLayerPaintingCompositingForegroundPhase;
+ if (paintInfo.paintingPhase & GraphicsLayerPaintMask)
+ paintFlags |= PaintLayerPaintingCompositingMaskPhase;
+ if (paintInfo.paintingPhase & GraphicsLayerPaintChildClippingMask)
+ paintFlags |= PaintLayerPaintingChildClippingMaskPhase;
+ if (paintInfo.paintingPhase & GraphicsLayerPaintOverflowContents)
+ paintFlags |= PaintLayerPaintingOverflowContents;
+ if (paintInfo.paintingPhase & GraphicsLayerPaintCompositedScroll)
+ paintFlags |= PaintLayerPaintingCompositingScrollingPhase;
+
+ if (paintInfo.isBackgroundLayer)
+ paintFlags |= (PaintLayerPaintingRootBackgroundOnly | PaintLayerPaintingCompositingForegroundPhase); // Need PaintLayerPaintingCompositingForegroundPhase to walk child layers.
+ else if (compositor()->fixedRootBackgroundLayer())
+ paintFlags |= PaintLayerPaintingSkipRootBackground;
+
+ // Note carefully: in theory it is appropriate to invoke context->save() here
+ // and restore the context after painting. For efficiency, we are assuming that
+ // it is equivalent to manually undo this offset translation, which means we are
+ // assuming that the context's space was not affected by the RenderLayer
+ // painting code.
+
+ LayoutSize offset = paintInfo.offsetFromRenderer;
+ context->translate(-offset);
+ LayoutRect relativeClip(clip);
+ relativeClip.move(offset);
+
+ // The dirtyRect is in the coords of the painting root.
+ IntRect dirtyRect = pixelSnappedIntRect(relativeClip);
+ if (!(paintInfo.paintingPhase & GraphicsLayerPaintOverflowContents))
+ dirtyRect.intersect(paintInfo.compositedBounds);
+
+#ifndef NDEBUG
+ paintInfo.renderLayer->renderer()->assertSubtreeIsLaidOut();
+#endif
+
+ if (paintInfo.renderLayer->compositingState() != PaintsIntoGroupedBacking) {
+ // FIXME: GraphicsLayers need a way to split for RenderRegions.
+ LayerPaintingInfo paintingInfo(paintInfo.renderLayer, dirtyRect, PaintBehaviorNormal, LayoutSize());
+ paintInfo.renderLayer->paintLayerContents(context, paintingInfo, paintFlags);
+
+ ASSERT(!paintInfo.isBackgroundLayer || paintFlags & PaintLayerPaintingRootBackgroundOnly);
+
+ if (paintInfo.renderLayer->containsDirtyOverlayScrollbars())
+ paintInfo.renderLayer->paintLayerContents(context, paintingInfo, paintFlags | PaintLayerPaintingOverlayScrollbars);
+ } else {
+ ASSERT(compositor()->layerSquashingEnabled());
+ LayerPaintingInfo paintingInfo(paintInfo.renderLayer, dirtyRect, PaintBehaviorNormal, LayoutSize());
+ paintInfo.renderLayer->paintLayer(context, paintingInfo, paintFlags);
+ }
+
+ ASSERT(!paintInfo.renderLayer->m_usedTransparency);
+
+ // Manually restore the context to its original state by applying the opposite translation.
+ context->translate(offset);
+}
+
+static void paintScrollbar(Scrollbar* scrollbar, GraphicsContext& context, const IntRect& clip)
+{
+ if (!scrollbar)
+ return;
+
+ context.save();
+ const IntRect& scrollbarRect = scrollbar->frameRect();
+ context.translate(-scrollbarRect.x(), -scrollbarRect.y());
+ IntRect transformedClip = clip;
+ transformedClip.moveBy(scrollbarRect.location());
+ scrollbar->paint(&context, transformedClip);
+ context.restore();
+}
+
+// Up-call from compositing layer drawing callback.
+void CompositedLayerMapping::paintContents(const GraphicsLayer* graphicsLayer, GraphicsContext& context, GraphicsLayerPaintingPhase paintingPhase, const IntRect& clip)
+{
+#ifndef NDEBUG
+ if (Page* page = renderer()->frame()->page())
+ page->setIsPainting(true);
+#endif
+ InspectorInstrumentation::willPaint(m_owningLayer->renderer(), graphicsLayer);
+
+ if (graphicsLayer == m_graphicsLayer.get()
+ || graphicsLayer == m_foregroundLayer.get()
+ || graphicsLayer == m_backgroundLayer.get()
+ || graphicsLayer == m_maskLayer.get()
+ || graphicsLayer == m_childClippingMaskLayer.get()
+ || graphicsLayer == m_scrollingContentsLayer.get()) {
+
+ GraphicsLayerPaintInfo paintInfo;
+ paintInfo.renderLayer = m_owningLayer;
+ paintInfo.compositedBounds = compositedBounds();
+ paintInfo.offsetFromRenderer = graphicsLayer->offsetFromRenderer();
+ paintInfo.paintingPhase = paintingPhase;
+ paintInfo.isBackgroundLayer = (graphicsLayer == m_backgroundLayer);
+
+ // We have to use the same root as for hit testing, because both methods can compute and cache clipRects.
+ doPaintTask(paintInfo, &context, clip);
+ } else if (graphicsLayer == m_squashingLayer.get()) {
+ ASSERT(compositor()->layerSquashingEnabled());
+ for (size_t i = 0; i < m_squashedLayers.size(); ++i)
+ doPaintTask(m_squashedLayers[i], &context, clip);
+ } else if (graphicsLayer == layerForHorizontalScrollbar()) {
+ paintScrollbar(m_owningLayer->scrollableArea()->horizontalScrollbar(), context, clip);
+ } else if (graphicsLayer == layerForVerticalScrollbar()) {
+ paintScrollbar(m_owningLayer->scrollableArea()->verticalScrollbar(), context, clip);
+ } else if (graphicsLayer == layerForScrollCorner()) {
+ const IntRect& scrollCornerAndResizer = m_owningLayer->scrollableArea()->scrollCornerAndResizerRect();
+ context.save();
+ context.translate(-scrollCornerAndResizer.x(), -scrollCornerAndResizer.y());
+ IntRect transformedClip = clip;
+ transformedClip.moveBy(scrollCornerAndResizer.location());
+ m_owningLayer->scrollableArea()->paintScrollCorner(&context, IntPoint(), transformedClip);
+ m_owningLayer->scrollableArea()->paintResizer(&context, IntPoint(), transformedClip);
+ context.restore();
+ }
+ InspectorInstrumentation::didPaint(m_owningLayer->renderer(), graphicsLayer, &context, clip);
+#ifndef NDEBUG
+ if (Page* page = renderer()->frame()->page())
+ page->setIsPainting(false);
+#endif
+}
+
+void CompositedLayerMapping::didCommitChangesForLayer(const GraphicsLayer* layer) const
+{
+}
+
+bool CompositedLayerMapping::getCurrentTransform(const GraphicsLayer* graphicsLayer, TransformationMatrix& transform) const
+{
+ if (graphicsLayer != m_graphicsLayer.get())
+ return false;
+
+ if (m_owningLayer->hasTransform()) {
+ transform = m_owningLayer->currentTransform(RenderStyle::ExcludeTransformOrigin);
+ return true;
+ }
+ return false;
+}
+
+bool CompositedLayerMapping::isTrackingRepaints() const
+{
+ GraphicsLayerClient* client = compositor();
+ return client ? client->isTrackingRepaints() : false;
+}
+
+static void collectTrackedRepaintRectsForGraphicsLayer(GraphicsLayer* graphicsLayer, Vector<FloatRect>& rects)
+{
+ if (graphicsLayer)
+ graphicsLayer->collectTrackedRepaintRects(rects);
+}
+
+PassOwnPtr<Vector<FloatRect> > CompositedLayerMapping::collectTrackedRepaintRects() const
+{
+ OwnPtr<Vector<FloatRect> > rects = adoptPtr(new Vector<FloatRect>);
+ collectTrackedRepaintRectsForGraphicsLayer(m_ancestorClippingLayer.get(), *rects);
+ collectTrackedRepaintRectsForGraphicsLayer(m_graphicsLayer.get(), *rects);
+ collectTrackedRepaintRectsForGraphicsLayer(m_childContainmentLayer.get(), *rects);
+ collectTrackedRepaintRectsForGraphicsLayer(m_scrollingLayer.get(), *rects);
+ collectTrackedRepaintRectsForGraphicsLayer(m_scrollingContentsLayer.get(), *rects);
+ collectTrackedRepaintRectsForGraphicsLayer(m_maskLayer.get(), *rects);
+ collectTrackedRepaintRectsForGraphicsLayer(m_childClippingMaskLayer.get(), *rects);
+ collectTrackedRepaintRectsForGraphicsLayer(m_foregroundLayer.get(), *rects);
+ collectTrackedRepaintRectsForGraphicsLayer(m_backgroundLayer.get(), *rects);
+ collectTrackedRepaintRectsForGraphicsLayer(m_layerForHorizontalScrollbar.get(), *rects);
+ collectTrackedRepaintRectsForGraphicsLayer(m_layerForVerticalScrollbar.get(), *rects);
+ collectTrackedRepaintRectsForGraphicsLayer(m_layerForScrollCorner.get(), *rects);
+ return rects.release();
+}
+
+#ifndef NDEBUG
+void CompositedLayerMapping::verifyNotPainting()
+{
+ ASSERT(!renderer()->frame()->page() || !renderer()->frame()->page()->isPainting());
+}
+#endif
+
+bool CompositedLayerMapping::startAnimation(double timeOffset, const CSSAnimationData* anim, const KeyframeList& keyframes)
+{
+ bool hasTransform = renderer()->isBox() && keyframes.containsProperty(CSSPropertyWebkitTransform);
+ IntSize boxSize;
+ if (hasTransform)
+ boxSize = toRenderBox(renderer())->pixelSnappedBorderBoxRect().size();
+ WebAnimations animations(m_animationProvider->startAnimation(timeOffset, anim, keyframes, hasTransform, boxSize));
+ if (animations.isEmpty())
+ return false;
+
+ bool hasOpacity = keyframes.containsProperty(CSSPropertyOpacity);
+ bool hasFilter = keyframes.containsProperty(CSSPropertyWebkitFilter);
+ int animationId = m_animationProvider->getWebAnimationId(keyframes.animationName());
+
+ // Animating only some properties of the animation is not supported. So if the
+ // GraphicsLayer rejects any property of the animation, we have to remove the
+ // animation and return false to indicate un-accelerated animation is required.
+ if (hasTransform) {
+ if (!animations.m_transformAnimation || !m_graphicsLayer->addAnimation(animations.m_transformAnimation.release()))
+ return false;
+ }
+ if (hasOpacity) {
+ if (!animations.m_opacityAnimation || !m_graphicsLayer->addAnimation(animations.m_opacityAnimation.release())) {
+ if (hasTransform)
+ m_graphicsLayer->removeAnimation(animationId);
+ return false;
+ }
+ }
+ if (hasFilter) {
+ if (!animations.m_filterAnimation || !m_graphicsLayer->addAnimation(animations.m_filterAnimation.release())) {
+ if (hasTransform || hasOpacity)
+ m_graphicsLayer->removeAnimation(animationId);
+ return false;
+ }
+ }
+ return true;
+}
+
+void CompositedLayerMapping::animationPaused(double timeOffset, const String& animationName)
+{
+ int animationId = m_animationProvider->getWebAnimationId(animationName);
+ ASSERT(animationId);
+ m_graphicsLayer->pauseAnimation(animationId, timeOffset);
+}
+
+void CompositedLayerMapping::animationFinished(const String& animationName)
+{
+ int animationId = m_animationProvider->getWebAnimationId(animationName);
+ ASSERT(animationId);
+ m_graphicsLayer->removeAnimation(animationId);
+}
+
+bool CompositedLayerMapping::startTransition(double timeOffset, CSSPropertyID property, const RenderStyle* fromStyle, const RenderStyle* toStyle)
+{
+ ASSERT(property != CSSPropertyInvalid);
+ IntSize boxSize;
+ if (property == CSSPropertyWebkitTransform && m_owningLayer->hasTransform()) {
+ ASSERT(renderer()->isBox());
+ boxSize = toRenderBox(renderer())->pixelSnappedBorderBoxRect().size();
+ }
+ float fromOpacity = 0;
+ float toOpacity = 0;
+ if (property == CSSPropertyOpacity) {
+ fromOpacity = compositingOpacity(fromStyle->opacity());
+ toOpacity = compositingOpacity(toStyle->opacity());
+ }
+
+ // Although KeyframeAnimation can have multiple properties of the animation, ImplicitAnimation (= Transition) has only one animation property.
+ WebAnimations animations(m_animationProvider->startTransition(timeOffset, property, fromStyle,
+ toStyle, m_owningLayer->hasTransform(), m_owningLayer->hasFilter(), boxSize, fromOpacity, toOpacity));
+ if (animations.m_transformAnimation && m_graphicsLayer->addAnimation(animations.m_transformAnimation.release())) {
+ // To ensure that the correct transform is visible when the animation ends, also set the final transform.
+ updateTransform(toStyle);
+ return true;
+ }
+ if (animations.m_opacityAnimation && m_graphicsLayer->addAnimation(animations.m_opacityAnimation.release())) {
+ // To ensure that the correct opacity is visible when the animation ends, also set the final opacity.
+ updateOpacity(toStyle);
+ return true;
+ }
+ if (animations.m_filterAnimation && m_graphicsLayer->addAnimation(animations.m_filterAnimation.release())) {
+ // To ensure that the correct filter is visible when the animation ends, also set the final filter.
+ updateFilters(toStyle);
+ return true;
+ }
+
+ return false;
+}
+
+void CompositedLayerMapping::transitionPaused(double timeOffset, CSSPropertyID property)
+{
+ int animationId = m_animationProvider->getWebAnimationId(property);
+ ASSERT(animationId);
+ m_graphicsLayer->pauseAnimation(animationId, timeOffset);
+}
+
+void CompositedLayerMapping::transitionFinished(CSSPropertyID property)
+{
+ int animationId = m_animationProvider->getWebAnimationId(property);
+ ASSERT(animationId);
+ m_graphicsLayer->removeAnimation(animationId);
+}
+
+void CompositedLayerMapping::notifyAnimationStarted(const GraphicsLayer*, double wallClockTime, double monotonicTime)
+{
+ if (RuntimeEnabledFeatures::webAnimationsCSSEnabled())
+ renderer()->node()->document().cssPendingAnimations().notifyCompositorAnimationStarted(monotonicTime);
+ else
+ renderer()->animation().notifyAnimationStarted(renderer(), wallClockTime);
+}
+
+IntRect CompositedLayerMapping::compositedBounds() const
+{
+ return m_compositedBounds;
+}
+
+void CompositedLayerMapping::setCompositedBounds(const IntRect& bounds)
+{
+ m_compositedBounds = bounds;
+}
+
+void CompositedLayerMapping::addRenderLayerToSquashingGraphicsLayer(RenderLayer* layer, IntSize offsetFromTargetBacking, size_t nextSquashedLayerIndex)
+{
+ ASSERT(compositor()->layerSquashingEnabled());
+
+ GraphicsLayerPaintInfo paintInfo;
+ paintInfo.renderLayer = layer;
+ // NOTE: composited bounds are updated elsewhere
+ // NOTE: offsetFromRenderer is updated elsewhere
+ paintInfo.offsetFromBackingRoot = offsetFromTargetBacking;
+ paintInfo.paintingPhase = GraphicsLayerPaintAllWithOverflowClip;
+ paintInfo.isBackgroundLayer = false;
+
+ // Change tracking on squashing layers: at the first sign of something changed, just invalidate the layer.
+ // FIXME: Perhaps we can find a tighter more clever mechanism later.
+ if (nextSquashedLayerIndex < m_squashedLayers.size()) {
+ if (m_squashedLayers[nextSquashedLayerIndex].renderLayer != layer) {
+ m_squashedLayers[nextSquashedLayerIndex] = paintInfo;
+ if (m_squashingLayer)
+ m_squashingLayer->setNeedsDisplay();
+ }
+ } else {
+ m_squashedLayers.append(paintInfo);
+ if (m_squashingLayer)
+ m_squashingLayer->setNeedsDisplay();
+ }
+ layer->setGroupedMapping(this);
+}
+
+void CompositedLayerMapping::finishAccumulatingSquashingLayers(size_t nextSquashedLayerIndex)
+{
+ ASSERT(compositor()->layerSquashingEnabled());
+
+ // Any additional squashed RenderLayers in the array no longer exist, and removing invalidates the squashingLayer contents.
+ if (nextSquashedLayerIndex < m_squashedLayers.size()) {
+ m_squashedLayers.remove(nextSquashedLayerIndex, m_squashedLayers.size() - nextSquashedLayerIndex);
+ if (m_squashingLayer)
+ m_squashingLayer->setNeedsDisplay();
+ }
+}
+
+CompositingLayerType CompositedLayerMapping::compositingLayerType() const
+{
+ if (m_graphicsLayer->hasContentsLayer())
+ return MediaCompositingLayer;
+
+ if (m_graphicsLayer->drawsContent())
+ return NormalCompositingLayer;
+
+ return ContainerCompositingLayer;
+}
+
+double CompositedLayerMapping::backingStoreMemoryEstimate() const
+{
+ double backingMemory;
+
+ // m_ancestorClippingLayer and m_childContainmentLayer are just used for masking or containment, so have no backing.
+ backingMemory = m_graphicsLayer->backingStoreMemoryEstimate();
+ if (m_foregroundLayer)
+ backingMemory += m_foregroundLayer->backingStoreMemoryEstimate();
+ if (m_backgroundLayer)
+ backingMemory += m_backgroundLayer->backingStoreMemoryEstimate();
+ if (m_maskLayer)
+ backingMemory += m_maskLayer->backingStoreMemoryEstimate();
+ if (m_childClippingMaskLayer)
+ backingMemory += m_childClippingMaskLayer->backingStoreMemoryEstimate();
+
+ if (m_scrollingContentsLayer)
+ backingMemory += m_scrollingContentsLayer->backingStoreMemoryEstimate();
+
+ if (m_layerForHorizontalScrollbar)
+ backingMemory += m_layerForHorizontalScrollbar->backingStoreMemoryEstimate();
+
+ if (m_layerForVerticalScrollbar)
+ backingMemory += m_layerForVerticalScrollbar->backingStoreMemoryEstimate();
+
+ if (m_layerForScrollCorner)
+ backingMemory += m_layerForScrollCorner->backingStoreMemoryEstimate();
+
+ return backingMemory;
+}
+
+String CompositedLayerMapping::debugName(const GraphicsLayer* graphicsLayer)
+{
+ String name;
+ if (graphicsLayer == m_graphicsLayer.get()) {
+ name = m_owningLayer->debugName();
+ } else if (graphicsLayer == m_ancestorClippingLayer.get()) {
+ name = "Ancestor Clipping Layer";
+ } else if (graphicsLayer == m_foregroundLayer.get()) {
+ name = m_owningLayer->debugName() + " (foreground) Layer";
+ } else if (graphicsLayer == m_backgroundLayer.get()) {
+ name = m_owningLayer->debugName() + " (background) Layer";
+ } else if (graphicsLayer == m_childContainmentLayer.get()) {
+ name = "Child Containment Layer";
+ } else if (graphicsLayer == m_maskLayer.get()) {
+ name = "Mask Layer";
+ } else if (graphicsLayer == m_childClippingMaskLayer.get()) {
+ name = "Child Clipping Mask Layer";
+ } else if (graphicsLayer == m_layerForHorizontalScrollbar.get()) {
+ name = "Horizontal Scrollbar Layer";
+ } else if (graphicsLayer == m_layerForVerticalScrollbar.get()) {
+ name = "Vertical Scrollbar Layer";
+ } else if (graphicsLayer == m_layerForScrollCorner.get()) {
+ name = "Scroll Corner Layer";
+ } else if (graphicsLayer == m_scrollingLayer.get()) {
+ name = "Scrolling Layer";
+ } else if (graphicsLayer == m_scrollingContentsLayer.get()) {
+ name = "Scrolling Contents Layer";
+ } else {
+ ASSERT_NOT_REACHED();
+ }
+
+ return name;
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/CompositedLayerMapping.h b/chromium/third_party/WebKit/Source/core/rendering/CompositedLayerMapping.h
new file mode 100644
index 00000000000..b0f85e44d0e
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/rendering/CompositedLayerMapping.h
@@ -0,0 +1,359 @@
+/*
+ * Copyright (C) 2009, 2010, 2011 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef CompositedLayerMapping_h
+#define CompositedLayerMapping_h
+
+#include "core/rendering/RenderLayer.h"
+#include "platform/geometry/FloatPoint.h"
+#include "platform/geometry/FloatPoint3D.h"
+#include "platform/graphics/GraphicsLayer.h"
+#include "platform/graphics/GraphicsLayerClient.h"
+#include "platform/transforms/TransformationMatrix.h"
+
+namespace WebCore {
+
+class KeyframeList;
+class RenderLayerCompositor;
+class WebAnimationProvider;
+
+enum CompositingLayerType {
+ NormalCompositingLayer, // non-tiled layer with backing store
+ MediaCompositingLayer, // layer that contains an image, video, webGL or plugin
+ ContainerCompositingLayer // layer with no backing store
+};
+
+
+// A GraphicsLayerPaintInfo contains all the info needed to paint a partial subtree of RenderLayers into a GraphicsLayer.
+struct GraphicsLayerPaintInfo {
+ RenderLayer* renderLayer;
+
+ IntRect compositedBounds;
+
+ // A temporary offset used for squashing layers, when the origin of the
+ // squashing layer is not yet known.
+ IntSize offsetFromBackingRoot;
+
+ IntSize offsetFromRenderer;
+
+ GraphicsLayerPaintingPhase paintingPhase;
+
+ bool isBackgroundLayer;
+};
+
+// CompositedLayerMapping keeps track of how RenderLayers of the render tree correspond to
+// GraphicsLayers of the composited layer tree. Each instance of CompositedLayerMapping
+// manages a small cluster of GraphicsLayers and the references to which RenderLayers
+// and paint phases contribute to each GraphicsLayer.
+//
+// Currently (Oct. 2013) there is one CompositedLayerMapping for each RenderLayer,
+// but this is likely to evolve soon.
+class CompositedLayerMapping : public GraphicsLayerClient {
+ WTF_MAKE_NONCOPYABLE(CompositedLayerMapping); WTF_MAKE_FAST_ALLOCATED;
+public:
+ explicit CompositedLayerMapping(RenderLayer*);
+ ~CompositedLayerMapping();
+
+ RenderLayer* owningLayer() const { return m_owningLayer; }
+
+ enum UpdateAfterLayoutFlag {
+ CompositingChildrenOnly = 1 << 0,
+ NeedsFullRepaint = 1 << 1,
+ IsUpdateRoot = 1 << 2
+ };
+ typedef unsigned UpdateAfterLayoutFlags;
+ void updateAfterLayout(UpdateAfterLayoutFlags);
+
+ // Returns true if layer configuration changed.
+ bool updateGraphicsLayerConfiguration();
+ // Update graphics layer position and bounds.
+ void updateGraphicsLayerGeometry(); // make private
+ // Update whether layer needs blending.
+ void updateContentsOpaque();
+
+ GraphicsLayer* mainGraphicsLayer() const { return m_graphicsLayer.get(); }
+
+ // Layer to clip children
+ bool hasClippingLayer() const { return m_childContainmentLayer; }
+ GraphicsLayer* clippingLayer() const { return m_childContainmentLayer.get(); }
+
+ // Layer to get clipped by ancestor
+ bool hasAncestorClippingLayer() const { return m_ancestorClippingLayer; }
+ GraphicsLayer* ancestorClippingLayer() const { return m_ancestorClippingLayer.get(); }
+
+ bool hasContentsLayer() const { return m_foregroundLayer; }
+ GraphicsLayer* foregroundLayer() const { return m_foregroundLayer.get(); }
+
+ GraphicsLayer* backgroundLayer() const { return m_backgroundLayer.get(); }
+ bool backgroundLayerPaintsFixedRootBackground() const { return m_backgroundLayerPaintsFixedRootBackground; }
+
+ bool hasScrollingLayer() const { return m_scrollingLayer; }
+ GraphicsLayer* scrollingLayer() const { return m_scrollingLayer.get(); }
+ GraphicsLayer* scrollingContentsLayer() const { return m_scrollingContentsLayer.get(); }
+
+ bool hasMaskLayer() const { return m_maskLayer; }
+ bool hasChildClippingMaskLayer() const { return m_childClippingMaskLayer; }
+
+ GraphicsLayer* parentForSublayers() const;
+ GraphicsLayer* childForSuperlayers() const;
+
+ GraphicsLayer* squashingLayer() const { return m_squashingLayer.get(); }
+
+ // Returns true for a composited layer that has no backing store of its own, so
+ // paints into some ancestor layer.
+ bool paintsIntoCompositedAncestor() const { return !(m_requiresOwnBackingStoreForAncestorReasons || m_requiresOwnBackingStoreForIntrinsicReasons); }
+
+ // Updates whether a backing store is needed based on the layer's compositing ancestor's
+ // properties; returns true if the need for a backing store for ancestor reasons changed.
+ bool updateRequiresOwnBackingStoreForAncestorReasons(const RenderLayer* compositingAncestor);
+
+ // Updates whether a backing store is needed for intrinsic reasons (that is, based on the
+ // layer's own properties or compositing reasons); returns true if the intrinsic need for
+ // a backing store changed.
+ bool updateRequiresOwnBackingStoreForIntrinsicReasons();
+
+ void setContentsNeedDisplay();
+ // r is in the coordinate space of the layer's render object
+ void setContentsNeedDisplayInRect(const IntRect&);
+
+ // Notification from the renderer that its content changed.
+ void contentChanged(ContentChangeType);
+
+ // Interface to start, finish, suspend and resume animations and transitions
+ bool startTransition(double, CSSPropertyID, const RenderStyle* fromStyle, const RenderStyle* toStyle);
+ void transitionPaused(double timeOffset, CSSPropertyID);
+ void transitionFinished(CSSPropertyID);
+
+ bool startAnimation(double timeOffset, const CSSAnimationData*, const KeyframeList& keyframes);
+ void animationPaused(double timeOffset, const String& name);
+ void animationFinished(const String& name);
+
+ IntRect compositedBounds() const;
+ void setCompositedBounds(const IntRect&);
+ void updateCompositedBounds();
+
+ void updateAfterWidgetResize();
+ void positionOverflowControlsLayers(const IntSize& offsetFromRoot);
+ bool hasUnpositionedOverflowControlsLayers() const;
+
+ void addRenderLayerToSquashingGraphicsLayer(RenderLayer*, IntSize offsetFromTargetBacking, size_t nextSquashedLayerIndex);
+ void finishAccumulatingSquashingLayers(size_t nextSquashedLayerIndex);
+
+ // GraphicsLayerClient interface
+ virtual void notifyAnimationStarted(const GraphicsLayer*, double wallClockTime, double monotonicTime) OVERRIDE;
+
+ virtual void paintContents(const GraphicsLayer*, GraphicsContext&, GraphicsLayerPaintingPhase, const IntRect& clip) OVERRIDE;
+
+ virtual void didCommitChangesForLayer(const GraphicsLayer*) const OVERRIDE;
+ virtual bool getCurrentTransform(const GraphicsLayer*, TransformationMatrix&) const OVERRIDE;
+
+ virtual bool isTrackingRepaints() const OVERRIDE;
+
+ PassOwnPtr<Vector<FloatRect> > collectTrackedRepaintRects() const;
+
+#ifndef NDEBUG
+ virtual void verifyNotPainting();
+#endif
+
+ IntRect contentsBox() const;
+ IntRect backgroundBox() const;
+
+ // For informative purposes only.
+ CompositingLayerType compositingLayerType() const;
+
+ GraphicsLayer* layerForHorizontalScrollbar() const { return m_layerForHorizontalScrollbar.get(); }
+ GraphicsLayer* layerForVerticalScrollbar() const { return m_layerForVerticalScrollbar.get(); }
+ GraphicsLayer* layerForScrollCorner() const { return m_layerForScrollCorner.get(); }
+
+ void updateFilters(const RenderStyle*);
+ bool canCompositeFilters() const { return m_canCompositeFilters; }
+
+ // Return an estimate of the backing store area (in pixels) allocated by this object's GraphicsLayers.
+ double backingStoreMemoryEstimate() const;
+
+ void setBlendMode(blink::WebBlendMode);
+
+ virtual String debugName(const GraphicsLayer*) OVERRIDE;
+
+private:
+ void createPrimaryGraphicsLayer();
+ void destroyGraphicsLayers();
+
+ PassOwnPtr<GraphicsLayer> createGraphicsLayer(CompositingReasons);
+
+ RenderLayerModelObject* renderer() const { return m_owningLayer->renderer(); }
+ RenderLayerCompositor* compositor() const { return m_owningLayer->compositor(); }
+
+ void updateInternalHierarchy();
+ bool updateClippingLayers(bool needsAncestorClip, bool needsDescendantClip);
+ bool updateOverflowControlsLayers(bool needsHorizontalScrollbarLayer, bool needsVerticalScrollbarLayer, bool needsScrollCornerLayer);
+ bool updateForegroundLayer(bool needsForegroundLayer);
+ bool updateBackgroundLayer(bool needsBackgroundLayer);
+ bool updateMaskLayer(bool needsMaskLayer);
+ bool updateClippingMaskLayers(bool needsChildClippingMaskLayer);
+ bool requiresHorizontalScrollbarLayer() const { return m_owningLayer->scrollableArea() && m_owningLayer->scrollableArea()->horizontalScrollbar(); }
+ bool requiresVerticalScrollbarLayer() const { return m_owningLayer->scrollableArea() && m_owningLayer->scrollableArea()->verticalScrollbar(); }
+ bool requiresScrollCornerLayer() const { return m_owningLayer->scrollableArea() && !m_owningLayer->scrollableArea()->scrollCornerAndResizerRect().isEmpty(); }
+ bool updateScrollingLayers(bool scrollingLayers);
+ void updateScrollParent(RenderLayer*);
+ void updateClipParent(RenderLayer*);
+ bool updateSquashingLayers(bool needsSquashingLayers);
+ void updateDrawsContent(bool isSimpleContainer);
+ void registerScrollingLayers();
+
+ void setBackgroundLayerPaintsFixedRootBackground(bool);
+
+ GraphicsLayerPaintingPhase paintingPhaseForPrimaryLayer() const;
+
+ IntSize contentOffsetInCompostingLayer() const;
+ // Result is transform origin in pixels.
+ FloatPoint3D computeTransformOrigin(const IntRect& borderBox) const;
+ // Result is perspective origin in pixels.
+ FloatPoint computePerspectiveOrigin(const IntRect& borderBox) const;
+
+ void updateOpacity(const RenderStyle*);
+ void updateTransform(const RenderStyle*);
+ void updateLayerBlendMode(const RenderStyle*);
+ void updateIsRootForIsolatedGroup();
+ // Return the opacity value that this layer should use for compositing.
+ float compositingOpacity(float rendererOpacity) const;
+
+ bool isMainFrameRenderViewLayer() const;
+
+ bool paintsBoxDecorations() const;
+ bool paintsChildren() const;
+
+ // Returns true if this compositing layer has no visible content.
+ bool isSimpleContainerCompositingLayer() const;
+ // Returns true if this layer has content that needs to be rendered by painting into the backing store.
+ bool containsPaintedContent(bool isSimpleContainer) const;
+ // Returns true if the RenderLayer just contains an image that we can composite directly.
+ bool isDirectlyCompositedImage() const;
+ void updateImageContents();
+
+ Color rendererBackgroundColor() const;
+ void updateBackgroundColor(bool isSimpleContainer);
+ void updateContentsRect(bool isSimpleContainer);
+
+ void updateCompositingReasons();
+
+ bool hasVisibleNonCompositingDescendantLayers() const;
+
+ bool shouldClipCompositedBounds() const;
+
+ void paintsIntoCompositedAncestorChanged();
+
+ void doPaintTask(GraphicsLayerPaintInfo&, GraphicsContext*, const IntRect& clip);
+
+ RenderLayer* m_owningLayer;
+
+ // The hierarchy of layers that is maintained by the CompositedLayerMapping looks like this:
+ //
+ // + m_ancestorClippingLayer [OPTIONAL]
+ // + m_graphicsLayer
+ // + m_childContainmentLayer [OPTIONAL] <-OR-> m_scrollingLayer [OPTIONAL]
+ // + m_scrollingContentsLayer [OPTIONAL]
+ //
+ // We need an ancestor clipping layer if our clipping ancestor is not our ancestor in the
+ // clipping tree. Here's what that might look like.
+ //
+ // Let A = the clipping ancestor,
+ // B = the clip descendant, and
+ // SC = the stacking context that is the ancestor of A and B in the stacking tree.
+ //
+ // SC
+ // + A = m_graphicsLayer
+ // | + m_childContainmentLayer
+ // | + ...
+ // ...
+ // |
+ // + B = m_ancestorClippingLayer [+]
+ // + m_graphicsLayer
+ // + ...
+ //
+ // In this case B is clipped by another layer that doesn't happen to be its ancestor: A.
+ // So we create an ancestor clipping layer for B, [+], which ensures that B is clipped
+ // as if it had been A's descendant.
+ OwnPtr<GraphicsLayer> m_ancestorClippingLayer; // Only used if we are clipped by an ancestor which is not a stacking context.
+ OwnPtr<GraphicsLayer> m_graphicsLayer;
+ OwnPtr<GraphicsLayer> m_childContainmentLayer; // Only used if we have clipping on a stacking context with compositing children.
+ OwnPtr<GraphicsLayer> m_scrollingLayer; // Only used if the layer is using composited scrolling.
+ OwnPtr<GraphicsLayer> m_scrollingContentsLayer; // Only used if the layer is using composited scrolling.
+
+ // This layer is also added to the hierarchy by the RLB, but in a different way than
+ // the layers above. It's added to m_graphicsLayer as its mask layer (naturally) if
+ // we have a mask, and isn't part of the typical hierarchy (it has no children).
+ OwnPtr<GraphicsLayer> m_maskLayer; // Only used if we have a mask.
+ OwnPtr<GraphicsLayer> m_childClippingMaskLayer; // Only used if we have to clip child layers or accelerated contents with border radius or clip-path.
+
+ // There are two other (optional) layers whose painting is managed by the CompositedLayerMapping,
+ // but whose position in the hierarchy is maintained by the RenderLayerCompositor. These
+ // are the foreground and background layers. The foreground layer exists if we have composited
+ // descendants with negative z-order. We need the extra layer in this case because the layer
+ // needs to draw both below (for the background, say) and above (for the normal flow content, say)
+ // the negative z-order descendants and this is impossible with a single layer. The RLC handles
+ // inserting m_foregroundLayer in the correct position in our descendant list for us (right after
+ // the neg z-order dsecendants).
+ //
+ // The background layer is only created if this is the root layer and our background is entirely
+ // fixed. In this case we want to put the background in a separate composited layer so that when
+ // we scroll, we don't have to re-raster the background into position. This layer is also inserted
+ // into the tree by the RLC as it gets a special home. This layer becomes a descendant of the
+ // frame clipping layer. That is:
+ // ...
+ // + frame clipping layer
+ // + m_backgroundLayer
+ // + frame scrolling layer
+ // + root content layer
+ //
+ // With the hierarchy set up like this, the root content layer is able to scroll without affecting
+ // the background layer (or repainting).
+ OwnPtr<GraphicsLayer> m_foregroundLayer; // Only used in cases where we need to draw the foreground separately.
+ OwnPtr<GraphicsLayer> m_backgroundLayer; // Only used in cases where we need to draw the background separately.
+
+ OwnPtr<GraphicsLayer> m_layerForHorizontalScrollbar;
+ OwnPtr<GraphicsLayer> m_layerForVerticalScrollbar;
+ OwnPtr<GraphicsLayer> m_layerForScrollCorner;
+
+ OwnPtr<WebAnimationProvider> m_animationProvider;
+
+ OwnPtr<GraphicsLayer> m_squashingContainmentLayer; // Only used if any squashed layers exist, to contain the squashed layers as siblings to the rest of the GraphicsLayer tree chunk.
+ OwnPtr<GraphicsLayer> m_squashingLayer; // Only used if any squashed layers exist, this is the backing that squashed layers paint into.
+ Vector<GraphicsLayerPaintInfo> m_squashedLayers;
+
+ IntRect m_compositedBounds;
+
+ bool m_artificiallyInflatedBounds; // bounds had to be made non-zero to make transform-origin work
+ bool m_boundsConstrainedByClipping;
+ bool m_isMainFrameRenderViewLayer;
+ bool m_requiresOwnBackingStoreForIntrinsicReasons;
+ bool m_requiresOwnBackingStoreForAncestorReasons;
+ bool m_canCompositeFilters;
+ bool m_backgroundLayerPaintsFixedRootBackground;
+};
+
+} // namespace WebCore
+
+#endif // CompositedLayerMapping_h
diff --git a/chromium/third_party/WebKit/Source/core/rendering/CompositedLayerMappingPtr.h b/chromium/third_party/WebKit/Source/core/rendering/CompositedLayerMappingPtr.h
new file mode 100644
index 00000000000..27cb68581d5
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/rendering/CompositedLayerMappingPtr.h
@@ -0,0 +1,39 @@
+// Copyright 2013 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CompositedLayerMappingPtr_h
+#define CompositedLayerMappingPtr_h
+
+#include "wtf/Assertions.h"
+
+namespace WebCore {
+
+class CompositedLayerMapping;
+
+class CompositedLayerMappingPtr {
+public:
+ CompositedLayerMappingPtr(CompositedLayerMapping* mapping)
+ : m_mapping(mapping)
+ {
+ }
+
+ CompositedLayerMapping& operator*() const
+ {
+ ASSERT(m_mapping);
+ return *m_mapping;
+ }
+
+ CompositedLayerMapping* operator->() const
+ {
+ ASSERT(m_mapping);
+ return m_mapping;
+ }
+
+private:
+ CompositedLayerMapping* m_mapping;
+};
+
+} // namespace WebCore
+
+#endif // CompositedLayerMappingPtr_h
diff --git a/chromium/third_party/WebKit/Source/core/rendering/CompositingReasons.h b/chromium/third_party/WebKit/Source/core/rendering/CompositingReasons.h
index 47713ee962b..8b023a724f8 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/CompositingReasons.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/CompositingReasons.h
@@ -24,7 +24,6 @@ const uint64_t CompositingReasonFilters = UINT64_
const uint64_t CompositingReasonPositionFixed = UINT64_C(1) << 8;
const uint64_t CompositingReasonPositionSticky = UINT64_C(1) << 9;
const uint64_t CompositingReasonOverflowScrollingTouch = UINT64_C(1) << 10;
-const uint64_t CompositingReasonBlending = UINT64_C(1) << 11;
// Overlap reasons that require knowing what's behind you in paint-order before knowing the answer
const uint64_t CompositingReasonAssumedOverlap = UINT64_C(1) << 12;
@@ -47,7 +46,7 @@ const uint64_t CompositingReasonReflectionOfCompositedParent = UINT64_
// a layer if anything else in the subtree is composited.
const uint64_t CompositingReasonRoot = UINT64_C(1) << 25;
-// RenderLayerBacking internal hierarchy reasons
+// CompositedLayerMapping internal hierarchy reasons
const uint64_t CompositingReasonLayerForClip = UINT64_C(1) << 26;
const uint64_t CompositingReasonLayerForScrollbar = UINT64_C(1) << 27;
const uint64_t CompositingReasonLayerForScrollingContainer = UINT64_C(1) << 28;
@@ -61,8 +60,43 @@ const uint64_t CompositingReasonOverflowScrollingParent = UINT64_
const uint64_t CompositingReasonOutOfFlowClipping = UINT64_C(1) << 33;
const uint64_t CompositingReasonLayerForVideoOverlay = UINT64_C(1) << 34;
+const uint64_t CompositingReasonIsolateCompositedDescendants = UINT64_C(1) << 35;
// Note: if you add more reasons here, you will need to update WebCompositingReasons as well.
+
+// Various combinations of compositing reasons are defined here also, for more intutive and faster bitwise logic.
+const uint64_t CompositingReasonComboAllDirectReasons =
+ CompositingReason3DTransform
+ | CompositingReasonVideo
+ | CompositingReasonCanvas
+ | CompositingReasonPlugin
+ | CompositingReasonIFrame
+ | CompositingReasonBackfaceVisibilityHidden
+ | CompositingReasonAnimation
+ | CompositingReasonFilters
+ | CompositingReasonPositionFixed
+ | CompositingReasonPositionSticky
+ | CompositingReasonOverflowScrollingTouch
+ | CompositingReasonOverflowScrollingParent
+ | CompositingReasonOutOfFlowClipping;
+
+const uint64_t CompositingReasonComboReasonsThatRequireOwnBacking =
+ CompositingReasonComboAllDirectReasons
+ | CompositingReasonOverlap
+ | CompositingReasonAssumedOverlap
+ | CompositingReasonNegativeZIndexChildren
+ | CompositingReasonTransformWithCompositedDescendants
+ | CompositingReasonOpacityWithCompositedDescendants
+ | CompositingReasonMaskWithCompositedDescendants
+ | CompositingReasonFilterWithCompositedDescendants
+ | CompositingReasonBlendingWithCompositedDescendants
+ | CompositingReasonIsolateCompositedDescendants
+ | CompositingReasonPreserve3D; // preserve-3d has to create backing store to ensure that 3d-transformed elements intersect.
+
+const uint64_t CompositingReasonComboAllOverlapReasons =
+ CompositingReasonOverlap
+ | CompositingReasonAssumedOverlap;
+
typedef uint64_t CompositingReasons;
diff --git a/chromium/third_party/WebKit/Source/core/rendering/CompositingState.h b/chromium/third_party/WebKit/Source/core/rendering/CompositingState.h
new file mode 100644
index 00000000000..3873871f304
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/rendering/CompositingState.h
@@ -0,0 +1,29 @@
+// Copyright 2013 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CompositingState_h
+#define CompositingState_h
+
+namespace WebCore {
+
+enum CompositingState {
+ // The layer paints into its enclosing composited ancestor.
+ NotComposited = 0,
+
+ // The layer is composited, but its contents still paint into enclosing composited ancestor.
+ // In this state, repaint invalidations must be sent to the enclosing composited ancestor.
+ // Typically this happens when a layer's properties need to be represented in the compositor
+ // output data structures, but it doesn't actually have any other reasons to be composited.
+ HasOwnBackingButPaintsIntoAncestor = 1,
+
+ PaintsIntoOwnBacking = 2,
+
+ // In this state, the RenderLayer subtree paints into a backing that is shared by
+ // several RenderLayer subtrees.
+ PaintsIntoGroupedBacking = 3
+};
+
+} // namespace WebCore
+
+#endif // CompositingState_h
diff --git a/chromium/third_party/WebKit/Source/core/rendering/CounterNode.cpp b/chromium/third_party/WebKit/Source/core/rendering/CounterNode.cpp
index 53957f81e7a..87beb7fd627 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/CounterNode.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/CounterNode.cpp
@@ -30,7 +30,7 @@
namespace WebCore {
-CounterNode::CounterNode(RenderObject* o, bool hasResetType, int value)
+CounterNode::CounterNode(RenderObject& o, bool hasResetType, int value)
: m_hasResetType(hasResetType)
, m_value(value)
, m_countInParent(0)
@@ -92,7 +92,7 @@ CounterNode::~CounterNode()
resetRenderers();
}
-PassRefPtr<CounterNode> CounterNode::create(RenderObject* owner, bool hasResetType, int value)
+PassRefPtr<CounterNode> CounterNode::create(RenderObject& owner, bool hasResetType, int value)
{
return adoptRef(new CounterNode(owner, hasResetType, value));
}
@@ -367,7 +367,7 @@ static void showTreeAndMark(const CounterNode* node)
fprintf(stderr, "%p %s: %d %d P:%p PS:%p NS:%p R:%p\n",
current, current->actsAsReset() ? "reset____" : "increment", current->value(),
current->countInParent(), current->parent(), current->previousSibling(),
- current->nextSibling(), current->owner());
+ current->nextSibling(), &current->owner());
}
fflush(stderr);
}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/CounterNode.h b/chromium/third_party/WebKit/Source/core/rendering/CounterNode.h
index c467036d091..baaeed3aa29 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/CounterNode.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/CounterNode.h
@@ -42,13 +42,13 @@ class RenderCounter;
class CounterNode : public RefCounted<CounterNode> {
public:
- static PassRefPtr<CounterNode> create(RenderObject*, bool isReset, int value);
+ static PassRefPtr<CounterNode> create(RenderObject&, bool isReset, int value);
~CounterNode();
bool actsAsReset() const { return m_hasResetType || !m_parent; }
bool hasResetType() const { return m_hasResetType; }
int value() const { return m_value; }
int countInParent() const { return m_countInParent; }
- RenderObject* owner() const { return m_owner; }
+ RenderObject& owner() const { return m_owner; }
void addRenderer(RenderCounter*);
void removeRenderer(RenderCounter*);
@@ -71,7 +71,7 @@ public:
void removeChild(CounterNode*);
private:
- CounterNode(RenderObject*, bool isReset, int value);
+ CounterNode(RenderObject&, bool isReset, int value);
int computeCountInParent() const;
// Invalidates the text in the renderer of this counter, if any,
// and in the renderers of all descendants of this counter, if any.
@@ -81,7 +81,7 @@ private:
bool m_hasResetType;
int m_value;
int m_countInParent;
- RenderObject* m_owner;
+ RenderObject& m_owner;
RenderCounter* m_rootRenderer;
CounterNode* m_parent;
diff --git a/chromium/third_party/WebKit/Source/core/rendering/EllipsisBox.cpp b/chromium/third_party/WebKit/Source/core/rendering/EllipsisBox.cpp
index c5cb7cf373b..9051eb20342 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/EllipsisBox.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/EllipsisBox.cpp
@@ -20,16 +20,16 @@
#include "config.h"
#include "core/rendering/EllipsisBox.h"
-#include "core/platform/graphics/DrawLooper.h"
-#include "core/platform/graphics/Font.h"
-#include "core/platform/graphics/GraphicsContextStateSaver.h"
-#include "core/platform/graphics/TextRun.h"
#include "core/rendering/HitTestResult.h"
#include "core/rendering/InlineTextBox.h"
#include "core/rendering/PaintInfo.h"
-#include "core/rendering/RenderBlock.h"
+#include "core/rendering/RenderBlockFlow.h"
#include "core/rendering/RootInlineBox.h"
-#include "core/rendering/style/ShadowData.h"
+#include "core/rendering/style/ShadowList.h"
+#include "platform/fonts/Font.h"
+#include "platform/graphics/DrawLooper.h"
+#include "platform/graphics/GraphicsContextStateSaver.h"
+#include "platform/text/TextRun.h"
namespace WebCore {
@@ -37,14 +37,25 @@ void EllipsisBox::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset, La
{
GraphicsContext* context = paintInfo.context;
RenderStyle* style = m_renderer->style(isFirstLineStyle());
+
+ const Font& font = style->font();
+ FloatPoint boxOrigin = locationIncludingFlipping();
+ LayoutPoint adjustedPaintOffset = paintOffset;
+ if (!isHorizontal())
+ adjustedPaintOffset.move(0, -virtualLogicalHeight());
+ boxOrigin.move(adjustedPaintOffset.x(), adjustedPaintOffset.y());
+ FloatRect boxRect(boxOrigin, LayoutSize(logicalWidth(), virtualLogicalHeight()));
+ GraphicsContextStateSaver stateSaver(*context);
+ if (!isHorizontal())
+ context->concatCTM(InlineTextBox::rotation(boxRect, InlineTextBox::Clockwise));
+ FloatPoint textOrigin = FloatPoint(boxOrigin.x(), boxOrigin.y() + font.fontMetrics().ascent());
+
Color styleTextColor = m_renderer->resolveColor(style, CSSPropertyWebkitTextFillColor);
if (styleTextColor != context->fillColor())
context->setFillColor(styleTextColor);
- Color textColor = styleTextColor;
- const Font& font = style->font();
if (selectionState() != RenderObject::SelectionNone) {
- paintSelection(context, paintOffset, style, font);
+ paintSelection(context, boxOrigin, style, font);
// Select the correct color for painting the text.
Color foreground = paintInfo.forceBlackText() ? Color::black : renderer()->selectionForegroundColor();
@@ -53,27 +64,24 @@ void EllipsisBox::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset, La
}
// Text shadows are disabled when printing. http://crbug.com/258321
- const ShadowData* shadow = context->printing() ? 0 : style->textShadow();
- bool hasShadow = shadow;
+ const ShadowList* shadowList = context->printing() ? 0 : style->textShadow();
+ bool hasShadow = shadowList;
if (hasShadow) {
DrawLooper drawLooper;
- do {
- int shadowX = isHorizontal() ? shadow->x() : shadow->y();
- int shadowY = isHorizontal() ? shadow->y() : -shadow->x();
+ for (size_t i = shadowList->shadows().size(); i--; ) {
+ const ShadowData& shadow = shadowList->shadows()[i];
+ int shadowX = isHorizontal() ? shadow.x() : shadow.y();
+ int shadowY = isHorizontal() ? shadow.y() : -shadow.x();
FloatSize offset(shadowX, shadowY);
- drawLooper.addShadow(offset, shadow->blur(), m_renderer->resolveColor(shadow->color()),
+ drawLooper.addShadow(offset, shadow.blur(), m_renderer->resolveColor(shadow.color()),
DrawLooper::ShadowRespectsTransforms, DrawLooper::ShadowIgnoresAlpha);
- } while ((shadow = shadow->next()));
+ }
drawLooper.addUnmodifiedContent();
context->setDrawLooper(drawLooper);
}
// FIXME: Why is this always LTR? Fix by passing correct text run flags below.
- FloatPoint boxOrigin(paintOffset);
- boxOrigin.move(x(), y());
- FloatRect boxRect(boxOrigin, LayoutSize(logicalWidth(), logicalHeight()));
- FloatPoint textOrigin(boxOrigin.x(), boxOrigin.y() + style->fontMetrics().ascent());
- TextRun textRun = RenderBlock::constructTextRun(renderer(), font, m_str, style, TextRun::AllowTrailingExpansion);
+ TextRun textRun = RenderBlockFlow::constructTextRun(renderer(), font, m_str, style, TextRun::AllowTrailingExpansion);
TextRunPaintInfo textRunPaintInfo(textRun);
textRunPaintInfo.bounds = boxRect;
context->drawText(font, textRunPaintInfo, textOrigin);
@@ -124,10 +132,10 @@ IntRect EllipsisBox::selectionRect()
RenderStyle* style = m_renderer->style(isFirstLineStyle());
const Font& font = style->font();
// FIXME: Why is this always LTR? Fix by passing correct text run flags below.
- return enclosingIntRect(font.selectionRectForText(RenderBlock::constructTextRun(renderer(), font, m_str, style, TextRun::AllowTrailingExpansion), IntPoint(x(), y() + root()->selectionTopAdjustedForPrecedingBlock()), root()->selectionHeightAdjustedForPrecedingBlock()));
+ return enclosingIntRect(font.selectionRectForText(RenderBlockFlow::constructTextRun(renderer(), font, m_str, style, TextRun::AllowTrailingExpansion), IntPoint(logicalLeft(), logicalTop() + root()->selectionTopAdjustedForPrecedingBlock()), root()->selectionHeightAdjustedForPrecedingBlock()));
}
-void EllipsisBox::paintSelection(GraphicsContext* context, const LayoutPoint& paintOffset, RenderStyle* style, const Font& font)
+void EllipsisBox::paintSelection(GraphicsContext* context, const FloatPoint& boxOrigin, RenderStyle* style, const Font& font)
{
Color textColor = m_renderer->resolveColor(style, CSSPropertyColor);
Color c = m_renderer->selectionBackgroundColor();
@@ -140,13 +148,16 @@ void EllipsisBox::paintSelection(GraphicsContext* context, const LayoutPoint& pa
c = Color(0xff - c.red(), 0xff - c.green(), 0xff - c.blue());
GraphicsContextStateSaver stateSaver(*context);
+ LayoutUnit selectionBottom = root()->selectionBottom();
LayoutUnit top = root()->selectionTop();
LayoutUnit h = root()->selectionHeight();
- FloatRect clipRect(x() + paintOffset.x(), top + paintOffset.y(), m_logicalWidth, h);
+ const int deltaY = roundToInt(renderer()->style()->isFlippedLinesWritingMode() ? selectionBottom - logicalBottom() : logicalTop() - top);
+ const FloatPoint localOrigin(boxOrigin.x(), boxOrigin.y() - deltaY);
+ FloatRect clipRect(localOrigin, FloatSize(m_logicalWidth, h));
alignSelectionRectToDevicePixels(clipRect);
context->clip(clipRect);
// FIXME: Why is this always LTR? Fix by passing correct text run flags below.
- context->drawHighlightForText(font, RenderBlock::constructTextRun(renderer(), font, m_str, style, TextRun::AllowTrailingExpansion), roundedIntPoint(LayoutPoint(x() + paintOffset.x(), y() + paintOffset.y() + top)), h, c);
+ context->drawHighlightForText(font, RenderBlockFlow::constructTextRun(renderer(), font, m_str, style, TextRun::AllowTrailingExpansion), localOrigin, h, c);
}
bool EllipsisBox::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, LayoutUnit lineTop, LayoutUnit lineBottom)
@@ -164,7 +175,9 @@ bool EllipsisBox::nodeAtPoint(const HitTestRequest& request, HitTestResult& resu
}
}
- LayoutRect boundsRect(adjustedLocation, LayoutSize(m_logicalWidth, m_height));
+ FloatPoint boxOrigin = locationIncludingFlipping();
+ boxOrigin.moveBy(accumulatedOffset);
+ FloatRect boundsRect(boxOrigin, size());
if (visibleToHitTestRequest(request) && boundsRect.intersects(HitTestLocation::rectForPoint(locationInContainer.point(), 0, 0, 0, 0))) {
renderer()->updateHitTestResult(result, locationInContainer.point() - toLayoutSize(adjustedLocation));
if (!result.addNodeToRectBasedTestResult(renderer()->node(), request, locationInContainer, boundsRect))
diff --git a/chromium/third_party/WebKit/Source/core/rendering/EllipsisBox.h b/chromium/third_party/WebKit/Source/core/rendering/EllipsisBox.h
index 9382e774d45..ad8e61291f5 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/EllipsisBox.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/EllipsisBox.h
@@ -30,13 +30,14 @@ class HitTestResult;
class EllipsisBox FINAL : public InlineBox {
public:
EllipsisBox(RenderObject* obj, const AtomicString& ellipsisStr, InlineFlowBox* parent,
- int width, int height, int y, bool firstLine, bool isVertical, InlineBox* markupBox)
- : InlineBox(obj, FloatPoint(0, y), width, firstLine, true, false, false, isVertical, 0, 0, parent)
+ int width, int height, int x, int y, bool firstLine, bool isVertical, InlineBox* markupBox)
+ : InlineBox(obj, FloatPoint(x, y), width, firstLine, true, false, false, isVertical, 0, 0, parent)
, m_shouldPaintMarkupBox(markupBox)
, m_height(height)
, m_str(ellipsisStr)
, m_selectionState(RenderObject::SelectionNone)
{
+ setHasVirtualLogicalHeight();
}
virtual void paint(PaintInfo&, const LayoutPoint&, LayoutUnit lineTop, LayoutUnit lineBottom);
@@ -44,11 +45,12 @@ public:
void setSelectionState(RenderObject::SelectionState s) { m_selectionState = s; }
IntRect selectionRect();
+ virtual float virtualLogicalHeight() const OVERRIDE { return m_height; }
private:
void paintMarkupBox(PaintInfo&, const LayoutPoint& paintOffset, LayoutUnit lineTop, LayoutUnit lineBottom, RenderStyle*);
virtual int height() const { return m_height; }
virtual RenderObject::SelectionState selectionState() { return m_selectionState; }
- void paintSelection(GraphicsContext*, const LayoutPoint&, RenderStyle*, const Font&);
+ void paintSelection(GraphicsContext*, const FloatPoint&, RenderStyle*, const Font&);
InlineBox* markupBox() const;
bool m_shouldPaintMarkupBox;
diff --git a/chromium/third_party/WebKit/Source/core/rendering/FastTextAutosizer.cpp b/chromium/third_party/WebKit/Source/core/rendering/FastTextAutosizer.cpp
new file mode 100644
index 00000000000..cbdcafc68f0
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/rendering/FastTextAutosizer.cpp
@@ -0,0 +1,139 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/rendering/FastTextAutosizer.h"
+
+#include "core/dom/Document.h"
+#include "core/frame/Settings.h"
+#include "core/rendering/InlineIterator.h"
+#include "core/rendering/RenderBlock.h"
+#include "core/rendering/TextAutosizer.h"
+
+namespace WebCore {
+
+FastTextAutosizer::FastTextAutosizer(Document* document)
+ : m_document(document)
+{
+}
+
+void FastTextAutosizer::record(const RenderBlock* block)
+{
+ if (!m_document->settings()
+ || !m_document->settings()->textAutosizingEnabled()
+ || m_document->printing()
+ || !m_document->page())
+ return;
+
+ if (!TextAutosizer::isAutosizingContainer(block))
+ return;
+
+ AtomicString blockFingerprint = fingerprint(block);
+ HashMap<AtomicString, OwnPtr<Cluster> >::AddResult result =
+ m_clusterForFingerprint.add(blockFingerprint, PassOwnPtr<Cluster>());
+
+ if (result.isNewEntry)
+ result.iterator->value = adoptPtr(new Cluster(blockFingerprint));
+
+ Cluster* cluster = result.iterator->value.get();
+ cluster->m_blocks.add(block);
+
+ m_clusterForBlock.set(block, cluster);
+}
+
+void FastTextAutosizer::destroy(const RenderBlock* block)
+{
+ Cluster* cluster = m_clusterForBlock.take(block);
+ if (!cluster)
+ return;
+ cluster->m_blocks.remove(block);
+ if (cluster->m_blocks.isEmpty()) {
+ // This deletes the Cluster.
+ m_clusterForFingerprint.remove(cluster->m_fingerprint);
+ return;
+ }
+ cluster->m_multiplier = 0;
+}
+
+static void applyMultiplier(RenderObject* renderer, float multiplier)
+{
+ // We need to clone the render style to avoid breaking style sharing.
+ RefPtr<RenderStyle> style = RenderStyle::clone(renderer->style());
+ style->setTextAutosizingMultiplier(multiplier);
+ style->setUnique();
+ renderer->setStyleInternal(style.release());
+}
+
+void FastTextAutosizer::inflate(RenderBlock* block)
+{
+ Cluster* cluster = 0;
+ for (const RenderObject* clusterBlock = block; clusterBlock && !cluster; clusterBlock = clusterBlock->parent()) {
+ if (clusterBlock->isRenderBlock())
+ cluster = m_clusterForBlock.get(toRenderBlock(clusterBlock));
+ }
+ if (!cluster)
+ return;
+ if (!cluster->m_multiplier)
+ cluster->m_multiplier = computeMultiplier(cluster);
+ if (cluster->m_multiplier == 1)
+ return;
+
+ applyMultiplier(block, cluster->m_multiplier);
+ for (InlineWalker walker(block); !walker.atEnd(); walker.advance()) {
+ RenderObject* inlineObj = walker.current();
+ if (inlineObj->isRenderBlock() && m_clusterForBlock.contains(toRenderBlock(inlineObj)))
+ continue;
+
+ applyMultiplier(inlineObj, cluster->m_multiplier);
+ }
+}
+
+AtomicString FastTextAutosizer::fingerprint(const RenderBlock* block)
+{
+ // FIXME(crbug.com/322340): Implement a better fingerprinting algorithm.
+ return String::number((unsigned long long) block);
+}
+
+float FastTextAutosizer::computeMultiplier(const FastTextAutosizer::Cluster* cluster)
+{
+ const WTF::HashSet<const RenderBlock*>& blocks = cluster->m_blocks;
+
+ bool shouldAutosize = false;
+ for (WTF::HashSet<const RenderBlock*>::iterator it = blocks.begin(); it != blocks.end(); ++it)
+ shouldAutosize |= TextAutosizer::containerShouldBeAutosized(*it);
+
+ if (!shouldAutosize)
+ return 1.0f;
+
+ // FIXME(crbug.com/322344): Implement multiplier computation.
+ return 1.5f;
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/FastTextAutosizer.h b/chromium/third_party/WebKit/Source/core/rendering/FastTextAutosizer.h
new file mode 100644
index 00000000000..16265fd899a
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/rendering/FastTextAutosizer.h
@@ -0,0 +1,91 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef FastTextAutosizer_h
+#define FastTextAutosizer_h
+
+#include "wtf/HashMap.h"
+#include "wtf/HashSet.h"
+#include "wtf/Noncopyable.h"
+#include "wtf/OwnPtr.h"
+#include "wtf/PassOwnPtr.h"
+#include "wtf/text/AtomicStringHash.h"
+
+namespace WebCore {
+
+class Document;
+class RenderBlock;
+
+// Single-pass text autosizer (work in progress). Works in two stages:
+// (1) record information about page elements during style recalc
+// (2) inflate sizes during layout
+// See: http://tinyurl.com/chromium-fast-autosizer
+
+class FastTextAutosizer FINAL {
+ WTF_MAKE_NONCOPYABLE(FastTextAutosizer);
+
+public:
+ static PassOwnPtr<FastTextAutosizer> create(Document* document)
+ {
+ return adoptPtr(new FastTextAutosizer(document));
+ }
+
+ void record(const RenderBlock*);
+ void destroy(const RenderBlock*);
+ void inflate(RenderBlock*);
+
+private:
+ // TODO: make a proper API for this class?
+ struct Cluster {
+ explicit Cluster(AtomicString fingerprint)
+ : m_fingerprint(fingerprint)
+ , m_multiplier(0)
+ {
+ }
+
+ AtomicString m_fingerprint;
+ WTF::HashSet<const RenderBlock*> m_blocks;
+ float m_multiplier;
+ };
+
+ explicit FastTextAutosizer(Document*);
+
+ AtomicString fingerprint(const RenderBlock*);
+ float computeMultiplier(const Cluster*);
+
+ Document* m_document;
+
+ WTF::HashMap<const RenderBlock*, Cluster*> m_clusterForBlock;
+ WTF::HashMap<AtomicString, OwnPtr<Cluster> > m_clusterForFingerprint;
+};
+
+} // namespace WebCore
+
+#endif // FastTextAutosizer_h
diff --git a/chromium/third_party/WebKit/Source/core/rendering/FilterEffectRenderer.cpp b/chromium/third_party/WebKit/Source/core/rendering/FilterEffectRenderer.cpp
index b389aa4e2ac..ff60e9b0d76 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/FilterEffectRenderer.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/FilterEffectRenderer.cpp
@@ -32,22 +32,24 @@
#include "core/fetch/DocumentResource.h"
#include "core/fetch/DocumentResourceReference.h"
#include "core/page/Page.h"
-#include "core/platform/FloatConversion.h"
-#include "core/platform/graphics/ColorSpace.h"
-#include "core/platform/graphics/filters/FEColorMatrix.h"
-#include "core/platform/graphics/filters/FEComponentTransfer.h"
-#include "core/platform/graphics/filters/FEDropShadow.h"
-#include "core/platform/graphics/filters/FEGaussianBlur.h"
-#include "core/platform/graphics/filters/custom/CustomFilterGlobalContext.h"
-#include "core/platform/graphics/filters/custom/CustomFilterValidatedProgram.h"
-#include "core/platform/graphics/filters/custom/FECustomFilter.h"
-#include "core/platform/graphics/filters/custom/ValidatedCustomFilterOperation.h"
#include "core/rendering/RenderLayer.h"
#include "core/rendering/RenderView.h"
#include "core/rendering/svg/ReferenceFilterBuilder.h"
-
#include "core/svg/SVGElement.h"
#include "core/svg/SVGFilterPrimitiveStandardAttributes.h"
+#include "platform/FloatConversion.h"
+#include "platform/LengthFunctions.h"
+#include "platform/graphics/ColorSpace.h"
+#include "platform/graphics/UnacceleratedImageBufferSurface.h"
+#include "platform/graphics/filters/FEColorMatrix.h"
+#include "platform/graphics/filters/FEComponentTransfer.h"
+#include "platform/graphics/filters/FEDropShadow.h"
+#include "platform/graphics/filters/FEGaussianBlur.h"
+#include "platform/graphics/filters/custom/CustomFilterGlobalContext.h"
+#include "platform/graphics/filters/custom/CustomFilterValidatedProgram.h"
+#include "platform/graphics/filters/custom/FECustomFilter.h"
+#include "platform/graphics/filters/custom/ValidatedCustomFilterOperation.h"
+#include "platform/graphics/gpu/AcceleratedImageBufferSurface.h"
#include "wtf/MathExtras.h"
#include <algorithm>
@@ -124,16 +126,14 @@ bool FilterEffectRenderer::build(RenderObject* renderer, const FilterOperations&
for (size_t i = 0; i < operations.operations().size(); ++i) {
RefPtr<FilterEffect> effect;
FilterOperation* filterOperation = operations.operations().at(i).get();
- switch (filterOperation->getOperationType()) {
+ switch (filterOperation->type()) {
case FilterOperation::REFERENCE: {
- ReferenceFilterOperation* referenceOperation = static_cast<ReferenceFilterOperation*>(filterOperation);
- effect = ReferenceFilterBuilder::build(this, renderer, previousEffect.get(), referenceOperation);
+ effect = ReferenceFilterBuilder::build(this, renderer, previousEffect.get(), toReferenceFilterOperation(filterOperation));
break;
}
case FilterOperation::GRAYSCALE: {
- BasicColorMatrixFilterOperation* colorMatrixOperation = static_cast<BasicColorMatrixFilterOperation*>(filterOperation);
Vector<float> inputParameters;
- double oneMinusAmount = clampTo(1 - colorMatrixOperation->amount(), 0.0, 1.0);
+ double oneMinusAmount = clampTo(1 - toBasicColorMatrixFilterOperation(filterOperation)->amount(), 0.0, 1.0);
// See https://dvcs.w3.org/hg/FXTF/raw-file/tip/filters/index.html#grayscaleEquivalent
// for information on parameters.
@@ -159,9 +159,8 @@ bool FilterEffectRenderer::build(RenderObject* renderer, const FilterOperations&
break;
}
case FilterOperation::SEPIA: {
- BasicColorMatrixFilterOperation* colorMatrixOperation = static_cast<BasicColorMatrixFilterOperation*>(filterOperation);
Vector<float> inputParameters;
- double oneMinusAmount = clampTo(1 - colorMatrixOperation->amount(), 0.0, 1.0);
+ double oneMinusAmount = clampTo(1 - toBasicColorMatrixFilterOperation(filterOperation)->amount(), 0.0, 1.0);
// See https://dvcs.w3.org/hg/FXTF/raw-file/tip/filters/index.html#sepiaEquivalent
// for information on parameters.
@@ -187,21 +186,19 @@ bool FilterEffectRenderer::build(RenderObject* renderer, const FilterOperations&
break;
}
case FilterOperation::SATURATE: {
- BasicColorMatrixFilterOperation* colorMatrixOperation = static_cast<BasicColorMatrixFilterOperation*>(filterOperation);
Vector<float> inputParameters;
- inputParameters.append(narrowPrecisionToFloat(colorMatrixOperation->amount()));
+ inputParameters.append(narrowPrecisionToFloat(toBasicColorMatrixFilterOperation(filterOperation)->amount()));
effect = FEColorMatrix::create(this, FECOLORMATRIX_TYPE_SATURATE, inputParameters);
break;
}
case FilterOperation::HUE_ROTATE: {
- BasicColorMatrixFilterOperation* colorMatrixOperation = static_cast<BasicColorMatrixFilterOperation*>(filterOperation);
Vector<float> inputParameters;
- inputParameters.append(narrowPrecisionToFloat(colorMatrixOperation->amount()));
+ inputParameters.append(narrowPrecisionToFloat(toBasicColorMatrixFilterOperation(filterOperation)->amount()));
effect = FEColorMatrix::create(this, FECOLORMATRIX_TYPE_HUEROTATE, inputParameters);
break;
}
case FilterOperation::INVERT: {
- BasicComponentTransferFilterOperation* componentTransferOperation = static_cast<BasicComponentTransferFilterOperation*>(filterOperation);
+ BasicComponentTransferFilterOperation* componentTransferOperation = toBasicComponentTransferFilterOperation(filterOperation);
ComponentTransferFunction transferFunction;
transferFunction.type = FECOMPONENTTRANSFER_TYPE_TABLE;
Vector<float> transferParameters;
@@ -214,12 +211,11 @@ bool FilterEffectRenderer::build(RenderObject* renderer, const FilterOperations&
break;
}
case FilterOperation::OPACITY: {
- BasicComponentTransferFilterOperation* componentTransferOperation = static_cast<BasicComponentTransferFilterOperation*>(filterOperation);
ComponentTransferFunction transferFunction;
transferFunction.type = FECOMPONENTTRANSFER_TYPE_TABLE;
Vector<float> transferParameters;
transferParameters.append(0);
- transferParameters.append(narrowPrecisionToFloat(componentTransferOperation->amount()));
+ transferParameters.append(narrowPrecisionToFloat(toBasicComponentTransferFilterOperation(filterOperation)->amount()));
transferFunction.tableValues = transferParameters;
ComponentTransferFunction nullFunction;
@@ -227,10 +223,9 @@ bool FilterEffectRenderer::build(RenderObject* renderer, const FilterOperations&
break;
}
case FilterOperation::BRIGHTNESS: {
- BasicComponentTransferFilterOperation* componentTransferOperation = static_cast<BasicComponentTransferFilterOperation*>(filterOperation);
ComponentTransferFunction transferFunction;
transferFunction.type = FECOMPONENTTRANSFER_TYPE_LINEAR;
- transferFunction.slope = narrowPrecisionToFloat(componentTransferOperation->amount());
+ transferFunction.slope = narrowPrecisionToFloat(toBasicComponentTransferFilterOperation(filterOperation)->amount());
transferFunction.intercept = 0;
ComponentTransferFunction nullFunction;
@@ -238,10 +233,9 @@ bool FilterEffectRenderer::build(RenderObject* renderer, const FilterOperations&
break;
}
case FilterOperation::CONTRAST: {
- BasicComponentTransferFilterOperation* componentTransferOperation = static_cast<BasicComponentTransferFilterOperation*>(filterOperation);
ComponentTransferFunction transferFunction;
transferFunction.type = FECOMPONENTTRANSFER_TYPE_LINEAR;
- float amount = narrowPrecisionToFloat(componentTransferOperation->amount());
+ float amount = narrowPrecisionToFloat(toBasicComponentTransferFilterOperation(filterOperation)->amount());
transferFunction.slope = amount;
transferFunction.intercept = -0.5 * amount + 0.5;
@@ -250,13 +244,12 @@ bool FilterEffectRenderer::build(RenderObject* renderer, const FilterOperations&
break;
}
case FilterOperation::BLUR: {
- BlurFilterOperation* blurOperation = static_cast<BlurFilterOperation*>(filterOperation);
- float stdDeviation = floatValueForLength(blurOperation->stdDeviation(), 0) * invZoom;
+ float stdDeviation = floatValueForLength(toBlurFilterOperation(filterOperation)->stdDeviation(), 0) * invZoom;
effect = FEGaussianBlur::create(this, stdDeviation, stdDeviation);
break;
}
case FilterOperation::DROP_SHADOW: {
- DropShadowFilterOperation* dropShadowOperation = static_cast<DropShadowFilterOperation*>(filterOperation);
+ DropShadowFilterOperation* dropShadowOperation = toDropShadowFilterOperation(filterOperation);
float stdDeviation = dropShadowOperation->stdDeviation() * invZoom;
float x = dropShadowOperation->x() * invZoom;
float y = dropShadowOperation->y() * invZoom;
@@ -269,9 +262,8 @@ bool FilterEffectRenderer::build(RenderObject* renderer, const FilterOperations&
ASSERT_NOT_REACHED();
break;
case FilterOperation::VALIDATED_CUSTOM: {
- ValidatedCustomFilterOperation* customFilterOperation = static_cast<ValidatedCustomFilterOperation*>(filterOperation);
Document* document = renderer ? &renderer->document() : 0;
- effect = createCustomFilterEffect(this, document, customFilterOperation);
+ effect = createCustomFilterEffect(this, document, toValidatedCustomFilterOperation(filterOperation));
if (effect)
m_hasCustomShaderFilter = true;
break;
@@ -281,7 +273,7 @@ bool FilterEffectRenderer::build(RenderObject* renderer, const FilterOperations&
}
if (effect) {
- if (filterOperation->getOperationType() != FilterOperation::REFERENCE) {
+ if (filterOperation->type() != FilterOperation::REFERENCE) {
// Unlike SVG, filters applied here should not clip to their primitive subregions.
effect->setClipsToBounds(false);
effect->setOperatingColorSpace(ColorSpaceDeviceRGB);
@@ -321,8 +313,16 @@ void FilterEffectRenderer::allocateBackingStoreIfNeeded()
// buffer if we have not yet done so.
if (!m_graphicsBufferAttached) {
IntSize logicalSize(m_sourceDrawingRegion.width(), m_sourceDrawingRegion.height());
- if (!sourceImage() || sourceImage()->logicalSize() != logicalSize)
- setSourceImage(ImageBuffer::create(logicalSize, 1, renderingMode()));
+ if (!sourceImage() || sourceImage()->size() != logicalSize) {
+ OwnPtr<ImageBufferSurface> surface;
+ if (isAccelerated()) {
+ surface = adoptPtr(new AcceleratedImageBufferSurface(logicalSize));
+ }
+ if (!surface || !surface->isValid()) {
+ surface = adoptPtr(new UnacceleratedImageBufferSurface(logicalSize));
+ }
+ setSourceImage(ImageBuffer::create(surface.release()));
+ }
m_graphicsBufferAttached = true;
}
}
@@ -383,7 +383,7 @@ bool FilterEffectRendererHelper::prepareFilterEffect(RenderLayer* renderLayer, c
filter->setAbsoluteTransform(absoluteTransform);
filter->setAbsoluteFilterRegion(AffineTransform().scale(zoom).mapRect(filterSourceRect));
filter->setFilterRegion(absoluteTransform.inverse().mapRect(filterSourceRect));
- filter->lastEffect()->determineFilterPrimitiveSubregion();
+ filter->lastEffect()->determineFilterPrimitiveSubregion(MapRectForward);
bool hasUpdatedBackingStore = filter->updateBackingStoreRect(filterSourceRect);
if (filter->hasFilterThatMovesPixels()) {
diff --git a/chromium/third_party/WebKit/Source/core/rendering/FilterEffectRenderer.h b/chromium/third_party/WebKit/Source/core/rendering/FilterEffectRenderer.h
index 2dfe2682261..54f67f0ae8b 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/FilterEffectRenderer.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/FilterEffectRenderer.h
@@ -26,16 +26,16 @@
#ifndef FilterEffectRenderer_h
#define FilterEffectRenderer_h
-#include "core/platform/graphics/FloatRect.h"
-#include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/graphics/ImageBuffer.h"
-#include "core/platform/graphics/IntRectExtent.h"
-#include "core/platform/graphics/LayoutRect.h"
-#include "core/platform/graphics/filters/Filter.h"
-#include "core/platform/graphics/filters/FilterEffect.h"
-#include "core/platform/graphics/filters/FilterOperations.h"
-#include "core/platform/graphics/filters/SourceGraphic.h"
#include "core/svg/graphics/filters/SVGFilterBuilder.h"
+#include "platform/geometry/FloatRect.h"
+#include "platform/geometry/IntRectExtent.h"
+#include "platform/geometry/LayoutRect.h"
+#include "platform/graphics/GraphicsContext.h"
+#include "platform/graphics/ImageBuffer.h"
+#include "platform/graphics/filters/Filter.h"
+#include "platform/graphics/filters/FilterEffect.h"
+#include "platform/graphics/filters/FilterOperations.h"
+#include "platform/graphics/filters/SourceGraphic.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefCounted.h"
#include "wtf/RefPtr.h"
diff --git a/chromium/third_party/WebKit/Source/core/rendering/FixedTableLayout.cpp b/chromium/third_party/WebKit/Source/core/rendering/FixedTableLayout.cpp
index 2a516681f34..83cc6cebe96 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/FixedTableLayout.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/FixedTableLayout.cpp
@@ -22,11 +22,11 @@
#include "config.h"
#include "core/rendering/FixedTableLayout.h"
-#include "core/platform/LayoutUnit.h"
#include "core/rendering/RenderTable.h"
#include "core/rendering/RenderTableCell.h"
#include "core/rendering/RenderTableCol.h"
#include "core/rendering/RenderTableSection.h"
+#include "platform/LayoutUnit.h"
/*
The text below is from the CSS 2.1 specs.
@@ -318,4 +318,25 @@ void FixedTableLayout::layout()
m_table->setColumnPosition(colPositionsSize - 1, pos);
}
+void FixedTableLayout::willChangeTableLayout()
+{
+ // When switching table layout algorithm, we need to dirty the preferred
+ // logical widths as we cleared the bits without computing them.
+ // (see calcWidthArray above.) This optimization is preferred to always
+ // computing the logical widths we never intended to use.
+ m_table->recalcSectionsIfNeeded();
+ for (RenderTableSection* section = m_table->topNonEmptySection(); section; section = m_table->sectionBelow(section)) {
+ for (unsigned i = 0; i < section->numRows(); i++) {
+ RenderTableRow* row = section->rowRendererAt(i);
+ if (!row)
+ continue;
+ for (RenderObject* cell = row->firstChild(); cell; cell = cell->nextSibling()) {
+ if (!cell->isTableCell())
+ continue;
+ cell->setPreferredLogicalWidthsDirty();
+ }
+ }
+ }
+}
+
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/FixedTableLayout.h b/chromium/third_party/WebKit/Source/core/rendering/FixedTableLayout.h
index 7de0e48bcbd..39dffea2859 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/FixedTableLayout.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/FixedTableLayout.h
@@ -21,21 +21,22 @@
#ifndef FixedTableLayout_h
#define FixedTableLayout_h
-#include "core/platform/Length.h"
#include "core/rendering/TableLayout.h"
+#include "platform/Length.h"
#include "wtf/Vector.h"
namespace WebCore {
class RenderTable;
-class FixedTableLayout : public TableLayout {
+class FixedTableLayout FINAL : public TableLayout {
public:
FixedTableLayout(RenderTable*);
virtual void computeIntrinsicLogicalWidths(LayoutUnit& minWidth, LayoutUnit& maxWidth) OVERRIDE;
virtual void applyPreferredLogicalWidthQuirks(LayoutUnit& minWidth, LayoutUnit& maxWidth) const OVERRIDE;
- virtual void layout();
+ virtual void layout() OVERRIDE;
+ virtual void willChangeTableLayout() OVERRIDE;
private:
int calcWidthArray();
diff --git a/chromium/third_party/WebKit/Source/core/rendering/FloatingObjects.cpp b/chromium/third_party/WebKit/Source/core/rendering/FloatingObjects.cpp
index bcd98461f91..152a3a329c6 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/FloatingObjects.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/FloatingObjects.cpp
@@ -24,7 +24,7 @@
#include "config.h"
#include "core/rendering/FloatingObjects.h"
-#include "core/rendering/RenderBlock.h"
+#include "core/rendering/RenderBlockFlow.h"
#include "core/rendering/RenderBox.h"
#include "core/rendering/RenderView.h"
@@ -104,7 +104,7 @@ class ComputeFloatOffsetAdapter {
public:
typedef FloatingObjectInterval IntervalType;
- ComputeFloatOffsetAdapter(const RenderBlock* renderer, int lineTop, int lineBottom, LayoutUnit& offset)
+ ComputeFloatOffsetAdapter(const RenderBlockFlow* renderer, int lineTop, int lineBottom, LayoutUnit offset)
: m_renderer(renderer)
, m_lineTop(lineTop)
, m_lineBottom(lineBottom)
@@ -117,21 +117,17 @@ public:
int highValue() const { return m_lineBottom; }
void collectIfNeeded(const IntervalType&);
- // When computing the offset caused by the floats on a given line, if
- // the outermost float on that line has a shape-outside, the inline
- // content that butts up against that float must be positioned using
- // the contours of the shape, not the margin box of the float.
- const FloatingObject* outermostFloat() const { return m_outermostFloat; }
-
- LayoutUnit getHeightRemaining() const;
+ LayoutUnit offset() const { return m_offset; }
+ LayoutUnit shapeOffset() const;
+ LayoutUnit heightRemaining() const;
private:
bool updateOffsetIfNeeded(const FloatingObject*);
- const RenderBlock* m_renderer;
+ const RenderBlockFlow* m_renderer;
int m_lineTop;
int m_lineBottom;
- LayoutUnit& m_offset;
+ LayoutUnit m_offset;
const FloatingObject* m_outermostFloat;
};
@@ -154,7 +150,7 @@ void FloatingObjects::clearLineBoxTreePointers()
template<>
inline bool ComputeFloatOffsetAdapter<FloatingObject::FloatLeft>::updateOffsetIfNeeded(const FloatingObject* floatingObject)
{
- LayoutUnit logicalRight = floatingObject->logicalRight(m_renderer->isHorizontalWritingMode());
+ LayoutUnit logicalRight = m_renderer->logicalRightForFloat(floatingObject);
if (logicalRight > m_offset) {
m_offset = logicalRight;
return true;
@@ -162,7 +158,7 @@ inline bool ComputeFloatOffsetAdapter<FloatingObject::FloatLeft>::updateOffsetIf
return false;
}
-FloatingObjects::FloatingObjects(const RenderBlock* renderer, bool horizontalWritingMode)
+FloatingObjects::FloatingObjects(const RenderBlockFlow* renderer, bool horizontalWritingMode)
: m_placedFloatsTree(UninitializedTree)
, m_leftObjectsCount(0)
, m_rightObjectsCount(0)
@@ -202,10 +198,10 @@ LayoutUnit FloatingObjects::lowestFloatLogicalBottom(FloatingObject::Type floatT
LayoutUnit lowestFloatBottomLeft = 0;
LayoutUnit lowestFloatBottomRight = 0;
for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
- FloatingObject* r = *it;
- if (r->isPlaced()) {
- FloatingObject::Type curType = r->type();
- LayoutUnit curFloatLogicalBottom = r->logicalBottom(isInHorizontalWritingMode);
+ FloatingObject* floatingObject = *it;
+ if (floatingObject->isPlaced()) {
+ FloatingObject::Type curType = floatingObject->type();
+ LayoutUnit curFloatLogicalBottom = m_renderer->logicalBottomForFloat(floatingObject);
if (curType & FloatingObject::FloatLeft)
lowestFloatBottomLeft = max(lowestFloatBottomLeft, curFloatLogicalBottom);
if (curType & FloatingObject::FloatRight)
@@ -217,9 +213,9 @@ LayoutUnit FloatingObjects::lowestFloatLogicalBottom(FloatingObject::Type floatT
setCachedLowestFloatLogicalBottom(isInHorizontalWritingMode, FloatingObject::FloatRight, lowestFloatBottomRight);
} else {
for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
- FloatingObject* r = *it;
- if (r->isPlaced() && r->type() == floatType)
- lowestFloatBottom = max(lowestFloatBottom, r->logicalBottom(isInHorizontalWritingMode));
+ FloatingObject* floatingObject = *it;
+ if (floatingObject->isPlaced() && floatingObject->type() == floatType)
+ lowestFloatBottom = max(lowestFloatBottom, m_renderer->logicalBottomForFloat(floatingObject));
}
setCachedLowestFloatLogicalBottom(isInHorizontalWritingMode, floatType, lowestFloatBottom);
}
@@ -230,7 +226,7 @@ LayoutUnit FloatingObjects::lowestFloatLogicalBottom(FloatingObject::Type floatT
bool FloatingObjects::hasLowestFloatLogicalBottomCached(bool isHorizontal, FloatingObject::Type type) const
{
int floatIndex = static_cast<int>(type) - 1;
- ASSERT(floatIndex < sizeof(m_lowestFloatBottomCache) / sizeof(FloatBottomCachedValue));
+ ASSERT(floatIndex < static_cast<int>(sizeof(m_lowestFloatBottomCache) / sizeof(FloatBottomCachedValue)));
ASSERT(floatIndex >= 0);
return (m_cachedHorizontalWritingMode == isHorizontal && !m_lowestFloatBottomCache[floatIndex].dirty);
}
@@ -238,7 +234,7 @@ bool FloatingObjects::hasLowestFloatLogicalBottomCached(bool isHorizontal, Float
LayoutUnit FloatingObjects::getCachedlowestFloatLogicalBottom(FloatingObject::Type type) const
{
int floatIndex = static_cast<int>(type) - 1;
- ASSERT(floatIndex < sizeof(m_lowestFloatBottomCache) / sizeof(FloatBottomCachedValue));
+ ASSERT(floatIndex < static_cast<int>(sizeof(m_lowestFloatBottomCache) / sizeof(FloatBottomCachedValue)));
ASSERT(floatIndex >= 0);
return m_lowestFloatBottomCache[floatIndex].value;
}
@@ -246,7 +242,7 @@ LayoutUnit FloatingObjects::getCachedlowestFloatLogicalBottom(FloatingObject::Ty
void FloatingObjects::setCachedLowestFloatLogicalBottom(bool isHorizontal, FloatingObject::Type type, LayoutUnit value)
{
int floatIndex = static_cast<int>(type) - 1;
- ASSERT(floatIndex < sizeof(m_lowestFloatBottomCache) / sizeof(FloatBottomCachedValue));
+ ASSERT(floatIndex < static_cast<int>(sizeof(m_lowestFloatBottomCache) / sizeof(FloatBottomCachedValue)));
ASSERT(floatIndex >= 0);
m_cachedHorizontalWritingMode = isHorizontal;
m_lowestFloatBottomCache[floatIndex].value = value;
@@ -255,7 +251,7 @@ void FloatingObjects::setCachedLowestFloatLogicalBottom(bool isHorizontal, Float
void FloatingObjects::markLowestFloatLogicalBottomCacheAsDirty()
{
- for (int i = 0; i < sizeof(m_lowestFloatBottomCache) / sizeof(FloatBottomCachedValue); ++i)
+ for (size_t i = 0; i < sizeof(m_lowestFloatBottomCache) / sizeof(FloatBottomCachedValue); ++i)
m_lowestFloatBottomCache[i].dirty = true;
}
@@ -362,44 +358,74 @@ void FloatingObjects::computePlacedFloatsTree()
}
}
-LayoutUnit FloatingObjects::logicalLeftOffset(LayoutUnit fixedOffset, LayoutUnit logicalTop, LayoutUnit logicalHeight, ShapeOutsideFloatOffsetMode offsetMode, LayoutUnit *heightRemaining)
+static inline ShapeOutsideInfo* shapeInfoForFloat(const FloatingObject* floatingObject, const RenderBlockFlow* containingBlock, LayoutUnit lineTop, LayoutUnit lineBottom)
+{
+ if (floatingObject) {
+ if (ShapeOutsideInfo* shapeOutside = floatingObject->renderer()->shapeOutsideInfo()) {
+ shapeOutside->updateDeltasForContainingBlockLine(containingBlock, floatingObject, lineTop, lineBottom - lineTop);
+ return shapeOutside;
+ }
+ }
+
+ return 0;
+}
+
+template<>
+inline LayoutUnit ComputeFloatOffsetAdapter<FloatingObject::FloatLeft>::shapeOffset() const
+{
+ if (ShapeOutsideInfo* shapeOutside = shapeInfoForFloat(m_outermostFloat, m_renderer, m_lineTop, m_lineBottom))
+ return m_offset + shapeOutside->rightMarginBoxDelta();
+
+ return m_offset;
+}
+
+template<>
+inline LayoutUnit ComputeFloatOffsetAdapter<FloatingObject::FloatRight>::shapeOffset() const
{
- LayoutUnit offset = fixedOffset;
- ComputeFloatOffsetAdapter<FloatingObject::FloatLeft> adapter(m_renderer, roundToInt(logicalTop), roundToInt(logicalTop + logicalHeight), offset);
+ if (ShapeOutsideInfo* shapeOutside = shapeInfoForFloat(m_outermostFloat, m_renderer, m_lineTop, m_lineBottom))
+ return m_offset + shapeOutside->leftMarginBoxDelta();
+
+ return m_offset;
+}
+
+LayoutUnit FloatingObjects::logicalLeftOffsetForPositioningFloat(LayoutUnit fixedOffset, LayoutUnit logicalTop, LayoutUnit *heightRemaining)
+{
+ int logicalTopAsInt = roundToInt(logicalTop);
+ ComputeFloatOffsetAdapter<FloatingObject::FloatLeft> adapter(m_renderer, logicalTopAsInt, logicalTopAsInt, fixedOffset);
placedFloatsTree().allOverlapsWithAdapter(adapter);
if (heightRemaining)
- *heightRemaining = adapter.getHeightRemaining();
-
- const FloatingObject* outermostFloat = adapter.outermostFloat();
- if (offsetMode == ShapeOutsideFloatShapeOffset && outermostFloat) {
- if (ShapeOutsideInfo* shapeOutside = outermostFloat->renderer()->shapeOutsideInfo()) {
- shapeOutside->computeSegmentsForContainingBlockLine(m_renderer, outermostFloat, logicalTop, logicalHeight);
- offset += shapeOutside->rightSegmentMarginBoxDelta();
- }
- }
+ *heightRemaining = adapter.heightRemaining();
- return offset;
+ return adapter.offset();
}
-LayoutUnit FloatingObjects::logicalRightOffset(LayoutUnit fixedOffset, LayoutUnit logicalTop, LayoutUnit logicalHeight, ShapeOutsideFloatOffsetMode offsetMode, LayoutUnit *heightRemaining)
+LayoutUnit FloatingObjects::logicalRightOffsetForPositioningFloat(LayoutUnit fixedOffset, LayoutUnit logicalTop, LayoutUnit *heightRemaining)
{
- LayoutUnit offset = fixedOffset;
- ComputeFloatOffsetAdapter<FloatingObject::FloatRight> adapter(m_renderer, roundToInt(logicalTop), roundToInt(logicalTop + logicalHeight), offset);
+ int logicalTopAsInt = roundToInt(logicalTop);
+ ComputeFloatOffsetAdapter<FloatingObject::FloatRight> adapter(m_renderer, logicalTopAsInt, logicalTopAsInt, fixedOffset);
placedFloatsTree().allOverlapsWithAdapter(adapter);
if (heightRemaining)
- *heightRemaining = adapter.getHeightRemaining();
+ *heightRemaining = adapter.heightRemaining();
- const FloatingObject* outermostFloat = adapter.outermostFloat();
- if (offsetMode == ShapeOutsideFloatShapeOffset && outermostFloat) {
- if (ShapeOutsideInfo* shapeOutside = outermostFloat->renderer()->shapeOutsideInfo()) {
- shapeOutside->computeSegmentsForContainingBlockLine(m_renderer, outermostFloat, logicalTop, logicalHeight);
- offset += shapeOutside->leftSegmentMarginBoxDelta();
- }
- }
+ return min(fixedOffset, adapter.offset());
+}
+
+LayoutUnit FloatingObjects::logicalLeftOffset(LayoutUnit fixedOffset, LayoutUnit logicalTop, LayoutUnit logicalHeight)
+{
+ ComputeFloatOffsetAdapter<FloatingObject::FloatLeft> adapter(m_renderer, roundToInt(logicalTop), roundToInt(logicalTop + logicalHeight), fixedOffset);
+ placedFloatsTree().allOverlapsWithAdapter(adapter);
+
+ return adapter.shapeOffset();
+}
+
+LayoutUnit FloatingObjects::logicalRightOffset(LayoutUnit fixedOffset, LayoutUnit logicalTop, LayoutUnit logicalHeight)
+{
+ ComputeFloatOffsetAdapter<FloatingObject::FloatRight> adapter(m_renderer, roundToInt(logicalTop), roundToInt(logicalTop + logicalHeight), fixedOffset);
+ placedFloatsTree().allOverlapsWithAdapter(adapter);
- return min(fixedOffset, offset);
+ return min(fixedOffset, adapter.shapeOffset());
}
FloatingObjects::FloatBottomCachedValue::FloatBottomCachedValue()
@@ -431,7 +457,7 @@ inline static bool rangesIntersect(int floatTop, int floatBottom, int objectTop,
template<>
inline bool ComputeFloatOffsetAdapter<FloatingObject::FloatRight>::updateOffsetIfNeeded(const FloatingObject* floatingObject)
{
- LayoutUnit logicalLeft = floatingObject->logicalLeft(m_renderer->isHorizontalWritingMode());
+ LayoutUnit logicalLeft = m_renderer->logicalLeftForFloat(floatingObject);
if (logicalLeft < m_offset) {
m_offset = logicalLeft;
return true;
@@ -448,8 +474,8 @@ inline void ComputeFloatOffsetAdapter<FloatTypeValue>::collectIfNeeded(const Int
// Make sure the float hasn't changed since it was added to the placed floats tree.
ASSERT(floatingObject->isPlaced());
- ASSERT(interval.low() == floatingObject->pixelSnappedLogicalTop(m_renderer->isHorizontalWritingMode()));
- ASSERT(interval.high() == floatingObject->pixelSnappedLogicalBottom(m_renderer->isHorizontalWritingMode()));
+ ASSERT(interval.low() == m_renderer->pixelSnappedLogicalTopForFloat(floatingObject));
+ ASSERT(interval.high() == m_renderer->pixelSnappedLogicalBottomForFloat(floatingObject));
bool floatIsNewExtreme = updateOffsetIfNeeded(floatingObject);
if (floatIsNewExtreme)
@@ -457,9 +483,9 @@ inline void ComputeFloatOffsetAdapter<FloatTypeValue>::collectIfNeeded(const Int
}
template <FloatingObject::Type FloatTypeValue>
-LayoutUnit ComputeFloatOffsetAdapter<FloatTypeValue>::getHeightRemaining() const
+LayoutUnit ComputeFloatOffsetAdapter<FloatTypeValue>::heightRemaining() const
{
- return m_outermostFloat ? m_outermostFloat->logicalBottom(m_renderer->isHorizontalWritingMode()) - m_lineTop : LayoutUnit(1);
+ return m_outermostFloat ? m_renderer->logicalBottomForFloat(m_outermostFloat) - m_lineTop : LayoutUnit(1);
}
#ifndef NDEBUG
diff --git a/chromium/third_party/WebKit/Source/core/rendering/FloatingObjects.h b/chromium/third_party/WebKit/Source/core/rendering/FloatingObjects.h
index 9b258e39d17..ca3beb1a345 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/FloatingObjects.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/FloatingObjects.h
@@ -24,17 +24,18 @@
#ifndef FloatingObjects_h
#define FloatingObjects_h
-#include "core/platform/PODFreeListArena.h"
-#include "core/platform/PODIntervalTree.h"
#include "core/rendering/RootInlineBox.h"
+#include "platform/PODFreeListArena.h"
+#include "platform/PODIntervalTree.h"
#include "wtf/ListHashSet.h"
#include "wtf/OwnPtr.h"
namespace WebCore {
-class RenderBlock;
+class RenderBlockFlow;
class RenderBox;
+// FIXME this should be removed once RenderBlockFlow::nextFloatLogicalBottomBelow doesn't need it anymore. (Bug 123931)
enum ShapeOutsideFloatOffsetMode { ShapeOutsideFloatShapeOffset, ShapeOutsideFloatMarginBoxOffset };
class FloatingObject {
@@ -92,46 +93,6 @@ public:
RootInlineBox* originatingLine() const { return m_originatingLine; }
void setOriginatingLine(RootInlineBox* line) { m_originatingLine = line; }
- LayoutUnit logicalTop(bool isHorizontalWritingMode) const { return isHorizontalWritingMode ? y() : x(); }
- LayoutUnit logicalBottom(bool isHorizontalWritingMode) const { return isHorizontalWritingMode ? maxY() : maxX(); }
- LayoutUnit logicalLeft(bool isHorizontalWritingMode) const { return isHorizontalWritingMode ? x() : y(); }
- LayoutUnit logicalRight(bool isHorizontalWritingMode) const { return isHorizontalWritingMode ? maxX() : maxY(); }
- LayoutUnit logicalWidth(bool isHorizontalWritingMode) const { return isHorizontalWritingMode ? width() : height(); }
-
- int pixelSnappedLogicalTop(bool isHorizontalWritingMode) const { return isHorizontalWritingMode ? frameRect().pixelSnappedY() : frameRect().pixelSnappedX(); }
- int pixelSnappedLogicalBottom(bool isHorizontalWritingMode) const { return isHorizontalWritingMode ? frameRect().pixelSnappedMaxY() : frameRect().pixelSnappedMaxX(); }
- int pixelSnappedLogicalLeft(bool isHorizontalWritingMode) const { return isHorizontalWritingMode ? frameRect().pixelSnappedX() : frameRect().pixelSnappedY(); }
- int pixelSnappedLogicalRight(bool isHorizontalWritingMode) const { return isHorizontalWritingMode ? frameRect().pixelSnappedMaxX() : frameRect().pixelSnappedMaxY(); }
-
- void setLogicalTop(LayoutUnit logicalTop, bool isHorizontalWritingMode)
- {
- if (isHorizontalWritingMode)
- setY(logicalTop);
- else
- setX(logicalTop);
- }
- void setLogicalLeft(LayoutUnit logicalLeft, bool isHorizontalWritingMode)
- {
- if (isHorizontalWritingMode)
- setX(logicalLeft);
- else
- setY(logicalLeft);
- }
- void setLogicalHeight(LayoutUnit logicalHeight, bool isHorizontalWritingMode)
- {
- if (isHorizontalWritingMode)
- setHeight(logicalHeight);
- else
- setWidth(logicalHeight);
- }
- void setLogicalWidth(LayoutUnit logicalWidth, bool isHorizontalWritingMode)
- {
- if (isHorizontalWritingMode)
- setWidth(logicalWidth);
- else
- setHeight(logicalWidth);
- }
-
private:
explicit FloatingObject(RenderBox*);
FloatingObject(RenderBox*, Type, const LayoutRect&, bool shouldPaint, bool isDescendant);
@@ -169,7 +130,7 @@ typedef HashMap<RenderBox*, FloatingObject*> RendererToFloatInfoMap;
class FloatingObjects {
WTF_MAKE_NONCOPYABLE(FloatingObjects); WTF_MAKE_FAST_ALLOCATED;
public:
- FloatingObjects(const RenderBlock*, bool horizontalWritingMode);
+ FloatingObjects(const RenderBlockFlow*, bool horizontalWritingMode);
~FloatingObjects();
void clear();
@@ -184,8 +145,12 @@ public:
bool hasRightObjects() const { return m_rightObjectsCount > 0; }
const FloatingObjectSet& set() const { return m_set; }
void clearLineBoxTreePointers();
- LayoutUnit logicalLeftOffset(LayoutUnit fixedOffset, LayoutUnit logicalTop, LayoutUnit logicalHeight, ShapeOutsideFloatOffsetMode = ShapeOutsideFloatShapeOffset, LayoutUnit* heightRemaining = 0);
- LayoutUnit logicalRightOffset(LayoutUnit fixedOffset, LayoutUnit logicalTop, LayoutUnit logicalHeight, ShapeOutsideFloatOffsetMode = ShapeOutsideFloatShapeOffset, LayoutUnit* heightRemaining = 0);
+
+ LayoutUnit logicalLeftOffset(LayoutUnit fixedOffset, LayoutUnit logicalTop, LayoutUnit logicalHeight);
+ LayoutUnit logicalRightOffset(LayoutUnit fixedOffset, LayoutUnit logicalTop, LayoutUnit logicalHeight);
+
+ LayoutUnit logicalLeftOffsetForPositioningFloat(LayoutUnit fixedOffset, LayoutUnit logicalTop, LayoutUnit* heightRemaining);
+ LayoutUnit logicalRightOffsetForPositioningFloat(LayoutUnit fixedOffset, LayoutUnit logicalTop, LayoutUnit* heightRemaining);
LayoutUnit lowestFloatLogicalBottom(FloatingObject::Type);
@@ -211,7 +176,7 @@ private:
unsigned m_leftObjectsCount;
unsigned m_rightObjectsCount;
bool m_horizontalWritingMode;
- const RenderBlock* m_renderer;
+ const RenderBlockFlow* m_renderer;
struct FloatBottomCachedValue {
FloatBottomCachedValue();
diff --git a/chromium/third_party/WebKit/Source/core/rendering/FlowThreadController.cpp b/chromium/third_party/WebKit/Source/core/rendering/FlowThreadController.cpp
index d7f05596c76..521085ee453 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/FlowThreadController.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/FlowThreadController.cpp
@@ -117,7 +117,7 @@ void FlowThreadController::unregisterNamedFlowContentNode(Node* contentNode)
{
ASSERT(contentNode && contentNode->isElementNode());
HashMap<const Node*, RenderNamedFlowThread*>::iterator it = m_mapNamedFlowContentNodes.find(contentNode);
- ASSERT(it != m_mapNamedFlowContentNodes.end());
+ ASSERT_WITH_SECURITY_IMPLICATION(it != m_mapNamedFlowContentNodes.end());
ASSERT(it->value);
ASSERT(it->value->hasContentNode(contentNode));
it->value->unregisterNamedFlowContentNode(contentNode);
diff --git a/chromium/third_party/WebKit/Source/core/rendering/GapRects.h b/chromium/third_party/WebKit/Source/core/rendering/GapRects.h
index 48f7fec462d..951ad38964c 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/GapRects.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/GapRects.h
@@ -23,7 +23,7 @@
#ifndef GapRects_h
#define GapRects_h
-#include "core/platform/graphics/LayoutRect.h"
+#include "platform/geometry/LayoutRect.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/rendering/GraphicsContextAnnotator.cpp b/chromium/third_party/WebKit/Source/core/rendering/GraphicsContextAnnotator.cpp
new file mode 100644
index 00000000000..13739cbd1b7
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/rendering/GraphicsContextAnnotator.cpp
@@ -0,0 +1,134 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ * Copyright (C) 2013 Samsung Electronics. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/rendering/GraphicsContextAnnotator.h"
+
+#include "core/rendering/PaintInfo.h"
+#include "core/rendering/RenderObject.h"
+#include "platform/graphics/GraphicsContextAnnotation.h"
+#include "wtf/text/StringBuilder.h"
+
+namespace {
+
+static const char* paintPhaseName(WebCore::PaintPhase phase)
+{
+ switch (phase) {
+ case WebCore::PaintPhaseBlockBackground:
+ return "BlockBackground";
+ case WebCore::PaintPhaseChildBlockBackground:
+ return "ChildBlockBackground";
+ case WebCore::PaintPhaseChildBlockBackgrounds:
+ return "ChildBlockBackgrounds";
+ case WebCore::PaintPhaseFloat:
+ return "Float";
+ case WebCore::PaintPhaseForeground:
+ return "Foreground";
+ case WebCore::PaintPhaseOutline:
+ return "Outline";
+ case WebCore::PaintPhaseChildOutlines:
+ return "ChildOutlines";
+ case WebCore::PaintPhaseSelfOutline:
+ return "SelfOutline";
+ case WebCore::PaintPhaseSelection:
+ return "Selection";
+ case WebCore::PaintPhaseCollapsedTableBorders:
+ return "CollapsedTableBorders";
+ case WebCore::PaintPhaseTextClip:
+ return "TextClip";
+ case WebCore::PaintPhaseMask:
+ return "Mask";
+ case WebCore::PaintPhaseClippingMask:
+ return "ClippingMask";
+ default:
+ ASSERT_NOT_REACHED();
+ return "<unknown>";
+ }
+}
+
+}
+
+namespace WebCore {
+
+void GraphicsContextAnnotator::annotate(const PaintInfo& paintInfo, const RenderObject* object)
+{
+ ASSERT(!m_context);
+
+ ASSERT(paintInfo.context);
+ ASSERT(object);
+
+ AnnotationModeFlags mode = paintInfo.context->annotationMode();
+ Element* element = object->node() && object->node()->isElementNode() ? toElement(object->node()) : 0;
+
+ const char* rendererName = 0;
+ const char* paintPhase = 0;
+ String elementId, elementClass, elementTag;
+
+ if (mode & AnnotateRendererName)
+ rendererName = object->renderName();
+
+ if (mode & AnnotatePaintPhase)
+ paintPhase = paintPhaseName(paintInfo.phase);
+
+ if ((mode & AnnotateElementId) && element) {
+ const AtomicString id = element->getIdAttribute();
+ if (!id.isNull() && !id.isEmpty())
+ elementId = id.string();
+ }
+
+ if ((mode & AnnotateElementClass) && element && element->hasClass()) {
+ SpaceSplitString classes = element->classNames();
+ if (!classes.isNull() && classes.size() > 0) {
+ StringBuilder classBuilder;
+ for (size_t i = 0; i < classes.size(); ++i) {
+ if (i > 0)
+ classBuilder.append(" ");
+ classBuilder.append(classes[i]);
+ }
+
+ elementClass = classBuilder.toString();
+ }
+ }
+
+ if ((mode & AnnotateElementTag) && element)
+ elementTag = element->tagName();
+
+ m_context = paintInfo.context;
+ m_context->beginAnnotation(rendererName, paintPhase, elementId, elementClass, elementTag);
+}
+
+void GraphicsContextAnnotator::finishAnnotation()
+{
+ ASSERT(m_context);
+ m_context->endAnnotation();
+}
+
+}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/GraphicsContextAnnotator.h b/chromium/third_party/WebKit/Source/core/rendering/GraphicsContextAnnotator.h
new file mode 100644
index 00000000000..5d0936e551e
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/rendering/GraphicsContextAnnotator.h
@@ -0,0 +1,68 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ * Copyright (C) 2013 Samsung Electronics. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef GraphicsContextAnnotator_h
+#define GraphicsContextAnnotator_h
+
+#define ANNOTATE_GRAPHICS_CONTEXT(paintInfo, renderer) \
+ GraphicsContextAnnotator scopedGraphicsContextAnnotator; \
+ if (UNLIKELY(paintInfo.context->annotationMode())) \
+ scopedGraphicsContextAnnotator.annotate(paintInfo, renderer)
+
+namespace WebCore {
+
+class GraphicsContext;
+struct PaintInfo;
+class RenderObject;
+
+class GraphicsContextAnnotator {
+public:
+ GraphicsContextAnnotator()
+ : m_context(0)
+ { }
+
+ ~GraphicsContextAnnotator()
+ {
+ if (UNLIKELY(m_context != 0))
+ finishAnnotation();
+ }
+
+ void annotate(const PaintInfo&, const RenderObject*);
+
+private:
+ void finishAnnotation();
+
+ GraphicsContext* m_context;
+};
+
+} // namespace WebCore
+
+#endif // GraphicsContextAnnotator_h
diff --git a/chromium/third_party/WebKit/Source/core/rendering/HitTestLocation.h b/chromium/third_party/WebKit/Source/core/rendering/HitTestLocation.h
index 3be7377b25c..7edcd8e03bc 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/HitTestLocation.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/HitTestLocation.h
@@ -22,10 +22,10 @@
#ifndef HitTestLocation_h
#define HitTestLocation_h
-#include "core/platform/graphics/FloatQuad.h"
-#include "core/platform/graphics/FloatRect.h"
-#include "core/platform/graphics/LayoutRect.h"
-#include "core/platform/graphics/RoundedRect.h"
+#include "platform/geometry/FloatQuad.h"
+#include "platform/geometry/FloatRect.h"
+#include "platform/geometry/LayoutRect.h"
+#include "platform/geometry/RoundedRect.h"
#include "wtf/Forward.h"
#include "wtf/ListHashSet.h"
#include "wtf/OwnPtr.h"
diff --git a/chromium/third_party/WebKit/Source/core/rendering/HitTestRequest.h b/chromium/third_party/WebKit/Source/core/rendering/HitTestRequest.h
index 1166fe33273..97dfa5165a7 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/HitTestRequest.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/HitTestRequest.h
@@ -35,7 +35,8 @@ public:
IgnoreClipping = 1 << 5,
SVGClipContent = 1 << 6,
TouchEvent = 1 << 7,
- DisallowShadowContent = 1 << 8,
+ // Deprecated. Instead of this, callers should call HitTestResult::setToNodesInDocumentTreeScope() explicitly.
+ ConfusingAndOftenMisusedDisallowShadowContent = 1 << 8,
AllowFrameScrollbars = 1 << 9,
AllowChildFrameContent = 1 << 10,
ChildFrameHitTest = 1 << 11,
@@ -57,7 +58,7 @@ public:
bool svgClipContent() const { return m_requestType & SVGClipContent; }
bool touchEvent() const { return m_requestType & TouchEvent; }
bool mouseEvent() const { return !touchEvent(); }
- bool disallowsShadowContent() const { return m_requestType & DisallowShadowContent; }
+ bool disallowsShadowContent() const { return m_requestType & ConfusingAndOftenMisusedDisallowShadowContent; }
bool allowsFrameScrollbars() const { return m_requestType & AllowFrameScrollbars; }
bool allowsChildFrameContent() const { return m_requestType & AllowChildFrameContent; }
bool isChildFrameHitTest() const { return m_requestType & ChildFrameHitTest; }
diff --git a/chromium/third_party/WebKit/Source/core/rendering/HitTestResult.cpp b/chromium/third_party/WebKit/Source/core/rendering/HitTestResult.cpp
index f8e4caafb58..ad4e162801f 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/HitTestResult.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/HitTestResult.cpp
@@ -38,11 +38,11 @@
#include "core/html/HTMLTextAreaElement.h"
#include "core/html/HTMLVideoElement.h"
#include "core/html/parser/HTMLParserIdioms.h"
-#include "core/page/Frame.h"
+#include "core/frame/Frame.h"
#include "core/page/FrameTree.h"
-#include "core/platform/Scrollbar.h"
-#include "core/rendering/HitTestLocation.h"
#include "core/rendering/RenderImage.h"
+#include "core/rendering/RenderTextFragment.h"
+#include "platform/scroll/Scrollbar.h"
namespace WebCore {
@@ -50,6 +50,7 @@ using namespace HTMLNames;
HitTestResult::HitTestResult()
: m_isOverWidget(false)
+ , m_isFirstLetter(false)
{
}
@@ -57,6 +58,7 @@ HitTestResult::HitTestResult(const LayoutPoint& point)
: m_hitTestLocation(point)
, m_pointInInnerNodeFrame(point)
, m_isOverWidget(false)
+ , m_isFirstLetter(false)
{
}
@@ -64,6 +66,7 @@ HitTestResult::HitTestResult(const LayoutPoint& centerPoint, unsigned topPadding
: m_hitTestLocation(centerPoint, topPadding, rightPadding, bottomPadding, leftPadding)
, m_pointInInnerNodeFrame(centerPoint)
, m_isOverWidget(false)
+ , m_isFirstLetter(false)
{
}
@@ -71,18 +74,21 @@ HitTestResult::HitTestResult(const HitTestLocation& other)
: m_hitTestLocation(other)
, m_pointInInnerNodeFrame(m_hitTestLocation.point())
, m_isOverWidget(false)
+ , m_isFirstLetter(false)
{
}
HitTestResult::HitTestResult(const HitTestResult& other)
: m_hitTestLocation(other.m_hitTestLocation)
, m_innerNode(other.innerNode())
+ , m_innerPossiblyPseudoNode(other.m_innerPossiblyPseudoNode)
, m_innerNonSharedNode(other.innerNonSharedNode())
, m_pointInInnerNodeFrame(other.m_pointInInnerNodeFrame)
, m_localPoint(other.localPoint())
, m_innerURLElement(other.URLElement())
, m_scrollbar(other.scrollbar())
, m_isOverWidget(other.isOverWidget())
+ , m_isFirstLetter(other.m_isFirstLetter)
{
// Only copy the NodeSet in case of rect hit test.
m_rectBasedTestResult = adoptPtr(other.m_rectBasedTestResult ? new NodeSet(*other.m_rectBasedTestResult) : 0);
@@ -96,11 +102,13 @@ HitTestResult& HitTestResult::operator=(const HitTestResult& other)
{
m_hitTestLocation = other.m_hitTestLocation;
m_innerNode = other.innerNode();
+ m_innerPossiblyPseudoNode = other.innerPossiblyPseudoNode();
m_innerNonSharedNode = other.innerNonSharedNode();
m_pointInInnerNodeFrame = other.m_pointInInnerNodeFrame;
m_localPoint = other.localPoint();
m_innerURLElement = other.URLElement();
m_scrollbar = other.scrollbar();
+ m_isFirstLetter = other.m_isFirstLetter;
m_isOverWidget = other.isOverWidget();
// Only copy the NodeSet in case of rect hit test.
@@ -109,6 +117,16 @@ HitTestResult& HitTestResult::operator=(const HitTestResult& other)
return *this;
}
+RenderObject* HitTestResult::renderer() const
+{
+ if (!m_innerNode)
+ return 0;
+ RenderObject* renderer = m_innerNode->renderer();
+ if (!m_isFirstLetter || !renderer || !renderer->isText() || !toRenderText(renderer)->isTextFragment())
+ return renderer;
+ return toRenderTextFragment(renderer)->firstRenderTextInFirstLetter();
+}
+
void HitTestResult::setToNodesInDocumentTreeScope()
{
if (Node* node = innerNode()) {
@@ -141,6 +159,7 @@ void HitTestResult::setToShadowHostIfInUserAgentShadowRoot()
void HitTestResult::setInnerNode(Node* n)
{
+ m_innerPossiblyPseudoNode = n;
if (n && n->isPseudoElement())
n = n->parentOrShadowHostNode();
m_innerNode = n;
@@ -181,7 +200,7 @@ Frame* HitTestResult::targetFrame() const
if (!frame)
return 0;
- return frame->tree()->find(m_innerURLElement->target());
+ return frame->tree().find(m_innerURLElement->target());
}
bool HitTestResult::isSelected() const
@@ -229,29 +248,22 @@ String HitTestResult::title(TextDirection& dir) const
return String();
}
-String displayString(const String& string, const Node* node)
-{
- if (!node)
- return string;
- return node->document().displayStringModifiedByEncoding(string);
-}
-
-String HitTestResult::altDisplayString() const
+const AtomicString& HitTestResult::altDisplayString() const
{
if (!m_innerNonSharedNode)
- return String();
+ return nullAtom;
if (m_innerNonSharedNode->hasTagName(imgTag)) {
- HTMLImageElement* image = toHTMLImageElement(m_innerNonSharedNode.get());
- return displayString(image->getAttribute(altAttr), m_innerNonSharedNode.get());
+ HTMLImageElement* image = toHTMLImageElement(m_innerNonSharedNode);
+ return image->getAttribute(altAttr);
}
if (m_innerNonSharedNode->hasTagName(inputTag)) {
- HTMLInputElement* input = toHTMLInputElement(m_innerNonSharedNode.get());
- return displayString(input->alt(), m_innerNonSharedNode.get());
+ HTMLInputElement* input = toHTMLInputElement(m_innerNonSharedNode);
+ return input->alt();
}
- return String();
+ return nullAtom;
}
Image* HitTestResult::image() const
@@ -291,8 +303,7 @@ KURL HitTestResult::absoluteImageURL() const
|| m_innerNonSharedNode->hasTagName(objectTag)
|| m_innerNonSharedNode->hasTagName(SVGNames::imageTag)
) {
- Element* element = toElement(m_innerNonSharedNode.get());
- urlString = element->imageSourceURL();
+ urlString = toElement(m_innerNonSharedNode)->imageSourceURL();
} else
return KURL();
@@ -341,7 +352,7 @@ bool HitTestResult::isLiveLink() const
return false;
if (isHTMLAnchorElement(m_innerURLElement.get()))
- return toHTMLAnchorElement(m_innerURLElement.get())->isLiveLink();
+ return toHTMLAnchorElement(m_innerURLElement)->isLiveLink();
if (m_innerURLElement->hasTagName(SVGNames::aTag))
return m_innerURLElement->isLink();
@@ -360,12 +371,17 @@ bool HitTestResult::isMisspelled() const
makeRange(pos, pos).get(), DocumentMarker::MisspellingMarkers()).size() > 0;
}
+bool HitTestResult::isOverLink() const
+{
+ return m_innerURLElement && m_innerURLElement->isLink();
+}
+
String HitTestResult::titleDisplayString() const
{
if (!m_innerURLElement)
return String();
- return displayString(m_innerURLElement->title(), m_innerURLElement.get());
+ return m_innerURLElement->title();
}
String HitTestResult::textContent() const
@@ -388,7 +404,7 @@ bool HitTestResult::isContentEditable() const
return true;
if (m_innerNonSharedNode->hasTagName(inputTag))
- return toHTMLInputElement(m_innerNonSharedNode.get())->isTextField();
+ return toHTMLInputElement(m_innerNonSharedNode)->isTextField();
return m_innerNonSharedNode->rendererIsEditable();
}
@@ -437,13 +453,17 @@ void HitTestResult::append(const HitTestResult& other)
{
ASSERT(isRectBasedTest() && other.isRectBasedTest());
+ if (!m_scrollbar && other.scrollbar()) {
+ setScrollbar(other.scrollbar());
+ }
+
if (!m_innerNode && other.innerNode()) {
m_innerNode = other.innerNode();
+ m_innerPossiblyPseudoNode = other.innerPossiblyPseudoNode();
m_innerNonSharedNode = other.innerNonSharedNode();
m_localPoint = other.localPoint();
m_pointInInnerNodeFrame = other.m_pointInInnerNodeFrame;
m_innerURLElement = other.URLElement();
- m_scrollbar = other.scrollbar();
m_isOverWidget = other.isOverWidget();
}
@@ -485,9 +505,10 @@ Node* HitTestResult::targetNode() const
Element* HitTestResult::innerElement() const
{
- for (Node* node = m_innerNode.get(); node; node = NodeRenderingTraversal::parent(node))
+ for (Node* node = m_innerNode.get(); node; node = NodeRenderingTraversal::parent(node)) {
if (node->isElementNode())
return toElement(node);
+ }
return 0;
}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/HitTestResult.h b/chromium/third_party/WebKit/Source/core/rendering/HitTestResult.h
index c22efab01be..490596e4035 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/HitTestResult.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/HitTestResult.h
@@ -22,12 +22,12 @@
#ifndef HitTestResult_h
#define HitTestResult_h
-#include "core/platform/graphics/FloatQuad.h"
-#include "core/platform/graphics/FloatRect.h"
-#include "core/platform/graphics/LayoutRect.h"
-#include "core/platform/text/TextDirection.h"
#include "core/rendering/HitTestLocation.h"
#include "core/rendering/HitTestRequest.h"
+#include "platform/geometry/FloatQuad.h"
+#include "platform/geometry/FloatRect.h"
+#include "platform/geometry/LayoutRect.h"
+#include "platform/text/TextDirection.h"
#include "wtf/Forward.h"
#include "wtf/ListHashSet.h"
#include "wtf/OwnPtr.h"
@@ -41,6 +41,7 @@ class HTMLMediaElement;
class Image;
class KURL;
class Node;
+class RenderObject;
class RenderRegion;
class Scrollbar;
@@ -58,6 +59,7 @@ public:
HitTestResult& operator=(const HitTestResult&);
Node* innerNode() const { return m_innerNode.get(); }
+ Node* innerPossiblyPseudoNode() const { return m_innerPossiblyPseudoNode.get(); }
Element* innerElement() const;
Node* innerNonSharedNode() const { return m_innerNonSharedNode.get(); }
Element* URLElement() const { return m_innerURLElement.get(); }
@@ -80,6 +82,8 @@ public:
const LayoutPoint& localPoint() const { return m_localPoint; }
void setLocalPoint(const LayoutPoint& p) { m_localPoint = p; }
+ RenderObject* renderer() const;
+
void setToNodesInDocumentTreeScope();
void setToShadowHostIfInUserAgentShadowRoot();
@@ -89,13 +93,14 @@ public:
void setInnerNonSharedNode(Node*);
void setURLElement(Element*);
void setScrollbar(Scrollbar*);
+ void setIsFirstLetter(bool b) { m_isFirstLetter = b; }
void setIsOverWidget(bool b) { m_isOverWidget = b; }
Frame* targetFrame() const;
bool isSelected() const;
String spellingToolTip(TextDirection&) const;
String title(TextDirection&) const;
- String altDisplayString() const;
+ const AtomicString& altDisplayString() const;
String titleDisplayString() const;
Image* image() const;
IntRect imageRect() const;
@@ -107,6 +112,7 @@ public:
bool isMisspelled() const;
bool isContentEditable() const;
+ bool isOverLink() const;
// Returns true if it is rect-based hit test and needs to continue until the rect is fully
// enclosed by the boundaries of a node.
bool addNodeToRectBasedTestResult(Node*, const HitTestRequest&, const HitTestLocation& pointInContainer, const LayoutRect& = LayoutRect());
@@ -127,6 +133,7 @@ private:
HitTestLocation m_hitTestLocation;
RefPtr<Node> m_innerNode;
+ RefPtr<Node> m_innerPossiblyPseudoNode;
RefPtr<Node> m_innerNonSharedNode;
LayoutPoint m_pointInInnerNodeFrame; // The hit-tested point in innerNode frame coordinates.
LayoutPoint m_localPoint; // A point in the local coordinate space of m_innerNonSharedNode's renderer. Allows us to efficiently
@@ -134,12 +141,11 @@ private:
RefPtr<Element> m_innerURLElement;
RefPtr<Scrollbar> m_scrollbar;
bool m_isOverWidget; // Returns true if we are over a widget (and not in the border/padding area of a RenderWidget for example).
+ bool m_isFirstLetter;
mutable OwnPtr<NodeSet> m_rectBasedTestResult;
};
-String displayString(const String&, const Node*);
-
} // namespace WebCore
#endif // HitTestResult_h
diff --git a/chromium/third_party/WebKit/Source/core/rendering/HitTestingTransformState.cpp b/chromium/third_party/WebKit/Source/core/rendering/HitTestingTransformState.cpp
index c7c94a6a66d..93329a34062 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/HitTestingTransformState.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/HitTestingTransformState.cpp
@@ -26,7 +26,7 @@
#include "config.h"
#include "core/rendering/HitTestingTransformState.h"
-#include "core/platform/graphics/LayoutRect.h"
+#include "platform/geometry/LayoutRect.h"
#include "wtf/PassOwnPtr.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/rendering/HitTestingTransformState.h b/chromium/third_party/WebKit/Source/core/rendering/HitTestingTransformState.h
index bd8131235a9..86fbc40f9a6 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/HitTestingTransformState.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/HitTestingTransformState.h
@@ -26,11 +26,11 @@
#ifndef HitTestingTransformState_h
#define HitTestingTransformState_h
-#include "core/platform/graphics/FloatPoint.h"
-#include "core/platform/graphics/FloatQuad.h"
-#include "core/platform/graphics/IntSize.h"
-#include "core/platform/graphics/transforms/AffineTransform.h"
-#include "core/platform/graphics/transforms/TransformationMatrix.h"
+#include "platform/geometry/FloatQuad.h"
+#include "platform/geometry/FloatPoint.h"
+#include "platform/geometry/IntSize.h"
+#include "platform/transforms/AffineTransform.h"
+#include "platform/transforms/TransformationMatrix.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefCounted.h"
diff --git a/chromium/third_party/WebKit/Source/core/rendering/ImageQualityController.cpp b/chromium/third_party/WebKit/Source/core/rendering/ImageQualityController.cpp
index ebe6fd79378..ef4c23b73c8 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/ImageQualityController.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/ImageQualityController.cpp
@@ -31,9 +31,9 @@
#include "config.h"
#include "core/rendering/ImageQualityController.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameView.h"
-#include "core/platform/graphics/GraphicsContext.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
+#include "platform/graphics/GraphicsContext.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/rendering/ImageQualityController.h b/chromium/third_party/WebKit/Source/core/rendering/ImageQualityController.h
index c6487f11333..a9e8b108d88 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/ImageQualityController.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/ImageQualityController.h
@@ -31,12 +31,12 @@
#ifndef ImageQualityController_h
#define ImageQualityController_h
-#include "core/platform/graphics/Image.h"
-#include "core/platform/graphics/ImageOrientation.h"
-#include "core/platform/graphics/ImageSource.h"
-#include "core/platform/graphics/IntSize.h"
-#include "core/platform/graphics/LayoutSize.h"
#include "core/rendering/RenderObject.h"
+#include "platform/geometry/IntSize.h"
+#include "platform/geometry/LayoutSize.h"
+#include "platform/graphics/Image.h"
+#include "platform/graphics/ImageOrientation.h"
+#include "platform/graphics/ImageSource.h"
#include "wtf/HashMap.h"
namespace WebCore {
@@ -44,10 +44,10 @@ namespace WebCore {
typedef HashMap<const void*, LayoutSize> LayerSizeMap;
typedef HashMap<RenderObject*, LayerSizeMap> ObjectLayerSizeMap;
-class ImageQualityController {
+class ImageQualityController FINAL {
WTF_MAKE_NONCOPYABLE(ImageQualityController); WTF_MAKE_FAST_ALLOCATED;
public:
- virtual ~ImageQualityController();
+ ~ImageQualityController();
static ImageQualityController* imageQualityController();
diff --git a/chromium/third_party/WebKit/Source/core/rendering/InlineBox.cpp b/chromium/third_party/WebKit/Source/core/rendering/InlineBox.cpp
index fec2de077f7..0e1e21ea874 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/InlineBox.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/InlineBox.cpp
@@ -20,12 +20,12 @@
#include "config.h"
#include "core/rendering/InlineBox.h"
-#include "core/platform/Partitions.h"
-#include "core/platform/graphics/FontMetrics.h"
#include "core/rendering/InlineFlowBox.h"
#include "core/rendering/PaintInfo.h"
-#include "core/rendering/RenderBlock.h"
+#include "core/rendering/RenderBlockFlow.h"
#include "core/rendering/RootInlineBox.h"
+#include "platform/Partitions.h"
+#include "platform/fonts/FontMetrics.h"
#ifndef NDEBUG
#include <stdio.h>
@@ -49,10 +49,6 @@ struct SameSizeAsInlineBox {
COMPILE_ASSERT(sizeof(InlineBox) == sizeof(SameSizeAsInlineBox), InlineBox_size_guard);
#ifndef NDEBUG
-static bool inInlineBoxDetach;
-#endif
-
-#ifndef NDEBUG
InlineBox::~InlineBox()
{
@@ -320,7 +316,7 @@ FloatPoint InlineBox::locationIncludingFlipping()
{
if (!renderer()->style()->isFlippedBlocksWritingMode())
return FloatPoint(x(), y());
- RenderBlock* block = root()->block();
+ RenderBlockFlow* block = root()->block();
if (block->style()->isHorizontalWritingMode())
return FloatPoint(x(), block->height() - height() - y());
else
diff --git a/chromium/third_party/WebKit/Source/core/rendering/InlineBox.h b/chromium/third_party/WebKit/Source/core/rendering/InlineBox.h
index fdb04d5c96d..5803cd17e2b 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/InlineBox.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/InlineBox.h
@@ -21,8 +21,8 @@
#ifndef InlineBox_h
#define InlineBox_h
-#include "core/platform/text/TextDirection.h"
#include "core/rendering/RenderBoxModelObject.h"
+#include "platform/text/TextDirection.h"
namespace WebCore {
@@ -101,7 +101,6 @@ public:
void* operator new(size_t);
void operator delete(void*);
-public:
#ifndef NDEBUG
void showTreeForThis() const;
void showLineTreeForThis() const;
@@ -198,8 +197,8 @@ public:
const FloatPoint& topLeft() const { return m_topLeft; }
- float width() const { return isHorizontal() ? logicalWidth() : logicalHeight(); }
- float height() const { return isHorizontal() ? logicalHeight() : logicalWidth(); }
+ float width() const { return isHorizontal() ? logicalWidth() : hasVirtualLogicalHeight() ? virtualLogicalHeight() : logicalHeight(); }
+ float height() const { return isHorizontal() ? hasVirtualLogicalHeight() ? virtualLogicalHeight() : logicalHeight() : logicalWidth(); }
FloatSize size() const { return FloatSize(width(), height()); }
float right() const { return left() + width(); }
float bottom() const { return top() + height(); }
@@ -295,18 +294,6 @@ public:
bool dirOverride() const { return m_bitfields.dirOverride(); }
void setDirOverride(bool dirOverride) { m_bitfields.setDirOverride(dirOverride); }
-private:
- InlineBox* m_next; // The next element on the same line as us.
- InlineBox* m_prev; // The previous element on the same line as us.
-
- InlineFlowBox* m_parent; // The box that contains us.
-
-public:
- RenderObject* m_renderer;
-
- FloatPoint m_topLeft;
- float m_logicalWidth;
-
#define ADD_BOOLEAN_BITFIELD(name, Name) \
private:\
unsigned m_##name : 1;\
@@ -386,7 +373,10 @@ public:
#undef ADD_BOOLEAN_BITFIELD
private:
- InlineBoxBitfields m_bitfields;
+ InlineBox* m_next; // The next element on the same line as us.
+ InlineBox* m_prev; // The previous element on the same line as us.
+
+ InlineFlowBox* m_parent; // The box that contains us.
protected:
// For RootInlineBox
@@ -408,8 +398,15 @@ protected:
// For InlineFlowBox and InlineTextBox
bool extracted() const { return m_bitfields.extracted(); }
-#ifndef NDEBUG
+ RenderObject* m_renderer;
+
+ FloatPoint m_topLeft;
+ float m_logicalWidth;
+
private:
+ InlineBoxBitfields m_bitfields;
+
+#ifndef NDEBUG
bool m_hasBadParent;
#endif
};
@@ -427,6 +424,9 @@ inline void InlineBox::setHasBadParent()
}
#endif
+#define DEFINE_INLINE_BOX_TYPE_CASTS(typeName) \
+ DEFINE_TYPE_CASTS(typeName, InlineBox, box, box->is##typeName(), box.is##typeName())
+
} // namespace WebCore
#ifndef NDEBUG
diff --git a/chromium/third_party/WebKit/Source/core/rendering/InlineFlowBox.cpp b/chromium/third_party/WebKit/Source/core/rendering/InlineFlowBox.cpp
index f33c69ee075..68952fc6e18 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/InlineFlowBox.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/InlineFlowBox.cpp
@@ -22,8 +22,6 @@
#include "CSSPropertyNames.h"
#include "core/dom/Document.h"
-#include "core/platform/graphics/Font.h"
-#include "core/platform/graphics/GraphicsContextStateSaver.h"
#include "core/rendering/HitTestResult.h"
#include "core/rendering/InlineTextBox.h"
#include "core/rendering/RenderBlock.h"
@@ -35,6 +33,8 @@
#include "core/rendering/RenderRubyText.h"
#include "core/rendering/RenderView.h"
#include "core/rendering/RootInlineBox.h"
+#include "platform/fonts/Font.h"
+#include "platform/graphics/GraphicsContextStateSaver.h"
#include <math.h>
@@ -728,7 +728,6 @@ void InlineFlowBox::placeBoxesInBlockDirection(LayoutUnit top, LayoutUnit maxHei
}
}
-#if ENABLE(CSS3_TEXT)
void InlineFlowBox::computeMaxLogicalTop(float& maxLogicalTop) const
{
for (InlineBox* curr = firstChild(); curr; curr = curr->nextOnLine()) {
@@ -745,7 +744,6 @@ void InlineFlowBox::computeMaxLogicalTop(float& maxLogicalTop) const
maxLogicalTop = max<float>(maxLogicalTop, localMaxLogicalTop);
}
}
-#endif // CSS3_TEXT
void InlineFlowBox::flipLinesInBlockDirection(LayoutUnit lineTop, LayoutUnit lineBottom)
{
diff --git a/chromium/third_party/WebKit/Source/core/rendering/InlineFlowBox.h b/chromium/third_party/WebKit/Source/core/rendering/InlineFlowBox.h
index e81e426f2ea..066098fdac8 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/InlineFlowBox.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/InlineFlowBox.h
@@ -317,11 +317,10 @@ protected:
InlineFlowBox* m_prevLineBox; // The previous box that also uses our RenderObject
InlineFlowBox* m_nextLineBox; // The next box that also uses our RenderObject
-#if ENABLE(CSS3_TEXT)
// Maximum logicalTop among all children of an InlineFlowBox. Used to
// calculate the offset for TextUnderlinePositionUnder.
void computeMaxLogicalTop(float& maxLogicalTop) const;
-#endif // CSS3_TEXT
+
private:
unsigned m_includeLogicalLeftEdge : 1;
unsigned m_includeLogicalRightEdge : 1;
@@ -351,20 +350,7 @@ private:
#endif
};
-inline InlineFlowBox* toInlineFlowBox(InlineBox* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isInlineFlowBox());
- return static_cast<InlineFlowBox*>(object);
-}
-
-inline const InlineFlowBox* toInlineFlowBox(const InlineBox* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isInlineFlowBox());
- return static_cast<const InlineFlowBox*>(object);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toInlineFlowBox(const InlineFlowBox*);
+DEFINE_INLINE_BOX_TYPE_CASTS(InlineFlowBox);
#ifdef NDEBUG
inline void InlineFlowBox::checkConsistency() const
diff --git a/chromium/third_party/WebKit/Source/core/rendering/InlineIterator.h b/chromium/third_party/WebKit/Source/core/rendering/InlineIterator.h
index fa5a8ad7431..c0c30d9ad8a 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/InlineIterator.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/InlineIterator.h
@@ -24,7 +24,7 @@
#define InlineIterator_h
#include "core/rendering/BidiRun.h"
-#include "core/rendering/RenderBlock.h"
+#include "core/rendering/RenderBlockFlow.h"
#include "core/rendering/RenderText.h"
#include "wtf/StdLibExtras.h"
@@ -71,6 +71,8 @@ public:
}
RenderObject* object() const { return m_obj; }
+ void setObject(RenderObject* object) { m_obj = object; }
+
unsigned offset() const { return m_pos; }
RenderObject* root() const { return m_root; }
@@ -78,13 +80,13 @@ public:
void increment(InlineBidiResolver* = 0, IncrementRule = FastIncrementInTextNode);
bool atEnd() const;
- inline bool atTextParagraphSeparator()
+ inline bool atTextParagraphSeparator() const
{
return m_obj && m_obj->preservesNewline() && m_obj->isText() && toRenderText(m_obj)->textLength()
&& !toRenderText(m_obj)->isWordBreak() && toRenderText(m_obj)->characterAt(m_pos) == '\n';
}
- inline bool atParagraphSeparator()
+ inline bool atParagraphSeparator() const
{
return (m_obj && m_obj->isBR()) || atTextParagraphSeparator();
}
@@ -96,22 +98,22 @@ public:
private:
RenderObject* m_root;
+ RenderObject* m_obj;
- // FIXME: These should be private.
+// FIXME: These should be private.
public:
- RenderObject* m_obj;
unsigned m_pos;
int m_nextBreakablePosition;
};
inline bool operator==(const InlineIterator& it1, const InlineIterator& it2)
{
- return it1.m_pos == it2.m_pos && it1.m_obj == it2.m_obj;
+ return it1.m_pos == it2.m_pos && it1.object() == it2.object();
}
inline bool operator!=(const InlineIterator& it1, const InlineIterator& it2)
{
- return it1.m_pos != it2.m_pos || it1.m_obj != it2.m_obj;
+ return it1.m_pos != it2.m_pos || it1.object() != it2.object();
}
static inline WTF::Unicode::Direction embedCharFromDirection(TextDirection dir, EUnicodeBidi unicodeBidi)
@@ -326,7 +328,7 @@ inline void InlineIterator::fastIncrementInTextNode()
m_pos++;
}
-// FIXME: This is used by RenderBlock for simplified layout, and has nothing to do with bidi
+// FIXME: This is used by RenderBlockFlow for simplified layout, and has nothing to do with bidi
// it shouldn't use functions called bidiFirst and bidiNext.
class InlineWalker {
public:
@@ -357,12 +359,28 @@ private:
bool m_atEndOfInline;
};
+static inline bool endOfLineHasIsolatedObjectAncestor(const InlineIterator& isolatedIterator, const InlineIterator& ancestorItertor)
+{
+ if (!isolatedIterator.object() || !isIsolated(isolatedIterator.object()->style()->unicodeBidi()))
+ return false;
+
+ RenderObject* innerIsolatedObject = isolatedIterator.object();
+ while (innerIsolatedObject && innerIsolatedObject != isolatedIterator.root()) {
+ if (innerIsolatedObject == ancestorItertor.object())
+ return true;
+ innerIsolatedObject = innerIsolatedObject->parent();
+ }
+ return false;
+}
+
inline void InlineIterator::increment(InlineBidiResolver* resolver, IncrementRule rule)
{
if (!m_obj)
return;
- if (resolver && resolver->inIsolate() && rule == FastIncrementInIsolatedRenderer) {
+ if (rule == FastIncrementInIsolatedRenderer
+ && resolver && resolver->inIsolate()
+ && !endOfLineHasIsolatedObjectAncestor(resolver->endOfLine(), resolver->position())) {
moveTo(bidiNextSkippingEmptyInlines(m_root, m_obj, resolver), 0);
return;
}
@@ -420,15 +438,15 @@ inline void InlineBidiResolver::increment()
}
template <>
-inline bool InlineBidiResolver::isEndOfParagraph(const InlineIterator& end)
+inline bool InlineBidiResolver::isEndOfLine(const InlineIterator& end)
{
- bool inEndOfParagraph = m_current == end || m_current.atEnd() || (inIsolate() && m_current.m_obj == end.m_obj);
- if (inIsolate() && inEndOfParagraph) {
- m_current.moveTo(m_current.m_obj, end.m_pos, m_current.m_nextBreakablePosition);
+ bool inEndOfLine = m_current == end || m_current.atEnd() || (inIsolate() && m_current.object() == end.object());
+ if (inIsolate() && inEndOfLine) {
+ m_current.moveTo(m_current.object(), end.m_pos, m_current.m_nextBreakablePosition);
m_last = m_current;
updateStatusLastFromCurrentDirection(WTF::Unicode::OtherNeutral);
}
- return inEndOfParagraph;
+ return inEndOfLine;
}
static inline bool isIsolatedInline(RenderObject* object)
@@ -466,16 +484,27 @@ static inline unsigned numberOfIsolateAncestors(const InlineIterator& iter)
// FIXME: This belongs on InlineBidiResolver, except it's a template specialization
// of BidiResolver which knows nothing about RenderObjects.
-static inline void addPlaceholderRunForIsolatedInline(InlineBidiResolver& resolver, RenderObject* obj, unsigned pos)
+static inline BidiRun* addPlaceholderRunForIsolatedInline(InlineBidiResolver& resolver, RenderObject* obj, unsigned pos)
{
ASSERT(obj);
- BidiRun* isolatedRun = new BidiRun(pos, 0, obj, resolver.context(), resolver.dir());
+ BidiRun* isolatedRun = new BidiRun(pos, pos, obj, resolver.context(), resolver.dir());
resolver.runs().addRun(isolatedRun);
// FIXME: isolatedRuns() could be a hash of object->run and then we could cheaply
// ASSERT here that we didn't create multiple objects for the same inline.
resolver.isolatedRuns().append(isolatedRun);
+ return isolatedRun;
}
+static inline BidiRun* createRun(int start, int end, RenderObject* obj, InlineBidiResolver& resolver)
+{
+ return new BidiRun(start, end, obj, resolver.context(), resolver.dir());
+}
+
+enum AppendRunBehavior {
+ AppendingFakeRun,
+ AppendingRunsForObject
+};
+
class IsolateTracker {
public:
explicit IsolateTracker(unsigned nestedIsolateCount)
@@ -484,6 +513,11 @@ public:
{
}
+ void setMidpointStateForRootIsolate(const LineMidpointState& midpointState)
+ {
+ m_midpointStateForRootIsolate = midpointState;
+ }
+
void enterIsolate() { m_nestedIsolateCount++; }
void exitIsolate()
{
@@ -498,33 +532,85 @@ public:
void embed(WTF::Unicode::Direction, BidiEmbeddingSource) { }
void commitExplicitEmbedding() { }
- void addFakeRunIfNecessary(RenderObject* obj, unsigned pos, InlineBidiResolver& resolver)
+ void addFakeRunIfNecessary(RenderObject* obj, unsigned pos, unsigned end, InlineBidiResolver& resolver)
{
// We only need to add a fake run for a given isolated span once during each call to createBidiRunsForLine.
// We'll be called for every span inside the isolated span so we just ignore subsequent calls.
// We also avoid creating a fake run until we hit a child that warrants one, e.g. we skip floats.
- if (m_haveAddedFakeRunForRootIsolate || RenderBlock::shouldSkipCreatingRunsForObject(obj))
+ if (RenderBlockFlow::shouldSkipCreatingRunsForObject(obj))
return;
- m_haveAddedFakeRunForRootIsolate = true;
+ if (!m_haveAddedFakeRunForRootIsolate) {
+ BidiRun* run = addPlaceholderRunForIsolatedInline(resolver, obj, pos);
+ resolver.setMidpointStateForIsolatedRun(run, m_midpointStateForRootIsolate);
+ m_haveAddedFakeRunForRootIsolate = true;
+ }
// obj and pos together denote a single position in the inline, from which the parsing of the isolate will start.
// We don't need to mark the end of the run because this is implicit: it is either endOfLine or the end of the
// isolate, when we call createBidiRunsForLine it will stop at whichever comes first.
- addPlaceholderRunForIsolatedInline(resolver, obj, pos);
- // FIXME: Inline isolates don't work properly with collapsing whitespace, see webkit.org/b/109624
- // For now, if we enter an isolate between midpoints, we increment our current midpoint or else
- // we'll leave the isolate and ignore the content that follows.
- MidpointState<InlineIterator>& midpointState = resolver.midpointState();
- if (midpointState.betweenMidpoints && midpointState.midpoints[midpointState.currentMidpoint].object() == obj) {
- midpointState.betweenMidpoints = false;
- ++midpointState.currentMidpoint;
- }
}
private:
unsigned m_nestedIsolateCount;
bool m_haveAddedFakeRunForRootIsolate;
+ LineMidpointState m_midpointStateForRootIsolate;
};
+static void inline appendRunObjectIfNecessary(RenderObject* obj, unsigned start, unsigned end, InlineBidiResolver& resolver, AppendRunBehavior behavior, IsolateTracker& tracker)
+{
+ if (behavior == AppendingFakeRun)
+ tracker.addFakeRunIfNecessary(obj, start, end, resolver);
+ else
+ resolver.runs().addRun(createRun(start, end, obj, resolver));
+}
+
+static void adjustMidpointsAndAppendRunsForObjectIfNeeded(RenderObject* obj, unsigned start, unsigned end, InlineBidiResolver& resolver, AppendRunBehavior behavior, IsolateTracker& tracker)
+{
+ if (start > end || RenderBlockFlow::shouldSkipCreatingRunsForObject(obj))
+ return;
+
+ LineMidpointState& lineMidpointState = resolver.midpointState();
+ bool haveNextMidpoint = (lineMidpointState.currentMidpoint < lineMidpointState.numMidpoints);
+ InlineIterator nextMidpoint;
+ if (haveNextMidpoint)
+ nextMidpoint = lineMidpointState.midpoints[lineMidpointState.currentMidpoint];
+ if (lineMidpointState.betweenMidpoints) {
+ if (!(haveNextMidpoint && nextMidpoint.object() == obj))
+ return;
+ // This is a new start point. Stop ignoring objects and
+ // adjust our start.
+ lineMidpointState.betweenMidpoints = false;
+ start = nextMidpoint.m_pos;
+ lineMidpointState.currentMidpoint++;
+ if (start < end)
+ return adjustMidpointsAndAppendRunsForObjectIfNeeded(obj, start, end, resolver, behavior, tracker);
+ } else {
+ if (!haveNextMidpoint || (obj != nextMidpoint.object())) {
+ appendRunObjectIfNecessary(obj, start, end, resolver, behavior, tracker);
+ return;
+ }
+
+ // An end midpoint has been encountered within our object. We
+ // need to go ahead and append a run with our endpoint.
+ if (nextMidpoint.m_pos + 1 <= end) {
+ lineMidpointState.betweenMidpoints = true;
+ lineMidpointState.currentMidpoint++;
+ if (nextMidpoint.m_pos != UINT_MAX) { // UINT_MAX means stop at the object and don't nclude any of it.
+ if (nextMidpoint.m_pos + 1 > start)
+ appendRunObjectIfNecessary(obj, start, nextMidpoint.m_pos + 1, resolver, behavior, tracker);
+ return adjustMidpointsAndAppendRunsForObjectIfNeeded(obj, nextMidpoint.m_pos + 1, end, resolver, behavior, tracker);
+ }
+ } else {
+ appendRunObjectIfNecessary(obj, start, end, resolver, behavior, tracker);
+ }
+ }
+}
+
+static inline void addFakeRunIfNecessary(RenderObject* obj, unsigned start, unsigned end, InlineBidiResolver& resolver, IsolateTracker& tracker)
+{
+ tracker.setMidpointStateForRootIsolate(resolver.midpointState());
+ adjustMidpointsAndAppendRunsForObjectIfNeeded(obj, start, obj->length(), resolver, AppendingFakeRun, tracker);
+}
+
template <>
inline void InlineBidiResolver::appendRun()
{
@@ -534,31 +620,38 @@ inline void InlineBidiResolver::appendRun()
// FIXME: Could this initialize from this->inIsolate() instead of walking up the render tree?
IsolateTracker isolateTracker(numberOfIsolateAncestors(m_sor));
int start = m_sor.m_pos;
- RenderObject* obj = m_sor.m_obj;
- while (obj && obj != m_eor.m_obj && obj != endOfLine.m_obj) {
+ RenderObject* obj = m_sor.object();
+ while (obj && obj != m_eor.object() && obj != m_endOfRunAtEndOfLine.object()) {
if (isolateTracker.inIsolate())
- isolateTracker.addFakeRunIfNecessary(obj, start, *this);
+ addFakeRunIfNecessary(obj, start, obj->length(), *this, isolateTracker);
else
- RenderBlock::appendRunsForObject(m_runs, start, obj->length(), obj, *this);
+ adjustMidpointsAndAppendRunsForObjectIfNeeded(obj, start, obj->length(), *this, AppendingRunsForObject, isolateTracker);
// FIXME: start/obj should be an InlineIterator instead of two separate variables.
start = 0;
obj = bidiNextSkippingEmptyInlines(m_sor.root(), obj, &isolateTracker);
}
- if (obj) {
- unsigned pos = obj == m_eor.m_obj ? m_eor.m_pos : INT_MAX;
- if (obj == endOfLine.m_obj && endOfLine.m_pos <= pos) {
+ bool isEndOfLine = obj == m_endOfLine.object() && !m_endOfLine.m_pos;
+ if (obj && !isEndOfLine) {
+ unsigned pos = obj == m_eor.object() ? m_eor.m_pos : INT_MAX;
+ if (obj == m_endOfRunAtEndOfLine.object() && m_endOfRunAtEndOfLine.m_pos <= pos) {
m_reachedEndOfLine = true;
- pos = endOfLine.m_pos;
+ pos = m_endOfRunAtEndOfLine.m_pos;
}
// It's OK to add runs for zero-length RenderObjects, just don't make the run larger than it should be
int end = obj->length() ? pos + 1 : 0;
if (isolateTracker.inIsolate())
- isolateTracker.addFakeRunIfNecessary(obj, start, *this);
+ addFakeRunIfNecessary(obj, start, end, *this, isolateTracker);
else
- RenderBlock::appendRunsForObject(m_runs, start, end, obj, *this);
+ adjustMidpointsAndAppendRunsForObjectIfNeeded(obj, start, end, *this, AppendingRunsForObject, isolateTracker);
}
- m_eor.increment();
+ if (isEndOfLine)
+ m_reachedEndOfLine = true;
+ // If isolateTrack is inIsolate, the next |start of run| can not be the current isolated renderer.
+ if (isolateTracker.inIsolate())
+ m_eor.moveTo(bidiNextSkippingEmptyInlines(m_eor.root(), m_eor.object()), 0);
+ else
+ m_eor.increment();
m_sor = m_eor;
}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/InlineTextBox.cpp b/chromium/third_party/WebKit/Source/core/rendering/InlineTextBox.cpp
index 2f909808ce8..60a35deccf1 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/InlineTextBox.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/InlineTextBox.cpp
@@ -29,12 +29,10 @@
#include "core/dom/Text.h"
#include "core/editing/Editor.h"
#include "core/editing/InputMethodController.h"
-#include "core/page/Frame.h"
+#include "core/frame/Frame.h"
#include "core/page/Page.h"
-#include "core/page/Settings.h"
-#include "core/platform/graphics/DrawLooper.h"
-#include "core/platform/graphics/FontCache.h"
-#include "core/platform/graphics/GraphicsContextStateSaver.h"
+#include "core/frame/Settings.h"
+#include "core/rendering/AbstractInlineTextBox.h"
#include "core/rendering/EllipsisBox.h"
#include "core/rendering/HitTestResult.h"
#include "core/rendering/PaintInfo.h"
@@ -44,8 +42,12 @@
#include "core/rendering/RenderRubyRun.h"
#include "core/rendering/RenderRubyText.h"
#include "core/rendering/RenderTheme.h"
-#include "core/rendering/style/ShadowData.h"
+#include "core/rendering/style/ShadowList.h"
#include "core/rendering/svg/SVGTextRunRenderingContext.h"
+#include "platform/fonts/FontCache.h"
+#include "platform/fonts/WidthIterator.h"
+#include "platform/graphics/DrawLooper.h"
+#include "platform/graphics/GraphicsContextStateSaver.h"
#include "wtf/Vector.h"
#include "wtf/text/CString.h"
#include "wtf/text/StringBuilder.h"
@@ -69,6 +71,8 @@ static const int misspellingLineThickness = 3;
void InlineTextBox::destroy()
{
+ AbstractInlineTextBox::willDestroy(this);
+
if (!knownToHaveNoOverflow() && gTextBoxesWithOverflow)
gTextBoxesWithOverflow->remove(this);
InlineBox::destroy();
@@ -265,8 +269,8 @@ float InlineTextBox::placeEllipsisBox(bool flowIsLTR, float visibleLeftEdge, flo
// Criteria for full truncation:
// LTR: the left edge of the ellipsis is to the left of our text run.
// RTL: the right edge of the ellipsis is to the right of our text run.
- bool ltrFullTruncation = flowIsLTR && ellipsisX <= left();
- bool rtlFullTruncation = !flowIsLTR && ellipsisX >= left() + logicalWidth();
+ bool ltrFullTruncation = flowIsLTR && ellipsisX <= logicalLeft();
+ bool rtlFullTruncation = !flowIsLTR && ellipsisX >= logicalLeft() + logicalWidth();
if (ltrFullTruncation || rtlFullTruncation) {
// Too far. Just set full truncation, but return -1 and let the ellipsis just be placed at the edge of the box.
m_truncation = cFullTruncation;
@@ -274,8 +278,8 @@ float InlineTextBox::placeEllipsisBox(bool flowIsLTR, float visibleLeftEdge, flo
return -1;
}
- bool ltrEllipsisWithinBox = flowIsLTR && (ellipsisX < right());
- bool rtlEllipsisWithinBox = !flowIsLTR && (ellipsisX > left());
+ bool ltrEllipsisWithinBox = flowIsLTR && (ellipsisX < logicalRight());
+ bool rtlEllipsisWithinBox = !flowIsLTR && (ellipsisX > logicalLeft());
if (ltrEllipsisWithinBox || rtlEllipsisWithinBox) {
foundBox = true;
@@ -284,9 +288,9 @@ float InlineTextBox::placeEllipsisBox(bool flowIsLTR, float visibleLeftEdge, flo
// must keep track of these separately.
bool ltr = isLeftToRightDirection();
if (ltr != flowIsLTR) {
- // Width in pixels of the visible portion of the box, excluding the ellipsis.
- int visibleBoxWidth = visibleRightEdge - visibleLeftEdge - ellipsisWidth;
- ellipsisX = ltr ? left() + visibleBoxWidth : right() - visibleBoxWidth;
+ // Width in pixels of the visible portion of the box, excluding the ellipsis.
+ int visibleBoxWidth = visibleRightEdge - visibleLeftEdge - ellipsisWidth;
+ ellipsisX = ltr ? logicalLeft() + visibleBoxWidth : logicalRight() - visibleBoxWidth;
}
int offset = offsetForPosition(ellipsisX, false);
@@ -295,7 +299,7 @@ float InlineTextBox::placeEllipsisBox(bool flowIsLTR, float visibleLeftEdge, flo
// and the ellipsis edge.
m_truncation = cFullTruncation;
truncatedWidth += ellipsisWidth;
- return min(ellipsisX, x());
+ return min(ellipsisX, logicalLeft());
}
// Set the truncation index on the text run.
@@ -312,9 +316,9 @@ float InlineTextBox::placeEllipsisBox(bool flowIsLTR, float visibleLeftEdge, flo
// have a situation such as |Hello| -> |...He|
truncatedWidth += widthOfVisibleText + ellipsisWidth;
if (flowIsLTR)
- return left() + widthOfVisibleText;
+ return logicalLeft() + widthOfVisibleText;
else
- return right() - widthOfVisibleText - ellipsisWidth;
+ return logicalRight() - widthOfVisibleText - ellipsisWidth;
}
truncatedWidth += logicalWidth();
return -1;
@@ -389,21 +393,21 @@ static void paintTextWithShadows(GraphicsContext* context,
const AtomicString& emphasisMark, int emphasisMarkOffset,
int startOffset, int endOffset, int truncationPoint,
const FloatPoint& textOrigin, const FloatRect& boxRect,
- const ShadowData* shadow, bool stroked, bool horizontal)
+ const ShadowList* shadowList, bool stroked, bool horizontal)
{
// Text shadows are disabled when printing. http://crbug.com/258321
- bool hasShadow = shadow && !context->printing();
- Color fillColor = context->fillColor();
+ bool hasShadow = shadowList && !context->printing();
if (hasShadow) {
DrawLooper drawLooper;
- do {
- int shadowX = horizontal ? shadow->x() : shadow->y();
- int shadowY = horizontal ? shadow->y() : -shadow->x();
+ for (size_t i = shadowList->shadows().size(); i--; ) {
+ const ShadowData& shadow = shadowList->shadows()[i];
+ int shadowX = horizontal ? shadow.x() : shadow.y();
+ int shadowY = horizontal ? shadow.y() : -shadow.x();
FloatSize offset(shadowX, shadowY);
- drawLooper.addShadow(offset, shadow->blur(), renderer->resolveColor(shadow->color()),
+ drawLooper.addShadow(offset, shadow.blur(), renderer->resolveColor(shadow.color()),
DrawLooper::ShadowRespectsTransforms, DrawLooper::ShadowIgnoresAlpha);
- } while ((shadow = shadow->next()));
+ }
drawLooper.addUnmodifiedContent();
context->setDrawLooper(drawLooper);
}
@@ -463,14 +467,6 @@ bool InlineTextBox::getEmphasisMarkPosition(RenderStyle* style, TextEmphasisPosi
return !rubyText || !rubyText->firstLineBox();
}
-enum RotationDirection { Counterclockwise, Clockwise };
-
-static inline AffineTransform rotation(const FloatRect& boxRect, RotationDirection clockwise)
-{
- return clockwise ? AffineTransform(0, 1, -1, 0, boxRect.x() + boxRect.maxY(), boxRect.maxY() - boxRect.x())
- : AffineTransform(0, -1, 1, 0, boxRect.x() - boxRect.maxY(), boxRect.x() + boxRect.maxY());
-}
-
void InlineTextBox::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset, LayoutUnit /*lineTop*/, LayoutUnit /*lineBottom*/)
{
if (isLineBreak() || !paintInfo.shouldPaintWithinRoot(renderer()) || renderer()->style()->visibility() != VISIBLE ||
@@ -546,7 +542,7 @@ void InlineTextBox::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset,
float textStrokeWidth = styleToUse->textStrokeWidth();
// Text shadows are disabled when printing. http://crbug.com/258321
- const ShadowData* textShadow = (context->printing() || paintInfo.forceBlackText()) ? 0 : styleToUse->textShadow();
+ const ShadowList* textShadow = (context->printing() || paintInfo.forceBlackText()) ? 0 : styleToUse->textShadow();
if (paintInfo.forceBlackText()) {
textFillColor = Color::black;
@@ -587,7 +583,7 @@ void InlineTextBox::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset,
Color selectionStrokeColor = textStrokeColor;
Color selectionEmphasisMarkColor = emphasisMarkColor;
float selectionStrokeWidth = textStrokeWidth;
- const ShadowData* selectionShadow = textShadow;
+ const ShadowList* selectionShadow = textShadow;
if (haveSelection) {
// Check foreground color first.
Color foreground = paintInfo.forceBlackText() ? Color::black : renderer()->selectionForegroundColor();
@@ -606,7 +602,7 @@ void InlineTextBox::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset,
if (RenderStyle* pseudoStyle = renderer()->getCachedPseudoStyle(SELECTION)) {
// Text shadows are disabled when printing. http://crbug.com/258321
- const ShadowData* shadow = (context->printing() || paintInfo.forceBlackText()) ? 0 : pseudoStyle->textShadow();
+ const ShadowList* shadow = (context->printing() || paintInfo.forceBlackText()) ? 0 : pseudoStyle->textShadow();
if (shadow != selectionShadow) {
if (!paintSelectedTextOnly)
paintSelectedTextSeparately = true;
@@ -653,17 +649,6 @@ void InlineTextBox::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset,
paintSelection(context, boxOrigin, styleToUse, font, selectionFillColor);
}
- if (Frame* frame = renderer()->frame()) {
- if (Page* page = frame->page()) {
- // FIXME: Right now, InlineTextBoxes never call addRelevantUnpaintedObject() even though they might
- // legitimately be unpainted if they are waiting on a slow-loading web font. We should fix that, and
- // when we do, we will have to account for the fact the InlineTextBoxes do not always have unique
- // renderers and Page currently relies on each unpainted object having a unique renderer.
- if (paintInfo.phase == PaintPhaseForeground)
- page->addRelevantRepaintedObject(renderer(), IntRect(boxOrigin.x(), boxOrigin.y(), logicalWidth(), logicalHeight()));
- }
- }
-
// 2. Now paint the foreground, including text and decorations like underline/overline (in quirks mode only).
int length = m_len;
int maximumLength;
@@ -923,17 +908,14 @@ static StrokeStyle textDecorationStyleToStrokeStyle(TextDecorationStyle decorati
return strokeStyle;
}
-#if ENABLE(CSS3_TEXT)
-static int computeUnderlineOffset(const TextUnderlinePosition underlinePosition, const FontMetrics& fontMetrics, const InlineTextBox* inlineTextBox, const int textDecorationThickness)
+static int computeUnderlineOffset(const TextUnderlinePosition underlinePosition, const FontMetrics& fontMetrics, const InlineTextBox* inlineTextBox, const float textDecorationThickness)
{
// Compute the gap between the font and the underline. Use at least one
// pixel gap, if underline is thick then use a bigger gap.
- const int gap = max<int>(1, ceilf(textDecorationThickness / 2.0));
+ const int gap = std::max<int>(1, ceilf(textDecorationThickness / 2.f));
- // According to the specification TextUnderlinePositionAuto should default to 'alphabetic' for horizontal text
- // and to 'under Left' for vertical text (e.g. japanese). We support only horizontal text for now.
+ // FIXME: We support only horizontal text for now.
switch (underlinePosition) {
- case TextUnderlinePositionAlphabetic:
case TextUnderlinePositionAuto:
return fontMetrics.ascent() + gap; // Position underline near the alphabetic baseline.
case TextUnderlinePositionUnder: {
@@ -948,7 +930,6 @@ static int computeUnderlineOffset(const TextUnderlinePosition underlinePosition,
ASSERT_NOT_REACHED();
return fontMetrics.ascent() + gap;
}
-#endif // CSS3_TEXT
static void adjustStepToDecorationLength(float& step, float& controlPointDistance, float length)
{
@@ -1072,13 +1053,10 @@ static void strokeWavyTextDecoration(GraphicsContext* context, FloatPoint& p1, F
context->strokePath(path);
}
-void InlineTextBox::paintDecoration(GraphicsContext* context, const FloatPoint& boxOrigin, TextDecoration deco, TextDecorationStyle decorationStyle, const ShadowData* shadow)
+void InlineTextBox::paintDecoration(GraphicsContext* context, const FloatPoint& boxOrigin, TextDecoration deco, TextDecorationStyle decorationStyle, const ShadowList* shadowList)
{
GraphicsContextStateSaver stateSaver(*context);
- // FIXME: We should improve this rule and not always just assume 1.
- const float textDecorationThickness = 1.f;
-
if (m_truncation == cFullTruncation)
return;
@@ -1099,41 +1077,48 @@ void InlineTextBox::paintDecoration(GraphicsContext* context, const FloatPoint&
// Use a special function for underlines to get the positioning exactly right.
bool isPrinting = textRenderer()->document().printing();
- context->setStrokeThickness(textDecorationThickness);
bool linesAreOpaque = !isPrinting && (!(deco & TextDecorationUnderline) || underline.alpha() == 255) && (!(deco & TextDecorationOverline) || overline.alpha() == 255) && (!(deco & TextDecorationLineThrough) || linethrough.alpha() == 255);
RenderStyle* styleToUse = renderer()->style(isFirstLineStyle());
int baseline = styleToUse->fontMetrics().ascent();
+ size_t shadowCount = shadowList ? shadowList->shadows().size() : 0;
+ // Set the thick of the line to be 10% (or something else ?)of the computed font size and not less than 1px.
+ // Using computedFontSize should take care of zoom as well.
+ const float textDecorationThickness = std::max(1.f, styleToUse->computedFontSize() / 10.f);
+ context->setStrokeThickness(textDecorationThickness);
+
int extraOffset = 0;
- if (!linesAreOpaque && shadow && shadow->next()) {
+ if (!linesAreOpaque && shadowCount > 1) {
FloatRect clipRect(localOrigin, FloatSize(width, baseline + 2));
- for (const ShadowData* s = shadow; s; s = s->next()) {
+ for (size_t i = shadowCount; i--; ) {
+ const ShadowData& s = shadowList->shadows()[i];
FloatRect shadowRect(localOrigin, FloatSize(width, baseline + 2));
- shadowRect.inflate(s->blur());
- int shadowX = isHorizontal() ? s->x() : s->y();
- int shadowY = isHorizontal() ? s->y() : -s->x();
+ shadowRect.inflate(s.blur());
+ int shadowX = isHorizontal() ? s.x() : s.y();
+ int shadowY = isHorizontal() ? s.y() : -s.x();
shadowRect.move(shadowX, shadowY);
clipRect.unite(shadowRect);
- extraOffset = max(extraOffset, max(0, shadowY) + s->blur());
+ extraOffset = max(extraOffset, max(0, shadowY) + s.blur());
}
context->clip(clipRect);
extraOffset += baseline + 2;
localOrigin.move(0, extraOffset);
}
- do {
- if (shadow) {
- if (!shadow->next()) {
+ for (size_t i = max(static_cast<size_t>(1), shadowCount); i--; ) {
+ // Even if we have no shadows, we still want to run the code below this once.
+ if (i < shadowCount) {
+ if (!i) {
// The last set of lines paints normally inside the clip.
localOrigin.move(0, -extraOffset);
extraOffset = 0;
}
- int shadowX = isHorizontal() ? shadow->x() : shadow->y();
- int shadowY = isHorizontal() ? shadow->y() : -shadow->x();
- context->setShadow(FloatSize(shadowX, shadowY - extraOffset), shadow->blur(), shadow->color());
- shadow = shadow->next();
+ const ShadowData& shadow = shadowList->shadows()[i];
+ int shadowX = isHorizontal() ? shadow.x() : shadow.y();
+ int shadowY = isHorizontal() ? shadow.y() : -shadow.x();
+ context->setShadow(FloatSize(shadowX, shadowY - extraOffset), shadow.blur(), shadow.color());
}
// Offset between lines - always non-zero, so lines never cross each other.
@@ -1141,13 +1126,7 @@ void InlineTextBox::paintDecoration(GraphicsContext* context, const FloatPoint&
context->setStrokeStyle(textDecorationStyleToStrokeStyle(decorationStyle));
if (deco & TextDecorationUnderline) {
context->setStrokeColor(underline);
-#if ENABLE(CSS3_TEXT)
- TextUnderlinePosition underlinePosition = styleToUse->textUnderlinePosition();
- const int underlineOffset = computeUnderlineOffset(underlinePosition, styleToUse->fontMetrics(), this, textDecorationThickness);
-#else
- const int underlineOffset = styleToUse->fontMetrics().ascent() + max<int>(1, ceilf(textDecorationThickness / 2.0));
-#endif // CSS3_TEXT
-
+ const int underlineOffset = computeUnderlineOffset(styleToUse->textUnderlinePosition(), styleToUse->fontMetrics(), this, textDecorationThickness);
switch (decorationStyle) {
case TextDecorationStyleWavy: {
FloatPoint start(localOrigin.x(), localOrigin.y() + underlineOffset + doubleOffset);
@@ -1192,7 +1171,7 @@ void InlineTextBox::paintDecoration(GraphicsContext* context, const FloatPoint&
context->drawLineForText(FloatPoint(localOrigin.x(), localOrigin.y() + doubleOffset + 2 * baseline / 3), width, isPrinting);
}
}
- } while (shadow);
+ }
}
static GraphicsContext::DocumentMarkerLineStyle lineStyleForMarkerType(DocumentMarker::MarkerType markerType)
@@ -1485,6 +1464,27 @@ bool InlineTextBox::containsCaretOffset(int offset) const
return true;
}
+void InlineTextBox::characterWidths(Vector<float>& widths) const
+{
+ FontCachePurgePreventer fontCachePurgePreventer;
+
+ RenderText* textObj = textRenderer();
+ RenderStyle* styleToUse = textObj->style(isFirstLineStyle());
+ const Font& font = styleToUse->font();
+
+ TextRun textRun = constructTextRun(styleToUse, font);
+
+ GlyphBuffer glyphBuffer;
+ WidthIterator it(&font, textRun);
+ float lastWidth = 0;
+ widths.resize(m_len);
+ for (unsigned i = 0; i < m_len; i++) {
+ it.advance(i + 1, &glyphBuffer);
+ widths[i] = it.m_runWidthSoFar - lastWidth;
+ lastWidth = it.m_runWidthSoFar;
+ }
+}
+
TextRun InlineTextBox::constructTextRun(RenderStyle* style, const Font& font, StringBuilder* charactersWithHyphen) const
{
ASSERT(style);
diff --git a/chromium/third_party/WebKit/Source/core/rendering/InlineTextBox.h b/chromium/third_party/WebKit/Source/core/rendering/InlineTextBox.h
index 3d6fdee393a..27579edf5cb 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/InlineTextBox.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/InlineTextBox.h
@@ -23,9 +23,10 @@
#ifndef InlineTextBox_h
#define InlineTextBox_h
-#include "core/platform/graphics/TextRun.h"
#include "core/rendering/InlineBox.h"
#include "core/rendering/RenderText.h" // so textRenderer() can be inline
+#include "platform/graphics/GraphicsContext.h"
+#include "platform/text/TextRun.h"
#include "wtf/Forward.h"
namespace WebCore {
@@ -97,6 +98,8 @@ public:
virtual const char* boxName() const;
#endif
+ enum RotationDirection { Counterclockwise, Clockwise };
+ static AffineTransform rotation(const FloatRect& boxRect, RotationDirection);
private:
LayoutUnit selectionTop();
LayoutUnit selectionBottom();
@@ -159,6 +162,9 @@ public:
bool containsCaretOffset(int offset) const; // false for offset after line break
+ // Fills a vector with the pixel width of each character.
+ void characterWidths(Vector<float>&) const;
+
private:
InlineTextBox* m_prevTextBox; // The previous box that also uses our RenderObject
InlineTextBox* m_nextTextBox; // The next box that also uses our RenderObject
@@ -175,7 +181,7 @@ protected:
void paintCompositionUnderline(GraphicsContext*, const FloatPoint& boxOrigin, const CompositionUnderline&);
private:
- void paintDecoration(GraphicsContext*, const FloatPoint& boxOrigin, TextDecoration, TextDecorationStyle, const ShadowData*);
+ void paintDecoration(GraphicsContext*, const FloatPoint& boxOrigin, TextDecoration, TextDecorationStyle, const ShadowList*);
void paintSelection(GraphicsContext*, const FloatPoint& boxOrigin, RenderStyle*, const Font&, Color textColor);
void paintDocumentMarker(GraphicsContext*, const FloatPoint& boxOrigin, DocumentMarker*, RenderStyle*, const Font&, bool grammar);
void paintTextMatchMarker(GraphicsContext*, const FloatPoint& boxOrigin, DocumentMarker*, RenderStyle*, const Font&);
@@ -187,20 +193,7 @@ private:
}
};
-inline InlineTextBox* toInlineTextBox(InlineBox* inlineBox)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!inlineBox || inlineBox->isInlineTextBox());
- return static_cast<InlineTextBox*>(inlineBox);
-}
-
-inline const InlineTextBox* toInlineTextBox(const InlineBox* inlineBox)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!inlineBox || inlineBox->isInlineTextBox());
- return static_cast<const InlineTextBox*>(inlineBox);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toInlineTextBox(const InlineTextBox*);
+DEFINE_INLINE_BOX_TYPE_CASTS(InlineTextBox);
inline RenderText* InlineTextBox::textRenderer() const
{
@@ -209,6 +202,12 @@ inline RenderText* InlineTextBox::textRenderer() const
void alignSelectionRectToDevicePixels(FloatRect&);
+inline AffineTransform InlineTextBox::rotation(const FloatRect& boxRect, RotationDirection rotationDirection)
+{
+ return rotationDirection == Clockwise ? AffineTransform(0, 1, -1, 0, boxRect.x() + boxRect.maxY(), boxRect.maxY() - boxRect.x())
+ : AffineTransform(0, -1, 1, 0, boxRect.x() - boxRect.maxY(), boxRect.x() + boxRect.maxY());
+}
+
} // namespace WebCore
#endif // InlineTextBox_h
diff --git a/chromium/third_party/WebKit/Source/core/rendering/LayerPaintingInfo.h b/chromium/third_party/WebKit/Source/core/rendering/LayerPaintingInfo.h
new file mode 100644
index 00000000000..b9af0314271
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/rendering/LayerPaintingInfo.h
@@ -0,0 +1,100 @@
+/*
+ * Copyright (C) 2003, 2009, 2012 Apple Inc. All rights reserved.
+ * Copyright (C) 2013 Intel Corporation. All rights reserved.
+ *
+ * Portions are Copyright (C) 1998 Netscape Communications Corporation.
+ *
+ * Other contributors:
+ * Robert O'Callahan <roc+@cs.cmu.edu>
+ * David Baron <dbaron@fas.harvard.edu>
+ * Christian Biesinger <cbiesinger@web.de>
+ * Randall Jesup <rjesup@wgate.com>
+ * Roland Mainz <roland.mainz@informatik.med.uni-giessen.de>
+ * Josh Soref <timeless@mac.com>
+ * Boris Zbarsky <bzbarsky@mit.edu>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ * Alternatively, the contents of this file may be used under the terms
+ * of either the Mozilla Public License Version 1.1, found at
+ * http://www.mozilla.org/MPL/ (the "MPL") or the GNU General Public
+ * License Version 2.0, found at http://www.fsf.org/copyleft/gpl.html
+ * (the "GPL"), in which case the provisions of the MPL or the GPL are
+ * applicable instead of those above. If you wish to allow use of your
+ * version of this file only under the terms of one of those two
+ * licenses (the MPL or the GPL) and not to allow others to use your
+ * version of this file under the LGPL, indicate your decision by
+ * deletingthe provisions above and replace them with the notice and
+ * other provisions required by the MPL or the GPL, as the case may be.
+ * If you do not delete the provisions above, a recipient may use your
+ * version of this file under any of the LGPL, the MPL or the GPL.
+ */
+
+#ifndef LayerPaintingInfo_h
+#define LayerPaintingInfo_h
+
+#include "core/rendering/PaintInfo.h"
+#include "platform/geometry/LayoutRect.h"
+
+namespace WebCore {
+
+class RenderLayer;
+
+enum PaintLayerFlag {
+ PaintLayerHaveTransparency = 1,
+ PaintLayerAppliedTransform = 1 << 1,
+ PaintLayerTemporaryClipRects = 1 << 2,
+ PaintLayerPaintingReflection = 1 << 3,
+ PaintLayerPaintingOverlayScrollbars = 1 << 4,
+ PaintLayerPaintingCompositingBackgroundPhase = 1 << 5,
+ PaintLayerPaintingCompositingForegroundPhase = 1 << 6,
+ PaintLayerPaintingCompositingMaskPhase = 1 << 7,
+ PaintLayerPaintingCompositingScrollingPhase = 1 << 8,
+ PaintLayerPaintingOverflowContents = 1 << 9,
+ PaintLayerPaintingRootBackgroundOnly = 1 << 10,
+ PaintLayerPaintingSkipRootBackground = 1 << 11,
+ PaintLayerPaintingChildClippingMaskPhase = 1 << 12,
+ PaintLayerPaintingCompositingAllPhases = (PaintLayerPaintingCompositingBackgroundPhase | PaintLayerPaintingCompositingForegroundPhase | PaintLayerPaintingCompositingMaskPhase)
+};
+
+typedef unsigned PaintLayerFlags;
+
+struct LayerPaintingInfo {
+ LayerPaintingInfo(RenderLayer* inRootLayer, const LayoutRect& inDirtyRect,
+ PaintBehavior inPaintBehavior, const LayoutSize& inSubPixelAccumulation,
+ RenderObject* inPaintingRoot = 0, RenderRegion*inRegion = 0,
+ OverlapTestRequestMap* inOverlapTestRequests = 0)
+ : rootLayer(inRootLayer)
+ , paintingRoot(inPaintingRoot)
+ , paintDirtyRect(inDirtyRect)
+ , subPixelAccumulation(inSubPixelAccumulation)
+ , region(inRegion)
+ , overlapTestRequests(inOverlapTestRequests)
+ , paintBehavior(inPaintBehavior)
+ , clipToDirtyRect(true)
+ { }
+ RenderLayer* rootLayer;
+ RenderObject* paintingRoot; // only paint descendants of this object
+ LayoutRect paintDirtyRect; // relative to rootLayer;
+ LayoutSize subPixelAccumulation;
+ RenderRegion* region; // May be null.
+ OverlapTestRequestMap* overlapTestRequests; // May be null.
+ PaintBehavior paintBehavior;
+ bool clipToDirtyRect;
+};
+
+} // namespace WebCore
+
+#endif // LayerPaintingInfo_h
diff --git a/chromium/third_party/WebKit/Source/core/rendering/LayoutRectRecorder.cpp b/chromium/third_party/WebKit/Source/core/rendering/LayoutRectRecorder.cpp
new file mode 100644
index 00000000000..90c50d32884
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/rendering/LayoutRectRecorder.cpp
@@ -0,0 +1,76 @@
+/*
+ * Copyright (c) 2013, Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/rendering/LayoutRectRecorder.h"
+
+#include "core/rendering/RenderObject.h"
+
+namespace WebCore {
+
+bool LayoutRectRecorder::shouldRecordLayoutRects()
+{
+ bool isTracing;
+ TRACE_EVENT_CATEGORY_GROUP_ENABLED(TRACE_DISABLED_BY_DEFAULT("blink.debug.layout"), &isTracing);
+ return RuntimeEnabledFeatures::repaintAfterLayoutEnabled() || isTracing;
+}
+
+LayoutRectRecorder::LayoutRectRecorder(RenderObject& object, bool skipRecording)
+ : m_object(object)
+ , m_skipRecording(skipRecording)
+{
+ if (!shouldRecordLayoutRects())
+ return;
+ if (m_skipRecording)
+ return;
+
+ if (!m_object.layoutDidGetCalled())
+ m_object.setOldRepaintRect(m_object.clippedOverflowRectForRepaint(m_object.containerForRepaint()));
+
+ // If should do repaint was set previously make sure we don't accidentally unset it.
+ if (!m_object.shouldDoFullRepaintAfterLayout())
+ m_object.setShouldDoFullRepaintAfterLayout(m_object.selfNeedsLayout());
+
+ m_object.setLayoutDidGetCalled(true);
+}
+
+LayoutRectRecorder::~LayoutRectRecorder()
+{
+ if (!shouldRecordLayoutRects())
+ return;
+ if (m_skipRecording)
+ return;
+
+ // Note, we don't store the repaint container because it can change during layout.
+ m_object.setNewRepaintRect(m_object.clippedOverflowRectForRepaint(m_object.containerForRepaint()));
+}
+
+} // namespace WebCore
+
diff --git a/chromium/third_party/WebKit/Source/core/rendering/LayoutRectRecorder.h b/chromium/third_party/WebKit/Source/core/rendering/LayoutRectRecorder.h
new file mode 100644
index 00000000000..c92eb5efc90
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/rendering/LayoutRectRecorder.h
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) 2013, Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef LayoutRectRecorder_h
+#define LayoutRectRecorder_h
+
+#include "platform/geometry/LayoutRect.h"
+#include "wtf/Noncopyable.h"
+
+namespace WebCore {
+
+class RenderLayerModelObject;
+class RenderObject;
+
+class LayoutRectRecorder {
+ WTF_MAKE_NONCOPYABLE(LayoutRectRecorder);
+public:
+ LayoutRectRecorder(RenderObject&, bool skipRecording = false);
+ ~LayoutRectRecorder();
+
+ static bool shouldRecordLayoutRects();
+
+private:
+ RenderObject& m_object;
+ bool m_skipRecording;
+};
+
+} // namespace WebCore
+
+#endif // LayoutRectRecorder_h
+
diff --git a/chromium/third_party/WebKit/Source/core/rendering/LayoutRepainter.cpp b/chromium/third_party/WebKit/Source/core/rendering/LayoutRepainter.cpp
index 112db533003..fc06e0b3b21 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/LayoutRepainter.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/LayoutRepainter.cpp
@@ -35,6 +35,9 @@ LayoutRepainter::LayoutRepainter(RenderObject& object, bool checkForRepaint)
, m_repaintContainer(0)
, m_checkForRepaint(checkForRepaint)
{
+ if (RuntimeEnabledFeatures::repaintAfterLayoutEnabled())
+ return;
+
if (m_checkForRepaint) {
m_repaintContainer = m_object.containerForRepaint();
m_oldBounds = m_object.clippedOverflowRectForRepaint(m_repaintContainer);
@@ -44,7 +47,10 @@ LayoutRepainter::LayoutRepainter(RenderObject& object, bool checkForRepaint)
bool LayoutRepainter::repaintAfterLayout()
{
- return m_checkForRepaint ? m_object.repaintAfterLayoutIfNeeded(m_repaintContainer, m_oldBounds, m_oldOutlineBox) : false;
+ if (RuntimeEnabledFeatures::repaintAfterLayoutEnabled())
+ return false;
+
+ return m_checkForRepaint ? m_object.repaintAfterLayoutIfNeeded(m_repaintContainer, m_object.selfNeedsLayout(), m_oldBounds, m_oldOutlineBox) : false;
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/LayoutRepainter.h b/chromium/third_party/WebKit/Source/core/rendering/LayoutRepainter.h
index fe6129c991f..55fdd1eb23a 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/LayoutRepainter.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/LayoutRepainter.h
@@ -26,7 +26,7 @@
#ifndef LayoutRepainter_h
#define LayoutRepainter_h
-#include "core/platform/graphics/LayoutRect.h"
+#include "platform/geometry/LayoutRect.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/rendering/LayoutState.cpp b/chromium/third_party/WebKit/Source/core/rendering/LayoutState.cpp
index 445aa351867..940f21ccc16 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/LayoutState.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/LayoutState.cpp
@@ -26,11 +26,10 @@
#include "config.h"
#include "core/rendering/LayoutState.h"
-#include "core/platform/Partitions.h"
-#include "core/rendering/ColumnInfo.h"
#include "core/rendering/RenderInline.h"
#include "core/rendering/RenderLayer.h"
#include "core/rendering/RenderView.h"
+#include "platform/Partitions.h"
namespace WebCore {
@@ -110,7 +109,7 @@ LayoutState::LayoutState(LayoutState* prev, RenderBox* renderer, const LayoutSiz
if (renderer->isRenderBlock()) {
const RenderBlock* renderBlock = toRenderBlock(renderer);
m_shapeInsideInfo = renderBlock->shapeInsideInfo();
- if (!m_shapeInsideInfo && m_next->m_shapeInsideInfo && renderBlock->allowsShapeInsideInfoSharing())
+ if (!m_shapeInsideInfo && m_next->m_shapeInsideInfo && renderBlock->allowsShapeInsideInfoSharing(m_next->m_shapeInsideInfo->owner()))
m_shapeInsideInfo = m_next->m_shapeInsideInfo;
}
@@ -127,7 +126,7 @@ LayoutState::LayoutState(LayoutState* prev, RenderBox* renderer, const LayoutSiz
// If we have a new grid to track, then add it to our set.
if (renderer->style()->lineGrid() != RenderStyle::initialLineGrid() && renderer->isRenderBlockFlow())
- establishLineGrid(toRenderBlock(renderer));
+ establishLineGrid(toRenderBlockFlow(renderer));
// FIXME: <http://bugs.webkit.org/show_bug.cgi?id=13443> Apply control clip if present.
}
@@ -204,13 +203,13 @@ void LayoutState::propagateLineGridInfo(RenderBox* renderer)
m_lineGridPaginationOrigin = m_next->m_lineGridPaginationOrigin;
}
-void LayoutState::establishLineGrid(RenderBlock* block)
+void LayoutState::establishLineGrid(RenderBlockFlow* block)
{
// First check to see if this grid has been established already.
if (m_lineGrid) {
if (m_lineGrid->style()->lineGrid() == block->style()->lineGrid())
return;
- RenderBlock* currentGrid = m_lineGrid;
+ RenderBlockFlow* currentGrid = m_lineGrid;
for (LayoutState* currentState = m_next; currentState; currentState = currentState->m_next) {
if (currentState->m_lineGrid == currentGrid)
continue;
diff --git a/chromium/third_party/WebKit/Source/core/rendering/LayoutState.h b/chromium/third_party/WebKit/Source/core/rendering/LayoutState.h
index 32719050f8d..16aa5b6ef36 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/LayoutState.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/LayoutState.h
@@ -26,14 +26,14 @@
#ifndef LayoutState_h
#define LayoutState_h
-#include "core/platform/graphics/LayoutRect.h"
#include "core/rendering/ColumnInfo.h"
+#include "platform/geometry/LayoutRect.h"
#include "wtf/HashMap.h"
#include "wtf/Noncopyable.h"
namespace WebCore {
-class RenderBlock;
+class RenderBlockFlow;
class RenderBox;
class RenderObject;
class RenderFlowThread;
@@ -81,7 +81,7 @@ public:
LayoutUnit pageLogicalHeight() const { return m_pageLogicalHeight; }
bool pageLogicalHeightChanged() const { return m_pageLogicalHeightChanged; }
- RenderBlock* lineGrid() const { return m_lineGrid; }
+ RenderBlockFlow* lineGrid() const { return m_lineGrid; }
LayoutSize lineGridOffset() const { return m_lineGridOffset; }
LayoutSize lineGridPaginationOrigin() const { return m_lineGridPaginationOrigin; }
@@ -96,7 +96,7 @@ public:
#endif
private:
void propagateLineGridInfo(RenderBox*);
- void establishLineGrid(RenderBlock*);
+ void establishLineGrid(RenderBlockFlow*);
void computeLineGridPaginationOrigin(RenderBox*);
@@ -113,7 +113,7 @@ public:
// If the enclosing pagination model is a column model, then this will store column information for easy retrieval/manipulation.
ColumnInfo* m_columnInfo;
// The current line grid that we're snapping to and the offset of the start of the grid.
- RenderBlock* m_lineGrid;
+ RenderBlockFlow* m_lineGrid;
LayoutState* m_next;
ShapeInsideInfo* m_shapeInsideInfo;
diff --git a/chromium/third_party/WebKit/Source/core/rendering/LineWidth.cpp b/chromium/third_party/WebKit/Source/core/rendering/LineWidth.cpp
index 9fcacaf3e4a..ea720e2024e 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/LineWidth.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/LineWidth.cpp
@@ -30,9 +30,12 @@
#include "config.h"
#include "core/rendering/LineWidth.h"
+#include "core/rendering/RenderBlock.h"
+#include "core/rendering/RenderRubyRun.h"
+
namespace WebCore {
-LineWidth::LineWidth(RenderBlock& block, bool isFirstLine, IndentTextOrNot shouldIndentText)
+LineWidth::LineWidth(RenderBlockFlow& block, bool isFirstLine, IndentTextOrNot shouldIndentText)
: m_block(block)
, m_uncommittedWidth(0)
, m_committedWidth(0)
@@ -44,15 +47,14 @@ LineWidth::LineWidth(RenderBlock& block, bool isFirstLine, IndentTextOrNot shoul
, m_isFirstLine(isFirstLine)
, m_shouldIndentText(shouldIndentText)
{
- if (ShapeInsideInfo* shapeInsideInfo = m_block.layoutShapeInsideInfo())
- m_segment = shapeInsideInfo->currentSegment();
+ updateCurrentShapeSegment();
updateAvailableWidth();
}
void LineWidth::updateAvailableWidth(LayoutUnit replacedHeight)
{
LayoutUnit height = m_block.logicalHeight();
- LayoutUnit logicalHeight = logicalHeightForLine(&m_block, m_isFirstLine, replacedHeight);
+ LayoutUnit logicalHeight = m_block.minLineHeightForReplacedRenderer(m_isFirstLine, replacedHeight);
m_left = m_block.logicalLeftOffsetForLine(height, shouldIndentText(), logicalHeight);
m_right = m_block.logicalRightOffsetForLine(height, shouldIndentText(), logicalHeight);
@@ -67,7 +69,7 @@ void LineWidth::updateAvailableWidth(LayoutUnit replacedHeight)
void LineWidth::shrinkAvailableWidthForNewFloatIfNeeded(FloatingObject* newFloat)
{
LayoutUnit height = m_block.logicalHeight();
- if (height < newFloat->logicalTop(m_block.isHorizontalWritingMode()) || height >= newFloat->logicalBottom(m_block.isHorizontalWritingMode()))
+ if (height < m_block.logicalTopForFloat(newFloat) || height >= m_block.logicalBottomForFloat(newFloat))
return;
// When floats with shape outside are stacked, the floats are positioned based on the margin box of the float,
@@ -79,36 +81,37 @@ void LineWidth::shrinkAvailableWidthForNewFloatIfNeeded(FloatingObject* newFloat
const FloatingObjectSet& floatingObjectSet = m_block.m_floatingObjects->set();
FloatingObjectSetIterator it = floatingObjectSet.end();
FloatingObjectSetIterator begin = floatingObjectSet.begin();
+ LayoutUnit lineHeight = m_block.lineHeight(m_isFirstLine, m_block.isHorizontalWritingMode() ? HorizontalLine : VerticalLine, PositionOfInteriorLineBoxes);
for (--it; it != begin; --it) {
FloatingObject* previousFloat = *it;
if (previousFloat != newFloat && previousFloat->type() == newFloat->type()) {
previousShapeOutsideInfo = previousFloat->renderer()->shapeOutsideInfo();
if (previousShapeOutsideInfo)
- previousShapeOutsideInfo->computeSegmentsForContainingBlockLine(&m_block, previousFloat, m_block.logicalHeight(), logicalHeightForLine(&m_block, m_isFirstLine));
+ previousShapeOutsideInfo->updateDeltasForContainingBlockLine(&m_block, previousFloat, m_block.logicalHeight(), lineHeight);
break;
}
}
ShapeOutsideInfo* shapeOutsideInfo = newFloat->renderer()->shapeOutsideInfo();
if (shapeOutsideInfo)
- shapeOutsideInfo->computeSegmentsForContainingBlockLine(&m_block, newFloat, m_block.logicalHeight(), logicalHeightForLine(&m_block, m_isFirstLine));
+ shapeOutsideInfo->updateDeltasForContainingBlockLine(&m_block, newFloat, m_block.logicalHeight(), lineHeight);
if (newFloat->type() == FloatingObject::FloatLeft) {
- float newLeft = newFloat->logicalRight(m_block.isHorizontalWritingMode());
+ float newLeft = m_block.logicalRightForFloat(newFloat);
if (previousShapeOutsideInfo)
- newLeft -= previousShapeOutsideInfo->rightSegmentMarginBoxDelta();
+ newLeft -= previousShapeOutsideInfo->rightMarginBoxDelta();
if (shapeOutsideInfo)
- newLeft += shapeOutsideInfo->rightSegmentMarginBoxDelta();
+ newLeft += shapeOutsideInfo->rightMarginBoxDelta();
if (shouldIndentText() && m_block.style()->isLeftToRightDirection())
newLeft += floorToInt(m_block.textIndentOffset());
m_left = std::max<float>(m_left, newLeft);
} else {
- float newRight = newFloat->logicalLeft(m_block.isHorizontalWritingMode());
+ float newRight = m_block.logicalLeftForFloat(newFloat);
if (previousShapeOutsideInfo)
- newRight -= previousShapeOutsideInfo->leftSegmentMarginBoxDelta();
+ newRight -= previousShapeOutsideInfo->leftMarginBoxDelta();
if (shapeOutsideInfo)
- newRight += shapeOutsideInfo->leftSegmentMarginBoxDelta();
+ newRight += shapeOutsideInfo->leftMarginBoxDelta();
if (shouldIndentText() && !m_block.style()->isLeftToRightDirection())
newRight -= floorToInt(m_block.textIndentOffset());
@@ -149,7 +152,7 @@ void LineWidth::fitBelowFloats()
float newLineLeft = m_left;
float newLineRight = m_right;
while (true) {
- floatLogicalBottom = m_block.nextFloatLogicalBottomBelow(lastFloatLogicalBottom);
+ floatLogicalBottom = m_block.nextFloatLogicalBottomBelow(lastFloatLogicalBottom, ShapeOutsideFloatShapeOffset);
if (floatLogicalBottom <= lastFloatLogicalBottom)
break;
@@ -157,6 +160,17 @@ void LineWidth::fitBelowFloats()
newLineRight = m_block.logicalRightOffsetForLine(floatLogicalBottom, shouldIndentText());
newLineWidth = max(0.0f, newLineRight - newLineLeft);
lastFloatLogicalBottom = floatLogicalBottom;
+
+ // FIXME: This code should be refactored to incorporate with the code above.
+ ShapeInsideInfo* shapeInsideInfo = m_block.layoutShapeInsideInfo();
+ if (shapeInsideInfo) {
+ LayoutUnit logicalOffsetFromShapeContainer = m_block.logicalOffsetFromShapeAncestorContainer(shapeInsideInfo->owner()).height();
+ LayoutUnit lineHeight = m_block.lineHeight(false, m_block.isHorizontalWritingMode() ? HorizontalLine : VerticalLine, PositionOfInteriorLineBoxes);
+ shapeInsideInfo->updateSegmentsForLine(lastFloatLogicalBottom + logicalOffsetFromShapeContainer, lineHeight);
+ updateCurrentShapeSegment();
+ updateAvailableWidth();
+ }
+
if (newLineWidth >= m_uncommittedWidth)
break;
}
@@ -169,6 +183,12 @@ void LineWidth::fitBelowFloats()
}
}
+void LineWidth::updateCurrentShapeSegment()
+{
+ if (ShapeInsideInfo* shapeInsideInfo = m_block.layoutShapeInsideInfo())
+ m_segment = shapeInsideInfo->currentSegment();
+}
+
void LineWidth::computeAvailableWidthFromLeftAndRight()
{
m_availableWidth = max(0.0f, m_right - m_left) + m_overhangWidth;
diff --git a/chromium/third_party/WebKit/Source/core/rendering/LineWidth.h b/chromium/third_party/WebKit/Source/core/rendering/LineWidth.h
index f0bd81a463e..59e1442445e 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/LineWidth.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/LineWidth.h
@@ -30,30 +30,26 @@
#ifndef LineWidth_h
#define LineWidth_h
-#include "core/rendering/RenderBlock.h"
-#include "core/rendering/RenderRubyRun.h"
+#include "platform/LayoutUnit.h"
namespace WebCore {
-enum IndentTextOrNot { DoNotIndentText, IndentText };
-
-inline LayoutUnit logicalHeightForLine(const RenderBlock* block, bool isFirstLine, LayoutUnit replacedHeight = 0)
-{
- if (!block->document().inNoQuirksMode() && replacedHeight)
- return replacedHeight;
+class FloatingObject;
+class RenderBlock;
+class RenderObject;
+class RenderRubyRun;
+class RenderBlockFlow;
- if (!(block->style(isFirstLine)->lineBoxContain() & LineBoxContainBlock))
- return 0;
+struct LineSegment;
- return std::max<LayoutUnit>(replacedHeight, block->lineHeight(isFirstLine, block->isHorizontalWritingMode() ? HorizontalLine : VerticalLine, PositionOfInteriorLineBoxes));
-}
+enum IndentTextOrNot { DoNotIndentText, IndentText };
class LineWidth {
public:
- LineWidth(RenderBlock&, bool isFirstLine, IndentTextOrNot shouldIndentText);
+ LineWidth(RenderBlockFlow&, bool isFirstLine, IndentTextOrNot shouldIndentText);
- bool fitsOnLine() const { return currentWidth() <= m_availableWidth; }
- bool fitsOnLine(float extra) const { return currentWidth() + extra <= m_availableWidth; }
+ bool fitsOnLine() const { return currentWidth() <= (m_availableWidth + LayoutUnit::epsilon()); }
+ bool fitsOnLine(float extra) const { return currentWidth() + extra <= (m_availableWidth + LayoutUnit::epsilon()); }
float currentWidth() const { return m_committedWidth + m_uncommittedWidth; }
// FIXME: We should eventually replace these three functions by ones that work on a higher abstraction.
@@ -68,12 +64,14 @@ public:
void applyOverhang(RenderRubyRun*, RenderObject* startRenderer, RenderObject* endRenderer);
void fitBelowFloats();
+ void updateCurrentShapeSegment();
+
bool shouldIndentText() const { return m_shouldIndentText == IndentText; }
private:
void computeAvailableWidthFromLeftAndRight();
- RenderBlock& m_block;
+ RenderBlockFlow& m_block;
float m_uncommittedWidth;
float m_committedWidth;
float m_overhangWidth; // The amount by which |m_availableWidth| has been inflated to account for possible contraction due to ruby overhang.
diff --git a/chromium/third_party/WebKit/Source/core/rendering/OrderIterator.cpp b/chromium/third_party/WebKit/Source/core/rendering/OrderIterator.cpp
index 1cda9c59b3c..20926a576d5 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/OrderIterator.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/OrderIterator.cpp
@@ -38,7 +38,7 @@ namespace WebCore {
OrderIterator::OrderIterator(const RenderBox* containerBox)
: m_containerBox(containerBox)
, m_currentChild(0)
- , m_orderValuesIterator(0)
+ , m_isReset(false)
{
}
@@ -54,12 +54,13 @@ RenderBox* OrderIterator::next()
if (!m_currentChild) {
if (m_orderValuesIterator == m_orderValues.end())
return 0;
- if (m_orderValuesIterator) {
+
+ if (!m_isReset) {
++m_orderValuesIterator;
if (m_orderValuesIterator == m_orderValues.end())
return 0;
} else {
- m_orderValuesIterator = m_orderValues.begin();
+ m_isReset = false;
}
m_currentChild = firstChildBox();
@@ -74,7 +75,8 @@ RenderBox* OrderIterator::next()
void OrderIterator::reset()
{
m_currentChild = 0;
- m_orderValuesIterator = 0;
+ m_orderValuesIterator = m_orderValues.begin();
+ m_isReset = true;
}
RenderBox* OrderIterator::firstChildBox()
@@ -100,34 +102,6 @@ RenderBox* OrderIterator::nextSiblingBox()
OrderIteratorPopulator::~OrderIteratorPopulator()
{
m_iterator.reset();
-
- if (m_anyChildHasDefaultOrderValue)
- m_iterator.m_orderValues.append(0);
-
- if (m_iterator.m_orderValues.size() > 1)
- removeDuplicatedOrderValues();
-
- // Ensure that we release any extra memory we hold onto.
- m_iterator.m_orderValues.shrinkToFit();
-}
-
-void OrderIteratorPopulator::removeDuplicatedOrderValues()
-{
- OrderIterator::OrderValues& orderValues = m_iterator.m_orderValues;
-
- std::sort(orderValues.begin(), orderValues.end());
-
- int previous = orderValues[0];
- size_t uniqueItemIndex = 0;
- for (size_t i = 1; i < orderValues.size(); ++i) {
- int current = orderValues[i];
- if (current == previous)
- continue;
- ++uniqueItemIndex;
- std::swap(orderValues[i], orderValues[uniqueItemIndex]);
- previous = current;
- }
- orderValues.shrink(uniqueItemIndex + 1);
}
void OrderIteratorPopulator::storeChild(RenderBox* child)
@@ -139,11 +113,7 @@ void OrderIteratorPopulator::storeChild(RenderBox* child)
void OrderIteratorPopulator::collectChild(const RenderBox* child)
{
- // Avoid growing the vector for the common-case default value of 0.
- if (int order = child->style()->order())
- m_iterator.m_orderValues.append(order);
- else
- m_anyChildHasDefaultOrderValue = true;
+ m_iterator.m_orderValues.insert(child->style()->order());
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/OrderIterator.h b/chromium/third_party/WebKit/Source/core/rendering/OrderIterator.h
index 3f769852bf3..2a019150a6b 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/OrderIterator.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/OrderIterator.h
@@ -34,6 +34,8 @@
#include "wtf/Noncopyable.h"
#include "wtf/Vector.h"
+#include <set>
+
namespace WebCore {
class RenderBox;
@@ -61,22 +63,18 @@ private:
RenderBox* m_currentChild;
size_t m_childIndex;
- // The inline capacity for a single item is used to cover the most
- // common case by far: if we only have the default 'order' value 0.
- typedef Vector<int, 1> OrderValues;
+ typedef std::set<int> OrderValues;
OrderValues m_orderValues;
- Vector<int>::const_iterator m_orderValuesIterator;
+ OrderValues::const_iterator m_orderValuesIterator;
+ bool m_isReset;
};
class OrderIteratorPopulator {
public:
- OrderIteratorPopulator(OrderIterator& iterator)
+ explicit OrderIteratorPopulator(OrderIterator& iterator)
: m_iterator(iterator)
- , m_anyChildHasDefaultOrderValue(false)
{
- // Note that we don't release the memory here, we only invalidate the size.
- // This avoids unneeded reallocation if the size ends up not changing.
- m_iterator.m_orderValues.shrink(0);
+ m_iterator.m_orderValues.clear();
}
~OrderIteratorPopulator();
@@ -85,10 +83,7 @@ public:
void collectChild(const RenderBox*);
private:
- void removeDuplicatedOrderValues();
-
OrderIterator& m_iterator;
- bool m_anyChildHasDefaultOrderValue;
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/PaintInfo.h b/chromium/third_party/WebKit/Source/core/rendering/PaintInfo.h
index 3f7aa80d2bf..be99ec39407 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/PaintInfo.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/PaintInfo.h
@@ -27,11 +27,11 @@
#define PaintInfo_h
#include <limits>
-#include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/graphics/IntRect.h"
-#include "core/platform/graphics/LayoutRect.h"
-#include "core/platform/graphics/transforms/AffineTransform.h"
#include "core/rendering/PaintPhase.h"
+#include "platform/geometry/IntRect.h"
+#include "platform/geometry/LayoutRect.h"
+#include "platform/graphics/GraphicsContext.h"
+#include "platform/transforms/AffineTransform.h"
#include "wtf/HashMap.h"
#include "wtf/ListHashSet.h"
diff --git a/chromium/third_party/WebKit/Source/core/rendering/PaintPhase.h b/chromium/third_party/WebKit/Source/core/rendering/PaintPhase.h
index af0bd59b93e..cee9e9ba0a0 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/PaintPhase.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/PaintPhase.h
@@ -49,7 +49,8 @@ enum PaintPhase {
PaintPhaseSelection,
PaintPhaseCollapsedTableBorders,
PaintPhaseTextClip,
- PaintPhaseMask
+ PaintPhaseMask,
+ PaintPhaseClippingMask,
};
enum PaintBehaviorFlags {
diff --git a/chromium/third_party/WebKit/Source/core/rendering/PointerEventsHitRules.cpp b/chromium/third_party/WebKit/Source/core/rendering/PointerEventsHitRules.cpp
index 8ae6aa7ead5..b154570c651 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/PointerEventsHitRules.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/PointerEventsHitRules.cpp
@@ -28,13 +28,17 @@ PointerEventsHitRules::PointerEventsHitRules(EHitTesting hitTesting, const HitTe
, requireStroke(false)
, canHitStroke(false)
, canHitFill(false)
+ , canHitBoundingBox(false)
{
if (request.svgClipContent())
pointerEvents = PE_FILL;
- if (hitTesting == SVG_PATH_HITTESTING) {
+ if (hitTesting == SVG_GEOMETRY_HITTESTING) {
switch (pointerEvents)
{
+ case PE_BOUNDINGBOX:
+ canHitBoundingBox = true;
+ break;
case PE_VISIBLE_PAINTED:
case PE_AUTO: // "auto" is like "visiblePainted" when in SVG content
requireFill = true;
@@ -72,6 +76,9 @@ PointerEventsHitRules::PointerEventsHitRules(EHitTesting hitTesting, const HitTe
} else {
switch (pointerEvents)
{
+ case PE_BOUNDINGBOX:
+ canHitBoundingBox = true;
+ break;
case PE_VISIBLE_PAINTED:
case PE_AUTO: // "auto" is like "visiblePainted" when in SVG content
requireVisible = true;
diff --git a/chromium/third_party/WebKit/Source/core/rendering/PointerEventsHitRules.h b/chromium/third_party/WebKit/Source/core/rendering/PointerEventsHitRules.h
index bc0e24cd81b..1ffd98bc237 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/PointerEventsHitRules.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/PointerEventsHitRules.h
@@ -29,7 +29,7 @@ class PointerEventsHitRules {
public:
enum EHitTesting {
SVG_IMAGE_HITTESTING,
- SVG_PATH_HITTESTING,
+ SVG_GEOMETRY_HITTESTING,
SVG_TEXT_HITTESTING
};
@@ -40,6 +40,7 @@ public:
bool requireStroke;
bool canHitStroke;
bool canHitFill;
+ bool canHitBoundingBox;
};
}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderBR.h b/chromium/third_party/WebKit/Source/core/rendering/RenderBR.h
index a5ad8ff1f80..62d1a53479e 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderBR.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderBR.h
@@ -60,21 +60,7 @@ private:
mutable int m_lineHeight;
};
-
-inline RenderBR* toRenderBR(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isBR());
- return static_cast<RenderBR*>(object);
-}
-
-inline const RenderBR* toRenderBR(const RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isBR());
- return static_cast<const RenderBR*>(object);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toRenderBR(const RenderBR*);
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderBR, isBR());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderBlock.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderBlock.cpp
index 9b1ac42a850..84c790b6ab7 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderBlock.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderBlock.cpp
@@ -28,22 +28,22 @@
#include "core/accessibility/AXObjectCache.h"
#include "core/dom/Document.h"
#include "core/dom/Element.h"
-#include "core/dom/OverflowEvent.h"
+#include "core/events/OverflowEvent.h"
#include "core/dom/shadow/ShadowRoot.h"
#include "core/editing/Editor.h"
#include "core/editing/FrameSelection.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameView.h"
+#include "core/fetch/ResourceLoadPriorityOptimizer.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
#include "core/page/Page.h"
-#include "core/page/Settings.h"
-#include "core/platform/graphics/FloatQuad.h"
-#include "core/platform/graphics/GraphicsContextStateSaver.h"
-#include "core/platform/graphics/transforms/TransformState.h"
-#include "core/rendering/ColumnInfo.h"
+#include "core/frame/Settings.h"
+#include "core/rendering/FastTextAutosizer.h"
+#include "core/rendering/GraphicsContextAnnotator.h"
#include "core/rendering/HitTestLocation.h"
#include "core/rendering/HitTestResult.h"
#include "core/rendering/InlineIterator.h"
#include "core/rendering/InlineTextBox.h"
+#include "core/rendering/LayoutRectRecorder.h"
#include "core/rendering/LayoutRepainter.h"
#include "core/rendering/PaintInfo.h"
#include "core/rendering/RenderCombineText.h"
@@ -58,9 +58,12 @@
#include "core/rendering/RenderTextFragment.h"
#include "core/rendering/RenderTheme.h"
#include "core/rendering/RenderView.h"
-#include "core/rendering/shapes/ShapeInsideInfo.h"
#include "core/rendering/shapes/ShapeOutsideInfo.h"
-#include "core/rendering/svg/SVGTextRunRenderingContext.h"
+#include "core/rendering/style/ContentData.h"
+#include "core/rendering/style/RenderStyle.h"
+#include "platform/geometry/FloatQuad.h"
+#include "platform/geometry/TransformState.h"
+#include "platform/graphics/GraphicsContextStateSaver.h"
#include "wtf/StdLibExtras.h"
#include "wtf/TemporaryChange.h"
@@ -73,7 +76,7 @@ namespace WebCore {
using namespace HTMLNames;
struct SameSizeAsRenderBlock : public RenderBox {
- void* pointers[2];
+ void* pointers[1];
RenderObjectChildList children;
RenderLineBoxList lineBoxes;
uint32_t bitfields;
@@ -98,17 +101,13 @@ static DelayedUpdateScrollInfoSet* gDelayedUpdateScrollInfoSet = 0;
static bool gColumnFlowSplitEnabled = true;
-bool RenderBlock::s_canPropagateFloatIntoSibling = false;
-
// This class helps dispatching the 'overflow' event on layout change. overflow can be set on RenderBoxes, yet the existing code
-// only works on RenderBlocks. If this change, this class should be shared with other RenderBoxes.
+// only works on RenderBlocks. If this changes, this class should be shared with other RenderBoxes.
class OverflowEventDispatcher {
WTF_MAKE_NONCOPYABLE(OverflowEventDispatcher);
public:
OverflowEventDispatcher(const RenderBlock* block)
: m_block(block)
- , m_hadHorizontalLayoutOverflow(false)
- , m_hadVerticalLayoutOverflow(false)
{
m_shouldDispatchEvent = !m_block->isAnonymous() && m_block->hasOverflowClip() && m_block->document().hasListenerType(Document::OVERFLOWCHANGED_LISTENER);
if (m_shouldDispatchEvent) {
@@ -127,10 +126,13 @@ public:
bool horizontalLayoutOverflowChanged = hasHorizontalLayoutOverflow != m_hadHorizontalLayoutOverflow;
bool verticalLayoutOverflowChanged = hasVerticalLayoutOverflow != m_hadVerticalLayoutOverflow;
- if (horizontalLayoutOverflowChanged || verticalLayoutOverflowChanged) {
- if (FrameView* frameView = m_block->document().view())
- frameView->scheduleEvent(OverflowEvent::create(horizontalLayoutOverflowChanged, hasHorizontalLayoutOverflow, verticalLayoutOverflowChanged, hasVerticalLayoutOverflow), m_block->node());
- }
+
+ if (!horizontalLayoutOverflowChanged && !verticalLayoutOverflowChanged)
+ return;
+
+ RefPtr<OverflowEvent> event = OverflowEvent::create(horizontalLayoutOverflowChanged, hasHorizontalLayoutOverflow, verticalLayoutOverflowChanged, hasVerticalLayoutOverflow);
+ event->setTarget(m_block->node());
+ m_block->document().enqueueAnimationFrameEvent(event.release());
}
private:
@@ -170,6 +172,19 @@ static void removeBlockFromDescendantAndContainerMaps(RenderBlock* block, Tracke
}
}
+static void appendImageIfNotNull(Vector<ImageResource*>& imageResources, const StyleImage* styleImage)
+{
+ if (styleImage && styleImage->cachedImage())
+ imageResources.append(styleImage->cachedImage());
+}
+
+static void appendLayers(Vector<ImageResource*>& images, const FillLayer* styleLayer)
+{
+ for (const FillLayer* layer = styleLayer; layer; layer = layer->next()) {
+ appendImageIfNotNull(images, layer->image());
+ }
+}
+
RenderBlock::~RenderBlock()
{
if (hasColumns())
@@ -180,13 +195,6 @@ RenderBlock::~RenderBlock()
removeBlockFromDescendantAndContainerMaps(this, gPositionedDescendantsMap, gPositionedContainerMap);
}
-RenderBlock* RenderBlock::createAnonymous(Document* document)
-{
- RenderBlock* renderer = new RenderBlockFlow(0);
- renderer->setDocumentForAnonymous(document);
- return renderer;
-}
-
void RenderBlock::willBeDestroyed()
{
// Mark as being destroyed to avoid trouble with merges in removeChild().
@@ -229,19 +237,19 @@ void RenderBlock::willBeDestroyed()
m_lineBoxes.deleteLineBoxes();
- if (lineGridBox())
- lineGridBox()->destroy();
-
if (UNLIKELY(gDelayedUpdateScrollInfoSet != 0))
gDelayedUpdateScrollInfoSet->remove(this);
+ FastTextAutosizer* textAutosizer = document().fastTextAutosizer();
+ if (textAutosizer)
+ textAutosizer->destroy(this);
+
RenderBox::willBeDestroyed();
}
void RenderBlock::styleWillChange(StyleDifference diff, const RenderStyle* newStyle)
{
RenderStyle* oldStyle = style();
- s_canPropagateFloatIntoSibling = oldStyle ? !isFloatingOrOutOfFlowPositioned() && !avoidsFloats() : false;
setReplaced(newStyle->isDisplayInlineType());
@@ -265,9 +273,6 @@ void RenderBlock::styleWillChange(StyleDifference diff, const RenderStyle* newSt
if (cb->isRenderBlock())
toRenderBlock(cb)->removePositionedObjects(this, NewContainingBlock);
}
-
- if (containsFloats() && !isFloating() && !isOutOfFlowPositioned() && newStyle->hasOutOfFlowPosition())
- markAllDescendantsWithFloatsForLayout();
}
RenderBox::styleWillChange(diff, newStyle);
@@ -293,7 +298,7 @@ void RenderBlock::styleDidChange(StyleDifference diff, const RenderStyle* oldSty
RenderStyle* newStyle = style();
- updateShapeInsideInfoAfterStyleChange(newStyle->resolvedShapeInside(), oldStyle ? oldStyle->resolvedShapeInside() : 0);
+ updateShapeInsideInfoAfterStyleChange(newStyle->resolvedShapeInside(), oldStyle ? oldStyle->resolvedShapeInside() : RenderStyle::initialShapeInside());
if (!isAnonymousBlock()) {
// Ensure that all of our continuation blocks pick up the new style.
@@ -305,39 +310,13 @@ void RenderBlock::styleDidChange(StyleDifference diff, const RenderStyle* oldSty
}
}
+ FastTextAutosizer* textAutosizer = document().fastTextAutosizer();
+ if (textAutosizer)
+ textAutosizer->record(this);
+
propagateStyleToAnonymousChildren(true);
m_lineHeight = -1;
- // After our style changed, if we lose our ability to propagate floats into next sibling
- // blocks, then we need to find the top most parent containing that overhanging float and
- // then mark its descendants with floats for layout and clear all floats from its next
- // sibling blocks that exist in our floating objects list. See bug 56299 and 62875.
- bool canPropagateFloatIntoSibling = !isFloatingOrOutOfFlowPositioned() && !avoidsFloats();
- if (diff == StyleDifferenceLayout && s_canPropagateFloatIntoSibling && !canPropagateFloatIntoSibling && hasOverhangingFloats()) {
- RenderBlock* parentBlock = this;
- const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
- FloatingObjectSetIterator end = floatingObjectSet.end();
-
- for (RenderObject* curr = parent(); curr && !curr->isRenderView(); curr = curr->parent()) {
- if (curr->isRenderBlock()) {
- RenderBlock* currBlock = toRenderBlock(curr);
-
- if (currBlock->hasOverhangingFloats()) {
- for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
- RenderBox* renderer = (*it)->renderer();
- if (currBlock->hasOverhangingFloat(renderer)) {
- parentBlock = currBlock;
- break;
- }
- }
- }
- }
- }
-
- parentBlock->markAllDescendantsWithFloatsForLayout();
- parentBlock->markSiblingsWithFloatsForLayout();
- }
-
// It's possible for our border/padding to change, but for the overall logical width of the block to
// end up being the same. We keep track of this change so in layoutBlock, we can know to set relayoutChildren=true.
m_hasBorderOrPaddingLogicalWidthChanged = oldStyle && diff == StyleDifferenceLayout && needsLayout() && borderOrPaddingLogicalWidthChanged(oldStyle, newStyle);
@@ -475,7 +454,7 @@ void RenderBlock::addChildToAnonymousColumnBlocks(RenderObject* newChild, Render
return;
}
-RenderBlock* RenderBlock::containingColumnsBlock(bool allowAnonymousColumnBlock)
+RenderBlockFlow* RenderBlock::containingColumnsBlock(bool allowAnonymousColumnBlock)
{
RenderBlock* firstChildIgnoringAnonymousWrappers = 0;
for (RenderObject* curr = this; curr; curr = curr->parent()) {
@@ -483,18 +462,18 @@ RenderBlock* RenderBlock::containingColumnsBlock(bool allowAnonymousColumnBlock)
|| curr->isInlineBlockOrInlineTable())
return 0;
- // FIXME: Tables, RenderButtons, and RenderListItems all do special management
- // of their children that breaks when the flow is split through them. Disabling
- // multi-column for them to avoid this problem.
- if (curr->isTable() || curr->isRenderButton() || curr->isListItem())
+ // FIXME: Renderers that do special management of their children (tables, buttons,
+ // lists, flexboxes, etc.) breaks when the flow is split through them. Disabling
+ // multi-column for them to avoid this problem.)
+ if (!curr->isRenderBlockFlow() || curr->isListItem())
return 0;
- RenderBlock* currBlock = toRenderBlock(curr);
+ RenderBlockFlow* currBlock = toRenderBlockFlow(curr);
if (!currBlock->createsAnonymousWrapper())
firstChildIgnoringAnonymousWrappers = currBlock;
if (currBlock->style()->specifiesColumns() && (allowAnonymousColumnBlock || !currBlock->isAnonymousColumnsBlock()))
- return firstChildIgnoringAnonymousWrappers;
+ return toRenderBlockFlow(firstChildIgnoringAnonymousWrappers);
if (currBlock->isAnonymousColumnSpanBlock())
return 0;
@@ -609,7 +588,8 @@ void RenderBlock::splitFlow(RenderObject* beforeChild, RenderBlock* newBlockBox,
// We can reuse this block and make it the preBlock of the next continuation.
pre = block;
pre->removePositionedObjects(0);
- pre->removeFloatingObjects();
+ if (block->isRenderBlockFlow())
+ toRenderBlockFlow(pre)->removeFloatingObjects();
block = toRenderBlock(block->parent());
} else {
// No anonymous block available for use. Make one.
@@ -647,10 +627,10 @@ void RenderBlock::splitFlow(RenderObject* beforeChild, RenderBlock* newBlockBox,
post->setNeedsLayoutAndPrefWidthsRecalc();
}
-void RenderBlock::makeChildrenAnonymousColumnBlocks(RenderObject* beforeChild, RenderBlock* newBlockBox, RenderObject* newChild)
+void RenderBlock::makeChildrenAnonymousColumnBlocks(RenderObject* beforeChild, RenderBlockFlow* newBlockBox, RenderObject* newChild)
{
- RenderBlock* pre = 0;
- RenderBlock* post = 0;
+ RenderBlockFlow* pre = 0;
+ RenderBlockFlow* post = 0;
RenderBlock* block = this; // Eventually block will not just be |this|, but will also be a block nested inside |this|. Assign to a variable
// so that we don't have to patch all of the rest of the code later on.
@@ -698,7 +678,7 @@ void RenderBlock::makeChildrenAnonymousColumnBlocks(RenderObject* beforeChild, R
post->setNeedsLayoutAndPrefWidthsRecalc();
}
-RenderBlock* RenderBlock::columnsBlockForSpanningElement(RenderObject* newChild)
+RenderBlockFlow* RenderBlock::columnsBlockForSpanningElement(RenderObject* newChild)
{
// FIXME: This function is the gateway for the addition of column-span support. It will
// be added to in three stages:
@@ -707,7 +687,7 @@ RenderBlock* RenderBlock::columnsBlockForSpanningElement(RenderObject* newChild)
// (3) Nested children with block or inline ancestors between them and the multi-column block can span (this is when we
// cross the streams and have to cope with both types of continuations mixed together).
// This function currently supports (1) and (2).
- RenderBlock* columnsBlockAncestor = 0;
+ RenderBlockFlow* columnsBlockAncestor = 0;
if (!newChild->isText() && newChild->style()->columnSpan() && !newChild->isBeforeOrAfterContent()
&& !newChild->isFloatingOrOutOfFlowPositioned() && !newChild->isInline() && !isAnonymousColumnSpanBlock()) {
columnsBlockAncestor = containingColumnsBlock(false);
@@ -767,27 +747,16 @@ void RenderBlock::addChildIgnoringAnonymousColumnBlocks(RenderObject* newChild,
// safe fallback to use the topmost beforeChild container.
beforeChild = beforeChildContainer;
}
- } else {
- // We will reach here when beforeChild is a run-in element.
- // If run-in element precedes a block-level element, it becomes the
- // the first inline child of that block level element. The insertion
- // point will be before that block-level element.
- ASSERT(beforeChild->isRunIn());
- beforeChild = beforeChildContainer;
}
}
- // Nothing goes before the intruded run-in.
- if (beforeChild && beforeChild->isRunIn() && runInIsPlacedIntoSiblingBlock(beforeChild))
- beforeChild = beforeChild->nextSibling();
-
// Check for a spanning element in columns.
if (gColumnFlowSplitEnabled) {
- RenderBlock* columnsBlockAncestor = columnsBlockForSpanningElement(newChild);
+ RenderBlockFlow* columnsBlockAncestor = columnsBlockForSpanningElement(newChild);
if (columnsBlockAncestor) {
TemporaryChange<bool> columnFlowSplitEnabled(gColumnFlowSplitEnabled, false);
// We are placing a column-span element inside a block.
- RenderBlock* newBox = createAnonymousColumnSpanBlock();
+ RenderBlockFlow* newBox = createAnonymousColumnSpanBlock();
if (columnsBlockAncestor != this && !isRenderFlowThread()) {
// We are nested inside a multi-column element and are being split by the span. We have to break up
@@ -848,9 +817,6 @@ void RenderBlock::addChildIgnoringAnonymousColumnBlocks(RenderObject* newChild,
RenderBox::addChild(newChild, beforeChild);
- // Handle placement of run-ins.
- placeRunInIfNeeded(newChild);
-
if (madeBoxesNonInline && parent() && isAnonymousBlock() && parent()->isRenderBlock())
toRenderBlock(parent())->removeLeftoverAnonymousBlock(this);
// this object may be dead here
@@ -914,19 +880,12 @@ static void getInlineRun(RenderObject* start, RenderObject* boundary,
void RenderBlock::deleteLineBoxTree()
{
- if (containsFloats())
- m_floatingObjects->clearLineBoxTreePointers();
m_lineBoxes.deleteLineBoxTree();
if (AXObjectCache* cache = document().existingAXObjectCache())
cache->recomputeIsIgnored(this);
}
-RootInlineBox* RenderBlock::createRootInlineBox()
-{
- return new RootInlineBox(this);
-}
-
RootInlineBox* RenderBlock::createAndAppendRootInlineBox()
{
RootInlineBox* rootBox = createRootInlineBox();
@@ -960,13 +919,6 @@ void RenderBlock::makeChildrenNonInline(RenderObject *insertionPoint)
deleteLineBoxTree();
- // Since we are going to have block children, we have to move
- // back the run-in to its original place.
- if (child->isRunIn()) {
- moveRunInToOriginalPosition(child);
- child = firstChild();
- }
-
while (child) {
RenderObject *inlineRunStart, *inlineRunEnd;
getInlineRun(child, insertionPoint, inlineRunStart, inlineRunEnd);
@@ -1050,10 +1002,6 @@ static bool canMergeContiguousAnonymousBlocks(RenderObject* oldChild, RenderObje
|| (next && (!next->isAnonymousBlock() || toRenderBlock(next)->continuation() || toRenderBlock(next)->beingDestroyed())))
return false;
- // FIXME: This check isn't required when inline run-ins can't be split into continuations.
- if (prev && prev->firstChild() && prev->firstChild()->isInline() && prev->firstChild()->isRunIn())
- return false;
-
if ((prev && (prev->isRubyRun() || prev->isRubyBase()))
|| (next && (next->isRubyRun() || next->isRubyBase())))
return false;
@@ -1090,47 +1038,6 @@ void RenderBlock::collapseAnonymousBlockChild(RenderBlock* parent, RenderBlock*
child->destroy();
}
-void RenderBlock::moveAllChildrenIncludingFloatsTo(RenderBlock* toBlock, bool fullRemoveInsert)
-{
- moveAllChildrenTo(toBlock, fullRemoveInsert);
-
- // When a portion of the render tree is being detached, anonymous blocks
- // will be combined as their children are deleted. In this process, the
- // anonymous block later in the tree is merged into the one preceeding it.
- // It can happen that the later block (this) contains floats that the
- // previous block (toBlock) did not contain, and thus are not in the
- // floating objects list for toBlock. This can result in toBlock containing
- // floats that are not in it's floating objects list, but are in the
- // floating objects lists of siblings and parents. This can cause problems
- // when the float itself is deleted, since the deletion code assumes that
- // if a float is not in it's containing block's floating objects list, it
- // isn't in any floating objects list. In order to preserve this condition
- // (removing it has serious performance implications), we need to copy the
- // floating objects from the old block (this) to the new block (toBlock).
- // The float's metrics will likely all be wrong, but since toBlock is
- // already marked for layout, this will get fixed before anything gets
- // displayed.
- // See bug https://code.google.com/p/chromium/issues/detail?id=230907
- if (m_floatingObjects) {
- if (!toBlock->m_floatingObjects)
- toBlock->createFloatingObjects();
-
- const FloatingObjectSet& fromFloatingObjectSet = m_floatingObjects->set();
- FloatingObjectSetIterator end = fromFloatingObjectSet.end();
-
- for (FloatingObjectSetIterator it = fromFloatingObjectSet.begin(); it != end; ++it) {
- FloatingObject* floatingObject = *it;
-
- // Don't insert the object again if it's already in the list
- if (toBlock->containsFloat(floatingObject->renderer()))
- continue;
-
- toBlock->m_floatingObjects->add(floatingObject->unsafeClone());
- }
- }
-
-}
-
void RenderBlock::removeChild(RenderObject* oldChild)
{
// No need to waste time in merging or removing empty anonymous blocks.
@@ -1313,7 +1220,7 @@ void RenderBlock::finishDelayUpdateScrollInfo()
for (DelayedUpdateScrollInfoSet::iterator it = infoSet->begin(); it != infoSet->end(); ++it) {
RenderBlock* block = *it;
if (block->hasOverflowClip()) {
- block->layer()->updateScrollInfoAfterLayout();
+ block->layer()->scrollableArea()->updateAfterLayout();
}
}
}
@@ -1327,20 +1234,21 @@ void RenderBlock::updateScrollInfoAfterLayout()
// Workaround for now. We cannot delay the scroll info for overflow
// for items with opposite writing directions, as the contents needs
// to overflow in that direction
- layer()->updateScrollInfoAfterLayout();
+ layer()->scrollableArea()->updateAfterLayout();
return;
}
if (gDelayUpdateScrollInfo)
gDelayedUpdateScrollInfoSet->add(this);
else
- layer()->updateScrollInfoAfterLayout();
+ layer()->scrollableArea()->updateAfterLayout();
}
}
void RenderBlock::layout()
{
OverflowEventDispatcher dispatcher(this);
+ LayoutRectRecorder recorder(*this);
// Update our first letter info now.
updateFirstLetter();
@@ -1360,6 +1268,60 @@ void RenderBlock::layout()
invalidateBackgroundObscurationStatus();
}
+void RenderBlock::didLayout(ResourceLoadPriorityOptimizer& optimizer)
+{
+ RenderBox::didLayout(optimizer);
+ updateStyleImageLoadingPriorities(optimizer);
+}
+
+void RenderBlock::didScroll(ResourceLoadPriorityOptimizer& optimizer)
+{
+ RenderBox::didScroll(optimizer);
+ updateStyleImageLoadingPriorities(optimizer);
+}
+
+void RenderBlock::updateStyleImageLoadingPriorities(ResourceLoadPriorityOptimizer& optimizer)
+{
+ RenderStyle* blockStyle = style();
+ if (!blockStyle)
+ return;
+
+ Vector<ImageResource*> images;
+
+ appendLayers(images, blockStyle->backgroundLayers());
+ appendLayers(images, blockStyle->maskLayers());
+
+ const ContentData* contentData = blockStyle->contentData();
+ if (contentData && contentData->isImage()) {
+ const ImageContentData* imageContentData = static_cast<const ImageContentData*>(contentData);
+ appendImageIfNotNull(images, imageContentData->image());
+ }
+ if (blockStyle->boxReflect())
+ appendImageIfNotNull(images, blockStyle->boxReflect()->mask().image());
+ appendImageIfNotNull(images, blockStyle->listStyleImage());
+ appendImageIfNotNull(images, blockStyle->borderImageSource());
+ appendImageIfNotNull(images, blockStyle->maskBoxImageSource());
+
+ if (images.isEmpty())
+ return;
+
+ LayoutRect viewBounds = viewRect();
+ LayoutRect objectBounds = absoluteContentBox();
+ // The object bounds might be empty right now, so intersects will fail since it doesn't deal
+ // with empty rects. Use LayoutRect::contains in that case.
+ bool isVisible;
+ if (!objectBounds.isEmpty())
+ isVisible = viewBounds.intersects(objectBounds);
+ else
+ isVisible = viewBounds.contains(objectBounds);
+
+ ResourceLoadPriorityOptimizer::VisibilityStatus status = isVisible ?
+ ResourceLoadPriorityOptimizer::Visible : ResourceLoadPriorityOptimizer::NotVisible;
+
+ for (Vector<ImageResource*>::iterator it = images.begin(), end = images.end(); it != end; ++it)
+ optimizer.notifyImageResourceVisibility(*it, status);
+}
+
void RenderBlock::relayoutShapeDescendantIfMoved(RenderBlock* child, LayoutSize offset)
{
LayoutUnit left = isHorizontalWritingMode() ? offset.width() : offset.height();
@@ -1372,6 +1334,24 @@ void RenderBlock::relayoutShapeDescendantIfMoved(RenderBlock* child, LayoutSize
child->layoutIfNeeded();
}
+ShapeInsideInfo* RenderBlock::layoutShapeInsideInfo() const
+{
+ if (ShapeInsideInfo* shapeInsideInfo = view()->layoutState()->shapeInsideInfo())
+ return shapeInsideInfo;
+
+ RenderFlowThread* flowThread = flowThreadContainingBlock();
+ if (allowsShapeInsideInfoSharing(flowThread)) {
+ LayoutUnit lineHeight = this->lineHeight(false, isHorizontalWritingMode() ? HorizontalLine : VerticalLine, PositionOfInteriorLineBoxes);
+ // regionAtBlockOffset returns regions like an array first={0,N-1}, second={N,M-1}, ...
+ LayoutUnit offset = logicalHeight() + lineHeight - LayoutUnit(1);
+ RenderRegion* region = regionAtBlockOffset(offset);
+ if (region && region->logicalHeight())
+ return region->shapeInsideInfo();
+ }
+
+ return 0;
+}
+
LayoutSize RenderBlock::logicalOffsetFromShapeAncestorContainer(const RenderBlock* container) const
{
const RenderBlock* currentBlock = this;
@@ -1408,7 +1388,7 @@ void RenderBlock::imageChanged(WrappedImagePtr image, const IntRect*)
{
RenderBox::imageChanged(image);
- if (!parent())
+ if (!parent() || !everHadLayout())
return;
ShapeValue* shapeValue = style()->shapeInside();
@@ -1417,6 +1397,10 @@ void RenderBlock::imageChanged(WrappedImagePtr image, const IntRect*)
shapeInsideInfo->dirtyShapeSize();
markShapeInsideDescendantsForLayout();
}
+
+ ShapeValue* shapeOutsideValue = style()->shapeOutside();
+ if (isFloating() && shapeOutsideValue && shapeOutsideValue->image() && shapeOutsideValue->image()->data() == image)
+ parent()->setNeedsLayoutAndPrefWidthsRecalc();
}
void RenderBlock::updateShapeInsideInfoAfterStyleChange(const ShapeValue* shapeInside, const ShapeValue* oldShapeInside)
@@ -1454,7 +1438,7 @@ bool RenderBlock::updateRegionsAndShapesLogicalSize(RenderFlowThread* flowThread
// Compute the maximum logical height content may cause this block to expand to
// FIXME: These should eventually use the const computeLogicalHeight rather than updateLogicalHeight
- setLogicalHeight(LayoutUnit::max() / 2);
+ setLogicalHeight(RenderFlowThread::maxLogicalHeight());
updateLogicalHeight();
computeShapeSize();
@@ -1472,7 +1456,14 @@ bool RenderBlock::updateRegionsAndShapesLogicalSize(RenderFlowThread* flowThread
void RenderBlock::computeShapeSize()
{
ShapeInsideInfo* shapeInsideInfo = this->shapeInsideInfo();
- if (shapeInsideInfo) {
+ if (!shapeInsideInfo)
+ return;
+
+ if (isRenderNamedFlowFragment()) {
+ ShapeInsideInfo* parentShapeInsideInfo = toRenderBlock(parent())->shapeInsideInfo();
+ ASSERT(parentShapeInsideInfo);
+ shapeInsideInfo->setShapeSize(parentShapeInsideInfo->shapeSize().width(), parentShapeInsideInfo->shapeSize().height());
+ } else {
bool percentageLogicalHeightResolvable = percentageLogicalHeightIsResolvableFromBlock(this, false);
shapeInsideInfo->setShapeSize(logicalWidth(), percentageLogicalHeightResolvable ? logicalHeight() : LayoutUnit());
}
@@ -1548,7 +1539,7 @@ void RenderBlock::addOverflowFromChildren()
{
if (!hasColumns()) {
if (childrenInline())
- addOverflowFromInlineChildren();
+ toRenderBlockFlow(this)->addOverflowFromInlineChildren();
else
addOverflowFromBlockChildren();
} else {
@@ -1561,16 +1552,13 @@ void RenderBlock::addOverflowFromChildren()
}
}
-void RenderBlock::computeOverflow(LayoutUnit oldClientAfterEdge, bool recomputeFloats)
+void RenderBlock::computeOverflow(LayoutUnit oldClientAfterEdge, bool)
{
m_overflow.clear();
// Add overflow from children.
addOverflowFromChildren();
- if (!hasColumns() && (recomputeFloats || isRoot() || expandsToEncloseOverhangingFloats() || hasSelfPaintingLayer()))
- addOverflowFromFloats();
-
// Add in the overflow from positioned objects.
addOverflowFromPositionedObjects();
@@ -1589,14 +1577,6 @@ void RenderBlock::computeOverflow(LayoutUnit oldClientAfterEdge, bool recomputeF
m_overflow->setLayoutClientAfterEdge(oldClientAfterEdge);
}
- // Allow our overflow to catch cases where the caret in an empty editable element with negative text indent needs to get painted.
- LayoutUnit textIndent = textIndentOffset();
- if (textIndent < 0) {
- LayoutRect clientRect(noOverflowRect());
- LayoutRect rectToApply = LayoutRect(clientRect.x() + textIndent, clientRect.y(), clientRect.width() - textIndent, clientRect.height());
- addContentsVisualOverflow(rectToApply);
- }
-
// Add visual overflow from box-shadow and border-image-outset.
addVisualEffectOverflow();
@@ -1615,20 +1595,6 @@ void RenderBlock::addOverflowFromBlockChildren()
}
}
-void RenderBlock::addOverflowFromFloats()
-{
- if (!m_floatingObjects)
- return;
-
- const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
- FloatingObjectSetIterator end = floatingObjectSet.end();
- for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
- FloatingObject* r = *it;
- if (r->isDescendant())
- addOverflowFromChild(r->renderer(), IntSize(xPositionForFloatIncludingMargin(r), yPositionForFloatIncludingMargin(r)));
- }
-}
-
void RenderBlock::addOverflowFromPositionedObjects()
{
TrackedRendererListHashSet* positionedDescendants = positionedObjects();
@@ -1641,12 +1607,8 @@ void RenderBlock::addOverflowFromPositionedObjects()
positionedObject = *it;
// Fixed positioned elements don't contribute to layout overflow, since they don't scroll with the content.
- if (positionedObject->style()->position() != FixedPosition) {
- LayoutUnit x = positionedObject->x();
- if (style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
- x -= verticalScrollbarWidth();
- addOverflowFromChild(positionedObject, LayoutSize(x, positionedObject->y()));
- }
+ if (positionedObject->style()->position() != FixedPosition)
+ addOverflowFromChild(positionedObject, LayoutSize(positionedObject->x(), positionedObject->y()));
}
}
@@ -1666,146 +1628,6 @@ bool RenderBlock::expandsToEncloseOverhangingFloats() const
|| hasColumns() || isTableCell() || isTableCaption() || isFieldset() || isWritingModeRoot() || isRoot();
}
-static void destroyRunIn(RenderBoxModelObject* runIn)
-{
- ASSERT(runIn->isRunIn());
- ASSERT(!runIn->firstChild());
-
- // Delete our line box tree. This is needed as our children got moved
- // and our line box tree is no longer valid.
- if (runIn->isRenderBlock())
- toRenderBlock(runIn)->deleteLineBoxTree();
- else if (runIn->isRenderInline())
- toRenderInline(runIn)->deleteLineBoxTree();
- else
- ASSERT_NOT_REACHED();
-
- runIn->destroy();
-}
-
-void RenderBlock::placeRunInIfNeeded(RenderObject* newChild)
-{
- if (newChild->isRunIn())
- moveRunInUnderSiblingBlockIfNeeded(newChild);
- else if (RenderObject* prevSibling = newChild->previousSibling()) {
- if (prevSibling->isRunIn())
- moveRunInUnderSiblingBlockIfNeeded(prevSibling);
- }
-}
-
-RenderBoxModelObject* RenderBlock::createReplacementRunIn(RenderBoxModelObject* runIn)
-{
- ASSERT(runIn->isRunIn());
- ASSERT(runIn->node());
-
- RenderBoxModelObject* newRunIn = 0;
- if (!runIn->isRenderBlockFlow())
- newRunIn = new RenderBlockFlow(runIn->node());
- else
- newRunIn = new RenderInline(toElement(runIn->node()));
-
- runIn->node()->setRenderer(newRunIn);
- newRunIn->setStyle(runIn->style());
-
- runIn->moveAllChildrenTo(newRunIn, true);
-
- return newRunIn;
-}
-
-void RenderBlock::moveRunInUnderSiblingBlockIfNeeded(RenderObject* runIn)
-{
- ASSERT(runIn->isRunIn());
-
- // See if we have inline children. If the children aren't inline,
- // then just treat the run-in as a normal block.
- if (!runIn->childrenInline())
- return;
-
- // FIXME: We don't handle non-block flow elements with run-in for now.
- if (!runIn->isRenderBlockFlow())
- return;
-
- // FIXME: We don't support run-ins with or as part of a continuation
- // as it makes the back-and-forth placing complex.
- if (runIn->isElementContinuation() || runIn->virtualContinuation())
- return;
-
- // Check if this node is allowed to run-in. E.g. <select> expects its renderer to
- // be a RenderListBox or RenderMenuList, and hence cannot be a RenderInline run-in.
- if (!runIn->canBeReplacedWithInlineRunIn())
- return;
-
- RenderObject* curr = runIn->nextSibling();
- if (!curr || !curr->isRenderBlock() || !curr->childrenInline())
- return;
-
- // Per CSS3, "A run-in cannot run in to a block that already starts with a
- // run-in or that itself is a run-in".
- if (curr->isRunIn() || (curr->firstChild() && curr->firstChild()->isRunIn()))
- return;
-
- if (curr->isAnonymous() || curr->isFloatingOrOutOfFlowPositioned())
- return;
-
- // FIXME: We don't support run-ins with or as part of a continuation
- // as it makes the back-and-forth placing complex.
- if (curr->isElementContinuation() || curr->virtualContinuation())
- return;
-
- RenderBoxModelObject* oldRunIn = toRenderBoxModelObject(runIn);
- RenderBoxModelObject* newRunIn = createReplacementRunIn(oldRunIn);
- destroyRunIn(oldRunIn);
-
- // Now insert the new child under |curr| block. Use addChild instead of insertChildNode
- // since it handles correct placement of the children, especially where we cannot insert
- // anything before the first child. e.g. details tag. See https://bugs.webkit.org/show_bug.cgi?id=58228.
- curr->addChild(newRunIn, curr->firstChild());
-
- // Make sure that |this| get a layout since its run-in child moved.
- curr->setNeedsLayoutAndPrefWidthsRecalc();
-}
-
-bool RenderBlock::runInIsPlacedIntoSiblingBlock(RenderObject* runIn)
-{
- ASSERT(runIn->isRunIn());
-
- // If we don't have a parent, we can't be moved into our sibling block.
- if (!parent())
- return false;
-
- // An intruded run-in needs to be an inline.
- if (!runIn->isRenderInline())
- return false;
-
- return true;
-}
-
-void RenderBlock::moveRunInToOriginalPosition(RenderObject* runIn)
-{
- ASSERT(runIn->isRunIn());
-
- if (!runInIsPlacedIntoSiblingBlock(runIn))
- return;
-
- // FIXME: Run-in that are now placed in sibling block can break up into continuation
- // chains when new children are added to it. We cannot easily send them back to their
- // original place since that requires writing integration logic with RenderInline::addChild
- // and all other places that might cause continuations to be created (without blowing away
- // |this|). Disabling this feature for now to prevent crashes.
- if (runIn->isElementContinuation() || runIn->virtualContinuation())
- return;
-
- RenderBoxModelObject* oldRunIn = toRenderBoxModelObject(runIn);
- RenderBoxModelObject* newRunIn = createReplacementRunIn(oldRunIn);
- destroyRunIn(oldRunIn);
-
- // Add the run-in block as our previous sibling.
- parent()->addChild(newRunIn, this);
-
- // Make sure that the parent holding the new run-in gets layout.
- parent()->setNeedsLayoutAndPrefWidthsRecalc();
-}
-
LayoutUnit RenderBlock::computeStartPositionDeltaForChildAvoidingFloats(const RenderBox* child, LayoutUnit childMarginStart, RenderRegion* region)
{
LayoutUnit startPosition = startOffsetForContent(region);
@@ -1818,7 +1640,7 @@ LayoutUnit RenderBlock::computeStartPositionDeltaForChildAvoidingFloats(const Re
if (region)
blockOffset = max(blockOffset, blockOffset + (region->logicalTopForFlowThreadContent() - offsetFromLogicalTopOfFirstPage()));
- LayoutUnit startOff = startOffsetForLine(blockOffset, false, region, logicalHeightForChild(child));
+ LayoutUnit startOff = startOffsetForLineInRegion(blockOffset, false, region, logicalHeightForChild(child));
if (style()->textAlign() != WEBKIT_CENTER && !child->style()->marginStartUsing(style()).isAuto()) {
if (childMarginStart < 0)
@@ -2096,36 +1918,10 @@ void RenderBlock::markForPaginationRelayoutIfNeeded(SubtreeLayoutScope& layoutSc
if (needsLayout())
return;
- if (view()->layoutState()->pageLogicalHeightChanged() || (view()->layoutState()->pageLogicalHeight() && view()->layoutState()->pageLogicalOffset(this, logicalTop()) != pageLogicalOffset()) || shouldBreakAtLineToAvoidWidow())
+ if (view()->layoutState()->pageLogicalHeightChanged() || (view()->layoutState()->pageLogicalHeight() && view()->layoutState()->pageLogicalOffset(this, logicalTop()) != pageLogicalOffset()))
layoutScope.setChildNeedsLayout(this);
}
-void RenderBlock::repaintOverhangingFloats(bool paintAllDescendants)
-{
- // Repaint any overhanging floats (if we know we're the one to paint them).
- // Otherwise, bail out.
- if (!hasOverhangingFloats())
- return;
-
- // FIXME: Avoid disabling LayoutState. At the very least, don't disable it for floats originating
- // in this block. Better yet would be to push extra state for the containers of other floats.
- LayoutStateDisabler layoutStateDisabler(view());
- const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
- FloatingObjectSetIterator end = floatingObjectSet.end();
- for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
- FloatingObject* r = *it;
- // Only repaint the object if it is overhanging, is not in its own layer, and
- // is our responsibility to paint (m_shouldPaint is set). When paintAllDescendants is true, the latter
- // condition is replaced with being a descendant of us.
- if (r->logicalBottom(isHorizontalWritingMode()) > logicalHeight()
- && !r->renderer()->hasSelfPaintingLayer()
- && (r->shouldPaint() || (paintAllDescendants && r->renderer()->isDescendantOf(this)))) {
- r->renderer()->repaint();
- r->renderer()->repaintOverhangingFloats(false);
- }
- }
-}
-
void RenderBlock::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
{
ANNOTATE_GRAPHICS_CONTEXT(paintInfo, this);
@@ -2161,7 +1957,7 @@ void RenderBlock::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
// z-index. We paint after we painted the background/border, so that the scrollbars will
// sit above the background/border.
if (hasOverflowClip() && style()->visibility() == VISIBLE && (phase == PaintPhaseBlockBackground || phase == PaintPhaseChildBlockBackground) && paintInfo.shouldPaintWithinRoot(this) && !paintInfo.paintRootBackgroundOnly())
- layer()->paintOverflowControls(paintInfo.context, roundedIntPoint(adjustedPaintOffset), paintInfo.rect);
+ layer()->scrollableArea()->paintOverflowControls(paintInfo.context, roundedIntPoint(adjustedPaintOffset), paintInfo.rect, false /* paintingOverlayControls */);
}
void RenderBlock::paintColumnRules(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
@@ -2408,12 +2204,17 @@ void RenderBlock::paintObject(PaintInfo& paintInfo, const LayoutPoint& paintOffs
{
PaintPhase paintPhase = paintInfo.phase;
+ // Adjust our painting position if we're inside a scrolled layer (e.g., an overflow:auto div).
+ LayoutPoint scrolledOffset = paintOffset;
+ if (hasOverflowClip())
+ scrolledOffset.move(-scrolledContentOffset());
+
// 1. paint background, borders etc
if ((paintPhase == PaintPhaseBlockBackground || paintPhase == PaintPhaseChildBlockBackground) && style()->visibility() == VISIBLE) {
if (hasBoxDecorations())
paintBoxDecorations(paintInfo, paintOffset);
if (hasColumns() && !paintInfo.paintRootBackgroundOnly())
- paintColumnRules(paintInfo, paintOffset);
+ paintColumnRules(paintInfo, scrolledOffset);
}
if (paintPhase == PaintPhaseMask && style()->visibility() == VISIBLE) {
@@ -2421,15 +2222,15 @@ void RenderBlock::paintObject(PaintInfo& paintInfo, const LayoutPoint& paintOffs
return;
}
+ if (paintPhase == PaintPhaseClippingMask && style()->visibility() == VISIBLE) {
+ paintClippingMask(paintInfo, paintOffset);
+ return;
+ }
+
// We're done. We don't bother painting any children.
if (paintPhase == PaintPhaseBlockBackground || paintInfo.paintRootBackgroundOnly())
return;
- // Adjust our painting position if we're inside a scrolled layer (e.g., an overflow:auto div).
- LayoutPoint scrolledOffset = paintOffset;
- if (hasOverflowClip())
- scrolledOffset.move(-scrolledContentOffset());
-
// 2. paint contents
if (paintPhase != PaintPhaseSelfOutline) {
if (hasColumns())
@@ -2491,49 +2292,6 @@ void RenderBlock::paintObject(PaintInfo& paintInfo, const LayoutPoint& paintOffs
}
}
-LayoutPoint RenderBlock::flipFloatForWritingModeForChild(const FloatingObject* child, const LayoutPoint& point) const
-{
- if (!style()->isFlippedBlocksWritingMode())
- return point;
-
- // This is similar to RenderBox::flipForWritingModeForChild. We have to subtract out our left/top offsets twice, since
- // it's going to get added back in. We hide this complication here so that the calling code looks normal for the unflipped
- // case.
- if (isHorizontalWritingMode())
- return LayoutPoint(point.x(), point.y() + height() - child->renderer()->height() - 2 * yPositionForFloatIncludingMargin(child));
- return LayoutPoint(point.x() + width() - child->renderer()->width() - 2 * xPositionForFloatIncludingMargin(child), point.y());
-}
-
-void RenderBlock::paintFloats(PaintInfo& paintInfo, const LayoutPoint& paintOffset, bool preservePhase)
-{
- if (!m_floatingObjects)
- return;
-
- const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
- FloatingObjectSetIterator end = floatingObjectSet.end();
- for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
- FloatingObject* r = *it;
- // Only paint the object if our m_shouldPaint flag is set.
- if (r->shouldPaint() && !r->renderer()->hasSelfPaintingLayer()) {
- PaintInfo currentPaintInfo(paintInfo);
- currentPaintInfo.phase = preservePhase ? paintInfo.phase : PaintPhaseBlockBackground;
- // FIXME: LayoutPoint version of xPositionForFloatIncludingMargin would make this much cleaner.
- LayoutPoint childPoint = flipFloatForWritingModeForChild(r, LayoutPoint(paintOffset.x() + xPositionForFloatIncludingMargin(r) - r->renderer()->x(), paintOffset.y() + yPositionForFloatIncludingMargin(r) - r->renderer()->y()));
- r->renderer()->paint(currentPaintInfo, childPoint);
- if (!preservePhase) {
- currentPaintInfo.phase = PaintPhaseChildBlockBackgrounds;
- r->renderer()->paint(currentPaintInfo, childPoint);
- currentPaintInfo.phase = PaintPhaseFloat;
- r->renderer()->paint(currentPaintInfo, childPoint);
- currentPaintInfo.phase = PaintPhaseForeground;
- r->renderer()->paint(currentPaintInfo, childPoint);
- currentPaintInfo.phase = PaintPhaseOutline;
- r->renderer()->paint(currentPaintInfo, childPoint);
- }
- }
- }
-}
-
RenderInline* RenderBlock::inlineElementContinuation() const
{
RenderBoxModelObject* continuation = this->continuation();
@@ -2699,14 +2457,14 @@ static void clipOutPositionedObjects(const PaintInfo* paintInfo, const LayoutPoi
}
}
-static LayoutUnit blockDirectionOffset(RenderBlock* rootBlock, const LayoutSize& offsetFromRootBlock)
+LayoutUnit RenderBlock::blockDirectionOffset(const LayoutSize& offsetFromBlock) const
{
- return rootBlock->isHorizontalWritingMode() ? offsetFromRootBlock.height() : offsetFromRootBlock.width();
+ return isHorizontalWritingMode() ? offsetFromBlock.height() : offsetFromBlock.width();
}
-static LayoutUnit inlineDirectionOffset(RenderBlock* rootBlock, const LayoutSize& offsetFromRootBlock)
+LayoutUnit RenderBlock::inlineDirectionOffset(const LayoutSize& offsetFromBlock) const
{
- return rootBlock->isHorizontalWritingMode() ? offsetFromRootBlock.width() : offsetFromRootBlock.height();
+ return isHorizontalWritingMode() ? offsetFromBlock.width() : offsetFromBlock.height();
}
LayoutRect RenderBlock::logicalRectToPhysicalRect(const LayoutPoint& rootBlockPhysicalPosition, const LayoutRect& logicalRect)
@@ -2735,19 +2493,7 @@ GapRects RenderBlock::selectionGaps(RenderBlock* rootBlock, const LayoutPoint& r
if (isBody() || isRoot()) // The <body> must make sure to examine its containingBlock's positioned objects.
for (RenderBlock* cb = containingBlock(); cb && !cb->isRenderView(); cb = cb->containingBlock())
clipOutPositionedObjects(paintInfo, LayoutPoint(cb->x(), cb->y()), cb->positionedObjects()); // FIXME: Not right for flipped writing modes.
- if (m_floatingObjects) {
- const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
- FloatingObjectSetIterator end = floatingObjectSet.end();
- for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
- FloatingObject* r = *it;
- LayoutRect floatBox(offsetFromRootBlock.width() + xPositionForFloatIncludingMargin(r),
- offsetFromRootBlock.height() + yPositionForFloatIncludingMargin(r),
- r->renderer()->width(), r->renderer()->height());
- rootBlock->flipForWritingMode(floatBox);
- floatBox.move(rootBlockPhysicalPosition.x(), rootBlockPhysicalPosition.y());
- paintInfo->context->clipOut(pixelSnappedIntRect(floatBox));
- }
- }
+ clipOutFloatingObjects(rootBlock, paintInfo, rootBlockPhysicalPosition, offsetFromRootBlock);
}
// FIXME: overflow: auto/scroll regions need more math here, since painting in the border box is different from painting in the padding box (one is scrolled, the other is
@@ -2758,14 +2504,14 @@ GapRects RenderBlock::selectionGaps(RenderBlock* rootBlock, const LayoutPoint& r
if (hasColumns() || hasTransform() || style()->columnSpan()) {
// FIXME: We should learn how to gap fill multiple columns and transforms eventually.
- lastLogicalTop = blockDirectionOffset(rootBlock, offsetFromRootBlock) + logicalHeight();
+ lastLogicalTop = rootBlock->blockDirectionOffset(offsetFromRootBlock) + logicalHeight();
lastLogicalLeft = logicalLeftSelectionOffset(rootBlock, logicalHeight());
lastLogicalRight = logicalRightSelectionOffset(rootBlock, logicalHeight());
return result;
}
if (childrenInline())
- result = inlineSelectionGaps(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, lastLogicalTop, lastLogicalLeft, lastLogicalRight, paintInfo);
+ result = toRenderBlockFlow(this)->inlineSelectionGaps(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, lastLogicalTop, lastLogicalLeft, lastLogicalRight, paintInfo);
else
result = blockSelectionGaps(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, lastLogicalTop, lastLogicalLeft, lastLogicalRight, paintInfo);
@@ -2776,61 +2522,6 @@ GapRects RenderBlock::selectionGaps(RenderBlock* rootBlock, const LayoutPoint& r
return result;
}
-GapRects RenderBlock::inlineSelectionGaps(RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
- LayoutUnit& lastLogicalTop, LayoutUnit& lastLogicalLeft, LayoutUnit& lastLogicalRight, const PaintInfo* paintInfo)
-{
- GapRects result;
-
- bool containsStart = selectionState() == SelectionStart || selectionState() == SelectionBoth;
-
- if (!firstLineBox()) {
- if (containsStart) {
- // Go ahead and update our lastLogicalTop to be the bottom of the block. <hr>s or empty blocks with height can trip this
- // case.
- lastLogicalTop = blockDirectionOffset(rootBlock, offsetFromRootBlock) + logicalHeight();
- lastLogicalLeft = logicalLeftSelectionOffset(rootBlock, logicalHeight());
- lastLogicalRight = logicalRightSelectionOffset(rootBlock, logicalHeight());
- }
- return result;
- }
-
- RootInlineBox* lastSelectedLine = 0;
- RootInlineBox* curr;
- for (curr = firstRootBox(); curr && !curr->hasSelectedChildren(); curr = curr->nextRootBox()) { }
-
- // Now paint the gaps for the lines.
- for (; curr && curr->hasSelectedChildren(); curr = curr->nextRootBox()) {
- LayoutUnit selTop = curr->selectionTopAdjustedForPrecedingBlock();
- LayoutUnit selHeight = curr->selectionHeightAdjustedForPrecedingBlock();
-
- if (!containsStart && !lastSelectedLine &&
- selectionState() != SelectionStart && selectionState() != SelectionBoth)
- result.uniteCenter(blockSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, lastLogicalTop, lastLogicalLeft, lastLogicalRight,
- selTop, paintInfo));
-
- LayoutRect logicalRect(curr->logicalLeft(), selTop, curr->logicalWidth(), selTop + selHeight);
- logicalRect.move(isHorizontalWritingMode() ? offsetFromRootBlock : offsetFromRootBlock.transposedSize());
- LayoutRect physicalRect = rootBlock->logicalRectToPhysicalRect(rootBlockPhysicalPosition, logicalRect);
- if (!paintInfo || (isHorizontalWritingMode() && physicalRect.y() < paintInfo->rect.maxY() && physicalRect.maxY() > paintInfo->rect.y())
- || (!isHorizontalWritingMode() && physicalRect.x() < paintInfo->rect.maxX() && physicalRect.maxX() > paintInfo->rect.x()))
- result.unite(curr->lineSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, selTop, selHeight, paintInfo));
-
- lastSelectedLine = curr;
- }
-
- if (containsStart && !lastSelectedLine)
- // VisibleSelection must start just after our last line.
- lastSelectedLine = lastRootBox();
-
- if (lastSelectedLine && selectionState() != SelectionEnd && selectionState() != SelectionBoth) {
- // Go ahead and update our lastY to be the bottom of the last selected line.
- lastLogicalTop = blockDirectionOffset(rootBlock, offsetFromRootBlock) + lastSelectedLine->selectionBottom();
- lastLogicalLeft = logicalLeftSelectionOffset(rootBlock, lastSelectedLine->selectionBottom());
- lastLogicalRight = logicalRightSelectionOffset(rootBlock, lastSelectedLine->selectionBottom());
- }
- return result;
-}
-
GapRects RenderBlock::blockSelectionGaps(RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
LayoutUnit& lastLogicalTop, LayoutUnit& lastLogicalLeft, LayoutUnit& lastLogicalRight, const PaintInfo* paintInfo)
{
@@ -2882,7 +2573,7 @@ GapRects RenderBlock::blockSelectionGaps(RenderBlock* rootBlock, const LayoutPoi
// Update lastLogicalTop to be just underneath the object. lastLogicalLeft and lastLogicalRight extend as far as
// they can without bumping into floating or positioned objects. Ideally they will go right up
// to the border of the root selection block.
- lastLogicalTop = blockDirectionOffset(rootBlock, offsetFromRootBlock) + curr->logicalBottom();
+ lastLogicalTop = rootBlock->blockDirectionOffset(offsetFromRootBlock) + curr->logicalBottom();
lastLogicalLeft = logicalLeftSelectionOffset(rootBlock, curr->logicalBottom());
lastLogicalRight = logicalRightSelectionOffset(rootBlock, curr->logicalBottom());
} else if (childState != SelectionNone)
@@ -2897,7 +2588,7 @@ LayoutRect RenderBlock::blockSelectionGap(RenderBlock* rootBlock, const LayoutPo
LayoutUnit lastLogicalTop, LayoutUnit lastLogicalLeft, LayoutUnit lastLogicalRight, LayoutUnit logicalBottom, const PaintInfo* paintInfo)
{
LayoutUnit logicalTop = lastLogicalTop;
- LayoutUnit logicalHeight = blockDirectionOffset(rootBlock, offsetFromRootBlock) + logicalBottom - logicalTop;
+ LayoutUnit logicalHeight = rootBlock->blockDirectionOffset(offsetFromRootBlock) + logicalBottom - logicalTop;
if (logicalHeight <= 0)
return LayoutRect();
@@ -2917,9 +2608,9 @@ LayoutRect RenderBlock::blockSelectionGap(RenderBlock* rootBlock, const LayoutPo
LayoutRect RenderBlock::logicalLeftSelectionGap(RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
RenderObject* selObj, LayoutUnit logicalLeft, LayoutUnit logicalTop, LayoutUnit logicalHeight, const PaintInfo* paintInfo)
{
- LayoutUnit rootBlockLogicalTop = blockDirectionOffset(rootBlock, offsetFromRootBlock) + logicalTop;
+ LayoutUnit rootBlockLogicalTop = rootBlock->blockDirectionOffset(offsetFromRootBlock) + logicalTop;
LayoutUnit rootBlockLogicalLeft = max(logicalLeftSelectionOffset(rootBlock, logicalTop), logicalLeftSelectionOffset(rootBlock, logicalTop + logicalHeight));
- LayoutUnit rootBlockLogicalRight = min(inlineDirectionOffset(rootBlock, offsetFromRootBlock) + floorToInt(logicalLeft), min(logicalRightSelectionOffset(rootBlock, logicalTop), logicalRightSelectionOffset(rootBlock, logicalTop + logicalHeight)));
+ LayoutUnit rootBlockLogicalRight = min(rootBlock->inlineDirectionOffset(offsetFromRootBlock) + floorToInt(logicalLeft), min(logicalRightSelectionOffset(rootBlock, logicalTop), logicalRightSelectionOffset(rootBlock, logicalTop + logicalHeight)));
LayoutUnit rootBlockLogicalWidth = rootBlockLogicalRight - rootBlockLogicalLeft;
if (rootBlockLogicalWidth <= 0)
return LayoutRect();
@@ -2933,8 +2624,8 @@ LayoutRect RenderBlock::logicalLeftSelectionGap(RenderBlock* rootBlock, const La
LayoutRect RenderBlock::logicalRightSelectionGap(RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
RenderObject* selObj, LayoutUnit logicalRight, LayoutUnit logicalTop, LayoutUnit logicalHeight, const PaintInfo* paintInfo)
{
- LayoutUnit rootBlockLogicalTop = blockDirectionOffset(rootBlock, offsetFromRootBlock) + logicalTop;
- LayoutUnit rootBlockLogicalLeft = max(inlineDirectionOffset(rootBlock, offsetFromRootBlock) + floorToInt(logicalRight), max(logicalLeftSelectionOffset(rootBlock, logicalTop), logicalLeftSelectionOffset(rootBlock, logicalTop + logicalHeight)));
+ LayoutUnit rootBlockLogicalTop = rootBlock->blockDirectionOffset(offsetFromRootBlock) + logicalTop;
+ LayoutUnit rootBlockLogicalLeft = max(rootBlock->inlineDirectionOffset(offsetFromRootBlock) + floorToInt(logicalRight), max(logicalLeftSelectionOffset(rootBlock, logicalTop), logicalLeftSelectionOffset(rootBlock, logicalTop + logicalHeight)));
LayoutUnit rootBlockLogicalRight = min(logicalRightSelectionOffset(rootBlock, logicalTop), logicalRightSelectionOffset(rootBlock, logicalTop + logicalHeight));
LayoutUnit rootBlockLogicalWidth = rootBlockLogicalRight - rootBlockLogicalLeft;
if (rootBlockLogicalWidth <= 0)
@@ -3139,301 +2830,6 @@ void RenderBlock::removePositionedObjects(RenderBlock* o, ContainingBlockState c
removePositionedObject(deadObjects.at(i));
}
-void RenderBlock::removeFloatingObjects()
-{
- if (!m_floatingObjects)
- return;
-
- m_floatingObjects->clear();
-}
-
-FloatingObject* RenderBlock::insertFloatingObject(RenderBox* o)
-{
- ASSERT(o->isFloating());
-
- // Create the list of special objects if we don't aleady have one
- if (!m_floatingObjects)
- createFloatingObjects();
- else {
- // Don't insert the object again if it's already in the list
- const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
- FloatingObjectSetIterator it = floatingObjectSet.find<RenderBox*, FloatingObjectHashTranslator>(o);
- if (it != floatingObjectSet.end())
- return *it;
- }
-
- // Create the special object entry & append it to the list
-
- OwnPtr<FloatingObject> newObj = FloatingObject::create(o);
-
- // Our location is irrelevant if we're unsplittable or no pagination is in effect.
- // Just go ahead and lay out the float.
- bool isChildRenderBlock = o->isRenderBlock();
- if (isChildRenderBlock && !o->needsLayout() && view()->layoutState()->pageLogicalHeightChanged())
- o->setChildNeedsLayout(MarkOnlyThis);
-
- bool needsBlockDirectionLocationSetBeforeLayout = isChildRenderBlock && view()->layoutState()->needsBlockDirectionLocationSetBeforeLayout();
- if (!needsBlockDirectionLocationSetBeforeLayout || isWritingModeRoot()) // We are unsplittable if we're a block flow root.
- o->layoutIfNeeded();
- else {
- o->updateLogicalWidth();
- o->computeAndSetBlockDirectionMargins(this);
- }
-
- newObj->setLogicalWidth(logicalWidthForChild(o) + marginStartForChild(o) + marginEndForChild(o), isHorizontalWritingMode());
-
- if (ShapeOutsideInfo* shapeOutside = o->shapeOutsideInfo())
- shapeOutside->setShapeSize(logicalWidthForChild(o), logicalHeightForChild(o));
-
- return m_floatingObjects->add(newObj.release());
-}
-
-void RenderBlock::removeFloatingObject(RenderBox* o)
-{
- if (m_floatingObjects) {
- const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
- FloatingObjectSetIterator it = floatingObjectSet.find<RenderBox*, FloatingObjectHashTranslator>(o);
- if (it != floatingObjectSet.end()) {
- FloatingObject* r = *it;
- if (childrenInline()) {
- LayoutUnit logicalTop = r->logicalTop(isHorizontalWritingMode());
- LayoutUnit logicalBottom = r->logicalBottom(isHorizontalWritingMode());
-
- // Fix for https://bugs.webkit.org/show_bug.cgi?id=54995.
- if (logicalBottom < 0 || logicalBottom < logicalTop || logicalTop == LayoutUnit::max())
- logicalBottom = LayoutUnit::max();
- else {
- // Special-case zero- and less-than-zero-height floats: those don't touch
- // the line that they're on, but it still needs to be dirtied. This is
- // accomplished by pretending they have a height of 1.
- logicalBottom = max(logicalBottom, logicalTop + 1);
- }
- if (r->originatingLine()) {
- if (!selfNeedsLayout()) {
- ASSERT(r->originatingLine()->renderer() == this);
- r->originatingLine()->markDirty();
- }
-#if !ASSERT_DISABLED
- r->setOriginatingLine(0);
-#endif
- }
- markLinesDirtyInBlockRange(0, logicalBottom);
- }
- m_floatingObjects->remove(r);
- }
- }
-}
-
-void RenderBlock::removeFloatingObjectsBelow(FloatingObject* lastFloat, int logicalOffset)
-{
- if (!containsFloats())
- return;
-
- const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
- FloatingObject* curr = floatingObjectSet.last();
- while (curr != lastFloat && (!curr->isPlaced() || curr->logicalTop(isHorizontalWritingMode()) >= logicalOffset)) {
- m_floatingObjects->remove(curr);
- if (floatingObjectSet.isEmpty())
- break;
- curr = floatingObjectSet.last();
- }
-}
-
-LayoutPoint RenderBlock::computeLogicalLocationForFloat(const FloatingObject* floatingObject, LayoutUnit logicalTopOffset) const
-{
- RenderBox* childBox = floatingObject->renderer();
- LayoutUnit logicalLeftOffset = logicalLeftOffsetForContent(logicalTopOffset); // Constant part of left offset.
- LayoutUnit logicalRightOffset; // Constant part of right offset.
- // FIXME Bug 102948: This only works for shape outside directly set on this block.
- ShapeInsideInfo* shapeInsideInfo = this->shapeInsideInfo();
- // FIXME: We should place the float based on its width/height.
- if (shapeInsideInfo)
- shapeInsideInfo->computeSegmentsForLine(logicalTopOffset, childBox->logicalHeight());
- if (shapeInsideInfo && shapeInsideInfo->hasSegments() && shapeInsideInfo->segments().size() == 1) {
- // FIXME Bug 102949: Add support for shapes with multipe segments.
-
- // The segment offsets are relative to the content box.
- logicalRightOffset = logicalLeftOffset + shapeInsideInfo->segments()[0].logicalRight;
- logicalLeftOffset += shapeInsideInfo->segments()[0].logicalLeft;
- } else
- logicalRightOffset = logicalRightOffsetForContent(logicalTopOffset);
-
- LayoutUnit floatLogicalWidth = min(floatingObject->logicalWidth(isHorizontalWritingMode()), logicalRightOffset - logicalLeftOffset); // The width we look for.
-
- LayoutUnit floatLogicalLeft;
-
- bool insideFlowThread = flowThreadContainingBlock();
-
- if (childBox->style()->floating() == LeftFloat) {
- LayoutUnit heightRemainingLeft = 1;
- LayoutUnit heightRemainingRight = 1;
- floatLogicalLeft = logicalLeftOffsetForLineIgnoringShapeOutside(logicalTopOffset, logicalLeftOffset, false, &heightRemainingLeft);
- while (logicalRightOffsetForLineIgnoringShapeOutside(logicalTopOffset, logicalRightOffset, false, &heightRemainingRight) - floatLogicalLeft < floatLogicalWidth) {
- logicalTopOffset += min(heightRemainingLeft, heightRemainingRight);
- floatLogicalLeft = logicalLeftOffsetForLineIgnoringShapeOutside(logicalTopOffset, logicalLeftOffset, false, &heightRemainingLeft);
- if (insideFlowThread) {
- // Have to re-evaluate all of our offsets, since they may have changed.
- logicalRightOffset = logicalRightOffsetForContent(logicalTopOffset); // Constant part of right offset.
- logicalLeftOffset = logicalLeftOffsetForContent(logicalTopOffset); // Constant part of left offset.
- floatLogicalWidth = min(floatingObject->logicalWidth(isHorizontalWritingMode()), logicalRightOffset - logicalLeftOffset);
- }
- }
- floatLogicalLeft = max(logicalLeftOffset - borderAndPaddingLogicalLeft(), floatLogicalLeft);
- } else {
- LayoutUnit heightRemainingLeft = 1;
- LayoutUnit heightRemainingRight = 1;
- floatLogicalLeft = logicalRightOffsetForLineIgnoringShapeOutside(logicalTopOffset, logicalRightOffset, false, &heightRemainingRight);
- while (floatLogicalLeft - logicalLeftOffsetForLineIgnoringShapeOutside(logicalTopOffset, logicalLeftOffset, false, &heightRemainingLeft) < floatLogicalWidth) {
- logicalTopOffset += min(heightRemainingLeft, heightRemainingRight);
- floatLogicalLeft = logicalRightOffsetForLineIgnoringShapeOutside(logicalTopOffset, logicalRightOffset, false, &heightRemainingRight);
- if (insideFlowThread) {
- // Have to re-evaluate all of our offsets, since they may have changed.
- logicalRightOffset = logicalRightOffsetForContent(logicalTopOffset); // Constant part of right offset.
- logicalLeftOffset = logicalLeftOffsetForContent(logicalTopOffset); // Constant part of left offset.
- floatLogicalWidth = min(floatingObject->logicalWidth(isHorizontalWritingMode()), logicalRightOffset - logicalLeftOffset);
- }
- }
- floatLogicalLeft -= floatingObject->logicalWidth(isHorizontalWritingMode()); // Use the original width of the float here, since the local variable
- // |floatLogicalWidth| was capped to the available line width.
- // See fast/block/float/clamped-right-float.html.
- }
-
- return LayoutPoint(floatLogicalLeft, logicalTopOffset);
-}
-
-bool RenderBlock::positionNewFloats()
-{
- if (!m_floatingObjects)
- return false;
-
- const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
- if (floatingObjectSet.isEmpty())
- return false;
-
- // If all floats have already been positioned, then we have no work to do.
- if (floatingObjectSet.last()->isPlaced())
- return false;
-
- // Move backwards through our floating object list until we find a float that has
- // already been positioned. Then we'll be able to move forward, positioning all of
- // the new floats that need it.
- FloatingObjectSetIterator it = floatingObjectSet.end();
- --it; // Go to last item.
- FloatingObjectSetIterator begin = floatingObjectSet.begin();
- FloatingObject* lastPlacedFloatingObject = 0;
- while (it != begin) {
- --it;
- if ((*it)->isPlaced()) {
- lastPlacedFloatingObject = *it;
- ++it;
- break;
- }
- }
-
- LayoutUnit logicalTop = logicalHeight();
-
- // The float cannot start above the top position of the last positioned float.
- if (lastPlacedFloatingObject)
- logicalTop = max(lastPlacedFloatingObject->logicalTop(isHorizontalWritingMode()), logicalTop);
-
- FloatingObjectSetIterator end = floatingObjectSet.end();
- // Now walk through the set of unpositioned floats and place them.
- for (; it != end; ++it) {
- FloatingObject* floatingObject = *it;
- // The containing block is responsible for positioning floats, so if we have floats in our
- // list that come from somewhere else, do not attempt to position them.
- if (floatingObject->renderer()->containingBlock() != this)
- continue;
-
- RenderBox* childBox = floatingObject->renderer();
- LayoutUnit childLogicalLeftMargin = style()->isLeftToRightDirection() ? marginStartForChild(childBox) : marginEndForChild(childBox);
-
- LayoutRect oldRect = childBox->frameRect();
-
- if (childBox->style()->clear() & CLEFT)
- logicalTop = max(lowestFloatLogicalBottom(FloatingObject::FloatLeft), logicalTop);
- if (childBox->style()->clear() & CRIGHT)
- logicalTop = max(lowestFloatLogicalBottom(FloatingObject::FloatRight), logicalTop);
-
- LayoutPoint floatLogicalLocation = computeLogicalLocationForFloat(floatingObject, logicalTop);
-
- floatingObject->setLogicalLeft(floatLogicalLocation.x(), isHorizontalWritingMode());
-
- setLogicalLeftForChild(childBox, floatLogicalLocation.x() + childLogicalLeftMargin);
- setLogicalTopForChild(childBox, floatLogicalLocation.y() + marginBeforeForChild(childBox));
-
- SubtreeLayoutScope layoutScope(childBox);
- LayoutState* layoutState = view()->layoutState();
- bool isPaginated = layoutState->isPaginated();
- if (isPaginated && !childBox->needsLayout())
- childBox->markForPaginationRelayoutIfNeeded(layoutScope);
-
- childBox->layoutIfNeeded();
-
- if (isPaginated) {
- // If we are unsplittable and don't fit, then we need to move down.
- // We include our margins as part of the unsplittable area.
- LayoutUnit newLogicalTop = adjustForUnsplittableChild(childBox, floatLogicalLocation.y(), true);
-
- // See if we have a pagination strut that is making us move down further.
- // Note that an unsplittable child can't also have a pagination strut, so this is
- // exclusive with the case above.
- RenderBlock* childBlock = childBox->isRenderBlock() ? toRenderBlock(childBox) : 0;
- if (childBlock && childBlock->paginationStrut()) {
- newLogicalTop += childBlock->paginationStrut();
- childBlock->setPaginationStrut(0);
- }
-
- if (newLogicalTop != floatLogicalLocation.y()) {
- floatingObject->setPaginationStrut(newLogicalTop - floatLogicalLocation.y());
-
- floatLogicalLocation = computeLogicalLocationForFloat(floatingObject, newLogicalTop);
- floatingObject->setLogicalLeft(floatLogicalLocation.x(), isHorizontalWritingMode());
-
- setLogicalLeftForChild(childBox, floatLogicalLocation.x() + childLogicalLeftMargin);
- setLogicalTopForChild(childBox, floatLogicalLocation.y() + marginBeforeForChild(childBox));
-
- if (childBlock)
- childBlock->setChildNeedsLayout(MarkOnlyThis);
- childBox->layoutIfNeeded();
- }
- }
-
- floatingObject->setLogicalTop(floatLogicalLocation.y(), isHorizontalWritingMode());
-
- floatingObject->setLogicalHeight(logicalHeightForChild(childBox) + marginBeforeForChild(childBox) + marginAfterForChild(childBox), isHorizontalWritingMode());
-
- m_floatingObjects->addPlacedObject(floatingObject);
-
- // If the child moved, we have to repaint it.
- if (childBox->checkForRepaintDuringLayout())
- childBox->repaintDuringLayoutIfMoved(oldRect);
- }
- return true;
-}
-
-void RenderBlock::newLine(EClear clear)
-{
- positionNewFloats();
- // set y position
- LayoutUnit newY = 0;
- switch (clear)
- {
- case CLEFT:
- newY = lowestFloatLogicalBottom(FloatingObject::FloatLeft);
- break;
- case CRIGHT:
- newY = lowestFloatLogicalBottom(FloatingObject::FloatRight);
- break;
- case CBOTH:
- newY = lowestFloatLogicalBottom();
- default:
- break;
- }
- if (height() < newY)
- setLogicalHeight(newY);
-}
-
void RenderBlock::addPercentHeightDescendant(RenderBox* descendant)
{
insertIntoTrackedRendererMaps(descendant, gPercentHeightDescendantsMap, gPercentHeightContainerMap);
@@ -3546,14 +2942,6 @@ LayoutUnit RenderBlock::logicalRightOffsetForContent(RenderRegion* region) const
return logicalRightOffset - (logicalWidth() - (isHorizontalWritingMode() ? boxRect.maxX() : boxRect.maxY()));
}
-LayoutUnit RenderBlock::logicalLeftFloatOffsetForLine(LayoutUnit logicalTop, LayoutUnit fixedOffset, LayoutUnit* heightRemaining, LayoutUnit logicalHeight, ShapeOutsideFloatOffsetMode offsetMode) const
-{
- if (m_floatingObjects && m_floatingObjects->hasLeftObjects())
- return m_floatingObjects->logicalLeftOffset(fixedOffset, logicalTop, logicalHeight, offsetMode, heightRemaining);
-
- return fixedOffset;
-}
-
LayoutUnit RenderBlock::adjustLogicalLeftOffsetForLine(LayoutUnit offsetFromFloats, bool applyTextIndent) const
{
LayoutUnit left = offsetFromFloats;
@@ -3592,14 +2980,6 @@ LayoutUnit RenderBlock::adjustLogicalLeftOffsetForLine(LayoutUnit offsetFromFloa
return left;
}
-LayoutUnit RenderBlock::logicalRightFloatOffsetForLine(LayoutUnit logicalTop, LayoutUnit fixedOffset, LayoutUnit* heightRemaining, LayoutUnit logicalHeight, ShapeOutsideFloatOffsetMode offsetMode) const
-{
- if (m_floatingObjects && m_floatingObjects->hasRightObjects())
- return m_floatingObjects->logicalRightOffset(fixedOffset, logicalTop, logicalHeight, offsetMode, heightRemaining);
-
- return fixedOffset;
-}
-
LayoutUnit RenderBlock::adjustLogicalRightOffsetForLine(LayoutUnit offsetFromFloats, bool applyTextIndent) const
{
LayoutUnit right = offsetFromFloats;
@@ -3638,32 +3018,6 @@ LayoutUnit RenderBlock::adjustLogicalRightOffsetForLine(LayoutUnit offsetFromFlo
return right;
}
-LayoutUnit RenderBlock::nextFloatLogicalBottomBelow(LayoutUnit logicalHeight) const
-{
- if (!m_floatingObjects)
- return logicalHeight;
-
- LayoutUnit bottom = LayoutUnit::max();
- const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
- FloatingObjectSetIterator end = floatingObjectSet.end();
- for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
- FloatingObject* r = *it;
- LayoutUnit floatBottom = r->logicalBottom(isHorizontalWritingMode());
- if (floatBottom > logicalHeight)
- bottom = min(floatBottom, bottom);
- }
-
- return bottom == LayoutUnit::max() ? LayoutUnit() : bottom;
-}
-
-LayoutUnit RenderBlock::lowestFloatLogicalBottom(FloatingObject::Type floatType) const
-{
- if (!m_floatingObjects)
- return 0;
-
- return m_floatingObjects->lowestFloatLogicalBottom(floatType);
-}
-
void RenderBlock::markLinesDirtyInBlockRange(LayoutUnit logicalTop, LayoutUnit logicalBottom, RootInlineBox* highest)
{
if (logicalTop >= logicalBottom)
@@ -3682,124 +3036,12 @@ void RenderBlock::markLinesDirtyInBlockRange(LayoutUnit logicalTop, LayoutUnit l
}
}
-LayoutUnit RenderBlock::addOverhangingFloats(RenderBlock* child, bool makeChildPaintOtherFloats)
-{
- // Prevent floats from being added to the canvas by the root element, e.g., <html>.
- if (child->hasOverflowClip() || !child->containsFloats() || child->isRoot() || child->hasColumns() || child->isWritingModeRoot())
- return 0;
-
- LayoutUnit childLogicalTop = child->logicalTop();
- LayoutUnit childLogicalLeft = child->logicalLeft();
- LayoutUnit lowestFloatLogicalBottom = 0;
-
- // Floats that will remain the child's responsibility to paint should factor into its
- // overflow.
- FloatingObjectSetIterator childEnd = child->m_floatingObjects->set().end();
- for (FloatingObjectSetIterator childIt = child->m_floatingObjects->set().begin(); childIt != childEnd; ++childIt) {
- FloatingObject* r = *childIt;
- LayoutUnit logicalBottomForFloat = min(r->logicalBottom(isHorizontalWritingMode()), LayoutUnit::max() - childLogicalTop);
- LayoutUnit logicalBottom = childLogicalTop + logicalBottomForFloat;
- lowestFloatLogicalBottom = max(lowestFloatLogicalBottom, logicalBottom);
-
- if (logicalBottom > logicalHeight()) {
- // If the object is not in the list, we add it now.
- if (!containsFloat(r->renderer())) {
- LayoutSize offset = isHorizontalWritingMode() ? LayoutSize(-childLogicalLeft, -childLogicalTop) : LayoutSize(-childLogicalTop, -childLogicalLeft);
- bool shouldPaint = false;
-
- // The nearest enclosing layer always paints the float (so that zindex and stacking
- // behaves properly). We always want to propagate the desire to paint the float as
- // far out as we can, to the outermost block that overlaps the float, stopping only
- // if we hit a self-painting layer boundary.
- if (r->renderer()->enclosingFloatPaintingLayer() == enclosingFloatPaintingLayer()) {
- r->setShouldPaint(false);
- shouldPaint = true;
- }
- // We create the floating object list lazily.
- if (!m_floatingObjects)
- createFloatingObjects();
-
- m_floatingObjects->add(r->copyToNewContainer(offset, shouldPaint, true));
- }
- } else {
- if (makeChildPaintOtherFloats && !r->shouldPaint() && !r->renderer()->hasSelfPaintingLayer()
- && r->renderer()->isDescendantOf(child) && r->renderer()->enclosingFloatPaintingLayer() == child->enclosingFloatPaintingLayer()) {
- // The float is not overhanging from this block, so if it is a descendant of the child, the child should
- // paint it (the other case is that it is intruding into the child), unless it has its own layer or enclosing
- // layer.
- // If makeChildPaintOtherFloats is false, it means that the child must already know about all the floats
- // it should paint.
- r->setShouldPaint(true);
- }
-
- // Since the float doesn't overhang, it didn't get put into our list. We need to go ahead and add its overflow in to the
- // child now.
- if (r->isDescendant())
- child->addOverflowFromChild(r->renderer(), LayoutSize(xPositionForFloatIncludingMargin(r), yPositionForFloatIncludingMargin(r)));
- }
- }
- return lowestFloatLogicalBottom;
-}
-
-bool RenderBlock::hasOverhangingFloat(RenderBox* renderer)
-{
- if (!m_floatingObjects || hasColumns() || !parent())
- return false;
-
- const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
- FloatingObjectSetIterator it = floatingObjectSet.find<RenderBox*, FloatingObjectHashTranslator>(renderer);
- if (it == floatingObjectSet.end())
- return false;
-
- return (*it)->logicalBottom(isHorizontalWritingMode()) > logicalHeight();
-}
-
-void RenderBlock::addIntrudingFloats(RenderBlock* prev, LayoutUnit logicalLeftOffset, LayoutUnit logicalTopOffset)
-{
- ASSERT(!avoidsFloats());
-
- // If the parent or previous sibling doesn't have any floats to add, don't bother.
- if (!prev->m_floatingObjects)
- return;
-
- logicalLeftOffset += marginLogicalLeft();
-
- const FloatingObjectSet& prevSet = prev->m_floatingObjects->set();
- FloatingObjectSetIterator prevEnd = prevSet.end();
- for (FloatingObjectSetIterator prevIt = prevSet.begin(); prevIt != prevEnd; ++prevIt) {
- FloatingObject* r = *prevIt;
- if (r->logicalBottom(isHorizontalWritingMode()) > logicalTopOffset) {
- if (!m_floatingObjects || !m_floatingObjects->set().contains(r)) {
- // We create the floating object list lazily.
- if (!m_floatingObjects)
- createFloatingObjects();
-
- // Applying the child's margin makes no sense in the case where the child was passed in.
- // since this margin was added already through the modification of the |logicalLeftOffset| variable
- // above. |logicalLeftOffset| will equal the margin in this case, so it's already been taken
- // into account. Only apply this code if prev is the parent, since otherwise the left margin
- // will get applied twice.
- LayoutSize offset = isHorizontalWritingMode()
- ? LayoutSize(logicalLeftOffset - (prev != parent() ? prev->marginLeft() : LayoutUnit()), logicalTopOffset)
- : LayoutSize(logicalTopOffset, logicalLeftOffset - (prev != parent() ? prev->marginTop() : LayoutUnit()));
-
- m_floatingObjects->add(r->copyToNewContainer(offset));
- }
- }
- }
-}
-
bool RenderBlock::avoidsFloats() const
{
// Floats can't intrude into our box if we have a non-auto column count or width.
return RenderBox::avoidsFloats() || !style()->hasAutoColumnCount() || !style()->hasAutoColumnWidth();
}
-bool RenderBlock::containsFloat(RenderBox* renderer) const
-{
- return m_floatingObjects && m_floatingObjects->set().contains<RenderBox*, FloatingObjectHashTranslator>(renderer);
-}
-
void RenderBlock::markShapeInsideDescendantsForLayout()
{
if (!everHadLayout())
@@ -3816,130 +3058,12 @@ void RenderBlock::markShapeInsideDescendantsForLayout()
}
}
-void RenderBlock::markAllDescendantsWithFloatsForLayout(RenderBox* floatToRemove, bool inLayout)
-{
- if (!everHadLayout() && !containsFloats())
- return;
-
- MarkingBehavior markParents = inLayout ? MarkOnlyThis : MarkContainingBlockChain;
- setChildNeedsLayout(markParents);
-
- if (floatToRemove)
- removeFloatingObject(floatToRemove);
-
- // Iterate over our children and mark them as needed.
- if (!childrenInline()) {
- for (RenderObject* child = firstChild(); child; child = child->nextSibling()) {
- if ((!floatToRemove && child->isFloatingOrOutOfFlowPositioned()) || !child->isRenderBlock())
- continue;
- RenderBlock* childBlock = toRenderBlock(child);
- if ((floatToRemove ? childBlock->containsFloat(floatToRemove) : childBlock->containsFloats()) || childBlock->shrinkToAvoidFloats())
- childBlock->markAllDescendantsWithFloatsForLayout(floatToRemove, inLayout);
- }
- }
-}
-
-void RenderBlock::markSiblingsWithFloatsForLayout(RenderBox* floatToRemove)
-{
- if (!m_floatingObjects)
- return;
-
- const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
- FloatingObjectSetIterator end = floatingObjectSet.end();
-
- for (RenderObject* next = nextSibling(); next; next = next->nextSibling()) {
- if (!next->isRenderBlock() || next->isFloatingOrOutOfFlowPositioned() || toRenderBlock(next)->avoidsFloats())
- continue;
-
- RenderBlock* nextBlock = toRenderBlock(next);
- for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
- RenderBox* floatingBox = (*it)->renderer();
- if (floatToRemove && floatingBox != floatToRemove)
- continue;
- if (nextBlock->containsFloat(floatingBox))
- nextBlock->markAllDescendantsWithFloatsForLayout(floatingBox);
- }
- }
-}
-
-LayoutUnit RenderBlock::getClearDelta(RenderBox* child, LayoutUnit logicalTop)
-{
- // There is no need to compute clearance if we have no floats.
- if (!containsFloats())
- return 0;
-
- // At least one float is present. We need to perform the clearance computation.
- bool clearSet = child->style()->clear() != CNONE;
- LayoutUnit logicalBottom = 0;
- switch (child->style()->clear()) {
- case CNONE:
- break;
- case CLEFT:
- logicalBottom = lowestFloatLogicalBottom(FloatingObject::FloatLeft);
- break;
- case CRIGHT:
- logicalBottom = lowestFloatLogicalBottom(FloatingObject::FloatRight);
- break;
- case CBOTH:
- logicalBottom = lowestFloatLogicalBottom();
- break;
- }
-
- // We also clear floats if we are too big to sit on the same line as a float (and wish to avoid floats by default).
- LayoutUnit result = clearSet ? max<LayoutUnit>(0, logicalBottom - logicalTop) : LayoutUnit();
- if (!result && child->avoidsFloats()) {
- LayoutUnit newLogicalTop = logicalTop;
- while (true) {
- LayoutUnit availableLogicalWidthAtNewLogicalTopOffset = availableLogicalWidthForLine(newLogicalTop, false, logicalHeightForChild(child));
- if (availableLogicalWidthAtNewLogicalTopOffset == availableLogicalWidthForContent(newLogicalTop))
- return newLogicalTop - logicalTop;
-
- RenderRegion* region = regionAtBlockOffset(logicalTopForChild(child));
- LayoutRect borderBox = child->borderBoxRectInRegion(region, DoNotCacheRenderBoxRegionInfo);
- LayoutUnit childLogicalWidthAtOldLogicalTopOffset = isHorizontalWritingMode() ? borderBox.width() : borderBox.height();
-
- // FIXME: None of this is right for perpendicular writing-mode children.
- LayoutUnit childOldLogicalWidth = child->logicalWidth();
- LayoutUnit childOldMarginLeft = child->marginLeft();
- LayoutUnit childOldMarginRight = child->marginRight();
- LayoutUnit childOldLogicalTop = child->logicalTop();
-
- child->setLogicalTop(newLogicalTop);
- child->updateLogicalWidth();
- region = regionAtBlockOffset(logicalTopForChild(child));
- borderBox = child->borderBoxRectInRegion(region, DoNotCacheRenderBoxRegionInfo);
- LayoutUnit childLogicalWidthAtNewLogicalTopOffset = isHorizontalWritingMode() ? borderBox.width() : borderBox.height();
-
- child->setLogicalTop(childOldLogicalTop);
- child->setLogicalWidth(childOldLogicalWidth);
- child->setMarginLeft(childOldMarginLeft);
- child->setMarginRight(childOldMarginRight);
-
- if (childLogicalWidthAtNewLogicalTopOffset <= availableLogicalWidthAtNewLogicalTopOffset) {
- // Even though we may not be moving, if the logical width did shrink because of the presence of new floats, then
- // we need to force a relayout as though we shifted. This happens because of the dynamic addition of overhanging floats
- // from previous siblings when negative margins exist on a child (see the addOverhangingFloats call at the end of collapseMargins).
- if (childLogicalWidthAtOldLogicalTopOffset != childLogicalWidthAtNewLogicalTopOffset)
- child->setChildNeedsLayout(MarkOnlyThis);
- return newLogicalTop - logicalTop;
- }
-
- newLogicalTop = nextFloatLogicalBottomBelow(newLogicalTop);
- ASSERT(newLogicalTop >= logicalTop);
- if (newLogicalTop < logicalTop)
- break;
- }
- ASSERT_NOT_REACHED();
- }
- return result;
-}
-
bool RenderBlock::isPointInOverflowControl(HitTestResult& result, const LayoutPoint& locationInContainer, const LayoutPoint& accumulatedOffset)
{
if (!scrollsOverflow())
return false;
- return layer()->hitTestOverflowControls(result, roundedIntPoint(locationInContainer - toLayoutSize(accumulatedOffset)));
+ return layer()->scrollableArea()->hitTestOverflowControls(result, roundedIntPoint(locationInContainer - toLayoutSize(accumulatedOffset)));
}
Node* RenderBlock::nodeForHitTest() const
@@ -4017,35 +3141,6 @@ bool RenderBlock::nodeAtPoint(const HitTestRequest& request, HitTestResult& resu
return false;
}
-bool RenderBlock::hitTestFloats(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset)
-{
- if (!m_floatingObjects)
- return false;
-
- LayoutPoint adjustedLocation = accumulatedOffset;
- if (isRenderView()) {
- adjustedLocation += toLayoutSize(toRenderView(this)->frameView()->scrollPosition());
- }
-
- const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
- FloatingObjectSetIterator begin = floatingObjectSet.begin();
- for (FloatingObjectSetIterator it = floatingObjectSet.end(); it != begin;) {
- --it;
- FloatingObject* floatingObject = *it;
- if (floatingObject->shouldPaint() && !floatingObject->renderer()->hasSelfPaintingLayer()) {
- LayoutUnit xOffset = xPositionForFloatIncludingMargin(floatingObject) - floatingObject->renderer()->x();
- LayoutUnit yOffset = yPositionForFloatIncludingMargin(floatingObject) - floatingObject->renderer()->y();
- LayoutPoint childPoint = flipFloatForWritingModeForChild(floatingObject, adjustedLocation + LayoutSize(xOffset, yOffset));
- if (floatingObject->renderer()->hitTest(request, result, locationInContainer, childPoint)) {
- updateHitTestResult(result, locationInContainer.point() - toLayoutSize(childPoint));
- return true;
- }
- }
- }
-
- return false;
-}
-
class ColumnRectIterator {
WTF_MAKE_NONCOPYABLE(ColumnRectIterator);
public:
@@ -4504,13 +3599,6 @@ LayoutUnit RenderBlock::desiredColumnWidth() const
return gColumnInfoMap->get(this)->desiredColumnWidth();
}
-unsigned RenderBlock::desiredColumnCount() const
-{
- if (!hasColumns())
- return 1;
- return gColumnInfoMap->get(this)->desiredColumnCount();
-}
-
ColumnInfo* RenderBlock::columnInfo() const
{
if (!hasColumns())
@@ -4552,56 +3640,15 @@ LayoutRect RenderBlock::columnRectAt(ColumnInfo* colInfo, unsigned index) const
return LayoutRect(colLogicalTop, colLogicalLeft, colLogicalHeight, colLogicalWidth);
}
-bool RenderBlock::relayoutForPagination(bool hasSpecifiedPageLogicalHeight, LayoutUnit pageLogicalHeight, LayoutStateMaintainer& statePusher)
+bool RenderBlock::relayoutToAvoidWidows(LayoutStateMaintainer& statePusher)
{
- if (!hasColumns())
+ if (!shouldBreakAtLineToAvoidWidow())
return false;
- OwnPtr<RenderOverflow> savedOverflow = m_overflow.release();
- if (childrenInline())
- addOverflowFromInlineChildren();
- else
- addOverflowFromBlockChildren();
- LayoutUnit layoutOverflowLogicalBottom = (isHorizontalWritingMode() ? layoutOverflowRect().maxY() : layoutOverflowRect().maxX()) - borderBefore() - paddingBefore();
-
- // FIXME: We don't balance properly at all in the presence of forced page breaks. We need to understand what
- // the distance between forced page breaks is so that we can avoid making the minimum column height too tall.
- ColumnInfo* colInfo = columnInfo();
- if (!hasSpecifiedPageLogicalHeight) {
- LayoutUnit columnHeight = pageLogicalHeight;
- int minColumnCount = colInfo->forcedBreaks() + 1;
- int desiredColumnCount = colInfo->desiredColumnCount();
- if (minColumnCount >= desiredColumnCount) {
- // The forced page breaks are in control of the balancing. Just set the column height to the
- // maximum page break distance.
- if (!pageLogicalHeight) {
- LayoutUnit distanceBetweenBreaks = max<LayoutUnit>(colInfo->maximumDistanceBetweenForcedBreaks(),
- view()->layoutState()->pageLogicalOffset(this, borderBefore() + paddingBefore() + layoutOverflowLogicalBottom) - colInfo->forcedBreakOffset());
- columnHeight = max(colInfo->minimumColumnHeight(), distanceBetweenBreaks);
- }
- } else if (layoutOverflowLogicalBottom > boundedMultiply(pageLogicalHeight, desiredColumnCount)) {
- // Now that we know the intrinsic height of the columns, we have to rebalance them.
- columnHeight = max<LayoutUnit>(colInfo->minimumColumnHeight(), ceilf((float)layoutOverflowLogicalBottom / desiredColumnCount));
- }
-
- if (columnHeight && columnHeight != pageLogicalHeight) {
- statePusher.pop();
- setEverHadLayout(true);
- layoutBlock(false, columnHeight);
- return true;
- }
- }
-
- if (pageLogicalHeight)
- colInfo->setColumnCountAndHeight(ceilf((float)layoutOverflowLogicalBottom / pageLogicalHeight), pageLogicalHeight);
-
- if (columnCount(colInfo)) {
- setLogicalHeight(borderBefore() + paddingBefore() + colInfo->columnHeight() + borderAfter() + paddingAfter() + scrollbarLogicalHeight());
- m_overflow.clear();
- } else
- m_overflow = savedOverflow.release();
-
- return false;
+ statePusher.pop();
+ setEverHadLayout(true);
+ layoutBlock(false);
+ return true;
}
void RenderBlock::adjustPointToColumnContents(LayoutPoint& point) const
@@ -5006,7 +4053,7 @@ static inline void stripTrailingSpace(float& inlineMax, float& inlineMin,
RenderText* t = toRenderText(trailingSpaceChild);
const UChar space = ' ';
const Font& font = t->style()->font(); // FIXME: This ignores first-line.
- float spaceWidth = font.width(RenderBlock::constructTextRun(t, font, &space, 1, t->style()));
+ float spaceWidth = font.width(RenderBlockFlow::constructTextRun(t, font, &space, 1, t->style()));
inlineMax -= spaceWidth + font.wordSpacing();
if (inlineMin > inlineMax)
inlineMin = inlineMax;
@@ -5137,8 +4184,18 @@ void RenderBlock::computeInlinePreferredLogicalWidths(LayoutUnit& minLogicalWidt
// Case (2). Inline replaced elements and floats.
// Go ahead and terminate the current line as far as
// minwidth is concerned.
- childMin += child->minPreferredLogicalWidth().ceilToFloat();
- childMax += child->maxPreferredLogicalWidth().ceilToFloat();
+ LayoutUnit childMinPreferredLogicalWidth, childMaxPreferredLogicalWidth;
+ if (child->isBox() && child->isHorizontalWritingMode() != isHorizontalWritingMode()) {
+ RenderBox* childBox = toRenderBox(child);
+ LogicalExtentComputedValues computedValues;
+ childBox->computeLogicalHeight(childBox->borderAndPaddingLogicalHeight(), 0, computedValues);
+ childMinPreferredLogicalWidth = childMaxPreferredLogicalWidth = computedValues.m_extent;
+ } else {
+ childMinPreferredLogicalWidth = child->minPreferredLogicalWidth();
+ childMaxPreferredLogicalWidth = child->maxPreferredLogicalWidth();
+ }
+ childMin += childMinPreferredLogicalWidth.ceilToFloat();
+ childMax += childMaxPreferredLogicalWidth.ceilToFloat();
bool clearPreviousFloat;
if (child->isFloating()) {
@@ -5480,8 +4537,8 @@ int RenderBlock::baselinePosition(FontBaseline baselineType, bool firstLine, Lin
// (the content inside them moves). This matches WinIE as well, which just bottom-aligns them.
// We also give up on finding a baseline if we have a vertical scrollbar, or if we are scrolled
// vertically (e.g., an overflow:hidden block that has had scrollTop moved).
- bool ignoreBaseline = (layer() && (isMarquee() || (direction == HorizontalLine ? (layer()->verticalScrollbar() || layer()->scrollYOffset())
- : (layer()->horizontalScrollbar() || layer()->scrollXOffset())))) || (isWritingModeRoot() && !isRubyRun());
+ bool ignoreBaseline = (layer() && layer()->scrollableArea() && (isMarquee() || (direction == HorizontalLine ? (layer()->scrollableArea()->verticalScrollbar() || layer()->scrollableArea()->scrollYOffset())
+ : (layer()->scrollableArea()->horizontalScrollbar() || layer()->scrollableArea()->scrollXOffset())))) || (isWritingModeRoot() && !isRubyRun());
int baselinePos = ignoreBaseline ? -1 : inlineBlockBaseline(direction);
@@ -5509,6 +4566,17 @@ int RenderBlock::baselinePosition(FontBaseline baselineType, bool firstLine, Lin
return fontMetrics.ascent(baselineType) + (lineHeight(firstLine, direction, linePositionMode) - fontMetrics.height()) / 2;
}
+LayoutUnit RenderBlock::minLineHeightForReplacedRenderer(bool isFirstLine, LayoutUnit replacedHeight) const
+{
+ if (!document().inNoQuirksMode() && replacedHeight)
+ return replacedHeight;
+
+ if (!(style(isFirstLine)->lineBoxContain() & LineBoxContainBlock))
+ return 0;
+
+ return std::max<LayoutUnit>(replacedHeight, lineHeight(isFirstLine, isHorizontalWritingMode() ? HorizontalLine : VerticalLine, PositionOfInteriorLineBoxes));
+}
+
int RenderBlock::firstLineBoxBaseline() const
{
if (isWritingModeRoot() && !isRubyRun())
@@ -5671,11 +4739,11 @@ void RenderBlock::updateFirstLetterStyle(RenderObject* firstLetterBlock, RenderO
if (RenderStyle::compare(firstLetter->style(), pseudoStyle) == Reattach) {
// The first-letter renderer needs to be replaced. Create a new renderer of the right type.
- RenderObject* newFirstLetter;
+ RenderBoxModelObject* newFirstLetter;
if (pseudoStyle->display() == INLINE)
newFirstLetter = RenderInline::createAnonymous(&document());
else
- newFirstLetter = RenderBlock::createAnonymous(&document());
+ newFirstLetter = RenderBlockFlow::createAnonymous(&document());
newFirstLetter->setStyle(pseudoStyle);
// Move the first letter into the new renderer.
@@ -5687,16 +4755,12 @@ void RenderBlock::updateFirstLetterStyle(RenderObject* firstLetterBlock, RenderO
newFirstLetter->addChild(child, 0);
}
- RenderTextFragment* remainingText = 0;
RenderObject* nextSibling = firstLetter->nextSibling();
- RenderObject* remainingTextObject = toRenderBoxModelObject(firstLetter)->firstLetterRemainingText();
- if (remainingTextObject && remainingTextObject->isText() && toRenderText(remainingTextObject)->isTextFragment())
- remainingText = toRenderTextFragment(remainingTextObject);
- if (remainingText) {
+ if (RenderTextFragment* remainingText = toRenderBoxModelObject(firstLetter)->firstLetterRemainingText()) {
ASSERT(remainingText->isAnonymous() || remainingText->node()->renderer() == remainingText);
// Replace the old renderer with the new one.
remainingText->setFirstLetter(newFirstLetter);
- toRenderBoxModelObject(newFirstLetter)->setFirstLetterRemainingText(remainingText);
+ newFirstLetter->setFirstLetterRemainingText(remainingText);
}
// To prevent removal of single anonymous block in RenderBlock::removeChild and causing
// |nextSibling| to go stale, we remove the old first letter using removeChildNode first.
@@ -5716,10 +4780,15 @@ void RenderBlock::updateFirstLetterStyle(RenderObject* firstLetterBlock, RenderO
static inline unsigned firstLetterLength(const String& text)
{
unsigned length = 0;
+ bool punctuationOpen = false;
// Account for leading spaces and punctuation.
- while (length < text.length() && shouldSkipForFirstLetter((text)[length]))
+ while (length < text.length() && shouldSkipForFirstLetter((text)[length])) {
+ if (isPunctuationForFirstLetter((text)[length]))
+ punctuationOpen = true;
+
length++;
+ }
// Bail if we didn't find a letter
if (text.length() && length == text.length())
@@ -5728,6 +4797,9 @@ static inline unsigned firstLetterLength(const String& text)
// Account for first letter.
length++;
+ if (!punctuationOpen)
+ return length;
+
// Keep looking for whitespace and allowed punctuation, but avoid
// accumulating just whitespace into the :first-letter.
for (unsigned scanLength = length; scanLength < text.length(); ++scanLength) {
@@ -5753,7 +4825,7 @@ void RenderBlock::createFirstLetterRenderer(RenderObject* firstLetterBlock, Rend
if (pseudoStyle->display() == INLINE)
firstLetter = RenderInline::createAnonymous(&document());
else
- firstLetter = RenderBlock::createAnonymous(&document());
+ firstLetter = RenderBlockFlow::createAnonymous(&document());
firstLetter->setStyle(pseudoStyle);
firstLetterContainer->addChild(firstLetter, currentChild);
@@ -5854,7 +4926,7 @@ void RenderBlock::updateFirstLetter()
// (crawling into blocks).
static bool shouldCheckLines(RenderObject* obj)
{
- return !obj->isFloatingOrOutOfFlowPositioned() && !obj->isRunIn()
+ return !obj->isFloatingOrOutOfFlowPositioned()
&& obj->isRenderBlock() && obj->style()->height().isAuto()
&& (!obj->isDeprecatedFlexibleBox() || obj->style()->boxOrient() == VERTICAL);
}
@@ -5875,7 +4947,7 @@ static int getHeightForLineCount(RenderBlock* block, int l, bool includeBottom,
int result = getHeightForLineCount(toRenderBlock(obj), l, false, count);
if (result != -1)
return result + obj->y() + (includeBottom ? (block->borderBottom() + block->paddingBottom()) : LayoutUnit());
- } else if (!obj->isFloatingOrOutOfFlowPositioned() && !obj->isRunIn())
+ } else if (!obj->isFloatingOrOutOfFlowPositioned())
normalFlowChildWithoutLines = obj;
}
if (normalFlowChildWithoutLines && l == 0)
@@ -5969,21 +5041,6 @@ void RenderBlock::adjustForBorderFit(LayoutUnit x, LayoutUnit& left, LayoutUnit&
}
}
}
-
- if (m_floatingObjects) {
- const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
- FloatingObjectSetIterator end = floatingObjectSet.end();
- for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
- FloatingObject* r = *it;
- // Only examine the object if our m_shouldPaint flag is set.
- if (r->shouldPaint()) {
- LayoutUnit floatLeft = xPositionForFloatIncludingMargin(r) - r->renderer()->x();
- LayoutUnit floatRight = floatLeft + r->renderer()->width();
- left = min(left, floatLeft);
- right = max(right, floatRight);
- }
- }
- }
}
}
@@ -6049,21 +5106,42 @@ void RenderBlock::setPageLogicalOffset(LayoutUnit logicalOffset)
m_rareData->m_pageLogicalOffset = logicalOffset;
}
-void RenderBlock::setBreakAtLineToAvoidWidow(RootInlineBox* lineToBreak)
+void RenderBlock::setBreakAtLineToAvoidWidow(int lineToBreak)
{
- ASSERT(lineToBreak);
+ ASSERT(lineToBreak >= 0);
if (!m_rareData)
m_rareData = adoptPtr(new RenderBlockRareData());
- m_rareData->m_shouldBreakAtLineToAvoidWidow = true;
+
+ ASSERT(!m_rareData->m_didBreakAtLineToAvoidWidow);
m_rareData->m_lineBreakToAvoidWidow = lineToBreak;
}
+void RenderBlock::setDidBreakAtLineToAvoidWidow()
+{
+ ASSERT(!shouldBreakAtLineToAvoidWidow());
+
+ // This function should be called only after a break was applied to avoid widows
+ // so assert |m_rareData| exists.
+ ASSERT(m_rareData);
+
+ m_rareData->m_didBreakAtLineToAvoidWidow = true;
+}
+
+void RenderBlock::clearDidBreakAtLineToAvoidWidow()
+{
+ if (!m_rareData)
+ return;
+
+ m_rareData->m_didBreakAtLineToAvoidWidow = false;
+}
+
void RenderBlock::clearShouldBreakAtLineToAvoidWidow() const
{
+ ASSERT(shouldBreakAtLineToAvoidWidow());
if (!m_rareData)
return;
- m_rareData->m_shouldBreakAtLineToAvoidWidow = false;
- m_rareData->m_lineBreakToAvoidWidow = 0;
+
+ m_rareData->m_lineBreakToAvoidWidow = -1;
}
void RenderBlock::absoluteRects(Vector<IntRect>& rects, const LayoutPoint& accumulatedOffset) const
@@ -6438,12 +5516,17 @@ void RenderBlock::adjustLinePositionForPagination(RootInlineBox* lineBox, Layout
// still going to add a strut, so that the visible overflow fits on a single page.
if (!pageLogicalHeight || (hasUniformPageLogicalHeight && logicalVisualOverflow.height() > pageLogicalHeight)
|| !hasNextPage(logicalOffset))
+ // FIXME: In case the line aligns with the top of the page (or it's slightly shifted downwards) it will not be marked as the first line in the page.
+ // From here, the fix is not straightforward because it's not easy to always determine when the current line is the first in the page.
return;
LayoutUnit remainingLogicalHeight = pageRemainingLogicalHeightForOffset(logicalOffset, ExcludePageBoundary);
- if (remainingLogicalHeight < lineHeight || (shouldBreakAtLineToAvoidWidow() && lineBreakToAvoidWidow() == lineBox)) {
- if (shouldBreakAtLineToAvoidWidow() && lineBreakToAvoidWidow() == lineBox)
+ int lineIndex = lineCount(lineBox);
+ if (remainingLogicalHeight < lineHeight || (shouldBreakAtLineToAvoidWidow() && lineBreakToAvoidWidow() == lineIndex)) {
+ if (shouldBreakAtLineToAvoidWidow() && lineBreakToAvoidWidow() == lineIndex) {
clearShouldBreakAtLineToAvoidWidow();
+ setDidBreakAtLineToAvoidWidow();
+ }
// If we have a non-uniform page height, then we have to shift further possibly.
if (!hasUniformPageLogicalHeight && !pushToNextPageWithMinimumLogicalHeight(remainingLogicalHeight, logicalOffset, lineHeight))
return;
@@ -6454,7 +5537,7 @@ void RenderBlock::adjustLinePositionForPagination(RootInlineBox* lineBox, Layout
LayoutUnit totalLogicalHeight = lineHeight + max<LayoutUnit>(0, logicalOffset);
LayoutUnit pageLogicalHeightAtNewOffset = hasUniformPageLogicalHeight ? pageLogicalHeight : pageLogicalHeightForOffset(logicalOffset + remainingLogicalHeight);
setPageBreak(logicalOffset, lineHeight - remainingLogicalHeight);
- if (((lineBox == firstRootBox() && totalLogicalHeight < pageLogicalHeightAtNewOffset) || (!style()->hasAutoOrphans() && style()->orphans() >= lineCount(lineBox)))
+ if (((lineBox == firstRootBox() && totalLogicalHeight < pageLogicalHeightAtNewOffset) || (!style()->hasAutoOrphans() && style()->orphans() >= lineIndex))
&& !isOutOfFlowPositioned() && !isTableCell())
setPaginationStrut(remainingLogicalHeight + max<LayoutUnit>(0, logicalOffset));
else {
@@ -6462,7 +5545,28 @@ void RenderBlock::adjustLinePositionForPagination(RootInlineBox* lineBox, Layout
lineBox->setPaginationStrut(remainingLogicalHeight);
lineBox->setIsFirstAfterPageBreak(true);
}
- } else if (remainingLogicalHeight == pageLogicalHeight && lineBox != firstRootBox())
+ } else if (remainingLogicalHeight == pageLogicalHeight) {
+ // We're at the very top of a page or column.
+ if (lineBox != firstRootBox())
+ lineBox->setIsFirstAfterPageBreak(true);
+ if (lineBox != firstRootBox() || offsetFromLogicalTopOfFirstPage())
+ setPageBreak(logicalOffset, lineHeight);
+ }
+}
+
+void RenderBlock::updateRegionForLine(RootInlineBox* lineBox) const
+{
+ ASSERT(lineBox);
+ lineBox->setContainingRegion(regionAtBlockOffset(lineBox->lineTopWithLeading()));
+
+ RootInlineBox* prevLineBox = lineBox->prevRootBox();
+ if (!prevLineBox)
+ return;
+
+ // This check is more accurate than the one in |adjustLinePositionForPagination| because it takes into
+ // account just the container changes between lines. The before mentioned function doesn't set the flag
+ // correctly if the line is positioned at the top of the last fragment container.
+ if (lineBox->containingRegion() != prevLineBox->containingRegion())
lineBox->setIsFirstAfterPageBreak(true);
}
@@ -6508,23 +5612,6 @@ RenderRegion* RenderBlock::regionAtBlockOffset(LayoutUnit blockOffset) const
return flowThread->regionAtBlockOffset(offsetFromLogicalTopOfFirstPage() + blockOffset, true);
}
-void RenderBlock::updateStaticInlinePositionForChild(RenderBox* child, LayoutUnit logicalTop)
-{
- if (child->style()->isOriginalDisplayInlineType())
- setStaticInlinePositionForChild(child, logicalTop, startAlignedOffsetForLine(logicalTop, false));
- else
- setStaticInlinePositionForChild(child, logicalTop, startOffsetForContent(logicalTop));
-}
-
-void RenderBlock::setStaticInlinePositionForChild(RenderBox* child, LayoutUnit blockOffset, LayoutUnit inlinePosition)
-{
- if (flowThreadContainingBlock()) {
- // Shift the inline position to exclude the region offset.
- inlinePosition += startOffsetForContent() - startOffsetForContent(blockOffset);
- }
- child->layer()->setStaticInlinePosition(inlinePosition);
-}
-
bool RenderBlock::logicalWidthChangedInRegions(RenderFlowThread* flowThread) const
{
if (!flowThread || !flowThread->hasValidRegionInfo())
@@ -6649,86 +5736,9 @@ const char* RenderBlock::renderName() const
return "RenderBlock (relative positioned)";
if (isStickyPositioned())
return "RenderBlock (sticky positioned)";
- if (isRunIn())
- return "RenderBlock (run-in)";
return "RenderBlock";
}
-void RenderBlock::createFloatingObjects()
-{
- m_floatingObjects = adoptPtr(new FloatingObjects(this, isHorizontalWritingMode()));
-}
-
-template <typename CharacterType>
-static inline TextRun constructTextRunInternal(RenderObject* context, const Font& font, const CharacterType* characters, int length, RenderStyle* style, TextRun::ExpansionBehavior expansion)
-{
- ASSERT(style);
-
- TextDirection textDirection = LTR;
- bool directionalOverride = style->rtlOrdering() == VisualOrder;
-
- TextRun run(characters, length, 0, 0, expansion, textDirection, directionalOverride);
- if (textRunNeedsRenderingContext(font))
- run.setRenderingContext(SVGTextRunRenderingContext::create(context));
-
- return run;
-}
-
-template <typename CharacterType>
-static inline TextRun constructTextRunInternal(RenderObject* context, const Font& font, const CharacterType* characters, int length, RenderStyle* style, TextRun::ExpansionBehavior expansion, TextRunFlags flags)
-{
- ASSERT(style);
-
- TextDirection textDirection = LTR;
- bool directionalOverride = style->rtlOrdering() == VisualOrder;
- if (flags != DefaultTextRunFlags) {
- if (flags & RespectDirection)
- textDirection = style->direction();
- if (flags & RespectDirectionOverride)
- directionalOverride |= isOverride(style->unicodeBidi());
- }
- TextRun run(characters, length, 0, 0, expansion, textDirection, directionalOverride);
- if (textRunNeedsRenderingContext(font))
- run.setRenderingContext(SVGTextRunRenderingContext::create(context));
-
- return run;
-}
-
-TextRun RenderBlock::constructTextRun(RenderObject* context, const Font& font, const LChar* characters, int length, RenderStyle* style, TextRun::ExpansionBehavior expansion)
-{
- return constructTextRunInternal(context, font, characters, length, style, expansion);
-}
-
-TextRun RenderBlock::constructTextRun(RenderObject* context, const Font& font, const UChar* characters, int length, RenderStyle* style, TextRun::ExpansionBehavior expansion)
-{
- return constructTextRunInternal(context, font, characters, length, style, expansion);
-}
-
-TextRun RenderBlock::constructTextRun(RenderObject* context, const Font& font, const RenderText* text, RenderStyle* style, TextRun::ExpansionBehavior expansion)
-{
- if (text->is8Bit())
- return constructTextRunInternal(context, font, text->characters8(), text->textLength(), style, expansion);
- return constructTextRunInternal(context, font, text->characters16(), text->textLength(), style, expansion);
-}
-
-TextRun RenderBlock::constructTextRun(RenderObject* context, const Font& font, const RenderText* text, unsigned offset, unsigned length, RenderStyle* style, TextRun::ExpansionBehavior expansion)
-{
- ASSERT(offset + length <= text->textLength());
- if (text->is8Bit())
- return constructTextRunInternal(context, font, text->characters8() + offset, length, style, expansion);
- return constructTextRunInternal(context, font, text->characters16() + offset, length, style, expansion);
-}
-
-TextRun RenderBlock::constructTextRun(RenderObject* context, const Font& font, const String& string, RenderStyle* style, TextRun::ExpansionBehavior expansion, TextRunFlags flags)
-{
- unsigned length = string.length();
- if (!length)
- return constructTextRunInternal(context, font, static_cast<const LChar*>(0), length, style, expansion, flags);
- if (string.is8Bit())
- return constructTextRunInternal(context, font, string.characters8(), length, style, expansion, flags);
- return constructTextRunInternal(context, font, string.characters16(), length, style, expansion, flags);
-}
-
RenderBlock* RenderBlock::createAnonymousWithParentRendererAndDisplay(const RenderObject* parent, EDisplay display)
{
// FIXME: Do we need to convert all our inline displays to block-type in the anonymous logic ?
@@ -6742,7 +5752,7 @@ RenderBlock* RenderBlock::createAnonymousWithParentRendererAndDisplay(const Rend
newBox = RenderFlexibleBox::createAnonymous(&parent->document());
newDisplay = FLEX;
} else {
- newBox = RenderBlock::createAnonymous(&parent->document());
+ newBox = RenderBlockFlow::createAnonymous(&parent->document());
newDisplay = BLOCK;
}
@@ -6751,22 +5761,22 @@ RenderBlock* RenderBlock::createAnonymousWithParentRendererAndDisplay(const Rend
return newBox;
}
-RenderBlock* RenderBlock::createAnonymousColumnsWithParentRenderer(const RenderObject* parent)
+RenderBlockFlow* RenderBlock::createAnonymousColumnsWithParentRenderer(const RenderObject* parent)
{
RefPtr<RenderStyle> newStyle = RenderStyle::createAnonymousStyleWithDisplay(parent->style(), BLOCK);
newStyle->inheritColumnPropertiesFrom(parent->style());
- RenderBlock* newBox = RenderBlock::createAnonymous(&parent->document());
+ RenderBlockFlow* newBox = RenderBlockFlow::createAnonymous(&parent->document());
newBox->setStyle(newStyle.release());
return newBox;
}
-RenderBlock* RenderBlock::createAnonymousColumnSpanWithParentRenderer(const RenderObject* parent)
+RenderBlockFlow* RenderBlock::createAnonymousColumnSpanWithParentRenderer(const RenderObject* parent)
{
RefPtr<RenderStyle> newStyle = RenderStyle::createAnonymousStyleWithDisplay(parent->style(), BLOCK);
newStyle->setColumnSpan(ColumnSpanAll);
- RenderBlock* newBox = RenderBlock::createAnonymous(&parent->document());
+ RenderBlockFlow* newBox = RenderBlockFlow::createAnonymous(&parent->document());
newBox->setStyle(newStyle.release());
return newBox;
}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderBlock.h b/chromium/third_party/WebKit/Source/core/rendering/RenderBlock.h
index 491550034e9..cd090231993 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderBlock.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderBlock.h
@@ -23,8 +23,6 @@
#ifndef RenderBlock_h
#define RenderBlock_h
-#include "core/platform/graphics/TextRun.h"
-#include "core/platform/text/TextBreakIterator.h"
#include "core/rendering/ColumnInfo.h"
#include "core/rendering/FloatingObjects.h"
#include "core/rendering/GapRects.h"
@@ -33,6 +31,8 @@
#include "core/rendering/RootInlineBox.h"
#include "core/rendering/shapes/ShapeInsideInfo.h"
#include "core/rendering/style/ShapeValue.h"
+#include "platform/text/TextBreakIterator.h"
+#include "platform/text/TextRun.h"
#include "wtf/ListHashSet.h"
#include "wtf/OwnPtr.h"
@@ -43,13 +43,11 @@ class BidiContext;
class InlineIterator;
class LayoutStateMaintainer;
class LineLayoutState;
-class LineWidth;
class RenderInline;
class RenderText;
struct BidiRun;
struct PaintInfo;
-class LineBreaker;
class LineInfo;
class RenderRubyRun;
class TextLayout;
@@ -85,8 +83,6 @@ protected:
virtual ~RenderBlock();
public:
- static RenderBlock* createAnonymous(Document*);
-
RenderObject* firstChild() const { ASSERT(children() == virtualChildren()); return children()->firstChild(); }
RenderObject* lastChild() const { ASSERT(children() == virtualChildren()); return children()->lastChild(); }
@@ -99,13 +95,15 @@ public:
virtual LayoutUnit lineHeight(bool firstLine, LineDirectionMode, LinePositionMode = PositionOnContainingLine) const OVERRIDE FINAL;
virtual int baselinePosition(FontBaseline, bool firstLine, LineDirectionMode, LinePositionMode = PositionOnContainingLine) const;
+ LayoutUnit minLineHeightForReplacedRenderer(bool isFirstLine, LayoutUnit replacedHeight) const;
+
RenderLineBoxList* lineBoxes() { return &m_lineBoxes; }
- const RenderLineBoxList* lineBoxes() const { return &m_lineBoxes; }
InlineFlowBox* firstLineBox() const { return m_lineBoxes.firstLineBox(); }
InlineFlowBox* lastLineBox() const { return m_lineBoxes.lastLineBox(); }
- void deleteLineBoxTree();
+ // FIXME-BLOCKFLOW: Remove virtualizaion when all callers have moved to RenderBlockFlow
+ virtual void deleteLineBoxTree();
virtual void addChild(RenderObject* newChild, RenderObject* beforeChild = 0);
virtual void removeChild(RenderObject*);
@@ -116,8 +114,6 @@ public:
static void removePositionedObject(RenderBox*);
void removePositionedObjects(RenderBlock*, ContainingBlockState = SameContainingBlock);
- void removeFloatingObjects();
-
TrackedRendererListHashSet* positionedObjects() const;
bool hasPositionedObjects() const
{
@@ -147,56 +143,52 @@ public:
RootInlineBox* createAndAppendRootInlineBox();
- bool generatesLineBoxesForInlineChild(RenderObject*);
-
void markShapeInsideDescendantsForLayout();
- void markAllDescendantsWithFloatsForLayout(RenderBox* floatToRemove = 0, bool inLayout = true);
- void markSiblingsWithFloatsForLayout(RenderBox* floatToRemove = 0);
void markPositionedObjectsForLayout();
// FIXME: Do we really need this to be virtual? It's just so we can call this on
// RenderBoxes without needed to check whether they're RenderBlocks first.
virtual void markForPaginationRelayoutIfNeeded(SubtreeLayoutScope&) OVERRIDE FINAL;
- bool containsFloats() const { return m_floatingObjects && !m_floatingObjects->set().isEmpty(); }
- bool containsFloat(RenderBox*) const;
+ // FIXME-BLOCKFLOW: Remove virtualizaion when all of the line layout code has been moved out of RenderBlock
+ virtual bool containsFloats() const { return false; }
// Versions that can compute line offsets with the region and page offset passed in. Used for speed to avoid having to
// compute the region all over again when you already know it.
- LayoutUnit availableLogicalWidthForLine(LayoutUnit position, bool shouldIndentText, RenderRegion* region, LayoutUnit logicalHeight = 0) const
+ LayoutUnit availableLogicalWidthForLineInRegion(LayoutUnit position, bool shouldIndentText, RenderRegion* region, LayoutUnit logicalHeight = 0) const
{
- return max<LayoutUnit>(0, logicalRightOffsetForLine(position, shouldIndentText, region, logicalHeight)
- - logicalLeftOffsetForLine(position, shouldIndentText, region, logicalHeight));
+ return max<LayoutUnit>(0, logicalRightOffsetForLineInRegion(position, shouldIndentText, region, logicalHeight)
+ - logicalLeftOffsetForLineInRegion(position, shouldIndentText, region, logicalHeight));
}
- LayoutUnit logicalRightOffsetForLine(LayoutUnit position, bool shouldIndentText, RenderRegion* region, LayoutUnit logicalHeight = 0) const
+ LayoutUnit logicalRightOffsetForLineInRegion(LayoutUnit position, bool shouldIndentText, RenderRegion* region, LayoutUnit logicalHeight = 0) const
{
- return logicalRightOffsetForLine(position, logicalRightOffsetForContent(region), shouldIndentText, 0, logicalHeight);
+ return logicalRightOffsetForLine(position, logicalRightOffsetForContent(region), shouldIndentText, logicalHeight);
}
- LayoutUnit logicalLeftOffsetForLine(LayoutUnit position, bool shouldIndentText, RenderRegion* region, LayoutUnit logicalHeight = 0) const
+ LayoutUnit logicalLeftOffsetForLineInRegion(LayoutUnit position, bool shouldIndentText, RenderRegion* region, LayoutUnit logicalHeight = 0) const
{
- return logicalLeftOffsetForLine(position, logicalLeftOffsetForContent(region), shouldIndentText, 0, logicalHeight);
+ return logicalLeftOffsetForLine(position, logicalLeftOffsetForContent(region), shouldIndentText, logicalHeight);
}
- LayoutUnit startOffsetForLine(LayoutUnit position, bool shouldIndentText, RenderRegion* region, LayoutUnit logicalHeight = 0) const
+ LayoutUnit startOffsetForLineInRegion(LayoutUnit position, bool shouldIndentText, RenderRegion* region, LayoutUnit logicalHeight = 0) const
{
- return style()->isLeftToRightDirection() ? logicalLeftOffsetForLine(position, shouldIndentText, region, logicalHeight)
- : logicalWidth() - logicalRightOffsetForLine(position, shouldIndentText, region, logicalHeight);
+ return style()->isLeftToRightDirection() ? logicalLeftOffsetForLineInRegion(position, shouldIndentText, region, logicalHeight)
+ : logicalWidth() - logicalRightOffsetForLineInRegion(position, shouldIndentText, region, logicalHeight);
}
- LayoutUnit endOffsetForLine(LayoutUnit position, bool shouldIndentText, RenderRegion* region, LayoutUnit logicalHeight = 0) const
+ LayoutUnit endOffsetForLineInRegion(LayoutUnit position, bool shouldIndentText, RenderRegion* region, LayoutUnit logicalHeight = 0) const
{
- return !style()->isLeftToRightDirection() ? logicalLeftOffsetForLine(position, shouldIndentText, region, logicalHeight)
- : logicalWidth() - logicalRightOffsetForLine(position, shouldIndentText, region, logicalHeight);
+ return !style()->isLeftToRightDirection() ? logicalLeftOffsetForLineInRegion(position, shouldIndentText, region, logicalHeight)
+ : logicalWidth() - logicalRightOffsetForLineInRegion(position, shouldIndentText, region, logicalHeight);
}
LayoutUnit availableLogicalWidthForLine(LayoutUnit position, bool shouldIndentText, LayoutUnit logicalHeight = 0) const
{
- return availableLogicalWidthForLine(position, shouldIndentText, regionAtBlockOffset(position), logicalHeight);
+ return availableLogicalWidthForLineInRegion(position, shouldIndentText, regionAtBlockOffset(position), logicalHeight);
}
LayoutUnit logicalRightOffsetForLine(LayoutUnit position, bool shouldIndentText, LayoutUnit logicalHeight = 0) const
{
- return logicalRightOffsetForLine(position, logicalRightOffsetForContent(position), shouldIndentText, 0, logicalHeight);
+ return logicalRightOffsetForLine(position, logicalRightOffsetForContent(position), shouldIndentText, logicalHeight);
}
LayoutUnit logicalLeftOffsetForLine(LayoutUnit position, bool shouldIndentText, LayoutUnit logicalHeight = 0) const
{
- return logicalLeftOffsetForLine(position, logicalLeftOffsetForContent(position), shouldIndentText, 0, logicalHeight);
+ return logicalLeftOffsetForLine(position, logicalLeftOffsetForContent(position), shouldIndentText, logicalHeight);
}
LayoutUnit pixelSnappedLogicalLeftOffsetForLine(LayoutUnit position, bool shouldIndentText, LayoutUnit logicalHeight = 0) const
{
@@ -221,7 +213,6 @@ public:
: logicalWidth() - logicalRightOffsetForLine(position, shouldIndentText, logicalHeight);
}
- LayoutUnit startAlignedOffsetForLine(LayoutUnit position, bool shouldIndentText);
LayoutUnit textIndentOffset() const;
virtual PositionWithAffinity positionForPoint(const LayoutPoint&) OVERRIDE;
@@ -232,6 +223,9 @@ public:
LayoutPoint flipForWritingModeIncludingColumns(const LayoutPoint&) const;
void adjustStartEdgeForWritingModeIncludingColumns(LayoutRect&) const;
+ LayoutUnit blockDirectionOffset(const LayoutSize& offsetFromBlock) const;
+ LayoutUnit inlineDirectionOffset(const LayoutSize& offsetFromBlock) const;
+
RootInlineBox* firstRootBox() const { return static_cast<RootInlineBox*>(firstLineBox()); }
RootInlineBox* lastRootBox() const { return static_cast<RootInlineBox*>(lastLineBox()); }
@@ -267,39 +261,14 @@ public:
using RenderBoxModelObject::setContinuation;
static RenderBlock* createAnonymousWithParentRendererAndDisplay(const RenderObject*, EDisplay = BLOCK);
- static RenderBlock* createAnonymousColumnsWithParentRenderer(const RenderObject*);
- static RenderBlock* createAnonymousColumnSpanWithParentRenderer(const RenderObject*);
+ static RenderBlockFlow* createAnonymousColumnsWithParentRenderer(const RenderObject*);
+ static RenderBlockFlow* createAnonymousColumnSpanWithParentRenderer(const RenderObject*);
RenderBlock* createAnonymousBlock(EDisplay display = BLOCK) const { return createAnonymousWithParentRendererAndDisplay(this, display); }
- RenderBlock* createAnonymousColumnsBlock() const { return createAnonymousColumnsWithParentRenderer(this); }
- RenderBlock* createAnonymousColumnSpanBlock() const { return createAnonymousColumnSpanWithParentRenderer(this); }
+ RenderBlockFlow* createAnonymousColumnsBlock() const { return createAnonymousColumnsWithParentRenderer(this); }
+ RenderBlockFlow* createAnonymousColumnSpanBlock() const { return createAnonymousColumnSpanWithParentRenderer(this); }
virtual RenderBox* createAnonymousBoxWithSameTypeAs(const RenderObject* parent) const OVERRIDE;
- static bool shouldSkipCreatingRunsForObject(RenderObject* obj)
- {
- return obj->isFloating() || (obj->isOutOfFlowPositioned() && !obj->style()->isOriginalDisplayInlineType() && !obj->container()->isRenderInline());
- }
-
- static void appendRunsForObject(BidiRunList<BidiRun>&, int start, int end, RenderObject*, InlineBidiResolver&);
-
- static TextRun constructTextRun(RenderObject* context, const Font& font, const String& string, RenderStyle* style,
- TextRun::ExpansionBehavior = TextRun::AllowTrailingExpansion | TextRun::ForbidLeadingExpansion, TextRunFlags = DefaultTextRunFlags);
-
- static TextRun constructTextRun(RenderObject* context, const Font& font, const RenderText* text, RenderStyle* style,
- TextRun::ExpansionBehavior = TextRun::AllowTrailingExpansion | TextRun::ForbidLeadingExpansion);
-
- static TextRun constructTextRun(RenderObject* context, const Font& font, const RenderText* text, unsigned offset, unsigned length, RenderStyle* style,
- TextRun::ExpansionBehavior = TextRun::AllowTrailingExpansion | TextRun::ForbidLeadingExpansion);
-
- static TextRun constructTextRun(RenderObject* context, const Font& font, const RenderText* text, unsigned offset, RenderStyle* style,
- TextRun::ExpansionBehavior = TextRun::AllowTrailingExpansion | TextRun::ForbidLeadingExpansion);
-
- static TextRun constructTextRun(RenderObject* context, const Font& font, const LChar* characters, int length, RenderStyle* style,
- TextRun::ExpansionBehavior = TextRun::AllowTrailingExpansion | TextRun::ForbidLeadingExpansion);
-
- static TextRun constructTextRun(RenderObject* context, const Font& font, const UChar* characters, int length, RenderStyle* style,
- TextRun::ExpansionBehavior = TextRun::AllowTrailingExpansion | TextRun::ForbidLeadingExpansion);
-
ColumnInfo* columnInfo() const;
int columnGap() const;
@@ -312,32 +281,24 @@ public:
LayoutUnit paginationStrut() const { return m_rareData ? m_rareData->m_paginationStrut : LayoutUnit(); }
void setPaginationStrut(LayoutUnit);
- bool shouldBreakAtLineToAvoidWidow() const { return m_rareData && m_rareData->m_shouldBreakAtLineToAvoidWidow; }
+ bool shouldBreakAtLineToAvoidWidow() const { return m_rareData && m_rareData->m_lineBreakToAvoidWidow >= 0; }
void clearShouldBreakAtLineToAvoidWidow() const;
- RootInlineBox* lineBreakToAvoidWidow() const { return m_rareData ? m_rareData->m_lineBreakToAvoidWidow : 0; }
- void setBreakAtLineToAvoidWidow(RootInlineBox*);
+ int lineBreakToAvoidWidow() const { return m_rareData ? m_rareData->m_lineBreakToAvoidWidow : -1; }
+ void setBreakAtLineToAvoidWidow(int);
+ void clearDidBreakAtLineToAvoidWidow();
+ void setDidBreakAtLineToAvoidWidow();
+ bool didBreakAtLineToAvoidWidow() const { return m_rareData && m_rareData->m_didBreakAtLineToAvoidWidow; }
// The page logical offset is the object's offset from the top of the page in the page progression
// direction (so an x-offset in vertical text and a y-offset for horizontal text).
LayoutUnit pageLogicalOffset() const { return m_rareData ? m_rareData->m_pageLogicalOffset : LayoutUnit(); }
void setPageLogicalOffset(LayoutUnit);
- RootInlineBox* lineGridBox() const { return m_rareData ? m_rareData->m_lineGridBox : 0; }
- void setLineGridBox(RootInlineBox* box)
- {
- if (!m_rareData)
- m_rareData = adoptPtr(new RenderBlockRareData());
- if (m_rareData->m_lineGridBox)
- m_rareData->m_lineGridBox->destroy();
- m_rareData->m_lineGridBox = box;
- }
- void layoutLineGridBox();
-
// Accessors for logical width/height and margins in the containing block's block-flow direction.
enum ApplyLayoutDeltaMode { ApplyLayoutDelta, DoNotApplyLayoutDelta };
- LayoutUnit logicalWidthForChild(const RenderBox* child) { return isHorizontalWritingMode() ? child->width() : child->height(); }
- LayoutUnit logicalHeightForChild(const RenderBox* child) { return isHorizontalWritingMode() ? child->height() : child->width(); }
- LayoutUnit logicalTopForChild(const RenderBox* child) { return isHorizontalWritingMode() ? child->y() : child->x(); }
+ LayoutUnit logicalWidthForChild(const RenderBox* child) const { return isHorizontalWritingMode() ? child->width() : child->height(); }
+ LayoutUnit logicalHeightForChild(const RenderBox* child) const { return isHorizontalWritingMode() ? child->height() : child->width(); }
+ LayoutUnit logicalTopForChild(const RenderBox* child) const { return isHorizontalWritingMode() ? child->y() : child->x(); }
void setLogicalLeftForChild(RenderBox* child, LayoutUnit logicalLeft, ApplyLayoutDeltaMode = DoNotApplyLayoutDelta);
void setLogicalTopForChild(RenderBox* child, LayoutUnit logicalTop, ApplyLayoutDeltaMode = DoNotApplyLayoutDelta);
LayoutUnit marginBeforeForChild(const RenderBoxModelObject* child) const { return child->marginBefore(style()); }
@@ -351,8 +312,6 @@ public:
LayoutUnit collapsedMarginBeforeForChild(const RenderBox* child) const;
LayoutUnit collapsedMarginAfterForChild(const RenderBox* child) const;
- void updateLogicalWidthForAlignment(const ETextAlign&, const RootInlineBox*, BidiRun* trailingSpaceRun, float& logicalLeft, float& totalLogicalWidth, float& availableLogicalWidth, int expansionOpportunityCount);
-
virtual void updateFirstLetter();
virtual void scrollbarsChanged(bool /*horizontalScrollbarChanged*/, bool /*verticalScrollbarChanged*/) { };
@@ -361,7 +320,8 @@ public:
LayoutUnit logicalRightOffsetForContent(RenderRegion*) const;
LayoutUnit availableLogicalWidthForContent(RenderRegion* region) const
{
- return max<LayoutUnit>(0, logicalRightOffsetForContent(region) - logicalLeftOffsetForContent(region)); }
+ return max<LayoutUnit>(0, logicalRightOffsetForContent(region) - logicalLeftOffsetForContent(region));
+ }
LayoutUnit startOffsetForContent(RenderRegion* region) const
{
return style()->isLeftToRightDirection() ? logicalLeftOffsetForContent(region) : logicalWidth() - logicalRightOffsetForContent(region);
@@ -395,14 +355,8 @@ public:
LayoutUnit startOffsetForContent() const { return style()->isLeftToRightDirection() ? logicalLeftOffsetForContent() : logicalWidth() - logicalRightOffsetForContent(); }
LayoutUnit endOffsetForContent() const { return !style()->isLeftToRightDirection() ? logicalLeftOffsetForContent() : logicalWidth() - logicalRightOffsetForContent(); }
- void setStaticInlinePositionForChild(RenderBox*, LayoutUnit blockOffset, LayoutUnit inlinePosition);
- void updateStaticInlinePositionForChild(RenderBox*, LayoutUnit logicalTop);
-
LayoutUnit computeStartPositionDeltaForChildAvoidingFloats(const RenderBox* child, LayoutUnit childMarginStart, RenderRegion* = 0);
- void placeRunInIfNeeded(RenderObject* newChild);
- bool runInIsPlacedIntoSiblingBlock(RenderObject* runIn);
-
#ifndef NDEBUG
void checkPositionedObjectsNeedLayout();
void showLineTreeAndMark(const InlineBox* = 0, const char* = 0, const InlineBox* = 0, const char* = 0, const RenderObject* = 0) const;
@@ -425,7 +379,8 @@ public:
m_rareData->m_shapeInsideInfo = value;
}
ShapeInsideInfo* layoutShapeInsideInfo() const;
- bool allowsShapeInsideInfoSharing() const { return !isInline() && !isFloating(); }
+ bool allowsShapeInsideInfoSharing(const RenderBlock* other) const;
+ LayoutSize logicalOffsetFromShapeAncestorContainer(const RenderBlock* container) const;
virtual void imageChanged(WrappedImagePtr, const IntRect* = 0) OVERRIDE;
// inline-block elements paint all phases atomically. This function ensures that. Certain other elements
@@ -438,6 +393,9 @@ protected:
void dirtyForLayoutFromPercentageHeightDescendants(SubtreeLayoutScope&);
virtual void layout();
+ virtual void didLayout(ResourceLoadPriorityOptimizer&);
+ virtual void didScroll(ResourceLoadPriorityOptimizer&);
+ void updateStyleImageLoadingPriorities(ResourceLoadPriorityOptimizer&);
void layoutPositionedObjects(bool relayoutChildren, bool fixedPositionObjectsOnly = false);
void markFixedPositionObjectForLayoutIfNeeded(RenderObject* child, SubtreeLayoutScope&);
@@ -452,24 +410,15 @@ protected:
void paintChild(RenderBox*, PaintInfo&, const LayoutPoint&);
void paintChildAsInlineBlock(RenderBox*, PaintInfo&, const LayoutPoint&);
- LayoutUnit logicalRightOffsetForLine(LayoutUnit logicalTop, LayoutUnit fixedOffset, bool applyTextIndent, LayoutUnit* heightRemaining = 0, LayoutUnit logicalHeight = 0) const
+ LayoutUnit logicalRightOffsetForLine(LayoutUnit logicalTop, LayoutUnit fixedOffset, bool applyTextIndent, LayoutUnit logicalHeight = 0) const
{
- return adjustLogicalRightOffsetForLine(logicalRightFloatOffsetForLine(logicalTop, fixedOffset, heightRemaining, logicalHeight, ShapeOutsideFloatShapeOffset), applyTextIndent);
+ return adjustLogicalRightOffsetForLine(logicalRightFloatOffsetForLine(logicalTop, fixedOffset, logicalHeight), applyTextIndent);
}
- LayoutUnit logicalLeftOffsetForLine(LayoutUnit logicalTop, LayoutUnit fixedOffset, bool applyTextIndent, LayoutUnit* heightRemaining = 0, LayoutUnit logicalHeight = 0) const
+ LayoutUnit logicalLeftOffsetForLine(LayoutUnit logicalTop, LayoutUnit fixedOffset, bool applyTextIndent, LayoutUnit logicalHeight = 0) const
{
- return adjustLogicalLeftOffsetForLine(logicalLeftFloatOffsetForLine(logicalTop, fixedOffset, heightRemaining, logicalHeight, ShapeOutsideFloatShapeOffset), applyTextIndent);
- }
- LayoutUnit logicalRightOffsetForLineIgnoringShapeOutside(LayoutUnit logicalTop, LayoutUnit fixedOffset, bool applyTextIndent, LayoutUnit* heightRemaining = 0, LayoutUnit logicalHeight = 0) const
- {
- return adjustLogicalRightOffsetForLine(logicalRightFloatOffsetForLine(logicalTop, fixedOffset, heightRemaining, logicalHeight, ShapeOutsideFloatMarginBoxOffset), applyTextIndent);
- }
- LayoutUnit logicalLeftOffsetForLineIgnoringShapeOutside(LayoutUnit logicalTop, LayoutUnit fixedOffset, bool applyTextIndent, LayoutUnit* heightRemaining = 0, LayoutUnit logicalHeight = 0) const
- {
- return adjustLogicalLeftOffsetForLine(logicalLeftFloatOffsetForLine(logicalTop, fixedOffset, heightRemaining, logicalHeight, ShapeOutsideFloatMarginBoxOffset), applyTextIndent);
+ return adjustLogicalLeftOffsetForLine(logicalLeftFloatOffsetForLine(logicalTop, fixedOffset, logicalHeight), applyTextIndent);
}
- virtual ETextAlign textAlignmentForLine(bool endsWithSoftBreak) const;
virtual void adjustInlineDirectionLineBounds(int /* expansionOpportunityCount */, float& /* logicalLeft */, float& /* logicalWidth */) const { }
virtual bool nodeAtPoint(const HitTestRequest&, HitTestResult&, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction) OVERRIDE;
@@ -505,13 +454,11 @@ protected:
void setDesiredColumnCountAndWidth(int, LayoutUnit);
public:
- void computeOverflow(LayoutUnit oldClientAfterEdge, bool recomputeFloats = false);
+ virtual void computeOverflow(LayoutUnit oldClientAfterEdge, bool = false);
protected:
virtual void addOverflowFromChildren();
- void addOverflowFromFloats();
void addOverflowFromPositionedObjects();
void addOverflowFromBlockChildren();
- void addOverflowFromInlineChildren();
void addVisualOverflowFromTheme();
virtual void addFocusRingRects(Vector<IntRect>&, const LayoutPoint& additionalOffset, const RenderLayerModelObject* paintContainer = 0) OVERRIDE;
@@ -528,8 +475,10 @@ protected:
virtual bool isInlineBlockOrInlineTable() const OVERRIDE FINAL { return isInline() && isReplaced(); }
private:
- LayoutUnit logicalRightFloatOffsetForLine(LayoutUnit logicalTop, LayoutUnit fixedOffset, LayoutUnit* heightRemaining, LayoutUnit logicalHeight, ShapeOutsideFloatOffsetMode) const;
- LayoutUnit logicalLeftFloatOffsetForLine(LayoutUnit logicalTop, LayoutUnit fixedOffset, LayoutUnit* heightRemaining, LayoutUnit logicalHeight, ShapeOutsideFloatOffsetMode) const;
+ // FIXME-BLOCKFLOW: Remove virtualizaion when all callers have moved to RenderBlockFlow
+ virtual LayoutUnit logicalRightFloatOffsetForLine(LayoutUnit, LayoutUnit fixedOffset, LayoutUnit) const { return fixedOffset; }
+ // FIXME-BLOCKFLOW: Remove virtualizaion when all callers have moved to RenderBlockFlow
+ virtual LayoutUnit logicalLeftFloatOffsetForLine(LayoutUnit, LayoutUnit fixedOffset, LayoutUnit) const { return fixedOffset; }
LayoutUnit adjustLogicalRightOffsetForLine(LayoutUnit offsetFromFloats, bool applyTextIndent) const;
LayoutUnit adjustLogicalLeftOffsetForLine(LayoutUnit offsetFromFloats, bool applyTextIndent) const;
@@ -537,7 +486,6 @@ private:
void updateRegionsAndShapesAfterChildLayout(RenderFlowThread*, bool);
void updateShapeInsideInfoAfterStyleChange(const ShapeValue*, const ShapeValue* oldShape);
void relayoutShapeDescendantIfMoved(RenderBlock* child, LayoutSize offset);
- LayoutSize logicalOffsetFromShapeAncestorContainer(const RenderBlock* container) const;
virtual RenderObjectChildList* virtualChildren() OVERRIDE FINAL { return children(); }
virtual const RenderObjectChildList* virtualChildren() const OVERRIDE FINAL { return children(); }
@@ -550,7 +498,8 @@ private:
virtual void removeLeftoverAnonymousBlock(RenderBlock* child);
static void collapseAnonymousBlockChild(RenderBlock* parent, RenderBlock* child);
- void moveAllChildrenIncludingFloatsTo(RenderBlock* toBlock, bool fullRemoveInsert);
+ // FIXME-BLOCKFLOW: Remove virtualizaion when all callers have moved to RenderBlockFlow
+ virtual void moveAllChildrenIncludingFloatsTo(RenderBlock* toBlock, bool fullRemoveInsert) { moveAllChildrenTo(toBlock, fullRemoveInsert); }
virtual void dirtyLinesFromChangedChild(RenderObject* child) OVERRIDE FINAL { m_lineBoxes.dirtyLinesFromChangedChild(this, child); }
@@ -562,14 +511,10 @@ private:
virtual bool isSelfCollapsingBlock() const OVERRIDE FINAL;
- virtual void repaintOverhangingFloats(bool paintAllDescendants) OVERRIDE FINAL;
-
- BidiRun* handleTrailingSpaces(BidiRunList<BidiRun>&, BidiContext*);
-
void insertIntoTrackedRendererMaps(RenderBox* descendant, TrackedDescendantsMap*&, TrackedContainerMap*&);
static void removeFromTrackedRendererMaps(RenderBox* descendant, TrackedDescendantsMap*&, TrackedContainerMap*&);
- virtual RootInlineBox* createRootInlineBox(); // Subclassed by SVG and Ruby.
+ virtual RootInlineBox* createRootInlineBox() { return 0; } // Subclassed by RenderBlockFlow, SVG and Ruby.
// Called to lay out the legend for a fieldset or the ruby text of a ruby run.
virtual RenderObject* layoutSpecialExcludedChild(bool /*relayoutChildren*/, SubtreeLayoutScope&) { return 0; }
@@ -579,65 +524,8 @@ private:
Node* nodeForHitTest() const;
- struct FloatWithRect {
- FloatWithRect(RenderBox* f)
- : object(f)
- , rect(LayoutRect(f->x() - f->marginLeft(), f->y() - f->marginTop(), f->width() + f->marginWidth(), f->height() + f->marginHeight()))
- , everHadLayout(f->everHadLayout())
- {
- }
-
- RenderBox* object;
- LayoutRect rect;
- bool everHadLayout;
- };
-
- LayoutPoint flipFloatForWritingModeForChild(const FloatingObject*, const LayoutPoint&) const;
-
- LayoutUnit xPositionForFloatIncludingMargin(const FloatingObject* child) const
- {
- if (isHorizontalWritingMode())
- return child->x() + child->renderer()->marginLeft();
- else
- return child->x() + marginBeforeForChild(child->renderer());
- }
-
- LayoutUnit yPositionForFloatIncludingMargin(const FloatingObject* child) const
- {
- if (isHorizontalWritingMode())
- return child->y() + marginBeforeForChild(child->renderer());
- else
- return child->y() + child->renderer()->marginTop();
- }
-
- LayoutPoint computeLogicalLocationForFloat(const FloatingObject*, LayoutUnit logicalTopOffset) const;
-
- void checkFloatsInCleanLine(RootInlineBox*, Vector<FloatWithRect>&, size_t& floatIndex, bool& encounteredNewFloat, bool& dirtiedByFloat);
- RootInlineBox* determineStartPosition(LineLayoutState&, InlineBidiResolver&);
- void determineEndPosition(LineLayoutState&, RootInlineBox* startBox, InlineIterator& cleanLineStart, BidiStatus& cleanLineBidiStatus);
- bool matchedEndLine(LineLayoutState&, const InlineBidiResolver&, const InlineIterator& endLineStart, const BidiStatus& endLineStatus);
- bool checkPaginationAndFloatsAtEndLine(LineLayoutState&);
-
- RootInlineBox* constructLine(BidiRunList<BidiRun>&, const LineInfo&);
- InlineFlowBox* createLineBoxes(RenderObject*, const LineInfo&, InlineBox* childBox, bool startsNewSegment);
-
- void setMarginsForRubyRun(BidiRun*, RenderRubyRun*, RenderObject*, const LineInfo&);
-
- BidiRun* computeInlineDirectionPositionsForSegment(RootInlineBox*, const LineInfo&, ETextAlign, float& logicalLeft,
- float& availableLogicalWidth, BidiRun* firstRun, BidiRun* trailingSpaceRun, GlyphOverflowAndFallbackFontsMap& textBoxDataMap, VerticalPositionCache&, WordMeasurements&);
- void computeInlineDirectionPositionsForLine(RootInlineBox*, const LineInfo&, BidiRun* firstRun, BidiRun* trailingSpaceRun, bool reachedEnd, GlyphOverflowAndFallbackFontsMap&, VerticalPositionCache&, WordMeasurements&);
- void computeBlockDirectionPositionsForLine(RootInlineBox*, BidiRun*, GlyphOverflowAndFallbackFontsMap&, VerticalPositionCache&);
- void deleteEllipsisLineBoxes();
- void checkLinesForTextOverflow();
-
- // Positions new floats and also adjust all floats encountered on the line if any of them
- // have to move to the next page/column.
- bool positionNewFloatOnLine(FloatingObject* newFloat, FloatingObject* lastFloatFromPreviousLine, LineInfo&, LineWidth&);
- void appendFloatingObjectToLastLine(FloatingObject*);
-
- // End of functions defined in RenderBlockLineLayout.cpp.
-
- void paintFloats(PaintInfo&, const LayoutPoint&, bool preservePhase = false);
+ // FIXME-BLOCKFLOW: Remove virtualizaion when all callers have moved to RenderBlockFlow
+ virtual void paintFloats(PaintInfo&, const LayoutPoint&, bool) { }
void paintContents(PaintInfo&, const LayoutPoint&);
void paintColumnContents(PaintInfo&, const LayoutPoint&, bool paintFloats = false);
void paintColumnRules(PaintInfo&, const LayoutPoint&);
@@ -647,29 +535,12 @@ private:
bool hasCaret() const { return hasCaret(CursorCaret) || hasCaret(DragCaret); }
bool hasCaret(CaretType) const;
- FloatingObject* insertFloatingObject(RenderBox*);
- void removeFloatingObject(RenderBox*);
- void removeFloatingObjectsBelow(FloatingObject*, int logicalOffset);
-
- // Called from lineWidth, to position the floats added in the last line.
- // Returns true if and only if it has positioned any floats.
- bool positionNewFloats();
-
- LayoutUnit getClearDelta(RenderBox* child, LayoutUnit yPos);
-
virtual bool avoidsFloats() const;
- bool hasOverhangingFloats() { return parent() && !hasColumns() && containsFloats() && lowestFloatLogicalBottom() > logicalHeight(); }
- bool hasOverhangingFloat(RenderBox*);
- void addIntrudingFloats(RenderBlock* prev, LayoutUnit xoffset, LayoutUnit yoffset);
- LayoutUnit addOverhangingFloats(RenderBlock* child, bool makeChildPaintOtherFloats);
-
- LayoutUnit lowestFloatLogicalBottom(FloatingObject::Type = FloatingObject::FloatLeftRight) const;
- LayoutUnit nextFloatLogicalBottomBelow(LayoutUnit) const;
-
bool hitTestColumns(const HitTestRequest&, HitTestResult&, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction);
bool hitTestContents(const HitTestRequest&, HitTestResult&, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction);
- bool hitTestFloats(const HitTestRequest&, HitTestResult&, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset);
+ // FIXME-BLOCKFLOW: Remove virtualizaion when all callers have moved to RenderBlockFlow
+ virtual bool hitTestFloats(const HitTestRequest&, HitTestResult&, const HitTestLocation&, const LayoutPoint&) { return false; }
virtual bool isPointInOverflowControl(HitTestResult&, const LayoutPoint& locationInContainer, const LayoutPoint& accumulatedOffset);
@@ -696,8 +567,6 @@ private:
bool isSelectionRoot() const;
GapRects selectionGaps(RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
LayoutUnit& lastLogicalTop, LayoutUnit& lastLogicalLeft, LayoutUnit& lastLogicalRight, const PaintInfo* = 0);
- GapRects inlineSelectionGaps(RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
- LayoutUnit& lastLogicalTop, LayoutUnit& lastLogicalLeft, LayoutUnit& lastLogicalRight, const PaintInfo*);
GapRects blockSelectionGaps(RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
LayoutUnit& lastLogicalTop, LayoutUnit& lastLogicalLeft, LayoutUnit& lastLogicalRight, const PaintInfo*);
LayoutRect blockSelectionGap(RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
@@ -705,11 +574,13 @@ private:
LayoutUnit logicalLeftSelectionOffset(RenderBlock* rootBlock, LayoutUnit position);
LayoutUnit logicalRightSelectionOffset(RenderBlock* rootBlock, LayoutUnit position);
+ // FIXME-BLOCKFLOW: Remove virtualizaion when all callers have moved to RenderBlockFlow
+ virtual void clipOutFloatingObjects(RenderBlock*, const PaintInfo*, const LayoutPoint&, const LayoutSize&) { };
+
virtual void absoluteRects(Vector<IntRect>&, const LayoutPoint& accumulatedOffset) const;
virtual void absoluteQuads(Vector<FloatQuad>&, bool* wasFixed) const;
LayoutUnit desiredColumnWidth() const;
- unsigned desiredColumnCount() const;
void paintContinuationOutlines(PaintInfo&, const LayoutPoint&);
@@ -718,17 +589,15 @@ private:
void adjustPointToColumnContents(LayoutPoint&) const;
void fitBorderToLinesIfNeeded(); // Shrink the box in which the border paints if border-fit is set.
- void adjustForBorderFit(LayoutUnit x, LayoutUnit& left, LayoutUnit& right) const; // Helper function for borderFitAdjust
+ virtual void adjustForBorderFit(LayoutUnit x, LayoutUnit& left, LayoutUnit& right) const; // Helper function for borderFitAdjust
void markLinesDirtyInBlockRange(LayoutUnit logicalTop, LayoutUnit logicalBottom, RootInlineBox* highest = 0);
- void newLine(EClear);
-
Position positionForBox(InlineBox*, bool start = true) const;
PositionWithAffinity positionForPointWithInlineChildren(const LayoutPoint&);
virtual void calcColumnWidth();
- void makeChildrenAnonymousColumnBlocks(RenderObject* beforeChild, RenderBlock* newBlockBox, RenderObject* newChild);
+ void makeChildrenAnonymousColumnBlocks(RenderObject* beforeChild, RenderBlockFlow* newBlockBox, RenderObject* newChild);
bool expandsToEncloseOverhangingFloats() const;
@@ -738,30 +607,16 @@ private:
RenderObject* newChild, RenderBoxModelObject* oldCont);
RenderBlock* clone() const;
RenderBlock* continuationBefore(RenderObject* beforeChild);
- RenderBlock* containingColumnsBlock(bool allowAnonymousColumnBlock = true);
- RenderBlock* columnsBlockForSpanningElement(RenderObject* newChild);
+ RenderBlockFlow* containingColumnsBlock(bool allowAnonymousColumnBlock = true);
+ RenderBlockFlow* columnsBlockForSpanningElement(RenderObject* newChild);
- RenderBoxModelObject* createReplacementRunIn(RenderBoxModelObject* runIn);
- void moveRunInUnderSiblingBlockIfNeeded(RenderObject* runIn);
- void moveRunInToOriginalPosition(RenderObject* runIn);
// End helper functions and structs used by layoutBlockChildren.
- // Helper function for layoutInlineChildren()
- RootInlineBox* createLineBoxesFromBidiRuns(unsigned bidiLevel, BidiRunList<BidiRun>&, const InlineIterator& end, LineInfo&, VerticalPositionCache&, BidiRun* trailingSpaceRun, WordMeasurements&);
- void layoutRunsAndFloats(LineLayoutState&, bool hasInlineChild);
- void layoutRunsAndFloatsInRange(LineLayoutState&, InlineBidiResolver&, const InlineIterator& cleanLineStart, const BidiStatus& cleanLineBidiStatus, unsigned consecutiveHyphenatedLines);
- void updateShapeAndSegmentsForCurrentLine(ShapeInsideInfo*&, const LayoutSize&, LineLayoutState&);
- void updateShapeAndSegmentsForCurrentLineInFlowThread(ShapeInsideInfo*&, LineLayoutState&);
- bool adjustLogicalLineTopAndLogicalHeightIfNeeded(ShapeInsideInfo*, LayoutUnit, LineLayoutState&, InlineBidiResolver&, FloatingObject*, InlineIterator&, WordMeasurements&);
- const InlineIterator& restartLayoutRunsAndFloatsInRange(LayoutUnit oldLogicalHeight, LayoutUnit newLogicalHeight, FloatingObject* lastFloatFromPreviousLine, InlineBidiResolver&, const InlineIterator&);
- void linkToEndLineIfNeeded(LineLayoutState&);
- static void repaintDirtyFloats(Vector<FloatWithRect>& floats);
-
protected:
void determineLogicalLeftPositionForChild(RenderBox* child, ApplyLayoutDeltaMode = DoNotApplyLayoutDelta);
// Pagination routines.
- virtual bool relayoutForPagination(bool hasSpecifiedPageLogicalHeight, LayoutUnit pageLogicalHeight, LayoutStateMaintainer&);
+ bool relayoutToAvoidWidows(LayoutStateMaintainer&);
// Returns the logicalOffset at the top of the next page. If the offset passed in is already at the top of the current page,
// then nextPageLogicalTop with ExcludePageBoundary will still move to the top of the next page. nextPageLogicalTop with
@@ -792,6 +647,7 @@ protected:
LayoutUnit adjustForUnsplittableChild(RenderBox* child, LayoutUnit logicalOffset, bool includeMargins = false); // If the child is unsplittable and can't fit on the current page, return the top of the next page/column.
void adjustLinePositionForPagination(RootInlineBox*, LayoutUnit& deltaOffset, RenderFlowThread*); // Computes a deltaOffset value that put a line at the top of the next page if it doesn't fit on the current page.
+ void updateRegionForLine(RootInlineBox*) const;
// Adjust from painting offsets to the local coords of this renderer
void offsetForContents(LayoutPoint&) const;
@@ -814,10 +670,6 @@ public:
RenderRegion* regionAtBlockOffset(LayoutUnit) const;
RenderRegion* clampToStartAndEndRegions(RenderRegion*) const;
-protected:
-
- void createFloatingObjects();
-
public:
// Allocated only when some of these fields have non-default values
@@ -827,25 +679,20 @@ public:
RenderBlockRareData()
: m_paginationStrut(0)
, m_pageLogicalOffset(0)
- , m_lineGridBox(0)
- , m_lineBreakToAvoidWidow(0)
- , m_shouldBreakAtLineToAvoidWidow(false)
+ , m_lineBreakToAvoidWidow(-1)
+ , m_didBreakAtLineToAvoidWidow(false)
{
}
LayoutUnit m_paginationStrut;
LayoutUnit m_pageLogicalOffset;
- RootInlineBox* m_lineGridBox;
-
- RootInlineBox* m_lineBreakToAvoidWidow;
+ int m_lineBreakToAvoidWidow;
OwnPtr<ShapeInsideInfo> m_shapeInsideInfo;
- bool m_shouldBreakAtLineToAvoidWidow : 1;
+ bool m_didBreakAtLineToAvoidWidow : 1;
};
protected:
-
- OwnPtr<FloatingObjects> m_floatingObjects;
OwnPtr<RenderBlockRareData> m_rareData;
RenderObjectChildList m_children;
@@ -861,31 +708,29 @@ protected:
// RenderRubyBase objects need to be able to split and merge, moving their children around
// (calling moveChildTo, moveAllChildrenTo, and makeChildrenNonInline).
friend class RenderRubyBase;
+ // FIXME-BLOCKFLOW: Remove this when the line layout stuff has all moved out of RenderBlock
friend class LineBreaker;
- friend class LineWidth; // Needs to know FloatingObject
// FIXME: This is temporary as we move code that accesses block flow
// member variables out of RenderBlock and into RenderBlockFlow.
friend class RenderBlockFlow;
-private:
- // Used to store state between styleWillChange and styleDidChange
- static bool s_canPropagateFloatIntoSibling;
};
-inline RenderBlock* toRenderBlock(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isRenderBlock());
- return static_cast<RenderBlock*>(object);
-}
-inline const RenderBlock* toRenderBlock(const RenderObject* object)
+inline bool RenderBlock::allowsShapeInsideInfoSharing(const RenderBlock* other) const
{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isRenderBlock());
- return static_cast<const RenderBlock*>(object);
+ if (!other)
+ return false;
+ for (const RenderBlock* current = this; current && current != other && !current->isRenderFlowThread(); current = current->containingBlock()) {
+ if (current->isInline() || current->isFloating())
+ return false;
+ if (current->parent() != current->containingBlock())
+ return false;
+ }
+ return true;
}
-// This will catch anyone doing an unnecessary cast.
-void toRenderBlock(const RenderBlock*);
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderBlock, isRenderBlock());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderBlockFlow.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderBlockFlow.cpp
index 51faaef8457..96725842afd 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderBlockFlow.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderBlockFlow.cpp
@@ -31,16 +31,26 @@
#include "config.h"
#include "core/rendering/RenderBlockFlow.h"
-#include "core/page/FrameView.h"
+#include "core/frame/FrameView.h"
+#include "core/rendering/HitTestLocation.h"
+#include "core/rendering/LayoutRectRecorder.h"
#include "core/rendering/LayoutRepainter.h"
+#include "core/rendering/LineWidth.h"
#include "core/rendering/RenderLayer.h"
+#include "core/rendering/RenderNamedFlowFragment.h"
#include "core/rendering/RenderNamedFlowThread.h"
+#include "core/rendering/RenderText.h"
#include "core/rendering/RenderView.h"
+#include "core/rendering/svg/SVGTextRunRenderingContext.h"
+#include "platform/text/BidiResolver.h"
+#include "platform/text/TextRunIterator.h"
using namespace std;
namespace WebCore {
+bool RenderBlockFlow::s_canPropagateFloatIntoSibling = false;
+
struct SameSizeAsMarginInfo {
uint16_t bitfields;
LayoutUnit margins[2];
@@ -151,6 +161,82 @@ RenderBlockFlow::~RenderBlockFlow()
{
}
+RenderBlockFlow* RenderBlockFlow::createAnonymous(Document* document)
+{
+ RenderBlockFlow* renderer = new RenderBlockFlow(0);
+ renderer->setDocumentForAnonymous(document);
+ return renderer;
+}
+
+RenderBlockFlow* RenderBlockFlow::createAnonymousBlockFlow() const
+{
+ return toRenderBlockFlow(createAnonymousWithParentRendererAndDisplay(this, BLOCK));
+}
+
+void RenderBlockFlow::willBeDestroyed()
+{
+ if (lineGridBox())
+ lineGridBox()->destroy();
+
+ if (renderNamedFlowFragment())
+ setRenderNamedFlowFragment(0);
+
+ RenderBlock::willBeDestroyed();
+}
+
+bool RenderBlockFlow::relayoutForPagination(bool hasSpecifiedPageLogicalHeight, LayoutUnit pageLogicalHeight, LayoutStateMaintainer& statePusher)
+{
+ if (!hasColumns())
+ return false;
+
+ OwnPtr<RenderOverflow> savedOverflow = m_overflow.release();
+ if (childrenInline())
+ addOverflowFromInlineChildren();
+ else
+ addOverflowFromBlockChildren();
+ LayoutUnit layoutOverflowLogicalBottom = (isHorizontalWritingMode() ? layoutOverflowRect().maxY() : layoutOverflowRect().maxX()) - borderBefore() - paddingBefore();
+
+ // FIXME: We don't balance properly at all in the presence of forced page breaks. We need to understand what
+ // the distance between forced page breaks is so that we can avoid making the minimum column height too tall.
+ ColumnInfo* colInfo = columnInfo();
+ if (!hasSpecifiedPageLogicalHeight) {
+ LayoutUnit columnHeight = pageLogicalHeight;
+ int minColumnCount = colInfo->forcedBreaks() + 1;
+ int desiredColumnCount = colInfo->desiredColumnCount();
+ if (minColumnCount >= desiredColumnCount) {
+ // The forced page breaks are in control of the balancing. Just set the column height to the
+ // maximum page break distance.
+ if (!pageLogicalHeight) {
+ LayoutUnit distanceBetweenBreaks = max<LayoutUnit>(colInfo->maximumDistanceBetweenForcedBreaks(),
+ view()->layoutState()->pageLogicalOffset(this, borderBefore() + paddingBefore() + layoutOverflowLogicalBottom) - colInfo->forcedBreakOffset());
+ columnHeight = max(colInfo->minimumColumnHeight(), distanceBetweenBreaks);
+ }
+ } else if (layoutOverflowLogicalBottom > boundedMultiply(pageLogicalHeight, desiredColumnCount)) {
+ // Now that we know the intrinsic height of the columns, we have to rebalance them.
+ columnHeight = max<LayoutUnit>(colInfo->minimumColumnHeight(), ceilf((float)layoutOverflowLogicalBottom / desiredColumnCount));
+ }
+
+ if (columnHeight && columnHeight != pageLogicalHeight) {
+ statePusher.pop();
+ setEverHadLayout(true);
+ layoutBlock(false, columnHeight);
+ return true;
+ }
+ }
+
+ if (pageLogicalHeight)
+ colInfo->setColumnCountAndHeight(ceilf((float)layoutOverflowLogicalBottom / pageLogicalHeight), pageLogicalHeight);
+
+ if (columnCount(colInfo)) {
+ setLogicalHeight(borderBefore() + paddingBefore() + colInfo->columnHeight() + borderAfter() + paddingAfter() + scrollbarLogicalHeight());
+ m_overflow.clear();
+ } else {
+ m_overflow = savedOverflow.release();
+ }
+
+ return false;
+}
+
void RenderBlockFlow::layoutBlock(bool relayoutChildren, LayoutUnit pageLogicalHeight)
{
ASSERT(needsLayout());
@@ -166,7 +252,7 @@ void RenderBlockFlow::layoutBlock(bool relayoutChildren, LayoutUnit pageLogicalH
if (updateLogicalWidthAndColumnWidth())
relayoutChildren = true;
- clearFloats();
+ rebuildFloatsFromIntruding();
LayoutUnit previousHeight = logicalHeight();
// FIXME: should this start out as borderAndPaddingLogicalHeight() + scrollbarLogicalHeight(),
@@ -178,8 +264,7 @@ void RenderBlockFlow::layoutBlock(bool relayoutChildren, LayoutUnit pageLogicalH
checkForPaginationLogicalHeightChange(pageLogicalHeight, pageLogicalHeightChanged, hasSpecifiedPageLogicalHeight);
RenderView* renderView = view();
- RenderStyle* styleToUse = style();
- LayoutStateMaintainer statePusher(renderView, this, locationOffset(), hasColumns() || hasTransform() || hasReflection() || styleToUse->isFlippedBlocksWritingMode(), pageLogicalHeight, pageLogicalHeightChanged, columnInfo());
+ LayoutStateMaintainer statePusher(renderView, this, locationOffset(), hasColumns() || hasTransform() || hasReflection() || style()->isFlippedBlocksWritingMode(), pageLogicalHeight, pageLogicalHeightChanged, columnInfo());
// Regions changing widths can force us to relayout our children.
RenderFlowThread* flowThread = flowThreadContainingBlock();
@@ -187,6 +272,8 @@ void RenderBlockFlow::layoutBlock(bool relayoutChildren, LayoutUnit pageLogicalH
relayoutChildren = true;
if (updateRegionsAndShapesLogicalSize(flowThread))
relayoutChildren = true;
+ if (!relayoutChildren && isRenderNamedFlowFragmentContainer())
+ relayoutChildren = true;
// We use four values, maxTopPos, maxTopNeg, maxBottomPos, and maxBottomNeg, to track
// our current maximal positive and negative margins. These values are used when we
@@ -202,20 +289,20 @@ void RenderBlockFlow::layoutBlock(bool relayoutChildren, LayoutUnit pageLogicalH
if (!isCell) {
initMaxMarginValues();
- setHasMarginBeforeQuirk(styleToUse->hasMarginBeforeQuirk());
- setHasMarginAfterQuirk(styleToUse->hasMarginAfterQuirk());
+ setHasMarginBeforeQuirk(style()->hasMarginBeforeQuirk());
+ setHasMarginAfterQuirk(style()->hasMarginAfterQuirk());
setPaginationStrut(0);
}
SubtreeLayoutScope layoutScope(this);
- LayoutUnit repaintLogicalTop = 0;
- LayoutUnit repaintLogicalBottom = 0;
+ m_repaintLogicalTop = 0;
+ m_repaintLogicalBottom = 0;
LayoutUnit maxFloatLogicalBottom = 0;
if (!firstChild() && !isAnonymousBlock())
setChildrenInline(true);
if (childrenInline())
- layoutInlineChildren(relayoutChildren, repaintLogicalTop, repaintLogicalBottom);
+ layoutInlineChildren(relayoutChildren, m_repaintLogicalTop, m_repaintLogicalBottom);
else
layoutBlockChildren(relayoutChildren, maxFloatLogicalBottom, layoutScope);
@@ -229,8 +316,10 @@ void RenderBlockFlow::layoutBlock(bool relayoutChildren, LayoutUnit pageLogicalH
if (lowestFloatLogicalBottom() > (logicalHeight() - toAdd) && expandsToEncloseOverhangingFloats())
setLogicalHeight(lowestFloatLogicalBottom() + toAdd);
- if (relayoutForPagination(hasSpecifiedPageLogicalHeight, pageLogicalHeight, statePusher))
+ if (relayoutForPagination(hasSpecifiedPageLogicalHeight, pageLogicalHeight, statePusher) || relayoutToAvoidWidows(statePusher)) {
+ ASSERT(!shouldBreakAtLineToAvoidWidow());
return;
+ }
// Calculate our new height.
LayoutUnit oldHeight = logicalHeight();
@@ -248,7 +337,7 @@ void RenderBlockFlow::layoutBlock(bool relayoutChildren, LayoutUnit pageLogicalH
// One of our children's floats may have become an overhanging float for us. We need to look for it.
for (RenderObject* child = firstChild(); child; child = child->nextSibling()) {
if (child->isRenderBlockFlow() && !child->isFloatingOrOutOfFlowPositioned()) {
- RenderBlock* block = toRenderBlock(child);
+ RenderBlockFlow* block = toRenderBlockFlow(child);
if (block->lowestFloatLogicalBottom() + block->logicalTop() > newHeight)
addOverhangingFloats(block, false);
}
@@ -283,47 +372,13 @@ void RenderBlockFlow::layoutBlock(bool relayoutChildren, LayoutUnit pageLogicalH
// we overflow or not.
updateScrollInfoAfterLayout();
- // FIXME: This repaint logic should be moved into a separate helper function!
// Repaint with our new bounds if they are different from our old bounds.
bool didFullRepaint = repainter.repaintAfterLayout();
- if (!didFullRepaint && repaintLogicalTop != repaintLogicalBottom && (styleToUse->visibility() == VISIBLE || enclosingLayer()->hasVisibleContent())) {
- // FIXME: We could tighten up the left and right invalidation points if we let layoutInlineChildren fill them in based off the particular lines
- // it had to lay out. We wouldn't need the hasOverflowClip() hack in that case either.
- LayoutUnit repaintLogicalLeft = logicalLeftVisualOverflow();
- LayoutUnit repaintLogicalRight = logicalRightVisualOverflow();
- if (hasOverflowClip()) {
- // If we have clipped overflow, we should use layout overflow as well, since visual overflow from lines didn't propagate to our block's overflow.
- // Note the old code did this as well but even for overflow:visible. The addition of hasOverflowClip() at least tightens up the hack a bit.
- // layoutInlineChildren should be patched to compute the entire repaint rect.
- repaintLogicalLeft = min(repaintLogicalLeft, logicalLeftLayoutOverflow());
- repaintLogicalRight = max(repaintLogicalRight, logicalRightLayoutOverflow());
- }
-
- LayoutRect repaintRect;
- if (isHorizontalWritingMode())
- repaintRect = LayoutRect(repaintLogicalLeft, repaintLogicalTop, repaintLogicalRight - repaintLogicalLeft, repaintLogicalBottom - repaintLogicalTop);
+ if (!didFullRepaint && m_repaintLogicalTop != m_repaintLogicalBottom && (style()->visibility() == VISIBLE || enclosingLayer()->hasVisibleContent())) {
+ if (RuntimeEnabledFeatures::repaintAfterLayoutEnabled())
+ setShouldRepaintOverflowIfNeeded(true);
else
- repaintRect = LayoutRect(repaintLogicalTop, repaintLogicalLeft, repaintLogicalBottom - repaintLogicalTop, repaintLogicalRight - repaintLogicalLeft);
-
- // The repaint rect may be split across columns, in which case adjustRectForColumns() will return the union.
- adjustRectForColumns(repaintRect);
-
- repaintRect.inflate(maximalOutlineSize(PaintPhaseOutline));
-
- if (hasOverflowClip()) {
- // Adjust repaint rect for scroll offset
- repaintRect.move(-scrolledContentOffset());
-
- // Don't allow this rect to spill out of our overflow box.
- repaintRect.intersect(LayoutRect(LayoutPoint(), size()));
- }
-
- // Make sure the rect is still non-empty after intersecting for overflow above
- if (!repaintRect.isEmpty()) {
- repaintRectangle(repaintRect); // We need to do a partial repaint of our content.
- if (hasReflection())
- repaintRectangle(reflectedRect(repaintRect));
- }
+ repaintOverflow();
}
clearNeedsLayout();
@@ -354,6 +409,7 @@ void RenderBlockFlow::layoutBlockChild(RenderBox* child, MarginInfo& marginInfo,
setLogicalTopForChild(child, logicalTopEstimate, ApplyLayoutDelta);
RenderBlock* childRenderBlock = child->isRenderBlock() ? toRenderBlock(child) : 0;
+ RenderBlockFlow* childRenderBlockFlow = (childRenderBlock && child->isRenderBlockFlow()) ? toRenderBlockFlow(child) : 0;
bool markDescendantsWithFloats = false;
if (logicalTopEstimate != oldLogicalTop && !child->avoidsFloats() && childRenderBlock && childRenderBlock->containsFloats()) {
markDescendantsWithFloats = true;
@@ -371,11 +427,11 @@ void RenderBlockFlow::layoutBlockChild(RenderBox* child, MarginInfo& marginInfo,
markDescendantsWithFloats = true;
}
- if (childRenderBlock) {
+ if (childRenderBlockFlow) {
if (markDescendantsWithFloats)
- childRenderBlock->markAllDescendantsWithFloatsForLayout();
+ childRenderBlockFlow->markAllDescendantsWithFloatsForLayout();
if (!child->isWritingModeRoot())
- previousFloatLogicalBottom = max(previousFloatLogicalBottom, oldLogicalTop + childRenderBlock->lowestFloatLogicalBottom());
+ previousFloatLogicalBottom = max(previousFloatLogicalBottom, oldLogicalTop + childRenderBlockFlow->lowestFloatLogicalBottom());
}
SubtreeLayoutScope layoutScope(child);
@@ -423,7 +479,7 @@ void RenderBlockFlow::layoutBlockChild(RenderBox* child, MarginInfo& marginInfo,
if (childRenderBlock) {
if (!child->avoidsFloats() && childRenderBlock->containsFloats())
- childRenderBlock->markAllDescendantsWithFloatsForLayout();
+ childRenderBlockFlow->markAllDescendantsWithFloatsForLayout();
if (!child->needsLayout())
child->markForPaginationRelayoutIfNeeded(layoutScope);
}
@@ -451,8 +507,8 @@ void RenderBlockFlow::layoutBlockChild(RenderBox* child, MarginInfo& marginInfo,
}
// If the child has overhanging floats that intrude into following siblings (or possibly out
// of this block), then the parent gets notified of the floats now.
- if (childRenderBlock && childRenderBlock->containsFloats())
- maxFloatLogicalBottom = max(maxFloatLogicalBottom, addOverhangingFloats(toRenderBlock(child), !childNeededLayout));
+ if (childRenderBlockFlow && childRenderBlockFlow->containsFloats())
+ maxFloatLogicalBottom = max(maxFloatLogicalBottom, addOverhangingFloats(childRenderBlockFlow, !childNeededLayout));
if (childOffset.width() || childOffset.height()) {
view()->addLayoutDelta(childOffset);
@@ -460,12 +516,15 @@ void RenderBlockFlow::layoutBlockChild(RenderBox* child, MarginInfo& marginInfo,
// If the child moved, we have to repaint it as well as any floating/positioned
// descendants. An exception is if we need a layout. In this case, we know we're going to
// repaint ourselves (and the child) anyway.
- if (childHadLayout && !selfNeedsLayout() && child->checkForRepaintDuringLayout())
+ if (RuntimeEnabledFeatures::repaintAfterLayoutEnabled() && childHadLayout && !selfNeedsLayout())
+ child->repaintOverhangingFloats(true);
+ else if (childHadLayout && !selfNeedsLayout() && child->checkForRepaintDuringLayout())
child->repaintDuringLayoutIfMoved(oldRect);
}
if (!childHadLayout && child->checkForRepaintDuringLayout()) {
- child->repaint();
+ if (!RuntimeEnabledFeatures::repaintAfterLayoutEnabled())
+ child->repaint();
child->repaintOverhangingFloats(true);
}
@@ -501,7 +560,7 @@ LayoutUnit RenderBlockFlow::adjustBlockChildForPagination(LayoutUnit logicalTopA
if (childRenderBlock) {
if (!child->avoidsFloats() && childRenderBlock->containsFloats())
- childRenderBlock->markAllDescendantsWithFloatsForLayout();
+ toRenderBlockFlow(childRenderBlock)->markAllDescendantsWithFloatsForLayout();
if (!child->needsLayout())
child->markForPaginationRelayoutIfNeeded(layoutScope);
}
@@ -563,7 +622,7 @@ LayoutUnit RenderBlockFlow::adjustBlockChildForPagination(LayoutUnit logicalTopA
return result;
}
-void RenderBlockFlow::clearFloats()
+void RenderBlockFlow::rebuildFloatsFromIntruding()
{
if (m_floatingObjects)
m_floatingObjects->setHorizontalWritingMode(isHorizontalWritingMode());
@@ -598,16 +657,16 @@ void RenderBlockFlow::clearFloats()
m_floatingObjects->clear();
}
- // We should not process floats if the parent node is not a RenderBlock. Otherwise, we will add
+ // We should not process floats if the parent node is not a RenderBlockFlow. Otherwise, we will add
// floats in an invalid context. This will cause a crash arising from a bad cast on the parent.
// See <rdar://problem/8049753>, where float property is applied on a text node in a SVG.
- if (!parent() || !parent()->isRenderBlock())
+ if (!parent() || !parent()->isRenderBlockFlow())
return;
// Attempt to locate a previous sibling with overhanging floats. We skip any elements that are
// out of flow (like floating/positioned elements), and we also skip over any objects that may have shifted
// to avoid floats.
- RenderBlock* parentBlock = toRenderBlock(parent());
+ RenderBlockFlow* parentBlockFlow = toRenderBlockFlow(parent());
bool parentHasFloats = false;
RenderObject* prev = previousSibling();
while (prev && (prev->isFloatingOrOutOfFlowPositioned() || !prev->isBox() || !prev->isRenderBlock() || toRenderBlock(prev)->avoidsFloats())) {
@@ -616,23 +675,24 @@ void RenderBlockFlow::clearFloats()
prev = prev->previousSibling();
}
- // First add in floats from the parent.
+ // First add in floats from the parent. Self-collapsing blocks let their parent track any floats that intrude into
+ // them (as opposed to floats they contain themselves) so check for those here too.
LayoutUnit logicalTopOffset = logicalTop();
- if (parentHasFloats)
- addIntrudingFloats(parentBlock, parentBlock->logicalLeftOffsetForContent(), logicalTopOffset);
+ if (parentHasFloats || (prev && toRenderBlockFlow(prev)->isSelfCollapsingBlock() && parentBlockFlow->lowestFloatLogicalBottom() > logicalTopOffset))
+ addIntrudingFloats(parentBlockFlow, parentBlockFlow->logicalLeftOffsetForContent(), logicalTopOffset);
LayoutUnit logicalLeftOffset = 0;
if (prev) {
logicalTopOffset -= toRenderBox(prev)->logicalTop();
} else {
- prev = parentBlock;
- logicalLeftOffset += parentBlock->logicalLeftOffsetForContent();
+ prev = parentBlockFlow;
+ logicalLeftOffset += parentBlockFlow->logicalLeftOffsetForContent();
}
- // Add overhanging floats from the previous RenderBlock, but only if it has a float that intrudes into our space.
- RenderBlock* block = toRenderBlock(prev);
- if (block->m_floatingObjects && block->lowestFloatLogicalBottom() > logicalTopOffset)
- addIntrudingFloats(block, logicalLeftOffset, logicalTopOffset);
+ // Add overhanging floats from the previous RenderBlockFlow, but only if it has a float that intrudes into our space.
+ RenderBlockFlow* blockFlow = toRenderBlockFlow(prev);
+ if (blockFlow->m_floatingObjects && blockFlow->lowestFloatLogicalBottom() > logicalTopOffset)
+ addIntrudingFloats(blockFlow, logicalLeftOffset, logicalTopOffset);
if (childrenInline()) {
LayoutUnit changeLogicalTop = LayoutUnit::max();
@@ -641,12 +701,12 @@ void RenderBlockFlow::clearFloats()
const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
FloatingObjectSetIterator end = floatingObjectSet.end();
for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
- FloatingObject* f = *it;
- FloatingObject* oldFloatingObject = floatMap.get(f->renderer());
- LayoutUnit logicalBottom = f->logicalBottom(isHorizontalWritingMode());
+ FloatingObject* floatingObject = *it;
+ FloatingObject* oldFloatingObject = floatMap.get(floatingObject->renderer());
+ LayoutUnit logicalBottom = logicalBottomForFloat(floatingObject);
if (oldFloatingObject) {
- LayoutUnit oldLogicalBottom = oldFloatingObject->logicalBottom(isHorizontalWritingMode());
- if (f->logicalWidth(isHorizontalWritingMode()) != oldFloatingObject->logicalWidth(isHorizontalWritingMode()) || f->logicalLeft(isHorizontalWritingMode()) != oldFloatingObject->logicalLeft(isHorizontalWritingMode())) {
+ LayoutUnit oldLogicalBottom = logicalBottomForFloat(oldFloatingObject);
+ if (logicalWidthForFloat(floatingObject) != logicalWidthForFloat(oldFloatingObject) || logicalLeftForFloat(floatingObject) != logicalLeftForFloat(oldFloatingObject)) {
changeLogicalTop = 0;
changeLogicalBottom = max(changeLogicalBottom, max(logicalBottom, oldLogicalBottom));
} else {
@@ -654,15 +714,15 @@ void RenderBlockFlow::clearFloats()
changeLogicalTop = min(changeLogicalTop, min(logicalBottom, oldLogicalBottom));
changeLogicalBottom = max(changeLogicalBottom, max(logicalBottom, oldLogicalBottom));
}
- LayoutUnit logicalTop = f->logicalTop(isHorizontalWritingMode());
- LayoutUnit oldLogicalTop = oldFloatingObject->logicalTop(isHorizontalWritingMode());
+ LayoutUnit logicalTop = logicalTopForFloat(floatingObject);
+ LayoutUnit oldLogicalTop = logicalTopForFloat(oldFloatingObject);
if (logicalTop != oldLogicalTop) {
changeLogicalTop = min(changeLogicalTop, min(logicalTop, oldLogicalTop));
changeLogicalBottom = max(changeLogicalBottom, max(logicalTop, oldLogicalTop));
}
}
- floatMap.remove(f->renderer());
+ floatMap.remove(floatingObject->renderer());
if (oldFloatingObject->originatingLine() && !selfNeedsLayout()) {
ASSERT(oldFloatingObject->originatingLine()->renderer() == this);
oldFloatingObject->originatingLine()->markDirty();
@@ -680,7 +740,7 @@ void RenderBlockFlow::clearFloats()
FloatingObject* floatingObject = (*it).value;
if (!floatingObject->isDescendant()) {
changeLogicalTop = 0;
- changeLogicalBottom = max(changeLogicalBottom, floatingObject->logicalBottom(isHorizontalWritingMode()));
+ changeLogicalBottom = max(changeLogicalBottom, logicalBottomForFloat(floatingObject));
}
}
deleteAllValues(floatMap);
@@ -732,6 +792,8 @@ void RenderBlockFlow::layoutBlockChildren(bool relayoutChildren, LayoutUnit& max
RenderBox* child = next;
next = child->nextSiblingBox();
+ LayoutRectRecorder recorder(*child);
+
if (childToExclude == child)
continue; // Skip this child, since it will be positioned by the specialized subclass (fieldsets and ruby runs).
@@ -923,6 +985,17 @@ LayoutUnit RenderBlockFlow::collapseMargins(RenderBox* child, MarginInfo& margin
LayoutUnit beforeCollapseLogicalTop = logicalHeight();
LayoutUnit logicalTop = beforeCollapseLogicalTop;
+
+ LayoutUnit clearanceForSelfCollapsingBlock;
+ RenderObject* prev = child->previousSibling();
+ // If the child's previous sibling is a self-collapsing block that cleared a float then its top border edge has been set at the bottom border edge
+ // of the float. Since we want to collapse the child's top margin with the self-collapsing block's top and bottom margins we need to adjust our parent's height to match the
+ // margin top of the self-collapsing block. If the resulting collapsed margin leaves the child still intruding into the float then we will want to clear it.
+ if (!marginInfo.canCollapseWithMarginBefore() && prev && prev->isRenderBlockFlow() && toRenderBlockFlow(prev)->isSelfCollapsingBlock()) {
+ clearanceForSelfCollapsingBlock = toRenderBlockFlow(prev)->marginOffsetForSelfCollapsingBlock();
+ setLogicalHeight(logicalHeight() - clearanceForSelfCollapsingBlock);
+ }
+
if (childIsSelfCollapsing) {
// For a self collapsing block both the before and after margins get discarded. The block doesn't contribute anything to the height of the block.
// Also, the child's top position equals the logical height of the container.
@@ -988,18 +1061,23 @@ LayoutUnit RenderBlockFlow::collapseMargins(RenderBox* child, MarginInfo& margin
setLogicalHeight(logicalHeight() + (logicalTop - oldLogicalTop));
}
- // If we have collapsed into a previous sibling and so reduced the height of the parent, ensure any floats that now
- // overhang from the previous sibling are added to our parent. If the child's previous sibling itself is a float the child will avoid
- // or clear it anyway, so don't worry about any floating children it may contain.
- LayoutUnit oldLogicalHeight = logicalHeight();
- setLogicalHeight(logicalTop);
- RenderObject* prev = child->previousSibling();
if (prev && prev->isRenderBlockFlow() && !prev->isFloatingOrOutOfFlowPositioned()) {
+ // If |child| is a self-collapsing block it may have collapsed into a previous sibling and although it hasn't reduced the height of the parent yet
+ // any floats from the parent will now overhang.
RenderBlockFlow* blockFlow = toRenderBlockFlow(prev);
+ LayoutUnit oldLogicalHeight = logicalHeight();
+ setLogicalHeight(logicalTop);
if (blockFlow->containsFloats() && !blockFlow->avoidsFloats() && (blockFlow->logicalTop() + blockFlow->lowestFloatLogicalBottom()) > logicalTop)
addOverhangingFloats(blockFlow, false);
+ setLogicalHeight(oldLogicalHeight);
+
+ // If |child|'s previous sibling is a self-collapsing block that cleared a float and margin collapsing resulted in |child| moving up
+ // into the margin area of the self-collapsing block then the float it clears is now intruding into |child|. Layout again so that we can look for
+ // floats in the parent that overhang |child|'s new logical top.
+ bool logicalTopIntrudesIntoFloat = clearanceForSelfCollapsingBlock > 0 && logicalTop < beforeCollapseLogicalTop;
+ if (logicalTopIntrudesIntoFloat && containsFloats() && !child->avoidsFloats() && lowestFloatLogicalBottom() > logicalTop)
+ child->setNeedsLayout();
}
- setLogicalHeight(oldLogicalHeight);
return logicalTop;
}
@@ -1041,8 +1119,8 @@ LayoutUnit RenderBlockFlow::clearFloatsIfNeeded(RenderBox* child, MarginInfo& ma
// margins with following siblings. Reset the current margins to represent
// the self-collapsing block's margins only.
// If DISCARD is specified for -webkit-margin-collapse, reset the margin values.
+ RenderBlockFlow::MarginValues childMargins = marginValuesForChild(child);
if (!childDiscardMargin) {
- RenderBlockFlow::MarginValues childMargins = marginValuesForChild(child);
marginInfo.setPositiveMargin(max(childMargins.positiveMarginBefore(), childMargins.positiveMarginAfter()));
marginInfo.setNegativeMargin(max(childMargins.negativeMarginBefore(), childMargins.negativeMarginAfter()));
} else {
@@ -1063,12 +1141,14 @@ LayoutUnit RenderBlockFlow::clearFloatsIfNeeded(RenderBox* child, MarginInfo& ma
if (wouldCollapseMarginsWithParent)
marginInfo.setCanCollapseMarginAfterWithChildren(false);
- // CSS2.1: "the amount of clearance is set so that clearance + margin-top = [height of float], i.e., clearance = [height of float] - margin-top"
- // Move the top of the child box to the bottom of the float ignoring the child's top margin.
- LayoutUnit collapsedMargin = collapsedMarginBeforeForChild(child);
- setLogicalHeight(child->logicalTop() - collapsedMargin);
- // A negative collapsed margin-top value cancels itself out as it has already been factored into |yPos| above.
- heightIncrease -= max(LayoutUnit(), collapsedMargin);
+ // For now set the border-top of |child| flush with the bottom border-edge of the float so it can layout any floating or positioned children of
+ // its own at the correct vertical position. If subsequent siblings attempt to collapse with |child|'s margins in |collapseMargins| we will
+ // adjust the height of the parent to |child|'s margin top (which if it is positive sits up 'inside' the float it's clearing) so that all three
+ // margins can collapse at the correct vertical position.
+ // Per CSS2.1 we need to ensure that any negative margin-top clears |child| beyond the bottom border-edge of the float so that the top border edge of the child
+ // (i.e. its clearance) is at a position that satisfies the equation: "the amount of clearance is set so that clearance + margin-top = [height of float],
+ // i.e., clearance = [height of float] - margin-top".
+ setLogicalHeight(child->logicalTop() + childMargins.negativeMarginBefore());
} else {
// Increase our height by the amount we had to clear.
setLogicalHeight(logicalHeight() + heightIncrease);
@@ -1087,13 +1167,7 @@ LayoutUnit RenderBlockFlow::clearFloatsIfNeeded(RenderBox* child, MarginInfo& ma
setMustDiscardMarginBefore(style()->marginBeforeCollapse() == MDISCARD);
}
- LayoutUnit logicalTop = yPos + heightIncrease;
- // After margin collapsing, one of our floats may now intrude into the child. If the child doesn't contain floats of its own it
- // won't get picked up for relayout even though the logical top estimate was wrong - so add the newly intruding float now.
- if (containsFloats() && child->isRenderBlock() && !toRenderBlock(child)->containsFloats() && !child->avoidsFloats() && lowestFloatLogicalBottom() > logicalTop)
- toRenderBlock(child)->addIntrudingFloats(this, logicalLeftOffsetForContent(), logicalTop);
-
- return logicalTop;
+ return yPos + heightIncrease;
}
void RenderBlockFlow::setCollapsedBottomMargin(const MarginInfo& marginInfo)
@@ -1229,6 +1303,15 @@ LayoutUnit RenderBlockFlow::estimateLogicalTopPosition(RenderBox* child, const M
return logicalTopEstimate;
}
+LayoutUnit RenderBlockFlow::marginOffsetForSelfCollapsingBlock()
+{
+ ASSERT(isSelfCollapsingBlock());
+ RenderBlockFlow* parentBlock = toRenderBlockFlow(parent());
+ if (parentBlock && style()->clear() && parentBlock->getClearDelta(this, logicalHeight()))
+ return marginValuesForChild(this).positiveMarginBefore();
+ return LayoutUnit();
+}
+
void RenderBlockFlow::adjustFloatingBlock(const MarginInfo& marginInfo)
{
// The float should be positioned taking into account the bottom margin
@@ -1254,6 +1337,13 @@ void RenderBlockFlow::handleAfterSideOfBlock(LayoutUnit beforeSide, LayoutUnit a
{
marginInfo.setAtAfterSideOfBlock(true);
+ // If our last child was a self-collapsing block with clearance then our logical height is flush with the
+ // bottom edge of the float that the child clears. The correct vertical position for the margin-collapsing we want
+ // to perform now is at the child's margin-top - so adjust our height to that position.
+ RenderObject* child = lastChild();
+ if (child && child->isRenderBlockFlow() && toRenderBlockFlow(child)->isSelfCollapsingBlock())
+ setLogicalHeight(logicalHeight() - toRenderBlockFlow(child)->marginOffsetForSelfCollapsingBlock());
+
// If we can't collapse with children then go ahead and add in the bottom margin.
if (!marginInfo.discardMargin() && (!marginInfo.canCollapseWithMarginAfter() && !marginInfo.canCollapseWithMarginBefore()
&& (!document().inQuirksMode() || !marginInfo.quirkContainer() || !marginInfo.hasMarginAfterQuirk())))
@@ -1434,4 +1524,1136 @@ LayoutUnit RenderBlockFlow::applyAfterBreak(RenderBox* child, LayoutUnit logical
return logicalOffset;
}
+void RenderBlockFlow::addOverflowFromFloats()
+{
+ if (!m_floatingObjects)
+ return;
+
+ const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
+ FloatingObjectSetIterator end = floatingObjectSet.end();
+ for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
+ FloatingObject* floatingObject = *it;
+ if (floatingObject->isDescendant())
+ addOverflowFromChild(floatingObject->renderer(), IntSize(xPositionForFloatIncludingMargin(floatingObject), yPositionForFloatIncludingMargin(floatingObject)));
+ }
+}
+
+void RenderBlockFlow::computeOverflow(LayoutUnit oldClientAfterEdge, bool recomputeFloats)
+{
+ RenderBlock::computeOverflow(oldClientAfterEdge, recomputeFloats);
+ if (!hasColumns() && (recomputeFloats || isRoot() || expandsToEncloseOverhangingFloats() || hasSelfPaintingLayer()))
+ addOverflowFromFloats();
+}
+
+void RenderBlockFlow::deleteLineBoxTree()
+{
+ if (containsFloats())
+ m_floatingObjects->clearLineBoxTreePointers();
+ RenderBlock::deleteLineBoxTree();
+}
+
+void RenderBlockFlow::markAllDescendantsWithFloatsForLayout(RenderBox* floatToRemove, bool inLayout)
+{
+ if (!everHadLayout() && !containsFloats())
+ return;
+
+ MarkingBehavior markParents = inLayout ? MarkOnlyThis : MarkContainingBlockChain;
+ setChildNeedsLayout(markParents);
+
+ if (floatToRemove)
+ removeFloatingObject(floatToRemove);
+
+ // Iterate over our children and mark them as needed.
+ if (!childrenInline()) {
+ for (RenderObject* child = firstChild(); child; child = child->nextSibling()) {
+ if ((!floatToRemove && child->isFloatingOrOutOfFlowPositioned()) || !child->isRenderBlock())
+ continue;
+ if (!child->isRenderBlockFlow()) {
+ RenderBlock* childBlock = toRenderBlock(child);
+ if (childBlock->shrinkToAvoidFloats() && childBlock->everHadLayout())
+ childBlock->setChildNeedsLayout(markParents);
+ continue;
+ }
+ RenderBlockFlow* childBlockFlow = toRenderBlockFlow(child);
+ if ((floatToRemove ? childBlockFlow->containsFloat(floatToRemove) : childBlockFlow->containsFloats()) || childBlockFlow->shrinkToAvoidFloats())
+ childBlockFlow->markAllDescendantsWithFloatsForLayout(floatToRemove, inLayout);
+ }
+ }
+}
+
+void RenderBlockFlow::markSiblingsWithFloatsForLayout(RenderBox* floatToRemove)
+{
+ if (!m_floatingObjects)
+ return;
+
+ const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
+ FloatingObjectSetIterator end = floatingObjectSet.end();
+
+ for (RenderObject* next = nextSibling(); next; next = next->nextSibling()) {
+ if (!next->isRenderBlockFlow() || next->isFloatingOrOutOfFlowPositioned() || toRenderBlock(next)->avoidsFloats())
+ continue;
+
+ RenderBlockFlow* nextBlock = toRenderBlockFlow(next);
+ for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
+ RenderBox* floatingBox = (*it)->renderer();
+ if (floatToRemove && floatingBox != floatToRemove)
+ continue;
+ if (nextBlock->containsFloat(floatingBox))
+ nextBlock->markAllDescendantsWithFloatsForLayout(floatingBox);
+ }
+ }
+}
+
+LayoutUnit RenderBlockFlow::getClearDelta(RenderBox* child, LayoutUnit logicalTop)
+{
+ // There is no need to compute clearance if we have no floats.
+ if (!containsFloats())
+ return 0;
+
+ // At least one float is present. We need to perform the clearance computation.
+ bool clearSet = child->style()->clear() != CNONE;
+ LayoutUnit logicalBottom = 0;
+ switch (child->style()->clear()) {
+ case CNONE:
+ break;
+ case CLEFT:
+ logicalBottom = lowestFloatLogicalBottom(FloatingObject::FloatLeft);
+ break;
+ case CRIGHT:
+ logicalBottom = lowestFloatLogicalBottom(FloatingObject::FloatRight);
+ break;
+ case CBOTH:
+ logicalBottom = lowestFloatLogicalBottom();
+ break;
+ }
+
+ // We also clear floats if we are too big to sit on the same line as a float (and wish to avoid floats by default).
+ LayoutUnit result = clearSet ? max<LayoutUnit>(0, logicalBottom - logicalTop) : LayoutUnit();
+ if (!result && child->avoidsFloats()) {
+ LayoutUnit newLogicalTop = logicalTop;
+ while (true) {
+ LayoutUnit availableLogicalWidthAtNewLogicalTopOffset = availableLogicalWidthForLine(newLogicalTop, false, logicalHeightForChild(child));
+ if (availableLogicalWidthAtNewLogicalTopOffset == availableLogicalWidthForContent(newLogicalTop))
+ return newLogicalTop - logicalTop;
+
+ RenderRegion* region = regionAtBlockOffset(logicalTopForChild(child));
+ LayoutRect borderBox = child->borderBoxRectInRegion(region, DoNotCacheRenderBoxRegionInfo);
+ LayoutUnit childLogicalWidthAtOldLogicalTopOffset = isHorizontalWritingMode() ? borderBox.width() : borderBox.height();
+
+ // FIXME: None of this is right for perpendicular writing-mode children.
+ LayoutUnit childOldLogicalWidth = child->logicalWidth();
+ LayoutUnit childOldMarginLeft = child->marginLeft();
+ LayoutUnit childOldMarginRight = child->marginRight();
+ LayoutUnit childOldLogicalTop = child->logicalTop();
+
+ child->setLogicalTop(newLogicalTop);
+ child->updateLogicalWidth();
+ region = regionAtBlockOffset(logicalTopForChild(child));
+ borderBox = child->borderBoxRectInRegion(region, DoNotCacheRenderBoxRegionInfo);
+ LayoutUnit childLogicalWidthAtNewLogicalTopOffset = isHorizontalWritingMode() ? borderBox.width() : borderBox.height();
+
+ child->setLogicalTop(childOldLogicalTop);
+ child->setLogicalWidth(childOldLogicalWidth);
+ child->setMarginLeft(childOldMarginLeft);
+ child->setMarginRight(childOldMarginRight);
+
+ if (childLogicalWidthAtNewLogicalTopOffset <= availableLogicalWidthAtNewLogicalTopOffset) {
+ // Even though we may not be moving, if the logical width did shrink because of the presence of new floats, then
+ // we need to force a relayout as though we shifted. This happens because of the dynamic addition of overhanging floats
+ // from previous siblings when negative margins exist on a child (see the addOverhangingFloats call at the end of collapseMargins).
+ if (childLogicalWidthAtOldLogicalTopOffset != childLogicalWidthAtNewLogicalTopOffset)
+ child->setChildNeedsLayout(MarkOnlyThis);
+ return newLogicalTop - logicalTop;
+ }
+
+ newLogicalTop = nextFloatLogicalBottomBelow(newLogicalTop);
+ ASSERT(newLogicalTop >= logicalTop);
+ if (newLogicalTop < logicalTop)
+ break;
+ }
+ ASSERT_NOT_REACHED();
+ }
+ return result;
+}
+
+void RenderBlockFlow::createFloatingObjects()
+{
+ m_floatingObjects = adoptPtr(new FloatingObjects(this, isHorizontalWritingMode()));
+}
+
+void RenderBlockFlow::styleWillChange(StyleDifference diff, const RenderStyle* newStyle)
+{
+ RenderStyle* oldStyle = style();
+ s_canPropagateFloatIntoSibling = oldStyle ? !isFloatingOrOutOfFlowPositioned() && !avoidsFloats() : false;
+ if (oldStyle && parent() && diff == StyleDifferenceLayout && oldStyle->position() != newStyle->position()
+ && containsFloats() && !isFloating() && !isOutOfFlowPositioned() && newStyle->hasOutOfFlowPosition())
+ markAllDescendantsWithFloatsForLayout();
+
+ RenderBlock::styleWillChange(diff, newStyle);
+}
+
+void RenderBlockFlow::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
+{
+ RenderBlock::styleDidChange(diff, oldStyle);
+
+ // After our style changed, if we lose our ability to propagate floats into next sibling
+ // blocks, then we need to find the top most parent containing that overhanging float and
+ // then mark its descendants with floats for layout and clear all floats from its next
+ // sibling blocks that exist in our floating objects list. See bug 56299 and 62875.
+ bool canPropagateFloatIntoSibling = !isFloatingOrOutOfFlowPositioned() && !avoidsFloats();
+ if (diff == StyleDifferenceLayout && s_canPropagateFloatIntoSibling && !canPropagateFloatIntoSibling && hasOverhangingFloats()) {
+ RenderBlockFlow* parentBlockFlow = this;
+ const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
+ FloatingObjectSetIterator end = floatingObjectSet.end();
+
+ for (RenderObject* curr = parent(); curr && !curr->isRenderView(); curr = curr->parent()) {
+ if (curr->isRenderBlockFlow()) {
+ RenderBlockFlow* currBlock = toRenderBlockFlow(curr);
+
+ if (currBlock->hasOverhangingFloats()) {
+ for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
+ RenderBox* renderer = (*it)->renderer();
+ if (currBlock->hasOverhangingFloat(renderer)) {
+ parentBlockFlow = currBlock;
+ break;
+ }
+ }
+ }
+ }
+ }
+
+ parentBlockFlow->markAllDescendantsWithFloatsForLayout();
+ parentBlockFlow->markSiblingsWithFloatsForLayout();
+ }
+
+ if (renderNamedFlowFragment())
+ renderNamedFlowFragment()->setStyleForNamedFlowFragment(style());
+}
+
+void RenderBlockFlow::updateStaticInlinePositionForChild(RenderBox* child, LayoutUnit logicalTop)
+{
+ if (child->style()->isOriginalDisplayInlineType())
+ setStaticInlinePositionForChild(child, logicalTop, startAlignedOffsetForLine(logicalTop, false));
+ else
+ setStaticInlinePositionForChild(child, logicalTop, startOffsetForContent(logicalTop));
+}
+
+void RenderBlockFlow::setStaticInlinePositionForChild(RenderBox* child, LayoutUnit blockOffset, LayoutUnit inlinePosition)
+{
+ if (flowThreadContainingBlock()) {
+ // Shift the inline position to exclude the region offset.
+ inlinePosition += startOffsetForContent() - startOffsetForContent(blockOffset);
+ }
+ child->layer()->setStaticInlinePosition(inlinePosition);
+}
+
+void RenderBlockFlow::moveAllChildrenIncludingFloatsTo(RenderBlock* toBlock, bool fullRemoveInsert)
+{
+ RenderBlockFlow* toBlockFlow = toRenderBlockFlow(toBlock);
+ moveAllChildrenTo(toBlockFlow, fullRemoveInsert);
+
+ // When a portion of the render tree is being detached, anonymous blocks
+ // will be combined as their children are deleted. In this process, the
+ // anonymous block later in the tree is merged into the one preceeding it.
+ // It can happen that the later block (this) contains floats that the
+ // previous block (toBlockFlow) did not contain, and thus are not in the
+ // floating objects list for toBlockFlow. This can result in toBlockFlow containing
+ // floats that are not in it's floating objects list, but are in the
+ // floating objects lists of siblings and parents. This can cause problems
+ // when the float itself is deleted, since the deletion code assumes that
+ // if a float is not in it's containing block's floating objects list, it
+ // isn't in any floating objects list. In order to preserve this condition
+ // (removing it has serious performance implications), we need to copy the
+ // floating objects from the old block (this) to the new block (toBlockFlow).
+ // The float's metrics will likely all be wrong, but since toBlockFlow is
+ // already marked for layout, this will get fixed before anything gets
+ // displayed.
+ // See bug https://code.google.com/p/chromium/issues/detail?id=230907
+ if (m_floatingObjects) {
+ if (!toBlockFlow->m_floatingObjects)
+ toBlockFlow->createFloatingObjects();
+
+ const FloatingObjectSet& fromFloatingObjectSet = m_floatingObjects->set();
+ FloatingObjectSetIterator end = fromFloatingObjectSet.end();
+
+ for (FloatingObjectSetIterator it = fromFloatingObjectSet.begin(); it != end; ++it) {
+ FloatingObject* floatingObject = *it;
+
+ // Don't insert the object again if it's already in the list
+ if (toBlockFlow->containsFloat(floatingObject->renderer()))
+ continue;
+
+ toBlockFlow->m_floatingObjects->add(floatingObject->unsafeClone());
+ }
+ }
+
+}
+
+void RenderBlockFlow::repaintOverhangingFloats(bool paintAllDescendants)
+{
+ // Repaint any overhanging floats (if we know we're the one to paint them).
+ // Otherwise, bail out.
+ if (!hasOverhangingFloats())
+ return;
+
+ // FIXME: Avoid disabling LayoutState. At the very least, don't disable it for floats originating
+ // in this block. Better yet would be to push extra state for the containers of other floats.
+ LayoutStateDisabler layoutStateDisabler(view());
+ const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
+ FloatingObjectSetIterator end = floatingObjectSet.end();
+ for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
+ FloatingObject* floatingObject = *it;
+ // Only repaint the object if it is overhanging, is not in its own layer, and
+ // is our responsibility to paint (m_shouldPaint is set). When paintAllDescendants is true, the latter
+ // condition is replaced with being a descendant of us.
+ if (logicalBottomForFloat(floatingObject) > logicalHeight()
+ && !floatingObject->renderer()->hasSelfPaintingLayer()
+ && (floatingObject->shouldPaint() || (paintAllDescendants && floatingObject->renderer()->isDescendantOf(this)))) {
+
+ RenderBox* floatingRenderer = floatingObject->renderer();
+ LayoutRectRecorder recorder(*floatingRenderer);
+ if (RuntimeEnabledFeatures::repaintAfterLayoutEnabled())
+ floatingRenderer->setShouldDoFullRepaintAfterLayout(true);
+ else
+ floatingRenderer->repaint();
+
+ floatingRenderer->repaintOverhangingFloats(false);
+ }
+ }
+}
+
+void RenderBlockFlow::repaintOverflow()
+{
+ // FIXME: We could tighten up the left and right invalidation points if we let layoutInlineChildren fill them in based off the particular lines
+ // it had to lay out. We wouldn't need the hasOverflowClip() hack in that case either.
+ LayoutUnit repaintLogicalLeft = logicalLeftVisualOverflow();
+ LayoutUnit repaintLogicalRight = logicalRightVisualOverflow();
+ if (hasOverflowClip()) {
+ // If we have clipped overflow, we should use layout overflow as well, since visual overflow from lines didn't propagate to our block's overflow.
+ // Note the old code did this as well but even for overflow:visible. The addition of hasOverflowClip() at least tightens up the hack a bit.
+ // layoutInlineChildren should be patched to compute the entire repaint rect.
+ repaintLogicalLeft = min(repaintLogicalLeft, logicalLeftLayoutOverflow());
+ repaintLogicalRight = max(repaintLogicalRight, logicalRightLayoutOverflow());
+ }
+
+ LayoutRect repaintRect;
+ if (isHorizontalWritingMode())
+ repaintRect = LayoutRect(repaintLogicalLeft, m_repaintLogicalTop, repaintLogicalRight - repaintLogicalLeft, m_repaintLogicalBottom - m_repaintLogicalTop);
+ else
+ repaintRect = LayoutRect(m_repaintLogicalTop, repaintLogicalLeft, m_repaintLogicalBottom - m_repaintLogicalTop, repaintLogicalRight - repaintLogicalLeft);
+
+ // The repaint rect may be split across columns, in which case adjustRectForColumns() will return the union.
+ adjustRectForColumns(repaintRect);
+
+ repaintRect.inflate(maximalOutlineSize(PaintPhaseOutline));
+
+ if (hasOverflowClip()) {
+ // Adjust repaint rect for scroll offset
+ repaintRect.move(-scrolledContentOffset());
+
+ // Don't allow this rect to spill out of our overflow box.
+ repaintRect.intersect(LayoutRect(LayoutPoint(), size()));
+ }
+
+ // Make sure the rect is still non-empty after intersecting for overflow above
+ if (!repaintRect.isEmpty()) {
+ repaintRectangle(repaintRect); // We need to do a partial repaint of our content.
+ if (hasReflection())
+ repaintRectangle(reflectedRect(repaintRect));
+ }
+
+ m_repaintLogicalTop = 0;
+ m_repaintLogicalBottom = 0;
+}
+
+void RenderBlockFlow::paintFloats(PaintInfo& paintInfo, const LayoutPoint& paintOffset, bool preservePhase)
+{
+ if (!m_floatingObjects)
+ return;
+
+ const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
+ FloatingObjectSetIterator end = floatingObjectSet.end();
+ for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
+ FloatingObject* floatingObject = *it;
+ // Only paint the object if our m_shouldPaint flag is set.
+ if (floatingObject->shouldPaint() && !floatingObject->renderer()->hasSelfPaintingLayer()) {
+ PaintInfo currentPaintInfo(paintInfo);
+ currentPaintInfo.phase = preservePhase ? paintInfo.phase : PaintPhaseBlockBackground;
+ // FIXME: LayoutPoint version of xPositionForFloatIncludingMargin would make this much cleaner.
+ LayoutPoint childPoint = flipFloatForWritingModeForChild(floatingObject, LayoutPoint(paintOffset.x() + xPositionForFloatIncludingMargin(floatingObject) - floatingObject->renderer()->x(), paintOffset.y() + yPositionForFloatIncludingMargin(floatingObject) - floatingObject->renderer()->y()));
+ floatingObject->renderer()->paint(currentPaintInfo, childPoint);
+ if (!preservePhase) {
+ currentPaintInfo.phase = PaintPhaseChildBlockBackgrounds;
+ floatingObject->renderer()->paint(currentPaintInfo, childPoint);
+ currentPaintInfo.phase = PaintPhaseFloat;
+ floatingObject->renderer()->paint(currentPaintInfo, childPoint);
+ currentPaintInfo.phase = PaintPhaseForeground;
+ floatingObject->renderer()->paint(currentPaintInfo, childPoint);
+ currentPaintInfo.phase = PaintPhaseOutline;
+ floatingObject->renderer()->paint(currentPaintInfo, childPoint);
+ }
+ }
+ }
+}
+
+void RenderBlockFlow::clipOutFloatingObjects(RenderBlock* rootBlock, const PaintInfo* paintInfo, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock)
+{
+ if (m_floatingObjects) {
+ const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
+ FloatingObjectSetIterator end = floatingObjectSet.end();
+ for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
+ FloatingObject* floatingObject = *it;
+ LayoutRect floatBox(offsetFromRootBlock.width() + xPositionForFloatIncludingMargin(floatingObject),
+ offsetFromRootBlock.height() + yPositionForFloatIncludingMargin(floatingObject),
+ floatingObject->renderer()->width(), floatingObject->renderer()->height());
+ rootBlock->flipForWritingMode(floatBox);
+ floatBox.move(rootBlockPhysicalPosition.x(), rootBlockPhysicalPosition.y());
+ paintInfo->context->clipOut(pixelSnappedIntRect(floatBox));
+ }
+ }
+}
+
+void RenderBlockFlow::clearFloats(EClear clear)
+{
+ positionNewFloats();
+ // set y position
+ LayoutUnit newY = 0;
+ switch (clear) {
+ case CLEFT:
+ newY = lowestFloatLogicalBottom(FloatingObject::FloatLeft);
+ break;
+ case CRIGHT:
+ newY = lowestFloatLogicalBottom(FloatingObject::FloatRight);
+ break;
+ case CBOTH:
+ newY = lowestFloatLogicalBottom();
+ default:
+ break;
+ }
+ if (height() < newY)
+ setLogicalHeight(newY);
+}
+
+bool RenderBlockFlow::containsFloat(RenderBox* renderer) const
+{
+ return m_floatingObjects && m_floatingObjects->set().contains<FloatingObjectHashTranslator>(renderer);
+}
+
+void RenderBlockFlow::removeFloatingObjects()
+{
+ if (!m_floatingObjects)
+ return;
+
+ m_floatingObjects->clear();
+}
+
+LayoutPoint RenderBlockFlow::flipFloatForWritingModeForChild(const FloatingObject* child, const LayoutPoint& point) const
+{
+ if (!style()->isFlippedBlocksWritingMode())
+ return point;
+
+ // This is similar to RenderBox::flipForWritingModeForChild. We have to subtract out our left/top offsets twice, since
+ // it's going to get added back in. We hide this complication here so that the calling code looks normal for the unflipped
+ // case.
+ if (isHorizontalWritingMode())
+ return LayoutPoint(point.x(), point.y() + height() - child->renderer()->height() - 2 * yPositionForFloatIncludingMargin(child));
+ return LayoutPoint(point.x() + width() - child->renderer()->width() - 2 * xPositionForFloatIncludingMargin(child), point.y());
+}
+
+LayoutUnit RenderBlockFlow::logicalLeftOffsetForPositioningFloat(LayoutUnit logicalTop, LayoutUnit fixedOffset, bool applyTextIndent, LayoutUnit* heightRemaining) const
+{
+ LayoutUnit offset = fixedOffset;
+ if (m_floatingObjects && m_floatingObjects->hasLeftObjects())
+ offset = m_floatingObjects->logicalLeftOffsetForPositioningFloat(fixedOffset, logicalTop, heightRemaining);
+ return adjustLogicalLeftOffsetForLine(offset, applyTextIndent);
+}
+
+LayoutUnit RenderBlockFlow::logicalRightOffsetForPositioningFloat(LayoutUnit logicalTop, LayoutUnit fixedOffset, bool applyTextIndent, LayoutUnit* heightRemaining) const
+{
+ LayoutUnit offset = fixedOffset;
+ if (m_floatingObjects && m_floatingObjects->hasRightObjects())
+ offset = m_floatingObjects->logicalRightOffsetForPositioningFloat(fixedOffset, logicalTop, heightRemaining);
+ return adjustLogicalRightOffsetForLine(offset, applyTextIndent);
+}
+
+LayoutPoint RenderBlockFlow::computeLogicalLocationForFloat(const FloatingObject* floatingObject, LayoutUnit logicalTopOffset) const
+{
+ RenderBox* childBox = floatingObject->renderer();
+ LayoutUnit logicalLeftOffset = logicalLeftOffsetForContent(logicalTopOffset); // Constant part of left offset.
+ LayoutUnit logicalRightOffset; // Constant part of right offset.
+ // FIXME Bug 102948: This only works for shape outside directly set on this block.
+ ShapeInsideInfo* shapeInsideInfo = this->layoutShapeInsideInfo();
+ // FIXME: Implement behavior for right floats.
+ if (shapeInsideInfo) {
+ LayoutSize floatLogicalSize = logicalSizeForFloat(floatingObject);
+ // floatingObject's logicalSize doesn't contain the actual height at this point, so we need to calculate it
+ floatLogicalSize.setHeight(logicalHeightForChild(childBox) + marginBeforeForChild(childBox) + marginAfterForChild(childBox));
+
+ // FIXME: If the float doesn't fit in the shape we should push it under the content box
+ logicalTopOffset = shapeInsideInfo->computeFirstFitPositionForFloat(floatLogicalSize);
+ if (logicalHeight() > logicalTopOffset)
+ logicalTopOffset = logicalHeight();
+
+ SegmentList segments = shapeInsideInfo->computeSegmentsForLine(logicalTopOffset, floatLogicalSize.height());
+ // FIXME: Add support for shapes with multiple segments.
+ if (segments.size() == 1) {
+ // The segment offsets are relative to the content box.
+ logicalRightOffset = logicalLeftOffset + segments[0].logicalRight;
+ logicalLeftOffset += segments[0].logicalLeft;
+ }
+ } else {
+ logicalRightOffset = logicalRightOffsetForContent(logicalTopOffset);
+ }
+
+ LayoutUnit floatLogicalWidth = min(logicalWidthForFloat(floatingObject), logicalRightOffset - logicalLeftOffset); // The width we look for.
+
+ LayoutUnit floatLogicalLeft;
+
+ bool insideFlowThread = flowThreadContainingBlock();
+
+ if (childBox->style()->floating() == LeftFloat) {
+ LayoutUnit heightRemainingLeft = 1;
+ LayoutUnit heightRemainingRight = 1;
+ floatLogicalLeft = logicalLeftOffsetForPositioningFloat(logicalTopOffset, logicalLeftOffset, false, &heightRemainingLeft);
+ while (logicalRightOffsetForPositioningFloat(logicalTopOffset, logicalRightOffset, false, &heightRemainingRight) - floatLogicalLeft < floatLogicalWidth) {
+ logicalTopOffset += min(heightRemainingLeft, heightRemainingRight);
+ floatLogicalLeft = logicalLeftOffsetForPositioningFloat(logicalTopOffset, logicalLeftOffset, false, &heightRemainingLeft);
+ if (insideFlowThread) {
+ // Have to re-evaluate all of our offsets, since they may have changed.
+ logicalRightOffset = logicalRightOffsetForContent(logicalTopOffset); // Constant part of right offset.
+ logicalLeftOffset = logicalLeftOffsetForContent(logicalTopOffset); // Constant part of left offset.
+ floatLogicalWidth = min(logicalWidthForFloat(floatingObject), logicalRightOffset - logicalLeftOffset);
+ }
+ }
+ floatLogicalLeft = max(logicalLeftOffset - borderAndPaddingLogicalLeft(), floatLogicalLeft);
+ } else {
+ LayoutUnit heightRemainingLeft = 1;
+ LayoutUnit heightRemainingRight = 1;
+ floatLogicalLeft = logicalRightOffsetForPositioningFloat(logicalTopOffset, logicalRightOffset, false, &heightRemainingRight);
+ while (floatLogicalLeft - logicalLeftOffsetForPositioningFloat(logicalTopOffset, logicalLeftOffset, false, &heightRemainingLeft) < floatLogicalWidth) {
+ logicalTopOffset += min(heightRemainingLeft, heightRemainingRight);
+ floatLogicalLeft = logicalRightOffsetForPositioningFloat(logicalTopOffset, logicalRightOffset, false, &heightRemainingRight);
+ if (insideFlowThread) {
+ // Have to re-evaluate all of our offsets, since they may have changed.
+ logicalRightOffset = logicalRightOffsetForContent(logicalTopOffset); // Constant part of right offset.
+ logicalLeftOffset = logicalLeftOffsetForContent(logicalTopOffset); // Constant part of left offset.
+ floatLogicalWidth = min(logicalWidthForFloat(floatingObject), logicalRightOffset - logicalLeftOffset);
+ }
+ }
+ // Use the original width of the float here, since the local variable
+ // |floatLogicalWidth| was capped to the available line width. See
+ // fast/block/float/clamped-right-float.html.
+ floatLogicalLeft -= logicalWidthForFloat(floatingObject);
+ }
+
+ return LayoutPoint(floatLogicalLeft, logicalTopOffset);
+}
+
+FloatingObject* RenderBlockFlow::insertFloatingObject(RenderBox* floatBox)
+{
+ ASSERT(floatBox->isFloating());
+
+ // Create the list of special objects if we don't aleady have one
+ if (!m_floatingObjects) {
+ createFloatingObjects();
+ } else {
+ // Don't insert the object again if it's already in the list
+ const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
+ FloatingObjectSetIterator it = floatingObjectSet.find<FloatingObjectHashTranslator>(floatBox);
+ if (it != floatingObjectSet.end())
+ return *it;
+ }
+
+ // Create the special object entry & append it to the list
+
+ OwnPtr<FloatingObject> newObj = FloatingObject::create(floatBox);
+
+ // Our location is irrelevant if we're unsplittable or no pagination is in effect.
+ // Just go ahead and lay out the float.
+ bool isChildRenderBlock = floatBox->isRenderBlock();
+ if (isChildRenderBlock && !floatBox->needsLayout() && view()->layoutState()->pageLogicalHeightChanged())
+ floatBox->setChildNeedsLayout(MarkOnlyThis);
+
+ bool needsBlockDirectionLocationSetBeforeLayout = isChildRenderBlock && view()->layoutState()->needsBlockDirectionLocationSetBeforeLayout();
+ if (!needsBlockDirectionLocationSetBeforeLayout || isWritingModeRoot()) { // We are unsplittable if we're a block flow root.
+ floatBox->layoutIfNeeded();
+ } else {
+ floatBox->updateLogicalWidth();
+ floatBox->computeAndSetBlockDirectionMargins(this);
+ }
+
+ setLogicalWidthForFloat(newObj.get(), logicalWidthForChild(floatBox) + marginStartForChild(floatBox) + marginEndForChild(floatBox));
+
+ return m_floatingObjects->add(newObj.release());
+}
+
+void RenderBlockFlow::removeFloatingObject(RenderBox* floatBox)
+{
+ if (m_floatingObjects) {
+ const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
+ FloatingObjectSetIterator it = floatingObjectSet.find<FloatingObjectHashTranslator>(floatBox);
+ if (it != floatingObjectSet.end()) {
+ FloatingObject* floatingObject = *it;
+ if (childrenInline()) {
+ LayoutUnit logicalTop = logicalTopForFloat(floatingObject);
+ LayoutUnit logicalBottom = logicalBottomForFloat(floatingObject);
+
+ // Fix for https://bugs.webkit.org/show_bug.cgi?id=54995.
+ if (logicalBottom < 0 || logicalBottom < logicalTop || logicalTop == LayoutUnit::max()) {
+ logicalBottom = LayoutUnit::max();
+ } else {
+ // Special-case zero- and less-than-zero-height floats: those don't touch
+ // the line that they're on, but it still needs to be dirtied. This is
+ // accomplished by pretending they have a height of 1.
+ logicalBottom = max(logicalBottom, logicalTop + 1);
+ }
+ if (floatingObject->originatingLine()) {
+ if (!selfNeedsLayout()) {
+ ASSERT(floatingObject->originatingLine()->renderer() == this);
+ floatingObject->originatingLine()->markDirty();
+ }
+#if !ASSERT_DISABLED
+ floatingObject->setOriginatingLine(0);
+#endif
+ }
+ markLinesDirtyInBlockRange(0, logicalBottom);
+ }
+ m_floatingObjects->remove(floatingObject);
+ }
+ }
+}
+
+void RenderBlockFlow::removeFloatingObjectsBelow(FloatingObject* lastFloat, int logicalOffset)
+{
+ if (!containsFloats())
+ return;
+
+ const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
+ FloatingObject* curr = floatingObjectSet.last();
+ while (curr != lastFloat && (!curr->isPlaced() || logicalTopForFloat(curr) >= logicalOffset)) {
+ m_floatingObjects->remove(curr);
+ if (floatingObjectSet.isEmpty())
+ break;
+ curr = floatingObjectSet.last();
+ }
+}
+
+bool RenderBlockFlow::positionNewFloats()
+{
+ if (!m_floatingObjects)
+ return false;
+
+ const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
+ if (floatingObjectSet.isEmpty())
+ return false;
+
+ // If all floats have already been positioned, then we have no work to do.
+ if (floatingObjectSet.last()->isPlaced())
+ return false;
+
+ // Move backwards through our floating object list until we find a float that has
+ // already been positioned. Then we'll be able to move forward, positioning all of
+ // the new floats that need it.
+ FloatingObjectSetIterator it = floatingObjectSet.end();
+ --it; // Go to last item.
+ FloatingObjectSetIterator begin = floatingObjectSet.begin();
+ FloatingObject* lastPlacedFloatingObject = 0;
+ while (it != begin) {
+ --it;
+ if ((*it)->isPlaced()) {
+ lastPlacedFloatingObject = *it;
+ ++it;
+ break;
+ }
+ }
+
+ LayoutUnit logicalTop = logicalHeight();
+
+ // The float cannot start above the top position of the last positioned float.
+ if (lastPlacedFloatingObject)
+ logicalTop = max(logicalTopForFloat(lastPlacedFloatingObject), logicalTop);
+
+ FloatingObjectSetIterator end = floatingObjectSet.end();
+ // Now walk through the set of unpositioned floats and place them.
+ for (; it != end; ++it) {
+ FloatingObject* floatingObject = *it;
+ // The containing block is responsible for positioning floats, so if we have floats in our
+ // list that come from somewhere else, do not attempt to position them.
+ if (floatingObject->renderer()->containingBlock() != this)
+ continue;
+
+ RenderBox* childBox = floatingObject->renderer();
+ LayoutUnit childLogicalLeftMargin = style()->isLeftToRightDirection() ? marginStartForChild(childBox) : marginEndForChild(childBox);
+
+ LayoutRect oldRect = childBox->frameRect();
+
+ if (childBox->style()->clear() & CLEFT)
+ logicalTop = max(lowestFloatLogicalBottom(FloatingObject::FloatLeft), logicalTop);
+ if (childBox->style()->clear() & CRIGHT)
+ logicalTop = max(lowestFloatLogicalBottom(FloatingObject::FloatRight), logicalTop);
+
+ LayoutPoint floatLogicalLocation = computeLogicalLocationForFloat(floatingObject, logicalTop);
+
+ setLogicalLeftForFloat(floatingObject, floatLogicalLocation.x());
+
+ setLogicalLeftForChild(childBox, floatLogicalLocation.x() + childLogicalLeftMargin);
+ setLogicalTopForChild(childBox, floatLogicalLocation.y() + marginBeforeForChild(childBox));
+
+ SubtreeLayoutScope layoutScope(childBox);
+ LayoutState* layoutState = view()->layoutState();
+ bool isPaginated = layoutState->isPaginated();
+ if (isPaginated && !childBox->needsLayout())
+ childBox->markForPaginationRelayoutIfNeeded(layoutScope);
+
+ childBox->layoutIfNeeded();
+
+ if (isPaginated) {
+ // If we are unsplittable and don't fit, then we need to move down.
+ // We include our margins as part of the unsplittable area.
+ LayoutUnit newLogicalTop = adjustForUnsplittableChild(childBox, floatLogicalLocation.y(), true);
+
+ // See if we have a pagination strut that is making us move down further.
+ // Note that an unsplittable child can't also have a pagination strut, so this is
+ // exclusive with the case above.
+ RenderBlock* childBlock = childBox->isRenderBlock() ? toRenderBlock(childBox) : 0;
+ if (childBlock && childBlock->paginationStrut()) {
+ newLogicalTop += childBlock->paginationStrut();
+ childBlock->setPaginationStrut(0);
+ }
+
+ if (newLogicalTop != floatLogicalLocation.y()) {
+ floatingObject->setPaginationStrut(newLogicalTop - floatLogicalLocation.y());
+
+ floatLogicalLocation = computeLogicalLocationForFloat(floatingObject, newLogicalTop);
+ setLogicalLeftForFloat(floatingObject, floatLogicalLocation.x());
+
+ setLogicalLeftForChild(childBox, floatLogicalLocation.x() + childLogicalLeftMargin);
+ setLogicalTopForChild(childBox, floatLogicalLocation.y() + marginBeforeForChild(childBox));
+
+ if (childBlock)
+ childBlock->setChildNeedsLayout(MarkOnlyThis);
+ childBox->layoutIfNeeded();
+ }
+ }
+
+ setLogicalTopForFloat(floatingObject, floatLogicalLocation.y());
+
+ setLogicalHeightForFloat(floatingObject, logicalHeightForChild(childBox) + marginBeforeForChild(childBox) + marginAfterForChild(childBox));
+
+ m_floatingObjects->addPlacedObject(floatingObject);
+
+ if (ShapeOutsideInfo* shapeOutside = childBox->shapeOutsideInfo())
+ shapeOutside->setShapeSize(logicalWidthForChild(childBox), logicalHeightForChild(childBox));
+
+ // If the child moved, we have to repaint it.
+ if (childBox->checkForRepaintDuringLayout())
+ childBox->repaintDuringLayoutIfMoved(oldRect);
+ }
+ return true;
+}
+
+bool RenderBlockFlow::hasOverhangingFloat(RenderBox* renderer)
+{
+ if (!m_floatingObjects || hasColumns() || !parent())
+ return false;
+
+ const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
+ FloatingObjectSetIterator it = floatingObjectSet.find<FloatingObjectHashTranslator>(renderer);
+ if (it == floatingObjectSet.end())
+ return false;
+
+ return logicalBottomForFloat(*it) > logicalHeight();
+}
+
+void RenderBlockFlow::addIntrudingFloats(RenderBlockFlow* prev, LayoutUnit logicalLeftOffset, LayoutUnit logicalTopOffset)
+{
+ ASSERT(!avoidsFloats());
+
+ // If the parent or previous sibling doesn't have any floats to add, don't bother.
+ if (!prev->m_floatingObjects)
+ return;
+
+ logicalLeftOffset += marginLogicalLeft();
+
+ const FloatingObjectSet& prevSet = prev->m_floatingObjects->set();
+ FloatingObjectSetIterator prevEnd = prevSet.end();
+ for (FloatingObjectSetIterator prevIt = prevSet.begin(); prevIt != prevEnd; ++prevIt) {
+ FloatingObject* floatingObject = *prevIt;
+ if (logicalBottomForFloat(floatingObject) > logicalTopOffset) {
+ if (!m_floatingObjects || !m_floatingObjects->set().contains(floatingObject)) {
+ // We create the floating object list lazily.
+ if (!m_floatingObjects)
+ createFloatingObjects();
+
+ // Applying the child's margin makes no sense in the case where the child was passed in.
+ // since this margin was added already through the modification of the |logicalLeftOffset| variable
+ // above. |logicalLeftOffset| will equal the margin in this case, so it's already been taken
+ // into account. Only apply this code if prev is the parent, since otherwise the left margin
+ // will get applied twice.
+ LayoutSize offset = isHorizontalWritingMode()
+ ? LayoutSize(logicalLeftOffset - (prev != parent() ? prev->marginLeft() : LayoutUnit()), logicalTopOffset)
+ : LayoutSize(logicalTopOffset, logicalLeftOffset - (prev != parent() ? prev->marginTop() : LayoutUnit()));
+
+ m_floatingObjects->add(floatingObject->copyToNewContainer(offset));
+ }
+ }
+ }
+}
+
+LayoutUnit RenderBlockFlow::addOverhangingFloats(RenderBlockFlow* child, bool makeChildPaintOtherFloats)
+{
+ // Prevent floats from being added to the canvas by the root element, e.g., <html>.
+ if (child->hasOverflowClip() || !child->containsFloats() || child->isRoot() || child->hasColumns() || child->isWritingModeRoot())
+ return 0;
+
+ LayoutUnit childLogicalTop = child->logicalTop();
+ LayoutUnit childLogicalLeft = child->logicalLeft();
+ LayoutUnit lowestFloatLogicalBottom = 0;
+
+ // Floats that will remain the child's responsibility to paint should factor into its
+ // overflow.
+ FloatingObjectSetIterator childEnd = child->m_floatingObjects->set().end();
+ for (FloatingObjectSetIterator childIt = child->m_floatingObjects->set().begin(); childIt != childEnd; ++childIt) {
+ FloatingObject* floatingObject = *childIt;
+ LayoutUnit logicalBottomForFloat = min(this->logicalBottomForFloat(floatingObject), LayoutUnit::max() - childLogicalTop);
+ LayoutUnit logicalBottom = childLogicalTop + logicalBottomForFloat;
+ lowestFloatLogicalBottom = max(lowestFloatLogicalBottom, logicalBottom);
+
+ if (logicalBottom > logicalHeight()) {
+ // If the object is not in the list, we add it now.
+ if (!containsFloat(floatingObject->renderer())) {
+ LayoutSize offset = isHorizontalWritingMode() ? LayoutSize(-childLogicalLeft, -childLogicalTop) : LayoutSize(-childLogicalTop, -childLogicalLeft);
+ bool shouldPaint = false;
+
+ // The nearest enclosing layer always paints the float (so that zindex and stacking
+ // behaves properly). We always want to propagate the desire to paint the float as
+ // far out as we can, to the outermost block that overlaps the float, stopping only
+ // if we hit a self-painting layer boundary.
+ if (floatingObject->renderer()->enclosingFloatPaintingLayer() == enclosingFloatPaintingLayer()) {
+ floatingObject->setShouldPaint(false);
+ shouldPaint = true;
+ }
+ // We create the floating object list lazily.
+ if (!m_floatingObjects)
+ createFloatingObjects();
+
+ m_floatingObjects->add(floatingObject->copyToNewContainer(offset, shouldPaint, true));
+ }
+ } else {
+ if (makeChildPaintOtherFloats && !floatingObject->shouldPaint() && !floatingObject->renderer()->hasSelfPaintingLayer()
+ && floatingObject->renderer()->isDescendantOf(child) && floatingObject->renderer()->enclosingFloatPaintingLayer() == child->enclosingFloatPaintingLayer()) {
+ // The float is not overhanging from this block, so if it is a descendant of the child, the child should
+ // paint it (the other case is that it is intruding into the child), unless it has its own layer or enclosing
+ // layer.
+ // If makeChildPaintOtherFloats is false, it means that the child must already know about all the floats
+ // it should paint.
+ floatingObject->setShouldPaint(true);
+ }
+
+ // Since the float doesn't overhang, it didn't get put into our list. We need to go ahead and add its overflow in to the
+ // child now.
+ if (floatingObject->isDescendant())
+ child->addOverflowFromChild(floatingObject->renderer(), LayoutSize(xPositionForFloatIncludingMargin(floatingObject), yPositionForFloatIncludingMargin(floatingObject)));
+ }
+ }
+ return lowestFloatLogicalBottom;
+}
+
+LayoutUnit RenderBlockFlow::lowestFloatLogicalBottom(FloatingObject::Type floatType) const
+{
+ if (!m_floatingObjects)
+ return 0;
+
+ return m_floatingObjects->lowestFloatLogicalBottom(floatType);
+}
+
+LayoutUnit RenderBlockFlow::nextFloatLogicalBottomBelow(LayoutUnit logicalHeight, ShapeOutsideFloatOffsetMode offsetMode) const
+{
+ if (!m_floatingObjects)
+ return logicalHeight;
+
+ LayoutUnit logicalBottom = LayoutUnit::max();
+ const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
+ FloatingObjectSetIterator end = floatingObjectSet.end();
+ for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
+ FloatingObject* floatingObject = *it;
+ LayoutUnit floatLogicalBottom = logicalBottomForFloat(floatingObject);
+ ShapeOutsideInfo* shapeOutside = floatingObject->renderer()->shapeOutsideInfo();
+ if (shapeOutside && (offsetMode == ShapeOutsideFloatShapeOffset)) {
+ LayoutUnit shapeLogicalBottom = logicalTopForFloat(floatingObject) + marginBeforeForChild(floatingObject->renderer()) + shapeOutside->shapeLogicalBottom();
+ // Use the shapeLogicalBottom unless it extends outside of the margin box, in which case it is clipped.
+ if (shapeLogicalBottom < floatLogicalBottom)
+ floatLogicalBottom = shapeLogicalBottom;
+ }
+ if (floatLogicalBottom > logicalHeight)
+ logicalBottom = min(floatLogicalBottom, logicalBottom);
+ }
+
+ return logicalBottom == LayoutUnit::max() ? LayoutUnit() : logicalBottom;
+}
+
+bool RenderBlockFlow::hitTestFloats(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset)
+{
+ if (!m_floatingObjects)
+ return false;
+
+ LayoutPoint adjustedLocation = accumulatedOffset;
+ if (isRenderView()) {
+ adjustedLocation += toLayoutSize(toRenderView(this)->frameView()->scrollPosition());
+ }
+
+ const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
+ FloatingObjectSetIterator begin = floatingObjectSet.begin();
+ for (FloatingObjectSetIterator it = floatingObjectSet.end(); it != begin;) {
+ --it;
+ FloatingObject* floatingObject = *it;
+ if (floatingObject->shouldPaint() && !floatingObject->renderer()->hasSelfPaintingLayer()) {
+ LayoutUnit xOffset = xPositionForFloatIncludingMargin(floatingObject) - floatingObject->renderer()->x();
+ LayoutUnit yOffset = yPositionForFloatIncludingMargin(floatingObject) - floatingObject->renderer()->y();
+ LayoutPoint childPoint = flipFloatForWritingModeForChild(floatingObject, adjustedLocation + LayoutSize(xOffset, yOffset));
+ if (floatingObject->renderer()->hitTest(request, result, locationInContainer, childPoint)) {
+ updateHitTestResult(result, locationInContainer.point() - toLayoutSize(childPoint));
+ return true;
+ }
+ }
+ }
+
+ return false;
+}
+
+void RenderBlockFlow::adjustForBorderFit(LayoutUnit x, LayoutUnit& left, LayoutUnit& right) const
+{
+ RenderBlock::adjustForBorderFit(x, left, right);
+ if (m_floatingObjects && style()->visibility() == VISIBLE) {
+ const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
+ FloatingObjectSetIterator end = floatingObjectSet.end();
+ for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
+ FloatingObject* floatingObject = *it;
+ // Only examine the object if our m_shouldPaint flag is set.
+ if (floatingObject->shouldPaint()) {
+ LayoutUnit floatLeft = xPositionForFloatIncludingMargin(floatingObject) - floatingObject->renderer()->x();
+ LayoutUnit floatRight = floatLeft + floatingObject->renderer()->width();
+ left = min(left, floatLeft);
+ right = max(right, floatRight);
+ }
+ }
+ }
+}
+
+LayoutUnit RenderBlockFlow::logicalLeftFloatOffsetForLine(LayoutUnit logicalTop, LayoutUnit fixedOffset, LayoutUnit logicalHeight) const
+{
+ if (m_floatingObjects && m_floatingObjects->hasLeftObjects())
+ return m_floatingObjects->logicalLeftOffset(fixedOffset, logicalTop, logicalHeight);
+
+ return fixedOffset;
+}
+
+LayoutUnit RenderBlockFlow::logicalRightFloatOffsetForLine(LayoutUnit logicalTop, LayoutUnit fixedOffset, LayoutUnit logicalHeight) const
+{
+ if (m_floatingObjects && m_floatingObjects->hasRightObjects())
+ return m_floatingObjects->logicalRightOffset(fixedOffset, logicalTop, logicalHeight);
+
+ return fixedOffset;
+}
+
+GapRects RenderBlockFlow::inlineSelectionGaps(RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
+ LayoutUnit& lastLogicalTop, LayoutUnit& lastLogicalLeft, LayoutUnit& lastLogicalRight, const PaintInfo* paintInfo)
+{
+ GapRects result;
+
+ bool containsStart = selectionState() == SelectionStart || selectionState() == SelectionBoth;
+
+ if (!firstLineBox()) {
+ if (containsStart) {
+ // Go ahead and update our lastLogicalTop to be the bottom of the block. <hr>s or empty blocks with height can trip this
+ // case.
+ lastLogicalTop = rootBlock->blockDirectionOffset(offsetFromRootBlock) + logicalHeight();
+ lastLogicalLeft = logicalLeftSelectionOffset(rootBlock, logicalHeight());
+ lastLogicalRight = logicalRightSelectionOffset(rootBlock, logicalHeight());
+ }
+ return result;
+ }
+
+ RootInlineBox* lastSelectedLine = 0;
+ RootInlineBox* curr;
+ for (curr = firstRootBox(); curr && !curr->hasSelectedChildren(); curr = curr->nextRootBox()) { }
+
+ // Now paint the gaps for the lines.
+ for (; curr && curr->hasSelectedChildren(); curr = curr->nextRootBox()) {
+ LayoutUnit selTop = curr->selectionTopAdjustedForPrecedingBlock();
+ LayoutUnit selHeight = curr->selectionHeightAdjustedForPrecedingBlock();
+
+ if (!containsStart && !lastSelectedLine && selectionState() != SelectionStart && selectionState() != SelectionBoth) {
+ result.uniteCenter(blockSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, lastLogicalTop,
+ lastLogicalLeft, lastLogicalRight, selTop, paintInfo));
+ }
+
+ LayoutRect logicalRect(curr->logicalLeft(), selTop, curr->logicalWidth(), selTop + selHeight);
+ logicalRect.move(isHorizontalWritingMode() ? offsetFromRootBlock : offsetFromRootBlock.transposedSize());
+ LayoutRect physicalRect = rootBlock->logicalRectToPhysicalRect(rootBlockPhysicalPosition, logicalRect);
+ if (!paintInfo || (isHorizontalWritingMode() && physicalRect.y() < paintInfo->rect.maxY() && physicalRect.maxY() > paintInfo->rect.y())
+ || (!isHorizontalWritingMode() && physicalRect.x() < paintInfo->rect.maxX() && physicalRect.maxX() > paintInfo->rect.x()))
+ result.unite(curr->lineSelectionGap(rootBlock, rootBlockPhysicalPosition, offsetFromRootBlock, selTop, selHeight, paintInfo));
+
+ lastSelectedLine = curr;
+ }
+
+ if (containsStart && !lastSelectedLine) {
+ // VisibleSelection must start just after our last line.
+ lastSelectedLine = lastRootBox();
+ }
+
+ if (lastSelectedLine && selectionState() != SelectionEnd && selectionState() != SelectionBoth) {
+ // Go ahead and update our lastY to be the bottom of the last selected line.
+ lastLogicalTop = rootBlock->blockDirectionOffset(offsetFromRootBlock) + lastSelectedLine->selectionBottom();
+ lastLogicalLeft = logicalLeftSelectionOffset(rootBlock, lastSelectedLine->selectionBottom());
+ lastLogicalRight = logicalRightSelectionOffset(rootBlock, lastSelectedLine->selectionBottom());
+ }
+ return result;
+}
+
+template <typename CharacterType>
+static inline TextRun constructTextRunInternal(RenderObject* context, const Font& font, const CharacterType* characters, int length, RenderStyle* style, TextRun::ExpansionBehavior expansion)
+{
+ ASSERT(style);
+
+ TextDirection textDirection = LTR;
+ bool directionalOverride = style->rtlOrdering() == VisualOrder;
+
+ TextRun run(characters, length, 0, 0, expansion, textDirection, directionalOverride);
+ if (textRunNeedsRenderingContext(font))
+ run.setRenderingContext(SVGTextRunRenderingContext::create(context));
+
+ return run;
+}
+
+template <typename CharacterType>
+static inline TextRun constructTextRunInternal(RenderObject* context, const Font& font, const CharacterType* characters, int length, RenderStyle* style, TextRun::ExpansionBehavior expansion, TextRunFlags flags)
+{
+ ASSERT(style);
+
+ TextDirection textDirection = LTR;
+ bool directionalOverride = style->rtlOrdering() == VisualOrder;
+ if (flags != DefaultTextRunFlags) {
+ if (flags & RespectDirection)
+ textDirection = style->direction();
+ if (flags & RespectDirectionOverride)
+ directionalOverride |= isOverride(style->unicodeBidi());
+ }
+
+ TextRun run(characters, length, 0, 0, expansion, textDirection, directionalOverride);
+ if (!directionalOverride) {
+ BidiResolver<TextRunIterator, BidiCharacterRun> bidiResolver;
+ bidiResolver.setStatus(BidiStatus(run.direction(), run.directionalOverride()));
+ bidiResolver.setPositionIgnoringNestedIsolates(TextRunIterator(&run, 0));
+ bool hasStrongDirectionality;
+ TextDirection direction = bidiResolver.determineParagraphDirectionality(&hasStrongDirectionality);
+ if (hasStrongDirectionality)
+ run.setDirection(direction);
+ }
+
+ if (textRunNeedsRenderingContext(font))
+ run.setRenderingContext(SVGTextRunRenderingContext::create(context));
+
+ return run;
+}
+
+TextRun RenderBlockFlow::constructTextRun(RenderObject* context, const Font& font, const LChar* characters, int length, RenderStyle* style, TextRun::ExpansionBehavior expansion)
+{
+ return constructTextRunInternal(context, font, characters, length, style, expansion);
+}
+
+TextRun RenderBlockFlow::constructTextRun(RenderObject* context, const Font& font, const UChar* characters, int length, RenderStyle* style, TextRun::ExpansionBehavior expansion)
+{
+ return constructTextRunInternal(context, font, characters, length, style, expansion);
+}
+
+TextRun RenderBlockFlow::constructTextRun(RenderObject* context, const Font& font, const RenderText* text, RenderStyle* style, TextRun::ExpansionBehavior expansion)
+{
+ if (text->is8Bit())
+ return constructTextRunInternal(context, font, text->characters8(), text->textLength(), style, expansion);
+ return constructTextRunInternal(context, font, text->characters16(), text->textLength(), style, expansion);
+}
+
+TextRun RenderBlockFlow::constructTextRun(RenderObject* context, const Font& font, const RenderText* text, unsigned offset, unsigned length, RenderStyle* style, TextRun::ExpansionBehavior expansion)
+{
+ ASSERT(offset + length <= text->textLength());
+ if (text->is8Bit())
+ return constructTextRunInternal(context, font, text->characters8() + offset, length, style, expansion);
+ return constructTextRunInternal(context, font, text->characters16() + offset, length, style, expansion);
+}
+
+TextRun RenderBlockFlow::constructTextRun(RenderObject* context, const Font& font, const String& string, RenderStyle* style, TextRun::ExpansionBehavior expansion, TextRunFlags flags)
+{
+ unsigned length = string.length();
+ if (!length)
+ return constructTextRunInternal(context, font, static_cast<const LChar*>(0), length, style, expansion, flags);
+ if (string.is8Bit())
+ return constructTextRunInternal(context, font, string.characters8(), length, style, expansion, flags);
+ return constructTextRunInternal(context, font, string.characters16(), length, style, expansion, flags);
+}
+
+RootInlineBox* RenderBlockFlow::createRootInlineBox()
+{
+ return new RootInlineBox(this);
+}
+
+void RenderBlockFlow::createRenderNamedFlowFragmentIfNeeded()
+{
+ if (!RuntimeEnabledFeatures::cssRegionsEnabled()
+ || renderNamedFlowFragment()
+ || isRenderNamedFlowFragment())
+ return;
+
+ RenderStyle* styleToUse = style();
+ if (styleToUse->isDisplayRegionType() && styleToUse->hasFlowFrom() && document().renderView()) {
+ RenderNamedFlowFragment* flowFragment = RenderNamedFlowFragment::createAnonymous(&document());
+ flowFragment->setStyleForNamedFlowFragment(styleToUse);
+ setRenderNamedFlowFragment(flowFragment);
+ addChild(flowFragment);
+ }
+}
+
+void RenderBlockFlow::insertedIntoTree()
+{
+ RenderBlock::insertedIntoTree();
+
+ createRenderNamedFlowFragmentIfNeeded();
+}
+
+bool RenderBlockFlow::canHaveChildren() const
+{
+ return !renderNamedFlowFragment() ? RenderBlock::canHaveChildren() : renderNamedFlowFragment()->canHaveChildren();
+}
+
+bool RenderBlockFlow::canHaveGeneratedChildren() const
+{
+ return !renderNamedFlowFragment() ? RenderBlock::canHaveGeneratedChildren() : renderNamedFlowFragment()->canHaveGeneratedChildren();
+}
+
+void RenderBlockFlow::updateLogicalHeight()
+{
+ RenderBlock::updateLogicalHeight();
+
+ if (renderNamedFlowFragment())
+ renderNamedFlowFragment()->setLogicalHeight(max<LayoutUnit>(0, logicalHeight() - borderAndPaddingLogicalHeight()));
+}
+
+void RenderBlockFlow::setRenderNamedFlowFragment(RenderNamedFlowFragment* flowFragment)
+{
+ RenderBlockFlow::RenderBlockFlowRareData& rareData = ensureRareData();
+ if (rareData.m_renderNamedFlowFragment)
+ rareData.m_renderNamedFlowFragment->destroy();
+ rareData.m_renderNamedFlowFragment = flowFragment;
+}
+
+RenderBlockFlow::RenderBlockFlowRareData& RenderBlockFlow::ensureRareData()
+{
+ if (m_rareData)
+ return *m_rareData;
+
+ m_rareData = adoptPtr(new RenderBlockFlowRareData(this));
+ return *m_rareData;
+}
+
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderBlockFlow.h b/chromium/third_party/WebKit/Source/core/rendering/RenderBlockFlow.h
index d01686ea429..e68388194f5 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderBlockFlow.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderBlockFlow.h
@@ -36,30 +36,145 @@
#ifndef RenderBlockFlow_h
#define RenderBlockFlow_h
-#include "RenderBlock.h"
+#include "core/rendering/FloatingObjects.h"
+#include "core/rendering/RenderBlock.h"
+#include "core/rendering/style/RenderStyleConstants.h"
namespace WebCore {
class MarginInfo;
+class LineBreaker;
+class LineWidth;
+class RenderNamedFlowFragment;
class RenderBlockFlow : public RenderBlock {
public:
explicit RenderBlockFlow(ContainerNode*);
virtual ~RenderBlockFlow();
+ static RenderBlockFlow* createAnonymous(Document*);
+ RenderBlockFlow* createAnonymousBlockFlow() const;
+
virtual bool isRenderBlockFlow() const OVERRIDE FINAL { return true; }
virtual void layoutBlock(bool relayoutChildren, LayoutUnit pageLogicalHeight = 0) OVERRIDE;
+
+ virtual void computeOverflow(LayoutUnit oldClientAfterEdge, bool recomputeFloats = false) OVERRIDE;
+ virtual void deleteLineBoxTree() OVERRIDE FINAL;
+
+ void markAllDescendantsWithFloatsForLayout(RenderBox* floatToRemove = 0, bool inLayout = true);
+ void markSiblingsWithFloatsForLayout(RenderBox* floatToRemove = 0);
+
+ virtual bool containsFloats() const OVERRIDE FINAL { return m_floatingObjects && !m_floatingObjects->set().isEmpty(); }
+ bool containsFloat(RenderBox*) const;
+
+ void removeFloatingObjects();
+
+ bool generatesLineBoxesForInlineChild(RenderObject*);
+
+ LayoutUnit logicalTopForFloat(const FloatingObject* floatingObject) const { return isHorizontalWritingMode() ? floatingObject->y() : floatingObject->x(); }
+ LayoutUnit logicalBottomForFloat(const FloatingObject* floatingObject) const { return isHorizontalWritingMode() ? floatingObject->maxY() : floatingObject->maxX(); }
+ LayoutUnit logicalLeftForFloat(const FloatingObject* floatingObject) const { return isHorizontalWritingMode() ? floatingObject->x() : floatingObject->y(); }
+ LayoutUnit logicalRightForFloat(const FloatingObject* floatingObject) const { return isHorizontalWritingMode() ? floatingObject->maxX() : floatingObject->maxY(); }
+ LayoutUnit logicalWidthForFloat(const FloatingObject* floatingObject) const { return isHorizontalWritingMode() ? floatingObject->width() : floatingObject->height(); }
+ LayoutUnit logicalHeightForFloat(const FloatingObject* floatingObject) const { return isHorizontalWritingMode() ? floatingObject->height() : floatingObject->width(); }
+ LayoutSize logicalSizeForFloat(const FloatingObject* floatingObject) const { return isHorizontalWritingMode() ? LayoutSize(floatingObject->width(), floatingObject->height()) : LayoutSize(floatingObject->height(), floatingObject->width()); }
+
+ int pixelSnappedLogicalTopForFloat(const FloatingObject* floatingObject) const { return isHorizontalWritingMode() ? floatingObject->frameRect().pixelSnappedY() : floatingObject->frameRect().pixelSnappedX(); }
+ int pixelSnappedLogicalBottomForFloat(const FloatingObject* floatingObject) const { return isHorizontalWritingMode() ? floatingObject->frameRect().pixelSnappedMaxY() : floatingObject->frameRect().pixelSnappedMaxX(); }
+ int pixelSnappedLogicalLeftForFloat(const FloatingObject* floatingObject) const { return isHorizontalWritingMode() ? floatingObject->frameRect().pixelSnappedX() : floatingObject->frameRect().pixelSnappedY(); }
+ int pixelSnappedLogicalRightForFloat(const FloatingObject* floatingObject) const { return isHorizontalWritingMode() ? floatingObject->frameRect().pixelSnappedMaxX() : floatingObject->frameRect().pixelSnappedMaxY(); }
+
+ void setLogicalTopForFloat(FloatingObject* floatingObject, LayoutUnit logicalTop)
+ {
+ if (isHorizontalWritingMode())
+ floatingObject->setY(logicalTop);
+ else
+ floatingObject->setX(logicalTop);
+ }
+ void setLogicalLeftForFloat(FloatingObject* floatingObject, LayoutUnit logicalLeft)
+ {
+ if (isHorizontalWritingMode())
+ floatingObject->setX(logicalLeft);
+ else
+ floatingObject->setY(logicalLeft);
+ }
+ void setLogicalHeightForFloat(FloatingObject* floatingObject, LayoutUnit logicalHeight)
+ {
+ if (isHorizontalWritingMode())
+ floatingObject->setHeight(logicalHeight);
+ else
+ floatingObject->setWidth(logicalHeight);
+ }
+ void setLogicalWidthForFloat(FloatingObject* floatingObject, LayoutUnit logicalWidth)
+ {
+ if (isHorizontalWritingMode())
+ floatingObject->setWidth(logicalWidth);
+ else
+ floatingObject->setHeight(logicalWidth);
+ }
+
+ LayoutUnit startAlignedOffsetForLine(LayoutUnit position, bool shouldIndentText);
+
+ void setStaticInlinePositionForChild(RenderBox*, LayoutUnit blockOffset, LayoutUnit inlinePosition);
+ void updateStaticInlinePositionForChild(RenderBox*, LayoutUnit logicalTop);
+
+ static bool shouldSkipCreatingRunsForObject(RenderObject* obj)
+ {
+ return obj->isFloating() || (obj->isOutOfFlowPositioned() && !obj->style()->isOriginalDisplayInlineType() && !obj->container()->isRenderInline());
+ }
+
+ static TextRun constructTextRun(RenderObject* context, const Font&, const String&, RenderStyle*,
+ TextRun::ExpansionBehavior = TextRun::AllowTrailingExpansion | TextRun::ForbidLeadingExpansion, TextRunFlags = DefaultTextRunFlags);
+
+ static TextRun constructTextRun(RenderObject* context, const Font&, const RenderText*, RenderStyle*,
+ TextRun::ExpansionBehavior = TextRun::AllowTrailingExpansion | TextRun::ForbidLeadingExpansion);
+
+ static TextRun constructTextRun(RenderObject* context, const Font&, const RenderText*, unsigned offset, unsigned length, RenderStyle*,
+ TextRun::ExpansionBehavior = TextRun::AllowTrailingExpansion | TextRun::ForbidLeadingExpansion);
+
+ static TextRun constructTextRun(RenderObject* context, const Font&, const RenderText*, unsigned offset, RenderStyle*,
+ TextRun::ExpansionBehavior = TextRun::AllowTrailingExpansion | TextRun::ForbidLeadingExpansion);
+
+ static TextRun constructTextRun(RenderObject* context, const Font&, const LChar* characters, int length, RenderStyle*,
+ TextRun::ExpansionBehavior = TextRun::AllowTrailingExpansion | TextRun::ForbidLeadingExpansion);
+
+ static TextRun constructTextRun(RenderObject* context, const Font&, const UChar* characters, int length, RenderStyle*,
+ TextRun::ExpansionBehavior = TextRun::AllowTrailingExpansion | TextRun::ForbidLeadingExpansion);
+
+ RootInlineBox* lineGridBox() const { return m_rareData ? m_rareData->m_lineGridBox : 0; }
+ void setLineGridBox(RootInlineBox* box)
+ {
+ RenderBlockFlow::RenderBlockFlowRareData& rareData = ensureRareData();
+ if (rareData.m_lineGridBox)
+ rareData.m_lineGridBox->destroy();
+ rareData.m_lineGridBox = box;
+ }
+ void layoutLineGridBox();
+
+ void addOverflowFromInlineChildren();
+
+ GapRects inlineSelectionGaps(RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock,
+ LayoutUnit& lastLogicalTop, LayoutUnit& lastLogicalLeft, LayoutUnit& lastLogicalRight, const PaintInfo*);
protected:
// Only used by RenderSVGText, which explicitly overrides RenderBlock::layoutBlock(), do NOT use for anything else.
void forceLayoutInlineChildren()
{
LayoutUnit repaintLogicalTop = 0;
LayoutUnit repaintLogicalBottom = 0;
- clearFloats();
+ rebuildFloatsFromIntruding();
layoutInlineChildren(true, repaintLogicalTop, repaintLogicalBottom);
}
+ void createFloatingObjects();
+
+ virtual void styleWillChange(StyleDifference, const RenderStyle* newStyle) OVERRIDE;
+ virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle) OVERRIDE;
+
+ void addOverflowFromFloats();
+
+ virtual void insertedIntoTree() OVERRIDE;
+ virtual void willBeDestroyed() OVERRIDE;
private:
void layoutBlockChildren(bool relayoutChildren, LayoutUnit& maxFloatLogicalBottom, SubtreeLayoutScope&);
void layoutInlineChildren(bool relayoutChildren, LayoutUnit& repaintLogicalTop, LayoutUnit& repaintLogicalBottom);
@@ -68,9 +183,81 @@ private:
void adjustPositionedBlock(RenderBox* child, const MarginInfo&);
void adjustFloatingBlock(const MarginInfo&);
- void clearFloats();
+ void rebuildFloatsFromIntruding();
+
+ LayoutPoint flipFloatForWritingModeForChild(const FloatingObject*, const LayoutPoint&) const;
+ LayoutUnit xPositionForFloatIncludingMargin(const FloatingObject* child) const
+ {
+ if (isHorizontalWritingMode())
+ return child->x() + child->renderer()->marginLeft();
+
+ return child->x() + marginBeforeForChild(child->renderer());
+ }
+
+ LayoutUnit yPositionForFloatIncludingMargin(const FloatingObject* child) const
+ {
+ if (isHorizontalWritingMode())
+ return child->y() + marginBeforeForChild(child->renderer());
+
+ return child->y() + child->renderer()->marginTop();
+ }
+
+ LayoutPoint computeLogicalLocationForFloat(const FloatingObject*, LayoutUnit logicalTopOffset) const;
+
+ FloatingObject* insertFloatingObject(RenderBox*);
+ void removeFloatingObject(RenderBox*);
+ void removeFloatingObjectsBelow(FloatingObject*, int logicalOffset);
+
+ // Called from lineWidth, to position the floats added in the last line.
+ // Returns true if and only if it has positioned any floats.
+ bool positionNewFloats();
+
+ LayoutUnit getClearDelta(RenderBox* child, LayoutUnit yPos);
+
+ bool hasOverhangingFloats() { return parent() && !hasColumns() && containsFloats() && lowestFloatLogicalBottom() > logicalHeight(); }
+ bool hasOverhangingFloat(RenderBox*);
+ void addIntrudingFloats(RenderBlockFlow* prev, LayoutUnit xoffset, LayoutUnit yoffset);
+ LayoutUnit addOverhangingFloats(RenderBlockFlow* child, bool makeChildPaintOtherFloats);
+
+ LayoutUnit lowestFloatLogicalBottom(FloatingObject::Type = FloatingObject::FloatLeftRight) const;
+ LayoutUnit nextFloatLogicalBottomBelow(LayoutUnit, ShapeOutsideFloatOffsetMode = ShapeOutsideFloatMarginBoxOffset) const;
+
+ virtual bool hitTestFloats(const HitTestRequest&, HitTestResult&, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset) OVERRIDE FINAL;
+
+ virtual void moveAllChildrenIncludingFloatsTo(RenderBlock* toBlock, bool fullRemoveInsert) OVERRIDE;
+ virtual void repaintOverhangingFloats(bool paintAllDescendants) OVERRIDE FINAL;
+ virtual void repaintOverflow() OVERRIDE;
+ virtual void paintFloats(PaintInfo&, const LayoutPoint&, bool preservePhase = false) OVERRIDE FINAL;
+ virtual void clipOutFloatingObjects(RenderBlock*, const PaintInfo*, const LayoutPoint&, const LayoutSize&) OVERRIDE;
+ void clearFloats(EClear);
+
+ virtual LayoutUnit logicalRightFloatOffsetForLine(LayoutUnit logicalTop, LayoutUnit fixedOffset, LayoutUnit logicalHeight) const OVERRIDE;
+ virtual LayoutUnit logicalLeftFloatOffsetForLine(LayoutUnit logicalTop, LayoutUnit fixedOffset, LayoutUnit logicalHeight) const OVERRIDE;
+
+ LayoutUnit logicalRightOffsetForPositioningFloat(LayoutUnit logicalTop, LayoutUnit fixedOffset, bool applyTextIndent, LayoutUnit* heightRemaining) const;
+ LayoutUnit logicalLeftOffsetForPositioningFloat(LayoutUnit logicalTop, LayoutUnit fixedOffset, bool applyTextIndent, LayoutUnit* heightRemaining) const;
+
+ virtual void adjustForBorderFit(LayoutUnit x, LayoutUnit& left, LayoutUnit& right) const OVERRIDE; // Helper function for borderFitAdjust
+
+ virtual RootInlineBox* createRootInlineBox() OVERRIDE;
+
+ void updateLogicalWidthForAlignment(const ETextAlign&, const RootInlineBox*, BidiRun* trailingSpaceRun, float& logicalLeft, float& totalLogicalWidth, float& availableLogicalWidth, int expansionOpportunityCount);
+ virtual bool relayoutForPagination(bool hasSpecifiedPageLogicalHeight, LayoutUnit pageLogicalHeight, LayoutStateMaintainer&);
public:
+ struct FloatWithRect {
+ FloatWithRect(RenderBox* f)
+ : object(f)
+ , rect(LayoutRect(f->x() - f->marginLeft(), f->y() - f->marginTop(), f->width() + f->marginWidth(), f->height() + f->marginHeight()))
+ , everHadLayout(f->everHadLayout())
+ {
+ }
+
+ RenderBox* object;
+ LayoutRect rect;
+ bool everHadLayout;
+ };
+
class MarginValues {
public:
MarginValues(LayoutUnit beforePos, LayoutUnit beforeNeg, LayoutUnit afterPos, LayoutUnit afterNeg)
@@ -98,14 +285,18 @@ public:
};
MarginValues marginValuesForChild(RenderBox* child) const;
+ virtual void updateLogicalHeight() OVERRIDE;
+
// Allocated only when some of these fields have non-default values
struct RenderBlockFlowRareData {
WTF_MAKE_NONCOPYABLE(RenderBlockFlowRareData); WTF_MAKE_FAST_ALLOCATED;
public:
RenderBlockFlowRareData(const RenderBlockFlow* block)
: m_margins(positiveMarginBeforeDefault(block), negativeMarginBeforeDefault(block), positiveMarginAfterDefault(block), negativeMarginAfterDefault(block))
+ , m_lineGridBox(0)
, m_discardMarginBefore(false)
, m_discardMarginAfter(false)
+ , m_renderNamedFlowFragment(0)
{
}
@@ -127,9 +318,17 @@ public:
}
MarginValues m_margins;
+
+ RootInlineBox* m_lineGridBox;
+
bool m_discardMarginBefore : 1;
bool m_discardMarginAfter : 1;
+ RenderNamedFlowFragment* m_renderNamedFlowFragment;
};
+ LayoutUnit marginOffsetForSelfCollapsingBlock();
+
+ RenderNamedFlowFragment* renderNamedFlowFragment() const { return m_rareData ? m_rareData->m_renderNamedFlowFragment : 0; }
+ void setRenderNamedFlowFragment(RenderNamedFlowFragment*);
protected:
LayoutUnit maxPositiveMarginBefore() const { return m_rareData ? m_rareData->m_margins.positiveMarginBefore() : RenderBlockFlowRareData::positiveMarginBeforeDefault(this); }
@@ -163,6 +362,7 @@ protected:
}
}
+ virtual ETextAlign textAlignmentForLine(bool endsWithSoftBreak) const;
private:
virtual LayoutUnit collapsedMarginBefore() const OVERRIDE FINAL { return maxPositiveMarginBefore() - maxNegativeMarginBefore(); }
virtual LayoutUnit collapsedMarginAfter() const OVERRIDE FINAL { return maxPositiveMarginAfter() - maxNegativeMarginAfter(); }
@@ -179,39 +379,69 @@ private:
LayoutUnit adjustBlockChildForPagination(LayoutUnit logicalTopAfterClear, LayoutUnit estimateWithoutPagination, RenderBox* child, bool atBeforeSideOfBlock);
+ // Used to store state between styleWillChange and styleDidChange
+ static bool s_canPropagateFloatIntoSibling;
+
+ virtual bool canHaveChildren() const OVERRIDE;
+ virtual bool canHaveGeneratedChildren() const OVERRIDE;
+
+ void createRenderNamedFlowFragmentIfNeeded();
+
+ RenderBlockFlowRareData& ensureRareData();
+
+ LayoutUnit m_repaintLogicalTop;
+ LayoutUnit m_repaintLogicalBottom;
+
protected:
OwnPtr<RenderBlockFlowRareData> m_rareData;
+ OwnPtr<FloatingObjects> m_floatingObjects;
+ friend class BreakingContext; // FIXME: It uses insertFloatingObject and positionNewFloatOnLine, if we move those out from the private scope/add a helper to LineBreaker, we can remove this friend
friend class MarginInfo;
+ friend class LineBreaker;
+ friend class LineWidth; // needs to know FloatingObject
+
+// FIXME-BLOCKFLOW: These methods have implementations in
+// RenderBlockLineLayout. They should be moved to the proper header once the
+// line layout code is separated from RenderBlock and RenderBlockFlow.
+// START METHODS DEFINED IN RenderBlockLineLayout
+private:
+ InlineFlowBox* createLineBoxes(RenderObject*, const LineInfo&, InlineBox* childBox, bool startsNewSegment);
+ RootInlineBox* constructLine(BidiRunList<BidiRun>&, const LineInfo&);
+ void setMarginsForRubyRun(BidiRun*, RenderRubyRun*, RenderObject*, const LineInfo&);
+ void computeInlineDirectionPositionsForLine(RootInlineBox*, const LineInfo&, BidiRun* firstRun, BidiRun* trailingSpaceRun, bool reachedEnd, GlyphOverflowAndFallbackFontsMap&, VerticalPositionCache&, WordMeasurements&);
+ BidiRun* computeInlineDirectionPositionsForSegment(RootInlineBox*, const LineInfo&, ETextAlign, float& logicalLeft,
+ float& availableLogicalWidth, BidiRun* firstRun, BidiRun* trailingSpaceRun, GlyphOverflowAndFallbackFontsMap& textBoxDataMap, VerticalPositionCache&, WordMeasurements&);
+ void computeBlockDirectionPositionsForLine(RootInlineBox*, BidiRun*, GlyphOverflowAndFallbackFontsMap&, VerticalPositionCache&);
+ BidiRun* handleTrailingSpaces(BidiRunList<BidiRun>&, BidiContext*);
+ void appendFloatingObjectToLastLine(FloatingObject*);
+ // Helper function for layoutInlineChildren()
+ RootInlineBox* createLineBoxesFromBidiRuns(unsigned bidiLevel, BidiRunList<BidiRun>&, const InlineIterator& end, LineInfo&, VerticalPositionCache&, BidiRun* trailingSpaceRun, WordMeasurements&);
+ void layoutRunsAndFloats(LineLayoutState&, bool hasInlineChild);
+ const InlineIterator& restartLayoutRunsAndFloatsInRange(LayoutUnit oldLogicalHeight, LayoutUnit newLogicalHeight, FloatingObject* lastFloatFromPreviousLine, InlineBidiResolver&, const InlineIterator&);
+ void layoutRunsAndFloatsInRange(LineLayoutState&, InlineBidiResolver&, const InlineIterator& cleanLineStart, const BidiStatus& cleanLineBidiStatus, unsigned consecutiveHyphenatedLines);
+ void updateShapeAndSegmentsForCurrentLine(ShapeInsideInfo*&, const LayoutSize&, LineLayoutState&);
+ void updateShapeAndSegmentsForCurrentLineInFlowThread(ShapeInsideInfo*&, LineLayoutState&);
+ bool adjustLogicalLineTopAndLogicalHeightIfNeeded(ShapeInsideInfo*, LayoutUnit, LineLayoutState&, InlineBidiResolver&, FloatingObject*, InlineIterator&, WordMeasurements&);
+ void linkToEndLineIfNeeded(LineLayoutState&);
+ static void repaintDirtyFloats(Vector<FloatWithRect>& floats);
+ void checkFloatsInCleanLine(RootInlineBox*, Vector<FloatWithRect>&, size_t& floatIndex, bool& encounteredNewFloat, bool& dirtiedByFloat);
+ RootInlineBox* determineStartPosition(LineLayoutState&, InlineBidiResolver&);
+ void determineEndPosition(LineLayoutState&, RootInlineBox* startBox, InlineIterator& cleanLineStart, BidiStatus& cleanLineBidiStatus);
+ bool checkPaginationAndFloatsAtEndLine(LineLayoutState&);
+ bool matchedEndLine(LineLayoutState&, const InlineBidiResolver&, const InlineIterator& endLineStart, const BidiStatus& endLineStatus);
+ void deleteEllipsisLineBoxes();
+ void checkLinesForTextOverflow();
+ // Positions new floats and also adjust all floats encountered on the line if any of them
+ // have to move to the next page/column.
+ bool positionNewFloatOnLine(FloatingObject* newFloat, FloatingObject* lastFloatFromPreviousLine, LineInfo&, LineWidth&);
+
+
+// END METHODS DEFINED IN RenderBlockLineLayout
+
};
-inline RenderBlockFlow& toRenderBlockFlow(RenderObject& object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(object.isRenderBlockFlow());
- return static_cast<RenderBlockFlow&>(object);
-}
-
-inline const RenderBlockFlow& toRenderBlockFlow(const RenderObject& object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(object.isRenderBlockFlow());
- return static_cast<const RenderBlockFlow&>(object);
-}
-
-inline RenderBlockFlow* toRenderBlockFlow(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isRenderBlockFlow());
- return static_cast<RenderBlockFlow*>(object);
-}
-
-inline const RenderBlockFlow* toRenderBlockFlow(const RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isRenderBlockFlow());
- return static_cast<const RenderBlockFlow*>(object);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toRenderBlockFlow(const RenderBlockFlow*);
-void toRenderBlockFlow(const RenderBlockFlow&);
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderBlockFlow, isRenderBlockFlow());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderBlockLineLayout.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderBlockLineLayout.cpp
index 2aa369f20d2..9c877c5d802 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderBlockLineLayout.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderBlockLineLayout.cpp
@@ -22,14 +22,10 @@
#include "config.h"
-#include "core/platform/text/BidiResolver.h"
-#include "core/rendering/InlineIterator.h"
-#include "core/rendering/InlineTextBox.h"
-#include "core/rendering/LineWidth.h"
-#include "core/rendering/RenderCombineText.h"
+#include "core/rendering/FastTextAutosizer.h"
+#include "core/rendering/LayoutRectRecorder.h"
#include "core/rendering/RenderCounter.h"
#include "core/rendering/RenderFlowThread.h"
-#include "core/rendering/RenderInline.h"
#include "core/rendering/RenderLayer.h"
#include "core/rendering/RenderListMarker.h"
#include "core/rendering/RenderRegion.h"
@@ -37,38 +33,30 @@
#include "core/rendering/RenderView.h"
#include "core/rendering/TrailingFloatsRootInlineBox.h"
#include "core/rendering/VerticalPositionCache.h"
-#include "core/rendering/break_lines.h"
-#include "core/rendering/shapes/ShapeInsideInfo.h"
-#include "core/rendering/svg/RenderSVGInlineText.h"
+#include "core/rendering/line/BreakingContextInlineHeaders.h"
#include "core/rendering/svg/SVGRootInlineBox.h"
+#include "platform/text/BidiResolver.h"
#include "wtf/RefCountedLeakCounter.h"
#include "wtf/StdLibExtras.h"
#include "wtf/Vector.h"
#include "wtf/unicode/CharacterNames.h"
-using namespace std;
-using namespace WTF;
-using namespace Unicode;
-
namespace WebCore {
-// We don't let our line box tree for a single line get any deeper than this.
-const unsigned cMaxLineDepth = 200;
-
-struct RenderTextInfo {
- // Destruction of m_layout requires TextLayout to be a complete type, so the constructor and destructor are made non-inline to avoid compilation errors.
- RenderTextInfo();
- ~RenderTextInfo();
+static IndentTextOrNot requiresIndent(bool isFirstLine, bool isAfterHardLineBreak, RenderStyle* style)
+{
+ if (isFirstLine)
+ return IndentText;
+ if (isAfterHardLineBreak && style->textIndentLine() == TextIndentEachLine)
+ return IndentText;
- RenderText* m_text;
- OwnPtr<TextLayout> m_layout;
- LazyLineBreakIterator m_lineBreakIterator;
- const Font* m_font;
-};
+ return DoNotIndentText;
+}
class LineBreaker {
public:
- LineBreaker(RenderBlock* block)
+ friend class BreakingContext;
+ LineBreaker(RenderBlockFlow* block)
: m_block(block)
{
reset();
@@ -83,115 +71,14 @@ private:
void reset();
InlineIterator nextSegmentBreak(InlineBidiResolver&, LineInfo&, RenderTextInfo&, FloatingObject* lastFloatFromPreviousLine, unsigned consecutiveHyphenatedLines, WordMeasurements&);
- void skipTrailingWhitespace(InlineIterator&, const LineInfo&);
void skipLeadingWhitespace(InlineBidiResolver&, LineInfo&, FloatingObject* lastFloatFromPreviousLine, LineWidth&);
- RenderBlock* m_block;
+ RenderBlockFlow* m_block;
bool m_hyphenated;
EClear m_clear;
Vector<RenderBox*> m_positionedObjects;
};
-ShapeInsideInfo* RenderBlock::layoutShapeInsideInfo() const
-{
- ShapeInsideInfo* shapeInsideInfo = view()->layoutState()->shapeInsideInfo();
-
- if (!shapeInsideInfo && flowThreadContainingBlock() && allowsShapeInsideInfoSharing()) {
- // regionAtBlockOffset returns regions like an array first={0,N-1}, second={N,M-1}, ...
- LayoutUnit offset = logicalHeight() + logicalHeightForLine(this, false) - LayoutUnit(1);
- RenderRegion* region = regionAtBlockOffset(offset);
- if (region)
- shapeInsideInfo = region->shapeInsideInfo();
- }
-
- return shapeInsideInfo;
-}
-
-class LineInfo {
-public:
- LineInfo()
- : m_isFirstLine(true)
- , m_isLastLine(false)
- , m_isEmpty(true)
- , m_previousLineBrokeCleanly(true)
- , m_floatPaginationStrut(0)
- , m_runsFromLeadingWhitespace(0)
- { }
-
- bool isFirstLine() const { return m_isFirstLine; }
- bool isLastLine() const { return m_isLastLine; }
- bool isEmpty() const { return m_isEmpty; }
- bool previousLineBrokeCleanly() const { return m_previousLineBrokeCleanly; }
- LayoutUnit floatPaginationStrut() const { return m_floatPaginationStrut; }
- unsigned runsFromLeadingWhitespace() const { return m_runsFromLeadingWhitespace; }
- void resetRunsFromLeadingWhitespace() { m_runsFromLeadingWhitespace = 0; }
- void incrementRunsFromLeadingWhitespace() { m_runsFromLeadingWhitespace++; }
-
- void setFirstLine(bool firstLine) { m_isFirstLine = firstLine; }
- void setLastLine(bool lastLine) { m_isLastLine = lastLine; }
- void setEmpty(bool empty, RenderBlock* block = 0, LineWidth* lineWidth = 0)
- {
- if (m_isEmpty == empty)
- return;
- m_isEmpty = empty;
- if (!empty && block && floatPaginationStrut()) {
- block->setLogicalHeight(block->logicalHeight() + floatPaginationStrut());
- setFloatPaginationStrut(0);
- lineWidth->updateAvailableWidth();
- }
- }
-
- void setPreviousLineBrokeCleanly(bool previousLineBrokeCleanly) { m_previousLineBrokeCleanly = previousLineBrokeCleanly; }
- void setFloatPaginationStrut(LayoutUnit strut) { m_floatPaginationStrut = strut; }
-
-private:
- bool m_isFirstLine;
- bool m_isLastLine;
- bool m_isEmpty;
- bool m_previousLineBrokeCleanly;
- LayoutUnit m_floatPaginationStrut;
- unsigned m_runsFromLeadingWhitespace;
-};
-
-static inline LayoutUnit borderPaddingMarginStart(RenderInline* child)
-{
- return child->marginStart() + child->paddingStart() + child->borderStart();
-}
-
-static inline LayoutUnit borderPaddingMarginEnd(RenderInline* child)
-{
- return child->marginEnd() + child->paddingEnd() + child->borderEnd();
-}
-
-static bool shouldAddBorderPaddingMargin(RenderObject* child, bool &checkSide)
-{
- if (!child || (child->isText() && !toRenderText(child)->textLength()))
- return true;
- checkSide = false;
- return checkSide;
-}
-
-static LayoutUnit inlineLogicalWidth(RenderObject* child, bool start = true, bool end = true)
-{
- unsigned lineDepth = 1;
- LayoutUnit extraWidth = 0;
- RenderObject* parent = child->parent();
- while (parent->isRenderInline() && lineDepth++ < cMaxLineDepth) {
- RenderInline* parentAsRenderInline = toRenderInline(parent);
- if (!isEmptyInline(parentAsRenderInline)) {
- if (start && shouldAddBorderPaddingMargin(child->previousSibling(), start))
- extraWidth += borderPaddingMarginStart(parentAsRenderInline);
- if (end && shouldAddBorderPaddingMargin(child->nextSibling(), end))
- extraWidth += borderPaddingMarginEnd(parentAsRenderInline);
- if (!start && !end)
- return extraWidth;
- }
- child = parent;
- parent = child->parent();
- }
- return extraWidth;
-}
-
static RenderObject* firstRenderObjectForDirectionalityDetermination(RenderObject* root, RenderObject* current = 0)
{
RenderObject* next = current;
@@ -240,131 +127,9 @@ static TextDirection determinePlaintextDirectionality(RenderObject* root, Render
{
InlineIterator iter(root, firstRenderObjectForDirectionalityDetermination(root, current), pos);
InlineBidiResolver observer;
- observer.setPositionIgnoringNestedIsolates(iter);
observer.setStatus(BidiStatus(root->style()->direction(), isOverride(root->style()->unicodeBidi())));
- while (!iter.atEnd()) {
- if (observer.inIsolate()) {
- iter.increment(&observer, InlineIterator::FastIncrementInIsolatedRenderer);
- continue;
- }
- if (iter.atParagraphSeparator())
- break;
- if (UChar current = iter.current()) {
- Direction charDirection = direction(current);
- if (charDirection == LeftToRight)
- return LTR;
- if (charDirection == RightToLeft || charDirection == RightToLeftArabic)
- return RTL;
- }
- iter.increment(&observer);
- }
- return LTR;
-}
-
-static void checkMidpoints(LineMidpointState& lineMidpointState, InlineIterator& lBreak)
-{
- // Check to see if our last midpoint is a start point beyond the line break. If so,
- // shave it off the list, and shave off a trailing space if the previous end point doesn't
- // preserve whitespace.
- if (lBreak.m_obj && lineMidpointState.numMidpoints && !(lineMidpointState.numMidpoints % 2)) {
- InlineIterator* midpoints = lineMidpointState.midpoints.data();
- InlineIterator& endpoint = midpoints[lineMidpointState.numMidpoints - 2];
- const InlineIterator& startpoint = midpoints[lineMidpointState.numMidpoints - 1];
- InlineIterator currpoint = endpoint;
- while (!currpoint.atEnd() && currpoint != startpoint && currpoint != lBreak)
- currpoint.increment();
- if (currpoint == lBreak) {
- // We hit the line break before the start point. Shave off the start point.
- lineMidpointState.numMidpoints--;
- if (endpoint.m_obj->style()->collapseWhiteSpace() && endpoint.m_obj->isText())
- endpoint.m_pos--;
- }
- }
-}
-
-// Don't call this directly. Use one of the descriptive helper functions below.
-static void deprecatedAddMidpoint(LineMidpointState& lineMidpointState, const InlineIterator& midpoint)
-{
- if (lineMidpointState.midpoints.size() <= lineMidpointState.numMidpoints)
- lineMidpointState.midpoints.grow(lineMidpointState.numMidpoints + 10);
-
- InlineIterator* midpoints = lineMidpointState.midpoints.data();
- midpoints[lineMidpointState.numMidpoints++] = midpoint;
-}
-
-static inline void startIgnoringSpaces(LineMidpointState& lineMidpointState, const InlineIterator& midpoint)
-{
- ASSERT(!(lineMidpointState.numMidpoints % 2));
- deprecatedAddMidpoint(lineMidpointState, midpoint);
-}
-
-static inline void stopIgnoringSpaces(LineMidpointState& lineMidpointState, const InlineIterator& midpoint)
-{
- ASSERT(lineMidpointState.numMidpoints % 2);
- deprecatedAddMidpoint(lineMidpointState, midpoint);
-}
-
-// When ignoring spaces, this needs to be called for objects that need line boxes such as RenderInlines or
-// hard line breaks to ensure that they're not ignored.
-static inline void ensureLineBoxInsideIgnoredSpaces(LineMidpointState& lineMidpointState, RenderObject* renderer)
-{
- InlineIterator midpoint(0, renderer, 0);
- stopIgnoringSpaces(lineMidpointState, midpoint);
- startIgnoringSpaces(lineMidpointState, midpoint);
-}
-
-// Adding a pair of midpoints before a character will split it out into a new line box.
-static inline void ensureCharacterGetsLineBox(LineMidpointState& lineMidpointState, InlineIterator& textParagraphSeparator)
-{
- InlineIterator midpoint(0, textParagraphSeparator.m_obj, textParagraphSeparator.m_pos);
- startIgnoringSpaces(lineMidpointState, InlineIterator(0, textParagraphSeparator.m_obj, textParagraphSeparator.m_pos - 1));
- stopIgnoringSpaces(lineMidpointState, InlineIterator(0, textParagraphSeparator.m_obj, textParagraphSeparator.m_pos));
-}
-
-static inline BidiRun* createRun(int start, int end, RenderObject* obj, InlineBidiResolver& resolver)
-{
- return new BidiRun(start, end, obj, resolver.context(), resolver.dir());
-}
-
-void RenderBlock::appendRunsForObject(BidiRunList<BidiRun>& runs, int start, int end, RenderObject* obj, InlineBidiResolver& resolver)
-{
- if (start > end || shouldSkipCreatingRunsForObject(obj))
- return;
-
- LineMidpointState& lineMidpointState = resolver.midpointState();
- bool haveNextMidpoint = (lineMidpointState.currentMidpoint < lineMidpointState.numMidpoints);
- InlineIterator nextMidpoint;
- if (haveNextMidpoint)
- nextMidpoint = lineMidpointState.midpoints[lineMidpointState.currentMidpoint];
- if (lineMidpointState.betweenMidpoints) {
- if (!(haveNextMidpoint && nextMidpoint.m_obj == obj))
- return;
- // This is a new start point. Stop ignoring objects and
- // adjust our start.
- lineMidpointState.betweenMidpoints = false;
- start = nextMidpoint.m_pos;
- lineMidpointState.currentMidpoint++;
- if (start < end)
- return appendRunsForObject(runs, start, end, obj, resolver);
- } else {
- if (!haveNextMidpoint || (obj != nextMidpoint.m_obj)) {
- runs.addRun(createRun(start, end, obj, resolver));
- return;
- }
-
- // An end midpoint has been encountered within our object. We
- // need to go ahead and append a run with our endpoint.
- if (static_cast<int>(nextMidpoint.m_pos + 1) <= end) {
- lineMidpointState.betweenMidpoints = true;
- lineMidpointState.currentMidpoint++;
- if (nextMidpoint.m_pos != UINT_MAX) { // UINT_MAX means stop at the object and don't include any of it.
- if (static_cast<int>(nextMidpoint.m_pos + 1) > start)
- runs.addRun(createRun(start, nextMidpoint.m_pos + 1, obj, resolver));
- return appendRunsForObject(runs, nextMidpoint.m_pos + 1, end, obj, resolver);
- }
- } else
- runs.addRun(createRun(start, end, obj, resolver));
- }
+ observer.setPositionIgnoringNestedIsolates(iter);
+ return observer.determineParagraphDirectionality();
}
static inline InlineBox* createInlineBoxForRenderer(RenderObject* obj, bool isRootLineBox, bool isOnlyRun = false)
@@ -406,7 +171,7 @@ static bool parentIsConstructedOrHaveNext(InlineFlowBox* parentBox)
return false;
}
-InlineFlowBox* RenderBlock::createLineBoxes(RenderObject* obj, const LineInfo& lineInfo, InlineBox* childBox, bool startNewSegment)
+InlineFlowBox* RenderBlockFlow::createLineBoxes(RenderObject* obj, const LineInfo& lineInfo, InlineBox* childBox, bool startNewSegment)
{
// See if we have an unconstructed line box for this object that is also
// the last item on the line.
@@ -499,7 +264,7 @@ static bool reachedEndOfTextRenderer(const BidiRunList<BidiRun>& bidiRuns)
return endsWithASCIISpaces(renderText->characters16(), pos, length);
}
-RootInlineBox* RenderBlock::constructLine(BidiRunList<BidiRun>& bidiRuns, const LineInfo& lineInfo)
+RootInlineBox* RenderBlockFlow::constructLine(BidiRunList<BidiRun>& bidiRuns, const LineInfo& lineInfo)
{
ASSERT(bidiRuns.firstRun());
@@ -575,11 +340,36 @@ RootInlineBox* RenderBlock::constructLine(BidiRunList<BidiRun>& bidiRuns, const
return lastRootBox();
}
-ETextAlign RenderBlock::textAlignmentForLine(bool endsWithSoftBreak) const
+ETextAlign RenderBlockFlow::textAlignmentForLine(bool endsWithSoftBreak) const
{
ETextAlign alignment = style()->textAlign();
- if (!endsWithSoftBreak && alignment == JUSTIFY)
- alignment = TASTART;
+ if (endsWithSoftBreak)
+ return alignment;
+
+ if (!RuntimeEnabledFeatures::css3TextEnabled())
+ return (alignment == JUSTIFY) ? TASTART : alignment;
+
+ TextAlignLast alignmentLast = style()->textAlignLast();
+ switch (alignmentLast) {
+ case TextAlignLastStart:
+ return TASTART;
+ case TextAlignLastEnd:
+ return TAEND;
+ case TextAlignLastLeft:
+ return LEFT;
+ case TextAlignLastRight:
+ return RIGHT;
+ case TextAlignLastCenter:
+ return CENTER;
+ case TextAlignLastJustify:
+ return JUSTIFY;
+ case TextAlignLastAuto:
+ if (alignment != JUSTIFY)
+ return alignment;
+ if (style()->textJustify() == TextJustifyDistribute)
+ return JUSTIFY;
+ return TASTART;
+ }
return alignment;
}
@@ -636,7 +426,7 @@ static void updateLogicalWidthForCenterAlignedBlock(bool isLeftToRightDirection,
logicalLeft += totalLogicalWidth > availableLogicalWidth ? (availableLogicalWidth - totalLogicalWidth) : (availableLogicalWidth - totalLogicalWidth) / 2 - trailingSpaceWidth;
}
-void RenderBlock::setMarginsForRubyRun(BidiRun* run, RenderRubyRun* renderer, RenderObject* previousObject, const LineInfo& lineInfo)
+void RenderBlockFlow::setMarginsForRubyRun(BidiRun* run, RenderRubyRun* renderer, RenderObject* previousObject, const LineInfo& lineInfo)
{
int startOverhang;
int endOverhang;
@@ -652,29 +442,6 @@ void RenderBlock::setMarginsForRubyRun(BidiRun* run, RenderRubyRun* renderer, Re
setMarginEndForChild(renderer, -endOverhang);
}
-static inline float measureHyphenWidth(RenderText* renderer, const Font& font)
-{
- RenderStyle* style = renderer->style();
- return font.width(RenderBlock::constructTextRun(renderer, font, style->hyphenString().string(), style));
-}
-
-class WordMeasurement {
-public:
- WordMeasurement()
- : renderer(0)
- , width(0)
- , startOffset(0)
- , endOffset(0)
- {
- }
-
- RenderText* renderer;
- float width;
- int startOffset;
- int endOffset;
- HashSet<const SimpleFontData*> fallbackFonts;
-};
-
static inline void setLogicalWidthForTextRun(RootInlineBox* lineBox, BidiRun* run, RenderText* renderer, float xPos, const LineInfo& lineInfo,
GlyphOverflowAndFallbackFontsMap& textBoxDataMap, VerticalPositionCache& verticalPositionCache, WordMeasurements& wordMeasurements)
{
@@ -797,7 +564,7 @@ static inline void computeExpansionForJustifiedText(BidiRun* firstRun, BidiRun*
}
}
-void RenderBlock::updateLogicalWidthForAlignment(const ETextAlign& textAlign, const RootInlineBox* rootInlineBox, BidiRun* trailingSpaceRun, float& logicalLeft, float& totalLogicalWidth, float& availableLogicalWidth, int expansionOpportunityCount)
+void RenderBlockFlow::updateLogicalWidthForAlignment(const ETextAlign& textAlign, const RootInlineBox* rootInlineBox, BidiRun* trailingSpaceRun, float& logicalLeft, float& totalLogicalWidth, float& availableLogicalWidth, int expansionOpportunityCount)
{
TextDirection direction;
if (rootInlineBox && rootInlineBox->renderer()->style()->unicodeBidi() == Plaintext)
@@ -847,25 +614,17 @@ void RenderBlock::updateLogicalWidthForAlignment(const ETextAlign& textAlign, co
}
}
-static IndentTextOrNot requiresIndent(bool isFirstLine, bool isAfterHardLineBreak, RenderStyle* style)
-{
- if (isFirstLine)
- return IndentText;
- if (isAfterHardLineBreak && style->textIndentLine() == TextIndentEachLine)
- return IndentText;
-
- return DoNotIndentText;
-}
-
-static void updateLogicalInlinePositions(RenderBlock* block, float& lineLogicalLeft, float& lineLogicalRight, float& availableLogicalWidth, bool firstLine, IndentTextOrNot shouldIndentText, LayoutUnit boxLogicalHeight)
+static void updateLogicalInlinePositions(RenderBlockFlow* block, float& lineLogicalLeft, float& lineLogicalRight, float& availableLogicalWidth, bool firstLine, IndentTextOrNot shouldIndentText, LayoutUnit boxLogicalHeight)
{
- LayoutUnit lineLogicalHeight = logicalHeightForLine(block, firstLine, boxLogicalHeight);
- lineLogicalLeft = block->pixelSnappedLogicalLeftOffsetForLine(block->logicalHeight(), shouldIndentText == IndentText, lineLogicalHeight);
+ LayoutUnit lineLogicalHeight = block->minLineHeightForReplacedRenderer(firstLine, boxLogicalHeight);
+ lineLogicalLeft = block->logicalLeftOffsetForLine(block->logicalHeight(), shouldIndentText == IndentText, lineLogicalHeight);
+ // FIXME: This shouldn't be pixel snapped once multicolumn layout has been updated to correctly carry over subpixel values.
+ // https://bugs.webkit.org/show_bug.cgi?id=105461
lineLogicalRight = block->pixelSnappedLogicalRightOffsetForLine(block->logicalHeight(), shouldIndentText == IndentText, lineLogicalHeight);
availableLogicalWidth = lineLogicalRight - lineLogicalLeft;
}
-void RenderBlock::computeInlineDirectionPositionsForLine(RootInlineBox* lineBox, const LineInfo& lineInfo, BidiRun* firstRun, BidiRun* trailingSpaceRun, bool reachedEnd,
+void RenderBlockFlow::computeInlineDirectionPositionsForLine(RootInlineBox* lineBox, const LineInfo& lineInfo, BidiRun* firstRun, BidiRun* trailingSpaceRun, bool reachedEnd,
GlyphOverflowAndFallbackFontsMap& textBoxDataMap, VerticalPositionCache& verticalPositionCache, WordMeasurements& wordMeasurements)
{
ETextAlign textAlign = textAlignmentForLine(!reachedEnd && !lineBox->endsWithBreak());
@@ -886,8 +645,8 @@ void RenderBlock::computeInlineDirectionPositionsForLine(RootInlineBox* lineBox,
if (shapeInsideInfo && shapeInsideInfo->hasSegments()) {
BidiRun* segmentStart = firstRun;
const SegmentList& segments = shapeInsideInfo->segments();
- float logicalLeft = max<float>(roundToInt(segments[0].logicalLeft), lineLogicalLeft);
- float logicalRight = min<float>(floorToInt(segments[0].logicalRight), lineLogicalRight);
+ float logicalLeft = max<float>(segments[0].logicalLeft, lineLogicalLeft);
+ float logicalRight = min<float>(segments[0].logicalRight, lineLogicalRight);
float startLogicalLeft = logicalLeft;
float endLogicalRight = logicalLeft;
float minLogicalLeft = logicalLeft;
@@ -895,8 +654,8 @@ void RenderBlock::computeInlineDirectionPositionsForLine(RootInlineBox* lineBox,
lineBox->beginPlacingBoxRangesInInlineDirection(logicalLeft);
for (size_t i = 0; i < segments.size(); i++) {
if (i) {
- logicalLeft = max<float>(roundToInt(segments[i].logicalLeft), lineLogicalLeft);
- logicalRight = min<float>(floorToInt(segments[i].logicalRight), lineLogicalRight);
+ logicalLeft = max<float>(segments[i].logicalLeft, lineLogicalLeft);
+ logicalRight = min<float>(segments[i].logicalRight, lineLogicalRight);
}
availableLogicalWidth = logicalRight - logicalLeft;
BidiRun* newSegmentStart = computeInlineDirectionPositionsForSegment(lineBox, lineInfo, textAlign, logicalLeft, availableLogicalWidth, segmentStart, trailingSpaceRun, textBoxDataMap, verticalPositionCache, wordMeasurements);
@@ -924,7 +683,7 @@ void RenderBlock::computeInlineDirectionPositionsForLine(RootInlineBox* lineBox,
lineBox->placeBoxesInInlineDirection(lineLogicalLeft, needsWordSpacing, textBoxDataMap);
}
-BidiRun* RenderBlock::computeInlineDirectionPositionsForSegment(RootInlineBox* lineBox, const LineInfo& lineInfo, ETextAlign textAlign, float& logicalLeft,
+BidiRun* RenderBlockFlow::computeInlineDirectionPositionsForSegment(RootInlineBox* lineBox, const LineInfo& lineInfo, ETextAlign textAlign, float& logicalLeft,
float& availableLogicalWidth, BidiRun* firstRun, BidiRun* trailingSpaceRun, GlyphOverflowAndFallbackFontsMap& textBoxDataMap, VerticalPositionCache& verticalPositionCache,
WordMeasurements& wordMeasurements)
{
@@ -934,6 +693,7 @@ BidiRun* RenderBlock::computeInlineDirectionPositionsForSegment(RootInlineBox* l
bool isAfterExpansion = true;
Vector<unsigned, 16> expansionOpportunities;
RenderObject* previousObject = 0;
+ TextJustify textJustify = style()->textJustify();
BidiRun* r = firstRun;
for (; r; r = r->next()) {
@@ -947,7 +707,7 @@ BidiRun* RenderBlock::computeInlineDirectionPositionsForSegment(RootInlineBox* l
// Similarly, line break boxes have no effect on the width.
if (r->m_object->isText()) {
RenderText* rt = toRenderText(r->m_object);
- if (textAlign == JUSTIFY && r != trailingSpaceRun) {
+ if (textAlign == JUSTIFY && r != trailingSpaceRun && textJustify != TextJustifyNone) {
if (!isAfterExpansion)
toInlineTextBox(r->m_box)->setCanHaveLeadingExpansion(true);
unsigned opportunitiesInRun;
@@ -993,7 +753,7 @@ BidiRun* RenderBlock::computeInlineDirectionPositionsForSegment(RootInlineBox* l
return r;
}
-void RenderBlock::computeBlockDirectionPositionsForLine(RootInlineBox* lineBox, BidiRun* firstRun, GlyphOverflowAndFallbackFontsMap& textBoxDataMap,
+void RenderBlockFlow::computeBlockDirectionPositionsForLine(RootInlineBox* lineBox, BidiRun* firstRun, GlyphOverflowAndFallbackFontsMap& textBoxDataMap,
VerticalPositionCache& verticalPositionCache)
{
setLogicalHeight(lineBox->alignBoxesInBlockDirection(logicalHeight(), textBoxDataMap, verticalPositionCache));
@@ -1030,24 +790,6 @@ static inline bool isCollapsibleSpace(UChar character, RenderText* renderer)
return false;
}
-
-static void setStaticPositions(RenderBlock* block, RenderBox* child)
-{
- // FIXME: The math here is actually not really right. It's a best-guess approximation that
- // will work for the common cases
- RenderObject* containerBlock = child->container();
- LayoutUnit blockHeight = block->logicalHeight();
- if (containerBlock->isRenderInline()) {
- // A relative positioned inline encloses us. In this case, we also have to determine our
- // position as though we were an inline. Set |staticInlinePosition| and |staticBlockPosition| on the relative positioned
- // inline so that we can obtain the value later.
- toRenderInline(containerBlock)->layer()->setStaticInlinePosition(block->startAlignedOffsetForLine(blockHeight, false));
- toRenderInline(containerBlock)->layer()->setStaticBlockPosition(blockHeight);
- }
- block->updateStaticInlinePositionForChild(child, blockHeight);
- child->layer()->setStaticBlockPosition(blockHeight);
-}
-
template <typename CharacterType>
static inline int findFirstTrailingSpace(RenderText* lastText, const CharacterType* characters, int start, int stop)
{
@@ -1062,7 +804,7 @@ static inline int findFirstTrailingSpace(RenderText* lastText, const CharacterTy
return firstSpace;
}
-inline BidiRun* RenderBlock::handleTrailingSpaces(BidiRunList<BidiRun>& bidiRuns, BidiContext* currentContext)
+inline BidiRun* RenderBlockFlow::handleTrailingSpaces(BidiRunList<BidiRun>& bidiRuns, BidiContext* currentContext)
{
if (!bidiRuns.runCount()
|| !bidiRuns.logicallyLastRun()->m_object->style()->breakOnlyAfterWhiteSpace()
@@ -1113,7 +855,7 @@ inline BidiRun* RenderBlock::handleTrailingSpaces(BidiRunList<BidiRun>& bidiRuns
return trailingSpaceRun;
}
-void RenderBlock::appendFloatingObjectToLastLine(FloatingObject* floatingObject)
+void RenderBlockFlow::appendFloatingObjectToLastLine(FloatingObject* floatingObject)
{
ASSERT(!floatingObject->originatingLine());
floatingObject->setOriginatingLine(lastRootBox());
@@ -1126,7 +868,7 @@ static inline BidiStatus statusWithDirection(TextDirection textDirection, bool i
WTF::Unicode::Direction direction = textDirection == LTR ? LeftToRight : RightToLeft;
RefPtr<BidiContext> context = BidiContext::create(textDirection == LTR ? 0 : 1, direction, isOverride, FromStyleOrDOM);
- // This copies BidiStatus and may churn the ref on BidiContext. I doubt it matters.
+ // This copies BidiStatus and may churn the ref on BidiContext I doubt it matters.
return BidiStatus(direction, direction, direction, context.release());
}
@@ -1139,8 +881,17 @@ static inline void setupResolverToResumeInIsolate(InlineBidiResolver& resolver,
}
}
+static void restoreIsolatedMidpointStates(InlineBidiResolver& topResolver, InlineBidiResolver& isolatedResolver)
+{
+ while (!isolatedResolver.isolatedRuns().isEmpty()) {
+ BidiRun* run = isolatedResolver.isolatedRuns().last();
+ isolatedResolver.isolatedRuns().removeLast();
+ topResolver.setMidpointStateForIsolatedRun(run, isolatedResolver.midpointStateForIsolatedRun(run));
+ }
+}
+
// FIXME: BidiResolver should have this logic.
-static inline void constructBidiRunsForSegment(InlineBidiResolver& topResolver, BidiRunList<BidiRun>& bidiRuns, const InlineIterator& endOfRuns, VisualDirectionOverride override, bool previousLineBrokeCleanly)
+static inline void constructBidiRunsForSegment(InlineBidiResolver& topResolver, BidiRunList<BidiRun>& bidiRuns, const InlineIterator& endOfRuns, VisualDirectionOverride override, bool previousLineBrokeCleanly, bool isNewUBAParagraph)
{
// FIXME: We should pass a BidiRunList into createBidiRunsForLine instead
// of the resolver owning the runs.
@@ -1165,11 +916,16 @@ static inline void constructBidiRunsForSegment(InlineBidiResolver& topResolver,
ASSERT(isolatedInline);
InlineBidiResolver isolatedResolver;
+ LineMidpointState& isolatedLineMidpointState = isolatedResolver.midpointState();
+ isolatedLineMidpointState = topResolver.midpointStateForIsolatedRun(isolatedRun);
EUnicodeBidi unicodeBidi = isolatedInline->style()->unicodeBidi();
TextDirection direction = isolatedInline->style()->direction();
- if (unicodeBidi == Plaintext)
- direction = determinePlaintextDirectionality(isolatedInline, startObj);
- else {
+ if (unicodeBidi == Plaintext) {
+ if (isNewUBAParagraph)
+ direction = determinePlaintextDirectionality(isolatedInline, startObj);
+ else
+ direction = determinePlaintextDirectionality(isolatedInline);
+ } else {
ASSERT(unicodeBidi == Isolate || unicodeBidi == IsolateOverride);
direction = isolatedInline->style()->direction();
}
@@ -1182,15 +938,12 @@ static inline void constructBidiRunsForSegment(InlineBidiResolver& topResolver,
// first run within the isolate.
InlineIterator iter = InlineIterator(isolatedInline, startObj, isolatedRun->m_start);
isolatedResolver.setPositionIgnoringNestedIsolates(iter);
-
// We stop at the next end of line; we may re-enter this isolate in the next call to constructBidiRuns().
// FIXME: What should end and previousLineBrokeCleanly be?
// rniwa says previousLineBrokeCleanly is just a WinIE hack and could always be false here?
isolatedResolver.createBidiRunsForLine(endOfRuns, NoVisualOverride, previousLineBrokeCleanly);
- // Note that we do not delete the runs from the resolver.
- // We're not guaranteed to get any BidiRuns in the previous step. If we don't, we allow the placeholder
- // itself to be turned into an InlineBox. We can't remove it here without potentially losing track of
- // the logically last run.
+
+ ASSERT(isolatedResolver.runs().runCount());
if (isolatedResolver.runs().runCount())
bidiRuns.replaceRunWithRuns(isolatedRun, isolatedResolver.runs());
@@ -1198,8 +951,8 @@ static inline void constructBidiRunsForSegment(InlineBidiResolver& topResolver,
// to the top resolver's list for later processing.
if (!isolatedResolver.isolatedRuns().isEmpty()) {
topResolver.isolatedRuns().append(isolatedResolver.isolatedRuns());
- isolatedResolver.isolatedRuns().clear();
currentRoot = isolatedInline;
+ restoreIsolatedMidpointStates(topResolver, isolatedResolver);
}
}
}
@@ -1209,11 +962,11 @@ static inline bool segmentIsEmpty(const InlineIterator& segmentStart, const Inli
return segmentStart == segmentEnd;
}
-static inline void constructBidiRunsForLine(const RenderBlock* block, InlineBidiResolver& topResolver, BidiRunList<BidiRun>& bidiRuns, const InlineIterator& endOfLine, VisualDirectionOverride override, bool previousLineBrokeCleanly)
+static inline void constructBidiRunsForLine(const RenderBlockFlow* block, InlineBidiResolver& topResolver, BidiRunList<BidiRun>& bidiRuns, const InlineIterator& endOfLine, VisualDirectionOverride override, bool previousLineBrokeCleanly, bool isNewUBAParagraph)
{
ShapeInsideInfo* shapeInsideInfo = block->layoutShapeInsideInfo();
if (!shapeInsideInfo || !shapeInsideInfo->hasSegments()) {
- constructBidiRunsForSegment(topResolver, bidiRuns, endOfLine, override, previousLineBrokeCleanly);
+ constructBidiRunsForSegment(topResolver, bidiRuns, endOfLine, override, previousLineBrokeCleanly, isNewUBAParagraph);
return;
}
@@ -1226,8 +979,8 @@ static inline void constructBidiRunsForLine(const RenderBlock* block, InlineBidi
iterator = segmentRanges[i].end;
InlineIterator segmentEnd(iterator.root, iterator.object, iterator.offset);
if (i) {
- ASSERT(segmentStart.m_obj);
- BidiRun* segmentMarker = createRun(segmentStart.m_pos, segmentStart.m_pos, segmentStart.m_obj, topResolver);
+ ASSERT(segmentStart.object());
+ BidiRun* segmentMarker = createRun(segmentStart.m_pos, segmentStart.m_pos, segmentStart.object(), topResolver);
segmentMarker->m_startsSegment = true;
bidiRuns.addRun(segmentMarker);
// Do not collapse midpoints between segments
@@ -1235,19 +988,19 @@ static inline void constructBidiRunsForLine(const RenderBlock* block, InlineBidi
}
if (!segmentIsEmpty(segmentStart, segmentEnd)) {
topResolver.setPosition(segmentStart, numberOfIsolateAncestors(segmentStart));
- constructBidiRunsForSegment(topResolver, bidiRuns, segmentEnd, override, previousLineBrokeCleanly);
+ constructBidiRunsForSegment(topResolver, bidiRuns, segmentEnd, override, previousLineBrokeCleanly, isNewUBAParagraph);
}
}
}
// This function constructs line boxes for all of the text runs in the resolver and computes their position.
-RootInlineBox* RenderBlock::createLineBoxesFromBidiRuns(unsigned bidiLevel, BidiRunList<BidiRun>& bidiRuns, const InlineIterator& end, LineInfo& lineInfo, VerticalPositionCache& verticalPositionCache, BidiRun* trailingSpaceRun, WordMeasurements& wordMeasurements)
+RootInlineBox* RenderBlockFlow::createLineBoxesFromBidiRuns(unsigned bidiLevel, BidiRunList<BidiRun>& bidiRuns, const InlineIterator& end, LineInfo& lineInfo, VerticalPositionCache& verticalPositionCache, BidiRun* trailingSpaceRun, WordMeasurements& wordMeasurements)
{
if (!bidiRuns.runCount())
return 0;
// FIXME: Why is this only done when we had runs?
- lineInfo.setLastLine(!end.m_obj);
+ lineInfo.setLastLine(!end.object());
RootInlineBox* lineBox = constructLine(bidiRuns, lineInfo);
if (!lineBox)
@@ -1338,7 +1091,7 @@ public:
FloatingObject* lastFloat() const { return m_lastFloat; }
void setLastFloat(FloatingObject* lastFloat) { m_lastFloat = lastFloat; }
- Vector<RenderBlock::FloatWithRect>& floats() { return m_floats; }
+ Vector<RenderBlockFlow::FloatWithRect>& floats() { return m_floats; }
unsigned floatIndex() const { return m_floatIndex; }
void setFloatIndex(unsigned floatIndex) { m_floatIndex = floatIndex; }
@@ -1350,7 +1103,7 @@ public:
void setFlowThread(RenderFlowThread* thread) { m_flowThread = thread; }
private:
- Vector<RenderBlock::FloatWithRect> m_floats;
+ Vector<RenderBlockFlow::FloatWithRect> m_floats;
FloatingObject* m_lastFloat;
RootInlineBox* m_endLine;
LineInfo m_lineInfo;
@@ -1385,7 +1138,7 @@ static void deleteLineRange(LineLayoutState& layoutState, RootInlineBox* startLi
}
}
-void RenderBlock::layoutRunsAndFloats(LineLayoutState& layoutState, bool hasInlineChild)
+void RenderBlockFlow::layoutRunsAndFloats(LineLayoutState& layoutState, bool hasInlineChild)
{
// We want to skip ahead to the first dirty line
InlineBidiResolver resolver;
@@ -1401,14 +1154,21 @@ void RenderBlock::layoutRunsAndFloats(LineLayoutState& layoutState, bool hasInli
// determineStartPosition can change the fullLayout flag we have to do this here. Failure to call
// determineStartPosition first will break fast/repaint/line-flow-with-floats-9.html.
if (layoutState.isFullLayout() && hasInlineChild && !selfNeedsLayout()) {
- setNeedsLayout(MarkOnlyThis); // Mark as needing a full layout to force us to repaint.
- RenderView* v = view();
- if (v && !v->doingFullRepaint() && hasLayer()) {
- // Because we waited until we were already inside layout to discover
- // that the block really needed a full layout, we missed our chance to repaint the layer
- // before layout started. Luckily the layer has cached the repaint rect for its original
- // position and size, and so we can use that to make a repaint happen now.
- repaintUsingContainer(containerForRepaint(), pixelSnappedIntRect(layer()->repaintRect()));
+ // Mark as needing a full layout to force us to repaint. Allow regions
+ // to reflow as needed.
+ setNeedsLayout(MarkOnlyThis);
+
+ if (RuntimeEnabledFeatures::repaintAfterLayoutEnabled()) {
+ setShouldDoFullRepaintAfterLayout(true);
+ } else {
+ RenderView* v = view();
+ if (v && !v->doingFullRepaint() && hasLayer()) {
+ // Because we waited until we were already inside layout to discover
+ // that the block really needed a full layout, we missed our chance to repaint the layer
+ // before layout started. Luckily the layer has cached the repaint rect for its original
+ // position and size, and so we can use that to make a repaint happen now.
+ repaintUsingContainer(containerForRepaint(), pixelSnappedIntRect(layer()->repainter().repaintRect()));
+ }
}
}
@@ -1439,7 +1199,7 @@ void RenderBlock::layoutRunsAndFloats(LineLayoutState& layoutState, bool hasInli
if (lastObject->isBR()) {
EClear clear = lastObject->style()->clear();
if (clear != CNONE)
- newLine(clear);
+ clearFloats(clear);
}
}
}
@@ -1460,7 +1220,7 @@ RenderTextInfo::~RenderTextInfo()
}
// Before restarting the layout loop with a new logicalHeight, remove all floats that were added and reset the resolver.
-inline const InlineIterator& RenderBlock::restartLayoutRunsAndFloatsInRange(LayoutUnit oldLogicalHeight, LayoutUnit newLogicalHeight, FloatingObject* lastFloatFromPreviousLine, InlineBidiResolver& resolver, const InlineIterator& oldEnd)
+inline const InlineIterator& RenderBlockFlow::restartLayoutRunsAndFloatsInRange(LayoutUnit oldLogicalHeight, LayoutUnit newLogicalHeight, FloatingObject* lastFloatFromPreviousLine, InlineBidiResolver& resolver, const InlineIterator& oldEnd)
{
removeFloatingObjectsBelow(lastFloatFromPreviousLine, oldLogicalHeight);
setLogicalHeight(newLogicalHeight);
@@ -1468,16 +1228,6 @@ inline const InlineIterator& RenderBlock::restartLayoutRunsAndFloatsInRange(Layo
return oldEnd;
}
-static inline float firstPositiveWidth(const WordMeasurements& wordMeasurements)
-{
- for (size_t i = 0; i < wordMeasurements.size(); ++i) {
- if (wordMeasurements[i].width > 0)
- return wordMeasurements[i].width;
- }
- return 0;
-}
-
-
static inline LayoutUnit adjustLogicalLineTop(ShapeInsideInfo* shapeInsideInfo, InlineIterator start, InlineIterator end, const WordMeasurements& wordMeasurements)
{
if (!shapeInsideInfo || end != start)
@@ -1491,7 +1241,7 @@ static inline LayoutUnit adjustLogicalLineTop(ShapeInsideInfo* shapeInsideInfo,
return shapeInsideInfo->shapeLogicalBottom();
}
-static inline void pushShapeContentOverflowBelowTheContentBox(RenderBlock* block, ShapeInsideInfo* shapeInsideInfo, LayoutUnit lineTop, LayoutUnit lineHeight)
+static inline void pushShapeContentOverflowBelowTheContentBox(RenderBlockFlow* block, ShapeInsideInfo* shapeInsideInfo, LayoutUnit lineTop, LayoutUnit lineHeight)
{
ASSERT(shapeInsideInfo);
@@ -1511,7 +1261,7 @@ static inline void pushShapeContentOverflowBelowTheContentBox(RenderBlock* block
block->setLogicalHeight(newLogicalHeight);
}
-void RenderBlock::updateShapeAndSegmentsForCurrentLine(ShapeInsideInfo*& shapeInsideInfo, const LayoutSize& logicalOffsetFromShapeContainer, LineLayoutState& layoutState)
+void RenderBlockFlow::updateShapeAndSegmentsForCurrentLine(ShapeInsideInfo*& shapeInsideInfo, const LayoutSize& logicalOffsetFromShapeContainer, LineLayoutState& layoutState)
{
if (layoutState.flowThread())
return updateShapeAndSegmentsForCurrentLineInFlowThread(shapeInsideInfo, layoutState);
@@ -1524,52 +1274,54 @@ void RenderBlock::updateShapeAndSegmentsForCurrentLine(ShapeInsideInfo*& shapeIn
LayoutUnit lineHeight = this->lineHeight(layoutState.lineInfo().isFirstLine(), isHorizontalWritingMode() ? HorizontalLine : VerticalLine, PositionOfInteriorLineBoxes);
// FIXME: Bug 95361: It is possible for a line to grow beyond lineHeight, in which case these segments may be incorrect.
- shapeInsideInfo->computeSegmentsForLine(LayoutSize(lineLeft, lineTop), lineHeight);
+ shapeInsideInfo->updateSegmentsForLine(LayoutSize(lineLeft, lineTop), lineHeight);
pushShapeContentOverflowBelowTheContentBox(this, shapeInsideInfo, lineTop, lineHeight);
}
-void RenderBlock::updateShapeAndSegmentsForCurrentLineInFlowThread(ShapeInsideInfo*& shapeInsideInfo, LineLayoutState& layoutState)
+void RenderBlockFlow::updateShapeAndSegmentsForCurrentLineInFlowThread(ShapeInsideInfo*& shapeInsideInfo, LineLayoutState& layoutState)
{
ASSERT(layoutState.flowThread());
- LayoutUnit lineHeight = this->lineHeight(layoutState.lineInfo().isFirstLine(), isHorizontalWritingMode() ? HorizontalLine : VerticalLine, PositionOfInteriorLineBoxes);
-
RenderRegion* currentRegion = regionAtBlockOffset(logicalHeight());
- if (!currentRegion)
+ if (!currentRegion || !currentRegion->logicalHeight())
return;
shapeInsideInfo = currentRegion->shapeInsideInfo();
+ RenderRegion* nextRegion = 0;
+ if (!currentRegion->isLastRegion()) {
+ RenderRegionList regionList = layoutState.flowThread()->renderRegionList();
+ RenderRegionList::const_iterator it = regionList.find(currentRegion);
+ nextRegion = *(++it);
+ }
+
+ // We only want to deal regions with shapes, so we check if the next region has a shape
+ if (!shapeInsideInfo && nextRegion && !nextRegion->shapeInsideInfo())
+ return;
+
+ LayoutUnit lineHeight = this->lineHeight(layoutState.lineInfo().isFirstLine(), isHorizontalWritingMode() ? HorizontalLine : VerticalLine, PositionOfInteriorLineBoxes);
LayoutUnit logicalLineTopInFlowThread = logicalHeight() + offsetFromLogicalTopOfFirstPage();
LayoutUnit logicalLineBottomInFlowThread = logicalLineTopInFlowThread + lineHeight;
LayoutUnit logicalRegionTopInFlowThread = currentRegion->logicalTopForFlowThreadContent();
LayoutUnit logicalRegionBottomInFlowThread = logicalRegionTopInFlowThread + currentRegion->logicalHeight() - currentRegion->borderAndPaddingBefore() - currentRegion->borderAndPaddingAfter();
- // We only want to deal regions with shapes, so we look up for the next region whether it has a shape
- if (!shapeInsideInfo && !currentRegion->isLastRegion()) {
- LayoutUnit deltaToNextRegion = logicalHeight() + logicalRegionBottomInFlowThread - logicalLineTopInFlowThread;
- RenderRegion* lookupForNextRegion = regionAtBlockOffset(logicalHeight() + deltaToNextRegion);
- if (!lookupForNextRegion->shapeInsideInfo())
- return;
- }
-
LayoutUnit shapeBottomInFlowThread = LayoutUnit::max();
if (shapeInsideInfo)
shapeBottomInFlowThread = shapeInsideInfo->shapeLogicalBottom() + currentRegion->logicalTopForFlowThreadContent();
- // If the line is between two shapes/regions we position the line to the top of the next shape/region
- RenderRegion* nextRegion = regionAtBlockOffset(logicalHeight() + lineHeight);
- if ((currentRegion != nextRegion && (logicalLineBottomInFlowThread > logicalRegionBottomInFlowThread)) || (!currentRegion->isLastRegion() && shapeBottomInFlowThread < logicalLineBottomInFlowThread)) {
- LayoutUnit deltaToNextRegion = logicalRegionBottomInFlowThread - logicalLineTopInFlowThread;
- nextRegion = regionAtBlockOffset(logicalHeight() + deltaToNextRegion);
+ bool lineOverLapsWithShapeBottom = shapeBottomInFlowThread < logicalLineBottomInFlowThread;
+ bool lineOverLapsWithRegionBottom = logicalLineBottomInFlowThread > logicalRegionBottomInFlowThread;
+ bool overFlowsToNextRegion = nextRegion && (lineOverLapsWithShapeBottom || lineOverLapsWithRegionBottom);
+ // If the line is between two shapes/regions we position the line to the top of the next shape/region
+ if (overFlowsToNextRegion) {
ASSERT(currentRegion != nextRegion);
-
- shapeInsideInfo = nextRegion->shapeInsideInfo();
+ LayoutUnit deltaToNextRegion = logicalRegionBottomInFlowThread - logicalLineTopInFlowThread;
setLogicalHeight(logicalHeight() + deltaToNextRegion);
currentRegion = nextRegion;
+ shapeInsideInfo = currentRegion->shapeInsideInfo();
logicalLineTopInFlowThread = logicalHeight() + offsetFromLogicalTopOfFirstPage();
logicalLineBottomInFlowThread = logicalLineTopInFlowThread + lineHeight;
@@ -1580,10 +1332,12 @@ void RenderBlock::updateShapeAndSegmentsForCurrentLineInFlowThread(ShapeInsideIn
if (!shapeInsideInfo)
return;
+ bool isFirstLineInRegion = logicalLineBottomInFlowThread <= (logicalRegionTopInFlowThread + lineHeight);
+ bool isFirstLineAdjusted = (logicalLineTopInFlowThread - logicalRegionTopInFlowThread) < (layoutState.adjustedLogicalLineTop() - currentRegion->borderAndPaddingBefore());
// We position the first line to the top of the shape in the region or to the previously adjusted position in the shape
- if (logicalLineBottomInFlowThread <= (logicalRegionTopInFlowThread + lineHeight) || (logicalLineTopInFlowThread - logicalRegionTopInFlowThread) < (layoutState.adjustedLogicalLineTop() - currentRegion->borderAndPaddingBefore())) {
+ if (isFirstLineInRegion || isFirstLineAdjusted) {
LayoutUnit shapeTopOffset = layoutState.adjustedLogicalLineTop();
- if (!shapeTopOffset)
+ if (!shapeTopOffset && (shapeInsideInfo->shapeLogicalTop() > 0))
shapeTopOffset = shapeInsideInfo->shapeLogicalTop();
LayoutUnit shapePositionInFlowThread = currentRegion->logicalTopForFlowThreadContent() + shapeTopOffset;
@@ -1596,15 +1350,25 @@ void RenderBlock::updateShapeAndSegmentsForCurrentLineInFlowThread(ShapeInsideIn
LayoutUnit lineTop = logicalLineTopInFlowThread - currentRegion->logicalTopForFlowThreadContent() + currentRegion->borderAndPaddingBefore();
// FIXME: Shape inside on a region does not yet take into account its padding for nested flow blocks
- shapeInsideInfo->computeSegmentsForLine(LayoutSize(0, lineTop), lineHeight);
+ shapeInsideInfo->updateSegmentsForLine(LayoutSize(0, lineTop), lineHeight);
if (currentRegion->isLastRegion())
pushShapeContentOverflowBelowTheContentBox(this, shapeInsideInfo, lineTop, lineHeight);
}
-bool RenderBlock::adjustLogicalLineTopAndLogicalHeightIfNeeded(ShapeInsideInfo* shapeInsideInfo, LayoutUnit absoluteLogicalTop, LineLayoutState& layoutState, InlineBidiResolver& resolver, FloatingObject* lastFloatFromPreviousLine, InlineIterator& end, WordMeasurements& wordMeasurements)
+bool RenderBlockFlow::adjustLogicalLineTopAndLogicalHeightIfNeeded(ShapeInsideInfo* shapeInsideInfo, LayoutUnit absoluteLogicalTop, LineLayoutState& layoutState, InlineBidiResolver& resolver, FloatingObject* lastFloatFromPreviousLine, InlineIterator& end, WordMeasurements& wordMeasurements)
{
LayoutUnit adjustedLogicalLineTop = adjustLogicalLineTop(shapeInsideInfo, resolver.position(), end, wordMeasurements);
+
+ if (shapeInsideInfo && containsFloats()) {
+ lastFloatFromPreviousLine = m_floatingObjects->set().last();
+ if (!wordMeasurements.size()) {
+ LayoutUnit floatLogicalTopOffset = shapeInsideInfo->computeFirstFitPositionForFloat(logicalSizeForFloat(lastFloatFromPreviousLine));
+ if (logicalHeight() < floatLogicalTopOffset)
+ adjustedLogicalLineTop = floatLogicalTopOffset;
+ }
+ }
+
if (!adjustedLogicalLineTop)
return false;
@@ -1615,17 +1379,16 @@ bool RenderBlock::adjustLogicalLineTopAndLogicalHeightIfNeeded(ShapeInsideInfo*
newLogicalHeight = logicalHeight();
}
-
end = restartLayoutRunsAndFloatsInRange(logicalHeight(), newLogicalHeight, lastFloatFromPreviousLine, resolver, end);
return true;
}
-void RenderBlock::layoutRunsAndFloatsInRange(LineLayoutState& layoutState, InlineBidiResolver& resolver, const InlineIterator& cleanLineStart, const BidiStatus& cleanLineBidiStatus, unsigned consecutiveHyphenatedLines)
+void RenderBlockFlow::layoutRunsAndFloatsInRange(LineLayoutState& layoutState, InlineBidiResolver& resolver, const InlineIterator& cleanLineStart, const BidiStatus& cleanLineBidiStatus, unsigned consecutiveHyphenatedLines)
{
RenderStyle* styleToUse = style();
bool paginated = view()->layoutState() && view()->layoutState()->isPaginated();
LineMidpointState& lineMidpointState = resolver.midpointState();
- InlineIterator end = resolver.position();
+ InlineIterator endOfLine = resolver.position();
bool checkForEndLineMatch = layoutState.endLine();
RenderTextInfo renderTextInfo;
VerticalPositionCache verticalPositionCache;
@@ -1635,7 +1398,7 @@ void RenderBlock::layoutRunsAndFloatsInRange(LineLayoutState& layoutState, Inlin
LayoutSize logicalOffsetFromShapeContainer;
ShapeInsideInfo* shapeInsideInfo = layoutShapeInsideInfo();
if (shapeInsideInfo) {
- ASSERT(shapeInsideInfo->owner() == this || allowsShapeInsideInfoSharing());
+ ASSERT(shapeInsideInfo->owner() == this || allowsShapeInsideInfoSharing(shapeInsideInfo->owner()));
if (shapeInsideInfo != this->shapeInsideInfo()) {
// FIXME Bug 100284: If subsequent LayoutStates are pushed, we will have to add
// their offsets from the original shape-inside container.
@@ -1650,7 +1413,7 @@ void RenderBlock::layoutRunsAndFloatsInRange(LineLayoutState& layoutState, Inlin
}
}
- while (!end.atEnd()) {
+ while (!endOfLine.atEnd()) {
// FIXME: Is this check necessary before the first iteration or can it be moved to the end?
if (checkForEndLineMatch) {
layoutState.setEndLineMatched(matchedEndLine(layoutState, resolver, cleanLineStart, cleanLineBidiStatus));
@@ -1665,14 +1428,14 @@ void RenderBlock::layoutRunsAndFloatsInRange(LineLayoutState& layoutState, Inlin
layoutState.lineInfo().setEmpty(true);
layoutState.lineInfo().resetRunsFromLeadingWhitespace();
- const InlineIterator oldEnd = end;
+ const InlineIterator previousEndofLine = endOfLine;
bool isNewUBAParagraph = layoutState.lineInfo().previousLineBrokeCleanly();
FloatingObject* lastFloatFromPreviousLine = (containsFloats()) ? m_floatingObjects->set().last() : 0;
updateShapeAndSegmentsForCurrentLine(shapeInsideInfo, logicalOffsetFromShapeContainer, layoutState);
WordMeasurements wordMeasurements;
- end = lineBreaker.nextLineBreak(resolver, layoutState.lineInfo(), renderTextInfo, lastFloatFromPreviousLine, consecutiveHyphenatedLines, wordMeasurements);
+ endOfLine = lineBreaker.nextLineBreak(resolver, layoutState.lineInfo(), renderTextInfo, lastFloatFromPreviousLine, consecutiveHyphenatedLines, wordMeasurements);
renderTextInfo.m_lineBreakIterator.resetPriorContext();
if (resolver.position().atEnd()) {
// FIXME: We shouldn't be creating any runs in nextLineBreak to begin with!
@@ -1684,15 +1447,15 @@ void RenderBlock::layoutRunsAndFloatsInRange(LineLayoutState& layoutState, Inlin
break;
}
- if (adjustLogicalLineTopAndLogicalHeightIfNeeded(shapeInsideInfo, logicalOffsetFromShapeContainer.height(), layoutState, resolver, lastFloatFromPreviousLine, end, wordMeasurements))
+ if (adjustLogicalLineTopAndLogicalHeightIfNeeded(shapeInsideInfo, logicalOffsetFromShapeContainer.height(), layoutState, resolver, lastFloatFromPreviousLine, endOfLine, wordMeasurements))
continue;
- ASSERT(end != resolver.position());
+ ASSERT(endOfLine != resolver.position());
// This is a short-cut for empty lines.
if (layoutState.lineInfo().isEmpty()) {
if (lastRootBox())
- lastRootBox()->setLineBreakInfo(end.m_obj, end.m_pos, resolver.status());
+ lastRootBox()->setLineBreakInfo(endOfLine.object(), endOfLine.m_pos, resolver.status());
} else {
VisualDirectionOverride override = (styleToUse->rtlOrdering() == VisualOrder ? (styleToUse->direction() == LTR ? VisualLeftToRightOverride : VisualRightToLeftOverride) : NoVisualOverride);
@@ -1702,8 +1465,8 @@ void RenderBlock::layoutRunsAndFloatsInRange(LineLayoutState& layoutState, Inlin
}
// FIXME: This ownership is reversed. We should own the BidiRunList and pass it to createBidiRunsForLine.
BidiRunList<BidiRun>& bidiRuns = resolver.runs();
- constructBidiRunsForLine(this, resolver, bidiRuns, end, override, layoutState.lineInfo().previousLineBrokeCleanly());
- ASSERT(resolver.position() == end);
+ constructBidiRunsForLine(this, resolver, bidiRuns, endOfLine, override, layoutState.lineInfo().previousLineBrokeCleanly(), isNewUBAParagraph);
+ ASSERT(resolver.position() == endOfLine);
BidiRun* trailingSpaceRun = !layoutState.lineInfo().previousLineBrokeCleanly() ? handleTrailingSpaces(bidiRuns, resolver.context()) : 0;
@@ -1718,13 +1481,13 @@ void RenderBlock::layoutRunsAndFloatsInRange(LineLayoutState& layoutState, Inlin
// inline flow boxes.
LayoutUnit oldLogicalHeight = logicalHeight();
- RootInlineBox* lineBox = createLineBoxesFromBidiRuns(resolver.status().context->level(), bidiRuns, end, layoutState.lineInfo(), verticalPositionCache, trailingSpaceRun, wordMeasurements);
+ RootInlineBox* lineBox = createLineBoxesFromBidiRuns(resolver.status().context->level(), bidiRuns, endOfLine, layoutState.lineInfo(), verticalPositionCache, trailingSpaceRun, wordMeasurements);
bidiRuns.deleteRuns();
resolver.markCurrentRunEmpty(); // FIXME: This can probably be replaced by an ASSERT (or just removed).
if (lineBox) {
- lineBox->setLineBreakInfo(end.m_obj, end.m_pos, resolver.status());
+ lineBox->setLineBreakInfo(endOfLine.object(), endOfLine.m_pos, resolver.status());
if (layoutState.usesRepaintBounds())
layoutState.updateRepaintRangeFromBox(lineBox);
@@ -1740,7 +1503,7 @@ void RenderBlock::layoutRunsAndFloatsInRange(LineLayoutState& layoutState, Inlin
if (availableLogicalWidthForLine(oldLogicalHeight + adjustment, layoutState.lineInfo().isFirstLine()) != oldLineWidth) {
// We have to delete this line, remove all floats that got added, and let line layout re-run.
lineBox->deleteLine();
- end = restartLayoutRunsAndFloatsInRange(oldLogicalHeight, oldLogicalHeight + adjustment, lastFloatFromPreviousLine, resolver, oldEnd);
+ endOfLine = restartLayoutRunsAndFloatsInRange(oldLogicalHeight, oldLogicalHeight + adjustment, lastFloatFromPreviousLine, resolver, previousEndofLine);
continue;
}
@@ -1748,7 +1511,7 @@ void RenderBlock::layoutRunsAndFloatsInRange(LineLayoutState& layoutState, Inlin
}
if (layoutState.flowThread())
- lineBox->setContainingRegion(regionAtBlockOffset(lineBox->lineTopWithLeading()));
+ updateRegionForLine(lineBox);
}
}
}
@@ -1758,7 +1521,7 @@ void RenderBlock::layoutRunsAndFloatsInRange(LineLayoutState& layoutState, Inlin
if (!layoutState.lineInfo().isEmpty()) {
layoutState.lineInfo().setFirstLine(false);
- newLine(lineBreaker.clear());
+ clearFloats(lineBreaker.clear());
}
if (m_floatingObjects && lastRootBox()) {
@@ -1784,10 +1547,13 @@ void RenderBlock::layoutRunsAndFloatsInRange(LineLayoutState& layoutState, Inlin
}
lineMidpointState.reset();
- resolver.setPosition(end, numberOfIsolateAncestors(end));
+ resolver.setPosition(endOfLine, numberOfIsolateAncestors(endOfLine));
}
- if (paginated && !style()->hasAutoWidows()) {
+ // In case we already adjusted the line positions during this layout to avoid widows
+ // then we need to ignore the possibility of having a new widows situation.
+ // Otherwise, we risk leaving empty containers which is against the block fragmentation principles.
+ if (paginated && !style()->hasAutoWidows() && !didBreakAtLineToAvoidWidow()) {
// Check the line boxes to make sure we didn't create unacceptable widows.
// However, we'll prioritize orphans - so nothing we do here should create
// a new orphan.
@@ -1839,13 +1605,15 @@ void RenderBlock::layoutRunsAndFloatsInRange(LineLayoutState& layoutState, Inlin
lineBox = lineBox->prevRootBox();
// We now want to break at this line. Remember for next layout and trigger relayout.
- setBreakAtLineToAvoidWidow(lineBox);
+ setBreakAtLineToAvoidWidow(lineCount(lineBox));
markLinesDirtyInBlockRange(lastRootBox()->lineBottomWithLeading(), lineBox->lineBottomWithLeading(), lineBox);
}
}
+
+ clearDidBreakAtLineToAvoidWidow();
}
-void RenderBlock::linkToEndLineIfNeeded(LineLayoutState& layoutState)
+void RenderBlockFlow::linkToEndLineIfNeeded(LineLayoutState& layoutState)
{
if (layoutState.endLine()) {
if (layoutState.endLineMatched()) {
@@ -1863,7 +1631,7 @@ void RenderBlock::linkToEndLineIfNeeded(LineLayoutState& layoutState)
line->adjustBlockDirectionPosition(delta);
}
if (layoutState.flowThread())
- line->setContainingRegion(regionAtBlockOffset(line->lineTopWithLeading()));
+ updateRegionForLine(line);
if (Vector<RenderBox*>* cleanLineFloats = line->floatsPtr()) {
Vector<RenderBox*>::iterator end = cleanLineFloats->end();
for (Vector<RenderBox*>::iterator f = cleanLineFloats->begin(); f != end; ++f) {
@@ -1902,7 +1670,7 @@ void RenderBlock::linkToEndLineIfNeeded(LineLayoutState& layoutState)
LayoutRect logicalVisualOverflow(0, blockLogicalHeight, 1, bottomVisualOverflow - blockLogicalHeight);
trailingFloatsLineBox->setOverflowFromLogicalRects(logicalLayoutOverflow, logicalVisualOverflow, trailingFloatsLineBox->lineTop(), trailingFloatsLineBox->lineBottom());
if (layoutState.flowThread())
- trailingFloatsLineBox->setContainingRegion(regionAtBlockOffset(trailingFloatsLineBox->lineTopWithLeading()));
+ updateRegionForLine(trailingFloatsLineBox);
}
const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
@@ -1920,7 +1688,7 @@ void RenderBlock::linkToEndLineIfNeeded(LineLayoutState& layoutState)
}
}
-void RenderBlock::repaintDirtyFloats(Vector<FloatWithRect>& floats)
+void RenderBlockFlow::repaintDirtyFloats(Vector<FloatWithRect>& floats)
{
size_t floatCount = floats.size();
// Floats that did not have layout did not repaint when we laid them out. They would have
@@ -1929,14 +1697,22 @@ void RenderBlock::repaintDirtyFloats(Vector<FloatWithRect>& floats)
for (size_t i = 0; i < floatCount; ++i) {
if (!floats[i].everHadLayout) {
RenderBox* f = floats[i].object;
- if (!f->x() && !f->y() && f->checkForRepaintDuringLayout())
- f->repaint();
+ if (!f->x() && !f->y() && f->checkForRepaintDuringLayout()) {
+ if (RuntimeEnabledFeatures::repaintAfterLayoutEnabled())
+ f->setShouldDoFullRepaintAfterLayout(true);
+ else
+ f->repaint();
+ }
}
}
}
void RenderBlockFlow::layoutInlineChildren(bool relayoutChildren, LayoutUnit& repaintLogicalTop, LayoutUnit& repaintLogicalBottom)
{
+ FastTextAutosizer* textAutosizer = document().fastTextAutosizer();
+ if (textAutosizer)
+ textAutosizer->inflate(this);
+
setLogicalHeight(borderBefore() + paddingBefore());
// Lay out our hypothetical grid line as though it occurs at the top of the block.
@@ -1980,6 +1756,9 @@ void RenderBlockFlow::layoutInlineChildren(bool relayoutChildren, LayoutUnit& re
Vector<RenderBox*> replacedChildren;
for (InlineWalker walker(this); !walker.atEnd(); walker.advance()) {
RenderObject* o = walker.current();
+
+ LayoutRectRecorder recorder(*o, !o->isText());
+
if (!hasInlineChild && o->isInline())
hasInlineChild = true;
@@ -2042,7 +1821,7 @@ void RenderBlockFlow::layoutInlineChildren(bool relayoutChildren, LayoutUnit& re
checkLinesForTextOverflow();
}
-void RenderBlock::checkFloatsInCleanLine(RootInlineBox* line, Vector<FloatWithRect>& floats, size_t& floatIndex, bool& encounteredNewFloat, bool& dirtiedByFloat)
+void RenderBlockFlow::checkFloatsInCleanLine(RootInlineBox* line, Vector<FloatWithRect>& floats, size_t& floatIndex, bool& encounteredNewFloat, bool& dirtiedByFloat)
{
Vector<RenderBox*>* cleanLineFloats = line->floatsPtr();
if (!cleanLineFloats)
@@ -2072,7 +1851,7 @@ void RenderBlock::checkFloatsInCleanLine(RootInlineBox* line, Vector<FloatWithRe
}
}
-RootInlineBox* RenderBlock::determineStartPosition(LineLayoutState& layoutState, InlineBidiResolver& resolver)
+RootInlineBox* RenderBlockFlow::determineStartPosition(LineLayoutState& layoutState, InlineBidiResolver& resolver)
{
RootInlineBox* curr = 0;
RootInlineBox* last = 0;
@@ -2103,7 +1882,7 @@ RootInlineBox* RenderBlock::determineStartPosition(LineLayoutState& layoutState,
curr->adjustBlockDirectionPosition(paginationDelta);
}
if (layoutState.flowThread())
- curr->setContainingRegion(regionAtBlockOffset(curr->lineTopWithLeading()));
+ updateRegionForLine(curr);
}
// If a new float has been inserted before this line or before its last known float, just do a full layout.
@@ -2195,7 +1974,7 @@ RootInlineBox* RenderBlock::determineStartPosition(LineLayoutState& layoutState,
return curr;
}
-void RenderBlock::determineEndPosition(LineLayoutState& layoutState, RootInlineBox* startLine, InlineIterator& cleanLineStart, BidiStatus& cleanLineBidiStatus)
+void RenderBlockFlow::determineEndPosition(LineLayoutState& layoutState, RootInlineBox* startLine, InlineIterator& cleanLineStart, BidiStatus& cleanLineBidiStatus)
{
ASSERT(!layoutState.endLine());
size_t floatIndex = layoutState.floatIndex();
@@ -2232,7 +2011,7 @@ void RenderBlock::determineEndPosition(LineLayoutState& layoutState, RootInlineB
layoutState.setEndLine(last);
}
-bool RenderBlock::checkPaginationAndFloatsAtEndLine(LineLayoutState& layoutState)
+bool RenderBlockFlow::checkPaginationAndFloatsAtEndLine(LineLayoutState& layoutState)
{
LayoutUnit lineDelta = logicalHeight() - layoutState.endLineLogicalTop();
@@ -2269,15 +2048,15 @@ bool RenderBlock::checkPaginationAndFloatsAtEndLine(LineLayoutState& layoutState
const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
FloatingObjectSetIterator end = floatingObjectSet.end();
for (FloatingObjectSetIterator it = floatingObjectSet.begin(); it != end; ++it) {
- FloatingObject* f = *it;
- if (f->logicalBottom(isHorizontalWritingMode()) >= logicalTop && f->logicalBottom(isHorizontalWritingMode()) < logicalBottom)
+ FloatingObject* floatingObject = *it;
+ if (logicalBottomForFloat(floatingObject) >= logicalTop && logicalBottomForFloat(floatingObject) < logicalBottom)
return false;
}
return true;
}
-bool RenderBlock::matchedEndLine(LineLayoutState& layoutState, const InlineBidiResolver& resolver, const InlineIterator& endLineStart, const BidiStatus& endLineStatus)
+bool RenderBlockFlow::matchedEndLine(LineLayoutState& layoutState, const InlineBidiResolver& resolver, const InlineIterator& endLineStart, const BidiStatus& endLineStatus)
{
if (resolver.position() == endLineStart) {
if (resolver.status() != endLineStatus)
@@ -2291,7 +2070,7 @@ bool RenderBlock::matchedEndLine(LineLayoutState& layoutState, const InlineBidiR
RootInlineBox* originalEndLine = layoutState.endLine();
RootInlineBox* line = originalEndLine;
for (int i = 0; i < numLines && line; i++, line = line->nextRootBox()) {
- if (line->lineBreakObj() == resolver.position().m_obj && line->lineBreakPos() == resolver.position().m_pos) {
+ if (line->lineBreakObj() == resolver.position().object() && line->lineBreakPos() == resolver.position().m_pos) {
// We have a match.
if (line->lineBreakBidiStatus() != resolver.status())
return false; // ...but the bidi state doesn't match.
@@ -2313,53 +2092,8 @@ bool RenderBlock::matchedEndLine(LineLayoutState& layoutState, const InlineBidiR
return false;
}
-enum WhitespacePosition { LeadingWhitespace, TrailingWhitespace };
-static inline bool shouldCollapseWhiteSpace(const RenderStyle* style, const LineInfo& lineInfo, WhitespacePosition whitespacePosition)
-{
- // CSS2 16.6.1
- // If a space (U+0020) at the beginning of a line has 'white-space' set to 'normal', 'nowrap', or 'pre-line', it is removed.
- // If a space (U+0020) at the end of a line has 'white-space' set to 'normal', 'nowrap', or 'pre-line', it is also removed.
- // If spaces (U+0020) or tabs (U+0009) at the end of a line have 'white-space' set to 'pre-wrap', UAs may visually collapse them.
- return style->collapseWhiteSpace()
- || (whitespacePosition == TrailingWhitespace && style->whiteSpace() == PRE_WRAP && (!lineInfo.isEmpty() || !lineInfo.previousLineBrokeCleanly()));
-}
-
-static bool requiresLineBoxForContent(RenderInline* flow, const LineInfo& lineInfo)
-{
- RenderObject* parent = flow->parent();
- if (flow->document().inNoQuirksMode()
- && (flow->style(lineInfo.isFirstLine())->lineHeight() != parent->style(lineInfo.isFirstLine())->lineHeight()
- || flow->style()->verticalAlign() != parent->style()->verticalAlign()
- || !parent->style()->font().fontMetrics().hasIdenticalAscentDescentAndLineGap(flow->style()->font().fontMetrics())))
- return true;
- return false;
-}
-
-static bool alwaysRequiresLineBox(RenderObject* flow)
-{
- // FIXME: Right now, we only allow line boxes for inlines that are truly empty.
- // We need to fix this, though, because at the very least, inlines containing only
- // ignorable whitespace should should also have line boxes.
- return isEmptyInline(flow) && toRenderInline(flow)->hasInlineDirectionBordersPaddingOrMargin();
-}
-
-static bool requiresLineBox(const InlineIterator& it, const LineInfo& lineInfo = LineInfo(), WhitespacePosition whitespacePosition = LeadingWhitespace)
-{
- if (it.m_obj->isFloatingOrOutOfFlowPositioned())
- return false;
-
- if (it.m_obj->isRenderInline() && !alwaysRequiresLineBox(it.m_obj) && !requiresLineBoxForContent(toRenderInline(it.m_obj), lineInfo))
- return false;
-
- if (!shouldCollapseWhiteSpace(it.m_obj->style(), lineInfo, whitespacePosition) || it.m_obj->isBR())
- return true;
-
- UChar current = it.current();
- bool notJustWhitespace = current != ' ' && current != '\t' && current != softHyphen && (current != '\n' || it.m_obj->preservesNewline());
- return notJustWhitespace || isEmptyInline(it.m_obj);
-}
+bool RenderBlockFlow::generatesLineBoxesForInlineChild(RenderObject* inlineObj)
-bool RenderBlock::generatesLineBoxesForInlineChild(RenderObject* inlineObj)
{
ASSERT(inlineObj->parent() == this);
@@ -2371,44 +2105,20 @@ bool RenderBlock::generatesLineBoxesForInlineChild(RenderObject* inlineObj)
return !it.atEnd();
}
-// FIXME: The entire concept of the skipTrailingWhitespace function is flawed, since we really need to be building
-// line boxes even for containers that may ultimately collapse away. Otherwise we'll never get positioned
-// elements quite right. In other words, we need to build this function's work into the normal line
-// object iteration process.
-// NB. this function will insert any floating elements that would otherwise
-// be skipped but it will not position them.
-void LineBreaker::skipTrailingWhitespace(InlineIterator& iterator, const LineInfo& lineInfo)
-{
- while (!iterator.atEnd() && !requiresLineBox(iterator, lineInfo, TrailingWhitespace)) {
- RenderObject* object = iterator.m_obj;
- if (object->isOutOfFlowPositioned())
- setStaticPositions(m_block, toRenderBox(object));
- else if (object->isFloating())
- m_block->insertFloatingObject(toRenderBox(object));
- iterator.increment();
- }
-}
-
void LineBreaker::skipLeadingWhitespace(InlineBidiResolver& resolver, LineInfo& lineInfo,
FloatingObject* lastFloatFromPreviousLine, LineWidth& width)
{
while (!resolver.position().atEnd() && !requiresLineBox(resolver.position(), lineInfo, LeadingWhitespace)) {
- RenderObject* object = resolver.position().m_obj;
+ RenderObject* object = resolver.position().object();
if (object->isOutOfFlowPositioned()) {
setStaticPositions(m_block, toRenderBox(object));
if (object->style()->isOriginalDisplayInlineType()) {
resolver.runs().addRun(createRun(0, 1, object, resolver));
lineInfo.incrementRunsFromLeadingWhitespace();
}
- } else if (object->isFloating()) {
- // The top margin edge of a self-collapsing block that clears a float intrudes up into it by the height of the margin,
- // so in order to place this first child float at the top content edge of the self-collapsing block add the margin back in before placement.
- LayoutUnit marginOffset = (!object->previousSibling() && m_block->isSelfCollapsingBlock() && m_block->style()->clear() && m_block->getClearDelta(m_block, LayoutUnit())) ? m_block->collapsedMarginBeforeForChild(m_block) : LayoutUnit();
- LayoutUnit oldLogicalHeight = m_block->logicalHeight();
- m_block->setLogicalHeight(oldLogicalHeight + marginOffset);
+ } else if (object->isFloating())
m_block->positionNewFloatOnLine(m_block->insertFloatingObject(toRenderBox(object)), lastFloatFromPreviousLine, lineInfo, width);
- m_block->setLogicalHeight(oldLogicalHeight);
- } else if (object->isText() && object->style()->hasTextCombine() && object->isCombineText() && !toRenderCombineText(object)->isCombined()) {
+ else if (object->isText() && object->style()->hasTextCombine() && object->isCombineText() && !toRenderCombineText(object)->isCombined()) {
toRenderCombineText(object)->combineText();
if (toRenderCombineText(object)->isCombined())
continue;
@@ -2418,129 +2128,6 @@ void LineBreaker::skipLeadingWhitespace(InlineBidiResolver& resolver, LineInfo&
resolver.commitExplicitEmbedding();
}
-// This is currently just used for list markers and inline flows that have line boxes. Neither should
-// have an effect on whitespace at the start of the line.
-static bool shouldSkipWhitespaceAfterStartObject(RenderBlock* block, RenderObject* o, LineMidpointState& lineMidpointState)
-{
- RenderObject* next = bidiNextSkippingEmptyInlines(block, o);
- while (next && next->isFloatingOrOutOfFlowPositioned())
- next = bidiNextSkippingEmptyInlines(block, next);
-
- if (next && !next->isBR() && next->isText() && toRenderText(next)->textLength() > 0) {
- RenderText* nextText = toRenderText(next);
- UChar nextChar = nextText->characterAt(0);
- if (nextText->style()->isCollapsibleWhiteSpace(nextChar)) {
- startIgnoringSpaces(lineMidpointState, InlineIterator(0, o, 0));
- return true;
- }
- }
-
- return false;
-}
-
-static ALWAYS_INLINE float textWidth(RenderText* text, unsigned from, unsigned len, const Font& font, float xPos, bool isFixedPitch, bool collapseWhiteSpace, HashSet<const SimpleFontData*>* fallbackFonts = 0, TextLayout* layout = 0)
-{
- GlyphOverflow glyphOverflow;
- if (isFixedPitch || (!from && len == text->textLength()) || text->style()->hasTextCombine())
- return text->width(from, len, font, xPos, fallbackFonts, &glyphOverflow);
-
- if (layout)
- return Font::width(*layout, from, len, fallbackFonts);
-
- TextRun run = RenderBlock::constructTextRun(text, font, text, from, len, text->style());
- run.setCharactersLength(text->textLength() - from);
- ASSERT(run.charactersLength() >= run.length());
-
- run.setCharacterScanForCodePath(!text->canUseSimpleFontCodePath());
- run.setTabSize(!collapseWhiteSpace, text->style()->tabSize());
- run.setXPos(xPos);
- return font.width(run, fallbackFonts, &glyphOverflow);
-}
-
-class TrailingObjects {
-public:
- TrailingObjects();
- void setTrailingWhitespace(RenderText*);
- void clear();
- void appendBoxIfNeeded(RenderBox*);
-
- enum CollapseFirstSpaceOrNot { DoNotCollapseFirstSpace, CollapseFirstSpace };
-
- void updateMidpointsForTrailingBoxes(LineMidpointState&, const InlineIterator& lBreak, CollapseFirstSpaceOrNot);
-
-private:
- RenderText* m_whitespace;
- Vector<RenderBox*, 4> m_boxes;
-};
-
-TrailingObjects::TrailingObjects()
- : m_whitespace(0)
-{
-}
-
-inline void TrailingObjects::setTrailingWhitespace(RenderText* whitespace)
-{
- ASSERT(whitespace);
- m_whitespace = whitespace;
-}
-
-inline void TrailingObjects::clear()
-{
- m_whitespace = 0;
- // Using resize(0) rather than clear() here saves 2% on
- // PerformanceTests/Layout/line-layout.html because we avoid freeing and
- // re-allocating the underlying buffer repeatedly.
- m_boxes.resize(0);
-}
-
-inline void TrailingObjects::appendBoxIfNeeded(RenderBox* box)
-{
- if (m_whitespace)
- m_boxes.append(box);
-}
-
-void TrailingObjects::updateMidpointsForTrailingBoxes(LineMidpointState& lineMidpointState, const InlineIterator& lBreak, CollapseFirstSpaceOrNot collapseFirstSpace)
-{
- if (!m_whitespace)
- return;
-
- // This object is either going to be part of the last midpoint, or it is going to be the actual endpoint.
- // In both cases we just decrease our pos by 1 level to exclude the space, allowing it to - in effect - collapse into the newline.
- if (lineMidpointState.numMidpoints % 2) {
- // Find the trailing space object's midpoint.
- int trailingSpaceMidpoint = lineMidpointState.numMidpoints - 1;
- for ( ; trailingSpaceMidpoint > 0 && lineMidpointState.midpoints[trailingSpaceMidpoint].m_obj != m_whitespace; --trailingSpaceMidpoint) { }
- ASSERT(trailingSpaceMidpoint >= 0);
- if (collapseFirstSpace == CollapseFirstSpace)
- lineMidpointState.midpoints[trailingSpaceMidpoint].m_pos--;
-
- // Now make sure every single trailingPositionedBox following the trailingSpaceMidpoint properly stops and starts
- // ignoring spaces.
- size_t currentMidpoint = trailingSpaceMidpoint + 1;
- for (size_t i = 0; i < m_boxes.size(); ++i) {
- if (currentMidpoint >= lineMidpointState.numMidpoints) {
- // We don't have a midpoint for this box yet.
- ensureLineBoxInsideIgnoredSpaces(lineMidpointState, m_boxes[i]);
- } else {
- ASSERT(lineMidpointState.midpoints[currentMidpoint].m_obj == m_boxes[i]);
- ASSERT(lineMidpointState.midpoints[currentMidpoint + 1].m_obj == m_boxes[i]);
- }
- currentMidpoint += 2;
- }
- } else if (!lBreak.m_obj) {
- ASSERT(m_whitespace->isText());
- ASSERT(collapseFirstSpace == CollapseFirstSpace);
- // Add a new end midpoint that stops right at the very end.
- unsigned length = m_whitespace->textLength();
- unsigned pos = length >= 2 ? length - 2 : UINT_MAX;
- InlineIterator endMid(0, m_whitespace, pos);
- startIgnoringSpaces(lineMidpointState, endMid);
- for (size_t i = 0; i < m_boxes.size(); ++i) {
- ensureLineBoxInsideIgnoredSpaces(lineMidpointState, m_boxes[i]);
- }
- }
-}
-
void LineBreaker::reset()
{
m_positionedObjects.clear();
@@ -2598,11 +2185,6 @@ InlineIterator LineBreaker::nextLineBreak(InlineBidiResolver& resolver, LineInfo
return end;
}
-static inline bool iteratorIsBeyondEndOfRenderCombineText(const InlineIterator& iter, RenderCombineText* renderer)
-{
- return iter.m_obj == renderer && iter.m_pos >= renderer->textLength();
-}
-
InlineIterator LineBreaker::nextSegmentBreak(InlineBidiResolver& resolver, LineInfo& lineInfo, RenderTextInfo& renderTextInfo, FloatingObject* lastFloatFromPreviousLine, unsigned consecutiveHyphenatedLines, WordMeasurements& wordMeasurements)
{
reset();
@@ -2610,8 +2192,6 @@ InlineIterator LineBreaker::nextSegmentBreak(InlineBidiResolver& resolver, LineI
ASSERT(resolver.position().root() == m_block);
bool appliedStartWidth = resolver.position().m_pos > 0;
- bool includeEndWidth = true;
- LineMidpointState& lineMidpointState = resolver.midpointState();
LineWidth width(*m_block, lineInfo.isFirstLine(), requiresIndent(lineInfo.isFirstLine(), lineInfo.previousLineBrokeCleanly(), m_block->style()));
@@ -2620,593 +2200,46 @@ InlineIterator LineBreaker::nextSegmentBreak(InlineBidiResolver& resolver, LineI
if (resolver.position().atEnd())
return resolver.position();
- // This variable is used only if whitespace isn't set to PRE, and it tells us whether
- // or not we are currently ignoring whitespace.
- bool ignoringSpaces = false;
- InlineIterator ignoreStart;
-
- // This variable tracks whether the very last character we saw was a space. We use
- // this to detect when we encounter a second space so we know we have to terminate
- // a run.
- bool currentCharacterIsSpace = false;
- bool currentCharacterShouldCollapseIfPreWap = false;
- TrailingObjects trailingObjects;
-
- InlineIterator lBreak = resolver.position();
-
- // FIXME: It is error-prone to split the position object out like this.
- // Teach this code to work with objects instead of this split tuple.
- InlineIterator current = resolver.position();
- RenderObject* last = current.m_obj;
- bool atStart = true;
-
- bool startingNewParagraph = lineInfo.previousLineBrokeCleanly();
- lineInfo.setPreviousLineBrokeCleanly(false);
-
- bool autoWrapWasEverTrueOnLine = false;
- bool floatsFitOnLine = true;
-
- // Firefox and Opera will allow a table cell to grow to fit an image inside it under
- // very specific circumstances (in order to match common WinIE renderings).
- // Not supporting the quirk has caused us to mis-render some real sites. (See Bugzilla 10517.)
- RenderStyle* blockStyle = m_block->style();
- bool allowImagesToBreak = !m_block->document().inQuirksMode() || !m_block->isTableCell() || !blockStyle->logicalWidth().isIntrinsicOrAuto();
-
- EWhiteSpace currWS = blockStyle->whiteSpace();
- EWhiteSpace lastWS = currWS;
- while (current.m_obj) {
- RenderStyle* currentStyle = current.m_obj->style();
- RenderObject* next = bidiNextSkippingEmptyInlines(m_block, current.m_obj);
- if (next && next->parent() && !next->parent()->isDescendantOf(current.m_obj->parent()))
- includeEndWidth = true;
-
- currWS = current.m_obj->isReplaced() ? current.m_obj->parent()->style()->whiteSpace() : currentStyle->whiteSpace();
- lastWS = last->isReplaced() ? last->parent()->style()->whiteSpace() : last->style()->whiteSpace();
-
- bool autoWrap = RenderStyle::autoWrap(currWS);
- autoWrapWasEverTrueOnLine = autoWrapWasEverTrueOnLine || autoWrap;
-
- bool preserveNewline = current.m_obj->isSVGInlineText() ? false : RenderStyle::preserveNewline(currWS);
-
- bool collapseWhiteSpace = RenderStyle::collapseWhiteSpace(currWS);
-
- if (current.m_obj->isBR()) {
- if (width.fitsOnLine()) {
- lBreak.moveToStartOf(current.m_obj);
- lBreak.increment();
-
- // A <br> always breaks a line, so don't let the line be collapsed
- // away. Also, the space at the end of a line with a <br> does not
- // get collapsed away. It only does this if the previous line broke
- // cleanly. Otherwise the <br> has no effect on whether the line is
- // empty or not.
- if (startingNewParagraph)
- lineInfo.setEmpty(false, m_block, &width);
- trailingObjects.clear();
- lineInfo.setPreviousLineBrokeCleanly(true);
-
- // A <br> with clearance always needs a linebox in case the lines below it get dirtied later and
- // need to check for floats to clear - so if we're ignoring spaces, stop ignoring them and add a
- // run for this object.
- if (ignoringSpaces && currentStyle->clear() != CNONE)
- ensureLineBoxInsideIgnoredSpaces(lineMidpointState, current.m_obj);
-
- if (!lineInfo.isEmpty())
- m_clear = currentStyle->clear();
+ BreakingContext context(resolver, lineInfo, width, renderTextInfo, lastFloatFromPreviousLine, appliedStartWidth, m_block);
+
+ while (context.currentObject()) {
+ context.initializeForCurrentObject();
+ if (context.currentObject()->isBR()) {
+ context.handleBR(m_clear);
+ } else if (context.currentObject()->isOutOfFlowPositioned()) {
+ context.handleOutOfFlowPositioned(m_positionedObjects);
+ } else if (context.currentObject()->isFloating()) {
+ context.handleFloat();
+ } else if (context.currentObject()->isRenderInline()) {
+ context.handleEmptyInline();
+ } else if (context.currentObject()->isReplaced()) {
+ context.handleReplaced();
+ } else if (context.currentObject()->isText()) {
+ if (context.handleText(wordMeasurements, m_hyphenated)) {
+ // We've hit a hard text line break. Our line break iterator is updated, so go ahead and early return.
+ return context.lineBreak();
}
- goto end;
- }
-
- if (current.m_obj->isOutOfFlowPositioned()) {
- // If our original display wasn't an inline type, then we can
- // go ahead and determine our static inline position now.
- RenderBox* box = toRenderBox(current.m_obj);
- bool isInlineType = box->style()->isOriginalDisplayInlineType();
- if (!isInlineType)
- m_block->setStaticInlinePositionForChild(box, m_block->logicalHeight(), m_block->startOffsetForContent(m_block->logicalHeight()));
- else {
- // If our original display was an INLINE type, then we can go ahead
- // and determine our static y position now.
- box->layer()->setStaticBlockPosition(m_block->logicalHeight());
- }
-
- // If we're ignoring spaces, we have to stop and include this object and
- // then start ignoring spaces again.
- if (isInlineType || current.m_obj->container()->isRenderInline()) {
- if (ignoringSpaces)
- ensureLineBoxInsideIgnoredSpaces(lineMidpointState, current.m_obj);
- trailingObjects.appendBoxIfNeeded(box);
- } else
- m_positionedObjects.append(box);
- width.addUncommittedWidth(inlineLogicalWidth(current.m_obj));
- // Reset prior line break context characters.
- renderTextInfo.m_lineBreakIterator.resetPriorContext();
- } else if (current.m_obj->isFloating()) {
- RenderBox* floatBox = toRenderBox(current.m_obj);
- FloatingObject* f = m_block->insertFloatingObject(floatBox);
- // check if it fits in the current line.
- // If it does, position it now, otherwise, position
- // it after moving to next line (in newLine() func)
- // FIXME: Bug 110372: Properly position multiple stacked floats with non-rectangular shape outside.
- if (floatsFitOnLine && width.fitsOnLine(f->logicalWidth(m_block->isHorizontalWritingMode()))) {
- m_block->positionNewFloatOnLine(f, lastFloatFromPreviousLine, lineInfo, width);
- if (lBreak.m_obj == current.m_obj) {
- ASSERT(!lBreak.m_pos);
- lBreak.increment();
- }
- } else
- floatsFitOnLine = false;
- // Update prior line break context characters, using U+FFFD (OBJECT REPLACEMENT CHARACTER) for floating element.
- renderTextInfo.m_lineBreakIterator.updatePriorContext(replacementCharacter);
- } else if (current.m_obj->isRenderInline()) {
- // Right now, we should only encounter empty inlines here.
- ASSERT(isEmptyInline(current.m_obj));
-
- RenderInline* flowBox = toRenderInline(current.m_obj);
-
- // Now that some inline flows have line boxes, if we are already ignoring spaces, we need
- // to make sure that we stop to include this object and then start ignoring spaces again.
- // If this object is at the start of the line, we need to behave like list markers and
- // start ignoring spaces.
- bool requiresLineBox = alwaysRequiresLineBox(current.m_obj);
- if (requiresLineBox || requiresLineBoxForContent(flowBox, lineInfo)) {
- // An empty inline that only has line-height, vertical-align or font-metrics will only get a
- // line box to affect the height of the line if the rest of the line is not empty.
- if (requiresLineBox)
- lineInfo.setEmpty(false, m_block, &width);
- if (ignoringSpaces) {
- trailingObjects.clear();
- ensureLineBoxInsideIgnoredSpaces(lineMidpointState, current.m_obj);
- } else if (blockStyle->collapseWhiteSpace() && resolver.position().m_obj == current.m_obj
- && shouldSkipWhitespaceAfterStartObject(m_block, current.m_obj, lineMidpointState)) {
- // Like with list markers, we start ignoring spaces to make sure that any
- // additional spaces we see will be discarded.
- currentCharacterShouldCollapseIfPreWap = currentCharacterIsSpace = true;
- ignoringSpaces = true;
- }
- }
-
- width.addUncommittedWidth(inlineLogicalWidth(current.m_obj) + borderPaddingMarginStart(flowBox) + borderPaddingMarginEnd(flowBox));
- } else if (current.m_obj->isReplaced()) {
- RenderBox* replacedBox = toRenderBox(current.m_obj);
-
- if (atStart)
- width.updateAvailableWidth(replacedBox->logicalHeight());
-
- // Break on replaced elements if either has normal white-space.
- if ((autoWrap || RenderStyle::autoWrap(lastWS)) && (!current.m_obj->isImage() || allowImagesToBreak)) {
- width.commit();
- lBreak.moveToStartOf(current.m_obj);
- }
-
- if (ignoringSpaces)
- stopIgnoringSpaces(lineMidpointState, InlineIterator(0, current.m_obj, 0));
-
- lineInfo.setEmpty(false, m_block, &width);
- ignoringSpaces = false;
- currentCharacterShouldCollapseIfPreWap = currentCharacterIsSpace = false;
- trailingObjects.clear();
-
- // Optimize for a common case. If we can't find whitespace after the list
- // item, then this is all moot.
- LayoutUnit replacedLogicalWidth = m_block->logicalWidthForChild(replacedBox) + m_block->marginStartForChild(replacedBox) + m_block->marginEndForChild(replacedBox) + inlineLogicalWidth(current.m_obj);
- if (current.m_obj->isListMarker()) {
- if (blockStyle->collapseWhiteSpace() && shouldSkipWhitespaceAfterStartObject(m_block, current.m_obj, lineMidpointState)) {
- // Like with inline flows, we start ignoring spaces to make sure that any
- // additional spaces we see will be discarded.
- currentCharacterShouldCollapseIfPreWap = currentCharacterIsSpace = true;
- ignoringSpaces = true;
- }
- if (toRenderListMarker(current.m_obj)->isInside())
- width.addUncommittedWidth(replacedLogicalWidth);
- } else
- width.addUncommittedWidth(replacedLogicalWidth);
- if (current.m_obj->isRubyRun())
- width.applyOverhang(toRenderRubyRun(current.m_obj), last, next);
- // Update prior line break context characters, using U+FFFD (OBJECT REPLACEMENT CHARACTER) for replaced element.
- renderTextInfo.m_lineBreakIterator.updatePriorContext(replacementCharacter);
- } else if (current.m_obj->isText()) {
- if (!current.m_pos)
- appliedStartWidth = false;
-
- RenderText* t = toRenderText(current.m_obj);
-
- bool isSVGText = t->isSVGInlineText();
-
- if (t->style()->hasTextCombine() && current.m_obj->isCombineText() && !toRenderCombineText(current.m_obj)->isCombined()) {
- RenderCombineText* combineRenderer = toRenderCombineText(current.m_obj);
- combineRenderer->combineText();
- // The length of the renderer's text may have changed. Increment stale iterator positions
- if (iteratorIsBeyondEndOfRenderCombineText(lBreak, combineRenderer)) {
- ASSERT(iteratorIsBeyondEndOfRenderCombineText(resolver.position(), combineRenderer));
- lBreak.increment();
- resolver.position().increment(&resolver);
- }
- }
-
- RenderStyle* style = t->style(lineInfo.isFirstLine());
- const Font& f = style->font();
- bool isFixedPitch = f.isFixedPitch();
-
- unsigned lastSpace = current.m_pos;
- float wordSpacing = currentStyle->wordSpacing();
- float lastSpaceWordSpacing = 0;
- float wordSpacingForWordMeasurement = 0;
-
- float wrapW = width.uncommittedWidth() + inlineLogicalWidth(current.m_obj, !appliedStartWidth, true);
- float charWidth = 0;
- // Auto-wrapping text should wrap in the middle of a word only if it could not wrap before the word,
- // which is only possible if the word is the first thing on the line, that is, if |w| is zero.
- bool breakWords = currentStyle->breakWords() && ((autoWrap && !width.committedWidth()) || currWS == PRE);
- bool midWordBreak = false;
- bool breakAll = currentStyle->wordBreak() == BreakAllWordBreak && autoWrap;
- float hyphenWidth = 0;
-
- if (isSVGText) {
- breakWords = false;
- breakAll = false;
- }
-
- if (t->isWordBreak()) {
- width.commit();
- lBreak.moveToStartOf(current.m_obj);
- ASSERT(current.m_pos == t->textLength());
- }
-
- if (renderTextInfo.m_text != t) {
- renderTextInfo.m_text = t;
- renderTextInfo.m_font = &f;
- renderTextInfo.m_layout = f.createLayout(t, width.currentWidth(), collapseWhiteSpace);
- renderTextInfo.m_lineBreakIterator.resetStringAndReleaseIterator(t->text(), style->locale());
- } else if (renderTextInfo.m_layout && renderTextInfo.m_font != &f) {
- renderTextInfo.m_font = &f;
- renderTextInfo.m_layout = f.createLayout(t, width.currentWidth(), collapseWhiteSpace);
- }
-
- TextLayout* textLayout = renderTextInfo.m_layout.get();
-
- // Non-zero only when kerning is enabled and TextLayout isn't used, in which case we measure
- // words with their trailing space, then subtract its width.
- float wordTrailingSpaceWidth = (f.typesettingFeatures() & Kerning) && !textLayout ? f.width(RenderBlock::constructTextRun(t, f, &space, 1, style)) + wordSpacing : 0;
-
- UChar lastCharacter = renderTextInfo.m_lineBreakIterator.lastCharacter();
- UChar secondToLastCharacter = renderTextInfo.m_lineBreakIterator.secondToLastCharacter();
- for (; current.m_pos < t->textLength(); current.fastIncrementInTextNode()) {
- bool previousCharacterIsSpace = currentCharacterIsSpace;
- bool previousCharacterShouldCollapseIfPreWap = currentCharacterShouldCollapseIfPreWap;
- UChar c = current.current();
- currentCharacterShouldCollapseIfPreWap = currentCharacterIsSpace = c == ' ' || c == '\t' || (!preserveNewline && (c == '\n'));
-
- if (!collapseWhiteSpace || !currentCharacterIsSpace)
- lineInfo.setEmpty(false, m_block, &width);
-
- if (c == softHyphen && autoWrap && !hyphenWidth) {
- hyphenWidth = measureHyphenWidth(t, f);
- width.addUncommittedWidth(hyphenWidth);
- }
-
- bool applyWordSpacing = false;
-
- if ((breakAll || breakWords) && !midWordBreak) {
- wrapW += charWidth;
- bool midWordBreakIsBeforeSurrogatePair = U16_IS_LEAD(c) && current.m_pos + 1 < t->textLength() && U16_IS_TRAIL((*t)[current.m_pos + 1]);
- charWidth = textWidth(t, current.m_pos, midWordBreakIsBeforeSurrogatePair ? 2 : 1, f, width.committedWidth() + wrapW, isFixedPitch, collapseWhiteSpace, 0, textLayout);
- midWordBreak = width.committedWidth() + wrapW + charWidth > width.availableWidth();
- }
-
- bool betweenWords = c == '\n' || (currWS != PRE && !atStart && isBreakable(renderTextInfo.m_lineBreakIterator, current.m_pos, current.m_nextBreakablePosition));
-
- if (betweenWords || midWordBreak) {
- bool stoppedIgnoringSpaces = false;
- if (ignoringSpaces) {
- lastSpaceWordSpacing = 0;
- if (!currentCharacterIsSpace) {
- // Stop ignoring spaces and begin at this
- // new point.
- ignoringSpaces = false;
- wordSpacingForWordMeasurement = 0;
- lastSpace = current.m_pos; // e.g., "Foo goo", don't add in any of the ignored spaces.
- stopIgnoringSpaces(lineMidpointState, InlineIterator(0, current.m_obj, current.m_pos));
- stoppedIgnoringSpaces = true;
- } else {
- // Just keep ignoring these spaces.
- goto nextCharacter;
- }
- }
-
- wordMeasurements.grow(wordMeasurements.size() + 1);
- WordMeasurement& wordMeasurement = wordMeasurements.last();
-
- wordMeasurement.renderer = t;
- wordMeasurement.endOffset = current.m_pos;
- wordMeasurement.startOffset = lastSpace;
-
- float additionalTmpW;
- if (wordTrailingSpaceWidth && c == ' ')
- additionalTmpW = textWidth(t, lastSpace, current.m_pos + 1 - lastSpace, f, width.currentWidth(), isFixedPitch, collapseWhiteSpace, &wordMeasurement.fallbackFonts, textLayout) - wordTrailingSpaceWidth;
- else
- additionalTmpW = textWidth(t, lastSpace, current.m_pos - lastSpace, f, width.currentWidth(), isFixedPitch, collapseWhiteSpace, &wordMeasurement.fallbackFonts, textLayout);
-
- wordMeasurement.width = additionalTmpW + wordSpacingForWordMeasurement;
- additionalTmpW += lastSpaceWordSpacing;
- width.addUncommittedWidth(additionalTmpW);
- if (!appliedStartWidth) {
- width.addUncommittedWidth(inlineLogicalWidth(current.m_obj, true, false));
- appliedStartWidth = true;
- }
-
- applyWordSpacing = wordSpacing && currentCharacterIsSpace;
-
- if (!width.committedWidth() && autoWrap && !width.fitsOnLine())
- width.fitBelowFloats();
-
- if (autoWrap || breakWords) {
- // If we break only after white-space, consider the current character
- // as candidate width for this line.
- bool lineWasTooWide = false;
- if (width.fitsOnLine() && currentCharacterIsSpace && currentStyle->breakOnlyAfterWhiteSpace() && !midWordBreak) {
- float charWidth = textWidth(t, current.m_pos, 1, f, width.currentWidth(), isFixedPitch, collapseWhiteSpace, &wordMeasurement.fallbackFonts, textLayout) + (applyWordSpacing ? wordSpacing : 0);
- // Check if line is too big even without the extra space
- // at the end of the line. If it is not, do nothing.
- // If the line needs the extra whitespace to be too long,
- // then move the line break to the space and skip all
- // additional whitespace.
- if (!width.fitsOnLine(charWidth)) {
- lineWasTooWide = true;
- lBreak.moveTo(current.m_obj, current.m_pos, current.m_nextBreakablePosition);
- skipTrailingWhitespace(lBreak, lineInfo);
- }
- }
- if (lineWasTooWide || !width.fitsOnLine()) {
- if (lBreak.atTextParagraphSeparator()) {
- if (!stoppedIgnoringSpaces && current.m_pos > 0)
- ensureCharacterGetsLineBox(lineMidpointState, current);
- lBreak.increment();
- lineInfo.setPreviousLineBrokeCleanly(true);
- wordMeasurement.endOffset = lBreak.m_pos;
- }
- if (lBreak.m_obj && lBreak.m_pos && lBreak.m_obj->isText() && toRenderText(lBreak.m_obj)->textLength() && toRenderText(lBreak.m_obj)->characterAt(lBreak.m_pos - 1) == softHyphen)
- m_hyphenated = true;
- if (lBreak.m_pos && lBreak.m_pos != (unsigned)wordMeasurement.endOffset && !wordMeasurement.width) {
- if (charWidth) {
- wordMeasurement.endOffset = lBreak.m_pos;
- wordMeasurement.width = charWidth;
- }
- }
- // Didn't fit. Jump to the end unless there's still an opportunity to collapse whitespace.
- if (ignoringSpaces || !collapseWhiteSpace || !currentCharacterIsSpace || !previousCharacterIsSpace)
- goto end;
- } else {
- if (!betweenWords || (midWordBreak && !autoWrap))
- width.addUncommittedWidth(-additionalTmpW);
- if (hyphenWidth) {
- // Subtract the width of the soft hyphen out since we fit on a line.
- width.addUncommittedWidth(-hyphenWidth);
- hyphenWidth = 0;
- }
- }
- }
-
- if (c == '\n' && preserveNewline) {
- if (!stoppedIgnoringSpaces && current.m_pos > 0)
- ensureCharacterGetsLineBox(lineMidpointState, current);
- lBreak.moveTo(current.m_obj, current.m_pos, current.m_nextBreakablePosition);
- lBreak.increment();
- lineInfo.setPreviousLineBrokeCleanly(true);
- return lBreak;
- }
-
- if (autoWrap && betweenWords) {
- width.commit();
- wrapW = 0;
- lBreak.moveTo(current.m_obj, current.m_pos, current.m_nextBreakablePosition);
- // Auto-wrapping text should not wrap in the middle of a word once it has had an
- // opportunity to break after a word.
- breakWords = false;
- }
-
- if (midWordBreak && !U16_IS_TRAIL(c) && !(category(c) & (Mark_NonSpacing | Mark_Enclosing | Mark_SpacingCombining))) {
- // Remember this as a breakable position in case
- // adding the end width forces a break.
- lBreak.moveTo(current.m_obj, current.m_pos, current.m_nextBreakablePosition);
- midWordBreak &= (breakWords || breakAll);
- }
-
- if (betweenWords) {
- lastSpaceWordSpacing = applyWordSpacing ? wordSpacing : 0;
- wordSpacingForWordMeasurement = (applyWordSpacing && wordMeasurement.width) ? wordSpacing : 0;
- lastSpace = current.m_pos;
- }
-
- if (!ignoringSpaces && currentStyle->collapseWhiteSpace()) {
- // If we encounter a newline, or if we encounter a
- // second space, we need to go ahead and break up this
- // run and enter a mode where we start collapsing spaces.
- if (currentCharacterIsSpace && previousCharacterIsSpace) {
- ignoringSpaces = true;
-
- // We just entered a mode where we are ignoring
- // spaces. Create a midpoint to terminate the run
- // before the second space.
- startIgnoringSpaces(lineMidpointState, ignoreStart);
- trailingObjects.updateMidpointsForTrailingBoxes(lineMidpointState, InlineIterator(), TrailingObjects::DoNotCollapseFirstSpace);
- }
- }
- } else if (ignoringSpaces) {
- // Stop ignoring spaces and begin at this
- // new point.
- ignoringSpaces = false;
- lastSpaceWordSpacing = applyWordSpacing ? wordSpacing : 0;
- wordSpacingForWordMeasurement = (applyWordSpacing && wordMeasurements.last().width) ? wordSpacing : 0;
- lastSpace = current.m_pos; // e.g., "Foo goo", don't add in any of the ignored spaces.
- stopIgnoringSpaces(lineMidpointState, InlineIterator(0, current.m_obj, current.m_pos));
- }
-
- if (isSVGText && current.m_pos > 0) {
- // Force creation of new InlineBoxes for each absolute positioned character (those that start new text chunks).
- if (toRenderSVGInlineText(t)->characterStartsNewTextChunk(current.m_pos))
- ensureCharacterGetsLineBox(lineMidpointState, current);
- }
-
- if (currentCharacterIsSpace && !previousCharacterIsSpace) {
- ignoreStart.m_obj = current.m_obj;
- ignoreStart.m_pos = current.m_pos;
- }
-
- if (!currentCharacterIsSpace && previousCharacterShouldCollapseIfPreWap) {
- if (autoWrap && currentStyle->breakOnlyAfterWhiteSpace())
- lBreak.moveTo(current.m_obj, current.m_pos, current.m_nextBreakablePosition);
- }
-
- if (collapseWhiteSpace && currentCharacterIsSpace && !ignoringSpaces)
- trailingObjects.setTrailingWhitespace(toRenderText(current.m_obj));
- else if (!currentStyle->collapseWhiteSpace() || !currentCharacterIsSpace)
- trailingObjects.clear();
-
- atStart = false;
- nextCharacter:
- secondToLastCharacter = lastCharacter;
- lastCharacter = c;
- }
-
- renderTextInfo.m_lineBreakIterator.setPriorContext(lastCharacter, secondToLastCharacter);
-
- wordMeasurements.grow(wordMeasurements.size() + 1);
- WordMeasurement& wordMeasurement = wordMeasurements.last();
- wordMeasurement.renderer = t;
-
- // IMPORTANT: current.m_pos is > length here!
- float additionalTmpW = ignoringSpaces ? 0 : textWidth(t, lastSpace, current.m_pos - lastSpace, f, width.currentWidth(), isFixedPitch, collapseWhiteSpace, &wordMeasurement.fallbackFonts, textLayout);
- wordMeasurement.startOffset = lastSpace;
- wordMeasurement.endOffset = current.m_pos;
- wordMeasurement.width = ignoringSpaces ? 0 : additionalTmpW + wordSpacingForWordMeasurement;
- additionalTmpW += lastSpaceWordSpacing;
- width.addUncommittedWidth(additionalTmpW + inlineLogicalWidth(current.m_obj, !appliedStartWidth, includeEndWidth));
- includeEndWidth = false;
-
- if (!width.fitsOnLine()) {
- if (!m_hyphenated && lBreak.previousInSameNode() == softHyphen)
- m_hyphenated = true;
-
- if (m_hyphenated)
- goto end;
- }
- } else
+ } else {
ASSERT_NOT_REACHED();
-
- bool checkForBreak = autoWrap;
- if (width.committedWidth() && !width.fitsOnLine() && lBreak.m_obj && currWS == NOWRAP)
- checkForBreak = true;
- else if (next && current.m_obj->isText() && next->isText() && !next->isBR() && (autoWrap || next->style()->autoWrap())) {
- if (autoWrap && currentCharacterIsSpace)
- checkForBreak = true;
- else {
- RenderText* nextText = toRenderText(next);
- if (nextText->textLength()) {
- UChar c = nextText->characterAt(0);
- // If the next item on the line is text, and if we did not end with
- // a space, then the next text run continues our word (and so it needs to
- // keep adding to the uncommitted width. Just update and continue.
- checkForBreak = !currentCharacterIsSpace && (c == ' ' || c == '\t' || (c == '\n' && !next->preservesNewline()));
- } else if (nextText->isWordBreak())
- checkForBreak = true;
-
- if (!width.fitsOnLine() && !width.committedWidth())
- width.fitBelowFloats();
-
- bool canPlaceOnLine = width.fitsOnLine() || !autoWrapWasEverTrueOnLine;
- if (canPlaceOnLine && checkForBreak) {
- width.commit();
- lBreak.moveToStartOf(next);
- }
- }
}
- if (checkForBreak && !width.fitsOnLine()) {
- // if we have floats, try to get below them.
- if (currentCharacterIsSpace && !ignoringSpaces && currentStyle->collapseWhiteSpace())
- trailingObjects.clear();
-
- if (width.committedWidth())
- goto end;
-
- width.fitBelowFloats();
-
- // |width| may have been adjusted because we got shoved down past a float (thus
- // giving us more room), so we need to retest, and only jump to
- // the end label if we still don't fit on the line. -dwh
- if (!width.fitsOnLine())
- goto end;
- } else if (blockStyle->autoWrap() && !width.fitsOnLine() && !width.committedWidth()) {
- // If the container autowraps but the current child does not then we still need to ensure that it
- // wraps and moves below any floats.
- width.fitBelowFloats();
- }
+ if (context.atEnd())
+ return context.handleEndOfLine();
- if (!current.m_obj->isFloatingOrOutOfFlowPositioned()) {
- last = current.m_obj;
- if (last->isReplaced() && autoWrap && (!last->isImage() || allowImagesToBreak) && (!last->isListMarker() || toRenderListMarker(last)->isInside())) {
- width.commit();
- lBreak.moveToStartOf(next);
- }
- }
+ context.commitAndUpdateLineBreakIfNeeded();
- // Clear out our character space bool, since inline <pre>s don't collapse whitespace
- // with adjacent inline normal/nowrap spans.
- if (!collapseWhiteSpace)
- currentCharacterIsSpace = false;
+ if (context.atEnd())
+ return context.handleEndOfLine();
- current.moveToStartOf(next);
- atStart = false;
+ context.increment();
}
- if (width.fitsOnLine() || lastWS == NOWRAP)
- lBreak.clear();
-
- end:
- ShapeInsideInfo* shapeInfo = m_block->layoutShapeInsideInfo();
- bool segmentAllowsOverflow = !shapeInfo || !shapeInfo->hasSegments();
+ context.clearLineBreakIfFitsOnLine();
- if (lBreak == resolver.position() && (!lBreak.m_obj || !lBreak.m_obj->isBR()) && segmentAllowsOverflow) {
- // we just add as much as possible
- if (blockStyle->whiteSpace() == PRE && !current.m_pos) {
- lBreak.moveTo(last, last->isText() ? last->length() : 0);
- } else if (lBreak.m_obj) {
- // Don't ever break in the middle of a word if we can help it.
- // There's no room at all. We just have to be on this line,
- // even though we'll spill out.
- lBreak.moveTo(current.m_obj, current.m_pos);
- }
- }
-
- // FIXME Bug 100049: We do not need to consume input in a multi-segment line
- // unless no segment will.
- // make sure we consume at least one char/object.
- if (lBreak == resolver.position() && segmentAllowsOverflow)
- lBreak.increment();
-
- // Sanity check our midpoints.
- checkMidpoints(lineMidpointState, lBreak);
-
- trailingObjects.updateMidpointsForTrailingBoxes(lineMidpointState, lBreak, TrailingObjects::CollapseFirstSpace);
-
- // We might have made lBreak an iterator that points past the end
- // of the object. Do this adjustment to make it point to the start
- // of the next object instead to avoid confusing the rest of the
- // code.
- if (lBreak.m_pos > 0) {
- lBreak.m_pos--;
- // This loop enforces the invariant that line breaks should never point
- // at an empty inline. See http://crbug.com/305904.
- do {
- lBreak.increment();
- } while (!lBreak.atEnd() && isEmptyInline(lBreak.m_obj));
- }
-
- return lBreak;
+ return context.handleEndOfLine();
}
-void RenderBlock::addOverflowFromInlineChildren()
+void RenderBlockFlow::addOverflowFromInlineChildren()
{
LayoutUnit endPadding = hasOverflowClip() ? paddingEnd() : LayoutUnit();
// FIXME: Need to find another way to do this, since scrollbars could show when we don't want them to.
@@ -3219,7 +2252,7 @@ void RenderBlock::addOverflowFromInlineChildren()
}
}
-void RenderBlock::deleteEllipsisLineBoxes()
+void RenderBlockFlow::deleteEllipsisLineBoxes()
{
ETextAlign textAlign = style()->textAlign();
bool ltr = style()->isLeftToRightDirection();
@@ -3243,7 +2276,7 @@ void RenderBlock::deleteEllipsisLineBoxes()
}
}
-void RenderBlock::checkLinesForTextOverflow()
+void RenderBlockFlow::checkLinesForTextOverflow()
{
// Determine the width of the ellipsis using the current font.
// FIXME: CSS3 says this is configurable, also need to use 0x002E (FULL STOP) if horizontal ellipsis is "not renderable"
@@ -3263,9 +2296,10 @@ void RenderBlock::checkLinesForTextOverflow()
for (RootInlineBox* curr = firstRootBox(); curr; curr = curr->nextRootBox()) {
// FIXME: Use pixelSnappedLogicalRightOffsetForLine instead of snapping it ourselves once the column workaround in said method has been fixed.
// https://bugs.webkit.org/show_bug.cgi?id=105461
- int blockRightEdge = snapSizeToPixel(logicalRightOffsetForLine(curr->lineTop(), firstLine), curr->x());
+ float currLogicalLeft = curr->logicalLeft();
+ int blockRightEdge = snapSizeToPixel(logicalRightOffsetForLine(curr->lineTop(), firstLine), currLogicalLeft);
int blockLeftEdge = pixelSnappedLogicalLeftOffsetForLine(curr->lineTop(), firstLine);
- int lineBoxEdge = ltr ? snapSizeToPixel(curr->x() + curr->logicalWidth(), curr->x()) : snapSizeToPixel(curr->x(), 0);
+ int lineBoxEdge = ltr ? snapSizeToPixel(currLogicalLeft + curr->logicalWidth(), currLogicalLeft) : snapSizeToPixel(currLogicalLeft, 0);
if ((ltr && lineBoxEdge > blockRightEdge) || (!ltr && lineBoxEdge < blockLeftEdge)) {
// This line spills out of our box in the appropriate direction. Now we need to see if the line
// can be truncated. In order for truncation to be possible, the line must have sufficient space to
@@ -3290,7 +2324,7 @@ void RenderBlock::checkLinesForTextOverflow()
}
}
-bool RenderBlock::positionNewFloatOnLine(FloatingObject* newFloat, FloatingObject* lastFloatFromPreviousLine, LineInfo& lineInfo, LineWidth& width)
+bool RenderBlockFlow::positionNewFloatOnLine(FloatingObject* newFloat, FloatingObject* lastFloatFromPreviousLine, LineInfo& lineInfo, LineWidth& width)
{
if (!positionNewFloats())
return false;
@@ -3306,7 +2340,7 @@ bool RenderBlock::positionNewFloatOnLine(FloatingObject* newFloat, FloatingObjec
const FloatingObjectSet& floatingObjectSet = m_floatingObjects->set();
ASSERT(floatingObjectSet.last() == newFloat);
- LayoutUnit floatLogicalTop = newFloat->logicalTop(isHorizontalWritingMode());
+ LayoutUnit floatLogicalTop = logicalTopForFloat(newFloat);
int paginationStrut = newFloat->paginationStrut();
if (floatLogicalTop - paginationStrut != logicalHeight() + lineInfo.floatPaginationStrut())
@@ -3317,23 +2351,23 @@ bool RenderBlock::positionNewFloatOnLine(FloatingObject* newFloat, FloatingObjec
FloatingObjectSetIterator begin = floatingObjectSet.begin();
while (it != begin) {
--it;
- FloatingObject* f = *it;
- if (f == lastFloatFromPreviousLine)
+ FloatingObject* floatingObject = *it;
+ if (floatingObject == lastFloatFromPreviousLine)
break;
- if (f->logicalTop(isHorizontalWritingMode()) == logicalHeight() + lineInfo.floatPaginationStrut()) {
- f->setPaginationStrut(paginationStrut + f->paginationStrut());
- RenderBox* o = f->renderer();
- setLogicalTopForChild(o, logicalTopForChild(o) + marginBeforeForChild(o) + paginationStrut);
- if (o->isRenderBlock())
- o->forceChildLayout();
+ if (logicalTopForFloat(floatingObject) == logicalHeight() + lineInfo.floatPaginationStrut()) {
+ floatingObject->setPaginationStrut(paginationStrut + floatingObject->paginationStrut());
+ RenderBox* floatBox = floatingObject->renderer();
+ setLogicalTopForChild(floatBox, logicalTopForChild(floatBox) + marginBeforeForChild(floatBox) + paginationStrut);
+ if (floatBox->isRenderBlock())
+ floatBox->forceChildLayout();
else
- o->layoutIfNeeded();
+ floatBox->layoutIfNeeded();
// Save the old logical top before calling removePlacedObject which will set
// isPlaced to false. Otherwise it will trigger an assert in logicalTopForFloat.
- LayoutUnit oldLogicalTop = f->logicalTop(isHorizontalWritingMode());
- m_floatingObjects->removePlacedObject(f);
- f->setLogicalTop(oldLogicalTop + paginationStrut, isHorizontalWritingMode());
- m_floatingObjects->addPlacedObject(f);
+ LayoutUnit oldLogicalTop = logicalTopForFloat(floatingObject);
+ m_floatingObjects->removePlacedObject(floatingObject);
+ setLogicalTopForFloat(floatingObject, oldLogicalTop + paginationStrut);
+ m_floatingObjects->addPlacedObject(floatingObject);
}
}
@@ -3343,7 +2377,7 @@ bool RenderBlock::positionNewFloatOnLine(FloatingObject* newFloat, FloatingObjec
return true;
}
-LayoutUnit RenderBlock::startAlignedOffsetForLine(LayoutUnit position, bool firstLine)
+LayoutUnit RenderBlockFlow::startAlignedOffsetForLine(LayoutUnit position, bool firstLine)
{
ETextAlign textAlign = style()->textAlign();
@@ -3361,8 +2395,7 @@ LayoutUnit RenderBlock::startAlignedOffsetForLine(LayoutUnit position, bool firs
return logicalLeft;
}
-
-void RenderBlock::layoutLineGridBox()
+void RenderBlockFlow::layoutLineGridBox()
{
if (style()->lineGrid() == RenderStyle::initialLineGrid()) {
setLineGridBox(0);
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderBox.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderBox.cpp
index 8beaa17b46d..9c960358ed5 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderBox.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderBox.cpp
@@ -32,16 +32,17 @@
#include "core/dom/Document.h"
#include "core/editing/htmlediting.h"
#include "core/html/HTMLElement.h"
+#include "core/html/HTMLFrameElementBase.h"
#include "core/html/HTMLFrameOwnerElement.h"
#include "core/html/HTMLHtmlElement.h"
#include "core/html/HTMLTextAreaElement.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameView.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
+#include "core/page/AutoscrollController.h"
+#include "core/page/EventHandler.h"
#include "core/page/Page.h"
-#include "core/platform/graphics/FloatQuad.h"
-#include "core/platform/graphics/GraphicsContextStateSaver.h"
-#include "core/platform/graphics/transforms/TransformState.h"
#include "core/rendering/HitTestResult.h"
+#include "core/rendering/LayoutRectRecorder.h"
#include "core/rendering/PaintInfo.h"
#include "core/rendering/RenderBoxRegionInfo.h"
#include "core/rendering/RenderFlexibleBox.h"
@@ -56,6 +57,9 @@
#include "core/rendering/RenderTableCell.h"
#include "core/rendering/RenderTheme.h"
#include "core/rendering/RenderView.h"
+#include "platform/geometry/FloatQuad.h"
+#include "platform/geometry/TransformState.h"
+#include "platform/graphics/GraphicsContextStateSaver.h"
using namespace std;
@@ -78,8 +82,6 @@ static OverrideSizeMap* gOverrideContainingBlockLogicalWidthMap = 0;
static const int autoscrollBeltSize = 20;
static const unsigned backgroundObscurationTestMaxDepth = 4;
-bool RenderBox::s_hadOverflowClip = false;
-
static bool skipBodyBackground(const RenderBox* bodyElementRenderer)
{
ASSERT(bodyElementRenderer->isBody());
@@ -171,22 +173,18 @@ void RenderBox::removeFloatingOrPositionedChildFromBlockLists()
return;
if (isFloating()) {
- RenderBlock* parentBlock = 0;
+ RenderBlockFlow* parentBlockFlow = 0;
for (RenderObject* curr = parent(); curr && !curr->isRenderView(); curr = curr->parent()) {
- if (curr->isRenderBlock()) {
- RenderBlock* currBlock = toRenderBlock(curr);
- if (!parentBlock || currBlock->containsFloat(this))
- parentBlock = currBlock;
+ if (curr->isRenderBlockFlow()) {
+ RenderBlockFlow* currBlockFlow = toRenderBlockFlow(curr);
+ if (!parentBlockFlow || currBlockFlow->containsFloat(this))
+ parentBlockFlow = currBlockFlow;
}
}
- if (parentBlock) {
- RenderObject* parent = parentBlock->parent();
- if (parent && parent->isFlexibleBoxIncludingDeprecated())
- parentBlock = toRenderBlock(parent);
-
- parentBlock->markSiblingsWithFloatsForLayout(this);
- parentBlock->markAllDescendantsWithFloatsForLayout(this, false);
+ if (parentBlockFlow) {
+ parentBlockFlow->markSiblingsWithFloatsForLayout(this);
+ parentBlockFlow->markAllDescendantsWithFloatsForLayout(this, false);
}
}
@@ -196,8 +194,6 @@ void RenderBox::removeFloatingOrPositionedChildFromBlockLists()
void RenderBox::styleWillChange(StyleDifference diff, const RenderStyle* newStyle)
{
- s_hadOverflowClip = hasOverflowClip();
-
RenderStyle* oldStyle = style();
if (oldStyle) {
// The background of the root element or the body element could propagate up to
@@ -254,19 +250,19 @@ void RenderBox::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle
// If our zoom factor changes and we have a defined scrollLeft/Top, we need to adjust that value into the
// new zoomed coordinate space.
- if (hasOverflowClip() && oldStyle && newStyle && oldStyle->effectiveZoom() != newStyle->effectiveZoom()) {
- if (int left = layer()->scrollXOffset()) {
+ if (hasOverflowClip() && oldStyle && newStyle && oldStyle->effectiveZoom() != newStyle->effectiveZoom() && layer()) {
+ if (int left = layer()->scrollableArea()->scrollXOffset()) {
left = (left / oldStyle->effectiveZoom()) * newStyle->effectiveZoom();
- layer()->scrollToXOffset(left);
+ layer()->scrollableArea()->scrollToXOffset(left);
}
- if (int top = layer()->scrollYOffset()) {
+ if (int top = layer()->scrollableArea()->scrollYOffset()) {
top = (top / oldStyle->effectiveZoom()) * newStyle->effectiveZoom();
- layer()->scrollToYOffset(top);
+ layer()->scrollableArea()->scrollToYOffset(top);
}
}
// Our opaqueness might have changed without triggering layout.
- if (diff == StyleDifferenceRepaint || diff == StyleDifferenceRepaintIfText || diff == StyleDifferenceRepaintLayer) {
+ if (diff == StyleDifferenceRepaint || diff == StyleDifferenceRepaintIfTextOrColorChange || diff == StyleDifferenceRepaintLayer) {
RenderObject* parentToInvalidate = parent();
for (unsigned i = 0; i < backgroundObscurationTestMaxDepth && parentToInvalidate; ++i) {
parentToInvalidate->invalidateBackgroundObscurationStatus();
@@ -277,22 +273,32 @@ void RenderBox::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle
if (isRoot() || isBody())
document().view()->recalculateScrollbarOverlayStyle();
- updateShapeOutsideInfoAfterStyleChange(style()->shapeOutside(), oldStyle ? oldStyle->shapeOutside() : 0);
+ updateShapeOutsideInfoAfterStyleChange(*style(), oldStyle);
updateGridPositionAfterStyleChange(oldStyle);
}
-void RenderBox::updateShapeOutsideInfoAfterStyleChange(const ShapeValue* shapeOutside, const ShapeValue* oldShapeOutside)
+void RenderBox::updateShapeOutsideInfoAfterStyleChange(const RenderStyle& style, const RenderStyle* oldStyle)
{
+ const ShapeValue* shapeOutside = style.shapeOutside();
+ const ShapeValue* oldShapeOutside = oldStyle ? oldStyle->shapeOutside() : RenderStyle::initialShapeOutside();
+
+ Length shapeMargin = style.shapeMargin();
+ Length oldShapeMargin = oldStyle ? oldStyle->shapeMargin() : RenderStyle::initialShapeMargin();
+
+ float shapeImageThreshold = style.shapeImageThreshold();
+ float oldShapeImageThreshold = oldStyle ? oldStyle->shapeImageThreshold() : RenderStyle::initialShapeImageThreshold();
+
// FIXME: A future optimization would do a deep comparison for equality. (bug 100811)
- if (shapeOutside == oldShapeOutside)
+ if (shapeOutside == oldShapeOutside && shapeMargin == oldShapeMargin && shapeImageThreshold == oldShapeImageThreshold)
return;
- if (shapeOutside) {
- ShapeOutsideInfo* shapeOutsideInfo = ShapeOutsideInfo::ensureInfo(this);
- shapeOutsideInfo->dirtyShapeSize();
- } else {
+ if (!shapeOutside)
ShapeOutsideInfo::removeInfo(this);
- }
+ else
+ ShapeOutsideInfo::ensureInfo(this)->dirtyShapeSize();
+
+ if (shapeOutside || shapeOutside != oldShapeOutside)
+ markShapeOutsideDependentsForLayout();
}
void RenderBox::updateGridPositionAfterStyleChange(const RenderStyle* oldStyle)
@@ -327,29 +333,28 @@ void RenderBox::updateFromStyle()
setFloating(!isOutOfFlowPositioned() && styleToUse->isFloating());
+ bool boxHasOverflowClip = false;
// We also handle <body> and <html>, whose overflow applies to the viewport.
+ // It's sufficient to just check one direction, since it's illegal to have visible on only one overflow value.
if (styleToUse->overflowX() != OVISIBLE && !isRootObject && isRenderBlock()) {
- bool boxHasOverflowClip = true;
- if (isBody()) {
- // Overflow on the body can propagate to the viewport under the following conditions.
- // (1) The root element is <html>.
- // (2) We are the primary <body> (can be checked by looking at document.body).
- // (3) The root element has visible overflow.
- if (isHTMLHtmlElement(document().documentElement())
- && document().body() == node()
- && document().documentElement()->renderer()->style()->overflowX() == OVISIBLE)
- boxHasOverflowClip = false;
- }
-
- // Check for overflow clip.
- // It's sufficient to just check one direction, since it's illegal to have visible on only one overflow value.
- if (boxHasOverflowClip) {
- if (!s_hadOverflowClip)
- // Erase the overflow
+ // Overflow on the body can propagate to the viewport under the following conditions.
+ // (1) The root element is <html>.
+ // (2) We are the primary <body> (can be checked by looking at document.body).
+ // (3) The root element has visible overflow.
+ if (isBody() && isHTMLHtmlElement(document().documentElement())
+ && document().body() == node()
+ && document().documentElement()->renderer()->style()->overflowX() == OVISIBLE) {
+ boxHasOverflowClip = false;
+ } else {
+ boxHasOverflowClip = true;
+ if (!hasOverflowClip()) {
+ // If we are getting an overflow clip, preemptively erase any overflowing content.
+ // FIXME: This should probably consult RenderOverflow.
repaint();
- setHasOverflowClip();
+ }
}
}
+ setHasOverflowClip(boxHasOverflowClip);
setHasTransform(styleToUse->hasTransformRelatedProperty());
setHasReflection(styleToUse->boxReflect());
@@ -359,6 +364,8 @@ void RenderBox::layout()
{
ASSERT(needsLayout());
+ LayoutRectRecorder recorder(*this);
+
RenderObject* child = firstChild();
if (!child) {
clearNeedsLayout();
@@ -408,33 +415,37 @@ int RenderBox::pixelSnappedOffsetHeight() const
return snapSizeToPixel(offsetHeight(), y() + clientTop());
}
-bool RenderBox::requiresLayoutToDetermineWidth() const
+bool RenderBox::canDetermineWidthWithoutLayout() const
{
- // This optimization unfortunately doesn't work:
- // https://code.google.com/p/chromium/issues/detail?id=290399
- // So we've disabled it for M30 until it can be fixed on trunk.
- // Attempting to revert the original change or trying to fix
- // it on trunk and merge over to M30 is too risky so we just
- // force code which uses this to always use the "slow" (correct) path
- // instead of the (broken) optimization returning false would allow.
- return true;
+ // FIXME: This optimization is incorrect as written.
+ // We need to be able to opt-in to this behavior only when
+ // it's guarentted correct.
+ // Until then disabling this optimization to be safe.
+ return false;
- RenderStyle* style = this->style();
- return !style->width().isFixed()
- || !style->minWidth().isFixed()
- || (!style->maxWidth().isUndefined() && !style->maxWidth().isFixed())
- || !style->paddingLeft().isFixed()
- || !style->paddingRight().isFixed()
- || style->resize() != RESIZE_NONE
- || style->boxSizing() == BORDER_BOX
- || !isRenderBlock()
- || !isRenderBlockFlow()
- || isFlexItemIncludingDeprecated();
+ // FIXME: There are likely many subclasses of RenderBlockFlow which
+ // cannot determine their layout just from style!
+ // Perhaps we should create a "PlainRenderBlockFlow"
+ // and move this optimization there?
+ if (!isRenderBlockFlow()
+ // Flexbox items can be expanded beyond their width.
+ || isFlexItemIncludingDeprecated()
+ // Table Layout controls cell size and can expand beyond width.
+ || isTableCell())
+ return false;
+
+ RenderStyle* style = this->style();
+ return style->width().isFixed()
+ && style->minWidth().isFixed()
+ && (style->maxWidth().isUndefined() || style->maxWidth().isFixed())
+ && style->paddingLeft().isFixed()
+ && style->paddingRight().isFixed()
+ && style->boxSizing() == CONTENT_BOX;
}
LayoutUnit RenderBox::fixedOffsetWidth() const
{
- ASSERT(!requiresLayoutToDetermineWidth());
+ ASSERT(canDetermineWidthWithoutLayout());
RenderStyle* style = this->style();
@@ -451,7 +462,7 @@ LayoutUnit RenderBox::fixedOffsetWidth() const
int RenderBox::scrollWidth() const
{
if (hasOverflowClip())
- return layer()->scrollWidth();
+ return layer()->scrollableArea()->scrollWidth();
// For objects with visible overflow, this matches IE.
// FIXME: Need to work right with writing modes.
if (style()->isLeftToRightDirection())
@@ -462,7 +473,7 @@ int RenderBox::scrollWidth() const
int RenderBox::scrollHeight() const
{
if (hasOverflowClip())
- return layer()->scrollHeight();
+ return layer()->scrollableArea()->scrollHeight();
// For objects with visible overflow, this matches IE.
// FIXME: Need to work right with writing modes.
return snapSizeToPixel(max(clientHeight(), layoutOverflowRect().maxY() - borderTop()), y() + clientTop());
@@ -470,24 +481,109 @@ int RenderBox::scrollHeight() const
int RenderBox::scrollLeft() const
{
- return hasOverflowClip() ? layer()->scrollXOffset() : 0;
+ return hasOverflowClip() ? layer()->scrollableArea()->scrollXOffset() : 0;
}
int RenderBox::scrollTop() const
{
- return hasOverflowClip() ? layer()->scrollYOffset() : 0;
+ return hasOverflowClip() ? layer()->scrollableArea()->scrollYOffset() : 0;
}
void RenderBox::setScrollLeft(int newLeft)
{
if (hasOverflowClip())
- layer()->scrollToXOffset(newLeft, ScrollOffsetClamped);
+ layer()->scrollableArea()->scrollToXOffset(newLeft, ScrollOffsetClamped);
}
void RenderBox::setScrollTop(int newTop)
{
if (hasOverflowClip())
- layer()->scrollToYOffset(newTop, ScrollOffsetClamped);
+ layer()->scrollableArea()->scrollToYOffset(newTop, ScrollOffsetClamped);
+}
+
+void RenderBox::scrollToOffset(const IntSize& offset)
+{
+ ASSERT(hasOverflowClip());
+ layer()->scrollableArea()->scrollToOffset(offset, ScrollOffsetClamped);
+}
+
+static inline bool frameElementAndViewPermitScroll(HTMLFrameElementBase* frameElementBase, FrameView* frameView)
+{
+ // If scrollbars aren't explicitly forbidden, permit scrolling.
+ if (frameElementBase && frameElementBase->scrollingMode() != ScrollbarAlwaysOff)
+ return true;
+
+ // If scrollbars are forbidden, user initiated scrolls should obviously be ignored.
+ if (frameView->wasScrolledByUser())
+ return false;
+
+ // Forbid autoscrolls when scrollbars are off, but permits other programmatic scrolls,
+ // like navigation to an anchor.
+ Page* page = frameView->frame().page();
+ if (!page)
+ return false;
+ return !page->autoscrollController().autoscrollInProgress();
+}
+
+void RenderBox::scrollRectToVisible(const LayoutRect& rect, const ScrollAlignment& alignX, const ScrollAlignment& alignY)
+{
+ RenderBox* parentBox = 0;
+ LayoutRect newRect = rect;
+
+ bool restrictedByLineClamp = false;
+ if (parent()) {
+ parentBox = parent()->enclosingBox();
+ restrictedByLineClamp = !parent()->style()->lineClamp().isNone();
+ }
+
+ if (hasOverflowClip() && !restrictedByLineClamp) {
+ // Don't scroll to reveal an overflow layer that is restricted by the -webkit-line-clamp property.
+ // This will prevent us from revealing text hidden by the slider in Safari RSS.
+ newRect = layer()->scrollableArea()->exposeRect(rect, alignX, alignY);
+ } else if (!parentBox && canBeProgramaticallyScrolled()) {
+ if (FrameView* frameView = this->frameView()) {
+ Element* ownerElement = document().ownerElement();
+
+ if (ownerElement && ownerElement->renderer()) {
+ HTMLFrameElementBase* frameElementBase = 0;
+
+ if (ownerElement->hasTagName(frameTag) || ownerElement->hasTagName(iframeTag))
+ frameElementBase = toHTMLFrameElementBase(ownerElement);
+
+ if (frameElementAndViewPermitScroll(frameElementBase, frameView)) {
+ LayoutRect viewRect = frameView->visibleContentRect();
+ LayoutRect exposeRect = ScrollAlignment::getRectToExpose(viewRect, rect, alignX, alignY);
+
+ int xOffset = roundToInt(exposeRect.x());
+ int yOffset = roundToInt(exposeRect.y());
+ // Adjust offsets if they're outside of the allowable range.
+ xOffset = max(0, min(frameView->contentsWidth(), xOffset));
+ yOffset = max(0, min(frameView->contentsHeight(), yOffset));
+
+ frameView->setScrollPosition(IntPoint(xOffset, yOffset));
+ if (frameView->safeToPropagateScrollToParent()) {
+ parentBox = ownerElement->renderer()->enclosingBox();
+ // FIXME: This doesn't correctly convert the rect to
+ // absolute coordinates in the parent.
+ newRect.setX(rect.x() - frameView->scrollX() + frameView->x());
+ newRect.setY(rect.y() - frameView->scrollY() + frameView->y());
+ } else {
+ parentBox = 0;
+ }
+ }
+ } else {
+ LayoutRect viewRect = frameView->visibleContentRect();
+ LayoutRect r = ScrollAlignment::getRectToExpose(viewRect, rect, alignX, alignY);
+ frameView->setScrollPosition(roundedIntPoint(r.location()));
+ }
+ }
+ }
+
+ if (frame()->page()->autoscrollController().autoscrollInProgress())
+ parentBox = enclosingScrollableBox();
+
+ if (parentBox)
+ parentBox->scrollRectToVisible(newRect, alignX, alignY);
}
void RenderBox::absoluteRects(Vector<IntRect>& rects, const LayoutPoint& accumulatedOffset) const
@@ -580,6 +676,14 @@ void RenderBox::addFocusRingRects(Vector<IntRect>& rects, const LayoutPoint& add
rects.append(pixelSnappedIntRect(additionalOffset, size()));
}
+bool RenderBox::canResize() const
+{
+ // We need a special case for <iframe> because they never have
+ // hasOverflowClip(). However, they do "implicitly" clip their contents, so
+ // we want to allow resizing them also.
+ return (hasOverflowClip() || isRenderIFrame()) && style()->resize() != RESIZE_NONE;
+}
+
void RenderBox::addLayerHitTestRects(LayerHitTestRects& layerRects, const RenderLayer* currentLayer, const LayoutPoint& layerOffset, const LayoutRect& containerRect) const
{
LayoutPoint adjustedLayerOffset = layerOffset + locationOffset();
@@ -650,26 +754,20 @@ LayoutRect RenderBox::reflectedRect(const LayoutRect& r) const
return result;
}
-bool RenderBox::includeVerticalScrollbarSize() const
-{
- return hasOverflowClip() && !layer()->hasOverlayScrollbars()
- && (style()->overflowY() == OSCROLL || style()->overflowY() == OAUTO);
-}
-
-bool RenderBox::includeHorizontalScrollbarSize() const
-{
- return hasOverflowClip() && !layer()->hasOverlayScrollbars()
- && (style()->overflowX() == OSCROLL || style()->overflowX() == OAUTO);
-}
-
int RenderBox::verticalScrollbarWidth() const
{
- return includeVerticalScrollbarSize() ? layer()->verticalScrollbarWidth() : 0;
+ if (!hasOverflowClip() || style()->overflowY() == OOVERLAY)
+ return 0;
+
+ return layer()->scrollableArea()->verticalScrollbarWidth();
}
int RenderBox::horizontalScrollbarHeight() const
{
- return includeHorizontalScrollbarSize() ? layer()->horizontalScrollbarHeight() : 0;
+ if (!hasOverflowClip() || style()->overflowX() == OOVERLAY)
+ return 0;
+
+ return layer()->scrollableArea()->horizontalScrollbarHeight();
}
int RenderBox::instrinsicScrollbarLogicalWidth() const
@@ -678,57 +776,27 @@ int RenderBox::instrinsicScrollbarLogicalWidth() const
return 0;
if (isHorizontalWritingMode() && style()->overflowY() == OSCROLL) {
- ASSERT(layer()->hasVerticalScrollbar());
+ ASSERT(layer()->scrollableArea() && layer()->scrollableArea()->hasVerticalScrollbar());
return verticalScrollbarWidth();
}
if (!isHorizontalWritingMode() && style()->overflowX() == OSCROLL) {
- ASSERT(layer()->hasHorizontalScrollbar());
+ ASSERT(layer()->scrollableArea() && layer()->scrollableArea()->hasHorizontalScrollbar());
return horizontalScrollbarHeight();
}
return 0;
}
-bool RenderBox::scrollImpl(ScrollDirection direction, ScrollGranularity granularity, float multiplier)
-{
- RenderLayer* l = layer();
- return l && l->scroll(direction, granularity, multiplier);
-}
-
-bool RenderBox::scroll(ScrollDirection direction, ScrollGranularity granularity, float multiplier, Node** stopNode)
-{
- if (scrollImpl(direction, granularity, multiplier)) {
- if (stopNode)
- *stopNode = node();
- return true;
- }
-
- if (stopNode && *stopNode && *stopNode == node())
- return true;
-
- RenderBlock* b = containingBlock();
- if (b && !b->isRenderView())
- return b->scroll(direction, granularity, multiplier, stopNode);
- return false;
-}
-
-bool RenderBox::logicalScroll(ScrollLogicalDirection direction, ScrollGranularity granularity, float multiplier, Node** stopNode)
+bool RenderBox::scroll(ScrollDirection direction, ScrollGranularity granularity, float multiplier)
{
- if (scrollImpl(logicalToPhysical(direction, isHorizontalWritingMode(), style()->isFlippedBlocksWritingMode()),
- granularity, multiplier)) {
- if (stopNode)
- *stopNode = node();
- return true;
- }
+ // Logical scroll is a higher level concept, all directions by here must be physical
+ ASSERT(!isLogical(direction));
- if (stopNode && *stopNode && *stopNode == node())
- return true;
+ if (!layer() || !layer()->scrollableArea())
+ return false;
- RenderBlock* b = containingBlock();
- if (b && !b->isRenderView())
- return b->logicalScroll(direction, granularity, multiplier, stopNode);
- return false;
+ return layer()->scrollableArea()->scroll(direction, granularity, multiplier);
}
bool RenderBox::canBeScrolledAndHasScrollableArea() const
@@ -754,18 +822,26 @@ bool RenderBox::canBeProgramaticallyScrolled() const
bool RenderBox::usesCompositedScrolling() const
{
- return hasOverflowClip() && hasLayer() && layer()->usesCompositedScrolling();
+ return hasOverflowClip() && hasLayer() && layer()->scrollableArea()->usesCompositedScrolling();
}
void RenderBox::autoscroll(const IntPoint& position)
{
- if (layer())
- layer()->autoscroll(position);
+ Frame* frame = this->frame();
+ if (!frame)
+ return;
+
+ FrameView* frameView = frame->view();
+ if (!frameView)
+ return;
+
+ IntPoint currentDocumentPosition = frameView->windowToContents(position);
+ scrollRectToVisible(LayoutRect(currentDocumentPosition, LayoutSize(1, 1)), ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignToEdgeIfNeeded);
}
bool RenderBox::autoscrollInProgress() const
{
- return frame() && frame()->page() && frame()->page()->autoscrollInProgress(this);
+ return frame() && frame()->page() && frame()->page()->autoscrollController().autoscrollInProgress(this);
}
// There are two kinds of renderer that can autoscroll.
@@ -811,7 +887,7 @@ IntSize RenderBox::calculateAutoscrollDirection(const IntPoint& windowPoint) con
RenderBox* RenderBox::findAutoscrollable(RenderObject* renderer)
{
while (renderer && !(renderer->isBox() && toRenderBox(renderer)->canAutoscroll())) {
- if (!renderer->parent() && renderer->node() == &renderer->document() && renderer->document().ownerElement())
+ if (!renderer->parent() && renderer->node() == renderer->document() && renderer->document().ownerElement())
renderer = renderer->document().ownerElement()->renderer();
else
renderer = renderer->parent();
@@ -820,10 +896,82 @@ RenderBox* RenderBox::findAutoscrollable(RenderObject* renderer)
return renderer && renderer->isBox() ? toRenderBox(renderer) : 0;
}
-void RenderBox::panScroll(const IntPoint& source)
+static inline int adjustedScrollDelta(int beginningDelta)
+{
+ // This implemention matches Firefox's.
+ // http://mxr.mozilla.org/firefox/source/toolkit/content/widgets/browser.xml#856.
+ const int speedReducer = 12;
+
+ int adjustedDelta = beginningDelta / speedReducer;
+ if (adjustedDelta > 1)
+ adjustedDelta = static_cast<int>(adjustedDelta * sqrt(static_cast<double>(adjustedDelta))) - 1;
+ else if (adjustedDelta < -1)
+ adjustedDelta = static_cast<int>(adjustedDelta * sqrt(static_cast<double>(-adjustedDelta))) + 1;
+
+ return adjustedDelta;
+}
+
+static inline IntSize adjustedScrollDelta(const IntSize& delta)
+{
+ return IntSize(adjustedScrollDelta(delta.width()), adjustedScrollDelta(delta.height()));
+}
+
+void RenderBox::panScroll(const IntPoint& sourcePoint)
+{
+ Frame* frame = this->frame();
+ if (!frame)
+ return;
+
+ IntPoint lastKnownMousePosition = frame->eventHandler().lastKnownMousePosition();
+
+ // We need to check if the last known mouse position is out of the window. When the mouse is out of the window, the position is incoherent
+ static IntPoint previousMousePosition;
+ if (lastKnownMousePosition.x() < 0 || lastKnownMousePosition.y() < 0)
+ lastKnownMousePosition = previousMousePosition;
+ else
+ previousMousePosition = lastKnownMousePosition;
+
+ IntSize delta = lastKnownMousePosition - sourcePoint;
+
+ if (abs(delta.width()) <= ScrollView::noPanScrollRadius) // at the center we let the space for the icon
+ delta.setWidth(0);
+ if (abs(delta.height()) <= ScrollView::noPanScrollRadius)
+ delta.setHeight(0);
+
+ scrollByRecursively(adjustedScrollDelta(delta), ScrollOffsetClamped);
+}
+
+void RenderBox::scrollByRecursively(const IntSize& delta, ScrollOffsetClamping clamp)
{
- if (layer())
- layer()->panScrollFromPoint(source);
+ if (delta.isZero())
+ return;
+
+ bool restrictedByLineClamp = false;
+ if (parent())
+ restrictedByLineClamp = !parent()->style()->lineClamp().isNone();
+
+ if (hasOverflowClip() && !restrictedByLineClamp) {
+ IntSize newScrollOffset = layer()->scrollableArea()->adjustedScrollOffset() + delta;
+ layer()->scrollableArea()->scrollToOffset(newScrollOffset, clamp);
+
+ // If this layer can't do the scroll we ask the next layer up that can scroll to try
+ IntSize remainingScrollOffset = newScrollOffset - layer()->scrollableArea()->adjustedScrollOffset();
+ if (!remainingScrollOffset.isZero() && parent()) {
+ if (RenderBox* scrollableBox = enclosingScrollableBox())
+ scrollableBox->scrollByRecursively(remainingScrollOffset, clamp);
+
+ Frame* frame = this->frame();
+ if (frame && frame->page())
+ frame->page()->autoscrollController().updateAutoscrollRenderer();
+ }
+ } else if (view()->frameView()) {
+ // If we are here, we were called on a renderer that can be programmatically scrolled, but doesn't
+ // have an overflow clip. Which means that it is a document node that can be scrolled.
+ view()->frameView()->scrollBy(delta);
+
+ // FIXME: If we didn't scroll the whole way, do we want to try looking at the frames ownerElement?
+ // https://bugs.webkit.org/show_bug.cgi?id=28237
+ }
}
bool RenderBox::needsPreferredWidthsRecalculation() const
@@ -835,7 +983,7 @@ IntSize RenderBox::scrolledContentOffset() const
{
ASSERT(hasOverflowClip());
ASSERT(hasLayer());
- return layer()->scrolledContentOffset();
+ return layer()->scrollableArea()->scrollOffset();
}
LayoutSize RenderBox::cachedSizeForOverflowClip() const
@@ -1116,7 +1264,11 @@ void RenderBox::paintBoxDecorations(PaintInfo& paintInfo, const LayoutPoint& pai
LayoutRect paintRect = borderBoxRectInRegion(paintInfo.renderRegion);
paintRect.moveBy(paintOffset);
+ paintBoxDecorationsWithRect(paintInfo, paintOffset, paintRect);
+}
+void RenderBox::paintBoxDecorationsWithRect(PaintInfo& paintInfo, const LayoutPoint& paintOffset, const LayoutRect& paintRect)
+{
BackgroundBleedAvoidance bleedAvoidance = determineBackgroundBleedAvoidance(paintInfo.context);
// FIXME: Should eventually give the theme control over whether the box shadow should paint, since controls could have
@@ -1135,6 +1287,14 @@ void RenderBox::paintBoxDecorations(PaintInfo& paintInfo, const LayoutPoint& pai
paintInfo.context->beginTransparencyLayer(1);
}
+ paintBackgroundWithBorderAndBoxShadow(paintInfo, paintRect, bleedAvoidance);
+
+ if (bleedAvoidance == BackgroundBleedUseTransparencyLayer)
+ paintInfo.context->endLayer();
+}
+
+void RenderBox::paintBackgroundWithBorderAndBoxShadow(PaintInfo& paintInfo, const LayoutRect& paintRect, BackgroundBleedAvoidance bleedAvoidance)
+{
// If we have a native theme appearance, paint that before painting our background.
// The theme will tell us whether or not we should also paint the CSS background.
IntRect snappedPaintRect(pixelSnappedIntRect(paintRect));
@@ -1151,11 +1311,8 @@ void RenderBox::paintBoxDecorations(PaintInfo& paintInfo, const LayoutPoint& pai
paintBoxShadow(paintInfo, paintRect, style(), Inset);
// The theme will tell us whether or not we should also paint the CSS border.
- if (bleedAvoidance != BackgroundBleedBackgroundOverBorder && (!style()->hasAppearance() || (!themePainted && RenderTheme::theme().paintBorderOnly(this, paintInfo, snappedPaintRect))) && style()->hasBorder())
+ if (bleedAvoidance != BackgroundBleedBackgroundOverBorder && (!style()->hasAppearance() || (!themePainted && RenderTheme::theme().paintBorderOnly(this, paintInfo, snappedPaintRect))) && style()->hasBorder() && !(isTable() && toRenderTable(this)->collapseBorders()))
paintBorder(paintInfo, paintRect, style(), bleedAvoidance);
-
- if (bleedAvoidance == BackgroundBleedUseTransparencyLayer)
- paintInfo.context->endLayer();
}
void RenderBox::paintBackground(const PaintInfo& paintInfo, const LayoutRect& paintRect, BackgroundBleedAvoidance bleedAvoidance)
@@ -1236,13 +1393,16 @@ static bool isCandidateForOpaquenessTest(RenderBox* childBox)
if (!childBox->width() || !childBox->height())
return false;
if (RenderLayer* childLayer = childBox->layer()) {
- if (childLayer->isComposited())
+ // FIXME: perhaps this could be less conservative?
+ if (childLayer->compositingState() != NotComposited)
return false;
// FIXME: Deal with z-index.
if (!childStyle->hasAutoZIndex())
return false;
if (childLayer->hasTransform() || childLayer->isTransparent() || childLayer->hasFilter())
return false;
+ if (childBox->hasOverflowClip() && childStyle->hasBorderRadius())
+ return false;
}
return true;
}
@@ -1326,6 +1486,22 @@ void RenderBox::paintMask(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
paintMaskImages(paintInfo, paintRect);
}
+void RenderBox::paintClippingMask(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
+{
+ if (!paintInfo.shouldPaintWithinRoot(this) || style()->visibility() != VISIBLE || paintInfo.phase != PaintPhaseClippingMask || paintInfo.context->paintingDisabled())
+ return;
+
+ if (!layer() || layer()->compositingState() != PaintsIntoOwnBacking)
+ return;
+
+ // We should never have this state in this function. A layer with a mask
+ // should have always created its own backing if it became composited.
+ ASSERT(layer()->compositingState() != HasOwnBackingButPaintsIntoAncestor);
+
+ LayoutRect paintRect = LayoutRect(paintOffset, size());
+ paintInfo.context->fillRect(pixelSnappedIntRect(paintRect), Color::black);
+}
+
void RenderBox::paintMaskImages(const PaintInfo& paintInfo, const LayoutRect& paintRect)
{
// Figure out if we need to push a transparency layer to render our mask.
@@ -1401,11 +1577,11 @@ void RenderBox::paintFillLayers(const PaintInfo& paintInfo, const Color& c, cons
// the layer recursion into paintFillLayerExtended, or to compute the layer geometry here
// and pass it down.
- if (!shouldDrawBackgroundInSeparateBuffer && curLayer->blendMode() != BlendModeNormal)
+ if (!shouldDrawBackgroundInSeparateBuffer && curLayer->blendMode() != blink::WebBlendModeNormal)
shouldDrawBackgroundInSeparateBuffer = true;
// The clipOccludesNextLayers condition must be evaluated first to avoid short-circuiting.
- if (curLayer->clipOccludesNextLayers(curLayer == fillLayer) && curLayer->hasOpaqueImage(this) && curLayer->image()->canRender(this, style()->effectiveZoom()) && curLayer->hasRepeatXY() && curLayer->blendMode() == BlendModeNormal)
+ if (curLayer->clipOccludesNextLayers(curLayer == fillLayer) && curLayer->hasOpaqueImage(this) && curLayer->image()->canRender(this, style()->effectiveZoom()) && curLayer->hasRepeatXY() && curLayer->blendMode() == blink::WebBlendModeNormal && !boxShadowShouldBeAppliedToBackground(bleedAvoidance))
break;
curLayer = curLayer->next();
}
@@ -1576,12 +1752,13 @@ LayoutRect RenderBox::overflowClipRect(const LayoutPoint& location, RenderRegion
clipRect.setLocation(location + clipRect.location() + LayoutSize(borderLeft(), borderTop()));
clipRect.setSize(clipRect.size() - LayoutSize(borderLeft() + borderRight(), borderTop() + borderBottom()));
+ if (!hasOverflowClip())
+ return clipRect;
+
// Subtract out scrollbars if we have them.
- if (layer()) {
- if (style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
- clipRect.move(layer()->verticalScrollbarWidth(relevancy), 0);
- clipRect.contract(layer()->verticalScrollbarWidth(relevancy), layer()->horizontalScrollbarHeight(relevancy));
- }
+ if (style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
+ clipRect.move(layer()->scrollableArea()->verticalScrollbarWidth(relevancy), 0);
+ clipRect.contract(layer()->scrollableArea()->verticalScrollbarWidth(relevancy), layer()->scrollableArea()->horizontalScrollbarHeight(relevancy));
return clipRect;
}
@@ -1616,7 +1793,7 @@ LayoutRect RenderBox::clipRect(const LayoutPoint& location, RenderRegion* region
return clipRect;
}
-LayoutUnit RenderBox::shrinkLogicalWidthToAvoidFloats(LayoutUnit childMarginStart, LayoutUnit childMarginEnd, const RenderBlock* cb, RenderRegion* region) const
+LayoutUnit RenderBox::shrinkLogicalWidthToAvoidFloats(LayoutUnit childMarginStart, LayoutUnit childMarginEnd, const RenderBlockFlow* cb, RenderRegion* region) const
{
RenderRegion* containingBlockRegion = 0;
LayoutUnit logicalTopPosition = logicalTop();
@@ -1626,7 +1803,7 @@ LayoutUnit RenderBox::shrinkLogicalWidthToAvoidFloats(LayoutUnit childMarginStar
containingBlockRegion = cb->clampToStartAndEndRegions(region);
}
- LayoutUnit result = cb->availableLogicalWidthForLine(logicalTopPosition, false, containingBlockRegion) - childMarginStart - childMarginEnd;
+ LayoutUnit result = cb->availableLogicalWidthForLineInRegion(logicalTopPosition, false, containingBlockRegion) - childMarginStart - childMarginEnd;
// We need to see if margins on either the start side or the end side can contain the floats in question. If they can,
// then just using the line width is inaccurate. In the case where a float completely fits, we don't need to use the line
@@ -1636,7 +1813,7 @@ LayoutUnit RenderBox::shrinkLogicalWidthToAvoidFloats(LayoutUnit childMarginStar
if (childMarginStart > 0) {
LayoutUnit startContentSide = cb->startOffsetForContent(containingBlockRegion);
LayoutUnit startContentSideWithMargin = startContentSide + childMarginStart;
- LayoutUnit startOffset = cb->startOffsetForLine(logicalTopPosition, false, containingBlockRegion);
+ LayoutUnit startOffset = cb->startOffsetForLineInRegion(logicalTopPosition, false, containingBlockRegion);
if (startOffset > startContentSideWithMargin)
result += childMarginStart;
else
@@ -1646,7 +1823,7 @@ LayoutUnit RenderBox::shrinkLogicalWidthToAvoidFloats(LayoutUnit childMarginStar
if (childMarginEnd > 0) {
LayoutUnit endContentSide = cb->endOffsetForContent(containingBlockRegion);
LayoutUnit endContentSideWithMargin = endContentSide + childMarginEnd;
- LayoutUnit endOffset = cb->endOffsetForLine(logicalTopPosition, false, containingBlockRegion);
+ LayoutUnit endOffset = cb->endOffsetForLineInRegion(logicalTopPosition, false, containingBlockRegion);
if (endOffset > endContentSideWithMargin)
result += childMarginEnd;
else
@@ -1700,7 +1877,7 @@ LayoutUnit RenderBox::containingBlockAvailableLineWidthInRegion(RenderRegion* re
logicalTopPosition = max(logicalTopPosition, logicalTopPosition + offsetFromLogicalTopOfRegion);
containingBlockRegion = cb->clampToStartAndEndRegions(region);
}
- return cb->availableLogicalWidthForLine(logicalTopPosition, false, containingBlockRegion, availableLogicalHeight(IncludeMarginBorderPadding));
+ return cb->availableLogicalWidthForLineInRegion(logicalTopPosition, false, containingBlockRegion, availableLogicalHeight(IncludeMarginBorderPadding));
}
LayoutUnit RenderBox::perpendicularContainingBlockLogicalHeight() const
@@ -2074,7 +2251,9 @@ static float getMaxWidthListMarker(const RenderBox* renderer)
if (!itemChild->isListMarker())
continue;
RenderBox* itemMarker = toRenderBox(itemChild);
- if (itemMarker->requiresLayoutToDetermineWidth() && itemMarker->needsLayout()) {
+ // FIXME: canDetermineWidthWithoutLayout expects us to use fixedOffsetWidth, which this code
+ // does not do! This check is likely wrong.
+ if (!itemMarker->canDetermineWidthWithoutLayout() && itemMarker->needsLayout()) {
// Make sure to compute the autosized width.
itemMarker->layout();
}
@@ -2131,7 +2310,7 @@ void RenderBox::computeLogicalWidthInRegion(LogicalExtentComputedValues& compute
computedValues.m_margins.m_start = minimumValueForLength(styleToUse->marginStart(), containerLogicalWidth, renderView);
computedValues.m_margins.m_end = minimumValueForLength(styleToUse->marginEnd(), containerLogicalWidth, renderView);
if (treatAsReplaced)
- computedValues.m_extent = max<LayoutUnit>(floatValueForLength(logicalWidthLength, 0) + borderAndPaddingLogicalWidth(), minPreferredLogicalWidth());
+ computedValues.m_extent = max<LayoutUnit>(floatValueForLength(logicalWidthLength, 0, 0) + borderAndPaddingLogicalWidth(), minPreferredLogicalWidth());
return;
}
@@ -2241,7 +2420,7 @@ LayoutUnit RenderBox::computeLogicalWidthInRegionUsing(SizeType widthType, Lengt
LayoutUnit logicalWidthResult = fillAvailableMeasure(availableLogicalWidth, marginStart, marginEnd);
if (shrinkToAvoidFloats() && cb->containsFloats())
- logicalWidthResult = min(logicalWidthResult, shrinkLogicalWidthToAvoidFloats(marginStart, marginEnd, cb, region));
+ logicalWidthResult = min(logicalWidthResult, shrinkLogicalWidthToAvoidFloats(marginStart, marginEnd, toRenderBlockFlow(cb), region));
if (widthType == MainOrPreferredSize && sizesLogicalWidthToFitContent(widthType))
return max(minPreferredLogicalWidth(), min(maxPreferredLogicalWidth(), logicalWidthResult));
@@ -2317,8 +2496,7 @@ bool RenderBox::sizesLogicalWidthToFitContent(SizeType widthType) const
// stretching column flexbox.
// FIXME: Think about block-flow here.
// https://bugs.webkit.org/show_bug.cgi?id=46473
- if (logicalWidth.type() == Auto && !isStretchingColumnFlexItem(this) && node() && (node()->hasTagName(inputTag)
- || node()->hasTagName(selectTag) || node()->hasTagName(buttonTag) || isHTMLTextAreaElement(node()) || node()->hasTagName(legendTag)))
+ if (logicalWidth.type() == Auto && !isStretchingColumnFlexItem(this) && autoWidthShouldFitContent())
return true;
if (isHorizontalWritingMode() != containingBlock()->isHorizontalWritingMode())
@@ -2327,6 +2505,15 @@ bool RenderBox::sizesLogicalWidthToFitContent(SizeType widthType) const
return false;
}
+bool RenderBox::autoWidthShouldFitContent() const
+{
+ if (node() && (node()->hasTagName(inputTag) || node()->hasTagName(selectTag) || node()->hasTagName(buttonTag)
+ || isHTMLTextAreaElement(node()) || node()->hasTagName(legendTag)))
+ return true;
+
+ return false;
+}
+
void RenderBox::computeInlineDirectionMargins(RenderBlock* containingBlock, LayoutUnit containerWidth, LayoutUnit childWidth, LayoutUnit& marginStart, LayoutUnit& marginEnd) const
{
const RenderStyle* containingBlockStyle = containingBlock->style();
@@ -2812,7 +2999,6 @@ LayoutUnit RenderBox::computeReplacedLogicalWidthUsing(Length logicalWidth) cons
case Intrinsic:
case MinIntrinsic:
case Auto:
- case Relative:
case ExtendToZoom:
case Undefined:
return intrinsicLogicalWidth();
@@ -2984,7 +3170,7 @@ LayoutUnit RenderBox::containingBlockLogicalWidthForPositioned(const RenderBoxMo
// Use viewport as container for top-level fixed-position elements.
if (style()->position() == FixedPosition && containingBlock->isRenderView()) {
- const RenderView* view = static_cast<const RenderView*>(containingBlock);
+ const RenderView* view = toRenderView(containingBlock);
if (FrameView* frameView = view->frameView()) {
LayoutRect viewportRect = frameView->viewportConstrainedVisibleContentRect();
return containingBlock->isHorizontalWritingMode() ? viewportRect.width() : viewportRect.height();
@@ -3046,7 +3232,7 @@ LayoutUnit RenderBox::containingBlockLogicalHeightForPositioned(const RenderBoxM
// Use viewport as container for top-level fixed-position elements.
if (style()->position() == FixedPosition && containingBlock->isRenderView()) {
- const RenderView* view = static_cast<const RenderView*>(containingBlock);
+ const RenderView* view = toRenderView(containingBlock);
if (FrameView* frameView = view->frameView()) {
LayoutRect viewportRect = frameView->viewportConstrainedVisibleContentRect();
return containingBlock->isHorizontalWritingMode() ? viewportRect.height() : viewportRect.width();
@@ -3295,6 +3481,15 @@ static void computeLogicalLeftPositionedOffset(LayoutUnit& logicalLeftPos, const
logicalLeftPos += (child->isHorizontalWritingMode() ? containerBlock->borderLeft() : containerBlock->borderTop());
}
+void RenderBox::shrinkToFitWidth(const LayoutUnit availableSpace, const LayoutUnit logicalLeftValue, const LayoutUnit bordersPlusPadding, LogicalExtentComputedValues& computedValues) const
+{
+ // FIXME: would it be better to have shrink-to-fit in one step?
+ LayoutUnit preferredWidth = maxPreferredLogicalWidth() - bordersPlusPadding;
+ LayoutUnit preferredMinWidth = minPreferredLogicalWidth() - bordersPlusPadding;
+ LayoutUnit availableWidth = availableSpace - logicalLeftValue;
+ computedValues.m_extent = min(max(preferredMinWidth, availableWidth), preferredWidth);
+}
+
void RenderBox::computePositionedLogicalWidthUsing(Length logicalWidth, const RenderBoxModelObject* containerBlock, TextDirection containerDirection,
LayoutUnit containerLogicalWidth, LayoutUnit bordersPlusPadding,
Length logicalLeft, Length logicalRight, Length marginLogicalLeft, Length marginLogicalRight,
@@ -3317,7 +3512,6 @@ void RenderBox::computePositionedLogicalWidthUsing(Length logicalWidth, const Re
RenderView* renderView = view();
LayoutUnit& marginLogicalLeftValue = style()->isLeftToRightDirection() ? computedValues.m_margins.m_start : computedValues.m_margins.m_end;
LayoutUnit& marginLogicalRightValue = style()->isLeftToRightDirection() ? computedValues.m_margins.m_end : computedValues.m_margins.m_start;
-
if (!logicalLeftIsAuto && !logicalWidthIsAuto && !logicalRightIsAuto) {
/*-----------------------------------------------------------------------*\
* If none of the three is 'auto': If both 'margin-left' and 'margin-
@@ -3438,11 +3632,7 @@ void RenderBox::computePositionedLogicalWidthUsing(Length logicalWidth, const Re
// RULE 3: (use shrink-to-fit for width, and no need solve of right)
logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth, renderView);
- // FIXME: would it be better to have shrink-to-fit in one step?
- LayoutUnit preferredWidth = maxPreferredLogicalWidth() - bordersPlusPadding;
- LayoutUnit preferredMinWidth = minPreferredLogicalWidth() - bordersPlusPadding;
- LayoutUnit availableWidth = availableSpace - logicalLeftValue;
- computedValues.m_extent = min(max(preferredMinWidth, availableWidth), preferredWidth);
+ shrinkToFitWidth(availableSpace, logicalLeftValue, bordersPlusPadding, computedValues);
} else if (logicalLeftIsAuto && !logicalWidthIsAuto && !logicalRightIsAuto) {
// RULE 4: (solve for left)
computedValues.m_extent = adjustContentBoxLogicalWidthForBoxSizing(valueForLength(logicalWidth, containerLogicalWidth, renderView));
@@ -3450,7 +3640,10 @@ void RenderBox::computePositionedLogicalWidthUsing(Length logicalWidth, const Re
} else if (!logicalLeftIsAuto && logicalWidthIsAuto && !logicalRightIsAuto) {
// RULE 5: (solve for width)
logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth, renderView);
- computedValues.m_extent = availableSpace - (logicalLeftValue + valueForLength(logicalRight, containerLogicalWidth, renderView));
+ if (autoWidthShouldFitContent())
+ shrinkToFitWidth(availableSpace, logicalLeftValue, bordersPlusPadding, computedValues);
+ else
+ computedValues.m_extent = availableSpace - (logicalLeftValue + valueForLength(logicalRight, containerLogicalWidth, renderView));
} else if (!logicalLeftIsAuto && !logicalWidthIsAuto && logicalRightIsAuto) {
// RULE 6: (no need solve for right)
logicalLeftValue = valueForLength(logicalLeft, containerLogicalWidth, renderView);
@@ -3474,6 +3667,10 @@ void RenderBox::computePositionedLogicalWidthUsing(Length logicalWidth, const Re
}
}
+ if (containerBlock->isBox() && toRenderBox(containerBlock)->scrollsOverflowY() && containerBlock->style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft()) {
+ logicalLeftValue = logicalLeftValue + toRenderBox(containerBlock)->verticalScrollbarWidth();
+ }
+
computedValues.m_position = logicalLeftValue + marginLogicalLeftValue;
computeLogicalLeftPositionedOffset(computedValues.m_position, this, computedValues.m_extent, containerBlock, containerLogicalWidth);
}
@@ -3646,18 +3843,18 @@ void RenderBox::computePositionedLogicalHeightUsing(Length logicalHeightLength,
bool logicalBottomIsAuto = logicalBottom.isAuto();
RenderView* renderView = view();
+ LayoutUnit resolvedLogicalHeight;
// Height is never unsolved for tables.
if (isTable()) {
- logicalHeightLength.setValue(Fixed, contentLogicalHeight);
+ resolvedLogicalHeight = contentLogicalHeight;
logicalHeightIsAuto = false;
+ } else {
+ if (logicalHeightLength.isIntrinsic())
+ resolvedLogicalHeight = computeIntrinsicLogicalContentHeightUsing(logicalHeightLength, contentLogicalHeight, bordersPlusPadding);
+ else
+ resolvedLogicalHeight = adjustContentBoxLogicalHeightForBoxSizing(valueForLength(logicalHeightLength, containerLogicalHeight, renderView));
}
- LayoutUnit resolvedLogicalHeight;
- if (logicalHeightLength.isIntrinsic())
- resolvedLogicalHeight = computeIntrinsicLogicalContentHeightUsing(logicalHeightLength, contentLogicalHeight, bordersPlusPadding);
- else
- resolvedLogicalHeight = adjustContentBoxLogicalHeightForBoxSizing(valueForLength(logicalHeightLength, containerLogicalHeight, renderView));
-
if (!logicalTopIsAuto && !logicalHeightIsAuto && !logicalBottomIsAuto) {
/*-----------------------------------------------------------------------*\
* If none of the three are 'auto': If both 'margin-top' and 'margin-
@@ -4097,7 +4294,7 @@ LayoutRect RenderBox::localCaretRect(InlineBox* box, int caretOffset, LayoutUnit
// FIXME: Border/padding should be added for all elements but this workaround
// is needed because we use offsets inside an "atomic" element to represent
// positions before and after the element in deprecated editing offsets.
- if (node() && !(editingIgnoresContent(node()) || isTableElement(node()))) {
+ if (node() && !(editingIgnoresContent(node()) || isRenderedTable(node()))) {
rect.setX(rect.x() + borderLeft() + paddingLeft());
rect.setY(rect.y() + paddingTop() + borderTop());
}
@@ -4503,6 +4700,11 @@ LayoutRect RenderBox::layoutOverflowRectForPropagation(RenderStyle* parentStyle)
{
// Only propagate interior layout overflow if we don't clip it.
LayoutRect rect = borderBoxRect();
+ // We want to include the margin, but only when it adds height. Quirky margins don't contribute height
+ // nor do the margins of self-collapsing blocks.
+ if (!style()->hasMarginAfterQuirk() && !isSelfCollapsingBlock())
+ rect.expand(isHorizontalWritingMode() ? LayoutSize(LayoutUnit(), marginAfter()) : LayoutSize(marginAfter(), LayoutUnit()));
+
if (!hasOverflowClip())
rect.unite(layoutOverflowRect());
@@ -4547,7 +4749,7 @@ LayoutRect RenderBox::noOverflowRect() const
// writing modes, x in vertical writing modes), which is always "logical top". Apart from the
// flipping, this method does the same as clientBoxRect().
- LayoutUnit left = borderLeft();
+ LayoutUnit left = borderLeft() + (style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft() ? verticalScrollbarWidth() : 0);
LayoutUnit top = borderTop();
LayoutUnit right = borderRight();
LayoutUnit bottom = borderBottom();
@@ -4562,7 +4764,10 @@ LayoutRect RenderBox::noOverflowRect() const
// FIXME: when the above mentioned bug is fixed, it should hopefully be possible to call
// clientBoxRect() or paddingBoxRect() in this method, rather than fiddling with the edges on
// our own.
- rect.contract(verticalScrollbarWidth(), horizontalScrollbarHeight());
+ if (style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
+ rect.contract(0, horizontalScrollbarHeight());
+ else
+ rect.contract(verticalScrollbarWidth(), horizontalScrollbarHeight());
return rect;
}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderBox.h b/chromium/third_party/WebKit/Source/core/rendering/RenderBox.h
index 208cfe747cb..350b640d75c 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderBox.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderBox.h
@@ -23,10 +23,10 @@
#ifndef RenderBox_h
#define RenderBox_h
-#include "core/platform/ScrollTypes.h"
#include "core/rendering/RenderBoxModelObject.h"
#include "core/rendering/RenderOverflow.h"
#include "core/rendering/shapes/ShapeOutsideInfo.h"
+#include "platform/scroll/ScrollTypes.h"
namespace WebCore {
@@ -42,6 +42,11 @@ enum ShouldComputePreferred { ComputeActual, ComputePreferred };
enum ContentsClipBehavior { ForceContentsClip, SkipContentsClipIfPossible };
+enum ScrollOffsetClamping {
+ ScrollOffsetUnclamped,
+ ScrollOffsetClamped
+};
+
class RenderBox : public RenderBoxModelObject {
public:
explicit RenderBox(ContainerNode*);
@@ -171,6 +176,8 @@ public:
RenderBox* nextSiblingBox() const;
RenderBox* parentBox() const;
+ bool canResize() const;
+
// Visual and layout overflow are in the coordinate space of the box. This means that they aren't purely physical directions.
// For horizontal-tb and vertical-lr they will match physical directions, but for horizontal-bt and vertical-rl, the top/bottom and left/right
// respectively are flipped when compared to their physical counterparts. For example minX is on the left in vertical-lr,
@@ -216,7 +223,7 @@ public:
virtual int pixelSnappedOffsetWidth() const OVERRIDE FINAL;
virtual int pixelSnappedOffsetHeight() const OVERRIDE FINAL;
- bool requiresLayoutToDetermineWidth() const;
+ bool canDetermineWidthWithoutLayout() const;
LayoutUnit fixedOffsetWidth() const;
// More IE extensions. clientWidth and clientHeight represent the interior of an object
@@ -245,6 +252,10 @@ public:
virtual void setScrollLeft(int);
virtual void setScrollTop(int);
+ void scrollToOffset(const IntSize&);
+ void scrollByRecursively(const IntSize& delta, ScrollOffsetClamping = ScrollOffsetUnclamped);
+ void scrollRectToVisible(const LayoutRect&, const ScrollAlignment& alignX, const ScrollAlignment& alignY);
+
virtual LayoutUnit marginTop() const OVERRIDE { return m_marginBox.top(); }
virtual LayoutUnit marginBottom() const OVERRIDE { return m_marginBox.bottom(); }
virtual LayoutUnit marginLeft() const OVERRIDE { return m_marginBox.left(); }
@@ -339,24 +350,15 @@ public:
LayoutUnit adjustContentBoxLogicalHeightForBoxSizing(LayoutUnit height) const;
struct ComputedMarginValues {
- ComputedMarginValues()
- : m_before(0)
- , m_after(0)
- , m_start(0)
- , m_end(0)
- {
- }
+ ComputedMarginValues() { }
+
LayoutUnit m_before;
LayoutUnit m_after;
LayoutUnit m_start;
LayoutUnit m_end;
};
struct LogicalExtentComputedValues {
- LogicalExtentComputedValues()
- : m_extent(0)
- , m_position(0)
- {
- }
+ LogicalExtentComputedValues() { }
LayoutUnit m_extent;
LayoutUnit m_position;
@@ -419,7 +421,7 @@ public:
// of a containing block). HTML4 buttons, <select>s, <input>s, legends, and floating/compact elements do this.
bool sizesLogicalWidthToFitContent(SizeType) const;
- LayoutUnit shrinkLogicalWidthToAvoidFloats(LayoutUnit childMarginStart, LayoutUnit childMarginEnd, const RenderBlock* cb, RenderRegion*) const;
+ LayoutUnit shrinkLogicalWidthToAvoidFloats(LayoutUnit childMarginStart, LayoutUnit childMarginEnd, const RenderBlockFlow* cb, RenderRegion*) const;
LayoutUnit computeLogicalWidthInRegionUsing(SizeType, Length logicalWidth, LayoutUnit availableLogicalWidth, const RenderBlock* containingBlock, RenderRegion*) const;
LayoutUnit computeLogicalHeightUsing(const Length& height, LayoutUnit intrinsicContentHeight) const;
@@ -450,8 +452,7 @@ public:
int horizontalScrollbarHeight() const;
int instrinsicScrollbarLogicalWidth() const;
int scrollbarLogicalHeight() const { return style()->isHorizontalWritingMode() ? horizontalScrollbarHeight() : verticalScrollbarWidth(); }
- virtual bool scroll(ScrollDirection, ScrollGranularity, float multiplier = 1, Node** stopNode = 0);
- virtual bool logicalScroll(ScrollLogicalDirection, ScrollGranularity, float multiplier = 1, Node** stopNode = 0);
+ virtual bool scroll(ScrollDirection, ScrollGranularity, float multiplier = 1);
bool canBeScrolledAndHasScrollableArea() const;
virtual bool canBeProgramaticallyScrolled() const;
virtual void autoscroll(const IntPoint&);
@@ -491,6 +492,7 @@ public:
virtual void paintObject(PaintInfo&, const LayoutPoint&) { ASSERT_NOT_REACHED(); }
virtual void paintBoxDecorations(PaintInfo&, const LayoutPoint&);
virtual void paintMask(PaintInfo&, const LayoutPoint&);
+ virtual void paintClippingMask(PaintInfo&, const LayoutPoint&);
virtual void imageChanged(WrappedImagePtr, const IntRect* = 0);
// Called when a positioned object moves but doesn't necessarily change size. A simplified layout is attempted
@@ -597,6 +599,12 @@ public:
return ShapeOutsideInfo::isEnabledFor(this) ? ShapeOutsideInfo::info(this) : 0;
}
+ void markShapeOutsideDependentsForLayout()
+ {
+ if (isFloating())
+ removeFloatingOrPositionedChildFromBlockLists();
+ }
+
protected:
virtual void willBeDestroyed();
@@ -608,12 +616,14 @@ protected:
virtual bool foregroundIsKnownToBeOpaqueInRect(const LayoutRect& localRect, unsigned maxDepthToTest) const;
virtual bool computeBackgroundIsKnownToBeObscured() OVERRIDE;
+ virtual void paintBackgroundWithBorderAndBoxShadow(PaintInfo&, const LayoutRect&, BackgroundBleedAvoidance);
void paintBackground(const PaintInfo&, const LayoutRect&, BackgroundBleedAvoidance = BackgroundBleedNone);
void paintFillLayer(const PaintInfo&, const Color&, const FillLayer*, const LayoutRect&, BackgroundBleedAvoidance, CompositeOperator, RenderObject* backgroundObject);
void paintFillLayers(const PaintInfo&, const Color&, const FillLayer*, const LayoutRect&, BackgroundBleedAvoidance = BackgroundBleedNone, CompositeOperator = CompositeSourceOver, RenderObject* backgroundObject = 0);
void paintMaskImages(const PaintInfo&, const LayoutRect&);
+ void paintBoxDecorationsWithRect(PaintInfo&, const LayoutPoint&, const LayoutRect&);
BackgroundBleedAvoidance determineBackgroundBleedAvoidance(GraphicsContext*) const;
bool backgroundHasOpaqueTopLayer() const;
@@ -636,11 +646,11 @@ protected:
virtual void computeSelfHitTestRects(Vector<LayoutRect>&, const LayoutPoint& layerOffset) const OVERRIDE;
private:
- void updateShapeOutsideInfoAfterStyleChange(const ShapeValue* shapeOutside, const ShapeValue* oldShapeOutside);
+ void updateShapeOutsideInfoAfterStyleChange(const RenderStyle&, const RenderStyle* oldStyle);
void updateGridPositionAfterStyleChange(const RenderStyle*);
- bool includeVerticalScrollbarSize() const;
- bool includeHorizontalScrollbarSize() const;
+ bool autoWidthShouldFitContent() const;
+ void shrinkToFitWidth(const LayoutUnit availableSpace, const LayoutUnit logicalLeftValue, const LayoutUnit bordersPlusPadding, LogicalExtentComputedValues&) const;
// Returns true if we did a full repaint
bool repaintLayerRectsForImage(WrappedImagePtr image, const FillLayer* layers, bool drawingBackground);
@@ -677,10 +687,6 @@ private:
virtual LayoutRect frameRectForStickyPositioning() const OVERRIDE FINAL { return frameRect(); }
- // This method performs the actual scroll. Override if scrolling without a RenderLayer. The scroll() and logicalScroll()
- // are responsible for scroll propagation/bubbling and call this method to do the actual scrolling
- virtual bool scrollImpl(ScrollDirection, ScrollGranularity, float);
-
private:
// The width/height of the contents + borders + padding. The x/y location is relative to our container (which is not always our parent).
LayoutRect m_frameRect;
@@ -704,26 +710,9 @@ protected:
// Our overflow information.
OwnPtr<RenderOverflow> m_overflow;
-
-private:
- // Used to store state between styleWillChange and styleDidChange
- static bool s_hadOverflowClip;
};
-inline RenderBox* toRenderBox(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isBox());
- return static_cast<RenderBox*>(object);
-}
-
-inline const RenderBox* toRenderBox(const RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isBox());
- return static_cast<const RenderBox*>(object);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toRenderBox(const RenderBox*);
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderBox, isBox());
inline RenderBox* RenderBox::previousSiblingBox() const
{
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderBoxModelObject.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderBoxModelObject.cpp
index 932db84e2a0..caef81861c4 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderBoxModelObject.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderBoxModelObject.cpp
@@ -28,22 +28,23 @@
#include "HTMLNames.h"
#include "core/html/HTMLFrameOwnerElement.h"
-#include "core/page/Settings.h"
+#include "core/frame/Settings.h"
#include "core/page/scrolling/ScrollingConstraints.h"
-#include "core/platform/graphics/DrawLooper.h"
-#include "core/platform/graphics/GraphicsContextStateSaver.h"
-#include "core/platform/graphics/Path.h"
-#include "core/platform/graphics/transforms/TransformState.h"
+#include "core/rendering/CompositedLayerMapping.h"
#include "core/rendering/ImageQualityController.h"
#include "core/rendering/RenderBlock.h"
#include "core/rendering/RenderGeometryMap.h"
#include "core/rendering/RenderInline.h"
#include "core/rendering/RenderLayer.h"
-#include "core/rendering/RenderLayerBacking.h"
#include "core/rendering/RenderLayerCompositor.h"
#include "core/rendering/RenderNamedFlowThread.h"
#include "core/rendering/RenderRegion.h"
#include "core/rendering/RenderView.h"
+#include "core/rendering/style/ShadowList.h"
+#include "platform/geometry/TransformState.h"
+#include "platform/graphics/DrawLooper.h"
+#include "platform/graphics/GraphicsContextStateSaver.h"
+#include "platform/graphics/Path.h"
#include "wtf/CurrentTime.h"
using namespace std;
@@ -64,7 +65,7 @@ static ContinuationMap* continuationMap = 0;
// This HashMap is similar to the continuation map, but connects first-letter
// renderers to their remaining text fragments.
-typedef HashMap<const RenderBoxModelObject*, RenderObject*> FirstLetterRemainingTextMap;
+typedef HashMap<const RenderBoxModelObject*, RenderTextFragment*> FirstLetterRemainingTextMap;
static FirstLetterRemainingTextMap* firstLetterRemainingTextMap = 0;
void RenderBoxModelObject::setSelectionState(SelectionState state)
@@ -102,50 +103,43 @@ bool RenderBoxModelObject::hasAcceleratedCompositing() const
bool RenderBoxModelObject::startTransition(double timeOffset, CSSPropertyID propertyId, const RenderStyle* fromStyle, const RenderStyle* toStyle)
{
ASSERT(hasLayer());
- ASSERT(isComposited());
- return layer()->backing()->startTransition(timeOffset, propertyId, fromStyle, toStyle);
+ ASSERT(compositingState() == PaintsIntoOwnBacking);
+ return layer()->compositedLayerMapping()->startTransition(timeOffset, propertyId, fromStyle, toStyle);
}
void RenderBoxModelObject::transitionPaused(double timeOffset, CSSPropertyID propertyId)
{
ASSERT(hasLayer());
- ASSERT(isComposited());
- layer()->backing()->transitionPaused(timeOffset, propertyId);
+ ASSERT(compositingState() == PaintsIntoOwnBacking);
+ layer()->compositedLayerMapping()->transitionPaused(timeOffset, propertyId);
}
void RenderBoxModelObject::transitionFinished(CSSPropertyID propertyId)
{
ASSERT(hasLayer());
- ASSERT(isComposited());
- layer()->backing()->transitionFinished(propertyId);
+ ASSERT(compositingState() == PaintsIntoOwnBacking);
+ layer()->compositedLayerMapping()->transitionFinished(propertyId);
}
bool RenderBoxModelObject::startAnimation(double timeOffset, const CSSAnimationData* animation, const KeyframeList& keyframes)
{
ASSERT(hasLayer());
- ASSERT(isComposited());
- return layer()->backing()->startAnimation(timeOffset, animation, keyframes);
+ ASSERT(compositingState() == PaintsIntoOwnBacking);
+ return layer()->compositedLayerMapping()->startAnimation(timeOffset, animation, keyframes);
}
void RenderBoxModelObject::animationPaused(double timeOffset, const String& name)
{
ASSERT(hasLayer());
- ASSERT(isComposited());
- layer()->backing()->animationPaused(timeOffset, name);
+ ASSERT(compositingState() == PaintsIntoOwnBacking);
+ layer()->compositedLayerMapping()->animationPaused(timeOffset, name);
}
void RenderBoxModelObject::animationFinished(const String& name)
{
ASSERT(hasLayer());
- ASSERT(isComposited());
- layer()->backing()->animationFinished(name);
-}
-
-void RenderBoxModelObject::suspendAnimations(double time)
-{
- ASSERT(hasLayer());
- ASSERT(isComposited());
- layer()->backing()->suspendAnimations(time);
+ ASSERT(compositingState() == PaintsIntoOwnBacking);
+ layer()->compositedLayerMapping()->animationFinished(name);
}
bool RenderBoxModelObject::shouldPaintAtLowQuality(GraphicsContext* context, Image* image, const void* layer, const LayoutSize& size)
@@ -180,8 +174,6 @@ void RenderBoxModelObject::updateFromStyle()
{
RenderLayerModelObject::updateFromStyle();
- // Set the appropriate bits for a box model object. Since all bits are cleared in styleWillChange,
- // we only check for bits that could possibly be set to true.
RenderStyle* styleToUse = style();
setHasBoxDecorations(hasBackground() || styleToUse->hasBorder() || styleToUse->hasAppearance() || styleToUse->boxShadow());
setInline(styleToUse->isDisplayInlineType());
@@ -511,13 +503,17 @@ RoundedRect RenderBoxModelObject::backgroundRoundedRectAdjustedForBleedAvoidance
static void applyBoxShadowForBackground(GraphicsContext* context, const RenderObject* renderer)
{
- const ShadowData* boxShadow = renderer->style()->boxShadow();
- while (boxShadow->style() != Normal)
- boxShadow = boxShadow->next();
-
- FloatSize shadowOffset(boxShadow->x(), boxShadow->y());
- context->setShadow(shadowOffset, boxShadow->blur(), renderer->resolveColor(boxShadow->color()),
- DrawLooper::ShadowRespectsTransforms, DrawLooper::ShadowIgnoresAlpha);
+ const ShadowList* shadowList = renderer->style()->boxShadow();
+ ASSERT(shadowList);
+ for (size_t i = shadowList->shadows().size(); i--; ) {
+ const ShadowData& boxShadow = shadowList->shadows()[i];
+ if (boxShadow.style() != Normal)
+ continue;
+ FloatSize shadowOffset(boxShadow.x(), boxShadow.y());
+ context->setShadow(shadowOffset, boxShadow.blur(), renderer->resolveColor(boxShadow.color()),
+ DrawLooper::ShadowRespectsTransforms, DrawLooper::ShadowIgnoresAlpha);
+ return;
+ }
}
void RenderBoxModelObject::paintFillLayerExtended(const PaintInfo& paintInfo, const Color& color, const FillLayer* bgLayer, const LayoutRect& rect,
@@ -623,8 +619,8 @@ void RenderBoxModelObject::paintFillLayerExtended(const PaintInfo& paintInfo, co
// Adjust the paint rect to reflect a scrolled content box with borders at the ends.
IntSize offset = thisBox->scrolledContentOffset();
scrolledPaintRect.move(-offset);
- scrolledPaintRect.setWidth(bLeft + layer()->scrollWidth() + bRight);
- scrolledPaintRect.setHeight(borderTop() + layer()->scrollHeight() + borderBottom());
+ scrolledPaintRect.setWidth(bLeft + thisBox->scrollWidth() + bRight);
+ scrolledPaintRect.setHeight(borderTop() + thisBox->scrollHeight() + borderBottom());
}
GraphicsContextStateSaver backgroundClipStateSaver(*context, false);
@@ -706,29 +702,28 @@ void RenderBoxModelObject::paintFillLayerExtended(const PaintInfo& paintInfo, co
if (!boxShadowShouldBeAppliedToBackground)
backgroundRect.intersect(paintInfo.rect);
- // If we have an alpha and we are painting the root element, go ahead and blend with the base background color.
- Color baseColor;
- bool shouldClearBackground = false;
- if (isOpaqueRoot) {
- baseColor = view()->frameView()->baseBackgroundColor();
- if (!baseColor.alpha())
- shouldClearBackground = true;
- }
-
GraphicsContextStateSaver shadowStateSaver(*context, boxShadowShouldBeAppliedToBackground);
if (boxShadowShouldBeAppliedToBackground)
applyBoxShadowForBackground(context, this);
- if (baseColor.alpha()) {
- if (bgColor.alpha())
- baseColor = baseColor.blend(bgColor);
-
- context->fillRect(backgroundRect, baseColor, CompositeCopy);
+ if (isOpaqueRoot) {
+ // If we have an alpha and we are painting the root element, go ahead and blend with the base background color.
+ Color baseColor = view()->frameView()->baseBackgroundColor();
+ bool shouldClearDocumentBackground = document().settings() && document().settings()->shouldClearDocumentBackground();
+ CompositeOperator operation = shouldClearDocumentBackground ? CompositeCopy : context->compositeOperation();
+
+ if (baseColor.alpha()) {
+ if (bgColor.alpha())
+ baseColor = baseColor.blend(bgColor);
+ context->fillRect(backgroundRect, baseColor, operation);
+ } else if (bgColor.alpha()) {
+ context->fillRect(backgroundRect, bgColor, operation);
+ } else if (shouldClearDocumentBackground) {
+ context->clearRect(backgroundRect);
+ }
} else if (bgColor.alpha()) {
- CompositeOperator operation = shouldClearBackground ? CompositeCopy : context->compositeOperation();
- context->fillRect(backgroundRect, bgColor, operation);
- } else if (shouldClearBackground)
- context->clearRect(backgroundRect);
+ context->fillRect(backgroundRect, bgColor, context->compositeOperation());
+ }
}
}
@@ -742,9 +737,10 @@ void RenderBoxModelObject::paintFillLayerExtended(const PaintInfo& paintInfo, co
RenderObject* clientForBackgroundImage = backgroundObject ? backgroundObject : this;
RefPtr<Image> image = bgImage->image(clientForBackgroundImage, geometry.tileSize());
bool useLowQualityScaling = shouldPaintAtLowQuality(context, image.get(), bgLayer, geometry.tileSize());
- context->setDrawLuminanceMask(bgLayer->maskSourceType() == MaskLuminance);
+ if (bgLayer->maskSourceType() == MaskLuminance)
+ context->setColorFilter(ColorFilterLuminanceToAlpha);
context->drawTiledImage(image.get(), geometry.destRect(), geometry.relativePhase(), geometry.tileSize(),
- compositeOp, useLowQualityScaling, bgLayer->blendMode());
+ compositeOp, useLowQualityScaling, bgLayer->blendMode(), geometry.spaceSize());
}
}
@@ -983,10 +979,21 @@ bool RenderBoxModelObject::fixedBackgroundPaintsInLocalCoordinates() const
return false;
RenderLayer* rootLayer = view()->layer();
- if (!rootLayer || !rootLayer->isComposited())
+ if (!rootLayer || rootLayer->compositingState() == NotComposited)
return false;
- return rootLayer->backing()->backgroundLayerPaintsFixedRootBackground();
+ return rootLayer->compositedLayerMapping()->backgroundLayerPaintsFixedRootBackground();
+}
+
+static inline int getSpace(int areaSize, int tileSize)
+{
+ int numberOfTiles = areaSize / tileSize;
+ int space = -1;
+
+ if (numberOfTiles > 1)
+ space = lroundf((float)(areaSize - numberOfTiles * tileSize) / (numberOfTiles - 1));
+
+ return space;
}
void RenderBoxModelObject::calculateBackgroundImageGeometry(const FillLayer* fillLayer, const LayoutRect& paintRect,
@@ -1063,7 +1070,7 @@ void RenderBoxModelObject::calculateBackgroundImageGeometry(const FillLayer* fil
LayoutUnit computedXPosition = minimumValueForLength(fillLayer->xPosition(), availableWidth, renderView, true);
if (backgroundRepeatX == RoundFill && positioningAreaSize.width() > 0 && fillTileSize.width() > 0) {
- long nrTiles = lroundf((float)positioningAreaSize.width() / fillTileSize.width());
+ long nrTiles = max(1l, lroundf((float)positioningAreaSize.width() / fillTileSize.width()));
if (fillLayer->size().size.height().isAuto() && backgroundRepeatY != RoundFill) {
fillTileSize.setHeight(fillTileSize.height() * positioningAreaSize.width() / (nrTiles * fillTileSize.width()));
@@ -1072,11 +1079,12 @@ void RenderBoxModelObject::calculateBackgroundImageGeometry(const FillLayer* fil
fillTileSize.setWidth(positioningAreaSize.width() / nrTiles);
geometry.setTileSize(fillTileSize);
geometry.setPhaseX(geometry.tileSize().width() ? geometry.tileSize().width() - roundToInt(computedXPosition + left) % geometry.tileSize().width() : 0);
+ geometry.setSpaceSize(IntSize());
}
LayoutUnit computedYPosition = minimumValueForLength(fillLayer->yPosition(), availableHeight, renderView, true);
if (backgroundRepeatY == RoundFill && positioningAreaSize.height() > 0 && fillTileSize.height() > 0) {
- long nrTiles = lroundf((float)positioningAreaSize.height() / fillTileSize.height());
+ long nrTiles = max(1l, lroundf((float)positioningAreaSize.height() / fillTileSize.height()));
if (fillLayer->size().size.width().isAuto() && backgroundRepeatX != RoundFill) {
fillTileSize.setWidth(fillTileSize.width() * positioningAreaSize.height() / (nrTiles * fillTileSize.height()));
@@ -1085,19 +1093,49 @@ void RenderBoxModelObject::calculateBackgroundImageGeometry(const FillLayer* fil
fillTileSize.setHeight(positioningAreaSize.height() / nrTiles);
geometry.setTileSize(fillTileSize);
geometry.setPhaseY(geometry.tileSize().height() ? geometry.tileSize().height() - roundToInt(computedYPosition + top) % geometry.tileSize().height() : 0);
+ geometry.setSpaceSize(IntSize());
}
if (backgroundRepeatX == RepeatFill) {
geometry.setPhaseX(geometry.tileSize().width() ? geometry.tileSize().width() - roundToInt(computedXPosition + left) % geometry.tileSize().width() : 0);
- } else if (backgroundRepeatX == NoRepeatFill) {
+ geometry.setSpaceSize(IntSize());
+ } else if (backgroundRepeatX == SpaceFill && fillTileSize.width() > 0) {
+ int space = getSpace(positioningAreaSize.width(), geometry.tileSize().width());
+ int actualWidth = geometry.tileSize().width() + space;
+
+ if (space >= 0) {
+ computedXPosition = minimumValueForLength(Length(), availableWidth, renderView, true);
+ geometry.setSpaceSize(IntSize(space, 0));
+ geometry.setPhaseX(actualWidth ? actualWidth - roundToInt(computedXPosition + left) % actualWidth : 0);
+ } else {
+ backgroundRepeatX = NoRepeatFill;
+ }
+ }
+ if (backgroundRepeatX == NoRepeatFill) {
int xOffset = fillLayer->backgroundXOrigin() == RightEdge ? availableWidth - computedXPosition : computedXPosition;
geometry.setNoRepeatX(left + xOffset);
+ geometry.setSpaceSize(IntSize(0, geometry.spaceSize().height()));
}
+
if (backgroundRepeatY == RepeatFill) {
geometry.setPhaseY(geometry.tileSize().height() ? geometry.tileSize().height() - roundToInt(computedYPosition + top) % geometry.tileSize().height() : 0);
- } else if (backgroundRepeatY == NoRepeatFill) {
+ geometry.setSpaceSize(IntSize(geometry.spaceSize().width(), 0));
+ } else if (backgroundRepeatY == SpaceFill && fillTileSize.height() > 0) {
+ int space = getSpace(positioningAreaSize.height(), geometry.tileSize().height());
+ int actualHeight = geometry.tileSize().height() + space;
+
+ if (space >= 0) {
+ computedYPosition = minimumValueForLength(Length(), availableHeight, renderView, true);
+ geometry.setSpaceSize(IntSize(geometry.spaceSize().width(), space));
+ geometry.setPhaseY(actualHeight ? actualHeight - roundToInt(computedYPosition + top) % actualHeight : 0);
+ } else {
+ backgroundRepeatY = NoRepeatFill;
+ }
+ }
+ if (backgroundRepeatY == NoRepeatFill) {
int yOffset = fillLayer->backgroundYOrigin() == BottomEdge ? availableHeight - computedYPosition : computedYPosition;
geometry.setNoRepeatY(top + yOffset);
+ geometry.setSpaceSize(IntSize(geometry.spaceSize().width(), 0));
}
if (fixedAttachment)
@@ -1107,13 +1145,13 @@ void RenderBoxModelObject::calculateBackgroundImageGeometry(const FillLayer* fil
geometry.setDestOrigin(geometry.destRect().location());
}
-static LayoutUnit computeBorderImageSide(Length borderSlice, LayoutUnit borderSide, LayoutUnit imageSide, LayoutUnit boxExtent, RenderView* renderView)
+static LayoutUnit computeBorderImageSide(const BorderImageLength& borderSlice, LayoutUnit borderSide, LayoutUnit imageSide, LayoutUnit boxExtent, RenderView* renderView)
{
- if (borderSlice.isRelative())
- return borderSlice.value() * borderSide;
- if (borderSlice.isAuto())
+ if (borderSlice.isNumber())
+ return borderSlice.number() * borderSide;
+ if (borderSlice.length().isAuto())
return imageSide;
- return valueForLength(borderSlice, boxExtent, renderView);
+ return valueForLength(borderSlice.length(), boxExtent, renderView);
}
bool RenderBoxModelObject::paintNinePieceImage(GraphicsContext* graphicsContext, const LayoutRect& rect, const RenderStyle* style,
@@ -1842,7 +1880,7 @@ void RenderBoxModelObject::paintBorder(const PaintInfo& info, const LayoutRect&
graphicsContext->clipRoundedRect(outerBorder);
// isRenderable() check avoids issue described in https://bugs.webkit.org/show_bug.cgi?id=38787
// The inside will be clipped out later (in clipBorderSideForComplexInnerPath)
- if (innerBorder.isRenderable())
+ if (innerBorder.isRenderable() && !innerBorder.isEmpty())
graphicsContext->clipOutRoundedRect(innerBorder);
}
@@ -2306,7 +2344,9 @@ void RenderBoxModelObject::clipBorderSideForComplexInnerPath(GraphicsContext* gr
BoxSide side, const class BorderEdge edges[])
{
graphicsContext->clip(calculateSideRectIncludingInner(outerBorder, edges, side));
- graphicsContext->clipOutRoundedRect(calculateAdjustedInnerBorder(innerBorder, side));
+ RoundedRect adjustedInnerRect = calculateAdjustedInnerBorder(innerBorder, side);
+ if (!adjustedInnerRect.isEmpty())
+ graphicsContext->clipOutRoundedRect(adjustedInnerRect);
}
void RenderBoxModelObject::getBorderEdgeInfo(BorderEdge edges[], const RenderStyle* style, bool includeLogicalLeftEdge, bool includeLogicalRightEdge) const
@@ -2383,16 +2423,22 @@ bool RenderBoxModelObject::boxShadowShouldBeAppliedToBackground(BackgroundBleedA
if (style()->hasAppearance())
return false;
+ const ShadowList* shadowList = style()->boxShadow();
+ if (!shadowList)
+ return false;
+
bool hasOneNormalBoxShadow = false;
- for (const ShadowData* currentShadow = style()->boxShadow(); currentShadow; currentShadow = currentShadow->next()) {
- if (currentShadow->style() != Normal)
+ size_t shadowCount = shadowList->shadows().size();
+ for (size_t i = 0; i < shadowCount; ++i) {
+ const ShadowData& currentShadow = shadowList->shadows()[i];
+ if (currentShadow.style() != Normal)
continue;
if (hasOneNormalBoxShadow)
return false;
hasOneNormalBoxShadow = true;
- if (currentShadow->spread())
+ if (currentShadow.spread())
return false;
}
@@ -2422,20 +2468,6 @@ bool RenderBoxModelObject::boxShadowShouldBeAppliedToBackground(BackgroundBleedA
return true;
}
-static inline IntRect areaCastingShadowInHole(const IntRect& holeRect, int shadowBlur, int shadowSpread, const IntSize& shadowOffset)
-{
- IntRect bounds(holeRect);
-
- bounds.inflate(shadowBlur);
-
- if (shadowSpread < 0)
- bounds.inflate(-shadowSpread);
-
- IntRect offsetBounds = bounds;
- offsetBounds.move(-shadowOffset);
- return unionRect(bounds, offsetBounds);
-}
-
void RenderBoxModelObject::paintBoxShadow(const PaintInfo& info, const LayoutRect& paintRect, const RenderStyle* s, ShadowStyle shadowStyle, bool includeLogicalLeftEdge, bool includeLogicalRightEdge)
{
// FIXME: Deal with border-image. Would be great to use border-image as a mask.
@@ -2451,20 +2483,23 @@ void RenderBoxModelObject::paintBoxShadow(const PaintInfo& info, const LayoutRec
bool hasOpaqueBackground = s->visitedDependentColor(CSSPropertyBackgroundColor).isValid() && s->visitedDependentColor(CSSPropertyBackgroundColor).alpha() == 255;
GraphicsContextStateSaver stateSaver(*context, false);
- for (const ShadowData* shadow = s->boxShadow(); shadow; shadow = shadow->next()) {
- if (shadow->style() != shadowStyle)
+
+ const ShadowList* shadowList = s->boxShadow();
+ for (size_t i = shadowList->shadows().size(); i--; ) {
+ const ShadowData& shadow = shadowList->shadows()[i];
+ if (shadow.style() != shadowStyle)
continue;
- IntSize shadowOffset(shadow->x(), shadow->y());
- int shadowBlur = shadow->blur();
- int shadowSpread = shadow->spread();
+ IntSize shadowOffset(shadow.x(), shadow.y());
+ int shadowBlur = shadow.blur();
+ int shadowSpread = shadow.spread();
if (shadowOffset.isZero() && !shadowBlur && !shadowSpread)
continue;
- const Color& shadowColor = resolveColor(shadow->color());
+ const Color& shadowColor = resolveColor(shadow.color());
- if (shadow->style() == Normal) {
+ if (shadow.style() == Normal) {
RoundedRect fillRect = border;
fillRect.inflate(shadowSpread);
if (fillRect.isEmpty())
@@ -2586,14 +2621,14 @@ void RenderBoxModelObject::computeLayerHitTestRects(LayerHitTestRects& rects) co
continuation()->computeLayerHitTestRects(rects);
}
-RenderObject* RenderBoxModelObject::firstLetterRemainingText() const
+RenderTextFragment* RenderBoxModelObject::firstLetterRemainingText() const
{
if (!firstLetterRemainingTextMap)
return 0;
return firstLetterRemainingTextMap->get(this);
}
-void RenderBoxModelObject::setFirstLetterRemainingText(RenderObject* remainingText)
+void RenderBoxModelObject::setFirstLetterRemainingText(RenderTextFragment* remainingText)
{
if (remainingText) {
if (!firstLetterRemainingTextMap)
@@ -2612,7 +2647,7 @@ LayoutRect RenderBoxModelObject::localCaretRectForEmptyElement(LayoutUnit width,
// constructed and this kludge is not called any more. So only the caret size
// of an empty :first-line'd block is wrong. I think we can live with that.
RenderStyle* currentStyle = firstLineStyle();
- LayoutUnit height = lineHeight(true, currentStyle->isHorizontalWritingMode() ? HorizontalLine : VerticalLine);
+ LayoutUnit height = lineHeight(true, currentStyle->isHorizontalWritingMode() ? HorizontalLine : VerticalLine, PositionOfInteriorLineBoxes);
enum CaretAlignment { alignLeft, alignRight, alignCenter };
@@ -2779,7 +2814,8 @@ void RenderBoxModelObject::moveChildrenTo(RenderBoxModelObject* toBoxModelObject
if (fullRemoveInsert && isRenderBlock()) {
RenderBlock* block = toRenderBlock(this);
block->removePositionedObjects(0);
- block->removeFloatingObjects();
+ if (block->isRenderBlockFlow())
+ toRenderBlockFlow(block)->removeFloatingObjects();
}
ASSERT(!beforeChild || toBoxModelObject == beforeChild->parent());
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderBoxModelObject.h b/chromium/third_party/WebKit/Source/core/rendering/RenderBoxModelObject.h
index bcbaf90666a..31b318612b8 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderBoxModelObject.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderBoxModelObject.h
@@ -24,9 +24,9 @@
#ifndef RenderBoxModelObject_h
#define RenderBoxModelObject_h
-#include "core/platform/graphics/LayoutRect.h"
#include "core/rendering/RenderLayerModelObject.h"
#include "core/rendering/style/ShadowData.h"
+#include "platform/geometry/LayoutRect.h"
namespace WebCore {
@@ -52,6 +52,7 @@ enum ContentChangeType {
};
class KeyframeList;
+class RenderTextFragment;
class StickyPositionViewportConstraints;
// This class is the base for all objects that adhere to the CSS box model as described
@@ -133,9 +134,13 @@ public:
LayoutUnit borderLogicalLeft() const { return style()->isHorizontalWritingMode() ? borderLeft() : borderTop(); }
LayoutUnit borderLogicalRight() const { return style()->isHorizontalWritingMode() ? borderRight() : borderBottom(); }
+ LayoutUnit borderLogicalWidth() const { return borderStart() + borderEnd(); }
+ LayoutUnit borderLogicalHeight() const { return borderBefore() + borderAfter(); }
LayoutUnit paddingLogicalLeft() const { return style()->isHorizontalWritingMode() ? paddingLeft() : paddingTop(); }
LayoutUnit paddingLogicalRight() const { return style()->isHorizontalWritingMode() ? paddingRight() : paddingBottom(); }
+ LayoutUnit paddingLogicalWidth() const { return paddingStart() + paddingEnd(); }
+ LayoutUnit paddingLogicalHeight() const { return paddingBefore() + paddingAfter(); }
virtual LayoutUnit marginTop() const = 0;
virtual LayoutUnit marginBottom() const = 0;
@@ -188,8 +193,6 @@ public:
void animationPaused(double timeOffset, const String& name);
void animationFinished(const String& name);
- void suspendAnimations(double time = 0);
-
virtual void computeLayerHitTestRects(LayerHitTestRects&) const OVERRIDE;
protected:
@@ -224,6 +227,14 @@ protected:
m_tileSize = tileSize;
}
+ // Space-size represents extra width and height that may be added to
+ // the image if used as a pattern with repeat: space
+ IntSize spaceSize() const { return m_repeatSpacing; }
+ void setSpaceSize(const IntSize& repeatSpacing)
+ {
+ m_repeatSpacing = repeatSpacing;
+ }
+
void setPhaseX(int x) { m_phase.setX(x); }
void setPhaseY(int y) { m_phase.setY(y); }
@@ -238,6 +249,7 @@ protected:
IntPoint m_destOrigin;
IntPoint m_phase;
IntSize m_tileSize;
+ IntSize m_repeatSpacing;
};
LayoutPoint adjustedPositionRelativeToOffsetParent(const LayoutPoint&) const;
@@ -264,8 +276,8 @@ protected:
public:
// For RenderBlocks and RenderInlines with m_style->styleType() == FIRST_LETTER, this tracks their remaining text fragments
- RenderObject* firstLetterRemainingText() const;
- void setFirstLetterRemainingText(RenderObject*);
+ RenderTextFragment* firstLetterRemainingText() const;
+ void setFirstLetterRemainingText(RenderTextFragment*);
// These functions are only used internally to manipulate the render tree structure via remove/insert/appendChildNode.
// Since they are typically called only to move objects around within anonymous blocks (which only have layers in
@@ -323,20 +335,7 @@ private:
Color, EBorderStyle, BackgroundBleedAvoidance, bool includeLogicalLeftEdge, bool includeLogicalRightEdge);
};
-inline RenderBoxModelObject* toRenderBoxModelObject(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isBoxModelObject());
- return static_cast<RenderBoxModelObject*>(object);
-}
-
-inline const RenderBoxModelObject* toRenderBoxModelObject(const RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isBoxModelObject());
- return static_cast<const RenderBoxModelObject*>(object);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toRenderBoxModelObject(const RenderBoxModelObject*);
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderBoxModelObject, isBoxModelObject());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderBoxRegionInfo.h b/chromium/third_party/WebKit/Source/core/rendering/RenderBoxRegionInfo.h
index 2abfa09d037..3bde47e9477 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderBoxRegionInfo.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderBoxRegionInfo.h
@@ -27,7 +27,7 @@
#ifndef RenderBoxRegionInfo_h
#define RenderBoxRegionInfo_h
-#include "core/platform/LayoutUnit.h"
+#include "platform/LayoutUnit.h"
#include "wtf/FastAllocBase.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderButton.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderButton.cpp
index 9b84765c218..ce1bec473ce 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderButton.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderButton.cpp
@@ -21,7 +21,6 @@
#include "config.h"
#include "core/rendering/RenderButton.h"
-#include "HTMLNames.h"
#include "core/dom/Document.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderButton.h b/chromium/third_party/WebKit/Source/core/rendering/RenderButton.h
index 395743df987..33df32be802 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderButton.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderButton.h
@@ -63,25 +63,10 @@ private:
virtual bool hasLineIfEmpty() const { return node() && node()->hasTagName(HTMLNames::inputTag); }
- virtual bool requiresForcedStyleRecalcPropagation() const { return true; }
-
RenderBlock* m_inner;
};
-inline RenderButton* toRenderButton(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isRenderButton());
- return static_cast<RenderButton*>(object);
-}
-
-inline const RenderButton* toRenderButton(const RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isRenderButton());
- return static_cast<const RenderButton*>(object);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toRenderButton(const RenderButton*);
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderButton, isRenderButton());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderCombineText.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderCombineText.cpp
index b8f1cf115b2..75ae66dec91 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderCombineText.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderCombineText.cpp
@@ -21,7 +21,7 @@
#include "config.h"
#include "core/rendering/RenderCombineText.h"
-#include "core/rendering/RenderBlock.h"
+#include "core/rendering/RenderBlockFlow.h"
namespace WebCore {
@@ -96,7 +96,7 @@ void RenderCombineText::combineText()
if (style()->isHorizontalWritingMode())
return;
- TextRun run = RenderBlock::constructTextRun(this, originalFont(), this, style());
+ TextRun run = RenderBlockFlow::constructTextRun(this, originalFont(), this, style());
FontDescription description = originalFont().fontDescription();
float emWidth = description.computedSize() * textCombineMargin;
bool shouldUpdateFont = false;
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderCombineText.h b/chromium/third_party/WebKit/Source/core/rendering/RenderCombineText.h
index cddaab1d56f..ce196d4c360 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderCombineText.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderCombineText.h
@@ -21,8 +21,8 @@
#ifndef RenderCombineText_h
#define RenderCombineText_h
-#include "core/platform/graphics/Font.h"
#include "core/rendering/RenderText.h"
+#include "platform/fonts/Font.h"
namespace WebCore {
@@ -49,20 +49,7 @@ private:
bool m_needsFontUpdate : 1;
};
-inline RenderCombineText* toRenderCombineText(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isCombineText());
- return static_cast<RenderCombineText*>(object);
-}
-
-inline const RenderCombineText* toRenderCombineText(const RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isCombineText());
- return static_cast<const RenderCombineText*>(object);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toRenderCombineText(const RenderCombineText*);
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderCombineText, isCombineText());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderCounter.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderCounter.cpp
index 224ca857549..5aac629a947 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderCounter.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderCounter.cpp
@@ -45,7 +45,7 @@ using namespace HTMLNames;
typedef HashMap<AtomicString, RefPtr<CounterNode> > CounterMap;
typedef HashMap<const RenderObject*, OwnPtr<CounterMap> > CounterMaps;
-static CounterNode* makeCounterNode(RenderObject*, const AtomicString& identifier, bool alwaysCreateCounter);
+static CounterNode* makeCounterNode(RenderObject&, const AtomicString& identifier, bool alwaysCreateCounter);
static CounterMaps& counterMaps()
{
@@ -55,70 +55,71 @@ static CounterMaps& counterMaps()
// This function processes the renderer tree in the order of the DOM tree
// including pseudo elements as defined in CSS 2.1.
-static RenderObject* previousInPreOrder(const RenderObject* object)
+static RenderObject* previousInPreOrder(const RenderObject& object)
{
- Element* self = toElement(object->node());
- Element* previous = ElementTraversal::previousIncludingPseudo(self);
+ Element* self = toElement(object.node());
+ ASSERT(self);
+ Element* previous = ElementTraversal::previousIncludingPseudo(*self);
while (previous && !previous->renderer())
- previous = ElementTraversal::previousIncludingPseudo(previous);
+ previous = ElementTraversal::previousIncludingPseudo(*previous);
return previous ? previous->renderer() : 0;
}
// This function processes the renderer tree in the order of the DOM tree
// including pseudo elements as defined in CSS 2.1.
-static RenderObject* previousSiblingOrParent(const RenderObject* object)
+static RenderObject* previousSiblingOrParent(const RenderObject& object)
{
- Element* self = toElement(object->node());
- Element* previous = ElementTraversal::pseudoAwarePreviousSibling(self);
+ Element* self = toElement(object.node());
+ ASSERT(self);
+ Element* previous = ElementTraversal::pseudoAwarePreviousSibling(*self);
while (previous && !previous->renderer())
- previous = ElementTraversal::pseudoAwarePreviousSibling(previous);
+ previous = ElementTraversal::pseudoAwarePreviousSibling(*previous);
if (previous)
return previous->renderer();
previous = self->parentElement();
return previous ? previous->renderer() : 0;
}
-static inline Element* parentElement(RenderObject* object)
+static inline Element* parentElement(RenderObject& object)
{
- return toElement(object->node())->parentElement();
+ return toElement(object.node())->parentElement();
}
-static inline bool areRenderersElementsSiblings(RenderObject* first, RenderObject* second)
+static inline bool areRenderersElementsSiblings(RenderObject& first, RenderObject& second)
{
return parentElement(first) == parentElement(second);
}
// This function processes the renderer tree in the order of the DOM tree
// including pseudo elements as defined in CSS 2.1.
-static RenderObject* nextInPreOrder(const RenderObject* object, const Element* stayWithin, bool skipDescendants = false)
+static RenderObject* nextInPreOrder(const RenderObject& object, const Element* stayWithin, bool skipDescendants = false)
{
- Element* self = toElement(object->node());
- Element* next = skipDescendants ? ElementTraversal::nextIncludingPseudoSkippingChildren(self, stayWithin) : ElementTraversal::nextIncludingPseudo(self, stayWithin);
+ Element* self = toElement(object.node());
+ ASSERT(self);
+ Element* next = skipDescendants ? ElementTraversal::nextIncludingPseudoSkippingChildren(*self, stayWithin) : ElementTraversal::nextIncludingPseudo(*self, stayWithin);
while (next && !next->renderer())
- next = skipDescendants ? ElementTraversal::nextIncludingPseudoSkippingChildren(next, stayWithin) : ElementTraversal::nextIncludingPseudo(next, stayWithin);
+ next = skipDescendants ? ElementTraversal::nextIncludingPseudoSkippingChildren(*next, stayWithin) : ElementTraversal::nextIncludingPseudo(*next, stayWithin);
return next ? next->renderer() : 0;
}
-static bool planCounter(RenderObject* object, const AtomicString& identifier, bool& isReset, int& value)
+static bool planCounter(RenderObject& object, const AtomicString& identifier, bool& isReset, int& value)
{
- ASSERT(object);
-
// Real text nodes don't have their own style so they can't have counters.
// We can't even look at their styles or we'll see extra resets and increments!
- if (object->isText() && !object->isBR())
+ if (object.isText() && !object.isBR())
return false;
- Node* generatingNode = object->generatingNode();
+ Node* generatingNode = object.generatingNode();
// We must have a generating node or else we cannot have a counter.
if (!generatingNode)
return false;
- RenderStyle* style = object->style();
+ RenderStyle* style = object.style();
ASSERT(style);
switch (style->styleType()) {
case NOPSEUDO:
// Sometimes nodes have more then one renderer. Only the first one gets the counter
// LayoutTests/http/tests/css/counter-crash.html
- if (generatingNode->renderer() != object)
+ if (generatingNode->renderer() != &object)
return false;
break;
case BEFORE:
@@ -136,9 +137,9 @@ static bool planCounter(RenderObject* object, const AtomicString& identifier, bo
}
if (identifier == "list-item") {
- if (object->isListItem()) {
- if (toRenderListItem(object)->hasExplicitValue()) {
- value = toRenderListItem(object)->explicitValue();
+ if (object.isListItem()) {
+ if (toRenderListItem(object).hasExplicitValue()) {
+ value = toRenderListItem(object).explicitValue();
isReset = true;
return true;
}
@@ -146,7 +147,7 @@ static bool planCounter(RenderObject* object, const AtomicString& identifier, bo
isReset = false;
return true;
}
- if (Node* e = object->node()) {
+ if (Node* e = object.node()) {
if (e->hasTagName(olTag)) {
value = toHTMLOListElement(e)->start();
isReset = true;
@@ -179,7 +180,7 @@ static bool planCounter(RenderObject* object, const AtomicString& identifier, bo
// reset node.
// - Non-reset CounterNodes cannot have descendants.
-static bool findPlaceForCounter(RenderObject* counterOwner, const AtomicString& identifier, bool isReset, RefPtr<CounterNode>& parent, RefPtr<CounterNode>& previousSibling)
+static bool findPlaceForCounter(RenderObject& counterOwner, const AtomicString& identifier, bool isReset, RefPtr<CounterNode>& parent, RefPtr<CounterNode>& previousSibling)
{
// We cannot stop searching for counters with the same identifier before we also
// check this renderer, because it may affect the positioning in the tree of our counter.
@@ -192,7 +193,7 @@ static bool findPlaceForCounter(RenderObject* counterOwner, const AtomicString&
RefPtr<CounterNode> previousSiblingProtector = 0;
while (currentRenderer) {
- CounterNode* currentCounter = makeCounterNode(currentRenderer, identifier, false);
+ CounterNode* currentCounter = makeCounterNode(*currentRenderer, identifier, false);
if (searchEndRenderer == currentRenderer) {
// We may be at the end of our search.
if (currentCounter) {
@@ -200,7 +201,7 @@ static bool findPlaceForCounter(RenderObject* counterOwner, const AtomicString&
if (previousSiblingProtector) { // But we already found another counter that we come after.
if (currentCounter->actsAsReset()) {
// We found a reset counter that is on a renderer that is a sibling of ours or a parent.
- if (isReset && areRenderersElementsSiblings(currentRenderer, counterOwner)) {
+ if (isReset && areRenderersElementsSiblings(*currentRenderer, counterOwner)) {
// We are also a reset counter and the previous reset was on a sibling renderer
// hence we are the next sibling of that counter if that reset is not a root or
// we are a root node if that reset is a root.
@@ -221,7 +222,7 @@ static bool findPlaceForCounter(RenderObject* counterOwner, const AtomicString&
return true;
}
// CurrentCounter, the counter at the EndSearchRenderer, is not reset.
- if (!isReset || !areRenderersElementsSiblings(currentRenderer, counterOwner)) {
+ if (!isReset || !areRenderersElementsSiblings(*currentRenderer, counterOwner)) {
// If the node we are placing is not reset or we have found a counter that is attached
// to an ancestor of the placed counter's owner renderer we know we are a sibling of that node.
if (currentCounter->parent() != previousSiblingProtector->parent())
@@ -237,7 +238,7 @@ static bool findPlaceForCounter(RenderObject* counterOwner, const AtomicString&
// previousSibling, and when we are a sibling of the end counter we must set previousSibling
// to currentCounter.
if (currentCounter->actsAsReset()) {
- if (isReset && areRenderersElementsSiblings(currentRenderer, counterOwner)) {
+ if (isReset && areRenderersElementsSiblings(*currentRenderer, counterOwner)) {
parent = currentCounter->parent();
previousSibling = currentCounter;
return parent;
@@ -246,7 +247,7 @@ static bool findPlaceForCounter(RenderObject* counterOwner, const AtomicString&
previousSibling = previousSiblingProtector.get();
return true;
}
- if (!isReset || !areRenderersElementsSiblings(currentRenderer, counterOwner)) {
+ if (!isReset || !areRenderersElementsSiblings(*currentRenderer, counterOwner)) {
parent = currentCounter->parent();
previousSibling = currentCounter;
return true;
@@ -258,7 +259,7 @@ static bool findPlaceForCounter(RenderObject* counterOwner, const AtomicString&
// good counter, or we are a reset node and the counter on the previous sibling
// of our owner renderer was not a reset counter.
// Set a new goal for the end of the search.
- searchEndRenderer = previousSiblingOrParent(currentRenderer);
+ searchEndRenderer = previousSiblingOrParent(*currentRenderer);
} else {
// We are searching descendants of a previous sibling of the renderer that the
// counter being placed is attached to.
@@ -271,12 +272,12 @@ static bool findPlaceForCounter(RenderObject* counterOwner, const AtomicString&
previousSiblingProtector = currentCounter;
// We are no longer interested in previous siblings of the currentRenderer or their children
// as counters they may have attached cannot be the previous sibling of the counter we are placing.
- currentRenderer = parentElement(currentRenderer)->renderer();
+ currentRenderer = parentElement(*currentRenderer)->renderer();
continue;
}
} else
previousSiblingProtector = currentCounter;
- currentRenderer = previousSiblingOrParent(currentRenderer);
+ currentRenderer = previousSiblingOrParent(*currentRenderer);
continue;
}
}
@@ -285,19 +286,17 @@ static bool findPlaceForCounter(RenderObject* counterOwner, const AtomicString&
// performance improvement would create more code duplication than is worthwhile in my oppinion and may further
// impede the readability of this already complex algorithm.
if (previousSiblingProtector)
- currentRenderer = previousSiblingOrParent(currentRenderer);
+ currentRenderer = previousSiblingOrParent(*currentRenderer);
else
- currentRenderer = previousInPreOrder(currentRenderer);
+ currentRenderer = previousInPreOrder(*currentRenderer);
}
return false;
}
-static CounterNode* makeCounterNode(RenderObject* object, const AtomicString& identifier, bool alwaysCreateCounter)
+static CounterNode* makeCounterNode(RenderObject& object, const AtomicString& identifier, bool alwaysCreateCounter)
{
- ASSERT(object);
-
- if (object->hasCounterNodeMap()) {
- if (CounterMap* nodeMap = counterMaps().get(object)) {
+ if (object.hasCounterNodeMap()) {
+ if (CounterMap* nodeMap = counterMaps().get(&object)) {
if (CounterNode* node = nodeMap->get(identifier))
return node;
}
@@ -314,12 +313,12 @@ static CounterNode* makeCounterNode(RenderObject* object, const AtomicString& id
if (findPlaceForCounter(object, identifier, isReset, newParent, newPreviousSibling))
newParent->insertAfter(newNode.get(), newPreviousSibling.get(), identifier);
CounterMap* nodeMap;
- if (object->hasCounterNodeMap())
- nodeMap = counterMaps().get(object);
+ if (object.hasCounterNodeMap())
+ nodeMap = counterMaps().get(&object);
else {
nodeMap = new CounterMap;
- counterMaps().set(object, adoptPtr(nodeMap));
- object->setHasCounterNodeMap(true);
+ counterMaps().set(&object, adoptPtr(nodeMap));
+ object.setHasCounterNodeMap(true);
}
nodeMap->set(identifier, newNode);
if (newNode->parent())
@@ -329,7 +328,7 @@ static CounterNode* makeCounterNode(RenderObject* object, const AtomicString& id
CounterMaps& maps = counterMaps();
Element* stayWithin = parentElement(object);
bool skipDescendants;
- for (RenderObject* currentRenderer = nextInPreOrder(object, stayWithin); currentRenderer; currentRenderer = nextInPreOrder(currentRenderer, stayWithin, skipDescendants)) {
+ for (RenderObject* currentRenderer = nextInPreOrder(object, stayWithin); currentRenderer; currentRenderer = nextInPreOrder(*currentRenderer, stayWithin, skipDescendants)) {
skipDescendants = false;
if (!currentRenderer->hasCounterNodeMap())
continue;
@@ -339,7 +338,7 @@ static CounterNode* makeCounterNode(RenderObject* object, const AtomicString& id
skipDescendants = true;
if (currentCounter->parent())
continue;
- if (stayWithin == parentElement(currentRenderer) && currentCounter->hasResetType())
+ if (stayWithin == parentElement(*currentRenderer) && currentCounter->hasResetType())
break;
newNode->insertAfter(currentCounter, newNode->lastChild(), identifier);
}
@@ -394,7 +393,7 @@ PassRefPtr<StringImpl> RenderCounter::originalText() const
break;
beforeAfterContainer = beforeAfterContainer->parent();
}
- makeCounterNode(beforeAfterContainer, m_counter.identifier(), true)->addRenderer(const_cast<RenderCounter*>(this));
+ makeCounterNode(*beforeAfterContainer, m_counter.identifier(), true)->addRenderer(const_cast<RenderCounter*>(this));
ASSERT(m_counterNode);
}
CounterNode* child = m_counterNode;
@@ -435,17 +434,17 @@ static void destroyCounterNodeWithoutMapRemoval(const AtomicString& identifier,
for (RefPtr<CounterNode> child = node->lastDescendant(); child && child != node; child = previous) {
previous = child->previousInPreOrder();
child->parent()->removeChild(child.get());
- ASSERT(counterMaps().get(child->owner())->get(identifier) == child);
- counterMaps().get(child->owner())->remove(identifier);
+ ASSERT(counterMaps().get(&child->owner())->get(identifier) == child);
+ counterMaps().get(&child->owner())->remove(identifier);
}
if (CounterNode* parent = node->parent())
parent->removeChild(node);
}
-void RenderCounter::destroyCounterNodes(RenderObject* owner)
+void RenderCounter::destroyCounterNodes(RenderObject& owner)
{
CounterMaps& maps = counterMaps();
- CounterMaps::iterator mapsIterator = maps.find(owner);
+ CounterMaps::iterator mapsIterator = maps.find(&owner);
if (mapsIterator == maps.end())
return;
CounterMap* map = mapsIterator->value.get();
@@ -454,12 +453,12 @@ void RenderCounter::destroyCounterNodes(RenderObject* owner)
destroyCounterNodeWithoutMapRemoval(it->key, it->value.get());
}
maps.remove(mapsIterator);
- owner->setHasCounterNodeMap(false);
+ owner.setHasCounterNodeMap(false);
}
-void RenderCounter::destroyCounterNode(RenderObject* owner, const AtomicString& identifier)
+void RenderCounter::destroyCounterNode(RenderObject& owner, const AtomicString& identifier)
{
- CounterMap* map = counterMaps().get(owner);
+ CounterMap* map = counterMaps().get(&owner);
if (!map)
return;
CounterMap::iterator mapIterator = map->find(identifier);
@@ -489,26 +488,26 @@ void RenderCounter::rendererRemovedFromTree(RenderObject* renderer)
if (!currentRenderer)
currentRenderer = renderer;
while (true) {
- destroyCounterNodes(currentRenderer);
+ destroyCounterNodes(*currentRenderer);
if (currentRenderer == renderer)
break;
currentRenderer = currentRenderer->previousInPreOrder();
}
}
-static void updateCounters(RenderObject* renderer)
+static void updateCounters(RenderObject& renderer)
{
- ASSERT(renderer->style());
- const CounterDirectiveMap* directiveMap = renderer->style()->counterDirectives();
+ ASSERT(renderer.style());
+ const CounterDirectiveMap* directiveMap = renderer.style()->counterDirectives();
if (!directiveMap)
return;
CounterDirectiveMap::const_iterator end = directiveMap->end();
- if (!renderer->hasCounterNodeMap()) {
+ if (!renderer.hasCounterNodeMap()) {
for (CounterDirectiveMap::const_iterator it = directiveMap->begin(); it != end; ++it)
makeCounterNode(renderer, it->key, false);
return;
}
- CounterMap* counterMap = counterMaps().get(renderer);
+ CounterMap* counterMap = counterMaps().get(&renderer);
ASSERT(counterMap);
for (CounterDirectiveMap::const_iterator it = directiveMap->begin(); it != end; ++it) {
RefPtr<CounterNode> node = counterMap->get(it->key);
@@ -542,16 +541,16 @@ void RenderCounter::rendererSubtreeAttached(RenderObject* renderer)
node = node->parentNode();
else
node = renderer->generatingNode();
- if (node && !node->attached())
+ if (node && node->needsAttach())
return; // No need to update if the parent is not attached yet
for (RenderObject* descendant = renderer; descendant; descendant = descendant->nextInPreOrder(renderer))
- updateCounters(descendant);
+ updateCounters(*descendant);
}
-void RenderCounter::rendererStyleChanged(RenderObject* renderer, const RenderStyle* oldStyle, const RenderStyle* newStyle)
+void RenderCounter::rendererStyleChanged(RenderObject& renderer, const RenderStyle* oldStyle, const RenderStyle* newStyle)
{
- Node* node = renderer->generatingNode();
- if (!node || !node->attached())
+ Node* node = renderer.generatingNode();
+ if (!node || node->needsAttach())
return; // cannot have generated content or if it can have, it will be handled during attaching
const CounterDirectiveMap* newCounterDirectives;
const CounterDirectiveMap* oldCounterDirectives;
@@ -577,7 +576,7 @@ void RenderCounter::rendererStyleChanged(RenderObject* renderer, const RenderSty
RenderCounter::destroyCounterNode(renderer, it->key);
}
} else {
- if (renderer->hasCounterNodeMap())
+ if (renderer.hasCounterNodeMap())
RenderCounter::destroyCounterNodes(renderer);
}
} else if (newStyle && (newCounterDirectives = newStyle->counterDirectives())) {
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderCounter.h b/chromium/third_party/WebKit/Source/core/rendering/RenderCounter.h
index 3fa3fdd350c..85cdff3b643 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderCounter.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderCounter.h
@@ -34,11 +34,11 @@ public:
RenderCounter(Document*, const CounterContent&);
virtual ~RenderCounter();
- static void destroyCounterNodes(RenderObject*);
- static void destroyCounterNode(RenderObject*, const AtomicString& identifier);
+ static void destroyCounterNodes(RenderObject&);
+ static void destroyCounterNode(RenderObject&, const AtomicString& identifier);
static void rendererSubtreeAttached(RenderObject*);
static void rendererRemovedFromTree(RenderObject*);
- static void rendererStyleChanged(RenderObject*, const RenderStyle* oldStyle, const RenderStyle* newStyle);
+ static void rendererStyleChanged(RenderObject&, const RenderStyle* oldStyle, const RenderStyle* newStyle);
void updateCounter();
@@ -60,14 +60,7 @@ private:
friend class CounterNode;
};
-inline RenderCounter* toRenderCounter(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isCounter());
- return static_cast<RenderCounter*>(object);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toRenderCounter(const RenderCounter*);
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderCounter, isCounter());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderDeprecatedFlexibleBox.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderDeprecatedFlexibleBox.cpp
index ee4d483f6e1..9babdc2aae7 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderDeprecatedFlexibleBox.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderDeprecatedFlexibleBox.cpp
@@ -25,11 +25,11 @@
#include "config.h"
#include "core/rendering/RenderDeprecatedFlexibleBox.h"
-#include "core/page/UseCounter.h"
-#include "core/platform/graphics/Font.h"
+#include "core/frame/UseCounter.h"
#include "core/rendering/LayoutRepainter.h"
#include "core/rendering/RenderLayer.h"
#include "core/rendering/RenderView.h"
+#include "platform/fonts/Font.h"
#include "wtf/StdLibExtras.h"
#include "wtf/unicode/CharacterNames.h"
@@ -81,11 +81,11 @@ public:
if (!m_ordinalIteration)
m_currentOrdinal = m_forward ? 1 : m_largestOrdinal;
else {
- if (m_ordinalIteration >= m_ordinalValues.size() + 1)
+ if (static_cast<size_t>(m_ordinalIteration) >= m_ordinalValues.size() + 1)
return 0;
// Only copy+sort the values once per layout even if the iterator is reset.
- if (static_cast<size_t>(m_ordinalValues.size()) != m_sortedOrdinalValues.size()) {
+ if (m_ordinalValues.size() != m_sortedOrdinalValues.size()) {
copyToVector(m_ordinalValues, m_sortedOrdinalValues);
sort(m_sortedOrdinalValues.begin(), m_sortedOrdinalValues.end());
}
@@ -128,11 +128,11 @@ RenderDeprecatedFlexibleBox::RenderDeprecatedFlexibleBox(Element* element)
if (!isAnonymous()) {
const KURL& url = document().url();
if (url.protocolIs("chrome"))
- UseCounter::count(&document(), UseCounter::DeprecatedFlexboxChrome);
+ UseCounter::count(document(), UseCounter::DeprecatedFlexboxChrome);
else if (url.protocolIs("chrome-extension"))
- UseCounter::count(&document(), UseCounter::DeprecatedFlexboxChromeExtension);
+ UseCounter::count(document(), UseCounter::DeprecatedFlexboxChromeExtension);
else
- UseCounter::count(&document(), UseCounter::DeprecatedFlexboxWebContent);
+ UseCounter::count(document(), UseCounter::DeprecatedFlexboxWebContent);
}
}
@@ -308,7 +308,7 @@ void RenderDeprecatedFlexibleBox::layoutBlock(bool relayoutChildren, LayoutUnit)
// Update our scrollbars if we're overflow:auto/scroll/hidden now that we know if
// we overflow or not.
if (hasOverflowClip())
- layer()->updateScrollInfoAfterLayout();
+ layer()->scrollableArea()->updateAfterLayout();
// Repaint with our new bounds if they are different from our old bounds.
repainter.repaintAfterLayout();
@@ -880,7 +880,7 @@ void RenderDeprecatedFlexibleBox::layoutVerticalBox(bool relayoutChildren)
void RenderDeprecatedFlexibleBox::applyLineClamp(FlexBoxIterator& iterator, bool relayoutChildren)
{
- UseCounter::count(&document(), UseCounter::LineClamp);
+ UseCounter::count(document(), UseCounter::LineClamp);
int maxLineCount = 0;
for (RenderBox* child = iterator.first(); child; child = iterator.next()) {
@@ -948,10 +948,10 @@ void RenderDeprecatedFlexibleBox::applyLineClamp(FlexBoxIterator& iterator, bool
LayoutUnit totalWidth;
InlineBox* anchorBox = lastLine->lastChild();
if (anchorBox && anchorBox->renderer()->style()->isLink())
- totalWidth = anchorBox->logicalWidth() + font.width(constructTextRun(this, font, ellipsisAndSpace, 2, style()));
+ totalWidth = anchorBox->logicalWidth() + font.width(RenderBlockFlow::constructTextRun(this, font, ellipsisAndSpace, 2, style()));
else {
anchorBox = 0;
- totalWidth = font.width(constructTextRun(this, font, &horizontalEllipsis, 1, style()));
+ totalWidth = font.width(RenderBlockFlow::constructTextRun(this, font, &horizontalEllipsis, 1, style()));
}
// See if this width can be accommodated on the last visible line
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderDetailsMarker.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderDetailsMarker.cpp
index f0762941f93..68e6083489c 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderDetailsMarker.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderDetailsMarker.cpp
@@ -23,8 +23,8 @@
#include "HTMLNames.h"
#include "core/dom/Element.h"
-#include "core/platform/graphics/GraphicsContext.h"
#include "core/rendering/PaintInfo.h"
+#include "platform/graphics/GraphicsContext.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderDetailsMarker.h b/chromium/third_party/WebKit/Source/core/rendering/RenderDetailsMarker.h
index 8fa0f7e27cc..aa996c818a2 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderDetailsMarker.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderDetailsMarker.h
@@ -44,20 +44,7 @@ private:
Path getPath(const LayoutPoint& origin) const;
};
-inline RenderDetailsMarker* toRenderDetailsMarker(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isDetailsMarker());
- return static_cast<RenderDetailsMarker*>(object);
-}
-
-inline const RenderDetailsMarker* toRenderDetailsMarker(const RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isDetailsMarker());
- return static_cast<const RenderDetailsMarker*>(object);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toRenderDetailsMarker(const RenderDetailsMarker*);
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderDetailsMarker, isDetailsMarker());
}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderEmbeddedObject.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderEmbeddedObject.cpp
index 03b6f495e98..376aab5c5d8 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderEmbeddedObject.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderEmbeddedObject.cpp
@@ -27,19 +27,20 @@
#include "CSSValueKeywords.h"
#include "HTMLNames.h"
#include "core/html/HTMLIFrameElement.h"
-#include "core/page/Frame.h"
+#include "core/frame/Frame.h"
#include "core/page/Page.h"
-#include "core/page/Settings.h"
-#include "core/platform/LocalizedStrings.h"
-#include "core/platform/graphics/Font.h"
-#include "core/platform/graphics/FontSelector.h"
-#include "core/platform/graphics/GraphicsContextStateSaver.h"
-#include "core/platform/graphics/Path.h"
-#include "core/platform/graphics/TextRun.h"
+#include "core/frame/Settings.h"
#include "core/plugins/PluginView.h"
+#include "core/rendering/LayoutRectRecorder.h"
#include "core/rendering/PaintInfo.h"
#include "core/rendering/RenderTheme.h"
#include "core/rendering/RenderView.h"
+#include "platform/fonts/Font.h"
+#include "platform/fonts/FontSelector.h"
+#include "platform/graphics/GraphicsContextStateSaver.h"
+#include "platform/graphics/Path.h"
+#include "platform/text/PlatformLocale.h"
+#include "platform/text/TextRun.h"
namespace WebCore {
@@ -51,12 +52,6 @@ static const float replacementTextRoundedRectOpacity = 0.20f;
static const float replacementTextRoundedRectRadius = 5;
static const float replacementTextTextOpacity = 0.55f;
-static const Color& replacementTextRoundedRectPressedColor()
-{
- static const Color lightGray(205, 205, 205);
- return lightGray;
-}
-
RenderEmbeddedObject::RenderEmbeddedObject(Element* element)
: RenderPart(element)
, m_hasFallbackContent(false)
@@ -67,8 +62,6 @@ RenderEmbeddedObject::RenderEmbeddedObject(Element* element)
RenderEmbeddedObject::~RenderEmbeddedObject()
{
- if (frameView())
- frameView()->removeWidgetToUpdate(this);
}
bool RenderEmbeddedObject::requiresLayer() const
@@ -84,13 +77,14 @@ bool RenderEmbeddedObject::allowsAcceleratedCompositing() const
return widget() && widget()->isPluginView() && toPluginView(widget())->platformLayer();
}
-static String unavailablePluginReplacementText(RenderEmbeddedObject::PluginUnavailabilityReason pluginUnavailabilityReason)
+static String unavailablePluginReplacementText(Node* node, RenderEmbeddedObject::PluginUnavailabilityReason pluginUnavailabilityReason)
{
+ Locale& locale = node ? toElement(node)->locale() : Locale::defaultLocale();
switch (pluginUnavailabilityReason) {
case RenderEmbeddedObject::PluginMissing:
- return missingPluginText();
+ return locale.queryString(blink::WebLocalizedString::MissingPluginText);
case RenderEmbeddedObject::PluginBlockedByContentSecurityPolicy:
- return blockedPluginByContentSecurityPolicyText();
+ return locale.queryString(blink::WebLocalizedString::BlockedPluginText);
}
ASSERT_NOT_REACHED();
@@ -103,7 +97,7 @@ void RenderEmbeddedObject::setPluginUnavailabilityReason(PluginUnavailabilityRea
m_showsUnavailablePluginIndicator = true;
m_pluginUnavailabilityReason = pluginUnavailabilityReason;
- m_unavailablePluginReplacementText = unavailablePluginReplacementText(pluginUnavailabilityReason);
+ m_unavailablePluginReplacementText = unavailablePluginReplacementText(node(), pluginUnavailabilityReason);
}
bool RenderEmbeddedObject::showsUnavailablePluginIndicator() const
@@ -122,20 +116,11 @@ void RenderEmbeddedObject::paintContents(PaintInfo& paintInfo, const LayoutPoint
void RenderEmbeddedObject::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
{
- Page* page = 0;
- if (Frame* frame = this->frame())
- page = frame->page();
-
if (showsUnavailablePluginIndicator()) {
- if (page && paintInfo.phase == PaintPhaseForeground)
- page->addRelevantUnpaintedObject(this, visualOverflowRect());
RenderReplaced::paint(paintInfo, paintOffset);
return;
}
- if (page && paintInfo.phase == PaintPhaseForeground)
- page->addRelevantRepaintedObject(this, visualOverflowRect());
-
RenderPart::paint(paintInfo, paintOffset);
}
@@ -210,6 +195,7 @@ void RenderEmbeddedObject::layout()
ASSERT(needsLayout());
LayoutSize oldSize = contentBoxRect().size();
+ LayoutRectRecorder recorder(*this);
updateLogicalWidth();
updateLogicalHeight();
@@ -222,7 +208,7 @@ void RenderEmbeddedObject::layout()
updateLayerTransform();
if (!widget() && frameView())
- frameView()->addWidgetToUpdate(this);
+ frameView()->addWidgetToUpdate(*this);
clearNeedsLayout();
@@ -277,12 +263,7 @@ void RenderEmbeddedObject::viewCleared()
}
}
-bool RenderEmbeddedObject::scroll(ScrollDirection direction, ScrollGranularity granularity, float, Node**)
-{
- return false;
-}
-
-bool RenderEmbeddedObject::logicalScroll(ScrollLogicalDirection direction, ScrollGranularity granularity, float multiplier, Node** stopNode)
+bool RenderEmbeddedObject::scroll(ScrollDirection direction, ScrollGranularity granularity, float)
{
return false;
}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderEmbeddedObject.h b/chromium/third_party/WebKit/Source/core/rendering/RenderEmbeddedObject.h
index cc49411bc07..679658ec445 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderEmbeddedObject.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderEmbeddedObject.h
@@ -71,8 +71,7 @@ private:
virtual void viewCleared() OVERRIDE FINAL;
- virtual bool scroll(ScrollDirection, ScrollGranularity, float multiplier, Node** stopNode) OVERRIDE FINAL;
- virtual bool logicalScroll(ScrollLogicalDirection, ScrollGranularity, float multiplier, Node** stopNode) OVERRIDE FINAL;
+ virtual bool scroll(ScrollDirection, ScrollGranularity, float multiplier) OVERRIDE FINAL;
bool getReplacementTextGeometry(const LayoutPoint& accumulatedOffset, FloatRect& contentRect, Path&, FloatRect& replacementTextRect, Font&, TextRun&, float& textWidth) const;
@@ -88,14 +87,7 @@ private:
RenderObjectChildList m_children;
};
-inline RenderEmbeddedObject* toRenderEmbeddedObject(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isEmbeddedObject());
- return static_cast<RenderEmbeddedObject*>(object);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toRenderEmbeddedObject(const RenderEmbeddedObject*);
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderEmbeddedObject, isEmbeddedObject());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderFieldset.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderFieldset.cpp
index 23a3cf9af4e..b3962cf6f0a 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderFieldset.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderFieldset.cpp
@@ -26,8 +26,8 @@
#include "CSSPropertyNames.h"
#include "HTMLNames.h"
-#include "core/platform/graphics/GraphicsContextStateSaver.h"
#include "core/rendering/PaintInfo.h"
+#include "platform/graphics/GraphicsContextStateSaver.h"
using std::min;
using std::max;
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderFieldset.h b/chromium/third_party/WebKit/Source/core/rendering/RenderFieldset.h
index 65329bd6923..944ab4c1dc6 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderFieldset.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderFieldset.h
@@ -50,14 +50,7 @@ private:
virtual void paintMask(PaintInfo&, const LayoutPoint&);
};
-inline RenderFieldset* toRenderFieldset(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isFieldset());
- return static_cast<RenderFieldset*>(object);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toRenderFieldset(const RenderFieldset*);
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderFieldset, isFieldset());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderFileUploadControl.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderFileUploadControl.cpp
index 64c1d92a8e1..80a822fe74c 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderFileUploadControl.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderFileUploadControl.cpp
@@ -27,12 +27,13 @@
#include "core/dom/shadow/ShadowRoot.h"
#include "core/fileapi/FileList.h"
#include "core/html/HTMLInputElement.h"
-#include "core/platform/graphics/Font.h"
-#include "core/platform/graphics/GraphicsContextStateSaver.h"
-#include "core/platform/graphics/TextRun.h"
#include "core/rendering/PaintInfo.h"
#include "core/rendering/RenderButton.h"
#include "core/rendering/RenderTheme.h"
+#include "platform/fonts/Font.h"
+#include "platform/graphics/GraphicsContextStateSaver.h"
+#include "platform/text/PlatformLocale.h"
+#include "platform/text/TextRun.h"
using namespace std;
@@ -54,11 +55,6 @@ RenderFileUploadControl::~RenderFileUploadControl()
{
}
-bool RenderFileUploadControl::canBeReplacedWithInlineRunIn() const
-{
- return false;
-}
-
void RenderFileUploadControl::updateFromElement()
{
HTMLInputElement* input = toHTMLInputElement(node());
@@ -87,7 +83,6 @@ static int nodeWidth(Node* node)
int RenderFileUploadControl::maxFilenameWidth() const
{
- HTMLInputElement* input = toHTMLInputElement(node());
return max(0, contentBoxRect().pixelSnappedWidth() - nodeWidth(uploadButton()) - afterButtonSpacing);
}
@@ -119,7 +114,6 @@ void RenderFileUploadControl::paintObject(PaintInfo& paintInfo, const LayoutPoin
if (!button)
return;
- HTMLInputElement* input = toHTMLInputElement(node());
LayoutUnit buttonWidth = nodeWidth(button);
LayoutUnit buttonAndSpacingWidth = buttonWidth + afterButtonSpacing;
float textWidth = font.width(textRun);
@@ -163,7 +157,7 @@ void RenderFileUploadControl::computeIntrinsicLogicalWidths(LayoutUnit& minLogic
RenderFileUploadControl* renderer = const_cast<RenderFileUploadControl*>(this);
float minDefaultLabelWidth = defaultWidthNumChars * font.width(constructTextRun(renderer, font, characterAsString, style(), TextRun::AllowTrailingExpansion));
- const String label = RenderTheme::theme().fileListDefaultLabel(toHTMLInputElement(node())->multiple());
+ const String label = toHTMLInputElement(node())->locale().queryString(blink::WebLocalizedString::FileButtonNoFileSelectedLabel);
float defaultLabelWidth = font.width(constructTextRun(renderer, font, label, style(), TextRun::AllowTrailingExpansion));
if (HTMLInputElement* button = uploadButton())
if (RenderObject* buttonRenderer = button->renderer())
@@ -228,7 +222,7 @@ String RenderFileUploadControl::fileTextValue() const
{
HTMLInputElement* input = toHTMLInputElement(node());
ASSERT(input->files());
- return RenderTheme::theme().fileListNameForWidth(input->files(), style()->font(), maxFilenameWidth(), input->multiple());
+ return RenderTheme::theme().fileListNameForWidth(input->locale(), input->files(), style()->font(), maxFilenameWidth());
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderFileUploadControl.h b/chromium/third_party/WebKit/Source/core/rendering/RenderFileUploadControl.h
index acc97136ed2..f83bb2a585d 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderFileUploadControl.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderFileUploadControl.h
@@ -44,14 +44,11 @@ public:
private:
virtual const char* renderName() const { return "RenderFileUploadControl"; }
- virtual bool canBeReplacedWithInlineRunIn() const OVERRIDE;
virtual void updateFromElement();
virtual void computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const OVERRIDE;
virtual void computePreferredLogicalWidths();
virtual void paintObject(PaintInfo&, const LayoutPoint&);
- virtual bool requiresForcedStyleRecalcPropagation() const { return true; }
-
virtual bool supportsPartialLayout() const OVERRIDE { return false; }
int maxFilenameWidth() const;
@@ -63,20 +60,7 @@ private:
bool m_canReceiveDroppedFiles;
};
-inline RenderFileUploadControl* toRenderFileUploadControl(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isFileUploadControl());
- return static_cast<RenderFileUploadControl*>(object);
-}
-
-inline const RenderFileUploadControl* toRenderFileUploadControl(const RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isFileUploadControl());
- return static_cast<const RenderFileUploadControl*>(object);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toRenderFileUploadControl(const RenderFileUploadControl*);
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderFileUploadControl, isFileUploadControl());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderFlexibleBox.h b/chromium/third_party/WebKit/Source/core/rendering/RenderFlexibleBox.h
index f82a44579a4..c9297da7001 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderFlexibleBox.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderFlexibleBox.h
@@ -161,20 +161,7 @@ private:
int m_numberOfInFlowChildrenOnFirstLine;
};
-inline RenderFlexibleBox* toRenderFlexibleBox(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isFlexibleBox());
- return static_cast<RenderFlexibleBox*>(object);
-}
-
-inline const RenderFlexibleBox* toRenderFlexibleBox(const RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isFlexibleBox());
- return static_cast<const RenderFlexibleBox*>(object);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toRenderFlexibleBox(const RenderFlexibleBox*);
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderFlexibleBox, isFlexibleBox());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderFlowThread.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderFlowThread.cpp
index 0ec0f06af26..2e9bb88992a 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderFlowThread.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderFlowThread.cpp
@@ -32,17 +32,18 @@
#include "core/rendering/RenderFlowThread.h"
#include "core/dom/Node.h"
-#include "core/platform/PODIntervalTree.h"
-#include "core/platform/graphics/transforms/TransformState.h"
#include "core/rendering/FlowThreadController.h"
#include "core/rendering/HitTestRequest.h"
#include "core/rendering/HitTestResult.h"
+#include "core/rendering/LayoutRectRecorder.h"
#include "core/rendering/PaintInfo.h"
#include "core/rendering/RenderBoxRegionInfo.h"
#include "core/rendering/RenderInline.h"
#include "core/rendering/RenderLayer.h"
#include "core/rendering/RenderRegion.h"
#include "core/rendering/RenderView.h"
+#include "platform/PODIntervalTree.h"
+#include "platform/geometry/TransformState.h"
namespace WebCore {
@@ -173,9 +174,9 @@ void RenderFlowThread::validateRegions()
LayoutUnit regionLogicalWidth = region->pageLogicalWidth();
LayoutUnit regionLogicalHeight = region->pageLogicalHeight();
- if (!firstRegionVisited)
+ if (!firstRegionVisited) {
firstRegionVisited = true;
- else {
+ } else {
if (m_regionsHaveUniformLogicalWidth && previousRegionLogicalWidth != regionLogicalWidth)
m_regionsHaveUniformLogicalWidth = false;
if (m_regionsHaveUniformLogicalHeight && previousRegionLogicalHeight != regionLogicalHeight)
@@ -193,6 +194,7 @@ void RenderFlowThread::validateRegions()
void RenderFlowThread::layout()
{
+ LayoutRectRecorder recorder(*this);
m_pageLogicalSizeChanged = m_regionsInvalidated && everHadLayout();
// In case this is the second pass of the normal phase we need to update the auto-height regions to their initial value.
@@ -282,8 +284,9 @@ void RenderFlowThread::paintFlowThreadPortionInRegion(PaintInfo& paintInfo, Rend
LayoutRect flippedFlowThreadPortionRect(flowThreadPortionRect);
flipForWritingMode(flippedFlowThreadPortionRect);
portionLocation = flippedFlowThreadPortionRect.location();
- } else
+ } else {
portionLocation = flowThreadPortionRect.location();
+ }
adjustedPaintOffset = roundedIntPoint(paintOffset - portionLocation);
// The clipping rect for the region is set up by assuming the flowThreadPortionRect is going to paint offset from adjustedPaintOffset.
@@ -303,7 +306,10 @@ void RenderFlowThread::paintFlowThreadPortionInRegion(PaintInfo& paintInfo, Rend
context->translate(adjustedPaintOffset.x(), adjustedPaintOffset.y());
info.rect.moveBy(-adjustedPaintOffset);
- layer()->paint(context, info.rect, 0, 0, region, RenderLayer::PaintLayerTemporaryClipRects);
+ if (info.phase == PaintPhaseTextClip)
+ info.paintBehavior = PaintBehaviorForceBlackText;
+
+ layer()->paint(context, info.rect, info.paintBehavior, 0, region, PaintLayerTemporaryClipRects);
context->restore();
}
@@ -327,11 +333,12 @@ bool RenderFlowThread::hitTestFlowThreadPortionInRegion(RenderRegion* region, co
LayoutRect flippedFlowThreadPortionRect(flowThreadPortionRect);
flipForWritingMode(flippedFlowThreadPortionRect);
renderFlowThreadOffset = accumulatedOffset - flippedFlowThreadPortionRect.location();
- } else
+ } else {
renderFlowThreadOffset = accumulatedOffset - flowThreadPortionRect.location();
+ }
// Always ignore clipping, since the RenderFlowThread has nothing to do with the bounds of the FrameView.
- HitTestRequest newRequest(request.type() | HitTestRequest::IgnoreClipping | HitTestRequest::DisallowShadowContent);
+ HitTestRequest newRequest(request.type() | HitTestRequest::IgnoreClipping | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent);
// Make a new temporary HitTestLocation in the new region.
HitTestLocation newHitTestLocation(locationInContainer, -renderFlowThreadOffset, region);
@@ -391,6 +398,31 @@ RenderRegion* RenderFlowThread::regionAtBlockOffset(LayoutUnit offset, bool exte
return adapter.result();
}
+RenderRegion* RenderFlowThread::regionFromAbsolutePointAndBox(IntPoint absolutePoint, const RenderBox* flowedBox)
+{
+ if (!flowedBox)
+ return 0;
+
+ RenderRegion* startRegion = 0;
+ RenderRegion* endRegion = 0;
+ getRegionRangeForBox(flowedBox, startRegion, endRegion);
+
+ if (!startRegion)
+ return 0;
+
+ for (RenderRegionList::iterator iter = m_regionList.find(startRegion); iter != m_regionList.end(); ++iter) {
+ RenderRegion* region = *iter;
+ IntRect regionAbsoluteRect(roundedIntPoint(region->localToAbsolute()), roundedIntSize(region->frameRect().size()));
+ if (regionAbsoluteRect.contains(absolutePoint))
+ return region;
+
+ if (region == endRegion)
+ break;
+ }
+
+ return 0;
+}
+
LayoutPoint RenderFlowThread::adjustedPositionRelativeToOffsetParent(const RenderBoxModelObject& boxModelObject, const LayoutPoint& startPoint)
{
LayoutPoint referencePoint = startPoint;
@@ -398,8 +430,9 @@ LayoutPoint RenderFlowThread::adjustedPositionRelativeToOffsetParent(const Rende
// FIXME: This needs to be adapted for different writing modes inside the flow thread.
RenderRegion* startRegion = regionAtBlockOffset(referencePoint.y());
if (startRegion) {
+ RenderBoxModelObject* startRegionBox = startRegion->isRenderNamedFlowFragment() ? toRenderBoxModelObject(startRegion->parent()) : startRegion;
// Take into account the offset coordinates of the region.
- RenderObject* currObject = startRegion;
+ RenderObject* currObject = startRegionBox;
RenderObject* currOffsetParentRenderer;
Element* currOffsetParentElement;
while ((currOffsetParentElement = currObject->offsetParent()) && (currOffsetParentRenderer = currOffsetParentElement->renderer())) {
@@ -440,9 +473,9 @@ LayoutPoint RenderFlowThread::adjustedPositionRelativeToOffsetParent(const Rende
// Get the logical top coordinate of the current object.
LayoutUnit top = 0;
- if (boxModelObject.isRenderBlock())
+ if (boxModelObject.isRenderBlock()) {
top = toRenderBlock(&boxModelObject)->offsetFromLogicalTopOfFirstPage();
- else {
+ } else {
if (boxModelObject.containingBlock())
top = boxModelObject.containingBlock()->offsetFromLogicalTopOfFirstPage();
@@ -456,7 +489,7 @@ LayoutPoint RenderFlowThread::adjustedPositionRelativeToOffsetParent(const Rende
// and compute the object's top, relative to the region's top.
LayoutUnit regionLogicalTop = startRegion->pageLogicalTopForOffset(top);
LayoutUnit topRelativeToRegion = top - regionLogicalTop;
- referencePoint.setY(startRegion->offsetTop() + topRelativeToRegion);
+ referencePoint.setY(startRegionBox->offsetTop() + topRelativeToRegion);
// Since the top has been overriden, check if the
// relative/sticky positioning must be reconsidered.
@@ -468,7 +501,7 @@ LayoutPoint RenderFlowThread::adjustedPositionRelativeToOffsetParent(const Rende
// Since we're looking for the offset relative to the body, we must also
// take into consideration the borders of the region.
- referencePoint.move(startRegion->borderLeft(), startRegion->borderTop());
+ referencePoint.move(startRegionBox->borderLeft(), startRegionBox->borderTop());
}
return referencePoint;
@@ -867,7 +900,7 @@ void RenderFlowThread::updateRegionsFlowThreadPortionRect(const RenderRegion* la
region->clearComputedAutoHeight();
LayoutUnit regionLogicalWidth = region->pageLogicalWidth();
- LayoutUnit regionLogicalHeight = std::min<LayoutUnit>(LayoutUnit::max() / 2 - logicalHeight, region->logicalHeightOfAllFlowThreadContent());
+ LayoutUnit regionLogicalHeight = std::min<LayoutUnit>(RenderFlowThread::maxLogicalHeight() - logicalHeight, region->logicalHeightOfAllFlowThreadContent());
LayoutRect regionRect(style()->direction() == LTR ? LayoutUnit() : logicalWidth() - regionLogicalWidth, logicalHeight, regionLogicalWidth, regionLogicalHeight);
@@ -904,7 +937,7 @@ bool RenderFlowThread::addForcedRegionBreak(LayoutUnit offsetBreakInFlowThread,
RenderObjectToRegionMap::iterator iter = mapToUse.find(breakChild);
if (iter != mapToUse.end()) {
RenderRegionList::iterator regionIter = m_regionList.find(iter->value);
- ASSERT(regionIter != m_regionList.end());
+ ASSERT_WITH_SECURITY_IMPLICATION(regionIter != m_regionList.end());
ASSERT((*regionIter)->hasAutoLogicalHeight());
initializeRegionsComputedAutoHeight(*regionIter);
@@ -944,8 +977,9 @@ bool RenderFlowThread::addForcedRegionBreak(LayoutUnit offsetBreakInFlowThread,
region->setComputedAutoHeight(regionComputedAutoHeight);
currentRegionOffsetInFlowThread += regionComputedAutoHeight;
- } else
+ } else {
currentRegionOffsetInFlowThread += isHorizontalWritingMode() ? region->flowThreadPortionRect().height() : region->flowThreadPortionRect().width();
+ }
// If the break was found inside an auto-height region its size changed so we need to recompute the flow thread portion rectangles.
// Also, if this is the last break after the content we need to clear the computedAutoHeight value on the last empty regions.
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderFlowThread.h b/chromium/third_party/WebKit/Source/core/rendering/RenderFlowThread.h
index c6106041319..7986768361e 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderFlowThread.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderFlowThread.h
@@ -35,7 +35,6 @@
#include "wtf/HashCountedSet.h"
#include "wtf/ListHashSet.h"
#include "wtf/PassRefPtr.h"
-#include "wtf/UnusedParam.h"
namespace WebCore {
@@ -115,6 +114,8 @@ public:
};
RenderRegion* regionAtBlockOffset(LayoutUnit, bool extendLastRegion = false, RegionAutoGenerationPolicy = AllowRegionAutoGeneration);
+ RenderRegion* regionFromAbsolutePointAndBox(IntPoint, const RenderBox* flowedBox);
+
bool regionsHaveUniformLogicalWidth() const { return m_regionsHaveUniformLogicalWidth; }
bool regionsHaveUniformLogicalHeight() const { return m_regionsHaveUniformLogicalHeight; }
@@ -171,6 +172,9 @@ public:
void popFlowThreadLayoutState();
LayoutUnit offsetFromLogicalTopOfFirstRegion(const RenderBlock*) const;
+ // Used to estimate the maximum height of the flow thread.
+ static LayoutUnit maxLogicalHeight() { return LayoutUnit::max() / 2; }
+
protected:
virtual const char* renderName() const = 0;
@@ -291,20 +295,7 @@ private:
};
-inline RenderFlowThread* toRenderFlowThread(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isRenderFlowThread());
- return static_cast<RenderFlowThread*>(object);
-}
-
-inline const RenderFlowThread* toRenderFlowThread(const RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isRenderFlowThread());
- return static_cast<const RenderFlowThread*>(object);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toRenderFlowThread(const RenderFlowThread*);
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderFlowThread, isRenderFlowThread());
class CurrentRenderFlowThreadMaintainer {
WTF_MAKE_NONCOPYABLE(CurrentRenderFlowThreadMaintainer);
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderFrame.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderFrame.cpp
index c67bd0a5dbd..329ae3422b4 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderFrame.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderFrame.cpp
@@ -25,7 +25,7 @@
#include "core/rendering/RenderFrame.h"
#include "core/html/HTMLFrameElement.h"
-#include "core/page/FrameView.h"
+#include "core/frame/FrameView.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderFrame.h b/chromium/third_party/WebKit/Source/core/rendering/RenderFrame.h
index 848b9257b82..55391b98bd9 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderFrame.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderFrame.h
@@ -45,14 +45,7 @@ private:
virtual void viewCleared();
};
-inline RenderFrame* toRenderFrame(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isFrame());
- return static_cast<RenderFrame*>(object);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toRenderFrame(const RenderFrame*);
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderFrame, isFrame());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderFrameSet.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderFrameSet.cpp
index 86748fbc85e..a0bf472cac3 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderFrameSet.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderFrameSet.cpp
@@ -25,17 +25,19 @@
#include "core/rendering/RenderFrameSet.h"
#include "core/dom/Document.h"
-#include "core/dom/EventNames.h"
-#include "core/dom/MouseEvent.h"
+#include "core/events/MouseEvent.h"
+#include "core/events/ThreadLocalEventNames.h"
#include "core/html/HTMLDimension.h"
#include "core/html/HTMLFrameSetElement.h"
#include "core/page/EventHandler.h"
-#include "core/page/Frame.h"
-#include "core/platform/Cursor.h"
-#include "core/platform/graphics/GraphicsContext.h"
+#include "core/frame/Frame.h"
+#include "core/rendering/GraphicsContextAnnotator.h"
+#include "core/rendering/LayoutRectRecorder.h"
#include "core/rendering/PaintInfo.h"
#include "core/rendering/RenderFrame.h"
#include "core/rendering/RenderView.h"
+#include "platform/Cursor.h"
+#include "platform/graphics/GraphicsContext.h"
namespace WebCore {
@@ -439,7 +441,8 @@ void RenderFrameSet::layout()
{
ASSERT(needsLayout());
- bool doFullRepaint = selfNeedsLayout() && checkForRepaintDuringLayout();
+ LayoutRectRecorder recorder(*this);
+ bool doFullRepaint = !RuntimeEnabledFeatures::repaintAfterLayoutEnabled() && selfNeedsLayout() && checkForRepaintDuringLayout();
LayoutRect oldBounds;
RenderLayerModelObject* repaintContainer = 0;
if (doFullRepaint) {
@@ -562,7 +565,7 @@ bool RenderFrameSet::userResize(MouseEvent* evt)
if (!m_isResizing) {
if (needsLayout())
return false;
- if (evt->type() == eventNames().mousedownEvent && evt->button() == LeftButton) {
+ if (evt->type() == EventTypeNames::mousedown && evt->button() == LeftButton) {
FloatPoint localPos = absoluteToLocal(evt->absoluteLocation(), UseTransforms);
startResizing(m_cols, localPos.x());
startResizing(m_rows, localPos.y());
@@ -572,11 +575,11 @@ bool RenderFrameSet::userResize(MouseEvent* evt)
}
}
} else {
- if (evt->type() == eventNames().mousemoveEvent || (evt->type() == eventNames().mouseupEvent && evt->button() == LeftButton)) {
+ if (evt->type() == EventTypeNames::mousemove || (evt->type() == EventTypeNames::mouseup && evt->button() == LeftButton)) {
FloatPoint localPos = absoluteToLocal(evt->absoluteLocation(), UseTransforms);
continueResizing(m_cols, localPos.x());
continueResizing(m_rows, localPos.y());
- if (evt->type() == eventNames().mouseupEvent && evt->button() == LeftButton) {
+ if (evt->type() == EventTypeNames::mouseup && evt->button() == LeftButton) {
setIsResizing(false);
return true;
}
@@ -594,7 +597,7 @@ void RenderFrameSet::setIsResizing(bool isResizing)
toRenderFrameSet(ancestor)->m_isChildResizing = isResizing;
}
if (Frame* frame = this->frame())
- frame->eventHandler()->setResizingFrameSet(isResizing ? frameSet() : 0);
+ frame->eventHandler().setResizingFrameSet(isResizing ? frameSet() : 0);
}
bool RenderFrameSet::isResizingRow() const
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderFrameSet.h b/chromium/third_party/WebKit/Source/core/rendering/RenderFrameSet.h
index b4a9a5179b2..21f90eac87a 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderFrameSet.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderFrameSet.h
@@ -132,15 +132,7 @@ private:
bool m_isChildResizing;
};
-
-inline RenderFrameSet* toRenderFrameSet(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isFrameSet());
- return static_cast<RenderFrameSet*>(object);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toRenderFrameSet(const RenderFrameSet*);
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderFrameSet, isFrameSet());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderFullScreen.h b/chromium/third_party/WebKit/Source/core/rendering/RenderFullScreen.h
index 65665d36d40..48c40f4f7fe 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderFullScreen.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderFullScreen.h
@@ -54,14 +54,8 @@ protected:
RenderBlock* m_placeholder;
};
-inline RenderFullScreen* toRenderFullScreen(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(object->isRenderFullScreen());
- return static_cast<RenderFullScreen*>(object);
-}
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderFullScreen, isRenderFullScreen());
-// This will catch anyone doing an unnecessary cast:
-void toRenderFullScreen(RenderFullScreen*);
}
#endif
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderGeometryMap.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderGeometryMap.cpp
index f7dc6401734..07ab16f7014 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderGeometryMap.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderGeometryMap.cpp
@@ -26,11 +26,10 @@
#include "config.h"
#include "core/rendering/RenderGeometryMap.h"
-#include "core/page/Frame.h"
-#include "core/page/Page.h"
-#include "core/platform/graphics/transforms/TransformState.h"
+#include "core/frame/Frame.h"
#include "core/rendering/RenderLayer.h"
#include "core/rendering/RenderView.h"
+#include "platform/geometry/TransformState.h"
#include "wtf/TemporaryChange.h"
namespace WebCore {
@@ -118,10 +117,19 @@ FloatPoint RenderGeometryMap::mapToContainer(const FloatPoint& p, const RenderLa
}
#if !ASSERT_DISABLED
- FloatPoint rendererMappedResult = m_mapping.last().m_renderer->localToAbsolute(p, m_mapCoordinatesFlags);
- ASSERT(roundedIntPoint(rendererMappedResult) == roundedIntPoint(result));
-// if (roundedIntPoint(rendererMappedResult) != roundedIntPoint(result))
-// fprintf(stderr, "Mismatched point\n");
+ if (m_mapping.size() > 0) {
+ const RenderObject* lastRenderer = m_mapping.last().m_renderer;
+ const RenderLayer* layer = lastRenderer->enclosingLayer();
+
+ // Bounds for invisible layers are intentionally not calculated, and are
+ // therefore not necessarily expected to be correct here. This is ok,
+ // because they will be recomputed if the layer becomes visible.
+ if (!layer || !layer->subtreeIsInvisible()) {
+ FloatPoint rendererMappedResult = lastRenderer->localToAbsolute(p, m_mapCoordinatesFlags);
+
+ ASSERT(roundedIntPoint(rendererMappedResult) == roundedIntPoint(result));
+ }
+ }
#endif
return result;
@@ -155,12 +163,21 @@ FloatQuad RenderGeometryMap::mapToContainer(const FloatRect& rect, const RenderL
}
#if !ASSERT_DISABLED
- FloatRect rendererMappedResult = m_mapping.last().m_renderer->localToContainerQuad(rect, container, m_mapCoordinatesFlags).boundingBox();
- // Inspector creates renderers with negative width <https://bugs.webkit.org/show_bug.cgi?id=87194>.
- // Taking FloatQuad bounds avoids spurious assertions because of that.
- ASSERT(enclosingIntRect(rendererMappedResult) == enclosingIntRect(FloatQuad(result).boundingBox()));
-// if (enclosingIntRect(rendererMappedResult) != enclosingIntRect(FloatQuad(result).boundingBox()))
-// fprintf(stderr, "Mismatched rects\n");
+ if (m_mapping.size() > 0) {
+ const RenderObject* lastRenderer = m_mapping.last().m_renderer;
+ const RenderLayer* layer = lastRenderer->enclosingLayer();
+
+ // Bounds for invisible layers are intentionally not calculated, and are
+ // therefore not necessarily expected to be correct here. This is ok,
+ // because they will be recomputed if the layer becomes visible.
+ if (!layer || !layer->subtreeIsInvisible()) {
+ FloatRect rendererMappedResult = lastRenderer->localToContainerQuad(rect, container, m_mapCoordinatesFlags).boundingBox();
+
+ // Inspector creates renderers with negative width <https://bugs.webkit.org/show_bug.cgi?id=87194>.
+ // Taking FloatQuad bounds avoids spurious assertions because of that.
+ ASSERT(enclosingIntRect(rendererMappedResult) == enclosingIntRect(FloatQuad(result).boundingBox()));
+ }
+ }
#endif
return result;
@@ -322,8 +339,7 @@ bool RenderGeometryMap::isTopmostRenderView(const RenderObject* renderer) const
if (!(m_mapCoordinatesFlags & TraverseDocumentBoundaries))
return true;
- Frame* thisFrame = renderer->frame();
- return thisFrame == thisFrame->page()->mainFrame();
+ return renderer->frame()->isMainFrame();
}
#endif
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderGeometryMap.h b/chromium/third_party/WebKit/Source/core/rendering/RenderGeometryMap.h
index 9892c8adfed..8049bbbc066 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderGeometryMap.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderGeometryMap.h
@@ -26,12 +26,12 @@
#ifndef RenderGeometryMap_h
#define RenderGeometryMap_h
-#include "core/platform/graphics/FloatPoint.h"
-#include "core/platform/graphics/FloatQuad.h"
-#include "core/platform/graphics/IntSize.h"
-#include "core/platform/graphics/LayoutSize.h"
-#include "core/platform/graphics/transforms/TransformationMatrix.h"
#include "core/rendering/RenderObject.h"
+#include "platform/geometry/FloatPoint.h"
+#include "platform/geometry/FloatQuad.h"
+#include "platform/geometry/IntSize.h"
+#include "platform/geometry/LayoutSize.h"
+#include "platform/transforms/TransformationMatrix.h"
#include "wtf/OwnPtr.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderGrid.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderGrid.cpp
index 9de8da1819b..38c296ac866 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderGrid.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderGrid.cpp
@@ -93,7 +93,7 @@ class RenderGrid::GridIterator {
public:
// |direction| is the direction that is fixed to |fixedTrackIndex| so e.g
// GridIterator(m_grid, ForColumns, 1) will walk over the rows of the 2nd column.
- GridIterator(const GridRepresentation& grid, TrackSizingDirection direction, size_t fixedTrackIndex)
+ GridIterator(const GridRepresentation& grid, GridTrackSizingDirection direction, size_t fixedTrackIndex)
: m_grid(grid)
, m_direction(direction)
, m_rowIndex((direction == ForColumns) ? 0 : fixedTrackIndex)
@@ -140,16 +140,35 @@ public:
private:
const GridRepresentation& m_grid;
- TrackSizingDirection m_direction;
+ GridTrackSizingDirection m_direction;
size_t m_rowIndex;
size_t m_columnIndex;
size_t m_childIndex;
};
+struct RenderGrid::GridSizingData {
+ WTF_MAKE_NONCOPYABLE(GridSizingData);
+public:
+ GridSizingData(size_t gridColumnCount, size_t gridRowCount)
+ : columnTracks(gridColumnCount)
+ , rowTracks(gridRowCount)
+ {
+ }
+
+ Vector<GridTrack> columnTracks;
+ Vector<GridTrack> rowTracks;
+ Vector<size_t> contentSizedTracksIndex;
+
+ // Performance optimization: hold onto these Vectors until the end of Layout to avoid repeated malloc / free.
+ Vector<LayoutUnit> distributeTrackVector;
+ Vector<GridTrack*> filteredTracks;
+};
+
RenderGrid::RenderGrid(Element* element)
: RenderBlock(element)
, m_gridIsDirty(true)
, m_orderIterator(this)
+ , m_gridItemOverflowGridArea(false)
{
// All of our children must be block level.
setChildrenInline(false);
@@ -272,7 +291,7 @@ void RenderGrid::layoutBlock(bool relayoutChildren, LayoutUnit)
// Update our scroll information if we're overflow:auto/scroll/hidden now that we know if
// we overflow or not.
if (hasOverflowClip())
- layer()->updateScrollInfoAfterLayout();
+ layer()->scrollableArea()->updateAfterLayout();
repainter.repaintAfterLayout();
@@ -283,13 +302,13 @@ void RenderGrid::computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, Layo
{
const_cast<RenderGrid*>(this)->placeItemsOnGrid();
- // FIXME: This is an inefficient way to fill our sizes as it will try every grid areas, when we would
- // only want to account for fixed grid tracks and grid items. Also this will be incorrect if we have spanning
- // grid items.
- for (size_t i = 0; i < gridColumnCount(); ++i) {
- const GridTrackSize& trackSize = gridTrackSize(ForColumns, i);
- LayoutUnit minTrackBreadth = computePreferredTrackWidth(trackSize.minTrackBreadth(), i);
- LayoutUnit maxTrackBreadth = computePreferredTrackWidth(trackSize.maxTrackBreadth(), i);
+ GridSizingData sizingData(gridColumnCount(), gridRowCount());
+ LayoutUnit availableLogicalSpace = 0;
+ const_cast<RenderGrid*>(this)->computedUsedBreadthOfGridTracks(ForColumns, sizingData, availableLogicalSpace);
+
+ for (size_t i = 0; i < sizingData.columnTracks.size(); ++i) {
+ LayoutUnit minTrackBreadth = sizingData.columnTracks[i].m_usedBreadth;
+ LayoutUnit maxTrackBreadth = sizingData.columnTracks[i].m_maxBreadth;
maxTrackBreadth = std::max(maxTrackBreadth, minTrackBreadth);
minLogicalWidth += minTrackBreadth;
@@ -318,46 +337,16 @@ void RenderGrid::computePreferredLogicalWidths()
clearPreferredLogicalWidthsDirty();
}
-LayoutUnit RenderGrid::computePreferredTrackWidth(const GridLength& gridLength, size_t trackIndex) const
+void RenderGrid::computedUsedBreadthOfGridTracks(GridTrackSizingDirection direction, GridSizingData& sizingData)
{
- if (gridLength.isFlex())
- return 0;
-
- const Length& length = gridLength.length();
-
- if (length.isFixed()) {
- // Grid areas don't have borders, margins or paddings so we don't need to account for them.
- return length.intValue();
- }
-
- if (length.isMinContent()) {
- LayoutUnit minContentSize = 0;
- GridIterator iterator(m_grid, ForColumns, trackIndex);
- while (RenderBox* gridItem = iterator.nextGridItem())
- minContentSize = std::max(minContentSize, gridItem->minPreferredLogicalWidth() + marginIntrinsicLogicalWidthForChild(gridItem));
-
- return minContentSize;
- }
-
- if (length.isMaxContent()) {
- LayoutUnit maxContentSize = 0;
- GridIterator iterator(m_grid, ForColumns, trackIndex);
- while (RenderBox* gridItem = iterator.nextGridItem())
- maxContentSize = std::max(maxContentSize, gridItem->maxPreferredLogicalWidth() + marginIntrinsicLogicalWidthForChild(gridItem));
-
- return maxContentSize;
- }
-
- // FIXME: css3-sizing mentions that we should resolve "definite sizes"
- // (including <percentage> and calc()) but we don't do it elsewhere.
- return 0;
+ LayoutUnit availableLogicalSpace = (direction == ForColumns) ? availableLogicalWidth() : availableLogicalHeight(IncludeMarginBorderPadding);
+ computedUsedBreadthOfGridTracks(direction, sizingData, availableLogicalSpace);
}
-void RenderGrid::computedUsedBreadthOfGridTracks(TrackSizingDirection direction, Vector<GridTrack>& columnTracks, Vector<GridTrack>& rowTracks)
+void RenderGrid::computedUsedBreadthOfGridTracks(GridTrackSizingDirection direction, GridSizingData& sizingData, LayoutUnit& availableLogicalSpace)
{
- LayoutUnit availableLogicalSpace = (direction == ForColumns) ? availableLogicalWidth() : availableLogicalHeight(IncludeMarginBorderPadding);
- Vector<GridTrack>& tracks = (direction == ForColumns) ? columnTracks : rowTracks;
- Vector<size_t> contentSizedTracks;
+ Vector<GridTrack>& tracks = (direction == ForColumns) ? sizingData.columnTracks : sizingData.rowTracks;
+ sizingData.contentSizedTracksIndex.shrink(0);
for (size_t i = 0; i < tracks.size(); ++i) {
GridTrack& track = tracks[i];
const GridTrackSize& trackSize = gridTrackSize(direction, i);
@@ -370,11 +359,11 @@ void RenderGrid::computedUsedBreadthOfGridTracks(TrackSizingDirection direction,
track.m_maxBreadth = std::max(track.m_maxBreadth, track.m_usedBreadth);
if (trackSize.isContentSized())
- contentSizedTracks.append(i);
+ sizingData.contentSizedTracksIndex.append(i);
}
- if (!contentSizedTracks.isEmpty())
- resolveContentBasedTrackSizingFunctions(direction, columnTracks, rowTracks, contentSizedTracks, availableLogicalSpace);
+ if (!sizingData.contentSizedTracksIndex.isEmpty())
+ resolveContentBasedTrackSizingFunctions(direction, sizingData, availableLogicalSpace);
for (size_t i = 0; i < tracks.size(); ++i) {
ASSERT(tracks[i].m_maxBreadth != infinity);
@@ -389,7 +378,7 @@ void RenderGrid::computedUsedBreadthOfGridTracks(TrackSizingDirection direction,
for (size_t i = 0; i < tracksSize; ++i)
tracksForDistribution[i] = tracks.data() + i;
- distributeSpaceToTracks(tracksForDistribution, 0, &GridTrack::usedBreadth, &GridTrack::growUsedBreadth, availableLogicalSpace);
+ distributeSpaceToTracks(tracksForDistribution, 0, &GridTrack::usedBreadth, &GridTrack::growUsedBreadth, sizingData, availableLogicalSpace);
// 4. Grow all Grid tracks having a fraction as the MaxTrackSizingFunction.
@@ -404,28 +393,28 @@ void RenderGrid::computedUsedBreadthOfGridTracks(TrackSizingDirection direction,
}
}
-LayoutUnit RenderGrid::computeUsedBreadthOfMinLength(TrackSizingDirection direction, const GridLength& gridLength) const
+LayoutUnit RenderGrid::computeUsedBreadthOfMinLength(GridTrackSizingDirection direction, const GridLength& gridLength) const
{
if (gridLength.isFlex())
return 0;
const Length& trackLength = gridLength.length();
ASSERT(!trackLength.isAuto());
- if (trackLength.isFixed() || trackLength.isPercent() || trackLength.isViewportPercentage())
+ if (trackLength.isSpecified())
return computeUsedBreadthOfSpecifiedLength(direction, trackLength);
ASSERT(trackLength.isMinContent() || trackLength.isMaxContent());
return 0;
}
-LayoutUnit RenderGrid::computeUsedBreadthOfMaxLength(TrackSizingDirection direction, const GridLength& gridLength, LayoutUnit usedBreadth) const
+LayoutUnit RenderGrid::computeUsedBreadthOfMaxLength(GridTrackSizingDirection direction, const GridLength& gridLength, LayoutUnit usedBreadth) const
{
if (gridLength.isFlex())
return usedBreadth;
const Length& trackLength = gridLength.length();
ASSERT(!trackLength.isAuto());
- if (trackLength.isFixed() || trackLength.isPercent() || trackLength.isViewportPercentage()) {
+ if (trackLength.isSpecified()) {
LayoutUnit computedBreadth = computeUsedBreadthOfSpecifiedLength(direction, trackLength);
ASSERT(computedBreadth != infinity);
return computedBreadth;
@@ -435,10 +424,9 @@ LayoutUnit RenderGrid::computeUsedBreadthOfMaxLength(TrackSizingDirection direct
return infinity;
}
-LayoutUnit RenderGrid::computeUsedBreadthOfSpecifiedLength(TrackSizingDirection direction, const Length& trackLength) const
+LayoutUnit RenderGrid::computeUsedBreadthOfSpecifiedLength(GridTrackSizingDirection direction, const Length& trackLength) const
{
- // FIXME: We still need to support calc() here (https://webkit.org/b/103761).
- ASSERT(trackLength.isFixed() || trackLength.isPercent() || trackLength.isViewportPercentage());
+ ASSERT(trackLength.isSpecified());
// FIXME: The -1 here should be replaced by whatever the intrinsic height of the grid is.
return valueForLength(trackLength, direction == ForColumns ? logicalWidth() : computeContentLogicalHeight(style()->logicalHeight(), -1), view());
}
@@ -448,7 +436,7 @@ static bool sortByGridNormalizedFlexValue(const GridTrackForNormalization& track
return track1.m_normalizedFlexValue < track2.m_normalizedFlexValue;
}
-double RenderGrid::computeNormalizedFractionBreadth(Vector<GridTrack>& tracks, TrackSizingDirection direction, LayoutUnit availableLogicalSpace) const
+double RenderGrid::computeNormalizedFractionBreadth(Vector<GridTrack>& tracks, GridTrackSizingDirection direction, LayoutUnit availableLogicalSpace) const
{
// |availableLogicalSpace| already accounts for the used breadths so no need to remove it here.
@@ -493,7 +481,7 @@ double RenderGrid::computeNormalizedFractionBreadth(Vector<GridTrack>& tracks, T
return availableLogicalSpaceIgnoringFractionTracks / accumulatedFractions;
}
-const GridTrackSize& RenderGrid::gridTrackSize(TrackSizingDirection direction, size_t i) const
+const GridTrackSize& RenderGrid::gridTrackSize(GridTrackSizingDirection direction, size_t i) const
{
const Vector<GridTrackSize>& trackStyles = (direction == ForColumns) ? style()->gridDefinitionColumns() : style()->gridDefinitionRows();
if (i >= trackStyles.size())
@@ -531,7 +519,7 @@ LayoutUnit RenderGrid::logicalContentHeightForChild(RenderBox* child, Vector<Gri
return child->logicalHeight();
}
-LayoutUnit RenderGrid::minContentForChild(RenderBox* child, TrackSizingDirection direction, Vector<GridTrack>& columnTracks)
+LayoutUnit RenderGrid::minContentForChild(RenderBox* child, GridTrackSizingDirection direction, Vector<GridTrack>& columnTracks)
{
bool hasOrthogonalWritingMode = child->isHorizontalWritingMode() != isHorizontalWritingMode();
// FIXME: Properly support orthogonal writing mode.
@@ -541,13 +529,13 @@ LayoutUnit RenderGrid::minContentForChild(RenderBox* child, TrackSizingDirection
if (direction == ForColumns) {
// FIXME: It's unclear if we should return the intrinsic width or the preferred width.
// See http://lists.w3.org/Archives/Public/www-style/2013Jan/0245.html
- return child->minPreferredLogicalWidth();
+ return child->minPreferredLogicalWidth() + marginIntrinsicLogicalWidthForChild(child);
}
return logicalContentHeightForChild(child, columnTracks);
}
-LayoutUnit RenderGrid::maxContentForChild(RenderBox* child, TrackSizingDirection direction, Vector<GridTrack>& columnTracks)
+LayoutUnit RenderGrid::maxContentForChild(RenderBox* child, GridTrackSizingDirection direction, Vector<GridTrack>& columnTracks)
{
bool hasOrthogonalWritingMode = child->isHorizontalWritingMode() != isHorizontalWritingMode();
// FIXME: Properly support orthogonal writing mode.
@@ -557,60 +545,60 @@ LayoutUnit RenderGrid::maxContentForChild(RenderBox* child, TrackSizingDirection
if (direction == ForColumns) {
// FIXME: It's unclear if we should return the intrinsic width or the preferred width.
// See http://lists.w3.org/Archives/Public/www-style/2013Jan/0245.html
- return child->maxPreferredLogicalWidth();
+ return child->maxPreferredLogicalWidth() + marginIntrinsicLogicalWidthForChild(child);
}
return logicalContentHeightForChild(child, columnTracks);
}
-void RenderGrid::resolveContentBasedTrackSizingFunctions(TrackSizingDirection direction, Vector<GridTrack>& columnTracks, Vector<GridTrack>& rowTracks, const Vector<size_t>& contentSizedTracks, LayoutUnit& availableLogicalSpace)
+void RenderGrid::resolveContentBasedTrackSizingFunctions(GridTrackSizingDirection direction, GridSizingData& sizingData, LayoutUnit& availableLogicalSpace)
{
// FIXME: Split the grid tracks into groups that doesn't overlap a <flex> grid track (crbug.com/235258).
// FIXME: Per step 2 of the specification, we should order the grid items by increasing span.
- for (size_t i = 0; i < contentSizedTracks.size(); ++i) {
- GridIterator iterator(m_grid, direction, contentSizedTracks[i]);
+ for (size_t i = 0; i < sizingData.contentSizedTracksIndex.size(); ++i) {
+ GridIterator iterator(m_grid, direction, sizingData.contentSizedTracksIndex[i]);
while (RenderBox* gridItem = iterator.nextGridItem()) {
- resolveContentBasedTrackSizingFunctionsForItems(direction, columnTracks, rowTracks, gridItem, &GridTrackSize::hasMinOrMaxContentMinTrackBreadth, &RenderGrid::minContentForChild, &GridTrack::usedBreadth, &GridTrack::growUsedBreadth);
- resolveContentBasedTrackSizingFunctionsForItems(direction, columnTracks, rowTracks, gridItem, &GridTrackSize::hasMaxContentMinTrackBreadth, &RenderGrid::maxContentForChild, &GridTrack::usedBreadth, &GridTrack::growUsedBreadth);
- resolveContentBasedTrackSizingFunctionsForItems(direction, columnTracks, rowTracks, gridItem, &GridTrackSize::hasMinOrMaxContentMaxTrackBreadth, &RenderGrid::minContentForChild, &GridTrack::maxBreadthIfNotInfinite, &GridTrack::growMaxBreadth);
- resolveContentBasedTrackSizingFunctionsForItems(direction, columnTracks, rowTracks, gridItem, &GridTrackSize::hasMaxContentMaxTrackBreadth, &RenderGrid::maxContentForChild, &GridTrack::maxBreadthIfNotInfinite, &GridTrack::growMaxBreadth);
+ resolveContentBasedTrackSizingFunctionsForItems(direction, sizingData, gridItem, &GridTrackSize::hasMinOrMaxContentMinTrackBreadth, &RenderGrid::minContentForChild, &GridTrack::usedBreadth, &GridTrack::growUsedBreadth);
+ resolveContentBasedTrackSizingFunctionsForItems(direction, sizingData, gridItem, &GridTrackSize::hasMaxContentMinTrackBreadth, &RenderGrid::maxContentForChild, &GridTrack::usedBreadth, &GridTrack::growUsedBreadth);
+ resolveContentBasedTrackSizingFunctionsForItems(direction, sizingData, gridItem, &GridTrackSize::hasMinOrMaxContentMaxTrackBreadth, &RenderGrid::minContentForChild, &GridTrack::maxBreadthIfNotInfinite, &GridTrack::growMaxBreadth);
+ resolveContentBasedTrackSizingFunctionsForItems(direction, sizingData, gridItem, &GridTrackSize::hasMaxContentMaxTrackBreadth, &RenderGrid::maxContentForChild, &GridTrack::maxBreadthIfNotInfinite, &GridTrack::growMaxBreadth);
}
- GridTrack& track = (direction == ForColumns) ? columnTracks[i] : rowTracks[i];
+ GridTrack& track = (direction == ForColumns) ? sizingData.columnTracks[i] : sizingData.rowTracks[i];
if (track.m_maxBreadth == infinity)
track.m_maxBreadth = track.m_usedBreadth;
}
}
-void RenderGrid::resolveContentBasedTrackSizingFunctionsForItems(TrackSizingDirection direction, Vector<GridTrack>& columnTracks, Vector<GridTrack>& rowTracks, RenderBox* gridItem, FilterFunction filterFunction, SizingFunction sizingFunction, AccumulatorGetter trackGetter, AccumulatorGrowFunction trackGrowthFunction)
+void RenderGrid::resolveContentBasedTrackSizingFunctionsForItems(GridTrackSizingDirection direction, GridSizingData& sizingData, RenderBox* gridItem, FilterFunction filterFunction, SizingFunction sizingFunction, AccumulatorGetter trackGetter, AccumulatorGrowFunction trackGrowthFunction)
{
const GridCoordinate coordinate = cachedGridCoordinate(gridItem);
const size_t initialTrackIndex = (direction == ForColumns) ? coordinate.columns.initialPositionIndex : coordinate.rows.initialPositionIndex;
const size_t finalTrackIndex = (direction == ForColumns) ? coordinate.columns.finalPositionIndex : coordinate.rows.finalPositionIndex;
- Vector<GridTrack*> tracks;
+ sizingData.filteredTracks.shrink(0);
for (size_t trackIndex = initialTrackIndex; trackIndex <= finalTrackIndex; ++trackIndex) {
const GridTrackSize& trackSize = gridTrackSize(direction, trackIndex);
if (!(trackSize.*filterFunction)())
continue;
- GridTrack& track = (direction == ForColumns) ? columnTracks[trackIndex] : rowTracks[trackIndex];
- tracks.append(&track);
+ GridTrack& track = (direction == ForColumns) ? sizingData.columnTracks[trackIndex] : sizingData.rowTracks[trackIndex];
+ sizingData.filteredTracks.append(&track);
}
- if (tracks.isEmpty())
+ if (sizingData.filteredTracks.isEmpty())
return;
- LayoutUnit additionalBreadthSpace = (this->*sizingFunction)(gridItem, direction, columnTracks);
+ LayoutUnit additionalBreadthSpace = (this->*sizingFunction)(gridItem, direction, sizingData.columnTracks);
for (size_t trackIndexForSpace = initialTrackIndex; trackIndexForSpace <= finalTrackIndex; ++trackIndexForSpace) {
- GridTrack& track = (direction == ForColumns) ? columnTracks[trackIndexForSpace] : rowTracks[trackIndexForSpace];
+ GridTrack& track = (direction == ForColumns) ? sizingData.columnTracks[trackIndexForSpace] : sizingData.rowTracks[trackIndexForSpace];
additionalBreadthSpace -= (track.*trackGetter)();
}
// FIXME: We should pass different values for |tracksForGrowthAboveMaxBreadth|.
- distributeSpaceToTracks(tracks, &tracks, trackGetter, trackGrowthFunction, additionalBreadthSpace);
+ distributeSpaceToTracks(sizingData.filteredTracks, &sizingData.filteredTracks, trackGetter, trackGrowthFunction, sizingData, additionalBreadthSpace);
}
static bool sortByGridTrackGrowthPotential(const GridTrack* track1, const GridTrack* track2)
@@ -618,41 +606,44 @@ static bool sortByGridTrackGrowthPotential(const GridTrack* track1, const GridTr
return (track1->m_maxBreadth - track1->m_usedBreadth) < (track2->m_maxBreadth - track2->m_usedBreadth);
}
-void RenderGrid::distributeSpaceToTracks(Vector<GridTrack*>& tracks, Vector<GridTrack*>* tracksForGrowthAboveMaxBreadth, AccumulatorGetter trackGetter, AccumulatorGrowFunction trackGrowthFunction, LayoutUnit& availableLogicalSpace)
+void RenderGrid::distributeSpaceToTracks(Vector<GridTrack*>& tracks, Vector<GridTrack*>* tracksForGrowthAboveMaxBreadth, AccumulatorGetter trackGetter, AccumulatorGrowFunction trackGrowthFunction, GridSizingData& sizingData, LayoutUnit& availableLogicalSpace)
{
std::sort(tracks.begin(), tracks.end(), sortByGridTrackGrowthPotential);
size_t tracksSize = tracks.size();
- Vector<LayoutUnit> updatedTrackBreadths(tracksSize);
+ sizingData.distributeTrackVector.resize(tracksSize);
for (size_t i = 0; i < tracksSize; ++i) {
GridTrack& track = *tracks[i];
LayoutUnit availableLogicalSpaceShare = availableLogicalSpace / (tracksSize - i);
LayoutUnit trackBreadth = (tracks[i]->*trackGetter)();
- LayoutUnit growthShare = std::max(LayoutUnit(), std::min(availableLogicalSpaceShare, track.m_maxBreadth - trackBreadth));
+ LayoutUnit growthShare = std::min(availableLogicalSpaceShare, track.m_maxBreadth - trackBreadth);
+ sizingData.distributeTrackVector[i] = trackBreadth;
// We should never shrink any grid track or else we can't guarantee we abide by our min-sizing function.
- updatedTrackBreadths[i] = trackBreadth + growthShare;
- availableLogicalSpace -= growthShare;
+ if (growthShare > 0) {
+ sizingData.distributeTrackVector[i] += growthShare;
+ availableLogicalSpace -= growthShare;
+ }
}
if (availableLogicalSpace > 0 && tracksForGrowthAboveMaxBreadth) {
tracksSize = tracksForGrowthAboveMaxBreadth->size();
for (size_t i = 0; i < tracksSize; ++i) {
LayoutUnit growthShare = availableLogicalSpace / (tracksSize - i);
- updatedTrackBreadths[i] += growthShare;
+ sizingData.distributeTrackVector[i] += growthShare;
availableLogicalSpace -= growthShare;
}
}
for (size_t i = 0; i < tracksSize; ++i) {
- LayoutUnit growth = updatedTrackBreadths[i] - (tracks[i]->*trackGetter)();
+ LayoutUnit growth = sizingData.distributeTrackVector[i] - (tracks[i]->*trackGetter)();
if (growth >= 0)
(tracks[i]->*trackGrowthFunction)(growth);
}
}
#ifndef NDEBUG
-bool RenderGrid::tracksAreWiderThanMinTrackBreadth(TrackSizingDirection direction, const Vector<GridTrack>& tracks)
+bool RenderGrid::tracksAreWiderThanMinTrackBreadth(GridTrackSizingDirection direction, const Vector<GridTrack>& tracks)
{
for (size_t i = 0; i < tracks.size(); ++i) {
const GridTrackSize& trackSize = gridTrackSize(direction, i);
@@ -664,7 +655,7 @@ bool RenderGrid::tracksAreWiderThanMinTrackBreadth(TrackSizingDirection directio
}
#endif
-void RenderGrid::growGrid(TrackSizingDirection direction)
+void RenderGrid::growGrid(GridTrackSizingDirection direction)
{
if (direction == ForColumns) {
const size_t oldColumnSize = m_grid[0].size();
@@ -822,14 +813,14 @@ void RenderGrid::placeAutoMajorAxisItemOnGrid(RenderBox* gridItem)
insertItemIntoGrid(gridItem, rowIndex, columnIndex);
}
-RenderGrid::TrackSizingDirection RenderGrid::autoPlacementMajorAxisDirection() const
+GridTrackSizingDirection RenderGrid::autoPlacementMajorAxisDirection() const
{
GridAutoFlow flow = style()->gridAutoFlow();
ASSERT(flow != AutoFlowNone);
return (flow == AutoFlowColumn) ? ForColumns : ForRows;
}
-RenderGrid::TrackSizingDirection RenderGrid::autoPlacementMinorAxisDirection() const
+GridTrackSizingDirection RenderGrid::autoPlacementMinorAxisDirection() const
{
GridAutoFlow flow = style()->gridAutoFlow();
ASSERT(flow != AutoFlowNone);
@@ -847,14 +838,13 @@ void RenderGrid::layoutGridItems()
{
placeItemsOnGrid();
- Vector<GridTrack> columnTracks(gridColumnCount());
- Vector<GridTrack> rowTracks(gridRowCount());
- computedUsedBreadthOfGridTracks(ForColumns, columnTracks, rowTracks);
- ASSERT(tracksAreWiderThanMinTrackBreadth(ForColumns, columnTracks));
- computedUsedBreadthOfGridTracks(ForRows, columnTracks, rowTracks);
- ASSERT(tracksAreWiderThanMinTrackBreadth(ForRows, rowTracks));
+ GridSizingData sizingData(gridColumnCount(), gridRowCount());
+ computedUsedBreadthOfGridTracks(ForColumns, sizingData);
+ ASSERT(tracksAreWiderThanMinTrackBreadth(ForColumns, sizingData.columnTracks));
+ computedUsedBreadthOfGridTracks(ForRows, sizingData);
+ ASSERT(tracksAreWiderThanMinTrackBreadth(ForRows, sizingData.rowTracks));
- populateGridPositions(columnTracks, rowTracks);
+ populateGridPositions(sizingData);
for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
// Because the grid area cannot be styled, we don't need to adjust
@@ -862,11 +852,11 @@ void RenderGrid::layoutGridItems()
LayoutUnit oldOverrideContainingBlockContentLogicalWidth = child->hasOverrideContainingBlockLogicalWidth() ? child->overrideContainingBlockContentLogicalWidth() : LayoutUnit();
LayoutUnit oldOverrideContainingBlockContentLogicalHeight = child->hasOverrideContainingBlockLogicalHeight() ? child->overrideContainingBlockContentLogicalHeight() : LayoutUnit();
- LayoutUnit overrideContainingBlockContentLogicalWidth = gridAreaBreadthForChild(child, ForColumns, columnTracks);
- LayoutUnit overrideContainingBlockContentLogicalHeight = gridAreaBreadthForChild(child, ForRows, rowTracks);
+ LayoutUnit overrideContainingBlockContentLogicalWidth = gridAreaBreadthForChild(child, ForColumns, sizingData.columnTracks);
+ LayoutUnit overrideContainingBlockContentLogicalHeight = gridAreaBreadthForChild(child, ForRows, sizingData.rowTracks);
SubtreeLayoutScope layoutScope(child);
- if (oldOverrideContainingBlockContentLogicalWidth != overrideContainingBlockContentLogicalWidth || (child->hasRelativeLogicalHeight() && oldOverrideContainingBlockContentLogicalHeight != overrideContainingBlockContentLogicalHeight))
+ if (oldOverrideContainingBlockContentLogicalWidth != overrideContainingBlockContentLogicalWidth || (oldOverrideContainingBlockContentLogicalHeight != overrideContainingBlockContentLogicalHeight && child->hasRelativeLogicalHeight()))
layoutScope.setNeedsLayout(child);
child->setOverrideContainingBlockContentLogicalWidth(overrideContainingBlockContentLogicalWidth);
@@ -879,7 +869,11 @@ void RenderGrid::layoutGridItems()
// now, just size as if we were a regular child.
child->layoutIfNeeded();
- child->setLogicalLocation(findChildLogicalPosition(child, columnTracks, rowTracks));
+ child->setLogicalLocation(findChildLogicalPosition(child, sizingData));
+
+ // For correctness, we disable some painting optimizations if we have a child overflowing its grid area.
+ m_gridItemOverflowGridArea = child->logicalHeight() > overrideContainingBlockContentLogicalHeight
+ || child->logicalWidth() > overrideContainingBlockContentLogicalWidth;
// If the child moved, we have to repaint it as well as any floating/positioned
// descendants. An exception is if we need a layout. In this case, we know we're going to
@@ -888,10 +882,10 @@ void RenderGrid::layoutGridItems()
child->repaintDuringLayoutIfMoved(oldChildRect);
}
- for (size_t i = 0; i < rowTracks.size(); ++i)
- setLogicalHeight(logicalHeight() + rowTracks[i].m_usedBreadth);
+ for (size_t i = 0; i < sizingData.rowTracks.size(); ++i)
+ setLogicalHeight(logicalHeight() + sizingData.rowTracks[i].m_usedBreadth);
- // FIXME: We should handle min / max logical height.
+ // Min / max logical height is handled by the call to updateLogicalHeight in layoutBlock.
setLogicalHeight(logicalHeight() + borderAndPaddingLogicalHeight());
}
@@ -902,14 +896,14 @@ GridCoordinate RenderGrid::cachedGridCoordinate(const RenderBox* gridItem) const
return m_gridItemCoordinate.get(gridItem);
}
-GridSpan RenderGrid::resolveGridPositionsFromAutoPlacementPosition(const RenderBox*, TrackSizingDirection, size_t initialPosition) const
+GridSpan RenderGrid::resolveGridPositionsFromAutoPlacementPosition(const RenderBox*, GridTrackSizingDirection, size_t initialPosition) const
{
// FIXME: We don't support spanning with auto positions yet. Once we do, this is wrong. Also we should make
// sure the grid can accomodate the new item as we only grow 1 position in a given direction.
return GridSpan(initialPosition, initialPosition);
}
-PassOwnPtr<GridSpan> RenderGrid::resolveGridPositionsFromStyle(const RenderBox* gridItem, TrackSizingDirection direction) const
+PassOwnPtr<GridSpan> RenderGrid::resolveGridPositionsFromStyle(const RenderBox* gridItem, GridTrackSizingDirection direction) const
{
const GridPosition& initialPosition = (direction == ForColumns) ? gridItem->style()->gridColumnStart() : gridItem->style()->gridRowStart();
const GridPositionSide initialPositionSide = (direction == ForColumns) ? ColumnStartSide : RowStartSide;
@@ -949,20 +943,6 @@ PassOwnPtr<GridSpan> RenderGrid::resolveGridPositionsFromStyle(const RenderBox*
return adoptPtr(new GridSpan(resolvedInitialPosition, resolvedFinalPosition));
}
-inline static size_t adjustGridPositionForAfterEndSide(size_t resolvedPosition)
-{
- return resolvedPosition ? resolvedPosition - 1 : 0;
-}
-
-static size_t adjustGridPositionForSide(size_t resolvedPosition, GridPositionSide side)
-{
- // An item finishing on the N-th line belongs to the N-1-th cell.
- if (side == ColumnEndSide || side == RowEndSide)
- return adjustGridPositionForAfterEndSide(resolvedPosition);
-
- return resolvedPosition;
-}
-
size_t RenderGrid::resolveNamedGridLinePositionFromStyle(const GridPosition& position, GridPositionSide side) const
{
ASSERT(!position.namedGridLine().isNull());
@@ -973,7 +953,7 @@ size_t RenderGrid::resolveNamedGridLinePositionFromStyle(const GridPosition& pos
if (position.isPositive())
return 0;
const size_t lastLine = explicitGridSizeForSide(side);
- return adjustGridPositionForSide(lastLine, side);
+ return GridPosition::adjustGridPositionForSide(lastLine, side);
}
size_t namedGridLineIndex;
@@ -981,7 +961,7 @@ size_t RenderGrid::resolveNamedGridLinePositionFromStyle(const GridPosition& pos
namedGridLineIndex = std::min<size_t>(position.integerPosition(), it->value.size()) - 1;
else
namedGridLineIndex = std::max<int>(it->value.size() - abs(position.integerPosition()), 0);
- return adjustGridPositionForSide(it->value[namedGridLineIndex], side);
+ return GridPosition::adjustGridPositionForSide(it->value[namedGridLineIndex], side);
}
size_t RenderGrid::resolveGridPositionFromStyle(const GridPosition& position, GridPositionSide side) const
@@ -995,7 +975,7 @@ size_t RenderGrid::resolveGridPositionFromStyle(const GridPosition& position, Gr
// Handle <integer> explicit position.
if (position.isPositive())
- return adjustGridPositionForSide(position.integerPosition() - 1, side);
+ return GridPosition::adjustGridPositionForSide(position.integerPosition() - 1, side);
size_t resolvedPosition = abs(position.integerPosition()) - 1;
const size_t endOfTrack = explicitGridSizeForSide(side);
@@ -1004,13 +984,13 @@ size_t RenderGrid::resolveGridPositionFromStyle(const GridPosition& position, Gr
if (endOfTrack < resolvedPosition)
return 0;
- return adjustGridPositionForSide(endOfTrack - resolvedPosition, side);
+ return GridPosition::adjustGridPositionForSide(endOfTrack - resolvedPosition, side);
}
case NamedGridAreaPosition:
{
NamedGridAreaMap::const_iterator it = style()->namedGridArea().find(position.namedGridLine());
// Unknown grid area should have been computed to 'auto' by now.
- ASSERT(it != style()->namedGridArea().end());
+ ASSERT_WITH_SECURITY_IMPLICATION(it != style()->namedGridArea().end());
const GridCoordinate& gridAreaCoordinate = it->value;
switch (side) {
case ColumnStartSide:
@@ -1048,15 +1028,7 @@ PassOwnPtr<GridSpan> RenderGrid::resolveGridPositionAgainstOppositePosition(size
return resolveNamedGridLinePositionAgainstOppositePosition(resolvedOppositePosition, position, side);
}
- // 'span 1' is contained inside a single grid track regardless of the direction.
- // That's why the CSS span value is one more than the offset we apply.
- size_t positionOffset = position.spanPosition() - 1;
- if (side == ColumnStartSide || side == RowStartSide) {
- size_t initialResolvedPosition = std::max<int>(0, resolvedOppositePosition - positionOffset);
- return GridSpan::create(initialResolvedPosition, resolvedOppositePosition);
- }
-
- return GridSpan::create(resolvedOppositePosition, resolvedOppositePosition + positionOffset);
+ return GridSpan::createWithSpanAgainstOpposite(resolvedOppositePosition, position, side);
}
PassOwnPtr<GridSpan> RenderGrid::resolveNamedGridLinePositionAgainstOppositePosition(size_t resolvedOppositePosition, const GridPosition& position, GridPositionSide side) const
@@ -1074,41 +1046,10 @@ PassOwnPtr<GridSpan> RenderGrid::resolveNamedGridLinePositionAgainstOppositePosi
if (it == gridLinesNames.end())
return GridSpan::create(resolvedOppositePosition, resolvedOppositePosition);
- if (side == RowStartSide || side == ColumnStartSide)
- return resolveBeforeStartNamedGridLinePositionAgainstOppositePosition(resolvedOppositePosition, position, it->value);
-
- return resolveAfterEndNamedGridLinePositionAgainstOppositePosition(resolvedOppositePosition, position, it->value);
-}
-
-PassOwnPtr<GridSpan> RenderGrid::resolveBeforeStartNamedGridLinePositionAgainstOppositePosition(size_t resolvedOppositePosition, const GridPosition& position, const Vector<size_t>& gridLines) const
-{
- // The grid line inequality needs to be strict (which doesn't match the after / end case) because |resolvedOppositePosition|
- // is already converted to an index in our grid representation (ie one was removed from the grid line to account for the side).
- // FIXME: This could be a binary search as |gridLines| is ordered.
- int firstLineBeforeOppositePositionIndex = gridLines.size() - 1;
- for (; firstLineBeforeOppositePositionIndex >= 0 && gridLines[firstLineBeforeOppositePositionIndex] > resolvedOppositePosition; --firstLineBeforeOppositePositionIndex) { }
-
- size_t gridLineIndex = std::max<int>(0, firstLineBeforeOppositePositionIndex - position.spanPosition() + 1);
- size_t resolvedGridLinePosition = gridLines[gridLineIndex];
- if (resolvedGridLinePosition > resolvedOppositePosition)
- resolvedGridLinePosition = resolvedOppositePosition;
- return GridSpan::create(resolvedGridLinePosition, resolvedOppositePosition);
-}
-
-PassOwnPtr<GridSpan> RenderGrid::resolveAfterEndNamedGridLinePositionAgainstOppositePosition(size_t resolvedOppositePosition, const GridPosition& position, const Vector<size_t>& gridLines) const
-{
- // FIXME: This could be a binary search as |gridLines| is ordered.
- size_t firstLineAfterOppositePositionIndex = 0;
- for (; firstLineAfterOppositePositionIndex < gridLines.size() && gridLines[firstLineAfterOppositePositionIndex] <= resolvedOppositePosition; ++firstLineAfterOppositePositionIndex) { }
-
- size_t gridLineIndex = std::min(gridLines.size() - 1, firstLineAfterOppositePositionIndex + position.spanPosition() - 1);
- size_t resolvedGridLinePosition = adjustGridPositionForAfterEndSide(gridLines[gridLineIndex]);
- if (resolvedGridLinePosition < resolvedOppositePosition)
- resolvedGridLinePosition = resolvedOppositePosition;
- return GridSpan::create(resolvedOppositePosition, resolvedGridLinePosition);
+ return GridSpan::createWithNamedSpanAgainstOpposite(resolvedOppositePosition, position, side, it->value);
}
-LayoutUnit RenderGrid::gridAreaBreadthForChild(const RenderBox* child, TrackSizingDirection direction, const Vector<GridTrack>& tracks) const
+LayoutUnit RenderGrid::gridAreaBreadthForChild(const RenderBox* child, GridTrackSizingDirection direction, const Vector<GridTrack>& tracks) const
{
const GridCoordinate& coordinate = cachedGridCoordinate(child);
const GridSpan& span = (direction == ForColumns) ? coordinate.columns : coordinate.rows;
@@ -1118,24 +1059,24 @@ LayoutUnit RenderGrid::gridAreaBreadthForChild(const RenderBox* child, TrackSizi
return gridAreaBreadth;
}
-void RenderGrid::populateGridPositions(const Vector<GridTrack>& columnTracks, const Vector<GridTrack>& rowTracks)
+void RenderGrid::populateGridPositions(const GridSizingData& sizingData)
{
- m_columnPositions.resize(columnTracks.size() + 1);
+ m_columnPositions.resize(sizingData.columnTracks.size() + 1);
m_columnPositions[0] = borderAndPaddingStart();
for (size_t i = 0; i < m_columnPositions.size() - 1; ++i)
- m_columnPositions[i + 1] = m_columnPositions[i] + columnTracks[i].m_usedBreadth;
+ m_columnPositions[i + 1] = m_columnPositions[i] + sizingData.columnTracks[i].m_usedBreadth;
- m_rowPositions.resize(rowTracks.size() + 1);
+ m_rowPositions.resize(sizingData.rowTracks.size() + 1);
m_rowPositions[0] = borderAndPaddingBefore();
for (size_t i = 0; i < m_rowPositions.size() - 1; ++i)
- m_rowPositions[i + 1] = m_rowPositions[i] + rowTracks[i].m_usedBreadth;
+ m_rowPositions[i + 1] = m_rowPositions[i] + sizingData.rowTracks[i].m_usedBreadth;
}
-LayoutPoint RenderGrid::findChildLogicalPosition(RenderBox* child, const Vector<GridTrack>& columnTracks, const Vector<GridTrack>& rowTracks)
+LayoutPoint RenderGrid::findChildLogicalPosition(RenderBox* child, const GridSizingData& sizingData)
{
const GridCoordinate& coordinate = cachedGridCoordinate(child);
- ASSERT(coordinate.columns.initialPositionIndex < columnTracks.size());
- ASSERT(coordinate.rows.initialPositionIndex < rowTracks.size());
+ ASSERT(coordinate.columns.initialPositionIndex < sizingData.columnTracks.size());
+ ASSERT(coordinate.rows.initialPositionIndex < sizingData.rowTracks.size());
// The grid items should be inside the grid container's border box, that's why they need to be shifted.
return LayoutPoint(m_columnPositions[coordinate.columns.initialPositionIndex] + marginStartForChild(child), m_rowPositions[coordinate.rows.initialPositionIndex] + marginBeforeForChild(child));
@@ -1154,10 +1095,21 @@ static GridSpan dirtiedGridAreas(const Vector<LayoutUnit>& coordinates, LayoutUn
return GridSpan(startGridAreaIndex, endGridAreaIndex);
}
+void RenderGrid::paintChildrenSlowCase(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
+{
+ for (RenderBox* child = m_orderIterator.first(); child; child = m_orderIterator.next())
+ paintChild(child, paintInfo, paintOffset);
+}
+
void RenderGrid::paintChildren(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
{
ASSERT_WITH_SECURITY_IMPLICATION(!gridIsDirty());
+ if (m_gridItemOverflowGridArea) {
+ paintChildrenSlowCase(paintInfo, paintOffset);
+ return;
+ }
+
LayoutRect localRepaintRect = paintInfo.rect;
localRepaintRect.moveBy(-paintOffset);
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderGrid.h b/chromium/third_party/WebKit/Source/core/rendering/RenderGrid.h
index b3956718a6a..f8a4de326f5 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderGrid.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderGrid.h
@@ -31,15 +31,13 @@
namespace WebCore {
-class GridCoordinate;
-class GridSpan;
+struct GridCoordinate;
+struct GridSpan;
class GridTrack;
-enum GridPositionSide {
- ColumnStartSide,
- ColumnEndSide,
- RowStartSide,
- RowEndSide
+enum GridTrackSizingDirection {
+ ForColumns,
+ ForRows
};
class RenderGrid FINAL : public RenderBlock {
@@ -56,6 +54,9 @@ public:
void dirtyGrid();
+ const Vector<LayoutUnit>& columnPositions() const { return m_columnPositions; }
+ const Vector<LayoutUnit>& rowPositions() const { return m_rowPositions; }
+
private:
virtual bool isRenderGrid() const OVERRIDE { return true; }
virtual void computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const OVERRIDE;
@@ -69,17 +70,16 @@ private:
bool explicitGridDidResize(const RenderStyle*) const;
bool namedGridLinesDefinitionDidChange(const RenderStyle*) const;
- LayoutUnit computePreferredTrackWidth(const GridLength&, size_t) const;
-
class GridIterator;
- enum TrackSizingDirection { ForColumns, ForRows };
- void computedUsedBreadthOfGridTracks(TrackSizingDirection, Vector<GridTrack>& columnTracks, Vector<GridTrack>& rowTracks);
- LayoutUnit computeUsedBreadthOfMinLength(TrackSizingDirection, const GridLength&) const;
- LayoutUnit computeUsedBreadthOfMaxLength(TrackSizingDirection, const GridLength&, LayoutUnit usedBreadth) const;
- LayoutUnit computeUsedBreadthOfSpecifiedLength(TrackSizingDirection, const Length&) const;
- void resolveContentBasedTrackSizingFunctions(TrackSizingDirection, Vector<GridTrack>& columnTracks, Vector<GridTrack>& rowTracks, const Vector<size_t>&, LayoutUnit& availableLogicalSpace);
-
- void growGrid(TrackSizingDirection);
+ struct GridSizingData;
+ void computedUsedBreadthOfGridTracks(GridTrackSizingDirection, GridSizingData&);
+ void computedUsedBreadthOfGridTracks(GridTrackSizingDirection, GridSizingData&, LayoutUnit& availableLogicalSpace);
+ LayoutUnit computeUsedBreadthOfMinLength(GridTrackSizingDirection, const GridLength&) const;
+ LayoutUnit computeUsedBreadthOfMaxLength(GridTrackSizingDirection, const GridLength&, LayoutUnit usedBreadth) const;
+ LayoutUnit computeUsedBreadthOfSpecifiedLength(GridTrackSizingDirection, const Length&) const;
+ void resolveContentBasedTrackSizingFunctions(GridTrackSizingDirection, GridSizingData&, LayoutUnit& availableLogicalSpace);
+
+ void growGrid(GridTrackSizingDirection);
void insertItemIntoGrid(RenderBox*, size_t rowTrack, size_t columnTrack);
void insertItemIntoGrid(RenderBox*, const GridCoordinate&);
void placeItemsOnGrid();
@@ -87,36 +87,36 @@ private:
void placeSpecifiedMajorAxisItemsOnGrid(const Vector<RenderBox*>&);
void placeAutoMajorAxisItemsOnGrid(const Vector<RenderBox*>&);
void placeAutoMajorAxisItemOnGrid(RenderBox*);
- TrackSizingDirection autoPlacementMajorAxisDirection() const;
- TrackSizingDirection autoPlacementMinorAxisDirection() const;
+ GridTrackSizingDirection autoPlacementMajorAxisDirection() const;
+ GridTrackSizingDirection autoPlacementMinorAxisDirection() const;
void layoutGridItems();
- void populateGridPositions(const Vector<GridTrack>& columnTracks, const Vector<GridTrack>& rowTracks);
+ void populateGridPositions(const GridSizingData&);
virtual bool supportsPartialLayout() const OVERRIDE { return false; }
- typedef LayoutUnit (RenderGrid::* SizingFunction)(RenderBox*, TrackSizingDirection, Vector<GridTrack>&);
+ typedef LayoutUnit (RenderGrid::* SizingFunction)(RenderBox*, GridTrackSizingDirection, Vector<GridTrack>&);
typedef LayoutUnit (GridTrack::* AccumulatorGetter)() const;
typedef void (GridTrack::* AccumulatorGrowFunction)(LayoutUnit);
typedef bool (GridTrackSize::* FilterFunction)() const;
- void resolveContentBasedTrackSizingFunctionsForItems(TrackSizingDirection, Vector<GridTrack>& columnTracks, Vector<GridTrack>& rowTracks, RenderBox*, FilterFunction, SizingFunction, AccumulatorGetter, AccumulatorGrowFunction);
- void distributeSpaceToTracks(Vector<GridTrack*>&, Vector<GridTrack*>* tracksForGrowthAboveMaxBreadth, AccumulatorGetter, AccumulatorGrowFunction, LayoutUnit& availableLogicalSpace);
+ void resolveContentBasedTrackSizingFunctionsForItems(GridTrackSizingDirection, GridSizingData&, RenderBox*, FilterFunction, SizingFunction, AccumulatorGetter, AccumulatorGrowFunction);
+ void distributeSpaceToTracks(Vector<GridTrack*>&, Vector<GridTrack*>* tracksForGrowthAboveMaxBreadth, AccumulatorGetter, AccumulatorGrowFunction, GridSizingData&, LayoutUnit& availableLogicalSpace);
- double computeNormalizedFractionBreadth(Vector<GridTrack>&, TrackSizingDirection, LayoutUnit availableLogicalSpace) const;
+ double computeNormalizedFractionBreadth(Vector<GridTrack>&, GridTrackSizingDirection, LayoutUnit availableLogicalSpace) const;
- const GridTrackSize& gridTrackSize(TrackSizingDirection, size_t) const;
+ const GridTrackSize& gridTrackSize(GridTrackSizingDirection, size_t) const;
size_t explicitGridColumnCount() const;
size_t explicitGridRowCount() const;
size_t explicitGridSizeForSide(GridPositionSide) const;
LayoutUnit logicalContentHeightForChild(RenderBox*, Vector<GridTrack>&);
- LayoutUnit minContentForChild(RenderBox*, TrackSizingDirection, Vector<GridTrack>& columnTracks);
- LayoutUnit maxContentForChild(RenderBox*, TrackSizingDirection, Vector<GridTrack>& columnTracks);
- LayoutPoint findChildLogicalPosition(RenderBox*, const Vector<GridTrack>& columnTracks, const Vector<GridTrack>& rowTracks);
+ LayoutUnit minContentForChild(RenderBox*, GridTrackSizingDirection, Vector<GridTrack>& columnTracks);
+ LayoutUnit maxContentForChild(RenderBox*, GridTrackSizingDirection, Vector<GridTrack>& columnTracks);
+ LayoutPoint findChildLogicalPosition(RenderBox*, const GridSizingData&);
GridCoordinate cachedGridCoordinate(const RenderBox*) const;
- GridSpan resolveGridPositionsFromAutoPlacementPosition(const RenderBox*, TrackSizingDirection, size_t) const;
- PassOwnPtr<GridSpan> resolveGridPositionsFromStyle(const RenderBox*, TrackSizingDirection) const;
+ GridSpan resolveGridPositionsFromAutoPlacementPosition(const RenderBox*, GridTrackSizingDirection, size_t) const;
+ PassOwnPtr<GridSpan> resolveGridPositionsFromStyle(const RenderBox*, GridTrackSizingDirection) const;
size_t resolveNamedGridLinePositionFromStyle(const GridPosition&, GridPositionSide) const;
size_t resolveGridPositionFromStyle(const GridPosition&, GridPositionSide) const;
PassOwnPtr<GridSpan> resolveGridPositionAgainstOppositePosition(size_t resolvedOppositePosition, const GridPosition&, GridPositionSide) const;
@@ -124,14 +124,15 @@ private:
PassOwnPtr<GridSpan> resolveBeforeStartNamedGridLinePositionAgainstOppositePosition(size_t resolvedOppositePosition, const GridPosition&, const Vector<size_t>&) const;
PassOwnPtr<GridSpan> resolveAfterEndNamedGridLinePositionAgainstOppositePosition(size_t resolvedOppositePosition, const GridPosition&, const Vector<size_t>&) const;
- LayoutUnit gridAreaBreadthForChild(const RenderBox* child, TrackSizingDirection, const Vector<GridTrack>&) const;
+ LayoutUnit gridAreaBreadthForChild(const RenderBox* child, GridTrackSizingDirection, const Vector<GridTrack>&) const;
virtual void paintChildren(PaintInfo&, const LayoutPoint&) OVERRIDE FINAL;
+ void paintChildrenSlowCase(PaintInfo&, const LayoutPoint&);
bool gridIsDirty() const { return m_gridIsDirty; }
#ifndef NDEBUG
- bool tracksAreWiderThanMinTrackBreadth(TrackSizingDirection, const Vector<GridTrack>&);
+ bool tracksAreWiderThanMinTrackBreadth(GridTrackSizingDirection, const Vector<GridTrack>&);
#endif
size_t gridColumnCount() const
@@ -153,22 +154,10 @@ private:
Vector<LayoutUnit> m_columnPositions;
HashMap<const RenderBox*, GridCoordinate> m_gridItemCoordinate;
OrderIterator m_orderIterator;
+ bool m_gridItemOverflowGridArea;
};
-inline RenderGrid* toRenderGrid(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isRenderGrid());
- return static_cast<RenderGrid*>(object);
-}
-
-inline const RenderGrid* toRenderGrid(const RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isRenderGrid());
- return static_cast<const RenderGrid*>(object);
-}
-
-// Catch unneeded cast.
-void toRenderGrid(const RenderGrid*);
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderGrid, isRenderGrid());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderHTMLCanvas.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderHTMLCanvas.cpp
index cf8f519a6ce..96a06bbb5fd 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderHTMLCanvas.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderHTMLCanvas.cpp
@@ -28,8 +28,8 @@
#include "core/html/HTMLCanvasElement.h"
#include "core/html/canvas/CanvasRenderingContext.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameView.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
#include "core/page/Page.h"
#include "core/rendering/PaintInfo.h"
#include "core/rendering/RenderView.h"
@@ -69,13 +69,6 @@ void RenderHTMLCanvas::paintReplaced(PaintInfo& paintInfo, const LayoutPoint& pa
paintInfo.context->clip(pixelSnappedIntRect(contentRect));
}
- if (Frame* frame = this->frame()) {
- if (Page* page = frame->page()) {
- if (paintInfo.phase == PaintPhaseForeground)
- page->addRelevantRepaintedObject(this, intersection(paintRect, contentRect));
- }
- }
-
bool useLowQualityScale = style()->imageRendering() == ImageRenderingOptimizeContrast;
toHTMLCanvasElement(node())->paint(context, paintRect, useLowQualityScale);
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderHTMLCanvas.h b/chromium/third_party/WebKit/Source/core/rendering/RenderHTMLCanvas.h
index 100482a5f65..6cdaf64a1da 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderHTMLCanvas.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderHTMLCanvas.h
@@ -47,14 +47,7 @@ private:
virtual void intrinsicSizeChanged() { canvasSizeChanged(); }
};
-inline RenderHTMLCanvas* toRenderHTMLCanvas(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isCanvas());
- return static_cast<RenderHTMLCanvas*>(object);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toRenderHTMLCanvas(const RenderHTMLCanvas*);
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderHTMLCanvas, isCanvas());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderIFrame.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderIFrame.cpp
index c6328703efd..85016ccc523 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderIFrame.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderIFrame.cpp
@@ -28,8 +28,9 @@
#include "HTMLNames.h"
#include "core/html/HTMLIFrameElement.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameView.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
+#include "core/rendering/LayoutRectRecorder.h"
#include "core/rendering/RenderView.h"
namespace WebCore {
@@ -123,6 +124,7 @@ void RenderIFrame::layout()
{
ASSERT(needsLayout());
+ LayoutRectRecorder recorder(*this);
if (isSeamless()) {
layoutSeamlessly();
// Do not return so as to share the layer and overflow updates below.
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderIFrame.h b/chromium/third_party/WebKit/Source/core/rendering/RenderIFrame.h
index b005572999f..e8a6197c91d 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderIFrame.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderIFrame.h
@@ -58,21 +58,7 @@ private:
RenderView* contentRootRenderer() const;
};
-inline RenderIFrame* toRenderIFrame(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isRenderIFrame());
- return static_cast<RenderIFrame*>(object);
-}
-
-inline const RenderIFrame* toRenderIFrame(const RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isRenderIFrame());
- return static_cast<const RenderIFrame*>(object);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toRenderIFrame(const RenderIFrame*);
-
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderIFrame, isRenderIFrame());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderImage.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderImage.cpp
index a11e51c40bd..f2db1e3a3a6 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderImage.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderImage.cpp
@@ -31,22 +31,23 @@
#include "HTMLNames.h"
#include "core/editing/FrameSelection.h"
#include "core/fetch/ImageResource.h"
+#include "core/fetch/ResourceLoadPriorityOptimizer.h"
+#include "core/fetch/ResourceLoader.h"
#include "core/html/HTMLAreaElement.h"
#include "core/html/HTMLImageElement.h"
#include "core/html/HTMLInputElement.h"
#include "core/html/HTMLMapElement.h"
#include "core/inspector/InspectorInstrumentation.h"
-#include "core/page/Frame.h"
-#include "core/page/Page.h"
-#include "core/platform/graphics/Font.h"
-#include "core/platform/graphics/FontCache.h"
-#include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/graphics/GraphicsContextStateSaver.h"
+#include "core/frame/Frame.h"
#include "core/rendering/HitTestResult.h"
+#include "core/rendering/LayoutRectRecorder.h"
#include "core/rendering/PaintInfo.h"
#include "core/rendering/RenderView.h"
#include "core/svg/graphics/SVGImage.h"
-#include "wtf/UnusedParam.h"
+#include "platform/fonts/Font.h"
+#include "platform/fonts/FontCache.h"
+#include "platform/graphics/GraphicsContext.h"
+#include "platform/graphics/GraphicsContextStateSaver.h"
using namespace std;
@@ -59,6 +60,7 @@ RenderImage::RenderImage(Element* element)
, m_needsToSetSizeForAltText(false)
, m_didIncrementVisuallyNonEmptyPixelCount(false)
, m_isGeneratedContent(false)
+ , m_imageDevicePixelRatio(1.0f)
{
updateAltText();
}
@@ -128,7 +130,7 @@ bool RenderImage::setImageSizeForAltText(ImageResource* newImage /* = 0 */)
FontCachePurgePreventer fontCachePurgePreventer;
const Font& font = style()->font();
- IntSize paddedTextSize(paddingWidth + min(ceilf(font.width(RenderBlock::constructTextRun(this, font, m_altText, style()))), maxAltTextWidth), paddingHeight + min(font.fontMetrics().height(), maxAltTextHeight));
+ IntSize paddedTextSize(paddingWidth + min(ceilf(font.width(RenderBlockFlow::constructTextRun(this, font, m_altText, style()))), maxAltTextWidth), paddingHeight + min(font.fontMetrics().height(), maxAltTextHeight));
imageSize = imageSize.expandedTo(paddedTextSize);
}
@@ -163,6 +165,11 @@ void RenderImage::imageChanged(WrappedImagePtr newImage, const IntRect* rect)
if (newImage != m_imageResource->imagePtr())
return;
+ // Per the spec, we let the server-sent header override srcset/other sources of dpr.
+ // https://github.com/igrigorik/http-client-hints/blob/master/draft-grigorik-http-client-hints-01.txt#L255
+ if (m_imageResource->cachedImage() && m_imageResource->cachedImage()->hasDevicePixelRatioHeaderValue())
+ m_imageDevicePixelRatio = 1 / m_imageResource->cachedImage()->devicePixelRatioHeaderValue();
+
if (!m_didIncrementVisuallyNonEmptyPixelCount) {
// At a zoom level of 1 the image is guaranteed to have an integer size.
view()->frameView()->incrementVisuallyNonEmptyPixelCount(flooredIntSize(m_imageResource->imageSize(1.0f)));
@@ -302,17 +309,10 @@ void RenderImage::paintReplaced(PaintInfo& paintInfo, const LayoutPoint& paintOf
GraphicsContext* context = paintInfo.context;
- Page* page = 0;
- if (Frame* frame = this->frame())
- page = frame->page();
-
if (!m_imageResource->hasImage() || m_imageResource->errorOccurred()) {
if (paintInfo.phase == PaintPhaseSelection)
return;
- if (page && paintInfo.phase == PaintPhaseForeground)
- page->addRelevantUnpaintedObject(this, visualOverflowRect());
-
if (cWidth > 2 && cHeight > 2) {
const int borderWidth = 1;
@@ -351,7 +351,6 @@ void RenderImage::paintReplaced(PaintInfo& paintInfo, const LayoutPoint& paintOf
}
if (!m_altText.isEmpty()) {
- String text = document().displayStringModifiedByEncoding(m_altText);
const Font& font = style()->font();
const FontMetrics& fontMetrics = font.fontMetrics();
LayoutUnit ascent = fontMetrics.ascent();
@@ -361,7 +360,7 @@ void RenderImage::paintReplaced(PaintInfo& paintInfo, const LayoutPoint& paintOf
// Only draw the alt text if it'll fit within the content box,
// and only if it fits above the error image.
- TextRun textRun = RenderBlock::constructTextRun(this, font, text, style());
+ TextRun textRun = RenderBlockFlow::constructTextRun(this, font, m_altText, style(), TextRun::AllowTrailingExpansion | TextRun::ForbidLeadingExpansion, DefaultTextRunFlags | RespectDirection);
LayoutUnit textWidth = font.width(textRun);
TextRunPaintInfo textRunPaintInfo(textRun);
textRunPaintInfo.bounds = FloatRect(textRectOrigin, FloatSize(textWidth, fontMetrics.height()));
@@ -375,11 +374,8 @@ void RenderImage::paintReplaced(PaintInfo& paintInfo, const LayoutPoint& paintOf
}
} else if (m_imageResource->hasImage() && cWidth > 0 && cHeight > 0) {
RefPtr<Image> img = m_imageResource->image(cWidth, cHeight);
- if (!img || img->isNull()) {
- if (page && paintInfo.phase == PaintPhaseForeground)
- page->addRelevantUnpaintedObject(this, visualOverflowRect());
+ if (!img || img->isNull())
return;
- }
LayoutRect contentRect = contentBoxRect();
contentRect.moveBy(paintOffset);
@@ -393,16 +389,6 @@ void RenderImage::paintReplaced(PaintInfo& paintInfo, const LayoutPoint& paintOf
paintIntoRect(context, paintRect);
- if (cachedImage() && page && paintInfo.phase == PaintPhaseForeground) {
- // For now, count images as unpainted if they are still progressively loading. We may want
- // to refine this in the future to account for the portion of the image that has painted.
- LayoutRect visibleRect = intersection(paintRect, contentRect);
- if (cachedImage()->isLoading())
- page->addRelevantUnpaintedObject(this, visibleRect);
- else
- page->addRelevantRepaintedObject(this, visibleRect);
- }
-
if (clip)
context->restore();
}
@@ -501,9 +487,8 @@ bool RenderImage::boxShadowShouldBeAppliedToBackground(BackgroundBleedAvoidance
return !const_cast<RenderImage*>(this)->backgroundIsKnownToBeObscured();
}
-bool RenderImage::foregroundIsKnownToBeOpaqueInRect(const LayoutRect& localRect, unsigned maxDepthToTest) const
+bool RenderImage::foregroundIsKnownToBeOpaqueInRect(const LayoutRect& localRect, unsigned) const
{
- UNUSED_PARAM(maxDepthToTest);
if (!m_imageResource->hasImage() || m_imageResource->errorOccurred())
return false;
if (m_imageResource->cachedImage() && !m_imageResource->cachedImage()->isLoaded())
@@ -583,10 +568,45 @@ void RenderImage::updateAltText()
void RenderImage::layout()
{
+ LayoutRectRecorder recorder(*this);
RenderReplaced::layout();
updateInnerContentRect();
}
+void RenderImage::didLayout(ResourceLoadPriorityOptimizer& optimizer)
+{
+ RenderReplaced::didLayout(optimizer);
+ updateImageLoadingPriority(optimizer);
+}
+
+void RenderImage::didScroll(ResourceLoadPriorityOptimizer& optimizer)
+{
+ RenderReplaced::didScroll(optimizer);
+ updateImageLoadingPriority(optimizer);
+}
+
+void RenderImage::updateImageLoadingPriority(ResourceLoadPriorityOptimizer& optimizer)
+{
+ if (!m_imageResource || !m_imageResource->cachedImage() || m_imageResource->cachedImage()->isLoaded())
+ return;
+
+ LayoutRect viewBounds = viewRect();
+ LayoutRect objectBounds = absoluteContentBox();
+
+ // The object bounds might be empty right now, so intersects will fail since it doesn't deal
+ // with empty rects. Use LayoutRect::contains in that case.
+ bool isVisible;
+ if (!objectBounds.isEmpty())
+ isVisible = viewBounds.intersects(objectBounds);
+ else
+ isVisible = viewBounds.contains(objectBounds);
+
+ ResourceLoadPriorityOptimizer::VisibilityStatus status = isVisible ?
+ ResourceLoadPriorityOptimizer::Visible : ResourceLoadPriorityOptimizer::NotVisible;
+
+ optimizer.notifyImageResourceVisibility(m_imageResource->cachedImage(), status);
+}
+
void RenderImage::computeIntrinsicRatioInformation(FloatSize& intrinsicSize, double& intrinsicRatio, bool& isPercentageIntrinsicSize) const
{
RenderReplaced::computeIntrinsicRatioInformation(intrinsicSize, intrinsicRatio, isPercentageIntrinsicSize);
@@ -601,7 +621,8 @@ void RenderImage::computeIntrinsicRatioInformation(FloatSize& intrinsicSize, dou
}
}
// Don't compute an intrinsic ratio to preserve historical WebKit behavior if we're painting alt text and/or a broken image.
- if (m_imageResource && m_imageResource->errorOccurred()) {
+ // Video is excluded from this behavior because video elements have a default aspect ratio that a failed poster image load should not override.
+ if (m_imageResource && m_imageResource->errorOccurred() && !isVideo()) {
intrinsicRatio = 1;
return;
}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderImage.h b/chromium/third_party/WebKit/Source/core/rendering/RenderImage.h
index 1204ea5ed79..d7e67f0c7e3 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderImage.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderImage.h
@@ -61,6 +61,9 @@ public:
String altText() const { return m_altText; }
+ inline void setImageDevicePixelRatio(float factor) { m_imageDevicePixelRatio = factor; }
+ float imageDevicePixelRatio() const { return m_imageDevicePixelRatio; }
+
protected:
virtual bool needsPreferredWidthsRecalculation() const OVERRIDE FINAL;
virtual RenderBox* embeddedContentBox() const OVERRIDE FINAL;
@@ -73,6 +76,9 @@ protected:
void paintIntoRect(GraphicsContext*, const LayoutRect&);
virtual void paint(PaintInfo&, const LayoutPoint&) OVERRIDE FINAL;
virtual void layout();
+ virtual void didLayout(ResourceLoadPriorityOptimizer&);
+ virtual void didScroll(ResourceLoadPriorityOptimizer&);
+ void updateImageLoadingPriority(ResourceLoadPriorityOptimizer&);
virtual void intrinsicSizeChanged()
{
@@ -112,24 +118,12 @@ private:
bool m_needsToSetSizeForAltText;
bool m_didIncrementVisuallyNonEmptyPixelCount;
bool m_isGeneratedContent;
+ float m_imageDevicePixelRatio;
friend class RenderImageScaleObserver;
};
-inline RenderImage* toRenderImage(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isRenderImage());
- return static_cast<RenderImage*>(object);
-}
-
-inline const RenderImage* toRenderImage(const RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isRenderImage());
- return static_cast<const RenderImage*>(object);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toRenderImage(const RenderImage*);
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderImage, isRenderImage());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderImageResource.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderImageResource.cpp
index 61301870230..12ab7231776 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderImageResource.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderImageResource.cpp
@@ -28,8 +28,7 @@
#include "config.h"
#include "core/rendering/RenderImageResource.h"
-#include "core/fetch/ImageResource.h"
-#include "core/platform/graphics/Image.h"
+#include "core/rendering/RenderImage.h"
#include "core/rendering/RenderObject.h"
namespace WebCore {
@@ -103,4 +102,14 @@ Image* RenderImageResource::nullImage()
return Image::nullImage();
}
+LayoutSize RenderImageResource::getImageSize(float multiplier, ImageResource::SizeType type) const
+{
+ if (!m_cachedImage)
+ return LayoutSize();
+ LayoutSize size = m_cachedImage->imageSizeForRenderer(m_renderer, multiplier, type);
+ if (m_renderer && m_renderer->isRenderImage())
+ size.scale(toRenderImage(m_renderer)->imageDevicePixelRatio());
+ return size;
+}
+
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderImageResource.h b/chromium/third_party/WebKit/Source/core/rendering/RenderImageResource.h
index d5d8fca6abe..cae42e2eb03 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderImageResource.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderImageResource.h
@@ -28,9 +28,9 @@
#include "core/fetch/ImageResource.h"
#include "core/fetch/ResourcePtr.h"
-#include "core/platform/graphics/Image.h"
-#include "core/platform/graphics/LayoutSize.h"
#include "core/rendering/style/StyleImage.h"
+#include "platform/geometry/LayoutSize.h"
+#include "platform/graphics/Image.h"
namespace WebCore {
@@ -63,8 +63,8 @@ public:
virtual bool imageHasRelativeWidth() const { return m_cachedImage ? m_cachedImage->imageHasRelativeWidth() : false; }
virtual bool imageHasRelativeHeight() const { return m_cachedImage ? m_cachedImage->imageHasRelativeHeight() : false; }
- virtual LayoutSize imageSize(float multiplier) const { return m_cachedImage ? m_cachedImage->imageSizeForRenderer(m_renderer, multiplier) : LayoutSize(); }
- virtual LayoutSize intrinsicSize(float multiplier) const { return m_cachedImage ? m_cachedImage->imageSizeForRenderer(m_renderer, multiplier, ImageResource::IntrinsicSize) : LayoutSize(); }
+ virtual LayoutSize imageSize(float multiplier) const { return getImageSize(multiplier, ImageResource::NormalSize); }
+ virtual LayoutSize intrinsicSize(float multiplier) const { return getImageSize(multiplier, ImageResource::IntrinsicSize); }
virtual WrappedImagePtr imagePtr() const { return m_cachedImage.get(); }
@@ -75,6 +75,7 @@ protected:
private:
static Image* nullImage();
+ LayoutSize getImageSize(float multiplier, ImageResource::SizeType) const;
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderImageResourceStyleImage.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderImageResourceStyleImage.cpp
index 9c3b03e8062..5e0fff78319 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderImageResourceStyleImage.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderImageResourceStyleImage.cpp
@@ -49,7 +49,7 @@ void RenderImageResourceStyleImage::initialize(RenderObject* renderer)
RenderImageResource::initialize(renderer);
if (m_styleImage->isImageResource())
- m_cachedImage = static_cast<StyleFetchedImage*>(m_styleImage.get())->cachedImage();
+ m_cachedImage = toStyleFetchedImage(m_styleImage)->cachedImage();
m_styleImage->addClient(m_renderer);
}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderInline.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderInline.cpp
index 0ab24231d7e..bd82486d441 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderInline.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderInline.cpp
@@ -26,11 +26,10 @@
#include "core/dom/FullscreenElementStack.h"
#include "core/page/Chrome.h"
#include "core/page/Page.h"
-#include "core/platform/graphics/FloatQuad.h"
-#include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/graphics/transforms/TransformState.h"
+#include "core/rendering/GraphicsContextAnnotator.h"
#include "core/rendering/HitTestResult.h"
#include "core/rendering/InlineTextBox.h"
+#include "core/rendering/LayoutRectRecorder.h"
#include "core/rendering/RenderBlock.h"
#include "core/rendering/RenderFlowThread.h"
#include "core/rendering/RenderFullScreen.h"
@@ -39,6 +38,9 @@
#include "core/rendering/RenderTheme.h"
#include "core/rendering/RenderView.h"
#include "core/rendering/style/StyleInheritedData.h"
+#include "platform/geometry/FloatQuad.h"
+#include "platform/geometry/TransformState.h"
+#include "platform/graphics/GraphicsContext.h"
using namespace std;
@@ -125,7 +127,8 @@ void RenderInline::updateFromStyle()
{
RenderBoxModelObject::updateFromStyle();
- setInline(true); // Needed for run-ins, since run-in is considered a block display type.
+ // FIXME: Is this still needed. Was needed for run-ins, since run-in is considered a block display type.
+ setInline(true);
// FIXME: Support transforms and reflections on inline flows someday.
setHasTransform(false);
@@ -313,7 +316,7 @@ void RenderInline::addChildIgnoringContinuation(RenderObject* newChild, RenderOb
if (RenderObject* positionedAncestor = inFlowPositionedInlineAncestor(this))
newStyle->setPosition(positionedAncestor->style()->position());
- RenderBlock* newBox = RenderBlock::createAnonymous(&document());
+ RenderBlockFlow* newBox = RenderBlockFlow::createAnonymous(&document());
newBox->setStyle(newStyle.release());
RenderBoxModelObject* oldContinuation = continuation();
setContinuation(newBox);
@@ -439,7 +442,8 @@ void RenderInline::splitFlow(RenderObject* beforeChild, RenderBlock* newBlockBox
// We can reuse this block and make it the preBlock of the next continuation.
pre = block;
pre->removePositionedObjects(0);
- pre->removeFloatingObjects();
+ if (pre->isRenderBlockFlow())
+ toRenderBlockFlow(pre)->removeFloatingObjects();
block = block->containingBlock();
} else {
// No anonymous block available for use. Make one.
@@ -511,12 +515,11 @@ void RenderInline::addChildToContinuation(RenderObject* newChild, RenderObject*
else {
// The goal here is to match up if we can, so that we can coalesce and create the
// minimal # of continuations needed for the inline.
- if (childInline == bcpInline)
+ if (childInline == bcpInline || (beforeChild && beforeChild->isInline()))
return beforeChildParent->addChildIgnoringContinuation(newChild, beforeChild);
- else if (flowInline == childInline)
+ if (flowInline == childInline)
return flow->addChildIgnoringContinuation(newChild, 0); // Just treat like an append.
- else
- return beforeChildParent->addChildIgnoringContinuation(newChild, beforeChild);
+ return beforeChildParent->addChildIgnoringContinuation(newChild, beforeChild);
}
}
@@ -749,8 +752,6 @@ const char* RenderInline::renderName() const
return "RenderInline (generated)";
if (isAnonymous())
return "RenderInline (generated)";
- if (isRunIn())
- return "RenderInline (run-in)";
return "RenderInline";
}
@@ -998,8 +999,7 @@ LayoutRect RenderInline::linesVisualOverflowBoundingBox() const
LayoutRect RenderInline::clippedOverflowRectForRepaint(const RenderLayerModelObject* repaintContainer) const
{
- // Only run-ins are allowed in here during layout.
- ASSERT(!view() || !view()->layoutStateEnabled() || isRunIn());
+ ASSERT(!view() || !view()->layoutStateEnabled() || LayoutRectRecorder::shouldRecordLayoutRects());
if (!firstLineBoxIncludingCulling() && !continuation())
return LayoutRect();
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderInline.h b/chromium/third_party/WebKit/Source/core/rendering/RenderInline.h
index 6e2e7f9ff9c..c69f0258daa 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderInline.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderInline.h
@@ -187,20 +187,7 @@ private:
bool m_alwaysCreateLineBoxes : 1;
};
-inline RenderInline* toRenderInline(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isRenderInline());
- return static_cast<RenderInline*>(object);
-}
-
-inline const RenderInline* toRenderInline(const RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isRenderInline());
- return static_cast<const RenderInline*>(object);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toRenderInline(const RenderInline*);
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderInline, isRenderInline());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderInputSpeech.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderInputSpeech.cpp
index c6e83eec16c..85134417040 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderInputSpeech.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderInputSpeech.cpp
@@ -33,9 +33,9 @@
#include "core/rendering/RenderInputSpeech.h"
#include "core/html/shadow/TextControlInnerElements.h"
-#include "core/platform/graphics/GraphicsContext.h"
#include "core/rendering/PaintInfo.h"
#include "core/rendering/RenderBox.h"
+#include "platform/graphics/GraphicsContext.h"
namespace WebCore {
@@ -82,16 +82,16 @@ bool RenderInputSpeech::paintInputFieldSpeechButton(RenderObject* object, const
// Account for the local drawing offset.
buttonRect.moveBy(rect.location());
- DEFINE_STATIC_LOCAL(RefPtr<Image>, imageStateNormal, (Image::loadPlatformResource("inputSpeech")));
- DEFINE_STATIC_LOCAL(RefPtr<Image>, imageStateRecording, (Image::loadPlatformResource("inputSpeechRecording")));
- DEFINE_STATIC_LOCAL(RefPtr<Image>, imageStateWaiting, (Image::loadPlatformResource("inputSpeechWaiting")));
+ DEFINE_STATIC_REF(Image, imageStateNormal, (Image::loadPlatformResource("inputSpeech")));
+ DEFINE_STATIC_REF(Image, imageStateRecording, (Image::loadPlatformResource("inputSpeechRecording")));
+ DEFINE_STATIC_REF(Image, imageStateWaiting, (Image::loadPlatformResource("inputSpeechWaiting")));
InputFieldSpeechButtonElement* speechButton = toInputFieldSpeechButtonElement(element);
- Image* image = imageStateNormal.get();
+ Image* image = imageStateNormal;
if (speechButton->state() == InputFieldSpeechButtonElement::Recording)
- image = imageStateRecording.get();
+ image = imageStateRecording;
else if (speechButton->state() == InputFieldSpeechButtonElement::Recognizing)
- image = imageStateWaiting.get();
+ image = imageStateWaiting;
paintInfo.context->drawImage(image, pixelSnappedIntRect(buttonRect));
return false;
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderLayer.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderLayer.cpp
index a6f510224d5..c3b8403215f 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderLayer.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderLayer.cpp
@@ -48,42 +48,19 @@
#include "HTMLNames.h"
#include "RuntimeEnabledFeatures.h"
#include "SVGNames.h"
+#include "core/animation/ActiveAnimations.h"
#include "core/css/PseudoStyleRequest.h"
#include "core/dom/Document.h"
-#include "core/dom/DocumentEventQueue.h"
#include "core/dom/shadow/ShadowRoot.h"
#include "core/html/HTMLFrameElement.h"
-#include "core/html/HTMLFrameOwnerElement.h"
-#include "core/page/EventHandler.h"
-#include "core/page/FocusController.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameView.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
#include "core/page/Page.h"
-#include "core/page/Settings.h"
-#include "core/page/UseCounter.h"
-#include "core/page/animation/AnimationController.h"
+#include "core/frame/Settings.h"
+#include "core/frame/animation/AnimationController.h"
#include "core/page/scrolling/ScrollingCoordinator.h"
-#include "core/platform/HistogramSupport.h"
-#include "core/platform/Partitions.h"
-#include "core/platform/PlatformGestureEvent.h"
-#include "core/platform/PlatformMouseEvent.h"
-#include "core/platform/ScrollAnimator.h"
-#include "core/platform/Scrollbar.h"
-#include "core/platform/ScrollbarTheme.h"
-#include "core/platform/chromium/TraceEvent.h"
-#include "core/platform/graphics/FloatPoint3D.h"
-#include "core/platform/graphics/FloatRect.h"
-#include "core/platform/graphics/GraphicsContextStateSaver.h"
-#include "core/platform/graphics/filters/ReferenceFilter.h"
-#include "core/platform/graphics/filters/SourceGraphic.h"
-#include "core/platform/graphics/filters/custom/CustomFilterGlobalContext.h"
-#include "core/platform/graphics/filters/custom/CustomFilterOperation.h"
-#include "core/platform/graphics/filters/custom/CustomFilterValidatedProgram.h"
-#include "core/platform/graphics/filters/custom/ValidatedCustomFilterOperation.h"
-#include "core/platform/graphics/transforms/ScaleTransformOperation.h"
-#include "core/platform/graphics/transforms/TransformationMatrix.h"
-#include "core/platform/graphics/transforms/TranslateTransformOperation.h"
#include "core/rendering/ColumnInfo.h"
+#include "core/rendering/CompositedLayerMapping.h"
#include "core/rendering/FilterEffectRenderer.h"
#include "core/rendering/HitTestRequest.h"
#include "core/rendering/HitTestResult.h"
@@ -91,7 +68,6 @@
#include "core/rendering/RenderFlowThread.h"
#include "core/rendering/RenderGeometryMap.h"
#include "core/rendering/RenderInline.h"
-#include "core/rendering/RenderLayerBacking.h"
#include "core/rendering/RenderLayerCompositor.h"
#include "core/rendering/RenderReplica.h"
#include "core/rendering/RenderScrollbar.h"
@@ -100,55 +76,54 @@
#include "core/rendering/RenderView.h"
#include "core/rendering/svg/ReferenceFilterBuilder.h"
#include "core/rendering/svg/RenderSVGResourceClipper.h"
+#include "platform/LengthFunctions.h"
+#include "platform/Partitions.h"
+#include "platform/TraceEvent.h"
+#include "platform/geometry/FloatPoint3D.h"
+#include "platform/geometry/FloatRect.h"
+#include "platform/graphics/GraphicsContextStateSaver.h"
+#include "platform/graphics/filters/ReferenceFilter.h"
+#include "platform/graphics/filters/SourceGraphic.h"
+#include "platform/graphics/filters/custom/CustomFilterGlobalContext.h"
+#include "platform/graphics/filters/custom/CustomFilterOperation.h"
+#include "platform/graphics/filters/custom/CustomFilterValidatedProgram.h"
+#include "platform/graphics/filters/custom/ValidatedCustomFilterOperation.h"
+#include "platform/transforms/ScaleTransformOperation.h"
+#include "platform/transforms/TransformationMatrix.h"
+#include "platform/transforms/TranslateTransformOperation.h"
+#include "public/platform/Platform.h"
#include "wtf/StdLibExtras.h"
-#include "wtf/UnusedParam.h"
#include "wtf/text/CString.h"
-#define MIN_INTERSECT_FOR_REVEAL 32
-
using namespace std;
namespace WebCore {
using namespace HTMLNames;
-const int MinimumWidthWhileResizing = 100;
-const int MinimumHeightWhileResizing = 40;
-const int ResizerControlExpandRatioForTouch = 2;
-
RenderLayer::RenderLayer(RenderLayerModelObject* renderer)
- : m_inResizeMode(false)
- , m_normalFlowListDirty(true)
- , m_hasSelfPaintingLayerDescendant(false)
+ : m_hasSelfPaintingLayerDescendant(false)
, m_hasSelfPaintingLayerDescendantDirty(false)
, m_hasOutOfFlowPositionedDescendant(false)
, m_hasOutOfFlowPositionedDescendantDirty(true)
, m_hasUnclippedDescendant(false)
, m_isUnclippedDescendant(false)
- , m_needsCompositedScrolling(false)
- , m_needsCompositedScrollingHasBeenRecorded(false)
- , m_willUseCompositedScrollingHasBeenRecorded(false)
- , m_isScrollableAreaHasBeenRecorded(false)
- , m_canBePromotedToStackingContainer(false)
- , m_canBePromotedToStackingContainerDirty(true)
, m_isRootLayer(renderer->isRenderView())
, m_usedTransparency(false)
- , m_paintingInsideReflection(false)
- , m_repaintStatus(NeedsNormalRepaint)
+ , m_childLayerHasBlendMode(false)
+ , m_childLayerHasBlendModeStatusDirty(false)
, m_visibleContentStatusDirty(true)
, m_hasVisibleContent(false)
, m_visibleDescendantStatusDirty(false)
, m_hasVisibleDescendant(false)
+ , m_hasVisibleNonLayerContent(false)
, m_isPaginated(false)
, m_3DTransformedDescendantStatusDirty(true)
, m_has3DTransformedDescendant(false)
, m_containsDirtyOverlayScrollbars(false)
-#if !ASSERT_DISABLED
- , m_layerListMutationAllowed(true)
-#endif
, m_canSkipRepaintRectsUpdateOnScroll(renderer->isTableCell())
, m_hasFilterInfo(false)
- , m_blendMode(BlendModeNormal)
+ , m_blendMode(blink::WebBlendModeNormal)
, m_renderer(renderer)
, m_parent(0)
, m_previous(0)
@@ -157,42 +132,25 @@ RenderLayer::RenderLayer(RenderLayerModelObject* renderer)
, m_last(0)
, m_staticInlinePosition(0)
, m_staticBlockPosition(0)
- , m_reflection(0)
- , m_resizer(0)
, m_enclosingPaginationLayer(0)
- , m_forceNeedsCompositedScrolling(DoNotForceCompositedScrolling)
- // FIXME: We could lazily allocate our ScrollableArea based on style properties
- // ('overflow', ...) but for now, we are always allocating it as it's safer.
- , m_scrollableArea(adoptPtr(new RenderLayerScrollableArea(this)))
-
+ , m_groupedMapping(0)
+ , m_repainter(renderer)
+ , m_clipper(renderer)
{
- m_isNormalFlowOnly = shouldBeNormalFlowOnly();
- m_isSelfPaintingLayer = shouldBeSelfPaintingLayer();
+ updateStackingNode();
- // Non-stacking containers should have empty z-order lists. As this is already the case,
- // there is no need to dirty / recompute these lists.
- m_zOrderListsDirty = isStackingContainer();
+ m_isSelfPaintingLayer = shouldBeSelfPaintingLayer();
if (!renderer->firstChild() && renderer->style()) {
m_visibleContentStatusDirty = false;
m_hasVisibleContent = renderer->style()->visibility() == VISIBLE;
}
- updateResizerAreaSet();
+ updateScrollableArea();
}
RenderLayer::~RenderLayer()
{
- if (inResizeMode() && !renderer()->documentBeingDestroyed()) {
- if (Frame* frame = renderer()->frame())
- frame->eventHandler()->resizeLayerDestroyed();
- }
-
- if (Frame* frame = renderer()->frame()) {
- if (FrameView* frameView = frame->view())
- frameView->removeResizerArea(this);
- }
-
if (!m_renderer->documentBeingDestroyed())
compositor()->removeOutOfFlowPositionedLayer(this);
@@ -201,26 +159,19 @@ RenderLayer::~RenderLayer()
scrollingCoordinator->willDestroyRenderLayer(this);
}
- if (m_reflection)
- removeReflection();
-
removeFilterInfoIfNeeded();
// Child layers will be deleted by their corresponding render objects, so
// we don't need to delete them ourselves.
- clearBacking(true);
-
- if (m_resizer)
- m_resizer->destroy();
+ clearCompositedLayerMapping(true);
}
String RenderLayer::debugName() const
{
- String name = renderer()->debugName();
- if (!isReflection())
- return name;
- return name + " (reflection)";
+ if (isReflection())
+ return m_reflectionInfo->debugName();
+ return renderer()->debugName();
}
RenderLayerCompositor* RenderLayer::compositor() const
@@ -236,8 +187,8 @@ void RenderLayer::contentChanged(ContentChangeType changeType)
if ((changeType == CanvasChanged || changeType == VideoChanged || changeType == FullScreenChanged) && compositor()->updateLayerCompositingState(this))
compositor()->setCompositingLayersNeedRebuild();
- if (m_backing)
- m_backing->contentChanged(changeType);
+ if (m_compositedLayerMapping)
+ m_compositedLayerMapping->contentChanged(changeType);
}
bool RenderLayer::canRender3DTransforms() const
@@ -247,14 +198,13 @@ bool RenderLayer::canRender3DTransforms() const
bool RenderLayer::paintsWithFilters() const
{
- // FIXME: Eventually there will be more factors than isComposited() to decide whether or not to render the filter
if (!renderer()->hasFilter())
return false;
- if (!isComposited())
+ if (compositingState() != PaintsIntoOwnBacking)
return true;
- if (!m_backing || !m_backing->canCompositeFilters())
+ if (!m_compositedLayerMapping || !m_compositedLayerMapping->canCompositeFilters())
return true;
return false;
@@ -307,7 +257,7 @@ void RenderLayer::updateLayerPositions(RenderGeometryMap* geometryMap, UpdateLay
geometryMap->pushMappingsToAncestor(this, parent());
// Clear our cached clip rect information.
- clearClipRects();
+ m_clipper.clearClipRects();
if (hasOverflowControls()) {
LayoutPoint offsetFromRoot;
@@ -318,7 +268,7 @@ void RenderLayer::updateLayerPositions(RenderGeometryMap* geometryMap, UpdateLay
// as canUseConvertToLayerCoords may be true for an ancestor layer.
convertToLayerCoords(root(), offsetFromRoot);
}
- positionOverflowControls(toIntSize(roundedIntPoint(offsetFromRoot)));
+ scrollableArea()->positionOverflowControls(toIntSize(roundedIntPoint(offsetFromRoot)));
}
updateDescendantDependentFlags();
@@ -330,43 +280,15 @@ void RenderLayer::updateLayerPositions(RenderGeometryMap* geometryMap, UpdateLay
m_enclosingPaginationLayer = 0;
}
- if (m_hasVisibleContent) {
- RenderView* view = renderer()->view();
- ASSERT(view);
- // FIXME: LayoutState does not work with RenderLayers as there is not a 1-to-1
- // mapping between them and the RenderObjects. It would be neat to enable
- // LayoutState outside the layout() phase and use it here.
- ASSERT(!view->layoutStateEnabled());
-
- RenderLayerModelObject* repaintContainer = renderer()->containerForRepaint();
- LayoutRect oldRepaintRect = m_repaintRect;
- LayoutRect oldOutlineBox = m_outlineBox;
- computeRepaintRects(repaintContainer, geometryMap);
-
- // FIXME: Should ASSERT that value calculated for m_outlineBox using the cached offset is the same
- // as the value not using the cached offset, but we can't due to https://bugs.webkit.org/show_bug.cgi?id=37048
- if (flags & CheckForRepaint) {
- if (view && !view->document().printing()) {
- if (m_repaintStatus & NeedsFullRepaint) {
- renderer()->repaintUsingContainer(repaintContainer, pixelSnappedIntRect(oldRepaintRect));
- if (m_repaintRect != oldRepaintRect)
- renderer()->repaintUsingContainer(repaintContainer, pixelSnappedIntRect(m_repaintRect));
- } else if (shouldRepaintAfterLayout())
- renderer()->repaintAfterLayoutIfNeeded(repaintContainer, oldRepaintRect, oldOutlineBox, &m_repaintRect, &m_outlineBox);
- }
- }
- } else
- clearRepaintRects();
-
- m_repaintStatus = NeedsNormalRepaint;
+ repainter().repaintAfterLayout(geometryMap, flags & CheckForRepaint);
// Go ahead and update the reflection's position and size.
- if (m_reflection)
- m_reflection->layout();
+ if (m_reflectionInfo)
+ m_reflectionInfo->reflection()->layout();
// Clear the IsCompositingUpdateRoot flag once we've found the first compositing layer in this update.
bool isUpdateRoot = (flags & IsCompositingUpdateRoot);
- if (isComposited())
+ if (hasCompositedLayerMapping())
flags &= ~IsCompositingUpdateRoot;
if (useRegionBasedColumns() && renderer()->isInFlowRenderFlowThread()) {
@@ -380,32 +302,19 @@ void RenderLayer::updateLayerPositions(RenderGeometryMap* geometryMap, UpdateLay
for (RenderLayer* child = firstChild(); child; child = child->nextSibling())
child->updateLayerPositions(geometryMap, flags);
- if ((flags & UpdateCompositingLayers) && isComposited()) {
- RenderLayerBacking::UpdateAfterLayoutFlags updateFlags = RenderLayerBacking::CompositingChildrenOnly;
+ if ((flags & UpdateCompositingLayers) && hasCompositedLayerMapping()) {
+ CompositedLayerMapping::UpdateAfterLayoutFlags updateFlags = CompositedLayerMapping::CompositingChildrenOnly;
if (flags & NeedsFullRepaintInBacking)
- updateFlags |= RenderLayerBacking::NeedsFullRepaint;
+ updateFlags |= CompositedLayerMapping::NeedsFullRepaint;
if (isUpdateRoot)
- updateFlags |= RenderLayerBacking::IsUpdateRoot;
- backing()->updateAfterLayout(updateFlags);
+ updateFlags |= CompositedLayerMapping::IsUpdateRoot;
+ compositedLayerMapping()->updateAfterLayout(updateFlags);
}
if (geometryMap)
geometryMap->popMappingsToAncestor(parent());
}
-LayoutRect RenderLayer::repaintRectIncludingNonCompositingDescendants() const
-{
- LayoutRect repaintRect = m_repaintRect;
- for (RenderLayer* child = firstChild(); child; child = child->nextSibling()) {
- // Don't include repaint rects for composited child layers; they will paint themselves and have a different origin.
- if (child->isComposited())
- continue;
-
- repaintRect.unite(child->repaintRectIncludingNonCompositingDescendants());
- }
- return repaintRect;
-}
-
void RenderLayer::setAncestorChainHasSelfPaintingLayerDescendant()
{
for (RenderLayer* layer = this; layer; layer = layer->parent()) {
@@ -473,171 +382,7 @@ bool RenderLayer::compositorDrivenAcceleratedScrollingEnabled() const
return false;
const Settings* settings = renderer()->document().settings();
- return settings && settings->isCompositorDrivenAcceleratedScrollingEnabled();
-}
-
-// Determine whether the current layer can be promoted to a stacking container.
-// We do this by computing what positive and negative z-order lists would look
-// like before and after promotion, and ensuring that proper stacking order is
-// preserved between the two sets of lists.
-void RenderLayer::updateCanBeStackingContainer()
-{
- TRACE_EVENT0("blink_rendering,comp-scroll", "RenderLayer::updateCanBeStackingContainer");
-
- if (isStackingContext() || !m_canBePromotedToStackingContainerDirty || !acceleratedCompositingForOverflowScrollEnabled())
- return;
-
- FrameView* frameView = renderer()->view()->frameView();
- if (!frameView || !frameView->containsScrollableArea(scrollableArea()))
- return;
-
- RenderLayer* ancestorStackingContext = this->ancestorStackingContext();
- if (!ancestorStackingContext)
- return;
-
- OwnPtr<Vector<RenderLayer*> > posZOrderListBeforePromote = adoptPtr(new Vector<RenderLayer*>);
- OwnPtr<Vector<RenderLayer*> > negZOrderListBeforePromote = adoptPtr(new Vector<RenderLayer*>);
- OwnPtr<Vector<RenderLayer*> > posZOrderListAfterPromote = adoptPtr(new Vector<RenderLayer*>);
- OwnPtr<Vector<RenderLayer*> > negZOrderListAfterPromote = adoptPtr(new Vector<RenderLayer*>);
-
- collectBeforePromotionZOrderList(ancestorStackingContext, posZOrderListBeforePromote, negZOrderListBeforePromote);
- collectAfterPromotionZOrderList(ancestorStackingContext, posZOrderListAfterPromote, negZOrderListAfterPromote);
-
- size_t maxIndex = std::min(posZOrderListAfterPromote->size() + negZOrderListAfterPromote->size(), posZOrderListBeforePromote->size() + negZOrderListBeforePromote->size());
-
- m_canBePromotedToStackingContainerDirty = false;
- m_canBePromotedToStackingContainer = false;
-
- const RenderLayer* layerAfterPromote = 0;
- for (size_t i = 0; i < maxIndex && layerAfterPromote != this; ++i) {
- const RenderLayer* layerBeforePromote = i < negZOrderListBeforePromote->size()
- ? negZOrderListBeforePromote->at(i)
- : posZOrderListBeforePromote->at(i - negZOrderListBeforePromote->size());
- layerAfterPromote = i < negZOrderListAfterPromote->size()
- ? negZOrderListAfterPromote->at(i)
- : posZOrderListAfterPromote->at(i - negZOrderListAfterPromote->size());
-
- if (layerBeforePromote != layerAfterPromote && (layerAfterPromote != this || renderer()->hasBackground()))
- return;
- }
-
- layerAfterPromote = 0;
- for (size_t i = 0; i < maxIndex && layerAfterPromote != this; ++i) {
- const RenderLayer* layerBeforePromote = i < posZOrderListBeforePromote->size()
- ? posZOrderListBeforePromote->at(posZOrderListBeforePromote->size() - i - 1)
- : negZOrderListBeforePromote->at(negZOrderListBeforePromote->size() + posZOrderListBeforePromote->size() - i - 1);
- layerAfterPromote = i < posZOrderListAfterPromote->size()
- ? posZOrderListAfterPromote->at(posZOrderListAfterPromote->size() - i - 1)
- : negZOrderListAfterPromote->at(negZOrderListAfterPromote->size() + posZOrderListAfterPromote->size() - i - 1);
-
- if (layerBeforePromote != layerAfterPromote && layerAfterPromote != this)
- return;
- }
-
- m_canBePromotedToStackingContainer = true;
-}
-
-static inline bool isPositionedContainer(const RenderLayer* layer)
-{
- // FIXME: This is not in sync with containingBlock.
- // RenderObject::canContainFixedPositionedObject() should probably be used
- // instead.
- RenderLayerModelObject* layerRenderer = layer->renderer();
- return layer->isRootLayer() || layerRenderer->isPositioned() || layer->hasTransform();
-}
-
-void RenderLayer::collectBeforePromotionZOrderList(RenderLayer* ancestorStackingContext, OwnPtr<Vector<RenderLayer*> >& posZOrderListBeforePromote, OwnPtr<Vector<RenderLayer*> >& negZOrderListBeforePromote)
-{
- ancestorStackingContext->rebuildZOrderLists(posZOrderListBeforePromote, negZOrderListBeforePromote, this, OnlyStackingContextsCanBeStackingContainers);
-
- const RenderLayer* positionedAncestor = parent();
- while (positionedAncestor && !isPositionedContainer(positionedAncestor) && !positionedAncestor->isStackingContext())
- positionedAncestor = positionedAncestor->parent();
- if (positionedAncestor && (!isPositionedContainer(positionedAncestor) || positionedAncestor->isStackingContext()))
- positionedAncestor = 0;
-
- if (!posZOrderListBeforePromote)
- posZOrderListBeforePromote = adoptPtr(new Vector<RenderLayer*>());
- else if (posZOrderListBeforePromote->find(this) != kNotFound)
- return;
-
- // The current layer will appear in the z-order lists after promotion, so
- // for a meaningful comparison, we must insert it in the z-order lists
- // before promotion if it does not appear there already.
- if (!positionedAncestor) {
- posZOrderListBeforePromote->prepend(this);
- return;
- }
-
- for (size_t index = 0; index < posZOrderListBeforePromote->size(); index++) {
- if (posZOrderListBeforePromote->at(index) == positionedAncestor) {
- posZOrderListBeforePromote->insert(index + 1, this);
- return;
- }
- }
-}
-
-void RenderLayer::collectAfterPromotionZOrderList(RenderLayer* ancestorStackingContext, OwnPtr<Vector<RenderLayer*> >& posZOrderListAfterPromote, OwnPtr<Vector<RenderLayer*> >& negZOrderListAfterPromote)
-{
- ancestorStackingContext->rebuildZOrderLists(posZOrderListAfterPromote, negZOrderListAfterPromote, this, ForceLayerToStackingContainer);
-}
-
-// Compute what positive and negative z-order lists would look like before and
-// after promotion, so we can later ensure that proper stacking order is
-// preserved between the two sets of lists.
-//
-// A few examples:
-// c = currentLayer
-// - = negative z-order child of currentLayer
-// + = positive z-order child of currentLayer
-// a = positioned ancestor of currentLayer
-// x = any other RenderLayer in the list
-//
-// (a) xxxxx-----++a+++x
-// (b) xxx-----c++++++xx
-//
-// Normally the current layer would be painted in the normal flow list if it
-// doesn't already appear in the positive z-order list. However, in the case
-// that the layer has a positioned ancestor, it will paint directly after the
-// positioned ancestor. In example (a), the current layer would be painted in
-// the middle of its own positive z-order children, so promoting would cause a
-// change in paint order (since a promoted layer will paint all of its positive
-// z-order children strictly after it paints itself).
-//
-// In example (b), it is ok to promote the current layer only if it does not
-// have a background. If it has a background, the background gets painted before
-// the layer's negative z-order children, so again, a promotion would cause a
-// change in paint order (causing the background to get painted after the
-// negative z-order children instead of before).
-//
-void RenderLayer::computePaintOrderList(PaintOrderListType type, Vector<RefPtr<Node> >& list)
-{
- OwnPtr<Vector<RenderLayer*> > posZOrderList;
- OwnPtr<Vector<RenderLayer*> > negZOrderList;
-
- RenderLayer* stackingContext = ancestorStackingContext();
-
- if (!stackingContext)
- return;
-
- switch (type) {
- case BeforePromote:
- collectBeforePromotionZOrderList(stackingContext, posZOrderList, negZOrderList);
- break;
- case AfterPromote:
- collectAfterPromotionZOrderList(stackingContext, posZOrderList, negZOrderList);
- break;
- }
-
- if (negZOrderList) {
- for (size_t index = 0; index < negZOrderList->size(); ++index)
- list.append(negZOrderList->at(index)->renderer()->node());
- }
-
- if (posZOrderList) {
- for (size_t index = 0; index < posZOrderList->size(); ++index)
- list.append(posZOrderList->at(index)->renderer()->node());
- }
+ return settings && settings->compositorDrivenAcceleratedScrollingEnabled();
}
bool RenderLayer::scrollsWithRespectTo(const RenderLayer* other) const
@@ -673,8 +418,6 @@ bool RenderLayer::scrollsWithRespectTo(const RenderLayer* other) const
if (isRootFixedPos || otherIsRootFixedPos)
return true;
- FrameView* frameView = renderer()->view()->frameView();
-
if (containingBlock == otherContainingBlock)
return false;
@@ -682,7 +425,7 @@ bool RenderLayer::scrollsWithRespectTo(const RenderLayer* other) const
// closest scrollable ancestor.
HashSet<const RenderObject*> containingBlocks;
while (containingBlock) {
- if (frameView && frameView->containsScrollableArea(containingBlock->enclosingLayer()->scrollableArea()))
+ if (containingBlock->enclosingLayer()->scrollsOverflow())
break;
containingBlocks.add(containingBlock);
containingBlock = containingBlock->containingBlock();
@@ -694,7 +437,7 @@ bool RenderLayer::scrollsWithRespectTo(const RenderLayer* other) const
while (otherContainingBlock) {
if (containingBlocks.contains(otherContainingBlock))
return false;
- if (frameView && frameView->containsScrollableArea(otherContainingBlock->enclosingLayer()->scrollableArea()))
+ if (otherContainingBlock->enclosingLayer()->scrollsOverflow())
break;
otherContainingBlock = otherContainingBlock->containingBlock();
}
@@ -702,35 +445,6 @@ bool RenderLayer::scrollsWithRespectTo(const RenderLayer* other) const
return true;
}
-void RenderLayer::computeRepaintRects(const RenderLayerModelObject* repaintContainer, const RenderGeometryMap* geometryMap)
-{
- ASSERT(!m_visibleContentStatusDirty);
-
- m_repaintRect = renderer()->clippedOverflowRectForRepaint(repaintContainer);
- m_outlineBox = renderer()->outlineBoundsForRepaint(repaintContainer, geometryMap);
-}
-
-
-void RenderLayer::computeRepaintRectsIncludingDescendants()
-{
- // FIXME: computeRepaintRects() has to walk up the parent chain for every layer to compute the rects.
- // We should make this more efficient.
- // FIXME: it's wrong to call this when layout is not up-to-date, which we do.
- computeRepaintRects(renderer()->containerForRepaint());
-
- for (RenderLayer* layer = firstChild(); layer; layer = layer->nextSibling())
- layer->computeRepaintRectsIncludingDescendants();
-}
-
-void RenderLayer::clearRepaintRects()
-{
- ASSERT(!m_hasVisibleContent);
- ASSERT(!m_visibleContentStatusDirty);
-
- m_repaintRect = IntRect();
- m_outlineBox = IntRect();
-}
-
void RenderLayer::updateLayerPositionsAfterDocumentScroll()
{
ASSERT(this == renderer()->view()->layer());
@@ -760,7 +474,7 @@ void RenderLayer::updateLayerPositionsAfterScroll(RenderGeometryMap* geometryMap
// If we have no visible content and no visible descendants, there is no point recomputing
// our rectangles as they will be empty. If our visibility changes, we are expected to
// recompute all our positions anyway.
- if (!m_hasVisibleDescendant && !m_hasVisibleContent)
+ if (subtreeIsInvisible())
return;
bool positionChanged = updateLayerPosition();
@@ -771,7 +485,7 @@ void RenderLayer::updateLayerPositionsAfterScroll(RenderGeometryMap* geometryMap
geometryMap->pushMappingsToAncestor(this, parent());
if (flags & HasChangedAncestor || flags & HasSeenViewportConstrainedAncestor || flags & IsOverflowScroll)
- clearClipRects();
+ m_clipper.clearClipRects();
if (renderer()->style()->hasViewportConstrainedPosition())
flags |= HasSeenViewportConstrainedAncestor;
@@ -782,12 +496,12 @@ void RenderLayer::updateLayerPositionsAfterScroll(RenderGeometryMap* geometryMap
if (flags & HasSeenViewportConstrainedAncestor
|| (flags & IsOverflowScroll && flags & HasSeenAncestorWithOverflowClip && !m_canSkipRepaintRectsUpdateOnScroll)) {
// FIXME: We could track the repaint container as we walk down the tree.
- computeRepaintRects(renderer()->containerForRepaint(), geometryMap);
+ repainter().computeRepaintRects(renderer()->containerForRepaint(), geometryMap);
} else {
- // Check that our cached rects are correct.
+ // Check that RenderLayerRepainter's cached rects are correct.
// FIXME: re-enable these assertions when the issue with table cells is resolved: https://bugs.webkit.org/show_bug.cgi?id=103432
- // ASSERT(m_repaintRect == renderer()->clippedOverflowRectForRepaint(renderer()->containerForRepaint()));
- // ASSERT(m_outlineBox == renderer()->outlineBoundsForRepaint(renderer()->containerForRepaint(), geometryMap));
+ // ASSERT(repainter().m_repaintRect == renderer()->clippedOverflowRectForRepaint(renderer()->containerForRepaint()));
+ // ASSERT(repainter().m_outlineBox == renderer()->outlineBoundsForRepaint(renderer()->containerForRepaint(), geometryMap));
}
for (RenderLayer* child = firstChild(); child; child = child->nextSibling())
@@ -801,20 +515,6 @@ void RenderLayer::updateLayerPositionsAfterScroll(RenderGeometryMap* geometryMap
geometryMap->popMappingsToAncestor(parent());
}
-void RenderLayer::positionNewlyCreatedOverflowControls()
-{
- if (!backing()->hasUnpositionedOverflowControlsLayers())
- return;
-
- RenderGeometryMap geometryMap(UseTransforms);
- RenderView* view = renderer()->view();
- if (this != view->layer() && parent())
- geometryMap.pushMappingsToAncestor(parent(), 0);
-
- LayoutPoint offsetFromRoot = LayoutPoint(geometryMap.absolutePoint(FloatPoint()));
- positionOverflowControls(toIntSize(roundedIntPoint(offsetFromRoot)));
-}
-
bool RenderLayer::hasBlendMode() const
{
return RuntimeEnabledFeatures::cssCompositingEnabled() && renderer()->hasBlendMode();
@@ -825,11 +525,17 @@ void RenderLayer::updateBlendMode()
if (!RuntimeEnabledFeatures::cssCompositingEnabled())
return;
- BlendMode newBlendMode = renderer()->style()->blendMode();
+ bool hadBlendMode = m_blendMode != blink::WebBlendModeNormal;
+ blink::WebBlendMode newBlendMode = renderer()->style()->blendMode();
if (newBlendMode != m_blendMode) {
m_blendMode = newBlendMode;
- if (backing())
- backing()->setBlendMode(newBlendMode);
+
+ // Only update the flag if a blend mode is set or unset.
+ if (parent() && (!hadBlendMode || !hasBlendMode()))
+ parent()->dirtyAncestorChainBlendedDescendantStatus();
+
+ if (hasCompositedLayerMapping())
+ compositedLayerMapping()->setBlendMode(newBlendMode);
}
}
@@ -848,7 +554,7 @@ void RenderLayer::updateTransform()
m_transform.clear();
// Layers with transforms act as clip rects roots, so clear the cached clip rects here.
- clearClipRectsIncludingDescendants();
+ m_clipper.clearClipRectsIncludingDescendants();
}
if (hasTransform) {
@@ -868,9 +574,10 @@ TransformationMatrix RenderLayer::currentTransform(RenderStyle::ApplyTransformOr
if (!m_transform)
return TransformationMatrix();
- if (renderer()->style()->isRunningAcceleratedAnimation()) {
+ // FIXME: handle this under web-animations
+ if (!RuntimeEnabledFeatures::webAnimationsCSSEnabled() && renderer()->style()->isRunningAcceleratedAnimation()) {
TransformationMatrix currTransform;
- RefPtr<RenderStyle> style = renderer()->animation()->getAnimatedStyleForRenderer(renderer());
+ RefPtr<RenderStyle> style = renderer()->animation().getAnimatedStyleForRenderer(renderer());
style->applyTransform(currTransform, renderBox()->pixelSnappedBorderBoxRect().size(), applyOrigin);
makeMatrixRenderable(currTransform, canRender3DTransforms());
return currTransform;
@@ -935,7 +642,7 @@ void RenderLayer::updatePagination()
m_isPaginated = false;
m_enclosingPaginationLayer = 0;
- if (isComposited() || !parent())
+ if (hasCompositedLayerMapping() || !parent())
return; // FIXME: We will have to deal with paginated compositing layers someday.
// FIXME: For now the RenderView can't be paginated. Eventually printing will move to a model where it is though.
@@ -952,7 +659,7 @@ void RenderLayer::updatePagination()
return;
}
- if (isNormalFlowOnly()) {
+ if (m_stackingNode->isNormalFlowOnly()) {
if (regionBasedColumnsUsed) {
// Content inside a transform is not considered to be paginated, since we simply
// paint the transform multiple times in each column, so we don't have to use
@@ -987,26 +694,17 @@ void RenderLayer::updatePagination()
}
// If we're not normal flow, then we need to look for a multi-column object between us and our stacking container.
- RenderLayer* ancestorStackingContainer = this->ancestorStackingContainer();
+ RenderLayerStackingNode* ancestorStackingContainerNode = m_stackingNode->ancestorStackingContainerNode();
for (RenderLayer* curr = parent(); curr; curr = curr->parent()) {
if (curr->renderer()->hasColumns()) {
m_isPaginated = checkContainingBlockChainForPagination(renderer(), curr->renderBox());
return;
}
- if (curr == ancestorStackingContainer)
+ if (curr->stackingNode() == ancestorStackingContainerNode)
return;
}
}
-bool RenderLayer::canBeStackingContainer() const
-{
- if (isStackingContext() || !ancestorStackingContainer())
- return true;
-
- ASSERT(!m_canBePromotedToStackingContainerDirty);
- return m_canBePromotedToStackingContainer;
-}
-
void RenderLayer::setHasVisibleContent()
{
if (m_hasVisibleContent && !m_visibleContentStatusDirty) {
@@ -1016,14 +714,14 @@ void RenderLayer::setHasVisibleContent()
m_visibleContentStatusDirty = false;
m_hasVisibleContent = true;
- computeRepaintRects(renderer()->containerForRepaint());
- if (!isNormalFlowOnly()) {
+ repainter().computeRepaintRects(renderer()->containerForRepaint());
+ if (!m_stackingNode->isNormalFlowOnly()) {
// We don't collect invisible layers in z-order lists if we are not in compositing mode.
// As we became visible, we need to dirty our stacking containers ancestors to be properly
// collected. FIXME: When compositing, we could skip this dirtying phase.
- for (RenderLayer* sc = ancestorStackingContainer(); sc; sc = sc->ancestorStackingContainer()) {
+ for (RenderLayerStackingNode* sc = m_stackingNode->ancestorStackingContainerNode(); sc; sc = sc->ancestorStackingContainerNode()) {
sc->dirtyZOrderLists();
- if (sc->hasVisibleContent())
+ if (sc->layer()->hasVisibleContent())
break;
}
}
@@ -1060,6 +758,33 @@ void RenderLayer::setAncestorChainHasVisibleDescendant()
}
}
+void RenderLayer::dirtyAncestorChainBlendedDescendantStatus()
+{
+ for (RenderLayer* layer = this; layer; layer = layer->parent()) {
+ if (layer->m_childLayerHasBlendModeStatusDirty)
+ break;
+
+ layer->m_childLayerHasBlendModeStatusDirty = true;
+
+ if (layer->stackingNode()->isStackingContext())
+ break;
+ }
+}
+
+void RenderLayer::setAncestorChainBlendedDescendant()
+{
+ for (RenderLayer* layer = this; layer; layer = layer->parent()) {
+ if (!layer->m_childLayerHasBlendModeStatusDirty && layer->childLayerHasBlendMode())
+ break;
+
+ layer->m_childLayerHasBlendMode = true;
+ layer->m_childLayerHasBlendModeStatusDirty = false;
+
+ if (layer->stackingNode()->isStackingContext())
+ break;
+ }
+}
+
void RenderLayer::updateHasUnclippedDescendant()
{
TRACE_EVENT0("blink_rendering", "RenderLayer::updateHasUnclippedDescendant");
@@ -1081,12 +806,26 @@ void RenderLayer::updateHasUnclippedDescendant()
// compositor, we will be able to relax this restriction without it being prohibitively
// expensive (currently, we have to do a lot of work in the compositor to honor a
// clip child/parent relationship).
- if (frameView->containsScrollableArea(ancestor->scrollableArea()))
+ if (ancestor->scrollsOverflow())
setIsUnclippedDescendant(true);
ancestor->setHasUnclippedDescendant(true);
}
}
+// FIXME: this is quite brute-force. We could be more efficient if we were to
+// track state and update it as appropriate as changes are made in the RenderObject tree.
+void RenderLayer::updateHasVisibleNonLayerContent()
+{
+ TRACE_EVENT0("blink_rendering", "RenderLayer::updateHasVisibleNonLayerContent");
+ m_hasVisibleNonLayerContent = false;
+ for (RenderObject* r = renderer()->firstChild(); r; r = r->nextSibling()) {
+ if (!r->hasLayer()) {
+ m_hasVisibleNonLayerContent = true;
+ break;
+ }
+ }
+}
+
static bool subtreeContainsOutOfFlowPositionedLayer(const RenderLayer* subtreeRoot)
{
return (subtreeRoot->renderer() && subtreeRoot->renderer()->isOutOfFlowPositioned()) || subtreeRoot->hasOutOfFlowPositionedDescendant();
@@ -1119,6 +858,21 @@ void RenderLayer::updateDescendantDependentFlags()
m_hasOutOfFlowPositionedDescendantDirty = false;
}
+ if (m_childLayerHasBlendModeStatusDirty) {
+ m_childLayerHasBlendMode = false;
+ for (RenderLayer* child = firstChild(); child; child = child->nextSibling()) {
+ if (!child->stackingNode()->isStackingContext())
+ child->updateDescendantDependentFlags();
+
+ bool childLayerHasBlendMode = child->paintsWithBlendMode() || (child->m_childLayerHasBlendMode && !child->stackingNode()->isStackingContext());
+ m_childLayerHasBlendMode |= childLayerHasBlendMode;
+
+ if (m_childLayerHasBlendMode)
+ break;
+ }
+ m_childLayerHasBlendModeStatusDirty = false;
+ }
+
if (m_visibleContentStatusDirty) {
if (renderer()->style()->visibility() == VISIBLE)
m_hasVisibleContent = true;
@@ -1152,15 +906,17 @@ void RenderLayer::updateDescendantDependentFlags()
void RenderLayer::dirty3DTransformedDescendantStatus()
{
- RenderLayer* curr = ancestorStackingContainer();
- if (curr)
- curr->m_3DTransformedDescendantStatusDirty = true;
+ RenderLayerStackingNode* stackingNode = m_stackingNode->ancestorStackingContainerNode();
+ if (!stackingNode)
+ return;
+
+ stackingNode->layer()->m_3DTransformedDescendantStatusDirty = true;
// This propagates up through preserve-3d hierarchies to the enclosing flattening layer.
// Note that preserves3D() creates stacking context, so we can just run up the stacking containers.
- while (curr && curr->preserves3D()) {
- curr->m_3DTransformedDescendantStatusDirty = true;
- curr = curr->ancestorStackingContainer();
+ while (stackingNode && stackingNode->layer()->preserves3D()) {
+ stackingNode->layer()->m_3DTransformedDescendantStatusDirty = true;
+ stackingNode = stackingNode->ancestorStackingContainerNode();
}
}
@@ -1170,20 +926,13 @@ bool RenderLayer::update3DTransformedDescendantStatus()
if (m_3DTransformedDescendantStatusDirty) {
m_has3DTransformedDescendant = false;
- updateZOrderLists();
+ m_stackingNode->updateZOrderLists();
// Transformed or preserve-3d descendants can only be in the z-order lists, not
// in the normal flow list, so we only need to check those.
- if (Vector<RenderLayer*>* positiveZOrderList = posZOrderList()) {
- for (unsigned i = 0; i < positiveZOrderList->size(); ++i)
- m_has3DTransformedDescendant |= positiveZOrderList->at(i)->update3DTransformedDescendantStatus();
- }
-
- // Now check our negative z-index children.
- if (Vector<RenderLayer*>* negativeZOrderList = negZOrderList()) {
- for (unsigned i = 0; i < negativeZOrderList->size(); ++i)
- m_has3DTransformedDescendant |= negativeZOrderList->at(i)->update3DTransformedDescendantStatus();
- }
+ RenderLayerStackingNodeIterator iterator(*m_stackingNode.get(), PositiveZOrderChildren | NegativeZOrderChildren);
+ while (RenderLayerStackingNode* node = iterator.next())
+ m_has3DTransformedDescendant |= node->layer()->update3DTransformedDescendantStatus();
m_3DTransformedDescendantStatusDirty = false;
}
@@ -1236,7 +985,7 @@ bool RenderLayer::updateLayerPosition()
// For positioned layers, we subtract out the enclosing positioned layer's scroll offset.
if (positionedParent->renderer()->hasOverflowClip()) {
- LayoutSize offset = positionedParent->scrolledContentOffset();
+ LayoutSize offset = positionedParent->renderBox()->scrolledContentOffset();
localPoint -= offset;
}
@@ -1245,7 +994,7 @@ bool RenderLayer::updateLayerPosition()
localPoint += offset;
}
} else if (parent()) {
- if (isComposited()) {
+ if (hasCompositedLayerMapping()) {
// FIXME: Composited layers ignore pagination, so about the best we can do is make sure they're offset into the appropriate column.
// They won't split across columns properly.
LayoutSize columnOffset;
@@ -1258,7 +1007,7 @@ bool RenderLayer::updateLayerPosition()
}
if (parent()->renderer()->hasOverflowClip()) {
- IntSize scrollOffset = parent()->scrolledContentOffset();
+ IntSize scrollOffset = parent()->renderBox()->scrolledContentOffset();
localPoint -= scrollOffset;
}
}
@@ -1323,22 +1072,6 @@ FloatPoint RenderLayer::perspectiveOrigin() const
floatValueForLength(style->perspectiveOriginY(), borderBox.height()));
}
-RenderLayer* RenderLayer::ancestorStackingContainer() const
-{
- RenderLayer* ancestor = parent();
- while (ancestor && !ancestor->isStackingContainer())
- ancestor = ancestor->parent();
- return ancestor;
-}
-
-RenderLayer* RenderLayer::ancestorStackingContext() const
-{
- RenderLayer* ancestor = parent();
- while (ancestor && !ancestor->isStackingContext())
- ancestor = ancestor->parent();
- return ancestor;
-}
-
static inline bool isFixedPositionedContainer(RenderLayer* layer)
{
return layer->isRootLayer() || layer->hasTransform();
@@ -1347,7 +1080,7 @@ static inline bool isFixedPositionedContainer(RenderLayer* layer)
RenderLayer* RenderLayer::enclosingPositionedAncestor() const
{
RenderLayer* curr = parent();
- while (curr && !isPositionedContainer(curr))
+ while (curr && !curr->isPositionedContainer())
curr = curr->parent();
return curr;
@@ -1355,50 +1088,12 @@ RenderLayer* RenderLayer::enclosingPositionedAncestor() const
RenderLayer* RenderLayer::enclosingScrollableLayer() const
{
- for (RenderLayer* nextLayer = parent(); nextLayer; nextLayer = nextLayer->parent()) {
- if (nextLayer->renderer()->isBox() && toRenderBox(nextLayer->renderer())->canBeScrolledAndHasScrollableArea())
- return nextLayer;
- }
+ if (RenderBox* enclosingScrollableBox = renderer()->enclosingScrollableBox())
+ return enclosingScrollableBox->layer();
return 0;
}
-IntRect RenderLayer::scrollableAreaBoundingBox() const
-{
- return renderer()->absoluteBoundingBoxRect();
-}
-
-bool RenderLayer::userInputScrollable(ScrollbarOrientation orientation) const
-{
- RenderBox* box = renderBox();
- ASSERT(box);
-
- if (box->isIntristicallyScrollable(orientation))
- return true;
-
- EOverflow overflowStyle = (orientation == HorizontalScrollbar) ?
- renderer()->style()->overflowX() : renderer()->style()->overflowY();
- return (overflowStyle == OSCROLL || overflowStyle == OAUTO || overflowStyle == OOVERLAY);
-}
-
-bool RenderLayer::shouldPlaceVerticalScrollbarOnLeft() const
-{
- return renderer()->style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft();
-}
-
-int RenderLayer::pageStep(ScrollbarOrientation orientation) const
-{
- RenderBox* box = renderBox();
- ASSERT(box);
-
- int length = (orientation == HorizontalScrollbar) ?
- box->pixelSnappedClientWidth() : box->pixelSnappedClientHeight();
- int minPageStep = static_cast<float>(length) * ScrollableArea::minFractionToStepWhenPaging();
- int pageStep = max(minPageStep, length - ScrollableArea::maxOverlapBetweenPages());
-
- return max(pageStep, 1);
-}
-
RenderLayer* RenderLayer::enclosingTransformedAncestor() const
{
RenderLayer* curr = parent();
@@ -1410,27 +1105,21 @@ RenderLayer* RenderLayer::enclosingTransformedAncestor() const
static inline const RenderLayer* compositingContainer(const RenderLayer* layer)
{
- return layer->isNormalFlowOnly() ? layer->parent() : layer->ancestorStackingContainer();
-}
-
-inline bool RenderLayer::shouldRepaintAfterLayout() const
-{
- if (m_repaintStatus == NeedsNormalRepaint)
- return true;
-
- // Composited layers that were moved during a positioned movement only
- // layout, don't need to be repainted. They just need to be recomposited.
- ASSERT(m_repaintStatus == NeedsFullRepaintForPositionedMovementLayout);
- return !isComposited();
+ return layer->stackingNode()->isNormalFlowOnly() ? layer->parent() : (layer->stackingNode()->ancestorStackingContainerNode() ? layer->stackingNode()->ancestorStackingContainerNode()->layer() : 0);
}
+// FIXME: having two different functions named enclosingCompositingLayer and enclosingCompositingLayerForRepaint
+// is error-prone and misleading for reading code that uses these functions - especially compounded with
+// the includeSelf option. It is very likely that we don't even want either of these functions; A layer
+// should be told explicitly which GraphicsLayer is the repaintContainer for a RenderLayer, and
+// any other use cases should probably have an API between the non-compositing and compositing sides of code.
RenderLayer* RenderLayer::enclosingCompositingLayer(bool includeSelf) const
{
- if (includeSelf && isComposited())
+ if (includeSelf && compositingState() != NotComposited && compositingState() != PaintsIntoGroupedBacking)
return const_cast<RenderLayer*>(this);
for (const RenderLayer* curr = compositingContainer(this); curr; curr = compositingContainer(curr)) {
- if (curr->isComposited())
+ if (curr->compositingState() != NotComposited && curr->compositingState() != PaintsIntoGroupedBacking)
return const_cast<RenderLayer*>(curr);
}
@@ -1439,18 +1128,18 @@ RenderLayer* RenderLayer::enclosingCompositingLayer(bool includeSelf) const
RenderLayer* RenderLayer::enclosingCompositingLayerForRepaint(bool includeSelf) const
{
- if (includeSelf && isComposited() && !backing()->paintsIntoCompositedAncestor())
+ if (includeSelf && (compositingState() == PaintsIntoOwnBacking || compositingState() == PaintsIntoGroupedBacking))
return const_cast<RenderLayer*>(this);
for (const RenderLayer* curr = compositingContainer(this); curr; curr = compositingContainer(curr)) {
- if (curr->isComposited() && !curr->backing()->paintsIntoCompositedAncestor())
+ if (curr->compositingState() == PaintsIntoOwnBacking || curr->compositingState() == PaintsIntoGroupedBacking)
return const_cast<RenderLayer*>(curr);
}
return 0;
}
-RenderLayer* RenderLayer::ancestorScrollingLayer() const
+RenderLayer* RenderLayer::ancestorCompositedScrollingLayer() const
{
if (!acceleratedCompositingForOverflowScrollEnabled())
return 0;
@@ -1467,68 +1156,29 @@ RenderLayer* RenderLayer::ancestorScrollingLayer() const
return 0;
}
-RenderLayer* RenderLayer::enclosingFilterLayer(bool includeSelf) const
+RenderLayer* RenderLayer::ancestorScrollingLayer() const
{
- const RenderLayer* curr = includeSelf ? this : parent();
- for (; curr; curr = curr->parent()) {
- if (curr->requiresFullLayerImageForFilters())
- return const_cast<RenderLayer*>(curr);
+ RenderObject* containingBlock = renderer()->containingBlock();
+ if (!containingBlock)
+ return 0;
+
+ for (RenderLayer* ancestorLayer = containingBlock->enclosingLayer(); ancestorLayer; ancestorLayer = ancestorLayer->parent()) {
+ if (ancestorLayer->scrollsOverflow())
+ return ancestorLayer;
}
return 0;
}
-RenderLayer* RenderLayer::enclosingFilterRepaintLayer() const
+RenderLayer* RenderLayer::enclosingFilterLayer(bool includeSelf) const
{
- for (const RenderLayer* curr = this; curr; curr = curr->parent()) {
- if ((curr != this && curr->requiresFullLayerImageForFilters()) || curr->isComposited() || curr->isRootLayer())
+ const RenderLayer* curr = includeSelf ? this : parent();
+ for (; curr; curr = curr->parent()) {
+ if (curr->requiresFullLayerImageForFilters())
return const_cast<RenderLayer*>(curr);
}
- return 0;
-}
-
-void RenderLayer::setFilterBackendNeedsRepaintingInRect(const LayoutRect& rect)
-{
- if (rect.isEmpty())
- return;
-
- LayoutRect rectForRepaint = rect;
- renderer()->style()->filterOutsets().expandRect(rectForRepaint);
-
- RenderLayerFilterInfo* filterInfo = this->filterInfo();
- ASSERT(filterInfo);
- filterInfo->expandDirtySourceRect(rectForRepaint);
-
- ASSERT(filterInfo->renderer());
- if (filterInfo->renderer()->hasCustomShaderFilter()) {
- // If we have at least one custom shader, we need to update the whole bounding box of the layer, because the
- // shader can address any ouput pixel.
- // Note: This is only for output rect, so there's no need to expand the dirty source rect.
- rectForRepaint.unite(calculateLayerBounds(this));
- }
-
- RenderLayer* parentLayer = enclosingFilterRepaintLayer();
- ASSERT(parentLayer);
- FloatQuad repaintQuad(rectForRepaint);
- LayoutRect parentLayerRect = renderer()->localToContainerQuad(repaintQuad, parentLayer->renderer()).enclosingBoundingBox();
-
- if (parentLayer->isComposited()) {
- parentLayer->setBackingNeedsRepaintInRect(parentLayerRect);
- return;
- }
-
- if (parentLayer->paintsWithFilters()) {
- parentLayer->setFilterBackendNeedsRepaintingInRect(parentLayerRect);
- return;
- }
-
- if (parentLayer->isRootLayer()) {
- RenderView* view = toRenderView(parentLayer->renderer());
- view->repaintViewRectangle(parentLayerRect);
- return;
- }
- ASSERT_NOT_REACHED();
+ return 0;
}
bool RenderLayer::hasAncestorWithFilterOutsets() const
@@ -1543,7 +1193,7 @@ bool RenderLayer::hasAncestorWithFilterOutsets() const
RenderLayer* RenderLayer::clippingRootForPainting() const
{
- if (isComposited())
+ if (hasCompositedLayerMapping())
return const_cast<RenderLayer*>(this);
const RenderLayer* current = this;
@@ -1554,7 +1204,7 @@ RenderLayer* RenderLayer::clippingRootForPainting() const
current = compositingContainer(current);
ASSERT(current);
if (current->transform()
- || (current->isComposited() && !current->backing()->paintsIntoCompositedAncestor())
+ || (current->compositingState() == PaintsIntoOwnBacking)
)
return const_cast<RenderLayer*>(current);
}
@@ -1563,15 +1213,9 @@ RenderLayer* RenderLayer::clippingRootForPainting() const
return 0;
}
-LayoutPoint RenderLayer::absoluteToContents(const LayoutPoint& absolutePoint) const
-{
- // We don't use convertToLayerCoords because it doesn't know about transforms
- return roundedLayoutPoint(renderer()->absoluteToLocal(absolutePoint, UseTransforms));
-}
-
bool RenderLayer::cannotBlitToWindow() const
{
- if (isTransparent() || hasReflection() || hasTransform())
+ if (isTransparent() || m_reflectionInfo || hasTransform())
return true;
if (!parent())
return false;
@@ -1580,8 +1224,7 @@ bool RenderLayer::cannotBlitToWindow() const
bool RenderLayer::isTransparent() const
{
- // FIXME: This seems incorrect; why would SVG layers be opaque?
- if (renderer()->node() && renderer()->node()->namespaceURI() == SVGNames::svgNamespaceURI)
+ if (renderer()->node() && renderer()->node()->isSVGElement())
return false;
return renderer()->isTransparent() || renderer()->hasMask();
@@ -1589,11 +1232,11 @@ bool RenderLayer::isTransparent() const
RenderLayer* RenderLayer::transparentPaintingAncestor()
{
- if (isComposited())
+ if (hasCompositedLayerMapping())
return 0;
for (RenderLayer* curr = parent(); curr; curr = curr->parent()) {
- if (curr->isComposited())
+ if (curr->hasCompositedLayerMapping())
return 0;
if (curr->isTransparent())
return curr;
@@ -1622,7 +1265,7 @@ static void expandClipRectForDescendantsAndReflection(LayoutRect& clipRect, cons
// Note: we don't have to walk z-order lists since transparent elements always establish
// a stacking container. This means we can just walk the layer tree directly.
for (RenderLayer* curr = layer->firstChild(); curr; curr = curr->nextSibling()) {
- if (!layer->reflection() || layer->reflectionLayer() != curr)
+ if (!layer->reflectionInfo() || layer->reflectionInfo()->reflectionLayer() != curr)
clipRect.unite(transparencyClipBox(curr, rootLayer, transparencyBehavior, DescendantsOfTransparencyClipBox, paintBehavior));
}
}
@@ -1694,18 +1337,22 @@ LayoutRect RenderLayer::paintingExtent(const RenderLayer* rootLayer, const Layou
void RenderLayer::beginTransparencyLayers(GraphicsContext* context, const RenderLayer* rootLayer, const LayoutRect& paintDirtyRect, PaintBehavior paintBehavior)
{
- if (context->paintingDisabled() || (paintsWithTransparency(paintBehavior) && m_usedTransparency))
+ bool createTransparencyLayerForBlendMode = m_stackingNode->isStackingContext() && m_childLayerHasBlendMode;
+ if (context->paintingDisabled() || ((paintsWithTransparency(paintBehavior) || paintsWithBlendMode() || createTransparencyLayerForBlendMode) && m_usedTransparency))
return;
RenderLayer* ancestor = transparentPaintingAncestor();
if (ancestor)
ancestor->beginTransparencyLayers(context, rootLayer, paintDirtyRect, paintBehavior);
- if (paintsWithTransparency(paintBehavior)) {
+ if (paintsWithTransparency(paintBehavior) || paintsWithBlendMode() || createTransparencyLayerForBlendMode) {
m_usedTransparency = true;
context->save();
LayoutRect clipRect = paintingExtent(rootLayer, paintDirtyRect, paintBehavior);
context->clip(clipRect);
+ if (paintsWithBlendMode())
+ context->setCompositeOperation(context->compositeOperation(), m_blendMode);
+
context->beginTransparencyLayer(renderer()->opacity());
#ifdef REVEAL_TRANSPARENCY_LAYERS
context->setFillColor(Color(0.0f, 0.0f, 0.5f, 0.2f));
@@ -1743,14 +1390,14 @@ void RenderLayer::addChild(RenderLayer* child, RenderLayer* beforeChild)
child->setParent(this);
- if (child->isNormalFlowOnly())
- dirtyNormalFlowList();
+ if (child->stackingNode()->isNormalFlowOnly())
+ m_stackingNode->dirtyNormalFlowList();
- if (!child->isNormalFlowOnly() || child->firstChild()) {
- // Dirty the z-order list in which we are contained. The ancestorStackingContainer() can be null in the
+ if (!child->stackingNode()->isNormalFlowOnly() || child->firstChild()) {
+ // Dirty the z-order list in which we are contained. The ancestorStackingContainerNode() can be null in the
// case where we're building up generated content layers. This is ok, since the lists will start
// off dirty in that case anyway.
- child->dirtyStackingContainerZOrderLists();
+ child->stackingNode()->dirtyStackingContainerZOrderLists();
}
child->updateDescendantDependentFlags();
@@ -1760,6 +1407,9 @@ void RenderLayer::addChild(RenderLayer* child, RenderLayer* beforeChild)
if (child->isSelfPaintingLayer() || child->hasSelfPaintingLayerDescendant())
setAncestorChainHasSelfPaintingLayerDescendant();
+ if (child->paintsWithBlendMode() || child->childLayerHasBlendMode())
+ setAncestorChainBlendedDescendant();
+
if (subtreeContainsOutOfFlowPositionedLayer(child)) {
// Now that the out of flow positioned descendant is in the tree, we
// need to tell the compositor to reevaluate the compositing
@@ -1773,7 +1423,7 @@ void RenderLayer::addChild(RenderLayer* child, RenderLayer* beforeChild)
// layer's stacking context. We need to manually do it here as well, in case
// we're adding this layer after the stacking context has already been
// updated.
- child->m_canBePromotedToStackingContainerDirty = true;
+ child->stackingNode()->setDescendantsAreContiguousInStackingOrderDirty(true);
compositor()->layerWasAdded(this, child);
}
@@ -1793,13 +1443,13 @@ RenderLayer* RenderLayer::removeChild(RenderLayer* oldChild)
if (m_last == oldChild)
m_last = oldChild->previousSibling();
- if (oldChild->isNormalFlowOnly())
- dirtyNormalFlowList();
- if (!oldChild->isNormalFlowOnly() || oldChild->firstChild()) {
+ if (oldChild->stackingNode()->isNormalFlowOnly())
+ m_stackingNode->dirtyNormalFlowList();
+ if (!oldChild->stackingNode()->isNormalFlowOnly() || oldChild->firstChild()) {
// Dirty the z-order list in which we are contained. When called via the
// reattachment process in removeOnlyThisLayer, the layer may already be disconnected
// from the main layer tree, so we need to null-check the |stackingContainer| value.
- oldChild->dirtyStackingContainerZOrderLists();
+ oldChild->stackingNode()->dirtyStackingContainerZOrderLists();
}
oldChild->setPreviousSibling(0);
@@ -1818,6 +1468,9 @@ RenderLayer* RenderLayer::removeChild(RenderLayer* oldChild)
if (oldChild->m_hasVisibleContent || oldChild->m_hasVisibleDescendant)
dirtyAncestorChainVisibleDescendantStatus();
+ if (oldChild->paintsWithBlendMode() || oldChild->childLayerHasBlendMode())
+ dirtyAncestorChainBlendedDescendantStatus();
+
if (oldChild->isSelfPaintingLayer() || oldChild->hasSelfPaintingLayerDescendant())
dirtyAncestorChainHasSelfPaintingLayerDescendantStatus();
@@ -1829,21 +1482,17 @@ void RenderLayer::removeOnlyThisLayer()
if (!m_parent)
return;
- // Mark that we are about to lose our layer. This makes render tree
- // walks ignore this layer while we're removing it.
- m_renderer->setHasLayer(false);
-
compositor()->layerWillBeRemoved(m_parent, this);
// Dirty the clip rects.
- clearClipRectsIncludingDescendants();
+ m_clipper.clearClipRectsIncludingDescendants();
RenderLayer* nextSib = nextSibling();
// Remove the child reflection layer before moving other child layers.
// The reflection layer should not be moved to the parent.
- if (reflection())
- removeChild(reflectionLayer());
+ if (m_reflectionInfo)
+ removeChild(m_reflectionInfo->reflectionLayer());
// Now walk our kids and reattach them to our parent.
RenderLayer* current = m_first;
@@ -1851,9 +1500,7 @@ void RenderLayer::removeOnlyThisLayer()
RenderLayer* next = current->nextSibling();
removeChild(current);
m_parent->addChild(current, nextSib);
- current->setRepaintStatus(NeedsFullRepaint);
- // updateLayerPositions depends on hasLayer() already being false for proper layout.
- ASSERT(!renderer()->hasLayer());
+ current->repainter().setRepaintStatus(NeedsFullRepaint);
current->updateLayerPositions(0); // FIXME: use geometry map.
current = next;
}
@@ -1870,7 +1517,7 @@ void RenderLayer::insertOnlyThisLayer()
// Find our enclosingLayer and add ourselves.
RenderLayer* parentLayer = renderer()->parent()->enclosingLayer();
ASSERT(parentLayer);
- RenderLayer* beforeChild = parentLayer->reflectionLayer() != this ? renderer()->parent()->findNextLayer(parentLayer, renderer()) : 0;
+ RenderLayer* beforeChild = !parentLayer->reflectionInfo() || parentLayer->reflectionInfo()->reflectionLayer() != this ? renderer()->parent()->findNextLayer(parentLayer, renderer()) : 0;
parentLayer->addChild(this, beforeChild);
}
@@ -1879,7 +1526,7 @@ void RenderLayer::insertOnlyThisLayer()
curr->moveLayers(m_parent, this);
// Clear out all the clip rects.
- clearClipRectsIncludingDescendants();
+ m_clipper.clearClipRectsIncludingDescendants();
}
void RenderLayer::convertToPixelSnappedLayerCoords(const RenderLayer* ancestorLayer, IntPoint& roundedLocation) const
@@ -1967,7 +1614,7 @@ static inline const RenderLayer* accumulateOffsetTowardsAncestor(const RenderLay
// RenderFlowThread is a positioned container, child of RenderView, positioned at (0,0).
// This implies that, for out-of-flow positioned elements inside a RenderFlowThread,
// we are bailing out before reaching root layer.
- if (isPositionedContainer(parentLayer))
+ if (parentLayer->isPositionedContainer())
break;
if (parentLayer == ancestorLayer) {
@@ -2024,46 +1671,16 @@ void RenderLayer::convertToLayerCoords(const RenderLayer* ancestorLayer, LayoutR
rect.move(-delta.x(), -delta.y());
}
-bool RenderLayer::usesCompositedScrolling() const
-{
- RenderBox* box = renderBox();
-
- // Scroll form controls on the main thread so they exhibit correct touch scroll event bubbling
- if (box && (box->isIntristicallyScrollable(VerticalScrollbar) || box->isIntristicallyScrollable(HorizontalScrollbar)))
- return false;
-
- return isComposited() && backing()->scrollingLayer();
-}
-
-bool RenderLayer::needsCompositedScrolling() const
-{
- if (!compositorDrivenAcceleratedScrollingEnabled())
- return needsToBeStackingContainer();
- if (FrameView* frameView = renderer()->view()->frameView())
- return frameView->containsScrollableArea(scrollableArea());
- return false;
-}
-
-bool RenderLayer::needsToBeStackingContainer() const
-{
- switch (m_forceNeedsCompositedScrolling) {
- case DoNotForceCompositedScrolling:
- return m_needsCompositedScrolling;
- case CompositedScrollingAlwaysOn:
- return true;
- case CompositedScrollingAlwaysOff:
- return false;
- }
-
- ASSERT_NOT_REACHED();
- return m_needsCompositedScrolling;
-}
-
RenderLayer* RenderLayer::scrollParent() const
{
if (!compositorDrivenAcceleratedScrollingEnabled())
return 0;
+ // Normal flow elements will be parented under the main scrolling layer, so
+ // we don't need a scroll parent/child relationship to get them to scroll.
+ if (stackingNode()->isNormalFlowOnly())
+ return 0;
+
// A layer scrolls with its containing block. So to find the overflow scrolling layer
// that we scroll with respect to, we must ascend the layer tree until we reach the
// first overflow scrolling div at or above our containing block. I will refer to this
@@ -2076,15 +1693,15 @@ RenderLayer* RenderLayer::scrollParent() const
// our scrolling ancestor, and we will therefore not scroll with it. In this case, we must
// be a composited layer since the compositor will need to take special measures to ensure
// that we scroll with our scrolling ancestor and it cannot do this if we do not promote.
- RenderLayer* scrollParent = ancestorScrollingLayer();
+ RenderLayer* scrollParent = ancestorCompositedScrollingLayer();
- if (!scrollParent || scrollParent->isStackingContext())
+ if (!scrollParent || scrollParent->stackingNode()->isStackingContainer())
return 0;
// If we hit a stacking context on our way up to the ancestor scrolling layer, it will already
// be composited due to an overflow scrolling parent, so we don't need to.
for (RenderLayer* ancestor = parent(); ancestor && ancestor != scrollParent; ancestor = ancestor->parent()) {
- if (ancestor->isStackingContext())
+ if (ancestor->stackingNode()->isStackingContainer())
return 0;
}
@@ -2104,841 +1721,59 @@ RenderLayer* RenderLayer::clipParent() const
return clipParent;
}
-void RenderLayer::updateNeedsCompositedScrolling()
-{
- TRACE_EVENT0("comp-scroll", "RenderLayer::updateNeedsCompositedScrolling");
-
- updateCanBeStackingContainer();
- updateDescendantDependentFlags();
-
- ASSERT(renderer()->view()->frameView() && renderer()->view()->frameView()->containsScrollableArea(scrollableArea()));
- bool needsCompositedScrolling = acceleratedCompositingForOverflowScrollEnabled()
- && canBeStackingContainer()
- && !hasUnclippedDescendant();
-
- // We gather a boolean value for use with Google UMA histograms to
- // quantify the actual effects of a set of patches attempting to
- // relax composited scrolling requirements, thereby increasing the
- // number of composited overflow divs.
- if (acceleratedCompositingForOverflowScrollEnabled())
- HistogramSupport::histogramEnumeration("Renderer.NeedsCompositedScrolling", needsCompositedScrolling, 2);
-
- setNeedsCompositedScrolling(needsCompositedScrolling);
-}
-
-enum CompositedScrollingHistogramBuckets {
- IsScrollableAreaBucket = 0,
- NeedsToBeStackingContainerBucket = 1,
- WillUseCompositedScrollingBucket = 2,
- CompositedScrollingHistogramMax = 3
-};
-
-void RenderLayer::setNeedsCompositedScrolling(bool needsCompositedScrolling)
-{
- if (m_needsCompositedScrolling == needsCompositedScrolling)
- return;
-
- // Count the total number of RenderLayers which need to be stacking
- // containers some point. This should be recorded at most once per
- // RenderLayer, so we check m_needsCompositedScrollingHasBeenRecorded.
- if (acceleratedCompositingForOverflowScrollEnabled() && !m_needsCompositedScrollingHasBeenRecorded) {
- HistogramSupport::histogramEnumeration("Renderer.CompositedScrolling", NeedsToBeStackingContainerBucket, CompositedScrollingHistogramMax);
- m_needsCompositedScrollingHasBeenRecorded = true;
- }
-
- // Count the total number of RenderLayers which need composited scrolling at
- // some point. This should be recorded at most once per RenderLayer, so we
- // check m_willUseCompositedScrollingHasBeenRecorded.
- //
- // FIXME: Currently, this computes the exact same value as the above.
- // However, it will soon be expanded to cover more than just stacking
- // containers (see crbug.com/249354). When this happens, we should see a
- // spike in "WillUseCompositedScrolling", while "NeedsToBeStackingContainer"
- // will remain relatively static.
- if (acceleratedCompositingForOverflowScrollEnabled() && !m_willUseCompositedScrollingHasBeenRecorded) {
- HistogramSupport::histogramEnumeration("Renderer.CompositedScrolling", WillUseCompositedScrollingBucket, CompositedScrollingHistogramMax);
- m_willUseCompositedScrollingHasBeenRecorded = true;
- }
-
- m_needsCompositedScrolling = needsCompositedScrolling;
-
- // Note, the z-order lists may need to be rebuilt, but our code guarantees
- // that we have not affected stacking, so we will not dirty
- // m_canBePromotedToStackingContainer for either us or our stacking context
- // or container.
- didUpdateNeedsCompositedScrolling();
-}
-
-void RenderLayer::setForceNeedsCompositedScrolling(RenderLayer::ForceNeedsCompositedScrollingMode mode)
-{
- if (m_forceNeedsCompositedScrolling == mode)
- return;
-
- m_forceNeedsCompositedScrolling = mode;
- didUpdateNeedsCompositedScrolling();
-}
-
void RenderLayer::didUpdateNeedsCompositedScrolling()
{
- updateIsNormalFlowOnly();
+ m_stackingNode->updateIsNormalFlowOnly();
updateSelfPaintingLayer();
- if (isStackingContainer())
- dirtyZOrderLists();
+ if (m_stackingNode->isStackingContainer())
+ m_stackingNode->dirtyZOrderLists();
else
- clearZOrderLists();
+ m_stackingNode->clearZOrderLists();
- dirtyStackingContainerZOrderLists();
+ m_stackingNode->dirtyStackingContainerZOrderLists();
- compositor()->setShouldReevaluateCompositingAfterLayout();
+ compositor()->setNeedsToRecomputeCompositingRequirements();
compositor()->setCompositingLayersNeedRebuild();
}
-static inline int adjustedScrollDelta(int beginningDelta) {
- // This implemention matches Firefox's.
- // http://mxr.mozilla.org/firefox/source/toolkit/content/widgets/browser.xml#856.
- const int speedReducer = 12;
-
- int adjustedDelta = beginningDelta / speedReducer;
- if (adjustedDelta > 1)
- adjustedDelta = static_cast<int>(adjustedDelta * sqrt(static_cast<double>(adjustedDelta))) - 1;
- else if (adjustedDelta < -1)
- adjustedDelta = static_cast<int>(adjustedDelta * sqrt(static_cast<double>(-adjustedDelta))) + 1;
-
- return adjustedDelta;
-}
-
-static inline IntSize adjustedScrollDelta(const IntSize& delta)
-{
- return IntSize(adjustedScrollDelta(delta.width()), adjustedScrollDelta(delta.height()));
-}
-
-void RenderLayer::panScrollFromPoint(const IntPoint& sourcePoint)
-{
- Frame* frame = renderer()->frame();
- if (!frame)
- return;
-
- IntPoint lastKnownMousePosition = frame->eventHandler()->lastKnownMousePosition();
-
- // We need to check if the last known mouse position is out of the window. When the mouse is out of the window, the position is incoherent
- static IntPoint previousMousePosition;
- if (lastKnownMousePosition.x() < 0 || lastKnownMousePosition.y() < 0)
- lastKnownMousePosition = previousMousePosition;
- else
- previousMousePosition = lastKnownMousePosition;
-
- IntSize delta = lastKnownMousePosition - sourcePoint;
-
- if (abs(delta.width()) <= ScrollView::noPanScrollRadius) // at the center we let the space for the icon
- delta.setWidth(0);
- if (abs(delta.height()) <= ScrollView::noPanScrollRadius)
- delta.setHeight(0);
-
- scrollByRecursively(adjustedScrollDelta(delta), ScrollOffsetClamped);
-}
-
-void RenderLayer::scrollByRecursively(const IntSize& delta, ScrollOffsetClamping clamp)
-{
- if (delta.isZero())
- return;
-
- bool restrictedByLineClamp = false;
- if (renderer()->parent())
- restrictedByLineClamp = !renderer()->parent()->style()->lineClamp().isNone();
-
- if (renderer()->hasOverflowClip() && !restrictedByLineClamp) {
- IntSize newScrollOffset = adjustedScrollOffset() + delta;
- m_scrollableArea->scrollToOffset(newScrollOffset, clamp);
-
- // If this layer can't do the scroll we ask the next layer up that can scroll to try
- IntSize remainingScrollOffset = newScrollOffset - adjustedScrollOffset();
- if (!remainingScrollOffset.isZero() && renderer()->parent()) {
- if (RenderLayer* scrollableLayer = enclosingScrollableLayer())
- scrollableLayer->scrollByRecursively(remainingScrollOffset, clamp);
-
- Frame* frame = renderer()->frame();
- if (frame && frame->page())
- frame->page()->updateAutoscrollRenderer();
- }
- } else if (renderer()->view()->frameView()) {
- // If we are here, we were called on a renderer that can be programmatically scrolled, but doesn't
- // have an overflow clip. Which means that it is a document node that can be scrolled.
- renderer()->view()->frameView()->scrollBy(delta);
-
- // FIXME: If we didn't scroll the whole way, do we want to try looking at the frames ownerElement?
- // https://bugs.webkit.org/show_bug.cgi?id=28237
- }
-}
-
-void RenderLayer::scrollToOffset(const IntSize& scrollOffset, ScrollOffsetClamping clamp)
-{
- m_scrollableArea->scrollToOffset(scrollOffset, clamp);
-}
-
-static inline bool frameElementAndViewPermitScroll(HTMLFrameElementBase* frameElementBase, FrameView* frameView)
-{
- // If scrollbars aren't explicitly forbidden, permit scrolling.
- if (frameElementBase && frameElementBase->scrollingMode() != ScrollbarAlwaysOff)
- return true;
-
- // If scrollbars are forbidden, user initiated scrolls should obviously be ignored.
- if (frameView->wasScrolledByUser())
- return false;
-
- // Forbid autoscrolls when scrollbars are off, but permits other programmatic scrolls,
- // like navigation to an anchor.
- Page* page = frameView->frame().page();
- if (!page)
- return false;
- return !page->autoscrollInProgress();
-}
-
-void RenderLayer::scrollRectToVisible(const LayoutRect& rect, const ScrollAlignment& alignX, const ScrollAlignment& alignY)
+void RenderLayer::updateReflectionInfo(const RenderStyle* oldStyle)
{
- RenderLayer* parentLayer = 0;
- LayoutRect newRect = rect;
-
- // We may end up propagating a scroll event. It is important that we suspend events until
- // the end of the function since they could delete the layer or the layer's renderer().
- FrameView* frameView = renderer()->document().view();
- if (frameView)
- frameView->pauseScheduledEvents();
-
- bool restrictedByLineClamp = false;
- if (renderer()->parent()) {
- parentLayer = renderer()->parent()->enclosingLayer();
- restrictedByLineClamp = !renderer()->parent()->style()->lineClamp().isNone();
+ if (renderer()->hasReflection()) {
+ if (!m_reflectionInfo)
+ m_reflectionInfo = adoptPtr(new RenderLayerReflectionInfo(toRenderBox(renderer())));
+ m_reflectionInfo->updateAfterStyleChange(oldStyle);
+ } else if (m_reflectionInfo) {
+ m_reflectionInfo = nullptr;
}
-
- if (renderer()->hasOverflowClip() && !restrictedByLineClamp) {
- // Don't scroll to reveal an overflow layer that is restricted by the -webkit-line-clamp property.
- // This will prevent us from revealing text hidden by the slider in Safari RSS.
- RenderBox* box = renderBox();
- ASSERT(box);
- LayoutRect localExposeRect(box->absoluteToLocalQuad(FloatQuad(FloatRect(rect)), UseTransforms).boundingBox());
- LayoutRect layerBounds(0, 0, box->clientWidth(), box->clientHeight());
- LayoutRect r = getRectToExpose(layerBounds, localExposeRect, alignX, alignY);
-
- IntSize clampedScrollOffset = m_scrollableArea->clampScrollOffset(adjustedScrollOffset() + toIntSize(roundedIntRect(r).location()));
- if (clampedScrollOffset != adjustedScrollOffset()) {
- IntSize oldScrollOffset = adjustedScrollOffset();
- m_scrollableArea->scrollToOffset(clampedScrollOffset);
- IntSize scrollOffsetDifference = adjustedScrollOffset() - oldScrollOffset;
- localExposeRect.move(-scrollOffsetDifference);
- newRect = LayoutRect(box->localToAbsoluteQuad(FloatQuad(FloatRect(localExposeRect)), UseTransforms).boundingBox());
- }
- } else if (!parentLayer && renderer()->isBox() && renderBox()->canBeProgramaticallyScrolled()) {
- if (frameView) {
- Element* ownerElement = renderer()->document().ownerElement();
-
- if (ownerElement && ownerElement->renderer()) {
- HTMLFrameElementBase* frameElementBase = 0;
-
- if (ownerElement->hasTagName(frameTag) || ownerElement->hasTagName(iframeTag))
- frameElementBase = toHTMLFrameElementBase(ownerElement);
-
- if (frameElementAndViewPermitScroll(frameElementBase, frameView)) {
- LayoutRect viewRect = frameView->visibleContentRect();
- LayoutRect exposeRect = getRectToExpose(viewRect, rect, alignX, alignY);
-
- int xOffset = roundToInt(exposeRect.x());
- int yOffset = roundToInt(exposeRect.y());
- // Adjust offsets if they're outside of the allowable range.
- xOffset = max(0, min(frameView->contentsWidth(), xOffset));
- yOffset = max(0, min(frameView->contentsHeight(), yOffset));
-
- frameView->setScrollPosition(IntPoint(xOffset, yOffset));
- if (frameView->safeToPropagateScrollToParent()) {
- parentLayer = ownerElement->renderer()->enclosingLayer();
- // FIXME: This doesn't correctly convert the rect to
- // absolute coordinates in the parent.
- newRect.setX(rect.x() - frameView->scrollX() + frameView->x());
- newRect.setY(rect.y() - frameView->scrollY() + frameView->y());
- } else
- parentLayer = 0;
- }
- } else {
- LayoutRect viewRect = frameView->visibleContentRect();
- LayoutRect r = getRectToExpose(viewRect, rect, alignX, alignY);
- frameView->setScrollPosition(roundedIntPoint(r.location()));
- }
- }
- }
-
- if (renderer()->frame()->page()->autoscrollInProgress())
- parentLayer = enclosingScrollableLayer();
-
- if (parentLayer)
- parentLayer->scrollRectToVisible(newRect, alignX, alignY);
-
- if (frameView)
- frameView->resumeScheduledEvents();
}
-void RenderLayer::updateCompositingLayersAfterScroll()
+void RenderLayer::updateStackingNode()
{
- if (compositor()->inCompositingMode()) {
- // Our stacking container is guaranteed to contain all of our descendants that may need
- // repositioning, so update compositing layers from there.
- if (RenderLayer* compositingAncestor = ancestorStackingContainer()->enclosingCompositingLayer()) {
- if (usesCompositedScrolling())
- compositor()->updateCompositingLayers(CompositingUpdateOnCompositedScroll, compositingAncestor);
- else
- compositor()->updateCompositingLayers(CompositingUpdateOnScroll, compositingAncestor);
- }
- }
-}
-
-LayoutRect RenderLayer::getRectToExpose(const LayoutRect &visibleRect, const LayoutRect &exposeRect, const ScrollAlignment& alignX, const ScrollAlignment& alignY)
-{
- // Determine the appropriate X behavior.
- ScrollBehavior scrollX;
- LayoutRect exposeRectX(exposeRect.x(), visibleRect.y(), exposeRect.width(), visibleRect.height());
- LayoutUnit intersectWidth = intersection(visibleRect, exposeRectX).width();
- if (intersectWidth == exposeRect.width() || intersectWidth >= MIN_INTERSECT_FOR_REVEAL)
- // If the rectangle is fully visible, use the specified visible behavior.
- // If the rectangle is partially visible, but over a certain threshold,
- // then treat it as fully visible to avoid unnecessary horizontal scrolling
- scrollX = ScrollAlignment::getVisibleBehavior(alignX);
- else if (intersectWidth == visibleRect.width()) {
- // If the rect is bigger than the visible area, don't bother trying to center. Other alignments will work.
- scrollX = ScrollAlignment::getVisibleBehavior(alignX);
- if (scrollX == alignCenter)
- scrollX = noScroll;
- } else if (intersectWidth > 0)
- // If the rectangle is partially visible, but not above the minimum threshold, use the specified partial behavior
- scrollX = ScrollAlignment::getPartialBehavior(alignX);
- else
- scrollX = ScrollAlignment::getHiddenBehavior(alignX);
- if (scrollX == alignToClosestEdge) {
- // Closest edge is the right in two cases:
- // (1) exposeRect to the right of and smaller than visibleRect
- // (2) exposeRect to the left of and larger than visibleRect
- if ((exposeRect.maxX() > visibleRect.maxX() && exposeRect.width() < visibleRect.width())
- || (exposeRect.maxX() < visibleRect.maxX() && exposeRect.width() > visibleRect.width())) {
- scrollX = alignRight;
- }
- }
-
- // Given the X behavior, compute the X coordinate.
- LayoutUnit x;
- if (scrollX == noScroll)
- x = visibleRect.x();
- else if (scrollX == alignRight)
- x = exposeRect.maxX() - visibleRect.width();
- else if (scrollX == alignCenter)
- x = exposeRect.x() + (exposeRect.width() - visibleRect.width()) / 2;
- else
- x = exposeRect.x();
-
- // Determine the appropriate Y behavior.
- ScrollBehavior scrollY;
- LayoutRect exposeRectY(visibleRect.x(), exposeRect.y(), visibleRect.width(), exposeRect.height());
- LayoutUnit intersectHeight = intersection(visibleRect, exposeRectY).height();
- if (intersectHeight == exposeRect.height())
- // If the rectangle is fully visible, use the specified visible behavior.
- scrollY = ScrollAlignment::getVisibleBehavior(alignY);
- else if (intersectHeight == visibleRect.height()) {
- // If the rect is bigger than the visible area, don't bother trying to center. Other alignments will work.
- scrollY = ScrollAlignment::getVisibleBehavior(alignY);
- if (scrollY == alignCenter)
- scrollY = noScroll;
- } else if (intersectHeight > 0)
- // If the rectangle is partially visible, use the specified partial behavior
- scrollY = ScrollAlignment::getPartialBehavior(alignY);
+ if (requiresStackingNode())
+ m_stackingNode = adoptPtr(new RenderLayerStackingNode(this));
else
- scrollY = ScrollAlignment::getHiddenBehavior(alignY);
- if (scrollY == alignToClosestEdge) {
- // Closest edge is the bottom in two cases:
- // (1) exposeRect below and smaller than visibleRect
- // (2) exposeRect above and larger than visibleRect
- if ((exposeRect.maxY() > visibleRect.maxY() && exposeRect.height() < visibleRect.height())
- || (exposeRect.maxY() < visibleRect.maxY() && exposeRect.height() > visibleRect.height())) {
- scrollY = alignBottom;
- }
- }
-
- // Given the Y behavior, compute the Y coordinate.
- LayoutUnit y;
- if (scrollY == noScroll)
- y = visibleRect.y();
- else if (scrollY == alignBottom)
- y = exposeRect.maxY() - visibleRect.height();
- else if (scrollY == alignCenter)
- y = exposeRect.y() + (exposeRect.height() - visibleRect.height()) / 2;
- else
- y = exposeRect.y();
-
- return LayoutRect(LayoutPoint(x, y), visibleRect.size());
-}
-
-void RenderLayer::autoscroll(const IntPoint& position)
-{
- Frame* frame = renderer()->frame();
- if (!frame)
- return;
-
- FrameView* frameView = frame->view();
- if (!frameView)
- return;
-
- IntPoint currentDocumentPosition = frameView->windowToContents(position);
- scrollRectToVisible(LayoutRect(currentDocumentPosition, LayoutSize(1, 1)), ScrollAlignment::alignToEdgeIfNeeded, ScrollAlignment::alignToEdgeIfNeeded);
-}
-
-void RenderLayer::resize(const PlatformEvent& evt, const LayoutSize& oldOffset)
-{
- // FIXME: This should be possible on generated content but is not right now.
- if (!inResizeMode() || !renderer()->canResize() || !renderer()->node())
- return;
-
- ASSERT(renderer()->node()->isElementNode());
- Element* element = toElement(renderer()->node());
- RenderBox* renderer = toRenderBox(element->renderer());
-
- Document& document = element->document();
-
- IntPoint pos;
- const PlatformGestureEvent* gevt = 0;
-
- switch (evt.type()) {
- case PlatformEvent::MouseMoved:
- if (!document.frame()->eventHandler()->mousePressed())
- return;
- pos = static_cast<const PlatformMouseEvent*>(&evt)->position();
- break;
- case PlatformEvent::GestureScrollUpdate:
- case PlatformEvent::GestureScrollUpdateWithoutPropagation:
- pos = static_cast<const PlatformGestureEvent*>(&evt)->position();
- gevt = static_cast<const PlatformGestureEvent*>(&evt);
- pos = gevt->position();
- pos.move(gevt->deltaX(), gevt->deltaY());
- break;
- default:
- ASSERT_NOT_REACHED();
- }
-
- float zoomFactor = renderer->style()->effectiveZoom();
-
- LayoutSize newOffset = offsetFromResizeCorner(document.view()->windowToContents(pos));
- newOffset.setWidth(newOffset.width() / zoomFactor);
- newOffset.setHeight(newOffset.height() / zoomFactor);
-
- LayoutSize currentSize = LayoutSize(renderer->width() / zoomFactor, renderer->height() / zoomFactor);
- LayoutSize minimumSize = element->minimumSizeForResizing().shrunkTo(currentSize);
- element->setMinimumSizeForResizing(minimumSize);
-
- LayoutSize adjustedOldOffset = LayoutSize(oldOffset.width() / zoomFactor, oldOffset.height() / zoomFactor);
- if (renderer->style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft()) {
- newOffset.setWidth(-newOffset.width());
- adjustedOldOffset.setWidth(-adjustedOldOffset.width());
- }
-
- LayoutSize difference = (currentSize + newOffset - adjustedOldOffset).expandedTo(minimumSize) - currentSize;
-
- bool isBoxSizingBorder = renderer->style()->boxSizing() == BORDER_BOX;
-
- EResize resize = renderer->style()->resize();
- if (resize != RESIZE_VERTICAL && difference.width()) {
- if (element->isFormControlElement()) {
- // Make implicit margins from the theme explicit (see <http://bugs.webkit.org/show_bug.cgi?id=9547>).
- element->setInlineStyleProperty(CSSPropertyMarginLeft, renderer->marginLeft() / zoomFactor, CSSPrimitiveValue::CSS_PX);
- element->setInlineStyleProperty(CSSPropertyMarginRight, renderer->marginRight() / zoomFactor, CSSPrimitiveValue::CSS_PX);
- }
- LayoutUnit baseWidth = renderer->width() - (isBoxSizingBorder ? LayoutUnit() : renderer->borderAndPaddingWidth());
- baseWidth = baseWidth / zoomFactor;
- element->setInlineStyleProperty(CSSPropertyWidth, roundToInt(baseWidth + difference.width()), CSSPrimitiveValue::CSS_PX);
- }
-
- if (resize != RESIZE_HORIZONTAL && difference.height()) {
- if (element->isFormControlElement()) {
- // Make implicit margins from the theme explicit (see <http://bugs.webkit.org/show_bug.cgi?id=9547>).
- element->setInlineStyleProperty(CSSPropertyMarginTop, renderer->marginTop() / zoomFactor, CSSPrimitiveValue::CSS_PX);
- element->setInlineStyleProperty(CSSPropertyMarginBottom, renderer->marginBottom() / zoomFactor, CSSPrimitiveValue::CSS_PX);
- }
- LayoutUnit baseHeight = renderer->height() - (isBoxSizingBorder ? LayoutUnit() : renderer->borderAndPaddingHeight());
- baseHeight = baseHeight / zoomFactor;
- element->setInlineStyleProperty(CSSPropertyHeight, roundToInt(baseHeight + difference.height()), CSSPrimitiveValue::CSS_PX);
- }
-
- document.updateLayout();
-
- // FIXME (Radar 4118564): We should also autoscroll the window as necessary to keep the point under the cursor in view.
-}
-
-int RenderLayer::scrollSize(ScrollbarOrientation orientation) const
-{
- IntSize scrollDimensions = scrollableArea()->maximumScrollPosition() - scrollableArea()->minimumScrollPosition();
- return (orientation == HorizontalScrollbar) ? scrollDimensions.width() : scrollDimensions.height();
-}
-
-IntSize RenderLayer::overhangAmount() const
-{
- return IntSize();
-}
-
-bool RenderLayer::isActive() const
-{
- Page* page = renderer()->frame()->page();
- return page && page->focusController().isActive();
-}
-
-static int cornerStart(const RenderStyle* style, int minX, int maxX, int thickness)
-{
- if (style->shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
- return minX + style->borderLeftWidth();
- return maxX - thickness - style->borderRightWidth();
-}
-
-static IntRect cornerRect(const RenderStyle* style, const Scrollbar* horizontalScrollbar, const Scrollbar* verticalScrollbar, const IntRect& bounds)
-{
- int horizontalThickness;
- int verticalThickness;
- if (!verticalScrollbar && !horizontalScrollbar) {
- // FIXME: This isn't right. We need to know the thickness of custom scrollbars
- // even when they don't exist in order to set the resizer square size properly.
- horizontalThickness = ScrollbarTheme::theme()->scrollbarThickness();
- verticalThickness = horizontalThickness;
- } else if (verticalScrollbar && !horizontalScrollbar) {
- horizontalThickness = verticalScrollbar->width();
- verticalThickness = horizontalThickness;
- } else if (horizontalScrollbar && !verticalScrollbar) {
- verticalThickness = horizontalScrollbar->height();
- horizontalThickness = verticalThickness;
- } else {
- horizontalThickness = verticalScrollbar->width();
- verticalThickness = horizontalScrollbar->height();
- }
- return IntRect(cornerStart(style, bounds.x(), bounds.maxX(), horizontalThickness),
- bounds.maxY() - verticalThickness - style->borderBottomWidth(),
- horizontalThickness, verticalThickness);
-}
-
-IntRect RenderLayer::scrollCornerRect() const
-{
- // We have a scrollbar corner when a scrollbar is visible and not filling the entire length of the box.
- // This happens when:
- // (a) A resizer is present and at least one scrollbar is present
- // (b) Both scrollbars are present.
- bool hasHorizontalBar = horizontalScrollbar();
- bool hasVerticalBar = verticalScrollbar();
- bool hasResizer = renderer()->style()->resize() != RESIZE_NONE;
- if ((hasHorizontalBar && hasVerticalBar) || (hasResizer && (hasHorizontalBar || hasVerticalBar)))
- return cornerRect(renderer()->style(), horizontalScrollbar(), verticalScrollbar(), renderBox()->pixelSnappedBorderBoxRect());
- return IntRect();
-}
-
-IntRect RenderLayer::resizerCornerRect(const IntRect& bounds, ResizerHitTestType resizerHitTestType) const
-{
- ASSERT(renderer()->isBox());
- if (renderer()->style()->resize() == RESIZE_NONE)
- return IntRect();
- IntRect corner = cornerRect(renderer()->style(), horizontalScrollbar(), verticalScrollbar(), bounds);
-
- if (resizerHitTestType == ResizerForTouch) {
- // We make the resizer virtually larger for touch hit testing. With the
- // expanding ratio k = ResizerControlExpandRatioForTouch, we first move
- // the resizer rect (of width w & height h), by (-w * (k-1), -h * (k-1)),
- // then expand the rect by new_w/h = w/h * k.
- int expand_ratio = ResizerControlExpandRatioForTouch - 1;
- corner.move(-corner.width() * expand_ratio, -corner.height() * expand_ratio);
- corner.expand(corner.width() * expand_ratio, corner.height() * expand_ratio);
- }
-
- return corner;
-}
-
-IntRect RenderLayer::scrollCornerAndResizerRect() const
-{
- RenderBox* box = renderBox();
- if (!box)
- return IntRect();
- IntRect scrollCornerAndResizer = scrollCornerRect();
- if (scrollCornerAndResizer.isEmpty())
- scrollCornerAndResizer = resizerCornerRect(box->pixelSnappedBorderBoxRect(), ResizerForPointer);
- return scrollCornerAndResizer;
-}
-
-bool RenderLayer::isScrollCornerVisible() const
-{
- ASSERT(renderer()->isBox());
- return !scrollCornerRect().isEmpty();
-}
-
-int RenderLayer::visibleHeight() const
-{
- return m_layerSize.height();
-}
-
-int RenderLayer::visibleWidth() const
-{
- return m_layerSize.width();
+ m_stackingNode = nullptr;
}
-bool RenderLayer::shouldSuspendScrollAnimations() const
+void RenderLayer::updateScrollableArea()
{
- RenderView* view = renderer()->view();
- if (!view)
- return true;
- return view->frameView()->shouldSuspendScrollAnimations();
-}
-
-bool RenderLayer::scrollbarsCanBeActive() const
-{
- RenderView* view = renderer()->view();
- if (!view)
- return false;
- return view->frameView()->scrollbarsCanBeActive();
-}
-
-IntPoint RenderLayer::lastKnownMousePosition() const
-{
- return renderer()->frame() ? renderer()->frame()->eventHandler()->lastKnownMousePosition() : IntPoint();
-}
-
-void RenderLayer::invalidateScrollCornerRect(const IntRect& rect)
-{
- if (m_resizer)
- m_resizer->repaintRectangle(rect);
-}
-
-// FIXME: This function is temporarily duplicated in RenderLayerScrollableArea.
-static inline RenderObject* rendererForScrollbar(RenderObject* renderer)
-{
- if (Node* node = renderer->node()) {
- if (ShadowRoot* shadowRoot = node->containingShadowRoot()) {
- if (shadowRoot->type() == ShadowRoot::UserAgentShadowRoot)
- return shadowRoot->host()->renderer();
- }
- }
-
- return renderer;
-}
-
-ScrollableArea* RenderLayer::enclosingScrollableArea() const
-{
- if (RenderLayer* scrollableLayer = enclosingScrollableLayer())
- return scrollableLayer->scrollableArea();
-
- // FIXME: We should return the frame view here (or possibly an ancestor frame view,
- // if the frame view isn't scrollable.
- return 0;
+ if (requiresScrollableArea())
+ m_scrollableArea = adoptPtr(new RenderLayerScrollableArea(renderBox()));
+ else
+ m_scrollableArea = nullptr;
}
-IntSize RenderLayer::offsetFromResizeCorner(const IntPoint& absolutePoint) const
+PassOwnPtr<Vector<FloatRect> > RenderLayer::collectTrackedRepaintRects() const
{
- // Currently the resize corner is either the bottom right corner or the bottom left corner.
- // FIXME: This assumes the location is 0, 0. Is this guaranteed to always be the case?
- IntSize elementSize = size();
- if (renderer()->style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
- elementSize.setWidth(0);
- IntPoint resizerPoint = IntPoint(elementSize);
- IntPoint localPoint = roundedIntPoint(absoluteToContents(absolutePoint));
- return localPoint - resizerPoint;
+ if (hasCompositedLayerMapping())
+ return compositedLayerMapping()->collectTrackedRepaintRects();
+ return nullptr;
}
bool RenderLayer::hasOverflowControls() const
{
- return m_scrollableArea->hasScrollbar() || m_scrollableArea->hasScrollCorner() || renderer()->style()->resize() != RESIZE_NONE;
-}
-
-void RenderLayer::positionOverflowControls(const IntSize& offsetFromRoot)
-{
- if (!m_scrollableArea->hasScrollbar() && !renderer()->canResize())
- return;
-
- RenderBox* box = renderBox();
- if (!box)
- return;
-
- m_scrollableArea->positionOverflowControls(offsetFromRoot);
-
- const IntRect borderBox = box->pixelSnappedBorderBoxRect();
- if (m_resizer)
- m_resizer->setFrameRect(resizerCornerRect(borderBox, ResizerForPointer));
-
- if (isComposited())
- backing()->positionOverflowControlsLayers(offsetFromRoot);
-}
-
-int RenderLayer::scrollWidth() const
-{
- return m_scrollableArea->scrollWidth();
-}
-
-int RenderLayer::scrollHeight() const
-{
- return m_scrollableArea->scrollHeight();
-}
-
-void RenderLayer::updateScrollInfoAfterLayout()
-{
- RenderBox* box = renderBox();
- if (!box)
- return;
-
- m_scrollableArea->updateAfterLayout();
-
- // Composited scrolling may need to be enabled or disabled if the amount of overflow changed.
- if (renderer()->view() && compositor()->updateLayerCompositingState(this))
- compositor()->setCompositingLayersNeedRebuild();
-}
-
-bool RenderLayer::overflowControlsIntersectRect(const IntRect& localRect) const
-{
- const IntRect borderBox = renderBox()->pixelSnappedBorderBoxRect();
-
- if (m_scrollableArea->rectForHorizontalScrollbar(borderBox).intersects(localRect))
- return true;
-
- if (m_scrollableArea->rectForVerticalScrollbar(borderBox).intersects(localRect))
- return true;
-
- if (scrollCornerRect().intersects(localRect))
- return true;
-
- if (resizerCornerRect(borderBox, ResizerForPointer).intersects(localRect))
- return true;
-
- return false;
-}
-
-void RenderLayer::paintOverflowControls(GraphicsContext* context, const IntPoint& paintOffset, const IntRect& damageRect, bool paintingOverlayControls)
-{
- // Don't do anything if we have no overflow.
- if (!renderer()->hasOverflowClip())
- return;
-
- IntPoint adjustedPaintOffset = paintOffset;
- if (paintingOverlayControls)
- adjustedPaintOffset = m_cachedOverlayScrollbarOffset;
-
- // Move the scrollbar widgets if necessary. We normally move and resize widgets during layout, but sometimes
- // widgets can move without layout occurring (most notably when you scroll a document that
- // contains fixed positioned elements).
- positionOverflowControls(toIntSize(adjustedPaintOffset));
-
- m_scrollableArea->paintOverflowControls(context, paintOffset, damageRect, paintingOverlayControls);
-
- if (layerForScrollCorner())
- return;
-
- // Paint our resizer last, since it sits on top of the scroll corner.
- paintResizer(context, adjustedPaintOffset, damageRect);
-}
-
-void RenderLayer::paintScrollCorner(GraphicsContext* context, const IntPoint& paintOffset, const IntRect& damageRect)
-{
- m_scrollableArea->paintScrollCorner(context, paintOffset, damageRect);
-}
-
-void RenderLayer::drawPlatformResizerImage(GraphicsContext* context, IntRect resizerCornerRect)
-{
- float deviceScaleFactor = WebCore::deviceScaleFactor(renderer()->frame());
-
- RefPtr<Image> resizeCornerImage;
- IntSize cornerResizerSize;
- if (deviceScaleFactor >= 2) {
- DEFINE_STATIC_LOCAL(Image*, resizeCornerImageHiRes, (Image::loadPlatformResource("textAreaResizeCorner@2x").leakRef()));
- resizeCornerImage = resizeCornerImageHiRes;
- cornerResizerSize = resizeCornerImage->size();
- cornerResizerSize.scale(0.5f);
- } else {
- DEFINE_STATIC_LOCAL(Image*, resizeCornerImageLoRes, (Image::loadPlatformResource("textAreaResizeCorner").leakRef()));
- resizeCornerImage = resizeCornerImageLoRes;
- cornerResizerSize = resizeCornerImage->size();
- }
-
- if (renderer()->style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft()) {
- context->save();
- context->translate(resizerCornerRect.x() + cornerResizerSize.width(), resizerCornerRect.y() + resizerCornerRect.height() - cornerResizerSize.height());
- context->scale(FloatSize(-1.0, 1.0));
- context->drawImage(resizeCornerImage.get(), IntRect(IntPoint(), cornerResizerSize));
- context->restore();
- return;
- }
- IntRect imageRect(resizerCornerRect.maxXMaxYCorner() - cornerResizerSize, cornerResizerSize);
- context->drawImage(resizeCornerImage.get(), imageRect);
-}
-
-void RenderLayer::paintResizer(GraphicsContext* context, const IntPoint& paintOffset, const IntRect& damageRect)
-{
- if (renderer()->style()->resize() == RESIZE_NONE)
- return;
-
- RenderBox* box = renderBox();
- ASSERT(box);
-
- IntRect absRect = resizerCornerRect(box->pixelSnappedBorderBoxRect(), ResizerForPointer);
- absRect.moveBy(paintOffset);
- if (!absRect.intersects(damageRect))
- return;
-
- if (context->updatingControlTints()) {
- updateResizerStyle();
- return;
- }
-
- if (m_resizer) {
- m_resizer->paintIntoRect(context, paintOffset, absRect);
- return;
- }
-
- drawPlatformResizerImage(context, absRect);
-
- // Draw a frame around the resizer (1px grey line) if there are any scrollbars present.
- // Clipping will exclude the right and bottom edges of this frame.
- if (!hasOverlayScrollbars() && m_scrollableArea->hasScrollbar()) {
- GraphicsContextStateSaver stateSaver(*context);
- context->clip(absRect);
- IntRect largerCorner = absRect;
- largerCorner.setSize(IntSize(largerCorner.width() + 1, largerCorner.height() + 1));
- context->setStrokeColor(Color(217, 217, 217));
- context->setStrokeThickness(1.0f);
- context->setFillColor(Color::transparent);
- context->drawRect(largerCorner);
- }
-}
-
-bool RenderLayer::isPointInResizeControl(const IntPoint& absolutePoint,
- ResizerHitTestType resizerHitTestType) const
-{
- if (!renderer()->canResize())
- return false;
-
- RenderBox* box = renderBox();
- ASSERT(box);
-
- IntPoint localPoint = roundedIntPoint(absoluteToContents(absolutePoint));
- IntRect localBounds (0, 0, box->pixelSnappedWidth(), box->pixelSnappedHeight());
- return resizerCornerRect(localBounds, resizerHitTestType).contains(localPoint);
-}
-
-bool RenderLayer::hitTestOverflowControls(HitTestResult& result, const IntPoint& localPoint)
-{
- if (!m_scrollableArea->hasScrollbar() && !renderer()->canResize())
- return false;
-
- RenderBox* box = renderBox();
- ASSERT(box);
-
- IntRect resizeControlRect;
- if (renderer()->style()->resize() != RESIZE_NONE) {
- resizeControlRect = resizerCornerRect(box->pixelSnappedBorderBoxRect(), ResizerForPointer);
- if (resizeControlRect.contains(localPoint))
- return true;
- }
-
- return m_scrollableArea->hitTestOverflowControls(result, localPoint, resizeControlRect);
-}
-
-bool RenderLayer::scroll(ScrollDirection direction, ScrollGranularity granularity, float multiplier)
-{
- if (ScrollableArea* scrollableArea = this->scrollableArea())
- return scrollableArea->scroll(direction, granularity, multiplier);
-
- return false;
+ return m_scrollableArea && (m_scrollableArea->hasScrollbar() || m_scrollableArea->hasScrollCorner() || renderer()->style()->resize() != RESIZE_NONE);
}
void RenderLayer::paint(GraphicsContext* context, const LayoutRect& damageRect, PaintBehavior paintBehavior, RenderObject* paintingRoot, RenderRegion* region, PaintLayerFlags paintFlags)
@@ -3043,22 +1878,22 @@ static inline bool shouldSuppressPaintingLayer(RenderLayer* layer)
return false;
}
-static bool paintForFixedRootBackground(const RenderLayer* layer, RenderLayer::PaintLayerFlags paintFlags)
+static bool paintForFixedRootBackground(const RenderLayer* layer, PaintLayerFlags paintFlags)
{
- return layer->renderer()->isRoot() && (paintFlags & RenderLayer::PaintLayerPaintingRootBackgroundOnly);
+ return layer->renderer()->isRoot() && (paintFlags & PaintLayerPaintingRootBackgroundOnly);
}
void RenderLayer::paintLayer(GraphicsContext* context, const LayerPaintingInfo& paintingInfo, PaintLayerFlags paintFlags)
{
- if (isComposited()) {
+ if (compositingState() != NotComposited && compositingState() != PaintsIntoGroupedBacking) {
// The updatingControlTints() painting pass goes through compositing layers,
// but we need to ensure that we don't cache clip rects computed with the wrong root in this case.
if (context->updatingControlTints() || (paintingInfo.paintBehavior & PaintBehaviorFlattenCompositingLayers)) {
paintFlags |= PaintLayerTemporaryClipRects;
- } else if (!backing()->paintsIntoCompositedAncestor()
+ } else if (!compositedLayerMapping()->paintsIntoCompositedAncestor()
&& !shouldDoSoftwarePaint(this, paintFlags & PaintLayerPaintingReflection)
&& !paintForFixedRootBackground(this, paintFlags)) {
- // If this RenderLayer should paint into its backing, that will be done via RenderLayerBacking::paintIntoLayer().
+ // If this RenderLayer should paint into its own backing, that will be done via CompositedLayerMapping::paintIntoLayer().
return;
}
} else if (viewportConstrainedNotCompositedReason() == NotCompositedForBoundsOutOfView) {
@@ -3133,12 +1968,8 @@ void RenderLayer::paintLayerContentsAndReflection(GraphicsContext* context, cons
PaintLayerFlags localPaintFlags = paintFlags & ~(PaintLayerAppliedTransform);
// Paint the reflection first if we have one.
- if (m_reflection && !m_paintingInsideReflection) {
- // Mark that we are now inside replica painting.
- m_paintingInsideReflection = true;
- reflectionLayer()->paintLayer(context, paintingInfo, localPaintFlags | PaintLayerPaintingReflection);
- m_paintingInsideReflection = false;
- }
+ if (m_reflectionInfo)
+ m_reflectionInfo->paint(context, paintingInfo, localPaintFlags | PaintLayerPaintingReflection);
localPaintFlags |= PaintLayerPaintingCompositingAllPhases;
paintLayerContents(context, paintingInfo, localPaintFlags);
@@ -3176,7 +2007,7 @@ void RenderLayer::paintLayerContents(GraphicsContext* context, const LayerPainti
return;
// Ensure our lists are up-to-date.
- updateLayerListsIfNeeded();
+ m_stackingNode->updateLayerListsIfNeeded();
LayoutPoint offsetFromRoot;
convertToLayerCoords(paintingInfo.rootLayer, offsetFromRoot);
@@ -3191,10 +2022,10 @@ void RenderLayer::paintLayerContents(GraphicsContext* context, const LayerPainti
ClipperContext clipperContext;
if (renderer()->hasClipPath() && !context->paintingDisabled() && style) {
ASSERT(style->clipPath());
- if (style->clipPath()->getOperationType() == ClipPathOperation::SHAPE) {
+ if (style->clipPath()->type() == ClipPathOperation::SHAPE) {
hasClipPath = true;
context->save();
- ShapeClipPathOperation* clipPath = static_cast<ShapeClipPathOperation*>(style->clipPath());
+ ShapeClipPathOperation* clipPath = toShapeClipPathOperation(style->clipPath());
if (!rootRelativeBoundsComputed) {
rootRelativeBounds = calculateLayerBounds(paintingInfo.rootLayer, &offsetFromRoot, 0);
@@ -3202,8 +2033,8 @@ void RenderLayer::paintLayerContents(GraphicsContext* context, const LayerPainti
}
context->clipPath(clipPath->path(rootRelativeBounds), clipPath->windRule());
- } else if (style->clipPath()->getOperationType() == ClipPathOperation::REFERENCE) {
- ReferenceClipPathOperation* referenceClipPathOperation = static_cast<ReferenceClipPathOperation*>(style->clipPath());
+ } else if (style->clipPath()->type() == ClipPathOperation::REFERENCE) {
+ ReferenceClipPathOperation* referenceClipPathOperation = toReferenceClipPathOperation(style->clipPath());
Document& document = renderer()->document();
// FIXME: It doesn't work with forward or external SVG references (https://bugs.webkit.org/show_bug.cgi?id=90405)
Element* element = document.getElementById(referenceClipPathOperation->fragment());
@@ -3213,7 +2044,7 @@ void RenderLayer::paintLayerContents(GraphicsContext* context, const LayerPainti
rootRelativeBoundsComputed = true;
}
- resourceClipper = toRenderSVGResourceClipper(element->renderer()->toRenderSVGResourceContainer());
+ resourceClipper = toRenderSVGResourceClipper(toRenderSVGResourceContainer(element->renderer()));
if (!resourceClipper->applyClippingToContext(renderer(), rootRelativeBounds,
paintingInfo.paintDirtyRect, context, clipperContext)) {
// No need to post-apply the clipper if this failed.
@@ -3223,6 +2054,13 @@ void RenderLayer::paintLayerContents(GraphicsContext* context, const LayerPainti
}
}
+ // Blending operations must be performed only with the nearest ancestor stacking context.
+ // Note that there is no need to create a transparency layer if we're painting the root.
+ bool createTransparencyLayerForBlendMode = !renderer()->isRoot() && m_stackingNode->isStackingContext() && m_childLayerHasBlendMode;
+
+ if (createTransparencyLayerForBlendMode)
+ beginTransparencyLayers(context, paintingInfo.rootLayer, paintingInfo.paintDirtyRect, paintingInfo.paintBehavior);
+
LayerPaintingInfo localPaintingInfo(paintingInfo);
FilterEffectRendererHelper filterPainter(filterRenderer() && paintsWithFilters());
if (filterPainter.haveFilterEffect() && !context->paintingDisabled()) {
@@ -3282,6 +2120,7 @@ void RenderLayer::paintLayerContents(GraphicsContext* context, const LayerPainti
bool shouldPaintNormalFlowAndPosZOrderLists = isPaintingCompositedForeground;
bool shouldPaintOverlayScrollbars = isPaintingOverlayScrollbars;
bool shouldPaintMask = (paintFlags & PaintLayerPaintingCompositingMaskPhase) && shouldPaintContent && renderer()->hasMask() && !selectionOnly;
+ bool shouldPaintClippingMask = (paintFlags & PaintLayerPaintingChildClippingMaskPhase) && shouldPaintContent && !selectionOnly;
PaintBehavior paintBehavior = PaintBehaviorNormal;
if (paintFlags & PaintLayerPaintingSkipRootBackground)
@@ -3304,7 +2143,7 @@ void RenderLayer::paintLayerContents(GraphicsContext* context, const LayerPainti
localPaintingInfo, paintBehavior, paintingRootForRenderer);
if (shouldPaintNegZOrderList)
- paintList(negZOrderList(), context, localPaintingInfo, paintFlags);
+ paintChildren(NegativeZOrderChildren, context, localPaintingInfo, paintFlags);
if (shouldPaintOwnContents)
paintForegroundForFragments(layerFragments, context, transparencyLayerContext, paintingInfo.paintDirtyRect, haveTransparency,
@@ -3314,10 +2153,7 @@ void RenderLayer::paintLayerContents(GraphicsContext* context, const LayerPainti
paintOutlineForFragments(layerFragments, context, localPaintingInfo, paintBehavior, paintingRootForRenderer);
if (shouldPaintNormalFlowAndPosZOrderLists)
- paintList(m_normalFlowList.get(), context, localPaintingInfo, paintFlags);
-
- if (shouldPaintNormalFlowAndPosZOrderLists)
- paintList(posZOrderList(), context, localPaintingInfo, paintFlags);
+ paintChildren(NormalFlowChildren | PositiveZOrderChildren, context, localPaintingInfo, paintFlags);
if (shouldPaintOverlayScrollbars)
paintOverflowControlsForFragments(layerFragments, context, localPaintingInfo);
@@ -3337,8 +2173,13 @@ void RenderLayer::paintLayerContents(GraphicsContext* context, const LayerPainti
if (shouldPaintMask)
paintMaskForFragments(layerFragments, context, localPaintingInfo, paintingRootForRenderer);
+ if (shouldPaintClippingMask) {
+ // Paint the border radius mask for the fragments.
+ paintChildClippingMaskForFragments(layerFragments, context, localPaintingInfo, paintingRootForRenderer);
+ }
+
// End our transparency layer
- if (haveTransparency && m_usedTransparency && !m_paintingInsideReflection) {
+ if ((haveTransparency || paintsWithBlendMode() || createTransparencyLayerForBlendMode) && m_usedTransparency && !(m_reflectionInfo && m_reflectionInfo->isPaintingInsideReflection())) {
context->endLayer();
context->restore();
m_usedTransparency = false;
@@ -3373,20 +2214,23 @@ void RenderLayer::paintLayerByApplyingTransform(GraphicsContext* context, const
paintLayerContentsAndReflection(context, transformedPaintingInfo, paintFlags);
}
-void RenderLayer::paintList(Vector<RenderLayer*>* list, GraphicsContext* context, const LayerPaintingInfo& paintingInfo, PaintLayerFlags paintFlags)
+void RenderLayer::paintChildren(unsigned childrenToVisit, GraphicsContext* context, const LayerPaintingInfo& paintingInfo, PaintLayerFlags paintFlags)
{
- if (!list)
- return;
-
if (!hasSelfPaintingLayerDescendant())
return;
#if !ASSERT_DISABLED
- LayerListMutationDetector mutationChecker(this);
+ LayerListMutationDetector mutationChecker(m_stackingNode.get());
#endif
- for (size_t i = 0; i < list->size(); ++i) {
- RenderLayer* childLayer = list->at(i);
+ RenderLayerStackingNodeIterator iterator(*m_stackingNode, childrenToVisit);
+ while (RenderLayerStackingNode* child = iterator.next()) {
+ RenderLayer* childLayer = child->layer();
+
+ // Squashed RenderLayers should not paint into their ancestor.
+ if (childLayer->compositingState() == PaintsIntoGroupedBacking)
+ continue;
+
if (!childLayer->isPaginated())
childLayer->paintLayer(context, paintingInfo, paintFlags);
else
@@ -3523,7 +2367,7 @@ void RenderLayer::paintBackgroundForFragments(const LayerFragments& layerFragmen
continue;
// Begin transparency layers lazily now that we know we have to paint something.
- if (haveTransparency)
+ if (haveTransparency || paintsWithBlendMode())
beginTransparencyLayers(transparencyLayerContext, localPaintingInfo.rootLayer, transparencyPaintDirtyRect, localPaintingInfo.paintBehavior);
if (localPaintingInfo.clipToDirtyRect) {
@@ -3547,7 +2391,7 @@ void RenderLayer::paintForegroundForFragments(const LayerFragments& layerFragmen
RenderObject* paintingRootForRenderer, bool selectionOnly, bool forceBlackText)
{
// Begin transparency if we have something to paint.
- if (haveTransparency) {
+ if (haveTransparency || paintsWithBlendMode()) {
for (size_t i = 0; i < layerFragments.size(); ++i) {
const LayerFragment& fragment = layerFragments.at(i);
if (fragment.shouldPaintContent && !fragment.foregroundRect.isEmpty()) {
@@ -3639,13 +2483,33 @@ void RenderLayer::paintMaskForFragments(const LayerFragments& layerFragments, Gr
}
}
+void RenderLayer::paintChildClippingMaskForFragments(const LayerFragments& layerFragments, GraphicsContext* context, const LayerPaintingInfo& localPaintingInfo,
+ RenderObject* paintingRootForRenderer)
+{
+ for (size_t i = 0; i < layerFragments.size(); ++i) {
+ const LayerFragment& fragment = layerFragments.at(i);
+ if (!fragment.shouldPaintContent)
+ continue;
+
+ if (localPaintingInfo.clipToDirtyRect)
+ clipToRect(localPaintingInfo.rootLayer, context, localPaintingInfo.paintDirtyRect, fragment.foregroundRect, IncludeSelfForBorderRadius); // Child clipping mask painting will handle clipping to self.
+
+ // Paint the the clipped mask.
+ PaintInfo paintInfo(context, pixelSnappedIntRect(fragment.backgroundRect.rect()), PaintPhaseClippingMask, PaintBehaviorNormal, paintingRootForRenderer, localPaintingInfo.region, 0, 0, localPaintingInfo.rootLayer->renderer());
+ renderer()->paint(paintInfo, toPoint(fragment.layerBounds.location() - renderBoxLocation() + localPaintingInfo.subPixelAccumulation));
+
+ if (localPaintingInfo.clipToDirtyRect)
+ restoreClip(context, localPaintingInfo.paintDirtyRect, fragment.foregroundRect);
+ }
+}
+
void RenderLayer::paintOverflowControlsForFragments(const LayerFragments& layerFragments, GraphicsContext* context, const LayerPaintingInfo& localPaintingInfo)
{
for (size_t i = 0; i < layerFragments.size(); ++i) {
const LayerFragment& fragment = layerFragments.at(i);
clipToRect(localPaintingInfo.rootLayer, context, localPaintingInfo.paintDirtyRect, fragment.backgroundRect);
- paintOverflowControls(context, roundedIntPoint(toPoint(fragment.layerBounds.location() - renderBoxLocation() + localPaintingInfo.subPixelAccumulation)),
- pixelSnappedIntRect(fragment.backgroundRect.rect()), true);
+ if (RenderLayerScrollableArea* scrollableArea = this->scrollableArea())
+ scrollableArea->paintOverflowControls(context, roundedIntPoint(toPoint(fragment.layerBounds.location() - renderBoxLocation() + localPaintingInfo.subPixelAccumulation)), pixelSnappedIntRect(fragment.backgroundRect.rect()), true);
restoreClip(context, localPaintingInfo.paintDirtyRect, fragment.backgroundRect);
}
}
@@ -3654,11 +2518,11 @@ void RenderLayer::paintPaginatedChildLayer(RenderLayer* childLayer, GraphicsCont
{
// We need to do multiple passes, breaking up our child layer into strips.
Vector<RenderLayer*> columnLayers;
- RenderLayer* ancestorLayer = isNormalFlowOnly() ? parent() : ancestorStackingContainer();
+ RenderLayerStackingNode* ancestorNode = m_stackingNode->isNormalFlowOnly() ? parent()->stackingNode() : m_stackingNode->ancestorStackingContainerNode();
for (RenderLayer* curr = childLayer->parent(); curr; curr = curr->parent()) {
if (curr->renderer()->hasColumns() && checkContainingBlockChainForPagination(childLayer->renderer(), curr->renderBox()))
columnLayers.append(curr);
- if (curr == ancestorLayer)
+ if (curr->stackingNode() == ancestorNode)
break;
}
@@ -3947,7 +2811,7 @@ RenderLayer* RenderLayer::hitTestLayer(RenderLayer* rootLayer, RenderLayer* cont
}
// Ensure our lists and 3d status are up-to-date.
- updateLayerListsIfNeeded();
+ m_stackingNode->updateLayerListsIfNeeded();
update3DTransformedDescendantStatus();
RefPtr<HitTestingTransformState> localTransformState;
@@ -4003,7 +2867,7 @@ RenderLayer* RenderLayer::hitTestLayer(RenderLayer* rootLayer, RenderLayer* cont
RenderLayer* candidateLayer = 0;
// Begin by walking our list of positive layers from highest z-index down to the lowest z-index.
- RenderLayer* hitLayer = hitTestList(posZOrderList(), rootLayer, request, result, hitTestRect, hitTestLocation,
+ RenderLayer* hitLayer = hitTestChildren(PositiveZOrderChildren, rootLayer, request, result, hitTestRect, hitTestLocation,
localTransformState.get(), zOffsetForDescendantsPtr, zOffset, unflattenedTransformState.get(), depthSortDescendants);
if (hitLayer) {
if (!depthSortDescendants)
@@ -4012,7 +2876,7 @@ RenderLayer* RenderLayer::hitTestLayer(RenderLayer* rootLayer, RenderLayer* cont
}
// Now check our overflow objects.
- hitLayer = hitTestList(m_normalFlowList.get(), rootLayer, request, result, hitTestRect, hitTestLocation,
+ hitLayer = hitTestChildren(NormalFlowChildren, rootLayer, request, result, hitTestRect, hitTestLocation,
localTransformState.get(), zOffsetForDescendantsPtr, zOffset, unflattenedTransformState.get(), depthSortDescendants);
if (hitLayer) {
if (!depthSortDescendants)
@@ -4024,7 +2888,7 @@ RenderLayer* RenderLayer::hitTestLayer(RenderLayer* rootLayer, RenderLayer* cont
LayerFragments layerFragments;
collectFragments(layerFragments, rootLayer, hitTestLocation.region(), hitTestRect, RootRelativeClipRects, IncludeOverlayScrollbarSize);
- if (renderer()->canResize() && hitTestResizerInFragments(layerFragments, hitTestLocation)) {
+ if (m_scrollableArea && m_scrollableArea->hitTestResizerInFragments(layerFragments, hitTestLocation)) {
renderer()->updateHitTestResult(result, hitTestLocation.point());
return this;
}
@@ -4050,7 +2914,7 @@ RenderLayer* RenderLayer::hitTestLayer(RenderLayer* rootLayer, RenderLayer* cont
}
// Now check our negative z-index children.
- hitLayer = hitTestList(negZOrderList(), rootLayer, request, result, hitTestRect, hitTestLocation,
+ hitLayer = hitTestChildren(NegativeZOrderChildren, rootLayer, request, result, hitTestRect, hitTestLocation,
localTransformState.get(), zOffsetForDescendantsPtr, zOffset, unflattenedTransformState.get(), depthSortDescendants);
if (hitLayer) {
if (!depthSortDescendants)
@@ -4099,20 +2963,6 @@ bool RenderLayer::hitTestContentsForFragments(const LayerFragments& layerFragmen
return false;
}
-bool RenderLayer::hitTestResizerInFragments(const LayerFragments& layerFragments, const HitTestLocation& hitTestLocation) const
-{
- if (layerFragments.isEmpty())
- return false;
-
- for (int i = layerFragments.size() - 1; i >= 0; --i) {
- const LayerFragment& fragment = layerFragments.at(i);
- if (fragment.backgroundRect.intersects(hitTestLocation) && resizerCornerRect(pixelSnappedIntRect(fragment.layerBounds), ResizerForPointer).contains(hitTestLocation.roundedPoint()))
- return true;
- }
-
- return false;
-}
-
RenderLayer* RenderLayer::hitTestTransformedLayerInFragments(RenderLayer* rootLayer, RenderLayer* containerLayer, const HitTestRequest& request, HitTestResult& result,
const LayoutRect& hitTestRect, const HitTestLocation& hitTestLocation, const HitTestingTransformState* transformState, double* zOffset)
{
@@ -4207,23 +3057,21 @@ bool RenderLayer::hitTestContents(const HitTestRequest& request, HitTestResult&
return true;
}
-RenderLayer* RenderLayer::hitTestList(Vector<RenderLayer*>* list, RenderLayer* rootLayer,
- const HitTestRequest& request, HitTestResult& result,
- const LayoutRect& hitTestRect, const HitTestLocation& hitTestLocation,
- const HitTestingTransformState* transformState,
- double* zOffsetForDescendants, double* zOffset,
- const HitTestingTransformState* unflattenedTransformState,
- bool depthSortDescendants)
+RenderLayer* RenderLayer::hitTestChildren(ChildrenIteration childrentoVisit, RenderLayer* rootLayer,
+ const HitTestRequest& request, HitTestResult& result,
+ const LayoutRect& hitTestRect, const HitTestLocation& hitTestLocation,
+ const HitTestingTransformState* transformState,
+ double* zOffsetForDescendants, double* zOffset,
+ const HitTestingTransformState* unflattenedTransformState,
+ bool depthSortDescendants)
{
- if (!list)
- return 0;
-
if (!hasSelfPaintingLayerDescendant())
return 0;
RenderLayer* resultLayer = 0;
- for (int i = list->size() - 1; i >= 0; --i) {
- RenderLayer* childLayer = list->at(i);
+ RenderLayerStackingNodeReverseIterator iterator(*m_stackingNode, childrentoVisit);
+ while (RenderLayerStackingNode* child = iterator.next()) {
+ RenderLayer* childLayer = child->layer();
RenderLayer* hitLayer = 0;
HitTestResult tempResult(result.hitTestLocation());
if (childLayer->isPaginated())
@@ -4252,11 +3100,11 @@ RenderLayer* RenderLayer::hitTestPaginatedChildLayer(RenderLayer* childLayer, Re
const LayoutRect& hitTestRect, const HitTestLocation& hitTestLocation, const HitTestingTransformState* transformState, double* zOffset)
{
Vector<RenderLayer*> columnLayers;
- RenderLayer* ancestorLayer = isNormalFlowOnly() ? parent() : ancestorStackingContainer();
+ RenderLayerStackingNode* ancestorNode = m_stackingNode->isNormalFlowOnly() ? parent()->stackingNode() : m_stackingNode->ancestorStackingContainerNode();
for (RenderLayer* curr = childLayer->parent(); curr; curr = curr->parent()) {
if (curr->renderer()->hasColumns() && checkContainingBlockChainForPagination(childLayer->renderer(), curr->renderBox()))
columnLayers.append(curr);
- if (curr == ancestorLayer)
+ if (curr->stackingNode() == ancestorNode)
break;
}
@@ -4368,128 +3216,16 @@ RenderLayer* RenderLayer::hitTestChildLayerColumns(RenderLayer* childLayer, Rend
return 0;
}
-void RenderLayer::updateClipRects(const ClipRectsContext& clipRectsContext)
-{
- ClipRectsType clipRectsType = clipRectsContext.clipRectsType;
- ASSERT(clipRectsType < NumCachedClipRectsTypes);
- if (m_clipRectsCache && m_clipRectsCache->getClipRects(clipRectsType, clipRectsContext.respectOverflowClip)) {
- ASSERT(clipRectsContext.rootLayer == m_clipRectsCache->m_clipRectsRoot[clipRectsType]);
- ASSERT(m_clipRectsCache->m_scrollbarRelevancy[clipRectsType] == clipRectsContext.overlayScrollbarSizeRelevancy);
-
-#ifdef CHECK_CACHED_CLIP_RECTS
- // This code is useful to check cached clip rects, but is too expensive to leave enabled in debug builds by default.
- ClipRectsContext tempContext(clipRectsContext);
- tempContext.clipRectsType = TemporaryClipRects;
- ClipRects clipRects;
- calculateClipRects(tempContext, clipRects);
- ASSERT(clipRects == *m_clipRectsCache->getClipRects(clipRectsType, clipRectsContext.respectOverflowClip).get());
-#endif
- return; // We have the correct cached value.
- }
-
- // For transformed layers, the root layer was shifted to be us, so there is no need to
- // examine the parent. We want to cache clip rects with us as the root.
- RenderLayer* parentLayer = clipRectsContext.rootLayer != this ? parent() : 0;
- if (parentLayer)
- parentLayer->updateClipRects(clipRectsContext);
-
- ClipRects clipRects;
- calculateClipRects(clipRectsContext, clipRects);
-
- if (!m_clipRectsCache)
- m_clipRectsCache = adoptPtr(new ClipRectsCache);
-
- if (parentLayer && parentLayer->clipRects(clipRectsContext) && clipRects == *parentLayer->clipRects(clipRectsContext))
- m_clipRectsCache->setClipRects(clipRectsType, clipRectsContext.respectOverflowClip, parentLayer->clipRects(clipRectsContext));
- else
- m_clipRectsCache->setClipRects(clipRectsType, clipRectsContext.respectOverflowClip, ClipRects::create(clipRects));
-
-#ifndef NDEBUG
- m_clipRectsCache->m_clipRectsRoot[clipRectsType] = clipRectsContext.rootLayer;
- m_clipRectsCache->m_scrollbarRelevancy[clipRectsType] = clipRectsContext.overlayScrollbarSizeRelevancy;
-#endif
-}
-
-void RenderLayer::calculateClipRects(const ClipRectsContext& clipRectsContext, ClipRects& clipRects) const
-{
- if (!parent()) {
- // The root layer's clip rect is always infinite.
- clipRects.reset(PaintInfo::infiniteRect());
- return;
- }
-
- ClipRectsType clipRectsType = clipRectsContext.clipRectsType;
- bool useCached = clipRectsType != TemporaryClipRects;
-
- // For transformed layers, the root layer was shifted to be us, so there is no need to
- // examine the parent. We want to cache clip rects with us as the root.
- RenderLayer* parentLayer = clipRectsContext.rootLayer != this ? parent() : 0;
-
- // Ensure that our parent's clip has been calculated so that we can examine the values.
- if (parentLayer) {
- if (useCached && parentLayer->clipRects(clipRectsContext))
- clipRects = *parentLayer->clipRects(clipRectsContext);
- else {
- ClipRectsContext parentContext(clipRectsContext);
- parentContext.overlayScrollbarSizeRelevancy = IgnoreOverlayScrollbarSize; // FIXME: why?
- parentLayer->calculateClipRects(parentContext, clipRects);
- }
- } else
- clipRects.reset(PaintInfo::infiniteRect());
-
- // A fixed object is essentially the root of its containing block hierarchy, so when
- // we encounter such an object, we reset our clip rects to the fixedClipRect.
- if (renderer()->style()->position() == FixedPosition) {
- clipRects.setPosClipRect(clipRects.fixedClipRect());
- clipRects.setOverflowClipRect(clipRects.fixedClipRect());
- clipRects.setFixed(true);
- } else if (renderer()->style()->hasInFlowPosition())
- clipRects.setPosClipRect(clipRects.overflowClipRect());
- else if (renderer()->style()->position() == AbsolutePosition)
- clipRects.setOverflowClipRect(clipRects.posClipRect());
-
- // Update the clip rects that will be passed to child layers.
- if ((renderer()->hasOverflowClip() && (clipRectsContext.respectOverflowClip == RespectOverflowClip || this != clipRectsContext.rootLayer)) || renderer()->hasClip()) {
- // This layer establishes a clip of some kind.
-
- // This offset cannot use convertToLayerCoords, because sometimes our rootLayer may be across
- // some transformed layer boundary, for example, in the RenderLayerCompositor overlapMap, where
- // clipRects are needed in view space.
- LayoutPoint offset;
- offset = roundedLayoutPoint(renderer()->localToContainerPoint(FloatPoint(), clipRectsContext.rootLayer->renderer()));
- RenderView* view = renderer()->view();
- ASSERT(view);
- if (view && clipRects.fixed() && clipRectsContext.rootLayer->renderer() == view) {
- offset -= view->frameView()->scrollOffsetForFixedPosition();
- }
-
- if (renderer()->hasOverflowClip()) {
- ClipRect newOverflowClip = toRenderBox(renderer())->overflowClipRect(offset, clipRectsContext.region, clipRectsContext.overlayScrollbarSizeRelevancy);
- if (renderer()->style()->hasBorderRadius())
- newOverflowClip.setHasRadius(true);
- clipRects.setOverflowClipRect(intersection(newOverflowClip, clipRects.overflowClipRect()));
- if (renderer()->isPositioned())
- clipRects.setPosClipRect(intersection(newOverflowClip, clipRects.posClipRect()));
- }
- if (renderer()->hasClip()) {
- LayoutRect newPosClip = toRenderBox(renderer())->clipRect(offset, clipRectsContext.region);
- clipRects.setPosClipRect(intersection(newPosClip, clipRects.posClipRect()));
- clipRects.setOverflowClipRect(intersection(newPosClip, clipRects.overflowClipRect()));
- clipRects.setFixedClipRect(intersection(newPosClip, clipRects.fixedClipRect()));
- }
- }
-}
-
void RenderLayer::parentClipRects(const ClipRectsContext& clipRectsContext, ClipRects& clipRects) const
{
ASSERT(parent());
if (clipRectsContext.clipRectsType == TemporaryClipRects) {
- parent()->calculateClipRects(clipRectsContext, clipRects);
+ parent()->clipper().calculateClipRects(clipRectsContext, clipRects);
return;
}
- parent()->updateClipRects(clipRectsContext);
- clipRects = *parent()->clipRects(clipRectsContext);
+ parent()->m_clipper.updateClipRects(clipRectsContext);
+ clipRects = *parent()->clipper().clipRects(clipRectsContext);
}
static inline ClipRect backgroundClipRectForPosition(const ClipRects& parentRects, EPosition position)
@@ -4658,15 +3394,23 @@ void RenderLayer::repaintBlockSelectionGaps()
return;
LayoutRect rect = m_blockSelectionGapsBounds;
- rect.move(-scrolledContentOffset());
- if (renderer()->hasOverflowClip() && !usesCompositedScrolling())
- rect.intersect(toRenderBox(renderer())->overflowClipRect(LayoutPoint(), 0)); // FIXME: Regions not accounted for.
+ if (renderer()->hasOverflowClip()) {
+ RenderBox* box = renderBox();
+ rect.move(-box->scrolledContentOffset());
+ if (!scrollableArea()->usesCompositedScrolling())
+ rect.intersect(box->overflowClipRect(LayoutPoint(), 0)); // FIXME: Regions not accounted for.
+ }
if (renderer()->hasClip())
rect.intersect(toRenderBox(renderer())->clipRect(LayoutPoint(), 0)); // FIXME: Regions not accounted for.
if (!rect.isEmpty())
renderer()->repaintRectangle(rect);
}
+bool RenderLayer::hasBlockSelectionGapBounds() const
+{
+ return !m_blockSelectionGapsBounds.isEmpty();
+}
+
bool RenderLayer::intersectsDamageRect(const LayoutRect& layerBounds, const LayoutRect& damageRect, const RenderLayer* rootLayer, const LayoutPoint* offsetFromRoot) const
{
// Always examine the canvas and the root.
@@ -4818,11 +3562,12 @@ IntRect RenderLayer::calculateLayerBounds(const RenderLayer* ancestorLayer, cons
}
LayoutRect unionBounds = boundingBoxRect;
+ bool shouldIncludeTransform = paintsWithTransform(PaintBehaviorNormal) || (transform() && flags & PretendLayerHasOwnBacking);
if (flags & UseLocalClipRectIfPossible) {
LayoutRect localClipRect = this->localClipRect();
if (localClipRect != PaintInfo::infiniteRect()) {
- if ((flags & IncludeSelfTransform) && paintsWithTransform(PaintBehaviorNormal))
+ if ((flags & IncludeSelfTransform) && shouldIncludeTransform)
localClipRect = transform()->mapRect(localClipRect);
LayoutPoint ancestorRelOffset;
@@ -4835,51 +3580,38 @@ IntRect RenderLayer::calculateLayerBounds(const RenderLayer* ancestorLayer, cons
// FIXME: should probably just pass 'flags' down to descendants.
CalculateLayerBoundsFlags descendantFlags = DefaultCalculateLayerBoundsFlags | (flags & ExcludeHiddenDescendants) | (flags & IncludeCompositedDescendants);
- const_cast<RenderLayer*>(this)->updateLayerListsIfNeeded();
+ const_cast<RenderLayer*>(this)->stackingNode()->updateLayerListsIfNeeded();
- if (RenderLayer* reflection = reflectionLayer()) {
- if (!reflection->isComposited()) {
- IntRect childUnionBounds = reflection->calculateLayerBounds(this, 0, descendantFlags);
+ if (m_reflectionInfo) {
+ RenderLayer* reflectionLayer = m_reflectionInfo->reflectionLayer();
+ if (!reflectionLayer->hasCompositedLayerMapping()) {
+ IntRect childUnionBounds = reflectionLayer->calculateLayerBounds(this, 0, descendantFlags);
unionBounds.unite(childUnionBounds);
}
}
- ASSERT(isStackingContainer() || (!posZOrderList() || !posZOrderList()->size()));
+ ASSERT(m_stackingNode->isStackingContainer() || !m_stackingNode->hasPositiveZOrderList());
#if !ASSERT_DISABLED
- LayerListMutationDetector mutationChecker(const_cast<RenderLayer*>(this));
+ LayerListMutationDetector mutationChecker(const_cast<RenderLayer*>(this)->stackingNode());
#endif
- if (Vector<RenderLayer*>* negZOrderList = this->negZOrderList()) {
- size_t listSize = negZOrderList->size();
- for (size_t i = 0; i < listSize; ++i) {
- RenderLayer* curLayer = negZOrderList->at(i);
- if (flags & IncludeCompositedDescendants || !curLayer->isComposited()) {
- IntRect childUnionBounds = curLayer->calculateLayerBounds(this, 0, descendantFlags);
- unionBounds.unite(childUnionBounds);
- }
- }
- }
-
- if (Vector<RenderLayer*>* posZOrderList = this->posZOrderList()) {
- size_t listSize = posZOrderList->size();
- for (size_t i = 0; i < listSize; ++i) {
- RenderLayer* curLayer = posZOrderList->at(i);
- if (flags & IncludeCompositedDescendants || !curLayer->isComposited()) {
- IntRect childUnionBounds = curLayer->calculateLayerBounds(this, 0, descendantFlags);
- unionBounds.unite(childUnionBounds);
- }
+ // FIXME: Descendants that are composited should not necessarily be skipped, if they don't paint into their own
+ // separate backing. Instead, they ought to contribute to the bounds of the layer we're trying to compute.
+ // This applies to all z-order lists below.
+ RenderLayerStackingNodeIterator iterator(*m_stackingNode.get(), AllChildren);
+ while (RenderLayerStackingNode* node = iterator.next()) {
+ // Node's compositing ancestor may have changed its draw content status
+ // prior to updating its bounds. The requires-own-backing-store-for-ancestor-reasons
+ // could be stale. Refresh them now.
+ if (node->layer()->hasCompositedLayerMapping()) {
+ RenderLayer* enclosingCompositingLayer = node->layer()->enclosingCompositingLayer(false);
+ node->layer()->compositedLayerMapping()->updateRequiresOwnBackingStoreForAncestorReasons(enclosingCompositingLayer);
}
- }
- if (Vector<RenderLayer*>* normalFlowList = this->normalFlowList()) {
- size_t listSize = normalFlowList->size();
- for (size_t i = 0; i < listSize; ++i) {
- RenderLayer* curLayer = normalFlowList->at(i);
- if (flags & IncludeCompositedDescendants || !curLayer->isComposited()) {
- IntRect curAbsBounds = curLayer->calculateLayerBounds(this, 0, descendantFlags);
- unionBounds.unite(curAbsBounds);
- }
+ if (flags & IncludeCompositedDescendants || !node->layer()->hasCompositedLayerMapping()) {
+ IntRect childUnionBounds = node->layer()->calculateLayerBounds(this, 0, descendantFlags);
+ unionBounds.unite(childUnionBounds);
}
}
@@ -4889,7 +3621,7 @@ IntRect RenderLayer::calculateLayerBounds(const RenderLayer* ancestorLayer, cons
if (flags & IncludeLayerFilterOutsets)
renderer->style()->filterOutsets().expandRect(unionBounds);
- if ((flags & IncludeSelfTransform) && paintsWithTransform(PaintBehaviorNormal)) {
+ if ((flags & IncludeSelfTransform) && shouldIncludeTransform) {
TransformationMatrix* affineTrans = transform();
boundingBoxRect = affineTrans->mapRect(boundingBoxRect);
unionBounds = affineTrans->mapRect(unionBounds);
@@ -4905,49 +3637,43 @@ IntRect RenderLayer::calculateLayerBounds(const RenderLayer* ancestorLayer, cons
return pixelSnappedIntRect(unionBounds);
}
-void RenderLayer::clearClipRectsIncludingDescendants(ClipRectsType typeToClear)
+CompositingState RenderLayer::compositingState() const
{
- // FIXME: it's not clear how this layer not having clip rects guarantees that no descendants have any.
- if (!m_clipRectsCache)
- return;
+ // This is computed procedurally so there is no redundant state variable that
+ // can get out of sync from the real actual compositing state.
- clearClipRects(typeToClear);
+ if (m_groupedMapping) {
+ ASSERT(compositor()->layerSquashingEnabled());
+ ASSERT(!m_compositedLayerMapping);
+ return PaintsIntoGroupedBacking;
+ }
- for (RenderLayer* l = firstChild(); l; l = l->nextSibling())
- l->clearClipRectsIncludingDescendants(typeToClear);
-}
+ if (!m_compositedLayerMapping)
+ return NotComposited;
-void RenderLayer::clearClipRects(ClipRectsType typeToClear)
-{
- if (typeToClear == AllClipRectTypes)
- m_clipRectsCache = nullptr;
- else {
- ASSERT(typeToClear < NumCachedClipRectsTypes);
- RefPtr<ClipRects> dummy;
- m_clipRectsCache->setClipRects(typeToClear, RespectOverflowClip, dummy);
- m_clipRectsCache->setClipRects(typeToClear, IgnoreOverflowClip, dummy);
- }
+ if (m_compositedLayerMapping && compositedLayerMapping()->paintsIntoCompositedAncestor())
+ return HasOwnBackingButPaintsIntoAncestor;
+
+ ASSERT(m_compositedLayerMapping);
+ return PaintsIntoOwnBacking;
}
-RenderLayerBacking* RenderLayer::ensureBacking()
+CompositedLayerMappingPtr RenderLayer::ensureCompositedLayerMapping()
{
- if (!m_backing) {
- m_backing = adoptPtr(new RenderLayerBacking(this));
- compositor()->layerBecameComposited(this);
+ if (!m_compositedLayerMapping) {
+ m_compositedLayerMapping = adoptPtr(new CompositedLayerMapping(this));
updateOrRemoveFilterEffectRenderer();
if (RuntimeEnabledFeatures::cssCompositingEnabled())
- backing()->setBlendMode(m_blendMode);
+ compositedLayerMapping()->setBlendMode(m_blendMode);
}
- return m_backing.get();
+ return m_compositedLayerMapping.get();
}
-void RenderLayer::clearBacking(bool layerBeingDestroyed)
+void RenderLayer::clearCompositedLayerMapping(bool layerBeingDestroyed)
{
- if (m_backing && !renderer()->documentBeingDestroyed())
- compositor()->layerBecameNonComposited(this);
- m_backing.clear();
+ m_compositedLayerMapping.clear();
if (!layerBeingDestroyed)
updateOrRemoveFilterEffectRenderer();
@@ -4955,37 +3681,26 @@ void RenderLayer::clearBacking(bool layerBeingDestroyed)
bool RenderLayer::hasCompositedMask() const
{
- return m_backing && m_backing->hasMaskLayer();
+ return m_compositedLayerMapping && m_compositedLayerMapping->hasMaskLayer();
}
-GraphicsLayer* RenderLayer::layerForScrolling() const
+bool RenderLayer::hasCompositedClippingMask() const
{
- return m_backing ? m_backing->scrollingContentsLayer() : 0;
+ return m_compositedLayerMapping && m_compositedLayerMapping->hasChildClippingMaskLayer();
}
-GraphicsLayer* RenderLayer::layerForScrollChild() const
+bool RenderLayer::clipsCompositingDescendantsWithBorderRadius() const
{
- return m_backing ? m_backing->childForSuperlayers() : 0;
-}
-
-GraphicsLayer* RenderLayer::layerForHorizontalScrollbar() const
-{
- return m_backing ? m_backing->layerForHorizontalScrollbar() : 0;
-}
-
-GraphicsLayer* RenderLayer::layerForVerticalScrollbar() const
-{
- return m_backing ? m_backing->layerForVerticalScrollbar() : 0;
-}
+ RenderStyle* style = renderer()->style();
+ if (!style)
+ return false;
-GraphicsLayer* RenderLayer::layerForScrollCorner() const
-{
- return m_backing ? m_backing->layerForScrollCorner() : 0;
+ return compositor()->clipsCompositingDescendants(this) && style->hasBorderRadius();
}
bool RenderLayer::paintsWithTransform(PaintBehavior paintBehavior) const
{
- return transform() && ((paintBehavior & PaintBehaviorFlattenCompositingLayers) || !isComposited());
+ return transform() && ((paintBehavior & PaintBehaviorFlattenCompositingLayers) || compositingState() != PaintsIntoOwnBacking);
}
bool RenderLayer::backgroundIsKnownToBeOpaqueInRect(const LayoutRect& localRect) const
@@ -5011,7 +3726,7 @@ bool RenderLayer::backgroundIsKnownToBeOpaqueInRect(const LayoutRect& localRect)
// FIXME: Remove this check.
// This function should not be called when layer-lists are dirty.
// It is somehow getting triggered during style update.
- if (m_zOrderListsDirty || m_normalFlowListDirty)
+ if (m_stackingNode->zOrderListsDirty() || m_stackingNode->normalFlowListDirty())
return false;
// FIXME: We currently only check the immediate renderer,
@@ -5024,19 +3739,15 @@ bool RenderLayer::backgroundIsKnownToBeOpaqueInRect(const LayoutRect& localRect)
if (renderer()->hasOverflowClip())
return false;
- return listBackgroundIsKnownToBeOpaqueInRect(posZOrderList(), localRect)
- || listBackgroundIsKnownToBeOpaqueInRect(negZOrderList(), localRect)
- || listBackgroundIsKnownToBeOpaqueInRect(normalFlowList(), localRect);
+ return childBackgroundIsKnownToBeOpaqueInRect(localRect);
}
-bool RenderLayer::listBackgroundIsKnownToBeOpaqueInRect(const Vector<RenderLayer*>* list, const LayoutRect& localRect) const
+bool RenderLayer::childBackgroundIsKnownToBeOpaqueInRect(const LayoutRect& localRect) const
{
- if (!list || list->isEmpty())
- return false;
-
- for (Vector<RenderLayer*>::const_reverse_iterator iter = list->rbegin(); iter != list->rend(); ++iter) {
- const RenderLayer* childLayer = *iter;
- if (childLayer->isComposited())
+ RenderLayerStackingNodeReverseIterator revertseIterator(*m_stackingNode, PositiveZOrderChildren | NormalFlowChildren | NegativeZOrderChildren);
+ while (RenderLayerStackingNode* child = revertseIterator.next()) {
+ const RenderLayer* childLayer = child->layer();
+ if (childLayer->hasCompositedLayerMapping())
continue;
if (!childLayer->canUseConvertToLayerCoords())
@@ -5067,308 +3778,10 @@ void RenderLayer::setParent(RenderLayer* parent)
compositor()->layerWasAdded(m_parent, this);
}
-// Helper for the sorting of layers by z-index.
-static inline bool compareZIndex(RenderLayer* first, RenderLayer* second)
-{
- return first->zIndex() < second->zIndex();
-}
-
-void RenderLayer::dirtyNormalFlowListCanBePromotedToStackingContainer()
-{
- m_canBePromotedToStackingContainerDirty = true;
-
- if (m_normalFlowListDirty || !normalFlowList())
- return;
-
- for (size_t index = 0; index < normalFlowList()->size(); ++index)
- normalFlowList()->at(index)->dirtyNormalFlowListCanBePromotedToStackingContainer();
-}
-
-void RenderLayer::dirtySiblingStackingContextCanBePromotedToStackingContainer()
-{
- RenderLayer* ancestorStackingContext = this->ancestorStackingContext();
- if (!ancestorStackingContext)
- return;
-
- if (!ancestorStackingContext->m_zOrderListsDirty && ancestorStackingContext->posZOrderList()) {
- for (size_t index = 0; index < ancestorStackingContext->posZOrderList()->size(); ++index)
- ancestorStackingContext->posZOrderList()->at(index)->m_canBePromotedToStackingContainerDirty = true;
- }
-
- ancestorStackingContext->dirtyNormalFlowListCanBePromotedToStackingContainer();
-
- if (!ancestorStackingContext->m_zOrderListsDirty && ancestorStackingContext->negZOrderList()) {
- for (size_t index = 0; index < ancestorStackingContext->negZOrderList()->size(); ++index)
- ancestorStackingContext->negZOrderList()->at(index)->m_canBePromotedToStackingContainerDirty = true;
- }
-}
-
-void RenderLayer::dirtyZOrderLists()
-{
- ASSERT(m_layerListMutationAllowed);
- ASSERT(isStackingContainer());
-
- if (m_posZOrderList)
- m_posZOrderList->clear();
- if (m_negZOrderList)
- m_negZOrderList->clear();
- m_zOrderListsDirty = true;
-
- m_canBePromotedToStackingContainerDirty = true;
-
- if (!renderer()->documentBeingDestroyed()) {
- compositor()->setNeedsUpdateCompositingRequirementsState();
- compositor()->setCompositingLayersNeedRebuild();
- if (acceleratedCompositingForOverflowScrollEnabled())
- compositor()->setShouldReevaluateCompositingAfterLayout();
- }
-}
-
-void RenderLayer::dirtyStackingContainerZOrderLists()
-{
- // Any siblings in the ancestor stacking context could also be affected.
- // Changing z-index, for example, could cause us to stack in between a
- // sibling's descendants, meaning that we have to recompute
- // m_canBePromotedToStackingContainer for that sibling.
- dirtySiblingStackingContextCanBePromotedToStackingContainer();
-
- RenderLayer* stackingContainer = this->ancestorStackingContainer();
- if (stackingContainer)
- stackingContainer->dirtyZOrderLists();
-
- // Any change that could affect our stacking container's z-order list could
- // cause other RenderLayers in our stacking context to either opt in or out
- // of composited scrolling. It is important that we make our stacking
- // context aware of these z-order changes so the appropriate updating can
- // happen.
- RenderLayer* stackingContext = this->ancestorStackingContext();
- if (stackingContext && stackingContext != stackingContainer)
- stackingContext->dirtyZOrderLists();
-}
-
-void RenderLayer::dirtyNormalFlowList()
-{
- ASSERT(m_layerListMutationAllowed);
-
- if (m_normalFlowList)
- m_normalFlowList->clear();
- m_normalFlowListDirty = true;
-
- if (!renderer()->documentBeingDestroyed()) {
- compositor()->setCompositingLayersNeedRebuild();
- if (acceleratedCompositingForOverflowScrollEnabled())
- compositor()->setShouldReevaluateCompositingAfterLayout();
- }
-}
-
-void RenderLayer::rebuildZOrderLists()
-{
- ASSERT(m_layerListMutationAllowed);
- ASSERT(isDirtyStackingContainer());
- rebuildZOrderLists(m_posZOrderList, m_negZOrderList);
- m_zOrderListsDirty = false;
-}
-
-void RenderLayer::rebuildZOrderLists(OwnPtr<Vector<RenderLayer*> >& posZOrderList, OwnPtr<Vector<RenderLayer*> >& negZOrderList, const RenderLayer* layerToForceAsStackingContainer, CollectLayersBehavior collectLayersBehavior)
-{
- bool includeHiddenLayers = compositor()->inCompositingMode();
- for (RenderLayer* child = firstChild(); child; child = child->nextSibling())
- if (!m_reflection || reflectionLayer() != child)
- child->collectLayers(includeHiddenLayers, posZOrderList, negZOrderList, layerToForceAsStackingContainer, collectLayersBehavior);
-
- // Sort the two lists.
- if (posZOrderList)
- std::stable_sort(posZOrderList->begin(), posZOrderList->end(), compareZIndex);
-
- if (negZOrderList)
- std::stable_sort(negZOrderList->begin(), negZOrderList->end(), compareZIndex);
-
- // Append layers for top layer elements after normal layer collection, to ensure they are on top regardless of z-indexes.
- // The renderers of top layer elements are children of the view, sorted in top layer stacking order.
- if (isRootLayer()) {
- RenderObject* view = renderer()->view();
- for (RenderObject* child = view->firstChild(); child; child = child->nextSibling()) {
- Element* childElement = (child->node() && child->node()->isElementNode()) ? toElement(child->node()) : 0;
- if (childElement && childElement->isInTopLayer()) {
- RenderLayer* layer = toRenderLayerModelObject(child)->layer();
- posZOrderList->append(layer);
- }
- }
- }
-}
-
-void RenderLayer::updateNormalFlowList()
-{
- if (!m_normalFlowListDirty)
- return;
-
- ASSERT(m_layerListMutationAllowed);
-
- for (RenderLayer* child = firstChild(); child; child = child->nextSibling()) {
- // Ignore non-overflow layers and reflections.
- if (child->isNormalFlowOnly() && (!m_reflection || reflectionLayer() != child)) {
- if (!m_normalFlowList)
- m_normalFlowList = adoptPtr(new Vector<RenderLayer*>);
- m_normalFlowList->append(child);
- }
- }
-
- m_normalFlowListDirty = false;
-}
-
-void RenderLayer::collectLayers(bool includeHiddenLayers, OwnPtr<Vector<RenderLayer*> >& posBuffer, OwnPtr<Vector<RenderLayer*> >& negBuffer, const RenderLayer* layerToForceAsStackingContainer, CollectLayersBehavior collectLayersBehavior)
-{
- if (isInTopLayer())
- return;
-
- updateDescendantDependentFlags();
-
- bool isStacking = false;
- bool isNormalFlow = false;
-
- switch (collectLayersBehavior) {
- case ForceLayerToStackingContainer:
- ASSERT(layerToForceAsStackingContainer);
- if (this == layerToForceAsStackingContainer) {
- isStacking = true;
- isNormalFlow = false;
- } else {
- isStacking = isStackingContext();
- isNormalFlow = shouldBeNormalFlowOnlyIgnoringCompositedScrolling();
- }
- break;
- case OverflowScrollCanBeStackingContainers:
- ASSERT(!layerToForceAsStackingContainer);
- isStacking = isStackingContainer();
- isNormalFlow = isNormalFlowOnly();
- break;
- case OnlyStackingContextsCanBeStackingContainers:
- isStacking = isStackingContext();
- isNormalFlow = shouldBeNormalFlowOnlyIgnoringCompositedScrolling();
- break;
- }
-
- // Overflow layers are just painted by their enclosing layers, so they don't get put in zorder lists.
- bool includeHiddenLayer = includeHiddenLayers || (m_hasVisibleContent || (m_hasVisibleDescendant && isStacking));
- if (includeHiddenLayer && !isNormalFlow && !isOutOfFlowRenderFlowThread()) {
- // Determine which buffer the child should be in.
- OwnPtr<Vector<RenderLayer*> >& buffer = (zIndex() >= 0) ? posBuffer : negBuffer;
-
- // Create the buffer if it doesn't exist yet.
- if (!buffer)
- buffer = adoptPtr(new Vector<RenderLayer*>);
-
- // Append ourselves at the end of the appropriate buffer.
- buffer->append(this);
- }
-
- // Recur into our children to collect more layers, but only if we don't establish
- // a stacking context/container.
- if ((includeHiddenLayers || m_hasVisibleDescendant) && !isStacking) {
- for (RenderLayer* child = firstChild(); child; child = child->nextSibling()) {
- // Ignore reflections.
- if (!m_reflection || reflectionLayer() != child)
- child->collectLayers(includeHiddenLayers, posBuffer, negBuffer, layerToForceAsStackingContainer, collectLayersBehavior);
- }
- }
-}
-
-void RenderLayer::updateLayerListsIfNeeded()
-{
- updateZOrderLists();
- updateNormalFlowList();
-
- if (RenderLayer* reflectionLayer = this->reflectionLayer()) {
- reflectionLayer->updateZOrderLists();
- reflectionLayer->updateNormalFlowList();
- }
-}
-
-void RenderLayer::repaintIncludingDescendants()
-{
- renderer()->repaint();
- for (RenderLayer* curr = firstChild(); curr; curr = curr->nextSibling())
- curr->repaintIncludingDescendants();
-}
-
-void RenderLayer::setBackingNeedsRepaint()
-{
- ASSERT(isComposited());
- backing()->setContentsNeedDisplay();
-}
-
-void RenderLayer::setBackingNeedsRepaintInRect(const LayoutRect& r)
-{
- // https://bugs.webkit.org/show_bug.cgi?id=61159 describes an unreproducible crash here,
- // so assert but check that the layer is composited.
- ASSERT(isComposited());
- if (!isComposited()) {
- // If we're trying to repaint the placeholder document layer, propagate the
- // repaint to the native view system.
- LayoutRect absRect(r);
- LayoutPoint delta;
- convertToLayerCoords(root(), delta);
- absRect.moveBy(delta);
-
- RenderView* view = renderer()->view();
- if (view)
- view->repaintViewRectangle(absRect);
- } else
- backing()->setContentsNeedDisplayInRect(pixelSnappedIntRect(r));
-}
-
-// Since we're only painting non-composited layers, we know that they all share the same repaintContainer.
-void RenderLayer::repaintIncludingNonCompositingDescendants(RenderLayerModelObject* repaintContainer)
-{
- renderer()->repaintUsingContainer(repaintContainer, pixelSnappedIntRect(renderer()->clippedOverflowRectForRepaint(repaintContainer)));
-
- for (RenderLayer* curr = firstChild(); curr; curr = curr->nextSibling()) {
- if (!curr->isComposited())
- curr->repaintIncludingNonCompositingDescendants(repaintContainer);
- }
-}
-
-bool RenderLayer::shouldBeNormalFlowOnly() const
-{
- return shouldBeNormalFlowOnlyIgnoringCompositedScrolling() && !needsCompositedScrolling();
-}
-
-bool RenderLayer::shouldBeNormalFlowOnlyIgnoringCompositedScrolling() const
-{
- const bool couldBeNormalFlow = renderer()->hasOverflowClip()
- || renderer()->hasReflection()
- || renderer()->hasMask()
- || renderer()->isCanvas()
- || renderer()->isVideo()
- || renderer()->isEmbeddedObject()
- || renderer()->isRenderIFrame()
- || (renderer()->style()->specifiesColumns() && !isRootLayer());
- const bool preventsElementFromBeingNormalFlow = renderer()->isPositioned()
- || renderer()->hasTransform()
- || renderer()->hasClipPath()
- || renderer()->hasFilter()
- || renderer()->hasBlendMode()
- || isTransparent();
-
- return couldBeNormalFlow && !preventsElementFromBeingNormalFlow;
-}
-
-void RenderLayer::updateIsNormalFlowOnly()
-{
- bool isNormalFlowOnly = shouldBeNormalFlowOnly();
- if (isNormalFlowOnly == m_isNormalFlowOnly)
- return;
-
- m_isNormalFlowOnly = isNormalFlowOnly;
- if (RenderLayer* p = parent())
- p->dirtyNormalFlowList();
- dirtyStackingContainerZOrderLists();
-}
-
bool RenderLayer::shouldBeSelfPaintingLayer() const
{
- return !isNormalFlowOnly()
- || hasOverlayScrollbars()
+ return !m_stackingNode->isNormalFlowOnly()
+ || (m_scrollableArea && m_scrollableArea->hasOverlayScrollbars())
|| needsCompositedScrolling()
|| renderer()->hasReflection()
|| renderer()->hasMask()
@@ -5381,8 +3794,8 @@ bool RenderLayer::shouldBeSelfPaintingLayer() const
void RenderLayer::updateSelfPaintingLayer()
{
- bool isSelfPaintingLayer = shouldBeSelfPaintingLayer();
- if (m_isSelfPaintingLayer == isSelfPaintingLayer)
+ bool isSelfPaintingLayer = this->shouldBeSelfPaintingLayer();
+ if (this->isSelfPaintingLayer() == isSelfPaintingLayer)
return;
m_isSelfPaintingLayer = isSelfPaintingLayer;
@@ -5453,28 +3866,6 @@ void RenderLayer::updateVisibilityAfterStyleChange(const RenderStyle* oldStyle)
compositor()->setNeedsUpdateCompositingRequirementsState();
}
-void RenderLayer::updateStackingContextsAfterStyleChange(const RenderStyle* oldStyle)
-{
- bool wasStackingContext = oldStyle ? isStackingContext(oldStyle) : false;
- EVisibility oldVisibility = oldStyle ? oldStyle->visibility() : VISIBLE;
- int oldZIndex = oldStyle ? oldStyle->zIndex() : 0;
-
- // FIXME: RenderLayer already handles visibility changes through our visiblity dirty bits. This logic could
- // likely be folded along with the rest.
- bool isStackingContext = this->isStackingContext();
- if (isStackingContext == wasStackingContext && oldVisibility == renderer()->style()->visibility() && oldZIndex == renderer()->style()->zIndex())
- return;
-
- dirtyStackingContainerZOrderLists();
-
- if (isStackingContainer())
- dirtyZOrderLists();
- else
- clearZOrderLists();
-
- compositor()->setNeedsUpdateCompositingRequirementsState();
-}
-
void RenderLayer::updateOutOfFlowPositioned(const RenderStyle* oldStyle)
{
if (oldStyle && (renderer()->style()->position() == oldStyle->position()))
@@ -5529,7 +3920,7 @@ inline bool RenderLayer::needsCompositingLayersRebuiltForClip(const RenderStyle*
inline bool RenderLayer::needsCompositingLayersRebuiltForOverflow(const RenderStyle* oldStyle, const RenderStyle* newStyle) const
{
ASSERT(newStyle);
- return !isComposited() && oldStyle && (oldStyle->overflowX() != newStyle->overflowX()) && ancestorStackingContainer()->hasCompositingDescendant();
+ return !hasCompositedLayerMapping() && oldStyle && (oldStyle->overflowX() != newStyle->overflowX()) && m_stackingNode->ancestorStackingContainerNode()->layer()->hasCompositingDescendant();
}
inline bool RenderLayer::needsCompositingLayersRebuiltForFilters(const RenderStyle* oldStyle, const RenderStyle* newStyle, bool didPaintWithFilters) const
@@ -5537,7 +3928,10 @@ inline bool RenderLayer::needsCompositingLayersRebuiltForFilters(const RenderSty
if (!hasOrHadFilters(oldStyle, newStyle))
return false;
- if (renderer()->animation()->isRunningAcceleratedAnimationOnRenderer(renderer(), CSSPropertyWebkitFilter)) {
+ if (RuntimeEnabledFeatures::webAnimationsCSSEnabled()
+ ? hasActiveAnimationsOnCompositor(*renderer(), CSSPropertyWebkitFilter)
+ : renderer()->animation().isRunningAcceleratedAnimationOnRenderer(renderer(), CSSPropertyWebkitFilter)) {
+
// When the compositor is performing the filter animation, we shouldn't touch the compositing layers.
// All of the layers above us should have been promoted to compositing layers already.
return false;
@@ -5565,6 +3959,15 @@ inline bool RenderLayer::needsCompositingLayersRebuiltForFilters(const RenderSty
return false;
}
+inline bool RenderLayer::needsCompositingLayersRebuiltForBlending(const RenderStyle* oldStyle, const RenderStyle* newStyle) const
+{
+ ASSERT(newStyle);
+ if (!hasCompositedLayerMapping())
+ return false;
+ return (shouldIsolateCompositedDescendants() && !stackingNode()->isStackingContext())
+ || (oldStyle && (oldStyle->hasBlendMode() != newStyle->hasBlendMode()));
+}
+
void RenderLayer::updateFilters(const RenderStyle* oldStyle, const RenderStyle* newStyle)
{
if (!hasOrHadFilters(oldStyle, newStyle))
@@ -5573,42 +3976,34 @@ void RenderLayer::updateFilters(const RenderStyle* oldStyle, const RenderStyle*
updateOrRemoveFilterClients();
// During an accelerated animation, both WebKit and the compositor animate properties.
// However, WebKit shouldn't ask the compositor to update its filters if the compositor is performing the animation.
- bool shouldUpdateFilters = isComposited() && !renderer()->animation()->isRunningAcceleratedAnimationOnRenderer(renderer(), CSSPropertyWebkitFilter);
- if (shouldUpdateFilters)
- backing()->updateFilters(renderer()->style());
+ if (hasCompositedLayerMapping() && (RuntimeEnabledFeatures::webAnimationsCSSEnabled()
+ ? !hasActiveAnimationsOnCompositor(*renderer(), CSSPropertyWebkitFilter)
+ : !renderer()->animation().isRunningAcceleratedAnimationOnRenderer(renderer(), CSSPropertyWebkitFilter)))
+ compositedLayerMapping()->updateFilters(renderer()->style());
updateOrRemoveFilterEffectRenderer();
}
void RenderLayer::styleChanged(StyleDifference, const RenderStyle* oldStyle)
{
- updateIsNormalFlowOnly();
+ m_stackingNode->updateIsNormalFlowOnly();
- updateResizerAreaSet();
- m_scrollableArea->updateAfterStyleChange(oldStyle);
- updateStackingContextsAfterStyleChange(oldStyle);
+ if (m_scrollableArea)
+ m_scrollableArea->updateAfterStyleChange(oldStyle);
+ m_stackingNode->updateStackingNodesAfterStyleChange(oldStyle);
updateVisibilityAfterStyleChange(oldStyle);
// Overlay scrollbars can make this layer self-painting so we need
// to recompute the bit once scrollbars have been updated.
updateSelfPaintingLayer();
updateOutOfFlowPositioned(oldStyle);
- if (!hasReflection() && m_reflection)
- removeReflection();
- else if (hasReflection()) {
- if (!m_reflection)
- createReflection();
- UseCounter::count(&renderer()->document(), UseCounter::Reflection);
- updateReflectionStyle();
- }
+ updateReflectionInfo(oldStyle);
- updateResizerStyle();
+ if (RuntimeEnabledFeatures::cssCompositingEnabled())
+ updateBlendMode();
updateDescendantDependentFlags();
updateTransform();
- if (RuntimeEnabledFeatures::cssCompositingEnabled())
- updateBlendMode();
-
bool didPaintWithFilters = false;
if (paintsWithFilters())
@@ -5619,149 +4014,36 @@ void RenderLayer::styleChanged(StyleDifference, const RenderStyle* oldStyle)
if (compositor()->updateLayerCompositingState(this)
|| needsCompositingLayersRebuiltForClip(oldStyle, newStyle)
|| needsCompositingLayersRebuiltForOverflow(oldStyle, newStyle)
- || needsCompositingLayersRebuiltForFilters(oldStyle, newStyle, didPaintWithFilters))
+ || needsCompositingLayersRebuiltForFilters(oldStyle, newStyle, didPaintWithFilters)
+ || needsCompositingLayersRebuiltForBlending(oldStyle, newStyle)) {
compositor()->setCompositingLayersNeedRebuild();
- else if (isComposited())
- backing()->updateGraphicsLayerGeometry();
-}
-
-void RenderLayer::updateResizerAreaSet() {
- Frame* frame = renderer()->frame();
- if (!frame)
- return;
- FrameView* frameView = frame->view();
- if (!frameView)
- return;
- if (renderer()->canResize())
- frameView->addResizerArea(this);
- else
- frameView->removeResizerArea(this);
-}
-
-void RenderLayer::updateScrollableAreaSet(bool hasOverflow)
-{
- Frame* frame = renderer()->frame();
- if (!frame)
- return;
-
- FrameView* frameView = frame->view();
- if (!frameView)
- return;
-
- bool isVisibleToHitTest = renderer()->visibleToHitTesting();
- if (HTMLFrameOwnerElement* owner = frame->ownerElement())
- isVisibleToHitTest &= owner->renderer() && owner->renderer()->visibleToHitTesting();
-
- bool requiresScrollableArea = hasOverflow && isVisibleToHitTest;
- bool updatedScrollableAreaSet = false;
- if (requiresScrollableArea) {
- if (frameView->addScrollableArea(scrollableArea()))
- updatedScrollableAreaSet = true;
- } else {
- if (frameView->removeScrollableArea(scrollableArea()))
- updatedScrollableAreaSet = true;
- }
-
- if (updatedScrollableAreaSet) {
- // Count the total number of RenderLayers that are scrollable areas for
- // any period. We only want to record this at most once per RenderLayer.
- if (requiresScrollableArea && !m_isScrollableAreaHasBeenRecorded) {
- HistogramSupport::histogramEnumeration("Renderer.CompositedScrolling", IsScrollableAreaBucket, CompositedScrollingHistogramMax);
- m_isScrollableAreaHasBeenRecorded = true;
- }
-
- // We always want composited scrolling if compositor driven accelerated
- // scrolling is enabled. Since we will not update needs composited scrolling
- // in this case, we must force our state to update.
- if (compositorDrivenAcceleratedScrollingEnabled())
- didUpdateNeedsCompositedScrolling();
- else if (requiresScrollableArea)
- compositor()->setNeedsUpdateCompositingRequirementsState();
- else
- setNeedsCompositedScrolling(false);
+ } else if (compositingState() == PaintsIntoOwnBacking || compositingState() == HasOwnBackingButPaintsIntoAncestor) {
+ ASSERT(hasCompositedLayerMapping());
+ compositedLayerMapping()->updateGraphicsLayerGeometry();
+ } else if (compositingState() == PaintsIntoGroupedBacking) {
+ ASSERT(compositor()->layerSquashingEnabled());
+ ASSERT(groupedMapping());
+ // updateGraphicsLayerGeometry() is called to update the squashingLayer in case its size/position has changed.
+ // FIXME: Make sure to create a layout test that covers this scenario.
+ // FIXME: It is not expected that any other layers on the compositedLayerMapping would change. we should
+ // be able to just update the squashing layer only and save a lot of computation.
+ groupedMapping()->updateGraphicsLayerGeometry();
}
}
-void RenderLayer::updateResizerStyle()
+bool RenderLayer::scrollsOverflow() const
{
- RenderObject* actualRenderer = rendererForScrollbar(renderer());
- RefPtr<RenderStyle> resizer = renderer()->hasOverflowClip() ? actualRenderer->getUncachedPseudoStyle(PseudoStyleRequest(RESIZER), actualRenderer->style()) : PassRefPtr<RenderStyle>(0);
- if (resizer) {
- if (!m_resizer) {
- m_resizer = RenderScrollbarPart::createAnonymous(&renderer()->document());
- m_resizer->setParent(renderer());
- }
- m_resizer->setStyle(resizer.release());
- } else if (m_resizer) {
- m_resizer->destroy();
- m_resizer = 0;
- }
-}
+ if (RenderLayerScrollableArea* scrollableArea = this->scrollableArea())
+ return scrollableArea->scrollsOverflow();
-RenderLayer* RenderLayer::reflectionLayer() const
-{
- return m_reflection ? m_reflection->layer() : 0;
-}
-
-void RenderLayer::createReflection()
-{
- ASSERT(!m_reflection);
- m_reflection = RenderReplica::createAnonymous(&renderer()->document());
- m_reflection->setParent(renderer()); // We create a 1-way connection.
-}
-
-void RenderLayer::removeReflection()
-{
- if (!m_reflection->documentBeingDestroyed())
- m_reflection->removeLayers(this);
-
- m_reflection->setParent(0);
- m_reflection->destroy();
- m_reflection = 0;
-}
-
-void RenderLayer::updateReflectionStyle()
-{
- RefPtr<RenderStyle> newStyle = RenderStyle::create();
- newStyle->inheritFrom(renderer()->style());
-
- // Map in our transform.
- TransformOperations transform;
- switch (renderer()->style()->boxReflect()->direction()) {
- case ReflectionBelow:
- transform.operations().append(TranslateTransformOperation::create(Length(0, Fixed), Length(100., Percent), TransformOperation::Translate));
- transform.operations().append(TranslateTransformOperation::create(Length(0, Fixed), renderer()->style()->boxReflect()->offset(), TransformOperation::Translate));
- transform.operations().append(ScaleTransformOperation::create(1.0, -1.0, ScaleTransformOperation::Scale));
- break;
- case ReflectionAbove:
- transform.operations().append(ScaleTransformOperation::create(1.0, -1.0, ScaleTransformOperation::Scale));
- transform.operations().append(TranslateTransformOperation::create(Length(0, Fixed), Length(100., Percent), TransformOperation::Translate));
- transform.operations().append(TranslateTransformOperation::create(Length(0, Fixed), renderer()->style()->boxReflect()->offset(), TransformOperation::Translate));
- break;
- case ReflectionRight:
- transform.operations().append(TranslateTransformOperation::create(Length(100., Percent), Length(0, Fixed), TransformOperation::Translate));
- transform.operations().append(TranslateTransformOperation::create(renderer()->style()->boxReflect()->offset(), Length(0, Fixed), TransformOperation::Translate));
- transform.operations().append(ScaleTransformOperation::create(-1.0, 1.0, ScaleTransformOperation::Scale));
- break;
- case ReflectionLeft:
- transform.operations().append(ScaleTransformOperation::create(-1.0, 1.0, ScaleTransformOperation::Scale));
- transform.operations().append(TranslateTransformOperation::create(Length(100., Percent), Length(0, Fixed), TransformOperation::Translate));
- transform.operations().append(TranslateTransformOperation::create(renderer()->style()->boxReflect()->offset(), Length(0, Fixed), TransformOperation::Translate));
- break;
- }
- newStyle->setTransform(transform);
-
- // Map in our mask.
- newStyle->setMaskBoxImage(renderer()->style()->boxReflect()->mask());
-
- m_reflection->setStyle(newStyle.release());
+ return false;
}
bool RenderLayer::isCSSCustomFilterEnabled() const
{
// We only want to enable shaders if WebGL is also enabled on this platform.
const Settings* settings = renderer()->document().settings();
- return settings && settings->isCSSCustomFilterEnabled() && settings->webGLEnabled();
+ return settings && RuntimeEnabledFeatures::cssCustomFilterEnabled() && settings->webGLEnabled();
}
FilterOperations RenderLayer::computeFilterOperations(const RenderStyle* style)
@@ -5770,9 +4052,9 @@ FilterOperations RenderLayer::computeFilterOperations(const RenderStyle* style)
if (filters.hasReferenceFilter()) {
for (size_t i = 0; i < filters.size(); ++i) {
FilterOperation* filterOperation = filters.operations().at(i).get();
- if (filterOperation->getOperationType() != FilterOperation::REFERENCE)
+ if (filterOperation->type() != FilterOperation::REFERENCE)
continue;
- ReferenceFilterOperation* referenceOperation = static_cast<ReferenceFilterOperation*>(filterOperation);
+ ReferenceFilterOperation* referenceOperation = toReferenceFilterOperation(filterOperation);
// FIXME: Cache the ReferenceFilter if it didn't change.
RefPtr<ReferenceFilter> referenceFilter = ReferenceFilter::create();
float zoom = style->effectiveZoom() * WebCore::deviceScaleFactor(renderer()->frame());
@@ -5796,10 +4078,10 @@ FilterOperations RenderLayer::computeFilterOperations(const RenderStyle* style)
FilterOperations outputFilters;
for (size_t i = 0; i < filters.size(); ++i) {
RefPtr<FilterOperation> filterOperation = filters.operations().at(i);
- if (filterOperation->getOperationType() == FilterOperation::CUSTOM) {
+ if (filterOperation->type() == FilterOperation::CUSTOM) {
// We have to wait until the program of CSS Shaders is loaded before setting it on the layer.
// Note that we will handle the loading of the shaders and repainting of the layer in updateOrRemoveFilterClients.
- const CustomFilterOperation* customOperation = static_cast<const CustomFilterOperation*>(filterOperation.get());
+ const CustomFilterOperation* customOperation = toCustomFilterOperation(filterOperation.get());
RefPtr<CustomFilterProgram> program = customOperation->program();
if (!program->isLoaded())
continue;
@@ -5854,8 +4136,7 @@ void RenderLayer::updateOrRemoveFilterEffectRenderer()
RenderLayerFilterInfo* filterInfo = ensureFilterInfo();
if (!filterInfo->renderer()) {
RefPtr<FilterEffectRenderer> filterRenderer = FilterEffectRenderer::create();
- RenderingMode renderingMode = renderer()->frame()->page()->settings().acceleratedFiltersEnabled() ? Accelerated : Unaccelerated;
- filterRenderer->setRenderingMode(renderingMode);
+ filterRenderer->setIsAccelerated(renderer()->frame()->settings()->acceleratedFiltersEnabled());
filterInfo->setRenderer(filterRenderer.release());
// We can optimize away code paths in other places if we know that there are no software filters.
@@ -5902,66 +4183,6 @@ void RenderLayer::addLayerHitTestRects(LayerHitTestRects& rects) const
child->addLayerHitTestRects(rects);
}
-const IntPoint& RenderLayer::scrollOrigin() const
-{
- if (!m_scrollableArea) {
- static IntPoint emptyPoint = IntPoint::zero();
- return emptyPoint;
- }
-
- return m_scrollableArea->scrollOrigin();
-}
-
-int RenderLayer::scrollXOffset() const
-{
- return m_scrollableArea->scrollXOffset();
-}
-
-int RenderLayer::scrollYOffset() const
-{
- return m_scrollableArea->scrollYOffset();
-}
-
-IntSize RenderLayer::scrolledContentOffset() const
-{
- return m_scrollableArea->scrollOffset();
-}
-
-bool RenderLayer::hasOverlayScrollbars() const
-{
- return m_scrollableArea && m_scrollableArea->hasOverlayScrollbars();
-}
-
-Scrollbar* RenderLayer::horizontalScrollbar() const
-{
- return m_scrollableArea->horizontalScrollbar();
-}
-
-Scrollbar* RenderLayer::verticalScrollbar() const
-{
- return m_scrollableArea->verticalScrollbar();
-}
-
-bool RenderLayer::hasVerticalScrollbar() const
-{
- return m_scrollableArea->hasVerticalScrollbar();
-}
-
-bool RenderLayer::hasHorizontalScrollbar() const
-{
- return m_scrollableArea->hasHorizontalScrollbar();
-}
-
-int RenderLayer::verticalScrollbarWidth(OverlayScrollbarSizeRelevancy relevancy) const
-{
- return m_scrollableArea->verticalScrollbarWidth(relevancy);
-}
-
-int RenderLayer::horizontalScrollbarHeight(OverlayScrollbarSizeRelevancy relevancy) const
-{
- return m_scrollableArea->horizontalScrollbarHeight(relevancy);
-}
-
} // namespace WebCore
#ifndef NDEBUG
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderLayer.h b/chromium/third_party/WebKit/Source/core/rendering/RenderLayer.h
index e3b78c5d31a..06dd644f8b7 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderLayer.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderLayer.h
@@ -45,16 +45,20 @@
#ifndef RenderLayer_h
#define RenderLayer_h
-#include "core/rendering/ClipRect.h"
+#include "core/rendering/CompositedLayerMappingPtr.h"
#include "core/rendering/CompositingReasons.h"
+#include "core/rendering/LayerPaintingInfo.h"
#include "core/rendering/PaintInfo.h"
#include "core/rendering/RenderBox.h"
+#include "core/rendering/RenderLayerClipper.h"
+#include "core/rendering/RenderLayerFilterInfo.h"
+#include "core/rendering/RenderLayerReflectionInfo.h"
+#include "core/rendering/RenderLayerRepainter.h"
#include "core/rendering/RenderLayerScrollableArea.h"
-
+#include "core/rendering/RenderLayerStackingNode.h"
+#include "core/rendering/RenderLayerStackingNodeIterator.h"
#include "wtf/OwnPtr.h"
-#include "core/rendering/RenderLayerFilterInfo.h"
-
namespace WebCore {
class FilterEffectRenderer;
@@ -65,7 +69,7 @@ class HitTestingTransformState;
class PlatformEvent;
class RenderFlowThread;
class RenderGeometryMap;
-class RenderLayerBacking;
+class CompositedLayerMapping;
class RenderLayerCompositor;
class RenderReplica;
class RenderScrollbarPart;
@@ -76,16 +80,12 @@ class TransformationMatrix;
enum BorderRadiusClippingRule { IncludeSelfForBorderRadius, DoNotIncludeSelfForBorderRadius };
-enum RepaintStatus {
- NeedsNormalRepaint = 0,
- NeedsFullRepaint = 1 << 0,
- NeedsFullRepaintForPositionedMovementLayout = 1 << 1
-};
-
class RenderLayer {
public:
friend class RenderReplica;
// FIXME: Needed until we move all the necessary bits to the new class.
+ friend class RenderLayerStackingNode;
+ // FIXME: Needed until we move all the necessary bits to the new class.
friend class RenderLayerScrollableArea;
RenderLayer(RenderLayerModelObject*);
@@ -107,17 +107,8 @@ public:
void removeOnlyThisLayer();
void insertOnlyThisLayer();
- void repaintIncludingDescendants();
-
- // Indicate that the layer contents need to be repainted. Only has an effect
- // if layer compositing is being used,
- void setBackingNeedsRepaint();
- void setBackingNeedsRepaintInRect(const LayoutRect&); // r is in the coordinate space of the layer's render object
- void repaintIncludingNonCompositingDescendants(RenderLayerModelObject* repaintContainer);
-
void styleChanged(StyleDifference, const RenderStyle* oldStyle);
- bool isNormalFlowOnly() const { return m_isNormalFlowOnly; }
bool isSelfPaintingLayer() const { return m_isSelfPaintingLayer; }
bool cannotBlitToWindow() const;
@@ -126,10 +117,9 @@ public:
RenderLayer* transparentPaintingAncestor();
void beginTransparencyLayers(GraphicsContext*, const RenderLayer* rootLayer, const LayoutRect& paintDirtyRect, PaintBehavior);
- bool hasReflection() const { return renderer()->hasReflection(); }
bool isReflection() const { return renderer()->isReplica(); }
- RenderReplica* reflection() const { return m_reflection; }
- RenderLayer* reflectionLayer() const;
+ RenderLayerReflectionInfo* reflectionInfo() { return m_reflectionInfo.get(); }
+ const RenderLayerReflectionInfo* reflectionInfo() const { return m_reflectionInfo.get(); }
const RenderLayer* root() const
{
@@ -147,42 +137,6 @@ public:
LayoutRect rect() const { return LayoutRect(location(), size()); }
- // See comments on isPointInResizeControl.
- IntRect resizerCornerRect(const IntRect& bounds, ResizerHitTestType) const;
-
- int scrollWidth() const;
- int scrollHeight() const;
-
- void panScrollFromPoint(const IntPoint&);
-
- // Scrolling methods for layers that can scroll their overflow.
- void scrollByRecursively(const IntSize&, ScrollOffsetClamping = ScrollOffsetUnclamped);
- void scrollToOffset(const IntSize&, ScrollOffsetClamping = ScrollOffsetUnclamped);
- void scrollToXOffset(int x, ScrollOffsetClamping clamp = ScrollOffsetUnclamped) { scrollToOffset(IntSize(x, scrollYOffset()), clamp); }
- void scrollToYOffset(int y, ScrollOffsetClamping clamp = ScrollOffsetUnclamped) { scrollToOffset(IntSize(scrollXOffset(), y), clamp); }
- void scrollRectToVisible(const LayoutRect&, const ScrollAlignment& alignX, const ScrollAlignment& alignY);
-
- LayoutRect getRectToExpose(const LayoutRect& visibleRect, const LayoutRect& exposeRect, const ScrollAlignment& alignX, const ScrollAlignment& alignY);
-
- // isPointInResizeControl() is used for testing if a pointer/touch position is in the resize control
- // area.
- bool isPointInResizeControl(const IntPoint& absolutePoint, ResizerHitTestType resizerHitTestType) const;
- bool hitTestOverflowControls(HitTestResult&, const IntPoint& localPoint);
- IntSize offsetFromResizeCorner(const IntPoint& absolutePoint) const;
-
- void paintOverflowControls(GraphicsContext*, const IntPoint&, const IntRect& damageRect, bool paintingOverlayControls = false);
- void paintScrollCorner(GraphicsContext*, const IntPoint&, const IntRect& damageRect);
- void paintResizer(GraphicsContext*, const IntPoint&, const IntRect& damageRect);
-
- void updateScrollInfoAfterLayout();
-
- bool scroll(ScrollDirection, ScrollGranularity, float multiplier = 1);
- void autoscroll(const IntPoint&);
-
- void resize(const PlatformEvent&, const LayoutSize&);
- bool inResizeMode() const { return m_inResizeMode; }
- void setInResizeMode(bool b) { m_inResizeMode = b; }
-
bool isRootLayer() const { return m_isRootLayer; }
RenderLayerCompositor* compositor() const;
@@ -208,8 +162,6 @@ public:
void updateLayerPositionsAfterOverflowScroll();
void updateLayerPositionsAfterDocumentScroll();
- void positionNewlyCreatedOverflowControls();
-
bool isPaginated() const { return m_isPaginated; }
RenderLayer* enclosingPaginationLayer() const { return m_enclosingPaginationLayer; }
@@ -219,53 +171,15 @@ public:
const LayoutSize& offsetForInFlowPosition() const { return m_offsetForInFlowPosition; }
- void clearClipRectsIncludingDescendants(ClipRectsType typeToClear = AllClipRectTypes);
- void clearClipRects(ClipRectsType typeToClear = AllClipRectTypes);
-
void addBlockSelectionGapsBounds(const LayoutRect&);
void clearBlockSelectionGapsBounds();
void repaintBlockSelectionGaps();
+ bool hasBlockSelectionGapBounds() const;
- // A stacking context is a layer that has a non-auto z-index.
- bool isStackingContext() const { return isStackingContext(renderer()->style()); }
-
- // A stacking container can have z-order lists. All stacking contexts are
- // stacking containers, but the converse is not true. Layers that use
- // composited scrolling are stacking containers, but they may not
- // necessarily be stacking contexts.
- bool isStackingContainer() const { return isStackingContext() || needsToBeStackingContainer(); }
-
- RenderLayer* ancestorStackingContainer() const;
- RenderLayer* ancestorStackingContext() const;
-
- // Gets the enclosing stacking container for this layer, possibly the layer
- // itself, if it is a stacking container.
- RenderLayer* enclosingStackingContainer() { return isStackingContainer() ? this : ancestorStackingContainer(); }
-
- void dirtyZOrderLists();
- void dirtyStackingContainerZOrderLists();
-
- Vector<RenderLayer*>* posZOrderList() const
- {
- ASSERT(!m_zOrderListsDirty);
- ASSERT(isStackingContainer() || !m_posZOrderList);
- return m_posZOrderList.get();
- }
-
- bool hasNegativeZOrderList() const { return negZOrderList() && negZOrderList()->size(); }
-
- Vector<RenderLayer*>* negZOrderList() const
- {
- ASSERT(!m_zOrderListsDirty);
- ASSERT(isStackingContainer() || !m_negZOrderList);
- return m_negZOrderList.get();
- }
-
- void dirtyNormalFlowList();
- Vector<RenderLayer*>* normalFlowList() const { ASSERT(!m_normalFlowListDirty); return m_normalFlowList.get(); }
+ RenderLayerStackingNode* stackingNode() { return m_stackingNode.get(); }
+ const RenderLayerStackingNode* stackingNode() const { return m_stackingNode.get(); }
- // Update our normal and z-index lists.
- void updateLayerListsIfNeeded();
+ bool subtreeIsInvisible() const { return !hasVisibleContent() && !hasVisibleDescendant(); }
// FIXME: We should ASSERT(!m_visibleContentStatusDirty) here, but see https://bugs.webkit.org/show_bug.cgi?id=71044
// ditto for hasVisibleDescendant(), see https://bugs.webkit.org/show_bug.cgi?id=71277
@@ -292,11 +206,16 @@ public:
void setHasOutOfFlowPositionedDescendant(bool hasDescendant) { m_hasOutOfFlowPositionedDescendant = hasDescendant; }
void setHasOutOfFlowPositionedDescendantDirty(bool dirty) { m_hasOutOfFlowPositionedDescendantDirty = dirty; }
+ bool childLayerHasBlendMode() const { ASSERT(!m_childLayerHasBlendModeStatusDirty); return m_childLayerHasBlendMode; }
+
bool hasUnclippedDescendant() const { return m_hasUnclippedDescendant; }
void setHasUnclippedDescendant(bool hasDescendant) { m_hasUnclippedDescendant = hasDescendant; }
void updateHasUnclippedDescendant();
bool isUnclippedDescendant() const { return m_isUnclippedDescendant; }
+ bool hasVisibleNonLayerContent() const { return m_hasVisibleNonLayerContent; }
+ void updateHasVisibleNonLayerContent();
+
// Gets the nearest enclosing positioned ancestor layer (also includes
// the <html> layer and the root layer).
RenderLayer* enclosingPositionedAncestor() const;
@@ -313,12 +232,14 @@ public:
// Ancestor compositing layer, excluding this.
RenderLayer* ancestorCompositingLayer() const { return enclosingCompositingLayer(false); }
+ // Ancestor composited scrolling layer at or above our containing block.
+ RenderLayer* ancestorCompositedScrollingLayer() const;
+
// Ancestor scrolling layer at or above our containing block.
RenderLayer* ancestorScrollingLayer() const;
RenderLayer* enclosingFilterLayer(bool includeSelf = true) const;
RenderLayer* enclosingFilterRepaintLayer() const;
- void setFilterBackendNeedsRepaintingInRect(const LayoutRect&);
bool hasAncestorWithFilterOutsets() const;
bool canUseConvertToLayerCoords() const
@@ -332,26 +253,6 @@ public:
void convertToLayerCoords(const RenderLayer* ancestorLayer, LayoutPoint& location) const;
void convertToLayerCoords(const RenderLayer* ancestorLayer, LayoutRect&) const;
- int zIndex() const { return renderer()->style()->zIndex(); }
-
- enum PaintLayerFlag {
- PaintLayerHaveTransparency = 1,
- PaintLayerAppliedTransform = 1 << 1,
- PaintLayerTemporaryClipRects = 1 << 2,
- PaintLayerPaintingReflection = 1 << 3,
- PaintLayerPaintingOverlayScrollbars = 1 << 4,
- PaintLayerPaintingCompositingBackgroundPhase = 1 << 5,
- PaintLayerPaintingCompositingForegroundPhase = 1 << 6,
- PaintLayerPaintingCompositingMaskPhase = 1 << 7,
- PaintLayerPaintingCompositingScrollingPhase = 1 << 8,
- PaintLayerPaintingOverflowContents = 1 << 9,
- PaintLayerPaintingRootBackgroundOnly = 1 << 10,
- PaintLayerPaintingSkipRootBackground = 1 << 11,
- PaintLayerPaintingCompositingAllPhases = (PaintLayerPaintingCompositingBackgroundPhase | PaintLayerPaintingCompositingForegroundPhase | PaintLayerPaintingCompositingMaskPhase)
- };
-
- typedef unsigned PaintLayerFlags;
-
// The two main functions that use the layer system. The paint method
// paints the layers that intersect the damage rect from back to
// front. The hitTest method looks for mouse events by walking
@@ -362,21 +263,6 @@ public:
bool hitTest(const HitTestRequest&, const HitTestLocation&, HitTestResult&);
void paintOverlayScrollbars(GraphicsContext*, const LayoutRect& damageRect, PaintBehavior, RenderObject* paintingRoot = 0);
- struct ClipRectsContext {
- ClipRectsContext(const RenderLayer* inRootLayer, RenderRegion* inRegion, ClipRectsType inClipRectsType, OverlayScrollbarSizeRelevancy inOverlayScrollbarSizeRelevancy = IgnoreOverlayScrollbarSize, ShouldRespectOverflowClip inRespectOverflowClip = RespectOverflowClip)
- : rootLayer(inRootLayer)
- , region(inRegion)
- , clipRectsType(inClipRectsType)
- , overlayScrollbarSizeRelevancy(inOverlayScrollbarSizeRelevancy)
- , respectOverflowClip(inRespectOverflowClip)
- { }
- const RenderLayer* rootLayer;
- RenderRegion* region;
- ClipRectsType clipRectsType;
- OverlayScrollbarSizeRelevancy overlayScrollbarSizeRelevancy;
- ShouldRespectOverflowClip respectOverflowClip;
- };
-
// This method figures out our layerBounds in coordinates relative to
// |rootLayer}. It also computes our background and foreground clip rects
// for painting/event handling.
@@ -384,18 +270,6 @@ public:
void calculateRects(const ClipRectsContext&, const LayoutRect& paintDirtyRect, LayoutRect& layerBounds,
ClipRect& backgroundRect, ClipRect& foregroundRect, ClipRect& outlineRect, const LayoutPoint* offsetFromRoot = 0) const;
- // Compute and cache clip rects computed with the given layer as the root
- void updateClipRects(const ClipRectsContext&);
- // Compute and return the clip rects. If useCached is true, will used previously computed clip rects on ancestors
- // (rather than computing them all from scratch up the parent chain).
- void calculateClipRects(const ClipRectsContext&, ClipRects&) const;
-
- ClipRects* clipRects(const ClipRectsContext& context) const
- {
- ASSERT(context.clipRectsType < NumCachedClipRectsTypes);
- return m_clipRectsCache ? m_clipRectsCache->getClipRects(context.clipRectsType, context.respectOverflowClip).get() : 0;
- }
-
LayoutRect childrenClipRect() const; // Returns the foreground clip rect of the layer in the document's coordinate space.
LayoutRect selfClipRect() const; // Returns the background clip rect of the layer in the document's coordinate space.
LayoutRect localClipRect() const; // Returns the background clip rect of the layer in the local coordinate space.
@@ -411,6 +285,7 @@ public:
DontConstrainForMask = 1 << 4,
IncludeCompositedDescendants = 1 << 5,
UseFragmentBoxes = 1 << 6,
+ PretendLayerHasOwnBacking = 1 << 7,
DefaultCalculateLayerBoundsFlags = IncludeSelfTransform | UseLocalClipRectIfPossible | IncludeLayerFilterOutsets | UseFragmentBoxes
};
typedef unsigned CalculateLayerBoundsFlags;
@@ -435,12 +310,6 @@ public:
// WARNING: This method returns the offset for the parent as this is what updateLayerPositions expects.
LayoutPoint computeOffsetFromRoot(bool& hasLayerOffset) const;
- // Return a cached repaint rect, computed relative to the layer renderer's containerForRepaint.
- LayoutRect repaintRect() const { return m_repaintRect; }
- LayoutRect repaintRectIncludingNonCompositingDescendants() const;
-
- void setRepaintStatus(RepaintStatus status) { m_repaintStatus = status; }
-
LayoutUnit staticInlinePosition() const { return m_staticInlinePosition; }
LayoutUnit staticBlockPosition() const { return m_staticBlockPosition; }
@@ -468,18 +337,31 @@ public:
bool hasFilter() const { return renderer()->hasFilter(); }
bool hasBlendMode() const;
+ bool paintsWithBlendMode() const { return hasBlendMode() && compositingState() != PaintsIntoOwnBacking; }
void* operator new(size_t);
// Only safe to call from RenderLayerModelObject::destroyLayer()
void operator delete(void*);
- bool isComposited() const { return m_backing != 0; }
+ CompositingState compositingState() const;
+
+ CompositedLayerMappingPtr compositedLayerMapping() const { return m_compositedLayerMapping.get(); }
+ CompositedLayerMappingPtr ensureCompositedLayerMapping();
+
+ // NOTE: If you are using hasCompositedLayerMapping to determine the state of compositing for this layer,
+ // (and not just to do bookkeeping related to the mapping like, say, allocating or deallocating a mapping),
+ // then you may have incorrect logic. Use compositingState() instead.
+ bool hasCompositedLayerMapping() const { return m_compositedLayerMapping.get(); }
+ void clearCompositedLayerMapping(bool layerBeingDestroyed = false);
+
+ CompositedLayerMapping* groupedMapping() const { return m_groupedMapping; }
+ void setGroupedMapping(CompositedLayerMapping* groupedMapping) { m_groupedMapping = groupedMapping; }
+
bool hasCompositedMask() const;
- RenderLayerBacking* backing() const { return m_backing.get(); }
- RenderLayerBacking* ensureBacking();
- void clearBacking(bool layerBeingDestroyed = false);
- bool needsCompositedScrolling() const;
- bool needsToBeStackingContainer() const;
+ bool hasCompositedClippingMask() const;
+ bool needsCompositedScrolling() const { return m_scrollableArea && m_scrollableArea->needsCompositedScrolling(); }
+
+ bool clipsCompositingDescendantsWithBorderRadius() const;
RenderLayer* scrollParent() const;
RenderLayer* clipParent() const;
@@ -487,10 +369,11 @@ public:
bool needsCompositingLayersRebuiltForClip(const RenderStyle* oldStyle, const RenderStyle* newStyle) const;
bool needsCompositingLayersRebuiltForOverflow(const RenderStyle* oldStyle, const RenderStyle* newStyle) const;
bool needsCompositingLayersRebuiltForFilters(const RenderStyle* oldStyle, const RenderStyle* newStyle, bool didPaintWithFilters) const;
+ bool needsCompositingLayersRebuiltForBlending(const RenderStyle* oldStyle, const RenderStyle* newStyle) const;
bool paintsWithTransparency(PaintBehavior paintBehavior) const
{
- return isTransparent() && ((paintBehavior & PaintBehaviorFlattenCompositingLayers) || !isComposited());
+ return isTransparent() && ((paintBehavior & PaintBehaviorFlattenCompositingLayers) || compositingState() != PaintsIntoOwnBacking);
}
bool paintsWithTransform(PaintBehavior) const;
@@ -526,11 +409,6 @@ public:
void updateFilters(const RenderStyle* oldStyle, const RenderStyle* newStyle);
-#if !ASSERT_DISABLED
- bool layerListMutationAllowed() const { return m_layerListMutationAllowed; }
- void setLayerListMutationAllowed(bool flag) { m_layerListMutationAllowed = flag; }
-#endif
-
Node* enclosingElement() const;
bool isInTopLayer() const;
@@ -549,44 +427,35 @@ public:
bool isOutOfFlowRenderFlowThread() const { return renderer()->isOutOfFlowRenderFlowThread(); }
- enum PaintOrderListType {BeforePromote, AfterPromote};
- void computePaintOrderList(PaintOrderListType type, Vector<RefPtr<Node> >&);
bool scrollsWithRespectTo(const RenderLayer*) const;
- enum ForceNeedsCompositedScrollingMode {
- DoNotForceCompositedScrolling = 0,
- CompositedScrollingAlwaysOn = 1,
- CompositedScrollingAlwaysOff = 2
- };
-
- void setForceNeedsCompositedScrolling(ForceNeedsCompositedScrollingMode);
-
void addLayerHitTestRects(LayerHitTestRects&) const;
- ScrollableArea* scrollableArea() const { return m_scrollableArea.get(); }
-
-private:
- enum CollectLayersBehavior {
- ForceLayerToStackingContainer,
- OverflowScrollCanBeStackingContainers,
- OnlyStackingContextsCanBeStackingContainers
- };
+ // FIXME: This should probably return a ScrollableArea but a lot of internal methods are mistakenly exposed.
+ RenderLayerScrollableArea* scrollableArea() const { return m_scrollableArea.get(); }
+ RenderLayerRepainter& repainter() { return m_repainter; }
+ RenderLayerClipper& clipper() { return m_clipper; }
- bool hasOverflowControls() const;
+ inline bool isPositionedContainer() const
+ {
+ // FIXME: This is not in sync with containingBlock.
+ // RenderObject::canContainFixedPositionedObject() should probably be used
+ // instead.
+ RenderLayerModelObject* layerRenderer = renderer();
+ return isRootLayer() || layerRenderer->isPositioned() || hasTransform();
+ }
- void updateZOrderLists();
- void rebuildZOrderLists();
- // See the comment for collectLayers for information about the layerToForceAsStackingContainer parameter.
- void rebuildZOrderLists(OwnPtr<Vector<RenderLayer*> >&, OwnPtr<Vector<RenderLayer*> >&, const RenderLayer* layerToForceAsStackingContainer = 0, CollectLayersBehavior = OverflowScrollCanBeStackingContainers);
- void clearZOrderLists();
- void setIsUnclippedDescendant(bool isUnclippedDescendant) { m_isUnclippedDescendant = isUnclippedDescendant; }
+ void paintLayer(GraphicsContext*, const LayerPaintingInfo&, PaintLayerFlags);
+ PassOwnPtr<Vector<FloatRect> > collectTrackedRepaintRects() const;
- void updateNormalFlowList();
+ void setOffsetFromSquashingLayerOrigin(IntSize offset) { m_compositingProperties.offsetFromSquashingLayerOrigin = offset; }
+ IntSize offsetFromSquashingLayerOrigin() const { return m_compositingProperties.offsetFromSquashingLayerOrigin; }
- bool isStackingContext(const RenderStyle* style) const { return !style->hasAutoZIndex() || isRootLayer(); }
+private:
+ bool hasOverflowControls() const;
- bool isDirtyStackingContainer() const { return m_zOrderListsDirty && isStackingContainer(); }
+ void setIsUnclippedDescendant(bool isUnclippedDescendant) { m_isUnclippedDescendant = isUnclippedDescendant; }
void setAncestorChainHasSelfPaintingLayerDescendant();
void dirtyAncestorChainHasSelfPaintingLayerDescendantStatus();
@@ -598,31 +467,16 @@ private:
// FIXME: This is a temporary flag and should be removed once accelerated
// overflow scroll is ready (crbug.com/254111).
bool compositorDrivenAcceleratedScrollingEnabled() const;
- void updateCanBeStackingContainer();
- void collectBeforePromotionZOrderList(RenderLayer* ancestorStackingContext, OwnPtr<Vector<RenderLayer*> >& posZOrderListBeforePromote, OwnPtr<Vector<RenderLayer*> >& negZOrderListBeforePromote);
- void collectAfterPromotionZOrderList(RenderLayer* ancestorStackingContext, OwnPtr<Vector<RenderLayer*> >& posZOrderListAfterPromote, OwnPtr<Vector<RenderLayer*> >& negZOrderListAfterPromote);
-
- void dirtyNormalFlowListCanBePromotedToStackingContainer();
- void dirtySiblingStackingContextCanBePromotedToStackingContainer();
-
- void computeRepaintRects(const RenderLayerModelObject* repaintContainer, const RenderGeometryMap* = 0);
- void computeRepaintRectsIncludingDescendants();
- void clearRepaintRects();
void clipToRect(RenderLayer* rootLayer, GraphicsContext*, const LayoutRect& paintDirtyRect, const ClipRect&,
BorderRadiusClippingRule = IncludeSelfForBorderRadius);
void restoreClip(GraphicsContext*, const LayoutRect& paintDirtyRect, const ClipRect&);
- bool shouldRepaintAfterLayout() const;
-
void updateSelfPaintingLayer();
- void updateIsNormalFlowOnly();
void updateVisibilityAfterStyleChange(const RenderStyle* oldStyle);
- void updateStackingContextsAfterStyleChange(const RenderStyle* oldStyle);
void updateOutOfFlowPositioned(const RenderStyle* oldStyle);
- void setNeedsCompositedScrolling(bool);
void didUpdateNeedsCompositedScrolling();
// Returns true if the position changed.
@@ -648,38 +502,10 @@ private:
LayoutPoint renderBoxLocation() const { return renderer()->isBox() ? toRenderBox(renderer())->location() : LayoutPoint(); }
- // layerToForceAsStackingContainer allows us to build pre-promotion and
- // post-promotion layer lists, by allowing us to treat a layer as if it is a
- // stacking context, without adding a new member to RenderLayer or modifying
- // the style (which could cause extra allocations).
- void collectLayers(bool includeHiddenLayers, OwnPtr<Vector<RenderLayer*> >&, OwnPtr<Vector<RenderLayer*> >&, const RenderLayer* layerToForceAsStackingContainer = 0, CollectLayersBehavior = OverflowScrollCanBeStackingContainers);
-
- struct LayerPaintingInfo {
- LayerPaintingInfo(RenderLayer* inRootLayer, const LayoutRect& inDirtyRect, PaintBehavior inPaintBehavior, const LayoutSize& inSubPixelAccumulation, RenderObject* inPaintingRoot = 0, RenderRegion*inRegion = 0, OverlapTestRequestMap* inOverlapTestRequests = 0)
- : rootLayer(inRootLayer)
- , paintingRoot(inPaintingRoot)
- , paintDirtyRect(inDirtyRect)
- , subPixelAccumulation(inSubPixelAccumulation)
- , region(inRegion)
- , overlapTestRequests(inOverlapTestRequests)
- , paintBehavior(inPaintBehavior)
- , clipToDirtyRect(true)
- { }
- RenderLayer* rootLayer;
- RenderObject* paintingRoot; // only paint descendants of this object
- LayoutRect paintDirtyRect; // relative to rootLayer;
- LayoutSize subPixelAccumulation;
- RenderRegion* region; // May be null.
- OverlapTestRequestMap* overlapTestRequests; // May be null.
- PaintBehavior paintBehavior;
- bool clipToDirtyRect;
- };
-
- void paintLayer(GraphicsContext*, const LayerPaintingInfo&, PaintLayerFlags);
void paintLayerContentsAndReflection(GraphicsContext*, const LayerPaintingInfo&, PaintLayerFlags);
void paintLayerByApplyingTransform(GraphicsContext*, const LayerPaintingInfo&, PaintLayerFlags, const LayoutPoint& translationOffset = LayoutPoint());
void paintLayerContents(GraphicsContext*, const LayerPaintingInfo&, PaintLayerFlags);
- void paintList(Vector<RenderLayer*>*, GraphicsContext*, const LayerPaintingInfo&, PaintLayerFlags);
+ void paintChildren(unsigned childrenToVisit, GraphicsContext*, const LayerPaintingInfo&, PaintLayerFlags);
void paintPaginatedChildLayer(RenderLayer* childLayer, GraphicsContext*, const LayerPaintingInfo&, PaintLayerFlags);
void paintChildLayerIntoColumns(RenderLayer* childLayer, GraphicsContext*, const LayerPaintingInfo&, PaintLayerFlags, const Vector<RenderLayer*>& columnLayers, size_t columnIndex);
@@ -696,6 +522,7 @@ private:
void paintOutlineForFragments(const LayerFragments&, GraphicsContext*, const LayerPaintingInfo&, PaintBehavior, RenderObject* paintingRootForRenderer);
void paintOverflowControlsForFragments(const LayerFragments&, GraphicsContext*, const LayerPaintingInfo&);
void paintMaskForFragments(const LayerFragments&, GraphicsContext*, const LayerPaintingInfo&, RenderObject* paintingRootForRenderer);
+ void paintChildClippingMaskForFragments(const LayerFragments&, GraphicsContext*, const LayerPaintingInfo&, RenderObject* paintingRootForRenderer);
void paintTransformedLayerIntoFragments(GraphicsContext*, const LayerPaintingInfo&, PaintLayerFlags);
RenderLayer* hitTestLayer(RenderLayer* rootLayer, RenderLayer* containerLayer, const HitTestRequest& request, HitTestResult& result,
@@ -704,7 +531,7 @@ private:
RenderLayer* hitTestLayerByApplyingTransform(RenderLayer* rootLayer, RenderLayer* containerLayer, const HitTestRequest&, HitTestResult&,
const LayoutRect& hitTestRect, const HitTestLocation&, const HitTestingTransformState* = 0, double* zOffset = 0,
const LayoutPoint& translationOffset = LayoutPoint());
- RenderLayer* hitTestList(Vector<RenderLayer*>*, RenderLayer* rootLayer, const HitTestRequest& request, HitTestResult& result,
+ RenderLayer* hitTestChildren(ChildrenIteration, RenderLayer* rootLayer, const HitTestRequest&, HitTestResult&,
const LayoutRect& hitTestRect, const HitTestLocation&,
const HitTestingTransformState* transformState, double* zOffsetForDescendants, double* zOffset,
const HitTestingTransformState* unflattenedTransformState, bool depthSortDescendants);
@@ -723,78 +550,35 @@ private:
bool hitTestContents(const HitTestRequest&, HitTestResult&, const LayoutRect& layerBounds, const HitTestLocation&, HitTestFilter) const;
bool hitTestContentsForFragments(const LayerFragments&, const HitTestRequest&, HitTestResult&, const HitTestLocation&, HitTestFilter, bool& insideClipRect) const;
- bool hitTestResizerInFragments(const LayerFragments&, const HitTestLocation&) const;
RenderLayer* hitTestTransformedLayerInFragments(RenderLayer* rootLayer, RenderLayer* containerLayer, const HitTestRequest&, HitTestResult&,
const LayoutRect& hitTestRect, const HitTestLocation&, const HitTestingTransformState* = 0, double* zOffset = 0);
- bool listBackgroundIsKnownToBeOpaqueInRect(const Vector<RenderLayer*>*, const LayoutRect&) const;
-
- bool shouldBeNormalFlowOnly() const;
- bool shouldBeNormalFlowOnlyIgnoringCompositedScrolling() const;
+ bool childBackgroundIsKnownToBeOpaqueInRect(const LayoutRect&) const;
bool shouldBeSelfPaintingLayer() const;
- // Start of ScrollableArea interface
- // To be moved to RenderLayerScrollableArea
- ScrollableArea* enclosingScrollableArea() const;
+private:
+ // FIXME: We should only create the stacking node if needed.
+ bool requiresStackingNode() const { return true; }
+ void updateStackingNode();
- void updateNeedsCompositedScrolling();
+ void updateReflectionInfo(const RenderStyle*);
-public:
- GraphicsLayer* layerForScrolling() const;
- GraphicsLayer* layerForScrollChild() const;
- GraphicsLayer* layerForHorizontalScrollbar() const;
- GraphicsLayer* layerForVerticalScrollbar() const;
- GraphicsLayer* layerForScrollCorner() const;
- bool usesCompositedScrolling() const;
-
- bool hasOverlayScrollbars() const;
- Scrollbar* horizontalScrollbar() const;
- Scrollbar* verticalScrollbar() const;
- bool hasVerticalScrollbar() const;
- bool hasHorizontalScrollbar() const;
- int verticalScrollbarWidth(OverlayScrollbarSizeRelevancy = IgnoreOverlayScrollbarSize) const;
- int horizontalScrollbarHeight(OverlayScrollbarSizeRelevancy = IgnoreOverlayScrollbarSize) const;
-
- int scrollXOffset() const;
- int scrollYOffset() const;
- friend IntSize RenderBox::scrolledContentOffset() const;
- IntSize scrolledContentOffset() const;
- IntSize adjustedScrollOffset() const { return IntSize(scrollXOffset(), scrollYOffset()); }
+ // FIXME: We could lazily allocate our ScrollableArea based on style properties ('overflow', ...)
+ // but for now, we are always allocating it for RenderBox as it's safer.
+ bool requiresScrollableArea() const { return renderBox(); }
+ void updateScrollableArea();
-private:
- void invalidateScrollCornerRect(const IntRect&);
- bool isActive() const;
- bool isScrollCornerVisible() const;
- IntRect scrollCornerRect() const;
- int scrollSize(ScrollbarOrientation) const;
- int visibleHeight() const;
- int visibleWidth() const;
- IntSize overhangAmount() const;
- IntPoint lastKnownMousePosition() const;
- bool shouldSuspendScrollAnimations() const;
- bool scrollbarsCanBeActive() const;
- IntRect scrollableAreaBoundingBox() const;
- bool userInputScrollable(ScrollbarOrientation) const;
- bool shouldPlaceVerticalScrollbarOnLeft() const;
- int pageStep(ScrollbarOrientation) const;
- // End of ScrollableArea interface
-
- // FIXME: This should be removed once we have transitioned to RenderLayerScrollableArea.
- const IntPoint& scrollOrigin() const;
-
- // Rectangle encompassing the scroll corner and resizer rect.
- IntRect scrollCornerAndResizerRect() const;
-
- void updateCompositingLayersAfterScroll();
-
- bool requiresScrollableArea() const { return renderer()->style()->overflowX() != OVISIBLE || renderer()->canResize() || usesCompositedScrolling(); }
- void updateResizerAreaSet();
- void updateScrollableAreaSet(bool hasOverflow);
+ // Returns true our scrollable area is in the FrameView's collection of scrollable areas. This can
+ // only happen if we're both scrollable, and we do in fact overflow.
+ bool scrollsOverflow() const;
void dirtyAncestorChainVisibleDescendantStatus();
void setAncestorChainHasVisibleDescendant();
+ void dirtyAncestorChainBlendedDescendantStatus();
+ void setAncestorChainBlendedDescendant();
+
void updateDescendantDependentFlags();
// This flag is computed by RenderLayerCompositor, which knows more about 3d hierarchies than we do.
@@ -805,13 +589,6 @@ private:
// Both updates the status, and returns true if descendants of this have 3d.
bool update3DTransformedDescendantStatus();
- void createReflection();
- void removeReflection();
-
- void updateReflectionStyle();
- bool paintingInsideReflection() const { return m_paintingInsideReflection; }
- void setPaintingInsideReflection(bool b) { m_paintingInsideReflection = b; }
-
void updateOrRemoveFilterClients();
void updateOrRemoveFilterEffectRenderer();
@@ -822,14 +599,6 @@ private:
RenderLayer* enclosingTransformedAncestor() const;
- // Convert a point in absolute coords into layer coords, taking transforms into account
- LayoutPoint absoluteToContents(const LayoutPoint&) const;
-
- void positionOverflowControls(const IntSize&);
- void updateResizerStyle();
-
- void drawPlatformResizerImage(GraphicsContext*, IntRect resizerCornerRect);
-
void updatePagination();
// FIXME: Temporary. Remove when new columns come online.
@@ -838,26 +607,20 @@ private:
bool hasCompositingDescendant() const { return m_compositingProperties.hasCompositingDescendant; }
void setHasCompositingDescendant(bool b) { m_compositingProperties.hasCompositingDescendant = b; }
+ bool hasNonCompositedChild() const { return m_compositingProperties.hasNonCompositedChild; }
+ void setHasNonCompositedChild(bool b) { m_compositingProperties.hasNonCompositedChild = b; }
+
+ bool shouldIsolateCompositedDescendants() const { return m_compositingProperties.shouldIsolateCompositedDescendants; }
+ void setShouldIsolateCompositedDescendants(bool b) { m_compositingProperties.shouldIsolateCompositedDescendants = b; }
+
void setCompositingReasons(CompositingReasons reasons) { m_compositingProperties.compositingReasons = reasons; }
CompositingReasons compositingReasons() const { return m_compositingProperties.compositingReasons; }
- // Returns true if z ordering would not change if this layer were a stacking container.
- bool canBeStackingContainer() const;
-
- friend class RenderLayerBacking;
+ friend class CompositedLayerMapping;
friend class RenderLayerCompositor;
friend class RenderLayerModelObject;
- bool overflowControlsIntersectRect(const IntRect& localRect) const;
-
protected:
- // Keeps track of whether the layer is currently resizing, so events can cause resizing to start and stop.
- unsigned m_inResizeMode : 1;
-
- unsigned m_zOrderListsDirty : 1;
- unsigned m_normalFlowListDirty: 1;
- unsigned m_isNormalFlowOnly : 1;
-
unsigned m_isSelfPaintingLayer : 1;
// If have no self-painting descendants, we don't have to walk our children during painting. This can lead to
@@ -876,31 +639,22 @@ protected:
unsigned m_isUnclippedDescendant : 1;
- unsigned m_needsCompositedScrolling : 1;
- unsigned m_needsCompositedScrollingHasBeenRecorded : 1;
- unsigned m_willUseCompositedScrollingHasBeenRecorded : 1;
-
- unsigned m_isScrollableAreaHasBeenRecorded : 1;
-
- // If this is true, then no non-descendant appears between any of our
- // descendants in stacking order. This is one of the requirements of being
- // able to safely become a stacking context.
- unsigned m_canBePromotedToStackingContainer : 1;
- unsigned m_canBePromotedToStackingContainerDirty : 1;
-
const unsigned m_isRootLayer : 1;
unsigned m_usedTransparency : 1; // Tracks whether we need to close a transparent layer, i.e., whether
// we ended up painting this layer or any descendants (and therefore need to
// blend).
- unsigned m_paintingInsideReflection : 1; // A state bit tracking if we are painting inside a replica.
- unsigned m_repaintStatus : 2; // RepaintStatus
+
+ unsigned m_childLayerHasBlendMode : 1;
+ unsigned m_childLayerHasBlendModeStatusDirty : 1;
unsigned m_visibleContentStatusDirty : 1;
unsigned m_hasVisibleContent : 1;
unsigned m_visibleDescendantStatusDirty : 1;
unsigned m_hasVisibleDescendant : 1;
+ unsigned m_hasVisibleNonLayerContent : 1;
+
unsigned m_isPaginated : 1; // If we think this layer is split by a multi-column ancestor, then this bit will be set.
unsigned m_3DTransformedDescendantStatusDirty : 1;
@@ -910,9 +664,6 @@ protected:
unsigned m_containsDirtyOverlayScrollbars : 1;
-#if !ASSERT_DISABLED
- unsigned m_layerListMutationAllowed : 1;
-#endif
// This is an optimization added for <table>.
// Currently cells do not need to update their repaint rectangles when scrolling. This also
// saves a lot of time when scrolling on a table.
@@ -920,7 +671,7 @@ protected:
unsigned m_hasFilterInfo : 1;
- BlendMode m_blendMode;
+ blink::WebBlendMode m_blendMode;
RenderLayerModelObject* m_renderer;
@@ -930,9 +681,6 @@ protected:
RenderLayer* m_first;
RenderLayer* m_last;
- LayoutRect m_repaintRect; // Cached repaint rects. Used by layout.
- LayoutRect m_outlineBox;
-
// Our current relative position offset.
LayoutSize m_offsetForInFlowPosition;
@@ -942,33 +690,12 @@ protected:
// The layer's width/height
IntSize m_layerSize;
- // For layers that establish stacking contexts, m_posZOrderList holds a sorted list of all the
- // descendant layers within the stacking context that have z-indices of 0 or greater
- // (auto will count as 0). m_negZOrderList holds descendants within our stacking context with negative
- // z-indices.
- OwnPtr<Vector<RenderLayer*> > m_posZOrderList;
- OwnPtr<Vector<RenderLayer*> > m_negZOrderList;
-
- // This list contains child layers that cannot create stacking contexts. For now it is just
- // overflow layers, but that may change in the future.
- OwnPtr<Vector<RenderLayer*> > m_normalFlowList;
-
- OwnPtr<ClipRectsCache> m_clipRectsCache;
-
- IntPoint m_cachedOverlayScrollbarOffset;
-
// Cached normal flow values for absolute positioned elements with static left/top values.
LayoutUnit m_staticInlinePosition;
LayoutUnit m_staticBlockPosition;
OwnPtr<TransformationMatrix> m_transform;
- // May ultimately be extended to many replicas (with their own paint order).
- RenderReplica* m_reflection;
-
- // Renderers to hold our custom resizer.
- RenderScrollbarPart* m_resizer;
-
// Pointer to the enclosing RenderLayer that caused us to be paginated. It is 0 if we are not paginated.
RenderLayer* m_enclosingPaginationLayer;
@@ -977,6 +704,8 @@ protected:
struct CompositingProperties {
CompositingProperties()
: hasCompositingDescendant(false)
+ , hasNonCompositedChild(false)
+ , shouldIsolateCompositedDescendants(false)
, viewportConstrainedNotCompositedReason(NoNotCompositedReason)
, compositingReasons(CompositingReasonNone)
{ }
@@ -984,67 +713,45 @@ protected:
// Used only while determining what layers should be composited. Applies to the tree of z-order lists.
bool hasCompositingDescendant : 1;
+ // Applies to the real render layer tree (i.e., the tree determined by the layer's parent and children and
+ // as opposed to the tree formed by the z-order and normal flow lists).
+ bool hasNonCompositedChild : 1;
+
+ // Should be for stacking contexts having unisolated blending descendants.
+ bool shouldIsolateCompositedDescendants : 1;
+
// The reason, if any exists, that a fixed-position layer is chosen not to be composited.
unsigned viewportConstrainedNotCompositedReason : 2;
// Once computed, indicates all that a layer needs to become composited using the CompositingReasons enum bitfield.
CompositingReasons compositingReasons;
+
+ // Used for invalidating this layer's contents on the squashing GraphicsLayer.
+ IntSize offsetFromSquashingLayerOrigin;
};
CompositingProperties m_compositingProperties;
- ForceNeedsCompositedScrollingMode m_forceNeedsCompositedScrolling;
-
private:
+ enum CompositedScrollingHistogramBuckets {
+ IsScrollableAreaBucket = 0,
+ NeedsToBeStackingContainerBucket = 1,
+ WillUseCompositedScrollingBucket = 2,
+ CompositedScrollingHistogramMax = 3
+ };
+
IntRect m_blockSelectionGapsBounds;
- OwnPtr<RenderLayerBacking> m_backing;
+ OwnPtr<CompositedLayerMapping> m_compositedLayerMapping;
OwnPtr<RenderLayerScrollableArea> m_scrollableArea;
-};
-inline void RenderLayer::clearZOrderLists()
-{
- ASSERT(!isStackingContainer());
+ CompositedLayerMapping* m_groupedMapping;
- m_posZOrderList.clear();
- m_negZOrderList.clear();
-}
-
-inline void RenderLayer::updateZOrderLists()
-{
- if (!m_zOrderListsDirty)
- return;
-
- if (!isStackingContainer()) {
- clearZOrderLists();
- m_zOrderListsDirty = false;
- return;
- }
-
- rebuildZOrderLists();
-}
-
-#if !ASSERT_DISABLED
-class LayerListMutationDetector {
-public:
- LayerListMutationDetector(RenderLayer* layer)
- : m_layer(layer)
- , m_previousMutationAllowedState(layer->layerListMutationAllowed())
- {
- m_layer->setLayerListMutationAllowed(false);
- }
-
- ~LayerListMutationDetector()
- {
- m_layer->setLayerListMutationAllowed(m_previousMutationAllowedState);
- }
-
-private:
- RenderLayer* m_layer;
- bool m_previousMutationAllowedState;
+ RenderLayerRepainter m_repainter;
+ RenderLayerClipper m_clipper; // FIXME: Lazily allocate?
+ OwnPtr<RenderLayerStackingNode> m_stackingNode;
+ OwnPtr<RenderLayerReflectionInfo> m_reflectionInfo;
};
-#endif
-
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderLayerBacking.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderLayerBacking.cpp
deleted file mode 100644
index 51174576cdd..00000000000
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderLayerBacking.cpp
+++ /dev/null
@@ -1,1974 +0,0 @@
-/*
- * Copyright (C) 2009, 2010, 2011 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/rendering/RenderLayerBacking.h"
-
-#include "CSSPropertyNames.h"
-#include "HTMLNames.h"
-#include "RuntimeEnabledFeatures.h"
-#include "core/fetch/ImageResource.h"
-#include "core/html/HTMLIFrameElement.h"
-#include "core/html/HTMLMediaElement.h"
-#include "core/html/canvas/CanvasRenderingContext.h"
-#include "core/inspector/InspectorInstrumentation.h"
-#include "core/page/Chrome.h"
-#include "core/page/FrameView.h"
-#include "core/page/Settings.h"
-#include "core/page/animation/AnimationController.h"
-#include "core/page/scrolling/ScrollingCoordinator.h"
-#include "core/platform/animation/KeyframeValueList.h"
-#include "core/platform/graphics/FontCache.h"
-#include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/graphics/GraphicsLayer.h"
-#include "core/plugins/PluginView.h"
-#include "core/rendering/RenderApplet.h"
-#include "core/rendering/RenderEmbeddedObject.h"
-#include "core/rendering/RenderIFrame.h"
-#include "core/rendering/RenderImage.h"
-#include "core/rendering/RenderLayer.h"
-#include "core/rendering/RenderLayerCompositor.h"
-#include "core/rendering/RenderVideo.h"
-#include "core/rendering/RenderView.h"
-#include "core/rendering/style/KeyframeList.h"
-#include "wtf/CurrentTime.h"
-#include "wtf/text/StringBuilder.h"
-
-#include "core/platform/graphics/filters/custom/CustomFilterOperation.h"
-#include "core/rendering/FilterEffectRenderer.h"
-
-#include "core/platform/graphics/GraphicsContext3D.h"
-
-using namespace std;
-
-namespace WebCore {
-
-using namespace HTMLNames;
-
-static IntRect clipBox(RenderBox* renderer);
-
-static IntRect contentsRect(const RenderObject* renderer)
-{
- if (!renderer->isBox())
- return IntRect();
-
- return renderer->isVideo() ?
- toRenderVideo(renderer)->videoBox() :
- pixelSnappedIntRect(toRenderBox(renderer)->contentBoxRect());
-}
-
-static IntRect backgroundRect(const RenderObject* renderer)
-{
- if (!renderer->isBox())
- return IntRect();
-
- LayoutRect rect;
- const RenderBox* box = toRenderBox(renderer);
- EFillBox clip = box->style()->backgroundClip();
- switch (clip) {
- case BorderFillBox:
- rect = box->borderBoxRect();
- break;
- case PaddingFillBox:
- rect = box->paddingBoxRect();
- break;
- case ContentFillBox:
- rect = box->contentBoxRect();
- break;
- case TextFillBox:
- break;
- }
-
- return pixelSnappedIntRect(rect);
-}
-
-static inline bool isAcceleratedCanvas(const RenderObject* renderer)
-{
- if (renderer->isCanvas()) {
- HTMLCanvasElement* canvas = toHTMLCanvasElement(renderer->node());
- if (CanvasRenderingContext* context = canvas->renderingContext())
- return context->isAccelerated();
- }
- return false;
-}
-
-static bool hasBoxDecorations(const RenderStyle* style)
-{
- return style->hasBorder() || style->hasBorderRadius() || style->hasOutline() || style->hasAppearance() || style->boxShadow() || style->hasFilter();
-}
-
-static bool hasBoxDecorationsOrBackgroundImage(const RenderStyle* style)
-{
- return hasBoxDecorations(style) || style->hasBackgroundImage();
-}
-
-static bool contentLayerSupportsDirectBackgroundComposition(const RenderObject* renderer)
-{
- // No support for decorations - border, border-radius or outline.
- // Only simple background - solid color or transparent.
- if (hasBoxDecorationsOrBackgroundImage(renderer->style()))
- return false;
-
- // If there is no background, there is nothing to support.
- if (!renderer->style()->hasBackground())
- return true;
-
- // Simple background that is contained within the contents rect.
- return contentsRect(renderer).contains(backgroundRect(renderer));
-}
-
-// Get the scrolling coordinator in a way that works inside RenderLayerBacking's destructor.
-static ScrollingCoordinator* scrollingCoordinatorFromLayer(RenderLayer* layer)
-{
- Page* page = layer->renderer()->frame()->page();
- if (!page)
- return 0;
-
- return page->scrollingCoordinator();
-}
-
-RenderLayerBacking::RenderLayerBacking(RenderLayer* layer)
- : m_owningLayer(layer)
- , m_artificiallyInflatedBounds(false)
- , m_boundsConstrainedByClipping(false)
- , m_isMainFrameRenderViewLayer(false)
- , m_requiresOwnBackingStore(true)
- , m_canCompositeFilters(false)
- , m_backgroundLayerPaintsFixedRootBackground(false)
-{
- if (layer->isRootLayer()) {
- Frame& frame = toRenderView(renderer())->frameView()->frame();
- Page* page = frame.page();
- if (page && page->mainFrame() == &frame) {
- m_isMainFrameRenderViewLayer = true;
- }
- }
-
- createPrimaryGraphicsLayer();
-}
-
-RenderLayerBacking::~RenderLayerBacking()
-{
- updateClippingLayers(false, false);
- updateOverflowControlsLayers(false, false, false);
- updateForegroundLayer(false);
- updateBackgroundLayer(false);
- updateMaskLayer(false);
- updateScrollingLayers(false);
- destroyGraphicsLayers();
-}
-
-PassOwnPtr<GraphicsLayer> RenderLayerBacking::createGraphicsLayer(CompositingReasons reasons)
-{
- GraphicsLayerFactory* graphicsLayerFactory = 0;
- if (Page* page = renderer()->frame()->page())
- graphicsLayerFactory = page->chrome().client().graphicsLayerFactory();
-
- OwnPtr<GraphicsLayer> graphicsLayer = GraphicsLayer::create(graphicsLayerFactory, this);
-
- graphicsLayer->setCompositingReasons(reasons);
-
- return graphicsLayer.release();
-}
-
-void RenderLayerBacking::createPrimaryGraphicsLayer()
-{
- m_graphicsLayer = createGraphicsLayer(m_owningLayer->compositingReasons());
-
-#if !OS(ANDROID)
- if (m_isMainFrameRenderViewLayer)
- m_graphicsLayer->contentLayer()->setDrawCheckerboardForMissingTiles(true);
-#endif
-
- updateOpacity(renderer()->style());
- updateTransform(renderer()->style());
- updateFilters(renderer()->style());
-
- if (RuntimeEnabledFeatures::cssCompositingEnabled())
- updateLayerBlendMode(renderer()->style());
-}
-
-void RenderLayerBacking::destroyGraphicsLayers()
-{
- if (m_graphicsLayer)
- m_graphicsLayer->removeFromParent();
-
- m_ancestorClippingLayer = nullptr;
- m_graphicsLayer = nullptr;
- m_foregroundLayer = nullptr;
- m_backgroundLayer = nullptr;
- m_childContainmentLayer = nullptr;
- m_maskLayer = nullptr;
-
- m_scrollingLayer = nullptr;
- m_scrollingContentsLayer = nullptr;
-}
-
-void RenderLayerBacking::updateOpacity(const RenderStyle* style)
-{
- m_graphicsLayer->setOpacity(compositingOpacity(style->opacity()));
-}
-
-void RenderLayerBacking::updateTransform(const RenderStyle* style)
-{
- // FIXME: This could use m_owningLayer->transform(), but that currently has transform-origin
- // baked into it, and we don't want that.
- TransformationMatrix t;
- if (m_owningLayer->hasTransform()) {
- style->applyTransform(t, toRenderBox(renderer())->pixelSnappedBorderBoxRect().size(), RenderStyle::ExcludeTransformOrigin);
- makeMatrixRenderable(t, compositor()->canRender3DTransforms());
- }
-
- m_graphicsLayer->setTransform(t);
-}
-
-void RenderLayerBacking::updateFilters(const RenderStyle* style)
-{
- bool didCompositeFilters = m_canCompositeFilters;
- m_canCompositeFilters = m_graphicsLayer->setFilters(owningLayer()->computeFilterOperations(style));
- if (didCompositeFilters != m_canCompositeFilters) {
- //
- // If filters used to be painted in software and are now painted in the compositor, we need to:
- // (1) Remove the FilterEffectRenderer, which was used for painting filters in software.
- // (2) Repaint the layer contents to remove the software-applied filter because the compositor will apply it.
- //
- // Similarly, if filters used to be painted in the compositor and are now painted in software, we need to:
- // (1) Create a FilterEffectRenderer.
- // (2) Repaint the layer contents to apply a software filter because the compositor won't apply it.
- //
- m_owningLayer->updateOrRemoveFilterEffectRenderer();
- setContentsNeedDisplay();
- }
-}
-
-void RenderLayerBacking::updateLayerBlendMode(const RenderStyle*)
-{
-}
-
-void RenderLayerBacking::updateContentsOpaque()
-{
- // For non-root layers, background is always painted by the primary graphics layer.
- ASSERT(m_isMainFrameRenderViewLayer || !m_backgroundLayer);
- if (m_backgroundLayer) {
- m_graphicsLayer->setContentsOpaque(false);
- m_backgroundLayer->setContentsOpaque(m_owningLayer->backgroundIsKnownToBeOpaqueInRect(compositedBounds()));
- } else {
- m_graphicsLayer->setContentsOpaque(m_owningLayer->backgroundIsKnownToBeOpaqueInRect(compositedBounds()));
- }
-}
-
-static bool hasNonZeroTransformOrigin(const RenderObject* renderer)
-{
- RenderStyle* style = renderer->style();
- return (style->transformOriginX().type() == Fixed && style->transformOriginX().value())
- || (style->transformOriginY().type() == Fixed && style->transformOriginY().value());
-}
-
-static bool layerOrAncestorIsTransformedOrUsingCompositedScrolling(RenderLayer* layer)
-{
- for (RenderLayer* curr = layer; curr; curr = curr->parent()) {
- if (curr->hasTransform() || curr->needsCompositedScrolling())
- return true;
- }
-
- return false;
-}
-
-bool RenderLayerBacking::shouldClipCompositedBounds() const
-{
- // Scrollbar layers use this layer for relative positioning, so don't clip.
- if (layerForHorizontalScrollbar() || layerForVerticalScrollbar())
- return false;
-
- if (layerOrAncestorIsTransformedOrUsingCompositedScrolling(m_owningLayer))
- return false;
-
- return true;
-}
-
-void RenderLayerBacking::updateCompositedBounds()
-{
- IntRect layerBounds = compositor()->calculateCompositedBounds(m_owningLayer, m_owningLayer);
-
- // Clip to the size of the document or enclosing overflow-scroll layer.
- // If this or an ancestor is transformed, we can't currently compute the correct rect to intersect with.
- // We'd need RenderObject::convertContainerToLocalQuad(), which doesn't yet exist.
- if (shouldClipCompositedBounds()) {
- RenderView* view = m_owningLayer->renderer()->view();
- RenderLayer* rootLayer = view->layer();
-
- LayoutRect clippingBounds;
- if (renderer()->style()->position() == FixedPosition && renderer()->container() == view)
- clippingBounds = view->frameView()->viewportConstrainedVisibleContentRect();
- else
- clippingBounds = view->unscaledDocumentRect();
-
- if (m_owningLayer != rootLayer)
- clippingBounds.intersect(m_owningLayer->backgroundClipRect(RenderLayer::ClipRectsContext(rootLayer, 0, AbsoluteClipRects)).rect()); // FIXME: Incorrect for CSS regions.
-
- LayoutPoint delta;
- m_owningLayer->convertToLayerCoords(rootLayer, delta);
- clippingBounds.move(-delta.x(), -delta.y());
-
- layerBounds.intersect(pixelSnappedIntRect(clippingBounds));
- m_boundsConstrainedByClipping = true;
- } else
- m_boundsConstrainedByClipping = false;
-
- // If the element has a transform-origin that has fixed lengths, and the renderer has zero size,
- // then we need to ensure that the compositing layer has non-zero size so that we can apply
- // the transform-origin via the GraphicsLayer anchorPoint (which is expressed as a fractional value).
- if (layerBounds.isEmpty() && hasNonZeroTransformOrigin(renderer())) {
- layerBounds.setWidth(1);
- layerBounds.setHeight(1);
- m_artificiallyInflatedBounds = true;
- } else
- m_artificiallyInflatedBounds = false;
-
- setCompositedBounds(layerBounds);
-}
-
-void RenderLayerBacking::updateAfterWidgetResize()
-{
- if (renderer()->isRenderPart()) {
- if (RenderLayerCompositor* innerCompositor = RenderLayerCompositor::frameContentsCompositor(toRenderPart(renderer()))) {
- innerCompositor->frameViewDidChangeSize();
- innerCompositor->frameViewDidChangeLocation(contentsBox().location());
- }
- }
-}
-
-void RenderLayerBacking::updateCompositingReasons()
-{
- // All other layers owned by this backing will have the same compositing reason
- // for their lifetime, so they are initialized only when created.
- m_graphicsLayer->setCompositingReasons(m_owningLayer->compositingReasons());
-}
-
-void RenderLayerBacking::updateAfterLayout(UpdateAfterLayoutFlags flags)
-{
- RenderLayerCompositor* layerCompositor = compositor();
- if (!layerCompositor->compositingLayersNeedRebuild()) {
- // Calling updateGraphicsLayerGeometry() here gives incorrect results, because the
- // position of this layer's GraphicsLayer depends on the position of our compositing
- // ancestor's GraphicsLayer. That cannot be determined until all the descendant
- // RenderLayers of that ancestor have been processed via updateLayerPositions().
- //
- // The solution is to update compositing children of this layer here,
- // via updateCompositingChildrenGeometry().
- updateCompositedBounds();
- layerCompositor->updateCompositingDescendantGeometry(m_owningLayer, m_owningLayer, flags & CompositingChildrenOnly);
-
- if (flags & IsUpdateRoot) {
- updateGraphicsLayerGeometry();
- layerCompositor->updateRootLayerPosition();
- RenderLayer* stackingContainer = m_owningLayer->enclosingStackingContainer();
- if (!layerCompositor->compositingLayersNeedRebuild() && stackingContainer && (stackingContainer != m_owningLayer))
- layerCompositor->updateCompositingDescendantGeometry(stackingContainer, stackingContainer, flags & CompositingChildrenOnly);
- }
- }
-
- if (flags & NeedsFullRepaint && !paintsIntoCompositedAncestor())
- setContentsNeedDisplay();
-}
-
-bool RenderLayerBacking::updateGraphicsLayerConfiguration()
-{
- RenderLayerCompositor* compositor = this->compositor();
- RenderObject* renderer = this->renderer();
-
- m_owningLayer->updateDescendantDependentFlags();
- m_owningLayer->updateZOrderLists();
-
- bool layerConfigChanged = false;
- setBackgroundLayerPaintsFixedRootBackground(compositor->needsFixedRootBackgroundLayer(m_owningLayer));
-
- // The background layer is currently only used for fixed root backgrounds.
- if (updateBackgroundLayer(m_backgroundLayerPaintsFixedRootBackground))
- layerConfigChanged = true;
-
- if (updateForegroundLayer(compositor->needsContentsCompositingLayer(m_owningLayer)))
- layerConfigChanged = true;
-
- bool needsDescendentsClippingLayer = compositor->clipsCompositingDescendants(m_owningLayer);
-
- // Our scrolling layer will clip.
- if (m_owningLayer->needsCompositedScrolling())
- needsDescendentsClippingLayer = false;
-
- RenderLayer* scrollParent = m_owningLayer->scrollParent();
- bool needsAncestorClip = compositor->clippedByAncestor(m_owningLayer);
- if (scrollParent) {
- // If our containing block is our ancestor scrolling layer, then we'll already be clipped
- // to it via our scroll parent and we don't need an ancestor clipping layer.
- if (m_owningLayer->renderer()->containingBlock()->enclosingLayer() == m_owningLayer->ancestorScrollingLayer())
- needsAncestorClip = false;
- }
- if (updateClippingLayers(needsAncestorClip, needsDescendentsClippingLayer))
- layerConfigChanged = true;
-
- if (updateOverflowControlsLayers(requiresHorizontalScrollbarLayer(), requiresVerticalScrollbarLayer(), requiresScrollCornerLayer()))
- layerConfigChanged = true;
-
- if (updateScrollingLayers(m_owningLayer->needsCompositedScrolling()))
- layerConfigChanged = true;
-
- updateScrollParent(scrollParent);
- updateClipParent(m_owningLayer->clipParent());
-
- if (layerConfigChanged)
- updateInternalHierarchy();
-
- if (updateMaskLayer(renderer->hasMask()))
- m_graphicsLayer->setMaskLayer(m_maskLayer.get());
-
- if (m_owningLayer->hasReflection()) {
- if (m_owningLayer->reflectionLayer()->backing()) {
- GraphicsLayer* reflectionLayer = m_owningLayer->reflectionLayer()->backing()->graphicsLayer();
- m_graphicsLayer->setReplicatedByLayer(reflectionLayer);
- }
- } else
- m_graphicsLayer->setReplicatedByLayer(0);
-
- updateBackgroundColor(isSimpleContainerCompositingLayer());
-
- if (isDirectlyCompositedImage())
- updateImageContents();
-
- if (renderer->isEmbeddedObject() && toRenderEmbeddedObject(renderer)->allowsAcceleratedCompositing()) {
- PluginView* pluginView = toPluginView(toRenderWidget(renderer)->widget());
- m_graphicsLayer->setContentsToMedia(pluginView->platformLayer());
- } else if (renderer->isVideo()) {
- HTMLMediaElement* mediaElement = toHTMLMediaElement(renderer->node());
- m_graphicsLayer->setContentsToMedia(mediaElement->platformLayer());
- } else if (isAcceleratedCanvas(renderer)) {
- HTMLCanvasElement* canvas = toHTMLCanvasElement(renderer->node());
- if (CanvasRenderingContext* context = canvas->renderingContext())
- m_graphicsLayer->setContentsToCanvas(context->platformLayer());
- layerConfigChanged = true;
- }
- if (renderer->isRenderPart())
- layerConfigChanged = RenderLayerCompositor::parentFrameContentLayers(toRenderPart(renderer));
-
- return layerConfigChanged;
-}
-
-static IntRect clipBox(RenderBox* renderer)
-{
- LayoutRect result = PaintInfo::infiniteRect();
- if (renderer->hasOverflowClip())
- result = renderer->overflowClipRect(LayoutPoint(), 0); // FIXME: Incorrect for CSS regions.
-
- if (renderer->hasClip())
- result.intersect(renderer->clipRect(LayoutPoint(), 0)); // FIXME: Incorrect for CSS regions.
-
- return pixelSnappedIntRect(result);
-}
-
-void RenderLayerBacking::updateGraphicsLayerGeometry()
-{
- // If we haven't built z-order lists yet, wait until later.
- if (m_owningLayer->isStackingContainer() && m_owningLayer->m_zOrderListsDirty)
- return;
-
- // Set transform property, if it is not animating. We have to do this here because the transform
- // is affected by the layer dimensions.
- if (!renderer()->animation()->isRunningAcceleratedAnimationOnRenderer(renderer(), CSSPropertyWebkitTransform))
- updateTransform(renderer()->style());
-
- // Set opacity, if it is not animating.
- if (!renderer()->animation()->isRunningAcceleratedAnimationOnRenderer(renderer(), CSSPropertyOpacity))
- updateOpacity(renderer()->style());
-
- if (RuntimeEnabledFeatures::cssCompositingEnabled())
- updateLayerBlendMode(renderer()->style());
-
- bool isSimpleContainer = isSimpleContainerCompositingLayer();
-
- m_owningLayer->updateDescendantDependentFlags();
-
- // m_graphicsLayer is the corresponding GraphicsLayer for this RenderLayer and its non-compositing
- // descendants. So, the visibility flag for m_graphicsLayer should be true if there are any
- // non-compositing visible layers.
- bool contentsVisible = m_owningLayer->hasVisibleContent() || hasVisibleNonCompositingDescendantLayers();
- if (RuntimeEnabledFeatures::overlayFullscreenVideoEnabled() && renderer()->isVideo()) {
- HTMLMediaElement* mediaElement = toHTMLMediaElement(renderer()->node());
- if (mediaElement->isFullscreen())
- contentsVisible = false;
- }
- m_graphicsLayer->setContentsVisible(contentsVisible);
-
- RenderStyle* style = renderer()->style();
- // FIXME: reflections should force transform-style to be flat in the style: https://bugs.webkit.org/show_bug.cgi?id=106959
- bool preserves3D = style->transformStyle3D() == TransformStyle3DPreserve3D && !renderer()->hasReflection();
- m_graphicsLayer->setPreserves3D(preserves3D);
- m_graphicsLayer->setBackfaceVisibility(style->backfaceVisibility() == BackfaceVisibilityVisible);
-
- RenderLayer* compAncestor = m_owningLayer->ancestorCompositingLayer();
-
- // We compute everything relative to the enclosing compositing layer.
- IntRect ancestorCompositingBounds;
- if (compAncestor) {
- ASSERT(compAncestor->backing());
- ancestorCompositingBounds = pixelSnappedIntRect(compAncestor->backing()->compositedBounds());
- }
-
- IntRect localCompositingBounds = pixelSnappedIntRect(compositedBounds());
-
- IntRect relativeCompositingBounds(localCompositingBounds);
- IntPoint delta;
- m_owningLayer->convertToPixelSnappedLayerCoords(compAncestor, delta);
- relativeCompositingBounds.moveBy(delta);
-
- IntPoint graphicsLayerParentLocation;
- if (compAncestor && compAncestor->backing()->hasClippingLayer()) {
- // If the compositing ancestor has a layer to clip children, we parent in that, and therefore
- // position relative to it.
- IntRect clippingBox = clipBox(toRenderBox(compAncestor->renderer()));
- graphicsLayerParentLocation = clippingBox.location();
- } else if (compAncestor)
- graphicsLayerParentLocation = ancestorCompositingBounds.location();
- else
- graphicsLayerParentLocation = renderer()->view()->documentRect().location();
-
- if (compAncestor && compAncestor->needsCompositedScrolling()) {
- RenderBox* renderBox = toRenderBox(compAncestor->renderer());
- IntSize scrollOffset = compAncestor->scrolledContentOffset();
- IntPoint scrollOrigin(renderBox->borderLeft(), renderBox->borderTop());
- graphicsLayerParentLocation = scrollOrigin - scrollOffset;
- }
-
- if (compAncestor && m_ancestorClippingLayer) {
- // Call calculateRects to get the backgroundRect which is what is used to clip the contents of this
- // layer. Note that we call it with temporaryClipRects = true because normally when computing clip rects
- // for a compositing layer, rootLayer is the layer itself.
- RenderLayer::ClipRectsContext clipRectsContext(compAncestor, 0, TemporaryClipRects, IgnoreOverlayScrollbarSize, IgnoreOverflowClip);
- IntRect parentClipRect = pixelSnappedIntRect(m_owningLayer->backgroundClipRect(clipRectsContext).rect()); // FIXME: Incorrect for CSS regions.
- ASSERT(parentClipRect != PaintInfo::infiniteRect());
- m_ancestorClippingLayer->setPosition(FloatPoint(parentClipRect.location() - graphicsLayerParentLocation));
- m_ancestorClippingLayer->setSize(parentClipRect.size());
-
- // backgroundRect is relative to compAncestor, so subtract deltaX/deltaY to get back to local coords.
- m_ancestorClippingLayer->setOffsetFromRenderer(parentClipRect.location() - delta);
-
- // The primary layer is then parented in, and positioned relative to this clipping layer.
- graphicsLayerParentLocation = parentClipRect.location();
- }
-
- FloatSize contentsSize = relativeCompositingBounds.size();
-
- m_graphicsLayer->setPosition(FloatPoint(relativeCompositingBounds.location() - graphicsLayerParentLocation));
- m_graphicsLayer->setOffsetFromRenderer(toIntSize(localCompositingBounds.location()));
-
- FloatSize oldSize = m_graphicsLayer->size();
- if (oldSize != contentsSize) {
- m_graphicsLayer->setSize(contentsSize);
- // Usually invalidation will happen via layout etc, but if we've affected the layer
- // size by constraining relative to a clipping ancestor or the viewport, we
- // have to invalidate to avoid showing stretched content.
- if (m_boundsConstrainedByClipping)
- m_graphicsLayer->setNeedsDisplay();
- }
-
- // If we have a layer that clips children, position it.
- IntRect clippingBox;
- if (GraphicsLayer* clipLayer = clippingLayer()) {
- clippingBox = clipBox(toRenderBox(renderer()));
- clipLayer->setPosition(FloatPoint(clippingBox.location() - localCompositingBounds.location()));
- clipLayer->setSize(clippingBox.size());
- clipLayer->setOffsetFromRenderer(toIntSize(clippingBox.location()));
- }
-
- if (m_maskLayer) {
- if (m_maskLayer->size() != m_graphicsLayer->size()) {
- m_maskLayer->setSize(m_graphicsLayer->size());
- m_maskLayer->setNeedsDisplay();
- }
- m_maskLayer->setPosition(FloatPoint());
- m_maskLayer->setOffsetFromRenderer(m_graphicsLayer->offsetFromRenderer());
- }
-
- if (m_owningLayer->hasTransform()) {
- const IntRect borderBox = toRenderBox(renderer())->pixelSnappedBorderBoxRect();
-
- // Get layout bounds in the coords of compAncestor to match relativeCompositingBounds.
- IntRect layerBounds = IntRect(delta, borderBox.size());
-
- // Update properties that depend on layer dimensions
- FloatPoint3D transformOrigin = computeTransformOrigin(borderBox);
- // Compute the anchor point, which is in the center of the renderer box unless transform-origin is set.
- FloatPoint3D anchor(relativeCompositingBounds.width() != 0.0f ? ((layerBounds.x() - relativeCompositingBounds.x()) + transformOrigin.x()) / relativeCompositingBounds.width() : 0.5f,
- relativeCompositingBounds.height() != 0.0f ? ((layerBounds.y() - relativeCompositingBounds.y()) + transformOrigin.y()) / relativeCompositingBounds.height() : 0.5f,
- transformOrigin.z());
- m_graphicsLayer->setAnchorPoint(anchor);
-
- RenderStyle* style = renderer()->style();
- GraphicsLayer* clipLayer = clippingLayer();
- if (style->hasPerspective()) {
- TransformationMatrix t = owningLayer()->perspectiveTransform();
-
- if (clipLayer) {
- clipLayer->setChildrenTransform(t);
- m_graphicsLayer->setChildrenTransform(TransformationMatrix());
- }
- else
- m_graphicsLayer->setChildrenTransform(t);
- } else {
- if (clipLayer)
- clipLayer->setChildrenTransform(TransformationMatrix());
- else
- m_graphicsLayer->setChildrenTransform(TransformationMatrix());
- }
- } else {
- m_graphicsLayer->setAnchorPoint(FloatPoint3D(0.5f, 0.5f, 0));
- }
-
- if (m_foregroundLayer) {
- FloatPoint foregroundPosition;
- FloatSize foregroundSize = contentsSize;
- IntSize foregroundOffset = m_graphicsLayer->offsetFromRenderer();
- if (hasClippingLayer()) {
- // If we have a clipping layer (which clips descendants), then the foreground layer is a child of it,
- // so that it gets correctly sorted with children. In that case, position relative to the clipping layer.
- foregroundSize = FloatSize(clippingBox.size());
- foregroundOffset = toIntSize(clippingBox.location());
- }
-
- m_foregroundLayer->setPosition(foregroundPosition);
- if (foregroundSize != m_foregroundLayer->size()) {
- m_foregroundLayer->setSize(foregroundSize);
- m_foregroundLayer->setNeedsDisplay();
- }
- m_foregroundLayer->setOffsetFromRenderer(foregroundOffset);
- }
-
- if (m_backgroundLayer) {
- FloatPoint backgroundPosition;
- FloatSize backgroundSize = contentsSize;
- if (backgroundLayerPaintsFixedRootBackground()) {
- FrameView* frameView = toRenderView(renderer())->frameView();
- backgroundSize = frameView->visibleContentRect().size();
- }
- m_backgroundLayer->setPosition(backgroundPosition);
- if (backgroundSize != m_backgroundLayer->size()) {
- m_backgroundLayer->setSize(backgroundSize);
- m_backgroundLayer->setNeedsDisplay();
- }
- m_backgroundLayer->setOffsetFromRenderer(m_graphicsLayer->offsetFromRenderer());
- }
-
- if (m_owningLayer->reflectionLayer() && m_owningLayer->reflectionLayer()->isComposited()) {
- RenderLayerBacking* reflectionBacking = m_owningLayer->reflectionLayer()->backing();
- reflectionBacking->updateGraphicsLayerGeometry();
-
- // The reflection layer has the bounds of m_owningLayer->reflectionLayer(),
- // but the reflected layer is the bounds of this layer, so we need to position it appropriately.
- FloatRect layerBounds = compositedBounds();
- FloatRect reflectionLayerBounds = reflectionBacking->compositedBounds();
- reflectionBacking->graphicsLayer()->setReplicatedLayerPosition(FloatPoint(layerBounds.location() - reflectionLayerBounds.location()));
- }
-
- if (m_scrollingLayer) {
- ASSERT(m_scrollingContentsLayer);
- RenderBox* renderBox = toRenderBox(renderer());
- IntRect clientBox = enclosingIntRect(renderBox->clientBoxRect());
- // FIXME: We should make RenderBox::clientBoxRect consider scrollbar placement.
- if (style->shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
- clientBox.move(renderBox->verticalScrollbarWidth(), 0);
-
- IntSize adjustedScrollOffset = m_owningLayer->adjustedScrollOffset();
- m_scrollingLayer->setPosition(FloatPoint(clientBox.location() - localCompositingBounds.location()));
- m_scrollingLayer->setSize(clientBox.size());
-
- IntSize oldScrollingLayerOffset = m_scrollingLayer->offsetFromRenderer();
- m_scrollingLayer->setOffsetFromRenderer(-toIntSize(clientBox.location()));
-
- bool clientBoxOffsetChanged = oldScrollingLayerOffset != m_scrollingLayer->offsetFromRenderer();
-
- IntSize scrollSize(m_owningLayer->scrollWidth(), m_owningLayer->scrollHeight());
- if (scrollSize != m_scrollingContentsLayer->size() || clientBoxOffsetChanged)
- m_scrollingContentsLayer->setNeedsDisplay();
-
- IntSize scrollingContentsOffset = toIntSize(clientBox.location() - adjustedScrollOffset);
- if (scrollingContentsOffset != m_scrollingContentsLayer->offsetFromRenderer() || scrollSize != m_scrollingContentsLayer->size()) {
- bool scrollingCoordinatorHandlesOffset = compositor()->scrollingLayerDidChange(m_owningLayer);
-
- if (scrollingCoordinatorHandlesOffset)
- m_scrollingContentsLayer->setPosition(-m_owningLayer->scrollOrigin());
- else
- m_scrollingContentsLayer->setPosition(FloatPoint(-adjustedScrollOffset));
- }
-
- m_scrollingContentsLayer->setSize(scrollSize);
- // FIXME: The paint offset and the scroll offset should really be separate concepts.
- m_scrollingContentsLayer->setOffsetFromRenderer(scrollingContentsOffset, GraphicsLayer::DontSetNeedsDisplay);
-
- if (m_foregroundLayer) {
- if (m_foregroundLayer->size() != m_scrollingContentsLayer->size())
- m_foregroundLayer->setSize(m_scrollingContentsLayer->size());
- m_foregroundLayer->setNeedsDisplay();
- m_foregroundLayer->setOffsetFromRenderer(m_scrollingContentsLayer->offsetFromRenderer());
- }
- }
-
- // If this layer was created just for clipping or to apply perspective, it doesn't need its own backing store.
- setRequiresOwnBackingStore(compositor()->requiresOwnBackingStore(m_owningLayer, compAncestor));
-
- updateContentsRect(isSimpleContainer);
- updateBackgroundColor(isSimpleContainer);
- updateDrawsContent(isSimpleContainer);
- updateContentsOpaque();
- updateAfterWidgetResize();
- registerScrollingLayers();
-
- updateCompositingReasons();
-}
-
-void RenderLayerBacking::registerScrollingLayers()
-{
- // Register fixed position layers and their containers with the scrolling coordinator.
- ScrollingCoordinator* scrollingCoordinator = scrollingCoordinatorFromLayer(m_owningLayer);
- if (!scrollingCoordinator)
- return;
-
- compositor()->updateViewportConstraintStatus(m_owningLayer);
-
- scrollingCoordinator->updateLayerPositionConstraint(m_owningLayer);
-
- // Page scale is applied as a transform on the root render view layer. Because the scroll
- // layer is further up in the hierarchy, we need to avoid marking the root render view
- // layer as a container.
- bool isContainer = m_owningLayer->hasTransform() && !m_owningLayer->isRootLayer();
- scrollingCoordinator->setLayerIsContainerForFixedPositionLayers(childForSuperlayers(), isContainer);
-}
-
-void RenderLayerBacking::updateInternalHierarchy()
-{
- // m_foregroundLayer has to be inserted in the correct order with child layers,
- // so it's not inserted here.
- if (m_ancestorClippingLayer)
- m_ancestorClippingLayer->removeAllChildren();
-
- m_graphicsLayer->removeFromParent();
-
- if (m_ancestorClippingLayer)
- m_ancestorClippingLayer->addChild(m_graphicsLayer.get());
-
- if (m_childContainmentLayer) {
- m_childContainmentLayer->removeFromParent();
- m_graphicsLayer->addChild(m_childContainmentLayer.get());
- }
-
- if (m_scrollingLayer) {
- GraphicsLayer* superlayer = m_childContainmentLayer ? m_childContainmentLayer.get() : m_graphicsLayer.get();
- m_scrollingLayer->removeFromParent();
- superlayer->addChild(m_scrollingLayer.get());
- }
-
- // The clip for child layers does not include space for overflow controls, so they exist as
- // siblings of the clipping layer if we have one. Normal children of this layer are set as
- // children of the clipping layer.
- if (m_layerForHorizontalScrollbar) {
- m_layerForHorizontalScrollbar->removeFromParent();
- m_graphicsLayer->addChild(m_layerForHorizontalScrollbar.get());
- }
- if (m_layerForVerticalScrollbar) {
- m_layerForVerticalScrollbar->removeFromParent();
- m_graphicsLayer->addChild(m_layerForVerticalScrollbar.get());
- }
- if (m_layerForScrollCorner) {
- m_layerForScrollCorner->removeFromParent();
- m_graphicsLayer->addChild(m_layerForScrollCorner.get());
- }
-}
-
-void RenderLayerBacking::updateContentsRect(bool isSimpleContainer)
-{
- IntRect contentsRect;
- if (isSimpleContainer && renderer()->hasBackground())
- contentsRect = backgroundBox();
- else
- contentsRect = contentsBox();
-
- m_graphicsLayer->setContentsRect(contentsRect);
-}
-
-void RenderLayerBacking::updateDrawsContent(bool isSimpleContainer)
-{
- if (m_scrollingLayer) {
- // We don't have to consider overflow controls, because we know that the scrollbars are drawn elsewhere.
- // m_graphicsLayer only needs backing store if the non-scrolling parts (background, outlines, borders, shadows etc) need to paint.
- // m_scrollingLayer never has backing store.
- // m_scrollingContentsLayer only needs backing store if the scrolled contents need to paint.
- bool hasNonScrollingPaintedContent = m_owningLayer->hasVisibleContent() && m_owningLayer->hasBoxDecorationsOrBackground();
- m_graphicsLayer->setDrawsContent(hasNonScrollingPaintedContent);
-
- bool hasScrollingPaintedContent = m_owningLayer->hasVisibleContent() && (renderer()->hasBackground() || paintsChildren());
- m_scrollingContentsLayer->setDrawsContent(hasScrollingPaintedContent);
- return;
- }
-
- bool hasPaintedContent = containsPaintedContent(isSimpleContainer);
- if (hasPaintedContent && isAcceleratedCanvas(renderer())) {
- CanvasRenderingContext* context = toHTMLCanvasElement(renderer()->node())->renderingContext();
- // Content layer may be null if context is lost.
- if (WebKit::WebLayer* contentLayer = context->platformLayer()) {
- Color bgColor;
- if (contentLayerSupportsDirectBackgroundComposition(renderer())) {
- bgColor = rendererBackgroundColor();
- hasPaintedContent = false;
- }
- contentLayer->setBackgroundColor(bgColor.rgb());
- }
- }
-
- // FIXME: we could refine this to only allocate backing for one of these layers if possible.
- m_graphicsLayer->setDrawsContent(hasPaintedContent);
- if (m_foregroundLayer)
- m_foregroundLayer->setDrawsContent(hasPaintedContent);
-
- if (m_backgroundLayer)
- m_backgroundLayer->setDrawsContent(hasPaintedContent);
-}
-
-// Return true if the layers changed.
-bool RenderLayerBacking::updateClippingLayers(bool needsAncestorClip, bool needsDescendantClip)
-{
- bool layersChanged = false;
-
- if (needsAncestorClip) {
- if (!m_ancestorClippingLayer) {
- m_ancestorClippingLayer = createGraphicsLayer(CompositingReasonLayerForClip);
- m_ancestorClippingLayer->setMasksToBounds(true);
- layersChanged = true;
- }
- } else if (m_ancestorClippingLayer) {
- m_ancestorClippingLayer->removeFromParent();
- m_ancestorClippingLayer = nullptr;
- layersChanged = true;
- }
-
- if (needsDescendantClip) {
- // We don't need a child containment layer if we're the main frame render view
- // layer. It's redundant as the frame clip above us will handle this clipping.
- if (!m_childContainmentLayer && !m_isMainFrameRenderViewLayer) {
- m_childContainmentLayer = createGraphicsLayer(CompositingReasonLayerForClip);
- m_childContainmentLayer->setMasksToBounds(true);
- layersChanged = true;
- }
- } else if (hasClippingLayer()) {
- m_childContainmentLayer->removeFromParent();
- m_childContainmentLayer = nullptr;
- layersChanged = true;
- }
-
- return layersChanged;
-}
-
-void RenderLayerBacking::setBackgroundLayerPaintsFixedRootBackground(bool backgroundLayerPaintsFixedRootBackground)
-{
- m_backgroundLayerPaintsFixedRootBackground = backgroundLayerPaintsFixedRootBackground;
-}
-
-bool RenderLayerBacking::updateOverflowControlsLayers(bool needsHorizontalScrollbarLayer, bool needsVerticalScrollbarLayer, bool needsScrollCornerLayer)
-{
- bool horizontalScrollbarLayerChanged = false;
- if (needsHorizontalScrollbarLayer) {
- if (!m_layerForHorizontalScrollbar) {
- m_layerForHorizontalScrollbar = createGraphicsLayer(CompositingReasonLayerForScrollbar);
- horizontalScrollbarLayerChanged = true;
- }
- } else if (m_layerForHorizontalScrollbar) {
- m_layerForHorizontalScrollbar = nullptr;
- horizontalScrollbarLayerChanged = true;
- }
-
- bool verticalScrollbarLayerChanged = false;
- if (needsVerticalScrollbarLayer) {
- if (!m_layerForVerticalScrollbar) {
- m_layerForVerticalScrollbar = createGraphicsLayer(CompositingReasonLayerForScrollbar);
- verticalScrollbarLayerChanged = true;
- }
- } else if (m_layerForVerticalScrollbar) {
- m_layerForVerticalScrollbar = nullptr;
- verticalScrollbarLayerChanged = true;
- }
-
- bool scrollCornerLayerChanged = false;
- if (needsScrollCornerLayer) {
- if (!m_layerForScrollCorner) {
- m_layerForScrollCorner = createGraphicsLayer(CompositingReasonLayerForScrollbar);
- scrollCornerLayerChanged = true;
- }
- } else if (m_layerForScrollCorner) {
- m_layerForScrollCorner = nullptr;
- scrollCornerLayerChanged = true;
- }
-
- if (ScrollingCoordinator* scrollingCoordinator = scrollingCoordinatorFromLayer(m_owningLayer)) {
- if (horizontalScrollbarLayerChanged)
- scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(m_owningLayer->scrollableArea(), HorizontalScrollbar);
- if (verticalScrollbarLayerChanged)
- scrollingCoordinator->scrollableAreaScrollbarLayerDidChange(m_owningLayer->scrollableArea(), VerticalScrollbar);
- }
-
- return horizontalScrollbarLayerChanged || verticalScrollbarLayerChanged || scrollCornerLayerChanged;
-}
-
-void RenderLayerBacking::positionOverflowControlsLayers(const IntSize& offsetFromRoot)
-{
- IntSize offsetFromRenderer = m_graphicsLayer->offsetFromRenderer();
- if (GraphicsLayer* layer = layerForHorizontalScrollbar()) {
- Scrollbar* hBar = m_owningLayer->horizontalScrollbar();
- if (hBar) {
- layer->setPosition(hBar->frameRect().location() - offsetFromRoot - offsetFromRenderer);
- layer->setSize(hBar->frameRect().size());
- if (layer->hasContentsLayer())
- layer->setContentsRect(IntRect(IntPoint(), hBar->frameRect().size()));
- }
- layer->setDrawsContent(hBar && !layer->hasContentsLayer());
- }
-
- if (GraphicsLayer* layer = layerForVerticalScrollbar()) {
- Scrollbar* vBar = m_owningLayer->verticalScrollbar();
- if (vBar) {
- layer->setPosition(vBar->frameRect().location() - offsetFromRoot - offsetFromRenderer);
- layer->setSize(vBar->frameRect().size());
- if (layer->hasContentsLayer())
- layer->setContentsRect(IntRect(IntPoint(), vBar->frameRect().size()));
- }
- layer->setDrawsContent(vBar && !layer->hasContentsLayer());
- }
-
- if (GraphicsLayer* layer = layerForScrollCorner()) {
- const LayoutRect& scrollCornerAndResizer = m_owningLayer->scrollCornerAndResizerRect();
- layer->setPosition(scrollCornerAndResizer.location() - offsetFromRenderer);
- layer->setSize(scrollCornerAndResizer.size());
- layer->setDrawsContent(!scrollCornerAndResizer.isEmpty());
- }
-}
-
-bool RenderLayerBacking::hasUnpositionedOverflowControlsLayers() const
-{
- if (GraphicsLayer* layer = layerForHorizontalScrollbar())
- if (!layer->drawsContent())
- return true;
-
- if (GraphicsLayer* layer = layerForVerticalScrollbar())
- if (!layer->drawsContent())
- return true;
-
- if (GraphicsLayer* layer = layerForScrollCorner())
- if (!layer->drawsContent())
- return true;
-
- return false;
-}
-
-bool RenderLayerBacking::updateForegroundLayer(bool needsForegroundLayer)
-{
- bool layerChanged = false;
- if (needsForegroundLayer) {
- if (!m_foregroundLayer) {
- m_foregroundLayer = createGraphicsLayer(CompositingReasonLayerForForeground);
- m_foregroundLayer->setDrawsContent(true);
- m_foregroundLayer->setPaintingPhase(GraphicsLayerPaintForeground);
- layerChanged = true;
- }
- } else if (m_foregroundLayer) {
- m_foregroundLayer->removeFromParent();
- m_foregroundLayer = nullptr;
- layerChanged = true;
- }
-
- if (layerChanged)
- m_graphicsLayer->setPaintingPhase(paintingPhaseForPrimaryLayer());
-
- return layerChanged;
-}
-
-bool RenderLayerBacking::updateBackgroundLayer(bool needsBackgroundLayer)
-{
- bool layerChanged = false;
- if (needsBackgroundLayer) {
- if (!m_backgroundLayer) {
- m_backgroundLayer = createGraphicsLayer(CompositingReasonLayerForBackground);
- m_backgroundLayer->setDrawsContent(true);
- m_backgroundLayer->setAnchorPoint(FloatPoint3D());
- m_backgroundLayer->setPaintingPhase(GraphicsLayerPaintBackground);
-#if !OS(ANDROID)
- m_backgroundLayer->contentLayer()->setDrawCheckerboardForMissingTiles(true);
- m_graphicsLayer->contentLayer()->setDrawCheckerboardForMissingTiles(false);
-#endif
- layerChanged = true;
- }
- } else {
- if (m_backgroundLayer) {
- m_backgroundLayer->removeFromParent();
- m_backgroundLayer = nullptr;
-#if !OS(ANDROID)
- m_graphicsLayer->contentLayer()->setDrawCheckerboardForMissingTiles(true);
-#endif
- layerChanged = true;
- }
- }
-
- if (layerChanged && !m_owningLayer->renderer()->documentBeingDestroyed())
- compositor()->rootFixedBackgroundsChanged();
-
- return layerChanged;
-}
-
-bool RenderLayerBacking::updateMaskLayer(bool needsMaskLayer)
-{
- bool layerChanged = false;
- if (needsMaskLayer) {
- if (!m_maskLayer) {
- m_maskLayer = createGraphicsLayer(CompositingReasonLayerForMask);
- m_maskLayer->setDrawsContent(true);
- m_maskLayer->setPaintingPhase(GraphicsLayerPaintMask);
- layerChanged = true;
- }
- } else if (m_maskLayer) {
- m_maskLayer = nullptr;
- layerChanged = true;
- }
-
- if (layerChanged)
- m_graphicsLayer->setPaintingPhase(paintingPhaseForPrimaryLayer());
-
- return layerChanged;
-}
-
-bool RenderLayerBacking::updateScrollingLayers(bool needsScrollingLayers)
-{
- ScrollingCoordinator* scrollingCoordinator = scrollingCoordinatorFromLayer(m_owningLayer);
-
- bool layerChanged = false;
- if (needsScrollingLayers) {
- if (!m_scrollingLayer) {
- // Outer layer which corresponds with the scroll view.
- m_scrollingLayer = createGraphicsLayer(CompositingReasonLayerForClip);
- m_scrollingLayer->setDrawsContent(false);
- m_scrollingLayer->setMasksToBounds(true);
-
- // Inner layer which renders the content that scrolls.
- m_scrollingContentsLayer = createGraphicsLayer(CompositingReasonLayerForScrollingContainer);
- m_scrollingContentsLayer->setDrawsContent(true);
- GraphicsLayerPaintingPhase paintPhase = GraphicsLayerPaintOverflowContents | GraphicsLayerPaintCompositedScroll;
- if (!m_foregroundLayer)
- paintPhase |= GraphicsLayerPaintForeground;
- m_scrollingContentsLayer->setPaintingPhase(paintPhase);
- m_scrollingLayer->addChild(m_scrollingContentsLayer.get());
-
- layerChanged = true;
- if (scrollingCoordinator)
- scrollingCoordinator->scrollableAreaScrollLayerDidChange(m_owningLayer->scrollableArea());
- }
- } else if (m_scrollingLayer) {
- m_scrollingLayer = nullptr;
- m_scrollingContentsLayer = nullptr;
- layerChanged = true;
- if (scrollingCoordinator)
- scrollingCoordinator->scrollableAreaScrollLayerDidChange(m_owningLayer->scrollableArea());
- }
-
- if (layerChanged) {
- updateInternalHierarchy();
- m_graphicsLayer->setPaintingPhase(paintingPhaseForPrimaryLayer());
- m_graphicsLayer->setNeedsDisplay();
- if (renderer()->view())
- compositor()->scrollingLayerDidChange(m_owningLayer);
- }
-
- return layerChanged;
-}
-
-void RenderLayerBacking::updateScrollParent(RenderLayer* scrollParent)
-{
- if (ScrollingCoordinator* scrollingCoordinator = scrollingCoordinatorFromLayer(m_owningLayer))
- scrollingCoordinator->updateScrollParentForLayer(m_owningLayer, scrollParent);
-}
-
-void RenderLayerBacking::updateClipParent(RenderLayer* clipParent)
-{
- if (ScrollingCoordinator* scrollingCoordinator = scrollingCoordinatorFromLayer(m_owningLayer))
- scrollingCoordinator->updateClipParentForLayer(m_owningLayer, clipParent);
-}
-
-GraphicsLayerPaintingPhase RenderLayerBacking::paintingPhaseForPrimaryLayer() const
-{
- unsigned phase = 0;
- if (!m_backgroundLayer)
- phase |= GraphicsLayerPaintBackground;
- if (!m_foregroundLayer)
- phase |= GraphicsLayerPaintForeground;
- if (!m_maskLayer)
- phase |= GraphicsLayerPaintMask;
-
- if (m_scrollingContentsLayer) {
- phase &= ~GraphicsLayerPaintForeground;
- phase |= GraphicsLayerPaintCompositedScroll;
- }
-
- if (m_owningLayer->compositingReasons() & CompositingReasonOverflowScrollingParent)
- phase |= GraphicsLayerPaintCompositedScroll;
-
- return static_cast<GraphicsLayerPaintingPhase>(phase);
-}
-
-float RenderLayerBacking::compositingOpacity(float rendererOpacity) const
-{
- float finalOpacity = rendererOpacity;
-
- for (RenderLayer* curr = m_owningLayer->parent(); curr; curr = curr->parent()) {
- // We only care about parents that are stacking contexts.
- // Recall that opacity creates stacking context.
- if (!curr->isStackingContainer())
- continue;
-
- // If we found a compositing layer, we want to compute opacity
- // relative to it. So we can break here.
- if (curr->isComposited())
- break;
-
- finalOpacity *= curr->renderer()->opacity();
- }
-
- return finalOpacity;
-}
-
-Color RenderLayerBacking::rendererBackgroundColor() const
-{
- RenderObject* backgroundRenderer = renderer();
- if (backgroundRenderer->isRoot())
- backgroundRenderer = backgroundRenderer->rendererForRootBackground();
-
- return backgroundRenderer->resolveColor(CSSPropertyBackgroundColor);
-}
-
-void RenderLayerBacking::updateBackgroundColor(bool isSimpleContainer)
-{
- Color backgroundColor = rendererBackgroundColor();
- if (isSimpleContainer) {
- m_graphicsLayer->setContentsToSolidColor(backgroundColor);
- m_graphicsLayer->setBackgroundColor(Color());
- } else {
- // An unset (invalid) color will remove the solid color.
- m_graphicsLayer->setContentsToSolidColor(Color());
- m_graphicsLayer->setBackgroundColor(backgroundColor);
- }
-}
-
-static bool supportsDirectBoxDecorationsComposition(const RenderObject* renderer)
-{
- if (!GraphicsLayer::supportsBackgroundColorContent())
- return false;
-
- if (renderer->hasClip())
- return false;
-
- if (hasBoxDecorationsOrBackgroundImage(renderer->style()))
- return false;
-
- // FIXME: we should be able to allow backgroundComposite; However since this is not a common use case it has been deferred for now.
- if (renderer->style()->backgroundComposite() != CompositeSourceOver)
- return false;
-
- if (renderer->style()->backgroundClip() == TextFillBox)
- return false;
-
- return true;
-}
-
-bool RenderLayerBacking::paintsBoxDecorations() const
-{
- if (!m_owningLayer->hasVisibleBoxDecorations())
- return false;
-
- if (!supportsDirectBoxDecorationsComposition(renderer()))
- return true;
-
- return false;
-}
-
-bool RenderLayerBacking::paintsChildren() const
-{
- if (m_owningLayer->hasVisibleContent() && m_owningLayer->hasNonEmptyChildRenderers())
- return true;
-
- if (hasVisibleNonCompositingDescendantLayers())
- return true;
-
- return false;
-}
-
-static bool isCompositedPlugin(RenderObject* renderer)
-{
- return renderer->isEmbeddedObject() && toRenderEmbeddedObject(renderer)->allowsAcceleratedCompositing();
-}
-
-// A "simple container layer" is a RenderLayer which has no visible content to render.
-// It may have no children, or all its children may be themselves composited.
-// This is a useful optimization, because it allows us to avoid allocating backing store.
-bool RenderLayerBacking::isSimpleContainerCompositingLayer() const
-{
- RenderObject* renderObject = renderer();
- if (renderObject->hasMask()) // masks require special treatment
- return false;
-
- if (renderObject->isReplaced() && !isCompositedPlugin(renderObject))
- return false;
-
- if (paintsBoxDecorations() || paintsChildren())
- return false;
-
- if (renderObject->isRenderRegion())
- return false;
-
- if (renderObject->node() && renderObject->node()->isDocumentNode()) {
- // Look to see if the root object has a non-simple background
- RenderObject* rootObject = renderObject->document().documentElement() ? renderObject->document().documentElement()->renderer() : 0;
- if (!rootObject)
- return false;
-
- RenderStyle* style = rootObject->style();
-
- // Reject anything that has a border, a border-radius or outline,
- // or is not a simple background (no background, or solid color).
- if (hasBoxDecorationsOrBackgroundImage(style))
- return false;
-
- // Now look at the body's renderer.
- HTMLElement* body = renderObject->document().body();
- RenderObject* bodyObject = (body && body->hasLocalName(bodyTag)) ? body->renderer() : 0;
- if (!bodyObject)
- return false;
-
- style = bodyObject->style();
-
- if (hasBoxDecorationsOrBackgroundImage(style))
- return false;
- }
-
- return true;
-}
-
-static bool hasVisibleNonCompositingDescendant(RenderLayer* parent)
-{
- // FIXME: We shouldn't be called with a stale z-order lists. See bug 85512.
- parent->updateLayerListsIfNeeded();
-
-#if !ASSERT_DISABLED
- LayerListMutationDetector mutationChecker(parent);
-#endif
-
- if (Vector<RenderLayer*>* normalFlowList = parent->normalFlowList()) {
- size_t listSize = normalFlowList->size();
- for (size_t i = 0; i < listSize; ++i) {
- RenderLayer* curLayer = normalFlowList->at(i);
- if (!curLayer->isComposited()
- && (curLayer->hasVisibleContent() || hasVisibleNonCompositingDescendant(curLayer)))
- return true;
- }
- }
-
- if (parent->isStackingContainer()) {
- if (!parent->hasVisibleDescendant())
- return false;
-
- // Use the m_hasCompositingDescendant bit to optimize?
- if (Vector<RenderLayer*>* negZOrderList = parent->negZOrderList()) {
- size_t listSize = negZOrderList->size();
- for (size_t i = 0; i < listSize; ++i) {
- RenderLayer* curLayer = negZOrderList->at(i);
- if (!curLayer->isComposited()
- && (curLayer->hasVisibleContent() || hasVisibleNonCompositingDescendant(curLayer)))
- return true;
- }
- }
-
- if (Vector<RenderLayer*>* posZOrderList = parent->posZOrderList()) {
- size_t listSize = posZOrderList->size();
- for (size_t i = 0; i < listSize; ++i) {
- RenderLayer* curLayer = posZOrderList->at(i);
- if (!curLayer->isComposited()
- && (curLayer->hasVisibleContent() || hasVisibleNonCompositingDescendant(curLayer)))
- return true;
- }
- }
- }
-
- return false;
-}
-
-// Conservative test for having no rendered children.
-bool RenderLayerBacking::hasVisibleNonCompositingDescendantLayers() const
-{
- return hasVisibleNonCompositingDescendant(m_owningLayer);
-}
-
-bool RenderLayerBacking::containsPaintedContent(bool isSimpleContainer) const
-{
- if (isSimpleContainer || paintsIntoCompositedAncestor() || m_artificiallyInflatedBounds || m_owningLayer->isReflection())
- return false;
-
- if (isDirectlyCompositedImage())
- return false;
-
- // FIXME: we could optimize cases where the image, video or canvas is known to fill the border box entirely,
- // and set background color on the layer in that case, instead of allocating backing store and painting.
- if (renderer()->isVideo() && toRenderVideo(renderer())->shouldDisplayVideo())
- return m_owningLayer->hasBoxDecorationsOrBackground();
-
- return true;
-}
-
-// An image can be directly compositing if it's the sole content of the layer, and has no box decorations
-// that require painting. Direct compositing saves backing store.
-bool RenderLayerBacking::isDirectlyCompositedImage() const
-{
- RenderObject* renderObject = renderer();
-
- if (!renderObject->isImage() || m_owningLayer->hasBoxDecorationsOrBackground() || renderObject->hasClip())
- return false;
-
- RenderImage* imageRenderer = toRenderImage(renderObject);
- if (ImageResource* cachedImage = imageRenderer->cachedImage()) {
- if (!cachedImage->hasImage())
- return false;
-
- Image* image = cachedImage->imageForRenderer(imageRenderer);
- if (!image->isBitmapImage())
- return false;
-
- return m_graphicsLayer->shouldDirectlyCompositeImage(image);
- }
-
- return false;
-}
-
-void RenderLayerBacking::contentChanged(ContentChangeType changeType)
-{
- if ((changeType == ImageChanged) && isDirectlyCompositedImage()) {
- updateImageContents();
- return;
- }
-
- if ((changeType == MaskImageChanged) && m_maskLayer) {
- // The composited layer bounds relies on box->maskClipRect(), which changes
- // when the mask image becomes available.
- updateAfterLayout(CompositingChildrenOnly | IsUpdateRoot);
- }
-
- if ((changeType == CanvasChanged || changeType == CanvasPixelsChanged) && isAcceleratedCanvas(renderer())) {
- m_graphicsLayer->setContentsNeedsDisplay();
- return;
- }
-}
-
-void RenderLayerBacking::updateImageContents()
-{
- ASSERT(renderer()->isImage());
- RenderImage* imageRenderer = toRenderImage(renderer());
-
- ImageResource* cachedImage = imageRenderer->cachedImage();
- if (!cachedImage)
- return;
-
- Image* image = cachedImage->imageForRenderer(imageRenderer);
- if (!image)
- return;
-
- // We have to wait until the image is fully loaded before setting it on the layer.
- if (!cachedImage->isLoaded())
- return;
-
- // This is a no-op if the layer doesn't have an inner layer for the image.
- m_graphicsLayer->setContentsToImage(image);
- bool isSimpleContainer = false;
- updateDrawsContent(isSimpleContainer);
-
- // Image animation is "lazy", in that it automatically stops unless someone is drawing
- // the image. So we have to kick the animation each time; this has the downside that the
- // image will keep animating, even if its layer is not visible.
- image->startAnimation();
-}
-
-FloatPoint3D RenderLayerBacking::computeTransformOrigin(const IntRect& borderBox) const
-{
- RenderStyle* style = renderer()->style();
-
- FloatPoint3D origin;
- origin.setX(floatValueForLength(style->transformOriginX(), borderBox.width()));
- origin.setY(floatValueForLength(style->transformOriginY(), borderBox.height()));
- origin.setZ(style->transformOriginZ());
-
- return origin;
-}
-
-FloatPoint RenderLayerBacking::computePerspectiveOrigin(const IntRect& borderBox) const
-{
- RenderStyle* style = renderer()->style();
-
- float boxWidth = borderBox.width();
- float boxHeight = borderBox.height();
-
- FloatPoint origin;
- origin.setX(floatValueForLength(style->perspectiveOriginX(), boxWidth));
- origin.setY(floatValueForLength(style->perspectiveOriginY(), boxHeight));
-
- return origin;
-}
-
-// Return the offset from the top-left of this compositing layer at which the renderer's contents are painted.
-IntSize RenderLayerBacking::contentOffsetInCompostingLayer() const
-{
- return IntSize(-m_compositedBounds.x(), -m_compositedBounds.y());
-}
-
-IntRect RenderLayerBacking::contentsBox() const
-{
- IntRect contentsBox = contentsRect(renderer());
- contentsBox.move(contentOffsetInCompostingLayer());
- return contentsBox;
-}
-
-IntRect RenderLayerBacking::backgroundBox() const
-{
- IntRect backgroundBox = backgroundRect(renderer());
- backgroundBox.move(contentOffsetInCompostingLayer());
- return backgroundBox;
-}
-
-GraphicsLayer* RenderLayerBacking::parentForSublayers() const
-{
- if (m_scrollingContentsLayer)
- return m_scrollingContentsLayer.get();
-
- return m_childContainmentLayer ? m_childContainmentLayer.get() : m_graphicsLayer.get();
-}
-
-GraphicsLayer* RenderLayerBacking::childForSuperlayers() const
-{
- if (m_ancestorClippingLayer)
- return m_ancestorClippingLayer.get();
-
- return m_graphicsLayer.get();
-}
-
-void RenderLayerBacking::setRequiresOwnBackingStore(bool requiresOwnBacking)
-{
- if (requiresOwnBacking == m_requiresOwnBackingStore)
- return;
-
- m_requiresOwnBackingStore = requiresOwnBacking;
-
- // This affects the answer to paintsIntoCompositedAncestor(), which in turn affects
- // cached clip rects, so when it changes we have to clear clip rects on descendants.
- m_owningLayer->clearClipRectsIncludingDescendants(PaintingClipRects);
- m_owningLayer->computeRepaintRectsIncludingDescendants();
-
- compositor()->repaintInCompositedAncestor(m_owningLayer, compositedBounds());
-}
-
-void RenderLayerBacking::setBlendMode(BlendMode)
-{
-}
-
-void RenderLayerBacking::setContentsNeedDisplay()
-{
- ASSERT(!paintsIntoCompositedAncestor());
-
- if (m_graphicsLayer && m_graphicsLayer->drawsContent())
- m_graphicsLayer->setNeedsDisplay();
-
- if (m_foregroundLayer && m_foregroundLayer->drawsContent())
- m_foregroundLayer->setNeedsDisplay();
-
- if (m_backgroundLayer && m_backgroundLayer->drawsContent())
- m_backgroundLayer->setNeedsDisplay();
-
- if (m_maskLayer && m_maskLayer->drawsContent())
- m_maskLayer->setNeedsDisplay();
-
- if (m_scrollingContentsLayer && m_scrollingContentsLayer->drawsContent())
- m_scrollingContentsLayer->setNeedsDisplay();
-}
-
-// r is in the coordinate space of the layer's render object
-void RenderLayerBacking::setContentsNeedDisplayInRect(const IntRect& r)
-{
- ASSERT(!paintsIntoCompositedAncestor());
-
- if (m_graphicsLayer && m_graphicsLayer->drawsContent()) {
- IntRect layerDirtyRect = r;
- layerDirtyRect.move(-m_graphicsLayer->offsetFromRenderer());
- m_graphicsLayer->setNeedsDisplayInRect(layerDirtyRect);
- }
-
- if (m_foregroundLayer && m_foregroundLayer->drawsContent()) {
- IntRect layerDirtyRect = r;
- layerDirtyRect.move(-m_foregroundLayer->offsetFromRenderer());
- m_foregroundLayer->setNeedsDisplayInRect(layerDirtyRect);
- }
-
- // FIXME: need to split out repaints for the background.
- if (m_backgroundLayer && m_backgroundLayer->drawsContent()) {
- IntRect layerDirtyRect = r;
- layerDirtyRect.move(-m_backgroundLayer->offsetFromRenderer());
- m_backgroundLayer->setNeedsDisplayInRect(layerDirtyRect);
- }
-
- if (m_maskLayer && m_maskLayer->drawsContent()) {
- IntRect layerDirtyRect = r;
- layerDirtyRect.move(-m_maskLayer->offsetFromRenderer());
- m_maskLayer->setNeedsDisplayInRect(layerDirtyRect);
- }
-
- if (m_scrollingContentsLayer && m_scrollingContentsLayer->drawsContent()) {
- IntRect layerDirtyRect = r;
- layerDirtyRect.move(-m_scrollingContentsLayer->offsetFromRenderer());
- m_scrollingContentsLayer->setNeedsDisplayInRect(layerDirtyRect);
- }
-}
-
-void RenderLayerBacking::doPaintTask(GraphicsLayerPaintInfo& paintInfo, GraphicsContext* context,
- const IntRect& clip) // In the coords of rootLayer.
-{
- if (paintsIntoCompositedAncestor()) {
- ASSERT_NOT_REACHED();
- return;
- }
-
- FontCachePurgePreventer fontCachePurgePreventer;
-
- RenderLayer::PaintLayerFlags paintFlags = 0;
- if (paintInfo.paintingPhase & GraphicsLayerPaintBackground)
- paintFlags |= RenderLayer::PaintLayerPaintingCompositingBackgroundPhase;
- if (paintInfo.paintingPhase & GraphicsLayerPaintForeground)
- paintFlags |= RenderLayer::PaintLayerPaintingCompositingForegroundPhase;
- if (paintInfo.paintingPhase & GraphicsLayerPaintMask)
- paintFlags |= RenderLayer::PaintLayerPaintingCompositingMaskPhase;
- if (paintInfo.paintingPhase & GraphicsLayerPaintOverflowContents)
- paintFlags |= RenderLayer::PaintLayerPaintingOverflowContents;
- if (paintInfo.paintingPhase & GraphicsLayerPaintCompositedScroll)
- paintFlags |= RenderLayer::PaintLayerPaintingCompositingScrollingPhase;
-
- if (paintInfo.isBackgroundLayer)
- paintFlags |= (RenderLayer::PaintLayerPaintingRootBackgroundOnly | RenderLayer::PaintLayerPaintingCompositingForegroundPhase); // Need PaintLayerPaintingCompositingForegroundPhase to walk child layers.
- else if (compositor()->fixedRootBackgroundLayer())
- paintFlags |= RenderLayer::PaintLayerPaintingSkipRootBackground;
-
- InspectorInstrumentation::willPaint(paintInfo.renderLayer->renderer());
-
- // Note carefully: in theory it is appropriate to invoke context->save() here
- // and restore the context after painting. For efficiency, we are assuming that
- // it is equivalent to manually undo this offset translation, which means we are
- // assuming that the context's space was not affected by the RenderLayer
- // painting code.
-
- LayoutSize offset = paintInfo.offsetFromRenderer;
- context->translate(-offset);
- LayoutRect relativeClip(clip);
- relativeClip.move(offset);
-
- // The dirtyRect is in the coords of the painting root.
- IntRect dirtyRect = pixelSnappedIntRect(relativeClip);
- if (!(paintInfo.paintingPhase & GraphicsLayerPaintOverflowContents))
- dirtyRect.intersect(paintInfo.compositedBounds);
-
-#ifndef NDEBUG
- paintInfo.renderLayer->renderer()->assertSubtreeIsLaidOut();
-#endif
-
- // FIXME: GraphicsLayers need a way to split for RenderRegions.
- RenderLayer::LayerPaintingInfo paintingInfo(paintInfo.renderLayer, dirtyRect, PaintBehaviorNormal, LayoutSize());
- paintInfo.renderLayer->paintLayerContents(context, paintingInfo, paintFlags);
-
- ASSERT(!paintInfo.isBackgroundLayer || paintFlags & RenderLayer::PaintLayerPaintingRootBackgroundOnly);
-
- if (paintInfo.renderLayer->containsDirtyOverlayScrollbars())
- paintInfo.renderLayer->paintLayerContents(context, paintingInfo, paintFlags | RenderLayer::PaintLayerPaintingOverlayScrollbars);
-
- ASSERT(!paintInfo.renderLayer->m_usedTransparency);
-
- // Manually restore the context to its original state by applying the opposite translation.
- context->translate(offset);
-
- InspectorInstrumentation::didPaint(paintInfo.renderLayer->renderer(), context, clip);
-}
-
-static void paintScrollbar(Scrollbar* scrollbar, GraphicsContext& context, const IntRect& clip)
-{
- if (!scrollbar)
- return;
-
- context.save();
- const IntRect& scrollbarRect = scrollbar->frameRect();
- context.translate(-scrollbarRect.x(), -scrollbarRect.y());
- IntRect transformedClip = clip;
- transformedClip.moveBy(scrollbarRect.location());
- scrollbar->paint(&context, transformedClip);
- context.restore();
-}
-
-// Up-call from compositing layer drawing callback.
-void RenderLayerBacking::paintContents(const GraphicsLayer* graphicsLayer, GraphicsContext& context, GraphicsLayerPaintingPhase paintingPhase, const IntRect& clip)
-{
-#ifndef NDEBUG
- if (Page* page = renderer()->frame()->page())
- page->setIsPainting(true);
-#endif
-
- if (graphicsLayer == m_graphicsLayer.get()
- || graphicsLayer == m_foregroundLayer.get()
- || graphicsLayer == m_backgroundLayer.get()
- || graphicsLayer == m_maskLayer.get()
- || graphicsLayer == m_scrollingContentsLayer.get()) {
-
- GraphicsLayerPaintInfo paintInfo;
- paintInfo.renderLayer = m_owningLayer;
- paintInfo.compositedBounds = compositedBounds();
- paintInfo.offsetFromRenderer = graphicsLayer->offsetFromRenderer();
- paintInfo.paintingPhase = paintingPhase;
- paintInfo.isBackgroundLayer = (graphicsLayer == m_backgroundLayer);
-
- // We have to use the same root as for hit testing, because both methods can compute and cache clipRects.
- doPaintTask(paintInfo, &context, clip);
- } else if (graphicsLayer == layerForHorizontalScrollbar()) {
- paintScrollbar(m_owningLayer->horizontalScrollbar(), context, clip);
- } else if (graphicsLayer == layerForVerticalScrollbar()) {
- paintScrollbar(m_owningLayer->verticalScrollbar(), context, clip);
- } else if (graphicsLayer == layerForScrollCorner()) {
- const IntRect& scrollCornerAndResizer = m_owningLayer->scrollCornerAndResizerRect();
- context.save();
- context.translate(-scrollCornerAndResizer.x(), -scrollCornerAndResizer.y());
- IntRect transformedClip = clip;
- transformedClip.moveBy(scrollCornerAndResizer.location());
- m_owningLayer->paintScrollCorner(&context, IntPoint(), transformedClip);
- m_owningLayer->paintResizer(&context, IntPoint(), transformedClip);
- context.restore();
- }
-#ifndef NDEBUG
- if (Page* page = renderer()->frame()->page())
- page->setIsPainting(false);
-#endif
-}
-
-void RenderLayerBacking::didCommitChangesForLayer(const GraphicsLayer* layer) const
-{
-}
-
-bool RenderLayerBacking::getCurrentTransform(const GraphicsLayer* graphicsLayer, TransformationMatrix& transform) const
-{
- if (graphicsLayer != m_graphicsLayer.get())
- return false;
-
- if (m_owningLayer->hasTransform()) {
- transform = m_owningLayer->currentTransform(RenderStyle::ExcludeTransformOrigin);
- return true;
- }
- return false;
-}
-
-bool RenderLayerBacking::isTrackingRepaints() const
-{
- GraphicsLayerClient* client = compositor();
- return client ? client->isTrackingRepaints() : false;
-}
-
-#ifndef NDEBUG
-void RenderLayerBacking::verifyNotPainting()
-{
- ASSERT(!renderer()->frame()->page() || !renderer()->frame()->page()->isPainting());
-}
-#endif
-
-bool RenderLayerBacking::startAnimation(double timeOffset, const CSSAnimationData* anim, const KeyframeList& keyframes)
-{
- bool hasOpacity = keyframes.containsProperty(CSSPropertyOpacity);
- bool hasTransform = renderer()->isBox() && keyframes.containsProperty(CSSPropertyWebkitTransform);
- bool hasFilter = keyframes.containsProperty(CSSPropertyWebkitFilter);
-
- if (!hasOpacity && !hasTransform && !hasFilter)
- return false;
-
- KeyframeValueList transformVector(AnimatedPropertyWebkitTransform);
- KeyframeValueList opacityVector(AnimatedPropertyOpacity);
- KeyframeValueList filterVector(AnimatedPropertyWebkitFilter);
-
- size_t numKeyframes = keyframes.size();
- for (size_t i = 0; i < numKeyframes; ++i) {
- const KeyframeValue& currentKeyframe = keyframes[i];
- const RenderStyle* keyframeStyle = currentKeyframe.style();
- double key = currentKeyframe.key();
-
- if (!keyframeStyle)
- continue;
-
- // Get timing function.
- RefPtr<TimingFunction> tf = KeyframeValue::timingFunction(currentKeyframe.style(), keyframes.animationName());
-
- bool isFirstOrLastKeyframe = key == 0 || key == 1;
- if ((hasTransform && isFirstOrLastKeyframe) || currentKeyframe.containsProperty(CSSPropertyWebkitTransform))
- transformVector.insert(adoptPtr(new TransformAnimationValue(key, &(keyframeStyle->transform()), tf)));
-
- if ((hasOpacity && isFirstOrLastKeyframe) || currentKeyframe.containsProperty(CSSPropertyOpacity))
- opacityVector.insert(adoptPtr(new FloatAnimationValue(key, keyframeStyle->opacity(), tf)));
-
- if ((hasFilter && isFirstOrLastKeyframe) || currentKeyframe.containsProperty(CSSPropertyWebkitFilter))
- filterVector.insert(adoptPtr(new FilterAnimationValue(key, &(keyframeStyle->filter()), tf)));
- }
-
- bool didAnimate = false;
-
- if (hasTransform && m_graphicsLayer->addAnimation(transformVector, toRenderBox(renderer())->pixelSnappedBorderBoxRect().size(), anim, keyframes.animationName(), timeOffset))
- didAnimate = true;
-
- if (hasOpacity && m_graphicsLayer->addAnimation(opacityVector, IntSize(), anim, keyframes.animationName(), timeOffset))
- didAnimate = true;
-
- if (hasFilter && m_graphicsLayer->addAnimation(filterVector, IntSize(), anim, keyframes.animationName(), timeOffset))
- didAnimate = true;
-
- return didAnimate;
-}
-
-void RenderLayerBacking::animationPaused(double timeOffset, const String& animationName)
-{
- m_graphicsLayer->pauseAnimation(animationName, timeOffset);
-}
-
-void RenderLayerBacking::animationFinished(const String& animationName)
-{
- m_graphicsLayer->removeAnimation(animationName);
-}
-
-bool RenderLayerBacking::startTransition(double timeOffset, CSSPropertyID property, const RenderStyle* fromStyle, const RenderStyle* toStyle)
-{
- bool didAnimate = false;
-
- ASSERT(property != CSSPropertyInvalid);
-
- if (property == CSSPropertyOpacity) {
- const CSSAnimationData* opacityAnim = toStyle->transitionForProperty(CSSPropertyOpacity);
- if (opacityAnim && !opacityAnim->isEmptyOrZeroDuration()) {
- KeyframeValueList opacityVector(AnimatedPropertyOpacity);
- opacityVector.insert(adoptPtr(new FloatAnimationValue(0, compositingOpacity(fromStyle->opacity()))));
- opacityVector.insert(adoptPtr(new FloatAnimationValue(1, compositingOpacity(toStyle->opacity()))));
- // The boxSize param is only used for transform animations (which can only run on RenderBoxes), so we pass an empty size here.
- if (m_graphicsLayer->addAnimation(opacityVector, IntSize(), opacityAnim, GraphicsLayer::animationNameForTransition(AnimatedPropertyOpacity), timeOffset)) {
- // To ensure that the correct opacity is visible when the animation ends, also set the final opacity.
- updateOpacity(toStyle);
- didAnimate = true;
- }
- }
- }
-
- if (property == CSSPropertyWebkitTransform && m_owningLayer->hasTransform()) {
- const CSSAnimationData* transformAnim = toStyle->transitionForProperty(CSSPropertyWebkitTransform);
- if (transformAnim && !transformAnim->isEmptyOrZeroDuration()) {
- KeyframeValueList transformVector(AnimatedPropertyWebkitTransform);
- transformVector.insert(adoptPtr(new TransformAnimationValue(0, &fromStyle->transform())));
- transformVector.insert(adoptPtr(new TransformAnimationValue(1, &toStyle->transform())));
- if (m_graphicsLayer->addAnimation(transformVector, toRenderBox(renderer())->pixelSnappedBorderBoxRect().size(), transformAnim, GraphicsLayer::animationNameForTransition(AnimatedPropertyWebkitTransform), timeOffset)) {
- // To ensure that the correct transform is visible when the animation ends, also set the final transform.
- updateTransform(toStyle);
- didAnimate = true;
- }
- }
- }
-
- if (property == CSSPropertyWebkitFilter && m_owningLayer->hasFilter()) {
- const CSSAnimationData* filterAnim = toStyle->transitionForProperty(CSSPropertyWebkitFilter);
- if (filterAnim && !filterAnim->isEmptyOrZeroDuration()) {
- KeyframeValueList filterVector(AnimatedPropertyWebkitFilter);
- filterVector.insert(adoptPtr(new FilterAnimationValue(0, &fromStyle->filter())));
- filterVector.insert(adoptPtr(new FilterAnimationValue(1, &toStyle->filter())));
- if (m_graphicsLayer->addAnimation(filterVector, IntSize(), filterAnim, GraphicsLayer::animationNameForTransition(AnimatedPropertyWebkitFilter), timeOffset)) {
- // To ensure that the correct filter is visible when the animation ends, also set the final filter.
- updateFilters(toStyle);
- didAnimate = true;
- }
- }
- }
-
- return didAnimate;
-}
-
-void RenderLayerBacking::transitionPaused(double timeOffset, CSSPropertyID property)
-{
- AnimatedPropertyID animatedProperty = cssToGraphicsLayerProperty(property);
- if (animatedProperty != AnimatedPropertyInvalid)
- m_graphicsLayer->pauseAnimation(GraphicsLayer::animationNameForTransition(animatedProperty), timeOffset);
-}
-
-void RenderLayerBacking::transitionFinished(CSSPropertyID property)
-{
- AnimatedPropertyID animatedProperty = cssToGraphicsLayerProperty(property);
- if (animatedProperty != AnimatedPropertyInvalid)
- m_graphicsLayer->removeAnimation(GraphicsLayer::animationNameForTransition(animatedProperty));
-}
-
-void RenderLayerBacking::notifyAnimationStarted(const GraphicsLayer*, double time)
-{
- renderer()->animation()->notifyAnimationStarted(renderer(), time);
-}
-
-// This is used for the 'freeze' API, for testing only.
-void RenderLayerBacking::suspendAnimations(double time)
-{
- m_graphicsLayer->suspendAnimations(time);
-}
-
-void RenderLayerBacking::resumeAnimations()
-{
- m_graphicsLayer->resumeAnimations();
-}
-
-IntRect RenderLayerBacking::compositedBounds() const
-{
- return m_compositedBounds;
-}
-
-void RenderLayerBacking::setCompositedBounds(const IntRect& bounds)
-{
- m_compositedBounds = bounds;
-}
-
-CSSPropertyID RenderLayerBacking::graphicsLayerToCSSProperty(AnimatedPropertyID property)
-{
- CSSPropertyID cssProperty = CSSPropertyInvalid;
- switch (property) {
- case AnimatedPropertyWebkitTransform:
- cssProperty = CSSPropertyWebkitTransform;
- break;
- case AnimatedPropertyOpacity:
- cssProperty = CSSPropertyOpacity;
- break;
- case AnimatedPropertyBackgroundColor:
- cssProperty = CSSPropertyBackgroundColor;
- break;
- case AnimatedPropertyWebkitFilter:
- cssProperty = CSSPropertyWebkitFilter;
- break;
- case AnimatedPropertyInvalid:
- ASSERT_NOT_REACHED();
- }
- return cssProperty;
-}
-
-AnimatedPropertyID RenderLayerBacking::cssToGraphicsLayerProperty(CSSPropertyID cssProperty)
-{
- switch (cssProperty) {
- case CSSPropertyWebkitTransform:
- return AnimatedPropertyWebkitTransform;
- case CSSPropertyOpacity:
- return AnimatedPropertyOpacity;
- case CSSPropertyBackgroundColor:
- return AnimatedPropertyBackgroundColor;
- case CSSPropertyWebkitFilter:
- return AnimatedPropertyWebkitFilter;
- default:
- // It's fine if we see other css properties here; they are just not accelerated.
- break;
- }
- return AnimatedPropertyInvalid;
-}
-
-CompositingLayerType RenderLayerBacking::compositingLayerType() const
-{
- if (m_graphicsLayer->hasContentsLayer())
- return MediaCompositingLayer;
-
- if (m_graphicsLayer->drawsContent())
- return NormalCompositingLayer;
-
- return ContainerCompositingLayer;
-}
-
-double RenderLayerBacking::backingStoreMemoryEstimate() const
-{
- double backingMemory;
-
- // m_ancestorClippingLayer and m_childContainmentLayer are just used for masking or containment, so have no backing.
- backingMemory = m_graphicsLayer->backingStoreMemoryEstimate();
- if (m_foregroundLayer)
- backingMemory += m_foregroundLayer->backingStoreMemoryEstimate();
- if (m_backgroundLayer)
- backingMemory += m_backgroundLayer->backingStoreMemoryEstimate();
- if (m_maskLayer)
- backingMemory += m_maskLayer->backingStoreMemoryEstimate();
-
- if (m_scrollingContentsLayer)
- backingMemory += m_scrollingContentsLayer->backingStoreMemoryEstimate();
-
- if (m_layerForHorizontalScrollbar)
- backingMemory += m_layerForHorizontalScrollbar->backingStoreMemoryEstimate();
-
- if (m_layerForVerticalScrollbar)
- backingMemory += m_layerForVerticalScrollbar->backingStoreMemoryEstimate();
-
- if (m_layerForScrollCorner)
- backingMemory += m_layerForScrollCorner->backingStoreMemoryEstimate();
-
- return backingMemory;
-}
-
-String RenderLayerBacking::debugName(const GraphicsLayer* graphicsLayer)
-{
- String name;
- if (graphicsLayer == m_graphicsLayer.get()) {
- name = m_owningLayer->debugName();
- } else if (graphicsLayer == m_ancestorClippingLayer.get()) {
- name = "Ancestor Clipping Layer";
- } else if (graphicsLayer == m_foregroundLayer.get()) {
- name = m_owningLayer->debugName() + " (foreground) Layer";
- } else if (graphicsLayer == m_backgroundLayer.get()) {
- name = m_owningLayer->debugName() + " (background) Layer";
- } else if (graphicsLayer == m_childContainmentLayer.get()) {
- name = "Child Containment Layer";
- } else if (graphicsLayer == m_maskLayer.get()) {
- name = "Mask Layer";
- } else if (graphicsLayer == m_layerForHorizontalScrollbar.get()) {
- name = "Horizontal Scrollbar Layer";
- } else if (graphicsLayer == m_layerForVerticalScrollbar.get()) {
- name = "Vertical Scrollbar Layer";
- } else if (graphicsLayer == m_layerForScrollCorner.get()) {
- name = "Scroll Corner Layer";
- } else if (graphicsLayer == m_scrollingLayer.get()) {
- name = "Scrolling Layer";
- } else if (graphicsLayer == m_scrollingContentsLayer.get()) {
- name = "Scrolling Contents Layer";
- } else {
- ASSERT_NOT_REACHED();
- }
-
- return name;
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderLayerBacking.h b/chromium/third_party/WebKit/Source/core/rendering/RenderLayerBacking.h
deleted file mode 100644
index 6e388527935..00000000000
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderLayerBacking.h
+++ /dev/null
@@ -1,331 +0,0 @@
-/*
- * Copyright (C) 2009, 2010, 2011 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef RenderLayerBacking_h
-#define RenderLayerBacking_h
-
-#include "core/platform/graphics/FloatPoint.h"
-#include "core/platform/graphics/FloatPoint3D.h"
-#include "core/platform/graphics/GraphicsLayer.h"
-#include "core/platform/graphics/GraphicsLayerClient.h"
-#include "core/platform/graphics/transforms/TransformationMatrix.h"
-#include "core/rendering/RenderLayer.h"
-
-namespace WebCore {
-
-class KeyframeList;
-class RenderLayerCompositor;
-
-enum CompositingLayerType {
- NormalCompositingLayer, // non-tiled layer with backing store
- MediaCompositingLayer, // layer that contains an image, video, webGL or plugin
- ContainerCompositingLayer // layer with no backing store
-};
-
-
-// A GraphicsLayerPaintInfo contains all the info needed to paint a partial subtree of RenderLayers into a GraphicsLayer.
-struct GraphicsLayerPaintInfo {
- RenderLayer* renderLayer;
-
- IntRect compositedBounds;
-
- IntSize offsetFromRenderer;
-
- GraphicsLayerPaintingPhase paintingPhase;
-
- bool isBackgroundLayer;
-};
-
-// RenderLayerBacking controls the compositing behavior for a single RenderLayer.
-// It holds the various GraphicsLayers, and makes decisions about intra-layer rendering
-// optimizations.
-//
-// There is one RenderLayerBacking for each RenderLayer that is composited.
-
-class RenderLayerBacking : public GraphicsLayerClient {
- WTF_MAKE_NONCOPYABLE(RenderLayerBacking); WTF_MAKE_FAST_ALLOCATED;
-public:
- explicit RenderLayerBacking(RenderLayer*);
- ~RenderLayerBacking();
-
- RenderLayer* owningLayer() const { return m_owningLayer; }
-
- enum UpdateAfterLayoutFlag {
- CompositingChildrenOnly = 1 << 0,
- NeedsFullRepaint = 1 << 1,
- IsUpdateRoot = 1 << 2
- };
- typedef unsigned UpdateAfterLayoutFlags;
- void updateAfterLayout(UpdateAfterLayoutFlags);
-
- // Returns true if layer configuration changed.
- bool updateGraphicsLayerConfiguration();
- // Update graphics layer position and bounds.
- void updateGraphicsLayerGeometry(); // make private
- // Update whether layer needs blending.
- void updateContentsOpaque();
-
- GraphicsLayer* graphicsLayer() const { return m_graphicsLayer.get(); }
-
- // Layer to clip children
- bool hasClippingLayer() const { return m_childContainmentLayer; }
- GraphicsLayer* clippingLayer() const { return m_childContainmentLayer.get(); }
-
- // Layer to get clipped by ancestor
- bool hasAncestorClippingLayer() const { return m_ancestorClippingLayer; }
- GraphicsLayer* ancestorClippingLayer() const { return m_ancestorClippingLayer.get(); }
-
- bool hasContentsLayer() const { return m_foregroundLayer != 0; }
- GraphicsLayer* foregroundLayer() const { return m_foregroundLayer.get(); }
-
- GraphicsLayer* backgroundLayer() const { return m_backgroundLayer.get(); }
- bool backgroundLayerPaintsFixedRootBackground() const { return m_backgroundLayerPaintsFixedRootBackground; }
-
- bool hasScrollingLayer() const { return m_scrollingLayer; }
- GraphicsLayer* scrollingLayer() const { return m_scrollingLayer.get(); }
- GraphicsLayer* scrollingContentsLayer() const { return m_scrollingContentsLayer.get(); }
-
- bool hasMaskLayer() const { return m_maskLayer != 0; }
-
- GraphicsLayer* parentForSublayers() const;
- GraphicsLayer* childForSuperlayers() const;
-
- // Returns true for a composited layer that has no backing store of its own, so
- // paints into some ancestor layer.
- bool paintsIntoCompositedAncestor() const { return !m_requiresOwnBackingStore; }
-
- void setRequiresOwnBackingStore(bool);
-
- void setContentsNeedDisplay();
- // r is in the coordinate space of the layer's render object
- void setContentsNeedDisplayInRect(const IntRect&);
-
- // Notification from the renderer that its content changed.
- void contentChanged(ContentChangeType);
-
- // Interface to start, finish, suspend and resume animations and transitions
- bool startTransition(double, CSSPropertyID, const RenderStyle* fromStyle, const RenderStyle* toStyle);
- void transitionPaused(double timeOffset, CSSPropertyID);
- void transitionFinished(CSSPropertyID);
-
- bool startAnimation(double timeOffset, const CSSAnimationData* anim, const KeyframeList& keyframes);
- void animationPaused(double timeOffset, const String& name);
- void animationFinished(const String& name);
-
- void suspendAnimations(double time = 0);
- void resumeAnimations();
-
- IntRect compositedBounds() const;
- void setCompositedBounds(const IntRect&);
- void updateCompositedBounds();
-
- void updateAfterWidgetResize();
- void positionOverflowControlsLayers(const IntSize& offsetFromRoot);
- bool hasUnpositionedOverflowControlsLayers() const;
-
- // GraphicsLayerClient interface
- virtual void notifyAnimationStarted(const GraphicsLayer*, double startTime) OVERRIDE;
-
- virtual void paintContents(const GraphicsLayer*, GraphicsContext&, GraphicsLayerPaintingPhase, const IntRect& clip) OVERRIDE;
-
- virtual void didCommitChangesForLayer(const GraphicsLayer*) const OVERRIDE;
- virtual bool getCurrentTransform(const GraphicsLayer*, TransformationMatrix&) const OVERRIDE;
-
- virtual bool isTrackingRepaints() const OVERRIDE;
-
-#ifndef NDEBUG
- virtual void verifyNotPainting();
-#endif
-
- IntRect contentsBox() const;
- IntRect backgroundBox() const;
-
- // For informative purposes only.
- CompositingLayerType compositingLayerType() const;
-
- GraphicsLayer* layerForHorizontalScrollbar() const { return m_layerForHorizontalScrollbar.get(); }
- GraphicsLayer* layerForVerticalScrollbar() const { return m_layerForVerticalScrollbar.get(); }
- GraphicsLayer* layerForScrollCorner() const { return m_layerForScrollCorner.get(); }
-
- void updateFilters(const RenderStyle*);
- bool canCompositeFilters() const { return m_canCompositeFilters; }
-
- // Return an estimate of the backing store area (in pixels) allocated by this object's GraphicsLayers.
- double backingStoreMemoryEstimate() const;
-
- void setBlendMode(BlendMode);
-
- virtual String debugName(const GraphicsLayer*) OVERRIDE;
-
-private:
- void createPrimaryGraphicsLayer();
- void destroyGraphicsLayers();
-
- PassOwnPtr<GraphicsLayer> createGraphicsLayer(CompositingReasons);
-
- RenderLayerModelObject* renderer() const { return m_owningLayer->renderer(); }
- RenderLayerCompositor* compositor() const { return m_owningLayer->compositor(); }
-
- void updateInternalHierarchy();
- bool updateClippingLayers(bool needsAncestorClip, bool needsDescendantClip);
- bool updateOverflowControlsLayers(bool needsHorizontalScrollbarLayer, bool needsVerticalScrollbarLayer, bool needsScrollCornerLayer);
- bool updateForegroundLayer(bool needsForegroundLayer);
- bool updateBackgroundLayer(bool needsBackgroundLayer);
- bool updateMaskLayer(bool needsMaskLayer);
- bool requiresHorizontalScrollbarLayer() const { return m_owningLayer->horizontalScrollbar(); }
- bool requiresVerticalScrollbarLayer() const { return m_owningLayer->verticalScrollbar(); }
- bool requiresScrollCornerLayer() const { return !m_owningLayer->scrollCornerAndResizerRect().isEmpty(); }
- bool updateScrollingLayers(bool scrollingLayers);
- void updateScrollParent(RenderLayer*);
- void updateClipParent(RenderLayer*);
- void updateDrawsContent(bool isSimpleContainer);
- void registerScrollingLayers();
-
- void setBackgroundLayerPaintsFixedRootBackground(bool);
-
- GraphicsLayerPaintingPhase paintingPhaseForPrimaryLayer() const;
-
- IntSize contentOffsetInCompostingLayer() const;
- // Result is transform origin in pixels.
- FloatPoint3D computeTransformOrigin(const IntRect& borderBox) const;
- // Result is perspective origin in pixels.
- FloatPoint computePerspectiveOrigin(const IntRect& borderBox) const;
-
- void updateOpacity(const RenderStyle*);
- void updateTransform(const RenderStyle*);
- void updateLayerBlendMode(const RenderStyle*);
- // Return the opacity value that this layer should use for compositing.
- float compositingOpacity(float rendererOpacity) const;
-
- bool isMainFrameRenderViewLayer() const;
-
- bool paintsBoxDecorations() const;
- bool paintsChildren() const;
-
- // Returns true if this compositing layer has no visible content.
- bool isSimpleContainerCompositingLayer() const;
- // Returns true if this layer has content that needs to be rendered by painting into the backing store.
- bool containsPaintedContent(bool isSimpleContainer) const;
- // Returns true if the RenderLayer just contains an image that we can composite directly.
- bool isDirectlyCompositedImage() const;
- void updateImageContents();
-
- Color rendererBackgroundColor() const;
- void updateBackgroundColor(bool isSimpleContainer);
- void updateContentsRect(bool isSimpleContainer);
-
- void updateCompositingReasons();
-
- bool hasVisibleNonCompositingDescendantLayers() const;
-
- bool shouldClipCompositedBounds() const;
-
- void doPaintTask(GraphicsLayerPaintInfo&, GraphicsContext*, const IntRect& clip);
-
- static CSSPropertyID graphicsLayerToCSSProperty(AnimatedPropertyID);
- static AnimatedPropertyID cssToGraphicsLayerProperty(CSSPropertyID);
-
- RenderLayer* m_owningLayer;
-
- // The hierarchy of layers that is maintained by the RenderLayerBacking looks like this:
- //
- // + m_ancestorClippingLayer [OPTIONAL]
- // + m_graphicsLayer
- // + m_childContainmentLayer [OPTIONAL] <-OR-> m_scrollingLayer [OPTIONAL]
- // + m_scrollingContentsLayer [OPTIONAL]
- //
- // We need an ancestor clipping layer if our clipping ancestor is not our ancestor in the
- // clipping tree. Here's what that might look like.
- //
- // Let A = the clipping ancestor,
- // B = the clip descendant, and
- // SC = the stacking context that is the ancestor of A and B in the stacking tree.
- //
- // SC
- // + A = m_graphicsLayer
- // | + m_childContainmentLayer
- // | + ...
- // ...
- // |
- // + B = m_ancestorClippingLayer [+]
- // + m_graphicsLayer
- // + ...
- //
- // In this case B is clipped by another layer that doesn't happen to be its ancestor: A.
- // So we create an ancestor clipping layer for B, [+], which ensures that B is clipped
- // as if it had been A's descendant.
- OwnPtr<GraphicsLayer> m_ancestorClippingLayer; // Only used if we are clipped by an ancestor which is not a stacking context.
- OwnPtr<GraphicsLayer> m_graphicsLayer;
- OwnPtr<GraphicsLayer> m_childContainmentLayer; // Only used if we have clipping on a stacking context with compositing children.
- OwnPtr<GraphicsLayer> m_scrollingLayer; // Only used if the layer is using composited scrolling.
- OwnPtr<GraphicsLayer> m_scrollingContentsLayer; // Only used if the layer is using composited scrolling.
-
- // This layer is also added to the hierarchy by the RLB, but in a different way than
- // the layers above. It's added to m_graphicsLayer as its mask layer (naturally) if
- // we have a mask, and isn't part of the typical hierarchy (it has no children).
- OwnPtr<GraphicsLayer> m_maskLayer; // Only used if we have a mask.
-
- // There are two other (optional) layers whose painting is managed by the RenderLayerBacking,
- // but whose position in the hierarchy is maintained by the RenderLayerCompositor. These
- // are the foreground and background layers. The foreground layer exists if we have composited
- // descendants with negative z-order. We need the extra layer in this case because the layer
- // needs to draw both below (for the background, say) and above (for the normal flow content, say)
- // the negative z-order descendants and this is impossible with a single layer. The RLC handles
- // inserting m_foregroundLayer in the correct position in our descendant list for us (right after
- // the neg z-order dsecendants).
- //
- // The background layer is only created if this is the root layer and our background is entirely
- // fixed. In this case we want to put the background in a separate composited layer so that when
- // we scroll, we don't have to re-raster the background into position. This layer is also inserted
- // into the tree by the RLC as it gets a special home. This layer becomes a descendant of the
- // frame clipping layer. That is:
- // ...
- // + frame clipping layer
- // + m_backgroundLayer
- // + frame scrolling layer
- // + root content layer
- //
- // With the hierarchy set up like this, the root content layer is able to scroll without affecting
- // the background layer (or repainting).
- OwnPtr<GraphicsLayer> m_foregroundLayer; // Only used in cases where we need to draw the foreground separately.
- OwnPtr<GraphicsLayer> m_backgroundLayer; // Only used in cases where we need to draw the background separately.
-
- OwnPtr<GraphicsLayer> m_layerForHorizontalScrollbar;
- OwnPtr<GraphicsLayer> m_layerForVerticalScrollbar;
- OwnPtr<GraphicsLayer> m_layerForScrollCorner;
-
- IntRect m_compositedBounds;
-
- bool m_artificiallyInflatedBounds; // bounds had to be made non-zero to make transform-origin work
- bool m_boundsConstrainedByClipping;
- bool m_isMainFrameRenderViewLayer;
- bool m_requiresOwnBackingStore;
- bool m_canCompositeFilters;
- bool m_backgroundLayerPaintsFixedRootBackground;
-};
-
-} // namespace WebCore
-
-#endif // RenderLayerBacking_h
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderLayerClipper.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderLayerClipper.cpp
new file mode 100644
index 00000000000..f14aa06ee27
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderLayerClipper.cpp
@@ -0,0 +1,191 @@
+/*
+ * Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012 Apple Inc. All rights reserved.
+ *
+ * Portions are Copyright (C) 1998 Netscape Communications Corporation.
+ *
+ * Other contributors:
+ * Robert O'Callahan <roc+@cs.cmu.edu>
+ * David Baron <dbaron@fas.harvard.edu>
+ * Christian Biesinger <cbiesinger@web.de>
+ * Randall Jesup <rjesup@wgate.com>
+ * Roland Mainz <roland.mainz@informatik.med.uni-giessen.de>
+ * Josh Soref <timeless@mac.com>
+ * Boris Zbarsky <bzbarsky@mit.edu>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ * Alternatively, the contents of this file may be used under the terms
+ * of either the Mozilla Public License Version 1.1, found at
+ * http://www.mozilla.org/MPL/ (the "MPL") or the GNU General Public
+ * License Version 2.0, found at http://www.fsf.org/copyleft/gpl.html
+ * (the "GPL"), in which case the provisions of the MPL or the GPL are
+ * applicable instead of those above. If you wish to allow use of your
+ * version of this file only under the terms of one of those two
+ * licenses (the MPL or the GPL) and not to allow others to use your
+ * version of this file under the LGPL, indicate your decision by
+ * deletingthe provisions above and replace them with the notice and
+ * other provisions required by the MPL or the GPL, as the case may be.
+ * If you do not delete the provisions above, a recipient may use your
+ * version of this file under any of the LGPL, the MPL or the GPL.
+ */
+
+#include "config.h"
+#include "core/rendering/RenderLayerClipper.h"
+
+#include "core/rendering/RenderLayer.h"
+#include "core/rendering/RenderView.h"
+
+namespace WebCore {
+
+void RenderLayerClipper::updateClipRects(const ClipRectsContext& clipRectsContext)
+{
+ ClipRectsType clipRectsType = clipRectsContext.clipRectsType;
+ ASSERT(clipRectsType < NumCachedClipRectsTypes);
+ if (m_clipRectsCache && m_clipRectsCache->getClipRects(clipRectsType, clipRectsContext.respectOverflowClip)) {
+ // FIXME: these asserts trigger for squashing. Need to update this code to support squashing as appropriate.
+ ASSERT(clipRectsContext.rootLayer == m_clipRectsCache->m_clipRectsRoot[clipRectsType]);
+ ASSERT(m_clipRectsCache->m_scrollbarRelevancy[clipRectsType] == clipRectsContext.overlayScrollbarSizeRelevancy);
+
+#ifdef CHECK_CACHED_CLIP_RECTS
+ // This code is useful to check cached clip rects, but is too expensive to leave enabled in debug builds by default.
+ ClipRectsContext tempContext(clipRectsContext);
+ tempContext.clipRectsType = TemporaryClipRects;
+ ClipRects clipRects;
+ calculateClipRects(tempContext, clipRects);
+ ASSERT(clipRects == *m_clipRectsCache->getClipRects(clipRectsType, clipRectsContext.respectOverflowClip).get());
+#endif
+ return; // We have the correct cached value.
+ }
+
+ // For transformed layers, the root layer was shifted to be us, so there is no need to
+ // examine the parent. We want to cache clip rects with us as the root.
+ RenderLayer* parentLayer = clipRectsContext.rootLayer != m_renderer->layer() ? m_renderer->layer()->parent() : 0;
+ if (parentLayer)
+ parentLayer->clipper().updateClipRects(clipRectsContext);
+
+ ClipRects clipRects;
+ calculateClipRects(clipRectsContext, clipRects);
+
+ if (!m_clipRectsCache)
+ m_clipRectsCache = adoptPtr(new ClipRectsCache);
+
+ if (parentLayer && parentLayer->clipper().clipRects(clipRectsContext) && clipRects == *parentLayer->clipper().clipRects(clipRectsContext))
+ m_clipRectsCache->setClipRects(clipRectsType, clipRectsContext.respectOverflowClip, parentLayer->clipper().clipRects(clipRectsContext));
+ else
+ m_clipRectsCache->setClipRects(clipRectsType, clipRectsContext.respectOverflowClip, ClipRects::create(clipRects));
+
+#ifndef NDEBUG
+ m_clipRectsCache->m_clipRectsRoot[clipRectsType] = clipRectsContext.rootLayer;
+ m_clipRectsCache->m_scrollbarRelevancy[clipRectsType] = clipRectsContext.overlayScrollbarSizeRelevancy;
+#endif
+}
+
+void RenderLayerClipper::clearClipRectsIncludingDescendants(ClipRectsType typeToClear)
+{
+ // FIXME: it's not clear how this layer not having clip rects guarantees that no descendants have any.
+ if (!m_clipRectsCache)
+ return;
+
+ clearClipRects(typeToClear);
+
+ for (RenderLayer* layer = m_renderer->layer()->firstChild(); layer; layer = layer->nextSibling())
+ layer->clipper().clearClipRectsIncludingDescendants(typeToClear);
+}
+
+void RenderLayerClipper::clearClipRects(ClipRectsType typeToClear)
+{
+ if (typeToClear == AllClipRectTypes) {
+ m_clipRectsCache = nullptr;
+ } else {
+ ASSERT(typeToClear < NumCachedClipRectsTypes);
+ RefPtr<ClipRects> dummy;
+ m_clipRectsCache->setClipRects(typeToClear, RespectOverflowClip, dummy);
+ m_clipRectsCache->setClipRects(typeToClear, IgnoreOverflowClip, dummy);
+ }
+}
+
+void RenderLayerClipper::calculateClipRects(const ClipRectsContext& clipRectsContext, ClipRects& clipRects) const
+{
+ if (!m_renderer->layer()->parent()) {
+ // The root layer's clip rect is always infinite.
+ clipRects.reset(PaintInfo::infiniteRect());
+ return;
+ }
+
+ ClipRectsType clipRectsType = clipRectsContext.clipRectsType;
+ bool useCached = clipRectsType != TemporaryClipRects;
+
+ // For transformed layers, the root layer was shifted to be us, so there is no need to
+ // examine the parent. We want to cache clip rects with us as the root.
+ RenderLayer* parentLayer = clipRectsContext.rootLayer != m_renderer->layer() ? m_renderer->layer()->parent() : 0;
+
+ // Ensure that our parent's clip has been calculated so that we can examine the values.
+ if (parentLayer) {
+ if (useCached && parentLayer->clipper().clipRects(clipRectsContext)) {
+ clipRects = *parentLayer->clipper().clipRects(clipRectsContext);
+ } else {
+ ClipRectsContext parentContext(clipRectsContext);
+ parentContext.overlayScrollbarSizeRelevancy = IgnoreOverlayScrollbarSize; // FIXME: why?
+ parentLayer->clipper().calculateClipRects(parentContext, clipRects);
+ }
+ } else {
+ clipRects.reset(PaintInfo::infiniteRect());
+ }
+
+ // A fixed object is essentially the root of its containing block hierarchy, so when
+ // we encounter such an object, we reset our clip rects to the fixedClipRect.
+ if (m_renderer->style()->position() == FixedPosition) {
+ clipRects.setPosClipRect(clipRects.fixedClipRect());
+ clipRects.setOverflowClipRect(clipRects.fixedClipRect());
+ clipRects.setFixed(true);
+ } else if (m_renderer->style()->hasInFlowPosition()) {
+ clipRects.setPosClipRect(clipRects.overflowClipRect());
+ } else if (m_renderer->style()->position() == AbsolutePosition) {
+ clipRects.setOverflowClipRect(clipRects.posClipRect());
+ }
+
+ // Update the clip rects that will be passed to child layers.
+ if ((m_renderer->hasOverflowClip() && (clipRectsContext.respectOverflowClip == RespectOverflowClip || m_renderer->layer() != clipRectsContext.rootLayer)) || m_renderer->hasClip()) {
+ // This layer establishes a clip of some kind.
+
+ // This offset cannot use convertToLayerCoords, because sometimes our rootLayer may be across
+ // some transformed layer boundary, for example, in the RenderLayerCompositor overlapMap, where
+ // clipRects are needed in view space.
+ LayoutPoint offset;
+ offset = roundedLayoutPoint(m_renderer->localToContainerPoint(FloatPoint(), clipRectsContext.rootLayer->renderer()));
+ RenderView* view = m_renderer->view();
+ ASSERT(view);
+ if (view && clipRects.fixed() && clipRectsContext.rootLayer->renderer() == view) {
+ offset -= view->frameView()->scrollOffsetForFixedPosition();
+ }
+
+ if (m_renderer->hasOverflowClip()) {
+ ClipRect newOverflowClip = toRenderBox(m_renderer)->overflowClipRect(offset, clipRectsContext.region, clipRectsContext.overlayScrollbarSizeRelevancy);
+ if (m_renderer->style()->hasBorderRadius())
+ newOverflowClip.setHasRadius(true);
+ clipRects.setOverflowClipRect(intersection(newOverflowClip, clipRects.overflowClipRect()));
+ if (m_renderer->isPositioned())
+ clipRects.setPosClipRect(intersection(newOverflowClip, clipRects.posClipRect()));
+ }
+ if (m_renderer->hasClip()) {
+ LayoutRect newPosClip = toRenderBox(m_renderer)->clipRect(offset, clipRectsContext.region);
+ clipRects.setPosClipRect(intersection(newPosClip, clipRects.posClipRect()));
+ clipRects.setOverflowClipRect(intersection(newPosClip, clipRects.overflowClipRect()));
+ clipRects.setFixedClipRect(intersection(newPosClip, clipRects.fixedClipRect()));
+ }
+ }
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderLayerClipper.h b/chromium/third_party/WebKit/Source/core/rendering/RenderLayerClipper.h
new file mode 100644
index 00000000000..03a3ef1a603
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderLayerClipper.h
@@ -0,0 +1,104 @@
+/*
+ * Copyright (C) 2003, 2009, 2012 Apple Inc. All rights reserved.
+ * Copyright (C) 2013 Intel Corporation. All rights reserved.
+ *
+ * Portions are Copyright (C) 1998 Netscape Communications Corporation.
+ *
+ * Other contributors:
+ * Robert O'Callahan <roc+@cs.cmu.edu>
+ * David Baron <dbaron@fas.harvard.edu>
+ * Christian Biesinger <cbiesinger@web.de>
+ * Randall Jesup <rjesup@wgate.com>
+ * Roland Mainz <roland.mainz@informatik.med.uni-giessen.de>
+ * Josh Soref <timeless@mac.com>
+ * Boris Zbarsky <bzbarsky@mit.edu>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ * Alternatively, the contents of this file may be used under the terms
+ * of either the Mozilla Public License Version 1.1, found at
+ * http://www.mozilla.org/MPL/ (the "MPL") or the GNU General Public
+ * License Version 2.0, found at http://www.fsf.org/copyleft/gpl.html
+ * (the "GPL"), in which case the provisions of the MPL or the GPL are
+ * applicable instead of those above. If you wish to allow use of your
+ * version of this file only under the terms of one of those two
+ * licenses (the MPL or the GPL) and not to allow others to use your
+ * version of this file under the LGPL, indicate your decision by
+ * deletingthe provisions above and replace them with the notice and
+ * other provisions required by the MPL or the GPL, as the case may be.
+ * If you do not delete the provisions above, a recipient may use your
+ * version of this file under any of the LGPL, the MPL or the GPL.
+ */
+
+#ifndef RenderLayerClipper_h
+#define RenderLayerClipper_h
+
+#include "core/rendering/ClipRect.h"
+#include "core/rendering/RenderBox.h" // For OverlayScrollbarSizeRelevancy.
+
+namespace WebCore {
+
+class RenderLayer;
+class RenderRegion;
+
+struct ClipRectsContext {
+ ClipRectsContext(const RenderLayer* inRootLayer, RenderRegion* inRegion, ClipRectsType inClipRectsType, OverlayScrollbarSizeRelevancy inOverlayScrollbarSizeRelevancy = IgnoreOverlayScrollbarSize, ShouldRespectOverflowClip inRespectOverflowClip = RespectOverflowClip)
+ : rootLayer(inRootLayer)
+ , region(inRegion)
+ , clipRectsType(inClipRectsType)
+ , overlayScrollbarSizeRelevancy(inOverlayScrollbarSizeRelevancy)
+ , respectOverflowClip(inRespectOverflowClip)
+ { }
+ const RenderLayer* rootLayer;
+ RenderRegion* region;
+ ClipRectsType clipRectsType;
+ OverlayScrollbarSizeRelevancy overlayScrollbarSizeRelevancy;
+ ShouldRespectOverflowClip respectOverflowClip;
+};
+
+class RenderLayerClipper {
+ WTF_MAKE_NONCOPYABLE(RenderLayerClipper);
+public:
+ RenderLayerClipper(RenderLayerModelObject* renderer)
+ : m_renderer(renderer)
+ {
+ }
+
+ ClipRects* clipRects(const ClipRectsContext& context) const
+ {
+ ASSERT(context.clipRectsType < NumCachedClipRectsTypes);
+ return m_clipRectsCache ? m_clipRectsCache->getClipRects(context.clipRectsType, context.respectOverflowClip).get() : 0;
+ }
+
+ // Compute and cache clip rects computed with the given layer as the root
+ void updateClipRects(const ClipRectsContext&);
+
+ void clearClipRectsIncludingDescendants(ClipRectsType typeToClear = AllClipRectTypes);
+ void clearClipRects(ClipRectsType typeToClear = AllClipRectTypes);
+
+ // Compute and return the clip rects. If useCached is true, will used previously computed clip rects on ancestors
+ // (rather than computing them all from scratch up the parent chain).
+ void calculateClipRects(const ClipRectsContext&, ClipRects&) const;
+
+private:
+ // FIXME: Could this be a RenderBox?
+ RenderLayerModelObject* m_renderer;
+
+ OwnPtr<ClipRectsCache> m_clipRectsCache;
+};
+
+} // namespace WebCore
+
+#endif // RenderLayerClipper_h
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderLayerCompositor.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderLayerCompositor.cpp
index 04b980e0635..45565a55007 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderLayerCompositor.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderLayerCompositor.cpp
@@ -30,6 +30,8 @@
#include "CSSPropertyNames.h"
#include "HTMLNames.h"
#include "RuntimeEnabledFeatures.h"
+#include "core/animation/ActiveAnimations.h"
+#include "core/animation/DocumentAnimations.h"
#include "core/dom/FullscreenElementStack.h"
#include "core/dom/NodeList.h"
#include "core/html/HTMLCanvasElement.h"
@@ -38,45 +40,37 @@
#include "core/html/canvas/CanvasRenderingContext.h"
#include "core/inspector/InspectorInstrumentation.h"
#include "core/page/Chrome.h"
-#include "core/page/ChromeClient.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameView.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
#include "core/page/Page.h"
-#include "core/page/Settings.h"
-#include "core/page/animation/AnimationController.h"
+#include "core/frame/Settings.h"
+#include "core/frame/animation/AnimationController.h"
#include "core/page/scrolling/ScrollingConstraints.h"
#include "core/page/scrolling/ScrollingCoordinator.h"
-#include "core/platform/HistogramSupport.h"
-#include "core/platform/Logging.h"
-#include "core/platform/ScrollbarTheme.h"
-#include "core/platform/chromium/TraceEvent.h"
-#include "core/platform/graphics/GraphicsLayer.h"
-#include "core/platform/graphics/GraphicsLayerClient.h"
-#include "core/platform/graphics/transforms/TransformState.h"
+#include "core/rendering/CompositedLayerMapping.h"
#include "core/rendering/HitTestResult.h"
#include "core/rendering/RenderApplet.h"
#include "core/rendering/RenderEmbeddedObject.h"
#include "core/rendering/RenderFullScreen.h"
#include "core/rendering/RenderGeometryMap.h"
#include "core/rendering/RenderIFrame.h"
-#include "core/rendering/RenderLayerBacking.h"
+#include "core/rendering/RenderLayerStackingNode.h"
+#include "core/rendering/RenderLayerStackingNodeIterator.h"
#include "core/rendering/RenderReplica.h"
#include "core/rendering/RenderVideo.h"
#include "core/rendering/RenderView.h"
+#include "platform/OverscrollTheme.h"
+#include "platform/TraceEvent.h"
+#include "platform/geometry/TransformState.h"
+#include "platform/graphics/GraphicsLayer.h"
+#include "platform/scroll/ScrollbarTheme.h"
+#include "public/platform/Platform.h"
#include "wtf/TemporaryChange.h"
-#if !LOG_DISABLED
-#include "wtf/CurrentTime.h"
-#endif
-
#ifndef NDEBUG
#include "core/rendering/RenderTreeAsText.h"
#endif
-#define WTF_USE_COMPOSITING_FOR_SMALL_CANVASES 1
-
-static const int canvasAreaThresholdRequiringCompositing = 50 * 100;
-
namespace WebCore {
using namespace HTMLNames;
@@ -179,10 +173,11 @@ private:
RenderGeometryMap m_geometryMap;
};
-struct CompositingState {
- CompositingState(RenderLayer* compAncestor, bool testOverlap)
+struct CompositingRecursionData {
+ CompositingRecursionData(RenderLayer* compAncestor, bool testOverlap)
: m_compositingAncestor(compAncestor)
, m_subtreeIsCompositing(false)
+ , m_hasUnisolatedCompositedBlendingDescendant(false)
, m_testingOverlap(testOverlap)
#ifndef NDEBUG
, m_depth(0)
@@ -190,9 +185,10 @@ struct CompositingState {
{
}
- CompositingState(const CompositingState& other)
+ CompositingRecursionData(const CompositingRecursionData& other)
: m_compositingAncestor(other.m_compositingAncestor)
, m_subtreeIsCompositing(other.m_subtreeIsCompositing)
+ , m_hasUnisolatedCompositedBlendingDescendant(other.m_hasUnisolatedCompositedBlendingDescendant)
, m_testingOverlap(other.m_testingOverlap)
#ifndef NDEBUG
, m_depth(other.m_depth + 1)
@@ -202,6 +198,7 @@ struct CompositingState {
RenderLayer* m_compositingAncestor;
bool m_subtreeIsCompositing;
+ bool m_hasUnisolatedCompositedBlendingDescendant;
bool m_testingOverlap;
#ifndef NDEBUG
int m_depth;
@@ -209,22 +206,13 @@ struct CompositingState {
};
-static inline bool compositingLogEnabled()
-{
-#if !LOG_DISABLED
- return LogCompositing.state == WTFLogChannelOn;
-#else
- return false;
-#endif
-}
-
RenderLayerCompositor::RenderLayerCompositor(RenderView* renderView)
: m_renderView(renderView)
, m_hasAcceleratedCompositing(true)
, m_compositingTriggers(static_cast<ChromeClient::CompositingTriggerFlags>(ChromeClient::AllTriggers))
- , m_compositedLayerCount(0)
, m_showRepaintCounter(false)
- , m_reevaluateCompositingAfterLayout(false)
+ , m_needsToRecomputeCompositingRequirements(false)
+ , m_needsToUpdateLayerTreeGeometry(false)
, m_compositing(false)
, m_compositingLayersNeedRebuild(false)
, m_forceCompositingMode(false)
@@ -232,13 +220,6 @@ RenderLayerCompositor::RenderLayerCompositor(RenderView* renderView)
, m_needsUpdateCompositingRequirementsState(false)
, m_isTrackingRepaints(false)
, m_rootLayerAttachment(RootLayerUnattached)
-#if !LOG_DISABLED
- , m_rootLayerUpdateCount(0)
- , m_obligateCompositedLayerCount(0)
- , m_secondaryCompositedLayerCount(0)
- , m_obligatoryBackingStoreBytes(0)
- , m_secondaryBackingStoreBytes(0)
-#endif
{
}
@@ -293,6 +274,14 @@ void RenderLayerCompositor::cacheAcceleratedCompositingFlags()
m_forceCompositingMode = forceCompositingMode;
}
+bool RenderLayerCompositor::layerSquashingEnabled() const
+{
+ if (Settings* settings = m_renderView->document().settings())
+ return settings->layerSquashingEnabled();
+
+ return false;
+}
+
bool RenderLayerCompositor::canRender3DTransforms() const
{
return hasAcceleratedCompositing() && (m_compositingTriggers & ChromeClient::ThreeDTransformTrigger);
@@ -300,8 +289,11 @@ bool RenderLayerCompositor::canRender3DTransforms() const
void RenderLayerCompositor::setCompositingLayersNeedRebuild(bool needRebuild)
{
+ // FIXME: crbug,com/332248 ideally this could be merged with setNeedsCompositingUpdate().
if (inCompositingMode())
m_compositingLayersNeedRebuild = needRebuild;
+
+ m_renderView->frameView()->scheduleAnimation();
}
void RenderLayerCompositor::didChangeVisibleRect()
@@ -321,11 +313,6 @@ void RenderLayerCompositor::didChangeVisibleRect()
}
}
-bool RenderLayerCompositor::hasAnyAdditionalCompositedLayers(const RenderLayer* rootLayer) const
-{
- return m_compositedLayerCount > (rootLayer->isComposited() ? 1 : 0);
-}
-
void RenderLayerCompositor::updateCompositingRequirementsState()
{
if (!m_needsUpdateCompositingRequirementsState)
@@ -338,19 +325,15 @@ void RenderLayerCompositor::updateCompositingRequirementsState()
if (!rootRenderLayer() || !rootRenderLayer()->acceleratedCompositingForOverflowScrollEnabled())
return;
- const bool compositorDrivenAcceleratedScrollingEnabled = rootRenderLayer()->compositorDrivenAcceleratedScrollingEnabled();
+ for (HashSet<RenderLayer*>::iterator it = m_outOfFlowPositionedLayers.begin(); it != m_outOfFlowPositionedLayers.end(); ++it)
+ (*it)->updateHasUnclippedDescendant();
const FrameView::ScrollableAreaSet* scrollableAreas = m_renderView->frameView()->scrollableAreas();
- if (!compositorDrivenAcceleratedScrollingEnabled && !scrollableAreas)
+ if (!scrollableAreas)
return;
- for (HashSet<RenderLayer*>::iterator it = m_outOfFlowPositionedLayers.begin(); it != m_outOfFlowPositionedLayers.end(); ++it)
- (*it)->updateHasUnclippedDescendant();
-
- if (!compositorDrivenAcceleratedScrollingEnabled) {
- for (FrameView::ScrollableAreaSet::iterator it = scrollableAreas->begin(); it != scrollableAreas->end(); ++it)
- (*it)->updateNeedsCompositedScrolling();
- }
+ for (FrameView::ScrollableAreaSet::iterator it = scrollableAreas->begin(); it != scrollableAreas->end(); ++it)
+ (*it)->updateNeedsCompositedScrolling();
}
static RenderVideo* findFullscreenVideoRenderer(Document* document)
@@ -370,64 +353,81 @@ static RenderVideo* findFullscreenVideoRenderer(Document* document)
return toRenderVideo(renderer);
}
-void RenderLayerCompositor::updateCompositingLayers(CompositingUpdateType updateType, RenderLayer* updateRoot)
+void RenderLayerCompositor::finishCompositingUpdateForFrameTree(Frame* frame)
+{
+ for (Frame* child = frame->tree().firstChild(); child; child = child->tree().nextSibling())
+ finishCompositingUpdateForFrameTree(child);
+
+ // Update compositing for current frame after all descendant frames are updated.
+ if (frame && frame->contentRenderer()) {
+ RenderLayerCompositor* frameCompositor = frame->contentRenderer()->compositor();
+ if (frameCompositor && !frameCompositor->isMainFrame())
+ frame->contentRenderer()->compositor()->updateCompositingLayers(CompositingUpdateFinishAllDeferredWork);
+ }
+}
+
+void RenderLayerCompositor::updateCompositingLayers(CompositingUpdateType updateType)
{
// Avoid updating the layers with old values. Compositing layers will be updated after the layout is finished.
if (m_renderView->needsLayout())
return;
+ if (updateType == CompositingUpdateFinishAllDeferredWork && isMainFrame() && m_renderView->frameView())
+ finishCompositingUpdateForFrameTree(&m_renderView->frameView()->frame());
+
if (m_forceCompositingMode && !m_compositing)
enableCompositingMode(true);
- if (!m_reevaluateCompositingAfterLayout && !m_compositing)
+ if (!m_needsToRecomputeCompositingRequirements && !m_compositing)
return;
AnimationUpdateBlock animationUpdateBlock(m_renderView->frameView()->frame().animation());
TemporaryChange<bool> postLayoutChange(m_inPostLayoutUpdate, true);
- bool checkForHierarchyUpdate = m_reevaluateCompositingAfterLayout;
+ bool needCompositingRequirementsUpdate = false;
+ bool needHierarchyAndGeometryUpdate = false;
bool needGeometryUpdate = false;
+ bool needsToUpdateScrollingCoordinator = false;
+ // CompositingUpdateFinishAllDeferredWork is the only updateType that will actually do any work in this
+ // function. All other updateTypes will simply mark that something needed updating, and defer the actual
+ // update. This way we only need to compute all compositing state once for every frame drawn (if needed).
switch (updateType) {
case CompositingUpdateAfterStyleChange:
case CompositingUpdateAfterLayout:
- checkForHierarchyUpdate = true;
+ m_needsToRecomputeCompositingRequirements = true;
break;
case CompositingUpdateOnScroll:
- checkForHierarchyUpdate = true; // Overlap can change with scrolling, so need to check for hierarchy updates.
- needGeometryUpdate = true;
+ m_needsToRecomputeCompositingRequirements = true; // Overlap can change with scrolling, so need to check for hierarchy updates.
+ m_needsToUpdateLayerTreeGeometry = true;
break;
case CompositingUpdateOnCompositedScroll:
- needGeometryUpdate = true;
+ m_needsToUpdateLayerTreeGeometry = true;
+ break;
+ case CompositingUpdateFinishAllDeferredWork:
+ needCompositingRequirementsUpdate = m_needsToRecomputeCompositingRequirements;
+ needHierarchyAndGeometryUpdate = m_compositingLayersNeedRebuild;
+ needGeometryUpdate = m_needsToUpdateLayerTreeGeometry;
+ needsToUpdateScrollingCoordinator = scrollingCoordinator() ? scrollingCoordinator()->needsToUpdateAfterCompositingChange() : false;
break;
}
- if (!checkForHierarchyUpdate && !needGeometryUpdate)
+ if (!needCompositingRequirementsUpdate && !needHierarchyAndGeometryUpdate && !needGeometryUpdate && !needsToUpdateScrollingCoordinator)
return;
- bool needHierarchyUpdate = m_compositingLayersNeedRebuild;
- bool isFullUpdate = !updateRoot;
+ ASSERT(updateType == CompositingUpdateFinishAllDeferredWork);
- // Only clear the flag if we're updating the entire hierarchy.
+ // Only clear the flags if we're updating the entire hierarchy.
m_compositingLayersNeedRebuild = false;
- updateRoot = rootRenderLayer();
+ m_needsToUpdateLayerTreeGeometry = false;
+ m_needsToRecomputeCompositingRequirements = false;
+ RenderLayer* updateRoot = rootRenderLayer();
- if (isFullUpdate && updateType == CompositingUpdateAfterLayout)
- m_reevaluateCompositingAfterLayout = false;
-
-#if !LOG_DISABLED
- double startTime = 0;
- if (compositingLogEnabled()) {
- ++m_rootLayerUpdateCount;
- startTime = currentTime();
- }
-#endif
-
- if (checkForHierarchyUpdate) {
+ if (needCompositingRequirementsUpdate) {
// Go through the layers in presentation order, so that we can compute which RenderLayers need compositing layers.
// FIXME: we could maybe do this and the hierarchy udpate in one pass, but the parenting logic would be more complex.
- CompositingState compState(updateRoot, true);
+ CompositingRecursionData recursionData(updateRoot, true);
bool layersChanged = false;
bool saw3DTransform = false;
{
@@ -439,24 +439,27 @@ void RenderLayerCompositor::updateCompositingLayers(CompositingUpdateType update
// should be removed as soon as proper overlap testing based on
// scrolling and animation bounds is implemented (crbug.com/252472).
Vector<RenderLayer*> unclippedDescendants;
- computeCompositingRequirements(0, updateRoot, &overlapTestRequestMap, compState, layersChanged, saw3DTransform, unclippedDescendants);
+ computeCompositingRequirements(0, updateRoot, &overlapTestRequestMap, recursionData, saw3DTransform, unclippedDescendants);
}
- needHierarchyUpdate |= layersChanged;
- }
-#if !LOG_DISABLED
- if (compositingLogEnabled() && isFullUpdate && (needHierarchyUpdate || needGeometryUpdate)) {
- m_obligateCompositedLayerCount = 0;
- m_secondaryCompositedLayerCount = 0;
- m_obligatoryBackingStoreBytes = 0;
- m_secondaryBackingStoreBytes = 0;
+ {
+ TRACE_EVENT0("blink_rendering", "RenderLayerCompositor::assignLayersToBackings");
+ assignLayersToBackings(updateRoot, layersChanged);
+ }
- Frame& frame = m_renderView->frameView()->frame();
- LOG(Compositing, "\nUpdate %d of %s.\n", m_rootLayerUpdateCount, isMainFrame() ? "main frame" : frame.tree()->uniqueName().string().utf8().data());
+ {
+ TRACE_EVENT0("blink_rendering", "RenderLayerCompositor::updateHasVisibleNonLayerContentLoop");
+ const FrameView::ScrollableAreaSet* scrollableAreas = m_renderView->frameView()->scrollableAreas();
+ if (scrollableAreas) {
+ for (FrameView::ScrollableAreaSet::iterator it = scrollableAreas->begin(); it != scrollableAreas->end(); ++it)
+ (*it)->updateHasVisibleNonLayerContent();
+ }
+ }
+
+ needHierarchyAndGeometryUpdate |= layersChanged;
}
-#endif
- if (needHierarchyUpdate) {
+ if (needHierarchyAndGeometryUpdate) {
// Update the hierarchy of the compositing layers.
Vector<GraphicsLayer*> childList;
{
@@ -465,85 +468,60 @@ void RenderLayerCompositor::updateCompositingLayers(CompositingUpdateType update
}
// Host the document layer in the RenderView's root layer.
- if (isFullUpdate) {
- if (RuntimeEnabledFeatures::overlayFullscreenVideoEnabled() && isMainFrame()) {
- RenderVideo* video = findFullscreenVideoRenderer(&m_renderView->document());
- if (video) {
- RenderLayerBacking* backing = video->backing();
- if (backing) {
- childList.clear();
- childList.append(backing->graphicsLayer());
- }
- }
+ if (RuntimeEnabledFeatures::overlayFullscreenVideoEnabled() && isMainFrame()) {
+ RenderVideo* video = findFullscreenVideoRenderer(&m_renderView->document());
+ if (video && video->hasCompositedLayerMapping()) {
+ childList.clear();
+ childList.append(video->compositedLayerMapping()->mainGraphicsLayer());
}
- // Even when childList is empty, don't drop out of compositing mode if there are
- // composited layers that we didn't hit in our traversal (e.g. because of visibility:hidden).
- if (childList.isEmpty() && !hasAnyAdditionalCompositedLayers(updateRoot))
- destroyRootLayer();
- else
- m_rootContentLayer->setChildren(childList);
}
+
+ if (childList.isEmpty())
+ destroyRootLayer();
+ else
+ m_rootContentLayer->setChildren(childList);
} else if (needGeometryUpdate) {
// We just need to do a geometry update. This is only used for position:fixed scrolling;
// most of the time, geometry is updated via RenderLayer::styleChanged().
- updateLayerTreeGeometry(updateRoot, 0);
+ updateLayerTreeGeometry(updateRoot);
}
-#if !LOG_DISABLED
- if (compositingLogEnabled() && isFullUpdate && (needHierarchyUpdate || needGeometryUpdate)) {
- double endTime = currentTime();
- LOG(Compositing, "Total layers primary secondary obligatory backing (KB) secondary backing(KB) total backing (KB) update time (ms)\n");
-
- LOG(Compositing, "%8d %11d %9d %20.2f %22.2f %22.2f %18.2f\n",
- m_obligateCompositedLayerCount + m_secondaryCompositedLayerCount, m_obligateCompositedLayerCount,
- m_secondaryCompositedLayerCount, m_obligatoryBackingStoreBytes / 1024, m_secondaryBackingStoreBytes / 1024, (m_obligatoryBackingStoreBytes + m_secondaryBackingStoreBytes) / 1024, 1000.0 * (endTime - startTime));
- }
-#endif
ASSERT(updateRoot || !m_compositingLayersNeedRebuild);
if (!hasAcceleratedCompositing())
enableCompositingMode(false);
+ // The scrolling coordinator may realize that it needs updating while compositing was being updated in this function.
+ needsToUpdateScrollingCoordinator |= scrollingCoordinator() ? scrollingCoordinator()->needsToUpdateAfterCompositingChange() : false;
+ if (needsToUpdateScrollingCoordinator && isMainFrame() && scrollingCoordinator() && inCompositingMode())
+ scrollingCoordinator()->updateAfterCompositingChange();
+
// Inform the inspector that the layer tree has changed.
- InspectorInstrumentation::layerTreeDidChange(page());
+ if (isMainFrame())
+ InspectorInstrumentation::layerTreeDidChange(page());
}
-void RenderLayerCompositor::layerBecameNonComposited(const RenderLayer* renderLayer)
+static bool requiresCompositing(CompositingReasons reasons)
{
- ASSERT(m_compositedLayerCount > 0);
- --m_compositedLayerCount;
+ // Any reasons other than overlap or assumed overlap will require the layer to be separately compositing.
+ return reasons & ~CompositingReasonComboAllOverlapReasons;
}
-static bool requiresCompositing(CompositingReasons reasons)
+static bool requiresSquashing(CompositingReasons reasons)
{
- return reasons != CompositingReasonNone;
+ // If the layer has overlap or assumed overlap, but no other reasons, then it should be squashed.
+ return !requiresCompositing(reasons) && (reasons & CompositingReasonComboAllOverlapReasons);
}
-#if !LOG_DISABLED
-void RenderLayerCompositor::logLayerInfo(const RenderLayer* layer, int depth)
+static bool requiresCompositingOrSquashing(CompositingReasons reasons)
{
- if (!compositingLogEnabled())
- return;
-
- RenderLayerBacking* backing = layer->backing();
- if (requiresCompositing(directReasonsForCompositing(layer)) || layer->isRootLayer()) {
- ++m_obligateCompositedLayerCount;
- m_obligatoryBackingStoreBytes += backing->backingStoreMemoryEstimate();
- } else {
- ++m_secondaryCompositedLayerCount;
- m_secondaryBackingStoreBytes += backing->backingStoreMemoryEstimate();
- }
-
- String layerName;
#ifndef NDEBUG
- layerName = layer->debugName();
+ bool fastAnswer = reasons != CompositingReasonNone;
+ bool slowAnswer = requiresCompositing(reasons) || requiresSquashing(reasons);
+ ASSERT(fastAnswer == slowAnswer);
#endif
-
- LOG(Compositing, "%*p %dx%d %.2fKB (%s) %s\n", 12 + depth * 2, layer, backing->compositedBounds().width(), backing->compositedBounds().height(),
- backing->backingStoreMemoryEstimate() / 1024,
- logReasonsForCompositing(layer), layerName.utf8().data());
+ return reasons != CompositingReasonNone;
}
-#endif
void RenderLayerCompositor::addOutOfFlowPositionedLayer(RenderLayer* layer)
{
@@ -555,98 +533,113 @@ void RenderLayerCompositor::removeOutOfFlowPositionedLayer(RenderLayer* layer)
m_outOfFlowPositionedLayers.remove(layer);
}
-bool RenderLayerCompositor::updateBacking(RenderLayer* layer, CompositingChangeRepaint shouldRepaint)
+bool RenderLayerCompositor::allocateOrClearCompositedLayerMapping(RenderLayer* layer)
{
- bool layerChanged = false;
+ bool compositedLayerMappingChanged = false;
RenderLayer::ViewportConstrainedNotCompositedReason viewportConstrainedNotCompositedReason = RenderLayer::NoNotCompositedReason;
requiresCompositingForPosition(layer->renderer(), layer, &viewportConstrainedNotCompositedReason);
// FIXME: It would be nice to directly use the layer's compositing reason,
- // but updateBacking() also gets called without having updated compositing
+ // but allocateOrClearCompositedLayerMapping also gets called without having updated compositing
// requirements fully.
- if (needsToBeComposited(layer)) {
+ if (needsOwnBacking(layer)) {
enableCompositingMode();
- if (!layer->backing()) {
- // If we need to repaint, do so before making backing
- if (shouldRepaint == CompositingChangeRepaintNow)
- repaintOnCompositingChange(layer);
+ if (!layer->hasCompositedLayerMapping()) {
+ // If we need to repaint, do so before allocating the compositedLayerMapping
+ repaintOnCompositingChange(layer);
- layer->ensureBacking();
+ layer->ensureCompositedLayerMapping();
+ compositedLayerMappingChanged = true;
// At this time, the ScrollingCooridnator only supports the top-level frame.
- if (layer->isRootLayer() && !isMainFrame()) {
+ if (layer->isRootLayer() && isMainFrame()) {
if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
scrollingCoordinator->frameViewRootLayerDidChange(m_renderView->frameView());
}
+ // If this layer was previously squashed, we need to remove its reference to a groupedMapping right away, so
+ // that computing repaint rects will know the layer's correct compositingState.
+ // FIXME: do we need to also remove the layer from it's location in the squashing list of its groupedMapping?
+ // Need to create a test where a squashed layer pops into compositing. And also to cover all other
+ // sorts of compositingState transitions.
+ layer->setGroupedMapping(0);
+
+ // FIXME: it seems premature to compute this before all compositing state has been updated?
// This layer and all of its descendants have cached repaints rects that are relative to
// the repaint container, so change when compositing changes; we need to update them here.
if (layer->parent())
- layer->computeRepaintRectsIncludingDescendants();
-
- layerChanged = true;
+ layer->repainter().computeRepaintRectsIncludingDescendants();
}
+
+ if (layer->compositedLayerMapping()->updateRequiresOwnBackingStoreForIntrinsicReasons())
+ compositedLayerMappingChanged = true;
} else {
- if (layer->backing()) {
- // If we're removing backing on a reflection, clear the source GraphicsLayer's pointer to
+ if (layer->hasCompositedLayerMapping()) {
+ // If we're removing the compositedLayerMapping from a reflection, clear the source GraphicsLayer's pointer to
// its replica GraphicsLayer. In practice this should never happen because reflectee and reflection
// are both either composited, or not composited.
if (layer->isReflection()) {
RenderLayer* sourceLayer = toRenderLayerModelObject(layer->renderer()->parent())->layer();
- if (RenderLayerBacking* backing = sourceLayer->backing()) {
- ASSERT(backing->graphicsLayer()->replicaLayer() == layer->backing()->graphicsLayer());
- backing->graphicsLayer()->setReplicatedByLayer(0);
+ if (sourceLayer->hasCompositedLayerMapping()) {
+ ASSERT(sourceLayer->compositedLayerMapping()->mainGraphicsLayer()->replicaLayer() == layer->compositedLayerMapping()->mainGraphicsLayer());
+ sourceLayer->compositedLayerMapping()->mainGraphicsLayer()->setReplicatedByLayer(0);
}
}
removeViewportConstrainedLayer(layer);
- layer->clearBacking();
- layerChanged = true;
+ layer->clearCompositedLayerMapping();
+ compositedLayerMappingChanged = true;
// This layer and all of its descendants have cached repaints rects that are relative to
// the repaint container, so change when compositing changes; we need to update them here.
- layer->computeRepaintRectsIncludingDescendants();
+ layer->repainter().computeRepaintRectsIncludingDescendants();
- // If we need to repaint, do so now that we've removed the backing
- if (shouldRepaint == CompositingChangeRepaintNow)
- repaintOnCompositingChange(layer);
+ // If we need to repaint, do so now that we've removed the compositedLayerMapping
+ repaintOnCompositingChange(layer);
}
}
- if (layerChanged && layer->renderer()->isRenderPart()) {
+ if (compositedLayerMappingChanged && layer->renderer()->isRenderPart()) {
RenderLayerCompositor* innerCompositor = frameContentsCompositor(toRenderPart(layer->renderer()));
if (innerCompositor && innerCompositor->inCompositingMode())
innerCompositor->updateRootLayerAttachment();
}
- if (layerChanged)
- layer->clearClipRectsIncludingDescendants(PaintingClipRects);
+ if (compositedLayerMappingChanged)
+ layer->clipper().clearClipRectsIncludingDescendants(PaintingClipRects);
- // If a fixed position layer gained/lost a backing or the reason not compositing it changed,
+ // If a fixed position layer gained/lost a compositedLayerMapping or the reason not compositing it changed,
// the scrolling coordinator needs to recalculate whether it can do fast scrolling.
+ bool nonCompositedReasonChanged = false;
if (layer->renderer()->style()->position() == FixedPosition) {
if (layer->viewportConstrainedNotCompositedReason() != viewportConstrainedNotCompositedReason) {
layer->setViewportConstrainedNotCompositedReason(viewportConstrainedNotCompositedReason);
- layerChanged = true;
+ nonCompositedReasonChanged = true;
}
- if (layerChanged) {
+ if (compositedLayerMappingChanged || nonCompositedReasonChanged) {
if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
scrollingCoordinator->frameViewFixedObjectsDidChange(m_renderView->frameView());
}
}
- return layerChanged;
+ return compositedLayerMappingChanged || nonCompositedReasonChanged;
}
-bool RenderLayerCompositor::updateLayerCompositingState(RenderLayer* layer, CompositingChangeRepaint shouldRepaint)
+bool RenderLayerCompositor::updateLayerCompositingState(RenderLayer* layer)
{
- bool layerChanged = updateBacking(layer, shouldRepaint);
+ updateDirectCompositingReasons(layer);
+ bool layerChanged = allocateOrClearCompositedLayerMapping(layer);
+
+ if (layerSquashingEnabled()) {
+ // FIXME: this is not correct... info may be out of date and squashing returning true doesn't indicate that the layer changed
+ layerChanged = requiresSquashing(layer->compositingReasons());
+ }
// See if we need content or clipping layers. Methods called here should assume
// that the compositing state of descendant layers has not been updated yet.
- if (layer->backing() && layer->backing()->updateGraphicsLayerConfiguration())
+ if (layer->hasCompositedLayerMapping() && layer->compositedLayerMapping()->updateGraphicsLayerConfiguration())
layerChanged = true;
return layerChanged;
@@ -662,7 +655,7 @@ void RenderLayerCompositor::repaintOnCompositingChange(RenderLayer* layer)
if (!repaintContainer)
repaintContainer = m_renderView;
- layer->repaintIncludingNonCompositingDescendants(repaintContainer);
+ layer->repainter().repaintIncludingNonCompositingDescendants(repaintContainer);
}
// This method assumes that layout is up-to-date, unlike repaintOnCompositingChange().
@@ -670,15 +663,21 @@ void RenderLayerCompositor::repaintInCompositedAncestor(RenderLayer* layer, cons
{
RenderLayer* compositedAncestor = layer->enclosingCompositingLayerForRepaint(false /*exclude self*/);
if (compositedAncestor) {
- ASSERT(compositedAncestor->backing());
-
+ // FIXME: make sure repaintRect is computed correctly for squashed scenario
LayoutPoint offset;
layer->convertToLayerCoords(compositedAncestor, offset);
LayoutRect repaintRect = rect;
repaintRect.moveBy(offset);
- compositedAncestor->setBackingNeedsRepaintInRect(repaintRect);
+ if (compositedAncestor->compositingState() == PaintsIntoOwnBacking) {
+ compositedAncestor->repainter().setBackingNeedsRepaintInRect(repaintRect);
+ } else if (compositedAncestor->compositingState() == PaintsIntoGroupedBacking) {
+ // FIXME: Need to perform the correct coordinate conversion for repaintRect here, including transforms
+ compositedAncestor->groupedMapping()->squashingLayer()->setNeedsDisplayInRect(repaintRect);
+ } else {
+ ASSERT_NOT_REACHED();
+ }
}
}
@@ -705,11 +704,11 @@ void RenderLayerCompositor::layerWasAdded(RenderLayer* /*parent*/, RenderLayer*
void RenderLayerCompositor::layerWillBeRemoved(RenderLayer* parent, RenderLayer* child)
{
- if (!child->isComposited() || parent->renderer()->documentBeingDestroyed())
+ if (!child->hasCompositedLayerMapping() || parent->renderer()->documentBeingDestroyed())
return;
removeViewportConstrainedLayer(child);
- repaintInCompositedAncestor(child, child->backing()->compositedBounds());
+ repaintInCompositedAncestor(child, child->compositedLayerMapping()->compositedBounds());
setCompositingParent(child, 0);
setCompositingLayersNeedRebuild();
@@ -718,7 +717,7 @@ void RenderLayerCompositor::layerWillBeRemoved(RenderLayer* parent, RenderLayer*
RenderLayer* RenderLayerCompositor::enclosingNonStackingClippingLayer(const RenderLayer* layer) const
{
for (RenderLayer* curr = layer->parent(); curr != 0; curr = curr->parent()) {
- if (curr->isStackingContainer())
+ if (curr->stackingNode()->isStackingContainer())
return 0;
if (curr->renderer()->hasClipOrOverflowClip())
@@ -742,7 +741,7 @@ void RenderLayerCompositor::addToOverlapMap(OverlapMap& overlapMap, RenderLayer*
boundsComputed = true;
}
- IntRect clipRect = pixelSnappedIntRect(layer->backgroundClipRect(RenderLayer::ClipRectsContext(rootRenderLayer(), 0, AbsoluteClipRects)).rect()); // FIXME: Incorrect for CSS regions.
+ IntRect clipRect = pixelSnappedIntRect(layer->backgroundClipRect(ClipRectsContext(rootRenderLayer(), 0, AbsoluteClipRects)).rect()); // FIXME: Incorrect for CSS regions.
clipRect.intersect(layerBounds);
overlapMap.add(layer, clipRect);
}
@@ -761,36 +760,12 @@ void RenderLayerCompositor::addToOverlapMapRecursive(OverlapMap& overlapMap, Ren
addToOverlapMap(overlapMap, layer, bounds, haveComputedBounds);
#if !ASSERT_DISABLED
- LayerListMutationDetector mutationChecker(layer);
+ LayerListMutationDetector mutationChecker(layer->stackingNode());
#endif
- if (layer->isStackingContainer()) {
- if (Vector<RenderLayer*>* negZOrderList = layer->negZOrderList()) {
- size_t listSize = negZOrderList->size();
- for (size_t i = 0; i < listSize; ++i) {
- RenderLayer* curLayer = negZOrderList->at(i);
- addToOverlapMapRecursive(overlapMap, curLayer, layer);
- }
- }
- }
-
- if (Vector<RenderLayer*>* normalFlowList = layer->normalFlowList()) {
- size_t listSize = normalFlowList->size();
- for (size_t i = 0; i < listSize; ++i) {
- RenderLayer* curLayer = normalFlowList->at(i);
- addToOverlapMapRecursive(overlapMap, curLayer, layer);
- }
- }
-
- if (layer->isStackingContainer()) {
- if (Vector<RenderLayer*>* posZOrderList = layer->posZOrderList()) {
- size_t listSize = posZOrderList->size();
- for (size_t i = 0; i < listSize; ++i) {
- RenderLayer* curLayer = posZOrderList->at(i);
- addToOverlapMapRecursive(overlapMap, curLayer, layer);
- }
- }
- }
+ RenderLayerStackingNodeIterator iterator(*layer->stackingNode(), AllChildren);
+ while (RenderLayerStackingNode* curNode = iterator.next())
+ addToOverlapMapRecursive(overlapMap, curNode->layer(), layer);
if (ancestorLayer)
overlapMap.geometryMap().popMappingsToAncestor(ancestorLayer);
@@ -805,15 +780,16 @@ void RenderLayerCompositor::addToOverlapMapRecursive(OverlapMap& overlapMap, Ren
// must be compositing so that its contents render over that child.
// This implies that its positive z-index children must also be compositing.
//
-void RenderLayerCompositor::computeCompositingRequirements(RenderLayer* ancestorLayer, RenderLayer* layer, OverlapMap* overlapMap, CompositingState& compositingState, bool& layersChanged, bool& descendantHas3DTransform, Vector<RenderLayer*>& unclippedDescendants)
+void RenderLayerCompositor::computeCompositingRequirements(RenderLayer* ancestorLayer, RenderLayer* layer, OverlapMap* overlapMap, CompositingRecursionData& currentRecursionData, bool& descendantHas3DTransform, Vector<RenderLayer*>& unclippedDescendants)
{
- layer->updateLayerListsIfNeeded();
+ layer->stackingNode()->updateLayerListsIfNeeded();
if (overlapMap)
overlapMap->geometryMap().pushMappingsToAncestor(layer, ancestorLayer);
// Clear the flag
layer->setHasCompositingDescendant(false);
+ layer->setHasNonCompositedChild(false);
// Start by assuming this layer will not need to composite.
CompositingReasons reasonsToComposite = CompositingReasonNone;
@@ -825,18 +801,16 @@ void RenderLayerCompositor::computeCompositingRequirements(RenderLayer* ancestor
// RenderLayer children and whose children can't use its backing to render
// into. These children (the controls) always need to be promoted into their
// own layers to draw on top of the accelerated video.
- if (compositingState.m_compositingAncestor && compositingState.m_compositingAncestor->renderer()->isVideo())
+ if (currentRecursionData.m_compositingAncestor && currentRecursionData.m_compositingAncestor->renderer()->isVideo())
directReasons |= CompositingReasonLayerForVideoOverlay;
- if (canBeComposited(layer)) {
+ if (canBeComposited(layer))
reasonsToComposite |= directReasons;
- reasonsToComposite |= (inCompositingMode() && layer->isRootLayer()) ? CompositingReasonRoot : CompositingReasonNone;
- }
// Next, accumulate reasons related to overlap.
// If overlap testing is used, this reason will be overridden. If overlap testing is not
// used, we must assume we overlap if there is anything composited behind us in paint-order.
- CompositingReasons overlapCompositingReason = compositingState.m_subtreeIsCompositing ? CompositingReasonAssumedOverlap : CompositingReasonNone;
+ CompositingReasons overlapCompositingReason = currentRecursionData.m_subtreeIsCompositing ? CompositingReasonAssumedOverlap : CompositingReasonNone;
if (rootRenderLayer()->compositorDrivenAcceleratedScrollingEnabled()) {
Vector<size_t> unclippedDescendantsToRemove;
@@ -866,7 +840,7 @@ void RenderLayerCompositor::computeCompositingRequirements(RenderLayer* ancestor
bool haveComputedBounds = false;
IntRect absBounds;
// If we know for sure the layer is going to be composited, don't bother looking it up in the overlap map.
- if (overlapMap && !overlapMap->isEmpty() && compositingState.m_testingOverlap && !requiresCompositing(directReasons)) {
+ if (overlapMap && !overlapMap->isEmpty() && currentRecursionData.m_testingOverlap && !requiresCompositingOrSquashing(directReasons)) {
// If we're testing for overlap, we only need to composite if we overlap something that is already composited.
absBounds = enclosingIntRect(overlapMap->geometryMap().absoluteRect(layer->overlapBounds()));
@@ -882,15 +856,15 @@ void RenderLayerCompositor::computeCompositingRequirements(RenderLayer* ancestor
// The children of this layer don't need to composite, unless there is
// a compositing layer among them, so start by inheriting the compositing
// ancestor with m_subtreeIsCompositing set to false.
- CompositingState childState(compositingState);
- childState.m_subtreeIsCompositing = false;
+ CompositingRecursionData childRecursionData(currentRecursionData);
+ childRecursionData.m_subtreeIsCompositing = false;
- bool willBeComposited = canBeComposited(layer) && requiresCompositing(reasonsToComposite);
+ bool willBeComposited = canBeComposited(layer) && requiresCompositingOrSquashing(reasonsToComposite);
if (willBeComposited) {
// Tell the parent it has compositing descendants.
- compositingState.m_subtreeIsCompositing = true;
+ currentRecursionData.m_subtreeIsCompositing = true;
// This layer now acts as the ancestor for kids.
- childState.m_compositingAncestor = layer;
+ childRecursionData.m_compositingAncestor = layer;
// Here we know that all children and the layer's own contents can blindly paint into
// this layer's backing, until a descendant is composited. So, we don't need to check
@@ -899,47 +873,44 @@ void RenderLayerCompositor::computeCompositingRequirements(RenderLayer* ancestor
overlapMap->beginNewOverlapTestingContext();
// This layer is going to be composited, so children can safely ignore the fact that there's an
// animation running behind this layer, meaning they can rely on the overlap map testing again.
- childState.m_testingOverlap = true;
+ childRecursionData.m_testingOverlap = true;
}
#if !ASSERT_DISABLED
- LayerListMutationDetector mutationChecker(layer);
+ LayerListMutationDetector mutationChecker(layer->stackingNode());
#endif
bool anyDescendantHas3DTransform = false;
bool willHaveForegroundLayer = false;
- if (layer->isStackingContainer()) {
- if (Vector<RenderLayer*>* negZOrderList = layer->negZOrderList()) {
- size_t listSize = negZOrderList->size();
- for (size_t i = 0; i < listSize; ++i) {
- RenderLayer* curLayer = negZOrderList->at(i);
- computeCompositingRequirements(layer, curLayer, overlapMap, childState, layersChanged, anyDescendantHas3DTransform, unclippedDescendants);
-
- // If we have to make a layer for this child, make one now so we can have a contents layer
- // (since we need to ensure that the -ve z-order child renders underneath our contents).
- if (childState.m_subtreeIsCompositing) {
- reasonsToComposite |= CompositingReasonNegativeZIndexChildren;
-
- if (!willBeComposited) {
- // make layer compositing
- childState.m_compositingAncestor = layer;
+ if (layer->stackingNode()->isStackingContainer()) {
+ RenderLayerStackingNodeIterator iterator(*layer->stackingNode(), NegativeZOrderChildren);
+ while (RenderLayerStackingNode* curNode = iterator.next()) {
+ computeCompositingRequirements(layer, curNode->layer(), overlapMap, childRecursionData, anyDescendantHas3DTransform, unclippedDescendants);
+
+ // If we have to make a layer for this child, make one now so we can have a contents layer
+ // (since we need to ensure that the -ve z-order child renders underneath our contents).
+ if (childRecursionData.m_subtreeIsCompositing) {
+ reasonsToComposite |= CompositingReasonNegativeZIndexChildren;
+
+ if (!willBeComposited) {
+ // make layer compositing
+ childRecursionData.m_compositingAncestor = layer;
+ overlapMap->beginNewOverlapTestingContext();
+ willBeComposited = true;
+ willHaveForegroundLayer = true;
+
+ // FIXME: temporary solution for the first negative z-index composited child:
+ // re-compute the absBounds for the child so that we can add the
+ // negative z-index child's bounds to the new overlap context.
+ if (overlapMap) {
+ overlapMap->geometryMap().pushMappingsToAncestor(curNode->layer(), layer);
+ IntRect childAbsBounds = enclosingIntRect(overlapMap->geometryMap().absoluteRect(curNode->layer()->overlapBounds()));
+ bool boundsComputed = true;
overlapMap->beginNewOverlapTestingContext();
- willBeComposited = true;
- willHaveForegroundLayer = true;
-
- // FIXME: temporary solution for the first negative z-index composited child:
- // re-compute the absBounds for the child so that we can add the
- // negative z-index child's bounds to the new overlap context.
- if (overlapMap) {
- overlapMap->geometryMap().pushMappingsToAncestor(curLayer, layer);
- IntRect childAbsBounds = enclosingIntRect(overlapMap->geometryMap().absoluteRect(curLayer->overlapBounds()));
- bool boundsComputed = true;
- overlapMap->beginNewOverlapTestingContext();
- addToOverlapMap(*overlapMap, curLayer, childAbsBounds, boundsComputed);
- overlapMap->finishCurrentOverlapTestingContext();
- overlapMap->geometryMap().popMappingsToAncestor(layer);
- }
+ addToOverlapMap(*overlapMap, curNode->layer(), childAbsBounds, boundsComputed);
+ overlapMap->finishCurrentOverlapTestingContext();
+ overlapMap->geometryMap().popMappingsToAncestor(layer);
}
}
}
@@ -956,26 +927,12 @@ void RenderLayerCompositor::computeCompositingRequirements(RenderLayer* ancestor
overlapMap->beginNewOverlapTestingContext();
// This layer is going to be composited, so children can safely ignore the fact that there's an
// animation running behind this layer, meaning they can rely on the overlap map testing again
- childState.m_testingOverlap = true;
- }
-
- if (Vector<RenderLayer*>* normalFlowList = layer->normalFlowList()) {
- size_t listSize = normalFlowList->size();
- for (size_t i = 0; i < listSize; ++i) {
- RenderLayer* curLayer = normalFlowList->at(i);
- computeCompositingRequirements(layer, curLayer, overlapMap, childState, layersChanged, anyDescendantHas3DTransform, unclippedDescendants);
- }
+ childRecursionData.m_testingOverlap = true;
}
- if (layer->isStackingContainer()) {
- if (Vector<RenderLayer*>* posZOrderList = layer->posZOrderList()) {
- size_t listSize = posZOrderList->size();
- for (size_t i = 0; i < listSize; ++i) {
- RenderLayer* curLayer = posZOrderList->at(i);
- computeCompositingRequirements(layer, curLayer, overlapMap, childState, layersChanged, anyDescendantHas3DTransform, unclippedDescendants);
- }
- }
- }
+ RenderLayerStackingNodeIterator iterator(*layer->stackingNode(), NormalFlowChildren | PositiveZOrderChildren);
+ while (RenderLayerStackingNode* curNode = iterator.next())
+ computeCompositingRequirements(layer, curNode->layer(), overlapMap, childRecursionData, anyDescendantHas3DTransform, unclippedDescendants);
// Now that the subtree has been traversed, we can check for compositing reasons that depended on the state of the subtree.
@@ -986,16 +943,23 @@ void RenderLayerCompositor::computeCompositingRequirements(RenderLayer* ancestor
}
// All layers (even ones that aren't being composited) need to get added to
- // the overlap map. Layers that do not composite will draw into their
+ // the overlap map. Layers that are not separately composited will paint into their
// compositing ancestor's backing, and so are still considered for overlap.
- if (overlapMap && childState.m_compositingAncestor && !childState.m_compositingAncestor->isRootLayer())
+ if (overlapMap && childRecursionData.m_compositingAncestor && !childRecursionData.m_compositingAncestor->isRootLayer())
addToOverlapMap(*overlapMap, layer, absBounds, haveComputedBounds);
+ if (layer->stackingNode()->isStackingContext()) {
+ layer->setShouldIsolateCompositedDescendants(childRecursionData.m_hasUnisolatedCompositedBlendingDescendant);
+ } else {
+ layer->setShouldIsolateCompositedDescendants(false);
+ currentRecursionData.m_hasUnisolatedCompositedBlendingDescendant = childRecursionData.m_hasUnisolatedCompositedBlendingDescendant;
+ }
+
// Now check for reasons to become composited that depend on the state of descendant layers.
- CompositingReasons subtreeCompositingReasons = subtreeReasonsForCompositing(layer->renderer(), childState.m_subtreeIsCompositing, anyDescendantHas3DTransform);
+ CompositingReasons subtreeCompositingReasons = subtreeReasonsForCompositing(layer->renderer(), childRecursionData.m_subtreeIsCompositing, anyDescendantHas3DTransform);
reasonsToComposite |= subtreeCompositingReasons;
- if (!willBeComposited && canBeComposited(layer) && requiresCompositing(subtreeCompositingReasons)) {
- childState.m_compositingAncestor = layer;
+ if (!willBeComposited && canBeComposited(layer) && requiresCompositingOrSquashing(subtreeCompositingReasons)) {
+ childRecursionData.m_compositingAncestor = layer;
if (overlapMap) {
// FIXME: this context push is effectively a no-op but needs to exist for
// now, because the code is designed to push overlap information to the
@@ -1007,49 +971,50 @@ void RenderLayerCompositor::computeCompositingRequirements(RenderLayer* ancestor
}
// If the original layer is composited, the reflection needs to be, too.
- if (layer->reflectionLayer()) {
+ if (layer->reflectionInfo()) {
// FIXME: Shouldn't we call computeCompositingRequirements to handle a reflection overlapping with another renderer?
CompositingReasons reflectionCompositingReason = willBeComposited ? CompositingReasonReflectionOfCompositedParent : CompositingReasonNone;
- layer->reflectionLayer()->setCompositingReasons(layer->reflectionLayer()->compositingReasons() | reflectionCompositingReason);
+ layer->reflectionInfo()->reflectionLayer()->setCompositingReasons(layer->reflectionInfo()->reflectionLayer()->compositingReasons() | reflectionCompositingReason);
}
// Subsequent layers in the parent's stacking context may also need to composite.
- if (childState.m_subtreeIsCompositing)
- compositingState.m_subtreeIsCompositing = true;
+ if (childRecursionData.m_subtreeIsCompositing)
+ currentRecursionData.m_subtreeIsCompositing = true;
- // Set the flag to say that this SC has compositing children.
- layer->setHasCompositingDescendant(childState.m_subtreeIsCompositing);
+ if (willBeComposited && layer->hasBlendMode())
+ currentRecursionData.m_hasUnisolatedCompositedBlendingDescendant = true;
+ // Set the flag to say that this SC has compositing children.
+ layer->setHasCompositingDescendant(childRecursionData.m_subtreeIsCompositing);
// Turn overlap testing off for later layers if it's already off, or if we have an animating transform.
// Note that if the layer clips its descendants, there's no reason to propagate the child animation to the parent layers. That's because
// we know for sure the animation is contained inside the clipping rectangle, which is already added to the overlap map.
bool isCompositedClippingLayer = canBeComposited(layer) && (reasonsToComposite & CompositingReasonClipsCompositingDescendants);
- if ((!childState.m_testingOverlap && !isCompositedClippingLayer) || isRunningAcceleratedTransformAnimation(layer->renderer()))
- compositingState.m_testingOverlap = false;
+ if ((!childRecursionData.m_testingOverlap && !isCompositedClippingLayer) || isRunningAcceleratedTransformAnimation(layer->renderer()))
+ currentRecursionData.m_testingOverlap = false;
- if (overlapMap && childState.m_compositingAncestor == layer && !layer->isRootLayer())
+ if (overlapMap && childRecursionData.m_compositingAncestor == layer && !layer->isRootLayer())
overlapMap->finishCurrentOverlapTestingContext();
- // If we're back at the root, and no other layers need to be composited, and the root layer itself doesn't need
- // to be composited, then we can drop out of compositing mode altogether. However, don't drop out of compositing mode
- // if there are composited layers that we didn't hit in our traversal (e.g. because of visibility:hidden).
- // FIXME: hasAnyAdditionalCompositedLayers() code seems fishy. We need to make root layer logic more obvious.
- if (layer->isRootLayer() && !childState.m_subtreeIsCompositing && !requiresCompositing(directReasons) && !m_forceCompositingMode && !hasAnyAdditionalCompositedLayers(layer)) {
- enableCompositingMode(false);
- willBeComposited = false;
- reasonsToComposite = CompositingReasonNone;
+ if (layer->isRootLayer()) {
+ // The root layer needs to be composited if anything else in the tree is composited.
+ // Otherwise, we can disable compositing entirely.
+ if (childRecursionData.m_subtreeIsCompositing || requiresCompositingOrSquashing(reasonsToComposite) || m_forceCompositingMode) {
+ willBeComposited = true;
+ reasonsToComposite |= CompositingReasonRoot;
+ } else {
+ enableCompositingMode(false);
+ willBeComposited = false;
+ reasonsToComposite = CompositingReasonNone;
+ }
}
// At this point we have finished collecting all reasons to composite this layer.
layer->setCompositingReasons(reasonsToComposite);
- // Update backing now, so that we can use isComposited() reliably during tree traversal in rebuildCompositingLayerTree().
- if (updateBacking(layer, CompositingChangeRepaintNow))
- layersChanged = true;
-
- if (layer->reflectionLayer() && updateLayerCompositingState(layer->reflectionLayer(), CompositingChangeRepaintNow))
- layersChanged = true;
+ if (!willBeComposited && layer->parent())
+ layer->parent()->setHasNonCompositedChild(true);
descendantHas3DTransform |= anyDescendantHas3DTransform || layer->has3DTransform();
@@ -1057,31 +1022,116 @@ void RenderLayerCompositor::computeCompositingRequirements(RenderLayer* ancestor
overlapMap->geometryMap().popMappingsToAncestor(ancestorLayer);
}
+void RenderLayerCompositor::SquashingState::updateSquashingStateForNewMapping(CompositedLayerMappingPtr newCompositedLayerMapping, bool hasNewCompositedLayerMapping, IntPoint newOffsetFromAbsolute)
+{
+ // The most recent backing is done accumulating any more squashing layers.
+ if (hasMostRecentMapping)
+ mostRecentMapping->finishAccumulatingSquashingLayers(nextSquashedLayerIndex);
+
+ nextSquashedLayerIndex = 0;
+ mostRecentMapping = newCompositedLayerMapping;
+ hasMostRecentMapping = hasNewCompositedLayerMapping;
+ offsetFromAbsolute = newOffsetFromAbsolute;
+}
+
+static IntPoint computeOffsetFromAbsolute(RenderLayer* layer)
+{
+ TransformState transformState(TransformState::ApplyTransformDirection, FloatPoint());
+ layer->renderer()->mapLocalToContainer(0, transformState, ApplyContainerFlip);
+ transformState.flatten();
+ return roundedIntPoint(transformState.lastPlanarPoint());
+}
+
+void RenderLayerCompositor::assignLayersToBackings(RenderLayer* updateRoot, bool& layersChanged)
+{
+ SquashingState squashingState;
+ assignLayersToBackingsInternal(updateRoot, squashingState, layersChanged);
+ if (squashingState.hasMostRecentMapping)
+ squashingState.mostRecentMapping->finishAccumulatingSquashingLayers(squashingState.nextSquashedLayerIndex);
+}
+
+void RenderLayerCompositor::assignLayersToBackingsInternal(RenderLayer* layer, SquashingState& squashingState, bool& layersChanged)
+{
+ if (allocateOrClearCompositedLayerMapping(layer))
+ layersChanged = true;
+
+ if (layer->reflectionInfo() && updateLayerCompositingState(layer->reflectionInfo()->reflectionLayer()))
+ layersChanged = true;
+
+ // Add this layer to a squashing backing if needed.
+ if (layerSquashingEnabled()) {
+ // NOTE: In the future as we generalize this, the background of this layer may need to be assigned to a different backing than
+ // the layer's own primary contents. This would happen when we have a composited negative z-index element that needs to
+ // paint on top of the background, but below the layer's main contents. For now, because we always composite layers
+ // when they have a composited negative z-index child, such layers will never need squashing so it is not yet an issue.
+ if (requiresSquashing(layer->compositingReasons())) {
+ // A layer that is squashed with other layers cannot have its own CompositedLayerMapping.
+ ASSERT(!layer->hasCompositedLayerMapping());
+ ASSERT(squashingState.hasMostRecentMapping);
+
+ IntPoint offsetFromAbsolute = computeOffsetFromAbsolute(layer);
+
+ // FIXME: see if we can refactor this to be clearer
+ IntSize offsetFromTargetBacking(offsetFromAbsolute.x() - squashingState.offsetFromAbsolute.x(),
+ offsetFromAbsolute.y() - squashingState.offsetFromAbsolute.y());
+
+ squashingState.mostRecentMapping->addRenderLayerToSquashingGraphicsLayer(layer, offsetFromTargetBacking, squashingState.nextSquashedLayerIndex);
+ squashingState.nextSquashedLayerIndex++;
+
+ // FIXME: does this need to be true here? Do we need more logic to decide when it should be true?
+ layersChanged = true;
+
+ // FIXME: this should be conditioned on whether this layer actually changed status
+ layer->clipper().clearClipRectsIncludingDescendants();
+ }
+ }
+
+ if (layer->stackingNode()->isStackingContainer()) {
+ RenderLayerStackingNodeIterator iterator(*layer->stackingNode(), NegativeZOrderChildren);
+ while (RenderLayerStackingNode* curNode = iterator.next())
+ assignLayersToBackingsInternal(curNode->layer(), squashingState, layersChanged);
+ }
+
+ if (layerSquashingEnabled()) {
+ // At this point, if the layer is to be "separately" composited, then its backing becomes the most recent in paint-order.
+ if (layer->compositingState() == PaintsIntoOwnBacking || layer->compositingState() == HasOwnBackingButPaintsIntoAncestor) {
+ ASSERT(!requiresSquashing(layer->compositingReasons()));
+ IntPoint offsetFromAbsolute = computeOffsetFromAbsolute(layer);
+ squashingState.updateSquashingStateForNewMapping(layer->compositedLayerMapping(), layer->hasCompositedLayerMapping(), offsetFromAbsolute);
+ }
+ }
+
+ RenderLayerStackingNodeIterator iterator(*layer->stackingNode(), NormalFlowChildren | PositiveZOrderChildren);
+ while (RenderLayerStackingNode* curNode = iterator.next())
+ assignLayersToBackingsInternal(curNode->layer(), squashingState, layersChanged);
+}
+
void RenderLayerCompositor::setCompositingParent(RenderLayer* childLayer, RenderLayer* parentLayer)
{
ASSERT(!parentLayer || childLayer->ancestorCompositingLayer() == parentLayer);
- ASSERT(childLayer->isComposited());
+ ASSERT(childLayer->hasCompositedLayerMapping());
// It's possible to be called with a parent that isn't yet composited when we're doing
// partial updates as required by painting or hit testing. Just bail in that case;
// we'll do a full layer update soon.
- if (!parentLayer || !parentLayer->isComposited())
+ if (!parentLayer || !parentLayer->hasCompositedLayerMapping())
return;
if (parentLayer) {
- GraphicsLayer* hostingLayer = parentLayer->backing()->parentForSublayers();
- GraphicsLayer* hostedLayer = childLayer->backing()->childForSuperlayers();
+ GraphicsLayer* hostingLayer = parentLayer->compositedLayerMapping()->parentForSublayers();
+ GraphicsLayer* hostedLayer = childLayer->compositedLayerMapping()->childForSuperlayers();
hostingLayer->addChild(hostedLayer);
- } else
- childLayer->backing()->childForSuperlayers()->removeFromParent();
+ } else {
+ childLayer->compositedLayerMapping()->childForSuperlayers()->removeFromParent();
+ }
}
void RenderLayerCompositor::removeCompositedChildren(RenderLayer* layer)
{
- ASSERT(layer->isComposited());
+ ASSERT(layer->hasCompositedLayerMapping());
- GraphicsLayer* hostingLayer = layer->backing()->parentForSublayers();
+ GraphicsLayer* hostingLayer = layer->compositedLayerMapping()->parentForSublayers();
hostingLayer->removeAllChildren();
}
@@ -1099,6 +1149,8 @@ void RenderLayerCompositor::rebuildCompositingLayerTree(RenderLayer* layer, Vect
// Note that we can only do work here that is independent of whether the descendant layers
// have been processed. computeCompositingRequirements() will already have done the repaint if necessary.
+ layer->stackingNode()->updateLayerListsIfNeeded();
+
// Used for gathering UMA data about the effect on memory usage of promoting all layers
// that have a webkit-transition on opacity or transform and intersect the viewport.
static double pixelsWithoutPromotingAllTransitions = 0.0;
@@ -1109,30 +1161,27 @@ void RenderLayerCompositor::rebuildCompositingLayerTree(RenderLayer* layer, Vect
pixelsAddedByPromotingAllTransitions = 0.0;
}
- RenderLayerBacking* layerBacking = layer->backing();
- if (layerBacking) {
+ const bool hasCompositedLayerMapping = layer->hasCompositedLayerMapping();
+ CompositedLayerMappingPtr currentCompositedLayerMapping = layer->compositedLayerMapping();
+ if (hasCompositedLayerMapping) {
// The compositing state of all our children has been updated already, so now
// we can compute and cache the composited bounds for this layer.
- layerBacking->updateCompositedBounds();
+ currentCompositedLayerMapping->updateCompositedBounds();
- if (RenderLayer* reflection = layer->reflectionLayer()) {
- if (reflection->backing())
- reflection->backing()->updateCompositedBounds();
+ if (layer->reflectionInfo()) {
+ RenderLayer* reflectionLayer = layer->reflectionInfo()->reflectionLayer();
+ if (reflectionLayer->hasCompositedLayerMapping())
+ reflectionLayer->compositedLayerMapping()->updateCompositedBounds();
}
- layerBacking->updateGraphicsLayerConfiguration();
- layerBacking->updateGraphicsLayerGeometry();
+ currentCompositedLayerMapping->updateGraphicsLayerConfiguration();
+ currentCompositedLayerMapping->updateGraphicsLayerGeometry();
if (!layer->parent())
updateRootLayerPosition();
-#if !LOG_DISABLED
- logLayerInfo(layer, depth);
-#else
- UNUSED_PARAM(depth);
-#endif
- if (layerBacking->hasUnpositionedOverflowControlsLayers())
- layer->positionNewlyCreatedOverflowControls();
+ if (currentCompositedLayerMapping->hasUnpositionedOverflowControlsLayers())
+ layer->scrollableArea()->positionOverflowControls();
pixelsWithoutPromotingAllTransitions += layer->size().height() * layer->size().width();
} else {
@@ -1142,80 +1191,62 @@ void RenderLayerCompositor::rebuildCompositingLayerTree(RenderLayer* layer, Vect
pixelsAddedByPromotingAllTransitions += layer->size().height() * layer->size().width();
}
- // If this layer has backing, then we are collecting its children, otherwise appending
- // to the compositing child list of an enclosing layer.
+ // If this layer has a compositedLayerMapping, then that is where we place subsequent children GraphicsLayers.
+ // Otherwise children continue to append to the child list of the enclosing layer.
Vector<GraphicsLayer*> layerChildren;
- Vector<GraphicsLayer*>& childList = layerBacking ? layerChildren : childLayersOfEnclosingLayer;
+ Vector<GraphicsLayer*>& childList = hasCompositedLayerMapping ? layerChildren : childLayersOfEnclosingLayer;
#if !ASSERT_DISABLED
- LayerListMutationDetector mutationChecker(layer);
+ LayerListMutationDetector mutationChecker(layer->stackingNode());
#endif
- if (layer->isStackingContainer()) {
- if (Vector<RenderLayer*>* negZOrderList = layer->negZOrderList()) {
- size_t listSize = negZOrderList->size();
- for (size_t i = 0; i < listSize; ++i) {
- RenderLayer* curLayer = negZOrderList->at(i);
- rebuildCompositingLayerTree(curLayer, childList, depth + 1);
- }
- }
+ if (layer->stackingNode()->isStackingContainer()) {
+ RenderLayerStackingNodeIterator iterator(*layer->stackingNode(), NegativeZOrderChildren);
+ while (RenderLayerStackingNode* curNode = iterator.next())
+ rebuildCompositingLayerTree(curNode->layer(), childList, depth + 1);
// If a negative z-order child is compositing, we get a foreground layer which needs to get parented.
- if (layerBacking && layerBacking->foregroundLayer())
- childList.append(layerBacking->foregroundLayer());
- }
-
- if (Vector<RenderLayer*>* normalFlowList = layer->normalFlowList()) {
- size_t listSize = normalFlowList->size();
- for (size_t i = 0; i < listSize; ++i) {
- RenderLayer* curLayer = normalFlowList->at(i);
- rebuildCompositingLayerTree(curLayer, childList, depth + 1);
- }
+ if (hasCompositedLayerMapping && currentCompositedLayerMapping->foregroundLayer())
+ childList.append(currentCompositedLayerMapping->foregroundLayer());
}
- if (layer->isStackingContainer()) {
- if (Vector<RenderLayer*>* posZOrderList = layer->posZOrderList()) {
- size_t listSize = posZOrderList->size();
- for (size_t i = 0; i < listSize; ++i) {
- RenderLayer* curLayer = posZOrderList->at(i);
- rebuildCompositingLayerTree(curLayer, childList, depth + 1);
- }
- }
- }
+ RenderLayerStackingNodeIterator iterator(*layer->stackingNode(), NormalFlowChildren | PositiveZOrderChildren);
+ while (RenderLayerStackingNode* curNode = iterator.next())
+ rebuildCompositingLayerTree(curNode->layer(), childList, depth + 1);
- if (layerBacking) {
+ if (hasCompositedLayerMapping) {
bool parented = false;
if (layer->renderer()->isRenderPart())
parented = parentFrameContentLayers(toRenderPart(layer->renderer()));
if (!parented)
- layerBacking->parentForSublayers()->setChildren(layerChildren);
+ currentCompositedLayerMapping->parentForSublayers()->setChildren(layerChildren);
// If the layer has a clipping layer the overflow controls layers will be siblings of the clipping layer.
// Otherwise, the overflow control layers are normal children.
- if (!layerBacking->hasClippingLayer() && !layerBacking->hasScrollingLayer()) {
- if (GraphicsLayer* overflowControlLayer = layerBacking->layerForHorizontalScrollbar()) {
+ if (!currentCompositedLayerMapping->hasClippingLayer() && !currentCompositedLayerMapping->hasScrollingLayer()) {
+ if (GraphicsLayer* overflowControlLayer = currentCompositedLayerMapping->layerForHorizontalScrollbar()) {
overflowControlLayer->removeFromParent();
- layerBacking->parentForSublayers()->addChild(overflowControlLayer);
+ currentCompositedLayerMapping->parentForSublayers()->addChild(overflowControlLayer);
}
- if (GraphicsLayer* overflowControlLayer = layerBacking->layerForVerticalScrollbar()) {
+ if (GraphicsLayer* overflowControlLayer = currentCompositedLayerMapping->layerForVerticalScrollbar()) {
overflowControlLayer->removeFromParent();
- layerBacking->parentForSublayers()->addChild(overflowControlLayer);
+ currentCompositedLayerMapping->parentForSublayers()->addChild(overflowControlLayer);
}
- if (GraphicsLayer* overflowControlLayer = layerBacking->layerForScrollCorner()) {
+ if (GraphicsLayer* overflowControlLayer = currentCompositedLayerMapping->layerForScrollCorner()) {
overflowControlLayer->removeFromParent();
- layerBacking->parentForSublayers()->addChild(overflowControlLayer);
+ currentCompositedLayerMapping->parentForSublayers()->addChild(overflowControlLayer);
}
}
- childLayersOfEnclosingLayer.append(layerBacking->childForSuperlayers());
+ childLayersOfEnclosingLayer.append(currentCompositedLayerMapping->childForSuperlayers());
}
if (!depth) {
int percentageIncreaseInPixels = static_cast<int>(pixelsAddedByPromotingAllTransitions / pixelsWithoutPromotingAllTransitions * 100);
- HistogramSupport::histogramCustomCounts("Renderer.PixelIncreaseFromTransitions", percentageIncreaseInPixels, 0, 1000, 50);
+ blink::Platform::current()->histogramCustomCounts("Renderer.PixelIncreaseFromTransitions", percentageIncreaseInPixels, 0, 1000, 50);
}
}
@@ -1233,11 +1264,6 @@ void RenderLayerCompositor::frameViewDidChangeSize()
frameViewDidScroll();
updateOverflowControlsLayers();
-
-#if USE(RUBBER_BANDING)
- if (m_layerForOverhangAreas)
- m_layerForOverhangAreas->setSize(frameView->frameRect().size());
-#endif
}
}
@@ -1273,14 +1299,14 @@ void RenderLayerCompositor::frameViewDidScroll()
m_scrollLayer->setPosition(-scrollPosition);
- HistogramSupport::histogramEnumeration("Renderer.AcceleratedFixedRootBackground",
+ blink::Platform::current()->histogramEnumeration("Renderer.AcceleratedFixedRootBackground",
ScrolledMainFrameBucket,
AcceleratedFixedRootBackgroundHistogramMax);
if (!m_renderView->rootBackgroundIsEntirelyFixed())
return;
- HistogramSupport::histogramEnumeration("Renderer.AcceleratedFixedRootBackground",
+ blink::Platform::current()->histogramEnumeration("Renderer.AcceleratedFixedRootBackground",
!!fixedRootBackgroundLayer()
? ScrolledMainFrameWithAcceleratedFixedRootBackground
: ScrolledMainFrameWithUnacceleratedFixedRootBackground,
@@ -1291,6 +1317,12 @@ void RenderLayerCompositor::frameViewDidLayout()
{
}
+void RenderLayerCompositor::frameViewScrollbarsExistenceDidChange()
+{
+ if (m_containerLayer)
+ updateOverflowControlsLayers();
+}
+
void RenderLayerCompositor::rootFixedBackgroundsChanged()
{
if (!supportsFixedRootBackgroundCompositing())
@@ -1322,7 +1354,8 @@ bool RenderLayerCompositor::scrollingLayerDidChange(RenderLayer* layer)
String RenderLayerCompositor::layerTreeAsText(LayerTreeFlags flags)
{
- updateCompositingLayers(CompositingUpdateAfterLayout);
+ // Before dumping the layer tree, finish any pending compositing update.
+ updateCompositingLayers(CompositingUpdateFinishAllDeferredWork);
if (!m_rootContentLayer)
return String();
@@ -1338,11 +1371,8 @@ String RenderLayerCompositor::layerTreeAsText(LayerTreeFlags flags)
// The true root layer is not included in the dump, so if we want to report
// its repaint rects, they must be included here.
- if (flags & LayerTreeIncludesRepaintRects) {
- String layerTreeTextWithRootRepaintRects = m_renderView->frameView()->trackedRepaintRectsAsText();
- layerTreeTextWithRootRepaintRects.append(layerTreeText);
- return layerTreeTextWithRootRepaintRects;
- }
+ if (flags & LayerTreeIncludesRepaintRects)
+ return m_renderView->frameView()->trackedRepaintRectsAsText() + layerTreeText;
return layerTreeText;
}
@@ -1367,11 +1397,11 @@ bool RenderLayerCompositor::parentFrameContentLayers(RenderPart* renderer)
return false;
RenderLayer* layer = renderer->layer();
- if (!layer->isComposited())
+ if (!layer->hasCompositedLayerMapping())
return false;
- RenderLayerBacking* backing = layer->backing();
- GraphicsLayer* hostingLayer = backing->parentForSublayers();
+ CompositedLayerMappingPtr compositedLayerMapping = layer->compositedLayerMapping();
+ GraphicsLayer* hostingLayer = compositedLayerMapping->parentForSublayers();
GraphicsLayer* rootLayer = innerCompositor->rootGraphicsLayer();
if (hostingLayer->children().size() != 1 || hostingLayer->children()[0] != rootLayer) {
hostingLayer->removeAllChildren();
@@ -1381,107 +1411,69 @@ bool RenderLayerCompositor::parentFrameContentLayers(RenderPart* renderer)
}
// This just updates layer geometry without changing the hierarchy.
-void RenderLayerCompositor::updateLayerTreeGeometry(RenderLayer* layer, int depth)
+void RenderLayerCompositor::updateLayerTreeGeometry(RenderLayer* layer)
{
- if (RenderLayerBacking* layerBacking = layer->backing()) {
+ if (layer->hasCompositedLayerMapping()) {
+ CompositedLayerMappingPtr compositedLayerMapping = layer->compositedLayerMapping();
// The compositing state of all our children has been updated already, so now
// we can compute and cache the composited bounds for this layer.
- layerBacking->updateCompositedBounds();
+ compositedLayerMapping->updateCompositedBounds();
- if (RenderLayer* reflection = layer->reflectionLayer()) {
- if (reflection->backing())
- reflection->backing()->updateCompositedBounds();
+ if (layer->reflectionInfo()) {
+ RenderLayer* reflectionLayer = layer->reflectionInfo()->reflectionLayer();
+ if (reflectionLayer->hasCompositedLayerMapping())
+ reflectionLayer->compositedLayerMapping()->updateCompositedBounds();
}
- layerBacking->updateGraphicsLayerConfiguration();
- layerBacking->updateGraphicsLayerGeometry();
+ compositedLayerMapping->updateGraphicsLayerConfiguration();
+ compositedLayerMapping->updateGraphicsLayerGeometry();
if (!layer->parent())
updateRootLayerPosition();
-
-#if !LOG_DISABLED
- logLayerInfo(layer, depth);
-#else
- UNUSED_PARAM(depth);
-#endif
}
#if !ASSERT_DISABLED
- LayerListMutationDetector mutationChecker(layer);
+ LayerListMutationDetector mutationChecker(layer->stackingNode());
#endif
- if (layer->isStackingContainer()) {
- if (Vector<RenderLayer*>* negZOrderList = layer->negZOrderList()) {
- size_t listSize = negZOrderList->size();
- for (size_t i = 0; i < listSize; ++i)
- updateLayerTreeGeometry(negZOrderList->at(i), depth + 1);
- }
- }
-
- if (Vector<RenderLayer*>* normalFlowList = layer->normalFlowList()) {
- size_t listSize = normalFlowList->size();
- for (size_t i = 0; i < listSize; ++i)
- updateLayerTreeGeometry(normalFlowList->at(i), depth + 1);
- }
-
- if (layer->isStackingContainer()) {
- if (Vector<RenderLayer*>* posZOrderList = layer->posZOrderList()) {
- size_t listSize = posZOrderList->size();
- for (size_t i = 0; i < listSize; ++i)
- updateLayerTreeGeometry(posZOrderList->at(i), depth + 1);
- }
- }
+ RenderLayerStackingNodeIterator iterator(*layer->stackingNode(), AllChildren);
+ while (RenderLayerStackingNode* curNode = iterator.next())
+ updateLayerTreeGeometry(curNode->layer());
}
// Recurs down the RenderLayer tree until its finds the compositing descendants of compositingAncestor and updates their geometry.
-void RenderLayerCompositor::updateCompositingDescendantGeometry(RenderLayer* compositingAncestor, RenderLayer* layer, bool compositedChildrenOnly)
+void RenderLayerCompositor::updateCompositingDescendantGeometry(RenderLayerStackingNode* compositingAncestor, RenderLayer* layer, bool compositedChildrenOnly)
{
- if (layer != compositingAncestor) {
- if (RenderLayerBacking* layerBacking = layer->backing()) {
- layerBacking->updateCompositedBounds();
+ if (layer->stackingNode() != compositingAncestor) {
+ if (layer->hasCompositedLayerMapping()) {
+ CompositedLayerMappingPtr compositedLayerMapping = layer->compositedLayerMapping();
+ compositedLayerMapping->updateCompositedBounds();
- if (RenderLayer* reflection = layer->reflectionLayer()) {
- if (reflection->backing())
- reflection->backing()->updateCompositedBounds();
+ if (layer->reflectionInfo()) {
+ RenderLayer* reflectionLayer = layer->reflectionInfo()->reflectionLayer();
+ if (reflectionLayer->hasCompositedLayerMapping())
+ reflectionLayer->compositedLayerMapping()->updateCompositedBounds();
}
- layerBacking->updateGraphicsLayerGeometry();
+ compositedLayerMapping->updateGraphicsLayerGeometry();
if (compositedChildrenOnly)
return;
}
}
- if (layer->reflectionLayer())
- updateCompositingDescendantGeometry(compositingAncestor, layer->reflectionLayer(), compositedChildrenOnly);
+ if (layer->reflectionInfo())
+ updateCompositingDescendantGeometry(compositingAncestor, layer->reflectionInfo()->reflectionLayer(), compositedChildrenOnly);
if (!layer->hasCompositingDescendant())
return;
#if !ASSERT_DISABLED
- LayerListMutationDetector mutationChecker(layer);
+ LayerListMutationDetector mutationChecker(layer->stackingNode());
#endif
- if (layer->isStackingContainer()) {
- if (Vector<RenderLayer*>* negZOrderList = layer->negZOrderList()) {
- size_t listSize = negZOrderList->size();
- for (size_t i = 0; i < listSize; ++i)
- updateCompositingDescendantGeometry(compositingAncestor, negZOrderList->at(i), compositedChildrenOnly);
- }
- }
-
- if (Vector<RenderLayer*>* normalFlowList = layer->normalFlowList()) {
- size_t listSize = normalFlowList->size();
- for (size_t i = 0; i < listSize; ++i)
- updateCompositingDescendantGeometry(compositingAncestor, normalFlowList->at(i), compositedChildrenOnly);
- }
-
- if (layer->isStackingContainer()) {
- if (Vector<RenderLayer*>* posZOrderList = layer->posZOrderList()) {
- size_t listSize = posZOrderList->size();
- for (size_t i = 0; i < listSize; ++i)
- updateCompositingDescendantGeometry(compositingAncestor, posZOrderList->at(i), compositedChildrenOnly);
- }
- }
+ RenderLayerStackingNodeIterator iterator(*layer->stackingNode(), AllChildren);
+ while (RenderLayerStackingNode* curNode = iterator.next())
+ updateCompositingDescendantGeometry(compositingAncestor, curNode->layer(), compositedChildrenOnly);
}
@@ -1493,54 +1485,28 @@ void RenderLayerCompositor::repaintCompositedLayers(const IntRect* absRect)
void RenderLayerCompositor::recursiveRepaintLayer(RenderLayer* layer, const IntRect* rect)
{
// FIXME: This method does not work correctly with transforms.
- if (layer->isComposited() && !layer->backing()->paintsIntoCompositedAncestor()) {
+ if (layer->compositingState() == PaintsIntoOwnBacking) {
if (rect)
- layer->setBackingNeedsRepaintInRect(*rect);
+ layer->repainter().setBackingNeedsRepaintInRect(*rect);
else
- layer->setBackingNeedsRepaint();
+ layer->repainter().setBackingNeedsRepaint();
}
#if !ASSERT_DISABLED
- LayerListMutationDetector mutationChecker(layer);
+ LayerListMutationDetector mutationChecker(layer->stackingNode());
#endif
- if (layer->hasCompositingDescendant()) {
- if (Vector<RenderLayer*>* negZOrderList = layer->negZOrderList()) {
- size_t listSize = negZOrderList->size();
- for (size_t i = 0; i < listSize; ++i) {
- RenderLayer* curLayer = negZOrderList->at(i);
- if (rect) {
- IntRect childRect(*rect);
- curLayer->convertToPixelSnappedLayerCoords(layer, childRect);
- recursiveRepaintLayer(curLayer, &childRect);
- } else
- recursiveRepaintLayer(curLayer);
- }
- }
-
- if (Vector<RenderLayer*>* posZOrderList = layer->posZOrderList()) {
- size_t listSize = posZOrderList->size();
- for (size_t i = 0; i < listSize; ++i) {
- RenderLayer* curLayer = posZOrderList->at(i);
- if (rect) {
- IntRect childRect(*rect);
- curLayer->convertToPixelSnappedLayerCoords(layer, childRect);
- recursiveRepaintLayer(curLayer, &childRect);
- } else
- recursiveRepaintLayer(curLayer);
- }
- }
- }
- if (Vector<RenderLayer*>* normalFlowList = layer->normalFlowList()) {
- size_t listSize = normalFlowList->size();
- for (size_t i = 0; i < listSize; ++i) {
- RenderLayer* curLayer = normalFlowList->at(i);
- if (rect) {
- IntRect childRect(*rect);
- curLayer->convertToPixelSnappedLayerCoords(layer, childRect);
- recursiveRepaintLayer(curLayer, &childRect);
- } else
- recursiveRepaintLayer(curLayer);
+ unsigned childrenToVisit = NormalFlowChildren;
+ if (layer->hasCompositingDescendant())
+ childrenToVisit |= PositiveZOrderChildren | NegativeZOrderChildren;
+ RenderLayerStackingNodeIterator iterator(*layer->stackingNode(), childrenToVisit);
+ while (RenderLayerStackingNode* curNode = iterator.next()) {
+ if (rect) {
+ IntRect childRect(*rect);
+ curNode->layer()->convertToPixelSnappedLayerCoords(layer, childRect);
+ recursiveRepaintLayer(curNode->layer(), &childRect);
+ } else {
+ recursiveRepaintLayer(curNode->layer());
}
}
}
@@ -1581,23 +1547,23 @@ void RenderLayerCompositor::setIsInWindow(bool isInWindow)
}
}
-void RenderLayerCompositor::clearBackingForLayerIncludingDescendants(RenderLayer* layer)
+void RenderLayerCompositor::clearMappingForRenderLayerIncludingDescendants(RenderLayer* layer)
{
if (!layer)
return;
- if (layer->isComposited()) {
+ if (layer->hasCompositedLayerMapping()) {
removeViewportConstrainedLayer(layer);
- layer->clearBacking();
+ layer->clearCompositedLayerMapping();
}
for (RenderLayer* currLayer = layer->firstChild(); currLayer; currLayer = currLayer->nextSibling())
- clearBackingForLayerIncludingDescendants(currLayer);
+ clearMappingForRenderLayerIncludingDescendants(currLayer);
}
-void RenderLayerCompositor::clearBackingForAllLayers()
+void RenderLayerCompositor::clearMappingForAllRenderLayers()
{
- clearBackingForLayerIncludingDescendants(m_renderView->layer());
+ clearMappingForRenderLayerIncludingDescendants(m_renderView->layer());
}
void RenderLayerCompositor::updateRootLayerPosition()
@@ -1608,7 +1574,7 @@ void RenderLayerCompositor::updateRootLayerPosition()
m_rootContentLayer->setPosition(documentRect.location());
#if USE(RUBBER_BANDING)
if (m_layerForOverhangShadow)
- ScrollbarTheme::theme()->updateOverhangShadowLayer(m_layerForOverhangShadow.get(), m_rootContentLayer.get());
+ OverscrollTheme::theme()->updateOverhangShadowLayer(m_layerForOverhangShadow.get(), m_rootContentLayer.get());
#endif
}
if (m_containerLayer) {
@@ -1622,12 +1588,24 @@ bool RenderLayerCompositor::has3DContent() const
return layerHas3DContent(rootRenderLayer());
}
-bool RenderLayerCompositor::needsToBeComposited(const RenderLayer* layer) const
+void RenderLayerCompositor::updateDirectCompositingReasons(RenderLayer* layer)
+{
+ CompositingReasons layerReasons = layer->compositingReasons();
+
+ layerReasons &= ~CompositingReasonComboAllDirectReasons;
+ layerReasons |= directReasonsForCompositing(layer);
+ layer->setCompositingReasons(layerReasons);
+}
+
+bool RenderLayerCompositor::needsOwnBacking(const RenderLayer* layer) const
{
if (!canBeComposited(layer))
return false;
- return requiresCompositing(directReasonsForCompositing(layer)) || requiresCompositing(layer->compositingReasons()) || (inCompositingMode() && layer->isRootLayer());
+ // If squashing is disabled, then layers that would have been squashed should just be separately composited.
+ bool needsOwnBackingForDisabledSquashing = !layerSquashingEnabled() && requiresSquashing(layer->compositingReasons());
+
+ return requiresCompositing(layer->compositingReasons()) || needsOwnBackingForDisabledSquashing || (inCompositingMode() && layer->isRootLayer());
}
bool RenderLayerCompositor::canBeComposited(const RenderLayer* layer) const
@@ -1637,47 +1615,6 @@ bool RenderLayerCompositor::canBeComposited(const RenderLayer* layer) const
return m_hasAcceleratedCompositing && layer->isSelfPaintingLayer() && layer->renderer()->flowThreadState() == RenderObject::NotInsideFlowThread;
}
-bool RenderLayerCompositor::requiresOwnBackingStore(const RenderLayer* layer, const RenderLayer* compositingAncestorLayer) const
-{
- RenderObject* renderer = layer->renderer();
- if (compositingAncestorLayer
- && !(compositingAncestorLayer->backing()->graphicsLayer()->drawsContent()
- || compositingAncestorLayer->backing()->paintsIntoCompositedAncestor()))
- return true;
-
- if (layer->isRootLayer()
- || layer->transform() // note: excludes perspective and transformStyle3D.
- || requiresCompositingForVideo(renderer)
- || requiresCompositingForCanvas(renderer)
- || requiresCompositingForPlugin(renderer)
- || requiresCompositingForFrame(renderer)
- || requiresCompositingForBackfaceVisibilityHidden(renderer)
- || requiresCompositingForAnimation(renderer)
- || requiresCompositingForTransition(renderer)
- || requiresCompositingForFilters(renderer)
- || requiresCompositingForBlending(renderer)
- || requiresCompositingForPosition(renderer, layer)
- || requiresCompositingForOverflowScrolling(layer)
- || requiresCompositingForOverflowScrollingParent(layer)
- || requiresCompositingForOutOfFlowClipping(layer)
- || renderer->isTransparent()
- || renderer->hasMask()
- || renderer->hasReflection()
- || renderer->hasFilter())
- return true;
-
- CompositingReasons indirectReasonsThatNeedBacking = CompositingReasonOverlap
- | CompositingReasonAssumedOverlap
- | CompositingReasonNegativeZIndexChildren
- | CompositingReasonTransformWithCompositedDescendants
- | CompositingReasonOpacityWithCompositedDescendants
- | CompositingReasonMaskWithCompositedDescendants
- | CompositingReasonFilterWithCompositedDescendants
- | CompositingReasonBlendingWithCompositedDescendants
- | CompositingReasonPreserve3D; // preserve-3d has to create backing store to ensure that 3d-transformed elements intersect.
- return layer->compositingReasons() & indirectReasonsThatNeedBacking;
-}
-
CompositingReasons RenderLayerCompositor::directReasonsForCompositing(const RenderLayer* layer) const
{
RenderObject* renderer = layer->renderer();
@@ -1714,9 +1651,6 @@ CompositingReasons RenderLayerCompositor::directReasonsForCompositing(const Rend
if (requiresCompositingForOverflowScrolling(layer))
directReasons |= CompositingReasonOverflowScrollingTouch;
- if (requiresCompositingForBlending(renderer))
- directReasons |= CompositingReasonBlending;
-
if (requiresCompositingForOverflowScrollingParent(layer))
directReasons |= CompositingReasonOverflowScrollingParent;
@@ -1726,94 +1660,6 @@ CompositingReasons RenderLayerCompositor::directReasonsForCompositing(const Rend
return directReasons;
}
-CompositingReasons RenderLayerCompositor::reasonsForCompositing(const RenderLayer* layer) const
-{
- CompositingReasons reasons = CompositingReasonNone;
-
- if (!layer || !layer->isComposited())
- return reasons;
-
- return layer->compositingReasons();
-}
-
-#if !LOG_DISABLED
-const char* RenderLayerCompositor::logReasonsForCompositing(const RenderLayer* layer)
-{
- CompositingReasons reasons = reasonsForCompositing(layer);
-
- if (reasons & CompositingReason3DTransform)
- return "3D transform";
-
- if (reasons & CompositingReasonVideo)
- return "video";
- else if (reasons & CompositingReasonCanvas)
- return "canvas";
- else if (reasons & CompositingReasonPlugin)
- return "plugin";
- else if (reasons & CompositingReasonIFrame)
- return "iframe";
-
- if (reasons & CompositingReasonBackfaceVisibilityHidden)
- return "backface-visibility: hidden";
-
- if (reasons & CompositingReasonClipsCompositingDescendants)
- return "clips compositing descendants";
-
- if (reasons & CompositingReasonAnimation)
- return "animation";
-
- if (reasons & CompositingReasonFilters)
- return "filters";
-
- if (reasons & CompositingReasonPositionFixed)
- return "position: fixed";
-
- if (reasons & CompositingReasonPositionSticky)
- return "position: sticky";
-
- if (reasons & CompositingReasonOverflowScrollingTouch)
- return "-webkit-overflow-scrolling: touch";
-
- if (reasons & CompositingReasonAssumedOverlap)
- return "stacking";
-
- if (reasons & CompositingReasonOverlap)
- return "overlap";
-
- if (reasons & CompositingReasonNegativeZIndexChildren)
- return "negative z-index children";
-
- if (reasons & CompositingReasonTransformWithCompositedDescendants)
- return "transform with composited descendants";
-
- if (reasons & CompositingReasonOpacityWithCompositedDescendants)
- return "opacity with composited descendants";
-
- if (reasons & CompositingReasonMaskWithCompositedDescendants)
- return "mask with composited descendants";
-
- if (reasons & CompositingReasonReflectionWithCompositedDescendants)
- return "reflection with composited descendants";
-
- if (reasons & CompositingReasonFilterWithCompositedDescendants)
- return "filter with composited descendants";
-
- if (reasons & CompositingReasonBlendingWithCompositedDescendants)
- return "blending with composited descendants";
-
- if (reasons & CompositingReasonPerspective)
- return "perspective";
-
- if (reasons & CompositingReasonPreserve3D)
- return "preserve-3d";
-
- if (reasons & CompositingReasonRoot)
- return "root";
-
- return "";
-}
-#endif
-
// Return true if the given layer has some ancestor in the RenderLayer hierarchy that clips,
// up to the enclosing compositing ancestor. This is required because compositing layers are parented
// according to the z-order hierarchy, yet clipping goes down the renderer hierarchy.
@@ -1821,9 +1667,10 @@ const char* RenderLayerCompositor::logReasonsForCompositing(const RenderLayer* l
// but a sibling in the z-order hierarchy.
bool RenderLayerCompositor::clippedByAncestor(const RenderLayer* layer) const
{
- if (!layer->isComposited() || !layer->parent())
+ if (!layer->hasCompositedLayerMapping() || !layer->parent())
return false;
+ // FIXME: need to double-check if semantics of ancestorCompositingLayer() work correctly here?
const RenderLayer* compositingAncestor = layer->ancestorCompositingLayer();
if (!compositingAncestor)
return false;
@@ -1845,7 +1692,7 @@ bool RenderLayerCompositor::clippedByAncestor(const RenderLayer* layer) const
if (!computeClipRoot || computeClipRoot == layer)
return false;
- return layer->backgroundClipRect(RenderLayer::ClipRectsContext(computeClipRoot, 0, TemporaryClipRects)).rect() != PaintInfo::infiniteRect(); // FIXME: Incorrect for CSS regions.
+ return layer->backgroundClipRect(ClipRectsContext(computeClipRoot, 0, TemporaryClipRects)).rect() != PaintInfo::infiniteRect(); // FIXME: Incorrect for CSS regions.
}
// Return true if the given layer is a stacking context and has compositing child
@@ -1906,12 +1753,7 @@ bool RenderLayerCompositor::requiresCompositingForCanvas(RenderObject* renderer)
if (renderer->isCanvas()) {
HTMLCanvasElement* canvas = toHTMLCanvasElement(renderer->node());
-#if USE(COMPOSITING_FOR_SMALL_CANVASES)
- bool isCanvasLargeEnoughToForceCompositing = true;
-#else
- bool isCanvasLargeEnoughToForceCompositing = canvas->size().area() >= canvasAreaThresholdRequiringCompositing;
-#endif
- return canvas->renderingContext() && canvas->renderingContext()->isAccelerated() && (canvas->renderingContext()->is3d() || isCanvasLargeEnoughToForceCompositing);
+ return canvas->renderingContext() && canvas->renderingContext()->isAccelerated();
}
return false;
}
@@ -1925,12 +1767,13 @@ bool RenderLayerCompositor::requiresCompositingForPlugin(RenderObject* renderer)
if (!composite)
return false;
- m_reevaluateCompositingAfterLayout = true;
+ // FIXME: this seems bogus. If we don't know the layout position/size of the plugin yet, would't that be handled elsewhere?
+ m_needsToRecomputeCompositingRequirements = true;
RenderWidget* pluginRenderer = toRenderWidget(renderer);
// If we can't reliably know the size of the plugin yet, don't change compositing state.
if (pluginRenderer->needsLayout())
- return pluginRenderer->hasLayer() && pluginRenderer->layer()->isComposited();
+ return pluginRenderer->hasLayer() && pluginRenderer->layer()->hasCompositedLayerMapping();
// Don't go into compositing mode if height or width are zero, or size is 1x1.
IntRect contentBox = pixelSnappedIntRect(pluginRenderer->contentBoxRect());
@@ -1947,7 +1790,11 @@ bool RenderLayerCompositor::requiresCompositingForFrame(RenderObject* renderer)
if (!frameRenderer->requiresAcceleratedCompositing())
return false;
- m_reevaluateCompositingAfterLayout = true;
+ if (frameRenderer->node() && frameRenderer->node()->isFrameOwnerElement() && toHTMLFrameOwnerElement(frameRenderer->node())->contentFrame() && toHTMLFrameOwnerElement(frameRenderer->node())->contentFrame()->remotePlatformLayer())
+ return true;
+
+ // FIXME: this seems bogus. If we don't know the layout position/size of the frame yet, wouldn't that be handled elsehwere?
+ m_needsToRecomputeCompositingRequirements = true;
RenderLayerCompositor* innerCompositor = frameContentsCompositor(frameRenderer);
if (!innerCompositor)
@@ -1955,7 +1802,7 @@ bool RenderLayerCompositor::requiresCompositingForFrame(RenderObject* renderer)
// If we can't reliably know the size of the iframe yet, don't change compositing state.
if (renderer->needsLayout())
- return frameRenderer->hasLayer() && frameRenderer->layer()->isComposited();
+ return frameRenderer->hasLayer() && frameRenderer->layer()->hasCompositedLayerMapping();
// Don't go into compositing mode if height or width are zero.
IntRect contentBox = pixelSnappedIntRect(frameRenderer->contentBoxRect());
@@ -1972,9 +1819,10 @@ bool RenderLayerCompositor::requiresCompositingForAnimation(RenderObject* render
if (!(m_compositingTriggers & ChromeClient::AnimationTrigger))
return false;
- if (AnimationController* animController = renderer->animation())
- return animController->isRunningAcceleratableAnimationOnRenderer(renderer);
- return false;
+ if (!RuntimeEnabledFeatures::webAnimationsCSSEnabled())
+ return renderer->animation().isRunningAcceleratableAnimationOnRenderer(renderer);
+
+ return shouldCompositeForActiveAnimations(*renderer);
}
bool RenderLayerCompositor::requiresCompositingForTransition(RenderObject* renderer) const
@@ -2005,6 +1853,11 @@ CompositingReasons RenderLayerCompositor::subtreeReasonsForCompositing(RenderObj
if (layer->transform())
subtreeReasons |= CompositingReasonTransformWithCompositedDescendants;
+ if (layer->shouldIsolateCompositedDescendants()) {
+ ASSERT(layer->stackingNode()->isStackingContext());
+ subtreeReasons |= CompositingReasonIsolateCompositedDescendants;
+ }
+
// If the implementation of createsGroup changes, we need to be aware of that in this part of code.
ASSERT((renderer->isTransparent() || renderer->hasMask() || renderer->hasFilter() || renderer->hasBlendMode()) == renderer->createsGroup());
if (renderer->isTransparent())
@@ -2045,11 +1898,6 @@ bool RenderLayerCompositor::requiresCompositingForFilters(RenderObject* renderer
return renderer->hasFilter();
}
-bool RenderLayerCompositor::requiresCompositingForBlending(RenderObject* renderer) const
-{
- return renderer->hasBlendMode();
-}
-
bool RenderLayerCompositor::requiresCompositingForOverflowScrollingParent(const RenderLayer* layer) const
{
return !!layer->scrollParent();
@@ -2070,7 +1918,7 @@ bool RenderLayerCompositor::requiresCompositingForPosition(RenderObject* rendere
EPosition position = renderer->style()->position();
bool isFixed = renderer->isOutOfFlowPositioned() && position == FixedPosition;
- if (isFixed && !layer->isStackingContainer())
+ if (isFixed && !layer->stackingNode()->isStackingContainer())
return false;
bool isSticky = renderer->isInFlowPositioned() && position == StickyPosition;
@@ -2089,7 +1937,7 @@ bool RenderLayerCompositor::requiresCompositingForPosition(RenderObject* rendere
RenderObject* container = renderer->container();
// If the renderer is not hooked up yet then we have to wait until it is.
if (!container) {
- m_reevaluateCompositingAfterLayout = true;
+ m_needsToRecomputeCompositingRequirements = true;
return false;
}
@@ -2129,8 +1977,8 @@ bool RenderLayerCompositor::requiresCompositingForPosition(RenderObject* rendere
// Subsequent tests depend on layout. If we can't tell now, just keep things the way they are until layout is done.
if (!m_inPostLayoutUpdate) {
- m_reevaluateCompositingAfterLayout = true;
- return layer->isComposited();
+ m_needsToRecomputeCompositingRequirements = true;
+ return layer->hasCompositedLayerMapping();
}
bool paintsContent = layer->isVisuallyNonEmpty() || layer->hasVisibleDescendant();
@@ -2143,12 +1991,16 @@ bool RenderLayerCompositor::requiresCompositingForPosition(RenderObject* rendere
// Fixed position elements that are invisible in the current view don't get their own layer.
if (FrameView* frameView = m_renderView->frameView()) {
LayoutRect viewBounds = frameView->viewportConstrainedVisibleContentRect();
- LayoutRect layerBounds = layer->calculateLayerBounds(rootRenderLayer(), 0, RenderLayer::DefaultCalculateLayerBoundsFlags
- | RenderLayer::ExcludeHiddenDescendants | RenderLayer::DontConstrainForMask | RenderLayer::IncludeCompositedDescendants);
+ LayoutRect layerBounds = layer->calculateLayerBounds(rootRenderLayer(), 0,
+ RenderLayer::DefaultCalculateLayerBoundsFlags
+ | RenderLayer::ExcludeHiddenDescendants
+ | RenderLayer::DontConstrainForMask
+ | RenderLayer::IncludeCompositedDescendants
+ | RenderLayer::PretendLayerHasOwnBacking);
if (!viewBounds.intersects(enclosingIntRect(layerBounds))) {
if (viewportConstrainedNotCompositedReason) {
*viewportConstrainedNotCompositedReason = RenderLayer::NotCompositedForBoundsOutOfView;
- m_reevaluateCompositingAfterLayout = true;
+ m_needsToRecomputeCompositingRequirements = true;
}
return false;
}
@@ -2166,11 +2018,9 @@ bool RenderLayerCompositor::isRunningAcceleratedTransformAnimation(RenderObject*
{
if (!(m_compositingTriggers & ChromeClient::AnimationTrigger))
return false;
-
- if (AnimationController* animController = renderer->animation())
- return animController->isRunningAnimationOnRenderer(renderer, CSSPropertyWebkitTransform);
-
- return false;
+ if (!RuntimeEnabledFeatures::webAnimationsCSSEnabled())
+ return renderer->animation().isRunningAnimationOnRenderer(renderer, CSSPropertyWebkitTransform);
+ return hasActiveAnimations(*renderer, CSSPropertyWebkitTransform);
}
// If an element has negative z-index children, those children render in front of the
@@ -2178,7 +2028,7 @@ bool RenderLayerCompositor::isRunningAcceleratedTransformAnimation(RenderObject*
// object.
bool RenderLayerCompositor::needsContentsCompositingLayer(const RenderLayer* layer) const
{
- return layer->hasNegativeZOrderList();
+ return layer->stackingNode()->hasNegativeZOrderList();
}
static void paintScrollbar(Scrollbar* scrollbar, GraphicsContext& context, const IntRect& clip)
@@ -2209,11 +2059,6 @@ void RenderLayerCompositor::paintContents(const GraphicsLayer* graphicsLayer, Gr
transformedClip.moveBy(scrollCorner.location());
m_renderView->frameView()->paintScrollCorner(&context, transformedClip);
context.restore();
-#if USE(RUBBER_BANDING)
- } else if (graphicsLayer == layerForOverhangAreas()) {
- ScrollView* view = m_renderView->frameView();
- view->calculateAndPaintOverhangBackground(&context, clip);
-#endif
}
}
@@ -2236,13 +2081,13 @@ bool RenderLayerCompositor::needsFixedRootBackgroundLayer(const RenderLayer* lay
GraphicsLayer* RenderLayerCompositor::fixedRootBackgroundLayer() const
{
- // Get the fixed root background from the RenderView layer's backing.
+ // Get the fixed root background from the RenderView layer's compositedLayerMapping.
RenderLayer* viewLayer = m_renderView->layer();
if (!viewLayer)
return 0;
- if (viewLayer->isComposited() && viewLayer->backing()->backgroundLayerPaintsFixedRootBackground())
- return viewLayer->backing()->backgroundLayer();
+ if (viewLayer->compositingState() == PaintsIntoOwnBacking && viewLayer->compositedLayerMapping()->backgroundLayerPaintsFixedRootBackground())
+ return viewLayer->compositedLayerMapping()->backgroundLayer();
return 0;
}
@@ -2262,6 +2107,9 @@ static void resetTrackedRepaintRectsRecursive(GraphicsLayer* graphicsLayer)
if (GraphicsLayer* maskLayer = graphicsLayer->maskLayer())
resetTrackedRepaintRectsRecursive(maskLayer);
+
+ if (GraphicsLayer* clippingMaskLayer = graphicsLayer->contentsClippingMaskLayer())
+ resetTrackedRepaintRectsRecursive(clippingMaskLayer);
}
void RenderLayerCompositor::resetTrackedRepaintRects()
@@ -2272,6 +2120,7 @@ void RenderLayerCompositor::resetTrackedRepaintRects()
void RenderLayerCompositor::setTracksRepaints(bool tracksRepaints)
{
+ updateCompositingLayers(CompositingUpdateFinishAllDeferredWork);
m_isTrackingRepaints = tracksRepaints;
}
@@ -2334,26 +2183,13 @@ void RenderLayerCompositor::updateOverflowControlsLayers()
{
#if USE(RUBBER_BANDING)
if (requiresOverhangLayers()) {
- if (!m_layerForOverhangAreas) {
- m_layerForOverhangAreas = GraphicsLayer::create(graphicsLayerFactory(), this);
- m_layerForOverhangAreas->setDrawsContent(false);
- m_layerForOverhangAreas->setSize(m_renderView->frameView()->frameRect().size());
-
- // We want the overhang areas layer to be positioned below the frame contents,
- // so insert it below the clip layer.
- m_overflowControlsHostLayer->addChildBelow(m_layerForOverhangAreas.get(), m_containerLayer.get());
- }
if (!m_layerForOverhangShadow) {
m_layerForOverhangShadow = GraphicsLayer::create(graphicsLayerFactory(), this);
- ScrollbarTheme::theme()->setUpOverhangShadowLayer(m_layerForOverhangShadow.get());
- ScrollbarTheme::theme()->updateOverhangShadowLayer(m_layerForOverhangShadow.get(), m_rootContentLayer.get());
+ OverscrollTheme::theme()->setUpOverhangShadowLayer(m_layerForOverhangShadow.get());
+ OverscrollTheme::theme()->updateOverhangShadowLayer(m_layerForOverhangShadow.get(), m_rootContentLayer.get());
m_scrollLayer->addChild(m_layerForOverhangShadow.get());
}
} else {
- if (m_layerForOverhangAreas) {
- m_layerForOverhangAreas->removeFromParent();
- m_layerForOverhangAreas = nullptr;
- }
if (m_layerForOverhangShadow) {
m_layerForOverhangShadow->removeFromParent();
m_layerForOverhangShadow = nullptr;
@@ -2429,12 +2265,14 @@ void RenderLayerCompositor::ensureRootLayer()
// Create a layer to host the clipping layer and the overflow controls layers.
m_overflowControlsHostLayer = GraphicsLayer::create(graphicsLayerFactory(), this);
- // Create a clipping layer if this is an iframe
+ // Create a clipping layer if this is an iframe or settings require to clip.
m_containerLayer = GraphicsLayer::create(graphicsLayerFactory(), this);
-#if OS(ANDROID)
- if (!isMainFrame())
-#endif
- m_containerLayer->setMasksToBounds(true);
+ bool containerMasksToBounds = !isMainFrame();
+ if (Settings* settings = m_renderView->document().settings()) {
+ if (settings->mainFrameClipsContent())
+ containerMasksToBounds = true;
+ }
+ m_containerLayer->setMasksToBounds(containerMasksToBounds);
m_scrollLayer = GraphicsLayer::create(graphicsLayerFactory(), this);
if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
@@ -2464,10 +2302,6 @@ void RenderLayerCompositor::destroyRootLayer()
detachRootLayer();
#if USE(RUBBER_BANDING)
- if (m_layerForOverhangAreas) {
- m_layerForOverhangAreas->removeFromParent();
- m_layerForOverhangAreas = nullptr;
- }
if (m_layerForOverhangShadow) {
m_layerForOverhangShadow->removeFromParent();
m_layerForOverhangShadow = nullptr;
@@ -2524,7 +2358,7 @@ void RenderLayerCompositor::attachRootLayer(RootLayerAttachment attachment)
break;
}
case RootLayerAttachedViaEnclosingFrame: {
- // The layer will get hooked up via RenderLayerBacking::updateGraphicsLayerConfiguration()
+ // The layer will get hooked up via CompositedLayerMapping::updateGraphicsLayerConfiguration()
// for the frame's renderer in the parent document.
m_renderView->document().ownerElement()->scheduleLayerUpdate();
break;
@@ -2541,7 +2375,7 @@ void RenderLayerCompositor::detachRootLayer()
switch (m_rootLayerAttachment) {
case RootLayerAttachedViaEnclosingFrame: {
- // The layer will get unhooked up via RenderLayerBacking::updateGraphicsLayerConfiguration()
+ // The layer will get unhooked up via CompositedLayerMapping::updateGraphicsLayerConfiguration()
// for the frame's renderer in the parent document.
if (m_overflowControlsHostLayer)
m_overflowControlsHostLayer->removeFromParent();
@@ -2574,6 +2408,7 @@ void RenderLayerCompositor::updateRootLayerAttachment()
bool RenderLayerCompositor::isMainFrame() const
{
+ // FIXME: Frame::isMainFrame() is probably better.
return !m_renderView->document().ownerElement();
}
@@ -2586,7 +2421,7 @@ void RenderLayerCompositor::notifyIFramesOfCompositingChange()
return;
Frame& frame = m_renderView->frameView()->frame();
- for (Frame* child = frame.tree()->firstChild(); child; child = child->tree()->traverseNext(&frame)) {
+ for (Frame* child = frame.tree().firstChild(); child; child = child->tree().traverseNext(&frame)) {
if (child->document() && child->document()->ownerElement())
child->document()->ownerElement()->scheduleLayerUpdate();
}
@@ -2600,6 +2435,7 @@ void RenderLayerCompositor::notifyIFramesOfCompositingChange()
bool RenderLayerCompositor::layerHas3DContent(const RenderLayer* layer) const
{
const RenderStyle* style = layer->renderer()->style();
+ RenderLayerStackingNode* stackingNode = const_cast<RenderLayer*>(layer)->stackingNode();
if (style &&
(style->transformStyle3D() == TransformStyle3DPreserve3D ||
@@ -2607,40 +2443,18 @@ bool RenderLayerCompositor::layerHas3DContent(const RenderLayer* layer) const
style->transform().has3DOperation()))
return true;
- const_cast<RenderLayer*>(layer)->updateLayerListsIfNeeded();
+ stackingNode->updateLayerListsIfNeeded();
#if !ASSERT_DISABLED
- LayerListMutationDetector mutationChecker(const_cast<RenderLayer*>(layer));
+ LayerListMutationDetector mutationChecker(stackingNode);
#endif
- if (layer->isStackingContainer()) {
- if (Vector<RenderLayer*>* negZOrderList = layer->negZOrderList()) {
- size_t listSize = negZOrderList->size();
- for (size_t i = 0; i < listSize; ++i) {
- RenderLayer* curLayer = negZOrderList->at(i);
- if (layerHas3DContent(curLayer))
- return true;
- }
- }
-
- if (Vector<RenderLayer*>* posZOrderList = layer->posZOrderList()) {
- size_t listSize = posZOrderList->size();
- for (size_t i = 0; i < listSize; ++i) {
- RenderLayer* curLayer = posZOrderList->at(i);
- if (layerHas3DContent(curLayer))
- return true;
- }
- }
+ RenderLayerStackingNodeIterator iterator(*layer->stackingNode(), AllChildren);
+ while (RenderLayerStackingNode* curNode = iterator.next()) {
+ if (layerHas3DContent(curNode->layer()))
+ return true;
}
- if (Vector<RenderLayer*>* normalFlowList = layer->normalFlowList()) {
- size_t listSize = normalFlowList->size();
- for (size_t i = 0; i < listSize; ++i) {
- RenderLayer* curLayer = normalFlowList->at(i);
- if (layerHas3DContent(curLayer))
- return true;
- }
- }
return false;
}
@@ -2652,8 +2466,8 @@ static bool isRootmostFixedOrStickyLayer(RenderLayer* layer)
if (layer->renderer()->style()->position() != FixedPosition)
return false;
- for (RenderLayer* stackingContainer = layer->ancestorStackingContainer(); stackingContainer; stackingContainer = stackingContainer->ancestorStackingContainer()) {
- if (stackingContainer->isComposited() && stackingContainer->renderer()->style()->position() == FixedPosition)
+ for (RenderLayerStackingNode* stackingContainerNode = layer->stackingNode()->ancestorStackingContainerNode(); stackingContainerNode; stackingContainerNode = stackingContainerNode->ancestorStackingContainerNode()) {
+ if (stackingContainerNode->layer()->hasCompositedLayerMapping() && stackingContainerNode->layer()->renderer()->style()->position() == FixedPosition)
return false;
}
@@ -2683,14 +2497,14 @@ void RenderLayerCompositor::removeViewportConstrainedLayer(RenderLayer* layer)
FixedPositionViewportConstraints RenderLayerCompositor::computeFixedViewportConstraints(RenderLayer* layer) const
{
- ASSERT(layer->isComposited());
+ ASSERT(layer->hasCompositedLayerMapping());
FrameView* frameView = m_renderView->frameView();
LayoutRect viewportRect = frameView->viewportConstrainedVisibleContentRect();
FixedPositionViewportConstraints constraints;
- GraphicsLayer* graphicsLayer = layer->backing()->graphicsLayer();
+ GraphicsLayer* graphicsLayer = layer->compositedLayerMapping()->mainGraphicsLayer();
constraints.setLayerPositionAtLastLayout(graphicsLayer->position());
constraints.setViewportRectAtLastLayout(viewportRect);
@@ -2721,7 +2535,7 @@ FixedPositionViewportConstraints RenderLayerCompositor::computeFixedViewportCons
StickyPositionViewportConstraints RenderLayerCompositor::computeStickyViewportConstraints(RenderLayer* layer) const
{
- ASSERT(layer->isComposited());
+ ASSERT(layer->hasCompositedLayerMapping());
FrameView* frameView = m_renderView->frameView();
LayoutRect viewportRect = frameView->viewportConstrainedVisibleContentRect();
@@ -2732,7 +2546,7 @@ StickyPositionViewportConstraints RenderLayerCompositor::computeStickyViewportCo
renderer->computeStickyPositionConstraints(constraints, viewportRect);
- GraphicsLayer* graphicsLayer = layer->backing()->graphicsLayer();
+ GraphicsLayer* graphicsLayer = layer->compositedLayerMapping()->mainGraphicsLayer();
constraints.setLayerPositionAtLastLayout(graphicsLayer->position());
constraints.setStickyOffsetAtLastLayout(renderer->stickyPositionOffset());
@@ -2766,9 +2580,7 @@ String RenderLayerCompositor::debugName(const GraphicsLayer* graphicsLayer)
if (graphicsLayer == m_rootContentLayer.get()) {
name = "Content Root Layer";
#if USE(RUBBER_BANDING)
- } else if (graphicsLayer == m_layerForOverhangAreas.get()) {
- name = "Overhang Areas Layer";
- } else if (graphicsLayer == m_layerForOverhangAreas.get()) {
+ } else if (graphicsLayer == m_layerForOverhangShadow.get()) {
name = "Overhang Areas Shadow";
#endif
} else if (graphicsLayer == m_overflowControlsHostLayer.get()) {
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderLayerCompositor.h b/chromium/third_party/WebKit/Source/core/rendering/RenderLayerCompositor.h
index 218928b5904..162348c866c 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderLayerCompositor.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderLayerCompositor.h
@@ -27,8 +27,8 @@
#define RenderLayerCompositor_h
#include "core/page/ChromeClient.h"
-#include "core/platform/graphics/GraphicsLayerClient.h"
#include "core/rendering/RenderLayer.h"
+#include "platform/graphics/GraphicsLayerClient.h"
#include "wtf/HashMap.h"
namespace WebCore {
@@ -36,6 +36,7 @@ namespace WebCore {
class FixedPositionViewportConstraints;
class GraphicsLayer;
class RenderEmbeddedObject;
+class RenderLayerStackingNode;
class RenderPart;
class RenderVideo;
class ScrollingCoordinator;
@@ -46,7 +47,8 @@ enum CompositingUpdateType {
CompositingUpdateAfterStyleChange,
CompositingUpdateAfterLayout,
CompositingUpdateOnScroll,
- CompositingUpdateOnCompositedScroll
+ CompositingUpdateOnCompositedScroll,
+ CompositingUpdateFinishAllDeferredWork
};
// RenderLayerCompositor manages the hierarchy of
@@ -73,6 +75,7 @@ public:
// Returns true if the accelerated compositing is enabled
bool hasAcceleratedCompositing() const { return m_hasAcceleratedCompositing; }
+ bool layerSquashingEnabled() const;
bool canRender3DTransforms() const;
@@ -91,19 +94,20 @@ public:
void updateCompositingRequirementsState();
void setNeedsUpdateCompositingRequirementsState() { m_needsUpdateCompositingRequirementsState = true; }
- // Rebuild the tree of compositing layers
- void updateCompositingLayers(CompositingUpdateType, RenderLayer* updateRoot = 0);
+ // Main entry point for a full update. As needed, this function will compute compositing requirements,
+ // rebuild the composited layer tree, and/or update all the properties assocaited with each layer of the
+ // composited layer tree.
+ void updateCompositingLayers(CompositingUpdateType);
// Update the compositing state of the given layer. Returns true if that state changed.
- enum CompositingChangeRepaint { CompositingChangeRepaintNow, CompositingChangeWillRepaintLater };
- bool updateLayerCompositingState(RenderLayer*, CompositingChangeRepaint = CompositingChangeRepaintNow);
+ bool updateLayerCompositingState(RenderLayer*);
// Update the geometry for compositing children of compositingAncestor.
- void updateCompositingDescendantGeometry(RenderLayer* compositingAncestor, RenderLayer*, bool compositedChildrenOnly);
+ void updateCompositingDescendantGeometry(RenderLayerStackingNode* compositingAncestor, RenderLayer*, bool compositedChildrenOnly);
- // Whether layer's backing needs a graphics layer to do clipping by an ancestor (non-stacking-context parent with overflow).
+ // Whether layer's compositedLayerMapping needs a GraphicsLayer to do clipping by an ancestor (non-stacking-context parent with overflow).
bool clippedByAncestor(const RenderLayer*) const;
- // Whether layer's backing needs a graphics layer to clip z-order children of the given layer.
+ // Whether layer's compositedLayerMapping needs a GraphicsLayer to clip z-order children of the given RenderLayer.
bool clipsCompositingDescendants(const RenderLayer*) const;
// Whether the given layer needs an extra 'contents' layer.
@@ -132,9 +136,6 @@ public:
// Repaint parts of all composited layers that intersect the given absolute rectangle (or the entire layer if the pointer is null).
void repaintCompositedLayers(const IntRect* = 0);
- // Returns true if the given layer needs it own backing store.
- bool requiresOwnBackingStore(const RenderLayer*, const RenderLayer* compositingAncestorLayer) const;
-
RenderLayer* rootRenderLayer() const;
GraphicsLayer* rootGraphicsLayer() const;
GraphicsLayer* scrollLayer() const;
@@ -151,10 +152,7 @@ public:
void setIsInWindow(bool);
- void clearBackingForAllLayers();
-
- void layerBecameComposited(const RenderLayer*) { ++m_compositedLayerCount; }
- void layerBecameNonComposited(const RenderLayer*);
+ void clearMappingForAllRenderLayers();
// Use by RenderVideo to ask if it should try to use accelerated compositing.
bool canAccelerateVideoRendering(RenderVideo*) const;
@@ -172,6 +170,7 @@ public:
void frameViewDidChangeSize();
void frameViewDidScroll();
void frameViewDidLayout();
+ void frameViewScrollbarsExistenceDidChange();
void rootFixedBackgroundsChanged();
bool scrollingLayerDidChange(RenderLayer*);
@@ -183,12 +182,6 @@ public:
GraphicsLayer* layerForHorizontalScrollbar() const { return m_layerForHorizontalScrollbar.get(); }
GraphicsLayer* layerForVerticalScrollbar() const { return m_layerForVerticalScrollbar.get(); }
GraphicsLayer* layerForScrollCorner() const { return m_layerForScrollCorner.get(); }
-#if USE(RUBBER_BANDING)
- GraphicsLayer* layerForOverhangAreas() const { return m_layerForOverhangAreas.get(); }
-
- GraphicsLayer* updateLayerForTopOverhangArea(bool wantsLayer);
- GraphicsLayer* updateLayerForBottomOverhangArea(bool wantsLayer);
-#endif
void updateViewportConstraintStatus(RenderLayer*);
void removeViewportConstrainedLayer(RenderLayer*);
@@ -199,10 +192,7 @@ public:
void resetTrackedRepaintRects();
void setTracksRepaints(bool);
- void setShouldReevaluateCompositingAfterLayout() { m_reevaluateCompositingAfterLayout = true; }
-
- // Returns all reasons (direct, indirectly due to subtree, and indirectly due to overlap) that a layer should be composited.
- CompositingReasons reasonsForCompositing(const RenderLayer*) const;
+ void setNeedsToRecomputeCompositingRequirements() { m_needsToRecomputeCompositingRequirements = true; }
virtual String debugName(const GraphicsLayer*) OVERRIDE;
@@ -210,26 +200,28 @@ private:
class OverlapMap;
// GraphicsLayerClient implementation
- virtual void notifyAnimationStarted(const GraphicsLayer*, double) OVERRIDE { }
+ virtual void notifyAnimationStarted(const GraphicsLayer*, double, double) OVERRIDE { }
virtual void paintContents(const GraphicsLayer*, GraphicsContext&, GraphicsLayerPaintingPhase, const IntRect&) OVERRIDE;
virtual bool isTrackingRepaints() const OVERRIDE;
- // Whether the given RL needs a compositing layer.
- bool needsToBeComposited(const RenderLayer*) const;
+ // Whether the given RL needs to paint into its own separate backing (and hence would need its own CompositedLayerMapping).
+ bool needsOwnBacking(const RenderLayer*) const;
// Whether the layer could ever be composited.
bool canBeComposited(const RenderLayer*) const;
// Returns all direct reasons that a layer should be composited.
CompositingReasons directReasonsForCompositing(const RenderLayer*) const;
+ void updateDirectCompositingReasons(RenderLayer*);
+
// Returns indirect reasons that a layer should be composited because of something in its subtree.
CompositingReasons subtreeReasonsForCompositing(RenderObject*, bool hasCompositedDescendants, bool has3DTransformedDescendants) const;
- // Make or destroy the backing for this layer; returns true if backing changed.
- bool updateBacking(RenderLayer*, CompositingChangeRepaint shouldRepaint);
+ // Make or destroy the CompositedLayerMapping for this layer; returns true if the compositedLayerMapping changed.
+ bool allocateOrClearCompositedLayerMapping(RenderLayer*);
- void clearBackingForLayerIncludingDescendants(RenderLayer*);
+ void clearMappingForRenderLayerIncludingDescendants(RenderLayer*);
// Repaint the given rect (which is layer's coords), and regions of child layers that intersect that rect.
void recursiveRepaintLayer(RenderLayer*, const IntRect* = 0);
@@ -237,14 +229,41 @@ private:
void addToOverlapMap(OverlapMap&, RenderLayer*, IntRect& layerBounds, bool& boundsComputed);
void addToOverlapMapRecursive(OverlapMap&, RenderLayer*, RenderLayer* ancestorLayer = 0);
+ struct SquashingState {
+ SquashingState()
+ : mostRecentMapping(0)
+ , hasMostRecentMapping(false)
+ , nextSquashedLayerIndex(0) { }
+
+ void updateSquashingStateForNewMapping(CompositedLayerMappingPtr, bool hasNewCompositedLayerMapping, IntPoint newOffsetFromAbsolute);
+
+ // The most recent composited backing that the layer should squash onto if needed.
+ CompositedLayerMappingPtr mostRecentMapping;
+ bool hasMostRecentMapping;
+
+ // Offset in absolute coordinates of the compositedLayerMapping's owning layer.
+ IntPoint offsetFromAbsolute;
+
+ // Counter that tracks what index the next RenderLayer would be if it gets squashed to the current squashing layer.
+ size_t nextSquashedLayerIndex;
+ };
+
+ // Forces an update for all frames of frame tree recursively. Used only when the mainFrame compositor is ready to
+ // finish all deferred work.
+ static void finishCompositingUpdateForFrameTree(Frame*);
+
// Returns true if any layer's compositing changed
- void computeCompositingRequirements(RenderLayer* ancestorLayer, RenderLayer*, OverlapMap*, struct CompositingState&, bool& layersChanged, bool& descendantHas3DTransform, Vector<RenderLayer*>& unclippedDescendants);
+ void computeCompositingRequirements(RenderLayer* ancestorLayer, RenderLayer*, OverlapMap*, struct CompositingRecursionData&, bool& descendantHas3DTransform, Vector<RenderLayer*>& unclippedDescendants);
+
+ // Defines which RenderLayers will paint into which composited backings, by allocating and destroying CompositedLayerMappings as needed.
+ void assignLayersToBackings(RenderLayer*, bool& layersChanged);
+ void assignLayersToBackingsInternal(RenderLayer*, SquashingState&, bool& layersChanged);
// Recurses down the tree, parenting descendant compositing layers and collecting an array of child layers for the current compositing layer.
void rebuildCompositingLayerTree(RenderLayer*, Vector<GraphicsLayer*>& childGraphicsLayersOfEnclosingLayer, int depth);
// Recurses down the tree, updating layer geometry only.
- void updateLayerTreeGeometry(RenderLayer*, int depth);
+ void updateLayerTreeGeometry(RenderLayer*);
// Hook compositing layers together
void setCompositingParent(RenderLayer* childLayer, RenderLayer* parentLayer);
@@ -283,7 +302,6 @@ private:
bool requiresCompositingForFrame(RenderObject*) const;
bool requiresCompositingForBackfaceVisibilityHidden(RenderObject*) const;
bool requiresCompositingForFilters(RenderObject*) const;
- bool requiresCompositingForBlending(RenderObject* renderer) const;
bool requiresCompositingForOverflowScrollingParent(const RenderLayer*) const;
bool requiresCompositingForOutOfFlowClipping(const RenderLayer*) const;
bool requiresCompositingForScrollableFrame() const;
@@ -302,11 +320,6 @@ private:
bool requiresOverhangLayers() const;
#endif
-#if !LOG_DISABLED
- const char* logReasonsForCompositing(const RenderLayer*);
- void logLayerInfo(const RenderLayer*, int depth);
-#endif
-
private:
RenderView* m_renderView;
OwnPtr<GraphicsLayer> m_rootContentLayer;
@@ -314,12 +327,11 @@ private:
bool m_hasAcceleratedCompositing;
ChromeClient::CompositingTriggerFlags m_compositingTriggers;
- int m_compositedLayerCount;
bool m_showRepaintCounter;
- // When true, we have to wait until layout has happened before we can decide whether to enter compositing mode,
- // because only then do we know the final size of plugins and iframes.
- mutable bool m_reevaluateCompositingAfterLayout;
+ // FIXME: This should absolutely not be mutable.
+ mutable bool m_needsToRecomputeCompositingRequirements;
+ bool m_needsToUpdateLayerTreeGeometry;
bool m_compositing;
bool m_compositingLayersNeedRebuild;
@@ -350,17 +362,8 @@ private:
OwnPtr<GraphicsLayer> m_layerForVerticalScrollbar;
OwnPtr<GraphicsLayer> m_layerForScrollCorner;
#if USE(RUBBER_BANDING)
- OwnPtr<GraphicsLayer> m_layerForOverhangAreas;
OwnPtr<GraphicsLayer> m_layerForOverhangShadow;
#endif
-
-#if !LOG_DISABLED
- int m_rootLayerUpdateCount;
- int m_obligateCompositedLayerCount; // count of layer that have to be composited.
- int m_secondaryCompositedLayerCount; // count of layers that have to be composited because of stacking or overlap.
- double m_obligatoryBackingStoreBytes;
- double m_secondaryBackingStoreBytes;
-#endif
};
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderLayerFilterInfo.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderLayerFilterInfo.cpp
index effb5854cee..600ced9e77a 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderLayerFilterInfo.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderLayerFilterInfo.cpp
@@ -31,16 +31,16 @@
#include "core/rendering/RenderLayerFilterInfo.h"
-#include "core/fetch/DocumentResource.h"
#include "core/fetch/DocumentResourceReference.h"
-#include "core/platform/graphics/filters/custom/CustomFilterOperation.h"
-#include "core/platform/graphics/filters/custom/CustomFilterProgram.h"
#include "core/rendering/FilterEffectRenderer.h"
#include "core/rendering/RenderLayer.h"
+#include "core/rendering/svg/ReferenceFilterBuilder.h"
#include "core/rendering/svg/RenderSVGResourceContainer.h"
#include "core/svg/SVGFilterElement.h"
#include "core/svg/SVGFilterPrimitiveStandardAttributes.h"
#include "core/svg/graphics/filters/SVGFilter.h"
+#include "platform/graphics/filters/custom/CustomFilterOperation.h"
+#include "platform/graphics/filters/custom/CustomFilterProgram.h"
namespace WebCore {
@@ -116,10 +116,10 @@ void RenderLayerFilterInfo::updateReferenceFilterClients(const FilterOperations&
removeReferenceFilterClients();
for (size_t i = 0; i < operations.size(); ++i) {
RefPtr<FilterOperation> filterOperation = operations.operations().at(i);
- if (filterOperation->getOperationType() != FilterOperation::REFERENCE)
+ if (filterOperation->type() != FilterOperation::REFERENCE)
continue;
- ReferenceFilterOperation* referenceFilterOperation = static_cast<ReferenceFilterOperation*>(filterOperation.get());
- DocumentResourceReference* documentReference = referenceFilterOperation->documentResourceReference();
+ ReferenceFilterOperation* referenceFilterOperation = toReferenceFilterOperation(filterOperation.get());
+ DocumentResourceReference* documentReference = ReferenceFilterBuilder::documentResourceReference(referenceFilterOperation);
DocumentResource* cachedSVGDocument = documentReference ? documentReference->document() : 0;
if (cachedSVGDocument) {
@@ -133,7 +133,7 @@ void RenderLayerFilterInfo::updateReferenceFilterClients(const FilterOperations&
if (!filter || !filter->hasTagName(SVGNames::filterTag))
continue;
if (filter->renderer())
- filter->renderer()->toRenderSVGResourceContainer()->addClientRenderLayer(m_layer);
+ toRenderSVGResourceContainer(filter->renderer())->addClientRenderLayer(m_layer);
else
toSVGFilterElement(filter)->addClient(m_layer->renderer()->node());
m_internalSVGReferences.append(filter);
@@ -149,7 +149,7 @@ void RenderLayerFilterInfo::removeReferenceFilterClients()
for (size_t i = 0; i < m_internalSVGReferences.size(); ++i) {
Element* filter = m_internalSVGReferences.at(i).get();
if (filter->renderer())
- filter->renderer()->toRenderSVGResourceContainer()->removeClientRenderLayer(m_layer);
+ toRenderSVGResourceContainer(filter->renderer())->removeClientRenderLayer(m_layer);
else
toSVGFilterElement(filter)->removeClient(m_layer->renderer()->node());
}
@@ -172,10 +172,9 @@ void RenderLayerFilterInfo::updateCustomFilterClients(const FilterOperations& op
CustomFilterProgramList cachedCustomFilterPrograms;
for (size_t i = 0; i < operations.size(); ++i) {
const FilterOperation* filterOperation = operations.at(i);
- if (filterOperation->getOperationType() != FilterOperation::CUSTOM)
+ if (filterOperation->type() != FilterOperation::CUSTOM)
continue;
- const CustomFilterOperation* customFilterOperation = static_cast<const CustomFilterOperation*>(filterOperation);
- RefPtr<CustomFilterProgram> program = customFilterOperation->program();
+ RefPtr<CustomFilterProgram> program = toCustomFilterOperation(filterOperation)->program();
cachedCustomFilterPrograms.append(program);
program->addClient(this);
}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderLayerFilterInfo.h b/chromium/third_party/WebKit/Source/core/rendering/RenderLayerFilterInfo.h
index 4e44b3f2f7a..f982008fc55 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderLayerFilterInfo.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderLayerFilterInfo.h
@@ -32,9 +32,9 @@
#include "core/dom/Element.h"
#include "core/fetch/DocumentResource.h"
-#include "core/platform/graphics/LayoutRect.h"
-#include "core/platform/graphics/filters/FilterOperation.h"
-#include "core/platform/graphics/filters/custom/CustomFilterProgramClient.h"
+#include "platform/geometry/LayoutRect.h"
+#include "platform/graphics/filters/FilterOperation.h"
+#include "platform/graphics/filters/custom/CustomFilterProgramClient.h"
#include "wtf/HashMap.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefPtr.h"
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderLayerModelObject.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderLayerModelObject.cpp
index 2019c7c7853..801c0af5199 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderLayerModelObject.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderLayerModelObject.cpp
@@ -25,7 +25,7 @@
#include "config.h"
#include "core/rendering/RenderLayerModelObject.h"
-#include "core/page/Frame.h"
+#include "core/frame/Frame.h"
#include "core/rendering/RenderLayer.h"
#include "core/rendering/RenderView.h"
@@ -34,13 +34,9 @@ using namespace std;
namespace WebCore {
bool RenderLayerModelObject::s_wasFloating = false;
-bool RenderLayerModelObject::s_hadLayer = false;
-bool RenderLayerModelObject::s_hadTransform = false;
-bool RenderLayerModelObject::s_layerWasSelfPainting = false;
RenderLayerModelObject::RenderLayerModelObject(ContainerNode* node)
: RenderObject(node)
- , m_layer(0)
{
}
@@ -53,18 +49,14 @@ RenderLayerModelObject::~RenderLayerModelObject()
void RenderLayerModelObject::destroyLayer()
{
- ASSERT(!hasLayer()); // Callers should have already called setHasLayer(false)
- ASSERT(m_layer);
- delete m_layer;
- m_layer = 0;
+ setHasLayer(false);
+ m_layer = nullptr;
}
-void RenderLayerModelObject::ensureLayer()
+void RenderLayerModelObject::createLayer()
{
- if (m_layer)
- return;
-
- m_layer = new RenderLayer(this);
+ ASSERT(!m_layer);
+ m_layer = adoptPtr(new RenderLayer(this));
setHasLayer(true);
m_layer->insertOnlyThisLayer();
}
@@ -91,17 +83,14 @@ void RenderLayerModelObject::willBeDestroyed()
}
}
- // RenderObject::willBeDestroyed calls back to destroyLayer() for layer destruction
RenderObject::willBeDestroyed();
+
+ destroyLayer();
}
void RenderLayerModelObject::styleWillChange(StyleDifference diff, const RenderStyle* newStyle)
{
s_wasFloating = isFloating();
- s_hadLayer = hasLayer();
- s_hadTransform = hasTransform();
- if (s_hadLayer)
- s_layerWasSelfPainting = layer()->isSelfPaintingLayer();
// If our z-index changes value or our visibility changes,
// we need to dirty our stacking context's z-order list.
@@ -111,9 +100,9 @@ void RenderLayerModelObject::styleWillChange(StyleDifference diff, const RenderS
// Do a repaint with the old style first, e.g., for example if we go from
// having an outline to not having an outline.
if (diff == StyleDifferenceRepaintLayer) {
- layer()->repaintIncludingDescendants();
+ layer()->repainter().repaintIncludingDescendants();
if (!(oldStyle->clip() == newStyle->clip()))
- layer()->clearClipRectsIncludingDescendants();
+ layer()->clipper().clearClipRectsIncludingDescendants();
} else if (diff == StyleDifferenceRepaint || newStyle->outlineSize() < oldStyle->outlineSize())
repaint();
}
@@ -131,7 +120,7 @@ void RenderLayerModelObject::styleWillChange(StyleDifference diff, const RenderS
|| oldStyle->transform() != newStyle->transform()
|| oldStyle->filter() != newStyle->filter()
)
- layer()->repaintIncludingDescendants();
+ layer()->repainter().repaintIncludingDescendants();
} else if (newStyle->hasTransform() || newStyle->opacity() < 1 || newStyle->hasFilter()) {
// If we don't have a layer yet, but we are going to get one because of transform or opacity,
// then we need to repaint the old position of the object.
@@ -145,6 +134,10 @@ void RenderLayerModelObject::styleWillChange(StyleDifference diff, const RenderS
void RenderLayerModelObject::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
{
+ bool hadTransform = hasTransform();
+ bool hadLayer = hasLayer();
+ bool layerWasSelfPainting = hadLayer && layer()->isSelfPaintingLayer();
+
RenderObject::styleDidChange(diff, oldStyle);
updateFromStyle();
@@ -152,9 +145,9 @@ void RenderLayerModelObject::styleDidChange(StyleDifference diff, const RenderSt
if (!layer() && layerCreationAllowedForSubtree()) {
if (s_wasFloating && isFloating())
setChildNeedsLayout();
- ensureLayer();
+ createLayer();
if (parent() && !needsLayout() && containingBlock()) {
- layer()->setRepaintStatus(NeedsFullRepaint);
+ layer()->repainter().setRepaintStatus(NeedsFullRepaint);
// There is only one layer to update, it is not worth using |cachedOffset| since
// we are not sure the value will be used.
layer()->updateLayerPositions(0);
@@ -166,13 +159,13 @@ void RenderLayerModelObject::styleDidChange(StyleDifference diff, const RenderSt
layer()->removeOnlyThisLayer(); // calls destroyLayer() which clears m_layer
if (s_wasFloating && isFloating())
setChildNeedsLayout();
- if (s_hadTransform)
+ if (hadTransform)
setNeedsLayoutAndPrefWidthsRecalc();
}
if (layer()) {
layer()->styleChanged(diff, oldStyle);
- if (s_hadLayer && layer()->isSelfPaintingLayer() != s_layerWasSelfPainting)
+ if (hadLayer && layer()->isSelfPaintingLayer() != layerWasSelfPainting)
setChildNeedsLayout();
}
@@ -206,9 +199,19 @@ void RenderLayerModelObject::addLayerHitTestRects(LayerHitTestRects& rects, cons
}
}
-RenderLayerBacking* RenderLayerModelObject::backing() const
+CompositedLayerMappingPtr RenderLayerModelObject::compositedLayerMapping() const
+{
+ return m_layer ? m_layer->compositedLayerMapping() : 0;
+}
+
+bool RenderLayerModelObject::hasCompositedLayerMapping() const
+{
+ return m_layer ? m_layer->hasCompositedLayerMapping() : false;
+}
+
+CompositedLayerMapping* RenderLayerModelObject::groupedMapping() const
{
- return m_layer ? m_layer->backing() : 0;
+ return m_layer ? m_layer->groupedMapping() : 0;
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderLayerModelObject.h b/chromium/third_party/WebKit/Source/core/rendering/RenderLayerModelObject.h
index 414fe361faa..4eb42633a7f 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderLayerModelObject.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderLayerModelObject.h
@@ -23,12 +23,13 @@
#ifndef RenderLayerModelObject_h
#define RenderLayerModelObject_h
+#include "core/rendering/CompositedLayerMappingPtr.h"
#include "core/rendering/RenderObject.h"
namespace WebCore {
class RenderLayer;
-class RenderLayerBacking;
+class CompositedLayerMapping;
class ScrollableArea;
class RenderLayerModelObject : public RenderObject {
@@ -36,11 +37,11 @@ public:
explicit RenderLayerModelObject(ContainerNode*);
virtual ~RenderLayerModelObject();
- // Called by RenderObject::willBeDestroyed() and is the only way layers should ever be destroyed
+ // This is the only way layers should ever be destroyed.
void destroyLayer();
bool hasSelfPaintingLayer() const;
- RenderLayer* layer() const { return m_layer; }
+ RenderLayer* layer() const { return m_layer.get(); }
ScrollableArea* scrollableArea() const;
virtual void styleWillChange(StyleDifference, const RenderStyle* newStyle) OVERRIDE;
@@ -56,10 +57,12 @@ public:
// This is null for anonymous renderers.
ContainerNode* node() const { return toContainerNode(RenderObject::node()); }
- RenderLayerBacking* backing() const;
+ CompositedLayerMappingPtr compositedLayerMapping() const;
+ bool hasCompositedLayerMapping() const;
+ CompositedLayerMapping* groupedMapping() const;
protected:
- void ensureLayer();
+ void createLayer();
virtual void willBeDestroyed() OVERRIDE;
@@ -68,29 +71,13 @@ protected:
private:
virtual bool isLayerModelObject() const OVERRIDE FINAL { return true; }
- RenderLayer* m_layer;
+ OwnPtr<RenderLayer> m_layer;
// Used to store state between styleWillChange and styleDidChange
static bool s_wasFloating;
- static bool s_hadLayer;
- static bool s_hadTransform;
- static bool s_layerWasSelfPainting;
};
-inline RenderLayerModelObject* toRenderLayerModelObject(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isLayerModelObject());
- return static_cast<RenderLayerModelObject*>(object);
-}
-
-inline const RenderLayerModelObject* toRenderLayerModelObject(const RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isLayerModelObject());
- return static_cast<const RenderLayerModelObject*>(object);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toRenderLayerModelObject(const RenderLayerModelObject*);
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderLayerModelObject, isLayerModelObject());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderLayerReflectionInfo.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderLayerReflectionInfo.cpp
new file mode 100644
index 00000000000..38801bdbdc4
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderLayerReflectionInfo.cpp
@@ -0,0 +1,148 @@
+/*
+ * Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012 Apple Inc. All rights reserved.
+ *
+ * Portions are Copyright (C) 1998 Netscape Communications Corporation.
+ *
+ * Other contributors:
+ * Robert O'Callahan <roc+@cs.cmu.edu>
+ * David Baron <dbaron@fas.harvard.edu>
+ * Christian Biesinger <cbiesinger@web.de>
+ * Randall Jesup <rjesup@wgate.com>
+ * Roland Mainz <roland.mainz@informatik.med.uni-giessen.de>
+ * Josh Soref <timeless@mac.com>
+ * Boris Zbarsky <bzbarsky@mit.edu>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ * Alternatively, the contents of this file may be used under the terms
+ * of either the Mozilla Public License Version 1.1, found at
+ * http://www.mozilla.org/MPL/ (the "MPL") or the GNU General Public
+ * License Version 2.0, found at http://www.fsf.org/copyleft/gpl.html
+ * (the "GPL"), in which case the provisions of the MPL or the GPL are
+ * applicable instead of those above. If you wish to allow use of your
+ * version of this file only under the terms of one of those two
+ * licenses (the MPL or the GPL) and not to allow others to use your
+ * version of this file under the LGPL, indicate your decision by
+ * deletingthe provisions above and replace them with the notice and
+ * other provisions required by the MPL or the GPL, as the case may be.
+ * If you do not delete the provisions above, a recipient may use your
+ * version of this file under any of the LGPL, the MPL or the GPL.
+ */
+
+#include "config.h"
+#include "core/rendering/RenderLayerReflectionInfo.h"
+
+#include "core/frame/UseCounter.h"
+#include "core/rendering/RenderLayer.h"
+#include "core/rendering/RenderReplica.h"
+#include "core/rendering/style/RenderStyle.h"
+#include "platform/transforms/ScaleTransformOperation.h"
+#include "platform/transforms/TranslateTransformOperation.h"
+
+#include "wtf/RefPtr.h"
+
+namespace WebCore {
+
+RenderLayerReflectionInfo::RenderLayerReflectionInfo(RenderBox* renderer)
+ : m_renderer(renderer)
+ , m_isPaintingInsideReflection(false)
+{
+ UseCounter::count(m_renderer->document(), UseCounter::Reflection);
+
+ m_reflection = RenderReplica::createAnonymous(&(m_renderer->document()));
+ m_reflection->setParent(m_renderer); // We create a 1-way connection.
+}
+
+RenderLayerReflectionInfo::~RenderLayerReflectionInfo()
+{
+ if (!m_reflection->documentBeingDestroyed())
+ m_reflection->removeLayers(renderer()->layer());
+
+ m_reflection->setParent(0);
+ m_reflection->destroy();
+ m_reflection = 0;
+}
+
+
+RenderLayer* RenderLayerReflectionInfo::reflectionLayer() const
+{
+ return m_reflection->layer();
+}
+
+void RenderLayerReflectionInfo::updateAfterStyleChange(const RenderStyle* oldStyle)
+{
+ RefPtr<RenderStyle> newStyle = RenderStyle::create();
+ newStyle->inheritFrom(renderer()->style());
+
+ // Map in our transform.
+ TransformOperations transform;
+ switch (renderer()->style()->boxReflect()->direction()) {
+ case ReflectionBelow:
+ transform.operations().append(TranslateTransformOperation::create(Length(0, Fixed),
+ Length(100., Percent), TransformOperation::Translate));
+ transform.operations().append(TranslateTransformOperation::create(Length(0, Fixed),
+ renderer()->style()->boxReflect()->offset(), TransformOperation::Translate));
+ transform.operations().append(ScaleTransformOperation::create(1.0, -1.0, ScaleTransformOperation::Scale));
+ break;
+
+ case ReflectionAbove:
+ transform.operations().append(ScaleTransformOperation::create(1.0, -1.0, ScaleTransformOperation::Scale));
+ transform.operations().append(TranslateTransformOperation::create(Length(0, Fixed),
+ Length(100., Percent), TransformOperation::Translate));
+ transform.operations().append(TranslateTransformOperation::create(Length(0, Fixed),
+ renderer()->style()->boxReflect()->offset(), TransformOperation::Translate));
+ break;
+
+ case ReflectionRight:
+ transform.operations().append(TranslateTransformOperation::create(Length(100., Percent),
+ Length(0, Fixed), TransformOperation::Translate));
+ transform.operations().append(TranslateTransformOperation::create(
+ renderer()->style()->boxReflect()->offset(), Length(0, Fixed), TransformOperation::Translate));
+ transform.operations().append(ScaleTransformOperation::create(-1.0, 1.0, ScaleTransformOperation::Scale));
+ break;
+
+ case ReflectionLeft:
+ transform.operations().append(ScaleTransformOperation::create(-1.0, 1.0, ScaleTransformOperation::Scale));
+ transform.operations().append(TranslateTransformOperation::create(Length(100., Percent),
+ Length(0, Fixed), TransformOperation::Translate));
+ transform.operations().append(TranslateTransformOperation::create(
+ renderer()->style()->boxReflect()->offset(), Length(0, Fixed), TransformOperation::Translate));
+ break;
+ }
+ newStyle->setTransform(transform);
+
+ // Map in our mask.
+ newStyle->setMaskBoxImage(renderer()->style()->boxReflect()->mask());
+
+ m_reflection->setStyle(newStyle.release());
+}
+
+void RenderLayerReflectionInfo::paint(GraphicsContext* context, const LayerPaintingInfo& paintingInfo, PaintLayerFlags flags)
+{
+ if (m_isPaintingInsideReflection)
+ return;
+
+ // Mark that we are now inside replica painting.
+ m_isPaintingInsideReflection = true;
+ reflectionLayer()->paintLayer(context, paintingInfo, flags);
+ m_isPaintingInsideReflection = false;
+}
+
+String RenderLayerReflectionInfo::debugName() const
+{
+ return renderer()->debugName() + " (reflection)";
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderLayerReflectionInfo.h b/chromium/third_party/WebKit/Source/core/rendering/RenderLayerReflectionInfo.h
new file mode 100644
index 00000000000..90ec7898acf
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderLayerReflectionInfo.h
@@ -0,0 +1,86 @@
+/*
+ * Copyright (C) 2003, 2009, 2012 Apple Inc. All rights reserved.
+ * Copyright (C) 2013 Intel Corporation. All rights reserved.
+ *
+ * Portions are Copyright (C) 1998 Netscape Communications Corporation.
+ *
+ * Other contributors:
+ * Robert O'Callahan <roc+@cs.cmu.edu>
+ * David Baron <dbaron@fas.harvard.edu>
+ * Christian Biesinger <cbiesinger@web.de>
+ * Randall Jesup <rjesup@wgate.com>
+ * Roland Mainz <roland.mainz@informatik.med.uni-giessen.de>
+ * Josh Soref <timeless@mac.com>
+ * Boris Zbarsky <bzbarsky@mit.edu>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ * Alternatively, the contents of this file may be used under the terms
+ * of either the Mozilla Public License Version 1.1, found at
+ * http://www.mozilla.org/MPL/ (the "MPL") or the GNU General Public
+ * License Version 2.0, found at http://www.fsf.org/copyleft/gpl.html
+ * (the "GPL"), in which case the provisions of the MPL or the GPL are
+ * applicable instead of those above. If you wish to allow use of your
+ * version of this file only under the terms of one of those two
+ * licenses (the MPL or the GPL) and not to allow others to use your
+ * version of this file under the LGPL, indicate your decision by
+ * deletingthe provisions above and replace them with the notice and
+ * other provisions required by the MPL or the GPL, as the case may be.
+ * If you do not delete the provisions above, a recipient may use your
+ * version of this file under any of the LGPL, the MPL or the GPL.
+ */
+
+#ifndef RenderLayerReflectionInfo_h
+#define RenderLayerReflectionInfo_h
+
+#include "core/rendering/LayerPaintingInfo.h"
+#include "core/rendering/RenderLayerModelObject.h"
+#include "wtf/Noncopyable.h"
+
+namespace WebCore {
+
+class RenderLayer;
+class RenderReplica;
+
+class RenderLayerReflectionInfo {
+ WTF_MAKE_NONCOPYABLE(RenderLayerReflectionInfo);
+public:
+ explicit RenderLayerReflectionInfo(RenderBox*);
+ ~RenderLayerReflectionInfo();
+
+ RenderReplica* reflection() const { return m_reflection; }
+ RenderLayer* reflectionLayer() const;
+
+ bool isPaintingInsideReflection() const { return m_isPaintingInsideReflection; }
+
+ void updateAfterStyleChange(const RenderStyle* oldStyle);
+
+ void paint(GraphicsContext*, const LayerPaintingInfo&, PaintLayerFlags);
+
+ String debugName() const;
+
+private:
+ RenderBox* renderer() const { return m_renderer; }
+
+ RenderBox* m_renderer;
+ RenderReplica* m_reflection;
+
+ // A state bit tracking if we are painting inside a replica.
+ unsigned m_isPaintingInsideReflection : 1;
+};
+
+} // namespace WebCore
+
+#endif // RenderLayerReflectinInfo_h
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderLayerRepainter.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderLayerRepainter.cpp
new file mode 100644
index 00000000000..77da5c125d9
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderLayerRepainter.cpp
@@ -0,0 +1,259 @@
+/*
+ * Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012 Apple Inc. All rights reserved.
+ *
+ * Portions are Copyright (C) 1998 Netscape Communications Corporation.
+ *
+ * Other contributors:
+ * Robert O'Callahan <roc+@cs.cmu.edu>
+ * David Baron <dbaron@fas.harvard.edu>
+ * Christian Biesinger <cbiesinger@web.de>
+ * Randall Jesup <rjesup@wgate.com>
+ * Roland Mainz <roland.mainz@informatik.med.uni-giessen.de>
+ * Josh Soref <timeless@mac.com>
+ * Boris Zbarsky <bzbarsky@mit.edu>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ * Alternatively, the contents of this file may be used under the terms
+ * of either the Mozilla Public License Version 1.1, found at
+ * http://www.mozilla.org/MPL/ (the "MPL") or the GNU General Public
+ * License Version 2.0, found at http://www.fsf.org/copyleft/gpl.html
+ * (the "GPL"), in which case the provisions of the MPL or the GPL are
+ * applicable instead of those above. If you wish to allow use of your
+ * version of this file only under the terms of one of those two
+ * licenses (the MPL or the GPL) and not to allow others to use your
+ * version of this file under the LGPL, indicate your decision by
+ * deletingthe provisions above and replace them with the notice and
+ * other provisions required by the MPL or the GPL, as the case may be.
+ * If you do not delete the provisions above, a recipient may use your
+ * version of this file under any of the LGPL, the MPL or the GPL.
+ */
+
+#include "config.h"
+#include "core/rendering/RenderLayerRepainter.h"
+
+#include "core/rendering/CompositedLayerMapping.h"
+#include "core/rendering/FilterEffectRenderer.h"
+#include "core/rendering/RenderLayer.h"
+#include "core/rendering/RenderView.h"
+
+namespace WebCore {
+
+RenderLayerRepainter::RenderLayerRepainter(RenderLayerModelObject* renderer)
+ : m_renderer(renderer)
+ , m_repaintStatus(NeedsNormalRepaint)
+{
+}
+
+void RenderLayerRepainter::repaintAfterLayout(RenderGeometryMap* geometryMap, bool shouldCheckForRepaint)
+{
+ if (m_renderer->layer()->hasVisibleContent()) {
+ RenderView* view = m_renderer->view();
+ ASSERT(view);
+ // FIXME: LayoutState does not work with RenderLayers as there is not a 1-to-1
+ // mapping between them and the RenderObjects. It would be neat to enable
+ // LayoutState outside the layout() phase and use it here.
+ ASSERT(!view->layoutStateEnabled());
+
+ RenderLayerModelObject* repaintContainer = m_renderer->containerForRepaint();
+ LayoutRect oldRepaintRect = m_repaintRect;
+ LayoutRect oldOutlineBox = m_outlineBox;
+ computeRepaintRects(repaintContainer, geometryMap);
+
+ // FIXME: Should ASSERT that value calculated for m_outlineBox using the cached offset is the same
+ // as the value not using the cached offset, but we can't due to https://bugs.webkit.org/show_bug.cgi?id=37048
+ if (shouldCheckForRepaint) {
+ if (view && !view->document().printing()) {
+ if (m_repaintStatus & NeedsFullRepaint) {
+ m_renderer->repaintUsingContainer(repaintContainer, pixelSnappedIntRect(oldRepaintRect));
+ if (m_repaintRect != oldRepaintRect)
+ m_renderer->repaintUsingContainer(repaintContainer, pixelSnappedIntRect(m_repaintRect));
+ } else if (shouldRepaintAfterLayout()) {
+ m_renderer->repaintAfterLayoutIfNeeded(repaintContainer, m_renderer->selfNeedsLayout(), oldRepaintRect, oldOutlineBox, &m_repaintRect, &m_outlineBox);
+ }
+ }
+ }
+ } else {
+ clearRepaintRects();
+ }
+
+ m_repaintStatus = NeedsNormalRepaint;
+
+}
+
+void RenderLayerRepainter::clearRepaintRects()
+{
+ ASSERT(!m_renderer->layer()->hasVisibleContent());
+
+ m_repaintRect = IntRect();
+ m_outlineBox = IntRect();
+}
+
+void RenderLayerRepainter::computeRepaintRects(const RenderLayerModelObject* repaintContainer, const RenderGeometryMap* geometryMap)
+{
+ m_repaintRect = m_renderer->clippedOverflowRectForRepaint(repaintContainer);
+ m_outlineBox = m_renderer->outlineBoundsForRepaint(repaintContainer, geometryMap);
+}
+
+void RenderLayerRepainter::computeRepaintRectsIncludingDescendants()
+{
+ // FIXME: computeRepaintRects() has to walk up the parent chain for every layer to compute the rects.
+ // We should make this more efficient.
+ // FIXME: it's wrong to call this when layout is not up-to-date, which we do.
+ computeRepaintRects(m_renderer->containerForRepaint());
+
+ for (RenderLayer* layer = m_renderer->layer()->firstChild(); layer; layer = layer->nextSibling())
+ layer->repainter().computeRepaintRectsIncludingDescendants();
+}
+
+inline bool RenderLayerRepainter::shouldRepaintAfterLayout() const
+{
+ if (m_repaintStatus == NeedsNormalRepaint)
+ return true;
+
+ // Composited layers that were moved during a positioned movement only
+ // layout, don't need to be repainted. They just need to be recomposited.
+ ASSERT(m_repaintStatus == NeedsFullRepaintForPositionedMovementLayout);
+ return m_renderer->compositingState() != PaintsIntoOwnBacking;
+}
+
+// Since we're only painting non-composited layers, we know that they all share the same repaintContainer.
+void RenderLayerRepainter::repaintIncludingNonCompositingDescendants(RenderLayerModelObject* repaintContainer)
+{
+ m_renderer->repaintUsingContainer(repaintContainer, pixelSnappedIntRect(m_renderer->clippedOverflowRectForRepaint(repaintContainer)));
+
+ for (RenderLayer* curr = m_renderer->layer()->firstChild(); curr; curr = curr->nextSibling()) {
+ if (!curr->hasCompositedLayerMapping())
+ curr->repainter().repaintIncludingNonCompositingDescendants(repaintContainer);
+ }
+}
+
+LayoutRect RenderLayerRepainter::repaintRectIncludingNonCompositingDescendants() const
+{
+ LayoutRect repaintRect = m_repaintRect;
+ for (RenderLayer* child = m_renderer->layer()->firstChild(); child; child = child->nextSibling()) {
+ // Don't include repaint rects for composited child layers; they will paint themselves and have a different origin.
+ if (child->hasCompositedLayerMapping())
+ continue;
+
+ repaintRect.unite(child->repainter().repaintRectIncludingNonCompositingDescendants());
+ }
+ return repaintRect;
+}
+
+void RenderLayerRepainter::setBackingNeedsRepaint()
+{
+ ASSERT(m_renderer->compositingState() != NotComposited);
+
+ if (m_renderer->compositingState() == PaintsIntoGroupedBacking) {
+ // FIXME: should probably setNeedsDisplayInRect for this layer's bounds only.
+ m_renderer->groupedMapping()->squashingLayer()->setNeedsDisplay();
+ } else {
+ m_renderer->compositedLayerMapping()->setContentsNeedDisplay();
+ }
+}
+
+void RenderLayerRepainter::setBackingNeedsRepaintInRect(const LayoutRect& r)
+{
+ // https://bugs.webkit.org/show_bug.cgi?id=61159 describes an unreproducible crash here,
+ // so assert but check that the layer is composited.
+ ASSERT(m_renderer->compositingState() != NotComposited);
+ if (m_renderer->compositingState() == NotComposited) {
+ // If we're trying to repaint the placeholder document layer, propagate the
+ // repaint to the native view system.
+ LayoutRect absRect(r);
+ LayoutPoint delta;
+ m_renderer->layer()->convertToLayerCoords(m_renderer->layer()->root(), delta);
+ absRect.moveBy(delta);
+
+ RenderView* view = m_renderer->view();
+ if (view)
+ view->repaintViewRectangle(absRect);
+ } else {
+ if (m_renderer->compositingState() == PaintsIntoGroupedBacking) {
+ // FIXME: LayoutRect rounding to IntRect is probably not a good idea.
+ IntRect offsetRect = pixelSnappedIntRect(r);
+ if (m_renderer->hasTransform())
+ offsetRect = m_renderer->layer()->transform()->mapRect(pixelSnappedIntRect(r));
+
+ offsetRect.move(-m_renderer->layer()->offsetFromSquashingLayerOrigin());
+ m_renderer->groupedMapping()->squashingLayer()->setNeedsDisplayInRect(offsetRect);
+ } else {
+ m_renderer->compositedLayerMapping()->setContentsNeedDisplayInRect(pixelSnappedIntRect(r));
+ }
+ }
+}
+
+void RenderLayerRepainter::repaintIncludingDescendants()
+{
+ m_renderer->repaint();
+ for (RenderLayer* curr = m_renderer->layer()->firstChild(); curr; curr = curr->nextSibling())
+ curr->repainter().repaintIncludingDescendants();
+}
+
+void RenderLayerRepainter::setFilterBackendNeedsRepaintingInRect(const LayoutRect& rect)
+{
+ if (rect.isEmpty())
+ return;
+
+ LayoutRect rectForRepaint = rect;
+ m_renderer->style()->filterOutsets().expandRect(rectForRepaint);
+
+ RenderLayerFilterInfo* filterInfo = m_renderer->layer()->filterInfo();
+ ASSERT(filterInfo);
+ filterInfo->expandDirtySourceRect(rectForRepaint);
+
+ ASSERT(filterInfo->renderer());
+ if (filterInfo->renderer()->hasCustomShaderFilter()) {
+ // If we have at least one custom shader, we need to update the whole bounding box of the layer, because the
+ // shader can address any ouput pixel.
+ // Note: This is only for output rect, so there's no need to expand the dirty source rect.
+ rectForRepaint.unite(m_renderer->layer()->calculateLayerBounds(m_renderer->layer()));
+ }
+
+ RenderLayer* parentLayer = enclosingFilterRepaintLayer();
+ ASSERT(parentLayer);
+ FloatQuad repaintQuad(rectForRepaint);
+ LayoutRect parentLayerRect = m_renderer->localToContainerQuad(repaintQuad, parentLayer->renderer()).enclosingBoundingBox();
+
+ if (parentLayer->hasCompositedLayerMapping()) {
+ parentLayer->repainter().setBackingNeedsRepaintInRect(parentLayerRect);
+ return;
+ }
+
+ if (parentLayer->paintsWithFilters()) {
+ parentLayer->repainter().setFilterBackendNeedsRepaintingInRect(parentLayerRect);
+ return;
+ }
+
+ if (parentLayer->isRootLayer()) {
+ RenderView* view = toRenderView(parentLayer->renderer());
+ view->repaintViewRectangle(parentLayerRect);
+ return;
+ }
+
+ ASSERT_NOT_REACHED();
+}
+
+RenderLayer* RenderLayerRepainter::enclosingFilterRepaintLayer() const
+{
+ for (const RenderLayer* curr = m_renderer->layer(); curr; curr = curr->parent()) {
+ if ((curr != m_renderer->layer() && curr->requiresFullLayerImageForFilters()) || curr->compositingState() == PaintsIntoOwnBacking || curr->isRootLayer())
+ return const_cast<RenderLayer*>(curr);
+ }
+ return 0;
+}
+
+} // Namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderLayerRepainter.h b/chromium/third_party/WebKit/Source/core/rendering/RenderLayerRepainter.h
new file mode 100644
index 00000000000..ffc08ee8947
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderLayerRepainter.h
@@ -0,0 +1,105 @@
+/*
+ * Copyright (C) 2003, 2009, 2012 Apple Inc. All rights reserved.
+ * Copyright (C) 2013 Intel Corporation. All rights reserved.
+ *
+ * Portions are Copyright (C) 1998 Netscape Communications Corporation.
+ *
+ * Other contributors:
+ * Robert O'Callahan <roc+@cs.cmu.edu>
+ * David Baron <dbaron@fas.harvard.edu>
+ * Christian Biesinger <cbiesinger@web.de>
+ * Randall Jesup <rjesup@wgate.com>
+ * Roland Mainz <roland.mainz@informatik.med.uni-giessen.de>
+ * Josh Soref <timeless@mac.com>
+ * Boris Zbarsky <bzbarsky@mit.edu>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ * Alternatively, the contents of this file may be used under the terms
+ * of either the Mozilla Public License Version 1.1, found at
+ * http://www.mozilla.org/MPL/ (the "MPL") or the GNU General Public
+ * License Version 2.0, found at http://www.fsf.org/copyleft/gpl.html
+ * (the "GPL"), in which case the provisions of the MPL or the GPL are
+ * applicable instead of those above. If you wish to allow use of your
+ * version of this file only under the terms of one of those two
+ * licenses (the MPL or the GPL) and not to allow others to use your
+ * version of this file under the LGPL, indicate your decision by
+ * deletingthe provisions above and replace them with the notice and
+ * other provisions required by the MPL or the GPL, as the case may be.
+ * If you do not delete the provisions above, a recipient may use your
+ * version of this file under any of the LGPL, the MPL or the GPL.
+ */
+
+#ifndef RenderLayerRepainter_h
+#define RenderLayerRepainter_h
+
+#include "platform/geometry/LayoutRect.h"
+#include "wtf/Noncopyable.h"
+
+namespace WebCore {
+
+enum RepaintStatus {
+ NeedsNormalRepaint = 0,
+ NeedsFullRepaint = 1 << 0,
+ NeedsFullRepaintForPositionedMovementLayout = 1 << 1
+};
+
+class RenderGeometryMap;
+class RenderLayer;
+class RenderLayerModelObject;
+
+class RenderLayerRepainter {
+ WTF_MAKE_NONCOPYABLE(RenderLayerRepainter);
+public:
+ RenderLayerRepainter(RenderLayerModelObject*);
+
+ // Return a cached repaint rect, computed relative to the layer renderer's containerForRepaint.
+ LayoutRect repaintRect() const { return m_repaintRect; }
+ LayoutRect repaintRectIncludingNonCompositingDescendants() const;
+
+ void repaintAfterLayout(RenderGeometryMap*, bool shouldCheckForRepaint);
+ void repaintIncludingNonCompositingDescendants(RenderLayerModelObject* repaintContainer);
+ void repaintIncludingDescendants();
+
+ void setRepaintStatus(RepaintStatus status) { m_repaintStatus = status; }
+
+ void computeRepaintRects(const RenderLayerModelObject* repaintContainer, const RenderGeometryMap* = 0);
+ void computeRepaintRectsIncludingDescendants();
+
+ // Indicate that the layer contents need to be repainted. Only has an effect
+ // if layer compositing is being used,
+ void setBackingNeedsRepaint();
+ void setBackingNeedsRepaintInRect(const LayoutRect&); // r is in the coordinate space of the layer's render object
+
+ void setFilterBackendNeedsRepaintingInRect(const LayoutRect&);
+
+private:
+ bool shouldRepaintAfterLayout() const;
+
+ void clearRepaintRects();
+
+ RenderLayer* enclosingFilterRepaintLayer() const;
+
+ RenderLayerModelObject* m_renderer;
+
+ unsigned m_repaintStatus; // RepaintStatus
+
+ LayoutRect m_repaintRect; // Cached repaint rects. Used by layout.
+ LayoutRect m_outlineBox;
+};
+
+} // namespace WebCore
+
+#endif // RenderLayerRepainter_h
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderLayerScrollableArea.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderLayerScrollableArea.cpp
index e3ee6e609b2..0486111467d 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderLayerScrollableArea.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderLayerScrollableArea.cpp
@@ -47,30 +47,47 @@
#include "core/css/PseudoStyleRequest.h"
#include "core/dom/shadow/ShadowRoot.h"
#include "core/editing/FrameSelection.h"
+#include "core/html/HTMLFrameOwnerElement.h"
#include "core/inspector/InspectorInstrumentation.h"
#include "core/page/EventHandler.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameView.h"
+#include "core/page/FocusController.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
#include "core/page/Page.h"
#include "core/page/scrolling/ScrollingCoordinator.h"
-#include "core/platform/ScrollAnimator.h"
-#include "core/platform/graphics/GraphicsLayer.h"
+#include "core/rendering/CompositedLayerMapping.h"
+#include "core/rendering/RenderGeometryMap.h"
#include "core/rendering/RenderLayerCompositor.h"
#include "core/rendering/RenderScrollbar.h"
#include "core/rendering/RenderScrollbarPart.h"
#include "core/rendering/RenderView.h"
+#include "platform/PlatformGestureEvent.h"
+#include "platform/PlatformMouseEvent.h"
+#include "platform/graphics/GraphicsContextStateSaver.h"
+#include "platform/graphics/GraphicsLayer.h"
+#include "platform/scroll/ScrollAnimator.h"
+#include "platform/scroll/ScrollbarTheme.h"
+#include "public/platform/Platform.h"
namespace WebCore {
-RenderLayerScrollableArea::RenderLayerScrollableArea(RenderLayer* layer)
- : m_layer(layer)
+const int ResizerControlExpandRatioForTouch = 2;
+
+RenderLayerScrollableArea::RenderLayerScrollableArea(RenderBox* box)
+ : m_box(box)
+ , m_inResizeMode(false)
, m_scrollDimensionsDirty(true)
, m_inOverflowRelayout(false)
+ , m_needsCompositedScrolling(false)
+ , m_willUseCompositedScrollingHasBeenRecorded(false)
+ , m_isScrollableAreaHasBeenRecorded(false)
+ , m_forceNeedsCompositedScrolling(DoNotForceCompositedScrolling)
, m_scrollCorner(0)
+ , m_resizer(0)
{
ScrollableArea::setConstrainsScrollingToContentEdge(false);
- Node* node = renderer()->node();
+ Node* node = m_box->node();
if (node && node->isElementNode()) {
// We save and restore only the scrollOffset as the other scroll values are recalculated.
Element* element = toElement(node);
@@ -80,67 +97,75 @@ RenderLayerScrollableArea::RenderLayerScrollableArea(RenderLayer* layer)
element->setSavedLayerScrollOffset(IntSize());
}
+ updateResizerAreaSet();
}
RenderLayerScrollableArea::~RenderLayerScrollableArea()
{
- if (Frame* frame = renderer()->frame()) {
+ if (inResizeMode() && !m_box->documentBeingDestroyed()) {
+ if (Frame* frame = m_box->frame())
+ frame->eventHandler().resizeScrollableAreaDestroyed();
+ }
+
+ if (Frame* frame = m_box->frame()) {
if (FrameView* frameView = frame->view()) {
frameView->removeScrollableArea(this);
}
}
- if (renderer()->frame() && renderer()->frame()->page()) {
- if (ScrollingCoordinator* scrollingCoordinator = renderer()->frame()->page()->scrollingCoordinator())
+ if (m_box->frame() && m_box->frame()->page()) {
+ if (ScrollingCoordinator* scrollingCoordinator = m_box->frame()->page()->scrollingCoordinator())
scrollingCoordinator->willDestroyScrollableArea(this);
}
- if (!renderer()->documentBeingDestroyed()) {
- Node* node = renderer()->node();
+ if (!m_box->documentBeingDestroyed()) {
+ Node* node = m_box->node();
if (node && node->isElementNode())
toElement(node)->setSavedLayerScrollOffset(m_scrollOffset);
}
+ if (Frame* frame = m_box->frame()) {
+ if (FrameView* frameView = frame->view())
+ frameView->removeResizerArea(m_box);
+ }
+
destroyScrollbar(HorizontalScrollbar);
destroyScrollbar(VerticalScrollbar);
if (m_scrollCorner)
m_scrollCorner->destroy();
+ if (m_resizer)
+ m_resizer->destroy();
}
ScrollableArea* RenderLayerScrollableArea::enclosingScrollableArea() const
{
- return m_layer->enclosingScrollableArea();
-}
+ if (RenderBox* enclosingScrollableBox = m_box->enclosingScrollableBox())
+ return enclosingScrollableBox->layer()->scrollableArea();
-void RenderLayerScrollableArea::updateNeedsCompositedScrolling()
-{
- m_layer->updateNeedsCompositedScrolling();
+ // FIXME: We should return the frame view here (or possibly an ancestor frame view,
+ // if the frame view isn't scrollable.
+ return 0;
}
GraphicsLayer* RenderLayerScrollableArea::layerForScrolling() const
{
- return m_layer->layerForScrolling();
+ return m_box->hasCompositedLayerMapping() ? m_box->compositedLayerMapping()->scrollingContentsLayer() : 0;
}
GraphicsLayer* RenderLayerScrollableArea::layerForHorizontalScrollbar() const
{
- return m_layer->layerForHorizontalScrollbar();
+ return m_box->hasCompositedLayerMapping() ? m_box->compositedLayerMapping()->layerForHorizontalScrollbar() : 0;
}
GraphicsLayer* RenderLayerScrollableArea::layerForVerticalScrollbar() const
{
- return m_layer->layerForVerticalScrollbar();
+ return m_box->hasCompositedLayerMapping() ? m_box->compositedLayerMapping()->layerForVerticalScrollbar() : 0;
}
GraphicsLayer* RenderLayerScrollableArea::layerForScrollCorner() const
{
- return m_layer->layerForScrollCorner();
-}
-
-bool RenderLayerScrollableArea::usesCompositedScrolling() const
-{
- return m_layer->usesCompositedScrolling();
+ return m_box->hasCompositedLayerMapping() ? m_box->compositedLayerMapping()->layerForScrollCorner() : 0;
}
void RenderLayerScrollableArea::invalidateScrollbarRect(Scrollbar* scrollbar, const IntRect& rect)
@@ -158,16 +183,15 @@ void RenderLayerScrollableArea::invalidateScrollbarRect(Scrollbar* scrollbar, co
}
IntRect scrollRect = rect;
- RenderBox* box = toRenderBox(renderer());
// If we are not yet inserted into the tree, there is no need to repaint.
- if (!box->parent())
+ if (!m_box->parent())
return;
if (scrollbar == m_vBar.get())
- scrollRect.move(verticalScrollbarStart(0, box->width()), box->borderTop());
+ scrollRect.move(verticalScrollbarStart(0, m_box->width()), m_box->borderTop());
else
- scrollRect.move(horizontalScrollbarStart(0), box->height() - box->borderBottom() - scrollbar->height());
- renderer()->repaintRectangle(scrollRect);
+ scrollRect.move(horizontalScrollbarStart(0), m_box->height() - m_box->borderBottom() - scrollbar->height());
+ m_box->repaintRectangle(scrollRect);
}
void RenderLayerScrollableArea::invalidateScrollCornerRect(const IntRect& rect)
@@ -179,65 +203,108 @@ void RenderLayerScrollableArea::invalidateScrollCornerRect(const IntRect& rect)
if (m_scrollCorner)
m_scrollCorner->repaintRectangle(rect);
- m_layer->invalidateScrollCornerRect(rect);
+ if (m_resizer)
+ m_resizer->repaintRectangle(rect);
}
bool RenderLayerScrollableArea::isActive() const
{
- return m_layer->isActive();
+ Page* page = m_box->frame()->page();
+ return page && page->focusController().isActive();
}
bool RenderLayerScrollableArea::isScrollCornerVisible() const
{
- return m_layer->isScrollCornerVisible();
+ return !scrollCornerRect().isEmpty();
+}
+
+static int cornerStart(const RenderStyle* style, int minX, int maxX, int thickness)
+{
+ if (style->shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
+ return minX + style->borderLeftWidth();
+ return maxX - thickness - style->borderRightWidth();
}
+static IntRect cornerRect(const RenderStyle* style, const Scrollbar* horizontalScrollbar, const Scrollbar* verticalScrollbar, const IntRect& bounds)
+{
+ int horizontalThickness;
+ int verticalThickness;
+ if (!verticalScrollbar && !horizontalScrollbar) {
+ // FIXME: This isn't right. We need to know the thickness of custom scrollbars
+ // even when they don't exist in order to set the resizer square size properly.
+ horizontalThickness = ScrollbarTheme::theme()->scrollbarThickness();
+ verticalThickness = horizontalThickness;
+ } else if (verticalScrollbar && !horizontalScrollbar) {
+ horizontalThickness = verticalScrollbar->width();
+ verticalThickness = horizontalThickness;
+ } else if (horizontalScrollbar && !verticalScrollbar) {
+ verticalThickness = horizontalScrollbar->height();
+ horizontalThickness = verticalThickness;
+ } else {
+ horizontalThickness = verticalScrollbar->width();
+ verticalThickness = horizontalScrollbar->height();
+ }
+ return IntRect(cornerStart(style, bounds.x(), bounds.maxX(), horizontalThickness),
+ bounds.maxY() - verticalThickness - style->borderBottomWidth(),
+ horizontalThickness, verticalThickness);
+}
+
+
IntRect RenderLayerScrollableArea::scrollCornerRect() const
{
- return m_layer->scrollCornerRect();
+ // We have a scrollbar corner when a scrollbar is visible and not filling the entire length of the box.
+ // This happens when:
+ // (a) A resizer is present and at least one scrollbar is present
+ // (b) Both scrollbars are present.
+ bool hasHorizontalBar = horizontalScrollbar();
+ bool hasVerticalBar = verticalScrollbar();
+ bool hasResizer = m_box->style()->resize() != RESIZE_NONE;
+ if ((hasHorizontalBar && hasVerticalBar) || (hasResizer && (hasHorizontalBar || hasVerticalBar)))
+ return cornerRect(m_box->style(), horizontalScrollbar(), verticalScrollbar(), m_box->pixelSnappedBorderBoxRect());
+ return IntRect();
}
IntRect RenderLayerScrollableArea::convertFromScrollbarToContainingView(const Scrollbar* scrollbar, const IntRect& scrollbarRect) const
{
- RenderView* view = renderer()->view();
+ RenderView* view = m_box->view();
if (!view)
return scrollbarRect;
IntRect rect = scrollbarRect;
rect.move(scrollbarOffset(scrollbar));
- return view->frameView()->convertFromRenderer(renderer(), rect);
+ return view->frameView()->convertFromRenderer(m_box, rect);
}
IntRect RenderLayerScrollableArea::convertFromContainingViewToScrollbar(const Scrollbar* scrollbar, const IntRect& parentRect) const
{
- RenderView* view = renderer()->view();
+ RenderView* view = m_box->view();
if (!view)
return parentRect;
- IntRect rect = view->frameView()->convertToRenderer(renderer(), parentRect);
+ IntRect rect = view->frameView()->convertToRenderer(m_box, parentRect);
rect.move(-scrollbarOffset(scrollbar));
return rect;
}
IntPoint RenderLayerScrollableArea::convertFromScrollbarToContainingView(const Scrollbar* scrollbar, const IntPoint& scrollbarPoint) const
{
- RenderView* view = renderer()->view();
+ RenderView* view = m_box->view();
if (!view)
return scrollbarPoint;
IntPoint point = scrollbarPoint;
point.move(scrollbarOffset(scrollbar));
- return view->frameView()->convertFromRenderer(renderer(), point);
+ return view->frameView()->convertFromRenderer(m_box, point);
}
IntPoint RenderLayerScrollableArea::convertFromContainingViewToScrollbar(const Scrollbar* scrollbar, const IntPoint& parentPoint) const
{
- RenderView* view = renderer()->view();
+ RenderView* view = m_box->view();
if (!view)
return parentPoint;
- IntPoint point = view->frameView()->convertToRenderer(renderer(), parentPoint);
+ IntPoint point = view->frameView()->convertToRenderer(m_box, parentPoint);
point.move(-scrollbarOffset(scrollbar));
return point;
@@ -245,12 +312,13 @@ IntPoint RenderLayerScrollableArea::convertFromContainingViewToScrollbar(const S
int RenderLayerScrollableArea::scrollSize(ScrollbarOrientation orientation) const
{
- return m_layer->scrollSize(orientation);
+ IntSize scrollDimensions = maximumScrollPosition() - minimumScrollPosition();
+ return (orientation == HorizontalScrollbar) ? scrollDimensions.width() : scrollDimensions.height();
}
void RenderLayerScrollableArea::setScrollOffset(const IntPoint& newScrollOffset)
{
- if (!toRenderBox(renderer())->isMarquee()) {
+ if (!m_box->isMarquee()) {
// Ensure that the dimensions will be computed if they need to be (for overflow:hidden blocks).
if (m_scrollDimensionsDirty)
computeScrollDimensions();
@@ -261,10 +329,10 @@ void RenderLayerScrollableArea::setScrollOffset(const IntPoint& newScrollOffset)
setScrollOffset(toIntSize(newScrollOffset));
- Frame* frame = renderer()->frame();
- InspectorInstrumentation::willScrollLayer(renderer());
+ Frame* frame = m_box->frame();
+ InspectorInstrumentation::willScrollLayer(m_box);
- RenderView* view = renderer()->view();
+ RenderView* view = m_box->view();
// We should have a RenderView if we're trying to scroll.
ASSERT(view);
@@ -274,41 +342,49 @@ void RenderLayerScrollableArea::setScrollOffset(const IntPoint& newScrollOffset)
bool inLayout = view ? view->frameView()->isInLayout() : false;
if (!inLayout) {
// If we're in the middle of layout, we'll just update layers once layout has finished.
- m_layer->updateLayerPositionsAfterOverflowScroll();
+ layer()->updateLayerPositionsAfterOverflowScroll();
if (view) {
// Update regions, scrolling may change the clip of a particular region.
view->frameView()->updateAnnotatedRegions();
view->updateWidgetPositions();
}
- m_layer->updateCompositingLayersAfterScroll();
+ updateCompositingLayersAfterScroll();
}
- RenderLayerModelObject* repaintContainer = renderer()->containerForRepaint();
+ RenderLayerModelObject* repaintContainer = m_box->containerForRepaint();
if (frame) {
// The caret rect needs to be invalidated after scrolling
frame->selection().setCaretRectNeedsUpdate();
- FloatQuad quadForFakeMouseMoveEvent = FloatQuad(m_layer->m_repaintRect);
+ FloatQuad quadForFakeMouseMoveEvent = FloatQuad(layer()->repainter().repaintRect());
if (repaintContainer)
quadForFakeMouseMoveEvent = repaintContainer->localToAbsoluteQuad(quadForFakeMouseMoveEvent);
- frame->eventHandler()->dispatchFakeMouseMoveEventSoonInQuad(quadForFakeMouseMoveEvent);
+ frame->eventHandler().dispatchFakeMouseMoveEventSoonInQuad(quadForFakeMouseMoveEvent);
}
bool requiresRepaint = true;
- if (m_layer->compositor()->inCompositingMode() && m_layer->usesCompositedScrolling())
- requiresRepaint = false;
+ if (m_box->view()->compositor()->inCompositingMode()) {
+ bool onlyScrolledCompositedLayers = scrollsOverflow()
+ && !layer()->hasVisibleNonLayerContent()
+ && !layer()->hasNonCompositedChild()
+ && !layer()->hasBlockSelectionGapBounds()
+ && !m_box->isMarquee();
+
+ if (usesCompositedScrolling() || onlyScrolledCompositedLayers)
+ requiresRepaint = false;
+ }
// Just schedule a full repaint of our object.
if (view && requiresRepaint)
- renderer()->repaintUsingContainer(repaintContainer, pixelSnappedIntRect(m_layer->m_repaintRect));
+ m_box->repaintUsingContainer(repaintContainer, pixelSnappedIntRect(layer()->repainter().repaintRect()));
// Schedule the scroll DOM event.
- if (renderer()->node())
- renderer()->node()->document().eventQueue()->enqueueOrDispatchScrollEvent(renderer()->node(), DocumentEventQueue::ScrollEventElementTarget);
+ if (m_box->node())
+ m_box->node()->document().enqueueScrollEventForNode(m_box->node());
- InspectorInstrumentation::didScrollLayer(renderer());
+ InspectorInstrumentation::didScrollLayer(m_box);
}
IntPoint RenderLayerScrollableArea::scrollPosition() const
@@ -323,15 +399,13 @@ IntPoint RenderLayerScrollableArea::minimumScrollPosition() const
IntPoint RenderLayerScrollableArea::maximumScrollPosition() const
{
- RenderBox* box = toRenderBox(renderer());
-
- if (!box->hasOverflowClip())
+ if (!m_box->hasOverflowClip())
return -scrollOrigin();
- return -scrollOrigin() + enclosingIntRect(m_overflowRect).size() - enclosingIntRect(box->clientBoxRect()).size();
+ return -scrollOrigin() + enclosingIntRect(m_overflowRect).size() - enclosingIntRect(m_box->clientBoxRect()).size();
}
-IntRect RenderLayerScrollableArea::visibleContentRect(VisibleContentRectIncludesScrollbars scrollbarInclusion) const
+IntRect RenderLayerScrollableArea::visibleContentRect(IncludeScrollbarsInRect scrollbarInclusion) const
{
int verticalScrollbarWidth = 0;
int horizontalScrollbarHeight = 0;
@@ -341,17 +415,17 @@ IntRect RenderLayerScrollableArea::visibleContentRect(VisibleContentRectIncludes
}
return IntRect(IntPoint(scrollXOffset(), scrollYOffset()),
- IntSize(max(0, m_layer->size().width() - verticalScrollbarWidth), max(0, m_layer->size().height() - horizontalScrollbarHeight)));
+ IntSize(max(0, layer()->size().width() - verticalScrollbarWidth), max(0, layer()->size().height() - horizontalScrollbarHeight)));
}
int RenderLayerScrollableArea::visibleHeight() const
{
- return m_layer->visibleHeight();
+ return layer()->size().height();
}
int RenderLayerScrollableArea::visibleWidth() const
{
- return m_layer->visibleWidth();
+ return layer()->size().width();
}
IntSize RenderLayerScrollableArea::contentsSize() const
@@ -361,78 +435,88 @@ IntSize RenderLayerScrollableArea::contentsSize() const
IntSize RenderLayerScrollableArea::overhangAmount() const
{
- return m_layer->overhangAmount();
+ return IntSize();
}
IntPoint RenderLayerScrollableArea::lastKnownMousePosition() const
{
- return m_layer->lastKnownMousePosition();
+ return m_box->frame() ? m_box->frame()->eventHandler().lastKnownMousePosition() : IntPoint();
}
bool RenderLayerScrollableArea::shouldSuspendScrollAnimations() const
{
- return m_layer->shouldSuspendScrollAnimations();
+ RenderView* view = m_box->view();
+ if (!view)
+ return true;
+ return view->frameView()->shouldSuspendScrollAnimations();
}
bool RenderLayerScrollableArea::scrollbarsCanBeActive() const
{
- return m_layer->scrollbarsCanBeActive();
+ RenderView* view = m_box->view();
+ if (!view)
+ return false;
+ return view->frameView()->scrollbarsCanBeActive();
}
IntRect RenderLayerScrollableArea::scrollableAreaBoundingBox() const
{
- return m_layer->scrollableAreaBoundingBox();
+ return m_box->absoluteBoundingBoxRect();
}
bool RenderLayerScrollableArea::userInputScrollable(ScrollbarOrientation orientation) const
{
- return m_layer->userInputScrollable(orientation);
+ if (m_box->isIntristicallyScrollable(orientation))
+ return true;
+
+ EOverflow overflowStyle = (orientation == HorizontalScrollbar) ?
+ m_box->style()->overflowX() : m_box->style()->overflowY();
+ return (overflowStyle == OSCROLL || overflowStyle == OAUTO || overflowStyle == OOVERLAY);
}
bool RenderLayerScrollableArea::shouldPlaceVerticalScrollbarOnLeft() const
{
- return m_layer->shouldPlaceVerticalScrollbarOnLeft();
+ return m_box->style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft();
}
int RenderLayerScrollableArea::pageStep(ScrollbarOrientation orientation) const
{
- return m_layer->pageStep(orientation);
+ int length = (orientation == HorizontalScrollbar) ?
+ m_box->pixelSnappedClientWidth() : m_box->pixelSnappedClientHeight();
+ int minPageStep = static_cast<float>(length) * ScrollableArea::minFractionToStepWhenPaging();
+ int pageStep = max(minPageStep, length - ScrollableArea::maxOverlapBetweenPages());
+
+ return max(pageStep, 1);
}
-RenderLayerModelObject* RenderLayerScrollableArea::renderer() const
+RenderLayer* RenderLayerScrollableArea::layer() const
{
- // Only RenderBoxes can have a scrollable area, however we allocate an
- // RenderLayerScrollableArea for any renderers (FIXME).
- return m_layer->renderer();
+ return m_box->layer();
}
int RenderLayerScrollableArea::scrollWidth() const
{
- RenderBox* box = toRenderBox(renderer());
if (m_scrollDimensionsDirty)
const_cast<RenderLayerScrollableArea*>(this)->computeScrollDimensions();
- return snapSizeToPixel(m_overflowRect.width(), box->clientLeft() + box->x());
+ return snapSizeToPixel(m_overflowRect.width(), m_box->clientLeft() + m_box->x());
}
int RenderLayerScrollableArea::scrollHeight() const
{
- RenderBox* box = toRenderBox(renderer());
if (m_scrollDimensionsDirty)
const_cast<RenderLayerScrollableArea*>(this)->computeScrollDimensions();
- return snapSizeToPixel(m_overflowRect.height(), box->clientTop() + box->y());
+ return snapSizeToPixel(m_overflowRect.height(), m_box->clientTop() + m_box->y());
}
void RenderLayerScrollableArea::computeScrollDimensions()
{
- RenderBox* box = toRenderBox(renderer());
-
m_scrollDimensionsDirty = false;
- m_overflowRect = box->layoutOverflowRect();
- box->flipForWritingMode(m_overflowRect);
+ m_overflowRect = m_box->layoutOverflowRect();
+ m_box->flipForWritingMode(m_overflowRect);
- int scrollableLeftOverflow = m_overflowRect.x() - box->borderLeft();
- int scrollableTopOverflow = m_overflowRect.y() - box->borderTop();
+ int scrollableLeftOverflow = m_overflowRect.x() - m_box->borderLeft() - (m_box->style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft() ? m_box->verticalScrollbarWidth() : 0);
+ int scrollableTopOverflow = m_overflowRect.y() - m_box->borderTop();
setScrollOrigin(IntPoint(-scrollableLeftOverflow, -scrollableTopOverflow));
}
@@ -445,9 +529,8 @@ void RenderLayerScrollableArea::scrollToOffset(const IntSize& scrollOffset, Scro
void RenderLayerScrollableArea::updateAfterLayout()
{
- RenderBox* box = toRenderBox(renderer());
// List box parts handle the scrollbars by themselves so we have nothing to do.
- if (box->style()->appearance() == ListboxPart)
+ if (m_box->style()->appearance() == ListboxPart)
return;
m_scrollDimensionsDirty = true;
@@ -455,7 +538,7 @@ void RenderLayerScrollableArea::updateAfterLayout()
computeScrollDimensions();
- if (!box->isMarquee()) {
+ if (!m_box->isMarquee()) {
// Layout may cause us to be at an invalid scroll position. In this case we need
// to pull our scroll offsets back to the max (or push them up to the min).
IntSize clampedScrollOffset = clampScrollOffset(adjustedScrollOffset());
@@ -470,41 +553,41 @@ void RenderLayerScrollableArea::updateAfterLayout()
bool hasVerticalOverflow = this->hasVerticalOverflow();
// overflow:scroll should just enable/disable.
- if (renderer()->style()->overflowX() == OSCROLL)
+ if (m_box->style()->overflowX() == OSCROLL)
horizontalScrollbar()->setEnabled(hasHorizontalOverflow);
- if (renderer()->style()->overflowY() == OSCROLL)
+ if (m_box->style()->overflowY() == OSCROLL)
verticalScrollbar()->setEnabled(hasVerticalOverflow);
// overflow:auto may need to lay out again if scrollbars got added/removed.
- bool autoHorizontalScrollBarChanged = box->hasAutoHorizontalScrollbar() && (hasHorizontalScrollbar() != hasHorizontalOverflow);
- bool autoVerticalScrollBarChanged = box->hasAutoVerticalScrollbar() && (hasVerticalScrollbar() != hasVerticalOverflow);
+ bool autoHorizontalScrollBarChanged = m_box->hasAutoHorizontalScrollbar() && (hasHorizontalScrollbar() != hasHorizontalOverflow);
+ bool autoVerticalScrollBarChanged = m_box->hasAutoVerticalScrollbar() && (hasVerticalScrollbar() != hasVerticalOverflow);
if (autoHorizontalScrollBarChanged || autoVerticalScrollBarChanged) {
- if (box->hasAutoHorizontalScrollbar())
+ if (m_box->hasAutoHorizontalScrollbar())
setHasHorizontalScrollbar(hasHorizontalOverflow);
- if (box->hasAutoVerticalScrollbar())
+ if (m_box->hasAutoVerticalScrollbar())
setHasVerticalScrollbar(hasVerticalOverflow);
- m_layer->updateSelfPaintingLayer();
+ layer()->updateSelfPaintingLayer();
// Force an update since we know the scrollbars have changed things.
- if (renderer()->document().hasAnnotatedRegions())
- renderer()->document().setAnnotatedRegionsDirty(true);
+ if (m_box->document().hasAnnotatedRegions())
+ m_box->document().setAnnotatedRegionsDirty(true);
- renderer()->repaint();
+ m_box->repaint();
- if (renderer()->style()->overflowX() == OAUTO || renderer()->style()->overflowY() == OAUTO) {
+ if (m_box->style()->overflowX() == OAUTO || m_box->style()->overflowY() == OAUTO) {
if (!m_inOverflowRelayout) {
// Our proprietary overflow: overlay value doesn't trigger a layout.
m_inOverflowRelayout = true;
- SubtreeLayoutScope layoutScope(renderer());
- layoutScope.setNeedsLayout(renderer());
- if (renderer()->isRenderBlock()) {
- RenderBlock* block = toRenderBlock(renderer());
+ SubtreeLayoutScope layoutScope(m_box);
+ layoutScope.setNeedsLayout(m_box);
+ if (m_box->isRenderBlock()) {
+ RenderBlock* block = toRenderBlock(m_box);
block->scrollbarsChanged(autoHorizontalScrollBarChanged, autoVerticalScrollBarChanged);
block->layoutBlock(true);
} else {
- renderer()->layout();
+ m_box->layout();
}
m_inOverflowRelayout = false;
}
@@ -513,39 +596,43 @@ void RenderLayerScrollableArea::updateAfterLayout()
// Set up the range (and page step/line step).
if (Scrollbar* horizontalScrollbar = this->horizontalScrollbar()) {
- int clientWidth = box->pixelSnappedClientWidth();
+ int clientWidth = m_box->pixelSnappedClientWidth();
horizontalScrollbar->setProportion(clientWidth, overflowRect().width());
}
if (Scrollbar* verticalScrollbar = this->verticalScrollbar()) {
- int clientHeight = box->pixelSnappedClientHeight();
+ int clientHeight = m_box->pixelSnappedClientHeight();
verticalScrollbar->setProportion(clientHeight, overflowRect().height());
}
- m_layer->updateScrollableAreaSet(hasScrollableHorizontalOverflow() || hasScrollableVerticalOverflow());
+ updateScrollableAreaSet(hasScrollableHorizontalOverflow() || hasScrollableVerticalOverflow());
+
+ // Composited scrolling may need to be enabled or disabled if the amount of overflow changed.
+ if (m_box->view() && m_box->view()->compositor()->updateLayerCompositingState(m_box->layer()))
+ m_box->view()->compositor()->setCompositingLayersNeedRebuild();
}
bool RenderLayerScrollableArea::hasHorizontalOverflow() const
{
ASSERT(!m_scrollDimensionsDirty);
- return scrollWidth() > toRenderBox(renderer())->pixelSnappedClientWidth();
+ return scrollWidth() > m_box->pixelSnappedClientWidth();
}
bool RenderLayerScrollableArea::hasVerticalOverflow() const
{
ASSERT(!m_scrollDimensionsDirty);
- return scrollHeight() > toRenderBox(renderer())->pixelSnappedClientHeight();
+ return scrollHeight() > m_box->pixelSnappedClientHeight();
}
bool RenderLayerScrollableArea::hasScrollableHorizontalOverflow() const
{
- return hasHorizontalOverflow() && toRenderBox(renderer())->scrollsOverflowX();
+ return hasHorizontalOverflow() && m_box->scrollsOverflowX();
}
bool RenderLayerScrollableArea::hasScrollableVerticalOverflow() const
{
- return hasVerticalOverflow() && toRenderBox(renderer())->scrollsOverflowY();
+ return hasVerticalOverflow() && m_box->scrollsOverflowY();
}
static bool overflowRequiresScrollbar(EOverflow overflow)
@@ -560,21 +647,15 @@ static bool overflowDefinesAutomaticScrollbar(EOverflow overflow)
void RenderLayerScrollableArea::updateAfterStyleChange(const RenderStyle* oldStyle)
{
- // Overflow are a box concept.
- if (!renderer()->isBox())
- return;
-
- RenderBox* box = toRenderBox(renderer());
-
// List box parts handle the scrollbars by themselves so we have nothing to do.
- if (box->style()->appearance() == ListboxPart)
+ if (m_box->style()->appearance() == ListboxPart)
return;
if (!m_scrollDimensionsDirty)
- m_layer->updateScrollableAreaSet(hasScrollableHorizontalOverflow() || hasScrollableVerticalOverflow());
+ updateScrollableAreaSet(hasScrollableHorizontalOverflow() || hasScrollableVerticalOverflow());
- EOverflow overflowX = box->style()->overflowX();
- EOverflow overflowY = box->style()->overflowY();
+ EOverflow overflowX = m_box->style()->overflowX();
+ EOverflow overflowY = m_box->style()->overflowY();
// To avoid doing a relayout in updateScrollbarsAfterLayout, we try to keep any automatic scrollbar that was already present.
bool needsHorizontalScrollbar = (hasHorizontalScrollbar() && overflowDefinesAutomaticScrollbar(overflowX)) || overflowRequiresScrollbar(overflowX);
@@ -601,14 +682,14 @@ void RenderLayerScrollableArea::updateAfterStyleChange(const RenderStyle* oldSty
m_vBar->styleChanged();
updateScrollCornerStyle();
+ updateResizerAreaSet();
+ updateResizerStyle();
}
IntSize RenderLayerScrollableArea::clampScrollOffset(const IntSize& scrollOffset) const
{
- RenderBox* box = toRenderBox(renderer());
-
- int maxX = scrollWidth() - box->pixelSnappedClientWidth();
- int maxY = scrollHeight() - box->pixelSnappedClientHeight();
+ int maxX = scrollWidth() - m_box->pixelSnappedClientWidth();
+ int maxY = scrollHeight() - m_box->pixelSnappedClientHeight();
int x = std::max(std::min(scrollOffset.width(), maxX), 0);
int y = std::max(std::min(scrollOffset.height(), maxY), 0);
@@ -620,12 +701,11 @@ IntRect RenderLayerScrollableArea::rectForHorizontalScrollbar(const IntRect& bor
if (!m_hBar)
return IntRect();
- const RenderBox* box = toRenderBox(renderer());
const IntRect& scrollCorner = scrollCornerRect();
return IntRect(horizontalScrollbarStart(borderBoxRect.x()),
- borderBoxRect.maxY() - box->borderBottom() - m_hBar->height(),
- borderBoxRect.width() - (box->borderLeft() + box->borderRight()) - scrollCorner.width(),
+ borderBoxRect.maxY() - m_box->borderBottom() - m_hBar->height(),
+ borderBoxRect.width() - (m_box->borderLeft() + m_box->borderRight()) - scrollCorner.width(),
m_hBar->height());
}
@@ -634,41 +714,36 @@ IntRect RenderLayerScrollableArea::rectForVerticalScrollbar(const IntRect& borde
if (!m_vBar)
return IntRect();
- const RenderBox* box = toRenderBox(renderer());
const IntRect& scrollCorner = scrollCornerRect();
return IntRect(verticalScrollbarStart(borderBoxRect.x(), borderBoxRect.maxX()),
- borderBoxRect.y() + box->borderTop(),
+ borderBoxRect.y() + m_box->borderTop(),
m_vBar->width(),
- borderBoxRect.height() - (box->borderTop() + box->borderBottom()) - scrollCorner.height());
+ borderBoxRect.height() - (m_box->borderTop() + m_box->borderBottom()) - scrollCorner.height());
}
LayoutUnit RenderLayerScrollableArea::verticalScrollbarStart(int minX, int maxX) const
{
- const RenderBox* box = toRenderBox(renderer());
- if (renderer()->style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
- return minX + box->borderLeft();
- return maxX - box->borderRight() - m_vBar->width();
+ if (m_box->style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
+ return minX + m_box->borderLeft();
+ return maxX - m_box->borderRight() - m_vBar->width();
}
LayoutUnit RenderLayerScrollableArea::horizontalScrollbarStart(int minX) const
{
- const RenderBox* box = toRenderBox(renderer());
- int x = minX + box->borderLeft();
- if (renderer()->style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
- x += m_vBar ? m_vBar->width() : m_layer->resizerCornerRect(box->pixelSnappedBorderBoxRect(), ResizerForPointer).width();
+ int x = minX + m_box->borderLeft();
+ if (m_box->style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
+ x += m_vBar ? m_vBar->width() : resizerCornerRect(m_box->pixelSnappedBorderBoxRect(), ResizerForPointer).width();
return x;
}
IntSize RenderLayerScrollableArea::scrollbarOffset(const Scrollbar* scrollbar) const
{
- RenderBox* box = toRenderBox(renderer());
-
if (scrollbar == m_vBar.get())
- return IntSize(verticalScrollbarStart(0, box->width()), box->borderTop());
+ return IntSize(verticalScrollbarStart(0, m_box->width()), m_box->borderTop());
if (scrollbar == m_hBar.get())
- return IntSize(horizontalScrollbarStart(0), box->height() - box->borderBottom() - scrollbar->height());
+ return IntSize(horizontalScrollbarStart(0), m_box->height() - m_box->borderBottom() - scrollbar->height());
ASSERT_NOT_REACHED();
return IntSize();
@@ -689,18 +764,18 @@ static inline RenderObject* rendererForScrollbar(RenderObject* renderer)
PassRefPtr<Scrollbar> RenderLayerScrollableArea::createScrollbar(ScrollbarOrientation orientation)
{
RefPtr<Scrollbar> widget;
- RenderObject* actualRenderer = rendererForScrollbar(renderer());
+ RenderObject* actualRenderer = rendererForScrollbar(m_box);
bool hasCustomScrollbarStyle = actualRenderer->isBox() && actualRenderer->style()->hasPseudoStyle(SCROLLBAR);
if (hasCustomScrollbarStyle) {
widget = RenderScrollbar::createCustomScrollbar(this, orientation, actualRenderer->node());
} else {
widget = Scrollbar::create(this, orientation, RegularScrollbar);
if (orientation == HorizontalScrollbar)
- didAddHorizontalScrollbar(widget.get());
+ didAddScrollbar(widget.get(), HorizontalScrollbar);
else
- didAddVerticalScrollbar(widget.get());
+ didAddScrollbar(widget.get(), VerticalScrollbar);
}
- renderer()->document().view()->addChild(widget.get());
+ m_box->document().view()->addChild(widget.get());
return widget.release();
}
@@ -710,12 +785,8 @@ void RenderLayerScrollableArea::destroyScrollbar(ScrollbarOrientation orientatio
if (!scrollbar)
return;
- if (!scrollbar->isCustomScrollbar()) {
- if (orientation == HorizontalScrollbar)
- willRemoveHorizontalScrollbar(scrollbar.get());
- else
- willRemoveVerticalScrollbar(scrollbar.get());
- }
+ if (!scrollbar->isCustomScrollbar())
+ willRemoveScrollbar(scrollbar.get(), orientation);
scrollbar->removeFromParent();
scrollbar->disconnectFromScrollableArea();
@@ -739,8 +810,8 @@ void RenderLayerScrollableArea::setHasHorizontalScrollbar(bool hasScrollbar)
m_vBar->styleChanged();
// Force an update since we know the scrollbars have changed things.
- if (renderer()->document().hasAnnotatedRegions())
- renderer()->document().setAnnotatedRegionsDirty(true);
+ if (m_box->document().hasAnnotatedRegions())
+ m_box->document().setAnnotatedRegionsDirty(true);
}
void RenderLayerScrollableArea::setHasVerticalScrollbar(bool hasScrollbar)
@@ -760,8 +831,8 @@ void RenderLayerScrollableArea::setHasVerticalScrollbar(bool hasScrollbar)
m_vBar->styleChanged();
// Force an update since we know the scrollbars have changed things.
- if (renderer()->document().hasAnnotatedRegions())
- renderer()->document().setAnnotatedRegionsDirty(true);
+ if (m_box->document().hasAnnotatedRegions())
+ m_box->document().setAnnotatedRegionsDirty(true);
}
int RenderLayerScrollableArea::verticalScrollbarWidth(OverlayScrollbarSizeRelevancy relevancy) const
@@ -778,10 +849,23 @@ int RenderLayerScrollableArea::horizontalScrollbarHeight(OverlayScrollbarSizeRel
return m_hBar->height();
}
+void RenderLayerScrollableArea::positionOverflowControls()
+{
+ RenderGeometryMap geometryMap(UseTransforms);
+ RenderView* view = m_box->view();
+ if (m_box->layer() != view->layer() && m_box->layer()->parent())
+ geometryMap.pushMappingsToAncestor(m_box->layer()->parent(), 0);
+
+ LayoutPoint offsetFromRoot = LayoutPoint(geometryMap.absolutePoint(FloatPoint()));
+ positionOverflowControls(toIntSize(roundedIntPoint(offsetFromRoot)));
+}
void RenderLayerScrollableArea::positionOverflowControls(const IntSize& offsetFromRoot)
{
- const IntRect borderBox = toRenderBox(renderer())->pixelSnappedBorderBoxRect();
+ if (!hasScrollbar() && !m_box->canResize())
+ return;
+
+ const IntRect borderBox = m_box->pixelSnappedBorderBoxRect();
if (Scrollbar* verticalScrollbar = this->verticalScrollbar()) {
IntRect vBarRect = rectForVerticalScrollbar(borderBox);
vBarRect.move(offsetFromRoot);
@@ -797,16 +881,33 @@ void RenderLayerScrollableArea::positionOverflowControls(const IntSize& offsetFr
const IntRect& scrollCorner = scrollCornerRect();
if (m_scrollCorner)
m_scrollCorner->setFrameRect(scrollCorner);
+
+ if (m_resizer)
+ m_resizer->setFrameRect(resizerCornerRect(borderBox, ResizerForPointer));
+
+ // FIXME, this should eventually be removed, once we are certain that composited
+ // controls get correctly positioned on a compositor update. For now, conservatively
+ // leaving this unchanged.
+ if (m_box->hasCompositedLayerMapping())
+ m_box->compositedLayerMapping()->positionOverflowControlsLayers(offsetFromRoot);
+}
+
+bool RenderLayerScrollableArea::scrollsOverflow() const
+{
+ if (FrameView* frameView = m_box->view()->frameView())
+ return frameView->containsScrollableArea(this);
+
+ return false;
}
void RenderLayerScrollableArea::updateScrollCornerStyle()
{
- RenderObject* actualRenderer = rendererForScrollbar(renderer());
- RefPtr<RenderStyle> corner = renderer()->hasOverflowClip() ? actualRenderer->getUncachedPseudoStyle(PseudoStyleRequest(SCROLLBAR_CORNER), actualRenderer->style()) : PassRefPtr<RenderStyle>(0);
+ RenderObject* actualRenderer = rendererForScrollbar(m_box);
+ RefPtr<RenderStyle> corner = m_box->hasOverflowClip() ? actualRenderer->getUncachedPseudoStyle(PseudoStyleRequest(SCROLLBAR_CORNER), actualRenderer->style()) : PassRefPtr<RenderStyle>(0);
if (corner) {
if (!m_scrollCorner) {
- m_scrollCorner = RenderScrollbarPart::createAnonymous(&renderer()->document());
- m_scrollCorner->setParent(renderer());
+ m_scrollCorner = RenderScrollbarPart::createAnonymous(&m_box->document());
+ m_scrollCorner->setParent(m_box);
}
m_scrollCorner->setStyle(corner.release());
} else if (m_scrollCorner) {
@@ -815,9 +916,21 @@ void RenderLayerScrollableArea::updateScrollCornerStyle()
}
}
-// FIXME: Move m_cachedOverlayScrollbarOffset.
void RenderLayerScrollableArea::paintOverflowControls(GraphicsContext* context, const IntPoint& paintOffset, const IntRect& damageRect, bool paintingOverlayControls)
{
+ // Don't do anything if we have no overflow.
+ if (!m_box->hasOverflowClip())
+ return;
+
+ IntPoint adjustedPaintOffset = paintOffset;
+ if (paintingOverlayControls)
+ adjustedPaintOffset = m_cachedOverlayScrollbarOffset;
+
+ // Move the scrollbar widgets if necessary. We normally move and resize widgets during layout,
+ // but sometimes widgets can move without layout occurring (most notably when you scroll a
+ // document that contains fixed positioned elements).
+ positionOverflowControls(toIntSize(adjustedPaintOffset));
+
// Overlay scrollbars paint in a second pass through the layer tree so that they will paint
// on top of everything else. If this is the normal painting pass, paintingOverlayControls
// will be false, and we should just tell the root layer that there are overlay scrollbars
@@ -825,18 +938,18 @@ void RenderLayerScrollableArea::paintOverflowControls(GraphicsContext* context,
// and we'll paint the scrollbars then. In the meantime, cache tx and ty so that the
// second pass doesn't need to re-enter the RenderTree to get it right.
if (hasOverlayScrollbars() && !paintingOverlayControls) {
- m_layer->m_cachedOverlayScrollbarOffset = paintOffset;
+ m_cachedOverlayScrollbarOffset = paintOffset;
// It's not necessary to do the second pass if the scrollbars paint into layers.
if ((m_hBar && layerForHorizontalScrollbar()) || (m_vBar && layerForVerticalScrollbar()))
return;
IntRect localDamgeRect = damageRect;
localDamgeRect.moveBy(-paintOffset);
- if (!m_layer->overflowControlsIntersectRect(localDamgeRect))
+ if (!overflowControlsIntersectRect(localDamgeRect))
return;
- RenderView* renderView = renderer()->view();
+ RenderView* renderView = m_box->view();
- RenderLayer* paintingRoot = m_layer->enclosingCompositingLayer();
+ RenderLayer* paintingRoot = layer()->enclosingCompositingLayer();
if (!paintingRoot)
paintingRoot = renderView->layer();
@@ -859,17 +972,14 @@ void RenderLayerScrollableArea::paintOverflowControls(GraphicsContext* context,
// We fill our scroll corner with white if we have a scrollbar that doesn't run all the way up to the
// edge of the box.
- IntPoint adjustedPaintOffset = paintOffset;
- if (paintingOverlayControls)
- adjustedPaintOffset = m_layer->m_cachedOverlayScrollbarOffset;
-
paintScrollCorner(context, adjustedPaintOffset, damageRect);
+
+ // Paint our resizer last, since it sits on top of the scroll corner.
+ paintResizer(context, adjustedPaintOffset, damageRect);
}
void RenderLayerScrollableArea::paintScrollCorner(GraphicsContext* context, const IntPoint& paintOffset, const IntRect& damageRect)
{
- ASSERT(renderer()->isBox());
-
IntRect absRect = scrollCornerRect();
absRect.moveBy(paintOffset);
if (!absRect.intersects(damageRect))
@@ -891,16 +1001,24 @@ void RenderLayerScrollableArea::paintScrollCorner(GraphicsContext* context, cons
context->fillRect(absRect, Color::white);
}
-bool RenderLayerScrollableArea::hitTestOverflowControls(HitTestResult& result, const IntPoint& localPoint, const IntRect& resizeControlRect)
+bool RenderLayerScrollableArea::hitTestOverflowControls(HitTestResult& result, const IntPoint& localPoint)
{
- RenderBox* box = toRenderBox(renderer());
+ if (!hasScrollbar() && !m_box->canResize())
+ return false;
+
+ IntRect resizeControlRect;
+ if (m_box->style()->resize() != RESIZE_NONE) {
+ resizeControlRect = resizerCornerRect(m_box->pixelSnappedBorderBoxRect(), ResizerForPointer);
+ if (resizeControlRect.contains(localPoint))
+ return true;
+ }
int resizeControlSize = max(resizeControlRect.height(), 0);
if (m_vBar && m_vBar->shouldParticipateInHitTesting()) {
- LayoutRect vBarRect(verticalScrollbarStart(0, box->width()),
- box->borderTop(),
+ LayoutRect vBarRect(verticalScrollbarStart(0, m_box->width()),
+ m_box->borderTop(),
m_vBar->width(),
- box->height() - (box->borderTop() + box->borderBottom()) - (m_hBar ? m_hBar->height() : resizeControlSize));
+ m_box->height() - (m_box->borderTop() + m_box->borderBottom()) - (m_hBar ? m_hBar->height() : resizeControlSize));
if (vBarRect.contains(localPoint)) {
result.setScrollbar(m_vBar.get());
return true;
@@ -910,8 +1028,8 @@ bool RenderLayerScrollableArea::hitTestOverflowControls(HitTestResult& result, c
resizeControlSize = max(resizeControlRect.width(), 0);
if (m_hBar && m_hBar->shouldParticipateInHitTesting()) {
LayoutRect hBarRect(horizontalScrollbarStart(0),
- box->height() - box->borderBottom() - m_hBar->height(),
- box->width() - (box->borderLeft() + box->borderRight()) - (m_vBar ? m_vBar->width() : resizeControlSize),
+ m_box->height() - m_box->borderBottom() - m_hBar->height(),
+ m_box->width() - (m_box->borderLeft() + m_box->borderRight()) - (m_vBar ? m_vBar->width() : resizeControlSize),
m_hBar->height());
if (hBarRect.contains(localPoint)) {
result.setScrollbar(m_hBar.get());
@@ -924,4 +1042,434 @@ bool RenderLayerScrollableArea::hitTestOverflowControls(HitTestResult& result, c
return false;
}
+IntRect RenderLayerScrollableArea::resizerCornerRect(const IntRect& bounds, ResizerHitTestType resizerHitTestType) const
+{
+ if (m_box->style()->resize() == RESIZE_NONE)
+ return IntRect();
+ IntRect corner = cornerRect(m_box->style(), horizontalScrollbar(), verticalScrollbar(), bounds);
+
+ if (resizerHitTestType == ResizerForTouch) {
+ // We make the resizer virtually larger for touch hit testing. With the
+ // expanding ratio k = ResizerControlExpandRatioForTouch, we first move
+ // the resizer rect (of width w & height h), by (-w * (k-1), -h * (k-1)),
+ // then expand the rect by new_w/h = w/h * k.
+ int expandRatio = ResizerControlExpandRatioForTouch - 1;
+ corner.move(-corner.width() * expandRatio, -corner.height() * expandRatio);
+ corner.expand(corner.width() * expandRatio, corner.height() * expandRatio);
+ }
+
+ return corner;
+}
+
+IntRect RenderLayerScrollableArea::scrollCornerAndResizerRect() const
+{
+ IntRect scrollCornerAndResizer = scrollCornerRect();
+ if (scrollCornerAndResizer.isEmpty())
+ scrollCornerAndResizer = resizerCornerRect(m_box->pixelSnappedBorderBoxRect(), ResizerForPointer);
+ return scrollCornerAndResizer;
+}
+
+bool RenderLayerScrollableArea::overflowControlsIntersectRect(const IntRect& localRect) const
+{
+ const IntRect borderBox = m_box->pixelSnappedBorderBoxRect();
+
+ if (rectForHorizontalScrollbar(borderBox).intersects(localRect))
+ return true;
+
+ if (rectForVerticalScrollbar(borderBox).intersects(localRect))
+ return true;
+
+ if (scrollCornerRect().intersects(localRect))
+ return true;
+
+ if (resizerCornerRect(borderBox, ResizerForPointer).intersects(localRect))
+ return true;
+
+ return false;
+}
+
+void RenderLayerScrollableArea::paintResizer(GraphicsContext* context, const IntPoint& paintOffset, const IntRect& damageRect)
+{
+ if (m_box->style()->resize() == RESIZE_NONE)
+ return;
+
+ IntRect absRect = resizerCornerRect(m_box->pixelSnappedBorderBoxRect(), ResizerForPointer);
+ absRect.moveBy(paintOffset);
+ if (!absRect.intersects(damageRect))
+ return;
+
+ if (context->updatingControlTints()) {
+ updateResizerStyle();
+ return;
+ }
+
+ if (m_resizer) {
+ m_resizer->paintIntoRect(context, paintOffset, absRect);
+ return;
+ }
+
+ drawPlatformResizerImage(context, absRect);
+
+ // Draw a frame around the resizer (1px grey line) if there are any scrollbars present.
+ // Clipping will exclude the right and bottom edges of this frame.
+ if (!hasOverlayScrollbars() && hasScrollbar()) {
+ GraphicsContextStateSaver stateSaver(*context);
+ context->clip(absRect);
+ IntRect largerCorner = absRect;
+ largerCorner.setSize(IntSize(largerCorner.width() + 1, largerCorner.height() + 1));
+ context->setStrokeColor(Color(217, 217, 217));
+ context->setStrokeThickness(1.0f);
+ context->setFillColor(Color::transparent);
+ context->drawRect(largerCorner);
+ }
+}
+
+bool RenderLayerScrollableArea::isPointInResizeControl(const IntPoint& absolutePoint, ResizerHitTestType resizerHitTestType) const
+{
+ if (!m_box->canResize())
+ return false;
+
+ IntPoint localPoint = roundedIntPoint(m_box->absoluteToLocal(absolutePoint, UseTransforms));
+ IntRect localBounds(0, 0, m_box->pixelSnappedWidth(), m_box->pixelSnappedHeight());
+ return resizerCornerRect(localBounds, resizerHitTestType).contains(localPoint);
+}
+
+bool RenderLayerScrollableArea::hitTestResizerInFragments(const LayerFragments& layerFragments, const HitTestLocation& hitTestLocation) const
+{
+ if (!m_box->canResize())
+ return false;
+
+ if (layerFragments.isEmpty())
+ return false;
+
+ for (int i = layerFragments.size() - 1; i >= 0; --i) {
+ const LayerFragment& fragment = layerFragments.at(i);
+ if (fragment.backgroundRect.intersects(hitTestLocation) && resizerCornerRect(pixelSnappedIntRect(fragment.layerBounds), ResizerForPointer).contains(hitTestLocation.roundedPoint()))
+ return true;
+ }
+
+ return false;
+}
+
+void RenderLayerScrollableArea::updateResizerAreaSet()
+{
+ Frame* frame = m_box->frame();
+ if (!frame)
+ return;
+ FrameView* frameView = frame->view();
+ if (!frameView)
+ return;
+ if (m_box->canResize())
+ frameView->addResizerArea(m_box);
+ else
+ frameView->removeResizerArea(m_box);
+}
+
+void RenderLayerScrollableArea::updateResizerStyle()
+{
+ RenderObject* actualRenderer = rendererForScrollbar(m_box);
+ RefPtr<RenderStyle> resizer = m_box->hasOverflowClip() ? actualRenderer->getUncachedPseudoStyle(PseudoStyleRequest(RESIZER), actualRenderer->style()) : PassRefPtr<RenderStyle>(0);
+ if (resizer) {
+ if (!m_resizer) {
+ m_resizer = RenderScrollbarPart::createAnonymous(&m_box->document());
+ m_resizer->setParent(m_box);
+ }
+ m_resizer->setStyle(resizer.release());
+ } else if (m_resizer) {
+ m_resizer->destroy();
+ m_resizer = 0;
+ }
+}
+
+void RenderLayerScrollableArea::drawPlatformResizerImage(GraphicsContext* context, IntRect resizerCornerRect)
+{
+ float deviceScaleFactor = WebCore::deviceScaleFactor(m_box->frame());
+
+ RefPtr<Image> resizeCornerImage;
+ IntSize cornerResizerSize;
+ if (deviceScaleFactor >= 2) {
+ DEFINE_STATIC_REF(Image, resizeCornerImageHiRes, (Image::loadPlatformResource("textAreaResizeCorner@2x")));
+ resizeCornerImage = resizeCornerImageHiRes;
+ cornerResizerSize = resizeCornerImage->size();
+ cornerResizerSize.scale(0.5f);
+ } else {
+ DEFINE_STATIC_REF(Image, resizeCornerImageLoRes, (Image::loadPlatformResource("textAreaResizeCorner")));
+ resizeCornerImage = resizeCornerImageLoRes;
+ cornerResizerSize = resizeCornerImage->size();
+ }
+
+ if (m_box->style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft()) {
+ context->save();
+ context->translate(resizerCornerRect.x() + cornerResizerSize.width(), resizerCornerRect.y() + resizerCornerRect.height() - cornerResizerSize.height());
+ context->scale(FloatSize(-1.0, 1.0));
+ context->drawImage(resizeCornerImage.get(), IntRect(IntPoint(), cornerResizerSize));
+ context->restore();
+ return;
+ }
+ IntRect imageRect(resizerCornerRect.maxXMaxYCorner() - cornerResizerSize, cornerResizerSize);
+ context->drawImage(resizeCornerImage.get(), imageRect);
+}
+
+IntSize RenderLayerScrollableArea::offsetFromResizeCorner(const IntPoint& absolutePoint) const
+{
+ // Currently the resize corner is either the bottom right corner or the bottom left corner.
+ // FIXME: This assumes the location is 0, 0. Is this guaranteed to always be the case?
+ IntSize elementSize = layer()->size();
+ if (m_box->style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
+ elementSize.setWidth(0);
+ IntPoint resizerPoint = IntPoint(elementSize);
+ IntPoint localPoint = roundedIntPoint(m_box->absoluteToLocal(absolutePoint, UseTransforms));
+ return localPoint - resizerPoint;
+}
+
+void RenderLayerScrollableArea::resize(const PlatformEvent& evt, const LayoutSize& oldOffset)
+{
+ // FIXME: This should be possible on generated content but is not right now.
+ if (!inResizeMode() || !m_box->canResize() || !m_box->node())
+ return;
+
+ ASSERT(m_box->node()->isElementNode());
+ Element* element = toElement(m_box->node());
+
+ Document& document = element->document();
+
+ IntPoint pos;
+ const PlatformGestureEvent* gevt = 0;
+
+ switch (evt.type()) {
+ case PlatformEvent::MouseMoved:
+ if (!document.frame()->eventHandler().mousePressed())
+ return;
+ pos = static_cast<const PlatformMouseEvent*>(&evt)->position();
+ break;
+ case PlatformEvent::GestureScrollUpdate:
+ case PlatformEvent::GestureScrollUpdateWithoutPropagation:
+ pos = static_cast<const PlatformGestureEvent*>(&evt)->position();
+ gevt = static_cast<const PlatformGestureEvent*>(&evt);
+ pos = gevt->position();
+ pos.move(gevt->deltaX(), gevt->deltaY());
+ break;
+ default:
+ ASSERT_NOT_REACHED();
+ }
+
+ float zoomFactor = m_box->style()->effectiveZoom();
+
+ LayoutSize newOffset = offsetFromResizeCorner(document.view()->windowToContents(pos));
+ newOffset.setWidth(newOffset.width() / zoomFactor);
+ newOffset.setHeight(newOffset.height() / zoomFactor);
+
+ LayoutSize currentSize = LayoutSize(m_box->width() / zoomFactor, m_box->height() / zoomFactor);
+ LayoutSize minimumSize = element->minimumSizeForResizing().shrunkTo(currentSize);
+ element->setMinimumSizeForResizing(minimumSize);
+
+ LayoutSize adjustedOldOffset = LayoutSize(oldOffset.width() / zoomFactor, oldOffset.height() / zoomFactor);
+ if (m_box->style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft()) {
+ newOffset.setWidth(-newOffset.width());
+ adjustedOldOffset.setWidth(-adjustedOldOffset.width());
+ }
+
+ LayoutSize difference = (currentSize + newOffset - adjustedOldOffset).expandedTo(minimumSize) - currentSize;
+
+ bool isBoxSizingBorder = m_box->style()->boxSizing() == BORDER_BOX;
+
+ EResize resize = m_box->style()->resize();
+ if (resize != RESIZE_VERTICAL && difference.width()) {
+ if (element->isFormControlElement()) {
+ // Make implicit margins from the theme explicit (see <http://bugs.webkit.org/show_bug.cgi?id=9547>).
+ element->setInlineStyleProperty(CSSPropertyMarginLeft, m_box->marginLeft() / zoomFactor, CSSPrimitiveValue::CSS_PX);
+ element->setInlineStyleProperty(CSSPropertyMarginRight, m_box->marginRight() / zoomFactor, CSSPrimitiveValue::CSS_PX);
+ }
+ LayoutUnit baseWidth = m_box->width() - (isBoxSizingBorder ? LayoutUnit() : m_box->borderAndPaddingWidth());
+ baseWidth = baseWidth / zoomFactor;
+ element->setInlineStyleProperty(CSSPropertyWidth, roundToInt(baseWidth + difference.width()), CSSPrimitiveValue::CSS_PX);
+ }
+
+ if (resize != RESIZE_HORIZONTAL && difference.height()) {
+ if (element->isFormControlElement()) {
+ // Make implicit margins from the theme explicit (see <http://bugs.webkit.org/show_bug.cgi?id=9547>).
+ element->setInlineStyleProperty(CSSPropertyMarginTop, m_box->marginTop() / zoomFactor, CSSPrimitiveValue::CSS_PX);
+ element->setInlineStyleProperty(CSSPropertyMarginBottom, m_box->marginBottom() / zoomFactor, CSSPrimitiveValue::CSS_PX);
+ }
+ LayoutUnit baseHeight = m_box->height() - (isBoxSizingBorder ? LayoutUnit() : m_box->borderAndPaddingHeight());
+ baseHeight = baseHeight / zoomFactor;
+ element->setInlineStyleProperty(CSSPropertyHeight, roundToInt(baseHeight + difference.height()), CSSPrimitiveValue::CSS_PX);
+ }
+
+ document.updateLayout();
+
+ // FIXME (Radar 4118564): We should also autoscroll the window as necessary to keep the point under the cursor in view.
+}
+
+LayoutRect RenderLayerScrollableArea::exposeRect(const LayoutRect& rect, const ScrollAlignment& alignX, const ScrollAlignment& alignY)
+{
+ LayoutRect localExposeRect(m_box->absoluteToLocalQuad(FloatQuad(FloatRect(rect)), UseTransforms).boundingBox());
+ LayoutRect layerBounds(0, 0, m_box->clientWidth(), m_box->clientHeight());
+ LayoutRect r = ScrollAlignment::getRectToExpose(layerBounds, localExposeRect, alignX, alignY);
+
+ IntSize clampedScrollOffset = clampScrollOffset(adjustedScrollOffset() + toIntSize(roundedIntRect(r).location()));
+ if (clampedScrollOffset == adjustedScrollOffset())
+ return rect;
+
+ IntSize oldScrollOffset = adjustedScrollOffset();
+ scrollToOffset(clampedScrollOffset);
+ IntSize scrollOffsetDifference = adjustedScrollOffset() - oldScrollOffset;
+ localExposeRect.move(-scrollOffsetDifference);
+ return LayoutRect(m_box->localToAbsoluteQuad(FloatQuad(FloatRect(localExposeRect)), UseTransforms).boundingBox());
+}
+
+void RenderLayerScrollableArea::updateScrollableAreaSet(bool hasOverflow)
+{
+ Frame* frame = m_box->frame();
+ if (!frame)
+ return;
+
+ FrameView* frameView = frame->view();
+ if (!frameView)
+ return;
+
+ bool isVisibleToHitTest = m_box->visibleToHitTesting();
+ if (HTMLFrameOwnerElement* owner = frame->ownerElement())
+ isVisibleToHitTest &= owner->renderer() && owner->renderer()->visibleToHitTesting();
+
+ bool requiresScrollableArea = hasOverflow && isVisibleToHitTest;
+ bool updatedScrollableAreaSet = false;
+ if (requiresScrollableArea) {
+ if (frameView->addScrollableArea(this))
+ updatedScrollableAreaSet = true;
+ } else {
+ if (frameView->removeScrollableArea(this))
+ updatedScrollableAreaSet = true;
+ }
+
+ if (updatedScrollableAreaSet) {
+ // Count the total number of RenderLayers that are scrollable areas for
+ // any period. We only want to record this at most once per RenderLayer.
+ if (requiresScrollableArea && !m_isScrollableAreaHasBeenRecorded) {
+ blink::Platform::current()->histogramEnumeration("Renderer.CompositedScrolling", RenderLayer::IsScrollableAreaBucket, RenderLayer::CompositedScrollingHistogramMax);
+ m_isScrollableAreaHasBeenRecorded = true;
+ }
+
+ // We always want composited scrolling if compositor driven accelerated
+ // scrolling is enabled. Since we will not update needs composited scrolling
+ // in this case, we must force our state to update.
+ if (layer()->compositorDrivenAcceleratedScrollingEnabled())
+ layer()->didUpdateNeedsCompositedScrolling();
+ else if (requiresScrollableArea)
+ m_box->view()->compositor()->setNeedsUpdateCompositingRequirementsState();
+ else
+ setNeedsCompositedScrolling(false);
+ }
+}
+
+void RenderLayerScrollableArea::updateNeedsCompositedScrolling()
+{
+ TRACE_EVENT0("comp-scroll", "RenderLayer::updateNeedsCompositedScrolling");
+
+ layer()->stackingNode()->updateDescendantsAreContiguousInStackingOrder();
+ layer()->updateDescendantDependentFlags();
+
+ ASSERT(scrollsOverflow());
+ const bool needsToBeStackingContainer = layer()->acceleratedCompositingForOverflowScrollEnabled()
+ && layer()->stackingNode()->descendantsAreContiguousInStackingOrder()
+ && !layer()->hasUnclippedDescendant();
+
+ const bool needsToBeStackingContainerDidChange = layer()->stackingNode()->setNeedsToBeStackingContainer(needsToBeStackingContainer);
+
+ const bool needsCompositedScrolling = needsToBeStackingContainer
+ || layer()->compositorDrivenAcceleratedScrollingEnabled();
+
+ // We gather a boolean value for use with Google UMA histograms to
+ // quantify the actual effects of a set of patches attempting to
+ // relax composited scrolling requirements, thereby increasing the
+ // number of composited overflow divs.
+ if (layer()->acceleratedCompositingForOverflowScrollEnabled())
+ blink::Platform::current()->histogramEnumeration("Renderer.NeedsCompositedScrolling", needsCompositedScrolling, 2);
+
+ const bool needsCompositedScrollingDidChange = setNeedsCompositedScrolling(needsCompositedScrolling);
+
+ if (needsToBeStackingContainerDidChange || needsCompositedScrollingDidChange) {
+ // Note, the z-order lists may need to be rebuilt, but our code guarantees
+ // that we have not affected stacking, so we will not dirty
+ // m_descendantsAreContiguousInStackingOrder for either us or our stacking
+ // context or container.
+ layer()->didUpdateNeedsCompositedScrolling();
+ }
+}
+
+bool RenderLayerScrollableArea::setNeedsCompositedScrolling(bool needsCompositedScrolling)
+{
+ if (this->needsCompositedScrolling() == needsCompositedScrolling)
+ return false;
+
+ // Count the total number of RenderLayers which need composited scrolling at
+ // some point. This should be recorded at most once per RenderLayer, so we
+ // check m_willUseCompositedScrollingHasBeenRecorded.
+ if (layer()->acceleratedCompositingForOverflowScrollEnabled() && !m_willUseCompositedScrollingHasBeenRecorded) {
+ blink::Platform::current()->histogramEnumeration("Renderer.CompositedScrolling", RenderLayer::WillUseCompositedScrollingBucket, RenderLayer::CompositedScrollingHistogramMax);
+ m_willUseCompositedScrollingHasBeenRecorded = true;
+ }
+
+ m_needsCompositedScrolling = needsCompositedScrolling;
+
+ return true;
+}
+
+void RenderLayerScrollableArea::updateHasVisibleNonLayerContent()
+{
+ layer()->updateHasVisibleNonLayerContent();
+}
+
+void RenderLayerScrollableArea::updateCompositingLayersAfterScroll()
+{
+ RenderLayerCompositor* compositor = m_box->view()->compositor();
+ if (compositor->inCompositingMode()) {
+ // FIXME: Our stacking container is guaranteed to contain all of our descendants that may need
+ // repositioning, so we should be able to enqueue a partial update compositing layers from there.
+ // this feature was overridden for now by deferred compositing updates.
+ if (usesCompositedScrolling())
+ compositor->updateCompositingLayers(CompositingUpdateOnCompositedScroll);
+ else
+ compositor->updateCompositingLayers(CompositingUpdateOnScroll);
+ }
+}
+
+bool RenderLayerScrollableArea::usesCompositedScrolling() const
+{
+ // Scroll form controls on the main thread so they exhibit correct touch scroll event bubbling
+ if (m_box && (m_box->isIntristicallyScrollable(VerticalScrollbar) || m_box->isIntristicallyScrollable(HorizontalScrollbar)))
+ return false;
+
+ return m_box->hasCompositedLayerMapping() && m_box->compositedLayerMapping()->scrollingLayer();
+}
+
+bool RenderLayerScrollableArea::adjustForForceCompositedScrollingMode(bool value) const
+{
+ switch (m_forceNeedsCompositedScrolling) {
+ case DoNotForceCompositedScrolling:
+ return value;
+ case CompositedScrollingAlwaysOn:
+ return true;
+ case CompositedScrollingAlwaysOff:
+ return false;
+ }
+
+ ASSERT_NOT_REACHED();
+ return value;
+}
+
+bool RenderLayerScrollableArea::needsCompositedScrolling() const
+{
+ return adjustForForceCompositedScrollingMode(m_needsCompositedScrolling);
+}
+
+void RenderLayerScrollableArea::setForceNeedsCompositedScrolling(ForceNeedsCompositedScrollingMode mode)
+{
+ if (m_forceNeedsCompositedScrolling == mode)
+ return;
+
+ m_forceNeedsCompositedScrolling = mode;
+ layer()->didUpdateNeedsCompositedScrolling();
+}
+
} // Namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderLayerScrollableArea.h b/chromium/third_party/WebKit/Source/core/rendering/RenderLayerScrollableArea.h
index 05e06d38fc5..0444ca78b33 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderLayerScrollableArea.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderLayerScrollableArea.h
@@ -44,7 +44,7 @@
#ifndef RenderLayerScrollableArea_h
#define RenderLayerScrollableArea_h
-#include "core/platform/ScrollableArea.h"
+#include "platform/scroll/ScrollableArea.h"
namespace WebCore {
@@ -53,28 +53,31 @@ enum ResizerHitTestType {
ResizerForTouch
};
-enum ScrollOffsetClamping {
- ScrollOffsetUnclamped,
- ScrollOffsetClamped
+enum ForceNeedsCompositedScrollingMode {
+ DoNotForceCompositedScrolling = 0,
+ CompositedScrollingAlwaysOn = 1,
+ CompositedScrollingAlwaysOff = 2
};
+class PlatformEvent;
+class RenderBox;
class RenderLayer;
-class RenderLayerModelObject;
class RenderScrollbarPart;
class RenderLayerScrollableArea FINAL : public ScrollableArea {
- // FIXME: Remove once the bits from RenderLayer have been moved here.
- friend class RenderLayer;
+ friend class Internals;
+
public:
- RenderLayerScrollableArea(RenderLayer*);
+ RenderLayerScrollableArea(RenderBox*);
virtual ~RenderLayerScrollableArea();
+ bool hasHorizontalScrollbar() const { return horizontalScrollbar(); }
+ bool hasVerticalScrollbar() const { return verticalScrollbar(); }
+
virtual Scrollbar* horizontalScrollbar() const OVERRIDE { return m_hBar.get(); }
virtual Scrollbar* verticalScrollbar() const OVERRIDE { return m_vBar.get(); }
virtual ScrollableArea* enclosingScrollableArea() const OVERRIDE;
- virtual void updateNeedsCompositedScrolling() OVERRIDE;
-
virtual GraphicsLayer* layerForScrolling() const OVERRIDE;
virtual GraphicsLayer* layerForHorizontalScrollbar() const OVERRIDE;
virtual GraphicsLayer* layerForVerticalScrollbar() const OVERRIDE;
@@ -94,7 +97,7 @@ public:
virtual IntPoint scrollPosition() const OVERRIDE;
virtual IntPoint minimumScrollPosition() const OVERRIDE;
virtual IntPoint maximumScrollPosition() const OVERRIDE;
- virtual IntRect visibleContentRect(VisibleContentRectIncludesScrollbars) const OVERRIDE;
+ virtual IntRect visibleContentRect(IncludeScrollbarsInRect) const OVERRIDE;
virtual int visibleHeight() const OVERRIDE;
virtual int visibleWidth() const OVERRIDE;
virtual IntSize contentsSize() const OVERRIDE;
@@ -116,6 +119,8 @@ public:
LayoutRect overflowRect() const { return m_overflowRect; }
void scrollToOffset(const IntSize& scrollOffset, ScrollOffsetClamping = ScrollOffsetUnclamped);
+ void scrollToXOffset(int x, ScrollOffsetClamping clamp = ScrollOffsetUnclamped) { scrollToOffset(IntSize(x, scrollYOffset()), clamp); }
+ void scrollToYOffset(int y, ScrollOffsetClamping clamp = ScrollOffsetUnclamped) { scrollToOffset(IntSize(scrollXOffset(), y), clamp); }
void updateAfterLayout();
void updateAfterStyleChange(const RenderStyle*);
@@ -125,19 +130,63 @@ public:
// FIXME: This should be removed.
bool hasScrollCorner() const { return m_scrollCorner; }
+ void resize(const PlatformEvent&, const LayoutSize&);
+ IntSize offsetFromResizeCorner(const IntPoint& absolutePoint) const;
+
+ bool inResizeMode() const { return m_inResizeMode; }
+ void setInResizeMode(bool inResizeMode) { m_inResizeMode = inResizeMode; }
+
+ IntRect touchResizerCornerRect(const IntRect& bounds) const
+ {
+ return resizerCornerRect(bounds, ResizerForTouch);
+ }
+
+ int scrollWidth() const;
+ int scrollHeight() const;
+
+ int verticalScrollbarWidth(OverlayScrollbarSizeRelevancy = IgnoreOverlayScrollbarSize) const;
+ int horizontalScrollbarHeight(OverlayScrollbarSizeRelevancy = IgnoreOverlayScrollbarSize) const;
+
+ IntSize adjustedScrollOffset() const { return IntSize(scrollXOffset(), scrollYOffset()); }
+
+ void paintResizer(GraphicsContext*, const IntPoint& paintOffset, const IntRect& damageRect);
+ void paintOverflowControls(GraphicsContext*, const IntPoint& paintOffset, const IntRect& damageRect, bool paintingOverlayControls);
+ void paintScrollCorner(GraphicsContext*, const IntPoint&, const IntRect& damageRect);
+
+ // If IntSize is not given, then we must incur additional overhead to instantiate a RenderGeometryMap
+ // and compute the correct offset ourselves.
+ void positionOverflowControls();
+ void positionOverflowControls(const IntSize& offsetFromRoot);
+
+ // isPointInResizeControl() is used for testing if a pointer/touch position is in the resize control
+ // area.
+ bool isPointInResizeControl(const IntPoint& absolutePoint, ResizerHitTestType) const;
+ bool hitTestOverflowControls(HitTestResult&, const IntPoint& localPoint);
+
+ bool hitTestResizerInFragments(const LayerFragments&, const HitTestLocation&) const;
+
+ LayoutRect exposeRect(const LayoutRect&, const ScrollAlignment& alignX, const ScrollAlignment& alignY);
+
+ bool scrollsOverflow() const;
+
+ // Rectangle encompassing the scroll corner and resizer rect.
+ IntRect scrollCornerAndResizerRect() const;
+
+ bool needsCompositedScrolling() const;
+
+ // FIXME: This needs to be exposed as forced compositing scrolling is a RenderLayerScrollableArea
+ // concept and stacking container is a RenderLayerStackingNode concept.
+ bool adjustForForceCompositedScrollingMode(bool) const;
+
private:
bool hasHorizontalOverflow() const;
bool hasVerticalOverflow() const;
bool hasScrollableHorizontalOverflow() const;
bool hasScrollableVerticalOverflow() const;
- int scrollWidth() const;
- int scrollHeight() const;
-
void computeScrollDimensions();
IntSize clampScrollOffset(const IntSize&) const;
- IntSize adjustedScrollOffset() const { return IntSize(scrollXOffset(), scrollYOffset()); }
void setScrollOffset(const IntSize& scrollOffset) { m_scrollOffset = scrollOffset; }
@@ -150,40 +199,62 @@ private:
PassRefPtr<Scrollbar> createScrollbar(ScrollbarOrientation);
void destroyScrollbar(ScrollbarOrientation);
- bool hasHorizontalScrollbar() const { return horizontalScrollbar(); }
- bool hasVerticalScrollbar() const { return verticalScrollbar(); }
-
void setHasHorizontalScrollbar(bool hasScrollbar);
void setHasVerticalScrollbar(bool hasScrollbar);
- int verticalScrollbarWidth(OverlayScrollbarSizeRelevancy = IgnoreOverlayScrollbarSize) const;
- int horizontalScrollbarHeight(OverlayScrollbarSizeRelevancy = IgnoreOverlayScrollbarSize) const;
-
- void positionOverflowControls(const IntSize& offsetFromRoot);
void updateScrollCornerStyle();
- void paintOverflowControls(GraphicsContext*, const IntPoint& paintOffset, const IntRect& damageRect, bool paintingOverlayControls);
- void paintScrollCorner(GraphicsContext*, const IntPoint&, const IntRect& damageRect);
- bool hitTestOverflowControls(HitTestResult&, const IntPoint& localPoint, const IntRect&);
- RenderLayerModelObject* renderer() const;
+ // See comments on isPointInResizeControl.
+ IntRect resizerCornerRect(const IntRect&, ResizerHitTestType) const;
+ bool overflowControlsIntersectRect(const IntRect& localRect) const;
+ void updateResizerAreaSet();
+ void updateResizerStyle();
+ void drawPlatformResizerImage(GraphicsContext*, IntRect resizerCornerRect);
+
+ RenderLayer* layer() const;
+
+ void updateScrollableAreaSet(bool hasOverflow);
+
+ void updateCompositingLayersAfterScroll();
+ virtual void updateNeedsCompositedScrolling() OVERRIDE;
+ bool setNeedsCompositedScrolling(bool);
+
+ virtual void updateHasVisibleNonLayerContent() OVERRIDE;
+
+ void setForceNeedsCompositedScrolling(ForceNeedsCompositedScrollingMode);
- RenderLayer* m_layer;
+ RenderBox* m_box;
+
+ // Keeps track of whether the layer is currently resizing, so events can cause resizing to start and stop.
+ unsigned m_inResizeMode : 1;
unsigned m_scrollDimensionsDirty : 1;
unsigned m_inOverflowRelayout : 1;
+ unsigned m_needsCompositedScrolling : 1;
+ unsigned m_willUseCompositedScrollingHasBeenRecorded : 1;
+
+ unsigned m_isScrollableAreaHasBeenRecorded : 1;
+
+ ForceNeedsCompositedScrollingMode m_forceNeedsCompositedScrolling;
+
// The width/height of our scrolled area.
LayoutRect m_overflowRect;
// This is the (scroll) offset from scrollOrigin().
IntSize m_scrollOffset;
+ IntPoint m_cachedOverlayScrollbarOffset;
+
// For areas with overflow, we have a pair of scrollbars.
RefPtr<Scrollbar> m_hBar;
RefPtr<Scrollbar> m_vBar;
// Renderers to hold our custom scroll corner.
RenderScrollbarPart* m_scrollCorner;
+
+ // Renderers to hold our custom resizer.
+ RenderScrollbarPart* m_resizer;
};
} // Namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderLayerStackingNode.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderLayerStackingNode.cpp
new file mode 100644
index 00000000000..715dcecfe77
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderLayerStackingNode.cpp
@@ -0,0 +1,661 @@
+/*
+ * Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012 Apple Inc. All rights reserved.
+ *
+ * Portions are Copyright (C) 1998 Netscape Communications Corporation.
+ *
+ * Other contributors:
+ * Robert O'Callahan <roc+@cs.cmu.edu>
+ * David Baron <dbaron@fas.harvard.edu>
+ * Christian Biesinger <cbiesinger@web.de>
+ * Randall Jesup <rjesup@wgate.com>
+ * Roland Mainz <roland.mainz@informatik.med.uni-giessen.de>
+ * Josh Soref <timeless@mac.com>
+ * Boris Zbarsky <bzbarsky@mit.edu>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ * Alternatively, the contents of this file may be used under the terms
+ * of either the Mozilla Public License Version 1.1, found at
+ * http://www.mozilla.org/MPL/ (the "MPL") or the GNU General Public
+ * License Version 2.0, found at http://www.fsf.org/copyleft/gpl.html
+ * (the "GPL"), in which case the provisions of the MPL or the GPL are
+ * applicable instead of those above. If you wish to allow use of your
+ * version of this file only under the terms of one of those two
+ * licenses (the MPL or the GPL) and not to allow others to use your
+ * version of this file under the LGPL, indicate your decision by
+ * deletingthe provisions above and replace them with the notice and
+ * other provisions required by the MPL or the GPL, as the case may be.
+ * If you do not delete the provisions above, a recipient may use your
+ * version of this file under any of the LGPL, the MPL or the GPL.
+ */
+
+#include "config.h"
+#include "core/rendering/RenderLayerStackingNode.h"
+
+#include "core/rendering/RenderLayer.h"
+#include "core/rendering/RenderLayerCompositor.h"
+#include "core/rendering/RenderView.h"
+#include "public/platform/Platform.h"
+
+namespace WebCore {
+
+// FIXME: This should not require RenderLayer. There is currently a cycle where
+// in order to determine if we shoulBeNormalFlowOnly() and isStackingContainer()
+// we have to ask the render layer about some of its state.
+RenderLayerStackingNode::RenderLayerStackingNode(RenderLayer* layer)
+ : m_layer(layer)
+ , m_descendantsAreContiguousInStackingOrder(false)
+ , m_descendantsAreContiguousInStackingOrderDirty(true)
+ , m_normalFlowListDirty(true)
+ , m_needsToBeStackingContainer(false)
+ , m_needsToBeStackingContainerHasBeenRecorded(false)
+#if !ASSERT_DISABLED
+ , m_layerListMutationAllowed(true)
+ , m_stackingParent(0)
+#endif
+{
+ m_isNormalFlowOnly = shouldBeNormalFlowOnly();
+
+ // Non-stacking containers should have empty z-order lists. As this is already the case,
+ // there is no need to dirty / recompute these lists.
+ m_zOrderListsDirty = isStackingContainer();
+}
+
+RenderLayerStackingNode::~RenderLayerStackingNode()
+{
+#if !ASSERT_DISABLED
+ if (!renderer()->documentBeingDestroyed()) {
+ ASSERT(!isInStackingParentZOrderLists());
+ ASSERT(!isInStackingParentNormalFlowList());
+
+ updateStackingParentForZOrderLists(0);
+ updateStackingParentForNormalFlowList(0);
+ }
+#endif
+}
+
+bool RenderLayerStackingNode::isStackingContext(const RenderStyle* style) const
+{
+ return !style->hasAutoZIndex() || layer()->isRootLayer();
+}
+
+// Helper for the sorting of layers by z-index.
+static inline bool compareZIndex(RenderLayerStackingNode* first, RenderLayerStackingNode* second)
+{
+ return first->zIndex() < second->zIndex();
+}
+
+RenderLayerCompositor* RenderLayerStackingNode::compositor() const
+{
+ if (!renderer()->view())
+ return 0;
+ return renderer()->view()->compositor();
+}
+
+void RenderLayerStackingNode::dirtyNormalFlowListCanBePromotedToStackingContainer()
+{
+ m_descendantsAreContiguousInStackingOrderDirty = true;
+
+ if (m_normalFlowListDirty || !normalFlowList())
+ return;
+
+ for (size_t index = 0; index < normalFlowList()->size(); ++index)
+ normalFlowList()->at(index)->dirtyNormalFlowListCanBePromotedToStackingContainer();
+}
+
+void RenderLayerStackingNode::dirtySiblingStackingNodeCanBePromotedToStackingContainer()
+{
+ RenderLayerStackingNode* stackingNode = ancestorStackingNode();
+ if (!stackingNode)
+ return;
+
+ if (!stackingNode->zOrderListsDirty() && stackingNode->posZOrderList()) {
+ for (size_t index = 0; index < stackingNode->posZOrderList()->size(); ++index)
+ stackingNode->posZOrderList()->at(index)->setDescendantsAreContiguousInStackingOrderDirty(true);
+ }
+
+ stackingNode->dirtyNormalFlowListCanBePromotedToStackingContainer();
+
+ if (!stackingNode->zOrderListsDirty() && stackingNode->negZOrderList()) {
+ for (size_t index = 0; index < stackingNode->negZOrderList()->size(); ++index)
+ stackingNode->negZOrderList()->at(index)->setDescendantsAreContiguousInStackingOrderDirty(true);
+ }
+}
+
+void RenderLayerStackingNode::dirtyZOrderLists()
+{
+ ASSERT(m_layerListMutationAllowed);
+ ASSERT(isStackingContainer());
+
+#if !ASSERT_DISABLED
+ updateStackingParentForZOrderLists(0);
+#endif
+
+ if (m_posZOrderList)
+ m_posZOrderList->clear();
+ if (m_negZOrderList)
+ m_negZOrderList->clear();
+ m_zOrderListsDirty = true;
+
+ m_descendantsAreContiguousInStackingOrderDirty = true;
+
+ if (!renderer()->documentBeingDestroyed()) {
+ compositor()->setNeedsUpdateCompositingRequirementsState();
+ compositor()->setCompositingLayersNeedRebuild();
+ if (layer()->acceleratedCompositingForOverflowScrollEnabled())
+ compositor()->setNeedsToRecomputeCompositingRequirements();
+ }
+}
+
+void RenderLayerStackingNode::dirtyStackingContainerZOrderLists()
+{
+ // Any siblings in the ancestor stacking context could also be affected.
+ // Changing z-index, for example, could cause us to stack in between a
+ // sibling's descendants, meaning that we have to recompute
+ // m_descendantsAreContiguousInStackingOrder for that sibling.
+ dirtySiblingStackingNodeCanBePromotedToStackingContainer();
+
+ RenderLayerStackingNode* stackingContainerNode = ancestorStackingContainerNode();
+ if (stackingContainerNode)
+ stackingContainerNode->dirtyZOrderLists();
+
+ // Any change that could affect our stacking container's z-order list could
+ // cause other RenderLayers in our stacking context to either opt in or out
+ // of composited scrolling. It is important that we make our stacking
+ // context aware of these z-order changes so the appropriate updating can
+ // happen.
+ RenderLayerStackingNode* stackingNode = ancestorStackingNode();
+ if (stackingNode && stackingNode != stackingContainerNode)
+ stackingNode->dirtyZOrderLists();
+}
+
+void RenderLayerStackingNode::dirtyNormalFlowList()
+{
+ ASSERT(m_layerListMutationAllowed);
+
+#if !ASSERT_DISABLED
+ updateStackingParentForNormalFlowList(0);
+#endif
+
+ if (m_normalFlowList)
+ m_normalFlowList->clear();
+ m_normalFlowListDirty = true;
+
+ if (!renderer()->documentBeingDestroyed()) {
+ compositor()->setCompositingLayersNeedRebuild();
+ if (layer()->acceleratedCompositingForOverflowScrollEnabled())
+ compositor()->setNeedsToRecomputeCompositingRequirements();
+ }
+}
+
+void RenderLayerStackingNode::rebuildZOrderLists()
+{
+ ASSERT(m_layerListMutationAllowed);
+ ASSERT(isDirtyStackingContainer());
+ rebuildZOrderLists(m_posZOrderList, m_negZOrderList);
+
+#if !ASSERT_DISABLED
+ updateStackingParentForZOrderLists(this);
+#endif
+
+ m_zOrderListsDirty = false;
+}
+
+void RenderLayerStackingNode::rebuildZOrderLists(OwnPtr<Vector<RenderLayerStackingNode*> >& posZOrderList,
+ OwnPtr<Vector<RenderLayerStackingNode*> >& negZOrderList, const RenderLayerStackingNode* nodeToForceAsStackingContainer,
+ CollectLayersBehavior collectLayersBehavior)
+{
+ for (RenderLayer* child = layer()->firstChild(); child; child = child->nextSibling()) {
+ if (!layer()->reflectionInfo() || layer()->reflectionInfo()->reflectionLayer() != child)
+ child->stackingNode()->collectLayers(posZOrderList, negZOrderList, nodeToForceAsStackingContainer, collectLayersBehavior);
+ }
+
+ // Sort the two lists.
+ if (posZOrderList)
+ std::stable_sort(posZOrderList->begin(), posZOrderList->end(), compareZIndex);
+
+ if (negZOrderList)
+ std::stable_sort(negZOrderList->begin(), negZOrderList->end(), compareZIndex);
+
+ // Append layers for top layer elements after normal layer collection, to ensure they are on top regardless of z-indexes.
+ // The renderers of top layer elements are children of the view, sorted in top layer stacking order.
+ if (layer()->isRootLayer()) {
+ RenderObject* view = renderer()->view();
+ for (RenderObject* child = view->firstChild(); child; child = child->nextSibling()) {
+ Element* childElement = (child->node() && child->node()->isElementNode()) ? toElement(child->node()) : 0;
+ if (childElement && childElement->isInTopLayer()) {
+ RenderLayer* layer = toRenderLayerModelObject(child)->layer();
+ // Create the buffer if it doesn't exist yet.
+ if (!posZOrderList)
+ posZOrderList = adoptPtr(new Vector<RenderLayerStackingNode*>);
+ posZOrderList->append(layer->stackingNode());
+ }
+ }
+ }
+}
+
+void RenderLayerStackingNode::updateNormalFlowList()
+{
+ if (!m_normalFlowListDirty)
+ return;
+
+ ASSERT(m_layerListMutationAllowed);
+
+ for (RenderLayer* child = layer()->firstChild(); child; child = child->nextSibling()) {
+ // Ignore non-overflow layers and reflections.
+ if (child->stackingNode()->isNormalFlowOnly() && (!layer()->reflectionInfo() || layer()->reflectionInfo()->reflectionLayer() != child)) {
+ if (!m_normalFlowList)
+ m_normalFlowList = adoptPtr(new Vector<RenderLayerStackingNode*>);
+ m_normalFlowList->append(child->stackingNode());
+ }
+ }
+
+#if !ASSERT_DISABLED
+ updateStackingParentForNormalFlowList(this);
+#endif
+
+ m_normalFlowListDirty = false;
+}
+
+void RenderLayerStackingNode::collectLayers(OwnPtr<Vector<RenderLayerStackingNode*> >& posBuffer, OwnPtr<Vector<RenderLayerStackingNode*> >& negBuffer,
+ const RenderLayerStackingNode* nodeToForceAsStackingContainer, CollectLayersBehavior collectLayersBehavior)
+{
+ if (layer()->isInTopLayer())
+ return;
+
+ layer()->updateDescendantDependentFlags();
+
+ bool isStacking = false;
+ bool isNormalFlow = false;
+
+ switch (collectLayersBehavior) {
+ case ForceLayerToStackingContainer:
+ ASSERT(nodeToForceAsStackingContainer);
+ if (this == nodeToForceAsStackingContainer) {
+ isStacking = true;
+ isNormalFlow = false;
+ } else {
+ isStacking = isStackingContext();
+ isNormalFlow = shouldBeNormalFlowOnlyIgnoringCompositedScrolling();
+ }
+ break;
+ case OverflowScrollCanBeStackingContainers:
+ ASSERT(!nodeToForceAsStackingContainer);
+ isStacking = isStackingContainer();
+ isNormalFlow = isNormalFlowOnly();
+ break;
+ case OnlyStackingContextsCanBeStackingContainers:
+ isStacking = isStackingContext();
+ isNormalFlow = shouldBeNormalFlowOnlyIgnoringCompositedScrolling();
+ break;
+ }
+
+ // Overflow layers are just painted by their enclosing layers, so they don't get put in zorder lists.
+ if (!isNormalFlow && !layer()->isOutOfFlowRenderFlowThread()) {
+ // Determine which buffer the child should be in.
+ OwnPtr<Vector<RenderLayerStackingNode*> >& buffer = (zIndex() >= 0) ? posBuffer : negBuffer;
+
+ // Create the buffer if it doesn't exist yet.
+ if (!buffer)
+ buffer = adoptPtr(new Vector<RenderLayerStackingNode*>);
+
+ // Append ourselves at the end of the appropriate buffer.
+ buffer->append(this);
+ }
+
+ // Recur into our children to collect more layers, but only if we don't establish
+ // a stacking context/container.
+ if (!isStacking) {
+ for (RenderLayer* child = layer()->firstChild(); child; child = child->nextSibling()) {
+ // Ignore reflections.
+ if (!layer()->reflectionInfo() || layer()->reflectionInfo()->reflectionLayer() != child)
+ child->stackingNode()->collectLayers(posBuffer, negBuffer, nodeToForceAsStackingContainer, collectLayersBehavior);
+ }
+ }
+}
+
+#if !ASSERT_DISABLED
+bool RenderLayerStackingNode::isInStackingParentZOrderLists() const
+{
+ if (!m_stackingParent || m_stackingParent->zOrderListsDirty())
+ return false;
+
+ if (m_stackingParent->posZOrderList() && m_stackingParent->posZOrderList()->find(this) != kNotFound)
+ return true;
+
+ if (m_stackingParent->negZOrderList() && m_stackingParent->negZOrderList()->find(this) != kNotFound)
+ return true;
+
+ return false;
+}
+
+bool RenderLayerStackingNode::isInStackingParentNormalFlowList() const
+{
+ if (!m_stackingParent || m_stackingParent->normalFlowListDirty())
+ return false;
+
+ return (m_stackingParent->normalFlowList() && m_stackingParent->normalFlowList()->find(this) != kNotFound);
+}
+
+void RenderLayerStackingNode::updateStackingParentForZOrderLists(RenderLayerStackingNode* stackingParent)
+{
+ if (m_posZOrderList) {
+ for (size_t i = 0; i < m_posZOrderList->size(); ++i)
+ m_posZOrderList->at(i)->setStackingParent(stackingParent);
+ }
+
+ if (m_negZOrderList) {
+ for (size_t i = 0; i < m_negZOrderList->size(); ++i)
+ m_negZOrderList->at(i)->setStackingParent(stackingParent);
+ }
+}
+
+void RenderLayerStackingNode::updateStackingParentForNormalFlowList(RenderLayerStackingNode* stackingParent)
+{
+ if (m_normalFlowList) {
+ for (size_t i = 0; i < m_normalFlowList->size(); ++i)
+ m_normalFlowList->at(i)->setStackingParent(stackingParent);
+ }
+}
+#endif
+
+void RenderLayerStackingNode::updateLayerListsIfNeeded()
+{
+ updateZOrderLists();
+ updateNormalFlowList();
+
+ if (!layer()->reflectionInfo())
+ return;
+
+ RenderLayer* reflectionLayer = layer()->reflectionInfo()->reflectionLayer();
+ reflectionLayer->stackingNode()->updateZOrderLists();
+ reflectionLayer->stackingNode()->updateNormalFlowList();
+}
+
+void RenderLayerStackingNode::updateStackingNodesAfterStyleChange(const RenderStyle* oldStyle)
+{
+ bool wasStackingContext = oldStyle ? isStackingContext(oldStyle) : false;
+ EVisibility oldVisibility = oldStyle ? oldStyle->visibility() : VISIBLE;
+ int oldZIndex = oldStyle ? oldStyle->zIndex() : 0;
+
+ // FIXME: RenderLayer already handles visibility changes through our visiblity dirty bits. This logic could
+ // likely be folded along with the rest.
+ bool isStackingContext = this->isStackingContext();
+ if (isStackingContext == wasStackingContext && oldVisibility == renderer()->style()->visibility() && oldZIndex == zIndex())
+ return;
+
+ dirtyStackingContainerZOrderLists();
+
+ if (isStackingContainer())
+ dirtyZOrderLists();
+ else
+ clearZOrderLists();
+
+ compositor()->setNeedsUpdateCompositingRequirementsState();
+}
+
+bool RenderLayerStackingNode::shouldBeNormalFlowOnly() const
+{
+ return shouldBeNormalFlowOnlyIgnoringCompositedScrolling() && !layer()->needsCompositedScrolling();
+}
+
+bool RenderLayerStackingNode::shouldBeNormalFlowOnlyIgnoringCompositedScrolling() const
+{
+ const bool couldBeNormalFlow = renderer()->hasOverflowClip()
+ || renderer()->hasReflection()
+ || renderer()->hasMask()
+ || renderer()->isCanvas()
+ || renderer()->isVideo()
+ || renderer()->isEmbeddedObject()
+ || renderer()->isRenderIFrame()
+ || (renderer()->style()->specifiesColumns() && !layer()->isRootLayer());
+ const bool preventsElementFromBeingNormalFlow = renderer()->isPositioned()
+ || renderer()->hasTransform()
+ || renderer()->hasClipPath()
+ || renderer()->hasFilter()
+ || renderer()->hasBlendMode()
+ || layer()->isTransparent()
+ || renderer()->style()->hasFlowFrom();
+
+ return couldBeNormalFlow && !preventsElementFromBeingNormalFlow;
+}
+
+void RenderLayerStackingNode::updateIsNormalFlowOnly()
+{
+ bool isNormalFlowOnly = shouldBeNormalFlowOnly();
+ if (isNormalFlowOnly == this->isNormalFlowOnly())
+ return;
+
+ m_isNormalFlowOnly = isNormalFlowOnly;
+ if (RenderLayer* p = layer()->parent())
+ p->stackingNode()->dirtyNormalFlowList();
+ dirtyStackingContainerZOrderLists();
+}
+
+bool RenderLayerStackingNode::needsToBeStackingContainer() const
+{
+ return layer()->scrollableArea() && layer()->scrollableArea()->adjustForForceCompositedScrollingMode(m_needsToBeStackingContainer);
+}
+
+// Determine whether the current layer can be promoted to a stacking container.
+// We do this by computing what positive and negative z-order lists would look
+// like before and after promotion, and ensuring that proper stacking order is
+// preserved between the two sets of lists.
+void RenderLayerStackingNode::updateDescendantsAreContiguousInStackingOrder()
+{
+ TRACE_EVENT0("blink_rendering,comp-scroll", "RenderLayerStackingNode::updateDescendantsAreContiguousInStackingOrder");
+
+ const RenderLayer* currentLayer = layer();
+ if (isStackingContext() || !m_descendantsAreContiguousInStackingOrderDirty || !currentLayer->acceleratedCompositingForOverflowScrollEnabled())
+ return;
+
+ if (!currentLayer->scrollsOverflow())
+ return;
+
+ RenderLayerStackingNode* stackingNode = ancestorStackingNode();
+ if (!stackingNode)
+ return;
+
+ OwnPtr<Vector<RenderLayerStackingNode*> > posZOrderListBeforePromote = adoptPtr(new Vector<RenderLayerStackingNode*>);
+ OwnPtr<Vector<RenderLayerStackingNode*> > negZOrderListBeforePromote = adoptPtr(new Vector<RenderLayerStackingNode*>);
+ OwnPtr<Vector<RenderLayerStackingNode*> > posZOrderListAfterPromote = adoptPtr(new Vector<RenderLayerStackingNode*>);
+ OwnPtr<Vector<RenderLayerStackingNode*> > negZOrderListAfterPromote = adoptPtr(new Vector<RenderLayerStackingNode*>);
+
+ collectBeforePromotionZOrderList(stackingNode, posZOrderListBeforePromote, negZOrderListBeforePromote);
+ collectAfterPromotionZOrderList(stackingNode, posZOrderListAfterPromote, negZOrderListAfterPromote);
+
+ size_t maxIndex = std::min(posZOrderListAfterPromote->size() + negZOrderListAfterPromote->size(), posZOrderListBeforePromote->size() + negZOrderListBeforePromote->size());
+
+ m_descendantsAreContiguousInStackingOrderDirty = false;
+ m_descendantsAreContiguousInStackingOrder = false;
+
+ const RenderLayerStackingNode* nodeAfterPromote = 0;
+ for (size_t i = 0; i < maxIndex && nodeAfterPromote != this; ++i) {
+ const RenderLayerStackingNode* nodeBeforePromote = i < negZOrderListBeforePromote->size()
+ ? negZOrderListBeforePromote->at(i)
+ : posZOrderListBeforePromote->at(i - negZOrderListBeforePromote->size());
+ nodeAfterPromote = i < negZOrderListAfterPromote->size()
+ ? negZOrderListAfterPromote->at(i)
+ : posZOrderListAfterPromote->at(i - negZOrderListAfterPromote->size());
+
+ if (nodeBeforePromote != nodeAfterPromote && (nodeAfterPromote != this || renderer()->hasBackground()))
+ return;
+ }
+
+ nodeAfterPromote = 0;
+ for (size_t i = 0; i < maxIndex && nodeAfterPromote != this; ++i) {
+ const RenderLayerStackingNode* nodeBeforePromote = i < posZOrderListBeforePromote->size()
+ ? posZOrderListBeforePromote->at(posZOrderListBeforePromote->size() - i - 1)
+ : negZOrderListBeforePromote->at(negZOrderListBeforePromote->size() + posZOrderListBeforePromote->size() - i - 1);
+ nodeAfterPromote = i < posZOrderListAfterPromote->size()
+ ? posZOrderListAfterPromote->at(posZOrderListAfterPromote->size() - i - 1)
+ : negZOrderListAfterPromote->at(negZOrderListAfterPromote->size() + posZOrderListAfterPromote->size() - i - 1);
+
+ if (nodeBeforePromote != nodeAfterPromote && nodeAfterPromote != this)
+ return;
+ }
+
+ m_descendantsAreContiguousInStackingOrder = true;
+}
+
+void RenderLayerStackingNode::collectBeforePromotionZOrderList(RenderLayerStackingNode* ancestorStackingNode,
+ OwnPtr<Vector<RenderLayerStackingNode*> >& posZOrderList, OwnPtr<Vector<RenderLayerStackingNode*> >& negZOrderList)
+{
+ ancestorStackingNode->rebuildZOrderLists(posZOrderList, negZOrderList, this, OnlyStackingContextsCanBeStackingContainers);
+
+ const RenderLayer* currentLayer = layer();
+ const RenderLayer* positionedAncestor = currentLayer->parent();
+ while (positionedAncestor && !positionedAncestor->isPositionedContainer() && !positionedAncestor->stackingNode()->isStackingContext())
+ positionedAncestor = positionedAncestor->parent();
+ if (positionedAncestor && (!positionedAncestor->isPositionedContainer() || positionedAncestor->stackingNode()->isStackingContext()))
+ positionedAncestor = 0;
+
+ if (!posZOrderList)
+ posZOrderList = adoptPtr(new Vector<RenderLayerStackingNode*>());
+ else if (posZOrderList->find(this) != kNotFound)
+ return;
+
+ // The current node will appear in the z-order lists after promotion, so
+ // for a meaningful comparison, we must insert it in the z-order lists
+ // before promotion if it does not appear there already.
+ if (!positionedAncestor) {
+ posZOrderList->prepend(this);
+ return;
+ }
+
+ for (size_t index = 0; index < posZOrderList->size(); index++) {
+ if (posZOrderList->at(index)->layer() == positionedAncestor) {
+ posZOrderList->insert(index + 1, this);
+ return;
+ }
+ }
+}
+
+void RenderLayerStackingNode::collectAfterPromotionZOrderList(RenderLayerStackingNode* ancestorStackingNode,
+ OwnPtr<Vector<RenderLayerStackingNode*> >& posZOrderList, OwnPtr<Vector<RenderLayerStackingNode*> >& negZOrderList)
+{
+ ancestorStackingNode->rebuildZOrderLists(posZOrderList, negZOrderList, this, ForceLayerToStackingContainer);
+}
+
+// Compute what positive and negative z-order lists would look like before and
+// after promotion, so we can later ensure that proper stacking order is
+// preserved between the two sets of lists.
+//
+// A few examples:
+// c = currentLayer
+// - = negative z-order child of currentLayer
+// + = positive z-order child of currentLayer
+// a = positioned ancestor of currentLayer
+// x = any other RenderLayer in the list
+//
+// (a) xxxxx-----++a+++x
+// (b) xxx-----c++++++xx
+//
+// Normally the current layer would be painted in the normal flow list if it
+// doesn't already appear in the positive z-order list. However, in the case
+// that the layer has a positioned ancestor, it will paint directly after the
+// positioned ancestor. In example (a), the current layer would be painted in
+// the middle of its own positive z-order children, so promoting would cause a
+// change in paint order (since a promoted layer will paint all of its positive
+// z-order children strictly after it paints itself).
+//
+// In example (b), it is ok to promote the current layer only if it does not
+// have a background. If it has a background, the background gets painted before
+// the layer's negative z-order children, so again, a promotion would cause a
+// change in paint order (causing the background to get painted after the
+// negative z-order children instead of before).
+//
+void RenderLayerStackingNode::computePaintOrderList(PaintOrderListType type, Vector<RefPtr<Node> >& list)
+{
+ OwnPtr<Vector<RenderLayerStackingNode*> > posZOrderList;
+ OwnPtr<Vector<RenderLayerStackingNode*> > negZOrderList;
+
+ RenderLayerStackingNode* stackingNode = ancestorStackingNode();
+ if (!stackingNode)
+ return;
+
+ switch (type) {
+ case BeforePromote:
+ collectBeforePromotionZOrderList(stackingNode, posZOrderList, negZOrderList);
+ break;
+ case AfterPromote:
+ collectAfterPromotionZOrderList(stackingNode, posZOrderList, negZOrderList);
+ break;
+ }
+
+ if (negZOrderList) {
+ for (size_t index = 0; index < negZOrderList->size(); ++index)
+ list.append(negZOrderList->at(index)->renderer()->node());
+ }
+
+ if (posZOrderList) {
+ for (size_t index = 0; index < posZOrderList->size(); ++index)
+ list.append(posZOrderList->at(index)->renderer()->node());
+ }
+}
+
+bool RenderLayerStackingNode::descendantsAreContiguousInStackingOrder() const
+{
+ if (isStackingContext() || !ancestorStackingContainerNode())
+ return true;
+
+ ASSERT(!m_descendantsAreContiguousInStackingOrderDirty);
+ return m_descendantsAreContiguousInStackingOrder;
+}
+
+bool RenderLayerStackingNode::setNeedsToBeStackingContainer(bool needsToBeStackingContainer)
+{
+ if (this->needsToBeStackingContainer() == needsToBeStackingContainer)
+ return false;
+
+ // Count the total number of RenderLayers which need to be stacking
+ // containers some point. This should be recorded at most once per
+ // RenderLayer, so we check m_needsToBeStackingContainerHasBeenRecorded.
+ if (layer()->acceleratedCompositingForOverflowScrollEnabled() && !m_needsToBeStackingContainerHasBeenRecorded) {
+ blink::Platform::current()->histogramEnumeration("Renderer.CompositedScrolling", RenderLayer::NeedsToBeStackingContainerBucket, RenderLayer::CompositedScrollingHistogramMax);
+ m_needsToBeStackingContainerHasBeenRecorded = true;
+ }
+
+ m_needsToBeStackingContainer = needsToBeStackingContainer;
+
+ return true;
+}
+
+RenderLayerStackingNode* RenderLayerStackingNode::ancestorStackingContainerNode() const
+{
+ RenderLayer* ancestor = layer()->parent();
+ while (ancestor && !ancestor->stackingNode()->isStackingContainer())
+ ancestor = ancestor->parent();
+ if (ancestor)
+ return ancestor->stackingNode();
+ return 0;
+}
+
+RenderLayerStackingNode* RenderLayerStackingNode::ancestorStackingNode() const
+{
+ RenderLayer* ancestor = layer()->parent();
+ while (ancestor && !ancestor->stackingNode()->isStackingContext())
+ ancestor = ancestor->parent();
+ if (ancestor)
+ return ancestor->stackingNode();
+ return 0;
+}
+
+RenderLayerModelObject* RenderLayerStackingNode::renderer() const
+{
+ return m_layer->renderer();
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderLayerStackingNode.h b/chromium/third_party/WebKit/Source/core/rendering/RenderLayerStackingNode.h
new file mode 100644
index 00000000000..12d7490fd8f
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderLayerStackingNode.h
@@ -0,0 +1,276 @@
+/*
+ * Copyright (C) 2003, 2009, 2012 Apple Inc. All rights reserved.
+ * Copyright (C) 2013 Intel Corporation. All rights reserved.
+ *
+ * Portions are Copyright (C) 1998 Netscape Communications Corporation.
+ *
+ * Other contributors:
+ * Robert O'Callahan <roc+@cs.cmu.edu>
+ * David Baron <dbaron@fas.harvard.edu>
+ * Christian Biesinger <cbiesinger@web.de>
+ * Randall Jesup <rjesup@wgate.com>
+ * Roland Mainz <roland.mainz@informatik.med.uni-giessen.de>
+ * Josh Soref <timeless@mac.com>
+ * Boris Zbarsky <bzbarsky@mit.edu>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ *
+ * Alternatively, the contents of this file may be used under the terms
+ * of either the Mozilla Public License Version 1.1, found at
+ * http://www.mozilla.org/MPL/ (the "MPL") or the GNU General Public
+ * License Version 2.0, found at http://www.fsf.org/copyleft/gpl.html
+ * (the "GPL"), in which case the provisions of the MPL or the GPL are
+ * applicable instead of those above. If you wish to allow use of your
+ * version of this file only under the terms of one of those two
+ * licenses (the MPL or the GPL) and not to allow others to use your
+ * version of this file under the LGPL, indicate your decision by
+ * deletingthe provisions above and replace them with the notice and
+ * other provisions required by the MPL or the GPL, as the case may be.
+ * If you do not delete the provisions above, a recipient may use your
+ * version of this file under any of the LGPL, the MPL or the GPL.
+ */
+
+#ifndef RenderLayerStackingNode_h
+#define RenderLayerStackingNode_h
+
+#include "core/rendering/RenderLayerModelObject.h"
+#include "wtf/Noncopyable.h"
+#include "wtf/OwnPtr.h"
+#include "wtf/Vector.h"
+
+namespace WebCore {
+
+class RenderLayer;
+class RenderLayerCompositor;
+class RenderStyle;
+
+class RenderLayerStackingNode {
+ WTF_MAKE_NONCOPYABLE(RenderLayerStackingNode);
+public:
+ explicit RenderLayerStackingNode(RenderLayer*);
+ ~RenderLayerStackingNode();
+
+ int zIndex() const { return renderer()->style()->zIndex(); }
+
+ // A stacking context is a layer that has a non-auto z-index.
+ bool isStackingContext() const { return isStackingContext(renderer()->style()); }
+
+ // A stacking container can have z-order lists. All stacking contexts are
+ // stacking containers, but the converse is not true. Layers that use
+ // composited scrolling are stacking containers, but they may not
+ // necessarily be stacking contexts.
+ bool isStackingContainer() const { return isStackingContext() || needsToBeStackingContainer(); }
+
+ bool setNeedsToBeStackingContainer(bool);
+
+ // Returns true if z ordering would not change if this layer were a stacking container.
+ bool descendantsAreContiguousInStackingOrder() const;
+ void setDescendantsAreContiguousInStackingOrderDirty(bool flag) { m_descendantsAreContiguousInStackingOrderDirty = flag; }
+ void updateDescendantsAreContiguousInStackingOrder();
+
+ // Update our normal and z-index lists.
+ void updateLayerListsIfNeeded();
+
+ bool zOrderListsDirty() const { return m_zOrderListsDirty; }
+ void dirtyZOrderLists();
+ void updateZOrderLists();
+ void clearZOrderLists();
+ void dirtyStackingContainerZOrderLists();
+
+ bool hasPositiveZOrderList() const { return posZOrderList() && posZOrderList()->size(); }
+ bool hasNegativeZOrderList() const { return negZOrderList() && negZOrderList()->size(); }
+
+ bool isNormalFlowOnly() const { return m_isNormalFlowOnly; }
+ void updateIsNormalFlowOnly();
+ bool normalFlowListDirty() const { return m_normalFlowListDirty; }
+ void dirtyNormalFlowList();
+
+ enum PaintOrderListType {BeforePromote, AfterPromote};
+ void computePaintOrderList(PaintOrderListType, Vector<RefPtr<Node> >&);
+
+ void updateStackingNodesAfterStyleChange(const RenderStyle* oldStyle);
+
+ RenderLayerStackingNode* ancestorStackingContainerNode() const;
+ RenderLayerStackingNode* ancestorStackingNode() const;
+
+ // Gets the enclosing stacking container for this node, possibly the node
+ // itself, if it is a stacking container.
+ RenderLayerStackingNode* enclosingStackingContainerNode() { return isStackingContainer() ? this : ancestorStackingContainerNode(); }
+
+ RenderLayer* layer() const { return m_layer; }
+
+#if !ASSERT_DISABLED
+ bool layerListMutationAllowed() const { return m_layerListMutationAllowed; }
+ void setLayerListMutationAllowed(bool flag) { m_layerListMutationAllowed = flag; }
+#endif
+
+private:
+ friend class RenderLayerStackingNodeIterator;
+ friend class RenderLayerStackingNodeReverseIterator;
+ friend class RenderTreeAsText;
+
+ Vector<RenderLayerStackingNode*>* posZOrderList() const
+ {
+ ASSERT(!m_zOrderListsDirty);
+ ASSERT(isStackingContainer() || !m_posZOrderList);
+ return m_posZOrderList.get();
+ }
+
+ Vector<RenderLayerStackingNode*>* normalFlowList() const
+ {
+ ASSERT(!m_normalFlowListDirty);
+ return m_normalFlowList.get();
+ }
+
+ Vector<RenderLayerStackingNode*>* negZOrderList() const
+ {
+ ASSERT(!m_zOrderListsDirty);
+ ASSERT(isStackingContainer() || !m_negZOrderList);
+ return m_negZOrderList.get();
+ }
+
+ enum CollectLayersBehavior {
+ ForceLayerToStackingContainer,
+ OverflowScrollCanBeStackingContainers,
+ OnlyStackingContextsCanBeStackingContainers
+ };
+
+ bool isStackingContext(const RenderStyle*) const;
+
+ void rebuildZOrderLists();
+
+ // layerToForceAsStackingContainer allows us to build pre-promotion and
+ // post-promotion layer lists, by allowing us to treat a layer as if it is a
+ // stacking context, without adding a new member to RenderLayer or modifying
+ // the style (which could cause extra allocations).
+ void rebuildZOrderLists(OwnPtr<Vector<RenderLayerStackingNode*> >&, OwnPtr<Vector<RenderLayerStackingNode*> >&,
+ const RenderLayerStackingNode* nodeToForceAsStackingContainer = 0,
+ CollectLayersBehavior = OverflowScrollCanBeStackingContainers);
+
+ void collectLayers(OwnPtr<Vector<RenderLayerStackingNode*> >&,
+ OwnPtr<Vector<RenderLayerStackingNode*> >&, const RenderLayerStackingNode* nodeToForceAsStackingContainer = 0,
+ CollectLayersBehavior = OverflowScrollCanBeStackingContainers);
+
+#if !ASSERT_DISABLED
+ bool isInStackingParentZOrderLists() const;
+ bool isInStackingParentNormalFlowList() const;
+ void updateStackingParentForZOrderLists(RenderLayerStackingNode* stackingParent);
+ void updateStackingParentForNormalFlowList(RenderLayerStackingNode* stackingParent);
+ void setStackingParent(RenderLayerStackingNode* stackingParent) { m_stackingParent = stackingParent; }
+#endif
+
+ bool shouldBeNormalFlowOnly() const;
+ bool shouldBeNormalFlowOnlyIgnoringCompositedScrolling() const;
+
+ void updateNormalFlowList();
+ void dirtyNormalFlowListCanBePromotedToStackingContainer();
+
+ void dirtySiblingStackingNodeCanBePromotedToStackingContainer();
+
+ void collectBeforePromotionZOrderList(RenderLayerStackingNode*,
+ OwnPtr<Vector<RenderLayerStackingNode*> >& posZOrderList, OwnPtr<Vector<RenderLayerStackingNode*> >& negZOrderList);
+ void collectAfterPromotionZOrderList(RenderLayerStackingNode*,
+ OwnPtr<Vector<RenderLayerStackingNode*> >& posZOrderList, OwnPtr<Vector<RenderLayerStackingNode*> >& negZOrderList);
+
+ bool isDirtyStackingContainer() const { return m_zOrderListsDirty && isStackingContainer(); }
+
+ bool needsToBeStackingContainer() const;
+
+ RenderLayerCompositor* compositor() const;
+ // FIXME: Investigate changing this to Renderbox.
+ RenderLayerModelObject* renderer() const;
+
+ RenderLayer* m_layer;
+
+ // For stacking contexts, m_posZOrderList holds a sorted list of all the
+ // descendant nodes within the stacking context that have z-indices of 0 or greater
+ // (auto will count as 0). m_negZOrderList holds descendants within our stacking context with negative
+ // z-indices.
+ OwnPtr<Vector<RenderLayerStackingNode*> > m_posZOrderList;
+ OwnPtr<Vector<RenderLayerStackingNode*> > m_negZOrderList;
+
+ // This list contains child nodes that cannot create stacking contexts. For now it is just
+ // overflow layers, but that may change in the future.
+ OwnPtr<Vector<RenderLayerStackingNode*> > m_normalFlowList;
+
+ // If this is true, then no non-descendant appears between any of our
+ // descendants in stacking order. This is one of the requirements of being
+ // able to safely become a stacking context.
+ unsigned m_descendantsAreContiguousInStackingOrder : 1;
+ unsigned m_descendantsAreContiguousInStackingOrderDirty : 1;
+
+ unsigned m_zOrderListsDirty : 1;
+ unsigned m_normalFlowListDirty: 1;
+ unsigned m_isNormalFlowOnly : 1;
+
+ unsigned m_needsToBeStackingContainer : 1;
+ unsigned m_needsToBeStackingContainerHasBeenRecorded : 1;
+
+#if !ASSERT_DISABLED
+ unsigned m_layerListMutationAllowed : 1;
+ RenderLayerStackingNode* m_stackingParent;
+#endif
+};
+
+inline void RenderLayerStackingNode::clearZOrderLists()
+{
+ ASSERT(!isStackingContainer());
+
+#if !ASSERT_DISABLED
+ updateStackingParentForZOrderLists(0);
+#endif
+
+ m_posZOrderList.clear();
+ m_negZOrderList.clear();
+}
+
+inline void RenderLayerStackingNode::updateZOrderLists()
+{
+ if (!m_zOrderListsDirty)
+ return;
+
+ if (!isStackingContainer()) {
+ clearZOrderLists();
+ m_zOrderListsDirty = false;
+ return;
+ }
+
+ rebuildZOrderLists();
+}
+
+#if !ASSERT_DISABLED
+class LayerListMutationDetector {
+public:
+ explicit LayerListMutationDetector(RenderLayerStackingNode* stackingNode)
+ : m_stackingNode(stackingNode)
+ , m_previousMutationAllowedState(stackingNode->layerListMutationAllowed())
+ {
+ m_stackingNode->setLayerListMutationAllowed(false);
+ }
+
+ ~LayerListMutationDetector()
+ {
+ m_stackingNode->setLayerListMutationAllowed(m_previousMutationAllowedState);
+ }
+
+private:
+ RenderLayerStackingNode* m_stackingNode;
+ bool m_previousMutationAllowedState;
+};
+#endif
+
+} // namespace WebCore
+
+#endif // RenderLayerStackingNode_h
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderLayerStackingNodeIterator.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderLayerStackingNodeIterator.cpp
new file mode 100644
index 00000000000..8c16179ef0a
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderLayerStackingNodeIterator.cpp
@@ -0,0 +1,140 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/rendering/RenderLayerStackingNodeIterator.h"
+
+#include "core/rendering/RenderLayer.h"
+#include "core/rendering/RenderLayerStackingNode.h"
+
+namespace WebCore {
+
+RenderLayerStackingNode* RenderLayerStackingNodeIterator::next()
+{
+ if (m_remainingChildren & NegativeZOrderChildren) {
+ Vector<RenderLayerStackingNode*>* negZOrderList = m_root.negZOrderList();
+ if (negZOrderList && m_index < negZOrderList->size())
+ return negZOrderList->at(m_index++);
+
+ m_index = 0;
+ m_remainingChildren &= ~NegativeZOrderChildren;
+ }
+
+ if (m_remainingChildren & NormalFlowChildren) {
+ Vector<RenderLayerStackingNode*>* normalFlowList = m_root.normalFlowList();
+ if (normalFlowList && m_index < normalFlowList->size())
+ return normalFlowList->at(m_index++);
+
+ m_index = 0;
+ m_remainingChildren &= ~NormalFlowChildren;
+ }
+
+ if (m_remainingChildren & PositiveZOrderChildren) {
+ Vector<RenderLayerStackingNode*>* posZOrderList = m_root.posZOrderList();
+ if (posZOrderList && m_index < posZOrderList->size())
+ return posZOrderList->at(m_index++);
+
+ m_index = 0;
+ m_remainingChildren &= ~PositiveZOrderChildren;
+ }
+
+ return 0;
+}
+
+RenderLayerStackingNode* RenderLayerStackingNodeReverseIterator::next()
+{
+ if (m_remainingChildren & NegativeZOrderChildren) {
+ Vector<RenderLayerStackingNode*>* negZOrderList = m_root.negZOrderList();
+ if (negZOrderList && m_index >= 0)
+ return negZOrderList->at(m_index--);
+
+ m_remainingChildren &= ~NegativeZOrderChildren;
+ setIndexToLastItem();
+ }
+
+ if (m_remainingChildren & NormalFlowChildren) {
+ Vector<RenderLayerStackingNode*>* normalFlowList = m_root.normalFlowList();
+ if (normalFlowList && m_index >= 0)
+ return normalFlowList->at(m_index--);
+
+ m_remainingChildren &= ~NormalFlowChildren;
+ setIndexToLastItem();
+ }
+
+ if (m_remainingChildren & PositiveZOrderChildren) {
+ Vector<RenderLayerStackingNode*>* posZOrderList = m_root.posZOrderList();
+ if (posZOrderList && m_index >= 0)
+ return posZOrderList->at(m_index--);
+
+ m_remainingChildren &= ~PositiveZOrderChildren;
+ setIndexToLastItem();
+ }
+
+ return 0;
+}
+
+void RenderLayerStackingNodeReverseIterator::setIndexToLastItem()
+{
+ if (m_remainingChildren & NegativeZOrderChildren) {
+ Vector<RenderLayerStackingNode*>* negZOrderList = m_root.negZOrderList();
+ if (negZOrderList) {
+ m_index = negZOrderList->size() - 1;
+ return;
+ }
+
+ m_remainingChildren &= ~NegativeZOrderChildren;
+ }
+
+ if (m_remainingChildren & NormalFlowChildren) {
+ Vector<RenderLayerStackingNode*>* normalFlowList = m_root.normalFlowList();
+ if (normalFlowList) {
+ m_index = normalFlowList->size() - 1;
+ return;
+ }
+
+ m_remainingChildren &= ~NormalFlowChildren;
+ }
+
+ if (m_remainingChildren & PositiveZOrderChildren) {
+ Vector<RenderLayerStackingNode*>* posZOrderList = m_root.posZOrderList();
+ if (posZOrderList) {
+ m_index = posZOrderList->size() - 1;
+ return;
+ }
+
+ m_remainingChildren &= ~PositiveZOrderChildren;
+ }
+
+ // No more list to visit.
+ ASSERT(!m_remainingChildren);
+ m_index = -1;
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderLayerStackingNodeIterator.h b/chromium/third_party/WebKit/Source/core/rendering/RenderLayerStackingNodeIterator.h
new file mode 100644
index 00000000000..7682ea33d58
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderLayerStackingNodeIterator.h
@@ -0,0 +1,92 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef RenderLayerStackingNodeIterator_h
+#define RenderLayerStackingNodeIterator_h
+
+#include "wtf/Noncopyable.h"
+
+namespace WebCore {
+
+enum ChildrenIteration {
+ NegativeZOrderChildren = 1,
+ NormalFlowChildren = 1 << 1,
+ PositiveZOrderChildren = 1 << 2,
+ AllChildren = NegativeZOrderChildren | NormalFlowChildren | PositiveZOrderChildren
+};
+
+class RenderLayer;
+class RenderLayerStackingNode;
+
+// This iterator walks the RenderLayerStackingNode lists in the following order:
+// NegativeZOrderChildren -> NormalFlowChildren -> PositiveZOrderChildren.
+class RenderLayerStackingNodeIterator {
+ WTF_MAKE_NONCOPYABLE(RenderLayerStackingNodeIterator);
+public:
+ RenderLayerStackingNodeIterator(const RenderLayerStackingNode& root, unsigned whichChildren)
+ : m_root(root)
+ , m_remainingChildren(whichChildren)
+ , m_index(0)
+ {
+ }
+
+ RenderLayerStackingNode* next();
+
+private:
+ const RenderLayerStackingNode& m_root;
+ unsigned m_remainingChildren;
+ unsigned m_index;
+};
+
+// This iterator is similar to RenderLayerStackingNodeIterator but it walks the lists in reverse order
+// (from the last item to the first one).
+class RenderLayerStackingNodeReverseIterator {
+ WTF_MAKE_NONCOPYABLE(RenderLayerStackingNodeReverseIterator);
+public:
+ RenderLayerStackingNodeReverseIterator(const RenderLayerStackingNode& root, unsigned whichChildren)
+ : m_root(root)
+ , m_remainingChildren(whichChildren)
+ {
+ setIndexToLastItem();
+ }
+
+ RenderLayerStackingNode* next();
+
+private:
+ void setIndexToLastItem();
+
+ const RenderLayerStackingNode& m_root;
+ unsigned m_remainingChildren;
+ int m_index;
+};
+
+} // namespace WebCore
+
+#endif // RenderLayerStackingNodeIterator_h
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderListBox.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderListBox.cpp
index 8dedc002ad0..bc4617f29ff 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderListBox.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderListBox.cpp
@@ -36,7 +36,6 @@
#include "core/css/CSSFontSelector.h"
#include "core/css/resolver/StyleResolver.h"
#include "core/dom/Document.h"
-#include "core/dom/DocumentEventQueue.h"
#include "core/dom/NodeRenderStyle.h"
#include "core/editing/FrameSelection.h"
#include "core/html/HTMLOptGroupElement.h"
@@ -44,19 +43,20 @@
#include "core/html/HTMLSelectElement.h"
#include "core/page/EventHandler.h"
#include "core/page/FocusController.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameView.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
#include "core/page/Page.h"
#include "core/page/SpatialNavigation.h"
-#include "core/platform/Scrollbar.h"
-#include "core/platform/graphics/FontCache.h"
-#include "core/platform/graphics/GraphicsContext.h"
#include "core/rendering/HitTestResult.h"
+#include "core/rendering/LayoutRectRecorder.h"
#include "core/rendering/PaintInfo.h"
#include "core/rendering/RenderScrollbar.h"
#include "core/rendering/RenderText.h"
#include "core/rendering/RenderTheme.h"
#include "core/rendering/RenderView.h"
+#include "platform/fonts/FontCache.h"
+#include "platform/graphics/GraphicsContext.h"
+#include "platform/scroll/Scrollbar.h"
using namespace std;
@@ -128,7 +128,7 @@ void RenderListBox::updateFromElement()
FontDescription d = itemFont.fontDescription();
d.setWeight(d.bolderWeight());
itemFont = Font(d, itemFont.letterSpacing(), itemFont.wordSpacing());
- itemFont.update(document().styleResolver()->fontSelector());
+ itemFont.update(document().styleEngine()->fontSelector());
}
if (!text.isEmpty()) {
@@ -149,11 +149,6 @@ void RenderListBox::updateFromElement()
}
}
-bool RenderListBox::canBeReplacedWithInlineRunIn() const
-{
- return false;
-}
-
void RenderListBox::selectionChanged()
{
repaint();
@@ -170,6 +165,7 @@ void RenderListBox::selectionChanged()
void RenderListBox::layout()
{
+ LayoutRectRecorder recorder(*this);
RenderBlockFlow::layout();
if (m_vBar) {
@@ -203,7 +199,7 @@ void RenderListBox::computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, L
{
maxLogicalWidth = m_optionsWidth + 2 * optionsSpacingHorizontal;
if (m_vBar)
- maxLogicalWidth += m_vBar->width();
+ maxLogicalWidth += verticalScrollbarWidth();
if (!style()->width().isPercent())
minLogicalWidth = maxLogicalWidth;
}
@@ -275,7 +271,9 @@ int RenderListBox::baselinePosition(FontBaseline baselineType, bool firstLine, L
LayoutRect RenderListBox::itemBoundingBoxRect(const LayoutPoint& additionalOffset, int index)
{
- return LayoutRect(additionalOffset.x() + borderLeft() + paddingLeft(),
+ // For RTL, items start after the left-side vertical scrollbar.
+ int scrollbarOffset = style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft() ? verticalScrollbarWidth() : 0;
+ return LayoutRect(additionalOffset.x() + borderLeft() + paddingLeft() + scrollbarOffset,
additionalOffset.y() + borderTop() + paddingTop() + itemHeight() * (index - m_indexOffset),
contentWidth(), itemHeight());
}
@@ -349,12 +347,22 @@ void RenderListBox::addFocusRingRects(Vector<IntRect>& rects, const LayoutPoint&
}
}
+int RenderListBox::scrollbarLeft() const
+{
+ int scrollbarLeft = 0;
+ if (style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
+ scrollbarLeft = borderLeft();
+ else
+ scrollbarLeft = width() - borderRight() - verticalScrollbarWidth();
+ return scrollbarLeft;
+}
+
void RenderListBox::paintScrollbar(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
{
if (m_vBar) {
- IntRect scrollRect = pixelSnappedIntRect(paintOffset.x() + width() - borderRight() - m_vBar->width(),
+ IntRect scrollRect = pixelSnappedIntRect(paintOffset.x() + scrollbarLeft(),
paintOffset.y() + borderTop(),
- m_vBar->width(),
+ verticalScrollbarWidth(),
height() - (borderTop() + borderBottom()));
m_vBar->setFrameRect(scrollRect);
m_vBar->paint(paintInfo.context, paintInfo.rect);
@@ -425,7 +433,7 @@ void RenderListBox::paintItemForeground(PaintInfo& paintInfo, const LayoutPoint&
FontDescription d = itemFont.fontDescription();
d.setWeight(d.bolderWeight());
itemFont = Font(d, itemFont.letterSpacing(), itemFont.wordSpacing());
- itemFont.update(document().styleResolver()->fontSelector());
+ itemFont.update(document().styleEngine()->fontSelector());
}
// Draw the item text
@@ -462,9 +470,9 @@ bool RenderListBox::isPointInOverflowControl(HitTestResult& result, const Layout
if (!m_vBar || !m_vBar->shouldParticipateInHitTesting())
return false;
- LayoutRect vertRect(accumulatedOffset.x() + width() - borderRight() - m_vBar->width(),
+ LayoutRect vertRect(accumulatedOffset.x() + scrollbarLeft(),
accumulatedOffset.y() + borderTop(),
- m_vBar->width(),
+ verticalScrollbarWidth(),
height() - borderTop() - borderBottom());
if (vertRect.contains(locationInContainer)) {
@@ -482,8 +490,11 @@ int RenderListBox::listIndexAtOffset(const LayoutSize& offset)
if (offset.height() < borderTop() + paddingTop() || offset.height() > height() - paddingBottom() - borderBottom())
return -1;
- int scrollbarWidth = m_vBar ? m_vBar->width() : 0;
- if (offset.width() < borderLeft() + paddingLeft() || offset.width() > width() - borderRight() - paddingRight() - scrollbarWidth)
+ int scrollbarWidth = verticalScrollbarWidth();
+ int rightScrollbarOffset = style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft() ? scrollbarWidth : 0;
+ int leftScrollbarOffset = style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft() ? 0 : scrollbarWidth;
+ if (offset.width() < borderLeft() + paddingLeft() + rightScrollbarOffset
+ || offset.width() > width() - borderRight() - paddingRight() - leftScrollbarOffset)
return -1;
int newOffset = (offset.height() - borderTop() - paddingTop()) / itemHeight() + m_indexOffset;
@@ -499,7 +510,7 @@ void RenderListBox::panScroll(const IntPoint& panStartMousePosition)
// FIXME: This doesn't work correctly with transforms.
FloatPoint absOffset = localToAbsolute();
- IntPoint lastKnownMousePosition = frame()->eventHandler()->lastKnownMousePosition();
+ IntPoint lastKnownMousePosition = frame()->eventHandler().lastKnownMousePosition();
// We need to check if the last known mouse position is out of the window. When the mouse is out of the window, the position is incoherent
static IntPoint previousMousePosition;
if (lastKnownMousePosition.y() < 0)
@@ -556,7 +567,7 @@ int RenderListBox::scrollToward(const IntPoint& destination)
void RenderListBox::autoscroll(const IntPoint&)
{
- IntPoint pos = frame()->view()->windowToContents(frame()->eventHandler()->lastKnownMousePosition());
+ IntPoint pos = frame()->view()->windowToContents(frame()->eventHandler().lastKnownMousePosition());
int endIndex = scrollToward(pos);
if (selectElement()->isDisabledFormControl())
@@ -604,7 +615,7 @@ bool RenderListBox::listIndexIsVisible(int index)
return index >= m_indexOffset && index < m_indexOffset + numVisibleItems();
}
-bool RenderListBox::scrollImpl(ScrollDirection direction, ScrollGranularity granularity, float multiplier)
+bool RenderListBox::scroll(ScrollDirection direction, ScrollGranularity granularity, float multiplier)
{
return ScrollableArea::scroll(direction, granularity, multiplier);
}
@@ -638,7 +649,7 @@ void RenderListBox::scrollTo(int newOffset)
m_indexOffset = newOffset;
repaint();
- node()->document().eventQueue()->enqueueOrDispatchScrollEvent(node(), DocumentEventQueue::ScrollEventElementTarget);
+ node()->document().enqueueScrollEventForNode(node());
}
LayoutUnit RenderListBox::itemHeight() const
@@ -714,7 +725,10 @@ bool RenderListBox::nodeAtPoint(const HitTestRequest& request, HitTestResult& re
LayoutRect RenderListBox::controlClipRect(const LayoutPoint& additionalOffset) const
{
LayoutRect clipRect = contentBoxRect();
- clipRect.moveBy(additionalOffset);
+ if (style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
+ clipRect.moveBy(additionalOffset + LayoutPoint(verticalScrollbarWidth(), 0));
+ else
+ clipRect.moveBy(additionalOffset);
return clipRect;
}
@@ -727,7 +741,10 @@ bool RenderListBox::isActive() const
void RenderListBox::invalidateScrollbarRect(Scrollbar* scrollbar, const IntRect& rect)
{
IntRect scrollRect = rect;
- scrollRect.move(width() - borderRight() - scrollbar->width(), borderTop());
+ if (style()->shouldPlaceBlockDirectionScrollbarOnLogicalLeft())
+ scrollRect.move(borderLeft(), borderTop());
+ else
+ scrollRect.move(width() - borderRight() - scrollbar->width(), borderTop());
repaintRectangle(scrollRect);
}
@@ -739,9 +756,8 @@ IntRect RenderListBox::convertFromScrollbarToContainingView(const Scrollbar* scr
IntRect rect = scrollbarRect;
- int scrollbarLeft = width() - borderRight() - scrollbar->width();
int scrollbarTop = borderTop();
- rect.move(scrollbarLeft, scrollbarTop);
+ rect.move(scrollbarLeft(), scrollbarTop);
return view->frameView()->convertFromRenderer(this, rect);
}
@@ -754,9 +770,8 @@ IntRect RenderListBox::convertFromContainingViewToScrollbar(const Scrollbar* scr
IntRect rect = view->frameView()->convertToRenderer(this, parentRect);
- int scrollbarLeft = width() - borderRight() - scrollbar->width();
int scrollbarTop = borderTop();
- rect.move(-scrollbarLeft, -scrollbarTop);
+ rect.move(-scrollbarLeft(), -scrollbarTop);
return rect;
}
@@ -768,9 +783,8 @@ IntPoint RenderListBox::convertFromScrollbarToContainingView(const Scrollbar* sc
IntPoint point = scrollbarPoint;
- int scrollbarLeft = width() - borderRight() - scrollbar->width();
int scrollbarTop = borderTop();
- point.move(scrollbarLeft, scrollbarTop);
+ point.move(scrollbarLeft(), scrollbarTop);
return view->frameView()->convertFromRenderer(this, point);
}
@@ -783,9 +797,8 @@ IntPoint RenderListBox::convertFromContainingViewToScrollbar(const Scrollbar* sc
IntPoint point = view->frameView()->convertToRenderer(this, parentPoint);
- int scrollbarLeft = width() - borderRight() - scrollbar->width();
int scrollbarTop = borderTop();
- point.move(-scrollbarLeft, -scrollbarTop);
+ point.move(-scrollbarLeft(), -scrollbarTop);
return point;
}
@@ -882,7 +895,7 @@ PassRefPtr<Scrollbar> RenderListBox::createScrollbar()
widget = RenderScrollbar::createCustomScrollbar(this, VerticalScrollbar, this->node());
else {
widget = Scrollbar::create(this, VerticalScrollbar, RenderTheme::theme().scrollbarControlSizeForPart(ListboxPart));
- didAddVerticalScrollbar(widget.get());
+ didAddScrollbar(widget.get(), VerticalScrollbar);
}
document().view()->addChild(widget.get());
return widget.release();
@@ -894,7 +907,7 @@ void RenderListBox::destroyScrollbar()
return;
if (!m_vBar->isCustomScrollbar())
- ScrollableArea::willRemoveVerticalScrollbar(m_vBar.get());
+ ScrollableArea::willRemoveScrollbar(m_vBar.get(), VerticalScrollbar);
m_vBar->removeFromParent();
m_vBar->disconnectFromScrollableArea();
m_vBar = 0;
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderListBox.h b/chromium/third_party/WebKit/Source/core/rendering/RenderListBox.h
index 9c4eceba769..c86b50869bc 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderListBox.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderListBox.h
@@ -31,8 +31,8 @@
#ifndef RenderListBox_h
#define RenderListBox_h
-#include "core/platform/ScrollableArea.h"
#include "core/rendering/RenderBlockFlow.h"
+#include "platform/scroll/ScrollableArea.h"
namespace WebCore {
@@ -65,14 +65,13 @@ private:
virtual bool isListBox() const { return true; }
virtual void updateFromElement();
- virtual bool canBeReplacedWithInlineRunIn() const OVERRIDE;
virtual bool hasControlClip() const { return true; }
virtual void paintObject(PaintInfo&, const LayoutPoint&);
virtual LayoutRect controlClipRect(const LayoutPoint&) const;
virtual bool isPointInOverflowControl(HitTestResult&, const LayoutPoint& locationInContainer, const LayoutPoint& accumulatedOffset);
- virtual bool scrollImpl(ScrollDirection, ScrollGranularity, float) OVERRIDE;
+ virtual bool scroll(ScrollDirection, ScrollGranularity, float) OVERRIDE;
virtual void computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const OVERRIDE;
virtual void computePreferredLogicalWidths() OVERRIDE;
@@ -146,6 +145,7 @@ private:
int numVisibleItems() const;
int numItems() const;
LayoutUnit listHeight() const;
+ int scrollbarLeft() const;
void paintScrollbar(PaintInfo&, const LayoutPoint&);
void paintItemForeground(PaintInfo&, const LayoutPoint&, int listIndex);
void paintItemBackground(PaintInfo&, const LayoutPoint&, int listIndex);
@@ -160,14 +160,7 @@ private:
RefPtr<Scrollbar> m_vBar;
};
-inline RenderListBox* toRenderListBox(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isListBox());
- return static_cast<RenderListBox*>(object);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toRenderListBox(const RenderListBox*);
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderListBox, isListBox());
} // namepace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderListItem.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderListItem.cpp
index d88a48f5e7a..b3b57a571ba 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderListItem.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderListItem.cpp
@@ -27,6 +27,7 @@
#include "HTMLNames.h"
#include "core/dom/ElementTraversal.h"
#include "core/html/HTMLOListElement.h"
+#include "core/rendering/LayoutRectRecorder.h"
#include "core/rendering/RenderListMarker.h"
#include "core/rendering/RenderView.h"
#include "wtf/StdLibExtras.h"
@@ -55,6 +56,10 @@ void RenderListItem::styleDidChange(StyleDifference diff, const RenderStyle* old
if (style()->listStyleType() != NoneListStyle
|| (style()->listStyleImage() && !style()->listStyleImage()->errorOccurred())) {
RefPtr<RenderStyle> newStyle = RenderStyle::create();
+ // Markers update their own margin style. By copying the existing style we can
+ // avoid an unnecessary layout in setStyle below.
+ if (m_marker)
+ newStyle->copyNonInheritedFrom(m_marker->style());
// The marker always inherits from the list item, regardless of where it might end
// up (e.g., in some deeply nested line box). See CSS3 spec.
newStyle->inheritFrom(style());
@@ -78,7 +83,7 @@ void RenderListItem::willBeDestroyed()
void RenderListItem::insertedIntoTree()
{
- RenderBlock::insertedIntoTree();
+ RenderBlockFlow::insertedIntoTree();
updateListMarkerNumbers();
}
@@ -121,12 +126,13 @@ static RenderListItem* nextListItem(const Node* listNode, const RenderListItem*
return 0;
const Node* current = item ? item->node() : listNode;
- current = ElementTraversal::nextIncludingPseudo(current, listNode);
+ ASSERT(current);
+ current = ElementTraversal::nextIncludingPseudo(*current, listNode);
while (current) {
if (isList(current)) {
// We've found a nested, independent list: nothing to do here.
- current = ElementTraversal::nextIncludingPseudoSkippingChildren(current, listNode);
+ current = ElementTraversal::nextIncludingPseudoSkippingChildren(*current, listNode);
continue;
}
@@ -135,7 +141,7 @@ static RenderListItem* nextListItem(const Node* listNode, const RenderListItem*
return toRenderListItem(renderer);
// FIXME: Can this be optimized to skip the children of the elements without a renderer?
- current = ElementTraversal::nextIncludingPseudo(current, listNode);
+ current = ElementTraversal::nextIncludingPseudo(*current, listNode);
}
return 0;
@@ -145,7 +151,8 @@ static RenderListItem* nextListItem(const Node* listNode, const RenderListItem*
static RenderListItem* previousListItem(const Node* listNode, const RenderListItem* item)
{
Node* current = item->node();
- for (current = ElementTraversal::previousIncludingPseudo(current, listNode); current; current = ElementTraversal::previousIncludingPseudo(current, listNode)) {
+ ASSERT(current);
+ for (current = ElementTraversal::previousIncludingPseudo(*current, listNode); current; current = ElementTraversal::previousIncludingPseudo(*current, listNode)) {
RenderObject* renderer = current->renderer();
if (!renderer || (renderer && !renderer->isListItem()))
continue;
@@ -158,7 +165,7 @@ static RenderListItem* previousListItem(const Node* listNode, const RenderListIt
// be a list item itself. We need to examine it, so we do this to counteract
// the previousIncludingPseudo() that will be done by the loop.
if (otherList)
- current = ElementTraversal::nextIncludingPseudo(otherList);
+ current = ElementTraversal::nextIncludingPseudo(*otherList);
}
return 0;
}
@@ -215,7 +222,7 @@ bool RenderListItem::isEmpty() const
return lastChild() == m_marker;
}
-static RenderObject* getParentOfFirstLineBox(RenderBlock* curr, RenderObject* marker)
+static RenderObject* getParentOfFirstLineBox(RenderBlockFlow* curr, RenderObject* marker)
{
RenderObject* firstChild = curr->firstChild();
if (!firstChild)
@@ -232,14 +239,14 @@ static RenderObject* getParentOfFirstLineBox(RenderBlock* curr, RenderObject* ma
if (currChild->isFloating() || currChild->isOutOfFlowPositioned())
continue;
- if (currChild->isTable() || !currChild->isRenderBlock() || (currChild->isBox() && toRenderBox(currChild)->isWritingModeRoot()))
+ if (!currChild->isRenderBlockFlow() || (currChild->isBox() && toRenderBox(currChild)->isWritingModeRoot()))
break;
if (curr->isListItem() && inQuirksMode && currChild->node() &&
(currChild->node()->hasTagName(ulTag)|| currChild->node()->hasTagName(olTag)))
break;
- RenderObject* lineBox = getParentOfFirstLineBox(toRenderBlock(currChild), marker);
+ RenderObject* lineBox = getParentOfFirstLineBox(toRenderBlockFlow(currChild), marker);
if (lineBox)
return lineBox;
}
@@ -309,6 +316,7 @@ void RenderListItem::layout()
{
ASSERT(needsLayout());
+ LayoutRectRecorder recorder(*this);
updateMarkerLocation();
RenderBlockFlow::layout();
}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderListItem.h b/chromium/third_party/WebKit/Source/core/rendering/RenderListItem.h
index 9e5d42eb208..76f6087ea4b 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderListItem.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderListItem.h
@@ -49,6 +49,7 @@ public:
String markerTextWithSuffix() const;
void updateListMarkerNumbers();
+ void updateMarkerLocation();
static void updateItemValuesForOrderedList(const HTMLOListElement*);
static unsigned itemCountForOrderedList(const HTMLOListElement*);
@@ -74,11 +75,8 @@ private:
virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle);
- virtual bool requiresForcedStyleRecalcPropagation() const { return true; }
-
virtual void addOverflowFromChildren();
- void updateMarkerLocation();
inline int calcValue() const;
void updateValueNow() const;
void explicitValueChanged();
@@ -92,14 +90,7 @@ private:
bool m_notInList : 1;
};
-inline RenderListItem* toRenderListItem(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isListItem());
- return static_cast<RenderListItem*>(object);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toRenderListItem(const RenderListItem*);
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderListItem, isListItem());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderListMarker.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderListMarker.cpp
index 48c7676aa87..f05497493e5 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderListMarker.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderListMarker.cpp
@@ -27,11 +27,13 @@
#include "core/dom/Document.h"
#include "core/fetch/ImageResource.h"
-#include "core/platform/graphics/Font.h"
-#include "core/platform/graphics/GraphicsContextStateSaver.h"
+#include "core/rendering/GraphicsContextAnnotator.h"
+#include "core/rendering/LayoutRectRecorder.h"
#include "core/rendering/RenderLayer.h"
#include "core/rendering/RenderListItem.h"
#include "core/rendering/RenderView.h"
+#include "platform/fonts/Font.h"
+#include "platform/graphics/GraphicsContextStateSaver.h"
#include "wtf/text/StringBuilder.h"
#include "wtf/unicode/CharacterNames.h"
@@ -1264,7 +1266,7 @@ void RenderListMarker::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffse
return;
const Font& font = style()->font();
- TextRun textRun = RenderBlock::constructTextRun(this, font, m_text, style());
+ TextRun textRun = RenderBlockFlow::constructTextRun(this, font, m_text, style());
GraphicsContextStateSaver stateSaver(*context, false);
if (!style()->isHorizontalWritingMode()) {
@@ -1303,13 +1305,13 @@ void RenderListMarker::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffse
context->drawText(font, textRunPaintInfo, textOrigin);
UChar suffixSpace[2] = { suffix, ' ' };
- TextRun suffixRun = RenderBlock::constructTextRun(this, font, suffixSpace, 2, style());
+ TextRun suffixRun = RenderBlockFlow::constructTextRun(this, font, suffixSpace, 2, style());
TextRunPaintInfo suffixRunInfo(suffixRun);
suffixRunInfo.bounds = marker;
context->drawText(font, suffixRunInfo, textOrigin + IntSize(font.width(textRun), 0));
} else {
UChar spaceSuffix[2] = { ' ', suffix };
- TextRun suffixRun = RenderBlock::constructTextRun(this, font, spaceSuffix, 2, style());
+ TextRun suffixRun = RenderBlockFlow::constructTextRun(this, font, spaceSuffix, 2, style());
TextRunPaintInfo suffixRunInfo(suffixRun);
suffixRunInfo.bounds = marker;
context->drawText(font, suffixRunInfo, textOrigin);
@@ -1323,6 +1325,7 @@ void RenderListMarker::layout()
{
ASSERT(needsLayout());
+ LayoutRectRecorder recorder(*this);
if (isImage()) {
updateMarginsAndContent();
setWidth(m_image->imageSize(this, style()->effectiveZoom()).width());
@@ -1580,7 +1583,7 @@ void RenderListMarker::computePreferredLogicalWidths()
else {
LayoutUnit itemWidth = font.width(m_text);
UChar suffixSpace[2] = { listMarkerSuffix(type, m_listItem->value()), ' ' };
- LayoutUnit suffixSpaceWidth = font.width(RenderBlock::constructTextRun(this, font, suffixSpace, 2, style()));
+ LayoutUnit suffixSpaceWidth = font.width(RenderBlockFlow::constructTextRun(this, font, suffixSpace, 2, style()));
logicalWidth = itemWidth + suffixSpaceWidth;
}
break;
@@ -1806,7 +1809,7 @@ IntRect RenderListMarker::getRelativeMarkerRect()
const Font& font = style()->font();
int itemWidth = font.width(m_text);
UChar suffixSpace[2] = { listMarkerSuffix(type, m_listItem->value()), ' ' };
- int suffixSpaceWidth = font.width(RenderBlock::constructTextRun(this, font, suffixSpace, 2, style()));
+ int suffixSpaceWidth = font.width(RenderBlockFlow::constructTextRun(this, font, suffixSpace, 2, style()));
relativeRect = IntRect(0, 0, itemWidth + suffixSpaceWidth, font.fontMetrics().height());
}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderListMarker.h b/chromium/third_party/WebKit/Source/core/rendering/RenderListMarker.h
index c8a086790d9..d0002ffb973 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderListMarker.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderListMarker.h
@@ -86,20 +86,7 @@ private:
RenderListItem* m_listItem;
};
-inline RenderListMarker* toRenderListMarker(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isListMarker());
- return static_cast<RenderListMarker*>(object);
-}
-
-inline const RenderListMarker* toRenderListMarker(const RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isListMarker());
- return static_cast<const RenderListMarker*>(object);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toRenderListMarker(const RenderListMarker*);
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderListMarker, isListMarker());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderMarquee.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderMarquee.cpp
index 58492226f79..a40fed1583d 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderMarquee.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderMarquee.cpp
@@ -48,8 +48,8 @@
#include "HTMLNames.h"
#include "core/html/HTMLMarqueeElement.h"
-#include "core/page/FrameView.h"
-#include "core/page/UseCounter.h"
+#include "core/frame/FrameView.h"
+#include "core/frame/UseCounter.h"
#include "core/rendering/RenderLayer.h"
#include "core/rendering/RenderView.h"
@@ -59,11 +59,11 @@ namespace WebCore {
using namespace HTMLNames;
-RenderMarquee::RenderMarquee(Element* element)
+RenderMarquee::RenderMarquee(HTMLMarqueeElement* element)
: RenderBlockFlow(element)
, m_currentLoop(0)
, m_totalLoops(0)
- , m_timer(this, &RenderMarquee::timerFired)
+ , m_timer(element, &HTMLMarqueeElement::timerFired)
, m_start(0)
, m_end(0)
, m_speed(0)
@@ -72,7 +72,7 @@ RenderMarquee::RenderMarquee(Element* element)
, m_stopped(false)
, m_direction(MAUTO)
{
- UseCounter::count(&document(), UseCounter::HTMLMarqueeElement);
+ UseCounter::count(document(), UseCounter::HTMLMarqueeElement);
}
RenderMarquee::~RenderMarquee()
@@ -162,27 +162,17 @@ void RenderMarquee::start()
if (m_timer.isActive() || style()->marqueeIncrement().isZero())
return;
- // We may end up propagating a scroll event. It is important that we suspend events until
- // the end of the function since they could delete the layer, including the marquee.
- FrameView* frameView = document().view();
- if (frameView)
- frameView->pauseScheduledEvents();
-
if (!m_suspended && !m_stopped) {
if (isHorizontal())
- layer()->scrollToOffset(IntSize(m_start, 0));
+ layer()->scrollableArea()->scrollToOffset(IntSize(m_start, 0));
else
- layer()->scrollToOffset(IntSize(0, m_start));
- }
- else {
+ layer()->scrollableArea()->scrollToOffset(IntSize(0, m_start));
+ } else {
m_suspended = false;
m_stopped = false;
}
m_timer.startRepeating(speed() * 0.001);
-
- if (frameView)
- frameView->resumeScheduledEvents();
}
void RenderMarquee::suspend()
@@ -219,8 +209,6 @@ const char* RenderMarquee::renderName() const
return "RenderMarquee (generated)";
if (isRelPositioned())
return "RenderMarquee (relative positioned)";
- if (isRunIn())
- return "RenderMarquee (run-in)";
return "RenderMarquee";
}
@@ -278,7 +266,7 @@ void RenderMarquee::layoutBlock(bool relayoutChildren, LayoutUnit pageLogicalHei
updateMarqueePosition();
}
-void RenderMarquee::timerFired(Timer<RenderMarquee>*)
+void RenderMarquee::timerFired()
{
// FIXME: Why do we need to check the view and not just the RenderMarquee itself?
if (view()->needsLayout())
@@ -287,9 +275,9 @@ void RenderMarquee::timerFired(Timer<RenderMarquee>*)
if (m_reset) {
m_reset = false;
if (isHorizontal())
- layer()->scrollToXOffset(m_start);
+ layer()->scrollableArea()->scrollToXOffset(m_start);
else
- layer()->scrollToYOffset(m_start);
+ layer()->scrollableArea()->scrollToYOffset(m_start);
return;
}
@@ -312,7 +300,7 @@ void RenderMarquee::timerFired(Timer<RenderMarquee>*)
bool positive = range > 0;
int clientSize = (isHorizontal() ? clientWidth() : clientHeight());
int increment = abs(intValueForLength(style()->marqueeIncrement(), clientSize));
- int currentPos = (isHorizontal() ? layer()->scrollXOffset() : layer()->scrollYOffset());
+ int currentPos = (isHorizontal() ? layer()->scrollableArea()->scrollXOffset() : layer()->scrollableArea()->scrollYOffset());
newPos = currentPos + (addIncrement ? increment : -increment);
if (positive)
newPos = min(newPos, endPoint);
@@ -329,9 +317,9 @@ void RenderMarquee::timerFired(Timer<RenderMarquee>*)
}
if (isHorizontal())
- layer()->scrollToXOffset(newPos);
+ layer()->scrollableArea()->scrollToXOffset(newPos);
else
- layer()->scrollToYOffset(newPos);
+ layer()->scrollableArea()->scrollToYOffset(newPos);
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderMarquee.h b/chromium/third_party/WebKit/Source/core/rendering/RenderMarquee.h
index 8cf3a791bda..f69801dd44f 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderMarquee.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderMarquee.h
@@ -44,10 +44,11 @@
#ifndef RenderMarquee_h
#define RenderMarquee_h
-#include "core/platform/Length.h"
-#include "core/platform/Timer.h"
+#include "core/html/HTMLMarqueeElement.h"
#include "core/rendering/RenderBlockFlow.h"
#include "core/rendering/style/RenderStyleConstants.h"
+#include "platform/Length.h"
+#include "platform/Timer.h"
namespace WebCore {
@@ -56,7 +57,7 @@ class RenderLayer;
// This class handles the auto-scrolling for <marquee>
class RenderMarquee FINAL : public RenderBlockFlow {
public:
- explicit RenderMarquee(Element*);
+ explicit RenderMarquee(HTMLMarqueeElement*);
virtual ~RenderMarquee();
int speed() const { return m_speed; }
@@ -79,6 +80,8 @@ public:
// However <marquee> tests are very timing dependent so we need to keep the existing timing.
void updateMarqueePosition();
+ void timerFired();
+
private:
virtual const char* renderName() const OVERRIDE FINAL;
@@ -90,11 +93,9 @@ private:
virtual bool supportsPartialLayout() const OVERRIDE { return false; }
- void timerFired(Timer<RenderMarquee>*);
-
int m_currentLoop;
int m_totalLoops;
- Timer<RenderMarquee> m_timer;
+ Timer<HTMLMarqueeElement> m_timer;
int m_start;
int m_end;
int m_speed;
@@ -105,20 +106,7 @@ private:
EMarqueeDirection m_direction : 4;
};
-inline RenderMarquee* toRenderMarquee(RenderObject* renderer)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!renderer || renderer->isMarquee());
- return static_cast<RenderMarquee*>(renderer);
-}
-
-inline const RenderMarquee* toRenderMarquee(const RenderObject* renderer)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!renderer || renderer->isMarquee());
- return static_cast<const RenderMarquee*>(renderer);
-}
-
-// Catch unneeded cast.
-void toRenderMarquee(const RenderMarquee*);
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderMarquee, isMarquee());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderMedia.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderMedia.cpp
index f76855e5a72..aacc6ae38a9 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderMedia.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderMedia.cpp
@@ -28,6 +28,7 @@
#include "core/rendering/RenderMedia.h"
#include "core/html/HTMLMediaElement.h"
+#include "core/rendering/LayoutRectRecorder.h"
#include "core/rendering/RenderFlowThread.h"
#include "core/rendering/RenderView.h"
@@ -39,13 +40,6 @@ RenderMedia::RenderMedia(HTMLMediaElement* video)
setImageResource(RenderImageResource::create());
}
-RenderMedia::RenderMedia(HTMLMediaElement* video, const IntSize& intrinsicSize)
- : RenderImage(video)
-{
- setImageResource(RenderImageResource::create());
- setIntrinsicSize(intrinsicSize);
-}
-
RenderMedia::~RenderMedia()
{
}
@@ -57,6 +51,7 @@ HTMLMediaElement* RenderMedia::mediaElement() const
void RenderMedia::layout()
{
+ LayoutRectRecorder recorder(*this);
LayoutSize oldSize = contentBoxRect().size();
RenderImage::layout();
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderMedia.h b/chromium/third_party/WebKit/Source/core/rendering/RenderMedia.h
index 5ad603de52c..ada064b59c0 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderMedia.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderMedia.h
@@ -35,7 +35,6 @@ class HTMLMediaElement;
class RenderMedia : public RenderImage {
public:
explicit RenderMedia(HTMLMediaElement*);
- RenderMedia(HTMLMediaElement*, const IntSize& intrinsicSize);
virtual ~RenderMedia();
RenderObject* firstChild() const { ASSERT(children() == virtualChildren()); return children()->firstChild(); }
@@ -63,19 +62,10 @@ private:
virtual bool isImage() const OVERRIDE FINAL { return false; }
virtual void paintReplaced(PaintInfo&, const LayoutPoint&);
- virtual bool requiresForcedStyleRecalcPropagation() const OVERRIDE FINAL { return true; }
-
RenderObjectChildList m_children;
};
-inline RenderMedia* toRenderMedia(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isMedia());
- return static_cast<RenderMedia*>(object);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toRenderMedia(const RenderMedia*);
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderMedia, isMedia());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderMediaControlElements.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderMediaControlElements.cpp
index 4e14e906b0a..da2babc48d5 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderMediaControlElements.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderMediaControlElements.cpp
@@ -29,6 +29,7 @@
#include "core/rendering/RenderMediaControlElements.h"
+#include "core/rendering/LayoutRectRecorder.h"
#include "core/rendering/RenderView.h"
namespace WebCore {
@@ -40,6 +41,7 @@ RenderTextTrackContainerElement::RenderTextTrackContainerElement(Element* elemen
void RenderTextTrackContainerElement::layout()
{
+ LayoutRectRecorder recorder(*this);
RenderBlock::layout();
if (style()->display() == NONE)
return;
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderMediaControls.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderMediaControls.cpp
index ae146c0338a..13d1620367a 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderMediaControls.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderMediaControls.cpp
@@ -1,5 +1,7 @@
/*
- * Copyright (C) 2009 Apple Inc. All Rights Reserved.
+ * Copyright (C) 2009 Apple Inc.
+ * Copyright (C) 2009 Google Inc.
+ * All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -24,12 +26,427 @@
*/
#include "config.h"
-
#include "core/rendering/RenderMediaControls.h"
-// FIXME: Unify more of the code for Mac and Win.
-
-using namespace std;
+#include "bindings/v8/ExceptionStatePlaceholder.h"
+#include "core/html/HTMLMediaElement.h"
+#include "core/html/TimeRanges.h"
+#include "core/rendering/PaintInfo.h"
+#include "platform/graphics/Gradient.h"
+#include "platform/graphics/GraphicsContext.h"
namespace WebCore {
+
+typedef WTF::HashMap<const char*, Image*> MediaControlImageMap;
+static MediaControlImageMap* gMediaControlImageMap = 0;
+
+static Image* platformResource(const char* name)
+{
+ if (!gMediaControlImageMap)
+ gMediaControlImageMap = new MediaControlImageMap();
+ if (Image* image = gMediaControlImageMap->get(name))
+ return image;
+ if (Image* image = Image::loadPlatformResource(name).leakRef()) {
+ gMediaControlImageMap->set(name, image);
+ return image;
+ }
+ ASSERT_NOT_REACHED();
+ return 0;
+}
+
+static bool hasSource(const HTMLMediaElement* mediaElement)
+{
+ return mediaElement->networkState() != HTMLMediaElement::NETWORK_EMPTY
+ && mediaElement->networkState() != HTMLMediaElement::NETWORK_NO_SOURCE;
+}
+
+static bool paintMediaButton(GraphicsContext* context, const IntRect& rect, Image* image)
+{
+ context->drawImage(image, rect);
+ return true;
+}
+
+static bool paintMediaMuteButton(RenderObject* object, const PaintInfo& paintInfo, const IntRect& rect)
+{
+ HTMLMediaElement* mediaElement = toParentMediaElement(object);
+ if (!mediaElement)
+ return false;
+
+ static Image* soundLevel3 = platformResource("mediaplayerSoundLevel3");
+ static Image* soundLevel2 = platformResource("mediaplayerSoundLevel2");
+ static Image* soundLevel1 = platformResource("mediaplayerSoundLevel1");
+ static Image* soundLevel0 = platformResource("mediaplayerSoundLevel0");
+ static Image* soundDisabled = platformResource("mediaplayerSoundDisabled");
+
+ if (!hasSource(mediaElement) || !mediaElement->hasAudio())
+ return paintMediaButton(paintInfo.context, rect, soundDisabled);
+
+ if (mediaElement->muted() || mediaElement->volume() <= 0)
+ return paintMediaButton(paintInfo.context, rect, soundLevel0);
+
+ if (mediaElement->volume() <= 0.33)
+ return paintMediaButton(paintInfo.context, rect, soundLevel1);
+
+ if (mediaElement->volume() <= 0.66)
+ return paintMediaButton(paintInfo.context, rect, soundLevel2);
+
+ return paintMediaButton(paintInfo.context, rect, soundLevel3);
+}
+
+static bool paintMediaPlayButton(RenderObject* object, const PaintInfo& paintInfo, const IntRect& rect)
+{
+ HTMLMediaElement* mediaElement = toParentMediaElement(object);
+ if (!mediaElement)
+ return false;
+
+ static Image* mediaPlay = platformResource("mediaplayerPlay");
+ static Image* mediaPause = platformResource("mediaplayerPause");
+ static Image* mediaPlayDisabled = platformResource("mediaplayerPlayDisabled");
+
+ if (!hasSource(mediaElement))
+ return paintMediaButton(paintInfo.context, rect, mediaPlayDisabled);
+
+ return paintMediaButton(paintInfo.context, rect, mediaElement->canPlay() ? mediaPlay : mediaPause);
+}
+
+static bool paintMediaOverlayPlayButton(RenderObject* object, const PaintInfo& paintInfo, const IntRect& rect)
+{
+ HTMLMediaElement* mediaElement = toParentMediaElement(object);
+ if (!mediaElement)
+ return false;
+
+ if (!hasSource(mediaElement) || !mediaElement->canPlay())
+ return false;
+
+ static Image* mediaOverlayPlay = platformResource("mediaplayerOverlayPlay");
+ return paintMediaButton(paintInfo.context, rect, mediaOverlayPlay);
}
+
+static Image* getMediaSliderThumb()
+{
+ static Image* mediaSliderThumb = platformResource("mediaplayerSliderThumb");
+ return mediaSliderThumb;
+}
+
+static void paintRoundedSliderBackground(const IntRect& rect, const RenderStyle* style, GraphicsContext* context)
+{
+ int borderRadius = rect.height() / 2;
+ IntSize radii(borderRadius, borderRadius);
+ Color sliderBackgroundColor = Color(11, 11, 11);
+ context->save();
+ context->fillRoundedRect(rect, radii, radii, radii, radii, sliderBackgroundColor);
+ context->restore();
+}
+
+static void paintSliderRangeHighlight(const IntRect& rect, const RenderStyle* style, GraphicsContext* context, int startPosition, int endPosition, Color startColor, Color endColor)
+{
+ // Calculate border radius; need to avoid being smaller than half the slider height
+ // because of https://bugs.webkit.org/show_bug.cgi?id=30143.
+ int borderRadius = rect.height() / 2;
+ IntSize radii(borderRadius, borderRadius);
+
+ // Calculate highlight rectangle and edge dimensions.
+ int startOffset = startPosition;
+ int endOffset = rect.width() - endPosition;
+ int rangeWidth = endPosition - startPosition;
+
+ if (rangeWidth <= 0)
+ return;
+
+ // Make sure the range width is bigger than border radius at the edges to retain rounded corners.
+ if (startOffset < borderRadius && rangeWidth < borderRadius)
+ rangeWidth = borderRadius;
+ if (endOffset < borderRadius && rangeWidth < borderRadius) {
+ startPosition -= borderRadius - rangeWidth;
+ rangeWidth = borderRadius;
+ }
+
+ // Set rectangle to highlight range.
+ IntRect highlightRect = rect;
+ highlightRect.move(startOffset, 0);
+ highlightRect.setWidth(rangeWidth);
+
+ // Don't bother drawing an empty area.
+ if (highlightRect.isEmpty())
+ return;
+
+ // Calculate white-grey gradient.
+ IntPoint sliderTopLeft = highlightRect.location();
+ IntPoint sliderBottomLeft = sliderTopLeft;
+ sliderBottomLeft.move(0, highlightRect.height());
+ RefPtr<Gradient> gradient = Gradient::create(sliderTopLeft, sliderBottomLeft);
+ gradient->addColorStop(0.0, startColor);
+ gradient->addColorStop(1.0, endColor);
+
+ // Fill highlight rectangle with gradient, potentially rounded if on left or right edge.
+ context->save();
+ context->setFillGradient(gradient);
+
+ if (startOffset < borderRadius && endOffset < borderRadius)
+ context->fillRoundedRect(highlightRect, radii, radii, radii, radii, startColor);
+ else if (startOffset < borderRadius)
+ context->fillRoundedRect(highlightRect, radii, IntSize(0, 0), radii, IntSize(0, 0), startColor);
+ else if (endOffset < borderRadius)
+ context->fillRoundedRect(highlightRect, IntSize(0, 0), radii, IntSize(0, 0), radii, startColor);
+ else
+ context->fillRect(highlightRect);
+
+ context->restore();
+}
+
+const int mediaSliderThumbWidth = 32;
+
+static bool paintMediaSlider(RenderObject* object, const PaintInfo& paintInfo, const IntRect& rect)
+{
+ HTMLMediaElement* mediaElement = toParentMediaElement(object);
+ if (!mediaElement)
+ return false;
+
+ RenderStyle* style = object->style();
+ GraphicsContext* context = paintInfo.context;
+
+ paintRoundedSliderBackground(rect, style, context);
+
+ // Draw the buffered range. Since the element may have multiple buffered ranges and it'd be
+ // distracting/'busy' to show all of them, show only the buffered range containing the current play head.
+ RefPtr<TimeRanges> bufferedTimeRanges = mediaElement->buffered();
+ float duration = mediaElement->duration();
+ float currentTime = mediaElement->currentTime();
+ if (std::isnan(duration) || std::isinf(duration) || !duration || std::isnan(currentTime))
+ return true;
+
+ for (unsigned i = 0; i < bufferedTimeRanges->length(); ++i) {
+ float start = bufferedTimeRanges->start(i, ASSERT_NO_EXCEPTION);
+ float end = bufferedTimeRanges->end(i, ASSERT_NO_EXCEPTION);
+ if (std::isnan(start) || std::isnan(end) || start > currentTime || end < currentTime)
+ continue;
+ int startPosition = int(start * rect.width() / duration);
+ int currentPosition = int(currentTime * rect.width() / duration);
+ int endPosition = int(end * rect.width() / duration);
+
+ // Add half the thumb width proportionally adjusted to the current painting position.
+ int thumbCenter = mediaSliderThumbWidth / 2;
+ int addWidth = thumbCenter * (1.0 - 2.0 * currentPosition / rect.width());
+ currentPosition += addWidth;
+
+ // Draw white-ish highlight before current time.
+ Color startColor = Color(195, 195, 195);
+ Color endColor = Color(217, 217, 217);
+ if (currentPosition > startPosition)
+ paintSliderRangeHighlight(rect, style, context, startPosition, currentPosition, startColor, endColor);
+
+ // Draw grey-ish highlight after current time.
+ startColor = Color(60, 60, 60);
+ endColor = Color(76, 76, 76);
+
+ if (endPosition > currentPosition)
+ paintSliderRangeHighlight(rect, style, context, currentPosition, endPosition, startColor, endColor);
+
+ return true;
+ }
+
+ return true;
+}
+
+static bool paintMediaSliderThumb(RenderObject* object, const PaintInfo& paintInfo, const IntRect& rect)
+{
+ ASSERT(object->node());
+ HTMLMediaElement* mediaElement = toParentMediaElement(object->node()->shadowHost());
+ if (!mediaElement)
+ return false;
+
+ if (!hasSource(mediaElement))
+ return true;
+
+ Image* mediaSliderThumb = getMediaSliderThumb();
+ return paintMediaButton(paintInfo.context, rect, mediaSliderThumb);
+}
+
+const int mediaVolumeSliderThumbWidth = 24;
+
+static bool paintMediaVolumeSlider(RenderObject* object, const PaintInfo& paintInfo, const IntRect& rect)
+{
+ HTMLMediaElement* mediaElement = toParentMediaElement(object);
+ if (!mediaElement)
+ return false;
+
+ GraphicsContext* context = paintInfo.context;
+ RenderStyle* style = object->style();
+
+ paintRoundedSliderBackground(rect, style, context);
+
+ // Calculate volume position for white background rectangle.
+ float volume = mediaElement->volume();
+ if (std::isnan(volume) || volume < 0)
+ return true;
+ if (volume > 1)
+ volume = 1;
+ if (!hasSource(mediaElement) || !mediaElement->hasAudio() || mediaElement->muted())
+ volume = 0;
+
+ // Calculate the position relative to the center of the thumb.
+ float fillWidth = 0;
+ if (volume > 0) {
+ float thumbCenter = mediaVolumeSliderThumbWidth / 2;
+ float zoomLevel = style->effectiveZoom();
+ float positionWidth = volume * (rect.width() - (zoomLevel * thumbCenter));
+ fillWidth = positionWidth + (zoomLevel * thumbCenter / 2);
+ }
+
+ Color startColor = Color(195, 195, 195);
+ Color endColor = Color(217, 217, 217);
+
+ paintSliderRangeHighlight(rect, style, context, 0.0, fillWidth, startColor, endColor);
+
+ return true;
+}
+
+static bool paintMediaVolumeSliderThumb(RenderObject* object, const PaintInfo& paintInfo, const IntRect& rect)
+{
+ ASSERT(object->node());
+ HTMLMediaElement* mediaElement = toParentMediaElement(object->node()->shadowHost());
+ if (!mediaElement)
+ return false;
+
+ if (!hasSource(mediaElement) || !mediaElement->hasAudio())
+ return true;
+
+ static Image* mediaVolumeSliderThumb = platformResource("mediaplayerVolumeSliderThumb");
+ return paintMediaButton(paintInfo.context, rect, mediaVolumeSliderThumb);
+}
+
+static bool paintMediaFullscreenButton(RenderObject* object, const PaintInfo& paintInfo, const IntRect& rect)
+{
+ HTMLMediaElement* mediaElement = toParentMediaElement(object);
+ if (!mediaElement)
+ return false;
+
+ static Image* mediaFullscreenButton = platformResource("mediaplayerFullscreen");
+ return paintMediaButton(paintInfo.context, rect, mediaFullscreenButton);
+}
+
+static bool paintMediaToggleClosedCaptionsButton(RenderObject* object, const PaintInfo& paintInfo, const IntRect& rect)
+{
+ HTMLMediaElement* mediaElement = toParentMediaElement(object);
+ if (!mediaElement)
+ return false;
+
+ static Image* mediaClosedCaptionButton = platformResource("mediaplayerClosedCaption");
+ static Image* mediaClosedCaptionButtonDisabled = platformResource("mediaplayerClosedCaptionDisabled");
+
+ if (mediaElement->closedCaptionsVisible())
+ return paintMediaButton(paintInfo.context, rect, mediaClosedCaptionButton);
+
+ return paintMediaButton(paintInfo.context, rect, mediaClosedCaptionButtonDisabled);
+}
+
+
+bool RenderMediaControls::paintMediaControlsPart(MediaControlElementType part, RenderObject* object, const PaintInfo& paintInfo, const IntRect& rect)
+{
+ switch (part) {
+ case MediaMuteButton:
+ case MediaUnMuteButton:
+ return paintMediaMuteButton(object, paintInfo, rect);
+ case MediaPauseButton:
+ case MediaPlayButton:
+ return paintMediaPlayButton(object, paintInfo, rect);
+ case MediaShowClosedCaptionsButton:
+ return paintMediaToggleClosedCaptionsButton(object, paintInfo, rect);
+ case MediaSlider:
+ return paintMediaSlider(object, paintInfo, rect);
+ case MediaSliderThumb:
+ return paintMediaSliderThumb(object, paintInfo, rect);
+ case MediaVolumeSlider:
+ return paintMediaVolumeSlider(object, paintInfo, rect);
+ case MediaVolumeSliderThumb:
+ return paintMediaVolumeSliderThumb(object, paintInfo, rect);
+ case MediaEnterFullscreenButton:
+ case MediaExitFullscreenButton:
+ return paintMediaFullscreenButton(object, paintInfo, rect);
+ case MediaOverlayPlayButton:
+ return paintMediaOverlayPlayButton(object, paintInfo, rect);
+ case MediaVolumeSliderMuteButton:
+ case MediaSeekBackButton:
+ case MediaSeekForwardButton:
+ case MediaVolumeSliderContainer:
+ case MediaTimelineContainer:
+ case MediaCurrentTimeDisplay:
+ case MediaTimeRemainingDisplay:
+ case MediaControlsPanel:
+ case MediaRewindButton:
+ case MediaReturnToRealtimeButton:
+ case MediaStatusDisplay:
+ case MediaHideClosedCaptionsButton:
+ case MediaTextTrackDisplayContainer:
+ case MediaTextTrackDisplay:
+ case MediaFullScreenVolumeSlider:
+ case MediaFullScreenVolumeSliderThumb:
+ ASSERT_NOT_REACHED();
+ break;
+ }
+ return false;
+}
+
+const int mediaSliderThumbHeight = 24;
+const int mediaVolumeSliderThumbHeight = 24;
+
+void RenderMediaControls::adjustMediaSliderThumbSize(RenderStyle* style)
+{
+ static Image* mediaSliderThumb = platformResource("mediaplayerSliderThumb");
+ static Image* mediaVolumeSliderThumb = platformResource("mediaplayerVolumeSliderThumb");
+ int width = 0;
+ int height = 0;
+
+ Image* thumbImage = 0;
+ if (style->appearance() == MediaSliderThumbPart) {
+ thumbImage = mediaSliderThumb;
+ width = mediaSliderThumbWidth;
+ height = mediaSliderThumbHeight;
+ } else if (style->appearance() == MediaVolumeSliderThumbPart) {
+ thumbImage = mediaVolumeSliderThumb;
+ width = mediaVolumeSliderThumbWidth;
+ height = mediaVolumeSliderThumbHeight;
+ }
+
+ float zoomLevel = style->effectiveZoom();
+ if (thumbImage) {
+ style->setWidth(Length(static_cast<int>(width * zoomLevel), Fixed));
+ style->setHeight(Length(static_cast<int>(height * zoomLevel), Fixed));
+ }
+}
+
+static String formatChromiumMediaControlsTime(float time, float duration)
+{
+ if (!std::isfinite(time))
+ time = 0;
+ if (!std::isfinite(duration))
+ duration = 0;
+ int seconds = static_cast<int>(fabsf(time));
+ int hours = seconds / (60 * 60);
+ int minutes = (seconds / 60) % 60;
+ seconds %= 60;
+
+ // duration defines the format of how the time is rendered
+ int durationSecs = static_cast<int>(fabsf(duration));
+ int durationHours = durationSecs / (60 * 60);
+ int durationMins = (durationSecs / 60) % 60;
+
+ if (durationHours || hours)
+ return String::format("%s%01d:%02d:%02d", (time < 0 ? "-" : ""), hours, minutes, seconds);
+ if (durationMins > 9)
+ return String::format("%s%02d:%02d", (time < 0 ? "-" : ""), minutes, seconds);
+
+ return String::format("%s%01d:%02d", (time < 0 ? "-" : ""), minutes, seconds);
+}
+
+String RenderMediaControls::formatMediaControlsTime(float time)
+{
+ return formatChromiumMediaControlsTime(time, time);
+}
+
+String RenderMediaControls::formatMediaControlsCurrentTime(float currentTime, float duration)
+{
+ return formatChromiumMediaControlsTime(currentTime, duration);
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderMediaControls.h b/chromium/third_party/WebKit/Source/core/rendering/RenderMediaControls.h
index aca27ba5a1c..8f40830228b 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderMediaControls.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderMediaControls.h
@@ -1,5 +1,7 @@
/*
- * Copyright (C) 2009 Apple Inc. All Rights Reserved.
+ * Copyright (C) 2009 Apple Inc.
+ * Copyright (C) 2009 Google Inc.
+ * All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
@@ -34,13 +36,14 @@ struct PaintInfo;
class HTMLMediaElement;
class IntRect;
-class IntSize;
-class RenderBox;
class RenderObject;
-class RenderStyle;
class RenderMediaControls {
public:
+ static bool paintMediaControlsPart(MediaControlElementType, RenderObject*, const PaintInfo&, const IntRect&);
+ static void adjustMediaSliderThumbSize(RenderStyle*);
+ static String formatMediaControlsTime(float time);
+ static String formatMediaControlsCurrentTime(float currentTime, float duration);
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderMediaControlsChromium.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderMediaControlsChromium.cpp
deleted file mode 100644
index 26fc395f103..00000000000
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderMediaControlsChromium.cpp
+++ /dev/null
@@ -1,452 +0,0 @@
-/*
- * Copyright (C) 2009 Apple Inc.
- * Copyright (C) 2009 Google Inc.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/rendering/RenderMediaControlsChromium.h"
-
-#include "bindings/v8/ExceptionStatePlaceholder.h"
-#include "core/html/HTMLMediaElement.h"
-#include "core/html/TimeRanges.h"
-#include "core/platform/graphics/Gradient.h"
-#include "core/platform/graphics/GraphicsContext.h"
-#include "core/rendering/PaintInfo.h"
-
-namespace WebCore {
-
-typedef WTF::HashMap<const char*, Image*> MediaControlImageMap;
-static MediaControlImageMap* gMediaControlImageMap = 0;
-
-static Image* platformResource(const char* name)
-{
- if (!gMediaControlImageMap)
- gMediaControlImageMap = new MediaControlImageMap();
- if (Image* image = gMediaControlImageMap->get(name))
- return image;
- if (Image* image = Image::loadPlatformResource(name).leakRef()) {
- gMediaControlImageMap->set(name, image);
- return image;
- }
- ASSERT_NOT_REACHED();
- return 0;
-}
-
-static bool hasSource(const HTMLMediaElement* mediaElement)
-{
- return mediaElement->networkState() != HTMLMediaElement::NETWORK_EMPTY
- && mediaElement->networkState() != HTMLMediaElement::NETWORK_NO_SOURCE;
-}
-
-static bool paintMediaButton(GraphicsContext* context, const IntRect& rect, Image* image)
-{
- context->drawImage(image, rect);
- return true;
-}
-
-static bool paintMediaMuteButton(RenderObject* object, const PaintInfo& paintInfo, const IntRect& rect)
-{
- HTMLMediaElement* mediaElement = toParentMediaElement(object);
- if (!mediaElement)
- return false;
-
- static Image* soundLevel3 = platformResource("mediaplayerSoundLevel3");
- static Image* soundLevel2 = platformResource("mediaplayerSoundLevel2");
- static Image* soundLevel1 = platformResource("mediaplayerSoundLevel1");
- static Image* soundLevel0 = platformResource("mediaplayerSoundLevel0");
- static Image* soundDisabled = platformResource("mediaplayerSoundDisabled");
-
- if (!hasSource(mediaElement) || !mediaElement->hasAudio())
- return paintMediaButton(paintInfo.context, rect, soundDisabled);
-
- if (mediaElement->muted() || mediaElement->volume() <= 0)
- return paintMediaButton(paintInfo.context, rect, soundLevel0);
-
- if (mediaElement->volume() <= 0.33)
- return paintMediaButton(paintInfo.context, rect, soundLevel1);
-
- if (mediaElement->volume() <= 0.66)
- return paintMediaButton(paintInfo.context, rect, soundLevel2);
-
- return paintMediaButton(paintInfo.context, rect, soundLevel3);
-}
-
-static bool paintMediaPlayButton(RenderObject* object, const PaintInfo& paintInfo, const IntRect& rect)
-{
- HTMLMediaElement* mediaElement = toParentMediaElement(object);
- if (!mediaElement)
- return false;
-
- static Image* mediaPlay = platformResource("mediaplayerPlay");
- static Image* mediaPause = platformResource("mediaplayerPause");
- static Image* mediaPlayDisabled = platformResource("mediaplayerPlayDisabled");
-
- if (!hasSource(mediaElement))
- return paintMediaButton(paintInfo.context, rect, mediaPlayDisabled);
-
- return paintMediaButton(paintInfo.context, rect, mediaElement->canPlay() ? mediaPlay : mediaPause);
-}
-
-static bool paintMediaOverlayPlayButton(RenderObject* object, const PaintInfo& paintInfo, const IntRect& rect)
-{
- HTMLMediaElement* mediaElement = toParentMediaElement(object);
- if (!mediaElement)
- return false;
-
- if (!hasSource(mediaElement) || !mediaElement->canPlay())
- return false;
-
- static Image* mediaOverlayPlay = platformResource("mediaplayerOverlayPlay");
- return paintMediaButton(paintInfo.context, rect, mediaOverlayPlay);
-}
-
-static Image* getMediaSliderThumb()
-{
- static Image* mediaSliderThumb = platformResource("mediaplayerSliderThumb");
- return mediaSliderThumb;
-}
-
-static void paintRoundedSliderBackground(const IntRect& rect, const RenderStyle* style, GraphicsContext* context)
-{
- int borderRadius = rect.height() / 2;
- IntSize radii(borderRadius, borderRadius);
- Color sliderBackgroundColor = Color(11, 11, 11);
- context->save();
- context->fillRoundedRect(rect, radii, radii, radii, radii, sliderBackgroundColor);
- context->restore();
-}
-
-static void paintSliderRangeHighlight(const IntRect& rect, const RenderStyle* style, GraphicsContext* context, int startPosition, int endPosition, Color startColor, Color endColor)
-{
- // Calculate border radius; need to avoid being smaller than half the slider height
- // because of https://bugs.webkit.org/show_bug.cgi?id=30143.
- int borderRadius = rect.height() / 2;
- IntSize radii(borderRadius, borderRadius);
-
- // Calculate highlight rectangle and edge dimensions.
- int startOffset = startPosition;
- int endOffset = rect.width() - endPosition;
- int rangeWidth = endPosition - startPosition;
-
- if (rangeWidth <= 0)
- return;
-
- // Make sure the range width is bigger than border radius at the edges to retain rounded corners.
- if (startOffset < borderRadius && rangeWidth < borderRadius)
- rangeWidth = borderRadius;
- if (endOffset < borderRadius && rangeWidth < borderRadius) {
- startPosition -= borderRadius - rangeWidth;
- rangeWidth = borderRadius;
- }
-
- // Set rectangle to highlight range.
- IntRect highlightRect = rect;
- highlightRect.move(startOffset, 0);
- highlightRect.setWidth(rangeWidth);
-
- // Don't bother drawing an empty area.
- if (highlightRect.isEmpty())
- return;
-
- // Calculate white-grey gradient.
- IntPoint sliderTopLeft = highlightRect.location();
- IntPoint sliderBottomLeft = sliderTopLeft;
- sliderBottomLeft.move(0, highlightRect.height());
- RefPtr<Gradient> gradient = Gradient::create(sliderTopLeft, sliderBottomLeft);
- gradient->addColorStop(0.0, startColor);
- gradient->addColorStop(1.0, endColor);
-
- // Fill highlight rectangle with gradient, potentially rounded if on left or right edge.
- context->save();
- context->setFillGradient(gradient);
-
- if (startOffset < borderRadius && endOffset < borderRadius)
- context->fillRoundedRect(highlightRect, radii, radii, radii, radii, startColor);
- else if (startOffset < borderRadius)
- context->fillRoundedRect(highlightRect, radii, IntSize(0, 0), radii, IntSize(0, 0), startColor);
- else if (endOffset < borderRadius)
- context->fillRoundedRect(highlightRect, IntSize(0, 0), radii, IntSize(0, 0), radii, startColor);
- else
- context->fillRect(highlightRect);
-
- context->restore();
-}
-
-const int mediaSliderThumbWidth = 32;
-
-static bool paintMediaSlider(RenderObject* object, const PaintInfo& paintInfo, const IntRect& rect)
-{
- HTMLMediaElement* mediaElement = toParentMediaElement(object);
- if (!mediaElement)
- return false;
-
- RenderStyle* style = object->style();
- GraphicsContext* context = paintInfo.context;
-
- paintRoundedSliderBackground(rect, style, context);
-
- // Draw the buffered range. Since the element may have multiple buffered ranges and it'd be
- // distracting/'busy' to show all of them, show only the buffered range containing the current play head.
- RefPtr<TimeRanges> bufferedTimeRanges = mediaElement->buffered();
- float duration = mediaElement->duration();
- float currentTime = mediaElement->currentTime();
- if (std::isnan(duration) || std::isinf(duration) || !duration || std::isnan(currentTime))
- return true;
-
- for (unsigned i = 0; i < bufferedTimeRanges->length(); ++i) {
- float start = bufferedTimeRanges->start(i, ASSERT_NO_EXCEPTION);
- float end = bufferedTimeRanges->end(i, ASSERT_NO_EXCEPTION);
- if (std::isnan(start) || std::isnan(end) || start > currentTime || end < currentTime)
- continue;
- int startPosition = int(start * rect.width() / duration);
- int currentPosition = int(currentTime * rect.width() / duration);
- int endPosition = int(end * rect.width() / duration);
-
- // Add half the thumb width proportionally adjusted to the current painting position.
- int thumbCenter = mediaSliderThumbWidth / 2;
- int addWidth = thumbCenter * (1.0 - 2.0 * currentPosition / rect.width());
- currentPosition += addWidth;
-
- // Draw white-ish highlight before current time.
- Color startColor = Color(195, 195, 195);
- Color endColor = Color(217, 217, 217);
- if (currentPosition > startPosition)
- paintSliderRangeHighlight(rect, style, context, startPosition, currentPosition, startColor, endColor);
-
- // Draw grey-ish highlight after current time.
- startColor = Color(60, 60, 60);
- endColor = Color(76, 76, 76);
-
- if (endPosition > currentPosition)
- paintSliderRangeHighlight(rect, style, context, currentPosition, endPosition, startColor, endColor);
-
- return true;
- }
-
- return true;
-}
-
-static bool paintMediaSliderThumb(RenderObject* object, const PaintInfo& paintInfo, const IntRect& rect)
-{
- ASSERT(object->node());
- HTMLMediaElement* mediaElement = toParentMediaElement(object->node()->shadowHost());
- if (!mediaElement)
- return false;
-
- if (!hasSource(mediaElement))
- return true;
-
- Image* mediaSliderThumb = getMediaSliderThumb();
- return paintMediaButton(paintInfo.context, rect, mediaSliderThumb);
-}
-
-const int mediaVolumeSliderThumbWidth = 24;
-
-static bool paintMediaVolumeSlider(RenderObject* object, const PaintInfo& paintInfo, const IntRect& rect)
-{
- HTMLMediaElement* mediaElement = toParentMediaElement(object);
- if (!mediaElement)
- return false;
-
- GraphicsContext* context = paintInfo.context;
- RenderStyle* style = object->style();
-
- paintRoundedSliderBackground(rect, style, context);
-
- // Calculate volume position for white background rectangle.
- float volume = mediaElement->volume();
- if (std::isnan(volume) || volume < 0)
- return true;
- if (volume > 1)
- volume = 1;
- if (!hasSource(mediaElement) || !mediaElement->hasAudio() || mediaElement->muted())
- volume = 0;
-
- // Calculate the position relative to the center of the thumb.
- float fillWidth = 0;
- if (volume > 0) {
- float thumbCenter = mediaVolumeSliderThumbWidth / 2;
- float zoomLevel = style->effectiveZoom();
- float positionWidth = volume * (rect.width() - (zoomLevel * thumbCenter));
- fillWidth = positionWidth + (zoomLevel * thumbCenter / 2);
- }
-
- Color startColor = Color(195, 195, 195);
- Color endColor = Color(217, 217, 217);
-
- paintSliderRangeHighlight(rect, style, context, 0.0, fillWidth, startColor, endColor);
-
- return true;
-}
-
-static bool paintMediaVolumeSliderThumb(RenderObject* object, const PaintInfo& paintInfo, const IntRect& rect)
-{
- ASSERT(object->node());
- HTMLMediaElement* mediaElement = toParentMediaElement(object->node()->shadowHost());
- if (!mediaElement)
- return false;
-
- if (!hasSource(mediaElement) || !mediaElement->hasAudio())
- return true;
-
- static Image* mediaVolumeSliderThumb = platformResource("mediaplayerVolumeSliderThumb");
- return paintMediaButton(paintInfo.context, rect, mediaVolumeSliderThumb);
-}
-
-static bool paintMediaFullscreenButton(RenderObject* object, const PaintInfo& paintInfo, const IntRect& rect)
-{
- HTMLMediaElement* mediaElement = toParentMediaElement(object);
- if (!mediaElement)
- return false;
-
- static Image* mediaFullscreenButton = platformResource("mediaplayerFullscreen");
- return paintMediaButton(paintInfo.context, rect, mediaFullscreenButton);
-}
-
-static bool paintMediaToggleClosedCaptionsButton(RenderObject* object, const PaintInfo& paintInfo, const IntRect& rect)
-{
- HTMLMediaElement* mediaElement = toParentMediaElement(object);
- if (!mediaElement)
- return false;
-
- static Image* mediaClosedCaptionButton = platformResource("mediaplayerClosedCaption");
- static Image* mediaClosedCaptionButtonDisabled = platformResource("mediaplayerClosedCaptionDisabled");
-
- if (mediaElement->webkitClosedCaptionsVisible())
- return paintMediaButton(paintInfo.context, rect, mediaClosedCaptionButton);
-
- return paintMediaButton(paintInfo.context, rect, mediaClosedCaptionButtonDisabled);
-}
-
-
-bool RenderMediaControlsChromium::paintMediaControlsPart(MediaControlElementType part, RenderObject* object, const PaintInfo& paintInfo, const IntRect& rect)
-{
- switch (part) {
- case MediaMuteButton:
- case MediaUnMuteButton:
- return paintMediaMuteButton(object, paintInfo, rect);
- case MediaPauseButton:
- case MediaPlayButton:
- return paintMediaPlayButton(object, paintInfo, rect);
- case MediaShowClosedCaptionsButton:
- return paintMediaToggleClosedCaptionsButton(object, paintInfo, rect);
- case MediaSlider:
- return paintMediaSlider(object, paintInfo, rect);
- case MediaSliderThumb:
- return paintMediaSliderThumb(object, paintInfo, rect);
- case MediaVolumeSlider:
- return paintMediaVolumeSlider(object, paintInfo, rect);
- case MediaVolumeSliderThumb:
- return paintMediaVolumeSliderThumb(object, paintInfo, rect);
- case MediaEnterFullscreenButton:
- case MediaExitFullscreenButton:
- return paintMediaFullscreenButton(object, paintInfo, rect);
- case MediaOverlayPlayButton:
- return paintMediaOverlayPlayButton(object, paintInfo, rect);
- case MediaVolumeSliderMuteButton:
- case MediaSeekBackButton:
- case MediaSeekForwardButton:
- case MediaVolumeSliderContainer:
- case MediaTimelineContainer:
- case MediaCurrentTimeDisplay:
- case MediaTimeRemainingDisplay:
- case MediaControlsPanel:
- case MediaRewindButton:
- case MediaReturnToRealtimeButton:
- case MediaStatusDisplay:
- case MediaHideClosedCaptionsButton:
- case MediaTextTrackDisplayContainer:
- case MediaTextTrackDisplay:
- case MediaFullScreenVolumeSlider:
- case MediaFullScreenVolumeSliderThumb:
- ASSERT_NOT_REACHED();
- break;
- }
- return false;
-}
-
-const int mediaSliderThumbHeight = 24;
-const int mediaVolumeSliderThumbHeight = 24;
-
-void RenderMediaControlsChromium::adjustMediaSliderThumbSize(RenderStyle* style)
-{
- static Image* mediaSliderThumb = platformResource("mediaplayerSliderThumb");
- static Image* mediaVolumeSliderThumb = platformResource("mediaplayerVolumeSliderThumb");
- int width = 0;
- int height = 0;
-
- Image* thumbImage = 0;
- if (style->appearance() == MediaSliderThumbPart) {
- thumbImage = mediaSliderThumb;
- width = mediaSliderThumbWidth;
- height = mediaSliderThumbHeight;
- } else if (style->appearance() == MediaVolumeSliderThumbPart) {
- thumbImage = mediaVolumeSliderThumb;
- width = mediaVolumeSliderThumbWidth;
- height = mediaVolumeSliderThumbHeight;
- }
-
- float zoomLevel = style->effectiveZoom();
- if (thumbImage) {
- style->setWidth(Length(static_cast<int>(width * zoomLevel), Fixed));
- style->setHeight(Length(static_cast<int>(height * zoomLevel), Fixed));
- }
-}
-
-static String formatChromiumMediaControlsTime(float time, float duration)
-{
- if (!std::isfinite(time))
- time = 0;
- if (!std::isfinite(duration))
- duration = 0;
- int seconds = static_cast<int>(fabsf(time));
- int hours = seconds / (60 * 60);
- int minutes = (seconds / 60) % 60;
- seconds %= 60;
-
- // duration defines the format of how the time is rendered
- int durationSecs = static_cast<int>(fabsf(duration));
- int durationHours = durationSecs / (60 * 60);
- int durationMins = (durationSecs / 60) % 60;
-
- if (durationHours || hours)
- return String::format("%s%01d:%02d:%02d", (time < 0 ? "-" : ""), hours, minutes, seconds);
- if (durationMins > 9)
- return String::format("%s%02d:%02d", (time < 0 ? "-" : ""), minutes, seconds);
-
- return String::format("%s%01d:%02d", (time < 0 ? "-" : ""), minutes, seconds);
-}
-
-String RenderMediaControlsChromium::formatMediaControlsTime(float time)
-{
- return formatChromiumMediaControlsTime(time, time);
-}
-
-String RenderMediaControlsChromium::formatMediaControlsCurrentTime(float currentTime, float duration)
-{
- return formatChromiumMediaControlsTime(currentTime, duration);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderMediaControlsChromium.h b/chromium/third_party/WebKit/Source/core/rendering/RenderMediaControlsChromium.h
deleted file mode 100644
index 9e9e81085b6..00000000000
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderMediaControlsChromium.h
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Copyright (C) 2009 Apple Inc.
- * Copyright (C) 2009 Google Inc.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef RenderMediaControlsChromium_h
-#define RenderMediaControlsChromium_h
-
-#include "core/html/shadow/MediaControlElements.h"
-
-namespace WebCore {
-
-struct PaintInfo;
-
-class HTMLMediaElement;
-class IntRect;
-class RenderObject;
-
-class RenderMediaControlsChromium {
-public:
- static bool paintMediaControlsPart(MediaControlElementType, RenderObject*, const PaintInfo&, const IntRect&);
- static void adjustMediaSliderThumbSize(RenderStyle*);
- static String formatMediaControlsTime(float time);
- static String formatMediaControlsCurrentTime(float currentTime, float duration);
-};
-
-} // namespace WebCore
-
-#endif // RenderMediaControlsChromium_h
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderMenuList.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderMenuList.cpp
index df13d20cc8e..57c8afc1cf8 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderMenuList.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderMenuList.cpp
@@ -27,8 +27,8 @@
#include <math.h>
#include "HTMLNames.h"
+#include "core/accessibility/AXMenuList.h"
#include "core/accessibility/AXObjectCache.h"
-#include "core/accessibility/AccessibilityMenuList.h"
#include "core/css/CSSFontSelector.h"
#include "core/css/resolver/StyleResolver.h"
#include "core/dom/NodeRenderStyle.h"
@@ -36,16 +36,15 @@
#include "core/html/HTMLOptionElement.h"
#include "core/html/HTMLSelectElement.h"
#include "core/page/Chrome.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameView.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
#include "core/page/Page.h"
-#include "core/platform/PopupMenu.h"
-#include "core/platform/graphics/FontCache.h"
-#include "core/platform/graphics/IntSize.h"
#include "core/rendering/RenderBR.h"
#include "core/rendering/RenderScrollbar.h"
#include "core/rendering/RenderTheme.h"
#include "core/rendering/RenderView.h"
+#include "platform/fonts/FontCache.h"
+#include "platform/geometry/IntSize.h"
using namespace std;
@@ -74,11 +73,6 @@ RenderMenuList::~RenderMenuList()
m_popup = 0;
}
-bool RenderMenuList::canBeReplacedWithInlineRunIn() const
-{
- return false;
-}
-
void RenderMenuList::createInnerBlock()
{
if (m_innerBlock) {
@@ -384,13 +378,8 @@ void RenderMenuList::didUpdateActiveOption(int optionIndex)
int listIndex = select->optionToListIndex(optionIndex);
if (listIndex < 0 || listIndex >= static_cast<int>(select->listItems().size()))
return;
-
- HTMLElement* listItem = select->listItems()[listIndex];
- ASSERT(listItem);
- if (listItem->attached()) {
- if (AccessibilityMenuList* menuList = toAccessibilityMenuList(document().axObjectCache()->get(this)))
- menuList->didUpdateActiveOption(optionIndex);
- }
+ if (AXMenuList* menuList = toAXMenuList(document().axObjectCache()->get(this)))
+ menuList->didUpdateActiveOption(optionIndex);
}
String RenderMenuList::itemText(unsigned listIndex) const
@@ -613,7 +602,7 @@ void RenderMenuList::setTextFromItem(unsigned listIndex)
FontSelector* RenderMenuList::fontSelector() const
{
- return document().styleResolver()->fontSelector();
+ return document().styleEngine()->fontSelector();
}
}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderMenuList.h b/chromium/third_party/WebKit/Source/core/rendering/RenderMenuList.h
index a91f3b8b142..54561e0d673 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderMenuList.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderMenuList.h
@@ -24,10 +24,10 @@
#ifndef RenderMenuList_h
#define RenderMenuList_h
-#include "core/platform/PopupMenu.h"
-#include "core/platform/PopupMenuClient.h"
-#include "core/platform/graphics/LayoutRect.h"
#include "core/rendering/RenderFlexibleBox.h"
+#include "platform/PopupMenu.h"
+#include "platform/PopupMenuClient.h"
+#include "platform/geometry/LayoutRect.h"
namespace WebCore {
@@ -65,7 +65,6 @@ private:
virtual LayoutRect controlClipRect(const LayoutPoint&) const;
virtual bool hasControlClip() const { return true; }
virtual bool canHaveGeneratedChildren() const OVERRIDE { return false; }
- virtual bool canBeReplacedWithInlineRunIn() const OVERRIDE;
virtual const char* renderName() const { return "RenderMenuList"; }
@@ -74,8 +73,6 @@ private:
virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle);
- virtual bool requiresForcedStyleRecalcPropagation() const { return true; }
-
// PopupMenuClient methods
virtual void valueChanged(unsigned listIndex, bool fireOnChange = true) OVERRIDE;
virtual void selectionChanged(unsigned, bool) OVERRIDE { }
@@ -141,14 +138,7 @@ private:
bool m_popupIsVisible;
};
-inline RenderMenuList* toRenderMenuList(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isMenuList());
- return static_cast<RenderMenuList*>(object);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toRenderMenuList(const RenderMenuList*);
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderMenuList, isMenuList());
}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderMeter.h b/chromium/third_party/WebKit/Source/core/rendering/RenderMeter.h
index 4dfcacadd86..d1f1e438aef 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderMeter.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderMeter.h
@@ -44,19 +44,11 @@ private:
virtual const char* renderName() const { return "RenderMeter"; }
virtual bool isMeter() const { return true; }
- virtual bool requiresForcedStyleRecalcPropagation() const { return true; }
double valueRatio() const;
};
-inline RenderMeter* toRenderMeter(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isMeter());
- return static_cast<RenderMeter*>(object);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toRenderMeter(const RenderMeter*);
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderMeter, isMeter());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderMultiColumnBlock.h b/chromium/third_party/WebKit/Source/core/rendering/RenderMultiColumnBlock.h
index 1ca4701ff2a..ac92d2f9ff9 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderMultiColumnBlock.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderMultiColumnBlock.h
@@ -44,7 +44,7 @@ public:
RenderMultiColumnFlowThread* flowThread() const { return m_flowThread; }
- bool requiresBalancing() const { return !m_columnHeightAvailable; }
+ bool requiresBalancing() const { return !m_columnHeightAvailable || style()->columnFill() == ColumnFillBalance; }
private:
virtual bool isRenderMultiColumnBlock() const { return true; }
@@ -75,20 +75,7 @@ private:
bool m_inBalancingPass; // Set when relayouting for column balancing.
};
-inline RenderMultiColumnBlock* toRenderMultiColumnBlock(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isRenderMultiColumnBlock());
- return static_cast<RenderMultiColumnBlock*>(object);
-}
-
-inline const RenderMultiColumnBlock* toRenderMultiColumnBlock(const RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isRenderMultiColumnBlock());
- return static_cast<const RenderMultiColumnBlock*>(object);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toRenderMultiColumnBlock(const RenderMultiColumnBlock*);
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderMultiColumnBlock, isRenderMultiColumnBlock());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderMultiColumnSet.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderMultiColumnSet.cpp
index e9687251ebb..449073752ae 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderMultiColumnSet.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderMultiColumnSet.cpp
@@ -282,39 +282,25 @@ LayoutRect RenderMultiColumnSet::flowThreadPortionOverflowRect(const LayoutRect&
bool isLastColumn = index == colCount - 1;
bool isLeftmostColumn = style()->isLeftToRightDirection() ? isFirstColumn : isLastColumn;
bool isRightmostColumn = style()->isLeftToRightDirection() ? isLastColumn : isFirstColumn;
- LayoutRect overflowRect(portionRect);
+
+ // Calculate the overflow rectangle, based on the flow thread's, clipped at column logical
+ // top/bottom unless it's the first/last column.
+ LayoutRect overflowRect = overflowRectForFlowThreadPortion(portionRect, isFirstColumn && isFirstRegion(), isLastColumn && isLastRegion());
+
+ // Avoid overflowing into neighboring columns, by clipping in the middle of adjacent column
+ // gaps. Also make sure that we avoid rounding errors.
if (isHorizontalWritingMode()) {
- if (isLeftmostColumn) {
- // Shift to the logical left overflow of the flow thread to make sure it's all covered.
- overflowRect.shiftXEdgeTo(min(flowThread()->visualOverflowRect().x(), portionRect.x()));
- } else {
- // Expand into half of the logical left column gap.
+ if (!isLeftmostColumn)
overflowRect.shiftXEdgeTo(portionRect.x() - colGap / 2);
- }
- if (isRightmostColumn) {
- // Shift to the logical right overflow of the flow thread to ensure content can spill out of the column.
- overflowRect.shiftMaxXEdgeTo(max(flowThread()->visualOverflowRect().maxX(), portionRect.maxX()));
- } else {
- // Expand into half of the logical right column gap.
- overflowRect.shiftMaxXEdgeTo(portionRect.maxX() + colGap / 2);
- }
+ if (!isRightmostColumn)
+ overflowRect.shiftMaxXEdgeTo(portionRect.maxX() + colGap - colGap / 2);
} else {
- if (isLeftmostColumn) {
- // Shift to the logical left overflow of the flow thread to make sure it's all covered.
- overflowRect.shiftYEdgeTo(min(flowThread()->visualOverflowRect().y(), portionRect.y()));
- } else {
- // Expand into half of the logical left column gap.
+ if (!isLeftmostColumn)
overflowRect.shiftYEdgeTo(portionRect.y() - colGap / 2);
- }
- if (isRightmostColumn) {
- // Shift to the logical right overflow of the flow thread to ensure content can spill out of the column.
- overflowRect.shiftMaxYEdgeTo(max(flowThread()->visualOverflowRect().maxY(), portionRect.maxY()));
- } else {
- // Expand into half of the logical right column gap.
- overflowRect.shiftMaxYEdgeTo(portionRect.maxY() + colGap / 2);
- }
+ if (!isRightmostColumn)
+ overflowRect.shiftMaxYEdgeTo(portionRect.maxY() + colGap - colGap / 2);
}
- return overflowRectForFlowThreadPortion(overflowRect, isFirstRegion() && isFirstColumn, isLastRegion() && isLastColumn);
+ return overflowRect;
}
void RenderMultiColumnSet::paintObject(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
@@ -429,14 +415,25 @@ void RenderMultiColumnSet::repaintFlowThreadContent(const LayoutRect& repaintRec
void RenderMultiColumnSet::collectLayerFragments(LayerFragments& fragments, const LayoutRect& layerBoundingBox, const LayoutRect& dirtyRect)
{
- // Put the layer bounds into flow thread-local coordinates by flipping it first.
+ // The two rectangles passed to this method are physical, except that we pretend that there's
+ // only one long column (that's how a flow thread works).
+ //
+ // Then there's the output from this method - the stuff we put into the list of fragments. The
+ // fragment.paginationOffset point is the actual physical translation required to get from a
+ // location in the flow thread to a location in a given column. The fragment.paginationClip
+ // rectangle, on the other hand, is in the same coordinate system as the two rectangles passed
+ // to this method (flow thread coordinates).
+ //
+ // All other rectangles in this method are sized physically, and the inline direction coordinate
+ // is physical too, but the block direction coordinate is "logical top". This is the same as
+ // e.g. RenderBox::frameRect(). These rectangles also pretend that there's only one long column,
+ // i.e. they are for the flow thread.
+
+ // Put the layer bounds into flow thread-local coordinates by flipping it first. Since we're in
+ // a renderer, most rectangles are represented this way.
LayoutRect layerBoundsInFlowThread(layerBoundingBox);
flowThread()->flipForWritingMode(layerBoundsInFlowThread);
- // Do the same for the dirty rect.
- LayoutRect dirtyRectInFlowThread(dirtyRect);
- flowThread()->flipForWritingMode(dirtyRectInFlowThread);
-
// Now we can compare with the flow thread portions owned by each column. First let's
// see if the rect intersects our flow thread portion at all.
LayoutRect clippedRect(layerBoundsInFlowThread);
@@ -488,11 +485,11 @@ void RenderMultiColumnSet::collectLayerFragments(LayerFragments& fragments, cons
// multicolumn block as well. This won't be an issue until we start creating multiple multicolumn sets.
// Shift the dirty rect to be in flow thread coordinates with this translation applied.
- LayoutRect translatedDirtyRect(dirtyRectInFlowThread);
+ LayoutRect translatedDirtyRect(dirtyRect);
translatedDirtyRect.moveBy(-translationOffset);
// See if we intersect the dirty rect.
- clippedRect = layerBoundsInFlowThread;
+ clippedRect = layerBoundingBox;
clippedRect.intersect(translatedDirtyRect);
if (clippedRect.isEmpty())
continue;
@@ -503,7 +500,8 @@ void RenderMultiColumnSet::collectLayerFragments(LayerFragments& fragments, cons
fragment.paginationOffset = translationOffset;
LayoutRect flippedFlowThreadOverflowPortion(flowThreadOverflowPortion);
- flipForWritingMode(flippedFlowThreadOverflowPortion);
+ // Flip it into more a physical (RenderLayer-style) rectangle.
+ flowThread()->flipForWritingMode(flippedFlowThreadOverflowPortion);
fragment.paginationClip = flippedFlowThreadOverflowPortion;
fragments.append(fragment);
}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderMultiColumnSet.h b/chromium/third_party/WebKit/Source/core/rendering/RenderMultiColumnSet.h
index d60bd977608..3ebfc5e9c56 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderMultiColumnSet.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderMultiColumnSet.h
@@ -152,20 +152,7 @@ private:
LayoutUnit m_forcedBreakOffset;
};
-inline RenderMultiColumnSet* toRenderMultiColumnSet(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isRenderMultiColumnSet());
- return static_cast<RenderMultiColumnSet*>(object);
-}
-
-inline const RenderMultiColumnSet* toRenderMultiColumnSet(const RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isRenderMultiColumnSet());
- return static_cast<const RenderMultiColumnSet*>(object);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toRenderMultiColumnSet(const RenderMultiColumnSet*);
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderMultiColumnSet, isRenderMultiColumnSet());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderNamedFlowFragment.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderNamedFlowFragment.cpp
new file mode 100644
index 00000000000..5a754e99f82
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderNamedFlowFragment.cpp
@@ -0,0 +1,108 @@
+/*
+ * Copyright (C) 2013 Adobe Systems Incorporated. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer.
+ * 2. Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer in the documentation and/or other materials
+ * provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
+ * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
+ * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
+ * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/rendering/RenderNamedFlowFragment.h"
+
+#include "core/rendering/FlowThreadController.h"
+#include "core/rendering/RenderBoxRegionInfo.h"
+#include "core/rendering/RenderFlowThread.h"
+#include "core/rendering/RenderNamedFlowThread.h"
+#include "core/rendering/RenderView.h"
+
+using namespace std;
+
+namespace WebCore {
+
+RenderNamedFlowFragment::RenderNamedFlowFragment()
+ : RenderRegion(0, 0)
+{
+}
+
+RenderNamedFlowFragment::~RenderNamedFlowFragment()
+{
+}
+
+RenderNamedFlowFragment* RenderNamedFlowFragment::createAnonymous(Document* document)
+{
+ RenderNamedFlowFragment* region = new RenderNamedFlowFragment();
+ region->setDocumentForAnonymous(document);
+ return region;
+}
+
+void RenderNamedFlowFragment::setStyleForNamedFlowFragment(const RenderStyle* parentStyle)
+{
+ RefPtr<RenderStyle> newStyle = RenderStyle::createAnonymousStyleWithDisplay(parentStyle, BLOCK);
+
+ newStyle->setFlowThread(parentStyle->flowThread());
+ newStyle->setRegionThread(parentStyle->regionThread());
+ newStyle->setRegionFragment(parentStyle->regionFragment());
+ newStyle->setShapeInside(parentStyle->shapeInside());
+ newStyle->setOverflowX(parentStyle->overflowX());
+ newStyle->setOverflowY(parentStyle->overflowY());
+
+ setStyle(newStyle.release());
+}
+
+void RenderNamedFlowFragment::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
+{
+ RenderRegion::styleDidChange(diff, oldStyle);
+
+ if (parent() && parent()->needsLayout())
+ setNeedsLayout();
+}
+
+// FIXME: flex items as regions with flex-basis: 0 inside a flex container
+// with flex-direction: column should not be treated as auto-height regions
+bool RenderNamedFlowFragment::shouldHaveAutoLogicalHeight() const
+{
+ ASSERT(parent());
+
+ RenderStyle* styleToUse = parent()->style();
+ bool hasSpecifiedEndpointsForHeight = styleToUse->logicalTop().isSpecified() && styleToUse->logicalBottom().isSpecified();
+ bool hasAnchoredEndpointsForHeight = isOutOfFlowPositioned() && hasSpecifiedEndpointsForHeight;
+ bool hasAutoHeightStyle = styleToUse->logicalHeight().isAuto()
+ || styleToUse->logicalHeight().isFitContent()
+ || styleToUse->logicalHeight().isMaxContent()
+ || styleToUse->logicalHeight().isMinContent();
+ return hasAutoHeightStyle && !hasAnchoredEndpointsForHeight;
+}
+
+LayoutUnit RenderNamedFlowFragment::maxPageLogicalHeight() const
+{
+ ASSERT(m_flowThread);
+ ASSERT(hasAutoLogicalHeight() && !m_flowThread->inConstrainedLayoutPhase());
+ ASSERT(isAnonymous());
+ ASSERT(parent());
+
+ RenderStyle* styleToUse = parent()->style();
+ return styleToUse->logicalMaxHeight().isUndefined() ? RenderFlowThread::maxLogicalHeight() : toRenderBlock(parent())->computeReplacedLogicalHeightUsing(styleToUse->logicalMaxHeight());
+}
+
+}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderNamedFlowFragment.h b/chromium/third_party/WebKit/Source/core/rendering/RenderNamedFlowFragment.h
new file mode 100644
index 00000000000..79e4d7ceb63
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderNamedFlowFragment.h
@@ -0,0 +1,74 @@
+/*
+ * Copyright (C) 2013 Adobe Systems Incorporated. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer.
+ * 2. Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer in the documentation and/or other materials
+ * provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
+ * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
+ * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
+ * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#ifndef RenderNamedFlowFragment_h
+#define RenderNamedFlowFragment_h
+
+#include "core/rendering/RenderRegion.h"
+
+namespace WebCore {
+
+class Element;
+class RenderStyle;
+
+// RenderNamedFlowFragment represents a region that is responsible for the fragmentation of
+// the RenderNamedFlowThread content.
+//
+// A RenderNamedFlowFragment object is created as an anonymous child for a RenderBlockFlow object
+// that has a valid -webkit-flow-from property.
+//
+// This allows a non-replaced block to behave like a region if needed, following the CSSRegions specification:
+// http://dev.w3.org/csswg/css-regions/#the-flow-from-property.
+// list-item, table-caption, table-cell can become regions in addition to block | inline-block.
+
+class RenderNamedFlowFragment FINAL : public RenderRegion {
+public:
+ virtual ~RenderNamedFlowFragment();
+ static RenderNamedFlowFragment* createAnonymous(Document*);
+
+ void setStyleForNamedFlowFragment(const RenderStyle*);
+
+ virtual bool isRenderNamedFlowFragment() const OVERRIDE { return true; }
+ virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle) OVERRIDE;
+
+ virtual LayoutUnit maxPageLogicalHeight() const OVERRIDE;
+
+protected:
+ RenderNamedFlowFragment();
+
+private:
+ virtual bool shouldHaveAutoLogicalHeight() const OVERRIDE;
+ virtual const char* renderName() const OVERRIDE { return "RenderNamedFlowFragment"; }
+};
+
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderNamedFlowFragment, isRenderNamedFlowFragment());
+
+}
+
+#endif // RenderNamedFlowFragment_h
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderNamedFlowThread.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderNamedFlowThread.cpp
index 7d25ae65f40..72049543c9d 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderNamedFlowThread.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderNamedFlowThread.cpp
@@ -82,7 +82,7 @@ void RenderNamedFlowThread::clearContentNodes()
ASSERT(contentNode && contentNode->isElementNode());
ASSERT(contentNode->inNamedFlow());
- ASSERT(&contentNode->document() == &document());
+ ASSERT(contentNode->document() == document());
contentNode->clearInNamedFlow();
}
@@ -193,12 +193,12 @@ static bool compareRenderRegions(const RenderRegion* firstRegion, const RenderRe
ASSERT(firstRegion);
ASSERT(secondRegion);
- ASSERT(firstRegion->generatingNode());
- ASSERT(secondRegion->generatingNode());
+ ASSERT(firstRegion->generatingNodeForRegion());
+ ASSERT(secondRegion->generatingNodeForRegion());
// If the regions belong to different nodes, compare their position in the DOM.
- if (firstRegion->generatingNode() != secondRegion->generatingNode()) {
- unsigned short position = firstRegion->generatingNode()->compareDocumentPosition(secondRegion->generatingNode());
+ if (firstRegion->generatingNodeForRegion() != secondRegion->generatingNodeForRegion()) {
+ unsigned short position = firstRegion->generatingNodeForRegion()->compareDocumentPosition(secondRegion->generatingNodeForRegion());
// If the second region is contained in the first one, the first region is "less" if it's :before.
if (position & Node::DOCUMENT_POSITION_CONTAINED_BY) {
@@ -442,7 +442,7 @@ void RenderNamedFlowThread::pushDependencies(RenderNamedFlowThreadList& list)
void RenderNamedFlowThread::registerNamedFlowContentNode(Node* contentNode)
{
ASSERT(contentNode && contentNode->isElementNode());
- ASSERT(&contentNode->document() == &document());
+ ASSERT(contentNode->document() == document());
contentNode->setInNamedFlow();
@@ -465,7 +465,7 @@ void RenderNamedFlowThread::unregisterNamedFlowContentNode(Node* contentNode)
ASSERT(contentNode && contentNode->isElementNode());
ASSERT(m_contentNodes.contains(contentNode));
ASSERT(contentNode->inNamedFlow());
- ASSERT(&contentNode->document() == &document());
+ ASSERT(contentNode->document() == document());
contentNode->clearInNamedFlow();
m_contentNodes.remove(contentNode);
@@ -568,12 +568,11 @@ static bool boxIntersectsRegion(LayoutUnit logicalTopForBox, LayoutUnit logicalB
}
// Retrieve the next node to be visited while computing the ranges inside a region.
-static Node* nextNodeInsideContentNode(const Node* currNode, const Node* contentNode)
+static Node* nextNodeInsideContentNode(const Node& currNode, const Node* contentNode)
{
- ASSERT(currNode);
ASSERT(contentNode && contentNode->inNamedFlow());
- if (currNode->renderer() && currNode->renderer()->isSVGRoot())
+ if (currNode.renderer() && currNode.renderer()->isSVGRoot())
return NodeTraversal::nextSkippingChildren(currNode, contentNode);
return NodeTraversal::next(currNode, contentNode);
}
@@ -615,7 +614,7 @@ void RenderNamedFlowThread::getRanges(Vector<RefPtr<Range> >& rangeObjects, cons
bool skipOverOutsideNodes = false;
Node* lastEndNode = 0;
- for (Node* node = contentNode; node; node = nextNodeInsideContentNode(node, contentNode)) {
+ for (Node* node = contentNode; node; node = nextNodeInsideContentNode(*node, contentNode)) {
RenderObject* renderer = node->renderer();
if (!renderer)
continue;
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderNamedFlowThread.h b/chromium/third_party/WebKit/Source/core/rendering/RenderNamedFlowThread.h
index c0dec6cbdc1..6528c1106c5 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderNamedFlowThread.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderNamedFlowThread.h
@@ -27,8 +27,8 @@
#ifndef RenderNamedFlowThread_h
#define RenderNamedFlowThread_h
-#include "core/platform/Timer.h"
#include "core/rendering/RenderFlowThread.h"
+#include "platform/Timer.h"
#include "wtf/HashCountedSet.h"
#include "wtf/ListHashSet.h"
#include "wtf/text/AtomicString.h"
@@ -136,20 +136,7 @@ private:
Timer<RenderNamedFlowThread> m_regionOversetChangeEventTimer;
};
-inline RenderNamedFlowThread* toRenderNamedFlowThread(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isRenderNamedFlowThread());
- return static_cast<RenderNamedFlowThread*>(object);
-}
-
-inline const RenderNamedFlowThread* toRenderNamedFlowThread(const RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isRenderNamedFlowThread());
- return static_cast<const RenderNamedFlowThread*>(object);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toRenderNamedFlowThread(const RenderNamedFlowThread*);
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderNamedFlowThread, isRenderNamedFlowThread());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderObject.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderObject.cpp
index dc4a42400ab..1192be3d768 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderObject.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderObject.cpp
@@ -35,23 +35,23 @@
#include "core/editing/EditingBoundary.h"
#include "core/editing/FrameSelection.h"
#include "core/editing/htmlediting.h"
+#include "core/fetch/ResourceLoader.h"
#include "core/html/HTMLAnchorElement.h"
#include "core/html/HTMLElement.h"
#include "core/html/HTMLHtmlElement.h"
#include "core/html/HTMLTableElement.h"
+#include "core/page/AutoscrollController.h"
#include "core/page/EventHandler.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameView.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
#include "core/page/Page.h"
-#include "core/page/Settings.h"
-#include "core/page/UseCounter.h"
-#include "core/page/animation/AnimationController.h"
-#include "core/platform/Partitions.h"
-#include "core/platform/graphics/FloatQuad.h"
-#include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/graphics/transforms/TransformState.h"
+#include "core/frame/Settings.h"
+#include "core/frame/UseCounter.h"
+#include "core/frame/animation/AnimationController.h"
+#include "core/rendering/CompositedLayerMapping.h"
#include "core/rendering/FlowThreadController.h"
#include "core/rendering/HitTestResult.h"
+#include "core/rendering/LayoutRectRecorder.h"
#include "core/rendering/RenderCounter.h"
#include "core/rendering/RenderDeprecatedFlexibleBox.h"
#include "core/rendering/RenderFlexibleBox.h"
@@ -61,7 +61,6 @@
#include "core/rendering/RenderImageResourceStyleImage.h"
#include "core/rendering/RenderInline.h"
#include "core/rendering/RenderLayer.h"
-#include "core/rendering/RenderLayerBacking.h"
#include "core/rendering/RenderLayerCompositor.h"
#include "core/rendering/RenderListItem.h"
#include "core/rendering/RenderMarquee.h"
@@ -79,9 +78,12 @@
#include "core/rendering/RenderView.h"
#include "core/rendering/style/ContentData.h"
#include "core/rendering/style/CursorList.h"
+#include "core/rendering/style/ShadowList.h"
#include "core/rendering/svg/SVGRenderSupport.h"
+#include "platform/Partitions.h"
+#include "platform/geometry/TransformState.h"
+#include "platform/graphics/GraphicsContext.h"
#include "wtf/RefCountedLeakCounter.h"
-#include "wtf/UnusedParam.h"
#include "wtf/text/StringBuilder.h"
#include <algorithm>
#ifndef NDEBUG
@@ -116,14 +118,14 @@ struct SameSizeAsRenderObject {
unsigned m_debugBitfields : 2;
#endif
unsigned m_bitfields;
+ unsigned m_bitfields2;
+ LayoutRect rects[2]; // Stores the old/new repaint rects.
};
COMPILE_ASSERT(sizeof(RenderObject) == sizeof(SameSizeAsRenderObject), RenderObject_should_stay_small);
bool RenderObject::s_affectsParentBlock = false;
-RenderObjectAncestorLineboxDirtySet* RenderObject::s_ancestorLineboxDirtySet = 0;
-
void* RenderObject::operator new(size_t sz)
{
ASSERT(isMainThread());
@@ -168,13 +170,6 @@ RenderObject* RenderObject::createObject(Element* element, RenderStyle* style)
// treat <rt> as ruby text ONLY if it still has its default treatment of block
if (element->hasTagName(rtTag) && style->display() == BLOCK)
return new RenderRubyText(element);
- if (RuntimeEnabledFeatures::cssRegionsEnabled() && style->isDisplayRegionType() && !style->regionThread().isEmpty() && doc.renderView())
- return new RenderRegion(element, 0);
-
- if (style->display() == RUN_IN)
- UseCounter::count(&doc, UseCounter::CSSDisplayRunIn);
- else if (style->display() == COMPACT)
- UseCounter::count(&doc, UseCounter::CSSDisplayCompact);
switch (style->display()) {
case NONE:
@@ -183,8 +178,6 @@ RenderObject* RenderObject::createObject(Element* element, RenderStyle* style)
return new RenderInline(element);
case BLOCK:
case INLINE_BLOCK:
- case RUN_IN:
- case COMPACT:
if ((!style->hasAutoColumnCount() || !style->hasAutoColumnWidth()) && doc.regionBasedColumnsEnabled())
return new RenderMultiColumnBlock(element);
return new RenderBlockFlow(element);
@@ -225,7 +218,7 @@ DEFINE_DEBUG_ONLY_GLOBAL(WTF::RefCountedLeakCounter, renderObjectCounter, ("Rend
RenderObject::RenderObject(Node* node)
: ImageResourceClient()
, m_style(0)
- , m_nodeProxy(node)
+ , m_node(node)
, m_parent(0)
, m_previous(0)
, m_next(0)
@@ -438,19 +431,6 @@ RenderObject* RenderObject::childAt(unsigned index) const
return child;
}
-RenderObject* RenderObject::firstLeafChild() const
-{
- RenderObject* r = firstChild();
- while (r) {
- RenderObject* n = 0;
- n = r->firstChild();
- if (!n)
- break;
- r = n;
- }
- return r;
-}
-
RenderObject* RenderObject::lastLeafChild() const
{
RenderObject* r = lastChild();
@@ -575,11 +555,11 @@ RenderLayer* RenderObject::enclosingLayer() const
bool RenderObject::scrollRectToVisible(const LayoutRect& rect, const ScrollAlignment& alignX, const ScrollAlignment& alignY)
{
- RenderLayer* enclosingLayer = this->enclosingLayer();
- if (!enclosingLayer)
+ RenderBox* enclosingBox = this->enclosingBox();
+ if (!enclosingBox)
return false;
- enclosingLayer->scrollRectToVisible(rect, alignX, alignY);
+ enclosingBox->scrollRectToVisible(rect, alignX, alignY);
return true;
}
@@ -609,6 +589,20 @@ RenderBoxModelObject* RenderObject::enclosingBoxModelObject() const
return 0;
}
+RenderBox* RenderObject::enclosingScrollableBox() const
+{
+ for (RenderObject* ancestor = parent(); ancestor; ancestor = ancestor->parent()) {
+ if (!ancestor->isBox())
+ continue;
+
+ RenderBox* ancestorBox = toRenderBox(ancestor);
+ if (ancestorBox->canBeScrolledAndHasScrollableArea())
+ return ancestorBox;
+ }
+
+ return 0;
+}
+
RenderFlowThread* RenderObject::locateFlowThreadContainingBlock() const
{
ASSERT(flowThreadState() != NotInsideFlowThread);
@@ -780,13 +774,29 @@ void RenderObject::invalidateContainerPreferredLogicalWidths()
void RenderObject::setLayerNeedsFullRepaint()
{
ASSERT(hasLayer());
- toRenderLayerModelObject(this)->layer()->setRepaintStatus(NeedsFullRepaint);
+ toRenderLayerModelObject(this)->layer()->repainter().setRepaintStatus(NeedsFullRepaint);
}
void RenderObject::setLayerNeedsFullRepaintForPositionedMovementLayout()
{
ASSERT(hasLayer());
- toRenderLayerModelObject(this)->layer()->setRepaintStatus(NeedsFullRepaintForPositionedMovementLayout);
+ toRenderLayerModelObject(this)->layer()->repainter().setRepaintStatus(NeedsFullRepaintForPositionedMovementLayout);
+}
+
+RenderBlock* RenderObject::containerForFixedPosition(const RenderLayerModelObject* repaintContainer, bool* repaintContainerSkipped) const
+{
+ ASSERT(!repaintContainerSkipped || !*repaintContainerSkipped);
+ ASSERT(!isText());
+ ASSERT(style()->position() == FixedPosition);
+
+ RenderObject* ancestor = parent();
+ for (; ancestor && !ancestor->canContainFixedPositionObjects(); ancestor = ancestor->parent()) {
+ if (repaintContainerSkipped && ancestor == repaintContainer)
+ *repaintContainerSkipped = true;
+ }
+
+ ASSERT(!ancestor || !ancestor->isAnonymousBlock());
+ return toRenderBlock(ancestor);
}
RenderBlock* RenderObject::containingBlock() const
@@ -795,12 +805,7 @@ RenderBlock* RenderObject::containingBlock() const
if (!o && isRenderScrollbarPart())
o = toRenderScrollbarPart(this)->rendererOwningScrollbar();
if (!isText() && m_style->position() == FixedPosition) {
- while (o) {
- if (o->canContainFixedPositionObjects())
- break;
- o = o->parent();
- }
- ASSERT(!o || !o->isAnonymousBlock());
+ return containerForFixedPosition();
} else if (!isText() && m_style->position() == AbsolutePosition) {
while (o) {
// For relpositioned inlines, we return the nearest non-anonymous enclosing block. We don't try
@@ -810,17 +815,14 @@ RenderBlock* RenderObject::containingBlock() const
// inline directly.
if (o->style()->position() != StaticPosition && (!o->isInline() || o->isReplaced()))
break;
- if (o->isRenderView())
- break;
- if (o->hasTransform() && o->isRenderBlock())
+
+ if (o->canContainAbsolutePositionObjects())
break;
if (o->style()->hasInFlowPosition() && o->isInline() && !o->isReplaced()) {
o = o->containingBlock();
break;
}
- if (o->isSVGForeignObject()) //foreignObject is the containing block for contents inside it
- break;
o = o->parent();
}
@@ -860,8 +862,11 @@ static bool mustRepaintFillLayers(const RenderObject* renderer, const FillLayer*
if (sizeType == SizeLength) {
if (layer->sizeLength().width().isPercent() || layer->sizeLength().height().isPercent())
return true;
- } else if (img->usesImageContainerSize())
+ if (img->isGeneratedImage() && (layer->sizeLength().width().isAuto() || layer->sizeLength().height().isAuto()))
+ return true;
+ } else if (img->usesImageContainerSize()) {
return true;
+ }
return false;
}
@@ -916,209 +921,234 @@ void RenderObject::drawLineForBoxSide(GraphicsContext* graphicsContext, int x1,
style = SOLID;
switch (style) {
- case BNONE:
- case BHIDDEN:
- return;
- case DOTTED:
- case DASHED: {
- if (thickness > 0) {
- bool wasAntialiased = graphicsContext->shouldAntialias();
- StrokeStyle oldStrokeStyle = graphicsContext->strokeStyle();
- graphicsContext->setShouldAntialias(antialias);
- graphicsContext->setStrokeColor(color);
- graphicsContext->setStrokeThickness(thickness);
- graphicsContext->setStrokeStyle(style == DASHED ? DashedStroke : DottedStroke);
-
- switch (side) {
- case BSBottom:
- case BSTop:
- graphicsContext->drawLine(IntPoint(x1, (y1 + y2) / 2), IntPoint(x2, (y1 + y2) / 2));
- break;
- case BSRight:
- case BSLeft:
- graphicsContext->drawLine(IntPoint((x1 + x2) / 2, y1), IntPoint((x1 + x2) / 2, y2));
- break;
- }
- graphicsContext->setShouldAntialias(wasAntialiased);
- graphicsContext->setStrokeStyle(oldStrokeStyle);
- }
- break;
- }
- case DOUBLE: {
- int thirdOfThickness = (thickness + 1) / 3;
- ASSERT(thirdOfThickness);
-
- if (adjacentWidth1 == 0 && adjacentWidth2 == 0) {
- StrokeStyle oldStrokeStyle = graphicsContext->strokeStyle();
- graphicsContext->setStrokeStyle(NoStroke);
- graphicsContext->setFillColor(color);
-
- bool wasAntialiased = graphicsContext->shouldAntialias();
- graphicsContext->setShouldAntialias(antialias);
-
- switch (side) {
- case BSTop:
- case BSBottom:
- graphicsContext->drawRect(IntRect(x1, y1, length, thirdOfThickness));
- graphicsContext->drawRect(IntRect(x1, y2 - thirdOfThickness, length, thirdOfThickness));
- break;
- case BSLeft:
- case BSRight:
- // FIXME: Why do we offset the border by 1 in this case but not the other one?
- if (length > 1) {
- graphicsContext->drawRect(IntRect(x1, y1 + 1, thirdOfThickness, length - 1));
- graphicsContext->drawRect(IntRect(x2 - thirdOfThickness, y1 + 1, thirdOfThickness, length - 1));
- }
- break;
- }
+ case BNONE:
+ case BHIDDEN:
+ return;
+ case DOTTED:
+ case DASHED:
+ drawDashedOrDottedBoxSide(graphicsContext, x1, y1, x2, y2, side,
+ color, thickness, style, antialias);
+ break;
+ case DOUBLE:
+ drawDoubleBoxSide(graphicsContext, x1, y1, x2, y2, length, side, color,
+ thickness, adjacentWidth1, adjacentWidth2, antialias);
+ break;
+ case RIDGE:
+ case GROOVE:
+ drawRidgeOrGrooveBoxSide(graphicsContext, x1, y1, x2, y2, side, color,
+ style, adjacentWidth1, adjacentWidth2, antialias);
+ break;
+ case INSET:
+ // FIXME: Maybe we should lighten the colors on one side like Firefox.
+ // https://bugs.webkit.org/show_bug.cgi?id=58608
+ if (side == BSTop || side == BSLeft)
+ color = color.dark();
+ // fall through
+ case OUTSET:
+ if (style == OUTSET && (side == BSBottom || side == BSRight))
+ color = color.dark();
+ // fall through
+ case SOLID:
+ drawSolidBoxSide(graphicsContext, x1, y1, x2, y2, side, color, adjacentWidth1, adjacentWidth2, antialias);
+ break;
+ }
+}
+
+void RenderObject::drawDashedOrDottedBoxSide(GraphicsContext* graphicsContext, int x1, int y1, int x2, int y2,
+ BoxSide side, Color color, int thickness, EBorderStyle style, bool antialias)
+{
+ if (thickness <= 0)
+ return;
- graphicsContext->setShouldAntialias(wasAntialiased);
- graphicsContext->setStrokeStyle(oldStrokeStyle);
- } else {
- int adjacent1BigThird = ((adjacentWidth1 > 0) ? adjacentWidth1 + 1 : adjacentWidth1 - 1) / 3;
- int adjacent2BigThird = ((adjacentWidth2 > 0) ? adjacentWidth2 + 1 : adjacentWidth2 - 1) / 3;
-
- switch (side) {
- case BSTop:
- drawLineForBoxSide(graphicsContext, x1 + max((-adjacentWidth1 * 2 + 1) / 3, 0),
- y1, x2 - max((-adjacentWidth2 * 2 + 1) / 3, 0), y1 + thirdOfThickness,
- side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
- drawLineForBoxSide(graphicsContext, x1 + max((adjacentWidth1 * 2 + 1) / 3, 0),
- y2 - thirdOfThickness, x2 - max((adjacentWidth2 * 2 + 1) / 3, 0), y2,
- side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
- break;
- case BSLeft:
- drawLineForBoxSide(graphicsContext, x1, y1 + max((-adjacentWidth1 * 2 + 1) / 3, 0),
- x1 + thirdOfThickness, y2 - max((-adjacentWidth2 * 2 + 1) / 3, 0),
- side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
- drawLineForBoxSide(graphicsContext, x2 - thirdOfThickness, y1 + max((adjacentWidth1 * 2 + 1) / 3, 0),
- x2, y2 - max((adjacentWidth2 * 2 + 1) / 3, 0),
- side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
- break;
- case BSBottom:
- drawLineForBoxSide(graphicsContext, x1 + max((adjacentWidth1 * 2 + 1) / 3, 0),
- y1, x2 - max((adjacentWidth2 * 2 + 1) / 3, 0), y1 + thirdOfThickness,
- side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
- drawLineForBoxSide(graphicsContext, x1 + max((-adjacentWidth1 * 2 + 1) / 3, 0),
- y2 - thirdOfThickness, x2 - max((-adjacentWidth2 * 2 + 1) / 3, 0), y2,
- side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
- break;
- case BSRight:
- drawLineForBoxSide(graphicsContext, x1, y1 + max((adjacentWidth1 * 2 + 1) / 3, 0),
- x1 + thirdOfThickness, y2 - max((adjacentWidth2 * 2 + 1) / 3, 0),
- side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
- drawLineForBoxSide(graphicsContext, x2 - thirdOfThickness, y1 + max((-adjacentWidth1 * 2 + 1) / 3, 0),
- x2, y2 - max((-adjacentWidth2 * 2 + 1) / 3, 0),
- side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
- break;
- default:
- break;
- }
- }
+ bool wasAntialiased = graphicsContext->shouldAntialias();
+ StrokeStyle oldStrokeStyle = graphicsContext->strokeStyle();
+ graphicsContext->setShouldAntialias(antialias);
+ graphicsContext->setStrokeColor(color);
+ graphicsContext->setStrokeThickness(thickness);
+ graphicsContext->setStrokeStyle(style == DASHED ? DashedStroke : DottedStroke);
+
+ switch (side) {
+ case BSBottom:
+ case BSTop:
+ graphicsContext->drawLine(IntPoint(x1, (y1 + y2) / 2), IntPoint(x2, (y1 + y2) / 2));
+ break;
+ case BSRight:
+ case BSLeft:
+ graphicsContext->drawLine(IntPoint((x1 + x2) / 2, y1), IntPoint((x1 + x2) / 2, y2));
+ break;
+ }
+ graphicsContext->setShouldAntialias(wasAntialiased);
+ graphicsContext->setStrokeStyle(oldStrokeStyle);
+}
+
+void RenderObject::drawDoubleBoxSide(GraphicsContext* graphicsContext, int x1, int y1, int x2, int y2,
+ int length, BoxSide side, Color color, int thickness, int adjacentWidth1, int adjacentWidth2, bool antialias)
+{
+ int thirdOfThickness = (thickness + 1) / 3;
+ ASSERT(thirdOfThickness);
+
+ if (!adjacentWidth1 && !adjacentWidth2) {
+ StrokeStyle oldStrokeStyle = graphicsContext->strokeStyle();
+ graphicsContext->setStrokeStyle(NoStroke);
+ graphicsContext->setFillColor(color);
+
+ bool wasAntialiased = graphicsContext->shouldAntialias();
+ graphicsContext->setShouldAntialias(antialias);
+
+ switch (side) {
+ case BSTop:
+ case BSBottom:
+ graphicsContext->drawRect(IntRect(x1, y1, length, thirdOfThickness));
+ graphicsContext->drawRect(IntRect(x1, y2 - thirdOfThickness, length, thirdOfThickness));
break;
- }
- case RIDGE:
- case GROOVE: {
- EBorderStyle s1;
- EBorderStyle s2;
- if (style == GROOVE) {
- s1 = INSET;
- s2 = OUTSET;
- } else {
- s1 = OUTSET;
- s2 = INSET;
- }
-
- int adjacent1BigHalf = ((adjacentWidth1 > 0) ? adjacentWidth1 + 1 : adjacentWidth1 - 1) / 2;
- int adjacent2BigHalf = ((adjacentWidth2 > 0) ? adjacentWidth2 + 1 : adjacentWidth2 - 1) / 2;
-
- switch (side) {
- case BSTop:
- drawLineForBoxSide(graphicsContext, x1 + max(-adjacentWidth1, 0) / 2, y1, x2 - max(-adjacentWidth2, 0) / 2, (y1 + y2 + 1) / 2,
- side, color, s1, adjacent1BigHalf, adjacent2BigHalf, antialias);
- drawLineForBoxSide(graphicsContext, x1 + max(adjacentWidth1 + 1, 0) / 2, (y1 + y2 + 1) / 2, x2 - max(adjacentWidth2 + 1, 0) / 2, y2,
- side, color, s2, adjacentWidth1 / 2, adjacentWidth2 / 2, antialias);
- break;
- case BSLeft:
- drawLineForBoxSide(graphicsContext, x1, y1 + max(-adjacentWidth1, 0) / 2, (x1 + x2 + 1) / 2, y2 - max(-adjacentWidth2, 0) / 2,
- side, color, s1, adjacent1BigHalf, adjacent2BigHalf, antialias);
- drawLineForBoxSide(graphicsContext, (x1 + x2 + 1) / 2, y1 + max(adjacentWidth1 + 1, 0) / 2, x2, y2 - max(adjacentWidth2 + 1, 0) / 2,
- side, color, s2, adjacentWidth1 / 2, adjacentWidth2 / 2, antialias);
- break;
- case BSBottom:
- drawLineForBoxSide(graphicsContext, x1 + max(adjacentWidth1, 0) / 2, y1, x2 - max(adjacentWidth2, 0) / 2, (y1 + y2 + 1) / 2,
- side, color, s2, adjacent1BigHalf, adjacent2BigHalf, antialias);
- drawLineForBoxSide(graphicsContext, x1 + max(-adjacentWidth1 + 1, 0) / 2, (y1 + y2 + 1) / 2, x2 - max(-adjacentWidth2 + 1, 0) / 2, y2,
- side, color, s1, adjacentWidth1 / 2, adjacentWidth2 / 2, antialias);
- break;
- case BSRight:
- drawLineForBoxSide(graphicsContext, x1, y1 + max(adjacentWidth1, 0) / 2, (x1 + x2 + 1) / 2, y2 - max(adjacentWidth2, 0) / 2,
- side, color, s2, adjacent1BigHalf, adjacent2BigHalf, antialias);
- drawLineForBoxSide(graphicsContext, (x1 + x2 + 1) / 2, y1 + max(-adjacentWidth1 + 1, 0) / 2, x2, y2 - max(-adjacentWidth2 + 1, 0) / 2,
- side, color, s1, adjacentWidth1 / 2, adjacentWidth2 / 2, antialias);
- break;
+ case BSLeft:
+ case BSRight:
+ // FIXME: Why do we offset the border by 1 in this case but not the other one?
+ if (length > 1) {
+ graphicsContext->drawRect(IntRect(x1, y1 + 1, thirdOfThickness, length - 1));
+ graphicsContext->drawRect(IntRect(x2 - thirdOfThickness, y1 + 1, thirdOfThickness, length - 1));
}
break;
}
- case INSET:
- // FIXME: Maybe we should lighten the colors on one side like Firefox.
- // https://bugs.webkit.org/show_bug.cgi?id=58608
- if (side == BSTop || side == BSLeft)
- color = color.dark();
- // fall through
- case OUTSET:
- if (style == OUTSET && (side == BSBottom || side == BSRight))
- color = color.dark();
- // fall through
- case SOLID: {
- StrokeStyle oldStrokeStyle = graphicsContext->strokeStyle();
- graphicsContext->setStrokeStyle(NoStroke);
- graphicsContext->setFillColor(color);
- ASSERT(x2 >= x1);
- ASSERT(y2 >= y1);
- if (!adjacentWidth1 && !adjacentWidth2) {
- // Turn off antialiasing to match the behavior of drawConvexPolygon();
- // this matters for rects in transformed contexts.
- bool wasAntialiased = graphicsContext->shouldAntialias();
- graphicsContext->setShouldAntialias(antialias);
- graphicsContext->drawRect(IntRect(x1, y1, x2 - x1, y2 - y1));
- graphicsContext->setShouldAntialias(wasAntialiased);
- graphicsContext->setStrokeStyle(oldStrokeStyle);
- return;
- }
- FloatPoint quad[4];
- switch (side) {
- case BSTop:
- quad[0] = FloatPoint(x1 + max(-adjacentWidth1, 0), y1);
- quad[1] = FloatPoint(x1 + max(adjacentWidth1, 0), y2);
- quad[2] = FloatPoint(x2 - max(adjacentWidth2, 0), y2);
- quad[3] = FloatPoint(x2 - max(-adjacentWidth2, 0), y1);
- break;
- case BSBottom:
- quad[0] = FloatPoint(x1 + max(adjacentWidth1, 0), y1);
- quad[1] = FloatPoint(x1 + max(-adjacentWidth1, 0), y2);
- quad[2] = FloatPoint(x2 - max(-adjacentWidth2, 0), y2);
- quad[3] = FloatPoint(x2 - max(adjacentWidth2, 0), y1);
- break;
- case BSLeft:
- quad[0] = FloatPoint(x1, y1 + max(-adjacentWidth1, 0));
- quad[1] = FloatPoint(x1, y2 - max(-adjacentWidth2, 0));
- quad[2] = FloatPoint(x2, y2 - max(adjacentWidth2, 0));
- quad[3] = FloatPoint(x2, y1 + max(adjacentWidth1, 0));
- break;
- case BSRight:
- quad[0] = FloatPoint(x1, y1 + max(adjacentWidth1, 0));
- quad[1] = FloatPoint(x1, y2 - max(adjacentWidth2, 0));
- quad[2] = FloatPoint(x2, y2 - max(-adjacentWidth2, 0));
- quad[3] = FloatPoint(x2, y1 + max(-adjacentWidth1, 0));
- break;
- }
- graphicsContext->drawConvexPolygon(4, quad, antialias);
- graphicsContext->setStrokeStyle(oldStrokeStyle);
- break;
- }
+ graphicsContext->setShouldAntialias(wasAntialiased);
+ graphicsContext->setStrokeStyle(oldStrokeStyle);
+ return;
}
+
+ int adjacent1BigThird = ((adjacentWidth1 > 0) ? adjacentWidth1 + 1 : adjacentWidth1 - 1) / 3;
+ int adjacent2BigThird = ((adjacentWidth2 > 0) ? adjacentWidth2 + 1 : adjacentWidth2 - 1) / 3;
+
+ switch (side) {
+ case BSTop:
+ drawLineForBoxSide(graphicsContext, x1 + max((-adjacentWidth1 * 2 + 1) / 3, 0),
+ y1, x2 - max((-adjacentWidth2 * 2 + 1) / 3, 0), y1 + thirdOfThickness,
+ side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
+ drawLineForBoxSide(graphicsContext, x1 + max((adjacentWidth1 * 2 + 1) / 3, 0),
+ y2 - thirdOfThickness, x2 - max((adjacentWidth2 * 2 + 1) / 3, 0), y2,
+ side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
+ break;
+ case BSLeft:
+ drawLineForBoxSide(graphicsContext, x1, y1 + max((-adjacentWidth1 * 2 + 1) / 3, 0),
+ x1 + thirdOfThickness, y2 - max((-adjacentWidth2 * 2 + 1) / 3, 0),
+ side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
+ drawLineForBoxSide(graphicsContext, x2 - thirdOfThickness, y1 + max((adjacentWidth1 * 2 + 1) / 3, 0),
+ x2, y2 - max((adjacentWidth2 * 2 + 1) / 3, 0),
+ side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
+ break;
+ case BSBottom:
+ drawLineForBoxSide(graphicsContext, x1 + max((adjacentWidth1 * 2 + 1) / 3, 0),
+ y1, x2 - max((adjacentWidth2 * 2 + 1) / 3, 0), y1 + thirdOfThickness,
+ side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
+ drawLineForBoxSide(graphicsContext, x1 + max((-adjacentWidth1 * 2 + 1) / 3, 0),
+ y2 - thirdOfThickness, x2 - max((-adjacentWidth2 * 2 + 1) / 3, 0), y2,
+ side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
+ break;
+ case BSRight:
+ drawLineForBoxSide(graphicsContext, x1, y1 + max((adjacentWidth1 * 2 + 1) / 3, 0),
+ x1 + thirdOfThickness, y2 - max((adjacentWidth2 * 2 + 1) / 3, 0),
+ side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
+ drawLineForBoxSide(graphicsContext, x2 - thirdOfThickness, y1 + max((-adjacentWidth1 * 2 + 1) / 3, 0),
+ x2, y2 - max((-adjacentWidth2 * 2 + 1) / 3, 0),
+ side, color, SOLID, adjacent1BigThird, adjacent2BigThird, antialias);
+ break;
+ default:
+ break;
+ }
+}
+
+void RenderObject::drawRidgeOrGrooveBoxSide(GraphicsContext* graphicsContext, int x1, int y1, int x2, int y2,
+ BoxSide side, Color color, EBorderStyle style, int adjacentWidth1, int adjacentWidth2, bool antialias)
+{
+ EBorderStyle s1;
+ EBorderStyle s2;
+ if (style == GROOVE) {
+ s1 = INSET;
+ s2 = OUTSET;
+ } else {
+ s1 = OUTSET;
+ s2 = INSET;
+ }
+
+ int adjacent1BigHalf = ((adjacentWidth1 > 0) ? adjacentWidth1 + 1 : adjacentWidth1 - 1) / 2;
+ int adjacent2BigHalf = ((adjacentWidth2 > 0) ? adjacentWidth2 + 1 : adjacentWidth2 - 1) / 2;
+
+ switch (side) {
+ case BSTop:
+ drawLineForBoxSide(graphicsContext, x1 + max(-adjacentWidth1, 0) / 2, y1, x2 - max(-adjacentWidth2, 0) / 2, (y1 + y2 + 1) / 2,
+ side, color, s1, adjacent1BigHalf, adjacent2BigHalf, antialias);
+ drawLineForBoxSide(graphicsContext, x1 + max(adjacentWidth1 + 1, 0) / 2, (y1 + y2 + 1) / 2, x2 - max(adjacentWidth2 + 1, 0) / 2, y2,
+ side, color, s2, adjacentWidth1 / 2, adjacentWidth2 / 2, antialias);
+ break;
+ case BSLeft:
+ drawLineForBoxSide(graphicsContext, x1, y1 + max(-adjacentWidth1, 0) / 2, (x1 + x2 + 1) / 2, y2 - max(-adjacentWidth2, 0) / 2,
+ side, color, s1, adjacent1BigHalf, adjacent2BigHalf, antialias);
+ drawLineForBoxSide(graphicsContext, (x1 + x2 + 1) / 2, y1 + max(adjacentWidth1 + 1, 0) / 2, x2, y2 - max(adjacentWidth2 + 1, 0) / 2,
+ side, color, s2, adjacentWidth1 / 2, adjacentWidth2 / 2, antialias);
+ break;
+ case BSBottom:
+ drawLineForBoxSide(graphicsContext, x1 + max(adjacentWidth1, 0) / 2, y1, x2 - max(adjacentWidth2, 0) / 2, (y1 + y2 + 1) / 2,
+ side, color, s2, adjacent1BigHalf, adjacent2BigHalf, antialias);
+ drawLineForBoxSide(graphicsContext, x1 + max(-adjacentWidth1 + 1, 0) / 2, (y1 + y2 + 1) / 2, x2 - max(-adjacentWidth2 + 1, 0) / 2, y2,
+ side, color, s1, adjacentWidth1 / 2, adjacentWidth2 / 2, antialias);
+ break;
+ case BSRight:
+ drawLineForBoxSide(graphicsContext, x1, y1 + max(adjacentWidth1, 0) / 2, (x1 + x2 + 1) / 2, y2 - max(adjacentWidth2, 0) / 2,
+ side, color, s2, adjacent1BigHalf, adjacent2BigHalf, antialias);
+ drawLineForBoxSide(graphicsContext, (x1 + x2 + 1) / 2, y1 + max(-adjacentWidth1 + 1, 0) / 2, x2, y2 - max(-adjacentWidth2 + 1, 0) / 2,
+ side, color, s1, adjacentWidth1 / 2, adjacentWidth2 / 2, antialias);
+ break;
+ }
+}
+
+void RenderObject::drawSolidBoxSide(GraphicsContext* graphicsContext, int x1, int y1, int x2, int y2,
+ BoxSide side, Color color, int adjacentWidth1, int adjacentWidth2, bool antialias)
+{
+ StrokeStyle oldStrokeStyle = graphicsContext->strokeStyle();
+ graphicsContext->setStrokeStyle(NoStroke);
+ graphicsContext->setFillColor(color);
+ ASSERT(x2 >= x1);
+ ASSERT(y2 >= y1);
+ if (!adjacentWidth1 && !adjacentWidth2) {
+ // Turn off antialiasing to match the behavior of drawConvexPolygon();
+ // this matters for rects in transformed contexts.
+ bool wasAntialiased = graphicsContext->shouldAntialias();
+ graphicsContext->setShouldAntialias(antialias);
+ graphicsContext->drawRect(IntRect(x1, y1, x2 - x1, y2 - y1));
+ graphicsContext->setShouldAntialias(wasAntialiased);
+ graphicsContext->setStrokeStyle(oldStrokeStyle);
+ return;
+ }
+ FloatPoint quad[4];
+ switch (side) {
+ case BSTop:
+ quad[0] = FloatPoint(x1 + max(-adjacentWidth1, 0), y1);
+ quad[1] = FloatPoint(x1 + max(adjacentWidth1, 0), y2);
+ quad[2] = FloatPoint(x2 - max(adjacentWidth2, 0), y2);
+ quad[3] = FloatPoint(x2 - max(-adjacentWidth2, 0), y1);
+ break;
+ case BSBottom:
+ quad[0] = FloatPoint(x1 + max(adjacentWidth1, 0), y1);
+ quad[1] = FloatPoint(x1 + max(-adjacentWidth1, 0), y2);
+ quad[2] = FloatPoint(x2 - max(-adjacentWidth2, 0), y2);
+ quad[3] = FloatPoint(x2 - max(adjacentWidth2, 0), y1);
+ break;
+ case BSLeft:
+ quad[0] = FloatPoint(x1, y1 + max(-adjacentWidth1, 0));
+ quad[1] = FloatPoint(x1, y2 - max(-adjacentWidth2, 0));
+ quad[2] = FloatPoint(x2, y2 - max(adjacentWidth2, 0));
+ quad[3] = FloatPoint(x2, y1 + max(adjacentWidth1, 0));
+ break;
+ case BSRight:
+ quad[0] = FloatPoint(x1, y1 + max(adjacentWidth1, 0));
+ quad[1] = FloatPoint(x1, y2 - max(adjacentWidth2, 0));
+ quad[2] = FloatPoint(x2, y2 - max(-adjacentWidth2, 0));
+ quad[3] = FloatPoint(x2, y1 + max(-adjacentWidth1, 0));
+ break;
+ }
+
+ graphicsContext->drawConvexPolygon(4, quad, antialias);
+ graphicsContext->setStrokeStyle(oldStrokeStyle);
}
void RenderObject::paintFocusRing(PaintInfo& paintInfo, const LayoutPoint& paintOffset, RenderStyle* style)
@@ -1336,7 +1366,7 @@ RenderLayerModelObject* RenderObject::containerForRepaint() const
if (parentRenderFlowThread) {
// The ancestor document will do the reparenting when the repaint propagates further up.
// We're just a seamless child document, and we don't need to do the hacking.
- if (&parentRenderFlowThread && &parentRenderFlowThread->document() != &document())
+ if (parentRenderFlowThread->document() != document())
return repaintContainer;
// If we have already found a repaint container then we will repaint into that container only if it is part of the same
// flow thread. Otherwise we will need to catch the repaint call and send it to the flow thread.
@@ -1354,20 +1384,48 @@ void RenderObject::repaintUsingContainer(const RenderLayerModelObject* repaintCo
return;
}
+ if (repaintContainer->compositingState() == PaintsIntoGroupedBacking) {
+ ASSERT(repaintContainer->groupedMapping());
+
+ // Not clean, but if squashing layer does not yet exist here (e.g. repaint invalidation coming from within recomputing compositing requirements)
+ // then it's ok to just exit here, since the squashing layer will get repainted when it is newly created.
+ if (!repaintContainer->groupedMapping()->squashingLayer())
+ return;
+
+
+ IntRect offsetRect(r);
+
+ // First, convert the repaint rect into the space of the repaintContainer
+ TransformState transformState(TransformState::ApplyTransformDirection, FloatQuad(FloatRect(r)));
+ mapLocalToContainer(repaintContainer, transformState, ApplyContainerFlip);
+ transformState.flatten();
+ offsetRect = transformState.lastPlanarQuad().enclosingBoundingBox();
+
+ // FIXME: the repaint rect computed below could be tighter in uncommon nested transform cases, if we passed the quad
+ // directly to the next chunk of code.
+
+ // Then, convert the repaint rect from repaintConainer space into the squashing GraphicsLayer's coordinates.
+ if (repaintContainer->hasTransform())
+ offsetRect = repaintContainer->layer()->transform()->mapRect(r);
+ offsetRect.move(-repaintContainer->layer()->offsetFromSquashingLayerOrigin());
+ repaintContainer->groupedMapping()->squashingLayer()->setNeedsDisplayInRect(offsetRect);
+ return;
+ }
+
if (repaintContainer->isRenderFlowThread()) {
toRenderFlowThread(repaintContainer)->repaintRectangleInRegions(r);
return;
}
- if (repaintContainer->hasFilter() && repaintContainer->layer() && repaintContainer->layer()->requiresFullLayerImageForFilters()) {
- repaintContainer->layer()->setFilterBackendNeedsRepaintingInRect(r);
+ if (repaintContainer->hasFilter() && repaintContainer->layer()->requiresFullLayerImageForFilters()) {
+ repaintContainer->layer()->repainter().setFilterBackendNeedsRepaintingInRect(r);
return;
}
RenderView* v = view();
if (repaintContainer->isRenderView()) {
ASSERT(repaintContainer == v);
- bool viewHasCompositedLayer = v->hasLayer() && v->layer()->isComposited();
+ bool viewHasCompositedLayer = v->hasLayer() && v->layer()->compositingState() == PaintsIntoOwnBacking;
if (!viewHasCompositedLayer) {
IntRect repaintRectangle = r;
if (viewHasCompositedLayer && v->layer()->transform())
@@ -1378,8 +1436,8 @@ void RenderObject::repaintUsingContainer(const RenderLayerModelObject* repaintCo
}
if (v->usesCompositing()) {
- ASSERT(repaintContainer->hasLayer() && repaintContainer->layer()->isComposited());
- repaintContainer->layer()->setBackingNeedsRepaintInRect(r);
+ ASSERT(repaintContainer->hasLayer() && repaintContainer->layer()->compositingState() == PaintsIntoOwnBacking);
+ repaintContainer->layer()->repainter().setBackingNeedsRepaintInRect(r);
}
}
@@ -1423,7 +1481,9 @@ IntRect RenderObject::pixelSnappedAbsoluteClippedOverflowRect() const
return pixelSnappedIntRect(absoluteClippedOverflowRect());
}
-bool RenderObject::repaintAfterLayoutIfNeeded(const RenderLayerModelObject* repaintContainer, const LayoutRect& oldBounds, const LayoutRect& oldOutlineBox, const LayoutRect* newBoundsPtr, const LayoutRect* newOutlineBoxRectPtr)
+bool RenderObject::repaintAfterLayoutIfNeeded(const RenderLayerModelObject* repaintContainer, bool wasSelfLayout,
+ const LayoutRect& oldBounds, const LayoutRect& oldOutlineBox,
+ const LayoutRect* newBoundsPtr, const LayoutRect* newOutlineBoxRectPtr)
{
RenderView* v = view();
if (v->document().printing())
@@ -1434,7 +1494,7 @@ bool RenderObject::repaintAfterLayoutIfNeeded(const RenderLayerModelObject* repa
LayoutRect newBounds = newBoundsPtr ? *newBoundsPtr : clippedOverflowRectForRepaint(repaintContainer);
LayoutRect newOutlineBox;
- bool fullRepaint = selfNeedsLayout();
+ bool fullRepaint = wasSelfLayout;
// Presumably a background or a border exists if border-fit:lines was specified.
if (!fullRepaint && style()->borderFit() == BorderFitLines)
fullRepaint = true;
@@ -1541,6 +1601,10 @@ bool RenderObject::repaintAfterLayoutIfNeeded(const RenderLayerModelObject* repa
return false;
}
+void RenderObject::repaintOverflow()
+{
+}
+
bool RenderObject::checkForRepaintDuringLayout() const
{
return !document().view()->needsFullRepaint() && !hasLayer() && everHadLayout();
@@ -1735,7 +1799,7 @@ void RenderObject::handleDynamicFloatPositionChange()
void RenderObject::setAnimatableStyle(PassRefPtr<RenderStyle> style)
{
if (!isText() && style && !RuntimeEnabledFeatures::webAnimationsCSSEnabled()) {
- setStyle(animation()->updateAnimations(this, style.get()));
+ setStyle(animation().updateAnimations(*this, *style));
return;
}
setStyle(style);
@@ -1743,12 +1807,15 @@ void RenderObject::setAnimatableStyle(PassRefPtr<RenderStyle> style)
StyleDifference RenderObject::adjustStyleDifference(StyleDifference diff, unsigned contextSensitiveProperties) const
{
- // If transform changed, and we are not composited, need to do a layout.
+ // If transform changed, and the layer does not paint into its own separate backing, then we need to do a layout.
+ // FIXME: The comment above is what the code does, but it is technically not following spec. This means we will
+ // not to layout for 3d transforms, but we should be invoking a simplified relayout. Is it possible we are avoiding
+ // doing this for some performance reason at this time?
if (contextSensitiveProperties & ContextSensitivePropertyTransform) {
// Text nodes share style with their parents but transforms don't apply to them,
// hence the !isText() check.
// FIXME: when transforms are taken into account for overflow, we will need to do a layout.
- if (!isText() && (!hasLayer() || !toRenderLayerModelObject(this)->layer()->isComposited())) {
+ if (!isText() && (!hasLayer() || toRenderLayerModelObject(this)->layer()->compositingState() != PaintsIntoOwnBacking)) {
// We need to set at least SimplifiedLayout, but if PositionedMovementOnly is already set
// then we actually need SimplifiedLayoutAndPositionedMovement.
if (!hasLayer())
@@ -1761,18 +1828,17 @@ StyleDifference RenderObject::adjustStyleDifference(StyleDifference diff, unsign
diff = StyleDifferenceRecompositeLayer;
}
- // If opacity changed, and we are not composited, need to repaint (also
+ // If opacity or filters changed, and the layer does not paint into its own separate backing, then we need to repaint (also
// ignoring text nodes)
- if (contextSensitiveProperties & ContextSensitivePropertyOpacity) {
- if (!isText() && (!hasLayer() || !toRenderLayerModelObject(this)->layer()->isComposited()))
+ if (contextSensitiveProperties & ContextSensitivePropertyOpacity && diff <= StyleDifferenceRepaintLayer) {
+ if (!isText() && (!hasLayer() || toRenderLayerModelObject(this)->layer()->compositingState() != PaintsIntoOwnBacking))
diff = StyleDifferenceRepaintLayer;
else if (diff < StyleDifferenceRecompositeLayer)
diff = StyleDifferenceRecompositeLayer;
}
-
- if ((contextSensitiveProperties & ContextSensitivePropertyFilter) && hasLayer()) {
+ if ((contextSensitiveProperties & ContextSensitivePropertyFilter) && hasLayer() && diff <= StyleDifferenceRepaintLayer) {
RenderLayer* layer = toRenderLayerModelObject(this)->layer();
- if (!layer->isComposited() || layer->paintsWithFilters())
+ if (layer->compositingState() != PaintsIntoOwnBacking || layer->paintsWithFilters())
diff = StyleDifferenceRepaintLayer;
else if (diff < StyleDifferenceRecompositeLayer)
diff = StyleDifferenceRecompositeLayer;
@@ -1816,18 +1882,20 @@ void RenderObject::setPseudoStyle(PassRefPtr<RenderStyle> pseudoStyle)
setStyle(pseudoStyle);
}
-inline bool RenderObject::hasImmediateNonWhitespaceTextChild() const
+inline bool RenderObject::hasImmediateNonWhitespaceTextChildOrPropertiesDependentOnColor() const
{
for (const RenderObject* r = firstChild(); r; r = r->nextSibling()) {
if (r->isText() && !toRenderText(r)->isAllCollapsibleWhitespace())
return true;
+ if (r->style()->hasOutline() || r->style()->hasBorder())
+ return true;
}
return false;
}
inline bool RenderObject::shouldRepaintForStyleDifference(StyleDifference diff) const
{
- return diff == StyleDifferenceRepaint || (diff == StyleDifferenceRepaintIfText && hasImmediateNonWhitespaceTextChild());
+ return diff == StyleDifferenceRepaint || (diff == StyleDifferenceRepaintIfTextOrColorChange && hasImmediateNonWhitespaceTextChildOrPropertiesDependentOnColor());
}
void RenderObject::setStyle(PassRefPtr<RenderStyle> style)
@@ -1858,6 +1926,7 @@ void RenderObject::setStyle(PassRefPtr<RenderStyle> style)
updateImage(oldStyle ? oldStyle->maskBoxImage().image() : 0, m_style ? m_style->maskBoxImage().image() : 0);
updateShapeImage(oldStyle ? oldStyle->shapeInside() : 0, m_style ? m_style->shapeInside() : 0);
+ updateShapeImage(oldStyle ? oldStyle->shapeOutside() : 0, m_style ? m_style->shapeOutside() : 0);
// We need to ensure that view->maximalOutlineSize() is valid for any repaints that happen
// during styleDidChange (it's used by clippedOverflowRectForRepaint()).
@@ -1948,16 +2017,12 @@ void RenderObject::styleWillChange(StyleDifference diff, const RenderStyle* newS
&& (!newStyle->isFloating() && !newStyle->hasOutOfFlowPosition())
&& parent() && (parent()->isRenderBlockFlow() || parent()->isRenderInline());
- // reset style flags
+ // Clearing these bits is required to avoid leaving stale renderers.
+ // FIXME: We shouldn't need that hack if our logic was totally correct.
if (diff == StyleDifferenceLayout || diff == StyleDifferenceLayoutPositionedMovementOnly) {
setFloating(false);
clearPositionedState();
}
- setHorizontalWritingMode(true);
- setHasBoxDecorations(false);
- setHasOverflowClip(false);
- setHasTransform(false);
- setHasReflection(false);
} else
s_affectsParentBlock = false;
@@ -2014,7 +2079,7 @@ void RenderObject::styleDidChange(StyleDifference diff, const RenderStyle* oldSt
return;
if (diff == StyleDifferenceLayout || diff == StyleDifferenceSimplifiedLayout) {
- RenderCounter::rendererStyleChanged(this, oldStyle, m_style.get());
+ RenderCounter::rendererStyleChanged(*this, oldStyle, m_style.get());
// If the object already needs layout, then setNeedsLayout won't do
// any work. But if the containing block has changed, then we may need
@@ -2039,7 +2104,7 @@ void RenderObject::styleDidChange(StyleDifference diff, const RenderStyle* oldSt
if (oldStyle && !areCursorsEqual(oldStyle, style())) {
if (Frame* frame = this->frame())
- frame->eventHandler()->dispatchFakeMouseMoveEventSoon();
+ frame->eventHandler().scheduleCursorUpdate();
}
}
@@ -2304,7 +2369,8 @@ void RenderObject::computeLayerHitTestRects(LayerHitTestRects& layerRects) const
// If the layer itself is scrolled, we have to undo the subtraction of its scroll
// offset since we want the offset relative to the scrolling content, not the
// element itself.
- layerOffset.move(currentLayer->scrolledContentOffset());
+ if (currentLayer->renderer()->hasOverflowClip())
+ layerOffset.move(currentLayer->renderBox()->scrolledContentOffset());
}
} else {
currentLayer = enclosingLayer();
@@ -2439,35 +2505,16 @@ RenderObject* RenderObject::container(const RenderLayerModelObject* repaintConta
EPosition pos = m_style->position();
if (pos == FixedPosition) {
- // container() can be called on an object that is not in the
- // tree yet. We don't call view() since it will assert if it
- // can't get back to the canvas. Instead we just walk as high up
- // as we can. If we're in the tree, we'll get the root. If we
- // aren't we'll get the root of our little subtree (most likely
- // we'll just return 0).
- // FIXME: The definition of view() has changed to not crawl up the render tree. It might
- // be safe now to use it.
- while (o && o->parent() && !(o->hasTransform() && o->isRenderBlock())) {
- // foreignObject is the containing block for its contents.
- if (o->isSVGForeignObject())
- break;
-
- // The render flow thread is the top most containing block
- // for the fixed positioned elements.
- if (o->isOutOfFlowRenderFlowThread())
+ return containerForFixedPosition(repaintContainer, repaintContainerSkipped);
+ } else if (pos == AbsolutePosition) {
+ // We technically just want our containing block, but
+ // we may not have one if we're part of an uninstalled
+ // subtree. We'll climb as high as we can though.
+ while (o) {
+ if (o->style()->position() != StaticPosition)
break;
- if (repaintContainerSkipped && o == repaintContainer)
- *repaintContainerSkipped = true;
-
- o = o->parent();
- }
- } else if (pos == AbsolutePosition) {
- // Same goes here. We technically just want our containing block, but
- // we may not have one if we're part of an uninstalled subtree. We'll
- // climb as high as we can though.
- while (o && o->style()->position() == StaticPosition && !o->isRenderView() && !(o->hasTransform() && o->isRenderBlock())) {
- if (o->isSVGForeignObject()) // foreignObject is the containing block for contents inside it
+ if (o->canContainFixedPositionObjects())
break;
if (repaintContainerSkipped && o == repaintContainer)
@@ -2509,16 +2556,12 @@ void RenderObject::willBeDestroyed()
if (children)
children->destroyLeftoverChildren();
- // If this renderer is being autoscrolled, stop the autoscroll timer
-
- // FIXME: RenderObject::destroy should not get called with a renderer whose document
- // has a null frame, so we assert this. However, we don't want release builds to crash which is why we
- // check that the frame is not null.
- ASSERT(frame());
- if (frame() && frame()->page())
- frame()->page()->stopAutoscrollIfNeeded(this);
-
- animation()->cancelAnimations(this);
+ // If this renderer is being autoscrolled, stop the autoscrolling.
+ if (Frame* frame = this->frame()) {
+ if (frame->page())
+ frame->page()->autoscrollController().stopAutoscrollIfNeeded(this);
+ frame->animation().cancelAnimations(this);
+ }
// For accessibility management, notify the parent of the imminent change to its child set.
// We do it now, before remove(), while the parent pointer is still available.
@@ -2550,14 +2593,7 @@ void RenderObject::willBeDestroyed()
// this renderer had no parent at the time remove() was called.
if (hasCounterNodeMap())
- RenderCounter::destroyCounterNodes(this);
-
- // FIXME: Would like to do this in RenderBoxModelObject, but the timing is so complicated that this can't easily
- // be moved into RenderBoxModelObject::destroy.
- if (hasLayer()) {
- setHasLayer(false);
- toRenderLayerModelObject(this)->destroyLayer();
- }
+ RenderCounter::destroyCounterNodes(*this);
setAncestorLineBoxDirty(false);
@@ -2711,6 +2747,7 @@ void RenderObject::postDestroy()
maskBoxImage->removeClient(this);
removeShapeImageClient(m_style->shapeInside());
+ removeShapeImageClient(m_style->shapeOutside());
}
delete this;
@@ -2731,20 +2768,11 @@ void RenderObject::updateDragState(bool dragOn)
curr->updateDragState(dragOn);
}
-bool RenderObject::isComposited() const
+CompositingState RenderObject::compositingState() const
{
- return hasLayer() && toRenderLayerModelObject(this)->layer()->isComposited();
+ return hasLayer() ? toRenderLayerModelObject(this)->layer()->compositingState() : NotComposited;
}
-bool RenderObject::canResize() const
-{
- // We need a special case for <iframe> because they never have
- // hasOverflowClip(). However, they do "implicitly" clip their contents, so
- // we want to allow resizing them also.
- return (hasOverflowClip() || isRenderIFrame()) && style()->resize() != RESIZE_NONE;
-}
-
-
bool RenderObject::hitTest(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestFilter hitTestFilter)
{
bool inside = false;
@@ -2814,6 +2842,7 @@ void RenderObject::scheduleRelayout()
void RenderObject::layout()
{
ASSERT(needsLayout());
+ LayoutRectRecorder recorder(*this);
RenderObject* child = firstChild();
while (child) {
child->layoutIfNeeded();
@@ -2823,9 +2852,22 @@ void RenderObject::layout()
clearNeedsLayout();
}
+void RenderObject::didLayout(ResourceLoadPriorityOptimizer& priorityModifier)
+{
+ for (RenderObject* child = firstChild(); child; child = child->nextSibling())
+ child->didLayout(priorityModifier);
+}
+
+void RenderObject::didScroll(ResourceLoadPriorityOptimizer& priorityModifier)
+{
+ for (RenderObject* child = firstChild(); child; child = child->nextSibling())
+ child->didScroll(priorityModifier);
+}
+
void RenderObject::forceLayout()
{
setSelfNeedsLayout(true);
+ setShouldDoFullRepaintAfterLayout(true);
layout();
}
@@ -2922,12 +2964,12 @@ PassRefPtr<RenderStyle> RenderObject::getUncachedPseudoStyle(const PseudoStyleRe
Element* element = toElement(n);
if (pseudoStyleRequest.pseudoId == FIRST_LINE_INHERITED) {
- RefPtr<RenderStyle> result = document().styleResolver()->styleForElement(element, parentStyle, DisallowStyleSharing);
+ RefPtr<RenderStyle> result = document().ensureStyleResolver().styleForElement(element, parentStyle, DisallowStyleSharing);
result->setStyleType(FIRST_LINE_INHERITED);
return result.release();
}
- return document().styleResolver()->pseudoStyleForElement(element, pseudoStyleRequest, parentStyle);
+ return document().ensureStyleResolver().pseudoStyleForElement(element, pseudoStyleRequest, parentStyle);
}
bool RenderObject::hasBlendMode() const
@@ -2953,16 +2995,17 @@ static Color decorationColor(const RenderObject* object, RenderStyle* style)
return result;
}
-void RenderObject::getTextDecorationColors(int decorations, Color& underline, Color& overline,
+void RenderObject::getTextDecorationColors(unsigned decorations, Color& underline, Color& overline,
Color& linethrough, bool quirksMode, bool firstlineStyle)
{
RenderObject* curr = this;
RenderStyle* styleToUse = 0;
- TextDecoration currDecs = TextDecorationNone;
+ unsigned currDecs = TextDecorationNone;
Color resultColor;
do {
styleToUse = curr->style(firstlineStyle);
currDecs = styleToUse->textDecoration();
+ currDecs &= decorations;
resultColor = decorationColor(this, styleToUse);
// Parameter 'decorations' is cast as an int to enable the bitwise operations below.
if (currDecs) {
@@ -3005,14 +3048,16 @@ void RenderObject::addAnnotatedRegions(Vector<AnnotatedRegionValue>& regions)
if (style()->visibility() != VISIBLE || !isBox())
return;
- RenderBox* box = toRenderBox(this);
- FloatPoint absPos = localToAbsolute();
-
if (style()->getDraggableRegionMode() == DraggableRegionNone)
return;
+
+ RenderBox* box = toRenderBox(this);
+ FloatRect localBounds(FloatPoint(), FloatSize(box->width(), box->height()));
+ FloatRect absBounds = localToAbsoluteQuad(localBounds).boundingBox();
+
AnnotatedRegionValue region;
region.draggable = style()->getDraggableRegionMode() == DraggableRegionDrag;
- region.bounds = LayoutRect(absPos.x(), absPos.y(), box->width(), box->height());
+ region.bounds = LayoutRect(absBounds);
regions.append(region);
}
@@ -3082,7 +3127,7 @@ int RenderObject::nextOffset(int current) const
void RenderObject::adjustRectForOutlineAndShadow(LayoutRect& rect) const
{
int outlineSize = outlineStyleForRepaint()->outlineSize();
- if (const ShadowData* boxShadow = style()->boxShadow()) {
+ if (const ShadowList* boxShadow = style()->boxShadow()) {
boxShadow->adjustRectForShadow(rect, outlineSize);
return;
}
@@ -3090,7 +3135,7 @@ void RenderObject::adjustRectForOutlineAndShadow(LayoutRect& rect) const
rect.inflate(outlineSize);
}
-AnimationController* RenderObject::animation() const
+AnimationController& RenderObject::animation() const
{
return frame()->animation();
}
@@ -3264,17 +3309,6 @@ bool RenderObject::canHaveGeneratedChildren() const
return canHaveChildren();
}
-bool RenderObject::canBeReplacedWithInlineRunIn() const
-{
- return true;
-}
-
-RenderSVGResourceContainer* RenderObject::toRenderSVGResourceContainer()
-{
- ASSERT_NOT_REACHED();
- return 0;
-}
-
void RenderObject::setNeedsBoundariesUpdate()
{
if (RenderObject* renderer = parent())
@@ -3319,6 +3353,27 @@ bool RenderObject::nodeAtFloatPoint(const HitTestRequest&, HitTestResult&, const
return false;
}
+// FIXME: This should really use local coords
+// Works on absolute coords - expensive to call
+bool RenderObject::isContainedInParentBoundingBox() const
+{
+ if (!parent())
+ return false;
+
+ IntRect parentRect = parent()->absoluteBoundingBoxRect();
+ return parentRect.contains(absoluteBoundingBoxRect());
+}
+
+bool RenderObject::isRelayoutBoundaryForInspector() const
+{
+ return objectIsRelayoutBoundary(this);
+}
+
+bool RenderObject::isRenderNamedFlowFragmentContainer() const
+{
+ return isRenderBlockFlow() && toRenderBlockFlow(this)->renderNamedFlowFragment();
+}
+
} // namespace WebCore
#ifndef NDEBUG
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderObject.h b/chromium/third_party/WebKit/Source/core/rendering/RenderObject.h
index e45fb1cdd40..37044c4e86d 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderObject.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderObject.h
@@ -30,18 +30,17 @@
#include "core/dom/Position.h"
#include "core/dom/StyleEngine.h"
#include "core/fetch/ImageResourceClient.h"
-#include "core/platform/graphics/FloatQuad.h"
-#include "core/platform/graphics/LayoutRect.h"
-#include "core/platform/graphics/transforms/TransformationMatrix.h"
+#include "core/rendering/CompositingState.h"
#include "core/rendering/LayoutIndicator.h"
#include "core/rendering/PaintPhase.h"
#include "core/rendering/RenderObjectChildList.h"
-#include "core/rendering/RenderingNodeProxy.h"
#include "core/rendering/ScrollBehavior.h"
#include "core/rendering/SubtreeLayoutScope.h"
#include "core/rendering/style/RenderStyle.h"
#include "core/rendering/style/StyleInheritedData.h"
-#include "wtf/HashSet.h"
+#include "platform/geometry/FloatQuad.h"
+#include "platform/geometry/LayoutRect.h"
+#include "platform/transforms/TransformationMatrix.h"
namespace WebCore {
@@ -68,6 +67,7 @@ class RenderSVGResourceContainer;
class RenderTable;
class RenderTheme;
class RenderView;
+class ResourceLoadPriorityOptimizer;
class TransformState;
struct PaintInfo;
@@ -120,16 +120,11 @@ struct AnnotatedRegionValue {
{
return draggable == o.draggable && bounds == o.bounds;
}
- bool operator!=(const AnnotatedRegionValue& o) const
- {
- return !(*this == o);
- }
LayoutRect bounds;
bool draggable;
};
-typedef WTF::HashSet<const RenderObject*> RenderObjectAncestorLineboxDirtySet;
typedef WTF::HashMap<const RenderLayer*, Vector<LayoutRect> > LayerHitTestRects;
#ifndef NDEBUG
@@ -139,7 +134,9 @@ const int showTreeCharacterOffset = 39;
// Base class for all rendering tree objects.
class RenderObject : public ImageResourceClient {
friend class RenderBlock;
+ friend class RenderBlockFlow;
friend class RenderLayer; // For setParent.
+ friend class RenderLayerReflectionInfo; // For setParent
friend class RenderLayerScrollableArea; // For setParent.
friend class RenderObjectChildList;
public:
@@ -187,7 +184,6 @@ public:
RenderObject* previousInPreOrder(const RenderObject* stayWithin) const;
RenderObject* childAt(unsigned) const;
- RenderObject* firstLeafChild() const;
RenderObject* lastLeafChild() const;
// The following six functions are used when the render tree hierarchy changes to make sure layers get
@@ -206,6 +202,8 @@ public:
RenderBox* enclosingBox() const;
RenderBoxModelObject* enclosingBoxModelObject() const;
+ RenderBox* enclosingScrollableBox() const;
+
// Function to return our enclosing flow thread if we are contained inside one. This
// function follows the containing block chain.
RenderFlowThread* flowThreadContainingBlock() const
@@ -322,7 +320,6 @@ public:
virtual bool isBR() const { return false; }
virtual bool isBoxModelObject() const { return false; }
virtual bool isCounter() const { return false; }
- virtual bool isDialog() const { return false; }
virtual bool isQuote() const { return false; }
virtual bool isDetailsMarker() const { return false; }
@@ -351,6 +348,7 @@ public:
virtual bool isRenderInline() const { return false; }
virtual bool isRenderPart() const { return false; }
virtual bool isRenderRegion() const { return false; }
+ virtual bool isRenderNamedFlowFragment() const { return false; }
virtual bool isRenderView() const { return false; }
virtual bool isReplica() const { return false; }
@@ -382,13 +380,14 @@ public:
virtual bool isRenderNamedFlowThread() const { return false; }
bool isInFlowRenderFlowThread() const { return isRenderFlowThread() && !isOutOfFlowPositioned(); }
bool isOutOfFlowRenderFlowThread() const { return isRenderFlowThread() && isOutOfFlowPositioned(); }
+ bool isRenderNamedFlowFragmentContainer() const;
virtual bool isRenderMultiColumnBlock() const { return false; }
virtual bool isRenderMultiColumnSet() const { return false; }
virtual bool isRenderScrollbarPart() const { return false; }
- bool isRoot() const { return document().documentElement() == m_nodeProxy.unsafeNode(); }
+ bool isRoot() const { return document().documentElement() == m_node; }
bool isBody() const;
bool isHR() const;
bool isLegend() const;
@@ -398,9 +397,7 @@ public:
inline bool isBeforeContent() const;
inline bool isAfterContent() const;
inline bool isBeforeOrAfterContent() const;
- static inline bool isBeforeContent(const RenderObject* obj) { return obj && obj->isBeforeContent(); }
static inline bool isAfterContent(const RenderObject* obj) { return obj && obj->isAfterContent(); }
- static inline bool isBeforeOrAfterContent(const RenderObject* obj) { return obj && obj->isBeforeOrAfterContent(); }
bool hasCounterNodeMap() const { return m_bitfields.hasCounterNodeMap(); }
void setHasCounterNodeMap(bool hasCounterNodeMap) { m_bitfields.setHasCounterNodeMap(hasCounterNodeMap); }
@@ -411,21 +408,12 @@ public:
bool hasColumns() const { return m_bitfields.hasColumns(); }
void setHasColumns(bool b = true) { m_bitfields.setHasColumns(b); }
- bool ancestorLineBoxDirty() const { return s_ancestorLineboxDirtySet && s_ancestorLineboxDirtySet->contains(this); }
- void setAncestorLineBoxDirty(bool b = true)
+ bool ancestorLineBoxDirty() const { return m_bitfields.ancestorLineBoxDirty(); }
+ void setAncestorLineBoxDirty(bool value = true)
{
- if (b) {
- if (!s_ancestorLineboxDirtySet)
- s_ancestorLineboxDirtySet = new RenderObjectAncestorLineboxDirtySet;
- s_ancestorLineboxDirtySet->add(this);
+ m_bitfields.setAncestorLineBoxDirty(value);
+ if (value)
setNeedsLayout();
- } else if (s_ancestorLineboxDirtySet) {
- s_ancestorLineboxDirtySet->remove(this);
- if (s_ancestorLineboxDirtySet->isEmpty()) {
- delete s_ancestorLineboxDirtySet;
- s_ancestorLineboxDirtySet = 0;
- }
- }
}
enum FlowThreadState {
@@ -439,8 +427,6 @@ public:
FlowThreadState flowThreadState() const { return m_bitfields.flowThreadState(); }
void setFlowThreadState(FlowThreadState state) { m_bitfields.setFlowThreadState(state); }
- virtual bool requiresForcedStyleRecalcPropagation() const { return false; }
-
// FIXME: Until all SVG renders can be subclasses of RenderSVGModelObject we have
// to add SVG renderer methods to RenderObject with an ASSERT_NOT_REACHED() default implementation.
virtual bool isSVGRoot() const { return false; }
@@ -461,8 +447,6 @@ public:
virtual bool isSVGResourceFilter() const { return false; }
virtual bool isSVGResourceFilterPrimitive() const { return false; }
- virtual RenderSVGResourceContainer* toRenderSVGResourceContainer();
-
// FIXME: Those belong into a SVG specific base-class for all renderers (see above)
// Unfortunately we don't have such a class yet, because it's not possible for all renderers
// to inherit from RenderSVGObject -> RenderObject (some need RenderBlock inheritance for instance)
@@ -518,7 +502,6 @@ public:
bool isAnonymousColumnSpanBlock() const { return style()->columnSpan() && isAnonymousBlock(); }
bool isElementContinuation() const { return node() && node()->renderer() != this; }
bool isInlineElementContinuation() const { return isElementContinuation() && isInline(); }
- bool isBlockElementContinuation() const { return isElementContinuation() && !isInline(); }
virtual RenderBoxModelObject* virtualContinuation() const { return 0; }
bool isFloating() const { return m_bitfields.floating(); }
@@ -532,7 +515,6 @@ public:
bool isText() const { return m_bitfields.isText(); }
bool isBox() const { return m_bitfields.isBox(); }
bool isInline() const { return m_bitfields.isInline(); } // inline object
- bool isRunIn() const { return style()->display() == RUN_IN; } // run-in object
bool isDragging() const { return m_bitfields.isDragging(); }
bool isReplaced() const { return m_bitfields.isReplaced(); } // a "replaced" element (see CSS)
bool isHorizontalWritingMode() const { return m_bitfields.horizontalWritingMode(); }
@@ -602,7 +584,11 @@ public:
// Returns true if this renderer is rooted, and optionally returns the hosting view (the root of the hierarchy).
bool isRooted(RenderView** = 0) const;
- Node* node() const { return isAnonymous() ? 0 : m_nodeProxy.unsafeNode(); }
+ Node* node() const
+ {
+ return isAnonymous() ? 0 : m_node;
+ }
+
Node* nonPseudoNode() const
{
ASSERT(!LayoutIndicator::inLayout());
@@ -610,14 +596,14 @@ public:
}
// FIXME: Why does RenderWidget need this?
- void clearNode() { m_nodeProxy.clear(); }
+ void clearNode() { m_node = 0; }
// Returns the styled node that caused the generation of this renderer.
// This is the same as node() except for renderers of :before and :after
// pseudo elements for which their parent node is returned.
Node* generatingNode() const { return isPseudoElement() ? node()->parentOrShadowHostNode() : node(); }
- Document& document() const { return m_nodeProxy.unsafeNode()->document(); }
+ Document& document() const { return m_node->document(); }
Frame* frame() const { return document().frame(); }
bool hasOutlineAnnotation() const;
@@ -655,21 +641,21 @@ public:
}
void clearPositionedState() { m_bitfields.clearPositionedState(); }
- void setFloating(bool b = true) { m_bitfields.setFloating(b); }
- void setInline(bool b = true) { m_bitfields.setIsInline(b); }
+ void setFloating(bool isFloating) { m_bitfields.setFloating(isFloating); }
+ void setInline(bool isInline) { m_bitfields.setIsInline(isInline); }
- void setHasBoxDecorations(bool = true);
+ void setHasBoxDecorations(bool);
void invalidateBackgroundObscurationStatus();
virtual bool computeBackgroundIsKnownToBeObscured() { return false; }
void setIsText() { m_bitfields.setIsText(true); }
void setIsBox() { m_bitfields.setIsBox(true); }
- void setReplaced(bool b = true) { m_bitfields.setIsReplaced(b); }
- void setHorizontalWritingMode(bool b = true) { m_bitfields.setHorizontalWritingMode(b); }
- void setHasOverflowClip(bool b = true) { m_bitfields.setHasOverflowClip(b); }
- void setHasLayer(bool b = true) { m_bitfields.setHasLayer(b); }
- void setHasTransform(bool b = true) { m_bitfields.setHasTransform(b); }
- void setHasReflection(bool b = true) { m_bitfields.setHasReflection(b); }
+ void setReplaced(bool isReplaced) { m_bitfields.setIsReplaced(isReplaced); }
+ void setHorizontalWritingMode(bool hasHorizontalWritingMode) { m_bitfields.setHorizontalWritingMode(hasHorizontalWritingMode); }
+ void setHasOverflowClip(bool hasOverflowClip) { m_bitfields.setHasOverflowClip(hasOverflowClip); }
+ void setHasLayer(bool hasLayer) { m_bitfields.setHasLayer(hasLayer); }
+ void setHasTransform(bool hasTransform) { m_bitfields.setHasTransform(hasTransform); }
+ void setHasReflection(bool hasReflection) { m_bitfields.setHasReflection(hasReflection); }
void scheduleRelayout();
@@ -681,6 +667,8 @@ public:
// Recursive function that computes the size and position of this object and all its descendants.
virtual void layout();
+ virtual void didLayout(ResourceLoadPriorityOptimizer&);
+ virtual void didScroll(ResourceLoadPriorityOptimizer&);
/* This function performs a layout only if one is needed. */
void layoutIfNeeded() { if (needsLayout()) layout(); }
@@ -698,12 +686,7 @@ public:
virtual void addAnnotatedRegions(Vector<AnnotatedRegionValue>&);
void collectAnnotatedRegions(Vector<AnnotatedRegionValue>&);
- bool isComposited() const;
-
- // FIXME: This should be moved to RenderBox once the scrolling code
- // has been completely separated from RenderLayer and made to assume
- // it talks to a RenderBox, not just a RenderObject.
- bool canResize() const;
+ CompositingState compositingState() const;
bool hitTest(const HitTestRequest&, HitTestResult&, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestFilter = HitTestAll);
virtual void updateHitTestResult(HitTestResult&, const LayoutPoint&);
@@ -721,7 +704,7 @@ public:
void setAnimatableStyle(PassRefPtr<RenderStyle>);
// Set the style of the object and update the state of the object accordingly.
- virtual void setStyle(PassRefPtr<RenderStyle>);
+ void setStyle(PassRefPtr<RenderStyle>);
// Set the style of the object if it's generated content.
void setPseudoStyle(PassRefPtr<RenderStyle>);
@@ -737,6 +720,10 @@ public:
{
return isRenderView() || (hasTransform() && isRenderBlock()) || isSVGForeignObject() || isOutOfFlowRenderFlowThread();
}
+ bool canContainAbsolutePositionObjects() const
+ {
+ return isRenderView() || (hasTransform() && isRenderBlock()) || isSVGForeignObject();
+ }
// Convert the given local point to absolute coordinates
// FIXME: Temporary. If UseTransforms is true, take transforms into account. Eventually localToAbsolute() will always be transform-aware.
@@ -767,6 +754,8 @@ public:
IntRect absoluteBoundingBoxRect(bool useTransform = true) const;
IntRect absoluteBoundingBoxRectIgnoringTransforms() const { return absoluteBoundingBoxRect(false); }
+ bool isContainedInParentBoundingBox() const;
+
// Build an array of quads in absolute coords for line boxes
virtual void absoluteQuads(Vector<FloatQuad>&, bool* /*wasFixed*/ = 0) const { }
@@ -815,7 +804,7 @@ public:
virtual CursorDirective getCursor(const LayoutPoint&, Cursor&) const;
- void getTextDecorationColors(int decorations, Color& underline, Color& overline, Color& linethrough, bool quirksMode = false, bool firstlineStyle = false);
+ void getTextDecorationColors(unsigned decorations, Color& underline, Color& overline, Color& linethrough, bool quirksMode = false, bool firstlineStyle = false);
// Return the RenderLayerModelObject in the container chain which is responsible for painting this object, or 0
// if painting is root-relative. This is the container that should be passed to the 'forRepaint'
@@ -833,7 +822,10 @@ public:
void repaintRectangle(const LayoutRect&) const;
// Repaint only if our old bounds and new bounds are different. The caller may pass in newBounds and newOutlineBox if they are known.
- bool repaintAfterLayoutIfNeeded(const RenderLayerModelObject* repaintContainer, const LayoutRect& oldBounds, const LayoutRect& oldOutlineBox, const LayoutRect* newBoundsPtr = 0, const LayoutRect* newOutlineBoxPtr = 0);
+ bool repaintAfterLayoutIfNeeded(const RenderLayerModelObject* repaintContainer, bool wasSelfLayout,
+ const LayoutRect& oldBounds, const LayoutRect& oldOutlineBox, const LayoutRect* newBoundsPtr = 0, const LayoutRect* newOutlineBoxPtr = 0);
+
+ virtual void repaintOverflow();
bool checkForRepaintDuringLayout() const;
@@ -849,12 +841,6 @@ public:
virtual LayoutRect outlineBoundsForRepaint(const RenderLayerModelObject* /*repaintContainer*/, const RenderGeometryMap* = 0) const { return LayoutRect(); }
// Given a rect in the object's coordinate space, compute a rect suitable for repainting
- // that rect in view coordinates.
- void computeAbsoluteRepaintRect(LayoutRect& r, bool fixed = false) const
- {
- computeRectForRepaint(0, r, fixed);
- }
- // Given a rect in the object's coordinate space, compute a rect suitable for repainting
// that rect in the coordinate space of repaintContainer.
virtual void computeRectForRepaint(const RenderLayerModelObject* repaintContainer, LayoutRect&, bool fixed = false) const;
virtual void computeFloatRectForRepaint(const RenderLayerModelObject* repaintContainer, FloatRect& repaintRect, bool fixed = false) const;
@@ -921,7 +907,7 @@ public:
*/
virtual LayoutRect localCaretRect(InlineBox*, int caretOffset, LayoutUnit* extraWidthToEndOfLine = 0);
- // When performing a global document tear-down, the renderer of the document is cleared. We use this
+ // When performing a global document tear-down, the renderer of the document is cleared. We use this
// as a hook to detect the case of document destruction and don't waste time doing unnecessary work.
bool documentBeingDestroyed() const;
@@ -957,7 +943,7 @@ public:
void remove() { if (parent()) parent()->removeChild(this); }
- AnimationController* animation() const;
+ AnimationController& animation() const;
bool isInert() const;
bool visibleToHitTestRequest(const HitTestRequest& request) const { return style()->visibility() == VISIBLE && (request.ignorePointerEventsNone() || style()->pointerEvents() != PE_NONE) && !isInert(); }
@@ -975,7 +961,6 @@ public:
bool shouldUseTransformFromContainer(const RenderObject* container) const;
void getTransformFromContainer(const RenderObject* container, const LayoutSize& offsetInContainer, TransformationMatrix&) const;
- // return true if this object requires a new stacking context
bool createsGroup() const { return isTransparent() || hasMask() || hasFilter() || hasBlendMode(); }
virtual void addFocusRingRects(Vector<IntRect>&, const LayoutPoint& /* additionalOffset */, const RenderLayerModelObject* /* paintContainer */ = 0) { };
@@ -993,6 +978,33 @@ public:
RespectImageOrientationEnum shouldRespectImageOrientation() const;
+ bool isRelayoutBoundaryForInspector() const;
+
+ const LayoutRect& newRepaintRect() const { return m_newRepaintRect; }
+ void setNewRepaintRect(const LayoutRect& rect) { m_newRepaintRect = rect; }
+
+ const LayoutRect& oldRepaintRect() const { return m_oldRepaintRect; }
+ void setOldRepaintRect(const LayoutRect& rect) { m_oldRepaintRect = rect; }
+
+ bool shouldDoFullRepaintAfterLayout() const { return m_bitfields.shouldDoFullRepaintAfterLayout(); }
+ void setShouldDoFullRepaintAfterLayout(bool b) { m_bitfields.setShouldDoFullRepaintAfterLayout(b); }
+ bool shouldRepaintOverflowIfNeeded() const { return m_bitfields.shouldRepaintOverflowIfNeeded(); }
+
+ void clearRepaintRects()
+ {
+ setNewRepaintRect(LayoutRect());
+ setOldRepaintRect(LayoutRect());
+
+ setShouldDoFullRepaintAfterLayout(false);
+ setShouldRepaintOverflowIfNeeded(false);
+ setLayoutDidGetCalled(false);
+ }
+
+ // layoutDidGetCalled indicates whether this render object was re-laid-out
+ // since the last call to setLayoutDidGetCalled(false) on this object.
+ bool layoutDidGetCalled() { return m_bitfields.layoutDidGetCalled(); }
+ void setLayoutDidGetCalled(bool b) { m_bitfields.setLayoutDidGetCalled(b); }
+
protected:
inline bool layerCreationAllowedForSubtree() const;
@@ -1004,6 +1016,14 @@ protected:
void drawLineForBoxSide(GraphicsContext*, int x1, int y1, int x2, int y2, BoxSide,
Color, EBorderStyle, int adjbw1, int adjbw2, bool antialias = false);
+ void drawDashedOrDottedBoxSide(GraphicsContext*, int x1, int y1, int x2, int y2,
+ BoxSide, Color, int thickness, EBorderStyle, bool antialias);
+ void drawDoubleBoxSide(GraphicsContext*, int x1, int y1, int x2, int y2,
+ int length, BoxSide, Color, int thickness, int adjacentWidth1, int adjacentWidth2, bool antialias);
+ void drawRidgeOrGrooveBoxSide(GraphicsContext*, int x1, int y1, int x2, int y2,
+ BoxSide, Color, EBorderStyle, int adjacentWidth1, int adjacentWidth2, bool antialias);
+ void drawSolidBoxSide(GraphicsContext*, int x1, int y1, int x2, int y2,
+ BoxSide, Color, int adjacentWidth1, int adjacentWidth2, bool antialias);
void paintFocusRing(PaintInfo&, const LayoutPoint&, RenderStyle*);
void paintOutline(PaintInfo&, const LayoutRect&);
@@ -1017,12 +1037,10 @@ protected:
virtual void willBeDestroyed();
void postDestroy();
- virtual bool canBeReplacedWithInlineRunIn() const;
-
virtual void insertedIntoTree();
virtual void willBeRemovedFromTree();
- void setDocumentForAnonymous(Document* document) { ASSERT(isAnonymous()); m_nodeProxy.set(document); }
+ void setDocumentForAnonymous(Document* document) { ASSERT(isAnonymous()); m_node = document; }
// Add hit-test rects for the render tree rooted at this node to the provided collection on a
// per-RenderLayer basis.
@@ -1039,12 +1057,14 @@ protected:
virtual void computeSelfHitTestRects(Vector<LayoutRect>&, const LayoutPoint& layerOffset) const { };
private:
+ RenderBlock* containerForFixedPosition(const RenderLayerModelObject* repaintContainer = 0, bool* repaintContainerSkipped = 0) const;
+
RenderFlowThread* locateFlowThreadContainingBlock() const;
void removeFromRenderFlowThread();
void removeFromRenderFlowThreadRecursive(RenderFlowThread*);
bool shouldRepaintForStyleDifference(StyleDifference) const;
- bool hasImmediateNonWhitespaceTextChild() const;
+ bool hasImmediateNonWhitespaceTextChildOrPropertiesDependentOnColor() const;
RenderStyle* cachedFirstLineStyle() const;
StyleDifference adjustStyleDifference(StyleDifference, unsigned contextSensitiveProperties) const;
@@ -1060,14 +1080,12 @@ private:
RefPtr<RenderStyle> m_style;
- RenderingNodeProxy m_nodeProxy;
+ Node* m_node;
RenderObject* m_parent;
RenderObject* m_previous;
RenderObject* m_next;
- static RenderObjectAncestorLineboxDirtySet* s_ancestorLineboxDirtySet;
-
#ifndef NDEBUG
unsigned m_hasAXObject : 1;
unsigned m_setNeedsLayoutForbidden : 1;
@@ -1091,6 +1109,12 @@ private:
public:
RenderObjectBitfields(Node* node)
: m_selfNeedsLayout(false)
+ // FIXME: shouldDoFullRepaintAfterLayout is needed because we reset
+ // the layout bits before repaint when doing repaintAfterLayout.
+ // Holding the layout bits until after repaint would remove the need
+ // for this flag.
+ , m_shouldDoFullRepaintAfterLayout(false)
+ , m_shouldRepaintOverflowIfNeeded(false)
, m_needsPositionedMovementLayout(false)
, m_normalChildNeedsLayout(false)
, m_posChildNeedsLayout(false)
@@ -1110,8 +1134,10 @@ private:
, m_hasReflection(false)
, m_hasCounterNodeMap(false)
, m_everHadLayout(false)
+ , m_ancestorLineBoxDirty(false)
, m_childrenInline(false)
, m_hasColumns(false)
+ , m_layoutDidGetCalled(false)
, m_positionedState(IsStaticallyPositioned)
, m_selectionState(SelectionNone)
, m_flowThreadState(NotInsideFlowThread)
@@ -1119,8 +1145,10 @@ private:
{
}
- // 31 bits have been used here. There is one bit available.
+ // 32 bits have been used in the first word, and 2 in the second.
ADD_BOOLEAN_BITFIELD(selfNeedsLayout, SelfNeedsLayout);
+ ADD_BOOLEAN_BITFIELD(shouldDoFullRepaintAfterLayout, ShouldDoFullRepaintAfterLayout);
+ ADD_BOOLEAN_BITFIELD(shouldRepaintOverflowIfNeeded, ShouldRepaintOverflowIfNeeded);
ADD_BOOLEAN_BITFIELD(needsPositionedMovementLayout, NeedsPositionedMovementLayout);
ADD_BOOLEAN_BITFIELD(normalChildNeedsLayout, NormalChildNeedsLayout);
ADD_BOOLEAN_BITFIELD(posChildNeedsLayout, PosChildNeedsLayout);
@@ -1143,11 +1171,14 @@ private:
ADD_BOOLEAN_BITFIELD(hasCounterNodeMap, HasCounterNodeMap);
ADD_BOOLEAN_BITFIELD(everHadLayout, EverHadLayout);
+ ADD_BOOLEAN_BITFIELD(ancestorLineBoxDirty, AncestorLineBoxDirty);
// from RenderBlock
ADD_BOOLEAN_BITFIELD(childrenInline, ChildrenInline);
ADD_BOOLEAN_BITFIELD(hasColumns, HasColumns);
+ ADD_BOOLEAN_BITFIELD(layoutDidGetCalled, LayoutDidGetCalled);
+
private:
unsigned m_positionedState : 2; // PositionedState
unsigned m_selectionState : 3; // SelectionState
@@ -1188,10 +1219,14 @@ private:
void setNeedsSimplifiedNormalFlowLayout(bool b) { m_bitfields.setNeedsSimplifiedNormalFlowLayout(b); }
void setIsDragging(bool b) { m_bitfields.setIsDragging(b); }
void setEverHadLayout(bool b) { m_bitfields.setEverHadLayout(b); }
+ void setShouldRepaintOverflowIfNeeded(bool b) { m_bitfields.setShouldRepaintOverflowIfNeeded(b); }
private:
// Store state between styleWillChange and styleDidChange
static bool s_affectsParentBlock;
+
+ LayoutRect m_oldRepaintRect;
+ LayoutRect m_newRepaintRect;
};
inline bool RenderObject::documentBeingDestroyed() const
@@ -1357,25 +1392,29 @@ inline int adjustForAbsoluteZoom(int value, RenderObject* renderer)
return adjustForAbsoluteZoom(value, renderer->style());
}
-inline LayoutUnit adjustLayoutUnitForAbsoluteZoom(LayoutUnit value, RenderObject* renderer)
+inline LayoutUnit adjustLayoutUnitForAbsoluteZoom(LayoutUnit value, RenderObject& renderer)
{
- return adjustLayoutUnitForAbsoluteZoom(value, renderer->style());
+ ASSERT(renderer.style());
+ return adjustLayoutUnitForAbsoluteZoom(value, *renderer.style());
}
-inline void adjustFloatQuadForAbsoluteZoom(FloatQuad& quad, RenderObject* renderer)
+inline void adjustFloatQuadForAbsoluteZoom(FloatQuad& quad, RenderObject& renderer)
{
- float zoom = renderer->style()->effectiveZoom();
+ float zoom = renderer.style()->effectiveZoom();
if (zoom != 1)
quad.scale(1 / zoom, 1 / zoom);
}
-inline void adjustFloatRectForAbsoluteZoom(FloatRect& rect, RenderObject* renderer)
+inline void adjustFloatRectForAbsoluteZoom(FloatRect& rect, RenderObject& renderer)
{
- float zoom = renderer->style()->effectiveZoom();
+ float zoom = renderer.style()->effectiveZoom();
if (zoom != 1)
rect.scale(1 / zoom, 1 / zoom);
}
+#define DEFINE_RENDER_OBJECT_TYPE_CASTS(thisType, predicate) \
+ DEFINE_TYPE_CASTS(thisType, RenderObject, object, object->predicate, object.predicate)
+
} // namespace WebCore
#ifndef NDEBUG
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderObjectChildList.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderObjectChildList.cpp
index ebb86f7eeb6..80cee464c7d 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderObjectChildList.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderObjectChildList.cpp
@@ -38,12 +38,8 @@ namespace WebCore {
void RenderObjectChildList::destroyLeftoverChildren()
{
while (firstChild()) {
- if (firstChild()->isListMarker() || (firstChild()->style()->styleType() == FIRST_LETTER && !firstChild()->isText()))
+ if (firstChild()->isListMarker() || (firstChild()->style()->styleType() == FIRST_LETTER && !firstChild()->isText())) {
firstChild()->remove(); // List markers are owned by their enclosing list and so don't get destroyed by this container. Similarly, first letters are destroyed by their remaining text fragment.
- else if (firstChild()->isRunIn() && firstChild()->node()) {
- firstChild()->node()->setRenderer(0);
- firstChild()->node()->setNeedsStyleRecalc();
- firstChild()->destroy();
} else {
// Destroy any anonymous children remaining in the render tree, as well as implicit (shadow) DOM elements like those used in the engine-based text fields.
if (firstChild()->node())
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderOverflow.h b/chromium/third_party/WebKit/Source/core/rendering/RenderOverflow.h
index 49ad02a0141..2a965c7037a 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderOverflow.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderOverflow.h
@@ -21,7 +21,7 @@
#ifndef RenderOverflow_h
#define RenderOverflow_h
-#include "core/platform/graphics/LayoutRect.h"
+#include "platform/geometry/LayoutRect.h"
namespace WebCore
{
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderOverflowTest.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderOverflowTest.cpp
index 0a5b7c3901e..d46aa35c69a 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderOverflowTest.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderOverflowTest.cpp
@@ -31,7 +31,7 @@
#include "config.h"
#include "core/rendering/RenderOverflow.h"
-#include "core/platform/graphics/LayoutRect.h"
+#include "platform/geometry/LayoutRect.h"
#include <gtest/gtest.h>
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderPart.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderPart.cpp
index 4670fc7b4f7..c0cbf957881 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderPart.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderPart.cpp
@@ -25,8 +25,9 @@
#include "config.h"
#include "core/rendering/RenderPart.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
#include "core/html/HTMLFrameElementBase.h"
-#include "core/page/FrameView.h"
#include "core/plugins/PluginView.h"
#include "core/rendering/HitTestResult.h"
#include "core/rendering/RenderLayer.h"
@@ -85,6 +86,9 @@ bool RenderPart::requiresAcceleratedCompositing() const
return false;
HTMLFrameOwnerElement* element = toHTMLFrameOwnerElement(node());
+ if (element->contentFrame() && element->contentFrame()->remotePlatformLayer())
+ return true;
+
if (Document* contentDocument = element->contentDocument()) {
if (RenderView* view = contentDocument->renderView())
return view->usesCompositing();
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderPart.h b/chromium/third_party/WebKit/Source/core/rendering/RenderPart.h
index 78b8e30cfab..f26a7e242c5 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderPart.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderPart.h
@@ -51,14 +51,7 @@ private:
virtual const char* renderName() const { return "RenderPart"; }
};
-inline RenderPart* toRenderPart(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isRenderPart());
- return static_cast<RenderPart*>(object);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toRenderPart(const RenderPart*);
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderPart, isRenderPart());
}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderProgress.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderProgress.cpp
index 1454d3cae34..9bf99a86a3d 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderProgress.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderProgress.cpp
@@ -58,11 +58,6 @@ void RenderProgress::updateFromElement()
RenderBlock::updateFromElement();
}
-bool RenderProgress::canBeReplacedWithInlineRunIn() const
-{
- return false;
-}
-
double RenderProgress::animationProgress() const
{
return m_animating ? (fmod((currentTime() - m_animationStartTime), m_animationDuration) / m_animationDuration) : 0;
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderProgress.h b/chromium/third_party/WebKit/Source/core/rendering/RenderProgress.h
index aa7a052fc09..bd1cac97f15 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderProgress.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderProgress.h
@@ -44,9 +44,7 @@ public:
private:
virtual const char* renderName() const { return "RenderProgress"; }
virtual bool isProgress() const { return true; }
- virtual bool requiresForcedStyleRecalcPropagation() const { return true; }
virtual bool supportsPartialLayout() const OVERRIDE { return false; }
- virtual bool canBeReplacedWithInlineRunIn() const OVERRIDE;
void animationTimerFired(Timer<RenderProgress>*);
void updateAnimationState();
@@ -59,14 +57,7 @@ private:
Timer<RenderProgress> m_animationTimer;
};
-inline RenderProgress* toRenderProgress(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isProgress());
- return static_cast<RenderProgress*>(object);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toRenderProgress(const RenderProgress*);
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderProgress, isProgress());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderQuote.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderQuote.cpp
index d6e308e9c54..6891671752c 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderQuote.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderQuote.cpp
@@ -251,7 +251,7 @@ const QuotesData* quotesDataForLanguage(const AtomicString& lang)
static const QuotesData* basicQuotesData()
{
// FIXME: The default quotes should be the fancy quotes for "en".
- static QuotesData* staticBasicQuotes = QuotesData::create('"', '"', '\'', '\'').leakRef();
+ DEFINE_STATIC_REF(QuotesData, staticBasicQuotes, (QuotesData::create('"', '"', '\'', '\'')));
return staticBasicQuotes;
}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderQuote.h b/chromium/third_party/WebKit/Source/core/rendering/RenderQuote.h
index 3fc0e47f127..47218e47991 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderQuote.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderQuote.h
@@ -60,14 +60,7 @@ private:
String m_text;
};
-inline RenderQuote* toRenderQuote(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isQuote());
- return static_cast<RenderQuote*>(object);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toRenderQuote(const RenderQuote*);
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderQuote, isQuote());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderRegion.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderRegion.cpp
index 680a98cd806..0614d3aade2 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderRegion.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderRegion.cpp
@@ -32,6 +32,7 @@
#include "core/css/resolver/StyleResolver.h"
#include "core/rendering/FlowThreadController.h"
+#include "core/rendering/HitTestLocation.h"
#include "core/rendering/PaintInfo.h"
#include "core/rendering/RenderBoxRegionInfo.h"
#include "core/rendering/RenderNamedFlowThread.h"
@@ -74,7 +75,7 @@ LayoutUnit RenderRegion::maxPageLogicalHeight() const
{
ASSERT(m_flowThread);
ASSERT(hasAutoLogicalHeight() && !m_flowThread->inConstrainedLayoutPhase());
- return style()->logicalMaxHeight().isUndefined() ? LayoutUnit::max() / 2 : computeReplacedLogicalHeightUsing(style()->logicalMaxHeight());
+ return style()->logicalMaxHeight().isUndefined() ? RenderFlowThread::maxLogicalHeight() : computeReplacedLogicalHeightUsing(style()->logicalMaxHeight());
}
LayoutUnit RenderRegion::logicalHeightOfAllFlowThreadContent() const
@@ -96,12 +97,8 @@ LayoutRect RenderRegion::overflowRectForFlowThreadPortion(const LayoutRect& flow
{
ASSERT(isValid());
- // FIXME: Would like to just use hasOverflowClip() but we aren't a block yet. When RenderRegion is eliminated and
- // folded into RenderBlock, switch to hasOverflowClip().
- bool clipX = style()->overflowX() != OVISIBLE;
- bool clipY = style()->overflowY() != OVISIBLE;
bool isLastRegionWithRegionFragmentBreak = (isLastPortion && (style()->regionFragment() == BreakRegionFragment));
- if ((clipX && clipY) || isLastRegionWithRegionFragmentBreak)
+ if (hasOverflowClip() || isLastRegionWithRegionFragmentBreak)
return flowThreadPortionRect;
LayoutRect flowThreadOverflow = m_flowThread->visualOverflowRect();
@@ -112,12 +109,14 @@ LayoutRect RenderRegion::overflowRectForFlowThreadPortion(const LayoutRect& flow
if (m_flowThread->isHorizontalWritingMode()) {
LayoutUnit minY = isFirstPortion ? (flowThreadOverflow.y() - outlineSize) : flowThreadPortionRect.y();
LayoutUnit maxY = isLastPortion ? max(flowThreadPortionRect.maxY(), flowThreadOverflow.maxY()) + outlineSize : flowThreadPortionRect.maxY();
+ bool clipX = style()->overflowX() != OVISIBLE;
LayoutUnit minX = clipX ? flowThreadPortionRect.x() : min(flowThreadPortionRect.x(), flowThreadOverflow.x() - outlineSize);
LayoutUnit maxX = clipX ? flowThreadPortionRect.maxX() : max(flowThreadPortionRect.maxX(), (flowThreadOverflow.maxX() + outlineSize));
clipRect = LayoutRect(minX, minY, maxX - minX, maxY - minY);
} else {
LayoutUnit minX = isFirstPortion ? (flowThreadOverflow.x() - outlineSize) : flowThreadPortionRect.x();
LayoutUnit maxX = isLastPortion ? max(flowThreadPortionRect.maxX(), flowThreadOverflow.maxX()) + outlineSize : flowThreadPortionRect.maxX();
+ bool clipY = style()->overflowY() != OVISIBLE;
LayoutUnit minY = clipY ? flowThreadPortionRect.y() : min(flowThreadPortionRect.y(), (flowThreadOverflow.y() - outlineSize));
LayoutUnit maxY = clipY ? flowThreadPortionRect.maxY() : max(flowThreadPortionRect.y(), (flowThreadOverflow.maxY() + outlineSize));
clipRect = LayoutRect(minX, minY, maxX - minX, maxY - minY);
@@ -142,8 +141,8 @@ void RenderRegion::setRegionOversetState(RegionOversetState state)
Element* RenderRegion::element() const
{
- ASSERT(node() && node()->isElementNode());
- return toElement(node());
+ ASSERT(nodeForRegion() && nodeForRegion()->isElementNode());
+ return toElement(nodeForRegion());
}
LayoutUnit RenderRegion::pageLogicalTopForOffset(LayoutUnit /* offset */) const
@@ -165,6 +164,13 @@ bool RenderRegion::isLastRegion() const
return m_flowThread->lastRegion() == this;
}
+static bool shouldPaintRegionContentsInPhase(PaintPhase phase)
+{
+ return phase == PaintPhaseForeground
+ || phase == PaintPhaseSelection
+ || phase == PaintPhaseTextClip;
+}
+
void RenderRegion::paintObject(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
{
if (style()->visibility() != VISIBLE)
@@ -172,11 +178,14 @@ void RenderRegion::paintObject(PaintInfo& paintInfo, const LayoutPoint& paintOff
RenderBlock::paintObject(paintInfo, paintOffset);
+ if (!isValid())
+ return;
+
// Delegate painting of content in region to RenderFlowThread.
// RenderFlowThread is a self painting layer (being a positioned object) who is painting its children, the collected objects.
// Since we do not want to paint the flow thread content multiple times (for each painting phase of the region object),
- // we allow the flow thread painting only for the selection and the foreground phase.
- if (!isValid() || (paintInfo.phase != PaintPhaseForeground && paintInfo.phase != PaintPhaseSelection))
+ // we allow the flow thread painting only in certain phases.
+ if (!shouldPaintRegionContentsInPhase(paintInfo.phase))
return;
setRegionObjectsRegionStyle();
@@ -207,10 +216,9 @@ void RenderRegion::checkRegionStyle()
bool customRegionStyle = false;
// FIXME: Region styling doesn't work for pseudo elements.
- if (node()) {
- Element* regionElement = toElement(node());
- customRegionStyle = view()->document().styleResolver()->checkRegionStyle(regionElement);
- }
+ if (isElementBasedRegion())
+ customRegionStyle = view()->document().ensureStyleResolver().checkRegionStyle(this->element());
+
setHasCustomRegionStyle(customRegionStyle);
m_flowThread->checkRegionsWithStyling();
}
@@ -240,9 +248,9 @@ void RenderRegion::updateRegionHasAutoLogicalHeightFlag()
bool didHaveAutoLogicalHeight = m_hasAutoLogicalHeight;
m_hasAutoLogicalHeight = shouldHaveAutoLogicalHeight();
if (m_hasAutoLogicalHeight != didHaveAutoLogicalHeight) {
- if (m_hasAutoLogicalHeight)
+ if (m_hasAutoLogicalHeight) {
incrementAutoLogicalHeightCount();
- else {
+ } else {
clearComputedAutoHeight();
decrementAutoLogicalHeightCount();
}
@@ -292,9 +300,10 @@ void RenderRegion::layoutBlock(bool relayoutChildren, LayoutUnit)
return;
}
- if (!isRenderRegionSet() && (oldRegionRect.width() != pageLogicalWidth() || oldRegionRect.height() != pageLogicalHeight()))
+ if (!isRenderRegionSet() && (oldRegionRect.width() != pageLogicalWidth() || oldRegionRect.height() != pageLogicalHeight())) {
// This can happen even if we are in the inConstrainedLayoutPhase and it will trigger a pathological layout of the flow thread.
m_flowThread->invalidateRegions();
+ }
}
// FIXME: We need to find a way to set up overflow properly. Our flow thread hasn't gotten a layout
@@ -480,8 +489,9 @@ void RenderRegion::setRegionObjectsRegionStyle()
objectStyleInRegion = it->value.style;
ASSERT(it->value.cached);
objectRegionStyleCached = true;
- } else
+ } else {
objectStyleInRegion = computeStyleInRegion(object);
+ }
setObjectStyleInRegion(object, objectStyleInRegion, objectRegionStyleCached);
@@ -543,7 +553,7 @@ PassRefPtr<RenderStyle> RenderRegion::computeStyleInRegion(const RenderObject* o
// FIXME: Region styling fails for pseudo-elements because the renderers don't have a node.
Element* element = toElement(object->node());
- RefPtr<RenderStyle> renderObjectRegionStyle = object->view()->document().styleResolver()->styleForElement(element, 0, DisallowStyleSharing, MatchAllRules, this);
+ RefPtr<RenderStyle> renderObjectRegionStyle = object->view()->document().ensureStyleResolver().styleForElement(element, 0, DisallowStyleSharing, MatchAllRules, this);
return renderObjectRegionStyle.release();
}
@@ -646,9 +656,33 @@ void RenderRegion::updateLogicalHeight()
LayoutUnit autoHeight = hasOverrideHeight() ? overrideLogicalContentHeight() : computedAutoHeight();
LayoutUnit newLogicalHeight = autoHeight + borderAndPaddingLogicalHeight();
- ASSERT(newLogicalHeight < LayoutUnit::max() / 2);
- if (newLogicalHeight > logicalHeight())
+ ASSERT(newLogicalHeight < RenderFlowThread::maxLogicalHeight());
+ if (newLogicalHeight > logicalHeight()) {
setLogicalHeight(newLogicalHeight);
+ // Recalculate position of the render block after new logical height is set.
+ // (needed in absolute positioning case with bottom alignment for example)
+ RenderBlock::updateLogicalHeight();
+ }
+}
+
+Node* RenderRegion::nodeForRegion() const
+{
+ if (parent() && isRenderNamedFlowFragment())
+ return parent()->node();
+ return node();
+}
+
+Node* RenderRegion::generatingNodeForRegion() const
+{
+ if (parent() && isRenderNamedFlowFragment())
+ return parent()->generatingNode();
+ return generatingNode();
+}
+
+bool RenderRegion::isElementBasedRegion() const
+{
+ Node* node = nodeForRegion();
+ return node && node->isElementNode() && !node->isPseudoElement();
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderRegion.h b/chromium/third_party/WebKit/Source/core/rendering/RenderRegion.h
index 2d9988d76d6..c05d61359b2 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderRegion.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderRegion.h
@@ -46,11 +46,11 @@ class RenderRegion : public RenderBlockFlow {
public:
explicit RenderRegion(Element*, RenderFlowThread*);
- virtual bool isRenderRegion() const { return true; }
+ virtual bool isRenderRegion() const OVERRIDE { return true; }
bool hitTestFlowThreadContents(const HitTestRequest&, HitTestResult&, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction);
- virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle);
+ virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle) OVERRIDE;
void setFlowThreadPortionRect(const LayoutRect& rect) { m_flowThreadPortionRect = rect; }
LayoutRect flowThreadPortionRect() const { return m_flowThreadPortionRect; }
@@ -85,14 +85,12 @@ public:
RegionOversetState regionOversetState() const;
void setRegionOversetState(RegionOversetState);
- Element* element() const;
-
// These methods represent the width and height of a "page" and for a RenderRegion they are just the
// content width and content height of a region. For RenderRegionSets, however, they will be the width and
// height of a single column or page in the set.
virtual LayoutUnit pageLogicalWidth() const;
virtual LayoutUnit pageLogicalHeight() const;
- LayoutUnit maxPageLogicalHeight() const;
+ virtual LayoutUnit maxPageLogicalHeight() const;
LayoutUnit logicalTopOfFlowThreadContentRect(const LayoutRect&) const;
LayoutUnit logicalBottomOfFlowThreadContentRect(const LayoutRect&) const;
@@ -127,8 +125,6 @@ public:
bool hasComputedAutoHeight() const { return (m_computedAutoHeight >= 0); }
- virtual void updateLogicalHeight() OVERRIDE;
-
// The top of the nearest page inside the region. For RenderRegions, this is just the logical top of the
// flow thread portion we contain. For sets, we have to figure out the top of the nearest column or
// page.
@@ -143,6 +139,16 @@ public:
virtual void collectLayerFragments(LayerFragments&, const LayoutRect&, const LayoutRect&) { }
+ virtual bool canHaveChildren() const OVERRIDE { return false; }
+ virtual bool canHaveGeneratedChildren() const OVERRIDE { return true; }
+
+ bool isElementBasedRegion() const;
+
+ Node* nodeForRegion() const;
+ Node* generatingNodeForRegion() const;
+
+ virtual const char* renderName() const OVERRIDE { return "RenderRegion"; }
+
protected:
void setRegionObjectsRegionStyle();
void restoreRegionObjectsOriginalStyle();
@@ -156,10 +162,6 @@ protected:
virtual bool shouldHaveAutoLogicalHeight() const;
private:
- virtual const char* renderName() const { return "RenderRegion"; }
-
- virtual bool canHaveChildren() const OVERRIDE { return false; }
-
virtual void insertedIntoTree() OVERRIDE;
virtual void willBeRemovedFromTree() OVERRIDE;
@@ -167,6 +169,8 @@ private:
virtual bool supportsPartialLayout() const OVERRIDE { return false; }
virtual void paintObject(PaintInfo&, const LayoutPoint&) OVERRIDE;
+ virtual void updateLogicalHeight() OVERRIDE;
+
virtual void installFlowThread();
PassRefPtr<RenderStyle> computeStyleInRegion(const RenderObject*);
@@ -179,6 +183,8 @@ private:
void incrementAutoLogicalHeightCount();
void decrementAutoLogicalHeightCount();
+ Element* element() const;
+
protected:
RenderFlowThread* m_flowThread;
@@ -216,20 +222,7 @@ private:
bool m_hasAutoLogicalHeight : 1;
};
-inline RenderRegion* toRenderRegion(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isRenderRegion());
- return static_cast<RenderRegion*>(object);
-}
-
-inline const RenderRegion* toRenderRegion(const RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isRenderRegion());
- return static_cast<const RenderRegion*>(object);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toRenderRegion(const RenderRegion*);
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderRegion, isRenderRegion());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderReplaced.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderReplaced.cpp
index f83db589eb6..059cd205f57 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderReplaced.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderReplaced.cpp
@@ -25,11 +25,14 @@
#include "core/rendering/RenderReplaced.h"
#include "RuntimeEnabledFeatures.h"
-#include "core/platform/graphics/GraphicsContext.h"
+#include "core/rendering/GraphicsContextAnnotator.h"
+#include "core/rendering/LayoutRectRecorder.h"
#include "core/rendering/LayoutRepainter.h"
#include "core/rendering/RenderBlock.h"
+#include "core/rendering/RenderImage.h"
#include "core/rendering/RenderLayer.h"
#include "core/rendering/RenderView.h"
+#include "platform/graphics/GraphicsContext.h"
using namespace std;
@@ -78,6 +81,7 @@ void RenderReplaced::layout()
{
ASSERT(needsLayout());
+ LayoutRectRecorder recorder(*this);
LayoutRepainter repainter(*this, checkForRepaintDuringLayout());
setHeight(minimumReplacedHeight());
@@ -119,11 +123,14 @@ void RenderReplaced::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
return;
}
+ if (paintInfo.phase == PaintPhaseClippingMask && (!hasLayer() || !layer()->hasCompositedClippingMask()))
+ return;
+
LayoutRect paintRect = LayoutRect(adjustedPaintOffset, size());
if ((paintInfo.phase == PaintPhaseOutline || paintInfo.phase == PaintPhaseSelfOutline) && style()->outlineWidth())
paintOutline(paintInfo, paintRect);
- if (paintInfo.phase != PaintPhaseForeground && paintInfo.phase != PaintPhaseSelection && !canHaveChildren())
+ if (paintInfo.phase != PaintPhaseForeground && paintInfo.phase != PaintPhaseSelection && !canHaveChildren() && paintInfo.phase != PaintPhaseClippingMask)
return;
if (!paintInfo.shouldPaintWithinRoot(this))
@@ -152,7 +159,11 @@ void RenderReplaced::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
}
if (!completelyClippedOut) {
- paintReplaced(paintInfo, adjustedPaintOffset);
+ if (paintInfo.phase == PaintPhaseClippingMask) {
+ paintClippingMask(paintInfo, adjustedPaintOffset);
+ } else {
+ paintReplaced(paintInfo, adjustedPaintOffset);
+ }
if (style()->hasBorderRadius())
paintInfo.context->restore();
@@ -170,7 +181,7 @@ void RenderReplaced::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
bool RenderReplaced::shouldPaint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
{
if (paintInfo.phase != PaintPhaseForeground && paintInfo.phase != PaintPhaseOutline && paintInfo.phase != PaintPhaseSelfOutline
- && paintInfo.phase != PaintPhaseSelection && paintInfo.phase != PaintPhaseMask)
+ && paintInfo.phase != PaintPhaseSelection && paintInfo.phase != PaintPhaseMask && paintInfo.phase != PaintPhaseClippingMask)
return false;
if (!paintInfo.shouldPaintWithinRoot(this))
@@ -270,8 +281,11 @@ void RenderReplaced::computeAspectRatioInformationForRenderBox(RenderBox* conten
ASSERT(!isPercentageIntrinsicSize);
// Handle zoom & vertical writing modes here, as the embedded document doesn't know about them.
- if (!isPercentageIntrinsicSize)
+ if (!isPercentageIntrinsicSize) {
intrinsicSize.scale(style()->effectiveZoom());
+ if (isRenderImage())
+ intrinsicSize.scale(toRenderImage(this)->imageDevicePixelRatio());
+ }
if (rendererHasAspectRatio(this) && isPercentageIntrinsicSize)
intrinsicRatio = 1;
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderReplica.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderReplica.cpp
index 5679d1bdfeb..d7885c27909 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderReplica.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderReplica.cpp
@@ -29,6 +29,8 @@
#include "config.h"
#include "core/rendering/RenderReplica.h"
+#include "core/rendering/GraphicsContextAnnotator.h"
+#include "core/rendering/LayoutRectRecorder.h"
#include "core/rendering/RenderLayer.h"
namespace WebCore {
@@ -56,6 +58,7 @@ RenderReplica::~RenderReplica()
void RenderReplica::layout()
{
+ LayoutRectRecorder recorder(*this);
setFrameRect(parentBox()->borderBoxRect());
updateLayerTransform();
clearNeedsLayout();
@@ -81,8 +84,8 @@ void RenderReplica::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
// Turn around and paint the parent layer. Use temporary clipRects, so that the layer doesn't end up caching clip rects
// computing using the wrong rootLayer
RenderLayer* rootPaintingLayer = layer()->transform() ? layer()->parent() : layer()->enclosingTransformedAncestor();
- RenderLayer::LayerPaintingInfo paintingInfo(rootPaintingLayer, paintInfo.rect, PaintBehaviorNormal, LayoutSize(), 0, paintInfo.renderRegion);
- RenderLayer::PaintLayerFlags flags = RenderLayer::PaintLayerHaveTransparency | RenderLayer::PaintLayerAppliedTransform | RenderLayer::PaintLayerTemporaryClipRects | RenderLayer::PaintLayerPaintingReflection;
+ LayerPaintingInfo paintingInfo(rootPaintingLayer, paintInfo.rect, PaintBehaviorNormal, LayoutSize(), 0, paintInfo.renderRegion);
+ PaintLayerFlags flags = PaintLayerHaveTransparency | PaintLayerAppliedTransform | PaintLayerTemporaryClipRects | PaintLayerPaintingReflection;
layer()->parent()->paintLayer(paintInfo.context, paintingInfo, flags);
} else if (paintInfo.phase == PaintPhaseMask)
paintMask(paintInfo, adjustedPaintOffset);
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderRuby.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderRuby.cpp
index 13e2b04e432..8a9ef79b624 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderRuby.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderRuby.cpp
@@ -82,10 +82,10 @@ static inline RenderBlock* rubyAfterBlock(const RenderObject* ruby)
return isRubyAfterBlock(child) ? toRenderBlock(child) : 0;
}
-static RenderBlock* createAnonymousRubyInlineBlock(RenderObject* ruby)
+static RenderBlockFlow* createAnonymousRubyInlineBlock(RenderObject* ruby)
{
RefPtr<RenderStyle> newStyle = RenderStyle::createAnonymousStyleWithDisplay(ruby->style(), INLINE_BLOCK);
- RenderBlock* newBlock = RenderBlock::createAnonymous(&ruby->document());
+ RenderBlockFlow* newBlock = RenderBlockFlow::createAnonymous(&ruby->document());
newBlock->setStyle(newStyle.release());
return newBlock;
}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderRubyRun.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderRubyRun.cpp
index 85d00e2b96a..fe58c872243 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderRubyRun.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderRubyRun.cpp
@@ -32,6 +32,7 @@
#include "core/rendering/RenderRubyRun.h"
+#include "core/rendering/LayoutRectRecorder.h"
#include "core/rendering/RenderRubyBase.h"
#include "core/rendering/RenderRubyText.h"
#include "core/rendering/RenderText.h"
@@ -228,6 +229,7 @@ RenderObject* RenderRubyRun::layoutSpecialExcludedChild(bool relayoutChildren, S
void RenderRubyRun::layout()
{
+ LayoutRectRecorder recorder(*this);
RenderBlock::layout();
RenderRubyText* rt = rubyText();
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderRubyRun.h b/chromium/third_party/WebKit/Source/core/rendering/RenderRubyRun.h
index ebf642b9296..2005bc1322b 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderRubyRun.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderRubyRun.h
@@ -79,19 +79,7 @@ private:
virtual void removeLeftoverAnonymousBlock(RenderBlock*) { }
};
-inline RenderRubyRun* toRenderRubyRun(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isRubyRun());
- return static_cast<RenderRubyRun*>(object);
-}
-
-inline const RenderRubyRun* toRenderRubyRun(const RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isBox());
- return static_cast<const RenderRubyRun*>(object);
-}
-
-void toRenderRubyRun(const RenderRubyRun*);
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderRubyRun, isRubyRun());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderRubyText.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderRubyText.cpp
index 585205fa9df..3e5a60f0dfb 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderRubyText.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderRubyText.cpp
@@ -56,7 +56,7 @@ ETextAlign RenderRubyText::textAlignmentForLine(bool endsWithSoftBreak) const
ETextAlign textAlign = style()->textAlign();
// FIXME: This check is bogus since user can set the initial value.
if (textAlign != RenderStyle::initialTextAlign())
- return RenderBlock::textAlignmentForLine(endsWithSoftBreak);
+ return RenderBlockFlow::textAlignmentForLine(endsWithSoftBreak);
// The default behavior is to allow ruby text to expand if it is shorter than the ruby base.
return JUSTIFY;
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderScrollbar.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderScrollbar.cpp
index 2cef428a518..a3aaeacba69 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderScrollbar.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderScrollbar.cpp
@@ -27,8 +27,8 @@
#include "core/rendering/RenderScrollbar.h"
#include "core/css/PseudoStyleRequest.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameView.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
#include "core/rendering/RenderPart.h"
#include "core/rendering/RenderScrollbarPart.h"
#include "core/rendering/RenderScrollbarTheme.h"
@@ -87,7 +87,7 @@ RenderBox* RenderScrollbar::owningRenderer() const
return m_owner && m_owner->renderer() ? m_owner->renderer()->enclosingBox() : 0;
}
-void RenderScrollbar::setParent(ScrollView* parent)
+void RenderScrollbar::setParent(Widget* parent)
{
Scrollbar::setParent(parent);
if (!parent) {
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderScrollbar.h b/chromium/third_party/WebKit/Source/core/rendering/RenderScrollbar.h
index a40ede8a80b..fcb60151a20 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderScrollbar.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderScrollbar.h
@@ -26,8 +26,8 @@
#ifndef RenderScrollbar_h
#define RenderScrollbar_h
-#include "core/platform/Scrollbar.h"
#include "core/rendering/style/RenderStyleConstants.h"
+#include "platform/scroll/Scrollbar.h"
#include "wtf/HashMap.h"
namespace WebCore {
@@ -60,7 +60,7 @@ public:
virtual bool isOverlayScrollbar() const { return false; }
private:
- virtual void setParent(ScrollView*);
+ virtual void setParent(Widget*) OVERRIDE;
virtual void setEnabled(bool);
virtual void paint(GraphicsContext*, const IntRect& damageRect);
@@ -87,14 +87,7 @@ private:
HashMap<unsigned, RenderScrollbarPart*> m_parts;
};
-inline RenderScrollbar* toRenderScrollbar(ScrollbarThemeClient* scrollbar)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!scrollbar || scrollbar->isCustomScrollbar());
- return static_cast<RenderScrollbar*>(scrollbar);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toRenderScrollbar(const RenderScrollbar*);
+DEFINE_TYPE_CASTS(RenderScrollbar, ScrollbarThemeClient, scrollbar, scrollbar->isCustomScrollbar(), scrollbar.isCustomScrollbar());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderScrollbarPart.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderScrollbarPart.cpp
index fc56bfc80f9..13a35ebb832 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderScrollbarPart.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderScrollbarPart.cpp
@@ -26,6 +26,7 @@
#include "config.h"
#include "core/rendering/RenderScrollbarPart.h"
+#include "core/rendering/LayoutRectRecorder.h"
#include "core/rendering/PaintInfo.h"
#include "core/rendering/RenderScrollbar.h"
#include "core/rendering/RenderScrollbarTheme.h"
@@ -55,6 +56,7 @@ RenderScrollbarPart* RenderScrollbarPart::createAnonymous(Document* document, Re
void RenderScrollbarPart::layout()
{
+ LayoutRectRecorder recorder(*this);
setLocation(LayoutPoint()); // We don't worry about positioning ourselves. We're just determining our minimum width/height.
if (m_scrollbar->orientation() == HorizontalScrollbar)
layoutHorizontalPart();
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderScrollbarPart.h b/chromium/third_party/WebKit/Source/core/rendering/RenderScrollbarPart.h
index fadaea77d77..a1f24654f4b 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderScrollbarPart.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderScrollbarPart.h
@@ -26,8 +26,8 @@
#ifndef RenderScrollbarPart_h
#define RenderScrollbarPart_h
-#include "core/platform/ScrollTypes.h"
#include "core/rendering/RenderBlock.h"
+#include "platform/scroll/ScrollTypes.h"
namespace WebCore {
@@ -78,20 +78,7 @@ private:
ScrollbarPart m_part;
};
-inline RenderScrollbarPart* toRenderScrollbarPart(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isRenderScrollbarPart());
- return static_cast<RenderScrollbarPart*>(object);
-}
-
-inline const RenderScrollbarPart* toRenderScrollbarPart(const RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isRenderScrollbarPart());
- return static_cast<const RenderScrollbarPart*>(object);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toRenderScrollbarPart(const RenderScrollbarPart*);
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderScrollbarPart, isRenderScrollbarPart());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderScrollbarTheme.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderScrollbarTheme.cpp
index 84185ff7158..63f1a1e23d5 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderScrollbarTheme.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderScrollbarTheme.cpp
@@ -24,9 +24,9 @@
*/
#include "config.h"
-#include "core/platform/ScrollbarThemeClient.h"
#include "core/rendering/RenderScrollbar.h"
#include "core/rendering/RenderScrollbarTheme.h"
+#include "platform/scroll/ScrollbarThemeClient.h"
#include "wtf/StdLibExtras.h"
namespace WebCore {
@@ -107,7 +107,7 @@ IntRect RenderScrollbarTheme::constrainTrackRectToTrackPieces(ScrollbarThemeClie
return result;
}
-void RenderScrollbarTheme::paintScrollCorner(ScrollView*, GraphicsContext* context, const IntRect& cornerRect)
+void RenderScrollbarTheme::paintScrollCorner(GraphicsContext* context, const IntRect& cornerRect)
{
// FIXME: Implement.
context->fillRect(cornerRect, Color::white);
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderScrollbarTheme.h b/chromium/third_party/WebKit/Source/core/rendering/RenderScrollbarTheme.h
index 8da44cdd0fb..0b5b56e8145 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderScrollbarTheme.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderScrollbarTheme.h
@@ -26,13 +26,12 @@
#ifndef RenderScrollbarTheme_h
#define RenderScrollbarTheme_h
-#include "core/platform/ScrollbarTheme.h"
+#include "platform/scroll/ScrollbarTheme.h"
namespace WebCore {
class PlatformMouseEvent;
class Scrollbar;
-class ScrollView;
class RenderScrollbarTheme : public ScrollbarTheme {
public:
@@ -44,7 +43,7 @@ public:
virtual bool supportsControlTints() const OVERRIDE { return true; }
- virtual void paintScrollCorner(ScrollView*, GraphicsContext*, const IntRect& cornerRect) OVERRIDE;
+ virtual void paintScrollCorner(GraphicsContext*, const IntRect& cornerRect) OVERRIDE;
virtual bool shouldCenterOnThumb(ScrollbarThemeClient* scrollbar, const PlatformMouseEvent& event) OVERRIDE { return ScrollbarTheme::theme()->shouldCenterOnThumb(scrollbar, event); }
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderSearchField.h b/chromium/third_party/WebKit/Source/core/rendering/RenderSearchField.h
index 006169bf67f..87d889feaf6 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderSearchField.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderSearchField.h
@@ -44,14 +44,7 @@ private:
Element* cancelButtonElement() const;
};
-inline RenderSearchField* toRenderSearchField(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isTextField());
- return static_cast<RenderSearchField*>(object);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toRenderSearchField(const RenderSearchField*);
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderSearchField, isTextField());
}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderSelectionInfo.h b/chromium/third_party/WebKit/Source/core/rendering/RenderSelectionInfo.h
index 96d00278dc7..d3ec42d5720 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderSelectionInfo.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderSelectionInfo.h
@@ -25,8 +25,8 @@
#ifndef RenderSelectionInfo_h
#define RenderSelectionInfo_h
-#include "core/platform/graphics/IntRect.h"
#include "core/rendering/RenderBox.h"
+#include "platform/geometry/IntRect.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderSlider.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderSlider.cpp
index f3e562d8988..73e4d67bdda 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderSlider.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderSlider.cpp
@@ -25,6 +25,7 @@
#include "core/html/HTMLInputElement.h"
#include "core/html/shadow/ShadowElementNames.h"
#include "core/html/shadow/SliderThumbElement.h"
+#include "core/rendering/LayoutRectRecorder.h"
#include "wtf/MathExtras.h"
using std::min;
@@ -44,11 +45,6 @@ RenderSlider::~RenderSlider()
{
}
-bool RenderSlider::canBeReplacedWithInlineRunIn() const
-{
- return false;
-}
-
int RenderSlider::baselinePosition(FontBaseline, bool /*firstLine*/, LineDirectionMode, LinePositionMode linePositionMode) const
{
ASSERT(linePositionMode == PositionOnContainingLine);
@@ -97,6 +93,7 @@ inline SliderThumbElement* RenderSlider::sliderThumbElement() const
void RenderSlider::layout()
{
+ LayoutRectRecorder recorder(*this);
// FIXME: Find a way to cascade appearance.
// http://webkit.org/b/62535
RenderBox* thumbBox = sliderThumbElement()->renderBox();
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderSlider.h b/chromium/third_party/WebKit/Source/core/rendering/RenderSlider.h
index d6b457efb4d..a627e2c0489 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderSlider.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderSlider.h
@@ -41,25 +41,16 @@ public:
private:
virtual const char* renderName() const { return "RenderSlider"; }
virtual bool isSlider() const { return true; }
- virtual bool canBeReplacedWithInlineRunIn() const OVERRIDE;
virtual int baselinePosition(FontBaseline, bool firstLine, LineDirectionMode, LinePositionMode = PositionOnContainingLine) const;
virtual void computeIntrinsicLogicalWidths(LayoutUnit& minLogicalWidth, LayoutUnit& maxLogicalWidth) const OVERRIDE;
virtual void computePreferredLogicalWidths() OVERRIDE;
- virtual bool requiresForcedStyleRecalcPropagation() const { return true; }
virtual void layout();
SliderThumbElement* sliderThumbElement() const;
};
-inline RenderSlider* toRenderSlider(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isSlider());
- return static_cast<RenderSlider*>(object);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toRenderSlider(const RenderSlider*);
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderSlider, isSlider());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderTable.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderTable.cpp
index 4cbcf05b99a..5ca0c17e93e 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderTable.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderTable.cpp
@@ -29,10 +29,12 @@
#include "HTMLNames.h"
#include "core/dom/Document.h"
#include "core/html/HTMLTableElement.h"
-#include "core/page/FrameView.h"
+#include "core/frame/FrameView.h"
#include "core/rendering/AutoTableLayout.h"
#include "core/rendering/FixedTableLayout.h"
+#include "core/rendering/GraphicsContextAnnotator.h"
#include "core/rendering/HitTestResult.h"
+#include "core/rendering/LayoutRectRecorder.h"
#include "core/rendering/LayoutRepainter.h"
#include "core/rendering/RenderLayer.h"
#include "core/rendering/RenderTableCaption.h"
@@ -41,8 +43,8 @@
#include "core/rendering/RenderTableSection.h"
#include "core/rendering/RenderView.h"
#include "core/rendering/SubtreeLayoutScope.h"
-#include "core/rendering/style/CollapsedBorderValue.h"
#include "core/rendering/style/StyleInheritedData.h"
+#include "platform/graphics/GraphicsContextStateSaver.h"
using namespace std;
@@ -88,6 +90,9 @@ void RenderTable::styleDidChange(StyleDifference diff, const RenderStyle* oldSty
m_columnPos[0] = m_hSpacing;
if (!m_tableLayout || style()->tableLayout() != oldTableLayout) {
+ if (m_tableLayout)
+ m_tableLayout->willChangeTableLayout();
+
// According to the CSS2 spec, you only use fixed table layout if an
// explicit width is specified on the table. Auto width implies auto table layout.
if (style()->tableLayout() == TFIXED && !style()->logicalWidth().isAuto())
@@ -267,7 +272,7 @@ void RenderTable::updateLogicalWidth()
LayoutUnit availableContentLogicalWidth = max<LayoutUnit>(0, containerWidthInInlineDirection - marginTotal);
if (shrinkToAvoidFloats() && cb->containsFloats() && !hasPerpendicularContainingBlock) {
// FIXME: Work with regions someday.
- availableContentLogicalWidth = shrinkLogicalWidthToAvoidFloats(marginStart, marginEnd, cb, 0);
+ availableContentLogicalWidth = shrinkLogicalWidthToAvoidFloats(marginStart, marginEnd, toRenderBlockFlow(cb), 0);
}
// Ensure we aren't bigger than our available width.
@@ -365,17 +370,17 @@ void RenderTable::layoutCaption(RenderTableCaption* caption)
if (caption->needsLayout()) {
// The margins may not be available but ensure the caption is at least located beneath any previous sibling caption
// so that it does not mistakenly think any floats in the previous caption intrude into it.
- caption->setLogicalLocation(LayoutPoint(caption->marginStart(), caption->marginBefore() + logicalHeight()));
+ caption->setLogicalLocation(LayoutPoint(caption->marginStart(), collapsedMarginBeforeForChild(caption) + logicalHeight()));
// If RenderTableCaption ever gets a layout() function, use it here.
caption->layoutIfNeeded();
}
// Apply the margins to the location now that they are definitely available from layout
- caption->setLogicalLocation(LayoutPoint(caption->marginStart(), caption->marginBefore() + logicalHeight()));
+ caption->setLogicalLocation(LayoutPoint(caption->marginStart(), collapsedMarginBeforeForChild(caption) + logicalHeight()));
if (!selfNeedsLayout() && caption->checkForRepaintDuringLayout())
caption->repaintDuringLayoutIfMoved(captionRect);
- setLogicalHeight(logicalHeight() + caption->logicalHeight() + caption->marginBefore() + caption->marginAfter());
+ setLogicalHeight(logicalHeight() + caption->logicalHeight() + collapsedMarginBeforeForChild(caption) + collapsedMarginAfterForChild(caption));
}
void RenderTable::distributeExtraLogicalHeight(int extraLogicalHeight)
@@ -404,6 +409,8 @@ void RenderTable::layout()
{
ASSERT(needsLayout());
+ LayoutRectRecorder recorder(*this);
+
if (simplifiedLayout())
return;
@@ -453,6 +460,11 @@ void RenderTable::layout()
} else if (child->isRenderTableCol()) {
child->layoutIfNeeded();
ASSERT(!child->needsLayout());
+ } else {
+ // FIXME: We should never have other type of children (they should be wrapped in an
+ // anonymous table section) but our code is too crazy and this can happen in practice.
+ // Until this is fixed, let's make sure we don't leave non laid out children in the tree.
+ child->layoutIfNeeded();
}
}
@@ -718,15 +730,7 @@ void RenderTable::paintBoxDecorations(PaintInfo& paintInfo, const LayoutPoint& p
LayoutRect rect(paintOffset, size());
subtractCaptionRect(rect);
-
- BackgroundBleedAvoidance bleedAvoidance = determineBackgroundBleedAvoidance(paintInfo.context);
- if (!boxShadowShouldBeAppliedToBackground(bleedAvoidance))
- paintBoxShadow(paintInfo, rect, style(), Normal);
- paintBackground(paintInfo, rect, bleedAvoidance);
- paintBoxShadow(paintInfo, rect, style(), Inset);
-
- if (style()->hasBorder() && !collapseBorders())
- paintBorder(paintInfo, rect, style());
+ paintBoxDecorationsWithRect(paintInfo, paintOffset, rect);
}
void RenderTable::paintMask(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
@@ -844,10 +848,6 @@ RenderTableCol* RenderTable::firstColumn() const
for (RenderObject* child = firstChild(); child; child = child->nextSibling()) {
if (child->isRenderTableCol())
return toRenderTableCol(child);
-
- // We allow only table-captions before columns or column-groups.
- if (!child->isTableCaption())
- return 0;
}
return 0;
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderTable.h b/chromium/third_party/WebKit/Source/core/rendering/RenderTable.h
index 686d9437ad1..ba7ab67b752 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderTable.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderTable.h
@@ -349,20 +349,7 @@ inline RenderTableSection* RenderTable::topSection() const
return m_foot;
}
-inline RenderTable* toRenderTable(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isTable());
- return static_cast<RenderTable*>(object);
-}
-
-inline const RenderTable* toRenderTable(const RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isTable());
- return static_cast<const RenderTable*>(object);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toRenderTable(const RenderTable*);
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderTable, isTable());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderTableCaption.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderTableCaption.cpp
index e35acc56181..af677b71de9 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderTableCaption.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderTableCaption.cpp
@@ -41,7 +41,7 @@ LayoutUnit RenderTableCaption::containingBlockLogicalWidthForContent() const
void RenderTableCaption::insertedIntoTree()
{
- RenderBlock::insertedIntoTree();
+ RenderBlockFlow::insertedIntoTree();
table()->addCaption(this);
}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderTableCaption.h b/chromium/third_party/WebKit/Source/core/rendering/RenderTableCaption.h
index 711bbb79fe0..35755a9d03b 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderTableCaption.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderTableCaption.h
@@ -43,20 +43,7 @@ private:
RenderTable* table() const;
};
-inline RenderTableCaption* toRenderTableCaption(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isTableCaption());
- return static_cast<RenderTableCaption*>(object);
-}
-
-inline const RenderTableCaption* toRenderTableCaption(const RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isTableCaption());
- return static_cast<const RenderTableCaption*>(object);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toRenderTableCaption(const RenderTableCaption*);
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderTableCaption, isTableCaption());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderTableCell.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderTableCell.cpp
index 3782283385d..9737da43de8 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderTableCell.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderTableCell.cpp
@@ -28,14 +28,15 @@
#include "HTMLNames.h"
#include "core/css/StylePropertySet.h"
#include "core/html/HTMLTableCellElement.h"
-#include "core/platform/graphics/FloatQuad.h"
-#include "core/platform/graphics/GraphicsContextStateSaver.h"
-#include "core/platform/graphics/transforms/TransformState.h"
+#include "core/rendering/LayoutRectRecorder.h"
#include "core/rendering/PaintInfo.h"
#include "core/rendering/RenderTableCol.h"
#include "core/rendering/RenderView.h"
#include "core/rendering/SubtreeLayoutScope.h"
#include "core/rendering/style/CollapsedBorderValue.h"
+#include "platform/geometry/FloatQuad.h"
+#include "platform/geometry/TransformState.h"
+#include "platform/graphics/GraphicsContextStateSaver.h"
using namespace std;
@@ -152,7 +153,7 @@ void RenderTableCell::computePreferredLogicalWidths()
if (node() && style()->autoWrap()) {
// See if nowrap was set.
Length w = styleOrColLogicalWidth();
- String nowrap = toElement(node())->getAttribute(nowrapAttr);
+ const AtomicString& nowrap = toElement(node())->getAttribute(nowrapAttr);
if (!nowrap.isNull() && w.isFixed())
// Nowrap is set, but we didn't actually use it because of the
// fixed width set on the cell. Even so, it is a WinIE/Moz trait
@@ -163,6 +164,16 @@ void RenderTableCell::computePreferredLogicalWidths()
}
}
+void RenderTableCell::addLayerHitTestRects(LayerHitTestRects& layerRects, const RenderLayer* currentLayer, const LayoutPoint& layerOffset, const LayoutRect& containerRect) const
+{
+ LayoutPoint adjustedLayerOffset = layerOffset;
+ // RenderTableCell's location includes the offset of it's containing RenderTableRow, so
+ // we need to subtract that again here (as for RenderTableCell::offsetFromContainer.
+ if (parent())
+ adjustedLayerOffset -= parentBox()->locationOffset();
+ RenderBox::addLayerHitTestRects(layerRects, currentLayer, adjustedLayerOffset, containerRect);
+}
+
void RenderTableCell::computeIntrinsicPadding(int rowHeight, SubtreeLayoutScope& layouter)
{
int oldIntrinsicPaddingBefore = intrinsicPaddingBefore();
@@ -226,6 +237,8 @@ void RenderTableCell::layout()
{
ASSERT(needsLayout());
+ LayoutRectRecorder recorder(*this);
+
updateFirstLetter();
int oldCellBaseline = cellBaselinePosition();
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderTableCell.h b/chromium/third_party/WebKit/Source/core/rendering/RenderTableCell.h
index 29439c5178d..9eeb48e4f01 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderTableCell.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderTableCell.h
@@ -219,6 +219,8 @@ protected:
virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle);
virtual void computePreferredLogicalWidths();
+ virtual void addLayerHitTestRects(LayerHitTestRects&, const RenderLayer* currentCompositedLayer, const LayoutPoint& layerOffset, const LayoutRect& containerRect) const OVERRIDE;
+
private:
virtual const char* renderName() const { return (isAnonymous() || isPseudoElement()) ? "RenderTableCell (anonymous)" : "RenderTableCell"; }
@@ -285,20 +287,7 @@ private:
int m_intrinsicPaddingAfter;
};
-inline RenderTableCell* toRenderTableCell(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isTableCell());
- return static_cast<RenderTableCell*>(object);
-}
-
-inline const RenderTableCell* toRenderTableCell(const RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isTableCell());
- return static_cast<const RenderTableCell*>(object);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toRenderTableCell(const RenderTableCell*);
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderTableCell, isTableCell());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderTableCol.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderTableCol.cpp
index 48a537dc3ef..26c5935f97f 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderTableCol.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderTableCol.cpp
@@ -153,13 +153,7 @@ RenderTableCol* RenderTableCol::nextColumn() const
if (!next && parent()->isRenderTableCol())
next = parent()->nextSibling();
- for (; next && !next->isRenderTableCol(); next = next->nextSibling()) {
- // We allow captions mixed with columns and column-groups.
- if (next->isTableCaption())
- continue;
-
- return 0;
- }
+ for (; next && !next->isRenderTableCol(); next = next->nextSibling()) { }
return toRenderTableCol(next);
}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderTableCol.h b/chromium/third_party/WebKit/Source/core/rendering/RenderTableCol.h
index dd3e1b0d80a..a28f36085bb 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderTableCol.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderTableCol.h
@@ -103,20 +103,7 @@ private:
unsigned m_span;
};
-inline RenderTableCol* toRenderTableCol(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isRenderTableCol());
- return static_cast<RenderTableCol*>(object);
-}
-
-inline const RenderTableCol* toRenderTableCol(const RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isRenderTableCol());
- return static_cast<const RenderTableCol*>(object);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toRenderTableCol(const RenderTableCol*);
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderTableCol, isRenderTableCol());
}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderTableRow.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderTableRow.cpp
index d3f45f75167..528ae08d38c 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderTableRow.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderTableRow.cpp
@@ -28,7 +28,9 @@
#include "HTMLNames.h"
#include "core/dom/Document.h"
#include "core/fetch/ImageResource.h"
+#include "core/rendering/GraphicsContextAnnotator.h"
#include "core/rendering/HitTestResult.h"
+#include "core/rendering/LayoutRectRecorder.h"
#include "core/rendering/PaintInfo.h"
#include "core/rendering/RenderTableCell.h"
#include "core/rendering/RenderView.h"
@@ -158,6 +160,8 @@ void RenderTableRow::layout()
{
ASSERT(needsLayout());
+ LayoutRectRecorder recorder(*this);
+
// Table rows do not add translation.
LayoutStateMaintainer statePusher(view(), this, LayoutSize(), style()->isFlippedBlocksWritingMode());
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderTableRow.h b/chromium/third_party/WebKit/Source/core/rendering/RenderTableRow.h
index 8f385fafa9d..735f903c627 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderTableRow.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderTableRow.h
@@ -115,20 +115,7 @@ private:
unsigned m_rowIndex : 31;
};
-inline RenderTableRow* toRenderTableRow(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isTableRow());
- return static_cast<RenderTableRow*>(object);
-}
-
-inline const RenderTableRow* toRenderTableRow(const RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isTableRow());
- return static_cast<const RenderTableRow*>(object);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toRenderTableRow(const RenderTableRow*);
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderTableRow, isTableRow());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderTableSection.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderTableSection.cpp
index b5e77a06320..ab6d4da9c60 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderTableSection.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderTableSection.cpp
@@ -29,7 +29,9 @@
// FIXME: Remove 'RuntimeEnabledFeatures.h' when http://crbug.com/78724 is closed.
#include "RuntimeEnabledFeatures.h"
#include <limits>
+#include "core/rendering/GraphicsContextAnnotator.h"
#include "core/rendering/HitTestResult.h"
+#include "core/rendering/LayoutRectRecorder.h"
#include "core/rendering/PaintInfo.h"
#include "core/rendering/RenderTableCell.h"
#include "core/rendering/RenderTableCol.h"
@@ -37,7 +39,6 @@
#include "core/rendering/RenderView.h"
#include "core/rendering/SubtreeLayoutScope.h"
#include "wtf/HashSet.h"
-#include "wtf/Vector.h"
using namespace std;
@@ -478,7 +479,7 @@ void RenderTableSection::updateRowsHeightHavingOnlySpanningCells(RenderTableCell
const unsigned rowSpan = cell->rowSpan();
const unsigned rowIndex = cell->rowIndex();
- ASSERT(rowSpan == spanningRowsHeight.rowHeight.size());
+ ASSERT_UNUSED(rowSpan, rowSpan == spanningRowsHeight.rowHeight.size());
for (unsigned row = 0; row < spanningRowsHeight.rowHeight.size(); row++) {
unsigned actualRow = row + rowIndex;
@@ -730,6 +731,8 @@ void RenderTableSection::layout()
ASSERT(!needsCellRecalc());
ASSERT(!table()->needsSectionRecalc());
+ LayoutRectRecorder recorder(*this);
+
// addChild may over-grow m_grid but we don't want to throw away the memory too early as addChild
// can be called in a loop (e.g during parsing). Doing it now ensures we have a stable-enough structure.
m_grid.shrinkToFit();
@@ -1026,7 +1029,7 @@ void RenderTableSection::computeOverflowFromCells()
void RenderTableSection::computeOverflowFromCells(unsigned totalRows, unsigned nEffCols)
{
unsigned totalCellsCount = nEffCols * totalRows;
- int maxAllowedOverflowingCellsCount = totalCellsCount < gMinTableSizeToUseFastPaintPathWithOverflowingCell ? 0 : gMaxAllowedOverflowingCellRatioForFastPaintPath * totalCellsCount;
+ unsigned maxAllowedOverflowingCellsCount = totalCellsCount < gMinTableSizeToUseFastPaintPathWithOverflowingCell ? 0 : gMaxAllowedOverflowingCellRatioForFastPaintPath * totalCellsCount;
#ifndef NDEBUG
bool hasOverflowingCell = false;
@@ -1283,8 +1286,7 @@ void RenderTableSection::paint(PaintInfo& paintInfo, const LayoutPoint& paintOff
{
ANNOTATE_GRAPHICS_CONTEXT(paintInfo, this);
- // put this back in when all layout tests can handle it
- // ASSERT(!needsLayout());
+ ASSERT_WITH_SECURITY_IMPLICATION(!needsLayout());
// avoid crashing on bugs that cause us to paint with dirty layout
if (needsLayout())
return;
@@ -1785,7 +1787,7 @@ CollapsedBorderValue& RenderTableSection::cachedCollapsedBorder(const RenderTabl
{
ASSERT(table()->collapseBorders());
HashMap<pair<const RenderTableCell*, int>, CollapsedBorderValue>::iterator it = m_cellsCollapsedBorders.find(make_pair(cell, side));
- ASSERT(it != m_cellsCollapsedBorders.end());
+ ASSERT_WITH_SECURITY_IMPLICATION(it != m_cellsCollapsedBorders.end());
return it->value;
}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderTableSection.h b/chromium/third_party/WebKit/Source/core/rendering/RenderTableSection.h
index c7b0bc0f65d..42b51ec6b3e 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderTableSection.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderTableSection.h
@@ -308,20 +308,7 @@ private:
HashMap<pair<const RenderTableCell*, int>, CollapsedBorderValue > m_cellsCollapsedBorders;
};
-inline RenderTableSection* toRenderTableSection(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isTableSection());
- return static_cast<RenderTableSection*>(object);
-}
-
-inline const RenderTableSection* toRenderTableSection(const RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isTableSection());
- return static_cast<const RenderTableSection*>(object);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toRenderTableSection(const RenderTableSection*);
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderTableSection, isTableSection());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderText.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderText.cpp
index 6e1703a0a23..b89ddc756ba 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderText.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderText.cpp
@@ -27,12 +27,11 @@
#include "core/accessibility/AXObjectCache.h"
#include "core/dom/Text.h"
+#include "core/editing/TextIterator.h"
#include "core/fetch/TextResourceDecoder.h"
-#include "core/page/FrameView.h"
-#include "core/page/Settings.h"
-#include "core/platform/graphics/FloatQuad.h"
-#include "core/platform/text/TextBreakIterator.h"
-#include "core/platform/text/transcoder/FontTranscoder.h"
+#include "core/frame/FrameView.h"
+#include "core/frame/Settings.h"
+#include "core/rendering/AbstractInlineTextBox.h"
#include "core/rendering/EllipsisBox.h"
#include "core/rendering/InlineTextBox.h"
#include "core/rendering/RenderBlock.h"
@@ -40,6 +39,8 @@
#include "core/rendering/RenderLayer.h"
#include "core/rendering/RenderView.h"
#include "core/rendering/break_lines.h"
+#include "platform/geometry/FloatQuad.h"
+#include "platform/text/TextBreakIterator.h"
#include "wtf/text/StringBuffer.h"
#include "wtf/text/StringBuilder.h"
#include "wtf/unicode/CharacterNames.h"
@@ -120,8 +121,8 @@ static void makeCapitalized(String* string, UChar previous)
result.reserveCapacity(length);
int32_t endOfWord;
- int32_t startOfWord = textBreakFirst(boundary);
- for (endOfWord = textBreakNext(boundary); endOfWord != TextBreakDone; startOfWord = endOfWord, endOfWord = textBreakNext(boundary)) {
+ int32_t startOfWord = boundary->first();
+ for (endOfWord = boundary->next(); endOfWord != TextBreakDone; startOfWord = endOfWord, endOfWord = boundary->next()) {
if (startOfWord) // Ignore first char of previous string
result.append(input[startOfWord - 1] == noBreakSpace ? noBreakSpace : toTitleCase(stringWithPrevious[startOfWord]));
for (int i = startOfWord + 1; i < endOfWord; i++)
@@ -137,7 +138,6 @@ RenderText::RenderText(Node* node, PassRefPtr<StringImpl> str)
, m_linesDirty(false)
, m_containsReversedText(false)
, m_knownToHaveNoOverflowAndNoFallbackFonts(false)
- , m_needsTranscoding(false)
, m_minWidth(-1)
, m_maxWidth(-1)
, m_firstLineMinWidth(0)
@@ -184,12 +184,6 @@ bool RenderText::isWordBreak() const
return false;
}
-void RenderText::updateNeedsTranscoding()
-{
- const WTF::TextEncoding* encoding = document().decoder() ? &document().decoder()->encoding() : 0;
- m_needsTranscoding = fontTranscoder().needsTranscoding(style()->font().fontDescription(), encoding);
-}
-
void RenderText::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
{
// There is no need to ever schedule repaints from a style change of a text run, since
@@ -202,18 +196,9 @@ void RenderText::styleDidChange(StyleDifference diff, const RenderStyle* oldStyl
}
RenderStyle* newStyle = style();
- bool needsResetText = false;
- if (!oldStyle) {
- updateNeedsTranscoding();
- needsResetText = m_needsTranscoding;
- } else if (oldStyle->font().needsTranscoding() != newStyle->font().needsTranscoding() || (newStyle->font().needsTranscoding() && oldStyle->font().family().family() != newStyle->font().family().family())) {
- updateNeedsTranscoding();
- needsResetText = true;
- }
-
ETextTransform oldTransform = oldStyle ? oldStyle->textTransform() : TTNONE;
ETextSecurity oldSecurity = oldStyle ? oldStyle->textSecurity() : TSNONE;
- if (needsResetText || oldTransform != newStyle->textTransform() || oldSecurity != newStyle->textSecurity())
+ if (oldTransform != newStyle->textTransform() || oldSecurity != newStyle->textSecurity())
transformText();
if (!text().containsOnlyWhitespace())
@@ -315,6 +300,22 @@ PassRefPtr<StringImpl> RenderText::originalText() const
return (e && e->isTextNode()) ? toText(e)->dataImpl() : 0;
}
+String RenderText::plainText() const
+{
+ if (node())
+ return WebCore::plainText(rangeOfContents(node()).get());
+
+ // FIXME: this is just a stopgap until TextIterator is adapted to support generated text.
+ StringBuilder plainTextBuilder;
+ for (InlineTextBox* textBox = firstTextBox(); textBox; textBox = textBox->nextTextBox()) {
+ String text = m_text.substring(textBox->start(), textBox->len()).simplifyWhiteSpace(WTF::DoNotStripWhiteSpace);
+ plainTextBuilder.append(text);
+ if (textBox->nextTextBox() && textBox->nextTextBox()->start() > textBox->end() && text.length() && !text.right(1).containsOnlyWhitespace())
+ plainTextBuilder.append(" ");
+ }
+ return plainTextBuilder.toString();
+}
+
void RenderText::absoluteRects(Vector<IntRect>& rects, const LayoutPoint& accumulatedOffset) const
{
for (InlineTextBox* box = firstTextBox(); box; box = box->nextTextBox())
@@ -330,10 +331,10 @@ static FloatRect localQuadForTextBox(InlineTextBox* box, unsigned start, unsigne
// Change the height and y position (or width and x for vertical text)
// because selectionRect uses selection-specific values.
if (box->isHorizontal()) {
- r.setHeight(box->logicalHeight());
+ r.setHeight(box->height());
r.setY(box->y());
} else {
- r.setWidth(box->logicalWidth());
+ r.setWidth(box->width());
r.setX(box->x());
}
}
@@ -532,7 +533,8 @@ static PositionWithAffinity createPositionWithAffinityForBox(const InlineBox* bo
affinity = offset > box->caretMinOffset() ? VP_UPSTREAM_IF_POSSIBLE : DOWNSTREAM;
break;
}
- return box->renderer()->createPositionWithAffinity(offset, affinity);
+ int textStartOffset = box->renderer()->isText() ? toRenderText(box->renderer())->textStartOffset() : 0;
+ return box->renderer()->createPositionWithAffinity(offset + textStartOffset, affinity);
}
static PositionWithAffinity createPositionWithAffinityForBoxAfterAdjustingOffsetForBiDi(const InlineTextBox* box, int offset, ShouldAffinityBeDownstream shouldAffinityBeDownstream)
@@ -758,7 +760,7 @@ ALWAYS_INLINE float RenderText::widthFromCache(const Font& f, int start, int len
return w;
}
- TextRun run = RenderBlock::constructTextRun(const_cast<RenderText*>(this), f, this, start, len, style());
+ TextRun run = RenderBlockFlow::constructTextRun(const_cast<RenderText*>(this), f, this, start, len, style());
run.setCharactersLength(textLength() - start);
ASSERT(run.charactersLength() >= run.length());
@@ -813,7 +815,7 @@ void RenderText::trimmedPrefWidths(float leadWidth,
const Font& font = style()->font(); // FIXME: This ignores first-line.
if (stripFrontSpaces) {
const UChar space = ' ';
- float spaceWidth = font.width(RenderBlock::constructTextRun(this, font, &space, 1, style()));
+ float spaceWidth = font.width(RenderBlockFlow::constructTextRun(this, font, &space, 1, style()));
maxWidth -= spaceWidth;
} else {
maxWidth += font.wordSpacing();
@@ -887,7 +889,7 @@ void RenderText::computePreferredLogicalWidths(float leadWidth)
static inline float hyphenWidth(RenderText* renderer, const Font& font)
{
RenderStyle* style = renderer->style();
- return font.width(RenderBlock::constructTextRun(renderer, font, style->hyphenString().string(), style));
+ return font.width(RenderBlockFlow::constructTextRun(renderer, font, style->hyphenString().string(), style));
}
void RenderText::computePreferredLogicalWidths(float leadWidth, HashSet<const SimpleFontData*>& fallbackFonts, GlyphOverflow& glyphOverflow)
@@ -926,13 +928,11 @@ void RenderText::computePreferredLogicalWidths(float leadWidth, HashSet<const Si
// Non-zero only when kerning is enabled, in which case we measure words with their trailing
// space, then subtract its width.
- float wordTrailingSpaceWidth = f.typesettingFeatures() & Kerning ? f.width(RenderBlock::constructTextRun(this, f, &space, 1, styleToUse)) + wordSpacing : 0;
+ float wordTrailingSpaceWidth = f.typesettingFeatures() & Kerning ? f.width(RenderBlockFlow::constructTextRun(this, f, &space, 1, styleToUse)) + wordSpacing : 0;
// If automatic hyphenation is allowed, we keep track of the width of the widest word (or word
// fragment) encountered so far, and only try hyphenating words that are wider.
float maxWordWidth = numeric_limits<float>::max();
- int minimumPrefixLength = 0;
- int minimumSuffixLength = 0;
int firstGlyphLeftOverflow = -1;
bool breakAll = (styleToUse->wordBreak() == BreakAllWordBreak || styleToUse->wordBreak() == BreakWordBreak) && styleToUse->autoWrap();
@@ -1074,7 +1074,7 @@ void RenderText::computePreferredLogicalWidths(float leadWidth, HashSet<const Si
m_maxWidth = currMaxWidth;
currMaxWidth = 0;
} else {
- TextRun run = RenderBlock::constructTextRun(this, f, this, i, 1, styleToUse);
+ TextRun run = RenderBlockFlow::constructTextRun(this, f, this, i, 1, styleToUse);
run.setCharactersLength(len - i);
ASSERT(run.charactersLength() >= run.length());
run.setTabSize(!style()->collapseWhiteSpace(), style()->tabSize());
@@ -1316,10 +1316,10 @@ void applyTextTransform(const RenderStyle* style, String& text, UChar previousCh
makeCapitalized(&text, previousCharacter);
break;
case UPPERCASE:
- text.makeUpper();
+ text = text.upper(style->locale());
break;
case LOWERCASE:
- text.makeLower();
+ text = text.lower(style->locale());
break;
}
}
@@ -1328,11 +1328,6 @@ void RenderText::setTextInternal(PassRefPtr<StringImpl> text)
{
ASSERT(text);
m_text = text;
- if (m_needsTranscoding) {
- const WTF::TextEncoding* encoding = document().decoder() ? &document().decoder()->encoding() : 0;
- fontTranscoder().convert(m_text, style()->font().fontDescription(), encoding);
- }
- ASSERT(m_text);
if (style()) {
applyTextTransform(style(), m_text, previousCharacter());
@@ -1366,17 +1361,17 @@ void RenderText::secureText(UChar mask)
return;
int lastTypedCharacterOffsetToReveal = -1;
- String revealedText;
+ UChar revealedText;
SecureTextTimer* secureTextTimer = gSecureTextTimers ? gSecureTextTimers->get(this) : 0;
if (secureTextTimer && secureTextTimer->isActive()) {
lastTypedCharacterOffsetToReveal = secureTextTimer->lastTypedCharacterOffset();
if (lastTypedCharacterOffsetToReveal >= 0)
- revealedText.append(m_text[lastTypedCharacterOffsetToReveal]);
+ revealedText = m_text[lastTypedCharacterOffsetToReveal];
}
m_text.fill(mask);
if (lastTypedCharacterOffsetToReveal >= 0) {
- m_text.replace(lastTypedCharacterOffsetToReveal, 1, revealedText);
+ m_text.replace(lastTypedCharacterOffsetToReveal, 1, String(&revealedText, 1));
// m_text may be updated later before timer fires. We invalidate the lastTypedCharacterOffset to avoid inconsistency.
secureTextTimer->invalidate();
}
@@ -1397,19 +1392,6 @@ void RenderText::setText(PassRefPtr<StringImpl> text, bool force)
cache->textChanged(this);
}
-String RenderText::textWithoutTranscoding() const
-{
- // If m_text isn't transcoded or is secure, we can just return the modified text.
- if (!m_needsTranscoding || style()->textSecurity() != TSNONE)
- return text();
-
- // Otherwise, we should use original text. If text-transform is
- // specified, we should transform the text on the fly.
- String text = originalText();
- applyTextTransform(style(), text, previousCharacter());
- return text;
-}
-
void RenderText::dirtyLineBoxes(bool fullLayout)
{
if (fullLayout)
@@ -1496,7 +1478,7 @@ float RenderText::width(unsigned from, unsigned len, const Font& f, float xPos,
} else
w = widthFromCache(f, from, len, xPos, fallbackFonts, glyphOverflow);
} else {
- TextRun run = RenderBlock::constructTextRun(const_cast<RenderText*>(this), f, this, from, len, style());
+ TextRun run = RenderBlockFlow::constructTextRun(const_cast<RenderText*>(this), f, this, from, len, style());
run.setCharactersLength(textLength() - from);
ASSERT(run.charactersLength() >= run.length());
@@ -1663,7 +1645,7 @@ int RenderText::previousOffset(int current) const
if (!iterator)
return current - 1;
- long result = textBreakPreceding(iterator, current);
+ long result = iterator->preceding(current);
if (result == TextBreakDone)
result = current - 1;
@@ -1671,7 +1653,7 @@ int RenderText::previousOffset(int current) const
return result;
}
-#if OS(MACOSX)
+#if OS(POSIX)
#define HANGUL_CHOSEONG_START (0x1100)
#define HANGUL_CHOSEONG_END (0x115F)
@@ -1713,7 +1695,7 @@ inline bool isRegionalIndicator(UChar32 c)
int RenderText::previousOffsetForBackwardDeletion(int current) const
{
-#if OS(MACOSX)
+#if OS(POSIX)
ASSERT(m_text);
StringImpl& text = *m_text.impl();
UChar32 character;
@@ -1756,7 +1738,6 @@ int RenderText::previousOffsetForBackwardDeletion(int current) const
character = text.characterStartingAt(current);
if (((character >= HANGUL_CHOSEONG_START) && (character <= HANGUL_JONGSEONG_END)) || ((character >= HANGUL_SYLLABLE_START) && (character <= HANGUL_SYLLABLE_END))) {
HangulState state;
- HangulState initialState;
if (character < HANGUL_JUNGSEONG_START)
state = HangulStateL;
@@ -1767,8 +1748,6 @@ int RenderText::previousOffsetForBackwardDeletion(int current) const
else
state = isHangulLVT(character) ? HangulStateLVT : HangulStateLV;
- initialState = state;
-
while (current > 0 && ((character = text.characterStartingAt(current - 1)) >= HANGUL_CHOSEONG_START) && (character <= HANGUL_SYLLABLE_END) && ((character <= HANGUL_JONGSEONG_END) || (character >= HANGUL_SYLLABLE_START))) {
switch (state) {
case HangulStateV:
@@ -1800,7 +1779,7 @@ int RenderText::previousOffsetForBackwardDeletion(int current) const
return current;
#else
- // Platforms other than Mac delete by one code point.
+ // Platforms other than Unix-like delete by one code point.
if (U16_IS_TRAIL(m_text[--current]))
--current;
if (current < 0)
@@ -1819,7 +1798,7 @@ int RenderText::nextOffset(int current) const
if (!iterator)
return current + 1;
- long result = textBreakFollowing(iterator, current);
+ long result = iterator->following(current);
if (result == TextBreakDone)
result = current + 1;
@@ -1863,4 +1842,9 @@ void RenderText::momentarilyRevealLastTypedCharacter(unsigned lastTypedCharacter
secureTextTimer->restartWithNewText(lastTypedCharacterOffset);
}
+PassRefPtr<AbstractInlineTextBox> RenderText::firstAbstractInlineTextBox()
+{
+ return AbstractInlineTextBox::getOrCreate(this, m_firstTextBox);
+}
+
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderText.h b/chromium/third_party/WebKit/Source/core/rendering/RenderText.h
index 1a49794cf22..13af4be1c6b 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderText.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderText.h
@@ -25,9 +25,11 @@
#include "core/rendering/RenderObject.h"
#include "wtf/Forward.h"
+#include "wtf/PassRefPtr.h"
namespace WebCore {
+class AbstractInlineTextBox;
class InlineTextBox;
class RenderText : public RenderObject {
@@ -52,7 +54,8 @@ public:
void removeTextBox(InlineTextBox*);
const String& text() const { return m_text; }
- String textWithoutTranscoding() const;
+ virtual unsigned textStartOffset() const { return 0; }
+ String plainText() const;
InlineTextBox* createInlineTextBox();
void dirtyLineBoxes(bool fullLayout);
@@ -141,6 +144,8 @@ public:
void removeAndDestroyTextBoxes();
+ PassRefPtr<AbstractInlineTextBox> firstAbstractInlineTextBox();
+
protected:
virtual void computePreferredLogicalWidths(float leadWidth);
virtual void willBeDestroyed();
@@ -173,7 +178,6 @@ private:
bool containsOnlyWhitespace(unsigned from, unsigned len) const;
float widthFromCache(const Font&, int start, int len, float xPos, HashSet<const SimpleFontData*>* fallbackFonts, GlyphOverflow*) const;
bool isAllASCII() const { return m_isAllASCII; }
- void updateNeedsTranscoding();
void secureText(UChar mask);
@@ -192,7 +196,6 @@ private:
bool m_isAllASCII : 1;
bool m_canUseSimpleFontCodePath : 1;
mutable bool m_knownToHaveNoOverflowAndNoFallbackFonts : 1;
- bool m_needsTranscoding : 1;
float m_minWidth;
float m_maxWidth;
@@ -219,20 +222,7 @@ inline UChar RenderText::characterAt(unsigned i) const
return uncheckedCharacterAt(i);
}
-inline RenderText* toRenderText(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isText());
- return static_cast<RenderText*>(object);
-}
-
-inline const RenderText* toRenderText(const RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isText());
- return static_cast<const RenderText*>(object);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toRenderText(const RenderText*);
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderText, isText());
#ifdef NDEBUG
inline void RenderText::checkConsistency() const
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderTextControl.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderTextControl.cpp
index 38e54c63265..d420fbff074 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderTextControl.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderTextControl.cpp
@@ -23,9 +23,9 @@
#include "core/rendering/RenderTextControl.h"
#include "core/html/HTMLTextFormControlElement.h"
-#include "core/platform/ScrollbarTheme.h"
#include "core/rendering/HitTestResult.h"
#include "core/rendering/RenderTheme.h"
+#include "platform/scroll/ScrollbarTheme.h"
#include "wtf/unicode/CharacterNames.h"
using namespace std;
@@ -57,7 +57,7 @@ void RenderTextControl::addChild(RenderObject* newChild, RenderObject* beforeChi
// FIXME: This is a terrible hack to get the caret over the placeholder text since it'll
// make us paint the placeholder first. (See https://trac.webkit.org/changeset/118733)
Node* node = newChild->node();
- if (node && node->isElementNode() && toElement(node)->part() == "-webkit-input-placeholder")
+ if (node && node->isElementNode() && toElement(node)->pseudo() == "-webkit-input-placeholder")
RenderBlock::addChild(newChild, firstChild());
else
RenderBlock::addChild(newChild, beforeChild);
@@ -158,7 +158,7 @@ void RenderTextControl::hitInnerTextElement(HitTestResult& result, const LayoutP
result.setLocalPoint(localPoint);
}
-static const char* fontFamiliesWithInvalidCharWidth[] = {
+static const char* const fontFamiliesWithInvalidCharWidth[] = {
"American Typewriter",
"Arial Hebrew",
"Chalkboard",
@@ -295,9 +295,4 @@ RenderObject* RenderTextControl::layoutSpecialExcludedChild(bool relayoutChildre
return placeholderRenderer;
}
-bool RenderTextControl::canBeReplacedWithInlineRunIn() const
-{
- return false;
-}
-
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderTextControl.h b/chromium/third_party/WebKit/Source/core/rendering/RenderTextControl.h
index e4af77a46ea..6269af8d7e0 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderTextControl.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderTextControl.h
@@ -58,7 +58,6 @@ protected:
virtual float getAvgCharWidth(AtomicString family);
virtual LayoutUnit preferredContentLogicalWidth(float charWidth) const = 0;
virtual LayoutUnit computeControlLogicalHeight(LayoutUnit lineHeight, LayoutUnit nonContentHeight) const = 0;
- virtual RenderStyle* textBaseStyle() const = 0;
virtual void updateFromElement();
virtual void computeLogicalHeight(LayoutUnit logicalHeight, LayoutUnit logicalTop, LogicalExtentComputedValues&) const OVERRIDE;
@@ -78,31 +77,15 @@ private:
virtual void removeLeftoverAnonymousBlock(RenderBlock*) { }
virtual bool avoidsFloats() const { return true; }
virtual bool canHaveGeneratedChildren() const OVERRIDE { return false; }
- virtual bool canBeReplacedWithInlineRunIn() const OVERRIDE;
virtual void addChild(RenderObject* newChild, RenderObject* beforeChild = 0) OVERRIDE FINAL;
virtual void addFocusRingRects(Vector<IntRect>&, const LayoutPoint& additionalOffset, const RenderLayerModelObject* paintContainer = 0) OVERRIDE;
virtual bool canBeProgramaticallyScrolled() const { return true; }
-
- virtual bool requiresForcedStyleRecalcPropagation() const { return true; }
};
-inline RenderTextControl* toRenderTextControl(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isTextControl());
- return static_cast<RenderTextControl*>(object);
-}
-
-inline const RenderTextControl* toRenderTextControl(const RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isTextControl());
- return static_cast<const RenderTextControl*>(object);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toRenderTextControl(const RenderTextControl*);
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderTextControl, isTextControl());
// Renderer for our inner container, for <search> and others.
// We can't use RenderFlexibleBox directly, because flexboxes have a different
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderTextControlMultiLine.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderTextControlMultiLine.cpp
index 6faf2acd96c..01fa15a7d4d 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderTextControlMultiLine.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderTextControlMultiLine.cpp
@@ -83,15 +83,11 @@ PassRefPtr<RenderStyle> RenderTextControlMultiLine::createInnerTextStyle(const R
textBlockStyle->inheritFrom(startStyle);
adjustInnerTextStyle(textBlockStyle.get());
textBlockStyle->setDisplay(BLOCK);
+ textBlockStyle->setUnique();
return textBlockStyle.release();
}
-RenderStyle* RenderTextControlMultiLine::textBaseStyle() const
-{
- return style();
-}
-
RenderObject* RenderTextControlMultiLine::layoutSpecialExcludedChild(bool relayoutChildren, SubtreeLayoutScope& layoutScope)
{
RenderObject* placeholderRenderer = RenderTextControl::layoutSpecialExcludedChild(relayoutChildren, layoutScope);
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderTextControlMultiLine.h b/chromium/third_party/WebKit/Source/core/rendering/RenderTextControlMultiLine.h
index 6ca01671bd4..3371c2602b0 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderTextControlMultiLine.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderTextControlMultiLine.h
@@ -41,21 +41,15 @@ private:
virtual float getAvgCharWidth(AtomicString family);
virtual LayoutUnit preferredContentLogicalWidth(float charWidth) const;
virtual LayoutUnit computeControlLogicalHeight(LayoutUnit lineHeight, LayoutUnit nonContentHeight) const OVERRIDE;
- virtual int baselinePosition(FontBaseline, bool firstLine, LineDirectionMode, LinePositionMode = PositionOnContainingLine) const;
+ // We override the two baseline functions because we want our baseline to be the bottom of our margin box.
+ virtual int baselinePosition(FontBaseline, bool firstLine, LineDirectionMode, LinePositionMode = PositionOnContainingLine) const OVERRIDE;
+ virtual int inlineBlockBaseline(LineDirectionMode) const OVERRIDE { return -1; }
- virtual RenderStyle* textBaseStyle() const;
virtual PassRefPtr<RenderStyle> createInnerTextStyle(const RenderStyle* startStyle) const;
virtual RenderObject* layoutSpecialExcludedChild(bool relayoutChildren, SubtreeLayoutScope&);
};
-inline RenderTextControlMultiLine* toRenderTextControlMultiLine(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isTextArea());
- return static_cast<RenderTextControlMultiLine*>(object);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toRenderTextControlMultiLine(const RenderTextControlMultiLine*);
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderTextControlMultiLine, isTextArea());
}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderTextControlSingleLine.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderTextControlSingleLine.cpp
index 6ad20efa7c5..04ecfea2fc8 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderTextControlSingleLine.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderTextControlSingleLine.cpp
@@ -28,12 +28,13 @@
#include "core/dom/shadow/ShadowRoot.h"
#include "core/editing/FrameSelection.h"
#include "core/html/shadow/ShadowElementNames.h"
-#include "core/page/Frame.h"
-#include "core/platform/PlatformKeyboardEvent.h"
-#include "core/platform/graphics/SimpleFontData.h"
+#include "core/frame/Frame.h"
#include "core/rendering/HitTestResult.h"
+#include "core/rendering/LayoutRectRecorder.h"
#include "core/rendering/RenderLayer.h"
#include "core/rendering/RenderTheme.h"
+#include "platform/PlatformKeyboardEvent.h"
+#include "platform/fonts/SimpleFontData.h"
using namespace std;
@@ -53,6 +54,11 @@ RenderTextControlSingleLine::~RenderTextControlSingleLine()
{
}
+inline Element* RenderTextControlSingleLine::containerElement() const
+{
+ return inputElement()->userAgentShadowRoot()->getElementById(ShadowElementNames::textFieldContainer());
+}
+
inline Element* RenderTextControlSingleLine::editingViewPortElement() const
{
return inputElement()->userAgentShadowRoot()->getElementById(ShadowElementNames::editingViewPort());
@@ -63,12 +69,6 @@ inline HTMLElement* RenderTextControlSingleLine::innerSpinButtonElement() const
return toHTMLElement(inputElement()->userAgentShadowRoot()->getElementById(ShadowElementNames::spinButton()));
}
-RenderStyle* RenderTextControlSingleLine::textBaseStyle() const
-{
- Element* viewPort = editingViewPortElement();
- return viewPort ? viewPort->renderer()->style() : style();
-}
-
void RenderTextControlSingleLine::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
{
RenderTextControl::paint(paintInfo, paintOffset);
@@ -95,6 +95,7 @@ LayoutUnit RenderTextControlSingleLine::computeLogicalHeightLimit() const
void RenderTextControlSingleLine::layout()
{
+ LayoutRectRecorder recorder(*this);
SubtreeLayoutScope layoutScope(this);
// FIXME: We should remove the height-related hacks in layout() and
@@ -123,7 +124,7 @@ void RenderTextControlSingleLine::layout()
RenderBlockFlow::layoutBlock(false);
- HTMLElement* container = containerElement();
+ Element* container = containerElement();
RenderBox* containerRenderer = container ? container->renderBox() : 0;
// Set the text block height
@@ -217,7 +218,7 @@ bool RenderTextControlSingleLine::nodeAtPoint(const HitTestRequest& request, Hit
// - we hit a node inside the inner text element,
// - we hit the <input> element (e.g. we're over the border or padding), or
// - we hit regions not in any decoration buttons.
- HTMLElement* container = containerElement();
+ Element* container = containerElement();
if (result.innerNode()->isDescendantOf(innerTextElement()) || result.innerNode() == node() || (container && container == result.innerNode())) {
LayoutPoint pointInParent = locationInContainer.point();
if (container && editingViewPortElement()) {
@@ -243,7 +244,7 @@ void RenderTextControlSingleLine::styleDidChange(StyleDifference diff, const Ren
viewPortRenderer->style()->setHeight(Length());
viewPortRenderer->style()->setWidth(Length());
}
- HTMLElement* container = containerElement();
+ Element* container = containerElement();
if (RenderObject* containerRenderer = container ? container->renderer() : 0) {
containerRenderer->style()->setHeight(Length());
containerRenderer->style()->setWidth(Length());
@@ -371,6 +372,7 @@ PassRefPtr<RenderStyle> RenderTextControlSingleLine::createInnerTextStyle(const
textBlockStyle->setLineHeight(RenderStyle::initialLineHeight());
textBlockStyle->setDisplay(BLOCK);
+ textBlockStyle->setUnique();
return textBlockStyle.release();
}
@@ -385,9 +387,8 @@ void RenderTextControlSingleLine::autoscroll(const IntPoint& position)
RenderBox* renderer = innerTextElement()->renderBox();
if (!renderer)
return;
- RenderLayer* layer = renderer->layer();
- if (layer)
- layer->autoscroll(position);
+
+ renderer->autoscroll(position);
}
int RenderTextControlSingleLine::scrollWidth() const
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderTextControlSingleLine.h b/chromium/third_party/WebKit/Source/core/rendering/RenderTextControlSingleLine.h
index 9a1bd461a2e..64a07cc74fc 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderTextControlSingleLine.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderTextControlSingleLine.h
@@ -42,7 +42,7 @@ public:
protected:
virtual void centerContainerIfNeeded(RenderBox*) const { }
virtual LayoutUnit computeLogicalHeightLimit() const;
- HTMLElement* containerElement() const;
+ Element* containerElement() const;
Element* editingViewPortElement() const;
HTMLInputElement* inputElement() const;
virtual void updateFromElement() OVERRIDE;
@@ -74,8 +74,6 @@ private:
virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle);
- virtual RenderStyle* textBaseStyle() const;
-
bool textShouldBeTruncated() const;
HTMLElement* innerSpinButtonElement() const;
@@ -84,19 +82,7 @@ private:
LayoutUnit m_desiredInnerTextLogicalHeight;
};
-inline HTMLElement* RenderTextControlSingleLine::containerElement() const
-{
- return inputElement()->containerElement();
-}
-
-inline RenderTextControlSingleLine* toRenderTextControlSingleLine(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isTextField());
- return static_cast<RenderTextControlSingleLine*>(object);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toRenderTextControlSingleLine(const RenderTextControlSingleLine*);
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderTextControlSingleLine, isTextField());
// ----------------------------
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderTextFragment.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderTextFragment.cpp
index d36e9c7f42b..759eb9dd368 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderTextFragment.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderTextFragment.cpp
@@ -24,6 +24,7 @@
#include "core/rendering/RenderTextFragment.h"
#include "core/dom/Text.h"
+#include "core/rendering/HitTestResult.h"
#include "core/rendering/RenderBlock.h"
namespace WebCore {
@@ -49,6 +50,15 @@ RenderTextFragment::~RenderTextFragment()
{
}
+RenderText* RenderTextFragment::firstRenderTextInFirstLetter() const
+{
+ for (RenderObject* current = m_firstLetter; current; current = current->nextInPreOrder(m_firstLetter)) {
+ if (current->isText())
+ return toRenderText(current);
+ }
+ return 0;
+}
+
PassRefPtr<StringImpl> RenderTextFragment::originalText() const
{
Node* e = node();
@@ -122,4 +132,20 @@ RenderBlock* RenderTextFragment::blockForAccompanyingFirstLetter() const
return 0;
}
+void RenderTextFragment::updateHitTestResult(HitTestResult& result, const LayoutPoint& point)
+{
+ if (result.innerNode())
+ return;
+
+ RenderObject::updateHitTestResult(result, point);
+ if (m_firstLetter || !node())
+ return;
+ RenderObject* nodeRenderer = node()->renderer();
+ if (!nodeRenderer || !nodeRenderer->isText() || !toRenderText(nodeRenderer)->isTextFragment())
+ return;
+
+ if (isDescendantOf(toRenderTextFragment(nodeRenderer)->m_firstLetter))
+ result.setIsFirstLetter(true);
+}
+
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderTextFragment.h b/chromium/third_party/WebKit/Source/core/rendering/RenderTextFragment.h
index 31506166905..44bbfe81f6d 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderTextFragment.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderTextFragment.h
@@ -43,9 +43,11 @@ public:
unsigned start() const { return m_start; }
unsigned end() const { return m_end; }
+ virtual unsigned textStartOffset() const OVERRIDE { return start(); }
RenderObject* firstLetter() const { return m_firstLetter; }
void setFirstLetter(RenderObject* firstLetter) { m_firstLetter = firstLetter; }
+ RenderText* firstRenderTextInFirstLetter() const;
StringImpl* contentString() const { return m_contentString.get(); }
virtual PassRefPtr<StringImpl> originalText() const;
@@ -62,6 +64,7 @@ private:
virtual UChar previousCharacter() const;
RenderBlock* blockForAccompanyingFirstLetter() const;
+ virtual void updateHitTestResult(HitTestResult&, const LayoutPoint&) OVERRIDE;
unsigned m_start;
unsigned m_end;
@@ -69,20 +72,7 @@ private:
RenderObject* m_firstLetter;
};
-inline RenderTextFragment* toRenderTextFragment(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || toRenderText(object)->isTextFragment());
- return static_cast<RenderTextFragment*>(object);
-}
-
-inline const RenderTextFragment* toRenderTextFragment(const RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || toRenderText(object)->isTextFragment());
- return static_cast<const RenderTextFragment*>(object);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toRenderTextFragment(const RenderTextFragment*);
+DEFINE_TYPE_CASTS(RenderTextFragment, RenderObject, object, toRenderText(object)->isTextFragment(), toRenderText(object).isTextFragment());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderTextTrackCue.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderTextTrackCue.cpp
deleted file mode 100644
index e54e923cf1b..00000000000
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderTextTrackCue.cpp
+++ /dev/null
@@ -1,293 +0,0 @@
-/*
- * Copyright (C) 2012 Victor Carbune (victor@rosedu.org)
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/rendering/RenderTextTrackCue.h"
-
-#include "core/html/track/TextTrackCue.h"
-#include "core/html/track/TextTrackCueGeneric.h"
-#include "core/rendering/RenderView.h"
-
-namespace WebCore {
-
-RenderTextTrackCue::RenderTextTrackCue(TextTrackCueBox* element)
- : RenderBlockFlow(element)
- , m_cue(element->getCue())
-{
-}
-
-void RenderTextTrackCue::layout()
-{
- RenderBlockFlow::layout();
-
-#if ENABLE(WEBVTT_REGIONS)
- // If WebVTT Regions are used, the regular WebVTT layout algorithm is no
- // longer necessary, since cues having the region parameter set do not have
- // any positioning parameters. Also, in this case, the regions themselves
- // have positioning information.
- if (!m_cue->regionId().isEmpty())
- return;
-#endif
-
- LayoutStateMaintainer statePusher(view(), this, locationOffset(), hasTransform() || hasReflection() || style()->isFlippedBlocksWritingMode());
-
- if (m_cue->cueType()== TextTrackCue::WebVTT) {
- if (m_cue->snapToLines())
- repositionCueSnapToLinesSet();
- else
- repositionCueSnapToLinesNotSet();
- } else
- repositionGenericCue();
-
- statePusher.pop();
-}
-
-bool RenderTextTrackCue::findFirstLineBox(InlineFlowBox*& firstLineBox)
-{
- if (firstChild()->isRenderInline())
- firstLineBox = toRenderInline(firstChild())->firstLineBox();
- else
- return false;
-
- return true;
-}
-
-bool RenderTextTrackCue::initializeLayoutParameters(InlineFlowBox* firstLineBox, LayoutUnit& step, LayoutUnit& position)
-{
- ASSERT(firstChild());
-
- RenderBlock* parentBlock = containingBlock();
-
- // 1. Horizontal: Let step be the height of the first line box in boxes.
- // Vertical: Let step be the width of the first line box in boxes.
- step = m_cue->getWritingDirection() == TextTrackCue::Horizontal ? firstLineBox->height() : firstLineBox->width();
-
- // 2. If step is zero, then jump to the step labeled done positioning below.
- if (!step)
- return false;
-
- // 3. Let line position be the text track cue computed line position.
- int linePosition = m_cue->calculateComputedLinePosition();
-
- // 4. Vertical Growing Left: Add one to line position then negate it.
- if (m_cue->getWritingDirection() == TextTrackCue::VerticalGrowingLeft)
- linePosition = -(linePosition + 1);
-
- // 5. Let position be the result of multiplying step and line position.
- position = step * linePosition;
-
- // 6. Vertical Growing Left: Decrease position by the width of the
- // bounding box of the boxes in boxes, then increase position by step.
- if (m_cue->getWritingDirection() == TextTrackCue::VerticalGrowingLeft) {
- position -= width();
- position += step;
- }
-
- // 7. If line position is less than zero...
- if (linePosition < 0) {
- // Horizontal / Vertical: ... then increase position by the
- // height / width of the video's rendering area ...
- position += m_cue->getWritingDirection() == TextTrackCue::Horizontal ? parentBlock->height() : parentBlock->width();
-
- // ... and negate step.
- step = -step;
- }
-
- return true;
-}
-
-void RenderTextTrackCue::placeBoxInDefaultPosition(LayoutUnit position, bool& switched)
-{
- // 8. Move all boxes in boxes ...
- if (m_cue->getWritingDirection() == TextTrackCue::Horizontal)
- // Horizontal: ... down by the distance given by position
- setY(y() + position);
- else
- // Vertical: ... right by the distance given by position
- setX(x() + position);
-
- // 9. Default: Remember the position of all the boxes in boxes as their
- // default position.
- m_fallbackPosition = FloatPoint(x(), y());
-
- // 10. Let switched be false.
- switched = false;
-}
-
-bool RenderTextTrackCue::isOutside() const
-{
- return !containingBlock()->absoluteBoundingBoxRect().contains(absoluteContentBox());
-}
-
-bool RenderTextTrackCue::isOverlapping() const
-{
- for (RenderObject* box = previousSibling(); box; box = box->previousSibling()) {
- IntRect boxRect = box->absoluteBoundingBoxRect();
-
- if (absoluteBoundingBoxRect().intersects(boxRect))
- return true;
- }
-
- return false;
-}
-
-bool RenderTextTrackCue::shouldSwitchDirection(InlineFlowBox* firstLineBox, LayoutUnit step) const
-{
- LayoutUnit top = y();
- LayoutUnit left = x();
- LayoutUnit bottom = top + firstLineBox->height();
- LayoutUnit right = left + firstLineBox->width();
-
- // 12. Horizontal: If step is negative and the top of the first line
- // box in boxes is now above the top of the video's rendering area,
- // or if step is positive and the bottom of the first line box in
- // boxes is now below the bottom of the video's rendering area, jump
- // to the step labeled switch direction.
- LayoutUnit parentHeight = containingBlock()->height();
- if (m_cue->getWritingDirection() == TextTrackCue::Horizontal && ((step < 0 && top < 0) || (step > 0 && bottom > parentHeight)))
- return true;
-
- // 12. Vertical: If step is negative and the left edge of the first line
- // box in boxes is now to the left of the left edge of the video's
- // rendering area, or if step is positive and the right edge of the
- // first line box in boxes is now to the right of the right edge of
- // the video's rendering area, jump to the step labeled switch direction.
- LayoutUnit parentWidth = containingBlock()->width();
- if (m_cue->getWritingDirection() != TextTrackCue::Horizontal && ((step < 0 && left < 0) || (step > 0 && right > parentWidth)))
- return true;
-
- return false;
-}
-
-void RenderTextTrackCue::moveBoxesByStep(LayoutUnit step)
-{
- // 13. Horizontal: Move all the boxes in boxes down by the distance
- // given by step. (If step is negative, then this will actually
- // result in an upwards movement of the boxes in absolute terms.)
- if (m_cue->getWritingDirection() == TextTrackCue::Horizontal)
- setY(y() + step);
-
- // 13. Vertical: Move all the boxes in boxes right by the distance
- // given by step. (If step is negative, then this will actually
- // result in a leftwards movement of the boxes in absolute terms.)
- else
- setX(x() + step);
-}
-
-bool RenderTextTrackCue::switchDirection(bool& switched, LayoutUnit& step)
-{
- // 15. Switch direction: Move all the boxes in boxes back to their
- // default position as determined in the step above labeled default.
- setX(m_fallbackPosition.x());
- setY(m_fallbackPosition.y());
-
- // 16. If switched is true, jump to the step labeled done
- // positioning below.
- if (switched)
- return false;
-
- // 17. Negate step.
- step = -step;
-
- // 18. Set switched to true.
- switched = true;
- return true;
-}
-
-void RenderTextTrackCue::repositionCueSnapToLinesSet()
-{
- InlineFlowBox* firstLineBox;
- LayoutUnit step;
- LayoutUnit position;
-
- if (!findFirstLineBox(firstLineBox))
- return;
-
- if (!initializeLayoutParameters(firstLineBox, step, position))
- return;
-
- bool switched;
- placeBoxInDefaultPosition(position, switched);
-
- // 11. Step loop: If none of the boxes in boxes would overlap any of the boxes
- // in output and all the boxes in output are within the video's rendering area
- // then jump to the step labeled done positioning.
- while (isOutside() || isOverlapping()) {
- if (!shouldSwitchDirection(firstLineBox, step))
- // 13. Move all the boxes in boxes ...
- // 14. Jump back to the step labeled step loop.
- moveBoxesByStep(step);
- else if (!switchDirection(switched, step))
- break;
-
- // 19. Jump back to the step labeled step loop.
- }
-
- // Acommodate extra top and bottom padding, border or margin.
- // Note: this is supported only for internal UA styling, not through the cue selector.
- if (hasInlineDirectionBordersPaddingOrMargin()) {
- IntRect containerRect = containingBlock()->absoluteBoundingBoxRect();
- IntRect cueRect = absoluteBoundingBoxRect();
-
- int topOverflow = cueRect.y() - containerRect.y();
- int bottomOverflow = containerRect.y() + containerRect.height() - cueRect.y() - cueRect.height();
-
- int adjustment = 0;
- if (topOverflow < 0)
- adjustment = -topOverflow;
- else if (bottomOverflow < 0)
- adjustment = bottomOverflow;
-
- if (adjustment)
- setY(y() + adjustment);
- }
-}
-
-void RenderTextTrackCue::repositionGenericCue()
-{
- TextTrackCueGeneric* cue = static_cast<TextTrackCueGeneric*>(m_cue);
- if (!cue->useDefaultPosition())
- return;
-
- ASSERT(firstChild());
-
- InlineFlowBox* firstLineBox;
- if (!findFirstLineBox(firstLineBox))
- return;
-
- LayoutUnit parentWidth = containingBlock()->logicalWidth();
- LayoutUnit width = firstLineBox->width();
- LayoutUnit right = (parentWidth / 2) - (width / 2);
- setX(right);
-}
-
-void RenderTextTrackCue::repositionCueSnapToLinesNotSet()
-{
- // FIXME: Implement overlapping detection when snap-to-lines is not set. http://wkb.ug/84296
-}
-
-} // namespace WebCore
-
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderTextTrackCue.h b/chromium/third_party/WebKit/Source/core/rendering/RenderTextTrackCue.h
deleted file mode 100644
index fb71e4c3a7b..00000000000
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderTextTrackCue.h
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * Copyright (C) 2012 Victor Carbune (victor@rosedu.org)
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef RenderTextTrackCue_h
-#define RenderTextTrackCue_h
-
-#include "core/platform/graphics/FloatPoint.h"
-#include "core/rendering/RenderBlockFlow.h"
-#include "core/rendering/RenderInline.h"
-
-namespace WebCore {
-
-class TextTrackCueBox;
-
-class RenderTextTrackCue FINAL : public RenderBlockFlow {
-public:
- explicit RenderTextTrackCue(TextTrackCueBox*);
-
-private:
- virtual void layout() OVERRIDE;
- virtual bool supportsPartialLayout() const OVERRIDE { return false; }
-
- bool isOutside() const;
- bool isOverlapping() const;
- bool shouldSwitchDirection(InlineFlowBox*, LayoutUnit) const;
-
- void moveBoxesByStep(LayoutUnit);
- bool switchDirection(bool&, LayoutUnit&);
-
- bool findFirstLineBox(InlineFlowBox*&);
- bool initializeLayoutParameters(InlineFlowBox*, LayoutUnit&, LayoutUnit&);
- void placeBoxInDefaultPosition(LayoutUnit, bool&);
- void repositionCueSnapToLinesSet();
- void repositionCueSnapToLinesNotSet();
- void repositionGenericCue();
-
- TextTrackCue* m_cue;
- FloatPoint m_fallbackPosition;
-};
-
-} // namespace WebCore
-
-#endif // RenderTextTrackCue_h
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderTheme.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderTheme.cpp
index d0a7b19d71d..90c56f77dbd 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderTheme.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderTheme.cpp
@@ -24,6 +24,7 @@
#include "CSSValueKeywords.h"
#include "HTMLNames.h"
+#include "InputTypeNames.h"
#include "RuntimeEnabledFeatures.h"
#include "core/dom/Document.h"
#include "core/dom/shadow/ElementShadow.h"
@@ -34,26 +35,25 @@
#include "core/html/HTMLInputElement.h"
#include "core/html/HTMLMeterElement.h"
#include "core/html/HTMLOptionElement.h"
-#include "core/html/forms/InputTypeNames.h"
#include "core/html/parser/HTMLParserIdioms.h"
#include "core/html/shadow/MediaControlElements.h"
#include "core/html/shadow/ShadowElementNames.h"
#include "core/html/shadow/SpinButtonElement.h"
#include "core/html/shadow/TextControlInnerElements.h"
#include "core/page/FocusController.h"
-#include "core/page/Frame.h"
+#include "core/frame/Frame.h"
#include "core/page/Page.h"
-#include "core/page/Settings.h"
-#include "core/platform/FileSystem.h"
-#include "core/platform/FloatConversion.h"
-#include "core/platform/LocalizedStrings.h"
-#include "core/platform/graphics/FontSelector.h"
-#include "core/platform/graphics/GraphicsContextStateSaver.h"
-#include "core/platform/graphics/StringTruncator.h"
+#include "core/frame/Settings.h"
#include "core/rendering/PaintInfo.h"
#include "core/rendering/RenderMeter.h"
#include "core/rendering/RenderView.h"
#include "core/rendering/style/RenderStyle.h"
+#include "platform/FileMetadata.h"
+#include "platform/FloatConversion.h"
+#include "platform/fonts/FontSelector.h"
+#include "platform/graphics/GraphicsContextStateSaver.h"
+#include "platform/text/PlatformLocale.h"
+#include "platform/text/StringTruncator.h"
#include "public/platform/Platform.h"
#include "public/platform/WebFallbackThemeEngine.h"
#include "public/platform/WebRect.h"
@@ -75,16 +75,16 @@ static Color& customFocusRingColor()
return color;
}
-static WebKit::WebFallbackThemeEngine::State getWebFallbackThemeState(const RenderTheme* theme, const RenderObject* o)
+static blink::WebFallbackThemeEngine::State getWebFallbackThemeState(const RenderTheme* theme, const RenderObject* o)
{
if (!theme->isEnabled(o))
- return WebKit::WebFallbackThemeEngine::StateDisabled;
+ return blink::WebFallbackThemeEngine::StateDisabled;
if (theme->isPressed(o))
- return WebKit::WebFallbackThemeEngine::StatePressed;
+ return blink::WebFallbackThemeEngine::StatePressed;
if (theme->isHovered(o))
- return WebKit::WebFallbackThemeEngine::StateHover;
+ return blink::WebFallbackThemeEngine::StateHover;
- return WebKit::WebFallbackThemeEngine::StateNormal;
+ return blink::WebFallbackThemeEngine::StateNormal;
}
RenderTheme::RenderTheme()
@@ -103,7 +103,7 @@ void RenderTheme::adjustStyle(RenderStyle* style, Element* e, const CachedUAStyl
|| style->display() == TABLE_ROW || style->display() == TABLE_COLUMN_GROUP || style->display() == TABLE_COLUMN
|| style->display() == TABLE_CELL || style->display() == TABLE_CAPTION)
style->setDisplay(INLINE_BLOCK);
- else if (style->display() == COMPACT || style->display() == RUN_IN || style->display() == LIST_ITEM || style->display() == TABLE)
+ else if (style->display() == LIST_ITEM || style->display() == TABLE)
style->setDisplay(BLOCK);
if (uaStyle.hasAppearance && isControlStyled(style, uaStyle)) {
@@ -132,7 +132,7 @@ void RenderTheme::adjustStyle(RenderStyle* style, Element* e, const CachedUAStyl
case ButtonPart: {
// Border
LengthBox borderBox(style->borderTopWidth(), style->borderRightWidth(), style->borderBottomWidth(), style->borderLeftWidth());
- borderBox = m_platformTheme->controlBorder(part, style->font(), borderBox, style->effectiveZoom());
+ borderBox = m_platformTheme->controlBorder(part, style->font().fontDescription(), borderBox, style->effectiveZoom());
if (borderBox.top().value() != static_cast<int>(style->borderTopWidth())) {
if (borderBox.top().value())
style->setBorderTopWidth(borderBox.top().value());
@@ -161,7 +161,7 @@ void RenderTheme::adjustStyle(RenderStyle* style, Element* e, const CachedUAStyl
}
// Padding
- LengthBox paddingBox = m_platformTheme->controlPadding(part, style->font(), style->paddingBox(), style->effectiveZoom());
+ LengthBox paddingBox = m_platformTheme->controlPadding(part, style->font().fontDescription(), style->paddingBox(), style->effectiveZoom());
if (paddingBox != style->paddingBox())
style->setPaddingBox(paddingBox);
@@ -172,21 +172,21 @@ void RenderTheme::adjustStyle(RenderStyle* style, Element* e, const CachedUAStyl
// Width / Height
// The width and height here are affected by the zoom.
// FIXME: Check is flawed, since it doesn't take min-width/max-width into account.
- LengthSize controlSize = m_platformTheme->controlSize(part, style->font(), LengthSize(style->width(), style->height()), style->effectiveZoom());
+ LengthSize controlSize = m_platformTheme->controlSize(part, style->font().fontDescription(), LengthSize(style->width(), style->height()), style->effectiveZoom());
if (controlSize.width() != style->width())
style->setWidth(controlSize.width());
if (controlSize.height() != style->height())
style->setHeight(controlSize.height());
// Min-Width / Min-Height
- LengthSize minControlSize = m_platformTheme->minimumControlSize(part, style->font(), style->effectiveZoom());
+ LengthSize minControlSize = m_platformTheme->minimumControlSize(part, style->font().fontDescription(), style->effectiveZoom());
if (minControlSize.width() != style->minWidth())
style->setMinWidth(minControlSize.width());
if (minControlSize.height() != style->minHeight())
style->setMinHeight(minControlSize.height());
// Font
- FontDescription controlFont = m_platformTheme->controlFont(part, style->font(), style->effectiveZoom());
+ FontDescription controlFont = m_platformTheme->controlFont(part, style->font().fontDescription(), style->effectiveZoom());
if (controlFont != style->font().fontDescription()) {
// Reset our line-height
style->setLineHeight(RenderStyle::initialLineHeight());
@@ -215,28 +215,10 @@ void RenderTheme::adjustStyle(RenderStyle* style, Element* e, const CachedUAStyl
case InnerSpinButtonPart:
return adjustInnerSpinButtonStyle(style, e);
#endif
- case TextFieldPart:
- return adjustTextFieldStyle(style, e);
- case TextAreaPart:
- return adjustTextAreaStyle(style, e);
case MenulistPart:
return adjustMenuListStyle(style, e);
case MenulistButtonPart:
return adjustMenuListButtonStyle(style, e);
- case MediaPlayButtonPart:
- case MediaCurrentTimePart:
- case MediaTimeRemainingPart:
- case MediaEnterFullscreenButtonPart:
- case MediaExitFullscreenButtonPart:
- case MediaMuteButtonPart:
- case MediaVolumeSliderContainerPart:
- return adjustMediaControlStyle(style, e);
- case MediaSliderPart:
- case MediaVolumeSliderPart:
- case MediaFullScreenVolumeSliderPart:
- case SliderHorizontalPart:
- case SliderVerticalPart:
- return adjustSliderTrackStyle(style, e);
case SliderThumbHorizontalPart:
case SliderThumbVerticalPart:
return adjustSliderThumbStyle(style, e);
@@ -248,14 +230,6 @@ void RenderTheme::adjustStyle(RenderStyle* style, Element* e, const CachedUAStyl
return adjustSearchFieldDecorationStyle(style, e);
case SearchFieldResultsDecorationPart:
return adjustSearchFieldResultsDecorationStyle(style, e);
- case ProgressBarPart:
- return adjustProgressBarStyle(style, e);
- case MeterPart:
- case RelevancyLevelIndicatorPart:
- case ContinuousCapacityLevelIndicatorPart:
- case DiscreteCapacityLevelIndicatorPart:
- case RatingLevelIndicatorPart:
- return adjustMeterStyle(style, e);
#if ENABLE(INPUT_SPEECH)
case InputSpeechButtonPart:
return adjustInputFieldSpeechButtonStyle(style, e);
@@ -497,7 +471,7 @@ String RenderTheme::extraDefaultStyleSheet()
if (RuntimeEnabledFeatures::dialogElementEnabled()) {
runtimeCSS.appendLiteral("dialog:not([open]) { display: none; }");
runtimeCSS.appendLiteral("dialog { position: absolute; left: 0; right: 0; width: -webkit-fit-content; height: -webkit-fit-content; margin: auto; border: solid; padding: 1em; background: white; color: black;}");
- runtimeCSS.appendLiteral("dialog::backdrop { background: rgba(0,0,0,0.1); }");
+ runtimeCSS.appendLiteral("dialog::backdrop { position: fixed; top: 0; right: 0; bottom: 0; left: 0; background: rgba(0,0,0,0.1); }");
}
return runtimeCSS.toString();
@@ -697,9 +671,6 @@ void RenderTheme::adjustRepaintRect(const RenderObject* o, IntRect& r)
{
#if USE(NEW_THEME)
m_platformTheme->inflateControlPaintRect(o->style()->appearance(), controlStatesForRenderer(o), r, o->style()->effectiveZoom());
-#else
- UNUSED_PARAM(o);
- UNUSED_PARAM(r);
#endif
}
@@ -893,10 +864,6 @@ void RenderTheme::adjustRadioStyle(RenderStyle* style, Element*) const
void RenderTheme::adjustButtonStyle(RenderStyle* style, Element*) const
{
- // Most platforms will completely honor all CSS, and so we have no need to
- // adjust the style at all by default. We will still allow the theme a crack
- // at setting up a desired vertical size.
- setButtonSize(style);
}
void RenderTheme::adjustInnerSpinButtonStyle(RenderStyle*, Element*) const
@@ -904,14 +871,6 @@ void RenderTheme::adjustInnerSpinButtonStyle(RenderStyle*, Element*) const
}
#endif
-void RenderTheme::adjustTextFieldStyle(RenderStyle*, Element*) const
-{
-}
-
-void RenderTheme::adjustTextAreaStyle(RenderStyle*, Element*) const
-{
-}
-
void RenderTheme::adjustMenuListStyle(RenderStyle*, Element*) const
{
}
@@ -928,10 +887,6 @@ bool RenderTheme::paintInputFieldSpeechButton(RenderObject* object, const PaintI
}
#endif
-void RenderTheme::adjustMeterStyle(RenderStyle* style, Element*) const
-{
-}
-
IntSize RenderTheme::meterSizeForBounds(const RenderMeter*, const IntRect& bounds) const
{
return bounds.size();
@@ -947,11 +902,6 @@ bool RenderTheme::paintMeter(RenderObject*, const PaintInfo&, const IntRect&)
return true;
}
-LayoutUnit RenderTheme::sliderTickSnappingThreshold() const
-{
- return 5;
-}
-
void RenderTheme::paintSliderTicks(RenderObject* o, const PaintInfo& paintInfo, const IntRect& rect)
{
Node* node = o->node();
@@ -1041,10 +991,6 @@ double RenderTheme::animationDurationForProgressBar(RenderProgress*) const
return 0;
}
-void RenderTheme::adjustProgressBarStyle(RenderStyle*, Element*) const
-{
-}
-
bool RenderTheme::shouldHaveSpinButton(HTMLInputElement* inputElement) const
{
return inputElement->isSteppable() && !inputElement->isRangeControl();
@@ -1054,14 +1000,6 @@ void RenderTheme::adjustMenuListButtonStyle(RenderStyle*, Element*) const
{
}
-void RenderTheme::adjustMediaControlStyle(RenderStyle*, Element*) const
-{
-}
-
-void RenderTheme::adjustSliderTrackStyle(RenderStyle*, Element*) const
-{
-}
-
void RenderTheme::adjustSliderThumbStyle(RenderStyle* style, Element* element) const
{
adjustSliderThumbSize(style, element);
@@ -1206,25 +1144,20 @@ Color RenderTheme::focusRingColor()
return customFocusRingColor().isValid() ? customFocusRingColor() : theme().platformFocusRingColor();
}
-String RenderTheme::fileListDefaultLabel(bool multipleFilesAllowed) const
-{
- if (multipleFilesAllowed)
- return fileButtonNoFilesSelectedLabel();
- return fileButtonNoFileSelectedLabel();
-}
-
-String RenderTheme::fileListNameForWidth(const FileList* fileList, const Font& font, int width, bool multipleFilesAllowed) const
+String RenderTheme::fileListNameForWidth(Locale& locale, const FileList* fileList, const Font& font, int width) const
{
if (width <= 0)
return String();
String string;
- if (fileList->isEmpty())
- string = fileListDefaultLabel(multipleFilesAllowed);
- else if (fileList->length() == 1)
+ if (fileList->isEmpty()) {
+ string = locale.queryString(blink::WebLocalizedString::FileButtonNoFileSelectedLabel);
+ } else if (fileList->length() == 1) {
string = fileList->item(0)->name();
- else
- return StringTruncator::rightTruncate(multipleFileUploadText(fileList->length()), width, font, StringTruncator::EnableRoundingHacks);
+ } else {
+ // FIXME: Localization of fileList->length().
+ return StringTruncator::rightTruncate(locale.queryString(blink::WebLocalizedString::MultipleFileUploadText, String::number(fileList->length())), width, font, StringTruncator::EnableRoundingHacks);
+ }
return StringTruncator::centerTruncate(string, width, font, StringTruncator::EnableRoundingHacks);
}
@@ -1236,26 +1169,26 @@ bool RenderTheme::shouldOpenPickerWithF4Key() const
bool RenderTheme::supportsDataListUI(const AtomicString& type) const
{
- return type == InputTypeNames::text() || type == InputTypeNames::search() || type == InputTypeNames::url()
- || type == InputTypeNames::telephone() || type == InputTypeNames::email() || type == InputTypeNames::number()
- || type == InputTypeNames::color()
- || type == InputTypeNames::date()
- || type == InputTypeNames::datetime()
- || type == InputTypeNames::datetimelocal()
- || type == InputTypeNames::month()
- || type == InputTypeNames::week()
- || type == InputTypeNames::time()
- || type == InputTypeNames::range();
+ return type == InputTypeNames::text || type == InputTypeNames::search || type == InputTypeNames::url
+ || type == InputTypeNames::tel || type == InputTypeNames::email || type == InputTypeNames::number
+ || type == InputTypeNames::color
+ || type == InputTypeNames::date
+ || type == InputTypeNames::datetime
+ || type == InputTypeNames::datetime_local
+ || type == InputTypeNames::month
+ || type == InputTypeNames::week
+ || type == InputTypeNames::time
+ || type == InputTypeNames::range;
}
#if ENABLE(INPUT_MULTIPLE_FIELDS_UI)
bool RenderTheme::supportsCalendarPicker(const AtomicString& type) const
{
- return type == InputTypeNames::date()
- || type == InputTypeNames::datetime()
- || type == InputTypeNames::datetimelocal()
- || type == InputTypeNames::month()
- || type == InputTypeNames::week();
+ return type == InputTypeNames::date
+ || type == InputTypeNames::datetime
+ || type == InputTypeNames::datetime_local
+ || type == InputTypeNames::month
+ || type == InputTypeNames::week;
}
#endif
@@ -1302,8 +1235,8 @@ void RenderTheme::setSizeIfAuto(RenderStyle* style, const IntSize& size)
bool RenderTheme::paintCheckboxUsingFallbackTheme(RenderObject* o, const PaintInfo& i, const IntRect& r)
{
- WebKit::WebFallbackThemeEngine::ExtraParams extraParams;
- WebKit::WebCanvas* canvas = i.context->canvas();
+ blink::WebFallbackThemeEngine::ExtraParams extraParams;
+ blink::WebCanvas* canvas = i.context->canvas();
extraParams.button.checked = isChecked(o);
extraParams.button.indeterminate = isIndeterminate(o);
@@ -1318,7 +1251,7 @@ bool RenderTheme::paintCheckboxUsingFallbackTheme(RenderObject* o, const PaintIn
i.context->translate(-unzoomedRect.x(), -unzoomedRect.y());
}
- WebKit::Platform::current()->fallbackThemeEngine()->paint(canvas, WebKit::WebFallbackThemeEngine::PartCheckbox, getWebFallbackThemeState(this, o), WebKit::WebRect(unzoomedRect), &extraParams);
+ blink::Platform::current()->fallbackThemeEngine()->paint(canvas, blink::WebFallbackThemeEngine::PartCheckbox, getWebFallbackThemeState(this, o), blink::WebRect(unzoomedRect), &extraParams);
return false;
}
@@ -1328,7 +1261,7 @@ void RenderTheme::adjustCheckboxStyleUsingFallbackTheme(RenderStyle* style, Elem
if (!style->width().isIntrinsicOrAuto() && !style->height().isAuto())
return;
- IntSize size = WebKit::Platform::current()->fallbackThemeEngine()->getSize(WebKit::WebFallbackThemeEngine::PartCheckbox);
+ IntSize size = blink::Platform::current()->fallbackThemeEngine()->getSize(blink::WebFallbackThemeEngine::PartCheckbox);
float zoomLevel = style->effectiveZoom();
size.setWidth(size.width() * zoomLevel);
size.setHeight(size.height() * zoomLevel);
@@ -1344,8 +1277,8 @@ void RenderTheme::adjustCheckboxStyleUsingFallbackTheme(RenderStyle* style, Elem
bool RenderTheme::paintRadioUsingFallbackTheme(RenderObject* o, const PaintInfo& i, const IntRect& r)
{
- WebKit::WebFallbackThemeEngine::ExtraParams extraParams;
- WebKit::WebCanvas* canvas = i.context->canvas();
+ blink::WebFallbackThemeEngine::ExtraParams extraParams;
+ blink::WebCanvas* canvas = i.context->canvas();
extraParams.button.checked = isChecked(o);
extraParams.button.indeterminate = isIndeterminate(o);
@@ -1360,7 +1293,7 @@ bool RenderTheme::paintRadioUsingFallbackTheme(RenderObject* o, const PaintInfo&
i.context->translate(-unzoomedRect.x(), -unzoomedRect.y());
}
- WebKit::Platform::current()->fallbackThemeEngine()->paint(canvas, WebKit::WebFallbackThemeEngine::PartRadio, getWebFallbackThemeState(this, o), WebKit::WebRect(unzoomedRect), &extraParams);
+ blink::Platform::current()->fallbackThemeEngine()->paint(canvas, blink::WebFallbackThemeEngine::PartRadio, getWebFallbackThemeState(this, o), blink::WebRect(unzoomedRect), &extraParams);
return false;
}
@@ -1370,7 +1303,7 @@ void RenderTheme::adjustRadioStyleUsingFallbackTheme(RenderStyle* style, Element
if (!style->width().isIntrinsicOrAuto() && !style->height().isAuto())
return;
- IntSize size = WebKit::Platform::current()->fallbackThemeEngine()->getSize(WebKit::WebFallbackThemeEngine::PartRadio);
+ IntSize size = blink::Platform::current()->fallbackThemeEngine()->getSize(blink::WebFallbackThemeEngine::PartRadio);
float zoomLevel = style->effectiveZoom();
size.setWidth(size.width() * zoomLevel);
size.setHeight(size.height() * zoomLevel);
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderTheme.h b/chromium/third_party/WebKit/Source/core/rendering/RenderTheme.h
index 8550b7b6ba9..30a1c143153 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderTheme.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderTheme.h
@@ -23,14 +23,14 @@
#ifndef RenderTheme_h
#define RenderTheme_h
-#include "core/platform/ScrollTypes.h"
#if USE(NEW_THEME)
-#include "core/platform/Theme.h"
+#include "platform/Theme.h"
#else
-#include "core/platform/ThemeTypes.h"
+#include "platform/ThemeTypes.h"
#endif
#include "core/rendering/RenderObject.h"
#include "core/rendering/style/CachedUAStyle.h"
+#include "platform/scroll/ScrollTypes.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefCounted.h"
#include "wtf/text/WTFString.h"
@@ -175,19 +175,13 @@ public:
// Media controls
virtual bool supportsClosedCaptioning() const { return false; }
virtual bool hasOwnDisabledStateHandlingFor(ControlPart) const { return false; }
- virtual bool usesMediaControlStatusDisplay() { return false; }
- virtual bool usesMediaControlVolumeSlider() const { return true; }
virtual bool usesVerticalVolumeSlider() const { return true; }
- virtual double mediaControlsFadeInDuration() { return 0.1; }
- virtual double mediaControlsFadeOutDuration() { return 0.3; }
virtual String formatMediaControlsTime(float time) const;
virtual String formatMediaControlsCurrentTime(float currentTime, float duration) const;
virtual IntSize meterSizeForBounds(const RenderMeter*, const IntRect&) const;
virtual bool supportsMeter(ControlPart) const;
- // Returns the threshold distance for snapping to a slider tick mark.
- virtual LayoutUnit sliderTickSnappingThreshold() const;
// Returns size of one slider tick mark for a horizontal track.
// For vertical tracks we rotate it and use it. i.e. Width is always length along the track.
virtual IntSize sliderTickSize() const = 0;
@@ -203,8 +197,7 @@ public:
virtual bool popsMenuByArrowKeys() const { return false; }
virtual bool popsMenuBySpaceOrReturn() const { return false; }
- virtual String fileListDefaultLabel(bool multipleFilesAllowed) const;
- virtual String fileListNameForWidth(const FileList*, const Font&, int width, bool multipleFilesAllowed) const;
+ virtual String fileListNameForWidth(Locale&, const FileList*, const Font&, int width) const;
virtual bool shouldOpenPickerWithF4Key() const;
@@ -237,16 +230,13 @@ protected:
virtual void adjustButtonStyle(RenderStyle*, Element*) const;
virtual bool paintButton(RenderObject*, const PaintInfo&, const IntRect&) { return true; }
- virtual void setButtonSize(RenderStyle*) const { }
virtual void adjustInnerSpinButtonStyle(RenderStyle*, Element*) const;
virtual bool paintInnerSpinButton(RenderObject*, const PaintInfo&, const IntRect&) { return true; }
#endif
- virtual void adjustTextFieldStyle(RenderStyle*, Element*) const;
virtual bool paintTextField(RenderObject*, const PaintInfo&, const IntRect&) { return true; }
- virtual void adjustTextAreaStyle(RenderStyle*, Element*) const;
virtual bool paintTextArea(RenderObject*, const PaintInfo&, const IntRect&) { return true; }
virtual void adjustMenuListStyle(RenderStyle*, Element*) const;
@@ -255,10 +245,8 @@ protected:
virtual void adjustMenuListButtonStyle(RenderStyle*, Element*) const;
virtual bool paintMenuListButton(RenderObject*, const PaintInfo&, const IntRect&) { return true; }
- virtual void adjustMeterStyle(RenderStyle*, Element*) const;
virtual bool paintMeter(RenderObject*, const PaintInfo&, const IntRect&);
- virtual void adjustProgressBarStyle(RenderStyle*, Element*) const;
virtual bool paintProgressBar(RenderObject*, const PaintInfo&, const IntRect&) { return true; }
#if ENABLE(INPUT_SPEECH)
@@ -266,7 +254,6 @@ protected:
virtual bool paintInputFieldSpeechButton(RenderObject*, const PaintInfo&, const IntRect&);
#endif
- virtual void adjustSliderTrackStyle(RenderStyle*, Element*) const;
virtual bool paintSliderTrack(RenderObject*, const PaintInfo&, const IntRect&) { return true; }
virtual void adjustSliderThumbStyle(RenderStyle*, Element*) const;
@@ -284,7 +271,6 @@ protected:
virtual void adjustSearchFieldResultsDecorationStyle(RenderStyle*, Element*) const;
virtual bool paintSearchFieldResultsDecoration(RenderObject*, const PaintInfo&, const IntRect&) { return true; }
- virtual void adjustMediaControlStyle(RenderStyle*, Element*) const;
virtual bool paintMediaFullscreenButton(RenderObject*, const PaintInfo&, const IntRect&) { return true; }
virtual bool paintMediaPlayButton(RenderObject*, const PaintInfo&, const IntRect&) { return true; }
virtual bool paintMediaOverlayPlayButton(RenderObject*, const PaintInfo&, const IntRect&) { return true; }
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderThemeChromiumAndroid.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderThemeChromiumAndroid.cpp
index 0e697365d3a..4cad9a6c0a6 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderThemeChromiumAndroid.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderThemeChromiumAndroid.cpp
@@ -27,18 +27,19 @@
#include "core/rendering/RenderThemeChromiumAndroid.h"
#include "CSSValueKeywords.h"
+#include "InputTypeNames.h"
#include "UserAgentStyleSheets.h"
-#include "core/platform/LayoutTestSupport.h"
-#include "core/platform/ScrollbarTheme.h"
-#include "core/platform/graphics/Color.h"
#include "core/rendering/PaintInfo.h"
-#include "core/rendering/RenderMediaControlsChromium.h"
+#include "core/rendering/RenderMediaControls.h"
#include "core/rendering/RenderObject.h"
#include "core/rendering/RenderProgress.h"
#include "core/rendering/RenderSlider.h"
-
-#include "public/platform/android/WebThemeEngine.h"
+#include "platform/LayoutTestSupport.h"
+#include "platform/graphics/Color.h"
+#include "platform/scroll/ScrollbarTheme.h"
#include "public/platform/Platform.h"
+#include "public/platform/default/WebThemeEngine.h"
+#include "wtf/StdLibExtras.h"
namespace WebCore {
@@ -49,7 +50,7 @@ PassRefPtr<RenderTheme> RenderThemeChromiumAndroid::create()
RenderTheme& RenderTheme::theme()
{
- static RenderTheme* renderTheme = RenderThemeChromiumAndroid::create().leakRef();
+ DEFINE_STATIC_REF(RenderTheme, renderTheme, (RenderThemeChromiumAndroid::create()));
return *renderTheme;
}
@@ -83,7 +84,7 @@ void RenderThemeChromiumAndroid::adjustInnerSpinButtonStyle(RenderStyle* style,
if (isRunningLayoutTest()) {
// Match Linux spin button style in layout tests.
// FIXME: Consider removing the conditional if a future Android theme matches this.
- IntSize size = WebKit::Platform::current()->themeEngine()->getSize(WebKit::WebThemeEngine::PartInnerSpinButton);
+ IntSize size = blink::Platform::current()->themeEngine()->getSize(blink::WebThemeEngine::PartInnerSpinButton);
style->setWidth(Length(size.width(), Fixed));
style->setMinWidth(Length(size.width(), Fixed));
@@ -92,20 +93,15 @@ void RenderThemeChromiumAndroid::adjustInnerSpinButtonStyle(RenderStyle* style,
bool RenderThemeChromiumAndroid::paintMediaOverlayPlayButton(RenderObject* object, const PaintInfo& paintInfo, const IntRect& rect)
{
- return RenderMediaControlsChromium::paintMediaControlsPart(MediaOverlayPlayButton, object, paintInfo, rect);
+ return RenderMediaControls::paintMediaControlsPart(MediaOverlayPlayButton, object, paintInfo, rect);
}
int RenderThemeChromiumAndroid::menuListArrowPadding() const
{
// We cannot use the scrollbar thickness here, as it's width is 0 on Android.
// Instead, use the width of the scrollbar down arrow.
- IntSize scrollbarSize = WebKit::Platform::current()->themeEngine()->getSize(WebKit::WebThemeEngine::PartScrollbarDownArrow);
+ IntSize scrollbarSize = blink::Platform::current()->themeEngine()->getSize(blink::WebThemeEngine::PartScrollbarDownArrow);
return scrollbarSize.width();
}
-bool RenderThemeChromiumAndroid::supportsDataListUI(const AtomicString& type) const
-{
- return false;
-}
-
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderThemeChromiumAndroid.h b/chromium/third_party/WebKit/Source/core/rendering/RenderThemeChromiumAndroid.h
index 7de033dd69c..93abb212e22 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderThemeChromiumAndroid.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderThemeChromiumAndroid.h
@@ -54,7 +54,6 @@ public:
{
return RenderThemeChromiumAndroid::defaultActiveSelectionBackgroundColor;
}
- virtual bool supportsDataListUI(const AtomicString&) const;
protected:
virtual int menuListArrowPadding() const OVERRIDE;
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderThemeChromiumDefault.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderThemeChromiumDefault.cpp
index adaa2d4241f..de62300e085 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderThemeChromiumDefault.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderThemeChromiumDefault.cpp
@@ -27,18 +27,25 @@
#include "CSSValueKeywords.h"
#include "UserAgentStyleSheets.h"
-#include "core/platform/graphics/Color.h"
-#include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/graphics/GraphicsContextStateSaver.h"
#include "core/rendering/PaintInfo.h"
#include "core/rendering/RenderObject.h"
#include "core/rendering/RenderProgress.h"
+#include "platform/LayoutTestSupport.h"
+#include "platform/graphics/Color.h"
+#include "platform/graphics/GraphicsContext.h"
+#include "platform/graphics/GraphicsContextStateSaver.h"
#include "public/platform/default/WebThemeEngine.h"
#include "public/platform/Platform.h"
#include "public/platform/WebRect.h"
+#include "wtf/StdLibExtras.h"
namespace WebCore {
+static bool useMockTheme()
+{
+ return isRunningLayoutTest();
+}
+
unsigned RenderThemeChromiumDefault::m_activeSelectionBackgroundColor =
0xff1e90ff;
unsigned RenderThemeChromiumDefault::m_activeSelectionForegroundColor =
@@ -52,16 +59,20 @@ double RenderThemeChromiumDefault::m_caretBlinkInterval;
static const unsigned defaultButtonBackgroundColor = 0xffdddddd;
-static WebKit::WebThemeEngine::State getWebThemeState(const RenderTheme* theme, const RenderObject* o)
+static blink::WebThemeEngine::State getWebThemeState(const RenderTheme* theme, const RenderObject* o)
{
if (!theme->isEnabled(o))
- return WebKit::WebThemeEngine::StateDisabled;
+ return blink::WebThemeEngine::StateDisabled;
+ if (useMockTheme() && theme->isReadOnlyControl(o))
+ return blink::WebThemeEngine::StateReadonly;
if (theme->isPressed(o))
- return WebKit::WebThemeEngine::StatePressed;
+ return blink::WebThemeEngine::StatePressed;
+ if (useMockTheme() && theme->isFocused(o))
+ return blink::WebThemeEngine::StateFocused;
if (theme->isHovered(o))
- return WebKit::WebThemeEngine::StateHover;
+ return blink::WebThemeEngine::StateHover;
- return WebKit::WebThemeEngine::StateNormal;
+ return blink::WebThemeEngine::StateNormal;
}
PassRefPtr<RenderTheme> RenderThemeChromiumDefault::create()
@@ -73,7 +84,7 @@ PassRefPtr<RenderTheme> RenderThemeChromiumDefault::create()
#if !OS(ANDROID)
RenderTheme& RenderTheme::theme()
{
- static RenderTheme* renderTheme = RenderThemeChromiumDefault::create().leakRef();
+ DEFINE_STATIC_REF(RenderTheme, renderTheme, (RenderThemeChromiumDefault::create()));
return *renderTheme;
}
#endif
@@ -87,13 +98,28 @@ RenderThemeChromiumDefault::~RenderThemeChromiumDefault()
{
}
+bool RenderThemeChromiumDefault::supportsFocusRing(const RenderStyle* style) const
+{
+ if (useMockTheme()) {
+ // Don't use focus rings for buttons when mocking controls.
+ return style->appearance() == ButtonPart
+ || style->appearance() == PushButtonPart
+ || style->appearance() == SquareButtonPart;
+ }
+
+ return RenderThemeChromiumSkia::supportsFocusRing(style);
+}
+
Color RenderThemeChromiumDefault::systemColor(CSSValueID cssValueId) const
{
static const Color defaultButtonGrayColor(0xffdddddd);
static const Color defaultMenuColor(0xfff7f7f7);
- if (cssValueId == CSSValueButtonface)
+ if (cssValueId == CSSValueButtonface) {
+ if (useMockTheme())
+ return Color(0xc0, 0xc0, 0xc0);
return defaultButtonGrayColor;
+ }
if (cssValueId == CSSValueMenu)
return defaultMenuColor;
return RenderTheme::systemColor(cssValueId);
@@ -138,38 +164,52 @@ Color RenderThemeChromiumDefault::inactiveListBoxSelectionForegroundColor() cons
Color RenderThemeChromiumDefault::platformActiveSelectionBackgroundColor() const
{
+ if (useMockTheme())
+ return Color(0x00, 0x00, 0xff); // Royal blue.
return m_activeSelectionBackgroundColor;
}
Color RenderThemeChromiumDefault::platformInactiveSelectionBackgroundColor() const
{
+ if (useMockTheme())
+ return Color(0x99, 0x99, 0x99); // Medium gray.
return m_inactiveSelectionBackgroundColor;
}
Color RenderThemeChromiumDefault::platformActiveSelectionForegroundColor() const
{
+ if (useMockTheme())
+ return Color(0xff, 0xff, 0xcc); // Pale yellow.
return m_activeSelectionForegroundColor;
}
Color RenderThemeChromiumDefault::platformInactiveSelectionForegroundColor() const
{
+ if (useMockTheme())
+ return Color::white;
return m_inactiveSelectionForegroundColor;
}
IntSize RenderThemeChromiumDefault::sliderTickSize() const
{
+ if (useMockTheme())
+ return IntSize(1, 3);
return IntSize(1, 6);
}
int RenderThemeChromiumDefault::sliderTickOffsetFromTrackCenter() const
{
+ if (useMockTheme())
+ return 11;
return -16;
}
void RenderThemeChromiumDefault::adjustSliderThumbSize(RenderStyle* style, Element* element) const
{
- IntSize size = WebKit::Platform::current()->themeEngine()->getSize(WebKit::WebThemeEngine::PartSliderThumb);
- float zoomLevel = style->effectiveZoom();
+ IntSize size = blink::Platform::current()->themeEngine()->getSize(blink::WebThemeEngine::PartSliderThumb);
+
+ // FIXME: Mock theme doesn't handle zoomed sliders.
+ float zoomLevel = useMockTheme() ? 1 : style->effectiveZoom();
if (style->appearance() == SliderThumbHorizontalPart) {
style->setWidth(Length(size.width() * zoomLevel, Fixed));
style->setHeight(Length(size.height() * zoomLevel, Fixed));
@@ -209,8 +249,8 @@ void RenderThemeChromiumDefault::setSelectionColors(
bool RenderThemeChromiumDefault::paintCheckbox(RenderObject* o, const PaintInfo& i, const IntRect& rect)
{
- WebKit::WebThemeEngine::ExtraParams extraParams;
- WebKit::WebCanvas* canvas = i.context->canvas();
+ blink::WebThemeEngine::ExtraParams extraParams;
+ blink::WebCanvas* canvas = i.context->canvas();
extraParams.button.checked = isChecked(o);
extraParams.button.indeterminate = isIndeterminate(o);
@@ -225,7 +265,7 @@ bool RenderThemeChromiumDefault::paintCheckbox(RenderObject* o, const PaintInfo&
i.context->translate(-unzoomedRect.x(), -unzoomedRect.y());
}
- WebKit::Platform::current()->themeEngine()->paint(canvas, WebKit::WebThemeEngine::PartCheckbox, getWebThemeState(this, o), WebKit::WebRect(unzoomedRect), &extraParams);
+ blink::Platform::current()->themeEngine()->paint(canvas, blink::WebThemeEngine::PartCheckbox, getWebThemeState(this, o), blink::WebRect(unzoomedRect), &extraParams);
return false;
}
@@ -235,7 +275,7 @@ void RenderThemeChromiumDefault::setCheckboxSize(RenderStyle* style) const
if (!style->width().isIntrinsicOrAuto() && !style->height().isAuto())
return;
- IntSize size = WebKit::Platform::current()->themeEngine()->getSize(WebKit::WebThemeEngine::PartCheckbox);
+ IntSize size = blink::Platform::current()->themeEngine()->getSize(blink::WebThemeEngine::PartCheckbox);
float zoomLevel = style->effectiveZoom();
size.setWidth(size.width() * zoomLevel);
size.setHeight(size.height() * zoomLevel);
@@ -244,11 +284,11 @@ void RenderThemeChromiumDefault::setCheckboxSize(RenderStyle* style) const
bool RenderThemeChromiumDefault::paintRadio(RenderObject* o, const PaintInfo& i, const IntRect& rect)
{
- WebKit::WebThemeEngine::ExtraParams extraParams;
- WebKit::WebCanvas* canvas = i.context->canvas();
+ blink::WebThemeEngine::ExtraParams extraParams;
+ blink::WebCanvas* canvas = i.context->canvas();
extraParams.button.checked = isChecked(o);
- WebKit::Platform::current()->themeEngine()->paint(canvas, WebKit::WebThemeEngine::PartRadio, getWebThemeState(this, o), WebKit::WebRect(rect), &extraParams);
+ blink::Platform::current()->themeEngine()->paint(canvas, blink::WebThemeEngine::PartRadio, getWebThemeState(this, o), blink::WebRect(rect), &extraParams);
return false;
}
@@ -258,7 +298,7 @@ void RenderThemeChromiumDefault::setRadioSize(RenderStyle* style) const
if (!style->width().isIntrinsicOrAuto() && !style->height().isAuto())
return;
- IntSize size = WebKit::Platform::current()->themeEngine()->getSize(WebKit::WebThemeEngine::PartRadio);
+ IntSize size = blink::Platform::current()->themeEngine()->getSize(blink::WebThemeEngine::PartRadio);
float zoomLevel = style->effectiveZoom();
size.setWidth(size.width() * zoomLevel);
size.setHeight(size.height() * zoomLevel);
@@ -267,14 +307,14 @@ void RenderThemeChromiumDefault::setRadioSize(RenderStyle* style) const
bool RenderThemeChromiumDefault::paintButton(RenderObject* o, const PaintInfo& i, const IntRect& rect)
{
- WebKit::WebThemeEngine::ExtraParams extraParams;
- WebKit::WebCanvas* canvas = i.context->canvas();
+ blink::WebThemeEngine::ExtraParams extraParams;
+ blink::WebCanvas* canvas = i.context->canvas();
extraParams.button.hasBorder = true;
- extraParams.button.backgroundColor = defaultButtonBackgroundColor;
+ extraParams.button.backgroundColor = useMockTheme() ? 0xffc0c0c0 : defaultButtonBackgroundColor;
if (o->hasBackground())
extraParams.button.backgroundColor = o->resolveColor(CSSPropertyBackgroundColor).rgb();
- WebKit::Platform::current()->themeEngine()->paint(canvas, WebKit::WebThemeEngine::PartButton, getWebThemeState(this, o), WebKit::WebRect(rect), &extraParams);
+ blink::Platform::current()->themeEngine()->paint(canvas, blink::WebThemeEngine::PartButton, getWebThemeState(this, o), blink::WebRect(rect), &extraParams);
return false;
}
@@ -287,17 +327,17 @@ bool RenderThemeChromiumDefault::paintTextField(RenderObject* o, const PaintInfo
ControlPart part = o->style()->appearance();
- WebKit::WebThemeEngine::ExtraParams extraParams;
+ blink::WebThemeEngine::ExtraParams extraParams;
extraParams.textField.isTextArea = part == TextAreaPart;
extraParams.textField.isListbox = part == ListboxPart;
- WebKit::WebCanvas* canvas = i.context->canvas();
+ blink::WebCanvas* canvas = i.context->canvas();
// Fallback to white if the specified color object is invalid.
Color backgroundColor = o->resolveColor(CSSPropertyBackgroundColor, Color::white);
extraParams.textField.backgroundColor = backgroundColor.rgb();
- WebKit::Platform::current()->themeEngine()->paint(canvas, WebKit::WebThemeEngine::PartTextField, getWebThemeState(this, o), WebKit::WebRect(rect), &extraParams);
+ blink::Platform::current()->themeEngine()->paint(canvas, blink::WebThemeEngine::PartTextField, getWebThemeState(this, o), blink::WebRect(rect), &extraParams);
return false;
}
@@ -309,33 +349,87 @@ bool RenderThemeChromiumDefault::paintMenuList(RenderObject* o, const PaintInfo&
const int right = rect.x() + rect.width();
const int middle = rect.y() + rect.height() / 2;
- WebKit::WebThemeEngine::ExtraParams extraParams;
- extraParams.menuList.arrowX = (o->style()->direction() == RTL) ? rect.x() + 7 : right - 13;
+ blink::WebThemeEngine::ExtraParams extraParams;
extraParams.menuList.arrowY = middle;
const RenderBox* box = toRenderBox(o);
// Match Chromium Win behaviour of showing all borders if any are shown.
extraParams.menuList.hasBorder = box->borderRight() || box->borderLeft() || box->borderTop() || box->borderBottom();
extraParams.menuList.hasBorderRadius = o->style()->hasBorderRadius();
// Fallback to transparent if the specified color object is invalid.
- extraParams.menuList.backgroundColor = Color::transparent;
+ Color backgroundColor(Color::transparent);
if (o->hasBackground())
- extraParams.menuList.backgroundColor = o->resolveColor(CSSPropertyBackgroundColor).rgb();
+ backgroundColor = o->resolveColor(CSSPropertyBackgroundColor);
+ extraParams.menuList.backgroundColor = backgroundColor.rgb();
+
+ // If we have a background image, don't fill the content area to expose the
+ // parent's background. Also, we shouldn't fill the content area if the
+ // alpha of the color is 0. The API of Windows GDI ignores the alpha.
+ // FIXME: the normal Aura theme doesn't care about this, so we should
+ // investigate if we really need fillContentArea.
+ extraParams.menuList.fillContentArea = !o->style()->hasBackgroundImage() && backgroundColor.alpha();
+
+ if (useMockTheme()) {
+ // The size and position of the drop-down button is different between
+ // the mock theme and the regular aura theme.
+ int spacingTop = box->borderTop() + box->paddingTop();
+ int spacingBottom = box->borderBottom() + box->paddingBottom();
+ int spacingRight = box->borderRight() + box->paddingRight();
+ extraParams.menuList.arrowX = (o->style()->direction() == RTL) ? rect.x() + 4 + spacingRight: right - 13 - spacingRight;
+ extraParams.menuList.arrowHeight = rect.height() - spacingBottom - spacingTop;
+ } else {
+ extraParams.menuList.arrowX = (o->style()->direction() == RTL) ? rect.x() + 7 : right - 13;
+ }
- WebKit::WebCanvas* canvas = i.context->canvas();
+ blink::WebCanvas* canvas = i.context->canvas();
- WebKit::Platform::current()->themeEngine()->paint(canvas, WebKit::WebThemeEngine::PartMenuList, getWebThemeState(this, o), WebKit::WebRect(rect), &extraParams);
+ blink::Platform::current()->themeEngine()->paint(canvas, blink::WebThemeEngine::PartMenuList, getWebThemeState(this, o), blink::WebRect(rect), &extraParams);
+ return false;
+}
+
+bool RenderThemeChromiumDefault::paintMenuListButton(RenderObject* o, const PaintInfo& i, const IntRect& rect)
+{
+ if (!o->isBox())
+ return false;
+
+ const int right = rect.x() + rect.width();
+ const int middle = rect.y() + rect.height() / 2;
+
+ blink::WebThemeEngine::ExtraParams extraParams;
+ extraParams.menuList.arrowY = middle;
+ extraParams.menuList.hasBorder = false;
+ extraParams.menuList.hasBorderRadius = o->style()->hasBorderRadius();
+ extraParams.menuList.backgroundColor = Color::transparent;
+ extraParams.menuList.fillContentArea = false;
+
+ if (useMockTheme()) {
+ const RenderBox* box = toRenderBox(o);
+ // The size and position of the drop-down button is different between
+ // the mock theme and the regular aura theme.
+ int spacingTop = box->borderTop() + box->paddingTop();
+ int spacingBottom = box->borderBottom() + box->paddingBottom();
+ int spacingRight = box->borderRight() + box->paddingRight();
+ extraParams.menuList.arrowX = (o->style()->direction() == RTL) ? rect.x() + 4 + spacingRight: right - 13 - spacingRight;
+ extraParams.menuList.arrowHeight = rect.height() - spacingBottom - spacingTop;
+ } else {
+ extraParams.menuList.arrowX = (o->style()->direction() == RTL) ? rect.x() + 7 : right - 13;
+ }
+
+ blink::WebCanvas* canvas = i.context->canvas();
+
+ blink::Platform::current()->themeEngine()->paint(canvas, blink::WebThemeEngine::PartMenuList, getWebThemeState(this, o), blink::WebRect(rect), &extraParams);
return false;
}
bool RenderThemeChromiumDefault::paintSliderTrack(RenderObject* o, const PaintInfo& i, const IntRect& rect)
{
- WebKit::WebThemeEngine::ExtraParams extraParams;
- WebKit::WebCanvas* canvas = i.context->canvas();
+ blink::WebThemeEngine::ExtraParams extraParams;
+ blink::WebCanvas* canvas = i.context->canvas();
extraParams.slider.vertical = o->style()->appearance() == SliderVerticalPart;
paintSliderTicks(o, i, rect);
- float zoomLevel = o->style()->effectiveZoom();
+ // FIXME: Mock theme doesn't handle zoomed sliders.
+ float zoomLevel = useMockTheme() ? 1 : o->style()->effectiveZoom();
GraphicsContextStateSaver stateSaver(*i.context);
IntRect unzoomedRect = rect;
if (zoomLevel != 1) {
@@ -346,19 +440,20 @@ bool RenderThemeChromiumDefault::paintSliderTrack(RenderObject* o, const PaintIn
i.context->translate(-unzoomedRect.x(), -unzoomedRect.y());
}
- WebKit::Platform::current()->themeEngine()->paint(canvas, WebKit::WebThemeEngine::PartSliderTrack, getWebThemeState(this, o), WebKit::WebRect(unzoomedRect), &extraParams);
+ blink::Platform::current()->themeEngine()->paint(canvas, blink::WebThemeEngine::PartSliderTrack, getWebThemeState(this, o), blink::WebRect(unzoomedRect), &extraParams);
return false;
}
bool RenderThemeChromiumDefault::paintSliderThumb(RenderObject* o, const PaintInfo& i, const IntRect& rect)
{
- WebKit::WebThemeEngine::ExtraParams extraParams;
- WebKit::WebCanvas* canvas = i.context->canvas();
+ blink::WebThemeEngine::ExtraParams extraParams;
+ blink::WebCanvas* canvas = i.context->canvas();
extraParams.slider.vertical = o->style()->appearance() == SliderThumbVerticalPart;
extraParams.slider.inDrag = isPressed(o);
- float zoomLevel = o->style()->effectiveZoom();
+ // FIXME: Mock theme doesn't handle zoomed sliders.
+ float zoomLevel = useMockTheme() ? 1 : o->style()->effectiveZoom();
GraphicsContextStateSaver stateSaver(*i.context);
IntRect unzoomedRect = rect;
if (zoomLevel != 1) {
@@ -369,13 +464,13 @@ bool RenderThemeChromiumDefault::paintSliderThumb(RenderObject* o, const PaintIn
i.context->translate(-unzoomedRect.x(), -unzoomedRect.y());
}
- WebKit::Platform::current()->themeEngine()->paint(canvas, WebKit::WebThemeEngine::PartSliderThumb, getWebThemeState(this, o), WebKit::WebRect(unzoomedRect), &extraParams);
+ blink::Platform::current()->themeEngine()->paint(canvas, blink::WebThemeEngine::PartSliderThumb, getWebThemeState(this, o), blink::WebRect(unzoomedRect), &extraParams);
return false;
}
void RenderThemeChromiumDefault::adjustInnerSpinButtonStyle(RenderStyle* style, Element*) const
{
- IntSize size = WebKit::Platform::current()->themeEngine()->getSize(WebKit::WebThemeEngine::PartInnerSpinButton);
+ IntSize size = blink::Platform::current()->themeEngine()->getSize(blink::WebThemeEngine::PartInnerSpinButton);
style->setWidth(Length(size.width(), Fixed));
style->setMinWidth(Length(size.width(), Fixed));
@@ -383,12 +478,12 @@ void RenderThemeChromiumDefault::adjustInnerSpinButtonStyle(RenderStyle* style,
bool RenderThemeChromiumDefault::paintInnerSpinButton(RenderObject* o, const PaintInfo& i, const IntRect& rect)
{
- WebKit::WebThemeEngine::ExtraParams extraParams;
- WebKit::WebCanvas* canvas = i.context->canvas();
+ blink::WebThemeEngine::ExtraParams extraParams;
+ blink::WebCanvas* canvas = i.context->canvas();
extraParams.innerSpin.spinUp = (controlStatesForRenderer(o) & SpinUpState);
extraParams.innerSpin.readOnly = isReadOnlyControl(o);
- WebKit::Platform::current()->themeEngine()->paint(canvas, WebKit::WebThemeEngine::PartInnerSpinButton, getWebThemeState(this, o), WebKit::WebRect(rect), &extraParams);
+ blink::Platform::current()->themeEngine()->paint(canvas, blink::WebThemeEngine::PartInnerSpinButton, getWebThemeState(this, o), blink::WebRect(rect), &extraParams);
return false;
}
@@ -400,7 +495,7 @@ bool RenderThemeChromiumDefault::paintProgressBar(RenderObject* o, const PaintIn
RenderProgress* renderProgress = toRenderProgress(o);
IntRect valueRect = progressValueRectFor(renderProgress, rect);
- WebKit::WebThemeEngine::ExtraParams extraParams;
+ blink::WebThemeEngine::ExtraParams extraParams;
extraParams.progressBar.determinate = renderProgress->isDeterminate();
extraParams.progressBar.valueRectX = valueRect.x();
extraParams.progressBar.valueRectY = valueRect.y();
@@ -408,8 +503,8 @@ bool RenderThemeChromiumDefault::paintProgressBar(RenderObject* o, const PaintIn
extraParams.progressBar.valueRectHeight = valueRect.height();
DirectionFlippingScope scope(o, i, rect);
- WebKit::WebCanvas* canvas = i.context->canvas();
- WebKit::Platform::current()->themeEngine()->paint(canvas, WebKit::WebThemeEngine::PartProgressBar, getWebThemeState(this, o), WebKit::WebRect(rect), &extraParams);
+ blink::WebCanvas* canvas = i.context->canvas();
+ blink::Platform::current()->themeEngine()->paint(canvas, blink::WebThemeEngine::PartProgressBar, getWebThemeState(this, o), blink::WebRect(rect), &extraParams);
return false;
}
@@ -418,4 +513,15 @@ bool RenderThemeChromiumDefault::shouldOpenPickerWithF4Key() const
return true;
}
+bool RenderThemeChromiumDefault::shouldUseFallbackTheme(RenderStyle* style) const
+{
+ if (useMockTheme()) {
+ // The mock theme can't handle zoomed controls, so we fall back to the "fallback" theme.
+ ControlPart part = style->appearance();
+ if (part == CheckboxPart || part == RadioPart)
+ return style->effectiveZoom() != 1;
+ }
+ return RenderTheme::shouldUseFallbackTheme(style);
+}
+
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderThemeChromiumDefault.h b/chromium/third_party/WebKit/Source/core/rendering/RenderThemeChromiumDefault.h
index 25423ed28f4..74527e0732d 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderThemeChromiumDefault.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderThemeChromiumDefault.h
@@ -43,6 +43,8 @@ public:
// A method asking if the control changes its tint when the window has focus or not.
virtual bool controlSupportsTints(const RenderObject*) const;
+ virtual bool supportsFocusRing(const RenderStyle*) const OVERRIDE;
+
// List Box selection color
virtual Color activeListBoxSelectionBackgroundColor() const;
virtual Color activeListBoxSelectionForegroundColor() const;
@@ -67,11 +69,12 @@ public:
virtual bool paintRadio(RenderObject*, const PaintInfo&, const IntRect&);
virtual void setRadioSize(RenderStyle*) const;
- virtual bool paintButton(RenderObject*, const PaintInfo&, const IntRect&);
- virtual bool paintTextField(RenderObject*, const PaintInfo&, const IntRect&);
- virtual bool paintMenuList(RenderObject*, const PaintInfo&, const IntRect&);
- virtual bool paintSliderTrack(RenderObject*, const PaintInfo&, const IntRect&);
- virtual bool paintSliderThumb(RenderObject*, const PaintInfo&, const IntRect&);
+ virtual bool paintButton(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
+ virtual bool paintTextField(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
+ virtual bool paintMenuList(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
+ virtual bool paintMenuListButton(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
+ virtual bool paintSliderTrack(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
+ virtual bool paintSliderThumb(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
virtual void adjustInnerSpinButtonStyle(RenderStyle*, Element*) const;
virtual bool paintInnerSpinButton(RenderObject*, const PaintInfo&, const IntRect&);
@@ -87,6 +90,7 @@ public:
protected:
RenderThemeChromiumDefault();
virtual ~RenderThemeChromiumDefault();
+ virtual bool shouldUseFallbackTheme(RenderStyle*) const OVERRIDE;
private:
// A general method asking if any control tinting is supported at all.
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderThemeChromiumFontProviderLinux.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderThemeChromiumFontProviderLinux.cpp
index 06fec413f55..3d1d0260d0a 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderThemeChromiumFontProviderLinux.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderThemeChromiumFontProviderLinux.cpp
@@ -27,7 +27,7 @@
#include "core/rendering/RenderThemeChromiumFontProvider.h"
#include "CSSValueKeywords.h"
-#include "core/platform/graphics/FontDescription.h"
+#include "platform/fonts/FontDescription.h"
#include "wtf/StdLibExtras.h"
#include "wtf/text/WTFString.h"
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderThemeChromiumFontProviderWin.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderThemeChromiumFontProviderWin.cpp
index e201d90cd7f..18305cc31d6 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderThemeChromiumFontProviderWin.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderThemeChromiumFontProviderWin.cpp
@@ -29,9 +29,9 @@
#include <windows.h>
#include "CSSValueKeywords.h"
-#include "core/platform/graphics/FontDescription.h"
-#include "core/platform/win/HWndDC.h"
-#include "core/platform/win/SystemInfo.h"
+#include "platform/fonts/FontDescription.h"
+#include "platform/win/HWndDC.h"
+#include "platform/win/SystemInfo.h"
#include "wtf/text/WTFString.h"
#define SIZEOF_STRUCT_WITH_SPECIFIED_LAST_MEMBER(structName, member) \
@@ -78,7 +78,7 @@ static float pointsToPixels(float points)
static void getNonClientMetrics(NONCLIENTMETRICS* metrics)
{
- static UINT size = (windowsVersion() >= WindowsVista) ?
+ static UINT size = isWindowsVistaOrGreater() ?
sizeof(NONCLIENTMETRICS) : NONCLIENTMETRICS_SIZE_PRE_VISTA;
metrics->cbSize = size;
bool success = !!SystemParametersInfo(SPI_GETNONCLIENTMETRICS, size, metrics, 0);
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderThemeChromiumMac.h b/chromium/third_party/WebKit/Source/core/rendering/RenderThemeChromiumMac.h
index fbbf684fc37..371ecc6c717 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderThemeChromiumMac.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderThemeChromiumMac.h
@@ -95,10 +95,8 @@ protected:
virtual bool supportsSelectionForegroundColors() const OVERRIDE { return false; }
virtual bool paintTextField(RenderObject*, const PaintInfo&, const IntRect&);
- virtual void adjustTextFieldStyle(RenderStyle*, Element*) const;
virtual bool paintTextArea(RenderObject*, const PaintInfo&, const IntRect&);
- virtual void adjustTextAreaStyle(RenderStyle*, Element*) const;
virtual bool paintMenuList(RenderObject*, const PaintInfo&, const IntRect&);
virtual void adjustMenuListStyle(RenderStyle*, Element*) const;
@@ -106,7 +104,6 @@ protected:
virtual bool paintMenuListButton(RenderObject*, const PaintInfo&, const IntRect&);
virtual void adjustMenuListButtonStyle(RenderStyle*, Element*) const;
- virtual void adjustProgressBarStyle(RenderStyle*, Element*) const;
virtual bool paintProgressBar(RenderObject*, const PaintInfo&, const IntRect&);
virtual bool paintSliderTrack(RenderObject*, const PaintInfo&, const IntRect&);
@@ -128,7 +125,7 @@ protected:
virtual bool supportsClosedCaptioning() const { return true; }
private:
- virtual String fileListNameForWidth(const FileList*, const Font&, int width, bool multipleFilesAllowed) const OVERRIDE;
+ virtual String fileListNameForWidth(Locale&, const FileList*, const Font&, int width) const OVERRIDE;
IntRect inflateRect(const IntRect&, const IntSize&, const int* margins, float zoomLevel = 1.0f) const;
@@ -186,7 +183,6 @@ protected:
virtual bool paintMediaVolumeSliderContainer(RenderObject*, const PaintInfo&, const IntRect&);
virtual bool paintMediaVolumeSliderTrack(RenderObject*, const PaintInfo&, const IntRect&);
virtual bool paintMediaVolumeSliderThumb(RenderObject*, const PaintInfo&, const IntRect&);
- virtual bool usesMediaControlStatusDisplay() { return false; }
virtual bool hasOwnDisabledStateHandlingFor(ControlPart) const { return true; }
virtual bool usesVerticalVolumeSlider() const { return false; }
virtual String formatMediaControlsTime(float time) const;
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderThemeChromiumMac.mm b/chromium/third_party/WebKit/Source/core/rendering/RenderThemeChromiumMac.mm
index c0d52c62170..82f39e25601 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderThemeChromiumMac.mm
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderThemeChromiumMac.mm
@@ -31,32 +31,31 @@
#import "core/html/HTMLInputElement.h"
#import "core/html/HTMLMediaElement.h"
#import "core/html/HTMLMeterElement.h"
-#import "core/html/HTMLPlugInImageElement.h"
#import "core/html/TimeRanges.h"
#import "core/html/shadow/MediaControlElements.h"
-#import "core/page/FrameView.h"
-#import "core/platform/LayoutTestSupport.h"
-#import "core/platform/LocalizedStrings.h"
-#import "core/platform/SharedBuffer.h"
-#import "core/platform/graphics/BitmapImage.h"
-#import "core/platform/graphics/GraphicsContextStateSaver.h"
-#import "core/platform/graphics/Image.h"
-#import "core/platform/graphics/ImageBuffer.h"
-#import "core/platform/graphics/StringTruncator.h"
-#import "core/platform/graphics/cg/GraphicsContextCG.h"
-#import "core/platform/graphics/mac/ColorMac.h"
-#import "core/platform/mac/LocalCurrentGraphicsContext.h"
+#import "core/frame/FrameView.h"
#import "core/platform/mac/ThemeMac.h"
-#import "core/platform/mac/WebCoreNSCellExtras.h"
#import "core/rendering/PaintInfo.h"
#import "core/rendering/RenderLayer.h"
#import "core/rendering/RenderMedia.h"
#import "core/rendering/RenderMediaControls.h"
-#import "core/rendering/RenderMediaControlsChromium.h"
#import "core/rendering/RenderMeter.h"
#import "core/rendering/RenderProgress.h"
#import "core/rendering/RenderSlider.h"
#import "core/rendering/RenderView.h"
+#import "core/rendering/style/ShadowList.h"
+#import "platform/LayoutTestSupport.h"
+#import "platform/SharedBuffer.h"
+#import "platform/graphics/BitmapImage.h"
+#import "platform/graphics/GraphicsContextStateSaver.h"
+#import "platform/graphics/Image.h"
+#import "platform/graphics/ImageBuffer.h"
+#import "platform/graphics/cg/GraphicsContextCG.h"
+#import "platform/mac/ColorMac.h"
+#import "platform/mac/LocalCurrentGraphicsContext.h"
+#import "platform/mac/WebCoreNSCellExtras.h"
+#import "platform/text/PlatformLocale.h"
+#import "platform/text/StringTruncator.h"
#import <AvailabilityMacros.h>
#import <Carbon/Carbon.h>
@@ -781,10 +780,6 @@ bool RenderThemeChromiumMac::paintTextField(RenderObject* o, const PaintInfo& pa
return false;
}
-void RenderThemeChromiumMac::adjustTextFieldStyle(RenderStyle*, Element*) const
-{
-}
-
bool RenderThemeChromiumMac::paintCapsLockIndicator(RenderObject*, const PaintInfo& paintInfo, const IntRect& r)
{
if (paintInfo.context->paintingDisabled())
@@ -854,10 +849,6 @@ bool RenderThemeChromiumMac::paintTextArea(RenderObject* o, const PaintInfo& pai
return false;
}
-void RenderThemeChromiumMac::adjustTextAreaStyle(RenderStyle*, Element*) const
-{
-}
-
const int* RenderThemeChromiumMac::popupButtonMargins() const
{
static const int margins[3][4] =
@@ -1059,10 +1050,6 @@ double RenderThemeChromiumMac::animationDurationForProgressBar(RenderProgress*)
return progressAnimationNumFrames * progressAnimationFrameRate;
}
-void RenderThemeChromiumMac::adjustProgressBarStyle(RenderStyle*, Element*) const
-{
-}
-
bool RenderThemeChromiumMac::paintProgressBar(RenderObject* renderObject, const PaintInfo& paintInfo, const IntRect& rect)
{
if (!renderObject->isProgress())
@@ -1097,7 +1084,7 @@ bool RenderThemeChromiumMac::paintProgressBar(RenderObject* renderObject, const
trackInfo.reserved = 0;
trackInfo.filler1 = 0;
- OwnPtr<ImageBuffer> imageBuffer = ImageBuffer::create(inflatedRect.size(), 1);
+ OwnPtr<ImageBuffer> imageBuffer = ImageBuffer::create(inflatedRect.size());
if (!imageBuffer)
return true;
@@ -1536,7 +1523,6 @@ bool RenderThemeChromiumMac::paintSliderThumb(RenderObject* o, const PaintInfo&
FloatRect borderBounds = unzoomedRect;
borderBounds.inflate(sliderThumbBorderWidth / 2.0);
- FloatRect shadowBounds = unzoomedRect;
borderBounds.inflate(-sliderThumbBorderWidth);
FloatSize shadowOffset(0, 1);
paintInfo.context->setShadow(shadowOffset, sliderThumbShadowBlur, shadowColor);
@@ -1875,18 +1861,20 @@ NSTextFieldCell* RenderThemeChromiumMac::textField() const
return m_textField.get();
}
-String RenderThemeChromiumMac::fileListNameForWidth(const FileList* fileList, const Font& font, int width, bool multipleFilesAllowed) const
+String RenderThemeChromiumMac::fileListNameForWidth(Locale& locale, const FileList* fileList, const Font& font, int width) const
{
if (width <= 0)
return String();
String strToTruncate;
- if (fileList->isEmpty())
- strToTruncate = fileListDefaultLabel(multipleFilesAllowed);
- else if (fileList->length() == 1)
+ if (fileList->isEmpty()) {
+ strToTruncate = locale.queryString(blink::WebLocalizedString::FileButtonNoFileSelectedLabel);
+ } else if (fileList->length() == 1) {
strToTruncate = [[NSFileManager defaultManager] displayNameAtPath:(fileList->item(0)->path())];
- else
- return StringTruncator::rightTruncate(multipleFileUploadText(fileList->length()), width, font, StringTruncator::EnableRoundingHacks);
+ } else {
+ // FIXME: Localization of fileList->length().
+ return StringTruncator::rightTruncate(locale.queryString(blink::WebLocalizedString::MultipleFileUploadText, String::number(fileList->length())), width, font, StringTruncator::EnableRoundingHacks);
+ }
return StringTruncator::centerTruncate(strToTruncate, width, font, StringTruncator::EnableRoundingHacks);
}
@@ -1899,7 +1887,7 @@ NSView* FlippedView()
RenderTheme& RenderTheme::theme()
{
- static RenderTheme* renderTheme = RenderThemeChromiumMac::create().leakRef();
+ DEFINE_STATIC_REF(RenderTheme, renderTheme, (RenderThemeChromiumMac::create()));
return *renderTheme;
}
@@ -1944,22 +1932,22 @@ bool RenderThemeChromiumMac::shouldShowPlaceholderWhenFocused() const
void RenderThemeChromiumMac::adjustMediaSliderThumbSize(RenderStyle* style) const
{
- RenderMediaControlsChromium::adjustMediaSliderThumbSize(style);
+ RenderMediaControls::adjustMediaSliderThumbSize(style);
}
bool RenderThemeChromiumMac::paintMediaPlayButton(RenderObject* object, const PaintInfo& paintInfo, const IntRect& rect)
{
- return RenderMediaControlsChromium::paintMediaControlsPart(MediaPlayButton, object, paintInfo, rect);
+ return RenderMediaControls::paintMediaControlsPart(MediaPlayButton, object, paintInfo, rect);
}
bool RenderThemeChromiumMac::paintMediaMuteButton(RenderObject* object, const PaintInfo& paintInfo, const IntRect& rect)
{
- return RenderMediaControlsChromium::paintMediaControlsPart(MediaMuteButton, object, paintInfo, rect);
+ return RenderMediaControls::paintMediaControlsPart(MediaMuteButton, object, paintInfo, rect);
}
bool RenderThemeChromiumMac::paintMediaSliderTrack(RenderObject* object, const PaintInfo& paintInfo, const IntRect& rect)
{
- return RenderMediaControlsChromium::paintMediaControlsPart(MediaSlider, object, paintInfo, rect);
+ return RenderMediaControls::paintMediaControlsPart(MediaSlider, object, paintInfo, rect);
}
String RenderThemeChromiumMac::extraFullScreenStyleSheet()
@@ -1981,37 +1969,37 @@ bool RenderThemeChromiumMac::paintMediaVolumeSliderContainer(RenderObject* objec
bool RenderThemeChromiumMac::paintMediaVolumeSliderTrack(RenderObject* object, const PaintInfo& paintInfo, const IntRect& rect)
{
- return RenderMediaControlsChromium::paintMediaControlsPart(MediaVolumeSlider, object, paintInfo, rect);
+ return RenderMediaControls::paintMediaControlsPart(MediaVolumeSlider, object, paintInfo, rect);
}
bool RenderThemeChromiumMac::paintMediaVolumeSliderThumb(RenderObject* object, const PaintInfo& paintInfo, const IntRect& rect)
{
- return RenderMediaControlsChromium::paintMediaControlsPart(MediaVolumeSliderThumb, object, paintInfo, rect);
+ return RenderMediaControls::paintMediaControlsPart(MediaVolumeSliderThumb, object, paintInfo, rect);
}
bool RenderThemeChromiumMac::paintMediaSliderThumb(RenderObject* object, const PaintInfo& paintInfo, const IntRect& rect)
{
- return RenderMediaControlsChromium::paintMediaControlsPart(MediaSliderThumb, object, paintInfo, rect);
+ return RenderMediaControls::paintMediaControlsPart(MediaSliderThumb, object, paintInfo, rect);
}
String RenderThemeChromiumMac::formatMediaControlsTime(float time) const
{
- return RenderMediaControlsChromium::formatMediaControlsTime(time);
+ return RenderMediaControls::formatMediaControlsTime(time);
}
String RenderThemeChromiumMac::formatMediaControlsCurrentTime(float currentTime, float duration) const
{
- return RenderMediaControlsChromium::formatMediaControlsCurrentTime(currentTime, duration);
+ return RenderMediaControls::formatMediaControlsCurrentTime(currentTime, duration);
}
bool RenderThemeChromiumMac::paintMediaFullscreenButton(RenderObject* object, const PaintInfo& paintInfo, const IntRect& rect)
{
- return RenderMediaControlsChromium::paintMediaControlsPart(MediaEnterFullscreenButton, object, paintInfo, rect);
+ return RenderMediaControls::paintMediaControlsPart(MediaEnterFullscreenButton, object, paintInfo, rect);
}
bool RenderThemeChromiumMac::paintMediaToggleClosedCaptionsButton(RenderObject* object, const PaintInfo& paintInfo, const IntRect& rect)
{
- return RenderMediaControlsChromium::paintMediaControlsPart(MediaShowClosedCaptionsButton, object, paintInfo, rect);
+ return RenderMediaControls::paintMediaControlsPart(MediaShowClosedCaptionsButton, object, paintInfo, rect);
}
bool RenderThemeChromiumMac::shouldUseFallbackTheme(RenderStyle* style) const
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderThemeChromiumSkia.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderThemeChromiumSkia.cpp
index ee4f442258e..2a7e3c2b232 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderThemeChromiumSkia.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderThemeChromiumSkia.cpp
@@ -25,17 +25,18 @@
#include "core/rendering/RenderThemeChromiumSkia.h"
#include "UserAgentStyleSheets.h"
-#include "core/platform/LayoutTestSupport.h"
-#include "core/platform/ScrollbarTheme.h"
-#include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/graphics/Image.h"
#include "core/rendering/PaintInfo.h"
#include "core/rendering/RenderBox.h"
-#include "core/rendering/RenderMediaControlsChromium.h"
+#include "core/rendering/RenderMediaControls.h"
#include "core/rendering/RenderObject.h"
#include "core/rendering/RenderProgress.h"
#include "core/rendering/RenderThemeChromiumFontProvider.h"
+#include "platform/LayoutTestSupport.h"
+#include "platform/graphics/GraphicsContext.h"
+#include "platform/graphics/Image.h"
+#include "platform/scroll/ScrollbarTheme.h"
#include "wtf/CurrentTime.h"
+#include "wtf/StdLibExtras.h"
namespace WebCore {
@@ -243,8 +244,8 @@ bool RenderThemeChromiumSkia::paintSearchFieldCancelButton(RenderObject* cancelB
cancelButtonSize, cancelButtonSize);
IntRect paintingRect = convertToPaintingRect(inputRenderBox, cancelButtonObject, cancelButtonRect, r);
- static Image* cancelImage = Image::loadPlatformResource("searchCancel").leakRef();
- static Image* cancelPressedImage = Image::loadPlatformResource("searchCancelPressed").leakRef();
+ DEFINE_STATIC_REF(Image, cancelImage, (Image::loadPlatformResource("searchCancel")));
+ DEFINE_STATIC_REF(Image, cancelPressedImage, (Image::loadPlatformResource("searchCancelPressed")));
paintInfo.context->drawImage(isPressed(cancelButtonObject) ? cancelPressedImage : cancelImage, paintingRect);
return false;
}
@@ -286,64 +287,64 @@ bool RenderThemeChromiumSkia::paintSearchFieldResultsDecoration(RenderObject* ma
magnifierSize, magnifierSize);
IntRect paintingRect = convertToPaintingRect(inputRenderBox, magnifierObject, magnifierRect, r);
- static Image* magnifierImage = Image::loadPlatformResource("searchMagnifier").leakRef();
+ DEFINE_STATIC_REF(Image, magnifierImage, (Image::loadPlatformResource("searchMagnifier")));
paintInfo.context->drawImage(magnifierImage, paintingRect);
return false;
}
bool RenderThemeChromiumSkia::paintMediaSliderTrack(RenderObject* object, const PaintInfo& paintInfo, const IntRect& rect)
{
- return RenderMediaControlsChromium::paintMediaControlsPart(MediaSlider, object, paintInfo, rect);
+ return RenderMediaControls::paintMediaControlsPart(MediaSlider, object, paintInfo, rect);
}
bool RenderThemeChromiumSkia::paintMediaVolumeSliderTrack(RenderObject* object, const PaintInfo& paintInfo, const IntRect& rect)
{
- return RenderMediaControlsChromium::paintMediaControlsPart(MediaVolumeSlider, object, paintInfo, rect);
+ return RenderMediaControls::paintMediaControlsPart(MediaVolumeSlider, object, paintInfo, rect);
}
void RenderThemeChromiumSkia::adjustSliderThumbSize(RenderStyle* style, Element*) const
{
- RenderMediaControlsChromium::adjustMediaSliderThumbSize(style);
+ RenderMediaControls::adjustMediaSliderThumbSize(style);
}
bool RenderThemeChromiumSkia::paintMediaSliderThumb(RenderObject* object, const PaintInfo& paintInfo, const IntRect& rect)
{
- return RenderMediaControlsChromium::paintMediaControlsPart(MediaSliderThumb, object, paintInfo, rect);
+ return RenderMediaControls::paintMediaControlsPart(MediaSliderThumb, object, paintInfo, rect);
}
bool RenderThemeChromiumSkia::paintMediaToggleClosedCaptionsButton(RenderObject* o, const PaintInfo& paintInfo, const IntRect& r)
{
- return RenderMediaControlsChromium::paintMediaControlsPart(MediaShowClosedCaptionsButton, o, paintInfo, r);
+ return RenderMediaControls::paintMediaControlsPart(MediaShowClosedCaptionsButton, o, paintInfo, r);
}
bool RenderThemeChromiumSkia::paintMediaVolumeSliderThumb(RenderObject* object, const PaintInfo& paintInfo, const IntRect& rect)
{
- return RenderMediaControlsChromium::paintMediaControlsPart(MediaVolumeSliderThumb, object, paintInfo, rect);
+ return RenderMediaControls::paintMediaControlsPart(MediaVolumeSliderThumb, object, paintInfo, rect);
}
bool RenderThemeChromiumSkia::paintMediaPlayButton(RenderObject* object, const PaintInfo& paintInfo, const IntRect& rect)
{
- return RenderMediaControlsChromium::paintMediaControlsPart(MediaPlayButton, object, paintInfo, rect);
+ return RenderMediaControls::paintMediaControlsPart(MediaPlayButton, object, paintInfo, rect);
}
bool RenderThemeChromiumSkia::paintMediaMuteButton(RenderObject* object, const PaintInfo& paintInfo, const IntRect& rect)
{
- return RenderMediaControlsChromium::paintMediaControlsPart(MediaMuteButton, object, paintInfo, rect);
+ return RenderMediaControls::paintMediaControlsPart(MediaMuteButton, object, paintInfo, rect);
}
String RenderThemeChromiumSkia::formatMediaControlsTime(float time) const
{
- return RenderMediaControlsChromium::formatMediaControlsTime(time);
+ return RenderMediaControls::formatMediaControlsTime(time);
}
String RenderThemeChromiumSkia::formatMediaControlsCurrentTime(float currentTime, float duration) const
{
- return RenderMediaControlsChromium::formatMediaControlsCurrentTime(currentTime, duration);
+ return RenderMediaControls::formatMediaControlsCurrentTime(currentTime, duration);
}
bool RenderThemeChromiumSkia::paintMediaFullscreenButton(RenderObject* object, const PaintInfo& paintInfo, const IntRect& rect)
{
- return RenderMediaControlsChromium::paintMediaControlsPart(MediaEnterFullscreenButton, object, paintInfo, rect);
+ return RenderMediaControls::paintMediaControlsPart(MediaEnterFullscreenButton, object, paintInfo, rect);
}
void RenderThemeChromiumSkia::adjustMenuListStyle(RenderStyle* style, WebCore::Element*) const
@@ -425,9 +426,8 @@ bool RenderThemeChromiumSkia::shouldShowPlaceholderWhenFocused() const
//
// Following values are come from default of GTK+
//
-static const int progressDeltaPixelsPerSecond = 100;
static const int progressActivityBlocks = 5;
-static const int progressAnimationFrmaes = 10;
+static const int progressAnimationFrames = 10;
static const double progressAnimationInterval = 0.125;
IntRect RenderThemeChromiumSkia::determinateProgressValueRectFor(RenderProgress* renderProgress, const IntRect& rect) const
@@ -457,7 +457,7 @@ double RenderThemeChromiumSkia::animationRepeatIntervalForProgressBar(RenderProg
double RenderThemeChromiumSkia::animationDurationForProgressBar(RenderProgress* renderProgress) const
{
- return progressAnimationInterval * progressAnimationFrmaes * 2; // "2" for back and forth
+ return progressAnimationInterval * progressAnimationFrames * 2; // "2" for back and forth
}
IntRect RenderThemeChromiumSkia::progressValueRectFor(RenderProgress* renderProgress, const IntRect& rect) const
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderThemeChromiumWin.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderThemeChromiumWin.cpp
index 1abbd9f931a..b1224074607 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderThemeChromiumWin.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderThemeChromiumWin.cpp
@@ -33,23 +33,22 @@
#include "HTMLNames.h"
#include "core/html/HTMLMediaElement.h"
#include "core/html/shadow/MediaControlElements.h"
-#include "core/platform/LayoutTestSupport.h"
-#include "core/platform/ScrollbarTheme.h"
-#include "core/platform/graphics/FontSelector.h"
-#include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/graphics/chromium/FontUtilsChromiumWin.h"
-#include "core/platform/graphics/chromium/TransparencyWin.h"
-#include "core/platform/win/SystemInfo.h"
#include "core/rendering/PaintInfo.h"
#include "core/rendering/RenderBox.h"
#include "core/rendering/RenderProgress.h"
#include "core/rendering/RenderSlider.h"
+#include "platform/LayoutTestSupport.h"
+#include "platform/fonts/FontSelector.h"
+#include "platform/graphics/GraphicsContext.h"
+#include "platform/graphics/win/TransparencyWin.h"
+#include "platform/scroll/ScrollbarTheme.h"
+#include "platform/win/SystemInfo.h"
#include "public/platform/Platform.h"
#include "public/platform/WebColor.h"
#include "public/platform/WebRect.h"
#include "public/platform/win/WebThemeEngine.h"
#include "wtf/CurrentTime.h"
-
+#include "wtf/StdLibExtras.h"
// FIXME: This dependency should eventually be removed.
#include <skia/ext/skia_utils_win.h>
@@ -165,7 +164,7 @@ PassRefPtr<RenderTheme> RenderThemeChromiumWin::create()
RenderTheme& RenderTheme::theme()
{
- static RenderTheme* renderTheme = RenderThemeChromiumWin::create().leakRef();
+ DEFINE_STATIC_REF(RenderTheme, renderTheme, (RenderThemeChromiumWin::create()));
return *renderTheme;
}
@@ -303,8 +302,8 @@ bool RenderThemeChromiumWin::paintButton(RenderObject* o, const PaintInfo& i, co
const ThemeData& themeData = getThemeData(o);
ThemePainter painter(i.context, r);
- WebKit::WebCanvas* canvas = painter.context()->canvas();
- WebKit::Platform::current()->themeEngine()->paintButton(canvas, themeData.m_part, themeData.m_state, themeData.m_classicState, WebKit::WebRect(painter.drawRect()));
+ blink::WebCanvas* canvas = painter.context()->canvas();
+ blink::Platform::current()->themeEngine()->paintButton(canvas, themeData.m_part, themeData.m_state, themeData.m_classicState, blink::WebRect(painter.drawRect()));
return false;
}
@@ -318,8 +317,8 @@ bool RenderThemeChromiumWin::paintSliderTrack(RenderObject* o, const PaintInfo&
const ThemeData& themeData = getThemeData(o);
ThemePainter painter(i.context, r);
- WebKit::WebCanvas* canvas = painter.context()->canvas();
- WebKit::Platform::current()->themeEngine()->paintTrackbar(canvas, themeData.m_part, themeData.m_state, themeData.m_classicState, WebKit::WebRect(painter.drawRect()));
+ blink::WebCanvas* canvas = painter.context()->canvas();
+ blink::Platform::current()->themeEngine()->paintTrackbar(canvas, themeData.m_part, themeData.m_state, themeData.m_classicState, blink::WebRect(painter.drawRect()));
paintSliderTicks(o, i, r);
@@ -331,8 +330,8 @@ bool RenderThemeChromiumWin::paintSliderThumb(RenderObject* o, const PaintInfo&
const ThemeData& themeData = getThemeData(o);
ThemePainter painter(i.context, r);
- WebKit::WebCanvas* canvas = painter.context()->canvas();
- WebKit::Platform::current()->themeEngine()->paintTrackbar(canvas, themeData.m_part, themeData.m_state, themeData.m_classicState, WebKit::WebRect(painter.drawRect()));
+ blink::WebCanvas* canvas = painter.context()->canvas();
+ blink::Platform::current()->themeEngine()->paintTrackbar(canvas, themeData.m_part, themeData.m_state, themeData.m_classicState, blink::WebRect(painter.drawRect()));
return false;
}
@@ -340,7 +339,7 @@ bool RenderThemeChromiumWin::paintSliderThumb(RenderObject* o, const PaintInfo&
static int menuListButtonWidth()
{
static int width = isRunningLayoutTest() ? kStandardMenuListButtonWidth :
- IntSize(WebKit::Platform::current()->themeEngine()->getSize(SBP_ARROWBTN)).width();
+ IntSize(blink::Platform::current()->themeEngine()->getSize(SBP_ARROWBTN)).width();
return width;
}
@@ -396,8 +395,8 @@ bool RenderThemeChromiumWin::paintMenuListButton(RenderObject* o, const PaintInf
// Get the correct theme data for a textfield and paint the menu.
ThemePainter painter(i.context, rect);
- WebKit::WebCanvas* canvas = painter.context()->canvas();
- WebKit::Platform::current()->themeEngine()->paintMenuList(canvas, CP_DROPDOWNBUTTON, determineState(o), determineClassicState(o), WebKit::WebRect(painter.drawRect()));
+ blink::WebCanvas* canvas = painter.context()->canvas();
+ blink::Platform::current()->themeEngine()->paintMenuList(canvas, CP_DROPDOWNBUTTON, determineState(o), determineClassicState(o), blink::WebRect(painter.drawRect()));
return false;
}
@@ -573,8 +572,8 @@ bool RenderThemeChromiumWin::paintTextFieldInternal(RenderObject* o,
{
const ThemeData& themeData = getThemeData(o);
ThemePainter painter(i.context, r);
- WebKit::WebCanvas* canvas = painter.context()->canvas();
- WebKit::Platform::current()->themeEngine()->paintTextField(canvas, themeData.m_part, themeData.m_state, themeData.m_classicState, WebKit::WebRect(painter.drawRect()), backgroundColor.rgb(), fillContentArea, drawEdges);
+ blink::WebCanvas* canvas = painter.context()->canvas();
+ blink::Platform::current()->themeEngine()->paintTextField(canvas, themeData.m_part, themeData.m_state, themeData.m_classicState, blink::WebRect(painter.drawRect()), backgroundColor.rgb(), fillContentArea, drawEdges);
// End of block commits the painter before restoring context.
}
if (o->style()->hasBorderRadius())
@@ -598,16 +597,16 @@ bool RenderThemeChromiumWin::paintInnerSpinButton(RenderObject* object, const Pa
half.setHeight(rect.height() / 2);
const ThemeData& upThemeData = getThemeData(object, SpinButtonUp);
ThemePainter upPainter(info.context, half);
- WebKit::WebCanvas* canvas = upPainter.context()->canvas();
- WebKit::Platform::current()->themeEngine()->paintSpinButton(canvas, upThemeData.m_part, upThemeData.m_state, upThemeData.m_classicState, WebKit::WebRect(upPainter.drawRect()));
+ blink::WebCanvas* canvas = upPainter.context()->canvas();
+ blink::Platform::current()->themeEngine()->paintSpinButton(canvas, upThemeData.m_part, upThemeData.m_state, upThemeData.m_classicState, blink::WebRect(upPainter.drawRect()));
}
{
half.setY(rect.y() + rect.height() / 2);
const ThemeData& downThemeData = getThemeData(object, SpinButtonDown);
ThemePainter downPainter(info.context, half);
- WebKit::WebCanvas* canvas = downPainter.context()->canvas();
- WebKit::Platform::current()->themeEngine()->paintSpinButton(canvas, downThemeData.m_part, downThemeData.m_state, downThemeData.m_classicState, WebKit::WebRect(downPainter.drawRect()));
+ blink::WebCanvas* canvas = downPainter.context()->canvas();
+ blink::Platform::current()->themeEngine()->paintSpinButton(canvas, downThemeData.m_part, downThemeData.m_state, downThemeData.m_classicState, blink::WebRect(downPainter.drawRect()));
}
return false;
}
@@ -628,10 +627,6 @@ double RenderThemeChromiumWin::animationDurationForProgressBar(RenderProgress* r
return progressAnimationFrameRate;
}
-void RenderThemeChromiumWin::adjustProgressBarStyle(RenderStyle*, Element*) const
-{
-}
-
bool RenderThemeChromiumWin::paintProgressBar(RenderObject* o, const PaintInfo& i, const IntRect& r)
{
if (!o->isProgress())
@@ -644,8 +639,8 @@ bool RenderThemeChromiumWin::paintProgressBar(RenderObject* o, const PaintInfo&
double animatedSeconds = renderProgress->animationStartTime() ? WTF::currentTime() - renderProgress->animationStartTime() : 0;
ThemePainter painter(i.context, r);
DirectionFlippingScope scope(o, i, r);
- WebKit::WebCanvas* canvas = painter.context()->canvas();
- WebKit::Platform::current()->themeEngine()->paintProgressBar(canvas, WebKit::WebRect(r), WebKit::WebRect(valueRect), renderProgress->isDeterminate(), animatedSeconds);
+ blink::WebCanvas* canvas = painter.context()->canvas();
+ blink::Platform::current()->themeEngine()->paintProgressBar(canvas, blink::WebRect(r), blink::WebRect(valueRect), renderProgress->isDeterminate(), animatedSeconds);
return false;
}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderThemeChromiumWin.h b/chromium/third_party/WebKit/Source/core/rendering/RenderThemeChromiumWin.h
index 2b59a220796..b44e44bb51e 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderThemeChromiumWin.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderThemeChromiumWin.h
@@ -82,7 +82,6 @@ public:
virtual double animationRepeatIntervalForProgressBar(RenderProgress*) const OVERRIDE;
virtual double animationDurationForProgressBar(RenderProgress*) const OVERRIDE;
- virtual void adjustProgressBarStyle(RenderStyle*, Element*) const OVERRIDE;
virtual bool paintProgressBar(RenderObject*, const PaintInfo&, const IntRect&) OVERRIDE;
virtual bool shouldOpenPickerWithF4Key() const OVERRIDE;
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderTreeAsText.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderTreeAsText.cpp
index 319f7525e48..ccc630e5e81 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderTreeAsText.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderTreeAsText.cpp
@@ -31,9 +31,10 @@
#include "core/dom/Document.h"
#include "core/editing/FrameSelection.h"
#include "core/html/HTMLElement.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameView.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
#include "core/page/PrintContext.h"
+#include "core/rendering/CompositedLayerMapping.h"
#include "core/rendering/FlowThreadController.h"
#include "core/rendering/InlineTextBox.h"
#include "core/rendering/RenderBR.h"
@@ -41,7 +42,6 @@
#include "core/rendering/RenderFileUploadControl.h"
#include "core/rendering/RenderInline.h"
#include "core/rendering/RenderLayer.h"
-#include "core/rendering/RenderLayerBacking.h"
#include "core/rendering/RenderListItem.h"
#include "core/rendering/RenderListMarker.h"
#include "core/rendering/RenderNamedFlowThread.h"
@@ -59,7 +59,6 @@
#include "core/rendering/svg/RenderSVGText.h"
#include "core/rendering/svg/SVGRenderTreeAsText.h"
#include "wtf/HexNumber.h"
-#include "wtf/UnusedParam.h"
#include "wtf/Vector.h"
#include "wtf/unicode/CharacterNames.h"
@@ -67,39 +66,6 @@ namespace WebCore {
using namespace HTMLNames;
-static void writeLayers(TextStream&, const RenderLayer* rootLayer, RenderLayer*, const LayoutRect& paintDirtyRect, int indent = 0, RenderAsTextBehavior = RenderAsTextBehaviorNormal);
-
-TextStream& operator<<(TextStream& ts, const IntRect& r)
-{
- return ts << "at (" << r.x() << "," << r.y() << ") size " << r.width() << "x" << r.height();
-}
-
-TextStream& operator<<(TextStream& ts, const IntPoint& p)
-{
- return ts << "(" << p.x() << "," << p.y() << ")";
-}
-
-TextStream& operator<<(TextStream& ts, const FloatPoint& p)
-{
- ts << "(" << TextStream::FormatNumberRespectingIntegers(p.x());
- ts << "," << TextStream::FormatNumberRespectingIntegers(p.y());
- ts << ")";
- return ts;
-}
-
-TextStream& operator<<(TextStream& ts, const FloatSize& s)
-{
- ts << "width=" << TextStream::FormatNumberRespectingIntegers(s.width());
- ts << " height=" << TextStream::FormatNumberRespectingIntegers(s.height());
- return ts;
-}
-
-void writeIndent(TextStream& ts, int indent)
-{
- for (int i = 0; i != indent; ++i)
- ts << " ";
-}
-
static void printBorderStyle(TextStream& ts, const EBorderStyle borderStyle)
{
switch (borderStyle) {
@@ -524,7 +490,7 @@ void write(TextStream& ts, const RenderObject& o, int indent, RenderAsTextBehavi
view->layout();
RenderLayer* l = root->layer();
if (l)
- writeLayers(ts, l, l, l->rect(), indent + 1, behavior);
+ RenderTreeAsText::writeLayers(ts, l, l, l->rect(), indent + 1, behavior);
}
}
}
@@ -547,6 +513,9 @@ static void write(TextStream& ts, RenderLayer& l,
writeIndent(ts, indent);
+ if (l.renderer()->style()->visibility() == HIDDEN)
+ ts << "hidden ";
+
ts << "layer ";
if (behavior & RenderAsTextShowAddresses)
@@ -562,16 +531,18 @@ static void write(TextStream& ts, RenderLayer& l,
if (!adjustedOutlineClipRect.contains(adjustedLayoutBounds))
ts << " outlineClip " << adjustedOutlineClipRect;
}
+ if (l.isTransparent())
+ ts << " transparent";
if (l.renderer()->hasOverflowClip()) {
- if (l.scrollXOffset())
- ts << " scrollX " << l.scrollXOffset();
- if (l.scrollYOffset())
- ts << " scrollY " << l.scrollYOffset();
- if (l.renderBox() && l.renderBox()->pixelSnappedClientWidth() != l.scrollWidth())
- ts << " scrollWidth " << l.scrollWidth();
- if (l.renderBox() && l.renderBox()->pixelSnappedClientHeight() != l.scrollHeight())
- ts << " scrollHeight " << l.scrollHeight();
+ if (l.scrollableArea()->scrollXOffset())
+ ts << " scrollX " << l.scrollableArea()->scrollXOffset();
+ if (l.scrollableArea()->scrollYOffset())
+ ts << " scrollY " << l.scrollableArea()->scrollYOffset();
+ if (l.renderBox() && l.renderBox()->pixelSnappedClientWidth() != l.renderBox()->scrollWidth())
+ ts << " scrollWidth " << l.renderBox()->scrollWidth();
+ if (l.renderBox() && l.renderBox()->pixelSnappedClientHeight() != l.renderBox()->scrollHeight())
+ ts << " scrollHeight " << l.renderBox()->scrollHeight();
}
if (paintPhase == LayerPaintPhaseBackground)
@@ -580,8 +551,15 @@ static void write(TextStream& ts, RenderLayer& l,
ts << " layerType: foreground only";
if (behavior & RenderAsTextShowCompositedLayers) {
- if (l.isComposited())
- ts << " (composited, bounds=" << l.backing()->compositedBounds() << ", drawsContent=" << l.backing()->graphicsLayer()->drawsContent() << ", paints into ancestor=" << l.backing()->paintsIntoCompositedAncestor() << ")";
+ if (l.hasCompositedLayerMapping()) {
+ ts << " (composited, bounds="
+ << l.compositedLayerMapping()->compositedBounds()
+ << ", drawsContent="
+ << l.compositedLayerMapping()->mainGraphicsLayer()->drawsContent()
+ << ", paints into ancestor="
+ << l.compositedLayerMapping()->paintsIntoCompositedAncestor()
+ << ")";
+ }
}
ts << "\n";
@@ -593,24 +571,47 @@ static void write(TextStream& ts, RenderLayer& l,
static void writeRenderRegionList(const RenderRegionList& flowThreadRegionList, TextStream& ts, int indent)
{
for (RenderRegionList::const_iterator itRR = flowThreadRegionList.begin(); itRR != flowThreadRegionList.end(); ++itRR) {
- RenderRegion* renderRegion = *itRR;
- writeIndent(ts, indent + 2);
- ts << "RenderRegion";
- if (renderRegion->generatingNode()) {
- String tagName = getTagName(renderRegion->generatingNode());
- if (!tagName.isEmpty())
- ts << " {" << tagName << "}";
- if (renderRegion->generatingNode()->isElementNode() && renderRegion->generatingNode()->hasID()) {
- Element* element = toElement(renderRegion->generatingNode());
- ts << " #" << element->idForStyleResolution();
- }
+ const RenderRegion* renderRegion = *itRR;
+
+ writeIndent(ts, indent);
+ ts << renderRegion->renderName();
+
+ Node* generatingNodeForRegion = renderRegion->generatingNodeForRegion();
+ if (generatingNodeForRegion) {
if (renderRegion->hasCustomRegionStyle())
ts << " region style: 1";
if (renderRegion->hasAutoLogicalHeight())
ts << " hasAutoLogicalHeight";
+
+ bool isRenderNamedFlowFragment = renderRegion->isRenderNamedFlowFragment();
+ if (isRenderNamedFlowFragment)
+ ts << " (anonymous child of";
+
+ StringBuilder tagName;
+ tagName.append(generatingNodeForRegion->nodeName());
+
+ Node* nodeForRegion = renderRegion->nodeForRegion();
+ if (nodeForRegion->isPseudoElement()) {
+ if (nodeForRegion->isBeforePseudoElement())
+ tagName.append("::before");
+ else if (nodeForRegion->isAfterPseudoElement())
+ tagName.append("::after");
+ }
+
+ ts << " {" << tagName.toString() << "}";
+
+ if (generatingNodeForRegion->isElementNode() && generatingNodeForRegion->hasID()) {
+ Element* element = toElement(generatingNodeForRegion);
+ ts << " #" << element->idForStyleResolution();
+ }
+
+ if (isRenderNamedFlowFragment)
+ ts << ")";
}
+
if (!renderRegion->isValid())
ts << " invalid";
+
ts << "\n";
}
}
@@ -624,53 +625,59 @@ static void writeRenderNamedFlowThreads(TextStream& ts, RenderView* renderView,
const RenderNamedFlowThreadList* list = renderView->flowThreadController()->renderNamedFlowThreadList();
writeIndent(ts, indent);
- ts << "Flow Threads\n";
+ ts << "Named flows\n";
for (RenderNamedFlowThreadList::const_iterator iter = list->begin(); iter != list->end(); ++iter) {
const RenderNamedFlowThread* renderFlowThread = *iter;
writeIndent(ts, indent + 1);
- ts << "Thread with flow-name '" << renderFlowThread->flowThreadName() << "'\n";
+ ts << "Named flow '" << renderFlowThread->flowThreadName() << "'\n";
RenderLayer* layer = renderFlowThread->layer();
- writeLayers(ts, rootLayer, layer, paintRect, indent + 2, behavior);
+ RenderTreeAsText::writeLayers(ts, rootLayer, layer, paintRect, indent + 2, behavior);
// Display the valid and invalid render regions attached to this flow thread.
const RenderRegionList& validRegionsList = renderFlowThread->renderRegionList();
+ if (!validRegionsList.isEmpty()) {
+ writeIndent(ts, indent + 2);
+ ts << "Regions for named flow '" << renderFlowThread->flowThreadName() << "'\n";
+ writeRenderRegionList(validRegionsList, ts, indent + 3);
+ }
+
const RenderRegionList& invalidRegionsList = renderFlowThread->invalidRenderRegionList();
- if (!validRegionsList.isEmpty() || !invalidRegionsList.isEmpty()) {
- writeIndent(ts, indent + 1);
- ts << "Regions for flow '"<< renderFlowThread->flowThreadName() << "'\n";
- writeRenderRegionList(validRegionsList, ts, indent);
- writeRenderRegionList(invalidRegionsList, ts, indent);
+ if (!invalidRegionsList.isEmpty()) {
+ writeIndent(ts, indent + 2);
+ ts << "Invalid regions for named flow '" << renderFlowThread->flowThreadName() << "'\n";
+ writeRenderRegionList(invalidRegionsList, ts, indent + 3);
}
}
}
-static void writeLayers(TextStream& ts, const RenderLayer* rootLayer, RenderLayer* l,
+void RenderTreeAsText::writeLayers(TextStream& ts, const RenderLayer* rootLayer, RenderLayer* layer,
const LayoutRect& paintRect, int indent, RenderAsTextBehavior behavior)
{
// FIXME: Apply overflow to the root layer to not break every test. Complete hack. Sigh.
LayoutRect paintDirtyRect(paintRect);
- if (rootLayer == l) {
+ if (rootLayer == layer) {
paintDirtyRect.setWidth(max<LayoutUnit>(paintDirtyRect.width(), rootLayer->renderBox()->layoutOverflowRect().maxX()));
paintDirtyRect.setHeight(max<LayoutUnit>(paintDirtyRect.height(), rootLayer->renderBox()->layoutOverflowRect().maxY()));
- l->setSize(l->size().expandedTo(pixelSnappedIntSize(l->renderBox()->maxLayoutOverflow(), LayoutPoint(0, 0))));
+ layer->setSize(layer->size().expandedTo(pixelSnappedIntSize(layer->renderBox()->maxLayoutOverflow(), LayoutPoint(0, 0))));
}
// Calculate the clip rects we should use.
LayoutRect layerBounds;
ClipRect damageRect, clipRectToApply, outlineRect;
- l->calculateRects(RenderLayer::ClipRectsContext(rootLayer, 0, TemporaryClipRects), paintDirtyRect, layerBounds, damageRect, clipRectToApply, outlineRect);
+ layer->calculateRects(ClipRectsContext(rootLayer, 0, TemporaryClipRects), paintDirtyRect, layerBounds, damageRect, clipRectToApply, outlineRect);
// Ensure our lists are up-to-date.
- l->updateLayerListsIfNeeded();
+ layer->stackingNode()->updateLayerListsIfNeeded();
+
+ bool shouldPaint = (behavior & RenderAsTextShowAllLayers) ? true : layer->intersectsDamageRect(layerBounds, damageRect.rect(), rootLayer);
- bool shouldPaint = (behavior & RenderAsTextShowAllLayers) ? true : l->intersectsDamageRect(layerBounds, damageRect.rect(), rootLayer);
- Vector<RenderLayer*>* negList = l->negZOrderList();
+ Vector<RenderLayerStackingNode*>* negList = layer->stackingNode()->negZOrderList();
bool paintsBackgroundSeparately = negList && negList->size() > 0;
if (shouldPaint && paintsBackgroundSeparately)
- write(ts, *l, layerBounds, damageRect.rect(), clipRectToApply.rect(), outlineRect.rect(), LayerPaintPhaseBackground, indent, behavior);
+ write(ts, *layer, layerBounds, damageRect.rect(), clipRectToApply.rect(), outlineRect.rect(), LayerPaintPhaseBackground, indent, behavior);
if (negList) {
int currIndent = indent;
@@ -680,13 +687,13 @@ static void writeLayers(TextStream& ts, const RenderLayer* rootLayer, RenderLaye
++currIndent;
}
for (unsigned i = 0; i != negList->size(); ++i)
- writeLayers(ts, rootLayer, negList->at(i), paintDirtyRect, currIndent, behavior);
+ writeLayers(ts, rootLayer, negList->at(i)->layer(), paintDirtyRect, currIndent, behavior);
}
if (shouldPaint)
- write(ts, *l, layerBounds, damageRect.rect(), clipRectToApply.rect(), outlineRect.rect(), paintsBackgroundSeparately ? LayerPaintPhaseForeground : LayerPaintPhaseAll, indent, behavior);
+ write(ts, *layer, layerBounds, damageRect.rect(), clipRectToApply.rect(), outlineRect.rect(), paintsBackgroundSeparately ? LayerPaintPhaseForeground : LayerPaintPhaseAll, indent, behavior);
- if (Vector<RenderLayer*>* normalFlowList = l->normalFlowList()) {
+ if (Vector<RenderLayerStackingNode*>* normalFlowList = layer->stackingNode()->normalFlowList()) {
int currIndent = indent;
if (behavior & RenderAsTextShowLayerNesting) {
writeIndent(ts, indent);
@@ -694,10 +701,10 @@ static void writeLayers(TextStream& ts, const RenderLayer* rootLayer, RenderLaye
++currIndent;
}
for (unsigned i = 0; i != normalFlowList->size(); ++i)
- writeLayers(ts, rootLayer, normalFlowList->at(i), paintDirtyRect, currIndent, behavior);
+ writeLayers(ts, rootLayer, normalFlowList->at(i)->layer(), paintDirtyRect, currIndent, behavior);
}
- if (Vector<RenderLayer*>* posList = l->posZOrderList()) {
+ if (Vector<RenderLayerStackingNode*>* posList = layer->stackingNode()->posZOrderList()) {
int currIndent = indent;
if (behavior & RenderAsTextShowLayerNesting) {
writeIndent(ts, indent);
@@ -705,13 +712,13 @@ static void writeLayers(TextStream& ts, const RenderLayer* rootLayer, RenderLaye
++currIndent;
}
for (unsigned i = 0; i != posList->size(); ++i)
- writeLayers(ts, rootLayer, posList->at(i), paintDirtyRect, currIndent, behavior);
+ writeLayers(ts, rootLayer, posList->at(i)->layer(), paintDirtyRect, currIndent, behavior);
}
// Altough the RenderFlowThread requires a layer, it is not collected by its parent,
// so we have to treat it as a special case.
- if (l->renderer()->isRenderView()) {
- RenderView* renderView = toRenderView(l->renderer());
+ if (layer->renderer()->isRenderView()) {
+ RenderView* renderView = toRenderView(layer->renderer());
writeRenderNamedFlowThreads(ts, renderView, rootLayer, paintDirtyRect, indent, behavior);
}
}
@@ -779,7 +786,7 @@ static String externalRepresentation(RenderBox* renderer, RenderAsTextBehavior b
return ts.release();
RenderLayer* layer = renderer->layer();
- writeLayers(ts, layer, layer, layer->rect(), 0, behavior);
+ RenderTreeAsText::writeLayers(ts, layer, layer, layer->rect(), 0, behavior);
writeSelection(ts, renderer);
return ts.release();
}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderTreeAsText.h b/chromium/third_party/WebKit/Source/core/rendering/RenderTreeAsText.h
index 61bbadb508a..63c900ca947 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderTreeAsText.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderTreeAsText.h
@@ -25,19 +25,16 @@
#ifndef RenderTreeAsText_h
#define RenderTreeAsText_h
-#include "core/platform/text/TextStream.h"
+#include "platform/text/TextStream.h"
#include "wtf/Forward.h"
namespace WebCore {
class Element;
-class FloatPoint;
-class FloatSize;
class Frame;
-class IntPoint;
-class IntRect;
-class LayoutPoint;
+class LayoutRect;
+class RenderLayer;
class RenderObject;
class TextStream;
@@ -58,7 +55,6 @@ typedef unsigned RenderAsTextBehavior;
String externalRepresentation(Frame*, RenderAsTextBehavior = RenderAsTextBehaviorNormal);
String externalRepresentation(Element*, RenderAsTextBehavior = RenderAsTextBehaviorNormal);
void write(TextStream&, const RenderObject&, int indent = 0, RenderAsTextBehavior = RenderAsTextBehaviorNormal);
-void writeIndent(TextStream&, int indent);
class RenderTreeAsText {
// FIXME: This is a cheesy hack to allow easy access to RenderStyle colors. It won't be needed if we convert
@@ -66,30 +62,9 @@ class RenderTreeAsText {
// not being done).
public:
static void writeRenderObject(TextStream& ts, const RenderObject& o, RenderAsTextBehavior behavior);
+static void writeLayers(TextStream&, const RenderLayer* rootLayer, RenderLayer*, const LayoutRect& paintDirtyRect, int indent = 0, RenderAsTextBehavior = RenderAsTextBehaviorNormal);
};
-TextStream& operator<<(TextStream&, const IntPoint&);
-TextStream& operator<<(TextStream&, const IntRect&);
-TextStream& operator<<(TextStream&, const LayoutPoint&);
-TextStream& operator<<(TextStream&, const FloatPoint&);
-TextStream& operator<<(TextStream&, const FloatSize&);
-
-template<typename Item>
-TextStream& operator<<(TextStream& ts, const Vector<Item>& vector)
-{
- ts << "[";
-
- unsigned size = vector.size();
- for (unsigned i = 0; i < size; ++i) {
- ts << vector[i];
- if (i < size - 1)
- ts << ", ";
- }
-
- ts << "]";
- return ts;
-}
-
// Helper function shared with SVGRenderTreeAsText
String quoteAndEscapeNonPrintables(const String&);
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderVTTCue.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderVTTCue.cpp
new file mode 100644
index 00000000000..4507321ee6f
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderVTTCue.cpp
@@ -0,0 +1,272 @@
+/*
+ * Copyright (C) 2012 Victor Carbune (victor@rosedu.org)
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/rendering/RenderVTTCue.h"
+
+#include "core/html/track/vtt/VTTCue.h"
+#include "core/rendering/LayoutRectRecorder.h"
+#include "core/rendering/RenderView.h"
+
+namespace WebCore {
+
+RenderVTTCue::RenderVTTCue(VTTCueBox* element)
+ : RenderBlockFlow(element)
+ , m_cue(element->getCue())
+{
+}
+
+void RenderVTTCue::layout()
+{
+ LayoutRectRecorder recorder(*this);
+ RenderBlockFlow::layout();
+
+ // If WebVTT Regions are used, the regular WebVTT layout algorithm is no
+ // longer necessary, since cues having the region parameter set do not have
+ // any positioning parameters. Also, in this case, the regions themselves
+ // have positioning information.
+ if (!m_cue->regionId().isEmpty())
+ return;
+
+ LayoutStateMaintainer statePusher(view(), this, locationOffset(), hasTransform() || hasReflection() || style()->isFlippedBlocksWritingMode());
+
+ if (m_cue->snapToLines())
+ repositionCueSnapToLinesSet();
+ else
+ repositionCueSnapToLinesNotSet();
+
+ statePusher.pop();
+}
+
+bool RenderVTTCue::findFirstLineBox(InlineFlowBox*& firstLineBox)
+{
+ if (firstChild()->isRenderInline())
+ firstLineBox = toRenderInline(firstChild())->firstLineBox();
+ else
+ return false;
+
+ return true;
+}
+
+bool RenderVTTCue::initializeLayoutParameters(InlineFlowBox* firstLineBox, LayoutUnit& step, LayoutUnit& position)
+{
+ ASSERT(firstChild());
+
+ RenderBlock* parentBlock = containingBlock();
+
+ // 1. Horizontal: Let step be the height of the first line box in boxes.
+ // Vertical: Let step be the width of the first line box in boxes.
+ step = m_cue->getWritingDirection() == VTTCue::Horizontal ? firstLineBox->height() : firstLineBox->width();
+
+ // 2. If step is zero, then jump to the step labeled done positioning below.
+ if (!step)
+ return false;
+
+ // 3. Let line position be the text track cue computed line position.
+ int linePosition = m_cue->calculateComputedLinePosition();
+
+ // 4. Vertical Growing Left: Add one to line position then negate it.
+ if (m_cue->getWritingDirection() == VTTCue::VerticalGrowingLeft)
+ linePosition = -(linePosition + 1);
+
+ // 5. Let position be the result of multiplying step and line position.
+ position = step * linePosition;
+
+ // 6. Vertical Growing Left: Decrease position by the width of the
+ // bounding box of the boxes in boxes, then increase position by step.
+ if (m_cue->getWritingDirection() == VTTCue::VerticalGrowingLeft) {
+ position -= width();
+ position += step;
+ }
+
+ // 7. If line position is less than zero...
+ if (linePosition < 0) {
+ // Horizontal / Vertical: ... then increase position by the
+ // height / width of the video's rendering area ...
+ position += m_cue->getWritingDirection() == VTTCue::Horizontal ? parentBlock->height() : parentBlock->width();
+
+ // ... and negate step.
+ step = -step;
+ }
+
+ return true;
+}
+
+void RenderVTTCue::placeBoxInDefaultPosition(LayoutUnit position, bool& switched)
+{
+ // 8. Move all boxes in boxes ...
+ if (m_cue->getWritingDirection() == VTTCue::Horizontal) {
+ // Horizontal: ... down by the distance given by position
+ setY(y() + position);
+ } else {
+ // Vertical: ... right by the distance given by position
+ setX(x() + position);
+ }
+
+ // 9. Default: Remember the position of all the boxes in boxes as their
+ // default position.
+ m_fallbackPosition = FloatPoint(x(), y());
+
+ // 10. Let switched be false.
+ switched = false;
+}
+
+bool RenderVTTCue::isOutside() const
+{
+ return !containingBlock()->absoluteBoundingBoxRect().contains(absoluteContentBox());
+}
+
+bool RenderVTTCue::isOverlapping() const
+{
+ for (RenderObject* box = previousSibling(); box; box = box->previousSibling()) {
+ IntRect boxRect = box->absoluteBoundingBoxRect();
+
+ if (absoluteBoundingBoxRect().intersects(boxRect))
+ return true;
+ }
+
+ return false;
+}
+
+bool RenderVTTCue::shouldSwitchDirection(InlineFlowBox* firstLineBox, LayoutUnit step) const
+{
+ LayoutUnit top = y();
+ LayoutUnit left = x();
+ LayoutUnit bottom = top + firstLineBox->height();
+ LayoutUnit right = left + firstLineBox->width();
+
+ // 12. Horizontal: If step is negative and the top of the first line
+ // box in boxes is now above the top of the video's rendering area,
+ // or if step is positive and the bottom of the first line box in
+ // boxes is now below the bottom of the video's rendering area, jump
+ // to the step labeled switch direction.
+ LayoutUnit parentHeight = containingBlock()->height();
+ if (m_cue->getWritingDirection() == VTTCue::Horizontal && ((step < 0 && top < 0) || (step > 0 && bottom > parentHeight)))
+ return true;
+
+ // 12. Vertical: If step is negative and the left edge of the first line
+ // box in boxes is now to the left of the left edge of the video's
+ // rendering area, or if step is positive and the right edge of the
+ // first line box in boxes is now to the right of the right edge of
+ // the video's rendering area, jump to the step labeled switch direction.
+ LayoutUnit parentWidth = containingBlock()->width();
+ if (m_cue->getWritingDirection() != VTTCue::Horizontal && ((step < 0 && left < 0) || (step > 0 && right > parentWidth)))
+ return true;
+
+ return false;
+}
+
+void RenderVTTCue::moveBoxesByStep(LayoutUnit step)
+{
+ // 13. Horizontal: Move all the boxes in boxes down by the distance
+ // given by step. (If step is negative, then this will actually
+ // result in an upwards movement of the boxes in absolute terms.)
+ if (m_cue->getWritingDirection() == VTTCue::Horizontal)
+ setY(y() + step);
+
+ // 13. Vertical: Move all the boxes in boxes right by the distance
+ // given by step. (If step is negative, then this will actually
+ // result in a leftwards movement of the boxes in absolute terms.)
+ else
+ setX(x() + step);
+}
+
+bool RenderVTTCue::switchDirection(bool& switched, LayoutUnit& step)
+{
+ // 15. Switch direction: Move all the boxes in boxes back to their
+ // default position as determined in the step above labeled default.
+ setX(m_fallbackPosition.x());
+ setY(m_fallbackPosition.y());
+
+ // 16. If switched is true, jump to the step labeled done
+ // positioning below.
+ if (switched)
+ return false;
+
+ // 17. Negate step.
+ step = -step;
+
+ // 18. Set switched to true.
+ switched = true;
+ return true;
+}
+
+void RenderVTTCue::repositionCueSnapToLinesSet()
+{
+ InlineFlowBox* firstLineBox;
+ LayoutUnit step;
+ LayoutUnit position;
+
+ if (!findFirstLineBox(firstLineBox))
+ return;
+
+ if (!initializeLayoutParameters(firstLineBox, step, position))
+ return;
+
+ bool switched;
+ placeBoxInDefaultPosition(position, switched);
+
+ // 11. Step loop: If none of the boxes in boxes would overlap any of the boxes
+ // in output and all the boxes in output are within the video's rendering area
+ // then jump to the step labeled done positioning.
+ while (isOutside() || isOverlapping()) {
+ if (!shouldSwitchDirection(firstLineBox, step)) {
+ // 13. Move all the boxes in boxes ...
+ // 14. Jump back to the step labeled step loop.
+ moveBoxesByStep(step);
+ } else if (!switchDirection(switched, step)) {
+ break;
+ }
+
+ // 19. Jump back to the step labeled step loop.
+ }
+
+ // Acommodate extra top and bottom padding, border or margin.
+ // Note: this is supported only for internal UA styling, not through the cue selector.
+ if (hasInlineDirectionBordersPaddingOrMargin()) {
+ IntRect containerRect = containingBlock()->absoluteBoundingBoxRect();
+ IntRect cueRect = absoluteBoundingBoxRect();
+
+ int topOverflow = cueRect.y() - containerRect.y();
+ int bottomOverflow = containerRect.y() + containerRect.height() - cueRect.y() - cueRect.height();
+
+ int adjustment = 0;
+ if (topOverflow < 0)
+ adjustment = -topOverflow;
+ else if (bottomOverflow < 0)
+ adjustment = bottomOverflow;
+
+ if (adjustment)
+ setY(y() + adjustment);
+ }
+}
+
+void RenderVTTCue::repositionCueSnapToLinesNotSet()
+{
+ // FIXME: Implement overlapping detection when snap-to-lines is not set. http://wkb.ug/84296
+}
+
+} // namespace WebCore
+
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderVTTCue.h b/chromium/third_party/WebKit/Source/core/rendering/RenderVTTCue.h
new file mode 100644
index 00000000000..d357b24cc3a
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderVTTCue.h
@@ -0,0 +1,65 @@
+/*
+ * Copyright (C) 2012 Victor Carbune (victor@rosedu.org)
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef RenderVTTCue_h
+#define RenderVTTCue_h
+
+#include "core/rendering/RenderBlockFlow.h"
+#include "core/rendering/RenderInline.h"
+#include "platform/geometry/FloatPoint.h"
+
+namespace WebCore {
+
+class VTTCue;
+class VTTCueBox;
+
+class RenderVTTCue FINAL : public RenderBlockFlow {
+public:
+ explicit RenderVTTCue(VTTCueBox*);
+
+private:
+ virtual void layout() OVERRIDE;
+ virtual bool supportsPartialLayout() const OVERRIDE { return false; }
+
+ bool isOutside() const;
+ bool isOverlapping() const;
+ bool shouldSwitchDirection(InlineFlowBox*, LayoutUnit) const;
+
+ void moveBoxesByStep(LayoutUnit);
+ bool switchDirection(bool&, LayoutUnit&);
+
+ bool findFirstLineBox(InlineFlowBox*&);
+ bool initializeLayoutParameters(InlineFlowBox*, LayoutUnit&, LayoutUnit&);
+ void placeBoxInDefaultPosition(LayoutUnit, bool&);
+ void repositionCueSnapToLinesSet();
+ void repositionCueSnapToLinesNotSet();
+
+ VTTCue* m_cue;
+ FloatPoint m_fallbackPosition;
+};
+
+} // namespace WebCore
+
+#endif // RenderVTTCue_h
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderVideo.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderVideo.cpp
index f551f995ea3..b498f90186a 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderVideo.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderVideo.cpp
@@ -30,12 +30,14 @@
#include "HTMLNames.h"
#include "core/dom/Document.h"
#include "core/html/HTMLVideoElement.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameView.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
#include "core/page/Page.h"
-#include "core/platform/graphics/MediaPlayer.h"
+#include "core/rendering/LayoutRectRecorder.h"
#include "core/rendering/PaintInfo.h"
#include "core/rendering/RenderFullScreen.h"
+#include "platform/graphics/media/MediaPlayer.h"
+#include "public/platform/WebLayer.h"
namespace WebCore {
@@ -107,12 +109,6 @@ LayoutSize RenderVideo::calculateIntrinsicSize()
if (video->shouldDisplayPosterImage() && !m_cachedImageSize.isEmpty() && !imageResource()->errorOccurred())
return m_cachedImageSize;
- // When the natural size of the video is unavailable, we use the provided
- // width and height attributes of the video element as the intrinsic size until
- // better values become available.
- if (video->hasAttribute(widthAttr) && video->hasAttribute(heightAttr))
- return LayoutSize(video->width(), video->height());
-
// <video> in standalone media documents should not use the default 300x150
// size since they also have audio-only files. By setting the intrinsic
// size to 300x1 the video will resize itself in these cases, and audio will
@@ -156,28 +152,14 @@ void RenderVideo::paintReplaced(PaintInfo& paintInfo, const LayoutPoint& paintOf
{
MediaPlayer* mediaPlayer = mediaElement()->player();
bool displayingPoster = videoElement()->shouldDisplayPosterImage();
-
- Page* page = 0;
- if (Frame* frame = this->frame())
- page = frame->page();
-
- if (!displayingPoster && !mediaPlayer) {
- if (page && paintInfo.phase == PaintPhaseForeground)
- page->addRelevantUnpaintedObject(this, visualOverflowRect());
+ if (!displayingPoster && !mediaPlayer)
return;
- }
LayoutRect rect = videoBox();
- if (rect.isEmpty()) {
- if (page && paintInfo.phase == PaintPhaseForeground)
- page->addRelevantUnpaintedObject(this, visualOverflowRect());
+ if (rect.isEmpty())
return;
- }
rect.moveBy(paintOffset);
- if (page && paintInfo.phase == PaintPhaseForeground)
- page->addRelevantRepaintedObject(this, rect);
-
LayoutRect contentRect = contentBoxRect();
contentRect.moveBy(paintOffset);
GraphicsContext* context = paintInfo.context;
@@ -189,17 +171,22 @@ void RenderVideo::paintReplaced(PaintInfo& paintInfo, const LayoutPoint& paintOf
if (displayingPoster)
paintIntoRect(context, rect);
- else if (document().view() && document().view()->paintBehavior() & PaintBehaviorFlattenCompositingLayers)
- mediaPlayer->paintCurrentFrameInContext(context, pixelSnappedIntRect(rect));
- else
+ else if ((document().view() && document().view()->paintBehavior() & PaintBehaviorFlattenCompositingLayers) || !acceleratedRenderingInUse())
mediaPlayer->paint(context, pixelSnappedIntRect(rect));
if (clip)
context->restore();
}
+bool RenderVideo::acceleratedRenderingInUse()
+{
+ blink::WebLayer* webLayer = mediaElement()->platformLayer();
+ return webLayer && !webLayer->isOrphan();
+}
+
void RenderVideo::layout()
{
+ LayoutRectRecorder recorder(*this);
updatePlayer();
RenderMedia::layout();
}
@@ -224,7 +211,7 @@ void RenderVideo::updatePlayer()
if (!mediaPlayer)
return;
- if (!videoElement()->inActiveDocument())
+ if (!videoElement()->isActive())
return;
contentChanged(VideoChanged);
@@ -247,11 +234,7 @@ LayoutUnit RenderVideo::minimumReplacedHeight() const
bool RenderVideo::supportsAcceleratedRendering() const
{
- MediaPlayer* p = mediaElement()->player();
- if (p)
- return p->supportsAcceleratedRendering();
-
- return false;
+ return !!mediaElement()->platformLayer();
}
static const RenderBlock* rendererPlaceholder(const RenderObject* renderer)
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderVideo.h b/chromium/third_party/WebKit/Source/core/rendering/RenderVideo.h
index 03eeb2cf84f..40a400d9075 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderVideo.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderVideo.h
@@ -76,23 +76,12 @@ private:
void updatePlayer();
+ bool acceleratedRenderingInUse();
+
LayoutSize m_cachedImageSize;
};
-inline RenderVideo* toRenderVideo(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isVideo());
- return static_cast<RenderVideo*>(object);
-}
-
-inline const RenderVideo* toRenderVideo(const RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isVideo());
- return static_cast<const RenderVideo*>(object);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toRenderVideo(const RenderVideo*);
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderVideo, isVideo());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderView.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderView.cpp
index ae8aa9c90f3..05955691af5 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderView.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderView.cpp
@@ -21,28 +21,31 @@
#include "config.h"
#include "core/rendering/RenderView.h"
+#include "RuntimeEnabledFeatures.h"
#include "core/dom/Document.h"
#include "core/dom/Element.h"
+#include "core/html/HTMLDialogElement.h"
#include "core/html/HTMLFrameOwnerElement.h"
#include "core/html/HTMLIFrameElement.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameView.h"
+#include "core/frame/Frame.h"
#include "core/page/Page.h"
-#include "core/platform/graphics/filters/custom/CustomFilterGlobalContext.h"
-#include "core/platform/graphics/FloatQuad.h"
-#include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/graphics/transforms/TransformState.h"
#include "core/rendering/ColumnInfo.h"
+#include "core/rendering/CompositedLayerMapping.h"
#include "core/rendering/FlowThreadController.h"
+#include "core/rendering/GraphicsContextAnnotator.h"
#include "core/rendering/HitTestResult.h"
+#include "core/rendering/LayoutRectRecorder.h"
#include "core/rendering/RenderFlowThread.h"
#include "core/rendering/RenderGeometryMap.h"
#include "core/rendering/RenderLayer.h"
-#include "core/rendering/RenderLayerBacking.h"
#include "core/rendering/RenderLayerCompositor.h"
#include "core/rendering/RenderSelectionInfo.h"
#include "core/rendering/RenderWidget.h"
-#include "core/svg/SVGElement.h"
+#include "core/svg/SVGDocumentExtensions.h"
+#include "platform/geometry/FloatQuad.h"
+#include "platform/geometry/TransformState.h"
+#include "platform/graphics/GraphicsContext.h"
+#include "platform/graphics/filters/custom/CustomFilterGlobalContext.h"
namespace WebCore {
@@ -116,13 +119,59 @@ bool RenderView::isChildAllowed(RenderObject* child, RenderStyle*) const
return child->isBox();
}
+static bool dialogNeedsCentering(const RenderStyle* style)
+{
+ return style->position() == AbsolutePosition && style->hasAutoTopAndBottom();
+}
+
+void RenderView::positionDialog(RenderBox* box)
+{
+ HTMLDialogElement* dialog = toHTMLDialogElement(box->node());
+ if (dialog->centeringMode() == HTMLDialogElement::NotCentered)
+ return;
+ if (dialog->centeringMode() == HTMLDialogElement::Centered) {
+ if (dialogNeedsCentering(box->style()))
+ box->setY(dialog->centeredPosition());
+ return;
+ }
+
+ if (!dialogNeedsCentering(box->style())) {
+ dialog->setNotCentered();
+ return;
+ }
+ FrameView* frameView = document().view();
+ int scrollTop = frameView->scrollOffset().height();
+ int visibleHeight = frameView->visibleContentRect(ScrollableArea::IncludeScrollbars).height();
+ LayoutUnit top = scrollTop;
+ if (box->height() < visibleHeight)
+ top += (visibleHeight - box->height()) / 2;
+ box->setY(top);
+ dialog->setCentered(top);
+}
+
+void RenderView::positionDialogs()
+{
+ TrackedRendererListHashSet* positionedDescendants = positionedObjects();
+ if (!positionedDescendants)
+ return;
+ TrackedRendererListHashSet::iterator end = positionedDescendants->end();
+ for (TrackedRendererListHashSet::iterator it = positionedDescendants->begin(); it != end; ++it) {
+ RenderBox* box = *it;
+ if (box->node() && box->node()->hasTagName(HTMLNames::dialogTag))
+ positionDialog(box);
+ }
+}
+
void RenderView::layoutContent(const LayoutState& state)
{
- UNUSED_PARAM(state);
ASSERT(needsLayout());
+ LayoutRectRecorder recorder(*this);
RenderBlock::layout();
+ if (RuntimeEnabledFeatures::dialogElementEnabled())
+ positionDialogs();
+
if (m_frameView->partialLayout().isStopping())
return;
@@ -252,7 +301,7 @@ void RenderView::layoutContentInAutoLogicalHeightRegions(const LayoutState& stat
void RenderView::layout()
{
- if (!configuration().paginated())
+ if (!document().paginated())
setPageLogicalHeight(0);
if (shouldUsePrintingLayout())
@@ -265,22 +314,21 @@ void RenderView::layout()
if (relayoutChildren) {
layoutScope.setChildNeedsLayout(this);
for (RenderObject* child = firstChild(); child; child = child->nextSibling()) {
+ if (child->isSVGRoot())
+ continue;
+
if ((child->isBox() && toRenderBox(child)->hasRelativeLogicalHeight())
|| child->style()->logicalHeight().isPercent()
|| child->style()->logicalMinHeight().isPercent()
|| child->style()->logicalMaxHeight().isPercent()
|| child->style()->logicalHeight().isViewportPercentage()
|| child->style()->logicalMinHeight().isViewportPercentage()
- || child->style()->logicalMaxHeight().isViewportPercentage()
- || child->isSVGRoot())
+ || child->style()->logicalMaxHeight().isViewportPercentage())
layoutScope.setChildNeedsLayout(child);
-
- if (child->isSVGRoot()) {
- ASSERT(child->node());
- ASSERT(child->node()->isSVGElement());
- toSVGElement(child->node())->invalidateRelativeLengthClients(&layoutScope);
- }
}
+
+ if (document().svgExtensions())
+ document().accessSVGExtensions()->invalidateSVGRootsWithRelativeLengthDescendents(&layoutScope);
}
ASSERT(!m_layoutState);
@@ -315,7 +363,7 @@ void RenderView::layout()
void RenderView::mapLocalToContainer(const RenderLayerModelObject* repaintContainer, TransformState& transformState, MapCoordinatesFlags mode, bool* wasFixed) const
{
- ASSERT_UNUSED(wasFixed, !wasFixed || *wasFixed == (mode & IsFixed));
+ ASSERT_UNUSED(wasFixed, !wasFixed || *wasFixed == static_cast<bool>(mode & IsFixed));
if (!repaintContainer && mode & UseTransforms && shouldUseTransformFromContainer(0)) {
TransformationMatrix t;
@@ -438,11 +486,6 @@ void RenderView::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
paintObject(paintInfo, paintOffset);
}
-static inline bool isComposited(RenderObject* object)
-{
- return object->hasLayer() && toRenderLayerModelObject(object)->layer()->isComposited();
-}
-
static inline bool rendererObscuresBackground(RenderObject* rootObject)
{
if (!rootObject)
@@ -454,7 +497,7 @@ static inline bool rendererObscuresBackground(RenderObject* rootObject)
|| style->hasTransform())
return false;
- if (isComposited(rootObject))
+ if (rootObject->compositingState() == PaintsIntoOwnBacking)
return false;
const RenderObject* rootRenderer = rootObject->rendererForRootBackground();
@@ -479,7 +522,7 @@ void RenderView::paintBoxDecorations(PaintInfo& paintInfo, const LayoutPoint&)
break;
}
- if (RenderLayer* compositingLayer = layer->enclosingCompositingLayerForRepaint()) {
+ if (layer->enclosingCompositingLayerForRepaint()) {
frameView()->setCannotBlitToWindow();
break;
}
@@ -527,18 +570,11 @@ void RenderView::paintBoxDecorations(PaintInfo& paintInfo, const LayoutPoint&)
}
}
-bool RenderView::shouldRepaint(const LayoutRect& r) const
+bool RenderView::shouldRepaint(const LayoutRect& rect) const
{
- if (document().printing() || r.width() == 0 || r.height() == 0)
- return false;
-
- if (!m_frameView)
- return false;
-
- if (m_frameView->repaintsDisabled())
+ if (document().printing())
return false;
-
- return true;
+ return m_frameView && !rect.isEmpty();
}
void RenderView::repaintViewRectangle(const LayoutRect& ur) const
@@ -635,8 +671,6 @@ static RenderObject* rendererAfterPosition(RenderObject* object, unsigned offset
IntRect RenderView::selectionBounds(bool clipToVisibleContent) const
{
- document().updateStyleIfNeeded();
-
typedef HashMap<RenderObject*, OwnPtr<RenderSelectionInfo> > SelectionMap;
SelectionMap selectedObjects;
@@ -677,8 +711,6 @@ IntRect RenderView::selectionBounds(bool clipToVisibleContent) const
void RenderView::repaintSelection() const
{
- document().updateStyleIfNeeded();
-
HashSet<RenderBlock*> processedBlocks;
RenderObject* end = rendererAfterPosition(m_selectionEnd, m_selectionEndPos);
@@ -712,8 +744,34 @@ void RenderView::setMaximalOutlineSize(int o)
}
}
+// When exploring the RenderTree looking for the nodes involved in the Selection, sometimes it's
+// required to change the traversing direction because the "start" position is below the "end" one.
+static inline RenderObject* getNextOrPrevRenderObjectBasedOnDirection(const RenderObject* o, const RenderObject* stop, bool& continueExploring, bool& exploringBackwards)
+{
+ RenderObject* next;
+ if (exploringBackwards) {
+ next = o->previousInPreOrder();
+ continueExploring = next && !(next)->isRenderView();
+ } else {
+ next = o->nextInPreOrder();
+ continueExploring = next && next != stop;
+ exploringBackwards = !next && (next != stop);
+ if (exploringBackwards) {
+ next = stop->previousInPreOrder();
+ continueExploring = next && !next->isRenderView();
+ }
+ }
+
+ return next;
+}
+
void RenderView::setSelection(RenderObject* start, int startPos, RenderObject* end, int endPos, SelectionRepaintMode blockRepaintMode)
{
+ // This code makes no assumptions as to if the rendering tree is up to date or not
+ // and will not try to update it. Currently clearSelection calls this
+ // (intentionally) without updating the rendering tree as it doesn't care.
+ // Other callers may want to force recalc style before calling this.
+
// Make sure both our start and end objects are defined.
// Check www.msnbc.com and try clicking around to find the case where this happened.
if ((start && !end) || (end && !start))
@@ -724,9 +782,6 @@ void RenderView::setSelection(RenderObject* start, int startPos, RenderObject* e
m_selectionEnd == end && m_selectionEndPos == endPos)
return;
- if ((start && end) && (start->flowThreadContainingBlock() != end->flowThreadContainingBlock()))
- return;
-
// Record the old selected objects. These will be used later
// when we compare against the new selected objects.
int oldStartPos = m_selectionStartPos;
@@ -746,7 +801,9 @@ void RenderView::setSelection(RenderObject* start, int startPos, RenderObject* e
RenderObject* os = m_selectionStart;
RenderObject* stop = rendererAfterPosition(m_selectionEnd, m_selectionEndPos);
- while (os && os != stop) {
+ bool exploringBackwards = false;
+ bool continueExploring = os && (os != stop);
+ while (continueExploring) {
if ((os->canBeSelectionLeaf() || os == m_selectionStart || os == m_selectionEnd) && os->selectionState() != SelectionNone) {
// Blocks are responsible for painting line gaps and margin gaps. They must be examined as well.
oldSelectedObjects.set(os, adoptPtr(new RenderSelectionInfo(os, true)));
@@ -762,7 +819,7 @@ void RenderView::setSelection(RenderObject* start, int startPos, RenderObject* e
}
}
- os = os->nextInPreOrder();
+ os = getNextOrPrevRenderObjectBasedOnDirection(os, stop, continueExploring, exploringBackwards);
}
// Now clear the selection.
@@ -801,7 +858,9 @@ void RenderView::setSelection(RenderObject* start, int startPos, RenderObject* e
// Now that the selection state has been updated for the new objects, walk them again and
// put them in the new objects list.
o = start;
- while (o && o != stop) {
+ exploringBackwards = false;
+ continueExploring = o && (o != stop);
+ while (continueExploring) {
if ((o->canBeSelectionLeaf() || o == start || o == end) && o->selectionState() != SelectionNone) {
newSelectedObjects.set(o, adoptPtr(new RenderSelectionInfo(o, true)));
RenderBlock* cb = o->containingBlock();
@@ -814,13 +873,13 @@ void RenderView::setSelection(RenderObject* start, int startPos, RenderObject* e
}
}
- o = o->nextInPreOrder();
+ o = getNextOrPrevRenderObjectBasedOnDirection(o, stop, continueExploring, exploringBackwards);
}
if (!m_frameView || blockRepaintMode == RepaintNothing)
return;
- m_frameView->beginDeferredRepaints();
+ FrameView::DeferredRepaintScope deferRepaints(*m_frameView);
// Have any of the old selected objects changed compared to the new selection?
for (SelectedObjectMap::iterator i = oldSelectedObjects.begin(); i != oldObjectsEnd; ++i) {
@@ -862,8 +921,6 @@ void RenderView::setSelection(RenderObject* start, int startPos, RenderObject* e
SelectedBlockMap::iterator newBlocksEnd = newSelectedBlocks.end();
for (SelectedBlockMap::iterator i = newSelectedBlocks.begin(); i != newBlocksEnd; ++i)
i->value->repaint();
-
- m_frameView->endDeferredRepaints();
}
void RenderView::getSelection(RenderObject*& startRenderer, int& startOffset, RenderObject*& endRenderer, int& endOffset) const
@@ -886,11 +943,6 @@ void RenderView::selectionStartEnd(int& startPos, int& endPos) const
endPos = m_selectionEndPos;
}
-void RenderView::updateConfiguration()
-{
- m_configuration.update(document());
-}
-
bool RenderView::shouldUsePrintingLayout() const
{
if (!document().printing() || !m_frameView)
@@ -997,27 +1049,25 @@ IntRect RenderView::documentRect() const
return IntRect(overflowRect);
}
-int RenderView::viewHeight(ScrollableArea::VisibleContentRectIncludesScrollbars scrollbarInclusion) const
+int RenderView::viewHeight(ScrollableArea::IncludeScrollbarsInRect scrollbarInclusion) const
{
int height = 0;
- if (!shouldUsePrintingLayout() && m_frameView) {
- height = m_frameView->layoutHeight(scrollbarInclusion);
- height = m_frameView->useFixedLayout() ? ceilf(style()->effectiveZoom() * float(height)) : height;
- }
+ if (!shouldUsePrintingLayout() && m_frameView)
+ height = m_frameView->layoutSize(scrollbarInclusion).height();
+
return height;
}
-int RenderView::viewWidth(ScrollableArea::VisibleContentRectIncludesScrollbars scrollbarInclusion) const
+int RenderView::viewWidth(ScrollableArea::IncludeScrollbarsInRect scrollbarInclusion) const
{
int width = 0;
- if (!shouldUsePrintingLayout() && m_frameView) {
- width = m_frameView->layoutWidth(scrollbarInclusion);
- width = m_frameView->useFixedLayout() ? ceilf(style()->effectiveZoom() * float(width)) : width;
- }
+ if (!shouldUsePrintingLayout() && m_frameView)
+ width = m_frameView->layoutSize(scrollbarInclusion).width();
+
return width;
}
-int RenderView::viewLogicalHeight(ScrollableArea::VisibleContentRectIncludesScrollbars scrollbarInclusion) const
+int RenderView::viewLogicalHeight(ScrollableArea::IncludeScrollbarsInRect scrollbarInclusion) const
{
int height = style()->isHorizontalWritingMode() ? viewHeight(scrollbarInclusion) : viewWidth(scrollbarInclusion);
@@ -1157,9 +1207,7 @@ IntervalArena* RenderView::intervalArena()
bool RenderView::backgroundIsKnownToBeOpaqueInRect(const LayoutRect&) const
{
// FIXME: Remove this main frame check. Same concept applies to subframes too.
- Page* page = document().page();
- Frame* mainFrame = page ? page->mainFrame() : 0;
- if (!m_frameView || &m_frameView->frame() != mainFrame)
+ if (!m_frameView || !m_frameView->isMainFrame())
return false;
return m_frameView->hasOpaqueBackground();
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderView.h b/chromium/third_party/WebKit/Source/core/rendering/RenderView.h
index 5ac228eded5..246db98be54 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderView.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderView.h
@@ -22,13 +22,12 @@
#ifndef RenderView_h
#define RenderView_h
-#include "core/page/FrameView.h"
-#include "core/platform/PODFreeListArena.h"
-#include "core/platform/ScrollableArea.h"
+#include "core/frame/FrameView.h"
#include "core/rendering/LayoutIndicator.h"
#include "core/rendering/LayoutState.h"
#include "core/rendering/RenderBlockFlow.h"
-#include "core/rendering/RenderingConfiguration.h"
+#include "platform/PODFreeListArena.h"
+#include "platform/scroll/ScrollableArea.h"
#include "wtf/OwnPtr.h"
namespace WebCore {
@@ -68,13 +67,13 @@ public:
virtual LayoutUnit availableLogicalHeight(AvailableLogicalHeightType) const OVERRIDE;
// The same as the FrameView's layoutHeight/layoutWidth but with null check guards.
- int viewHeight(ScrollableArea::VisibleContentRectIncludesScrollbars scrollbarInclusion = ScrollableArea::ExcludeScrollbars) const;
- int viewWidth(ScrollableArea::VisibleContentRectIncludesScrollbars scrollbarInclusion = ScrollableArea::ExcludeScrollbars) const;
- int viewLogicalWidth(ScrollableArea::VisibleContentRectIncludesScrollbars scrollbarInclusion = ScrollableArea::ExcludeScrollbars) const
+ int viewHeight(ScrollableArea::IncludeScrollbarsInRect scrollbarInclusion = ScrollableArea::ExcludeScrollbars) const;
+ int viewWidth(ScrollableArea::IncludeScrollbarsInRect scrollbarInclusion = ScrollableArea::ExcludeScrollbars) const;
+ int viewLogicalWidth(ScrollableArea::IncludeScrollbarsInRect scrollbarInclusion = ScrollableArea::ExcludeScrollbars) const
{
return style()->isHorizontalWritingMode() ? viewWidth(scrollbarInclusion) : viewHeight(scrollbarInclusion);
}
- int viewLogicalHeight(ScrollableArea::VisibleContentRectIncludesScrollbars scrollbarInclusion = ScrollableArea::ExcludeScrollbars) const;
+ int viewLogicalHeight(ScrollableArea::IncludeScrollbarsInRect scrollbarInclusion = ScrollableArea::ExcludeScrollbars) const;
float zoomFactor() const;
@@ -100,20 +99,15 @@ public:
void selectionStartEnd(int& startPos, int& endPos) const;
void repaintSelection() const;
- void updateConfiguration();
- const RenderingConfiguration& configuration()
- {
- // If we're not inLayout(), then the configuration might be out of date.
- ASSERT(LayoutIndicator::inLayout());
- return m_configuration;
- }
-
virtual void absoluteRects(Vector<IntRect>&, const LayoutPoint& accumulatedOffset) const;
virtual void absoluteQuads(Vector<FloatQuad>&, bool* wasFixed) const;
void setMaximalOutlineSize(int o);
int maximalOutlineSize() const { return m_maximalOutlineSize; }
+ void setOldMaximalOutlineSize(int o) { m_oldMaximalOutlineSize = o; }
+ int oldMaximalOutlineSize() const { return m_oldMaximalOutlineSize; }
+
virtual LayoutRect viewRect() const OVERRIDE;
void updateWidgetPositions();
@@ -235,7 +229,7 @@ private:
if (!doingFullRepaint() || m_layoutState->isPaginated() || renderer->hasColumns() || renderer->flowThreadContainingBlock()
|| m_layoutState->lineGrid() || (renderer->style()->lineGrid() != RenderStyle::initialLineGrid() && renderer->isRenderBlockFlow())
|| (renderer->isRenderBlock() && toRenderBlock(renderer)->shapeInsideInfo())
- || (m_layoutState->shapeInsideInfo() && renderer->isRenderBlock() && !toRenderBlock(renderer)->allowsShapeInsideInfoSharing())
+ || (m_layoutState->shapeInsideInfo() && renderer->isRenderBlock() && !toRenderBlock(renderer)->allowsShapeInsideInfoSharing(m_layoutState->shapeInsideInfo()->owner()))
) {
pushLayoutStateForCurrentFlowThread(renderer);
m_layoutState = new LayoutState(m_layoutState, renderer, offset, pageHeight, pageHeightChanged, colInfo);
@@ -266,6 +260,9 @@ private:
void checkLayoutState(const LayoutState&);
#endif
+ void positionDialog(RenderBox*);
+ void positionDialogs();
+
size_t getRetainedWidgets(Vector<RenderWidget*>&);
void releaseWidgets(Vector<RenderWidget*>&);
@@ -282,13 +279,11 @@ private:
RenderObject* m_selectionStart;
RenderObject* m_selectionEnd;
- // Please use the configuration() accessor instead of accessing this member directly.
- RenderingConfiguration m_configuration;
-
int m_selectionStartPos;
int m_selectionEndPos;
int m_maximalOutlineSize; // Used to apply a fudge factor to dirty-rect checks on blocks/tables.
+ int m_oldMaximalOutlineSize; // The fudge factor from the previous layout.
typedef HashSet<RenderWidget*> RenderWidgetSet;
RenderWidgetSet m_widgets;
@@ -306,25 +301,7 @@ private:
unsigned m_renderCounterCount;
};
-inline RenderView* toRenderView(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isRenderView());
- return static_cast<RenderView*>(object);
-}
-
-inline const RenderView* toRenderView(const RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isRenderView());
- return static_cast<const RenderView*>(object);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toRenderView(const RenderView*);
-
-ALWAYS_INLINE RenderView* Document::renderView() const
-{
- return toRenderView(renderer());
-}
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderView, isRenderView());
// Stack-based class to assist with LayoutState push/pop
class LayoutStateMaintainer {
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderWidget.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderWidget.cpp
index 8a076db39f8..90b089686a8 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderWidget.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderWidget.cpp
@@ -25,59 +25,64 @@
#include "core/rendering/RenderWidget.h"
#include "core/accessibility/AXObjectCache.h"
-#include "core/page/Frame.h"
-#include "core/platform/graphics/GraphicsContext.h"
+#include "core/frame/Frame.h"
+#include "core/rendering/CompositedLayerMapping.h"
+#include "core/rendering/GraphicsContextAnnotator.h"
#include "core/rendering/HitTestResult.h"
+#include "core/rendering/LayoutRectRecorder.h"
#include "core/rendering/RenderLayer.h"
-#include "core/rendering/RenderLayerBacking.h"
#include "core/rendering/RenderView.h"
-
-using namespace std;
+#include "platform/graphics/GraphicsContext.h"
+#include "wtf/HashMap.h"
namespace WebCore {
-static HashMap<const Widget*, RenderWidget*>& widgetRendererMap()
+typedef HashMap<RefPtr<Widget>, FrameView*> WidgetToParentMap;
+static WidgetToParentMap& widgetNewParentMap()
{
- static HashMap<const Widget*, RenderWidget*>* staticWidgetRendererMap = new HashMap<const Widget*, RenderWidget*>;
- return *staticWidgetRendererMap;
+ DEFINE_STATIC_LOCAL(WidgetToParentMap, map, ());
+ return map;
}
-unsigned WidgetHierarchyUpdatesSuspensionScope::s_widgetHierarchyUpdateSuspendCount = 0;
+static unsigned s_updateSuspendCount = 0;
-WidgetHierarchyUpdatesSuspensionScope::WidgetToParentMap& WidgetHierarchyUpdatesSuspensionScope::widgetNewParentMap()
+RenderWidget::UpdateSuspendScope::UpdateSuspendScope()
{
- DEFINE_STATIC_LOCAL(WidgetToParentMap, map, ());
- return map;
+ ++s_updateSuspendCount;
}
-void WidgetHierarchyUpdatesSuspensionScope::moveWidgets()
+RenderWidget::UpdateSuspendScope::~UpdateSuspendScope()
{
- WidgetToParentMap map;
- widgetNewParentMap().swap(map);
- WidgetToParentMap::iterator end = map.end();
- for (WidgetToParentMap::iterator it = map.begin(); it != end; ++it) {
- Widget* child = it->key.get();
- ScrollView* currentParent = child->parent();
- FrameView* newParent = it->value;
- if (newParent != currentParent) {
- if (currentParent)
- currentParent->removeChild(child);
- if (newParent)
- newParent->addChild(child);
+ ASSERT(s_updateSuspendCount > 0);
+ if (s_updateSuspendCount == 1) {
+ WidgetToParentMap map;
+ widgetNewParentMap().swap(map);
+ WidgetToParentMap::iterator end = map.end();
+ for (WidgetToParentMap::iterator it = map.begin(); it != end; ++it) {
+ Widget* child = it->key.get();
+ ScrollView* currentParent = toScrollView(child->parent());
+ FrameView* newParent = it->value;
+ if (newParent != currentParent) {
+ if (currentParent)
+ currentParent->removeChild(child);
+ if (newParent)
+ newParent->addChild(child);
+ }
}
}
+ --s_updateSuspendCount;
}
static void moveWidgetToParentSoon(Widget* child, FrameView* parent)
{
- if (!WidgetHierarchyUpdatesSuspensionScope::isSuspended()) {
+ if (!s_updateSuspendCount) {
if (parent)
parent->addChild(child);
else
- child->removeFromParent();
+ toScrollView(child->parent())->removeChild(child);
return;
}
- WidgetHierarchyUpdatesSuspensionScope::scheduleWidgetToMove(child, parent);
+ widgetNewParentMap().set(child, parent);
}
RenderWidget::RenderWidget(Element* element)
@@ -136,9 +141,9 @@ bool RenderWidget::setWidgetGeometry(const LayoutRect& frame)
IntRect clipRect = roundedIntRect(enclosingLayer()->childrenClipRect());
IntRect newFrame = roundedIntRect(frame);
bool clipChanged = m_clipRect != clipRect;
- bool boundsChanged = m_widget->frameRect() != newFrame;
+ bool frameRectChanged = m_widget->frameRect() != newFrame;
- if (!boundsChanged && !clipChanged)
+ if (!frameRectChanged && !clipChanged)
return false;
m_clipRect = clipRect;
@@ -147,12 +152,13 @@ bool RenderWidget::setWidgetGeometry(const LayoutRect& frame)
RefPtr<Node> protectedNode(node());
m_widget->setFrameRect(newFrame);
- if (clipChanged && !boundsChanged)
+ if (clipChanged && !frameRectChanged)
m_widget->clipRectChanged();
- if (hasLayer() && layer()->isComposited())
- layer()->backing()->updateAfterWidgetResize();
+ if (hasLayer() && layer()->compositingState() == PaintsIntoOwnBacking)
+ layer()->compositedLayerMapping()->updateAfterWidgetResize();
+ bool boundsChanged = m_widget->frameRect().size() != newFrame.size();
return boundsChanged;
}
@@ -175,12 +181,10 @@ void RenderWidget::setWidget(PassRefPtr<Widget> widget)
if (m_widget) {
moveWidgetToParentSoon(m_widget.get(), 0);
- widgetRendererMap().remove(m_widget.get());
clearWidget();
}
m_widget = widget;
if (m_widget) {
- widgetRendererMap().add(m_widget.get(), this);
// If we've already received a layout, apply the calculated space to the
// widget immediately, but we have to have really been fully constructed (with a non-null
// style pointer).
@@ -206,6 +210,7 @@ void RenderWidget::layout()
{
ASSERT(needsLayout());
+ LayoutRectRecorder recorder(*this);
clearNeedsLayout();
}
@@ -302,7 +307,7 @@ void RenderWidget::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
}
if (canResize())
- layer()->paintResizer(paintInfo.context, roundedIntPoint(adjustedPaintOffset), paintInfo.rect);
+ layer()->scrollableArea()->paintResizer(paintInfo.context, roundedIntPoint(adjustedPaintOffset), paintInfo.rect);
}
void RenderWidget::setIsOverlapped(bool isOverlapped)
@@ -342,24 +347,11 @@ void RenderWidget::widgetPositionsUpdated()
m_widget->widgetPositionsUpdated();
}
-IntRect RenderWidget::windowClipRect() const
-{
- if (!m_frameView)
- return IntRect();
-
- return intersection(m_frameView->contentsToWindow(m_clipRect), m_frameView->windowClipRect());
-}
-
void RenderWidget::clearWidget()
{
m_widget = 0;
}
-RenderWidget* RenderWidget::find(const Widget* widget)
-{
- return widgetRendererMap().get(widget);
-}
-
bool RenderWidget::nodeAtPoint(const HitTestRequest& request, HitTestResult& result, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction action)
{
bool hadResult = result.innerNode();
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderWidget.h b/chromium/third_party/WebKit/Source/core/rendering/RenderWidget.h
index cd418c45fdb..2cde8486906 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderWidget.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RenderWidget.h
@@ -22,37 +22,11 @@
#ifndef RenderWidget_h
#define RenderWidget_h
-#include "core/platform/Widget.h"
#include "core/rendering/RenderReplaced.h"
+#include "platform/Widget.h"
namespace WebCore {
-class WidgetHierarchyUpdatesSuspensionScope {
-public:
- WidgetHierarchyUpdatesSuspensionScope()
- {
- s_widgetHierarchyUpdateSuspendCount++;
- }
- ~WidgetHierarchyUpdatesSuspensionScope()
- {
- ASSERT(s_widgetHierarchyUpdateSuspendCount);
- if (s_widgetHierarchyUpdateSuspendCount == 1)
- moveWidgets();
- s_widgetHierarchyUpdateSuspendCount--;
- }
-
- static bool isSuspended() { return s_widgetHierarchyUpdateSuspendCount; }
- static void scheduleWidgetToMove(Widget* widget, FrameView* frame) { widgetNewParentMap().set(widget, frame); }
-
-private:
- typedef HashMap<RefPtr<Widget>, FrameView*> WidgetToParentMap;
- static WidgetToParentMap& widgetNewParentMap();
-
- void moveWidgets();
-
- static unsigned s_widgetHierarchyUpdateSuspendCount;
-};
-
class RenderWidget : public RenderReplaced {
public:
virtual ~RenderWidget();
@@ -60,21 +34,22 @@ public:
Widget* widget() const { return m_widget.get(); }
virtual void setWidget(PassRefPtr<Widget>);
- static RenderWidget* find(const Widget*);
-
void updateWidgetPosition();
void widgetPositionsUpdated();
- IntRect windowClipRect() const;
void setIsOverlapped(bool);
void ref() { ++m_refCount; }
void deref();
-protected:
- RenderWidget(Element*);
+ class UpdateSuspendScope {
+ public:
+ UpdateSuspendScope();
+ ~UpdateSuspendScope();
+ };
- FrameView* frameView() const { return m_frameView; }
+protected:
+ explicit RenderWidget(Element*);
void clearWidget();
@@ -101,20 +76,7 @@ private:
int m_refCount;
};
-inline RenderWidget* toRenderWidget(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isWidget());
- return static_cast<RenderWidget*>(object);
-}
-
-inline const RenderWidget* toRenderWidget(const RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isWidget());
- return static_cast<const RenderWidget*>(object);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toRenderWidget(const RenderWidget*);
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderWidget, isWidget());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderingConfiguration.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderingConfiguration.cpp
deleted file mode 100644
index 77060a310a8..00000000000
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderingConfiguration.cpp
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/rendering/RenderingConfiguration.h"
-
-#include "core/dom/Document.h"
-
-namespace WebCore {
-
-RenderingConfiguration::RenderingConfiguration()
- : m_inQuirksMode(false)
- , m_paginated(false)
- , m_printing(false)
-{
-}
-
-RenderingConfiguration::~RenderingConfiguration()
-{
-}
-
-void RenderingConfiguration::update(Document& document)
-{
- m_inQuirksMode = document.inQuirksMode();
- m_paginated = document.paginated();
- m_printing = document.printing();
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderingConfiguration.h b/chromium/third_party/WebKit/Source/core/rendering/RenderingConfiguration.h
deleted file mode 100644
index dc1af6da0ce..00000000000
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderingConfiguration.h
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef RenderingConfiguration_h
-#define RenderingConfiguration_h
-
-#include "wtf/Noncopyable.h"
-
-namespace WebCore {
-
-class Document;
-
-class RenderingConfiguration {
- WTF_MAKE_NONCOPYABLE(RenderingConfiguration);
-public:
- RenderingConfiguration();
- ~RenderingConfiguration();
-
- void update(Document&);
-
- bool inQuirksMode() const { return m_inQuirksMode; }
- bool paginated() const { return m_paginated; }
- bool printing() const { return m_printing; }
-
-private:
- bool m_inQuirksMode;
- bool m_paginated;
- bool m_printing;
-};
-
-}
-
-#endif // RenderingConfiguration_h
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderingNodeProxy.cpp b/chromium/third_party/WebKit/Source/core/rendering/RenderingNodeProxy.cpp
deleted file mode 100644
index 303972ba1e2..00000000000
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderingNodeProxy.cpp
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/rendering/RenderingNodeProxy.h"
-
-#include "core/dom/Node.h"
-
-namespace WebCore {
-
-RenderingNodeProxy::RenderingNodeProxy(Node* node)
- : m_node(node)
-{
-}
-
-RenderingNodeProxy::~RenderingNodeProxy()
-{
-}
-
-bool RenderingNodeProxy::hasTagName(const QualifiedName& tagName) const
-{
- return m_node->hasTagName(tagName);
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RenderingNodeProxy.h b/chromium/third_party/WebKit/Source/core/rendering/RenderingNodeProxy.h
deleted file mode 100644
index ac5cb6d6ab5..00000000000
--- a/chromium/third_party/WebKit/Source/core/rendering/RenderingNodeProxy.h
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef RenderingNodeProxy_h
-#define RenderingNodeProxy_h
-
-#include "core/rendering/LayoutIndicator.h"
-#include "wtf/Noncopyable.h"
-
-namespace WebCore {
-
-class QualifiedName;
-class Node;
-
-#define STRICT_LAYOUT_THREADING 0
-
-class RenderingNodeProxy {
- WTF_MAKE_NONCOPYABLE(RenderingNodeProxy);
-public:
- explicit RenderingNodeProxy(Node*);
- ~RenderingNodeProxy();
-
- bool hasTagName(const QualifiedName&) const;
-
- Node* unsafeNode() const
- {
-#if STRICT_LAYOUT_THREADING
- ASSERT(!LayoutIndicator::inLayout());
-#endif
- return m_node;
- }
-
- void clear() { m_node = 0; }
- void set(Node* node) { m_node = node; }
-
-private:
- Node* m_node;
-};
-
-#undef STRICT_LAYOUT_THREADING
-
-}
-
-#endif // RenderingNodeProxy_h
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RootInlineBox.cpp b/chromium/third_party/WebKit/Source/core/rendering/RootInlineBox.cpp
index 055748ed6d9..871cf0ff1ad 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RootInlineBox.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/RootInlineBox.cpp
@@ -21,16 +21,16 @@
#include "core/rendering/RootInlineBox.h"
#include "core/dom/Document.h"
-#include "core/platform/text/BidiResolver.h"
#include "core/rendering/EllipsisBox.h"
#include "core/rendering/HitTestResult.h"
#include "core/rendering/InlineTextBox.h"
#include "core/rendering/PaintInfo.h"
-#include "core/rendering/RenderBlock.h"
+#include "core/rendering/RenderBlockFlow.h"
#include "core/rendering/RenderFlowThread.h"
#include "core/rendering/RenderInline.h"
#include "core/rendering/RenderView.h"
#include "core/rendering/VerticalPositionCache.h"
+#include "platform/text/BidiResolver.h"
#include "wtf/unicode/Unicode.h"
using namespace std;
@@ -47,7 +47,7 @@ COMPILE_ASSERT(sizeof(RootInlineBox) == sizeof(SameSizeAsRootInlineBox), RootInl
typedef WTF::HashMap<const RootInlineBox*, EllipsisBox*> EllipsisBoxMap;
static EllipsisBoxMap* gEllipsisBoxMap = 0;
-RootInlineBox::RootInlineBox(RenderBlock* block)
+RootInlineBox::RootInlineBox(RenderBlockFlow* block)
: InlineFlowBox(block)
, m_lineBreakPos(0)
, m_lineBreakObj(0)
@@ -129,7 +129,7 @@ float RootInlineBox::placeEllipsis(const AtomicString& ellipsisStr, bool ltr, f
// Create an ellipsis box.
EllipsisBox* ellipsisBox = new EllipsisBox(renderer(), ellipsisStr, this,
ellipsisWidth - (markupBox ? markupBox->logicalWidth() : 0), logicalHeight(),
- y(), !prevRootBox(), isHorizontal(), markupBox);
+ x(), y(), !prevRootBox(), isHorizontal(), markupBox);
if (!gEllipsisBoxMap)
gEllipsisBoxMap = new EllipsisBoxMap();
@@ -137,8 +137,8 @@ float RootInlineBox::placeEllipsis(const AtomicString& ellipsisStr, bool ltr, f
setHasEllipsisBox(true);
// FIXME: Do we need an RTL version of this?
- if (ltr && (x() + logicalWidth() + ellipsisWidth) <= blockRightEdge) {
- ellipsisBox->setX(x() + logicalWidth());
+ if (ltr && (logicalLeft() + logicalWidth() + ellipsisWidth) <= blockRightEdge) {
+ ellipsisBox->setLogicalLeft(logicalLeft() + logicalWidth());
return logicalWidth() + ellipsisWidth;
}
@@ -148,7 +148,7 @@ float RootInlineBox::placeEllipsis(const AtomicString& ellipsisStr, bool ltr, f
bool foundBox = false;
float truncatedWidth = 0;
float position = placeEllipsisBox(ltr, blockLeftEdge, blockRightEdge, ellipsisWidth, truncatedWidth, foundBox);
- ellipsisBox->setX(position);
+ ellipsisBox->setLogicalLeft(position);
return truncatedWidth;
}
@@ -291,14 +291,12 @@ LayoutUnit RootInlineBox::alignBoxesInBlockDirection(LayoutUnit heightOfBlock, G
return heightOfBlock + maxHeight;
}
-#if ENABLE(CSS3_TEXT)
float RootInlineBox::maxLogicalTop() const
{
float maxLogicalTop = 0;
computeMaxLogicalTop(maxLogicalTop);
return maxLogicalTop;
}
-#endif // CSS3_TEXT
LayoutUnit RootInlineBox::beforeAnnotationsAdjustment() const
{
@@ -340,7 +338,7 @@ LayoutUnit RootInlineBox::lineSnapAdjustment(LayoutUnit delta) const
// Get the current line grid and offset.
LayoutState* layoutState = block()->view()->layoutState();
- RenderBlock* lineGrid = layoutState->lineGrid();
+ RenderBlockFlow* lineGrid = layoutState->lineGrid();
LayoutSize lineGridOffset = layoutState->lineGridOffset();
if (!lineGrid || lineGrid->style()->writingMode() != block()->style()->writingMode())
return 0;
@@ -598,9 +596,9 @@ int RootInlineBox::blockDirectionPointInLine() const
return !block()->style()->isFlippedBlocksWritingMode() ? max(lineTop(), selectionTop()) : min(lineBottom(), selectionBottom());
}
-RenderBlock* RootInlineBox::block() const
+RenderBlockFlow* RootInlineBox::block() const
{
- return toRenderBlock(renderer());
+ return toRenderBlockFlow(renderer());
}
static bool isEditableLeaf(InlineBox* leaf)
@@ -703,17 +701,16 @@ LayoutRect RootInlineBox::paddedLayoutOverflowRect(LayoutUnit endPadding) const
if (!endPadding)
return lineLayoutOverflow;
- // FIXME: Audit whether to use pixel snapped values when not using integers for layout: https://bugs.webkit.org/show_bug.cgi?id=63656
if (isHorizontal()) {
if (isLeftToRightDirection())
- lineLayoutOverflow.shiftMaxXEdgeTo(max<LayoutUnit>(lineLayoutOverflow.maxX(), pixelSnappedLogicalRight() + endPadding));
+ lineLayoutOverflow.shiftMaxXEdgeTo(max<LayoutUnit>(lineLayoutOverflow.maxX(), logicalRight() + endPadding));
else
- lineLayoutOverflow.shiftXEdgeTo(min<LayoutUnit>(lineLayoutOverflow.x(), pixelSnappedLogicalLeft() - endPadding));
+ lineLayoutOverflow.shiftXEdgeTo(min<LayoutUnit>(lineLayoutOverflow.x(), logicalLeft() - endPadding));
} else {
if (isLeftToRightDirection())
- lineLayoutOverflow.shiftMaxYEdgeTo(max<LayoutUnit>(lineLayoutOverflow.maxY(), pixelSnappedLogicalRight() + endPadding));
+ lineLayoutOverflow.shiftMaxYEdgeTo(max<LayoutUnit>(lineLayoutOverflow.maxY(), logicalRight() + endPadding));
else
- lineLayoutOverflow.shiftYEdgeTo(min<LayoutUnit>(lineLayoutOverflow.y(), pixelSnappedLogicalLeft() - endPadding));
+ lineLayoutOverflow.shiftYEdgeTo(min<LayoutUnit>(lineLayoutOverflow.y(), logicalLeft() - endPadding));
}
return lineLayoutOverflow;
diff --git a/chromium/third_party/WebKit/Source/core/rendering/RootInlineBox.h b/chromium/third_party/WebKit/Source/core/rendering/RootInlineBox.h
index f6ddc5fdda9..7dfde5faf5b 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/RootInlineBox.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/RootInlineBox.h
@@ -21,13 +21,14 @@
#ifndef RootInlineBox_h
#define RootInlineBox_h
-#include "core/platform/text/BidiContext.h"
#include "core/rendering/InlineFlowBox.h"
+#include "platform/text/BidiContext.h"
namespace WebCore {
class EllipsisBox;
class HitTestResult;
+class RenderBlockFlow;
class RenderRegion;
struct BidiStatus;
@@ -35,7 +36,7 @@ struct GapRects;
class RootInlineBox : public InlineFlowBox {
public:
- explicit RootInlineBox(RenderBlock*);
+ explicit RootInlineBox(RenderBlockFlow*);
virtual void destroy() OVERRIDE FINAL;
@@ -128,7 +129,7 @@ public:
GapRects lineSelectionGap(RenderBlock* rootBlock, const LayoutPoint& rootBlockPhysicalPosition, const LayoutSize& offsetFromRootBlock, LayoutUnit selTop, LayoutUnit selHeight, const PaintInfo*);
- RenderBlock* block() const;
+ RenderBlockFlow* block() const;
InlineBox* closestLeafChildForPoint(const IntPoint&, bool onlyEditableLeaves);
InlineBox* closestLeafChildForLogicalLeftPosition(int, bool onlyEditableLeaves = false);
@@ -181,10 +182,8 @@ public:
return InlineFlowBox::logicalBottomLayoutOverflow(lineBottom());
}
-#if ENABLE(CSS3_TEXT)
// Used to calculate the underline offset for TextUnderlinePositionUnder.
float maxLogicalTop() const;
-#endif // CSS3_TEXT
Node* getLogicalStartBoxWithNode(InlineBox*&) const;
Node* getLogicalEndBoxWithNode(InlineBox*&) const;
diff --git a/chromium/third_party/WebKit/Source/core/rendering/ScrollBehavior.cpp b/chromium/third_party/WebKit/Source/core/rendering/ScrollBehavior.cpp
index d28c8e00b2e..d331f1dc07b 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/ScrollBehavior.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/ScrollBehavior.cpp
@@ -44,6 +44,8 @@
#include "config.h"
#include "core/rendering/ScrollBehavior.h"
+#include "platform/geometry/LayoutRect.h"
+
namespace WebCore {
const ScrollAlignment ScrollAlignment::alignCenterIfNeeded = { noScroll, alignCenter, alignToClosestEdge };
@@ -52,4 +54,93 @@ const ScrollAlignment ScrollAlignment::alignCenterAlways = { alignCenter, alignC
const ScrollAlignment ScrollAlignment::alignTopAlways = { alignTop, alignTop, alignTop };
const ScrollAlignment ScrollAlignment::alignBottomAlways = { alignBottom, alignBottom, alignBottom };
+#define MIN_INTERSECT_FOR_REVEAL 32
+
+LayoutRect ScrollAlignment::getRectToExpose(const LayoutRect& visibleRect, const LayoutRect& exposeRect, const ScrollAlignment& alignX, const ScrollAlignment& alignY)
+{
+ // Determine the appropriate X behavior.
+ ScrollBehavior scrollX;
+ LayoutRect exposeRectX(exposeRect.x(), visibleRect.y(), exposeRect.width(), visibleRect.height());
+ LayoutUnit intersectWidth = intersection(visibleRect, exposeRectX).width();
+ if (intersectWidth == exposeRect.width() || intersectWidth >= MIN_INTERSECT_FOR_REVEAL) {
+ // If the rectangle is fully visible, use the specified visible behavior.
+ // If the rectangle is partially visible, but over a certain threshold,
+ // then treat it as fully visible to avoid unnecessary horizontal scrolling
+ scrollX = getVisibleBehavior(alignX);
+ } else if (intersectWidth == visibleRect.width()) {
+ // If the rect is bigger than the visible area, don't bother trying to center. Other alignments will work.
+ scrollX = getVisibleBehavior(alignX);
+ if (scrollX == alignCenter)
+ scrollX = noScroll;
+ } else if (intersectWidth > 0) {
+ // If the rectangle is partially visible, but not above the minimum threshold, use the specified partial behavior
+ scrollX = getPartialBehavior(alignX);
+ } else {
+ scrollX = getHiddenBehavior(alignX);
+ }
+
+ if (scrollX == alignToClosestEdge) {
+ // Closest edge is the right in two cases:
+ // (1) exposeRect to the right of and smaller than visibleRect
+ // (2) exposeRect to the left of and larger than visibleRect
+ if ((exposeRect.maxX() > visibleRect.maxX() && exposeRect.width() < visibleRect.width())
+ || (exposeRect.maxX() < visibleRect.maxX() && exposeRect.width() > visibleRect.width())) {
+ scrollX = alignRight;
+ }
+ }
+
+ // Given the X behavior, compute the X coordinate.
+ LayoutUnit x;
+ if (scrollX == noScroll)
+ x = visibleRect.x();
+ else if (scrollX == alignRight)
+ x = exposeRect.maxX() - visibleRect.width();
+ else if (scrollX == alignCenter)
+ x = exposeRect.x() + (exposeRect.width() - visibleRect.width()) / 2;
+ else
+ x = exposeRect.x();
+
+ // Determine the appropriate Y behavior.
+ ScrollBehavior scrollY;
+ LayoutRect exposeRectY(visibleRect.x(), exposeRect.y(), visibleRect.width(), exposeRect.height());
+ LayoutUnit intersectHeight = intersection(visibleRect, exposeRectY).height();
+ if (intersectHeight == exposeRect.height()) {
+ // If the rectangle is fully visible, use the specified visible behavior.
+ scrollY = getVisibleBehavior(alignY);
+ } else if (intersectHeight == visibleRect.height()) {
+ // If the rect is bigger than the visible area, don't bother trying to center. Other alignments will work.
+ scrollY = getVisibleBehavior(alignY);
+ if (scrollY == alignCenter)
+ scrollY = noScroll;
+ } else if (intersectHeight > 0) {
+ // If the rectangle is partially visible, use the specified partial behavior
+ scrollY = getPartialBehavior(alignY);
+ } else {
+ scrollY = getHiddenBehavior(alignY);
+ }
+
+ if (scrollY == alignToClosestEdge) {
+ // Closest edge is the bottom in two cases:
+ // (1) exposeRect below and smaller than visibleRect
+ // (2) exposeRect above and larger than visibleRect
+ if ((exposeRect.maxY() > visibleRect.maxY() && exposeRect.height() < visibleRect.height())
+ || (exposeRect.maxY() < visibleRect.maxY() && exposeRect.height() > visibleRect.height())) {
+ scrollY = alignBottom;
+ }
+ }
+
+ // Given the Y behavior, compute the Y coordinate.
+ LayoutUnit y;
+ if (scrollY == noScroll)
+ y = visibleRect.y();
+ else if (scrollY == alignBottom)
+ y = exposeRect.maxY() - visibleRect.height();
+ else if (scrollY == alignCenter)
+ y = exposeRect.y() + (exposeRect.height() - visibleRect.height()) / 2;
+ else
+ y = exposeRect.y();
+
+ return LayoutRect(LayoutPoint(x, y), visibleRect.size());
+}
+
}; // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/ScrollBehavior.h b/chromium/third_party/WebKit/Source/core/rendering/ScrollBehavior.h
index 5988f62c970..7c683d874a0 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/ScrollBehavior.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/ScrollBehavior.h
@@ -56,11 +56,16 @@ enum ScrollBehavior {
alignToClosestEdge
};
+class LayoutRect;
+
struct ScrollAlignment {
static ScrollBehavior getVisibleBehavior(const ScrollAlignment& s) { return s.m_rectVisible; }
static ScrollBehavior getPartialBehavior(const ScrollAlignment& s) { return s.m_rectPartial; }
static ScrollBehavior getHiddenBehavior(const ScrollAlignment& s) { return s.m_rectHidden; }
+ // FIXME: This function should probably go somewhere else but where?
+ static LayoutRect getRectToExpose(const LayoutRect& visibleRect, const LayoutRect& exposeRect, const ScrollAlignment& alignX, const ScrollAlignment& alignY);
+
static const ScrollAlignment alignCenterIfNeeded;
static const ScrollAlignment alignToEdgeIfNeeded;
static const ScrollAlignment alignCenterAlways;
diff --git a/chromium/third_party/WebKit/Source/core/rendering/SubtreeLayoutScope.cpp b/chromium/third_party/WebKit/Source/core/rendering/SubtreeLayoutScope.cpp
index 0484cba0726..d650513a1c8 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/SubtreeLayoutScope.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/SubtreeLayoutScope.cpp
@@ -31,7 +31,7 @@
#include "config.h"
#include "core/rendering/SubtreeLayoutScope.h"
-#include "core/page/FrameView.h"
+#include "core/frame/FrameView.h"
#include "core/rendering/RenderObject.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/rendering/TableLayout.h b/chromium/third_party/WebKit/Source/core/rendering/TableLayout.h
index 42be53d446e..20885dd95ed 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/TableLayout.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/TableLayout.h
@@ -42,6 +42,7 @@ public:
virtual void computeIntrinsicLogicalWidths(LayoutUnit& minWidth, LayoutUnit& maxWidth) = 0;
virtual void applyPreferredLogicalWidthQuirks(LayoutUnit& minWidth, LayoutUnit& maxWidth) const = 0;
virtual void layout() = 0;
+ virtual void willChangeTableLayout() = 0;
protected:
// FIXME: Once we enable SATURATED_LAYOUT_ARITHMETHIC, this should just be LayoutUnit::nearlyMax().
diff --git a/chromium/third_party/WebKit/Source/core/rendering/TextAutosizer.cpp b/chromium/third_party/WebKit/Source/core/rendering/TextAutosizer.cpp
index 50a5154b265..bc57d66cfab 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/TextAutosizer.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/TextAutosizer.cpp
@@ -24,19 +24,17 @@
#include <algorithm>
#include "core/dom/Document.h"
-#include "core/html/HTMLDivElement.h"
#include "core/html/HTMLElement.h"
-#include "core/html/HTMLMetaElement.h"
#include "core/inspector/InspectorInstrumentation.h"
-#include "core/page/Settings.h"
-#include "core/platform/chromium/TraceEvent.h"
-#include "core/platform/graphics/IntSize.h"
+#include "core/frame/Settings.h"
#include "core/rendering/RenderListItem.h"
#include "core/rendering/RenderObject.h"
#include "core/rendering/RenderText.h"
#include "core/rendering/RenderView.h"
#include "core/rendering/style/RenderStyle.h"
#include "core/rendering/style/StyleInheritedData.h"
+#include "platform/TraceEvent.h"
+#include "platform/geometry/IntSize.h"
#include "wtf/StdLibExtras.h"
#include "wtf/Vector.h"
@@ -70,6 +68,14 @@ struct TextAutosizingClusterInfo {
Vector<TextAutosizingClusterInfo> narrowDescendants;
};
+#ifdef AUTOSIZING_DOM_DEBUG_INFO
+static void writeDebugInfo(RenderObject* renderObject, const AtomicString& output)
+{
+ Node* node = renderObject->node();
+ if (node && node->isElementNode())
+ toElement(node)->setAttribute("data-autosizing", output, ASSERT_NO_EXCEPTION);
+}
+#endif
static const Vector<QualifiedName>& formInputTags()
{
@@ -83,33 +89,6 @@ static const Vector<QualifiedName>& formInputTags()
return formInputTags;
}
-static const String& vBulletinForumCommentId()
-{
- // Websites using vBulletin forum software typically contain <div id="post_message_*"..> blocks.
- DEFINE_STATIC_LOCAL(const String, vBulletinForumCommentId, ("post_message_"));
- return vBulletinForumCommentId;
-}
-
-static bool isVBulletinComment(const RenderBlock* block)
-{
- Node* blockNode = block->node();
- if (blockNode && blockNode->hasTagName(divTag)) {
- const HTMLDivElement* element = toHTMLDivElement(blockNode);
- if (element && element->hasID() && element->idForStyleResolution().startsWith(vBulletinForumCommentId()))
- return true;
- }
- return false;
-}
-
-static bool hasForumCommentAncestor(const RenderBlock* container)
-{
- for (const RenderBlock* block = container; block; block = block->containingBlock()) {
- if (isVBulletinComment(block))
- return true;
- }
- return false;
-}
-
static RenderListItem* getAncestorListItem(const RenderObject* renderer)
{
RenderObject* ancestor = renderer->parent();
@@ -133,11 +112,6 @@ static RenderObject* getAncestorList(const RenderObject* renderer)
TextAutosizer::TextAutosizer(Document* document)
: m_document(document)
- , m_contentType(Unknown)
-{
-}
-
-TextAutosizer::~TextAutosizer()
{
}
@@ -151,44 +125,26 @@ void TextAutosizer::recalculateMultipliers()
}
}
-TextAutosizer::ContentType TextAutosizer::detectContentType()
-{
- RefPtr<NodeList> metaElements = m_document->getElementsByTagNameNS(xhtmlNamespaceURI, metaTag.localName());
- for (unsigned i = 0; i < metaElements->length(); ++i) {
- HTMLMetaElement* metaElement = toHTMLMetaElement(metaElements->item(i));
- if (equalIgnoringCase(metaElement->name(), "generator") && metaElement->content().startsWith("vBulletin", false))
- return VBulletin;
- }
- return Default;
-}
-
bool TextAutosizer::processSubtree(RenderObject* layoutRoot)
{
TRACE_EVENT0("webkit", "TextAutosizer::processSubtree");
- // FIXME: Text Autosizing should only be enabled when m_document->page()->mainFrame()->view()->useFixedLayout()
- // is true, but for now it's useful to ignore this so that it can be tested on desktop.
if (!m_document->settings() || !m_document->settings()->textAutosizingEnabled() || layoutRoot->view()->document().printing() || !m_document->page())
return false;
- if (m_contentType == Unknown && m_document->body())
- m_contentType = detectContentType();
-
Frame* mainFrame = m_document->page()->mainFrame();
TextAutosizingWindowInfo windowInfo;
// Window area, in logical (density-independent) pixels.
windowInfo.windowSize = m_document->settings()->textAutosizingWindowSizeOverride();
- if (windowInfo.windowSize.isEmpty()) {
- bool includeScrollbars = !InspectorInstrumentation::shouldApplyScreenWidthOverride(mainFrame);
- windowInfo.windowSize = mainFrame->view()->unscaledVisibleContentSize(includeScrollbars ? ScrollableArea::IncludeScrollbars : ScrollableArea::ExcludeScrollbars);
- }
+ if (windowInfo.windowSize.isEmpty())
+ windowInfo.windowSize = mainFrame->view()->unscaledVisibleContentSize(ScrollableArea::IncludeScrollbars);
// Largest area of block that can be visible at once (assuming the main
// frame doesn't get scaled to less than overview scale), in CSS pixels.
windowInfo.minLayoutSize = mainFrame->view()->layoutSize();
- for (Frame* frame = m_document->frame(); frame; frame = frame->tree()->parent())
+ for (Frame* frame = m_document->frame(); frame; frame = frame->tree().parent())
windowInfo.minLayoutSize = windowInfo.minLayoutSize.shrunkTo(frame->view()->layoutSize());
// The layoutRoot could be neither a container nor a cluster, so walk up the tree till we find each of these.
@@ -200,8 +156,16 @@ bool TextAutosizer::processSubtree(RenderObject* layoutRoot)
while (cluster && (!isAutosizingContainer(cluster) || !isIndependentDescendant(cluster)))
cluster = cluster->containingBlock();
+ // Skip autosizing for orphaned trees, or if it will have no effect.
+ // Note: this might suppress autosizing of an inner cluster with a different writing mode.
+ // It's not clear what the correct behavior is for mixed writing modes anyway.
+ if (!cluster || clusterMultiplier(cluster->style()->writingMode(), windowInfo,
+ std::numeric_limits<float>::infinity()) == 1.0f)
+ return false;
+
TextAutosizingClusterInfo clusterInfo(cluster);
processCluster(clusterInfo, container, layoutRoot, windowInfo);
+ InspectorInstrumentation::didAutosizeText(layoutRoot);
return true;
}
@@ -213,13 +177,22 @@ float TextAutosizer::clusterMultiplier(WritingMode writingMode, const TextAutosi
float logicalClusterWidth = std::min<float>(textWidth, logicalLayoutWidth);
float multiplier = logicalClusterWidth / logicalWindowWidth;
- multiplier *= m_document->settings()->textAutosizingFontScaleFactor();
+ multiplier *= m_document->settings()->accessibilityFontScaleFactor();
+
+ // If the page has a meta viewport or @viewport, don't apply the device scale adjustment.
+ const ViewportDescription& viewportDescription = m_document->page()->mainFrame()->document()->viewportDescription();
+ if (!viewportDescription.isSpecifiedByAuthor()) {
+ multiplier *= m_document->settings()->deviceScaleAdjustment();
+ }
return std::max(1.0f, multiplier);
}
void TextAutosizer::processClusterInternal(TextAutosizingClusterInfo& clusterInfo, RenderBlock* container, RenderObject* subtreeRoot, const TextAutosizingWindowInfo& windowInfo, float multiplier)
{
processContainer(multiplier, container, clusterInfo, subtreeRoot, windowInfo);
+#ifdef AUTOSIZING_DOM_DEBUG_INFO
+ writeDebugInfo(clusterInfo.root, String::format("cluster:%f", multiplier));
+#endif
Vector<Vector<TextAutosizingClusterInfo> > narrowDescendantsGroups;
getNarrowDescendantsGroupedByWidth(clusterInfo, narrowDescendantsGroups);
@@ -265,6 +238,9 @@ void TextAutosizer::processCompositeCluster(Vector<TextAutosizingClusterInfo>& c
void TextAutosizer::processContainer(float multiplier, RenderBlock* container, TextAutosizingClusterInfo& clusterInfo, RenderObject* subtreeRoot, const TextAutosizingWindowInfo& windowInfo)
{
ASSERT(isAutosizingContainer(container));
+#ifdef AUTOSIZING_DOM_DEBUG_INFO
+ writeDebugInfo(container, "container");
+#endif
float localMultiplier = containerShouldBeAutosized(container) ? multiplier: 1;
@@ -300,9 +276,9 @@ void TextAutosizer::processContainer(float multiplier, RenderBlock* container, T
void TextAutosizer::setMultiplier(RenderObject* renderer, float multiplier)
{
- // FIXME: Investigate if a clone() is needed and whether it does the right thing w.r.t. style sharing.
RefPtr<RenderStyle> newStyle = RenderStyle::clone(renderer->style());
newStyle->setTextAutosizingMultiplier(multiplier);
+ newStyle->setUnique();
renderer->setStyle(newStyle.release());
}
@@ -360,7 +336,10 @@ bool TextAutosizer::isAutosizingContainer(const RenderObject* renderer)
// - Must not be list items, as items in the same list should look consistent (*).
// - Must not be normal list items, as items in the same list should look
// consistent, unless they are floating or position:absolute/fixed.
- if (!renderer->isRenderBlock() || (renderer->isInline() && !renderer->style()->isDisplayReplacedType()))
+ Node* node = renderer->generatingNode();
+ if ((node && !node->hasChildNodes())
+ || !renderer->isRenderBlock()
+ || (renderer->isInline() && !renderer->style()->isDisplayReplacedType()))
return false;
if (renderer->isListItem())
return renderer->isFloating() || renderer->isOutOfFlowPositioned();
@@ -569,22 +548,15 @@ bool TextAutosizer::compositeClusterShouldBeAutosized(Vector<TextAutosizingClust
// few lines of text you'll only need to pan across once or twice.
//
// An exception to the 4 lines of text are the textarea and contenteditable
- // clusters, which are always autosized by default (i.e. treated as if they
+ // clusters, which are always autosized by default (i.e. threated as if they
// contain more than 4 lines of text). This is to ensure that the text does
// not suddenly get autosized when the user enters more than 4 lines of text.
- // Another exception are the forum comments which are autosized by default
- // to guarantee consistency.
float totalTextWidth = 0;
const float minLinesOfText = 4;
float minTextWidth = blockWidth * minLinesOfText;
for (size_t i = 0; i < clusterInfos.size(); ++i) {
if (clusterInfos[i].root->isTextArea() || (clusterInfos[i].root->style() && clusterInfos[i].root->style()->userModify() != READ_ONLY))
return true;
- if (m_contentType == VBulletin) {
- if (hasForumCommentAncestor(clusterInfos[i].blockContainingAllText)
- || clusterContainsForumComment(clusterInfos[i].blockContainingAllText, clusterInfos[i]))
- return true;
- }
measureDescendantTextWidth(clusterInfos[i].blockContainingAllText, clusterInfos[i], minTextWidth, totalTextWidth);
if (totalTextWidth >= minTextWidth)
return true;
@@ -592,25 +564,6 @@ bool TextAutosizer::compositeClusterShouldBeAutosized(Vector<TextAutosizingClust
return false;
}
-bool TextAutosizer::clusterContainsForumComment(const RenderBlock* container, TextAutosizingClusterInfo& clusterInfo)
-{
- ASSERT(m_contentType == VBulletin);
-
- RenderObject* descendant = nextInPreOrderSkippingDescendantsOfContainers(container, container);
- while (descendant) {
- if (isAutosizingContainer(descendant)) {
- RenderBlock* descendantBlock = toRenderBlock(descendant);
- if (isVBulletinComment(descendantBlock))
- return true;
- if (!isAutosizingCluster(descendantBlock, clusterInfo)
- && clusterContainsForumComment(descendantBlock, clusterInfo))
- return true;
- }
- descendant = nextInPreOrderSkippingDescendantsOfContainers(descendant, container);
- }
- return false;
-}
-
void TextAutosizer::measureDescendantTextWidth(const RenderBlock* container, TextAutosizingClusterInfo& clusterInfo, float minTextWidth, float& textWidth)
{
bool skipLocalText = !containerShouldBeAutosized(container);
diff --git a/chromium/third_party/WebKit/Source/core/rendering/TextAutosizer.h b/chromium/third_party/WebKit/Source/core/rendering/TextAutosizer.h
index d8f7f89b5c1..dda763efa7b 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/TextAutosizer.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/TextAutosizer.h
@@ -27,7 +27,7 @@
#define TextAutosizer_h
#include "HTMLNames.h"
-#include "core/platform/text/WritingMode.h"
+#include "platform/text/WritingMode.h"
#include "wtf/Noncopyable.h"
#include "wtf/PassOwnPtr.h"
@@ -40,31 +40,25 @@ class RenderText;
struct TextAutosizingWindowInfo;
struct TextAutosizingClusterInfo;
-class TextAutosizer {
+class TextAutosizer FINAL {
WTF_MAKE_NONCOPYABLE(TextAutosizer);
public:
static PassOwnPtr<TextAutosizer> create(Document* document) { return adoptPtr(new TextAutosizer(document)); }
- virtual ~TextAutosizer();
-
bool processSubtree(RenderObject* layoutRoot);
void recalculateMultipliers();
static float computeAutosizedFontSize(float specifiedSize, float multiplier);
private:
+ friend class FastTextAutosizer;
+
enum TraversalDirection {
FirstToLast,
LastToFirst
};
- enum ContentType {
- Unknown,
- Default,
- VBulletin
- };
-
explicit TextAutosizer(Document*);
float clusterMultiplier(WritingMode, const TextAutosizingWindowInfo&, float textWidth) const;
@@ -74,15 +68,9 @@ private:
void processCompositeCluster(Vector<TextAutosizingClusterInfo>&, const TextAutosizingWindowInfo&);
void processContainer(float multiplier, RenderBlock* container, TextAutosizingClusterInfo&, RenderObject* subtreeRoot, const TextAutosizingWindowInfo&);
- bool clusterShouldBeAutosized(TextAutosizingClusterInfo&, float blockWidth);
- bool compositeClusterShouldBeAutosized(Vector<TextAutosizingClusterInfo>&, float blockWidth);
- bool clusterContainsForumComment(const RenderBlock* container, TextAutosizingClusterInfo&);
-
void setMultiplier(RenderObject*, float);
void setMultiplierForList(RenderObject* renderer, float multiplier);
- ContentType detectContentType();
-
static bool isAutosizingContainer(const RenderObject*);
static bool isNarrowDescendant(const RenderBlock*, TextAutosizingClusterInfo& parentClusterInfo);
static bool isWiderDescendant(const RenderBlock*, const TextAutosizingClusterInfo& parentClusterInfo);
@@ -93,6 +81,8 @@ private:
static bool containerContainsOneOfTags(const RenderBlock* cluster, const Vector<QualifiedName>& tags);
static bool containerIsRowOfLinks(const RenderObject* container);
static bool contentHeightIsConstrained(const RenderBlock* container);
+ static bool clusterShouldBeAutosized(TextAutosizingClusterInfo&, float blockWidth);
+ static bool compositeClusterShouldBeAutosized(Vector<TextAutosizingClusterInfo>&, float blockWidth);
static void measureDescendantTextWidth(const RenderBlock* container, TextAutosizingClusterInfo&, float minTextWidth, float& textWidth);
// Use to traverse the tree of descendants, excluding descendants of containers (but returning the containers themselves).
@@ -110,7 +100,6 @@ private:
static void getNarrowDescendantsGroupedByWidth(const TextAutosizingClusterInfo& parentClusterInfo, Vector<Vector<TextAutosizingClusterInfo> >&);
Document* m_document;
- ContentType m_contentType;
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/TrailingFloatsRootInlineBox.h b/chromium/third_party/WebKit/Source/core/rendering/TrailingFloatsRootInlineBox.h
index 9bd0530bb83..8036f5a0432 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/TrailingFloatsRootInlineBox.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/TrailingFloatsRootInlineBox.h
@@ -32,7 +32,7 @@ namespace WebCore {
class TrailingFloatsRootInlineBox FINAL : public RootInlineBox {
public:
- TrailingFloatsRootInlineBox(RenderBlock* block)
+ TrailingFloatsRootInlineBox(RenderBlockFlow* block)
: RootInlineBox(block)
{
setHasVirtualLogicalHeight();
diff --git a/chromium/third_party/WebKit/Source/core/rendering/VerticalPositionCache.h b/chromium/third_party/WebKit/Source/core/rendering/VerticalPositionCache.h
index 9b65ed933d6..4ae17b491dc 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/VerticalPositionCache.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/VerticalPositionCache.h
@@ -26,7 +26,7 @@
#ifndef VerticalPositionCache_h
#define VerticalPositionCache_h
-#include "core/platform/graphics/FontBaseline.h"
+#include "platform/fonts/FontBaseline.h"
#include "wtf/HashMap.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/rendering/animation/WebAnimationProvider.cpp b/chromium/third_party/WebKit/Source/core/rendering/animation/WebAnimationProvider.cpp
new file mode 100644
index 00000000000..473e3ff8073
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/rendering/animation/WebAnimationProvider.cpp
@@ -0,0 +1,214 @@
+/*
+ * Copyright (C) 2013 Intel Corporation. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+
+#include "core/rendering/animation/WebAnimationProvider.h"
+
+#include "core/platform/animation/AnimationTranslationUtil.h"
+#include "core/platform/animation/CSSAnimationData.h"
+#include "core/rendering/style/KeyframeList.h"
+#include "core/rendering/style/RenderStyle.h"
+#include "public/platform/WebAnimation.h"
+#include "wtf/text/StringBuilder.h"
+
+using blink::WebAnimation;
+
+namespace WebCore {
+
+namespace {
+
+String animationNameForTransition(AnimatedPropertyID property)
+{
+ // | is not a valid identifier character in CSS, so this can never conflict with a keyframe identifier.
+ StringBuilder id;
+ id.appendLiteral("-|transition");
+ id.appendNumber(static_cast<int>(property));
+ id.append('-');
+ return id.toString();
+}
+
+AnimatedPropertyID cssToGraphicsLayerProperty(CSSPropertyID cssProperty)
+{
+ switch (cssProperty) {
+ case CSSPropertyWebkitTransform:
+ return AnimatedPropertyWebkitTransform;
+ case CSSPropertyOpacity:
+ return AnimatedPropertyOpacity;
+ case CSSPropertyBackgroundColor:
+ ASSERT_NOT_REACHED();
+ return AnimatedPropertyInvalid; // Chromium compositor cannot accelerate background color yet.
+ case CSSPropertyWebkitFilter:
+ return AnimatedPropertyWebkitFilter;
+ default:
+ // It's fine if we see other css properties here; they are just not accelerated.
+ break;
+ }
+ return AnimatedPropertyInvalid;
+}
+
+} // namespace
+
+WebAnimations::WebAnimations()
+{
+}
+
+WebAnimations::~WebAnimations()
+{
+}
+
+// Copy constructor is needed to use this struct as a return value. It actually moves the ownership, not copy.
+WebAnimations::WebAnimations(const WebAnimations& other)
+{
+ ASSERT(isEmpty());
+ m_transformAnimation.swap(const_cast<OwnPtr<WebAnimation>& >(other.m_transformAnimation));
+ m_opacityAnimation.swap(const_cast<OwnPtr<WebAnimation>& >(other.m_opacityAnimation));
+ m_filterAnimation.swap(const_cast<OwnPtr<WebAnimation>& >(other.m_filterAnimation));
+ ASSERT(other.isEmpty());
+}
+
+bool WebAnimations::isEmpty() const
+{
+ return !m_transformAnimation && !m_opacityAnimation && !m_filterAnimation;
+}
+
+WebAnimationProvider::WebAnimationProvider()
+{
+}
+
+WebAnimationProvider::~WebAnimationProvider()
+{
+}
+
+int WebAnimationProvider::getWebAnimationId(const String& animationName) const
+{
+ if (!m_animationIdMap.contains(animationName))
+ return 0;
+ return m_animationIdMap.get(animationName);
+}
+
+int WebAnimationProvider::getWebAnimationId(CSSPropertyID property) const
+{
+ AnimatedPropertyID animatedProperty = cssToGraphicsLayerProperty(property);
+ ASSERT(animatedProperty != AnimatedPropertyInvalid);
+ return getWebAnimationId(animationNameForTransition(animatedProperty));
+}
+
+WebAnimations WebAnimationProvider::startAnimation(double timeOffset, const CSSAnimationData* anim, const KeyframeList& keyframes, bool hasTransform, const IntSize& boxSize)
+{
+ ASSERT(hasTransform || boxSize.isEmpty());
+ bool hasOpacity = keyframes.containsProperty(CSSPropertyOpacity);
+ bool hasFilter = keyframes.containsProperty(CSSPropertyWebkitFilter);
+
+ if (!hasOpacity && !hasTransform && !hasFilter)
+ return WebAnimations();
+
+ KeyframeValueList transformVector(AnimatedPropertyWebkitTransform);
+ KeyframeValueList opacityVector(AnimatedPropertyOpacity);
+ KeyframeValueList filterVector(AnimatedPropertyWebkitFilter);
+
+ size_t numKeyframes = keyframes.size();
+ for (size_t i = 0; i < numKeyframes; ++i) {
+ const KeyframeValue& currentKeyframe = keyframes[i];
+ const RenderStyle* keyframeStyle = currentKeyframe.style();
+ double key = currentKeyframe.key();
+
+ if (!keyframeStyle)
+ continue;
+
+ // Get timing function.
+ RefPtr<TimingFunction> tf = KeyframeValue::timingFunction(*keyframeStyle);
+
+ bool isFirstOrLastKeyframe = !key || key == 1;
+ if ((hasTransform && isFirstOrLastKeyframe) || currentKeyframe.containsProperty(CSSPropertyWebkitTransform))
+ transformVector.insert(adoptPtr(new TransformAnimationValue(key, &(keyframeStyle->transform()), tf)));
+
+ if ((hasOpacity && isFirstOrLastKeyframe) || currentKeyframe.containsProperty(CSSPropertyOpacity))
+ opacityVector.insert(adoptPtr(new FloatAnimationValue(key, keyframeStyle->opacity(), tf)));
+
+ if ((hasFilter && isFirstOrLastKeyframe) || currentKeyframe.containsProperty(CSSPropertyWebkitFilter))
+ filterVector.insert(adoptPtr(new FilterAnimationValue(key, &(keyframeStyle->filter()), tf)));
+ }
+ WebAnimations resultAnimations;
+ if (hasTransform)
+ resultAnimations.m_transformAnimation = createWebAnimationAndStoreId(transformVector, boxSize, anim, keyframes.animationName(), timeOffset);
+ if (hasOpacity)
+ resultAnimations.m_opacityAnimation = createWebAnimationAndStoreId(opacityVector, IntSize(), anim, keyframes.animationName(), timeOffset);
+ if (hasFilter)
+ resultAnimations.m_filterAnimation = createWebAnimationAndStoreId(filterVector, IntSize(), anim, keyframes.animationName(), timeOffset);
+
+ return resultAnimations;
+}
+
+WebAnimations WebAnimationProvider::startTransition(double timeOffset, CSSPropertyID property, const RenderStyle* fromStyle, const RenderStyle* toStyle, bool hasTransform, bool hasFilter, const IntSize& boxSize, float fromOpacity, float toOpacity)
+{
+ ASSERT(property != CSSPropertyInvalid);
+ ASSERT(property == CSSPropertyOpacity || (!fromOpacity && !toOpacity));
+
+ WebAnimations resultAnimations;
+ if (property == CSSPropertyOpacity) {
+ const CSSAnimationData* opacityAnim = toStyle->transitionForProperty(CSSPropertyOpacity);
+ if (opacityAnim && !opacityAnim->isEmptyOrZeroDuration()) {
+ KeyframeValueList opacityVector(AnimatedPropertyOpacity);
+ opacityVector.insert(adoptPtr(new FloatAnimationValue(0, fromOpacity)));
+ opacityVector.insert(adoptPtr(new FloatAnimationValue(1, toOpacity)));
+ resultAnimations.m_opacityAnimation = createWebAnimationAndStoreId(opacityVector, IntSize(), opacityAnim, animationNameForTransition(AnimatedPropertyOpacity), timeOffset);
+ }
+ }
+ if (property == CSSPropertyWebkitTransform && hasTransform) {
+ const CSSAnimationData* transformAnim = toStyle->transitionForProperty(CSSPropertyWebkitTransform);
+ if (transformAnim && !transformAnim->isEmptyOrZeroDuration()) {
+ KeyframeValueList transformVector(AnimatedPropertyWebkitTransform);
+ transformVector.insert(adoptPtr(new TransformAnimationValue(0, &fromStyle->transform())));
+ transformVector.insert(adoptPtr(new TransformAnimationValue(1, &toStyle->transform())));
+ resultAnimations.m_transformAnimation = createWebAnimationAndStoreId(transformVector, boxSize, transformAnim, animationNameForTransition(AnimatedPropertyWebkitTransform), timeOffset);
+ }
+ }
+ if (property == CSSPropertyWebkitFilter && hasFilter) {
+ const CSSAnimationData* filterAnim = toStyle->transitionForProperty(CSSPropertyWebkitFilter);
+ if (filterAnim && !filterAnim->isEmptyOrZeroDuration()) {
+ KeyframeValueList filterVector(AnimatedPropertyWebkitFilter);
+ filterVector.insert(adoptPtr(new FilterAnimationValue(0, &fromStyle->filter())));
+ filterVector.insert(adoptPtr(new FilterAnimationValue(1, &toStyle->filter())));
+ resultAnimations.m_filterAnimation = createWebAnimationAndStoreId(filterVector, IntSize(), filterAnim, animationNameForTransition(AnimatedPropertyWebkitFilter), timeOffset);
+ }
+ }
+
+ return resultAnimations;
+}
+
+PassOwnPtr<WebAnimation> WebAnimationProvider::createWebAnimationAndStoreId(const KeyframeValueList& values, const IntSize& boxSize, const CSSAnimationData* animation, const String& animationName, double timeOffset)
+{
+ int animationId = getWebAnimationId(animationName);
+ OwnPtr<WebAnimation> webAnimation(createWebAnimation(values, animation, animationId, timeOffset, boxSize));
+ if (!webAnimation)
+ return PassOwnPtr<WebAnimation>();
+
+ if (!animationId)
+ m_animationIdMap.set(animationName, webAnimation->id());
+ return webAnimation.release();
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/animation/WebAnimationProvider.h b/chromium/third_party/WebKit/Source/core/rendering/animation/WebAnimationProvider.h
new file mode 100644
index 00000000000..724de2e1696
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/rendering/animation/WebAnimationProvider.h
@@ -0,0 +1,76 @@
+/*
+ * Copyright (C) 2013 Intel Corporation. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef WebAnimationProvider_h
+#define WebAnimationProvider_h
+
+#include "CSSPropertyNames.h"
+#include "core/platform/animation/KeyframeValueList.h"
+#include "wtf/HashMap.h"
+#include "wtf/OwnPtr.h"
+#include "wtf/PassOwnPtr.h"
+#include "wtf/text/WTFString.h"
+
+namespace blink {
+class WebAnimation;
+}
+
+namespace WebCore {
+class CSSAnimationData;
+class IntSize;
+class KeyframeList;
+class RenderStyle;
+
+struct WebAnimations {
+ WebAnimations();
+ ~WebAnimations();
+ WebAnimations(const WebAnimations&);
+ bool isEmpty() const;
+ OwnPtr<blink::WebAnimation> m_transformAnimation;
+ OwnPtr<blink::WebAnimation> m_opacityAnimation;
+ OwnPtr<blink::WebAnimation> m_filterAnimation;
+};
+
+class WebAnimationProvider {
+ WTF_MAKE_NONCOPYABLE(WebAnimationProvider); WTF_MAKE_FAST_ALLOCATED;
+public:
+ WebAnimationProvider();
+ ~WebAnimationProvider();
+
+ int getWebAnimationId(const String& animationName) const;
+ int getWebAnimationId(CSSPropertyID) const;
+ WebAnimations startAnimation(double timeOffset, const CSSAnimationData*, const KeyframeList&, bool hasTransform, const IntSize& boxSize);
+ WebAnimations startTransition(double timeOffset, CSSPropertyID, const RenderStyle* fromStyle, const RenderStyle* toStyle, bool hasTransform, bool hasFilter, const IntSize& boxSize, float fromOpacity, float toOpacity);
+
+private:
+ PassOwnPtr<blink::WebAnimation> createWebAnimationAndStoreId(const KeyframeValueList&, const IntSize& boxSize, const CSSAnimationData*, const String& animationName, double timeOffset);
+
+ typedef HashMap<String, int> AnimationIdMap;
+ AnimationIdMap m_animationIdMap;
+};
+
+} // namespace WebCore
+
+#endif // WebAnimationProvider_h
diff --git a/chromium/third_party/WebKit/Source/core/rendering/break_lines.cpp b/chromium/third_party/WebKit/Source/core/rendering/break_lines.cpp
index d1ab9132e6b..949e1ba4edc 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/break_lines.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/break_lines.cpp
@@ -27,7 +27,7 @@
#include "config.h"
#include "core/rendering/break_lines.h"
-#include "core/platform/text/TextBreakIterator.h"
+#include "platform/text/TextBreakIterator.h"
#include "wtf/ASCIICType.h"
#include "wtf/StdLibExtras.h"
#include "wtf/unicode/CharacterNames.h"
@@ -164,7 +164,7 @@ static inline int nextBreakablePosition(LazyLineBreakIterator& lazyBreakIterator
if (i || priorContextLength) {
TextBreakIterator* breakIterator = lazyBreakIterator.get(priorContextLength);
if (breakIterator) {
- nextBreak = textBreakFollowing(breakIterator, i - 1 + priorContextLength);
+ nextBreak = breakIterator->following(i - 1 + priorContextLength);
if (nextBreak >= 0) {
nextBreak -= priorContextLength;
}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/line/BreakingContextInlineHeaders.h b/chromium/third_party/WebKit/Source/core/rendering/line/BreakingContextInlineHeaders.h
new file mode 100644
index 00000000000..989d7e3cfd0
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/rendering/line/BreakingContextInlineHeaders.h
@@ -0,0 +1,1145 @@
+/*
+ * Copyright (C) 2000 Lars Knoll (knoll@kde.org)
+ * Copyright (C) 2003, 2004, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All right reserved.
+ * Copyright (C) 2010 Google Inc. All rights reserved.
+ * Copyright (C) 2013 Adobe Systems Incorporated.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ */
+
+#ifndef BreakingContextInlineHeaders_h
+#define BreakingContextInlineHeaders_h
+
+#include "core/rendering/InlineIterator.h"
+#include "core/rendering/InlineTextBox.h"
+#include "core/rendering/LineWidth.h"
+#include "core/rendering/RenderCombineText.h"
+#include "core/rendering/RenderInline.h"
+#include "core/rendering/break_lines.h"
+#include "core/rendering/line/LineInfo.h"
+#include "core/rendering/shapes/ShapeInsideInfo.h"
+#include "core/rendering/svg/RenderSVGInlineText.h"
+
+namespace WebCore {
+
+using namespace std;
+using namespace WTF;
+using namespace Unicode;
+
+// We don't let our line box tree for a single line get any deeper than this.
+const unsigned cMaxLineDepth = 200;
+
+struct RenderTextInfo {
+ // Destruction of m_layout requires TextLayout to be a complete type, so the constructor and destructor are made non-inline to avoid compilation errors.
+ RenderTextInfo();
+ ~RenderTextInfo();
+
+ RenderText* m_text;
+ OwnPtr<TextLayout> m_layout;
+ LazyLineBreakIterator m_lineBreakIterator;
+ const Font* m_font;
+
+ void createLayout(RenderText* renderText, float xPos, bool collapseWhiteSpace)
+ {
+#if OS(MACOSX)
+ m_layout = m_font->createLayoutForMacComplexText(RenderBlockFlow::constructTextRun(renderText, *m_font, renderText, renderText->style()), renderText->textLength(), xPos, collapseWhiteSpace);
+#else
+ m_layout = nullptr;
+#endif
+ }
+};
+
+class WordMeasurement {
+public:
+ WordMeasurement()
+ : renderer(0)
+ , width(0)
+ , startOffset(0)
+ , endOffset(0)
+ {
+ }
+
+ RenderText* renderer;
+ float width;
+ int startOffset;
+ int endOffset;
+ HashSet<const SimpleFontData*> fallbackFonts;
+};
+
+// Don't call this directly. Use one of the descriptive helper functions below.
+inline void deprecatedAddMidpoint(LineMidpointState& lineMidpointState, const InlineIterator& midpoint)
+{
+ if (lineMidpointState.midpoints.size() <= lineMidpointState.numMidpoints)
+ lineMidpointState.midpoints.grow(lineMidpointState.numMidpoints + 10);
+
+ InlineIterator* midpoints = lineMidpointState.midpoints.data();
+ midpoints[lineMidpointState.numMidpoints++] = midpoint;
+}
+
+inline void startIgnoringSpaces(LineMidpointState& lineMidpointState, const InlineIterator& midpoint)
+{
+ ASSERT(!(lineMidpointState.numMidpoints % 2));
+ deprecatedAddMidpoint(lineMidpointState, midpoint);
+}
+
+inline void stopIgnoringSpaces(LineMidpointState& lineMidpointState, const InlineIterator& midpoint)
+{
+ ASSERT(lineMidpointState.numMidpoints % 2);
+ deprecatedAddMidpoint(lineMidpointState, midpoint);
+}
+
+// When ignoring spaces, this needs to be called for objects that need line boxes such as RenderInlines or
+// hard line breaks to ensure that they're not ignored.
+inline void ensureLineBoxInsideIgnoredSpaces(LineMidpointState& lineMidpointState, RenderObject* renderer)
+{
+ InlineIterator midpoint(0, renderer, 0);
+ stopIgnoringSpaces(lineMidpointState, midpoint);
+ startIgnoringSpaces(lineMidpointState, midpoint);
+}
+
+// Adding a pair of midpoints before a character will split it out into a new line box.
+inline void ensureCharacterGetsLineBox(LineMidpointState& lineMidpointState, InlineIterator& textParagraphSeparator)
+{
+ InlineIterator midpoint(0, textParagraphSeparator.object(), textParagraphSeparator.m_pos);
+ startIgnoringSpaces(lineMidpointState, InlineIterator(0, textParagraphSeparator.object(), textParagraphSeparator.m_pos - 1));
+ stopIgnoringSpaces(lineMidpointState, InlineIterator(0, textParagraphSeparator.object(), textParagraphSeparator.m_pos));
+}
+
+class TrailingObjects {
+public:
+ TrailingObjects();
+ void setTrailingWhitespace(RenderText*);
+ void clear();
+ void appendBoxIfNeeded(RenderBox*);
+
+ enum CollapseFirstSpaceOrNot { DoNotCollapseFirstSpace, CollapseFirstSpace };
+
+ void updateMidpointsForTrailingBoxes(LineMidpointState&, const InlineIterator& lBreak, CollapseFirstSpaceOrNot);
+
+private:
+ RenderText* m_whitespace;
+ Vector<RenderBox*, 4> m_boxes;
+};
+
+TrailingObjects::TrailingObjects()
+ : m_whitespace(0)
+{
+}
+
+inline void TrailingObjects::setTrailingWhitespace(RenderText* whitespace)
+{
+ ASSERT(whitespace);
+ m_whitespace = whitespace;
+}
+
+inline void TrailingObjects::clear()
+{
+ m_whitespace = 0;
+ // Using resize(0) rather than clear() here saves 2% on
+ // PerformanceTests/Layout/line-layout.html because we avoid freeing and
+ // re-allocating the underlying buffer repeatedly.
+ m_boxes.resize(0);
+}
+
+inline void TrailingObjects::appendBoxIfNeeded(RenderBox* box)
+{
+ if (m_whitespace)
+ m_boxes.append(box);
+}
+
+void TrailingObjects::updateMidpointsForTrailingBoxes(LineMidpointState& lineMidpointState, const InlineIterator& lBreak, CollapseFirstSpaceOrNot collapseFirstSpace)
+{
+ if (!m_whitespace)
+ return;
+
+ // This object is either going to be part of the last midpoint, or it is going to be the actual endpoint.
+ // In both cases we just decrease our pos by 1 level to exclude the space, allowing it to - in effect - collapse into the newline.
+ if (lineMidpointState.numMidpoints % 2) {
+ // Find the trailing space object's midpoint.
+ int trailingSpaceMidpoint = lineMidpointState.numMidpoints - 1;
+ for ( ; trailingSpaceMidpoint > 0 && lineMidpointState.midpoints[trailingSpaceMidpoint].object() != m_whitespace; --trailingSpaceMidpoint) { }
+ ASSERT(trailingSpaceMidpoint >= 0);
+ if (collapseFirstSpace == CollapseFirstSpace)
+ lineMidpointState.midpoints[trailingSpaceMidpoint].m_pos--;
+
+ // Now make sure every single trailingPositionedBox following the trailingSpaceMidpoint properly stops and starts
+ // ignoring spaces.
+ size_t currentMidpoint = trailingSpaceMidpoint + 1;
+ for (size_t i = 0; i < m_boxes.size(); ++i) {
+ if (currentMidpoint >= lineMidpointState.numMidpoints) {
+ // We don't have a midpoint for this box yet.
+ ensureLineBoxInsideIgnoredSpaces(lineMidpointState, m_boxes[i]);
+ } else {
+ ASSERT(lineMidpointState.midpoints[currentMidpoint].object() == m_boxes[i]);
+ ASSERT(lineMidpointState.midpoints[currentMidpoint + 1].object() == m_boxes[i]);
+ }
+ currentMidpoint += 2;
+ }
+ } else if (!lBreak.object()) {
+ ASSERT(m_whitespace->isText());
+ ASSERT(collapseFirstSpace == CollapseFirstSpace);
+ // Add a new end midpoint that stops right at the very end.
+ unsigned length = m_whitespace->textLength();
+ unsigned pos = length >= 2 ? length - 2 : UINT_MAX;
+ InlineIterator endMid(0, m_whitespace, pos);
+ startIgnoringSpaces(lineMidpointState, endMid);
+ for (size_t i = 0; i < m_boxes.size(); ++i) {
+ ensureLineBoxInsideIgnoredSpaces(lineMidpointState, m_boxes[i]);
+ }
+ }
+}
+
+class BreakingContext {
+public:
+ BreakingContext(InlineBidiResolver& resolver, LineInfo& inLineInfo, LineWidth& lineWidth, RenderTextInfo& inRenderTextInfo, FloatingObject* inLastFloatFromPreviousLine, bool appliedStartWidth, RenderBlockFlow* block)
+ : m_resolver(resolver)
+ , m_current(resolver.position())
+ , m_lineBreak(resolver.position())
+ , m_block(block)
+ , m_lastObject(m_current.object())
+ , m_nextObject(0)
+ , m_currentStyle(0)
+ , m_blockStyle(block->style())
+ , m_lineInfo(inLineInfo)
+ , m_renderTextInfo(inRenderTextInfo)
+ , m_lastFloatFromPreviousLine(inLastFloatFromPreviousLine)
+ , m_width(lineWidth)
+ , m_currWS(NORMAL)
+ , m_lastWS(NORMAL)
+ , m_preservesNewline(false)
+ , m_atStart(true)
+ , m_ignoringSpaces(false)
+ , m_currentCharacterIsSpace(false)
+ , m_currentCharacterShouldCollapseIfPreWap(false)
+ , m_appliedStartWidth(appliedStartWidth)
+ , m_includeEndWidth(true)
+ , m_autoWrap(false)
+ , m_autoWrapWasEverTrueOnLine(false)
+ , m_floatsFitOnLine(true)
+ , m_collapseWhiteSpace(false)
+ , m_startingNewParagraph(m_lineInfo.previousLineBrokeCleanly())
+ , m_allowImagesToBreak(!block->document().inQuirksMode() || !block->isTableCell() || !m_blockStyle->logicalWidth().isIntrinsicOrAuto())
+ , m_atEnd(false)
+ , m_lineMidpointState(resolver.midpointState())
+ {
+ m_lineInfo.setPreviousLineBrokeCleanly(false);
+ }
+
+ RenderObject* currentObject() { return m_current.object(); }
+ InlineIterator lineBreak() { return m_lineBreak; }
+ bool atEnd() { return m_atEnd; }
+
+ void initializeForCurrentObject();
+
+ void increment();
+
+ void handleBR(EClear&);
+ void handleOutOfFlowPositioned(Vector<RenderBox*>& positionedObjects);
+ void handleFloat();
+ void handleEmptyInline();
+ void handleReplaced();
+ bool handleText(WordMeasurements&, bool& hyphenated);
+ void commitAndUpdateLineBreakIfNeeded();
+ InlineIterator handleEndOfLine();
+
+ void clearLineBreakIfFitsOnLine()
+ {
+ if (m_width.fitsOnLine() || m_lastWS == NOWRAP)
+ m_lineBreak.clear();
+ }
+
+private:
+ void skipTrailingWhitespace(InlineIterator&, const LineInfo&);
+
+ InlineBidiResolver& m_resolver;
+
+ InlineIterator m_current;
+ InlineIterator m_lineBreak;
+ InlineIterator m_startOfIgnoredSpaces;
+
+ RenderBlockFlow* m_block;
+ RenderObject* m_lastObject;
+ RenderObject* m_nextObject;
+
+ RenderStyle* m_currentStyle;
+ RenderStyle* m_blockStyle;
+
+ LineInfo& m_lineInfo;
+
+ RenderTextInfo& m_renderTextInfo;
+
+ FloatingObject* m_lastFloatFromPreviousLine;
+
+ LineWidth m_width;
+
+ EWhiteSpace m_currWS;
+ EWhiteSpace m_lastWS;
+
+ bool m_preservesNewline;
+ bool m_atStart;
+ bool m_ignoringSpaces;
+ bool m_currentCharacterIsSpace;
+ bool m_currentCharacterShouldCollapseIfPreWap;
+ bool m_appliedStartWidth;
+ bool m_includeEndWidth;
+ bool m_autoWrap;
+ bool m_autoWrapWasEverTrueOnLine;
+ bool m_floatsFitOnLine;
+ bool m_collapseWhiteSpace;
+ bool m_startingNewParagraph;
+ bool m_allowImagesToBreak;
+ bool m_atEnd;
+
+ LineMidpointState& m_lineMidpointState;
+
+ TrailingObjects m_trailingObjects;
+};
+
+enum WhitespacePosition { LeadingWhitespace, TrailingWhitespace };
+
+inline bool shouldCollapseWhiteSpace(const RenderStyle* style, const LineInfo& lineInfo, WhitespacePosition whitespacePosition)
+{
+ // CSS2 16.6.1
+ // If a space (U+0020) at the beginning of a line has 'white-space' set to 'normal', 'nowrap', or 'pre-line', it is removed.
+ // If a space (U+0020) at the end of a line has 'white-space' set to 'normal', 'nowrap', or 'pre-line', it is also removed.
+ // If spaces (U+0020) or tabs (U+0009) at the end of a line have 'white-space' set to 'pre-wrap', UAs may visually collapse them.
+ return style->collapseWhiteSpace()
+ || (whitespacePosition == TrailingWhitespace && style->whiteSpace() == PRE_WRAP && (!lineInfo.isEmpty() || !lineInfo.previousLineBrokeCleanly()));
+}
+
+inline bool requiresLineBoxForContent(RenderInline* flow, const LineInfo& lineInfo)
+{
+ RenderObject* parent = flow->parent();
+ if (flow->document().inNoQuirksMode()
+ && (flow->style(lineInfo.isFirstLine())->lineHeight() != parent->style(lineInfo.isFirstLine())->lineHeight()
+ || flow->style()->verticalAlign() != parent->style()->verticalAlign()
+ || !parent->style()->font().fontMetrics().hasIdenticalAscentDescentAndLineGap(flow->style()->font().fontMetrics())))
+ return true;
+ return false;
+}
+
+inline bool alwaysRequiresLineBox(RenderObject* flow)
+{
+ // FIXME: Right now, we only allow line boxes for inlines that are truly empty.
+ // We need to fix this, though, because at the very least, inlines containing only
+ // ignorable whitespace should should also have line boxes.
+ return isEmptyInline(flow) && toRenderInline(flow)->hasInlineDirectionBordersPaddingOrMargin();
+}
+
+inline bool requiresLineBox(const InlineIterator& it, const LineInfo& lineInfo = LineInfo(), WhitespacePosition whitespacePosition = LeadingWhitespace)
+{
+ if (it.object()->isFloatingOrOutOfFlowPositioned())
+ return false;
+
+ if (it.object()->isRenderInline() && !alwaysRequiresLineBox(it.object()) && !requiresLineBoxForContent(toRenderInline(it.object()), lineInfo))
+ return false;
+
+ if (!shouldCollapseWhiteSpace(it.object()->style(), lineInfo, whitespacePosition) || it.object()->isBR())
+ return true;
+
+ UChar current = it.current();
+ bool notJustWhitespace = current != ' ' && current != '\t' && current != softHyphen && (current != '\n' || it.object()->preservesNewline());
+ return notJustWhitespace || isEmptyInline(it.object());
+}
+
+inline void setStaticPositions(RenderBlockFlow* block, RenderBox* child)
+{
+ // FIXME: The math here is actually not really right. It's a best-guess approximation that
+ // will work for the common cases
+ RenderObject* containerBlock = child->container();
+ LayoutUnit blockHeight = block->logicalHeight();
+ if (containerBlock->isRenderInline()) {
+ // A relative positioned inline encloses us. In this case, we also have to determine our
+ // position as though we were an inline. Set |staticInlinePosition| and |staticBlockPosition| on the relative positioned
+ // inline so that we can obtain the value later.
+ toRenderInline(containerBlock)->layer()->setStaticInlinePosition(block->startAlignedOffsetForLine(blockHeight, false));
+ toRenderInline(containerBlock)->layer()->setStaticBlockPosition(blockHeight);
+ }
+ block->updateStaticInlinePositionForChild(child, blockHeight);
+ child->layer()->setStaticBlockPosition(blockHeight);
+}
+
+// FIXME: The entire concept of the skipTrailingWhitespace function is flawed, since we really need to be building
+// line boxes even for containers that may ultimately collapse away. Otherwise we'll never get positioned
+// elements quite right. In other words, we need to build this function's work into the normal line
+// object iteration process.
+// NB. this function will insert any floating elements that would otherwise
+// be skipped but it will not position them.
+inline void BreakingContext::skipTrailingWhitespace(InlineIterator& iterator, const LineInfo& lineInfo)
+{
+ while (!iterator.atEnd() && !requiresLineBox(iterator, lineInfo, TrailingWhitespace)) {
+ RenderObject* object = iterator.object();
+ if (object->isOutOfFlowPositioned())
+ setStaticPositions(m_block, toRenderBox(object));
+ else if (object->isFloating())
+ m_block->insertFloatingObject(toRenderBox(object));
+ iterator.increment();
+ }
+}
+
+inline void BreakingContext::initializeForCurrentObject()
+{
+ m_currentStyle = m_current.object()->style();
+ m_nextObject = bidiNextSkippingEmptyInlines(m_block, m_current.object());
+ if (m_nextObject && m_nextObject->parent() && !m_nextObject->parent()->isDescendantOf(m_current.object()->parent()))
+ m_includeEndWidth = true;
+
+ m_currWS = m_current.object()->isReplaced() ? m_current.object()->parent()->style()->whiteSpace() : m_currentStyle->whiteSpace();
+ m_lastWS = m_lastObject->isReplaced() ? m_lastObject->parent()->style()->whiteSpace() : m_lastObject->style()->whiteSpace();
+
+ m_autoWrap = RenderStyle::autoWrap(m_currWS);
+ m_autoWrapWasEverTrueOnLine = m_autoWrapWasEverTrueOnLine || m_autoWrap;
+
+ m_preservesNewline = m_current.object()->isSVGInlineText() ? false : RenderStyle::preserveNewline(m_currWS);
+
+ m_collapseWhiteSpace = RenderStyle::collapseWhiteSpace(m_currWS);
+}
+
+inline void BreakingContext::increment()
+{
+ // Clear out our character space bool, since inline <pre>s don't collapse whitespace
+ // with adjacent inline normal/nowrap spans.
+ if (!m_collapseWhiteSpace)
+ m_currentCharacterIsSpace = false;
+
+ m_current.moveToStartOf(m_nextObject);
+ m_atStart = false;
+}
+
+inline void BreakingContext::handleBR(EClear& clear)
+{
+ if (m_width.fitsOnLine()) {
+ RenderObject* br = m_current.object();
+ m_lineBreak.moveToStartOf(br);
+ m_lineBreak.increment();
+
+ // A <br> always breaks a line, so don't let the line be collapsed
+ // away. Also, the space at the end of a line with a <br> does not
+ // get collapsed away. It only does this if the previous line broke
+ // cleanly. Otherwise the <br> has no effect on whether the line is
+ // empty or not.
+ if (m_startingNewParagraph)
+ m_lineInfo.setEmpty(false, m_block, &m_width);
+ m_trailingObjects.clear();
+ m_lineInfo.setPreviousLineBrokeCleanly(true);
+
+ // A <br> with clearance always needs a linebox in case the lines below it get dirtied later and
+ // need to check for floats to clear - so if we're ignoring spaces, stop ignoring them and add a
+ // run for this object.
+ if (m_ignoringSpaces && m_currentStyle->clear() != CNONE)
+ ensureLineBoxInsideIgnoredSpaces(m_lineMidpointState, br);
+
+ if (!m_lineInfo.isEmpty())
+ clear = m_currentStyle->clear();
+ }
+ m_atEnd = true;
+}
+
+inline LayoutUnit borderPaddingMarginStart(RenderInline* child)
+{
+ return child->marginStart() + child->paddingStart() + child->borderStart();
+}
+
+inline LayoutUnit borderPaddingMarginEnd(RenderInline* child)
+{
+ return child->marginEnd() + child->paddingEnd() + child->borderEnd();
+}
+
+inline bool shouldAddBorderPaddingMargin(RenderObject* child, bool &checkSide)
+{
+ if (!child || (child->isText() && !toRenderText(child)->textLength()))
+ return true;
+ checkSide = false;
+ return checkSide;
+}
+
+inline LayoutUnit inlineLogicalWidth(RenderObject* child, bool start = true, bool end = true)
+{
+ unsigned lineDepth = 1;
+ LayoutUnit extraWidth = 0;
+ RenderObject* parent = child->parent();
+ while (parent->isRenderInline() && lineDepth++ < cMaxLineDepth) {
+ RenderInline* parentAsRenderInline = toRenderInline(parent);
+ if (!isEmptyInline(parentAsRenderInline)) {
+ if (start && shouldAddBorderPaddingMargin(child->previousSibling(), start))
+ extraWidth += borderPaddingMarginStart(parentAsRenderInline);
+ if (end && shouldAddBorderPaddingMargin(child->nextSibling(), end))
+ extraWidth += borderPaddingMarginEnd(parentAsRenderInline);
+ if (!start && !end)
+ return extraWidth;
+ }
+ child = parent;
+ parent = child->parent();
+ }
+ return extraWidth;
+}
+
+inline void BreakingContext::handleOutOfFlowPositioned(Vector<RenderBox*>& positionedObjects)
+{
+ // If our original display wasn't an inline type, then we can
+ // go ahead and determine our static inline position now.
+ RenderBox* box = toRenderBox(m_current.object());
+ bool isInlineType = box->style()->isOriginalDisplayInlineType();
+ if (!isInlineType) {
+ m_block->setStaticInlinePositionForChild(box, m_block->logicalHeight(), m_block->startOffsetForContent(m_block->logicalHeight()));
+ } else {
+ // If our original display was an INLINE type, then we can go ahead
+ // and determine our static y position now.
+ box->layer()->setStaticBlockPosition(m_block->logicalHeight());
+ }
+
+ // If we're ignoring spaces, we have to stop and include this object and
+ // then start ignoring spaces again.
+ if (isInlineType || box->container()->isRenderInline()) {
+ if (m_ignoringSpaces)
+ ensureLineBoxInsideIgnoredSpaces(m_lineMidpointState, box);
+ m_trailingObjects.appendBoxIfNeeded(box);
+ } else {
+ positionedObjects.append(box);
+ }
+ m_width.addUncommittedWidth(inlineLogicalWidth(box));
+ // Reset prior line break context characters.
+ m_renderTextInfo.m_lineBreakIterator.resetPriorContext();
+}
+
+inline void BreakingContext::handleFloat()
+{
+ RenderBox* floatBox = toRenderBox(m_current.object());
+ FloatingObject* floatingObject = m_block->insertFloatingObject(floatBox);
+ // check if it fits in the current line.
+ // If it does, position it now, otherwise, position
+ // it after moving to next line (in newLine() func)
+ // FIXME: Bug 110372: Properly position multiple stacked floats with non-rectangular shape outside.
+ if (m_floatsFitOnLine && m_width.fitsOnLine(m_block->logicalWidthForFloat(floatingObject))) {
+ m_block->positionNewFloatOnLine(floatingObject, m_lastFloatFromPreviousLine, m_lineInfo, m_width);
+ if (m_lineBreak.object() == m_current.object()) {
+ ASSERT(!m_lineBreak.m_pos);
+ m_lineBreak.increment();
+ }
+ } else {
+ m_floatsFitOnLine = false;
+ }
+ // Update prior line break context characters, using U+FFFD (OBJECT REPLACEMENT CHARACTER) for floating element.
+ m_renderTextInfo.m_lineBreakIterator.updatePriorContext(replacementCharacter);
+}
+
+// This is currently just used for list markers and inline flows that have line boxes. Neither should
+// have an effect on whitespace at the start of the line.
+inline bool shouldSkipWhitespaceAfterStartObject(RenderBlockFlow* block, RenderObject* o, LineMidpointState& lineMidpointState)
+{
+ RenderObject* next = bidiNextSkippingEmptyInlines(block, o);
+ while (next && next->isFloatingOrOutOfFlowPositioned())
+ next = bidiNextSkippingEmptyInlines(block, next);
+
+ if (next && !next->isBR() && next->isText() && toRenderText(next)->textLength() > 0) {
+ RenderText* nextText = toRenderText(next);
+ UChar nextChar = nextText->characterAt(0);
+ if (nextText->style()->isCollapsibleWhiteSpace(nextChar)) {
+ startIgnoringSpaces(lineMidpointState, InlineIterator(0, o, 0));
+ return true;
+ }
+ }
+
+ return false;
+}
+
+inline void BreakingContext::handleEmptyInline()
+{
+ // This should only end up being called on empty inlines
+ ASSERT(isEmptyInline(m_current.object()));
+
+ RenderInline* flowBox = toRenderInline(m_current.object());
+
+ // Now that some inline flows have line boxes, if we are already ignoring spaces, we need
+ // to make sure that we stop to include this object and then start ignoring spaces again.
+ // If this object is at the start of the line, we need to behave like list markers and
+ // start ignoring spaces.
+ bool requiresLineBox = alwaysRequiresLineBox(m_current.object());
+ if (requiresLineBox || requiresLineBoxForContent(flowBox, m_lineInfo)) {
+ // An empty inline that only has line-height, vertical-align or font-metrics will only get a
+ // line box to affect the height of the line if the rest of the line is not empty.
+ if (requiresLineBox)
+ m_lineInfo.setEmpty(false, m_block, &m_width);
+ if (m_ignoringSpaces) {
+ m_trailingObjects.clear();
+ ensureLineBoxInsideIgnoredSpaces(m_lineMidpointState, m_current.object());
+ } else if (m_blockStyle->collapseWhiteSpace() && m_resolver.position().object() == m_current.object()
+ && shouldSkipWhitespaceAfterStartObject(m_block, m_current.object(), m_lineMidpointState)) {
+ // Like with list markers, we start ignoring spaces to make sure that any
+ // additional spaces we see will be discarded.
+ m_currentCharacterShouldCollapseIfPreWap = m_currentCharacterIsSpace = true;
+ m_ignoringSpaces = true;
+ }
+ }
+
+ m_width.addUncommittedWidth(inlineLogicalWidth(m_current.object()) + borderPaddingMarginStart(flowBox) + borderPaddingMarginEnd(flowBox));
+}
+
+inline void BreakingContext::handleReplaced()
+{
+ RenderBox* replacedBox = toRenderBox(m_current.object());
+
+ if (m_atStart)
+ m_width.updateAvailableWidth(replacedBox->logicalHeight());
+
+ // Break on replaced elements if either has normal white-space.
+ if ((m_autoWrap || RenderStyle::autoWrap(m_lastWS)) && (!m_current.object()->isImage() || m_allowImagesToBreak)) {
+ m_width.commit();
+ m_lineBreak.moveToStartOf(m_current.object());
+ }
+
+ if (m_ignoringSpaces)
+ stopIgnoringSpaces(m_lineMidpointState, InlineIterator(0, m_current.object(), 0));
+
+ m_lineInfo.setEmpty(false, m_block, &m_width);
+ m_ignoringSpaces = false;
+ m_currentCharacterShouldCollapseIfPreWap = m_currentCharacterIsSpace = false;
+ m_trailingObjects.clear();
+
+ // Optimize for a common case. If we can't find whitespace after the list
+ // item, then this is all moot.
+ LayoutUnit replacedLogicalWidth = m_block->logicalWidthForChild(replacedBox) + m_block->marginStartForChild(replacedBox) + m_block->marginEndForChild(replacedBox) + inlineLogicalWidth(m_current.object());
+ if (m_current.object()->isListMarker()) {
+ if (m_blockStyle->collapseWhiteSpace() && shouldSkipWhitespaceAfterStartObject(m_block, m_current.object(), m_lineMidpointState)) {
+ // Like with inline flows, we start ignoring spaces to make sure that any
+ // additional spaces we see will be discarded.
+ m_currentCharacterShouldCollapseIfPreWap = m_currentCharacterIsSpace = true;
+ m_ignoringSpaces = true;
+ }
+ if (toRenderListMarker(m_current.object())->isInside())
+ m_width.addUncommittedWidth(replacedLogicalWidth);
+ } else {
+ m_width.addUncommittedWidth(replacedLogicalWidth);
+ }
+ if (m_current.object()->isRubyRun())
+ m_width.applyOverhang(toRenderRubyRun(m_current.object()), m_lastObject, m_nextObject);
+ // Update prior line break context characters, using U+FFFD (OBJECT REPLACEMENT CHARACTER) for replaced element.
+ m_renderTextInfo.m_lineBreakIterator.updatePriorContext(replacementCharacter);
+}
+
+inline bool iteratorIsBeyondEndOfRenderCombineText(const InlineIterator& iter, RenderCombineText* renderer)
+{
+ return iter.object() == renderer && iter.m_pos >= renderer->textLength();
+}
+
+inline void nextCharacter(UChar& currentCharacter, UChar& lastCharacter, UChar& secondToLastCharacter)
+{
+ secondToLastCharacter = lastCharacter;
+ lastCharacter = currentCharacter;
+}
+
+inline float firstPositiveWidth(const WordMeasurements& wordMeasurements)
+{
+ for (size_t i = 0; i < wordMeasurements.size(); ++i) {
+ if (wordMeasurements[i].width > 0)
+ return wordMeasurements[i].width;
+ }
+ return 0;
+}
+
+inline void updateSegmentsForShapes(RenderBlockFlow* block, const FloatingObject* lastFloatFromPreviousLine, const WordMeasurements& wordMeasurements, LineWidth& width, bool isFirstLine)
+{
+ ASSERT(lastFloatFromPreviousLine);
+
+ ShapeInsideInfo* shapeInsideInfo = block->layoutShapeInsideInfo();
+ if (!lastFloatFromPreviousLine->isPlaced() || !shapeInsideInfo)
+ return;
+
+ bool isHorizontalWritingMode = block->isHorizontalWritingMode();
+ LayoutUnit logicalOffsetFromShapeContainer = block->logicalOffsetFromShapeAncestorContainer(shapeInsideInfo->owner()).height();
+
+ LayoutUnit lineLogicalTop = block->logicalHeight() + logicalOffsetFromShapeContainer;
+ LayoutUnit lineLogicalHeight = block->lineHeight(isFirstLine, isHorizontalWritingMode ? HorizontalLine : VerticalLine, PositionOfInteriorLineBoxes);
+ LayoutUnit lineLogicalBottom = lineLogicalTop + lineLogicalHeight;
+
+ LayoutUnit floatLogicalTop = block->logicalTopForFloat(lastFloatFromPreviousLine);
+ LayoutUnit floatLogicalBottom = block->logicalBottomForFloat(lastFloatFromPreviousLine);
+
+ bool lineOverlapsWithFloat = (floatLogicalTop < lineLogicalBottom) && (lineLogicalTop < floatLogicalBottom);
+ if (!lineOverlapsWithFloat)
+ return;
+
+ float minSegmentWidth = firstPositiveWidth(wordMeasurements);
+
+ LayoutUnit floatLogicalWidth = block->logicalWidthForFloat(lastFloatFromPreviousLine);
+ LayoutUnit availableLogicalWidth = block->logicalWidth() - block->logicalRightForFloat(lastFloatFromPreviousLine);
+ if (availableLogicalWidth < minSegmentWidth)
+ block->setLogicalHeight(floatLogicalBottom);
+
+ if (block->logicalHeight() < floatLogicalTop) {
+ shapeInsideInfo->adjustLogicalLineTop(minSegmentWidth + floatLogicalWidth);
+ block->setLogicalHeight(shapeInsideInfo->logicalLineTop() - logicalOffsetFromShapeContainer);
+ }
+
+ lineLogicalTop = block->logicalHeight() + logicalOffsetFromShapeContainer;
+
+ shapeInsideInfo->updateSegmentsForLine(lineLogicalTop, lineLogicalHeight);
+ width.updateCurrentShapeSegment();
+ width.updateAvailableWidth();
+}
+
+inline float measureHyphenWidth(RenderText* renderer, const Font& font)
+{
+ RenderStyle* style = renderer->style();
+ return font.width(RenderBlockFlow::constructTextRun(renderer, font, style->hyphenString().string(), style));
+}
+
+ALWAYS_INLINE float textWidth(RenderText* text, unsigned from, unsigned len, const Font& font, float xPos, bool isFixedPitch, bool collapseWhiteSpace, HashSet<const SimpleFontData*>* fallbackFonts = 0, TextLayout* layout = 0)
+{
+ GlyphOverflow glyphOverflow;
+ if (isFixedPitch || (!from && len == text->textLength()) || text->style()->hasTextCombine())
+ return text->width(from, len, font, xPos, fallbackFonts, &glyphOverflow);
+
+ if (layout)
+ return Font::width(*layout, from, len, fallbackFonts);
+
+ TextRun run = RenderBlockFlow::constructTextRun(text, font, text, from, len, text->style());
+ run.setCharactersLength(text->textLength() - from);
+ ASSERT(run.charactersLength() >= run.length());
+
+ run.setCharacterScanForCodePath(!text->canUseSimpleFontCodePath());
+ run.setTabSize(!collapseWhiteSpace, text->style()->tabSize());
+ run.setXPos(xPos);
+ return font.width(run, fallbackFonts, &glyphOverflow);
+}
+
+inline bool BreakingContext::handleText(WordMeasurements& wordMeasurements, bool& hyphenated)
+{
+ if (!m_current.m_pos)
+ m_appliedStartWidth = false;
+
+ RenderText* renderText = toRenderText(m_current.object());
+
+ bool isSVGText = renderText->isSVGInlineText();
+
+ if (renderText->style()->hasTextCombine() && m_current.object()->isCombineText() && !toRenderCombineText(m_current.object())->isCombined()) {
+ RenderCombineText* combineRenderer = toRenderCombineText(m_current.object());
+ combineRenderer->combineText();
+ // The length of the renderer's text may have changed. Increment stale iterator positions
+ if (iteratorIsBeyondEndOfRenderCombineText(m_lineBreak, combineRenderer)) {
+ ASSERT(iteratorIsBeyondEndOfRenderCombineText(m_resolver.position(), combineRenderer));
+ m_lineBreak.increment();
+ m_resolver.position().increment(&m_resolver);
+ }
+ }
+
+ RenderStyle* style = renderText->style(m_lineInfo.isFirstLine());
+ const Font& font = style->font();
+ bool isFixedPitch = font.isFixedPitch();
+
+ unsigned lastSpace = m_current.m_pos;
+ float wordSpacing = m_currentStyle->wordSpacing();
+ float lastSpaceWordSpacing = 0;
+ float wordSpacingForWordMeasurement = 0;
+
+ float wrapW = m_width.uncommittedWidth() + inlineLogicalWidth(m_current.object(), !m_appliedStartWidth, true);
+ float charWidth = 0;
+ // Auto-wrapping text should wrap in the middle of a word only if it could not wrap before the word,
+ // which is only possible if the word is the first thing on the line, that is, if |w| is zero.
+ bool breakWords = m_currentStyle->breakWords() && ((m_autoWrap && !m_width.committedWidth()) || m_currWS == PRE);
+ bool midWordBreak = false;
+ bool breakAll = m_currentStyle->wordBreak() == BreakAllWordBreak && m_autoWrap;
+ float hyphenWidth = 0;
+
+ if (isSVGText) {
+ breakWords = false;
+ breakAll = false;
+ }
+
+ if (renderText->isWordBreak()) {
+ m_width.commit();
+ m_lineBreak.moveToStartOf(m_current.object());
+ ASSERT(m_current.m_pos == renderText->textLength());
+ }
+
+ if (m_renderTextInfo.m_text != renderText) {
+ m_renderTextInfo.m_text = renderText;
+ m_renderTextInfo.m_font = &font;
+ m_renderTextInfo.createLayout(renderText, m_width.currentWidth(), m_collapseWhiteSpace);
+ m_renderTextInfo.m_lineBreakIterator.resetStringAndReleaseIterator(renderText->text(), style->locale());
+ } else if (m_renderTextInfo.m_layout && m_renderTextInfo.m_font != &font) {
+ m_renderTextInfo.m_font = &font;
+ m_renderTextInfo.createLayout(renderText, m_width.currentWidth(), m_collapseWhiteSpace);
+ }
+
+ TextLayout* textLayout = m_renderTextInfo.m_layout.get();
+
+ // Non-zero only when kerning is enabled and TextLayout isn't used, in which case we measure
+ // words with their trailing space, then subtract its width.
+ float wordTrailingSpaceWidth = (font.typesettingFeatures() & Kerning) && !textLayout ? font.width(RenderBlockFlow::constructTextRun(renderText, font, &space, 1, style)) + wordSpacing : 0;
+
+ UChar lastCharacter = m_renderTextInfo.m_lineBreakIterator.lastCharacter();
+ UChar secondToLastCharacter = m_renderTextInfo.m_lineBreakIterator.secondToLastCharacter();
+ for (; m_current.m_pos < renderText->textLength(); m_current.fastIncrementInTextNode()) {
+ bool previousCharacterIsSpace = m_currentCharacterIsSpace;
+ bool previousCharacterShouldCollapseIfPreWap = m_currentCharacterShouldCollapseIfPreWap;
+ UChar c = m_current.current();
+ m_currentCharacterShouldCollapseIfPreWap = m_currentCharacterIsSpace = c == ' ' || c == '\t' || (!m_preservesNewline && (c == '\n'));
+
+ if (!m_collapseWhiteSpace || !m_currentCharacterIsSpace)
+ m_lineInfo.setEmpty(false, m_block, &m_width);
+
+ if (c == softHyphen && m_autoWrap && !hyphenWidth) {
+ hyphenWidth = measureHyphenWidth(renderText, font);
+ m_width.addUncommittedWidth(hyphenWidth);
+ }
+
+ bool applyWordSpacing = false;
+
+ if ((breakAll || breakWords) && !midWordBreak) {
+ wrapW += charWidth;
+ bool midWordBreakIsBeforeSurrogatePair = U16_IS_LEAD(c) && m_current.m_pos + 1 < renderText->textLength() && U16_IS_TRAIL((*renderText)[m_current.m_pos + 1]);
+ charWidth = textWidth(renderText, m_current.m_pos, midWordBreakIsBeforeSurrogatePair ? 2 : 1, font, m_width.committedWidth() + wrapW, isFixedPitch, m_collapseWhiteSpace, 0, textLayout);
+ midWordBreak = m_width.committedWidth() + wrapW + charWidth > m_width.availableWidth();
+ }
+
+ bool betweenWords = c == '\n' || (m_currWS != PRE && !m_atStart && isBreakable(m_renderTextInfo.m_lineBreakIterator, m_current.m_pos, m_current.m_nextBreakablePosition));
+
+ if (betweenWords || midWordBreak) {
+ bool stoppedIgnoringSpaces = false;
+ if (m_ignoringSpaces) {
+ lastSpaceWordSpacing = 0;
+ if (!m_currentCharacterIsSpace) {
+ // Stop ignoring spaces and begin at this
+ // new point.
+ m_ignoringSpaces = false;
+ wordSpacingForWordMeasurement = 0;
+ lastSpace = m_current.m_pos; // e.g., "Foo goo", don't add in any of the ignored spaces.
+ stopIgnoringSpaces(m_lineMidpointState, InlineIterator(0, m_current.object(), m_current.m_pos));
+ stoppedIgnoringSpaces = true;
+ } else {
+ // Just keep ignoring these spaces.
+ nextCharacter(c, lastCharacter, secondToLastCharacter);
+ continue;
+ }
+ }
+
+ wordMeasurements.grow(wordMeasurements.size() + 1);
+ WordMeasurement& wordMeasurement = wordMeasurements.last();
+
+ wordMeasurement.renderer = renderText;
+ wordMeasurement.endOffset = m_current.m_pos;
+ wordMeasurement.startOffset = lastSpace;
+
+ float additionalTmpW;
+ if (wordTrailingSpaceWidth && c == ' ')
+ additionalTmpW = textWidth(renderText, lastSpace, m_current.m_pos + 1 - lastSpace, font, m_width.currentWidth(), isFixedPitch, m_collapseWhiteSpace, &wordMeasurement.fallbackFonts, textLayout) - wordTrailingSpaceWidth;
+ else
+ additionalTmpW = textWidth(renderText, lastSpace, m_current.m_pos - lastSpace, font, m_width.currentWidth(), isFixedPitch, m_collapseWhiteSpace, &wordMeasurement.fallbackFonts, textLayout);
+
+ wordMeasurement.width = additionalTmpW + wordSpacingForWordMeasurement;
+ additionalTmpW += lastSpaceWordSpacing;
+ m_width.addUncommittedWidth(additionalTmpW);
+ if (!m_appliedStartWidth) {
+ m_width.addUncommittedWidth(inlineLogicalWidth(m_current.object(), true, false));
+ m_appliedStartWidth = true;
+ }
+
+ if (m_lastFloatFromPreviousLine)
+ updateSegmentsForShapes(m_block, m_lastFloatFromPreviousLine, wordMeasurements, m_width, m_lineInfo.isFirstLine());
+
+ applyWordSpacing = wordSpacing && m_currentCharacterIsSpace;
+
+ if (!m_width.committedWidth() && m_autoWrap && !m_width.fitsOnLine())
+ m_width.fitBelowFloats();
+
+ if (m_autoWrap || breakWords) {
+ // If we break only after white-space, consider the current character
+ // as candidate width for this line.
+ bool lineWasTooWide = false;
+ if (m_width.fitsOnLine() && m_currentCharacterIsSpace && m_currentStyle->breakOnlyAfterWhiteSpace() && !midWordBreak) {
+ float charWidth = textWidth(renderText, m_current.m_pos, 1, font, m_width.currentWidth(), isFixedPitch, m_collapseWhiteSpace, &wordMeasurement.fallbackFonts, textLayout) + (applyWordSpacing ? wordSpacing : 0);
+ // Check if line is too big even without the extra space
+ // at the end of the line. If it is not, do nothing.
+ // If the line needs the extra whitespace to be too long,
+ // then move the line break to the space and skip all
+ // additional whitespace.
+ if (!m_width.fitsOnLine(charWidth)) {
+ lineWasTooWide = true;
+ m_lineBreak.moveTo(m_current.object(), m_current.m_pos, m_current.m_nextBreakablePosition);
+ skipTrailingWhitespace(m_lineBreak, m_lineInfo);
+ }
+ }
+ if (lineWasTooWide || !m_width.fitsOnLine()) {
+ if (m_lineBreak.atTextParagraphSeparator()) {
+ if (!stoppedIgnoringSpaces && m_current.m_pos > 0)
+ ensureCharacterGetsLineBox(m_lineMidpointState, m_current);
+ m_lineBreak.increment();
+ m_lineInfo.setPreviousLineBrokeCleanly(true);
+ wordMeasurement.endOffset = m_lineBreak.m_pos;
+ }
+ if (m_lineBreak.object() && m_lineBreak.m_pos && m_lineBreak.object()->isText() && toRenderText(m_lineBreak.object())->textLength() && toRenderText(m_lineBreak.object())->characterAt(m_lineBreak.m_pos - 1) == softHyphen)
+ hyphenated = true;
+ if (m_lineBreak.m_pos && m_lineBreak.m_pos != (unsigned)wordMeasurement.endOffset && !wordMeasurement.width) {
+ if (charWidth) {
+ wordMeasurement.endOffset = m_lineBreak.m_pos;
+ wordMeasurement.width = charWidth;
+ }
+ }
+ // Didn't fit. Jump to the end unless there's still an opportunity to collapse whitespace.
+ if (m_ignoringSpaces || !m_collapseWhiteSpace || !m_currentCharacterIsSpace || !previousCharacterIsSpace) {
+ m_atEnd = true;
+ return false;
+ }
+ } else {
+ if (!betweenWords || (midWordBreak && !m_autoWrap))
+ m_width.addUncommittedWidth(-additionalTmpW);
+ if (hyphenWidth) {
+ // Subtract the width of the soft hyphen out since we fit on a line.
+ m_width.addUncommittedWidth(-hyphenWidth);
+ hyphenWidth = 0;
+ }
+ }
+ }
+
+ if (c == '\n' && m_preservesNewline) {
+ if (!stoppedIgnoringSpaces && m_current.m_pos > 0)
+ ensureCharacterGetsLineBox(m_lineMidpointState, m_current);
+ m_lineBreak.moveTo(m_current.object(), m_current.m_pos, m_current.m_nextBreakablePosition);
+ m_lineBreak.increment();
+ m_lineInfo.setPreviousLineBrokeCleanly(true);
+ return true;
+ }
+
+ if (m_autoWrap && betweenWords) {
+ m_width.commit();
+ wrapW = 0;
+ m_lineBreak.moveTo(m_current.object(), m_current.m_pos, m_current.m_nextBreakablePosition);
+ // Auto-wrapping text should not wrap in the middle of a word once it has had an
+ // opportunity to break after a word.
+ breakWords = false;
+ }
+
+ if (midWordBreak && !U16_IS_TRAIL(c) && !(category(c) & (Mark_NonSpacing | Mark_Enclosing | Mark_SpacingCombining))) {
+ // Remember this as a breakable position in case
+ // adding the end width forces a break.
+ m_lineBreak.moveTo(m_current.object(), m_current.m_pos, m_current.m_nextBreakablePosition);
+ midWordBreak &= (breakWords || breakAll);
+ }
+
+ if (betweenWords) {
+ lastSpaceWordSpacing = applyWordSpacing ? wordSpacing : 0;
+ wordSpacingForWordMeasurement = (applyWordSpacing && wordMeasurement.width) ? wordSpacing : 0;
+ lastSpace = m_current.m_pos;
+ }
+
+ if (!m_ignoringSpaces && m_currentStyle->collapseWhiteSpace()) {
+ // If we encounter a newline, or if we encounter a
+ // second space, we need to go ahead and break up this
+ // run and enter a mode where we start collapsing spaces.
+ if (m_currentCharacterIsSpace && previousCharacterIsSpace) {
+ m_ignoringSpaces = true;
+
+ // We just entered a mode where we are ignoring
+ // spaces. Create a midpoint to terminate the run
+ // before the second space.
+ startIgnoringSpaces(m_lineMidpointState, m_startOfIgnoredSpaces);
+ m_trailingObjects.updateMidpointsForTrailingBoxes(m_lineMidpointState, InlineIterator(), TrailingObjects::DoNotCollapseFirstSpace);
+ }
+ }
+ } else if (m_ignoringSpaces) {
+ // Stop ignoring spaces and begin at this
+ // new point.
+ m_ignoringSpaces = false;
+ lastSpaceWordSpacing = applyWordSpacing ? wordSpacing : 0;
+ wordSpacingForWordMeasurement = (applyWordSpacing && wordMeasurements.last().width) ? wordSpacing : 0;
+ lastSpace = m_current.m_pos; // e.g., "Foo goo", don't add in any of the ignored spaces.
+ stopIgnoringSpaces(m_lineMidpointState, InlineIterator(0, m_current.object(), m_current.m_pos));
+ }
+
+ if (isSVGText && m_current.m_pos > 0) {
+ // Force creation of new InlineBoxes for each absolute positioned character (those that start new text chunks).
+ if (toRenderSVGInlineText(renderText)->characterStartsNewTextChunk(m_current.m_pos))
+ ensureCharacterGetsLineBox(m_lineMidpointState, m_current);
+ }
+
+ if (m_currentCharacterIsSpace && !previousCharacterIsSpace) {
+ m_startOfIgnoredSpaces.setObject(m_current.object());
+ m_startOfIgnoredSpaces.m_pos = m_current.m_pos;
+ }
+
+ if (!m_currentCharacterIsSpace && previousCharacterShouldCollapseIfPreWap) {
+ if (m_autoWrap && m_currentStyle->breakOnlyAfterWhiteSpace())
+ m_lineBreak.moveTo(m_current.object(), m_current.m_pos, m_current.m_nextBreakablePosition);
+ }
+
+ if (m_collapseWhiteSpace && m_currentCharacterIsSpace && !m_ignoringSpaces)
+ m_trailingObjects.setTrailingWhitespace(toRenderText(m_current.object()));
+ else if (!m_currentStyle->collapseWhiteSpace() || !m_currentCharacterIsSpace)
+ m_trailingObjects.clear();
+
+ m_atStart = false;
+ nextCharacter(c, lastCharacter, secondToLastCharacter);
+ }
+
+ m_renderTextInfo.m_lineBreakIterator.setPriorContext(lastCharacter, secondToLastCharacter);
+
+ wordMeasurements.grow(wordMeasurements.size() + 1);
+ WordMeasurement& wordMeasurement = wordMeasurements.last();
+ wordMeasurement.renderer = renderText;
+
+ // IMPORTANT: current.m_pos is > length here!
+ float additionalTmpW = m_ignoringSpaces ? 0 : textWidth(renderText, lastSpace, m_current.m_pos - lastSpace, font, m_width.currentWidth(), isFixedPitch, m_collapseWhiteSpace, &wordMeasurement.fallbackFonts, textLayout);
+ wordMeasurement.startOffset = lastSpace;
+ wordMeasurement.endOffset = m_current.m_pos;
+ wordMeasurement.width = m_ignoringSpaces ? 0 : additionalTmpW + wordSpacingForWordMeasurement;
+ additionalTmpW += lastSpaceWordSpacing;
+ m_width.addUncommittedWidth(additionalTmpW + inlineLogicalWidth(m_current.object(), !m_appliedStartWidth, m_includeEndWidth));
+ m_includeEndWidth = false;
+
+ if (!m_width.fitsOnLine()) {
+ if (!hyphenated && m_lineBreak.previousInSameNode() == softHyphen) {
+ hyphenated = true;
+ m_atEnd = true;
+ }
+ }
+ return false;
+}
+
+inline void BreakingContext::commitAndUpdateLineBreakIfNeeded()
+{
+ bool checkForBreak = m_autoWrap;
+ if (m_width.committedWidth() && !m_width.fitsOnLine() && m_lineBreak.object() && m_currWS == NOWRAP) {
+ checkForBreak = true;
+ } else if (m_nextObject && m_current.object()->isText() && m_nextObject->isText() && !m_nextObject->isBR() && (m_autoWrap || m_nextObject->style()->autoWrap())) {
+ if (m_autoWrap && m_currentCharacterIsSpace) {
+ checkForBreak = true;
+ } else {
+ RenderText* nextText = toRenderText(m_nextObject);
+ if (nextText->textLength()) {
+ UChar c = nextText->characterAt(0);
+ // If the next item on the line is text, and if we did not end with
+ // a space, then the next text run continues our word (and so it needs to
+ // keep adding to the uncommitted width. Just update and continue.
+ checkForBreak = !m_currentCharacterIsSpace && (c == ' ' || c == '\t' || (c == '\n' && !m_nextObject->preservesNewline()));
+ } else if (nextText->isWordBreak()) {
+ checkForBreak = true;
+ }
+
+ if (!m_width.fitsOnLine() && !m_width.committedWidth())
+ m_width.fitBelowFloats();
+
+ bool canPlaceOnLine = m_width.fitsOnLine() || !m_autoWrapWasEverTrueOnLine;
+ if (canPlaceOnLine && checkForBreak) {
+ m_width.commit();
+ m_lineBreak.moveToStartOf(m_nextObject);
+ }
+ }
+ }
+
+ if (checkForBreak && !m_width.fitsOnLine()) {
+ // if we have floats, try to get below them.
+ if (m_currentCharacterIsSpace && !m_ignoringSpaces && m_currentStyle->collapseWhiteSpace())
+ m_trailingObjects.clear();
+
+ if (m_width.committedWidth()) {
+ m_atEnd = true;
+ return;
+ }
+
+ m_width.fitBelowFloats();
+
+ // |width| may have been adjusted because we got shoved down past a float (thus
+ // giving us more room), so we need to retest, and only jump to
+ // the end label if we still don't fit on the line. -dwh
+ if (!m_width.fitsOnLine()) {
+ m_atEnd = true;
+ return;
+ }
+ } else if (m_blockStyle->autoWrap() && !m_width.fitsOnLine() && !m_width.committedWidth()) {
+ // If the container autowraps but the current child does not then we still need to ensure that it
+ // wraps and moves below any floats.
+ m_width.fitBelowFloats();
+ }
+
+ if (!m_current.object()->isFloatingOrOutOfFlowPositioned()) {
+ m_lastObject = m_current.object();
+ if (m_lastObject->isReplaced() && m_autoWrap && (!m_lastObject->isImage() || m_allowImagesToBreak) && (!m_lastObject->isListMarker() || toRenderListMarker(m_lastObject)->isInside())) {
+ m_width.commit();
+ m_lineBreak.moveToStartOf(m_nextObject);
+ }
+ }
+}
+
+inline void checkMidpoints(LineMidpointState& lineMidpointState, InlineIterator& lBreak)
+{
+ // Check to see if our last midpoint is a start point beyond the line break. If so,
+ // shave it off the list, and shave off a trailing space if the previous end point doesn't
+ // preserve whitespace.
+ if (lBreak.object() && lineMidpointState.numMidpoints && !(lineMidpointState.numMidpoints % 2)) {
+ InlineIterator* midpoints = lineMidpointState.midpoints.data();
+ InlineIterator& endpoint = midpoints[lineMidpointState.numMidpoints - 2];
+ const InlineIterator& startpoint = midpoints[lineMidpointState.numMidpoints - 1];
+ InlineIterator currpoint = endpoint;
+ while (!currpoint.atEnd() && currpoint != startpoint && currpoint != lBreak)
+ currpoint.increment();
+ if (currpoint == lBreak) {
+ // We hit the line break before the start point. Shave off the start point.
+ lineMidpointState.numMidpoints--;
+ if (endpoint.object()->style()->collapseWhiteSpace() && endpoint.object()->isText())
+ endpoint.m_pos--;
+ }
+ }
+}
+
+InlineIterator BreakingContext::handleEndOfLine()
+{
+ ShapeInsideInfo* shapeInfo = m_block->layoutShapeInsideInfo();
+ bool segmentAllowsOverflow = !shapeInfo || !shapeInfo->hasSegments();
+
+ if (m_lineBreak == m_resolver.position() && (!m_lineBreak.object() || !m_lineBreak.object()->isBR()) && segmentAllowsOverflow) {
+ // we just add as much as possible
+ if (m_blockStyle->whiteSpace() == PRE && !m_current.m_pos) {
+ m_lineBreak.moveTo(m_lastObject, m_lastObject->isText() ? m_lastObject->length() : 0);
+ } else if (m_lineBreak.object()) {
+ // Don't ever break in the middle of a word if we can help it.
+ // There's no room at all. We just have to be on this line,
+ // even though we'll spill out.
+ m_lineBreak.moveTo(m_current.object(), m_current.m_pos);
+ }
+ }
+
+ // FIXME Bug 100049: We do not need to consume input in a multi-segment line
+ // unless no segment will.
+ // make sure we consume at least one char/object.
+ if (m_lineBreak == m_resolver.position() && segmentAllowsOverflow)
+ m_lineBreak.increment();
+
+ // Sanity check our midpoints.
+ checkMidpoints(m_lineMidpointState, m_lineBreak);
+
+ m_trailingObjects.updateMidpointsForTrailingBoxes(m_lineMidpointState, m_lineBreak, TrailingObjects::CollapseFirstSpace);
+
+ // We might have made lineBreak an iterator that points past the end
+ // of the object. Do this adjustment to make it point to the start
+ // of the next object instead to avoid confusing the rest of the
+ // code.
+ if (m_lineBreak.m_pos > 0) {
+ // This loop enforces the invariant that line breaks should never point
+ // at an empty inline. See http://crbug.com/305904.
+ do {
+ m_lineBreak.m_pos--;
+ m_lineBreak.increment();
+ } while (!m_lineBreak.atEnd() && isEmptyInline(m_lineBreak.object()));
+ }
+
+ return m_lineBreak;
+}
+
+}
+
+#endif // BreakingContextInlineHeaders_h
diff --git a/chromium/third_party/WebKit/Source/core/rendering/line/LineInfo.h b/chromium/third_party/WebKit/Source/core/rendering/line/LineInfo.h
new file mode 100644
index 00000000000..337da116e8b
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/rendering/line/LineInfo.h
@@ -0,0 +1,77 @@
+/*
+ * Copyright (C) 2000 Lars Knoll (knoll@kde.org)
+ * Copyright (C) 2003, 2004, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All right reserved.
+ * Copyright (C) 2010 Google Inc. All rights reserved.
+ * Copyright (C) 2013 Adobe Systems Incorporated.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ */
+
+#ifndef LineInfo_h
+#define LineInfo_h
+
+namespace WebCore {
+
+class LineInfo {
+public:
+ LineInfo()
+ : m_isFirstLine(true)
+ , m_isLastLine(false)
+ , m_isEmpty(true)
+ , m_previousLineBrokeCleanly(true)
+ , m_floatPaginationStrut(0)
+ , m_runsFromLeadingWhitespace(0)
+ { }
+
+ bool isFirstLine() const { return m_isFirstLine; }
+ bool isLastLine() const { return m_isLastLine; }
+ bool isEmpty() const { return m_isEmpty; }
+ bool previousLineBrokeCleanly() const { return m_previousLineBrokeCleanly; }
+ LayoutUnit floatPaginationStrut() const { return m_floatPaginationStrut; }
+ unsigned runsFromLeadingWhitespace() const { return m_runsFromLeadingWhitespace; }
+ void resetRunsFromLeadingWhitespace() { m_runsFromLeadingWhitespace = 0; }
+ void incrementRunsFromLeadingWhitespace() { m_runsFromLeadingWhitespace++; }
+
+ void setFirstLine(bool firstLine) { m_isFirstLine = firstLine; }
+ void setLastLine(bool lastLine) { m_isLastLine = lastLine; }
+ void setEmpty(bool empty, RenderBlock* block = 0, LineWidth* lineWidth = 0)
+ {
+ if (m_isEmpty == empty)
+ return;
+ m_isEmpty = empty;
+ if (!empty && block && floatPaginationStrut()) {
+ block->setLogicalHeight(block->logicalHeight() + floatPaginationStrut());
+ setFloatPaginationStrut(0);
+ lineWidth->updateAvailableWidth();
+ }
+ }
+
+ void setPreviousLineBrokeCleanly(bool previousLineBrokeCleanly) { m_previousLineBrokeCleanly = previousLineBrokeCleanly; }
+ void setFloatPaginationStrut(LayoutUnit strut) { m_floatPaginationStrut = strut; }
+
+private:
+ bool m_isFirstLine;
+ bool m_isLastLine;
+ bool m_isEmpty;
+ bool m_previousLineBrokeCleanly;
+ LayoutUnit m_floatPaginationStrut;
+ unsigned m_runsFromLeadingWhitespace;
+};
+
+}
+
+#endif // LineInfo_h
diff --git a/chromium/third_party/WebKit/Source/core/rendering/shapes/BoxShape.cpp b/chromium/third_party/WebKit/Source/core/rendering/shapes/BoxShape.cpp
new file mode 100644
index 00000000000..86c9136ac90
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/rendering/shapes/BoxShape.cpp
@@ -0,0 +1,130 @@
+/*
+ * Copyright (C) 2013 Adobe Systems Incorporated. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer.
+ * 2. Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer in the documentation and/or other materials
+ * provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/rendering/shapes/BoxShape.h"
+
+#include "wtf/MathExtras.h"
+
+namespace WebCore {
+
+LayoutRect BoxShape::shapeMarginLogicalBoundingBox() const
+{
+ FloatRect marginBounds(m_bounds.rect());
+ if (shapeMargin() > 0)
+ marginBounds.inflate(shapeMargin());
+ return static_cast<LayoutRect>(marginBounds);
+}
+
+LayoutRect BoxShape::shapePaddingLogicalBoundingBox() const
+{
+ FloatRect paddingBounds(m_bounds.rect());
+ if (shapePadding() > 0)
+ paddingBounds.inflate(-shapePadding());
+ return static_cast<LayoutRect>(paddingBounds);
+}
+
+FloatRoundedRect BoxShape::shapeMarginBounds() const
+{
+ FloatRoundedRect marginBounds(m_bounds);
+ if (shapeMargin() > 0) {
+ marginBounds.inflate(shapeMargin());
+ marginBounds.expandRadii(shapeMargin());
+ }
+ return marginBounds;
+}
+
+FloatRoundedRect BoxShape::shapePaddingBounds() const
+{
+ FloatRoundedRect paddingBounds(m_bounds);
+ if (shapePadding() > 0) {
+ paddingBounds.inflate(-shapePadding());
+ paddingBounds.expandRadii(-shapePadding());
+ }
+ return paddingBounds;
+}
+
+void BoxShape::getExcludedIntervals(LayoutUnit logicalTop, LayoutUnit logicalHeight, SegmentList& result) const
+{
+ const FloatRoundedRect& marginBounds = shapeMarginBounds();
+ if (marginBounds.isEmpty() || !lineOverlapsShapeMarginBounds(logicalTop, logicalHeight))
+ return;
+
+ float y1 = logicalTop;
+ float y2 = logicalTop + logicalHeight;
+ const FloatRect& rect = marginBounds.rect();
+
+ if (!marginBounds.isRounded()) {
+ result.append(LineSegment(marginBounds.rect().x(), marginBounds.rect().maxX()));
+ return;
+ }
+
+ float x1 = rect.maxX();
+ float x2 = rect.x();
+ float minXIntercept;
+ float maxXIntercept;
+
+ if (marginBounds.xInterceptsAtY(y1, minXIntercept, maxXIntercept)) {
+ x1 = std::min<float>(x1, minXIntercept);
+ x2 = std::max<float>(x2, maxXIntercept);
+ }
+
+ if (marginBounds.xInterceptsAtY(y2, minXIntercept, maxXIntercept)) {
+ x1 = std::min<float>(x1, minXIntercept);
+ x2 = std::max<float>(x2, maxXIntercept);
+ }
+
+ ASSERT(x2 >= x1);
+ result.append(LineSegment(x1, x2));
+}
+
+void BoxShape::getIncludedIntervals(LayoutUnit logicalTop, LayoutUnit logicalHeight, SegmentList& result) const
+{
+ const FloatRoundedRect& paddingBounds = shapePaddingBounds();
+ if (paddingBounds.isEmpty())
+ return;
+
+ const FloatRect& rect = paddingBounds.rect();
+ if (logicalTop < rect.y() || logicalTop + logicalHeight > rect.maxY())
+ return;
+
+ // FIXME: this method is only a stub, https://bugs.webkit.org/show_bug.cgi?id=124605.
+
+ result.append(LineSegment(rect.x(), rect.maxX()));
+}
+
+bool BoxShape::firstIncludedIntervalLogicalTop(LayoutUnit minLogicalIntervalTop, const LayoutSize&, LayoutUnit& result) const
+{
+ // FIXME: this method is only a stub, https://bugs.webkit.org/show_bug.cgi?id=124606.
+
+ result = minLogicalIntervalTop;
+ return true;
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/shapes/BoxShape.h b/chromium/third_party/WebKit/Source/core/rendering/shapes/BoxShape.h
new file mode 100644
index 00000000000..823187a7ca9
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/rendering/shapes/BoxShape.h
@@ -0,0 +1,63 @@
+/*
+ * Copyright (C) 2013 Adobe Systems Incorporated. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer.
+ * 2. Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer in the documentation and/or other materials
+ * provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef BoxShape_h
+#define BoxShape_h
+
+#include "core/rendering/shapes/Shape.h"
+#include "platform/geometry/FloatRoundedRect.h"
+
+namespace WebCore {
+
+class BoxShape : public Shape {
+public:
+ BoxShape(const FloatRoundedRect& bounds)
+ : Shape()
+ , m_bounds(bounds)
+ {
+ }
+
+ virtual LayoutRect shapeMarginLogicalBoundingBox() const OVERRIDE;
+ virtual LayoutRect shapePaddingLogicalBoundingBox() const OVERRIDE;
+ virtual bool isEmpty() const OVERRIDE { return m_bounds.isEmpty(); }
+ virtual void getExcludedIntervals(LayoutUnit logicalTop, LayoutUnit logicalHeight, SegmentList&) const OVERRIDE;
+ virtual void getIncludedIntervals(LayoutUnit logicalTop, LayoutUnit logicalHeight, SegmentList&) const OVERRIDE;
+ virtual bool firstIncludedIntervalLogicalTop(LayoutUnit minLogicalIntervalTop, const LayoutSize& minLogicalIntervalSize, LayoutUnit&) const OVERRIDE;
+
+private:
+ FloatRoundedRect shapeMarginBounds() const;
+ FloatRoundedRect shapePaddingBounds() const;
+
+ FloatRoundedRect m_bounds;
+};
+
+} // namespace WebCore
+
+#endif // BoxShape_h
+
diff --git a/chromium/third_party/WebKit/Source/core/rendering/shapes/BoxShapeTest.cpp b/chromium/third_party/WebKit/Source/core/rendering/shapes/BoxShapeTest.cpp
new file mode 100644
index 00000000000..9b1f50193f1
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/rendering/shapes/BoxShapeTest.cpp
@@ -0,0 +1,113 @@
+/*
+ * Copyright (C) 2013 Adobe Systems Incorporated. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer.
+ * 2. Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer in the documentation and/or other materials
+ * provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+
+#include "core/rendering/shapes/BoxShape.h"
+
+#include <gtest/gtest.h>
+
+namespace WebCore {
+
+class BoxShapeTest : public ::testing::Test {
+protected:
+ BoxShapeTest() { }
+
+ PassOwnPtr<Shape> createBoxShape(const LayoutSize& size, float shapeMargin, float shapePadding)
+ {
+ return Shape::createLayoutBoxShape(size, TopToBottomWritingMode, Length(shapeMargin, Fixed), Length(shapePadding, Fixed));
+ }
+};
+
+} // namespace WebCore
+
+namespace {
+
+using namespace WebCore;
+
+#define TEST_EXCLUDED_INTERVAL(shapePtr, lineTop, lineHeight, expectedLeft, expectedRight) \
+{ \
+ SegmentList result; \
+ shapePtr->getExcludedIntervals(lineTop, lineHeight, result); \
+ EXPECT_EQ(1u, result.size()); \
+ EXPECT_EQ(expectedLeft, result[0].logicalLeft); \
+ EXPECT_EQ(expectedRight, result[0].logicalRight); \
+}
+
+#define TEST_NO_EXCLUDED_INTERVAL(shapePtr, lineTop, lineHeight) \
+{ \
+ SegmentList result; \
+ shapePtr->getExcludedIntervals(lineTop, lineHeight, result); \
+ EXPECT_EQ(0u, result.size()); \
+}
+
+TEST_F(BoxShapeTest, zeroRadii)
+{
+ OwnPtr<Shape> shape = createBoxShape(LayoutSize(100, 50), 10, 20);
+ EXPECT_FALSE(shape->isEmpty());
+
+ EXPECT_EQ(LayoutRect(-10, -10, 120, 70), shape->shapeMarginLogicalBoundingBox());
+ EXPECT_EQ(LayoutRect(20, 20, 60, 10), shape->shapePaddingLogicalBoundingBox());
+
+ // A BoxShape's bounds include the top edge but not the bottom edge.
+ // Similarly a "line", specified as top,height to the overlap methods,
+ // is defined as top <= y < top + height.
+
+ EXPECT_TRUE(shape->lineOverlapsShapeMarginBounds(-9, 1));
+ EXPECT_TRUE(shape->lineOverlapsShapeMarginBounds(-10, 0));
+ EXPECT_TRUE(shape->lineOverlapsShapeMarginBounds(-10, 200));
+ EXPECT_TRUE(shape->lineOverlapsShapeMarginBounds(5, 10));
+ EXPECT_TRUE(shape->lineOverlapsShapeMarginBounds(59, 1));
+
+ EXPECT_FALSE(shape->lineOverlapsShapeMarginBounds(-12, 2));
+ EXPECT_FALSE(shape->lineOverlapsShapeMarginBounds(60, 1));
+ EXPECT_FALSE(shape->lineOverlapsShapeMarginBounds(100, 200));
+
+ TEST_EXCLUDED_INTERVAL(shape, -9, 1, -10, 110);
+ TEST_EXCLUDED_INTERVAL(shape, -10, 0, -10, 110);
+ TEST_EXCLUDED_INTERVAL(shape, -10, 200, -10, 110);
+ TEST_EXCLUDED_INTERVAL(shape, 5, 10, -10, 110);
+ TEST_EXCLUDED_INTERVAL(shape, 59, 1, -10, 110);
+
+ TEST_NO_EXCLUDED_INTERVAL(shape, -12, 2);
+ TEST_NO_EXCLUDED_INTERVAL(shape, 60, 1);
+ TEST_NO_EXCLUDED_INTERVAL(shape, 100, 200);
+
+ EXPECT_TRUE(shape->lineOverlapsShapePaddingBounds(21, 1));
+ EXPECT_TRUE(shape->lineOverlapsShapePaddingBounds(20, 0));
+ EXPECT_TRUE(shape->lineOverlapsShapePaddingBounds(-10, 200));
+ EXPECT_TRUE(shape->lineOverlapsShapePaddingBounds(25, 35));
+ EXPECT_TRUE(shape->lineOverlapsShapePaddingBounds(29, 1));
+
+ EXPECT_FALSE(shape->lineOverlapsShapePaddingBounds(18, 2));
+ EXPECT_FALSE(shape->lineOverlapsShapePaddingBounds(30, 1));
+ EXPECT_FALSE(shape->lineOverlapsShapePaddingBounds(100, 200));
+}
+
+} // namespace
diff --git a/chromium/third_party/WebKit/Source/core/rendering/shapes/PolygonShape.cpp b/chromium/third_party/WebKit/Source/core/rendering/shapes/PolygonShape.cpp
index 61da7a31421..26ddcf3606b 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/shapes/PolygonShape.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/shapes/PolygonShape.cpp
@@ -30,8 +30,8 @@
#include "config.h"
#include "core/rendering/shapes/PolygonShape.h"
-#include "core/platform/graphics/LayoutPoint.h"
#include "core/rendering/shapes/ShapeInterval.h"
+#include "platform/geometry/LayoutPoint.h"
#include "wtf/MathExtras.h"
namespace WebCore {
@@ -182,7 +182,7 @@ static inline PassOwnPtr<FloatPolygon> computeShapeMarginBounds(const FloatPolyg
const FloatPolygon& PolygonShape::shapePaddingBounds() const
{
ASSERT(shapePadding() >= 0);
- if (!shapePadding())
+ if (!shapePadding() || m_polygon.isEmpty())
return m_polygon;
if (!m_paddingBounds)
@@ -194,7 +194,7 @@ const FloatPolygon& PolygonShape::shapePaddingBounds() const
const FloatPolygon& PolygonShape::shapeMarginBounds() const
{
ASSERT(shapeMargin() >= 0);
- if (!shapeMargin())
+ if (!shapeMargin() || m_polygon.isEmpty())
return m_polygon;
if (!m_marginBounds)
diff --git a/chromium/third_party/WebKit/Source/core/rendering/shapes/PolygonShape.h b/chromium/third_party/WebKit/Source/core/rendering/shapes/PolygonShape.h
index 14cd30dbb83..38b0d8e75c7 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/shapes/PolygonShape.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/shapes/PolygonShape.h
@@ -30,8 +30,8 @@
#ifndef PolygonShape_h
#define PolygonShape_h
-#include "core/platform/graphics/FloatPolygon.h"
#include "core/rendering/shapes/Shape.h"
+#include "platform/geometry/FloatPolygon.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/rendering/shapes/RasterShape.cpp b/chromium/third_party/WebKit/Source/core/rendering/shapes/RasterShape.cpp
index 55f334045a3..78b00211519 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/shapes/RasterShape.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/shapes/RasterShape.cpp
@@ -34,12 +34,64 @@
namespace WebCore {
-void RasterShapeIntervals::appendInterval(int y, int x1, int x2)
+class MarginIntervalGenerator {
+public:
+ MarginIntervalGenerator(unsigned radius);
+ void set(int y, const IntShapeInterval&);
+ IntShapeInterval intervalAt(int y) const;
+
+private:
+ Vector<int> m_xIntercepts;
+ int m_y;
+ int m_x1;
+ int m_x2;
+};
+
+MarginIntervalGenerator::MarginIntervalGenerator(unsigned radius)
+ : m_y(0)
+ , m_x1(0)
+ , m_x2(0)
{
- ASSERT(y >= 0 && y < size() && x1 >= 0 && x2 > x1 && (m_intervalLists[y].isEmpty() || x1 > m_intervalLists[y].last().x2()));
+ m_xIntercepts.resize(radius + 1);
+ unsigned radiusSquared = radius * radius;
+ for (unsigned y = 0; y <= radius; y++)
+ m_xIntercepts[y] = sqrt(static_cast<double>(radiusSquared - y * y));
+}
+
+void MarginIntervalGenerator::set(int y, const IntShapeInterval& interval)
+{
+ ASSERT(y >= 0 && interval.x1() >= 0);
+ m_y = y;
+ m_x1 = interval.x1();
+ m_x2 = interval.x2();
+}
+IntShapeInterval MarginIntervalGenerator::intervalAt(int y) const
+{
+ unsigned xInterceptsIndex = abs(y - m_y);
+ int dx = (xInterceptsIndex >= m_xIntercepts.size()) ? 0 : m_xIntercepts[xInterceptsIndex];
+ return IntShapeInterval(m_x1 - dx, m_x2 + dx);
+}
+
+void RasterShapeIntervals::appendInterval(int y, int x1, int x2)
+{
+ ASSERT(x2 > x1 && (intervalsAt(y).isEmpty() || x1 > intervalsAt(y).last().x2()));
m_bounds.unite(IntRect(x1, y, x2 - x1, 1));
- m_intervalLists[y].append(IntShapeInterval(x1, x2));
+ intervalsAt(y).append(IntShapeInterval(x1, x2));
+}
+
+void RasterShapeIntervals::uniteMarginInterval(int y, const IntShapeInterval& interval)
+{
+ ASSERT(intervalsAt(y).size() <= 1); // Each m_intervalLists entry has 0 or one interval.
+
+ if (intervalsAt(y).isEmpty()) {
+ intervalsAt(y).append(interval);
+ } else {
+ IntShapeInterval& resultInterval = intervalsAt(y)[0];
+ resultInterval.set(std::min(resultInterval.x1(), interval.x1()), std::max(resultInterval.x2(), interval.x2()));
+ }
+
+ m_bounds.unite(IntRect(interval.x1(), y, interval.width(), 1));
}
static inline bool shapeIntervalsContain(const IntShapeIntervals& intervals, const IntShapeInterval& interval)
@@ -61,7 +113,7 @@ bool RasterShapeIntervals::contains(const IntRect& rect) const
const IntShapeInterval& rectInterval = IntShapeInterval(rect.x(), rect.maxX());
for (int y = rect.y(); y < rect.maxY(); y++) {
- if (!shapeIntervalsContain(getIntervals(y), rectInterval))
+ if (!shapeIntervalsContain(intervalsAt(y), rectInterval))
return false;
}
@@ -81,14 +133,14 @@ bool RasterShapeIntervals::getIntervalX1Values(int y1, int y2, int minIntervalWi
ASSERT(y1 >= 0 && y2 > y1);
for (int y = y1; y < y2; y++) {
- if (getIntervals(y).isEmpty())
+ if (intervalsAt(y).isEmpty())
return false;
}
- appendX1Values(getIntervals(y1), minIntervalWidth, result);
+ appendX1Values(intervalsAt(y1), minIntervalWidth, result);
for (int y = y1 + 1; y < y2; y++) {
- if (getIntervals(y) != getIntervals(y - 1))
- appendX1Values(getIntervals(y), minIntervalWidth, result);
+ if (intervalsAt(y) != intervalsAt(y - 1))
+ appendX1Values(intervalsAt(y), minIntervalWidth, result);
}
return true;
@@ -134,14 +186,14 @@ void RasterShapeIntervals::getIncludedIntervals(int y1, int y2, IntShapeInterval
return;
for (int y = y1; y < y2; y++) {
- if (getIntervals(y).isEmpty())
+ if (intervalsAt(y).isEmpty())
return;
}
- result = getIntervals(y1);
+ result = intervalsAt(y1);
for (int y = y1 + 1; y < y2 && !result.isEmpty(); y++) {
IntShapeIntervals intervals;
- IntShapeInterval::intersectShapeIntervals(result, getIntervals(y), intervals);
+ IntShapeInterval::intersectShapeIntervals(result, intervalsAt(y), intervals);
result.swap(intervals);
}
}
@@ -153,27 +205,63 @@ void RasterShapeIntervals::getExcludedIntervals(int y1, int y2, IntShapeInterval
if (y2 < bounds().y() || y1 >= bounds().maxY())
return;
- for (int y = y1; y < y2; y++) {
- if (getIntervals(y).isEmpty())
- return;
- }
+ y1 = std::max(y1, bounds().y());
+ y2 = std::min(y2, bounds().maxY());
- result = getIntervals(y1);
+ result = intervalsAt(y1);
for (int y = y1 + 1; y < y2; y++) {
IntShapeIntervals intervals;
- IntShapeInterval::uniteShapeIntervals(result, getIntervals(y), intervals);
+ IntShapeInterval::uniteShapeIntervals(result, intervalsAt(y), intervals);
result.swap(intervals);
}
}
+PassOwnPtr<RasterShapeIntervals> RasterShapeIntervals::computeShapeMarginIntervals(unsigned shapeMargin) const
+{
+ OwnPtr<RasterShapeIntervals> result = adoptPtr(new RasterShapeIntervals(size(), shapeMargin));
+ MarginIntervalGenerator marginIntervalGenerator(shapeMargin);
+
+ int minY = bounds().y();
+ int maxY = bounds().maxY();
+
+ for (int y = minY; y < maxY; ++y) {
+ const IntShapeInterval& intervalAtY = limitIntervalAt(y);
+ if (intervalAtY.isEmpty())
+ continue;
+
+ marginIntervalGenerator.set(y, intervalAtY);
+ int marginY0 = y - clampToInteger(shapeMargin);
+ int marginY1 = y + clampToInteger(shapeMargin);
+
+ for (int marginY = y - 1; marginY >= marginY0; --marginY) {
+ if (marginY > minY && limitIntervalAt(marginY).contains(intervalAtY))
+ break;
+ result->uniteMarginInterval(marginY, marginIntervalGenerator.intervalAt(marginY));
+ }
+
+ result->uniteMarginInterval(y, marginIntervalGenerator.intervalAt(y));
+
+ for (int marginY = y + 1; marginY <= marginY1; ++marginY) {
+ if (marginY < maxY && limitIntervalAt(marginY).contains(intervalAtY))
+ break;
+ result->uniteMarginInterval(marginY, marginIntervalGenerator.intervalAt(marginY));
+ }
+ }
+
+ return result.release();
+}
+
const RasterShapeIntervals& RasterShape::marginIntervals() const
{
ASSERT(shapeMargin() >= 0);
if (!shapeMargin())
return *m_intervals;
- // FIXME: Add support for non-zero margin, see https://bugs.webkit.org/show_bug.cgi?id=116348.
- return *m_intervals;
+ unsigned marginBoundaryRadius = std::min(clampToUnsigned(ceil(shapeMargin())), std::max<unsigned>(m_imageSize.width(), m_imageSize.height()));
+ if (!m_marginIntervals)
+ m_marginIntervals = m_intervals->computeShapeMarginIntervals(marginBoundaryRadius);
+
+ return *m_marginIntervals;
}
const RasterShapeIntervals& RasterShape::paddingIntervals() const
diff --git a/chromium/third_party/WebKit/Source/core/rendering/shapes/RasterShape.h b/chromium/third_party/WebKit/Source/core/rendering/shapes/RasterShape.h
index 492e50d63db..903eabb0527 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/shapes/RasterShape.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/shapes/RasterShape.h
@@ -30,9 +30,9 @@
#ifndef RasterShape_h
#define RasterShape_h
-#include "core/platform/graphics/FloatRect.h"
#include "core/rendering/shapes/Shape.h"
#include "core/rendering/shapes/ShapeInterval.h"
+#include "platform/geometry/FloatRect.h"
#include "wtf/Assertions.h"
#include "wtf/Vector.h"
@@ -40,9 +40,10 @@ namespace WebCore {
class RasterShapeIntervals {
public:
- RasterShapeIntervals(unsigned size)
+ RasterShapeIntervals(unsigned size, unsigned shapeMargin = 0)
+ : m_shapeMargin(shapeMargin)
{
- m_intervalLists.resize(size);
+ m_intervalLists.resize(size + shapeMargin * 2);
}
const IntRect& bounds() const { return m_bounds; }
@@ -52,27 +53,44 @@ public:
void getIncludedIntervals(int y1, int y2, IntShapeIntervals& result) const;
void getExcludedIntervals(int y1, int y2, IntShapeIntervals& result) const;
bool firstIncludedIntervalY(int minY, const IntSize& minSize, LayoutUnit& result) const;
+ PassOwnPtr<RasterShapeIntervals> computeShapeMarginIntervals(unsigned shapeMargin) const;
private:
int size() const { return m_intervalLists.size(); }
- const IntShapeIntervals& getIntervals(int y) const
+
+ IntShapeIntervals& intervalsAt(int y)
{
- ASSERT(y >= 0 && y < size());
- return m_intervalLists[y];
+ ASSERT(y + m_shapeMargin >= 0 && y + m_shapeMargin < m_intervalLists.size());
+ return m_intervalLists[y + m_shapeMargin];
}
+
+ const IntShapeIntervals& intervalsAt(int y) const
+ {
+ ASSERT(y + m_shapeMargin >= 0 && y + m_shapeMargin < m_intervalLists.size());
+ return m_intervalLists[y + m_shapeMargin];
+ }
+
+ IntShapeInterval limitIntervalAt(int y) const
+ {
+ const IntShapeIntervals& intervals = intervalsAt(y);
+ return intervals.size() ? IntShapeInterval(intervals[0].x1(), intervals.last().x2()) : IntShapeInterval();
+ }
+
bool contains(const IntRect&) const;
bool getIntervalX1Values(int minY, int maxY, int minIntervalWidth, Vector<int>& result) const;
-
+ void uniteMarginInterval(int y, const IntShapeInterval&);
IntRect m_bounds;
- Vector<IntShapeIntervals > m_intervalLists;
+ Vector<IntShapeIntervals> m_intervalLists;
+ unsigned m_shapeMargin;
};
class RasterShape : public Shape {
WTF_MAKE_NONCOPYABLE(RasterShape);
public:
- RasterShape(PassOwnPtr<RasterShapeIntervals> intervals)
+ RasterShape(PassOwnPtr<RasterShapeIntervals> intervals, const IntSize& imageSize)
: Shape()
, m_intervals(intervals)
+ , m_imageSize(imageSize)
{
}
@@ -88,6 +106,8 @@ private:
const RasterShapeIntervals& paddingIntervals() const;
OwnPtr<RasterShapeIntervals> m_intervals;
+ mutable OwnPtr<RasterShapeIntervals> m_marginIntervals;
+ IntSize m_imageSize;
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/shapes/RectangleShape.cpp b/chromium/third_party/WebKit/Source/core/rendering/shapes/RectangleShape.cpp
index b2b26aabfe1..efe1f69831b 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/shapes/RectangleShape.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/shapes/RectangleShape.cpp
@@ -46,64 +46,36 @@ static inline float ellipseYIntercept(float x, float rx, float ry)
return ry * sqrt(1 - (x * x) / (rx * rx));
}
-FloatRoundedRect FloatRoundedRect::paddingBounds(float padding) const
+FloatRect RectangleShape::shapePaddingBounds() const
{
- ASSERT(padding >= 0);
- if (!padding || isEmpty())
- return *this;
-
- float boundsX = x() + std::min(width() / 2, padding);
- float boundsY = y() + std::min(height() / 2, padding);
- float boundsWidth = std::max(0.0f, width() - padding * 2);
- float boundsHeight = std::max(0.0f, height() - padding * 2);
- float boundsRadiusX = std::max(0.0f, rx() - padding);
- float boundsRadiusY = std::max(0.0f, ry() - padding);
- return FloatRoundedRect(FloatRect(boundsX, boundsY, boundsWidth, boundsHeight), FloatSize(boundsRadiusX, boundsRadiusY));
-}
-
-FloatRoundedRect FloatRoundedRect::marginBounds(float margin) const
-{
- ASSERT(margin >= 0);
- if (!margin)
- return *this;
-
- float boundsX = x() - margin;
- float boundsY = y() - margin;
- float boundsWidth = width() + margin * 2;
- float boundsHeight = height() + margin * 2;
- float boundsRadiusX = rx() + margin;
- float boundsRadiusY = ry() + margin;
- return FloatRoundedRect(FloatRect(boundsX, boundsY, boundsWidth, boundsHeight), FloatSize(boundsRadiusX, boundsRadiusY));
-}
+ ASSERT(shapePadding() >= 0);
+ if (!shapePadding() || isEmpty())
+ return m_bounds;
-FloatPoint FloatRoundedRect::cornerInterceptForWidth(float widthAtIntercept) const
-{
- float xi = (width() - widthAtIntercept) / 2;
- float yi = ry() - ellipseYIntercept(rx() - xi, rx(), ry());
- return FloatPoint(xi, yi);
-}
+ float boundsX = x() + std::min(width() / 2, shapePadding());
+ float boundsY = y() + std::min(height() / 2, shapePadding());
+ float boundsWidth = std::max(0.0f, width() - shapePadding() * 2);
+ float boundsHeight = std::max(0.0f, height() - shapePadding() * 2);
-FloatRoundedRect RectangleShape::shapePaddingBounds() const
-{
- if (!m_haveInitializedPaddingBounds) {
- m_haveInitializedPaddingBounds = true;
- m_paddingBounds = m_bounds.paddingBounds(shapePadding());
- }
- return m_paddingBounds;
+ return FloatRect(boundsX, boundsY, boundsWidth, boundsHeight);
}
-FloatRoundedRect RectangleShape::shapeMarginBounds() const
+FloatRect RectangleShape::shapeMarginBounds() const
{
- if (!m_haveInitializedMarginBounds) {
- m_haveInitializedMarginBounds = true;
- m_marginBounds = m_bounds.marginBounds(shapeMargin());
- }
- return m_marginBounds;
+ ASSERT(shapeMargin() >= 0);
+ if (!shapeMargin())
+ return m_bounds;
+
+ float boundsX = x() - shapeMargin();
+ float boundsY = y() - shapeMargin();
+ float boundsWidth = width() + shapeMargin() * 2;
+ float boundsHeight = height() + shapeMargin() * 2;
+ return FloatRect(boundsX, boundsY, boundsWidth, boundsHeight);
}
void RectangleShape::getExcludedIntervals(LayoutUnit logicalTop, LayoutUnit logicalHeight, SegmentList& result) const
{
- const FloatRoundedRect& bounds = shapeMarginBounds();
+ const FloatRect& bounds = shapeMarginBounds();
if (bounds.isEmpty())
return;
@@ -116,17 +88,20 @@ void RectangleShape::getExcludedIntervals(LayoutUnit logicalTop, LayoutUnit logi
float x1 = bounds.x();
float x2 = bounds.maxX();
- if (bounds.ry() > 0) {
- if (y2 < bounds.y() + bounds.ry()) {
- float yi = y2 - bounds.y() - bounds.ry();
- float xi = ellipseXIntercept(yi, bounds.rx(), bounds.ry());
- x1 = bounds.x() + bounds.rx() - xi;
- x2 = bounds.maxX() - bounds.rx() + xi;
- } else if (y1 > bounds.maxY() - bounds.ry()) {
- float yi = y1 - (bounds.maxY() - bounds.ry());
- float xi = ellipseXIntercept(yi, bounds.rx(), bounds.ry());
- x1 = bounds.x() + bounds.rx() - xi;
- x2 = bounds.maxX() - bounds.rx() + xi;
+ float marginRadiusX = rx() + shapeMargin();
+ float marginRadiusY = ry() + shapeMargin();
+
+ if (marginRadiusY > 0) {
+ if (y2 < bounds.y() + marginRadiusY) {
+ float yi = y2 - bounds.y() - marginRadiusY;
+ float xi = ellipseXIntercept(yi, marginRadiusX, marginRadiusY);
+ x1 = bounds.x() + marginRadiusX - xi;
+ x2 = bounds.maxX() - marginRadiusX + xi;
+ } else if (y1 > bounds.maxY() - marginRadiusY) {
+ float yi = y1 - (bounds.maxY() - marginRadiusY);
+ float xi = ellipseXIntercept(yi, marginRadiusX, marginRadiusY);
+ x1 = bounds.x() + marginRadiusX - xi;
+ x2 = bounds.maxX() - marginRadiusX + xi;
}
}
@@ -135,7 +110,7 @@ void RectangleShape::getExcludedIntervals(LayoutUnit logicalTop, LayoutUnit logi
void RectangleShape::getIncludedIntervals(LayoutUnit logicalTop, LayoutUnit logicalHeight, SegmentList& result) const
{
- const FloatRoundedRect& bounds = shapePaddingBounds();
+ const FloatRect& bounds = shapePaddingBounds();
if (bounds.isEmpty())
return;
@@ -148,54 +123,67 @@ void RectangleShape::getIncludedIntervals(LayoutUnit logicalTop, LayoutUnit logi
float x1 = bounds.x();
float x2 = bounds.maxX();
- if (bounds.ry() > 0) {
- bool y1InterceptsCorner = y1 < bounds.y() + bounds.ry();
- bool y2InterceptsCorner = y2 > bounds.maxY() - bounds.ry();
+ float paddingRadiusX = std::max(0.0f, rx() - shapePadding());
+ float paddingRadiusY = std::max(0.0f, ry() - shapePadding());
+
+ if (paddingRadiusX > 0) {
+ bool y1InterceptsCorner = y1 < bounds.y() + paddingRadiusY;
+ bool y2InterceptsCorner = y2 > bounds.maxY() - paddingRadiusY;
float xi = 0;
if (y1InterceptsCorner && y2InterceptsCorner) {
if (y1 < bounds.height() + 2 * bounds.y() - y2) {
- float yi = y1 - bounds.y() - bounds.ry();
- xi = ellipseXIntercept(yi, bounds.rx(), bounds.ry());
+ float yi = y1 - bounds.y() - paddingRadiusY;
+ xi = ellipseXIntercept(yi, paddingRadiusX, paddingRadiusY);
} else {
- float yi = y2 - (bounds.maxY() - bounds.ry());
- xi = ellipseXIntercept(yi, bounds.rx(), bounds.ry());
+ float yi = y2 - (bounds.maxY() - paddingRadiusY);
+ xi = ellipseXIntercept(yi, paddingRadiusX, paddingRadiusY);
}
} else if (y1InterceptsCorner) {
- float yi = y1 - bounds.y() - bounds.ry();
- xi = ellipseXIntercept(yi, bounds.rx(), bounds.ry());
+ float yi = y1 - bounds.y() - paddingRadiusY;
+ xi = ellipseXIntercept(yi, paddingRadiusX, paddingRadiusY);
} else if (y2InterceptsCorner) {
- float yi = y2 - (bounds.maxY() - bounds.ry());
- xi = ellipseXIntercept(yi, bounds.rx(), bounds.ry());
+ float yi = y2 - (bounds.maxY() - paddingRadiusY);
+ xi = ellipseXIntercept(yi, paddingRadiusX, paddingRadiusY);
}
if (y1InterceptsCorner || y2InterceptsCorner) {
- x1 = bounds.x() + bounds.rx() - xi;
- x2 = bounds.maxX() - bounds.rx() + xi;
+ x1 = bounds.x() + paddingRadiusX - xi;
+ x2 = bounds.maxX() - paddingRadiusX + xi;
}
}
result.append(LineSegment(x1, x2));
}
+static FloatPoint cornerInterceptForWidth(float width, float widthAtIntercept, float rx, float ry)
+{
+ float xi = (width - widthAtIntercept) / 2;
+ float yi = ry - ellipseYIntercept(rx - xi, rx, ry);
+ return FloatPoint(xi, yi);
+}
+
bool RectangleShape::firstIncludedIntervalLogicalTop(LayoutUnit minLogicalIntervalTop, const LayoutSize& minLogicalIntervalSize, LayoutUnit& result) const
{
float minIntervalTop = minLogicalIntervalTop;
float minIntervalHeight = minLogicalIntervalSize.height();
float minIntervalWidth = minLogicalIntervalSize.width();
- const FloatRoundedRect& bounds = shapePaddingBounds();
+ const FloatRect& bounds = shapePaddingBounds();
if (bounds.isEmpty() || minIntervalWidth > bounds.width())
return false;
- float minY = std::max(bounds.y(), minIntervalTop);
+ float minY = LayoutUnit::fromFloatCeil(std::max(bounds.y(), minIntervalTop));
float maxY = minY + minIntervalHeight;
if (maxY > bounds.maxY())
return false;
- bool intervalOverlapsMinCorner = minY < bounds.y() + bounds.ry();
- bool intervalOverlapsMaxCorner = maxY > bounds.maxY() - bounds.ry();
+ float paddingRadiusX = std::max(0.0f, rx() - shapePadding());
+ float paddingRadiusY = std::max(0.0f, ry() - shapePadding());
+
+ bool intervalOverlapsMinCorner = minY < bounds.y() + paddingRadiusY;
+ bool intervalOverlapsMaxCorner = maxY > bounds.maxY() - paddingRadiusY;
if (!intervalOverlapsMinCorner && !intervalOverlapsMaxCorner) {
result = minY;
@@ -204,8 +192,8 @@ bool RectangleShape::firstIncludedIntervalLogicalTop(LayoutUnit minLogicalInterv
float centerY = bounds.y() + bounds.height() / 2;
bool minCornerDefinesX = fabs(centerY - minY) > fabs(centerY - maxY);
- bool intervalFitsWithinCorners = minIntervalWidth + 2 * bounds.rx() <= bounds.width();
- FloatPoint cornerIntercept = bounds.cornerInterceptForWidth(minIntervalWidth);
+ bool intervalFitsWithinCorners = minIntervalWidth + 2 * paddingRadiusX <= bounds.width();
+ FloatPoint cornerIntercept = cornerInterceptForWidth(bounds.width(), minIntervalWidth, paddingRadiusX, paddingRadiusY);
if (intervalOverlapsMinCorner && (!intervalOverlapsMaxCorner || minCornerDefinesX)) {
if (intervalFitsWithinCorners || bounds.y() + cornerIntercept.y() < minY) {
diff --git a/chromium/third_party/WebKit/Source/core/rendering/shapes/RectangleShape.h b/chromium/third_party/WebKit/Source/core/rendering/shapes/RectangleShape.h
index cd512d11b07..9a9dae5522e 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/shapes/RectangleShape.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/shapes/RectangleShape.h
@@ -30,41 +30,21 @@
#ifndef RectangleShape_h
#define RectangleShape_h
-#include "core/platform/graphics/FloatPoint.h"
-#include "core/platform/graphics/FloatRect.h"
-#include "core/platform/graphics/FloatSize.h"
#include "core/rendering/shapes/Shape.h"
+#include "platform/geometry/FloatPoint.h"
+#include "platform/geometry/FloatRect.h"
+#include "platform/geometry/FloatSize.h"
#include "wtf/Assertions.h"
#include "wtf/Vector.h"
namespace WebCore {
-class FloatRoundedRect : public FloatRect {
-public:
- FloatRoundedRect() { }
- FloatRoundedRect(const FloatRect& bounds, const FloatSize& radii)
- : FloatRect(bounds)
- , m_radii(radii)
- {
- }
-
- float rx() const { return m_radii.width(); }
- float ry() const { return m_radii.height(); }
- FloatRoundedRect marginBounds(float margin) const;
- FloatRoundedRect paddingBounds(float padding) const;
- FloatPoint cornerInterceptForWidth(float width) const;
-
-private:
- FloatSize m_radii;
-};
-
class RectangleShape : public Shape {
public:
RectangleShape(const FloatRect& bounds, const FloatSize& radii)
: Shape()
- , m_bounds(bounds, radii)
- , m_haveInitializedMarginBounds(false)
- , m_haveInitializedPaddingBounds(false)
+ , m_bounds(bounds)
+ , m_radii(radii)
{
}
@@ -76,14 +56,18 @@ public:
virtual bool firstIncludedIntervalLogicalTop(LayoutUnit minLogicalIntervalTop, const LayoutSize& minLogicalIntervalSize, LayoutUnit&) const OVERRIDE;
private:
- FloatRoundedRect shapeMarginBounds() const;
- FloatRoundedRect shapePaddingBounds() const;
+ FloatRect shapeMarginBounds() const;
+ FloatRect shapePaddingBounds() const;
- FloatRoundedRect m_bounds;
- mutable FloatRoundedRect m_marginBounds;
- mutable FloatRoundedRect m_paddingBounds;
- mutable bool m_haveInitializedMarginBounds : 1;
- mutable bool m_haveInitializedPaddingBounds : 1;
+ float rx() const { return m_radii.width(); }
+ float ry() const { return m_radii.height(); }
+ float x() const { return m_bounds.x(); }
+ float y() const { return m_bounds.y(); }
+ float width() const { return m_bounds.width(); }
+ float height() const { return m_bounds.height(); }
+
+ FloatRect m_bounds;
+ FloatSize m_radii;
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/shapes/Shape.cpp b/chromium/third_party/WebKit/Source/core/rendering/shapes/Shape.cpp
index 0d660ae16a1..ffe05053133 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/shapes/Shape.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/shapes/Shape.cpp
@@ -30,20 +30,27 @@
#include "config.h"
#include "core/rendering/shapes/Shape.h"
-#include "core/css/LengthFunctions.h"
#include "core/fetch/ImageResource.h"
-#include "core/platform/graphics/FloatSize.h"
-#include "core/platform/graphics/ImageBuffer.h"
-#include "core/platform/graphics/WindRule.h"
+#include "core/rendering/shapes/BoxShape.h"
#include "core/rendering/shapes/PolygonShape.h"
#include "core/rendering/shapes/RasterShape.h"
#include "core/rendering/shapes/RectangleShape.h"
+#include "platform/LengthFunctions.h"
+#include "platform/geometry/FloatRoundedRect.h"
+#include "platform/geometry/FloatSize.h"
+#include "platform/graphics/ImageBuffer.h"
+#include "platform/graphics/WindRule.h"
#include "wtf/MathExtras.h"
#include "wtf/OwnPtr.h"
-#include "wtf/PassOwnPtr.h"
namespace WebCore {
+static PassOwnPtr<Shape> createBoxShape(const FloatRoundedRect& bounds)
+{
+ ASSERT(bounds.rect().width() >= 0 && bounds.rect().height() >= 0);
+ return adoptPtr(new BoxShape(bounds));
+}
+
static PassOwnPtr<Shape> createRectangleShape(const FloatRect& bounds, const FloatSize& radii)
{
ASSERT(bounds.width() >= 0 && bounds.height() >= 0 && radii.width() >= 0 && radii.height() >= 0);
@@ -135,7 +142,11 @@ PassOwnPtr<Shape> Shape::createShape(const BasicShape* basicShape, const LayoutS
const BasicShapeCircle* circle = static_cast<const BasicShapeCircle*>(basicShape);
float centerX = floatValueForLength(circle->centerX(), boxWidth);
float centerY = floatValueForLength(circle->centerY(), boxHeight);
- float radius = floatValueForLength(circle->radius(), std::min(boxHeight, boxWidth));
+ // This method of computing the radius is as defined in SVG
+ // (http://www.w3.org/TR/SVG/coords.html#Units). It bases the radius
+ // off of the diagonal of the box and ensures that if the box is
+ // square, the radius is equal to half the diagonal.
+ float radius = floatValueForLength(circle->radius(), sqrtf((boxWidth * boxWidth + boxHeight * boxHeight) / 2));
FloatPoint logicalCenter = physicalPointToLogical(FloatPoint(centerX, centerY), logicalBoxSize.height(), writingMode);
shape = createCircleShape(logicalCenter, radius);
@@ -207,10 +218,8 @@ PassOwnPtr<Shape> Shape::createShape(const StyleImage* styleImage, float thresho
Image* image = styleImage->cachedImage()->image();
const IntSize& imageSize = image->size();
- OwnPtr<ImageBuffer> imageBuffer = ImageBuffer::create(imageSize);
-
OwnPtr<RasterShapeIntervals> intervals = adoptPtr(new RasterShapeIntervals(imageSize.height()));
-
+ OwnPtr<ImageBuffer> imageBuffer = ImageBuffer::create(imageSize);
if (imageBuffer) {
GraphicsContext* graphicsContext = imageBuffer->context();
graphicsContext->drawImage(image, IntPoint());
@@ -236,11 +245,24 @@ PassOwnPtr<Shape> Shape::createShape(const StyleImage* styleImage, float thresho
}
}
- OwnPtr<RasterShape> rasterShape = adoptPtr(new RasterShape(intervals.release()));
+ OwnPtr<RasterShape> rasterShape = adoptPtr(new RasterShape(intervals.release(), imageSize));
rasterShape->m_writingMode = writingMode;
rasterShape->m_margin = floatValueForLength(margin, 0);
rasterShape->m_padding = floatValueForLength(padding, 0);
return rasterShape.release();
}
+PassOwnPtr<Shape> Shape::createLayoutBoxShape(const LayoutSize& logicalSize, WritingMode writingMode, const Length& margin, const Length& padding)
+{
+ FloatRect rect(0, 0, logicalSize.width(), logicalSize.height());
+ FloatSize radii(0, 0);
+ FloatRoundedRect bounds(rect, radii, radii, radii, radii);
+ OwnPtr<Shape> shape = createBoxShape(bounds);
+ shape->m_writingMode = writingMode;
+ shape->m_margin = floatValueForLength(margin, 0);
+ shape->m_padding = floatValueForLength(padding, 0);
+
+ return shape.release();
+}
+
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/shapes/Shape.h b/chromium/third_party/WebKit/Source/core/rendering/shapes/Shape.h
index b1ea954b3fd..de9aef9f99d 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/shapes/Shape.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/shapes/Shape.h
@@ -30,10 +30,10 @@
#ifndef Shape_h
#define Shape_h
-#include "core/platform/graphics/LayoutRect.h"
-#include "core/platform/text/WritingMode.h"
#include "core/rendering/style/BasicShapes.h"
#include "core/rendering/style/StyleImage.h"
+#include "platform/geometry/LayoutRect.h"
+#include "platform/text/WritingMode.h"
#include "wtf/PassOwnPtr.h"
#include "wtf/Vector.h"
@@ -62,6 +62,7 @@ class Shape {
public:
static PassOwnPtr<Shape> createShape(const BasicShape*, const LayoutSize& logicalBoxSize, WritingMode, Length margin, Length padding);
static PassOwnPtr<Shape> createShape(const StyleImage*, float threshold, const LayoutSize& logicalBoxSize, WritingMode, Length margin, Length padding);
+ static PassOwnPtr<Shape> createLayoutBoxShape(const LayoutSize& logicalBoxSize, WritingMode, const Length& margin, const Length& padding);
virtual ~Shape() { }
@@ -71,12 +72,21 @@ public:
virtual void getIncludedIntervals(LayoutUnit logicalTop, LayoutUnit logicalHeight, SegmentList&) const = 0;
virtual void getExcludedIntervals(LayoutUnit logicalTop, LayoutUnit logicalHeight, SegmentList&) const = 0;
virtual bool firstIncludedIntervalLogicalTop(LayoutUnit minLogicalIntervalTop, const LayoutSize& minLogicalIntervalSize, LayoutUnit& result) const = 0;
+ bool lineOverlapsShapeMarginBounds(LayoutUnit lineTop, LayoutUnit lineHeight) const { return lineOverlapsBoundingBox(lineTop, lineHeight, shapeMarginLogicalBoundingBox()); }
+ bool lineOverlapsShapePaddingBounds(LayoutUnit lineTop, LayoutUnit lineHeight) const { return lineOverlapsBoundingBox(lineTop, lineHeight, shapePaddingLogicalBoundingBox()); }
protected:
float shapeMargin() const { return m_margin; }
float shapePadding() const { return m_padding; }
private:
+ bool lineOverlapsBoundingBox(LayoutUnit lineTop, LayoutUnit lineHeight, const LayoutRect& rect) const
+ {
+ if (rect.isEmpty())
+ return false;
+ return (lineTop < rect.maxY() && lineTop + lineHeight > rect.y()) || (!lineHeight && lineTop == rect.y());
+ }
+
WritingMode m_writingMode;
float m_margin;
float m_padding;
diff --git a/chromium/third_party/WebKit/Source/core/rendering/shapes/ShapeInfo.cpp b/chromium/third_party/WebKit/Source/core/rendering/shapes/ShapeInfo.cpp
index 47699d26c66..e2668712991 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/shapes/ShapeInfo.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/shapes/ShapeInfo.cpp
@@ -31,10 +31,21 @@
#include "core/rendering/shapes/ShapeInfo.h"
#include "core/rendering/RenderRegion.h"
-#include "core/rendering/shapes/Shape.h"
-#include "core/rendering/style/RenderStyle.h"
namespace WebCore {
+
+bool checkShapeImageOrigin(Document& document, ImageResource& imageResource)
+{
+ if (imageResource.isAccessAllowed(document.securityOrigin()))
+ return true;
+
+ const KURL& url = imageResource.url();
+ String urlString = url.isNull() ? "''" : url.elidedString();
+ document.addConsoleMessage(SecurityMessageSource, ErrorMessageLevel, "Unsafe attempt to load URL " + urlString + ".");
+
+ return false;
+}
+
template<class RenderType>
const Shape* ShapeInfo<RenderType>::computedShape() const
{
@@ -44,6 +55,7 @@ const Shape* ShapeInfo<RenderType>::computedShape() const
WritingMode writingMode = m_renderer->style()->writingMode();
Length margin = m_renderer->style()->shapeMargin();
Length padding = m_renderer->style()->shapePadding();
+ float shapeImageThreshold = m_renderer->style()->shapeImageThreshold();
const ShapeValue* shapeValue = this->shapeValue();
ASSERT(shapeValue);
@@ -54,9 +66,13 @@ const Shape* ShapeInfo<RenderType>::computedShape() const
break;
case ShapeValue::Image:
ASSERT(shapeValue->image());
- m_shape = Shape::createShape(shapeValue->image(), 0, m_shapeLogicalSize, writingMode, margin, padding);
+ m_shape = Shape::createShape(shapeValue->image(), shapeImageThreshold, m_shapeLogicalSize, writingMode, margin, padding);
+ break;
+ case ShapeValue::Box:
+ m_shape = Shape::createLayoutBoxShape(m_shapeLogicalSize, writingMode, margin, padding);
break;
- default:
+ case ShapeValue::Outside:
+ // Outside should have already resolved to a different shape value.
ASSERT_NOT_REACHED();
}
@@ -65,23 +81,19 @@ const Shape* ShapeInfo<RenderType>::computedShape() const
}
template<class RenderType>
-bool ShapeInfo<RenderType>::computeSegmentsForLine(LayoutUnit lineTop, LayoutUnit lineHeight)
+SegmentList ShapeInfo<RenderType>::computeSegmentsForLine(LayoutUnit lineTop, LayoutUnit lineHeight) const
{
ASSERT(lineHeight >= 0);
- m_shapeLineTop = lineTop - logicalTopOffset();
- m_lineHeight = lineHeight;
- m_segments.clear();
+ SegmentList segments;
- if (lineOverlapsShapeBounds())
- getIntervals(m_shapeLineTop, std::min(m_lineHeight, shapeLogicalBottom() - lineTop), m_segments);
+ getIntervals((lineTop - logicalTopOffset()), std::min(lineHeight, shapeLogicalBottom() - lineTop), segments);
- LayoutUnit logicalLeftOffset = this->logicalLeftOffset();
- for (size_t i = 0; i < m_segments.size(); i++) {
- m_segments[i].logicalLeft += logicalLeftOffset;
- m_segments[i].logicalRight += logicalLeftOffset;
+ for (size_t i = 0; i < segments.size(); i++) {
+ segments[i].logicalLeft += logicalLeftOffset();
+ segments[i].logicalRight += logicalLeftOffset();
}
- return m_segments.size();
+ return segments;
}
template class ShapeInfo<RenderBlock>;
diff --git a/chromium/third_party/WebKit/Source/core/rendering/shapes/ShapeInfo.h b/chromium/third_party/WebKit/Source/core/rendering/shapes/ShapeInfo.h
index 3468ccccadb..1314f3409c1 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/shapes/ShapeInfo.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/shapes/ShapeInfo.h
@@ -30,11 +30,11 @@
#ifndef ShapeInfo_h
#define ShapeInfo_h
-#include "core/platform/LayoutUnit.h"
-#include "core/platform/graphics/FloatRect.h"
#include "core/rendering/shapes/Shape.h"
#include "core/rendering/style/RenderStyle.h"
#include "core/rendering/style/ShapeValue.h"
+#include "platform/LayoutUnit.h"
+#include "platform/geometry/FloatRect.h"
#include "wtf/OwnPtr.h"
#include "wtf/Vector.h"
@@ -70,19 +70,36 @@ public:
void setShapeSize(LayoutUnit logicalWidth, LayoutUnit logicalHeight)
{
- LayoutSize newLogicalSize(logicalWidth, logicalHeight);
-
- if (m_renderer->style()->boxSizing() == CONTENT_BOX)
- newLogicalSize -= LayoutSize(m_renderer->borderAndPaddingLogicalWidth(), m_renderer->borderAndPaddingLogicalHeight());
+ if (shapeValue()->type() == ShapeValue::Box) {
+ switch (shapeValue()->layoutBox()) {
+ case MarginBox:
+ logicalHeight += m_renderer->marginLogicalHeight();
+ logicalWidth += m_renderer->marginLogicalWidth();
+ break;
+ case BorderBox:
+ break;
+ case PaddingBox:
+ logicalHeight -= m_renderer->borderLogicalHeight();
+ logicalWidth -= m_renderer->borderLogicalWidth();
+ break;
+ case ContentBox:
+ logicalHeight -= m_renderer->borderAndPaddingLogicalHeight();
+ logicalWidth -= m_renderer->borderAndPaddingLogicalWidth();
+ break;
+ }
+ } else if (m_renderer->style()->boxSizing() == CONTENT_BOX) {
+ logicalHeight -= m_renderer->borderAndPaddingLogicalHeight();
+ logicalWidth -= m_renderer->borderAndPaddingLogicalWidth();
+ }
+ LayoutSize newLogicalSize(logicalWidth, logicalHeight);
if (m_shapeLogicalSize == newLogicalSize)
return;
dirtyShapeSize();
m_shapeLogicalSize = newLogicalSize;
}
- virtual bool computeSegmentsForLine(LayoutUnit lineTop, LayoutUnit lineHeight);
- void clearSegments() { m_segments.clear(); }
+ SegmentList computeSegmentsForLine(LayoutUnit lineTop, LayoutUnit lineHeight) const;
LayoutUnit shapeLogicalTop() const { return computedShapeLogicalBoundingBox().y() + logicalTopOffset(); }
LayoutUnit shapeLogicalBottom() const { return computedShapeLogicalBoundingBox().maxY() + logicalTopOffset(); }
@@ -101,21 +118,53 @@ public:
void dirtyShapeSize() { m_shape.clear(); }
bool shapeSizeDirty() { return !m_shape.get(); }
const RenderType* owner() const { return m_renderer; }
+ LayoutSize shapeSize() const { return m_shapeLogicalSize; }
protected:
ShapeInfo(const RenderType* renderer): m_renderer(renderer) { }
const Shape* computedShape() const;
+
virtual LayoutRect computedShapeLogicalBoundingBox() const = 0;
virtual ShapeValue* shapeValue() const = 0;
virtual void getIntervals(LayoutUnit, LayoutUnit, SegmentList&) const = 0;
- LayoutUnit logicalTopOffset() const { return m_renderer->style()->boxSizing() == CONTENT_BOX ? m_renderer->borderAndPaddingBefore() : LayoutUnit(); }
- LayoutUnit logicalLeftOffset() const { return (m_renderer->style()->boxSizing() == CONTENT_BOX && !m_renderer->isRenderRegion()) ? m_renderer->borderAndPaddingStart() : LayoutUnit(); }
+ LayoutUnit logicalTopOffset() const
+ {
+ if (shapeValue()->type() == ShapeValue::Box) {
+ switch (shapeValue()->layoutBox()) {
+ case MarginBox:
+ return -m_renderer->marginBefore();
+ case BorderBox:
+ return LayoutUnit();
+ case PaddingBox:
+ return m_renderer->borderBefore();
+ case ContentBox:
+ return m_renderer->borderAndPaddingBefore();
+ }
+ }
+ return m_renderer->style()->boxSizing() == CONTENT_BOX ? m_renderer->borderAndPaddingBefore() : LayoutUnit();
+ }
+
+ LayoutUnit logicalLeftOffset() const
+ {
+ if (shapeValue()->type() == ShapeValue::Box) {
+ switch (shapeValue()->layoutBox()) {
+ case MarginBox:
+ return -m_renderer->marginStart();
+ case BorderBox:
+ return LayoutUnit();
+ case PaddingBox:
+ return m_renderer->borderStart();
+ case ContentBox:
+ return m_renderer->borderAndPaddingStart();
+ }
+ }
+ return (m_renderer->style()->boxSizing() == CONTENT_BOX && !m_renderer->isRenderRegion()) ? m_renderer->borderAndPaddingStart() : LayoutUnit();
+ }
LayoutUnit m_shapeLineTop;
LayoutUnit m_lineHeight;
- SegmentList m_segments;
const RenderType* m_renderer;
@@ -123,5 +172,8 @@ private:
mutable OwnPtr<Shape> m_shape;
LayoutSize m_shapeLogicalSize;
};
+
+bool checkShapeImageOrigin(Document&, ImageResource&);
+
}
#endif
diff --git a/chromium/third_party/WebKit/Source/core/rendering/shapes/ShapeInsideInfo.cpp b/chromium/third_party/WebKit/Source/core/rendering/shapes/ShapeInsideInfo.cpp
index c6e004d649c..301200b19e7 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/shapes/ShapeInsideInfo.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/shapes/ShapeInsideInfo.cpp
@@ -51,7 +51,8 @@ bool ShapeInsideInfo::isEnabledFor(const RenderBlock* renderer)
case ShapeValue::Shape:
return shapeValue->shape() && shapeValue->shape()->type() != BasicShape::BasicShapeInsetRectangleType;
case ShapeValue::Image:
- return shapeValue->isImageValid();
+ return shapeValue->isImageValid() && checkShapeImageOrigin(renderer->document(), *(shapeValue->image()->cachedImage()));
+ case ShapeValue::Box:
case ShapeValue::Outside:
return false;
}
@@ -59,6 +60,30 @@ bool ShapeInsideInfo::isEnabledFor(const RenderBlock* renderer)
return false;
}
+bool ShapeInsideInfo::updateSegmentsForLine(LayoutSize lineOffset, LayoutUnit lineHeight)
+{
+ bool result = updateSegmentsForLine(lineOffset.height(), lineHeight);
+ for (size_t i = 0; i < m_segments.size(); i++) {
+ m_segments[i].logicalLeft -= lineOffset.width();
+ m_segments[i].logicalRight -= lineOffset.width();
+ }
+ return result;
+}
+
+bool ShapeInsideInfo::updateSegmentsForLine(LayoutUnit lineTop, LayoutUnit lineHeight)
+{
+ ASSERT(lineHeight >= 0);
+ m_shapeLineTop = lineTop - logicalTopOffset();
+ m_lineHeight = lineHeight;
+ m_segments.clear();
+ m_segmentRanges.clear();
+
+ if (lineOverlapsShapeBounds())
+ m_segments = computeSegmentsForLine(lineTop, lineHeight);
+
+ return m_segments.size();
+}
+
bool ShapeInsideInfo::adjustLogicalLineTop(float minSegmentWidth)
{
const Shape* shape = computedShape();
@@ -81,4 +106,16 @@ ShapeValue* ShapeInsideInfo::shapeValue() const
return m_renderer->style()->resolvedShapeInside();
}
+LayoutUnit ShapeInsideInfo::computeFirstFitPositionForFloat(const LayoutSize floatSize) const
+{
+ if (!computedShape() || !floatSize.width() || shapeLogicalBottom() < logicalLineTop())
+ return 0;
+
+ LayoutUnit firstFitPosition = 0;
+ if (computedShape()->firstIncludedIntervalLogicalTop(m_shapeLineTop, floatSize, firstFitPosition) && (m_shapeLineTop <= firstFitPosition))
+ return firstFitPosition;
+
+ return 0;
+}
+
}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/shapes/ShapeInsideInfo.h b/chromium/third_party/WebKit/Source/core/rendering/shapes/ShapeInsideInfo.h
index a18af4c0a90..0f0f3855266 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/shapes/ShapeInsideInfo.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/shapes/ShapeInsideInfo.h
@@ -66,21 +66,8 @@ public:
static bool isEnabledFor(const RenderBlock* renderer);
- bool computeSegmentsForLine(LayoutSize lineOffset, LayoutUnit lineHeight)
- {
- bool result = computeSegmentsForLine(lineOffset.height(), lineHeight);
- for (size_t i = 0; i < m_segments.size(); i++) {
- m_segments[i].logicalLeft -= lineOffset.width();
- m_segments[i].logicalRight -= lineOffset.width();
- }
- return result;
- }
-
- virtual bool computeSegmentsForLine(LayoutUnit lineTop, LayoutUnit lineHeight) OVERRIDE
- {
- m_segmentRanges.clear();
- return ShapeInfo<RenderBlock>::computeSegmentsForLine(lineTop, lineHeight);
- }
+ bool updateSegmentsForLine(LayoutSize lineOffset, LayoutUnit lineHeight);
+ bool updateSegmentsForLine(LayoutUnit lineTop, LayoutUnit lineHeight);
bool hasSegments() const
{
@@ -100,15 +87,16 @@ public:
ASSERT(m_segmentRanges.size() < m_segments.size());
return &m_segments[m_segmentRanges.size()];
}
+ void clearSegments() { m_segments.clear(); }
bool adjustLogicalLineTop(float minSegmentWidth);
+ LayoutUnit computeFirstFitPositionForFloat(const LayoutSize) const;
void setNeedsLayout(bool value) { m_needsLayout = value; }
bool needsLayout() { return m_needsLayout; }
virtual bool lineOverlapsShapeBounds() const OVERRIDE
{
- // The <= test is to handle the case of a zero height line or a zero height shape.
- return logicalLineTop() < shapeLogicalBottom() && shapeLogicalTop() <= logicalLineBottom();
+ return computedShape()->lineOverlapsShapePaddingBounds(m_shapeLineTop, m_lineHeight);
}
protected:
@@ -127,6 +115,7 @@ private:
SegmentRangeList m_segmentRanges;
bool m_needsLayout;
+ SegmentList m_segments;
};
}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/shapes/ShapeInterval.h b/chromium/third_party/WebKit/Source/core/rendering/shapes/ShapeInterval.h
index a3c1322e63e..efeb7d862c0 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/shapes/ShapeInterval.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/shapes/ShapeInterval.h
@@ -48,6 +48,7 @@ public:
T x1() const { return m_x1; }
T x2() const { return m_x2; }
T width() const { return m_x2 - m_x1; }
+ bool isEmpty() const { return m_x1 == m_x2; }
void setX1(T x1)
{
diff --git a/chromium/third_party/WebKit/Source/core/rendering/shapes/ShapeOutsideInfo.cpp b/chromium/third_party/WebKit/Source/core/rendering/shapes/ShapeOutsideInfo.cpp
index 2cff8f8c86d..98bea9a0a16 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/shapes/ShapeOutsideInfo.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/shapes/ShapeOutsideInfo.cpp
@@ -31,7 +31,7 @@
#include "core/rendering/shapes/ShapeOutsideInfo.h"
#include "core/rendering/FloatingObjects.h"
-#include "core/rendering/RenderBlock.h"
+#include "core/rendering/RenderBlockFlow.h"
#include "core/rendering/RenderBox.h"
namespace WebCore {
@@ -45,7 +45,9 @@ bool ShapeOutsideInfo::isEnabledFor(const RenderBox* box)
case ShapeValue::Shape:
return shapeValue->shape();
case ShapeValue::Image:
- return shapeValue->isImageValid();
+ return shapeValue->isImageValid() && checkShapeImageOrigin(box->document(), *(shapeValue->image()->cachedImage()));
+ case ShapeValue::Box:
+ return true;
case ShapeValue::Outside:
return false;
}
@@ -53,27 +55,41 @@ bool ShapeOutsideInfo::isEnabledFor(const RenderBox* box)
return false;
}
-bool ShapeOutsideInfo::computeSegmentsForContainingBlockLine(const RenderBlock* containingBlock, const FloatingObject* floatingObject, LayoutUnit lineTop, LayoutUnit lineHeight)
+void ShapeOutsideInfo::updateDeltasForContainingBlockLine(const RenderBlockFlow* containingBlock, const FloatingObject* floatingObject, LayoutUnit lineTop, LayoutUnit lineHeight)
{
- LayoutUnit shapeTop = floatingObject->logicalTop(containingBlock->isHorizontalWritingMode()) + std::max(LayoutUnit(), containingBlock->marginBeforeForChild(m_renderer));
- LayoutUnit lineTopInShapeCoordinates = lineTop - shapeTop + logicalTopOffset();
- return computeSegmentsForLine(lineTopInShapeCoordinates, lineHeight);
-}
+ LayoutUnit shapeTop = containingBlock->logicalTopForFloat(floatingObject) + std::max(LayoutUnit(), containingBlock->marginBeforeForChild(m_renderer));
+ LayoutUnit floatRelativeLineTop = lineTop - shapeTop;
-bool ShapeOutsideInfo::computeSegmentsForLine(LayoutUnit lineTop, LayoutUnit lineHeight)
-{
- if (shapeSizeDirty() || m_lineTop != lineTop || m_lineHeight != lineHeight) {
- if (ShapeInfo<RenderBox>::computeSegmentsForLine(lineTop, lineHeight)) {
- m_leftSegmentMarginBoxDelta = m_segments[0].logicalLeft + m_renderer->marginStart();
- m_rightSegmentMarginBoxDelta = m_segments[m_segments.size()-1].logicalRight - m_renderer->logicalWidth() - m_renderer->marginEnd();
- } else {
- m_leftSegmentMarginBoxDelta = m_renderer->logicalWidth() + m_renderer->marginStart();
- m_rightSegmentMarginBoxDelta = -m_renderer->logicalWidth() - m_renderer->marginEnd();
+ if (shapeSizeDirty() || m_lineTop != floatRelativeLineTop || m_lineHeight != lineHeight) {
+ m_lineTop = floatRelativeLineTop;
+ m_shapeLineTop = floatRelativeLineTop - logicalTopOffset();
+ m_lineHeight = lineHeight;
+
+ LayoutUnit floatMarginBoxWidth = containingBlock->logicalWidthForFloat(floatingObject);
+
+ if (lineOverlapsShapeBounds()) {
+ SegmentList segments = computeSegmentsForLine(floatRelativeLineTop, lineHeight);
+ if (segments.size()) {
+ LayoutUnit rawLeftMarginBoxDelta = segments.first().logicalLeft + containingBlock->marginStartForChild(m_renderer);
+ m_leftMarginBoxDelta = clampTo<LayoutUnit>(rawLeftMarginBoxDelta, LayoutUnit(), floatMarginBoxWidth);
+
+ LayoutUnit rawRightMarginBoxDelta = segments.last().logicalRight - containingBlock->logicalWidthForChild(m_renderer) - containingBlock->marginEndForChild(m_renderer);
+ m_rightMarginBoxDelta = clampTo<LayoutUnit>(rawRightMarginBoxDelta, -floatMarginBoxWidth, LayoutUnit());
+ return;
+ }
}
- m_lineTop = lineTop;
- }
- return m_segments.size();
+ // Lines that do not overlap the shape should act as if the float
+ // wasn't there for layout purposes. So we set the deltas to remove the
+ // entire width of the float.
+ // FIXME: The latest CSS Shapes spec says that in this case, the
+ // content should interact with previously stacked floats on the line
+ // as if this outermost float did not exist. Perhaps obviously, this
+ // solution cannot do that, and will be revisted when that part of the
+ // spec is implemented.
+ m_leftMarginBoxDelta = floatMarginBoxWidth;
+ m_rightMarginBoxDelta = -floatMarginBoxWidth;
+ }
}
ShapeValue* ShapeOutsideInfo::shapeValue() const
diff --git a/chromium/third_party/WebKit/Source/core/rendering/shapes/ShapeOutsideInfo.h b/chromium/third_party/WebKit/Source/core/rendering/shapes/ShapeOutsideInfo.h
index d5f50fca975..82b31f65f69 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/shapes/ShapeOutsideInfo.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/shapes/ShapeOutsideInfo.h
@@ -30,30 +30,28 @@
#ifndef ShapeOutsideInfo_h
#define ShapeOutsideInfo_h
-#include "core/platform/graphics/LayoutSize.h"
#include "core/rendering/shapes/ShapeInfo.h"
+#include "platform/geometry/LayoutSize.h"
namespace WebCore {
-class RenderBlock;
+class RenderBlockFlow;
class RenderBox;
class FloatingObject;
class ShapeOutsideInfo FINAL : public ShapeInfo<RenderBox>, public MappedInfo<RenderBox, ShapeOutsideInfo> {
public:
- LayoutUnit leftSegmentMarginBoxDelta() const { return m_leftSegmentMarginBoxDelta; }
- LayoutUnit rightSegmentMarginBoxDelta() const { return m_rightSegmentMarginBoxDelta; }
+ LayoutUnit leftMarginBoxDelta() const { return m_leftMarginBoxDelta; }
+ LayoutUnit rightMarginBoxDelta() const { return m_rightMarginBoxDelta; }
- bool computeSegmentsForContainingBlockLine(const RenderBlock*, const FloatingObject*, LayoutUnit lineTop, LayoutUnit lineHeight);
- virtual bool computeSegmentsForLine(LayoutUnit lineTop, LayoutUnit lineHeight) OVERRIDE;
+ void updateDeltasForContainingBlockLine(const RenderBlockFlow*, const FloatingObject*, LayoutUnit lineTop, LayoutUnit lineHeight);
static PassOwnPtr<ShapeOutsideInfo> createInfo(const RenderBox* renderer) { return adoptPtr(new ShapeOutsideInfo(renderer)); }
static bool isEnabledFor(const RenderBox*);
virtual bool lineOverlapsShapeBounds() const OVERRIDE
{
- return (logicalLineTop() < shapeLogicalBottom() && shapeLogicalTop() < logicalLineBottom())
- || logicalLineTop() == shapeLogicalTop(); // case of zero height line or zero height shape
+ return computedShape()->lineOverlapsShapeMarginBounds(m_shapeLineTop, m_lineHeight);
}
protected:
@@ -67,8 +65,8 @@ protected:
private:
ShapeOutsideInfo(const RenderBox* renderer) : ShapeInfo<RenderBox>(renderer) { }
- LayoutUnit m_leftSegmentMarginBoxDelta;
- LayoutUnit m_rightSegmentMarginBoxDelta;
+ LayoutUnit m_leftMarginBoxDelta;
+ LayoutUnit m_rightMarginBoxDelta;
LayoutUnit m_lineTop;
};
diff --git a/chromium/third_party/WebKit/Source/core/rendering/style/BasicShapes.cpp b/chromium/third_party/WebKit/Source/core/rendering/style/BasicShapes.cpp
index 559bfe65d7c..1eed605f291 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/style/BasicShapes.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/style/BasicShapes.cpp
@@ -29,10 +29,10 @@
#include "config.h"
-#include "core/css/LengthFunctions.h"
-#include "core/platform/graphics/FloatRect.h"
-#include "core/platform/graphics/Path.h"
#include "core/rendering/style/BasicShapes.h"
+#include "platform/LengthFunctions.h"
+#include "platform/geometry/FloatRect.h"
+#include "platform/graphics/Path.h"
namespace WebCore {
@@ -73,12 +73,12 @@ PassRefPtr<BasicShape> BasicShapeRectangle::blend(const BasicShape* other, doubl
const BasicShapeRectangle* o = static_cast<const BasicShapeRectangle*>(other);
RefPtr<BasicShapeRectangle> result = BasicShapeRectangle::create();
- result->setX(m_x.blend(o->x(), progress));
- result->setY(m_y.blend(o->y(), progress));
- result->setWidth(m_width.blend(o->width(), progress));
- result->setHeight(m_height.blend(o->height(), progress));
- result->setCornerRadiusX(m_cornerRadiusX.blend(o->cornerRadiusX(), progress));
- result->setCornerRadiusY(m_cornerRadiusY.blend(o->cornerRadiusY(), progress));
+ result->setX(m_x.blend(o->x(), progress, ValueRangeAll));
+ result->setY(m_y.blend(o->y(), progress, ValueRangeAll));
+ result->setWidth(m_width.blend(o->width(), progress, ValueRangeNonNegative));
+ result->setHeight(m_height.blend(o->height(), progress, ValueRangeNonNegative));
+ result->setCornerRadiusX(m_cornerRadiusX.blend(o->cornerRadiusX(), progress, ValueRangeNonNegative));
+ result->setCornerRadiusY(m_cornerRadiusY.blend(o->cornerRadiusY(), progress, ValueRangeNonNegative));
return result.release();
}
@@ -103,9 +103,9 @@ PassRefPtr<BasicShape> BasicShapeCircle::blend(const BasicShape* other, double p
const BasicShapeCircle* o = static_cast<const BasicShapeCircle*>(other);
RefPtr<BasicShapeCircle> result = BasicShapeCircle::create();
- result->setCenterX(m_centerX.blend(o->centerX(), progress));
- result->setCenterY(m_centerY.blend(o->centerY(), progress));
- result->setRadius(m_radius.blend(o->radius(), progress));
+ result->setCenterX(m_centerX.blend(o->centerX(), progress, ValueRangeAll));
+ result->setCenterY(m_centerY.blend(o->centerY(), progress, ValueRangeAll));
+ result->setRadius(m_radius.blend(o->radius(), progress, ValueRangeNonNegative));
return result.release();
}
@@ -130,10 +130,10 @@ PassRefPtr<BasicShape> BasicShapeEllipse::blend(const BasicShape* other, double
const BasicShapeEllipse* o = static_cast<const BasicShapeEllipse*>(other);
RefPtr<BasicShapeEllipse> result = BasicShapeEllipse::create();
- result->setCenterX(m_centerX.blend(o->centerX(), progress));
- result->setCenterY(m_centerY.blend(o->centerY(), progress));
- result->setRadiusX(m_radiusX.blend(o->radiusX(), progress));
- result->setRadiusY(m_radiusY.blend(o->radiusY(), progress));
+ result->setCenterX(m_centerX.blend(o->centerX(), progress, ValueRangeAll));
+ result->setCenterY(m_centerY.blend(o->centerY(), progress, ValueRangeAll));
+ result->setRadiusX(m_radiusX.blend(o->radiusX(), progress, ValueRangeNonNegative));
+ result->setRadiusY(m_radiusY.blend(o->radiusY(), progress, ValueRangeNonNegative));
return result.release();
}
@@ -171,8 +171,8 @@ PassRefPtr<BasicShape> BasicShapePolygon::blend(const BasicShape* other, double
result->setWindRule(o->windRule());
for (size_t i = 0; i < length; i = i + 2) {
- result->appendPoint(m_values.at(i).blend(o->values().at(i), progress),
- m_values.at(i + 1).blend(o->values().at(i + 1), progress));
+ result->appendPoint(m_values.at(i).blend(o->values().at(i), progress, ValueRangeAll),
+ m_values.at(i + 1).blend(o->values().at(i + 1), progress, ValueRangeAll));
}
return result.release();
@@ -203,12 +203,12 @@ PassRefPtr<BasicShape> BasicShapeInsetRectangle::blend(const BasicShape* other,
const BasicShapeInsetRectangle* o = static_cast<const BasicShapeInsetRectangle*>(other);
RefPtr<BasicShapeInsetRectangle> result = BasicShapeInsetRectangle::create();
- result->setTop(m_top.blend(o->top(), progress));
- result->setRight(m_right.blend(o->right(), progress));
- result->setBottom(m_bottom.blend(o->bottom(), progress));
- result->setLeft(m_left.blend(o->left(), progress));
- result->setCornerRadiusX(m_cornerRadiusX.blend(o->cornerRadiusX(), progress));
- result->setCornerRadiusY(m_cornerRadiusY.blend(o->cornerRadiusY(), progress));
+ result->setTop(m_top.blend(o->top(), progress, ValueRangeNonNegative));
+ result->setRight(m_right.blend(o->right(), progress, ValueRangeNonNegative));
+ result->setBottom(m_bottom.blend(o->bottom(), progress, ValueRangeNonNegative));
+ result->setLeft(m_left.blend(o->left(), progress, ValueRangeNonNegative));
+ result->setCornerRadiusX(m_cornerRadiusX.blend(o->cornerRadiusX(), progress, ValueRangeNonNegative));
+ result->setCornerRadiusY(m_cornerRadiusY.blend(o->cornerRadiusY(), progress, ValueRangeNonNegative));
return result.release();
}
}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/style/BasicShapes.h b/chromium/third_party/WebKit/Source/core/rendering/style/BasicShapes.h
index 3cf6301ea2b..b8735a82095 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/style/BasicShapes.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/style/BasicShapes.h
@@ -30,8 +30,8 @@
#ifndef BasicShapes_h
#define BasicShapes_h
-#include "core/platform/Length.h"
-#include "core/platform/graphics/WindRule.h"
+#include "platform/Length.h"
+#include "platform/graphics/WindRule.h"
#include "wtf/RefCounted.h"
#include "wtf/RefPtr.h"
#include "wtf/Vector.h"
diff --git a/chromium/third_party/WebKit/Source/core/rendering/style/BorderData.h b/chromium/third_party/WebKit/Source/core/rendering/style/BorderData.h
index 6c4760187c9..bf96bcf797c 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/style/BorderData.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/style/BorderData.h
@@ -25,10 +25,10 @@
#ifndef BorderData_h
#define BorderData_h
-#include "core/platform/LengthSize.h"
-#include "core/platform/graphics/IntRect.h"
#include "core/rendering/style/BorderValue.h"
#include "core/rendering/style/NinePieceImage.h"
+#include "platform/LengthSize.h"
+#include "platform/geometry/IntRect.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/rendering/style/BorderImageLength.h b/chromium/third_party/WebKit/Source/core/rendering/style/BorderImageLength.h
new file mode 100644
index 00000000000..a3a954feeb1
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/rendering/style/BorderImageLength.h
@@ -0,0 +1,89 @@
+/*
+ * Copyright (c) 2013, Opera Software ASA. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Opera Software ASA nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef BorderImageLength_h
+#define BorderImageLength_h
+
+#include "platform/Length.h"
+
+namespace WebCore {
+
+// Represents an individual computed border image width or outset.
+//
+// http://www.w3.org/TR/css3-background/#border-image-width
+// http://www.w3.org/TR/css3-background/#border-image-outset
+class BorderImageLength {
+public:
+ BorderImageLength(double number)
+ : m_length(Undefined)
+ , m_number(number)
+ , m_type(NumberType)
+ {
+ }
+
+ BorderImageLength(const Length& length)
+ : m_length(length)
+ , m_number(0)
+ , m_type(LengthType)
+ {
+ }
+
+ bool isNumber() const { return m_type == NumberType; }
+ bool isLength() const { return m_type == LengthType; }
+
+ const Length& length() const { ASSERT(isLength()); return m_length; }
+ Length& length() { ASSERT(isLength()); return m_length; }
+
+ double number() const { ASSERT(isNumber()); return m_number; }
+
+ bool operator==(const BorderImageLength& other) const
+ {
+ return m_type == other.m_type && m_length == other.m_length && m_number == other.m_number;
+ }
+
+ bool isZero() const
+ {
+ return (isLength() && m_length.isZero()) || (isNumber() && m_number);
+ }
+
+private:
+ // Ideally we would put the 2 following fields in a union, but Length has a constructor,
+ // a destructor and a copy assignment which isn't allowed.
+ Length m_length;
+ double m_number;
+ enum {
+ LengthType,
+ NumberType
+ } m_type;
+};
+
+} // namespace WebCore
+
+#endif // BorderImageLength_h
diff --git a/chromium/third_party/WebKit/Source/core/rendering/style/BorderImageLengthBox.h b/chromium/third_party/WebKit/Source/core/rendering/style/BorderImageLengthBox.h
new file mode 100644
index 00000000000..436846ac9b9
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/rendering/style/BorderImageLengthBox.h
@@ -0,0 +1,99 @@
+/*
+ * Copyright (c) 2013, Opera Software ASA. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Opera Software ASA nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef BorderImageLengthBox_h
+#define BorderImageLengthBox_h
+
+#include "core/rendering/style/BorderImageLength.h"
+
+namespace WebCore {
+
+// Represents a computed border image width or outset.
+//
+// http://www.w3.org/TR/css3-background/#border-image-width
+// http://www.w3.org/TR/css3-background/#border-image-outset
+class BorderImageLengthBox {
+public:
+ BorderImageLengthBox(Length length)
+ : m_left(length)
+ , m_right(length)
+ , m_top(length)
+ , m_bottom(length)
+ {
+ }
+
+ BorderImageLengthBox(double number)
+ : m_left(number)
+ , m_right(number)
+ , m_top(number)
+ , m_bottom(number)
+ {
+ }
+
+ BorderImageLengthBox(const BorderImageLength& top, const BorderImageLength& right,
+ const BorderImageLength& bottom, const BorderImageLength& left)
+ : m_left(left)
+ , m_right(right)
+ , m_top(top)
+ , m_bottom(bottom)
+ {
+ }
+
+ const BorderImageLength& left() const { return m_left; }
+ const BorderImageLength& right() const { return m_right; }
+ const BorderImageLength& top() const { return m_top; }
+ const BorderImageLength& bottom() const { return m_bottom; }
+
+ bool operator==(const BorderImageLengthBox& other) const
+ {
+ return m_left == other.m_left && m_right == other.m_right
+ && m_top == other.m_top && m_bottom == other.m_bottom;
+ }
+
+ bool operator!=(const BorderImageLengthBox& other) const
+ {
+ return !(*this == other);
+ }
+
+ bool nonZero() const
+ {
+ return !(m_left.isZero() && m_right.isZero() && m_top.isZero() && m_bottom.isZero());
+ }
+
+private:
+ BorderImageLength m_left;
+ BorderImageLength m_right;
+ BorderImageLength m_top;
+ BorderImageLength m_bottom;
+};
+
+} // namespace WebCore
+
+#endif // BorderImageLengthBox_h
diff --git a/chromium/third_party/WebKit/Source/core/rendering/style/BorderValue.h b/chromium/third_party/WebKit/Source/core/rendering/style/BorderValue.h
index fb8c61c8104..dcd5096df0b 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/style/BorderValue.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/style/BorderValue.h
@@ -25,8 +25,8 @@
#ifndef BorderValue_h
#define BorderValue_h
-#include "core/platform/graphics/Color.h"
#include "core/rendering/style/RenderStyleConstants.h"
+#include "platform/graphics/Color.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/rendering/style/CursorData.h b/chromium/third_party/WebKit/Source/core/rendering/style/CursorData.h
index b5ec096c8b2..90934a21d44 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/style/CursorData.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/style/CursorData.h
@@ -25,8 +25,8 @@
#ifndef CursorData_h
#define CursorData_h
-#include "core/platform/graphics/IntPoint.h"
#include "core/rendering/style/StyleImage.h"
+#include "platform/geometry/IntPoint.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/rendering/style/FillLayer.cpp b/chromium/third_party/WebKit/Source/core/rendering/style/FillLayer.cpp
index ca66f47152b..5a621e0c1f2 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/style/FillLayer.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/style/FillLayer.cpp
@@ -40,7 +40,7 @@ struct SameSizeAsFillLayer {
COMPILE_ASSERT(sizeof(FillLayer) == sizeof(SameSizeAsFillLayer), FillLayer_should_stay_small);
-FillLayer::FillLayer(EFillLayerType type)
+FillLayer::FillLayer(EFillLayerType type, bool useInitialValues)
: m_next(0)
, m_image(FillLayer::initialFillImage(type))
, m_xPosition(FillLayer::initialFillXPosition(type))
@@ -52,23 +52,24 @@ FillLayer::FillLayer(EFillLayerType type)
, m_repeatX(FillLayer::initialFillRepeatX(type))
, m_repeatY(FillLayer::initialFillRepeatY(type))
, m_composite(FillLayer::initialFillComposite(type))
- , m_sizeType(FillLayer::initialFillSizeType(type))
+ , m_sizeType(useInitialValues ? FillLayer::initialFillSizeType(type) : SizeNone)
, m_blendMode(FillLayer::initialFillBlendMode(type))
, m_maskSourceType(FillLayer::initialFillMaskSourceType(type))
- , m_imageSet(false)
- , m_attachmentSet(false)
- , m_clipSet(false)
- , m_originSet(false)
- , m_repeatXSet(false)
- , m_repeatYSet(false)
- , m_xPosSet(false)
- , m_yPosSet(false)
- , m_backgroundOriginSet(false)
, m_backgroundXOrigin(LeftEdge)
, m_backgroundYOrigin(TopEdge)
- , m_compositeSet(type == MaskFillLayer)
- , m_blendModeSet(false)
- , m_maskSourceTypeSet(false)
+ , m_imageSet(useInitialValues)
+ , m_attachmentSet(useInitialValues)
+ , m_clipSet(useInitialValues)
+ , m_originSet(useInitialValues)
+ , m_repeatXSet(useInitialValues)
+ , m_repeatYSet(useInitialValues)
+ , m_xPosSet(useInitialValues)
+ , m_yPosSet(useInitialValues)
+ , m_backgroundXOriginSet(false)
+ , m_backgroundYOriginSet(false)
+ , m_compositeSet(useInitialValues || type == MaskFillLayer)
+ , m_blendModeSet(useInitialValues)
+ , m_maskSourceTypeSet(useInitialValues)
, m_type(type)
{
}
@@ -88,6 +89,8 @@ FillLayer::FillLayer(const FillLayer& o)
, m_sizeType(o.m_sizeType)
, m_blendMode(o.m_blendMode)
, m_maskSourceType(o.m_maskSourceType)
+ , m_backgroundXOrigin(o.m_backgroundXOrigin)
+ , m_backgroundYOrigin(o.m_backgroundYOrigin)
, m_imageSet(o.m_imageSet)
, m_attachmentSet(o.m_attachmentSet)
, m_clipSet(o.m_clipSet)
@@ -96,9 +99,8 @@ FillLayer::FillLayer(const FillLayer& o)
, m_repeatYSet(o.m_repeatYSet)
, m_xPosSet(o.m_xPosSet)
, m_yPosSet(o.m_yPosSet)
- , m_backgroundOriginSet(o.m_backgroundOriginSet)
- , m_backgroundXOrigin(o.m_backgroundXOrigin)
- , m_backgroundYOrigin(o.m_backgroundYOrigin)
+ , m_backgroundXOriginSet(o.m_backgroundXOriginSet)
+ , m_backgroundYOriginSet(o.m_backgroundYOriginSet)
, m_compositeSet(o.m_compositeSet)
, m_blendModeSet(o.m_blendModeSet)
, m_maskSourceTypeSet(o.m_maskSourceTypeSet)
@@ -123,7 +125,8 @@ FillLayer& FillLayer::operator=(const FillLayer& o)
m_yPosition = o.m_yPosition;
m_backgroundXOrigin = o.m_backgroundXOrigin;
m_backgroundYOrigin = o.m_backgroundYOrigin;
- m_backgroundOriginSet = o.m_backgroundOriginSet;
+ m_backgroundXOriginSet = o.m_backgroundXOriginSet;
+ m_backgroundYOriginSet = o.m_backgroundYOriginSet;
m_sizeLength = o.m_sizeLength;
m_attachment = o.m_attachment;
m_clip = o.m_clip;
@@ -173,10 +176,10 @@ void FillLayer::fillUnsetProperties()
// We need to fill in the remaining values with the pattern specified.
for (FillLayer* pattern = this; curr; curr = curr->next()) {
curr->m_xPosition = pattern->m_xPosition;
- if (pattern->isBackgroundOriginSet()) {
+ if (pattern->isBackgroundXOriginSet())
curr->m_backgroundXOrigin = pattern->m_backgroundXOrigin;
+ if (pattern->isBackgroundYOriginSet())
curr->m_backgroundYOrigin = pattern->m_backgroundYOrigin;
- }
pattern = pattern->next();
if (pattern == curr || !pattern)
pattern = this;
@@ -188,10 +191,10 @@ void FillLayer::fillUnsetProperties()
// We need to fill in the remaining values with the pattern specified.
for (FillLayer* pattern = this; curr; curr = curr->next()) {
curr->m_yPosition = pattern->m_yPosition;
- if (pattern->isBackgroundOriginSet()) {
+ if (pattern->isBackgroundXOriginSet())
curr->m_backgroundXOrigin = pattern->m_backgroundXOrigin;
+ if (pattern->isBackgroundYOriginSet())
curr->m_backgroundYOrigin = pattern->m_backgroundYOrigin;
- }
pattern = pattern->next();
if (pattern == curr || !pattern)
pattern = this;
@@ -358,7 +361,7 @@ bool FillLayer::hasOpaqueImage(const RenderObject* renderer) const
if (m_composite == CompositeClear || m_composite == CompositeCopy)
return true;
- if (m_blendMode != BlendModeNormal)
+ if (m_blendMode != blink::WebBlendModeNormal)
return false;
if (m_composite == CompositeSourceOver)
diff --git a/chromium/third_party/WebKit/Source/core/rendering/style/FillLayer.h b/chromium/third_party/WebKit/Source/core/rendering/style/FillLayer.h
index b0167ee8fdc..790f202db1b 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/style/FillLayer.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/style/FillLayer.h
@@ -25,11 +25,11 @@
#ifndef FillLayer_h
#define FillLayer_h
-#include "core/platform/Length.h"
-#include "core/platform/LengthSize.h"
-#include "core/platform/graphics/GraphicsTypes.h"
#include "core/rendering/style/RenderStyleConstants.h"
#include "core/rendering/style/StyleImage.h"
+#include "platform/Length.h"
+#include "platform/LengthSize.h"
+#include "platform/graphics/GraphicsTypes.h"
#include "wtf/RefPtr.h"
namespace WebCore {
@@ -62,7 +62,7 @@ struct FillSize {
class FillLayer {
WTF_MAKE_FAST_ALLOCATED;
public:
- FillLayer(EFillLayerType);
+ FillLayer(EFillLayerType, bool useInitialValues = false);
~FillLayer();
StyleImage* image() const { return m_image.get(); }
@@ -76,7 +76,7 @@ public:
EFillRepeat repeatX() const { return static_cast<EFillRepeat>(m_repeatX); }
EFillRepeat repeatY() const { return static_cast<EFillRepeat>(m_repeatY); }
CompositeOperator composite() const { return static_cast<CompositeOperator>(m_composite); }
- BlendMode blendMode() const { return static_cast<BlendMode>(m_blendMode); }
+ blink::WebBlendMode blendMode() const { return static_cast<blink::WebBlendMode>(m_blendMode); }
LengthSize sizeLength() const { return m_sizeLength; }
EFillSizeType sizeType() const { return static_cast<EFillSizeType>(m_sizeType); }
FillSize size() const { return FillSize(static_cast<EFillSizeType>(m_sizeType), m_sizeLength); }
@@ -88,7 +88,8 @@ public:
bool isImageSet() const { return m_imageSet; }
bool isXPositionSet() const { return m_xPosSet; }
bool isYPositionSet() const { return m_yPosSet; }
- bool isBackgroundOriginSet() const { return m_backgroundOriginSet; }
+ bool isBackgroundXOriginSet() const { return m_backgroundXOriginSet; }
+ bool isBackgroundYOriginSet() const { return m_backgroundYOriginSet; }
bool isAttachmentSet() const { return m_attachmentSet; }
bool isClipSet() const { return m_clipSet; }
bool isOriginSet() const { return m_originSet; }
@@ -100,17 +101,17 @@ public:
bool isMaskSourceTypeSet() const { return m_maskSourceTypeSet; }
void setImage(PassRefPtr<StyleImage> i) { m_image = i; m_imageSet = true; }
- void setXPosition(Length l) { m_xPosition = l; m_xPosSet = true; }
- void setYPosition(Length l) { m_yPosition = l; m_yPosSet = true; }
- void setBackgroundXOrigin(BackgroundEdgeOrigin o) { m_backgroundXOrigin = o; m_backgroundOriginSet = true; }
- void setBackgroundYOrigin(BackgroundEdgeOrigin o) { m_backgroundYOrigin = o; m_backgroundOriginSet = true; }
+ void setXPosition(Length position) { m_xPosition = position; m_xPosSet = true; m_backgroundXOriginSet = false; m_backgroundXOrigin = LeftEdge; }
+ void setYPosition(Length position) { m_yPosition = position; m_yPosSet = true; m_backgroundYOriginSet = false; m_backgroundYOrigin = TopEdge; }
+ void setBackgroundXOrigin(BackgroundEdgeOrigin origin) { m_backgroundXOrigin = origin; m_backgroundXOriginSet = true; }
+ void setBackgroundYOrigin(BackgroundEdgeOrigin origin) { m_backgroundYOrigin = origin; m_backgroundYOriginSet = true; }
void setAttachment(EFillAttachment attachment) { m_attachment = attachment; m_attachmentSet = true; }
void setClip(EFillBox b) { m_clip = b; m_clipSet = true; }
void setOrigin(EFillBox b) { m_origin = b; m_originSet = true; }
void setRepeatX(EFillRepeat r) { m_repeatX = r; m_repeatXSet = true; }
void setRepeatY(EFillRepeat r) { m_repeatY = r; m_repeatYSet = true; }
void setComposite(CompositeOperator c) { m_composite = c; m_compositeSet = true; }
- void setBlendMode(BlendMode b) { m_blendMode = b; m_blendModeSet = true; }
+ void setBlendMode(blink::WebBlendMode b) { m_blendMode = b; m_blendModeSet = true; }
void setSizeType(EFillSizeType b) { m_sizeType = b; }
void setSizeLength(LengthSize l) { m_sizeLength = l; }
void setSize(FillSize f) { m_sizeType = f.type; m_sizeLength = f.size; }
@@ -120,12 +121,12 @@ public:
void clearXPosition()
{
m_xPosSet = false;
- m_backgroundOriginSet = false;
+ m_backgroundXOriginSet = false;
}
void clearYPosition()
{
m_yPosSet = false;
- m_backgroundOriginSet = false;
+ m_backgroundYOriginSet = false;
}
void clearAttachment() { m_attachmentSet = false; }
@@ -181,8 +182,8 @@ public:
static EFillRepeat initialFillRepeatX(EFillLayerType) { return RepeatFill; }
static EFillRepeat initialFillRepeatY(EFillLayerType) { return RepeatFill; }
static CompositeOperator initialFillComposite(EFillLayerType) { return CompositeSourceOver; }
- static BlendMode initialFillBlendMode(EFillLayerType) { return BlendModeNormal; }
- static EFillSizeType initialFillSizeType(EFillLayerType) { return SizeNone; }
+ static blink::WebBlendMode initialFillBlendMode(EFillLayerType) { return blink::WebBlendModeNormal; }
+ static EFillSizeType initialFillSizeType(EFillLayerType) { return SizeLength; }
static LengthSize initialFillSizeLength(EFillLayerType) { return LengthSize(); }
static FillSize initialFillSize(EFillLayerType type) { return FillSize(initialFillSizeType(type), initialFillSizeLength(type)); }
static Length initialFillXPosition(EFillLayerType) { return Length(0.0, Percent); }
@@ -213,8 +214,10 @@ private:
unsigned m_repeatY : 3; // EFillRepeat
unsigned m_composite : 4; // CompositeOperator
unsigned m_sizeType : 2; // EFillSizeType
- unsigned m_blendMode : 5; // BlendMode
+ unsigned m_blendMode : 5; // blink::WebBlendMode
unsigned m_maskSourceType : 1; // EMaskSourceType
+ unsigned m_backgroundXOrigin : 2; // BackgroundEdgeOrigin
+ unsigned m_backgroundYOrigin : 2; // BackgroundEdgeOrigin
unsigned m_imageSet : 1;
unsigned m_attachmentSet : 1;
@@ -224,9 +227,8 @@ private:
unsigned m_repeatYSet : 1;
unsigned m_xPosSet : 1;
unsigned m_yPosSet : 1;
- unsigned m_backgroundOriginSet : 1;
- unsigned m_backgroundXOrigin : 2; // BackgroundEdgeOrigin
- unsigned m_backgroundYOrigin : 2; // BackgroundEdgeOrigin
+ unsigned m_backgroundXOriginSet : 1;
+ unsigned m_backgroundYOriginSet : 1;
unsigned m_compositeSet : 1;
unsigned m_blendModeSet : 1;
unsigned m_maskSourceTypeSet : 1;
diff --git a/chromium/third_party/WebKit/Source/core/rendering/style/GridCoordinate.h b/chromium/third_party/WebKit/Source/core/rendering/style/GridCoordinate.h
index ec0d890a43b..937d3f08b9b 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/style/GridCoordinate.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/style/GridCoordinate.h
@@ -31,6 +31,7 @@
#ifndef GridCoordinate_h
#define GridCoordinate_h
+#include "core/rendering/style/GridPosition.h"
#include "wtf/HashMap.h"
#include "wtf/PassOwnPtr.h"
#include "wtf/text/WTFString.h"
@@ -46,6 +47,57 @@ struct GridSpan {
return adoptPtr(new GridSpan(initialPosition, finalPosition));
}
+ static PassOwnPtr<GridSpan> createWithSpanAgainstOpposite(size_t resolvedOppositePosition, const GridPosition& position, GridPositionSide side)
+ {
+ // 'span 1' is contained inside a single grid track regardless of the direction.
+ // That's why the CSS span value is one more than the offset we apply.
+ size_t positionOffset = position.spanPosition() - 1;
+ if (side == ColumnStartSide || side == RowStartSide) {
+ size_t initialResolvedPosition = std::max<int>(0, resolvedOppositePosition - positionOffset);
+ return GridSpan::create(initialResolvedPosition, resolvedOppositePosition);
+ }
+
+ return GridSpan::create(resolvedOppositePosition, resolvedOppositePosition + positionOffset);
+ }
+
+ static PassOwnPtr<GridSpan> createWithNamedSpanAgainstOpposite(size_t resolvedOppositePosition, const GridPosition& position, GridPositionSide side, const Vector<size_t>& gridLines)
+ {
+ if (side == RowStartSide || side == ColumnStartSide)
+ return createWithInitialNamedSpanAgainstOpposite(resolvedOppositePosition, position, gridLines);
+
+ return createWithFinalNamedSpanAgainstOpposite(resolvedOppositePosition, position, gridLines);
+ }
+
+ static PassOwnPtr<GridSpan> createWithInitialNamedSpanAgainstOpposite(size_t resolvedOppositePosition, const GridPosition& position, const Vector<size_t>& gridLines)
+ {
+ // The grid line inequality needs to be strict (which doesn't match the after / end case) because |resolvedOppositePosition|
+ // is already converted to an index in our grid representation (ie one was removed from the grid line to account for the side).
+ size_t firstLineBeforeOppositePositionIndex = 0;
+ const size_t* firstLineBeforeOppositePosition = std::lower_bound(gridLines.begin(), gridLines.end(), resolvedOppositePosition);
+ if (firstLineBeforeOppositePosition != gridLines.end())
+ firstLineBeforeOppositePositionIndex = firstLineBeforeOppositePosition - gridLines.begin();
+
+ size_t gridLineIndex = std::max<int>(0, firstLineBeforeOppositePositionIndex - position.spanPosition() + 1);
+ size_t resolvedGridLinePosition = gridLines[gridLineIndex];
+ if (resolvedGridLinePosition > resolvedOppositePosition)
+ resolvedGridLinePosition = resolvedOppositePosition;
+ return GridSpan::create(resolvedGridLinePosition, resolvedOppositePosition);
+ }
+
+ static PassOwnPtr<GridSpan> createWithFinalNamedSpanAgainstOpposite(size_t resolvedOppositePosition, const GridPosition& position, const Vector<size_t>& gridLines)
+ {
+ size_t firstLineAfterOppositePositionIndex = gridLines.size() - 1;
+ const size_t* firstLineAfterOppositePosition = std::upper_bound(gridLines.begin(), gridLines.end(), resolvedOppositePosition);
+ if (firstLineAfterOppositePosition != gridLines.end())
+ firstLineAfterOppositePositionIndex = firstLineAfterOppositePosition - gridLines.begin();
+
+ size_t gridLineIndex = std::min(gridLines.size() - 1, firstLineAfterOppositePositionIndex + position.spanPosition() - 1);
+ size_t resolvedGridLinePosition = GridPosition::adjustGridPositionForAfterEndSide(gridLines[gridLineIndex]);
+ if (resolvedGridLinePosition < resolvedOppositePosition)
+ resolvedGridLinePosition = resolvedOppositePosition;
+ return GridSpan::create(resolvedOppositePosition, resolvedGridLinePosition);
+ }
+
GridSpan(size_t initialPosition, size_t finalPosition)
: initialPositionIndex(initialPosition)
, finalPositionIndex(finalPosition)
diff --git a/chromium/third_party/WebKit/Source/core/rendering/style/GridLength.h b/chromium/third_party/WebKit/Source/core/rendering/style/GridLength.h
index 277b35584b6..dadf7dac255 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/style/GridLength.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/style/GridLength.h
@@ -31,7 +31,7 @@
#ifndef GridLength_h
#define GridLength_h
-#include "core/platform/Length.h"
+#include "platform/Length.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/rendering/style/GridPosition.h b/chromium/third_party/WebKit/Source/core/rendering/style/GridPosition.h
index 256f4163dbb..133cdd55123 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/style/GridPosition.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/style/GridPosition.h
@@ -42,6 +42,13 @@ enum GridPositionType {
NamedGridAreaPosition // <ident>
};
+enum GridPositionSide {
+ ColumnStartSide,
+ ColumnEndSide,
+ RowStartSide,
+ RowEndSide
+};
+
class GridPosition {
public:
GridPosition()
@@ -50,6 +57,20 @@ public:
{
}
+ static size_t adjustGridPositionForAfterEndSide(size_t resolvedPosition)
+ {
+ return resolvedPosition ? resolvedPosition - 1 : 0;
+ }
+
+ static size_t adjustGridPositionForSide(size_t resolvedPosition, GridPositionSide side)
+ {
+ // An item finishing on the N-th line belongs to the N-1-th cell.
+ if (side == ColumnEndSide || side == RowEndSide)
+ return adjustGridPositionForAfterEndSide(resolvedPosition);
+
+ return resolvedPosition;
+ }
+
bool isPositive() const { return integerPosition() > 0; }
GridPositionType type() const { return m_type; }
diff --git a/chromium/third_party/WebKit/Source/core/rendering/style/GridTrackSize.h b/chromium/third_party/WebKit/Source/core/rendering/style/GridTrackSize.h
index a75820e7360..584b47a4024 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/style/GridTrackSize.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/style/GridTrackSize.h
@@ -42,11 +42,31 @@ enum GridTrackSizeType {
class GridTrackSize {
public:
- GridTrackSize(LengthType type = Undefined)
+ GridTrackSize()
+ : m_type(LengthTrackSizing)
+ , m_minTrackBreadth(Undefined)
+ , m_maxTrackBreadth(Undefined)
+ , m_minTrackBreadthIsMinOrMaxContent(false)
+ , m_minTrackBreadthIsMaxContent(false)
+ , m_maxTrackBreadthIsMinOrMaxContent(false)
+ , m_maxTrackBreadthIsMaxContent(false)
+ {
+ // Someone has to set a valid lenght type through setLength or
+ // setMinMax before using the object.
+ }
+
+ GridTrackSize(LengthType type)
: m_type(LengthTrackSizing)
, m_minTrackBreadth(type)
, m_maxTrackBreadth(type)
+ , m_minTrackBreadthIsMinOrMaxContent(false)
+ , m_minTrackBreadthIsMaxContent(false)
+ , m_maxTrackBreadthIsMinOrMaxContent(false)
+ , m_maxTrackBreadthIsMaxContent(false)
{
+ ASSERT(type != Undefined);
+
+ cacheMinMaxTrackBreadthTypes();
}
const GridLength& length() const
@@ -63,6 +83,8 @@ public:
m_type = LengthTrackSizing;
m_minTrackBreadth = length;
m_maxTrackBreadth = length;
+
+ cacheMinMaxTrackBreadthTypes();
}
const GridLength& minTrackBreadth() const
@@ -90,6 +112,8 @@ public:
m_type = MinMaxTrackSizing;
m_minTrackBreadth = minTrackBreadth;
m_maxTrackBreadth = maxTrackBreadth;
+
+ cacheMinMaxTrackBreadthTypes();
}
GridTrackSizeType type() const { return m_type; }
@@ -101,15 +125,27 @@ public:
return m_type == other.m_type && m_minTrackBreadth == other.m_minTrackBreadth && m_maxTrackBreadth == other.m_maxTrackBreadth;
}
- bool hasMinOrMaxContentMinTrackBreadth() const { return minTrackBreadth().isLength() && (minTrackBreadth().length().isMinContent() || minTrackBreadth().length().isMaxContent()); }
- bool hasMaxContentMinTrackBreadth() const { return minTrackBreadth().isLength() && minTrackBreadth().length().isMaxContent(); }
- bool hasMinOrMaxContentMaxTrackBreadth() const { return maxTrackBreadth().isLength() && (maxTrackBreadth().length().isMinContent() || maxTrackBreadth().length().isMaxContent()); }
- bool hasMaxContentMaxTrackBreadth() const { return maxTrackBreadth().isLength() && maxTrackBreadth().length().isMaxContent(); }
+ void cacheMinMaxTrackBreadthTypes()
+ {
+ m_minTrackBreadthIsMaxContent = minTrackBreadth().isLength() && minTrackBreadth().length().isMaxContent();
+ m_minTrackBreadthIsMinOrMaxContent = m_minTrackBreadthIsMaxContent || (minTrackBreadth().isLength() && minTrackBreadth().length().isMinContent());
+ m_maxTrackBreadthIsMaxContent = maxTrackBreadth().isLength() && maxTrackBreadth().length().isMaxContent();
+ m_maxTrackBreadthIsMinOrMaxContent = m_maxTrackBreadthIsMaxContent || (maxTrackBreadth().isLength() && maxTrackBreadth().length().isMinContent());
+ }
+
+ bool hasMinOrMaxContentMinTrackBreadth() const { return m_minTrackBreadthIsMinOrMaxContent; }
+ bool hasMaxContentMinTrackBreadth() const { return m_minTrackBreadthIsMaxContent; }
+ bool hasMinOrMaxContentMaxTrackBreadth() const { return m_maxTrackBreadthIsMinOrMaxContent; }
+ bool hasMaxContentMaxTrackBreadth() const { return m_maxTrackBreadthIsMaxContent; }
private:
GridTrackSizeType m_type;
GridLength m_minTrackBreadth;
GridLength m_maxTrackBreadth;
+ bool m_minTrackBreadthIsMinOrMaxContent;
+ bool m_minTrackBreadthIsMaxContent;
+ bool m_maxTrackBreadthIsMinOrMaxContent;
+ bool m_maxTrackBreadthIsMaxContent;
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/style/KeyframeList.cpp b/chromium/third_party/WebKit/Source/core/rendering/style/KeyframeList.cpp
index a28da7e95db..2ed58360ee1 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/style/KeyframeList.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/style/KeyframeList.cpp
@@ -42,15 +42,11 @@ void KeyframeValue::addProperties(const StylePropertySet* propertySet)
}
}
-TimingFunction* KeyframeValue::timingFunction(const RenderStyle* keyframeStyle, const AtomicString& name)
+TimingFunction* KeyframeValue::timingFunction(const RenderStyle& keyframeStyle)
{
- ASSERT(keyframeStyle && keyframeStyle->animations());
- for (size_t i = 0; i < keyframeStyle->animations()->size(); i++) {
- if (name == keyframeStyle->animations()->animation(i)->name())
- return keyframeStyle->animations()->animation(i)->timingFunction();
- }
- ASSERT_NOT_REACHED();
- return 0;
+ const CSSAnimationDataList* animations = keyframeStyle.animations();
+ ASSERT(animations && !animations->isEmpty());
+ return animations->animation(0)->timingFunction();
}
KeyframeList::~KeyframeList()
@@ -64,25 +60,6 @@ void KeyframeList::clear()
m_properties.clear();
}
-bool KeyframeList::operator==(const KeyframeList& o) const
-{
- if (m_keyframes.size() != o.m_keyframes.size())
- return false;
-
- Vector<KeyframeValue>::const_iterator it2 = o.m_keyframes.begin();
- for (Vector<KeyframeValue>::const_iterator it1 = m_keyframes.begin(); it1 != m_keyframes.end(); ++it1) {
- if (it1->key() != it2->key())
- return false;
- const RenderStyle& style1 = *it1->style();
- const RenderStyle& style2 = *it2->style();
- if (style1 != style2)
- return false;
- ++it2;
- }
-
- return true;
-}
-
void KeyframeList::insert(const KeyframeValue& keyframe)
{
if (keyframe.key() < 0 || keyframe.key() > 1)
diff --git a/chromium/third_party/WebKit/Source/core/rendering/style/KeyframeList.h b/chromium/third_party/WebKit/Source/core/rendering/style/KeyframeList.h
index 792f1eb0705..ee2d237b505 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/style/KeyframeList.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/style/KeyframeList.h
@@ -58,7 +58,7 @@ public:
const RenderStyle* style() const { return m_style.get(); }
void setStyle(PassRefPtr<RenderStyle> style) { m_style = style; }
- static TimingFunction* timingFunction(const RenderStyle*, const AtomicString& name);
+ static TimingFunction* timingFunction(const RenderStyle& keyframeStyle);
private:
double m_key;
@@ -68,7 +68,7 @@ private:
class KeyframeList {
public:
- KeyframeList(RenderObject*, const AtomicString& animationName)
+ KeyframeList(RenderObject&, const AtomicString& animationName)
: m_animationName(animationName)
{
insert(KeyframeValue(0, 0));
@@ -76,9 +76,6 @@ public:
}
~KeyframeList();
- bool operator==(const KeyframeList& o) const;
- bool operator!=(const KeyframeList& o) const { return !(*this == o); }
-
const AtomicString& animationName() const { return m_animationName; }
void insert(const KeyframeValue& keyframe);
diff --git a/chromium/third_party/WebKit/Source/core/rendering/style/NinePieceImage.cpp b/chromium/third_party/WebKit/Source/core/rendering/style/NinePieceImage.cpp
index afe320ee8b9..383ca14283a 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/style/NinePieceImage.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/style/NinePieceImage.cpp
@@ -39,7 +39,7 @@ NinePieceImage::NinePieceImage()
{
}
-NinePieceImage::NinePieceImage(PassRefPtr<StyleImage> image, LengthBox imageSlices, bool fill, LengthBox borderSlices, LengthBox outset, ENinePieceImageRule horizontalRule, ENinePieceImageRule verticalRule)
+NinePieceImage::NinePieceImage(PassRefPtr<StyleImage> image, LengthBox imageSlices, bool fill, const BorderImageLengthBox& borderSlices, const BorderImageLengthBox& outset, ENinePieceImageRule horizontalRule, ENinePieceImageRule verticalRule)
{
m_data.init();
m_data.access()->image = image;
@@ -57,8 +57,8 @@ NinePieceImageData::NinePieceImageData()
, verticalRule(StretchImageRule)
, image(0)
, imageSlices(Length(100, Percent), Length(100, Percent), Length(100, Percent), Length(100, Percent))
- , borderSlices(Length(1, Relative), Length(1, Relative), Length(1, Relative), Length(1, Relative))
- , outset(0)
+ , borderSlices(1.0, 1.0, 1.0, 1.0)
+ , outset(Length(0, Fixed), Length(0, Fixed), Length(0, Fixed), Length(0, Fixed))
{
}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/style/NinePieceImage.h b/chromium/third_party/WebKit/Source/core/rendering/style/NinePieceImage.h
index d4d10c9faf4..dd5ec09a7cc 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/style/NinePieceImage.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/style/NinePieceImage.h
@@ -24,10 +24,11 @@
#ifndef NinePieceImage_h
#define NinePieceImage_h
-#include "core/platform/LayoutUnit.h"
-#include "core/platform/LengthBox.h"
+#include "core/rendering/style/BorderImageLengthBox.h"
#include "core/rendering/style/DataRef.h"
#include "core/rendering/style/StyleImage.h"
+#include "platform/LayoutUnit.h"
+#include "platform/LengthBox.h"
namespace WebCore {
@@ -48,8 +49,8 @@ public:
unsigned verticalRule : 2; // ENinePieceImageRule
RefPtr<StyleImage> image;
LengthBox imageSlices;
- LengthBox borderSlices;
- LengthBox outset;
+ BorderImageLengthBox borderSlices;
+ BorderImageLengthBox outset;
private:
NinePieceImageData();
@@ -59,7 +60,8 @@ private:
class NinePieceImage {
public:
NinePieceImage();
- NinePieceImage(PassRefPtr<StyleImage>, LengthBox imageSlices, bool fill, LengthBox borderSlices, LengthBox outset, ENinePieceImageRule horizontalRule, ENinePieceImageRule verticalRule);
+ NinePieceImage(PassRefPtr<StyleImage>, LengthBox imageSlices, bool fill, const BorderImageLengthBox& borderSlices,
+ const BorderImageLengthBox& outset, ENinePieceImageRule horizontalRule, ENinePieceImageRule verticalRule);
bool operator==(const NinePieceImage& other) const { return m_data == other.m_data; }
bool operator!=(const NinePieceImage& other) const { return m_data != other.m_data; }
@@ -74,11 +76,11 @@ public:
bool fill() const { return m_data->fill; }
void setFill(bool fill) { m_data.access()->fill = fill; }
- const LengthBox& borderSlices() const { return m_data->borderSlices; }
- void setBorderSlices(const LengthBox& slices) { m_data.access()->borderSlices = slices; }
+ const BorderImageLengthBox& borderSlices() const { return m_data->borderSlices; }
+ void setBorderSlices(const BorderImageLengthBox& slices) { m_data.access()->borderSlices = slices; }
- const LengthBox& outset() const { return m_data->outset; }
- void setOutset(const LengthBox& outset) { m_data.access()->outset = outset; }
+ const BorderImageLengthBox& outset() const { return m_data->outset; }
+ void setOutset(const BorderImageLengthBox& outset) { m_data.access()->outset = outset; }
ENinePieceImageRule horizontalRule() const { return static_cast<ENinePieceImageRule>(m_data->horizontalRule); }
void setHorizontalRule(ENinePieceImageRule rule) { m_data.access()->horizontalRule = rule; }
@@ -112,14 +114,14 @@ public:
{
m_data.access()->imageSlices = LengthBox(0);
m_data.access()->fill = true;
- m_data.access()->borderSlices = LengthBox();
+ m_data.access()->borderSlices = BorderImageLengthBox(Length(Auto));
}
- static LayoutUnit computeOutset(Length outsetSide, LayoutUnit borderSide)
+ static LayoutUnit computeOutset(const BorderImageLength& outsetSide, LayoutUnit borderSide)
{
- if (outsetSide.isRelative())
- return outsetSide.value() * borderSide;
- return outsetSide.value();
+ if (outsetSide.isNumber())
+ return outsetSide.number() * borderSide;
+ return outsetSide.length().value();
}
private:
diff --git a/chromium/third_party/WebKit/Source/core/rendering/style/RenderStyle.cpp b/chromium/third_party/WebKit/Source/core/rendering/style/RenderStyle.cpp
index ece4c74925e..2bbea394980 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/style/RenderStyle.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/style/RenderStyle.cpp
@@ -24,21 +24,19 @@
#include "core/rendering/style/RenderStyle.h"
#include <algorithm>
-#include "CSSPropertyNames.h"
#include "RuntimeEnabledFeatures.h"
#include "core/css/resolver/StyleResolver.h"
-#include "core/platform/graphics/Font.h"
-#include "core/platform/graphics/FontSelector.h"
#include "core/rendering/RenderTheme.h"
#include "core/rendering/TextAutosizer.h"
#include "core/rendering/style/ContentData.h"
#include "core/rendering/style/CursorList.h"
#include "core/rendering/style/QuotesData.h"
-#include "core/rendering/style/ShadowData.h"
+#include "core/rendering/style/ShadowList.h"
#include "core/rendering/style/StyleImage.h"
#include "core/rendering/style/StyleInheritedData.h"
+#include "platform/fonts/Font.h"
+#include "platform/fonts/FontSelector.h"
#include "wtf/MathExtras.h"
-#include "wtf/StdLibExtras.h"
using namespace std;
@@ -69,7 +67,7 @@ COMPILE_ASSERT(sizeof(RenderStyle) == sizeof(SameSizeAsRenderStyle), RenderStyle
inline RenderStyle* defaultStyle()
{
- static RenderStyle* s_defaultStyle = RenderStyle::createDefaultStyle().leakRef();
+ DEFINE_STATIC_REF(RenderStyle, s_defaultStyle, (RenderStyle::createDefaultStyle()));
return s_defaultStyle;
}
@@ -260,30 +258,6 @@ bool RenderStyle::isStyleAvailable() const
return this != StyleResolver::styleNotYetAvailable();
}
-static inline int pseudoBit(PseudoId pseudo)
-{
- return 1 << (pseudo - 1);
-}
-
-bool RenderStyle::hasAnyPublicPseudoStyles() const
-{
- return PUBLIC_PSEUDOID_MASK & noninherited_flags._pseudoBits;
-}
-
-bool RenderStyle::hasPseudoStyle(PseudoId pseudo) const
-{
- ASSERT(pseudo > NOPSEUDO);
- ASSERT(pseudo < FIRST_INTERNAL_PSEUDOID);
- return pseudoBit(pseudo) & noninherited_flags._pseudoBits;
-}
-
-void RenderStyle::setHasPseudoStyle(PseudoId pseudo)
-{
- ASSERT(pseudo > NOPSEUDO);
- ASSERT(pseudo < FIRST_INTERNAL_PSEUDOID);
- noninherited_flags._pseudoBits |= pseudoBit(pseudo);
-}
-
bool RenderStyle::hasUniquePseudoStyle() const
{
if (!m_cachedPseudoStyles || styleType() != NOPSEUDO)
@@ -480,6 +454,7 @@ StyleDifference RenderStyle::diff(const RenderStyle* other, unsigned& changedCon
if (rareInheritedData.get() != other->rareInheritedData.get()) {
if (rareInheritedData->highlight != other->rareInheritedData->highlight
|| rareInheritedData->indent != other->rareInheritedData->indent
+ || rareInheritedData->m_textAlignLast != other->rareInheritedData->m_textAlignLast
|| rareInheritedData->m_textIndentLine != other->rareInheritedData->m_textIndentLine
|| rareInheritedData->m_effectiveZoom != other->rareInheritedData->m_effectiveZoom
|| rareInheritedData->wordBreak != other->rareInheritedData->wordBreak
@@ -496,6 +471,7 @@ StyleDifference RenderStyle::diff(const RenderStyle* other, unsigned& changedCon
|| rareInheritedData->textEmphasisPosition != other->rareInheritedData->textEmphasisPosition
|| rareInheritedData->textEmphasisCustomMark != other->rareInheritedData->textEmphasisCustomMark
|| rareInheritedData->m_textAlignLast != other->rareInheritedData->m_textAlignLast
+ || rareInheritedData->m_textJustify != other->rareInheritedData->m_textJustify
|| rareInheritedData->m_textOrientation != other->rareInheritedData->m_textOrientation
|| rareInheritedData->m_tabSize != other->rareInheritedData->m_tabSize
|| rareInheritedData->m_lineBoxContain != other->rareInheritedData->m_lineBoxContain
@@ -616,25 +592,27 @@ StyleDifference RenderStyle::diff(const RenderStyle* other, unsigned& changedCon
// Make sure these left/top/right/bottom checks stay below all layout checks and above
// all visible checks.
- if (position() != StaticPosition) {
- if (surround->offset != other->surround->offset) {
- // Optimize for the case where a positioned layer is moving but not changing size.
- if (position() == AbsolutePosition && positionedObjectMoved(surround->offset, other->surround->offset, m_box->width()))
-
- return StyleDifferenceLayoutPositionedMovementOnly;
+ if (position() != StaticPosition && surround->offset != other->surround->offset) {
+ // Optimize for the case where a positioned layer is moving but not changing size.
+ if (position() == AbsolutePosition && positionedObjectMoved(surround->offset, other->surround->offset, m_box->width()) && repaintOnlyDiff(other, changedContextSensitiveProperties) == StyleDifferenceEqual)
+ return StyleDifferenceLayoutPositionedMovementOnly;
- // FIXME: We would like to use SimplifiedLayout for relative positioning, but we can't quite do that yet.
- // We need to make sure SimplifiedLayout can operate correctly on RenderInlines (we will need
- // to add a selfNeedsSimplifiedLayout bit in order to not get confused and taint every line).
- return StyleDifferenceLayout;
- } else if (m_box->zIndex() != other->m_box->zIndex() || m_box->hasAutoZIndex() != other->m_box->hasAutoZIndex()
- || visual->clip != other->visual->clip || visual->hasClip != other->visual->hasClip)
- return StyleDifferenceRepaintLayer;
+ // FIXME: We would like to use SimplifiedLayout for relative positioning, but we can't quite do that yet.
+ // We need to make sure SimplifiedLayout can operate correctly on RenderInlines (we will need
+ // to add a selfNeedsSimplifiedLayout bit in order to not get confused and taint every line).
+ return StyleDifferenceLayout;
}
+ return repaintOnlyDiff(other, changedContextSensitiveProperties);
+}
- if (RuntimeEnabledFeatures::cssCompositingEnabled())
- if (rareNonInheritedData->m_effectiveBlendMode != other->rareNonInheritedData->m_effectiveBlendMode)
- return StyleDifferenceRepaintLayer;
+StyleDifference RenderStyle::repaintOnlyDiff(const RenderStyle* other, unsigned& changedContextSensitiveProperties) const
+{
+ if (position() != StaticPosition && (m_box->zIndex() != other->m_box->zIndex() || m_box->hasAutoZIndex() != other->m_box->hasAutoZIndex()
+ || visual->clip != other->visual->clip || visual->hasClip != other->visual->hasClip))
+ return StyleDifferenceRepaintLayer;
+
+ if (RuntimeEnabledFeatures::cssCompositingEnabled() && rareNonInheritedData->m_effectiveBlendMode != other->rareNonInheritedData->m_effectiveBlendMode)
+ return StyleDifferenceRepaintLayer;
if (rareNonInheritedData->opacity != other->rareNonInheritedData->opacity) {
// Don't return early here; instead take note of the type of change,
@@ -696,7 +674,7 @@ StyleDifference RenderStyle::diff(const RenderStyle* other, unsigned& changedCon
|| rareInheritedData->textStrokeColor != other->rareInheritedData->textStrokeColor
|| rareInheritedData->textEmphasisColor != other->rareInheritedData->textEmphasisColor
|| rareInheritedData->textEmphasisFill != other->rareInheritedData->textEmphasisFill)
- return StyleDifferenceRepaintIfText;
+ return StyleDifferenceRepaintIfTextOrColorChange;
// Cursors are not checked, since they will be set appropriately in response to mouse events,
// so they don't need to cause any repaint or layout.
@@ -740,6 +718,12 @@ void RenderStyle::clearCursorList()
rareInheritedData.access()->cursorData = 0;
}
+void RenderStyle::addCallbackSelector(const String& selector)
+{
+ if (!rareNonInheritedData->m_callbackSelectors.contains(selector))
+ rareNonInheritedData.access()->m_callbackSelectors.append(selector);
+}
+
void RenderStyle::clearContent()
{
if (rareNonInheritedData->m_content)
@@ -818,14 +802,14 @@ void RenderStyle::setContent(QuoteType quote, bool add)
rareNonInheritedData.access()->m_content = ContentData::create(quote);
}
-BlendMode RenderStyle::blendMode() const
+blink::WebBlendMode RenderStyle::blendMode() const
{
if (RuntimeEnabledFeatures::cssCompositingEnabled())
- return static_cast<BlendMode>(rareNonInheritedData->m_effectiveBlendMode);
- return BlendModeNormal;
+ return static_cast<blink::WebBlendMode>(rareNonInheritedData->m_effectiveBlendMode);
+ return blink::WebBlendModeNormal;
}
-void RenderStyle::setBlendMode(BlendMode v)
+void RenderStyle::setBlendMode(blink::WebBlendMode v)
{
if (RuntimeEnabledFeatures::cssCompositingEnabled())
rareNonInheritedData.access()->m_effectiveBlendMode = v;
@@ -834,7 +818,7 @@ void RenderStyle::setBlendMode(BlendMode v)
bool RenderStyle::hasBlendMode() const
{
if (RuntimeEnabledFeatures::cssCompositingEnabled())
- return static_cast<BlendMode>(rareNonInheritedData->m_effectiveBlendMode) != BlendModeNormal;
+ return static_cast<blink::WebBlendMode>(rareNonInheritedData->m_effectiveBlendMode) != blink::WebBlendModeNormal;
return false;
}
@@ -851,6 +835,13 @@ void RenderStyle::setIsolation(EIsolation v)
rareNonInheritedData.access()->m_isolation = v;
}
+bool RenderStyle::hasIsolation() const
+{
+ if (RuntimeEnabledFeatures::cssCompositingEnabled())
+ return rareNonInheritedData->m_isolation != IsolationAuto;
+ return false;
+}
+
inline bool requireTransformOrigin(const Vector<RefPtr<TransformOperation> >& transformOperations, RenderStyle::ApplyTransformOrigin applyOrigin)
{
// transform-origin brackets the transform with translate operations.
@@ -861,7 +852,7 @@ inline bool requireTransformOrigin(const Vector<RefPtr<TransformOperation> >& tr
unsigned size = transformOperations.size();
for (unsigned i = 0; i < size; ++i) {
- TransformOperation::OperationType type = transformOperations[i]->getOperationType();
+ TransformOperation::OperationType type = transformOperations[i]->type();
if (type != TransformOperation::TranslateX
&& type != TransformOperation::TranslateY
&& type != TransformOperation::Translate
@@ -887,9 +878,9 @@ void RenderStyle::applyTransform(TransformationMatrix& transform, const FloatRec
float offsetY = transformOriginY().type() == Percent ? boundingBox.y() : 0;
if (applyTransformOrigin) {
- transform.translate3d(floatValueForLength(transformOriginX(), boundingBox.width()) + offsetX,
- floatValueForLength(transformOriginY(), boundingBox.height()) + offsetY,
- transformOriginZ());
+ transform.translate3d(floatValueForLength(transformOriginX(), boundingBox.width(), 0) + offsetX,
+ floatValueForLength(transformOriginY(), boundingBox.height(), 0) + offsetY,
+ transformOriginZ());
}
unsigned size = transformOperations.size();
@@ -897,36 +888,20 @@ void RenderStyle::applyTransform(TransformationMatrix& transform, const FloatRec
transformOperations[i]->apply(transform, boundingBox.size());
if (applyTransformOrigin) {
- transform.translate3d(-floatValueForLength(transformOriginX(), boundingBox.width()) - offsetX,
- -floatValueForLength(transformOriginY(), boundingBox.height()) - offsetY,
- -transformOriginZ());
+ transform.translate3d(-floatValueForLength(transformOriginX(), boundingBox.width(), 0) - offsetX,
+ -floatValueForLength(transformOriginY(), boundingBox.height(), 0) - offsetY,
+ -transformOriginZ());
}
}
-void RenderStyle::setTextShadow(PassOwnPtr<ShadowData> shadowData, bool add)
+void RenderStyle::setTextShadow(PassRefPtr<ShadowList> s)
{
- ASSERT(!shadowData || (!shadowData->spread() && shadowData->style() == Normal));
-
- StyleRareInheritedData* rareData = rareInheritedData.access();
- if (!add) {
- rareData->textShadow = shadowData;
- return;
- }
-
- shadowData->setNext(rareData->textShadow.release());
- rareData->textShadow = shadowData;
+ rareInheritedData.access()->textShadow = s;
}
-void RenderStyle::setBoxShadow(PassOwnPtr<ShadowData> shadowData, bool add)
+void RenderStyle::setBoxShadow(PassRefPtr<ShadowList> s)
{
- StyleRareNonInheritedData* rareData = rareNonInheritedData.access();
- if (!add) {
- rareData->m_boxShadow = shadowData;
- return;
- }
-
- shadowData->setNext(rareData->m_boxShadow.release());
- rareData->m_boxShadow = shadowData;
+ rareNonInheritedData.access()->m_boxShadow = s;
}
static RoundedRect::Radii calcRadiiFor(const BorderData& border, IntSize size, RenderView* renderView)
@@ -1287,72 +1262,80 @@ void RenderStyle::setFontSize(float size)
font().update(currentFontSelector);
}
-void RenderStyle::getShadowExtent(const ShadowData* shadow, LayoutUnit &top, LayoutUnit &right, LayoutUnit &bottom, LayoutUnit &left) const
+void RenderStyle::getShadowExtent(const ShadowList* shadowList, LayoutUnit &top, LayoutUnit &right, LayoutUnit &bottom, LayoutUnit &left) const
{
top = 0;
right = 0;
bottom = 0;
left = 0;
- for ( ; shadow; shadow = shadow->next()) {
- if (shadow->style() == Inset)
+ size_t shadowCount = shadowList ? shadowList->shadows().size() : 0;
+ for (size_t i = 0; i < shadowCount; ++i) {
+ const ShadowData& shadow = shadowList->shadows()[i];
+ if (shadow.style() == Inset)
continue;
- int blurAndSpread = shadow->blur() + shadow->spread();
+ int blurAndSpread = shadow.blur() + shadow.spread();
- top = min<LayoutUnit>(top, shadow->y() - blurAndSpread);
- right = max<LayoutUnit>(right, shadow->x() + blurAndSpread);
- bottom = max<LayoutUnit>(bottom, shadow->y() + blurAndSpread);
- left = min<LayoutUnit>(left, shadow->x() - blurAndSpread);
+ top = min<LayoutUnit>(top, shadow.y() - blurAndSpread);
+ right = max<LayoutUnit>(right, shadow.x() + blurAndSpread);
+ bottom = max<LayoutUnit>(bottom, shadow.y() + blurAndSpread);
+ left = min<LayoutUnit>(left, shadow.x() - blurAndSpread);
}
}
-LayoutBoxExtent RenderStyle::getShadowInsetExtent(const ShadowData* shadow) const
+LayoutBoxExtent RenderStyle::getShadowInsetExtent(const ShadowList* shadowList) const
{
LayoutUnit top = 0;
LayoutUnit right = 0;
LayoutUnit bottom = 0;
LayoutUnit left = 0;
- for ( ; shadow; shadow = shadow->next()) {
- if (shadow->style() == Normal)
+ size_t shadowCount = shadowList ? shadowList->shadows().size() : 0;
+ for (size_t i = 0; i < shadowCount; ++i) {
+ const ShadowData& shadow = shadowList->shadows()[i];
+ if (shadow.style() == Normal)
continue;
- int blurAndSpread = shadow->blur() + shadow->spread();
- top = max<LayoutUnit>(top, shadow->y() + blurAndSpread);
- right = min<LayoutUnit>(right, shadow->x() - blurAndSpread);
- bottom = min<LayoutUnit>(bottom, shadow->y() - blurAndSpread);
- left = max<LayoutUnit>(left, shadow->x() + blurAndSpread);
+ int blurAndSpread = shadow.blur() + shadow.spread();
+ top = max<LayoutUnit>(top, shadow.y() + blurAndSpread);
+ right = min<LayoutUnit>(right, shadow.x() - blurAndSpread);
+ bottom = min<LayoutUnit>(bottom, shadow.y() - blurAndSpread);
+ left = max<LayoutUnit>(left, shadow.x() + blurAndSpread);
}
return LayoutBoxExtent(top, right, bottom, left);
}
-void RenderStyle::getShadowHorizontalExtent(const ShadowData* shadow, LayoutUnit &left, LayoutUnit &right) const
+void RenderStyle::getShadowHorizontalExtent(const ShadowList* shadowList, LayoutUnit &left, LayoutUnit &right) const
{
left = 0;
right = 0;
- for ( ; shadow; shadow = shadow->next()) {
- if (shadow->style() == Inset)
+ size_t shadowCount = shadowList ? shadowList->shadows().size() : 0;
+ for (size_t i = 0; i < shadowCount; ++i) {
+ const ShadowData& shadow = shadowList->shadows()[i];
+ if (shadow.style() == Inset)
continue;
- int blurAndSpread = shadow->blur() + shadow->spread();
+ int blurAndSpread = shadow.blur() + shadow.spread();
- left = min<LayoutUnit>(left, shadow->x() - blurAndSpread);
- right = max<LayoutUnit>(right, shadow->x() + blurAndSpread);
+ left = min<LayoutUnit>(left, shadow.x() - blurAndSpread);
+ right = max<LayoutUnit>(right, shadow.x() + blurAndSpread);
}
}
-void RenderStyle::getShadowVerticalExtent(const ShadowData* shadow, LayoutUnit &top, LayoutUnit &bottom) const
+void RenderStyle::getShadowVerticalExtent(const ShadowList* shadowList, LayoutUnit &top, LayoutUnit &bottom) const
{
top = 0;
bottom = 0;
- for ( ; shadow; shadow = shadow->next()) {
- if (shadow->style() == Inset)
+ size_t shadowCount = shadowList ? shadowList->shadows().size() : 0;
+ for (size_t i = 0; i < shadowCount; ++i) {
+ const ShadowData& shadow = shadowList->shadows()[i];
+ if (shadow.style() == Inset)
continue;
- int blurAndSpread = shadow->blur() + shadow->spread();
+ int blurAndSpread = shadow.blur() + shadow.spread();
- top = min<LayoutUnit>(top, shadow->y() - blurAndSpread);
- bottom = max<LayoutUnit>(bottom, shadow->y() + blurAndSpread);
+ top = min<LayoutUnit>(top, shadow.y() - blurAndSpread);
+ bottom = max<LayoutUnit>(bottom, shadow.y() + blurAndSpread);
}
}
@@ -1611,24 +1594,18 @@ void RenderStyle::setBorderImageSlices(LengthBox slices)
surround.access()->border.m_image.setImageSlices(slices);
}
-void RenderStyle::setBorderImageWidth(LengthBox slices)
+void RenderStyle::setBorderImageWidth(const BorderImageLengthBox& slices)
{
if (surround->border.m_image.borderSlices() == slices)
return;
surround.access()->border.m_image.setBorderSlices(slices);
}
-void RenderStyle::setBorderImageOutset(LengthBox outset)
+void RenderStyle::setBorderImageOutset(const BorderImageLengthBox& outset)
{
if (surround->border.m_image.outset() == outset)
return;
surround.access()->border.m_image.setOutset(outset);
}
-ShapeValue* RenderStyle::initialShapeInside()
-{
- DEFINE_STATIC_LOCAL(RefPtr<ShapeValue>, sOutsideValue, (ShapeValue::createOutsideValue()));
- return sOutsideValue.get();
-}
-
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/style/RenderStyle.h b/chromium/third_party/WebKit/Source/core/rendering/style/RenderStyle.h
index ce0e7524c9c..f405b951fbe 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/style/RenderStyle.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/style/RenderStyle.h
@@ -26,23 +26,10 @@
#define RenderStyle_h
#include "CSSPropertyNames.h"
+#include "core/css/CSSLengthFunctions.h"
#include "core/css/CSSLineBoxContainValue.h"
#include "core/css/CSSPrimitiveValue.h"
-#include "core/css/LengthFunctions.h"
-#include "core/platform/Length.h"
-#include "core/platform/LengthBox.h"
-#include "core/platform/LengthSize.h"
-#include "core/platform/ThemeTypes.h"
#include "core/platform/animation/CSSAnimationDataList.h"
-#include "core/platform/graphics/Color.h"
-#include "core/platform/graphics/FontBaseline.h"
-#include "core/platform/graphics/FontDescription.h"
-#include "core/platform/graphics/GraphicsTypes.h"
-#include "core/platform/graphics/LayoutBoxExtent.h"
-#include "core/platform/graphics/RoundedRect.h"
-#include "core/platform/graphics/transforms/TransformOperations.h"
-#include "core/platform/text/TextDirection.h"
-#include "core/platform/text/UnicodeBidi.h"
#include "core/rendering/style/BorderValue.h"
#include "core/rendering/style/CounterDirectives.h"
#include "core/rendering/style/DataRef.h"
@@ -51,7 +38,6 @@
#include "core/rendering/style/OutlineValue.h"
#include "core/rendering/style/RenderStyleConstants.h"
#include "core/rendering/style/SVGRenderStyle.h"
-#include "core/rendering/style/ShadowData.h"
#include "core/rendering/style/ShapeValue.h"
#include "core/rendering/style/StyleBackgroundData.h"
#include "core/rendering/style/StyleBoxData.h"
@@ -69,6 +55,19 @@
#include "core/rendering/style/StyleTransformData.h"
#include "core/rendering/style/StyleVisualData.h"
#include "core/svg/SVGPaint.h"
+#include "platform/Length.h"
+#include "platform/LengthBox.h"
+#include "platform/LengthSize.h"
+#include "platform/ThemeTypes.h"
+#include "platform/fonts/FontBaseline.h"
+#include "platform/fonts/FontDescription.h"
+#include "platform/geometry/LayoutBoxExtent.h"
+#include "platform/geometry/RoundedRect.h"
+#include "platform/graphics/Color.h"
+#include "platform/graphics/GraphicsTypes.h"
+#include "platform/text/TextDirection.h"
+#include "platform/text/UnicodeBidi.h"
+#include "platform/transforms/TransformOperations.h"
#include "wtf/Forward.h"
#include "wtf/OwnPtr.h"
#include "wtf/RefCounted.h"
@@ -98,7 +97,7 @@ class Font;
class FontMetrics;
class IntRect;
class Pair;
-class ShadowData;
+class ShadowList;
class StyleImage;
class StyleInheritedData;
class StyleResolver;
@@ -117,9 +116,15 @@ class RenderStyle: public RefCounted<RenderStyle> {
friend class CSSComputedStyleDeclaration; // Ignores visited styles, so needs to be able to see unvisited info.
friend class PropertyWrapperMaybeInvalidColor; // Used by CSS animations. We can't allow them to animate based off visited colors.
friend class StyleBuilderFunctions; // Sets color styles
- friend class StyleBuilder; // FIXME: Revove this! StyleBuilder::oldApplyProperty reads color().
- friend class StyleResolver; // Sets members directly.
friend class CachedUAStyle; // Saves Border/Background information for later comparison.
+
+ // FIXME: When we stop resolving currentColor at style time, these can be removed.
+ friend class CSSToStyleMap;
+ friend class FilterOperationResolver;
+ friend class StyleBuilderConverter;
+ friend class StyleBuilder;
+ friend class StyleResolverState;
+ friend class StyleResolver;
protected:
// non-inherited attributes
@@ -210,6 +215,7 @@ protected:
&& _page_break_after == other._page_break_after
&& _page_break_inside == other._page_break_inside
&& _styleType == other._styleType
+ && _affectedByFocus == other._affectedByFocus
&& _affectedByHover == other._affectedByHover
&& _affectedByActive == other._affectedByActive
&& _affectedByDrag == other._affectedByDrag
@@ -251,6 +257,8 @@ protected:
unsigned firstChildState : 1;
unsigned lastChildState : 1;
+ bool affectedByFocus() const { return _affectedByFocus; }
+ void setAffectedByFocus(bool value) { _affectedByFocus = value; }
bool affectedByHover() const { return _affectedByHover; }
void setAffectedByHover(bool value) { _affectedByHover = value; }
bool affectedByActive() const { return _affectedByActive; }
@@ -260,12 +268,13 @@ protected:
bool isLink() const { return _isLink; }
void setIsLink(bool value) { _isLink = value; }
private:
+ unsigned _affectedByFocus : 1;
unsigned _affectedByHover : 1;
unsigned _affectedByActive : 1;
unsigned _affectedByDrag : 1;
unsigned _isLink : 1;
// If you add more style bits here, you will also need to update RenderStyle::copyNonInheritedFrom()
- // 61 bits
+ // 60 bits
} noninherited_flags;
// !END SYNC!
@@ -312,6 +321,7 @@ protected:
noninherited_flags.emptyState = false;
noninherited_flags.firstChildState = false;
noninherited_flags.lastChildState = false;
+ noninherited_flags.setAffectedByFocus(false);
noninherited_flags.setAffectedByHover(false);
noninherited_flags.setAffectedByActive(false);
noninherited_flags.setAffectedByDrag(false);
@@ -355,10 +365,12 @@ public:
void setVariable(const AtomicString& name, const String& value) { rareInheritedData.access()->m_variables.access()->setVariable(name, value); }
const HashMap<AtomicString, String>* variables() { return &(rareInheritedData->m_variables->m_data); }
+ bool affectedByFocus() const { return noninherited_flags.affectedByFocus(); }
bool affectedByHover() const { return noninherited_flags.affectedByHover(); }
bool affectedByActive() const { return noninherited_flags.affectedByActive(); }
bool affectedByDrag() const { return noninherited_flags.affectedByDrag(); }
+ void setAffectedByFocus() { noninherited_flags.setAffectedByFocus(true); }
void setAffectedByHover() { noninherited_flags.setAffectedByHover(true); }
void setAffectedByActive() { noninherited_flags.setAffectedByActive(true); }
void setAffectedByDrag() { noninherited_flags.setAffectedByDrag(true); }
@@ -473,8 +485,8 @@ public:
const NinePieceImage& borderImage() const { return surround->border.image(); }
StyleImage* borderImageSource() const { return surround->border.image().image(); }
LengthBox borderImageSlices() const { return surround->border.image().imageSlices(); }
- LengthBox borderImageWidth() const { return surround->border.image().borderSlices(); }
- LengthBox borderImageOutset() const { return surround->border.image().outset(); }
+ const BorderImageLengthBox& borderImageWidth() const { return surround->border.image().borderSlices(); }
+ const BorderImageLengthBox& borderImageOutset() const { return surround->border.image().outset(); }
LengthSize borderTopLeftRadius() const { return surround->border.topLeft(); }
LengthSize borderTopRightRadius() const { return surround->border.topRight(); }
@@ -543,12 +555,11 @@ public:
TextIndentLine textIndentLine() const { return static_cast<TextIndentLine>(rareInheritedData->m_textIndentLine); }
ETextAlign textAlign() const { return static_cast<ETextAlign>(inherited_flags._text_align); }
TextAlignLast textAlignLast() const { return static_cast<TextAlignLast>(rareInheritedData->m_textAlignLast); }
+ TextJustify textJustify() const { return static_cast<TextJustify>(rareInheritedData->m_textJustify); }
ETextTransform textTransform() const { return static_cast<ETextTransform>(inherited_flags._text_transform); }
TextDecoration textDecorationsInEffect() const { return static_cast<TextDecoration>(inherited_flags._text_decorations); }
TextDecoration textDecoration() const { return static_cast<TextDecoration>(visual->textDecoration); }
-#if ENABLE(CSS3_TEXT)
TextUnderlinePosition textUnderlinePosition() const { return static_cast<TextUnderlinePosition>(rareInheritedData->m_textUnderlinePosition); }
-#endif // CSS3_TEXT
TextDecorationStyle textDecorationStyle() const { return static_cast<TextDecorationStyle>(rareNonInheritedData->m_textDecorationStyle); }
float wordSpacing() const;
float letterSpacing() const;
@@ -644,8 +655,13 @@ public:
LengthSize maskSizeLength() const { return rareNonInheritedData->m_mask.sizeLength(); }
FillLayer* accessMaskLayers() { return &(rareNonInheritedData.access()->m_mask); }
const FillLayer* maskLayers() const { return &(rareNonInheritedData->m_mask); }
+
const NinePieceImage& maskBoxImage() const { return rareNonInheritedData->m_maskBoxImage; }
StyleImage* maskBoxImageSource() const { return rareNonInheritedData->m_maskBoxImage.image(); }
+ LengthBox maskBoxImageSlices() const { return rareNonInheritedData->m_maskBoxImage.imageSlices(); }
+ bool maskBoxImageSlicesFill() const { return rareNonInheritedData->m_maskBoxImage.fill(); }
+ const BorderImageLengthBox& maskBoxImageWidth() const { return rareNonInheritedData->m_maskBoxImage.borderSlices(); }
+ const BorderImageLengthBox& maskBoxImageOutset() const { return rareNonInheritedData->m_maskBoxImage.outset(); }
EBorderCollapse borderCollapse() const { return static_cast<EBorderCollapse>(inherited_flags._border_collapse); }
short horizontalBorderSpacing() const;
@@ -703,7 +719,7 @@ public:
return m_background->outline().offset();
}
- const ShadowData* textShadow() const { return rareInheritedData->textShadow.get(); }
+ ShadowList* textShadow() const { return rareInheritedData->textShadow.get(); }
void getTextShadowExtent(LayoutUnit& top, LayoutUnit& right, LayoutUnit& bottom, LayoutUnit& left) const { getShadowExtent(textShadow(), top, right, bottom, left); }
void getTextShadowHorizontalExtent(LayoutUnit& left, LayoutUnit& right) const { getShadowHorizontalExtent(textShadow(), left, right); }
void getTextShadowVerticalExtent(LayoutUnit& top, LayoutUnit& bottom) const { getShadowVerticalExtent(textShadow(), top, bottom); }
@@ -728,6 +744,7 @@ public:
EBoxPack boxPack() const { return static_cast<EBoxPack>(rareNonInheritedData->m_deprecatedFlexibleBox->pack); }
int order() const { return rareNonInheritedData->m_order; }
+ const Vector<String>& callbackSelectors() const { return rareNonInheritedData->m_callbackSelectors; }
float flexGrow() const { return rareNonInheritedData->m_flexibleBox->m_flexGrow; }
float flexShrink() const { return rareNonInheritedData->m_flexibleBox->m_flexShrink; }
Length flexBasis() const { return rareNonInheritedData->m_flexibleBox->m_flexBasis; }
@@ -758,7 +775,7 @@ public:
const GridPosition& gridRowStart() const { return rareNonInheritedData->m_gridItem->m_gridRowStart; }
const GridPosition& gridRowEnd() const { return rareNonInheritedData->m_gridItem->m_gridRowEnd; }
- const ShadowData* boxShadow() const { return rareNonInheritedData->m_boxShadow.get(); }
+ ShadowList* boxShadow() const { return rareNonInheritedData->m_boxShadow.get(); }
void getBoxShadowExtent(LayoutUnit& top, LayoutUnit& right, LayoutUnit& bottom, LayoutUnit& left) const { getShadowExtent(boxShadow(), top, right, bottom, left); }
LayoutBoxExtent getBoxShadowInsetExtent() const { return getShadowInsetExtent(boxShadow()); }
void getBoxShadowHorizontalExtent(LayoutUnit& left, LayoutUnit& right) const { getShadowHorizontalExtent(boxShadow(), left, right); }
@@ -800,6 +817,7 @@ public:
bool hasAutoColumnCount() const { return rareNonInheritedData->m_multiCol->m_autoCount; }
bool specifiesAutoColumns() const { return hasAutoColumnCount() && hasAutoColumnWidth(); }
bool specifiesColumns() const { return !hasAutoColumnCount() || !hasAutoColumnWidth() || !hasInlineColumnAxis(); }
+ ColumnFill columnFill() const { return static_cast<ColumnFill>(rareNonInheritedData->m_multiCol->m_fill); }
float columnGap() const { return rareNonInheritedData->m_multiCol->m_gap; }
bool hasNormalColumnGap() const { return rareNonInheritedData->m_multiCol->m_normalGap; }
EBorderStyle columnRuleStyle() const { return rareNonInheritedData->m_multiCol->m_rule.style(); }
@@ -849,6 +867,7 @@ public:
// End CSS3 Getters
const AtomicString& flowThread() const { return rareNonInheritedData->m_flowThread; }
+ bool hasFlowFrom() const { return !rareNonInheritedData->m_regionThread.isNull(); }
const AtomicString& regionThread() const { return rareNonInheritedData->m_regionThread; }
RegionFragment regionFragment() const { return static_cast<RegionFragment>(rareNonInheritedData->m_regionFragment); }
@@ -904,16 +923,18 @@ public:
const FilterOperations& filter() const { return rareNonInheritedData->m_filter->m_operations; }
bool hasFilter() const { return !rareNonInheritedData->m_filter->m_operations.operations().isEmpty(); }
- BlendMode blendMode() const;
- void setBlendMode(BlendMode v);
+ blink::WebBlendMode blendMode() const;
+ void setBlendMode(blink::WebBlendMode v);
bool hasBlendMode() const;
EIsolation isolation() const;
void setIsolation(EIsolation v);
+ bool hasIsolation() const;
bool shouldPlaceBlockDirectionScrollbarOnLogicalLeft() const { return !isLeftToRightDirection() && isHorizontalWritingMode(); }
TouchAction touchAction() const { return static_cast<TouchAction>(rareNonInheritedData->m_touchAction); }
+ TouchActionDelay touchActionDelay() const { return static_cast<TouchActionDelay>(rareInheritedData->m_touchActionDelay); }
// attribute setter methods
@@ -978,8 +999,8 @@ public:
void setBorderImage(const NinePieceImage& b) { SET_VAR(surround, border.m_image, b); }
void setBorderImageSource(PassRefPtr<StyleImage>);
void setBorderImageSlices(LengthBox);
- void setBorderImageWidth(LengthBox);
- void setBorderImageOutset(LengthBox);
+ void setBorderImageWidth(const BorderImageLengthBox&);
+ void setBorderImageOutset(const BorderImageLengthBox&);
void setBorderTopLeftRadius(LengthSize s) { SET_VAR(surround, border.m_topLeft, s); }
void setBorderTopRightRadius(LengthSize s) { SET_VAR(surround, border.m_topRight, s); }
@@ -1056,13 +1077,12 @@ public:
void setTextIndentLine(TextIndentLine v) { SET_VAR(rareInheritedData, m_textIndentLine, v); }
void setTextAlign(ETextAlign v) { inherited_flags._text_align = v; }
void setTextAlignLast(TextAlignLast v) { SET_VAR(rareInheritedData, m_textAlignLast, v); }
+ void setTextJustify(TextJustify v) { SET_VAR(rareInheritedData, m_textJustify, v); }
void setTextTransform(ETextTransform v) { inherited_flags._text_transform = v; }
void addToTextDecorationsInEffect(TextDecoration v) { inherited_flags._text_decorations |= v; }
void setTextDecorationsInEffect(TextDecoration v) { inherited_flags._text_decorations = v; }
void setTextDecoration(TextDecoration v) { SET_VAR(visual, textDecoration, v); }
-#if ENABLE(CSS3_TEXT)
void setTextUnderlinePosition(TextUnderlinePosition v) { SET_VAR(rareInheritedData, m_textUnderlinePosition, v); }
-#endif // CSS3_TEXT
void setTextDecorationStyle(TextDecorationStyle v) { SET_VAR(rareNonInheritedData, m_textDecorationStyle, v); }
void setDirection(TextDirection v) { inherited_flags._direction = v; }
void setLineHeight(Length specifiedLineHeight);
@@ -1103,6 +1123,22 @@ public:
void setMaskBoxImage(const NinePieceImage& b) { SET_VAR(rareNonInheritedData, m_maskBoxImage, b); }
void setMaskBoxImageSource(PassRefPtr<StyleImage> v) { rareNonInheritedData.access()->m_maskBoxImage.setImage(v); }
+ void setMaskBoxImageSlices(LengthBox slices)
+ {
+ rareNonInheritedData.access()->m_maskBoxImage.setImageSlices(slices);
+ }
+ void setMaskBoxImageSlicesFill(bool fill)
+ {
+ rareNonInheritedData.access()->m_maskBoxImage.setFill(fill);
+ }
+ void setMaskBoxImageWidth(const BorderImageLengthBox& slices)
+ {
+ rareNonInheritedData.access()->m_maskBoxImage.setBorderSlices(slices);
+ }
+ void setMaskBoxImageOutset(const BorderImageLengthBox& outset)
+ {
+ rareNonInheritedData.access()->m_maskBoxImage.setOutset(outset);
+ }
void setMaskXPosition(Length length) { SET_VAR(rareNonInheritedData, m_mask.m_xPosition, length); }
void setMaskYPosition(Length length) { SET_VAR(rareNonInheritedData, m_mask.m_yPosition, length); }
void setMaskSize(LengthSize s) { SET_VAR(rareNonInheritedData, m_mask.m_sizeLength, s); }
@@ -1165,7 +1201,7 @@ public:
// CSS3 Setters
void setOutlineOffset(int v) { SET_VAR(m_background, m_outline.m_offset, v); }
- void setTextShadow(PassOwnPtr<ShadowData>, bool add = false);
+ void setTextShadow(PassRefPtr<ShadowList>);
void setTextStrokeColor(const Color& c) { SET_VAR(rareInheritedData, textStrokeColor, c); }
void setTextStrokeWidth(float w) { SET_VAR(rareInheritedData, textStrokeWidth, w); }
void setTextFillColor(const Color& c) { SET_VAR(rareInheritedData, textFillColor, c); }
@@ -1181,13 +1217,14 @@ public:
void setBoxOrdinalGroup(unsigned int og) { SET_VAR(rareNonInheritedData.access()->m_deprecatedFlexibleBox, ordinal_group, og); }
void setBoxOrient(EBoxOrient o) { SET_VAR(rareNonInheritedData.access()->m_deprecatedFlexibleBox, orient, o); }
void setBoxPack(EBoxPack p) { SET_VAR(rareNonInheritedData.access()->m_deprecatedFlexibleBox, pack, p); }
- void setBoxShadow(PassOwnPtr<ShadowData>, bool add = false);
+ void setBoxShadow(PassRefPtr<ShadowList>);
void setBoxReflect(PassRefPtr<StyleReflection> reflect) { if (rareNonInheritedData->m_boxReflect != reflect) rareNonInheritedData.access()->m_boxReflect = reflect; }
void setBoxSizing(EBoxSizing s) { SET_VAR(m_box, m_boxSizing, s); }
void setFlexGrow(float f) { SET_VAR(rareNonInheritedData.access()->m_flexibleBox, m_flexGrow, f); }
void setFlexShrink(float f) { SET_VAR(rareNonInheritedData.access()->m_flexibleBox, m_flexShrink, f); }
void setFlexBasis(Length length) { SET_VAR(rareNonInheritedData.access()->m_flexibleBox, m_flexBasis, length); }
void setOrder(int o) { SET_VAR(rareNonInheritedData, m_order, o); }
+ void addCallbackSelector(const String& selector);
void setAlignContent(EAlignContent p) { SET_VAR(rareNonInheritedData, m_alignContent, p); }
void setAlignItems(EAlignItems a) { SET_VAR(rareNonInheritedData, m_alignItems, a); }
void setAlignSelf(EAlignItems a) { SET_VAR(rareNonInheritedData, m_alignSelf, a); }
@@ -1238,6 +1275,7 @@ public:
void setHasAutoColumnWidth() { SET_VAR(rareNonInheritedData.access()->m_multiCol, m_autoWidth, true); SET_VAR(rareNonInheritedData.access()->m_multiCol, m_width, 0); }
void setColumnCount(unsigned short c) { SET_VAR(rareNonInheritedData.access()->m_multiCol, m_autoCount, false); SET_VAR(rareNonInheritedData.access()->m_multiCol, m_count, c); }
void setHasAutoColumnCount() { SET_VAR(rareNonInheritedData.access()->m_multiCol, m_autoCount, true); SET_VAR(rareNonInheritedData.access()->m_multiCol, m_count, 0); }
+ void setColumnFill(ColumnFill columnFill) { SET_VAR(rareNonInheritedData.access()->m_multiCol, m_fill, columnFill); }
void setColumnGap(float f) { SET_VAR(rareNonInheritedData.access()->m_multiCol, m_normalGap, false); SET_VAR(rareNonInheritedData.access()->m_multiCol, m_gap, f); }
void setHasNormalColumnGap() { SET_VAR(rareNonInheritedData.access()->m_multiCol, m_normalGap, true); SET_VAR(rareNonInheritedData.access()->m_multiCol, m_gap, 0); }
void setColumnRuleColor(const Color& c) { SET_BORDERVALUE_COLOR(rareNonInheritedData.access()->m_multiCol, m_rule, c); }
@@ -1321,6 +1359,7 @@ public:
void setTapHighlightColor(const Color& c) { SET_VAR(rareInheritedData, tapHighlightColor, c); }
void setTextSecurity(ETextSecurity aTextSecurity) { SET_VAR(rareInheritedData, textSecurity, aTextSecurity); }
void setTouchAction(TouchAction t) { SET_VAR(rareNonInheritedData, m_touchAction, t); }
+ void setTouchActionDelay(TouchActionDelay t) { SET_VAR(rareInheritedData, m_touchActionDelay, t); }
const SVGRenderStyle* svgStyle() const { return m_svgStyle.get(); }
SVGRenderStyle* accessSVGStyle() { return m_svgStyle.access(); }
@@ -1383,7 +1422,7 @@ public:
}
ShapeValue* shapeOutside() const { return rareNonInheritedData->m_shapeOutside.get(); }
- static ShapeValue* initialShapeInside();
+ static ShapeValue* initialShapeInside() { return 0; }
static ShapeValue* initialShapeOutside() { return 0; }
void setClipPath(PassRefPtr<ClipPathOperation> operation)
@@ -1403,6 +1442,14 @@ public:
void setShapeMargin(Length shapeMargin) { SET_VAR(rareNonInheritedData, m_shapeMargin, shapeMargin); }
static Length initialShapeMargin() { return Length(0, Fixed); }
+ float shapeImageThreshold() const { return rareNonInheritedData->m_shapeImageThreshold; }
+ void setShapeImageThreshold(float shapeImageThreshold)
+ {
+ float clampedShapeImageThreshold = clampTo<float>(shapeImageThreshold, 0, 1);
+ SET_VAR(rareNonInheritedData, m_shapeImageThreshold, clampedShapeImageThreshold);
+ }
+ static float initialShapeImageThreshold() { return 0; }
+
bool hasContent() const { return contentData(); }
const ContentData* contentData() const { return rareNonInheritedData->m_content.get(); }
bool contentDataEquivalent(const RenderStyle* otherStyle) const { return const_cast<RenderStyle*>(this)->rareNonInheritedData->contentDataEquivalent(*const_cast<RenderStyle*>(otherStyle)->rareNonInheritedData); }
@@ -1449,6 +1496,8 @@ public:
bool unique() const { return noninherited_flags.unique; }
void setUnique() { noninherited_flags.unique = true; }
+ bool isSharable() const;
+
bool emptyState() const { return noninherited_flags.emptyState; }
void setEmptyState(bool b) { setUnique(); noninherited_flags.emptyState = b; }
bool firstChildState() const { return noninherited_flags.firstChildState; }
@@ -1517,10 +1566,9 @@ public:
static Length initialLineHeight() { return Length(-100.0, Percent); }
static ETextAlign initialTextAlign() { return TASTART; }
static TextAlignLast initialTextAlignLast() { return TextAlignLastAuto; }
+ static TextJustify initialTextJustify() { return TextJustifyAuto; }
static TextDecoration initialTextDecoration() { return TextDecorationNone; }
-#if ENABLE(CSS3_TEXT)
static TextUnderlinePosition initialTextUnderlinePosition() { return TextUnderlinePositionAuto; }
-#endif // CSS3_TEXT
static TextDecorationStyle initialTextDecorationStyle() { return TextDecorationStyleSolid; }
static float initialZoom() { return 1.0f; }
static int initialOutlineOffset() { return 0; }
@@ -1573,6 +1621,7 @@ public:
static Order initialRTLOrdering() { return LogicalOrder; }
static float initialTextStrokeWidth() { return 0; }
static unsigned short initialColumnCount() { return 1; }
+ static ColumnFill initialColumnFill() { return ColumnFillBalance; }
static ColumnSpan initialColumnSpan() { return ColumnSpanNone; }
static const TransformOperations& initialTransform() { DEFINE_STATIC_LOCAL(TransformOperations, ops, ()); return ops; }
static Length initialTransformOriginX() { return Length(50.0, Percent); }
@@ -1601,6 +1650,9 @@ public:
static StyleImage* initialMaskBoxImageSource() { return 0; }
static PrintColorAdjust initialPrintColorAdjust() { return PrintColorAdjustEconomy; }
static TouchAction initialTouchAction() { return TouchActionAuto; }
+ static TouchActionDelay initialTouchActionDelay() { return TouchActionDelayScript; }
+ static ShadowList* initialBoxShadow() { return 0; }
+ static ShadowList* initialTextShadow() { return 0; }
// The initial value is 'none' for grid tracks.
static Vector<GridTrackSize> initialGridDefinitionColumns() { return Vector<GridTrackSize>(); }
@@ -1647,7 +1699,7 @@ public:
static ETextSecurity initialTextSecurity() { return TSNONE; }
static Color initialTapHighlightColor();
static const FilterOperations& initialFilter() { DEFINE_STATIC_LOCAL(FilterOperations, ops, ()); return ops; }
- static BlendMode initialBlendMode() { return BlendModeNormal; }
+ static blink::WebBlendMode initialBlendMode() { return blink::WebBlendModeNormal; }
static EIsolation initialIsolation() { return IsolationAuto; }
private:
void setVisitedLinkColor(const Color&);
@@ -1664,15 +1716,15 @@ private:
void setVisitedLinkTextStrokeColor(const Color& v) { SET_VAR(rareInheritedData, visitedLinkTextStrokeColor, v); }
void inheritUnicodeBidiFrom(const RenderStyle* parent) { noninherited_flags._unicodeBidi = parent->noninherited_flags._unicodeBidi; }
- void getShadowExtent(const ShadowData*, LayoutUnit& top, LayoutUnit& right, LayoutUnit& bottom, LayoutUnit& left) const;
- LayoutBoxExtent getShadowInsetExtent(const ShadowData*) const;
- void getShadowHorizontalExtent(const ShadowData*, LayoutUnit& left, LayoutUnit& right) const;
- void getShadowVerticalExtent(const ShadowData*, LayoutUnit& top, LayoutUnit& bottom) const;
- void getShadowInlineDirectionExtent(const ShadowData* shadow, LayoutUnit& logicalLeft, LayoutUnit& logicalRight) const
+ void getShadowExtent(const ShadowList*, LayoutUnit& top, LayoutUnit& right, LayoutUnit& bottom, LayoutUnit& left) const;
+ LayoutBoxExtent getShadowInsetExtent(const ShadowList*) const;
+ void getShadowHorizontalExtent(const ShadowList*, LayoutUnit& left, LayoutUnit& right) const;
+ void getShadowVerticalExtent(const ShadowList*, LayoutUnit& top, LayoutUnit& bottom) const;
+ void getShadowInlineDirectionExtent(const ShadowList* shadow, LayoutUnit& logicalLeft, LayoutUnit& logicalRight) const
{
return isHorizontalWritingMode() ? getShadowHorizontalExtent(shadow, logicalLeft, logicalRight) : getShadowVerticalExtent(shadow, logicalLeft, logicalRight);
}
- void getShadowBlockDirectionExtent(const ShadowData* shadow, LayoutUnit& logicalTop, LayoutUnit& logicalBottom) const
+ void getShadowBlockDirectionExtent(const ShadowList* shadow, LayoutUnit& logicalTop, LayoutUnit& logicalBottom) const
{
return isHorizontalWritingMode() ? getShadowVerticalExtent(shadow, logicalTop, logicalBottom) : getShadowHorizontalExtent(shadow, logicalTop, logicalBottom);
}
@@ -1722,11 +1774,11 @@ private:
Color lightingColor() const { return svgStyle()->lightingColor(); }
void appendContent(PassOwnPtr<ContentData>);
+ StyleDifference repaintOnlyDiff(const RenderStyle* other, unsigned& changedContextSensitiveProperties) const;
};
-inline int adjustForAbsoluteZoom(int value, const RenderStyle* style)
+inline int adjustForAbsoluteZoom(int value, float zoomFactor)
{
- double zoomFactor = style->effectiveZoom();
if (zoomFactor == 1)
return value;
// Needed because computeLengthInt truncates (rather than rounds) when scaling up.
@@ -1740,14 +1792,19 @@ inline int adjustForAbsoluteZoom(int value, const RenderStyle* style)
return roundForImpreciseConversion<int>(value / zoomFactor);
}
-inline float adjustFloatForAbsoluteZoom(float value, const RenderStyle* style)
+inline int adjustForAbsoluteZoom(int value, const RenderStyle* style)
{
- return value / style->effectiveZoom();
+ return adjustForAbsoluteZoom(value, style->effectiveZoom());
}
-inline LayoutUnit adjustLayoutUnitForAbsoluteZoom(LayoutUnit value, const RenderStyle* style)
+inline float adjustFloatForAbsoluteZoom(float value, const RenderStyle& style)
{
- return value / style->effectiveZoom();
+ return value / style.effectiveZoom();
+}
+
+inline LayoutUnit adjustLayoutUnitForAbsoluteZoom(LayoutUnit value, const RenderStyle& style)
+{
+ return value / style.effectiveZoom();
}
inline bool RenderStyle::setZoom(float f)
@@ -1767,6 +1824,17 @@ inline bool RenderStyle::setEffectiveZoom(float f)
return true;
}
+inline bool RenderStyle::isSharable() const
+{
+ if (unique())
+ return false;
+ if (hasUniquePseudoStyle())
+ return false;
+ if (transitions() || animations())
+ return false;
+ return true;
+}
+
inline bool RenderStyle::setTextOrientation(TextOrientation textOrientation)
{
if (compareEqual(rareInheritedData->m_textOrientation, textOrientation))
@@ -1776,6 +1844,25 @@ inline bool RenderStyle::setTextOrientation(TextOrientation textOrientation)
return true;
}
+inline bool RenderStyle::hasAnyPublicPseudoStyles() const
+{
+ return PUBLIC_PSEUDOID_MASK & noninherited_flags._pseudoBits;
+}
+
+inline bool RenderStyle::hasPseudoStyle(PseudoId pseudo) const
+{
+ ASSERT(pseudo > NOPSEUDO);
+ ASSERT(pseudo < FIRST_INTERNAL_PSEUDOID);
+ return (1 << (pseudo - 1)) & noninherited_flags._pseudoBits;
+}
+
+inline void RenderStyle::setHasPseudoStyle(PseudoId pseudo)
+{
+ ASSERT(pseudo > NOPSEUDO);
+ ASSERT(pseudo < FIRST_INTERNAL_PSEUDOID);
+ noninherited_flags._pseudoBits |= 1 << (pseudo - 1);
+}
+
} // namespace WebCore
#endif // RenderStyle_h
diff --git a/chromium/third_party/WebKit/Source/core/rendering/style/RenderStyleConstants.h b/chromium/third_party/WebKit/Source/core/rendering/style/RenderStyleConstants.h
index 59c4ab86f5c..45531d20231 100644..100755
--- a/chromium/third_party/WebKit/Source/core/rendering/style/RenderStyleConstants.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/style/RenderStyleConstants.h
@@ -46,7 +46,7 @@ enum PrintColorAdjust {
// (1) StyleDifferenceEqual - The two styles are identical.
// (2) StyleDifferenceRecompositeLayer - The layer needs its position and transform updated, but no repaint.
// (3) StyleDifferenceRepaint - The object just needs to be repainted.
-// (4) StyleDifferenceRepaintIfText - The object needs to be repainted if it contains text.
+// (4) StyleDifferenceRepaintIfTextOrColorChange - The object needs to be repainted if it contains text or properties dependent on color (e.g., border or outline).
// (5) StyleDifferenceRepaintLayer - The layer and its descendant layers needs to be repainted.
// (6) StyleDifferenceLayoutPositionedMovementOnly - Only the position of this positioned object has been updated.
// (7) StyleDifferenceSimplifiedLayout - Only overflow needs to be recomputed.
@@ -56,7 +56,7 @@ enum StyleDifference {
StyleDifferenceEqual,
StyleDifferenceRecompositeLayer,
StyleDifferenceRepaint,
- StyleDifferenceRepaintIfText,
+ StyleDifferenceRepaintIfTextOrColorChange,
StyleDifferenceRepaintLayer,
StyleDifferenceLayoutPositionedMovementOnly,
StyleDifferenceSimplifiedLayout,
@@ -90,6 +90,8 @@ enum PseudoId {
PUBLIC_PSEUDOID_MASK = ((1 << FIRST_INTERNAL_PSEUDOID) - 1) & ~((1 << FIRST_PUBLIC_PSEUDOID) - 1)
};
+enum ColumnFill { ColumnFillBalance, ColumnFillAuto };
+
enum ColumnSpan { ColumnSpanNone = 0, ColumnSpanAll };
enum EBorderCollapse { BSEPARATE = 0, BCOLLAPSE = 1 };
@@ -371,12 +373,15 @@ enum TextAlignLast {
TextAlignLastAuto, TextAlignLastStart, TextAlignLastEnd, TextAlignLastLeft, TextAlignLastRight, TextAlignLastCenter, TextAlignLastJustify
};
-#if ENABLE(CSS3_TEXT)
+enum TextJustify {
+ TextJustifyAuto, TextJustifyNone, TextJustifyInterWord, TextJustifyDistribute
+};
+
enum TextUnderlinePosition {
// FIXME: Implement support for 'under left' and 'under right' values.
- TextUnderlinePositionAuto = 0x1, TextUnderlinePositionAlphabetic = 0x2, TextUnderlinePositionUnder = 0x4
+ TextUnderlinePositionAuto = 0x1,
+ TextUnderlinePositionUnder = 0x2
};
-#endif // CSS3_TEXT
enum EPageBreak {
PBAUTO, PBALWAYS, PBAVOID
@@ -438,7 +443,7 @@ enum ECursor {
// The order of this enum must match the order of the display values in CSSValueKeywords.in.
enum EDisplay {
- INLINE, BLOCK, LIST_ITEM, RUN_IN, COMPACT, INLINE_BLOCK,
+ INLINE, BLOCK, LIST_ITEM, INLINE_BLOCK,
TABLE, INLINE_TABLE, TABLE_ROW_GROUP,
TABLE_HEADER_GROUP, TABLE_FOOTER_GROUP, TABLE_ROW,
TABLE_COLUMN_GROUP, TABLE_COLUMN, TABLE_CELL,
@@ -454,7 +459,8 @@ enum EInsideLink {
enum EPointerEvents {
PE_NONE, PE_AUTO, PE_STROKE, PE_FILL, PE_PAINTED, PE_VISIBLE,
- PE_VISIBLE_STROKE, PE_VISIBLE_FILL, PE_VISIBLE_PAINTED, PE_ALL
+ PE_VISIBLE_STROKE, PE_VISIBLE_FILL, PE_VISIBLE_PAINTED, PE_BOUNDINGBOX,
+ PE_ALL
};
enum ETransformStyle3D {
@@ -509,15 +515,29 @@ enum GridAutoFlow { AutoFlowNone, AutoFlowColumn, AutoFlowRow };
enum DraggableRegionMode { DraggableRegionNone, DraggableRegionDrag, DraggableRegionNoDrag };
-enum TouchAction { TouchActionAuto, TouchActionNone };
+static const size_t TouchActionBits = 3;
+enum TouchAction {
+ TouchActionAuto = 0x0,
+ TouchActionNone = 0x1,
+ TouchActionPanX = 0x2,
+ TouchActionPanY = 0x4
+};
+inline TouchAction operator| (TouchAction a, TouchAction b) { return TouchAction(int(a) | int(b)); }
+inline TouchAction& operator|= (TouchAction& a, TouchAction b) { return a = a | b; }
+inline TouchAction operator& (TouchAction a, TouchAction b) { return TouchAction(int(a) & int(b)); }
+inline TouchAction& operator&= (TouchAction& a, TouchAction b) { return a = a & b; }
enum EIsolation { IsolationAuto, IsolationIsolate };
+enum TouchActionDelay { TouchActionDelayNone, TouchActionDelayScript };
+
// Reasonable maximum to prevent insane font sizes from causing crashes on some platforms (such as Windows).
static const float maximumAllowedFontSize = 1000000.0f;
enum TextIndentLine { TextIndentFirstLine, TextIndentEachLine };
+enum LayoutBox { MarginBox, BorderBox, PaddingBox, ContentBox };
+
} // namespace WebCore
#endif // RenderStyleConstants_h
diff --git a/chromium/third_party/WebKit/Source/core/rendering/style/SVGRenderStyle.cpp b/chromium/third_party/WebKit/Source/core/rendering/style/SVGRenderStyle.cpp
index 7d7498a7e1e..947c39db641 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/style/SVGRenderStyle.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/style/SVGRenderStyle.cpp
@@ -29,7 +29,6 @@
#include "core/rendering/style/SVGRenderStyle.h"
-#include "core/css/CSSValueList.h"
using namespace std;
@@ -209,7 +208,8 @@ StyleDifference SVGRenderStyle::diff(const SVGRenderStyle* other) const
|| svg_inherited_flags._clipRule != other->svg_inherited_flags._clipRule
|| svg_inherited_flags._fillRule != other->svg_inherited_flags._fillRule
|| svg_inherited_flags._colorInterpolation != other->svg_inherited_flags._colorInterpolation
- || svg_inherited_flags._colorInterpolationFilters != other->svg_inherited_flags._colorInterpolationFilters)
+ || svg_inherited_flags._colorInterpolationFilters != other->svg_inherited_flags._colorInterpolationFilters
+ || svg_inherited_flags._paintOrder != other->svg_inherited_flags._paintOrder)
return StyleDifferenceRepaint;
if (svg_noninherited_flags.f.bufferedRendering != other->svg_noninherited_flags.f.bufferedRendering)
diff --git a/chromium/third_party/WebKit/Source/core/rendering/style/SVGRenderStyle.h b/chromium/third_party/WebKit/Source/core/rendering/style/SVGRenderStyle.h
index 658af072370..dba333e1ddf 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/style/SVGRenderStyle.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/style/SVGRenderStyle.h
@@ -25,12 +25,12 @@
#include "bindings/v8/ExceptionStatePlaceholder.h"
#include "core/css/CSSValueList.h"
-#include "core/platform/graphics/GraphicsTypes.h"
-#include "core/platform/graphics/Path.h"
#include "core/rendering/style/DataRef.h"
#include "core/rendering/style/RenderStyleConstants.h"
#include "core/rendering/style/SVGRenderStyleDefs.h"
#include "core/svg/SVGPaint.h"
+#include "platform/graphics/GraphicsTypes.h"
+#include "platform/graphics/Path.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/rendering/style/ShadowData.cpp b/chromium/third_party/WebKit/Source/core/rendering/style/ShadowData.cpp
index 52e391b6eb3..7f81d909f6b 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/style/ShadowData.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/style/ShadowData.cpp
@@ -22,28 +22,12 @@
#include "config.h"
#include "core/rendering/style/ShadowData.h"
-#include "core/platform/graphics/LayoutRect.h"
-
-using namespace std;
+#include "platform/animation/AnimationUtilities.h"
namespace WebCore {
-ShadowData::ShadowData(const ShadowData& o)
- : m_location(o.m_location)
- , m_blur(o.m_blur)
- , m_spread(o.m_spread)
- , m_color(o.m_color)
- , m_style(o.m_style)
- , m_next(o.m_next ? adoptPtr(new ShadowData(*o.m_next)) : nullptr)
-{
-}
-
bool ShadowData::operator==(const ShadowData& o) const
{
- if ((m_next && !o.m_next) || (!m_next && o.m_next)
- || (m_next && o.m_next && *m_next != *o.m_next))
- return false;
-
return m_location == o.m_location
&& m_blur == o.m_blur
&& m_spread == o.m_spread
@@ -51,45 +35,16 @@ bool ShadowData::operator==(const ShadowData& o) const
&& m_color == o.m_color;
}
-static inline void calculateShadowExtent(const ShadowData* shadow, int additionalOutlineSize, int& shadowLeft, int& shadowRight, int& shadowTop, int& shadowBottom)
-{
- do {
- int blurAndSpread = shadow->blur() + shadow->spread() + additionalOutlineSize;
- if (shadow->style() == Normal) {
- shadowLeft = min(shadow->x() - blurAndSpread, shadowLeft);
- shadowRight = max(shadow->x() + blurAndSpread, shadowRight);
- shadowTop = min(shadow->y() - blurAndSpread, shadowTop);
- shadowBottom = max(shadow->y() + blurAndSpread, shadowBottom);
- }
-
- shadow = shadow->next();
- } while (shadow);
-}
-
-void ShadowData::adjustRectForShadow(LayoutRect& rect, int additionalOutlineSize) const
+ShadowData ShadowData::blend(const ShadowData& from, double progress) const
{
- int shadowLeft = 0;
- int shadowRight = 0;
- int shadowTop = 0;
- int shadowBottom = 0;
- calculateShadowExtent(this, additionalOutlineSize, shadowLeft, shadowRight, shadowTop, shadowBottom);
-
- rect.move(shadowLeft, shadowTop);
- rect.setWidth(rect.width() - shadowLeft + shadowRight);
- rect.setHeight(rect.height() - shadowTop + shadowBottom);
-}
-
-void ShadowData::adjustRectForShadow(FloatRect& rect, int additionalOutlineSize) const
-{
- int shadowLeft = 0;
- int shadowRight = 0;
- int shadowTop = 0;
- int shadowBottom = 0;
- calculateShadowExtent(this, additionalOutlineSize, shadowLeft, shadowRight, shadowTop, shadowBottom);
-
- rect.move(shadowLeft, shadowTop);
- rect.setWidth(rect.width() - shadowLeft + shadowRight);
- rect.setHeight(rect.height() - shadowTop + shadowBottom);
+ if (style() != from.style())
+ return *this;
+
+ return ShadowData(WebCore::blend(from.location(), location(), progress),
+ clampTo<int>(WebCore::blend(from.blur(), blur(), progress), 0),
+ WebCore::blend(from.spread(), spread(), progress),
+ style(),
+ WebCore::blend(from.color(), color(), progress));
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/style/ShadowData.h b/chromium/third_party/WebKit/Source/core/rendering/style/ShadowData.h
index 86377c2546c..574b3f8214e 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/style/ShadowData.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/style/ShadowData.h
@@ -25,11 +25,8 @@
#ifndef ShadowData_h
#define ShadowData_h
-#include "core/platform/graphics/Color.h"
-#include "core/platform/graphics/FloatRect.h"
-#include "core/platform/graphics/LayoutRect.h"
-#include "wtf/OwnPtr.h"
-#include "wtf/PassOwnPtr.h"
+#include "platform/geometry/IntPoint.h"
+#include "platform/graphics/Color.h"
namespace WebCore {
@@ -39,20 +36,20 @@ enum ShadowStyle { Normal, Inset };
class ShadowData {
WTF_MAKE_FAST_ALLOCATED;
public:
- static PassOwnPtr<ShadowData> create() { return adoptPtr(new ShadowData); }
- static PassOwnPtr<ShadowData> create(const IntPoint& location, int blur, int spread, ShadowStyle style, const Color& color)
- {
- return adoptPtr(new ShadowData(location, blur, spread, style, color));
- }
- // This clones the whole ShadowData linked list.
- PassOwnPtr<ShadowData> clone() const
+ ShadowData(const IntPoint& location, int blur, int spread, ShadowStyle style, const Color& color)
+ : m_location(location)
+ , m_blur(blur)
+ , m_spread(spread)
+ , m_color(color)
+ , m_style(style)
{
- return adoptPtr(new ShadowData(*this));
}
bool operator==(const ShadowData&) const;
bool operator!=(const ShadowData& o) const { return !(*this == o); }
+ ShadowData blend(const ShadowData& from, double progress) const;
+
int x() const { return m_location.x(); }
int y() const { return m_location.y(); }
IntPoint location() const { return m_location; }
@@ -61,50 +58,14 @@ public:
ShadowStyle style() const { return m_style; }
const Color& color() const { return m_color; }
- const ShadowData* next() const { return m_next.get(); }
- void setNext(PassOwnPtr<ShadowData> shadow) { m_next = shadow; }
-
- void adjustRectForShadow(LayoutRect&, int additionalOutlineSize = 0) const;
- void adjustRectForShadow(FloatRect&, int additionalOutlineSize = 0) const;
-
private:
- ShadowData()
- : m_blur(0)
- , m_spread(0)
- , m_style(Normal)
- {
- }
-
- ShadowData(const IntPoint& location, int blur, int spread, ShadowStyle style, const Color& color)
- : m_location(location)
- , m_blur(blur)
- , m_spread(spread)
- , m_color(color)
- , m_style(style)
- {
- }
-
- ShadowData(const ShadowData&);
-
IntPoint m_location;
int m_blur;
int m_spread;
Color m_color;
ShadowStyle m_style;
- OwnPtr<ShadowData> m_next;
};
-// Helper method to handle nullptr, otherwise all callers need an ugly ternary.
-inline PassOwnPtr<ShadowData> cloneShadow(const ShadowData* shadow)
-{
- return shadow ? shadow->clone() : nullptr;
-}
-
-inline PassOwnPtr<ShadowData> cloneShadow(const OwnPtr<ShadowData>& shadow)
-{
- return cloneShadow(shadow.get());
-}
-
} // namespace WebCore
#endif // ShadowData_h
diff --git a/chromium/third_party/WebKit/Source/core/rendering/style/ShadowList.cpp b/chromium/third_party/WebKit/Source/core/rendering/style/ShadowList.cpp
new file mode 100644
index 00000000000..675effec90b
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/rendering/style/ShadowList.cpp
@@ -0,0 +1,107 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/rendering/style/ShadowList.h"
+
+#include "platform/geometry/FloatRect.h"
+#include "platform/geometry/LayoutRect.h"
+
+namespace WebCore {
+
+static inline void calculateShadowExtent(const ShadowList* shadowList, int additionalOutlineSize, int& shadowLeft, int& shadowRight, int& shadowTop, int& shadowBottom)
+{
+ ASSERT(shadowList);
+ size_t shadowCount = shadowList->shadows().size();
+ for (size_t i = 0; i < shadowCount; ++i) {
+ const ShadowData& shadow = shadowList->shadows()[i];
+ if (shadow.style() == Inset)
+ continue;
+ int blurAndSpread = shadow.blur() + shadow.spread() + additionalOutlineSize;
+ shadowLeft = std::min(shadow.x() - blurAndSpread, shadowLeft);
+ shadowRight = std::max(shadow.x() + blurAndSpread, shadowRight);
+ shadowTop = std::min(shadow.y() - blurAndSpread, shadowTop);
+ shadowBottom = std::max(shadow.y() + blurAndSpread, shadowBottom);
+ }
+}
+
+void ShadowList::adjustRectForShadow(LayoutRect& rect, int additionalOutlineSize) const
+{
+ int shadowLeft = 0;
+ int shadowRight = 0;
+ int shadowTop = 0;
+ int shadowBottom = 0;
+ calculateShadowExtent(this, additionalOutlineSize, shadowLeft, shadowRight, shadowTop, shadowBottom);
+
+ rect.move(shadowLeft, shadowTop);
+ rect.setWidth(rect.width() - shadowLeft + shadowRight);
+ rect.setHeight(rect.height() - shadowTop + shadowBottom);
+}
+
+void ShadowList::adjustRectForShadow(FloatRect& rect, int additionalOutlineSize) const
+{
+ int shadowLeft = 0;
+ int shadowRight = 0;
+ int shadowTop = 0;
+ int shadowBottom = 0;
+ calculateShadowExtent(this, additionalOutlineSize, shadowLeft, shadowRight, shadowTop, shadowBottom);
+
+ rect.move(shadowLeft, shadowTop);
+ rect.setWidth(rect.width() - shadowLeft + shadowRight);
+ rect.setHeight(rect.height() - shadowTop + shadowBottom);
+}
+
+PassRefPtr<ShadowList> ShadowList::blend(const ShadowList* from, const ShadowList* to, double progress)
+{
+ size_t fromLength = from ? from->shadows().size() : 0;
+ size_t toLength = to ? to->shadows().size() : 0;
+ if (!fromLength && !toLength)
+ return 0;
+
+ ShadowDataVector shadows;
+
+ DEFINE_STATIC_LOCAL(ShadowData, defaultShadowData, (IntPoint(), 0, 0, Normal, Color::transparent));
+ DEFINE_STATIC_LOCAL(ShadowData, defaultInsetShadowData, (IntPoint(), 0, 0, Inset, Color::transparent));
+
+ size_t maxLength = std::max(fromLength, toLength);
+ for (size_t i = 0; i < maxLength; ++i) {
+ const ShadowData* fromShadow = i < fromLength ? &from->shadows()[i] : 0;
+ const ShadowData* toShadow = i < toLength ? &to->shadows()[i] : 0;
+ if (!fromShadow)
+ fromShadow = toShadow->style() == Inset ? &defaultInsetShadowData : &defaultShadowData;
+ else if (!toShadow)
+ toShadow = fromShadow->style() == Inset ? &defaultInsetShadowData : &defaultShadowData;
+ shadows.append(toShadow->blend(*fromShadow, progress));
+ }
+
+ return ShadowList::adopt(shadows);
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/style/ShadowList.h b/chromium/third_party/WebKit/Source/core/rendering/style/ShadowList.h
new file mode 100644
index 00000000000..12acedf4801
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/rendering/style/ShadowList.h
@@ -0,0 +1,76 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef ShadowList_h
+#define ShadowList_h
+
+#include "core/rendering/style/ShadowData.h"
+#include "wtf/RefCounted.h"
+#include "wtf/Vector.h"
+
+namespace WebCore {
+
+class FloatRect;
+class LayoutRect;
+
+typedef Vector<ShadowData, 1> ShadowDataVector;
+
+// These are used to store shadows in specified order, but we usually want to
+// iterate over them backwards as the first-specified shadow is painted on top.
+class ShadowList : public RefCounted<ShadowList> {
+public:
+ // This consumes passed in vector.
+ static PassRefPtr<ShadowList> adopt(ShadowDataVector& shadows)
+ {
+ return adoptRef(new ShadowList(shadows));
+ }
+ const ShadowDataVector& shadows() const { return m_shadows; }
+ bool operator==(const ShadowList& o) const { return m_shadows == o.m_shadows; }
+ bool operator!=(const ShadowList& o) const { return !(*this == o); }
+
+ static PassRefPtr<ShadowList> blend(const ShadowList* from, const ShadowList* to, double progress);
+
+ void adjustRectForShadow(LayoutRect&, int additionalOutlineSize = 0) const;
+ void adjustRectForShadow(FloatRect&, int additionalOutlineSize = 0) const;
+
+private:
+ ShadowList(ShadowDataVector& shadows)
+ {
+ // If we have no shadows, we use a null ShadowList
+ ASSERT(!shadows.isEmpty());
+ m_shadows.swap(shadows);
+ m_shadows.shrinkToFit();
+ }
+ ShadowDataVector m_shadows;
+};
+
+} // namespace WebCore
+
+#endif // ShadowList_h
diff --git a/chromium/third_party/WebKit/Source/core/rendering/style/ShapeValue.h b/chromium/third_party/WebKit/Source/core/rendering/style/ShapeValue.h
index bb71dab440a..6b872807dce 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/style/ShapeValue.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/style/ShapeValue.h
@@ -32,6 +32,7 @@
#include "core/fetch/ImageResource.h"
#include "core/rendering/style/BasicShapes.h"
+#include "core/rendering/style/RenderStyleConstants.h"
#include "core/rendering/style/StyleImage.h"
#include "wtf/PassRefPtr.h"
@@ -42,6 +43,7 @@ public:
enum ShapeValueType {
// The Auto value is defined by a null ShapeValue*
Shape,
+ Box,
Outside,
Image
};
@@ -56,6 +58,11 @@ public:
return adoptRef(new ShapeValue(Outside));
}
+ static PassRefPtr<ShapeValue> createLayoutBoxValue(LayoutBox layoutBox)
+ {
+ return adoptRef(new ShapeValue(layoutBox));
+ }
+
static PassRefPtr<ShapeValue> createImageValue(PassRefPtr<StyleImage> image)
{
return adoptRef(new ShapeValue(image));
@@ -72,26 +79,40 @@ public:
if (m_image != image)
m_image = image;
}
+ LayoutBox layoutBox() const { return m_layoutBox; }
+ void setLayoutBox(LayoutBox layoutBox) { m_layoutBox = layoutBox; }
+
bool operator==(const ShapeValue& other) const { return type() == other.type(); }
private:
ShapeValue(PassRefPtr<BasicShape> shape)
: m_type(Shape)
, m_shape(shape)
+ , m_layoutBox(ContentBox)
{
}
ShapeValue(ShapeValueType type)
: m_type(type)
+ , m_layoutBox(ContentBox)
{
}
ShapeValue(PassRefPtr<StyleImage> image)
: m_type(Image)
, m_image(image)
+ , m_layoutBox(ContentBox)
{
}
+ ShapeValue(LayoutBox layoutBox)
+ : m_type(Box)
+ , m_layoutBox(layoutBox)
+ {
+ }
+
+
ShapeValueType m_type;
RefPtr<BasicShape> m_shape;
RefPtr<StyleImage> m_image;
+ LayoutBox m_layoutBox;
};
}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/style/StyleBackgroundData.cpp b/chromium/third_party/WebKit/Source/core/rendering/style/StyleBackgroundData.cpp
index 8c4261e04a3..d0b7ba4ff27 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/style/StyleBackgroundData.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/style/StyleBackgroundData.cpp
@@ -28,7 +28,7 @@
namespace WebCore {
StyleBackgroundData::StyleBackgroundData()
- : m_background(BackgroundFillLayer)
+ : m_background(BackgroundFillLayer, true)
, m_color(RenderStyle::initialBackgroundColor())
{
}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/style/StyleBackgroundData.h b/chromium/third_party/WebKit/Source/core/rendering/style/StyleBackgroundData.h
index 78f2042002b..fda242f38f2 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/style/StyleBackgroundData.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/style/StyleBackgroundData.h
@@ -25,9 +25,9 @@
#ifndef StyleBackgroundData_h
#define StyleBackgroundData_h
-#include "core/platform/graphics/Color.h"
#include "core/rendering/style/FillLayer.h"
#include "core/rendering/style/OutlineValue.h"
+#include "platform/graphics/Color.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefCounted.h"
diff --git a/chromium/third_party/WebKit/Source/core/rendering/style/StyleBoxData.cpp b/chromium/third_party/WebKit/Source/core/rendering/style/StyleBoxData.cpp
index f78d548b310..124b2f4c079 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/style/StyleBoxData.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/style/StyleBoxData.cpp
@@ -23,7 +23,6 @@
#include "core/rendering/style/StyleBoxData.h"
#include "core/rendering/style/RenderStyle.h"
-#include "core/rendering/style/RenderStyleConstants.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/rendering/style/StyleBoxData.h b/chromium/third_party/WebKit/Source/core/rendering/style/StyleBoxData.h
index ff9b5439c3d..9b2296641df 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/style/StyleBoxData.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/style/StyleBoxData.h
@@ -25,8 +25,8 @@
#ifndef StyleBoxData_h
#define StyleBoxData_h
-#include "core/platform/Length.h"
#include "core/rendering/style/RenderStyleConstants.h"
+#include "platform/Length.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefCounted.h"
diff --git a/chromium/third_party/WebKit/Source/core/rendering/style/StyleCustomFilterProgram.h b/chromium/third_party/WebKit/Source/core/rendering/style/StyleCustomFilterProgram.h
index 18be011b566..d79cf6368f5 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/style/StyleCustomFilterProgram.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/style/StyleCustomFilterProgram.h
@@ -33,9 +33,9 @@
#include "core/fetch/ResourceClient.h"
#include "core/fetch/ResourcePtr.h"
#include "core/fetch/ShaderResource.h"
-#include "core/platform/graphics/filters/custom/CustomFilterProgram.h"
#include "core/rendering/style/StyleShader.h"
-#include "weborigin/KURL.h"
+#include "platform/graphics/filters/custom/CustomFilterProgram.h"
+#include "platform/weborigin/KURL.h"
#include "wtf/FastAllocBase.h"
namespace WebCore {
@@ -88,6 +88,14 @@ public:
// so missing and canceled resources will have isLoaded set to true, even if they are not loaded yet.
ASSERT(!m_vertexShader || m_vertexShader->isShaderResource());
ASSERT(!m_fragmentShader || m_fragmentShader->isShaderResource());
+
+ // If we failed to create resources for the vertex shader or the
+ // fragment shader, they won't be set here.
+ // This can happen if the ResourceFetcher is no longer accepting fetch
+ // requests because the page is being torn down.
+ if (!m_vertexShader && !m_fragmentShader)
+ return false;
+
ASSERT(m_cachedVertexShader.get() || m_cachedFragmentShader.get());
return (!m_cachedVertexShader.get() || m_isVertexShaderLoaded)
&& (!m_cachedFragmentShader.get() || m_isFragmentShaderLoaded);
diff --git a/chromium/third_party/WebKit/Source/core/rendering/style/StyleCustomFilterProgramCache.cpp b/chromium/third_party/WebKit/Source/core/rendering/style/StyleCustomFilterProgramCache.cpp
index fb4c011755f..87d3aba9b66 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/style/StyleCustomFilterProgramCache.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/style/StyleCustomFilterProgramCache.cpp
@@ -31,7 +31,6 @@
#include "core/rendering/style/StyleCustomFilterProgramCache.h"
-#include "core/platform/graphics/filters/custom/CustomFilterProgramInfo.h"
#include "core/rendering/style/StyleCustomFilterProgram.h"
namespace WebCore {
@@ -77,7 +76,7 @@ void StyleCustomFilterProgramCache::add(StyleCustomFilterProgram* program)
void StyleCustomFilterProgramCache::remove(StyleCustomFilterProgram* program)
{
CacheMap::iterator iter = m_cache.find(programCacheKey(program));
- ASSERT(iter != m_cache.end());
+ ASSERT_WITH_SECURITY_IMPLICATION(iter != m_cache.end());
m_cache.remove(iter);
}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/style/StyleCustomFilterProgramCache.h b/chromium/third_party/WebKit/Source/core/rendering/style/StyleCustomFilterProgramCache.h
index bfd16102381..2bc1652d0e6 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/style/StyleCustomFilterProgramCache.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/style/StyleCustomFilterProgramCache.h
@@ -30,7 +30,7 @@
#ifndef StyleCustomFilterProgramCache_h
#define StyleCustomFilterProgramCache_h
-#include "core/platform/graphics/filters/custom/CustomFilterProgramInfo.h"
+#include "platform/graphics/filters/custom/CustomFilterProgramInfo.h"
#include "wtf/FastAllocBase.h"
#include "wtf/HashMap.h"
diff --git a/chromium/third_party/WebKit/Source/core/rendering/style/StyleFetchedImage.h b/chromium/third_party/WebKit/Source/core/rendering/style/StyleFetchedImage.h
index 9ea82f51778..e783439b195 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/style/StyleFetchedImage.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/style/StyleFetchedImage.h
@@ -63,5 +63,7 @@ private:
ResourcePtr<ImageResource> m_image;
};
+DEFINE_STYLE_IMAGE_TYPE_CASTS(StyleFetchedImage, isImageResource());
+
}
#endif
diff --git a/chromium/third_party/WebKit/Source/core/rendering/style/StyleFetchedImageSet.h b/chromium/third_party/WebKit/Source/core/rendering/style/StyleFetchedImageSet.h
index 178ec3c87b0..873c14299ef 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/style/StyleFetchedImageSet.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/style/StyleFetchedImageSet.h
@@ -28,8 +28,8 @@
#include "core/fetch/ImageResourceClient.h"
#include "core/fetch/ResourcePtr.h"
-#include "core/platform/graphics/LayoutSize.h"
#include "core/rendering/style/StyleImage.h"
+#include "platform/geometry/LayoutSize.h"
namespace WebCore {
@@ -80,6 +80,8 @@ private:
CSSImageSetValue* m_imageSetValue; // Not retained; it owns us.
};
+DEFINE_STYLE_IMAGE_TYPE_CASTS(StyleFetchedImageSet, isImageResourceSet());
+
} // namespace WebCore
#endif // StyleFetchedImageSet_h
diff --git a/chromium/third_party/WebKit/Source/core/rendering/style/StyleFilterData.h b/chromium/third_party/WebKit/Source/core/rendering/style/StyleFilterData.h
index 12a3e84ce34..d9623e0000b 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/style/StyleFilterData.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/style/StyleFilterData.h
@@ -26,7 +26,7 @@
#ifndef StyleFilterData_h
#define StyleFilterData_h
-#include "core/platform/graphics/filters/FilterOperations.h"
+#include "platform/graphics/filters/FilterOperations.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefCounted.h"
diff --git a/chromium/third_party/WebKit/Source/core/rendering/style/StyleFlexibleBoxData.h b/chromium/third_party/WebKit/Source/core/rendering/style/StyleFlexibleBoxData.h
index 887755860d0..b943eace79d 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/style/StyleFlexibleBoxData.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/style/StyleFlexibleBoxData.h
@@ -26,7 +26,7 @@
#ifndef StyleFlexibleBoxData_h
#define StyleFlexibleBoxData_h
-#include "core/platform/Length.h"
+#include "platform/Length.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefCounted.h"
diff --git a/chromium/third_party/WebKit/Source/core/rendering/style/StyleImage.h b/chromium/third_party/WebKit/Source/core/rendering/style/StyleImage.h
index e440c224ff0..bca329ac568 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/style/StyleImage.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/style/StyleImage.h
@@ -25,9 +25,9 @@
#define StyleImage_h
#include "core/css/CSSValue.h"
-#include "core/platform/graphics/Image.h"
-#include "core/platform/graphics/IntSize.h"
-#include "core/platform/graphics/LayoutSize.h"
+#include "platform/geometry/IntSize.h"
+#include "platform/geometry/LayoutSize.h"
+#include "platform/graphics/Image.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefCounted.h"
#include "wtf/RefPtr.h"
@@ -97,5 +97,10 @@ protected:
bool m_isImageResourceSet:1;
};
+#define DEFINE_STYLE_IMAGE_TYPE_CASTS(thisType, function) \
+ DEFINE_TYPE_CASTS(thisType, StyleImage, styleImage, styleImage->function, styleImage.function); \
+ inline thisType* to##thisType(const RefPtr<StyleImage>& styleImage) { return to##thisType(styleImage.get()); } \
+ typedef int NeedsSemiColonAfterDefineStyleImageTypeCasts
+
}
#endif
diff --git a/chromium/third_party/WebKit/Source/core/rendering/style/StyleInheritedData.h b/chromium/third_party/WebKit/Source/core/rendering/style/StyleInheritedData.h
index 54dc7d71b2c..11613a4abf7 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/style/StyleInheritedData.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/style/StyleInheritedData.h
@@ -25,9 +25,9 @@
#ifndef StyleInheritedData_h
#define StyleInheritedData_h
-#include "core/platform/Length.h"
-#include "core/platform/graphics/Color.h"
-#include "core/platform/graphics/Font.h"
+#include "platform/Length.h"
+#include "platform/fonts/Font.h"
+#include "platform/graphics/Color.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefCounted.h"
#include "wtf/RefPtr.h"
diff --git a/chromium/third_party/WebKit/Source/core/rendering/style/StyleMarqueeData.h b/chromium/third_party/WebKit/Source/core/rendering/style/StyleMarqueeData.h
index 31de9b87aee..3a6bb9f2902 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/style/StyleMarqueeData.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/style/StyleMarqueeData.h
@@ -25,8 +25,8 @@
#ifndef StyleMarqueeData_h
#define StyleMarqueeData_h
-#include "core/platform/Length.h"
#include "core/rendering/style/RenderStyleConstants.h"
+#include "platform/Length.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefCounted.h"
diff --git a/chromium/third_party/WebKit/Source/core/rendering/style/StyleMultiColData.cpp b/chromium/third_party/WebKit/Source/core/rendering/style/StyleMultiColData.cpp
index 9a4eb5ff3f1..90897bb28bf 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/style/StyleMultiColData.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/style/StyleMultiColData.cpp
@@ -33,6 +33,7 @@ StyleMultiColData::StyleMultiColData()
, m_autoWidth(true)
, m_autoCount(true)
, m_normalGap(true)
+ , m_fill(RenderStyle::initialColumnFill())
, m_columnSpan(false)
, m_breakBefore(RenderStyle::initialPageBreak())
, m_breakAfter(RenderStyle::initialPageBreak())
@@ -52,6 +53,7 @@ StyleMultiColData::StyleMultiColData(const StyleMultiColData& o)
, m_autoWidth(o.m_autoWidth)
, m_autoCount(o.m_autoCount)
, m_normalGap(o.m_normalGap)
+ , m_fill(o.m_fill)
, m_columnSpan(o.m_columnSpan)
, m_breakBefore(o.m_breakBefore)
, m_breakAfter(o.m_breakAfter)
@@ -64,10 +66,11 @@ StyleMultiColData::StyleMultiColData(const StyleMultiColData& o)
bool StyleMultiColData::operator==(const StyleMultiColData& o) const
{
return m_width == o.m_width && m_count == o.m_count && m_gap == o.m_gap
- && m_rule == o.m_rule && m_visitedLinkColumnRuleColor == o.m_visitedLinkColumnRuleColor && m_breakBefore == o.m_breakBefore
- && m_autoWidth == o.m_autoWidth && m_autoCount == o.m_autoCount && m_normalGap == o.m_normalGap
- && m_columnSpan == o.m_columnSpan && m_breakAfter == o.m_breakAfter && m_breakInside == o.m_breakInside && m_axis == o.m_axis
- && m_progression == o.m_progression;
+ && m_rule == o.m_rule && m_visitedLinkColumnRuleColor == o.m_visitedLinkColumnRuleColor && m_breakBefore == o.m_breakBefore
+ && m_autoWidth == o.m_autoWidth && m_autoCount == o.m_autoCount && m_normalGap == o.m_normalGap
+ && m_fill == o.m_fill && m_columnSpan == o.m_columnSpan
+ && m_breakAfter == o.m_breakAfter && m_breakInside == o.m_breakInside
+ && m_axis == o.m_axis && m_progression == o.m_progression;
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/style/StyleMultiColData.h b/chromium/third_party/WebKit/Source/core/rendering/style/StyleMultiColData.h
index dcd1478ca8d..fcf66802667 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/style/StyleMultiColData.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/style/StyleMultiColData.h
@@ -25,9 +25,9 @@
#ifndef StyleMultiColData_h
#define StyleMultiColData_h
-#include "core/platform/Length.h"
#include "core/rendering/style/BorderValue.h"
#include "core/rendering/style/RenderStyleConstants.h"
+#include "platform/Length.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefCounted.h"
@@ -62,6 +62,7 @@ public:
bool m_autoWidth : 1;
bool m_autoCount : 1;
bool m_normalGap : 1;
+ unsigned m_fill : 1; // ColumnFill
unsigned m_columnSpan : 1;
unsigned m_breakBefore : 2; // EPageBreak
unsigned m_breakAfter : 2; // EPageBreak
diff --git a/chromium/third_party/WebKit/Source/core/rendering/style/StylePendingImage.h b/chromium/third_party/WebKit/Source/core/rendering/style/StylePendingImage.h
index 3633d154d1e..4589f59a63d 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/style/StylePendingImage.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/style/StylePendingImage.h
@@ -30,8 +30,8 @@
#include "core/css/CSSImageGeneratorValue.h"
#include "core/css/CSSImageSetValue.h"
#include "core/css/CSSImageValue.h"
-#include "core/platform/graphics/Image.h"
#include "core/rendering/style/StyleImage.h"
+#include "platform/graphics/Image.h"
namespace WebCore {
@@ -47,9 +47,9 @@ public:
virtual PassRefPtr<CSSValue> cssValue() const { return m_value; }
CSSImageValue* cssImageValue() const { return m_value->isImageValue() ? toCSSImageValue(m_value) : 0; }
- CSSImageGeneratorValue* cssImageGeneratorValue() const { return m_value->isImageGeneratorValue() ? static_cast<CSSImageGeneratorValue*>(m_value) : 0; }
- CSSCursorImageValue* cssCursorImageValue() const { return m_value->isCursorImageValue() ? static_cast<CSSCursorImageValue*>(m_value) : 0; }
- CSSImageSetValue* cssImageSetValue() const { return m_value->isImageSetValue() ? static_cast<CSSImageSetValue*>(m_value) : 0; }
+ CSSImageGeneratorValue* cssImageGeneratorValue() const { return m_value->isImageGeneratorValue() ? toCSSImageGeneratorValue(m_value) : 0; }
+ CSSCursorImageValue* cssCursorImageValue() const { return m_value->isCursorImageValue() ? toCSSCursorImageValue(m_value) : 0; }
+ CSSImageSetValue* cssImageSetValue() const { return m_value->isImageSetValue() ? toCSSImageSetValue(m_value) : 0; }
virtual LayoutSize imageSize(const RenderObject*, float /*multiplier*/) const OVERRIDE { return LayoutSize(); }
virtual bool imageHasRelativeWidth() const { return false; }
@@ -76,5 +76,7 @@ private:
CSSValue* m_value; // Not retained; it owns us.
};
+DEFINE_STYLE_IMAGE_TYPE_CASTS(StylePendingImage, isPendingImage());
+
}
#endif
diff --git a/chromium/third_party/WebKit/Source/core/rendering/style/StyleRareInheritedData.cpp b/chromium/third_party/WebKit/Source/core/rendering/style/StyleRareInheritedData.cpp
index 3ca9ff22144..1a1769c787f 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/style/StyleRareInheritedData.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/style/StyleRareInheritedData.cpp
@@ -26,7 +26,7 @@
#include "core/rendering/style/QuotesData.h"
#include "core/rendering/style/RenderStyle.h"
#include "core/rendering/style/RenderStyleConstants.h"
-#include "core/rendering/style/ShadowData.h"
+#include "core/rendering/style/ShadowList.h"
#include "core/rendering/style/StyleImage.h"
namespace WebCore {
@@ -75,16 +75,16 @@ StyleRareInheritedData::StyleRareInheritedData()
, textEmphasisMark(TextEmphasisMarkNone)
, textEmphasisPosition(TextEmphasisPositionOver)
, m_textAlignLast(RenderStyle::initialTextAlignLast())
+ , m_textJustify(RenderStyle::initialTextJustify())
, m_textOrientation(TextOrientationVerticalRight)
, m_textIndentLine(RenderStyle::initialTextIndentLine())
, m_lineBoxContain(RenderStyle::initialLineBoxContain())
, m_imageRendering(RenderStyle::initialImageRendering())
, m_lineSnap(RenderStyle::initialLineSnap())
, m_lineAlign(RenderStyle::initialLineAlign())
-#if ENABLE(CSS3_TEXT)
, m_textUnderlinePosition(RenderStyle::initialTextUnderlinePosition())
-#endif // CSS3_TEXT
, m_rubyPosition(RenderStyle::initialRubyPosition())
+ , m_touchActionDelay(RenderStyle::initialTouchActionDelay())
, hyphenationLimitBefore(-1)
, hyphenationLimitAfter(-1)
, hyphenationLimitLines(-1)
@@ -105,7 +105,7 @@ StyleRareInheritedData::StyleRareInheritedData(const StyleRareInheritedData& o)
, visitedLinkTextStrokeColor(o.visitedLinkTextStrokeColor)
, visitedLinkTextFillColor(o.visitedLinkTextFillColor)
, visitedLinkTextEmphasisColor(o.visitedLinkTextEmphasisColor)
- , textShadow(cloneShadow(o.textShadow))
+ , textShadow(o.textShadow)
, highlight(o.highlight)
, cursorData(o.cursorData)
, indent(o.indent)
@@ -127,16 +127,16 @@ StyleRareInheritedData::StyleRareInheritedData(const StyleRareInheritedData& o)
, textEmphasisMark(o.textEmphasisMark)
, textEmphasisPosition(o.textEmphasisPosition)
, m_textAlignLast(o.m_textAlignLast)
+ , m_textJustify(o.m_textJustify)
, m_textOrientation(o.m_textOrientation)
, m_textIndentLine(o.m_textIndentLine)
, m_lineBoxContain(o.m_lineBoxContain)
, m_imageRendering(o.m_imageRendering)
, m_lineSnap(o.m_lineSnap)
, m_lineAlign(o.m_lineAlign)
-#if ENABLE(CSS3_TEXT)
, m_textUnderlinePosition(o.m_textUnderlinePosition)
-#endif // CSS3_TEXT
, m_rubyPosition(o.m_rubyPosition)
+ , m_touchActionDelay(o.m_touchActionDelay)
, hyphenationString(o.hyphenationString)
, hyphenationLimitBefore(o.hyphenationLimitBefore)
, hyphenationLimitAfter(o.hyphenationLimitAfter)
@@ -197,7 +197,9 @@ bool StyleRareInheritedData::operator==(const StyleRareInheritedData& o) const
&& textEmphasisFill == o.textEmphasisFill
&& textEmphasisMark == o.textEmphasisMark
&& textEmphasisPosition == o.textEmphasisPosition
+ && m_touchActionDelay == o.m_touchActionDelay
&& m_textAlignLast == o.m_textAlignLast
+ && m_textJustify == o.m_textJustify
&& m_textOrientation == o.m_textOrientation
&& m_textIndentLine == o.m_textIndentLine
&& m_lineBoxContain == o.m_lineBoxContain
@@ -208,9 +210,7 @@ bool StyleRareInheritedData::operator==(const StyleRareInheritedData& o) const
&& m_tabSize == o.m_tabSize
&& m_lineGrid == o.m_lineGrid
&& m_imageRendering == o.m_imageRendering
-#if ENABLE(CSS3_TEXT)
&& m_textUnderlinePosition == o.m_textUnderlinePosition
-#endif // CSS3_TEXT
&& m_rubyPosition == o.m_rubyPosition
&& m_lineSnap == o.m_lineSnap
&& m_variables == o.m_variables
diff --git a/chromium/third_party/WebKit/Source/core/rendering/style/StyleRareInheritedData.h b/chromium/third_party/WebKit/Source/core/rendering/style/StyleRareInheritedData.h
index 2e0bbb53df2..11d3c4b0f52 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/style/StyleRareInheritedData.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/style/StyleRareInheritedData.h
@@ -25,20 +25,19 @@
#ifndef StyleRareInheritedData_h
#define StyleRareInheritedData_h
-#include "core/platform/Length.h"
-#include "core/platform/graphics/Color.h"
+#include "core/rendering/style/DataRef.h"
+#include "core/rendering/style/StyleVariableData.h"
+#include "platform/Length.h"
+#include "platform/graphics/Color.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefCounted.h"
#include "wtf/text/AtomicString.h"
-#include "core/rendering/style/DataRef.h"
-#include "core/rendering/style/StyleVariableData.h"
-
namespace WebCore {
class CursorList;
class QuotesData;
-class ShadowData;
+class ShadowList;
class StyleImage;
// This struct is for rarely used inherited CSS3, CSS2, and WebKit-specific properties.
@@ -68,7 +67,7 @@ public:
Color visitedLinkTextFillColor;
Color visitedLinkTextEmphasisColor;
- OwnPtr<ShadowData> textShadow; // Our text shadow information for shadowed text drawing.
+ RefPtr<ShadowList> textShadow; // Our text shadow information for shadowed text drawing.
AtomicString highlight; // Apple-specific extension for custom highlight rendering.
RefPtr<CursorList> cursorData;
@@ -94,6 +93,7 @@ public:
unsigned textEmphasisMark : 3; // TextEmphasisMark
unsigned textEmphasisPosition : 1; // TextEmphasisPosition
unsigned m_textAlignLast : 3; // TextAlignLast
+ unsigned m_textJustify : 2; // TextJustify
unsigned m_textOrientation : 2; // TextOrientation
unsigned m_textIndentLine : 1; // TextIndentEachLine
unsigned m_lineBoxContain: 7; // LineBoxContain
@@ -101,10 +101,9 @@ public:
unsigned m_imageRendering : 2; // EImageRendering
unsigned m_lineSnap : 2; // LineSnap
unsigned m_lineAlign : 1; // LineAlign
-#if ENABLE(CSS3_TEXT)
- unsigned m_textUnderlinePosition : 3; // TextUnderlinePosition
-#endif // CSS3_TEXT
+ unsigned m_textUnderlinePosition : 2; // TextUnderlinePosition
unsigned m_rubyPosition : 1; // RubyPosition
+ unsigned m_touchActionDelay : 1; // TouchActionDelay
AtomicString hyphenationString;
short hyphenationLimitBefore;
diff --git a/chromium/third_party/WebKit/Source/core/rendering/style/StyleRareNonInheritedData.cpp b/chromium/third_party/WebKit/Source/core/rendering/style/StyleRareNonInheritedData.cpp
index 5428546fc9b..2d312788ec6 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/style/StyleRareNonInheritedData.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/style/StyleRareNonInheritedData.cpp
@@ -24,9 +24,10 @@
#include "core/rendering/style/ContentData.h"
#include "core/rendering/style/RenderStyle.h"
-#include "core/rendering/style/ShadowData.h"
+#include "core/rendering/style/ShadowList.h"
#include "core/rendering/style/StyleFilterData.h"
#include "core/rendering/style/StyleTransformData.h"
+#include "core/rendering/svg/ReferenceFilterBuilder.h"
namespace WebCore {
@@ -39,12 +40,13 @@ StyleRareNonInheritedData::StyleRareNonInheritedData()
, m_perspectiveOriginY(RenderStyle::initialPerspectiveOriginY())
, lineClamp(RenderStyle::initialLineClamp())
, m_draggableRegionMode(DraggableRegionNone)
- , m_mask(FillLayer(MaskFillLayer))
+ , m_mask(MaskFillLayer, true)
, m_pageSize()
, m_shapeInside(RenderStyle::initialShapeInside())
, m_shapeOutside(RenderStyle::initialShapeOutside())
, m_shapeMargin(RenderStyle::initialShapeMargin())
, m_shapePadding(RenderStyle::initialShapePadding())
+ , m_shapeImageThreshold(RenderStyle::initialShapeImageThreshold())
, m_clipPath(RenderStyle::initialClipPath())
, m_visitedLinkBackgroundColor(RenderStyle::initialBackgroundColor())
, m_order(RenderStyle::initialOrder())
@@ -102,7 +104,7 @@ StyleRareNonInheritedData::StyleRareNonInheritedData(const StyleRareNonInherited
, m_gridItem(o.m_gridItem)
, m_content(o.m_content ? o.m_content->clone() : nullptr)
, m_counterDirectives(o.m_counterDirectives ? clone(*o.m_counterDirectives) : nullptr)
- , m_boxShadow(cloneShadow(o.m_boxShadow))
+ , m_boxShadow(o.m_boxShadow)
, m_boxReflect(o.m_boxReflect)
, m_animations(o.m_animations ? adoptPtr(new CSSAnimationDataList(*o.m_animations)) : nullptr)
, m_transitions(o.m_transitions ? adoptPtr(new CSSAnimationDataList(*o.m_transitions)) : nullptr)
@@ -113,6 +115,7 @@ StyleRareNonInheritedData::StyleRareNonInheritedData(const StyleRareNonInherited
, m_shapeOutside(o.m_shapeOutside)
, m_shapeMargin(o.m_shapeMargin)
, m_shapePadding(o.m_shapePadding)
+ , m_shapeImageThreshold(o.m_shapeImageThreshold)
, m_clipPath(o.m_clipPath)
, m_textDecorationColor(o.m_textDecorationColor)
, m_visitedLinkTextDecorationColor(o.m_visitedLinkTextDecorationColor)
@@ -158,6 +161,9 @@ StyleRareNonInheritedData::StyleRareNonInheritedData(const StyleRareNonInherited
StyleRareNonInheritedData::~StyleRareNonInheritedData()
{
+ const FilterOperations& filterOperations = m_filter->m_operations;
+ for (unsigned i = 0; i < filterOperations.size(); ++i)
+ ReferenceFilterBuilder::clearDocumentResourceReference(filterOperations.at(i));
}
bool StyleRareNonInheritedData::operator==(const StyleRareNonInheritedData& o) const
@@ -191,6 +197,7 @@ bool StyleRareNonInheritedData::operator==(const StyleRareNonInheritedData& o) c
&& m_shapeOutside == o.m_shapeOutside
&& m_shapeMargin == o.m_shapeMargin
&& m_shapePadding == o.m_shapePadding
+ && m_shapeImageThreshold == o.m_shapeImageThreshold
&& m_clipPath == o.m_clipPath
&& m_textDecorationColor == o.m_textDecorationColor
&& m_visitedLinkTextDecorationColor == o.m_visitedLinkTextDecorationColor
@@ -202,6 +209,7 @@ bool StyleRareNonInheritedData::operator==(const StyleRareNonInheritedData& o) c
&& m_visitedLinkBorderBottomColor == o.m_visitedLinkBorderBottomColor
&& m_order == o.m_order
&& m_objectPosition == o.m_objectPosition
+ && m_callbackSelectors == o.m_callbackSelectors
&& m_flowThread == o.m_flowThread
&& m_regionThread == o.m_regionThread
&& m_regionFragment == o.m_regionFragment
diff --git a/chromium/third_party/WebKit/Source/core/rendering/style/StyleRareNonInheritedData.h b/chromium/third_party/WebKit/Source/core/rendering/style/StyleRareNonInheritedData.h
index eadba190c75..9ce04870219 100644..100755
--- a/chromium/third_party/WebKit/Source/core/rendering/style/StyleRareNonInheritedData.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/style/StyleRareNonInheritedData.h
@@ -25,7 +25,6 @@
#ifndef StyleRareNonInheritedData_h
#define StyleRareNonInheritedData_h
-#include "core/platform/LengthPoint.h"
#include "core/rendering/ClipPathOperation.h"
#include "core/rendering/style/BasicShapes.h"
#include "core/rendering/style/CounterDirectives.h"
@@ -34,15 +33,18 @@
#include "core/rendering/style/FillLayer.h"
#include "core/rendering/style/LineClampValue.h"
#include "core/rendering/style/NinePieceImage.h"
+#include "core/rendering/style/RenderStyleConstants.h"
#include "core/rendering/style/ShapeValue.h"
+#include "platform/LengthPoint.h"
#include "wtf/OwnPtr.h"
#include "wtf/PassRefPtr.h"
#include "wtf/Vector.h"
namespace WebCore {
+class ContentData;
class CSSAnimationDataList;
-class ShadowData;
+class ShadowList;
class StyleDeprecatedFlexibleBoxData;
class StyleFilterData;
class StyleFlexibleBoxData;
@@ -54,7 +56,6 @@ class StyleReflection;
class StyleResolver;
class StyleTransformData;
-class ContentData;
struct LengthSize;
// Page size type.
@@ -114,7 +115,7 @@ public:
OwnPtr<ContentData> m_content;
OwnPtr<CounterDirectiveMap> m_counterDirectives;
- OwnPtr<ShadowData> m_boxShadow; // For box-shadow decorations.
+ RefPtr<ShadowList> m_boxShadow;
RefPtr<StyleReflection> m_boxReflect;
@@ -130,6 +131,7 @@ public:
RefPtr<ShapeValue> m_shapeOutside;
Length m_shapeMargin;
Length m_shapePadding;
+ float m_shapeImageThreshold;
RefPtr<ClipPathOperation> m_clipPath;
@@ -146,6 +148,8 @@ public:
LengthPoint m_objectPosition;
+ Vector<String> m_callbackSelectors;
+
AtomicString m_flowThread;
AtomicString m_regionThread;
unsigned m_regionFragment : 1; // RegionFragment
@@ -181,7 +185,7 @@ public:
unsigned m_effectiveBlendMode: 5; // EBlendMode
- unsigned m_touchAction : 1; // TouchAction
+ unsigned m_touchAction : TouchActionBits; // TouchAction
unsigned m_objectFit : 3; // ObjectFit
diff --git a/chromium/third_party/WebKit/Source/core/rendering/style/StyleReflection.h b/chromium/third_party/WebKit/Source/core/rendering/style/StyleReflection.h
index 76829a3ffeb..40e451a3a1f 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/style/StyleReflection.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/style/StyleReflection.h
@@ -26,8 +26,8 @@
#define StyleReflection_h
#include "core/css/CSSReflectionDirection.h"
-#include "core/platform/Length.h"
#include "core/rendering/style/NinePieceImage.h"
+#include "platform/Length.h"
#include "wtf/RefCounted.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/rendering/style/StyleSurroundData.h b/chromium/third_party/WebKit/Source/core/rendering/style/StyleSurroundData.h
index 3d4913f0751..26d91f6d62e 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/style/StyleSurroundData.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/style/StyleSurroundData.h
@@ -25,8 +25,8 @@
#ifndef StyleSurroundData_h
#define StyleSurroundData_h
-#include "core/platform/LengthBox.h"
#include "core/rendering/style/BorderData.h"
+#include "platform/LengthBox.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefCounted.h"
diff --git a/chromium/third_party/WebKit/Source/core/rendering/style/StyleTransformData.h b/chromium/third_party/WebKit/Source/core/rendering/style/StyleTransformData.h
index 8f59a6da5f7..3253652e469 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/style/StyleTransformData.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/style/StyleTransformData.h
@@ -25,8 +25,8 @@
#ifndef StyleTransformData_h
#define StyleTransformData_h
-#include "core/platform/Length.h"
-#include "core/platform/graphics/transforms/TransformOperations.h"
+#include "platform/Length.h"
+#include "platform/transforms/TransformOperations.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefCounted.h"
diff --git a/chromium/third_party/WebKit/Source/core/rendering/style/StyleVisualData.h b/chromium/third_party/WebKit/Source/core/rendering/style/StyleVisualData.h
index 9e29cb0b20d..2657b93ceec 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/style/StyleVisualData.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/style/StyleVisualData.h
@@ -25,8 +25,8 @@
#ifndef StyleVisualData_h
#define StyleVisualData_h
-#include "core/platform/LengthBox.h"
#include "core/rendering/style/RenderStyleConstants.h"
+#include "platform/LengthBox.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefCounted.h"
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/ReferenceFilterBuilder.cpp b/chromium/third_party/WebKit/Source/core/rendering/svg/ReferenceFilterBuilder.cpp
index e9c656c19ac..8c0a5c517a4 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/ReferenceFilterBuilder.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/ReferenceFilterBuilder.cpp
@@ -34,16 +34,39 @@
#include "core/css/CSSPrimitiveValueMappings.h"
#include "core/dom/Element.h"
#include "core/fetch/DocumentResource.h"
-#include "core/fetch/DocumentResourceReference.h"
-#include "core/platform/graphics/filters/FilterEffect.h"
-#include "core/platform/graphics/filters/SourceAlpha.h"
#include "core/rendering/svg/RenderSVGResourceFilter.h"
#include "core/svg/SVGDocumentExtensions.h"
#include "core/svg/SVGFilterPrimitiveStandardAttributes.h"
#include "core/svg/graphics/filters/SVGFilterBuilder.h"
+#include "platform/graphics/filters/SourceAlpha.h"
namespace WebCore {
+HashMap<const FilterOperation*, OwnPtr<DocumentResourceReference> >* ReferenceFilterBuilder::documentResourceReferences = 0;
+
+DocumentResourceReference* ReferenceFilterBuilder::documentResourceReference(const FilterOperation* filterOperation)
+{
+ if (!documentResourceReferences)
+ return 0;
+
+ return documentResourceReferences->get(filterOperation);
+}
+
+void ReferenceFilterBuilder::setDocumentResourceReference(const FilterOperation* filterOperation, PassOwnPtr<DocumentResourceReference> documentResourceReference)
+{
+ if (!documentResourceReferences)
+ documentResourceReferences = new HashMap<const FilterOperation*, OwnPtr<DocumentResourceReference> >;
+ documentResourceReferences->add(filterOperation, documentResourceReference);
+}
+
+void ReferenceFilterBuilder::clearDocumentResourceReference(const FilterOperation* filterOperation)
+{
+ if (!documentResourceReferences)
+ return;
+
+ documentResourceReferences->remove(filterOperation);
+}
+
// Returns whether or not the SVGElement object contains a valid color-interpolation-filters attribute
static bool getSVGElementColorSpace(SVGElement* svgElement, ColorSpace& cs)
{
@@ -91,13 +114,14 @@ PassRefPtr<FilterEffect> ReferenceFilterBuilder::build(Filter* parentFilter, Ren
Document* document = &renderer->document();
- DocumentResourceReference* documentResourceReference = filterOperation->documentResourceReference();
- DocumentResource* cachedSVGDocument = documentResourceReference ? documentResourceReference->document() : 0;
+ if (DocumentResourceReference* documentResourceRef = documentResourceReference(filterOperation)) {
+ DocumentResource* cachedSVGDocument = documentResourceRef->document();
- // If we have an SVG document, this is an external reference. Otherwise
- // we look up the referenced node in the current document.
- if (cachedSVGDocument)
- document = cachedSVGDocument->document();
+ // If we have an SVG document, this is an external reference. Otherwise
+ // we look up the referenced node in the current document.
+ if (cachedSVGDocument)
+ document = cachedSVGDocument->document();
+ }
if (!document)
return 0;
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/ReferenceFilterBuilder.h b/chromium/third_party/WebKit/Source/core/rendering/svg/ReferenceFilterBuilder.h
index 9cc113a3fff..f7e0ac20223 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/ReferenceFilterBuilder.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/ReferenceFilterBuilder.h
@@ -31,19 +31,29 @@
#ifndef ReferenceFilterBuilder_h
#define ReferenceFilterBuilder_h
-#include "core/platform/graphics/filters/FilterEffect.h"
+#include "core/fetch/DocumentResourceReference.h"
+#include "platform/graphics/filters/FilterEffect.h"
+#include "wtf/HashMap.h"
#include "wtf/PassRefPtr.h"
namespace WebCore {
class Filter;
class FilterEffect;
+class FilterOperation;
class ReferenceFilterOperation;
class RenderObject;
class ReferenceFilterBuilder {
public:
+ static DocumentResourceReference* documentResourceReference(const FilterOperation*);
+ static void setDocumentResourceReference(const FilterOperation*, PassOwnPtr<DocumentResourceReference>);
+ static void clearDocumentResourceReference(const FilterOperation*);
+
static PassRefPtr<FilterEffect> build(Filter*, RenderObject* renderer, FilterEffect* previousEffect, const ReferenceFilterOperation*);
+
+private:
+ static HashMap<const FilterOperation*, OwnPtr<DocumentResourceReference> >* documentResourceReferences;
};
}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGBlock.cpp b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGBlock.cpp
index c3bed7eea5c..ab40394a4b3 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGBlock.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGBlock.cpp
@@ -23,6 +23,7 @@
#include "core/rendering/svg/RenderSVGBlock.h"
+#include "core/rendering/style/ShadowList.h"
#include "core/rendering/svg/SVGResourcesCache.h"
#include "core/svg/SVGElement.h"
@@ -37,27 +38,12 @@ LayoutRect RenderSVGBlock::visualOverflowRect() const
{
LayoutRect borderRect = borderBoxRect();
- if (const ShadowData* textShadow = style()->textShadow())
+ if (const ShadowList* textShadow = style()->textShadow())
textShadow->adjustRectForShadow(borderRect);
return borderRect;
}
-void RenderSVGBlock::setStyle(PassRefPtr<RenderStyle> style)
-{
- RefPtr<RenderStyle> useStyle = style;
-
- // SVG text layout code expects us to be a block-level style element.
- if (useStyle->isDisplayInlineType()) {
- RefPtr<RenderStyle> newStyle = RenderStyle::create();
- newStyle->inheritFrom(useStyle.get());
- newStyle->setDisplay(BLOCK);
- useStyle = newStyle.release();
- }
-
- RenderBlock::setStyle(useStyle.release());
-}
-
void RenderSVGBlock::updateFromStyle()
{
RenderBlock::updateFromStyle();
@@ -86,18 +72,14 @@ void RenderSVGBlock::absoluteRects(Vector<IntRect>&, const LayoutPoint&) const
void RenderSVGBlock::willBeDestroyed()
{
SVGResourcesCache::clientDestroyed(this);
- RenderBlock::willBeDestroyed();
+ RenderBlockFlow::willBeDestroyed();
}
-void RenderSVGBlock::styleWillChange(StyleDifference diff, const RenderStyle* newStyle)
+void RenderSVGBlock::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
{
if (diff == StyleDifferenceLayout)
setNeedsBoundariesUpdate();
- RenderBlock::styleWillChange(diff, newStyle);
-}
-void RenderSVGBlock::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
-{
RenderBlock::styleDidChange(diff, oldStyle);
SVGResourcesCache::clientStyleChanged(this, diff, style());
}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGBlock.h b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGBlock.h
index 7963e731ddf..6f08eb1f72f 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGBlock.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGBlock.h
@@ -36,7 +36,6 @@ protected:
virtual void willBeDestroyed() OVERRIDE;
private:
- virtual void setStyle(PassRefPtr<RenderStyle>) OVERRIDE FINAL;
virtual void updateFromStyle() OVERRIDE FINAL;
virtual bool isRenderSVGBlock() const OVERRIDE FINAL { return true; };
@@ -45,7 +44,6 @@ private:
virtual void absoluteRects(Vector<IntRect>&, const LayoutPoint& accumulatedOffset) const OVERRIDE FINAL;
- virtual void styleWillChange(StyleDifference, const RenderStyle* newStyle) OVERRIDE FINAL;
virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle) OVERRIDE FINAL;
};
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGContainer.cpp b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGContainer.cpp
index f9a9bf16c9a..04f28cae872 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGContainer.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGContainer.cpp
@@ -25,12 +25,14 @@
#include "core/rendering/svg/RenderSVGContainer.h"
-#include "core/platform/graphics/GraphicsContextStateSaver.h"
+#include "core/rendering/GraphicsContextAnnotator.h"
+#include "core/rendering/LayoutRectRecorder.h"
#include "core/rendering/LayoutRepainter.h"
#include "core/rendering/RenderView.h"
#include "core/rendering/svg/SVGRenderingContext.h"
#include "core/rendering/svg/SVGResources.h"
#include "core/rendering/svg/SVGResourcesCache.h"
+#include "platform/graphics/GraphicsContextStateSaver.h"
namespace WebCore {
@@ -52,6 +54,7 @@ void RenderSVGContainer::layout()
// RenderSVGRoot disables layoutState for the SVG rendering tree.
ASSERT(!view()->layoutStateEnabled());
+ LayoutRectRecorder recorder(*this);
LayoutRepainter repainter(*this, SVGRenderSupport::checkForSVGRepaintDuringLayout(this) || selfWillPaint());
// Allow RenderSVGViewportContainer to update its viewport.
@@ -183,7 +186,14 @@ bool RenderSVGContainer::nodeAtFloatPoint(const HitTestRequest& request, HitTest
}
}
- // Spec: Only graphical elements can be targeted by the mouse, period.
+ // pointer-events=boundingBox makes it possible for containers to be direct targets
+ if (style()->pointerEvents() == PE_BOUNDINGBOX) {
+ ASSERT(isObjectBoundingBoxValid());
+ if (objectBoundingBox().contains(localPoint)) {
+ updateHitTestResult(result, roundedLayoutPoint(localPoint));
+ return true;
+ }
+ }
// 16.4: "If there are no graphics elements whose relevant graphics content is under the pointer (i.e., there is no target element), the event is not dispatched."
return false;
}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGContainer.h b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGContainer.h
index b25932bedef..fd4e74db96b 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGContainer.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGContainer.h
@@ -87,20 +87,7 @@ private:
bool m_needsBoundariesUpdate : 1;
};
-inline RenderSVGContainer* toRenderSVGContainer(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isSVGContainer());
- return static_cast<RenderSVGContainer*>(object);
-}
-
-inline const RenderSVGContainer* toRenderSVGContainer(const RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isSVGContainer());
- return static_cast<const RenderSVGContainer*>(object);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toRenderSVGContainer(const RenderSVGContainer*);
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderSVGContainer, isSVGContainer());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGForeignObject.cpp b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGForeignObject.cpp
index 2506ee4e1c7..e27e037926f 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGForeignObject.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGForeignObject.cpp
@@ -23,14 +23,15 @@
#include "core/rendering/svg/RenderSVGForeignObject.h"
-#include "core/platform/graphics/GraphicsContextStateSaver.h"
#include "core/rendering/HitTestResult.h"
+#include "core/rendering/LayoutRectRecorder.h"
#include "core/rendering/LayoutRepainter.h"
#include "core/rendering/RenderView.h"
#include "core/rendering/svg/SVGRenderSupport.h"
#include "core/rendering/svg/SVGRenderingContext.h"
#include "core/rendering/svg/SVGResourcesCache.h"
#include "core/svg/SVGForeignObjectElement.h"
+#include "platform/graphics/GraphicsContextStateSaver.h"
namespace WebCore {
@@ -122,6 +123,7 @@ void RenderSVGForeignObject::layout()
ASSERT(needsLayout());
ASSERT(!view()->layoutStateEnabled()); // RenderSVGRoot disables layoutState for the SVG rendering tree.
+ LayoutRectRecorder recorder(*this);
LayoutRepainter repainter(*this, SVGRenderSupport::checkForSVGRepaintDuringLayout(this));
SVGForeignObjectElement* foreign = toSVGForeignObjectElement(node());
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGGradientStop.cpp b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGGradientStop.cpp
index b3b0c55eb25..ca5f315a7bc 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGGradientStop.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGGradientStop.cpp
@@ -55,8 +55,7 @@ void RenderSVGGradientStop::styleDidChange(StyleDifference diff, const RenderSty
if (!renderer)
return;
- ASSERT(renderer->isSVGResourceContainer());
- RenderSVGResourceContainer* container = renderer->toRenderSVGResourceContainer();
+ RenderSVGResourceContainer* container = toRenderSVGResourceContainer(renderer);
container->removeAllClientsFromCache();
}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGGradientStop.h b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGGradientStop.h
index bf2a10aabe8..e56274e3ffc 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGGradientStop.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGGradientStop.h
@@ -54,11 +54,7 @@ private:
SVGGradientElement* gradientElement() const;
};
-inline const RenderSVGGradientStop* toRenderSVGGradientStop(const RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isSVGGradientStop());
- return static_cast<const RenderSVGGradientStop*>(object);
-}
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderSVGGradientStop, isSVGGradientStop());
}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGHiddenContainer.cpp b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGHiddenContainer.cpp
index 1bfe249ef8b..0f1578935a5 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGHiddenContainer.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGHiddenContainer.cpp
@@ -21,6 +21,8 @@
#include "core/rendering/svg/RenderSVGHiddenContainer.h"
+#include "core/rendering/LayoutRectRecorder.h"
+
namespace WebCore {
RenderSVGHiddenContainer::RenderSVGHiddenContainer(SVGElement* element)
@@ -31,7 +33,9 @@ RenderSVGHiddenContainer::RenderSVGHiddenContainer(SVGElement* element)
void RenderSVGHiddenContainer::layout()
{
ASSERT(needsLayout());
+ LayoutRectRecorder recorder(*this);
SVGRenderSupport::layoutChildren(this, selfNeedsLayout());
+ updateCachedBoundaries();
clearNeedsLayout();
}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGImage.cpp b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGImage.cpp
index 7cf23884f16..9e2e4cd9414 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGImage.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGImage.cpp
@@ -27,8 +27,9 @@
#include "core/rendering/svg/RenderSVGImage.h"
-#include "core/platform/graphics/GraphicsContextStateSaver.h"
+#include "core/rendering/GraphicsContextAnnotator.h"
#include "core/rendering/ImageQualityController.h"
+#include "core/rendering/LayoutRectRecorder.h"
#include "core/rendering/LayoutRepainter.h"
#include "core/rendering/PointerEventsHitRules.h"
#include "core/rendering/RenderImageResource.h"
@@ -37,6 +38,7 @@
#include "core/rendering/svg/SVGResources.h"
#include "core/rendering/svg/SVGResourcesCache.h"
#include "core/svg/SVGImageElement.h"
+#include "platform/graphics/GraphicsContextStateSaver.h"
namespace WebCore {
@@ -91,6 +93,7 @@ void RenderSVGImage::layout()
{
ASSERT(needsLayout());
+ LayoutRectRecorder recorder(*this);
LayoutRepainter repainter(*this, SVGRenderSupport::checkForSVGRepaintDuringLayout(this) && selfNeedsLayout());
updateImageViewport();
@@ -136,11 +139,11 @@ void RenderSVGImage::paint(PaintInfo& paintInfo, const LayoutPoint&)
GraphicsContextStateSaver stateSaver(*childPaintInfo.context);
childPaintInfo.applyTransform(m_localTransform);
- if (childPaintInfo.phase == PaintPhaseForeground) {
+ if (childPaintInfo.phase == PaintPhaseForeground && !m_objectBoundingBox.isEmpty()) {
SVGRenderingContext renderingContext(this, childPaintInfo);
if (renderingContext.isRenderingPrepared()) {
- if (style()->svgStyle()->bufferedRendering() == BR_STATIC && renderingContext.bufferForeground(m_bufferedForeground))
+ if (style()->svgStyle()->bufferedRendering() == BR_STATIC && renderingContext.bufferForeground(m_bufferedForeground))
return;
paintForeground(childPaintInfo);
@@ -187,7 +190,7 @@ bool RenderSVGImage::nodeAtFloatPoint(const HitTestRequest& request, HitTestResu
if (!SVGRenderSupport::pointInClippingArea(this, localPoint))
return false;
- if (hitRules.canHitFill) {
+ if (hitRules.canHitFill || hitRules.canHitBoundingBox) {
if (m_objectBoundingBox.contains(localPoint)) {
updateHitTestResult(result, roundedLayoutPoint(localPoint));
return true;
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGImage.h b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGImage.h
index 15c5b5c9391..e87392e04fa 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGImage.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGImage.h
@@ -42,7 +42,6 @@ public:
virtual void setNeedsTransformUpdate() { m_needsTransformUpdate = true; }
RenderImageResource* imageResource() { return m_imageResource.get(); }
- const RenderImageResource* imageResource() const { return m_imageResource.get(); }
// Note: Assumes the PaintInfo context has had all local transforms applied.
void paintForeground(PaintInfo&);
@@ -69,7 +68,6 @@ private:
virtual bool nodeAtFloatPoint(const HitTestRequest&, HitTestResult&, const FloatPoint& pointInParent, HitTestAction);
virtual AffineTransform localTransform() const { return m_localTransform; }
- void calculateImageViewport();
bool m_needsBoundariesUpdate : 1;
bool m_needsTransformUpdate : 1;
@@ -81,20 +79,7 @@ private:
OwnPtr<ImageBuffer> m_bufferedForeground;
};
-inline RenderSVGImage* toRenderSVGImage(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isSVGImage());
- return static_cast<RenderSVGImage*>(object);
-}
-
-inline const RenderSVGImage* toRenderSVGImage(const RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isSVGImage());
- return static_cast<const RenderSVGImage*>(object);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toRenderSVGImage(const RenderSVGImage*);
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderSVGImage, isSVGImage());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGInline.cpp b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGInline.cpp
index 917ea334aee..68b1a4029cd 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGInline.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGInline.cpp
@@ -112,15 +112,11 @@ void RenderSVGInline::willBeDestroyed()
RenderInline::willBeDestroyed();
}
-void RenderSVGInline::styleWillChange(StyleDifference diff, const RenderStyle* newStyle)
+void RenderSVGInline::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
{
if (diff == StyleDifferenceLayout)
setNeedsBoundariesUpdate();
- RenderInline::styleWillChange(diff, newStyle);
-}
-void RenderSVGInline::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
-{
RenderInline::styleDidChange(diff, oldStyle);
SVGResourcesCache::clientStyleChanged(this, diff, style());
}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGInline.h b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGInline.h
index 4cc390f3f59..43634a39c22 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGInline.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGInline.h
@@ -54,7 +54,6 @@ private:
virtual InlineFlowBox* createInlineFlowBox() OVERRIDE FINAL;
virtual void willBeDestroyed() OVERRIDE FINAL;
- virtual void styleWillChange(StyleDifference, const RenderStyle* newStyle) OVERRIDE FINAL;
virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle) OVERRIDE FINAL;
virtual void addChild(RenderObject* child, RenderObject* beforeChild = 0) OVERRIDE FINAL;
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGInlineText.cpp b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGInlineText.cpp
index cc612ca9c53..e8041f8c1c2 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGInlineText.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGInlineText.cpp
@@ -27,7 +27,6 @@
#include "core/css/CSSFontSelector.h"
#include "core/css/FontSize.h"
-#include "core/css/resolver/StyleResolver.h"
#include "core/editing/VisiblePosition.h"
#include "core/rendering/svg/RenderSVGText.h"
#include "core/rendering/svg/SVGInlineTextBox.h"
@@ -219,11 +218,6 @@ void RenderSVGInlineText::computeNewScaledFontForStyle(RenderObject* renderer, c
ASSERT(style);
ASSERT(renderer);
- Document& document = renderer->document();
-
- StyleResolver* styleResolver = document.styleResolver();
- ASSERT(styleResolver);
-
// Alter font-size to the right on-screen value to avoid scaling the glyphs themselves, except when GeometricPrecision is specified.
scalingFactor = SVGRenderingContext::calculateScreenFontSizeScalingFactor(renderer);
if (scalingFactor == 1 || !scalingFactor) {
@@ -237,11 +231,12 @@ void RenderSVGInlineText::computeNewScaledFontForStyle(RenderObject* renderer, c
FontDescription fontDescription(style->fontDescription());
+ Document& document = renderer->document();
// FIXME: We need to better handle the case when we compute very small fonts below (below 1pt).
fontDescription.setComputedSize(FontSize::getComputedSizeFromSpecifiedSize(&document, scalingFactor, fontDescription.isAbsoluteSize(), fontDescription.specifiedSize(), DoNotUseSmartMinimumForFontSize));
scaledFont = Font(fontDescription, 0, 0);
- scaledFont.update(styleResolver->fontSelector());
+ scaledFont.update(document.styleEngine()->fontSelector());
}
}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGInlineText.h b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGInlineText.h
index 8ce8fd2b0eb..8c7f711a68f 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGInlineText.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGInlineText.h
@@ -52,7 +52,6 @@ private:
virtual FloatRect objectBoundingBox() const { return floatLinesBoundingBox(); }
- virtual bool requiresLayer() const { return false; }
virtual bool isSVGInlineText() const { return true; }
virtual PositionWithAffinity positionForPoint(const LayoutPoint&) OVERRIDE FINAL;
@@ -65,20 +64,7 @@ private:
SVGTextLayoutAttributes m_layoutAttributes;
};
-inline RenderSVGInlineText* toRenderSVGInlineText(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isSVGInlineText());
- return static_cast<RenderSVGInlineText*>(object);
-}
-
-inline const RenderSVGInlineText* toRenderSVGInlineText(const RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isSVGInlineText());
- return static_cast<const RenderSVGInlineText*>(object);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toRenderSVGInlineText(const RenderSVGInlineText*);
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderSVGInlineText, isSVGInlineText());
}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGModelObject.cpp b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGModelObject.cpp
index 124f5a02682..12da706b521 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGModelObject.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGModelObject.cpp
@@ -35,7 +35,7 @@
#include "SVGNames.h"
#include "core/rendering/svg/RenderSVGRoot.h"
#include "core/rendering/svg/SVGResourcesCache.h"
-#include "core/svg/SVGElement.h"
+#include "core/svg/SVGGraphicsElement.h"
namespace WebCore {
@@ -105,18 +105,14 @@ void RenderSVGModelObject::addLayerHitTestRects(LayerHitTestRects&, const Render
// We don't walk into SVG trees at all - just report their container.
}
-void RenderSVGModelObject::styleWillChange(StyleDifference diff, const RenderStyle* newStyle)
+void RenderSVGModelObject::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
{
if (diff == StyleDifferenceLayout) {
setNeedsBoundariesUpdate();
- if (newStyle->hasTransform())
+ if (style()->hasTransform())
setNeedsTransformUpdate();
}
- RenderObject::styleWillChange(diff, newStyle);
-}
-void RenderSVGModelObject::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
-{
RenderObject::styleDidChange(diff, oldStyle);
SVGResourcesCache::clientStyleChanged(this, diff, style());
}
@@ -127,12 +123,12 @@ bool RenderSVGModelObject::nodeAtPoint(const HitTestRequest&, HitTestResult&, co
return false;
}
-static void getElementCTM(SVGElement* element, AffineTransform& transform)
+static void getElementCTM(SVGGraphicsElement* element, AffineTransform& transform)
{
ASSERT(element);
element->document().updateLayoutIgnorePendingStylesheets();
- SVGElement* stopAtElement = SVGLocatable::nearestViewportElement(element);
+ SVGElement* stopAtElement = element->nearestViewportElement();
ASSERT(stopAtElement);
AffineTransform localTransform;
@@ -186,7 +182,7 @@ bool RenderSVGModelObject::checkIntersection(RenderObject* renderer, const SVGRe
if (!isGraphicsElement(renderer))
return false;
AffineTransform ctm;
- SVGElement* svgElement = toSVGElement(renderer->node());
+ SVGGraphicsElement* svgElement = toSVGGraphicsElement(renderer->node());
getElementCTM(svgElement, ctm);
ASSERT(svgElement->renderer());
return intersectsAllowingEmpty(rect, ctm.mapRect(svgElement->renderer()->repaintRectInLocalCoordinates()));
@@ -199,7 +195,7 @@ bool RenderSVGModelObject::checkEnclosure(RenderObject* renderer, const SVGRect&
if (!isGraphicsElement(renderer))
return false;
AffineTransform ctm;
- SVGElement* svgElement = toSVGElement(renderer->node());
+ SVGGraphicsElement* svgElement = toSVGGraphicsElement(renderer->node());
getElementCTM(svgElement, ctm);
ASSERT(svgElement->renderer());
return rect.contains(ctm.mapRect(svgElement->renderer()->repaintRectInLocalCoordinates()));
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGModelObject.h b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGModelObject.h
index e06d68845f4..c8df10aca7d 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGModelObject.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGModelObject.h
@@ -58,7 +58,6 @@ public:
virtual void mapLocalToContainer(const RenderLayerModelObject* repaintContainer, TransformState&, MapCoordinatesFlags = ApplyContainerFlip, bool* wasFixed = 0) const OVERRIDE FINAL;
virtual const RenderObject* pushMappingToContainer(const RenderLayerModelObject* ancestorToStopAt, RenderGeometryMap&) const OVERRIDE FINAL;
- virtual void styleWillChange(StyleDifference, const RenderStyle* newStyle) OVERRIDE FINAL;
virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle);
static bool checkIntersection(RenderObject*, const SVGRect&);
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGPath.cpp b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGPath.cpp
index 0eadbf97e4e..8f60c8d1cfb 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGPath.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGPath.cpp
@@ -29,8 +29,8 @@
#include "core/rendering/svg/RenderSVGPath.h"
-#include "core/platform/graphics/GraphicsContextStateSaver.h"
#include "core/rendering/svg/SVGSubpathData.h"
+#include "platform/graphics/GraphicsContextStateSaver.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGPath.h b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGPath.h
index 5d83f86468d..8cec15c4c92 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGPath.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGPath.h
@@ -53,11 +53,7 @@ private:
Vector<FloatPoint> m_zeroLengthLinecapLocations;
};
-inline RenderSVGPath* toRenderSVGPath(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isSVGPath());
- return static_cast<RenderSVGPath*>(object);
-}
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderSVGPath, isSVGPath());
}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResource.cpp b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResource.cpp
index ea7931aee47..4dd3ae01c90 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResource.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResource.cpp
@@ -24,8 +24,8 @@
#include "core/rendering/svg/RenderSVGResource.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameView.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
#include "core/rendering/svg/RenderSVGResourceClipper.h"
#include "core/rendering/svg/RenderSVGResourceFilter.h"
#include "core/rendering/svg/RenderSVGResourceMasker.h"
@@ -203,7 +203,7 @@ void RenderSVGResource::markForLayoutAndParentResourceInvalidation(RenderObject*
if (current->isSVGResourceContainer()) {
// This will process the rest of the ancestors.
- current->toRenderSVGResourceContainer()->removeAllClientsFromCache();
+ toRenderSVGResourceContainer(current)->removeAllClientsFromCache();
break;
}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResource.h b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResource.h
index 5feaa1aab21..676562dd01c 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResource.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResource.h
@@ -62,7 +62,6 @@ public:
virtual bool applyResource(RenderObject*, RenderStyle*, GraphicsContext*&, unsigned short resourceMode) = 0;
virtual void postApplyResource(RenderObject*, GraphicsContext*&, unsigned short, const Path*, const RenderSVGShape*) { }
- virtual FloatRect resourceBoundingBox(RenderObject*) = 0;
virtual RenderSVGResourceType resourceType() const = 0;
@@ -83,6 +82,9 @@ public:
static void markForLayoutAndParentResourceInvalidation(RenderObject*, bool needsLayout = true);
};
+#define DEFINE_RENDER_SVG_RESOURCE_TYPE_CASTS(thisType, typeName) \
+ DEFINE_TYPE_CASTS(thisType, RenderSVGResource, resource, resource->resourceType() == typeName, resource.resourceType() == typeName)
+
}
#endif
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceClipper.cpp b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceClipper.cpp
index 6b39c6ba40f..b98db0f7c86 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceClipper.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceClipper.cpp
@@ -26,19 +26,20 @@
#include "RuntimeEnabledFeatures.h"
#include "SVGNames.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameView.h"
-#include "core/platform/graphics/GraphicsContextStateSaver.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
#include "core/rendering/HitTestResult.h"
#include "core/rendering/svg/SVGRenderingContext.h"
#include "core/rendering/svg/SVGResources.h"
#include "core/rendering/svg/SVGResourcesCache.h"
#include "core/svg/SVGUseElement.h"
+#include "platform/graphics/DisplayList.h"
+#include "platform/graphics/GraphicsContextStateSaver.h"
#include "wtf/TemporaryChange.h"
namespace WebCore {
-RenderSVGResourceType RenderSVGResourceClipper::s_resourceType = ClipperResourceType;
+const RenderSVGResourceType RenderSVGResourceClipper::s_resourceType = ClipperResourceType;
RenderSVGResourceClipper::RenderSVGResourceClipper(SVGClipPathElement* node)
: RenderSVGResourceContainer(node)
@@ -52,6 +53,7 @@ RenderSVGResourceClipper::~RenderSVGResourceClipper()
void RenderSVGResourceClipper::removeAllClientsFromCache(bool markForInvalidation)
{
+ m_clipContentDisplayList.clear();
m_clipBoundaries = FloatRect();
markAllClientsForInvalidation(markForInvalidation ? LayoutAndBoundariesInvalidation : ParentOnlyInvalidation);
}
@@ -74,6 +76,8 @@ bool RenderSVGResourceClipper::applyStatefulResource(RenderObject* object, Graph
ASSERT(object);
ASSERT(context);
+ clearInvalidationMask();
+
return applyClippingToContext(object, object->objectBoundingBox(), object->repaintRectInLocalCoordinates(), context, clipperContext);
}
@@ -144,6 +148,7 @@ bool RenderSVGResourceClipper::applyClippingToContext(RenderObject* target, cons
const FloatRect& repaintRect, GraphicsContext* context, ClipperContext& clipperContext)
{
ASSERT(target);
+ ASSERT(target->node());
ASSERT(context);
ASSERT(clipperContext.state == ClipperContext::NotAppliedState);
ASSERT_WITH_SECURITY_IMPLICATION(!needsLayout());
@@ -152,8 +157,17 @@ bool RenderSVGResourceClipper::applyClippingToContext(RenderObject* target, cons
return false;
TemporaryChange<bool> inClipExpansionChange(m_inClipExpansion, true);
- // First, try to apply the clip as a clipPath.
AffineTransform animatedLocalTransform = toSVGClipPathElement(element())->animatedLocalTransform();
+ // When drawing a clip for non-SVG elements, the CTM does not include the zoom factor.
+ // In this case, we need to apply the zoom scale explicitly - but only for clips with
+ // userSpaceOnUse units (the zoom is accounted for objectBoundingBox-resolved lengths).
+ if (!target->node()->isSVGElement()
+ && toSVGClipPathElement(element())->clipPathUnitsCurrentValue() == SVGUnitTypes::SVG_UNIT_TYPE_USERSPACEONUSE) {
+ ASSERT(style());
+ animatedLocalTransform.scale(style()->effectiveZoom());
+ }
+
+ // First, try to apply the clip as a clipPath.
if (tryPathOnlyClipping(context, animatedLocalTransform, targetBoundingBox)) {
clipperContext.state = ClipperContext::AppliedPathState;
return true;
@@ -184,14 +198,14 @@ bool RenderSVGResourceClipper::applyClippingToContext(RenderObject* target, cons
}
}
- drawMaskContent(context, targetBoundingBox);
+ drawClipMaskContent(context, targetBoundingBox);
if (clipPathClipper)
clipPathClipper->postApplyStatefulResource(this, context, clipPathClipperContext);
}
// Masked content layer start.
- context->beginMaskedLayer(repaintRect);
+ context->beginLayer(1, CompositeSourceIn, &repaintRect);
return true;
}
@@ -219,19 +233,33 @@ void RenderSVGResourceClipper::postApplyStatefulResource(RenderObject*, Graphics
}
}
-void RenderSVGResourceClipper::drawMaskContent(GraphicsContext* context, const FloatRect& targetBoundingBox)
+void RenderSVGResourceClipper::drawClipMaskContent(GraphicsContext* context, const FloatRect& targetBoundingBox)
{
- ASSERT(frame());
ASSERT(context);
- // Adjust the mask image context according to the target objectBoundingBox.
- AffineTransform maskContentTransformation;
- if (toSVGClipPathElement(element())->clipPathUnitsCurrentValue() == SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX) {
- maskContentTransformation.translate(targetBoundingBox.x(), targetBoundingBox.y());
- maskContentTransformation.scaleNonUniform(targetBoundingBox.width(), targetBoundingBox.height());
- context->concatCTM(maskContentTransformation);
+ AffineTransform contentTransformation;
+ SVGUnitTypes::SVGUnitType contentUnits = toSVGClipPathElement(element())->clipPathUnitsCurrentValue();
+ if (contentUnits == SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX) {
+ contentTransformation.translate(targetBoundingBox.x(), targetBoundingBox.y());
+ contentTransformation.scaleNonUniform(targetBoundingBox.width(), targetBoundingBox.height());
+ context->concatCTM(contentTransformation);
}
+ if (!m_clipContentDisplayList)
+ m_clipContentDisplayList = asDisplayList(context, contentTransformation);
+
+ ASSERT(m_clipContentDisplayList);
+ context->drawDisplayList(m_clipContentDisplayList.get());
+}
+
+PassRefPtr<DisplayList> RenderSVGResourceClipper::asDisplayList(GraphicsContext* context,
+ const AffineTransform& contentTransformation)
+{
+ ASSERT(context);
+ ASSERT(frame());
+
+ context->beginRecording(repaintRectInLocalCoordinates());
+
// Switch to a paint behavior where all children of this <clipPath> will be rendered using special constraints:
// - fill-opacity/stroke-opacity/opacity set to 1
// - masker/filter not applied when rendering the children
@@ -269,10 +297,12 @@ void RenderSVGResourceClipper::drawMaskContent(GraphicsContext* context, const F
if (isUseElement)
renderer = childNode->renderer();
- SVGRenderingContext::renderSubtree(context, renderer, maskContentTransformation);
+ SVGRenderingContext::renderSubtree(context, renderer, contentTransformation);
}
frame()->view()->setPaintBehavior(oldBehavior);
+
+ return context->endRecording();
}
void RenderSVGResourceClipper::calculateClipContentRepaintRect()
@@ -316,7 +346,7 @@ bool RenderSVGResourceClipper::hitTestClipContent(const FloatRect& objectBoundin
continue;
IntPoint hitPoint;
HitTestResult result(hitPoint);
- if (renderer->nodeAtFloatPoint(HitTestRequest(HitTestRequest::SVGClipContent | HitTestRequest::DisallowShadowContent), result, point, HitTestForeground))
+ if (renderer->nodeAtFloatPoint(HitTestRequest(HitTestRequest::SVGClipContent | HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent), result, point, HitTestForeground))
return true;
}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceClipper.h b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceClipper.h
index 839583ce7d9..ae89b1e3df5 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceClipper.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceClipper.h
@@ -25,6 +25,8 @@
namespace WebCore {
+class DisplayList;
+
struct ClipperContext {
WTF_MAKE_FAST_ALLOCATED;
public:
@@ -62,31 +64,29 @@ public:
// FIXME: We made applyClippingToContext public because we cannot call applyResource on HTML elements (it asserts on RenderObject::objectBoundingBox)
bool applyClippingToContext(RenderObject*, const FloatRect&, const FloatRect&, GraphicsContext*, ClipperContext&);
- virtual FloatRect resourceBoundingBox(RenderObject*);
+ FloatRect resourceBoundingBox(RenderObject*);
- virtual RenderSVGResourceType resourceType() const { return ClipperResourceType; }
+ virtual RenderSVGResourceType resourceType() const { return s_resourceType; }
bool hitTestClipContent(const FloatRect&, const FloatPoint&);
SVGUnitTypes::SVGUnitType clipPathUnits() const { return toSVGClipPathElement(element())->clipPathUnitsCurrentValue(); }
- static RenderSVGResourceType s_resourceType;
+ static const RenderSVGResourceType s_resourceType;
private:
bool tryPathOnlyClipping(GraphicsContext*, const AffineTransform&, const FloatRect&);
- void drawMaskContent(GraphicsContext*, const FloatRect& targetBoundingBox);
+ void drawClipMaskContent(GraphicsContext*, const FloatRect& targetBoundingBox);
+ PassRefPtr<DisplayList> asDisplayList(GraphicsContext*, const AffineTransform&);
void calculateClipContentRepaintRect();
+ RefPtr<DisplayList> m_clipContentDisplayList;
FloatRect m_clipBoundaries;
// Reference cycle detection.
bool m_inClipExpansion;
};
-inline RenderSVGResourceClipper* toRenderSVGResourceClipper(RenderSVGResource* resource)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!resource || resource->resourceType() == ClipperResourceType);
- return static_cast<RenderSVGResourceClipper*>(resource);
-}
+DEFINE_RENDER_SVG_RESOURCE_TYPE_CASTS(RenderSVGResourceClipper, ClipperResourceType);
}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceContainer.cpp b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceContainer.cpp
index 78966fe064c..55405a77a08 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceContainer.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceContainer.cpp
@@ -21,6 +21,7 @@
#include "core/rendering/svg/RenderSVGResourceContainer.h"
+#include "core/rendering/LayoutRectRecorder.h"
#include "core/rendering/RenderLayer.h"
#include "core/rendering/RenderView.h"
#include "core/rendering/svg/SVGRenderingContext.h"
@@ -39,10 +40,11 @@ static inline SVGDocumentExtensions* svgExtensionsFromElement(SVGElement* elemen
RenderSVGResourceContainer::RenderSVGResourceContainer(SVGElement* node)
: RenderSVGHiddenContainer(node)
+ , m_isInLayout(false)
, m_id(node->getIdAttribute())
+ , m_invalidationMask(0)
, m_registered(false)
, m_isInvalidating(false)
- , m_isInLayout(false)
{
}
@@ -54,17 +56,18 @@ RenderSVGResourceContainer::~RenderSVGResourceContainer()
void RenderSVGResourceContainer::layout()
{
+ // FIXME: Investigate a way to detect and break resource layout dependency cycles early.
+ // Then we can remove this method altogether, and fall back onto RenderSVGHiddenContainer::layout().
ASSERT(needsLayout());
if (m_isInLayout)
return;
+ LayoutRectRecorder recorder(*this);
TemporaryChange<bool> inLayoutChange(m_isInLayout, true);
- // Invalidate all resources if our layout changed.
- if (everHadLayout() && selfNeedsLayout())
- removeAllClientsFromCache();
-
RenderSVGHiddenContainer::layout();
+
+ clearInvalidationMask();
}
void RenderSVGResourceContainer::willBeDestroyed()
@@ -101,6 +104,10 @@ void RenderSVGResourceContainer::markAllClientsForInvalidation(InvalidationMode
if ((m_clients.isEmpty() && m_clientLayers.isEmpty()) || m_isInvalidating)
return;
+ if (m_invalidationMask & mode)
+ return;
+
+ m_invalidationMask |= mode;
m_isInvalidating = true;
bool needsLayout = mode == LayoutAndBoundariesInvalidation;
bool markForInvalidation = mode != ParentOnlyInvalidation;
@@ -109,7 +116,7 @@ void RenderSVGResourceContainer::markAllClientsForInvalidation(InvalidationMode
for (HashSet<RenderObject*>::iterator it = m_clients.begin(); it != end; ++it) {
RenderObject* client = *it;
if (client->isSVGResourceContainer()) {
- client->toRenderSVGResourceContainer()->removeAllClientsFromCache(markForInvalidation);
+ toRenderSVGResourceContainer(client)->removeAllClientsFromCache(markForInvalidation);
continue;
}
@@ -142,8 +149,12 @@ void RenderSVGResourceContainer::markClientForInvalidation(RenderObject* client,
client->setNeedsBoundariesUpdate();
break;
case RepaintInvalidation:
- if (client->view())
- client->repaint();
+ if (client->view()) {
+ if (RuntimeEnabledFeatures::repaintAfterLayoutEnabled() && frameView()->isInLayout())
+ client->setShouldDoFullRepaintAfterLayout(true);
+ else
+ client->repaint();
+ }
break;
case ParentOnlyInvalidation:
break;
@@ -154,6 +165,7 @@ void RenderSVGResourceContainer::addClient(RenderObject* client)
{
ASSERT(client);
m_clients.add(client);
+ clearInvalidationMask();
}
void RenderSVGResourceContainer::removeClient(RenderObject* client)
@@ -169,12 +181,14 @@ void RenderSVGResourceContainer::addClientRenderLayer(Node* node)
if (!node->renderer() || !node->renderer()->hasLayer())
return;
m_clientLayers.add(toRenderLayerModelObject(node->renderer())->layer());
+ clearInvalidationMask();
}
void RenderSVGResourceContainer::addClientRenderLayer(RenderLayer* client)
{
ASSERT(client);
m_clientLayers.add(client);
+ clearInvalidationMask();
}
void RenderSVGResourceContainer::removeClientRenderLayer(RenderLayer* client)
@@ -183,6 +197,17 @@ void RenderSVGResourceContainer::removeClientRenderLayer(RenderLayer* client)
m_clientLayers.remove(client);
}
+void RenderSVGResourceContainer::invalidateCacheAndMarkForLayout(SubtreeLayoutScope* layoutScope)
+{
+ if (selfNeedsLayout())
+ return;
+
+ setNeedsLayout(MarkContainingBlockChain, layoutScope);
+
+ if (everHadLayout())
+ removeAllClientsFromCache();
+}
+
void RenderSVGResourceContainer::registerResource()
{
SVGDocumentExtensions* extensions = svgExtensionsFromElement(element());
@@ -233,7 +258,7 @@ AffineTransform RenderSVGResourceContainer::transformOnNonScalingStroke(RenderOb
return resourceTransform;
SVGGraphicsElement* element = toSVGGraphicsElement(object->node());
- AffineTransform transform = element->getScreenCTM(SVGLocatable::DisallowStyleUpdate);
+ AffineTransform transform = element->getScreenCTM(SVGGraphicsElement::DisallowStyleUpdate);
transform *= resourceTransform;
return transform;
}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceContainer.h b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceContainer.h
index 9489a6f8a2d..71d3c6f0cf1 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceContainer.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceContainer.h
@@ -37,7 +37,6 @@ public:
virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle) OVERRIDE FINAL;
virtual bool isSVGResourceContainer() const OVERRIDE FINAL { return true; }
- virtual RenderSVGResourceContainer* toRenderSVGResourceContainer() OVERRIDE FINAL { return this; }
static bool shouldTransformOnTextPainting(RenderObject*, AffineTransform&);
static AffineTransform transformOnNonScalingStroke(RenderObject*, const AffineTransform& resourceTransform);
@@ -47,12 +46,15 @@ public:
void addClientRenderLayer(RenderLayer*);
void removeClientRenderLayer(RenderLayer*);
+ void invalidateCacheAndMarkForLayout(SubtreeLayoutScope* = 0);
+
protected:
+ // When adding modes, make sure we don't overflow m_invalidationMask below.
enum InvalidationMode {
- LayoutAndBoundariesInvalidation,
- BoundariesInvalidation,
- RepaintInvalidation,
- ParentOnlyInvalidation
+ LayoutAndBoundariesInvalidation = 1 << 0,
+ BoundariesInvalidation = 1 << 1,
+ RepaintInvalidation = 1 << 2,
+ ParentOnlyInvalidation = 1 << 3
};
// Used from the invalidateClient/invalidateClients methods from classes, inheriting from us.
@@ -60,6 +62,8 @@ protected:
void markAllClientLayersForInvalidation();
void markClientForInvalidation(RenderObject*, InvalidationMode);
+ void clearInvalidationMask() { m_invalidationMask = 0; }
+
bool m_isInLayout;
private:
@@ -71,8 +75,13 @@ private:
void registerResource();
AtomicString m_id;
+ // Track global (markAllClientsForInvalidation) invals to avoid redundant crawls.
+ unsigned m_invalidationMask : 8;
+
bool m_registered : 1;
bool m_isInvalidating : 1;
+ // 22 padding bits available
+
HashSet<RenderObject*> m_clients;
HashSet<RenderLayer*> m_clientLayers;
};
@@ -97,6 +106,8 @@ Renderer* getRenderSVGResourceById(Document& document, const AtomicString& id)
return 0;
}
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderSVGResourceContainer, isSVGResourceContainer());
+
}
#endif
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceFilter.cpp b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceFilter.cpp
index 09494b3acd9..840c563c4c2 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceFilter.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceFilter.cpp
@@ -25,19 +25,20 @@
#include "core/rendering/svg/RenderSVGResourceFilter.h"
-#include "core/page/Page.h"
-#include "core/page/Settings.h"
-#include "core/platform/graphics/filters/SourceAlpha.h"
-#include "core/platform/graphics/filters/SourceGraphic.h"
+#include "core/frame/Settings.h"
#include "core/rendering/svg/RenderSVGResourceFilterPrimitive.h"
#include "core/rendering/svg/SVGRenderingContext.h"
#include "core/svg/SVGFilterPrimitiveStandardAttributes.h"
+#include "platform/graphics/UnacceleratedImageBufferSurface.h"
+#include "platform/graphics/filters/SourceAlpha.h"
+#include "platform/graphics/filters/SourceGraphic.h"
+#include "platform/graphics/gpu/AcceleratedImageBufferSurface.h"
using namespace std;
namespace WebCore {
-RenderSVGResourceType RenderSVGResourceFilter::s_resourceType = FilterResourceType;
+const RenderSVGResourceType RenderSVGResourceFilter::s_resourceType = FilterResourceType;
RenderSVGResourceFilter::RenderSVGResourceFilter(SVGFilterElement* node)
: RenderSVGResourceContainer(node)
@@ -46,20 +47,12 @@ RenderSVGResourceFilter::RenderSVGResourceFilter(SVGFilterElement* node)
RenderSVGResourceFilter::~RenderSVGResourceFilter()
{
- if (m_filter.isEmpty())
- return;
-
- deleteAllValues(m_filter);
m_filter.clear();
}
void RenderSVGResourceFilter::removeAllClientsFromCache(bool markForInvalidation)
{
- if (!m_filter.isEmpty()) {
- deleteAllValues(m_filter);
- m_filter.clear();
- }
-
+ m_filter.clear();
markAllClientsForInvalidation(markForInvalidation ? LayoutAndBoundariesInvalidation : ParentOnlyInvalidation);
}
@@ -71,7 +64,7 @@ void RenderSVGResourceFilter::removeClientFromCache(RenderObject* client, bool m
if (filterData->savedContext)
filterData->state = FilterData::MarkedForRemoval;
else
- delete m_filter.take(client);
+ m_filter.remove(client);
}
markClientForInvalidation(client, markForInvalidation ? BoundariesInvalidation : ParentOnlyInvalidation);
@@ -124,16 +117,21 @@ bool RenderSVGResourceFilter::fitsInMaximumImageSize(const FloatSize& size, Floa
}
static bool createImageBuffer(const FloatRect& targetRect, const AffineTransform& absoluteTransform,
- OwnPtr<ImageBuffer>& imageBuffer, RenderingMode renderingMode)
+ OwnPtr<ImageBuffer>& imageBuffer, bool accelerated)
{
IntRect paintRect = SVGRenderingContext::calculateImageBufferRect(targetRect, absoluteTransform);
// Don't create empty ImageBuffers.
if (paintRect.isEmpty())
return false;
- OwnPtr<ImageBuffer> image = ImageBuffer::create(paintRect.size(), 1, renderingMode);
- if (!image)
+ OwnPtr<ImageBufferSurface> surface;
+ if (accelerated)
+ surface = adoptPtr(new AcceleratedImageBufferSurface(paintRect.size()));
+ if (!accelerated || !surface->isValid())
+ surface = adoptPtr(new UnacceleratedImageBufferSurface(paintRect.size()));
+ if (!surface->isValid())
return false;
+ OwnPtr<ImageBuffer> image = ImageBuffer::create(surface.release());
GraphicsContext* imageContext = image->context();
ASSERT(imageContext);
@@ -151,6 +149,8 @@ bool RenderSVGResourceFilter::applyResource(RenderObject* object, RenderStyle*,
ASSERT(context);
ASSERT_UNUSED(resourceMode, resourceMode == ApplyToDefaultMode);
+ clearInvalidationMask();
+
if (m_filter.contains(object)) {
FilterData* filterData = m_filter.get(object);
if (filterData->state == FilterData::PaintingSource || filterData->state == FilterData::Applying)
@@ -213,13 +213,13 @@ bool RenderSVGResourceFilter::applyResource(RenderObject* object, RenderStyle*,
if (!lastEffect)
return false;
- RenderSVGResourceFilterPrimitive::determineFilterPrimitiveSubregion(lastEffect);
+ lastEffect->determineFilterPrimitiveSubregion(ClipToFilterRegion);
FloatRect subRegion = lastEffect->maxEffectRect();
// At least one FilterEffect has a too big image size,
// recalculate the effect sizes with new scale factors.
if (!fitsInMaximumImageSize(subRegion.size(), scale)) {
filterData->filter->setFilterResolution(scale);
- RenderSVGResourceFilterPrimitive::determineFilterPrimitiveSubregion(lastEffect);
+ lastEffect->determineFilterPrimitiveSubregion(ClipToFilterRegion);
}
// If the drawingRegion is empty, we have something like <g filter=".."/>.
@@ -227,7 +227,7 @@ bool RenderSVGResourceFilter::applyResource(RenderObject* object, RenderStyle*,
if (filterData->drawingRegion.isEmpty()) {
ASSERT(!m_filter.contains(object));
filterData->savedContext = context;
- m_filter.set(object, filterData.leakPtr());
+ m_filter.set(object, filterData.release());
return false;
}
@@ -237,16 +237,16 @@ bool RenderSVGResourceFilter::applyResource(RenderObject* object, RenderStyle*,
effectiveTransform.multiply(filterData->shearFreeAbsoluteTransform);
OwnPtr<ImageBuffer> sourceGraphic;
- RenderingMode renderingMode = object->document().page()->settings().acceleratedFiltersEnabled() ? Accelerated : Unaccelerated;
- if (!createImageBuffer(filterData->drawingRegion, effectiveTransform, sourceGraphic, renderingMode)) {
+ bool isAccelerated = object->document().settings()->acceleratedFiltersEnabled();
+ if (!createImageBuffer(filterData->drawingRegion, effectiveTransform, sourceGraphic, isAccelerated)) {
ASSERT(!m_filter.contains(object));
filterData->savedContext = context;
- m_filter.set(object, filterData.leakPtr());
+ m_filter.set(object, filterData.release());
return false;
}
// Set the rendering mode from the page's settings.
- filterData->filter->setRenderingMode(renderingMode);
+ filterData->filter->setIsAccelerated(isAccelerated);
GraphicsContext* sourceGraphicContext = sourceGraphic->context();
ASSERT(sourceGraphicContext);
@@ -257,7 +257,7 @@ bool RenderSVGResourceFilter::applyResource(RenderObject* object, RenderStyle*,
context = sourceGraphicContext;
ASSERT(!m_filter.contains(object));
- m_filter.set(object, filterData.leakPtr());
+ m_filter.set(object, filterData.release());
return true;
}
@@ -274,7 +274,7 @@ void RenderSVGResourceFilter::postApplyResource(RenderObject* object, GraphicsCo
switch (filterData->state) {
case FilterData::MarkedForRemoval:
- delete m_filter.take(object);
+ m_filter.remove(object);
return;
case FilterData::CycleDetected:
@@ -341,12 +341,12 @@ FloatRect RenderSVGResourceFilter::resourceBoundingBox(RenderObject* object)
void RenderSVGResourceFilter::primitiveAttributeChanged(RenderObject* object, const QualifiedName& attribute)
{
- HashMap<RenderObject*, FilterData*>::iterator it = m_filter.begin();
- HashMap<RenderObject*, FilterData*>::iterator end = m_filter.end();
+ FilterMap::iterator it = m_filter.begin();
+ FilterMap::iterator end = m_filter.end();
SVGFilterPrimitiveStandardAttributes* primitve = static_cast<SVGFilterPrimitiveStandardAttributes*>(object->node());
for (; it != end; ++it) {
- FilterData* filterData = it->value;
+ FilterData* filterData = it->value.get();
if (filterData->state != FilterData::Built)
continue;
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceFilter.h b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceFilter.h
index 25faa03b950..6455b039284 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceFilter.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceFilter.h
@@ -69,7 +69,7 @@ public:
virtual bool applyResource(RenderObject*, RenderStyle*, GraphicsContext*&, unsigned short resourceMode);
virtual void postApplyResource(RenderObject*, GraphicsContext*&, unsigned short resourceMode, const Path*, const RenderSVGShape*);
- virtual FloatRect resourceBoundingBox(RenderObject*);
+ FloatRect resourceBoundingBox(RenderObject*);
PassRefPtr<SVGFilterBuilder> buildPrimitives(SVGFilter*);
@@ -79,26 +79,17 @@ public:
void primitiveAttributeChanged(RenderObject*, const QualifiedName&);
virtual RenderSVGResourceType resourceType() const { return s_resourceType; }
- static RenderSVGResourceType s_resourceType;
+ static const RenderSVGResourceType s_resourceType;
FloatRect drawingRegion(RenderObject*) const;
private:
bool fitsInMaximumImageSize(const FloatSize&, FloatSize&);
- HashMap<RenderObject*, FilterData*> m_filter;
+ typedef HashMap<RenderObject*, OwnPtr<FilterData> > FilterMap;
+ FilterMap m_filter;
};
-inline RenderSVGResourceFilter* toRenderSVGResourceFilter(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isSVGResourceFilter());
- return static_cast<RenderSVGResourceFilter*>(object);
-}
-
-inline RenderSVGResourceFilter* toRenderSVGResourceFilter(RenderSVGResourceContainer* resource)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!resource || resource->resourceType() == FilterResourceType);
- return static_cast<RenderSVGResourceFilter*>(resource);
-}
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderSVGResourceFilter, isSVGResourceFilter());
}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceFilterPrimitive.cpp b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceFilterPrimitive.cpp
index 18cc67a61e7..e34449d35ea 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceFilterPrimitive.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceFilterPrimitive.cpp
@@ -55,47 +55,4 @@ void RenderSVGResourceFilterPrimitive::styleDidChange(StyleDifference diff, cons
}
}
-FloatRect RenderSVGResourceFilterPrimitive::determineFilterPrimitiveSubregion(FilterEffect* effect)
-{
- SVGFilter* filter = static_cast<SVGFilter*>(effect->filter());
- ASSERT(filter);
-
- // FETile, FETurbulence, FEFlood don't have input effects, take the filter region as unite rect.
- FloatRect subregion;
- if (unsigned numberOfInputEffects = effect->inputEffects().size()) {
- subregion = determineFilterPrimitiveSubregion(effect->inputEffect(0));
- for (unsigned i = 1; i < numberOfInputEffects; ++i)
- subregion.unite(determineFilterPrimitiveSubregion(effect->inputEffect(i)));
- } else
- subregion = filter->filterRegion();
-
- // After calling determineFilterPrimitiveSubregion on the target effect, reset the subregion again for <feTile>.
- if (effect->filterEffectType() == FilterEffectTypeTile)
- subregion = filter->filterRegion();
-
- FloatRect effectBoundaries = effect->effectBoundaries();
- if (effect->hasX())
- subregion.setX(effectBoundaries.x());
- if (effect->hasY())
- subregion.setY(effectBoundaries.y());
- if (effect->hasWidth())
- subregion.setWidth(effectBoundaries.width());
- if (effect->hasHeight())
- subregion.setHeight(effectBoundaries.height());
-
- effect->setFilterPrimitiveSubregion(subregion);
-
- FloatRect absoluteSubregion = filter->absoluteTransform().mapRect(subregion);
- FloatSize filterResolution = filter->filterResolution();
- absoluteSubregion.scale(filterResolution.width(), filterResolution.height());
-
- // Clip every filter effect to the filter region.
- FloatRect absoluteScaledFilterRegion = filter->absoluteFilterRegion();
- absoluteScaledFilterRegion.scale(filterResolution.width(), filterResolution.height());
- absoluteSubregion.intersect(absoluteScaledFilterRegion);
-
- effect->setMaxEffectRect(absoluteSubregion);
- return subregion;
-}
-
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceFilterPrimitive.h b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceFilterPrimitive.h
index e2edf3f852d..704df3d4075 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceFilterPrimitive.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceFilterPrimitive.h
@@ -31,8 +31,6 @@
namespace WebCore {
-class FilterEffect;
-
class RenderSVGResourceFilterPrimitive FINAL : public RenderSVGHiddenContainer {
public:
explicit RenderSVGResourceFilterPrimitive(SVGElement* filterPrimitiveElement)
@@ -45,9 +43,6 @@ public:
virtual const char* renderName() const { return "RenderSVGResourceFilterPrimitive"; }
virtual bool isSVGResourceFilterPrimitive() const { return true; }
- // They depend on the RenderObject argument of RenderSVGResourceFilter::applyResource.
- static FloatRect determineFilterPrimitiveSubregion(FilterEffect*);
-
inline void primitiveAttributeChanged(const QualifiedName& attribute)
{
RenderObject* filter = parent();
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceGradient.cpp b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceGradient.cpp
index 7cd75f15017..4e432a56082 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceGradient.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceGradient.cpp
@@ -24,10 +24,9 @@
#include "core/rendering/svg/RenderSVGResourceGradient.h"
-#include "core/platform/graphics/GraphicsContext.h"
#include "core/rendering/svg/RenderSVGShape.h"
#include "core/rendering/svg/SVGRenderSupport.h"
-#include "wtf/UnusedParam.h"
+#include "platform/graphics/GraphicsContext.h"
namespace WebCore {
@@ -58,6 +57,8 @@ bool RenderSVGResourceGradient::applyResource(RenderObject* object, RenderStyle*
ASSERT(context);
ASSERT(resourceMode != ApplyToDefaultMode);
+ clearInvalidationMask();
+
// Be sure to synchronize all SVG properties on the gradientElement _before_ processing any further.
// Otherwhise the call to collectGradientAttributes() in createTileImage(), may cause the SVG DOM property
// synchronization to kick in, which causes removeAllClientsFromCache() to be called, which in turn deletes our
@@ -137,11 +138,10 @@ bool RenderSVGResourceGradient::applyResource(RenderObject* object, RenderStyle*
return true;
}
-void RenderSVGResourceGradient::postApplyResource(RenderObject* object, GraphicsContext*& context, unsigned short resourceMode, const Path* path, const RenderSVGShape* shape)
+void RenderSVGResourceGradient::postApplyResource(RenderObject*, GraphicsContext*& context, unsigned short resourceMode, const Path* path, const RenderSVGShape* shape)
{
ASSERT(context);
ASSERT(resourceMode != ApplyToDefaultMode);
- UNUSED_PARAM(object);
if (resourceMode & ApplyToFillMode) {
if (path)
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceGradient.h b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceGradient.h
index 13c82fbc6ae..0bcfedc1eae 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceGradient.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceGradient.h
@@ -22,13 +22,12 @@
#ifndef RenderSVGResourceGradient_h
#define RenderSVGResourceGradient_h
-#include "core/platform/graphics/FloatRect.h"
-#include "core/platform/graphics/Gradient.h"
-#include "core/platform/graphics/ImageBuffer.h"
-#include "core/platform/graphics/transforms/AffineTransform.h"
#include "core/rendering/svg/RenderSVGResourceContainer.h"
#include "core/svg/SVGGradientElement.h"
-
+#include "platform/geometry/FloatRect.h"
+#include "platform/graphics/Gradient.h"
+#include "platform/graphics/ImageBuffer.h"
+#include "platform/transforms/AffineTransform.h"
#include "wtf/HashMap.h"
namespace WebCore {
@@ -51,7 +50,6 @@ public:
virtual bool applyResource(RenderObject*, RenderStyle*, GraphicsContext*&, unsigned short resourceMode) OVERRIDE FINAL;
virtual void postApplyResource(RenderObject*, GraphicsContext*&, unsigned short resourceMode, const Path*, const RenderSVGShape*) OVERRIDE FINAL;
- virtual FloatRect resourceBoundingBox(RenderObject*) OVERRIDE FINAL { return FloatRect(); }
protected:
void addStops(GradientData*, const Vector<Gradient::ColorStop>&) const;
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceLinearGradient.cpp b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceLinearGradient.cpp
index c8936a61a09..7fb571ef2f9 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceLinearGradient.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceLinearGradient.cpp
@@ -22,12 +22,11 @@
#include "core/rendering/svg/RenderSVGResourceLinearGradient.h"
-#include "core/svg/LinearGradientAttributes.h"
#include "core/svg/SVGLinearGradientElement.h"
namespace WebCore {
-RenderSVGResourceType RenderSVGResourceLinearGradient::s_resourceType = LinearGradientResourceType;
+const RenderSVGResourceType RenderSVGResourceLinearGradient::s_resourceType = LinearGradientResourceType;
RenderSVGResourceLinearGradient::RenderSVGResourceLinearGradient(SVGLinearGradientElement* node)
: RenderSVGResourceGradient(node)
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceLinearGradient.h b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceLinearGradient.h
index 048468c64a3..ba1c3d27884 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceLinearGradient.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceLinearGradient.h
@@ -36,7 +36,7 @@ public:
virtual const char* renderName() const { return "RenderSVGResourceLinearGradient"; }
virtual RenderSVGResourceType resourceType() const { return s_resourceType; }
- static RenderSVGResourceType s_resourceType;
+ static const RenderSVGResourceType s_resourceType;
virtual SVGUnitTypes::SVGUnitType gradientUnits() const { return m_attributes.gradientUnits(); }
virtual void calculateGradientTransform(AffineTransform& transform) { transform = m_attributes.gradientTransform(); }
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceMarker.cpp b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceMarker.cpp
index 5f3108d384c..d3de3b7cc64 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceMarker.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceMarker.cpp
@@ -23,17 +23,16 @@
#include "core/rendering/svg/RenderSVGResourceMarker.h"
-#include "core/platform/graphics/GraphicsContextStateSaver.h"
+#include "core/rendering/LayoutRectRecorder.h"
#include "core/rendering/svg/RenderSVGContainer.h"
#include "core/rendering/svg/SVGRenderSupport.h"
-#include "core/svg/SVGElement.h"
-#include "core/svg/SVGMarkerElement.h"
+#include "platform/graphics/GraphicsContextStateSaver.h"
#include "wtf/TemporaryChange.h"
namespace WebCore {
-RenderSVGResourceType RenderSVGResourceMarker::s_resourceType = MarkerResourceType;
+const RenderSVGResourceType RenderSVGResourceMarker::s_resourceType = MarkerResourceType;
RenderSVGResourceMarker::RenderSVGResourceMarker(SVGMarkerElement* node)
: RenderSVGResourceContainer(node)
@@ -50,6 +49,7 @@ void RenderSVGResourceMarker::layout()
if (m_isInLayout)
return;
+ LayoutRectRecorder recorder(*this);
TemporaryChange<bool> inLayoutChange(m_isInLayout, true);
// Invalidate all resources if our layout changed.
@@ -60,6 +60,8 @@ void RenderSVGResourceMarker::layout()
// layouting of RenderSVGContainer for calculating local
// transformations and repaint.
RenderSVGContainer::layout();
+
+ clearInvalidationMask();
}
void RenderSVGResourceMarker::removeAllClientsFromCache(bool markForInvalidation)
@@ -135,10 +137,12 @@ AffineTransform RenderSVGResourceMarker::markerTransformation(const FloatPoint&
void RenderSVGResourceMarker::draw(PaintInfo& paintInfo, const AffineTransform& transform)
{
+ clearInvalidationMask();
+
// An empty viewBox disables rendering.
SVGMarkerElement* marker = toSVGMarkerElement(element());
ASSERT(marker);
- if (marker->hasAttribute(SVGNames::viewBoxAttr) && marker->viewBoxIsValid() && marker->viewBoxCurrentValue().isEmpty())
+ if (marker->hasAttribute(SVGNames::viewBoxAttr) && marker->viewBoxCurrentValue().isValid() && marker->viewBoxCurrentValue().isEmpty())
return;
PaintInfo info(paintInfo);
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceMarker.h b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceMarker.h
index b88869c3196..625b37a652a 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceMarker.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceMarker.h
@@ -20,11 +20,10 @@
#ifndef RenderSVGResourceMarker_h
#define RenderSVGResourceMarker_h
-#include "core/platform/graphics/FloatRect.h"
#include "core/rendering/svg/RenderSVGResourceContainer.h"
#include "core/svg/SVGElement.h"
#include "core/svg/SVGMarkerElement.h"
-
+#include "platform/geometry/FloatRect.h"
#include "wtf/HashSet.h"
namespace WebCore {
@@ -55,14 +54,13 @@ public:
AffineTransform markerTransformation(const FloatPoint& origin, float angle, float strokeWidth) const;
virtual bool applyResource(RenderObject*, RenderStyle*, GraphicsContext*&, unsigned short) { return false; }
- virtual FloatRect resourceBoundingBox(RenderObject*) { return FloatRect(); }
FloatPoint referencePoint() const;
float angle() const;
SVGMarkerUnitsType markerUnits() const { return toSVGMarkerElement(element())->markerUnitsCurrentValue(); }
virtual RenderSVGResourceType resourceType() const { return s_resourceType; }
- static RenderSVGResourceType s_resourceType;
+ static const RenderSVGResourceType s_resourceType;
private:
// Generates a transformation matrix usable to render marker content. Handles scaling the marker content
@@ -75,11 +73,7 @@ private:
FloatRect m_viewport;
};
-inline RenderSVGResourceMarker* toRenderSVGResourceMarker(RenderSVGResource* resource)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!resource || resource->resourceType() == MarkerResourceType);
- return static_cast<RenderSVGResourceMarker*>(resource);
-}
+DEFINE_RENDER_SVG_RESOURCE_TYPE_CASTS(RenderSVGResourceMarker, MarkerResourceType);
}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceMasker.cpp b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceMasker.cpp
index 0aae3871d25..43c64ca081d 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceMasker.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceMasker.cpp
@@ -21,23 +21,17 @@
#include "core/rendering/svg/RenderSVGResourceMasker.h"
-#include "core/platform/graphics/FloatRect.h"
-#include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/graphics/GraphicsContextStateSaver.h"
-#include "core/platform/graphics/ImageBuffer.h"
-#include "core/platform/graphics/transforms/AffineTransform.h"
#include "core/rendering/svg/RenderSVGResource.h"
#include "core/rendering/svg/SVGRenderingContext.h"
#include "core/svg/SVGElement.h"
-#include "core/svg/SVGMaskElement.h"
-#include "core/svg/SVGUnitTypes.h"
-
-#include "wtf/UnusedParam.h"
+#include "platform/graphics/DisplayList.h"
+#include "platform/graphics/GraphicsContextStateSaver.h"
+#include "platform/transforms/AffineTransform.h"
#include "wtf/Vector.h"
namespace WebCore {
-RenderSVGResourceType RenderSVGResourceMasker::s_resourceType = MaskerResourceType;
+const RenderSVGResourceType RenderSVGResourceMasker::s_resourceType = MaskerResourceType;
RenderSVGResourceMasker::RenderSVGResourceMasker(SVGMaskElement* node)
: RenderSVGResourceContainer(node)
@@ -50,6 +44,7 @@ RenderSVGResourceMasker::~RenderSVGResourceMasker()
void RenderSVGResourceMasker::removeAllClientsFromCache(bool markForInvalidation)
{
+ m_maskContentDisplayList.clear();
m_maskContentBoundaries = FloatRect();
markAllClientsForInvalidation(markForInvalidation ? LayoutAndBoundariesInvalidation : ParentOnlyInvalidation);
}
@@ -69,56 +64,76 @@ bool RenderSVGResourceMasker::applyResource(RenderObject* object, RenderStyle*,
ASSERT_UNUSED(resourceMode, resourceMode == ApplyToDefaultMode);
ASSERT_WITH_SECURITY_IMPLICATION(!needsLayout());
+ clearInvalidationMask();
+
FloatRect repaintRect = object->repaintRectInLocalCoordinates();
if (repaintRect.isEmpty() || !element()->hasChildNodes())
return false;
+ // Content layer start.
+ context->beginTransparencyLayer(1, &repaintRect);
+
+ return true;
+}
+
+void RenderSVGResourceMasker::postApplyResource(RenderObject* object, GraphicsContext*& context,
+ unsigned short resourceMode, const Path*, const RenderSVGShape*)
+{
+ ASSERT(object);
+ ASSERT(context);
+ ASSERT(style());
+ ASSERT_UNUSED(resourceMode, resourceMode == ApplyToDefaultMode);
+ ASSERT_WITH_SECURITY_IMPLICATION(!needsLayout());
+
+ FloatRect repaintRect = object->repaintRectInLocalCoordinates();
+
const SVGRenderStyle* svgStyle = style()->svgStyle();
ASSERT(svgStyle);
- ColorSpace colorSpace = svgStyle->colorInterpolation() == CI_LINEARRGB
- ? ColorSpaceLinearRGB
- : ColorSpaceDeviceRGB;
+ ColorFilter maskLayerFilter = svgStyle->maskType() == MT_LUMINANCE
+ ? ColorFilterLuminanceToAlpha : ColorFilterNone;
+ ColorFilter maskContentFilter = svgStyle->colorInterpolation() == CI_LINEARRGB
+ ? ColorFilterSRGBToLinearRGB : ColorFilterNone;
// Mask layer start.
- context->beginTransparencyLayer(1, &repaintRect);
+ context->beginLayer(1, CompositeDestinationIn, &repaintRect, maskLayerFilter);
{
// Draw the mask with color conversion (when needed).
GraphicsContextStateSaver maskContentSaver(*context);
- context->setColorSpaceConversion(ColorSpaceDeviceRGB, colorSpace);
+ context->setColorFilter(maskContentFilter);
- drawMaskContent(context, object->objectBoundingBox());
+ drawMaskForRenderer(context, object->objectBoundingBox());
}
- // Content layer start.
- MaskType maskType = svgStyle->maskType() == MT_LUMINANCE ? LuminanceMaskType : AlphaMaskType;
- context->beginMaskedLayer(repaintRect, maskType);
-
- return true;
-}
-
-void RenderSVGResourceMasker::postApplyResource(RenderObject*, GraphicsContext*& context,
- unsigned short resourceMode, const Path*, const RenderSVGShape*)
-{
- ASSERT_UNUSED(resourceMode, resourceMode == ApplyToDefaultMode);
-
- // Transfer content layer -> mask layer (SrcIn)
+ // Transfer mask layer -> content layer (DstIn)
context->endLayer();
- // Transfer mask layer -> bg layer (SrcOver)
+ // Transfer content layer -> backdrop (SrcOver)
context->endLayer();
}
-void RenderSVGResourceMasker::drawMaskContent(GraphicsContext* context, const FloatRect& targetBoundingBox)
+void RenderSVGResourceMasker::drawMaskForRenderer(GraphicsContext* context, const FloatRect& targetBoundingBox)
{
ASSERT(context);
- // Adjust the mask image context according to the target objectBoundingBox.
- AffineTransform maskContentTransformation;
- if (toSVGMaskElement(element())->maskContentUnitsCurrentValue() == SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX) {
- maskContentTransformation.translate(targetBoundingBox.x(), targetBoundingBox.y());
- maskContentTransformation.scaleNonUniform(targetBoundingBox.width(), targetBoundingBox.height());
- context->concatCTM(maskContentTransformation);
+ AffineTransform contentTransformation;
+ SVGUnitTypes::SVGUnitType contentUnits = toSVGMaskElement(element())->maskContentUnitsCurrentValue();
+ if (contentUnits == SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX) {
+ contentTransformation.translate(targetBoundingBox.x(), targetBoundingBox.y());
+ contentTransformation.scaleNonUniform(targetBoundingBox.width(), targetBoundingBox.height());
+ context->concatCTM(contentTransformation);
}
+ if (!m_maskContentDisplayList)
+ m_maskContentDisplayList = asDisplayList(context, contentTransformation);
+ ASSERT(m_maskContentDisplayList);
+ context->drawDisplayList(m_maskContentDisplayList.get());
+}
+
+PassRefPtr<DisplayList> RenderSVGResourceMasker::asDisplayList(GraphicsContext* context,
+ const AffineTransform& contentTransform)
+{
+ ASSERT(context);
+
+ context->beginRecording(repaintRectInLocalCoordinates());
for (Node* childNode = element()->firstChild(); childNode; childNode = childNode->nextSibling()) {
RenderObject* renderer = childNode->renderer();
if (!childNode->isSVGElement() || !renderer)
@@ -127,8 +142,10 @@ void RenderSVGResourceMasker::drawMaskContent(GraphicsContext* context, const Fl
if (!style || style->display() == NONE || style->visibility() != VISIBLE)
continue;
- SVGRenderingContext::renderSubtree(context, renderer, maskContentTransformation);
+ SVGRenderingContext::renderSubtree(context, renderer, contentTransform);
}
+
+ return context->endRecording();
}
void RenderSVGResourceMasker::calculateMaskContentRepaintRect()
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceMasker.h b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceMasker.h
index 629950c52f4..2af52752127 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceMasker.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceMasker.h
@@ -20,19 +20,21 @@
#ifndef RenderSVGResourceMasker_h
#define RenderSVGResourceMasker_h
-#include "core/platform/graphics/FloatRect.h"
-#include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/graphics/ImageBuffer.h"
-#include "core/platform/graphics/IntSize.h"
#include "core/rendering/svg/RenderSVGResourceContainer.h"
#include "core/svg/SVGMaskElement.h"
#include "core/svg/SVGUnitTypes.h"
+#include "platform/geometry/FloatRect.h"
+#include "platform/geometry/IntSize.h"
+#include "platform/graphics/GraphicsContext.h"
+#include "platform/graphics/ImageBuffer.h"
#include "wtf/HashMap.h"
#include "wtf/OwnPtr.h"
namespace WebCore {
+class DisplayList;
+
class RenderSVGResourceMasker FINAL : public RenderSVGResourceContainer {
public:
explicit RenderSVGResourceMasker(SVGMaskElement*);
@@ -44,26 +46,24 @@ public:
virtual void removeClientFromCache(RenderObject*, bool markForInvalidation = true);
virtual bool applyResource(RenderObject*, RenderStyle*, GraphicsContext*&, unsigned short resourceMode) OVERRIDE;
virtual void postApplyResource(RenderObject*, GraphicsContext*&, unsigned short, const Path*, const RenderSVGShape*) OVERRIDE;
- virtual FloatRect resourceBoundingBox(RenderObject*);
+ FloatRect resourceBoundingBox(RenderObject*);
SVGUnitTypes::SVGUnitType maskUnits() const { return toSVGMaskElement(element())->maskUnitsCurrentValue(); }
SVGUnitTypes::SVGUnitType maskContentUnits() const { return toSVGMaskElement(element())->maskContentUnitsCurrentValue(); }
virtual RenderSVGResourceType resourceType() const { return s_resourceType; }
- static RenderSVGResourceType s_resourceType;
+ static const RenderSVGResourceType s_resourceType;
private:
void calculateMaskContentRepaintRect();
- void drawMaskContent(GraphicsContext*, const FloatRect& targetBoundingBox);
+ void drawMaskForRenderer(GraphicsContext*, const FloatRect& targetBoundingBox);
+ PassRefPtr<DisplayList> asDisplayList(GraphicsContext*, const AffineTransform&);
+ RefPtr<DisplayList> m_maskContentDisplayList;
FloatRect m_maskContentBoundaries;
};
-inline RenderSVGResourceMasker* toRenderSVGResourceMasker(RenderSVGResource* resource)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!resource || resource->resourceType() == MaskerResourceType);
- return static_cast<RenderSVGResourceMasker*>(resource);
-}
+DEFINE_RENDER_SVG_RESOURCE_TYPE_CASTS(RenderSVGResourceMasker, MaskerResourceType);
}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourcePattern.cpp b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourcePattern.cpp
index 74c11c58466..c107a793f4a 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourcePattern.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourcePattern.cpp
@@ -22,15 +22,14 @@
#include "core/rendering/svg/RenderSVGResourcePattern.h"
-#include "core/platform/graphics/GraphicsContext.h"
#include "core/rendering/svg/SVGRenderSupport.h"
#include "core/rendering/svg/SVGRenderingContext.h"
-#include "core/svg/PatternAttributes.h"
#include "core/svg/SVGFitToViewBox.h"
+#include "platform/graphics/GraphicsContext.h"
namespace WebCore {
-RenderSVGResourceType RenderSVGResourcePattern::s_resourceType = PatternResourceType;
+const RenderSVGResourceType RenderSVGResourcePattern::s_resourceType = PatternResourceType;
RenderSVGResourcePattern::RenderSVGResourcePattern(SVGPatternElement* node)
: RenderSVGResourceContainer(node)
@@ -110,7 +109,7 @@ PatternData* RenderSVGResourcePattern::buildPattern(RenderObject* object, unsign
patternData->pattern = Pattern::create(copiedImage, true, true);
// Compute pattern space transformation.
- const IntSize tileImageSize = tileImage->logicalSize();
+ const IntSize tileImageSize = tileImage->size();
patternData->transform.translate(tileBoundaries.x(), tileBoundaries.y());
patternData->transform.scale(tileBoundaries.width() / tileImageSize.width(), tileBoundaries.height() / tileImageSize.height());
@@ -139,6 +138,8 @@ bool RenderSVGResourcePattern::applyResource(RenderObject* object, RenderStyle*
ASSERT(context);
ASSERT(resourceMode != ApplyToDefaultMode);
+ clearInvalidationMask();
+
// Spec: When the geometry of the applicable element has no width or height and objectBoundingBox is specified,
// then the given effect (e.g. a gradient or a filter) will be ignored.
FloatRect objectBoundingBox = object->objectBoundingBox();
@@ -239,13 +240,17 @@ PassOwnPtr<ImageBuffer> RenderSVGResourcePattern::createTileImage(const PatternA
{
clampedAbsoluteTileBoundaries = SVGRenderingContext::clampedAbsoluteTargetRect(absoluteTileBoundaries);
- OwnPtr<ImageBuffer> tileImage;
-
- if (!SVGRenderingContext::createImageBufferForPattern(absoluteTileBoundaries, clampedAbsoluteTileBoundaries, tileImage, Unaccelerated))
+ IntSize imageSize(roundedIntSize(clampedAbsoluteTileBoundaries.size()));
+ if (imageSize.isEmpty())
+ return nullptr;
+ OwnPtr<ImageBuffer> tileImage = ImageBuffer::create(imageSize);
+ if (!tileImage)
return nullptr;
GraphicsContext* tileImageContext = tileImage->context();
ASSERT(tileImageContext);
+ IntSize unclampedImageSize(roundedIntSize(absoluteTileBoundaries.size()));
+ tileImageContext->scale(FloatSize(unclampedImageSize.width() / absoluteTileBoundaries.width(), unclampedImageSize.height() / absoluteTileBoundaries.height()));
// The image buffer represents the final rendered size, so the content has to be scaled (to avoid pixelation).
tileImageContext->scale(FloatSize(clampedAbsoluteTileBoundaries.width() / tileBoundaries.width(),
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourcePattern.h b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourcePattern.h
index ad473462218..56a8318e06d 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourcePattern.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourcePattern.h
@@ -21,14 +21,14 @@
#ifndef RenderSVGResourcePattern_h
#define RenderSVGResourcePattern_h
-#include "core/platform/graphics/FloatRect.h"
-#include "core/platform/graphics/ImageBuffer.h"
-#include "core/platform/graphics/Pattern.h"
-#include "core/platform/graphics/transforms/AffineTransform.h"
#include "core/rendering/svg/RenderSVGResourceContainer.h"
#include "core/svg/PatternAttributes.h"
#include "core/svg/SVGPatternElement.h"
#include "core/svg/SVGUnitTypes.h"
+#include "platform/geometry/FloatRect.h"
+#include "platform/graphics/ImageBuffer.h"
+#include "platform/graphics/Pattern.h"
+#include "platform/transforms/AffineTransform.h"
#include "wtf/HashMap.h"
#include "wtf/OwnPtr.h"
@@ -53,10 +53,9 @@ public:
virtual bool applyResource(RenderObject*, RenderStyle*, GraphicsContext*&, unsigned short resourceMode);
virtual void postApplyResource(RenderObject*, GraphicsContext*&, unsigned short resourceMode, const Path*, const RenderSVGShape*);
- virtual FloatRect resourceBoundingBox(RenderObject*) { return FloatRect(); }
virtual RenderSVGResourceType resourceType() const { return s_resourceType; }
- static RenderSVGResourceType s_resourceType;
+ static const RenderSVGResourceType s_resourceType;
private:
bool buildTileImageTransform(RenderObject*, const PatternAttributes&, const SVGPatternElement*, FloatRect& patternBoundaries, AffineTransform& tileImageTransform) const;
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceRadialGradient.cpp b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceRadialGradient.cpp
index f9b9359ff31..c8c758b5241 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceRadialGradient.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceRadialGradient.cpp
@@ -23,12 +23,11 @@
#include "core/rendering/svg/RenderSVGResourceRadialGradient.h"
-#include "core/svg/RadialGradientAttributes.h"
#include "core/svg/SVGRadialGradientElement.h"
namespace WebCore {
-RenderSVGResourceType RenderSVGResourceRadialGradient::s_resourceType = RadialGradientResourceType;
+const RenderSVGResourceType RenderSVGResourceRadialGradient::s_resourceType = RadialGradientResourceType;
RenderSVGResourceRadialGradient::RenderSVGResourceRadialGradient(SVGRadialGradientElement* node)
: RenderSVGResourceGradient(node)
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceRadialGradient.h b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceRadialGradient.h
index 739de28c4c9..43ee07601e0 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceRadialGradient.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceRadialGradient.h
@@ -36,7 +36,7 @@ public:
virtual const char* renderName() const { return "RenderSVGResourceRadialGradient"; }
virtual RenderSVGResourceType resourceType() const { return s_resourceType; }
- static RenderSVGResourceType s_resourceType;
+ static const RenderSVGResourceType s_resourceType;
virtual SVGUnitTypes::SVGUnitType gradientUnits() const { return m_attributes.gradientUnits(); }
virtual void calculateGradientTransform(AffineTransform& transform) { transform = m_attributes.gradientTransform(); }
@@ -52,11 +52,7 @@ private:
RadialGradientAttributes m_attributes;
};
-inline RenderSVGResourceRadialGradient* toRenderSVGResourceRadialGradient(RenderSVGResourceContainer* resource)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!resource || resource->resourceType() == RadialGradientResourceType);
- return static_cast<RenderSVGResourceRadialGradient*>(resource);
-}
+DEFINE_RENDER_SVG_RESOURCE_TYPE_CASTS(RenderSVGResourceRadialGradient, RadialGradientResourceType);
}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceSolidColor.cpp b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceSolidColor.cpp
index 5693fb1081f..a79ad3ad916 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceSolidColor.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceSolidColor.cpp
@@ -21,16 +21,16 @@
#include "core/rendering/svg/RenderSVGResourceSolidColor.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameView.h"
-#include "core/platform/graphics/GraphicsContext.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
#include "core/rendering/style/RenderStyle.h"
#include "core/rendering/svg/RenderSVGShape.h"
#include "core/rendering/svg/SVGRenderSupport.h"
+#include "platform/graphics/GraphicsContext.h"
namespace WebCore {
-RenderSVGResourceType RenderSVGResourceSolidColor::s_resourceType = SolidColorResourceType;
+const RenderSVGResourceType RenderSVGResourceSolidColor::s_resourceType = SolidColorResourceType;
RenderSVGResourceSolidColor::RenderSVGResourceSolidColor()
{
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceSolidColor.h b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceSolidColor.h
index c2ca000827f..85937ce9ef1 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceSolidColor.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGResourceSolidColor.h
@@ -20,9 +20,9 @@
#ifndef RenderSVGResourceSolidColor_h
#define RenderSVGResourceSolidColor_h
-#include "core/platform/graphics/Color.h"
-#include "core/platform/graphics/FloatRect.h"
#include "core/rendering/svg/RenderSVGResource.h"
+#include "platform/geometry/FloatRect.h"
+#include "platform/graphics/Color.h"
namespace WebCore {
@@ -36,10 +36,9 @@ public:
virtual bool applyResource(RenderObject*, RenderStyle*, GraphicsContext*&, unsigned short resourceMode);
virtual void postApplyResource(RenderObject*, GraphicsContext*&, unsigned short resourceMode, const Path*, const RenderSVGShape*);
- virtual FloatRect resourceBoundingBox(RenderObject*) { return FloatRect(); }
virtual RenderSVGResourceType resourceType() const { return s_resourceType; }
- static RenderSVGResourceType s_resourceType;
+ static const RenderSVGResourceType s_resourceType;
const Color& color() const { return m_color; }
void setColor(const Color& color) { m_color = color; }
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGRoot.cpp b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGRoot.cpp
index a3ac4b8136c..a4355cd4d9a 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGRoot.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGRoot.cpp
@@ -25,12 +25,9 @@
#include "core/rendering/svg/RenderSVGRoot.h"
-#include "core/page/Chrome.h"
-#include "core/page/ChromeClient.h"
-#include "core/page/Frame.h"
-#include "core/page/Page.h"
-#include "core/platform/graphics/GraphicsContext.h"
+#include "core/frame/Frame.h"
#include "core/rendering/HitTestResult.h"
+#include "core/rendering/LayoutRectRecorder.h"
#include "core/rendering/LayoutRepainter.h"
#include "core/rendering/RenderPart.h"
#include "core/rendering/RenderView.h"
@@ -41,6 +38,7 @@
#include "core/svg/SVGElement.h"
#include "core/svg/SVGSVGElement.h"
#include "core/svg/graphics/SVGImage.h"
+#include "platform/graphics/GraphicsContext.h"
using namespace std;
@@ -81,9 +79,9 @@ void RenderSVGRoot::computeIntrinsicRatioInformation(FloatSize& intrinsicSize, d
// resolving both values to user units.
if (intrinsicWidthAttribute.isFixed() || intrinsicHeightAttribute.isFixed()) {
if (intrinsicWidthAttribute.isFixed())
- intrinsicSize.setWidth(floatValueForLength(intrinsicWidthAttribute, 0));
+ intrinsicSize.setWidth(floatValueForLength(intrinsicWidthAttribute, 0, 0));
if (intrinsicHeightAttribute.isFixed())
- intrinsicSize.setHeight(floatValueForLength(intrinsicHeightAttribute, 0));
+ intrinsicSize.setHeight(floatValueForLength(intrinsicHeightAttribute, 0, 0));
if (!intrinsicSize.isEmpty())
intrinsicRatio = intrinsicSize.width() / static_cast<double>(intrinsicSize.height());
return;
@@ -197,6 +195,8 @@ void RenderSVGRoot::layout()
{
ASSERT(needsLayout());
+ LayoutRectRecorder recorder(*this);
+
// Arbitrary affine transforms are incompatible with LayoutState.
LayoutStateDisabler layoutStateDisabler(view());
@@ -246,23 +246,13 @@ void RenderSVGRoot::paintReplaced(PaintInfo& paintInfo, const LayoutPoint& paint
if (svg->hasEmptyViewBox())
return;
- Page* page = 0;
- if (Frame* frame = this->frame())
- page = frame->page();
-
// Don't paint if we don't have kids, except if we have filters we should paint those.
if (!firstChild()) {
SVGResources* resources = SVGResourcesCache::cachedResourcesForRenderObject(this);
- if (!resources || !resources->filter()) {
- if (page && paintInfo.phase == PaintPhaseForeground)
- page->addRelevantUnpaintedObject(this, visualOverflowRect());
+ if (!resources || !resources->filter())
return;
- }
}
- if (page && paintInfo.phase == PaintPhaseForeground)
- page->addRelevantRepaintedObject(this, visualOverflowRect());
-
// Make a copy of the PaintInfo because applyTransform will modify the damage rect.
PaintInfo childPaintInfo(paintInfo);
childPaintInfo.context->save();
@@ -300,15 +290,11 @@ void RenderSVGRoot::willBeDestroyed()
RenderReplaced::willBeDestroyed();
}
-void RenderSVGRoot::styleWillChange(StyleDifference diff, const RenderStyle* newStyle)
+void RenderSVGRoot::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
{
if (diff == StyleDifferenceLayout)
setNeedsBoundariesUpdate();
- RenderReplaced::styleWillChange(diff, newStyle);
-}
-void RenderSVGRoot::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
-{
RenderReplaced::styleDidChange(diff, oldStyle);
SVGResourcesCache::clientStyleChanged(this, diff, style());
}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGRoot.h b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGRoot.h
index ff7db555d86..f907222eb81 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGRoot.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGRoot.h
@@ -23,9 +23,9 @@
#ifndef RenderSVGRoot_h
#define RenderSVGRoot_h
-#include "core/platform/graphics/FloatRect.h"
#include "core/rendering/RenderReplaced.h"
#include "core/rendering/svg/SVGRenderSupport.h"
+#include "platform/geometry/FloatRect.h"
namespace WebCore {
@@ -76,7 +76,6 @@ private:
virtual void paintReplaced(PaintInfo&, const LayoutPoint&);
virtual void willBeDestroyed();
- virtual void styleWillChange(StyleDifference, const RenderStyle* newStyle);
virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle);
virtual void addChild(RenderObject* child, RenderObject* beforeChild = 0) OVERRIDE;
virtual void removeChild(RenderObject*) OVERRIDE;
@@ -86,9 +85,6 @@ private:
virtual const AffineTransform& localToParentTransform() const;
- bool fillContains(const FloatPoint&) const;
- bool strokeContains(const FloatPoint&) const;
-
virtual FloatRect objectBoundingBox() const { return m_objectBoundingBox; }
virtual FloatRect strokeBoundingBox() const { return m_strokeBoundingBox; }
virtual FloatRect repaintRectInLocalCoordinates() const { return m_repaintBoundingBox; }
@@ -119,20 +115,7 @@ private:
bool m_needsBoundariesOrTransformUpdate : 1;
};
-inline RenderSVGRoot* toRenderSVGRoot(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isSVGRoot());
- return static_cast<RenderSVGRoot*>(object);
-}
-
-inline const RenderSVGRoot* toRenderSVGRoot(const RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isSVGRoot());
- return static_cast<const RenderSVGRoot*>(object);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toRenderSVGRoot(const RenderSVGRoot*);
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderSVGRoot, isSVGRoot());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGShape.cpp b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGShape.cpp
index 12b90a31260..04298f7e49d 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGShape.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGShape.cpp
@@ -29,9 +29,9 @@
#include "core/rendering/svg/RenderSVGShape.h"
-#include "core/platform/graphics/FloatPoint.h"
-#include "core/platform/graphics/GraphicsContextStateSaver.h"
+#include "core/rendering/GraphicsContextAnnotator.h"
#include "core/rendering/HitTestRequest.h"
+#include "core/rendering/LayoutRectRecorder.h"
#include "core/rendering/LayoutRepainter.h"
#include "core/rendering/PointerEventsHitRules.h"
#include "core/rendering/svg/RenderSVGResourceMarker.h"
@@ -41,6 +41,8 @@
#include "core/rendering/svg/SVGResources.h"
#include "core/rendering/svg/SVGResourcesCache.h"
#include "core/svg/SVGGraphicsElement.h"
+#include "platform/geometry/FloatPoint.h"
+#include "platform/graphics/GraphicsContextStateSaver.h"
#include "wtf/MathExtras.h"
namespace WebCore {
@@ -138,6 +140,7 @@ bool RenderSVGShape::strokeContains(const FloatPoint& point, bool requiresStroke
void RenderSVGShape::layout()
{
+ LayoutRectRecorder recorder(*this);
LayoutRepainter repainter(*this, SVGRenderSupport::checkForSVGRepaintDuringLayout(this) && selfNeedsLayout());
bool updateCachedBoundariesInParents = false;
@@ -190,7 +193,7 @@ bool RenderSVGShape::setupNonScalingStrokeContext(AffineTransform& strokeTransfo
AffineTransform RenderSVGShape::nonScalingStrokeTransform() const
{
- return toSVGGraphicsElement(element())->getScreenCTM(SVGLocatable::DisallowStyleUpdate);
+ return toSVGGraphicsElement(element())->getScreenCTM(SVGGraphicsElement::DisallowStyleUpdate);
}
bool RenderSVGShape::shouldGenerateMarkerPositions() const
@@ -309,7 +312,7 @@ void RenderSVGShape::addFocusRingRects(Vector<IntRect>& rects, const LayoutPoint
bool RenderSVGShape::nodeAtFloatPoint(const HitTestRequest& request, HitTestResult& result, const FloatPoint& pointInParent, HitTestAction hitTestAction)
{
- // We only draw in the forground phase, so we only hit-test then.
+ // We only draw in the foreground phase, so we only hit-test then.
if (hitTestAction != HitTestForeground)
return false;
@@ -318,18 +321,27 @@ bool RenderSVGShape::nodeAtFloatPoint(const HitTestRequest& request, HitTestResu
if (!SVGRenderSupport::pointInClippingArea(this, localPoint))
return false;
- PointerEventsHitRules hitRules(PointerEventsHitRules::SVG_PATH_HITTESTING, request, style()->pointerEvents());
+ PointerEventsHitRules hitRules(PointerEventsHitRules::SVG_GEOMETRY_HITTESTING, request, style()->pointerEvents());
+ if (nodeAtFloatPointInternal(request, localPoint, hitRules)) {
+ updateHitTestResult(result, roundedLayoutPoint(localPoint));
+ return true;
+ }
+
+ return false;
+}
+
+bool RenderSVGShape::nodeAtFloatPointInternal(const HitTestRequest& request, const FloatPoint& localPoint, PointerEventsHitRules hitRules)
+{
bool isVisible = (style()->visibility() == VISIBLE);
if (isVisible || !hitRules.requireVisible) {
const SVGRenderStyle* svgStyle = style()->svgStyle();
WindRule fillRule = svgStyle->fillRule();
if (request.svgClipContent())
fillRule = svgStyle->clipRule();
- if ((hitRules.canHitStroke && (svgStyle->hasStroke() || !hitRules.requireStroke) && strokeContains(localPoint, hitRules.requireStroke))
- || (hitRules.canHitFill && (svgStyle->hasFill() || !hitRules.requireFill) && fillContains(localPoint, hitRules.requireFill, fillRule))) {
- updateHitTestResult(result, roundedLayoutPoint(localPoint));
+ if ((hitRules.canHitBoundingBox && objectBoundingBox().contains(localPoint))
+ || (hitRules.canHitStroke && (svgStyle->hasStroke() || !hitRules.requireStroke) && strokeContains(localPoint, hitRules.requireStroke))
+ || (hitRules.canHitFill && (svgStyle->hasFill() || !hitRules.requireFill) && fillContains(localPoint, hitRules.requireFill, fillRule)))
return true;
- }
}
return false;
}
@@ -405,6 +417,8 @@ FloatRect RenderSVGShape::calculateStrokeBoundingBox() const
void RenderSVGShape::updateRepaintBoundingBox()
{
m_repaintBoundingBox = strokeBoundingBox();
+ if (strokeWidth() < 1.0f)
+ m_repaintBoundingBox.inflate(1);
SVGRenderSupport::intersectRepaintRectWithResources(this, m_repaintBoundingBox);
}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGShape.h b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGShape.h
index 49295b483fd..f800b2db555 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGShape.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGShape.h
@@ -26,10 +26,10 @@
#ifndef RenderSVGShape_h
#define RenderSVGShape_h
-#include "core/platform/graphics/FloatRect.h"
-#include "core/platform/graphics/transforms/AffineTransform.h"
#include "core/rendering/svg/RenderSVGModelObject.h"
#include "core/rendering/svg/SVGMarkerData.h"
+#include "platform/geometry/FloatRect.h"
+#include "platform/transforms/AffineTransform.h"
#include "wtf/OwnPtr.h"
#include "wtf/Vector.h"
@@ -37,6 +37,7 @@ namespace WebCore {
class FloatPoint;
class GraphicsContextStateSaver;
+class PointerEventsHitRules;
class RenderSVGContainer;
class RenderSVGPath;
class RenderSVGResource;
@@ -55,6 +56,8 @@ public:
virtual void fillShape(GraphicsContext*) const;
virtual void strokeShape(GraphicsContext*) const;
+ bool nodeAtFloatPointInternal(const HitTestRequest&, const FloatPoint&, PointerEventsHitRules);
+
Path& path() const
{
ASSERT(m_path);
@@ -123,20 +126,7 @@ private:
bool m_needsTransformUpdate : 1;
};
-inline RenderSVGShape* toRenderSVGShape(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isSVGShape());
- return static_cast<RenderSVGShape*>(object);
-}
-
-inline const RenderSVGShape* toRenderSVGShape(const RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isSVGShape());
- return static_cast<const RenderSVGShape*>(object);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toRenderSVGShape(const RenderSVGShape*);
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderSVGShape, isSVGShape());
}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGText.cpp b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGText.cpp
index cc43f258ee8..ba45ce98f18 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGText.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGText.cpp
@@ -28,28 +28,29 @@
#include "core/rendering/svg/RenderSVGText.h"
-#include "core/platform/FloatConversion.h"
-#include "core/platform/graphics/FloatQuad.h"
-#include "core/platform/graphics/FontCache.h"
-#include "core/platform/graphics/GraphicsContextStateSaver.h"
-#include "core/platform/graphics/SimpleFontData.h"
-#include "core/platform/graphics/transforms/TransformState.h"
#include "core/rendering/HitTestRequest.h"
#include "core/rendering/HitTestResult.h"
+#include "core/rendering/LayoutRectRecorder.h"
#include "core/rendering/LayoutRepainter.h"
#include "core/rendering/PointerEventsHitRules.h"
+#include "core/rendering/style/ShadowList.h"
#include "core/rendering/svg/RenderSVGInlineText.h"
#include "core/rendering/svg/RenderSVGResource.h"
#include "core/rendering/svg/RenderSVGRoot.h"
#include "core/rendering/svg/SVGRenderSupport.h"
#include "core/rendering/svg/SVGResourcesCache.h"
#include "core/rendering/svg/SVGRootInlineBox.h"
-#include "core/rendering/svg/SVGTextLayoutAttributesBuilder.h"
#include "core/rendering/svg/SVGTextRunRenderingContext.h"
#include "core/svg/SVGLengthList.h"
#include "core/svg/SVGTextElement.h"
#include "core/svg/SVGTransformList.h"
#include "core/svg/SVGURIReference.h"
+#include "platform/FloatConversion.h"
+#include "platform/fonts/FontCache.h"
+#include "platform/fonts/SimpleFontData.h"
+#include "platform/geometry/FloatQuad.h"
+#include "platform/geometry/TransformState.h"
+#include "platform/graphics/GraphicsContextStateSaver.h"
namespace WebCore {
@@ -230,9 +231,6 @@ static inline void checkLayoutAttributesConsistency(RenderSVGText* text, Vector<
Vector<SVGTextLayoutAttributes*> newLayoutAttributes;
collectLayoutAttributes(text, newLayoutAttributes);
ASSERT(newLayoutAttributes == expectedLayoutAttributes);
-#else
- UNUSED_PARAM(text);
- UNUSED_PARAM(expectedLayoutAttributes);
#endif
}
@@ -346,6 +344,7 @@ static inline void updateFontInAllDescendants(RenderObject* start, SVGTextLayout
void RenderSVGText::layout()
{
ASSERT(needsLayout());
+ LayoutRectRecorder recorder(*this);
LayoutRepainter repainter(*this, SVGRenderSupport::checkForSVGRepaintDuringLayout(this));
bool updateCachedBoundariesInParents = false;
@@ -441,12 +440,15 @@ bool RenderSVGText::nodeAtFloatPoint(const HitTestRequest& request, HitTestResul
PointerEventsHitRules hitRules(PointerEventsHitRules::SVG_TEXT_HITTESTING, request, style()->pointerEvents());
bool isVisible = (style()->visibility() == VISIBLE);
if (isVisible || !hitRules.requireVisible) {
- if ((hitRules.canHitStroke && (style()->svgStyle()->hasStroke() || !hitRules.requireStroke))
+ if ((hitRules.canHitBoundingBox && !objectBoundingBox().isEmpty())
+ || (hitRules.canHitStroke && (style()->svgStyle()->hasStroke() || !hitRules.requireStroke))
|| (hitRules.canHitFill && (style()->svgStyle()->hasFill() || !hitRules.requireFill))) {
FloatPoint localPoint = localToParentTransform().inverse().mapPoint(pointInParent);
if (!SVGRenderSupport::pointInClippingArea(this, localPoint))
return false;
+ if (hitRules.canHitBoundingBox && !objectBoundingBox().contains(localPoint))
+ return false;
HitTestLocation hitTestLocation(LayoutPoint(flooredIntPoint(localPoint)));
return RenderBlock::nodeAtPoint(request, result, hitTestLocation, LayoutPoint(), hitTestAction);
@@ -518,7 +520,7 @@ FloatRect RenderSVGText::repaintRectInLocalCoordinates() const
FloatRect repaintRect = strokeBoundingBox();
SVGRenderSupport::intersectRepaintRectWithResources(this, repaintRect);
- if (const ShadowData* textShadow = style()->textShadow())
+ if (const ShadowList* textShadow = style()->textShadow())
textShadow->adjustRectForShadow(repaintRect);
return repaintRect;
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGText.h b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGText.h
index 5f750c4bc34..56fb0db8e49 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGText.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGText.h
@@ -22,9 +22,9 @@
#ifndef RenderSVGText_h
#define RenderSVGText_h
-#include "core/platform/graphics/transforms/AffineTransform.h"
#include "core/rendering/svg/RenderSVGBlock.h"
#include "core/rendering/svg/SVGTextLayoutAttributesBuilder.h"
+#include "platform/transforms/AffineTransform.h"
namespace WebCore {
@@ -101,20 +101,7 @@ private:
Vector<SVGTextLayoutAttributes*> m_layoutAttributes;
};
-inline RenderSVGText* toRenderSVGText(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isSVGText());
- return static_cast<RenderSVGText*>(object);
-}
-
-inline const RenderSVGText* toRenderSVGText(const RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isSVGText());
- return static_cast<const RenderSVGText*>(object);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toRenderSVGText(const RenderSVGText*);
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderSVGText, isSVGText());
}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGTextPath.cpp b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGTextPath.cpp
index f2068b80ac5..aec2da5ac29 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGTextPath.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGTextPath.cpp
@@ -59,14 +59,4 @@ float RenderSVGTextPath::startOffset() const
return toSVGTextPathElement(node())->startOffsetCurrentValue().valueAsPercentage();
}
-bool RenderSVGTextPath::exactAlignment() const
-{
- return toSVGTextPathElement(node())->spacingCurrentValue() == SVGTextPathSpacingExact;
-}
-
-bool RenderSVGTextPath::stretchMethod() const
-{
- return toSVGTextPathElement(node())->methodCurrentValue() == SVGTextPathMethodStretch;
-}
-
}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGTextPath.h b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGTextPath.h
index 690604c36c2..6e14b5528f6 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGTextPath.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGTextPath.h
@@ -31,8 +31,6 @@ public:
Path layoutPath() const;
float startOffset() const;
- bool exactAlignment() const;
- bool stretchMethod() const;
virtual bool isSVGTextPath() const { return true; }
@@ -42,14 +40,7 @@ private:
Path m_layoutPath;
};
-inline RenderSVGTextPath* toRenderSVGTextPath(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isSVGTextPath());
- return static_cast<RenderSVGTextPath*>(object);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toRenderSVGTextPath(const RenderSVGTextPath*);
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderSVGTextPath, isSVGTextPath());
}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGViewportContainer.cpp b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGViewportContainer.cpp
index 112cb563a3d..05234c18b57 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGViewportContainer.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGViewportContainer.cpp
@@ -25,10 +25,10 @@
#include "core/rendering/svg/RenderSVGViewportContainer.h"
#include "SVGNames.h"
-#include "core/platform/graphics/GraphicsContext.h"
#include "core/svg/SVGElementInstance.h"
#include "core/svg/SVGSVGElement.h"
#include "core/svg/SVGUseElement.h"
+#include "platform/graphics/GraphicsContext.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGViewportContainer.h b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGViewportContainer.h
index c01e7a582d1..b1b79ed5e31 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGViewportContainer.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/RenderSVGViewportContainer.h
@@ -62,20 +62,7 @@ private:
bool m_needsTransformUpdate : 1;
};
-inline RenderSVGViewportContainer* toRenderSVGViewportContainer(RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isSVGViewportContainer());
- return static_cast<RenderSVGViewportContainer*>(object);
-}
-
-inline const RenderSVGViewportContainer* toRenderSVGViewportContainer(const RenderObject* object)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!object || object->isSVGViewportContainer());
- return static_cast<const RenderSVGViewportContainer*>(object);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toRenderSVGViewportContainer(const RenderSVGViewportContainer*);
+DEFINE_RENDER_OBJECT_TYPE_CASTS(RenderSVGViewportContainer, isSVGViewportContainer());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/SVGInlineFlowBox.h b/chromium/third_party/WebKit/Source/core/rendering/svg/SVGInlineFlowBox.h
index 3623a4ace20..e76a9ccdafc 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/SVGInlineFlowBox.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/SVGInlineFlowBox.h
@@ -50,11 +50,7 @@ private:
float m_logicalHeight;
};
-inline SVGInlineFlowBox* toSVGInlineFlowBox(InlineBox* box)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!box || box->isSVGInlineFlowBox());
- return static_cast<SVGInlineFlowBox*>(box);
-}
+DEFINE_INLINE_BOX_TYPE_CASTS(SVGInlineFlowBox);
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/SVGInlineTextBox.cpp b/chromium/third_party/WebKit/Source/core/rendering/svg/SVGInlineTextBox.cpp
index d15a979b6a4..6c593827328 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/SVGInlineTextBox.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/SVGInlineTextBox.cpp
@@ -22,20 +22,21 @@
#include "config.h"
#include "core/rendering/svg/SVGInlineTextBox.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameView.h"
-#include "core/platform/FloatConversion.h"
-#include "core/platform/graphics/DrawLooper.h"
-#include "core/platform/graphics/FontCache.h"
-#include "core/platform/graphics/GraphicsContextStateSaver.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
#include "core/rendering/HitTestResult.h"
#include "core/rendering/InlineFlowBox.h"
#include "core/rendering/PointerEventsHitRules.h"
+#include "core/rendering/style/ShadowList.h"
#include "core/rendering/svg/RenderSVGInlineText.h"
#include "core/rendering/svg/RenderSVGResource.h"
#include "core/rendering/svg/RenderSVGResourceSolidColor.h"
#include "core/rendering/svg/SVGResourcesCache.h"
#include "core/rendering/svg/SVGTextRunRenderingContext.h"
+#include "platform/FloatConversion.h"
+#include "platform/fonts/FontCache.h"
+#include "platform/graphics/DrawLooper.h"
+#include "platform/graphics/GraphicsContextStateSaver.h"
using namespace std;
@@ -320,7 +321,7 @@ void SVGInlineTextBox::paint(PaintInfo& paintInfo, const LayoutPoint&, LayoutUni
paintInfo.context->concatCTM(fragmentTransform);
// Spec: All text decorations except line-through should be drawn before the text is filled and stroked; thus, the text is rendered on top of these decorations.
- int decorations = style->textDecorationsInEffect();
+ unsigned decorations = style->textDecorationsInEffect();
if (decorations & TextDecorationUnderline)
paintDecoration(paintInfo.context, TextDecorationUnderline, fragment);
if (decorations & TextDecorationOverline)
@@ -432,8 +433,6 @@ void SVGInlineTextBox::restoreGraphicsContextAfterTextPainting(GraphicsContext*&
TextRun::RenderingContext* renderingContext = textRun.renderingContext();
if (renderingContext)
static_cast<SVGTextRunRenderingContext*>(renderingContext)->setActivePaintingResource(0);
-#else
- UNUSED_PARAM(textRun);
#endif
}
@@ -622,10 +621,10 @@ void SVGInlineTextBox::paintTextWithShadows(GraphicsContext* context, RenderStyl
ASSERT(scalingFactor);
const Font& scaledFont = textRenderer->scaledFont();
- const ShadowData* shadow = style->textShadow();
+ const ShadowList* shadowList = style->textShadow();
// Text shadows are disabled when printing. http://crbug.com/258321
- bool hasShadow = shadow && !context->printing();
+ bool hasShadow = shadowList && !context->printing();
FloatPoint textOrigin(fragment.x, fragment.y);
FloatSize textSize(fragment.width, fragment.height);
@@ -639,11 +638,12 @@ void SVGInlineTextBox::paintTextWithShadows(GraphicsContext* context, RenderStyl
if (hasShadow) {
DrawLooper drawLooper;
- do {
- FloatSize offset(shadow->x(), shadow->y());
- drawLooper.addShadow(offset, shadow->blur(), shadow->color(),
+ for (size_t i = shadowList->shadows().size(); i--; ) {
+ const ShadowData& shadow = shadowList->shadows()[i];
+ FloatSize offset(shadow.x(), shadow.y());
+ drawLooper.addShadow(offset, shadow.blur(), shadow.color(),
DrawLooper::ShadowRespectsTransforms, DrawLooper::ShadowRespectsAlpha);
- } while ((shadow = shadow->next()));
+ }
drawLooper.addUnmodifiedContent();
context->setDrawLooper(drawLooper);
}
@@ -736,7 +736,8 @@ bool SVGInlineTextBox::nodeAtPoint(const HitTestRequest& request, HitTestResult&
PointerEventsHitRules hitRules(PointerEventsHitRules::SVG_TEXT_HITTESTING, request, renderer()->style()->pointerEvents());
bool isVisible = renderer()->style()->visibility() == VISIBLE;
if (isVisible || !hitRules.requireVisible) {
- if ((hitRules.canHitStroke && (renderer()->style()->svgStyle()->hasStroke() || !hitRules.requireStroke))
+ if (hitRules.canHitBoundingBox
+ || (hitRules.canHitStroke && (renderer()->style()->svgStyle()->hasStroke() || !hitRules.requireStroke))
|| (hitRules.canHitFill && (renderer()->style()->svgStyle()->hasFill() || !hitRules.requireFill))) {
FloatPoint boxOrigin(x(), y());
boxOrigin.moveBy(accumulatedOffset);
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/SVGInlineTextBox.h b/chromium/third_party/WebKit/Source/core/rendering/svg/SVGInlineTextBox.h
index bd85d3f49c5..ccec860b863 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/SVGInlineTextBox.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/SVGInlineTextBox.h
@@ -39,8 +39,6 @@ public:
virtual float virtualLogicalHeight() const { return m_logicalHeight; }
void setLogicalHeight(float height) { m_logicalHeight = height; }
- virtual int selectionTop() { return top(); }
- virtual int selectionHeight() { return static_cast<int>(ceilf(m_logicalHeight)); }
virtual int offsetForPosition(float x, bool includePartialGlyphs = true) const;
virtual float positionForOffset(int offset) const;
@@ -88,11 +86,7 @@ private:
Vector<SVGTextFragment> m_textFragments;
};
-inline SVGInlineTextBox* toSVGInlineTextBox(InlineBox* box)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!box || box->isSVGInlineTextBox());
- return static_cast<SVGInlineTextBox*>(box);
-}
+DEFINE_INLINE_BOX_TYPE_CASTS(SVGInlineTextBox);
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/SVGMarkerData.h b/chromium/third_party/WebKit/Source/core/rendering/svg/SVGMarkerData.h
index 61f90a37fdc..aebd83b3e1a 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/SVGMarkerData.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/SVGMarkerData.h
@@ -20,8 +20,8 @@
#ifndef SVGMarkerData_h
#define SVGMarkerData_h
-#include "core/platform/FloatConversion.h"
-#include "core/platform/graphics/Path.h"
+#include "platform/FloatConversion.h"
+#include "platform/graphics/Path.h"
#include "wtf/MathExtras.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/SVGPathData.cpp b/chromium/third_party/WebKit/Source/core/rendering/svg/SVGPathData.cpp
index d9085d66881..f42f6410e57 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/SVGPathData.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/SVGPathData.cpp
@@ -21,7 +21,6 @@
#include "core/rendering/svg/SVGPathData.h"
#include "SVGNames.h"
-#include "core/platform/graphics/Path.h"
#include "core/svg/SVGCircleElement.h"
#include "core/svg/SVGEllipseElement.h"
#include "core/svg/SVGLineElement.h"
@@ -30,6 +29,7 @@
#include "core/svg/SVGPolygonElement.h"
#include "core/svg/SVGPolylineElement.h"
#include "core/svg/SVGRectElement.h"
+#include "platform/graphics/Path.h"
#include "wtf/HashMap.h"
namespace WebCore {
@@ -74,7 +74,7 @@ static void updatePathFromPathElement(SVGElement* element, Path& path)
static void updatePathFromPolygonElement(SVGElement* element, Path& path)
{
- SVGPointList& points = toSVGPolygonElement(element)->pointList();
+ SVGPointList& points = toSVGPolygonElement(element)->pointsCurrentValue();
if (points.isEmpty())
return;
@@ -89,7 +89,7 @@ static void updatePathFromPolygonElement(SVGElement* element, Path& path)
static void updatePathFromPolylineElement(SVGElement* element, Path& path)
{
- SVGPointList& points = toSVGPolylineElement(element)->pointList();
+ SVGPointList& points = toSVGPolylineElement(element)->pointsCurrentValue();
if (points.isEmpty())
return;
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/SVGRenderSupport.cpp b/chromium/third_party/WebKit/Source/core/rendering/svg/SVGRenderSupport.cpp
index ad9d5ffeb3b..cfc4a641f7f 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/SVGRenderSupport.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/SVGRenderSupport.cpp
@@ -26,7 +26,6 @@
#include "core/rendering/svg/SVGRenderSupport.h"
-#include "core/platform/graphics/transforms/TransformState.h"
#include "core/rendering/RenderGeometryMap.h"
#include "core/rendering/RenderLayer.h"
#include "core/rendering/SubtreeLayoutScope.h"
@@ -40,7 +39,7 @@
#include "core/rendering/svg/SVGResources.h"
#include "core/rendering/svg/SVGResourcesCache.h"
#include "core/svg/SVGElement.h"
-#include "wtf/UnusedParam.h"
+#include "platform/geometry/TransformState.h"
namespace WebCore {
@@ -257,7 +256,7 @@ void SVGRenderSupport::layoutChildren(RenderObject* start, bool selfNeedsLayout)
// for the initial paint to avoid potential double-painting caused by non-sensical "old" bounds.
// We could handle this in the individual objects, but for now it's easier to have
// parent containers call repaint(). (RenderBlock::layout* has similar logic.)
- if (!childEverHadLayout)
+ if (!childEverHadLayout && !RuntimeEnabledFeatures::repaintAfterLayoutEnabled())
child->repaint();
} else if (layoutSizeChanged)
notlayoutedObjects.add(child);
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/SVGRenderTreeAsText.cpp b/chromium/third_party/WebKit/Source/core/rendering/svg/SVGRenderTreeAsText.cpp
index ada7f29ded6..b92e9b99833 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/SVGRenderTreeAsText.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/SVGRenderTreeAsText.cpp
@@ -31,7 +31,6 @@
#include "core/rendering/svg/SVGRenderTreeAsText.h"
#include "SVGNames.h"
-#include "core/platform/graphics/GraphicsTypes.h"
#include "core/rendering/InlineTextBox.h"
#include "core/rendering/RenderTreeAsText.h"
#include "core/rendering/svg/RenderSVGGradientStop.h"
@@ -65,8 +64,10 @@
#include "core/svg/SVGRadialGradientElement.h"
#include "core/svg/SVGRectElement.h"
#include "core/svg/SVGStopElement.h"
+#include "platform/graphics/GraphicsTypes.h"
#include <math.h>
+#include <memory>
namespace WebCore {
@@ -123,15 +124,6 @@ static void writeIfNotDefault(TextStream& ts, const char* name, ValueType value,
writeNameValuePair(ts, name, value);
}
-TextStream& operator<<(TextStream& ts, const FloatRect& r)
-{
- ts << "at (" << TextStream::FormatNumberRespectingIntegers(r.x());
- ts << "," << TextStream::FormatNumberRespectingIntegers(r.y());
- ts << ") size " << TextStream::FormatNumberRespectingIntegers(r.width());
- ts << "x" << TextStream::FormatNumberRespectingIntegers(r.height());
- return ts;
-}
-
TextStream& operator<<(TextStream& ts, const AffineTransform& transform)
{
if (transform.isIdentity())
@@ -274,7 +266,7 @@ static void writeStyle(TextStream& ts, const RenderObject& object)
ts << " [stroke={" << s;
writeSVGPaintingResource(ts, strokePaintingResource);
- SVGLengthContext lengthContext(toSVGElement(shape.element()));
+ SVGLengthContext lengthContext(shape.element());
double dashOffset = svgStyle->strokeDashOffset().value(lengthContext);
double strokeWidth = svgStyle->strokeWidth().value(lengthContext);
const Vector<SVGLength>& dashes = svgStyle->strokeDashArray();
@@ -351,7 +343,7 @@ static TextStream& operator<<(TextStream& ts, const RenderSVGShape& shape)
writeNameValuePair(ts, "cy", element->cyCurrentValue().value(lengthContext));
writeNameValuePair(ts, "r", element->rCurrentValue().value(lengthContext));
} else if (svgElement->hasTagName(SVGNames::polygonTag) || svgElement->hasTagName(SVGNames::polylineTag)) {
- writeNameAndQuotedValue(ts, "points", toSVGPolyElement(svgElement)->pointList().valueAsString());
+ writeNameAndQuotedValue(ts, "points", toSVGPolyElement(svgElement)->pointsCurrentValue().valueAsString());
} else if (svgElement->hasTagName(SVGNames::pathTag)) {
String pathString;
// FIXME: We should switch to UnalteredParsing here - this will affect the path dumping output of dozens of tests.
@@ -483,7 +475,7 @@ void writeSVGResourceContainer(TextStream& ts, const RenderObject& object, int i
const AtomicString& id = element->getIdAttribute();
writeNameAndQuotedValue(ts, "id", id);
- RenderSVGResourceContainer* resource = const_cast<RenderObject&>(object).toRenderSVGResourceContainer();
+ RenderSVGResourceContainer* resource = toRenderSVGResourceContainer(const_cast<RenderObject*>(&object));
ASSERT(resource);
if (resource->resourceType() == MaskerResourceType) {
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/SVGRenderTreeAsText.h b/chromium/third_party/WebKit/Source/core/rendering/svg/SVGRenderTreeAsText.h
index 70b4e17d196..055c587df57 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/SVGRenderTreeAsText.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/SVGRenderTreeAsText.h
@@ -26,7 +26,7 @@
#ifndef SVGRenderTreeAsText_h
#define SVGRenderTreeAsText_h
-#include "core/platform/text/TextStream.h"
+#include "platform/text/TextStream.h"
namespace WebCore {
@@ -59,7 +59,6 @@ void writeResources(TextStream&, const RenderObject&, int indent);
// helper operators defined used in various classes to dump the render tree.
TextStream& operator<<(TextStream&, const AffineTransform&);
TextStream& operator<<(TextStream&, const Color&);
-TextStream& operator<<(TextStream&, const FloatRect&);
// helper operators specific to dumping the render tree. these are used in various classes to dump the render tree
// these could be defined in separate namespace to avoid matching these generic signatures unintentionally.
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/SVGRenderingContext.cpp b/chromium/third_party/WebKit/Source/core/rendering/svg/SVGRenderingContext.cpp
index 359351ecd2c..55545097c0f 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/SVGRenderingContext.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/SVGRenderingContext.cpp
@@ -26,13 +26,12 @@
#include "core/rendering/svg/SVGRenderingContext.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameView.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
#include "core/page/Page.h"
#include "core/rendering/RenderLayer.h"
#include "core/rendering/svg/RenderSVGImage.h"
#include "core/rendering/svg/RenderSVGResource.h"
-#include "core/rendering/svg/RenderSVGResourceClipper.h"
#include "core/rendering/svg/RenderSVGResourceFilter.h"
#include "core/rendering/svg/RenderSVGResourceMasker.h"
#include "core/rendering/svg/SVGResources.h"
@@ -115,13 +114,13 @@ void SVGRenderingContext::prepareToRenderSVGContent(RenderObject* object, PaintI
// Setup transparency layers before setting up SVG resources!
bool isRenderingMask = isRenderingMaskImage(m_object);
float opacity = isRenderingMask ? 1 : style->opacity();
- BlendMode blendMode = isRenderingMask ? BlendModeNormal : style->blendMode();
- if (opacity < 1 || blendMode != BlendModeNormal) {
+ blink::WebBlendMode blendMode = isRenderingMask ? blink::WebBlendModeNormal : style->blendMode();
+ if (opacity < 1 || blendMode != blink::WebBlendModeNormal) {
FloatRect repaintRect = m_object->repaintRectInLocalCoordinates();
- if (opacity < 1 || blendMode != BlendModeNormal) {
+ if (opacity < 1 || blendMode != blink::WebBlendModeNormal) {
m_paintInfo->context->clip(repaintRect);
- if (blendMode != BlendModeNormal) {
+ if (blendMode != blink::WebBlendModeNormal) {
if (!(m_renderingFlags & RestoreGraphicsContext)) {
m_paintInfo->context->save();
m_renderingFlags |= RestoreGraphicsContext;
@@ -134,8 +133,8 @@ void SVGRenderingContext::prepareToRenderSVGContent(RenderObject* object, PaintI
}
ClipPathOperation* clipPathOperation = style->clipPath();
- if (clipPathOperation && clipPathOperation->getOperationType() == ClipPathOperation::SHAPE) {
- ShapeClipPathOperation* clipPath = static_cast<ShapeClipPathOperation*>(clipPathOperation);
+ if (clipPathOperation && clipPathOperation->type() == ClipPathOperation::SHAPE) {
+ ShapeClipPathOperation* clipPath = toShapeClipPathOperation(clipPathOperation);
m_paintInfo->context->clipPath(clipPath->path(object->objectBoundingBox()), clipPath->windRule());
}
@@ -226,7 +225,11 @@ void SVGRenderingContext::calculateTransformationToOutermostCoordinateSystem(con
absoluteTransform = layerTransform->toAffineTransform() * absoluteTransform;
// We can stop at compositing layers, to match the backing resolution.
- if (layer->isComposited())
+ // FIXME: should we be computing the transform to the nearest composited layer,
+ // or the nearest composited layer that does not paint into its ancestor?
+ // I think this is the nearest composited ancestor since we will inherit its
+ // transforms in the composited layer tree.
+ if (layer->hasCompositedLayerMapping())
break;
layer = layer->parent();
@@ -236,29 +239,6 @@ void SVGRenderingContext::calculateTransformationToOutermostCoordinateSystem(con
absoluteTransform.scale(deviceScaleFactor);
}
-bool SVGRenderingContext::createImageBufferForPattern(const FloatRect& absoluteTargetRect, const FloatRect& clampedAbsoluteTargetRect, OwnPtr<ImageBuffer>& imageBuffer, RenderingMode renderingMode)
-{
- IntSize imageSize(roundedIntSize(clampedAbsoluteTargetRect.size()));
- IntSize unclampedImageSize(roundedIntSize(absoluteTargetRect.size()));
-
- // Don't create empty ImageBuffers.
- if (imageSize.isEmpty())
- return false;
-
- OwnPtr<ImageBuffer> image = ImageBuffer::create(imageSize, 1, renderingMode);
- if (!image)
- return false;
-
- GraphicsContext* imageContext = image->context();
- ASSERT(imageContext);
-
- // Compensate rounding effects, as the absolute target rect is using floating-point numbers and the image buffer size is integer.
- imageContext->scale(FloatSize(unclampedImageSize.width() / absoluteTargetRect.width(), unclampedImageSize.height() / absoluteTargetRect.height()));
-
- imageBuffer = image.release();
- return true;
-}
-
void SVGRenderingContext::renderSubtree(GraphicsContext* context, RenderObject* item, const AffineTransform& subtreeContentTransformation)
{
ASSERT(item);
@@ -282,12 +262,6 @@ FloatRect SVGRenderingContext::clampedAbsoluteTargetRect(const FloatRect& absolu
return FloatRect(absoluteTargetRect.location(), absoluteTargetRect.size().shrunkTo(maxImageBufferSize));
}
-IntSize SVGRenderingContext::clampedAbsoluteSize(const IntSize& absoluteSize)
-{
- const IntSize maxImageBufferSize(kMaxImageBufferSize, kMaxImageBufferSize);
- return absoluteSize.shrunkTo(maxImageBufferSize);
-}
-
void SVGRenderingContext::clear2DRotation(AffineTransform& transform)
{
AffineTransform::DecomposedType decomposition;
@@ -307,13 +281,13 @@ bool SVGRenderingContext::bufferForeground(OwnPtr<ImageBuffer>& imageBuffer)
AffineTransform transform = m_paintInfo->context->getCTM(GraphicsContext::DefinitelyIncludeDeviceScale);
IntSize expandedBoundingBox = expandedIntSize(boundingBox.size());
IntSize bufferSize(static_cast<int>(ceil(expandedBoundingBox.width() * transform.xScale())), static_cast<int>(ceil(expandedBoundingBox.height() * transform.yScale())));
- if (bufferSize != imageBuffer->internalSize())
+ if (bufferSize != imageBuffer->size())
imageBuffer.clear();
}
// Create a new buffer and paint the foreground into it.
if (!imageBuffer) {
- if ((imageBuffer = m_paintInfo->context->createCompatibleBuffer(expandedIntSize(boundingBox.size()), true))) {
+ if ((imageBuffer = m_paintInfo->context->createCompatibleBuffer(expandedIntSize(boundingBox.size())))) {
GraphicsContext* bufferedRenderingContext = imageBuffer->context();
bufferedRenderingContext->translate(-boundingBox.x(), -boundingBox.y());
PaintInfo bufferedInfo(*m_paintInfo);
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/SVGRenderingContext.h b/chromium/third_party/WebKit/Source/core/rendering/svg/SVGRenderingContext.h
index 5b679ba17b1..742e0a09997 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/SVGRenderingContext.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/SVGRenderingContext.h
@@ -25,9 +25,9 @@
#ifndef SVGRenderingContext_h
#define SVGRenderingContext_h
-#include "core/platform/graphics/ImageBuffer.h"
#include "core/rendering/PaintInfo.h"
#include "core/rendering/svg/RenderSVGResourceClipper.h"
+#include "platform/graphics/ImageBuffer.h"
namespace WebCore {
@@ -76,14 +76,10 @@ public:
void prepareToRenderSVGContent(RenderObject*, PaintInfo&, NeedsGraphicsContextSave = DontSaveGraphicsContext);
bool isRenderingPrepared() const { return m_renderingFlags & RenderingPrepared; }
- // Patterns need a different float-to-integer coordinate mapping.
- static bool createImageBufferForPattern(const FloatRect& absoluteTargetRect, const FloatRect& clampedAbsoluteTargetRect, OwnPtr<ImageBuffer>&, RenderingMode);
-
static void renderSubtree(GraphicsContext*, RenderObject*, const AffineTransform&);
static float calculateScreenFontSizeScalingFactor(const RenderObject*);
static void calculateTransformationToOutermostCoordinateSystem(const RenderObject*, AffineTransform& absoluteTransform);
- static IntSize clampedAbsoluteSize(const IntSize&);
static FloatRect clampedAbsoluteTargetRect(const FloatRect& absoluteTargetRect);
static void clear2DRotation(AffineTransform&);
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/SVGResources.cpp b/chromium/third_party/WebKit/Source/core/rendering/svg/SVGResources.cpp
index 248d44b67c6..5c42dbcef69 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/SVGResources.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/SVGResources.cpp
@@ -177,7 +177,23 @@ static inline void registerPendingResource(SVGDocumentExtensions* extensions, co
extensions->addPendingResource(id, element);
}
-bool SVGResources::buildResources(const RenderObject* object, const SVGRenderStyle* style)
+bool SVGResources::hasResourceData() const
+{
+ return !m_clipperFilterMaskerData
+ && !m_markerData
+ && !m_fillStrokeData
+ && !m_linkedResource;
+}
+
+static inline SVGResources* ensureResources(OwnPtr<SVGResources>& resources)
+{
+ if (!resources)
+ resources = adoptPtr(new SVGResources);
+
+ return resources.get();
+}
+
+PassOwnPtr<SVGResources> SVGResources::buildResources(const RenderObject* object, const SVGRenderStyle* style)
{
ASSERT(object);
ASSERT(style);
@@ -188,7 +204,7 @@ bool SVGResources::buildResources(const RenderObject* object, const SVGRenderSty
SVGElement* element = toSVGElement(node);
if (!element)
- return false;
+ return nullptr;
Document& document = object->document();
@@ -197,52 +213,40 @@ bool SVGResources::buildResources(const RenderObject* object, const SVGRenderSty
const AtomicString& tagName = element->localName();
if (tagName.isNull())
- return false;
+ return nullptr;
- bool foundResources = false;
+ OwnPtr<SVGResources> resources;
if (clipperFilterMaskerTags().contains(tagName)) {
if (style->hasClipper()) {
AtomicString id(style->clipperResource());
- if (setClipper(getRenderSVGResourceById<RenderSVGResourceClipper>(document, id)))
- foundResources = true;
- else
+ if (!ensureResources(resources)->setClipper(getRenderSVGResourceById<RenderSVGResourceClipper>(document, id)))
registerPendingResource(extensions, id, element);
}
if (style->hasFilter()) {
AtomicString id(style->filterResource());
- if (setFilter(getRenderSVGResourceById<RenderSVGResourceFilter>(document, id)))
- foundResources = true;
- else
+ if (!ensureResources(resources)->setFilter(getRenderSVGResourceById<RenderSVGResourceFilter>(document, id)))
registerPendingResource(extensions, id, element);
}
if (style->hasMasker()) {
AtomicString id(style->maskerResource());
- if (setMasker(getRenderSVGResourceById<RenderSVGResourceMasker>(document, id)))
- foundResources = true;
- else
+ if (!ensureResources(resources)->setMasker(getRenderSVGResourceById<RenderSVGResourceMasker>(document, id)))
registerPendingResource(extensions, id, element);
}
}
if (markerTags().contains(tagName) && style->hasMarkers()) {
AtomicString markerStartId(style->markerStartResource());
- if (setMarkerStart(getRenderSVGResourceById<RenderSVGResourceMarker>(document, markerStartId)))
- foundResources = true;
- else
+ if (!ensureResources(resources)->setMarkerStart(getRenderSVGResourceById<RenderSVGResourceMarker>(document, markerStartId)))
registerPendingResource(extensions, markerStartId, element);
AtomicString markerMidId(style->markerMidResource());
- if (setMarkerMid(getRenderSVGResourceById<RenderSVGResourceMarker>(document, markerMidId)))
- foundResources = true;
- else
+ if (!ensureResources(resources)->setMarkerMid(getRenderSVGResourceById<RenderSVGResourceMarker>(document, markerMidId)))
registerPendingResource(extensions, markerMidId, element);
AtomicString markerEndId(style->markerEndResource());
- if (setMarkerEnd(getRenderSVGResourceById<RenderSVGResourceMarker>(document, markerEndId)))
- foundResources = true;
- else
+ if (!ensureResources(resources)->setMarkerEnd(getRenderSVGResourceById<RenderSVGResourceMarker>(document, markerEndId)))
registerPendingResource(extensions, markerEndId, element);
}
@@ -250,31 +254,29 @@ bool SVGResources::buildResources(const RenderObject* object, const SVGRenderSty
if (style->hasFill()) {
bool hasPendingResource = false;
AtomicString id;
- if (setFill(paintingResourceFromSVGPaint(document, style->fillPaintType(), style->fillPaintUri(), id, hasPendingResource)))
- foundResources = true;
- else if (hasPendingResource)
+ RenderSVGResourceContainer* resource = paintingResourceFromSVGPaint(document, style->fillPaintType(), style->fillPaintUri(), id, hasPendingResource);
+ if (!ensureResources(resources)->setFill(resource) && hasPendingResource) {
registerPendingResource(extensions, id, element);
+ }
}
if (style->hasStroke()) {
bool hasPendingResource = false;
AtomicString id;
- if (setStroke(paintingResourceFromSVGPaint(document, style->strokePaintType(), style->strokePaintUri(), id, hasPendingResource)))
- foundResources = true;
- else if (hasPendingResource)
+ RenderSVGResourceContainer* resource = paintingResourceFromSVGPaint(document, style->strokePaintType(), style->strokePaintUri(), id, hasPendingResource);
+ if (!ensureResources(resources)->setStroke(resource) && hasPendingResource) {
registerPendingResource(extensions, id, element);
+ }
}
}
if (chainableResourceTags().contains(tagName)) {
AtomicString id(targetReferenceFromResource(element));
- if (setLinkedResource(getRenderSVGResourceContainerById(document, id)))
- foundResources = true;
- else
+ if (!ensureResources(resources)->setLinkedResource(getRenderSVGResourceContainerById(document, id)))
registerPendingResource(extensions, id, element);
}
- return foundResources;
+ return (!resources || resources->hasResourceData()) ? nullptr : resources.release();
}
void SVGResources::layoutIfNeeded()
@@ -296,11 +298,21 @@ void SVGResources::layoutIfNeeded()
if (RenderSVGResourceMarker* marker = m_markerData->markerEnd)
marker->layoutIfNeeded();
}
+
+ if (m_fillStrokeData) {
+ if (RenderSVGResourceContainer* fill = m_fillStrokeData->fill)
+ fill->layoutIfNeeded();
+ if (RenderSVGResourceContainer* stroke = m_fillStrokeData->stroke)
+ stroke->layoutIfNeeded();
+ }
+
+ if (m_linkedResource)
+ m_linkedResource->layoutIfNeeded();
}
void SVGResources::removeClientFromCache(RenderObject* object, bool markForInvalidation) const
{
- if (!m_clipperFilterMaskerData && !m_markerData && !m_fillStrokeData && !m_linkedResource)
+ if (hasResourceData())
return;
if (m_linkedResource) {
@@ -340,7 +352,7 @@ void SVGResources::removeClientFromCache(RenderObject* object, bool markForInval
void SVGResources::resourceDestroyed(RenderSVGResourceContainer* resource)
{
ASSERT(resource);
- if (!m_clipperFilterMaskerData && !m_markerData && !m_fillStrokeData && !m_linkedResource)
+ if (hasResourceData())
return;
if (m_linkedResource == resource) {
@@ -414,7 +426,7 @@ void SVGResources::resourceDestroyed(RenderSVGResourceContainer* resource)
void SVGResources::buildSetOfResources(HashSet<RenderSVGResourceContainer*>& set)
{
- if (!m_clipperFilterMaskerData && !m_markerData && !m_fillStrokeData && !m_linkedResource)
+ if (hasResourceData())
return;
if (m_linkedResource) {
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/SVGResources.h b/chromium/third_party/WebKit/Source/core/rendering/svg/SVGResources.h
index 3df2a1f9a11..8eb10adcb4e 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/SVGResources.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/SVGResources.h
@@ -42,7 +42,7 @@ class SVGResources {
public:
SVGResources();
- bool buildResources(const RenderObject*, const SVGRenderStyle*);
+ static PassOwnPtr<SVGResources> buildResources(const RenderObject*, const SVGRenderStyle*);
void layoutIfNeeded();
// Ordinary resources
@@ -79,6 +79,8 @@ public:
private:
friend class SVGResourcesCycleSolver;
+ bool hasResourceData() const;
+
// Only used by SVGResourcesCache cycle detection logic
void resetClipper();
void resetFilter();
@@ -90,7 +92,6 @@ private:
void resetStroke();
void resetLinkedResource();
-private:
bool setClipper(RenderSVGResourceClipper*);
bool setFilter(RenderSVGResourceFilter*);
bool setMarkerStart(RenderSVGResourceMarker*);
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/SVGResourcesCache.cpp b/chromium/third_party/WebKit/Source/core/rendering/svg/SVGResourcesCache.cpp
index 330ee7f7f83..7a8ed18b4d8 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/SVGResourcesCache.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/SVGResourcesCache.cpp
@@ -46,8 +46,8 @@ void SVGResourcesCache::addResourcesFromRenderObject(RenderObject* object, const
ASSERT(svgStyle);
// Build a list of all resources associated with the passed RenderObject
- OwnPtr<SVGResources> newResources = adoptPtr(new SVGResources);
- if (!newResources->buildResources(object, svgStyle))
+ OwnPtr<SVGResources> newResources = SVGResources::buildResources(object, svgStyle);
+ if (!newResources)
return;
// Put object in cache.
@@ -68,10 +68,9 @@ void SVGResourcesCache::addResourcesFromRenderObject(RenderObject* object, const
void SVGResourcesCache::removeResourcesFromRenderObject(RenderObject* object)
{
- if (!m_cache.contains(object))
- return;
-
OwnPtr<SVGResources> resources = m_cache.take(object);
+ if (!resources)
+ return;
// Walk resources and register the render object at each resources.
HashSet<RenderSVGResourceContainer*> resourceSet;
@@ -122,11 +121,14 @@ static inline bool rendererCanHaveResources(RenderObject* renderer)
void SVGResourcesCache::clientStyleChanged(RenderObject* renderer, StyleDifference diff, const RenderStyle* newStyle)
{
ASSERT(renderer);
+ ASSERT(renderer->node());
+ ASSERT(renderer->node()->isSVGElement());
+
if (diff == StyleDifferenceEqual || !renderer->parent())
return;
// In this case the proper SVGFE*Element will decide whether the modified CSS properties require a relayout or repaint.
- if (renderer->isSVGResourceFilterPrimitive() && (diff == StyleDifferenceRepaint || diff == StyleDifferenceRepaintIfText))
+ if (renderer->isSVGResourceFilterPrimitive() && (diff == StyleDifferenceRepaint || diff == StyleDifferenceRepaintIfTextOrColorChange))
return;
// Dynamic changes of CSS properties like 'clip-path' may require us to recompute the associated resources for a renderer.
@@ -139,12 +141,6 @@ void SVGResourcesCache::clientStyleChanged(RenderObject* renderer, StyleDifferen
}
RenderSVGResource::markForLayoutAndParentResourceInvalidation(renderer, false);
-
- // FIXME: This doesn't look right, we often go through here in styleDidChange which means
- // we're changing the needsStyleRecalc bits in the middle of recalcStyle on ourself which
- // makes no sense. It's also not clear why we'd go through here for non-SVG elements.
- if (renderer->node() && !renderer->node()->isSVGElement())
- renderer->node()->setNeedsStyleRecalc(LocalStyleChange, StyleChangeFromRenderer);
}
void SVGResourcesCache::clientWasAddedToTree(RenderObject* renderer, const RenderStyle* newStyle)
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/SVGResourcesCycleSolver.cpp b/chromium/third_party/WebKit/Source/core/rendering/svg/SVGResourcesCycleSolver.cpp
index aad9086875a..efa1b933394 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/SVGResourcesCycleSolver.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/SVGResourcesCycleSolver.cpp
@@ -112,7 +112,7 @@ void SVGResourcesCycleSolver::resolveCycles()
RenderObject* parent = m_renderer->parent();
while (parent) {
if (parent->isSVGResourceContainer())
- parentResources.add(parent->toRenderSVGResourceContainer());
+ parentResources.add(toRenderSVGResourceContainer(parent));
parent = parent->parent();
}
@@ -139,7 +139,7 @@ void SVGResourcesCycleSolver::resolveCycles()
// If we're a resource, add ourselves to the HashSet.
if (m_renderer->isSVGResourceContainer())
- m_allResources.add(m_renderer->toRenderSVGResourceContainer());
+ m_allResources.add(toRenderSVGResourceContainer(m_renderer));
ASSERT(!m_allResources.isEmpty());
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/SVGRootInlineBox.cpp b/chromium/third_party/WebKit/Source/core/rendering/svg/SVGRootInlineBox.cpp
index d9e6ec7c0d3..ec9a953d1b3 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/SVGRootInlineBox.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/SVGRootInlineBox.cpp
@@ -166,7 +166,7 @@ void SVGRootInlineBox::layoutChildBoxes(InlineFlowBox* start, FloatRect* childRe
void SVGRootInlineBox::layoutRootBox(const FloatRect& childRect)
{
- RenderBlock* parentBlock = block();
+ RenderBlockFlow* parentBlock = block();
ASSERT(parentBlock);
// Finally, assign the root block position, now that all content is laid out.
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/SVGRootInlineBox.h b/chromium/third_party/WebKit/Source/core/rendering/svg/SVGRootInlineBox.h
index 41475cd2f3d..efbe2f6b79b 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/SVGRootInlineBox.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/SVGRootInlineBox.h
@@ -33,7 +33,7 @@ class SVGInlineTextBox;
class SVGRootInlineBox FINAL : public RootInlineBox {
public:
- SVGRootInlineBox(RenderBlock* block)
+ SVGRootInlineBox(RenderBlockFlow* block)
: RootInlineBox(block)
, m_logicalHeight(0)
{
@@ -62,11 +62,7 @@ private:
float m_logicalHeight;
};
-inline SVGRootInlineBox* toSVGRootInlineBox(RootInlineBox* box)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!box || box->isSVGRootInlineBox());
- return static_cast<SVGRootInlineBox*>(box);
-}
+DEFINE_INLINE_BOX_TYPE_CASTS(SVGRootInlineBox);
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/SVGSubpathData.h b/chromium/third_party/WebKit/Source/core/rendering/svg/SVGSubpathData.h
index 1ab5294c42e..d2d9e890996 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/SVGSubpathData.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/SVGSubpathData.h
@@ -20,7 +20,7 @@
#ifndef SVGSubpathData_h
#define SVGSubpathData_h
-#include "core/platform/graphics/Path.h"
+#include "platform/graphics/Path.h"
#include "wtf/Vector.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/SVGTextFragment.h b/chromium/third_party/WebKit/Source/core/rendering/svg/SVGTextFragment.h
index 8790482a775..b9132bbc28e 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/SVGTextFragment.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/SVGTextFragment.h
@@ -20,7 +20,7 @@
#ifndef SVGTextFragment_h
#define SVGTextFragment_h
-#include "core/platform/graphics/transforms/AffineTransform.h"
+#include "platform/transforms/AffineTransform.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/SVGTextLayoutEngine.h b/chromium/third_party/WebKit/Source/core/rendering/svg/SVGTextLayoutEngine.h
index 3c6feca885c..3ae5fa09087 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/SVGTextLayoutEngine.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/SVGTextLayoutEngine.h
@@ -20,11 +20,11 @@
#ifndef SVGTextLayoutEngine_h
#define SVGTextLayoutEngine_h
-#include "core/platform/graphics/Path.h"
#include "core/rendering/svg/SVGTextChunkBuilder.h"
#include "core/rendering/svg/SVGTextFragment.h"
#include "core/rendering/svg/SVGTextLayoutAttributes.h"
#include "core/rendering/svg/SVGTextMetrics.h"
+#include "platform/graphics/Path.h"
#include "wtf/Vector.h"
namespace WebCore {
@@ -50,7 +50,6 @@ public:
SVGTextLayoutEngine(Vector<SVGTextLayoutAttributes*>&);
Vector<SVGTextLayoutAttributes*>& layoutAttributes() { return m_layoutAttributes; }
- SVGTextChunkBuilder& chunkLayoutBuilder() { return m_chunkLayoutBuilder; }
void beginTextPathLayout(RenderObject*, SVGTextLayoutEngine& lineLayout);
void endTextPathLayout();
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/SVGTextLayoutEngineBaseline.cpp b/chromium/third_party/WebKit/Source/core/rendering/svg/SVGTextLayoutEngineBaseline.cpp
index 30870edb337..3825b4b1220 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/SVGTextLayoutEngineBaseline.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/SVGTextLayoutEngineBaseline.cpp
@@ -21,12 +21,12 @@
#include "core/rendering/svg/SVGTextLayoutEngineBaseline.h"
-#include "core/platform/graphics/Font.h"
-#include "core/platform/text/UnicodeRange.h"
#include "core/rendering/RenderObject.h"
#include "core/rendering/style/SVGRenderStyle.h"
#include "core/rendering/svg/SVGTextMetrics.h"
#include "core/svg/SVGLengthContext.h"
+#include "platform/fonts/Font.h"
+#include "platform/text/UnicodeRange.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/SVGTextLayoutEngineSpacing.cpp b/chromium/third_party/WebKit/Source/core/rendering/svg/SVGTextLayoutEngineSpacing.cpp
index 5eb553010fc..6f68e475f1e 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/SVGTextLayoutEngineSpacing.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/SVGTextLayoutEngineSpacing.cpp
@@ -21,16 +21,14 @@
#include "core/rendering/svg/SVGTextLayoutEngineSpacing.h"
-#include "core/platform/graphics/Font.h"
#include "core/rendering/style/SVGRenderStyle.h"
#include "core/svg/SVGLengthContext.h"
+#include "platform/fonts/Font.h"
#if ENABLE(SVG_FONTS)
#include "core/svg/SVGFontData.h"
#include "core/svg/SVGFontElement.h"
#include "core/svg/SVGFontFaceElement.h"
-#else
-#include "wtf/UnusedParam.h"
#endif
namespace WebCore {
@@ -53,7 +51,8 @@ float SVGTextLayoutEngineSpacing::calculateSVGKerning(bool isVerticalText, const
ASSERT(fontData->isCustomFont());
ASSERT(fontData->isSVGFont());
- const SVGFontData* svgFontData = static_cast<const SVGFontData*>(fontData->fontData());
+ RefPtr<CustomFontData> customFontData = fontData->customFontData();
+ const SVGFontData* svgFontData = static_cast<const SVGFontData*>(customFontData.get());
SVGFontFaceElement* svgFontFace = svgFontData->svgFontFaceElement();
ASSERT(svgFontFace);
@@ -76,8 +75,6 @@ float SVGTextLayoutEngineSpacing::calculateSVGKerning(bool isVerticalText, const
kerning *= m_font.size() / m_font.fontMetrics().unitsPerEm();
return kerning;
#else
- UNUSED_PARAM(isVerticalText);
- UNUSED_PARAM(currentGlyph);
return false;
#endif
}
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/SVGTextMetrics.h b/chromium/third_party/WebKit/Source/core/rendering/svg/SVGTextMetrics.h
index 3f1ddea3706..362933997ed 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/SVGTextMetrics.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/SVGTextMetrics.h
@@ -55,13 +55,6 @@ public:
{
}
- bool operator==(const Glyph& other)
- {
- return isValid == other.isValid
- && name == other.name
- && unicodeString == other.unicodeString;
- }
-
bool isValid;
String name;
String unicodeString;
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/SVGTextMetricsBuilder.h b/chromium/third_party/WebKit/Source/core/rendering/svg/SVGTextMetricsBuilder.h
index 6c3148a0a21..076b052283a 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/SVGTextMetricsBuilder.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/SVGTextMetricsBuilder.h
@@ -20,10 +20,10 @@
#ifndef SVGTextMetricsBuilder_h
#define SVGTextMetricsBuilder_h
-#include "core/platform/graphics/TextRun.h"
-#include "core/platform/graphics/WidthIterator.h"
#include "core/rendering/svg/SVGTextLayoutAttributes.h"
#include "core/rendering/svg/SVGTextMetrics.h"
+#include "platform/fonts/WidthIterator.h"
+#include "platform/text/TextRun.h"
#include "wtf/Vector.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/SVGTextQuery.cpp b/chromium/third_party/WebKit/Source/core/rendering/svg/SVGTextQuery.cpp
index 32674aba78f..4bf2a3c3da7 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/SVGTextQuery.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/SVGTextQuery.cpp
@@ -20,14 +20,13 @@
#include "config.h"
#include "core/rendering/svg/SVGTextQuery.h"
-#include "core/platform/FloatConversion.h"
#include "core/rendering/InlineFlowBox.h"
#include "core/rendering/RenderBlock.h"
#include "core/rendering/RenderInline.h"
#include "core/rendering/svg/RenderSVGInlineText.h"
#include "core/rendering/svg/SVGInlineTextBox.h"
#include "core/rendering/svg/SVGTextMetrics.h"
-
+#include "platform/FloatConversion.h"
#include "wtf/MathExtras.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/SVGTextRunRenderingContext.cpp b/chromium/third_party/WebKit/Source/core/rendering/svg/SVGTextRunRenderingContext.cpp
index eaf01967a60..c48c91e2486 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/SVGTextRunRenderingContext.cpp
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/SVGTextRunRenderingContext.cpp
@@ -24,10 +24,6 @@
#include "core/rendering/svg/SVGTextRunRenderingContext.h"
#include "SVGNames.h"
-#include "core/platform/graphics/Font.h"
-#include "core/platform/graphics/GlyphBuffer.h"
-#include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/graphics/WidthIterator.h"
#include "core/rendering/RenderObject.h"
#include "core/rendering/svg/RenderSVGInlineText.h"
#include "core/rendering/svg/RenderSVGResourceSolidColor.h"
@@ -35,6 +31,9 @@
#include "core/svg/SVGFontElement.h"
#include "core/svg/SVGFontFaceElement.h"
#include "core/svg/SVGGlyphElement.h"
+#include "platform/fonts/GlyphBuffer.h"
+#include "platform/fonts/WidthIterator.h"
+#include "platform/graphics/GraphicsContext.h"
namespace WebCore {
@@ -44,7 +43,8 @@ static inline const SVGFontData* svgFontAndFontFaceElementForFontData(const Simp
ASSERT(fontData->isCustomFont());
ASSERT(fontData->isSVGFont());
- const SVGFontData* svgFontData = static_cast<const SVGFontData*>(fontData->fontData());
+ RefPtr<CustomFontData> customFontData = fontData->customFontData();
+ const SVGFontData* svgFontData = static_cast<const SVGFontData*>(customFontData.get());
fontFace = svgFontData->svgFontFaceElement();
ASSERT(fontFace);
@@ -192,7 +192,7 @@ GlyphData SVGTextRunRenderingContext::glyphDataForCharacter(const Font& font, co
// Characters enclosed by an <altGlyph> element, may not be registered in the GlyphPage.
const SimpleFontData* originalFontData = glyphData.fontData;
- if (glyphData.fontData && !glyphData.fontData->isSVGFont()) {
+ if (originalFontData && !originalFontData->isSVGFont()) {
if (TextRun::RenderingContext* renderingContext = run.renderingContext()) {
RenderObject* renderObject = static_cast<SVGTextRunRenderingContext*>(renderingContext)->renderer();
RenderObject* parentRenderObject = renderObject->isText() ? renderObject->parent() : renderObject;
diff --git a/chromium/third_party/WebKit/Source/core/rendering/svg/SVGTextRunRenderingContext.h b/chromium/third_party/WebKit/Source/core/rendering/svg/SVGTextRunRenderingContext.h
index 6b4793ca695..e71eca2ca29 100644
--- a/chromium/third_party/WebKit/Source/core/rendering/svg/SVGTextRunRenderingContext.h
+++ b/chromium/third_party/WebKit/Source/core/rendering/svg/SVGTextRunRenderingContext.h
@@ -21,8 +21,8 @@
#ifndef SVGTextRunRenderingContext_h
#define SVGTextRunRenderingContext_h
-#include "core/platform/graphics/Font.h"
-#include "core/platform/graphics/TextRun.h"
+#include "platform/fonts/Font.h"
+#include "platform/text/TextRun.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/scripts/Hasher.pm b/chromium/third_party/WebKit/Source/core/scripts/Hasher.pm
deleted file mode 100644
index 05a43f54517..00000000000
--- a/chromium/third_party/WebKit/Source/core/scripts/Hasher.pm
+++ /dev/null
@@ -1,93 +0,0 @@
-# Copyright (C) 2005, 2006, 2007, 2008 Nikolas Zimmermann <zimmermann@kde.org>
-# Copyright (C) 2006 Anders Carlsson <andersca@mac.com>
-# Copyright (C) 2006, 2007 Samuel Weinig <sam@webkit.org>
-# Copyright (C) 2006 Alexey Proskuryakov <ap@webkit.org>
-# Copyright (C) 2006, 2007, 2008, 2009, 2010 Apple Inc. All rights reserved.
-# Copyright (C) 2009 Cameron McCormack <cam@mcc.id.au>
-# Copyright (C) Research In Motion Limited 2010. All rights reserved.
-# Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
-# Copyright (C) 2011 Patrick Gansterer <paroga@webkit.org>
-# Copyright (C) 2012 Ericsson AB. All rights reserved.
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Library General Public
-# License as published by the Free Software Foundation; either
-# version 2 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Library General Public License for more details.
-#
-# You should have received a copy of the GNU Library General Public License
-# along with this library; see the file COPYING.LIB. If not, write to
-# the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
-# Boston, MA 02110-1301, USA.
-
-package Hasher;
-
-use strict;
-
-sub leftShift($$) {
- my ($value, $distance) = @_;
- return (($value << $distance) & 0xFFFFFFFF);
-}
-
-# Paul Hsieh's SuperFastHash
-# http://www.azillionmonkeys.com/qed/hash.html
-sub GenerateHashValue
-{
- my @chars = split(/ */, $_[0]);
-
- # This hash is designed to work on 16-bit chunks at a time. But since the normal case
- # (above) is to hash UTF-16 characters, we just treat the 8-bit chars as if they
- # were 16-bit chunks, which should give matching results
-
- my $EXP2_32 = 4294967296;
-
- my $hash = 0x9e3779b9;
- my $l = scalar @chars; #I wish this was in Ruby --- Maks
- my $rem = $l & 1;
- $l = $l >> 1;
-
- my $s = 0;
-
- # Main loop
- for (; $l > 0; $l--) {
- $hash += ord($chars[$s]);
- my $tmp = leftShift(ord($chars[$s+1]), 11) ^ $hash;
- $hash = (leftShift($hash, 16)% $EXP2_32) ^ $tmp;
- $s += 2;
- $hash += $hash >> 11;
- $hash %= $EXP2_32;
- }
-
- # Handle end case
- if ($rem != 0) {
- $hash += ord($chars[$s]);
- $hash ^= (leftShift($hash, 11)% $EXP2_32);
- $hash += $hash >> 17;
- }
-
- # Force "avalanching" of final 127 bits
- $hash ^= leftShift($hash, 3);
- $hash += ($hash >> 5);
- $hash = ($hash% $EXP2_32);
- $hash ^= (leftShift($hash, 2)% $EXP2_32);
- $hash += ($hash >> 15);
- $hash = $hash% $EXP2_32;
- $hash ^= (leftShift($hash, 10)% $EXP2_32);
-
- # Save 8 bits for StringImpl to use as flags.
- $hash &= 0xffffff;
-
- # This avoids ever returning a hash code of 0, since that is used to
- # signal "hash not computed yet". Setting the high bit maintains
- # reasonable fidelity to a hash code of 0 because it is likely to yield
- # exactly 0 when hash lookup masks out the high bits.
- $hash = (0x80000000 >> 8) if ($hash == 0);
-
- return $hash;
-}
-
-1;
diff --git a/chromium/third_party/WebKit/Source/core/scripts/InFilesCompiler.pm b/chromium/third_party/WebKit/Source/core/scripts/InFilesCompiler.pm
deleted file mode 100644
index 40cff493bb9..00000000000
--- a/chromium/third_party/WebKit/Source/core/scripts/InFilesCompiler.pm
+++ /dev/null
@@ -1,182 +0,0 @@
-#!/usr/bin/perl -w
-
-# Copyright (C) 2011 Adam Barth <abarth@webkit.org>
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions
-# are met:
-# 1. Redistributions of source code must retain the above copyright
-# notice, this list of conditions and the following disclaimer.
-# 2. Redistributions in binary form must reproduce the above copyright
-# notice, this list of conditions and the following disclaimer in the
-# documentation and/or other materials provided with the distribution.
-#
-# THIS SOFTWARE IS PROVIDED BY GOOGLE, INC. ``AS IS'' AND ANY
-# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
-# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
-# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
-# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
-# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
-# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
-# OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-#
-
-use strict;
-
-use Config;
-use Getopt::Long;
-use File::Path;
-use File::Spec;
-use IO::File;
-use InFilesParser;
-
-require Config;
-
-package InFilesCompiler;
-
-my $inputFile = "";
-my $outputDir = ".";
-my $defaultItemFactory;
-
-my %parsedItems;
-my %parsedItemPaths;
-my %parsedParameters;
-
-sub itemHandler($$$)
-{
- my ($itemName, $property, $value) = @_;
-
- if ($itemName =~ /\//) {
- my ($dirname, $basename) = $itemName =~ /^(.*)\/(.*)/;
- $itemName = $basename;
- $parsedItemPaths{$itemName} = $dirname;
- }
-
- $parsedItems{$itemName} = { &$defaultItemFactory($itemName) } if !defined($parsedItems{$itemName});
-
- return unless $property;
-
- die "Unknown property $property for $itemName\n" if !defined($parsedItems{$itemName}{$property});
- $parsedItems{$itemName}{$property} = $value;
-}
-
-sub parameterHandler($$)
-{
- my ($parameter, $value) = @_;
-
- die "Unknown parameter $parameter\n" if !defined($parsedParameters{$parameter});
- $parsedParameters{$parameter} = $value;
-}
-
-sub new()
-{
- my $object = shift;
- my $reference = { };
-
- my $defaultParametersRef = shift;
- %parsedParameters = %{ $defaultParametersRef };
- $defaultItemFactory = shift;
-
- %parsedItems = ();
-
- bless($reference, $object);
- return $reference;
-}
-
-sub initializeFromCommandLine()
-{
- ::GetOptions(
- 'input=s' => \$inputFile,
- 'outputDir=s' => \$outputDir,
- );
-
- die "You must specify --input <file>" unless length($inputFile);
-
- ::mkpath($outputDir);
-
- # FIXME: Should we provide outputDir via an accessor?
- return $outputDir;
-}
-
-sub compile()
-{
- my $object = shift;
- my $generateCode = shift;
-
- my $file = new IO::File;
- open($file, $inputFile) or die "Failed to open file: $!";
-
- my $InParser = InFilesParser->new();
- $InParser->parse($file, \&parameterHandler, \&itemHandler);
-
- close($file);
- die "Failed to read from file: $inputFile" if (keys %parsedItems == 0);
-
- &$generateCode(\%parsedParameters, \%parsedItems, \%parsedItemPaths);
-}
-
-sub license()
-{
- return "/*
- * THIS FILE WAS AUTOMATICALLY GENERATED, DO NOT EDIT.
- *
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY GOOGLE, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-";
-}
-
-sub interfaceForItem($)
-{
- my $object = shift;
- my $itemName = shift;
-
- my $interfaceName = $parsedItems{$itemName}{"interfaceName"};
- $interfaceName = $itemName unless $interfaceName;
-
- return $interfaceName;
-}
-
-
-sub preferredConditional()
-{
- my $object = shift;
- my $conditional = shift;
-
- my @conditionals = split('\\|', $conditional);
- return $conditionals[0];
-}
-
-sub conditionalStringFromAttributeValue()
-{
- my $object = shift;
- my $conditional = shift;
-
- return "ENABLE(" . join(') || ENABLE(', split('\\|', $conditional)) . ")";
-}
-
-1;
diff --git a/chromium/third_party/WebKit/Source/core/scripts/InFilesParser.pm b/chromium/third_party/WebKit/Source/core/scripts/InFilesParser.pm
deleted file mode 100644
index eaaaa81c141..00000000000
--- a/chromium/third_party/WebKit/Source/core/scripts/InFilesParser.pm
+++ /dev/null
@@ -1,154 +0,0 @@
-#!/usr/bin/perl -w
-
-# Copyright (C) 2008 Julien Chaffraix <jchaffraix@webkit.org>
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions
-# are met:
-# 1. Redistributions of source code must retain the above copyright
-# notice, this list of conditions and the following disclaimer.
-# 2. Redistributions in binary form must reproduce the above copyright
-# notice, this list of conditions and the following disclaimer in the
-# documentation and/or other materials provided with the distribution.
-#
-# THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
-# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
-# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
-# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
-# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
-# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
-# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
-# OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-#
-
-use strict;
-
-package InFilesParser;
-
-my $isParsingCommonParameters;
-my $hasStartedParsing;
-
-# Helper functions
-
-sub trimComment
-{
- my $string = shift;
- $string =~ s/#.+$//;
- chomp($string);
- return $string;
-}
-
-sub trimWS
-{
- my $string = shift;
- $string =~ s/^\s+//;
- $string =~ s/\s+$//;
- chomp($string);
- return $string;
-}
-
-sub trimQuoteAndWS
-{
- my $string = shift;
- $string =~ s/\"([^\"]+)\"/$1/;
- return trimWS($string);
-}
-
-# Default constructor
-
-sub new
-{
- my $object = shift;
- my $reference = { };
-
- # Initialize the parser.
- $isParsingCommonParameters = 1;
- $hasStartedParsing = 0;
-
- bless($reference, $object);
- return $reference;
-}
-
-# parse take 3 attributes:
-# - the filestream to read from (the caller has to open / close it).
-# - the commonParameterHandler called when parsing the first part of the file with the parameter and the value.
-# - the perTagHandler called for each optional parameter with the element name, the parameter and its value.
-# If no parameter were provided, it is called once with an empty parameter and value.
-sub parse($)
-{
- my $object = shift;
- my $fileStream = shift; # IO::File only
- my $commonParameterHandler = shift;
- my $perTagHandler = shift;
-
- foreach (<$fileStream>) {
- # Ignore whitespace, in case the .in files have the wrong EOL
- # markers and those are getting treated as whitespace.
- $_ = trimWS($_);
-
- # Empty line, change from common parameter part
- # to per tag part if we have started parsing.
- if (/^$/) {
- if ($hasStartedParsing) {
- $isParsingCommonParameters = 0;
- }
- next;
- }
-
- # There may be a few empty lines at the beginning of the file
- # so detect the first non empty line which starts the common
- # parameters part.
- $hasStartedParsing = 1;
-
- if (/^#/) {
- next;
- }
-
- $_ = trimComment($_);
-
- if ($isParsingCommonParameters) {
- my ($name, $value) = split '=', $_;
-
- $name = trimWS($name);
- if (defined($value)) {
- $value = trimQuoteAndWS($value);
- } else {
- # We default to 1 as it eases the syntax.
- $value = "1";
- }
-
- &$commonParameterHandler($name, $value);
- } else {
- # Parsing per-tag parameters.
-
- # Split the tag name ($1) from the optionnal parameter(s) ($2)
- /^(\S+)\s*(.*)$/;
- my $elementName = $1;
-
- if ($2) {
- my @options = split "," , $2;
- my ($option, $value);
- for (my $i = 0; $i < @options; ++$i) {
- ($option, $value) = split "=", $options[$i];
- $option = trimWS($option);
- if (defined($value)) {
- $value = trimQuoteAndWS($value);
- } else {
- # We default to 1 as it eases the syntax.
- $value = "1";
- }
-
- &$perTagHandler($elementName, $option, $value);
- }
- } else {
- # No parameter was given so call it with empty strings.
- &$perTagHandler($elementName, "", "");
- }
- }
- }
-}
-
-1;
diff --git a/chromium/third_party/WebKit/Source/core/scripts/StaticString.pm b/chromium/third_party/WebKit/Source/core/scripts/StaticString.pm
deleted file mode 100644
index a404d70be92..00000000000
--- a/chromium/third_party/WebKit/Source/core/scripts/StaticString.pm
+++ /dev/null
@@ -1,49 +0,0 @@
-# Copyright (C) 2013 Google, Inc. All Rights Reserved.
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions
-# are met:
-# 1. Redistributions of source code must retain the above copyright
-# notice, this list of conditions and the following disclaimer.
-# 2. Redistributions in binary form must reproduce the above copyright
-# notice, this list of conditions and the following disclaimer in the
-# documentation and/or other materials provided with the distribution.
-#
-# THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
-# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
-# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
-# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
-# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
-# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
-# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
-# OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-package StaticString;
-
-use strict;
-use Hasher;
-
-sub GenerateStringImpls($)
-{
- my $stringsRef = shift;
- my %strings = %$stringsRef;
-
- my @result = ();
-
- push(@result, "\n");
-
- while ( my ($name, $value) = each %strings ) {
- my $length = length($value);
- my $hash = Hasher::GenerateHashValue($value);
- push(@result, " StringImpl* ${name}Impl = StringImpl::createStatic(\"$value\", $length, $hash);\n");
- }
-
- push(@result, "\n");
-
- return join "", @result;
-}
-
-1;
diff --git a/chromium/third_party/WebKit/Source/core/scripts/action_derivedsourcesallinone.py b/chromium/third_party/WebKit/Source/core/scripts/action_derivedsourcesallinone.py
deleted file mode 100644
index fec5088917a..00000000000
--- a/chromium/third_party/WebKit/Source/core/scripts/action_derivedsourcesallinone.py
+++ /dev/null
@@ -1,225 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright (C) 2009 Google Inc. All rights reserved.
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions are
-# met:
-#
-# * Redistributions of source code must retain the above copyright
-# notice, this list of conditions and the following disclaimer.
-# * Redistributions in binary form must reproduce the above
-# copyright notice, this list of conditions and the following disclaimer
-# in the documentation and/or other materials provided with the
-# distribution.
-# * Neither the name of Google Inc. nor the names of its
-# contributors may be used to endorse or promote products derived from
-# this software without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-#
-# Copyright (c) 2009 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-# action_derivedsourcesallinone.py generates a single cpp file that includes
-# all v8 bindings cpp files generated from idls. Files can be assigned into
-# multiple output files, to reduce maximum compilation unit size and allow
-# parallel compilation.
-#
-# usage: action_derivedsourcesallinone.py IDL_FILES_LIST -- OUTPUT_FILE1 OUTPUT_FILE2 ...
-#
-# Note that IDL_FILES_LIST is a text file containing the IDL file paths.
-
-import errno
-import os
-import os.path
-import re
-import subprocess
-import sys
-
-# A regexp for finding Conditional attributes in interface definitions.
-conditionalPattern = re.compile('interface[\s]*\[[^\]]*Conditional=([\_0-9a-zA-Z&|]*)')
-
-copyrightTemplate = """/*
- * THIS FILE WAS AUTOMATICALLY GENERATED, DO NOT EDIT.
- *
- * This file was generated by the action_derivedsourcesallinone.py script.
- *
- * Copyright (C) 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-"""
-
-
-# Wraps conditional with ENABLE() and replace '&','|' with '&&','||' if more than one conditional is specified.
-def formatConditional(conditional):
- def wrapWithEnable(s):
- if re.match('[|&]$', s):
- return s * 2
- return 'ENABLE(' + s + ')'
- return ' '.join(map(wrapWithEnable, conditional))
-
-
-# Find the conditional interface attribute.
-def extractConditional(idlFilePath):
- conditional = None
-
- # Read file and look for "interface [ Conditional=XXX ]".
- idlFile = open(idlFilePath)
- idlContents = idlFile.read().replace('\n', '')
- idlFile.close()
-
- match = conditionalPattern.search(idlContents)
- if match:
- conditional = match.group(1)
- conditional = re.split('([|&])', conditional)
-
- return conditional
-
-# Extracts conditional and interface name from each IDL file.
-def extractMetaData(filePaths):
- metaDataList = []
-
- for f in filePaths:
- metaData = {}
- if len(f) == 0:
- continue
- if not os.path.exists(f):
- print 'WARNING: file not found: "%s"' % f
- continue
-
- # Extract type name from file name
- (parentPath, fileName) = os.path.split(f)
- (interfaceName, ext) = os.path.splitext(fileName)
-
- if not ext == '.idl':
- continue
-
- metaData = {
- 'conditional': extractConditional(f),
- 'name': interfaceName,
- }
-
- metaDataList.append(metaData)
-
- return metaDataList
-
-
-def generateContent(filesMetaData, partition, totalPartitions):
- # Sort files by conditionals.
- filesMetaData.sort()
-
- output = []
-
- # Add fixed content.
- output.append(copyrightTemplate)
- output.append('#define NO_IMPLICIT_ATOMICSTRING\n\n')
-
- # List all includes segmented by if and endif.
- prevConditional = None
- for metaData in filesMetaData:
- name = metaData['name']
- if (hash(name) % totalPartitions) != partition:
- continue
- conditional = metaData['conditional']
-
- if prevConditional and prevConditional != conditional:
- output.append('#endif\n')
- if conditional and prevConditional != conditional:
- output.append('\n#if %s\n' % formatConditional(conditional))
-
- output.append('#include "bindings/V8%s.cpp"\n' % name)
-
- prevConditional = conditional
-
- if prevConditional:
- output.append('#endif\n')
-
- return ''.join(output)
-
-
-def writeContent(content, outputFileName):
- (parentPath, fileName) = os.path.split(outputFileName)
- if not os.path.exists(parentPath):
- print parentPath
- os.mkdir(parentPath)
- f = open(outputFileName, 'w')
- f.write(content)
- f.close()
-
-
-def resolveCygpath(cygdriveNames):
- cmd = ['cygpath', '-f', '-', '-wa']
- process = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
- idlFileNames = []
- for fileName in cygdriveNames:
- process.stdin.write("%s\n" % fileName)
- process.stdin.flush()
- idlFileNames.append(process.stdout.readline().rstrip())
- process.stdin.close()
- process.wait()
- return idlFileNames
-
-
-def main(args):
- assert(len(args) > 3)
- inOutBreakIndex = args.index('--')
- inputFileName = args[1]
- outputFileNames = args[inOutBreakIndex+1:]
-
- inputFile = open(inputFileName, 'r')
- idlFileNames = []
- cygdriveNames = []
- for line in inputFile:
- idlFileName = line.rstrip().split(' ')[0]
- if idlFileName.startswith("/cygdrive"):
- cygdriveNames.append(idlFileName)
- else:
- idlFileNames.append(idlFileName)
-
- if cygdriveNames:
- idlFileNames.extend(resolveCygpath(cygdriveNames))
- inputFile.close()
-
- filesMetaData = extractMetaData(idlFileNames)
- for fileName in outputFileNames:
- partition = outputFileNames.index(fileName)
- fileContents = generateContent(filesMetaData, partition, len(outputFileNames))
- writeContent(fileContents, fileName)
-
- return 0
-
-
-if __name__ == '__main__':
- sys.exit(main(sys.argv))
diff --git a/chromium/third_party/WebKit/Source/core/scripts/action_makenames.py b/chromium/third_party/WebKit/Source/core/scripts/action_makenames.py
deleted file mode 100644
index 224abd693f0..00000000000
--- a/chromium/third_party/WebKit/Source/core/scripts/action_makenames.py
+++ /dev/null
@@ -1,182 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright (C) 2009 Google Inc. All rights reserved.
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions are
-# met:
-#
-# * Redistributions of source code must retain the above copyright
-# notice, this list of conditions and the following disclaimer.
-# * Redistributions in binary form must reproduce the above
-# copyright notice, this list of conditions and the following disclaimer
-# in the documentation and/or other materials provided with the
-# distribution.
-# * Neither the name of Google Inc. nor the names of its
-# contributors may be used to endorse or promote products derived from
-# this software without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-#
-# Copyright (c) 2009 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-# action_makenames.py is a harness script to connect actions sections of
-# gyp-based builds to make_names.pl.
-#
-# usage: action_makenames.py OUTPUTS -- INPUTS [-- OPTIONS]
-#
-# Multiple OUTPUTS, INPUTS, and OPTIONS may be listed. The sections are
-# separated by -- arguments.
-#
-# The directory name of the first output is chosen as the directory in which
-# make_names will run. If the directory name for any subsequent output is
-# different, those files will be moved to the desired directory.
-#
-# Multiple INPUTS may be listed. An input with a basename matching
-# "make_names.pl" is taken as the path to that script. Inputs with names
-# ending in TagNames.in or tags.in are taken as tag inputs. Inputs with names
-# ending in AttributeNames.in or attrs.in are taken as attribute inputs. There
-# may be at most one tag input and one attribute input. A make_names.pl input
-# is required and at least one tag or attribute input must be present.
-#
-# OPTIONS is a list of additional options to pass to make_names.pl. This
-# section need not be present.
-
-
-import os
-import posixpath
-import shutil
-import subprocess
-import sys
-
-
-def SplitArgsIntoSections(args):
- sections = []
- while len(args) > 0:
- if not '--' in args:
- # If there is no '--' left, everything remaining is an entire section.
- dashes = len(args)
- else:
- dashes = args.index('--')
-
- sections.append(args[:dashes])
-
- # Next time through the loop, look at everything after this '--'.
- if dashes + 1 == len(args):
- # If the '--' is at the end of the list, we won't come back through the
- # loop again. Add an empty section now corresponding to the nothingness
- # following the final '--'.
- args = []
- sections.append(args)
- else:
- args = args[dashes + 1:]
-
- return sections
-
-
-def main(args):
- sections = SplitArgsIntoSections(args[1:])
- assert len(sections) == 2 or len(sections) == 3
- (outputs, inputs) = sections[:2]
- if len(sections) == 3:
- options = sections[2]
- else:
- options = []
-
- # Make all output pathnames absolute so that they can be accessed after
- # changing directory.
- for index in xrange(0, len(outputs)):
- outputs[index] = os.path.abspath(outputs[index])
-
- outputDir = os.path.dirname(outputs[0])
-
- # Look at the inputs and figure out which ones are make_names.pl, tags, and
- # attributes. There can be at most one of each, and those are the only
- # input types supported. make_names.pl is required and at least one of tags
- # and attributes is required.
- makeNamesInput = None
- tagInput = None
- attrInput = None
- eventsInput = None
- for input in inputs:
- # Make input pathnames absolute so they can be accessed after changing
- # directory. On Windows, convert \ to / for inputs to the perl script to
- # work around the intermix of activepython + cygwin perl.
- inputAbs = os.path.abspath(input)
- inputAbsPosix = inputAbs.replace(os.path.sep, posixpath.sep)
- inputBasename = os.path.basename(input)
- if inputBasename in ('make_names.pl', 'make_event_factory.pl', 'make_dom_exceptions.pl', 'make_settings.pl'):
- assert makeNamesInput == None
- makeNamesInput = inputAbs
- elif inputBasename.endswith('TagNames.in') or inputBasename.endswith('tags.in'):
- assert tagInput == None
- tagInput = inputAbsPosix
- elif inputBasename.endswith('AttributeNames.in') or inputBasename.endswith('attrs.in'):
- assert attrInput == None
- attrInput = inputAbsPosix
- elif (inputBasename.endswith('EventTargetFactory.in') or inputBasename.endswith('EventNames.in')
- or inputBasename.endswith('DOMExceptions.in') or inputBasename.endswith('Settings.in')):
- eventsInput = inputAbsPosix
- elif inputBasename.endswith('Names.in'):
- options.append(inputAbsPosix)
- elif inputBasename.endswith('.pm'):
- continue
- else:
- assert False
-
- assert makeNamesInput != None
- assert tagInput != None or attrInput != None or eventsInput != None or ('--fonts' in options) or ('--resourceTypes' in options)
-
- # scriptsPath is a Perl include directory, located relative to
- # makeNamesInput.
- scriptsPath = os.path.normpath(
- os.path.join(os.path.dirname(makeNamesInput), os.pardir, 'scripts'))
-
- # Change to the output directory because make_names.pl puts output in its
- # working directory.
- os.chdir(outputDir)
-
- # Build up the command.
- command = ['perl', '-I', scriptsPath, makeNamesInput]
- if tagInput != None:
- command.extend(['--tags', tagInput])
- if attrInput != None:
- command.extend(['--attrs', attrInput])
- if eventsInput != None:
- command.extend(['--input', eventsInput])
- command.extend(options)
-
- # Do it. check_call is new in 2.5, so simulate its behavior with call and
- # assert.
- returnCode = subprocess.call(command)
- assert returnCode == 0
-
- # Go through the outputs. Any output that belongs in a different directory
- # is moved. Do a copy and delete instead of rename for maximum portability.
- # Note that all paths used in this section are still absolute.
- for output in outputs:
- thisOutputDir = os.path.dirname(output)
- if thisOutputDir != outputDir:
- outputBasename = os.path.basename(output)
- src = os.path.join(outputDir, outputBasename)
- dst = os.path.join(thisOutputDir, outputBasename)
- shutil.copyfile(src, dst)
- os.unlink(src)
-
- return returnCode
-
-
-if __name__ == '__main__':
- sys.exit(main(sys.argv))
diff --git a/chromium/third_party/WebKit/Source/core/scripts/action_useragentstylesheets.py b/chromium/third_party/WebKit/Source/core/scripts/action_useragentstylesheets.py
deleted file mode 100644
index c0712b3ec4d..00000000000
--- a/chromium/third_party/WebKit/Source/core/scripts/action_useragentstylesheets.py
+++ /dev/null
@@ -1,124 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright (C) 2009 Google Inc. All rights reserved.
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions are
-# met:
-#
-# * Redistributions of source code must retain the above copyright
-# notice, this list of conditions and the following disclaimer.
-# * Redistributions in binary form must reproduce the above
-# copyright notice, this list of conditions and the following disclaimer
-# in the documentation and/or other materials provided with the
-# distribution.
-# * Neither the name of Google Inc. nor the names of its
-# contributors may be used to endorse or promote products derived from
-# this software without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-#
-# Copyright (c) 2009 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-# usage:
-# action_useragentstylesheets.py OUTPUTS INPUTS -- MAINSCRIPT MODULES -- OPTIONS
-#
-# OUTPUTS must contain two items, in order: a path to UserAgentStyleSheets.h
-# and a path to UserAgentStyleSheetsData.cpp.
-# INPUTS contains one or more CSS files.
-#
-# MAINSCRIPT is the path to make-css-file-arrays.pl. MODULES may contain
-# multiple paths to additional perl modules.
-#
-# OPTIONS are passed as-is to MAINSCRIPT as additional arguments.
-
-
-import os
-import shlex
-import subprocess
-import sys
-
-
-def SplitArgsIntoSections(args):
- sections = []
- while len(args) > 0:
- if not '--' in args:
- # If there is no '--' left, everything remaining is an entire section.
- dashes = len(args)
- else:
- dashes = args.index('--')
-
- sections.append(args[:dashes])
-
- # Next time through the loop, look at everything after this '--'.
- if dashes + 1 == len(args):
- # If the '--' is at the end of the list, we won't come back through the
- # loop again. Add an empty section now corresponding to the nothingness
- # following the final '--'.
- args = []
- sections.append(args)
- else:
- args = args[dashes + 1:]
-
- return sections
-
-
-def main(args):
- sections = SplitArgsIntoSections(args[1:])
- assert len(sections) == 3
- (outputsInputs, scripts, options) = sections
-
- assert len(outputsInputs) >= 3
- outputH = outputsInputs[0]
- outputCpp = outputsInputs[1]
- styleSheets = outputsInputs[2:]
-
- assert len(scripts) >= 1
- makeCssFileArrays = scripts[0]
- perlModules = scripts[1:]
-
- includeDirs = []
- for perlModule in perlModules:
- includeDir = os.path.dirname(perlModule)
- if not includeDir in includeDirs:
- includeDirs.append(includeDir)
-
- # The defines come in as one flat string. Split it up into distinct arguments.
- if '--defines' in options:
- definesIndex = options.index('--defines')
- if definesIndex + 1 < len(options):
- splitOptions = shlex.split(options[definesIndex + 1])
- if splitOptions:
- options[definesIndex + 1] = ' '.join(splitOptions)
-
- # Build up the command.
- command = ['perl']
- for includeDir in includeDirs:
- command.extend(['-I', includeDir])
- command.append(makeCssFileArrays)
- command.extend(options)
- command.extend([outputH, outputCpp])
- command.extend(styleSheets)
-
- # Do it. check_call is new in 2.5, so simulate its behavior with call and
- # assert.
- returnCode = subprocess.call(command)
- assert returnCode == 0
-
- return returnCode
-
-
-if __name__ == '__main__':
- sys.exit(main(sys.argv))
diff --git a/chromium/third_party/WebKit/Source/core/scripts/check_objc_rename.sh b/chromium/third_party/WebKit/Source/core/scripts/check_objc_rename.sh
deleted file mode 100755
index 5a5176e862d..00000000000
--- a/chromium/third_party/WebKit/Source/core/scripts/check_objc_rename.sh
+++ /dev/null
@@ -1,79 +0,0 @@
-#!/bin/bash
-
-#
-# Copyright (C) 2011 Google Inc. All rights reserved.
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions are
-# met:
-#
-# * Redistributions of source code must retain the above copyright
-# notice, this list of conditions and the following disclaimer.
-# * Redistributions in binary form must reproduce the above
-# copyright notice, this list of conditions and the following disclaimer
-# in the documentation and/or other materials provided with the
-# distribution.
-# * Neither the name of Google Inc. nor the names of its
-# contributors may be used to endorse or promote products derived from
-# this software without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-#
-
-# This script checks a WebCore static library for potential Objective-C
-# class name collisions with the system's copy of the WebCore framework.
-# See the postbuild action that calls it from ../WebCore.gyp for details.
-
-set -e
-set -o pipefail
-
-if [[ $# -ne 2 ]]; then
- echo "usage: ${0} class_whitelist_pattern category_whitelist_pattern" >& 2
- exit 1
-fi
-
-lib="${BUILT_PRODUCTS_DIR}/${FULL_PRODUCT_NAME}"
-nm_pattern='[atsATS] ([+-]\[|\.objc_class_name_)'
-
-class_whitelist_pattern="${1}"
-category_whitelist_pattern="${2}"
-
-# Send nm's stderr in the pipeline to /dev/null to avoid spewing
-# "nm: no name list" messages. This means that if the pipelined nm fails, there
-# won't be any output, so if the entire assignment fails, run nm again to get
-# some output.
-violators=$(nm -p "${lib}" 2> /dev/null | \
- (grep -E "${nm_pattern}" || true) | \
- (grep -Ev "${nm_pattern}(${class_whitelist_pattern})" || true) | \
- (grep -Ev "\((${category_whitelist_pattern})\)" || true)) || nm -p "${lib}"
-
-if [[ -z "${violators}" ]]; then
- # An empty list means that everything's clean.
- exit 0
-fi
-
-cat << __EOF__ >&2
-These Objective-C symbols may clash with those provided by the system's own
-WebCore framework:
-${violators}
-
-These symbols were found in:
-${lib}
-
-This should be corrected by adding the appropriate definitions to
-$(dirname ${0})/../WebCore.gyp
-or by updating the whitelist in
-${0}
-__EOF__
-
-exit 1
diff --git a/chromium/third_party/WebKit/Source/core/scripts/in_file.py b/chromium/third_party/WebKit/Source/core/scripts/in_file.py
deleted file mode 100644
index d8d8235704b..00000000000
--- a/chromium/third_party/WebKit/Source/core/scripts/in_file.py
+++ /dev/null
@@ -1,160 +0,0 @@
-# Copyright (C) 2013 Google Inc. All rights reserved.
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions are
-# met:
-#
-# * Redistributions of source code must retain the above copyright
-# notice, this list of conditions and the following disclaimer.
-# * Redistributions in binary form must reproduce the above
-# copyright notice, this list of conditions and the following disclaimer
-# in the documentation and/or other materials provided with the
-# distribution.
-# * Neither the name of Google Inc. nor the names of its
-# contributors may be used to endorse or promote products derived from
-# this software without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-import copy
-import os
-
-# NOTE: This has only been used to parse
-# core/page/RuntimeEnabledFeatures.in and may not be capable
-# of parsing other .in files correctly.
-
-# .in file format is:
-# // comment
-# name1 arg=value, arg2=value2, arg2=value3
-#
-# InFile must be passed a dictionary of default values
-# with which to validate arguments against known names.
-# Sequence types as default values will produce sequences
-# as parse results.
-# Bare arguments (no '=') are treated as names with value True.
-# The first field will always be labeled 'name'.
-#
-# InFile.load_from_files(['file.in'], {'arg': None, 'arg2': []})
-#
-# Parsing produces an array of dictionaries:
-# [ { 'name' : 'name1', 'arg' :' value', arg2=['value2', 'value3'] }
-
-def _is_comment(line):
- return line.startswith("//") or line.startswith("#")
-
-class InFile(object):
- def __init__(self, lines, defaults, valid_values=None, default_parameters=None):
- self.name_dictionaries = []
- self.parameters = copy.deepcopy(default_parameters if default_parameters else {})
- self._defaults = defaults
- self._valid_values = copy.deepcopy(valid_values if valid_values else {})
- self._parse(map(str.strip, lines))
-
- @classmethod
- def load_from_files(self, file_paths, defaults, valid_values, default_parameters):
- lines = []
- for path in file_paths:
- with open(os.path.abspath(path)) as in_file:
- lines += in_file.readlines()
- return InFile(lines, defaults, valid_values, default_parameters)
-
- def _is_sequence(self, arg):
- return (not hasattr(arg, "strip")
- and hasattr(arg, "__getitem__")
- or hasattr(arg, "__iter__"))
-
- def _parse(self, lines):
- parsing_parameters = True
- indices = {}
- for line in lines:
- if _is_comment(line):
- continue
- if not line:
- parsing_parameters = False
- continue
- if parsing_parameters:
- self._parse_parameter(line)
- else:
- entry = self._parse_line(line)
- name = entry['name']
- if name in indices:
- entry = self._merge_entries(entry, self.name_dictionaries[indices[name]])
- entry['name'] = name
- self.name_dictionaries[indices[name]] = entry
- else:
- indices[name] = len(self.name_dictionaries)
- self.name_dictionaries.append(entry)
-
-
- def _merge_entries(self, one, two):
- merged = {}
- for key in one:
- if key not in two:
- self._fatal("Expected key '%s' not found in entry: %s" % (key, two))
- if one[key] and two[key]:
- val_one = one[key]
- val_two = two[key]
- if isinstance(val_one, list) and isinstance(val_two, list):
- val = val_one + val_two
- elif isinstance(val_one, list):
- val = val_one + [val_two]
- elif isinstance(val_two, list):
- val = [val_one] + val_two
- else:
- val = [val_one, val_two]
- merged[key] = val
- elif one[key]:
- merged[key] = one[key]
- else:
- merged[key] = two[key]
- return merged
-
-
- def _parse_parameter(self, line):
- if '=' in line:
- name, value = line.split('=')
- else:
- name, value = line, True
- if not name in self.parameters:
- self._fatal("Unknown parameter: '%s' in line:\n%s\nKnown parameters: %s" % (name, line, self.parameters.keys()))
- self.parameters[name] = value
-
- def _parse_line(self, line):
- args = copy.deepcopy(self._defaults)
- parts = line.split(' ')
- args['name'] = parts[0]
- # re-join the rest of the line and split on ','
- args_list = ' '.join(parts[1:]).strip().split(',')
- for arg_string in args_list:
- arg_string = arg_string.strip()
- if not arg_string: # Ignore empty args
- continue
- if '=' in arg_string:
- arg_name, arg_value = arg_string.split('=')
- else:
- arg_name, arg_value = arg_string, True
- if arg_name not in self._defaults:
- self._fatal("Unknown argument: '%s' in line:\n%s\nKnown arguments: %s" % (arg_name, line, self._defaults.keys()))
- valid_values = self._valid_values.get(arg_name)
- if valid_values and arg_value not in valid_values:
- self._fatal("Unknown value: '%s' in line:\n%s\nKnown values: %s" % (arg_value, line, valid_values))
- if self._is_sequence(args[arg_name]):
- args[arg_name].append(arg_value)
- else:
- args[arg_name] = arg_value
- return args
-
- def _fatal(self, message):
- # FIXME: This should probably raise instead of exit(1)
- print message
- exit(1)
diff --git a/chromium/third_party/WebKit/Source/core/scripts/in_file_unittest.py b/chromium/third_party/WebKit/Source/core/scripts/in_file_unittest.py
deleted file mode 100644
index e065d442987..00000000000
--- a/chromium/third_party/WebKit/Source/core/scripts/in_file_unittest.py
+++ /dev/null
@@ -1,77 +0,0 @@
-#!/usr/bin/env python
-# Copyright (C) 2013 Google Inc. All rights reserved.
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions are
-# met:
-#
-# * Redistributions of source code must retain the above copyright
-# notice, this list of conditions and the following disclaimer.
-# * Redistributions in binary form must reproduce the above
-# copyright notice, this list of conditions and the following disclaimer
-# in the documentation and/or other materials provided with the
-# distribution.
-# * Neither the name of Google Inc. nor the names of its
-# contributors may be used to endorse or promote products derived from
-# this software without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-import unittest
-
-from in_file import InFile
-
-class InFileTest(unittest.TestCase):
- def test_basic_parse(self):
- contents = """
-name1 arg=value, arg2=value2, arg2=value3
-name2
-"""
- lines = contents.split("\n")
- defaults = {
- 'arg': None,
- 'arg2': [],
- }
- in_file = InFile(lines, defaults, None)
- expected_values = [
- {'name': 'name1', 'arg': 'value', 'arg2': ['value2', 'value3']},
- {'name': 'name2', 'arg': None, 'arg2': []},
- ]
- self.assertEquals(in_file.name_dictionaries, expected_values)
-
- def test_with_parameters(self):
- contents = """namespace=TestNamespace
-fruit
-
-name1 arg=value, arg2=value2, arg2=value3
-name2
-"""
- lines = contents.split("\n")
- defaults = {
- 'arg': None,
- 'arg2': [],
- }
- default_parameters = {
- 'namespace': '',
- 'fruit': False,
- }
- in_file = InFile(lines, defaults, default_parameters)
- expected_parameters = {
- 'namespace': 'TestNamespace',
- 'fruit': True,
- }
- self.assertEquals(in_file.parameters, expected_parameters)
-
-
-if __name__ == "__main__":
- unittest.main()
diff --git a/chromium/third_party/WebKit/Source/core/scripts/in_generator.py b/chromium/third_party/WebKit/Source/core/scripts/in_generator.py
deleted file mode 100644
index b02d6e6cbed..00000000000
--- a/chromium/third_party/WebKit/Source/core/scripts/in_generator.py
+++ /dev/null
@@ -1,119 +0,0 @@
-# Copyright (C) 2013 Google Inc. All rights reserved.
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions are
-# met:
-#
-# * Redistributions of source code must retain the above copyright
-# notice, this list of conditions and the following disclaimer.
-# * Redistributions in binary form must reproduce the above
-# copyright notice, this list of conditions and the following disclaimer
-# in the documentation and/or other materials provided with the
-# distribution.
-# * Neither the name of Google Inc. nor the names of its
-# contributors may be used to endorse or promote products derived from
-# this software without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-import os.path
-import shlex
-import shutil
-import optparse
-
-from in_file import InFile
-
-
-class Writer(object):
- # Subclasses should override.
- class_name = None
- defaults = None
- valid_values = None
- default_parameters = None
-
- def __init__(self, in_files, enabled_conditions):
- if isinstance(in_files, basestring):
- in_files = [in_files]
- self.in_file = InFile.load_from_files(in_files, self.defaults, self.valid_values, self.default_parameters)
- self._enabled_conditions = enabled_conditions
- self._outputs = {} # file_name -> generator
-
- def wrap_with_condition(self, string, condition):
- if not condition:
- return string
- return "#if ENABLE(%(condition)s)\n%(string)s\n#endif" % { 'condition' : condition, 'string' : string }
-
- def _forcibly_create_text_file_at_path_with_contents(self, file_path, contents):
- # FIXME: This method can be made less force-full anytime after 6/1/2013.
- # A gyp error was briefly checked into the tree, causing
- # a directory to have been generated in place of one of
- # our output files. Clean up after that error so that
- # all users don't need to clobber their output directories.
- shutil.rmtree(file_path, ignore_errors=True)
- # The build system should ensure our output directory exists, but just in case.
- directory = os.path.dirname(file_path)
- if not os.path.exists(directory):
- os.makedirs(directory)
-
- with open(file_path, "w") as file_to_write:
- file_to_write.write(contents)
-
- def _write_file(self, output_dir, contents, file_name):
- path = os.path.join(output_dir, file_name)
- self._forcibly_create_text_file_at_path_with_contents(path, contents)
-
- def write_files(self, output_dir):
- for file_name, generator in self._outputs.items():
- self._write_file(output_dir, generator(), file_name)
-
-
-class Maker(object):
- def __init__(self, writer_class):
- self._writer_class = writer_class
-
- def _enabled_conditions_from_defines(self, defines_arg_string):
- if not defines_arg_string:
- return []
-
- defines_strings = shlex.split(defines_arg_string)
-
- # We only care about feature defines.
- enable_prefix = 'ENABLE_'
-
- enabled_conditions = []
- for define_string in defines_strings:
- split_define = define_string.split('=')
- if split_define[1] != '1':
- continue
- define = split_define[0]
- if not define.startswith(enable_prefix):
- continue
- enabled_conditions.append(define[len(enable_prefix):])
- return enabled_conditions
-
- def main(self, argv):
- script_name = os.path.basename(argv[0])
- args = argv[1:]
- if len(args) < 1:
- print "USAGE: %i INPUT_FILES" % script_name
- exit(1)
-
- parser = optparse.OptionParser()
- parser.add_option("--defines")
- parser.add_option("--output_dir", default=os.getcwd())
- (options, args) = parser.parse_args()
-
- enabled_conditions = self._enabled_conditions_from_defines(options.defines)
-
- writer = self._writer_class(args, enabled_conditions)
- writer.write_files(options.output_dir)
diff --git a/chromium/third_party/WebKit/Source/core/scripts/license.py b/chromium/third_party/WebKit/Source/core/scripts/license.py
deleted file mode 100644
index 32da9800be6..00000000000
--- a/chromium/third_party/WebKit/Source/core/scripts/license.py
+++ /dev/null
@@ -1,62 +0,0 @@
-# Copyright (C) 2013 Google Inc. All rights reserved.
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions are
-# met:
-#
-# * Redistributions of source code must retain the above copyright
-# notice, this list of conditions and the following disclaimer.
-# * Redistributions in binary form must reproduce the above
-# copyright notice, this list of conditions and the following disclaimer
-# in the documentation and/or other materials provided with the
-# distribution.
-# * Neither the name of Google Inc. nor the names of its
-# contributors may be used to endorse or promote products derived from
-# this software without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-# FIXME: We should either not use license blocks in generated files
-# or we should read this from some central license file.
-
-def license_for_generated_cpp():
- return """/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-"""
diff --git a/chromium/third_party/WebKit/Source/core/scripts/list_idl_files_with_partial_interface.py b/chromium/third_party/WebKit/Source/core/scripts/list_idl_files_with_partial_interface.py
deleted file mode 100644
index edebc517d08..00000000000
--- a/chromium/third_party/WebKit/Source/core/scripts/list_idl_files_with_partial_interface.py
+++ /dev/null
@@ -1,44 +0,0 @@
-# Copyright (C) 2013 Google Inc. All rights reserved.
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions are
-# met:
-#
-# * Redistributions of source code must retain the above copyright
-# notice, this list of conditions and the following disclaimer.
-# * Redistributions in binary form must reproduce the above
-# copyright notice, this list of conditions and the following disclaimer
-# in the documentation and/or other materials provided with the
-# distribution.
-# * Neither the name of Google Inc. nor the names of its
-# contributors may be used to endorse or promote products derived from
-# this software without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-"""This file returns a list of all the IDL files that contain a partial interface."""
-
-import re
-import sys
-
-partial_interface_regex = re.compile(r'partial\s+interface\s+(\w+).+\]', re.M | re.S)
-
-
-def DoMain(filenames):
- partial_files = set()
- for filename in filenames:
- with open(filename) as f:
- match = re.search(partial_interface_regex, f.read())
- if match:
- partial_files.add(filename)
- return '\n'.join(partial_files)
diff --git a/chromium/third_party/WebKit/Source/core/scripts/make-file-arrays.py b/chromium/third_party/WebKit/Source/core/scripts/make-file-arrays.py
deleted file mode 100755
index 68af2ae671f..00000000000
--- a/chromium/third_party/WebKit/Source/core/scripts/make-file-arrays.py
+++ /dev/null
@@ -1,136 +0,0 @@
-#!/usr/bin/env python
-# Copyright (C) 2012 Google Inc. All rights reserved.
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions are
-# met:
-#
-# * Redistributions of source code must retain the above copyright
-# notice, this list of conditions and the following disclaimer.
-# * Redistributions in binary form must reproduce the above
-# copyright notice, this list of conditions and the following disclaimer
-# in the documentation and/or other materials provided with the
-# distribution.
-# * Neither the name of Google Inc. nor the names of its
-# contributors may be used to endorse or promote products derived from
-# this software without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-# Usage: make-file-arrays.py [--condition=condition-string] --out-h=<header-file-name> --out-cpp=<cpp-file-name> <input-file>...
-
-import os.path
-import re
-import sys
-from optparse import OptionParser
-
-
-def make_variable_name_and_read(file_name):
- result = re.match(r"([\w\d_]+)\.([\w\d_]+)", os.path.basename(file_name))
- if not result:
- print "Invalid input file name:", os.path.basename(file_name)
- sys.exit(1)
- variable_name = result.group(1)[0].lower() + result.group(1)[1:] + result.group(2).capitalize()
- file = open(file_name, "rb")
- content = file.read()
- file.close()
- return (variable_name, content)
-
-
-def strip_whitespace_and_comments(file_name, content):
- result = re.match(r".*\.([^.]+)", file_name)
- if not result:
- print "The file name has no extension:", file_name
- sys.exit(1)
- extension = result.group(1).lower()
- multi_line_comment = re.compile(r"/\*.*?\*/", re.MULTILINE | re.DOTALL)
- single_line_comment = re.compile(r"//.*$", re.MULTILINE)
- repeating_space = re.compile(r"[ \t]+", re.MULTILINE)
- leading_space = re.compile(r"^[ \t]+", re.MULTILINE)
- trailing_space = re.compile(r"[ \t]+$", re.MULTILINE)
- empty_line = re.compile(r"\n+")
- if extension == "js":
- content = multi_line_comment.sub("", content)
- content = single_line_comment.sub("", content)
- content = repeating_space.sub(" ", content)
- content = leading_space.sub("", content)
- content = trailing_space.sub("", content)
- content = empty_line.sub("\n", content)
- elif extension == "css":
- content = multi_line_comment.sub("", content)
- content = repeating_space.sub(" ", content)
- content = leading_space.sub("", content)
- content = trailing_space.sub("", content)
- content = empty_line.sub("\n", content)
- return content
-
-
-def main():
- parser = OptionParser()
- parser.add_option("--out-h", dest="out_header")
- parser.add_option("--out-cpp", dest="out_cpp")
- parser.add_option("--condition", dest="flag")
- (options, args) = parser.parse_args()
- if len(args) < 1:
- parser.error("Need one or more input files")
- if not options.out_header:
- parser.error("Need to specify --out-h=filename")
- if not options.out_cpp:
- parser.error("Need to specify --out-cpp=filename")
-
- if options.flag:
- options.flag = options.flag.replace(" AND ", " && ")
- options.flag = options.flag.replace(" OR ", " || ")
-
- header_file = open(options.out_header, "w")
- if options.flag:
- header_file.write("#if " + options.flag + "\n")
- header_file.write("namespace WebCore {\n")
-
- cpp_file = open(options.out_cpp, "w")
- cpp_file.write("#include \"config.h\"\n")
- cpp_file.write("#include \"" + os.path.basename(options.out_header) + "\"\n")
- if options.flag:
- cpp_file.write("#if " + options.flag + "\n")
- cpp_file.write("namespace WebCore {\n")
-
- for file_name in args:
- (variable_name, content) = make_variable_name_and_read(file_name)
- content = strip_whitespace_and_comments(file_name, content)
- size = len(content)
- header_file.write("extern const char %s[%d];\n" % (variable_name, size))
- cpp_file.write("const char %s[%d] = {\n" % (variable_name, size))
- for index in range(size):
- char_code = ord(content[index])
- if char_code < 128:
- cpp_file.write("%d" % char_code)
- else:
- cpp_file.write("'\\x%02x'" % char_code)
- cpp_file.write("," if index != len(content) - 1 else "};\n")
- if index % 20 == 19:
- cpp_file.write("\n")
- cpp_file.write("\n")
-
- header_file.write("}\n")
- if options.flag:
- header_file.write("#endif\n")
- header_file.close()
-
- cpp_file.write("}\n")
- if options.flag:
- cpp_file.write("#endif\n")
- cpp_file.close()
-
-
-if __name__ == "__main__":
- main()
diff --git a/chromium/third_party/WebKit/Source/core/scripts/make-hash-tools.pl b/chromium/third_party/WebKit/Source/core/scripts/make-hash-tools.pl
deleted file mode 100644
index 5f77d2bd6d5..00000000000
--- a/chromium/third_party/WebKit/Source/core/scripts/make-hash-tools.pl
+++ /dev/null
@@ -1,44 +0,0 @@
-#! /usr/bin/perl
-#
-# This file is part of the WebKit project
-#
-# Copyright (C) 2010 Andras Becsi (abecsi@inf.u-szeged.hu), University of Szeged
-# Copyright (C) 2012 Apple Inc. All rights reserved.
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Library General Public
-# License as published by the Free Software Foundation; either
-# version 2 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Library General Public License for more details.
-#
-# You should have received a copy of the GNU Library General Public License
-# along with this library; see the file COPYING.LIB. If not, write to
-# the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
-# Boston, MA 02110-1301, USA.
-
-use strict;
-use File::Basename;
-
-my $outdir = $ARGV[0];
-shift;
-my $option = basename($ARGV[0],".gperf");
-
-if ($option eq "ColorData") {
- my $colorDataGenerated = "$outdir/ColorData.cpp";
- my $colorDataGperf = shift;
- my $customGperf = shift;
-
- # gperf emits this filename literally in #line directives, but VS errors
- # out because the filenames then contain unescaped \s, so replace the \
- # with /.
- $colorDataGperf =~ s/\\/\//g;
- my $gperf = $ENV{GPERF} ? $ENV{GPERF} : ($customGperf ? $customGperf : "gperf");
- system("\"$gperf\" --key-positions=\"*\" -D -s 2 $colorDataGperf --output-file=$colorDataGenerated") == 0 || die "calling gperf failed: $?";
-
-} else {
- die "Unknown option.";
-}
diff --git a/chromium/third_party/WebKit/Source/core/scripts/make_css_property_names.py b/chromium/third_party/WebKit/Source/core/scripts/make_css_property_names.py
deleted file mode 100755
index ab137e95ef4..00000000000
--- a/chromium/third_party/WebKit/Source/core/scripts/make_css_property_names.py
+++ /dev/null
@@ -1,257 +0,0 @@
-#!/usr/bin/env python
-
-import os.path
-import re
-import subprocess
-import sys
-
-from in_file import InFile
-import in_generator
-import license
-
-
-HEADER_TEMPLATE = """
-%(license)s
-
-#ifndef %(class_name)s_h
-#define %(class_name)s_h
-
-#include "core/css/CSSParserMode.h"
-#include "wtf/HashFunctions.h"
-#include "wtf/HashTraits.h"
-#include <string.h>
-
-namespace WTF {
-class AtomicString;
-class String;
-}
-
-namespace WebCore {
-
-enum CSSPropertyID {
- CSSPropertyInvalid = 0,
- CSSPropertyVariable = 1,
-%(property_enums)s
-};
-
-const int firstCSSProperty = %(first_property_id)s;
-const int numCSSProperties = %(properties_count)s;
-const int lastCSSProperty = %(last_property_id)d;
-const size_t maxCSSPropertyNameLength = %(max_name_length)d;
-
-const char* getPropertyName(CSSPropertyID);
-const WTF::AtomicString& getPropertyNameAtomicString(CSSPropertyID);
-WTF::String getPropertyNameString(CSSPropertyID);
-WTF::String getJSPropertyName(CSSPropertyID);
-bool isInternalProperty(CSSPropertyID id);
-
-inline CSSPropertyID convertToCSSPropertyID(int value)
-{
- ASSERT((value >= firstCSSProperty && value <= lastCSSProperty) || value == CSSPropertyInvalid);
- return static_cast<CSSPropertyID>(value);
-}
-
-} // namespace WebCore
-
-namespace WTF {
-template<> struct DefaultHash<WebCore::CSSPropertyID> { typedef IntHash<unsigned> Hash; };
-template<> struct HashTraits<WebCore::CSSPropertyID> : GenericHashTraits<WebCore::CSSPropertyID> {
- static const bool emptyValueIsZero = true;
- static const bool needsDestruction = false;
- static void constructDeletedValue(WebCore::CSSPropertyID& slot) { slot = static_cast<WebCore::CSSPropertyID>(WebCore::lastCSSProperty + 1); }
- static bool isDeletedValue(WebCore::CSSPropertyID value) { return value == (WebCore::lastCSSProperty + 1); }
-};
-}
-
-#endif // %(class_name)s_h
-"""
-
-GPERF_TEMPLATE = """
-%%{
-%(license)s
-
-#include "config.h"
-#include "%(class_name)s.h"
-#include "core/platform/HashTools.h"
-#include <string.h>
-
-#include "wtf/ASCIICType.h"
-#include "wtf/text/AtomicString.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-static const char propertyNameStringsPool[] = {
-%(property_name_strings)s
-};
-
-static const unsigned short propertyNameStringsOffsets[] = {
-%(property_name_offsets)s
-};
-
-%%}
-%%struct-type
-struct Property;
-%%omit-struct-type
-%%language=C++
-%%readonly-tables
-%%global-table
-%%compare-strncmp
-%%define class-name %(class_name)sHash
-%%define lookup-function-name findPropertyImpl
-%%define hash-function-name propery_hash_function
-%%define slot-name nameOffset
-%%define word-array-name property_wordlist
-%%enum
-%%%%
-%(property_to_enum_map)s
-%%%%
-const Property* findProperty(register const char* str, register unsigned int len)
-{
- return %(class_name)sHash::findPropertyImpl(str, len);
-}
-
-const char* getPropertyName(CSSPropertyID id)
-{
- if (id < firstCSSProperty)
- return 0;
- int index = id - firstCSSProperty;
- if (index >= numCSSProperties)
- return 0;
- return propertyNameStringsPool + propertyNameStringsOffsets[index];
-}
-
-const AtomicString& getPropertyNameAtomicString(CSSPropertyID id)
-{
- if (id < firstCSSProperty)
- return nullAtom;
- int index = id - firstCSSProperty;
- if (index >= numCSSProperties)
- return nullAtom;
-
- static AtomicString* propertyStrings = new AtomicString[numCSSProperties]; // Intentionally never destroyed.
- AtomicString& propertyString = propertyStrings[index];
- if (propertyString.isNull()) {
- const char* propertyName = propertyNameStringsPool + propertyNameStringsOffsets[index];
- propertyString = AtomicString(propertyName, strlen(propertyName), AtomicString::ConstructFromLiteral);
- }
- return propertyString;
-}
-
-String getPropertyNameString(CSSPropertyID id)
-{
- // We share the StringImpl with the AtomicStrings.
- return getPropertyNameAtomicString(id).string();
-}
-
-String getJSPropertyName(CSSPropertyID id)
-{
- char result[maxCSSPropertyNameLength + 1];
- const char* cssPropertyName = getPropertyName(id);
- const char* propertyNamePointer = cssPropertyName;
- if (!propertyNamePointer)
- return emptyString();
-
- char* resultPointer = result;
- while (char character = *propertyNamePointer++) {
- if (character == '-') {
- char nextCharacter = *propertyNamePointer++;
- if (!nextCharacter)
- break;
- character = (propertyNamePointer - 2 != cssPropertyName) ? toASCIIUpper(nextCharacter) : nextCharacter;
- }
- *resultPointer++ = character;
- }
- *resultPointer = '\\0';
- return String(result);
-}
-
-bool isInternalProperty(CSSPropertyID id)
-{
- switch (id) {
- %(internal_properties)s
- return true;
- default:
- return false;
- }
-}
-
-} // namespace WebCore
-"""
-
-
-class CSSPropertiesWriter(in_generator.Writer):
- class_name = "CSSPropertyNames"
- defaults = {
- 'alias_for': None,
- 'condition': None,
- 'is_internal': False,
- }
-
- def __init__(self, file_paths, enabled_conditions):
- in_generator.Writer.__init__(self, file_paths, enabled_conditions)
- self._outputs = {(self.class_name + ".h"): self.generate_header,
- (self.class_name + ".cpp"): self.generate_implementation,
- }
-
- all_properties = self.in_file.name_dictionaries
- self._aliases = filter(lambda property: property['alias_for'], all_properties)
- for offset, property in enumerate(self._aliases):
- # Aliases use the enum_name that they are an alias for.
- property['enum_name'] = self._enum_name_from_property_name(property['alias_for'])
- # Aliases do not get an enum_value.
-
- self._properties = filter(lambda property: not property['alias_for'] and not property['condition'] or property['condition'] in self._enabled_conditions, all_properties)
- if len(self._properties) > 1024:
- print "ERROR : There is more than 1024 CSS Properties, you need to update CSSProperty.h/StylePropertyMetadata m_propertyID accordingly."
- exit(1)
- self._first_property_id = 2 # We start after CSSPropertyInvalid and CSSPropertyVariable.
- property_id = self._first_property_id
- for offset, property in enumerate(self._properties):
- property['enum_name'] = self._enum_name_from_property_name(property['name'])
- property['enum_value'] = self._first_property_id + offset
- if property['name'].startswith('-internal-'):
- property['is_internal'] = True
-
- def _enum_name_from_property_name(self, property_name):
- return "CSSProperty" + re.sub(r'(^[^-])|-(.)', lambda match: (match.group(1) or match.group(2)).upper(), property_name)
-
- def _enum_declaration(self, property):
- return " %(enum_name)s = %(enum_value)s," % property
-
- def generate_header(self):
- return HEADER_TEMPLATE % {
- 'license': license.license_for_generated_cpp(),
- 'class_name': self.class_name,
- 'property_enums': "\n".join(map(self._enum_declaration, self._properties)),
- 'first_property_id': self._first_property_id,
- 'properties_count': len(self._properties),
- 'last_property_id': self._first_property_id + len(self._properties) - 1,
- 'max_name_length': reduce(max, map(len, map(lambda property: property['name'], self._properties))),
- }
-
- def _case_properties(self, property):
- return "case %(enum_name)s:" % property
-
- def generate_implementation(self):
- property_offsets = []
- current_offset = 0
- for property in self._properties:
- property_offsets.append(current_offset)
- current_offset += len(property["name"]) + 1
-
- gperf_input = GPERF_TEMPLATE % {
- 'license': license.license_for_generated_cpp(),
- 'class_name': self.class_name,
- 'property_name_strings': '\n'.join(map(lambda property: ' "%(name)s\\0"' % property, self._properties)),
- 'property_name_offsets': '\n'.join(map(lambda offset: ' %d,' % offset, property_offsets)),
- 'property_to_enum_map': '\n'.join(map(lambda property: '%(name)s, %(enum_name)s' % property, self._properties + self._aliases)),
- 'internal_properties': '\n'.join(map(self._case_properties, filter(lambda property: property['is_internal'], self._properties))),
- }
- # FIXME: If we could depend on Python 2.7, we would use subprocess.check_output
- gperf_args = ['gperf', '--key-positions=*', '-P', '-D', '-n', '-s', '2']
- gperf = subprocess.Popen(gperf_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
- return gperf.communicate(gperf_input)[0]
-
-
-if __name__ == "__main__":
- in_generator.Maker(CSSPropertiesWriter).main(sys.argv)
diff --git a/chromium/third_party/WebKit/Source/core/scripts/make_css_value_keywords.py b/chromium/third_party/WebKit/Source/core/scripts/make_css_value_keywords.py
deleted file mode 100755
index 0b5a3d65e6b..00000000000
--- a/chromium/third_party/WebKit/Source/core/scripts/make_css_value_keywords.py
+++ /dev/null
@@ -1,177 +0,0 @@
-#!/usr/bin/env python
-
-import os.path
-import re
-import subprocess
-import sys
-
-from in_file import InFile
-import in_generator
-import license
-
-
-HEADER_TEMPLATE = """
-%(license)s
-
-#ifndef %(class_name)s_h
-#define %(class_name)s_h
-
-#include "core/css/CSSParserMode.h"
-#include <string.h>
-
-namespace WebCore {
-
-enum CSSValueID {
-%(value_keyword_enums)s
-};
-
-const int numCSSValueKeywords = %(value_keywords_count)d;
-const size_t maxCSSValueKeywordLength = %(max_value_keyword_length)d;
-
-const char* getValueName(unsigned short id);
-bool isValueAllowedInMode(unsigned short id, CSSParserMode mode);
-
-} // namespace WebCore
-
-#endif // %(class_name)s_h
-"""
-
-GPERF_TEMPLATE = """
-%%{
-%(license)s
-
-#include "config.h"
-#include "%(class_name)s.h"
-#include "core/platform/HashTools.h"
-#include <string.h>
-
-namespace WebCore {
-static const char valueListStringPool[] = {
-"\\0"
-%(value_keyword_strings)s
-};
-
-static const unsigned short valueListStringOffsets[] = {
-%(value_keyword_offsets)s
-};
-
-%%}
-%%struct-type
-struct Value;
-%%omit-struct-type
-%%language=C++
-%%readonly-tables
-%%compare-strncmp
-%%define class-name %(class_name)sHash
-%%define lookup-function-name findValueImpl
-%%define hash-function-name value_hash_function
-%%define slot-name nameOffset
-%%define word-array-name value_word_list
-%%pic
-%%enum
-%%%%
-%(value_keyword_to_enum_map)s
-%%%%
-const Value* findValue(register const char* str, register unsigned int len)
-{
- return CSSValueKeywordsHash::findValueImpl(str, len);
-}
-
-const char* getValueName(unsigned short id)
-{
- if (id >= numCSSValueKeywords || id <= 0)
- return 0;
- return valueListStringPool + valueListStringOffsets[id];
-}
-
-bool isValueAllowedInMode(unsigned short id, CSSParserMode mode)
-{
- switch (id) {
- %(ua_sheet_mode_values_keywords)s
- return mode == UASheetMode;
- %(quirks_mode_values_keywords)s
- return mode == CSSQuirksMode;
- %(quirks_mode_or_ua_sheet_mode_values_keywords)s
- return mode == UASheetMode || mode == CSSQuirksMode;
- default:
- return true;
- }
-}
-
-} // namespace WebCore
-"""
-
-
-class CSSValueKeywordsWriter(in_generator.Writer):
- class_name = "CSSValueKeywords"
- defaults = {
- 'condition': None,
- 'mode': None,
- }
-
- def __init__(self, file_paths, enabled_conditions):
- in_generator.Writer.__init__(self, file_paths, enabled_conditions)
- self._outputs = {(self.class_name + ".h"): self.generate_header,
- (self.class_name + ".cpp"): self.generate_implementation,
- }
-
- all_properties = self.in_file.name_dictionaries
- self._value_keywords = filter(lambda property: not property['condition'] or property['condition'] in self._enabled_conditions, all_properties)
- first_property_id = 1
- for offset, property in enumerate(self._value_keywords):
- property['name'] = property['name'].lower()
- property['enum_name'] = self._enum_name_from_value_keyword(property['name'])
- property['enum_value'] = first_property_id + offset
- if property['name'].startswith('-internal-'):
- assert property['mode'] is None, 'Can\'t specify mode for value keywords with the prefix "-internal-".'
- property['mode'] = 'UASheet'
- else:
- assert property['mode'] != 'UASheet', 'UASheet mode only value keywords should have the prefix "-internal-".'
-
- def _enum_name_from_value_keyword(self, value_keyword):
- return "CSSValue" + "".join(w.capitalize() for w in value_keyword.split("-"))
-
- def _enum_declaration(self, property):
- return " %(enum_name)s = %(enum_value)s," % property
-
- def _case_value_keyword(self, property):
- return "case %(enum_name)s:" % property
-
- def generate_header(self):
- enum_enties = map(self._enum_declaration, [{'enum_name': 'CSSValueInvalid', 'enum_value': 0}] + self._value_keywords)
- return HEADER_TEMPLATE % {
- 'license': license.license_for_generated_cpp(),
- 'class_name': self.class_name,
- 'value_keyword_enums': "\n".join(enum_enties),
- 'value_keywords_count': len(enum_enties),
- 'max_value_keyword_length': reduce(max, map(len, map(lambda property: property['name'], self._value_keywords))),
- }
-
- def _value_keywords_with_mode(self, mode):
- return filter(lambda property: property['mode'] == mode, self._value_keywords)
-
- def generate_implementation(self):
- keyword_offsets = [0]
- current_offset = 1
- for keyword in self._value_keywords:
- keyword_offsets.append(current_offset)
- current_offset += len(keyword["name"]) + 1
-
- gperf_input = GPERF_TEMPLATE % {
- 'license': license.license_for_generated_cpp(),
- 'class_name': self.class_name,
- 'value_keyword_strings': '\n'.join(map(lambda property: ' "%(name)s\\0"' % property, self._value_keywords)),
- 'value_keyword_offsets': '\n'.join(map(lambda offset: ' %d,' % offset, keyword_offsets)),
- 'value_keyword_to_enum_map': '\n'.join(map(lambda property: '%(name)s, %(enum_name)s' % property, self._value_keywords)),
- 'ua_sheet_mode_values_keywords': '\n '.join(map(self._case_value_keyword, self._value_keywords_with_mode('UASheet'))),
- 'quirks_mode_values_keywords': '\n '.join(map(self._case_value_keyword, self._value_keywords_with_mode('Quirks'))),
- 'quirks_mode_or_ua_sheet_mode_values_keywords': '\n '.join(map(self._case_value_keyword, self._value_keywords_with_mode('QuirksOrUASheet'))),
- }
- # FIXME: If we could depend on Python 2.7, we would use subprocess.check_output
- gperf_args = ['gperf', '--key-positions=*', '-D', '-n', '-s', '2']
- gperf = subprocess.Popen(gperf_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
- return gperf.communicate(gperf_input)[0]
-
-
-if __name__ == "__main__":
- in_generator.Maker(CSSValueKeywordsWriter).main(sys.argv)
diff --git a/chromium/third_party/WebKit/Source/core/scripts/make_event_factory.py b/chromium/third_party/WebKit/Source/core/scripts/make_event_factory.py
deleted file mode 100644
index ace45ab3a17..00000000000
--- a/chromium/third_party/WebKit/Source/core/scripts/make_event_factory.py
+++ /dev/null
@@ -1,100 +0,0 @@
-#!/usr/bin/env python
-# Copyright (C) 2013 Google Inc. All rights reserved.
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions are
-# met:
-#
-# * Redistributions of source code must retain the above copyright
-# notice, this list of conditions and the following disclaimer.
-# * Redistributions in binary form must reproduce the above
-# copyright notice, this list of conditions and the following disclaimer
-# in the documentation and/or other materials provided with the
-# distribution.
-# * Neither the name of Google Inc. nor the names of its
-# contributors may be used to endorse or promote products derived from
-# this software without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-import os.path
-import sys
-import shutil
-
-from in_file import InFile
-import name_macros
-from name_utilities import lower_first
-import license
-
-
-IMPLEMENTATION_TEMPLATE = """%(license)s
-#include "config.h"
-#include "%(class_name)sFactory.h"
-
-#include "%(class_name)sHeaders.h"
-#include "RuntimeEnabledFeatures.h"
-
-namespace WebCore {
-
-PassRefPtr<%(class_name)s> %(class_name)sFactory::create(const String& type)
-{
-%(factory_implementation)s
- return 0;
-}
-
-} // namespace WebCore
-"""
-
-
-class EventFactoryWriter(name_macros.Writer):
- defaults = {
- 'ImplementedAs': None,
- 'Conditional': None,
- 'EnabledAtRuntime': None,
- }
- default_parameters = {
- 'namespace': '',
- }
-
- def __init__(self, in_file_path, enabled_conditions):
- super(EventFactoryWriter, self).__init__(in_file_path, enabled_conditions)
- self._outputs[(self.class_name + ".cpp")] = self.generate_implementation
-
- def _events(self):
- return self.in_file.name_dictionaries
-
- def _factory_implementation(self, event):
- if event['EnabledAtRuntime']:
- runtime_condition = ' && RuntimeEnabledFeatures::%s()' % lower_first(event['EnabledAtRuntime'])
- else:
- runtime_condition = ''
- name = os.path.basename(event['name'])
- class_name = self._class_name_for_entry(event)
- implementation = """ if (type == "%(name)s"%(runtime_condition)s)
- return %(class_name)s::create();""" % {
- 'name': name,
- 'runtime_condition': runtime_condition,
- 'class_name': class_name,
- }
- return self.wrap_with_condition(implementation, event['Conditional'])
-
- def generate_implementation(self):
- return IMPLEMENTATION_TEMPLATE % {
- 'class_name': self.class_name,
- 'license': license.license_for_generated_cpp(),
- 'factory_implementation': "\n".join(map(self._factory_implementation, self._events())),
- }
-
-
-if __name__ == "__main__":
- name_macros.Maker(EventFactoryWriter).main(sys.argv)
diff --git a/chromium/third_party/WebKit/Source/core/scripts/make_internal_runtime_flags.py b/chromium/third_party/WebKit/Source/core/scripts/make_internal_runtime_flags.py
deleted file mode 100755
index 522e00f5962..00000000000
--- a/chromium/third_party/WebKit/Source/core/scripts/make_internal_runtime_flags.py
+++ /dev/null
@@ -1,64 +0,0 @@
-#!/usr/bin/env python
-# Copyright (C) 2013 Google Inc. All rights reserved.
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions are
-# met:
-#
-# * Redistributions of source code must retain the above copyright
-# notice, this list of conditions and the following disclaimer.
-# * Redistributions in binary form must reproduce the above
-# copyright notice, this list of conditions and the following disclaimer
-# in the documentation and/or other materials provided with the
-# distribution.
-# * Neither the name of Google Inc. nor the names of its
-# contributors may be used to endorse or promote products derived from
-# this software without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-import os.path
-import sys
-
-import in_generator
-import make_runtime_features
-import template_expander
-
-
-# We want exactly the same parsing as RuntimeFeatureWriter
-# but generate different files.
-class InternalRuntimeFlagsWriter(make_runtime_features.RuntimeFeatureWriter):
- class_name = "InternalRuntimeFlags"
-
- def __init__(self, in_file_path, enabled_conditions):
- super(InternalRuntimeFlagsWriter, self).__init__(in_file_path, enabled_conditions)
- self._outputs = {(self.class_name + ".idl"): self.generate_idl,
- (self.class_name + ".h"): self.generate_header,
- }
-
- @template_expander.use_jinja(class_name + ".idl.tmpl")
- def generate_idl(self):
- return {
- 'features': self._features,
- }
-
- @template_expander.use_jinja(class_name + ".h.tmpl")
- def generate_header(self):
- return {
- 'features': self._features,
- 'feature_sets': self._feature_sets(),
- }
-
-
-if __name__ == "__main__":
- in_generator.Maker(InternalRuntimeFlagsWriter).main(sys.argv)
diff --git a/chromium/third_party/WebKit/Source/core/scripts/make_names.pl b/chromium/third_party/WebKit/Source/core/scripts/make_names.pl
deleted file mode 100755
index 1748ca62255..00000000000
--- a/chromium/third_party/WebKit/Source/core/scripts/make_names.pl
+++ /dev/null
@@ -1,1292 +0,0 @@
-#!/usr/bin/perl -w
-
-# Copyright (C) 2005, 2006, 2007, 2009 Apple Inc. All rights reserved.
-# Copyright (C) 2009, Julien Chaffraix <jchaffraix@webkit.org>
-# Copyright (C) 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
-# Copyright (C) 2011 Ericsson AB. All rights reserved.
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions
-# are met:
-#
-# 1. Redistributions of source code must retain the above copyright
-# notice, this list of conditions and the following disclaimer.
-# 2. Redistributions in binary form must reproduce the above copyright
-# notice, this list of conditions and the following disclaimer in the
-# documentation and/or other materials provided with the distribution.
-# 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
-# its contributors may be used to endorse or promote products derived
-# from this software without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
-# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-# DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
-# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
-# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
-# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
-# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
-# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-use strict;
-
-use StaticString;
-use Config;
-use Getopt::Long;
-use File::Path;
-use File::Spec;
-use IO::File;
-use InFilesParser;
-
-sub readTags($$);
-sub readAttrs($$);
-
-my $printFactory = 0;
-my $fontNamesIn = "";
-my $resourceTypesIn = "";
-my $tagsFile = "";
-my $attrsFile = "";
-my $outputDir = ".";
-my %parsedTags = ();
-my %parsedAttrs = ();
-my %enabledTags = ();
-my %enabledAttrs = ();
-my %allTags = ();
-my %allAttrs = ();
-my %allStrings = ();
-my %parameters = ();
-my $extraDefines = 0;
-my $initDefaults = 1;
-my %extensionAttrs = ();
-
-require Config;
-
-my $gccLocation = "";
-if ($ENV{CC}) {
- $gccLocation = $ENV{CC};
-} elsif (($Config::Config{'osname'}) =~ /solaris/i) {
- $gccLocation = "/usr/sfw/bin/gcc";
-} else {
- $gccLocation = "/usr/bin/gcc";
-}
-my $preprocessor = $gccLocation . " -E -x c++";
-
-GetOptions(
- 'tags=s' => \$tagsFile,
- 'attrs=s' => \$attrsFile,
- 'factory' => \$printFactory,
- 'outputDir=s' => \$outputDir,
- 'extraDefines=s' => \$extraDefines,
- 'preprocessor=s' => \$preprocessor,
- 'fonts=s' => \$fontNamesIn,
- 'resourceTypes=s' => \$resourceTypesIn
-);
-
-mkpath($outputDir);
-
-if (length($fontNamesIn)) {
- my $familyNamesFileBase = "FontFamily";
- my $familyNamesPrefix = "CSS";
- createGenericNamesFile($fontNamesIn, $familyNamesFileBase, $familyNamesPrefix);
-}
-
-if (length($resourceTypesIn)) {
- my $baseName = "FetchInitiatorType";
- my $basePrefix = "Loader_Cache";
- createGenericNamesFile($resourceTypesIn, $baseName, $basePrefix);
-}
-
-die "You must specify at least one of --tags <file> or --attrs <file>" unless (length($tagsFile) || length($attrsFile));
-
-if (length($tagsFile)) {
- %allTags = %{readTags($tagsFile, 0)};
- %enabledTags = %{readTags($tagsFile, 1)};
- namesToStrings(\%allTags, \%allStrings);
-}
-
-if (length($attrsFile)) {
- %allAttrs = %{readAttrs($attrsFile, 0)};
- %enabledAttrs = %{readAttrs($attrsFile, 1)};
- namesToStrings(\%allAttrs, \%allStrings);
-}
-
-die "You must specify a namespace (e.g. SVG) for <namespace>Names.h" unless $parameters{namespace};
-die "You must specify a namespaceURI (e.g. http://www.w3.org/2000/svg)" unless $parameters{namespaceURI};
-
-$parameters{namespacePrefix} = $parameters{namespace} unless $parameters{namespacePrefix};
-$parameters{fallbackJSInterfaceName} = $parameters{fallbackInterfaceName} unless $parameters{fallbackJSInterfaceName};
-
-my $namesBasePath = "$outputDir/$parameters{namespace}Names";
-my $factoryBasePath = "$outputDir/$parameters{namespace}ElementFactory";
-my $wrapperFactoryFileName = "$parameters{namespace}ElementWrapperFactory";
-
-printNamesHeaderFile("$namesBasePath.h");
-printNamesCppFile("$namesBasePath.cpp");
-
-if ($printFactory) {
- printFactoryCppFile("$factoryBasePath.cpp");
- printFactoryHeaderFile("$factoryBasePath.h");
-}
-
-printWrapperFactoryCppFile($outputDir, $wrapperFactoryFileName);
-printWrapperFactoryHeaderFile($outputDir, $wrapperFactoryFileName);
-
-### Hash initialization
-
-sub defaultTagPropertyHash
-{
- return (
- 'constructorNeedsCreatedByParser' => 0,
- 'constructorNeedsFormElement' => 0,
- 'noConstructor' => 0,
- 'interfaceName' => defaultInterfaceName($_[0]),
- # By default, the JSInterfaceName is the same as the interfaceName.
- 'JSInterfaceName' => defaultInterfaceName($_[0]),
- 'mapToTagName' => '',
- 'wrapperOnlyIfMediaIsAvailable' => 0,
- 'conditional' => 0,
- 'contextConditional' => 0,
- 'runtimeConditional' => 0
- );
-}
-
-sub defaultParametersHash
-{
- return (
- 'namespace' => '',
- 'namespacePrefix' => '',
- 'namespaceURI' => '',
- 'guardFactoryWith' => '',
- 'tagsNullNamespace' => 0,
- 'attrsNullNamespace' => 0,
- 'fallbackInterfaceName' => '',
- 'fallbackJSInterfaceName' => ''
- );
-}
-
-sub defaultInterfaceName
-{
- die "No namespace found" if !$parameters{namespace};
- return $parameters{namespace} . upperCaseName($_[0]) . "Element"
-}
-
-### Parsing handlers
-
-sub valueForName
-{
- my $name = shift;
- my $value = $extensionAttrs{$name};
-
- if (!$value) {
- $value = $name;
- $value =~ s/_/-/g;
- }
-
- return $value;
-}
-
-sub namesToStrings
-{
- my $namesRef = shift;
- my $stringsRef = shift;
-
- my %names = %$namesRef;
-
- for my $name (keys %names) {
- $stringsRef->{$name} = valueForName($name);
- }
-}
-
-sub tagsHandler
-{
- my ($tag, $property, $value) = @_;
-
- $tag =~ s/-/_/g;
-
- # Initialize default property values.
- $parsedTags{$tag} = { defaultTagPropertyHash($tag) } if !defined($parsedTags{$tag});
-
- if ($property) {
- die "Unknown property $property for tag $tag\n" if !defined($parsedTags{$tag}{$property});
-
- # The code relies on JSInterfaceName deriving from interfaceName to check for custom JSInterfaceName.
- # So override JSInterfaceName if it was not already set.
- $parsedTags{$tag}{JSInterfaceName} = $value if $property eq "interfaceName" && $parsedTags{$tag}{JSInterfaceName} eq $parsedTags{$tag}{interfaceName};
-
- $parsedTags{$tag}{$property} = $value;
- }
-}
-
-sub attrsHandler
-{
- my ($attr, $property, $value) = @_;
- # Translate HTML5 extension attributes of the form 'x-webkit-feature' to 'webkitfeature'.
- # We don't just check for the 'x-' prefix because there are attributes such as x-height
- # which should follow the default path below.
- if ($attr =~ m/^x-webkit-(.*)/) {
- my $newAttr = "webkit$1";
- $extensionAttrs{$newAttr} = $attr;
- $attr = $newAttr;
- }
- $attr =~ s/-/_/g;
-
- # Initialize default properties' values.
- $parsedAttrs{$attr} = {} if !defined($parsedAttrs{$attr});
-
- if ($property) {
- die "Unknown property $property for attribute $attr\n" if !defined($parsedAttrs{$attr}{$property});
- $parsedAttrs{$attr}{$property} = $value;
- }
-}
-
-sub parametersHandler
-{
- my ($parameter, $value) = @_;
-
- # Initialize default properties' values.
- %parameters = defaultParametersHash() if (!(keys %parameters) && $initDefaults);
-
- # If the input is an array, we want the strings to have the same value as the key.
- if ( $value eq 1) {
- $value = $parameter;
- }
-
- die "Unknown parameter $parameter for tags/attrs\n" if (!defined($parameters{$parameter}) && $initDefaults);
- $parameters{$parameter} = $value;
-}
-
-## Support routines
-
-sub preprocessorCommand()
-{
- return $preprocessor if $extraDefines eq 0;
- return $preprocessor . " -D" . join(" -D", split(" ", $extraDefines));
-}
-
-sub readNames($$$$)
-{
- my ($namesFile, $hashToFillRef, $handler, $usePreprocessor) = @_;
-
- my $names = new IO::File;
- if ($usePreprocessor) {
- open($names, preprocessorCommand() . " " . $namesFile . "|") or die "Failed to open file: $namesFile";
- } else {
- open($names, $namesFile) or die "Failed to open file: $namesFile";
- }
-
- my $InParser = InFilesParser->new();
- $InParser->parse($names, \&parametersHandler, $handler);
-
- close($names);
- die "Failed to read names from file: $namesFile" if (keys %{$hashToFillRef} == 0);
- return $hashToFillRef;
-}
-
-sub readAttrs($$)
-{
- my ($namesFile, $usePreprocessor) = @_;
- %parsedAttrs = ();
- return readNames($namesFile, \%parsedAttrs, \&attrsHandler, $usePreprocessor);
-}
-
-sub readTags($$)
-{
- my ($namesFile, $usePreprocessor) = @_;
- %parsedTags = ();
- return readNames($namesFile, \%parsedTags, \&tagsHandler, $usePreprocessor);
-}
-
-sub printMacros
-{
- my ($F, $macro, $suffix, $namesRef) = @_;
- my %names = %$namesRef;
-
- for my $name (sort keys %names) {
- print F "$macro $name","$suffix;\n";
- }
-}
-
-sub usesDefaultWrapper
-{
- my $tagName = shift;
- return $tagName eq $parameters{namespace} . "Element";
-}
-
-# Build a direct mapping from the tags to the Element to create.
-sub buildConstructorMap
-{
- my %tagConstructorMap = ();
- for my $tagName (keys %enabledTags) {
- my $interfaceName = $enabledTags{$tagName}{interfaceName};
-
- if ($enabledTags{$tagName}{mapToTagName}) {
- die "Cannot handle multiple mapToTagName for $tagName\n" if $enabledTags{$enabledTags{$tagName}{mapToTagName}}{mapToTagName};
- $interfaceName = $enabledTags{ $enabledTags{$tagName}{mapToTagName} }{interfaceName};
- }
-
- # Chop the string to keep the interesting part.
- $interfaceName =~ s/$parameters{namespace}(.*)Element/$1/;
- $tagConstructorMap{$tagName} = lc($interfaceName);
- }
-
- return %tagConstructorMap;
-}
-
-# Helper method that print the constructor's signature avoiding
-# unneeded arguments.
-sub printConstructorSignature
-{
- my ($F, $tagName, $constructorName, $constructorTagName) = @_;
-
- print F "static PassRefPtr<$parameters{namespace}Element> ${constructorName}Constructor(const QualifiedName& $constructorTagName, Document& document";
- if ($parameters{namespace} eq "HTML") {
- print F ", HTMLFormElement*";
- print F " formElement" if $enabledTags{$tagName}{constructorNeedsFormElement};
- }
- print F ", bool";
- print F " createdByParser" if $enabledTags{$tagName}{constructorNeedsCreatedByParser};
- print F ")\n{\n";
-}
-
-# Helper method to dump the constructor interior and call the
-# Element constructor with the right arguments.
-# The variable names should be kept in sync with the previous method.
-sub printConstructorInterior
-{
- my ($F, $tagName, $interfaceName, $constructorTagName) = @_;
-
- # Handle media elements.
- if ($enabledTags{$tagName}{wrapperOnlyIfMediaIsAvailable}) {
- print F <<END
- Settings* settings = document.settings();
- if (!RuntimeEnabledFeatures::mediaEnabled() || (settings && !settings->mediaEnabled()))
- return 0;
-
-END
-;
- }
-
- my $contextConditional = $enabledTags{$tagName}{contextConditional};
- if ($contextConditional) {
- print F <<END
- if (!ContextFeatures::${contextConditional}Enabled(&document))
- return 0;
-END
-;
- }
-
- my $runtimeConditional = $enabledTags{$tagName}{runtimeConditional};
- if ($runtimeConditional) {
- print F <<END
- if (!RuntimeEnabledFeatures::${runtimeConditional}Enabled())
- return 0;
-END
-;
- }
-
- # Call the constructor with the right parameters.
- print F " return ${interfaceName}::create($constructorTagName, document";
- print F ", formElement" if $enabledTags{$tagName}{constructorNeedsFormElement};
- print F ", createdByParser" if $enabledTags{$tagName}{constructorNeedsCreatedByParser};
- print F ");\n}\n\n";
-}
-
-sub printConstructors
-{
- my ($F, $tagConstructorMapRef) = @_;
- my %tagConstructorMap = %$tagConstructorMapRef;
-
- # This is to avoid generating the same constructor several times.
- my %uniqueTags = ();
- for my $tagName (sort keys %tagConstructorMap) {
- my $interfaceName = $enabledTags{$tagName}{interfaceName};
-
- # Ignore the mapped tag
- # FIXME: It could be moved inside this loop but was split for readibility.
- next if (defined($uniqueTags{$interfaceName}) || $enabledTags{$tagName}{mapToTagName});
- # Tags can have wrappers without constructors.
- # This is useful to make user-agent shadow elements internally testable
- # while keeping them from being avaialble in the HTML markup.
- next if $enabledTags{$tagName}{noConstructor};
-
- $uniqueTags{$interfaceName} = '1';
-
- my $conditional = $enabledTags{$tagName}{conditional};
- if ($conditional) {
- my $conditionalString = "ENABLE(" . join(") && ENABLE(", split(/&/, $conditional)) . ")";
- print F "#if ${conditionalString}\n\n";
- }
-
- printConstructorSignature($F, $tagName, $tagConstructorMap{$tagName}, "tagName");
- printConstructorInterior($F, $tagName, $interfaceName, "tagName");
-
- if ($conditional) {
- print F "#endif\n";
- }
- }
-
- # Mapped tag name uses a special wrapper to keep their prefix and namespaceURI while using the mapped localname.
- for my $tagName (sort keys %tagConstructorMap) {
- if ($enabledTags{$tagName}{mapToTagName}) {
- my $mappedName = $enabledTags{$tagName}{mapToTagName};
- printConstructorSignature($F, $mappedName, $mappedName . "To" . $tagName, "tagName");
- printConstructorInterior($F, $mappedName, $enabledTags{$mappedName}{interfaceName}, "QualifiedName(tagName.prefix(), ${mappedName}Tag.localName(), tagName.namespaceURI())");
- }
- }
-}
-
-sub printFunctionInits
-{
- my ($F, $tagConstructorMap) = @_;
- my %tagConstructorMap = %$tagConstructorMap;
-
- for my $tagName (sort keys %tagConstructorMap) {
- next if $enabledTags{$tagName}{noConstructor};
-
- my $conditional = $enabledTags{$tagName}{conditional};
- if ($conditional) {
- my $conditionalString = "ENABLE(" . join(") && ENABLE(", split(/&/, $conditional)) . ")";
- print F "#if ${conditionalString}\n";
- }
-
- if ($enabledTags{$tagName}{mapToTagName}) {
- print F " addTag(${tagName}Tag, $enabledTags{$tagName}{mapToTagName}To${tagName}Constructor);\n";
- } else {
- print F " addTag(${tagName}Tag, $tagConstructorMap{$tagName}Constructor);\n";
- }
-
- if ($conditional) {
- print F "#endif\n\n";
- }
- }
-}
-
-sub svgCapitalizationHacks
-{
- my $name = shift;
-
- $name = "FE" . ucfirst $1 if $name =~ /^fe(.+)$/;
-
- return $name;
-}
-
-sub upperCaseName
-{
- my $name = shift;
-
- $name = svgCapitalizationHacks($name) if ($parameters{namespace} eq "SVG");
-
- while ($name =~ /^(.*?)_(.*)/) {
- $name = $1 . ucfirst $2;
- }
-
- return ucfirst $name;
-}
-
-sub printHeaderHead
-{
- my ($F, $prefix, $nsName, $includes) = @_;
-
- print F "#ifndef ${prefix}_${nsName}Names_h\n";
- print F "#define ${prefix}_${nsName}Names_h\n\n";
- print F "$includes\n\n";
-
- print F "namespace WebCore {\n\n";
- print F "namespace ${nsName}Names {\n\n";
-
- print F "#ifndef ${prefix}_${nsName}NAMES_HIDE_GLOBALS\n";
-}
-
-sub printCppHead
-{
- my ($F, $prefix, $nsName, $usedNamespace) = @_;
-
- print F "#include \"config.h\"\n\n";
- print F "#ifdef SKIP_STATIC_CONSTRUCTORS_ON_GCC\n";
- print F "#define ${prefix}_${nsName}NAMES_HIDE_GLOBALS 1\n";
- print F "#else\n";
- print F "#define QNAME_DEFAULT_CONSTRUCTOR 1\n";
- print F "#endif\n\n";
-
- print F "#include \"${nsName}Names.h\"\n\n";
- print F "#include \"wtf/StaticConstructors.h\"\n";
-
- print F "namespace WebCore {\n\n";
- print F "namespace ${nsName}Names {\n\n";
- print F "using namespace $usedNamespace;\n\n";
-}
-
-sub printInit
-{
- my ($F, $isDefinition) = @_;
-
- if ($isDefinition) {
- print F "\nvoid init();\n\n";
- print F "} }\n\n";
- print F "#endif\n\n";
- return;
- }
-
-print F "\nvoid init()
-{
- // Use placement new to initialize the globals.
-
-";
-}
-
-sub printLicenseHeader
-{
- my $F = shift;
- print F "/*
- * THIS FILE WAS AUTOMATICALLY GENERATED, DO NOT EDIT.
- *
- * This file was generated by the core/scripts/make_names.pl script.
- *
- * Copyright (C) 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-";
-}
-
-sub printNamesHeaderFile
-{
- my ($headerPath) = shift;
- my $F;
- open F, ">$headerPath";
-
- printLicenseHeader($F);
- printHeaderHead($F, "DOM", $parameters{namespace}, "#include \"core/dom/QualifiedName.h\"");
-
- my $lowerNamespace = lc($parameters{namespacePrefix});
- print F "// Namespace\n";
- print F "extern const WTF::AtomicString ${lowerNamespace}NamespaceURI;\n\n";
-
- if (keys %allTags) {
- print F "// Tags\n";
- printMacros($F, "extern const WebCore::QualifiedName", "Tag", \%allTags);
- }
-
- if (keys %allAttrs) {
- print F "// Attributes\n";
- printMacros($F, "extern const WebCore::QualifiedName", "Attr", \%allAttrs);
- }
- print F "#endif\n\n";
-
- if (keys %allTags) {
- print F "const unsigned $parameters{namespace}TagsCount = ", scalar(keys %allTags), ";\n";
- print F "WebCore::QualifiedName** get$parameters{namespace}Tags();\n";
- }
-
- if (keys %allAttrs) {
- print F "const unsigned $parameters{namespace}AttrsCount = ", scalar(keys %allAttrs), ";\n";
- print F "WebCore::QualifiedName** get$parameters{namespace}Attrs();\n";
- }
-
- printInit($F, 1);
- close F;
-}
-
-sub printNamesCppFile
-{
- my $cppPath = shift;
- my $F;
- open F, ">$cppPath";
-
- printLicenseHeader($F);
- printCppHead($F, "DOM", $parameters{namespace}, "WebCore");
-
- my $lowerNamespace = lc($parameters{namespacePrefix});
-
- print F "DEFINE_GLOBAL(AtomicString, ${lowerNamespace}NamespaceURI)\n\n";
-
- if (keys %allTags) {
- print F "// Tags\n";
- for my $name (sort keys %allTags) {
- print F "DEFINE_GLOBAL(QualifiedName, ", $name, "Tag)\n";
- }
-
- print F "\n\nWebCore::QualifiedName** get$parameters{namespace}Tags()\n";
- print F "{\n static WebCore::QualifiedName* $parameters{namespace}Tags[] = {\n";
- for my $name (sort keys %allTags) {
- print F " (WebCore::QualifiedName*)&${name}Tag,\n";
- }
- print F " };\n";
- print F " return $parameters{namespace}Tags;\n";
- print F "}\n";
- }
-
- if (keys %allAttrs) {
- print F "\n// Attributes\n";
- for my $name (sort keys %allAttrs) {
- print F "DEFINE_GLOBAL(QualifiedName, ", $name, "Attr)\n";
- }
- print F "\n\nWebCore::QualifiedName** get$parameters{namespace}Attrs()\n";
- print F "{\n static WebCore::QualifiedName* $parameters{namespace}Attr[] = {\n";
- for my $name (sort keys %allAttrs) {
- print F " (WebCore::QualifiedName*)&${name}Attr,\n";
- }
- print F " };\n";
- print F " return $parameters{namespace}Attr;\n";
- print F "}\n";
- }
-
- printInit($F, 0);
-
- print(F " AtomicString ${lowerNamespace}NS(\"$parameters{namespaceURI}\", AtomicString::ConstructFromLiteral);\n\n");
-
- print(F " // Namespace\n");
- print(F " new ((void*)&${lowerNamespace}NamespaceURI) AtomicString(${lowerNamespace}NS);\n");
- print(F "\n");
- print F StaticString::GenerateStringImpls(\%allStrings);
-
- if (keys %allTags) {
- my $tagsNamespace = $parameters{tagsNullNamespace} ? "nullAtom" : "${lowerNamespace}NS";
- printDefinitions($F, \%allTags, "tags", $tagsNamespace);
- }
- if (keys %allAttrs) {
- my $attrsNamespace = $parameters{attrsNullNamespace} ? "nullAtom" : "${lowerNamespace}NS";
- printDefinitions($F, \%allAttrs, "attributes", $attrsNamespace);
- }
-
- print F "}\n\n} }\n\n";
- close F;
-}
-
-sub printJSElementIncludes
-{
- my $F = shift;
-
- my %tagsSeen;
- for my $tagName (sort keys %enabledTags) {
- my $JSInterfaceName = $enabledTags{$tagName}{JSInterfaceName};
- next if defined($tagsSeen{$JSInterfaceName}) || usesDefaultJSWrapper($tagName);
- if ($enabledTags{$tagName}{conditional}) {
- # We skip feature-define-specific #includes here since we handle them separately.
- next;
- }
- $tagsSeen{$JSInterfaceName} = 1;
-
- print F "#include \"V8${JSInterfaceName}.h\"\n";
- }
- print F "#include \"V8$parameters{fallbackJSInterfaceName}.h\"\n";
-}
-
-sub printElementIncludes
-{
- my $F = shift;
-
- my %tagsSeen;
- for my $tagName (sort keys %enabledTags) {
- my $interfaceName = $enabledTags{$tagName}{interfaceName};
- next if defined($tagsSeen{$interfaceName});
- if ($enabledTags{$tagName}{conditional}) {
- # We skip feature-define-specific #includes here since we handle them separately.
- next;
- }
- $tagsSeen{$interfaceName} = 1;
-
- print F "#include \"${interfaceName}.h\"\n";
- }
- print F "#include \"$parameters{fallbackInterfaceName}.h\"\n";
-}
-
-sub printConditionalElementIncludes
-{
- my ($F, $shouldIncludeV8Headers) = @_;
-
- my %conditionals;
- my %unconditionalElementIncludes;
- my %unconditionalJSElementIncludes;
-
- for my $tagName (keys %enabledTags) {
- my $conditional = $enabledTags{$tagName}{conditional};
- my $interfaceName = $enabledTags{$tagName}{interfaceName};
- my $JSInterfaceName = $enabledTags{$tagName}{JSInterfaceName};
-
- if ($conditional) {
- $conditionals{$conditional}{interfaceNames}{$interfaceName} = 1;
- $conditionals{$conditional}{JSInterfaceNames}{$JSInterfaceName} = 1;
- } else {
- $unconditionalElementIncludes{$interfaceName} = 1;
- $unconditionalJSElementIncludes{$JSInterfaceName} = 1;
- }
- }
-
- for my $conditional (sort keys %conditionals) {
- print F "\n#if ENABLE($conditional)\n";
- for my $interfaceName (sort keys %{$conditionals{$conditional}{interfaceNames}}) {
- next if $unconditionalElementIncludes{$interfaceName};
- print F "#include \"$interfaceName.h\"\n";
- }
- if ($shouldIncludeV8Headers) {
- for my $JSInterfaceName (sort keys %{$conditionals{$conditional}{JSInterfaceNames}}) {
- next if $unconditionalJSElementIncludes{$JSInterfaceName};
- print F "#include \"V8$JSInterfaceName.h\"\n";
- }
- }
- print F "#endif\n";
- }
-}
-
-sub printDefinitions
-{
- my ($F, $namesRef, $type, $namespaceURI) = @_;
- my $singularType = substr($type, 0, -1);
- my $shortType = substr($singularType, 0, 4);
- my $shortCamelType = ucfirst($shortType);
- my $shortUpperType = uc($shortType);
-
- print F " // " . ucfirst($type) . "\n";
-
- for my $name (sort keys %$namesRef) {
- # To generate less code in init(), the common case of nullAtom for the namespace, we call createQualifiedName() without passing $namespaceURI.
- if ($namespaceURI eq "nullAtom") {
- print F " createQualifiedName((void*)&$name","${shortCamelType}, ${name}Impl);\n";
- } else {
- print F " createQualifiedName((void*)&$name","${shortCamelType}, ${name}Impl, $namespaceURI);\n";
- }
- }
-}
-
-## ElementFactory routines
-
-sub printFactoryCppFile
-{
- my $cppPath = shift;
- my $F;
- open F, ">$cppPath";
-
-printLicenseHeader($F);
-
-print F <<END
-#include "config.h"
-END
-;
-
-print F "\n#if $parameters{guardFactoryWith}\n\n" if $parameters{guardFactoryWith};
-
-print F <<END
-#include "$parameters{namespace}ElementFactory.h"
-#include "$parameters{namespace}Names.h"
-END
-;
-
-printElementIncludes($F);
-
-print F "\n#include \"wtf/HashMap.h\"\n";
-
-printConditionalElementIncludes($F);
-
-print F <<END
-
-#include "ContextFeatures.h"
-#include "CustomElement.h"
-#include "CustomElementRegistrationContext.h"
-#include "Document.h"
-#include "RuntimeEnabledFeatures.h"
-#include "Settings.h"
-
-namespace WebCore {
-
-using namespace $parameters{namespace}Names;
-
-END
-;
-
-print F "typedef PassRefPtr<$parameters{namespace}Element> (*ConstructorFunction)(const QualifiedName&, Document&";
-print F ", HTMLFormElement*" if $parameters{namespace} eq "HTML";
-print F ", bool createdByParser);\n";
-print F <<END
-typedef HashMap<StringImpl*, ConstructorFunction> FunctionMap;
-
-static FunctionMap* gFunctionMap = 0;
-
-END
-;
-
-my %tagConstructorMap = buildConstructorMap();
-
-printConstructors($F, \%tagConstructorMap);
-
-print F <<END
-static void addTag(const QualifiedName& tag, ConstructorFunction func)
-{
- gFunctionMap->set(tag.localName().impl(), func);
-}
-
-static void createFunctionMap()
-{
- ASSERT(!gFunctionMap);
-
- // Create the table.
- gFunctionMap = new FunctionMap;
-
- // Populate it with constructor functions.
-END
-;
-
-printFunctionInits($F, \%tagConstructorMap);
-
-print F "}\n";
-
-
-print F "\nPassRefPtr<$parameters{namespace}Element> $parameters{namespace}ElementFactory::create$parameters{namespace}Element(const QualifiedName& qName, Document* document";
-print F ", HTMLFormElement* formElement" if $parameters{namespace} eq "HTML";
-print F ", bool createdByParser)\n{\n";
-
-print F <<END
- if (!document)
- return 0;
-
- if (CustomElement::isValidName(qName.localName()) && document->registrationContext()) {
- RefPtr<Element> element = document->registrationContext()->createCustomTagElement(*document, qName, createdByParser ? CustomElementRegistrationContext::CreatedByParser : CustomElementRegistrationContext::NotCreatedByParser);
- ASSERT_WITH_SECURITY_IMPLICATION(element->is$parameters{namespace}Element());
- return static_pointer_cast<$parameters{namespace}Element>(element.release());
- }
-
- if (!gFunctionMap)
- createFunctionMap();
- if (ConstructorFunction function = gFunctionMap->get(qName.localName().impl())) {
-END
-;
-
-if ($parameters{namespace} eq "HTML") {
- print F " if (PassRefPtr<$parameters{namespace}Element> element = function(qName, *document, formElement, createdByParser))\n";
- print F " return element;\n";
-} else {
- print F " if (PassRefPtr<$parameters{namespace}Element> element = function(qName, *document, createdByParser))\n";
- print F " return element;\n";
-}
-print F <<END
- }
-
- return $parameters{fallbackInterfaceName}::create(qName, *document);
-}
-
-} // namespace WebCore
-
-END
-;
-
- print F "#endif\n" if $parameters{guardFactoryWith};
-
- close F;
-}
-
-sub printFactoryHeaderFile
-{
- my $headerPath = shift;
- my $F;
- open F, ">$headerPath";
-
- printLicenseHeader($F);
-
- print F<<END
-#ifndef $parameters{namespace}ElementFactory_h
-#define $parameters{namespace}ElementFactory_h
-
-#include "wtf/Forward.h"
-#include "wtf/PassRefPtr.h"
-
-namespace WebCore {
- class Element;
- class Document;
- class QualifiedName;
-}
-
-namespace WebCore {
-
- class $parameters{namespace}Element;
-END
-;
-
-print F " class HTMLFormElement;\n" if $parameters{namespace} eq "HTML";
-
-print F<<END
- // The idea behind this class is that there will eventually be a mapping from namespace URIs to ElementFactories that can dispense
- // elements. In a compound document world, the generic createElement function (will end up being virtual) will be called.
- class $parameters{namespace}ElementFactory {
- public:
- PassRefPtr<Element> createElement(const WebCore::QualifiedName&, WebCore::Document*, bool createdByParser = true);
-END
-;
-print F " static PassRefPtr<$parameters{namespace}Element> create$parameters{namespace}Element(const WebCore::QualifiedName&, WebCore::Document*";
-print F ", HTMLFormElement* = 0" if $parameters{namespace} eq "HTML";
-print F ", bool createdByParser = true);\n";
-
-printf F<<END
- };
-}
-
-#endif // $parameters{namespace}ElementFactory_h
-
-END
-;
-
- close F;
-}
-
-## Wrapper Factory routines
-
-sub usesDefaultJSWrapper
-{
- my $name = shift;
-
- # A tag reuses the default wrapper if its JSInterfaceName matches the default namespace Element.
- return $enabledTags{$name}{JSInterfaceName} eq $parameters{namespace} . "Element";
-}
-
-sub printWrapperFunctions
-{
- my $F = shift;
-
- my %tagsSeen;
- for my $tagName (sort keys %enabledTags) {
- # Avoid defining the same wrapper method twice.
- my $JSInterfaceName = $enabledTags{$tagName}{JSInterfaceName};
- next if defined($tagsSeen{$JSInterfaceName}) || (usesDefaultJSWrapper($tagName) && ($parameters{fallbackJSInterfaceName} eq $parameters{namespace} . "Element"));
- $tagsSeen{$JSInterfaceName} = 1;
-
- my $conditional = $enabledTags{$tagName}{conditional};
- if ($conditional) {
- my $conditionalString = "ENABLE(" . join(") && ENABLE(", split(/&/, $conditional)) . ")";
- print F "#if ${conditionalString}\n\n";
- }
-
- if ($enabledTags{$tagName}{wrapperOnlyIfMediaIsAvailable}) {
- print F <<END
-static v8::Handle<v8::Object> create${JSInterfaceName}Wrapper($parameters{namespace}Element* element, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
-{
- Settings* settings = element->document().settings();
- if (!RuntimeEnabledFeatures::mediaEnabled() || (settings && !settings->mediaEnabled()))
- return createV8$parameters{namespace}DirectWrapper(element, creationContext, isolate);
- return wrap(static_cast<${JSInterfaceName}*>(element), creationContext, isolate);
-}
-
-END
-;
- } elsif ($enabledTags{$tagName}{contextConditional}) {
- my $contextConditional = $enabledTags{$tagName}{contextConditional};
- print F <<END
-static v8::Handle<v8::Object> create${JSInterfaceName}Wrapper($parameters{namespace}Element* element, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
-{
- if (!ContextFeatures::${contextConditional}Enabled(&element->document()))
- return createV8$parameters{namespace}FallbackWrapper(to$parameters{fallbackInterfaceName}(element), creationContext, isolate);
- return wrap(static_cast<${JSInterfaceName}*>(element), creationContext, isolate);
-}
-END
-;
- } elsif ($enabledTags{$tagName}{runtimeConditional}) {
- my $runtimeConditional = $enabledTags{$tagName}{runtimeConditional};
- print F <<END
-static v8::Handle<v8::Object> create${JSInterfaceName}Wrapper($parameters{namespace}Element* element, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
-{
- if (!RuntimeEnabledFeatures::${runtimeConditional}Enabled())
- return createV8$parameters{namespace}FallbackWrapper(to$parameters{fallbackInterfaceName}(element), creationContext, isolate);
- return wrap(static_cast<${JSInterfaceName}*>(element), creationContext, isolate);
-}
-END
-;
- } elsif (${JSInterfaceName} eq "HTMLElement") {
- print F <<END
-static v8::Handle<v8::Object> create${JSInterfaceName}Wrapper($parameters{namespace}Element* element, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
-{
- ASSERT_NOT_REACHED();
- return v8::Handle<v8::Object>();
-}
-
-END
-;
- } else {
- print F <<END
-static v8::Handle<v8::Object> create${JSInterfaceName}Wrapper($parameters{namespace}Element* element, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
-{
- return wrap(static_cast<${JSInterfaceName}*>(element), creationContext, isolate);
-}
-
-
-END
-;
- }
-
- if ($conditional) {
- print F "#endif\n\n";
- }
- }
-}
-
-sub printWrapperFactoryCppFile
-{
- my $outputDir = shift;
- my $wrapperFactoryFileName = shift;
- my $F;
- open F, ">" . $outputDir . "/V8" . $wrapperFactoryFileName . ".cpp";
-
- printLicenseHeader($F);
-
- print F "#include \"config.h\"\n";
- print F "#include \"V8$parameters{namespace}ElementWrapperFactory.h\"\n";
-
- print F "\n#if $parameters{guardFactoryWith}\n\n" if $parameters{guardFactoryWith};
-
- printJSElementIncludes($F);
-
- print F "\n#include \"$parameters{namespace}Names.h\"\n\n";
-
- printElementIncludes($F);
-
- print F "\n#include \"wtf/StdLibExtras.h\"\n";
-
- printConditionalElementIncludes($F, 1);
-
- print F <<END
-
-#include "ContextFeatures.h"
-#include "Document.h"
-#include "RuntimeEnabledFeatures.h"
-#include "Settings.h"
-
-#include "V8$parameters{namespace}Element.h"
-
-#include "bindings/v8/CustomElementWrapper.h"
-
-#include <v8.h>
-
-namespace WebCore {
-
-using namespace $parameters{namespace}Names;
-
-typedef v8::Handle<v8::Object> (*Create$parameters{namespace}ElementWrapperFunction)($parameters{namespace}Element*, v8::Handle<v8::Object> creationContext, v8::Isolate*);
-
-END
-;
-
- printWrapperFunctions($F);
-
- print F <<END
-v8::Handle<v8::Object> createV8$parameters{namespace}Wrapper($parameters{namespace}Element* element, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
-{
- typedef HashMap<WTF::StringImpl*, Create$parameters{namespace}ElementWrapperFunction> FunctionMap;
- DEFINE_STATIC_LOCAL(FunctionMap, map, ());
- if (map.isEmpty()) {
-END
-;
-
- for my $tag (sort keys %enabledTags) {
- # Do not add the name to the map if it does not have a JS wrapper constructor or uses the default wrapper.
- next if (usesDefaultJSWrapper($tag, \%enabledTags) && ($parameters{fallbackJSInterfaceName} eq $parameters{namespace} . "Element"));
-
- my $conditional = $enabledTags{$tag}{conditional};
- if ($conditional) {
- my $conditionalString = "ENABLE(" . join(") && ENABLE(", split(/&/, $conditional)) . ")";
- print F "#if ${conditionalString}\n";
- }
-
- my $ucTag = $enabledTags{$tag}{JSInterfaceName};
- print F " map.set(${tag}Tag.localName().impl(), create${ucTag}Wrapper);\n";
-
- if ($conditional) {
- print F "#endif\n";
- }
- }
-
- print F <<END
- }
-
- Create$parameters{namespace}ElementWrapperFunction createWrapperFunction = map.get(element->localName().impl());
-END
-;
- if ($parameters{namespace} eq "HTML") {
- print F <<END
- if (createWrapperFunction == createHTMLElementWrapper)
- createWrapperFunction = createV8HTMLDirectWrapper;
-END
-;
- }
- print F <<END
- if (element->isCustomElement())
- return CustomElementWrapper<$parameters{namespace}Element, V8$parameters{namespace}Element>::wrap(element, creationContext, isolate, createWrapperFunction);
-
- if (createWrapperFunction)
- return createWrapperFunction(element, creationContext, isolate);
-END
-;
- if ($parameters{namespace} eq "SVG") {
- print F <<END
- return V8SVGElement::createWrapper(element, creationContext, isolate);
-END
-;
- } else {
- print F <<END
- return wrap(to$parameters{fallbackInterfaceName}(element), creationContext, isolate);
-END
-;
- }
-
- my $fallbackWrapper = $parameters{fallbackInterfaceName};
- if ($parameters{namespace} eq "SVG") {
- $fallbackWrapper = "SVGElement";
- }
-
- print F <<END
-}
-
-WrapperTypeInfo* findWrapperTypeFor$parameters{namespace}TagName(const AtomicString& name)
-{
- typedef HashMap<WTF::StringImpl*, WrapperTypeInfo*> NameTypeMap;
- DEFINE_STATIC_LOCAL(NameTypeMap, map, ());
- if (map.isEmpty()) {
-END
-;
-
- for my $tagName (sort keys %enabledTags) {
- if (!usesDefaultJSWrapper($tagName)) {
- my $conditional = $enabledTags{$tagName}{conditional};
- if ($conditional) {
- my $conditionalString = "ENABLE(" . join(") && ENABLE(", split(/&/, $conditional)) . ")";
- print F "#if ${conditionalString}\n";
- }
-
- my $JSInterfaceName = $enabledTags{$tagName}{JSInterfaceName};
- print F " map.set(${tagName}Tag.localName().impl(), WrapperTypeTraits<${JSInterfaceName}>::info());\n";
-
- if ($conditional) {
- print F "#endif\n";
- }
- }
- }
-
- print F <<END
- }
-
- if (WrapperTypeInfo* result = map.get(name.impl()))
- return result;
-
- return WrapperTypeTraits<$fallbackWrapper>::info();
-}
-
-END
-;
-
- print F "}\n\n";
- print F "#endif\n" if $parameters{guardFactoryWith};
-
- close F;
-}
-
-sub printWrapperFactoryHeaderFile
-{
- my $outputDir = shift;
- my $wrapperFactoryFileName = shift;
- my $F;
- open F, ">" . $outputDir . "/V8" . $wrapperFactoryFileName . ".h";
-
- printLicenseHeader($F);
-
- print F "#ifndef V8$parameters{namespace}ElementWrapperFactory_h\n";
- print F "#define V8$parameters{namespace}ElementWrapperFactory_h\n\n";
-
- print F "#if $parameters{guardFactoryWith}\n" if $parameters{guardFactoryWith};
-
- print F <<END
-#include <V8$parameters{namespace}Element.h>
-#include <V8$parameters{fallbackJSInterfaceName}.h>
-#include <v8.h>
-
-namespace WebCore {
-
- class $parameters{namespace}Element;
-
- WrapperTypeInfo* findWrapperTypeFor$parameters{namespace}TagName(const AtomicString& name);
-
- v8::Handle<v8::Object> createV8$parameters{namespace}Wrapper($parameters{namespace}Element*, v8::Handle<v8::Object> creationContext, v8::Isolate*);
- inline v8::Handle<v8::Object> createV8$parameters{namespace}DirectWrapper($parameters{namespace}Element* element, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
- {
- return V8$parameters{namespace}Element::createWrapper(element, creationContext, isolate);
- }
- inline v8::Handle<v8::Object> createV8$parameters{namespace}FallbackWrapper($parameters{fallbackJSInterfaceName}* element, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate)
- {
- return V8$parameters{fallbackJSInterfaceName}::createWrapper(element, creationContext, isolate);
- }
-}
-END
-;
- print F "#endif // $parameters{guardFactoryWith}\n\n" if $parameters{guardFactoryWith};
-
- print F "#endif // V8$parameters{namespace}ElementWrapperFactory_h\n";
-
- close F;
-}
-
-sub createGenericNamesFile
-{
- my $inputName = shift;
- my $baseName = shift;
- my $basePrefix = shift;
-
- my $names = new IO::File;
- open($names, $inputName) or die "Failed to open file: $inputName";
-
- $initDefaults = 0;
- my $Parser = InFilesParser->new();
- my $dummy;
- $Parser->parse($names, \&parametersHandler, \&dummy);
-
- my $F;
- my $header = File::Spec->catfile($outputDir, "${baseName}Names.h");
- open F, ">$header" or die "Unable to open $header for writing.";
-
- printLicenseHeader($F);
- printHeaderHead($F, $basePrefix, $baseName, "#include \"wtf/text/AtomicString.h\"");
-
- printMacros($F, "extern const WTF::AtomicString", "", \%parameters);
- print F "#endif\n\n";
-
- printInit($F, 1);
- close F;
-
- my $source = File::Spec->catfile($outputDir, "${baseName}Names.cpp");
- open F, ">$source" or die "Unable to open $source for writing.";
-
- printLicenseHeader($F);
- printCppHead($F, $basePrefix, $baseName, "WTF");
-
- while ( my ($name, $identifier) = each %parameters ) {
- print F "DEFINE_GLOBAL(AtomicString, $name)\n";
- }
-
- printInit($F, 0);
-
- print F "\n";
- print F StaticString::GenerateStringImpls(\%parameters);
-
- while ( my ($name, $identifier) = each %parameters ) {
- print F " new ((void*)&$name) AtomicString(${name}Impl);\n";
- }
-
- print F "}\n}\n}\n";
- close F;
- exit 0;
-}
diff --git a/chromium/third_party/WebKit/Source/core/scripts/make_runtime_features.py b/chromium/third_party/WebKit/Source/core/scripts/make_runtime_features.py
deleted file mode 100755
index ad84a25a7dc..00000000000
--- a/chromium/third_party/WebKit/Source/core/scripts/make_runtime_features.py
+++ /dev/null
@@ -1,92 +0,0 @@
-#!/usr/bin/env python
-# Copyright (C) 2013 Google Inc. All rights reserved.
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions are
-# met:
-#
-# * Redistributions of source code must retain the above copyright
-# notice, this list of conditions and the following disclaimer.
-# * Redistributions in binary form must reproduce the above
-# copyright notice, this list of conditions and the following disclaimer
-# in the documentation and/or other materials provided with the
-# distribution.
-# * Neither the name of Google Inc. nor the names of its
-# contributors may be used to endorse or promote products derived from
-# this software without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-import os.path
-import sys
-
-from in_file import InFile
-import in_generator
-from name_utilities import lower_first
-import template_expander
-
-
-class RuntimeFeatureWriter(in_generator.Writer):
- class_name = 'RuntimeEnabledFeatures'
-
- # FIXME: valid_values and defaults should probably roll into one object.
- valid_values = {
- 'status': ['stable', 'experimental', 'test'],
- }
- defaults = {
- 'condition' : None,
- 'depends_on' : [],
- 'custom': False,
- 'status': None,
- }
-
- def __init__(self, in_file_path, enabled_conditions):
- super(RuntimeFeatureWriter, self).__init__(in_file_path, enabled_conditions)
- self._outputs = {(self.class_name + ".h"): self.generate_header,
- (self.class_name + ".cpp"): self.generate_implementation,
- }
-
- self._features = self.in_file.name_dictionaries
- # Make sure the resulting dictionaries have all the keys we expect.
- for feature in self._features:
- feature['first_lowered_name'] = lower_first(feature['name'])
- # Most features just check their isFooEnabled bool
- # but some depend on more than one bool.
- enabled_condition = "is%sEnabled" % feature['name']
- for dependant_name in feature['depends_on']:
- enabled_condition += " && is%sEnabled" % dependant_name
- feature['enabled_condition'] = enabled_condition
- self._non_custom_features = filter(lambda feature: not feature['custom'], self._features)
-
- def _feature_sets(self):
- # Another way to think of the status levels is as "sets of features"
- # which is how we're referring to them in this generator.
- return self.valid_values['status']
-
- @template_expander.use_jinja(class_name + ".h.tmpl")
- def generate_header(self):
- return {
- 'features': self._features,
- 'feature_sets': self._feature_sets(),
- }
-
- @template_expander.use_jinja(class_name + ".cpp.tmpl")
- def generate_implementation(self):
- return {
- 'features': self._features,
- 'feature_sets': self._feature_sets(),
- }
-
-
-if __name__ == "__main__":
- in_generator.Maker(RuntimeFeatureWriter).main(sys.argv)
diff --git a/chromium/third_party/WebKit/Source/core/scripts/make_style_builder.py b/chromium/third_party/WebKit/Source/core/scripts/make_style_builder.py
deleted file mode 100755
index b408c94b2e4..00000000000
--- a/chromium/third_party/WebKit/Source/core/scripts/make_style_builder.py
+++ /dev/null
@@ -1,128 +0,0 @@
-#!/usr/bin/env python
-# Copyright (C) 2013 Google Inc. All rights reserved.
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions are
-# met:
-#
-# * Redistributions of source code must retain the above copyright
-# notice, this list of conditions and the following disclaimer.
-# * Redistributions in binary form must reproduce the above
-# copyright notice, this list of conditions and the following disclaimer
-# in the documentation and/or other materials provided with the
-# distribution.
-# * Neither the name of Google Inc. nor the names of its
-# contributors may be used to endorse or promote products derived from
-# this software without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-import re
-import sys
-
-import in_generator
-import template_expander
-
-
-class StyleBuilderWriter(in_generator.Writer):
- class_name = 'StyleBuilder'
-
- valid_values = {
- 'svg': [True, False],
- 'custom_all': [True, False],
- 'custom_initial': [True, False],
- 'custom_inherit': [True, False],
- 'custom_value': [True, False],
- }
- defaults = {
- 'condition': None,
- 'name_for_methods': None,
- 'use_handlers_for': None,
- 'svg': False,
- 'converter': None,
-# These depend on property name by default
- 'type_name': None,
- 'getter': None,
- 'setter': None,
- 'initial': None,
-# Setting these stops default handlers being generated
-# Setting custom_all is the same as setting the other three
- 'custom_all': False,
- 'custom_initial': False,
- 'custom_inherit': False,
- 'custom_value': False,
- }
-
- def __init__(self, in_files, enabled_conditions):
- super(StyleBuilderWriter, self).__init__(in_files, enabled_conditions)
- self._outputs = {("StyleBuilderFunctions.h"): self.generate_style_builder_functions_h,
- ("StyleBuilderFunctions.cpp"): self.generate_style_builder_functions_cpp,
- ("StyleBuilder.cpp"): self.generate_style_builder,
- }
-
- self._properties = self.in_file.name_dictionaries
-
- def set_if_none(property, key, value):
- if property[key] is None:
- property[key] = value
-
- for property in self._properties:
- cc = self._camelcase_property_name(property["name"])
- property["property_id"] = "CSSProperty" + cc
- cc = property["name_for_methods"] or cc.replace("Webkit", "")
- property["camel_case_name"] = cc
- set_if_none(property, "type_name", "E" + cc)
- set_if_none(property, "getter", self._lower_first(cc))
- set_if_none(property, "setter", "set" + cc)
- set_if_none(property, "initial", "initial" + cc)
- if property["custom_all"]:
- property["custom_initial"] = True
- property["custom_inherit"] = True
- property["custom_value"] = True
-
- self._properties = dict((property["property_id"], property) for property in self._properties)
-
-# FIXME: some of these might be better in a utils file
- @staticmethod
- def _camelcase_property_name(property_name):
- return re.sub(r'(^[^-])|-(.)', lambda match: (match.group(1) or match.group(2)).upper(), property_name)
-
- @staticmethod
- def _lower_first(s):
- return s[0].lower() + s[1:]
-
- @staticmethod
- def _upper_first(s):
- return s[0].upper() + s[1:]
-
- @template_expander.use_jinja("StyleBuilderFunctions.h.tmpl")
- def generate_style_builder_functions_h(self):
- return {
- "properties": self._properties,
- }
-
- @template_expander.use_jinja("StyleBuilderFunctions.cpp.tmpl")
- def generate_style_builder_functions_cpp(self):
- return {
- "properties": self._properties,
- }
-
- @template_expander.use_jinja("StyleBuilder.cpp.tmpl")
- def generate_style_builder(self):
- return {
- "properties": self._properties,
- }
-
-
-if __name__ == "__main__":
- in_generator.Maker(StyleBuilderWriter).main(sys.argv)
diff --git a/chromium/third_party/WebKit/Source/core/scripts/make_style_shorthands.py b/chromium/third_party/WebKit/Source/core/scripts/make_style_shorthands.py
deleted file mode 100644
index c73de2fc7ad..00000000000
--- a/chromium/third_party/WebKit/Source/core/scripts/make_style_shorthands.py
+++ /dev/null
@@ -1,96 +0,0 @@
-#!/usr/bin/env python
-# Copyright (C) 2013 Intel Corporation. All rights reserved.
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions are
-# met:
-#
-# * Redistributions of source code must retain the above copyright
-# notice, this list of conditions and the following disclaimer.
-# * Redistributions in binary form must reproduce the above
-# copyright notice, this list of conditions and the following disclaimer
-# in the documentation and/or other materials provided with the
-# distribution.
-# * Neither the name of Google Inc. nor the names of its
-# contributors may be used to endorse or promote products derived from
-# this software without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-import re
-import sys
-from collections import defaultdict
-
-import in_generator
-import template_expander
-
-
-class StylePropertyShorthandWriter(in_generator.Writer):
- class_name = 'StylePropertyShorthand'
-
- defaults = {
- 'longhands': "",
- 'runtimeEnabledShorthand': None,
- }
-
- def __init__(self, in_files, enabled_conditions):
- super(StylePropertyShorthandWriter, self).__init__(in_files, enabled_conditions)
- self._outputs = {("StylePropertyShorthand.cpp"): self.generate_style_property_shorthand_cpp, ("StylePropertyShorthand.h"): self.generate_style_property_shorthand_h}
-
- self._properties = self.in_file.name_dictionaries
- self._longhand_dictionary = defaultdict(list)
-
- for property in self._properties:
- cc = self._camelcase_property_name(property["name"])
- property["property_id"] = self._create_css_property_name_enum_value(cc)
- cc = cc[0].lower() + cc[1:]
- property["camel_case_name"] = cc
- longhands = property["longhands"].split(';')
- property["camel_case_longhands"] = list()
- for longhand in longhands:
- longhand = self._camelcase_property_name(longhand)
- longhand = self._create_css_property_name_enum_value(longhand)
- property["camel_case_longhands"].append(longhand)
- self._longhand_dictionary[longhand].append(property)
- if property["runtimeEnabledShorthand"] is not None:
- lowerFirstConditional = self._lower_first(property["runtimeEnabledShorthand"])
- property["runtime_conditional_getter"] = "%sEnabled" % lowerFirstConditional
- self._properties = dict((property["property_id"], property) for property in self._properties)
-
-# FIXME: some of these might be better in a utils file
- def _camelcase_property_name(self, property_name):
- return re.sub(r'(^[^-])|-(.)', lambda match: (match.group(1) or match.group(2)).upper(), property_name)
-
- def _create_css_property_name_enum_value(self, property_name):
- return "CSSProperty" + property_name
-
- def _lower_first(self, string):
- lowered = string[0].lower() + string[1:]
- lowered = lowered.replace("cSS", "css")
- return lowered
-
- @template_expander.use_jinja("StylePropertyShorthand.cpp.tmpl")
- def generate_style_property_shorthand_cpp(self):
- return {
- "properties": self._properties,
- "longhands_dictionary": self._longhand_dictionary,
- }
-
- @template_expander.use_jinja("StylePropertyShorthand.h.tmpl")
- def generate_style_property_shorthand_h(self):
- return {
- "properties": self._properties,
- }
-
-if __name__ == "__main__":
- in_generator.Maker(StylePropertyShorthandWriter).main(sys.argv)
diff --git a/chromium/third_party/WebKit/Source/core/scripts/make_token_matcher.py b/chromium/third_party/WebKit/Source/core/scripts/make_token_matcher.py
deleted file mode 100755
index 10fae628c1c..00000000000
--- a/chromium/third_party/WebKit/Source/core/scripts/make_token_matcher.py
+++ /dev/null
@@ -1,231 +0,0 @@
-#!/usr/bin/env python
-# Copyright (C) 2013 Google Inc. All rights reserved.
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions are
-# met:
-#
-# * Redistributions of source code must retain the above copyright
-# notice, this list of conditions and the following disclaimer.
-# * Redistributions in binary form must reproduce the above
-# copyright notice, this list of conditions and the following disclaimer
-# in the documentation and/or other materials provided with the
-# distribution.
-# * Neither the name of Google Inc. nor the names of its
-# contributors may be used to endorse or promote products derived from
-# this software without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-import io
-import itertools
-import re
-import sys
-
-
-class BadInput(Exception):
- """Unsupported input has been found."""
-
-
-class SwitchCase(object):
- """Represents a CASE block."""
- def __init__(self, identifier, block):
- self.identifier = identifier
- self.block = block
-
-
-class Optimizer(object):
- """Generates optimized identifier matching code."""
- def __init__(self, output_file, array_variable, length_variable):
- self.output_file = output_file
- self.array_variable = array_variable
- self.length_variable = length_variable
-
- def inspect(self, cases):
- lengths = list(set([len(c.identifier) for c in cases]))
- lengths.sort()
-
- def response(length):
- self.inspect_array([c for c in cases if len(c.identifier) == length], range(length))
- self.write_selection(self.length_variable, lengths, str, response)
-
- def score(self, alternatives):
- return -sum([len(list(count)) ** 2 for _, count in itertools.groupby(sorted(alternatives))])
-
- def choose_selection_pos(self, cases, pending):
- candidates = [pos for pos in pending if all(alternative.isalpha() for alternative in [c.identifier[pos] for c in cases])]
- if not candidates:
- raise BadInput('Case-insensitive switching on non-alphabetic characters not yet implemented')
- return sorted(candidates, key=lambda pos: self.score([c.identifier[pos] for c in cases]))[0]
-
- def inspect_array(self, cases, pending):
- assert len(cases) >= 1
- if pending:
- common = [pos for pos in pending
- if len(set([c.identifier[pos] for c in cases])) == 1]
- if common:
- identifier = cases[0].identifier
- for index in xrange(len(common)):
- if index == 0:
- self.output_file.write(u'if (LIKELY(')
- else:
- self.output_file.write(u' && ')
- pos = common[index]
- if identifier[pos].isalpha():
- self.output_file.write("(%s[%d] | 0x20) == '%s'" %
- (self.array_variable, pos, identifier[pos]))
- else:
- self.output_file.write("%s[%d] == '%s'" %
- (self.array_variable, pos, identifier[pos]))
- self.output_file.write(u')) {\n')
- next_pending = list(set(pending) - set(common))
- next_pending.sort()
- self.inspect_array(cases, next_pending)
- self.output_file.write(u'}\n')
- else:
- pos = self.choose_selection_pos(cases, pending)
- next_pending = filter(lambda p: p != pos, pending)
-
- alternatives = list(set([c.identifier[pos] for c in cases]))
- alternatives.sort()
-
- def literal(alternative):
- if isinstance(alternative, int):
- return str(alternative)
- else:
- return "'%s'" % alternative
-
- def response(alternative):
- self.inspect_array([c for c in cases if c.identifier[pos] == alternative],
- next_pending)
-
- expression = '(%s[%d] | 0x20)' % (self.array_variable, pos)
- self.write_selection(expression, alternatives, literal, response)
- else:
- assert len(cases) == 1
- for block_line in cases[0].block:
- self.output_file.write(block_line)
-
- def write_selection(self, expression, alternatives, literal, response):
- if len(alternatives) == 1:
- self.output_file.write(u'if (LIKELY(%s == %s)) {\n' % (expression, literal(alternatives[0])))
- response(alternatives[0])
- self.output_file.write(u'}\n')
- elif len(alternatives) == 2:
- self.output_file.write(u'if (%s == %s) {\n' % (expression, literal(alternatives[0])))
- response(alternatives[0])
- self.output_file.write(u'} else if (LIKELY(%s == %s)) {\n' % (expression, literal(alternatives[1])))
- response(alternatives[1])
- self.output_file.write(u'}\n')
- else:
- self.output_file.write('switch (%s) {\n' % expression)
- for alternative in alternatives:
- self.output_file.write(u'case %s: {\n' % literal(alternative))
- response(alternative)
- self.output_file.write(u'} break;\n')
- self.output_file.write(u'}\n')
-
-
-class LineProcessor(object):
- def process_line(self, line):
- pass
-
-
-class MainLineProcessor(LineProcessor):
- """Processes the contents of an input file."""
- SWITCH_PATTERN = re.compile(r'\s*SWITCH\s*\((\w*),\s*(\w*)\) \{$')
-
- def __init__(self, output_file):
- self.output_file = output_file
-
- def process_line(self, line):
- match_switch = MainLineProcessor.SWITCH_PATTERN.match(line)
- if match_switch:
- array_variable = match_switch.group(1)
- length_variable = match_switch.group(2)
- return SwitchLineProcessor(self, self.output_file, array_variable, length_variable)
- else:
- self.output_file.write(line)
- return self
-
-
-class SwitchLineProcessor(LineProcessor):
- """Processes the contents of a SWITCH block."""
- CASE_PATTERN = re.compile(r'\s*CASE\s*\(\"([a-z0-9_\-\(]*)\"\) \{$')
- CLOSE_BRACE_PATTERN = re.compile(r'\s*\}$')
- EMPTY_PATTERN = re.compile(r'\s*$')
-
- def __init__(self, parent, output_file, array_variable, length_variable):
- self.parent = parent
- self.output_file = output_file
- self.array_variable = array_variable
- self.length_variable = length_variable
- self.cases = []
-
- def process_line(self, line):
- match_case = SwitchLineProcessor.CASE_PATTERN.match(line)
- match_close_brace = SwitchLineProcessor.CLOSE_BRACE_PATTERN.match(line)
- match_empty = SwitchLineProcessor.EMPTY_PATTERN.match(line)
- if match_case:
- identifier = match_case.group(1)
- return CaseLineProcessor(self, self.output_file, identifier)
- elif match_close_brace:
- Optimizer(self.output_file, self.array_variable, self.length_variable).inspect(self.cases)
- return self.parent
- elif match_empty:
- return self
- else:
- raise BadInput('Invalid line within SWITCH: %s' % line)
-
- def add_case(self, latest_case):
- if latest_case.identifier in [c.identifier for c in self.cases]:
- raise BadInput('Repeated case: %s' % latest_case.identifier)
- self.cases.append(latest_case)
-
-
-class CaseLineProcessor(LineProcessor):
- """Processes the contents of a CASE block."""
- CLOSE_BRACE_PATTERN = re.compile(r'\s*\}$')
- BREAK_PATTERN = re.compile(r'break;')
-
- def __init__(self, parent, output_file, identifier):
- self.parent = parent
- self.output_file = output_file
- self.identifier = identifier
- self.block = []
-
- def process_line(self, line):
- match_close_brace = CaseLineProcessor.CLOSE_BRACE_PATTERN.match(line)
- match_break = CaseLineProcessor.BREAK_PATTERN.search(line)
- if match_close_brace:
- self.parent.add_case(SwitchCase(self.identifier, self.block))
- return self.parent
- elif match_break:
- raise BadInput('break within CASE not supported: %s' % line)
- else:
- self.block.append(line)
- return self
-
-
-def process_file(input_name, output_name):
- """Transforms input file into legal C++ source code."""
- with io.open(input_name, 'r', -1, 'utf-8') as input_file:
- with io.open(output_name, 'w', -1, 'utf-8') as output_file:
- processor = MainLineProcessor(output_file)
- input_lines = input_file.readlines()
- for line in input_lines:
- processor = processor.process_line(line)
-
-
-if __name__ == '__main__':
- process_file(sys.argv[1], sys.argv[2])
diff --git a/chromium/third_party/WebKit/Source/core/scripts/make_token_matcher_unittest.py b/chromium/third_party/WebKit/Source/core/scripts/make_token_matcher_unittest.py
deleted file mode 100755
index c0c82863970..00000000000
--- a/chromium/third_party/WebKit/Source/core/scripts/make_token_matcher_unittest.py
+++ /dev/null
@@ -1,243 +0,0 @@
-#!/usr/bin/env python
-# Copyright (C) 2013 Google Inc. All rights reserved.
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions are
-# met:
-#
-# * Redistributions of source code must retain the above copyright
-# notice, this list of conditions and the following disclaimer.
-# * Redistributions in binary form must reproduce the above
-# copyright notice, this list of conditions and the following disclaimer
-# in the documentation and/or other materials provided with the
-# distribution.
-# * Neither the name of Google Inc. nor the names of its
-# contributors may be used to endorse or promote products derived from
-# this software without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-import tempfile
-import unittest
-
-from make_token_matcher import BadInput, CaseLineProcessor, MainLineProcessor, Optimizer, process_file, SwitchCase, SwitchLineProcessor
-
-
-class OptimizerTest(unittest.TestCase):
- def test_nonalphabetic(self):
- optimizer = Optimizer(None, None, None)
- self.assertRaises(
- BadInput,
- optimizer.inspect_array,
- [SwitchCase('-', None), SwitchCase('x', None)],
- [0])
-
-
-class MainLineProcessorTest(unittest.TestCase):
- def test_switch(self):
- processor = MainLineProcessor(None)
- switchLineProcessor = processor.process_line('SWITCH(array, length) {')
- self.assertIsInstance(switchLineProcessor, SwitchLineProcessor)
- self.assertEquals('array', switchLineProcessor.array_variable)
- self.assertEquals('length', switchLineProcessor.length_variable)
-
-
-class SwitchLineProcessorTest(unittest.TestCase):
- def test_case(self):
- processor = SwitchLineProcessor(None, None, None, None)
- caseLineProcessor = processor.process_line('CASE("identifier") {')
- self.assertIsInstance(caseLineProcessor, CaseLineProcessor)
- self.assertEquals('identifier', caseLineProcessor.identifier)
-
- def test_unexpected(self):
- processor = SwitchLineProcessor(None, None, None, None)
- self.assertRaises(
- BadInput,
- processor.process_line,
- 'unexpected')
-
- def test_repeated(self):
- processor = SwitchLineProcessor(None, None, None, None)
- processor.process_line('CASE("x") {').process_line('}')
- caseLineProcessor = processor.process_line('CASE("x") {')
- self.assertRaises(
- BadInput,
- caseLineProcessor.process_line,
- '}')
-
-
-class CaseLineProcessorTest(unittest.TestCase):
- def test_break(self):
- processor = CaseLineProcessor(None, None, None)
- self.assertRaises(
- BadInput,
- processor.process_line,
- 'break;')
-
-
-class ProcessFileTest(unittest.TestCase):
- SOURCE_SMALL = """
- SWITCH(p, q) {
- CASE("a(") {
- X;
- }
- CASE("b(") {
- Y;
- }
- }
- """
-
- EXPECTED_SMALL = """
- if (LIKELY(q == 2)) {
- if (LIKELY(p[1] == '(')) {
- if ((p[0] | 0x20) == 'a') {
- X;
- } else if (LIKELY((p[0] | 0x20) == 'b')) {
- Y;
- }
- }
- }
- """
-
- SOURCE_MEDIUM = """
- SWITCH (p, q) {
- CASE ("ab") {
- X;
- }
- CASE ("cd") {
- Y;
- }
- CASE ("ed") {
- Z;
- }
- }
- """
-
- EXPECTED_MEDIUM = """
- if (LIKELY(q == 2)) {
- if ((p[1] | 0x20) == 'b') {
- if (LIKELY((p[0] | 0x20) == 'a')) {
- X;
- }
- } else if (LIKELY((p[1] | 0x20) == 'd')) {
- if ((p[0] | 0x20) == 'c') {
- Y;
- } else if (LIKELY((p[0] | 0x20) == 'e')) {
- Z;
- }
- }
- }
- """
-
- SOURCE_LARGE = """
- prefix;
- SWITCH(p, q) {
- CASE("hij") {
- R;
- }
- CASE("efg") {
- S;
- }
- CASE("c-") {
- T;
- }
- CASE("klm") {
- U;
- }
-
- CASE("d-") {
- V;
- }
- CASE("a") {
- W;
- X;
- }
- CASE("b-") {
- Y;
- Z;
- }
- }
- suffix;
- """
-
- EXPECTED_LARGE = """
- prefix;
- switch (q) {
- case 1: {
- if (LIKELY((p[0] | 0x20) == 'a')) {
- W;
- X;
- }
- } break;
- case 2: {
- if (LIKELY(p[1] == '-')) {
- switch ((p[0] | 0x20)) {
- case 'b': {
- Y;
- Z;
- } break;
- case 'c': {
- T;
- } break;
- case 'd': {
- V;
- } break;
- }
- }
- } break;
- case 3: {
- switch ((p[0] | 0x20)) {
- case 'e': {
- if (LIKELY((p[1] | 0x20) == 'f' && (p[2] | 0x20) == 'g')) {
- S;
- }
- } break;
- case 'h': {
- if (LIKELY((p[1] | 0x20) == 'i' && (p[2] | 0x20) == 'j')) {
- R;
- }
- } break;
- case 'k': {
- if (LIKELY((p[1] | 0x20) == 'l' && (p[2] | 0x20) == 'm')) {
- U;
- }
- } break;
- }
- } break;
- }
- suffix;
- """
-
- def validate(self, source, expected):
- with tempfile.NamedTemporaryFile() as input_file:
- with tempfile.NamedTemporaryFile() as generated_file:
- input_file.write(source)
- input_file.flush()
- process_file(input_file.name, generated_file.name)
- # Our code generation does not yet implement pretty indentation.
- actual = generated_file.read().replace(' ', '')
- expected = expected.replace(' ', '')
- self.assertEquals(actual, expected)
-
- def test_small(self):
- self.validate(ProcessFileTest.SOURCE_SMALL, ProcessFileTest.EXPECTED_SMALL)
-
- def test_medium(self):
- self.validate(ProcessFileTest.SOURCE_MEDIUM, ProcessFileTest.EXPECTED_MEDIUM)
-
- def test_large(self):
- self.validate(ProcessFileTest.SOURCE_LARGE, ProcessFileTest.EXPECTED_LARGE)
-
-
-if __name__ == "__main__":
- unittest.main()
diff --git a/chromium/third_party/WebKit/Source/core/scripts/name_macros.py b/chromium/third_party/WebKit/Source/core/scripts/name_macros.py
deleted file mode 100644
index 01d36446362..00000000000
--- a/chromium/third_party/WebKit/Source/core/scripts/name_macros.py
+++ /dev/null
@@ -1,175 +0,0 @@
-# Copyright (C) 2013 Google Inc. All rights reserved.
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions are
-# met:
-#
-# * Redistributions of source code must retain the above copyright
-# notice, this list of conditions and the following disclaimer.
-# * Redistributions in binary form must reproduce the above
-# copyright notice, this list of conditions and the following disclaimer
-# in the documentation and/or other materials provided with the
-# distribution.
-# * Neither the name of Google Inc. nor the names of its
-# contributors may be used to endorse or promote products derived from
-# this software without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-import os.path
-import re
-
-import in_generator
-from in_generator import Maker
-import license
-
-
-HEADER_TEMPLATE = """%(license)s
-
-#ifndef %(class_name)sHeaders_h
-#define %(class_name)sHeaders_h
-
-%(includes)s
-
-#endif // %(class_name)sHeaders_h
-"""
-
-
-INTERFACES_HEADER_TEMPLATE = """%(license)s
-
-#ifndef %(class_name)sInterfaces_h
-#define %(class_name)sInterfaces_h
-
-%(declare_conditional_macros)s
-
-#define %(macro_style_name)s_INTERFACES_FOR_EACH(macro) \\
- \\
-%(unconditional_macros)s
- \\
-%(conditional_macros)s
-
-#endif // %(class_name)sInterfaces_h
-"""
-
-
-def _to_macro_style(name):
- s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
- return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).upper()
-
-
-class Writer(in_generator.Writer):
- def __init__(self, in_file_path, enabled_conditions):
- super(Writer, self).__init__(in_file_path, enabled_conditions)
- self.class_name = self.in_file.parameters['namespace'].strip('"')
- self._entries_by_conditional = {}
- self._unconditional_entries = []
- self._sort_entries_by_conditional()
- self._outputs = {(self.class_name + "Headers.h"): self.generate_headers_header,
- (self.class_name + "Interfaces.h"): self.generate_interfaces_header,
- }
-
- def _sort_entries_by_conditional(self):
- unconditional_names = set()
- for entry in self.in_file.name_dictionaries:
- conditional = entry['Conditional']
- if not conditional:
- name = self._class_name_for_entry(entry)
- if name in unconditional_names:
- continue
- unconditional_names.add(name)
- self._unconditional_entries.append(entry)
- continue
- for entry in self.in_file.name_dictionaries:
- name = self._class_name_for_entry(entry)
- if name in unconditional_names:
- continue
- conditional = entry['Conditional']
- if not conditional in self._entries_by_conditional:
- self._entries_by_conditional[conditional] = []
- self._entries_by_conditional[conditional].append(entry)
-
- def _class_name_for_entry(self, entry):
- if entry['ImplementedAs']:
- return entry['ImplementedAs']
- return os.path.basename(entry['name'])
-
- def _headers_header_include_path(self, entry):
- if entry['ImplementedAs']:
- path = os.path.dirname(entry['name'])
- if len(path):
- path += '/'
- path += entry['ImplementedAs']
- else:
- path = entry['name']
- return path + '.h'
-
- def _headers_header_includes(self, entries):
- includes = dict()
- for entry in entries:
- class_name = self._class_name_for_entry(entry)
- # Avoid duplicate includes.
- if class_name in includes:
- continue
- include = '#include "%(path)s"\n#include "V8%(js_name)s.h"' % {
- 'path': self._headers_header_include_path(entry),
- 'js_name': os.path.basename(entry['name']),
- }
- includes[class_name] = self.wrap_with_condition(include, entry['Conditional'])
- return includes.values()
-
- def generate_headers_header(self):
- return HEADER_TEMPLATE % {
- 'license': license.license_for_generated_cpp(),
- 'class_name': self.class_name,
- 'includes': '\n'.join(self._headers_header_includes(self.in_file.name_dictionaries)),
- }
-
- def _declare_one_conditional_macro(self, conditional, entries):
- macro_name = '%(macro_style_name)s_INTERFACES_FOR_EACH_%(conditional)s' % {
- 'macro_style_name': _to_macro_style(self.class_name),
- 'conditional': conditional,
- }
- return self.wrap_with_condition("""#define %(macro_name)s(macro) \\
-%(declarations)s
-
-#else
-#define %(macro_name)s(macro)""" % {
- 'macro_name': macro_name,
- 'declarations': '\n'.join(sorted(set([
- ' macro(%(name)s) \\' % {'name': self._class_name_for_entry(entry)}
- for entry in entries]))),
- }, conditional)
-
- def _declare_conditional_macros(self):
- return '\n'.join([
- self._declare_one_conditional_macro(conditional, entries)
- for conditional, entries in self._entries_by_conditional.items()])
-
- def _unconditional_macro(self, entry):
- return ' macro(%(name)s) \\' % {'name': self._class_name_for_entry(entry)}
-
- def _conditional_macros(self, conditional):
- return ' %(macro_style_name)s_INTERFACES_FOR_EACH_%(conditional)s(macro) \\' % {
- 'macro_style_name': _to_macro_style(self.class_name),
- 'conditional': conditional,
- }
-
- def generate_interfaces_header(self):
- return INTERFACES_HEADER_TEMPLATE % {
- 'license': license.license_for_generated_cpp(),
- 'class_name': self.class_name,
- 'macro_style_name': _to_macro_style(self.class_name),
- 'declare_conditional_macros': self._declare_conditional_macros(),
- 'unconditional_macros': '\n'.join(sorted(set(map(self._unconditional_macro, self._unconditional_entries)))),
- 'conditional_macros': '\n'.join(map(self._conditional_macros, self._entries_by_conditional.keys())),
- }
diff --git a/chromium/third_party/WebKit/Source/core/scripts/name_utilities.py b/chromium/third_party/WebKit/Source/core/scripts/name_utilities.py
deleted file mode 100644
index c4993b0c552..00000000000
--- a/chromium/third_party/WebKit/Source/core/scripts/name_utilities.py
+++ /dev/null
@@ -1,40 +0,0 @@
-# Copyright (C) 2013 Google Inc. All rights reserved.
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions are
-# met:
-#
-# * Redistributions of source code must retain the above copyright
-# notice, this list of conditions and the following disclaimer.
-# * Redistributions in binary form must reproduce the above
-# copyright notice, this list of conditions and the following disclaimer
-# in the documentation and/or other materials provided with the
-# distribution.
-# * Neither the name of Google Inc. nor the names of its
-# contributors may be used to endorse or promote products derived from
-# this software without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-ACRONYMS = ['CSS', 'HTML', 'IME', 'JS', 'SVG', 'URL', 'WOFF', 'XML', 'XSLT']
-
-
-def lower_first(name):
- """Return name with first letter or initial acronym lowercased.
-
- E.g., 'SetURL' becomes 'setURL', but 'URLFoo' becomes 'urlFoo'.
- """
- for acronym in ACRONYMS:
- if name.startswith(acronym):
- return name.replace(acronym, acronym.lower())
- return name[0].lower() + name[1:]
diff --git a/chromium/third_party/WebKit/Source/core/scripts/preprocessor.pm b/chromium/third_party/WebKit/Source/core/scripts/preprocessor.pm
deleted file mode 100644
index 95995f00af0..00000000000
--- a/chromium/third_party/WebKit/Source/core/scripts/preprocessor.pm
+++ /dev/null
@@ -1,89 +0,0 @@
-#
-# Copyright (C) 2005 Nikolas Zimmermann <wildfox@kde.org>
-# Copyright (C) 2011 Google Inc.
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Library General Public
-# License as published by the Free Software Foundation; either
-# version 2 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Library General Public License for more details.
-#
-# You should have received a copy of the GNU Library General Public License
-# along with this library; see the file COPYING.LIB. If not, write to
-# the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
-# Boston, MA 02110-1301, USA.
-#
-
-use strict;
-use warnings;
-
-use Config;
-use IPC::Open2;
-use IPC::Open3;
-
-BEGIN {
- use Exporter ();
- our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
- $VERSION = 1.00;
- @ISA = qw(Exporter);
- @EXPORT = qw(&applyPreprocessor);
- %EXPORT_TAGS = ( );
- @EXPORT_OK = ();
-}
-
-# Returns an array of lines.
-sub applyPreprocessor
-{
- my $fileName = shift;
- my $defines = shift;
- my $preprocessor = shift;
-
- my @args = ();
- if (!$preprocessor) {
- require Config;
- if ($ENV{CC}) {
- $preprocessor = $ENV{CC};
- } elsif (($Config::Config{'osname'}) =~ /solaris/i) {
- $preprocessor = "/usr/sfw/bin/gcc";
- } else {
- $preprocessor = "/usr/bin/gcc";
- }
- push(@args, qw(-E -P -x c++));
- }
-
- # Remove double quotations from $defines and extract macros.
- # For example, if $defines is ' "A=1" "B=1" C=1 "" D ',
- # then it is converted into four macros -DA=1, -DB=1, -DC=1 and -DD.
- $defines =~ s/\"//g;
- my @macros = grep { $_ } split(/\s+/, $defines); # grep skips empty macros.
- @macros = map { "-D$_" } @macros;
-
- my $pid = 0;
- if ($Config{osname} eq "cygwin" || $Config{osname} eq 'MSWin32') {
- # This call can fail if Windows rebases cygwin, so retry a few times until it succeeds.
- for (my $tries = 0; !$pid && ($tries < 20); $tries++) {
- eval {
- # Suppress STDERR so that if we're using cl.exe, the output
- # name isn't needlessly echoed.
- use Symbol 'gensym'; my $err = gensym;
- $pid = open3(\*PP_IN, \*PP_OUT, $err, split(' ', $preprocessor), @args, @macros, $fileName);
- 1;
- } or do {
- sleep 1;
- }
- };
- } else {
- $pid = open2(\*PP_OUT, \*PP_IN, split(' ', $preprocessor), @args, @macros, $fileName);
- }
- close PP_IN;
- my @documentContent = <PP_OUT>;
- close PP_OUT;
- waitpid($pid, 0);
- return @documentContent;
-}
-
-1;
diff --git a/chromium/third_party/WebKit/Source/core/scripts/rule_bison.py b/chromium/third_party/WebKit/Source/core/scripts/rule_bison.py
deleted file mode 100644
index 97a0541f4b5..00000000000
--- a/chromium/third_party/WebKit/Source/core/scripts/rule_bison.py
+++ /dev/null
@@ -1,105 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright (C) 2009 Google Inc. All rights reserved.
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions are
-# met:
-#
-# * Redistributions of source code must retain the above copyright
-# notice, this list of conditions and the following disclaimer.
-# * Redistributions in binary form must reproduce the above
-# copyright notice, this list of conditions and the following disclaimer
-# in the documentation and/or other materials provided with the
-# distribution.
-# * Neither the name of Google Inc. nor the names of its
-# contributors may be used to endorse or promote products derived from
-# this software without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-#
-# Copyright (c) 2009 The Chromium Authors. All rights reserved.
-# Use of this source code is governed by a BSD-style license that can be
-# found in the LICENSE file.
-
-# usage: rule_bison.py INPUT_FILE OUTPUT_DIR [BISON_EXE]
-# INPUT_FILE is a path to either CSSGrammar.y or XPathGrammar.y.
-# OUTPUT_DIR is where the bison-generated .cpp and .h files should be placed.
-
-import errno
-import os
-import os.path
-import subprocess
-import sys
-
-assert len(sys.argv) == 3 or len(sys.argv) == 4
-
-inputFile = sys.argv[1]
-outputDir = sys.argv[2]
-bisonExe = 'bison'
-if len(sys.argv) > 3:
- bisonExe = sys.argv[3]
-
-inputName = os.path.basename(inputFile)
-assert inputName == 'CSSGrammar.y' or inputName == 'XPathGrammar.y'
-prefix = {'CSSGrammar.y': 'cssyy', 'XPathGrammar.y': 'xpathyy'}[inputName]
-
-(inputRoot, inputExt) = os.path.splitext(inputName)
-
-# The generated .h will be in a different location depending on the bison
-# version.
-outputHTries = [
- os.path.join(outputDir, inputRoot + '.cpp.h'),
- os.path.join(outputDir, inputRoot + '.hpp'),
-]
-
-for outputHTry in outputHTries:
- try:
- os.unlink(outputHTry)
- except OSError, e:
- if e.errno != errno.ENOENT:
- raise
-
-outputCpp = os.path.join(outputDir, inputRoot + '.cpp')
-
-returnCode = subprocess.call([bisonExe, '-d', '-p', prefix, inputFile, '-o', outputCpp])
-assert returnCode == 0
-
-# Find the name that bison used for the generated header file.
-outputHTmp = None
-for outputHTry in outputHTries:
- try:
- os.stat(outputHTry)
- outputHTmp = outputHTry
- break
- except OSError, e:
- if e.errno != errno.ENOENT:
- raise
-
-assert outputHTmp != None
-
-# Read the header file in under the generated name and remove it.
-outputHFile = open(outputHTmp)
-outputHContents = outputHFile.read()
-outputHFile.close()
-os.unlink(outputHTmp)
-
-# Rewrite the generated header with #include guards.
-outputH = os.path.join(outputDir, inputRoot + '.h')
-
-outputHFile = open(outputH, 'w')
-print >>outputHFile, '#ifndef %sH' % inputRoot
-print >>outputHFile, '#define %sH' % inputRoot
-print >>outputHFile, outputHContents
-print >>outputHFile, '#endif'
-outputHFile.close()
diff --git a/chromium/third_party/WebKit/Source/core/scripts/template_expander.py b/chromium/third_party/WebKit/Source/core/scripts/template_expander.py
deleted file mode 100644
index b1e99b671fd..00000000000
--- a/chromium/third_party/WebKit/Source/core/scripts/template_expander.py
+++ /dev/null
@@ -1,54 +0,0 @@
-# Copyright (C) 2013 Google Inc. All rights reserved.
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions are
-# met:
-#
-# * Redistributions of source code must retain the above copyright
-# notice, this list of conditions and the following disclaimer.
-# * Redistributions in binary form must reproduce the above
-# copyright notice, this list of conditions and the following disclaimer
-# in the documentation and/or other materials provided with the
-# distribution.
-# * Neither the name of Google Inc. nor the names of its
-# contributors may be used to endorse or promote products derived from
-# this software without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-import os
-import sys
-
-_current_dir = os.path.dirname(os.path.realpath(__file__))
-# jinja2 is in chromium's third_party directory
-# Insert at front to override system libraries, and after path[0] == script dir
-sys.path.insert(1, os.path.join(_current_dir, *([os.pardir] * 4)))
-import jinja2
-
-
-def apply_template(path_to_template, params):
- dirname, basename = os.path.split(path_to_template)
- path_to_templates = os.path.join(_current_dir, "templates")
- jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader([dirname, path_to_templates]), keep_trailing_newline=True)
- template = jinja_env.get_template(basename)
- return template.render(params)
-
-
-def use_jinja(template_file_name):
- def real_decorator(generator):
- def generator_internal(*args, **kwargs):
- parameters = generator(*args, **kwargs)
- return apply_template(template_file_name, parameters)
- generator_internal.func_name = generator.func_name
- return generator_internal
- return real_decorator
diff --git a/chromium/third_party/WebKit/Source/core/scripts/templates/InternalRuntimeFlags.h.tmpl b/chromium/third_party/WebKit/Source/core/scripts/templates/InternalRuntimeFlags.h.tmpl
deleted file mode 100644
index c2d1a36836b..00000000000
--- a/chromium/third_party/WebKit/Source/core/scripts/templates/InternalRuntimeFlags.h.tmpl
+++ /dev/null
@@ -1,39 +0,0 @@
-{% from "macros.tmpl" import wrap_with_condition, license -%}
-{{ license() }}
-
-#ifndef InternalRuntimeFlags_h
-#define InternalRuntimeFlags_h
-
-#include "RuntimeEnabledFeatures.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefPtr.h"
-#include "wtf/RefCounted.h"
-
-namespace WebCore {
-
-class InternalRuntimeFlags : public RefCounted<InternalRuntimeFlags> {
-public:
- static PassRefPtr<InternalRuntimeFlags> create()
- {
- return adoptRef(new InternalRuntimeFlags);
- }
-
-{#-
- Setting after startup does not work for most runtime flags, but we
- could add an option to print setters for ones which do:
- void set{{feature.name}}Enabled(bool isEnabled) { RuntimeEnabledFeatures::set{{feature.name}}Enabled(isEnabled); }
- If we do that, we also need to respect Internals::resetToConsistentState.
-#}
-{% for feature in features if not feature.custom %}
-{%- call wrap_with_condition(feature.condition) %}
- bool {{feature.first_lowered_name}}Enabled() { return RuntimeEnabledFeatures::{{feature.first_lowered_name}}Enabled(); }
-{%- endcall %}
-{% endfor %}
-
-private:
- InternalRuntimeFlags() { }
-};
-
-} // namespace WebCore
-
-#endif // InternalRuntimeFlags_h
diff --git a/chromium/third_party/WebKit/Source/core/scripts/templates/InternalRuntimeFlags.idl.tmpl b/chromium/third_party/WebKit/Source/core/scripts/templates/InternalRuntimeFlags.idl.tmpl
deleted file mode 100644
index 92838f258a5..00000000000
--- a/chromium/third_party/WebKit/Source/core/scripts/templates/InternalRuntimeFlags.idl.tmpl
+++ /dev/null
@@ -1,14 +0,0 @@
-{% from "macros.tmpl" import license -%}
-{{ license() }}
-
-[
-] interface InternalRuntimeFlags {
-{%- for feature in features if not feature.custom %}
-{#-
- Currently assuming that runtime flags cannot be changed after startup
- it's possible that some can be and should be conditionally readonly.
-#}
- {% if feature.condition -%} [Conditional={{feature.condition}}] {% endif -%}
- readonly attribute boolean {{feature.first_lowered_name}}Enabled;
-{%- endfor %}
-};
diff --git a/chromium/third_party/WebKit/Source/core/scripts/templates/RuntimeEnabledFeatures.cpp.tmpl b/chromium/third_party/WebKit/Source/core/scripts/templates/RuntimeEnabledFeatures.cpp.tmpl
deleted file mode 100644
index 9de600f0eee..00000000000
--- a/chromium/third_party/WebKit/Source/core/scripts/templates/RuntimeEnabledFeatures.cpp.tmpl
+++ /dev/null
@@ -1,24 +0,0 @@
-{% from "macros.tmpl" import wrap_with_condition, license -%}
-{{ license() }}
-
-#include "config.h"
-#include "RuntimeEnabledFeatures.h"
-
-namespace WebCore {
-
-{% for feature_set in feature_sets %}
-void RuntimeEnabledFeatures::set{{feature_set|capitalize}}FeaturesEnabled(bool enable)
-{
-{%- for feature in features if feature.status == feature_set %}
- set{{feature.name}}Enabled(enable);
-{%- endfor %}
-}
-{% endfor %}
-
-{%- for feature in features if not feature.custom %}
-{%- call wrap_with_condition(feature.condition) %}
-bool RuntimeEnabledFeatures::is{{feature.name}}Enabled = false;
-{%- endcall %}
-{%- endfor %}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/scripts/templates/RuntimeEnabledFeatures.h.tmpl b/chromium/third_party/WebKit/Source/core/scripts/templates/RuntimeEnabledFeatures.h.tmpl
deleted file mode 100644
index e9eab83557d..00000000000
--- a/chromium/third_party/WebKit/Source/core/scripts/templates/RuntimeEnabledFeatures.h.tmpl
+++ /dev/null
@@ -1,47 +0,0 @@
-{% from "macros.tmpl" import wrap_with_condition, license -%}
-{{ license() }}
-
-#ifndef RuntimeEnabledFeatures_h
-#define RuntimeEnabledFeatures_h
-
-namespace WebCore {
-
-// A class that stores static enablers for all experimental features.
-
-class RuntimeEnabledFeatures {
-public:
-
-{%- for feature_set in feature_sets %}
- static void set{{feature_set|capitalize}}FeaturesEnabled(bool);
-{%- endfor %}
-
-{% for feature in features %}
-{%- if feature.custom %}
- static bool {{feature.first_lowered_name}}Enabled();
-{%- else %}
-{%- if feature.condition %}
-#if ENABLE({{feature.condition}})
-{%- endif %}
- static void set{{feature.name}}Enabled(bool isEnabled) { is{{feature.name}}Enabled = isEnabled; }
- static bool {{feature.first_lowered_name}}Enabled() { return {{feature.enabled_condition}}; }
-{%- if feature.condition %}
-#else
- static void set{{feature.name}}Enabled(bool) { }
- static bool {{feature.first_lowered_name}}Enabled() { return false; }
-#endif
-{%- endif %}
-{%- endif %}
-{% endfor %}
-
-private:
- RuntimeEnabledFeatures() { }
-{% for feature in features if not feature.custom %}
-{%- call wrap_with_condition(feature.condition) %}
- static bool is{{feature.name}}Enabled;
-{%- endcall %}
-{%- endfor %}
-};
-
-} // namespace WebCore
-
-#endif // RuntimeEnabledFeatures_h
diff --git a/chromium/third_party/WebKit/Source/core/scripts/templates/StyleBuilder.cpp.tmpl b/chromium/third_party/WebKit/Source/core/scripts/templates/StyleBuilder.cpp.tmpl
deleted file mode 100644
index 94b468d233c..00000000000
--- a/chromium/third_party/WebKit/Source/core/scripts/templates/StyleBuilder.cpp.tmpl
+++ /dev/null
@@ -1,85 +0,0 @@
-{% from "macros.tmpl" import wrap_with_condition, license -%}
-{{ license() }}
-
-#include "config.h"
-#include "core/css/resolver/StyleBuilder.h"
-
-#include "StyleBuilderFunctions.h"
-#include "core/css/CSSPrimitiveValueMappings.h"
-#include "core/css/resolver/StyleResolverState.h"
-
-// FIXME: currently we're just generating a switch statement, but we should
-// test other variations for performance once we have more properties here.
-
-{%- macro set_value(property) %}
-{%- if property.svg -%}
- state.style()->accessSVGStyle()->{{property.setter}}
-{%- else -%}
- state.style()->{{property.setter}}
-{%- endif %}
-{%- endmacro %}
-
-namespace WebCore {
-
-{%- for property_id, property in properties.items() if not property.use_handlers_for %}
-{%- call wrap_with_condition(property.condition) %}
-{%- set apply_type = property.apply_type %}
-
-{%- if not property.custom_initial %}
-void StyleBuilderFunctions::applyInitial{{property_id}}(StyleResolverState& state)
-{
-{%- if property.svg %}
- {{ set_value(property) }}(SVGRenderStyle::{{property.initial}}());
-{%- else %}
- {{ set_value(property) }}(RenderStyle::{{property.initial}}());
-{%- endif %}
-}
-{% endif %}
-
-{%- if not property.custom_inherit %}
-void StyleBuilderFunctions::applyInherit{{property_id}}(StyleResolverState& state)
-{
-{%- if property.svg %}
- {{ set_value(property) }}(state.parentStyle()->svgStyle()->{{property.getter}}());
-{%- else %}
- {{ set_value(property) }}(state.parentStyle()->{{property.getter}}());
-{%- endif %}
-}
-{% endif %}
-
-{%- if not property.custom_value %}
-void StyleBuilderFunctions::applyValue{{property_id}}(StyleResolverState& state, CSSValue* value)
-{
-{%- if property.converter %}
- {{ set_value(property) }}(StyleBuilderConverter::{{property.converter}}(state, value));
-{%- else %}
- {{ set_value(property) }}(static_cast<{{property.type_name}}>(*toCSSPrimitiveValue(value)));
-{%- endif %}
-}
-{% endif %}
-
-{%- endcall %}
-{%- endfor %}
-
-bool StyleBuilder::applyProperty(CSSPropertyID property, StyleResolverState& state, CSSValue* value, bool isInitial, bool isInherit) {
- switch(property) {
-{%- for property_id, property in properties.items() %}
-{%- set used_property = properties[property.use_handlers_for] or property %}
-{%- set used_property_id = used_property.property_id %}
-{%- call wrap_with_condition(used_property.condition) %}
- case {{ property_id }}:
- if (isInitial)
- StyleBuilderFunctions::applyInitial{{ used_property_id }}(state);
- else if (isInherit)
- StyleBuilderFunctions::applyInherit{{ used_property_id }}(state);
- else
- StyleBuilderFunctions::applyValue{{ used_property_id }}(state, value);
- return true;
-{%- endcall %}
-{% endfor %}
- default:
- return false;
- }
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/scripts/templates/StyleBuilderFunctions.cpp.tmpl b/chromium/third_party/WebKit/Source/core/scripts/templates/StyleBuilderFunctions.cpp.tmpl
deleted file mode 100644
index 4be798fba3b..00000000000
--- a/chromium/third_party/WebKit/Source/core/scripts/templates/StyleBuilderFunctions.cpp.tmpl
+++ /dev/null
@@ -1,519 +0,0 @@
-{% from "macros.tmpl" import lower_first -%}
-
-{#
- This file is for property handlers which use the templating engine to
- reduce (handwritten) code duplication.
-
- The `properties' dict can be used to access a property's parameters in
- jinja2 templates (i.e. setter, getter, initial, type_name)
--#}
-
-#include "config.h"
-#include "StyleBuilderFunctions.h"
-
-#include "CSSValueKeywords.h"
-#include "core/css/BasicShapeFunctions.h"
-#include "core/css/CSSPrimitiveValueMappings.h"
-#include "core/css/Pair.h"
-#include "core/css/resolver/StyleResolverState.h"
-#include "core/platform/animation/CSSAnimationDataList.h"
-
-
-{%- macro declare_initial_function(property_id) -%}
-void StyleBuilderFunctions::applyInitial{{property_id}}(StyleResolverState& state)
-{%- endmacro %}
-
-{%- macro declare_inherit_function(property_id) -%}
-void StyleBuilderFunctions::applyInherit{{property_id}}(StyleResolverState& state)
-{%- endmacro %}
-
-{%- macro declare_value_function(property_id) -%}
-void StyleBuilderFunctions::applyValue{{property_id}}(StyleResolverState& state, CSSValue* value)
-{%- endmacro %}
-
-// FIXME: This is duplicated in StyleBuilder.cpp.tmpl, but we'll move the
-// function definitions there over to here later.
-{%- macro set_value(property) %}
-{%- if property.svg -%}
- state.style()->accessSVGStyle()->{{property.setter}}
-{%- else -%}
- state.style()->{{property.setter}}
-{%- endif -%}
-{%- endmacro %}
-
-namespace WebCore {
-
-{%- macro apply_animation(property_id, attribute, animation) %}
-{{ declare_initial_function(property_id) }}
-{
- CSSAnimationDataList* list = state.style()->access{{animation}}();
- if (list->isEmpty())
- list->append(CSSAnimationData::create());
- list->animation(0)->set{{attribute}}(CSSAnimationData::initialAnimation{{attribute}}());
- {%- if property_id == "CSSPropertyWebkitTransitionProperty" %}
- list->animation(0)->setAnimationMode(CSSAnimationData::AnimateAll);
- {%- endif %}
- for (size_t i = 1; i < list->size(); ++i)
- list->animation(i)->clear{{attribute}}();
-}
-
-{{ declare_inherit_function(property_id) }}
-{
- CSSAnimationDataList* list = state.style()->access{{animation}}();
- const CSSAnimationDataList* parentList = state.parentStyle()->{{animation|lower}}();
- size_t i = 0, parentSize = parentList ? parentList->size() : 0;
- for ( ; i < parentSize && parentList->animation(i)->is{{attribute}}Set(); ++i) {
- ASSERT(list->size() >= i);
- if (list->size() == i)
- list->append(CSSAnimationData::create());
- list->animation(i)->set{{attribute}}(parentList->animation(i)->{{lower_first(attribute)}}());
- list->animation(i)->setAnimationMode(parentList->animation(i)->animationMode());
- }
-
- // Reset any remaining animations to not have the property set.
- for ( ; i < list->size(); ++i)
- list->animation(i)->clear{{attribute}}();
-}
-
-{{ declare_value_function(property_id) }}
-{
- CSSAnimationDataList* list = state.style()->access{{animation}}();
- size_t childIndex = 0;
- if (value->isValueList()) {
- // Walk each value and put it into an animation, creating new animations as needed.
- for (CSSValueListIterator i = value; i.hasMore(); i.advance()) {
- ASSERT(list->size() >= childIndex);
- if (list->size() == childIndex)
- list->append(CSSAnimationData::create());
- state.styleMap().mapAnimation{{attribute}}(list->animation(childIndex), i.value());
- ++childIndex;
- }
- } else {
- if (list->isEmpty())
- list->append(CSSAnimationData::create());
- state.styleMap().mapAnimation{{attribute}}(list->animation(childIndex), value);
- childIndex = 1;
- }
- for ( ; childIndex < list->size(); ++childIndex) {
- // Reset all remaining animations to not have the property set.
- list->animation(childIndex)->clear{{attribute}}();
- }
-}
-{%- endmacro %}
-
-{{ apply_animation("CSSPropertyWebkitAnimationDelay", "Delay", "Animations") }}
-{{ apply_animation("CSSPropertyWebkitAnimationDirection", "Direction", "Animations") }}
-{{ apply_animation("CSSPropertyWebkitAnimationDuration", "Duration", "Animations") }}
-{{ apply_animation("CSSPropertyWebkitAnimationFillMode", "FillMode", "Animations") }}
-{{ apply_animation("CSSPropertyWebkitAnimationIterationCount", "IterationCount", "Animations") }}
-{{ apply_animation("CSSPropertyWebkitAnimationName", "Name", "Animations") }}
-{{ apply_animation("CSSPropertyWebkitAnimationPlayState", "PlayState", "Animations") }}
-{{ apply_animation("CSSPropertyWebkitAnimationTimingFunction", "TimingFunction", "Animations") }}
-{{ apply_animation("CSSPropertyWebkitTransitionDelay", "Delay", "Transitions") }}
-{{ apply_animation("CSSPropertyWebkitTransitionDuration", "Duration", "Transitions") }}
-{{ apply_animation("CSSPropertyWebkitTransitionProperty", "Property", "Transitions") }}
-{{ apply_animation("CSSPropertyWebkitTransitionTimingFunction", "TimingFunction", "Transitions") }}
-
-{%- macro apply_auto(property_id, auto_getter=none, auto_setter=none, auto_identity="CSSValueAuto", compute_length=false) %}
-{%- set property = properties[property_id] %}
-{%- set auto_getter = auto_getter or "hasAuto" + property.camel_case_name %}
-{%- set auto_setter = auto_setter or "setHasAuto" + property.camel_case_name %}
-{{ declare_initial_function(property_id) }}
-{
- state.style()->{{auto_setter}}();
-}
-
-{{ declare_inherit_function(property_id) }}
-{
- if (state.parentStyle()->{{auto_getter}}())
- state.style()->{{auto_setter}}();
- else
- {{ set_value(property) }}(state.parentStyle()->{{property.getter}}());
-}
-
-{{ declare_value_function(property_id) }}
-{
- if (!value->isPrimitiveValue())
- return;
-
- CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
- if (primitiveValue->getValueID() == {{auto_identity}})
- state.style()->{{auto_setter}}();
- else
- {%- if compute_length %}
- {{ set_value(property) }}(primitiveValue->computeLength<{{property.type_name}}>(state.style(), state.rootElementStyle(), state.style()->effectiveZoom()));
- {%- else %}
- {{ set_value(property) }}(*primitiveValue);
- {%- endif %}
-}
-{%- endmacro %}
-
-{{ apply_auto("CSSPropertyOrphans") }}
-{{ apply_auto("CSSPropertyWebkitColumnCount") }}
-{{ apply_auto("CSSPropertyWebkitColumnGap", auto_getter="hasNormalColumnGap", auto_setter="setHasNormalColumnGap", auto_identity="CSSValueNormal", compute_length=true) }}
-{{ apply_auto("CSSPropertyWebkitColumnWidth", compute_length=true) }}
-{{ apply_auto("CSSPropertyWidows") }}
-{{ apply_auto("CSSPropertyZIndex") }}
-
-{%- macro apply_value_border_image(property_id) %}
-{{ declare_value_function(property_id) }}
-{
- {%- set property = properties[property_id] %}
- NinePieceImage image;
- {%- if property_id == "CSSPropertyWebkitMaskBoxImage" %}
- image.setMaskDefaults();
- {%- endif %}
- state.styleMap().mapNinePieceImage(state.style(), {{property_id}}, value, image);
- {{ set_value(property) }}(image);
-}
-{%- endmacro %}
-
-{{ apply_value_border_image("CSSPropertyWebkitBorderImage") }}
-{{ apply_value_border_image("CSSPropertyWebkitMaskBoxImage") }}
-
-{%- macro apply_border_image_modifier(property_id, modifier_type) %}
-{%- set is_mask_box = "MaskBox" in property_id %}
-{%- set getter = "maskBoxImage" if is_mask_box else "borderImage" %}
-{%- set setter = "setMaskBoxImage" if is_mask_box else "setBorderImage" %}
-{{ declare_initial_function(property_id) }}
-{
- NinePieceImage image(state.style()->{{getter}}());
- {%- if modifier_type == "Outset" %}
- image.setOutset(LengthBox(0));
- {%- elif modifier_type == "Repeat" %}
- image.setHorizontalRule(StretchImageRule);
- image.setVerticalRule(StretchImageRule);
- {%- elif modifier_type == "Slice" %}
- // Masks have a different initial value for slices. Preserve the value of 0 for backwards compatibility.
- image.setImageSlices(LengthBox({{ (["Length(100, Percent)"]*4) | join(", ") if not is_mask_box }}));
- image.setFill(false);
- {%- elif modifier_type == "Width" %}
- // Masks have a different initial value for widths. Preserve the value of 0 for backwards compatibility.
- image.setBorderSlices(LengthBox({{ (["Length(1, Relative)"]*4) | join(", ") if not is_mask_box }}));
- {%- endif %}
- state.style()->{{setter}}(image);
-}
-
-{{ declare_inherit_function(property_id) }}
-{
- NinePieceImage image(state.style()->{{getter}}());
- {%- if modifier_type == "Outset" %}
- image.copyOutsetFrom(state.parentStyle()->{{getter}}());
- {%- elif modifier_type == "Repeat" %}
- image.copyRepeatFrom(state.parentStyle()->{{getter}}());
- {%- elif modifier_type == "Slice" %}
- image.copyImageSlicesFrom(state.parentStyle()->{{getter}}());
- {%- elif modifier_type == "Width" %}
- image.copyBorderSlicesFrom(state.parentStyle()->{{getter}}());
- {%- endif %}
- state.style()->{{setter}}(image);
-}
-
-{{ declare_value_function(property_id) }}
-{
- NinePieceImage image(state.style()->{{getter}}());
- {%- if modifier_type == "Outset" %}
- image.setOutset(state.styleMap().mapNinePieceImageQuad(value));
- {%- elif modifier_type == "Repeat" %}
- state.styleMap().mapNinePieceImageRepeat(value, image);
- {%- elif modifier_type == "Slice" %}
- state.styleMap().mapNinePieceImageSlice(value, image);
- {%- elif modifier_type == "Width" %}
- image.setBorderSlices(state.styleMap().mapNinePieceImageQuad(value));
- {%- endif %}
- state.style()->{{setter}}(image);
-}
-{%- endmacro %}
-
-{{ apply_border_image_modifier("CSSPropertyBorderImageOutset", "Outset") }}
-{{ apply_border_image_modifier("CSSPropertyBorderImageRepeat", "Repeat") }}
-{{ apply_border_image_modifier("CSSPropertyBorderImageSlice", "Slice") }}
-{{ apply_border_image_modifier("CSSPropertyBorderImageWidth", "Width") }}
-{{ apply_border_image_modifier("CSSPropertyWebkitMaskBoxImageOutset", "Outset") }}
-{{ apply_border_image_modifier("CSSPropertyWebkitMaskBoxImageRepeat", "Repeat") }}
-{{ apply_border_image_modifier("CSSPropertyWebkitMaskBoxImageSlice", "Slice") }}
-{{ apply_border_image_modifier("CSSPropertyWebkitMaskBoxImageWidth", "Width") }}
-
-{%- macro apply_value_border_image_source(property_id) %}
-{{ declare_value_function(property_id) }}
-{
- {%- set property = properties[property_id] %}
- {{ set_value(property) }}(state.styleImage({{property_id}}, value));
-}
-{%- endmacro %}
-
-{{ apply_value_border_image_source("CSSPropertyBorderImageSource") }}
-{{ apply_value_border_image_source("CSSPropertyWebkitMaskBoxImageSource") }}
-
-{%- macro apply_color(property_id, default_getter="color", initial_color=none, inherit_color=false) %}
-{%- set property = properties[property_id] %}
-{%- set visited_link_setter = "setVisitedLink" + property.camel_case_name %}
-{{ declare_initial_function(property_id) }}
-{
- Color color = {{ initial_color or "Color" -}}();
- if (state.applyPropertyToRegularStyle())
- {{ set_value(property) }}(color);
- if (state.applyPropertyToVisitedLinkStyle())
- state.style()->{{visited_link_setter}}(color);
-}
-
-{{ declare_inherit_function(property_id) }}
-{
- // Visited link style can never explicitly inherit from parent visited link style so no separate getters are needed.
- Color color = state.parentStyle()->{{property.getter}}();
- if (!color.isValid())
- color = state.parentStyle()->{{default_getter}}();
- if (state.applyPropertyToRegularStyle())
- {{ set_value(property) }}(color);
- if (state.applyPropertyToVisitedLinkStyle())
- state.style()->{{visited_link_setter}}(color);
-}
-
-{{ declare_value_function(property_id) }}
-{
- if (!value->isPrimitiveValue())
- return;
-
- CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
-
-{%- if inherit_color %}
- if (primitiveValue->getValueID() == CSSValueCurrentcolor) {
- applyInherit{{property_id}}(state);
- return;
- }
-{%- endif %}
-
- if (state.applyPropertyToRegularStyle())
- {{ set_value(property) }}(state.document().textLinkColors().colorFromPrimitiveValue(primitiveValue, state.style()->visitedDependentColor(CSSPropertyColor)));
- if (state.applyPropertyToVisitedLinkStyle())
- state.style()->{{visited_link_setter}}(state.document().textLinkColors().colorFromPrimitiveValue(primitiveValue, state.style()->visitedDependentColor(CSSPropertyColor), state.element()->isLink() /* forVisitedLink */));
-}
-{%- endmacro %}
-
-{{ apply_color("CSSPropertyBackgroundColor", default_getter="invalidColor") }}
-{{ apply_color("CSSPropertyBorderBottomColor") }}
-{{ apply_color("CSSPropertyBorderLeftColor") }}
-{{ apply_color("CSSPropertyBorderRightColor") }}
-{{ apply_color("CSSPropertyBorderTopColor") }}
-{{ apply_color("CSSPropertyColor", inherit_color=true, default_getter="invalidColor", initial_color="RenderStyle::initialColor") }}
-{{ apply_color("CSSPropertyOutlineColor") }}
-{{ apply_color("CSSPropertyTextDecorationColor") }}
-{{ apply_color("CSSPropertyWebkitColumnRuleColor") }}
-{{ apply_color("CSSPropertyWebkitTextEmphasisColor") }}
-{{ apply_color("CSSPropertyWebkitTextFillColor") }}
-{{ apply_color("CSSPropertyWebkitTextStrokeColor") }}
-
-{%- macro apply_counter(property_id, action) %}
-{%- set property = properties[property_id] %}
-{{ declare_initial_function(property_id) }} { }
-
-{{ declare_inherit_function(property_id) }}
-{
- CounterDirectiveMap& map = state.style()->accessCounterDirectives();
- CounterDirectiveMap& parentMap = state.parentStyle()->accessCounterDirectives();
-
- typedef CounterDirectiveMap::iterator Iterator;
- Iterator end = parentMap.end();
- for (Iterator it = parentMap.begin(); it != end; ++it) {
- CounterDirectives& directives = map.add(it->key, CounterDirectives()).iterator->value;
- directives.inherit{{action}}(it->value);
- }
-}
-
-{{ declare_value_function(property_id) }}
-{
- if (!value->isValueList())
- return;
-
- CSSValueList* list = toCSSValueList(value);
-
- CounterDirectiveMap& map = state.style()->accessCounterDirectives();
- typedef CounterDirectiveMap::iterator Iterator;
-
- Iterator end = map.end();
- for (Iterator it = map.begin(); it != end; ++it)
- it->value.clear{{action}}();
-
- int length = list ? list->length() : 0;
- for (int i = 0; i < length; ++i) {
- CSSValue* currValue = list->itemWithoutBoundsCheck(i);
- if (!currValue->isPrimitiveValue())
- continue;
-
- Pair* pair = toCSSPrimitiveValue(currValue)->getPairValue();
- if (!pair || !pair->first() || !pair->second())
- continue;
-
- AtomicString identifier = pair->first()->getStringValue();
- int value = pair->second()->getIntValue();
- CounterDirectives& directives = map.add(identifier, CounterDirectives()).iterator->value;
- {%- if action == "Reset" %}
- directives.setResetValue(value);
- {%- else %}
- directives.addIncrementValue(value);
- {%- endif %}
- }
-}
-{%- endmacro %}
-
-{{ apply_counter("CSSPropertyCounterIncrement", "Increment") }}
-{{ apply_counter("CSSPropertyCounterReset", "Reset") }}
-
-{%- macro apply_fill_layer(property_id, fill_type) %}
-{%- set layer_type = "Background" if "Background" in property_id else "Mask" %}
-{%- set fill_layer_type = layer_type + "FillLayer" %}
-{%- set access_layers = "access" + layer_type + "Layers" %}
-{%- set map_fill = "mapFill" + fill_type %}
-{{ declare_initial_function(property_id) }}
-{
- FillLayer* currChild = state.style()->{{access_layers}}();
- currChild->set{{fill_type}}(FillLayer::initialFill{{fill_type}}({{fill_layer_type}}));
- for (currChild = currChild->next(); currChild; currChild = currChild->next())
- currChild->clear{{fill_type}}();
-}
-
-{{ declare_inherit_function(property_id) }}
-{
- FillLayer* currChild = state.style()->{{access_layers}}();
- FillLayer* prevChild = 0;
- const FillLayer* currParent = state.parentStyle()->{{layer_type|lower}}Layers();
- while (currParent && currParent->is{{fill_type}}Set()) {
- if (!currChild) {
- /* Need to make a new layer.*/
- currChild = new FillLayer({{fill_layer_type}});
- prevChild->setNext(currChild);
- }
- currChild->set{{fill_type}}(currParent->{{lower_first(fill_type)}}());
- prevChild = currChild;
- currChild = prevChild->next();
- currParent = currParent->next();
- }
-
- while (currChild) {
- /* Reset any remaining layers to not have the property set. */
- currChild->clear{{fill_type}}();
- currChild = currChild->next();
- }
-}
-
-{{ declare_value_function(property_id) }}
-{
- FillLayer* currChild = state.style()->{{access_layers}}();
- FillLayer* prevChild = 0;
- if (value->isValueList() && !value->isImageSetValue()) {
- /* Walk each value and put it into a layer, creating new layers as needed. */
- CSSValueList* valueList = toCSSValueList(value);
- for (unsigned int i = 0; i < valueList->length(); i++) {
- if (!currChild) {
- /* Need to make a new layer to hold this value */
- currChild = new FillLayer({{fill_layer_type}});
- prevChild->setNext(currChild);
- }
- state.styleMap().{{map_fill}}({{property_id}}, currChild, valueList->itemWithoutBoundsCheck(i));
- prevChild = currChild;
- currChild = currChild->next();
- }
- } else {
- state.styleMap().{{map_fill}}({{property_id}}, currChild, value);
- currChild = currChild->next();
- }
- while (currChild) {
- /* Reset all remaining layers to not have the property set. */
- currChild->clear{{fill_type}}();
- currChild = currChild->next();
- }
-}
-{%- endmacro %}
-
-{{ apply_fill_layer("CSSPropertyBackgroundAttachment", "Attachment") }}
-{{ apply_fill_layer("CSSPropertyBackgroundBlendMode", "BlendMode") }}
-{{ apply_fill_layer("CSSPropertyBackgroundClip", "Clip") }}
-{{ apply_fill_layer("CSSPropertyBackgroundImage", "Image") }}
-{{ apply_fill_layer("CSSPropertyBackgroundOrigin", "Origin") }}
-{{ apply_fill_layer("CSSPropertyBackgroundPositionX", "XPosition") }}
-{{ apply_fill_layer("CSSPropertyBackgroundPositionY", "YPosition") }}
-{{ apply_fill_layer("CSSPropertyBackgroundRepeatX", "RepeatX") }}
-{{ apply_fill_layer("CSSPropertyBackgroundRepeatY", "RepeatY") }}
-{{ apply_fill_layer("CSSPropertyBackgroundSize", "Size") }}
-{{ apply_fill_layer("CSSPropertyMaskSourceType", "MaskSourceType") }}
-{{ apply_fill_layer("CSSPropertyWebkitBackgroundComposite", "Composite") }}
-{{ apply_fill_layer("CSSPropertyWebkitMaskClip", "Clip") }}
-{{ apply_fill_layer("CSSPropertyWebkitMaskComposite", "Composite") }}
-{{ apply_fill_layer("CSSPropertyWebkitMaskImage", "Image") }}
-{{ apply_fill_layer("CSSPropertyWebkitMaskOrigin", "Origin") }}
-{{ apply_fill_layer("CSSPropertyWebkitMaskPositionX", "XPosition") }}
-{{ apply_fill_layer("CSSPropertyWebkitMaskPositionY", "YPosition") }}
-{{ apply_fill_layer("CSSPropertyWebkitMaskRepeatX", "RepeatX") }}
-{{ apply_fill_layer("CSSPropertyWebkitMaskRepeatY", "RepeatY") }}
-{{ apply_fill_layer("CSSPropertyWebkitMaskSize", "Size") }}
-
-{%- macro apply_font(property_id, name_for_methods, initial, type_name) %}
-{#- We specify the getters/setters here since they are on FontDescription
- and not RenderStyle #}
-{%- set getter = lower_first(name_for_methods) %}
-{%- set setter = "set" + name_for_methods %}
-{{ declare_initial_function(property_id) }}
-{
- state.fontBuilder().{{setter}}({{initial}});
-}
-
-{{ declare_inherit_function(property_id) }}
-{
- state.fontBuilder().{{setter}}(state.parentFontDescription().{{getter}}());
-}
-
-{{ declare_value_function(property_id) }}
-{
- if (!value->isPrimitiveValue())
- return;
- CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
- state.fontBuilder().{{setter}}(static_cast<{{type_name}}>(*primitiveValue));
-}
-{%- endmacro %}
-
-{{ apply_font("CSSPropertyFontStyle", "Italic", "FontItalicOff", "FontItalic") }}
-{{ apply_font("CSSPropertyFontVariant", "SmallCaps", "FontSmallCapsOff", "FontSmallCaps") }}
-{{ apply_font("CSSPropertyTextRendering", "TextRenderingMode", "AutoTextRendering", "TextRenderingMode") }}
-{{ apply_font("CSSPropertyWebkitFontKerning", "Kerning", "FontDescription::AutoKerning", "FontDescription::Kerning") }}
-{{ apply_font("CSSPropertyWebkitFontSmoothing", "FontSmoothing", "AutoSmoothing", "FontSmoothingMode") }}
-
-{%- macro apply_value_number(property_id, id_for_minus_one) %}
-{{ declare_value_function(property_id) }}
-{
- {%- set property = properties[property_id] %}
- if (!value->isPrimitiveValue())
- return;
-
- CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
- if (primitiveValue->getValueID() == {{id_for_minus_one}})
- {{ set_value(property) }}(-1);
- else
- {{ set_value(property) }}(primitiveValue->getValue<{{property.type_name}}>(CSSPrimitiveValue::CSS_NUMBER));
-}
-{%- endmacro %}
-
-{{ apply_value_number("CSSPropertyInternalMarqueeRepetition", "CSSValueInfinite") }}
-
-{%- macro apply_value_shape(property_id) %}
-{{ declare_value_function(property_id) }}
-{
- {%- set property = properties[property_id] %}
- if (value->isPrimitiveValue()) {
- CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value);
- if (primitiveValue->getValueID() == CSSValueAuto)
- {{ set_value(property) }}(0);
- else if (primitiveValue->getValueID() == CSSValueOutsideShape)
- {{ set_value(property) }}(ShapeValue::createOutsideValue());
- else if (primitiveValue->isShape()) {
- {{ set_value(property) }}(ShapeValue::createShapeValue(basicShapeForValue(state, primitiveValue->getShapeValue())));
- }
- } else if (value->isImageValue()) {
- {{ set_value(property) }}(ShapeValue::createImageValue(state.styleImage({{property_id}}, value)));
- }
-}
-{%- endmacro %}
-
-{{ apply_value_shape("CSSPropertyWebkitShapeInside") }}
-{{ apply_value_shape("CSSPropertyWebkitShapeOutside") }}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/scripts/templates/StyleBuilderFunctions.h.tmpl b/chromium/third_party/WebKit/Source/core/scripts/templates/StyleBuilderFunctions.h.tmpl
deleted file mode 100644
index a7063e234e0..00000000000
--- a/chromium/third_party/WebKit/Source/core/scripts/templates/StyleBuilderFunctions.h.tmpl
+++ /dev/null
@@ -1,29 +0,0 @@
-{% from "macros.tmpl" import wrap_with_condition, license -%}
-{{ license() }}
-
-#ifndef StyleBuilderFunctions_h
-#define StyleBuilderFunctions_h
-
-#include "core/css/resolver/StyleBuilderCustom.h"
-
-namespace WebCore {
-
-class CSSValue;
-class StyleResolverState;
-
-class StyleBuilderFunctions {
-public:
-
-{%- for property_id, property in properties.items() if not property.use_handlers_for %}
-{% call wrap_with_condition(property.condition) %}
- static void applyInitial{{property_id}}(StyleResolverState&);
- static void applyInherit{{property_id}}(StyleResolverState&);
- static void applyValue{{property_id}}(StyleResolverState&, CSSValue*);
-{%- endcall %}
-{%- endfor %}
-
-};
-
-} // namespace WebCore
-
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/scripts/templates/StylePropertyShorthand.cpp.tmpl b/chromium/third_party/WebKit/Source/core/scripts/templates/StylePropertyShorthand.cpp.tmpl
deleted file mode 100644
index 257dae4d14a..00000000000
--- a/chromium/third_party/WebKit/Source/core/scripts/templates/StylePropertyShorthand.cpp.tmpl
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- * (C) 1999-2003 Lars Knoll (knoll@kde.org)
- * Copyright (C) 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
- * Copyright (C) 2013 Intel Corporation. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-#include "StylePropertyShorthand.h"
-#include "RuntimeEnabledFeatures.h"
-
-#include "wtf/HashMap.h"
-#include "wtf/StdLibExtras.h"
-
-namespace WebCore {
-
-{%- for property_id, property in properties.items() %}
-
-const StylePropertyShorthand& {{ property.camel_case_name }}Shorthand()
-{
- static const CSSPropertyID {{ property.camel_case_name }}Properties[] = {
- {%- for longhand_id in property.camel_case_longhands %}
- {{ longhand_id }},
- {%- endfor %}
- };
- DEFINE_STATIC_LOCAL(StylePropertyShorthand, {{ property.camel_case_name }}Longhands, ({{ property_id }}, {{ property.camel_case_name }}Properties, WTF_ARRAY_LENGTH({{ property.camel_case_name }}Properties)));
- return {{ property.camel_case_name }}Longhands;
-}
-{%- endfor %}
-
-// Returns an empty list if the property is not a shorthand
-const StylePropertyShorthand& shorthandForProperty(CSSPropertyID propertyID)
-{
- DEFINE_STATIC_LOCAL(StylePropertyShorthand, emptyShorthand, ());
- switch (propertyID) {
-{%- for property_id, property in properties.items() %}
- {%- if property.camel_case_name not in ["width", "height", "marker"] %}
- case {{ property_id }}:
- {%- if property.runtime_conditional_getter %}
- if (!RuntimeEnabledFeatures::{{ property.runtime_conditional_getter }}())
- return emptyShorthand;
- {%- endif %}
- return {{ property.camel_case_name }}Shorthand();
- {%- endif %}
-{%- endfor %}
- default: {
- return emptyShorthand;
- }
- }
-}
-
-typedef HashMap<CSSPropertyID, Vector<StylePropertyShorthand> > longhandsMap;
-const Vector<StylePropertyShorthand> matchingShorthandsForLonghand(CSSPropertyID propertyID)
-{
- DEFINE_STATIC_LOCAL(longhandsMap, map, ());
- if (map.isEmpty()) {
-{%- for longhand_id, shorthands in longhands_dictionary.items() %}
-
- Vector<StylePropertyShorthand, {{ shorthands|length }}> {{ longhand_id }}Shorthands;
- {% for shorthand in shorthands -%}
- {{ longhand_id }}Shorthands.uncheckedAppend({{ shorthand.camel_case_name }}Shorthand());
- {% endfor -%}
- // FIXME: the explicit Vector conversion copies into a temporary and is
- // wasteful.
- map.set({{ longhand_id }}, Vector<StylePropertyShorthand>({{ longhand_id }}Shorthands));
-{%- endfor %}
- }
- return map.get(propertyID);
-}
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/scripts/templates/StylePropertyShorthand.h.tmpl b/chromium/third_party/WebKit/Source/core/scripts/templates/StylePropertyShorthand.h.tmpl
deleted file mode 100644
index 5ef9febce37..00000000000
--- a/chromium/third_party/WebKit/Source/core/scripts/templates/StylePropertyShorthand.h.tmpl
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
- * (C) 1999-2003 Lars Knoll (knoll@kde.org)
- * Copyright (C) 2004, 2005, 2006, 2008 Apple Inc. All rights reserved.
- * Copyright (C) 2013 Intel Corporation. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#ifndef StylePropertyShorthand_h
-#define StylePropertyShorthand_h
-
-#include "CSSPropertyNames.h"
-#include "wtf/Vector.h"
-
-namespace WebCore {
-
-class StylePropertyShorthand {
- WTF_MAKE_FAST_ALLOCATED;
-public:
- StylePropertyShorthand()
- : m_properties(0)
- , m_propertiesForInitialization(0)
- , m_length(0)
- , m_shorthandID(CSSPropertyInvalid)
- {
- }
-
- StylePropertyShorthand(CSSPropertyID id, const CSSPropertyID* properties, unsigned numProperties)
- : m_properties(properties)
- , m_propertiesForInitialization(0)
- , m_length(numProperties)
- , m_shorthandID(id)
- {
- }
-
- StylePropertyShorthand(CSSPropertyID id, const CSSPropertyID* properties, const StylePropertyShorthand** propertiesForInitialization, unsigned numProperties)
- : m_properties(properties)
- , m_propertiesForInitialization(propertiesForInitialization)
- , m_length(numProperties)
- , m_shorthandID(id)
- {
- }
-
- const CSSPropertyID* properties() const { return m_properties; }
- const StylePropertyShorthand** propertiesForInitialization() const { return m_propertiesForInitialization; }
- unsigned length() const { return m_length; }
- CSSPropertyID id() const { return m_shorthandID; }
-
-private:
- const CSSPropertyID* m_properties;
- const StylePropertyShorthand** m_propertiesForInitialization;
- unsigned m_length;
- CSSPropertyID m_shorthandID;
-};
-
-{% for property_id, property in properties.items() %}
-{%- set camel_case_name = property.camel_case_name %}
-const StylePropertyShorthand& {{ camel_case_name }}Shorthand();
-{%- endfor %}
-
-// Returns an empty list if the property is not a shorthand, otherwise the list of longhands for parsing.
-const StylePropertyShorthand& parsingShorthandForProperty(CSSPropertyID);
-
-// Returns an empty list if the property is not a shorthand.
-const StylePropertyShorthand& shorthandForProperty(CSSPropertyID);
-
-// Return the list of shorthands for a given longhand.
-const Vector<StylePropertyShorthand> matchingShorthandsForLonghand(CSSPropertyID);
-unsigned indexOfShorthandForLonghand(CSSPropertyID, const Vector<StylePropertyShorthand>&);
-
-bool isExpandedShorthand(CSSPropertyID);
-
-} // namespace WebCore
-
-#endif // StylePropertyShorthand_h
diff --git a/chromium/third_party/WebKit/Source/core/scripts/templates/macros.tmpl b/chromium/third_party/WebKit/Source/core/scripts/templates/macros.tmpl
deleted file mode 100644
index b805c98d360..00000000000
--- a/chromium/third_party/WebKit/Source/core/scripts/templates/macros.tmpl
+++ /dev/null
@@ -1,48 +0,0 @@
-{% macro wrap_with_condition(condition) %}
-{%- if condition %}
-#if ENABLE({{condition}})
-{{- caller() }}
-#endif
-{%- else %}
-{{- caller() }}
-{%- endif %}
-{%- endmacro %}
-
-{#
- FIXME: Do we need to put license blocks in generated files?
-#}
-{% macro license() -%}
-/*
- * Copyright (C) 2013 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-{%- endmacro %}
-
-{% macro lower_first(s) -%}
-{{ (s[0]|lower) + s[1:] }}
-{%- endmacro %}
diff --git a/chromium/third_party/WebKit/Source/core/scripts/xxd.pl b/chromium/third_party/WebKit/Source/core/scripts/xxd.pl
deleted file mode 100644
index 5ee08a52d8e..00000000000
--- a/chromium/third_party/WebKit/Source/core/scripts/xxd.pl
+++ /dev/null
@@ -1,45 +0,0 @@
-#! /usr/bin/perl
-
-# Copyright (C) 2010-2011 Google Inc. All rights reserved.
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions are
-# met:
-#
-# # Redistributions of source code must retain the above copyright
-# notice, this list of conditions and the following disclaimer.
-# # Redistributions in binary form must reproduce the above
-# copyright notice, this list of conditions and the following disclaimer
-# in the documentation and/or other materials provided with the
-# distribution.
-# # Neither the name of Google Inc. nor the names of its
-# contributors may be used to endorse or promote products derived from
-# this software without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-#
-
-$varname = shift;
-$fname = shift;
-$output = shift;
-
-open($input, '<', $fname) or die "Can't open file for read: $fname $!";
-$/ = undef;
-$text = <$input>;
-close($input);
-
-$text = join(', ', map('0x' . unpack("H*", $_), split(undef, $text)));
-
-open($output, '>', $output) or die "Can't open file for write: $output $!";
-print $output "const unsigned char $varname\[\] = {\n$text\n};\n";
-close($output);
diff --git a/chromium/third_party/WebKit/Source/core/speech/SpeechInput.cpp b/chromium/third_party/WebKit/Source/core/speech/SpeechInput.cpp
new file mode 100644
index 00000000000..221e02377f2
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/speech/SpeechInput.cpp
@@ -0,0 +1,130 @@
+/*
+ * Copyright (C) 2010 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/speech/SpeechInput.h"
+
+#if ENABLE(INPUT_SPEECH)
+
+#include "core/speech/SpeechInputClient.h"
+#include "wtf/PassOwnPtr.h"
+
+namespace WebCore {
+
+SpeechInput::SpeechInput(SpeechInputClient* client)
+ : m_client(client)
+ , m_nextListenerId(1)
+{
+ m_client->setListener(this);
+}
+
+SpeechInput::~SpeechInput()
+{
+ m_client->setListener(0);
+}
+
+PassOwnPtr<SpeechInput> SpeechInput::create(SpeechInputClient* client)
+{
+ return adoptPtr(new SpeechInput(client));
+}
+
+int SpeechInput::registerListener(SpeechInputListener* listener)
+{
+#if defined(DEBUG)
+ // Check if already present.
+ for (HashMap<int, SpeechInputListener*>::iterator it = m_listeners.begin(); it != m_listeners.end(); ++it)
+ ASSERT(it->value != listener);
+#endif
+
+ m_listeners.add(m_nextListenerId, listener);
+ return m_nextListenerId++;
+}
+
+void SpeechInput::unregisterListener(int listenerId)
+{
+ if (m_listeners.contains(listenerId))
+ m_listeners.remove(listenerId);
+}
+
+void SpeechInput::didCompleteRecording(int listenerId)
+{
+ // Don't assert if not present as the element might have been removed by the page while
+ // this event was on the way.
+ if (m_listeners.contains(listenerId))
+ m_listeners.get(listenerId)->didCompleteRecording(listenerId);
+}
+
+void SpeechInput::didCompleteRecognition(int listenerId)
+{
+ // Don't assert if not present as the element might have been removed by the page while
+ // this event was on the way.
+ if (m_listeners.contains(listenerId))
+ m_listeners.get(listenerId)->didCompleteRecognition(listenerId);
+}
+
+void SpeechInput::setRecognitionResult(int listenerId, const SpeechInputResultArray& result)
+{
+ // Don't assert if not present as the element might have been removed by the page while
+ // this event was on the way.
+ if (m_listeners.contains(listenerId))
+ m_listeners.get(listenerId)->setRecognitionResult(listenerId, result);
+}
+
+bool SpeechInput::startRecognition(int listenerId, const IntRect& elementRect, const AtomicString& language, const String& grammar, SecurityOrigin* origin)
+{
+ ASSERT(m_listeners.contains(listenerId));
+ return m_client->startRecognition(listenerId, elementRect, language, grammar, origin);
+}
+
+void SpeechInput::stopRecording(int listenerId)
+{
+ ASSERT(m_listeners.contains(listenerId));
+ m_client->stopRecording(listenerId);
+}
+
+void SpeechInput::cancelRecognition(int listenerId)
+{
+ ASSERT(m_listeners.contains(listenerId));
+ m_client->cancelRecognition(listenerId);
+}
+
+const char* SpeechInput::supplementName()
+{
+ return "SpeechInput";
+}
+
+void provideSpeechInputTo(Page* page, SpeechInputClient* client)
+{
+ SpeechInput::provideTo(page, SpeechInput::supplementName(), SpeechInput::create(client));
+}
+
+} // namespace WebCore
+
+#endif // ENABLE(INPUT_SPEECH)
diff --git a/chromium/third_party/WebKit/Source/core/speech/SpeechInput.h b/chromium/third_party/WebKit/Source/core/speech/SpeechInput.h
new file mode 100644
index 00000000000..dcc717137bf
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/speech/SpeechInput.h
@@ -0,0 +1,90 @@
+/*
+ * Copyright (C) 2010 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SpeechInput_h
+#define SpeechInput_h
+
+#if ENABLE(INPUT_SPEECH)
+
+#include "core/page/Page.h"
+#include "core/speech/SpeechInputListener.h"
+#include "wtf/Forward.h"
+#include "wtf/HashMap.h"
+
+namespace WebCore {
+
+class IntRect;
+class SecurityOrigin;
+class SpeechInputClient;
+class SpeechInputListener;
+
+// This class connects the input elements requiring speech input with the platform specific
+// speech recognition engine. It provides methods for the input elements to activate speech
+// recognition and methods for the speech recognition engine to return back the results.
+class SpeechInput : public SpeechInputListener, public Supplement<Page> {
+ WTF_MAKE_NONCOPYABLE(SpeechInput);
+public:
+ virtual ~SpeechInput();
+
+ static PassOwnPtr<SpeechInput> create(SpeechInputClient*);
+ static const char* supplementName();
+ static SpeechInput* from(Page* page) { return static_cast<SpeechInput*>(Supplement<Page>::from(page, supplementName())); }
+
+ // Generates a unique ID for the given listener to be used for speech requests.
+ // This should be the first call made by listeners before anything else.
+ int registerListener(SpeechInputListener*);
+
+ // Invoked when the listener is done with recording or getting destroyed.
+ // Failure to unregister may result in crashes if there were any pending speech events.
+ void unregisterListener(int);
+
+ // Methods invoked by the input elements.
+ bool startRecognition(int listenerId, const IntRect& elementRect, const AtomicString& language, const String& grammar, SecurityOrigin*);
+ void stopRecording(int);
+ void cancelRecognition(int);
+
+ // SpeechInputListener methods.
+ virtual void didCompleteRecording(int);
+ virtual void didCompleteRecognition(int);
+ virtual void setRecognitionResult(int, const SpeechInputResultArray&);
+
+private:
+ explicit SpeechInput(SpeechInputClient*);
+
+ SpeechInputClient* m_client;
+ HashMap<int, SpeechInputListener*> m_listeners;
+ int m_nextListenerId;
+};
+
+} // namespace WebCore
+
+#endif // ENABLE(INPUT_SPEECH)
+
+#endif // SpeechInput_h
diff --git a/chromium/third_party/WebKit/Source/core/page/SpeechInputClient.h b/chromium/third_party/WebKit/Source/core/speech/SpeechInputClient.h
index 4e8eb6ff7a7..4e8eb6ff7a7 100644
--- a/chromium/third_party/WebKit/Source/core/page/SpeechInputClient.h
+++ b/chromium/third_party/WebKit/Source/core/speech/SpeechInputClient.h
diff --git a/chromium/third_party/WebKit/Source/core/speech/SpeechInputEvent.cpp b/chromium/third_party/WebKit/Source/core/speech/SpeechInputEvent.cpp
new file mode 100644
index 00000000000..f0222e9bb77
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/speech/SpeechInputEvent.cpp
@@ -0,0 +1,74 @@
+/*
+ * Copyright (C) 2010 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+
+#if ENABLE(INPUT_SPEECH)
+
+#include "core/speech/SpeechInputEvent.h"
+
+#include "core/events/ThreadLocalEventNames.h"
+
+namespace WebCore {
+
+PassRefPtr<SpeechInputEvent> SpeechInputEvent::create()
+{
+ return adoptRef(new SpeechInputEvent);
+}
+
+PassRefPtr<SpeechInputEvent> SpeechInputEvent::create(const AtomicString& eventType, const SpeechInputResultArray& results)
+{
+ return adoptRef(new SpeechInputEvent(eventType, results));
+}
+
+SpeechInputEvent::SpeechInputEvent()
+{
+ ScriptWrappable::init(this);
+}
+
+SpeechInputEvent::SpeechInputEvent(const AtomicString& eventType, const SpeechInputResultArray& results)
+ : Event(eventType, true, false) // Can bubble, not cancelable
+ , m_results(SpeechInputResultList::create(results))
+{
+ ScriptWrappable::init(this);
+}
+
+SpeechInputEvent::~SpeechInputEvent()
+{
+}
+
+const AtomicString& SpeechInputEvent::interfaceName() const
+{
+ return EventNames::SpeechInputEvent;
+}
+
+} // namespace WebCore
+
+#endif // ENABLE(INPUT_SPEECH)
diff --git a/chromium/third_party/WebKit/Source/core/speech/SpeechInputEvent.h b/chromium/third_party/WebKit/Source/core/speech/SpeechInputEvent.h
new file mode 100644
index 00000000000..1a00925bf39
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/speech/SpeechInputEvent.h
@@ -0,0 +1,59 @@
+/*
+ * Copyright (C) 2010 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SpeechInputEvent_h
+#define SpeechInputEvent_h
+
+#if ENABLE(INPUT_SPEECH)
+
+#include "core/events/Event.h"
+#include "core/speech/SpeechInputResultList.h"
+
+#include "wtf/PassRefPtr.h"
+
+namespace WebCore {
+
+class SpeechInputEvent : public Event {
+public:
+ static PassRefPtr<SpeechInputEvent> create();
+ static PassRefPtr<SpeechInputEvent> create(const AtomicString& eventType, const SpeechInputResultArray& results);
+ ~SpeechInputEvent();
+
+ SpeechInputResultList* results() const { return m_results.get(); }
+
+ virtual const AtomicString& interfaceName() const;
+
+private:
+ SpeechInputEvent();
+ SpeechInputEvent(const AtomicString& eventType, const SpeechInputResultArray& results);
+
+ RefPtr<SpeechInputResultList> m_results;
+};
+
+} // namespace WebCore
+
+#endif // ENABLE(INPUT_SPEECH)
+
+#endif // SpeechInputEvent_h
diff --git a/chromium/third_party/WebKit/Source/core/page/SpeechInputEvent.idl b/chromium/third_party/WebKit/Source/core/speech/SpeechInputEvent.idl
index 4fe740b1bdb..4fe740b1bdb 100644
--- a/chromium/third_party/WebKit/Source/core/page/SpeechInputEvent.idl
+++ b/chromium/third_party/WebKit/Source/core/speech/SpeechInputEvent.idl
diff --git a/chromium/third_party/WebKit/Source/core/speech/SpeechInputListener.h b/chromium/third_party/WebKit/Source/core/speech/SpeechInputListener.h
new file mode 100644
index 00000000000..b4fc017d138
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/speech/SpeechInputListener.h
@@ -0,0 +1,67 @@
+/*
+ * Copyright (C) 2010 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SpeechInputListener_h
+#define SpeechInputListener_h
+
+#if ENABLE(INPUT_SPEECH)
+
+#include "core/speech/SpeechInputResult.h"
+#include "wtf/Forward.h"
+
+namespace WebCore {
+
+// Interface to be implemented by the element which invokes SpeechInput.
+class SpeechInputListener {
+public:
+ // Informs that audio recording has completed and recognition is underway.
+ virtual void didCompleteRecording(int requestId) = 0;
+
+ // Informs that speech recognition has completed. This gets invoked irrespective of whether
+ // recognition was succesful or not, whether setRecognitionResult() was invoked or not. The
+ // handler typically frees up any temporary resources allocated and waits for the next speech
+ // recognition request.
+ virtual void didCompleteRecognition(int requestId) = 0;
+
+ // Gives results from speech recognition, either partial or the final results.
+ // This method can potentially get called multiple times if there are partial results
+ // available as the user keeps speaking. If the speech could not be recognized properly
+ // or if there was any other errors in the process, this method may never be called.
+ virtual void setRecognitionResult(int requestId, const SpeechInputResultArray&) = 0;
+
+protected:
+ virtual ~SpeechInputListener() { }
+};
+
+} // namespace WebCore
+
+#endif // ENABLE(INPUT_SPEECH)
+
+#endif // SpeechInputListener_h
diff --git a/chromium/third_party/WebKit/Source/core/speech/SpeechInputResult.cpp b/chromium/third_party/WebKit/Source/core/speech/SpeechInputResult.cpp
new file mode 100644
index 00000000000..1673455fe4b
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/speech/SpeechInputResult.cpp
@@ -0,0 +1,62 @@
+/*
+ * Copyright (C) 2010 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/speech/SpeechInputResult.h"
+
+#if ENABLE(INPUT_SPEECH)
+
+namespace WebCore {
+
+PassRefPtr<SpeechInputResult> SpeechInputResult::create(const String& utterance, double confidence)
+{
+ return adoptRef(new SpeechInputResult(utterance, confidence));
+}
+
+PassRefPtr<SpeechInputResult> SpeechInputResult::create(const SpeechInputResult& source)
+{
+ return adoptRef(new SpeechInputResult(source.m_utterance, source.m_confidence));
+}
+
+SpeechInputResult::SpeechInputResult(const String& utterance, double confidence)
+ : m_utterance(utterance)
+ , m_confidence(confidence)
+{
+ ScriptWrappable::init(this);
+}
+
+double SpeechInputResult::confidence() const
+{
+ return m_confidence;
+}
+
+const String& SpeechInputResult::utterance() const
+{
+ return m_utterance;
+}
+
+} // namespace WebCore
+
+#endif // ENABLE(INPUT_SPEECH)
diff --git a/chromium/third_party/WebKit/Source/core/page/SpeechInputResult.h b/chromium/third_party/WebKit/Source/core/speech/SpeechInputResult.h
index 5a5d44da7bd..5a5d44da7bd 100644
--- a/chromium/third_party/WebKit/Source/core/page/SpeechInputResult.h
+++ b/chromium/third_party/WebKit/Source/core/speech/SpeechInputResult.h
diff --git a/chromium/third_party/WebKit/Source/core/page/SpeechInputResult.idl b/chromium/third_party/WebKit/Source/core/speech/SpeechInputResult.idl
index bc2d4097aac..bc2d4097aac 100644
--- a/chromium/third_party/WebKit/Source/core/page/SpeechInputResult.idl
+++ b/chromium/third_party/WebKit/Source/core/speech/SpeechInputResult.idl
diff --git a/chromium/third_party/WebKit/Source/core/speech/SpeechInputResultList.cpp b/chromium/third_party/WebKit/Source/core/speech/SpeechInputResultList.cpp
new file mode 100644
index 00000000000..86f7fda0764
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/speech/SpeechInputResultList.cpp
@@ -0,0 +1,56 @@
+/*
+ * Copyright (C) 2010 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/speech/SpeechInputResultList.h"
+
+#if ENABLE(INPUT_SPEECH)
+
+namespace WebCore {
+
+PassRefPtr<SpeechInputResultList> SpeechInputResultList::create(const SpeechInputResultArray& results)
+{
+ return adoptRef(new SpeechInputResultList(results));
+}
+
+SpeechInputResult* SpeechInputResultList::item(unsigned index)
+{
+ return index >= m_results.size() ? 0 : m_results[index].get();
+}
+
+SpeechInputResultList::SpeechInputResultList(const SpeechInputResultArray& results)
+ : m_results(results) // Takes a copy of the array of RefPtrs.
+{
+ ScriptWrappable::init(this);
+}
+
+} // namespace WebCore
+
+#endif // ENABLE(INPUT_SPEECH)
diff --git a/chromium/third_party/WebKit/Source/core/speech/SpeechInputResultList.h b/chromium/third_party/WebKit/Source/core/speech/SpeechInputResultList.h
new file mode 100644
index 00000000000..3edb9d5bef0
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/speech/SpeechInputResultList.h
@@ -0,0 +1,56 @@
+/*
+ * Copyright (C) 2010 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SpeechInputResultList_h
+#define SpeechInputResultList_h
+
+#if ENABLE(INPUT_SPEECH)
+
+#include "bindings/v8/ScriptWrappable.h"
+#include "core/speech/SpeechInputResult.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefCounted.h"
+
+namespace WebCore {
+
+class SpeechInputResultList : public RefCounted<SpeechInputResultList>, public ScriptWrappable {
+public:
+ static PassRefPtr<SpeechInputResultList> create(const SpeechInputResultArray& results);
+
+ // Methods from the IDL.
+ size_t length() { return m_results.size(); }
+ SpeechInputResult* item(unsigned index);
+
+private:
+ explicit SpeechInputResultList(const SpeechInputResultArray& results);
+
+ SpeechInputResultArray m_results;
+};
+
+} // namespace WebCore
+
+#endif // ENABLE(INPUT_SPEECH)
+
+#endif // SpeechInputResultList_h
diff --git a/chromium/third_party/WebKit/Source/core/page/SpeechInputResultList.idl b/chromium/third_party/WebKit/Source/core/speech/SpeechInputResultList.idl
index 1983aed5017..1983aed5017 100644
--- a/chromium/third_party/WebKit/Source/core/page/SpeechInputResultList.idl
+++ b/chromium/third_party/WebKit/Source/core/speech/SpeechInputResultList.idl
diff --git a/chromium/third_party/WebKit/Source/core/storage/Storage.cpp b/chromium/third_party/WebKit/Source/core/storage/Storage.cpp
index c46e9bbdc81..76abd82a300 100644
--- a/chromium/third_party/WebKit/Source/core/storage/Storage.cpp
+++ b/chromium/third_party/WebKit/Source/core/storage/Storage.cpp
@@ -51,73 +51,73 @@ Storage::~Storage()
{
}
-String Storage::anonymousIndexedGetter(unsigned index, ExceptionState& es)
+String Storage::anonymousIndexedGetter(unsigned index, ExceptionState& exceptionState)
{
- return anonymousNamedGetter(String::number(index), es);
+ return anonymousNamedGetter(AtomicString::number(index), exceptionState);
}
-String Storage::anonymousNamedGetter(const AtomicString& name, ExceptionState& es)
+String Storage::anonymousNamedGetter(const AtomicString& name, ExceptionState& exceptionState)
{
- bool found = contains(name, es);
- if (es.hadException() || !found)
+ bool found = contains(name, exceptionState);
+ if (exceptionState.hadException() || !found)
return String();
- String result = getItem(name, es);
- if (es.hadException())
+ String result = getItem(name, exceptionState);
+ if (exceptionState.hadException())
return String();
return result;
}
-bool Storage::anonymousNamedSetter(const AtomicString& name, const AtomicString& value, ExceptionState& es)
+bool Storage::anonymousNamedSetter(const AtomicString& name, const AtomicString& value, ExceptionState& exceptionState)
{
- setItem(name, value, es);
+ setItem(name, value, exceptionState);
return true;
}
-bool Storage::anonymousIndexedSetter(unsigned index, const AtomicString& value, ExceptionState& es)
+bool Storage::anonymousIndexedSetter(unsigned index, const AtomicString& value, ExceptionState& exceptionState)
{
- return anonymousNamedSetter(String::number(index), value, es);
+ return anonymousNamedSetter(AtomicString::number(index), value, exceptionState);
}
-bool Storage::anonymousNamedDeleter(const AtomicString& name, ExceptionState& es)
+bool Storage::anonymousNamedDeleter(const AtomicString& name, ExceptionState& exceptionState)
{
- bool found = contains(name, es);
- if (!found || es.hadException())
+ bool found = contains(name, exceptionState);
+ if (!found || exceptionState.hadException())
return false;
- removeItem(name, es);
- if (es.hadException())
+ removeItem(name, exceptionState);
+ if (exceptionState.hadException())
return false;
return true;
}
-bool Storage::anonymousIndexedDeleter(unsigned index, ExceptionState& es)
+bool Storage::anonymousIndexedDeleter(unsigned index, ExceptionState& exceptionState)
{
- return anonymousNamedDeleter(String::number(index), es);
+ return anonymousNamedDeleter(AtomicString::number(index), exceptionState);
}
-void Storage::namedPropertyEnumerator(Vector<String>& names, ExceptionState& es)
+void Storage::namedPropertyEnumerator(Vector<String>& names, ExceptionState& exceptionState)
{
- unsigned length = this->length(es);
- if (es.hadException())
+ unsigned length = this->length(exceptionState);
+ if (exceptionState.hadException())
return;
names.resize(length);
for (unsigned i = 0; i < length; ++i) {
- String key = this->key(i, es);
- if (es.hadException())
+ String key = this->key(i, exceptionState);
+ if (exceptionState.hadException())
return;
ASSERT(!key.isNull());
- String val = getItem(key, es);
- if (es.hadException())
+ String val = getItem(key, exceptionState);
+ if (exceptionState.hadException())
return;
names[i] = key;
}
}
-bool Storage::namedPropertyQuery(const AtomicString& name, ExceptionState& es)
+bool Storage::namedPropertyQuery(const AtomicString& name, ExceptionState& exceptionState)
{
if (name == "length")
return false;
- bool found = contains(name, es);
- if (es.hadException() || !found)
+ bool found = contains(name, exceptionState);
+ if (exceptionState.hadException() || !found)
return false;
return true;
}
diff --git a/chromium/third_party/WebKit/Source/core/storage/Storage.h b/chromium/third_party/WebKit/Source/core/storage/Storage.h
index 825dad39357..34e131712c6 100644
--- a/chromium/third_party/WebKit/Source/core/storage/Storage.h
+++ b/chromium/third_party/WebKit/Source/core/storage/Storage.h
@@ -27,7 +27,7 @@
#define Storage_h
#include "bindings/v8/ScriptWrappable.h"
-#include "core/page/DOMWindowProperty.h"
+#include "core/frame/DOMWindowProperty.h"
#include "core/storage/StorageArea.h"
#include "wtf/Forward.h"
#include "wtf/RefCounted.h"
diff --git a/chromium/third_party/WebKit/Source/core/storage/Storage.idl b/chromium/third_party/WebKit/Source/core/storage/Storage.idl
index e3b5c705c3d..90309fe7ccd 100644
--- a/chromium/third_party/WebKit/Source/core/storage/Storage.idl
+++ b/chromium/third_party/WebKit/Source/core/storage/Storage.idl
@@ -30,11 +30,11 @@ interface Storage {
[RaisesException, ImplementedAs=anonymousNamedGetter] getter DOMString(DOMString name);
[RaisesException, ImplementedAs=anonymousNamedSetter] setter DOMString(DOMString name, DOMString value);
[ImplementedAs=anonymousNamedDeleter, RaisesException] deleter boolean (DOMString name);
- [NotEnumerable, GetterRaisesException] readonly attribute unsigned long length;
+ [NotEnumerable, RaisesException=Getter] readonly attribute unsigned long length;
[NotEnumerable, TreatReturnedNullStringAs=Null, RaisesException] DOMString key(unsigned long index);
- [NotEnumerable, TreatReturnedNullStringAs=Null, PerWorldBindings, ActivityLog=AccessForIsolatedWorlds, RaisesException] DOMString getItem(DOMString key);
- [NotEnumerable, RaisesException, PerWorldBindings, ActivityLog=AccessForIsolatedWorlds] void setItem(DOMString key, DOMString data);
- [NotEnumerable, RaisesException, PerWorldBindings, ActivityLog=AccessForIsolatedWorlds] void removeItem(DOMString key);
- [NotEnumerable, RaisesException, PerWorldBindings, ActivityLog=AccessForIsolatedWorlds] void clear();
+ [NotEnumerable, TreatReturnedNullStringAs=Null, PerWorldBindings, ActivityLogging=ForIsolatedWorlds, RaisesException] DOMString getItem(DOMString key);
+ [NotEnumerable, RaisesException, PerWorldBindings, ActivityLogging=ForIsolatedWorlds] void setItem(DOMString key, DOMString data);
+ [NotEnumerable, RaisesException, PerWorldBindings, ActivityLogging=ForIsolatedWorlds] void removeItem(DOMString key);
+ [NotEnumerable, RaisesException, PerWorldBindings, ActivityLogging=ForIsolatedWorlds] void clear();
};
diff --git a/chromium/third_party/WebKit/Source/core/storage/StorageEvent.cpp b/chromium/third_party/WebKit/Source/core/storage/StorageEvent.cpp
index 255b7fec4ae..1c434f39b4d 100644
--- a/chromium/third_party/WebKit/Source/core/storage/StorageEvent.cpp
+++ b/chromium/third_party/WebKit/Source/core/storage/StorageEvent.cpp
@@ -26,7 +26,7 @@
#include "config.h"
#include "core/storage/StorageEvent.h"
-#include "core/dom/EventNames.h"
+#include "core/events/ThreadLocalEventNames.h"
#include "core/storage/Storage.h"
namespace WebCore {
@@ -97,7 +97,7 @@ void StorageEvent::initStorageEvent(const AtomicString& type, bool canBubble, bo
const AtomicString& StorageEvent::interfaceName() const
{
- return eventNames().interfaceForStorageEvent;
+ return EventNames::StorageEvent;
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/storage/StorageEvent.h b/chromium/third_party/WebKit/Source/core/storage/StorageEvent.h
index a4e8ffc9a3e..2e6743a79d1 100644
--- a/chromium/third_party/WebKit/Source/core/storage/StorageEvent.h
+++ b/chromium/third_party/WebKit/Source/core/storage/StorageEvent.h
@@ -26,7 +26,7 @@
#ifndef StorageEvent_h
#define StorageEvent_h
-#include "core/dom/Event.h"
+#include "core/events/Event.h"
#include "wtf/text/WTFString.h"
namespace WebCore {
@@ -55,6 +55,7 @@ public:
const String& newValue() const { return m_newValue; }
const String& url() const { return m_url; }
Storage* storageArea() const { return m_storageArea.get(); }
+ Storage* storageArea(bool& isNull) const { isNull = !m_storageArea; return m_storageArea.get(); }
void initStorageEvent(const AtomicString& type, bool canBubble, bool cancelable, const String& key, const String& oldValue, const String& newValue, const String& url, Storage* storageArea);
diff --git a/chromium/third_party/WebKit/Source/core/storage/StorageEvent.idl b/chromium/third_party/WebKit/Source/core/storage/StorageEvent.idl
index f7b4e8b18e8..effe79fa213 100644
--- a/chromium/third_party/WebKit/Source/core/storage/StorageEvent.idl
+++ b/chromium/third_party/WebKit/Source/core/storage/StorageEvent.idl
@@ -24,13 +24,13 @@
*/
[
- ConstructorTemplate=Event
+ EventConstructor,
] interface StorageEvent : Event {
[InitializedByEventConstructor] readonly attribute DOMString key;
[InitializedByEventConstructor, TreatReturnedNullStringAs=Null] readonly attribute DOMString oldValue;
[InitializedByEventConstructor, TreatReturnedNullStringAs=Null] readonly attribute DOMString newValue;
[InitializedByEventConstructor] readonly attribute DOMString url;
- [InitializedByEventConstructor] readonly attribute Storage storageArea;
+ [InitializedByEventConstructor] readonly attribute Storage? storageArea;
void initStorageEvent([Default=Undefined] optional DOMString typeArg,
[Default=Undefined] optional boolean canBubbleArg,
diff --git a/chromium/third_party/WebKit/Source/core/svg/ColorDistance.cpp b/chromium/third_party/WebKit/Source/core/svg/ColorDistance.cpp
index df61eeedd29..00008684340 100644
--- a/chromium/third_party/WebKit/Source/core/svg/ColorDistance.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/ColorDistance.cpp
@@ -20,7 +20,7 @@
#include "config.h"
#include "core/svg/ColorDistance.h"
-#include "core/platform/graphics/Color.h"
+#include "platform/graphics/Color.h"
#include "wtf/MathExtras.h"
namespace WebCore {
@@ -55,13 +55,6 @@ static inline int clampColorValue(int v)
return v;
}
-ColorDistance ColorDistance::scaledDistance(float scaleFactor) const
-{
- return ColorDistance(static_cast<int>(scaleFactor * m_redDiff),
- static_cast<int>(scaleFactor * m_greenDiff),
- static_cast<int>(scaleFactor * m_blueDiff));
-}
-
Color ColorDistance::clampColor(int red, int green, int blue, int alpha)
{
return Color(clampColorValue(red), clampColorValue(green), clampColorValue(blue), clampColorValue(alpha));
@@ -72,16 +65,6 @@ Color ColorDistance::addColors(const Color& first, const Color& second)
return Color(first.red() + second.red(), first.green() + second.green(), first.blue() + second.blue());
}
-Color ColorDistance::addToColor(const Color& color) const
-{
- return Color(color.red() + m_redDiff, color.green() + m_greenDiff, color.blue() + m_blueDiff);
-}
-
-bool ColorDistance::isZero() const
-{
- return !m_redDiff && !m_blueDiff && !m_greenDiff;
-}
-
float ColorDistance::distance() const
{
// This is just a simple distance calculation, not respecting color spaces
diff --git a/chromium/third_party/WebKit/Source/core/svg/ColorDistance.h b/chromium/third_party/WebKit/Source/core/svg/ColorDistance.h
index 4f8b3fd46bf..470effb7598 100644
--- a/chromium/third_party/WebKit/Source/core/svg/ColorDistance.h
+++ b/chromium/third_party/WebKit/Source/core/svg/ColorDistance.h
@@ -30,14 +30,9 @@ public:
ColorDistance(const Color& fromColor, const Color& toColor);
ColorDistance(int redDiff, int blueDiff, int greenDiff);
- ColorDistance scaledDistance(float scaleFactor) const;
- Color addToColor(const Color&) const;
-
static Color addColors(const Color&, const Color&);
static Color clampColor(int red, int green, int blue, int alpha);
- bool isZero() const;
-
float distance() const;
private:
diff --git a/chromium/third_party/WebKit/Source/core/svg/PatternAttributes.h b/chromium/third_party/WebKit/Source/core/svg/PatternAttributes.h
index 1400e824395..7e4ae7520ca 100644
--- a/chromium/third_party/WebKit/Source/core/svg/PatternAttributes.h
+++ b/chromium/third_party/WebKit/Source/core/svg/PatternAttributes.h
@@ -20,9 +20,9 @@
#ifndef PatternAttributes_h
#define PatternAttributes_h
-#include "core/platform/graphics/transforms/AffineTransform.h"
#include "core/svg/SVGLength.h"
#include "core/svg/SVGPreserveAspectRatio.h"
+#include "platform/transforms/AffineTransform.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGAElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGAElement.cpp
index 84fa34de617..4cac139fddc 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGAElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGAElement.cpp
@@ -29,9 +29,10 @@
#include "core/dom/Attr.h"
#include "core/dom/Attribute.h"
#include "core/dom/Document.h"
-#include "core/dom/EventNames.h"
-#include "core/dom/KeyboardEvent.h"
-#include "core/dom/MouseEvent.h"
+#include "core/events/KeyboardEvent.h"
+#include "core/events/MouseEvent.h"
+#include "core/events/ThreadLocalEventNames.h"
+#include "core/frame/Frame.h"
#include "core/html/HTMLAnchorElement.h"
#include "core/html/HTMLFormElement.h"
#include "core/html/parser/HTMLParserIdioms.h"
@@ -40,15 +41,14 @@
#include "core/loader/FrameLoaderTypes.h"
#include "core/page/Chrome.h"
#include "core/page/ChromeClient.h"
-#include "core/page/Frame.h"
#include "core/page/Page.h"
-#include "core/platform/PlatformMouseEvent.h"
-#include "core/platform/network/ResourceRequest.h"
#include "core/rendering/svg/RenderSVGInline.h"
#include "core/rendering/svg/RenderSVGText.h"
#include "core/rendering/svg/RenderSVGTransformableContainer.h"
#include "core/svg/SVGElementInstance.h"
#include "core/svg/animation/SVGSMILElement.h"
+#include "platform/PlatformMouseEvent.h"
+#include "platform/network/ResourceRequest.h"
namespace WebCore {
@@ -66,17 +66,16 @@ BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGAElement)
REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
END_REGISTER_ANIMATED_PROPERTIES
-inline SVGAElement::SVGAElement(const QualifiedName& tagName, Document& document)
- : SVGGraphicsElement(tagName, document)
+inline SVGAElement::SVGAElement(Document& document)
+ : SVGGraphicsElement(SVGNames::aTag, document)
{
- ASSERT(hasTagName(SVGNames::aTag));
ScriptWrappable::init(this);
registerAnimatedPropertiesForSVGAElement();
}
-PassRefPtr<SVGAElement> SVGAElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGAElement> SVGAElement::create(Document& document)
{
- return adoptRef(new SVGAElement(tagName, document));
+ return adoptRef(new SVGAElement(document));
}
String SVGAElement::title() const
@@ -163,7 +162,7 @@ void SVGAElement::defaultEventHandler(Event* event)
if (url[0] == '#') {
Element* targetElement = treeScope().getElementById(url.substring(1));
- if (SVGSMILElement::isSMILElement(targetElement)) {
+ if (targetElement && isSVGSMILElement(*targetElement)) {
toSVGSMILElement(targetElement)->beginByLinkActivation();
event->setDefaultHandled();
return;
@@ -181,9 +180,9 @@ void SVGAElement::defaultEventHandler(Event* event)
Frame* frame = document().frame();
if (!frame)
return;
- FrameLoadRequest frameRequest(document().securityOrigin(), ResourceRequest(document().completeURL(url)), target);
+ FrameLoadRequest frameRequest(&document(), ResourceRequest(document().completeURL(url)), target);
frameRequest.setTriggeringEvent(event);
- frame->loader()->load(frameRequest);
+ frame->loader().load(frameRequest);
return;
}
}
@@ -235,7 +234,7 @@ bool SVGAElement::childShouldCreateRenderer(const Node& child) const
if (parentNode() && parentNode()->isSVGElement())
return parentNode()->childShouldCreateRenderer(child);
- return SVGElement::childShouldCreateRenderer(child);
+ return SVGGraphicsElement::childShouldCreateRenderer(child);
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGAElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGAElement.h
index b3d0743aeee..10036dbee99 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGAElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGAElement.h
@@ -33,10 +33,10 @@ class SVGAElement FINAL : public SVGGraphicsElement,
public SVGURIReference,
public SVGExternalResourcesRequired {
public:
- static PassRefPtr<SVGAElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGAElement> create(Document&);
private:
- SVGAElement(const QualifiedName&, Document&);
+ explicit SVGAElement(Document&);
virtual bool isValid() const { return SVGTests::isValid(); }
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGAltGlyphDefElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGAltGlyphDefElement.cpp
index d99b1656aac..4924ec5f3c5 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGAltGlyphDefElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGAltGlyphDefElement.cpp
@@ -28,16 +28,15 @@
namespace WebCore {
-inline SVGAltGlyphDefElement::SVGAltGlyphDefElement(const QualifiedName& tagName, Document& document)
- : SVGElement(tagName, document)
+inline SVGAltGlyphDefElement::SVGAltGlyphDefElement(Document& document)
+ : SVGElement(SVGNames::altGlyphDefTag, document)
{
- ASSERT(hasTagName(SVGNames::altGlyphDefTag));
ScriptWrappable::init(this);
}
-PassRefPtr<SVGAltGlyphDefElement> SVGAltGlyphDefElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGAltGlyphDefElement> SVGAltGlyphDefElement::create(Document& document)
{
- return adoptRef(new SVGAltGlyphDefElement(tagName, document));
+ return adoptRef(new SVGAltGlyphDefElement(document));
}
bool SVGAltGlyphDefElement::hasValidGlyphElements(Vector<String>& glyphNames) const
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGAltGlyphDefElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGAltGlyphDefElement.h
index f3b1fd809b1..e55794417b7 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGAltGlyphDefElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGAltGlyphDefElement.h
@@ -28,12 +28,12 @@ namespace WebCore {
class SVGAltGlyphDefElement FINAL : public SVGElement {
public:
- static PassRefPtr<SVGAltGlyphDefElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGAltGlyphDefElement> create(Document&);
bool hasValidGlyphElements(Vector<String>& glyphNames) const;
private:
- SVGAltGlyphDefElement(const QualifiedName&, Document&);
+ explicit SVGAltGlyphDefElement(Document&);
virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE { return false; }
};
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGAltGlyphElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGAltGlyphElement.cpp
index 691b8f49f3a..b170919f5b9 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGAltGlyphElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGAltGlyphElement.cpp
@@ -42,22 +42,21 @@ BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGAltGlyphElement)
REGISTER_PARENT_ANIMATED_PROPERTIES(SVGTextPositioningElement)
END_REGISTER_ANIMATED_PROPERTIES
-inline SVGAltGlyphElement::SVGAltGlyphElement(const QualifiedName& tagName, Document& document)
- : SVGTextPositioningElement(tagName, document)
+inline SVGAltGlyphElement::SVGAltGlyphElement(Document& document)
+ : SVGTextPositioningElement(SVGNames::altGlyphTag, document)
{
- ASSERT(hasTagName(SVGNames::altGlyphTag));
ScriptWrappable::init(this);
registerAnimatedPropertiesForSVGAltGlyphElement();
}
-PassRefPtr<SVGAltGlyphElement> SVGAltGlyphElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGAltGlyphElement> SVGAltGlyphElement::create(Document& document)
{
- return adoptRef(new SVGAltGlyphElement(tagName, document));
+ return adoptRef(new SVGAltGlyphElement(document));
}
-void SVGAltGlyphElement::setGlyphRef(const AtomicString&, ExceptionState& es)
+void SVGAltGlyphElement::setGlyphRef(const AtomicString&, ExceptionState& exceptionState)
{
- es.throwDOMException(NoModificationAllowedError);
+ exceptionState.throwUninformativeAndGenericDOMException(NoModificationAllowedError);
}
const AtomicString& SVGAltGlyphElement::glyphRef() const
@@ -65,9 +64,9 @@ const AtomicString& SVGAltGlyphElement::glyphRef() const
return fastGetAttribute(SVGNames::glyphRefAttr);
}
-void SVGAltGlyphElement::setFormat(const AtomicString&, ExceptionState& es)
+void SVGAltGlyphElement::setFormat(const AtomicString&, ExceptionState& exceptionState)
{
- es.throwDOMException(NoModificationAllowedError);
+ exceptionState.throwUninformativeAndGenericDOMException(NoModificationAllowedError);
}
const AtomicString& SVGAltGlyphElement::format() const
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGAltGlyphElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGAltGlyphElement.h
index 2ab0ee76ced..841e1f0993e 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGAltGlyphElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGAltGlyphElement.h
@@ -35,7 +35,7 @@ class SVGGlyphElement;
class SVGAltGlyphElement FINAL : public SVGTextPositioningElement,
public SVGURIReference {
public:
- static PassRefPtr<SVGAltGlyphElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGAltGlyphElement> create(Document&);
const AtomicString& glyphRef() const;
void setGlyphRef(const AtomicString&, ExceptionState&);
@@ -45,7 +45,7 @@ public:
bool hasValidGlyphElements(Vector<String>& glyphNames) const;
private:
- SVGAltGlyphElement(const QualifiedName&, Document&);
+ explicit SVGAltGlyphElement(Document&);
virtual RenderObject* createRenderer(RenderStyle*);
virtual bool childShouldCreateRenderer(const Node& child) const;
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGAltGlyphElement.idl b/chromium/third_party/WebKit/Source/core/svg/SVGAltGlyphElement.idl
index 999598e8014..e3f99152598 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGAltGlyphElement.idl
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGAltGlyphElement.idl
@@ -26,8 +26,8 @@
[
Conditional=SVG_FONTS
] interface SVGAltGlyphElement : SVGTextPositioningElement {
- [SetterRaisesException] attribute DOMString glyphRef;
- [SetterRaisesException] attribute DOMString format;
+ [RaisesException=Setter] attribute DOMString glyphRef;
+ [RaisesException=Setter] attribute DOMString format;
};
SVGAltGlyphElement implements SVGURIReference;
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGAltGlyphItemElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGAltGlyphItemElement.cpp
index 22c4d959c6b..662dfeb54b7 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGAltGlyphItemElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGAltGlyphItemElement.cpp
@@ -27,16 +27,15 @@
namespace WebCore {
-inline SVGAltGlyphItemElement::SVGAltGlyphItemElement(const QualifiedName& tagName, Document& document)
- : SVGElement(tagName, document)
+inline SVGAltGlyphItemElement::SVGAltGlyphItemElement(Document& document)
+ : SVGElement(SVGNames::altGlyphItemTag, document)
{
- ASSERT(hasTagName(SVGNames::altGlyphItemTag));
ScriptWrappable::init(this);
}
-PassRefPtr<SVGAltGlyphItemElement> SVGAltGlyphItemElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGAltGlyphItemElement> SVGAltGlyphItemElement::create(Document& document)
{
- return adoptRef(new SVGAltGlyphItemElement(tagName, document));
+ return adoptRef(new SVGAltGlyphItemElement(document));
}
bool SVGAltGlyphItemElement::hasValidGlyphElements(Vector<String>& glyphNames) const
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGAltGlyphItemElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGAltGlyphItemElement.h
index 18223d7b8ca..cf4c9b09180 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGAltGlyphItemElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGAltGlyphItemElement.h
@@ -28,12 +28,12 @@ namespace WebCore {
class SVGAltGlyphItemElement FINAL : public SVGElement {
public:
- static PassRefPtr<SVGAltGlyphItemElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGAltGlyphItemElement> create(Document&);
bool hasValidGlyphElements(Vector<String>& glyphNames) const;
private:
- SVGAltGlyphItemElement(const QualifiedName&, Document&);
+ explicit SVGAltGlyphItemElement(Document&);
virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE { return false; }
};
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGAngle.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGAngle.cpp
index e88d5da4956..30f4155db32 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGAngle.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGAngle.cpp
@@ -150,7 +150,7 @@ static bool parseValue(const String& value, float& valueInSpecifiedUnits, SVGAng
return true;
}
-void SVGAngle::setValueAsString(const String& value, ExceptionState& es)
+void SVGAngle::setValueAsString(const String& value, ExceptionState& exceptionState)
{
if (value.isEmpty()) {
m_unitType = SVG_ANGLETYPE_UNSPECIFIED;
@@ -163,7 +163,7 @@ void SVGAngle::setValueAsString(const String& value, ExceptionState& es)
bool success = value.is8Bit() ? parseValue<LChar>(value, valueInSpecifiedUnits, unitType)
: parseValue<UChar>(value, valueInSpecifiedUnits, unitType);
if (!success) {
- es.throwDOMException(SyntaxError);
+ exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
return;
}
@@ -171,10 +171,10 @@ void SVGAngle::setValueAsString(const String& value, ExceptionState& es)
m_valueInSpecifiedUnits = valueInSpecifiedUnits;
}
-void SVGAngle::newValueSpecifiedUnits(unsigned short unitType, float valueInSpecifiedUnits, ExceptionState& es)
+void SVGAngle::newValueSpecifiedUnits(unsigned short unitType, float valueInSpecifiedUnits, ExceptionState& exceptionState)
{
if (unitType == SVG_ANGLETYPE_UNKNOWN || unitType > SVG_ANGLETYPE_GRAD) {
- es.throwDOMException(NotSupportedError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
return;
}
@@ -184,10 +184,10 @@ void SVGAngle::newValueSpecifiedUnits(unsigned short unitType, float valueInSpec
m_valueInSpecifiedUnits = valueInSpecifiedUnits;
}
-void SVGAngle::convertToSpecifiedUnits(unsigned short unitType, ExceptionState& es)
+void SVGAngle::convertToSpecifiedUnits(unsigned short unitType, ExceptionState& exceptionState)
{
if (unitType == SVG_ANGLETYPE_UNKNOWN || m_unitType == SVG_ANGLETYPE_UNKNOWN || unitType > SVG_ANGLETYPE_GRAD) {
- es.throwDOMException(NotSupportedError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
return;
}
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGAngle.idl b/chromium/third_party/WebKit/Source/core/svg/SVGAngle.idl
index 4501978c40d..665f6ead7fc 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGAngle.idl
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGAngle.idl
@@ -32,7 +32,7 @@ interface SVGAngle {
[StrictTypeChecking] attribute float value;
[StrictTypeChecking] attribute float valueInSpecifiedUnits;
- [TreatNullAs=NullString, SetterRaisesException] attribute DOMString valueAsString;
+ [TreatNullAs=NullString, RaisesException=Setter] attribute DOMString valueAsString;
[StrictTypeChecking, RaisesException] void newValueSpecifiedUnits(unsigned short unitType, float valueInSpecifiedUnits);
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGAnimateColorElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGAnimateColorElement.cpp
index ce8d772bba7..7bf3842c491 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGAnimateColorElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGAnimateColorElement.cpp
@@ -22,23 +22,22 @@
#include "config.h"
#include "SVGNames.h"
-#include "core/page/UseCounter.h"
+#include "core/frame/UseCounter.h"
#include "core/svg/SVGAnimateColorElement.h"
namespace WebCore {
-inline SVGAnimateColorElement::SVGAnimateColorElement(const QualifiedName& tagName, Document& document)
- : SVGAnimateElement(tagName, document)
+inline SVGAnimateColorElement::SVGAnimateColorElement(Document& document)
+ : SVGAnimateElement(SVGNames::animateColorTag, document)
{
- ASSERT(hasTagName(SVGNames::animateColorTag));
ScriptWrappable::init(this);
- UseCounter::count(&document, UseCounter::SVGAnimateColorElement);
+ UseCounter::count(document, UseCounter::SVGAnimateColorElement);
}
-PassRefPtr<SVGAnimateColorElement> SVGAnimateColorElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGAnimateColorElement> SVGAnimateColorElement::create(Document& document)
{
- return adoptRef(new SVGAnimateColorElement(tagName, document));
+ return adoptRef(new SVGAnimateColorElement(document));
}
static bool attributeValueIsCurrentColor(const String& value)
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGAnimateColorElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGAnimateColorElement.h
index 160b1c63ab2..f17ea2627ce 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGAnimateColorElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGAnimateColorElement.h
@@ -28,10 +28,10 @@ namespace WebCore {
class SVGAnimateColorElement FINAL : public SVGAnimateElement {
public:
- static PassRefPtr<SVGAnimateColorElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGAnimateColorElement> create(Document&);
private:
- SVGAnimateColorElement(const QualifiedName&, Document&);
+ explicit SVGAnimateColorElement(Document&);
virtual void determinePropertyValueTypes(const String& from, const String& to);
};
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGAnimateElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGAnimateElement.cpp
index 4baee606355..83e30da7fc3 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGAnimateElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGAnimateElement.cpp
@@ -25,13 +25,13 @@
#include "core/svg/SVGAnimateElement.h"
#include "CSSPropertyNames.h"
-#include "SVGNames.h"
#include "core/css/CSSParser.h"
#include "core/css/StylePropertySet.h"
#include "core/dom/QualifiedName.h"
#include "core/svg/SVGAnimatedType.h"
#include "core/svg/SVGAnimatedTypeAnimator.h"
#include "core/svg/SVGAnimatorFactory.h"
+#include "core/svg/SVGDocumentExtensions.h"
namespace WebCore {
@@ -43,13 +43,15 @@ SVGAnimateElement::SVGAnimateElement(const QualifiedName& tagName, Document& doc
ScriptWrappable::init(this);
}
-PassRefPtr<SVGAnimateElement> SVGAnimateElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGAnimateElement> SVGAnimateElement::create(Document& document)
{
- return adoptRef(new SVGAnimateElement(tagName, document));
+ return adoptRef(new SVGAnimateElement(SVGNames::animateTag, document));
}
SVGAnimateElement::~SVGAnimateElement()
{
+ if (targetElement())
+ clearAnimatedType(targetElement());
}
bool SVGAnimateElement::hasValidAttributeType()
@@ -97,7 +99,7 @@ void SVGAnimateElement::calculateAnimatedValue(float percentage, unsigned repeat
{
ASSERT(resultElement);
SVGElement* targetElement = this->targetElement();
- if (!targetElement)
+ if (!targetElement || !isSVGAnimateElement(*resultElement))
return;
ASSERT(m_animatedPropertyType == determineAnimatedPropertyType(targetElement));
@@ -211,6 +213,10 @@ void SVGAnimateElement::resetAnimatedType()
if (shouldApply == ApplyXMLAnimation) {
// SVG DOM animVal animation code-path.
m_animatedProperties = animator->findAnimatedPropertiesForAttributeName(targetElement, attributeName);
+ SVGElementAnimatedPropertyList::const_iterator end = m_animatedProperties.end();
+ for (SVGElementAnimatedPropertyList::const_iterator it = m_animatedProperties.begin(); it != end; ++it)
+ document().accessSVGExtensions()->addElementReferencingTarget(this, it->element);
+
ASSERT(!m_animatedProperties.isEmpty());
ASSERT(propertyTypesAreConsistent(m_animatedPropertyType, m_animatedProperties));
@@ -240,7 +246,7 @@ void SVGAnimateElement::resetAnimatedType()
static inline void applyCSSPropertyToTarget(SVGElement* targetElement, CSSPropertyID id, const String& value)
{
- ASSERT(!targetElement->m_deletionHasBegun);
+ ASSERT_WITH_SECURITY_IMPLICATION(!targetElement->m_deletionHasBegun);
MutableStylePropertySet* propertySet = targetElement->ensureAnimatedSMILStyleProperties();
if (!propertySet->setProperty(id, value, false, 0))
@@ -251,7 +257,7 @@ static inline void applyCSSPropertyToTarget(SVGElement* targetElement, CSSProper
static inline void removeCSSPropertyFromTarget(SVGElement* targetElement, CSSPropertyID id)
{
- ASSERT(!targetElement->m_deletionHasBegun);
+ ASSERT_WITH_SECURITY_IMPLICATION(!targetElement->m_deletionHasBegun);
targetElement->ensureAnimatedSMILStyleProperties()->removeProperty(id);
targetElement->setNeedsStyleRecalc(LocalStyleChange);
}
@@ -298,7 +304,7 @@ static inline void removeCSSPropertyFromTargetAndInstances(SVGElement* targetEle
static inline void notifyTargetAboutAnimValChange(SVGElement* targetElement, const QualifiedName& attributeName)
{
- ASSERT(!targetElement->m_deletionHasBegun);
+ ASSERT_WITH_SECURITY_IMPLICATION(!targetElement->m_deletionHasBegun);
targetElement->svgAttributeChanged(attributeName);
}
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGAnimateElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGAnimateElement.h
index e7f2c673d83..e8b2dc438ab 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGAnimateElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGAnimateElement.h
@@ -35,7 +35,7 @@ class SVGAnimatedTypeAnimator;
class SVGAnimateElement : public SVGAnimationElement {
public:
- static PassRefPtr<SVGAnimateElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGAnimateElement> create(Document&);
virtual ~SVGAnimateElement();
AnimatedPropertyType determineAnimatedPropertyType(SVGElement*) const;
@@ -75,16 +75,16 @@ private:
OwnPtr<SVGAnimatedTypeAnimator> m_animator;
};
-inline SVGAnimateElement* toSVGAnimateElement(Element* element)
+inline bool isSVGAnimateElement(const Node& node)
{
- ASSERT_WITH_SECURITY_IMPLICATION(!element
- || element->hasTagName(SVGNames::animateTag)
- || element->hasTagName(SVGNames::animateColorTag)
- || element->hasTagName(SVGNames::animateTransformTag)
- || element->hasTagName(SVGNames::setTag));
- return static_cast<SVGAnimateElement*>(element);
+ return node.hasTagName(SVGNames::animateTag)
+ || node.hasTagName(SVGNames::animateColorTag)
+ || node.hasTagName(SVGNames::animateTransformTag)
+ || node.hasTagName(SVGNames::setTag);
}
+DEFINE_NODE_TYPE_CASTS_WITH_FUNCTION(SVGAnimateElement);
+
} // namespace WebCore
#endif // SVGAnimateElement_h
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGAnimateMotionElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGAnimateMotionElement.cpp
index faf70569fda..9c76b316404 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGAnimateMotionElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGAnimateMotionElement.cpp
@@ -24,7 +24,6 @@
#include "core/svg/SVGAnimateMotionElement.h"
#include "SVGNames.h"
-#include "core/platform/graphics/transforms/AffineTransform.h"
#include "core/rendering/RenderObject.h"
#include "core/rendering/svg/RenderSVGResource.h"
#include "core/rendering/svg/SVGPathData.h"
@@ -33,6 +32,7 @@
#include "core/svg/SVGParserUtilities.h"
#include "core/svg/SVGPathElement.h"
#include "core/svg/SVGPathUtilities.h"
+#include "platform/transforms/AffineTransform.h"
#include "wtf/MathExtras.h"
#include "wtf/StdLibExtras.h"
@@ -40,18 +40,23 @@ namespace WebCore {
using namespace SVGNames;
-inline SVGAnimateMotionElement::SVGAnimateMotionElement(const QualifiedName& tagName, Document& document)
- : SVGAnimationElement(tagName, document)
+inline SVGAnimateMotionElement::SVGAnimateMotionElement(Document& document)
+ : SVGAnimationElement(animateMotionTag, document)
, m_hasToPointAtEndOfDuration(false)
{
setCalcMode(CalcModePaced);
- ASSERT(hasTagName(animateMotionTag));
ScriptWrappable::init(this);
}
-PassRefPtr<SVGAnimateMotionElement> SVGAnimateMotionElement::create(const QualifiedName& tagName, Document& document)
+SVGAnimateMotionElement::~SVGAnimateMotionElement()
{
- return adoptRef(new SVGAnimateMotionElement(tagName, document));
+ if (targetElement())
+ clearAnimatedType(targetElement());
+}
+
+PassRefPtr<SVGAnimateMotionElement> SVGAnimateMotionElement::create(Document& document)
+{
+ return adoptRef(new SVGAnimateMotionElement(document));
}
bool SVGAnimateMotionElement::hasValidAttributeType()
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGAnimateMotionElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGAnimateMotionElement.h
index 79c84157ae4..46094a1302a 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGAnimateMotionElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGAnimateMotionElement.h
@@ -21,8 +21,8 @@
#ifndef SVGAnimateMotionElement_h
#define SVGAnimateMotionElement_h
-#include "core/platform/graphics/Path.h"
#include "core/svg/SVGAnimationElement.h"
+#include "platform/graphics/Path.h"
namespace WebCore {
@@ -30,11 +30,13 @@ class AffineTransform;
class SVGAnimateMotionElement FINAL : public SVGAnimationElement {
public:
- static PassRefPtr<SVGAnimateMotionElement> create(const QualifiedName&, Document&);
+ virtual ~SVGAnimateMotionElement();
+
+ static PassRefPtr<SVGAnimateMotionElement> create(Document&);
void updateAnimationPath();
private:
- SVGAnimateMotionElement(const QualifiedName&, Document&);
+ explicit SVGAnimateMotionElement(Document&);
virtual bool hasValidAttributeType();
virtual bool hasValidAttributeName();
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGAnimateTransformElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGAnimateTransformElement.cpp
index 051cf9377d9..6774a387307 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGAnimateTransformElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGAnimateTransformElement.cpp
@@ -25,21 +25,20 @@
#include "core/svg/SVGAnimateTransformElement.h"
#include "SVGNames.h"
-#include "core/svg/SVGTransformable.h"
+#include "core/svg/SVGParserUtilities.h"
namespace WebCore {
-inline SVGAnimateTransformElement::SVGAnimateTransformElement(const QualifiedName& tagName, Document& document)
- : SVGAnimateElement(tagName, document)
+inline SVGAnimateTransformElement::SVGAnimateTransformElement(Document& document)
+ : SVGAnimateElement(SVGNames::animateTransformTag, document)
, m_type(SVGTransform::SVG_TRANSFORM_UNKNOWN)
{
- ASSERT(hasTagName(SVGNames::animateTransformTag));
ScriptWrappable::init(this);
}
-PassRefPtr<SVGAnimateTransformElement> SVGAnimateTransformElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGAnimateTransformElement> SVGAnimateTransformElement::create(Document& document)
{
- return adoptRef(new SVGAnimateTransformElement(tagName, document));
+ return adoptRef(new SVGAnimateTransformElement(document));
}
bool SVGAnimateTransformElement::hasValidAttributeType()
@@ -70,7 +69,7 @@ void SVGAnimateTransformElement::parseAttribute(const QualifiedName& name, const
}
if (name == SVGNames::typeAttr) {
- m_type = SVGTransformable::parseTransformType(value);
+ m_type = parseTransformType(value);
if (m_type == SVGTransform::SVG_TRANSFORM_MATRIX)
m_type = SVGTransform::SVG_TRANSFORM_UNKNOWN;
return;
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGAnimateTransformElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGAnimateTransformElement.h
index 21c80f26991..86606d8890a 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGAnimateTransformElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGAnimateTransformElement.h
@@ -32,12 +32,12 @@ class AffineTransform;
class SVGAnimateTransformElement FINAL : public SVGAnimateElement {
public:
- static PassRefPtr<SVGAnimateTransformElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGAnimateTransformElement> create(Document&);
SVGTransform::SVGTransformType transformType() const { return m_type; }
private:
- SVGAnimateTransformElement(const QualifiedName&, Document&);
+ explicit SVGAnimateTransformElement(Document&);
virtual bool hasValidAttributeType();
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGAnimatedAngle.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGAnimatedAngle.cpp
index e5e1a771cc2..a6265e5466b 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGAnimatedAngle.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGAnimatedAngle.cpp
@@ -31,13 +31,6 @@ SVGAnimatedAngleAnimator::SVGAnimatedAngleAnimator(SVGAnimationElement* animatio
{
}
-static inline SVGAngle& sharedSVGAngle(const String& valueAsString)
-{
- DEFINE_STATIC_LOCAL(SVGAngle, sharedAngle, ());
- sharedAngle.setValueAsString(valueAsString, ASSERT_NO_EXCEPTION);
- return sharedAngle;
-}
-
PassOwnPtr<SVGAnimatedType> SVGAnimatedAngleAnimator::constructFromString(const String& string)
{
OwnPtr<SVGAnimatedType> animatedType = SVGAnimatedType::createAngleAndEnumeration(new pair<SVGAngle, unsigned>);
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGAnimatedBoolean.idl b/chromium/third_party/WebKit/Source/core/svg/SVGAnimatedBoolean.idl
index fa2ca08e01b..7fc919ccf26 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGAnimatedBoolean.idl
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGAnimatedBoolean.idl
@@ -24,7 +24,7 @@
*/
interface SVGAnimatedBoolean {
- [StrictTypeChecking, SetterRaisesException] attribute boolean baseVal;
+ [StrictTypeChecking, RaisesException=Setter] attribute boolean baseVal;
readonly attribute boolean animVal;
};
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGAnimatedEnumeration.idl b/chromium/third_party/WebKit/Source/core/svg/SVGAnimatedEnumeration.idl
index cb04e753a08..e51c9c1f87d 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGAnimatedEnumeration.idl
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGAnimatedEnumeration.idl
@@ -24,7 +24,7 @@
*/
interface SVGAnimatedEnumeration {
- [StrictTypeChecking, SetterRaisesException] attribute unsigned short baseVal;
+ [StrictTypeChecking, RaisesException=Setter] attribute unsigned short baseVal;
readonly attribute unsigned short animVal;
};
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGAnimatedInteger.idl b/chromium/third_party/WebKit/Source/core/svg/SVGAnimatedInteger.idl
index ae72080cfbf..3c31681dc6c 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGAnimatedInteger.idl
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGAnimatedInteger.idl
@@ -24,7 +24,7 @@
*/
interface SVGAnimatedInteger {
- [StrictTypeChecking, SetterRaisesException] attribute long baseVal;
+ [StrictTypeChecking, RaisesException=Setter] attribute long baseVal;
readonly attribute long animVal;
};
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGAnimatedNumber.idl b/chromium/third_party/WebKit/Source/core/svg/SVGAnimatedNumber.idl
index 6e3485cc238..e8cc9ba3161 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGAnimatedNumber.idl
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGAnimatedNumber.idl
@@ -25,7 +25,7 @@
*/
interface SVGAnimatedNumber {
- [StrictTypeChecking, SetterRaisesException] attribute float baseVal;
+ [StrictTypeChecking, RaisesException=Setter] attribute float baseVal;
readonly attribute float animVal;
};
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGAnimatedPointList.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGAnimatedPointList.cpp
index 837cfdaf62c..fd68ad04e7e 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGAnimatedPointList.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGAnimatedPointList.cpp
@@ -23,7 +23,6 @@
#include "core/svg/SVGAnimateElement.h"
#include "core/svg/SVGParserUtilities.h"
-#include "core/svg/SVGPointList.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGAnimatedString.idl b/chromium/third_party/WebKit/Source/core/svg/SVGAnimatedString.idl
index 27e27dc29f1..d1fbf52a247 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGAnimatedString.idl
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGAnimatedString.idl
@@ -24,7 +24,7 @@
*/
interface SVGAnimatedString {
- [SetterRaisesException] attribute DOMString baseVal;
+ [RaisesException=Setter] attribute DOMString baseVal;
readonly attribute DOMString animVal;
};
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGAnimatedType.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGAnimatedType.cpp
index 148e00bb42b..486773f4306 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGAnimatedType.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGAnimatedType.cpp
@@ -280,9 +280,9 @@ bool SVGAnimatedType::setValueAsString(const QualifiedName& attrName, const Stri
break;
case AnimatedLength: {
ASSERT(m_data.length);
- TrackExceptionState es;
- m_data.length->setValueAsString(value, SVGLength::lengthModeForAnimatedLengthAttribute(attrName), es);
- return !es.hadException();
+ TrackExceptionState exceptionState;
+ m_data.length->setValueAsString(value, SVGLength::lengthModeForAnimatedLengthAttribute(attrName), exceptionState);
+ return !exceptionState.hadException();
}
case AnimatedLengthList:
ASSERT(m_data.lengthList);
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGAnimatedType.h b/chromium/third_party/WebKit/Source/core/svg/SVGAnimatedType.h
index d5d60334bf2..7c6aa01350a 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGAnimatedType.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGAnimatedType.h
@@ -35,10 +35,10 @@ namespace WebCore {
class SVGPathByteStream;
-class SVGAnimatedType {
+class SVGAnimatedType FINAL {
WTF_MAKE_FAST_ALLOCATED;
public:
- virtual ~SVGAnimatedType();
+ ~SVGAnimatedType();
static PassOwnPtr<SVGAnimatedType> createAngleAndEnumeration(std::pair<SVGAngle, unsigned>*);
static PassOwnPtr<SVGAnimatedType> createBoolean(bool*);
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGAnimationElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGAnimationElement.cpp
index 21873d73010..f17bd5e7bd5 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGAnimationElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGAnimationElement.cpp
@@ -30,11 +30,11 @@
#include "SVGNames.h"
#include "core/css/CSSComputedStyleDeclaration.h"
#include "core/css/CSSParser.h"
-#include "core/page/UseCounter.h"
-#include "core/platform/FloatConversion.h"
+#include "core/frame/UseCounter.h"
#include "core/svg/SVGAnimateElement.h"
#include "core/svg/SVGElement.h"
#include "core/svg/SVGParserUtilities.h"
+#include "platform/FloatConversion.h"
#include "wtf/MathExtras.h"
namespace WebCore {
@@ -60,7 +60,7 @@ SVGAnimationElement::SVGAnimationElement(const QualifiedName& tagName, Document&
ScriptWrappable::init(this);
registerAnimatedPropertiesForSVGAnimationElement();
- UseCounter::count(&document, UseCounter::SVGAnimationElement);
+ UseCounter::count(document, UseCounter::SVGAnimationElement);
}
static void parseKeyTimes(const String& string, Vector<float>& result, bool verifyOrder)
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGAnimationElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGAnimationElement.h
index 11410e1885f..087529fc32d 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGAnimationElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGAnimationElement.h
@@ -25,11 +25,11 @@
#ifndef SVGAnimationElement_h
#define SVGAnimationElement_h
-#include "core/platform/graphics/UnitBezier.h"
#include "core/svg/SVGAnimatedBoolean.h"
#include "core/svg/SVGExternalResourcesRequired.h"
#include "core/svg/SVGTests.h"
#include "core/svg/animation/SVGSMILElement.h"
+#include "platform/animation/UnitBezier.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/svg/svgattrs.in b/chromium/third_party/WebKit/Source/core/svg/SVGAttributeNames.in
index bee8ecc5e2c..bee8ecc5e2c 100644
--- a/chromium/third_party/WebKit/Source/core/svg/svgattrs.in
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGAttributeNames.in
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGCircleElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGCircleElement.cpp
index 8852d8c33af..e1d6ba3bb6d 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGCircleElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGCircleElement.cpp
@@ -22,7 +22,6 @@
#include "core/svg/SVGCircleElement.h"
-#include "SVGNames.h"
#include "core/rendering/svg/RenderSVGEllipse.h"
#include "core/rendering/svg/RenderSVGResource.h"
#include "core/svg/SVGElementInstance.h"
@@ -44,27 +43,25 @@ BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGCircleElement)
REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
END_REGISTER_ANIMATED_PROPERTIES
-inline SVGCircleElement::SVGCircleElement(const QualifiedName& tagName, Document& document)
- : SVGGraphicsElement(tagName, document)
+inline SVGCircleElement::SVGCircleElement(Document& document)
+ : SVGGeometryElement(SVGNames::circleTag, document)
, m_cx(LengthModeWidth)
, m_cy(LengthModeHeight)
, m_r(LengthModeOther)
{
- ASSERT(hasTagName(SVGNames::circleTag));
ScriptWrappable::init(this);
registerAnimatedPropertiesForSVGCircleElement();
}
-PassRefPtr<SVGCircleElement> SVGCircleElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGCircleElement> SVGCircleElement::create(Document& document)
{
- return adoptRef(new SVGCircleElement(tagName, document));
+ return adoptRef(new SVGCircleElement(document));
}
bool SVGCircleElement::isSupportedAttribute(const QualifiedName& attrName)
{
DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
if (supportedAttributes.isEmpty()) {
- SVGLangSpace::addSupportedAttributes(supportedAttributes);
SVGExternalResourcesRequired::addSupportedAttributes(supportedAttributes);
supportedAttributes.add(SVGNames::cxAttr);
supportedAttributes.add(SVGNames::cyAttr);
@@ -78,15 +75,14 @@ void SVGCircleElement::parseAttribute(const QualifiedName& name, const AtomicStr
SVGParsingError parseError = NoError;
if (!isSupportedAttribute(name))
- SVGGraphicsElement::parseAttribute(name, value);
+ SVGGeometryElement::parseAttribute(name, value);
else if (name == SVGNames::cxAttr)
setCxBaseValue(SVGLength::construct(LengthModeWidth, value, parseError));
else if (name == SVGNames::cyAttr)
setCyBaseValue(SVGLength::construct(LengthModeHeight, value, parseError));
else if (name == SVGNames::rAttr)
setRBaseValue(SVGLength::construct(LengthModeOther, value, parseError, ForbidNegativeLengths));
- else if (SVGLangSpace::parseAttribute(name, value)
- || SVGExternalResourcesRequired::parseAttribute(name, value)) {
+ else if (SVGExternalResourcesRequired::parseAttribute(name, value)) {
} else
ASSERT_NOT_REACHED();
@@ -96,7 +92,7 @@ void SVGCircleElement::parseAttribute(const QualifiedName& name, const AtomicStr
void SVGCircleElement::svgAttributeChanged(const QualifiedName& attrName)
{
if (!isSupportedAttribute(attrName)) {
- SVGGraphicsElement::svgAttributeChanged(attrName);
+ SVGGeometryElement::svgAttributeChanged(attrName);
return;
}
@@ -119,7 +115,7 @@ void SVGCircleElement::svgAttributeChanged(const QualifiedName& attrName)
return;
}
- if (SVGLangSpace::isKnownAttribute(attrName) || SVGExternalResourcesRequired::isKnownAttribute(attrName)) {
+ if (SVGExternalResourcesRequired::isKnownAttribute(attrName)) {
RenderSVGResource::markForLayoutAndParentResourceInvalidation(renderer);
return;
}
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGCircleElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGCircleElement.h
index ae702f6974f..eb689f8d31d 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGCircleElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGCircleElement.h
@@ -25,17 +25,17 @@
#include "core/svg/SVGAnimatedBoolean.h"
#include "core/svg/SVGAnimatedLength.h"
#include "core/svg/SVGExternalResourcesRequired.h"
-#include "core/svg/SVGGraphicsElement.h"
+#include "core/svg/SVGGeometryElement.h"
namespace WebCore {
-class SVGCircleElement FINAL : public SVGGraphicsElement,
+class SVGCircleElement FINAL : public SVGGeometryElement,
public SVGExternalResourcesRequired {
public:
- static PassRefPtr<SVGCircleElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGCircleElement> create(Document&);
private:
- SVGCircleElement(const QualifiedName&, Document&);
+ explicit SVGCircleElement(Document&);
virtual bool isValid() const { return SVGTests::isValid(); }
virtual bool supportsFocus() const OVERRIDE { return hasFocusEventListeners(); }
@@ -56,11 +56,7 @@ private:
END_DECLARE_ANIMATED_PROPERTIES
};
-inline SVGCircleElement* toSVGCircleElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(SVGNames::circleTag));
- return static_cast<SVGCircleElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(SVGCircleElement, hasTagName(SVGNames::circleTag));
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGCircleElement.idl b/chromium/third_party/WebKit/Source/core/svg/SVGCircleElement.idl
index 00ef676895a..67f3d445648 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGCircleElement.idl
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGCircleElement.idl
@@ -24,7 +24,7 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-interface SVGCircleElement : SVGGraphicsElement {
+interface SVGCircleElement : SVGGeometryElement {
readonly attribute SVGAnimatedLength cx;
readonly attribute SVGAnimatedLength cy;
readonly attribute SVGAnimatedLength r;
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGClipPathElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGClipPathElement.cpp
index de8058f0c50..c4224f1cfa5 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGClipPathElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGClipPathElement.cpp
@@ -23,7 +23,6 @@
#include "core/svg/SVGClipPathElement.h"
-#include "SVGNames.h"
#include "core/rendering/svg/RenderSVGResourceClipper.h"
#include "core/svg/SVGElementInstance.h"
@@ -39,18 +38,17 @@ BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGClipPathElement)
REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
END_REGISTER_ANIMATED_PROPERTIES
-inline SVGClipPathElement::SVGClipPathElement(const QualifiedName& tagName, Document& document)
- : SVGGraphicsElement(tagName, document)
+inline SVGClipPathElement::SVGClipPathElement(Document& document)
+ : SVGGraphicsElement(SVGNames::clipPathTag, document)
, m_clipPathUnits(SVGUnitTypes::SVG_UNIT_TYPE_USERSPACEONUSE)
{
- ASSERT(hasTagName(SVGNames::clipPathTag));
ScriptWrappable::init(this);
registerAnimatedPropertiesForSVGClipPathElement();
}
-PassRefPtr<SVGClipPathElement> SVGClipPathElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGClipPathElement> SVGClipPathElement::create(Document& document)
{
- return adoptRef(new SVGClipPathElement(tagName, document));
+ return adoptRef(new SVGClipPathElement(document));
}
bool SVGClipPathElement::isSupportedAttribute(const QualifiedName& attrName)
@@ -92,8 +90,9 @@ void SVGClipPathElement::svgAttributeChanged(const QualifiedName& attrName)
SVGElementInstance::InvalidationGuard invalidationGuard(this);
- if (RenderObject* object = renderer())
- object->setNeedsLayout();
+ RenderSVGResourceContainer* renderer = toRenderSVGResourceContainer(this->renderer());
+ if (renderer)
+ renderer->invalidateCacheAndMarkForLayout();
}
void SVGClipPathElement::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGClipPathElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGClipPathElement.h
index 80f6be944ea..0b0baec5ec7 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGClipPathElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGClipPathElement.h
@@ -35,10 +35,10 @@ class RenderObject;
class SVGClipPathElement FINAL : public SVGGraphicsElement,
public SVGExternalResourcesRequired {
public:
- static PassRefPtr<SVGClipPathElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGClipPathElement> create(Document&);
private:
- SVGClipPathElement(const QualifiedName&, Document&);
+ explicit SVGClipPathElement(Document&);
virtual bool isValid() const { return SVGTests::isValid(); }
virtual bool needsPendingResourceHandling() const { return false; }
@@ -56,11 +56,7 @@ private:
END_DECLARE_ANIMATED_PROPERTIES
};
-inline SVGClipPathElement* toSVGClipPathElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(SVGNames::clipPathTag));
- return static_cast<SVGClipPathElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(SVGClipPathElement, hasTagName(SVGNames::clipPathTag));
}
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGColor.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGColor.cpp
index 5253f89a7f5..788ecf8d9f4 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGColor.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGColor.cpp
@@ -54,24 +54,24 @@ Color SVGColor::colorFromRGBColorString(const String& colorString)
return Color();
}
-void SVGColor::setRGBColor(const String&, ExceptionState& es)
+void SVGColor::setRGBColor(const String&, ExceptionState& exceptionState)
{
// The whole SVGColor interface is deprecated in SVG 1.1 (2nd edition).
// The setters are the most problematic part so we remove the support for those first.
- es.throwDOMException(NoModificationAllowedError);
+ exceptionState.throwUninformativeAndGenericDOMException(NoModificationAllowedError);
}
-void SVGColor::setRGBColorICCColor(const String&, const String&, ExceptionState& es)
+void SVGColor::setRGBColorICCColor(const String&, const String&, ExceptionState& exceptionState)
{
- es.throwDOMException(NoModificationAllowedError);
+ exceptionState.throwUninformativeAndGenericDOMException(NoModificationAllowedError);
}
-void SVGColor::setColor(unsigned short, const String&, const String&, ExceptionState& es)
+void SVGColor::setColor(unsigned short, const String&, const String&, ExceptionState& exceptionState)
{
- es.throwDOMException(NoModificationAllowedError);
+ exceptionState.throwUninformativeAndGenericDOMException(NoModificationAllowedError);
}
-String SVGColor::customCssText() const
+String SVGColor::customCSSText() const
{
switch (m_colorType) {
case SVG_COLORTYPE_UNKNOWN:
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGColor.h b/chromium/third_party/WebKit/Source/core/svg/SVGColor.h
index 554fe77052b..03416661228 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGColor.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGColor.h
@@ -23,7 +23,7 @@
#define SVGColor_h
#include "core/css/CSSValue.h"
-#include "core/platform/graphics/Color.h"
+#include "platform/graphics/Color.h"
#include "wtf/PassRefPtr.h"
namespace WebCore {
@@ -69,7 +69,7 @@ public:
void setRGBColorICCColor(const String& rgbColor, const String& iccColor, ExceptionState&);
void setColor(unsigned short colorType, const String& rgbColor, const String& iccColor, ExceptionState&);
- String customCssText() const;
+ String customCSSText() const;
~SVGColor() { }
@@ -93,6 +93,8 @@ private:
SVGColorType m_colorType;
};
+DEFINE_CSS_VALUE_TYPE_CASTS(SVGColor, isSVGColor());
+
} // namespace WebCore
#endif // SVGColor_h
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGComponentTransferFunctionElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGComponentTransferFunctionElement.h
index 8a6bbd95984..b794e710d92 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGComponentTransferFunctionElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGComponentTransferFunctionElement.h
@@ -21,10 +21,10 @@
#ifndef SVGComponentTransferFunctionElement_h
#define SVGComponentTransferFunctionElement_h
-#include "core/platform/graphics/filters/FEComponentTransfer.h"
#include "core/svg/SVGAnimatedEnumeration.h"
#include "core/svg/SVGAnimatedNumber.h"
#include "core/svg/SVGAnimatedNumberList.h"
+#include "platform/graphics/filters/FEComponentTransfer.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGCursorElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGCursorElement.cpp
index f83ffa93a73..5473a2f3084 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGCursorElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGCursorElement.cpp
@@ -43,19 +43,18 @@ BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGCursorElement)
REGISTER_PARENT_ANIMATED_PROPERTIES(SVGTests)
END_REGISTER_ANIMATED_PROPERTIES
-inline SVGCursorElement::SVGCursorElement(const QualifiedName& tagName, Document& document)
- : SVGElement(tagName, document)
+inline SVGCursorElement::SVGCursorElement(Document& document)
+ : SVGElement(SVGNames::cursorTag, document)
, m_x(LengthModeWidth)
, m_y(LengthModeHeight)
{
- ASSERT(hasTagName(SVGNames::cursorTag));
ScriptWrappable::init(this);
registerAnimatedPropertiesForSVGCursorElement();
}
-PassRefPtr<SVGCursorElement> SVGCursorElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGCursorElement> SVGCursorElement::create(Document& document)
{
- return adoptRef(new SVGCursorElement(tagName, document));
+ return adoptRef(new SVGCursorElement(document));
}
SVGCursorElement::~SVGCursorElement()
@@ -134,11 +133,4 @@ void SVGCursorElement::svgAttributeChanged(const QualifiedName& attrName)
(*it)->setNeedsStyleRecalc();
}
-void SVGCursorElement::addSubresourceAttributeURLs(ListHashSet<KURL>& urls) const
-{
- SVGElement::addSubresourceAttributeURLs(urls);
-
- addSubresourceURL(urls, document().completeURL(hrefCurrentValue()));
-}
-
}
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGCursorElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGCursorElement.h
index eb93d4a4fee..57011308521 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGCursorElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGCursorElement.h
@@ -36,7 +36,7 @@ class SVGCursorElement FINAL : public SVGElement,
public SVGExternalResourcesRequired,
public SVGURIReference {
public:
- static PassRefPtr<SVGCursorElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGCursorElement> create(Document&);
virtual ~SVGCursorElement();
@@ -45,7 +45,7 @@ public:
void removeReferencedElement(SVGElement*);
private:
- SVGCursorElement(const QualifiedName&, Document&);
+ explicit SVGCursorElement(Document&);
virtual bool isValid() const { return SVGTests::isValid(); }
@@ -53,8 +53,6 @@ private:
virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
virtual void svgAttributeChanged(const QualifiedName&);
- virtual void addSubresourceAttributeURLs(ListHashSet<KURL>&) const;
-
virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE { return false; }
BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGCursorElement)
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGDefsElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGDefsElement.cpp
index 4b2d39b52f1..ae425f37ecf 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGDefsElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGDefsElement.cpp
@@ -35,17 +35,16 @@ BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGDefsElement)
REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
END_REGISTER_ANIMATED_PROPERTIES
-inline SVGDefsElement::SVGDefsElement(const QualifiedName& tagName, Document& document)
- : SVGGraphicsElement(tagName, document)
+inline SVGDefsElement::SVGDefsElement(Document& document)
+ : SVGGraphicsElement(SVGNames::defsTag, document)
{
- ASSERT(hasTagName(SVGNames::defsTag));
ScriptWrappable::init(this);
registerAnimatedPropertiesForSVGDefsElement();
}
-PassRefPtr<SVGDefsElement> SVGDefsElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGDefsElement> SVGDefsElement::create(Document& document)
{
- return adoptRef(new SVGDefsElement(tagName, document));
+ return adoptRef(new SVGDefsElement(document));
}
bool SVGDefsElement::isValid() const
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGDefsElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGDefsElement.h
index b29d526c924..60ff06beb4a 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGDefsElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGDefsElement.h
@@ -30,10 +30,10 @@ namespace WebCore {
class SVGDefsElement FINAL : public SVGGraphicsElement,
public SVGExternalResourcesRequired {
public:
- static PassRefPtr<SVGDefsElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGDefsElement> create(Document&);
private:
- SVGDefsElement(const QualifiedName&, Document&);
+ explicit SVGDefsElement(Document&);
virtual bool isValid() const;
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGDescElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGDescElement.cpp
index 219bedaf093..9696aa1c04e 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGDescElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGDescElement.cpp
@@ -24,16 +24,15 @@
namespace WebCore {
-inline SVGDescElement::SVGDescElement(const QualifiedName& tagName, Document& document)
- : SVGElement(tagName, document)
+inline SVGDescElement::SVGDescElement(Document& document)
+ : SVGElement(SVGNames::descTag, document)
{
- ASSERT(hasTagName(SVGNames::descTag));
ScriptWrappable::init(this);
}
-PassRefPtr<SVGDescElement> SVGDescElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGDescElement> SVGDescElement::create(Document& document)
{
- return adoptRef(new SVGDescElement(tagName, document));
+ return adoptRef(new SVGDescElement(document));
}
String SVGDescElement::description() const
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGDescElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGDescElement.h
index 2c8cfa65971..181053dc0a1 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGDescElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGDescElement.h
@@ -27,12 +27,12 @@ namespace WebCore {
class SVGDescElement FINAL : public SVGElement {
public:
- static PassRefPtr<SVGDescElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGDescElement> create(Document&);
String description() const;
private:
- SVGDescElement(const QualifiedName&, Document&);
+ explicit SVGDescElement(Document&);
virtual bool rendererIsNeeded(const RenderStyle&) { return false; }
};
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGDocument.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGDocument.cpp
index c82b6e73b65..876b66f645a 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGDocument.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGDocument.cpp
@@ -23,8 +23,8 @@
#include "SVGNames.h"
#include "bindings/v8/ExceptionStatePlaceholder.h"
-#include "core/dom/EventNames.h"
-#include "core/page/FrameView.h"
+#include "core/events/ThreadLocalEventNames.h"
+#include "core/frame/FrameView.h"
#include "core/rendering/RenderView.h"
#include "core/svg/SVGElement.h"
#include "core/svg/SVGSVGElement.h"
@@ -51,8 +51,8 @@ SVGSVGElement* SVGDocument::rootElement() const
void SVGDocument::dispatchZoomEvent(float prevScale, float newScale)
{
- RefPtr<SVGZoomEvent> event = static_pointer_cast<SVGZoomEvent>(createEvent("SVGZoomEvents", IGNORE_EXCEPTION));
- event->initEvent(eventNames().zoomEvent, true, false);
+ RefPtr<SVGZoomEvent> event = SVGZoomEvent::create();
+ event->initEvent(EventTypeNames::zoom, true, false);
event->setPreviousScale(prevScale);
event->setNewScale(newScale);
rootElement()->dispatchEvent(event.release(), IGNORE_EXCEPTION);
@@ -60,8 +60,8 @@ void SVGDocument::dispatchZoomEvent(float prevScale, float newScale)
void SVGDocument::dispatchScrollEvent()
{
- RefPtr<Event> event = createEvent("SVGEvents", IGNORE_EXCEPTION);
- event->initEvent(eventNames().scrollEvent, true, false);
+ RefPtr<Event> event = Event::create();
+ event->initEvent(EventTypeNames::scroll, true, false);
rootElement()->dispatchEvent(event.release(), IGNORE_EXCEPTION);
}
@@ -101,4 +101,9 @@ bool SVGDocument::childShouldCreateRenderer(const Node& child) const
return true;
}
+PassRefPtr<Document> SVGDocument::cloneDocumentWithoutChildren()
+{
+ return create(DocumentInit(url()));
+}
+
}
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGDocument.h b/chromium/third_party/WebKit/Source/core/svg/SVGDocument.h
index bddf66f45bd..a9b3392c398 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGDocument.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGDocument.h
@@ -22,7 +22,7 @@
#define SVGDocument_h
#include "core/dom/Document.h"
-#include "core/platform/graphics/FloatPoint.h"
+#include "platform/geometry/FloatPoint.h"
namespace WebCore {
@@ -45,6 +45,8 @@ public:
void startPan(const FloatPoint& start);
void updatePan(const FloatPoint& pos) const;
+ virtual PassRefPtr<Document> cloneDocumentWithoutChildren() OVERRIDE FINAL;
+
private:
explicit SVGDocument(const DocumentInit&);
@@ -53,20 +55,7 @@ private:
FloatPoint m_translate;
};
-inline SVGDocument* toSVGDocument(Document* document)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!document || document->isSVGDocument());
- return static_cast<SVGDocument*>(document);
-}
-
-inline const SVGDocument* toSVGDocument(const Document* document)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!document || document->isSVGDocument());
- return static_cast<const SVGDocument*>(document);
-}
-
-// This will catch anyone doing an unnecessary cast.
-void toSVGDocument(const SVGDocument*);
+DEFINE_DOCUMENT_TYPE_CASTS(SVGDocument);
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGDocument.idl b/chromium/third_party/WebKit/Source/core/svg/SVGDocument.idl
index 64ec90c33c8..dced4119455 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGDocument.idl
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGDocument.idl
@@ -19,9 +19,7 @@
* Boston, MA 02110-1301, USA.
*/
-[
- CustomToV8
-] interface SVGDocument : Document {
+interface SVGDocument : Document {
readonly attribute SVGSVGElement rootElement;
// Overwrite the one in events::DocumentEvent
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGDocumentExtensions.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGDocumentExtensions.cpp
index 4542e506be9..a135845e036 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGDocumentExtensions.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGDocumentExtensions.cpp
@@ -28,6 +28,7 @@
#include "core/svg/SVGElement.h"
#include "core/svg/SVGSVGElement.h"
#include "core/svg/animation/SMILTimeContainer.h"
+#include "wtf/TemporaryChange.h"
#include "wtf/text/AtomicString.h"
namespace WebCore {
@@ -35,6 +36,9 @@ namespace WebCore {
SVGDocumentExtensions::SVGDocumentExtensions(Document* document)
: m_document(document)
, m_resourcesCache(adoptPtr(new SVGResourcesCache))
+#if !ASSERT_DISABLED
+ , m_inRelativeLengthSVGRootsInvalidation(false)
+#endif
{
}
@@ -367,6 +371,35 @@ void SVGDocumentExtensions::removeAllElementReferencesForTarget(SVGElement* refe
m_elementDependencies.remove(it);
}
+void SVGDocumentExtensions::addSVGRootWithRelativeLengthDescendents(SVGSVGElement* svgRoot)
+{
+ ASSERT(!m_inRelativeLengthSVGRootsInvalidation);
+ m_relativeLengthSVGRoots.add(svgRoot);
+}
+
+void SVGDocumentExtensions::removeSVGRootWithRelativeLengthDescendents(SVGSVGElement* svgRoot)
+{
+ ASSERT(!m_inRelativeLengthSVGRootsInvalidation);
+ m_relativeLengthSVGRoots.remove(svgRoot);
+}
+
+bool SVGDocumentExtensions::isSVGRootWithRelativeLengthDescendents(SVGSVGElement* svgRoot) const
+{
+ return m_relativeLengthSVGRoots.contains(svgRoot);
+}
+
+void SVGDocumentExtensions::invalidateSVGRootsWithRelativeLengthDescendents(SubtreeLayoutScope* scope)
+{
+ ASSERT(!m_inRelativeLengthSVGRootsInvalidation);
+#if !ASSERT_DISABLED
+ TemporaryChange<bool> inRelativeLengthSVGRootsChange(m_inRelativeLengthSVGRootsInvalidation, true);
+#endif
+
+ HashSet<SVGSVGElement*>::iterator end = m_relativeLengthSVGRoots.end();
+ for (HashSet<SVGSVGElement*>::iterator it = m_relativeLengthSVGRoots.begin(); it != end; ++it)
+ (*it)->invalidateRelativeLengthClients(scope);
+}
+
#if ENABLE(SVG_FONTS)
void SVGDocumentExtensions::registerSVGFontFaceElement(SVGFontFaceElement* element)
{
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGDocumentExtensions.h b/chromium/third_party/WebKit/Source/core/svg/SVGDocumentExtensions.h
index 1223dd3291c..abf4a68172e 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGDocumentExtensions.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGDocumentExtensions.h
@@ -30,6 +30,7 @@ namespace WebCore {
class Document;
class RenderSVGResourceContainer;
+class SubtreeLayoutScope;
class SVGElement;
#if ENABLE(SVG_FONTS)
class SVGFontFaceElement;
@@ -69,6 +70,11 @@ public:
void rebuildAllElementReferencesForTarget(SVGElement*);
void removeAllElementReferencesForTarget(SVGElement*);
+ void addSVGRootWithRelativeLengthDescendents(SVGSVGElement*);
+ void removeSVGRootWithRelativeLengthDescendents(SVGSVGElement*);
+ bool isSVGRootWithRelativeLengthDescendents(SVGSVGElement*) const;
+ void invalidateSVGRootsWithRelativeLengthDescendents(SubtreeLayoutScope*);
+
#if ENABLE(SVG_FONTS)
const HashSet<SVGFontFaceElement*>& svgFontFaceElements() const { return m_svgFontFaceElements; }
void registerSVGFontFaceElement(SVGFontFaceElement*);
@@ -86,6 +92,10 @@ private:
HashMap<AtomicString, OwnPtr<SVGPendingElements> > m_pendingResourcesForRemoval; // Resources that are pending and scheduled for removal.
HashMap<SVGElement*, OwnPtr<HashSet<SVGElement*> > > m_elementDependencies;
OwnPtr<SVGResourcesCache> m_resourcesCache;
+ HashSet<SVGSVGElement*> m_relativeLengthSVGRoots; // Root SVG elements with relative length descendants.
+#if !ASSERT_DISABLED
+ bool m_inRelativeLengthSVGRootsInvalidation;
+#endif
public:
// This HashMap contains a list of pending resources. Pending resources, are such
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGElement.cpp
index 6fe95edfb35..0ab482d46c4 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGElement.cpp
@@ -32,10 +32,9 @@
#include "bindings/v8/ScriptEventListener.h"
#include "core/css/CSSCursorImageValue.h"
#include "core/css/CSSParser.h"
-#include "core/dom/DOMImplementation.h"
#include "core/dom/Document.h"
#include "core/dom/ElementTraversal.h"
-#include "core/dom/Event.h"
+#include "core/events/Event.h"
#include "core/dom/shadow/ShadowRoot.h"
#include "core/rendering/RenderObject.h"
#include "core/rendering/svg/RenderSVGResourceContainer.h"
@@ -76,6 +75,8 @@ SVGElement::SVGElement(const QualifiedName& tagName, Document& document, Constru
#if !ASSERT_DISABLED
, m_inRelativeLengthClientsInvalidation(false)
#endif
+ , m_animatedPropertiesDestructed(false)
+ , m_isContextElement(false)
{
ScriptWrappable::init(this);
registerAnimatedPropertiesForSVGElement();
@@ -84,12 +85,22 @@ SVGElement::SVGElement(const QualifiedName& tagName, Document& document, Constru
SVGElement::~SVGElement()
{
+ ASSERT(inDocument() || !hasRelativeLengths());
+}
+
+void
+SVGElement::cleanupAnimatedProperties()
+{
+ if (m_animatedPropertiesDestructed)
+ return;
+ m_animatedPropertiesDestructed = true;
+
if (!hasSVGRareData())
ASSERT(!SVGElementRareData::rareDataMap().contains(this));
else {
SVGElementRareData::SVGElementRareDataMap& rareDataMap = SVGElementRareData::rareDataMap();
SVGElementRareData::SVGElementRareDataMap::iterator it = rareDataMap.find(this);
- ASSERT(it != rareDataMap.end());
+ ASSERT_WITH_SECURITY_IMPLICATION(it != rareDataMap.end());
SVGElementRareData* rareData = it->value;
rareData->destroyAnimatedSMILStyleProperties();
@@ -111,8 +122,7 @@ SVGElement::~SVGElement()
}
document().accessSVGExtensions()->rebuildAllElementReferencesForTarget(this);
document().accessSVGExtensions()->removeAllElementReferencesForTarget(this);
-
- ASSERT(inDocument() || !hasRelativeLengths());
+ SVGAnimatedProperty::detachAnimatedPropertiesForElement(this);
}
void SVGElement::willRecalcStyle(StyleRecalcChange change)
@@ -228,12 +238,6 @@ void SVGElement::reportAttributeParsingError(SVGParsingError error, const Qualif
ASSERT_NOT_REACHED();
}
-
-bool SVGElement::isSupported(StringImpl* feature, StringImpl* version) const
-{
- return DOMImplementation::hasFeature(feature, version);
-}
-
String SVGElement::title() const
{
// According to spec, we should not return titles when hovering over root <svg> elements (those
@@ -260,8 +264,8 @@ String SVGElement::title() const
// If we aren't an instance in a <use> or the <use> title was not found, then find the first
// <title> child of this element.
- Element* titleElement = ElementTraversal::firstWithin(this);
- for (; titleElement; titleElement = ElementTraversal::nextSkippingChildren(titleElement, this)) {
+ Element* titleElement = ElementTraversal::firstWithin(*this);
+ for (; titleElement; titleElement = ElementTraversal::nextSkippingChildren(*titleElement, this)) {
if (titleElement->hasTagName(SVGNames::titleTag) && titleElement->isSVGElement())
break;
}
@@ -291,10 +295,6 @@ PassRefPtr<CSSValue> SVGElement::getPresentationAttribute(const String& name)
return cssValue ? cssValue->cloneForCSSOM() : 0;
}
-bool SVGElement::isKnownAttribute(const QualifiedName& attrName)
-{
- return isIdAttributeName(attrName);
-}
bool SVGElement::instanceUpdatesBlocked() const
{
@@ -307,7 +307,7 @@ void SVGElement::setInstanceUpdatesBlocked(bool value)
svgRareData()->setInstanceUpdatesBlocked(value);
}
-AffineTransform SVGElement::localCoordinateSpaceTransform(SVGLocatable::CTMScope) const
+AffineTransform SVGElement::localCoordinateSpaceTransform(CTMScope) const
{
// To be overriden by SVGGraphicsElement (or as special case SVGTextElement and SVGPatternElement)
return AffineTransform();
@@ -318,11 +318,31 @@ String SVGElement::xmlbase() const
return fastGetAttribute(XMLNames::baseAttr);
}
-void SVGElement::setXmlbase(const String& value)
+void SVGElement::setXMLbase(const String& value)
{
setAttribute(XMLNames::baseAttr, value);
}
+String SVGElement::xmllang() const
+{
+ return fastGetAttribute(XMLNames::langAttr);
+}
+
+void SVGElement::setXMLlang(const String& value)
+{
+ setAttribute(XMLNames::langAttr, value);
+}
+
+String SVGElement::xmlspace() const
+{
+ return fastGetAttribute(XMLNames::spaceAttr);
+}
+
+void SVGElement::setXMLspace(const String& value)
+{
+ setAttribute(XMLNames::spaceAttr, value);
+}
+
Node::InsertionNotificationRequest SVGElement::insertedInto(ContainerNode* rootParent)
{
Element::insertedInto(rootParent);
@@ -447,6 +467,8 @@ CSSPropertyID SVGElement::cssPropertyIdForSVGAttributeName(const QualifiedName&
void SVGElement::updateRelativeLengthsInformation(bool clientHasRelativeLengths, SVGElement* clientElement)
{
+ ASSERT(clientElement);
+
// If we're not yet in a document, this function will be called again from insertedInto(). Do nothing now.
if (!inDocument())
return;
@@ -464,13 +486,22 @@ void SVGElement::updateRelativeLengthsInformation(bool clientHasRelativeLengths,
else
currentElement->m_elementsWithRelativeLengths.remove(clientElement);
- // If the relative length state hasn't changed, we can stop propagating the notfication.
+ // If the relative length state hasn't changed, we can stop propagating the notification.
if (hadRelativeLengths == currentElement->hasRelativeLengths())
- break;
+ return;
clientElement = currentElement;
clientHasRelativeLengths = clientElement->hasRelativeLengths();
}
+
+ // Register root SVG elements for top level viewport change notifications.
+ if (clientElement->isSVGSVGElement()) {
+ SVGDocumentExtensions* svgExtensions = accessDocumentSVGExtensions();
+ if (clientElement->hasRelativeLengths())
+ svgExtensions->addSVGRootWithRelativeLengthDescendents(toSVGSVGElement(clientElement));
+ else
+ svgExtensions->removeSVGRootWithRelativeLengthDescendents(toSVGSVGElement(clientElement));
+ }
}
void SVGElement::invalidateRelativeLengthClients(SubtreeLayoutScope* layoutScope)
@@ -483,15 +514,18 @@ void SVGElement::invalidateRelativeLengthClients(SubtreeLayoutScope* layoutScope
TemporaryChange<bool> inRelativeLengthClientsInvalidationChange(m_inRelativeLengthClientsInvalidation, true);
#endif
+ RenderObject* renderer = this->renderer();
+ if (renderer && selfHasRelativeLengths()) {
+ if (renderer->isSVGResourceContainer())
+ toRenderSVGResourceContainer(renderer)->invalidateCacheAndMarkForLayout(layoutScope);
+ else
+ renderer->setNeedsLayout(MarkContainingBlockChain, layoutScope);
+ }
+
HashSet<SVGElement*>::iterator end = m_elementsWithRelativeLengths.end();
for (HashSet<SVGElement*>::iterator it = m_elementsWithRelativeLengths.begin(); it != end; ++it) {
- if (*it == this)
- continue;
-
- if ((*it)->renderer() && (*it)->selfHasRelativeLengths())
- (*it)->renderer()->setNeedsLayout(MarkContainingBlockChain, layoutScope);
-
- (*it)->invalidateRelativeLengthClients(layoutScope);
+ if (*it != this)
+ (*it)->invalidateRelativeLengthClients(layoutScope);
}
}
@@ -560,13 +594,13 @@ const HashSet<SVGElementInstance*>& SVGElement::instancesForElement() const
return svgRareData()->elementInstances();
}
-bool SVGElement::getBoundingBox(FloatRect& rect, SVGLocatable::StyleUpdateStrategy styleUpdateStrategy)
+bool SVGElement::getBoundingBox(FloatRect& rect)
{
- if (isSVGGraphicsElement()) {
- rect = toSVGGraphicsElement(this)->getBBox(styleUpdateStrategy);
- return true;
- }
- return false;
+ if (!isSVGGraphicsElement())
+ return false;
+
+ rect = toSVGGraphicsElement(this)->getBBox();
+ return true;
}
void SVGElement::setCursorElement(SVGCursorElement* cursorElement)
@@ -618,36 +652,42 @@ void SVGElement::parseAttribute(const QualifiedName& name, const AtomicString& v
{
// standard events
if (name == onloadAttr)
- setAttributeEventListener(eventNames().loadEvent, createAttributeEventListener(this, name, value));
+ setAttributeEventListener(EventTypeNames::load, createAttributeEventListener(this, name, value));
+ else if (name == onbeginAttr)
+ setAttributeEventListener(EventTypeNames::beginEvent, createAttributeEventListener(this, name, value));
+ else if (name == onendAttr)
+ setAttributeEventListener(EventTypeNames::endEvent, createAttributeEventListener(this, name, value));
+ else if (name == onrepeatAttr)
+ setAttributeEventListener(EventTypeNames::repeatEvent, createAttributeEventListener(this, name, value));
else if (name == onclickAttr)
- setAttributeEventListener(eventNames().clickEvent, createAttributeEventListener(this, name, value));
+ setAttributeEventListener(EventTypeNames::click, createAttributeEventListener(this, name, value));
else if (name == onmousedownAttr)
- setAttributeEventListener(eventNames().mousedownEvent, createAttributeEventListener(this, name, value));
+ setAttributeEventListener(EventTypeNames::mousedown, createAttributeEventListener(this, name, value));
else if (name == onmouseenterAttr)
- setAttributeEventListener(eventNames().mouseenterEvent, createAttributeEventListener(this, name, value));
+ setAttributeEventListener(EventTypeNames::mouseenter, createAttributeEventListener(this, name, value));
else if (name == onmouseleaveAttr)
- setAttributeEventListener(eventNames().mouseleaveEvent, createAttributeEventListener(this, name, value));
+ setAttributeEventListener(EventTypeNames::mouseleave, createAttributeEventListener(this, name, value));
else if (name == onmousemoveAttr)
- setAttributeEventListener(eventNames().mousemoveEvent, createAttributeEventListener(this, name, value));
+ setAttributeEventListener(EventTypeNames::mousemove, createAttributeEventListener(this, name, value));
else if (name == onmouseoutAttr)
- setAttributeEventListener(eventNames().mouseoutEvent, createAttributeEventListener(this, name, value));
+ setAttributeEventListener(EventTypeNames::mouseout, createAttributeEventListener(this, name, value));
else if (name == onmouseoverAttr)
- setAttributeEventListener(eventNames().mouseoverEvent, createAttributeEventListener(this, name, value));
+ setAttributeEventListener(EventTypeNames::mouseover, createAttributeEventListener(this, name, value));
else if (name == onmouseupAttr)
- setAttributeEventListener(eventNames().mouseupEvent, createAttributeEventListener(this, name, value));
+ setAttributeEventListener(EventTypeNames::mouseup, createAttributeEventListener(this, name, value));
else if (name == SVGNames::onfocusinAttr)
- setAttributeEventListener(eventNames().focusinEvent, createAttributeEventListener(this, name, value));
+ setAttributeEventListener(EventTypeNames::focusin, createAttributeEventListener(this, name, value));
else if (name == SVGNames::onfocusoutAttr)
- setAttributeEventListener(eventNames().focusoutEvent, createAttributeEventListener(this, name, value));
+ setAttributeEventListener(EventTypeNames::focusout, createAttributeEventListener(this, name, value));
else if (name == SVGNames::onactivateAttr)
- setAttributeEventListener(eventNames().DOMActivateEvent, createAttributeEventListener(this, name, value));
+ setAttributeEventListener(EventTypeNames::DOMActivate, createAttributeEventListener(this, name, value));
else if (name == HTMLNames::classAttr) {
// SVG animation has currently requires special storage of values so we set
// the className here. svgAttributeChanged actually causes the resulting
// style updates (instead of Element::parseAttribute). We don't
// tell Element about the change to avoid parsing the class list twice
setClassNameBaseValue(value);
- } else if (SVGLangSpace::parseAttribute(name, value)) {
+ } else if (name.matches(XMLNames::langAttr) || name.matches(XMLNames::spaceAttr)) {
} else
Element::parseAttribute(name, value);
}
@@ -842,11 +882,11 @@ bool SVGElement::removeEventListener(const AtomicString& eventType, EventListene
static bool hasLoadListener(Element* element)
{
- if (element->hasEventListeners(eventNames().loadEvent))
+ if (element->hasEventListeners(EventTypeNames::load))
return true;
for (element = element->parentOrShadowHostElement(); element; element = element->parentOrShadowHostElement()) {
- const EventListenerVector& entry = element->getEventListeners(eventNames().loadEvent);
+ const EventListenerVector& entry = element->getEventListeners(EventTypeNames::load);
for (size_t i = 0; i < entry.size(); ++i) {
if (entry[i].useCapture)
return true;
@@ -870,9 +910,9 @@ void SVGElement::sendSVGLoadEventIfPossible(bool sendParentLoadEvents)
if (sendParentLoadEvents)
parent = currentTarget->parentOrShadowHostElement(); // save the next parent to dispatch too incase dispatching the event changes the tree
if (hasLoadListener(currentTarget.get()))
- currentTarget->dispatchEvent(Event::create(eventNames().loadEvent));
+ currentTarget->dispatchEvent(Event::create(EventTypeNames::load));
currentTarget = (parent && parent->isSVGElement()) ? static_pointer_cast<SVGElement>(parent) : RefPtr<SVGElement>();
- SVGElement* element = toSVGElement(currentTarget.get());
+ SVGElement* element = currentTarget.get();
if (!element || !element->isOutermostSVGSVGElement())
continue;
@@ -970,7 +1010,7 @@ void SVGElement::svgAttributeChanged(const QualifiedName& attrName)
RenderObject* object = renderer();
// Notify resources about id changes, this is important as we cache resources by id in SVGDocumentExtensions
if (object && object->isSVGResourceContainer())
- object->toRenderSVGResourceContainer()->idChanged();
+ toRenderSVGResourceContainer(object)->idChanged();
if (inDocument())
buildPendingResourcesIfNeeded();
SVGElementInstance::invalidateAllInstancesOfElement(this);
@@ -1012,7 +1052,7 @@ void SVGElement::synchronizeSystemLanguage(SVGElement* contextElement)
PassRefPtr<RenderStyle> SVGElement::customStyleForRenderer()
{
if (!correspondingElement())
- return document().styleResolver()->styleForElement(this);
+ return document().ensureStyleResolver().styleForElement(this);
RenderStyle* style = 0;
if (Element* parent = parentOrShadowHostElement()) {
@@ -1020,7 +1060,7 @@ PassRefPtr<RenderStyle> SVGElement::customStyleForRenderer()
style = renderer->style();
}
- return document().styleResolver()->styleForElement(correspondingElement(), style, DisallowStyleSharing);
+ return document().ensureStyleResolver().styleForElement(correspondingElement(), style, DisallowStyleSharing);
}
MutableStylePropertySet* SVGElement::animatedSMILStyleProperties() const
@@ -1057,9 +1097,7 @@ RenderStyle* SVGElement::computedStyle(PseudoId pseudoElementSpecifier)
bool SVGElement::hasFocusEventListeners() const
{
- // FIXME: EventTarget::hasEventListeners should be const.
- SVGElement* mutableThis = const_cast<SVGElement*>(this);
- return mutableThis->hasEventListeners(eventNames().focusinEvent) || mutableThis->hasEventListeners(eventNames().focusoutEvent);
+ return hasEventListeners(EventTypeNames::focusin) || hasEventListeners(EventTypeNames::focusout);
}
bool SVGElement::isKeyboardFocusable() const
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGElement.h
index 9badaae41b5..9098753995f 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGElement.h
@@ -23,13 +23,11 @@
#define SVGElement_h
#include "core/dom/Element.h"
-#include "core/platform/Timer.h"
#include "core/svg/SVGAnimatedString.h"
-#include "core/svg/SVGLangSpace.h"
-#include "core/svg/SVGLocatable.h"
#include "core/svg/SVGParsingError.h"
#include "core/svg/properties/SVGAnimatedPropertyMacros.h"
#include "core/svg/properties/SVGPropertyInfo.h"
+#include "platform/Timer.h"
#include "wtf/HashMap.h"
namespace WebCore {
@@ -47,7 +45,7 @@ class SVGSVGElement;
void mapAttributeToCSSProperty(HashMap<StringImpl*, CSSPropertyID>* propertyNameToIdMap, const QualifiedName& attrName);
-class SVGElement : public Element, public SVGLangSpace {
+class SVGElement : public Element {
public:
virtual ~SVGElement();
@@ -57,16 +55,25 @@ public:
bool hasRelativeLengths() const { return !m_elementsWithRelativeLengths.isEmpty(); }
virtual bool supportsMarkers() const { return false; }
PassRefPtr<CSSValue> getPresentationAttribute(const String& name);
- bool isKnownAttribute(const QualifiedName&);
static bool isAnimatableCSSProperty(const QualifiedName&);
- virtual AffineTransform localCoordinateSpaceTransform(SVGLocatable::CTMScope) const;
+ enum CTMScope {
+ NearestViewportScope, // Used by SVGGraphicsElement::getCTM()
+ ScreenScope // Used by SVGGraphicsElement::getScreenCTM()
+ };
+ virtual AffineTransform localCoordinateSpaceTransform(CTMScope) const;
virtual bool needsPendingResourceHandling() const { return true; }
bool instanceUpdatesBlocked() const;
void setInstanceUpdatesBlocked(bool);
String xmlbase() const;
- void setXmlbase(const String&);
+ void setXMLbase(const String&);
+
+ String xmllang() const;
+ void setXMLlang(const String& xmlLang);
+
+ String xmlspace() const;
+ void setXMLspace(const String& xmlSpace);
SVGSVGElement* ownerSVGElement() const;
SVGElement* viewportElement() const;
@@ -97,7 +104,7 @@ public:
const HashSet<SVGElementInstance*>& instancesForElement() const;
- bool getBoundingBox(FloatRect&, SVGLocatable::StyleUpdateStrategy = SVGLocatable::AllowStyleUpdate);
+ bool getBoundingBox(FloatRect&);
void setCursorElement(SVGCursorElement*);
void cursorElementRemoved();
@@ -136,6 +143,9 @@ public:
void invalidateRelativeLengthClients(SubtreeLayoutScope* = 0);
+ bool isContextElement() const { return m_isContextElement; }
+ void setContextElement() { m_isContextElement = true; }
+
protected:
SVGElement(const QualifiedName&, Document&, ConstructionType = CreateSVGElement);
@@ -165,6 +175,25 @@ protected:
void reportAttributeParsingError(SVGParsingError, const QualifiedName&, const AtomicString&);
bool hasFocusEventListeners() const;
+ class CleanUpAnimatedPropertiesCaller {
+ public:
+ CleanUpAnimatedPropertiesCaller()
+ : m_owner(0)
+ {
+ }
+
+ ~CleanUpAnimatedPropertiesCaller()
+ {
+ ASSERT(m_owner);
+ m_owner->cleanupAnimatedProperties();
+ }
+
+ void setOwner(SVGElement* owner) { m_owner = owner; }
+
+ private:
+ SVGElement* m_owner;
+ };
+
private:
friend class SVGElementInstance;
@@ -179,11 +208,12 @@ private:
void buildPendingResourcesIfNeeded();
- virtual bool isSupported(StringImpl* feature, StringImpl* version) const;
-
void mapInstanceToElement(SVGElementInstance*);
void removeInstanceMapping(SVGElementInstance*);
+ void cleanupAnimatedProperties();
+ friend class CleanUpAnimatedPropertiesCaller;
+
HashSet<SVGElement*> m_elementsWithRelativeLengths;
BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGElement)
@@ -193,6 +223,8 @@ private:
#if !ASSERT_DISABLED
bool m_inRelativeLengthClientsInvalidation;
#endif
+ bool m_animatedPropertiesDestructed;
+ bool m_isContextElement;
};
struct SVGAttributeHashTranslator {
@@ -207,17 +239,7 @@ struct SVGAttributeHashTranslator {
static bool equal(const QualifiedName& a, const QualifiedName& b) { return a.matches(b); }
};
-inline SVGElement* toSVGElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->isSVGElement());
- return static_cast<SVGElement*>(node);
-}
-
-inline const SVGElement* toSVGElement(const Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->isSVGElement());
- return static_cast<const SVGElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(SVGElement, isSVGElement());
}
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGElement.idl b/chromium/third_party/WebKit/Source/core/svg/SVGElement.idl
index 26d6c95dda1..d27e2abb355 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGElement.idl
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGElement.idl
@@ -21,7 +21,7 @@
*/
[
- CustomToV8
+ Custom=Wrap,
] interface SVGElement : Element {
[TreatNullAs=NullString] attribute DOMString xmlbase;
readonly attribute SVGSVGElement ownerSVGElement;
@@ -36,3 +36,4 @@
CSSValue getPresentationAttribute([Default=Undefined] optional DOMString name);
};
+SVGElement implements GlobalEventHandlers;
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGElementInstance.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGElementInstance.cpp
index e93740c100e..3e835c184e4 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGElementInstance.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGElementInstance.cpp
@@ -24,9 +24,9 @@
#include "core/svg/SVGElementInstance.h"
#include "core/dom/ContainerNodeAlgorithms.h"
-#include "core/dom/Event.h"
-#include "core/dom/EventListener.h"
-#include "core/dom/EventNames.h"
+#include "core/events/Event.h"
+#include "core/events/EventListener.h"
+#include "core/events/ThreadLocalEventNames.h"
#include "core/svg/SVGElement.h"
#include "core/svg/SVGElementInstanceList.h"
#include "core/svg/SVGUseElement.h"
@@ -125,7 +125,7 @@ SVGElementInstance::~SVGElementInstance()
// delete an SVGElementInstance at each deref call site.
void SVGElementInstance::removedLastRef()
{
-#ifndef NDEBUG
+#if SECURITY_ASSERT_ENABLED
m_deletionHasBegun = true;
#endif
delete this;
@@ -149,7 +149,7 @@ void SVGElementInstance::detach()
m_directUseElement = 0;
m_correspondingUseElement = 0;
- removeDetachedChildrenInContainer<SVGElementInstance, SVGElementInstance>(this);
+ removeDetachedChildrenInContainer<SVGElementInstance, SVGElementInstance>(*this);
}
PassRefPtr<SVGElementInstanceList> SVGElementInstance::childNodes()
@@ -165,7 +165,7 @@ void SVGElementInstance::setShadowTreeElement(SVGElement* element)
void SVGElementInstance::appendChild(PassRefPtr<SVGElementInstance> child)
{
- appendChildToContainer<SVGElementInstance, SVGElementInstance>(child.get(), this);
+ appendChildToContainer<SVGElementInstance, SVGElementInstance>(*child, *this);
}
void SVGElementInstance::invalidateAllInstancesOfElement(SVGElement* element)
@@ -200,10 +200,10 @@ void SVGElementInstance::invalidateAllInstancesOfElement(SVGElement* element)
const AtomicString& SVGElementInstance::interfaceName() const
{
- return eventNames().interfaceForSVGElementInstance;
+ return EventTargetNames::SVGElementInstance;
}
-ScriptExecutionContext* SVGElementInstance::scriptExecutionContext() const
+ExecutionContext* SVGElementInstance::executionContext() const
{
return &m_element->document();
}
@@ -248,12 +248,12 @@ EventTargetData* SVGElementInstance::eventTargetData()
return 0;
}
-EventTargetData* SVGElementInstance::ensureEventTargetData()
+EventTargetData& SVGElementInstance::ensureEventTargetData()
{
// EventTarget would use these methods if we were actually using its add/removeEventListener logic.
// As we're forwarding those calls to the correspondingElement(), no one should ever call this function.
ASSERT_NOT_REACHED();
- return 0;
+ return *eventTargetData();
}
SVGElementInstance::InstanceUpdateBlocker::InstanceUpdateBlocker(SVGElement* targetElement)
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGElementInstance.h b/chromium/third_party/WebKit/Source/core/svg/SVGElementInstance.h
index ba364f37255..66de33c7d75 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGElementInstance.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGElementInstance.h
@@ -22,14 +22,14 @@
#define SVGElementInstance_h
#include "bindings/v8/ScriptWrappable.h"
-#include "core/dom/EventTarget.h"
-#include "core/platform/TreeShared.h"
+#include "core/dom/TreeShared.h"
+#include "core/events/EventTarget.h"
namespace WebCore {
namespace Private {
template<class GenericNode, class GenericNodeContainer>
-void addChildNodesToDeletionQueue(GenericNode*& head, GenericNode*& tail, GenericNodeContainer* container);
+void addChildNodesToDeletionQueue(GenericNode*& head, GenericNode*& tail, GenericNodeContainer&);
};
class Document;
@@ -39,6 +39,7 @@ class SVGUseElement;
// SVGElementInstance mimics Node, but without providing all its functionality
class SVGElementInstance : public EventTarget, public ScriptWrappable, public TreeShared<SVGElementInstance> {
+ DEFINE_EVENT_TARGET_REFCOUNTING(TreeShared<SVGElementInstance>);
public:
static PassRefPtr<SVGElementInstance> create(SVGUseElement* correspondingUseElement, SVGUseElement* directUseElement, PassRefPtr<SVGElement> originalElement);
@@ -47,7 +48,7 @@ public:
void setParentOrShadowHostNode(SVGElementInstance* instance) { m_parentInstance = instance; }
virtual const AtomicString& interfaceName() const;
- virtual ScriptExecutionContext* scriptExecutionContext() const;
+ virtual ExecutionContext* executionContext() const;
virtual bool addEventListener(const AtomicString& eventType, PassRefPtr<EventListener>, bool useCapture);
virtual bool removeEventListener(const AtomicString& eventType, EventListener*, bool useCapture);
@@ -95,9 +96,6 @@ public:
static void invalidateAllInstancesOfElement(SVGElement*);
- using TreeShared<SVGElementInstance>::ref;
- using TreeShared<SVGElementInstance>::deref;
-
// EventTarget API
DECLARE_FORWARDING_ATTRIBUTE_EVENT_LISTENER(correspondingElement(), abort);
DECLARE_FORWARDING_ATTRIBUTE_EVENT_LISTENER(correspondingElement(), blur);
@@ -158,13 +156,13 @@ private:
void setShadowTreeElement(SVGElement*);
template<class GenericNode, class GenericNodeContainer>
- friend void appendChildToContainer(GenericNode* child, GenericNodeContainer* container);
+ friend void appendChildToContainer(GenericNode& child, GenericNodeContainer&);
template<class GenericNode, class GenericNodeContainer>
- friend void removeDetachedChildrenInContainer(GenericNodeContainer*);
+ friend void removeDetachedChildrenInContainer(GenericNodeContainer&);
template<class GenericNode, class GenericNodeContainer>
- friend void Private::addChildNodesToDeletionQueue(GenericNode*& head, GenericNode*& tail, GenericNodeContainer* container);
+ friend void Private::addChildNodesToDeletionQueue(GenericNode*& head, GenericNode*& tail, GenericNodeContainer&);
bool hasChildNodes() const { return m_firstChild; }
@@ -174,10 +172,8 @@ private:
void setNextSibling(SVGElementInstance* sibling) { m_nextSibling = sibling; }
void setPreviousSibling(SVGElementInstance* sibling) { m_previousSibling = sibling; }
- virtual void refEventTarget() { ref(); }
- virtual void derefEventTarget() { deref(); }
- virtual EventTargetData* eventTargetData();
- virtual EventTargetData* ensureEventTargetData();
+ virtual EventTargetData* eventTargetData() OVERRIDE;
+ virtual EventTargetData& ensureEventTargetData() OVERRIDE;
SVGElementInstance* m_parentInstance;
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGElementInstanceList.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGElementInstanceList.cpp
index c9f112d905b..0e3d89518b8 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGElementInstanceList.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGElementInstanceList.cpp
@@ -30,10 +30,6 @@ SVGElementInstanceList::SVGElementInstanceList(PassRefPtr<SVGElementInstance> ro
ScriptWrappable::init(this);
}
-SVGElementInstanceList::~SVGElementInstanceList()
-{
-}
-
unsigned SVGElementInstanceList::length() const
{
// NOTE: We could use the same caching facilities, like the ones "ChildNodeList" uses.
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGElementInstanceList.h b/chromium/third_party/WebKit/Source/core/svg/SVGElementInstanceList.h
index 5cc7bf3ca12..2ac15927df0 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGElementInstanceList.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGElementInstanceList.h
@@ -28,10 +28,9 @@ namespace WebCore {
class SVGElementInstance;
-class SVGElementInstanceList : public RefCounted<SVGElementInstanceList>, public ScriptWrappable {
+class SVGElementInstanceList FINAL : public RefCounted<SVGElementInstanceList>, public ScriptWrappable {
public:
static PassRefPtr<SVGElementInstanceList> create(PassRefPtr<SVGElementInstance> root) { return adoptRef(new SVGElementInstanceList(root)); }
- virtual ~SVGElementInstanceList();
unsigned length() const;
SVGElementInstance* item(unsigned index);
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGElementRareData.h b/chromium/third_party/WebKit/Source/core/svg/SVGElementRareData.h
index 6f3b38da8d1..91a69d938c5 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGElementRareData.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGElementRareData.h
@@ -94,7 +94,7 @@ public:
return 0;
if (!m_overrideComputedStyle || m_needsOverrideComputedStyleUpdate) {
// The style computed here contains no CSS Animations/Transitions or SMIL induced rules - this is needed to compute the "base value" for the SMIL animation sandwhich model.
- m_overrideComputedStyle = element->document().styleResolver()->styleForElement(element, parentStyle, DisallowStyleSharing, MatchAllRulesExcludingSMIL);
+ m_overrideComputedStyle = element->document().ensureStyleResolver().styleForElement(element, parentStyle, DisallowStyleSharing, MatchAllRulesExcludingSMIL);
m_needsOverrideComputedStyleUpdate = false;
}
ASSERT(m_overrideComputedStyle);
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGEllipseElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGEllipseElement.cpp
index 8002b06dd94..b0e4aeda679 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGEllipseElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGEllipseElement.cpp
@@ -22,7 +22,6 @@
#include "core/svg/SVGEllipseElement.h"
-#include "SVGNames.h"
#include "core/rendering/svg/RenderSVGEllipse.h"
#include "core/rendering/svg/RenderSVGResource.h"
#include "core/svg/SVGElementInstance.h"
@@ -46,28 +45,26 @@ BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGEllipseElement)
REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
END_REGISTER_ANIMATED_PROPERTIES
-inline SVGEllipseElement::SVGEllipseElement(const QualifiedName& tagName, Document& document)
- : SVGGraphicsElement(tagName, document)
+inline SVGEllipseElement::SVGEllipseElement(Document& document)
+ : SVGGeometryElement(SVGNames::ellipseTag, document)
, m_cx(LengthModeWidth)
, m_cy(LengthModeHeight)
, m_rx(LengthModeWidth)
, m_ry(LengthModeHeight)
{
- ASSERT(hasTagName(SVGNames::ellipseTag));
ScriptWrappable::init(this);
registerAnimatedPropertiesForSVGEllipseElement();
}
-PassRefPtr<SVGEllipseElement> SVGEllipseElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGEllipseElement> SVGEllipseElement::create(Document& document)
{
- return adoptRef(new SVGEllipseElement(tagName, document));
+ return adoptRef(new SVGEllipseElement(document));
}
bool SVGEllipseElement::isSupportedAttribute(const QualifiedName& attrName)
{
DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
if (supportedAttributes.isEmpty()) {
- SVGLangSpace::addSupportedAttributes(supportedAttributes);
SVGExternalResourcesRequired::addSupportedAttributes(supportedAttributes);
supportedAttributes.add(SVGNames::cxAttr);
supportedAttributes.add(SVGNames::cyAttr);
@@ -82,7 +79,7 @@ void SVGEllipseElement::parseAttribute(const QualifiedName& name, const AtomicSt
SVGParsingError parseError = NoError;
if (!isSupportedAttribute(name))
- SVGGraphicsElement::parseAttribute(name, value);
+ SVGGeometryElement::parseAttribute(name, value);
else if (name == SVGNames::cxAttr)
setCxBaseValue(SVGLength::construct(LengthModeWidth, value, parseError));
else if (name == SVGNames::cyAttr)
@@ -91,8 +88,7 @@ void SVGEllipseElement::parseAttribute(const QualifiedName& name, const AtomicSt
setRxBaseValue(SVGLength::construct(LengthModeWidth, value, parseError, ForbidNegativeLengths));
else if (name == SVGNames::ryAttr)
setRyBaseValue(SVGLength::construct(LengthModeHeight, value, parseError, ForbidNegativeLengths));
- else if (SVGLangSpace::parseAttribute(name, value)
- || SVGExternalResourcesRequired::parseAttribute(name, value)) {
+ else if (SVGExternalResourcesRequired::parseAttribute(name, value)) {
} else
ASSERT_NOT_REACHED();
@@ -102,7 +98,7 @@ void SVGEllipseElement::parseAttribute(const QualifiedName& name, const AtomicSt
void SVGEllipseElement::svgAttributeChanged(const QualifiedName& attrName)
{
if (!isSupportedAttribute(attrName)) {
- SVGGraphicsElement::svgAttributeChanged(attrName);
+ SVGGeometryElement::svgAttributeChanged(attrName);
return;
}
@@ -126,7 +122,7 @@ void SVGEllipseElement::svgAttributeChanged(const QualifiedName& attrName)
return;
}
- if (SVGLangSpace::isKnownAttribute(attrName) || SVGExternalResourcesRequired::isKnownAttribute(attrName)) {
+ if (SVGExternalResourcesRequired::isKnownAttribute(attrName)) {
RenderSVGResource::markForLayoutAndParentResourceInvalidation(renderer);
return;
}
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGEllipseElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGEllipseElement.h
index dcfc5ecb76d..e0cc981a96c 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGEllipseElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGEllipseElement.h
@@ -25,17 +25,17 @@
#include "core/svg/SVGAnimatedBoolean.h"
#include "core/svg/SVGAnimatedLength.h"
#include "core/svg/SVGExternalResourcesRequired.h"
-#include "core/svg/SVGGraphicsElement.h"
+#include "core/svg/SVGGeometryElement.h"
namespace WebCore {
-class SVGEllipseElement FINAL : public SVGGraphicsElement,
+class SVGEllipseElement FINAL : public SVGGeometryElement,
public SVGExternalResourcesRequired {
public:
- static PassRefPtr<SVGEllipseElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGEllipseElement> create(Document&);
private:
- SVGEllipseElement(const QualifiedName&, Document&);
+ explicit SVGEllipseElement(Document&);
virtual bool isValid() const { return SVGTests::isValid(); }
virtual bool supportsFocus() const OVERRIDE { return hasFocusEventListeners(); }
@@ -57,11 +57,7 @@ private:
END_DECLARE_ANIMATED_PROPERTIES
};
-inline SVGEllipseElement* toSVGEllipseElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(SVGNames::ellipseTag));
- return static_cast<SVGEllipseElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(SVGEllipseElement, hasTagName(SVGNames::ellipseTag));
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGEllipseElement.idl b/chromium/third_party/WebKit/Source/core/svg/SVGEllipseElement.idl
index a9ea183d55b..fcd09c7967f 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGEllipseElement.idl
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGEllipseElement.idl
@@ -23,7 +23,7 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-interface SVGEllipseElement : SVGGraphicsElement {
+interface SVGEllipseElement : SVGGeometryElement {
readonly attribute SVGAnimatedLength cx;
readonly attribute SVGAnimatedLength cy;
readonly attribute SVGAnimatedLength rx;
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGExternalResourcesRequired.h b/chromium/third_party/WebKit/Source/core/svg/SVGExternalResourcesRequired.h
index c8781c33726..04b94fdd05f 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGExternalResourcesRequired.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGExternalResourcesRequired.h
@@ -45,7 +45,7 @@ public:
protected:
// These types look a bit awkward, but have to match the generic types of the SVGAnimatedProperty macros.
- virtual void setExternalResourcesRequiredBaseValue(const bool&, const bool validValue = true) = 0;
+ virtual void setExternalResourcesRequiredBaseValue(const bool&) = 0;
virtual bool& externalResourcesRequiredBaseValue() const = 0;
virtual void setHaveFiredLoadEvent(bool) { }
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFEBlendElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGFEBlendElement.cpp
index 1719515e0f3..832b4e40e65 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFEBlendElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFEBlendElement.cpp
@@ -23,7 +23,7 @@
#include "core/svg/SVGFEBlendElement.h"
#include "SVGNames.h"
-#include "core/platform/graphics/filters/FilterEffect.h"
+#include "platform/graphics/filters/FilterEffect.h"
#include "core/svg/SVGElementInstance.h"
#include "core/svg/graphics/filters/SVGFilterBuilder.h"
@@ -41,18 +41,17 @@ BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGFEBlendElement)
REGISTER_PARENT_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
END_REGISTER_ANIMATED_PROPERTIES
-inline SVGFEBlendElement::SVGFEBlendElement(const QualifiedName& tagName, Document& document)
- : SVGFilterPrimitiveStandardAttributes(tagName, document)
+inline SVGFEBlendElement::SVGFEBlendElement(Document& document)
+ : SVGFilterPrimitiveStandardAttributes(SVGNames::feBlendTag, document)
, m_mode(FEBLEND_MODE_NORMAL)
{
- ASSERT(hasTagName(SVGNames::feBlendTag));
ScriptWrappable::init(this);
registerAnimatedPropertiesForSVGFEBlendElement();
}
-PassRefPtr<SVGFEBlendElement> SVGFEBlendElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFEBlendElement> SVGFEBlendElement::create(Document& document)
{
- return adoptRef(new SVGFEBlendElement(tagName, document));
+ return adoptRef(new SVGFEBlendElement(document));
}
bool SVGFEBlendElement::isSupportedAttribute(const QualifiedName& attrName)
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFEBlendElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGFEBlendElement.h
index af78dd96682..20e211dfd0f 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFEBlendElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFEBlendElement.h
@@ -21,9 +21,9 @@
#ifndef SVGFEBlendElement_h
#define SVGFEBlendElement_h
-#include "core/platform/graphics/filters/FEBlend.h"
#include "core/svg/SVGAnimatedEnumeration.h"
#include "core/svg/SVGFilterPrimitiveStandardAttributes.h"
+#include "platform/graphics/filters/FEBlend.h"
namespace WebCore {
@@ -70,10 +70,10 @@ struct SVGPropertyTraits<BlendModeType> {
class SVGFEBlendElement FINAL : public SVGFilterPrimitiveStandardAttributes {
public:
- static PassRefPtr<SVGFEBlendElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGFEBlendElement> create(Document&);
private:
- SVGFEBlendElement(const QualifiedName&, Document&);
+ explicit SVGFEBlendElement(Document&);
bool isSupportedAttribute(const QualifiedName&);
virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFEColorMatrixElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGFEColorMatrixElement.cpp
index 1ecb088e6c4..a6fc8e4079c 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFEColorMatrixElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFEColorMatrixElement.cpp
@@ -23,7 +23,7 @@
#include "core/svg/SVGFEColorMatrixElement.h"
#include "SVGNames.h"
-#include "core/platform/graphics/filters/FilterEffect.h"
+#include "platform/graphics/filters/FilterEffect.h"
#include "core/svg/SVGElementInstance.h"
#include "core/svg/graphics/filters/SVGFilterBuilder.h"
@@ -41,18 +41,17 @@ BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGFEColorMatrixElement)
REGISTER_PARENT_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
END_REGISTER_ANIMATED_PROPERTIES
-inline SVGFEColorMatrixElement::SVGFEColorMatrixElement(const QualifiedName& tagName, Document& document)
- : SVGFilterPrimitiveStandardAttributes(tagName, document)
+inline SVGFEColorMatrixElement::SVGFEColorMatrixElement(Document& document)
+ : SVGFilterPrimitiveStandardAttributes(SVGNames::feColorMatrixTag, document)
, m_type(FECOLORMATRIX_TYPE_MATRIX)
{
- ASSERT(hasTagName(SVGNames::feColorMatrixTag));
ScriptWrappable::init(this);
registerAnimatedPropertiesForSVGFEColorMatrixElement();
}
-PassRefPtr<SVGFEColorMatrixElement> SVGFEColorMatrixElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFEColorMatrixElement> SVGFEColorMatrixElement::create(Document& document)
{
- return adoptRef(new SVGFEColorMatrixElement(tagName, document));
+ return adoptRef(new SVGFEColorMatrixElement(document));
}
bool SVGFEColorMatrixElement::isSupportedAttribute(const QualifiedName& attrName)
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFEColorMatrixElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGFEColorMatrixElement.h
index acd3616f415..1ed615f2f24 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFEColorMatrixElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFEColorMatrixElement.h
@@ -21,10 +21,10 @@
#ifndef SVGFEColorMatrixElement_h
#define SVGFEColorMatrixElement_h
-#include "core/platform/graphics/filters/FEColorMatrix.h"
#include "core/svg/SVGAnimatedEnumeration.h"
#include "core/svg/SVGAnimatedNumberList.h"
#include "core/svg/SVGFilterPrimitiveStandardAttributes.h"
+#include "platform/graphics/filters/FEColorMatrix.h"
namespace WebCore {
@@ -67,10 +67,10 @@ struct SVGPropertyTraits<ColorMatrixType> {
class SVGFEColorMatrixElement FINAL : public SVGFilterPrimitiveStandardAttributes {
public:
- static PassRefPtr<SVGFEColorMatrixElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGFEColorMatrixElement> create(Document&);
private:
- SVGFEColorMatrixElement(const QualifiedName&, Document&);
+ explicit SVGFEColorMatrixElement(Document&);
bool isSupportedAttribute(const QualifiedName&);
virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFEComponentTransferElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGFEComponentTransferElement.cpp
index 7b774987736..127dac25411 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFEComponentTransferElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFEComponentTransferElement.cpp
@@ -23,7 +23,7 @@
#include "core/svg/SVGFEComponentTransferElement.h"
#include "SVGNames.h"
-#include "core/platform/graphics/filters/FilterEffect.h"
+#include "platform/graphics/filters/FilterEffect.h"
#include "core/svg/SVGFEFuncAElement.h"
#include "core/svg/SVGFEFuncBElement.h"
#include "core/svg/SVGFEFuncGElement.h"
@@ -40,17 +40,16 @@ BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGFEComponentTransferElement)
REGISTER_PARENT_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
END_REGISTER_ANIMATED_PROPERTIES
-inline SVGFEComponentTransferElement::SVGFEComponentTransferElement(const QualifiedName& tagName, Document& document)
- : SVGFilterPrimitiveStandardAttributes(tagName, document)
+inline SVGFEComponentTransferElement::SVGFEComponentTransferElement(Document& document)
+ : SVGFilterPrimitiveStandardAttributes(SVGNames::feComponentTransferTag, document)
{
- ASSERT(hasTagName(SVGNames::feComponentTransferTag));
ScriptWrappable::init(this);
registerAnimatedPropertiesForSVGFEComponentTransferElement();
}
-PassRefPtr<SVGFEComponentTransferElement> SVGFEComponentTransferElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFEComponentTransferElement> SVGFEComponentTransferElement::create(Document& document)
{
- return adoptRef(new SVGFEComponentTransferElement(tagName, document));
+ return adoptRef(new SVGFEComponentTransferElement(document));
}
bool SVGFEComponentTransferElement::isSupportedAttribute(const QualifiedName& attrName)
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFEComponentTransferElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGFEComponentTransferElement.h
index f9d212bcc5c..c83f1fedbdb 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFEComponentTransferElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFEComponentTransferElement.h
@@ -21,17 +21,17 @@
#ifndef SVGFEComponentTransferElement_h
#define SVGFEComponentTransferElement_h
-#include "core/platform/graphics/filters/FEComponentTransfer.h"
#include "core/svg/SVGFilterPrimitiveStandardAttributes.h"
+#include "platform/graphics/filters/FEComponentTransfer.h"
namespace WebCore {
class SVGFEComponentTransferElement FINAL : public SVGFilterPrimitiveStandardAttributes {
public:
- static PassRefPtr<SVGFEComponentTransferElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGFEComponentTransferElement> create(Document&);
private:
- SVGFEComponentTransferElement(const QualifiedName&, Document&);
+ explicit SVGFEComponentTransferElement(Document&);
// FIXME: svgAttributeChanged missing.
bool isSupportedAttribute(const QualifiedName&);
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFECompositeElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGFECompositeElement.cpp
index 343ca1025f4..d9afc49656f 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFECompositeElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFECompositeElement.cpp
@@ -23,7 +23,7 @@
#include "core/svg/SVGFECompositeElement.h"
#include "SVGNames.h"
-#include "core/platform/graphics/filters/FilterEffect.h"
+#include "platform/graphics/filters/FilterEffect.h"
#include "core/svg/SVGElementInstance.h"
#include "core/svg/graphics/filters/SVGFilterBuilder.h"
@@ -49,18 +49,17 @@ BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGFECompositeElement)
REGISTER_PARENT_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
END_REGISTER_ANIMATED_PROPERTIES
-inline SVGFECompositeElement::SVGFECompositeElement(const QualifiedName& tagName, Document& document)
- : SVGFilterPrimitiveStandardAttributes(tagName, document)
+inline SVGFECompositeElement::SVGFECompositeElement(Document& document)
+ : SVGFilterPrimitiveStandardAttributes(SVGNames::feCompositeTag, document)
, m_svgOperator(FECOMPOSITE_OPERATOR_OVER)
{
- ASSERT(hasTagName(SVGNames::feCompositeTag));
ScriptWrappable::init(this);
registerAnimatedPropertiesForSVGFECompositeElement();
}
-PassRefPtr<SVGFECompositeElement> SVGFECompositeElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFECompositeElement> SVGFECompositeElement::create(Document& document)
{
- return adoptRef(new SVGFECompositeElement(tagName, document));
+ return adoptRef(new SVGFECompositeElement(document));
}
bool SVGFECompositeElement::isSupportedAttribute(const QualifiedName& attrName)
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFECompositeElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGFECompositeElement.h
index 7b7b9439c16..dad0fb2e1a9 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFECompositeElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFECompositeElement.h
@@ -21,10 +21,10 @@
#ifndef SVGFECompositeElement_h
#define SVGFECompositeElement_h
-#include "core/platform/graphics/filters/FEComposite.h"
#include "core/svg/SVGAnimatedEnumeration.h"
#include "core/svg/SVGAnimatedNumber.h"
#include "core/svg/SVGFilterPrimitiveStandardAttributes.h"
+#include "platform/graphics/filters/FEComposite.h"
namespace WebCore {
@@ -75,10 +75,10 @@ struct SVGPropertyTraits<CompositeOperationType> {
class SVGFECompositeElement FINAL : public SVGFilterPrimitiveStandardAttributes {
public:
- static PassRefPtr<SVGFECompositeElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGFECompositeElement> create(Document&);
private:
- SVGFECompositeElement(const QualifiedName&, Document&);
+ explicit SVGFECompositeElement(Document&);
bool isSupportedAttribute(const QualifiedName&);
virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFEConvolveMatrixElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGFEConvolveMatrixElement.cpp
index 9453bf73c32..2fad4d9fbad 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFEConvolveMatrixElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFEConvolveMatrixElement.cpp
@@ -22,13 +22,13 @@
#include "core/svg/SVGFEConvolveMatrixElement.h"
#include "SVGNames.h"
-#include "core/platform/graphics/FloatPoint.h"
-#include "core/platform/graphics/IntPoint.h"
-#include "core/platform/graphics/IntSize.h"
-#include "core/platform/graphics/filters/FilterEffect.h"
+#include "platform/graphics/filters/FilterEffect.h"
#include "core/svg/SVGElementInstance.h"
#include "core/svg/SVGParserUtilities.h"
#include "core/svg/graphics/filters/SVGFilterBuilder.h"
+#include "platform/geometry/FloatPoint.h"
+#include "platform/geometry/IntPoint.h"
+#include "platform/geometry/IntSize.h"
namespace WebCore {
@@ -62,18 +62,17 @@ BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGFEConvolveMatrixElement)
REGISTER_PARENT_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
END_REGISTER_ANIMATED_PROPERTIES
-inline SVGFEConvolveMatrixElement::SVGFEConvolveMatrixElement(const QualifiedName& tagName, Document& document)
- : SVGFilterPrimitiveStandardAttributes(tagName, document)
+inline SVGFEConvolveMatrixElement::SVGFEConvolveMatrixElement(Document& document)
+ : SVGFilterPrimitiveStandardAttributes(SVGNames::feConvolveMatrixTag, document)
, m_edgeMode(EDGEMODE_DUPLICATE)
{
- ASSERT(hasTagName(SVGNames::feConvolveMatrixTag));
ScriptWrappable::init(this);
registerAnimatedPropertiesForSVGFEConvolveMatrixElement();
}
-PassRefPtr<SVGFEConvolveMatrixElement> SVGFEConvolveMatrixElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFEConvolveMatrixElement> SVGFEConvolveMatrixElement::create(Document& document)
{
- return adoptRef(new SVGFEConvolveMatrixElement(tagName, document));
+ return adoptRef(new SVGFEConvolveMatrixElement(document));
}
const AtomicString& SVGFEConvolveMatrixElement::kernelUnitLengthXIdentifier()
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFEConvolveMatrixElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGFEConvolveMatrixElement.h
index f1faec5c6a7..4bc21ab5fc4 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFEConvolveMatrixElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFEConvolveMatrixElement.h
@@ -20,13 +20,13 @@
#ifndef SVGFEConvolveMatrixElement_h
#define SVGFEConvolveMatrixElement_h
-#include "core/platform/graphics/filters/FEConvolveMatrix.h"
#include "core/svg/SVGAnimatedBoolean.h"
#include "core/svg/SVGAnimatedEnumeration.h"
#include "core/svg/SVGAnimatedInteger.h"
#include "core/svg/SVGAnimatedNumber.h"
#include "core/svg/SVGAnimatedNumberList.h"
#include "core/svg/SVGFilterPrimitiveStandardAttributes.h"
+#include "platform/graphics/filters/FEConvolveMatrix.h"
namespace WebCore {
@@ -65,13 +65,13 @@ struct SVGPropertyTraits<EdgeModeType> {
class SVGFEConvolveMatrixElement FINAL : public SVGFilterPrimitiveStandardAttributes {
public:
- static PassRefPtr<SVGFEConvolveMatrixElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGFEConvolveMatrixElement> create(Document&);
void setOrder(float orderX, float orderY);
void setKernelUnitLength(float kernelUnitLengthX, float kernelUnitLengthY);
private:
- SVGFEConvolveMatrixElement(const QualifiedName&, Document&);
+ explicit SVGFEConvolveMatrixElement(Document&);
bool isSupportedAttribute(const QualifiedName&);
virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFEDiffuseLightingElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGFEDiffuseLightingElement.cpp
index 7f146450aa3..9d18e3ccc74 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFEDiffuseLightingElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFEDiffuseLightingElement.cpp
@@ -21,14 +21,12 @@
#include "core/svg/SVGFEDiffuseLightingElement.h"
-#include "SVGNames.h"
-#include "core/platform/graphics/filters/FEDiffuseLighting.h"
-#include "core/platform/graphics/filters/FilterEffect.h"
#include "core/rendering/style/RenderStyle.h"
#include "core/svg/SVGElementInstance.h"
-#include "core/svg/SVGFELightElement.h"
#include "core/svg/SVGParserUtilities.h"
#include "core/svg/graphics/filters/SVGFilterBuilder.h"
+#include "platform/graphics/filters/FEDiffuseLighting.h"
+#include "platform/graphics/filters/FilterEffect.h"
namespace WebCore {
@@ -48,19 +46,18 @@ BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGFEDiffuseLightingElement)
REGISTER_PARENT_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
END_REGISTER_ANIMATED_PROPERTIES
-inline SVGFEDiffuseLightingElement::SVGFEDiffuseLightingElement(const QualifiedName& tagName, Document& document)
- : SVGFilterPrimitiveStandardAttributes(tagName, document)
+inline SVGFEDiffuseLightingElement::SVGFEDiffuseLightingElement(Document& document)
+ : SVGFilterPrimitiveStandardAttributes(SVGNames::feDiffuseLightingTag, document)
, m_diffuseConstant(1)
, m_surfaceScale(1)
{
- ASSERT(hasTagName(SVGNames::feDiffuseLightingTag));
ScriptWrappable::init(this);
registerAnimatedPropertiesForSVGFEDiffuseLightingElement();
}
-PassRefPtr<SVGFEDiffuseLightingElement> SVGFEDiffuseLightingElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFEDiffuseLightingElement> SVGFEDiffuseLightingElement::create(Document& document)
{
- return adoptRef(new SVGFEDiffuseLightingElement(tagName, document));
+ return adoptRef(new SVGFEDiffuseLightingElement(document));
}
const AtomicString& SVGFEDiffuseLightingElement::kernelUnitLengthXIdentifier()
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFEDiffuseLightingElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGFEDiffuseLightingElement.h
index efd8e3fedbe..c3cbbc4b035 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFEDiffuseLightingElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFEDiffuseLightingElement.h
@@ -33,11 +33,11 @@ class SVGColor;
class SVGFEDiffuseLightingElement FINAL : public SVGFilterPrimitiveStandardAttributes {
public:
- static PassRefPtr<SVGFEDiffuseLightingElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGFEDiffuseLightingElement> create(Document&);
void lightElementAttributeChanged(const SVGFELightElement*, const QualifiedName&);
private:
- SVGFEDiffuseLightingElement(const QualifiedName&, Document&);
+ explicit SVGFEDiffuseLightingElement(Document&);
bool isSupportedAttribute(const QualifiedName&);
virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
@@ -57,11 +57,7 @@ private:
END_DECLARE_ANIMATED_PROPERTIES
};
-inline SVGFEDiffuseLightingElement* toSVGFEDiffuseLightingElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(SVGNames::feDiffuseLightingTag));
- return static_cast<SVGFEDiffuseLightingElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(SVGFEDiffuseLightingElement, hasTagName(SVGNames::feDiffuseLightingTag));
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFEDisplacementMapElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGFEDisplacementMapElement.cpp
index 61fc8a90b01..6aff75bdbfd 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFEDisplacementMapElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFEDisplacementMapElement.cpp
@@ -22,7 +22,7 @@
#include "core/svg/SVGFEDisplacementMapElement.h"
#include "SVGNames.h"
-#include "core/platform/graphics/filters/FilterEffect.h"
+#include "platform/graphics/filters/FilterEffect.h"
#include "core/svg/SVGElementInstance.h"
#include "core/svg/graphics/filters/SVGFilterBuilder.h"
@@ -44,19 +44,18 @@ BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGFEDisplacementMapElement)
REGISTER_PARENT_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
END_REGISTER_ANIMATED_PROPERTIES
-inline SVGFEDisplacementMapElement::SVGFEDisplacementMapElement(const QualifiedName& tagName, Document& document)
- : SVGFilterPrimitiveStandardAttributes(tagName, document)
+inline SVGFEDisplacementMapElement::SVGFEDisplacementMapElement(Document& document)
+ : SVGFilterPrimitiveStandardAttributes(SVGNames::feDisplacementMapTag, document)
, m_xChannelSelector(CHANNEL_A)
, m_yChannelSelector(CHANNEL_A)
{
- ASSERT(hasTagName(SVGNames::feDisplacementMapTag));
ScriptWrappable::init(this);
registerAnimatedPropertiesForSVGFEDisplacementMapElement();
}
-PassRefPtr<SVGFEDisplacementMapElement> SVGFEDisplacementMapElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFEDisplacementMapElement> SVGFEDisplacementMapElement::create(Document& document)
{
- return adoptRef(new SVGFEDisplacementMapElement(tagName, document));
+ return adoptRef(new SVGFEDisplacementMapElement(document));
}
bool SVGFEDisplacementMapElement::isSupportedAttribute(const QualifiedName& attrName)
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFEDisplacementMapElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGFEDisplacementMapElement.h
index 0aa95c18b22..cb0c70733ce 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFEDisplacementMapElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFEDisplacementMapElement.h
@@ -20,10 +20,10 @@
#ifndef SVGFEDisplacementMapElement_h
#define SVGFEDisplacementMapElement_h
-#include "core/platform/graphics/filters/FEDisplacementMap.h"
#include "core/svg/SVGAnimatedEnumeration.h"
#include "core/svg/SVGAnimatedNumber.h"
#include "core/svg/SVGFilterPrimitiveStandardAttributes.h"
+#include "platform/graphics/filters/FEDisplacementMap.h"
namespace WebCore {
@@ -66,12 +66,12 @@ struct SVGPropertyTraits<ChannelSelectorType> {
class SVGFEDisplacementMapElement FINAL : public SVGFilterPrimitiveStandardAttributes {
public:
- static PassRefPtr<SVGFEDisplacementMapElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGFEDisplacementMapElement> create(Document&);
static ChannelSelectorType stringToChannel(const String&);
private:
- SVGFEDisplacementMapElement(const QualifiedName& tagName, Document&);
+ SVGFEDisplacementMapElement(Document&);
bool isSupportedAttribute(const QualifiedName&);
virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFEDistantLightElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGFEDistantLightElement.cpp
index d4535636404..f641868e74d 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFEDistantLightElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFEDistantLightElement.cpp
@@ -18,24 +18,22 @@
*/
#include "config.h"
-
-#include "SVGNames.h"
#include "core/svg/SVGFEDistantLightElement.h"
-#include "core/platform/graphics/filters/DistantLightSource.h"
+#include "SVGNames.h"
+#include "platform/graphics/filters/DistantLightSource.h"
namespace WebCore {
-inline SVGFEDistantLightElement::SVGFEDistantLightElement(const QualifiedName& tagName, Document& document)
- : SVGFELightElement(tagName, document)
+inline SVGFEDistantLightElement::SVGFEDistantLightElement(Document& document)
+ : SVGFELightElement(SVGNames::feDistantLightTag, document)
{
- ASSERT(hasTagName(SVGNames::feDistantLightTag));
ScriptWrappable::init(this);
}
-PassRefPtr<SVGFEDistantLightElement> SVGFEDistantLightElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFEDistantLightElement> SVGFEDistantLightElement::create(Document& document)
{
- return adoptRef(new SVGFEDistantLightElement(tagName, document));
+ return adoptRef(new SVGFEDistantLightElement(document));
}
PassRefPtr<LightSource> SVGFEDistantLightElement::lightSource() const
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFEDistantLightElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGFEDistantLightElement.h
index df1b9c2a2db..8a50cc8414d 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFEDistantLightElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFEDistantLightElement.h
@@ -26,10 +26,10 @@ namespace WebCore {
class SVGFEDistantLightElement FINAL : public SVGFELightElement {
public:
- static PassRefPtr<SVGFEDistantLightElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGFEDistantLightElement> create(Document&);
private:
- SVGFEDistantLightElement(const QualifiedName&, Document&);
+ explicit SVGFEDistantLightElement(Document&);
virtual PassRefPtr<LightSource> lightSource() const;
};
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFEDropShadowElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGFEDropShadowElement.cpp
index d5a5d296f08..366eaf3512c 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFEDropShadowElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFEDropShadowElement.cpp
@@ -46,21 +46,20 @@ BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGFEDropShadowElement)
REGISTER_PARENT_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
END_REGISTER_ANIMATED_PROPERTIES
-inline SVGFEDropShadowElement::SVGFEDropShadowElement(const QualifiedName& tagName, Document& document)
- : SVGFilterPrimitiveStandardAttributes(tagName, document)
+inline SVGFEDropShadowElement::SVGFEDropShadowElement(Document& document)
+ : SVGFilterPrimitiveStandardAttributes(SVGNames::feDropShadowTag, document)
, m_dx(2)
, m_dy(2)
, m_stdDeviationX(2)
, m_stdDeviationY(2)
{
- ASSERT(hasTagName(SVGNames::feDropShadowTag));
ScriptWrappable::init(this);
registerAnimatedPropertiesForSVGFEDropShadowElement();
}
-PassRefPtr<SVGFEDropShadowElement> SVGFEDropShadowElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFEDropShadowElement> SVGFEDropShadowElement::create(Document& document)
{
- return adoptRef(new SVGFEDropShadowElement(tagName, document));
+ return adoptRef(new SVGFEDropShadowElement(document));
}
const AtomicString& SVGFEDropShadowElement::stdDeviationXIdentifier()
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFEDropShadowElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGFEDropShadowElement.h
index 352f60217bb..2b48d763b7d 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFEDropShadowElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFEDropShadowElement.h
@@ -20,20 +20,20 @@
#ifndef SVGFEDropShadowElement_h
#define SVGFEDropShadowElement_h
-#include "core/platform/graphics/filters/FEDropShadow.h"
#include "core/svg/SVGAnimatedNumber.h"
#include "core/svg/SVGFilterPrimitiveStandardAttributes.h"
+#include "platform/graphics/filters/FEDropShadow.h"
namespace WebCore {
class SVGFEDropShadowElement FINAL : public SVGFilterPrimitiveStandardAttributes {
public:
- static PassRefPtr<SVGFEDropShadowElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGFEDropShadowElement> create(Document&);
void setStdDeviation(float stdDeviationX, float stdDeviationY);
private:
- SVGFEDropShadowElement(const QualifiedName&, Document&);
+ explicit SVGFEDropShadowElement(Document&);
bool isSupportedAttribute(const QualifiedName&);
virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFEFloodElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGFEFloodElement.cpp
index 33d3aa37050..baee77b7311 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFEFloodElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFEFloodElement.cpp
@@ -28,16 +28,15 @@
namespace WebCore {
-inline SVGFEFloodElement::SVGFEFloodElement(const QualifiedName& tagName, Document& document)
- : SVGFilterPrimitiveStandardAttributes(tagName, document)
+inline SVGFEFloodElement::SVGFEFloodElement(Document& document)
+ : SVGFilterPrimitiveStandardAttributes(SVGNames::feFloodTag, document)
{
- ASSERT(hasTagName(SVGNames::feFloodTag));
ScriptWrappable::init(this);
}
-PassRefPtr<SVGFEFloodElement> SVGFEFloodElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFEFloodElement> SVGFEFloodElement::create(Document& document)
{
- return adoptRef(new SVGFEFloodElement(tagName, document));
+ return adoptRef(new SVGFEFloodElement(document));
}
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFEFloodElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGFEFloodElement.h
index 378533eaf2d..4fa91b67834 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFEFloodElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFEFloodElement.h
@@ -21,17 +21,17 @@
#ifndef SVGFEFloodElement_h
#define SVGFEFloodElement_h
-#include "core/platform/graphics/filters/FEFlood.h"
#include "core/svg/SVGFilterPrimitiveStandardAttributes.h"
+#include "platform/graphics/filters/FEFlood.h"
namespace WebCore {
class SVGFEFloodElement FINAL : public SVGFilterPrimitiveStandardAttributes {
public:
- static PassRefPtr<SVGFEFloodElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGFEFloodElement> create(Document&);
private:
- SVGFEFloodElement(const QualifiedName&, Document&);
+ explicit SVGFEFloodElement(Document&);
virtual bool setFilterEffectAttribute(FilterEffect*, const QualifiedName& attrName);
virtual PassRefPtr<FilterEffect> build(SVGFilterBuilder*, Filter*);
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFEFuncAElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGFEFuncAElement.cpp
index 4d35ab7c947..757a4edf389 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFEFuncAElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFEFuncAElement.cpp
@@ -20,21 +20,19 @@
#include "config.h"
-#include "SVGNames.h"
#include "core/svg/SVGFEFuncAElement.h"
namespace WebCore {
-inline SVGFEFuncAElement::SVGFEFuncAElement(const QualifiedName& tagName, Document& document)
- : SVGComponentTransferFunctionElement(tagName, document)
+inline SVGFEFuncAElement::SVGFEFuncAElement(Document& document)
+ : SVGComponentTransferFunctionElement(SVGNames::feFuncATag, document)
{
- ASSERT(hasTagName(SVGNames::feFuncATag));
ScriptWrappable::init(this);
}
-PassRefPtr<SVGFEFuncAElement> SVGFEFuncAElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFEFuncAElement> SVGFEFuncAElement::create(Document& document)
{
- return adoptRef(new SVGFEFuncAElement(tagName, document));
+ return adoptRef(new SVGFEFuncAElement(document));
}
}
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFEFuncAElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGFEFuncAElement.h
index 7f6cfdc6e61..01a473aad7a 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFEFuncAElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFEFuncAElement.h
@@ -28,17 +28,13 @@ namespace WebCore {
class SVGFEFuncAElement FINAL : public SVGComponentTransferFunctionElement {
public:
- static PassRefPtr<SVGFEFuncAElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGFEFuncAElement> create(Document&);
private:
- SVGFEFuncAElement(const QualifiedName&, Document&);
+ explicit SVGFEFuncAElement(Document&);
};
-inline SVGFEFuncAElement* toSVGFEFuncAElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(SVGNames::feFuncATag));
- return static_cast<SVGFEFuncAElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(SVGFEFuncAElement, hasTagName(SVGNames::feFuncATag));
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFEFuncBElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGFEFuncBElement.cpp
index abca696dbf2..08bc49c289c 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFEFuncBElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFEFuncBElement.cpp
@@ -20,21 +20,19 @@
#include "config.h"
-#include "SVGNames.h"
#include "core/svg/SVGFEFuncBElement.h"
namespace WebCore {
-inline SVGFEFuncBElement::SVGFEFuncBElement(const QualifiedName& tagName, Document& document)
- : SVGComponentTransferFunctionElement(tagName, document)
+inline SVGFEFuncBElement::SVGFEFuncBElement(Document& document)
+ : SVGComponentTransferFunctionElement(SVGNames::feFuncBTag, document)
{
- ASSERT(hasTagName(SVGNames::feFuncBTag));
ScriptWrappable::init(this);
}
-PassRefPtr<SVGFEFuncBElement> SVGFEFuncBElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFEFuncBElement> SVGFEFuncBElement::create(Document& document)
{
- return adoptRef(new SVGFEFuncBElement(tagName, document));
+ return adoptRef(new SVGFEFuncBElement(document));
}
}
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFEFuncBElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGFEFuncBElement.h
index 6bf582e5912..24560e3c4f5 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFEFuncBElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFEFuncBElement.h
@@ -28,17 +28,13 @@ namespace WebCore {
class SVGFEFuncBElement FINAL : public SVGComponentTransferFunctionElement {
public:
- static PassRefPtr<SVGFEFuncBElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGFEFuncBElement> create(Document&);
private:
- SVGFEFuncBElement(const QualifiedName&, Document&);
+ explicit SVGFEFuncBElement(Document&);
};
-inline SVGFEFuncBElement* toSVGFEFuncBElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(SVGNames::feFuncBTag));
- return static_cast<SVGFEFuncBElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(SVGFEFuncBElement, hasTagName(SVGNames::feFuncBTag));
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFEFuncGElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGFEFuncGElement.cpp
index f7de1f35cba..4e27390412b 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFEFuncGElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFEFuncGElement.cpp
@@ -20,21 +20,19 @@
#include "config.h"
-#include "SVGNames.h"
#include "core/svg/SVGFEFuncGElement.h"
namespace WebCore {
-inline SVGFEFuncGElement::SVGFEFuncGElement(const QualifiedName& tagName, Document& document)
- : SVGComponentTransferFunctionElement(tagName, document)
+inline SVGFEFuncGElement::SVGFEFuncGElement(Document& document)
+ : SVGComponentTransferFunctionElement(SVGNames::feFuncGTag, document)
{
- ASSERT(hasTagName(SVGNames::feFuncGTag));
ScriptWrappable::init(this);
}
-PassRefPtr<SVGFEFuncGElement> SVGFEFuncGElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFEFuncGElement> SVGFEFuncGElement::create(Document& document)
{
- return adoptRef(new SVGFEFuncGElement(tagName, document));
+ return adoptRef(new SVGFEFuncGElement(document));
}
}
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFEFuncGElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGFEFuncGElement.h
index 5b29bdc0ccf..3d6ccb827d0 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFEFuncGElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFEFuncGElement.h
@@ -28,17 +28,13 @@ namespace WebCore {
class SVGFEFuncGElement FINAL : public SVGComponentTransferFunctionElement {
public:
- static PassRefPtr<SVGFEFuncGElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGFEFuncGElement> create(Document&);
private:
- SVGFEFuncGElement(const QualifiedName&, Document&);
+ explicit SVGFEFuncGElement(Document&);
};
-inline SVGFEFuncGElement* toSVGFEFuncGElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(SVGNames::feFuncGTag));
- return static_cast<SVGFEFuncGElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(SVGFEFuncGElement, hasTagName(SVGNames::feFuncGTag));
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFEFuncRElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGFEFuncRElement.cpp
index cf059b68fef..786d4f8327a 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFEFuncRElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFEFuncRElement.cpp
@@ -20,21 +20,19 @@
#include "config.h"
-#include "SVGNames.h"
#include "core/svg/SVGFEFuncRElement.h"
namespace WebCore {
-inline SVGFEFuncRElement::SVGFEFuncRElement(const QualifiedName& tagName, Document& document)
- : SVGComponentTransferFunctionElement(tagName, document)
+inline SVGFEFuncRElement::SVGFEFuncRElement(Document& document)
+ : SVGComponentTransferFunctionElement(SVGNames::feFuncRTag, document)
{
- ASSERT(hasTagName(SVGNames::feFuncRTag));
ScriptWrappable::init(this);
}
-PassRefPtr<SVGFEFuncRElement> SVGFEFuncRElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFEFuncRElement> SVGFEFuncRElement::create(Document& document)
{
- return adoptRef(new SVGFEFuncRElement(tagName, document));
+ return adoptRef(new SVGFEFuncRElement(document));
}
}
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFEFuncRElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGFEFuncRElement.h
index 4822a0b20bc..49bff723664 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFEFuncRElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFEFuncRElement.h
@@ -28,17 +28,13 @@ namespace WebCore {
class SVGFEFuncRElement FINAL : public SVGComponentTransferFunctionElement {
public:
- static PassRefPtr<SVGFEFuncRElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGFEFuncRElement> create(Document&);
private:
- SVGFEFuncRElement(const QualifiedName&, Document&);
+ explicit SVGFEFuncRElement(Document&);
};
-inline SVGFEFuncRElement* toSVGFEFuncRElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(SVGNames::feFuncRTag));
- return static_cast<SVGFEFuncRElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(SVGFEFuncRElement, hasTagName(SVGNames::feFuncRTag));
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFEGaussianBlurElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGFEGaussianBlurElement.cpp
index 3611e960183..75cadffb04f 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFEGaussianBlurElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFEGaussianBlurElement.cpp
@@ -23,7 +23,7 @@
#include "core/svg/SVGFEGaussianBlurElement.h"
#include "SVGNames.h"
-#include "core/platform/graphics/filters/FilterEffect.h"
+#include "platform/graphics/filters/FilterEffect.h"
#include "core/svg/SVGElementInstance.h"
#include "core/svg/SVGParserUtilities.h"
#include "core/svg/graphics/filters/SVGFilterBuilder.h"
@@ -42,17 +42,16 @@ BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGFEGaussianBlurElement)
REGISTER_PARENT_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
END_REGISTER_ANIMATED_PROPERTIES
-inline SVGFEGaussianBlurElement::SVGFEGaussianBlurElement(const QualifiedName& tagName, Document& document)
- : SVGFilterPrimitiveStandardAttributes(tagName, document)
+inline SVGFEGaussianBlurElement::SVGFEGaussianBlurElement(Document& document)
+ : SVGFilterPrimitiveStandardAttributes(SVGNames::feGaussianBlurTag, document)
{
- ASSERT(hasTagName(SVGNames::feGaussianBlurTag));
ScriptWrappable::init(this);
registerAnimatedPropertiesForSVGFEGaussianBlurElement();
}
-PassRefPtr<SVGFEGaussianBlurElement> SVGFEGaussianBlurElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFEGaussianBlurElement> SVGFEGaussianBlurElement::create(Document& document)
{
- return adoptRef(new SVGFEGaussianBlurElement(tagName, document));
+ return adoptRef(new SVGFEGaussianBlurElement(document));
}
const AtomicString& SVGFEGaussianBlurElement::stdDeviationXIdentifier()
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFEGaussianBlurElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGFEGaussianBlurElement.h
index 317addc7f65..16b456b1692 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFEGaussianBlurElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFEGaussianBlurElement.h
@@ -21,20 +21,20 @@
#ifndef SVGFEGaussianBlurElement_h
#define SVGFEGaussianBlurElement_h
-#include "core/platform/graphics/filters/FEGaussianBlur.h"
#include "core/svg/SVGAnimatedNumber.h"
#include "core/svg/SVGFilterPrimitiveStandardAttributes.h"
+#include "platform/graphics/filters/FEGaussianBlur.h"
namespace WebCore {
class SVGFEGaussianBlurElement FINAL : public SVGFilterPrimitiveStandardAttributes {
public:
- static PassRefPtr<SVGFEGaussianBlurElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGFEGaussianBlurElement> create(Document&);
void setStdDeviation(float stdDeviationX, float stdDeviationY);
private:
- SVGFEGaussianBlurElement(const QualifiedName&, Document&);
+ explicit SVGFEGaussianBlurElement(Document&);
bool isSupportedAttribute(const QualifiedName&);
virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFEImageElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGFEImageElement.cpp
index e164c6595f9..b886a5097f1 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFEImageElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFEImageElement.cpp
@@ -23,16 +23,14 @@
#include "core/svg/SVGFEImageElement.h"
-#include "SVGNames.h"
#include "XLinkNames.h"
#include "core/dom/Document.h"
#include "core/fetch/FetchRequest.h"
-#include "core/fetch/ImageResource.h"
#include "core/fetch/ResourceFetcher.h"
-#include "core/platform/graphics/Image.h"
#include "core/rendering/svg/RenderSVGResource.h"
#include "core/svg/SVGElementInstance.h"
#include "core/svg/SVGPreserveAspectRatio.h"
+#include "platform/graphics/Image.h"
namespace WebCore {
@@ -48,17 +46,16 @@ BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGFEImageElement)
REGISTER_PARENT_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
END_REGISTER_ANIMATED_PROPERTIES
-inline SVGFEImageElement::SVGFEImageElement(const QualifiedName& tagName, Document& document)
- : SVGFilterPrimitiveStandardAttributes(tagName, document)
+inline SVGFEImageElement::SVGFEImageElement(Document& document)
+ : SVGFilterPrimitiveStandardAttributes(SVGNames::feImageTag, document)
{
- ASSERT(hasTagName(SVGNames::feImageTag));
ScriptWrappable::init(this);
registerAnimatedPropertiesForSVGFEImageElement();
}
-PassRefPtr<SVGFEImageElement> SVGFEImageElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFEImageElement> SVGFEImageElement::create(Document& document)
{
- return adoptRef(new SVGFEImageElement(tagName, document));
+ return adoptRef(new SVGFEImageElement(document));
}
SVGFEImageElement::~SVGFEImageElement()
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFEImageElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGFEImageElement.h
index c769e557213..5e6bb048582 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFEImageElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFEImageElement.h
@@ -24,13 +24,13 @@
#include "SVGNames.h"
#include "core/fetch/ImageResource.h"
#include "core/fetch/ResourcePtr.h"
-#include "core/platform/graphics/ImageBuffer.h"
#include "core/svg/SVGAnimatedBoolean.h"
#include "core/svg/SVGAnimatedPreserveAspectRatio.h"
#include "core/svg/SVGExternalResourcesRequired.h"
#include "core/svg/SVGFilterPrimitiveStandardAttributes.h"
#include "core/svg/SVGURIReference.h"
#include "core/svg/graphics/filters/SVGFEImage.h"
+#include "platform/graphics/ImageBuffer.h"
namespace WebCore {
@@ -39,14 +39,14 @@ class SVGFEImageElement FINAL : public SVGFilterPrimitiveStandardAttributes,
public SVGExternalResourcesRequired,
public ImageResourceClient {
public:
- static PassRefPtr<SVGFEImageElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGFEImageElement> create(Document&);
bool currentFrameHasSingleSecurityOrigin() const;
virtual ~SVGFEImageElement();
private:
- SVGFEImageElement(const QualifiedName&, Document&);
+ explicit SVGFEImageElement(Document&);
bool isSupportedAttribute(const QualifiedName&);
virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
@@ -72,11 +72,7 @@ private:
ResourcePtr<ImageResource> m_cachedImage;
};
-inline SVGFEImageElement* toSVGFEImageElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(SVGNames::feImageTag));
- return static_cast<SVGFEImageElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(SVGFEImageElement, hasTagName(SVGNames::feImageTag));
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFELightElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGFELightElement.h
index 4d14e30d77c..4473ed3e646 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFELightElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFELightElement.h
@@ -22,9 +22,9 @@
#ifndef SVGFELightElement_h
#define SVGFELightElement_h
-#include "core/platform/graphics/filters/LightSource.h"
#include "core/svg/SVGAnimatedNumber.h"
#include "core/svg/SVGElement.h"
+#include "platform/graphics/filters/LightSource.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFEMergeElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGFEMergeElement.cpp
index 401fc30a46c..e1cf2db9b89 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFEMergeElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFEMergeElement.cpp
@@ -23,22 +23,21 @@
#include "core/svg/SVGFEMergeElement.h"
#include "SVGNames.h"
-#include "core/platform/graphics/filters/FilterEffect.h"
+#include "platform/graphics/filters/FilterEffect.h"
#include "core/svg/SVGFEMergeNodeElement.h"
#include "core/svg/graphics/filters/SVGFilterBuilder.h"
namespace WebCore {
-inline SVGFEMergeElement::SVGFEMergeElement(const QualifiedName& tagName, Document& document)
- : SVGFilterPrimitiveStandardAttributes(tagName, document)
+inline SVGFEMergeElement::SVGFEMergeElement(Document& document)
+ : SVGFilterPrimitiveStandardAttributes(SVGNames::feMergeTag, document)
{
- ASSERT(hasTagName(SVGNames::feMergeTag));
ScriptWrappable::init(this);
}
-PassRefPtr<SVGFEMergeElement> SVGFEMergeElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFEMergeElement> SVGFEMergeElement::create(Document& document)
{
- return adoptRef(new SVGFEMergeElement(tagName, document));
+ return adoptRef(new SVGFEMergeElement(document));
}
PassRefPtr<FilterEffect> SVGFEMergeElement::build(SVGFilterBuilder* filterBuilder, Filter* filter)
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFEMergeElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGFEMergeElement.h
index ab682bb5f5f..9fae4a98d8f 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFEMergeElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFEMergeElement.h
@@ -21,17 +21,17 @@
#ifndef SVGFEMergeElement_h
#define SVGFEMergeElement_h
-#include "core/platform/graphics/filters/FEMerge.h"
#include "core/svg/SVGFilterPrimitiveStandardAttributes.h"
+#include "platform/graphics/filters/FEMerge.h"
namespace WebCore {
class SVGFEMergeElement FINAL : public SVGFilterPrimitiveStandardAttributes {
public:
- static PassRefPtr<SVGFEMergeElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGFEMergeElement> create(Document&);
private:
- SVGFEMergeElement(const QualifiedName&, Document&);
+ explicit SVGFEMergeElement(Document&);
virtual PassRefPtr<FilterEffect> build(SVGFilterBuilder*, Filter*);
};
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFEMergeNodeElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGFEMergeNodeElement.cpp
index 648f22e81dd..30df5a14e5f 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFEMergeNodeElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFEMergeNodeElement.cpp
@@ -22,7 +22,6 @@
#include "core/svg/SVGFEMergeNodeElement.h"
-#include "SVGNames.h"
#include "core/svg/SVGElementInstance.h"
#include "core/svg/SVGFilterPrimitiveStandardAttributes.h"
@@ -35,17 +34,16 @@ BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGFEMergeNodeElement)
REGISTER_LOCAL_ANIMATED_PROPERTY(in1)
END_REGISTER_ANIMATED_PROPERTIES
-inline SVGFEMergeNodeElement::SVGFEMergeNodeElement(const QualifiedName& tagName, Document& document)
- : SVGElement(tagName, document)
+inline SVGFEMergeNodeElement::SVGFEMergeNodeElement(Document& document)
+ : SVGElement(SVGNames::feMergeNodeTag, document)
{
- ASSERT(hasTagName(SVGNames::feMergeNodeTag));
ScriptWrappable::init(this);
registerAnimatedPropertiesForSVGFEMergeNodeElement();
}
-PassRefPtr<SVGFEMergeNodeElement> SVGFEMergeNodeElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFEMergeNodeElement> SVGFEMergeNodeElement::create(Document& document)
{
- return adoptRef(new SVGFEMergeNodeElement(tagName, document));
+ return adoptRef(new SVGFEMergeNodeElement(document));
}
bool SVGFEMergeNodeElement::isSupportedAttribute(const QualifiedName& attrName)
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFEMergeNodeElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGFEMergeNodeElement.h
index 9bfe59aec6e..a0760887bc4 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFEMergeNodeElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFEMergeNodeElement.h
@@ -29,10 +29,10 @@ namespace WebCore {
class SVGFEMergeNodeElement FINAL : public SVGElement {
public:
- static PassRefPtr<SVGFEMergeNodeElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGFEMergeNodeElement> create(Document&);
private:
- SVGFEMergeNodeElement(const QualifiedName&, Document&);
+ explicit SVGFEMergeNodeElement(Document&);
bool isSupportedAttribute(const QualifiedName&);
virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
@@ -45,11 +45,7 @@ private:
END_DECLARE_ANIMATED_PROPERTIES
};
-inline SVGFEMergeNodeElement* toSVGFEMergeNodeElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(SVGNames::feMergeNodeTag));
- return static_cast<SVGFEMergeNodeElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(SVGFEMergeNodeElement, hasTagName(SVGNames::feMergeNodeTag));
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFEMorphologyElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGFEMorphologyElement.cpp
index 4502e22e521..4f5385824e7 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFEMorphologyElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFEMorphologyElement.cpp
@@ -22,7 +22,7 @@
#include "core/svg/SVGFEMorphologyElement.h"
#include "SVGNames.h"
-#include "core/platform/graphics/filters/FilterEffect.h"
+#include "platform/graphics/filters/FilterEffect.h"
#include "core/svg/SVGElementInstance.h"
#include "core/svg/SVGParserUtilities.h"
#include "core/svg/graphics/filters/SVGFilterBuilder.h"
@@ -43,18 +43,17 @@ BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGFEMorphologyElement)
REGISTER_PARENT_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
END_REGISTER_ANIMATED_PROPERTIES
-inline SVGFEMorphologyElement::SVGFEMorphologyElement(const QualifiedName& tagName, Document& document)
- : SVGFilterPrimitiveStandardAttributes(tagName, document)
+inline SVGFEMorphologyElement::SVGFEMorphologyElement(Document& document)
+ : SVGFilterPrimitiveStandardAttributes(SVGNames::feMorphologyTag, document)
, m_svgOperator(FEMORPHOLOGY_OPERATOR_ERODE)
{
- ASSERT(hasTagName(SVGNames::feMorphologyTag));
ScriptWrappable::init(this);
registerAnimatedPropertiesForSVGFEMorphologyElement();
}
-PassRefPtr<SVGFEMorphologyElement> SVGFEMorphologyElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFEMorphologyElement> SVGFEMorphologyElement::create(Document& document)
{
- return adoptRef(new SVGFEMorphologyElement(tagName, document));
+ return adoptRef(new SVGFEMorphologyElement(document));
}
const AtomicString& SVGFEMorphologyElement::radiusXIdentifier()
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFEMorphologyElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGFEMorphologyElement.h
index 38dede0489d..5462712fdd7 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFEMorphologyElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFEMorphologyElement.h
@@ -20,10 +20,10 @@
#ifndef SVGFEMorphologyElement_h
#define SVGFEMorphologyElement_h
-#include "core/platform/graphics/filters/FEMorphology.h"
#include "core/svg/SVGAnimatedEnumeration.h"
#include "core/svg/SVGAnimatedNumber.h"
#include "core/svg/SVGFilterPrimitiveStandardAttributes.h"
+#include "platform/graphics/filters/FEMorphology.h"
namespace WebCore {
@@ -58,12 +58,12 @@ struct SVGPropertyTraits<MorphologyOperatorType> {
class SVGFEMorphologyElement FINAL : public SVGFilterPrimitiveStandardAttributes {
public:
- static PassRefPtr<SVGFEMorphologyElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGFEMorphologyElement> create(Document&);
void setRadius(float radiusX, float radiusY);
private:
- SVGFEMorphologyElement(const QualifiedName&, Document&);
+ explicit SVGFEMorphologyElement(Document&);
bool isSupportedAttribute(const QualifiedName&);
virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFEOffsetElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGFEOffsetElement.cpp
index a110b837e55..7b29b59b8a4 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFEOffsetElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFEOffsetElement.cpp
@@ -23,7 +23,7 @@
#include "core/svg/SVGFEOffsetElement.h"
#include "SVGNames.h"
-#include "core/platform/graphics/filters/FilterEffect.h"
+#include "platform/graphics/filters/FilterEffect.h"
#include "core/svg/SVGElementInstance.h"
#include "core/svg/graphics/filters/SVGFilterBuilder.h"
@@ -41,17 +41,16 @@ BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGFEOffsetElement)
REGISTER_PARENT_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
END_REGISTER_ANIMATED_PROPERTIES
-inline SVGFEOffsetElement::SVGFEOffsetElement(const QualifiedName& tagName, Document& document)
- : SVGFilterPrimitiveStandardAttributes(tagName, document)
+inline SVGFEOffsetElement::SVGFEOffsetElement(Document& document)
+ : SVGFilterPrimitiveStandardAttributes(SVGNames::feOffsetTag, document)
{
- ASSERT(hasTagName(SVGNames::feOffsetTag));
ScriptWrappable::init(this);
registerAnimatedPropertiesForSVGFEOffsetElement();
}
-PassRefPtr<SVGFEOffsetElement> SVGFEOffsetElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFEOffsetElement> SVGFEOffsetElement::create(Document& document)
{
- return adoptRef(new SVGFEOffsetElement(tagName, document));
+ return adoptRef(new SVGFEOffsetElement(document));
}
bool SVGFEOffsetElement::isSupportedAttribute(const QualifiedName& attrName)
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFEOffsetElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGFEOffsetElement.h
index a0489a43811..74278647990 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFEOffsetElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFEOffsetElement.h
@@ -21,18 +21,18 @@
#ifndef SVGFEOffsetElement_h
#define SVGFEOffsetElement_h
-#include "core/platform/graphics/filters/FEOffset.h"
#include "core/svg/SVGAnimatedNumber.h"
#include "core/svg/SVGFilterPrimitiveStandardAttributes.h"
+#include "platform/graphics/filters/FEOffset.h"
namespace WebCore {
class SVGFEOffsetElement FINAL : public SVGFilterPrimitiveStandardAttributes {
public:
- static PassRefPtr<SVGFEOffsetElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGFEOffsetElement> create(Document&);
private:
- SVGFEOffsetElement(const QualifiedName&, Document&);
+ explicit SVGFEOffsetElement(Document&);
bool isSupportedAttribute(const QualifiedName&);
virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFEPointLightElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGFEPointLightElement.cpp
index 0f971b1bf47..aba77a621b8 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFEPointLightElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFEPointLightElement.cpp
@@ -18,24 +18,22 @@
*/
#include "config.h"
-
-#include "SVGNames.h"
#include "core/svg/SVGFEPointLightElement.h"
-#include "core/platform/graphics/filters/PointLightSource.h"
+#include "SVGNames.h"
+#include "platform/graphics/filters/PointLightSource.h"
namespace WebCore {
-inline SVGFEPointLightElement::SVGFEPointLightElement(const QualifiedName& tagName, Document& document)
- : SVGFELightElement(tagName, document)
+inline SVGFEPointLightElement::SVGFEPointLightElement(Document& document)
+ : SVGFELightElement(SVGNames::fePointLightTag, document)
{
- ASSERT(hasTagName(SVGNames::fePointLightTag));
ScriptWrappable::init(this);
}
-PassRefPtr<SVGFEPointLightElement> SVGFEPointLightElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFEPointLightElement> SVGFEPointLightElement::create(Document& document)
{
- return adoptRef(new SVGFEPointLightElement(tagName, document));
+ return adoptRef(new SVGFEPointLightElement(document));
}
PassRefPtr<LightSource> SVGFEPointLightElement::lightSource() const
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFEPointLightElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGFEPointLightElement.h
index 10bdec9e04a..b32b9516fb9 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFEPointLightElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFEPointLightElement.h
@@ -26,10 +26,10 @@ namespace WebCore {
class SVGFEPointLightElement FINAL : public SVGFELightElement {
public:
- static PassRefPtr<SVGFEPointLightElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGFEPointLightElement> create(Document&);
private:
- SVGFEPointLightElement(const QualifiedName&, Document&);
+ explicit SVGFEPointLightElement(Document&);
virtual PassRefPtr<LightSource> lightSource() const;
};
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFESpecularLightingElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGFESpecularLightingElement.cpp
index 12cd0c7f4f0..eee19788f0e 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFESpecularLightingElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFESpecularLightingElement.cpp
@@ -23,11 +23,9 @@
#include "core/svg/SVGFESpecularLightingElement.h"
-#include "SVGNames.h"
-#include "core/platform/graphics/filters/FilterEffect.h"
+#include "platform/graphics/filters/FilterEffect.h"
#include "core/rendering/style/RenderStyle.h"
#include "core/svg/SVGElementInstance.h"
-#include "core/svg/SVGFELightElement.h"
#include "core/svg/SVGParserUtilities.h"
#include "core/svg/graphics/filters/SVGFilterBuilder.h"
@@ -51,20 +49,19 @@ BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGFESpecularLightingElement)
REGISTER_PARENT_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
END_REGISTER_ANIMATED_PROPERTIES
-inline SVGFESpecularLightingElement::SVGFESpecularLightingElement(const QualifiedName& tagName, Document& document)
- : SVGFilterPrimitiveStandardAttributes(tagName, document)
+inline SVGFESpecularLightingElement::SVGFESpecularLightingElement(Document& document)
+ : SVGFilterPrimitiveStandardAttributes(SVGNames::feSpecularLightingTag, document)
, m_specularConstant(1)
, m_specularExponent(1)
, m_surfaceScale(1)
{
- ASSERT(hasTagName(SVGNames::feSpecularLightingTag));
ScriptWrappable::init(this);
registerAnimatedPropertiesForSVGFESpecularLightingElement();
}
-PassRefPtr<SVGFESpecularLightingElement> SVGFESpecularLightingElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFESpecularLightingElement> SVGFESpecularLightingElement::create(Document& document)
{
- return adoptRef(new SVGFESpecularLightingElement(tagName, document));
+ return adoptRef(new SVGFESpecularLightingElement(document));
}
const AtomicString& SVGFESpecularLightingElement::kernelUnitLengthXIdentifier()
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFESpecularLightingElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGFESpecularLightingElement.h
index 38d5d620e4a..f76b161286d 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFESpecularLightingElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFESpecularLightingElement.h
@@ -23,20 +23,20 @@
#define SVGFESpecularLightingElement_h
#include "SVGNames.h"
-#include "core/platform/graphics/filters/FESpecularLighting.h"
#include "core/svg/SVGAnimatedNumber.h"
#include "core/svg/SVGFELightElement.h"
#include "core/svg/SVGFilterPrimitiveStandardAttributes.h"
+#include "platform/graphics/filters/FESpecularLighting.h"
namespace WebCore {
class SVGFESpecularLightingElement FINAL : public SVGFilterPrimitiveStandardAttributes {
public:
- static PassRefPtr<SVGFESpecularLightingElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGFESpecularLightingElement> create(Document&);
void lightElementAttributeChanged(const SVGFELightElement*, const QualifiedName&);
private:
- SVGFESpecularLightingElement(const QualifiedName&, Document&);
+ explicit SVGFESpecularLightingElement(Document&);
bool isSupportedAttribute(const QualifiedName&);
virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
@@ -57,11 +57,7 @@ private:
END_DECLARE_ANIMATED_PROPERTIES
};
-inline SVGFESpecularLightingElement* toSVGFESpecularLightingElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(SVGNames::feSpecularLightingTag));
- return static_cast<SVGFESpecularLightingElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(SVGFESpecularLightingElement, hasTagName(SVGNames::feSpecularLightingTag));
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFESpotLightElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGFESpotLightElement.cpp
index c41e52aca2d..2eafdb32874 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFESpotLightElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFESpotLightElement.cpp
@@ -18,24 +18,22 @@
*/
#include "config.h"
-
-#include "SVGNames.h"
#include "core/svg/SVGFESpotLightElement.h"
-#include "core/platform/graphics/filters/SpotLightSource.h"
+#include "SVGNames.h"
+#include "platform/graphics/filters/SpotLightSource.h"
namespace WebCore {
-inline SVGFESpotLightElement::SVGFESpotLightElement(const QualifiedName& tagName, Document& document)
- : SVGFELightElement(tagName, document)
+inline SVGFESpotLightElement::SVGFESpotLightElement(Document& document)
+ : SVGFELightElement(SVGNames::feSpotLightTag, document)
{
- ASSERT(hasTagName(SVGNames::feSpotLightTag));
ScriptWrappable::init(this);
}
-PassRefPtr<SVGFESpotLightElement> SVGFESpotLightElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFESpotLightElement> SVGFESpotLightElement::create(Document& document)
{
- return adoptRef(new SVGFESpotLightElement(tagName, document));
+ return adoptRef(new SVGFESpotLightElement(document));
}
PassRefPtr<LightSource> SVGFESpotLightElement::lightSource() const
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFESpotLightElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGFESpotLightElement.h
index 3b0ca9c698c..a36d7628408 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFESpotLightElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFESpotLightElement.h
@@ -26,10 +26,10 @@ namespace WebCore {
class SVGFESpotLightElement FINAL : public SVGFELightElement {
public:
- static PassRefPtr<SVGFESpotLightElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGFESpotLightElement> create(Document&);
private:
- SVGFESpotLightElement(const QualifiedName&, Document&);
+ explicit SVGFESpotLightElement(Document&);
virtual PassRefPtr<LightSource> lightSource() const;
};
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFETileElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGFETileElement.cpp
index 44b94a04320..f9833e817ed 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFETileElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFETileElement.cpp
@@ -23,7 +23,7 @@
#include "core/svg/SVGFETileElement.h"
#include "SVGNames.h"
-#include "core/platform/graphics/filters/FilterEffect.h"
+#include "platform/graphics/filters/FilterEffect.h"
#include "core/svg/SVGElementInstance.h"
#include "core/svg/graphics/filters/SVGFilterBuilder.h"
@@ -37,17 +37,16 @@ BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGFETileElement)
REGISTER_PARENT_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
END_REGISTER_ANIMATED_PROPERTIES
-inline SVGFETileElement::SVGFETileElement(const QualifiedName& tagName, Document& document)
- : SVGFilterPrimitiveStandardAttributes(tagName, document)
+inline SVGFETileElement::SVGFETileElement(Document& document)
+ : SVGFilterPrimitiveStandardAttributes(SVGNames::feTileTag, document)
{
- ASSERT(hasTagName(SVGNames::feTileTag));
ScriptWrappable::init(this);
registerAnimatedPropertiesForSVGFETileElement();
}
-PassRefPtr<SVGFETileElement> SVGFETileElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFETileElement> SVGFETileElement::create(Document& document)
{
- return adoptRef(new SVGFETileElement(tagName, document));
+ return adoptRef(new SVGFETileElement(document));
}
bool SVGFETileElement::isSupportedAttribute(const QualifiedName& attrName)
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFETileElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGFETileElement.h
index 005c53b91b5..0e605cd726c 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFETileElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFETileElement.h
@@ -21,17 +21,17 @@
#ifndef SVGFETileElement_h
#define SVGFETileElement_h
-#include "core/platform/graphics/filters/FETile.h"
#include "core/svg/SVGFilterPrimitiveStandardAttributes.h"
+#include "platform/graphics/filters/FETile.h"
namespace WebCore {
class SVGFETileElement FINAL : public SVGFilterPrimitiveStandardAttributes {
public:
- static PassRefPtr<SVGFETileElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGFETileElement> create(Document&);
private:
- SVGFETileElement(const QualifiedName&, Document&);
+ explicit SVGFETileElement(Document&);
bool isSupportedAttribute(const QualifiedName&);
virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFETurbulenceElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGFETurbulenceElement.cpp
index 14236b2c0e4..b020f0fe1e4 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFETurbulenceElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFETurbulenceElement.cpp
@@ -46,20 +46,19 @@ BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGFETurbulenceElement)
REGISTER_PARENT_ANIMATED_PROPERTIES(SVGFilterPrimitiveStandardAttributes)
END_REGISTER_ANIMATED_PROPERTIES
-inline SVGFETurbulenceElement::SVGFETurbulenceElement(const QualifiedName& tagName, Document& document)
- : SVGFilterPrimitiveStandardAttributes(tagName, document)
+inline SVGFETurbulenceElement::SVGFETurbulenceElement(Document& document)
+ : SVGFilterPrimitiveStandardAttributes(SVGNames::feTurbulenceTag, document)
, m_numOctaves(1)
, m_stitchTiles(SVG_STITCHTYPE_NOSTITCH)
, m_type(FETURBULENCE_TYPE_TURBULENCE)
{
- ASSERT(hasTagName(SVGNames::feTurbulenceTag));
ScriptWrappable::init(this);
registerAnimatedPropertiesForSVGFETurbulenceElement();
}
-PassRefPtr<SVGFETurbulenceElement> SVGFETurbulenceElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFETurbulenceElement> SVGFETurbulenceElement::create(Document& document)
{
- return adoptRef(new SVGFETurbulenceElement(tagName, document));
+ return adoptRef(new SVGFETurbulenceElement(document));
}
const AtomicString& SVGFETurbulenceElement::baseFrequencyXIdentifier()
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFETurbulenceElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGFETurbulenceElement.h
index c77eceb7ed0..b9ead22cab9 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFETurbulenceElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFETurbulenceElement.h
@@ -21,11 +21,11 @@
#ifndef SVGFETurbulenceElement_h
#define SVGFETurbulenceElement_h
-#include "core/platform/graphics/filters/FETurbulence.h"
#include "core/svg/SVGAnimatedEnumeration.h"
#include "core/svg/SVGAnimatedInteger.h"
#include "core/svg/SVGAnimatedNumber.h"
#include "core/svg/SVGFilterPrimitiveStandardAttributes.h"
+#include "platform/graphics/filters/FETurbulence.h"
namespace WebCore {
@@ -95,10 +95,10 @@ struct SVGPropertyTraits<TurbulenceType> {
class SVGFETurbulenceElement FINAL : public SVGFilterPrimitiveStandardAttributes {
public:
- static PassRefPtr<SVGFETurbulenceElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGFETurbulenceElement> create(Document&);
private:
- SVGFETurbulenceElement(const QualifiedName&, Document&);
+ explicit SVGFETurbulenceElement(Document&);
bool isSupportedAttribute(const QualifiedName&);
virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFilterElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGFilterElement.cpp
index 391a1d88b19..332233635d1 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFilterElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFilterElement.cpp
@@ -25,7 +25,6 @@
#include "core/svg/SVGFilterElement.h"
-#include "SVGNames.h"
#include "XLinkNames.h"
#include "core/rendering/svg/RenderSVGResourceFilter.h"
#include "core/svg/SVGElementInstance.h"
@@ -58,8 +57,8 @@ BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGFilterElement)
REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired)
END_REGISTER_ANIMATED_PROPERTIES
-inline SVGFilterElement::SVGFilterElement(const QualifiedName& tagName, Document& document)
- : SVGElement(tagName, document)
+inline SVGFilterElement::SVGFilterElement(Document& document)
+ : SVGElement(SVGNames::filterTag, document)
, m_filterUnits(SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX)
, m_primitiveUnits(SVGUnitTypes::SVG_UNIT_TYPE_USERSPACEONUSE)
, m_x(LengthModeWidth, "-10%")
@@ -69,14 +68,13 @@ inline SVGFilterElement::SVGFilterElement(const QualifiedName& tagName, Document
{
// Spec: If the x/y attribute is not specified, the effect is as if a value of "-10%" were specified.
// Spec: If the width/height attribute is not specified, the effect is as if a value of "120%" were specified.
- ASSERT(hasTagName(SVGNames::filterTag));
ScriptWrappable::init(this);
registerAnimatedPropertiesForSVGFilterElement();
}
-PassRefPtr<SVGFilterElement> SVGFilterElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFilterElement> SVGFilterElement::create(Document& document)
{
- return adoptRef(new SVGFilterElement(tagName, document));
+ return adoptRef(new SVGFilterElement(document));
}
const AtomicString& SVGFilterElement::filterResXIdentifier()
@@ -96,8 +94,9 @@ void SVGFilterElement::setFilterRes(unsigned filterResX, unsigned filterResY)
setFilterResXBaseValue(filterResX);
setFilterResYBaseValue(filterResY);
- if (RenderObject* object = renderer())
- object->setNeedsLayout();
+ RenderSVGResourceContainer* renderer = toRenderSVGResourceContainer(this->renderer());
+ if (renderer)
+ renderer->invalidateCacheAndMarkForLayout();
}
bool SVGFilterElement::isSupportedAttribute(const QualifiedName& attrName)
@@ -168,8 +167,9 @@ void SVGFilterElement::svgAttributeChanged(const QualifiedName& attrName)
|| attrName == SVGNames::heightAttr)
updateRelativeLengthsInformation();
- if (RenderObject* object = renderer())
- object->setNeedsLayout();
+ RenderSVGResourceContainer* renderer = toRenderSVGResourceContainer(this->renderer());
+ if (renderer)
+ renderer->invalidateCacheAndMarkForLayout();
}
void SVGFilterElement::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFilterElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGFilterElement.h
index d344fd280b2..791939a0f5b 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFilterElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFilterElement.h
@@ -39,14 +39,14 @@ class SVGFilterElement FINAL : public SVGElement,
public SVGURIReference,
public SVGExternalResourcesRequired {
public:
- static PassRefPtr<SVGFilterElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGFilterElement> create(Document&);
void setFilterRes(unsigned filterResX, unsigned filterResY);
void addClient(Node*);
void removeClient(Node*);
private:
- SVGFilterElement(const QualifiedName&, Document&);
+ explicit SVGFilterElement(Document&);
virtual bool needsPendingResourceHandling() const { return false; }
@@ -79,11 +79,7 @@ private:
HashSet<RefPtr<Node> > m_clientsToAdd;
};
-inline SVGFilterElement* toSVGFilterElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(SVGNames::filterTag));
- return static_cast<SVGFilterElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(SVGFilterElement, hasTagName(SVGNames::filterTag));
}
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFilterPrimitiveStandardAttributes.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGFilterPrimitiveStandardAttributes.cpp
index 5299939d0b6..cb25ed470d9 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFilterPrimitiveStandardAttributes.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFilterPrimitiveStandardAttributes.cpp
@@ -24,7 +24,7 @@
#include "core/svg/SVGFilterPrimitiveStandardAttributes.h"
#include "SVGNames.h"
-#include "core/platform/graphics/filters/FilterEffect.h"
+#include "platform/graphics/filters/FilterEffect.h"
#include "core/rendering/svg/RenderSVGResourceFilterPrimitive.h"
#include "core/svg/SVGElementInstance.h"
#include "core/svg/SVGLength.h"
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFitToViewBox.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGFitToViewBox.cpp
index ed7de02c660..60425c87a88 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFitToViewBox.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFitToViewBox.cpp
@@ -22,14 +22,12 @@
#include "core/svg/SVGFitToViewBox.h"
-#include "SVGNames.h"
#include "core/dom/Attribute.h"
#include "core/dom/Document.h"
-#include "core/platform/graphics/FloatRect.h"
-#include "core/platform/graphics/transforms/AffineTransform.h"
#include "core/svg/SVGDocumentExtensions.h"
#include "core/svg/SVGParserUtilities.h"
-#include "core/svg/SVGPreserveAspectRatio.h"
+#include "platform/geometry/FloatRect.h"
+#include "platform/transforms/AffineTransform.h"
#include "wtf/text/StringImpl.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFitToViewBox.h b/chromium/third_party/WebKit/Source/core/svg/SVGFitToViewBox.h
index 65284454aea..ba8ca3cf8fa 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFitToViewBox.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFitToViewBox.h
@@ -23,8 +23,8 @@
#include "SVGNames.h"
#include "core/dom/QualifiedName.h"
-#include "core/platform/graphics/FloatRect.h"
#include "core/svg/SVGPreserveAspectRatio.h"
+#include "core/svg/SVGRect.h"
#include "wtf/HashSet.h"
namespace WebCore {
@@ -46,7 +46,10 @@ public:
if (name == SVGNames::viewBoxAttr) {
FloatRect viewBox;
bool valueIsValid = !value.isNull() && parseViewBox(&target->document(), value, viewBox);
- target->setViewBoxBaseValue(viewBox, valueIsValid);
+ if (valueIsValid)
+ target->setViewBoxBaseValue(viewBox);
+ else
+ target->setViewBoxBaseValue(SVGRect(SVGRect::InvalidSVGRectTag()));
return true;
}
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFontData.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGFontData.cpp
index 45a5d49292a..64b6b3de5ca 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFontData.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFontData.cpp
@@ -24,15 +24,16 @@
#include "SVGNames.h"
#include "XMLNames.h"
-#include "core/platform/graphics/SVGGlyph.h"
-#include "core/platform/graphics/TextRun.h"
-#include "core/platform/graphics/WidthIterator.h"
#include "core/rendering/RenderObject.h"
#include "core/rendering/svg/SVGTextRunRenderingContext.h"
#include "core/svg/SVGAltGlyphElement.h"
#include "core/svg/SVGFontElement.h"
#include "core/svg/SVGFontFaceElement.h"
#include "core/svg/SVGGlyphElement.h"
+#include "platform/fonts/SVGGlyph.h"
+#include "platform/fonts/SimpleFontData.h"
+#include "platform/fonts/WidthIterator.h"
+#include "platform/text/TextRun.h"
#include "wtf/text/StringBuilder.h"
#include "wtf/unicode/CharacterNames.h"
#include "wtf/unicode/Unicode.h"
@@ -43,7 +44,8 @@ using namespace Unicode;
namespace WebCore {
SVGFontData::SVGFontData(SVGFontFaceElement* fontFaceElement)
- : m_svgFontFaceElement(fontFaceElement)
+ : CustomFontData(false)
+ , m_svgFontFaceElement(fontFaceElement)
, m_horizontalOriginX(fontFaceElement->horizontalOriginX())
, m_horizontalOriginY(fontFaceElement->horizontalOriginY())
, m_horizontalAdvanceX(fontFaceElement->horizontalAdvanceX())
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFontData.h b/chromium/third_party/WebKit/Source/core/svg/SVGFontData.h
index 1e20938742d..8d4483fbfd7 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFontData.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFontData.h
@@ -21,26 +21,30 @@
#define SVGFontData_h
#if ENABLE(SVG_FONTS)
-#include "core/platform/graphics/SimpleFontData.h"
+#include "platform/fonts/CustomFontData.h"
+#include "wtf/text/WTFString.h"
namespace WebCore {
+class SimpleFontData;
class SVGFontElement;
class SVGFontFaceElement;
-class SVGFontData : public SimpleFontData::AdditionalFontData {
+class SVGFontData FINAL : public CustomFontData {
public:
- static PassOwnPtr<SVGFontData> create(SVGFontFaceElement* element)
+ static PassRefPtr<SVGFontData> create(SVGFontFaceElement* element)
{
- return adoptPtr(new SVGFontData(element));
+ return adoptRef(new SVGFontData(element));
}
virtual ~SVGFontData() { }
- virtual void initializeFontData(SimpleFontData*, float fontSize);
- virtual float widthForSVGGlyph(Glyph, float fontSize) const;
- virtual bool fillSVGGlyphPage(GlyphPage*, unsigned offset, unsigned length, UChar* buffer, unsigned bufferLength, const SimpleFontData*) const;
- virtual bool applySVGGlyphSelection(WidthIterator&, GlyphData&, bool mirror, int currentCharacter, unsigned& advanceLength) const;
+ virtual bool isSVGFont() const OVERRIDE { return true; };
+ virtual void initializeFontData(SimpleFontData*, float fontSize) OVERRIDE;
+ virtual float widthForSVGGlyph(Glyph, float fontSize) const OVERRIDE;
+ virtual bool fillSVGGlyphPage(GlyphPage*, unsigned offset, unsigned length, UChar* buffer, unsigned bufferLength, const SimpleFontData*) const OVERRIDE;
+ virtual bool applySVGGlyphSelection(WidthIterator&, GlyphData&, bool mirror, int currentCharacter, unsigned& advanceLength) const OVERRIDE;
+
SVGFontFaceElement* svgFontFaceElement() const { return m_svgFontFaceElement; }
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFontElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGFontElement.cpp
index ab333c079cd..6f956f582af 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFontElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFontElement.cpp
@@ -24,8 +24,7 @@
#if ENABLE(SVG_FONTS)
#include "core/svg/SVGFontElement.h"
-#include "SVGNames.h"
-#include "core/page/UseCounter.h"
+#include "core/frame/UseCounter.h"
#include "core/svg/SVGGlyphElement.h"
#include "core/svg/SVGHKernElement.h"
#include "core/svg/SVGMissingGlyphElement.h"
@@ -42,21 +41,20 @@ BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGFontElement)
REGISTER_PARENT_ANIMATED_PROPERTIES(SVGElement)
END_REGISTER_ANIMATED_PROPERTIES
-inline SVGFontElement::SVGFontElement(const QualifiedName& tagName, Document& document)
- : SVGElement(tagName, document)
+inline SVGFontElement::SVGFontElement(Document& document)
+ : SVGElement(SVGNames::fontTag, document)
, m_missingGlyph(0)
, m_isGlyphCacheValid(false)
{
- ASSERT(hasTagName(SVGNames::fontTag));
ScriptWrappable::init(this);
registerAnimatedPropertiesForSVGFontElement();
- UseCounter::count(&document, UseCounter::SVGFontElement);
+ UseCounter::count(document, UseCounter::SVGFontElement);
}
-PassRefPtr<SVGFontElement> SVGFontElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFontElement> SVGFontElement::create(Document& document)
{
- return adoptRef(new SVGFontElement(tagName, document));
+ return adoptRef(new SVGFontElement(document));
}
void SVGFontElement::invalidateGlyphCache()
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFontElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGFontElement.h
index fefa0a543fd..f7d945ef502 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFontElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFontElement.h
@@ -55,7 +55,7 @@ class SVGMissingGlyphElement;
class SVGFontElement FINAL : public SVGElement
, public SVGExternalResourcesRequired {
public:
- static PassRefPtr<SVGFontElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGFontElement> create(Document&);
void invalidateGlyphCache();
void collectGlyphsForString(const String&, Vector<SVGGlyph>&);
@@ -71,7 +71,7 @@ public:
SVGMissingGlyphElement* firstMissingGlyphElement() const;
private:
- SVGFontElement(const QualifiedName&, Document&);
+ explicit SVGFontElement(Document&);
virtual bool rendererIsNeeded(const RenderStyle&) { return false; }
@@ -89,11 +89,7 @@ private:
bool m_isGlyphCacheValid;
};
-inline SVGFontElement* toSVGFontElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(SVGNames::fontTag));
- return static_cast<SVGFontElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(SVGFontElement, hasTagName(SVGNames::fontTag));
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFontFaceElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGFontFaceElement.cpp
index 55945a5f407..a4907f53142 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFontFaceElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFontFaceElement.cpp
@@ -27,7 +27,6 @@
#include <math.h>
#include "CSSPropertyNames.h"
#include "CSSValueKeywords.h"
-#include "SVGNames.h"
#include "core/css/CSSFontFaceSrcValue.h"
#include "core/css/CSSParser.h"
#include "core/css/CSSStyleSheet.h"
@@ -36,33 +35,32 @@
#include "core/css/StyleRule.h"
#include "core/dom/Attribute.h"
#include "core/dom/Document.h"
-#include "core/platform/graphics/Font.h"
#include "core/svg/SVGDocumentExtensions.h"
#include "core/svg/SVGFontElement.h"
#include "core/svg/SVGFontFaceSrcElement.h"
#include "core/svg/SVGGlyphElement.h"
+#include "platform/fonts/Font.h"
namespace WebCore {
using namespace SVGNames;
-inline SVGFontFaceElement::SVGFontFaceElement(const QualifiedName& tagName, Document& document)
- : SVGElement(tagName, document)
+inline SVGFontFaceElement::SVGFontFaceElement(Document& document)
+ : SVGElement(font_faceTag, document)
, m_fontFaceRule(StyleRuleFontFace::create())
, m_fontElement(0)
{
- ASSERT(hasTagName(font_faceTag));
ScriptWrappable::init(this);
- RefPtr<MutableStylePropertySet> styleDeclaration = MutableStylePropertySet::create(CSSStrictMode);
+ RefPtr<MutableStylePropertySet> styleDeclaration = MutableStylePropertySet::create(HTMLStandardMode);
m_fontFaceRule->setProperties(styleDeclaration.release());
}
-PassRefPtr<SVGFontFaceElement> SVGFontFaceElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFontFaceElement> SVGFontFaceElement::create(Document& document)
{
- return adoptRef(new SVGFontFaceElement(tagName, document));
+ return adoptRef(new SVGFontFaceElement(document));
}
-static CSSPropertyID cssPropertyIdForSVGAttributeName(const QualifiedName& attrName)
+static CSSPropertyID cssPropertyIdForFontFaceAttributeName(const QualifiedName& attrName)
{
if (!attrName.namespaceURI().isNull())
return CSSPropertyInvalid;
@@ -112,7 +110,7 @@ static CSSPropertyID cssPropertyIdForSVGAttributeName(const QualifiedName& attrN
void SVGFontFaceElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
{
- CSSPropertyID propId = cssPropertyIdForSVGAttributeName(name);
+ CSSPropertyID propId = cssPropertyIdForFontFaceAttributeName(name);
if (propId > 0) {
m_fontFaceRule->mutableProperties()->setProperty(propId, value, false);
rebuildFontFace();
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFontFaceElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGFontFaceElement.h
index 5e77bd7a176..0950ef41323 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFontFaceElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFontFaceElement.h
@@ -33,7 +33,7 @@ class StyleRuleFontFace;
class SVGFontFaceElement FINAL : public SVGElement {
public:
- static PassRefPtr<SVGFontFaceElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGFontFaceElement> create(Document&);
unsigned unitsPerEm() const;
int xHeight() const;
@@ -53,7 +53,7 @@ public:
StyleRuleFontFace* fontFaceRule() const { return m_fontFaceRule.get(); }
private:
- SVGFontFaceElement(const QualifiedName&, Document&);
+ explicit SVGFontFaceElement(Document&);
virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
@@ -67,11 +67,7 @@ private:
SVGFontElement* m_fontElement;
};
-inline SVGFontFaceElement* toSVGFontFaceElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(SVGNames::font_faceTag));
- return static_cast<SVGFontFaceElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(SVGFontFaceElement, hasTagName(SVGNames::font_faceTag));
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFontFaceFormatElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGFontFaceFormatElement.cpp
index 94970ccf26b..5468bdb240e 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFontFaceFormatElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFontFaceFormatElement.cpp
@@ -29,16 +29,15 @@ namespace WebCore {
using namespace SVGNames;
-inline SVGFontFaceFormatElement::SVGFontFaceFormatElement(const QualifiedName& tagName, Document& document)
- : SVGElement(tagName, document)
+inline SVGFontFaceFormatElement::SVGFontFaceFormatElement(Document& document)
+ : SVGElement(font_face_formatTag, document)
{
- ASSERT(hasTagName(font_face_formatTag));
ScriptWrappable::init(this);
}
-PassRefPtr<SVGFontFaceFormatElement> SVGFontFaceFormatElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFontFaceFormatElement> SVGFontFaceFormatElement::create(Document& document)
{
- return adoptRef(new SVGFontFaceFormatElement(tagName, document));
+ return adoptRef(new SVGFontFaceFormatElement(document));
}
void SVGFontFaceFormatElement::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFontFaceFormatElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGFontFaceFormatElement.h
index 33e75021bd1..986431a58bd 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFontFaceFormatElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFontFaceFormatElement.h
@@ -27,10 +27,10 @@ namespace WebCore {
class SVGFontFaceFormatElement FINAL : public SVGElement {
public:
- static PassRefPtr<SVGFontFaceFormatElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGFontFaceFormatElement> create(Document&);
private:
- SVGFontFaceFormatElement(const QualifiedName&, Document&);
+ explicit SVGFontFaceFormatElement(Document&);
virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0);
virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE { return false; }
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFontFaceNameElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGFontFaceNameElement.cpp
index 8157a5e39d1..2675278c0ff 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFontFaceNameElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFontFaceNameElement.cpp
@@ -22,21 +22,19 @@
#if ENABLE(SVG_FONTS)
#include "core/svg/SVGFontFaceNameElement.h"
-#include "SVGNames.h"
#include "core/css/CSSFontFaceSrcValue.h"
namespace WebCore {
-inline SVGFontFaceNameElement::SVGFontFaceNameElement(const QualifiedName& tagName, Document& document)
- : SVGElement(tagName, document)
+inline SVGFontFaceNameElement::SVGFontFaceNameElement(Document& document)
+ : SVGElement(SVGNames::font_face_nameTag, document)
{
- ASSERT(hasTagName(SVGNames::font_face_nameTag));
ScriptWrappable::init(this);
}
-PassRefPtr<SVGFontFaceNameElement> SVGFontFaceNameElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFontFaceNameElement> SVGFontFaceNameElement::create(Document& document)
{
- return adoptRef(new SVGFontFaceNameElement(tagName, document));
+ return adoptRef(new SVGFontFaceNameElement(document));
}
PassRefPtr<CSSFontFaceSrcValue> SVGFontFaceNameElement::srcValue() const
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFontFaceNameElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGFontFaceNameElement.h
index 1339e4aa618..8b9394278c3 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFontFaceNameElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFontFaceNameElement.h
@@ -30,21 +30,17 @@ class CSSFontFaceSrcValue;
class SVGFontFaceNameElement FINAL : public SVGElement {
public:
- static PassRefPtr<SVGFontFaceNameElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGFontFaceNameElement> create(Document&);
PassRefPtr<CSSFontFaceSrcValue> srcValue() const;
private:
- SVGFontFaceNameElement(const QualifiedName&, Document&);
+ explicit SVGFontFaceNameElement(Document&);
virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE { return false; }
};
-inline SVGFontFaceNameElement* toSVGFontFaceNameElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(SVGNames::font_face_nameTag));
- return static_cast<SVGFontFaceNameElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(SVGFontFaceNameElement, hasTagName(SVGNames::font_face_nameTag));
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFontFaceSrcElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGFontFaceSrcElement.cpp
index e5ba1db9634..bc2254ddea8 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFontFaceSrcElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFontFaceSrcElement.cpp
@@ -33,16 +33,15 @@ namespace WebCore {
using namespace SVGNames;
-inline SVGFontFaceSrcElement::SVGFontFaceSrcElement(const QualifiedName& tagName, Document& document)
- : SVGElement(tagName, document)
+inline SVGFontFaceSrcElement::SVGFontFaceSrcElement(Document& document)
+ : SVGElement(font_face_srcTag, document)
{
- ASSERT(hasTagName(font_face_srcTag));
ScriptWrappable::init(this);
}
-PassRefPtr<SVGFontFaceSrcElement> SVGFontFaceSrcElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFontFaceSrcElement> SVGFontFaceSrcElement::create(Document& document)
{
- return adoptRef(new SVGFontFaceSrcElement(tagName, document));
+ return adoptRef(new SVGFontFaceSrcElement(document));
}
PassRefPtr<CSSValueList> SVGFontFaceSrcElement::srcValue() const
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFontFaceSrcElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGFontFaceSrcElement.h
index eb11d7b1d00..f7ef1af6f6b 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFontFaceSrcElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFontFaceSrcElement.h
@@ -29,12 +29,12 @@ class CSSValueList;
class SVGFontFaceSrcElement FINAL : public SVGElement {
public:
- static PassRefPtr<SVGFontFaceSrcElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGFontFaceSrcElement> create(Document&);
PassRefPtr<CSSValueList> srcValue() const;
private:
- SVGFontFaceSrcElement(const QualifiedName&, Document&);
+ explicit SVGFontFaceSrcElement(Document&);
virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0);
virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE { return false; }
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFontFaceUriElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGFontFaceUriElement.cpp
index f5168be5be3..fabcf7f5b0c 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFontFaceUriElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFontFaceUriElement.cpp
@@ -23,12 +23,10 @@
#if ENABLE(SVG_FONTS)
#include "core/svg/SVGFontFaceUriElement.h"
-#include "SVGNames.h"
#include "XLinkNames.h"
#include "core/css/CSSFontFaceSrcValue.h"
#include "core/dom/Document.h"
#include "core/fetch/FetchRequest.h"
-#include "core/fetch/FontResource.h"
#include "core/fetch/ResourceFetcher.h"
#include "core/svg/SVGFontFaceElement.h"
@@ -36,16 +34,15 @@ namespace WebCore {
using namespace SVGNames;
-inline SVGFontFaceUriElement::SVGFontFaceUriElement(const QualifiedName& tagName, Document& document)
- : SVGElement(tagName, document)
+inline SVGFontFaceUriElement::SVGFontFaceUriElement(Document& document)
+ : SVGElement(font_face_uriTag, document)
{
- ASSERT(hasTagName(font_face_uriTag));
ScriptWrappable::init(this);
}
-PassRefPtr<SVGFontFaceUriElement> SVGFontFaceUriElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGFontFaceUriElement> SVGFontFaceUriElement::create(Document& document)
{
- return adoptRef(new SVGFontFaceUriElement(tagName, document));
+ return adoptRef(new SVGFontFaceUriElement(document));
}
SVGFontFaceUriElement::~SVGFontFaceUriElement()
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGFontFaceUriElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGFontFaceUriElement.h
index 8a3f84eedd5..338ce85b115 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGFontFaceUriElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGFontFaceUriElement.h
@@ -32,14 +32,14 @@ class CSSFontFaceSrcValue;
class SVGFontFaceUriElement FINAL : public SVGElement, public FontResourceClient {
public:
- static PassRefPtr<SVGFontFaceUriElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGFontFaceUriElement> create(Document&);
virtual ~SVGFontFaceUriElement();
PassRefPtr<CSSFontFaceSrcValue> srcValue() const;
private:
- SVGFontFaceUriElement(const QualifiedName&, Document&);
+ explicit SVGFontFaceUriElement(Document&);
virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0);
@@ -52,11 +52,7 @@ private:
ResourcePtr<FontResource> m_resource;
};
-inline SVGFontFaceUriElement* toSVGFontFaceUriElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(SVGNames::font_face_uriTag));
- return static_cast<SVGFontFaceUriElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(SVGFontFaceUriElement, hasTagName(SVGNames::font_face_uriTag));
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGForeignObjectElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGForeignObjectElement.cpp
index e8a99a2b701..8db9e53ced7 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGForeignObjectElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGForeignObjectElement.cpp
@@ -21,7 +21,6 @@
#include "config.h"
#include "core/svg/SVGForeignObjectElement.h"
-#include "SVGNames.h"
#include "XLinkNames.h"
#include "core/rendering/svg/RenderSVGForeignObject.h"
#include "core/rendering/svg/RenderSVGResource.h"
@@ -49,21 +48,20 @@ BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGForeignObjectElement)
REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
END_REGISTER_ANIMATED_PROPERTIES
-inline SVGForeignObjectElement::SVGForeignObjectElement(const QualifiedName& tagName, Document& document)
- : SVGGraphicsElement(tagName, document)
+inline SVGForeignObjectElement::SVGForeignObjectElement(Document& document)
+ : SVGGraphicsElement(SVGNames::foreignObjectTag, document)
, m_x(LengthModeWidth)
, m_y(LengthModeHeight)
, m_width(LengthModeWidth)
, m_height(LengthModeHeight)
{
- ASSERT(hasTagName(SVGNames::foreignObjectTag));
ScriptWrappable::init(this);
registerAnimatedPropertiesForSVGForeignObjectElement();
}
-PassRefPtr<SVGForeignObjectElement> SVGForeignObjectElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGForeignObjectElement> SVGForeignObjectElement::create(Document& document)
{
- return adoptRef(new SVGForeignObjectElement(tagName, document));
+ return adoptRef(new SVGForeignObjectElement(document));
}
bool SVGForeignObjectElement::isSupportedAttribute(const QualifiedName& attrName)
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGForeignObjectElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGForeignObjectElement.h
index 83018a89a72..38d3734f37e 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGForeignObjectElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGForeignObjectElement.h
@@ -32,10 +32,10 @@ namespace WebCore {
class SVGForeignObjectElement FINAL : public SVGGraphicsElement,
public SVGExternalResourcesRequired {
public:
- static PassRefPtr<SVGForeignObjectElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGForeignObjectElement> create(Document&);
private:
- SVGForeignObjectElement(const QualifiedName&, Document&);
+ explicit SVGForeignObjectElement(Document&);
virtual bool isValid() const { return SVGTests::isValid(); }
bool isSupportedAttribute(const QualifiedName&);
@@ -58,11 +58,7 @@ private:
END_DECLARE_ANIMATED_PROPERTIES
};
-inline SVGForeignObjectElement* toSVGForeignObjectElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(SVGNames::foreignObjectTag));
- return static_cast<SVGForeignObjectElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(SVGForeignObjectElement, hasTagName(SVGNames::foreignObjectTag));
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGGElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGGElement.cpp
index 20e2dd875fa..6345cc7570f 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGGElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGGElement.cpp
@@ -38,17 +38,16 @@ BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGGElement)
REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
END_REGISTER_ANIMATED_PROPERTIES
-SVGGElement::SVGGElement(const QualifiedName& tagName, Document& document, ConstructionType constructionType)
- : SVGGraphicsElement(tagName, document, constructionType)
+SVGGElement::SVGGElement(Document& document, ConstructionType constructionType)
+ : SVGGraphicsElement(SVGNames::gTag, document, constructionType)
{
- ASSERT(hasTagName(SVGNames::gTag));
ScriptWrappable::init(this);
registerAnimatedPropertiesForSVGGElement();
}
-PassRefPtr<SVGGElement> SVGGElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGGElement> SVGGElement::create(Document& document)
{
- return adoptRef(new SVGGElement(tagName, document));
+ return adoptRef(new SVGGElement(document));
}
bool SVGGElement::isSupportedAttribute(const QualifiedName& attrName)
@@ -66,9 +65,6 @@ void SVGGElement::parseAttribute(const QualifiedName& name, const AtomicString&
return;
}
- if (SVGLangSpace::parseAttribute(name, value))
- return;
-
ASSERT_NOT_REACHED();
}
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGGElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGGElement.h
index ee1e91a9753..255e514de40 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGGElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGGElement.h
@@ -30,10 +30,10 @@ namespace WebCore {
class SVGGElement FINAL : public SVGGraphicsElement,
public SVGExternalResourcesRequired {
public:
- static PassRefPtr<SVGGElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGGElement> create(Document&);
protected:
- SVGGElement(const QualifiedName&, Document&, ConstructionType = CreateSVGElement);
+ explicit SVGGElement(Document&, ConstructionType = CreateSVGElement);
virtual RenderObject* createRenderer(RenderStyle*);
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGGeometryElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGGeometryElement.cpp
new file mode 100644
index 00000000000..56b3d03b560
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGGeometryElement.cpp
@@ -0,0 +1,74 @@
+/*
+ * Copyright (C) 2013 Samsung Electronics. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/svg/SVGGeometryElement.h"
+
+#include "SVGNames.h"
+#include "core/rendering/HitTestRequest.h"
+#include "core/rendering/PointerEventsHitRules.h"
+#include "core/rendering/svg/RenderSVGShape.h"
+
+namespace WebCore {
+
+SVGGeometryElement::SVGGeometryElement(const QualifiedName& tagName, Document& document, ConstructionType constructionType)
+ : SVGGraphicsElement(tagName, document, constructionType)
+{
+}
+
+bool SVGGeometryElement::isPointInFill(const SVGPoint& point) const
+{
+ document().updateLayoutIgnorePendingStylesheets();
+
+ // FIXME: Eventually we should support isPointInFill for display:none elements.
+ if (!renderer() || !renderer()->isSVGShape())
+ return false;
+
+ HitTestRequest request(HitTestRequest::ReadOnly);
+ PointerEventsHitRules hitRules(PointerEventsHitRules::SVG_GEOMETRY_HITTESTING, request, renderer()->style()->pointerEvents());
+ hitRules.canHitStroke = false;
+ return toRenderSVGShape(renderer())->nodeAtFloatPointInternal(request, point, hitRules);
+}
+
+bool SVGGeometryElement::isPointInStroke(const SVGPoint& point) const
+{
+ document().updateLayoutIgnorePendingStylesheets();
+
+ // FIXME: Eventually we should support isPointInStroke for display:none elements.
+ if (!renderer() || !renderer()->isSVGShape())
+ return false;
+
+ HitTestRequest request(HitTestRequest::ReadOnly);
+ PointerEventsHitRules hitRules(PointerEventsHitRules::SVG_GEOMETRY_HITTESTING, request, renderer()->style()->pointerEvents());
+ hitRules.canHitFill = false;
+ return toRenderSVGShape(renderer())->nodeAtFloatPointInternal(request, point, hitRules);
+}
+
+}
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGGeometryElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGGeometryElement.h
new file mode 100644
index 00000000000..09fffa51344
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGGeometryElement.h
@@ -0,0 +1,50 @@
+/*
+ * Copyright (C) 2013 Samsung Electronics. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SVGGeometryElement_h
+#define SVGGeometryElement_h
+
+#include "core/svg/SVGGraphicsElement.h"
+#include "core/svg/SVGPoint.h"
+
+namespace WebCore {
+
+class SVGGeometryElement : public SVGGraphicsElement {
+public:
+ bool isPointInFill(const SVGPoint&) const;
+ bool isPointInStroke(const SVGPoint&) const;
+
+protected:
+ SVGGeometryElement(const QualifiedName&, Document&, ConstructionType = CreateSVGElement);
+};
+
+} // namespace WebCore
+
+#endif // SVGGraphicsElement_h
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGGeometryElement.idl b/chromium/third_party/WebKit/Source/core/svg/SVGGeometryElement.idl
new file mode 100644
index 00000000000..d7837585b28
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGGeometryElement.idl
@@ -0,0 +1,34 @@
+/*
+ * Copyright (C) 2013 Samsung Electronics. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+interface SVGGeometryElement : SVGGraphicsElement {
+ boolean isPointInFill(SVGPoint point);
+ boolean isPointInStroke(SVGPoint point);
+};
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGGlyphElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGGlyphElement.cpp
index 93263a27c58..ace7f98f80e 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGGlyphElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGGlyphElement.cpp
@@ -24,23 +24,21 @@
#if ENABLE(SVG_FONTS)
#include "core/svg/SVGGlyphElement.h"
-#include "SVGNames.h"
#include "core/svg/SVGFontData.h"
#include "core/svg/SVGFontElement.h"
#include "core/svg/SVGPathUtilities.h"
namespace WebCore {
-inline SVGGlyphElement::SVGGlyphElement(const QualifiedName& tagName, Document& document)
- : SVGElement(tagName, document)
+inline SVGGlyphElement::SVGGlyphElement(Document& document)
+ : SVGElement(SVGNames::glyphTag, document)
{
- ASSERT(hasTagName(SVGNames::glyphTag));
ScriptWrappable::init(this);
}
-PassRefPtr<SVGGlyphElement> SVGGlyphElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGGlyphElement> SVGGlyphElement::create(Document& document)
{
- return adoptRef(new SVGGlyphElement(tagName, document));
+ return adoptRef(new SVGGlyphElement(document));
}
void SVGGlyphElement::invalidateGlyphCache()
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGGlyphElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGGlyphElement.h
index 2598356a5e8..565eb1de154 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGGlyphElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGGlyphElement.h
@@ -24,8 +24,8 @@
#if ENABLE(SVG_FONTS)
#include "SVGNames.h"
-#include "core/platform/graphics/SVGGlyph.h"
#include "core/svg/SVGElement.h"
+#include "platform/fonts/SVGGlyph.h"
namespace WebCore {
@@ -33,7 +33,7 @@ class SVGFontData;
class SVGGlyphElement FINAL : public SVGElement {
public:
- static PassRefPtr<SVGGlyphElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGGlyphElement> create(Document&);
SVGGlyph buildGlyphIdentifier() const;
@@ -45,7 +45,7 @@ public:
static SVGGlyph buildGenericGlyphIdentifier(const SVGElement*);
private:
- SVGGlyphElement(const QualifiedName&, Document&);
+ explicit SVGGlyphElement(Document&);
// FIXME: svgAttributeChanged missing.
virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
@@ -58,11 +58,7 @@ private:
void invalidateGlyphCache();
};
-inline SVGGlyphElement* toSVGGlyphElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(SVGNames::glyphTag));
- return static_cast<SVGGlyphElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(SVGGlyphElement, hasTagName(SVGNames::glyphTag));
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGGlyphMap.h b/chromium/third_party/WebKit/Source/core/svg/SVGGlyphMap.h
index ea45597ea2d..8e20f0644ca 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGGlyphMap.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGGlyphMap.h
@@ -21,9 +21,9 @@
#define SVGGlyphMap_h
#if ENABLE(SVG_FONTS)
-#include "core/platform/graphics/Latin1TextIterator.h"
-#include "core/platform/graphics/SVGGlyph.h"
-#include "core/platform/graphics/SurrogatePairAwareTextIterator.h"
+#include "platform/fonts/Latin1TextIterator.h"
+#include "platform/fonts/SVGGlyph.h"
+#include "platform/text/SurrogatePairAwareTextIterator.h"
#include "wtf/HashMap.h"
#include "wtf/Vector.h"
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGGlyphRefElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGGlyphRefElement.cpp
index 159a20bd67a..5fd1b1c3667 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGGlyphRefElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGGlyphRefElement.cpp
@@ -22,7 +22,6 @@
#if ENABLE(SVG_FONTS)
#include "core/svg/SVGGlyphRefElement.h"
-#include "SVGNames.h"
#include "XLinkNames.h"
#include "core/svg/SVGParserUtilities.h"
#include "wtf/text/AtomicString.h"
@@ -37,21 +36,20 @@ BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGGlyphRefElement)
REGISTER_PARENT_ANIMATED_PROPERTIES(SVGElement)
END_REGISTER_ANIMATED_PROPERTIES
-inline SVGGlyphRefElement::SVGGlyphRefElement(const QualifiedName& tagName, Document& document)
- : SVGElement(tagName, document)
+inline SVGGlyphRefElement::SVGGlyphRefElement(Document& document)
+ : SVGElement(SVGNames::glyphRefTag, document)
, m_x(0)
, m_y(0)
, m_dx(0)
, m_dy(0)
{
- ASSERT(hasTagName(SVGNames::glyphRefTag));
ScriptWrappable::init(this);
registerAnimatedPropertiesForSVGGlyphRefElement();
}
-PassRefPtr<SVGGlyphRefElement> SVGGlyphRefElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGGlyphRefElement> SVGGlyphRefElement::create(Document& document)
{
- return adoptRef(new SVGGlyphRefElement(tagName, document));
+ return adoptRef(new SVGGlyphRefElement(document));
}
bool SVGGlyphRefElement::hasValidGlyphElement(String& glyphName) const
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGGlyphRefElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGGlyphRefElement.h
index 21a2e4ff5d3..8de1d2b96ae 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGGlyphRefElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGGlyphRefElement.h
@@ -30,7 +30,7 @@ namespace WebCore {
class SVGGlyphRefElement FINAL : public SVGElement,
public SVGURIReference {
public:
- static PassRefPtr<SVGGlyphRefElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGGlyphRefElement> create(Document&);
bool hasValidGlyphElement(String& glyphName) const;
virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
@@ -48,7 +48,7 @@ public:
void setDy(float);
private:
- SVGGlyphRefElement(const QualifiedName&, Document&);
+ explicit SVGGlyphRefElement(Document&);
template<typename CharType>
void parseAttributeInternal(const QualifiedName&, const AtomicString&);
@@ -65,11 +65,7 @@ private:
float m_dy;
};
-inline SVGGlyphRefElement* toSVGGlyphRefElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(SVGNames::glyphRefTag));
- return static_cast<SVGGlyphRefElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(SVGGlyphRefElement, hasTagName(SVGNames::glyphRefTag));
}
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGGlyphRefElement.idl b/chromium/third_party/WebKit/Source/core/svg/SVGGlyphRefElement.idl
index e10bf7bae89..76a4e4a724b 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGGlyphRefElement.idl
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGGlyphRefElement.idl
@@ -22,7 +22,7 @@
] interface SVGGlyphRefElement : SVGElement {
// FIXME: Use [Reflect] after https://bugs.webkit.org/show_bug.cgi?id=64843 is fixed.
attribute DOMString glyphRef;
- [Reflect] attribute DOMString format;
+ [Reflect, TreatNullAs=NullString] attribute DOMString format;
attribute float x;
attribute float y;
attribute float dx;
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGGradientElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGGradientElement.cpp
index 2b8f6172bff..a9a85d2e449 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGGradientElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGGradientElement.cpp
@@ -23,7 +23,6 @@
#include "core/svg/SVGGradientElement.h"
-#include "SVGNames.h"
#include "XLinkNames.h"
#include "core/dom/Attribute.h"
#include "core/rendering/svg/RenderSVGHiddenContainer.h"
@@ -33,7 +32,6 @@
#include "core/svg/SVGElementInstance.h"
#include "core/svg/SVGStopElement.h"
#include "core/svg/SVGTransformList.h"
-#include "core/svg/SVGTransformable.h"
namespace WebCore {
@@ -121,8 +119,9 @@ void SVGGradientElement::svgAttributeChanged(const QualifiedName& attrName)
SVGElementInstance::InvalidationGuard invalidationGuard(this);
- if (RenderObject* object = renderer())
- object->setNeedsLayout();
+ RenderSVGResourceContainer* renderer = toRenderSVGResourceContainer(this->renderer());
+ if (renderer)
+ renderer->invalidateCacheAndMarkForLayout();
}
void SVGGradientElement::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGGradientElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGGradientElement.h
index 65f92d05aed..cb2c9162659 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGGradientElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGGradientElement.h
@@ -22,7 +22,6 @@
#define SVGGradientElement_h
#include "SVGNames.h"
-#include "core/platform/graphics/Gradient.h"
#include "core/svg/SVGAnimatedBoolean.h"
#include "core/svg/SVGAnimatedEnumeration.h"
#include "core/svg/SVGAnimatedTransformList.h"
@@ -30,6 +29,7 @@
#include "core/svg/SVGExternalResourcesRequired.h"
#include "core/svg/SVGURIReference.h"
#include "core/svg/SVGUnitTypes.h"
+#include "platform/graphics/Gradient.h"
namespace WebCore {
@@ -107,12 +107,13 @@ private:
END_DECLARE_ANIMATED_PROPERTIES
};
-inline SVGGradientElement* toSVGGradientElement(Node* node)
+inline bool isSVGGradientElement(const Node& node)
{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || (node->hasTagName(SVGNames::radialGradientTag) || node->hasTagName(SVGNames::linearGradientTag)));
- return static_cast<SVGGradientElement*>(node);
+ return node.hasTagName(SVGNames::radialGradientTag) || node.hasTagName(SVGNames::linearGradientTag);
}
+DEFINE_NODE_TYPE_CASTS_WITH_FUNCTION(SVGGradientElement);
+
} // namespace WebCore
#endif
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGGraphicsElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGGraphicsElement.cpp
index 2fec7167265..95bb0c2cd87 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGGraphicsElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGGraphicsElement.cpp
@@ -23,11 +23,11 @@
#include "core/svg/SVGGraphicsElement.h"
#include "SVGNames.h"
-#include "core/platform/graphics/transforms/AffineTransform.h"
#include "core/rendering/svg/RenderSVGPath.h"
#include "core/rendering/svg/RenderSVGResource.h"
#include "core/rendering/svg/SVGPathData.h"
#include "core/svg/SVGElementInstance.h"
+#include "platform/transforms/AffineTransform.h"
namespace WebCore {
@@ -50,14 +50,53 @@ SVGGraphicsElement::~SVGGraphicsElement()
{
}
+AffineTransform SVGGraphicsElement::getTransformToElement(SVGElement* target, ExceptionState& exceptionState)
+{
+ AffineTransform ctm = getCTM(AllowStyleUpdate);
+
+ if (target && target->isSVGGraphicsElement()) {
+ AffineTransform targetCTM = toSVGGraphicsElement(target)->getCTM(AllowStyleUpdate);
+ if (!targetCTM.isInvertible()) {
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidStateError);
+ return ctm;
+ }
+ ctm = targetCTM.inverse() * ctm;
+ }
+
+ return ctm;
+}
+
+static AffineTransform computeCTM(SVGGraphicsElement* element, SVGElement::CTMScope mode, SVGGraphicsElement::StyleUpdateStrategy styleUpdateStrategy)
+{
+ ASSERT(element);
+ if (styleUpdateStrategy == SVGGraphicsElement::AllowStyleUpdate)
+ element->document().updateLayoutIgnorePendingStylesheets();
+
+ AffineTransform ctm;
+
+ SVGElement* stopAtElement = mode == SVGGraphicsElement::NearestViewportScope ? element->nearestViewportElement() : 0;
+ for (Element* currentElement = element; currentElement; currentElement = currentElement->parentOrShadowHostElement()) {
+ if (!currentElement->isSVGElement())
+ break;
+
+ ctm = toSVGElement(currentElement)->localCoordinateSpaceTransform(mode).multiply(ctm);
+
+ // For getCTM() computation, stop at the nearest viewport element
+ if (currentElement == stopAtElement)
+ break;
+ }
+
+ return ctm;
+}
+
AffineTransform SVGGraphicsElement::getCTM(StyleUpdateStrategy styleUpdateStrategy)
{
- return SVGLocatable::computeCTM(this, SVGLocatable::NearestViewportScope, styleUpdateStrategy);
+ return computeCTM(this, NearestViewportScope, styleUpdateStrategy);
}
AffineTransform SVGGraphicsElement::getScreenCTM(StyleUpdateStrategy styleUpdateStrategy)
{
- return SVGLocatable::computeCTM(this, SVGLocatable::ScreenScope, styleUpdateStrategy);
+ return computeCTM(this, ScreenScope, styleUpdateStrategy);
}
AffineTransform SVGGraphicsElement::animatedLocalTransform() const
@@ -74,6 +113,14 @@ AffineTransform SVGGraphicsElement::animatedLocalTransform() const
// Flatten any 3D transform.
matrix = transform.toAffineTransform();
+
+ // CSS bakes the zoom factor into lengths, including translation components.
+ // In order to align CSS & SVG transforms, we need to invert this operation.
+ float zoom = style->effectiveZoom();
+ if (zoom != 1) {
+ matrix.setE(matrix.e() / zoom);
+ matrix.setF(matrix.f() / zoom);
+ }
} else {
transformCurrentValue().concatenate(matrix);
}
@@ -129,8 +176,11 @@ void SVGGraphicsElement::svgAttributeChanged(const QualifiedName& attrName)
SVGElementInstance::InvalidationGuard invalidationGuard(this);
- if (SVGTests::handleAttributeChange(this, attrName))
+ // Reattach so the isValid() check will be run again during renderer creation.
+ if (SVGTests::isKnownAttribute(attrName)) {
+ lazyReattachIfAttached();
return;
+ }
RenderObject* object = renderer();
if (!object)
@@ -145,19 +195,54 @@ void SVGGraphicsElement::svgAttributeChanged(const QualifiedName& attrName)
ASSERT_NOT_REACHED();
}
+static bool isViewportElement(Node* node)
+{
+ return (node->hasTagName(SVGNames::svgTag)
+ || node->hasTagName(SVGNames::symbolTag)
+ || node->hasTagName(SVGNames::foreignObjectTag)
+ || node->hasTagName(SVGNames::imageTag));
+}
+
SVGElement* SVGGraphicsElement::nearestViewportElement() const
{
- return SVGTransformable::nearestViewportElement(this);
+ for (Element* current = parentOrShadowHostElement(); current; current = current->parentOrShadowHostElement()) {
+ if (isViewportElement(current))
+ return toSVGElement(current);
+ }
+
+ return 0;
}
SVGElement* SVGGraphicsElement::farthestViewportElement() const
{
- return SVGTransformable::farthestViewportElement(this);
+ SVGElement* farthest = 0;
+ for (Element* current = parentOrShadowHostElement(); current; current = current->parentOrShadowHostElement()) {
+ if (isViewportElement(current))
+ farthest = toSVGElement(current);
+ }
+ return farthest;
}
-SVGRect SVGGraphicsElement::getBBox(StyleUpdateStrategy styleUpdateStrategy)
+SVGRect SVGGraphicsElement::getBBox()
{
- return SVGTransformable::getBBox(this, styleUpdateStrategy);
+ document().updateLayoutIgnorePendingStylesheets();
+
+ // FIXME: Eventually we should support getBBox for detached elements.
+ if (!renderer())
+ return SVGRect();
+
+ return renderer()->objectBoundingBox();
+}
+
+SVGRect SVGGraphicsElement::getStrokeBBox()
+{
+ document().updateLayoutIgnorePendingStylesheets();
+
+ // FIXME: Eventually we should support getStrokeBBox for detached elements.
+ if (!renderer())
+ return SVGRect();
+
+ return renderer()->strokeBoundingBox();
}
RenderObject* SVGGraphicsElement::createRenderer(RenderStyle*)
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGGraphicsElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGGraphicsElement.h
index d02a8db70d0..6bc8830c32f 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGGraphicsElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGGraphicsElement.h
@@ -24,27 +24,30 @@
#include "core/svg/SVGAnimatedTransformList.h"
#include "core/svg/SVGElement.h"
#include "core/svg/SVGTests.h"
-#include "core/svg/SVGTransformable.h"
namespace WebCore {
class AffineTransform;
class Path;
-class SVGGraphicsElement : public SVGElement, public SVGTransformable, public SVGTests {
+class SVGGraphicsElement : public SVGElement, public SVGTests {
public:
virtual ~SVGGraphicsElement();
- virtual AffineTransform getCTM(StyleUpdateStrategy = AllowStyleUpdate);
- virtual AffineTransform getScreenCTM(StyleUpdateStrategy = AllowStyleUpdate);
- virtual SVGElement* nearestViewportElement() const;
- virtual SVGElement* farthestViewportElement() const;
+ enum StyleUpdateStrategy { AllowStyleUpdate, DisallowStyleUpdate };
- virtual AffineTransform localCoordinateSpaceTransform(SVGLocatable::CTMScope mode) const { return SVGTransformable::localCoordinateSpaceTransform(mode); }
+ AffineTransform getCTM(StyleUpdateStrategy = AllowStyleUpdate);
+ AffineTransform getScreenCTM(StyleUpdateStrategy = AllowStyleUpdate);
+ AffineTransform getTransformToElement(SVGElement*, ExceptionState&);
+ SVGElement* nearestViewportElement() const;
+ SVGElement* farthestViewportElement() const;
+
+ virtual AffineTransform localCoordinateSpaceTransform(SVGElement::CTMScope) const OVERRIDE { return animatedLocalTransform(); }
virtual AffineTransform animatedLocalTransform() const;
virtual AffineTransform* supplementalTransform();
- virtual SVGRect getBBox(StyleUpdateStrategy = AllowStyleUpdate);
+ virtual SVGRect getBBox();
+ SVGRect getStrokeBBox();
// "base class" methods for all the elements which render as paths
virtual void toClipPath(Path&);
@@ -73,13 +76,13 @@ private:
OwnPtr<AffineTransform> m_supplementalTransform;
};
-inline SVGGraphicsElement* toSVGGraphicsElement(Node* node)
+inline bool isSVGGraphicsElement(const Node& node)
{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->isSVGElement());
- ASSERT_WITH_SECURITY_IMPLICATION(!node || toSVGElement(node)->isSVGGraphicsElement());
- return static_cast<SVGGraphicsElement*>(node);
+ return node.isSVGElement() && toSVGElement(node).isSVGGraphicsElement();
}
+DEFINE_NODE_TYPE_CASTS_WITH_FUNCTION(SVGGraphicsElement);
+
} // namespace WebCore
#endif // SVGGraphicsElement_h
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGGraphicsElement.idl b/chromium/third_party/WebKit/Source/core/svg/SVGGraphicsElement.idl
index 0af24404822..eed23aa1d2f 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGGraphicsElement.idl
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGGraphicsElement.idl
@@ -31,10 +31,11 @@
interface SVGGraphicsElement : SVGElement {
readonly attribute SVGAnimatedTransformList transform;
- readonly attribute SVGElement nearestViewportElement;
- readonly attribute SVGElement farthestViewportElement;
+ [MeasureAs=SVGLocatableNearestViewportElement] readonly attribute SVGElement nearestViewportElement;
+ [MeasureAs=SVGLocatableFarthestViewportElement] readonly attribute SVGElement farthestViewportElement;
SVGRect getBBox();
+ SVGRect getStrokeBBox();
SVGMatrix getCTM();
SVGMatrix getScreenCTM();
[RaisesException] SVGMatrix getTransformToElement([Default=Undefined] optional SVGElement element);
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGHKernElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGHKernElement.cpp
index d9277274f6e..cfd9229fdb8 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGHKernElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGHKernElement.cpp
@@ -24,21 +24,18 @@
#if ENABLE(SVG_FONTS)
#include "core/svg/SVGHKernElement.h"
-#include "SVGNames.h"
-#include "core/svg/SVGFontElement.h"
namespace WebCore {
-inline SVGHKernElement::SVGHKernElement(const QualifiedName& tagName, Document& document)
- : SVGElement(tagName, document)
+inline SVGHKernElement::SVGHKernElement(Document& document)
+ : SVGElement(SVGNames::hkernTag, document)
{
- ASSERT(hasTagName(SVGNames::hkernTag));
ScriptWrappable::init(this);
}
-PassRefPtr<SVGHKernElement> SVGHKernElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGHKernElement> SVGHKernElement::create(Document& document)
{
- return adoptRef(new SVGHKernElement(tagName, document));
+ return adoptRef(new SVGHKernElement(document));
}
Node::InsertionNotificationRequest SVGHKernElement::insertedInto(ContainerNode* rootParent)
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGHKernElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGHKernElement.h
index c60d6249b4f..d54d89d701a 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGHKernElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGHKernElement.h
@@ -30,12 +30,12 @@ namespace WebCore {
class SVGHKernElement FINAL : public SVGElement {
public:
- static PassRefPtr<SVGHKernElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGHKernElement> create(Document&);
void buildHorizontalKerningPair(KerningPairVector&);
private:
- SVGHKernElement(const QualifiedName&, Document&);
+ explicit SVGHKernElement(Document&);
virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
virtual void removedFrom(ContainerNode*) OVERRIDE;
@@ -43,11 +43,7 @@ private:
virtual bool rendererIsNeeded(const RenderStyle&) { return false; }
};
-inline SVGHKernElement* toSVGHKernElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(SVGNames::hkernTag));
- return static_cast<SVGHKernElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(SVGHKernElement, hasTagName(SVGNames::hkernTag));
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGImageElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGImageElement.cpp
index d2ce3c0db59..72e3008be73 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGImageElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGImageElement.cpp
@@ -24,7 +24,6 @@
#include "core/svg/SVGImageElement.h"
#include "CSSPropertyNames.h"
-#include "SVGNames.h"
#include "XLinkNames.h"
#include "core/rendering/RenderImageResource.h"
#include "core/rendering/svg/RenderSVGImage.h"
@@ -53,22 +52,21 @@ BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGImageElement)
REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
END_REGISTER_ANIMATED_PROPERTIES
-inline SVGImageElement::SVGImageElement(const QualifiedName& tagName, Document& document)
- : SVGGraphicsElement(tagName, document)
+inline SVGImageElement::SVGImageElement(Document& document)
+ : SVGGraphicsElement(SVGNames::imageTag, document)
, m_x(LengthModeWidth)
, m_y(LengthModeHeight)
, m_width(LengthModeWidth)
, m_height(LengthModeHeight)
, m_imageLoader(this)
{
- ASSERT(hasTagName(SVGNames::imageTag));
ScriptWrappable::init(this);
registerAnimatedPropertiesForSVGImageElement();
}
-PassRefPtr<SVGImageElement> SVGImageElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGImageElement> SVGImageElement::create(Document& document)
{
- return adoptRef(new SVGImageElement(tagName, document));
+ return adoptRef(new SVGImageElement(document));
}
bool SVGImageElement::currentFrameHasSingleSecurityOrigin() const
@@ -87,7 +85,6 @@ bool SVGImageElement::isSupportedAttribute(const QualifiedName& attrName)
{
DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
if (supportedAttributes.isEmpty()) {
- SVGLangSpace::addSupportedAttributes(supportedAttributes);
SVGExternalResourcesRequired::addSupportedAttributes(supportedAttributes);
SVGURIReference::addSupportedAttributes(supportedAttributes);
supportedAttributes.add(SVGNames::xAttr);
@@ -134,8 +131,7 @@ void SVGImageElement::parseAttribute(const QualifiedName& name, const AtomicStri
setWidthBaseValue(SVGLength::construct(LengthModeWidth, value, parseError, ForbidNegativeLengths));
else if (name == SVGNames::heightAttr)
setHeightBaseValue(SVGLength::construct(LengthModeHeight, value, parseError, ForbidNegativeLengths));
- else if (SVGLangSpace::parseAttribute(name, value)
- || SVGExternalResourcesRequired::parseAttribute(name, value)
+ else if (SVGExternalResourcesRequired::parseAttribute(name, value)
|| SVGURIReference::parseAttribute(name, value)) {
} else
ASSERT_NOT_REACHED();
@@ -176,7 +172,6 @@ void SVGImageElement::svgAttributeChanged(const QualifiedName& attrName)
}
if (attrName == SVGNames::preserveAspectRatioAttr
- || SVGLangSpace::isKnownAttribute(attrName)
|| SVGExternalResourcesRequired::isKnownAttribute(attrName)) {
RenderSVGResource::markForLayoutAndParentResourceInvalidation(renderer);
return;
@@ -238,7 +233,7 @@ void SVGImageElement::addSubresourceAttributeURLs(ListHashSet<KURL>& urls) const
addSubresourceURL(urls, document().completeURL(hrefCurrentValue()));
}
-void SVGImageElement::didMoveToNewDocument(Document* oldDocument)
+void SVGImageElement::didMoveToNewDocument(Document& oldDocument)
{
m_imageLoader.elementDidMoveToNewDocument();
SVGGraphicsElement::didMoveToNewDocument(oldDocument);
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGImageElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGImageElement.h
index fc4e1573635..1270dc14204 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGImageElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGImageElement.h
@@ -36,12 +36,12 @@ class SVGImageElement FINAL : public SVGGraphicsElement,
public SVGExternalResourcesRequired,
public SVGURIReference {
public:
- static PassRefPtr<SVGImageElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGImageElement> create(Document&);
bool currentFrameHasSingleSecurityOrigin() const;
private:
- SVGImageElement(const QualifiedName&, Document&);
+ explicit SVGImageElement(Document&);
virtual bool isValid() const { return SVGTests::isValid(); }
virtual bool supportsFocus() const OVERRIDE { return hasFocusEventListeners(); }
@@ -63,7 +63,7 @@ private:
virtual bool haveLoadedRequiredResources();
virtual bool selfHasRelativeLengths() const;
- virtual void didMoveToNewDocument(Document* oldDocument) OVERRIDE;
+ virtual void didMoveToNewDocument(Document& oldDocument) OVERRIDE;
BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGImageElement)
DECLARE_ANIMATED_LENGTH(X, x)
@@ -78,11 +78,7 @@ private:
SVGImageLoader m_imageLoader;
};
-inline SVGImageElement* toSVGImageElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(SVGNames::imageTag));
- return static_cast<SVGImageElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(SVGImageElement, hasTagName(SVGNames::imageTag));
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGImageLoader.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGImageLoader.cpp
index 6b503e2f05e..e889c61b149 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGImageLoader.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGImageLoader.cpp
@@ -22,8 +22,8 @@
#include "core/svg/SVGImageLoader.h"
-#include "core/dom/Event.h"
-#include "core/dom/EventNames.h"
+#include "core/events/Event.h"
+#include "core/events/ThreadLocalEventNames.h"
#include "core/fetch/ImageResource.h"
#include "core/html/parser/HTMLParserIdioms.h"
#include "core/svg/SVGImageElement.h"
@@ -38,7 +38,7 @@ SVGImageLoader::SVGImageLoader(SVGImageElement* node)
void SVGImageLoader::dispatchLoadEvent()
{
if (image()->errorOccurred())
- element()->dispatchEvent(Event::create(eventNames().errorEvent));
+ element()->dispatchEvent(Event::create(EventTypeNames::error));
else {
SVGImageElement* imageElement = toSVGImageElement(element());
if (imageElement->externalResourcesRequiredBaseValue())
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGLangSpace.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGLangSpace.cpp
deleted file mode 100644
index c6bfe936ee5..00000000000
--- a/chromium/third_party/WebKit/Source/core/svg/SVGLangSpace.cpp
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * Copyright (C) 2004, 2005, 2007, 2008 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2004, 2005, 2006 Rob Buis <buis@kde.org>
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-#include "core/svg/SVGLangSpace.h"
-
-#include "XMLNames.h"
-#include "wtf/StdLibExtras.h"
-
-namespace WebCore {
-
-void SVGLangSpace::setXmllang(const AtomicString& xmlLang)
-{
- m_lang = xmlLang;
-}
-
-const AtomicString& SVGLangSpace::xmlspace() const
-{
- if (!m_space) {
- DEFINE_STATIC_LOCAL(const AtomicString, defaultString, ("default", AtomicString::ConstructFromLiteral));
- return defaultString;
- }
-
- return m_space;
-}
-
-void SVGLangSpace::setXmlspace(const AtomicString& xmlSpace)
-{
- m_space = xmlSpace;
-}
-
-bool SVGLangSpace::parseAttribute(const QualifiedName& name, const AtomicString& value)
-{
- if (name.matches(XMLNames::langAttr)) {
- setXmllang(value);
- return true;
- }
- if (name.matches(XMLNames::spaceAttr)) {
- setXmlspace(value);
- return true;
- }
-
- return false;
-}
-
-bool SVGLangSpace::isKnownAttribute(const QualifiedName& attrName)
-{
- return attrName.matches(XMLNames::langAttr) || attrName.matches(XMLNames::spaceAttr);
-}
-
-void SVGLangSpace::addSupportedAttributes(HashSet<QualifiedName>& supportedAttributes)
-{
- DEFINE_STATIC_LOCAL(AtomicString, xmlPrefix, ("xml", AtomicString::ConstructFromLiteral));
-
- QualifiedName langWithPrefix = XMLNames::langAttr;
- langWithPrefix.setPrefix(xmlPrefix);
- supportedAttributes.add(langWithPrefix);
- supportedAttributes.add(XMLNames::langAttr);
-
- QualifiedName spaceWithPrefix = XMLNames::spaceAttr;
- spaceWithPrefix.setPrefix(xmlPrefix);
- supportedAttributes.add(spaceWithPrefix);
- supportedAttributes.add(XMLNames::spaceAttr);
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGLangSpace.h b/chromium/third_party/WebKit/Source/core/svg/SVGLangSpace.h
deleted file mode 100644
index b10c97d90a1..00000000000
--- a/chromium/third_party/WebKit/Source/core/svg/SVGLangSpace.h
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright (C) 2004, 2005, 2007, 2008 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2004, 2005, 2006 Rob Buis <buis@kde.org>
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#ifndef SVGLangSpace_h
-#define SVGLangSpace_h
-
-#include "core/dom/QualifiedName.h"
-#include "wtf/HashSet.h"
-
-namespace WebCore {
-
-class Attribute;
-
-class SVGLangSpace {
-public:
- const AtomicString& xmllang() const { return m_lang; }
- void setXmllang(const AtomicString& xmlLang);
-
- const AtomicString& xmlspace() const;
- void setXmlspace(const AtomicString& xmlSpace);
-
- bool parseAttribute(const QualifiedName&, const AtomicString&);
- bool isKnownAttribute(const QualifiedName&);
- void addSupportedAttributes(HashSet<QualifiedName>&);
-
-private:
- AtomicString m_lang;
- AtomicString m_space;
-};
-
-} // namespace WebCore
-
-#endif // SVGLangSpace_h
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGLength.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGLength.cpp
index 4f78c902643..b6a95967fea 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGLength.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGLength.cpp
@@ -24,7 +24,6 @@
#include "core/svg/SVGLength.h"
#include "SVGNames.h"
-#include "bindings/v8/ExceptionState.h"
#include "bindings/v8/ExceptionStatePlaceholder.h"
#include "core/css/CSSPrimitiveValue.h"
#include "core/dom/ExceptionCode.h"
@@ -150,11 +149,11 @@ SVGLength::SVGLength(const SVGLength& other)
{
}
-void SVGLength::setValueAsString(const String& valueAsString, SVGLengthMode mode, ExceptionState& es)
+void SVGLength::setValueAsString(const String& valueAsString, SVGLengthMode mode, ExceptionState& exceptionState)
{
m_valueInSpecifiedUnits = 0;
m_unit = storeUnit(mode, LengthTypeNumber);
- setValueAsString(valueAsString, es);
+ setValueAsString(valueAsString, exceptionState);
}
bool SVGLength::operator==(const SVGLength& other) const
@@ -170,12 +169,12 @@ bool SVGLength::operator!=(const SVGLength& other) const
SVGLength SVGLength::construct(SVGLengthMode mode, const String& valueAsString, SVGParsingError& parseError, SVGLengthNegativeValuesMode negativeValuesMode)
{
- TrackExceptionState es;
+ TrackExceptionState exceptionState;
SVGLength length(mode);
- length.setValueAsString(valueAsString, es);
+ length.setValueAsString(valueAsString, exceptionState);
- if (es.hadException())
+ if (exceptionState.hadException())
parseError = ParsingAttributeFailedError;
else if (negativeValuesMode == ForbidNegativeLengths && length.valueInSpecifiedUnits() < 0)
parseError = NegativeValueForbiddenError;
@@ -198,25 +197,25 @@ float SVGLength::value(const SVGLengthContext& context) const
return value(context, IGNORE_EXCEPTION);
}
-float SVGLength::value(const SVGLengthContext& context, ExceptionState& es) const
+float SVGLength::value(const SVGLengthContext& context, ExceptionState& exceptionState) const
{
- return context.convertValueToUserUnits(m_valueInSpecifiedUnits, extractMode(m_unit), extractType(m_unit), es);
+ return context.convertValueToUserUnits(m_valueInSpecifiedUnits, extractMode(m_unit), extractType(m_unit), exceptionState);
}
-void SVGLength::setValue(const SVGLengthContext& context, float value, SVGLengthMode mode, SVGLengthType unitType, ExceptionState& es)
+void SVGLength::setValue(const SVGLengthContext& context, float value, SVGLengthMode mode, SVGLengthType unitType, ExceptionState& exceptionState)
{
m_unit = storeUnit(mode, unitType);
- setValue(value, context, es);
+ setValue(value, context, exceptionState);
}
-void SVGLength::setValue(float value, const SVGLengthContext& context, ExceptionState& es)
+void SVGLength::setValue(float value, const SVGLengthContext& context, ExceptionState& exceptionState)
{
// 100% = 100.0 instead of 1.0 for historical reasons, this could eventually be changed
if (extractType(m_unit) == LengthTypePercentage)
value = value / 100;
- float convertedValue = context.convertValueFromUserUnits(value, extractMode(m_unit), extractType(m_unit), es);
- if (!es.hadException())
+ float convertedValue = context.convertValueFromUserUnits(value, extractMode(m_unit), extractType(m_unit), exceptionState);
+ if (!exceptionState.hadException())
m_valueInSpecifiedUnits = convertedValue;
}
float SVGLength::valueAsPercentage() const
@@ -245,7 +244,7 @@ static bool parseValueInternal(const String& string, float& convertedNumber, SVG
return true;
}
-void SVGLength::setValueAsString(const String& string, ExceptionState& es)
+void SVGLength::setValueAsString(const String& string, ExceptionState& exceptionState)
{
if (string.isEmpty())
return;
@@ -258,7 +257,7 @@ void SVGLength::setValueAsString(const String& string, ExceptionState& es)
parseValueInternal<UChar>(string, convertedNumber, type);
if (!success) {
- es.throwDOMException(SyntaxError);
+ exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
return;
}
@@ -271,10 +270,10 @@ String SVGLength::valueAsString() const
return String::number(m_valueInSpecifiedUnits) + lengthTypeToString(extractType(m_unit));
}
-void SVGLength::newValueSpecifiedUnits(unsigned short type, float value, ExceptionState& es)
+void SVGLength::newValueSpecifiedUnits(unsigned short type, float value, ExceptionState& exceptionState)
{
if (type == LengthTypeUnknown || type > LengthTypePC) {
- es.throwDOMException(NotSupportedError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
return;
}
@@ -282,21 +281,21 @@ void SVGLength::newValueSpecifiedUnits(unsigned short type, float value, Excepti
m_valueInSpecifiedUnits = value;
}
-void SVGLength::convertToSpecifiedUnits(unsigned short type, const SVGLengthContext& context, ExceptionState& es)
+void SVGLength::convertToSpecifiedUnits(unsigned short type, const SVGLengthContext& context, ExceptionState& exceptionState)
{
if (type == LengthTypeUnknown || type > LengthTypePC) {
- es.throwDOMException(NotSupportedError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
return;
}
- float valueInUserUnits = value(context, es);
- if (es.hadException())
+ float valueInUserUnits = value(context, exceptionState);
+ if (exceptionState.hadException())
return;
unsigned int originalUnitAndType = m_unit;
m_unit = storeUnit(extractMode(m_unit), toSVGLengthType(type));
- setValue(valueInUserUnits, context, es);
- if (!es.hadException())
+ setValue(valueInUserUnits, context, exceptionState);
+ if (!exceptionState.hadException())
return;
// Eventually restore old unit and type
@@ -348,10 +347,10 @@ SVGLength SVGLength::fromCSSPrimitiveValue(CSSPrimitiveValue* value)
if (svgType == LengthTypeUnknown)
return SVGLength();
- TrackExceptionState es;
+ TrackExceptionState exceptionState;
SVGLength length;
- length.newValueSpecifiedUnits(svgType, value->getFloatValue(), es);
- if (es.hadException())
+ length.newValueSpecifiedUnits(svgType, value->getFloatValue(), exceptionState);
+ if (exceptionState.hadException())
return SVGLength();
return length;
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGLength.h b/chromium/third_party/WebKit/Source/core/svg/SVGLength.h
index 1bc530ed197..31310509b1b 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGLength.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGLength.h
@@ -22,10 +22,10 @@
#define SVGLength_h
#include "bindings/v8/ExceptionState.h"
-#include "core/platform/animation/AnimationUtilities.h"
#include "core/svg/SVGLengthContext.h"
#include "core/svg/SVGParsingError.h"
#include "core/svg/properties/SVGPropertyTraits.h"
+#include "platform/animation/AnimationUtilities.h"
namespace WebCore {
@@ -114,13 +114,13 @@ public:
return *this;
SVGLength length;
- TrackExceptionState es;
+ TrackExceptionState exceptionState;
if (fromType == LengthTypePercentage || toType == LengthTypePercentage) {
float fromPercent = from.valueAsPercentage() * 100;
float toPercent = valueAsPercentage() * 100;
- length.newValueSpecifiedUnits(LengthTypePercentage, WebCore::blend(fromPercent, toPercent, progress), es);
- if (es.hadException())
+ length.newValueSpecifiedUnits(LengthTypePercentage, WebCore::blend(fromPercent, toPercent, progress), exceptionState);
+ if (exceptionState.hadException())
return SVGLength();
return length;
}
@@ -129,10 +129,10 @@ public:
float fromValue = from.valueInSpecifiedUnits();
float toValue = valueInSpecifiedUnits();
if (isZero())
- length.newValueSpecifiedUnits(fromType, WebCore::blend(fromValue, toValue, progress), es);
+ length.newValueSpecifiedUnits(fromType, WebCore::blend(fromValue, toValue, progress), exceptionState);
else
- length.newValueSpecifiedUnits(toType, WebCore::blend(fromValue, toValue, progress), es);
- if (es.hadException())
+ length.newValueSpecifiedUnits(toType, WebCore::blend(fromValue, toValue, progress), exceptionState);
+ if (exceptionState.hadException())
return SVGLength();
return length;
}
@@ -141,18 +141,18 @@ public:
ASSERT(!from.isRelative());
SVGLengthContext nonRelativeLengthContext(0);
- float fromValueInUserUnits = nonRelativeLengthContext.convertValueToUserUnits(from.valueInSpecifiedUnits(), from.unitMode(), fromType, es);
- if (es.hadException())
+ float fromValueInUserUnits = nonRelativeLengthContext.convertValueToUserUnits(from.valueInSpecifiedUnits(), from.unitMode(), fromType, exceptionState);
+ if (exceptionState.hadException())
return SVGLength();
- float fromValue = nonRelativeLengthContext.convertValueFromUserUnits(fromValueInUserUnits, unitMode(), toType, es);
- if (es.hadException())
+ float fromValue = nonRelativeLengthContext.convertValueFromUserUnits(fromValueInUserUnits, unitMode(), toType, exceptionState);
+ if (exceptionState.hadException())
return SVGLength();
float toValue = valueInSpecifiedUnits();
- length.newValueSpecifiedUnits(toType, WebCore::blend(fromValue, toValue, progress), es);
+ length.newValueSpecifiedUnits(toType, WebCore::blend(fromValue, toValue, progress), exceptionState);
- if (es.hadException())
+ if (exceptionState.hadException())
return SVGLength();
return length;
}
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGLength.idl b/chromium/third_party/WebKit/Source/core/svg/SVGLength.idl
index e073b1a36aa..4d29af7ffa4 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGLength.idl
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGLength.idl
@@ -35,10 +35,10 @@ interface SVGLength {
const unsigned short SVG_LENGTHTYPE_PC = 10;
readonly attribute unsigned short unitType;
- [Custom, StrictTypeChecking, GetterRaisesException, SetterRaisesException] attribute float value;
+ [Custom, StrictTypeChecking, RaisesException] attribute float value;
[StrictTypeChecking] attribute float valueInSpecifiedUnits;
- [TreatNullAs=NullString, StrictTypeChecking, SetterRaisesException] attribute DOMString valueAsString;
+ [TreatNullAs=NullString, StrictTypeChecking, RaisesException=Setter] attribute DOMString valueAsString;
[StrictTypeChecking, RaisesException] void newValueSpecifiedUnits(unsigned short unitType,
float valueInSpecifiedUnits);
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGLengthContext.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGLengthContext.cpp
index 1c8ed6a4bc1..7fed6c20b7a 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGLengthContext.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGLengthContext.cpp
@@ -27,12 +27,12 @@
#include "bindings/v8/ExceptionState.h"
#include "core/css/CSSHelper.h"
#include "core/dom/ExceptionCode.h"
-#include "core/platform/graphics/FontMetrics.h"
#include "core/rendering/RenderPart.h"
#include "core/rendering/RenderView.h"
#include "core/rendering/svg/RenderSVGRoot.h"
#include "core/rendering/svg/RenderSVGViewportContainer.h"
#include "core/svg/SVGSVGElement.h"
+#include "platform/fonts/FontMetrics.h"
namespace WebCore {
@@ -86,116 +86,114 @@ float SVGLengthContext::resolveLength(const SVGElement* context, SVGUnitTypes::S
return x.valueAsPercentage();
}
-float SVGLengthContext::convertValueToUserUnits(float value, SVGLengthMode mode, SVGLengthType fromUnit, ExceptionState& es) const
+float SVGLengthContext::convertValueToUserUnits(float value, SVGLengthMode mode, SVGLengthType fromUnit, ExceptionState& exceptionState) const
{
// If the SVGLengthContext carries a custom viewport, force resolving against it.
if (!m_overridenViewport.isEmpty()) {
// 100% = 100.0 instead of 1.0 for historical reasons, this could eventually be changed
if (fromUnit == LengthTypePercentage)
value /= 100;
- return convertValueFromPercentageToUserUnits(value, mode, es);
+ return convertValueFromPercentageToUserUnits(value, mode, exceptionState);
}
switch (fromUnit) {
case LengthTypeUnknown:
- es.throwDOMException(NotSupportedError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
return 0;
case LengthTypeNumber:
return value;
case LengthTypePX:
return value;
case LengthTypePercentage:
- return convertValueFromPercentageToUserUnits(value / 100, mode, es);
+ return convertValueFromPercentageToUserUnits(value / 100, mode, exceptionState);
case LengthTypeEMS:
- return convertValueFromEMSToUserUnits(value, es);
+ return convertValueFromEMSToUserUnits(value, exceptionState);
case LengthTypeEXS:
- return convertValueFromEXSToUserUnits(value, es);
+ return convertValueFromEXSToUserUnits(value, exceptionState);
case LengthTypeCM:
- return value * cssPixelsPerInch / 2.54f;
+ return value * cssPixelsPerCentimeter;
case LengthTypeMM:
- return value * cssPixelsPerInch / 25.4f;
+ return value * cssPixelsPerMillimeter;
case LengthTypeIN:
return value * cssPixelsPerInch;
case LengthTypePT:
- return value * cssPixelsPerInch / 72;
+ return value * cssPixelsPerPoint;
case LengthTypePC:
- return value * cssPixelsPerInch / 6;
+ return value * cssPixelsPerPica;
}
ASSERT_NOT_REACHED();
return 0;
}
-float SVGLengthContext::convertValueFromUserUnits(float value, SVGLengthMode mode, SVGLengthType toUnit, ExceptionState& es) const
+float SVGLengthContext::convertValueFromUserUnits(float value, SVGLengthMode mode, SVGLengthType toUnit, ExceptionState& exceptionState) const
{
switch (toUnit) {
case LengthTypeUnknown:
- es.throwDOMException(NotSupportedError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
return 0;
case LengthTypeNumber:
return value;
case LengthTypePercentage:
- return convertValueFromUserUnitsToPercentage(value * 100, mode, es);
+ return convertValueFromUserUnitsToPercentage(value * 100, mode, exceptionState);
case LengthTypeEMS:
- return convertValueFromUserUnitsToEMS(value, es);
+ return convertValueFromUserUnitsToEMS(value, exceptionState);
case LengthTypeEXS:
- return convertValueFromUserUnitsToEXS(value, es);
+ return convertValueFromUserUnitsToEXS(value, exceptionState);
case LengthTypePX:
return value;
case LengthTypeCM:
- return value * 2.54f / cssPixelsPerInch;
+ return value / cssPixelsPerCentimeter;
case LengthTypeMM:
- return value * 25.4f / cssPixelsPerInch;
+ return value / cssPixelsPerMillimeter;
case LengthTypeIN:
return value / cssPixelsPerInch;
case LengthTypePT:
- return value * 72 / cssPixelsPerInch;
+ return value / cssPixelsPerPoint;
case LengthTypePC:
- return value * 6 / cssPixelsPerInch;
+ return value / cssPixelsPerPica;
}
ASSERT_NOT_REACHED();
return 0;
}
-float SVGLengthContext::convertValueFromUserUnitsToPercentage(float value, SVGLengthMode mode, ExceptionState& es) const
+float SVGLengthContext::convertValueFromUserUnitsToPercentage(float value, SVGLengthMode mode, ExceptionState& exceptionState) const
{
- float width = 0;
- float height = 0;
- if (!determineViewport(width, height)) {
- es.throwDOMException(NotSupportedError);
+ FloatSize viewportSize;
+ if (!determineViewport(viewportSize)) {
+ exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
return 0;
}
switch (mode) {
case LengthModeWidth:
- return value / width * 100;
+ return value / viewportSize.width() * 100;
case LengthModeHeight:
- return value / height * 100;
+ return value / viewportSize.height() * 100;
case LengthModeOther:
- return value / (sqrtf((width * width + height * height) / 2)) * 100;
+ return value / sqrtf(viewportSize.diagonalLengthSquared() / 2) * 100;
};
ASSERT_NOT_REACHED();
return 0;
}
-float SVGLengthContext::convertValueFromPercentageToUserUnits(float value, SVGLengthMode mode, ExceptionState& es) const
+float SVGLengthContext::convertValueFromPercentageToUserUnits(float value, SVGLengthMode mode, ExceptionState& exceptionState) const
{
- float width = 0;
- float height = 0;
- if (!determineViewport(width, height)) {
- es.throwDOMException(NotSupportedError);
+ FloatSize viewportSize;
+ if (!determineViewport(viewportSize)) {
+ exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
return 0;
}
switch (mode) {
case LengthModeWidth:
- return value * width;
+ return value * viewportSize.width();
case LengthModeHeight:
- return value * height;
+ return value * viewportSize.height();
case LengthModeOther:
- return value * sqrtf((width * width + height * height) / 2);
+ return value * sqrtf(viewportSize.diagonalLengthSquared() / 2);
};
ASSERT_NOT_REACHED();
@@ -219,39 +217,39 @@ static inline RenderStyle* renderStyleForLengthResolving(const SVGElement* conte
return 0;
}
-float SVGLengthContext::convertValueFromUserUnitsToEMS(float value, ExceptionState& es) const
+float SVGLengthContext::convertValueFromUserUnitsToEMS(float value, ExceptionState& exceptionState) const
{
RenderStyle* style = renderStyleForLengthResolving(m_context);
if (!style) {
- es.throwDOMException(NotSupportedError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
return 0;
}
float fontSize = style->specifiedFontSize();
if (!fontSize) {
- es.throwDOMException(NotSupportedError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
return 0;
}
return value / fontSize;
}
-float SVGLengthContext::convertValueFromEMSToUserUnits(float value, ExceptionState& es) const
+float SVGLengthContext::convertValueFromEMSToUserUnits(float value, ExceptionState& exceptionState) const
{
RenderStyle* style = renderStyleForLengthResolving(m_context);
if (!style) {
- es.throwDOMException(NotSupportedError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
return 0;
}
return value * style->specifiedFontSize();
}
-float SVGLengthContext::convertValueFromUserUnitsToEXS(float value, ExceptionState& es) const
+float SVGLengthContext::convertValueFromUserUnitsToEXS(float value, ExceptionState& exceptionState) const
{
RenderStyle* style = renderStyleForLengthResolving(m_context);
if (!style) {
- es.throwDOMException(NotSupportedError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
return 0;
}
@@ -259,18 +257,18 @@ float SVGLengthContext::convertValueFromUserUnitsToEXS(float value, ExceptionSta
// if this causes problems in real world cases maybe it would be best to remove this
float xHeight = ceilf(style->fontMetrics().xHeight());
if (!xHeight) {
- es.throwDOMException(NotSupportedError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
return 0;
}
return value / xHeight;
}
-float SVGLengthContext::convertValueFromEXSToUserUnits(float value, ExceptionState& es) const
+float SVGLengthContext::convertValueFromEXSToUserUnits(float value, ExceptionState& exceptionState) const
{
RenderStyle* style = renderStyleForLengthResolving(m_context);
if (!style) {
- es.throwDOMException(NotSupportedError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
return 0;
}
@@ -279,34 +277,33 @@ float SVGLengthContext::convertValueFromEXSToUserUnits(float value, ExceptionSta
return value * ceilf(style->fontMetrics().xHeight());
}
-bool SVGLengthContext::determineViewport(float& width, float& height) const
+bool SVGLengthContext::determineViewport(FloatSize& viewportSize) const
{
if (!m_context)
return false;
// If an overriden viewport is given, it has precedence.
if (!m_overridenViewport.isEmpty()) {
- width = m_overridenViewport.width();
- height = m_overridenViewport.height();
+ viewportSize = m_overridenViewport.size();
return true;
}
- // SVGLengthContext should NEVER be used to resolve width/height values for <svg> elements,
- // as they require special treatment, due the relationship with the CSS width/height properties.
- ASSERT(m_context->document().documentElement() != m_context);
+ // Root <svg> element lengths are resolved against the top level viewport.
+ if (m_context->isOutermostSVGSVGElement()) {
+ viewportSize = toSVGSVGElement(m_context)->currentViewportSize();
+ return true;
+ }
// Take size from nearest viewport element.
SVGElement* viewportElement = m_context->viewportElement();
if (!viewportElement || !viewportElement->isSVGSVGElement())
return false;
- const SVGSVGElement* svg = static_cast<const SVGSVGElement*>(viewportElement);
- FloatSize viewportSize = svg->currentViewBoxRect().size();
+ const SVGSVGElement* svg = toSVGSVGElement(viewportElement);
+ viewportSize = svg->currentViewBoxRect().size();
if (viewportSize.isEmpty())
viewportSize = svg->currentViewportSize();
- width = viewportSize.width();
- height = viewportSize.height();
return true;
}
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGLengthContext.h b/chromium/third_party/WebKit/Source/core/svg/SVGLengthContext.h
index c2fea4ea1aa..64c237040c1 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGLengthContext.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGLengthContext.h
@@ -20,8 +20,8 @@
#ifndef SVGLengthContext_h
#define SVGLengthContext_h
-#include "core/platform/graphics/FloatRect.h"
#include "core/svg/SVGUnitTypes.h"
+#include "platform/geometry/FloatRect.h"
namespace WebCore {
@@ -66,7 +66,7 @@ public:
float convertValueToUserUnits(float, SVGLengthMode, SVGLengthType fromUnit, ExceptionState&) const;
float convertValueFromUserUnits(float, SVGLengthMode, SVGLengthType toUnit, ExceptionState&) const;
- bool determineViewport(float& width, float& height) const;
+ bool determineViewport(FloatSize&) const;
private:
SVGLengthContext(const SVGElement*, const FloatRect& viewport);
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGLengthList.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGLengthList.cpp
index 02c1a0772e0..1518d2c924a 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGLengthList.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGLengthList.cpp
@@ -30,7 +30,7 @@ namespace WebCore {
template<typename CharType>
void SVGLengthList::parseInternal(const CharType*& ptr, const CharType* end, SVGLengthMode mode)
{
- TrackExceptionState es;
+ TrackExceptionState exceptionState;
while (ptr < end) {
const CharType* start = ptr;
@@ -43,8 +43,8 @@ void SVGLengthList::parseInternal(const CharType*& ptr, const CharType* end, SVG
String valueString(start, ptr - start);
if (valueString.isEmpty())
return;
- length.setValueAsString(valueString, es);
- if (es.hadException())
+ length.setValueAsString(valueString, exceptionState);
+ if (exceptionState.hadException())
return;
append(length);
skipOptionalSVGSpacesOrDelimiter(ptr, end);
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGLineElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGLineElement.cpp
index fe21256f3a9..05ffe1509e1 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGLineElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGLineElement.cpp
@@ -22,7 +22,6 @@
#include "core/svg/SVGLineElement.h"
-#include "SVGNames.h"
#include "core/rendering/svg/RenderSVGResource.h"
#include "core/svg/SVGElementInstance.h"
#include "core/svg/SVGLength.h"
@@ -45,28 +44,26 @@ BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGLineElement)
REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
END_REGISTER_ANIMATED_PROPERTIES
-inline SVGLineElement::SVGLineElement(const QualifiedName& tagName, Document& document)
- : SVGGraphicsElement(tagName, document)
+inline SVGLineElement::SVGLineElement(Document& document)
+ : SVGGeometryElement(SVGNames::lineTag, document)
, m_x1(LengthModeWidth)
, m_y1(LengthModeHeight)
, m_x2(LengthModeWidth)
, m_y2(LengthModeHeight)
{
- ASSERT(hasTagName(SVGNames::lineTag));
ScriptWrappable::init(this);
registerAnimatedPropertiesForSVGLineElement();
}
-PassRefPtr<SVGLineElement> SVGLineElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGLineElement> SVGLineElement::create(Document& document)
{
- return adoptRef(new SVGLineElement(tagName, document));
+ return adoptRef(new SVGLineElement(document));
}
bool SVGLineElement::isSupportedAttribute(const QualifiedName& attrName)
{
DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
if (supportedAttributes.isEmpty()) {
- SVGLangSpace::addSupportedAttributes(supportedAttributes);
SVGExternalResourcesRequired::addSupportedAttributes(supportedAttributes);
supportedAttributes.add(SVGNames::x1Attr);
supportedAttributes.add(SVGNames::x2Attr);
@@ -81,7 +78,7 @@ void SVGLineElement::parseAttribute(const QualifiedName& name, const AtomicStrin
SVGParsingError parseError = NoError;
if (!isSupportedAttribute(name))
- SVGGraphicsElement::parseAttribute(name, value);
+ SVGGeometryElement::parseAttribute(name, value);
else if (name == SVGNames::x1Attr)
setX1BaseValue(SVGLength::construct(LengthModeWidth, value, parseError));
else if (name == SVGNames::y1Attr)
@@ -90,8 +87,7 @@ void SVGLineElement::parseAttribute(const QualifiedName& name, const AtomicStrin
setX2BaseValue(SVGLength::construct(LengthModeWidth, value, parseError));
else if (name == SVGNames::y2Attr)
setY2BaseValue(SVGLength::construct(LengthModeHeight, value, parseError));
- else if (SVGLangSpace::parseAttribute(name, value)
- || SVGExternalResourcesRequired::parseAttribute(name, value)) {
+ else if (SVGExternalResourcesRequired::parseAttribute(name, value)) {
} else
ASSERT_NOT_REACHED();
@@ -101,7 +97,7 @@ void SVGLineElement::parseAttribute(const QualifiedName& name, const AtomicStrin
void SVGLineElement::svgAttributeChanged(const QualifiedName& attrName)
{
if (!isSupportedAttribute(attrName)) {
- SVGGraphicsElement::svgAttributeChanged(attrName);
+ SVGGeometryElement::svgAttributeChanged(attrName);
return;
}
@@ -125,7 +121,7 @@ void SVGLineElement::svgAttributeChanged(const QualifiedName& attrName)
return;
}
- if (SVGLangSpace::isKnownAttribute(attrName) || SVGExternalResourcesRequired::isKnownAttribute(attrName)) {
+ if (SVGExternalResourcesRequired::isKnownAttribute(attrName)) {
RenderSVGResource::markForLayoutAndParentResourceInvalidation(renderer);
return;
}
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGLineElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGLineElement.h
index af514be6b49..68b961afa8d 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGLineElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGLineElement.h
@@ -25,17 +25,17 @@
#include "core/svg/SVGAnimatedBoolean.h"
#include "core/svg/SVGAnimatedLength.h"
#include "core/svg/SVGExternalResourcesRequired.h"
-#include "core/svg/SVGGraphicsElement.h"
+#include "core/svg/SVGGeometryElement.h"
namespace WebCore {
-class SVGLineElement FINAL : public SVGGraphicsElement,
+class SVGLineElement FINAL : public SVGGeometryElement,
public SVGExternalResourcesRequired {
public:
- static PassRefPtr<SVGLineElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGLineElement> create(Document&);
private:
- SVGLineElement(const QualifiedName&, Document&);
+ explicit SVGLineElement(Document&);
virtual bool isValid() const { return SVGTests::isValid(); }
virtual bool supportsFocus() const OVERRIDE { return hasFocusEventListeners(); }
@@ -57,11 +57,7 @@ private:
END_DECLARE_ANIMATED_PROPERTIES
};
-inline SVGLineElement* toSVGLineElement(Element* element)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!element || element->hasTagName(SVGNames::lineTag));
- return static_cast<SVGLineElement*>(element);
-}
+DEFINE_NODE_TYPE_CASTS(SVGLineElement, hasTagName(SVGNames::lineTag));
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGLineElement.idl b/chromium/third_party/WebKit/Source/core/svg/SVGLineElement.idl
index 9df8fe6151a..a12e80b2cf7 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGLineElement.idl
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGLineElement.idl
@@ -23,7 +23,7 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-interface SVGLineElement : SVGGraphicsElement {
+interface SVGLineElement : SVGGeometryElement {
readonly attribute SVGAnimatedLength x1;
readonly attribute SVGAnimatedLength y1;
readonly attribute SVGAnimatedLength x2;
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGLinearGradientElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGLinearGradientElement.cpp
index cd1d6eacd84..84cdebeab31 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGLinearGradientElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGLinearGradientElement.cpp
@@ -25,7 +25,6 @@
#include "core/svg/SVGLinearGradientElement.h"
-#include "SVGNames.h"
#include "core/rendering/svg/RenderSVGResourceLinearGradient.h"
#include "core/svg/LinearGradientAttributes.h"
#include "core/svg/SVGElementInstance.h"
@@ -48,22 +47,21 @@ BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGLinearGradientElement)
REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGradientElement)
END_REGISTER_ANIMATED_PROPERTIES
-inline SVGLinearGradientElement::SVGLinearGradientElement(const QualifiedName& tagName, Document& document)
- : SVGGradientElement(tagName, document)
+inline SVGLinearGradientElement::SVGLinearGradientElement(Document& document)
+ : SVGGradientElement(SVGNames::linearGradientTag, document)
, m_x1(LengthModeWidth)
, m_y1(LengthModeHeight)
, m_x2(LengthModeWidth, "100%")
, m_y2(LengthModeHeight)
{
// Spec: If the x2 attribute is not specified, the effect is as if a value of "100%" were specified.
- ASSERT(hasTagName(SVGNames::linearGradientTag));
ScriptWrappable::init(this);
registerAnimatedPropertiesForSVGLinearGradientElement();
}
-PassRefPtr<SVGLinearGradientElement> SVGLinearGradientElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGLinearGradientElement> SVGLinearGradientElement::create(Document& document)
{
- return adoptRef(new SVGLinearGradientElement(tagName, document));
+ return adoptRef(new SVGLinearGradientElement(document));
}
bool SVGLinearGradientElement::isSupportedAttribute(const QualifiedName& attrName)
@@ -109,8 +107,9 @@ void SVGLinearGradientElement::svgAttributeChanged(const QualifiedName& attrName
updateRelativeLengthsInformation();
- if (RenderObject* object = renderer())
- object->setNeedsLayout();
+ RenderSVGResourceContainer* renderer = toRenderSVGResourceContainer(this->renderer());
+ if (renderer)
+ renderer->invalidateCacheAndMarkForLayout();
}
RenderObject* SVGLinearGradientElement::createRenderer(RenderStyle*)
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGLinearGradientElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGLinearGradientElement.h
index 7f5f5ebe6ab..179424e1ca7 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGLinearGradientElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGLinearGradientElement.h
@@ -31,12 +31,12 @@ struct LinearGradientAttributes;
class SVGLinearGradientElement FINAL : public SVGGradientElement {
public:
- static PassRefPtr<SVGLinearGradientElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGLinearGradientElement> create(Document&);
bool collectGradientAttributes(LinearGradientAttributes&);
private:
- SVGLinearGradientElement(const QualifiedName&, Document&);
+ explicit SVGLinearGradientElement(Document&);
bool isSupportedAttribute(const QualifiedName&);
virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
@@ -54,11 +54,7 @@ private:
END_DECLARE_ANIMATED_PROPERTIES
};
-inline SVGLinearGradientElement* toSVGLinearGradientElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(SVGNames::linearGradientTag));
- return static_cast<SVGLinearGradientElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(SVGLinearGradientElement, hasTagName(SVGNames::linearGradientTag));
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGLocatable.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGLocatable.cpp
deleted file mode 100644
index c3354c9e879..00000000000
--- a/chromium/third_party/WebKit/Source/core/svg/SVGLocatable.cpp
+++ /dev/null
@@ -1,116 +0,0 @@
-/*
- * Copyright (C) 2004, 2005 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2004, 2005, 2006 Rob Buis <buis@kde.org>
- * Copyright (C) 2009 Google, Inc. All rights reserved.
- * Copyright (C) Research In Motion Limited 2010. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-#include "core/svg/SVGLocatable.h"
-
-#include "SVGNames.h"
-#include "bindings/v8/ExceptionState.h"
-#include "core/dom/ExceptionCode.h"
-#include "core/rendering/RenderObject.h"
-#include "core/svg/SVGGraphicsElement.h"
-
-namespace WebCore {
-
-static bool isViewportElement(Node* node)
-{
- return (node->hasTagName(SVGNames::svgTag)
- || node->hasTagName(SVGNames::symbolTag)
- || node->hasTagName(SVGNames::foreignObjectTag)
- || node->hasTagName(SVGNames::imageTag));
-}
-
-SVGElement* SVGLocatable::nearestViewportElement(const SVGElement* element)
-{
- ASSERT(element);
- for (Element* current = element->parentOrShadowHostElement(); current; current = current->parentOrShadowHostElement()) {
- if (isViewportElement(current))
- return toSVGElement(current);
- }
-
- return 0;
-}
-
-SVGElement* SVGLocatable::farthestViewportElement(const SVGElement* element)
-{
- ASSERT(element);
- SVGElement* farthest = 0;
- for (Element* current = element->parentOrShadowHostElement(); current; current = current->parentOrShadowHostElement()) {
- if (isViewportElement(current))
- farthest = toSVGElement(current);
- }
- return farthest;
-}
-
-SVGRect SVGLocatable::getBBox(SVGElement* element, StyleUpdateStrategy styleUpdateStrategy)
-{
- ASSERT(element);
- if (styleUpdateStrategy == AllowStyleUpdate)
- element->document().updateLayoutIgnorePendingStylesheets();
-
- // FIXME: Eventually we should support getBBox for detached elements.
- if (!element->renderer())
- return SVGRect();
-
- return element->renderer()->objectBoundingBox();
-}
-
-AffineTransform SVGLocatable::computeCTM(SVGElement* element, CTMScope mode, StyleUpdateStrategy styleUpdateStrategy)
-{
- ASSERT(element);
- if (styleUpdateStrategy == AllowStyleUpdate)
- element->document().updateLayoutIgnorePendingStylesheets();
-
- AffineTransform ctm;
-
- SVGElement* stopAtElement = mode == NearestViewportScope ? nearestViewportElement(element) : 0;
- for (Element* currentElement = element; currentElement; currentElement = currentElement->parentOrShadowHostElement()) {
- if (!currentElement->isSVGElement())
- break;
-
- ctm = toSVGElement(currentElement)->localCoordinateSpaceTransform(mode).multiply(ctm);
-
- // For getCTM() computation, stop at the nearest viewport element
- if (currentElement == stopAtElement)
- break;
- }
-
- return ctm;
-}
-
-AffineTransform SVGLocatable::getTransformToElement(SVGElement* target, ExceptionState& es, StyleUpdateStrategy styleUpdateStrategy)
-{
- AffineTransform ctm = getCTM(styleUpdateStrategy);
-
- if (target && target->isSVGGraphicsElement()) {
- AffineTransform targetCTM = toSVGGraphicsElement(target)->getCTM(styleUpdateStrategy);
- if (!targetCTM.isInvertible()) {
- es.throwDOMException(InvalidStateError);
- return ctm;
- }
- ctm = targetCTM.inverse() * ctm;
- }
-
- return ctm;
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGLocatable.h b/chromium/third_party/WebKit/Source/core/svg/SVGLocatable.h
deleted file mode 100644
index 6ab6aad4541..00000000000
--- a/chromium/third_party/WebKit/Source/core/svg/SVGLocatable.h
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * Copyright (C) 2004, 2005 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2004, 2005, 2007 Rob Buis <buis@kde.org>
- * Copyright (C) Research In Motion Limited 2010. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#ifndef SVGLocatable_h
-#define SVGLocatable_h
-
-#include "core/platform/graphics/transforms/AffineTransform.h"
-#include "core/svg/SVGRect.h"
-
-namespace WebCore {
-
-class ExceptionState;
-class SVGElement;
-
-class SVGLocatable {
-public:
- virtual ~SVGLocatable() { }
-
- // 'SVGLocatable' functions
- virtual SVGElement* nearestViewportElement() const = 0;
- virtual SVGElement* farthestViewportElement() const = 0;
-
- enum StyleUpdateStrategy { AllowStyleUpdate, DisallowStyleUpdate };
-
- virtual SVGRect getBBox(StyleUpdateStrategy) = 0;
- virtual AffineTransform getCTM(StyleUpdateStrategy) = 0;
- virtual AffineTransform getScreenCTM(StyleUpdateStrategy) = 0;
- AffineTransform getTransformToElement(SVGElement*, ExceptionState&, StyleUpdateStrategy = AllowStyleUpdate);
-
- static SVGElement* nearestViewportElement(const SVGElement*);
- static SVGElement* farthestViewportElement(const SVGElement*);
-
- enum CTMScope {
- NearestViewportScope, // Used for getCTM()
- ScreenScope // Used for getScreenCTM()
- };
-
-protected:
- virtual AffineTransform localCoordinateSpaceTransform(SVGLocatable::CTMScope) const { return AffineTransform(); }
-
- static SVGRect getBBox(SVGElement*, StyleUpdateStrategy);
- static AffineTransform computeCTM(SVGElement*, CTMScope, StyleUpdateStrategy);
-};
-
-} // namespace WebCore
-
-#endif // SVGLocatable_h
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGMPathElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGMPathElement.cpp
index b766818f475..058738f61de 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGMPathElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGMPathElement.cpp
@@ -21,7 +21,6 @@
#include "core/svg/SVGMPathElement.h"
-#include "SVGNames.h"
#include "XLinkNames.h"
#include "core/dom/Document.h"
#include "core/svg/SVGAnimateMotionElement.h"
@@ -39,17 +38,16 @@ BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGMPathElement)
REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired)
END_REGISTER_ANIMATED_PROPERTIES
-inline SVGMPathElement::SVGMPathElement(const QualifiedName& tagName, Document& document)
- : SVGElement(tagName, document)
+inline SVGMPathElement::SVGMPathElement(Document& document)
+ : SVGElement(SVGNames::mpathTag, document)
{
- ASSERT(hasTagName(SVGNames::mpathTag));
ScriptWrappable::init(this);
registerAnimatedPropertiesForSVGMPathElement();
}
-PassRefPtr<SVGMPathElement> SVGMPathElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGMPathElement> SVGMPathElement::create(Document& document)
{
- return adoptRef(new SVGMPathElement(tagName, document));
+ return adoptRef(new SVGMPathElement(document));
}
SVGMPathElement::~SVGMPathElement()
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGMPathElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGMPathElement.h
index 62e50a5e655..0bccf802d6c 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGMPathElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGMPathElement.h
@@ -35,7 +35,7 @@ class SVGMPathElement FINAL : public SVGElement,
public SVGURIReference,
public SVGExternalResourcesRequired {
public:
- static PassRefPtr<SVGMPathElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGMPathElement> create(Document&);
virtual ~SVGMPathElement();
@@ -44,7 +44,7 @@ public:
void targetPathChanged();
private:
- SVGMPathElement(const QualifiedName&, Document&);
+ explicit SVGMPathElement(Document&);
void buildPendingResource();
void clearResourceReferences();
@@ -64,11 +64,7 @@ private:
END_DECLARE_ANIMATED_PROPERTIES
};
-inline SVGMPathElement* toSVGMPathElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(SVGNames::mpathTag));
- return static_cast<SVGMPathElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(SVGMPathElement, hasTagName(SVGNames::mpathTag));
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGMarkerElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGMarkerElement.cpp
index 9c62bac0ac5..8bb26d62912 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGMarkerElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGMarkerElement.cpp
@@ -26,7 +26,6 @@
#include "SVGNames.h"
#include "core/rendering/svg/RenderSVGResourceMarker.h"
#include "core/svg/SVGElementInstance.h"
-#include "core/svg/SVGFitToViewBox.h"
namespace WebCore {
@@ -70,24 +69,23 @@ BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGMarkerElement)
REGISTER_PARENT_ANIMATED_PROPERTIES(SVGElement)
END_REGISTER_ANIMATED_PROPERTIES
-inline SVGMarkerElement::SVGMarkerElement(const QualifiedName& tagName, Document& document)
- : SVGElement(tagName, document)
+inline SVGMarkerElement::SVGMarkerElement(Document& document)
+ : SVGElement(SVGNames::markerTag, document)
+ , m_orientType(SVGMarkerOrientAngle)
, m_refX(LengthModeWidth)
, m_refY(LengthModeHeight)
, m_markerWidth(LengthModeWidth, "3")
, m_markerHeight(LengthModeHeight, "3")
, m_markerUnits(SVGMarkerUnitsStrokeWidth)
- , m_orientType(SVGMarkerOrientAngle)
{
// Spec: If the markerWidth/markerHeight attribute is not specified, the effect is as if a value of "3" were specified.
- ASSERT(hasTagName(SVGNames::markerTag));
ScriptWrappable::init(this);
registerAnimatedPropertiesForSVGMarkerElement();
}
-PassRefPtr<SVGMarkerElement> SVGMarkerElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGMarkerElement> SVGMarkerElement::create(Document& document)
{
- return adoptRef(new SVGMarkerElement(tagName, document));
+ return adoptRef(new SVGMarkerElement(document));
}
const AtomicString& SVGMarkerElement::orientTypeIdentifier()
@@ -171,8 +169,9 @@ void SVGMarkerElement::svgAttributeChanged(const QualifiedName& attrName)
|| attrName == SVGNames::markerHeightAttr)
updateRelativeLengthsInformation();
- if (RenderObject* object = renderer())
- object->setNeedsLayout();
+ RenderSVGResourceContainer* renderer = toRenderSVGResourceContainer(this->renderer());
+ if (renderer)
+ renderer->invalidateCacheAndMarkForLayout();
}
void SVGMarkerElement::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGMarkerElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGMarkerElement.h
index 05e50e2e6ac..da6b4654f8f 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGMarkerElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGMarkerElement.h
@@ -86,9 +86,9 @@ struct SVGPropertyTraits<SVGMarkerOrientType> {
if (value == "auto")
return SVGMarkerOrientAuto;
- TrackExceptionState es;
- angle.setValueAsString(value, es);
- if (!es.hadException())
+ TrackExceptionState exceptionState;
+ angle.setValueAsString(value, exceptionState);
+ if (!exceptionState.hadException())
return SVGMarkerOrientAngle;
return SVGMarkerOrientUnknown;
}
@@ -111,7 +111,7 @@ public:
SVG_MARKER_ORIENT_ANGLE = SVGMarkerOrientAngle
};
- static PassRefPtr<SVGMarkerElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGMarkerElement> create(Document&);
AffineTransform viewBoxToViewTransform(float viewWidth, float viewHeight) const;
@@ -120,8 +120,16 @@ public:
static const SVGPropertyInfo* orientTypePropertyInfo();
+ // Custom 'orientType' property.
+ static void synchronizeOrientType(SVGElement* contextElement);
+ static PassRefPtr<SVGAnimatedProperty> lookupOrCreateOrientTypeWrapper(SVGElement* contextElement);
+ SVGMarkerOrientType& orientTypeCurrentValue() const { return m_orientType.value; }
+ SVGMarkerOrientType& orientTypeBaseValue() const { return m_orientType.value; }
+ void setOrientTypeBaseValue(const SVGMarkerOrientType& type) { m_orientType.value = type; }
+ PassRefPtr<SVGAnimatedEnumerationPropertyTearOff<SVGMarkerOrientType> > orientType();
+
private:
- SVGMarkerElement(const QualifiedName&, Document&);
+ explicit SVGMarkerElement(Document&);
virtual bool needsPendingResourceHandling() const { return false; }
@@ -140,6 +148,8 @@ private:
static const AtomicString& orientTypeIdentifier();
static const AtomicString& orientAngleIdentifier();
+ mutable SVGSynchronizableAnimatedProperty<SVGMarkerOrientType> m_orientType;
+
BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGMarkerElement)
DECLARE_ANIMATED_LENGTH(RefX, refX)
DECLARE_ANIMATED_LENGTH(RefY, refY)
@@ -151,25 +161,9 @@ private:
DECLARE_ANIMATED_RECT(ViewBox, viewBox)
DECLARE_ANIMATED_PRESERVEASPECTRATIO(PreserveAspectRatio, preserveAspectRatio)
END_DECLARE_ANIMATED_PROPERTIES
-
-public:
- // Custom 'orientType' property.
- static void synchronizeOrientType(SVGElement* contextElement);
- static PassRefPtr<SVGAnimatedProperty> lookupOrCreateOrientTypeWrapper(SVGElement* contextElement);
- SVGMarkerOrientType& orientTypeCurrentValue() const { return m_orientType.value; }
- SVGMarkerOrientType& orientTypeBaseValue() const { return m_orientType.value; }
- void setOrientTypeBaseValue(const SVGMarkerOrientType& type) { m_orientType.value = type; }
- PassRefPtr<SVGAnimatedEnumerationPropertyTearOff<SVGMarkerOrientType> > orientType();
-
-private:
- mutable SVGSynchronizableAnimatedProperty<SVGMarkerOrientType> m_orientType;
};
-inline SVGMarkerElement* toSVGMarkerElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(SVGNames::markerTag));
- return static_cast<SVGMarkerElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(SVGMarkerElement, hasTagName(SVGNames::markerTag));
}
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGMaskElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGMaskElement.cpp
index ecae018ebaa..728dfcb8b4a 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGMaskElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGMaskElement.cpp
@@ -25,10 +25,8 @@
#include "core/svg/SVGMaskElement.h"
-#include "SVGNames.h"
#include "core/rendering/svg/RenderSVGResourceMasker.h"
#include "core/svg/SVGElementInstance.h"
-#include "core/svg/SVGUnitTypes.h"
namespace WebCore {
@@ -53,8 +51,8 @@ BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGMaskElement)
REGISTER_PARENT_ANIMATED_PROPERTIES(SVGTests)
END_REGISTER_ANIMATED_PROPERTIES
-inline SVGMaskElement::SVGMaskElement(const QualifiedName& tagName, Document& document)
- : SVGElement(tagName, document)
+inline SVGMaskElement::SVGMaskElement(Document& document)
+ : SVGElement(SVGNames::maskTag, document)
, m_maskUnits(SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX)
, m_maskContentUnits(SVGUnitTypes::SVG_UNIT_TYPE_USERSPACEONUSE)
, m_x(LengthModeWidth, "-10%")
@@ -64,14 +62,13 @@ inline SVGMaskElement::SVGMaskElement(const QualifiedName& tagName, Document& do
{
// Spec: If the x/y attribute is not specified, the effect is as if a value of "-10%" were specified.
// Spec: If the width/height attribute is not specified, the effect is as if a value of "120%" were specified.
- ASSERT(hasTagName(SVGNames::maskTag));
ScriptWrappable::init(this);
registerAnimatedPropertiesForSVGMaskElement();
}
-PassRefPtr<SVGMaskElement> SVGMaskElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGMaskElement> SVGMaskElement::create(Document& document)
{
- return adoptRef(new SVGMaskElement(tagName, document));
+ return adoptRef(new SVGMaskElement(document));
}
bool SVGMaskElement::isSupportedAttribute(const QualifiedName& attrName)
@@ -137,8 +134,9 @@ void SVGMaskElement::svgAttributeChanged(const QualifiedName& attrName)
|| attrName == SVGNames::heightAttr)
updateRelativeLengthsInformation();
- if (RenderObject* object = renderer())
- object->setNeedsLayout();
+ RenderSVGResourceContainer* renderer = toRenderSVGResourceContainer(this->renderer());
+ if (renderer)
+ renderer->invalidateCacheAndMarkForLayout();
}
void SVGMaskElement::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGMaskElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGMaskElement.h
index dd4043afb52..a4b09ae2e3a 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGMaskElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGMaskElement.h
@@ -35,10 +35,10 @@ class SVGMaskElement FINAL : public SVGElement,
public SVGTests,
public SVGExternalResourcesRequired {
public:
- static PassRefPtr<SVGMaskElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGMaskElement> create(Document&);
private:
- SVGMaskElement(const QualifiedName&, Document&);
+ explicit SVGMaskElement(Document&);
virtual bool isValid() const { return SVGTests::isValid(); }
virtual bool needsPendingResourceHandling() const { return false; }
@@ -68,11 +68,7 @@ private:
virtual void synchronizeSystemLanguage() { SVGTests::synchronizeSystemLanguage(this); }
};
-inline SVGMaskElement* toSVGMaskElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(SVGNames::maskTag));
- return static_cast<SVGMaskElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(SVGMaskElement, hasTagName(SVGNames::maskTag));
}
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGMatrix.h b/chromium/third_party/WebKit/Source/core/svg/SVGMatrix.h
index 7451d32a239..df536b56769 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGMatrix.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGMatrix.h
@@ -22,7 +22,7 @@
#include "bindings/v8/ExceptionState.h"
#include "core/dom/ExceptionCode.h"
-#include "core/platform/graphics/transforms/AffineTransform.h"
+#include "platform/transforms/AffineTransform.h"
namespace WebCore {
@@ -103,23 +103,19 @@ public:
return static_cast<SVGMatrix>(copy);
}
- SVGMatrix inverse(ExceptionState& es) const
+ SVGMatrix inverse(ExceptionState& exceptionState) const
{
AffineTransform transform = AffineTransform::inverse();
- if (!isInvertible()) {
- // FIXME: This used to have a more specific error message:
- // "An attempt was made to invert a matrix that is not invertible."
- // When switching to SVG2 style exceptions we lost this information.
- es.throwDOMException(InvalidStateError);
- }
+ if (!isInvertible())
+ exceptionState.throwDOMException(InvalidStateError, "The matrix is not invertible.");
return transform;
}
- SVGMatrix rotateFromVector(double x, double y, ExceptionState& es)
+ SVGMatrix rotateFromVector(double x, double y, ExceptionState& exceptionState)
{
if (!x || !y)
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwDOMException(InvalidAccessError, "Arguments cannot be zero.");
AffineTransform copy = *this;
copy.rotateFromVector(x, y);
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGMatrix.idl b/chromium/third_party/WebKit/Source/core/svg/SVGMatrix.idl
index dc871be5b9e..af560290c01 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGMatrix.idl
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGMatrix.idl
@@ -20,7 +20,9 @@
* Boston, MA 02110-1301, USA.
*/
-interface SVGMatrix {
+[
+ SetReference(SVGTransform parent)
+] interface SVGMatrix {
// FIXME: these attributes should all be floats but since we implement
// AffineTransform with doubles setting these as doubles makes more sense.
[StrictTypeChecking] attribute double a;
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGMetadataElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGMetadataElement.cpp
index a02eb3114e0..d8ef56a6098 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGMetadataElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGMetadataElement.cpp
@@ -24,16 +24,15 @@
namespace WebCore {
-inline SVGMetadataElement::SVGMetadataElement(const QualifiedName& tagName, Document& document)
- : SVGElement(tagName, document)
+inline SVGMetadataElement::SVGMetadataElement(Document& document)
+ : SVGElement(SVGNames::metadataTag, document)
{
- ASSERT(hasTagName(SVGNames::metadataTag));
ScriptWrappable::init(this);
}
-PassRefPtr<SVGMetadataElement> SVGMetadataElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGMetadataElement> SVGMetadataElement::create(Document& document)
{
- return adoptRef(new SVGMetadataElement(tagName, document));
+ return adoptRef(new SVGMetadataElement(document));
}
}
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGMetadataElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGMetadataElement.h
index 596f3179b30..1d889dfd0b2 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGMetadataElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGMetadataElement.h
@@ -27,10 +27,10 @@ namespace WebCore {
class SVGMetadataElement FINAL : public SVGElement {
public:
- static PassRefPtr<SVGMetadataElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGMetadataElement> create(Document&);
private:
- SVGMetadataElement(const QualifiedName&, Document&);
+ explicit SVGMetadataElement(Document&);
virtual bool rendererIsNeeded(const RenderStyle&) OVERRIDE { return false; }
};
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGMissingGlyphElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGMissingGlyphElement.cpp
index f426e6b1530..dd0ed72f92b 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGMissingGlyphElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGMissingGlyphElement.cpp
@@ -20,21 +20,19 @@
#include "config.h"
#if ENABLE(SVG_FONTS)
-#include "SVGNames.h"
#include "core/svg/SVGMissingGlyphElement.h"
namespace WebCore {
-inline SVGMissingGlyphElement::SVGMissingGlyphElement(const QualifiedName& tagName, Document& document)
- : SVGElement(tagName, document)
+inline SVGMissingGlyphElement::SVGMissingGlyphElement(Document& document)
+ : SVGElement(SVGNames::missing_glyphTag, document)
{
- ASSERT(hasTagName(SVGNames::missing_glyphTag));
ScriptWrappable::init(this);
}
-PassRefPtr<SVGMissingGlyphElement> SVGMissingGlyphElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGMissingGlyphElement> SVGMissingGlyphElement::create(Document& document)
{
- return adoptRef(new SVGMissingGlyphElement(tagName, document));
+ return adoptRef(new SVGMissingGlyphElement(document));
}
}
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGMissingGlyphElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGMissingGlyphElement.h
index 6ff776dec23..9057582fab5 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGMissingGlyphElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGMissingGlyphElement.h
@@ -28,19 +28,15 @@ namespace WebCore {
class SVGMissingGlyphElement FINAL : public SVGElement {
public:
- static PassRefPtr<SVGMissingGlyphElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGMissingGlyphElement> create(Document&);
private:
- SVGMissingGlyphElement(const QualifiedName&, Document&);
+ explicit SVGMissingGlyphElement(Document&);
virtual bool rendererIsNeeded(const RenderStyle&) { return false; }
};
-inline SVGMissingGlyphElement* toSVGMissingGlyphElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(SVGNames::missing_glyphTag));
- return static_cast<SVGMissingGlyphElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(SVGMissingGlyphElement, hasTagName(SVGNames::missing_glyphTag));
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGPaint.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGPaint.cpp
index ae2b9555864..8aa13ae372b 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGPaint.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGPaint.cpp
@@ -23,7 +23,6 @@
#include "core/svg/SVGPaint.h"
#include "bindings/v8/ExceptionState.h"
-#include "wtf/text/WTFString.h"
namespace WebCore {
@@ -63,19 +62,19 @@ void SVGPaint::setUri(const String&)
// The setters are the most problematic part so we remove the support for those first.
}
-void SVGPaint::setPaint(unsigned short, const String&, const String&, const String&, ExceptionState& es)
+void SVGPaint::setPaint(unsigned short, const String&, const String&, const String&, ExceptionState& exceptionState)
{
- es.throwDOMException(NoModificationAllowedError);
+ exceptionState.throwUninformativeAndGenericDOMException(NoModificationAllowedError);
}
-String SVGPaint::customCssText() const
+String SVGPaint::customCSSText() const
{
switch (m_paintType) {
case SVG_PAINTTYPE_UNKNOWN:
case SVG_PAINTTYPE_RGBCOLOR:
case SVG_PAINTTYPE_RGBCOLOR_ICCCOLOR:
case SVG_PAINTTYPE_CURRENTCOLOR:
- return SVGColor::customCssText();
+ return SVGColor::customCSSText();
case SVG_PAINTTYPE_NONE:
return "none";
case SVG_PAINTTYPE_URI_NONE:
@@ -83,7 +82,7 @@ String SVGPaint::customCssText() const
case SVG_PAINTTYPE_URI_CURRENTCOLOR:
case SVG_PAINTTYPE_URI_RGBCOLOR:
case SVG_PAINTTYPE_URI_RGBCOLOR_ICCCOLOR: {
- String color = SVGColor::customCssText();
+ String color = SVGColor::customCSSText();
if (color.isEmpty())
return m_uri;
return "url(" + m_uri + ") " + color;
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGPaint.h b/chromium/third_party/WebKit/Source/core/svg/SVGPaint.h
index f4f387dde15..f48b4b7ba07 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGPaint.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGPaint.h
@@ -92,7 +92,7 @@ public:
void setUri(const String&);
void setPaint(unsigned short paintType, const String& uri, const String& rgbColor, const String& iccColor, ExceptionState&);
- String customCssText() const;
+ String customCSSText() const;
PassRefPtr<SVGPaint> cloneForCSSOM() const;
@@ -116,6 +116,8 @@ private:
String m_uri;
};
+DEFINE_CSS_VALUE_TYPE_CASTS(SVGPaint, isSVGPaint());
+
} // namespace WebCore
#endif // SVGPaint_h
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGParserUtilities.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGParserUtilities.cpp
index bee9c1bb58c..262ef622f91 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGParserUtilities.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGParserUtilities.cpp
@@ -24,8 +24,10 @@
#include "core/svg/SVGParserUtilities.h"
#include "core/dom/Document.h"
-#include "core/platform/graphics/FloatRect.h"
#include "core/svg/SVGPointList.h"
+#include "core/svg/SVGTransformList.h"
+#include "platform/geometry/FloatRect.h"
+#include "platform/transforms/AffineTransform.h"
#include "wtf/ASCIICType.h"
#include <limits>
@@ -559,4 +561,207 @@ bool parseFloatPoint3(const CharType*& current, const CharType* end, FloatPoint&
template bool parseFloatPoint3(const LChar*& current, const LChar* end, FloatPoint& point1, FloatPoint& point2, FloatPoint& point3);
template bool parseFloatPoint3(const UChar*& current, const UChar* end, FloatPoint& point1, FloatPoint& point2, FloatPoint& point3);
+template<typename CharType>
+static int parseTransformParamList(const CharType*& ptr, const CharType* end, float* values, int required, int optional)
+{
+ int optionalParams = 0, requiredParams = 0;
+
+ if (!skipOptionalSVGSpaces(ptr, end) || *ptr != '(')
+ return -1;
+
+ ptr++;
+
+ skipOptionalSVGSpaces(ptr, end);
+
+ while (requiredParams < required) {
+ if (ptr >= end || !parseNumber(ptr, end, values[requiredParams], false))
+ return -1;
+ requiredParams++;
+ if (requiredParams < required)
+ skipOptionalSVGSpacesOrDelimiter(ptr, end);
+ }
+ if (!skipOptionalSVGSpaces(ptr, end))
+ return -1;
+
+ bool delimParsed = skipOptionalSVGSpacesOrDelimiter(ptr, end);
+
+ if (ptr >= end)
+ return -1;
+
+ if (*ptr == ')') { // skip optionals
+ ptr++;
+ if (delimParsed)
+ return -1;
+ } else {
+ while (optionalParams < optional) {
+ if (ptr >= end || !parseNumber(ptr, end, values[requiredParams + optionalParams], false))
+ return -1;
+ optionalParams++;
+ if (optionalParams < optional)
+ skipOptionalSVGSpacesOrDelimiter(ptr, end);
+ }
+
+ if (!skipOptionalSVGSpaces(ptr, end))
+ return -1;
+
+ delimParsed = skipOptionalSVGSpacesOrDelimiter(ptr, end);
+
+ if (ptr >= end || *ptr != ')' || delimParsed)
+ return -1;
+ ptr++;
+ }
+
+ return requiredParams + optionalParams;
+}
+
+// These should be kept in sync with enum SVGTransformType
+static const int requiredValuesForType[] = {0, 6, 1, 1, 1, 1, 1};
+static const int optionalValuesForType[] = {0, 0, 1, 1, 2, 0, 0};
+
+template<typename CharType>
+static bool parseTransformValueInternal(unsigned type, const CharType*& ptr, const CharType* end, SVGTransform& transform)
+{
+ if (type == SVGTransform::SVG_TRANSFORM_UNKNOWN)
+ return false;
+
+ int valueCount = 0;
+ float values[] = {0, 0, 0, 0, 0, 0};
+ if ((valueCount = parseTransformParamList(ptr, end, values, requiredValuesForType[type], optionalValuesForType[type])) < 0)
+ return false;
+
+ switch (type) {
+ case SVGTransform::SVG_TRANSFORM_SKEWX:
+ transform.setSkewX(values[0]);
+ break;
+ case SVGTransform::SVG_TRANSFORM_SKEWY:
+ transform.setSkewY(values[0]);
+ break;
+ case SVGTransform::SVG_TRANSFORM_SCALE:
+ if (valueCount == 1) // Spec: if only one param given, assume uniform scaling
+ transform.setScale(values[0], values[0]);
+ else
+ transform.setScale(values[0], values[1]);
+ break;
+ case SVGTransform::SVG_TRANSFORM_TRANSLATE:
+ if (valueCount == 1) // Spec: if only one param given, assume 2nd param to be 0
+ transform.setTranslate(values[0], 0);
+ else
+ transform.setTranslate(values[0], values[1]);
+ break;
+ case SVGTransform::SVG_TRANSFORM_ROTATE:
+ if (valueCount == 1)
+ transform.setRotate(values[0], 0, 0);
+ else
+ transform.setRotate(values[0], values[1], values[2]);
+ break;
+ case SVGTransform::SVG_TRANSFORM_MATRIX:
+ transform.setMatrix(AffineTransform(values[0], values[1], values[2], values[3], values[4], values[5]));
+ break;
+ }
+
+ return true;
+}
+
+bool parseTransformValue(unsigned type, const LChar*& ptr, const LChar* end, SVGTransform& transform)
+{
+ return parseTransformValueInternal(type, ptr, end, transform);
+}
+
+bool parseTransformValue(unsigned type, const UChar*& ptr, const UChar* end, SVGTransform& transform)
+{
+ return parseTransformValueInternal(type, ptr, end, transform);
+}
+
+static const LChar skewXDesc[] = {'s', 'k', 'e', 'w', 'X'};
+static const LChar skewYDesc[] = {'s', 'k', 'e', 'w', 'Y'};
+static const LChar scaleDesc[] = {'s', 'c', 'a', 'l', 'e'};
+static const LChar translateDesc[] = {'t', 'r', 'a', 'n', 's', 'l', 'a', 't', 'e'};
+static const LChar rotateDesc[] = {'r', 'o', 't', 'a', 't', 'e'};
+static const LChar matrixDesc[] = {'m', 'a', 't', 'r', 'i', 'x'};
+
+template<typename CharType>
+static inline bool parseAndSkipType(const CharType*& ptr, const CharType* end, unsigned short& type)
+{
+ if (ptr >= end)
+ return false;
+
+ if (*ptr == 's') {
+ if (skipString(ptr, end, skewXDesc, WTF_ARRAY_LENGTH(skewXDesc)))
+ type = SVGTransform::SVG_TRANSFORM_SKEWX;
+ else if (skipString(ptr, end, skewYDesc, WTF_ARRAY_LENGTH(skewYDesc)))
+ type = SVGTransform::SVG_TRANSFORM_SKEWY;
+ else if (skipString(ptr, end, scaleDesc, WTF_ARRAY_LENGTH(scaleDesc)))
+ type = SVGTransform::SVG_TRANSFORM_SCALE;
+ else
+ return false;
+ } else if (skipString(ptr, end, translateDesc, WTF_ARRAY_LENGTH(translateDesc)))
+ type = SVGTransform::SVG_TRANSFORM_TRANSLATE;
+ else if (skipString(ptr, end, rotateDesc, WTF_ARRAY_LENGTH(rotateDesc)))
+ type = SVGTransform::SVG_TRANSFORM_ROTATE;
+ else if (skipString(ptr, end, matrixDesc, WTF_ARRAY_LENGTH(matrixDesc)))
+ type = SVGTransform::SVG_TRANSFORM_MATRIX;
+ else
+ return false;
+
+ return true;
+}
+
+SVGTransform::SVGTransformType parseTransformType(const String& string)
+{
+ if (string.isEmpty())
+ return SVGTransform::SVG_TRANSFORM_UNKNOWN;
+ unsigned short type = SVGTransform::SVG_TRANSFORM_UNKNOWN;
+ if (string.is8Bit()) {
+ const LChar* ptr = string.characters8();
+ const LChar* end = ptr + string.length();
+ parseAndSkipType(ptr, end, type);
+ } else {
+ const UChar* ptr = string.characters16();
+ const UChar* end = ptr + string.length();
+ parseAndSkipType(ptr, end, type);
+ }
+ return static_cast<SVGTransform::SVGTransformType>(type);
+}
+
+template<typename CharType>
+bool parseTransformAttributeInternal(SVGTransformList& list, const CharType*& ptr, const CharType* end, TransformParsingMode mode)
+{
+ if (mode == ClearList)
+ list.clear();
+
+ bool delimParsed = false;
+ while (ptr < end) {
+ delimParsed = false;
+ unsigned short type = SVGTransform::SVG_TRANSFORM_UNKNOWN;
+ skipOptionalSVGSpaces(ptr, end);
+
+ if (!parseAndSkipType(ptr, end, type))
+ return false;
+
+ SVGTransform transform;
+ if (!parseTransformValue(type, ptr, end, transform))
+ return false;
+
+ list.append(transform);
+ skipOptionalSVGSpaces(ptr, end);
+ if (ptr < end && *ptr == ',') {
+ delimParsed = true;
+ ++ptr;
+ }
+ skipOptionalSVGSpaces(ptr, end);
+ }
+
+ return !delimParsed;
+}
+
+bool parseTransformAttribute(SVGTransformList& list, const LChar*& ptr, const LChar* end, TransformParsingMode mode)
+{
+ return parseTransformAttributeInternal(list, ptr, end, mode);
+}
+
+bool parseTransformAttribute(SVGTransformList& list, const UChar*& ptr, const UChar* end, TransformParsingMode mode)
+{
+ return parseTransformAttributeInternal(list, ptr, end, mode);
+}
+
}
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGParserUtilities.h b/chromium/third_party/WebKit/Source/core/svg/SVGParserUtilities.h
index 656e8b71e41..2946cf15cb7 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGParserUtilities.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGParserUtilities.h
@@ -22,7 +22,8 @@
#ifndef SVGParserUtilities_h
#define SVGParserUtilities_h
-#include "core/platform/text/ParserUtilities.h"
+#include "core/svg/SVGTransform.h"
+#include "platform/text/ParserUtilities.h"
#include "wtf/HashSet.h"
typedef pair<unsigned, unsigned> UnicodeRange;
@@ -33,6 +34,7 @@ namespace WebCore {
class FloatPoint;
class FloatRect;
class SVGPointList;
+class SVGTransformList;
template <typename CharType>
bool parseSVGNumber(CharType* ptr, size_t length, double& number);
@@ -86,6 +88,19 @@ Vector<String> parseDelimitedString(const String& input, const char seperator);
bool parseKerningUnicodeString(const String& input, UnicodeRanges&, HashSet<String>& stringList);
bool parseGlyphName(const String& input, HashSet<String>& values);
+enum TransformParsingMode {
+ ClearList,
+ DoNotClearList
+};
+
+bool parseTransformAttribute(SVGTransformList&, const LChar*& ptr, const LChar* end, TransformParsingMode = ClearList);
+bool parseTransformAttribute(SVGTransformList&, const UChar*& ptr, const UChar* end, TransformParsingMode = ClearList);
+
+bool parseTransformValue(unsigned type, const LChar*& ptr, const LChar* end, SVGTransform&);
+bool parseTransformValue(unsigned type, const UChar*& ptr, const UChar* end, SVGTransform&);
+
+SVGTransform::SVGTransformType parseTransformType(const String&);
+
} // namespace WebCore
#endif // SVGParserUtilities_h
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGPathBlender.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGPathBlender.cpp
index eba041bac43..dfeb61b2673 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGPathBlender.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGPathBlender.cpp
@@ -20,9 +20,9 @@
#include "config.h"
#include "core/svg/SVGPathBlender.h"
-#include "core/platform/animation/AnimationUtilities.h"
#include "core/svg/SVGPathSeg.h"
#include "core/svg/SVGPathSource.h"
+#include "platform/animation/AnimationUtilities.h"
#include "wtf/TemporaryChange.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGPathBuilder.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGPathBuilder.cpp
index a489a79b079..2a8cc001634 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGPathBuilder.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGPathBuilder.cpp
@@ -24,7 +24,7 @@
#include "config.h"
#include "core/svg/SVGPathBuilder.h"
-#include "core/platform/graphics/Path.h"
+#include "platform/graphics/Path.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGPathBuilder.h b/chromium/third_party/WebKit/Source/core/svg/SVGPathBuilder.h
index e3a9c4d215a..0c6a15d4aee 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGPathBuilder.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGPathBuilder.h
@@ -24,8 +24,8 @@
#ifndef SVGPathBuilder_h
#define SVGPathBuilder_h
-#include "core/platform/graphics/FloatPoint.h"
#include "core/svg/SVGPathConsumer.h"
+#include "platform/geometry/FloatPoint.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGPathByteStreamBuilder.h b/chromium/third_party/WebKit/Source/core/svg/SVGPathByteStreamBuilder.h
index 06c26e6805e..b3fd7472ffe 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGPathByteStreamBuilder.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGPathByteStreamBuilder.h
@@ -20,9 +20,9 @@
#ifndef SVGPathByteStreamBuilder_h
#define SVGPathByteStreamBuilder_h
-#include "core/platform/graphics/FloatPoint.h"
#include "core/svg/SVGPathByteStream.h"
#include "core/svg/SVGPathConsumer.h"
+#include "platform/geometry/FloatPoint.h"
#include "wtf/PassOwnPtr.h"
#include "wtf/text/WTFString.h"
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGPathByteStreamSource.h b/chromium/third_party/WebKit/Source/core/svg/SVGPathByteStreamSource.h
index ebdb90a1342..9dedab5bfe5 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGPathByteStreamSource.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGPathByteStreamSource.h
@@ -20,9 +20,9 @@
#ifndef SVGPathByteStreamSource_h
#define SVGPathByteStreamSource_h
-#include "core/platform/graphics/FloatPoint.h"
#include "core/svg/SVGPathByteStream.h"
#include "core/svg/SVGPathSource.h"
+#include "platform/geometry/FloatPoint.h"
#include "wtf/PassOwnPtr.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGPathConsumer.h b/chromium/third_party/WebKit/Source/core/svg/SVGPathConsumer.h
index fbd9e5609c3..dfb841f7e71 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGPathConsumer.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGPathConsumer.h
@@ -24,7 +24,7 @@
#ifndef SVGPathConsumer_h
#define SVGPathConsumer_h
-#include "core/platform/graphics/FloatPoint.h"
+#include "platform/geometry/FloatPoint.h"
#include "wtf/FastAllocBase.h"
#include "wtf/Noncopyable.h"
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGPathElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGPathElement.cpp
index 33b20a236d9..82af73a0123 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGPathElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGPathElement.cpp
@@ -22,7 +22,6 @@
#include "core/svg/SVGPathElement.h"
-#include "SVGNames.h"
#include "core/rendering/svg/RenderSVGPath.h"
#include "core/rendering/svg/RenderSVGResource.h"
#include "core/svg/SVGElementInstance.h"
@@ -44,7 +43,6 @@
#include "core/svg/SVGPathSegLinetoRel.h"
#include "core/svg/SVGPathSegLinetoVerticalAbs.h"
#include "core/svg/SVGPathSegLinetoVerticalRel.h"
-#include "core/svg/SVGPathSegList.h"
#include "core/svg/SVGPathSegMovetoAbs.h"
#include "core/svg/SVGPathSegMovetoRel.h"
#include "core/svg/SVGPathUtilities.h"
@@ -78,20 +76,19 @@ BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGPathElement)
REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
END_REGISTER_ANIMATED_PROPERTIES
-inline SVGPathElement::SVGPathElement(const QualifiedName& tagName, Document& document)
- : SVGGraphicsElement(tagName, document)
+inline SVGPathElement::SVGPathElement(Document& document)
+ : SVGGeometryElement(SVGNames::pathTag, document)
, m_pathByteStream(SVGPathByteStream::create())
, m_pathSegList(PathSegUnalteredRole)
, m_isAnimValObserved(false)
{
- ASSERT(hasTagName(SVGNames::pathTag));
ScriptWrappable::init(this);
registerAnimatedPropertiesForSVGPathElement();
}
-PassRefPtr<SVGPathElement> SVGPathElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGPathElement> SVGPathElement::create(Document& document)
{
- return adoptRef(new SVGPathElement(tagName, document));
+ return adoptRef(new SVGPathElement(document));
}
float SVGPathElement::getTotalLength()
@@ -224,7 +221,7 @@ bool SVGPathElement::isSupportedAttribute(const QualifiedName& attrName)
void SVGPathElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
{
if (!isSupportedAttribute(name)) {
- SVGGraphicsElement::parseAttribute(name, value);
+ SVGGeometryElement::parseAttribute(name, value);
return;
}
@@ -250,7 +247,7 @@ void SVGPathElement::parseAttribute(const QualifiedName& name, const AtomicStrin
void SVGPathElement::svgAttributeChanged(const QualifiedName& attrName)
{
if (!isSupportedAttribute(attrName)) {
- SVGGraphicsElement::svgAttributeChanged(attrName);
+ SVGGeometryElement::svgAttributeChanged(attrName);
return;
}
@@ -290,14 +287,14 @@ void SVGPathElement::invalidateMPathDependencies()
Node::InsertionNotificationRequest SVGPathElement::insertedInto(ContainerNode* rootParent)
{
- SVGGraphicsElement::insertedInto(rootParent);
+ SVGGeometryElement::insertedInto(rootParent);
invalidateMPathDependencies();
return InsertionDone;
}
void SVGPathElement::removedFrom(ContainerNode* rootParent)
{
- SVGGraphicsElement::removedFrom(rootParent);
+ SVGGeometryElement::removedFrom(rootParent);
invalidateMPathDependencies();
}
@@ -385,17 +382,18 @@ void SVGPathElement::pathSegListChanged(SVGPathSegRole role, ListModification li
RenderSVGResource::markForLayoutAndParentResourceInvalidation(renderer);
}
-FloatRect SVGPathElement::getBBox(StyleUpdateStrategy styleUpdateStrategy)
+SVGRect SVGPathElement::getBBox()
{
- if (styleUpdateStrategy == AllowStyleUpdate)
- this->document().updateLayoutIgnorePendingStylesheets();
+ // By default, getBBox() returns objectBoundingBox but that will include
+ // markers so we override it to return just the path's bounding rect.
- RenderSVGPath* renderer = toRenderSVGPath(this->renderer());
+ document().updateLayoutIgnorePendingStylesheets();
// FIXME: Eventually we should support getBBox for detached elements.
- if (!renderer)
- return FloatRect();
+ if (!renderer())
+ return SVGRect();
+ RenderSVGPath* renderer = toRenderSVGPath(this->renderer());
return renderer->path().boundingRect();
}
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGPathElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGPathElement.h
index 3065a0eda4d..adc861c4fea 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGPathElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGPathElement.h
@@ -25,7 +25,7 @@
#include "core/svg/SVGAnimatedBoolean.h"
#include "core/svg/SVGAnimatedNumber.h"
#include "core/svg/SVGExternalResourcesRequired.h"
-#include "core/svg/SVGGraphicsElement.h"
+#include "core/svg/SVGGeometryElement.h"
#include "core/svg/SVGPathByteStream.h"
#include "core/svg/SVGPathSegList.h"
@@ -52,10 +52,10 @@ class SVGPathSegCurvetoQuadraticSmoothAbs;
class SVGPathSegCurvetoQuadraticSmoothRel;
class SVGPathSegListPropertyTearOff;
-class SVGPathElement FINAL : public SVGGraphicsElement,
+class SVGPathElement FINAL : public SVGGeometryElement,
public SVGExternalResourcesRequired {
public:
- static PassRefPtr<SVGPathElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGPathElement> create(Document&);
float getTotalLength();
SVGPoint getPointAtLength(float distance);
@@ -91,14 +91,14 @@ public:
void pathSegListChanged(SVGPathSegRole, ListModification = ListModificationUnknown);
- virtual FloatRect getBBox(StyleUpdateStrategy = AllowStyleUpdate);
+ virtual SVGRect getBBox() OVERRIDE FINAL;
static const SVGPropertyInfo* dPropertyInfo();
bool isAnimValObserved() const { return m_isAnimValObserved; }
private:
- SVGPathElement(const QualifiedName&, Document&);
+ explicit SVGPathElement(Document&);
virtual bool isValid() const { return SVGTests::isValid(); }
virtual bool supportsFocus() const OVERRIDE { return hasFocusEventListeners(); }
@@ -112,11 +112,6 @@ private:
static void synchronizeD(SVGElement* contextElement);
static PassRefPtr<SVGAnimatedProperty> lookupOrCreateDWrapper(SVGElement* contextElement);
- BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGPathElement)
- DECLARE_ANIMATED_NUMBER(PathLength, pathLength)
- DECLARE_ANIMATED_BOOLEAN(ExternalResourcesRequired, externalResourcesRequired)
- END_DECLARE_ANIMATED_PROPERTIES
-
virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
virtual Node::InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
@@ -124,17 +119,17 @@ private:
void invalidateMPathDependencies();
-private:
OwnPtr<SVGPathByteStream> m_pathByteStream;
mutable SVGSynchronizableAnimatedProperty<SVGPathSegList> m_pathSegList;
bool m_isAnimValObserved;
+
+ BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGPathElement)
+ DECLARE_ANIMATED_NUMBER(PathLength, pathLength)
+ DECLARE_ANIMATED_BOOLEAN(ExternalResourcesRequired, externalResourcesRequired)
+ END_DECLARE_ANIMATED_PROPERTIES
};
-inline SVGPathElement* toSVGPathElement(Element* element)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!element || element->hasTagName(SVGNames::pathTag));
- return static_cast<SVGPathElement*>(element);
-}
+DEFINE_NODE_TYPE_CASTS(SVGPathElement, hasTagName(SVGNames::pathTag));
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGPathElement.idl b/chromium/third_party/WebKit/Source/core/svg/SVGPathElement.idl
index 083663bb15f..297b5b1d684 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGPathElement.idl
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGPathElement.idl
@@ -24,81 +24,47 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-interface SVGPathElement : SVGGraphicsElement {
+interface SVGPathElement : SVGGeometryElement {
readonly attribute SVGAnimatedNumber pathLength;
float getTotalLength();
- SVGPoint getPointAtLength([Default=Undefined] optional float distance);
- unsigned long getPathSegAtLength([Default=Undefined] optional float distance);
+ [StrictTypeChecking] SVGPoint getPointAtLength(float distance);
+ [StrictTypeChecking] unsigned long getPathSegAtLength(float distance);
SVGPathSegClosePath createSVGPathSegClosePath();
- SVGPathSegMovetoAbs createSVGPathSegMovetoAbs([Default=Undefined] optional float x,
- [Default=Undefined] optional float y);
- SVGPathSegMovetoRel createSVGPathSegMovetoRel([Default=Undefined] optional float x,
- [Default=Undefined] optional float y);
+ [StrictTypeChecking] SVGPathSegMovetoAbs createSVGPathSegMovetoAbs(float x, float y);
+ [StrictTypeChecking] SVGPathSegMovetoRel createSVGPathSegMovetoRel(float x, float y);
- SVGPathSegLinetoAbs createSVGPathSegLinetoAbs([Default=Undefined] optional float x,
- [Default=Undefined] optional float y);
- SVGPathSegLinetoRel createSVGPathSegLinetoRel([Default=Undefined] optional float x,
- [Default=Undefined] optional float y);
+ [StrictTypeChecking] SVGPathSegLinetoAbs createSVGPathSegLinetoAbs(float x, float y);
+ [StrictTypeChecking] SVGPathSegLinetoRel createSVGPathSegLinetoRel(float x, float y);
- SVGPathSegCurvetoCubicAbs createSVGPathSegCurvetoCubicAbs([Default=Undefined] optional float x,
- [Default=Undefined] optional float y,
- [Default=Undefined] optional float x1,
- [Default=Undefined] optional float y1,
- [Default=Undefined] optional float x2,
- [Default=Undefined] optional float y2);
- SVGPathSegCurvetoCubicRel createSVGPathSegCurvetoCubicRel([Default=Undefined] optional float x,
- [Default=Undefined] optional float y,
- [Default=Undefined] optional float x1,
- [Default=Undefined] optional float y1,
- [Default=Undefined] optional float x2,
- [Default=Undefined] optional float y2);
+ [StrictTypeChecking] SVGPathSegCurvetoCubicAbs
+ createSVGPathSegCurvetoCubicAbs(float x, float y, float x1, float y1, float x2, float y2);
+ [StrictTypeChecking] SVGPathSegCurvetoCubicRel
+ createSVGPathSegCurvetoCubicRel(float x, float y, float x1, float y1, float x2, float y2);
- SVGPathSegCurvetoQuadraticAbs createSVGPathSegCurvetoQuadraticAbs([Default=Undefined] optional float x,
- [Default=Undefined] optional float y,
- [Default=Undefined] optional float x1,
- [Default=Undefined] optional float y1);
- SVGPathSegCurvetoQuadraticRel createSVGPathSegCurvetoQuadraticRel([Default=Undefined] optional float x,
- [Default=Undefined] optional float y,
- [Default=Undefined] optional float x1,
- [Default=Undefined] optional float y1);
+ [StrictTypeChecking] SVGPathSegCurvetoQuadraticAbs
+ createSVGPathSegCurvetoQuadraticAbs(float x, float y, float x1, float y1);
+ [StrictTypeChecking] SVGPathSegCurvetoQuadraticRel
+ createSVGPathSegCurvetoQuadraticRel(float x, float y, float x1, float y1);
- SVGPathSegArcAbs createSVGPathSegArcAbs([Default=Undefined] optional float x,
- [Default=Undefined] optional float y,
- [Default=Undefined] optional float r1,
- [Default=Undefined] optional float r2,
- [Default=Undefined] optional float angle,
- [Default=Undefined] optional boolean largeArcFlag,
- [Default=Undefined] optional boolean sweepFlag);
- SVGPathSegArcRel createSVGPathSegArcRel([Default=Undefined] optional float x,
- [Default=Undefined] optional float y,
- [Default=Undefined] optional float r1,
- [Default=Undefined] optional float r2,
- [Default=Undefined] optional float angle,
- [Default=Undefined] optional boolean largeArcFlag,
- [Default=Undefined] optional boolean sweepFlag);
+ [StrictTypeChecking] SVGPathSegArcAbs
+ createSVGPathSegArcAbs(float x, float y, float r1, float r2, float angle, boolean largeArcFlag, boolean sweepFlag);
+ [StrictTypeChecking] SVGPathSegArcRel
+ createSVGPathSegArcRel(float x, float y, float r1, float r2, float angle, boolean largeArcFlag, boolean sweepFlag);
- SVGPathSegLinetoHorizontalAbs createSVGPathSegLinetoHorizontalAbs([Default=Undefined] optional float x);
- SVGPathSegLinetoHorizontalRel createSVGPathSegLinetoHorizontalRel([Default=Undefined] optional float x);
+ [StrictTypeChecking] SVGPathSegLinetoHorizontalAbs createSVGPathSegLinetoHorizontalAbs(float x);
+ [StrictTypeChecking] SVGPathSegLinetoHorizontalRel createSVGPathSegLinetoHorizontalRel(float x);
- SVGPathSegLinetoVerticalAbs createSVGPathSegLinetoVerticalAbs([Default=Undefined] optional float y);
- SVGPathSegLinetoVerticalRel createSVGPathSegLinetoVerticalRel([Default=Undefined] optional float y);
+ [StrictTypeChecking] SVGPathSegLinetoVerticalAbs createSVGPathSegLinetoVerticalAbs(float y);
+ [StrictTypeChecking] SVGPathSegLinetoVerticalRel createSVGPathSegLinetoVerticalRel(float y);
- SVGPathSegCurvetoCubicSmoothAbs createSVGPathSegCurvetoCubicSmoothAbs([Default=Undefined] optional float x,
- [Default=Undefined] optional float y,
- [Default=Undefined] optional float x2,
- [Default=Undefined] optional float y2);
- SVGPathSegCurvetoCubicSmoothRel createSVGPathSegCurvetoCubicSmoothRel([Default=Undefined] optional float x,
- [Default=Undefined] optional float y,
- [Default=Undefined] optional float x2,
- [Default=Undefined] optional float y2);
+ [StrictTypeChecking] SVGPathSegCurvetoCubicSmoothAbs createSVGPathSegCurvetoCubicSmoothAbs(float x, float y, float x2, float y2);
+ [StrictTypeChecking] SVGPathSegCurvetoCubicSmoothRel createSVGPathSegCurvetoCubicSmoothRel(float x, float y, float x2, float y2);
- SVGPathSegCurvetoQuadraticSmoothAbs createSVGPathSegCurvetoQuadraticSmoothAbs([Default=Undefined] optional float x,
- [Default=Undefined] optional float y);
- SVGPathSegCurvetoQuadraticSmoothRel createSVGPathSegCurvetoQuadraticSmoothRel([Default=Undefined] optional float x,
- [Default=Undefined] optional float y);
+ [StrictTypeChecking] SVGPathSegCurvetoQuadraticSmoothAbs createSVGPathSegCurvetoQuadraticSmoothAbs(float x, float y);
+ [StrictTypeChecking] SVGPathSegCurvetoQuadraticSmoothRel createSVGPathSegCurvetoQuadraticSmoothRel(float x, float y);
readonly attribute SVGPathSegList pathSegList;
readonly attribute SVGPathSegList normalizedPathSegList;
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGPathParser.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGPathParser.cpp
index 62c90c85bb5..6b7ac433993 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGPathParser.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGPathParser.cpp
@@ -24,8 +24,8 @@
#include "config.h"
#include "core/svg/SVGPathParser.h"
-#include "core/platform/graphics/transforms/AffineTransform.h"
#include "core/svg/SVGPathSource.h"
+#include "platform/transforms/AffineTransform.h"
#include "wtf/MathExtras.h"
static const float gOneOverThree = 1 / 3.f;
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGPathSeg.idl b/chromium/third_party/WebKit/Source/core/svg/SVGPathSeg.idl
index 4ca8a2c53dd..60ed633dd31 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGPathSeg.idl
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGPathSeg.idl
@@ -25,7 +25,7 @@
*/
[
- CustomToV8
+ Custom=Wrap,
] interface SVGPathSeg {
// Path Segment Types
const unsigned short PATHSEG_UNKNOWN = 0;
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGPathSegListBuilder.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGPathSegListBuilder.cpp
index afc00b4a175..b394f526c14 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGPathSegListBuilder.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGPathSegListBuilder.cpp
@@ -44,7 +44,6 @@
#include "core/svg/SVGPathSegLinetoRel.h"
#include "core/svg/SVGPathSegLinetoVerticalAbs.h"
#include "core/svg/SVGPathSegLinetoVerticalRel.h"
-#include "core/svg/SVGPathSegList.h"
#include "core/svg/SVGPathSegMovetoAbs.h"
#include "core/svg/SVGPathSegMovetoRel.h"
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGPathSegListBuilder.h b/chromium/third_party/WebKit/Source/core/svg/SVGPathSegListBuilder.h
index 1c9e06d9d47..7b5c3aacbe2 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGPathSegListBuilder.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGPathSegListBuilder.h
@@ -24,9 +24,9 @@
#ifndef SVGPathSegListBuilder_h
#define SVGPathSegListBuilder_h
-#include "core/platform/graphics/FloatPoint.h"
#include "core/svg/SVGPathConsumer.h"
#include "core/svg/SVGPathSegList.h"
+#include "platform/geometry/FloatPoint.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGPathSegListSource.h b/chromium/third_party/WebKit/Source/core/svg/SVGPathSegListSource.h
index b0e0cdd6160..9ff02c4d8ba 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGPathSegListSource.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGPathSegListSource.h
@@ -20,10 +20,10 @@
#ifndef SVGPathSegListSource_h
#define SVGPathSegListSource_h
-#include "core/platform/graphics/FloatPoint.h"
#include "core/svg/SVGPathSeg.h"
#include "core/svg/SVGPathSegList.h"
#include "core/svg/SVGPathSource.h"
+#include "platform/geometry/FloatPoint.h"
#include "wtf/PassOwnPtr.h"
#include "wtf/RefPtr.h"
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGPathSegWithContext.h b/chromium/third_party/WebKit/Source/core/svg/SVGPathSegWithContext.h
index e2fbe84b4d3..c12689d24dc 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGPathSegWithContext.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGPathSegWithContext.h
@@ -38,7 +38,7 @@ public:
case PathSegUndefinedRole:
return 0;
case PathSegUnalteredRole:
- return SVGAnimatedProperty::lookupWrapper<SVGPathElement, SVGAnimatedPathSegListPropertyTearOff>(m_element.get(), SVGPathElement::dPropertyInfo());
+ return SVGAnimatedProperty::lookupWrapper<SVGPathElement, SVGAnimatedPathSegListPropertyTearOff>(m_element, SVGPathElement::dPropertyInfo());
case PathSegNormalizedRole:
// FIXME: https://bugs.webkit.org/show_bug.cgi?id=15412 - Implement normalized path segment lists!
return 0;
@@ -47,7 +47,7 @@ public:
return 0;
}
- SVGPathElement* contextElement() const { return m_element.get(); }
+ SVGPathElement* contextElement() const { return m_element; }
SVGPathSegRole role() const { return m_role; }
void setContextAndRole(SVGPathElement* element, SVGPathSegRole role)
@@ -64,13 +64,12 @@ protected:
return;
}
- ASSERT(m_role != PathSegUndefinedRole);
m_element->pathSegListChanged(m_role);
}
private:
SVGPathSegRole m_role;
- RefPtr<SVGPathElement> m_element;
+ SVGPathElement* m_element;
};
class SVGPathSegSingleCoordinate : public SVGPathSegWithContext {
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGPathStringBuilder.h b/chromium/third_party/WebKit/Source/core/svg/SVGPathStringBuilder.h
index 8e20442aba3..68938945e1a 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGPathStringBuilder.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGPathStringBuilder.h
@@ -20,8 +20,8 @@
#ifndef SVGPathStringBuilder_h
#define SVGPathStringBuilder_h
-#include "core/platform/graphics/FloatPoint.h"
#include "core/svg/SVGPathConsumer.h"
+#include "platform/geometry/FloatPoint.h"
#include "wtf/text/StringBuilder.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGPathStringSource.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGPathStringSource.cpp
index 92c8ca64d15..75e983d6a2e 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGPathStringSource.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGPathStringSource.cpp
@@ -22,8 +22,8 @@
#include "core/svg/SVGPathStringSource.h"
-#include "core/platform/graphics/FloatPoint.h"
#include "core/svg/SVGParserUtilities.h"
+#include "platform/geometry/FloatPoint.h"
namespace WebCore {
@@ -247,4 +247,4 @@ bool SVGPathStringSource::parseArcToSegment(float& rx, float& ry, float& angle,
return parseArcToSegmentHelper(m_current.m_character16, m_end.m_character16, rx, ry, angle, largeArc, sweep, targetPoint);
}
-} // namespace WebKit
+} // namespace blink
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGPathTraversalStateBuilder.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGPathTraversalStateBuilder.cpp
index 99d93630cf6..1fe2b5cb183 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGPathTraversalStateBuilder.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGPathTraversalStateBuilder.cpp
@@ -21,7 +21,7 @@
*/
#include "config.h"
-#include "core/platform/graphics/PathTraversalState.h"
+#include "platform/graphics/PathTraversalState.h"
#include "core/svg/SVGPathTraversalStateBuilder.h"
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGPathUtilities.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGPathUtilities.cpp
index 2d938007a0e..dcbeb40b7b3 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGPathUtilities.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGPathUtilities.cpp
@@ -21,7 +21,6 @@
#include "core/svg/SVGPathUtilities.h"
-#include "core/platform/graphics/PathTraversalState.h"
#include "core/svg/SVGPathBlender.h"
#include "core/svg/SVGPathBuilder.h"
#include "core/svg/SVGPathByteStreamBuilder.h"
@@ -32,6 +31,7 @@
#include "core/svg/SVGPathStringBuilder.h"
#include "core/svg/SVGPathStringSource.h"
#include "core/svg/SVGPathTraversalStateBuilder.h"
+#include "platform/graphics/PathTraversalState.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGPatternElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGPatternElement.cpp
index 0fdf163bbdd..110bd77a5ea 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGPatternElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGPatternElement.cpp
@@ -23,13 +23,11 @@
#include "core/svg/SVGPatternElement.h"
-#include "SVGNames.h"
#include "XLinkNames.h"
-#include "core/platform/graphics/transforms/AffineTransform.h"
#include "core/rendering/svg/RenderSVGResourcePattern.h"
#include "core/svg/PatternAttributes.h"
#include "core/svg/SVGElementInstance.h"
-#include "core/svg/SVGFitToViewBox.h"
+#include "platform/transforms/AffineTransform.h"
namespace WebCore {
@@ -62,8 +60,8 @@ BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGPatternElement)
REGISTER_PARENT_ANIMATED_PROPERTIES(SVGTests)
END_REGISTER_ANIMATED_PROPERTIES
-inline SVGPatternElement::SVGPatternElement(const QualifiedName& tagName, Document& document)
- : SVGElement(tagName, document)
+inline SVGPatternElement::SVGPatternElement(Document& document)
+ : SVGElement(SVGNames::patternTag, document)
, m_x(LengthModeWidth)
, m_y(LengthModeHeight)
, m_width(LengthModeWidth)
@@ -71,14 +69,13 @@ inline SVGPatternElement::SVGPatternElement(const QualifiedName& tagName, Docume
, m_patternUnits(SVGUnitTypes::SVG_UNIT_TYPE_OBJECTBOUNDINGBOX)
, m_patternContentUnits(SVGUnitTypes::SVG_UNIT_TYPE_USERSPACEONUSE)
{
- ASSERT(hasTagName(SVGNames::patternTag));
ScriptWrappable::init(this);
registerAnimatedPropertiesForSVGPatternElement();
}
-PassRefPtr<SVGPatternElement> SVGPatternElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGPatternElement> SVGPatternElement::create(Document& document)
{
- return adoptRef(new SVGPatternElement(tagName, document));
+ return adoptRef(new SVGPatternElement(document));
}
bool SVGPatternElement::isSupportedAttribute(const QualifiedName& attrName)
@@ -155,8 +152,9 @@ void SVGPatternElement::svgAttributeChanged(const QualifiedName& attrName)
|| attrName == SVGNames::heightAttr)
updateRelativeLengthsInformation();
- if (RenderObject* object = renderer())
- object->setNeedsLayout();
+ RenderSVGResourceContainer* renderer = toRenderSVGResourceContainer(this->renderer());
+ if (renderer)
+ renderer->invalidateCacheAndMarkForLayout();
}
void SVGPatternElement::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
@@ -193,7 +191,7 @@ void SVGPatternElement::collectPatternAttributes(PatternAttributes& attributes)
if (!attributes.hasHeight() && current->hasAttribute(SVGNames::heightAttr))
attributes.setHeight(current->heightCurrentValue());
- if (!attributes.hasViewBox() && current->hasAttribute(SVGNames::viewBoxAttr) && current->viewBoxIsValid())
+ if (!attributes.hasViewBox() && current->hasAttribute(SVGNames::viewBoxAttr) && current->viewBoxCurrentValue().isValid())
attributes.setViewBox(current->viewBoxCurrentValue());
if (!attributes.hasPreserveAspectRatio() && current->hasAttribute(SVGNames::preserveAspectRatioAttr))
@@ -219,7 +217,7 @@ void SVGPatternElement::collectPatternAttributes(PatternAttributes& attributes)
// Respect xlink:href, take attributes from referenced element
Node* refNode = SVGURIReference::targetElementFromIRIString(current->hrefCurrentValue(), document());
if (refNode && refNode->hasTagName(SVGNames::patternTag)) {
- current = static_cast<const SVGPatternElement*>(const_cast<const Node*>(refNode));
+ current = toSVGPatternElement(const_cast<const Node*>(refNode));
// Cycle detection
if (processedPatterns.contains(current)) {
@@ -231,7 +229,7 @@ void SVGPatternElement::collectPatternAttributes(PatternAttributes& attributes)
}
}
-AffineTransform SVGPatternElement::localCoordinateSpaceTransform(SVGLocatable::CTMScope) const
+AffineTransform SVGPatternElement::localCoordinateSpaceTransform(SVGElement::CTMScope) const
{
AffineTransform matrix;
patternTransformCurrentValue().concatenate(matrix);
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGPatternElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGPatternElement.h
index 2afb90df3a9..3536b4b89ea 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGPatternElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGPatternElement.h
@@ -45,14 +45,14 @@ class SVGPatternElement FINAL : public SVGElement,
public SVGExternalResourcesRequired,
public SVGFitToViewBox {
public:
- static PassRefPtr<SVGPatternElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGPatternElement> create(Document&);
void collectPatternAttributes(PatternAttributes&) const;
- virtual AffineTransform localCoordinateSpaceTransform(SVGLocatable::CTMScope) const;
+ virtual AffineTransform localCoordinateSpaceTransform(SVGElement::CTMScope) const;
private:
- SVGPatternElement(const QualifiedName&, Document&);
+ explicit SVGPatternElement(Document&);
virtual bool isValid() const { return SVGTests::isValid(); }
virtual bool needsPendingResourceHandling() const { return false; }
@@ -86,11 +86,7 @@ private:
virtual void synchronizeSystemLanguage() { SVGTests::synchronizeSystemLanguage(this); }
};
-inline SVGPatternElement* toSVGPatternElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(SVGNames::patternTag));
- return static_cast<SVGPatternElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(SVGPatternElement, hasTagName(SVGNames::patternTag));
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGPoint.h b/chromium/third_party/WebKit/Source/core/svg/SVGPoint.h
index 78f91bb8bad..c258a0f3ad8 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGPoint.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGPoint.h
@@ -26,7 +26,7 @@
#ifndef SVGPoint_h
#define SVGPoint_h
-#include "core/platform/graphics/FloatRect.h"
+#include "platform/geometry/FloatRect.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGPoint.idl b/chromium/third_party/WebKit/Source/core/svg/SVGPoint.idl
index 19606d63a57..d8945c9ed72 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGPoint.idl
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGPoint.idl
@@ -24,6 +24,6 @@ interface SVGPoint {
[StrictTypeChecking] attribute float x;
[StrictTypeChecking] attribute float y;
- [StrictTypeChecking] SVGPoint matrixTransform(SVGMatrix matrix);
+ [MeasureAs=SVGPointMatrixTransform, StrictTypeChecking] SVGPoint matrixTransform(SVGMatrix matrix);
};
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGPointList.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGPointList.cpp
index 10013e63f2f..3b7d9b91f0e 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGPointList.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGPointList.cpp
@@ -21,7 +21,7 @@
#include "config.h"
#include "core/svg/SVGPointList.h"
-#include "core/platform/graphics/FloatPoint.h"
+#include "platform/geometry/FloatPoint.h"
#include "wtf/text/StringBuilder.h"
#include "wtf/text/WTFString.h"
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGPolyElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGPolyElement.cpp
index a6eec9b2fd5..8f984b9be0f 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGPolyElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGPolyElement.cpp
@@ -22,7 +22,6 @@
#include "core/svg/SVGPolyElement.h"
-#include "SVGNames.h"
#include "core/dom/Document.h"
#include "core/rendering/svg/RenderSVGResource.h"
#include "core/svg/SVGAnimatedPointList.h"
@@ -46,6 +45,17 @@ const SVGPropertyInfo* SVGPolyElement::pointsPropertyInfo()
return s_propertyInfo;
}
+SVGPointList& SVGPolyElement::pointsCurrentValue()
+{
+ SVGAnimatedProperty* wrapper = SVGAnimatedProperty::lookupWrapper<SVGPolyElement, SVGAnimatedPointList>(this, pointsPropertyInfo());
+ if (wrapper && wrapper->isAnimating()) {
+ if (SVGListPropertyTearOff<SVGPointList>* ap = animatedPoints())
+ return ap->values();
+ }
+
+ return m_points.value;
+}
+
// Animated property definitions
DEFINE_ANIMATED_BOOLEAN(SVGPolyElement, SVGNames::externalResourcesRequiredAttr, ExternalResourcesRequired, externalResourcesRequired)
@@ -56,7 +66,7 @@ BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGPolyElement)
END_REGISTER_ANIMATED_PROPERTIES
SVGPolyElement::SVGPolyElement(const QualifiedName& tagName, Document& document)
- : SVGGraphicsElement(tagName, document)
+ : SVGGeometryElement(tagName, document)
{
registerAnimatedPropertiesForSVGPolyElement();
}
@@ -65,7 +75,6 @@ bool SVGPolyElement::isSupportedAttribute(const QualifiedName& attrName)
{
DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
if (supportedAttributes.isEmpty()) {
- SVGLangSpace::addSupportedAttributes(supportedAttributes);
SVGExternalResourcesRequired::addSupportedAttributes(supportedAttributes);
supportedAttributes.add(SVGNames::pointsAttr);
}
@@ -75,7 +84,7 @@ bool SVGPolyElement::isSupportedAttribute(const QualifiedName& attrName)
void SVGPolyElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
{
if (!isSupportedAttribute(name)) {
- SVGGraphicsElement::parseAttribute(name, value);
+ SVGGeometryElement::parseAttribute(name, value);
return;
}
@@ -91,8 +100,6 @@ void SVGPolyElement::parseAttribute(const QualifiedName& name, const AtomicStrin
return;
}
- if (SVGLangSpace::parseAttribute(name, value))
- return;
if (SVGExternalResourcesRequired::parseAttribute(name, value))
return;
@@ -102,7 +109,7 @@ void SVGPolyElement::parseAttribute(const QualifiedName& name, const AtomicStrin
void SVGPolyElement::svgAttributeChanged(const QualifiedName& attrName)
{
if (!isSupportedAttribute(attrName)) {
- SVGGraphicsElement::svgAttributeChanged(attrName);
+ SVGGeometryElement::svgAttributeChanged(attrName);
return;
}
@@ -118,7 +125,7 @@ void SVGPolyElement::svgAttributeChanged(const QualifiedName& attrName)
return;
}
- if (SVGLangSpace::isKnownAttribute(attrName) || SVGExternalResourcesRequired::isKnownAttribute(attrName)) {
+ if (SVGExternalResourcesRequired::isKnownAttribute(attrName)) {
RenderSVGResource::markForLayoutAndParentResourceInvalidation(renderer);
return;
}
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGPolyElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGPolyElement.h
index 617de152ec4..4cc460158df 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGPolyElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGPolyElement.h
@@ -24,18 +24,18 @@
#include "SVGNames.h"
#include "core/svg/SVGAnimatedBoolean.h"
#include "core/svg/SVGExternalResourcesRequired.h"
-#include "core/svg/SVGGraphicsElement.h"
+#include "core/svg/SVGGeometryElement.h"
#include "core/svg/SVGPointList.h"
namespace WebCore {
-class SVGPolyElement : public SVGGraphicsElement
+class SVGPolyElement : public SVGGeometryElement
, public SVGExternalResourcesRequired {
public:
SVGListPropertyTearOff<SVGPointList>* points();
SVGListPropertyTearOff<SVGPointList>* animatedPoints();
- SVGPointList& pointList() const { return m_points.value; }
+ SVGPointList& pointsCurrentValue();
static const SVGPropertyInfo* pointsPropertyInfo();
@@ -56,20 +56,21 @@ private:
static void synchronizePoints(SVGElement* contextElement);
static PassRefPtr<SVGAnimatedProperty> lookupOrCreatePointsWrapper(SVGElement* contextElement);
+ mutable SVGSynchronizableAnimatedProperty<SVGPointList> m_points;
+
+private:
BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGPolyElement)
DECLARE_ANIMATED_BOOLEAN(ExternalResourcesRequired, externalResourcesRequired)
END_DECLARE_ANIMATED_PROPERTIES
-
-protected:
- mutable SVGSynchronizableAnimatedProperty<SVGPointList> m_points;
};
-inline SVGPolyElement* toSVGPolyElement(SVGElement* element)
+inline bool isSVGPolyElement(const Node& node)
{
- ASSERT_WITH_SECURITY_IMPLICATION(!element || element->hasTagName(SVGNames::polygonTag) || element->hasTagName(SVGNames::polylineTag));
- return static_cast<SVGPolyElement*>(element);
+ return node.hasTagName(SVGNames::polygonTag) || node.hasTagName(SVGNames::polylineTag);
}
+DEFINE_NODE_TYPE_CASTS_WITH_FUNCTION(SVGPolyElement);
+
} // namespace WebCore
#endif
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGPolygonElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGPolygonElement.cpp
index 28175e4bb41..14d7a94ebc7 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGPolygonElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGPolygonElement.cpp
@@ -20,21 +20,19 @@
#include "config.h"
-#include "SVGNames.h"
#include "core/svg/SVGPolygonElement.h"
namespace WebCore {
-inline SVGPolygonElement::SVGPolygonElement(const QualifiedName& tagName, Document& document)
- : SVGPolyElement(tagName, document)
+inline SVGPolygonElement::SVGPolygonElement(Document& document)
+ : SVGPolyElement(SVGNames::polygonTag, document)
{
- ASSERT(hasTagName(SVGNames::polygonTag));
ScriptWrappable::init(this);
}
-PassRefPtr<SVGPolygonElement> SVGPolygonElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGPolygonElement> SVGPolygonElement::create(Document& document)
{
- return adoptRef(new SVGPolygonElement(tagName, document));
+ return adoptRef(new SVGPolygonElement(document));
}
}
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGPolygonElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGPolygonElement.h
index 0076f6495aa..89571f75749 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGPolygonElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGPolygonElement.h
@@ -28,17 +28,13 @@ namespace WebCore {
class SVGPolygonElement FINAL : public SVGPolyElement {
public:
- static PassRefPtr<SVGPolygonElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGPolygonElement> create(Document&);
private:
- SVGPolygonElement(const QualifiedName&, Document&);
+ explicit SVGPolygonElement(Document&);
};
-inline SVGPolygonElement* toSVGPolygonElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(SVGNames::polygonTag));
- return static_cast<SVGPolygonElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(SVGPolygonElement, hasTagName(SVGNames::polygonTag));
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGPolygonElement.idl b/chromium/third_party/WebKit/Source/core/svg/SVGPolygonElement.idl
index 735067bd44b..be639f1d8c7 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGPolygonElement.idl
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGPolygonElement.idl
@@ -23,7 +23,7 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-interface SVGPolygonElement : SVGGraphicsElement {
+interface SVGPolygonElement : SVGGeometryElement {
readonly attribute SVGPointList points;
readonly attribute SVGPointList animatedPoints;
};
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGPolylineElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGPolylineElement.cpp
index 15b878d76a6..d3c3323f655 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGPolylineElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGPolylineElement.cpp
@@ -20,21 +20,19 @@
#include "config.h"
-#include "SVGNames.h"
#include "core/svg/SVGPolylineElement.h"
namespace WebCore {
-inline SVGPolylineElement::SVGPolylineElement(const QualifiedName& tagName, Document& document)
- : SVGPolyElement(tagName, document)
+inline SVGPolylineElement::SVGPolylineElement(Document& document)
+ : SVGPolyElement(SVGNames::polylineTag, document)
{
- ASSERT(hasTagName(SVGNames::polylineTag));
ScriptWrappable::init(this);
}
-PassRefPtr<SVGPolylineElement> SVGPolylineElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGPolylineElement> SVGPolylineElement::create(Document& document)
{
- return adoptRef(new SVGPolylineElement(tagName, document));
+ return adoptRef(new SVGPolylineElement(document));
}
}
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGPolylineElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGPolylineElement.h
index fe1a5c078ac..428314366de 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGPolylineElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGPolylineElement.h
@@ -28,17 +28,13 @@ namespace WebCore {
class SVGPolylineElement FINAL : public SVGPolyElement {
public:
- static PassRefPtr<SVGPolylineElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGPolylineElement> create(Document&);
private:
- SVGPolylineElement(const QualifiedName&, Document&);
+ explicit SVGPolylineElement(Document&);
};
-inline SVGPolylineElement* toSVGPolylineElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(SVGNames::polylineTag));
- return static_cast<SVGPolylineElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(SVGPolylineElement, hasTagName(SVGNames::polylineTag));
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGPolylineElement.idl b/chromium/third_party/WebKit/Source/core/svg/SVGPolylineElement.idl
index a7eefed045f..1fd499b8d96 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGPolylineElement.idl
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGPolylineElement.idl
@@ -23,7 +23,7 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-interface SVGPolylineElement : SVGGraphicsElement {
+interface SVGPolylineElement : SVGGeometryElement {
readonly attribute SVGPointList points;
readonly attribute SVGPointList animatedPoints;
};
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGPreserveAspectRatio.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGPreserveAspectRatio.cpp
index 5e425e323d6..5e9de721a00 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGPreserveAspectRatio.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGPreserveAspectRatio.cpp
@@ -24,9 +24,9 @@
#include "bindings/v8/ExceptionState.h"
#include "core/dom/ExceptionCode.h"
-#include "core/platform/graphics/FloatRect.h"
-#include "core/platform/graphics/transforms/AffineTransform.h"
#include "core/svg/SVGParserUtilities.h"
+#include "platform/geometry/FloatRect.h"
+#include "platform/transforms/AffineTransform.h"
#include "wtf/text/WTFString.h"
namespace WebCore {
@@ -37,20 +37,20 @@ SVGPreserveAspectRatio::SVGPreserveAspectRatio()
{
}
-void SVGPreserveAspectRatio::setAlign(unsigned short align, ExceptionState& es)
+void SVGPreserveAspectRatio::setAlign(unsigned short align, ExceptionState& exceptionState)
{
if (align == SVG_PRESERVEASPECTRATIO_UNKNOWN || align > SVG_PRESERVEASPECTRATIO_XMAXYMAX) {
- es.throwDOMException(NotSupportedError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
return;
}
m_align = static_cast<SVGPreserveAspectRatioType>(align);
}
-void SVGPreserveAspectRatio::setMeetOrSlice(unsigned short meetOrSlice, ExceptionState& es)
+void SVGPreserveAspectRatio::setMeetOrSlice(unsigned short meetOrSlice, ExceptionState& exceptionState)
{
if (meetOrSlice == SVG_MEETORSLICE_UNKNOWN || meetOrSlice > SVG_MEETORSLICE_SLICE) {
- es.throwDOMException(NotSupportedError);
+ exceptionState.throwUninformativeAndGenericDOMException(NotSupportedError);
return;
}
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGPreserveAspectRatio.idl b/chromium/third_party/WebKit/Source/core/svg/SVGPreserveAspectRatio.idl
index 178f1a048d6..477369ee6d9 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGPreserveAspectRatio.idl
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGPreserveAspectRatio.idl
@@ -42,8 +42,8 @@ interface SVGPreserveAspectRatio {
const unsigned short SVG_MEETORSLICE_MEET = 1;
const unsigned short SVG_MEETORSLICE_SLICE = 2;
- [StrictTypeChecking, SetterRaisesException] attribute unsigned short align;
+ [StrictTypeChecking, RaisesException=Setter] attribute unsigned short align;
- [StrictTypeChecking, SetterRaisesException] attribute unsigned short meetOrSlice;
+ [StrictTypeChecking, RaisesException=Setter] attribute unsigned short meetOrSlice;
};
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGRadialGradientElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGRadialGradientElement.cpp
index cb286b150fe..af45582ec58 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGRadialGradientElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGRadialGradientElement.cpp
@@ -25,7 +25,6 @@
#include "core/svg/SVGRadialGradientElement.h"
-#include "SVGNames.h"
#include "core/rendering/svg/RenderSVGResourceRadialGradient.h"
#include "core/svg/RadialGradientAttributes.h"
#include "core/svg/SVGElementInstance.h"
@@ -51,8 +50,8 @@ BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGRadialGradientElement)
REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGradientElement)
END_REGISTER_ANIMATED_PROPERTIES
-inline SVGRadialGradientElement::SVGRadialGradientElement(const QualifiedName& tagName, Document& document)
- : SVGGradientElement(tagName, document)
+inline SVGRadialGradientElement::SVGRadialGradientElement(Document& document)
+ : SVGGradientElement(SVGNames::radialGradientTag, document)
, m_cx(LengthModeWidth, "50%")
, m_cy(LengthModeHeight, "50%")
, m_r(LengthModeOther, "50%")
@@ -61,14 +60,13 @@ inline SVGRadialGradientElement::SVGRadialGradientElement(const QualifiedName& t
, m_fr(LengthModeOther, "0%")
{
// Spec: If the cx/cy/r/fr attribute is not specified, the effect is as if a value of "50%" were specified.
- ASSERT(hasTagName(SVGNames::radialGradientTag));
ScriptWrappable::init(this);
registerAnimatedPropertiesForSVGRadialGradientElement();
}
-PassRefPtr<SVGRadialGradientElement> SVGRadialGradientElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGRadialGradientElement> SVGRadialGradientElement::create(Document& document)
{
- return adoptRef(new SVGRadialGradientElement(tagName, document));
+ return adoptRef(new SVGRadialGradientElement(document));
}
bool SVGRadialGradientElement::isSupportedAttribute(const QualifiedName& attrName)
@@ -120,8 +118,9 @@ void SVGRadialGradientElement::svgAttributeChanged(const QualifiedName& attrName
updateRelativeLengthsInformation();
- if (RenderObject* object = renderer())
- object->setNeedsLayout();
+ RenderSVGResourceContainer* renderer = toRenderSVGResourceContainer(this->renderer());
+ if (renderer)
+ renderer->invalidateCacheAndMarkForLayout();
}
RenderObject* SVGRadialGradientElement::createRenderer(RenderStyle*)
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGRadialGradientElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGRadialGradientElement.h
index 4b7c376a3ac..e448d2077c8 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGRadialGradientElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGRadialGradientElement.h
@@ -31,12 +31,12 @@ struct RadialGradientAttributes;
class SVGRadialGradientElement FINAL : public SVGGradientElement {
public:
- static PassRefPtr<SVGRadialGradientElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGRadialGradientElement> create(Document&);
bool collectGradientAttributes(RadialGradientAttributes&);
private:
- SVGRadialGradientElement(const QualifiedName&, Document&);
+ explicit SVGRadialGradientElement(Document&);
bool isSupportedAttribute(const QualifiedName&);
virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
@@ -56,11 +56,7 @@ private:
END_DECLARE_ANIMATED_PROPERTIES
};
-inline SVGRadialGradientElement* toSVGRadialGradientElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(SVGNames::radialGradientTag));
- return static_cast<SVGRadialGradientElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(SVGRadialGradientElement, hasTagName(SVGNames::radialGradientTag));
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGRect.h b/chromium/third_party/WebKit/Source/core/svg/SVGRect.h
index a5c22121b96..775c1966012 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGRect.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGRect.h
@@ -20,17 +20,42 @@
#ifndef SVGRect_h
#define SVGRect_h
-#include "core/platform/graphics/FloatRect.h"
#include "core/svg/properties/SVGPropertyTraits.h"
+#include "platform/geometry/FloatRect.h"
#include "wtf/text/StringBuilder.h"
namespace WebCore {
-typedef FloatRect SVGRect;
+class SVGRect : public FloatRect {
+public:
+ struct InvalidSVGRectTag { };
+
+ SVGRect()
+ : m_isValid(true) { }
+ SVGRect(InvalidSVGRectTag)
+ : m_isValid(false) { }
+ SVGRect(const FloatRect& rect)
+ : FloatRect(rect), m_isValid(true) { }
+ SVGRect(const FloatPoint& location, const FloatSize& size)
+ : FloatRect(location, size), m_isValid(true) { }
+ SVGRect(float x, float y, float width, float height)
+ : FloatRect(x, y, width, height), m_isValid(true) { }
+ SVGRect(const IntRect& intRect)
+ : FloatRect(intRect), m_isValid(true) { }
+ SVGRect(const LayoutRect& layoutRect)
+ : FloatRect(layoutRect), m_isValid(true) { }
+ SVGRect(const SkRect& skRect)
+ : FloatRect(skRect), m_isValid(true) { }
+
+ bool isValid() const { return m_isValid; }
+
+private:
+ bool m_isValid;
+};
template<>
struct SVGPropertyTraits<SVGRect> {
- static SVGRect initialValue() { return SVGRect(); }
+ static SVGRect initialValue() { return SVGRect(SVGRect::InvalidSVGRectTag()); }
static String toString(const SVGRect& type)
{
StringBuilder builder;
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGRectElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGRectElement.cpp
index 2f0e12c0b97..61c539edf11 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGRectElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGRectElement.cpp
@@ -22,7 +22,6 @@
#include "core/svg/SVGRectElement.h"
-#include "SVGNames.h"
#include "core/rendering/svg/RenderSVGRect.h"
#include "core/rendering/svg/RenderSVGResource.h"
#include "core/svg/SVGElementInstance.h"
@@ -50,8 +49,8 @@ BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGRectElement)
REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
END_REGISTER_ANIMATED_PROPERTIES
-inline SVGRectElement::SVGRectElement(const QualifiedName& tagName, Document& document)
- : SVGGraphicsElement(tagName, document)
+inline SVGRectElement::SVGRectElement(Document& document)
+ : SVGGeometryElement(SVGNames::rectTag, document)
, m_x(LengthModeWidth)
, m_y(LengthModeHeight)
, m_width(LengthModeWidth)
@@ -59,21 +58,19 @@ inline SVGRectElement::SVGRectElement(const QualifiedName& tagName, Document& do
, m_rx(LengthModeWidth)
, m_ry(LengthModeHeight)
{
- ASSERT(hasTagName(SVGNames::rectTag));
ScriptWrappable::init(this);
registerAnimatedPropertiesForSVGRectElement();
}
-PassRefPtr<SVGRectElement> SVGRectElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGRectElement> SVGRectElement::create(Document& document)
{
- return adoptRef(new SVGRectElement(tagName, document));
+ return adoptRef(new SVGRectElement(document));
}
bool SVGRectElement::isSupportedAttribute(const QualifiedName& attrName)
{
DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
if (supportedAttributes.isEmpty()) {
- SVGLangSpace::addSupportedAttributes(supportedAttributes);
SVGExternalResourcesRequired::addSupportedAttributes(supportedAttributes);
supportedAttributes.add(SVGNames::xAttr);
supportedAttributes.add(SVGNames::yAttr);
@@ -90,7 +87,7 @@ void SVGRectElement::parseAttribute(const QualifiedName& name, const AtomicStrin
SVGParsingError parseError = NoError;
if (!isSupportedAttribute(name))
- SVGGraphicsElement::parseAttribute(name, value);
+ SVGGeometryElement::parseAttribute(name, value);
else if (name == SVGNames::xAttr)
setXBaseValue(SVGLength::construct(LengthModeWidth, value, parseError));
else if (name == SVGNames::yAttr)
@@ -103,8 +100,7 @@ void SVGRectElement::parseAttribute(const QualifiedName& name, const AtomicStrin
setWidthBaseValue(SVGLength::construct(LengthModeWidth, value, parseError, ForbidNegativeLengths));
else if (name == SVGNames::heightAttr)
setHeightBaseValue(SVGLength::construct(LengthModeHeight, value, parseError, ForbidNegativeLengths));
- else if (SVGLangSpace::parseAttribute(name, value)
- || SVGExternalResourcesRequired::parseAttribute(name, value)) {
+ else if (SVGExternalResourcesRequired::parseAttribute(name, value)) {
} else
ASSERT_NOT_REACHED();
@@ -114,7 +110,7 @@ void SVGRectElement::parseAttribute(const QualifiedName& name, const AtomicStrin
void SVGRectElement::svgAttributeChanged(const QualifiedName& attrName)
{
if (!isSupportedAttribute(attrName)) {
- SVGGraphicsElement::svgAttributeChanged(attrName);
+ SVGGeometryElement::svgAttributeChanged(attrName);
return;
}
@@ -140,7 +136,7 @@ void SVGRectElement::svgAttributeChanged(const QualifiedName& attrName)
return;
}
- if (SVGLangSpace::isKnownAttribute(attrName) || SVGExternalResourcesRequired::isKnownAttribute(attrName)) {
+ if (SVGExternalResourcesRequired::isKnownAttribute(attrName)) {
RenderSVGResource::markForLayoutAndParentResourceInvalidation(renderer);
return;
}
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGRectElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGRectElement.h
index 2c631b81ac7..1a500884f4e 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGRectElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGRectElement.h
@@ -25,17 +25,17 @@
#include "core/svg/SVGAnimatedBoolean.h"
#include "core/svg/SVGAnimatedLength.h"
#include "core/svg/SVGExternalResourcesRequired.h"
-#include "core/svg/SVGGraphicsElement.h"
+#include "core/svg/SVGGeometryElement.h"
namespace WebCore {
-class SVGRectElement FINAL : public SVGGraphicsElement,
+class SVGRectElement FINAL : public SVGGeometryElement,
public SVGExternalResourcesRequired {
public:
- static PassRefPtr<SVGRectElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGRectElement> create(Document&);
private:
- SVGRectElement(const QualifiedName&, Document&);
+ explicit SVGRectElement(Document&);
virtual bool isValid() const { return SVGTests::isValid(); }
virtual bool supportsFocus() const OVERRIDE { return hasFocusEventListeners(); }
@@ -59,11 +59,7 @@ private:
END_DECLARE_ANIMATED_PROPERTIES
};
-inline SVGRectElement* toSVGRectElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(SVGNames::rectTag));
- return static_cast<SVGRectElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(SVGRectElement, hasTagName(SVGNames::rectTag));
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGRectElement.idl b/chromium/third_party/WebKit/Source/core/svg/SVGRectElement.idl
index 42fe0633946..a3cf85e5d7a 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGRectElement.idl
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGRectElement.idl
@@ -24,7 +24,7 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-interface SVGRectElement : SVGGraphicsElement {
+interface SVGRectElement : SVGGeometryElement {
readonly attribute SVGAnimatedLength x;
readonly attribute SVGAnimatedLength y;
readonly attribute SVGAnimatedLength width;
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGRenderingIntent.idl b/chromium/third_party/WebKit/Source/core/svg/SVGRenderingIntent.idl
index 5c081536e13..4092cda304f 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGRenderingIntent.idl
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGRenderingIntent.idl
@@ -23,9 +23,7 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-[
- DoNotGenerateToV8
-] interface SVGRenderingIntent {
+interface SVGRenderingIntent {
// Rendering Intent Types
const unsigned short RENDERING_INTENT_UNKNOWN = 0;
const unsigned short RENDERING_INTENT_AUTO = 1;
@@ -34,4 +32,3 @@
const unsigned short RENDERING_INTENT_SATURATION = 4;
const unsigned short RENDERING_INTENT_ABSOLUTE_COLORIMETRIC = 5;
};
-
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGSVGElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGSVGElement.cpp
index f15b610e5c2..f53db048703 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGSVGElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGSVGElement.cpp
@@ -29,18 +29,15 @@
#include "core/css/CSSHelper.h"
#include "core/dom/Document.h"
#include "core/dom/ElementTraversal.h"
-#include "core/dom/EventListener.h"
-#include "core/dom/EventNames.h"
#include "core/dom/NodeTraversal.h"
#include "core/dom/StaticNodeList.h"
#include "core/editing/FrameSelection.h"
-#include "core/page/Frame.h"
+#include "core/events/EventListener.h"
+#include "core/events/ThreadLocalEventNames.h"
+#include "core/frame/Frame.h"
#include "core/page/FrameTree.h"
-#include "core/page/FrameView.h"
-#include "core/page/UseCounter.h"
-#include "core/platform/FloatConversion.h"
-#include "core/platform/graphics/FloatRect.h"
-#include "core/platform/graphics/transforms/AffineTransform.h"
+#include "core/frame/FrameView.h"
+#include "core/frame/UseCounter.h"
#include "core/rendering/RenderObject.h"
#include "core/rendering/RenderPart.h"
#include "core/rendering/svg/RenderSVGModelObject.h"
@@ -49,13 +46,16 @@
#include "core/rendering/svg/RenderSVGViewportContainer.h"
#include "core/svg/SVGAngle.h"
#include "core/svg/SVGElementInstance.h"
-#include "core/svg/SVGFitToViewBox.h"
#include "core/svg/SVGPreserveAspectRatio.h"
#include "core/svg/SVGTransform.h"
#include "core/svg/SVGTransformList.h"
#include "core/svg/SVGViewElement.h"
#include "core/svg/SVGViewSpec.h"
#include "core/svg/animation/SMILTimeContainer.h"
+#include "platform/FloatConversion.h"
+#include "platform/LengthFunctions.h"
+#include "platform/geometry/FloatRect.h"
+#include "platform/transforms/AffineTransform.h"
#include "wtf/StdLibExtras.h"
namespace WebCore {
@@ -80,8 +80,8 @@ BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGSVGElement)
REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
END_REGISTER_ANIMATED_PROPERTIES
-inline SVGSVGElement::SVGSVGElement(const QualifiedName& tagName, Document& doc)
- : SVGGraphicsElement(tagName, doc)
+inline SVGSVGElement::SVGSVGElement(Document& doc)
+ : SVGGraphicsElement(SVGNames::svgTag, doc)
, m_x(LengthModeWidth)
, m_y(LengthModeHeight)
, m_width(LengthModeWidth, "100%")
@@ -89,26 +89,26 @@ inline SVGSVGElement::SVGSVGElement(const QualifiedName& tagName, Document& doc)
, m_useCurrentView(false)
, m_zoomAndPan(SVGZoomAndPanMagnify)
, m_timeContainer(SMILTimeContainer::create(this))
+ , m_weakFactory(this)
{
- ASSERT(hasTagName(SVGNames::svgTag));
ScriptWrappable::init(this);
registerAnimatedPropertiesForSVGSVGElement();
- UseCounter::count(&doc, UseCounter::SVGSVGElement);
+ UseCounter::count(doc, UseCounter::SVGSVGElement);
}
-PassRefPtr<SVGSVGElement> SVGSVGElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGSVGElement> SVGSVGElement::create(Document& document)
{
- return adoptRef(new SVGSVGElement(tagName, document));
+ return adoptRef(new SVGSVGElement(document));
}
SVGSVGElement::~SVGSVGElement()
{
- if (m_viewSpec)
- m_viewSpec->resetContextElement();
// There are cases where removedFromDocument() is not called.
// see ContainerNode::removeAllChildren, called by its destructor.
document().accessSVGExtensions()->removeTimeContainer(this);
+
+ ASSERT(inDocument() || !accessDocumentSVGExtensions()->isSVGRootWithRelativeLengthDescendents(this));
}
const AtomicString& SVGSVGElement::contentScriptType() const
@@ -144,14 +144,12 @@ SVGRect SVGSVGElement::viewport() const
float SVGSVGElement::pixelUnitToMillimeterX() const
{
- // 2.54 / cssPixelsPerInch gives CM.
- return (2.54f / cssPixelsPerInch) * 10.0f;
+ return 1 / cssPixelsPerMillimeter;
}
float SVGSVGElement::pixelUnitToMillimeterY() const
{
- // 2.54 / cssPixelsPerInch gives CM.
- return (2.54f / cssPixelsPerInch) * 10.0f;
+ return 1 / cssPixelsPerMillimeter;
}
float SVGSVGElement::screenPixelToMillimeterX() const
@@ -167,7 +165,7 @@ float SVGSVGElement::screenPixelToMillimeterY() const
SVGViewSpec* SVGSVGElement::currentView()
{
if (!m_viewSpec)
- m_viewSpec = SVGViewSpec::create(this);
+ m_viewSpec = SVGViewSpec::create(m_weakFactory.createWeakPtr());
return m_viewSpec.get();
}
@@ -180,13 +178,12 @@ float SVGSVGElement::currentScale() const
if (!frame)
return 1;
- FrameTree* frameTree = frame->tree();
- ASSERT(frameTree);
+ const FrameTree& frameTree = frame->tree();
// The behaviour of currentScale() is undefined, when we're dealing with non-standalone SVG documents.
// If the svg is embedded, the scaling is handled by the host renderer, so when asking from inside
// the SVG document, a scale value of 1 seems reasonable, as it doesn't know anything about the parent scale.
- return frameTree->parent() ? 1 : frame->pageZoomFactor();
+ return frameTree.parent() ? 1 : frame->pageZoomFactor();
}
void SVGSVGElement::setCurrentScale(float scale)
@@ -198,13 +195,12 @@ void SVGSVGElement::setCurrentScale(float scale)
if (!frame)
return;
- FrameTree* frameTree = frame->tree();
- ASSERT(frameTree);
+ const FrameTree& frameTree = frame->tree();
// The behaviour of setCurrentScale() is undefined, when we're dealing with non-standalone SVG documents.
// We choose the ignore this call, it's pretty useless to support calling setCurrentScale() from within
// an embedded SVG document, for the same reasons as in currentScale() - needs resolution by SVG WG.
- if (frameTree->parent())
+ if (frameTree.parent())
return;
frame->setPageZoomFactor(scale);
@@ -221,7 +217,7 @@ void SVGSVGElement::updateCurrentTranslate()
if (RenderObject* object = renderer())
object->setNeedsLayout();
- if (parentNode() == &document() && document().renderer())
+ if (parentNode() == document() && document().renderer())
document().renderer()->repaint();
}
@@ -234,13 +230,13 @@ void SVGSVGElement::parseAttribute(const QualifiedName& name, const AtomicString
// Only handle events if we're the outermost <svg> element
if (name == HTMLNames::onunloadAttr)
- document().setWindowAttributeEventListener(eventNames().unloadEvent, createAttributeEventListener(document().frame(), name, value));
+ document().setWindowAttributeEventListener(EventTypeNames::unload, createAttributeEventListener(document().frame(), name, value));
else if (name == HTMLNames::onresizeAttr)
- document().setWindowAttributeEventListener(eventNames().resizeEvent, createAttributeEventListener(document().frame(), name, value));
+ document().setWindowAttributeEventListener(EventTypeNames::resize, createAttributeEventListener(document().frame(), name, value));
else if (name == HTMLNames::onscrollAttr)
- document().setWindowAttributeEventListener(eventNames().scrollEvent, createAttributeEventListener(document().frame(), name, value));
+ document().setWindowAttributeEventListener(EventTypeNames::scroll, createAttributeEventListener(document().frame(), name, value));
else if (name == SVGNames::onzoomAttr)
- document().setWindowAttributeEventListener(eventNames().zoomEvent, createAttributeEventListener(document().frame(), name, value));
+ document().setWindowAttributeEventListener(EventTypeNames::zoom, createAttributeEventListener(document().frame(), name, value));
else
setListener = false;
@@ -249,9 +245,9 @@ void SVGSVGElement::parseAttribute(const QualifiedName& name, const AtomicString
}
if (name == HTMLNames::onabortAttr)
- document().setWindowAttributeEventListener(eventNames().abortEvent, createAttributeEventListener(document().frame(), name, value));
+ document().setWindowAttributeEventListener(EventTypeNames::abort, createAttributeEventListener(document().frame(), name, value));
else if (name == HTMLNames::onerrorAttr)
- document().setWindowAttributeEventListener(eventNames().errorEvent, createAttributeEventListener(document().frame(), name, value));
+ document().setWindowAttributeEventListener(EventTypeNames::error, createAttributeEventListener(document().frame(), name, value));
else if (name == SVGNames::xAttr)
setXBaseValue(SVGLength::construct(LengthModeWidth, value, parseError));
else if (name == SVGNames::yAttr)
@@ -260,8 +256,7 @@ void SVGSVGElement::parseAttribute(const QualifiedName& name, const AtomicString
setWidthBaseValue(SVGLength::construct(LengthModeWidth, value, parseError, ForbidNegativeLengths));
else if (name == SVGNames::heightAttr)
setHeightBaseValue(SVGLength::construct(LengthModeHeight, value, parseError, ForbidNegativeLengths));
- else if (SVGLangSpace::parseAttribute(name, value)
- || SVGExternalResourcesRequired::parseAttribute(name, value)
+ else if (SVGExternalResourcesRequired::parseAttribute(name, value)
|| SVGFitToViewBox::parseAttribute(this, name, value)
|| SVGZoomAndPan::parseAttribute(this, name, value)) {
} else
@@ -300,7 +295,6 @@ void SVGSVGElement::svgAttributeChanged(const QualifiedName& attrName)
SVGElementInstance::InvalidationGuard invalidationGuard(this);
if (updateRelativeLengthsOrViewBox
- || SVGLangSpace::isKnownAttribute(attrName)
|| SVGExternalResourcesRequired::isKnownAttribute(attrName)
|| SVGZoomAndPan::isKnownAttribute(attrName)) {
if (renderer())
@@ -335,7 +329,7 @@ void SVGSVGElement::forceRedraw()
PassRefPtr<NodeList> SVGSVGElement::collectIntersectionOrEnclosureList(const SVGRect& rect, SVGElement* referenceElement, CollectIntersectionOrEnclosure collect) const
{
Vector<RefPtr<Node> > nodes;
- Element* element = ElementTraversal::next(referenceElement ? referenceElement : this);
+ Element* element = ElementTraversal::next(*(referenceElement ? referenceElement : this));
while (element) {
if (element->isSVGElement()) {
SVGElement* svgElement = toSVGElement(element);
@@ -348,7 +342,7 @@ PassRefPtr<NodeList> SVGSVGElement::collectIntersectionOrEnclosureList(const SVG
}
}
- element = ElementTraversal::next(element, referenceElement ? referenceElement : this);
+ element = ElementTraversal::next(*element, referenceElement ? referenceElement : this);
}
return StaticNodeList::adopt(nodes);
}
@@ -423,7 +417,7 @@ SVGTransform SVGSVGElement::createSVGTransformFromMatrix(const SVGMatrix& matrix
return SVGTransform(static_cast<const AffineTransform&>(matrix));
}
-AffineTransform SVGSVGElement::localCoordinateSpaceTransform(SVGLocatable::CTMScope mode) const
+AffineTransform SVGSVGElement::localCoordinateSpaceTransform(SVGElement::CTMScope mode) const
{
AffineTransform viewBoxTransform;
if (!hasEmptyViewBox()) {
@@ -435,7 +429,7 @@ AffineTransform SVGSVGElement::localCoordinateSpaceTransform(SVGLocatable::CTMSc
if (!isOutermostSVGSVGElement()) {
SVGLengthContext lengthContext(this);
transform.translate(xCurrentValue().value(lengthContext), yCurrentValue().value(lengthContext));
- } else if (mode == SVGLocatable::ScreenScope) {
+ } else if (mode == SVGElement::ScreenScope) {
if (RenderObject* renderer = this->renderer()) {
FloatPoint location;
float zoomFactor = 1;
@@ -505,8 +499,12 @@ Node::InsertionNotificationRequest SVGSVGElement::insertedInto(ContainerNode* ro
void SVGSVGElement::removedFrom(ContainerNode* rootParent)
{
- if (rootParent->inDocument())
- document().accessSVGExtensions()->removeTimeContainer(this);
+ if (rootParent->inDocument()) {
+ SVGDocumentExtensions* svgExtensions = document().accessSVGExtensions();
+ svgExtensions->removeTimeContainer(this);
+ svgExtensions->removeSVGRootWithRelativeLengthDescendents(this);
+ }
+
SVGGraphicsElement::removedFrom(rootParent);
}
@@ -569,7 +567,7 @@ SVGRect SVGSVGElement::currentViewBoxRect() const
// If no viewBox is specified but non-relative width/height values, then we
// should always synthesize a viewBox if we're embedded through a SVGImage.
- return SVGRect(FloatPoint(), FloatSize(floatValueForLength(intrinsicWidth, 0), floatValueForLength(intrinsicHeight, 0)));
+ return SVGRect(FloatPoint(), FloatSize(floatValueForLength(intrinsicWidth, 0, 0), floatValueForLength(intrinsicHeight, 0, 0)));
}
FloatSize SVGSVGElement::currentViewportSize() const
@@ -724,9 +722,7 @@ void SVGSVGElement::setupInitialView(const String& fragmentIdentifier, Element*
if (!viewElement)
return;
- SVGElement* element = SVGLocatable::nearestViewportElement(viewElement);
- if (element->hasTagName(SVGNames::svgTag)) {
- SVGSVGElement* svg = toSVGSVGElement(element);
+ if (SVGSVGElement* svg = viewElement->ownerSVGElement()) {
svg->inheritViewAttributes(viewElement);
if (RenderObject* renderer = svg->renderer())
@@ -769,7 +765,7 @@ Element* SVGSVGElement::getElementById(const AtomicString& id) const
// Fall back to traversing our subtree. Duplicate ids are allowed, the first found will
// be returned.
- for (Node* node = firstChild(); node; node = NodeTraversal::next(node, this)) {
+ for (Node* node = firstChild(); node; node = NodeTraversal::next(*node, this)) {
if (!node->isElementNode())
continue;
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGSVGElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGSVGElement.h
index 54b39de7ead..65f8c69c30e 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGSVGElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGSVGElement.h
@@ -29,6 +29,7 @@
#include "core/svg/SVGFitToViewBox.h"
#include "core/svg/SVGGraphicsElement.h"
#include "core/svg/SVGZoomAndPan.h"
+#include "wtf/WeakPtr.h"
namespace WebCore {
@@ -44,7 +45,7 @@ class SVGSVGElement FINAL : public SVGGraphicsElement,
public SVGFitToViewBox,
public SVGZoomAndPan {
public:
- static PassRefPtr<SVGSVGElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGSVGElement> create(Document&);
using SVGGraphicsElement::ref;
using SVGGraphicsElement::deref;
@@ -130,10 +131,10 @@ public:
SVGZoomAndPanType zoomAndPan() const { return m_zoomAndPan; }
void setZoomAndPan(unsigned short zoomAndPan) { m_zoomAndPan = SVGZoomAndPan::parseFromNumber(zoomAndPan); }
- bool hasEmptyViewBox() const { return viewBoxIsValid() && viewBoxCurrentValue().isEmpty(); }
+ bool hasEmptyViewBox() const { return viewBoxCurrentValue().isValid() && viewBoxCurrentValue().isEmpty(); }
private:
- SVGSVGElement(const QualifiedName&, Document&);
+ explicit SVGSVGElement(Document&);
virtual ~SVGSVGElement();
virtual bool isSVGSVGElement() const OVERRIDE { return true; }
@@ -169,26 +170,22 @@ private:
DECLARE_ANIMATED_PRESERVEASPECTRATIO(PreserveAspectRatio, preserveAspectRatio)
END_DECLARE_ANIMATED_PROPERTIES
- virtual AffineTransform localCoordinateSpaceTransform(SVGLocatable::CTMScope) const;
+ virtual AffineTransform localCoordinateSpaceTransform(SVGElement::CTMScope) const;
bool m_useCurrentView;
SVGZoomAndPanType m_zoomAndPan;
RefPtr<SMILTimeContainer> m_timeContainer;
SVGPoint m_translation;
RefPtr<SVGViewSpec> m_viewSpec;
+ WeakPtrFactory<SVGSVGElement> m_weakFactory;
};
-inline SVGSVGElement* toSVGSVGElement(Node* node)
+inline bool isSVGSVGElement(const Node& node)
{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || toSVGElement(node)->isSVGSVGElement());
- return static_cast<SVGSVGElement*>(node);
+ return node.isSVGElement() && toSVGElement(node).isSVGSVGElement();
}
-inline const SVGSVGElement* toSVGSVGElement(const Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || toSVGElement(node)->isSVGSVGElement());
- return static_cast<const SVGSVGElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS_WITH_FUNCTION(SVGSVGElement);
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGScriptElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGScriptElement.cpp
index c7d848288e0..9a7040f1093 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGScriptElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGScriptElement.cpp
@@ -27,8 +27,8 @@
#include "bindings/v8/ScriptEventListener.h"
#include "core/dom/Attribute.h"
#include "core/dom/Document.h"
-#include "core/dom/EventNames.h"
#include "core/dom/ScriptLoader.h"
+#include "core/events/ThreadLocalEventNames.h"
#include "core/svg/SVGElementInstance.h"
#include "core/svg/properties/SVGAnimatedStaticPropertyTearOff.h"
@@ -43,19 +43,18 @@ BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGScriptElement)
REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired)
END_REGISTER_ANIMATED_PROPERTIES
-inline SVGScriptElement::SVGScriptElement(const QualifiedName& tagName, Document& document, bool wasInsertedByParser, bool alreadyStarted)
- : SVGElement(tagName, document)
+inline SVGScriptElement::SVGScriptElement(Document& document, bool wasInsertedByParser, bool alreadyStarted)
+ : SVGElement(SVGNames::scriptTag, document)
, m_svgLoadEventTimer(this, &SVGElement::svgLoadEventTimerFired)
, m_loader(ScriptLoader::create(this, wasInsertedByParser, alreadyStarted))
{
- ASSERT(hasTagName(SVGNames::scriptTag));
ScriptWrappable::init(this);
registerAnimatedPropertiesForSVGScriptElement();
}
-PassRefPtr<SVGScriptElement> SVGScriptElement::create(const QualifiedName& tagName, Document& document, bool insertedByParser)
+PassRefPtr<SVGScriptElement> SVGScriptElement::create(Document& document, bool insertedByParser)
{
- return adoptRef(new SVGScriptElement(tagName, document, insertedByParser, false));
+ return adoptRef(new SVGScriptElement(document, insertedByParser, false));
}
bool SVGScriptElement::isSupportedAttribute(const QualifiedName& attrName)
@@ -83,7 +82,7 @@ void SVGScriptElement::parseAttribute(const QualifiedName& name, const AtomicStr
}
if (name == HTMLNames::onerrorAttr) {
- setAttributeEventListener(eventNames().errorEvent, createAttributeEventListener(this, name, value));
+ setAttributeEventListener(EventTypeNames::error, createAttributeEventListener(this, name, value));
return;
}
@@ -211,7 +210,7 @@ bool SVGScriptElement::hasSourceAttribute() const
PassRefPtr<Element> SVGScriptElement::cloneElementWithoutAttributesAndChildren()
{
- return adoptRef(new SVGScriptElement(tagQName(), document(), false, m_loader->alreadyStarted()));
+ return adoptRef(new SVGScriptElement(document(), false, m_loader->alreadyStarted()));
}
void SVGScriptElement::setHaveFiredLoadEvent(bool haveFiredLoadEvent)
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGScriptElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGScriptElement.h
index 10c5d4569a4..ec59d85ad68 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGScriptElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGScriptElement.h
@@ -39,7 +39,7 @@ class SVGScriptElement FINAL
, public SVGExternalResourcesRequired
, public ScriptLoaderClient {
public:
- static PassRefPtr<SVGScriptElement> create(const QualifiedName&, Document&, bool wasInsertedByParser);
+ static PassRefPtr<SVGScriptElement> create(Document&, bool wasInsertedByParser);
String type() const;
void setType(const String&);
@@ -47,7 +47,7 @@ public:
ScriptLoader* loader() const { return m_loader.get(); }
private:
- SVGScriptElement(const QualifiedName&, Document&, bool wasInsertedByParser, bool alreadyStarted);
+ SVGScriptElement(Document&, bool wasInsertedByParser, bool alreadyStarted);
bool isSupportedAttribute(const QualifiedName&);
virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
@@ -94,11 +94,7 @@ private:
OwnPtr<ScriptLoader> m_loader;
};
-inline SVGScriptElement* toSVGScriptElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(SVGNames::scriptTag));
- return static_cast<SVGScriptElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(SVGScriptElement, hasTagName(SVGNames::scriptTag));
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGSetElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGSetElement.cpp
index 934ed567571..da8334b751c 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGSetElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGSetElement.cpp
@@ -24,17 +24,16 @@
namespace WebCore {
-inline SVGSetElement::SVGSetElement(const QualifiedName& tagName, Document& document)
- : SVGAnimateElement(tagName, document)
+inline SVGSetElement::SVGSetElement(Document& document)
+ : SVGAnimateElement(SVGNames::setTag, document)
{
setAnimationMode(ToAnimation);
- ASSERT(hasTagName(SVGNames::setTag));
ScriptWrappable::init(this);
}
-PassRefPtr<SVGSetElement> SVGSetElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGSetElement> SVGSetElement::create(Document& document)
{
- return adoptRef(new SVGSetElement(tagName, document));
+ return adoptRef(new SVGSetElement(document));
}
void SVGSetElement::updateAnimationMode()
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGSetElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGSetElement.h
index 7ff5a5741cb..a2cd048c003 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGSetElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGSetElement.h
@@ -28,10 +28,10 @@ namespace WebCore {
// SVGAnimateElement implements superset of the functionality.
class SVGSetElement FINAL : public SVGAnimateElement {
public:
- static PassRefPtr<SVGSetElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGSetElement> create(Document&);
private:
- SVGSetElement(const QualifiedName&, Document&);
+ explicit SVGSetElement(Document&);
virtual void updateAnimationMode() OVERRIDE;
};
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGStopElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGStopElement.cpp
index 0751619940d..b3d85099a44 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGStopElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGStopElement.cpp
@@ -22,7 +22,6 @@
#include "core/svg/SVGStopElement.h"
-#include "SVGNames.h"
#include "core/rendering/svg/RenderSVGGradientStop.h"
#include "core/rendering/svg/RenderSVGResource.h"
#include "core/svg/SVGElementInstance.h"
@@ -37,18 +36,17 @@ BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGStopElement)
REGISTER_PARENT_ANIMATED_PROPERTIES(SVGElement)
END_REGISTER_ANIMATED_PROPERTIES
-inline SVGStopElement::SVGStopElement(const QualifiedName& tagName, Document& document)
- : SVGElement(tagName, document)
+inline SVGStopElement::SVGStopElement(Document& document)
+ : SVGElement(SVGNames::stopTag, document)
, m_offset(0)
{
- ASSERT(hasTagName(SVGNames::stopTag));
ScriptWrappable::init(this);
registerAnimatedPropertiesForSVGStopElement();
}
-PassRefPtr<SVGStopElement> SVGStopElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGStopElement> SVGStopElement::create(Document& document)
{
- return adoptRef(new SVGStopElement(tagName, document));
+ return adoptRef(new SVGStopElement(document));
}
bool SVGStopElement::isSupportedAttribute(const QualifiedName& attrName)
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGStopElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGStopElement.h
index 98b0dfe26fd..6b941f2e503 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGStopElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGStopElement.h
@@ -29,12 +29,12 @@ namespace WebCore {
class SVGStopElement FINAL : public SVGElement {
public:
- static PassRefPtr<SVGStopElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGStopElement> create(Document&);
Color stopColorIncludingOpacity() const;
private:
- SVGStopElement(const QualifiedName&, Document&);
+ explicit SVGStopElement(Document&);
bool isSupportedAttribute(const QualifiedName&);
virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
@@ -50,12 +50,13 @@ private:
END_DECLARE_ANIMATED_PROPERTIES
};
-inline SVGStopElement* toSVGStopElement(Node* node)
+inline bool isSVGStopElement(const Node& node)
{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || toSVGElement(node)->isGradientStop());
- return static_cast<SVGStopElement*>(node);
+ return node.isSVGElement() && toSVGElement(node).isGradientStop();
}
+DEFINE_NODE_TYPE_CASTS_WITH_FUNCTION(SVGStopElement);
+
} // namespace WebCore
#endif
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGStyleElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGStyleElement.cpp
index adb399dbd99..f0815b4daeb 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGStyleElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGStyleElement.cpp
@@ -23,18 +23,16 @@
#include "config.h"
#include "core/svg/SVGStyleElement.h"
-#include "SVGNames.h"
#include "core/css/CSSStyleSheet.h"
#include "wtf/StdLibExtras.h"
namespace WebCore {
-inline SVGStyleElement::SVGStyleElement(const QualifiedName& tagName, Document& document, bool createdByParser)
- : SVGElement(tagName, document)
+inline SVGStyleElement::SVGStyleElement(Document& document, bool createdByParser)
+ : SVGElement(SVGNames::styleTag, document)
, StyleElement(&document, createdByParser)
, m_svgLoadEventTimer(this, &SVGElement::svgLoadEventTimerFired)
{
- ASSERT(hasTagName(SVGNames::styleTag));
ScriptWrappable::init(this);
}
@@ -43,9 +41,9 @@ SVGStyleElement::~SVGStyleElement()
StyleElement::clearDocumentData(document(), this);
}
-PassRefPtr<SVGStyleElement> SVGStyleElement::create(const QualifiedName& tagName, Document& document, bool createdByParser)
+PassRefPtr<SVGStyleElement> SVGStyleElement::create(Document& document, bool createdByParser)
{
- return adoptRef(new SVGStyleElement(tagName, document, createdByParser));
+ return adoptRef(new SVGStyleElement(document, createdByParser));
}
bool SVGStyleElement::disabled() const
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGStyleElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGStyleElement.h
index 35cf7be6a1e..522f0af3dff 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGStyleElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGStyleElement.h
@@ -30,7 +30,7 @@ namespace WebCore {
class SVGStyleElement FINAL : public SVGElement
, public StyleElement {
public:
- static PassRefPtr<SVGStyleElement> create(const QualifiedName&, Document&, bool createdByParser);
+ static PassRefPtr<SVGStyleElement> create(Document&, bool createdByParser);
virtual ~SVGStyleElement();
using StyleElement::sheet;
@@ -48,7 +48,7 @@ public:
void setTitle(const AtomicString&);
private:
- SVGStyleElement(const QualifiedName&, Document&, bool createdByParser);
+ SVGStyleElement(Document&, bool createdByParser);
bool isSupportedAttribute(const QualifiedName&);
virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
@@ -68,11 +68,7 @@ private:
Timer<SVGElement> m_svgLoadEventTimer;
};
-inline SVGStyleElement* toSVGStyleElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(SVGNames::styleTag));
- return static_cast<SVGStyleElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(SVGStyleElement, hasTagName(SVGNames::styleTag));
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGSwitchElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGSwitchElement.cpp
index 07916668ca5..f4c8dd11e1a 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGSwitchElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGSwitchElement.cpp
@@ -23,7 +23,7 @@
#include "core/svg/SVGSwitchElement.h"
#include "SVGNames.h"
-#include "core/page/UseCounter.h"
+#include "core/frame/UseCounter.h"
#include "core/rendering/svg/RenderSVGTransformableContainer.h"
namespace WebCore {
@@ -36,25 +36,25 @@ BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGSwitchElement)
REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
END_REGISTER_ANIMATED_PROPERTIES
-inline SVGSwitchElement::SVGSwitchElement(const QualifiedName& tagName, Document& document)
- : SVGGraphicsElement(tagName, document)
+inline SVGSwitchElement::SVGSwitchElement(Document& document)
+ : SVGGraphicsElement(SVGNames::switchTag, document)
{
- ASSERT(hasTagName(SVGNames::switchTag));
ScriptWrappable::init(this);
registerAnimatedPropertiesForSVGSwitchElement();
- UseCounter::count(&document, UseCounter::SVGSwitchElement);
+ UseCounter::count(document, UseCounter::SVGSwitchElement);
}
-PassRefPtr<SVGSwitchElement> SVGSwitchElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGSwitchElement> SVGSwitchElement::create(Document& document)
{
- return adoptRef(new SVGSwitchElement(tagName, document));
+ return adoptRef(new SVGSwitchElement(document));
}
bool SVGSwitchElement::childShouldCreateRenderer(const Node& child) const
{
// FIXME: This function does not do what the comment below implies it does.
// It will create a renderer for any valid SVG element children, not just the first one.
+ bool shouldCreateRenderer = false;
for (Node* node = firstChild(); node; node = node->nextSibling()) {
if (!node->isSVGElement())
continue;
@@ -63,10 +63,11 @@ bool SVGSwitchElement::childShouldCreateRenderer(const Node& child) const
if (!element || !element->isValid())
continue;
- return node == &child; // Only allow this child if it's the first valid child
+ shouldCreateRenderer = node == &child; // Only allow this child if it's the first valid child.
+ break;
}
- return false;
+ return shouldCreateRenderer && SVGGraphicsElement::childShouldCreateRenderer(child);
}
RenderObject* SVGSwitchElement::createRenderer(RenderStyle*)
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGSwitchElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGSwitchElement.h
index d7af51c6caf..48312ea530b 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGSwitchElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGSwitchElement.h
@@ -30,10 +30,10 @@ namespace WebCore {
class SVGSwitchElement FINAL : public SVGGraphicsElement,
public SVGExternalResourcesRequired {
public:
- static PassRefPtr<SVGSwitchElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGSwitchElement> create(Document&);
private:
- SVGSwitchElement(const QualifiedName&, Document&);
+ explicit SVGSwitchElement(Document&);
virtual bool isValid() const { return SVGTests::isValid(); }
virtual bool supportsFocus() const OVERRIDE { return hasFocusEventListeners(); }
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGSymbolElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGSymbolElement.cpp
index 2d65a2da6f3..b9a405ad027 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGSymbolElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGSymbolElement.cpp
@@ -25,7 +25,6 @@
#include "SVGNames.h"
#include "core/rendering/svg/RenderSVGHiddenContainer.h"
#include "core/svg/SVGElementInstance.h"
-#include "core/svg/SVGFitToViewBox.h"
namespace WebCore {
@@ -41,17 +40,16 @@ BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGSymbolElement)
REGISTER_PARENT_ANIMATED_PROPERTIES(SVGElement)
END_REGISTER_ANIMATED_PROPERTIES
-inline SVGSymbolElement::SVGSymbolElement(const QualifiedName& tagName, Document& document)
- : SVGElement(tagName, document)
+inline SVGSymbolElement::SVGSymbolElement(Document& document)
+ : SVGElement(SVGNames::symbolTag, document)
{
- ASSERT(hasTagName(SVGNames::symbolTag));
ScriptWrappable::init(this);
registerAnimatedPropertiesForSVGSymbolElement();
}
-PassRefPtr<SVGSymbolElement> SVGSymbolElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGSymbolElement> SVGSymbolElement::create(Document& document)
{
- return adoptRef(new SVGSymbolElement(tagName, document));
+ return adoptRef(new SVGSymbolElement(document));
}
bool SVGSymbolElement::isSupportedAttribute(const QualifiedName& attrName)
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGSymbolElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGSymbolElement.h
index 9d010de67c5..d65a0da0f26 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGSymbolElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGSymbolElement.h
@@ -34,10 +34,10 @@ class SVGSymbolElement FINAL : public SVGElement,
public SVGExternalResourcesRequired,
public SVGFitToViewBox {
public:
- static PassRefPtr<SVGSymbolElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGSymbolElement> create(Document&);
private:
- SVGSymbolElement(const QualifiedName&, Document&);
+ explicit SVGSymbolElement(Document&);
virtual bool supportsFocus() const OVERRIDE { return hasFocusEventListeners(); }
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGTSpanElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGTSpanElement.cpp
index 7b47b96553e..77f13fcb23f 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGTSpanElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGTSpanElement.cpp
@@ -27,16 +27,15 @@
namespace WebCore {
-inline SVGTSpanElement::SVGTSpanElement(const QualifiedName& tagName, Document& document)
- : SVGTextPositioningElement(tagName, document)
+inline SVGTSpanElement::SVGTSpanElement(Document& document)
+ : SVGTextPositioningElement(SVGNames::tspanTag, document)
{
- ASSERT(hasTagName(SVGNames::tspanTag));
ScriptWrappable::init(this);
}
-PassRefPtr<SVGTSpanElement> SVGTSpanElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGTSpanElement> SVGTSpanElement::create(Document& document)
{
- return adoptRef(new SVGTSpanElement(tagName, document));
+ return adoptRef(new SVGTSpanElement(document));
}
RenderObject* SVGTSpanElement::createRenderer(RenderStyle*)
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGTSpanElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGTSpanElement.h
index 2861f85f661..547e9ee5e03 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGTSpanElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGTSpanElement.h
@@ -27,10 +27,10 @@ namespace WebCore {
class SVGTSpanElement FINAL : public SVGTextPositioningElement {
public:
- static PassRefPtr<SVGTSpanElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGTSpanElement> create(Document&);
private:
- SVGTSpanElement(const QualifiedName&, Document&);
+ explicit SVGTSpanElement(Document&);
virtual RenderObject* createRenderer(RenderStyle*);
virtual bool childShouldCreateRenderer(const Node& child) const;
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGTagNames.in b/chromium/third_party/WebKit/Source/core/svg/SVGTagNames.in
new file mode 100644
index 00000000000..caf925d610c
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGTagNames.in
@@ -0,0 +1,95 @@
+namespace="SVG"
+namespaceURI="http://www.w3.org/2000/svg"
+fallbackInterfaceName="SVGUnknownElement"
+fallbackJSInterfaceName="SVGElement"
+
+a
+#if ENABLE_SVG_FONTS
+altGlyph
+altGlyphDef
+altGlyphItem
+#endif
+animate
+animateColor
+animateMotion
+animateTransform
+set
+circle
+clipPath
+# color-profile
+cursor
+defs
+desc
+ellipse
+feBlend
+feColorMatrix
+feComponentTransfer
+feComposite
+feConvolveMatrix
+feDiffuseLighting
+feDisplacementMap
+feDistantLight
+feDropShadow
+feFlood
+feFuncA
+feFuncB
+feFuncG
+feFuncR
+feGaussianBlur
+feImage
+feMerge
+feMergeNode
+feMorphology
+feOffset
+fePointLight
+feSpecularLighting
+feSpotLight
+feTile
+feTurbulence
+filter
+#if ENABLE_SVG_FONTS
+font
+font-face
+font-face-format
+font-face-name
+font-face-src
+font-face-uri
+#endif
+foreignObject
+g
+#if ENABLE_SVG_FONTS
+glyph
+glyphRef
+hkern interfaceName=SVGHKernElement
+#endif
+image
+line
+linearGradient
+marker
+mask
+metadata
+#if ENABLE_SVG_FONTS
+missing-glyph
+#endif
+mpath interfaceName=SVGMPathElement
+path
+pattern
+polygon
+polyline
+radialGradient
+rect
+script constructorNeedsCreatedByParser
+stop
+style constructorNeedsCreatedByParser
+svg interfaceName=SVGSVGElement
+switch
+symbol
+text
+textPath
+title
+tspan interfaceName=SVGTSpanElement
+use constructorNeedsCreatedByParser
+view
+#if ENABLE_SVG_FONTS
+vkern interfaceName=SVGVKernElement
+#endif
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGTests.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGTests.cpp
index 2c309550176..1332610788d 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGTests.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGTests.cpp
@@ -24,9 +24,8 @@
#include "SVGNames.h"
#include "core/dom/DOMImplementation.h"
-#include "core/platform/Language.h"
+#include "platform/Language.h"
#include "core/svg/SVGElement.h"
-#include "core/svg/SVGStringList.h"
namespace WebCore {
@@ -146,23 +145,6 @@ bool SVGTests::isKnownAttribute(const QualifiedName& attrName)
|| attrName == SVGNames::systemLanguageAttr;
}
-bool SVGTests::handleAttributeChange(SVGElement* targetElement, const QualifiedName& attrName)
-{
- ASSERT(targetElement);
- if (!isKnownAttribute(attrName))
- return false;
- if (!targetElement->inDocument())
- return true;
-
- bool valid = targetElement->isValid();
- if (valid && !targetElement->attached() && targetElement->parentNode()->attached())
- targetElement->lazyAttach();
- else if (!valid && targetElement->attached())
- targetElement->detach();
-
- return true;
-}
-
void SVGTests::addSupportedAttributes(HashSet<QualifiedName>& supportedAttributes)
{
supportedAttributes.add(SVGNames::requiredFeaturesAttr);
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGTests.h b/chromium/third_party/WebKit/Source/core/svg/SVGTests.h
index 9350a15493f..7df0e223f1b 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGTests.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGTests.h
@@ -44,7 +44,6 @@ public:
bool isKnownAttribute(const QualifiedName&);
void addSupportedAttributes(HashSet<QualifiedName>&);
- bool handleAttributeChange(SVGElement*, const QualifiedName&);
static SVGAttributeToPropertyMap& attributeToPropertyMap();
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGTextContentElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGTextContentElement.cpp
index 4f7a3a805d4..1c298456cae 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGTextContentElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGTextContentElement.cpp
@@ -28,7 +28,7 @@
#include "bindings/v8/ExceptionState.h"
#include "bindings/v8/ExceptionStatePlaceholder.h"
#include "core/editing/FrameSelection.h"
-#include "core/page/Frame.h"
+#include "core/frame/Frame.h"
#include "core/rendering/RenderObject.h"
#include "core/rendering/svg/RenderSVGResource.h"
#include "core/rendering/svg/SVGTextQuery.h"
@@ -113,13 +113,13 @@ float SVGTextContentElement::getComputedTextLength()
return SVGTextQuery(renderer()).textLength();
}
-float SVGTextContentElement::getSubStringLength(unsigned charnum, unsigned nchars, ExceptionState& es)
+float SVGTextContentElement::getSubStringLength(unsigned charnum, unsigned nchars, ExceptionState& exceptionState)
{
document().updateLayoutIgnorePendingStylesheets();
unsigned numberOfChars = getNumberOfChars();
if (charnum >= numberOfChars) {
- es.throwDOMException(IndexSizeError);
+ exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
return 0.0f;
}
@@ -129,48 +129,48 @@ float SVGTextContentElement::getSubStringLength(unsigned charnum, unsigned nchar
return SVGTextQuery(renderer()).subStringLength(charnum, nchars);
}
-SVGPoint SVGTextContentElement::getStartPositionOfChar(unsigned charnum, ExceptionState& es)
+SVGPoint SVGTextContentElement::getStartPositionOfChar(unsigned charnum, ExceptionState& exceptionState)
{
document().updateLayoutIgnorePendingStylesheets();
if (charnum > getNumberOfChars()) {
- es.throwDOMException(IndexSizeError);
+ exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
return FloatPoint();
}
return SVGTextQuery(renderer()).startPositionOfCharacter(charnum);
}
-SVGPoint SVGTextContentElement::getEndPositionOfChar(unsigned charnum, ExceptionState& es)
+SVGPoint SVGTextContentElement::getEndPositionOfChar(unsigned charnum, ExceptionState& exceptionState)
{
document().updateLayoutIgnorePendingStylesheets();
if (charnum > getNumberOfChars()) {
- es.throwDOMException(IndexSizeError);
+ exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
return FloatPoint();
}
return SVGTextQuery(renderer()).endPositionOfCharacter(charnum);
}
-SVGRect SVGTextContentElement::getExtentOfChar(unsigned charnum, ExceptionState& es)
+SVGRect SVGTextContentElement::getExtentOfChar(unsigned charnum, ExceptionState& exceptionState)
{
document().updateLayoutIgnorePendingStylesheets();
if (charnum > getNumberOfChars()) {
- es.throwDOMException(IndexSizeError);
+ exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
return SVGRect();
}
return SVGTextQuery(renderer()).extentOfCharacter(charnum);
}
-float SVGTextContentElement::getRotationOfChar(unsigned charnum, ExceptionState& es)
+float SVGTextContentElement::getRotationOfChar(unsigned charnum, ExceptionState& exceptionState)
{
document().updateLayoutIgnorePendingStylesheets();
if (charnum > getNumberOfChars()) {
- es.throwDOMException(IndexSizeError);
+ exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
return 0.0f;
}
@@ -183,11 +183,11 @@ int SVGTextContentElement::getCharNumAtPosition(const SVGPoint& point)
return SVGTextQuery(renderer()).characterNumberAtPosition(point);
}
-void SVGTextContentElement::selectSubString(unsigned charnum, unsigned nchars, ExceptionState& es)
+void SVGTextContentElement::selectSubString(unsigned charnum, unsigned nchars, ExceptionState& exceptionState)
{
unsigned numberOfChars = getNumberOfChars();
if (charnum >= numberOfChars) {
- es.throwDOMException(IndexSizeError);
+ exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
return;
}
@@ -213,10 +213,10 @@ bool SVGTextContentElement::isSupportedAttribute(const QualifiedName& attrName)
{
DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
if (supportedAttributes.isEmpty()) {
- SVGLangSpace::addSupportedAttributes(supportedAttributes);
SVGExternalResourcesRequired::addSupportedAttributes(supportedAttributes);
supportedAttributes.add(SVGNames::lengthAdjustAttr);
supportedAttributes.add(SVGNames::textLengthAttr);
+ supportedAttributes.add(XMLNames::spaceAttr);
}
return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
}
@@ -255,7 +255,7 @@ void SVGTextContentElement::parseAttribute(const QualifiedName& name, const Atom
} else if (name == SVGNames::textLengthAttr) {
m_textLength.value = SVGLength::construct(LengthModeOther, value, parseError, ForbidNegativeLengths);
} else if (SVGExternalResourcesRequired::parseAttribute(name, value)) {
- } else if (SVGLangSpace::parseAttribute(name, value)) {
+ } else if (name.matches(XMLNames::spaceAttr)) {
} else
ASSERT_NOT_REACHED();
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGTextContentElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGTextContentElement.h
index 255330e8692..db0b622d8b9 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGTextContentElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGTextContentElement.h
@@ -122,12 +122,13 @@ private:
END_DECLARE_ANIMATED_PROPERTIES
};
-inline SVGTextContentElement* toSVGTextContentElement(SVGElement* element)
+inline bool isSVGTextContentElement(const Node& node)
{
- ASSERT_WITH_SECURITY_IMPLICATION(!element || element->isTextContent());
- return static_cast<SVGTextContentElement*>(element);
+ return node.isSVGElement() && toSVGElement(node).isTextContent();
}
+DEFINE_NODE_TYPE_CASTS_WITH_FUNCTION(SVGTextContentElement);
+
} // namespace WebCore
#endif
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGTextElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGTextElement.cpp
index d7ed0d686aa..7806ed129ed 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGTextElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGTextElement.cpp
@@ -22,23 +22,21 @@
#include "core/svg/SVGTextElement.h"
-#include "SVGNames.h"
#include "core/rendering/svg/RenderSVGResource.h"
#include "core/rendering/svg/RenderSVGText.h"
#include "core/svg/SVGElementInstance.h"
namespace WebCore {
-inline SVGTextElement::SVGTextElement(const QualifiedName& tagName, Document& doc)
- : SVGTextPositioningElement(tagName, doc)
+inline SVGTextElement::SVGTextElement(Document& doc)
+ : SVGTextPositioningElement(SVGNames::textTag, doc)
{
- ASSERT(hasTagName(SVGNames::textTag));
ScriptWrappable::init(this);
}
-PassRefPtr<SVGTextElement> SVGTextElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGTextElement> SVGTextElement::create(Document& document)
{
- return adoptRef(new SVGTextElement(tagName, document));
+ return adoptRef(new SVGTextElement(document));
}
// We override SVGGraphics::animatedLocalTransform() so that the transform-origin
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGTextElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGTextElement.h
index 55b63e6407e..b52204c15c3 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGTextElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGTextElement.h
@@ -28,12 +28,12 @@ namespace WebCore {
class SVGTextElement FINAL : public SVGTextPositioningElement {
public:
- static PassRefPtr<SVGTextElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGTextElement> create(Document&);
virtual AffineTransform animatedLocalTransform() const;
private:
- SVGTextElement(const QualifiedName&, Document&);
+ explicit SVGTextElement(Document&);
virtual bool supportsFocus() const OVERRIDE { return hasFocusEventListeners(); }
@@ -41,11 +41,7 @@ private:
virtual bool childShouldCreateRenderer(const Node& child) const;
};
-inline SVGTextElement* toSVGTextElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(SVGNames::textTag));
- return static_cast<SVGTextElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(SVGTextElement, hasTagName(SVGNames::textTag));
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGTextPathElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGTextPathElement.cpp
index eb21c90e306..b3f2e1b1fb4 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGTextPathElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGTextPathElement.cpp
@@ -22,7 +22,6 @@
#include "core/svg/SVGTextPathElement.h"
-#include "SVGNames.h"
#include "XLinkNames.h"
#include "core/rendering/svg/RenderSVGResource.h"
#include "core/rendering/svg/RenderSVGTextPath.h"
@@ -44,20 +43,19 @@ BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGTextPathElement)
REGISTER_PARENT_ANIMATED_PROPERTIES(SVGTextContentElement)
END_REGISTER_ANIMATED_PROPERTIES
-inline SVGTextPathElement::SVGTextPathElement(const QualifiedName& tagName, Document& document)
- : SVGTextContentElement(tagName, document)
+inline SVGTextPathElement::SVGTextPathElement(Document& document)
+ : SVGTextContentElement(SVGNames::textPathTag, document)
, m_startOffset(LengthModeOther)
, m_method(SVGTextPathMethodAlign)
, m_spacing(SVGTextPathSpacingExact)
{
- ASSERT(hasTagName(SVGNames::textPathTag));
ScriptWrappable::init(this);
registerAnimatedPropertiesForSVGTextPathElement();
}
-PassRefPtr<SVGTextPathElement> SVGTextPathElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGTextPathElement> SVGTextPathElement::create(Document& document)
{
- return adoptRef(new SVGTextPathElement(tagName, document));
+ return adoptRef(new SVGTextPathElement(document));
}
SVGTextPathElement::~SVGTextPathElement()
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGTextPathElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGTextPathElement.h
index 1ea5d11cde5..2b7a38c1ead 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGTextPathElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGTextPathElement.h
@@ -109,10 +109,10 @@ public:
TEXTPATH_SPACINGTYPE_EXACT = SVGTextPathSpacingExact
};
- static PassRefPtr<SVGTextPathElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGTextPathElement> create(Document&);
private:
- SVGTextPathElement(const QualifiedName&, Document&);
+ explicit SVGTextPathElement(Document&);
virtual ~SVGTextPathElement();
@@ -140,11 +140,7 @@ private:
END_DECLARE_ANIMATED_PROPERTIES
};
-inline SVGTextPathElement* toSVGTextPathElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(SVGNames::textPathTag));
- return static_cast<SVGTextPathElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(SVGTextPathElement, hasTagName(SVGNames::textPathTag));
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGTitleElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGTitleElement.cpp
index 7e6a1ce6571..cd018b8a0f1 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGTitleElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGTitleElement.cpp
@@ -26,16 +26,15 @@
namespace WebCore {
-inline SVGTitleElement::SVGTitleElement(const QualifiedName& tagName, Document& document)
- : SVGElement(tagName, document)
+inline SVGTitleElement::SVGTitleElement(Document& document)
+ : SVGElement(SVGNames::titleTag, document)
{
- ASSERT(hasTagName(SVGNames::titleTag));
ScriptWrappable::init(this);
}
-PassRefPtr<SVGTitleElement> SVGTitleElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGTitleElement> SVGTitleElement::create(Document& document)
{
- return adoptRef(new SVGTitleElement(tagName, document));
+ return adoptRef(new SVGTitleElement(document));
}
Node::InsertionNotificationRequest SVGTitleElement::insertedInto(ContainerNode* rootParent)
@@ -43,6 +42,7 @@ Node::InsertionNotificationRequest SVGTitleElement::insertedInto(ContainerNode*
SVGElement::insertedInto(rootParent);
if (!rootParent->inDocument())
return InsertionDone;
+ // FIXME: It's possible to register SVGTitleElement to an HTMLDocument.
if (firstChild())
document().setTitleElement(textContent(), this);
return InsertionDone;
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGTitleElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGTitleElement.h
index e5ac03b216b..21c3127f6dd 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGTitleElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGTitleElement.h
@@ -27,10 +27,10 @@ namespace WebCore {
class SVGTitleElement FINAL : public SVGElement {
public:
- static PassRefPtr<SVGTitleElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGTitleElement> create(Document&);
private:
- SVGTitleElement(const QualifiedName&, Document&);
+ explicit SVGTitleElement(Document&);
virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
virtual void removedFrom(ContainerNode*) OVERRIDE;
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGTransform.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGTransform.cpp
index 2c44d366e55..8cf0ef2ffcc 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGTransform.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGTransform.cpp
@@ -21,12 +21,10 @@
#include "config.h"
#include "core/svg/SVGTransform.h"
-#include "core/platform/FloatConversion.h"
-#include "core/platform/graphics/FloatPoint.h"
-#include "core/platform/graphics/FloatSize.h"
+#include "platform/FloatConversion.h"
+#include "platform/geometry/FloatSize.h"
#include "wtf/MathExtras.h"
#include "wtf/text/StringBuilder.h"
-#include "wtf/text/WTFString.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGTransform.h b/chromium/third_party/WebKit/Source/core/svg/SVGTransform.h
index 3053d4f2401..71f7668b38d 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGTransform.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGTransform.h
@@ -21,8 +21,8 @@
#ifndef SVGTransform_h
#define SVGTransform_h
-#include "core/platform/graphics/FloatPoint.h"
#include "core/svg/SVGMatrix.h"
+#include "platform/geometry/FloatPoint.h"
#include "wtf/text/WTFString.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGTransformDistance.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGTransformDistance.cpp
index 47a544346f9..1108f322039 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGTransformDistance.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGTransformDistance.cpp
@@ -21,10 +21,8 @@
#include "core/svg/SVGTransformDistance.h"
-#include "core/platform/graphics/FloatPoint.h"
-#include "core/platform/graphics/FloatSize.h"
-#include "core/svg/SVGTransform.h"
-
+#include "platform/geometry/FloatPoint.h"
+#include "platform/geometry/FloatSize.h"
#include <math.h>
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGTransformList.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGTransformList.cpp
index 3d3e58fda5d..f09a01046a5 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGTransformList.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGTransformList.cpp
@@ -21,10 +21,9 @@
#include "config.h"
#include "core/svg/SVGTransformList.h"
-#include "core/platform/graphics/transforms/AffineTransform.h"
+#include "core/svg/SVGParserUtilities.h"
#include "core/svg/SVGSVGElement.h"
-#include "core/svg/SVGTransform.h"
-#include "core/svg/SVGTransformable.h"
+#include "platform/transforms/AffineTransform.h"
#include "wtf/text/StringBuilder.h"
namespace WebCore {
@@ -83,12 +82,12 @@ void SVGTransformList::parse(const String& transform)
} else if (transform.is8Bit()) {
const LChar* ptr = transform.characters8();
const LChar* end = ptr + transform.length();
- if (!SVGTransformable::parseTransformAttribute(*this, ptr, end))
+ if (!parseTransformAttribute(*this, ptr, end))
clear();
} else {
const UChar* ptr = transform.characters16();
const UChar* end = ptr + transform.length();
- if (!SVGTransformable::parseTransformAttribute(*this, ptr, end))
+ if (!parseTransformAttribute(*this, ptr, end))
clear();
}
}
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGTransformable.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGTransformable.cpp
deleted file mode 100644
index 9c35dc3a337..00000000000
--- a/chromium/third_party/WebKit/Source/core/svg/SVGTransformable.cpp
+++ /dev/null
@@ -1,240 +0,0 @@
-/*
- * Copyright (C) 2004, 2005, 2008 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2004, 2005, 2006, 2007 Rob Buis <buis@kde.org>
- * Copyright (C) 2007 Eric Seidel <eric@webkit.org>
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-
-#include "core/svg/SVGTransformable.h"
-
-#include "core/platform/graphics/transforms/AffineTransform.h"
-#include "core/svg/SVGParserUtilities.h"
-#include "core/svg/SVGTransformList.h"
-
-namespace WebCore {
-
-template<typename CharType>
-static int parseTransformParamList(const CharType*& ptr, const CharType* end, float* values, int required, int optional)
-{
- int optionalParams = 0, requiredParams = 0;
-
- if (!skipOptionalSVGSpaces(ptr, end) || *ptr != '(')
- return -1;
-
- ptr++;
-
- skipOptionalSVGSpaces(ptr, end);
-
- while (requiredParams < required) {
- if (ptr >= end || !parseNumber(ptr, end, values[requiredParams], false))
- return -1;
- requiredParams++;
- if (requiredParams < required)
- skipOptionalSVGSpacesOrDelimiter(ptr, end);
- }
- if (!skipOptionalSVGSpaces(ptr, end))
- return -1;
-
- bool delimParsed = skipOptionalSVGSpacesOrDelimiter(ptr, end);
-
- if (ptr >= end)
- return -1;
-
- if (*ptr == ')') { // skip optionals
- ptr++;
- if (delimParsed)
- return -1;
- } else {
- while (optionalParams < optional) {
- if (ptr >= end || !parseNumber(ptr, end, values[requiredParams + optionalParams], false))
- return -1;
- optionalParams++;
- if (optionalParams < optional)
- skipOptionalSVGSpacesOrDelimiter(ptr, end);
- }
-
- if (!skipOptionalSVGSpaces(ptr, end))
- return -1;
-
- delimParsed = skipOptionalSVGSpacesOrDelimiter(ptr, end);
-
- if (ptr >= end || *ptr != ')' || delimParsed)
- return -1;
- ptr++;
- }
-
- return requiredParams + optionalParams;
-}
-
-// These should be kept in sync with enum SVGTransformType
-static const int requiredValuesForType[] = {0, 6, 1, 1, 1, 1, 1};
-static const int optionalValuesForType[] = {0, 0, 1, 1, 2, 0, 0};
-
-// This destructor is needed in order to link correctly with Intel ICC.
-SVGTransformable::~SVGTransformable()
-{
-}
-
-template<typename CharType>
-static bool parseTransformValueInternal(unsigned type, const CharType*& ptr, const CharType* end, SVGTransform& transform)
-{
- if (type == SVGTransform::SVG_TRANSFORM_UNKNOWN)
- return false;
-
- int valueCount = 0;
- float values[] = {0, 0, 0, 0, 0, 0};
- if ((valueCount = parseTransformParamList(ptr, end, values, requiredValuesForType[type], optionalValuesForType[type])) < 0)
- return false;
-
- switch (type) {
- case SVGTransform::SVG_TRANSFORM_SKEWX:
- transform.setSkewX(values[0]);
- break;
- case SVGTransform::SVG_TRANSFORM_SKEWY:
- transform.setSkewY(values[0]);
- break;
- case SVGTransform::SVG_TRANSFORM_SCALE:
- if (valueCount == 1) // Spec: if only one param given, assume uniform scaling
- transform.setScale(values[0], values[0]);
- else
- transform.setScale(values[0], values[1]);
- break;
- case SVGTransform::SVG_TRANSFORM_TRANSLATE:
- if (valueCount == 1) // Spec: if only one param given, assume 2nd param to be 0
- transform.setTranslate(values[0], 0);
- else
- transform.setTranslate(values[0], values[1]);
- break;
- case SVGTransform::SVG_TRANSFORM_ROTATE:
- if (valueCount == 1)
- transform.setRotate(values[0], 0, 0);
- else
- transform.setRotate(values[0], values[1], values[2]);
- break;
- case SVGTransform::SVG_TRANSFORM_MATRIX:
- transform.setMatrix(AffineTransform(values[0], values[1], values[2], values[3], values[4], values[5]));
- break;
- }
-
- return true;
-}
-
-bool SVGTransformable::parseTransformValue(unsigned type, const LChar*& ptr, const LChar* end, SVGTransform& transform)
-{
- return parseTransformValueInternal(type, ptr, end, transform);
-}
-
-bool SVGTransformable::parseTransformValue(unsigned type, const UChar*& ptr, const UChar* end, SVGTransform& transform)
-{
- return parseTransformValueInternal(type, ptr, end, transform);
-}
-
-static const LChar skewXDesc[] = {'s', 'k', 'e', 'w', 'X'};
-static const LChar skewYDesc[] = {'s', 'k', 'e', 'w', 'Y'};
-static const LChar scaleDesc[] = {'s', 'c', 'a', 'l', 'e'};
-static const LChar translateDesc[] = {'t', 'r', 'a', 'n', 's', 'l', 'a', 't', 'e'};
-static const LChar rotateDesc[] = {'r', 'o', 't', 'a', 't', 'e'};
-static const LChar matrixDesc[] = {'m', 'a', 't', 'r', 'i', 'x'};
-
-template<typename CharType>
-static inline bool parseAndSkipType(const CharType*& ptr, const CharType* end, unsigned short& type)
-{
- if (ptr >= end)
- return false;
-
- if (*ptr == 's') {
- if (skipString(ptr, end, skewXDesc, WTF_ARRAY_LENGTH(skewXDesc)))
- type = SVGTransform::SVG_TRANSFORM_SKEWX;
- else if (skipString(ptr, end, skewYDesc, WTF_ARRAY_LENGTH(skewYDesc)))
- type = SVGTransform::SVG_TRANSFORM_SKEWY;
- else if (skipString(ptr, end, scaleDesc, WTF_ARRAY_LENGTH(scaleDesc)))
- type = SVGTransform::SVG_TRANSFORM_SCALE;
- else
- return false;
- } else if (skipString(ptr, end, translateDesc, WTF_ARRAY_LENGTH(translateDesc)))
- type = SVGTransform::SVG_TRANSFORM_TRANSLATE;
- else if (skipString(ptr, end, rotateDesc, WTF_ARRAY_LENGTH(rotateDesc)))
- type = SVGTransform::SVG_TRANSFORM_ROTATE;
- else if (skipString(ptr, end, matrixDesc, WTF_ARRAY_LENGTH(matrixDesc)))
- type = SVGTransform::SVG_TRANSFORM_MATRIX;
- else
- return false;
-
- return true;
-}
-
-SVGTransform::SVGTransformType SVGTransformable::parseTransformType(const String& string)
-{
- if (string.isEmpty())
- return SVGTransform::SVG_TRANSFORM_UNKNOWN;
- unsigned short type = SVGTransform::SVG_TRANSFORM_UNKNOWN;
- if (string.is8Bit()) {
- const LChar* ptr = string.characters8();
- const LChar* end = ptr + string.length();
- parseAndSkipType(ptr, end, type);
- } else {
- const UChar* ptr = string.characters16();
- const UChar* end = ptr + string.length();
- parseAndSkipType(ptr, end, type);
- }
- return static_cast<SVGTransform::SVGTransformType>(type);
-}
-
-template<typename CharType>
-bool SVGTransformable::parseTransformAttributeInternal(SVGTransformList& list, const CharType*& ptr, const CharType* end, TransformParsingMode mode)
-{
- if (mode == ClearList)
- list.clear();
-
- bool delimParsed = false;
- while (ptr < end) {
- delimParsed = false;
- unsigned short type = SVGTransform::SVG_TRANSFORM_UNKNOWN;
- skipOptionalSVGSpaces(ptr, end);
-
- if (!parseAndSkipType(ptr, end, type))
- return false;
-
- SVGTransform transform;
- if (!parseTransformValue(type, ptr, end, transform))
- return false;
-
- list.append(transform);
- skipOptionalSVGSpaces(ptr, end);
- if (ptr < end && *ptr == ',') {
- delimParsed = true;
- ++ptr;
- }
- skipOptionalSVGSpaces(ptr, end);
- }
-
- return !delimParsed;
-}
-
-bool SVGTransformable::parseTransformAttribute(SVGTransformList& list, const LChar*& ptr, const LChar* end, TransformParsingMode mode)
-{
- return parseTransformAttributeInternal(list, ptr, end, mode);
-}
-
-bool SVGTransformable::parseTransformAttribute(SVGTransformList& list, const UChar*& ptr, const UChar* end, TransformParsingMode mode)
-{
- return parseTransformAttributeInternal(list, ptr, end, mode);
-}
-
-}
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGTransformable.h b/chromium/third_party/WebKit/Source/core/svg/SVGTransformable.h
deleted file mode 100644
index f060545ae4e..00000000000
--- a/chromium/third_party/WebKit/Source/core/svg/SVGTransformable.h
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * Copyright (C) 2004, 2005, 2008 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2004, 2005, 2006, 2007 Rob Buis <buis@kde.org>
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB. If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#ifndef SVGTransformable_h
-#define SVGTransformable_h
-
-#include "core/svg/SVGLocatable.h"
-#include "core/svg/SVGTransform.h"
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-class AffineTransform;
-class SVGTransformList;
-
-class SVGTransformable : virtual public SVGLocatable {
-public:
- enum TransformParsingMode {
- ClearList,
- DoNotClearList
- };
-
- virtual ~SVGTransformable();
-
- static bool parseTransformAttribute(SVGTransformList&, const LChar*& ptr, const LChar* end, TransformParsingMode = ClearList);
- static bool parseTransformAttribute(SVGTransformList&, const UChar*& ptr, const UChar* end, TransformParsingMode = ClearList);
-
- static bool parseTransformValue(unsigned type, const LChar*& ptr, const LChar* end, SVGTransform&);
- static bool parseTransformValue(unsigned type, const UChar*& ptr, const UChar* end, SVGTransform&);
-
- static SVGTransform::SVGTransformType parseTransformType(const String&);
-
- virtual AffineTransform localCoordinateSpaceTransform(SVGLocatable::CTMScope) const { return animatedLocalTransform(); }
- virtual AffineTransform animatedLocalTransform() const = 0;
-
-private:
- template<typename CharType>
- static bool parseTransformAttributeInternal(SVGTransformList&, const CharType*& ptr, const CharType* end, TransformParsingMode);
-};
-
-} // namespace WebCore
-
-#endif // SVGTransformable_h
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGURIReference.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGURIReference.cpp
index f51aa1c047a..02cd99fa022 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGURIReference.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGURIReference.cpp
@@ -23,8 +23,7 @@
#include "core/svg/SVGURIReference.h"
#include "XLinkNames.h"
-#include "core/dom/Document.h"
-#include "weborigin/KURL.h"
+#include "platform/weborigin/KURL.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGURIReference.h b/chromium/third_party/WebKit/Source/core/svg/SVGURIReference.h
index e6901e66bcd..f73a23bd2bf 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGURIReference.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGURIReference.h
@@ -51,7 +51,7 @@ public:
}
protected:
- virtual void setHrefBaseValue(const String&, const bool validValue = true) = 0;
+ virtual void setHrefBaseValue(const String&) = 0;
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGUnitTypes.idl b/chromium/third_party/WebKit/Source/core/svg/SVGUnitTypes.idl
index 22817c2d826..5f5ec2ec800 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGUnitTypes.idl
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGUnitTypes.idl
@@ -23,12 +23,9 @@
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-[
- DoNotGenerateToV8
-] interface SVGUnitTypes {
+interface SVGUnitTypes {
// Unit Types
const unsigned short SVG_UNIT_TYPE_UNKNOWN = 0;
const unsigned short SVG_UNIT_TYPE_USERSPACEONUSE = 1;
const unsigned short SVG_UNIT_TYPE_OBJECTBOUNDINGBOX = 2;
};
-
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGUseElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGUseElement.cpp
index 68fbe2fa39a..80d36bf97f3 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGUseElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGUseElement.cpp
@@ -26,15 +26,13 @@
#include "core/svg/SVGUseElement.h"
-#include "SVGNames.h"
#include "XLinkNames.h"
#include "bindings/v8/ExceptionStatePlaceholder.h"
#include "core/dom/Document.h"
#include "core/dom/ElementTraversal.h"
-#include "core/dom/Event.h"
+#include "core/events/Event.h"
#include "core/dom/shadow/ElementShadow.h"
#include "core/dom/shadow/ShadowRoot.h"
-#include "core/fetch/DocumentResource.h"
#include "core/fetch/FetchRequest.h"
#include "core/fetch/ResourceFetcher.h"
#include "core/rendering/svg/RenderSVGResource.h"
@@ -71,8 +69,8 @@ BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGUseElement)
REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
END_REGISTER_ANIMATED_PROPERTIES
-inline SVGUseElement::SVGUseElement(const QualifiedName& tagName, Document& document, bool wasInsertedByParser)
- : SVGGraphicsElement(tagName, document)
+inline SVGUseElement::SVGUseElement(Document& document, bool wasInsertedByParser)
+ : SVGGraphicsElement(SVGNames::useTag, document)
, m_x(LengthModeWidth)
, m_y(LengthModeHeight)
, m_width(LengthModeWidth)
@@ -83,15 +81,14 @@ inline SVGUseElement::SVGUseElement(const QualifiedName& tagName, Document& docu
, m_svgLoadEventTimer(this, &SVGElement::svgLoadEventTimerFired)
{
ASSERT(hasCustomStyleCallbacks());
- ASSERT(hasTagName(SVGNames::useTag));
ScriptWrappable::init(this);
registerAnimatedPropertiesForSVGUseElement();
}
-PassRefPtr<SVGUseElement> SVGUseElement::create(const QualifiedName& tagName, Document& document, bool wasInsertedByParser)
+PassRefPtr<SVGUseElement> SVGUseElement::create(Document& document, bool wasInsertedByParser)
{
// Always build a #shadow-root for SVGUseElement.
- RefPtr<SVGUseElement> use = adoptRef(new SVGUseElement(tagName, document, wasInsertedByParser));
+ RefPtr<SVGUseElement> use = adoptRef(new SVGUseElement(document, wasInsertedByParser));
use->ensureUserAgentShadowRoot();
return use.release();
}
@@ -125,7 +122,6 @@ bool SVGUseElement::isSupportedAttribute(const QualifiedName& attrName)
{
DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
if (supportedAttributes.isEmpty()) {
- SVGLangSpace::addSupportedAttributes(supportedAttributes);
SVGExternalResourcesRequired::addSupportedAttributes(supportedAttributes);
SVGURIReference::addSupportedAttributes(supportedAttributes);
supportedAttributes.add(SVGNames::xAttr);
@@ -150,8 +146,7 @@ void SVGUseElement::parseAttribute(const QualifiedName& name, const AtomicString
setWidthBaseValue(SVGLength::construct(LengthModeWidth, value, parseError, ForbidNegativeLengths));
else if (name == SVGNames::heightAttr)
setHeightBaseValue(SVGLength::construct(LengthModeHeight, value, parseError, ForbidNegativeLengths));
- else if (SVGLangSpace::parseAttribute(name, value)
- || SVGExternalResourcesRequired::parseAttribute(name, value)
+ else if (SVGExternalResourcesRequired::parseAttribute(name, value)
|| SVGURIReference::parseAttribute(name, value)) {
} else
ASSERT_NOT_REACHED();
@@ -159,12 +154,14 @@ void SVGUseElement::parseAttribute(const QualifiedName& name, const AtomicString
reportAttributeParsingError(parseError, name, value);
}
+#if !ASSERT_DISABLED
static inline bool isWellFormedDocument(Document* document)
{
if (document->isSVGDocument() || document->isXHTMLDocument())
return static_cast<XMLDocumentParser*>(document->parser())->wellFormed();
return true;
}
+#endif
Node::InsertionNotificationRequest SVGUseElement::insertedInto(ContainerNode* rootParent)
{
@@ -250,8 +247,7 @@ void SVGUseElement::svgAttributeChanged(const QualifiedName& attrName)
if (!renderer)
return;
- if (SVGLangSpace::isKnownAttribute(attrName)
- || SVGExternalResourcesRequired::isKnownAttribute(attrName)) {
+ if (SVGExternalResourcesRequired::isKnownAttribute(attrName)) {
invalidateShadowTree();
return;
}
@@ -657,7 +653,7 @@ bool SVGUseElement::hasCycleUseReferencing(SVGUseElement* use, SVGElementInstanc
while (instance) {
SVGElement* element = instance->correspondingElement();
- if (element->hasID() && element->getIdAttribute() == targetId && &element->document() == &newTarget->document())
+ if (element->hasID() && element->getIdAttribute() == targetId && element->document() == newTarget->document())
return true;
instance = instance->parentNode();
@@ -665,18 +661,19 @@ bool SVGUseElement::hasCycleUseReferencing(SVGUseElement* use, SVGElementInstanc
return false;
}
-static inline void removeDisallowedElementsFromSubtree(Element* subtree)
+static inline void removeDisallowedElementsFromSubtree(Element& subtree)
{
- ASSERT(!subtree->inDocument());
+ ASSERT(!subtree.inDocument());
Element* element = ElementTraversal::firstWithin(subtree);
while (element) {
if (isDisallowedElement(element)) {
- Element* next = ElementTraversal::nextSkippingChildren(element, subtree);
+ Element* next = ElementTraversal::nextSkippingChildren(*element, &subtree);
// The subtree is not in document so this won't generate events that could mutate the tree.
element->parentNode()->removeChild(element);
element = next;
- } else
- element = ElementTraversal::next(element, subtree);
+ } else {
+ element = ElementTraversal::next(*element, &subtree);
+ }
}
}
@@ -694,7 +691,7 @@ void SVGUseElement::buildShadowTree(SVGElement* target, SVGElementInstance* targ
// Though if there are disallowed elements in the subtree, we have to remove them.
// For instance: <use> on <g> containing <foreignObject> (indirect case).
if (subtreeContainsDisallowedElement(newChild.get()))
- removeDisallowedElementsFromSubtree(newChild.get());
+ removeDisallowedElementsFromSubtree(*newChild);
userAgentShadowRoot()->appendChild(newChild.release());
}
@@ -720,7 +717,7 @@ void SVGUseElement::expandUseElementsInShadowTree(Node* element)
// Don't ASSERT(target) here, it may be "pending", too.
// Setup sub-shadow tree root node
- RefPtr<SVGGElement> cloneParent = SVGGElement::create(SVGNames::gTag, *referencedDocument());
+ RefPtr<SVGGElement> cloneParent = SVGGElement::create(*referencedDocument());
use->cloneChildNodes(cloneParent.get());
// Spec: In the generated content, the 'use' will be replaced by 'g', where all attributes from the
@@ -739,7 +736,7 @@ void SVGUseElement::expandUseElementsInShadowTree(Node* element)
// Though if there are disallowed elements in the subtree, we have to remove them.
// For instance: <use> on <g> containing <foreignObject> (indirect case).
if (subtreeContainsDisallowedElement(cloneParent.get()))
- removeDisallowedElementsFromSubtree(cloneParent.get());
+ removeDisallowedElementsFromSubtree(*cloneParent);
RefPtr<Node> replacingElement(cloneParent.get());
@@ -768,7 +765,7 @@ void SVGUseElement::expandSymbolElementsInShadowTree(Node* element)
// the generated 'svg'. If attributes width and/or height are not specified, the generated
// 'svg' element will use values of 100% for these attributes.
ASSERT(referencedDocument());
- RefPtr<SVGSVGElement> svgElement = SVGSVGElement::create(SVGNames::svgTag, *referencedDocument());
+ RefPtr<SVGSVGElement> svgElement = SVGSVGElement::create(*referencedDocument());
// Transfer all data (attributes, etc.) from <symbol> to the new <svg> element.
svgElement->cloneDataFromElement(*toElement(element));
@@ -785,7 +782,7 @@ void SVGUseElement::expandSymbolElementsInShadowTree(Node* element)
// Though if there are disallowed elements in the subtree, we have to remove them.
// For instance: <use> on <g> containing <foreignObject> (indirect case).
if (subtreeContainsDisallowedElement(svgElement.get()))
- removeDisallowedElementsFromSubtree(svgElement.get());
+ removeDisallowedElementsFromSubtree(*svgElement);
RefPtr<Node> replacingElement(svgElement.get());
@@ -891,7 +888,7 @@ SVGElementInstance* SVGUseElement::instanceForShadowTreeElement(Node* element, S
void SVGUseElement::invalidateShadowTree()
{
- if (!attached() || m_needsShadowTreeRecreation)
+ if (!inActiveDocument() || m_needsShadowTreeRecreation)
return;
m_needsShadowTreeRecreation = true;
setNeedsStyleRecalc();
@@ -940,7 +937,7 @@ bool SVGUseElement::selfHasRelativeLengths() const
if (!element)
return false;
- return toSVGElement(element)->hasRelativeLengths();
+ return element->hasRelativeLengths();
}
void SVGUseElement::notifyFinished(Resource* resource)
@@ -950,7 +947,7 @@ void SVGUseElement::notifyFinished(Resource* resource)
invalidateShadowTree();
if (resource->errorOccurred())
- dispatchEvent(Event::create(eventNames().errorEvent));
+ dispatchEvent(Event::create(EventTypeNames::error));
else if (!resource->wasCanceled())
SVGExternalResourcesRequired::dispatchLoadEvent(this);
}
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGUseElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGUseElement.h
index 459cb2b46c2..800af8f7c80 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGUseElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGUseElement.h
@@ -39,7 +39,7 @@ class SVGUseElement FINAL : public SVGGraphicsElement,
public SVGURIReference,
public DocumentResourceClient {
public:
- static PassRefPtr<SVGUseElement> create(const QualifiedName&, Document&, bool wasInsertedByParser);
+ static PassRefPtr<SVGUseElement> create(Document&, bool wasInsertedByParser);
virtual ~SVGUseElement();
SVGElementInstance* instanceRoot();
@@ -51,7 +51,7 @@ public:
RenderObject* rendererClipChild() const;
private:
- SVGUseElement(const QualifiedName&, Document&, bool wasInsertedByParser);
+ SVGUseElement(Document&, bool wasInsertedByParser);
virtual bool isValid() const { return SVGTests::isValid(); }
virtual bool supportsFocus() const OVERRIDE { return hasFocusEventListeners(); }
@@ -126,11 +126,7 @@ private:
Timer<SVGElement> m_svgLoadEventTimer;
};
-inline SVGUseElement* toSVGUseElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(SVGNames::useTag));
- return static_cast<SVGUseElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(SVGUseElement, hasTagName(SVGNames::useTag));
}
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGUseElement.idl b/chromium/third_party/WebKit/Source/core/svg/SVGUseElement.idl
index 752daa99d05..eb5d82c8c22 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGUseElement.idl
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGUseElement.idl
@@ -29,7 +29,7 @@ interface SVGUseElement : SVGGraphicsElement {
readonly attribute SVGAnimatedLength width;
readonly attribute SVGAnimatedLength height;
- readonly attribute SVGElementInstance instanceRoot;
+ [MeasureAs=SVGInstanceRoot] readonly attribute SVGElementInstance instanceRoot;
readonly attribute SVGElementInstance animatedInstanceRoot;
};
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGVKernElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGVKernElement.cpp
index 0908be7bf8f..ff60552df30 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGVKernElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGVKernElement.cpp
@@ -22,22 +22,19 @@
#if ENABLE(SVG_FONTS)
#include "core/svg/SVGVKernElement.h"
-#include "SVGNames.h"
-#include "core/svg/SVGFontElement.h"
#include "core/svg/SVGParserUtilities.h"
namespace WebCore {
-inline SVGVKernElement::SVGVKernElement(const QualifiedName& tagName, Document& document)
- : SVGElement(tagName, document)
+inline SVGVKernElement::SVGVKernElement(Document& document)
+ : SVGElement(SVGNames::vkernTag, document)
{
- ASSERT(hasTagName(SVGNames::vkernTag));
ScriptWrappable::init(this);
}
-PassRefPtr<SVGVKernElement> SVGVKernElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGVKernElement> SVGVKernElement::create(Document& document)
{
- return adoptRef(new SVGVKernElement(tagName, document));
+ return adoptRef(new SVGVKernElement(document));
}
Node::InsertionNotificationRequest SVGVKernElement::insertedInto(ContainerNode* rootParent)
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGVKernElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGVKernElement.h
index 185b0deff97..f8837bf686e 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGVKernElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGVKernElement.h
@@ -29,12 +29,12 @@ namespace WebCore {
class SVGVKernElement FINAL : public SVGElement {
public:
- static PassRefPtr<SVGVKernElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGVKernElement> create(Document&);
void buildVerticalKerningPair(KerningPairVector&);
private:
- SVGVKernElement(const QualifiedName&, Document&);
+ explicit SVGVKernElement(Document&);
virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
virtual void removedFrom(ContainerNode*) OVERRIDE;
@@ -42,11 +42,7 @@ private:
virtual bool rendererIsNeeded(const RenderStyle&) { return false; }
};
-inline SVGVKernElement* toSVGVKernElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(SVGNames::vkernTag));
- return static_cast<SVGVKernElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(SVGVKernElement, hasTagName(SVGNames::vkernTag));
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGViewElement.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGViewElement.cpp
index 89d7bc448df..c72604a6f38 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGViewElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGViewElement.cpp
@@ -22,10 +22,6 @@
#include "core/svg/SVGViewElement.h"
-#include "SVGNames.h"
-#include "core/svg/SVGFitToViewBox.h"
-#include "core/svg/SVGStringList.h"
-#include "core/svg/SVGZoomAndPan.h"
namespace WebCore {
@@ -41,19 +37,18 @@ BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGViewElement)
REGISTER_PARENT_ANIMATED_PROPERTIES(SVGElement)
END_REGISTER_ANIMATED_PROPERTIES
-inline SVGViewElement::SVGViewElement(const QualifiedName& tagName, Document& document)
- : SVGElement(tagName, document)
+inline SVGViewElement::SVGViewElement(Document& document)
+ : SVGElement(SVGNames::viewTag, document)
, m_zoomAndPan(SVGZoomAndPanMagnify)
, m_viewTarget(SVGNames::viewTargetAttr)
{
- ASSERT(hasTagName(SVGNames::viewTag));
ScriptWrappable::init(this);
registerAnimatedPropertiesForSVGViewElement();
}
-PassRefPtr<SVGViewElement> SVGViewElement::create(const QualifiedName& tagName, Document& document)
+PassRefPtr<SVGViewElement> SVGViewElement::create(Document& document)
{
- return adoptRef(new SVGViewElement(tagName, document));
+ return adoptRef(new SVGViewElement(document));
}
bool SVGViewElement::isSupportedAttribute(const QualifiedName& attrName)
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGViewElement.h b/chromium/third_party/WebKit/Source/core/svg/SVGViewElement.h
index 881bfaf66b3..3069cbfcf7d 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGViewElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGViewElement.h
@@ -38,7 +38,7 @@ class SVGViewElement FINAL : public SVGElement,
public SVGFitToViewBox,
public SVGZoomAndPan {
public:
- static PassRefPtr<SVGViewElement> create(const QualifiedName&, Document&);
+ static PassRefPtr<SVGViewElement> create(Document&);
using SVGElement::ref;
using SVGElement::deref;
@@ -48,7 +48,7 @@ public:
void setZoomAndPan(unsigned short zoomAndPan) { m_zoomAndPan = SVGZoomAndPan::parseFromNumber(zoomAndPan); }
private:
- SVGViewElement(const QualifiedName&, Document&);
+ explicit SVGViewElement(Document&);
// FIXME: svgAttributeChanged missing.
bool isSupportedAttribute(const QualifiedName&);
@@ -66,11 +66,7 @@ private:
SVGStringList m_viewTarget;
};
-inline SVGViewElement* toSVGViewElement(Node* node)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(SVGNames::viewTag));
- return static_cast<SVGViewElement*>(node);
-}
+DEFINE_NODE_TYPE_CASTS(SVGViewElement, hasTagName(SVGNames::viewTag));
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGViewSpec.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGViewSpec.cpp
index 7a188ccf851..b3201072998 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGViewSpec.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGViewSpec.cpp
@@ -24,10 +24,7 @@
#include "bindings/v8/ExceptionState.h"
#include "core/dom/Document.h"
#include "core/svg/SVGAnimatedTransformList.h"
-#include "core/svg/SVGFitToViewBox.h"
#include "core/svg/SVGParserUtilities.h"
-#include "core/svg/SVGSVGElement.h"
-#include "core/svg/SVGTransformable.h"
namespace WebCore {
@@ -77,7 +74,7 @@ const SVGPropertyInfo* SVGViewSpec::transformPropertyInfo()
return s_propertyInfo;
}
-SVGViewSpec::SVGViewSpec(SVGElement* contextElement)
+SVGViewSpec::SVGViewSpec(WeakPtr<SVGSVGElement> contextElement)
: m_contextElement(contextElement)
, m_zoomAndPan(SVGZoomAndPanMagnify)
{
@@ -103,10 +100,10 @@ const AtomicString& SVGViewSpec::transformIdentifier()
return s_identifier;
}
-void SVGViewSpec::setZoomAndPan(unsigned short, ExceptionState& es)
+void SVGViewSpec::setZoomAndPan(unsigned short, ExceptionState& exceptionState)
{
// SVGViewSpec and all of its content is read-only.
- es.throwDOMException(NoModificationAllowedError);
+ exceptionState.throwUninformativeAndGenericDOMException(NoModificationAllowedError);
}
void SVGViewSpec::setTransformString(const String& transform)
@@ -117,7 +114,7 @@ void SVGViewSpec::setTransformString(const String& transform)
SVGTransformList newList;
newList.parse(transform);
- if (SVGAnimatedProperty* wrapper = SVGAnimatedProperty::lookupWrapper<SVGElement, SVGAnimatedTransformList>(m_contextElement, transformPropertyInfo()))
+ if (SVGAnimatedProperty* wrapper = SVGAnimatedProperty::lookupWrapper<SVGElement, SVGAnimatedTransformList>(m_contextElement.get(), transformPropertyInfo()))
static_cast<SVGAnimatedTransformList*>(wrapper)->detachListWrappers(newList.size());
m_transform = newList;
@@ -130,7 +127,7 @@ String SVGViewSpec::transformString() const
String SVGViewSpec::viewBoxString() const
{
- return SVGPropertyTraits<FloatRect>::toString(viewBoxBaseValue());
+ return SVGPropertyTraits<SVGRect>::toString(viewBoxBaseValue());
}
String SVGViewSpec::preserveAspectRatioString() const
@@ -142,7 +139,7 @@ SVGElement* SVGViewSpec::viewTarget() const
{
if (!m_contextElement)
return 0;
- Element* element = m_contextElement->treeScope().getElementById(m_viewTargetString);
+ Element* element = m_contextElement.get()->treeScope().getElementById(m_viewTargetString);
if (!element || !element->isSVGElement())
return 0;
return toSVGElement(element);
@@ -174,7 +171,7 @@ PassRefPtr<SVGAnimatedProperty> SVGViewSpec::lookupOrCreateViewBoxWrapper(SVGVie
{
ASSERT(ownerType);
ASSERT(ownerType->contextElement());
- return SVGAnimatedProperty::lookupOrCreateWrapper<SVGElement, SVGAnimatedRect, FloatRect>(ownerType->contextElement(), viewBoxPropertyInfo(), ownerType->m_viewBox);
+ return SVGAnimatedProperty::lookupOrCreateWrapper<SVGElement, SVGAnimatedRect, SVGRect>(ownerType->contextElement(), viewBoxPropertyInfo(), ownerType->m_viewBox);
}
PassRefPtr<SVGAnimatedProperty> SVGViewSpec::lookupOrCreatePreserveAspectRatioWrapper(SVGViewSpec* ownerType)
@@ -195,7 +192,7 @@ void SVGViewSpec::reset()
{
m_zoomAndPan = SVGZoomAndPanMagnify;
m_transform.clear();
- m_viewBox = FloatRect();
+ m_viewBox = SVGRect();
m_preserveAspectRatio = SVGPreserveAspectRatio();
m_viewTargetString = emptyString();
}
@@ -223,8 +220,8 @@ bool SVGViewSpec::parseViewSpecInternal(const CharType* ptr, const CharType* end
if (ptr >= end || *ptr != '(')
return false;
ptr++;
- FloatRect viewBox;
- if (!SVGFitToViewBox::parseViewBox(&m_contextElement->document(), ptr, end, viewBox, false))
+ SVGRect viewBox;
+ if (!SVGFitToViewBox::parseViewBox(&m_contextElement.get()->document(), ptr, end, viewBox, false))
return false;
setViewBoxBaseValue(viewBox);
if (ptr >= end || *ptr != ')')
@@ -272,7 +269,7 @@ bool SVGViewSpec::parseViewSpecInternal(const CharType* ptr, const CharType* end
if (ptr >= end || *ptr != '(')
return false;
ptr++;
- SVGTransformable::parseTransformAttribute(m_transform, ptr, end, SVGTransformable::DoNotClearList);
+ parseTransformAttribute(m_transform, ptr, end, DoNotClearList);
if (ptr >= end || *ptr != ')')
return false;
ptr++;
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGViewSpec.h b/chromium/third_party/WebKit/Source/core/svg/SVGViewSpec.h
index fd90616ff21..c5d742f5daa 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGViewSpec.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGViewSpec.h
@@ -24,23 +24,22 @@
#include "core/svg/SVGAnimatedPreserveAspectRatio.h"
#include "core/svg/SVGAnimatedRect.h"
#include "core/svg/SVGFitToViewBox.h"
+#include "core/svg/SVGSVGElement.h"
#include "core/svg/SVGTransformList.h"
#include "core/svg/SVGZoomAndPan.h"
+#include "wtf/WeakPtr.h"
namespace WebCore {
class ExceptionState;
-class SVGElement;
class SVGTransformListPropertyTearOff;
-class SVGViewSpec : public RefCounted<SVGViewSpec>, public ScriptWrappable, public SVGZoomAndPan, public SVGFitToViewBox {
+class SVGViewSpec FINAL : public RefCounted<SVGViewSpec>, public ScriptWrappable, public SVGZoomAndPan, public SVGFitToViewBox {
public:
- virtual ~SVGViewSpec() { }
-
using RefCounted<SVGViewSpec>::ref;
using RefCounted<SVGViewSpec>::deref;
- static PassRefPtr<SVGViewSpec> create(SVGElement* contextElement)
+ static PassRefPtr<SVGViewSpec> create(WeakPtr<SVGSVGElement> contextElement)
{
return adoptRef(new SVGViewSpec(contextElement));
}
@@ -64,8 +63,7 @@ public:
void setZoomAndPan(unsigned short, ExceptionState&);
void setZoomAndPanBaseValue(unsigned short zoomAndPan) { m_zoomAndPan = SVGZoomAndPan::parseFromNumber(zoomAndPan); }
- SVGElement* contextElement() const { return m_contextElement; }
- void resetContextElement() { m_contextElement = 0; }
+ SVGElement* contextElement() const { return m_contextElement.get(); }
// Custom non-animated 'transform' property.
SVGTransformListPropertyTearOff* transform();
@@ -73,9 +71,9 @@ public:
// Custom animated 'viewBox' property.
PassRefPtr<SVGAnimatedRect> viewBox();
- FloatRect& viewBoxCurrentValue() { return m_viewBox; }
- FloatRect viewBoxBaseValue() const { return m_viewBox; }
- void setViewBoxBaseValue(const FloatRect& viewBox) { m_viewBox = viewBox; }
+ SVGRect& viewBoxCurrentValue() { return m_viewBox; }
+ SVGRect viewBoxBaseValue() const { return m_viewBox; }
+ void setViewBoxBaseValue(const SVGRect& viewBox) { m_viewBox = viewBox; }
// Custom animated 'preserveAspectRatio' property.
PassRefPtr<SVGAnimatedPreserveAspectRatio> preserveAspectRatio();
@@ -84,7 +82,7 @@ public:
void setPreserveAspectRatioBaseValue(const SVGPreserveAspectRatio& preserveAspectRatio) { m_preserveAspectRatio = preserveAspectRatio; }
private:
- explicit SVGViewSpec(SVGElement*);
+ explicit SVGViewSpec(WeakPtr<SVGSVGElement>);
static const SVGPropertyInfo* transformPropertyInfo();
static const SVGPropertyInfo* viewBoxPropertyInfo();
@@ -101,11 +99,11 @@ private:
template<typename CharType>
bool parseViewSpecInternal(const CharType* ptr, const CharType* end);
- SVGElement* m_contextElement;
- SVGZoomAndPanType m_zoomAndPan;
+ WeakPtr<SVGSVGElement> m_contextElement;
+ SVGZoomAndPanType m_zoomAndPan;
SVGTransformList m_transform;
- FloatRect m_viewBox;
+ SVGRect m_viewBox;
SVGPreserveAspectRatio m_preserveAspectRatio;
String m_viewTargetString;
};
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGViewSpec.idl b/chromium/third_party/WebKit/Source/core/svg/SVGViewSpec.idl
index ab57e7e01c6..80b1d809c44 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGViewSpec.idl
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGViewSpec.idl
@@ -32,7 +32,7 @@ interface SVGViewSpec {
readonly attribute DOMString viewTargetString;
// SVGZoomAndPan
- [SetterRaisesException] attribute unsigned short zoomAndPan;
+ [RaisesException=Setter] attribute unsigned short zoomAndPan;
};
SVGViewSpec implements SVGFitToViewBox;
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGZoomEvent.cpp b/chromium/third_party/WebKit/Source/core/svg/SVGZoomEvent.cpp
index f5403d6167c..fe5d283270f 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGZoomEvent.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGZoomEvent.cpp
@@ -20,11 +20,10 @@
*/
#include "config.h"
-
-
-#include "core/dom/EventNames.h"
#include "core/svg/SVGZoomEvent.h"
+#include "core/events/ThreadLocalEventNames.h"
+
namespace WebCore {
SVGZoomEvent::SVGZoomEvent()
@@ -71,7 +70,7 @@ SVGPoint SVGZoomEvent::newTranslate() const
const AtomicString& SVGZoomEvent::interfaceName() const
{
- return eventNames().interfaceForSVGZoomEvent;
+ return EventNames::SVGZoomEvent;
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/svg/SVGZoomEvent.h b/chromium/third_party/WebKit/Source/core/svg/SVGZoomEvent.h
index 9aecc4d6bf1..59d31ae0b14 100644
--- a/chromium/third_party/WebKit/Source/core/svg/SVGZoomEvent.h
+++ b/chromium/third_party/WebKit/Source/core/svg/SVGZoomEvent.h
@@ -22,7 +22,7 @@
#ifndef SVGZoomEvent_h
#define SVGZoomEvent_h
-#include "core/dom/UIEvent.h"
+#include "core/events/UIEvent.h"
#include "core/svg/SVGPoint.h"
#include "core/svg/SVGRect.h"
diff --git a/chromium/third_party/WebKit/Source/core/svg/animation/SMILTimeContainer.cpp b/chromium/third_party/WebKit/Source/core/svg/animation/SMILTimeContainer.cpp
index 08493279595..1ab6eda4342 100644
--- a/chromium/third_party/WebKit/Source/core/svg/animation/SMILTimeContainer.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/animation/SMILTimeContainer.cpp
@@ -228,8 +228,8 @@ void SMILTimeContainer::timerFired(Timer<SMILTimeContainer>*)
void SMILTimeContainer::updateDocumentOrderIndexes()
{
unsigned timingElementCount = 0;
- for (Element* element = m_ownerSVGElement; element; element = ElementTraversal::next(element, m_ownerSVGElement)) {
- if (SVGSMILElement::isSMILElement(element))
+ for (Element* element = m_ownerSVGElement; element; element = ElementTraversal::next(*element, m_ownerSVGElement)) {
+ if (isSVGSMILElement(*element))
toSVGSMILElement(element)->setDocumentOrderIndex(timingElementCount++);
}
m_documentOrderIndexesDirty = false;
@@ -273,15 +273,6 @@ void SMILTimeContainer::updateAnimations(SMILTime elapsed, bool seekToTime)
GroupedAnimationsMap::iterator end = m_scheduledAnimations.end();
for (GroupedAnimationsMap::iterator it = m_scheduledAnimations.begin(); it != end; ++it) {
AnimationsVector* scheduled = it->value.get();
- unsigned size = scheduled->size();
- for (unsigned n = 0; n < size; n++) {
- SVGSMILElement* animation = scheduled->at(n);
- animation->connectConditions();
- }
- }
-
- for (GroupedAnimationsMap::iterator it = m_scheduledAnimations.begin(); it != end; ++it) {
- AnimationsVector* scheduled = it->value.get();
// Sort according to priority. Elements with later begin time have higher priority.
// In case of a tie, document order decides.
@@ -298,6 +289,7 @@ void SMILTimeContainer::updateAnimations(SMILTime elapsed, bool seekToTime)
ASSERT(animation->hasValidAttributeName());
// Results are accumulated to the first animation that animates and contributes to a particular element/attribute pair.
+ // FIXME: we should ensure that resultElement is of an appropriate type.
if (!resultElement) {
if (!animation->hasValidAttributeType())
continue;
diff --git a/chromium/third_party/WebKit/Source/core/svg/animation/SMILTimeContainer.h b/chromium/third_party/WebKit/Source/core/svg/animation/SMILTimeContainer.h
index af3fb01b188..86b24ab46d1 100644
--- a/chromium/third_party/WebKit/Source/core/svg/animation/SMILTimeContainer.h
+++ b/chromium/third_party/WebKit/Source/core/svg/animation/SMILTimeContainer.h
@@ -27,8 +27,8 @@
#define SMILTimeContainer_h
#include "core/dom/QualifiedName.h"
-#include "core/platform/Timer.h"
#include "core/svg/animation/SMILTime.h"
+#include "platform/Timer.h"
#include "wtf/HashMap.h"
#include "wtf/HashSet.h"
#include "wtf/PassRefPtr.h"
diff --git a/chromium/third_party/WebKit/Source/core/svg/animation/SVGSMILElement.cpp b/chromium/third_party/WebKit/Source/core/svg/animation/SVGSMILElement.cpp
index e380e73d153..7dbc0aedd5b 100644
--- a/chromium/third_party/WebKit/Source/core/svg/animation/SVGSMILElement.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/animation/SVGSMILElement.cpp
@@ -30,13 +30,13 @@
#include "XLinkNames.h"
#include "bindings/v8/ExceptionStatePlaceholder.h"
#include "core/dom/Document.h"
-#include "core/dom/EventListener.h"
-#include "core/dom/EventSender.h"
-#include "core/platform/FloatConversion.h"
+#include "core/events/EventListener.h"
+#include "core/events/EventSender.h"
#include "core/svg/SVGDocumentExtensions.h"
#include "core/svg/SVGSVGElement.h"
#include "core/svg/SVGURIReference.h"
#include "core/svg/animation/SMILTimeContainer.h"
+#include "platform/FloatConversion.h"
#include "wtf/MathExtras.h"
#include "wtf/StdLibExtras.h"
#include "wtf/Vector.h"
@@ -127,7 +127,7 @@ private:
{
}
- virtual void handleEvent(ScriptExecutionContext*, Event*);
+ virtual void handleEvent(ExecutionContext*, Event*);
SVGSMILElement* m_animation;
SVGSMILElement::Condition* m_condition;
@@ -140,7 +140,7 @@ bool ConditionEventListener::operator==(const EventListener& listener)
return false;
}
-void ConditionEventListener::handleEvent(ScriptExecutionContext*, Event* event)
+void ConditionEventListener::handleEvent(ExecutionContext*, Event* event)
{
if (!m_animation)
return;
@@ -239,7 +239,7 @@ void SVGSMILElement::buildPendingResource()
}
}
-static inline QualifiedName constructQualifiedName(const SVGElement* svgElement, const String& attributeName)
+static inline QualifiedName constructQualifiedName(const SVGElement* svgElement, const AtomicString& attributeName)
{
ASSERT(svgElement);
if (attributeName.isEmpty())
@@ -247,12 +247,12 @@ static inline QualifiedName constructQualifiedName(const SVGElement* svgElement,
if (!attributeName.contains(':'))
return QualifiedName(nullAtom, attributeName, nullAtom);
- String prefix;
- String localName;
+ AtomicString prefix;
+ AtomicString localName;
if (!Document::parseQualifiedName(attributeName, prefix, localName, ASSERT_NO_EXCEPTION))
return anyQName();
- String namespaceURI = svgElement->lookupNamespaceURI(prefix);
+ const AtomicString& namespaceURI = svgElement->lookupNamespaceURI(prefix);
if (namespaceURI.isEmpty())
return anyQName();
@@ -460,14 +460,6 @@ bool SVGSMILElement::parseCondition(const String& value, BeginOrEnd beginOrEnd)
return true;
}
-bool SVGSMILElement::isSMILElement(Node* node)
-{
- if (!node)
- return false;
- return node->hasTagName(SVGNames::setTag) || node->hasTagName(SVGNames::animateTag) || node->hasTagName(SVGNames::animateMotionTag)
- || node->hasTagName(SVGNames::animateTransformTag) || node->hasTagName(SVGNames::animateColorTag);
-}
-
void SVGSMILElement::parseBeginOrEnd(const String& parseString, BeginOrEnd beginOrEnd)
{
Vector<SMILTimeWithOrigin>& timeList = beginOrEnd == Begin ? m_beginTimes : m_endTimes;
@@ -551,6 +543,8 @@ void SVGSMILElement::svgAttributeChanged(const QualifiedName& attrName)
else if (attrName.matches(XLinkNames::hrefAttr)) {
SVGElementInstance::InvalidationGuard invalidationGuard(this);
buildPendingResource();
+ if (m_targetElement)
+ clearAnimatedType(m_targetElement);
} else if (inDocument()) {
if (attrName == SVGNames::beginAttr)
beginListChanged(elapsed());
@@ -584,7 +578,7 @@ void SVGSMILElement::connectConditions()
} else if (condition.m_type == Condition::Syncbase) {
ASSERT(!condition.m_baseID.isEmpty());
condition.m_syncbase = treeScope().getElementById(condition.m_baseID);
- if (!isSMILElement(condition.m_syncbase.get())) {
+ if (!condition.m_syncbase || !isSVGSMILElement(*condition.m_syncbase)) {
condition.m_syncbase = 0;
continue;
}
@@ -896,10 +890,9 @@ void SVGSMILElement::resolveFirstInterval()
ASSERT(!begin.isIndefinite());
if (!begin.isUnresolved() && (begin != m_intervalBegin || end != m_intervalEnd)) {
- bool wasUnresolved = m_intervalBegin.isUnresolved();
m_intervalBegin = begin;
m_intervalEnd = end;
- notifyDependentsIntervalChanged(wasUnresolved ? NewInterval : ExistingInterval);
+ notifyDependentsIntervalChanged();
m_nextProgressTime = min(m_nextProgressTime, m_intervalBegin);
if (m_timeContainer)
@@ -907,7 +900,7 @@ void SVGSMILElement::resolveFirstInterval()
}
}
-bool SVGSMILElement::resolveNextInterval(bool notifyDependents)
+bool SVGSMILElement::resolveNextInterval()
{
SMILTime begin;
SMILTime end;
@@ -917,8 +910,7 @@ bool SVGSMILElement::resolveNextInterval(bool notifyDependents)
if (!begin.isUnresolved() && begin != m_intervalBegin) {
m_intervalBegin = begin;
m_intervalEnd = end;
- if (notifyDependents)
- notifyDependentsIntervalChanged(NewInterval);
+ notifyDependentsIntervalChanged();
m_nextProgressTime = min(m_nextProgressTime, m_intervalBegin);
return true;
}
@@ -949,7 +941,7 @@ void SVGSMILElement::beginListChanged(SMILTime eventTime)
if (m_activeState != Active)
endedActiveInterval();
}
- notifyDependentsIntervalChanged(ExistingInterval);
+ notifyDependentsIntervalChanged();
}
}
}
@@ -970,7 +962,7 @@ void SVGSMILElement::endListChanged(SMILTime)
newEnd = resolveActiveEnd(m_intervalBegin, newEnd);
if (newEnd != m_intervalEnd) {
m_intervalEnd = newEnd;
- notifyDependentsIntervalChanged(ExistingInterval);
+ notifyDependentsIntervalChanged();
}
}
}
@@ -995,12 +987,12 @@ void SVGSMILElement::checkRestart(SMILTime elapsed)
SMILTime nextBegin = findInstanceTime(Begin, m_intervalBegin, false);
if (nextBegin < m_intervalEnd) {
m_intervalEnd = nextBegin;
- notifyDependentsIntervalChanged(ExistingInterval);
+ notifyDependentsIntervalChanged();
}
}
if (elapsed >= m_intervalEnd)
- resolveNextInterval(true);
+ resolveNextInterval();
}
void SVGSMILElement::seekToIntervalCorrespondingToTime(SMILTime elapsed)
@@ -1022,14 +1014,14 @@ void SVGSMILElement::seekToIntervalCorrespondingToTime(SMILTime elapsed)
if (nextBegin < m_intervalEnd && elapsed >= nextBegin) {
// End current interval, and start a new interval from the 'nextBegin' time.
m_intervalEnd = nextBegin;
- if (!resolveNextInterval(false))
+ if (!resolveNextInterval())
break;
continue;
}
// If the desired 'elapsed' time is past the current interval, advance to the next.
if (elapsed >= m_intervalEnd) {
- if (!resolveNextInterval(false))
+ if (!resolveNextInterval())
break;
continue;
}
@@ -1108,6 +1100,9 @@ bool SVGSMILElement::progress(SMILTime elapsed, SVGSMILElement* resultElement, b
ASSERT(m_timeContainer);
ASSERT(m_isWaitingForFirstInterval || m_intervalBegin.isFinite());
+ if (!m_conditionsConnected)
+ connectConditions();
+
if (!m_intervalBegin.isFinite()) {
ASSERT(m_activeState == Inactive);
m_nextProgressTime = SMILTime::unresolved();
@@ -1195,7 +1190,7 @@ bool SVGSMILElement::progress(SMILTime elapsed, SVGSMILElement* resultElement, b
return animationIsContributing;
}
-void SVGSMILElement::notifyDependentsIntervalChanged(NewOrExistingInterval newOrExisting)
+void SVGSMILElement::notifyDependentsIntervalChanged()
{
ASSERT(m_intervalBegin.isFinite());
DEFINE_STATIC_LOCAL(HashSet<SVGSMILElement*>, loopBreaker, ());
@@ -1205,13 +1200,13 @@ void SVGSMILElement::notifyDependentsIntervalChanged(NewOrExistingInterval newOr
TimeDependentSet::iterator end = m_timeDependents.end();
for (TimeDependentSet::iterator it = m_timeDependents.begin(); it != end; ++it) {
SVGSMILElement* dependent = *it;
- dependent->createInstanceTimesFromSyncbase(this, newOrExisting);
+ dependent->createInstanceTimesFromSyncbase(this);
}
loopBreaker.remove(this);
}
-void SVGSMILElement::createInstanceTimesFromSyncbase(SVGSMILElement* syncbase, NewOrExistingInterval)
+void SVGSMILElement::createInstanceTimesFromSyncbase(SVGSMILElement* syncbase)
{
// FIXME: To be really correct, this should handle updating exising interval by changing
// the associated times instead of creating new ones.
@@ -1238,7 +1233,7 @@ void SVGSMILElement::addTimeDependent(SVGSMILElement* animation)
{
m_timeDependents.add(animation);
if (m_intervalBegin.isFinite())
- animation->createInstanceTimesFromSyncbase(this, NewInterval);
+ animation->createInstanceTimesFromSyncbase(this);
}
void SVGSMILElement::removeTimeDependent(SVGSMILElement* animation)
diff --git a/chromium/third_party/WebKit/Source/core/svg/animation/SVGSMILElement.h b/chromium/third_party/WebKit/Source/core/svg/animation/SVGSMILElement.h
index e9d5e0560b5..44c4fa19a47 100644
--- a/chromium/third_party/WebKit/Source/core/svg/animation/SVGSMILElement.h
+++ b/chromium/third_party/WebKit/Source/core/svg/animation/SVGSMILElement.h
@@ -26,6 +26,7 @@
#ifndef SVGSMILElement_h
#define SVGSMILElement_h
+#include "SVGNames.h"
#include "core/svg/SVGElement.h"
#include "core/svg/animation/SMILTime.h"
#include "wtf/HashMap.h"
@@ -45,8 +46,6 @@ public:
SVGSMILElement(const QualifiedName&, Document&);
virtual ~SVGSMILElement();
- static bool isSMILElement(Node*);
-
bool isSupportedAttribute(const QualifiedName&);
virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
virtual void svgAttributeChanged(const QualifiedName&) OVERRIDE;
@@ -145,7 +144,7 @@ private:
SMILTime findInstanceTime(BeginOrEnd, SMILTime minimumTime, bool equalsMinimumOK) const;
void resolveFirstInterval();
- bool resolveNextInterval(bool notifyDependents);
+ bool resolveNextInterval();
void resolveInterval(bool first, SMILTime& beginResult, SMILTime& endResult) const;
SMILTime resolveActiveEnd(SMILTime resolvedBegin, SMILTime resolvedEnd) const;
SMILTime repeatingDuration() const;
@@ -181,14 +180,8 @@ private:
// Event base timing
void handleConditionEvent(Event*, Condition*);
- // Syncbase timing
- enum NewOrExistingInterval {
- NewInterval,
- ExistingInterval
- };
-
- void notifyDependentsIntervalChanged(NewOrExistingInterval);
- void createInstanceTimesFromSyncbase(SVGSMILElement* syncbase, NewOrExistingInterval);
+ void notifyDependentsIntervalChanged();
+ void createInstanceTimesFromSyncbase(SVGSMILElement* syncbase);
void addTimeDependent(SVGSMILElement*);
void removeTimeDependent(SVGSMILElement*);
@@ -245,12 +238,14 @@ private:
friend class ConditionEventListener;
};
-inline SVGSMILElement* toSVGSMILElement(Element* element)
+inline bool isSVGSMILElement(const Node& node)
{
- ASSERT_WITH_SECURITY_IMPLICATION(!element || SVGSMILElement::isSMILElement(element));
- return static_cast<SVGSMILElement*>(element);
+ return node.hasTagName(SVGNames::setTag) || node.hasTagName(SVGNames::animateTag) || node.hasTagName(SVGNames::animateMotionTag)
+ || node.hasTagName(SVGNames::animateTransformTag) || node.hasTagName(SVGNames::animateColorTag);
}
+DEFINE_NODE_TYPE_CASTS_WITH_FUNCTION(SVGSMILElement);
+
}
#endif // SVGSMILElement_h
diff --git a/chromium/third_party/WebKit/Source/core/svg/graphics/SVGImage.cpp b/chromium/third_party/WebKit/Source/core/svg/graphics/SVGImage.cpp
index e44c11b76c7..5526ab7ebf2 100644
--- a/chromium/third_party/WebKit/Source/core/svg/graphics/SVGImage.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/graphics/SVGImage.cpp
@@ -33,13 +33,9 @@
#include "core/dom/shadow/ComposedTreeWalker.h"
#include "core/loader/DocumentLoader.h"
#include "core/page/Chrome.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameView.h"
-#include "core/page/Settings.h"
-#include "core/platform/graphics/GraphicsContextStateSaver.h"
-#include "core/platform/graphics/ImageBuffer.h"
-#include "core/platform/graphics/ImageObserver.h"
-#include "core/platform/graphics/IntRect.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
+#include "core/frame/Settings.h"
#include "core/rendering/style/RenderStyle.h"
#include "core/rendering/svg/RenderSVGRoot.h"
#include "core/svg/SVGDocument.h"
@@ -47,6 +43,11 @@
#include "core/svg/SVGImageElement.h"
#include "core/svg/SVGSVGElement.h"
#include "core/svg/graphics/SVGImageChromeClient.h"
+#include "platform/LengthFunctions.h"
+#include "platform/geometry/IntRect.h"
+#include "platform/graphics/GraphicsContextStateSaver.h"
+#include "platform/graphics/ImageBuffer.h"
+#include "platform/graphics/ImageObserver.h"
#include "wtf/PassRefPtr.h"
namespace WebCore {
@@ -61,7 +62,7 @@ SVGImage::~SVGImage()
if (m_page) {
// Store m_page in a local variable, clearing m_page, so that SVGImageChromeClient knows we're destructed.
OwnPtr<Page> currentPage = m_page.release();
- currentPage->mainFrame()->loader()->frameDetached(); // Break both the loader and view references to the frame
+ currentPage->mainFrame()->loader().frameDetached(); // Break both the loader and view references to the frame
}
// Verify that page teardown destroyed the Chrome
@@ -119,13 +120,13 @@ void SVGImage::setContainerSize(const IntSize& size)
SVGSVGElement* rootElement = toSVGDocument(frame->document())->rootElement();
if (!rootElement)
return;
- RenderSVGRoot* renderer = toRenderSVGRoot(rootElement->renderer());
- if (!renderer)
- return;
FrameView* view = frameView();
view->resize(this->containerSize());
+ RenderSVGRoot* renderer = toRenderSVGRoot(rootElement->renderer());
+ if (!renderer)
+ return;
renderer->setContainerSize(size);
}
@@ -164,7 +165,7 @@ IntSize SVGImage::containerSize() const
}
void SVGImage::drawForContainer(GraphicsContext* context, const FloatSize containerSize, float zoom, const FloatRect& dstRect,
- const FloatRect& srcRect, CompositeOperator compositeOp, BlendMode blendMode)
+ const FloatRect& srcRect, CompositeOperator compositeOp, blink::WebBlendMode blendMode)
{
if (!m_page)
return;
@@ -191,18 +192,18 @@ PassRefPtr<NativeImageSkia> SVGImage::nativeImageForCurrentFrame()
if (!m_page)
return 0;
- OwnPtr<ImageBuffer> buffer = ImageBuffer::create(size(), 1);
- if (!buffer) // failed to allocate image
+ OwnPtr<ImageBuffer> buffer = ImageBuffer::create(size());
+ if (!buffer)
return 0;
- drawForContainer(buffer->context(), size(), 1, rect(), rect(), CompositeSourceOver, BlendModeNormal);
+ drawForContainer(buffer->context(), size(), 1, rect(), rect(), CompositeSourceOver, blink::WebBlendModeNormal);
// FIXME: WK(Bug 113657): We should use DontCopyBackingStore here.
return buffer->copyImage(CopyBackingStore)->nativeImageForCurrentFrame();
}
void SVGImage::drawPatternForContainer(GraphicsContext* context, const FloatSize containerSize, float zoom, const FloatRect& srcRect,
- const FloatSize& scale, const FloatPoint& phase, CompositeOperator compositeOp, const FloatRect& dstRect, BlendMode blendMode)
+ const FloatSize& scale, const FloatPoint& phase, CompositeOperator compositeOp, const FloatRect& dstRect, blink::WebBlendMode blendMode, const IntSize& repeatSpacing)
{
FloatRect zoomedContainerRect = FloatRect(FloatPoint(), containerSize);
zoomedContainerRect.scale(zoom);
@@ -219,20 +220,21 @@ void SVGImage::drawPatternForContainer(GraphicsContext* context, const FloatSize
FloatRect imageBufferSize = zoomedContainerRect;
imageBufferSize.scale(imageBufferScale.width(), imageBufferScale.height());
- OwnPtr<ImageBuffer> buffer = ImageBuffer::create(expandedIntSize(imageBufferSize.size()), 1);
+ OwnPtr<ImageBuffer> buffer = ImageBuffer::create(expandedIntSize(imageBufferSize.size()));
if (!buffer) // Failed to allocate buffer.
return;
- drawForContainer(buffer->context(), containerSize, zoom, imageBufferSize, zoomedContainerRect, CompositeSourceOver, BlendModeNormal);
+
+ drawForContainer(buffer->context(), containerSize, zoom, imageBufferSize, zoomedContainerRect, CompositeSourceOver, blink::WebBlendModeNormal);
RefPtr<Image> image = buffer->copyImage(DontCopyBackingStore, Unscaled);
// Adjust the source rect and transform due to the image buffer's scaling.
FloatRect scaledSrcRect = srcRect;
scaledSrcRect.scale(imageBufferScale.width(), imageBufferScale.height());
- image->drawPattern(context, scaledSrcRect, scaleWithoutCTM, phase, compositeOp, dstRect, blendMode);
+ image->drawPattern(context, scaledSrcRect, scaleWithoutCTM, phase, compositeOp, dstRect, blendMode, repeatSpacing);
}
-void SVGImage::draw(GraphicsContext* context, const FloatRect& dstRect, const FloatRect& srcRect, CompositeOperator compositeOp, BlendMode blendMode)
+void SVGImage::draw(GraphicsContext* context, const FloatRect& dstRect, const FloatRect& srcRect, CompositeOperator compositeOp, blink::WebBlendMode blendMode)
{
if (!m_page)
return;
@@ -361,6 +363,8 @@ void SVGImage::resetAnimation()
bool SVGImage::dataChanged(bool allDataReceived)
{
+ TRACE_EVENT0("webkit", "SVGImage::dataChanged");
+
// Don't do anything if is an empty image.
if (!data()->size())
return true;
@@ -385,20 +389,20 @@ bool SVGImage::dataChanged(bool allDataReceived)
m_page->settings().setPluginsEnabled(false);
m_page->settings().setAcceleratedCompositingEnabled(false);
- RefPtr<Frame> frame = Frame::create(m_page.get(), 0, dummyFrameLoaderClient);
+ RefPtr<Frame> frame = Frame::create(FrameInit::create(0, m_page.get(), dummyFrameLoaderClient));
frame->setView(FrameView::create(frame.get()));
frame->init();
- FrameLoader* loader = frame->loader();
- loader->forceSandboxFlags(SandboxAll);
+ FrameLoader& loader = frame->loader();
+ loader.forceSandboxFlags(SandboxAll);
frame->view()->setScrollbarsSuppressed(true);
frame->view()->setCanHaveScrollbars(false); // SVG Images will always synthesize a viewBox, if it's not available, and thus never see scrollbars.
frame->view()->setTransparent(true); // SVG Images are transparent.
- ASSERT(loader->activeDocumentLoader()); // DocumentLoader should have been created by frame->init().
- DocumentWriter* writer = loader->activeDocumentLoader()->beginWriting("image/svg+xml", "UTF-8");
+ ASSERT(loader.activeDocumentLoader()); // DocumentLoader should have been created by frame->init().
+ DocumentWriter* writer = loader.activeDocumentLoader()->beginWriting("image/svg+xml", "UTF-8");
writer->addData(data()->data(), data()->size());
- loader->activeDocumentLoader()->endWriting(writer);
+ loader.activeDocumentLoader()->endWriting(writer);
// Set the intrinsic size before a container size is available.
m_intrinsicSize = containerSize();
}
diff --git a/chromium/third_party/WebKit/Source/core/svg/graphics/SVGImage.h b/chromium/third_party/WebKit/Source/core/svg/graphics/SVGImage.h
index b75dd70e29e..19838c9e31d 100644
--- a/chromium/third_party/WebKit/Source/core/svg/graphics/SVGImage.h
+++ b/chromium/third_party/WebKit/Source/core/svg/graphics/SVGImage.h
@@ -27,7 +27,7 @@
#ifndef SVGImage_h
#define SVGImage_h
-#include "core/platform/graphics/Image.h"
+#include "platform/graphics/Image.h"
namespace WebCore {
@@ -65,7 +65,7 @@ public:
virtual PassRefPtr<NativeImageSkia> nativeImageForCurrentFrame() OVERRIDE;
private:
- friend class AccessibilityRenderObject;
+ friend class AXRenderObject;
friend class SVGImageChromeClient;
friend class SVGImageForContainer;
@@ -86,27 +86,22 @@ private:
// FIXME: SVGImages are underreporting decoded sizes and will be unable
// to prune because these functions are not implemented yet.
virtual void destroyDecodedData(bool) OVERRIDE { }
- virtual unsigned decodedSize() const OVERRIDE { return 0; }
// FIXME: Implement this to be less conservative.
virtual bool currentFrameKnownToBeOpaque() OVERRIDE { return false; }
SVGImage(ImageObserver*);
- virtual void draw(GraphicsContext*, const FloatRect& fromRect, const FloatRect& toRect, CompositeOperator, BlendMode) OVERRIDE;
- void drawForContainer(GraphicsContext*, const FloatSize, float, const FloatRect&, const FloatRect&, CompositeOperator, BlendMode);
+ virtual void draw(GraphicsContext*, const FloatRect& fromRect, const FloatRect& toRect, CompositeOperator, blink::WebBlendMode) OVERRIDE;
+ void drawForContainer(GraphicsContext*, const FloatSize, float, const FloatRect&, const FloatRect&, CompositeOperator, blink::WebBlendMode);
void drawPatternForContainer(GraphicsContext*, const FloatSize, float, const FloatRect&, const FloatSize&, const FloatPoint&,
- CompositeOperator, const FloatRect&, BlendMode);
+ CompositeOperator, const FloatRect&, blink::WebBlendMode, const IntSize& repeatSpacing);
OwnPtr<SVGImageChromeClient> m_chromeClient;
OwnPtr<Page> m_page;
IntSize m_intrinsicSize;
};
-inline SVGImage* toSVGImage(Image* image)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!image || image->isSVGImage());
- return static_cast<SVGImage*>(image);
-}
+DEFINE_IMAGE_TYPE_CASTS(SVGImage);
class ImageObserverDisabler {
WTF_MAKE_NONCOPYABLE(ImageObserverDisabler);
diff --git a/chromium/third_party/WebKit/Source/core/svg/graphics/SVGImageCache.cpp b/chromium/third_party/WebKit/Source/core/svg/graphics/SVGImageCache.cpp
index 81153b3739e..059bbb42b4f 100644
--- a/chromium/third_party/WebKit/Source/core/svg/graphics/SVGImageCache.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/graphics/SVGImageCache.cpp
@@ -22,13 +22,13 @@
#include "core/svg/graphics/SVGImageCache.h"
#include "core/fetch/ImageResource.h"
-#include "core/page/FrameView.h"
+#include "core/frame/FrameView.h"
#include "core/page/Page.h"
-#include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/graphics/ImageBuffer.h"
#include "core/rendering/svg/RenderSVGRoot.h"
#include "core/svg/graphics/SVGImage.h"
#include "core/svg/graphics/SVGImageForContainer.h"
+#include "platform/graphics/GraphicsContext.h"
+#include "platform/graphics/ImageBuffer.h"
namespace WebCore {
@@ -46,9 +46,7 @@ SVGImageCache::~SVGImageCache()
void SVGImageCache::removeClientFromCache(const ImageResourceClient* client)
{
ASSERT(client);
-
- if (m_imageForContainerMap.contains(client))
- m_imageForContainerMap.remove(client);
+ m_imageForContainerMap.remove(client);
}
void SVGImageCache::setContainerSizeForRenderer(const ImageResourceClient* client, const IntSize& containerSize, float containerZoom)
diff --git a/chromium/third_party/WebKit/Source/core/svg/graphics/SVGImageCache.h b/chromium/third_party/WebKit/Source/core/svg/graphics/SVGImageCache.h
index b2aef4ce377..0559062ba78 100644
--- a/chromium/third_party/WebKit/Source/core/svg/graphics/SVGImageCache.h
+++ b/chromium/third_party/WebKit/Source/core/svg/graphics/SVGImageCache.h
@@ -20,9 +20,9 @@
#ifndef SVGImageCache_h
#define SVGImageCache_h
-#include "core/platform/graphics/FloatSize.h"
-#include "core/platform/graphics/Image.h"
-#include "core/platform/graphics/IntSize.h"
+#include "platform/geometry/FloatSize.h"
+#include "platform/geometry/IntSize.h"
+#include "platform/graphics/Image.h"
#include "wtf/HashMap.h"
#include "wtf/PassOwnPtr.h"
#include "wtf/RefPtr.h"
diff --git a/chromium/third_party/WebKit/Source/core/svg/graphics/SVGImageChromeClient.h b/chromium/third_party/WebKit/Source/core/svg/graphics/SVGImageChromeClient.h
index b17ca84a17b..76a4a9c56be 100644
--- a/chromium/third_party/WebKit/Source/core/svg/graphics/SVGImageChromeClient.h
+++ b/chromium/third_party/WebKit/Source/core/svg/graphics/SVGImageChromeClient.h
@@ -30,7 +30,7 @@
#define SVGImageChromeClient_h
#include "core/loader/EmptyClients.h"
-#include "core/platform/graphics/ImageObserver.h"
+#include "platform/graphics/ImageObserver.h"
namespace WebCore {
@@ -61,11 +61,7 @@ private:
SVGImage* m_image;
};
-inline SVGImageChromeClient* toSVGImageChromeClient(ChromeClient* client)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!client || client->isSVGImageChromeClient());
- return static_cast<SVGImageChromeClient*>(client);
-}
+DEFINE_TYPE_CASTS(SVGImageChromeClient, ChromeClient, client, client->isSVGImageChromeClient(), client.isSVGImageChromeClient());
}
diff --git a/chromium/third_party/WebKit/Source/core/svg/graphics/SVGImageForContainer.cpp b/chromium/third_party/WebKit/Source/core/svg/graphics/SVGImageForContainer.cpp
index 27f9a94447a..96a0080d48c 100644
--- a/chromium/third_party/WebKit/Source/core/svg/graphics/SVGImageForContainer.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/graphics/SVGImageForContainer.cpp
@@ -20,10 +20,9 @@
#include "config.h"
#include "core/svg/graphics/SVGImageForContainer.h"
-#include "core/platform/graphics/FloatRect.h"
-#include "core/platform/graphics/FloatSize.h"
-#include "core/platform/graphics/Image.h"
#include "core/svg/graphics/SVGImage.h"
+#include "platform/geometry/FloatRect.h"
+#include "platform/geometry/FloatSize.h"
#include "wtf/PassRefPtr.h"
namespace WebCore {
@@ -36,15 +35,15 @@ IntSize SVGImageForContainer::size() const
}
void SVGImageForContainer::draw(GraphicsContext* context, const FloatRect& dstRect,
- const FloatRect& srcRect, CompositeOperator compositeOp, BlendMode blendMode)
+ const FloatRect& srcRect, CompositeOperator compositeOp, blink::WebBlendMode blendMode)
{
m_image->drawForContainer(context, m_containerSize, m_zoom, dstRect, srcRect, compositeOp, blendMode);
}
void SVGImageForContainer::drawPattern(GraphicsContext* context, const FloatRect& srcRect, const FloatSize& scale,
- const FloatPoint& phase, CompositeOperator compositeOp, const FloatRect& dstRect, BlendMode blendMode)
+ const FloatPoint& phase, CompositeOperator compositeOp, const FloatRect& dstRect, blink::WebBlendMode blendMode, const IntSize& repeatSpacing)
{
- m_image->drawPatternForContainer(context, m_containerSize, m_zoom, srcRect, scale, phase, compositeOp, dstRect, blendMode);
+ m_image->drawPatternForContainer(context, m_containerSize, m_zoom, srcRect, scale, phase, compositeOp, dstRect, blendMode, repeatSpacing);
}
PassRefPtr<NativeImageSkia> SVGImageForContainer::nativeImageForCurrentFrame()
diff --git a/chromium/third_party/WebKit/Source/core/svg/graphics/SVGImageForContainer.h b/chromium/third_party/WebKit/Source/core/svg/graphics/SVGImageForContainer.h
index a90f652d012..4ea589eec44 100644
--- a/chromium/third_party/WebKit/Source/core/svg/graphics/SVGImageForContainer.h
+++ b/chromium/third_party/WebKit/Source/core/svg/graphics/SVGImageForContainer.h
@@ -26,10 +26,10 @@
#ifndef SVGImageForContainer_h
#define SVGImageForContainer_h
-#include "core/platform/graphics/FloatRect.h"
-#include "core/platform/graphics/FloatSize.h"
-#include "core/platform/graphics/Image.h"
#include "core/svg/graphics/SVGImage.h"
+#include "platform/geometry/FloatRect.h"
+#include "platform/geometry/FloatSize.h"
+#include "platform/graphics/Image.h"
namespace WebCore {
@@ -52,9 +52,9 @@ public:
m_image->computeIntrinsicDimensions(intrinsicWidth, intrinsicHeight, intrinsicRatio);
}
- virtual void draw(GraphicsContext*, const FloatRect&, const FloatRect&, CompositeOperator, BlendMode) OVERRIDE;
+ virtual void draw(GraphicsContext*, const FloatRect&, const FloatRect&, CompositeOperator, blink::WebBlendMode) OVERRIDE;
- virtual void drawPattern(GraphicsContext*, const FloatRect&, const FloatSize&, const FloatPoint&, CompositeOperator, const FloatRect&, BlendMode) OVERRIDE;
+ virtual void drawPattern(GraphicsContext*, const FloatRect&, const FloatSize&, const FloatPoint&, CompositeOperator, const FloatRect&, blink::WebBlendMode, const IntSize& repeatSpacing) OVERRIDE;
// FIXME: Implement this to be less conservative.
virtual bool currentFrameKnownToBeOpaque() OVERRIDE { return false; }
@@ -70,7 +70,6 @@ private:
}
virtual void destroyDecodedData(bool) OVERRIDE { }
- virtual unsigned decodedSize() const OVERRIDE { return 0; }
SVGImage* m_image;
const FloatSize m_containerSize;
diff --git a/chromium/third_party/WebKit/Source/core/svg/graphics/filters/SVGFEImage.cpp b/chromium/third_party/WebKit/Source/core/svg/graphics/filters/SVGFEImage.cpp
index f61a702fc56..ab2d6ca4e97 100644
--- a/chromium/third_party/WebKit/Source/core/svg/graphics/filters/SVGFEImage.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/graphics/filters/SVGFEImage.cpp
@@ -26,16 +26,14 @@
#include "core/svg/graphics/filters/SVGFEImage.h"
#include "SkBitmapSource.h"
-#include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/graphics/filters/Filter.h"
-#include "core/platform/graphics/transforms/AffineTransform.h"
-#include "core/platform/text/TextStream.h"
#include "core/rendering/RenderObject.h"
-#include "core/rendering/RenderTreeAsText.h"
#include "core/rendering/svg/SVGRenderingContext.h"
#include "core/svg/SVGElement.h"
-#include "core/svg/SVGPreserveAspectRatio.h"
#include "core/svg/SVGURIReference.h"
+#include "platform/graphics/GraphicsContext.h"
+#include "platform/graphics/filters/Filter.h"
+#include "platform/text/TextStream.h"
+#include "platform/transforms/AffineTransform.h"
namespace WebCore {
@@ -122,13 +120,12 @@ void FEImage::applySoftware()
SVGElement* contextNode = toSVGElement(renderer->node());
if (contextNode->hasRelativeLengths()) {
SVGLengthContext lengthContext(contextNode);
- float width = 0;
- float height = 0;
+ FloatSize viewportSize;
// If we're referencing an element with percentage units, eg. <rect with="30%"> those values were resolved against the viewport.
// Build up a transformation that maps from the viewport space to the filter primitive subregion.
- if (lengthContext.determineViewport(width, height))
- resultImage->context()->concatCTM(makeMapBetweenRects(FloatRect(0, 0, width, height), destRect));
+ if (lengthContext.determineViewport(viewportSize))
+ resultImage->context()->concatCTM(makeMapBetweenRects(FloatRect(FloatPoint(), viewportSize), destRect));
} else {
const AffineTransform& absoluteTransform = filter()->absoluteTransform();
resultImage->context()->concatCTM(absoluteTransform);
diff --git a/chromium/third_party/WebKit/Source/core/svg/graphics/filters/SVGFEImage.h b/chromium/third_party/WebKit/Source/core/svg/graphics/filters/SVGFEImage.h
index 3f755418bad..b82f673b7a5 100644
--- a/chromium/third_party/WebKit/Source/core/svg/graphics/filters/SVGFEImage.h
+++ b/chromium/third_party/WebKit/Source/core/svg/graphics/filters/SVGFEImage.h
@@ -24,7 +24,7 @@
#ifndef SVGFEImage_h
#define SVGFEImage_h
-#include "core/platform/graphics/filters/FilterEffect.h"
+#include "platform/graphics/filters/FilterEffect.h"
#include "core/svg/SVGPreserveAspectRatio.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/svg/graphics/filters/SVGFilter.h b/chromium/third_party/WebKit/Source/core/svg/graphics/filters/SVGFilter.h
index d140541d7c5..ad30b39218c 100644
--- a/chromium/third_party/WebKit/Source/core/svg/graphics/filters/SVGFilter.h
+++ b/chromium/third_party/WebKit/Source/core/svg/graphics/filters/SVGFilter.h
@@ -21,11 +21,11 @@
#ifndef SVGFilter_h
#define SVGFilter_h
-#include "core/platform/graphics/FloatRect.h"
-#include "core/platform/graphics/FloatSize.h"
-#include "core/platform/graphics/filters/Filter.h"
-#include "core/platform/graphics/filters/FilterEffect.h"
-#include "core/platform/graphics/transforms/AffineTransform.h"
+#include "platform/geometry/FloatRect.h"
+#include "platform/geometry/FloatSize.h"
+#include "platform/graphics/filters/Filter.h"
+#include "platform/graphics/filters/FilterEffect.h"
+#include "platform/transforms/AffineTransform.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefCounted.h"
#include "wtf/RefPtr.h"
diff --git a/chromium/third_party/WebKit/Source/core/svg/graphics/filters/SVGFilterBuilder.cpp b/chromium/third_party/WebKit/Source/core/svg/graphics/filters/SVGFilterBuilder.cpp
index 084203f52c1..fec801263c6 100644
--- a/chromium/third_party/WebKit/Source/core/svg/graphics/filters/SVGFilterBuilder.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/graphics/filters/SVGFilterBuilder.cpp
@@ -20,11 +20,8 @@
#include "config.h"
#include "core/svg/graphics/filters/SVGFilterBuilder.h"
-#include "core/platform/graphics/filters/FilterEffect.h"
-#include "core/platform/graphics/filters/SourceAlpha.h"
-#include "core/platform/graphics/filters/SourceGraphic.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/text/WTFString.h"
+#include "platform/graphics/filters/SourceAlpha.h"
+#include "platform/graphics/filters/SourceGraphic.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/svg/graphics/filters/SVGFilterBuilder.h b/chromium/third_party/WebKit/Source/core/svg/graphics/filters/SVGFilterBuilder.h
index f879aca9a74..00482d3bb1c 100644
--- a/chromium/third_party/WebKit/Source/core/svg/graphics/filters/SVGFilterBuilder.h
+++ b/chromium/third_party/WebKit/Source/core/svg/graphics/filters/SVGFilterBuilder.h
@@ -21,7 +21,7 @@
#ifndef SVGFilterBuilder_h
#define SVGFilterBuilder_h
-#include "core/platform/graphics/filters/FilterEffect.h"
+#include "platform/graphics/filters/FilterEffect.h"
#include "wtf/HashMap.h"
#include "wtf/HashSet.h"
#include "wtf/PassRefPtr.h"
diff --git a/chromium/third_party/WebKit/Source/core/svg/properties/SVGAnimatedEnumerationPropertyTearOff.h b/chromium/third_party/WebKit/Source/core/svg/properties/SVGAnimatedEnumerationPropertyTearOff.h
index cd6014b37e8..962e7f3e2e0 100644
--- a/chromium/third_party/WebKit/Source/core/svg/properties/SVGAnimatedEnumerationPropertyTearOff.h
+++ b/chromium/third_party/WebKit/Source/core/svg/properties/SVGAnimatedEnumerationPropertyTearOff.h
@@ -29,14 +29,14 @@ namespace WebCore {
template<typename EnumType>
class SVGAnimatedEnumerationPropertyTearOff : public SVGAnimatedStaticPropertyTearOff<unsigned> {
public:
- virtual void setBaseVal(const unsigned& property, ExceptionState& es)
+ virtual void setBaseVal(const unsigned& property, ExceptionState& exceptionState)
{
// All SVG enumeration values, that are allowed to be set via SVG DOM start with 1, 0 corresponds to unknown and is not settable through SVG DOM.
if (!property || property > SVGPropertyTraits<EnumType>::highestEnumValue()) {
- es.throwTypeError();
+ exceptionState.throwUninformativeAndGenericTypeError();
return;
}
- SVGAnimatedStaticPropertyTearOff<unsigned>::setBaseVal(property, es);
+ SVGAnimatedStaticPropertyTearOff<unsigned>::setBaseVal(property, exceptionState);
}
static PassRefPtr<SVGAnimatedEnumerationPropertyTearOff<EnumType> > create(SVGElement* contextElement, const QualifiedName& attributeName, AnimatedPropertyType animatedPropertyType, EnumType& property)
diff --git a/chromium/third_party/WebKit/Source/core/svg/properties/SVGAnimatedListPropertyTearOff.h b/chromium/third_party/WebKit/Source/core/svg/properties/SVGAnimatedListPropertyTearOff.h
index fdbd217ffd5..bebcc5a7202 100644
--- a/chromium/third_party/WebKit/Source/core/svg/properties/SVGAnimatedListPropertyTearOff.h
+++ b/chromium/third_party/WebKit/Source/core/svg/properties/SVGAnimatedListPropertyTearOff.h
@@ -39,6 +39,14 @@ public:
typedef SVGListPropertyTearOff<PropertyType> ListPropertyTearOff;
typedef PropertyType ContentType;
+ virtual ~SVGAnimatedListPropertyTearOff()
+ {
+ if (m_baseVal)
+ static_cast<ListPropertyTearOff*>(m_baseVal.get())->clearAnimatedProperty();
+ if (m_animVal)
+ static_cast<ListPropertyTearOff*>(m_animVal.get())->clearAnimatedProperty();
+ }
+
virtual ListProperty* baseVal()
{
if (!m_baseVal)
@@ -109,6 +117,7 @@ public:
{
ASSERT(m_isAnimating);
ASSERT(m_animVal);
+ ASSERT(contextElement());
ASSERT(m_values.size() == m_wrappers.size());
ListProperty* animVal = static_cast<ListProperty*>(m_animVal.get());
diff --git a/chromium/third_party/WebKit/Source/core/svg/properties/SVGAnimatedProperty.cpp b/chromium/third_party/WebKit/Source/core/svg/properties/SVGAnimatedProperty.cpp
index e15971cd355..b1e1e7835cd 100644
--- a/chromium/third_party/WebKit/Source/core/svg/properties/SVGAnimatedProperty.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/properties/SVGAnimatedProperty.cpp
@@ -32,28 +32,43 @@ SVGAnimatedProperty::SVGAnimatedProperty(SVGElement* contextElement, const Quali
, m_isAnimating(false)
, m_isReadOnly(false)
{
+ contextElement->setContextElement();
}
SVGAnimatedProperty::~SVGAnimatedProperty()
{
- // Remove wrapper from cache.
+ // Assure that animationEnded() was called, if animationStarted() was called before.
+ ASSERT(!m_isAnimating);
+}
+
+void SVGAnimatedProperty::detachAnimatedPropertiesForElement(SVGElement* element)
+{
+ // Remove wrappers from cache.
Cache* cache = animatedPropertyCache();
+
+ Vector<SVGAnimatedPropertyDescription> keysToRemove;
+
const Cache::const_iterator end = cache->end();
for (Cache::const_iterator it = cache->begin(); it != end; ++it) {
- if (it->value == this) {
- cache->remove(it->key);
- break;
+ if (it->key.m_element == element) {
+ it->value->resetContextElement();
+ keysToRemove.append(it->key);
}
}
- // Assure that animationEnded() was called, if animationStarted() was called before.
- ASSERT(!m_isAnimating);
+ for (Vector<SVGAnimatedPropertyDescription>::const_iterator it = keysToRemove.begin(); it != keysToRemove.end(); ++it) {
+ // http://crbug.com/333156 :
+ // There are cases where detachAnimatedPropertiesForElement is called recursively from ~SVGAnimatedProperty.
+ // This below protect makes this function safe by deferring the recursive call until we finish touching the HashMap.
+ RefPtr<SVGAnimatedProperty> protect = cache->get(*it);
+ cache->remove(*it);
+ }
}
void SVGAnimatedProperty::commitChange()
{
ASSERT(m_contextElement);
- ASSERT(!m_contextElement->m_deletionHasBegun);
+ ASSERT_WITH_SECURITY_IMPLICATION(!m_contextElement->m_deletionHasBegun);
m_contextElement->invalidateSVGAttributes();
m_contextElement->svgAttributeChanged(m_attributeName);
}
diff --git a/chromium/third_party/WebKit/Source/core/svg/properties/SVGAnimatedProperty.h b/chromium/third_party/WebKit/Source/core/svg/properties/SVGAnimatedProperty.h
index 37eba881a58..eb0ba54e4bf 100644
--- a/chromium/third_party/WebKit/Source/core/svg/properties/SVGAnimatedProperty.h
+++ b/chromium/third_party/WebKit/Source/core/svg/properties/SVGAnimatedProperty.h
@@ -31,7 +31,8 @@ class SVGElement;
class SVGAnimatedProperty : public RefCounted<SVGAnimatedProperty> {
public:
- SVGElement* contextElement() const { return m_contextElement.get(); }
+ SVGElement* contextElement() const { return m_contextElement; }
+ void resetContextElement() { m_contextElement = 0; }
const QualifiedName& attributeName() const { return m_attributeName; }
AnimatedPropertyType animatedPropertyType() const { return m_animatedPropertyType; }
bool isAnimating() const { return m_isAnimating; }
@@ -43,7 +44,7 @@ public:
virtual bool isAnimatedListTearOff() const { return false; }
// Caching facilities.
- typedef HashMap<SVGAnimatedPropertyDescription, SVGAnimatedProperty*, SVGAnimatedPropertyDescriptionHash, SVGAnimatedPropertyDescriptionHashTraits> Cache;
+ typedef HashMap<SVGAnimatedPropertyDescription, RefPtr<SVGAnimatedProperty>, SVGAnimatedPropertyDescriptionHash, SVGAnimatedPropertyDescriptionHashTraits> Cache;
virtual ~SVGAnimatedProperty();
@@ -57,7 +58,7 @@ public:
wrapper = TearOffType::create(element, info->attributeName, info->animatedPropertyType, property);
if (info->animatedPropertyState == PropertyIsReadOnly)
wrapper->setIsReadOnly();
- animatedPropertyCache()->set(key, wrapper.get());
+ animatedPropertyCache()->set(key, wrapper);
}
return static_pointer_cast<TearOffType>(wrapper);
}
@@ -76,13 +77,15 @@ public:
return lookupWrapper<OwnerType, TearOffType>(const_cast<OwnerType*>(element), info);
}
+ static void detachAnimatedPropertiesForElement(SVGElement*);
+
protected:
SVGAnimatedProperty(SVGElement*, const QualifiedName&, AnimatedPropertyType);
private:
static Cache* animatedPropertyCache();
- RefPtr<SVGElement> m_contextElement;
+ SVGElement* m_contextElement;
const QualifiedName& m_attributeName;
AnimatedPropertyType m_animatedPropertyType;
diff --git a/chromium/third_party/WebKit/Source/core/svg/properties/SVGAnimatedPropertyMacros.h b/chromium/third_party/WebKit/Source/core/svg/properties/SVGAnimatedPropertyMacros.h
index e864b5cca78..74e377f6e6b 100644
--- a/chromium/third_party/WebKit/Source/core/svg/properties/SVGAnimatedPropertyMacros.h
+++ b/chromium/third_party/WebKit/Source/core/svg/properties/SVGAnimatedPropertyMacros.h
@@ -36,7 +36,6 @@ struct SVGSynchronizableAnimatedProperty {
SVGSynchronizableAnimatedProperty()
: value(SVGPropertyTraits<PropertyType>::initialValue())
, shouldSynchronize(false)
- , isValid(false)
{
}
@@ -44,7 +43,6 @@ struct SVGSynchronizableAnimatedProperty {
SVGSynchronizableAnimatedProperty(const ConstructorParameter1& value1)
: value(value1)
, shouldSynchronize(false)
- , isValid(false)
{
}
@@ -52,7 +50,6 @@ struct SVGSynchronizableAnimatedProperty {
SVGSynchronizableAnimatedProperty(const ConstructorParameter1& value1, const ConstructorParameter2& value2)
: value(value1, value2)
, shouldSynchronize(false)
- , isValid(false)
{
}
@@ -63,7 +60,6 @@ struct SVGSynchronizableAnimatedProperty {
PropertyType value;
bool shouldSynchronize : 1;
- bool isValid : 1;
};
// Property registration helpers
@@ -79,8 +75,9 @@ SVGAttributeToPropertyMap& OwnerType::localAttributeToPropertyMap() const \
return attributeToPropertyMap(); \
} \
\
-static void registerAnimatedPropertiesFor##OwnerType() \
+void OwnerType::registerAnimatedPropertiesFor##OwnerType() \
{ \
+ OwnerType::m_cleanupAnimatedPropertiesCaller.setOwner(this); \
SVGAttributeToPropertyMap& map = OwnerType::attributeToPropertyMap(); \
if (!map.isEmpty()) \
return; \
@@ -120,10 +117,9 @@ PropertyType& OwnerType::LowerProperty##BaseValue() const \
return m_##LowerProperty.value; \
} \
\
-void OwnerType::set##UpperProperty##BaseValue(const PropertyType& type, const bool validValue) \
+void OwnerType::set##UpperProperty##BaseValue(const PropertyType& type) \
{ \
m_##LowerProperty.value = type; \
- m_##LowerProperty.isValid = validValue; \
} \
\
PassRefPtr<TearOffType> OwnerType::LowerProperty() \
@@ -132,11 +128,6 @@ PassRefPtr<TearOffType> OwnerType::LowerProperty() \
return static_pointer_cast<TearOffType>(lookupOrCreate##UpperProperty##Wrapper(this)); \
} \
\
-bool OwnerType::LowerProperty##IsValid() const \
-{ \
- return m_##LowerProperty.isValid; \
-} \
-\
void OwnerType::synchronize##UpperProperty() \
{ \
if (!m_##LowerProperty.shouldSynchronize) \
@@ -164,6 +155,7 @@ void OwnerType::synchronize##UpperProperty(SVGElement* maskedOwnerType) \
public: \
static SVGAttributeToPropertyMap& attributeToPropertyMap(); \
virtual SVGAttributeToPropertyMap& localAttributeToPropertyMap() const; \
+ void registerAnimatedPropertiesFor##OwnerType(); \
typedef OwnerType UseOwnerType;
#define DECLARE_ANIMATED_PROPERTY(TearOffType, PropertyType, UpperProperty, LowerProperty) \
@@ -171,9 +163,8 @@ public: \
static const SVGPropertyInfo* LowerProperty##PropertyInfo(); \
PropertyType& LowerProperty##CurrentValue() const; \
PropertyType& LowerProperty##BaseValue() const; \
- void set##UpperProperty##BaseValue(const PropertyType& type, const bool = true); \
+ void set##UpperProperty##BaseValue(const PropertyType& type); \
PassRefPtr<TearOffType> LowerProperty(); \
- bool LowerProperty##IsValid() const; \
\
private: \
void synchronize##UpperProperty(); \
@@ -182,7 +173,8 @@ private: \
\
mutable SVGSynchronizableAnimatedProperty<PropertyType> m_##LowerProperty;
-#define END_DECLARE_ANIMATED_PROPERTIES
+#define END_DECLARE_ANIMATED_PROPERTIES \
+ CleanUpAnimatedPropertiesCaller m_cleanupAnimatedPropertiesCaller;
// List specific definition/declaration helpers
#define DECLARE_ANIMATED_LIST_PROPERTY(TearOffType, PropertyType, UpperProperty, LowerProperty) \
diff --git a/chromium/third_party/WebKit/Source/core/svg/properties/SVGListProperty.h b/chromium/third_party/WebKit/Source/core/svg/properties/SVGListProperty.h
index 7760b8d1d71..27e8d66cf1d 100644
--- a/chromium/third_party/WebKit/Source/core/svg/properties/SVGListProperty.h
+++ b/chromium/third_party/WebKit/Source/core/svg/properties/SVGListProperty.h
@@ -49,10 +49,10 @@ public:
typedef SVGAnimatedListPropertyTearOff<PropertyType> AnimatedListPropertyTearOff;
typedef typename SVGAnimatedListPropertyTearOff<PropertyType>::ListWrapperCache ListWrapperCache;
- bool canAlterList(ExceptionState& es) const
+ bool canAlterList(ExceptionState& exceptionState) const
{
if (m_role == AnimValRole) {
- es.throwDOMException(NoModificationAllowedError);
+ exceptionState.throwUninformativeAndGenericDOMException(NoModificationAllowedError);
return false;
}
@@ -97,18 +97,18 @@ public:
}
// SVGList::clear()
- void clearValues(ExceptionState& es)
+ void clearValues(ExceptionState& exceptionState)
{
- if (!canAlterList(es))
+ if (!canAlterList(exceptionState))
return;
m_values->clear();
commitChange();
}
- void clearValuesAndWrappers(ExceptionState& es)
+ void clearValuesAndWrappers(ExceptionState& exceptionState)
{
- if (!canAlterList(es))
+ if (!canAlterList(exceptionState))
return;
detachListWrappers(0);
@@ -123,9 +123,9 @@ public:
}
// SVGList::initialize()
- ListItemType initializeValues(const ListItemType& newItem, ExceptionState& es)
+ ListItemType initializeValues(const ListItemType& newItem, ExceptionState& exceptionState)
{
- if (!canAlterList(es))
+ if (!canAlterList(exceptionState))
return ListItemType();
// Spec: If the inserted item is already in a list, it is removed from its previous list before it is inserted into this list.
@@ -139,15 +139,15 @@ public:
return newItem;
}
- PassListItemTearOff initializeValuesAndWrappers(PassListItemTearOff passNewItem, ExceptionState& es)
+ PassListItemTearOff initializeValuesAndWrappers(PassListItemTearOff passNewItem, ExceptionState& exceptionState)
{
ASSERT(m_wrappers);
- if (!canAlterList(es))
+ if (!canAlterList(exceptionState))
return 0;
// Not specified, but FF/Opera do it this way, and it's just sane.
if (!passNewItem) {
- es.throwTypeError();
+ exceptionState.throwUninformativeAndGenericTypeError();
return 0;
}
@@ -169,29 +169,29 @@ public:
}
// SVGList::getItem()
- bool canGetItem(unsigned index, ExceptionState& es)
+ bool canGetItem(unsigned index, ExceptionState& exceptionState)
{
if (index >= m_values->size()) {
- es.throwDOMException(IndexSizeError);
+ exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
return false;
}
return true;
}
- ListItemType getItemValues(unsigned index, ExceptionState& es)
+ ListItemType getItemValues(unsigned index, ExceptionState& exceptionState)
{
- if (!canGetItem(index, es))
+ if (!canGetItem(index, exceptionState))
return ListItemType();
// Spec: Returns the specified item from the list. The returned item is the item itself and not a copy.
return m_values->at(index);
}
- PassListItemTearOff getItemValuesAndWrappers(AnimatedListPropertyTearOff* animatedList, unsigned index, ExceptionState& es)
+ PassListItemTearOff getItemValuesAndWrappers(AnimatedListPropertyTearOff* animatedList, unsigned index, ExceptionState& exceptionState)
{
ASSERT(m_wrappers);
- if (!canGetItem(index, es))
+ if (!canGetItem(index, exceptionState))
return 0;
// Spec: Returns the specified item from the list. The returned item is the item itself and not a copy.
@@ -210,9 +210,9 @@ public:
}
// SVGList::insertItemBefore()
- ListItemType insertItemBeforeValues(const ListItemType& newItem, unsigned index, ExceptionState& es)
+ ListItemType insertItemBeforeValues(const ListItemType& newItem, unsigned index, ExceptionState& exceptionState)
{
- if (!canAlterList(es))
+ if (!canAlterList(exceptionState))
return ListItemType();
// Spec: If the index is greater than or equal to numberOfItems, then the new item is appended to the end of the list.
@@ -233,15 +233,15 @@ public:
return newItem;
}
- PassListItemTearOff insertItemBeforeValuesAndWrappers(PassListItemTearOff passNewItem, unsigned index, ExceptionState& es)
+ PassListItemTearOff insertItemBeforeValuesAndWrappers(PassListItemTearOff passNewItem, unsigned index, ExceptionState& exceptionState)
{
ASSERT(m_wrappers);
- if (!canAlterList(es))
+ if (!canAlterList(exceptionState))
return 0;
// Not specified, but FF/Opera do it this way, and it's just sane.
if (!passNewItem) {
- es.throwTypeError();
+ exceptionState.throwUninformativeAndGenericTypeError();
return 0;
}
@@ -268,22 +268,22 @@ public:
}
// SVGList::replaceItem()
- bool canReplaceItem(unsigned index, ExceptionState& es)
+ bool canReplaceItem(unsigned index, ExceptionState& exceptionState)
{
- if (!canAlterList(es))
+ if (!canAlterList(exceptionState))
return false;
if (index >= m_values->size()) {
- es.throwDOMException(IndexSizeError);
+ exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
return false;
}
return true;
}
- ListItemType replaceItemValues(const ListItemType& newItem, unsigned index, ExceptionState& es)
+ ListItemType replaceItemValues(const ListItemType& newItem, unsigned index, ExceptionState& exceptionState)
{
- if (!canReplaceItem(index, es))
+ if (!canReplaceItem(index, exceptionState))
return ListItemType();
// Spec: If newItem is already in a list, it is removed from its previous list before it is inserted into this list.
@@ -295,7 +295,7 @@ public:
if (m_values->isEmpty()) {
// 'newItem' already lived in our list, we removed it, and now we're empty, which means there's nothing to replace.
- es.throwDOMException(IndexSizeError);
+ exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
return ListItemType();
}
@@ -306,15 +306,15 @@ public:
return newItem;
}
- PassListItemTearOff replaceItemValuesAndWrappers(PassListItemTearOff passNewItem, unsigned index, ExceptionState& es)
+ PassListItemTearOff replaceItemValuesAndWrappers(PassListItemTearOff passNewItem, unsigned index, ExceptionState& exceptionState)
{
ASSERT(m_wrappers);
- if (!canReplaceItem(index, es))
+ if (!canReplaceItem(index, exceptionState))
return 0;
// Not specified, but FF/Opera do it this way, and it's just sane.
if (!passNewItem) {
- es.throwTypeError();
+ exceptionState.throwUninformativeAndGenericTypeError();
return 0;
}
@@ -329,7 +329,7 @@ public:
if (m_values->isEmpty()) {
ASSERT(m_wrappers->isEmpty());
// 'passNewItem' already lived in our list, we removed it, and now we're empty, which means there's nothing to replace.
- es.throwDOMException(IndexSizeError);
+ exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
return 0;
}
@@ -347,22 +347,22 @@ public:
}
// SVGList::removeItem()
- bool canRemoveItem(unsigned index, ExceptionState& es)
+ bool canRemoveItem(unsigned index, ExceptionState& exceptionState)
{
- if (!canAlterList(es))
+ if (!canAlterList(exceptionState))
return false;
if (index >= m_values->size()) {
- es.throwDOMException(IndexSizeError);
+ exceptionState.throwUninformativeAndGenericDOMException(IndexSizeError);
return false;
}
return true;
}
- ListItemType removeItemValues(unsigned index, ExceptionState& es)
+ ListItemType removeItemValues(unsigned index, ExceptionState& exceptionState)
{
- if (!canRemoveItem(index, es))
+ if (!canRemoveItem(index, exceptionState))
return ListItemType();
ListItemType oldItem = m_values->at(index);
@@ -372,10 +372,10 @@ public:
return oldItem;
}
- PassListItemTearOff removeItemValuesAndWrappers(AnimatedListPropertyTearOff* animatedList, unsigned index, ExceptionState& es)
+ PassListItemTearOff removeItemValuesAndWrappers(AnimatedListPropertyTearOff* animatedList, unsigned index, ExceptionState& exceptionState)
{
ASSERT(m_wrappers);
- if (!canRemoveItem(index, es))
+ if (!canRemoveItem(index, exceptionState))
return 0;
ASSERT(m_values->size() == m_wrappers->size());
@@ -394,9 +394,9 @@ public:
}
// SVGList::appendItem()
- ListItemType appendItemValues(const ListItemType& newItem, ExceptionState& es)
+ ListItemType appendItemValues(const ListItemType& newItem, ExceptionState& exceptionState)
{
- if (!canAlterList(es))
+ if (!canAlterList(exceptionState))
return ListItemType();
// Spec: If newItem is already in a list, it is removed from its previous list before it is inserted into this list.
@@ -409,15 +409,15 @@ public:
return newItem;
}
- PassListItemTearOff appendItemValuesAndWrappers(PassListItemTearOff passNewItem, ExceptionState& es)
+ PassListItemTearOff appendItemValuesAndWrappers(PassListItemTearOff passNewItem, ExceptionState& exceptionState)
{
ASSERT(m_wrappers);
- if (!canAlterList(es))
+ if (!canAlterList(exceptionState))
return 0;
// Not specified, but FF/Opera do it this way, and it's just sane.
if (!passNewItem) {
- es.throwTypeError();
+ exceptionState.throwUninformativeAndGenericTypeError();
return 0;
}
diff --git a/chromium/third_party/WebKit/Source/core/svg/properties/SVGListPropertyTearOff.h b/chromium/third_party/WebKit/Source/core/svg/properties/SVGListPropertyTearOff.h
index c6246d7c24a..7f1410974fb 100644
--- a/chromium/third_party/WebKit/Source/core/svg/properties/SVGListPropertyTearOff.h
+++ b/chromium/third_party/WebKit/Source/core/svg/properties/SVGListPropertyTearOff.h
@@ -80,39 +80,53 @@ public:
}
// SVGList API
- void clear(ExceptionState& es)
+ void clear(ExceptionState& exceptionState)
{
- Base::clearValuesAndWrappers(es);
+ Base::clearValuesAndWrappers(exceptionState);
}
- PassListItemTearOff initialize(PassListItemTearOff passNewItem, ExceptionState& es)
+ PassListItemTearOff initialize(PassListItemTearOff passNewItem, ExceptionState& exceptionState)
{
- return Base::initializeValuesAndWrappers(passNewItem, es);
+ return Base::initializeValuesAndWrappers(passNewItem, exceptionState);
}
- PassListItemTearOff getItem(unsigned index, ExceptionState& es)
+ PassListItemTearOff getItem(unsigned index, ExceptionState& exceptionState)
{
- return Base::getItemValuesAndWrappers(m_animatedProperty.get(), index, es);
+ ASSERT(m_animatedProperty);
+ return Base::getItemValuesAndWrappers(m_animatedProperty, index, exceptionState);
}
- PassListItemTearOff insertItemBefore(PassListItemTearOff passNewItem, unsigned index, ExceptionState& es)
+ PassListItemTearOff insertItemBefore(PassListItemTearOff passNewItem, unsigned index, ExceptionState& exceptionState)
{
- return Base::insertItemBeforeValuesAndWrappers(passNewItem, index, es);
+ return Base::insertItemBeforeValuesAndWrappers(passNewItem, index, exceptionState);
}
- PassListItemTearOff replaceItem(PassListItemTearOff passNewItem, unsigned index, ExceptionState& es)
+ PassListItemTearOff replaceItem(PassListItemTearOff passNewItem, unsigned index, ExceptionState& exceptionState)
{
- return Base::replaceItemValuesAndWrappers(passNewItem, index, es);
+ return Base::replaceItemValuesAndWrappers(passNewItem, index, exceptionState);
}
- PassListItemTearOff removeItem(unsigned index, ExceptionState& es)
+ PassListItemTearOff removeItem(unsigned index, ExceptionState& exceptionState)
{
- return Base::removeItemValuesAndWrappers(m_animatedProperty.get(), index, es);
+ ASSERT(m_animatedProperty);
+ return Base::removeItemValuesAndWrappers(m_animatedProperty, index, exceptionState);
}
- PassListItemTearOff appendItem(PassListItemTearOff passNewItem, ExceptionState& es)
+ PassListItemTearOff appendItem(PassListItemTearOff passNewItem, ExceptionState& exceptionState)
{
- return Base::appendItemValuesAndWrappers(passNewItem, es);
+ return Base::appendItemValuesAndWrappers(passNewItem, exceptionState);
+ }
+
+ SVGElement* contextElement() const
+ {
+ ASSERT(m_animatedProperty);
+ return m_animatedProperty->contextElement();
+ }
+
+ void clearAnimatedProperty()
+ {
+ ASSERT(m_animatedProperty);
+ m_animatedProperty = 0;
}
protected:
@@ -120,6 +134,7 @@ protected:
: SVGListProperty<PropertyType>(role, values, &wrappers)
, m_animatedProperty(animatedProperty)
{
+ ASSERT(m_animatedProperty);
}
virtual bool isReadOnly() const
@@ -135,6 +150,7 @@ protected:
{
ASSERT(m_values);
ASSERT(m_wrappers);
+ ASSERT(m_animatedProperty);
// Update existing wrappers, as the index in the values list has changed.
unsigned size = m_wrappers->size();
@@ -143,7 +159,7 @@ protected:
ListItemTearOff* item = m_wrappers->at(i).get();
if (!item)
continue;
- item->setAnimatedProperty(m_animatedProperty.get());
+ item->setAnimatedProperty(m_animatedProperty);
item->setValue(m_values->at(i));
}
@@ -179,6 +195,7 @@ protected:
// Spec: If newItem is already in a list, it is removed from its previous list before it is inserted into this list.
// 'newItem' is already living in another list. If it's not our list, synchronize the other lists wrappers after the removal.
+ ASSERT(m_animatedProperty);
bool livesInOtherList = animatedPropertyOfItem != m_animatedProperty;
AnimatedListPropertyTearOff* propertyTearOff = static_cast<AnimatedListPropertyTearOff*>(animatedPropertyOfItem);
int indexToRemove = propertyTearOff->findItem(newItem.get());
@@ -206,7 +223,7 @@ protected:
// Back pointer to the animated property that created us
// For example (text.x.baseVal): m_animatedProperty points to the 'x' SVGAnimatedLengthList object
- RefPtr<AnimatedListPropertyTearOff> m_animatedProperty;
+ AnimatedListPropertyTearOff* m_animatedProperty;
};
}
diff --git a/chromium/third_party/WebKit/Source/core/svg/properties/SVGMatrixTearOff.h b/chromium/third_party/WebKit/Source/core/svg/properties/SVGMatrixTearOff.h
index 338899d735b..76935750407 100644
--- a/chromium/third_party/WebKit/Source/core/svg/properties/SVGMatrixTearOff.h
+++ b/chromium/third_party/WebKit/Source/core/svg/properties/SVGMatrixTearOff.h
@@ -27,6 +27,20 @@ namespace WebCore {
class SVGMatrixTearOff : public SVGPropertyTearOff<SVGMatrix> {
public:
+ // Used for child types (baseVal/animVal) of a SVGAnimated* property (for example: SVGAnimatedLength::baseVal()).
+ // Also used for list tear offs (for example: text.x.baseVal.getItem(0)).
+ static PassRefPtr<SVGMatrixTearOff> create(SVGAnimatedProperty* animatedProperty, SVGPropertyRole role, SVGMatrix& value)
+ {
+ ASSERT(animatedProperty);
+ return adoptRef(new SVGMatrixTearOff(animatedProperty, role, value));
+ }
+
+ // Used for non-animated POD types (for example: SVGSVGElement::createSVGLength()).
+ static PassRefPtr<SVGMatrixTearOff> create(const SVGMatrix& initialValue)
+ {
+ return adoptRef(new SVGMatrixTearOff(initialValue));
+ }
+
// Used for non-animated POD types that are not associated with a SVGAnimatedProperty object, nor with a XML DOM attribute
// and that contain a parent type that's exposed to the bindings via a SVGStaticPropertyTearOff object
// (for example: SVGTransform::matrix).
@@ -40,11 +54,42 @@ public:
virtual void commitChange()
{
- m_parent->propertyReference().updateSVGMatrix();
- m_parent->commitChange();
+ if (m_parent) {
+ // This is a tear-off from a SVGPropertyTearOff<SVGTransform>.
+ m_parent->propertyReference().updateSVGMatrix();
+ m_parent->commitChange();
+ } else {
+ // This is either a detached tear-off or a reference tear-off from a AnimatedProperty.
+ SVGPropertyTearOff<SVGMatrix>::commitChange();
+ }
}
+ // SVGMatrixTearOff can be a child tear-off of a SVGTransform tear-off,
+ // which means that |m_value| may be pointing inside |m_value| of the other tear-off.
+ // This method is called from the parent SVGTransform tear-off when |m_parent->m_value| is updated,
+ // so that |this->m_value| would point to valid location.
+ virtual void setValueForMatrixIfNeeded(SVGTransform* transform)
+ {
+ setValue(transform->svgMatrix());
+ }
+
+ SVGPropertyTearOff<SVGTransform>* parent() { return m_parent; }
+
private:
+ SVGMatrixTearOff(SVGAnimatedProperty* animatedProperty, SVGPropertyRole role, SVGMatrix& value)
+ : SVGPropertyTearOff<SVGMatrix>(animatedProperty, role, value)
+ , m_parent(0)
+ , m_weakFactory(this)
+ {
+ }
+
+ SVGMatrixTearOff(const SVGMatrix& initialValue)
+ : SVGPropertyTearOff<SVGMatrix>(initialValue)
+ , m_parent(0)
+ , m_weakFactory(this)
+ {
+ }
+
SVGMatrixTearOff(SVGPropertyTearOff<SVGTransform>* parent, SVGMatrix& value)
: SVGPropertyTearOff<SVGMatrix>(0, UndefinedRole, value)
, m_parent(parent)
@@ -52,7 +97,9 @@ private:
{
}
- RefPtr<SVGPropertyTearOff<SVGTransform> > m_parent;
+ // m_parent is kept alive from V8 wrapper.
+ SVGPropertyTearOff<SVGTransform>* m_parent;
+
WeakPtrFactory<SVGPropertyTearOffBase > m_weakFactory;
};
diff --git a/chromium/third_party/WebKit/Source/core/svg/properties/SVGPathSegListPropertyTearOff.cpp b/chromium/third_party/WebKit/Source/core/svg/properties/SVGPathSegListPropertyTearOff.cpp
index cfe7bb3d7e9..48cb03a468d 100644
--- a/chromium/third_party/WebKit/Source/core/svg/properties/SVGPathSegListPropertyTearOff.cpp
+++ b/chromium/third_party/WebKit/Source/core/svg/properties/SVGPathSegListPropertyTearOff.cpp
@@ -21,7 +21,6 @@
#include "core/svg/properties/SVGPathSegListPropertyTearOff.h"
#include "SVGNames.h"
-#include "bindings/v8/ExceptionState.h"
#include "core/dom/ExceptionCode.h"
#include "core/svg/SVGPathElement.h"
#include "core/svg/SVGPathSegWithContext.h"
@@ -39,19 +38,19 @@ void SVGPathSegListPropertyTearOff::clearContextAndRoles()
}
}
-void SVGPathSegListPropertyTearOff::clear(ExceptionState& es)
+void SVGPathSegListPropertyTearOff::clear(ExceptionState& exceptionState)
{
ASSERT(m_values);
if (m_values->isEmpty())
return;
clearContextAndRoles();
- SVGPathSegListPropertyTearOff::Base::clearValues(es);
+ SVGPathSegListPropertyTearOff::Base::clearValues(exceptionState);
}
-SVGPathSegListPropertyTearOff::PassListItemType SVGPathSegListPropertyTearOff::getItem(unsigned index, ExceptionState& es)
+SVGPathSegListPropertyTearOff::PassListItemType SVGPathSegListPropertyTearOff::getItem(unsigned index, ExceptionState& exceptionState)
{
- ListItemType returnedItem = Base::getItemValues(index, es);
+ ListItemType returnedItem = Base::getItemValues(index, exceptionState);
if (returnedItem) {
ASSERT(static_cast<SVGPathSegWithContext*>(returnedItem.get())->contextElement() == contextElement());
ASSERT(static_cast<SVGPathSegWithContext*>(returnedItem.get())->role() == m_pathSegRole);
@@ -59,11 +58,11 @@ SVGPathSegListPropertyTearOff::PassListItemType SVGPathSegListPropertyTearOff::g
return returnedItem.release();
}
-SVGPathSegListPropertyTearOff::PassListItemType SVGPathSegListPropertyTearOff::replaceItem(PassListItemType passNewItem, unsigned index, ExceptionState& es)
+SVGPathSegListPropertyTearOff::PassListItemType SVGPathSegListPropertyTearOff::replaceItem(PassListItemType passNewItem, unsigned index, ExceptionState& exceptionState)
{
// Not specified, but FF/Opera do it this way, and it's just sane.
if (!passNewItem) {
- es.throwTypeError();
+ exceptionState.throwUninformativeAndGenericTypeError();
return 0;
}
@@ -74,12 +73,12 @@ SVGPathSegListPropertyTearOff::PassListItemType SVGPathSegListPropertyTearOff::r
}
ListItemType newItem = passNewItem;
- return Base::replaceItemValues(newItem, index, es);
+ return Base::replaceItemValues(newItem, index, exceptionState);
}
-SVGPathSegListPropertyTearOff::PassListItemType SVGPathSegListPropertyTearOff::removeItem(unsigned index, ExceptionState& es)
+SVGPathSegListPropertyTearOff::PassListItemType SVGPathSegListPropertyTearOff::removeItem(unsigned index, ExceptionState& exceptionState)
{
- SVGPathSegListPropertyTearOff::ListItemType removedItem = SVGPathSegListPropertyTearOff::Base::removeItemValues(index, es);
+ SVGPathSegListPropertyTearOff::ListItemType removedItem = SVGPathSegListPropertyTearOff::Base::removeItemValues(index, exceptionState);
if (removedItem)
static_cast<SVGPathSegWithContext*>(removedItem.get())->setContextAndRole(0, PathSegUndefinedRole);
return removedItem.release();
diff --git a/chromium/third_party/WebKit/Source/core/svg/properties/SVGPathSegListPropertyTearOff.h b/chromium/third_party/WebKit/Source/core/svg/properties/SVGPathSegListPropertyTearOff.h
index 56055ed92b3..4a755f76b77 100644
--- a/chromium/third_party/WebKit/Source/core/svg/properties/SVGPathSegListPropertyTearOff.h
+++ b/chromium/third_party/WebKit/Source/core/svg/properties/SVGPathSegListPropertyTearOff.h
@@ -41,6 +41,9 @@ public:
return adoptRef(new SVGPathSegListPropertyTearOff(animatedProperty, role, pathSegRole, values, wrappers));
}
+ SVGPathElement* contextElement() const;
+ SVGAnimatedProperty* animatedProperty() const { return m_animatedProperty; }
+
int findItem(const ListItemType& item) const
{
ASSERT(m_values);
@@ -68,47 +71,47 @@ public:
// SVGList API
void clear(ExceptionState&);
- PassListItemType initialize(PassListItemType passNewItem, ExceptionState& es)
+ PassListItemType initialize(PassListItemType passNewItem, ExceptionState& exceptionState)
{
// Not specified, but FF/Opera do it this way, and it's just sane.
if (!passNewItem) {
- es.throwTypeError();
+ exceptionState.throwUninformativeAndGenericTypeError();
return 0;
}
clearContextAndRoles();
ListItemType newItem = passNewItem;
- return Base::initializeValues(newItem, es);
+ return Base::initializeValues(newItem, exceptionState);
}
PassListItemType getItem(unsigned index, ExceptionState&);
- PassListItemType insertItemBefore(PassListItemType passNewItem, unsigned index, ExceptionState& es)
+ PassListItemType insertItemBefore(PassListItemType passNewItem, unsigned index, ExceptionState& exceptionState)
{
// Not specified, but FF/Opera do it this way, and it's just sane.
if (!passNewItem) {
- es.throwTypeError();
+ exceptionState.throwUninformativeAndGenericTypeError();
return 0;
}
ListItemType newItem = passNewItem;
- return Base::insertItemBeforeValues(newItem, index, es);
+ return Base::insertItemBeforeValues(newItem, index, exceptionState);
}
PassListItemType replaceItem(PassListItemType, unsigned index, ExceptionState&);
PassListItemType removeItem(unsigned index, ExceptionState&);
- PassListItemType appendItem(PassListItemType passNewItem, ExceptionState& es)
+ PassListItemType appendItem(PassListItemType passNewItem, ExceptionState& exceptionState)
{
// Not specified, but FF/Opera do it this way, and it's just sane.
if (!passNewItem) {
- es.throwTypeError();
+ exceptionState.throwUninformativeAndGenericTypeError();
return 0;
}
ListItemType newItem = passNewItem;
- return Base::appendItemValues(newItem, es);
+ return Base::appendItemValues(newItem, exceptionState);
}
private:
@@ -119,8 +122,6 @@ private:
{
}
- SVGPathElement* contextElement() const;
-
void clearContextAndRoles();
using Base::m_role;
@@ -154,7 +155,7 @@ private:
}
private:
- RefPtr<AnimatedListPropertyTearOff> m_animatedProperty;
+ AnimatedListPropertyTearOff* m_animatedProperty;
SVGPathSegRole m_pathSegRole;
};
diff --git a/chromium/third_party/WebKit/Source/core/svg/properties/SVGPropertyTearOff.h b/chromium/third_party/WebKit/Source/core/svg/properties/SVGPropertyTearOff.h
index a78bdea5677..b42f29bc452 100644
--- a/chromium/third_party/WebKit/Source/core/svg/properties/SVGPropertyTearOff.h
+++ b/chromium/third_party/WebKit/Source/core/svg/properties/SVGPropertyTearOff.h
@@ -29,6 +29,8 @@ namespace WebCore {
class SVGPropertyTearOffBase : public SVGProperty {
public:
+ virtual void setValueForMatrixIfNeeded(SVGTransform*) { }
+
virtual void detachWrapper() = 0;
};
@@ -60,6 +62,9 @@ public:
detachChildren();
delete m_value;
}
+
+ updateChildrenTearOffs(&value);
+
m_valueIsCopy = false;
m_value = &value;
}
@@ -76,7 +81,8 @@ public:
{
if (!m_animatedProperty || m_valueIsCopy)
return 0;
- return m_contextElement.get();
+ ASSERT(m_contextElement);
+ return m_contextElement;
}
void addChild(WeakPtr<SVGPropertyTearOffBase> child)
@@ -156,7 +162,22 @@ protected:
m_childTearOffs.clear();
}
- RefPtr<SVGElement> m_contextElement;
+ // Update m_value of children tear-offs.
+ // Currently only SVGTransform has child tear-offs.
+ void updateChildrenTearOffs(SVGTransform* transform)
+ {
+ for (Vector<WeakPtr<SVGPropertyTearOffBase> >::iterator iter = m_childTearOffs.begin(); iter != m_childTearOffs.end(); iter++) {
+ if (iter->get())
+ iter->get()->setValueForMatrixIfNeeded(transform);
+ }
+ }
+
+ void updateChildrenTearOffs(void*)
+ {
+ // Tear-offs for other types do not have child tear-offs.
+ }
+
+ SVGElement* m_contextElement;
SVGAnimatedProperty* m_animatedProperty;
SVGPropertyRole m_role;
PropertyType* m_value;
diff --git a/chromium/third_party/WebKit/Source/core/svg/properties/SVGStaticListPropertyTearOff.h b/chromium/third_party/WebKit/Source/core/svg/properties/SVGStaticListPropertyTearOff.h
index 367560fdc89..596a55185d9 100644
--- a/chromium/third_party/WebKit/Source/core/svg/properties/SVGStaticListPropertyTearOff.h
+++ b/chromium/third_party/WebKit/Source/core/svg/properties/SVGStaticListPropertyTearOff.h
@@ -43,40 +43,42 @@ public:
return adoptRef(new SVGStaticListPropertyTearOff<PropertyType>(contextElement, values));
}
+ SVGElement* contextElement() const { return m_contextElement; }
+
// SVGList API
- void clear(ExceptionState& es)
+ void clear(ExceptionState& exceptionState)
{
- Base::clearValues(es);
+ Base::clearValues(exceptionState);
}
- ListItemType initialize(const ListItemType& newItem, ExceptionState& es)
+ ListItemType initialize(const ListItemType& newItem, ExceptionState& exceptionState)
{
- return Base::initializeValues(newItem, es);
+ return Base::initializeValues(newItem, exceptionState);
}
- ListItemType getItem(unsigned index, ExceptionState& es)
+ ListItemType getItem(unsigned index, ExceptionState& exceptionState)
{
- return Base::getItemValues(index, es);
+ return Base::getItemValues(index, exceptionState);
}
- ListItemType insertItemBefore(const ListItemType& newItem, unsigned index, ExceptionState& es)
+ ListItemType insertItemBefore(const ListItemType& newItem, unsigned index, ExceptionState& exceptionState)
{
- return Base::insertItemBeforeValues(newItem, index, es);
+ return Base::insertItemBeforeValues(newItem, index, exceptionState);
}
- ListItemType replaceItem(const ListItemType& newItem, unsigned index, ExceptionState& es)
+ ListItemType replaceItem(const ListItemType& newItem, unsigned index, ExceptionState& exceptionState)
{
- return Base::replaceItemValues(newItem, index, es);
+ return Base::replaceItemValues(newItem, index, exceptionState);
}
- ListItemType removeItem(unsigned index, ExceptionState& es)
+ ListItemType removeItem(unsigned index, ExceptionState& exceptionState)
{
- return Base::removeItemValues(index, es);
+ return Base::removeItemValues(index, exceptionState);
}
- ListItemType appendItem(const ListItemType& newItem, ExceptionState& es)
+ ListItemType appendItem(const ListItemType& newItem, ExceptionState& exceptionState)
{
- return Base::appendItemValues(newItem, es);
+ return Base::appendItemValues(newItem, exceptionState);
}
private:
@@ -84,6 +86,7 @@ private:
: SVGListProperty<PropertyType>(UndefinedRole, values, 0)
, m_contextElement(contextElement)
{
+ m_contextElement->setContextElement();
}
virtual bool isReadOnly() const
@@ -94,7 +97,8 @@ private:
virtual void commitChange()
{
ASSERT(m_values);
- m_values->commitChange(m_contextElement.get());
+ ASSERT(m_contextElement);
+ m_values->commitChange(m_contextElement);
}
virtual bool processIncomingListItemValue(const ListItemType&, unsigned*)
@@ -110,7 +114,7 @@ private:
}
private:
- RefPtr<SVGElement> m_contextElement;
+ SVGElement* m_contextElement;
};
}
diff --git a/chromium/third_party/WebKit/Source/core/svg/properties/SVGStaticPropertyTearOff.h b/chromium/third_party/WebKit/Source/core/svg/properties/SVGStaticPropertyTearOff.h
index 76683360fc7..93d1cc58be8 100644
--- a/chromium/third_party/WebKit/Source/core/svg/properties/SVGStaticPropertyTearOff.h
+++ b/chromium/third_party/WebKit/Source/core/svg/properties/SVGStaticPropertyTearOff.h
@@ -51,6 +51,7 @@ private:
, m_update(update)
, m_contextElement(contextElement)
{
+ m_contextElement->setContextElement();
}
UpdateMethod m_update;
diff --git a/chromium/third_party/WebKit/Source/core/svg/properties/SVGTransformListPropertyTearOff.h b/chromium/third_party/WebKit/Source/core/svg/properties/SVGTransformListPropertyTearOff.h
index b3064569d6d..2ec007fcfd8 100644
--- a/chromium/third_party/WebKit/Source/core/svg/properties/SVGTransformListPropertyTearOff.h
+++ b/chromium/third_party/WebKit/Source/core/svg/properties/SVGTransformListPropertyTearOff.h
@@ -39,21 +39,21 @@ public:
return adoptRef(new SVGTransformListPropertyTearOff(animatedProperty, role, values, wrappers));
}
- PassRefPtr<SVGPropertyTearOff<SVGTransform> > createSVGTransformFromMatrix(SVGPropertyTearOff<SVGMatrix>* matrix, ExceptionState& es)
+ PassRefPtr<SVGPropertyTearOff<SVGTransform> > createSVGTransformFromMatrix(SVGPropertyTearOff<SVGMatrix>* matrix, ExceptionState& exceptionState)
{
ASSERT(m_values);
if (!matrix) {
- es.throwDOMException(TypeMismatchError);
+ exceptionState.throwUninformativeAndGenericDOMException(TypeMismatchError);
return 0;
}
return SVGPropertyTearOff<SVGTransform>::create(m_values->createSVGTransformFromMatrix(matrix->propertyReference()));
}
- PassRefPtr<SVGPropertyTearOff<SVGTransform> > consolidate(ExceptionState& es)
+ PassRefPtr<SVGPropertyTearOff<SVGTransform> > consolidate(ExceptionState& exceptionState)
{
ASSERT(m_values);
ASSERT(m_wrappers);
- if (!canAlterList(es))
+ if (!canAlterList(exceptionState))
return 0;
ASSERT(m_values->size() == m_wrappers->size());
diff --git a/chromium/third_party/WebKit/Source/core/svg/svgtags.in b/chromium/third_party/WebKit/Source/core/svg/svgtags.in
deleted file mode 100644
index 094ccafbf8b..00000000000
--- a/chromium/third_party/WebKit/Source/core/svg/svgtags.in
+++ /dev/null
@@ -1,97 +0,0 @@
-namespace="SVG"
-namespaceURI="http://www.w3.org/2000/svg"
-fallbackInterfaceName="SVGUnknownElement"
-fallbackJSInterfaceName="SVGElement"
-
-a
-#if ENABLE_SVG_FONTS
-altGlyph
-altGlyphDef
-altGlyphItem
-#endif
-animate
-animateColor
-animateMotion
-animateTransform
-set
-circle
-clipPath
-#if 0
-color_profile
-#endif
-cursor
-defs
-desc
-ellipse
-feBlend
-feColorMatrix
-feComponentTransfer
-feComposite
-feConvolveMatrix
-feDiffuseLighting
-feDisplacementMap
-feDistantLight
-feDropShadow
-feFlood
-feFuncA
-feFuncB
-feFuncG
-feFuncR
-feGaussianBlur
-feImage
-feMerge
-feMergeNode
-feMorphology
-feOffset
-fePointLight
-feSpecularLighting
-feSpotLight
-feTile
-feTurbulence
-filter
-#if ENABLE_SVG_FONTS
-font
-font_face
-font_face_format
-font_face_name
-font_face_src
-font_face_uri
-#endif
-foreignObject
-g
-#if ENABLE_SVG_FONTS
-glyph
-glyphRef
-hkern interfaceName=SVGHKernElement
-#endif
-image
-line
-linearGradient
-marker
-mask
-metadata
-#if ENABLE_SVG_FONTS
-missing_glyph
-#endif
-mpath interfaceName=SVGMPathElement
-path
-pattern
-polygon
-polyline
-radialGradient
-rect
-script constructorNeedsCreatedByParser
-stop
-style constructorNeedsCreatedByParser
-svg interfaceName=SVGSVGElement
-switch
-symbol
-text
-textPath
-title
-tspan interfaceName=SVGTSpanElement
-use constructorNeedsCreatedByParser
-view
-#if ENABLE_SVG_FONTS
-vkern interfaceName=SVGVKernElement
-#endif
diff --git a/chromium/third_party/WebKit/Source/core/testing/DummyPageHolder.cpp b/chromium/third_party/WebKit/Source/core/testing/DummyPageHolder.cpp
new file mode 100644
index 00000000000..e4095502200
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/testing/DummyPageHolder.cpp
@@ -0,0 +1,89 @@
+/*
+ * Copyright (c) 2013, Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/testing/DummyPageHolder.h"
+
+#include "core/frame/DOMWindow.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
+#include "wtf/Assertions.h"
+
+namespace WebCore {
+
+PassOwnPtr<DummyPageHolder> DummyPageHolder::create(const IntSize& initialViewSize)
+{
+ return adoptPtr(new DummyPageHolder(initialViewSize));
+}
+
+DummyPageHolder::DummyPageHolder(const IntSize& initialViewSize)
+{
+ m_pageClients.chromeClient = &m_chromeClient;
+ m_pageClients.contextMenuClient = &m_contextMenuClient;
+ m_pageClients.editorClient = &m_editorClient;
+ m_pageClients.dragClient = &m_dragClient;
+ m_pageClients.inspectorClient = &m_inspectorClient;
+ m_pageClients.backForwardClient = &m_backForwardClient;
+
+ m_page = adoptPtr(new Page(m_pageClients));
+
+ m_frame = Frame::create(FrameInit::create(0, m_page.get(), &m_frameLoaderClient));
+ m_frame->setView(FrameView::create(m_frame.get(), initialViewSize));
+ m_frame->init();
+}
+
+DummyPageHolder::~DummyPageHolder()
+{
+ m_page.clear();
+ ASSERT(m_frame->hasOneRef());
+ m_frame.clear();
+}
+
+Page& DummyPageHolder::page() const
+{
+ return *m_page;
+}
+
+Frame& DummyPageHolder::frame() const
+{
+ return *m_frame;
+}
+
+FrameView& DummyPageHolder::frameView() const
+{
+ return *m_frame->view();
+}
+
+Document& DummyPageHolder::document() const
+{
+ return *m_frame->domWindow()->document();
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/testing/DummyPageHolder.h b/chromium/third_party/WebKit/Source/core/testing/DummyPageHolder.h
new file mode 100644
index 00000000000..d80f4dc083b
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/testing/DummyPageHolder.h
@@ -0,0 +1,88 @@
+/*
+ * Copyright (c) 2013, Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef DummyPageHolder_h
+#define DummyPageHolder_h
+
+#include "core/loader/EmptyClients.h"
+#include "core/page/Page.h"
+#include "platform/geometry/IntSize.h"
+#include "wtf/FastAllocBase.h"
+#include "wtf/Noncopyable.h"
+#include "wtf/OwnPtr.h"
+#include "wtf/PassOwnPtr.h"
+
+namespace WebCore {
+
+class Document;
+class Frame;
+class FrameView;
+class IntSize;
+
+// Creates a dummy Page, Frame, and FrameView whose clients are all no-op.
+//
+// This class can be used when you write unit tests for components which do not work correctly without renderers.
+// To make sure the renderers are created, you need to call |frameView().layout()| after you add nodes into
+// |document()|.
+//
+// Since DummyPageHolder stores empty clients in it, it must outlive the Page, Frame, FrameView and any other objects
+// created by it. DummyPageHolder's destructor ensures this condition by checking remaining references to the Frame.
+
+class DummyPageHolder {
+ WTF_MAKE_NONCOPYABLE(DummyPageHolder);
+ WTF_MAKE_FAST_ALLOCATED;
+public:
+ static PassOwnPtr<DummyPageHolder> create(const IntSize& initialViewSize = IntSize());
+ ~DummyPageHolder();
+
+ Page& page() const;
+ Frame& frame() const;
+ FrameView& frameView() const;
+ Document& document() const;
+
+private:
+ explicit DummyPageHolder(const IntSize& initialViewSize);
+
+ OwnPtr<Page> m_page;
+ RefPtr<Frame> m_frame;
+
+ Page::PageClients m_pageClients;
+ EmptyChromeClient m_chromeClient;
+ EmptyContextMenuClient m_contextMenuClient;
+ EmptyEditorClient m_editorClient;
+ EmptyDragClient m_dragClient;
+ EmptyInspectorClient m_inspectorClient;
+ EmptyBackForwardClient m_backForwardClient;
+ EmptyFrameLoaderClient m_frameLoaderClient;
+};
+
+} // namespace WebCore
+
+#endif // DummyPageHolder_h
diff --git a/chromium/third_party/WebKit/Source/core/testing/GCObservation.cpp b/chromium/third_party/WebKit/Source/core/testing/GCObservation.cpp
index 90738d495bb..7c25450115b 100644
--- a/chromium/third_party/WebKit/Source/core/testing/GCObservation.cpp
+++ b/chromium/third_party/WebKit/Source/core/testing/GCObservation.cpp
@@ -33,9 +33,9 @@
namespace WebCore {
-static void makeWeakCallback(v8::Isolate*, v8::Persistent<v8::Value>*, GCObservation* observation)
+static void setWeakCallback(const v8::WeakCallbackData<v8::Value, GCObservation>& data)
{
- observation->setWasCollected();
+ data.GetParameter()->setWasCollected();
}
void GCObservation::setWasCollected()
@@ -49,8 +49,7 @@ GCObservation::GCObservation(v8::Handle<v8::Value> observedValue)
: m_observed(v8::Isolate::GetCurrent(), observedValue)
, m_collected(false)
{
- m_observed.makeWeak(this, makeWeakCallback);
+ m_observed.setWeak(this, setWeakCallback);
}
} // namespace WebCore
-
diff --git a/chromium/third_party/WebKit/Source/core/testing/InspectorFrontendClientLocal.cpp b/chromium/third_party/WebKit/Source/core/testing/InspectorFrontendClientLocal.cpp
index 3d57d2617a4..f61a422654d 100644
--- a/chromium/third_party/WebKit/Source/core/testing/InspectorFrontendClientLocal.cpp
+++ b/chromium/third_party/WebKit/Source/core/testing/InspectorFrontendClientLocal.cpp
@@ -32,15 +32,15 @@
#include "InspectorFrontendClientLocal.h"
#include "bindings/v8/ScriptObject.h"
+#include "bindings/v8/ScriptState.h"
#include "core/inspector/InspectorController.h"
#include "core/inspector/InspectorFrontendHost.h"
#include "core/page/Page.h"
-#include "core/page/Settings.h"
-#include "core/platform/Timer.h"
+#include "core/frame/Settings.h"
+#include "platform/Timer.h"
#include "public/platform/Platform.h"
#include "public/platform/WebThread.h"
#include "wtf/Deque.h"
-#include "wtf/text/WTFString.h"
namespace WebCore {
@@ -68,7 +68,7 @@ public:
private:
void schedule()
{
- class TaskImpl : public WebKit::WebThread::Task {
+ class TaskImpl : public blink::WebThread::Task {
public:
RefPtr<InspectorBackendMessageQueue> owner;
virtual void run()
@@ -78,7 +78,7 @@ private:
};
TaskImpl* taskImpl = new TaskImpl;
taskImpl->owner = this;
- WebKit::Platform::current()->currentThread()->postTask(taskImpl);
+ blink::Platform::current()->currentThread()->postTask(taskImpl);
}
void deliver()
diff --git a/chromium/third_party/WebKit/Source/core/testing/InternalProfilers.cpp b/chromium/third_party/WebKit/Source/core/testing/InternalProfilers.cpp
index 4560ee4ae35..95d706f90cb 100644
--- a/chromium/third_party/WebKit/Source/core/testing/InternalProfilers.cpp
+++ b/chromium/third_party/WebKit/Source/core/testing/InternalProfilers.cpp
@@ -40,22 +40,22 @@ namespace WebCore {
void InternalProfilers::startHeapProfiling(const String& prefix)
{
- WebKit::Platform::current()->startHeapProfiling(prefix);
+ blink::Platform::current()->startHeapProfiling(prefix);
}
void InternalProfilers::stopHeapProfiling()
{
- WebKit::Platform::current()->stopHeapProfiling();
+ blink::Platform::current()->stopHeapProfiling();
}
void InternalProfilers::dumpHeapProfiling(const String& reason)
{
- WebKit::Platform::current()->dumpHeapProfiling(reason);
+ blink::Platform::current()->dumpHeapProfiling(reason);
}
String InternalProfilers::getHeapProfile()
{
- String text = WebKit::Platform::current()->getHeapProfile();
+ String text = blink::Platform::current()->getHeapProfile();
// Only return the first line which contains total numbers
// because whole dump is too big and too noisy to process in JavaScript.
return text.substring(0, text.find('\n'));
diff --git a/chromium/third_party/WebKit/Source/core/testing/InternalSettings.cpp b/chromium/third_party/WebKit/Source/core/testing/InternalSettings.cpp
index 33c45eb4a23..41c75658894 100644
--- a/chromium/third_party/WebKit/Source/core/testing/InternalSettings.cpp
+++ b/chromium/third_party/WebKit/Source/core/testing/InternalSettings.cpp
@@ -31,26 +31,26 @@
#include "bindings/v8/ExceptionState.h"
#include "core/dom/ExceptionCode.h"
#include "core/page/Page.h"
-#include "core/page/Settings.h"
-#include "core/platform/ColorChooser.h"
-#include "core/platform/Supplementable.h"
-#include "core/platform/text/LocaleToScriptMapping.h"
+#include "core/frame/Settings.h"
+#include "platform/ColorChooser.h"
+#include "platform/Supplementable.h"
+#include "platform/text/LocaleToScriptMapping.h"
#define InternalSettingsGuardForSettingsReturn(returnValue) \
if (!settings()) { \
- es.throwDOMException(InvalidAccessError); \
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError); \
return returnValue; \
}
#define InternalSettingsGuardForSettings() \
if (!settings()) { \
- es.throwDOMException(InvalidAccessError); \
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError); \
return; \
}
#define InternalSettingsGuardForPage() \
if (!page()) { \
- es.throwDOMException(InvalidAccessError); \
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError); \
return; \
}
@@ -65,16 +65,18 @@ InternalSettings::Backup::Backup(Settings* settings)
, m_originalEditingBehavior(settings->editingBehaviorType())
, m_originalTextAutosizingEnabled(settings->textAutosizingEnabled())
, m_originalTextAutosizingWindowSizeOverride(settings->textAutosizingWindowSizeOverride())
- , m_originalTextAutosizingFontScaleFactor(settings->textAutosizingFontScaleFactor())
+ , m_originalAccessibilityFontScaleFactor(settings->accessibilityFontScaleFactor())
, m_originalMediaTypeOverride(settings->mediaTypeOverride())
, m_originalMockScrollbarsEnabled(settings->mockScrollbarsEnabled())
, m_langAttributeAwareFormControlUIEnabled(RuntimeEnabledFeatures::langAttributeAwareFormControlUIEnabled())
- , m_imagesEnabled(settings->areImagesEnabled())
+ , m_imagesEnabled(settings->imagesEnabled())
, m_shouldDisplaySubtitles(settings->shouldDisplaySubtitles())
, m_shouldDisplayCaptions(settings->shouldDisplayCaptions())
, m_shouldDisplayTextDescriptions(settings->shouldDisplayTextDescriptions())
, m_defaultVideoPosterURL(settings->defaultVideoPosterURL())
- , m_originalCompositorDrivenAcceleratedScrollEnabled(settings->isCompositorDrivenAcceleratedScrollingEnabled())
+ , m_originalCompositorDrivenAcceleratedScrollEnabled(settings->compositorDrivenAcceleratedScrollingEnabled())
+ , m_originalLayerSquashingEnabled(settings->layerSquashingEnabled())
+ , m_originalPasswordGenerationDecorationEnabled(settings->passwordGenerationDecorationEnabled())
{
}
@@ -88,7 +90,7 @@ void InternalSettings::Backup::restoreTo(Settings* settings)
settings->setEditingBehaviorType(m_originalEditingBehavior);
settings->setTextAutosizingEnabled(m_originalTextAutosizingEnabled);
settings->setTextAutosizingWindowSizeOverride(m_originalTextAutosizingWindowSizeOverride);
- settings->setTextAutosizingFontScaleFactor(m_originalTextAutosizingFontScaleFactor);
+ settings->setAccessibilityFontScaleFactor(m_originalAccessibilityFontScaleFactor);
settings->setMediaTypeOverride(m_originalMediaTypeOverride);
settings->setMockScrollbarsEnabled(m_originalMockScrollbarsEnabled);
RuntimeEnabledFeatures::setLangAttributeAwareFormControlUIEnabled(m_langAttributeAwareFormControlUIEnabled);
@@ -98,6 +100,9 @@ void InternalSettings::Backup::restoreTo(Settings* settings)
settings->setShouldDisplayTextDescriptions(m_shouldDisplayTextDescriptions);
settings->setDefaultVideoPosterURL(m_defaultVideoPosterURL);
settings->setCompositorDrivenAcceleratedScrollingEnabled(m_originalCompositorDrivenAcceleratedScrollEnabled);
+ settings->setLayerSquashingEnabled(m_originalLayerSquashingEnabled);
+ settings->setPasswordGenerationDecorationEnabled(m_originalPasswordGenerationDecorationEnabled);
+ settings->genericFontFamilySettings().reset();
}
// We can't use RefCountedSupplement because that would try to make InternalSettings RefCounted
@@ -157,7 +162,7 @@ Settings* InternalSettings::settings() const
return &page()->settings();
}
-void InternalSettings::setMockScrollbarsEnabled(bool enabled, ExceptionState& es)
+void InternalSettings::setMockScrollbarsEnabled(bool enabled, ExceptionState& exceptionState)
{
InternalSettingsGuardForSettings();
settings()->setMockScrollbarsEnabled(enabled);
@@ -183,13 +188,13 @@ void InternalSettings::setOverlayScrollbarsEnabled(bool enabled)
RuntimeEnabledFeatures::setOverlayScrollbarsEnabled(enabled);
}
-void InternalSettings::setTouchEventEmulationEnabled(bool enabled, ExceptionState& es)
+void InternalSettings::setTouchEventEmulationEnabled(bool enabled, ExceptionState& exceptionState)
{
InternalSettingsGuardForSettings();
settings()->setTouchEventEmulationEnabled(enabled);
}
-void InternalSettings::setViewportEnabled(bool enabled, ExceptionState& es)
+void InternalSettings::setViewportEnabled(bool enabled, ExceptionState& exceptionState)
{
InternalSettingsGuardForSettings();
settings()->setViewportEnabled(enabled);
@@ -197,84 +202,112 @@ void InternalSettings::setViewportEnabled(bool enabled, ExceptionState& es)
// FIXME: This is a temporary flag and should be removed once accelerated
// overflow scroll is ready (crbug.com/254111).
-void InternalSettings::setCompositorDrivenAcceleratedScrollingEnabled(bool enabled, ExceptionState& es)
+void InternalSettings::setCompositorDrivenAcceleratedScrollingEnabled(bool enabled, ExceptionState& exceptionState)
{
InternalSettingsGuardForSettings();
settings()->setCompositorDrivenAcceleratedScrollingEnabled(enabled);
}
-typedef void (Settings::*SetFontFamilyFunction)(const AtomicString&, UScriptCode);
-static void setFontFamily(Settings* settings, const String& family, const String& script, SetFontFamilyFunction setter)
+// FIXME: This is a temporary flag and should be removed once squashing is
+// ready (crbug.com/261605).
+void InternalSettings::setLayerSquashingEnabled(bool enabled, ExceptionState& exceptionState)
{
- UScriptCode code = scriptNameToCode(script);
- if (code != USCRIPT_INVALID_CODE)
- (settings->*setter)(family, code);
+ InternalSettingsGuardForSettings();
+ settings()->setLayerSquashingEnabled(enabled);
}
-void InternalSettings::setStandardFontFamily(const String& family, const String& script, ExceptionState& es)
+void InternalSettings::setStandardFontFamily(const String& family, const String& script, ExceptionState& exceptionState)
{
InternalSettingsGuardForSettings();
- setFontFamily(settings(), family, script, &Settings::setStandardFontFamily);
+ UScriptCode code = scriptNameToCode(script);
+ if (code == USCRIPT_INVALID_CODE)
+ return;
+ settings()->genericFontFamilySettings().setStandard(family, code);
+ m_page->setNeedsRecalcStyleInAllFrames();
}
-void InternalSettings::setSerifFontFamily(const String& family, const String& script, ExceptionState& es)
+void InternalSettings::setSerifFontFamily(const String& family, const String& script, ExceptionState& exceptionState)
{
InternalSettingsGuardForSettings();
- setFontFamily(settings(), family, script, &Settings::setSerifFontFamily);
+ UScriptCode code = scriptNameToCode(script);
+ if (code == USCRIPT_INVALID_CODE)
+ return;
+ settings()->genericFontFamilySettings().setSerif(family, code);
+ m_page->setNeedsRecalcStyleInAllFrames();
}
-void InternalSettings::setSansSerifFontFamily(const String& family, const String& script, ExceptionState& es)
+void InternalSettings::setSansSerifFontFamily(const String& family, const String& script, ExceptionState& exceptionState)
{
InternalSettingsGuardForSettings();
- setFontFamily(settings(), family, script, &Settings::setSansSerifFontFamily);
+ UScriptCode code = scriptNameToCode(script);
+ if (code == USCRIPT_INVALID_CODE)
+ return;
+ settings()->genericFontFamilySettings().setSansSerif(family, code);
+ m_page->setNeedsRecalcStyleInAllFrames();
}
-void InternalSettings::setFixedFontFamily(const String& family, const String& script, ExceptionState& es)
+void InternalSettings::setFixedFontFamily(const String& family, const String& script, ExceptionState& exceptionState)
{
InternalSettingsGuardForSettings();
- setFontFamily(settings(), family, script, &Settings::setFixedFontFamily);
+ UScriptCode code = scriptNameToCode(script);
+ if (code == USCRIPT_INVALID_CODE)
+ return;
+ settings()->genericFontFamilySettings().setFixed(family, code);
+ m_page->setNeedsRecalcStyleInAllFrames();
}
-void InternalSettings::setCursiveFontFamily(const String& family, const String& script, ExceptionState& es)
+void InternalSettings::setCursiveFontFamily(const String& family, const String& script, ExceptionState& exceptionState)
{
InternalSettingsGuardForSettings();
- setFontFamily(settings(), family, script, &Settings::setCursiveFontFamily);
+ UScriptCode code = scriptNameToCode(script);
+ if (code == USCRIPT_INVALID_CODE)
+ return;
+ settings()->genericFontFamilySettings().setCursive(family, code);
+ m_page->setNeedsRecalcStyleInAllFrames();
}
-void InternalSettings::setFantasyFontFamily(const String& family, const String& script, ExceptionState& es)
+void InternalSettings::setFantasyFontFamily(const String& family, const String& script, ExceptionState& exceptionState)
{
InternalSettingsGuardForSettings();
- setFontFamily(settings(), family, script, &Settings::setFantasyFontFamily);
+ UScriptCode code = scriptNameToCode(script);
+ if (code == USCRIPT_INVALID_CODE)
+ return;
+ settings()->genericFontFamilySettings().setFantasy(family, code);
+ m_page->setNeedsRecalcStyleInAllFrames();
}
-void InternalSettings::setPictographFontFamily(const String& family, const String& script, ExceptionState& es)
+void InternalSettings::setPictographFontFamily(const String& family, const String& script, ExceptionState& exceptionState)
{
InternalSettingsGuardForSettings();
- setFontFamily(settings(), family, script, &Settings::setPictographFontFamily);
+ UScriptCode code = scriptNameToCode(script);
+ if (code == USCRIPT_INVALID_CODE)
+ return;
+ settings()->genericFontFamilySettings().setPictograph(family, code);
+ m_page->setNeedsRecalcStyleInAllFrames();
}
-void InternalSettings::setTextAutosizingEnabled(bool enabled, ExceptionState& es)
+void InternalSettings::setTextAutosizingEnabled(bool enabled, ExceptionState& exceptionState)
{
InternalSettingsGuardForSettings();
settings()->setTextAutosizingEnabled(enabled);
}
-void InternalSettings::setTextAutosizingWindowSizeOverride(int width, int height, ExceptionState& es)
+void InternalSettings::setTextAutosizingWindowSizeOverride(int width, int height, ExceptionState& exceptionState)
{
InternalSettingsGuardForSettings();
settings()->setTextAutosizingWindowSizeOverride(IntSize(width, height));
}
-void InternalSettings::setMediaTypeOverride(const String& mediaType, ExceptionState& es)
+void InternalSettings::setMediaTypeOverride(const String& mediaType, ExceptionState& exceptionState)
{
InternalSettingsGuardForSettings();
settings()->setMediaTypeOverride(mediaType);
}
-void InternalSettings::setTextAutosizingFontScaleFactor(float fontScaleFactor, ExceptionState& es)
+void InternalSettings::setAccessibilityFontScaleFactor(float fontScaleFactor, ExceptionState& exceptionState)
{
InternalSettingsGuardForSettings();
- settings()->setTextAutosizingFontScaleFactor(fontScaleFactor);
+ settings()->setAccessibilityFontScaleFactor(fontScaleFactor);
}
void InternalSettings::setCSSExclusionsEnabled(bool enabled)
@@ -282,7 +315,7 @@ void InternalSettings::setCSSExclusionsEnabled(bool enabled)
RuntimeEnabledFeatures::setCSSExclusionsEnabled(enabled);
}
-void InternalSettings::setEditingBehavior(const String& editingBehavior, ExceptionState& es)
+void InternalSettings::setEditingBehavior(const String& editingBehavior, ExceptionState& exceptionState)
{
InternalSettingsGuardForSettings();
if (equalIgnoringCase(editingBehavior, "win"))
@@ -294,7 +327,7 @@ void InternalSettings::setEditingBehavior(const String& editingBehavior, Excepti
else if (equalIgnoringCase(editingBehavior, "android"))
settings()->setEditingBehaviorType(EditingAndroidBehavior);
else
- es.throwDOMException(SyntaxError);
+ exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
}
void InternalSettings::setLangAttributeAwareFormControlUIEnabled(bool enabled)
@@ -302,16 +335,22 @@ void InternalSettings::setLangAttributeAwareFormControlUIEnabled(bool enabled)
RuntimeEnabledFeatures::setLangAttributeAwareFormControlUIEnabled(enabled);
}
-void InternalSettings::setImagesEnabled(bool enabled, ExceptionState& es)
+void InternalSettings::setImagesEnabled(bool enabled, ExceptionState& exceptionState)
{
InternalSettingsGuardForSettings();
settings()->setImagesEnabled(enabled);
}
-void InternalSettings::setDefaultVideoPosterURL(const String& url, ExceptionState& es)
+void InternalSettings::setDefaultVideoPosterURL(const String& url, ExceptionState& exceptionState)
{
InternalSettingsGuardForSettings();
settings()->setDefaultVideoPosterURL(url);
}
+void InternalSettings::setPasswordGenerationDecorationEnabled(bool enabled, ExceptionState& exceptionState)
+{
+ InternalSettingsGuardForSettings();
+ settings()->setPasswordGenerationDecorationEnabled(enabled);
+}
+
}
diff --git a/chromium/third_party/WebKit/Source/core/testing/InternalSettings.h b/chromium/third_party/WebKit/Source/core/testing/InternalSettings.h
index 7433e1eb89e..cc064baa413 100644
--- a/chromium/third_party/WebKit/Source/core/testing/InternalSettings.h
+++ b/chromium/third_party/WebKit/Source/core/testing/InternalSettings.h
@@ -29,7 +29,7 @@
#include "InternalSettingsGenerated.h"
#include "core/editing/EditingBehaviorTypes.h"
-#include "core/platform/graphics/IntSize.h"
+#include "platform/geometry/IntSize.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefCounted.h"
#include "wtf/text/WTFString.h"
@@ -57,7 +57,7 @@ public:
EditingBehaviorType m_originalEditingBehavior;
bool m_originalTextAutosizingEnabled;
IntSize m_originalTextAutosizingWindowSizeOverride;
- float m_originalTextAutosizingFontScaleFactor;
+ float m_originalAccessibilityFontScaleFactor;
String m_originalMediaTypeOverride;
bool m_originalMockScrollbarsEnabled;
bool m_langAttributeAwareFormControlUIEnabled;
@@ -67,6 +67,8 @@ public:
bool m_shouldDisplayTextDescriptions;
String m_defaultVideoPosterURL;
bool m_originalCompositorDrivenAcceleratedScrollEnabled;
+ bool m_originalLayerSquashingEnabled;
+ bool m_originalPasswordGenerationDecorationEnabled;
};
static PassRefPtr<InternalSettings> create(Page* page)
@@ -92,8 +94,9 @@ public:
void setImagesEnabled(bool, ExceptionState&);
void setMediaTypeOverride(const String& mediaType, ExceptionState&);
void setMockScrollbarsEnabled(bool, ExceptionState&);
+ void setPasswordGenerationDecorationEnabled(bool, ExceptionState&);
void setTextAutosizingEnabled(bool, ExceptionState&);
- void setTextAutosizingFontScaleFactor(float fontScaleFactor, ExceptionState&);
+ void setAccessibilityFontScaleFactor(float fontScaleFactor, ExceptionState&);
void setTextAutosizingWindowSizeOverride(int width, int height, ExceptionState&);
void setTouchEventEmulationEnabled(bool, ExceptionState&);
void setViewportEnabled(bool, ExceptionState&);
@@ -102,6 +105,10 @@ public:
// overflow scroll is ready (crbug.com/254111).
void setCompositorDrivenAcceleratedScrollingEnabled(bool, ExceptionState&);
+ // FIXME: This is a temporary flag and should be removed once squashing is
+ // ready (crbug.com/261605).
+ void setLayerSquashingEnabled(bool, ExceptionState&);
+
// FIXME: The following are RuntimeEnabledFeatures and likely
// cannot be changed after process start. These setters should
// be removed or moved onto internals.runtimeFlags:
diff --git a/chromium/third_party/WebKit/Source/core/testing/InternalSettings.idl b/chromium/third_party/WebKit/Source/core/testing/InternalSettings.idl
index 9e03edce2b8..d4f598460ea 100644
--- a/chromium/third_party/WebKit/Source/core/testing/InternalSettings.idl
+++ b/chromium/third_party/WebKit/Source/core/testing/InternalSettings.idl
@@ -38,10 +38,10 @@
[RaisesException] void setPictographFontFamily(DOMString family, DOMString script);
[RaisesException] void setTextAutosizingEnabled(boolean enabled);
[RaisesException] void setTextAutosizingWindowSizeOverride(long width, long height);
- [RaisesException] void setTextAutosizingFontScaleFactor(float fontScaleFactor);
+ [RaisesException] void setAccessibilityFontScaleFactor(float fontScaleFactor);
[RaisesException] void setMediaTypeOverride(DOMString mediaTypeOverride);
[RaisesException] void setEditingBehavior(DOMString behavior);
-
+ [RaisesException] void setPasswordGenerationDecorationEnabled(boolean enabled);
[RaisesException] void setImagesEnabled(boolean enabled);
[RaisesException] void setDefaultVideoPosterURL(DOMString poster);
[RaisesException] void setViewportEnabled(boolean enabled);
@@ -50,6 +50,10 @@
// overflow scroll is ready (crbug.com/254111).
[RaisesException] void setCompositorDrivenAcceleratedScrollingEnabled(boolean enabled);
+ // FIXME: This is a temporary flag and should be removed once squashing is
+ // ready (crbug.com/261605).
+ [RaisesException] void setLayerSquashingEnabled(boolean enabled);
+
// FIXME: The following are RuntimeEnabledFeatures and likely
// cannot be changed after process start. These setters should
// be removed or moved onto internals.runtimeFlags:
diff --git a/chromium/third_party/WebKit/Source/core/testing/Internals.cpp b/chromium/third_party/WebKit/Source/core/testing/Internals.cpp
index 746a0ab4884..5abaf92407e 100644
--- a/chromium/third_party/WebKit/Source/core/testing/Internals.cpp
+++ b/chromium/third_party/WebKit/Source/core/testing/Internals.cpp
@@ -27,6 +27,7 @@
#include "config.h"
#include "Internals.h"
+#include <v8.h>
#include "HTMLNames.h"
#include "InspectorFrontendClientLocal.h"
#include "InternalProfilers.h"
@@ -44,6 +45,7 @@
#include "core/animation/DocumentTimeline.h"
#include "core/css/StyleSheetContents.h"
#include "core/css/resolver/StyleResolver.h"
+#include "core/css/resolver/StyleResolverStats.h"
#include "core/css/resolver/ViewportStyleResolver.h"
#include "core/dom/ClientRect.h"
#include "core/dom/ClientRectList.h"
@@ -58,19 +60,23 @@
#include "core/dom/Range.h"
#include "core/dom/StaticNodeList.h"
#include "core/dom/TreeScope.h"
-#include "core/dom/ViewportArguments.h"
+#include "core/dom/ViewportDescription.h"
#include "core/dom/WheelController.h"
#include "core/dom/shadow/ComposedTreeWalker.h"
#include "core/dom/shadow/ElementShadow.h"
#include "core/dom/shadow/SelectRuleFeatureSet.h"
#include "core/dom/shadow/ShadowRoot.h"
#include "core/editing/Editor.h"
+#include "core/editing/PlainTextRange.h"
#include "core/editing/SpellCheckRequester.h"
+#include "core/editing/SpellChecker.h"
#include "core/editing/TextIterator.h"
#include "core/fetch/MemoryCache.h"
#include "core/fetch/ResourceFetcher.h"
-#include "core/history/BackForwardController.h"
+#include "core/frame/DOMPoint.h"
+#include "core/frame/Frame.h"
#include "core/history/HistoryItem.h"
+#include "core/html/HTMLIFrameElement.h"
#include "core/html/HTMLInputElement.h"
#include "core/html/HTMLMediaElement.h"
#include "core/html/HTMLSelectElement.h"
@@ -88,29 +94,16 @@
#include "core/loader/FrameLoader.h"
#include "core/page/Chrome.h"
#include "core/page/ChromeClient.h"
-#include "core/page/DOMPoint.h"
-#include "core/page/DOMWindow.h"
+#include "core/frame/DOMWindow.h"
#include "core/page/EventHandler.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameView.h"
+#include "core/frame/FrameView.h"
#include "core/page/Page.h"
#include "core/page/PagePopupController.h"
#include "core/page/PrintContext.h"
-#include "core/page/Settings.h"
-#include "core/page/animation/AnimationController.h"
-#include "core/page/scrolling/ScrollingCoordinator.h"
-#include "core/platform/ColorChooser.h"
-#include "core/platform/Cursor.h"
-#include "core/platform/Language.h"
-#include "core/platform/chromium/TraceEvent.h"
-#include "core/platform/graphics/GraphicsLayer.h"
-#include "core/platform/graphics/IntRect.h"
-#include "core/platform/graphics/filters/FilterOperation.h"
-#include "core/platform/graphics/filters/FilterOperations.h"
-#include "core/platform/graphics/gpu/SharedGraphicsContext3D.h"
-#include "core/platform/mock/PlatformSpeechSynthesizerMock.h"
+#include "core/frame/Settings.h"
+#include "core/frame/animation/AnimationController.h"
+#include "core/rendering/CompositedLayerMapping.h"
#include "core/rendering/RenderLayer.h"
-#include "core/rendering/RenderLayerBacking.h"
#include "core/rendering/RenderLayerCompositor.h"
#include "core/rendering/RenderMenuList.h"
#include "core/rendering/RenderObject.h"
@@ -118,13 +111,21 @@
#include "core/rendering/RenderView.h"
#include "core/testing/GCObservation.h"
#include "core/workers/WorkerThread.h"
-#include "modules/speech/DOMWindowSpeechSynthesis.h"
-#include "modules/speech/SpeechSynthesis.h"
+#include "platform/ColorChooser.h"
+#include "platform/Cursor.h"
+#include "platform/Language.h"
+#include "platform/TraceEvent.h"
+#include "platform/geometry/IntRect.h"
+#include "platform/geometry/LayoutRect.h"
+#include "platform/graphics/GraphicsLayer.h"
+#include "platform/graphics/filters/FilterOperation.h"
+#include "platform/graphics/filters/FilterOperations.h"
+#include "platform/graphics/gpu/SharedGraphicsContext3D.h"
+#include "platform/weborigin/SchemeRegistry.h"
#include "public/platform/WebLayer.h"
-#include "weborigin/SchemeRegistry.h"
+#include "wtf/InstanceCounter.h"
#include "wtf/dtoa.h"
#include "wtf/text/StringBuffer.h"
-#include <v8.h>
namespace WebCore {
@@ -172,7 +173,7 @@ static SpellCheckRequester* spellCheckRequester(Document* document)
{
if (!document || !document->frame())
return 0;
- return &document->frame()->editor().spellCheckRequester();
+ return &document->frame()->spellChecker().spellCheckRequester();
}
const char* Internals::internalsId = "internals";
@@ -191,6 +192,7 @@ void Internals::resetToConsistentState(Page* page)
ASSERT(page);
page->setDeviceScaleFactor(1);
+ page->setIsCursorVisible(true);
page->setPageScaleFactor(1, IntPoint(0, 0));
page->setPagination(Pagination());
TextRun::setAllowsRoundingHacks(false);
@@ -198,10 +200,15 @@ void Internals::resetToConsistentState(Page* page)
delete s_pagePopupDriver;
s_pagePopupDriver = 0;
page->chrome().client().resetPagePopupDriver();
- if (!page->mainFrame()->editor().isContinuousSpellCheckingEnabled())
- page->mainFrame()->editor().toggleContinuousSpellChecking();
+ if (!page->mainFrame()->spellChecker().isContinuousSpellCheckingEnabled())
+ page->mainFrame()->spellChecker().toggleContinuousSpellChecking();
if (page->mainFrame()->editor().isOverwriteModeEnabled())
page->mainFrame()->editor().toggleOverwriteModeEnabled();
+
+ if (ScrollingCoordinator* scrollingCoordinator = page->scrollingCoordinator())
+ scrollingCoordinator->reset();
+
+ page->mainFrame()->view()->clear();
}
Internals::Internals(Document* document)
@@ -213,7 +220,7 @@ Internals::Internals(Document* document)
Document* Internals::contextDocument() const
{
- return toDocument(scriptExecutionContext());
+ return toDocument(executionContext());
}
Frame* Internals::frame() const
@@ -271,6 +278,19 @@ PassRefPtr<GCObservation> Internals::observeGC(ScriptValue scriptValue)
return GCObservation::create(observedValue);
}
+unsigned Internals::updateStyleAndReturnAffectedElementCount(ExceptionState& exceptionState) const
+{
+ Document* document = contextDocument();
+ if (!document) {
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+ return 0;
+ }
+
+ unsigned beforeCount = document->styleEngine()->resolverAccessCount();
+ document->updateStyleIfNeeded();
+ return document->styleEngine()->resolverAccessCount() - beforeCount;
+}
+
bool Internals::isPreloaded(const String& url)
{
Document* document = contextDocument();
@@ -290,81 +310,110 @@ void Internals::crash()
CRASH();
}
-PassRefPtr<Element> Internals::createContentElement(ExceptionState& es)
+void Internals::setStyleResolverStatsEnabled(bool enabled)
+{
+ Document* document = contextDocument();
+ if (enabled)
+ document->ensureStyleResolver().enableStats(StyleResolver::ReportSlowStats);
+ else
+ document->ensureStyleResolver().disableStats();
+}
+
+String Internals::styleResolverStatsReport(ExceptionState& exceptionState) const
+{
+ Document* document = contextDocument();
+ if (!document->ensureStyleResolver().stats()) {
+ exceptionState.throwDOMException(InvalidStateError, "Style resolver stats not enabled");
+ return String();
+ }
+ return document->ensureStyleResolver().stats()->report();
+}
+
+String Internals::styleResolverStatsTotalsReport(ExceptionState& exceptionState) const
+{
+ Document* document = contextDocument();
+ if (!document->ensureStyleResolver().statsTotals()) {
+ exceptionState.throwDOMException(InvalidStateError, "Style resolver stats not enabled");
+ return String();
+ }
+ return document->ensureStyleResolver().statsTotals()->report();
+}
+
+PassRefPtr<Element> Internals::createContentElement(ExceptionState& exceptionState)
{
Document* document = contextDocument();
if (!document) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return 0;
}
return HTMLContentElement::create(*document);
}
-bool Internals::isValidContentSelect(Element* insertionPoint, ExceptionState& es)
+bool Internals::isValidContentSelect(Element* insertionPoint, ExceptionState& exceptionState)
{
if (!insertionPoint || !insertionPoint->isInsertionPoint()) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return false;
}
return isHTMLContentElement(insertionPoint) && toHTMLContentElement(insertionPoint)->isSelectValid();
}
-Node* Internals::treeScopeRootNode(Node* node, ExceptionState& es)
+Node* Internals::treeScopeRootNode(Node* node, ExceptionState& exceptionState)
{
if (!node) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return 0;
}
return node->treeScope().rootNode();
}
-Node* Internals::parentTreeScope(Node* node, ExceptionState& es)
+Node* Internals::parentTreeScope(Node* node, ExceptionState& exceptionState)
{
if (!node) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return 0;
}
const TreeScope* parentTreeScope = node->treeScope().parentTreeScope();
return parentTreeScope ? parentTreeScope->rootNode() : 0;
}
-bool Internals::hasSelectorForIdInShadow(Element* host, const String& idValue, ExceptionState& es)
+bool Internals::hasSelectorForIdInShadow(Element* host, const String& idValue, ExceptionState& exceptionState)
{
if (!host || !host->shadow()) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return 0;
}
return host->shadow()->ensureSelectFeatureSet().hasSelectorForId(idValue);
}
-bool Internals::hasSelectorForClassInShadow(Element* host, const String& className, ExceptionState& es)
+bool Internals::hasSelectorForClassInShadow(Element* host, const String& className, ExceptionState& exceptionState)
{
if (!host || !host->shadow()) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return 0;
}
return host->shadow()->ensureSelectFeatureSet().hasSelectorForClass(className);
}
-bool Internals::hasSelectorForAttributeInShadow(Element* host, const String& attributeName, ExceptionState& es)
+bool Internals::hasSelectorForAttributeInShadow(Element* host, const String& attributeName, ExceptionState& exceptionState)
{
if (!host || !host->shadow()) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return 0;
}
return host->shadow()->ensureSelectFeatureSet().hasSelectorForAttribute(attributeName);
}
-bool Internals::hasSelectorForPseudoClassInShadow(Element* host, const String& pseudoClass, ExceptionState& es)
+bool Internals::hasSelectorForPseudoClassInShadow(Element* host, const String& pseudoClass, ExceptionState& exceptionState)
{
if (!host || !host->shadow()) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return 0;
}
@@ -388,10 +437,10 @@ bool Internals::hasSelectorForPseudoClassInShadow(Element* host, const String& p
return false;
}
-unsigned short Internals::compareTreeScopePosition(const Node* node1, const Node* node2, ExceptionState& es) const
+unsigned short Internals::compareTreeScopePosition(const Node* node1, const Node* node2, ExceptionState& exceptionState) const
{
if (!node1 || !node2) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return 0;
}
const TreeScope* treeScope1 = node1->isDocumentNode() ? static_cast<const TreeScope*>(toDocument(node1)) :
@@ -399,7 +448,7 @@ unsigned short Internals::compareTreeScopePosition(const Node* node1, const Node
const TreeScope* treeScope2 = node2->isDocumentNode() ? static_cast<const TreeScope*>(toDocument(node2)) :
node2->isShadowRoot() ? static_cast<const TreeScope*>(toShadowRoot(node2)) : 0;
if (!treeScope1 || !treeScope2) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return 0;
}
return treeScope1->comparePosition(*treeScope2);
@@ -408,99 +457,58 @@ unsigned short Internals::compareTreeScopePosition(const Node* node1, const Node
unsigned Internals::numberOfActiveAnimations() const
{
Frame* contextFrame = frame();
+ Document* document = contextFrame->document();
if (RuntimeEnabledFeatures::webAnimationsCSSEnabled())
- return frame()->document()->timeline()->numberOfActiveAnimationsForTesting();
- if (AnimationController* controller = contextFrame->animation())
- return controller->numberOfActiveAnimations(contextFrame->document());
- return 0;
-}
-
-void Internals::suspendAnimations(Document* document, ExceptionState& es) const
-{
- if (!document || !document->frame()) {
- es.throwDOMException(InvalidAccessError);
- return;
- }
-
- if (!RuntimeEnabledFeatures::webAnimationsCSSEnabled()) {
- AnimationController* controller = document->frame()->animation();
- if (!controller)
- return;
-
- controller->suspendAnimations();
- }
+ return document->timeline()->numberOfActiveAnimationsForTesting() + document->transitionTimeline()->numberOfActiveAnimationsForTesting();
+ return contextFrame->animation().numberOfActiveAnimations(document);
}
-void Internals::resumeAnimations(Document* document, ExceptionState& es) const
-{
- if (!document || !document->frame()) {
- es.throwDOMException(InvalidAccessError);
- return;
- }
-
- if (!RuntimeEnabledFeatures::webAnimationsCSSEnabled()) {
- AnimationController* controller = document->frame()->animation();
- if (!controller)
- return;
-
- controller->resumeAnimations();
- }
-}
-
-void Internals::pauseAnimations(double pauseTime, ExceptionState& es)
+void Internals::pauseAnimations(double pauseTime, ExceptionState& exceptionState)
{
if (pauseTime < 0) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return;
}
- if (RuntimeEnabledFeatures::webAnimationsCSSEnabled())
+ if (RuntimeEnabledFeatures::webAnimationsCSSEnabled()) {
frame()->document()->timeline()->pauseAnimationsForTesting(pauseTime);
- else
- frame()->animation()->pauseAnimationsForTesting(pauseTime);
+ frame()->document()->transitionTimeline()->pauseAnimationsForTesting(pauseTime);
+ } else {
+ frame()->animation().pauseAnimationsForTesting(pauseTime);
+ }
}
-bool Internals::hasShadowInsertionPoint(const Node* root, ExceptionState& es) const
+bool Internals::hasShadowInsertionPoint(const Node* root, ExceptionState& exceptionState) const
{
if (root && root->isShadowRoot())
return toShadowRoot(root)->containsShadowElements();
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return 0;
}
-bool Internals::hasContentElement(const Node* root, ExceptionState& es) const
+bool Internals::hasContentElement(const Node* root, ExceptionState& exceptionState) const
{
if (root && root->isShadowRoot())
return toShadowRoot(root)->containsContentElements();
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return 0;
}
-size_t Internals::countElementShadow(const Node* root, ExceptionState& es) const
+size_t Internals::countElementShadow(const Node* root, ExceptionState& exceptionState) const
{
if (!root || !root->isShadowRoot()) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return 0;
}
return toShadowRoot(root)->childShadowRootCount();
}
-bool Internals::attached(Node* node, ExceptionState& es)
-{
- if (!node) {
- es.throwDOMException(InvalidAccessError);
- return false;
- }
-
- return node->attached();
-}
-
-Node* Internals::nextSiblingByWalker(Node* node, ExceptionState& es)
+Node* Internals::nextSiblingByWalker(Node* node, ExceptionState& exceptionState)
{
if (!node) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return 0;
}
ComposedTreeWalker walker(node);
@@ -508,10 +516,10 @@ Node* Internals::nextSiblingByWalker(Node* node, ExceptionState& es)
return walker.get();
}
-Node* Internals::firstChildByWalker(Node* node, ExceptionState& es)
+Node* Internals::firstChildByWalker(Node* node, ExceptionState& exceptionState)
{
if (!node) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return 0;
}
ComposedTreeWalker walker(node);
@@ -519,10 +527,10 @@ Node* Internals::firstChildByWalker(Node* node, ExceptionState& es)
return walker.get();
}
-Node* Internals::lastChildByWalker(Node* node, ExceptionState& es)
+Node* Internals::lastChildByWalker(Node* node, ExceptionState& exceptionState)
{
if (!node) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return 0;
}
ComposedTreeWalker walker(node);
@@ -530,10 +538,10 @@ Node* Internals::lastChildByWalker(Node* node, ExceptionState& es)
return walker.get();
}
-Node* Internals::nextNodeByWalker(Node* node, ExceptionState& es)
+Node* Internals::nextNodeByWalker(Node* node, ExceptionState& exceptionState)
{
if (!node) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return 0;
}
ComposedTreeWalker walker(node);
@@ -541,10 +549,10 @@ Node* Internals::nextNodeByWalker(Node* node, ExceptionState& es)
return walker.get();
}
-Node* Internals::previousNodeByWalker(Node* node, ExceptionState& es)
+Node* Internals::previousNodeByWalker(Node* node, ExceptionState& exceptionState)
{
if (!node) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return 0;
}
ComposedTreeWalker walker(node);
@@ -552,35 +560,35 @@ Node* Internals::previousNodeByWalker(Node* node, ExceptionState& es)
return walker.get();
}
-String Internals::elementRenderTreeAsText(Element* element, ExceptionState& es)
+String Internals::elementRenderTreeAsText(Element* element, ExceptionState& exceptionState)
{
if (!element) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return String();
}
String representation = externalRepresentation(element);
if (representation.isEmpty()) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return String();
}
return representation;
}
-size_t Internals::numberOfScopedHTMLStyleChildren(const Node* scope, ExceptionState& es) const
+size_t Internals::numberOfScopedHTMLStyleChildren(const Node* scope, ExceptionState& exceptionState) const
{
if (scope && (scope->isElementNode() || scope->isShadowRoot()))
return scope->numberOfScopedHTMLStyleChildren();
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return 0;
}
-PassRefPtr<CSSComputedStyleDeclaration> Internals::computedStyleIncludingVisitedInfo(Node* node, ExceptionState& es) const
+PassRefPtr<CSSComputedStyleDeclaration> Internals::computedStyleIncludingVisitedInfo(Node* node, ExceptionState& exceptionState) const
{
if (!node) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return 0;
}
@@ -588,30 +596,30 @@ PassRefPtr<CSSComputedStyleDeclaration> Internals::computedStyleIncludingVisited
return CSSComputedStyleDeclaration::create(node, allowVisitedStyle);
}
-ShadowRoot* Internals::ensureShadowRoot(Element* host, ExceptionState& es)
+ShadowRoot* Internals::ensureShadowRoot(Element* host, ExceptionState& exceptionState)
{
if (!host) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return 0;
}
if (ElementShadow* shadow = host->shadow())
return shadow->youngestShadowRoot();
- return host->createShadowRoot(es).get();
+ return host->createShadowRoot(exceptionState).get();
}
-ShadowRoot* Internals::shadowRoot(Element* host, ExceptionState& es)
+ShadowRoot* Internals::shadowRoot(Element* host, ExceptionState& exceptionState)
{
// FIXME: Internals::shadowRoot() in tests should be converted to youngestShadowRoot() or oldestShadowRoot().
// https://bugs.webkit.org/show_bug.cgi?id=78465
- return youngestShadowRoot(host, es);
+ return youngestShadowRoot(host, exceptionState);
}
-ShadowRoot* Internals::youngestShadowRoot(Element* host, ExceptionState& es)
+ShadowRoot* Internals::youngestShadowRoot(Element* host, ExceptionState& exceptionState)
{
if (!host) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return 0;
}
@@ -620,10 +628,10 @@ ShadowRoot* Internals::youngestShadowRoot(Element* host, ExceptionState& es)
return 0;
}
-ShadowRoot* Internals::oldestShadowRoot(Element* host, ExceptionState& es)
+ShadowRoot* Internals::oldestShadowRoot(Element* host, ExceptionState& exceptionState)
{
if (!host) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return 0;
}
@@ -632,30 +640,30 @@ ShadowRoot* Internals::oldestShadowRoot(Element* host, ExceptionState& es)
return 0;
}
-ShadowRoot* Internals::youngerShadowRoot(Node* shadow, ExceptionState& es)
+ShadowRoot* Internals::youngerShadowRoot(Node* shadow, ExceptionState& exceptionState)
{
if (!shadow || !shadow->isShadowRoot()) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return 0;
}
return toShadowRoot(shadow)->youngerShadowRoot();
}
-ShadowRoot* Internals::olderShadowRoot(Node* shadow, ExceptionState& es)
+ShadowRoot* Internals::olderShadowRoot(Node* shadow, ExceptionState& exceptionState)
{
if (!shadow || !shadow->isShadowRoot()) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return 0;
}
return toShadowRoot(shadow)->olderShadowRoot();
}
-String Internals::shadowRootType(const Node* root, ExceptionState& es) const
+String Internals::shadowRootType(const Node* root, ExceptionState& exceptionState) const
{
if (!root || !root->isShadowRoot()) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return String();
}
@@ -670,36 +678,24 @@ String Internals::shadowRootType(const Node* root, ExceptionState& es) const
}
}
-Element* Internals::includerFor(Node* node, ExceptionState& es)
-{
- if (!node) {
- es.throwDOMException(InvalidAccessError);
- return 0;
- }
-
- NodeRenderingTraversal::ParentDetails parentDetails;
- NodeRenderingTraversal::parent(node, &parentDetails);
- return parentDetails.insertionPoint();
-}
-
-String Internals::shadowPseudoId(Element* element, ExceptionState& es)
+String Internals::shadowPseudoId(Element* element, ExceptionState& exceptionState)
{
if (!element) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return String();
}
return element->shadowPseudoId().string();
}
-void Internals::setShadowPseudoId(Element* element, const String& id, ExceptionState& es)
+void Internals::setShadowPseudoId(Element* element, const String& id, ExceptionState& exceptionState)
{
if (!element) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return;
}
- return element->setPart(id);
+ return element->setPseudo(id);
}
String Internals::visiblePlaceholder(Element* element)
@@ -719,50 +715,27 @@ void Internals::selectColorInColorChooser(Element* element, const String& colorV
toHTMLInputElement(element)->selectColorInColorChooser(Color(colorValue));
}
-Vector<String> Internals::formControlStateOfPreviousHistoryItem(ExceptionState& es)
+Vector<String> Internals::formControlStateOfHistoryItem(ExceptionState& exceptionState)
{
- HistoryItem* mainItem = frame()->loader()->history()->previousItem();
+ HistoryItem* mainItem = frame()->loader().currentItem();
if (!mainItem) {
- es.throwDOMException(InvalidAccessError);
- return Vector<String>();
- }
- String uniqueName = frame()->tree()->uniqueName();
- if (mainItem->target() != uniqueName && !mainItem->childItemWithTarget(uniqueName)) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return Vector<String>();
}
- return mainItem->target() == uniqueName ? mainItem->documentState() : mainItem->childItemWithTarget(uniqueName)->documentState();
+ return mainItem->documentState();
}
-void Internals::setFormControlStateOfPreviousHistoryItem(const Vector<String>& state, ExceptionState& es)
+void Internals::setFormControlStateOfHistoryItem(const Vector<String>& state, ExceptionState& exceptionState)
{
- HistoryItem* mainItem = frame()->loader()->history()->previousItem();
+ HistoryItem* mainItem = frame()->loader().currentItem();
if (!mainItem) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return;
}
- String uniqueName = frame()->tree()->uniqueName();
- if (mainItem->target() == uniqueName)
- mainItem->setDocumentState(state);
- else if (HistoryItem* subItem = mainItem->childItemWithTarget(uniqueName))
- subItem->setDocumentState(state);
- else
- es.throwDOMException(InvalidAccessError);
+ mainItem->setDocumentState(state);
}
-void Internals::enableMockSpeechSynthesizer()
-{
- Document* document = contextDocument();
- if (!document || !document->domWindow())
- return;
- SpeechSynthesis* synthesis = DOMWindowSpeechSynthesis::speechSynthesis(document->domWindow());
- if (!synthesis)
- return;
-
- synthesis->setPlatformSynthesizer(PlatformSpeechSynthesizerMock::create(synthesis));
-}
-
-void Internals::setEnableMockPagePopup(bool enabled, ExceptionState& es)
+void Internals::setEnableMockPagePopup(bool enabled, ExceptionState& exceptionState)
{
Document* document = contextDocument();
if (!document || !document->page())
@@ -782,32 +755,32 @@ PassRefPtr<PagePopupController> Internals::pagePopupController()
return s_pagePopupDriver ? s_pagePopupDriver->pagePopupController() : 0;
}
-PassRefPtr<ClientRect> Internals::unscaledViewportRect(ExceptionState& es)
+PassRefPtr<ClientRect> Internals::unscaledViewportRect(ExceptionState& exceptionState)
{
Document* document = contextDocument();
if (!document || !document->view()) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return ClientRect::create();
}
return ClientRect::create(document->view()->visibleContentRect());
}
-PassRefPtr<ClientRect> Internals::absoluteCaretBounds(ExceptionState& es)
+PassRefPtr<ClientRect> Internals::absoluteCaretBounds(ExceptionState& exceptionState)
{
Document* document = contextDocument();
if (!document || !document->frame()) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return ClientRect::create();
}
return ClientRect::create(document->frame()->selection().absoluteCaretBounds());
}
-PassRefPtr<ClientRect> Internals::boundingBox(Element* element, ExceptionState& es)
+PassRefPtr<ClientRect> Internals::boundingBox(Element* element, ExceptionState& exceptionState)
{
if (!element) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return ClientRect::create();
}
@@ -818,10 +791,10 @@ PassRefPtr<ClientRect> Internals::boundingBox(Element* element, ExceptionState&
return ClientRect::create(renderer->absoluteBoundingBoxRectIgnoringTransforms());
}
-PassRefPtr<ClientRectList> Internals::inspectorHighlightRects(Document* document, ExceptionState& es)
+PassRefPtr<ClientRectList> Internals::inspectorHighlightRects(Document* document, ExceptionState& exceptionState)
{
if (!document || !document->page()) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return ClientRectList::create();
}
@@ -830,26 +803,26 @@ PassRefPtr<ClientRectList> Internals::inspectorHighlightRects(Document* document
return ClientRectList::create(highlight.quads);
}
-unsigned Internals::markerCountForNode(Node* node, const String& markerType, ExceptionState& es)
+unsigned Internals::markerCountForNode(Node* node, const String& markerType, ExceptionState& exceptionState)
{
if (!node) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return 0;
}
DocumentMarker::MarkerTypes markerTypes = 0;
if (!markerTypesFrom(markerType, markerTypes)) {
- es.throwDOMException(SyntaxError);
+ exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
return 0;
}
return node->document().markers()->markersFor(node, markerTypes).size();
}
-unsigned Internals::activeMarkerCountForNode(Node* node, ExceptionState& es)
+unsigned Internals::activeMarkerCountForNode(Node* node, ExceptionState& exceptionState)
{
if (!node) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return 0;
}
@@ -866,16 +839,16 @@ unsigned Internals::activeMarkerCountForNode(Node* node, ExceptionState& es)
return activeMarkerCount;
}
-DocumentMarker* Internals::markerAt(Node* node, const String& markerType, unsigned index, ExceptionState& es)
+DocumentMarker* Internals::markerAt(Node* node, const String& markerType, unsigned index, ExceptionState& exceptionState)
{
if (!node) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return 0;
}
DocumentMarker::MarkerTypes markerTypes = 0;
if (!markerTypesFrom(markerType, markerTypes)) {
- es.throwDOMException(SyntaxError);
+ exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
return 0;
}
@@ -885,17 +858,17 @@ DocumentMarker* Internals::markerAt(Node* node, const String& markerType, unsign
return markers[index];
}
-PassRefPtr<Range> Internals::markerRangeForNode(Node* node, const String& markerType, unsigned index, ExceptionState& es)
+PassRefPtr<Range> Internals::markerRangeForNode(Node* node, const String& markerType, unsigned index, ExceptionState& exceptionState)
{
- DocumentMarker* marker = markerAt(node, markerType, index, es);
+ DocumentMarker* marker = markerAt(node, markerType, index, exceptionState);
if (!marker)
return 0;
return Range::create(node->document(), node, marker->startOffset(), node, marker->endOffset());
}
-String Internals::markerDescriptionForNode(Node* node, const String& markerType, unsigned index, ExceptionState& es)
+String Internals::markerDescriptionForNode(Node* node, const String& markerType, unsigned index, ExceptionState& exceptionState)
{
- DocumentMarker* marker = markerAt(node, markerType, index, es);
+ DocumentMarker* marker = markerAt(node, markerType, index, exceptionState);
if (!marker)
return String();
return marker->description();
@@ -907,20 +880,20 @@ void Internals::addTextMatchMarker(const Range* range, bool isActive)
range->ownerDocument().markers()->addTextMatchMarker(range, isActive);
}
-void Internals::setMarkersActive(Node* node, unsigned startOffset, unsigned endOffset, bool active, ExceptionState& es)
+void Internals::setMarkersActive(Node* node, unsigned startOffset, unsigned endOffset, bool active, ExceptionState& exceptionState)
{
if (!node) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return;
}
node->document().markers()->setMarkersActive(node, startOffset, endOffset, active);
}
-void Internals::setScrollViewPosition(Document* document, long x, long y, ExceptionState& es)
+void Internals::setScrollViewPosition(Document* document, long x, long y, ExceptionState& exceptionState)
{
if (!document || !document->view()) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return;
}
@@ -935,10 +908,10 @@ void Internals::setScrollViewPosition(Document* document, long x, long y, Except
frameView->setConstrainsScrollingToContentEdge(constrainsScrollingToContentEdgeOldValue);
}
-void Internals::setPagination(Document* document, const String& mode, int gap, int pageLength, ExceptionState& es)
+void Internals::setPagination(Document* document, const String& mode, int gap, int pageLength, ExceptionState& exceptionState)
{
if (!document || !document->page()) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return;
}
Page* page = document->page();
@@ -955,7 +928,7 @@ void Internals::setPagination(Document* document, const String& mode, int gap, i
else if (mode == "BottomToTopPaginated")
pagination.mode = Pagination::BottomToTopPaginated;
else {
- es.throwDOMException(SyntaxError);
+ exceptionState.throwUninformativeAndGenericDOMException(SyntaxError);
return;
}
@@ -964,20 +937,23 @@ void Internals::setPagination(Document* document, const String& mode, int gap, i
page->setPagination(pagination);
}
-String Internals::viewportAsText(Document* document, float, int availableWidth, int availableHeight, ExceptionState& es)
+String Internals::viewportAsText(Document* document, float, int availableWidth, int availableHeight, ExceptionState& exceptionState)
{
if (!document || !document->page()) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return String();
}
+
+ document->updateLayoutIgnorePendingStylesheets();
+
Page* page = document->page();
// Update initial viewport size.
IntSize initialViewportSize(availableWidth, availableHeight);
document->page()->mainFrame()->view()->setFrameRect(IntRect(IntPoint::zero(), initialViewportSize));
- ViewportArguments arguments = page->viewportArguments();
- PageScaleConstraints constraints = arguments.resolve(initialViewportSize);
+ ViewportDescription description = page->viewportDescription();
+ PageScaleConstraints constraints = description.resolve(initialViewportSize);
constraints.fitToContentsWidth(constraints.layoutSize.width(), availableWidth);
@@ -996,15 +972,15 @@ String Internals::viewportAsText(Document* document, float, int availableWidth,
builder.append(String::number(constraints.maximumScale));
builder.appendLiteral("] and userScalable ");
- builder.append(arguments.userZoom ? "true" : "false");
+ builder.append(description.userZoom ? "true" : "false");
return builder.toString();
}
-bool Internals::wasLastChangeUserEdit(Element* textField, ExceptionState& es)
+bool Internals::wasLastChangeUserEdit(Element* textField, ExceptionState& exceptionState)
{
if (!textField) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return false;
}
@@ -1015,92 +991,92 @@ bool Internals::wasLastChangeUserEdit(Element* textField, ExceptionState& es)
if (textField->tagName() == "TEXTAREA")
return toHTMLTextAreaElement(textField)->lastChangeWasUserEdit();
- es.throwDOMException(InvalidNodeTypeError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidNodeTypeError);
return false;
}
-bool Internals::elementShouldAutoComplete(Element* element, ExceptionState& es)
+bool Internals::elementShouldAutoComplete(Element* element, ExceptionState& exceptionState)
{
if (!element) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return false;
}
if (element->hasTagName(inputTag))
return toHTMLInputElement(element)->shouldAutocomplete();
- es.throwDOMException(InvalidNodeTypeError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidNodeTypeError);
return false;
}
-String Internals::suggestedValue(Element* element, ExceptionState& es)
+String Internals::suggestedValue(Element* element, ExceptionState& exceptionState)
{
if (!element) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return String();
}
if (!element->hasTagName(inputTag)) {
- es.throwDOMException(InvalidNodeTypeError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidNodeTypeError);
return String();
}
return toHTMLInputElement(element)->suggestedValue();
}
-void Internals::setSuggestedValue(Element* element, const String& value, ExceptionState& es)
+void Internals::setSuggestedValue(Element* element, const String& value, ExceptionState& exceptionState)
{
if (!element) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return;
}
if (!element->hasTagName(inputTag)) {
- es.throwDOMException(InvalidNodeTypeError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidNodeTypeError);
return;
}
toHTMLInputElement(element)->setSuggestedValue(value);
}
-void Internals::setEditingValue(Element* element, const String& value, ExceptionState& es)
+void Internals::setEditingValue(Element* element, const String& value, ExceptionState& exceptionState)
{
if (!element) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return;
}
if (!element->hasTagName(inputTag)) {
- es.throwDOMException(InvalidNodeTypeError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidNodeTypeError);
return;
}
toHTMLInputElement(element)->setEditingValue(value);
}
-void Internals::setAutofilled(Element* element, bool enabled, ExceptionState& es)
+void Internals::setAutofilled(Element* element, bool enabled, ExceptionState& exceptionState)
{
- if (!element->hasTagName(inputTag)) {
- es.throwDOMException(InvalidAccessError);
+ if (!element->isFormControlElement()) {
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return;
}
- toHTMLInputElement(element)->setAutofilled(enabled);
+ toHTMLFormControlElement(element)->setAutofilled(enabled);
}
-void Internals::scrollElementToRect(Element* element, long x, long y, long w, long h, ExceptionState& es)
+void Internals::scrollElementToRect(Element* element, long x, long y, long w, long h, ExceptionState& exceptionState)
{
if (!element || !element->document().view()) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return;
}
FrameView* frameView = element->document().view();
frameView->scrollElementToRect(element, IntRect(x, y, w, h));
}
-void Internals::paintControlTints(Document* document, ExceptionState& es)
+void Internals::paintControlTints(Document* document, ExceptionState& exceptionState)
{
if (!document || !document->view()) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return;
}
@@ -1108,65 +1084,59 @@ void Internals::paintControlTints(Document* document, ExceptionState& es)
frameView->paintControlTints();
}
-PassRefPtr<Range> Internals::rangeFromLocationAndLength(Element* scope, int rangeLocation, int rangeLength, ExceptionState& es)
+PassRefPtr<Range> Internals::rangeFromLocationAndLength(Element* scope, int rangeLocation, int rangeLength, ExceptionState& exceptionState)
{
if (!scope) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return 0;
}
// TextIterator depends on Layout information, make sure layout it up to date.
scope->document().updateLayoutIgnorePendingStylesheets();
- return TextIterator::rangeFromLocationAndLength(scope, rangeLocation, rangeLength);
+ return PlainTextRange(rangeLocation, rangeLocation + rangeLength).createRange(*scope);
}
-unsigned Internals::locationFromRange(Element* scope, const Range* range, ExceptionState& es)
+unsigned Internals::locationFromRange(Element* scope, const Range* range, ExceptionState& exceptionState)
{
if (!scope || !range) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return 0;
}
- // TextIterator depends on Layout information, make sure layout it up to date.
+ // PlainTextRange depends on Layout information, make sure layout it up to date.
scope->document().updateLayoutIgnorePendingStylesheets();
- size_t location = 0;
- size_t unusedLength = 0;
- TextIterator::getLocationAndLengthFromRange(scope, range, location, unusedLength);
- return location;
+ return PlainTextRange::create(*scope, *range).start();
}
-unsigned Internals::lengthFromRange(Element* scope, const Range* range, ExceptionState& es)
+unsigned Internals::lengthFromRange(Element* scope, const Range* range, ExceptionState& exceptionState)
{
if (!scope || !range) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return 0;
}
- // TextIterator depends on Layout information, make sure layout it up to date.
+ // PlainTextRange depends on Layout information, make sure layout it up to date.
scope->document().updateLayoutIgnorePendingStylesheets();
- size_t unusedLocation = 0;
- size_t length = 0;
- TextIterator::getLocationAndLengthFromRange(scope, range, unusedLocation, length);
- return length;
+ return PlainTextRange::create(*scope, *range).length();
}
-String Internals::rangeAsText(const Range* range, ExceptionState& es)
+String Internals::rangeAsText(const Range* range, ExceptionState& exceptionState)
{
if (!range) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return String();
}
return range->text();
}
-PassRefPtr<DOMPoint> Internals::touchPositionAdjustedToBestClickableNode(long x, long y, long width, long height, Document* document, ExceptionState& es)
+PassRefPtr<DOMPoint> Internals::touchPositionAdjustedToBestClickableNode(long x, long y, long width, long height, Document* document, ExceptionState& exceptionState)
{
if (!document || !document->frame()) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return 0;
}
@@ -1178,17 +1148,17 @@ PassRefPtr<DOMPoint> Internals::touchPositionAdjustedToBestClickableNode(long x,
Node* targetNode;
IntPoint adjustedPoint;
- bool foundNode = document->frame()->eventHandler()->bestClickableNodeForTouchPoint(point, radius, adjustedPoint, targetNode);
+ bool foundNode = document->frame()->eventHandler().bestClickableNodeForTouchPoint(point, radius, adjustedPoint, targetNode);
if (foundNode)
return DOMPoint::create(adjustedPoint.x(), adjustedPoint.y());
return 0;
}
-Node* Internals::touchNodeAdjustedToBestClickableNode(long x, long y, long width, long height, Document* document, ExceptionState& es)
+Node* Internals::touchNodeAdjustedToBestClickableNode(long x, long y, long width, long height, Document* document, ExceptionState& exceptionState)
{
if (!document || !document->frame()) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return 0;
}
@@ -1199,14 +1169,14 @@ Node* Internals::touchNodeAdjustedToBestClickableNode(long x, long y, long width
Node* targetNode;
IntPoint adjustedPoint;
- document->frame()->eventHandler()->bestClickableNodeForTouchPoint(point, radius, adjustedPoint, targetNode);
+ document->frame()->eventHandler().bestClickableNodeForTouchPoint(point, radius, adjustedPoint, targetNode);
return targetNode;
}
-PassRefPtr<DOMPoint> Internals::touchPositionAdjustedToBestContextMenuNode(long x, long y, long width, long height, Document* document, ExceptionState& es)
+PassRefPtr<DOMPoint> Internals::touchPositionAdjustedToBestContextMenuNode(long x, long y, long width, long height, Document* document, ExceptionState& exceptionState)
{
if (!document || !document->frame()) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return 0;
}
@@ -1218,17 +1188,17 @@ PassRefPtr<DOMPoint> Internals::touchPositionAdjustedToBestContextMenuNode(long
Node* targetNode = 0;
IntPoint adjustedPoint;
- bool foundNode = document->frame()->eventHandler()->bestContextMenuNodeForTouchPoint(point, radius, adjustedPoint, targetNode);
+ bool foundNode = document->frame()->eventHandler().bestContextMenuNodeForTouchPoint(point, radius, adjustedPoint, targetNode);
if (foundNode)
return DOMPoint::create(adjustedPoint.x(), adjustedPoint.y());
return DOMPoint::create(x, y);
}
-Node* Internals::touchNodeAdjustedToBestContextMenuNode(long x, long y, long width, long height, Document* document, ExceptionState& es)
+Node* Internals::touchNodeAdjustedToBestContextMenuNode(long x, long y, long width, long height, Document* document, ExceptionState& exceptionState)
{
if (!document || !document->frame()) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return 0;
}
@@ -1239,14 +1209,14 @@ Node* Internals::touchNodeAdjustedToBestContextMenuNode(long x, long y, long wid
Node* targetNode = 0;
IntPoint adjustedPoint;
- document->frame()->eventHandler()->bestContextMenuNodeForTouchPoint(point, radius, adjustedPoint, targetNode);
+ document->frame()->eventHandler().bestContextMenuNodeForTouchPoint(point, radius, adjustedPoint, targetNode);
return targetNode;
}
-PassRefPtr<ClientRect> Internals::bestZoomableAreaForTouchPoint(long x, long y, long width, long height, Document* document, ExceptionState& es)
+PassRefPtr<ClientRect> Internals::bestZoomableAreaForTouchPoint(long x, long y, long width, long height, Document* document, ExceptionState& exceptionState)
{
if (!document || !document->frame()) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return 0;
}
@@ -1257,7 +1227,7 @@ PassRefPtr<ClientRect> Internals::bestZoomableAreaForTouchPoint(long x, long y,
Node* targetNode;
IntRect zoomableArea;
- bool foundNode = document->frame()->eventHandler()->bestZoomableAreaForTouchPoint(point, radius, zoomableArea, targetNode);
+ bool foundNode = document->frame()->eventHandler().bestZoomableAreaForTouchPoint(point, radius, zoomableArea, targetNode);
if (foundNode)
return ClientRect::create(zoomableArea);
@@ -1265,24 +1235,24 @@ PassRefPtr<ClientRect> Internals::bestZoomableAreaForTouchPoint(long x, long y,
}
-int Internals::lastSpellCheckRequestSequence(Document* document, ExceptionState& es)
+int Internals::lastSpellCheckRequestSequence(Document* document, ExceptionState& exceptionState)
{
SpellCheckRequester* requester = spellCheckRequester(document);
if (!requester) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return -1;
}
return requester->lastRequestSequence();
}
-int Internals::lastSpellCheckProcessedSequence(Document* document, ExceptionState& es)
+int Internals::lastSpellCheckProcessedSequence(Document* document, ExceptionState& exceptionState)
{
SpellCheckRequester* requester = spellCheckRequester(document);
if (!requester) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return -1;
}
@@ -1299,20 +1269,20 @@ void Internals::setUserPreferredLanguages(const Vector<String>& languages)
WebCore::overrideUserPreferredLanguages(languages);
}
-unsigned Internals::wheelEventHandlerCount(Document* document, ExceptionState& es)
+unsigned Internals::wheelEventHandlerCount(Document* document, ExceptionState& exceptionState)
{
if (!document) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return 0;
}
return WheelController::from(document)->wheelEventHandlerCount();
}
-unsigned Internals::touchEventHandlerCount(Document* document, ExceptionState& es)
+unsigned Internals::touchEventHandlerCount(Document* document, ExceptionState& exceptionState)
{
if (!document) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return 0;
}
@@ -1328,25 +1298,29 @@ unsigned Internals::touchEventHandlerCount(Document* document, ExceptionState& e
static RenderLayer* findRenderLayerForGraphicsLayer(RenderLayer* searchRoot, GraphicsLayer* graphicsLayer, String* layerType)
{
- if (searchRoot->backing() && graphicsLayer == searchRoot->backing()->graphicsLayer())
+ if (searchRoot->hasCompositedLayerMapping() && graphicsLayer == searchRoot->compositedLayerMapping()->mainGraphicsLayer())
return searchRoot;
- if (graphicsLayer == searchRoot->layerForScrolling()) {
+ GraphicsLayer* layerForScrolling = searchRoot->scrollableArea() ? searchRoot->scrollableArea()->layerForScrolling() : 0;
+ if (graphicsLayer == layerForScrolling) {
*layerType = "scrolling";
return searchRoot;
}
- if (graphicsLayer == searchRoot->layerForHorizontalScrollbar()) {
+ GraphicsLayer* layerForHorizontalScrollbar = searchRoot->scrollableArea() ? searchRoot->scrollableArea()->layerForHorizontalScrollbar() : 0;
+ if (graphicsLayer == layerForHorizontalScrollbar) {
*layerType = "horizontalScrollbar";
return searchRoot;
}
- if (graphicsLayer == searchRoot->layerForVerticalScrollbar()) {
+ GraphicsLayer* layerForVerticalScrollbar = searchRoot->scrollableArea() ? searchRoot->scrollableArea()->layerForVerticalScrollbar() : 0;
+ if (graphicsLayer == layerForVerticalScrollbar) {
*layerType = "verticalScrollbar";
return searchRoot;
}
- if (graphicsLayer == searchRoot->layerForScrollCorner()) {
+ GraphicsLayer* layerForScrollCorner = searchRoot->scrollableArea() ? searchRoot->scrollableArea()->layerForScrollCorner() : 0;
+ if (graphicsLayer == layerForScrollCorner) {
*layerType = "scrollCorner";
return searchRoot;
}
@@ -1365,7 +1339,7 @@ static RenderLayer* findRenderLayerForGraphicsLayer(RenderLayer* searchRoot, Gra
// of rects returned by an SkRegion (which have been split apart for sorting
// purposes). No attempt is made to do this efficiently (eg. by relying on the
// sort criteria of SkRegion).
-static void mergeRects(WebKit::WebVector<WebKit::WebRect>& rects)
+static void mergeRects(blink::WebVector<blink::WebRect>& rects)
{
for (size_t i = 0; i < rects.size(); ++i) {
if (rects[i].isEmpty())
@@ -1380,23 +1354,23 @@ static void mergeRects(WebKit::WebVector<WebKit::WebRect>& rects)
if (rects[i].y == rects[j].y && rects[i].height == rects[j].height) {
if (rects[i].x + rects[i].width == rects[j].x) {
rects[i].width += rects[j].width;
- rects[j] = WebKit::WebRect();
+ rects[j] = blink::WebRect();
updated = true;
} else if (rects[i].x == rects[j].x + rects[j].width) {
rects[i].x = rects[j].x;
rects[i].width += rects[j].width;
- rects[j] = WebKit::WebRect();
+ rects[j] = blink::WebRect();
updated = true;
}
} else if (rects[i].x == rects[j].x && rects[i].width == rects[j].width) {
if (rects[i].y + rects[i].height == rects[j].y) {
rects[i].height += rects[j].height;
- rects[j] = WebKit::WebRect();
+ rects[j] = blink::WebRect();
updated = true;
} else if (rects[i].y == rects[j].y + rects[j].height) {
rects[i].y = rects[j].y;
rects[i].height += rects[j].height;
- rects[j] = WebKit::WebRect();
+ rects[j] = blink::WebRect();
updated = true;
}
}
@@ -1407,7 +1381,7 @@ static void mergeRects(WebKit::WebVector<WebKit::WebRect>& rects)
static void accumulateLayerRectList(RenderLayerCompositor* compositor, GraphicsLayer* graphicsLayer, LayerRectList* rects)
{
- WebKit::WebVector<WebKit::WebRect> layerRects = graphicsLayer->platformLayer()->touchEventHandlerRegion();
+ blink::WebVector<blink::WebRect> layerRects = graphicsLayer->platformLayer()->touchEventHandlerRegion();
if (!layerRects.isEmpty()) {
mergeRects(layerRects);
String layerType;
@@ -1424,16 +1398,18 @@ static void accumulateLayerRectList(RenderLayerCompositor* compositor, GraphicsL
accumulateLayerRectList(compositor, graphicsLayer->children()[i], rects);
}
-PassRefPtr<LayerRectList> Internals::touchEventTargetLayerRects(Document* document, ExceptionState& es)
+PassRefPtr<LayerRectList> Internals::touchEventTargetLayerRects(Document* document, ExceptionState& exceptionState)
{
if (!document || !document->view() || !document->page() || document != contextDocument()) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return 0;
}
- // Do any pending layouts (which may call touchEventTargetRectsChange) to ensure this
+ // Do any pending layout and compositing update (which may call touchEventTargetRectsChange) to ensure this
// really takes any previous changes into account.
- document->updateLayout();
+ forceCompositingUpdate(document, exceptionState);
+ if (exceptionState.hadException())
+ return 0;
if (RenderView* view = document->renderView()) {
if (RenderLayerCompositor* compositor = view->compositor()) {
@@ -1449,10 +1425,10 @@ PassRefPtr<LayerRectList> Internals::touchEventTargetLayerRects(Document* docume
}
PassRefPtr<NodeList> Internals::nodesFromRect(Document* document, int centerX, int centerY, unsigned topPadding, unsigned rightPadding,
- unsigned bottomPadding, unsigned leftPadding, bool ignoreClipping, bool allowShadowContent, bool allowChildFrameContent, ExceptionState& es) const
+ unsigned bottomPadding, unsigned leftPadding, bool ignoreClipping, bool allowShadowContent, bool allowChildFrameContent, ExceptionState& exceptionState) const
{
if (!document || !document->frame() || !document->frame()->view()) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return 0;
}
@@ -1470,7 +1446,7 @@ PassRefPtr<NodeList> Internals::nodesFromRect(Document* document, int centerX, i
if (ignoreClipping)
hitType |= HitTestRequest::IgnoreClipping;
if (!allowShadowContent)
- hitType |= HitTestRequest::DisallowShadowContent;
+ hitType |= HitTestRequest::ConfusingAndOftenMisusedDisallowShadowContent;
if (allowChildFrameContent)
hitType |= HitTestRequest::AllowChildFrameContent;
@@ -1498,9 +1474,9 @@ PassRefPtr<NodeList> Internals::nodesFromRect(Document* document, int centerX, i
return StaticNodeList::adopt(matches);
}
-void Internals::emitInspectorDidBeginFrame()
+void Internals::emitInspectorDidBeginFrame(int frameId)
{
- contextDocument()->page()->inspectorController().didBeginFrame();
+ contextDocument()->page()->inspectorController().didBeginFrame(frameId);
}
void Internals::emitInspectorDidCancelFrame()
@@ -1513,7 +1489,7 @@ bool Internals::hasSpellingMarker(Document* document, int from, int length, Exce
if (!document || !document->frame())
return 0;
- return document->frame()->editor().selectionStartHasMarkerFor(DocumentMarker::Spelling, from, length);
+ return document->frame()->spellChecker().selectionStartHasMarkerFor(DocumentMarker::Spelling, from, length);
}
void Internals::setContinuousSpellCheckingEnabled(bool enabled, ExceptionState&)
@@ -1521,8 +1497,8 @@ void Internals::setContinuousSpellCheckingEnabled(bool enabled, ExceptionState&)
if (!contextDocument() || !contextDocument()->frame())
return;
- if (enabled != contextDocument()->frame()->editor().isContinuousSpellCheckingEnabled())
- contextDocument()->frame()->editor().toggleContinuousSpellChecking();
+ if (enabled != contextDocument()->frame()->spellChecker().isContinuousSpellCheckingEnabled())
+ contextDocument()->frame()->spellChecker().toggleContinuousSpellChecking();
}
bool Internals::isOverwriteModeEnabled(Document* document, ExceptionState&)
@@ -1543,20 +1519,19 @@ void Internals::toggleOverwriteModeEnabled(Document* document, ExceptionState&)
unsigned Internals::numberOfLiveNodes() const
{
- if (StyleResolver* resolver = contextDocument()->styleResolverIfExists())
- resolver->clearStyleSharingList();
-
return InspectorCounters::counterValue(InspectorCounters::NodeCounter);
}
unsigned Internals::numberOfLiveDocuments() const
{
- if (StyleResolver* resolver = contextDocument()->styleResolverIfExists())
- resolver->clearStyleSharingList();
-
return InspectorCounters::counterValue(InspectorCounters::DocumentCounter);
}
+String Internals::dumpRefCountedInstanceCounts() const
+{
+ return WTF::dumpRefCountedInstanceCounts();
+}
+
Vector<String> Internals::consoleMessageArgumentCounts(Document* document) const
{
InstrumentingAgents* instrumentingAgents = instrumentationForPage(document->page());
@@ -1607,7 +1582,7 @@ void Internals::closeDummyInspectorFrontend()
m_frontendChannel.release();
- m_frontendWindow->close(m_frontendWindow->scriptExecutionContext());
+ m_frontendWindow->close(m_frontendWindow->executionContext());
m_frontendWindow.release();
}
@@ -1621,11 +1596,11 @@ Vector<unsigned long> Internals::setMemoryCacheCapacities(unsigned long minDeadB
return result;
}
-void Internals::setInspectorResourcesDataSizeLimits(int maximumResourcesContentSize, int maximumSingleResourceContentSize, ExceptionState& es)
+void Internals::setInspectorResourcesDataSizeLimits(int maximumResourcesContentSize, int maximumSingleResourceContentSize, ExceptionState& exceptionState)
{
Page* page = contextDocument()->frame()->page();
if (!page) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return;
}
page->inspectorController().setResourcesDataSizeLimitsFromInternals(maximumResourcesContentSize, maximumSingleResourceContentSize);
@@ -1636,7 +1611,7 @@ bool Internals::hasGrammarMarker(Document* document, int from, int length, Excep
if (!document || !document->frame())
return 0;
- return document->frame()->editor().selectionStartHasMarkerFor(DocumentMarker::Grammar, from, length);
+ return document->frame()->spellChecker().selectionStartHasMarkerFor(DocumentMarker::Grammar, from, length);
}
unsigned Internals::numberOfScrollableAreas(Document* document, ExceptionState&)
@@ -1646,7 +1621,7 @@ unsigned Internals::numberOfScrollableAreas(Document* document, ExceptionState&)
if (frame->view()->scrollableAreas())
count += frame->view()->scrollableAreas()->size();
- for (Frame* child = frame->tree()->firstChild(); child; child = child->tree()->nextSibling()) {
+ for (Frame* child = frame->tree().firstChild(); child; child = child->tree().nextSibling()) {
if (child->view() && child->view()->scrollableAreas())
count += child->view()->scrollableAreas()->size();
}
@@ -1654,30 +1629,30 @@ unsigned Internals::numberOfScrollableAreas(Document* document, ExceptionState&)
return count;
}
-bool Internals::isPageBoxVisible(Document* document, int pageNumber, ExceptionState& es)
+bool Internals::isPageBoxVisible(Document* document, int pageNumber, ExceptionState& exceptionState)
{
if (!document) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return false;
}
return document->isPageBoxVisible(pageNumber);
}
-String Internals::layerTreeAsText(Document* document, ExceptionState& es) const
+String Internals::layerTreeAsText(Document* document, ExceptionState& exceptionState) const
{
- return layerTreeAsText(document, 0, es);
+ return layerTreeAsText(document, 0, exceptionState);
}
-String Internals::elementLayerTreeAsText(Element* element, ExceptionState& es) const
+String Internals::elementLayerTreeAsText(Element* element, ExceptionState& exceptionState) const
{
- return elementLayerTreeAsText(element, 0, es);
+ return elementLayerTreeAsText(element, 0, exceptionState);
}
-static PassRefPtr<NodeList> paintOrderList(Element* element, ExceptionState& es, RenderLayer::PaintOrderListType type)
+static PassRefPtr<NodeList> paintOrderList(Element* element, ExceptionState& exceptionState, RenderLayerStackingNode::PaintOrderListType type)
{
if (!element) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return 0;
}
@@ -1685,35 +1660,35 @@ static PassRefPtr<NodeList> paintOrderList(Element* element, ExceptionState& es,
RenderObject* renderer = element->renderer();
if (!renderer || !renderer->isBox()) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return 0;
}
RenderLayer* layer = toRenderBox(renderer)->layer();
if (!layer) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return 0;
}
Vector<RefPtr<Node> > nodes;
- layer->computePaintOrderList(type, nodes);
+ layer->stackingNode()->computePaintOrderList(type, nodes);
return StaticNodeList::adopt(nodes);
}
-PassRefPtr<NodeList> Internals::paintOrderListBeforePromote(Element* element, ExceptionState& es)
+PassRefPtr<NodeList> Internals::paintOrderListBeforePromote(Element* element, ExceptionState& exceptionState)
{
- return paintOrderList(element, es, RenderLayer::BeforePromote);
+ return paintOrderList(element, exceptionState, RenderLayerStackingNode::BeforePromote);
}
-PassRefPtr<NodeList> Internals::paintOrderListAfterPromote(Element* element, ExceptionState& es)
+PassRefPtr<NodeList> Internals::paintOrderListAfterPromote(Element* element, ExceptionState& exceptionState)
{
- return paintOrderList(element, es, RenderLayer::AfterPromote);
+ return paintOrderList(element, exceptionState, RenderLayerStackingNode::AfterPromote);
}
-bool Internals::scrollsWithRespectTo(Element* element1, Element* element2, ExceptionState& es)
+bool Internals::scrollsWithRespectTo(Element* element1, Element* element2, ExceptionState& exceptionState)
{
if (!element1 || !element2) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return 0;
}
@@ -1722,24 +1697,24 @@ bool Internals::scrollsWithRespectTo(Element* element1, Element* element2, Excep
RenderObject* renderer1 = element1->renderer();
RenderObject* renderer2 = element2->renderer();
if (!renderer1 || !renderer2 || !renderer1->isBox() || !renderer2->isBox()) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return 0;
}
RenderLayer* layer1 = toRenderBox(renderer1)->layer();
RenderLayer* layer2 = toRenderBox(renderer2)->layer();
if (!layer1 || !layer2) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return 0;
}
return layer1->scrollsWithRespectTo(layer2);
}
-bool Internals::isUnclippedDescendant(Element* element, ExceptionState& es)
+bool Internals::isUnclippedDescendant(Element* element, ExceptionState& exceptionState)
{
if (!element) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return 0;
}
@@ -1747,33 +1722,57 @@ bool Internals::isUnclippedDescendant(Element* element, ExceptionState& es)
RenderObject* renderer = element->renderer();
if (!renderer || !renderer->isBox()) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return 0;
}
RenderLayer* layer = toRenderBox(renderer)->layer();
if (!layer) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return 0;
}
return layer->isUnclippedDescendant();
}
-String Internals::layerTreeAsText(Document* document, unsigned flags, ExceptionState& es) const
+bool Internals::needsCompositedScrolling(Element* element, ExceptionState& exceptionState)
+{
+ if (!element) {
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+ return 0;
+ }
+
+ element->document().updateLayout();
+
+ RenderObject* renderer = element->renderer();
+ if (!renderer || !renderer->isBox()) {
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+ return 0;
+ }
+
+ RenderLayer* layer = toRenderBox(renderer)->layer();
+ if (!layer) {
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+ return 0;
+ }
+
+ return layer->needsCompositedScrolling();
+}
+
+String Internals::layerTreeAsText(Document* document, unsigned flags, ExceptionState& exceptionState) const
{
if (!document || !document->frame()) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return String();
}
return document->frame()->layerTreeAsText(flags);
}
-String Internals::elementLayerTreeAsText(Element* element, unsigned flags, ExceptionState& es) const
+String Internals::elementLayerTreeAsText(Element* element, unsigned flags, ExceptionState& exceptionState) const
{
if (!element) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return String();
}
@@ -1781,78 +1780,107 @@ String Internals::elementLayerTreeAsText(Element* element, unsigned flags, Excep
RenderObject* renderer = element->renderer();
if (!renderer || !renderer->isBox()) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return String();
}
RenderLayer* layer = toRenderBox(renderer)->layer();
if (!layer
- || !layer->backing()
- || !layer->backing()->graphicsLayer()) {
+ || !layer->hasCompositedLayerMapping()
+ || !layer->compositedLayerMapping()->mainGraphicsLayer()) {
// Don't raise exception in these cases which may be normally used in tests.
return String();
}
- return layer->backing()->graphicsLayer()->layerTreeAsText(flags);
+ return layer->compositedLayerMapping()->mainGraphicsLayer()->layerTreeAsText(flags);
}
-static RenderLayer* getRenderLayerForElement(Element* element, ExceptionState& es)
+static RenderLayer* getRenderLayerForElement(Element* element, ExceptionState& exceptionState)
{
if (!element) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return 0;
}
RenderObject* renderer = element->renderer();
if (!renderer || !renderer->isBox()) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return 0;
}
RenderLayer* layer = toRenderBox(renderer)->layer();
if (!layer) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return 0;
}
return layer;
}
-void Internals::setNeedsCompositedScrolling(Element* element, unsigned needsCompositedScrolling, ExceptionState& es)
+void Internals::setNeedsCompositedScrolling(Element* element, unsigned needsCompositedScrolling, ExceptionState& exceptionState)
{
if (!element) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return;
}
element->document().updateLayout();
- if (RenderLayer* layer = getRenderLayerForElement(element, es))
- layer->setForceNeedsCompositedScrolling(static_cast<RenderLayer::ForceNeedsCompositedScrollingMode>(needsCompositedScrolling));
+ if (RenderLayer* layer = getRenderLayerForElement(element, exceptionState))
+ layer->scrollableArea()->setForceNeedsCompositedScrolling(static_cast<ForceNeedsCompositedScrollingMode>(needsCompositedScrolling));
}
-String Internals::repaintRectsAsText(Document* document, ExceptionState& es) const
+String Internals::repaintRectsAsText(Document* document, ExceptionState& exceptionState) const
{
if (!document || !document->frame()) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return String();
}
return document->frame()->trackedRepaintRectsAsText();
}
-String Internals::scrollingStateTreeAsText(Document* document, ExceptionState& es) const
+PassRefPtr<ClientRectList> Internals::repaintRects(Element* element, ExceptionState& exceptionState) const
+{
+ if (!element) {
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+ return 0;
+ }
+
+ if (RenderLayer* layer = getRenderLayerForElement(element, exceptionState)) {
+ if (layer->compositingState() == PaintsIntoOwnBacking) {
+ OwnPtr<Vector<FloatRect> > rects = layer->collectTrackedRepaintRects();
+ ASSERT(rects.get());
+ Vector<FloatQuad> quads(rects->size());
+ for (size_t i = 0; i < rects->size(); ++i)
+ quads[i] = FloatRect(rects->at(i));
+ return ClientRectList::create(quads);
+ }
+ }
+
+ // It's an error to call this on an element that's not composited.
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+ return 0;
+}
+
+String Internals::scrollingStateTreeAsText(Document* document, ExceptionState& exceptionState) const
{
return String();
}
-String Internals::mainThreadScrollingReasons(Document* document, ExceptionState& es) const
+String Internals::mainThreadScrollingReasons(Document* document, ExceptionState& exceptionState) const
{
if (!document || !document->frame()) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return String();
}
+ // Force a re-layout and a compositing update.
+ document->updateLayout();
+ RenderView* view = document->renderView();
+ if (view->compositor())
+ view->compositor()->updateCompositingLayers(CompositingUpdateFinishAllDeferredWork);
+
Page* page = document->page();
if (!page)
return String();
@@ -1860,10 +1888,10 @@ String Internals::mainThreadScrollingReasons(Document* document, ExceptionState&
return page->mainThreadScrollingReasonsAsText();
}
-PassRefPtr<ClientRectList> Internals::nonFastScrollableRects(Document* document, ExceptionState& es) const
+PassRefPtr<ClientRectList> Internals::nonFastScrollableRects(Document* document, ExceptionState& exceptionState) const
{
if (!document || !document->frame()) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return 0;
}
@@ -1874,18 +1902,12 @@ PassRefPtr<ClientRectList> Internals::nonFastScrollableRects(Document* document,
return page->nonFastScrollableRects(document->frame());
}
-void Internals::garbageCollectDocumentResources(Document* document, ExceptionState& es) const
+void Internals::garbageCollectDocumentResources(Document* document, ExceptionState& exceptionState) const
{
if (!document) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return;
}
-
- if (StyleResolver* resolver = contextDocument()->styleResolverIfExists())
- resolver->clearStyleSharingList();
- if (StyleResolver* resolver = document->styleResolverIfExists())
- resolver->clearStyleSharingList();
-
ResourceFetcher* fetcher = document->fetcher();
if (!fetcher)
return;
@@ -1902,28 +1924,6 @@ void Internals::allowRoundingHacks() const
TextRun::setAllowsRoundingHacks(true);
}
-void Internals::insertAuthorCSS(Document* document, const String& css) const
-{
- if (!document)
- return;
-
- RefPtr<StyleSheetContents> parsedSheet = StyleSheetContents::create(*document);
- parsedSheet->setIsUserStyleSheet(false);
- parsedSheet->parseString(css);
- document->styleEngine()->addAuthorSheet(parsedSheet);
-}
-
-void Internals::insertUserCSS(Document* document, const String& css) const
-{
- if (!document)
- return;
-
- RefPtr<StyleSheetContents> parsedSheet = StyleSheetContents::create(*document);
- parsedSheet->setIsUserStyleSheet(true);
- parsedSheet->parseString(css);
- document->styleEngine()->addUserSheet(parsedSheet);
-}
-
String Internals::counterValue(Element* element)
{
if (!element)
@@ -1970,41 +1970,41 @@ int Internals::numberOfPages(float pageWidth, float pageHeight)
return PrintContext::numberOfPages(frame(), FloatSize(pageWidth, pageHeight));
}
-String Internals::pageProperty(String propertyName, int pageNumber, ExceptionState& es) const
+String Internals::pageProperty(String propertyName, int pageNumber, ExceptionState& exceptionState) const
{
if (!frame()) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return String();
}
return PrintContext::pageProperty(frame(), propertyName.utf8().data(), pageNumber);
}
-String Internals::pageSizeAndMarginsInPixels(int pageNumber, int width, int height, int marginTop, int marginRight, int marginBottom, int marginLeft, ExceptionState& es) const
+String Internals::pageSizeAndMarginsInPixels(int pageNumber, int width, int height, int marginTop, int marginRight, int marginBottom, int marginLeft, ExceptionState& exceptionState) const
{
if (!frame()) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return String();
}
return PrintContext::pageSizeAndMarginsInPixels(frame(), pageNumber, width, height, marginTop, marginRight, marginBottom, marginLeft);
}
-void Internals::setDeviceScaleFactor(float scaleFactor, ExceptionState& es)
+void Internals::setDeviceScaleFactor(float scaleFactor, ExceptionState& exceptionState)
{
Document* document = contextDocument();
if (!document || !document->page()) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return;
}
Page* page = document->page();
page->setDeviceScaleFactor(scaleFactor);
}
-void Internals::setIsCursorVisible(Document* document, bool isVisible, ExceptionState& es)
+void Internals::setIsCursorVisible(Document* document, bool isVisible, ExceptionState& exceptionState)
{
if (!document || !document->page()) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return;
}
document->page()->setIsCursorVisible(isVisible);
@@ -2060,14 +2060,14 @@ PassRefPtr<TypeConversions> Internals::typeConversions() const
Vector<String> Internals::getReferencedFilePaths() const
{
- frame()->loader()->history()->saveDocumentAndScrollState();
- return FormController::getReferencedFilePaths(frame()->loader()->history()->currentItem()->documentState());
+ frame()->loader().saveDocumentAndScrollState();
+ return FormController::getReferencedFilePaths(frame()->loader().currentItem()->documentState());
}
-void Internals::startTrackingRepaints(Document* document, ExceptionState& es)
+void Internals::startTrackingRepaints(Document* document, ExceptionState& exceptionState)
{
if (!document || !document->view()) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return;
}
@@ -2075,10 +2075,10 @@ void Internals::startTrackingRepaints(Document* document, ExceptionState& es)
frameView->setTracksRepaints(true);
}
-void Internals::stopTrackingRepaints(Document* document, ExceptionState& es)
+void Internals::stopTrackingRepaints(Document* document, ExceptionState& exceptionState)
{
if (!document || !document->view()) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return;
}
@@ -2086,6 +2086,56 @@ void Internals::stopTrackingRepaints(Document* document, ExceptionState& es)
frameView->setTracksRepaints(false);
}
+void Internals::updateLayoutIgnorePendingStylesheetsAndRunPostLayoutTasks(ExceptionState& exceptionState)
+{
+ updateLayoutIgnorePendingStylesheetsAndRunPostLayoutTasks(0, exceptionState);
+}
+
+void Internals::updateLayoutIgnorePendingStylesheetsAndRunPostLayoutTasks(Node* node, ExceptionState& exceptionState)
+{
+ Document* document;
+ if (!node) {
+ document = contextDocument();
+ } else if (node->isDocumentNode()) {
+ document = toDocument(node);
+ } else if (node->hasTagName(HTMLNames::iframeTag)) {
+ document = toHTMLIFrameElement(node)->contentDocument();
+ } else {
+ exceptionState.throwUninformativeAndGenericDOMException(TypeError);
+ return;
+ }
+ document->updateLayoutIgnorePendingStylesheets(Document::RunPostLayoutTasksSynchronously);
+}
+
+PassRefPtr<ClientRectList> Internals::draggableRegions(Document* document, ExceptionState& exceptionState)
+{
+ return annotatedRegions(document, true, exceptionState);
+}
+
+PassRefPtr<ClientRectList> Internals::nonDraggableRegions(Document* document, ExceptionState& exceptionState)
+{
+ return annotatedRegions(document, false, exceptionState);
+}
+
+PassRefPtr<ClientRectList> Internals::annotatedRegions(Document* document, bool draggable, ExceptionState& exceptionState)
+{
+ if (!document || !document->view()) {
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+ return ClientRectList::create();
+ }
+
+ document->updateLayout();
+ document->view()->updateAnnotatedRegions();
+ Vector<AnnotatedRegionValue> regions = document->annotatedRegions();
+
+ Vector<FloatQuad> quads;
+ for (size_t i = 0; i < regions.size(); ++i) {
+ if (regions[i].draggable == draggable)
+ quads.append(FloatQuad(regions[i].bounds));
+ }
+ return ClientRectList::create(quads);
+}
+
static const char* cursorTypeToString(Cursor::Type cursorType)
{
switch (cursorType) {
@@ -2139,14 +2189,14 @@ static const char* cursorTypeToString(Cursor::Type cursorType)
return "UNKNOWN";
}
-String Internals::getCurrentCursorInfo(Document* document, ExceptionState& es)
+String Internals::getCurrentCursorInfo(Document* document, ExceptionState& exceptionState)
{
if (!document || !document->frame()) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return String();
}
- Cursor cursor = document->frame()->eventHandler()->currentMouseCursor();
+ Cursor cursor = document->frame()->eventHandler().currentMouseCursor();
StringBuilder result;
result.append("type=");
@@ -2187,42 +2237,42 @@ PassRefPtr<SerializedScriptValue> Internals::deserializeBuffer(PassRefPtr<ArrayB
void Internals::forceReload(bool endToEnd)
{
- frame()->loader()->reload(endToEnd ? EndToEndReload : NormalReload);
+ frame()->loader().reload(endToEnd ? EndToEndReload : NormalReload);
}
-PassRefPtr<ClientRect> Internals::selectionBounds(ExceptionState& es)
+PassRefPtr<ClientRect> Internals::selectionBounds(ExceptionState& exceptionState)
{
Document* document = contextDocument();
if (!document || !document->frame()) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return 0;
}
return ClientRect::create(document->frame()->selection().bounds());
}
-String Internals::markerTextForListItem(Element* element, ExceptionState& es)
+String Internals::markerTextForListItem(Element* element, ExceptionState& exceptionState)
{
if (!element) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return String();
}
return WebCore::markerTextForListItem(element);
}
-String Internals::getImageSourceURL(Element* element, ExceptionState& es)
+String Internals::getImageSourceURL(Element* element, ExceptionState& exceptionState)
{
if (!element) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return String();
}
return element->imageSourceURL();
}
-String Internals::baseURL(Document* document, ExceptionState& es)
+String Internals::baseURL(Document* document, ExceptionState& exceptionState)
{
if (!document) {
- es.throwDOMException(InvalidAccessError);
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
return String();
}
@@ -2257,4 +2307,33 @@ bool Internals::loseSharedGraphicsContext3D()
return true;
}
+void Internals::forceCompositingUpdate(Document* document, ExceptionState& exceptionState)
+{
+ if (!document || !document->renderView()) {
+ exceptionState.throwUninformativeAndGenericDOMException(InvalidAccessError);
+ return;
+ }
+
+ document->updateLayout();
+
+ RenderView* view = document->renderView();
+ if (view->compositor())
+ view->compositor()->updateCompositingLayers(CompositingUpdateFinishAllDeferredWork);
+}
+
+bool Internals::isCompositorFramePending(Document* document, ExceptionState& exceptionState)
+{
+ if (!document || !document->renderView()) {
+ exceptionState.throwDOMException(InvalidAccessError, document ? "The document's render view cannot be retrieved." : "The document provided is invalid.");
+ return false;
+ }
+
+ return document->page()->chrome().client().isCompositorFramePending();
+}
+
+void Internals::setZoomFactor(float factor)
+{
+ frame()->setPageZoomFactor(factor);
+}
+
}
diff --git a/chromium/third_party/WebKit/Source/core/testing/Internals.h b/chromium/third_party/WebKit/Source/core/testing/Internals.h
index 18350ecd52d..32c969a3d74 100644
--- a/chromium/third_party/WebKit/Source/core/testing/Internals.h
+++ b/chromium/third_party/WebKit/Source/core/testing/Internals.h
@@ -61,7 +61,7 @@ class Node;
class Page;
class PagePopupController;
class Range;
-class ScriptExecutionContext;
+class ExecutionContext;
class SerializedScriptValue;
class ShadowRoot;
class TypeConversions;
@@ -85,6 +85,10 @@ public:
void crash();
+ void setStyleResolverStatsEnabled(bool);
+ String styleResolverStatsReport(ExceptionState&) const;
+ String styleResolverStatsTotalsReport(ExceptionState&) const;
+
size_t numberOfScopedHTMLStyleChildren(const Node*, ExceptionState&) const;
PassRefPtr<CSSComputedStyleDeclaration> computedStyleIncludingVisitedInfo(Node*, ExceptionState&) const;
@@ -98,14 +102,11 @@ public:
bool hasShadowInsertionPoint(const Node*, ExceptionState&) const;
bool hasContentElement(const Node*, ExceptionState&) const;
size_t countElementShadow(const Node*, ExceptionState&) const;
- Element* includerFor(Node*, ExceptionState&);
String shadowPseudoId(Element*, ExceptionState&);
void setShadowPseudoId(Element*, const String&, ExceptionState&);
// CSS Animation / Transition testing.
unsigned numberOfActiveAnimations() const;
- void suspendAnimations(Document*, ExceptionState&) const;
- void resumeAnimations(Document*, ExceptionState&) const;
void pauseAnimations(double pauseTime, ExceptionState&);
PassRefPtr<Element> createContentElement(ExceptionState&);
@@ -118,8 +119,6 @@ public:
bool hasSelectorForPseudoClassInShadow(Element* host, const String& pseudoClass, ExceptionState&);
unsigned short compareTreeScopePosition(const Node*, const Node*, ExceptionState&) const;
- bool attached(Node*, ExceptionState&);
-
// FIXME: Rename these functions if walker is prefered.
Node* nextSiblingByWalker(Node*, ExceptionState&);
Node* firstChildByWalker(Node*, ExceptionState&);
@@ -127,10 +126,12 @@ public:
Node* nextNodeByWalker(Node*, ExceptionState&);
Node* previousNodeByWalker(Node*, ExceptionState&);
+ unsigned updateStyleAndReturnAffectedElementCount(ExceptionState&) const;
+
String visiblePlaceholder(Element*);
void selectColorInColorChooser(Element*, const String& colorValue);
- Vector<String> formControlStateOfPreviousHistoryItem(ExceptionState&);
- void setFormControlStateOfPreviousHistoryItem(const Vector<String>&, ExceptionState&);
+ Vector<String> formControlStateOfHistoryItem(ExceptionState&);
+ void setFormControlStateOfHistoryItem(const Vector<String>&, ExceptionState&);
void setEnableMockPagePopup(bool, ExceptionState&);
PassRefPtr<PagePopupController> pagePopupController();
@@ -189,7 +190,7 @@ public:
PassRefPtr<NodeList> nodesFromRect(Document*, int x, int y, unsigned topPadding, unsigned rightPadding,
unsigned bottomPadding, unsigned leftPadding, bool ignoreClipping, bool allowShadowContent, bool allowChildFrameContent, ExceptionState&) const;
- void emitInspectorDidBeginFrame();
+ void emitInspectorDidBeginFrame(int frameId = 0);
void emitInspectorDidCancelFrame();
bool hasSpellingMarker(Document*, int from, int length, ExceptionState&);
@@ -222,10 +223,13 @@ public:
bool scrollsWithRespectTo(Element*, Element*, ExceptionState&);
bool isUnclippedDescendant(Element*, ExceptionState&);
+ bool needsCompositedScrolling(Element*, ExceptionState&);
void setNeedsCompositedScrolling(Element*, unsigned value, ExceptionState&);
String repaintRectsAsText(Document*, ExceptionState&) const;
+ PassRefPtr<ClientRectList> repaintRects(Element*, ExceptionState&) const;
+
String scrollingStateTreeAsText(Document*, ExceptionState&) const;
String mainThreadScrollingReasons(Document*, ExceptionState&) const;
PassRefPtr<ClientRectList> nonFastScrollableRects(Document*, ExceptionState&) const;
@@ -235,11 +239,9 @@ public:
void allowRoundingHacks() const;
- void insertAuthorCSS(Document*, const String&) const;
- void insertUserCSS(Document*, const String&) const;
-
unsigned numberOfLiveNodes() const;
unsigned numberOfLiveDocuments() const;
+ String dumpRefCountedInstanceCounts() const;
Vector<String> consoleMessageArgumentCounts(Document*) const;
PassRefPtr<DOMWindow> openDummyInspectorFrontend(const String& url);
void closeDummyInspectorFrontend();
@@ -275,6 +277,11 @@ public:
void startTrackingRepaints(Document*, ExceptionState&);
void stopTrackingRepaints(Document*, ExceptionState&);
+ void updateLayoutIgnorePendingStylesheetsAndRunPostLayoutTasks(ExceptionState&);
+ void updateLayoutIgnorePendingStylesheetsAndRunPostLayoutTasks(Node*, ExceptionState&);
+
+ PassRefPtr<ClientRectList> draggableRegions(Document*, ExceptionState&);
+ PassRefPtr<ClientRectList> nonDraggableRegions(Document*, ExceptionState&);
PassRefPtr<ArrayBuffer> serializeObject(PassRefPtr<SerializedScriptValue>) const;
PassRefPtr<SerializedScriptValue> deserializeBuffer(PassRefPtr<ArrayBuffer>) const;
@@ -285,8 +292,6 @@ public:
void forceReload(bool endToEnd);
- void enableMockSpeechSynthesizer();
-
String getImageSourceURL(Element*, ExceptionState&);
bool isSelectPopupVisible(Node*);
@@ -296,11 +301,18 @@ public:
bool loseSharedGraphicsContext3D();
+ void forceCompositingUpdate(Document*, ExceptionState&);
+
+ bool isCompositorFramePending(Document*, ExceptionState&);
+
+ void setZoomFactor(float);
+
private:
explicit Internals(Document*);
Document* contextDocument() const;
Frame* frame() const;
Vector<String> iconURLs(Document*, int iconTypesMask) const;
+ PassRefPtr<ClientRectList> annotatedRegions(Document*, bool draggable, ExceptionState&);
DocumentMarker* markerAt(Node*, const String& markerType, unsigned index, ExceptionState&);
RefPtr<DOMWindow> m_frontendWindow;
diff --git a/chromium/third_party/WebKit/Source/core/testing/Internals.idl b/chromium/third_party/WebKit/Source/core/testing/Internals.idl
index 0d21489b177..be6087df535 100644
--- a/chromium/third_party/WebKit/Source/core/testing/Internals.idl
+++ b/chromium/third_party/WebKit/Source/core/testing/Internals.idl
@@ -37,6 +37,10 @@
void crash();
+ void setStyleResolverStatsEnabled(boolean enabled);
+ [RaisesException] DOMString styleResolverStatsReport();
+ [RaisesException] DOMString styleResolverStatsTotalsReport();
+
[RaisesException] unsigned long numberOfScopedHTMLStyleChildren(Node scope);
[RaisesException] CSSStyleDeclaration computedStyleIncludingVisitedInfo(Node node);
@@ -51,7 +55,6 @@
[RaisesException] boolean hasShadowInsertionPoint(Node root);
[RaisesException] boolean hasContentElement(Node root);
[RaisesException] unsigned long countElementShadow(Node Root);
- [RaisesException] Element includerFor(Node node);
[RaisesException] DOMString shadowPseudoId(Element element);
[RaisesException] void setShadowPseudoId(Element element, DOMString id);
[RaisesException] Element createContentElement();
@@ -63,11 +66,10 @@
[RaisesException] boolean hasSelectorForAttributeInShadow(Element host, DOMString attributeName);
[RaisesException] boolean hasSelectorForPseudoClassInShadow(Element host, DOMString pseudoClass);
[RaisesException] unsigned short compareTreeScopePosition(Node treeScope1, Node treeScope2);
+ [RaisesException] unsigned long updateStyleAndReturnAffectedElementCount();
// CSS Animation and Transition testing.
unsigned long numberOfActiveAnimations();
- [RaisesException] void suspendAnimations(Document document);
- [RaisesException] void resumeAnimations(Document document);
[RaisesException] void pauseAnimations(double pauseTime);
[RaisesException] Node nextSiblingByWalker(Node node);
@@ -76,14 +78,12 @@
[RaisesException] Node nextNodeByWalker(Node node);
[RaisesException] Node previousNodeByWalker(Node node);
- [RaisesException] boolean attached(Node node);
-
DOMString visiblePlaceholder(Element element);
void selectColorInColorChooser(Element element, DOMString colorValue);
- [RaisesException] DOMString[] formControlStateOfPreviousHistoryItem();
- [RaisesException] void setFormControlStateOfPreviousHistoryItem(sequence<DOMString> values);
+ [RaisesException] DOMString[] formControlStateOfHistoryItem();
+ [RaisesException] void setFormControlStateOfHistoryItem(sequence<DOMString> values);
[RaisesException] void setEnableMockPagePopup(boolean enabled);
readonly attribute PagePopupController pagePopupController;
@@ -148,7 +148,7 @@
unsigned long topPadding, unsigned long rightPadding, unsigned long bottomPadding, unsigned long leftPadding,
boolean ignoreClipping, boolean allowShadowContent, boolean allowChildFrameContent);
- void emitInspectorDidBeginFrame();
+ void emitInspectorDidBeginFrame(optional long frameId);
void emitInspectorDidCancelFrame();
[RaisesException] boolean hasSpellingMarker(Document document, long from, long length);
@@ -172,6 +172,7 @@
const unsigned short LAYER_TREE_INCLUDES_REPAINT_RECTS = 2;
const unsigned short LAYER_TREE_INCLUDES_PAINTING_PHASES = 4;
const unsigned short LAYER_TREE_INCLUDES_ROOT_LAYER = 8;
+ const unsigned short LAYER_TREE_INCLUDES_CLIP_AND_SCROLL_PARENTS = 16;
[RaisesException] DOMString layerTreeAsText(Document document, optional unsigned short flags);
[RaisesException] DOMString elementLayerTreeAsText(Element element, optional unsigned short flags);
@@ -180,6 +181,7 @@
[RaisesException] boolean scrollsWithRespectTo(Element element1, Element element2);
[RaisesException] boolean isUnclippedDescendant(Element element);
+ [RaisesException] boolean needsCompositedScrolling(Element element);
// The values of these constants must be kept in sync with those in RenderLayer.
const unsigned short DO_NOT_FORCE_COMPOSITED_SCROLLING = 0;
@@ -192,17 +194,16 @@
[RaisesException] ClientRectList nonFastScrollableRects(Document document);
[RaisesException] DOMString repaintRectsAsText(Document document);
+ [RaisesException] ClientRectList repaintRects(Element element);
[RaisesException] void garbageCollectDocumentResources(Document document);
void evictAllResources();
void allowRoundingHacks();
- void insertAuthorCSS(Document document, DOMString css);
- void insertUserCSS(Document document, DOMString css);
-
unsigned long numberOfLiveNodes();
unsigned long numberOfLiveDocuments();
+ DOMString dumpRefCountedInstanceCounts();
sequence<DOMString> consoleMessageArgumentCounts(Document document);
Window openDummyInspectorFrontend(DOMString url);
void closeDummyInspectorFrontend();
@@ -239,6 +240,15 @@
[RaisesException] void startTrackingRepaints(Document document);
[RaisesException] void stopTrackingRepaints(Document document);
+ // |node| should be Document, HTMLIFrameElement, or unspecified.
+ // If |node| is an HTMLIFrameElement, it assumes node.contentDocument is
+ // specified without security checks. Unspecified means this document.
+ [RaisesException] void updateLayoutIgnorePendingStylesheetsAndRunPostLayoutTasks(optional Node node);
+
+ // Returns a list of draggable/non-draggable regions in the document.
+ [RaisesException] ClientRectList draggableRegions(Document document);
+ [RaisesException] ClientRectList nonDraggableRegions(Document document);
+
// Returns a string with information about the mouse cursor used at the specified client location.
[RaisesException] DOMString getCurrentCursorInfo(Document document);
@@ -251,8 +261,6 @@
void forceReload(boolean endToEnd);
- void enableMockSpeechSynthesizer();
-
[RaisesException] DOMString getImageSourceURL(Element element);
boolean isSelectPopupVisible(Node node);
@@ -260,4 +268,9 @@
[RaisesException] ClientRect selectionBounds();
boolean loseSharedGraphicsContext3D();
+
+ [RaisesException] void forceCompositingUpdate(Document document);
+ [RaisesException] boolean isCompositorFramePending(Document document);
+
+ void setZoomFactor(float factor);
};
diff --git a/chromium/third_party/WebKit/Source/core/testing/MockPagePopupDriver.cpp b/chromium/third_party/WebKit/Source/core/testing/MockPagePopupDriver.cpp
index 5ca92ce099a..56cc2482698 100644
--- a/chromium/third_party/WebKit/Source/core/testing/MockPagePopupDriver.cpp
+++ b/chromium/third_party/WebKit/Source/core/testing/MockPagePopupDriver.cpp
@@ -33,11 +33,10 @@
#include "core/loader/DocumentLoader.h"
#include "core/loader/DocumentWriter.h"
#include "core/loader/FrameLoader.h"
-#include "core/page/Frame.h"
+#include "core/frame/Frame.h"
#include "core/page/PagePopup.h"
-#include "core/page/PagePopupClient.h"
#include "core/page/PagePopupController.h"
-#include "core/platform/Timer.h"
+#include "platform/Timer.h"
namespace WebCore {
@@ -62,7 +61,7 @@ inline MockPagePopup::MockPagePopup(PagePopupClient* client, const IntRect& orig
{
Document* document = mainFrame->document();
ASSERT(document);
- m_iframe = HTMLIFrameElement::create(HTMLNames::iframeTag, *document);
+ m_iframe = HTMLIFrameElement::create(*document);
m_iframe->setIdAttribute("mock-page-popup");
m_iframe->setInlineStyleProperty(CSSPropertyBorderWidth, 0.0, CSSPrimitiveValue::CSS_PX);
m_iframe->setInlineStyleProperty(CSSPropertyPosition, CSSValueAbsolute);
@@ -71,11 +70,11 @@ inline MockPagePopup::MockPagePopup(PagePopupClient* client, const IntRect& orig
if (document->body())
document->body()->appendChild(m_iframe.get());
Frame* contentFrame = m_iframe->contentFrame();
- DocumentWriter* writer = contentFrame->loader()->activeDocumentLoader()->beginWriting("text/html", "UTF-8");
+ DocumentWriter* writer = contentFrame->loader().activeDocumentLoader()->beginWriting("text/html", "UTF-8");
const char scriptToSetUpPagePopupController[] = "<script>window.pagePopupController = parent.internals.pagePopupController;</script>";
writer->addData(scriptToSetUpPagePopupController, sizeof(scriptToSetUpPagePopupController));
m_popupClient->writeDocument(*writer);
- contentFrame->loader()->activeDocumentLoader()->endWriting(writer);
+ contentFrame->loader().activeDocumentLoader()->endWriting(writer);
}
PassRefPtr<MockPagePopup> MockPagePopup::create(PagePopupClient* client, const IntRect& originBoundsInRootView, Frame* mainFrame)
diff --git a/chromium/third_party/WebKit/Source/core/testing/TypeConversions.h b/chromium/third_party/WebKit/Source/core/testing/TypeConversions.h
index 10f675f42f4..9a2625d0643 100644
--- a/chromium/third_party/WebKit/Source/core/testing/TypeConversions.h
+++ b/chromium/third_party/WebKit/Source/core/testing/TypeConversions.h
@@ -38,31 +38,23 @@ public:
long testLong() { return m_long; }
void setTestLong(long value) { m_long = value; }
- long testEnforceRangeLong() { return m_long; }
- void setTestEnforceRangeLong(long value) { m_long = value; }
unsigned long testUnsignedLong() { return m_unsignedLong; }
void setTestUnsignedLong(unsigned long value) { m_unsignedLong = value; }
- unsigned long testEnforceRangeUnsignedLong() { return m_unsignedLong; }
- void setTestEnforceRangeUnsignedLong(unsigned long value) { m_unsignedLong = value; }
long long testLongLong() { return m_longLong; }
void setTestLongLong(long long value) { m_longLong = value; }
- long long testEnforceRangeLongLong() { return m_longLong; }
- void setTestEnforceRangeLongLong(long long value) { m_longLong = value; }
unsigned long long testUnsignedLongLong() { return m_unsignedLongLong; }
void setTestUnsignedLongLong(unsigned long long value) { m_unsignedLongLong = value; }
- unsigned long long testEnforceRangeUnsignedLongLong() { return m_unsignedLongLong; }
- void setTestEnforceRangeUnsignedLongLong(unsigned long long value) { m_unsignedLongLong = value; }
int8_t testByte() { return m_byte; }
void setTestByte(int8_t value) { m_byte = value; }
- int8_t testEnforceRangeByte() { return m_byte; }
- void setTestEnforceRangeByte(int8_t value) { m_byte = value; }
-
uint8_t testOctet() { return m_octet; }
void setTestOctet(uint8_t value) { m_octet = value; }
- uint8_t testEnforceRangeOctet() { return m_octet; }
- void setTestEnforceRangeOctet(uint8_t value) { m_octet = value; }
+
+ int16_t testShort() { return m_short; }
+ void setTestShort(int16_t value) { m_short = value; }
+ uint16_t testUnsignedShort() { return m_unsignedShort; }
+ void setTestUnsignedShort(uint16_t value) { m_unsignedShort = value; }
private:
TypeConversions()
@@ -75,6 +67,8 @@ private:
unsigned long long m_unsignedLongLong;
int8_t m_byte;
uint8_t m_octet;
+ int16_t m_short;
+ uint16_t m_unsignedShort;
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/testing/TypeConversions.idl b/chromium/third_party/WebKit/Source/core/testing/TypeConversions.idl
index 1f3df0c12fb..7a70cc5d3fd 100644
--- a/chromium/third_party/WebKit/Source/core/testing/TypeConversions.idl
+++ b/chromium/third_party/WebKit/Source/core/testing/TypeConversions.idl
@@ -26,17 +26,22 @@
[
] interface TypeConversions {
attribute long testLong;
- [EnforceRange] attribute long testEnforceRangeLong;
+ [EnforceRange, ImplementedAs=testLong] attribute long testEnforceRangeLong;
attribute unsigned long testUnsignedLong;
- [EnforceRange] attribute unsigned long testEnforceRangeUnsignedLong;
+ [EnforceRange, ImplementedAs=testUnsignedLong] attribute unsigned long testEnforceRangeUnsignedLong;
attribute long long testLongLong;
- [EnforceRange] attribute long long testEnforceRangeLongLong;
+ [EnforceRange, ImplementedAs=testLongLong] attribute long long testEnforceRangeLongLong;
attribute unsigned long long testUnsignedLongLong;
- [EnforceRange] attribute unsigned long long testEnforceRangeUnsignedLongLong;
+ [EnforceRange, ImplementedAs=testUnsignedLongLong] attribute unsigned long long testEnforceRangeUnsignedLongLong;
attribute byte testByte;
- [EnforceRange] attribute byte testEnforceRangeByte;
+ [EnforceRange, ImplementedAs=testByte] attribute byte testEnforceRangeByte;
attribute octet testOctet;
- [EnforceRange] attribute octet testEnforceRangeOctet;
+ [EnforceRange, ImplementedAs=testOctet] attribute octet testEnforceRangeOctet;
+
+ attribute short testShort;
+ [EnforceRange, ImplementedAs=testShort] attribute short testEnforceRangeShort;
+ attribute unsigned short testUnsignedShort;
+ [EnforceRange, ImplementedAs=testUnsignedShort] attribute unsigned short testEnforceRangeUnsignedShort;
};
diff --git a/chromium/third_party/WebKit/Source/core/testing/UnitTestHelpers.cpp b/chromium/third_party/WebKit/Source/core/testing/UnitTestHelpers.cpp
new file mode 100644
index 00000000000..8c5bc5bbe45
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/testing/UnitTestHelpers.cpp
@@ -0,0 +1,51 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/testing/UnitTestHelpers.h"
+
+#include "public/platform/Platform.h"
+#include "public/platform/WebThread.h"
+
+
+namespace WebCore {
+namespace testing {
+
+class QuitTask : public blink::WebThread::Task {
+public:
+ virtual void run()
+ {
+ blink::Platform::current()->currentThread()->exitRunLoop();
+ }
+};
+
+void runPendingTasks()
+{
+ blink::Platform::current()->currentThread()->postTask(new QuitTask);
+ blink::Platform::current()->currentThread()->enterRunLoop();
+}
+
+}
+}
diff --git a/chromium/third_party/WebKit/Source/core/testing/UnitTestHelpers.h b/chromium/third_party/WebKit/Source/core/testing/UnitTestHelpers.h
new file mode 100644
index 00000000000..cb8fe5880b3
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/testing/UnitTestHelpers.h
@@ -0,0 +1,37 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef UnitTestHelpers_h
+#define UnitTestHelpers_h
+
+namespace WebCore {
+namespace testing {
+
+void runPendingTasks();
+
+} // namespace testing
+} // namespace WebCore
+
+#endif
diff --git a/chromium/third_party/WebKit/Source/core/testing/v8/WebCoreTestSupport.cpp b/chromium/third_party/WebKit/Source/core/testing/v8/WebCoreTestSupport.cpp
index e18e3694d45..f28fecbb2a4 100644
--- a/chromium/third_party/WebKit/Source/core/testing/v8/WebCoreTestSupport.cpp
+++ b/chromium/third_party/WebKit/Source/core/testing/v8/WebCoreTestSupport.cpp
@@ -30,8 +30,8 @@
#include "Internals.h"
#include "V8Internals.h"
#include "core/dom/Document.h"
-#include "core/dom/ScriptExecutionContext.h"
-#include "core/page/Frame.h"
+#include "core/dom/ExecutionContext.h"
+#include "core/frame/Frame.h"
#include <v8.h>
@@ -43,9 +43,9 @@ void injectInternalsObject(v8::Local<v8::Context> context)
{
v8::Context::Scope contextScope(context);
v8::HandleScope scope(context->GetIsolate());
- ScriptExecutionContext* scriptContext = getScriptExecutionContext();
+ ExecutionContext* scriptContext = getExecutionContext();
if (scriptContext->isDocument())
- context->Global()->Set(v8::String::New(Internals::internalsId), toV8(Internals::create(toDocument(scriptContext)), v8::Handle<v8::Object>(), context->GetIsolate()));
+ context->Global()->Set(v8::String::NewFromUtf8(context->GetIsolate(), Internals::internalsId), toV8(Internals::create(toDocument(scriptContext)), v8::Handle<v8::Object>(), context->GetIsolate()));
}
void resetInternalsObject(v8::Local<v8::Context> context)
@@ -57,7 +57,7 @@ void resetInternalsObject(v8::Local<v8::Context> context)
v8::Context::Scope contextScope(context);
v8::HandleScope scope(context->GetIsolate());
- ScriptExecutionContext* scriptContext = getScriptExecutionContext();
+ ExecutionContext* scriptContext = getExecutionContext();
Page* page = toDocument(scriptContext)->frame()->page();
Internals::resetToConsistentState(page);
InternalSettings::from(page)->resetToConsistentState();
diff --git a/chromium/third_party/WebKit/Source/core/timing/MemoryInfo.cpp b/chromium/third_party/WebKit/Source/core/timing/MemoryInfo.cpp
new file mode 100644
index 00000000000..3bb082123a1
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/timing/MemoryInfo.cpp
@@ -0,0 +1,149 @@
+/*
+ * Copyright (C) 2010 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/timing/MemoryInfo.h"
+
+#include <limits>
+#include "core/frame/Frame.h"
+#include "core/frame/Settings.h"
+#include "wtf/CurrentTime.h"
+#include "wtf/MainThread.h"
+#include "wtf/MathExtras.h"
+
+namespace WebCore {
+
+
+class HeapSizeCache {
+ WTF_MAKE_NONCOPYABLE(HeapSizeCache); WTF_MAKE_FAST_ALLOCATED;
+public:
+ HeapSizeCache()
+ : m_lastUpdateTime(0)
+ {
+ }
+
+ void getCachedHeapSize(HeapInfo& info)
+ {
+ maybeUpdate();
+ info = m_info;
+ }
+
+private:
+ void maybeUpdate()
+ {
+ // We rate-limit queries to once every twenty minutes to make it more difficult
+ // for attackers to compare memory usage before and after some event.
+ const double TwentyMinutesInSeconds = 20 * 60;
+
+ double now = monotonicallyIncreasingTime();
+ if (now - m_lastUpdateTime >= TwentyMinutesInSeconds) {
+ update();
+ m_lastUpdateTime = now;
+ }
+ }
+
+ void update()
+ {
+ ScriptGCEvent::getHeapSize(m_info);
+ m_info.usedJSHeapSize = quantizeMemorySize(m_info.usedJSHeapSize);
+ m_info.totalJSHeapSize = quantizeMemorySize(m_info.totalJSHeapSize);
+ m_info.jsHeapSizeLimit = quantizeMemorySize(m_info.jsHeapSizeLimit);
+ }
+
+ double m_lastUpdateTime;
+
+ HeapInfo m_info;
+};
+
+// We quantize the sizes to make it more difficult for an attacker to see precise
+// impact of operations on memory. The values are used for performance tuning,
+// and hence don't need to be as refined when the value is large, so we threshold
+// at a list of exponentially separated buckets.
+size_t quantizeMemorySize(size_t size)
+{
+ const int numberOfBuckets = 100;
+ DEFINE_STATIC_LOCAL(Vector<size_t>, bucketSizeList, ());
+
+ ASSERT(isMainThread());
+ if (bucketSizeList.isEmpty()) {
+ bucketSizeList.resize(numberOfBuckets);
+
+ float sizeOfNextBucket = 10000000.0; // First bucket size is roughly 10M.
+ const float largestBucketSize = 4000000000.0; // Roughly 4GB.
+ // We scale with the Nth root of the ratio, so that we use all the bucktes.
+ const float scalingFactor = exp(log(largestBucketSize / sizeOfNextBucket) / numberOfBuckets);
+
+ size_t nextPowerOfTen = static_cast<size_t>(pow(10, floor(log10(sizeOfNextBucket)) + 1) + 0.5);
+ size_t granularity = nextPowerOfTen / 1000; // We want 3 signficant digits.
+
+ for (int i = 0; i < numberOfBuckets; ++i) {
+ size_t currentBucketSize = static_cast<size_t>(sizeOfNextBucket);
+ bucketSizeList[i] = currentBucketSize - (currentBucketSize % granularity);
+
+ sizeOfNextBucket *= scalingFactor;
+ if (sizeOfNextBucket >= nextPowerOfTen) {
+ if (std::numeric_limits<size_t>::max() / 10 <= nextPowerOfTen) {
+ nextPowerOfTen = std::numeric_limits<size_t>::max();
+ } else {
+ nextPowerOfTen *= 10;
+ granularity *= 10;
+ }
+ }
+
+ // Watch out for overflow, if the range is too large for size_t.
+ if (i > 0 && bucketSizeList[i] < bucketSizeList[i - 1])
+ bucketSizeList[i] = std::numeric_limits<size_t>::max();
+ }
+ }
+
+ for (int i = 0; i < numberOfBuckets; ++i) {
+ if (size <= bucketSizeList[i])
+ return bucketSizeList[i];
+ }
+
+ return bucketSizeList[numberOfBuckets - 1];
+}
+
+
+MemoryInfo::MemoryInfo(Frame* frame)
+{
+ ScriptWrappable::init(this);
+ if (!frame || !frame->settings())
+ return;
+
+ if (frame->settings()->memoryInfoEnabled()) {
+ ScriptGCEvent::getHeapSize(m_info);
+ } else {
+ DEFINE_STATIC_LOCAL(HeapSizeCache, heapSizeCache, ());
+ heapSizeCache.getCachedHeapSize(m_info);
+ }
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/page/MemoryInfo.h b/chromium/third_party/WebKit/Source/core/timing/MemoryInfo.h
index 59629a44dc8..59629a44dc8 100644
--- a/chromium/third_party/WebKit/Source/core/page/MemoryInfo.h
+++ b/chromium/third_party/WebKit/Source/core/timing/MemoryInfo.h
diff --git a/chromium/third_party/WebKit/Source/core/page/MemoryInfo.idl b/chromium/third_party/WebKit/Source/core/timing/MemoryInfo.idl
index 30ac718a67a..30ac718a67a 100644
--- a/chromium/third_party/WebKit/Source/core/page/MemoryInfo.idl
+++ b/chromium/third_party/WebKit/Source/core/timing/MemoryInfo.idl
diff --git a/chromium/third_party/WebKit/Source/core/timing/Performance.cpp b/chromium/third_party/WebKit/Source/core/timing/Performance.cpp
new file mode 100644
index 00000000000..e441579b930
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/timing/Performance.cpp
@@ -0,0 +1,280 @@
+/*
+ * Copyright (C) 2010 Google Inc. All rights reserved.
+ * Copyright (C) 2012 Intel Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/timing/Performance.h"
+
+#include "core/dom/Document.h"
+#include "core/loader/DocumentLoader.h"
+#include "core/timing/ResourceTimingInfo.h"
+#include "core/timing/PerformanceResourceTiming.h"
+#include "core/timing/PerformanceUserTiming.h"
+#include "platform/weborigin/SecurityOrigin.h"
+#include "wtf/CurrentTime.h"
+
+#include "core/frame/Frame.h"
+
+namespace WebCore {
+
+static const size_t defaultResourceTimingBufferSize = 150;
+
+Performance::Performance(Frame* frame)
+ : DOMWindowProperty(frame)
+ , m_resourceTimingBufferSize(defaultResourceTimingBufferSize)
+ , m_referenceTime(frame->document()->loader()->timing()->referenceMonotonicTime())
+ , m_userTiming(0)
+{
+ ASSERT(m_referenceTime);
+ ScriptWrappable::init(this);
+}
+
+Performance::~Performance()
+{
+}
+
+const AtomicString& Performance::interfaceName() const
+{
+ return EventTargetNames::Performance;
+}
+
+ExecutionContext* Performance::executionContext() const
+{
+ if (!frame())
+ return 0;
+ return frame()->document();
+}
+
+PassRefPtr<MemoryInfo> Performance::memory() const
+{
+ return MemoryInfo::create(m_frame);
+}
+
+PerformanceNavigation* Performance::navigation() const
+{
+ if (!m_navigation)
+ m_navigation = PerformanceNavigation::create(m_frame);
+
+ return m_navigation.get();
+}
+
+PerformanceTiming* Performance::timing() const
+{
+ if (!m_timing)
+ m_timing = PerformanceTiming::create(m_frame);
+
+ return m_timing.get();
+}
+
+Vector<RefPtr<PerformanceEntry> > Performance::getEntries() const
+{
+ Vector<RefPtr<PerformanceEntry> > entries;
+
+ entries.append(m_resourceTimingBuffer);
+
+ if (m_userTiming) {
+ entries.append(m_userTiming->getMarks());
+ entries.append(m_userTiming->getMeasures());
+ }
+
+ std::sort(entries.begin(), entries.end(), PerformanceEntry::startTimeCompareLessThan);
+ return entries;
+}
+
+Vector<RefPtr<PerformanceEntry> > Performance::getEntriesByType(const String& entryType)
+{
+ Vector<RefPtr<PerformanceEntry> > entries;
+
+ if (equalIgnoringCase(entryType, "resource"))
+ for (Vector<RefPtr<PerformanceEntry> >::const_iterator resource = m_resourceTimingBuffer.begin(); resource != m_resourceTimingBuffer.end(); ++resource)
+ entries.append(*resource);
+
+ if (m_userTiming) {
+ if (equalIgnoringCase(entryType, "mark"))
+ entries.append(m_userTiming->getMarks());
+ else if (equalIgnoringCase(entryType, "measure"))
+ entries.append(m_userTiming->getMeasures());
+ }
+
+ std::sort(entries.begin(), entries.end(), PerformanceEntry::startTimeCompareLessThan);
+ return entries;
+}
+
+Vector<RefPtr<PerformanceEntry> > Performance::getEntriesByName(const String& name, const String& entryType)
+{
+ Vector<RefPtr<PerformanceEntry> > entries;
+
+ if (entryType.isNull() || equalIgnoringCase(entryType, "resource"))
+ for (Vector<RefPtr<PerformanceEntry> >::const_iterator resource = m_resourceTimingBuffer.begin(); resource != m_resourceTimingBuffer.end(); ++resource)
+ if ((*resource)->name() == name)
+ entries.append(*resource);
+
+ if (m_userTiming) {
+ if (entryType.isNull() || equalIgnoringCase(entryType, "mark"))
+ entries.append(m_userTiming->getMarks(name));
+ if (entryType.isNull() || equalIgnoringCase(entryType, "measure"))
+ entries.append(m_userTiming->getMeasures(name));
+ }
+
+ std::sort(entries.begin(), entries.end(), PerformanceEntry::startTimeCompareLessThan);
+ return entries;
+}
+
+void Performance::webkitClearResourceTimings()
+{
+ m_resourceTimingBuffer.clear();
+}
+
+void Performance::webkitSetResourceTimingBufferSize(unsigned size)
+{
+ m_resourceTimingBufferSize = size;
+ if (isResourceTimingBufferFull())
+ dispatchEvent(Event::create(EventTypeNames::webkitresourcetimingbufferfull));
+}
+
+static bool passesTimingAllowCheck(const ResourceResponse& response, Document* requestingDocument)
+{
+ AtomicallyInitializedStatic(AtomicString&, timingAllowOrigin = *new AtomicString("timing-allow-origin"));
+
+ RefPtr<SecurityOrigin> resourceOrigin = SecurityOrigin::create(response.url());
+ if (resourceOrigin->isSameSchemeHostPort(requestingDocument->securityOrigin()))
+ return true;
+
+ const AtomicString& timingAllowOriginString = response.httpHeaderField(timingAllowOrigin);
+ if (timingAllowOriginString.isEmpty() || equalIgnoringCase(timingAllowOriginString, "null"))
+ return false;
+
+ if (timingAllowOriginString == starAtom)
+ return true;
+
+ const String& securityOrigin = requestingDocument->securityOrigin()->toString();
+ Vector<String> timingAllowOrigins;
+ timingAllowOriginString.string().split(" ", timingAllowOrigins);
+ for (size_t i = 0; i < timingAllowOrigins.size(); ++i) {
+ if (timingAllowOrigins[i] == securityOrigin)
+ return true;
+ }
+
+ return false;
+}
+
+static bool allowsTimingRedirect(const Vector<ResourceResponse>& redirectChain, const ResourceResponse& finalResponse, Document* initiatorDocument)
+{
+ if (!passesTimingAllowCheck(finalResponse, initiatorDocument))
+ return false;
+
+ for (size_t i = 0; i < redirectChain.size(); i++) {
+ if (!passesTimingAllowCheck(redirectChain[i], initiatorDocument))
+ return false;
+ }
+
+ return true;
+}
+
+void Performance::addResourceTiming(const ResourceTimingInfo& info, Document* initiatorDocument)
+{
+ if (isResourceTimingBufferFull())
+ return;
+
+ const ResourceResponse& finalResponse = info.finalResponse();
+ bool allowTimingDetails = passesTimingAllowCheck(finalResponse, initiatorDocument);
+ double startTime = info.initialTime();
+
+ if (info.redirectChain().isEmpty()) {
+ RefPtr<PerformanceEntry> entry = PerformanceResourceTiming::create(info, initiatorDocument, startTime, allowTimingDetails);
+ addResourceTimingBuffer(entry);
+ return;
+ }
+
+ const Vector<ResourceResponse>& redirectChain = info.redirectChain();
+ bool allowRedirectDetails = allowsTimingRedirect(redirectChain, finalResponse, initiatorDocument);
+
+ if (!allowRedirectDetails) {
+ ResourceLoadTiming* finalTiming = finalResponse.resourceLoadTiming();
+ ASSERT(finalTiming);
+ if (finalTiming)
+ startTime = finalTiming->requestTime;
+ }
+
+ ResourceLoadTiming* lastRedirectTiming = redirectChain.last().resourceLoadTiming();
+ ASSERT(lastRedirectTiming);
+ double lastRedirectEndTime = lastRedirectTiming->receiveHeadersEnd;
+
+ RefPtr<PerformanceEntry> entry = PerformanceResourceTiming::create(info, initiatorDocument, startTime, lastRedirectEndTime, allowTimingDetails, allowRedirectDetails);
+ addResourceTimingBuffer(entry);
+}
+
+void Performance::addResourceTimingBuffer(PassRefPtr<PerformanceEntry> entry)
+{
+ m_resourceTimingBuffer.append(entry);
+
+ if (isResourceTimingBufferFull())
+ dispatchEvent(Event::create(EventTypeNames::webkitresourcetimingbufferfull));
+}
+
+bool Performance::isResourceTimingBufferFull()
+{
+ return m_resourceTimingBuffer.size() >= m_resourceTimingBufferSize;
+}
+
+void Performance::mark(const String& markName, ExceptionState& exceptionState)
+{
+ if (!m_userTiming)
+ m_userTiming = UserTiming::create(this);
+ m_userTiming->mark(markName, exceptionState);
+}
+
+void Performance::clearMarks(const String& markName)
+{
+ if (!m_userTiming)
+ m_userTiming = UserTiming::create(this);
+ m_userTiming->clearMarks(markName);
+}
+
+void Performance::measure(const String& measureName, const String& startMark, const String& endMark, ExceptionState& exceptionState)
+{
+ if (!m_userTiming)
+ m_userTiming = UserTiming::create(this);
+ m_userTiming->measure(measureName, startMark, endMark, exceptionState);
+}
+
+void Performance::clearMeasures(const String& measureName)
+{
+ if (!m_userTiming)
+ m_userTiming = UserTiming::create(this);
+ m_userTiming->clearMeasures(measureName);
+}
+
+double Performance::now() const
+{
+ return 1000.0 * (monotonicallyIncreasingTime() - m_referenceTime);
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/timing/Performance.h b/chromium/third_party/WebKit/Source/core/timing/Performance.h
new file mode 100644
index 00000000000..8dfe0be352c
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/timing/Performance.h
@@ -0,0 +1,105 @@
+/*
+ * Copyright (C) 2010 Google Inc. All rights reserved.
+ * Copyright (C) 2012 Intel Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef Performance_h
+#define Performance_h
+
+#include "bindings/v8/ScriptWrappable.h"
+#include "core/events/EventTarget.h"
+#include "core/frame/DOMWindowProperty.h"
+#include "core/timing/MemoryInfo.h"
+#include "core/timing/PerformanceEntry.h"
+#include "core/timing/PerformanceNavigation.h"
+#include "core/timing/PerformanceTiming.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefCounted.h"
+#include "wtf/RefPtr.h"
+#include "wtf/text/WTFString.h"
+
+namespace WebCore {
+
+class Document;
+class ExceptionState;
+class ResourceRequest;
+class ResourceResponse;
+class ResourceTimingInfo;
+class UserTiming;
+
+class Performance : public ScriptWrappable, public RefCounted<Performance>, public DOMWindowProperty, public EventTargetWithInlineData {
+ REFCOUNTED_EVENT_TARGET(Performance);
+public:
+ static PassRefPtr<Performance> create(Frame* frame) { return adoptRef(new Performance(frame)); }
+ ~Performance();
+
+ virtual const AtomicString& interfaceName() const OVERRIDE;
+ virtual ExecutionContext* executionContext() const OVERRIDE;
+
+ PassRefPtr<MemoryInfo> memory() const;
+ PerformanceNavigation* navigation() const;
+ PerformanceTiming* timing() const;
+ double now() const;
+
+ Vector<RefPtr<PerformanceEntry> > getEntries() const;
+ Vector<RefPtr<PerformanceEntry> > getEntriesByType(const String& entryType);
+ Vector<RefPtr<PerformanceEntry> > getEntriesByName(const String& name, const String& entryType);
+
+ void webkitClearResourceTimings();
+ void webkitSetResourceTimingBufferSize(unsigned int);
+
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(webkitresourcetimingbufferfull);
+
+ void addResourceTiming(const ResourceTimingInfo&, Document*);
+
+ void mark(const String& markName, ExceptionState&);
+ void clearMarks(const String& markName);
+
+ void measure(const String& measureName, const String& startMark, const String& endMark, ExceptionState&);
+ void clearMeasures(const String& measureName);
+
+private:
+ explicit Performance(Frame*);
+
+ bool isResourceTimingBufferFull();
+ void addResourceTimingBuffer(PassRefPtr<PerformanceEntry>);
+
+ mutable RefPtr<PerformanceNavigation> m_navigation;
+ mutable RefPtr<PerformanceTiming> m_timing;
+
+ Vector<RefPtr<PerformanceEntry> > m_resourceTimingBuffer;
+ unsigned m_resourceTimingBufferSize;
+ double m_referenceTime;
+
+ RefPtr<UserTiming> m_userTiming;
+};
+
+}
+
+#endif // Performance_h
diff --git a/chromium/third_party/WebKit/Source/core/timing/Performance.idl b/chromium/third_party/WebKit/Source/core/timing/Performance.idl
new file mode 100644
index 00000000000..b29b83e4985
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/timing/Performance.idl
@@ -0,0 +1,66 @@
+/*
+ * Copyright (C) 2010 Google Inc. All rights reserved.
+ * Copyright (C) 2012 Intel Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+// See: http://www.w3.org/TR/navigation-timing/
+interface Performance : EventTarget {
+ readonly attribute PerformanceNavigation navigation;
+ readonly attribute PerformanceTiming timing;
+ readonly attribute MemoryInfo memory;
+
+ [MeasureAs=UnprefixedPerformanceTimeline] sequence<PerformanceEntry> getEntries();
+ [MeasureAs=UnprefixedPerformanceTimeline] sequence<PerformanceEntry> getEntriesByType(DOMString entryType);
+ [MeasureAs=UnprefixedPerformanceTimeline] sequence<PerformanceEntry> getEntriesByName(DOMString name, [Default=NullString] optional DOMString entryType);
+ [DeprecateAs=PrefixedPerformanceTimeline,ImplementedAs=getEntries] sequence<PerformanceEntry> webkitGetEntries();
+ [DeprecateAs=PrefixedPerformanceTimeline,ImplementedAs=getEntriesByType] sequence<PerformanceEntry> webkitGetEntriesByType(DOMString entryType);
+ [DeprecateAs=PrefixedPerformanceTimeline,ImplementedAs=getEntriesByName] sequence<PerformanceEntry> webkitGetEntriesByName(DOMString name, [Default=NullString] optional DOMString entryType);
+
+ void webkitClearResourceTimings();
+ void webkitSetResourceTimingBufferSize(unsigned long maxSize);
+
+ attribute EventHandler onwebkitresourcetimingbufferfull;
+
+ // See http://www.w3.org/TR/2012/CR-user-timing-20120726/
+ [RaisesException,MeasureAs=UnprefixedUserTiming] void mark(DOMString markName);
+ [MeasureAs=UnprefixedUserTiming] void clearMarks([Default=NullString] optional DOMString markName);
+
+ [RaisesException,MeasureAs=UnprefixedUserTiming] void measure(DOMString measureName, [Default=NullString] optional DOMString startMark, [Default=NullString] optional DOMString endMark);
+ [MeasureAs=UnprefixedUserTiming] void clearMeasures([Default=NullString] optional DOMString measureName);
+
+ [RaisesException,DeprecateAs=PrefixedUserTiming,ImplementedAs=mark] void webkitMark(DOMString markName);
+ [DeprecateAs=PrefixedUserTiming,ImplementedAs=clearMarks] void webkitClearMarks([Default=NullString] optional DOMString markName);
+
+ [RaisesException,DeprecateAs=PrefixedUserTiming,ImplementedAs=measure] void webkitMeasure(DOMString measureName, [Default=NullString] optional DOMString startMark, [Default=NullString] optional DOMString endMark);
+ [DeprecateAs=PrefixedUserTiming,ImplementedAs=clearMeasures] void webkitClearMeasures([Default=NullString] optional DOMString measureName);
+
+ // See http://www.w3.org/TR/hr-time/ for details.
+ double now();
+};
+
diff --git a/chromium/third_party/WebKit/Source/core/timing/PerformanceEntry.cpp b/chromium/third_party/WebKit/Source/core/timing/PerformanceEntry.cpp
new file mode 100644
index 00000000000..ee615282af2
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/timing/PerformanceEntry.cpp
@@ -0,0 +1,69 @@
+/*
+ * Copyright (C) 2012 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/timing/PerformanceEntry.h"
+
+namespace WebCore {
+
+PerformanceEntry::PerformanceEntry(const String& name, const String& entryType, double startTime, double finishTime)
+ : m_name(name)
+ , m_entryType(entryType)
+ , m_startTime(startTime)
+ , m_duration(finishTime - startTime)
+{
+ ScriptWrappable::init(this);
+}
+
+PerformanceEntry::~PerformanceEntry()
+{
+}
+
+String PerformanceEntry::name() const
+{
+ return m_name;
+}
+
+String PerformanceEntry::entryType() const
+{
+ return m_entryType;
+}
+
+double PerformanceEntry::startTime() const
+{
+ return m_startTime;
+}
+
+double PerformanceEntry::duration() const
+{
+ return m_duration;
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/page/PerformanceEntry.h b/chromium/third_party/WebKit/Source/core/timing/PerformanceEntry.h
index 1f19b434aff..1f19b434aff 100644
--- a/chromium/third_party/WebKit/Source/core/page/PerformanceEntry.h
+++ b/chromium/third_party/WebKit/Source/core/timing/PerformanceEntry.h
diff --git a/chromium/third_party/WebKit/Source/core/timing/PerformanceEntry.idl b/chromium/third_party/WebKit/Source/core/timing/PerformanceEntry.idl
new file mode 100644
index 00000000000..2f5771fc2c1
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/timing/PerformanceEntry.idl
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2012 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+// See: https://dvcs.w3.org/hg/webperf/raw-file/tip/specs/PerformanceTimeline/Overview.html
+[
+ Custom=Wrap,
+] interface PerformanceEntry {
+ readonly attribute DOMString name;
+ readonly attribute DOMString entryType;
+ readonly attribute double startTime;
+ readonly attribute double duration;
+};
diff --git a/chromium/third_party/WebKit/Source/core/timing/PerformanceMark.h b/chromium/third_party/WebKit/Source/core/timing/PerformanceMark.h
new file mode 100644
index 00000000000..793a7cd53d8
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/timing/PerformanceMark.h
@@ -0,0 +1,52 @@
+/*
+ * Copyright (C) 2012 Intel Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef PerformanceMark_h
+#define PerformanceMark_h
+
+#include "core/timing/PerformanceEntry.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/text/WTFString.h"
+
+namespace WebCore {
+
+class PerformanceMark : public PerformanceEntry {
+public:
+ static PassRefPtr<PerformanceMark> create(const String& name, double startTime) { return adoptRef(new PerformanceMark(name, startTime)); }
+
+ virtual bool isMark() { return true; }
+
+private:
+ PerformanceMark(const String& name, double startTime) : PerformanceEntry(name, "mark", startTime, startTime)
+ {
+ ScriptWrappable::init(this);
+ }
+
+ ~PerformanceMark() { }
+};
+
+}
+
+#endif // !defined(PerformanceMark_h)
diff --git a/chromium/third_party/WebKit/Source/core/page/PerformanceMark.idl b/chromium/third_party/WebKit/Source/core/timing/PerformanceMark.idl
index 6bae83efc1c..6bae83efc1c 100644
--- a/chromium/third_party/WebKit/Source/core/page/PerformanceMark.idl
+++ b/chromium/third_party/WebKit/Source/core/timing/PerformanceMark.idl
diff --git a/chromium/third_party/WebKit/Source/core/timing/PerformanceMeasure.h b/chromium/third_party/WebKit/Source/core/timing/PerformanceMeasure.h
new file mode 100644
index 00000000000..9d24142f4ee
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/timing/PerformanceMeasure.h
@@ -0,0 +1,51 @@
+/*
+ * Copyright (C) 2012 Intel Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef PerformanceMeasure_h
+#define PerformanceMeasure_h
+
+#include "core/timing/PerformanceEntry.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/text/WTFString.h"
+
+namespace WebCore {
+
+class PerformanceMeasure : public PerformanceEntry {
+public:
+ static PassRefPtr<PerformanceMeasure> create(const String& name, double startTime, double endTime) { return adoptRef(new PerformanceMeasure(name, startTime, endTime)); }
+
+ virtual bool isMeasure() { return true; }
+
+private:
+ PerformanceMeasure(const String& name, double startTime, double endTime) : PerformanceEntry(name, "measure", startTime, endTime)
+ {
+ ScriptWrappable::init(this);
+ }
+ ~PerformanceMeasure() { }
+};
+
+}
+
+#endif // !defined(PerformanceMeasure_h)
diff --git a/chromium/third_party/WebKit/Source/core/page/PerformanceMeasure.idl b/chromium/third_party/WebKit/Source/core/timing/PerformanceMeasure.idl
index ee032b7adf7..ee032b7adf7 100644
--- a/chromium/third_party/WebKit/Source/core/page/PerformanceMeasure.idl
+++ b/chromium/third_party/WebKit/Source/core/timing/PerformanceMeasure.idl
diff --git a/chromium/third_party/WebKit/Source/core/timing/PerformanceNavigation.cpp b/chromium/third_party/WebKit/Source/core/timing/PerformanceNavigation.cpp
new file mode 100644
index 00000000000..7e94d7596e4
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/timing/PerformanceNavigation.cpp
@@ -0,0 +1,82 @@
+/*
+ * Copyright (C) 2010 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/timing/PerformanceNavigation.h"
+
+#include "core/loader/DocumentLoader.h"
+#include "core/loader/FrameLoaderTypes.h"
+#include "core/frame/Frame.h"
+
+namespace WebCore {
+
+PerformanceNavigation::PerformanceNavigation(Frame* frame)
+ : DOMWindowProperty(frame)
+{
+ ScriptWrappable::init(this);
+}
+
+unsigned short PerformanceNavigation::type() const
+{
+ if (!m_frame)
+ return TYPE_NAVIGATE;
+
+ DocumentLoader* documentLoader = m_frame->loader().documentLoader();
+ if (!documentLoader)
+ return TYPE_NAVIGATE;
+
+ WebCore::NavigationType navigationType = documentLoader->triggeringAction().type();
+ switch (navigationType) {
+ case NavigationTypeReload:
+ return TYPE_RELOAD;
+ case NavigationTypeBackForward:
+ return TYPE_BACK_FORWARD;
+ default:
+ return TYPE_NAVIGATE;
+ }
+}
+
+unsigned short PerformanceNavigation::redirectCount() const
+{
+ if (!m_frame)
+ return 0;
+
+ DocumentLoader* loader = m_frame->loader().documentLoader();
+ if (!loader)
+ return 0;
+
+ DocumentLoadTiming* timing = loader->timing();
+ if (timing->hasCrossOriginRedirect())
+ return 0;
+
+ return timing->redirectCount();
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/timing/PerformanceNavigation.h b/chromium/third_party/WebKit/Source/core/timing/PerformanceNavigation.h
new file mode 100644
index 00000000000..2444b39f829
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/timing/PerformanceNavigation.h
@@ -0,0 +1,63 @@
+/*
+ * Copyright (C) 2010 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef PerformanceNavigation_h
+#define PerformanceNavigation_h
+
+#include "bindings/v8/ScriptWrappable.h"
+#include "core/frame/DOMWindowProperty.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefCounted.h"
+
+namespace WebCore {
+
+class Frame;
+
+class PerformanceNavigation : public RefCounted<PerformanceNavigation>, public ScriptWrappable, public DOMWindowProperty {
+public:
+ static PassRefPtr<PerformanceNavigation> create(Frame* frame) { return adoptRef(new PerformanceNavigation(frame)); }
+
+ enum PerformanceNavigationType {
+ TYPE_NAVIGATE,
+ TYPE_RELOAD,
+ TYPE_BACK_FORWARD,
+ TYPE_RESERVED = 255
+ };
+
+ unsigned short type() const;
+ unsigned short redirectCount() const;
+
+private:
+ explicit PerformanceNavigation(Frame*);
+};
+
+}
+
+#endif // !defined(PerformanceNavigation_h)
diff --git a/chromium/third_party/WebKit/Source/core/page/PerformanceNavigation.idl b/chromium/third_party/WebKit/Source/core/timing/PerformanceNavigation.idl
index cde7a72d4e3..cde7a72d4e3 100644
--- a/chromium/third_party/WebKit/Source/core/page/PerformanceNavigation.idl
+++ b/chromium/third_party/WebKit/Source/core/timing/PerformanceNavigation.idl
diff --git a/chromium/third_party/WebKit/Source/core/timing/PerformanceResourceTiming.cpp b/chromium/third_party/WebKit/Source/core/timing/PerformanceResourceTiming.cpp
new file mode 100644
index 00000000000..8648b4fcbef
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/timing/PerformanceResourceTiming.cpp
@@ -0,0 +1,194 @@
+/*
+ * Copyright (C) 2012 Google Inc. All rights reserved.
+ * Copyright (C) 2012 Intel Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/timing/PerformanceResourceTiming.h"
+
+#include "core/dom/Document.h"
+#include "core/loader/DocumentLoadTiming.h"
+#include "core/loader/DocumentLoader.h"
+#include "core/timing/ResourceTimingInfo.h"
+#include "platform/network/ResourceRequest.h"
+#include "platform/network/ResourceResponse.h"
+
+namespace WebCore {
+
+static double monotonicTimeToDocumentMilliseconds(Document* document, double seconds)
+{
+ ASSERT(seconds >= 0.0);
+ return document->loader()->timing()->monotonicTimeToZeroBasedDocumentTime(seconds) * 1000.0;
+}
+
+PerformanceResourceTiming::PerformanceResourceTiming(const ResourceTimingInfo& info, Document* requestingDocument, double startTime, double lastRedirectEndTime, bool allowTimingDetails, bool allowRedirectDetails)
+ : PerformanceEntry(info.initialRequest().url().string(), "resource", monotonicTimeToDocumentMilliseconds(requestingDocument, startTime), monotonicTimeToDocumentMilliseconds(requestingDocument, info.loadFinishTime()))
+ , m_initiatorType(info.initiatorType())
+ , m_timing(info.finalResponse().resourceLoadTiming())
+ , m_lastRedirectEndTime(lastRedirectEndTime)
+ , m_finishTime(info.loadFinishTime())
+ , m_didReuseConnection(info.finalResponse().connectionReused())
+ , m_allowTimingDetails(allowTimingDetails)
+ , m_allowRedirectDetails(allowRedirectDetails)
+ , m_requestingDocument(requestingDocument)
+{
+ ScriptWrappable::init(this);
+}
+
+PerformanceResourceTiming::~PerformanceResourceTiming()
+{
+}
+
+AtomicString PerformanceResourceTiming::initiatorType() const
+{
+ return m_initiatorType;
+}
+
+double PerformanceResourceTiming::redirectStart() const
+{
+ if (!m_lastRedirectEndTime || !m_allowRedirectDetails)
+ return 0.0;
+
+ return PerformanceEntry::startTime();
+}
+
+double PerformanceResourceTiming::redirectEnd() const
+{
+ if (!m_lastRedirectEndTime || !m_allowRedirectDetails)
+ return 0.0;
+
+ return monotonicTimeToDocumentMilliseconds(m_requestingDocument.get(), m_lastRedirectEndTime);
+}
+
+double PerformanceResourceTiming::fetchStart() const
+{
+ if (m_lastRedirectEndTime) {
+ // FIXME: ASSERT(m_timing) should be in constructor once timeticks of
+ // AppCache is exposed from chrome network stack, crbug/251100
+ ASSERT(m_timing);
+ return monotonicTimeToDocumentMilliseconds(m_requestingDocument.get(), m_timing->requestTime);
+ }
+
+ return PerformanceEntry::startTime();
+}
+
+double PerformanceResourceTiming::domainLookupStart() const
+{
+ if (!m_allowTimingDetails)
+ return 0.0;
+
+ if (!m_timing || m_timing->dnsStart == 0.0)
+ return fetchStart();
+
+ return monotonicTimeToDocumentMilliseconds(m_requestingDocument.get(), m_timing->dnsStart);
+}
+
+double PerformanceResourceTiming::domainLookupEnd() const
+{
+ if (!m_allowTimingDetails)
+ return 0.0;
+
+ if (!m_timing || m_timing->dnsEnd == 0.0)
+ return domainLookupStart();
+
+ return monotonicTimeToDocumentMilliseconds(m_requestingDocument.get(), m_timing->dnsEnd);
+}
+
+double PerformanceResourceTiming::connectStart() const
+{
+ if (!m_allowTimingDetails)
+ return 0.0;
+
+ // connectStart will be zero when a network request is not made.
+ if (!m_timing || m_timing->connectStart == 0.0 || m_didReuseConnection)
+ return domainLookupEnd();
+
+ // connectStart includes any DNS time, so we may need to trim that off.
+ double connectStart = m_timing->connectStart;
+ if (m_timing->dnsEnd > 0.0)
+ connectStart = m_timing->dnsEnd;
+
+ return monotonicTimeToDocumentMilliseconds(m_requestingDocument.get(), connectStart);
+}
+
+double PerformanceResourceTiming::connectEnd() const
+{
+ if (!m_allowTimingDetails)
+ return 0.0;
+
+ // connectStart will be zero when a network request is not made.
+ if (!m_timing || m_timing->connectEnd == 0.0 || m_didReuseConnection)
+ return connectStart();
+
+ return monotonicTimeToDocumentMilliseconds(m_requestingDocument.get(), m_timing->connectEnd);
+}
+
+double PerformanceResourceTiming::secureConnectionStart() const
+{
+ if (!m_allowTimingDetails)
+ return 0.0;
+
+ if (!m_timing || m_timing->sslStart == 0.0) // Secure connection not negotiated.
+ return 0.0;
+
+ return monotonicTimeToDocumentMilliseconds(m_requestingDocument.get(), m_timing->sslStart);
+}
+
+double PerformanceResourceTiming::requestStart() const
+{
+ if (!m_allowTimingDetails)
+ return 0.0;
+
+ if (!m_timing)
+ return connectEnd();
+
+ return monotonicTimeToDocumentMilliseconds(m_requestingDocument.get(), m_timing->sendStart);
+}
+
+double PerformanceResourceTiming::responseStart() const
+{
+ if (!m_allowTimingDetails)
+ return 0.0;
+
+ if (!m_timing)
+ return requestStart();
+
+ // FIXME: This number isn't exactly correct. See the notes in PerformanceTiming::responseStart().
+ return monotonicTimeToDocumentMilliseconds(m_requestingDocument.get(), m_timing->receiveHeadersEnd);
+}
+
+double PerformanceResourceTiming::responseEnd() const
+{
+ if (!m_finishTime)
+ return responseStart();
+
+ return monotonicTimeToDocumentMilliseconds(m_requestingDocument.get(), m_finishTime);
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/timing/PerformanceResourceTiming.h b/chromium/third_party/WebKit/Source/core/timing/PerformanceResourceTiming.h
new file mode 100644
index 00000000000..2c1c7ad99eb
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/timing/PerformanceResourceTiming.h
@@ -0,0 +1,92 @@
+/*
+ * Copyright (C) 2012 Google Inc. All rights reserved.
+ * Copyright (C) 2012 Intel Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef PerformanceResourceTiming_h
+#define PerformanceResourceTiming_h
+
+#include "core/timing/PerformanceEntry.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefPtr.h"
+
+namespace WebCore {
+
+class Document;
+class KURL;
+class ResourceLoadTiming;
+class ResourceRequest;
+class ResourceResponse;
+class ResourceTimingInfo;
+
+class PerformanceResourceTiming : public PerformanceEntry {
+public:
+ static PassRefPtr<PerformanceResourceTiming> create(const ResourceTimingInfo& info, Document* requestingDocument, double startTime, double lastRedirectEndTime, bool m_allowTimingDetails, bool m_allowRedirectDetails)
+ {
+ return adoptRef(new PerformanceResourceTiming(info, requestingDocument, startTime, lastRedirectEndTime, m_allowTimingDetails, m_allowRedirectDetails));
+ }
+
+ static PassRefPtr<PerformanceResourceTiming> create(const ResourceTimingInfo& info, Document* requestingDocument, double startTime, bool m_allowTimingDetails)
+ {
+ return adoptRef(new PerformanceResourceTiming(info, requestingDocument, startTime, 0.0, m_allowTimingDetails, false));
+ }
+
+ AtomicString initiatorType() const;
+
+ double redirectStart() const;
+ double redirectEnd() const;
+ double fetchStart() const;
+ double domainLookupStart() const;
+ double domainLookupEnd() const;
+ double connectStart() const;
+ double connectEnd() const;
+ double secureConnectionStart() const;
+ double requestStart() const;
+ double responseStart() const;
+ double responseEnd() const;
+
+ virtual bool isResource() { return true; }
+
+private:
+ PerformanceResourceTiming(const ResourceTimingInfo&, Document* requestingDocument, double startTime, double lastRedirectEndTime, bool m_allowTimingDetails, bool m_allowRedirectDetails);
+ ~PerformanceResourceTiming();
+
+ AtomicString m_initiatorType;
+ RefPtr<ResourceLoadTiming> m_timing;
+ double m_lastRedirectEndTime;
+ double m_finishTime;
+ bool m_didReuseConnection;
+ bool m_allowTimingDetails;
+ bool m_allowRedirectDetails;
+ RefPtr<Document> m_requestingDocument;
+};
+
+}
+
+#endif // !defined(PerformanceResourceTiming_h)
diff --git a/chromium/third_party/WebKit/Source/core/page/PerformanceResourceTiming.idl b/chromium/third_party/WebKit/Source/core/timing/PerformanceResourceTiming.idl
index 860c91dfa29..860c91dfa29 100644
--- a/chromium/third_party/WebKit/Source/core/page/PerformanceResourceTiming.idl
+++ b/chromium/third_party/WebKit/Source/core/timing/PerformanceResourceTiming.idl
diff --git a/chromium/third_party/WebKit/Source/core/timing/PerformanceTiming.cpp b/chromium/third_party/WebKit/Source/core/timing/PerformanceTiming.cpp
new file mode 100644
index 00000000000..0aa305e4e89
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/timing/PerformanceTiming.cpp
@@ -0,0 +1,356 @@
+/*
+ * Copyright (C) 2010 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/timing/PerformanceTiming.h"
+
+#include "core/dom/Document.h"
+#include "core/dom/DocumentTiming.h"
+#include "core/frame/Frame.h"
+#include "core/loader/DocumentLoadTiming.h"
+#include "core/loader/DocumentLoader.h"
+#include "core/loader/FrameLoader.h"
+#include "platform/network/ResourceLoadTiming.h"
+#include "platform/network/ResourceResponse.h"
+
+namespace WebCore {
+
+static unsigned long long toIntegerMilliseconds(double seconds)
+{
+ ASSERT(seconds >= 0);
+ return static_cast<unsigned long long>(seconds * 1000.0);
+}
+
+PerformanceTiming::PerformanceTiming(Frame* frame)
+ : DOMWindowProperty(frame)
+{
+ ScriptWrappable::init(this);
+}
+
+unsigned long long PerformanceTiming::navigationStart() const
+{
+ DocumentLoadTiming* timing = documentLoadTiming();
+ if (!timing)
+ return 0;
+
+ return monotonicTimeToIntegerMilliseconds(timing->navigationStart());
+}
+
+unsigned long long PerformanceTiming::unloadEventStart() const
+{
+ DocumentLoadTiming* timing = documentLoadTiming();
+ if (!timing)
+ return 0;
+
+ if (timing->hasCrossOriginRedirect() || !timing->hasSameOriginAsPreviousDocument())
+ return 0;
+
+ return monotonicTimeToIntegerMilliseconds(timing->unloadEventStart());
+}
+
+unsigned long long PerformanceTiming::unloadEventEnd() const
+{
+ DocumentLoadTiming* timing = documentLoadTiming();
+ if (!timing)
+ return 0;
+
+ if (timing->hasCrossOriginRedirect() || !timing->hasSameOriginAsPreviousDocument())
+ return 0;
+
+ return monotonicTimeToIntegerMilliseconds(timing->unloadEventEnd());
+}
+
+unsigned long long PerformanceTiming::redirectStart() const
+{
+ DocumentLoadTiming* timing = documentLoadTiming();
+ if (!timing)
+ return 0;
+
+ if (timing->hasCrossOriginRedirect())
+ return 0;
+
+ return monotonicTimeToIntegerMilliseconds(timing->redirectStart());
+}
+
+unsigned long long PerformanceTiming::redirectEnd() const
+{
+ DocumentLoadTiming* timing = documentLoadTiming();
+ if (!timing)
+ return 0;
+
+ if (timing->hasCrossOriginRedirect())
+ return 0;
+
+ return monotonicTimeToIntegerMilliseconds(timing->redirectEnd());
+}
+
+unsigned long long PerformanceTiming::fetchStart() const
+{
+ DocumentLoadTiming* timing = documentLoadTiming();
+ if (!timing)
+ return 0;
+
+ return monotonicTimeToIntegerMilliseconds(timing->fetchStart());
+}
+
+unsigned long long PerformanceTiming::domainLookupStart() const
+{
+ ResourceLoadTiming* timing = resourceLoadTiming();
+ if (!timing)
+ return fetchStart();
+
+ // This will be zero when a DNS request is not performed.
+ // Rather than exposing a special value that indicates no DNS, we "backfill" with fetchStart.
+ double dnsStart = timing->dnsStart;
+ if (dnsStart == 0.0)
+ return fetchStart();
+
+ return monotonicTimeToIntegerMilliseconds(dnsStart);
+}
+
+unsigned long long PerformanceTiming::domainLookupEnd() const
+{
+ ResourceLoadTiming* timing = resourceLoadTiming();
+ if (!timing)
+ return domainLookupStart();
+
+ // This will be zero when a DNS request is not performed.
+ // Rather than exposing a special value that indicates no DNS, we "backfill" with domainLookupStart.
+ double dnsEnd = timing->dnsEnd;
+ if (dnsEnd == 0.0)
+ return domainLookupStart();
+
+ return monotonicTimeToIntegerMilliseconds(dnsEnd);
+}
+
+unsigned long long PerformanceTiming::connectStart() const
+{
+ DocumentLoader* loader = documentLoader();
+ if (!loader)
+ return domainLookupEnd();
+
+ ResourceLoadTiming* timing = loader->response().resourceLoadTiming();
+ if (!timing)
+ return domainLookupEnd();
+
+ // connectStart will be zero when a network request is not made.
+ // Rather than exposing a special value that indicates no new connection, we "backfill" with domainLookupEnd.
+ double connectStart = timing->connectStart;
+ if (connectStart == 0.0 || loader->response().connectionReused())
+ return domainLookupEnd();
+
+ // ResourceLoadTiming's connect phase includes DNS, however Navigation Timing's
+ // connect phase should not. So if there is DNS time, trim it from the start.
+ if (timing->dnsEnd > 0.0 && timing->dnsEnd > connectStart)
+ connectStart = timing->dnsEnd;
+
+ return monotonicTimeToIntegerMilliseconds(connectStart);
+}
+
+unsigned long long PerformanceTiming::connectEnd() const
+{
+ DocumentLoader* loader = documentLoader();
+ if (!loader)
+ return connectStart();
+
+ ResourceLoadTiming* timing = loader->response().resourceLoadTiming();
+ if (!timing)
+ return connectStart();
+
+ // connectEnd will be zero when a network request is not made.
+ // Rather than exposing a special value that indicates no new connection, we "backfill" with connectStart.
+ double connectEnd = timing->connectEnd;
+ if (connectEnd == 0.0 || loader->response().connectionReused())
+ return connectStart();
+
+ return monotonicTimeToIntegerMilliseconds(connectEnd);
+}
+
+unsigned long long PerformanceTiming::secureConnectionStart() const
+{
+ DocumentLoader* loader = documentLoader();
+ if (!loader)
+ return 0;
+
+ ResourceLoadTiming* timing = loader->response().resourceLoadTiming();
+ if (!timing)
+ return 0;
+
+ double sslStart = timing->sslStart;
+ if (sslStart == 0.0)
+ return 0;
+
+ return monotonicTimeToIntegerMilliseconds(sslStart);
+}
+
+unsigned long long PerformanceTiming::requestStart() const
+{
+ ResourceLoadTiming* timing = resourceLoadTiming();
+
+ if (!timing || timing->sendStart == 0.0)
+ return connectEnd();
+
+ return monotonicTimeToIntegerMilliseconds(timing->sendStart);
+}
+
+unsigned long long PerformanceTiming::responseStart() const
+{
+ ResourceLoadTiming* timing = resourceLoadTiming();
+ if (!timing || timing->receiveHeadersEnd == 0.0)
+ return requestStart();
+
+ // FIXME: Response start needs to be the time of the first received byte.
+ // However, the ResourceLoadTiming API currently only supports the time
+ // the last header byte was received. For many responses with reasonable
+ // sized cookies, the HTTP headers fit into a single packet so this time
+ // is basically equivalent. But for some responses, particularly those with
+ // headers larger than a single packet, this time will be too late.
+ return monotonicTimeToIntegerMilliseconds(timing->receiveHeadersEnd);
+}
+
+unsigned long long PerformanceTiming::responseEnd() const
+{
+ DocumentLoadTiming* timing = documentLoadTiming();
+ if (!timing)
+ return 0;
+
+ return monotonicTimeToIntegerMilliseconds(timing->responseEnd());
+}
+
+unsigned long long PerformanceTiming::domLoading() const
+{
+ const DocumentTiming* timing = documentTiming();
+ if (!timing)
+ return fetchStart();
+
+ return monotonicTimeToIntegerMilliseconds(timing->domLoading);
+}
+
+unsigned long long PerformanceTiming::domInteractive() const
+{
+ const DocumentTiming* timing = documentTiming();
+ if (!timing)
+ return 0;
+
+ return monotonicTimeToIntegerMilliseconds(timing->domInteractive);
+}
+
+unsigned long long PerformanceTiming::domContentLoadedEventStart() const
+{
+ const DocumentTiming* timing = documentTiming();
+ if (!timing)
+ return 0;
+
+ return monotonicTimeToIntegerMilliseconds(timing->domContentLoadedEventStart);
+}
+
+unsigned long long PerformanceTiming::domContentLoadedEventEnd() const
+{
+ const DocumentTiming* timing = documentTiming();
+ if (!timing)
+ return 0;
+
+ return monotonicTimeToIntegerMilliseconds(timing->domContentLoadedEventEnd);
+}
+
+unsigned long long PerformanceTiming::domComplete() const
+{
+ const DocumentTiming* timing = documentTiming();
+ if (!timing)
+ return 0;
+
+ return monotonicTimeToIntegerMilliseconds(timing->domComplete);
+}
+
+unsigned long long PerformanceTiming::loadEventStart() const
+{
+ DocumentLoadTiming* timing = documentLoadTiming();
+ if (!timing)
+ return 0;
+
+ return monotonicTimeToIntegerMilliseconds(timing->loadEventStart());
+}
+
+unsigned long long PerformanceTiming::loadEventEnd() const
+{
+ DocumentLoadTiming* timing = documentLoadTiming();
+ if (!timing)
+ return 0;
+
+ return monotonicTimeToIntegerMilliseconds(timing->loadEventEnd());
+}
+
+DocumentLoader* PerformanceTiming::documentLoader() const
+{
+ if (!m_frame)
+ return 0;
+
+ return m_frame->loader().documentLoader();
+}
+
+const DocumentTiming* PerformanceTiming::documentTiming() const
+{
+ if (!m_frame)
+ return 0;
+
+ Document* document = m_frame->document();
+ if (!document)
+ return 0;
+
+ return document->timing();
+}
+
+DocumentLoadTiming* PerformanceTiming::documentLoadTiming() const
+{
+ DocumentLoader* loader = documentLoader();
+ if (!loader)
+ return 0;
+
+ return loader->timing();
+}
+
+ResourceLoadTiming* PerformanceTiming::resourceLoadTiming() const
+{
+ DocumentLoader* loader = documentLoader();
+ if (!loader)
+ return 0;
+
+ return loader->response().resourceLoadTiming();
+}
+
+unsigned long long PerformanceTiming::monotonicTimeToIntegerMilliseconds(double monotonicSeconds) const
+{
+ ASSERT(monotonicSeconds >= 0);
+ const DocumentLoadTiming* timing = documentLoadTiming();
+ ASSERT(timing);
+ return toIntegerMilliseconds(timing->monotonicTimeToPseudoWallTime(monotonicSeconds));
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/timing/PerformanceTiming.h b/chromium/third_party/WebKit/Source/core/timing/PerformanceTiming.h
new file mode 100644
index 00000000000..cd8ffae7cef
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/timing/PerformanceTiming.h
@@ -0,0 +1,86 @@
+/*
+ * Copyright (C) 2010 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef PerformanceTiming_h
+#define PerformanceTiming_h
+
+#include "bindings/v8/ScriptWrappable.h"
+#include "core/frame/DOMWindowProperty.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefCounted.h"
+
+namespace WebCore {
+
+class DocumentLoadTiming;
+class DocumentLoader;
+struct DocumentTiming;
+class Frame;
+class ResourceLoadTiming;
+
+class PerformanceTiming : public RefCounted<PerformanceTiming>, public ScriptWrappable, public DOMWindowProperty {
+public:
+ static PassRefPtr<PerformanceTiming> create(Frame* frame) { return adoptRef(new PerformanceTiming(frame)); }
+
+ unsigned long long navigationStart() const;
+ unsigned long long unloadEventStart() const;
+ unsigned long long unloadEventEnd() const;
+ unsigned long long redirectStart() const;
+ unsigned long long redirectEnd() const;
+ unsigned long long fetchStart() const;
+ unsigned long long domainLookupStart() const;
+ unsigned long long domainLookupEnd() const;
+ unsigned long long connectStart() const;
+ unsigned long long connectEnd() const;
+ unsigned long long secureConnectionStart() const;
+ unsigned long long requestStart() const;
+ unsigned long long responseStart() const;
+ unsigned long long responseEnd() const;
+ unsigned long long domLoading() const;
+ unsigned long long domInteractive() const;
+ unsigned long long domContentLoadedEventStart() const;
+ unsigned long long domContentLoadedEventEnd() const;
+ unsigned long long domComplete() const;
+ unsigned long long loadEventStart() const;
+ unsigned long long loadEventEnd() const;
+
+private:
+ explicit PerformanceTiming(Frame*);
+
+ const DocumentTiming* documentTiming() const;
+ DocumentLoader* documentLoader() const;
+ DocumentLoadTiming* documentLoadTiming() const;
+ ResourceLoadTiming* resourceLoadTiming() const;
+
+ unsigned long long monotonicTimeToIntegerMilliseconds(double) const;
+};
+
+}
+
+#endif // !defined(PerformanceTiming_h)
diff --git a/chromium/third_party/WebKit/Source/core/page/PerformanceTiming.idl b/chromium/third_party/WebKit/Source/core/timing/PerformanceTiming.idl
index 160e5ccd93a..160e5ccd93a 100644
--- a/chromium/third_party/WebKit/Source/core/page/PerformanceTiming.idl
+++ b/chromium/third_party/WebKit/Source/core/timing/PerformanceTiming.idl
diff --git a/chromium/third_party/WebKit/Source/core/timing/PerformanceUserTiming.cpp b/chromium/third_party/WebKit/Source/core/timing/PerformanceUserTiming.cpp
new file mode 100644
index 00000000000..f1f783613cd
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/timing/PerformanceUserTiming.cpp
@@ -0,0 +1,208 @@
+/*
+ * Copyright (C) 2012 Intel Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/timing/PerformanceUserTiming.h"
+
+#include "bindings/v8/ExceptionState.h"
+#include "core/dom/ExceptionCode.h"
+#include "core/timing/Performance.h"
+#include "core/timing/PerformanceMark.h"
+#include "core/timing/PerformanceMeasure.h"
+#include "public/platform/Platform.h"
+
+namespace WebCore {
+
+namespace {
+
+typedef HashMap<String, NavigationTimingFunction> RestrictedKeyMap;
+static RestrictedKeyMap restrictedKeyMap()
+{
+ DEFINE_STATIC_LOCAL(RestrictedKeyMap, map, ());
+ if (map.isEmpty()) {
+ map.add("navigationStart", &PerformanceTiming::navigationStart);
+ map.add("unloadEventStart", &PerformanceTiming::unloadEventStart);
+ map.add("unloadEventEnd", &PerformanceTiming::unloadEventEnd);
+ map.add("redirectStart", &PerformanceTiming::redirectStart);
+ map.add("redirectEnd", &PerformanceTiming::redirectEnd);
+ map.add("fetchStart", &PerformanceTiming::fetchStart);
+ map.add("domainLookupStart", &PerformanceTiming::domainLookupStart);
+ map.add("domainLookupEnd", &PerformanceTiming::domainLookupEnd);
+ map.add("connectStart", &PerformanceTiming::connectStart);
+ map.add("connectEnd", &PerformanceTiming::connectEnd);
+ map.add("secureConnectionStart", &PerformanceTiming::secureConnectionStart);
+ map.add("requestStart", &PerformanceTiming::requestStart);
+ map.add("responseStart", &PerformanceTiming::responseStart);
+ map.add("responseEnd", &PerformanceTiming::responseEnd);
+ map.add("domLoading", &PerformanceTiming::domLoading);
+ map.add("domInteractive", &PerformanceTiming::domInteractive);
+ map.add("domContentLoadedEventStart", &PerformanceTiming::domContentLoadedEventStart);
+ map.add("domContentLoadedEventEnd", &PerformanceTiming::domContentLoadedEventEnd);
+ map.add("domComplete", &PerformanceTiming::domComplete);
+ map.add("loadEventStart", &PerformanceTiming::loadEventStart);
+ map.add("loadEventEnd", &PerformanceTiming::loadEventEnd);
+ }
+ return map;
+}
+
+} // namespace anonymous
+
+UserTiming::UserTiming(Performance* performance)
+ : m_performance(performance)
+{
+}
+
+static void insertPerformanceEntry(PerformanceEntryMap& performanceEntryMap, PassRefPtr<PerformanceEntry> performanceEntry)
+{
+ RefPtr<PerformanceEntry> entry = performanceEntry;
+ PerformanceEntryMap::iterator it = performanceEntryMap.find(entry->name());
+ if (it != performanceEntryMap.end())
+ it->value.append(entry);
+ else {
+ Vector<RefPtr<PerformanceEntry> > v(1);
+ v[0] = entry;
+ performanceEntryMap.set(entry->name(), v);
+ }
+}
+
+static void clearPeformanceEntries(PerformanceEntryMap& performanceEntryMap, const String& name)
+{
+ if (name.isNull()) {
+ performanceEntryMap.clear();
+ return;
+ }
+
+ if (performanceEntryMap.contains(name))
+ performanceEntryMap.remove(name);
+}
+
+void UserTiming::mark(const String& markName, ExceptionState& exceptionState)
+{
+ if (restrictedKeyMap().contains(markName)) {
+ exceptionState.throwDOMException(SyntaxError, "'" + markName + "' is part of the PerformanceTiming interface, and cannot be used as a mark name.");
+ return;
+ }
+
+ double startTime = m_performance->now();
+ insertPerformanceEntry(m_marksMap, PerformanceMark::create(markName, startTime));
+ blink::Platform::current()->histogramCustomCounts("PLT.UserTiming_Mark", static_cast<int>(startTime), 0, 600000, 100);
+}
+
+void UserTiming::clearMarks(const String& markName)
+{
+ clearPeformanceEntries(m_marksMap, markName);
+}
+
+double UserTiming::findExistingMarkStartTime(const String& markName, ExceptionState& exceptionState)
+{
+ if (m_marksMap.contains(markName))
+ return m_marksMap.get(markName).last()->startTime();
+
+ if (restrictedKeyMap().contains(markName)) {
+ double value = static_cast<double>((m_performance->timing()->*(restrictedKeyMap().get(markName)))());
+ if (!value) {
+ exceptionState.throwDOMException(InvalidAccessError, "'" + markName + "' is empty: either the event hasn't happened yet, or it would provide cross-origin timing information.");
+ return 0.0;
+ }
+ return value - m_performance->timing()->navigationStart();
+ }
+
+ exceptionState.throwDOMException(SyntaxError, "The mark '" + markName + "' does not exist.");
+ return 0.0;
+}
+
+void UserTiming::measure(const String& measureName, const String& startMark, const String& endMark, ExceptionState& exceptionState)
+{
+ double startTime = 0.0;
+ double endTime = 0.0;
+
+ if (startMark.isNull())
+ endTime = m_performance->now();
+ else if (endMark.isNull()) {
+ endTime = m_performance->now();
+ startTime = findExistingMarkStartTime(startMark, exceptionState);
+ if (exceptionState.hadException())
+ return;
+ } else {
+ endTime = findExistingMarkStartTime(endMark, exceptionState);
+ if (exceptionState.hadException())
+ return;
+ startTime = findExistingMarkStartTime(startMark, exceptionState);
+ if (exceptionState.hadException())
+ return;
+ }
+
+ insertPerformanceEntry(m_measuresMap, PerformanceMeasure::create(measureName, startTime, endTime));
+ if (endTime >= startTime)
+ blink::Platform::current()->histogramCustomCounts("PLT.UserTiming_MeasureDuration", static_cast<int>(endTime - startTime), 0, 600000, 100);
+}
+
+void UserTiming::clearMeasures(const String& measureName)
+{
+ clearPeformanceEntries(m_measuresMap, measureName);
+}
+
+static Vector<RefPtr<PerformanceEntry> > convertToEntrySequence(const PerformanceEntryMap& performanceEntryMap)
+{
+ Vector<RefPtr<PerformanceEntry> > entries;
+
+ for (PerformanceEntryMap::const_iterator it = performanceEntryMap.begin(); it != performanceEntryMap.end(); ++it)
+ entries.append(it->value);
+
+ return entries;
+}
+
+static Vector<RefPtr<PerformanceEntry> > getEntrySequenceByName(const PerformanceEntryMap& performanceEntryMap, const String& name)
+{
+ Vector<RefPtr<PerformanceEntry> > entries;
+
+ PerformanceEntryMap::const_iterator it = performanceEntryMap.find(name);
+ if (it != performanceEntryMap.end())
+ entries.append(it->value);
+
+ return entries;
+}
+
+Vector<RefPtr<PerformanceEntry> > UserTiming::getMarks() const
+{
+ return convertToEntrySequence(m_marksMap);
+}
+
+Vector<RefPtr<PerformanceEntry> > UserTiming::getMarks(const String& name) const
+{
+ return getEntrySequenceByName(m_marksMap, name);
+}
+
+Vector<RefPtr<PerformanceEntry> > UserTiming::getMeasures() const
+{
+ return convertToEntrySequence(m_measuresMap);
+}
+
+Vector<RefPtr<PerformanceEntry> > UserTiming::getMeasures(const String& name) const
+{
+ return getEntrySequenceByName(m_measuresMap, name);
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/timing/PerformanceUserTiming.h b/chromium/third_party/WebKit/Source/core/timing/PerformanceUserTiming.h
new file mode 100644
index 00000000000..c12d6cfd491
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/timing/PerformanceUserTiming.h
@@ -0,0 +1,72 @@
+/*
+ * Copyright (C) 2012 Intel Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef PerformanceUserTiming_h
+#define PerformanceUserTiming_h
+
+#include "core/timing/PerformanceTiming.h"
+#include "wtf/HashMap.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefCounted.h"
+#include "wtf/text/StringHash.h"
+#include "wtf/text/WTFString.h"
+
+namespace WebCore {
+
+class ExceptionState;
+class Performance;
+class PerformanceEntry;
+
+typedef unsigned long long (PerformanceTiming::*NavigationTimingFunction)() const;
+typedef HashMap<String, Vector<RefPtr<PerformanceEntry> > > PerformanceEntryMap;
+
+class UserTiming : public RefCounted<UserTiming> {
+public:
+ static PassRefPtr<UserTiming> create(Performance* performance) { return adoptRef(new UserTiming(performance)); }
+
+ void mark(const String& markName, ExceptionState&);
+ void clearMarks(const String& markName);
+
+ void measure(const String& measureName, const String& startMark, const String& endMark, ExceptionState&);
+ void clearMeasures(const String& measureName);
+
+ Vector<RefPtr<PerformanceEntry> > getMarks() const;
+ Vector<RefPtr<PerformanceEntry> > getMeasures() const;
+
+ Vector<RefPtr<PerformanceEntry> > getMarks(const String& name) const;
+ Vector<RefPtr<PerformanceEntry> > getMeasures(const String& name) const;
+
+private:
+ explicit UserTiming(Performance*);
+
+ double findExistingMarkStartTime(const String& markName, ExceptionState&);
+ Performance* m_performance;
+ PerformanceEntryMap m_marksMap;
+ PerformanceEntryMap m_measuresMap;
+};
+
+}
+
+#endif // !defined(PerformanceUserTiming_h)
diff --git a/chromium/third_party/WebKit/Source/core/timing/ResourceTimingInfo.h b/chromium/third_party/WebKit/Source/core/timing/ResourceTimingInfo.h
new file mode 100644
index 00000000000..a3784a63e59
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/timing/ResourceTimingInfo.h
@@ -0,0 +1,88 @@
+/*
+ * Copyright (C) 2013 Intel Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef ResourceTimingInfo_h
+#define ResourceTimingInfo_h
+
+#include "platform/network/ResourceRequest.h"
+#include "platform/network/ResourceResponse.h"
+#include "wtf/text/AtomicString.h"
+
+namespace WebCore {
+
+class ResourceTimingInfo : public RefCounted<ResourceTimingInfo> {
+public:
+ static PassRefPtr<ResourceTimingInfo> create(const AtomicString& type, const double time)
+ {
+ return adoptRef(new ResourceTimingInfo(type, time));
+ }
+
+ double initialTime() const { return m_initialTime; }
+
+ void setInitiatorType(const AtomicString& type) { m_type = type; }
+ const AtomicString& initiatorType() const { return m_type; }
+
+ void setLoadFinishTime(double time) { m_loadFinishTime = time; }
+ double loadFinishTime() const { return m_loadFinishTime; }
+
+ void setInitialRequest(const ResourceRequest& request) { m_initialRequest = request; }
+ const ResourceRequest& initialRequest() const { return m_initialRequest; }
+
+ void setFinalResponse(const ResourceResponse& response) { m_finalResponse = response; }
+ const ResourceResponse& finalResponse() const { return m_finalResponse; }
+
+ void addRedirect(const ResourceResponse& redirectResponse) { m_redirectChain.append(redirectResponse); }
+ const Vector<ResourceResponse>& redirectChain() const { return m_redirectChain; }
+
+ void clearLoadTimings()
+ {
+ m_finalResponse.setResourceLoadTiming(0);
+ for (size_t i = 0; i < m_redirectChain.size(); ++i)
+ m_redirectChain[i].setResourceLoadTiming(0);
+ }
+
+private:
+ ResourceTimingInfo(const AtomicString& type, const double time)
+ : m_type(type)
+ , m_initialTime(time)
+ {
+ }
+
+ AtomicString m_type;
+ double m_initialTime;
+ double m_loadFinishTime;
+ ResourceRequest m_initialRequest;
+ ResourceResponse m_finalResponse;
+ Vector<ResourceResponse> m_redirectChain;
+};
+
+} // namespace WebCore
+
+#endif
diff --git a/chromium/third_party/WebKit/Source/core/workers/AbstractWorker.cpp b/chromium/third_party/WebKit/Source/core/workers/AbstractWorker.cpp
index 0d3907d6a53..a617c23b4f5 100644
--- a/chromium/third_party/WebKit/Source/core/workers/AbstractWorker.cpp
+++ b/chromium/third_party/WebKit/Source/core/workers/AbstractWorker.cpp
@@ -32,15 +32,14 @@
#include "core/workers/AbstractWorker.h"
#include "bindings/v8/ExceptionState.h"
-#include "core/dom/EventNames.h"
#include "core/dom/ExceptionCode.h"
-#include "core/dom/ScriptExecutionContext.h"
-#include "core/page/ContentSecurityPolicy.h"
-#include "weborigin/SecurityOrigin.h"
+#include "core/dom/ExecutionContext.h"
+#include "core/frame/ContentSecurityPolicy.h"
+#include "platform/weborigin/SecurityOrigin.h"
namespace WebCore {
-AbstractWorker::AbstractWorker(ScriptExecutionContext* context)
+AbstractWorker::AbstractWorker(ExecutionContext* context)
: ActiveDOMObject(context)
{
}
@@ -49,47 +48,27 @@ AbstractWorker::~AbstractWorker()
{
}
-void AbstractWorker::contextDestroyed()
+KURL AbstractWorker::resolveURL(const String& url, ExceptionState& exceptionState)
{
- ActiveDOMObject::contextDestroyed();
-}
-
-KURL AbstractWorker::resolveURL(const String& url, ExceptionState& es)
-{
- if (url.isEmpty()) {
- es.throwDOMException(SyntaxError, "Failed to create a worker: an empty URL was provided.");
- return KURL();
- }
-
// FIXME: This should use the dynamic global scope (bug #27887)
- KURL scriptURL = scriptExecutionContext()->completeURL(url);
+ KURL scriptURL = executionContext()->completeURL(url);
if (!scriptURL.isValid()) {
- es.throwDOMException(SyntaxError, "Failed to create a worker: '" + url + "' is not a valid URL.");
+ exceptionState.throwDOMException(SyntaxError, "'" + url + "' is not a valid URL.");
return KURL();
}
// We can safely expose the URL in the following exceptions, as these checks happen synchronously before redirection. JavaScript receives no new information.
- if (!scriptExecutionContext()->securityOrigin()->canRequest(scriptURL)) {
- es.throwSecurityError("Failed to create a worker: script at '" + scriptURL.elidedString() + "' cannot be accessed from origin '" + scriptExecutionContext()->securityOrigin()->toString() + "'.");
+ if (!executionContext()->securityOrigin()->canRequest(scriptURL)) {
+ exceptionState.throwSecurityError("Script at '" + scriptURL.elidedString() + "' cannot be accessed from origin '" + executionContext()->securityOrigin()->toString() + "'.");
return KURL();
}
- if (scriptExecutionContext()->contentSecurityPolicy() && !scriptExecutionContext()->contentSecurityPolicy()->allowScriptFromSource(scriptURL)) {
- es.throwSecurityError("Failed to create a worker: access to the script at '" + scriptURL.elidedString() + "' is denied by the document's Content Security Policy.");
+ if (executionContext()->contentSecurityPolicy() && !executionContext()->contentSecurityPolicy()->allowScriptFromSource(scriptURL)) {
+ exceptionState.throwSecurityError("Access to the script at '" + scriptURL.elidedString() + "' is denied by the document's Content Security Policy.");
return KURL();
}
return scriptURL;
}
-EventTargetData* AbstractWorker::eventTargetData()
-{
- return &m_eventTargetData;
-}
-
-EventTargetData* AbstractWorker::ensureEventTargetData()
-{
- return &m_eventTargetData;
-}
-
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/workers/AbstractWorker.h b/chromium/third_party/WebKit/Source/core/workers/AbstractWorker.h
index de94684d9bd..775f2e6ac4e 100644
--- a/chromium/third_party/WebKit/Source/core/workers/AbstractWorker.h
+++ b/chromium/third_party/WebKit/Source/core/workers/AbstractWorker.h
@@ -33,9 +33,9 @@
#include "bindings/v8/ScriptWrappable.h"
#include "core/dom/ActiveDOMObject.h"
-#include "core/dom/EventListener.h"
-#include "core/dom/EventNames.h"
-#include "core/dom/EventTarget.h"
+#include "core/events/EventListener.h"
+#include "core/events/EventTarget.h"
+#include "core/events/ThreadLocalEventNames.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefCounted.h"
#include "wtf/RefPtr.h"
@@ -45,34 +45,23 @@ namespace WebCore {
class ExceptionState;
class KURL;
-class ScriptExecutionContext;
+class ExecutionContext;
-class AbstractWorker : public RefCounted<AbstractWorker>, public EventTarget, public ActiveDOMObject {
+class AbstractWorker : public RefCounted<AbstractWorker>, public EventTargetWithInlineData, public ActiveDOMObject {
+ REFCOUNTED_EVENT_TARGET(AbstractWorker);
public:
// EventTarget APIs
- virtual ScriptExecutionContext* scriptExecutionContext() const OVERRIDE { return ActiveDOMObject::scriptExecutionContext(); }
+ virtual ExecutionContext* executionContext() const OVERRIDE { return ActiveDOMObject::executionContext(); }
DEFINE_ATTRIBUTE_EVENT_LISTENER(error);
- using RefCounted<AbstractWorker>::ref;
- using RefCounted<AbstractWorker>::deref;
-
- virtual void contextDestroyed() OVERRIDE;
- AbstractWorker(ScriptExecutionContext*);
+ AbstractWorker(ExecutionContext*);
virtual ~AbstractWorker();
protected:
// Helper function that converts a URL to an absolute URL and checks the result for validity.
KURL resolveURL(const String& url, ExceptionState&);
intptr_t asID() const { return reinterpret_cast<intptr_t>(this); }
-
-private:
- virtual void refEventTarget() OVERRIDE { ref(); }
- virtual void derefEventTarget() OVERRIDE { deref(); }
- virtual EventTargetData* eventTargetData() OVERRIDE;
- virtual EventTargetData* ensureEventTargetData() OVERRIDE;
-
- EventTargetData m_eventTargetData;
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/workers/DedicatedWorkerGlobalScope.cpp b/chromium/third_party/WebKit/Source/core/workers/DedicatedWorkerGlobalScope.cpp
index 5585cdf2d2d..0605c011b1d 100644
--- a/chromium/third_party/WebKit/Source/core/workers/DedicatedWorkerGlobalScope.cpp
+++ b/chromium/third_party/WebKit/Source/core/workers/DedicatedWorkerGlobalScope.cpp
@@ -32,7 +32,8 @@
#include "core/workers/DedicatedWorkerGlobalScope.h"
#include "bindings/v8/ExceptionState.h"
-#include "core/page/DOMWindow.h"
+#include "bindings/v8/SerializedScriptValue.h"
+#include "core/frame/DOMWindow.h"
#include "core/workers/DedicatedWorkerThread.h"
#include "core/workers/WorkerClients.h"
#include "core/workers/WorkerObjectProxy.h"
@@ -59,21 +60,21 @@ DedicatedWorkerGlobalScope::~DedicatedWorkerGlobalScope()
const AtomicString& DedicatedWorkerGlobalScope::interfaceName() const
{
- return eventNames().interfaceForDedicatedWorkerGlobalScope;
+ return EventTargetNames::DedicatedWorkerGlobalScope;
}
-void DedicatedWorkerGlobalScope::postMessage(PassRefPtr<SerializedScriptValue> message, const MessagePortArray* ports, ExceptionState& es)
+void DedicatedWorkerGlobalScope::postMessage(PassRefPtr<SerializedScriptValue> message, const MessagePortArray* ports, ExceptionState& exceptionState)
{
// Disentangle the port in preparation for sending it to the remote context.
- OwnPtr<MessagePortChannelArray> channels = MessagePort::disentanglePorts(ports, es);
- if (es.hadException())
+ OwnPtr<MessagePortChannelArray> channels = MessagePort::disentanglePorts(ports, exceptionState);
+ if (exceptionState.hadException())
return;
thread()->workerObjectProxy().postMessageToWorkerObject(message, channels.release());
}
-void DedicatedWorkerGlobalScope::importScripts(const Vector<String>& urls, ExceptionState& es)
+void DedicatedWorkerGlobalScope::importScripts(const Vector<String>& urls, ExceptionState& exceptionState)
{
- Base::importScripts(urls, es);
+ Base::importScripts(urls, exceptionState);
thread()->workerObjectProxy().reportPendingActivity(hasPendingActivity());
}
diff --git a/chromium/third_party/WebKit/Source/core/workers/DedicatedWorkerGlobalScope.h b/chromium/third_party/WebKit/Source/core/workers/DedicatedWorkerGlobalScope.h
index 3aea0000930..1555111e9f3 100644
--- a/chromium/third_party/WebKit/Source/core/workers/DedicatedWorkerGlobalScope.h
+++ b/chromium/third_party/WebKit/Source/core/workers/DedicatedWorkerGlobalScope.h
@@ -32,7 +32,7 @@
#define DedicatedWorkerGlobalScope_h
#include "core/dom/MessagePort.h"
-#include "core/page/ContentSecurityPolicy.h"
+#include "core/frame/ContentSecurityPolicy.h"
#include "core/workers/WorkerGlobalScope.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/workers/DedicatedWorkerThread.h b/chromium/third_party/WebKit/Source/core/workers/DedicatedWorkerThread.h
index 9701929bf8e..c8f44c7b0e4 100644
--- a/chromium/third_party/WebKit/Source/core/workers/DedicatedWorkerThread.h
+++ b/chromium/third_party/WebKit/Source/core/workers/DedicatedWorkerThread.h
@@ -30,7 +30,7 @@
#ifndef DedicatedWorkerThread_h
#define DedicatedWorkerThread_h
-#include "core/page/ContentSecurityPolicy.h"
+#include "core/frame/ContentSecurityPolicy.h"
#include "core/workers/WorkerThread.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/workers/DefaultSharedWorkerRepository.h b/chromium/third_party/WebKit/Source/core/workers/DefaultSharedWorkerRepository.h
deleted file mode 100644
index 6cf1ee1b450..00000000000
--- a/chromium/third_party/WebKit/Source/core/workers/DefaultSharedWorkerRepository.h
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
- * Copyright (C) 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef DefaultSharedWorkerRepository_h
-#define DefaultSharedWorkerRepository_h
-
-#include "core/page/ContentSecurityPolicy.h"
-#include "wtf/Forward.h"
-#include "wtf/HashMap.h"
-#include "wtf/Noncopyable.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/PassRefPtr.h"
-#include "wtf/RefPtr.h"
-#include "wtf/Threading.h"
-#include "wtf/text/StringHash.h"
-
-namespace WebCore {
-
- class Document;
- class ExceptionState;
- class KURL;
- class MessagePortChannel;
- class ScriptExecutionContext;
- class SharedWorker;
- class SharedWorkerProxy;
-
- // Platform-specific implementation of the SharedWorkerRepository static interface.
- class DefaultSharedWorkerRepository {
- WTF_MAKE_NONCOPYABLE(DefaultSharedWorkerRepository); WTF_MAKE_FAST_ALLOCATED;
- public:
- // Invoked once the worker script has been loaded to fire up the worker thread.
- void workerScriptLoaded(SharedWorkerProxy&, const String& userAgent, const String& workerScript, PassOwnPtr<MessagePortChannel>, const String& contentSecurityPolicy, ContentSecurityPolicy::HeaderType);
-
- // Internal implementation of SharedWorkerRepository::connect()
- void connectToWorker(PassRefPtr<SharedWorker>, PassOwnPtr<MessagePortChannel>, const KURL&, const String& name, ExceptionState&);
-
- // Notification that a document has been detached.
- void documentDetached(Document*);
-
- // Removes the passed SharedWorkerProxy from the repository.
- void removeProxy(SharedWorkerProxy*);
-
- bool hasSharedWorkers(Document*);
-
- static DefaultSharedWorkerRepository& instance();
- private:
- DefaultSharedWorkerRepository();
- ~DefaultSharedWorkerRepository();
-
- PassRefPtr<SharedWorkerProxy> getProxy(const String& name, const KURL&);
- // Mutex used to protect internal data structures.
- Mutex m_lock;
-
- // List of shared workers. Expectation is that there will be a limited number of shared workers, and so tracking them in a Vector is more efficient than nested HashMaps.
- typedef Vector<RefPtr<SharedWorkerProxy> > SharedWorkerProxyRepository;
- SharedWorkerProxyRepository m_proxies;
- };
-
-} // namespace WebCore
-
-#endif // DefaultSharedWorkerRepository_h
diff --git a/chromium/third_party/WebKit/Source/core/workers/SharedWorker.cpp b/chromium/third_party/WebKit/Source/core/workers/SharedWorker.cpp
index 484cbe8c844..35dbb17ecad 100644
--- a/chromium/third_party/WebKit/Source/core/workers/SharedWorker.cpp
+++ b/chromium/third_party/WebKit/Source/core/workers/SharedWorker.cpp
@@ -34,50 +34,53 @@
#include "bindings/v8/ExceptionState.h"
#include "core/dom/ExceptionCode.h"
+#include "core/dom/ExecutionContext.h"
#include "core/dom/MessageChannel.h"
#include "core/dom/MessagePort.h"
-#include "core/dom/ScriptExecutionContext.h"
#include "core/inspector/InspectorInstrumentation.h"
-#include "core/page/UseCounter.h"
-#include "core/workers/SharedWorkerRepository.h"
-#include "weborigin/KURL.h"
-#include "weborigin/SecurityOrigin.h"
+#include "core/page/Page.h"
+#include "core/frame/UseCounter.h"
+#include "core/workers/SharedWorkerRepositoryClient.h"
+#include "platform/weborigin/KURL.h"
+#include "platform/weborigin/SecurityOrigin.h"
namespace WebCore {
-inline SharedWorker::SharedWorker(ScriptExecutionContext* context)
+inline SharedWorker::SharedWorker(ExecutionContext* context)
: AbstractWorker(context)
{
ScriptWrappable::init(this);
}
-PassRefPtr<SharedWorker> SharedWorker::create(ScriptExecutionContext* context, const String& url, const String& name, ExceptionState& es)
+PassRefPtr<SharedWorker> SharedWorker::create(ExecutionContext* context, const String& url, const String& name, ExceptionState& exceptionState)
{
ASSERT(isMainThread());
+ ASSERT_WITH_SECURITY_IMPLICATION(context->isDocument());
+
UseCounter::count(toDocument(context)->domWindow(), UseCounter::SharedWorkerStart);
RefPtr<SharedWorker> worker = adoptRef(new SharedWorker(context));
RefPtr<MessageChannel> channel = MessageChannel::create(context);
worker->m_port = channel->port1();
- OwnPtr<MessagePortChannel> remotePort = channel->port2()->disentangle();
+ OwnPtr<blink::WebMessagePortChannel> remotePort = channel->port2()->disentangle();
ASSERT(remotePort);
worker->suspendIfNeeded();
// We don't currently support nested workers, so workers can only be created from documents.
- ASSERT_WITH_SECURITY_IMPLICATION(context->isDocument());
Document* document = toDocument(context);
if (!document->securityOrigin()->canAccessSharedWorkers()) {
- es.throwSecurityError("Failed to create 'SharedWorker': access to shared workers is denied to origin '" + document->securityOrigin()->toString() + "'.");
+ exceptionState.throwSecurityError("Access to shared workers is denied to origin '" + document->securityOrigin()->toString() + "'.");
return 0;
}
- KURL scriptURL = worker->resolveURL(url, es);
+ KURL scriptURL = worker->resolveURL(url, exceptionState);
if (scriptURL.isEmpty())
return 0;
- SharedWorkerRepository::connect(worker.get(), remotePort.release(), scriptURL, name, es);
+ if (document->page() && document->page()->sharedWorkerRepositoryClient())
+ document->page()->sharedWorkerRepositoryClient()->connect(worker.get(), remotePort.release(), scriptURL, name, exceptionState);
return worker.release();
}
@@ -88,7 +91,17 @@ SharedWorker::~SharedWorker()
const AtomicString& SharedWorker::interfaceName() const
{
- return eventNames().interfaceForSharedWorker;
+ return EventTargetNames::SharedWorker;
+}
+
+void SharedWorker::setPreventGC()
+{
+ setPendingActivity(this);
+}
+
+void SharedWorker::unsetPreventGC()
+{
+ unsetPendingActivity(this);
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/workers/SharedWorker.h b/chromium/third_party/WebKit/Source/core/workers/SharedWorker.h
index 6ec75067040..8f7902a6875 100644
--- a/chromium/third_party/WebKit/Source/core/workers/SharedWorker.h
+++ b/chromium/third_party/WebKit/Source/core/workers/SharedWorker.h
@@ -40,15 +40,20 @@ class ExceptionState;
class SharedWorker : public AbstractWorker, public ScriptWrappable {
public:
- static PassRefPtr<SharedWorker> create(ScriptExecutionContext*, const String& url, const String& name, ExceptionState&);
+ static PassRefPtr<SharedWorker> create(ExecutionContext*, const String& url, const String& name, ExceptionState&);
virtual ~SharedWorker();
MessagePort* port() const { return m_port.get(); }
virtual const AtomicString& interfaceName() const OVERRIDE;
+ // Prevents this SharedWorker + JS wrapper from being garbage collected.
+ void setPreventGC();
+ // Allows this SharedWorker + JS wrapper to be garbage collected.
+ void unsetPreventGC();
+
private:
- explicit SharedWorker(ScriptExecutionContext*);
+ explicit SharedWorker(ExecutionContext*);
RefPtr<MessagePort> m_port;
};
diff --git a/chromium/third_party/WebKit/Source/core/workers/SharedWorker.idl b/chromium/third_party/WebKit/Source/core/workers/SharedWorker.idl
index 6bba1302778..b36361efc05 100644
--- a/chromium/third_party/WebKit/Source/core/workers/SharedWorker.idl
+++ b/chromium/third_party/WebKit/Source/core/workers/SharedWorker.idl
@@ -30,14 +30,13 @@
*/
[
- EnabledAtRuntime=SharedWorker,
+ ActiveDOMObject,
Constructor(DOMString scriptURL, [Default=NullString] optional DOMString name),
- ConstructorCallWith=ScriptExecutionContext,
- ConstructorRaisesException,
- ActiveDOMObject
+ ConstructorCallWith=ExecutionContext,
+ RaisesException=Constructor,
+ RuntimeEnabled=SharedWorker,
] interface SharedWorker : EventTarget {
readonly attribute MessagePort port;
};
SharedWorker implements AbstractWorker;
-
diff --git a/chromium/third_party/WebKit/Source/core/workers/SharedWorkerGlobalScope.cpp b/chromium/third_party/WebKit/Source/core/workers/SharedWorkerGlobalScope.cpp
index fde138d65cb..c961699b922 100644
--- a/chromium/third_party/WebKit/Source/core/workers/SharedWorkerGlobalScope.cpp
+++ b/chromium/third_party/WebKit/Source/core/workers/SharedWorkerGlobalScope.cpp
@@ -32,13 +32,12 @@
#include "core/workers/SharedWorkerGlobalScope.h"
-#include "core/dom/EventNames.h"
-#include "core/dom/MessageEvent.h"
+#include "core/events/MessageEvent.h"
+#include "core/events/ThreadLocalEventNames.h"
#include "core/inspector/ScriptCallStack.h"
-#include "core/page/DOMWindow.h"
+#include "core/frame/DOMWindow.h"
#include "core/workers/SharedWorkerThread.h"
#include "core/workers/WorkerClients.h"
-#include "core/workers/WorkerThreadStartupData.h"
#include "wtf/CurrentTime.h"
namespace WebCore {
@@ -47,7 +46,7 @@ PassRefPtr<MessageEvent> createConnectEvent(PassRefPtr<MessagePort> prpPort)
{
RefPtr<MessagePort> port = prpPort;
RefPtr<MessageEvent> event = MessageEvent::create(adoptPtr(new MessagePortArray(1, port)), String(), String(), port);
- event->initEvent(eventNames().connectEvent, false, false);
+ event->initEvent(EventTypeNames::connect, false, false);
return event.release();
}
@@ -72,7 +71,7 @@ SharedWorkerGlobalScope::~SharedWorkerGlobalScope()
const AtomicString& SharedWorkerGlobalScope::interfaceName() const
{
- return eventNames().interfaceForSharedWorkerGlobalScope;
+ return EventTargetNames::SharedWorkerGlobalScope;
}
SharedWorkerThread* SharedWorkerGlobalScope::thread()
diff --git a/chromium/third_party/WebKit/Source/core/workers/SharedWorkerGlobalScope.h b/chromium/third_party/WebKit/Source/core/workers/SharedWorkerGlobalScope.h
index be9107772aa..a87e0a683a0 100644
--- a/chromium/third_party/WebKit/Source/core/workers/SharedWorkerGlobalScope.h
+++ b/chromium/third_party/WebKit/Source/core/workers/SharedWorkerGlobalScope.h
@@ -31,7 +31,7 @@
#ifndef SharedWorkerGlobalScope_h
#define SharedWorkerGlobalScope_h
-#include "core/page/ContentSecurityPolicy.h"
+#include "core/frame/ContentSecurityPolicy.h"
#include "core/workers/WorkerGlobalScope.h"
#include "core/workers/WorkerThreadStartupData.h"
diff --git a/chromium/third_party/WebKit/Source/core/workers/SharedWorkerRepository.h b/chromium/third_party/WebKit/Source/core/workers/SharedWorkerRepository.h
deleted file mode 100644
index 26d15cbf068..00000000000
--- a/chromium/third_party/WebKit/Source/core/workers/SharedWorkerRepository.h
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright (C) 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SharedWorkerRepository_h
-#define SharedWorkerRepository_h
-
-#include "wtf/Forward.h"
-#include "wtf/PassOwnPtr.h"
-#include "wtf/PassRefPtr.h"
-
-namespace WebCore {
-
- class Document;
- class ExceptionState;
- class KURL;
- class MessagePortChannel;
- class SharedWorker;
-
- // Interface to a repository which manages references to the set of active shared workers.
- class SharedWorkerRepository {
- public:
- // Returns true if the platform supports SharedWorkers, otherwise false.
- static bool isAvailable();
-
- // Connects the passed SharedWorker object with the specified worker thread, creating a new thread if necessary.
- static void connect(PassRefPtr<SharedWorker>, PassOwnPtr<MessagePortChannel>, const KURL&, const String& name, ExceptionState&);
-
- // Invoked when a document has been detached.
- static void documentDetached(Document*);
-
- // Returns true if the passed document is associated with any SharedWorkers.
- static bool hasSharedWorkers(Document*);
- private:
- SharedWorkerRepository() { }
- };
-
-} // namespace WebCore
-
-#endif // SharedWorkerRepository_h
diff --git a/chromium/third_party/WebKit/Source/core/workers/SharedWorkerRepositoryClient.h b/chromium/third_party/WebKit/Source/core/workers/SharedWorkerRepositoryClient.h
new file mode 100644
index 00000000000..607bc294264
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/workers/SharedWorkerRepositoryClient.h
@@ -0,0 +1,61 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SharedWorkerRepositoryClient_h
+#define SharedWorkerRepositoryClient_h
+
+#include "wtf/Forward.h"
+#include "wtf/Noncopyable.h"
+
+namespace blink {
+class WebMessagePortChannel;
+}
+
+namespace WebCore {
+
+class Document;
+class ExceptionState;
+class KURL;
+class SharedWorker;
+
+class SharedWorkerRepositoryClient {
+ WTF_MAKE_NONCOPYABLE(SharedWorkerRepositoryClient);
+public:
+ SharedWorkerRepositoryClient() { }
+ virtual ~SharedWorkerRepositoryClient() { }
+
+ virtual void connect(PassRefPtr<SharedWorker>, PassOwnPtr<blink::WebMessagePortChannel>, const KURL&, const String& name, ExceptionState&) = 0;
+
+ virtual void documentDetached(Document*) = 0;
+};
+
+} // namespace WebCore
+
+#endif // SharedWorkerRepositoryClient_h
diff --git a/chromium/third_party/WebKit/Source/core/workers/SharedWorkerThread.h b/chromium/third_party/WebKit/Source/core/workers/SharedWorkerThread.h
index 70a5d0ed51e..ca1f15e7b95 100644
--- a/chromium/third_party/WebKit/Source/core/workers/SharedWorkerThread.h
+++ b/chromium/third_party/WebKit/Source/core/workers/SharedWorkerThread.h
@@ -30,7 +30,7 @@
#ifndef SharedWorkerThread_h
#define SharedWorkerThread_h
-#include "core/page/ContentSecurityPolicy.h"
+#include "core/frame/ContentSecurityPolicy.h"
#include "core/workers/WorkerThread.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/workers/Worker.cpp b/chromium/third_party/WebKit/Source/core/workers/Worker.cpp
index fd19c817aee..cd1d10228e4 100644
--- a/chromium/third_party/WebKit/Source/core/workers/Worker.cpp
+++ b/chromium/third_party/WebKit/Source/core/workers/Worker.cpp
@@ -30,37 +30,40 @@
#include "bindings/v8/ExceptionState.h"
#include "core/dom/Document.h"
-#include "core/dom/EventListener.h"
-#include "core/dom/EventNames.h"
-#include "core/dom/MessageEvent.h"
+#include "core/events/MessageEvent.h"
#include "core/fetch/ResourceFetcher.h"
#include "core/inspector/InspectorInstrumentation.h"
-#include "core/page/DOMWindow.h"
-#include "core/page/UseCounter.h"
+#include "core/frame/DOMWindow.h"
+#include "core/frame/UseCounter.h"
#include "core/workers/WorkerGlobalScopeProxy.h"
+#include "core/workers/WorkerGlobalScopeProxyProvider.h"
#include "core/workers/WorkerScriptLoader.h"
#include "core/workers/WorkerThread.h"
#include "wtf/MainThread.h"
namespace WebCore {
-inline Worker::Worker(ScriptExecutionContext* context)
+inline Worker::Worker(ExecutionContext* context)
: AbstractWorker(context)
- , m_contextProxy(WorkerGlobalScopeProxy::create(this))
+ , m_contextProxy(0)
{
ScriptWrappable::init(this);
}
-PassRefPtr<Worker> Worker::create(ScriptExecutionContext* context, const String& url, ExceptionState& es)
+PassRefPtr<Worker> Worker::create(ExecutionContext* context, const String& url, ExceptionState& exceptionState)
{
ASSERT(isMainThread());
- UseCounter::count(toDocument(context)->domWindow(), UseCounter::WorkerStart);
+ Document* document = toDocument(context);
+ UseCounter::count(document->domWindow(), UseCounter::WorkerStart);
+ ASSERT(document->page());
+ WorkerGlobalScopeProxyProvider* proxyProvider = WorkerGlobalScopeProxyProvider::from(document->page());
+ ASSERT(proxyProvider);
RefPtr<Worker> worker = adoptRef(new Worker(context));
worker->suspendIfNeeded();
- KURL scriptURL = worker->resolveURL(url, es);
+ KURL scriptURL = worker->resolveURL(url, exceptionState);
if (scriptURL.isEmpty())
return 0;
@@ -69,27 +72,28 @@ PassRefPtr<Worker> Worker::create(ScriptExecutionContext* context, const String&
worker->m_scriptLoader = WorkerScriptLoader::create();
worker->m_scriptLoader->loadAsynchronously(context, scriptURL, DenyCrossOriginRequests, worker.get());
-
+ worker->m_contextProxy = proxyProvider->createWorkerGlobalScopeProxy(worker.get());
return worker.release();
}
Worker::~Worker()
{
ASSERT(isMainThread());
- ASSERT(scriptExecutionContext()); // The context is protected by worker context proxy, so it cannot be destroyed while a Worker exists.
- m_contextProxy->workerObjectDestroyed();
+ ASSERT(executionContext()); // The context is protected by worker context proxy, so it cannot be destroyed while a Worker exists.
+ if (m_contextProxy)
+ m_contextProxy->workerObjectDestroyed();
}
const AtomicString& Worker::interfaceName() const
{
- return eventNames().interfaceForWorker;
+ return EventTargetNames::Worker;
}
-void Worker::postMessage(PassRefPtr<SerializedScriptValue> message, const MessagePortArray* ports, ExceptionState& es)
+void Worker::postMessage(PassRefPtr<SerializedScriptValue> message, const MessagePortArray* ports, ExceptionState& exceptionState)
{
// Disentangle the port in preparation for sending it to the remote context.
- OwnPtr<MessagePortChannelArray> channels = MessagePort::disentanglePorts(ports, es);
- if (es.hadException())
+ OwnPtr<MessagePortChannelArray> channels = MessagePort::disentanglePorts(ports, exceptionState);
+ if (exceptionState.hadException())
return;
m_contextProxy->postMessageToWorkerGlobalScope(message, channels.release());
}
@@ -99,12 +103,6 @@ void Worker::terminate()
m_contextProxy->terminateWorkerGlobalScope();
}
-bool Worker::canSuspend() const
-{
- // FIXME: It is not currently possible to suspend a worker, so pages with workers can not go into page cache.
- return false;
-}
-
void Worker::stop()
{
terminate();
@@ -117,19 +115,19 @@ bool Worker::hasPendingActivity() const
void Worker::didReceiveResponse(unsigned long identifier, const ResourceResponse&)
{
- InspectorInstrumentation::didReceiveScriptResponse(scriptExecutionContext(), identifier);
+ InspectorInstrumentation::didReceiveScriptResponse(executionContext(), identifier);
}
void Worker::notifyFinished()
{
if (m_scriptLoader->failed()) {
- dispatchEvent(Event::createCancelable(eventNames().errorEvent));
+ dispatchEvent(Event::createCancelable(EventTypeNames::error));
} else {
WorkerThreadStartMode startMode = DontPauseWorkerGlobalScopeOnStart;
- if (InspectorInstrumentation::shouldPauseDedicatedWorkerOnStart(scriptExecutionContext()))
+ if (InspectorInstrumentation::shouldPauseDedicatedWorkerOnStart(executionContext()))
startMode = PauseWorkerGlobalScopeOnStart;
- m_contextProxy->startWorkerGlobalScope(m_scriptLoader->url(), scriptExecutionContext()->userAgent(m_scriptLoader->url()), m_scriptLoader->script(), startMode);
- InspectorInstrumentation::scriptImported(scriptExecutionContext(), m_scriptLoader->identifier(), m_scriptLoader->script());
+ m_contextProxy->startWorkerGlobalScope(m_scriptLoader->url(), executionContext()->userAgent(m_scriptLoader->url()), m_scriptLoader->script(), startMode);
+ InspectorInstrumentation::scriptImported(executionContext(), m_scriptLoader->identifier(), m_scriptLoader->script());
}
m_scriptLoader = nullptr;
diff --git a/chromium/third_party/WebKit/Source/core/workers/Worker.h b/chromium/third_party/WebKit/Source/core/workers/Worker.h
index 023578a9f21..6271fae48ec 100644
--- a/chromium/third_party/WebKit/Source/core/workers/Worker.h
+++ b/chromium/third_party/WebKit/Source/core/workers/Worker.h
@@ -28,10 +28,10 @@
#define Worker_h
#include "core/dom/ActiveDOMObject.h"
-#include "core/dom/EventListener.h"
-#include "core/dom/EventNames.h"
-#include "core/dom/EventTarget.h"
#include "core/dom/MessagePort.h"
+#include "core/events/EventListener.h"
+#include "core/events/EventTarget.h"
+#include "core/events/ThreadLocalEventNames.h"
#include "core/workers/AbstractWorker.h"
#include "core/workers/WorkerScriptLoaderClient.h"
#include "wtf/Forward.h"
@@ -42,13 +42,13 @@
namespace WebCore {
class ExceptionState;
-class ScriptExecutionContext;
+class ExecutionContext;
class WorkerGlobalScopeProxy;
class WorkerScriptLoader;
class Worker : public AbstractWorker, public ScriptWrappable, private WorkerScriptLoaderClient {
public:
- static PassRefPtr<Worker> create(ScriptExecutionContext*, const String& url, ExceptionState&);
+ static PassRefPtr<Worker> create(ExecutionContext*, const String& url, ExceptionState&);
virtual ~Worker();
virtual const AtomicString& interfaceName() const OVERRIDE;
@@ -57,22 +57,18 @@ public:
void terminate();
- virtual bool canSuspend() const OVERRIDE;
virtual void stop() OVERRIDE;
virtual bool hasPendingActivity() const OVERRIDE;
DEFINE_ATTRIBUTE_EVENT_LISTENER(message);
private:
- explicit Worker(ScriptExecutionContext*);
+ explicit Worker(ExecutionContext*);
// WorkerScriptLoaderClient callbacks
virtual void didReceiveResponse(unsigned long identifier, const ResourceResponse&) OVERRIDE;
virtual void notifyFinished() OVERRIDE;
- virtual void refEventTarget() OVERRIDE { ref(); }
- virtual void derefEventTarget() OVERRIDE { deref(); }
-
RefPtr<WorkerScriptLoader> m_scriptLoader;
WorkerGlobalScopeProxy* m_contextProxy; // The proxy outlives the worker to perform thread shutdown.
};
diff --git a/chromium/third_party/WebKit/Source/core/workers/Worker.idl b/chromium/third_party/WebKit/Source/core/workers/Worker.idl
index 40567a70810..6017569bee9 100644
--- a/chromium/third_party/WebKit/Source/core/workers/Worker.idl
+++ b/chromium/third_party/WebKit/Source/core/workers/Worker.idl
@@ -26,10 +26,10 @@
*/
[
+ ActiveDOMObject,
Constructor(DOMString scriptUrl),
- ConstructorCallWith=ScriptExecutionContext,
- ConstructorRaisesException,
- ActiveDOMObject
+ ConstructorCallWith=ExecutionContext,
+ RaisesException=Constructor,
] interface Worker : EventTarget {
attribute EventHandler onmessage;
@@ -39,4 +39,3 @@
};
Worker implements AbstractWorker;
-
diff --git a/chromium/third_party/WebKit/Source/core/workers/WorkerClients.h b/chromium/third_party/WebKit/Source/core/workers/WorkerClients.h
index b362662a0aa..8cc4aa2ff55 100644
--- a/chromium/third_party/WebKit/Source/core/workers/WorkerClients.h
+++ b/chromium/third_party/WebKit/Source/core/workers/WorkerClients.h
@@ -31,7 +31,7 @@
#ifndef WorkerClients_h
#define WorkerClients_h
-#include "core/platform/Supplementable.h"
+#include "platform/Supplementable.h"
#include "wtf/Forward.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/workers/WorkerConsole.cpp b/chromium/third_party/WebKit/Source/core/workers/WorkerConsole.cpp
index e3b34b924cf..f4a819e4dd0 100644
--- a/chromium/third_party/WebKit/Source/core/workers/WorkerConsole.cpp
+++ b/chromium/third_party/WebKit/Source/core/workers/WorkerConsole.cpp
@@ -31,22 +31,11 @@
#include "core/workers/WorkerConsole.h"
-#include "bindings/v8/ScriptCallStackFactory.h"
-#include "bindings/v8/ScriptProfiler.h"
-#include "core/inspector/ConsoleAPITypes.h"
-#include "core/inspector/InspectorConsoleInstrumentation.h"
-#include "core/inspector/ScriptArguments.h"
#include "core/inspector/ScriptCallStack.h"
-#include "core/inspector/ScriptProfile.h"
-#include "core/inspector/WorkerInspectorController.h"
-#include "core/page/ConsoleBase.h"
-#include "core/page/ConsoleTypes.h"
-#include "core/platform/chromium/TraceEvent.h"
#include "core/workers/WorkerGlobalScope.h"
#include "core/workers/WorkerReportingProxy.h"
#include "core/workers/WorkerThread.h"
-#include "wtf/text/WTFString.h"
namespace WebCore {
@@ -63,22 +52,16 @@ WorkerConsole::~WorkerConsole()
void WorkerConsole::reportMessageToClient(MessageLevel level, const String& message, PassRefPtr<ScriptCallStack> callStack)
{
const ScriptCallFrame& lastCaller = callStack->at(0);
- m_scope->thread()->workerReportingProxy().postConsoleMessageToWorkerObject(ConsoleAPIMessageSource, level, message, lastCaller.lineNumber(), lastCaller.sourceURL());
+ m_scope->thread()->workerReportingProxy().reportConsoleMessage(ConsoleAPIMessageSource, level, message, lastCaller.lineNumber(), lastCaller.sourceURL());
}
-ScriptExecutionContext* WorkerConsole::context()
+ExecutionContext* WorkerConsole::context()
{
if (!m_scope)
return 0;
- return m_scope->scriptExecutionContext();
-}
-
-bool WorkerConsole::profilerEnabled()
-{
- return InspectorInstrumentation::profilerEnabled(m_scope);
+ return m_scope->executionContext();
}
// FIXME: add memory getter
} // namespace WebCore
-
diff --git a/chromium/third_party/WebKit/Source/core/workers/WorkerConsole.h b/chromium/third_party/WebKit/Source/core/workers/WorkerConsole.h
index b5b82630cec..8d51b99c30c 100644
--- a/chromium/third_party/WebKit/Source/core/workers/WorkerConsole.h
+++ b/chromium/third_party/WebKit/Source/core/workers/WorkerConsole.h
@@ -30,11 +30,10 @@
#ifndef WorkerConsole_h
#define WorkerConsole_h
-#include "bindings/v8/ScriptState.h"
#include "bindings/v8/ScriptWrappable.h"
#include "core/inspector/ConsoleAPITypes.h"
-#include "core/page/ConsoleBase.h"
-#include "core/page/ConsoleTypes.h"
+#include "core/frame/ConsoleBase.h"
+#include "core/frame/ConsoleTypes.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefCounted.h"
#include "wtf/RefPtr.h"
@@ -53,9 +52,8 @@ public:
virtual ~WorkerConsole();
protected:
- virtual ScriptExecutionContext* context();
+ virtual ExecutionContext* context();
virtual void reportMessageToClient(MessageLevel, const String& message, PassRefPtr<ScriptCallStack>) OVERRIDE;
- virtual bool profilerEnabled();
private:
explicit WorkerConsole(WorkerGlobalScope*);
diff --git a/chromium/third_party/WebKit/Source/core/workers/WorkerEventQueue.cpp b/chromium/third_party/WebKit/Source/core/workers/WorkerEventQueue.cpp
index fef5b697e7b..6e9d01fde74 100644
--- a/chromium/third_party/WebKit/Source/core/workers/WorkerEventQueue.cpp
+++ b/chromium/third_party/WebKit/Source/core/workers/WorkerEventQueue.cpp
@@ -27,18 +27,19 @@
#include "config.h"
#include "core/workers/WorkerEventQueue.h"
-#include "core/dom/Event.h"
-#include "core/dom/ScriptExecutionContext.h"
+#include "core/dom/ExecutionContext.h"
+#include "core/dom/ExecutionContextTask.h"
+#include "core/events/Event.h"
namespace WebCore {
-PassOwnPtr<WorkerEventQueue> WorkerEventQueue::create(ScriptExecutionContext* context)
+PassOwnPtr<WorkerEventQueue> WorkerEventQueue::create(ExecutionContext* context)
{
return adoptPtr(new WorkerEventQueue(context));
}
-WorkerEventQueue::WorkerEventQueue(ScriptExecutionContext* context)
- : m_scriptExecutionContext(context)
+WorkerEventQueue::WorkerEventQueue(ExecutionContext* context)
+ : m_executionContext(context)
, m_isClosed(false)
{
}
@@ -48,7 +49,7 @@ WorkerEventQueue::~WorkerEventQueue()
close();
}
-class WorkerEventQueue::EventDispatcherTask : public ScriptExecutionContext::Task {
+class WorkerEventQueue::EventDispatcherTask : public ExecutionContextTask {
public:
static PassOwnPtr<EventDispatcherTask> create(PassRefPtr<Event> event, WorkerEventQueue* eventQueue)
{
@@ -61,12 +62,12 @@ public:
m_eventQueue->removeEvent(m_event.get());
}
- void dispatchEvent(ScriptExecutionContext*, PassRefPtr<Event> event)
+ void dispatchEvent(ExecutionContext*, PassRefPtr<Event> event)
{
event->target()->dispatchEvent(event);
}
- virtual void performTask(ScriptExecutionContext* context)
+ virtual void performTask(ExecutionContext* context)
{
if (m_isCancelled)
return;
@@ -106,7 +107,7 @@ bool WorkerEventQueue::enqueueEvent(PassRefPtr<Event> prpEvent)
RefPtr<Event> event = prpEvent;
OwnPtr<EventDispatcherTask> task = EventDispatcherTask::create(event, this);
m_eventTaskMap.add(event.release(), task.get());
- m_scriptExecutionContext->postTask(task.release());
+ m_executionContext->postTask(task.release());
return true;
}
diff --git a/chromium/third_party/WebKit/Source/core/workers/WorkerEventQueue.h b/chromium/third_party/WebKit/Source/core/workers/WorkerEventQueue.h
index fda0b93eed9..6a669019fd6 100644
--- a/chromium/third_party/WebKit/Source/core/workers/WorkerEventQueue.h
+++ b/chromium/third_party/WebKit/Source/core/workers/WorkerEventQueue.h
@@ -27,7 +27,7 @@
#ifndef WorkerEventQueue_h
#define WorkerEventQueue_h
-#include "core/dom/EventQueue.h"
+#include "core/events/EventQueue.h"
#include "wtf/HashMap.h"
#include "wtf/HashSet.h"
#include "wtf/PassOwnPtr.h"
@@ -37,13 +37,13 @@ namespace WebCore {
class Event;
class Node;
-class ScriptExecutionContext;
+class ExecutionContext;
class WorkerEventQueue : public EventQueue {
WTF_MAKE_FAST_ALLOCATED;
public:
- static PassOwnPtr<WorkerEventQueue> create(ScriptExecutionContext*);
+ static PassOwnPtr<WorkerEventQueue> create(ExecutionContext*);
virtual ~WorkerEventQueue();
// EventQueue
@@ -52,10 +52,10 @@ public:
virtual void close() OVERRIDE;
private:
- explicit WorkerEventQueue(ScriptExecutionContext*);
+ explicit WorkerEventQueue(ExecutionContext*);
void removeEvent(Event*);
- ScriptExecutionContext* m_scriptExecutionContext;
+ ExecutionContext* m_executionContext;
bool m_isClosed;
class EventDispatcherTask;
diff --git a/chromium/third_party/WebKit/Source/core/workers/WorkerGlobalScope.cpp b/chromium/third_party/WebKit/Source/core/workers/WorkerGlobalScope.cpp
index e7dc7d830b3..cd8daa3ef8a 100644
--- a/chromium/third_party/WebKit/Source/core/workers/WorkerGlobalScope.cpp
+++ b/chromium/third_party/WebKit/Source/core/workers/WorkerGlobalScope.cpp
@@ -33,40 +33,37 @@
#include "bindings/v8/ScriptSourceCode.h"
#include "bindings/v8/ScriptValue.h"
#include "core/dom/ActiveDOMObject.h"
+#include "core/dom/AddConsoleMessageTask.h"
#include "core/dom/ContextLifecycleNotifier.h"
-#include "core/dom/ErrorEvent.h"
-#include "core/dom/Event.h"
+#include "core/dom/DOMURL.h"
#include "core/dom/ExceptionCode.h"
#include "core/dom/MessagePort.h"
-#include "core/html/DOMURL.h"
+#include "core/events/ErrorEvent.h"
+#include "core/events/Event.h"
#include "core/inspector/InspectorConsoleInstrumentation.h"
#include "core/inspector/ScriptCallStack.h"
#include "core/inspector/WorkerInspectorController.h"
#include "core/loader/WorkerThreadableLoader.h"
-#include "core/page/ContentSecurityPolicy.h"
-#include "core/page/DOMWindow.h"
-#include "core/page/WorkerNavigator.h"
-#include "core/platform/NotImplemented.h"
+#include "core/frame/DOMWindow.h"
+#include "core/workers/WorkerNavigator.h"
#include "core/workers/WorkerClients.h"
#include "core/workers/WorkerLocation.h"
-#include "core/workers/WorkerObjectProxy.h"
+#include "core/workers/WorkerReportingProxy.h"
#include "core/workers/WorkerScriptLoader.h"
#include "core/workers/WorkerThread.h"
-#include "weborigin/KURL.h"
-#include "weborigin/SecurityOrigin.h"
-#include "wtf/RefPtr.h"
-#include "wtf/UnusedParam.h"
+#include "platform/weborigin/KURL.h"
+#include "platform/weborigin/SecurityOrigin.h"
namespace WebCore {
-class CloseWorkerGlobalScopeTask : public ScriptExecutionContext::Task {
+class CloseWorkerGlobalScopeTask : public ExecutionContextTask {
public:
static PassOwnPtr<CloseWorkerGlobalScopeTask> create()
{
return adoptPtr(new CloseWorkerGlobalScopeTask);
}
- virtual void performTask(ScriptExecutionContext *context)
+ virtual void performTask(ExecutionContext *context)
{
WorkerGlobalScope* workerGlobalScope = toWorkerGlobalScope(context);
// Notify parent that this context is closed. Parent is responsible for calling WorkerThread::stop().
@@ -79,17 +76,21 @@ public:
WorkerGlobalScope::WorkerGlobalScope(const KURL& url, const String& userAgent, WorkerThread* thread, double timeOrigin, PassOwnPtr<WorkerClients> workerClients)
: m_url(url)
, m_userAgent(userAgent)
- , m_script(adoptPtr(new WorkerScriptController(this)))
+ , m_script(adoptPtr(new WorkerScriptController(*this)))
, m_thread(thread)
, m_workerInspectorController(adoptPtr(new WorkerInspectorController(this)))
, m_closing(false)
, m_eventQueue(WorkerEventQueue::create(this))
- , m_timeOrigin(timeOrigin)
, m_workerClients(workerClients)
+ , m_timeOrigin(timeOrigin)
{
ScriptWrappable::init(this);
+ setClient(this);
setSecurityOrigin(SecurityOrigin::create(url));
m_workerClients->reattachThread();
+
+ // Notify proxy that a new WorkerGlobalScope has been created and started.
+ this->thread()->workerReportingProxy().workerGlobalScopeStarted();
}
WorkerGlobalScope::~WorkerGlobalScope()
@@ -101,6 +102,8 @@ WorkerGlobalScope::~WorkerGlobalScope()
// Notify proxy that we are going away. This can free the WorkerThread object, so do not access it after this.
thread()->workerReportingProxy().workerGlobalScopeDestroyed();
+
+ setClient(0);
}
void WorkerGlobalScope::applyContentSecurityPolicyFromString(const String& policy, ContentSecurityPolicy::HeaderType contentSecurityPolicyType)
@@ -109,7 +112,7 @@ void WorkerGlobalScope::applyContentSecurityPolicyFromString(const String& polic
contentSecurityPolicy()->didReceiveHeader(policy, contentSecurityPolicyType);
}
-ScriptExecutionContext* WorkerGlobalScope::scriptExecutionContext() const
+ExecutionContext* WorkerGlobalScope::executionContext() const
{
return const_cast<WorkerGlobalScope*>(this);
}
@@ -144,6 +147,11 @@ void WorkerGlobalScope::disableEval(const String& errorMessage)
m_script->disableEval(errorMessage);
}
+double WorkerGlobalScope::timerAlignmentInterval() const
+{
+ return DOMTimer::visiblePageAlignmentInterval();
+}
+
WorkerLocation* WorkerGlobalScope::location() const
{
if (!m_location)
@@ -177,7 +185,7 @@ WorkerNavigator* WorkerGlobalScope::navigator() const
return m_navigator.get();
}
-void WorkerGlobalScope::postTask(PassOwnPtr<Task> task)
+void WorkerGlobalScope::postTask(PassOwnPtr<ExecutionContextTask> task)
{
thread()->runLoop().postTask(task);
}
@@ -187,15 +195,15 @@ void WorkerGlobalScope::clearInspector()
m_workerInspectorController.clear();
}
-void WorkerGlobalScope::importScripts(const Vector<String>& urls, ExceptionState& es)
+void WorkerGlobalScope::importScripts(const Vector<String>& urls, ExceptionState& exceptionState)
{
ASSERT(contentSecurityPolicy());
Vector<String>::const_iterator urlsEnd = urls.end();
Vector<KURL> completedURLs;
for (Vector<String>::const_iterator it = urls.begin(); it != urlsEnd; ++it) {
- const KURL& url = scriptExecutionContext()->completeURL(*it);
+ const KURL& url = executionContext()->completeURL(*it);
if (!url.isValid()) {
- es.throwDOMException(SyntaxError, "Failed to execute 'importScripts': the URL '" + *it + "' is invalid.");
+ exceptionState.throwDOMException(SyntaxError, "The URL '" + *it + "' is invalid.");
return;
}
completedURLs.append(url);
@@ -205,15 +213,15 @@ void WorkerGlobalScope::importScripts(const Vector<String>& urls, ExceptionState
for (Vector<KURL>::const_iterator it = completedURLs.begin(); it != end; ++it) {
RefPtr<WorkerScriptLoader> scriptLoader(WorkerScriptLoader::create());
scriptLoader->setTargetType(ResourceRequest::TargetIsScript);
- scriptLoader->loadSynchronously(scriptExecutionContext(), *it, AllowCrossOriginRequests);
+ scriptLoader->loadSynchronously(executionContext(), *it, AllowCrossOriginRequests);
// If the fetching attempt failed, throw a NetworkError exception and abort all these steps.
if (scriptLoader->failed()) {
- es.throwDOMException(NetworkError, "Failed to execute 'importScripts': the script at '" + it->elidedString() + "' failed to load.");
+ exceptionState.throwDOMException(NetworkError, "The script at '" + it->elidedString() + "' failed to load.");
return;
}
- InspectorInstrumentation::scriptImported(scriptExecutionContext(), scriptLoader->identifier(), scriptLoader->script());
+ InspectorInstrumentation::scriptImported(executionContext(), scriptLoader->identifier(), scriptLoader->script());
RefPtr<ErrorEvent> errorEvent;
m_script->evaluate(ScriptSourceCode(scriptLoader->script(), scriptLoader->responseURL()), &errorEvent);
@@ -231,7 +239,12 @@ EventTarget* WorkerGlobalScope::errorEventTarget()
void WorkerGlobalScope::logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, int columnNumber, PassRefPtr<ScriptCallStack>)
{
- thread()->workerReportingProxy().postExceptionToWorkerObject(errorMessage, lineNumber, columnNumber, sourceURL);
+ thread()->workerReportingProxy().reportException(errorMessage, lineNumber, columnNumber, sourceURL);
+}
+
+void WorkerGlobalScope::reportBlockedScriptExecutionToInspector(const String& directiveText)
+{
+ InspectorInstrumentation::scriptExecutionBlockedByCSP(this, directiveText);
}
void WorkerGlobalScope::addMessage(MessageSource source, MessageLevel level, const String& message, const String& sourceURL, unsigned lineNumber, ScriptState* state)
@@ -240,7 +253,7 @@ void WorkerGlobalScope::addMessage(MessageSource source, MessageLevel level, con
postTask(AddConsoleMessageTask::create(source, level, message));
return;
}
- thread()->workerReportingProxy().postConsoleMessageToWorkerObject(source, level, message, lineNumber, sourceURL);
+ thread()->workerReportingProxy().reportConsoleMessage(source, level, message, lineNumber, sourceURL);
addMessageToWorkerConsole(source, level, message, sourceURL, lineNumber, 0, state);
}
@@ -263,16 +276,6 @@ bool WorkerGlobalScope::isJSExecutionForbidden() const
return m_script->isExecutionForbidden();
}
-EventTargetData* WorkerGlobalScope::eventTargetData()
-{
- return &m_eventTargetData;
-}
-
-EventTargetData* WorkerGlobalScope::ensureEventTargetData()
-{
- return &m_eventTargetData;
-}
-
WorkerGlobalScope::Observer::Observer(WorkerGlobalScope* context)
: m_context(context)
{
diff --git a/chromium/third_party/WebKit/Source/core/workers/WorkerGlobalScope.h b/chromium/third_party/WebKit/Source/core/workers/WorkerGlobalScope.h
index 1aca7bb3f40..8bbc43e3c64 100644
--- a/chromium/third_party/WebKit/Source/core/workers/WorkerGlobalScope.h
+++ b/chromium/third_party/WebKit/Source/core/workers/WorkerGlobalScope.h
@@ -29,13 +29,14 @@
#include "bindings/v8/ScriptWrappable.h"
#include "bindings/v8/WorkerScriptController.h"
-#include "core/dom/EventListener.h"
-#include "core/dom/EventNames.h"
-#include "core/dom/EventTarget.h"
-#include "core/dom/ScriptExecutionContext.h"
-#include "core/page/ContentSecurityPolicy.h"
+#include "core/dom/ExecutionContext.h"
+#include "core/events/EventListener.h"
+#include "core/events/EventTarget.h"
+#include "core/events/ThreadLocalEventNames.h"
+#include "core/frame/ContentSecurityPolicy.h"
#include "core/workers/WorkerConsole.h"
#include "core/workers/WorkerEventQueue.h"
+#include "core/workers/WorkerSupplementable.h"
#include "wtf/Assertions.h"
#include "wtf/HashMap.h"
#include "wtf/OwnPtr.h"
@@ -57,22 +58,23 @@ namespace WebCore {
class WorkerNavigator;
class WorkerThread;
- class WorkerGlobalScope : public RefCounted<WorkerGlobalScope>, public ScriptWrappable, public ScriptExecutionContext, public EventTarget {
+ class WorkerGlobalScope : public RefCounted<WorkerGlobalScope>, public ScriptWrappable, public SecurityContext, public ExecutionContext, public ExecutionContextClient, public WorkerSupplementable, public EventTargetWithInlineData {
+ REFCOUNTED_EVENT_TARGET(WorkerGlobalScope);
public:
virtual ~WorkerGlobalScope();
virtual bool isWorkerGlobalScope() const OVERRIDE { return true; }
- virtual ScriptExecutionContext* scriptExecutionContext() const OVERRIDE;
+ virtual ExecutionContext* executionContext() const OVERRIDE;
virtual bool isSharedWorkerGlobalScope() const { return false; }
virtual bool isDedicatedWorkerGlobalScope() const { return false; }
+ virtual bool isServiceWorkerGlobalScope() const { return false; }
const KURL& url() const { return m_url; }
KURL completeURL(const String&) const;
virtual String userAgent(const KURL&) const;
-
virtual void disableEval(const String& errorMessage) OVERRIDE;
WorkerScriptController* script() { return m_script.get(); }
@@ -81,7 +83,7 @@ namespace WebCore {
WorkerThread* thread() const { return m_thread; }
- virtual void postTask(PassOwnPtr<Task>) OVERRIDE; // Executes the task on context's thread asynchronously.
+ virtual void postTask(PassOwnPtr<ExecutionContextTask>) OVERRIDE; // Executes the task on context's thread asynchronously.
// WorkerGlobalScope
WorkerGlobalScope* self() { return this; }
@@ -95,12 +97,15 @@ namespace WebCore {
virtual void importScripts(const Vector<String>& urls, ExceptionState&);
WorkerNavigator* navigator() const;
- // ScriptExecutionContext
+ // ExecutionContextClient
virtual WorkerEventQueue* eventQueue() const OVERRIDE;
+ virtual SecurityContext& securityContext() OVERRIDE { return *this; }
virtual bool isContextThread() const OVERRIDE;
virtual bool isJSExecutionForbidden() const OVERRIDE;
+ virtual double timerAlignmentInterval() const OVERRIDE;
+
WorkerInspectorController* workerInspectorController() { return m_workerInspectorController.get(); }
// These methods are used for GC marking. See JSWorkerGlobalScope::visitChildrenVirtual(SlotVisitor&) in
// JSWorkerGlobalScopeCustom.cpp.
@@ -108,9 +113,6 @@ namespace WebCore {
WorkerNavigator* optionalNavigator() const { return m_navigator.get(); }
WorkerLocation* optionalLocation() const { return m_location.get(); }
- using RefCounted<WorkerGlobalScope>::ref;
- using RefCounted<WorkerGlobalScope>::deref;
-
bool isClosing() { return m_closing; }
// An observer interface to be notified when the worker thread is getting stopped.
@@ -135,6 +137,9 @@ namespace WebCore {
WorkerClients* clients() { return m_workerClients.get(); }
+ using SecurityContext::securityOrigin;
+ using SecurityContext::contentSecurityPolicy;
+
protected:
WorkerGlobalScope(const KURL&, const String& userAgent, WorkerThread*, double timeOrigin, PassOwnPtr<WorkerClients>);
void applyContentSecurityPolicyFromString(const String& contentSecurityPolicy, ContentSecurityPolicy::HeaderType);
@@ -143,20 +148,17 @@ namespace WebCore {
void addMessageToWorkerConsole(MessageSource, MessageLevel, const String& message, const String& sourceURL, unsigned lineNumber, PassRefPtr<ScriptCallStack>, ScriptState*);
private:
- virtual void refScriptExecutionContext() OVERRIDE { ref(); }
- virtual void derefScriptExecutionContext() OVERRIDE { deref(); }
-
- virtual void refEventTarget() OVERRIDE { ref(); }
- virtual void derefEventTarget() OVERRIDE { deref(); }
- virtual EventTargetData* eventTargetData() OVERRIDE;
- virtual EventTargetData* ensureEventTargetData() OVERRIDE;
+ virtual void refExecutionContext() OVERRIDE { ref(); }
+ virtual void derefExecutionContext() OVERRIDE { deref(); }
virtual const KURL& virtualURL() const OVERRIDE;
virtual KURL virtualCompleteURL(const String&) const;
+ virtual void reportBlockedScriptExecutionToInspector(const String& directiveText) OVERRIDE;
virtual void addMessage(MessageSource, MessageLevel, const String& message, const String& sourceURL, unsigned lineNumber, ScriptState* = 0) OVERRIDE;
virtual EventTarget* errorEventTarget() OVERRIDE;
+ virtual void didUpdateSecurityOrigin() OVERRIDE { }
KURL m_url;
String m_userAgent;
@@ -171,7 +173,6 @@ namespace WebCore {
mutable RefPtr<DOMURL> m_domURL;
OwnPtr<WorkerInspectorController> m_workerInspectorController;
bool m_closing;
- EventTargetData m_eventTargetData;
HashSet<Observer*> m_workerObservers;
@@ -182,11 +183,7 @@ namespace WebCore {
double m_timeOrigin;
};
-inline WorkerGlobalScope* toWorkerGlobalScope(ScriptExecutionContext* context)
-{
- ASSERT_WITH_SECURITY_IMPLICATION(!context || context->isWorkerGlobalScope());
- return static_cast<WorkerGlobalScope*>(context);
-}
+DEFINE_TYPE_CASTS(WorkerGlobalScope, ExecutionContext, context, context->isWorkerGlobalScope(), context.isWorkerGlobalScope());
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/workers/WorkerGlobalScope.idl b/chromium/third_party/WebKit/Source/core/workers/WorkerGlobalScope.idl
index 0d67095ada3..d61d48f19d0 100644
--- a/chromium/third_party/WebKit/Source/core/workers/WorkerGlobalScope.idl
+++ b/chromium/third_party/WebKit/Source/core/workers/WorkerGlobalScope.idl
@@ -25,9 +25,8 @@
*/
[
+ Custom=ToV8,
GlobalContext=WorkerGlobalScope,
- CustomToV8,
- DoNotGenerateWrap
] interface WorkerGlobalScope : EventTarget {
// WorkerGlobalScope
diff --git a/chromium/third_party/WebKit/Source/core/workers/WorkerGlobalScopeProxy.cpp b/chromium/third_party/WebKit/Source/core/workers/WorkerGlobalScopeProxy.cpp
deleted file mode 100644
index 06471bb88f2..00000000000
--- a/chromium/third_party/WebKit/Source/core/workers/WorkerGlobalScopeProxy.cpp
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- * * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- * * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/workers/WorkerGlobalScopeProxy.h"
-
-namespace WebCore {
-
-WorkerGlobalScopeProxy::CreateDelegate* WorkerGlobalScopeProxy::s_createDelegate = 0;
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/workers/WorkerGlobalScopeProxy.h b/chromium/third_party/WebKit/Source/core/workers/WorkerGlobalScopeProxy.h
index 67ffca3e1d1..f6adc53ce80 100644
--- a/chromium/third_party/WebKit/Source/core/workers/WorkerGlobalScopeProxy.h
+++ b/chromium/third_party/WebKit/Source/core/workers/WorkerGlobalScopeProxy.h
@@ -44,13 +44,6 @@ namespace WebCore {
// A proxy to talk to the worker global scope.
class WorkerGlobalScopeProxy {
public:
- typedef WorkerGlobalScopeProxy* CreateDelegate(Worker*);
-
- // FIXME: Instead of delegating through a static factory function we
- // should probably go through some client interface like ChromeClient.
- static WorkerGlobalScopeProxy* create(Worker* worker) { return s_createDelegate(worker); }
- static void setCreateDelegate(CreateDelegate* delegate) { s_createDelegate = delegate; }
-
virtual ~WorkerGlobalScopeProxy() { }
virtual void startWorkerGlobalScope(const KURL& scriptURL, const String& userAgent, const String& sourceCode, WorkerThreadStartMode) = 0;
@@ -71,9 +64,6 @@ namespace WebCore {
virtual void connectToInspector(PageInspector*) { }
virtual void disconnectFromInspector() { }
virtual void sendMessageToInspector(const String&) { }
-
- private:
- static CreateDelegate* s_createDelegate;
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/workers/WorkerGlobalScopeProxyProvider.cpp b/chromium/third_party/WebKit/Source/core/workers/WorkerGlobalScopeProxyProvider.cpp
new file mode 100644
index 00000000000..3a539dfcfe1
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/workers/WorkerGlobalScopeProxyProvider.cpp
@@ -0,0 +1,51 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "WorkerGlobalScopeProxyProvider.h"
+
+namespace WebCore {
+
+WorkerGlobalScopeProxyProvider* WorkerGlobalScopeProxyProvider::from(Page* page)
+{
+ return static_cast<WorkerGlobalScopeProxyProvider*>(Supplement<Page>::from(page, supplementName()));
+}
+
+const char* WorkerGlobalScopeProxyProvider::supplementName()
+{
+ return "WorkerGlobalScopeProxyProvider";
+}
+
+void provideWorkerGlobalScopeProxyProviderTo(Page* page, PassOwnPtr<WorkerGlobalScopeProxyProvider> provider)
+{
+ Supplement<Page>::provideTo(page, WorkerGlobalScopeProxyProvider::supplementName(), provider);
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/workers/WorkerGlobalScopeProxyProvider.h b/chromium/third_party/WebKit/Source/core/workers/WorkerGlobalScopeProxyProvider.h
new file mode 100644
index 00000000000..54b5f47ab0d
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/workers/WorkerGlobalScopeProxyProvider.h
@@ -0,0 +1,61 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef WorkerGlobalScopeProxyProvider_h
+#define WorkerGlobalScopeProxyProvider_h
+
+#include "core/page/Page.h"
+#include "platform/Supplementable.h"
+#include "wtf/Forward.h"
+#include "wtf/Noncopyable.h"
+
+
+namespace WebCore {
+
+class WorkerGlobalScopeProxy;
+class Worker;
+
+class WorkerGlobalScopeProxyProvider : public Supplement<Page> {
+ WTF_MAKE_NONCOPYABLE(WorkerGlobalScopeProxyProvider);
+public:
+ WorkerGlobalScopeProxyProvider() { }
+ virtual ~WorkerGlobalScopeProxyProvider() { }
+
+ virtual WorkerGlobalScopeProxy* createWorkerGlobalScopeProxy(Worker*) = 0;
+
+ static WorkerGlobalScopeProxyProvider* from(Page*);
+ static const char* supplementName();
+};
+
+void provideWorkerGlobalScopeProxyProviderTo(Page*, PassOwnPtr<WorkerGlobalScopeProxyProvider>);
+
+} // namespace WebCore
+
+#endif // WorkerGlobalScopeProxyProvider_h
diff --git a/chromium/third_party/WebKit/Source/core/workers/WorkerLoaderProxy.h b/chromium/third_party/WebKit/Source/core/workers/WorkerLoaderProxy.h
index f3eed8dc807..4cb40028fc6 100644
--- a/chromium/third_party/WebKit/Source/core/workers/WorkerLoaderProxy.h
+++ b/chromium/third_party/WebKit/Source/core/workers/WorkerLoaderProxy.h
@@ -31,14 +31,10 @@
#ifndef WorkerLoaderProxy_h
#define WorkerLoaderProxy_h
-#include "core/dom/ScriptExecutionContext.h"
+#include "core/dom/ExecutionContext.h"
#include "wtf/Forward.h"
#include "wtf/PassOwnPtr.h"
-namespace WebKit {
-class WebWorkerBase;
-}
-
namespace WebCore {
// A proxy to talk to the loader context. Normally, the document on the main thread
@@ -51,15 +47,12 @@ namespace WebCore {
virtual ~WorkerLoaderProxy() { }
// Posts a task to the thread which runs the loading code (normally, the main thread).
- virtual void postTaskToLoader(PassOwnPtr<ScriptExecutionContext::Task>) = 0;
+ virtual void postTaskToLoader(PassOwnPtr<ExecutionContextTask>) = 0;
// Posts callbacks from loading code to the WorkerGlobalScope. The 'mode' is used to differentiate
// specific synchronous loading requests so they can be 'nested', per spec.
// Returns true if the task was posted successfully.
- virtual bool postTaskForModeToWorkerGlobalScope(PassOwnPtr<ScriptExecutionContext::Task>, const String& mode) = 0;
-
- // Spans divergent class hierarchies for dedicated and shared workers.
- virtual WebKit::WebWorkerBase* toWebWorkerBase() = 0;
+ virtual bool postTaskForModeToWorkerGlobalScope(PassOwnPtr<ExecutionContextTask>, const String& mode) = 0;
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/workers/WorkerLocation.cpp b/chromium/third_party/WebKit/Source/core/workers/WorkerLocation.cpp
deleted file mode 100644
index c93e8d1be15..00000000000
--- a/chromium/third_party/WebKit/Source/core/workers/WorkerLocation.cpp
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * Copyright (C) 2008 Apple Inc. All Rights Reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-#include "config.h"
-#include "core/workers/WorkerLocation.h"
-
-#include "wtf/text/WTFString.h"
-
-namespace WebCore {
-
-String WorkerLocation::href() const
-{
- return m_url.string();
-}
-
-String WorkerLocation::protocol() const
-{
- return m_url.protocol() + ":";
-}
-
-String WorkerLocation::host() const
-{
- return m_url.port() ? m_url.host() + ":" + String::number(m_url.port()) : m_url.host();
-}
-
-String WorkerLocation::hostname() const
-{
- return m_url.host();
-}
-
-String WorkerLocation::port() const
-{
- return m_url.port() ? String::number(m_url.port()) : "";
-}
-
-String WorkerLocation::pathname() const
-{
- return m_url.path().isEmpty() ? "/" : m_url.path();
-}
-
-String WorkerLocation::search() const
-{
- return m_url.query().isEmpty() ? emptyString() : "?" + m_url.query();
-}
-
-String WorkerLocation::hash() const
-{
- return m_url.fragmentIdentifier().isEmpty() ? emptyString() : "#" + m_url.fragmentIdentifier();
-}
-
-
-} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/workers/WorkerLocation.h b/chromium/third_party/WebKit/Source/core/workers/WorkerLocation.h
index 420338a06d4..6b5aefb7cf7 100644
--- a/chromium/third_party/WebKit/Source/core/workers/WorkerLocation.h
+++ b/chromium/third_party/WebKit/Source/core/workers/WorkerLocation.h
@@ -28,7 +28,8 @@
#define WorkerLocation_h
#include "bindings/v8/ScriptWrappable.h"
-#include "weborigin/KURL.h"
+#include "core/dom/DOMURLUtilsReadOnly.h"
+#include "platform/weborigin/KURL.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefCounted.h"
#include "wtf/RefPtr.h"
@@ -36,27 +37,19 @@
namespace WebCore {
-class WorkerLocation : public RefCounted<WorkerLocation>, public ScriptWrappable {
+class WorkerLocation FINAL : public RefCounted<WorkerLocation>, public ScriptWrappable, public DOMURLUtilsReadOnly {
public:
static PassRefPtr<WorkerLocation> create(const KURL& url)
{
return adoptRef(new WorkerLocation(url));
}
- const KURL& url() const { return m_url; }
-
- String href() const;
-
- // URI decomposition attributes
- String protocol() const;
- String host() const;
- String hostname() const;
- String port() const;
- String pathname() const;
- String search() const;
- String hash() const;
-
- String toString() const { return href(); }
+ virtual KURL url() const OVERRIDE { return m_url; }
+ virtual String input() const OVERRIDE
+ {
+ ASSERT_NOT_REACHED();
+ return String();
+ }
private:
explicit WorkerLocation(const KURL& url) : m_url(url)
diff --git a/chromium/third_party/WebKit/Source/core/workers/WorkerLocation.idl b/chromium/third_party/WebKit/Source/core/workers/WorkerLocation.idl
index 0d8399bc442..c3dd851fede 100644
--- a/chromium/third_party/WebKit/Source/core/workers/WorkerLocation.idl
+++ b/chromium/third_party/WebKit/Source/core/workers/WorkerLocation.idl
@@ -29,15 +29,7 @@
[
GlobalContext=WorkerGlobalScope
] interface WorkerLocation {
- readonly attribute DOMString href;
- readonly attribute DOMString protocol;
- readonly attribute DOMString host;
- readonly attribute DOMString hostname;
- readonly attribute DOMString port;
- readonly attribute DOMString pathname;
- readonly attribute DOMString search;
- readonly attribute DOMString hash;
-
- [NotEnumerable] DOMString toString();
};
+// force rebuild: crbug.com/307023
+WorkerLocation implements URLUtilsReadOnly;
diff --git a/chromium/third_party/WebKit/Source/core/workers/WorkerMessagingProxy.cpp b/chromium/third_party/WebKit/Source/core/workers/WorkerMessagingProxy.cpp
index 950ee3d929d..a34d8e19b29 100644
--- a/chromium/third_party/WebKit/Source/core/workers/WorkerMessagingProxy.cpp
+++ b/chromium/third_party/WebKit/Source/core/workers/WorkerMessagingProxy.cpp
@@ -31,29 +31,30 @@
#include "core/dom/CrossThreadTask.h"
#include "core/dom/Document.h"
-#include "core/dom/ErrorEvent.h"
-#include "core/dom/MessageEvent.h"
-#include "core/dom/ScriptExecutionContext.h"
+#include "core/events/ErrorEvent.h"
+#include "core/events/MessageEvent.h"
+#include "core/frame/ContentSecurityPolicy.h"
+#include "core/frame/DOMWindow.h"
#include "core/inspector/InspectorInstrumentation.h"
#include "core/inspector/ScriptCallStack.h"
#include "core/inspector/WorkerDebuggerAgent.h"
#include "core/inspector/WorkerInspectorController.h"
#include "core/loader/DocumentLoadTiming.h"
#include "core/loader/DocumentLoader.h"
-#include "core/page/ContentSecurityPolicy.h"
-#include "core/page/DOMWindow.h"
#include "core/page/PageGroup.h"
-#include "core/platform/NotImplemented.h"
#include "core/workers/DedicatedWorkerGlobalScope.h"
#include "core/workers/DedicatedWorkerThread.h"
#include "core/workers/Worker.h"
#include "core/workers/WorkerClients.h"
+#include "core/workers/WorkerObjectProxy.h"
#include "core/workers/WorkerThreadStartupData.h"
+#include "platform/NotImplemented.h"
+#include "wtf/Functional.h"
#include "wtf/MainThread.h"
namespace WebCore {
-class MessageWorkerGlobalScopeTask : public ScriptExecutionContext::Task {
+class MessageWorkerGlobalScopeTask : public ExecutionContextTask {
public:
static PassOwnPtr<MessageWorkerGlobalScopeTask> create(PassRefPtr<SerializedScriptValue> message, PassOwnPtr<MessagePortChannelArray> channels)
{
@@ -67,7 +68,7 @@ private:
{
}
- virtual void performTask(ScriptExecutionContext* scriptContext)
+ virtual void performTask(ExecutionContext* scriptContext)
{
ASSERT_WITH_SECURITY_IMPLICATION(scriptContext->isWorkerGlobalScope());
DedicatedWorkerGlobalScope* context = static_cast<DedicatedWorkerGlobalScope*>(scriptContext);
@@ -81,169 +82,9 @@ private:
OwnPtr<MessagePortChannelArray> m_channels;
};
-class MessageWorkerTask : public ScriptExecutionContext::Task {
-public:
- static PassOwnPtr<MessageWorkerTask> create(PassRefPtr<SerializedScriptValue> message, PassOwnPtr<MessagePortChannelArray> channels, WorkerMessagingProxy* messagingProxy)
- {
- return adoptPtr(new MessageWorkerTask(message, channels, messagingProxy));
- }
-
-private:
- MessageWorkerTask(PassRefPtr<SerializedScriptValue> message, PassOwnPtr<MessagePortChannelArray> channels, WorkerMessagingProxy* messagingProxy)
- : m_message(message)
- , m_channels(channels)
- , m_messagingProxy(messagingProxy)
- {
- }
-
- virtual void performTask(ScriptExecutionContext* scriptContext)
- {
- Worker* workerObject = m_messagingProxy->workerObject();
- if (!workerObject || m_messagingProxy->askedToTerminate())
- return;
-
- OwnPtr<MessagePortArray> ports = MessagePort::entanglePorts(*scriptContext, m_channels.release());
- workerObject->dispatchEvent(MessageEvent::create(ports.release(), m_message));
- }
-
-private:
- RefPtr<SerializedScriptValue> m_message;
- OwnPtr<MessagePortChannelArray> m_channels;
- WorkerMessagingProxy* m_messagingProxy;
-};
-
-class WorkerExceptionTask : public ScriptExecutionContext::Task {
-public:
- static PassOwnPtr<WorkerExceptionTask> create(const String& errorMessage, int lineNumber, int columnNumber, const String& sourceURL, WorkerMessagingProxy* messagingProxy)
- {
- return adoptPtr(new WorkerExceptionTask(errorMessage, lineNumber, columnNumber, sourceURL, messagingProxy));
- }
-
-private:
- WorkerExceptionTask(const String& errorMessage, int lineNumber, int columnNumber, const String& sourceURL, WorkerMessagingProxy* messagingProxy)
- : m_errorMessage(errorMessage.isolatedCopy())
- , m_lineNumber(lineNumber)
- , m_columnNumber(columnNumber)
- , m_sourceURL(sourceURL.isolatedCopy())
- , m_messagingProxy(messagingProxy)
- {
- }
-
- virtual void performTask(ScriptExecutionContext* context)
- {
- Worker* workerObject = m_messagingProxy->workerObject();
- if (!workerObject)
- return;
-
- // We don't bother checking the askedToTerminate() flag here, because exceptions should *always* be reported even if the thread is terminated.
- // This is intentionally different than the behavior in MessageWorkerTask, because terminated workers no longer deliver messages (section 4.6 of the WebWorker spec), but they do report exceptions.
-
- RefPtr<ErrorEvent> event = ErrorEvent::create(m_errorMessage, m_sourceURL, m_lineNumber, m_columnNumber, 0);
- bool errorHandled = !workerObject->dispatchEvent(event);
- if (!errorHandled)
- context->reportException(event, 0, NotSharableCrossOrigin);
- }
-
- String m_errorMessage;
- int m_lineNumber;
- int m_columnNumber;
- String m_sourceURL;
- WorkerMessagingProxy* m_messagingProxy;
-};
-
-class WorkerGlobalScopeDestroyedTask : public ScriptExecutionContext::Task {
-public:
- static PassOwnPtr<WorkerGlobalScopeDestroyedTask> create(WorkerMessagingProxy* messagingProxy)
- {
- return adoptPtr(new WorkerGlobalScopeDestroyedTask(messagingProxy));
- }
-
-private:
- WorkerGlobalScopeDestroyedTask(WorkerMessagingProxy* messagingProxy)
- : m_messagingProxy(messagingProxy)
- {
- }
-
- virtual void performTask(ScriptExecutionContext*)
- {
- m_messagingProxy->workerGlobalScopeDestroyedInternal();
- }
-
- WorkerMessagingProxy* m_messagingProxy;
-};
-
-class WorkerTerminateTask : public ScriptExecutionContext::Task {
-public:
- static PassOwnPtr<WorkerTerminateTask> create(WorkerMessagingProxy* messagingProxy)
- {
- return adoptPtr(new WorkerTerminateTask(messagingProxy));
- }
-
-private:
- WorkerTerminateTask(WorkerMessagingProxy* messagingProxy)
- : m_messagingProxy(messagingProxy)
- {
- }
-
- virtual void performTask(ScriptExecutionContext*)
- {
- m_messagingProxy->terminateWorkerGlobalScope();
- }
-
- WorkerMessagingProxy* m_messagingProxy;
-};
-
-class WorkerThreadActivityReportTask : public ScriptExecutionContext::Task {
-public:
- static PassOwnPtr<WorkerThreadActivityReportTask> create(WorkerMessagingProxy* messagingProxy, bool confirmingMessage, bool hasPendingActivity)
- {
- return adoptPtr(new WorkerThreadActivityReportTask(messagingProxy, confirmingMessage, hasPendingActivity));
- }
-
-private:
- WorkerThreadActivityReportTask(WorkerMessagingProxy* messagingProxy, bool confirmingMessage, bool hasPendingActivity)
- : m_messagingProxy(messagingProxy)
- , m_confirmingMessage(confirmingMessage)
- , m_hasPendingActivity(hasPendingActivity)
- {
- }
-
- virtual void performTask(ScriptExecutionContext*)
- {
- m_messagingProxy->reportPendingActivityInternal(m_confirmingMessage, m_hasPendingActivity);
- }
-
- WorkerMessagingProxy* m_messagingProxy;
- bool m_confirmingMessage;
- bool m_hasPendingActivity;
-};
-
-class PostMessageToPageInspectorTask : public ScriptExecutionContext::Task {
-public:
- static PassOwnPtr<PostMessageToPageInspectorTask> create(WorkerMessagingProxy* messagingProxy, const String& message)
- {
- return adoptPtr(new PostMessageToPageInspectorTask(messagingProxy, message));
- }
-
-private:
- PostMessageToPageInspectorTask(WorkerMessagingProxy* messagingProxy, const String& message)
- : m_messagingProxy(messagingProxy)
- , m_message(message.isolatedCopy())
- {
- }
-
- virtual void performTask(ScriptExecutionContext*)
- {
- if (WorkerGlobalScopeProxy::PageInspector* pageInspector = m_messagingProxy->m_pageInspector)
- pageInspector->dispatchMessageFromWorker(m_message);
- }
-
- WorkerMessagingProxy* m_messagingProxy;
- String m_message;
-};
-
WorkerMessagingProxy::WorkerMessagingProxy(Worker* workerObject, PassOwnPtr<WorkerClients> workerClients)
- : m_scriptExecutionContext(workerObject->scriptExecutionContext())
+ : m_executionContext(workerObject->executionContext())
+ , m_workerObjectProxy(WorkerObjectProxy::create(m_executionContext.get(), this))
, m_workerObject(workerObject)
, m_mayBeDestroyed(false)
, m_unconfirmedMessageCount(0)
@@ -253,35 +94,39 @@ WorkerMessagingProxy::WorkerMessagingProxy(Worker* workerObject, PassOwnPtr<Work
, m_workerClients(workerClients)
{
ASSERT(m_workerObject);
- ASSERT((m_scriptExecutionContext->isDocument() && isMainThread())
- || (m_scriptExecutionContext->isWorkerGlobalScope() && toWorkerGlobalScope(m_scriptExecutionContext.get())->thread()->isCurrentThread()));
+ ASSERT((m_executionContext->isDocument() && isMainThread())
+ || (m_executionContext->isWorkerGlobalScope() && toWorkerGlobalScope(m_executionContext.get())->thread()->isCurrentThread()));
}
WorkerMessagingProxy::~WorkerMessagingProxy()
{
ASSERT(!m_workerObject);
- ASSERT((m_scriptExecutionContext->isDocument() && isMainThread())
- || (m_scriptExecutionContext->isWorkerGlobalScope() && toWorkerGlobalScope(m_scriptExecutionContext.get())->thread()->isCurrentThread()));
+ ASSERT((m_executionContext->isDocument() && isMainThread())
+ || (m_executionContext->isWorkerGlobalScope() && toWorkerGlobalScope(m_executionContext.get())->thread()->isCurrentThread()));
}
void WorkerMessagingProxy::startWorkerGlobalScope(const KURL& scriptURL, const String& userAgent, const String& sourceCode, WorkerThreadStartMode startMode)
{
// FIXME: This need to be revisited when we support nested worker one day
- ASSERT(m_scriptExecutionContext->isDocument());
- Document* document = toDocument(m_scriptExecutionContext.get());
+ ASSERT(m_executionContext->isDocument());
+ Document* document = toDocument(m_executionContext.get());
OwnPtr<WorkerThreadStartupData> startupData = WorkerThreadStartupData::create(scriptURL, userAgent, sourceCode, startMode, document->contentSecurityPolicy()->deprecatedHeader(), document->contentSecurityPolicy()->deprecatedHeaderType(), m_workerClients.release());
double originTime = document->loader() ? document->loader()->timing()->referenceMonotonicTime() : monotonicallyIncreasingTime();
- RefPtr<DedicatedWorkerThread> thread = DedicatedWorkerThread::create(*this, *this, originTime, startupData.release());
+ RefPtr<DedicatedWorkerThread> thread = DedicatedWorkerThread::create(*this, *m_workerObjectProxy.get(), originTime, startupData.release());
workerThreadCreated(thread);
thread->start();
- InspectorInstrumentation::didStartWorkerGlobalScope(m_scriptExecutionContext.get(), this, scriptURL);
+ InspectorInstrumentation::didStartWorkerGlobalScope(m_executionContext.get(), this, scriptURL);
}
void WorkerMessagingProxy::postMessageToWorkerObject(PassRefPtr<SerializedScriptValue> message, PassOwnPtr<MessagePortChannelArray> channels)
{
- m_scriptExecutionContext->postTask(MessageWorkerTask::create(message, channels, this));
+ if (!m_workerObject || m_askedToTerminate)
+ return;
+
+ OwnPtr<MessagePortArray> ports = MessagePort::entanglePorts(*m_executionContext.get(), channels);
+ m_workerObject->dispatchEvent(MessageEvent::create(ports.release(), message));
}
void WorkerMessagingProxy::postMessageToWorkerGlobalScope(PassRefPtr<SerializedScriptValue> message, PassOwnPtr<MessagePortChannelArray> channels)
@@ -296,7 +141,7 @@ void WorkerMessagingProxy::postMessageToWorkerGlobalScope(PassRefPtr<SerializedS
m_queuedEarlyTasks.append(MessageWorkerGlobalScopeTask::create(message, channels));
}
-bool WorkerMessagingProxy::postTaskForModeToWorkerGlobalScope(PassOwnPtr<ScriptExecutionContext::Task> task, const String& mode)
+bool WorkerMessagingProxy::postTaskForModeToWorkerGlobalScope(PassOwnPtr<ExecutionContextTask> task, const String& mode)
{
if (m_askedToTerminate)
return false;
@@ -306,28 +151,32 @@ bool WorkerMessagingProxy::postTaskForModeToWorkerGlobalScope(PassOwnPtr<ScriptE
return true;
}
-void WorkerMessagingProxy::postTaskToLoader(PassOwnPtr<ScriptExecutionContext::Task> task)
+void WorkerMessagingProxy::postTaskToLoader(PassOwnPtr<ExecutionContextTask> task)
{
// FIXME: In case of nested workers, this should go directly to the root Document context.
- ASSERT(m_scriptExecutionContext->isDocument());
- m_scriptExecutionContext->postTask(task);
+ ASSERT(m_executionContext->isDocument());
+ m_executionContext->postTask(task);
}
-void WorkerMessagingProxy::postExceptionToWorkerObject(const String& errorMessage, int lineNumber, int columnNumber, const String& sourceURL)
+void WorkerMessagingProxy::reportException(const String& errorMessage, int lineNumber, int columnNumber, const String& sourceURL)
{
- m_scriptExecutionContext->postTask(WorkerExceptionTask::create(errorMessage, lineNumber, columnNumber, sourceURL, this));
-}
-
-static void postConsoleMessageTask(ScriptExecutionContext* context, WorkerMessagingProxy* messagingProxy, MessageSource source, MessageLevel level, const String& message, unsigned lineNumber, const String& sourceURL)
-{
- if (messagingProxy->askedToTerminate())
+ if (!m_workerObject)
return;
- context->addConsoleMessage(source, level, message, sourceURL, lineNumber);
+
+ // We don't bother checking the askedToTerminate() flag here, because exceptions should *always* be reported even if the thread is terminated.
+ // This is intentionally different than the behavior in MessageWorkerTask, because terminated workers no longer deliver messages (section 4.6 of the WebWorker spec), but they do report exceptions.
+
+ RefPtr<ErrorEvent> event = ErrorEvent::create(errorMessage, sourceURL, lineNumber, columnNumber, 0);
+ bool errorHandled = !m_workerObject->dispatchEvent(event);
+ if (!errorHandled)
+ m_executionContext->reportException(event, 0, NotSharableCrossOrigin);
}
-void WorkerMessagingProxy::postConsoleMessageToWorkerObject(MessageSource source, MessageLevel level, const String& message, int lineNumber, const String& sourceURL)
+void WorkerMessagingProxy::reportConsoleMessage(MessageSource source, MessageLevel level, const String& message, int lineNumber, const String& sourceURL)
{
- m_scriptExecutionContext->postTask(createCallbackTask(&postConsoleMessageTask, AllowCrossThreadAccess(this), source, level, message, lineNumber, sourceURL));
+ if (m_askedToTerminate)
+ return;
+ m_executionContext->addConsoleMessage(source, level, message, sourceURL, lineNumber);
}
void WorkerMessagingProxy::workerThreadCreated(PassRefPtr<DedicatedWorkerThread> workerThread)
@@ -352,19 +201,19 @@ void WorkerMessagingProxy::workerThreadCreated(PassRefPtr<DedicatedWorkerThread>
void WorkerMessagingProxy::workerObjectDestroyed()
{
m_workerObject = 0;
- m_scriptExecutionContext->postTask(createCallbackTask(&workerObjectDestroyedInternal, AllowCrossThreadAccess(this)));
+ m_executionContext->postTask(createCallbackTask(&workerObjectDestroyedInternal, AllowCrossThreadAccess(this)));
}
-void WorkerMessagingProxy::workerObjectDestroyedInternal(ScriptExecutionContext*, WorkerMessagingProxy* proxy)
+void WorkerMessagingProxy::workerObjectDestroyedInternal(ExecutionContext*, WorkerMessagingProxy* proxy)
{
proxy->m_mayBeDestroyed = true;
if (proxy->m_workerThread)
proxy->terminateWorkerGlobalScope();
else
- proxy->workerGlobalScopeDestroyedInternal();
+ proxy->workerGlobalScopeDestroyed();
}
-static void connectToWorkerGlobalScopeInspectorTask(ScriptExecutionContext* context, bool)
+static void connectToWorkerGlobalScopeInspectorTask(ExecutionContext* context, bool)
{
toWorkerGlobalScope(context)->workerInspectorController()->connectFrontend();
}
@@ -378,7 +227,7 @@ void WorkerMessagingProxy::connectToInspector(WorkerGlobalScopeProxy::PageInspec
m_workerThread->runLoop().postTaskForMode(createCallbackTask(connectToWorkerGlobalScopeInspectorTask, true), WorkerDebuggerAgent::debuggerTaskMode);
}
-static void disconnectFromWorkerGlobalScopeInspectorTask(ScriptExecutionContext* context, bool)
+static void disconnectFromWorkerGlobalScopeInspectorTask(ExecutionContext* context, bool)
{
toWorkerGlobalScope(context)->workerInspectorController()->disconnectFrontend();
}
@@ -391,7 +240,7 @@ void WorkerMessagingProxy::disconnectFromInspector()
m_workerThread->runLoop().postTaskForMode(createCallbackTask(disconnectFromWorkerGlobalScopeInspectorTask, true), WorkerDebuggerAgent::debuggerTaskMode);
}
-static void dispatchOnInspectorBackendTask(ScriptExecutionContext* context, const String& message)
+static void dispatchOnInspectorBackendTask(ExecutionContext* context, const String& message)
{
toWorkerGlobalScope(context)->workerInspectorController()->dispatchMessageFromFrontend(message);
}
@@ -406,24 +255,12 @@ void WorkerMessagingProxy::sendMessageToInspector(const String& message)
void WorkerMessagingProxy::workerGlobalScopeDestroyed()
{
- m_scriptExecutionContext->postTask(WorkerGlobalScopeDestroyedTask::create(this));
- // Will execute workerGlobalScopeDestroyedInternal() on context's thread.
-}
-
-void WorkerMessagingProxy::workerGlobalScopeClosed()
-{
- // Executes terminateWorkerGlobalScope() on parent context's thread.
- m_scriptExecutionContext->postTask(WorkerTerminateTask::create(this));
-}
-
-void WorkerMessagingProxy::workerGlobalScopeDestroyedInternal()
-{
- // WorkerGlobalScopeDestroyedTask is always the last to be performed, so the proxy is not needed for communication
+ // This method is always the last to be performed, so the proxy is not needed for communication
// in either side any more. However, the Worker object may still exist, and it assumes that the proxy exists, too.
m_askedToTerminate = true;
m_workerThread = 0;
- InspectorInstrumentation::workerGlobalScopeTerminated(m_scriptExecutionContext.get(), this);
+ InspectorInstrumentation::workerGlobalScopeTerminated(m_executionContext.get(), this);
if (m_mayBeDestroyed)
delete this;
@@ -438,38 +275,26 @@ void WorkerMessagingProxy::terminateWorkerGlobalScope()
if (m_workerThread)
m_workerThread->stop();
- InspectorInstrumentation::workerGlobalScopeTerminated(m_scriptExecutionContext.get(), this);
+ InspectorInstrumentation::workerGlobalScopeTerminated(m_executionContext.get(), this);
}
void WorkerMessagingProxy::postMessageToPageInspector(const String& message)
{
- m_scriptExecutionContext->postTask(PostMessageToPageInspectorTask::create(this, message));
-}
-
-void WorkerMessagingProxy::updateInspectorStateCookie(const String&)
-{
- notImplemented();
+ if (m_pageInspector)
+ m_pageInspector->dispatchMessageFromWorker(message);
}
void WorkerMessagingProxy::confirmMessageFromWorkerObject(bool hasPendingActivity)
{
- m_scriptExecutionContext->postTask(WorkerThreadActivityReportTask::create(this, true, hasPendingActivity));
- // Will execute reportPendingActivityInternal() on context's thread.
-}
-
-void WorkerMessagingProxy::reportPendingActivity(bool hasPendingActivity)
-{
- m_scriptExecutionContext->postTask(WorkerThreadActivityReportTask::create(this, false, hasPendingActivity));
- // Will execute reportPendingActivityInternal() on context's thread.
-}
-
-void WorkerMessagingProxy::reportPendingActivityInternal(bool confirmingMessage, bool hasPendingActivity)
-{
- if (confirmingMessage && !m_askedToTerminate) {
+ if (!m_askedToTerminate) {
ASSERT(m_unconfirmedMessageCount);
--m_unconfirmedMessageCount;
}
+ reportPendingActivity(hasPendingActivity);
+}
+void WorkerMessagingProxy::reportPendingActivity(bool hasPendingActivity)
+{
m_workerThreadHadPendingActivity = hasPendingActivity;
}
diff --git a/chromium/third_party/WebKit/Source/core/workers/WorkerMessagingProxy.h b/chromium/third_party/WebKit/Source/core/workers/WorkerMessagingProxy.h
index 26566bfb2b5..c94337415a2 100644
--- a/chromium/third_party/WebKit/Source/core/workers/WorkerMessagingProxy.h
+++ b/chromium/third_party/WebKit/Source/core/workers/WorkerMessagingProxy.h
@@ -27,10 +27,9 @@
#ifndef WorkerMessagingProxy_h
#define WorkerMessagingProxy_h
-#include "core/dom/ScriptExecutionContext.h"
+#include "core/dom/ExecutionContext.h"
#include "core/workers/WorkerGlobalScopeProxy.h"
#include "core/workers/WorkerLoaderProxy.h"
-#include "core/workers/WorkerObjectProxy.h"
#include "wtf/Forward.h"
#include "wtf/Noncopyable.h"
#include "wtf/PassOwnPtr.h"
@@ -40,12 +39,13 @@
namespace WebCore {
+ class WorkerObjectProxy;
class DedicatedWorkerThread;
- class ScriptExecutionContext;
+ class ExecutionContext;
class Worker;
class WorkerClients;
- class WorkerMessagingProxy : public WorkerGlobalScopeProxy, public WorkerObjectProxy, public WorkerLoaderProxy {
+ class WorkerMessagingProxy : public WorkerGlobalScopeProxy, public WorkerLoaderProxy {
WTF_MAKE_NONCOPYABLE(WorkerMessagingProxy); WTF_MAKE_FAST_ALLOCATED;
public:
WorkerMessagingProxy(Worker*, PassOwnPtr<WorkerClients>);
@@ -61,45 +61,33 @@ namespace WebCore {
virtual void disconnectFromInspector() OVERRIDE;
virtual void sendMessageToInspector(const String&) OVERRIDE;
- // Implementations of WorkerObjectProxy.
- // (Only use these methods in the worker context thread.)
- virtual void postMessageToWorkerObject(PassRefPtr<SerializedScriptValue>, PassOwnPtr<MessagePortChannelArray>) OVERRIDE;
- virtual void postExceptionToWorkerObject(const String& errorMessage, int lineNumber, int columnNumber, const String& sourceURL) OVERRIDE;
- virtual void postConsoleMessageToWorkerObject(MessageSource, MessageLevel, const String& message, int lineNumber, const String& sourceURL) OVERRIDE;
- virtual void postMessageToPageInspector(const String&) OVERRIDE;
- virtual void updateInspectorStateCookie(const String&) OVERRIDE;
- virtual void confirmMessageFromWorkerObject(bool hasPendingActivity) OVERRIDE;
- virtual void reportPendingActivity(bool hasPendingActivity) OVERRIDE;
- virtual void workerGlobalScopeClosed() OVERRIDE;
- virtual void workerGlobalScopeDestroyed() OVERRIDE;
+ // These methods come from worker context thread via WorkerObjectProxy
+ // and are called on the worker object thread (e.g. main thread).
+ void postMessageToWorkerObject(PassRefPtr<SerializedScriptValue>, PassOwnPtr<MessagePortChannelArray>);
+ void reportException(const String& errorMessage, int lineNumber, int columnNumber, const String& sourceURL);
+ void reportConsoleMessage(MessageSource, MessageLevel, const String& message, int lineNumber, const String& sourceURL);
+ void postMessageToPageInspector(const String&);
+ void confirmMessageFromWorkerObject(bool hasPendingActivity);
+ void reportPendingActivity(bool hasPendingActivity);
+ void workerGlobalScopeClosed();
+ void workerGlobalScopeDestroyed();
// Implementation of WorkerLoaderProxy.
// These methods are called on different threads to schedule loading
// requests and to send callbacks back to WorkerGlobalScope.
- virtual void postTaskToLoader(PassOwnPtr<ScriptExecutionContext::Task>) OVERRIDE;
- virtual bool postTaskForModeToWorkerGlobalScope(PassOwnPtr<ScriptExecutionContext::Task>, const String& mode) OVERRIDE;
+ virtual void postTaskToLoader(PassOwnPtr<ExecutionContextTask>) OVERRIDE;
+ virtual bool postTaskForModeToWorkerGlobalScope(PassOwnPtr<ExecutionContextTask>, const String& mode) OVERRIDE;
void workerThreadCreated(PassRefPtr<DedicatedWorkerThread>);
- // Only use this method on the worker object thread.
- bool askedToTerminate() const { return m_askedToTerminate; }
-
protected:
virtual ~WorkerMessagingProxy();
private:
- friend class MessageWorkerTask;
- friend class PostMessageToPageInspectorTask;
- friend class WorkerGlobalScopeDestroyedTask;
- friend class WorkerExceptionTask;
- friend class WorkerThreadActivityReportTask;
-
- void workerGlobalScopeDestroyedInternal();
- static void workerObjectDestroyedInternal(ScriptExecutionContext*, WorkerMessagingProxy*);
- void reportPendingActivityInternal(bool confirmingMessage, bool hasPendingActivity);
- Worker* workerObject() const { return m_workerObject; }
-
- RefPtr<ScriptExecutionContext> m_scriptExecutionContext;
+ static void workerObjectDestroyedInternal(ExecutionContext*, WorkerMessagingProxy*);
+
+ RefPtr<ExecutionContext> m_executionContext;
+ OwnPtr<WorkerObjectProxy> m_workerObjectProxy;
Worker* m_workerObject;
bool m_mayBeDestroyed;
RefPtr<DedicatedWorkerThread> m_workerThread;
@@ -109,7 +97,7 @@ namespace WebCore {
bool m_askedToTerminate;
- Vector<OwnPtr<ScriptExecutionContext::Task> > m_queuedEarlyTasks; // Tasks are queued here until there's a thread object created.
+ Vector<OwnPtr<ExecutionContextTask> > m_queuedEarlyTasks; // Tasks are queued here until there's a thread object created.
WorkerGlobalScopeProxy::PageInspector* m_pageInspector;
OwnPtr<WorkerClients> m_workerClients;
diff --git a/chromium/third_party/WebKit/Source/core/workers/WorkerNavigator.cpp b/chromium/third_party/WebKit/Source/core/workers/WorkerNavigator.cpp
new file mode 100644
index 00000000000..7ad476c0476
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/workers/WorkerNavigator.cpp
@@ -0,0 +1,48 @@
+/*
+ * Copyright (C) 2008 Apple Inc. All Rights Reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "config.h"
+
+#include "core/workers/WorkerNavigator.h"
+
+namespace WebCore {
+
+WorkerNavigator::WorkerNavigator(const String& userAgent)
+ : m_userAgent(userAgent)
+{
+ ScriptWrappable::init(this);
+}
+
+WorkerNavigator::~WorkerNavigator()
+{
+}
+
+String WorkerNavigator::userAgent() const
+{
+ return m_userAgent;
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/workers/WorkerNavigator.h b/chromium/third_party/WebKit/Source/core/workers/WorkerNavigator.h
new file mode 100644
index 00000000000..61c06183fad
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/workers/WorkerNavigator.h
@@ -0,0 +1,53 @@
+/*
+ * Copyright (C) 2008 Apple Inc. All Rights Reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+#ifndef WorkerNavigator_h
+#define WorkerNavigator_h
+
+#include "bindings/v8/ScriptWrappable.h"
+#include "core/frame/NavigatorBase.h"
+#include "platform/Supplementable.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefCounted.h"
+#include "wtf/text/WTFString.h"
+
+namespace WebCore {
+
+class WorkerNavigator : public RefCounted<WorkerNavigator>, public ScriptWrappable, public NavigatorBase, public Supplementable<WorkerNavigator> {
+public:
+ static PassRefPtr<WorkerNavigator> create(const String& userAgent) { return adoptRef(new WorkerNavigator(userAgent)); }
+ virtual ~WorkerNavigator();
+
+ virtual String userAgent() const OVERRIDE;
+
+private:
+ explicit WorkerNavigator(const String&);
+
+ String m_userAgent;
+};
+
+} // namespace WebCore
+
+#endif // WorkerNavigator_h
diff --git a/chromium/third_party/WebKit/Source/core/page/WorkerNavigator.idl b/chromium/third_party/WebKit/Source/core/workers/WorkerNavigator.idl
index 3debfca937b..3debfca937b 100644
--- a/chromium/third_party/WebKit/Source/core/page/WorkerNavigator.idl
+++ b/chromium/third_party/WebKit/Source/core/workers/WorkerNavigator.idl
diff --git a/chromium/third_party/WebKit/Source/core/workers/WorkerObjectProxy.cpp b/chromium/third_party/WebKit/Source/core/workers/WorkerObjectProxy.cpp
new file mode 100644
index 00000000000..3eb1920f94c
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/workers/WorkerObjectProxy.cpp
@@ -0,0 +1,99 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "WorkerObjectProxy.h"
+
+#include "bindings/v8/SerializedScriptValue.h"
+#include "core/dom/ExecutionContext.h"
+#include "core/workers/WorkerMessagingProxy.h"
+#include "platform/NotImplemented.h"
+#include "wtf/Functional.h"
+
+namespace WebCore {
+
+PassOwnPtr<WorkerObjectProxy> WorkerObjectProxy::create(ExecutionContext* executionContext, WorkerMessagingProxy* messagingProxy)
+{
+ return adoptPtr(new WorkerObjectProxy(executionContext, messagingProxy));
+}
+
+void WorkerObjectProxy::postMessageToWorkerObject(PassRefPtr<SerializedScriptValue> message, PassOwnPtr<MessagePortChannelArray> channels)
+{
+ m_executionContext->postTask(bind(&WorkerMessagingProxy::postMessageToWorkerObject, m_messagingProxy, message, channels));
+}
+
+void WorkerObjectProxy::confirmMessageFromWorkerObject(bool hasPendingActivity)
+{
+ m_executionContext->postTask(bind(&WorkerMessagingProxy::confirmMessageFromWorkerObject, m_messagingProxy, hasPendingActivity));
+}
+
+void WorkerObjectProxy::reportPendingActivity(bool hasPendingActivity)
+{
+ m_executionContext->postTask(bind(&WorkerMessagingProxy::reportPendingActivity, m_messagingProxy, hasPendingActivity));
+}
+
+void WorkerObjectProxy::reportException(const String& errorMessage, int lineNumber, int columnNumber, const String& sourceURL)
+{
+ m_executionContext->postTask(bind(&WorkerMessagingProxy::reportException, m_messagingProxy, errorMessage.isolatedCopy(), lineNumber, columnNumber, sourceURL.isolatedCopy()));
+}
+
+void WorkerObjectProxy::reportConsoleMessage(MessageSource source, MessageLevel level, const String& message, int lineNumber, const String& sourceURL)
+{
+ m_executionContext->postTask(bind(&WorkerMessagingProxy::reportConsoleMessage, m_messagingProxy, source, level, message.isolatedCopy(), lineNumber, sourceURL.isolatedCopy()));
+}
+
+void WorkerObjectProxy::postMessageToPageInspector(const String& message)
+{
+ m_executionContext->postTask(bind(&WorkerMessagingProxy::postMessageToPageInspector, m_messagingProxy, message.isolatedCopy()));
+}
+
+void WorkerObjectProxy::updateInspectorStateCookie(const String&)
+{
+ notImplemented();
+}
+
+void WorkerObjectProxy::workerGlobalScopeClosed()
+{
+ m_executionContext->postTask(bind(&WorkerMessagingProxy::terminateWorkerGlobalScope, m_messagingProxy));
+}
+
+void WorkerObjectProxy::workerGlobalScopeDestroyed()
+{
+ // This will terminate the MessagingProxy.
+ m_executionContext->postTask(bind(&WorkerMessagingProxy::workerGlobalScopeDestroyed, m_messagingProxy));
+}
+
+WorkerObjectProxy::WorkerObjectProxy(ExecutionContext* executionContext, WorkerMessagingProxy* messagingProxy)
+ : m_executionContext(executionContext)
+ , m_messagingProxy(messagingProxy)
+{
+}
+
+} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/workers/WorkerObjectProxy.h b/chromium/third_party/WebKit/Source/core/workers/WorkerObjectProxy.h
index d0061f752ac..8b727a148d4 100644
--- a/chromium/third_party/WebKit/Source/core/workers/WorkerObjectProxy.h
+++ b/chromium/third_party/WebKit/Source/core/workers/WorkerObjectProxy.h
@@ -34,21 +34,44 @@
#include "core/dom/MessagePort.h"
#include "core/workers/WorkerReportingProxy.h"
#include "wtf/PassOwnPtr.h"
+#include "wtf/PassRefPtr.h"
namespace WebCore {
- class MessagePortChannel;
+ class ExecutionContext;
+ class WorkerMessagingProxy;
- // A proxy to talk to the worker object.
+ // A proxy to talk to the worker object. This object is created on the
+ // worker object thread (i.e. usually the main thread), passed on to
+ // the worker thread, and used just to proxy messages to the
+ // WorkerMessagingProxy on the worker object thread.
+ //
+ // Used only by Dedicated Worker.
class WorkerObjectProxy : public WorkerReportingProxy {
public:
- virtual void postMessageToWorkerObject(PassRefPtr<SerializedScriptValue>, PassOwnPtr<MessagePortChannelArray>) = 0;
+ static PassOwnPtr<WorkerObjectProxy> create(ExecutionContext*, WorkerMessagingProxy*);
+ ~WorkerObjectProxy() { }
- virtual void confirmMessageFromWorkerObject(bool hasPendingActivity) = 0;
- virtual void reportPendingActivity(bool hasPendingActivity) = 0;
+ void postMessageToWorkerObject(PassRefPtr<SerializedScriptValue>, PassOwnPtr<MessagePortChannelArray>);
- // No need to notify the parent page context when dedicated workers are closing.
- virtual void workerGlobalScopeClosed() OVERRIDE { }
+ void confirmMessageFromWorkerObject(bool hasPendingActivity);
+ void reportPendingActivity(bool hasPendingActivity);
+
+ // WorkerReportingProxy overrides.
+ virtual void reportException(const String& errorMessage, int lineNumber, int columnNumber, const String& sourceURL) OVERRIDE;
+ virtual void reportConsoleMessage(MessageSource, MessageLevel, const String& message, int lineNumber, const String& sourceURL) OVERRIDE;
+ virtual void postMessageToPageInspector(const String&) OVERRIDE;
+ virtual void updateInspectorStateCookie(const String&) OVERRIDE;
+ virtual void workerGlobalScopeStarted() OVERRIDE { }
+ virtual void workerGlobalScopeClosed() OVERRIDE;
+ virtual void workerGlobalScopeDestroyed() OVERRIDE;
+
+ private:
+ WorkerObjectProxy(ExecutionContext*, WorkerMessagingProxy*);
+
+ // These objects always outlive this proxy.
+ ExecutionContext* m_executionContext;
+ WorkerMessagingProxy* m_messagingProxy;
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/workers/WorkerReportingProxy.h b/chromium/third_party/WebKit/Source/core/workers/WorkerReportingProxy.h
index daa8f500b45..75b13891133 100644
--- a/chromium/third_party/WebKit/Source/core/workers/WorkerReportingProxy.h
+++ b/chromium/third_party/WebKit/Source/core/workers/WorkerReportingProxy.h
@@ -31,7 +31,7 @@
#ifndef WorkerReportingProxy_h
#define WorkerReportingProxy_h
-#include "core/page/ConsoleTypes.h"
+#include "core/frame/ConsoleTypes.h"
#include "wtf/Forward.h"
namespace WebCore {
@@ -41,11 +41,14 @@ namespace WebCore {
public:
virtual ~WorkerReportingProxy() {}
- virtual void postExceptionToWorkerObject(const String& errorMessage, int lineNumber, int columnNumber, const String& sourceURL) = 0;
-
- virtual void postConsoleMessageToWorkerObject(MessageSource, MessageLevel, const String& message, int lineNumber, const String& sourceURL) = 0;
+ virtual void reportException(const String& errorMessage, int lineNumber, int columnNumber, const String& sourceURL) = 0;
+ virtual void reportConsoleMessage(MessageSource, MessageLevel, const String& message, int lineNumber, const String& sourceURL) = 0;
virtual void postMessageToPageInspector(const String&) = 0;
virtual void updateInspectorStateCookie(const String&) = 0;
+
+ // Invoked when the new WorkerGlobalScope is started.
+ virtual void workerGlobalScopeStarted() = 0;
+
// Invoked when close() is invoked on the worker context.
virtual void workerGlobalScopeClosed() = 0;
diff --git a/chromium/third_party/WebKit/Source/core/workers/WorkerRunLoop.cpp b/chromium/third_party/WebKit/Source/core/workers/WorkerRunLoop.cpp
index 5dedc0ef700..b7ad2fd73ae 100644
--- a/chromium/third_party/WebKit/Source/core/workers/WorkerRunLoop.cpp
+++ b/chromium/third_party/WebKit/Source/core/workers/WorkerRunLoop.cpp
@@ -31,17 +31,42 @@
#include "config.h"
#include "core/workers/WorkerRunLoop.h"
-#include "core/dom/ScriptExecutionContext.h"
#include "core/inspector/InspectorInstrumentation.h"
-#include "core/platform/SharedTimer.h"
-#include "core/platform/ThreadGlobalData.h"
-#include "core/platform/ThreadTimers.h"
#include "core/workers/WorkerGlobalScope.h"
#include "core/workers/WorkerThread.h"
+#include "platform/PlatformThreadData.h"
+#include "platform/SharedTimer.h"
+#include "platform/ThreadTimers.h"
#include "wtf/CurrentTime.h"
namespace WebCore {
+class WorkerRunLoop::Task {
+ WTF_MAKE_NONCOPYABLE(Task); WTF_MAKE_FAST_ALLOCATED;
+public:
+ static PassOwnPtr<Task> create(PassOwnPtr<ExecutionContextTask> task, const String& mode)
+ {
+ return adoptPtr(new Task(task, mode));
+ }
+ const String& mode() const { return m_mode; }
+ void performTask(const WorkerRunLoop& runLoop, ExecutionContext* context)
+ {
+ WorkerGlobalScope* workerGlobalScope = toWorkerGlobalScope(context);
+ if ((!workerGlobalScope->isClosing() && !runLoop.terminated()) || m_task->isCleanupTask())
+ m_task->performTask(context);
+ }
+
+private:
+ Task(PassOwnPtr<ExecutionContextTask> task, const String& mode)
+ : m_task(task)
+ , m_mode(mode.isolatedCopy())
+ {
+ }
+
+ OwnPtr<ExecutionContextTask> m_task;
+ String m_mode;
+};
+
class WorkerSharedTimer : public SharedTimer {
public:
WorkerSharedTimer()
@@ -112,7 +137,7 @@ public:
, m_context(context)
{
if (!m_runLoop.m_nestedCount)
- threadGlobalData().threadTimers().setSharedTimer(m_runLoop.m_sharedTimer.get());
+ PlatformThreadData::current().threadTimers().setSharedTimer(m_runLoop.m_sharedTimer.get());
m_runLoop.m_nestedCount++;
InspectorInstrumentation::willEnterNestedRunLoop(m_context);
}
@@ -121,7 +146,7 @@ public:
{
m_runLoop.m_nestedCount--;
if (!m_runLoop.m_nestedCount)
- threadGlobalData().threadTimers().setSharedTimer(0);
+ PlatformThreadData::current().threadTimers().setSharedTimer(0);
InspectorInstrumentation::didLeaveNestedRunLoop(m_context);
}
private:
@@ -224,37 +249,29 @@ void WorkerRunLoop::terminate()
m_messageQueue.kill();
}
-bool WorkerRunLoop::postTask(PassOwnPtr<ScriptExecutionContext::Task> task)
+bool WorkerRunLoop::postTask(PassOwnPtr<ExecutionContextTask> task)
{
return postTaskForMode(task, defaultMode());
}
-void WorkerRunLoop::postTaskAndTerminate(PassOwnPtr<ScriptExecutionContext::Task> task)
-{
- m_messageQueue.appendAndKill(Task::create(task, defaultMode().isolatedCopy()));
-}
-
-bool WorkerRunLoop::postTaskForMode(PassOwnPtr<ScriptExecutionContext::Task> task, const String& mode)
+bool WorkerRunLoop::postTask(const Closure& closure)
{
- return m_messageQueue.append(Task::create(task, mode.isolatedCopy()));
+ return postTask(CallClosureTask::create(closure));
}
-PassOwnPtr<WorkerRunLoop::Task> WorkerRunLoop::Task::create(PassOwnPtr<ScriptExecutionContext::Task> task, const String& mode)
+void WorkerRunLoop::postTaskAndTerminate(PassOwnPtr<ExecutionContextTask> task)
{
- return adoptPtr(new Task(task, mode));
+ m_messageQueue.appendAndKill(Task::create(task, defaultMode().isolatedCopy()));
}
-void WorkerRunLoop::Task::performTask(const WorkerRunLoop& runLoop, ScriptExecutionContext* context)
+bool WorkerRunLoop::postTaskForMode(PassOwnPtr<ExecutionContextTask> task, const String& mode)
{
- WorkerGlobalScope* workerGlobalScope = toWorkerGlobalScope(context);
- if ((!workerGlobalScope->isClosing() && !runLoop.terminated()) || m_task->isCleanupTask())
- m_task->performTask(context);
+ return m_messageQueue.append(Task::create(task, mode.isolatedCopy()));
}
-WorkerRunLoop::Task::Task(PassOwnPtr<ScriptExecutionContext::Task> task, const String& mode)
- : m_task(task)
- , m_mode(mode.isolatedCopy())
+bool WorkerRunLoop::postTaskForMode(const Closure& closure, const String& mode)
{
+ return postTaskForMode(CallClosureTask::create(closure), mode);
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/workers/WorkerRunLoop.h b/chromium/third_party/WebKit/Source/core/workers/WorkerRunLoop.h
index 8ee3e8eadf4..88d1b3ace9e 100644
--- a/chromium/third_party/WebKit/Source/core/workers/WorkerRunLoop.h
+++ b/chromium/third_party/WebKit/Source/core/workers/WorkerRunLoop.h
@@ -31,7 +31,9 @@
#ifndef WorkerRunLoop_h
#define WorkerRunLoop_h
-#include "core/dom/ScriptExecutionContext.h"
+#include "core/dom/ExecutionContext.h"
+#include "core/dom/ExecutionContextTask.h"
+#include "wtf/Functional.h"
#include "wtf/MessageQueue.h"
#include "wtf/OwnPtr.h"
#include "wtf/PassOwnPtr.h"
@@ -59,29 +61,20 @@ namespace WebCore {
bool terminated() const { return m_messageQueue.killed(); }
// Returns true if the loop is still alive, false if it has been terminated.
- bool postTask(PassOwnPtr<ScriptExecutionContext::Task>);
- void postTaskAndTerminate(PassOwnPtr<ScriptExecutionContext::Task>);
+ bool postTask(PassOwnPtr<ExecutionContextTask>);
+ bool postTask(const Closure&);
+
+ void postTaskAndTerminate(PassOwnPtr<ExecutionContextTask>);
+
// Returns true if the loop is still alive, false if it has been terminated.
- bool postTaskForMode(PassOwnPtr<ScriptExecutionContext::Task>, const String& mode);
+ bool postTaskForMode(PassOwnPtr<ExecutionContextTask>, const String& mode);
+ bool postTaskForMode(const Closure&, const String& mode);
unsigned long createUniqueId() { return ++m_uniqueId; }
static String defaultMode();
- class Task {
- WTF_MAKE_NONCOPYABLE(Task); WTF_MAKE_FAST_ALLOCATED;
- public:
- static PassOwnPtr<Task> create(PassOwnPtr<ScriptExecutionContext::Task> task, const String& mode);
- ~Task() { }
- const String& mode() const { return m_mode; }
- void performTask(const WorkerRunLoop&, ScriptExecutionContext*);
-
- private:
- Task(PassOwnPtr<ScriptExecutionContext::Task> task, const String& mode);
-
- OwnPtr<ScriptExecutionContext::Task> m_task;
- String m_mode;
- };
+ class Task;
private:
friend class RunLoopSetup;
diff --git a/chromium/third_party/WebKit/Source/core/workers/WorkerScriptLoader.cpp b/chromium/third_party/WebKit/Source/core/workers/WorkerScriptLoader.cpp
index 7e0e9303cad..1ed0d43d643 100644
--- a/chromium/third_party/WebKit/Source/core/workers/WorkerScriptLoader.cpp
+++ b/chromium/third_party/WebKit/Source/core/workers/WorkerScriptLoader.cpp
@@ -28,16 +28,15 @@
#include "config.h"
#include "core/workers/WorkerScriptLoader.h"
-#include "core/dom/ScriptExecutionContext.h"
+#include "core/dom/ExecutionContext.h"
#include "core/fetch/TextResourceDecoder.h"
#include "core/loader/WorkerThreadableLoader.h"
-#include "core/platform/network/ResourceResponse.h"
#include "core/workers/WorkerGlobalScope.h"
#include "core/workers/WorkerScriptLoaderClient.h"
+#include "platform/network/ResourceResponse.h"
#include "wtf/OwnPtr.h"
#include "wtf/RefPtr.h"
-#include "wtf/UnusedParam.h"
namespace WebCore {
@@ -54,7 +53,7 @@ WorkerScriptLoader::~WorkerScriptLoader()
{
}
-void WorkerScriptLoader::loadSynchronously(ScriptExecutionContext* scriptExecutionContext, const KURL& url, CrossOriginRequestPolicy crossOriginRequestPolicy)
+void WorkerScriptLoader::loadSynchronously(ExecutionContext* executionContext, const KURL& url, CrossOriginRequestPolicy crossOriginRequestPolicy)
{
m_url = url;
@@ -62,7 +61,7 @@ void WorkerScriptLoader::loadSynchronously(ScriptExecutionContext* scriptExecuti
if (!request)
return;
- ASSERT_WITH_SECURITY_IMPLICATION(scriptExecutionContext->isWorkerGlobalScope());
+ ASSERT_WITH_SECURITY_IMPLICATION(executionContext->isWorkerGlobalScope());
ThreadableLoaderOptions options;
options.allowCredentials = AllowStoredCredentials;
@@ -71,10 +70,10 @@ void WorkerScriptLoader::loadSynchronously(ScriptExecutionContext* scriptExecuti
// FIXME: Should we add EnforceScriptSrcDirective here?
options.contentSecurityPolicyEnforcement = DoNotEnforceContentSecurityPolicy;
- WorkerThreadableLoader::loadResourceSynchronously(toWorkerGlobalScope(scriptExecutionContext), *request, *this, options);
+ WorkerThreadableLoader::loadResourceSynchronously(toWorkerGlobalScope(executionContext), *request, *this, options);
}
-void WorkerScriptLoader::loadAsynchronously(ScriptExecutionContext* scriptExecutionContext, const KURL& url, CrossOriginRequestPolicy crossOriginRequestPolicy, WorkerScriptLoaderClient* client)
+void WorkerScriptLoader::loadAsynchronously(ExecutionContext* executionContext, const KURL& url, CrossOriginRequestPolicy crossOriginRequestPolicy, WorkerScriptLoaderClient* client)
{
ASSERT(client);
m_client = client;
@@ -91,7 +90,7 @@ void WorkerScriptLoader::loadAsynchronously(ScriptExecutionContext* scriptExecut
// During create, callbacks may happen which remove the last reference to this object.
RefPtr<WorkerScriptLoader> protect(this);
- m_threadableLoader = ThreadableLoader::create(scriptExecutionContext, this, *request, options);
+ m_threadableLoader = ThreadableLoader::create(executionContext, this, *request, options);
}
const KURL& WorkerScriptLoader::responseURL() const
@@ -171,6 +170,12 @@ void WorkerScriptLoader::notifyError()
notifyFinished();
}
+void WorkerScriptLoader::cancel()
+{
+ if (m_threadableLoader)
+ m_threadableLoader->cancel();
+}
+
String WorkerScriptLoader::script()
{
return m_script.toString();
diff --git a/chromium/third_party/WebKit/Source/core/workers/WorkerScriptLoader.h b/chromium/third_party/WebKit/Source/core/workers/WorkerScriptLoader.h
index ef4b655b71a..e4038516948 100644
--- a/chromium/third_party/WebKit/Source/core/workers/WorkerScriptLoader.h
+++ b/chromium/third_party/WebKit/Source/core/workers/WorkerScriptLoader.h
@@ -30,8 +30,8 @@
#include "core/loader/ThreadableLoader.h"
#include "core/loader/ThreadableLoaderClient.h"
-#include "core/platform/network/ResourceRequest.h"
-#include "weborigin/KURL.h"
+#include "platform/network/ResourceRequest.h"
+#include "platform/weborigin/KURL.h"
#include "wtf/FastAllocBase.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefCounted.h"
@@ -41,7 +41,7 @@ namespace WebCore {
class ResourceRequest;
class ResourceResponse;
- class ScriptExecutionContext;
+ class ExecutionContext;
class TextResourceDecoder;
class WorkerScriptLoaderClient;
@@ -53,11 +53,17 @@ namespace WebCore {
return adoptRef(new WorkerScriptLoader());
}
- void loadSynchronously(ScriptExecutionContext*, const KURL&, CrossOriginRequestPolicy);
- void loadAsynchronously(ScriptExecutionContext*, const KURL&, CrossOriginRequestPolicy, WorkerScriptLoaderClient*);
+ void loadSynchronously(ExecutionContext*, const KURL&, CrossOriginRequestPolicy);
+ void loadAsynchronously(ExecutionContext*, const KURL&, CrossOriginRequestPolicy, WorkerScriptLoaderClient*);
void notifyError();
+ // This will immediately lead to notifyFinished() if loadAsynchronously
+ // is in progress.
+ void cancel();
+
+ void setClient(WorkerScriptLoaderClient* client) { m_client = client; }
+
String script();
const KURL& url() const { return m_url; }
const KURL& responseURL() const;
@@ -84,7 +90,7 @@ namespace WebCore {
WorkerScriptLoaderClient* m_client;
RefPtr<ThreadableLoader> m_threadableLoader;
String m_responseEncoding;
- RefPtr<TextResourceDecoder> m_decoder;
+ OwnPtr<TextResourceDecoder> m_decoder;
StringBuilder m_script;
KURL m_url;
KURL m_responseURL;
diff --git a/chromium/third_party/WebKit/Source/core/workers/WorkerSupplementable.h b/chromium/third_party/WebKit/Source/core/workers/WorkerSupplementable.h
new file mode 100644
index 00000000000..f091474148e
--- /dev/null
+++ b/chromium/third_party/WebKit/Source/core/workers/WorkerSupplementable.h
@@ -0,0 +1,42 @@
+/*
+ * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
+ * (C) 1999 Antti Koivisto (koivisto@kde.org)
+ * (C) 2001 Dirk Mueller (mueller@kde.org)
+ * (C) 2006 Alexey Proskuryakov (ap@webkit.org)
+ * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2012 Apple Inc. All rights reserved.
+ * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
+ * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ */
+
+#ifndef WorkerSupplementable_h
+#define WorkerSupplementable_h
+
+#include "platform/Supplementable.h"
+
+namespace WebCore {
+
+class WorkerGlobalScope;
+
+typedef Supplementable<WorkerGlobalScope> WorkerSupplementable;
+typedef Supplement<WorkerGlobalScope> WorkerSupplement;
+
+} // namespace WebCore
+
+#endif // WorkerSupplementable_h
diff --git a/chromium/third_party/WebKit/Source/core/workers/WorkerThread.cpp b/chromium/third_party/WebKit/Source/core/workers/WorkerThread.cpp
index eed80474826..6f842e8db42 100644
--- a/chromium/third_party/WebKit/Source/core/workers/WorkerThread.cpp
+++ b/chromium/third_party/WebKit/Source/core/workers/WorkerThread.cpp
@@ -30,15 +30,15 @@
#include "bindings/v8/ScriptSourceCode.h"
#include "core/inspector/InspectorInstrumentation.h"
-#include "core/platform/ThreadGlobalData.h"
#include "core/workers/DedicatedWorkerGlobalScope.h"
#include "core/workers/WorkerClients.h"
#include "core/workers/WorkerThreadStartupData.h"
#include "modules/webdatabase/DatabaseManager.h"
#include "modules/webdatabase/DatabaseTask.h"
+#include "platform/PlatformThreadData.h"
+#include "platform/weborigin/KURL.h"
#include "public/platform/Platform.h"
#include "public/platform/WebWorkerRunLoop.h"
-#include "weborigin/KURL.h"
#include "wtf/Noncopyable.h"
#include "wtf/text/WTFString.h"
@@ -119,7 +119,7 @@ void WorkerThread::workerThread()
}
// The corresponding call to didStopWorkerRunLoop is in
// ~WorkerScriptController.
- WebKit::Platform::current()->didStartWorkerRunLoop(WebKit::WebWorkerRunLoop(&m_runLoop));
+ blink::Platform::current()->didStartWorkerRunLoop(blink::WebWorkerRunLoop(&m_runLoop));
WorkerScriptController* script = m_workerGlobalScope->script();
InspectorInstrumentation::willEvaluateWorkerScript(workerGlobalScope(), startMode);
@@ -135,8 +135,8 @@ void WorkerThread::workerThread()
// We cannot let any objects survive past thread exit, because no other thread will run GC or otherwise destroy them.
m_workerGlobalScope = 0;
- // Clean up WebCore::ThreadGlobalData before WTF::WTFThreadData goes away!
- threadGlobalData().destroy();
+ // Clean up PlatformThreadData before WTF::WTFThreadData goes away!
+ PlatformThreadData::current().destroy();
// The thread object may be already destroyed from notification now, don't try to access "this".
detachThread(threadID);
@@ -148,14 +148,14 @@ void WorkerThread::runEventLoop()
m_runLoop.run(m_workerGlobalScope.get());
}
-class WorkerThreadShutdownFinishTask : public ScriptExecutionContext::Task {
+class WorkerThreadShutdownFinishTask : public ExecutionContextTask {
public:
static PassOwnPtr<WorkerThreadShutdownFinishTask> create()
{
return adoptPtr(new WorkerThreadShutdownFinishTask());
}
- virtual void performTask(ScriptExecutionContext *context)
+ virtual void performTask(ExecutionContext *context)
{
WorkerGlobalScope* workerGlobalScope = toWorkerGlobalScope(context);
workerGlobalScope->clearInspector();
@@ -166,14 +166,14 @@ public:
virtual bool isCleanupTask() const { return true; }
};
-class WorkerThreadShutdownStartTask : public ScriptExecutionContext::Task {
+class WorkerThreadShutdownStartTask : public ExecutionContextTask {
public:
static PassOwnPtr<WorkerThreadShutdownStartTask> create()
{
return adoptPtr(new WorkerThreadShutdownStartTask());
}
- virtual void performTask(ScriptExecutionContext *context)
+ virtual void performTask(ExecutionContext *context)
{
WorkerGlobalScope* workerGlobalScope = toWorkerGlobalScope(context);
@@ -222,8 +222,8 @@ bool WorkerThread::isCurrentThread() const
return m_threadID == currentThread();
}
-class ReleaseFastMallocFreeMemoryTask : public ScriptExecutionContext::Task {
- virtual void performTask(ScriptExecutionContext*) OVERRIDE { WTF::releaseFastMallocFreeMemory(); }
+class ReleaseFastMallocFreeMemoryTask : public ExecutionContextTask {
+ virtual void performTask(ExecutionContext*) OVERRIDE { WTF::releaseFastMallocFreeMemory(); }
};
void WorkerThread::releaseFastMallocFreeMemoryInAllThreads()
diff --git a/chromium/third_party/WebKit/Source/core/workers/WorkerThread.h b/chromium/third_party/WebKit/Source/core/workers/WorkerThread.h
index c019d80a449..83bf3f445e4 100644
--- a/chromium/third_party/WebKit/Source/core/workers/WorkerThread.h
+++ b/chromium/third_party/WebKit/Source/core/workers/WorkerThread.h
@@ -27,9 +27,9 @@
#ifndef WorkerThread_h
#define WorkerThread_h
-#include "core/page/ContentSecurityPolicy.h"
+#include "core/frame/ContentSecurityPolicy.h"
#include "core/workers/WorkerRunLoop.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/weborigin/SecurityOrigin.h"
#include "wtf/Forward.h"
#include "wtf/OwnPtr.h"
#include "wtf/PassRefPtr.h"
diff --git a/chromium/third_party/WebKit/Source/core/workers/WorkerThreadStartupData.cpp b/chromium/third_party/WebKit/Source/core/workers/WorkerThreadStartupData.cpp
index 15924d9bc0b..2e99b068ccd 100644
--- a/chromium/third_party/WebKit/Source/core/workers/WorkerThreadStartupData.cpp
+++ b/chromium/third_party/WebKit/Source/core/workers/WorkerThreadStartupData.cpp
@@ -31,7 +31,6 @@
#include "config.h"
#include "WorkerThreadStartupData.h"
-#include "core/workers/WorkerClients.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/workers/WorkerThreadStartupData.h b/chromium/third_party/WebKit/Source/core/workers/WorkerThreadStartupData.h
index 2ff3ff83320..c1b13d703b7 100644
--- a/chromium/third_party/WebKit/Source/core/workers/WorkerThreadStartupData.h
+++ b/chromium/third_party/WebKit/Source/core/workers/WorkerThreadStartupData.h
@@ -31,10 +31,10 @@
#ifndef WorkerThreadStartupData_h
#define WorkerThreadStartupData_h
-#include "core/page/ContentSecurityPolicy.h"
+#include "core/frame/ContentSecurityPolicy.h"
#include "core/workers/WorkerClients.h"
#include "core/workers/WorkerThread.h"
-#include "weborigin/KURL.h"
+#include "platform/weborigin/KURL.h"
#include "wtf/Forward.h"
#include "wtf/Noncopyable.h"
diff --git a/chromium/third_party/WebKit/Source/core/xml/DOMParser.cpp b/chromium/third_party/WebKit/Source/core/xml/DOMParser.cpp
index 25c1cb6d6d2..bc509de4ca5 100644
--- a/chromium/third_party/WebKit/Source/core/xml/DOMParser.cpp
+++ b/chromium/third_party/WebKit/Source/core/xml/DOMParser.cpp
@@ -20,14 +20,23 @@
#include "core/xml/DOMParser.h"
#include "core/dom/DOMImplementation.h"
+#include "core/dom/ExceptionCode.h"
#include "wtf/text/WTFString.h"
namespace WebCore {
-PassRefPtr<Document> DOMParser::parseFromString(const String& str, const String& contentType)
+PassRefPtr<Document> DOMParser::parseFromString(const String& str, const String& contentType, ExceptionState& exceptionState)
{
- if (!DOMImplementation::isXMLMIMEType(contentType) && contentType != "text/html")
+ // HTML5 is very explicit about which types we're allowed to support here:
+ // http://domparsing.spec.whatwg.org/#the-domparser-interface
+ if (contentType != "text/html"
+ && contentType != "text/xml"
+ && contentType != "application/xml"
+ && contentType != "application/xhtml+xml"
+ && contentType != "image/svg+xml") {
+ exceptionState.throwDOMException(TypeError, "Unsupported mime-type specified.");
return 0;
+ }
RefPtr<Document> doc = DOMImplementation::createDocument(contentType, 0, KURL(), false);
doc->setContent(str);
diff --git a/chromium/third_party/WebKit/Source/core/xml/DOMParser.h b/chromium/third_party/WebKit/Source/core/xml/DOMParser.h
index 020debaa4b8..afe0d16433c 100644
--- a/chromium/third_party/WebKit/Source/core/xml/DOMParser.h
+++ b/chromium/third_party/WebKit/Source/core/xml/DOMParser.h
@@ -27,12 +27,13 @@
namespace WebCore {
class Document;
+class ExceptionState;
class DOMParser : public RefCounted<DOMParser>, public ScriptWrappable {
public:
static PassRefPtr<DOMParser> create() { return adoptRef(new DOMParser); }
- PassRefPtr<Document> parseFromString(const String&, const String& contentType);
+ PassRefPtr<Document> parseFromString(const String&, const String& contentType, ExceptionState&);
private:
DOMParser()
diff --git a/chromium/third_party/WebKit/Source/core/xml/DOMParser.idl b/chromium/third_party/WebKit/Source/core/xml/DOMParser.idl
index 5cbe49eaea9..ff6af341d86 100644
--- a/chromium/third_party/WebKit/Source/core/xml/DOMParser.idl
+++ b/chromium/third_party/WebKit/Source/core/xml/DOMParser.idl
@@ -20,6 +20,6 @@
[
Constructor
] interface DOMParser {
- Document parseFromString([Default=Undefined] optional DOMString str,
+ [RaisesException] Document parseFromString([Default=Undefined] optional DOMString str,
[Default=Undefined] optional DOMString contentType);
};
diff --git a/chromium/third_party/WebKit/Source/core/xml/DocumentXPathEvaluator.cpp b/chromium/third_party/WebKit/Source/core/xml/DocumentXPathEvaluator.cpp
index b5a3e5c0b09..d14ca546074 100644
--- a/chromium/third_party/WebKit/Source/core/xml/DocumentXPathEvaluator.cpp
+++ b/chromium/third_party/WebKit/Source/core/xml/DocumentXPathEvaluator.cpp
@@ -27,10 +27,8 @@
#include "core/xml/DocumentXPathEvaluator.h"
#include "bindings/v8/ExceptionState.h"
-#include "core/dom/ScriptExecutionContext.h"
-#include "core/xml/XPathEvaluator.h"
+#include "core/dom/Document.h"
#include "core/xml/XPathExpression.h"
-#include "core/xml/XPathNSResolver.h"
#include "core/xml/XPathResult.h"
namespace WebCore {
@@ -43,41 +41,41 @@ DocumentXPathEvaluator::~DocumentXPathEvaluator()
{
}
-DocumentXPathEvaluator* DocumentXPathEvaluator::from(ScriptExecutionContext* context)
+DocumentXPathEvaluator* DocumentXPathEvaluator::from(DocumentSupplementable* document)
{
- DocumentXPathEvaluator* cache = static_cast<DocumentXPathEvaluator*>(Supplement<ScriptExecutionContext>::from(context, supplementName()));
+ DocumentXPathEvaluator* cache = static_cast<DocumentXPathEvaluator*>(DocumentSupplement::from(document, supplementName()));
if (!cache) {
cache = new DocumentXPathEvaluator();
- Supplement<ScriptExecutionContext>::provideTo(context, supplementName(), adoptPtr(cache));
+ DocumentSupplement::provideTo(document, supplementName(), adoptPtr(cache));
}
return cache;
}
-PassRefPtr<XPathExpression> DocumentXPathEvaluator::createExpression(ScriptExecutionContext* context,
- const String& expression, XPathNSResolver* resolver, ExceptionState& es)
+PassRefPtr<XPathExpression> DocumentXPathEvaluator::createExpression(DocumentSupplementable* document,
+ const String& expression, PassRefPtr<XPathNSResolver> resolver, ExceptionState& exceptionState)
{
- DocumentXPathEvaluator* suplement = from(context);
+ DocumentXPathEvaluator* suplement = from(document);
if (!suplement->m_xpathEvaluator)
suplement->m_xpathEvaluator = XPathEvaluator::create();
- return suplement->m_xpathEvaluator->createExpression(expression, resolver, es);
+ return suplement->m_xpathEvaluator->createExpression(expression, resolver, exceptionState);
}
-PassRefPtr<XPathNSResolver> DocumentXPathEvaluator::createNSResolver(ScriptExecutionContext* context, Node* nodeResolver)
+PassRefPtr<XPathNSResolver> DocumentXPathEvaluator::createNSResolver(DocumentSupplementable* document, Node* nodeResolver)
{
- DocumentXPathEvaluator* suplement = from(context);
+ DocumentXPathEvaluator* suplement = from(document);
if (!suplement->m_xpathEvaluator)
suplement->m_xpathEvaluator = XPathEvaluator::create();
return suplement->m_xpathEvaluator->createNSResolver(nodeResolver);
}
-PassRefPtr<XPathResult> DocumentXPathEvaluator::evaluate(ScriptExecutionContext* context, const String& expression,
- Node* contextNode, XPathNSResolver* resolver, unsigned short type,
- XPathResult* result, ExceptionState& es)
+PassRefPtr<XPathResult> DocumentXPathEvaluator::evaluate(DocumentSupplementable* document, const String& expression,
+ Node* contextNode, PassRefPtr<XPathNSResolver> resolver, unsigned short type,
+ XPathResult* result, ExceptionState& exceptionState)
{
- DocumentXPathEvaluator* suplement = from(context);
+ DocumentXPathEvaluator* suplement = from(document);
if (!suplement->m_xpathEvaluator)
suplement->m_xpathEvaluator = XPathEvaluator::create();
- return suplement->m_xpathEvaluator->evaluate(expression, contextNode, resolver, type, result, es);
+ return suplement->m_xpathEvaluator->evaluate(expression, contextNode, resolver, type, result, exceptionState);
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/xml/DocumentXPathEvaluator.h b/chromium/third_party/WebKit/Source/core/xml/DocumentXPathEvaluator.h
index eda4f2d75f4..769a44930a2 100644
--- a/chromium/third_party/WebKit/Source/core/xml/DocumentXPathEvaluator.h
+++ b/chromium/third_party/WebKit/Source/core/xml/DocumentXPathEvaluator.h
@@ -26,28 +26,27 @@
#ifndef DocumentXPathEvaluator_h
#define DocumentXPathEvaluator_h
-#include "core/platform/Supplementable.h"
+#include "core/dom/DocumentSupplementable.h"
#include "core/xml/XPathEvaluator.h"
+#include "core/xml/XPathNSResolver.h"
namespace WebCore {
class ExceptionState;
-class ScriptExecutionContext;
class XPathExpression;
-class XPathNSResolver;
class XPathResult;
-class DocumentXPathEvaluator : public Supplement<ScriptExecutionContext> {
+class DocumentXPathEvaluator : public DocumentSupplement {
public:
virtual ~DocumentXPathEvaluator();
- static DocumentXPathEvaluator* from(ScriptExecutionContext*);
+ static DocumentXPathEvaluator* from(DocumentSupplementable*);
- static PassRefPtr<XPathExpression> createExpression(ScriptExecutionContext*,
- const String& expression, XPathNSResolver*, ExceptionState&);
- static PassRefPtr<XPathNSResolver> createNSResolver(ScriptExecutionContext*, Node* nodeResolver);
- static PassRefPtr<XPathResult> evaluate(ScriptExecutionContext*,
- const String& expression, Node* contextNode, XPathNSResolver*,
+ static PassRefPtr<XPathExpression> createExpression(DocumentSupplementable*,
+ const String& expression, PassRefPtr<XPathNSResolver>, ExceptionState&);
+ static PassRefPtr<XPathNSResolver> createNSResolver(DocumentSupplementable*, Node* nodeResolver);
+ static PassRefPtr<XPathResult> evaluate(DocumentSupplementable*,
+ const String& expression, Node* contextNode, PassRefPtr<XPathNSResolver>,
unsigned short type, XPathResult*, ExceptionState&);
private:
diff --git a/chromium/third_party/WebKit/Source/core/xml/NativeXPathNSResolver.cpp b/chromium/third_party/WebKit/Source/core/xml/NativeXPathNSResolver.cpp
index 8ae8c04db12..cbe118aaa38 100644
--- a/chromium/third_party/WebKit/Source/core/xml/NativeXPathNSResolver.cpp
+++ b/chromium/third_party/WebKit/Source/core/xml/NativeXPathNSResolver.cpp
@@ -41,14 +41,14 @@ NativeXPathNSResolver::~NativeXPathNSResolver()
{
}
-String NativeXPathNSResolver::lookupNamespaceURI(const String& prefix)
+AtomicString NativeXPathNSResolver::lookupNamespaceURI(const String& prefix)
{
// This is not done by Node::lookupNamespaceURI as per the DOM3 Core spec,
// but the XPath spec says that we should do it for XPathNSResolver.
if (prefix == "xml")
return XMLNames::xmlNamespaceURI;
- return m_node ? m_node->lookupNamespaceURI(prefix) : String();
+ return m_node ? m_node->lookupNamespaceURI(prefix) : nullAtom;
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/xml/NativeXPathNSResolver.h b/chromium/third_party/WebKit/Source/core/xml/NativeXPathNSResolver.h
index 17a1238ba10..79523100b4d 100644
--- a/chromium/third_party/WebKit/Source/core/xml/NativeXPathNSResolver.h
+++ b/chromium/third_party/WebKit/Source/core/xml/NativeXPathNSResolver.h
@@ -38,7 +38,7 @@ public:
static PassRefPtr<NativeXPathNSResolver> create(PassRefPtr<Node> node) { return adoptRef(new NativeXPathNSResolver(node)); }
virtual ~NativeXPathNSResolver();
- virtual String lookupNamespaceURI(const String& prefix);
+ virtual AtomicString lookupNamespaceURI(const String& prefix) OVERRIDE;
private:
explicit NativeXPathNSResolver(PassRefPtr<Node>);
diff --git a/chromium/third_party/WebKit/Source/core/xml/XMLErrors.cpp b/chromium/third_party/WebKit/Source/core/xml/XMLErrors.cpp
index 26a6d1acd9d..11936242c65 100644
--- a/chromium/third_party/WebKit/Source/core/xml/XMLErrors.cpp
+++ b/chromium/third_party/WebKit/Source/core/xml/XMLErrors.cpp
@@ -129,7 +129,7 @@ void XMLErrors::insertErrorMessageBlock()
RefPtr<Element> body = m_document->createElement(bodyTag, true);
rootElement->parserAppendChild(body);
- m_document->parserRemoveChild(documentElement.get());
+ m_document->parserRemoveChild(*documentElement);
body->parserAppendChild(documentElement);
m_document->parserAppendChild(rootElement);
@@ -151,7 +151,7 @@ void XMLErrors::insertErrorMessageBlock()
Node* firstChild = documentElement->firstChild();
if (firstChild)
- documentElement->parserInsertBefore(reportElement, documentElement->firstChild());
+ documentElement->parserInsertBefore(reportElement, *firstChild);
else
documentElement->parserAppendChild(reportElement);
diff --git a/chromium/third_party/WebKit/Source/core/xml/XMLHttpRequest.cpp b/chromium/third_party/WebKit/Source/core/xml/XMLHttpRequest.cpp
index 183eb21c2e2..e89de304925 100644
--- a/chromium/third_party/WebKit/Source/core/xml/XMLHttpRequest.cpp
+++ b/chromium/third_party/WebKit/Source/core/xml/XMLHttpRequest.cpp
@@ -25,41 +25,37 @@
#include "FetchInitiatorTypeNames.h"
#include "RuntimeEnabledFeatures.h"
-#include "bindings/v8/ExceptionMessages.h"
#include "bindings/v8/ExceptionState.h"
#include "core/dom/ContextFeatures.h"
#include "core/dom/DOMImplementation.h"
-#include "core/dom/Event.h"
-#include "core/dom/EventListener.h"
-#include "core/dom/EventNames.h"
#include "core/dom/ExceptionCode.h"
#include "core/editing/markup.h"
+#include "core/events/Event.h"
#include "core/fetch/CrossOriginAccessControl.h"
#include "core/fetch/TextResourceDecoder.h"
#include "core/fileapi/Blob.h"
#include "core/fileapi/File.h"
#include "core/fileapi/Stream.h"
+#include "core/frame/ContentSecurityPolicy.h"
#include "core/html/DOMFormData.h"
#include "core/html/HTMLDocument.h"
#include "core/inspector/InspectorInstrumentation.h"
#include "core/loader/ThreadableLoader.h"
-#include "core/page/ContentSecurityPolicy.h"
-#include "core/page/Settings.h"
-#include "core/platform/HistogramSupport.h"
-#include "core/platform/SharedBuffer.h"
-#include "core/platform/network/BlobData.h"
-#include "core/platform/network/HTTPParsers.h"
-#include "core/platform/network/ParsedContentType.h"
-#include "core/platform/network/ResourceError.h"
-#include "core/platform/network/ResourceRequest.h"
+#include "core/frame/Settings.h"
#include "core/xml/XMLHttpRequestProgressEvent.h"
#include "core/xml/XMLHttpRequestUpload.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/Logging.h"
+#include "platform/SharedBuffer.h"
+#include "platform/blob/BlobData.h"
+#include "platform/network/HTTPParsers.h"
+#include "platform/network/ParsedContentType.h"
+#include "platform/network/ResourceError.h"
+#include "platform/network/ResourceRequest.h"
+#include "public/platform/Platform.h"
#include "wtf/ArrayBuffer.h"
#include "wtf/ArrayBufferView.h"
#include "wtf/RefCountedLeakCounter.h"
#include "wtf/StdLibExtras.h"
-#include "wtf/UnusedParam.h"
#include "wtf/text/CString.h"
namespace WebCore {
@@ -148,7 +144,7 @@ static const XMLHttpRequestStaticData* initializeXMLHttpRequestStaticData()
return dummy;
}
-static void logConsoleError(ScriptExecutionContext* context, const String& message)
+static void logConsoleError(ExecutionContext* context, const String& message)
{
if (!context)
return;
@@ -157,7 +153,7 @@ static void logConsoleError(ScriptExecutionContext* context, const String& messa
context->addConsoleMessage(JSMessageSource, ErrorMessageLevel, message);
}
-PassRefPtr<XMLHttpRequest> XMLHttpRequest::create(ScriptExecutionContext* context, PassRefPtr<SecurityOrigin> securityOrigin)
+PassRefPtr<XMLHttpRequest> XMLHttpRequest::create(ExecutionContext* context, PassRefPtr<SecurityOrigin> securityOrigin)
{
RefPtr<XMLHttpRequest> xmlHttpRequest(adoptRef(new XMLHttpRequest(context, securityOrigin)));
xmlHttpRequest->suspendIfNeeded();
@@ -165,13 +161,14 @@ PassRefPtr<XMLHttpRequest> XMLHttpRequest::create(ScriptExecutionContext* contex
return xmlHttpRequest.release();
}
-XMLHttpRequest::XMLHttpRequest(ScriptExecutionContext* context, PassRefPtr<SecurityOrigin> securityOrigin)
+XMLHttpRequest::XMLHttpRequest(ExecutionContext* context, PassRefPtr<SecurityOrigin> securityOrigin)
: ActiveDOMObject(context)
, m_async(true)
, m_includeCredentials(false)
, m_timeoutMilliseconds(0)
, m_state(UNSENT)
, m_createdDocument(false)
+ , m_downloadedBlobLength(0)
, m_error(false)
, m_uploadEventsAllowed(true)
, m_uploadComplete(false)
@@ -181,7 +178,7 @@ XMLHttpRequest::XMLHttpRequest(ScriptExecutionContext* context, PassRefPtr<Secur
, m_exceptionCode(0)
, m_progressEventThrottle(this)
, m_responseTypeCode(ResponseTypeDefault)
- , m_protectionTimer(this, &XMLHttpRequest::dropProtection)
+ , m_dropProtectionRunner(this, &XMLHttpRequest::dropProtection)
, m_securityOrigin(securityOrigin)
{
initializeXMLHttpRequestStaticData();
@@ -200,13 +197,13 @@ XMLHttpRequest::~XMLHttpRequest()
Document* XMLHttpRequest::document() const
{
- ASSERT(scriptExecutionContext()->isDocument());
- return toDocument(scriptExecutionContext());
+ ASSERT(executionContext()->isDocument());
+ return toDocument(executionContext());
}
SecurityOrigin* XMLHttpRequest::securityOrigin() const
{
- return m_securityOrigin ? m_securityOrigin.get() : scriptExecutionContext()->securityOrigin();
+ return m_securityOrigin ? m_securityOrigin.get() : executionContext()->securityOrigin();
}
XMLHttpRequest::State XMLHttpRequest::readyState() const
@@ -214,10 +211,10 @@ XMLHttpRequest::State XMLHttpRequest::readyState() const
return m_state;
}
-ScriptString XMLHttpRequest::responseText(ExceptionState& es)
+ScriptString XMLHttpRequest::responseText(ExceptionState& exceptionState)
{
if (m_responseTypeCode != ResponseTypeDefault && m_responseTypeCode != ResponseTypeText) {
- es.throwDOMException(InvalidStateError, ExceptionMessages::failedToGet("responseText", "XMLHttpRequest", "the value is only accessible if the object's 'responseType' is '' or 'text' (was '" + responseType() + "')."));
+ exceptionState.throwDOMException(InvalidStateError, "The value is only accessible if the object's 'responseType' is '' or 'text' (was '" + responseType() + "').");
return ScriptString();
}
if (m_error || (m_state != LOADING && m_state != DONE))
@@ -234,10 +231,10 @@ ScriptString XMLHttpRequest::responseJSONSource()
return m_responseText;
}
-Document* XMLHttpRequest::responseXML(ExceptionState& es)
+Document* XMLHttpRequest::responseXML(ExceptionState& exceptionState)
{
if (m_responseTypeCode != ResponseTypeDefault && m_responseTypeCode != ResponseTypeDocument) {
- es.throwDOMException(InvalidStateError, ExceptionMessages::failedToGet("responseXML", "XMLHttpRequest", "the value is only accessible if the object's 'responseType' is '' or 'document' (was '" + responseType() + "')."));
+ exceptionState.throwDOMException(InvalidStateError, "The value is only accessible if the object's 'responseType' is '' or 'document' (was '" + responseType() + "').");
return 0;
}
@@ -251,7 +248,7 @@ Document* XMLHttpRequest::responseXML(ExceptionState& es)
// If it is text/html, then the responseType of "document" must have been supplied explicitly.
if ((m_response.isHTTP() && !responseIsXML() && !isHTML)
|| (isHTML && m_responseTypeCode == ResponseTypeDefault)
- || scriptExecutionContext()->isWorkerGlobalScope()) {
+ || executionContext()->isWorkerGlobalScope()) {
m_responseDocument = 0;
} else {
DocumentInit init = DocumentInit::fromContext(document()->contextDocument(), m_url);
@@ -275,31 +272,26 @@ Document* XMLHttpRequest::responseXML(ExceptionState& es)
Blob* XMLHttpRequest::responseBlob()
{
ASSERT(m_responseTypeCode == ResponseTypeBlob);
+ ASSERT(!m_binaryResponseBuilder.get());
// We always return null before DONE.
if (m_error || m_state != DONE)
return 0;
if (!m_responseBlob) {
- // FIXME: This causes two (or more) unnecessary copies of the data.
- // Chromium stores blob data in the browser process, so we're pulling the data
- // from the network only to copy it into the renderer to copy it back to the browser.
- // Ideally we'd get the blob/file-handle from the ResourceResponse directly
- // instead of copying the bytes. Embedders who store blob data in the
- // same process as WebCore would at least to teach BlobData to take
- // a SharedBuffer, even if they don't get the Blob from the network layer directly.
+ // When "blob" is specified for the responseType attribute,
+ // we redirect the downloaded data to a file-handle directly
+ // in the browser process.
+ // We get the file-path from the ResourceResponse directly
+ // instead of copying the bytes between the browser and the renderer.
OwnPtr<BlobData> blobData = BlobData::create();
+ String filePath = m_response.downloadedFilePath();
// If we errored out or got no data, we still return a blob, just an empty one.
- size_t size = 0;
- if (m_binaryResponseBuilder) {
- RefPtr<RawData> rawData = RawData::create();
- size = m_binaryResponseBuilder->size();
- rawData->mutableData()->append(m_binaryResponseBuilder->data(), size);
- blobData->appendData(rawData, 0, BlobDataItem::toEndOfFile);
+ if (!filePath.isEmpty() && m_downloadedBlobLength) {
+ blobData->appendFile(filePath);
blobData->setContentType(responseMIMEType()); // responseMIMEType defaults to text/xml which may be incorrect.
- m_binaryResponseBuilder.clear();
}
- m_responseBlob = Blob::create(blobData.release(), size);
+ m_responseBlob = Blob::create(BlobDataHandle::create(blobData.release(), m_downloadedBlobLength));
}
return m_responseBlob.get();
@@ -334,21 +326,21 @@ Stream* XMLHttpRequest::responseStream()
return m_responseStream.get();
}
-void XMLHttpRequest::setTimeout(unsigned long timeout, ExceptionState& es)
+void XMLHttpRequest::setTimeout(unsigned long timeout, ExceptionState& exceptionState)
{
// FIXME: Need to trigger or update the timeout Timer here, if needed. http://webkit.org/b/98156
// XHR2 spec, 4.7.3. "This implies that the timeout attribute can be set while fetching is in progress. If that occurs it will still be measured relative to the start of fetching."
- if (scriptExecutionContext()->isDocument() && !m_async) {
- es.throwDOMException(InvalidAccessError, ExceptionMessages::failedToSet("timeout", "XMLHttpRequest", "timeouts cannot be set for synchronous requests made from a document."));
+ if (executionContext()->isDocument() && !m_async) {
+ exceptionState.throwDOMException(InvalidAccessError, "Timeouts cannot be set for synchronous requests made from a document.");
return;
}
m_timeoutMilliseconds = timeout;
}
-void XMLHttpRequest::setResponseType(const String& responseType, ExceptionState& es)
+void XMLHttpRequest::setResponseType(const String& responseType, ExceptionState& exceptionState)
{
if (m_state >= LOADING) {
- es.throwDOMException(InvalidStateError, ExceptionMessages::failedToSet("responseType", "XMLHttpRequest", "the response type cannot be set if the object's state is LOADING or DONE."));
+ exceptionState.throwDOMException(InvalidStateError, "The response type cannot be set if the object's state is LOADING or DONE.");
return;
}
@@ -356,8 +348,8 @@ void XMLHttpRequest::setResponseType(const String& responseType, ExceptionState&
// attempt to discourage synchronous XHR use. responseType is one such piece of functionality.
// We'll only disable this functionality for HTTP(S) requests since sync requests for local protocols
// such as file: and data: still make sense to allow.
- if (!m_async && scriptExecutionContext()->isDocument() && m_url.protocolIsInHTTPFamily()) {
- es.throwDOMException(InvalidAccessError, ExceptionMessages::failedToSet("responseType", "XMLHttpRequest", "the response type can only be changed for asynchronous HTTP requests made from a document."));
+ if (!m_async && executionContext()->isDocument() && m_url.protocolIsInHTTPFamily()) {
+ exceptionState.throwDOMException(InvalidAccessError, "The response type can only be changed for asynchronous HTTP requests made from a document.");
return;
}
@@ -411,37 +403,64 @@ XMLHttpRequestUpload* XMLHttpRequest::upload()
return m_upload.get();
}
+void XMLHttpRequest::trackProgress(int length)
+{
+ m_receivedLength += length;
+
+ if (m_async)
+ dispatchThrottledProgressEventSnapshot(EventTypeNames::progress);
+
+ if (m_state != LOADING) {
+ changeState(LOADING);
+ } else {
+ // Firefox calls readyStateChanged every time it receives data. Do
+ // the same to align with Firefox.
+ //
+ // FIXME: Make our implementation and the spec consistent. This
+ // behavior was needed when the progress event was not available.
+ dispatchReadyStateChangeEvent();
+ }
+}
+
void XMLHttpRequest::changeState(State newState)
{
if (m_state != newState) {
m_state = newState;
- callReadyStateChangeListener();
+ dispatchReadyStateChangeEvent();
}
}
-void XMLHttpRequest::callReadyStateChangeListener()
+void XMLHttpRequest::dispatchReadyStateChangeEvent()
{
- if (!scriptExecutionContext())
+ if (!executionContext())
return;
- InspectorInstrumentationCookie cookie = InspectorInstrumentation::willDispatchXHRReadyStateChangeEvent(scriptExecutionContext(), this);
+ InspectorInstrumentationCookie cookie = InspectorInstrumentation::willDispatchXHRReadyStateChangeEvent(executionContext(), this);
- if (m_async || (m_state <= OPENED || m_state == DONE))
- m_progressEventThrottle.dispatchReadyStateChangeEvent(XMLHttpRequestProgressEvent::create(eventNames().readystatechangeEvent), m_state == DONE ? FlushProgressEvent : DoNotFlushProgressEvent);
+ if (m_async || (m_state <= OPENED || m_state == DONE)) {
+ ProgressEventAction flushAction = DoNotFlushProgressEvent;
+ if (m_state == DONE) {
+ if (m_error)
+ flushAction = FlushDeferredProgressEvent;
+ else
+ flushAction = FlushProgressEvent;
+ }
+ m_progressEventThrottle.dispatchReadyStateChangeEvent(XMLHttpRequestProgressEvent::create(EventTypeNames::readystatechange), flushAction);
+ }
InspectorInstrumentation::didDispatchXHRReadyStateChangeEvent(cookie);
if (m_state == DONE && !m_error) {
- InspectorInstrumentationCookie cookie = InspectorInstrumentation::willDispatchXHRLoadEvent(scriptExecutionContext(), this);
- m_progressEventThrottle.dispatchEvent(XMLHttpRequestProgressEvent::create(eventNames().loadEvent));
+ InspectorInstrumentationCookie cookie = InspectorInstrumentation::willDispatchXHRLoadEvent(executionContext(), this);
+ dispatchThrottledProgressEventSnapshot(EventTypeNames::load);
InspectorInstrumentation::didDispatchXHRLoadEvent(cookie);
- m_progressEventThrottle.dispatchEvent(XMLHttpRequestProgressEvent::create(eventNames().loadendEvent));
+ dispatchThrottledProgressEventSnapshot(EventTypeNames::loadend);
}
}
-void XMLHttpRequest::setWithCredentials(bool value, ExceptionState& es)
+void XMLHttpRequest::setWithCredentials(bool value, ExceptionState& exceptionState)
{
if (m_state > OPENED || m_loader) {
- es.throwDOMException(InvalidStateError, ExceptionMessages::failedToSet("withCredentials", "XMLHttpRequest", "the value may only be set if the object's state is UNSENT or OPENED."));
+ exceptionState.throwDOMException(InvalidStateError, "The value may only be set if the object's state is UNSENT or OPENED.");
return;
}
@@ -455,14 +474,31 @@ bool XMLHttpRequest::isAllowedHTTPMethod(const String& method)
&& !equalIgnoringCase(method, "CONNECT");
}
-String XMLHttpRequest::uppercaseKnownHTTPMethod(const String& method)
-{
- if (equalIgnoringCase(method, "COPY") || equalIgnoringCase(method, "DELETE") || equalIgnoringCase(method, "GET")
- || equalIgnoringCase(method, "HEAD") || equalIgnoringCase(method, "INDEX") || equalIgnoringCase(method, "LOCK")
- || equalIgnoringCase(method, "M-POST") || equalIgnoringCase(method, "MKCOL") || equalIgnoringCase(method, "MOVE")
- || equalIgnoringCase(method, "OPTIONS") || equalIgnoringCase(method, "POST") || equalIgnoringCase(method, "PROPFIND")
- || equalIgnoringCase(method, "PROPPATCH") || equalIgnoringCase(method, "PUT") || equalIgnoringCase(method, "UNLOCK")) {
- return method.upper();
+AtomicString XMLHttpRequest::uppercaseKnownHTTPMethod(const AtomicString& method)
+{
+ const char* const methods[] = {
+ "COPY",
+ "DELETE",
+ "GET",
+ "HEAD",
+ "INDEX",
+ "LOCK",
+ "M-POST",
+ "MKCOL",
+ "MOVE",
+ "OPTIONS",
+ "POST",
+ "PROPFIND",
+ "PROPPATCH",
+ "PUT",
+ "UNLOCK" };
+ for (unsigned i = 0; i < WTF_ARRAY_LENGTH(methods); ++i) {
+ if (equalIgnoringCase(method, methods[i])) {
+ // Don't bother allocating a new string if it's already all uppercase.
+ if (method == methods[i])
+ return method;
+ return methods[i];
+ }
}
return method;
}
@@ -474,13 +510,15 @@ bool XMLHttpRequest::isAllowedHTTPHeader(const String& name)
&& !name.startsWith(staticData->m_secHeaderPrefix, false);
}
-void XMLHttpRequest::open(const String& method, const KURL& url, ExceptionState& es)
+void XMLHttpRequest::open(const AtomicString& method, const KURL& url, ExceptionState& exceptionState)
{
- open(method, url, true, es);
+ open(method, url, true, exceptionState);
}
-void XMLHttpRequest::open(const String& method, const KURL& url, bool async, ExceptionState& es)
+void XMLHttpRequest::open(const AtomicString& method, const KURL& url, bool async, ExceptionState& exceptionState)
{
+ WTF_LOG(Network, "XMLHttpRequest %p open('%s', '%s', %d)", this, method.string().utf8().data(), url.elidedString().utf8().data(), async);
+
if (!internalAbort())
return;
@@ -496,24 +534,24 @@ void XMLHttpRequest::open(const String& method, const KURL& url, bool async, Exc
ASSERT(m_state == UNSENT);
if (!isValidHTTPToken(method)) {
- es.throwDOMException(SyntaxError, ExceptionMessages::failedToExecute("open", "XMLHttpRequest", "'" + method + "' is not a valid HTTP method."));
+ exceptionState.throwDOMException(SyntaxError, "'" + method + "' is not a valid HTTP method.");
return;
}
if (!isAllowedHTTPMethod(method)) {
- es.throwSecurityError(ExceptionMessages::failedToExecute("open", "XMLHttpRequest", "'" + method + "' HTTP method is unsupported."));
+ exceptionState.throwSecurityError("'" + method + "' HTTP method is unsupported.");
return;
}
- if (!ContentSecurityPolicy::shouldBypassMainWorld(scriptExecutionContext()) && !scriptExecutionContext()->contentSecurityPolicy()->allowConnectToSource(url)) {
+ if (!ContentSecurityPolicy::shouldBypassMainWorld(executionContext()) && !executionContext()->contentSecurityPolicy()->allowConnectToSource(url)) {
// We can safely expose the URL to JavaScript, as these checks happen synchronously before redirection. JavaScript receives no new information.
- es.throwSecurityError("Refused to connect to '" + url.elidedString() + "' because it violates the document's Content Security Policy.");
+ exceptionState.throwSecurityError("Refused to connect to '" + url.elidedString() + "' because it violates the document's Content Security Policy.");
return;
}
- if (!async && scriptExecutionContext()->isDocument()) {
+ if (!async && executionContext()->isDocument()) {
if (document()->settings() && !document()->settings()->syncXHRInDocumentsEnabled()) {
- es.throwDOMException(InvalidAccessError, ExceptionMessages::failedToExecute("open", "XMLHttpRequest", "synchronous requests are disabled for this page."));
+ exceptionState.throwDOMException(InvalidAccessError, "Synchronous requests are disabled for this page.");
return;
}
@@ -522,13 +560,13 @@ void XMLHttpRequest::open(const String& method, const KURL& url, bool async, Exc
// We'll only disable this functionality for HTTP(S) requests since sync requests for local protocols
// such as file: and data: still make sense to allow.
if (url.protocolIsInHTTPFamily() && m_responseTypeCode != ResponseTypeDefault) {
- es.throwDOMException(InvalidAccessError, ExceptionMessages::failedToExecute("open", "XMLHttpRequest", "synchronous HTTP requests from a document must not set a response type."));
+ exceptionState.throwDOMException(InvalidAccessError, "Synchronous HTTP requests from a document must not set a response type.");
return;
}
// Similarly, timeouts are disabled for synchronous requests as well.
if (m_timeoutMilliseconds > 0) {
- es.throwDOMException(InvalidAccessError, ExceptionMessages::failedToExecute("open", "XMLHttpRequest", "synchronous requests must not set a timeout."));
+ exceptionState.throwDOMException(InvalidAccessError, "Synchronous requests must not set a timeout.");
return;
}
}
@@ -549,30 +587,30 @@ void XMLHttpRequest::open(const String& method, const KURL& url, bool async, Exc
m_state = OPENED;
}
-void XMLHttpRequest::open(const String& method, const KURL& url, bool async, const String& user, ExceptionState& es)
+void XMLHttpRequest::open(const AtomicString& method, const KURL& url, bool async, const String& user, ExceptionState& exceptionState)
{
KURL urlWithCredentials(url);
urlWithCredentials.setUser(user);
- open(method, urlWithCredentials, async, es);
+ open(method, urlWithCredentials, async, exceptionState);
}
-void XMLHttpRequest::open(const String& method, const KURL& url, bool async, const String& user, const String& password, ExceptionState& es)
+void XMLHttpRequest::open(const AtomicString& method, const KURL& url, bool async, const String& user, const String& password, ExceptionState& exceptionState)
{
KURL urlWithCredentials(url);
urlWithCredentials.setUser(user);
urlWithCredentials.setPass(password);
- open(method, urlWithCredentials, async, es);
+ open(method, urlWithCredentials, async, exceptionState);
}
-bool XMLHttpRequest::initSend(ExceptionState& es)
+bool XMLHttpRequest::initSend(ExceptionState& exceptionState)
{
- if (!scriptExecutionContext())
+ if (!executionContext())
return false;
if (m_state != OPENED || m_loader) {
- es.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("send", "XMLHttpRequest", "the object's state must be OPENED."));
+ exceptionState.throwDOMException(InvalidStateError, "The object's state must be OPENED.");
return false;
}
@@ -580,9 +618,9 @@ bool XMLHttpRequest::initSend(ExceptionState& es)
return true;
}
-void XMLHttpRequest::send(ExceptionState& es)
+void XMLHttpRequest::send(ExceptionState& exceptionState)
{
- send(String(), es);
+ send(String(), exceptionState);
}
bool XMLHttpRequest::areMethodAndURLValidForSend()
@@ -590,16 +628,17 @@ bool XMLHttpRequest::areMethodAndURLValidForSend()
return m_method != "GET" && m_method != "HEAD" && m_url.protocolIsInHTTPFamily();
}
-void XMLHttpRequest::send(Document* document, ExceptionState& es)
+void XMLHttpRequest::send(Document* document, ExceptionState& exceptionState)
{
+ WTF_LOG(Network, "XMLHttpRequest %p send() Document %p", this, document);
+
ASSERT(document);
- if (!initSend(es))
+ if (!initSend(exceptionState))
return;
if (areMethodAndURLValidForSend()) {
- String contentType = getRequestHeader("Content-Type");
- if (contentType.isEmpty()) {
+ if (getRequestHeader("Content-Type").isEmpty()) {
// FIXME: this should include the charset used for encoding.
setRequestHeaderInternal("Content-Type", "application/xml");
}
@@ -614,12 +653,14 @@ void XMLHttpRequest::send(Document* document, ExceptionState& es)
m_requestEntityBody->setAlwaysStream(true);
}
- createRequest(es);
+ createRequest(exceptionState);
}
-void XMLHttpRequest::send(const String& body, ExceptionState& es)
+void XMLHttpRequest::send(const String& body, ExceptionState& exceptionState)
{
- if (!initSend(es))
+ WTF_LOG(Network, "XMLHttpRequest %p send() String '%s'", this, body.utf8().data());
+
+ if (!initSend(exceptionState))
return;
if (!body.isNull() && areMethodAndURLValidForSend()) {
@@ -628,7 +669,7 @@ void XMLHttpRequest::send(const String& body, ExceptionState& es)
setRequestHeaderInternal("Content-Type", "text/plain;charset=UTF-8");
} else {
replaceCharsetInMediaType(contentType, "UTF-8");
- m_requestHeaders.set("Content-Type", contentType);
+ m_requestHeaders.set("Content-Type", AtomicString(contentType));
}
m_requestEntityBody = FormData::create(UTF8Encoding().encode(body, WTF::EntitiesForUnencodables));
@@ -636,20 +677,21 @@ void XMLHttpRequest::send(const String& body, ExceptionState& es)
m_requestEntityBody->setAlwaysStream(true);
}
- createRequest(es);
+ createRequest(exceptionState);
}
-void XMLHttpRequest::send(Blob* body, ExceptionState& es)
+void XMLHttpRequest::send(Blob* body, ExceptionState& exceptionState)
{
- if (!initSend(es))
+ WTF_LOG(Network, "XMLHttpRequest %p send() Blob '%s'", this, body->uuid().utf8().data());
+
+ if (!initSend(exceptionState))
return;
if (areMethodAndURLValidForSend()) {
- const String& contentType = getRequestHeader("Content-Type");
- if (contentType.isEmpty()) {
+ if (getRequestHeader("Content-Type").isEmpty()) {
const String& blobType = body->type();
if (!blobType.isEmpty() && isValidContentType(blobType))
- setRequestHeaderInternal("Content-Type", blobType);
+ setRequestHeaderInternal("Content-Type", AtomicString(blobType));
else {
// From FileAPI spec, whenever media type cannot be determined, empty string must be returned.
setRequestHeaderInternal("Content-Type", "");
@@ -658,53 +700,58 @@ void XMLHttpRequest::send(Blob* body, ExceptionState& es)
// FIXME: add support for uploading bundles.
m_requestEntityBody = FormData::create();
- if (body->isFile())
+ if (body->hasBackingFile())
m_requestEntityBody->appendFile(toFile(body)->path());
else
- m_requestEntityBody->appendBlob(body->url());
+ m_requestEntityBody->appendBlob(body->uuid(), body->blobDataHandle());
}
- createRequest(es);
+ createRequest(exceptionState);
}
-void XMLHttpRequest::send(DOMFormData* body, ExceptionState& es)
+void XMLHttpRequest::send(DOMFormData* body, ExceptionState& exceptionState)
{
- if (!initSend(es))
+ WTF_LOG(Network, "XMLHttpRequest %p send() DOMFormData %p", this, body);
+
+ if (!initSend(exceptionState))
return;
if (areMethodAndURLValidForSend()) {
- m_requestEntityBody = FormData::createMultiPart(*(static_cast<FormDataList*>(body)), body->encoding(), document());
+ m_requestEntityBody = body->createMultiPartFormData(body->encoding());
- String contentType = getRequestHeader("Content-Type");
- if (contentType.isEmpty()) {
- contentType = String("multipart/form-data; boundary=") + m_requestEntityBody->boundary().data();
+ if (getRequestHeader("Content-Type").isEmpty()) {
+ AtomicString contentType = AtomicString("multipart/form-data; boundary=", AtomicString::ConstructFromLiteral) + m_requestEntityBody->boundary().data();
setRequestHeaderInternal("Content-Type", contentType);
}
}
- createRequest(es);
+ createRequest(exceptionState);
}
-void XMLHttpRequest::send(ArrayBuffer* body, ExceptionState& es)
+void XMLHttpRequest::send(ArrayBuffer* body, ExceptionState& exceptionState)
{
+ WTF_LOG(Network, "XMLHttpRequest %p send() ArrayBuffer %p", this, body);
+
String consoleMessage("ArrayBuffer is deprecated in XMLHttpRequest.send(). Use ArrayBufferView instead.");
- scriptExecutionContext()->addConsoleMessage(JSMessageSource, WarningMessageLevel, consoleMessage);
+ executionContext()->addConsoleMessage(JSMessageSource, WarningMessageLevel, consoleMessage);
- HistogramSupport::histogramEnumeration("WebCore.XHR.send.ArrayBufferOrView", XMLHttpRequestSendArrayBuffer, XMLHttpRequestSendArrayBufferOrViewMax);
+ blink::Platform::current()->histogramEnumeration("WebCore.XHR.send.ArrayBufferOrView", XMLHttpRequestSendArrayBuffer, XMLHttpRequestSendArrayBufferOrViewMax);
- sendBytesData(body->data(), body->byteLength(), es);
+ sendBytesData(body->data(), body->byteLength(), exceptionState);
}
-void XMLHttpRequest::send(ArrayBufferView* body, ExceptionState& es)
+void XMLHttpRequest::send(ArrayBufferView* body, ExceptionState& exceptionState)
{
- HistogramSupport::histogramEnumeration("WebCore.XHR.send.ArrayBufferOrView", XMLHttpRequestSendArrayBufferView, XMLHttpRequestSendArrayBufferOrViewMax);
+ WTF_LOG(Network, "XMLHttpRequest %p send() ArrayBufferView %p", this, body);
+
+ blink::Platform::current()->histogramEnumeration("WebCore.XHR.send.ArrayBufferOrView", XMLHttpRequestSendArrayBufferView, XMLHttpRequestSendArrayBufferOrViewMax);
- sendBytesData(body->baseAddress(), body->byteLength(), es);
+ sendBytesData(body->baseAddress(), body->byteLength(), exceptionState);
}
-void XMLHttpRequest::sendBytesData(const void* data, size_t length, ExceptionState& es)
+void XMLHttpRequest::sendBytesData(const void* data, size_t length, ExceptionState& exceptionState)
{
- if (!initSend(es))
+ if (!initSend(exceptionState))
return;
if (areMethodAndURLValidForSend()) {
@@ -713,21 +760,21 @@ void XMLHttpRequest::sendBytesData(const void* data, size_t length, ExceptionSta
m_requestEntityBody->setAlwaysStream(true);
}
- createRequest(es);
+ createRequest(exceptionState);
}
-void XMLHttpRequest::sendForInspectorXHRReplay(PassRefPtr<FormData> formData, ExceptionState& es)
+void XMLHttpRequest::sendForInspectorXHRReplay(PassRefPtr<FormData> formData, ExceptionState& exceptionState)
{
m_requestEntityBody = formData ? formData->deepCopy() : 0;
- createRequest(es);
- m_exceptionCode = es.code();
+ createRequest(exceptionState);
+ m_exceptionCode = exceptionState.code();
}
-void XMLHttpRequest::createRequest(ExceptionState& es)
+void XMLHttpRequest::createRequest(ExceptionState& exceptionState)
{
// Only GET request is supported for blob URL.
if (m_url.protocolIs("blob") && m_method != "GET") {
- es.throwDOMException(NetworkError, ExceptionMessages::failedToExecute("send", "XMLHttpRequest", "'GET' is the only method allowed for 'blob:' URLs."));
+ exceptionState.throwDOMException(NetworkError, "'GET' is the only method allowed for 'blob:' URLs.");
return;
}
@@ -736,10 +783,10 @@ void XMLHttpRequest::createRequest(ExceptionState& es)
// Also, only async requests support upload progress events.
bool uploadEvents = false;
if (m_async) {
- m_progressEventThrottle.dispatchEvent(XMLHttpRequestProgressEvent::create(eventNames().loadstartEvent));
+ m_progressEventThrottle.dispatchEvent(XMLHttpRequestProgressEvent::create(EventTypeNames::loadstart));
if (m_requestEntityBody && m_upload) {
uploadEvents = m_upload->hasEventListeners();
- m_upload->dispatchEvent(XMLHttpRequestProgressEvent::create(eventNames().loadstartEvent));
+ m_upload->dispatchEvent(XMLHttpRequestProgressEvent::create(EventTypeNames::loadstart));
}
}
@@ -753,7 +800,13 @@ void XMLHttpRequest::createRequest(ExceptionState& es)
request.setHTTPMethod(m_method);
request.setTargetType(ResourceRequest::TargetIsXHR);
- InspectorInstrumentation::willLoadXHR(scriptExecutionContext(), this, m_method, m_url, m_async, m_requestEntityBody ? m_requestEntityBody->deepCopy() : 0, m_requestHeaders, m_includeCredentials);
+ // When "blob" is specified for the responseType attribute,
+ // we redirect the downloaded data to a file-handle directly
+ // and get the file-path as the result.
+ if (responseTypeCode() == ResponseTypeBlob)
+ request.setDownloadToFile(true);
+
+ InspectorInstrumentation::willLoadXHR(executionContext(), this, this, m_method, m_url, m_async, m_requestEntityBody ? m_requestEntityBody->deepCopy() : 0, m_requestHeaders, m_includeCredentials);
if (m_requestEntityBody) {
ASSERT(m_method != "GET");
@@ -773,11 +826,17 @@ void XMLHttpRequest::createRequest(ExceptionState& es)
options.crossOriginRequestPolicy = UseAccessControl;
options.securityOrigin = securityOrigin();
options.initiator = FetchInitiatorTypeNames::xmlhttprequest;
- options.contentSecurityPolicyEnforcement = ContentSecurityPolicy::shouldBypassMainWorld(scriptExecutionContext()) ? DoNotEnforceContentSecurityPolicy : EnforceConnectSrcDirective;
+ options.contentSecurityPolicyEnforcement = ContentSecurityPolicy::shouldBypassMainWorld(executionContext()) ? DoNotEnforceContentSecurityPolicy : EnforceConnectSrcDirective;
// TODO(tsepez): Specify TreatAsActiveContent per http://crbug.com/305303.
options.mixedContentBlockingTreatment = TreatAsPassiveContent;
options.timeoutMilliseconds = m_timeoutMilliseconds;
+ // Since we redirect the downloaded data to a file-handle directly
+ // when "blob" is specified for the responseType attribute,
+ // buffering is not needed.
+ if (responseTypeCode() == ResponseTypeBlob)
+ options.dataBufferingPolicy = DoNotBufferData;
+
m_exceptionCode = 0;
m_error = false;
@@ -790,7 +849,7 @@ void XMLHttpRequest::createRequest(ExceptionState& es)
// FIXME: Maybe we need to be able to send XMLHttpRequests from onunload, <http://bugs.webkit.org/show_bug.cgi?id=10904>.
// FIXME: Maybe create() can return null for other reasons too?
ASSERT(!m_loader);
- m_loader = ThreadableLoader::create(scriptExecutionContext(), this, request, options);
+ m_loader = ThreadableLoader::create(executionContext(), this, request, options);
if (m_loader) {
// Neither this object nor the JavaScript wrapper should be deleted while
// a request is in progress because we need to keep the listeners alive,
@@ -798,55 +857,57 @@ void XMLHttpRequest::createRequest(ExceptionState& es)
setPendingActivity(this);
}
} else {
- ThreadableLoader::loadResourceSynchronously(scriptExecutionContext(), request, *this, options);
+ ThreadableLoader::loadResourceSynchronously(executionContext(), request, *this, options);
}
if (!m_exceptionCode && m_error)
m_exceptionCode = NetworkError;
if (m_exceptionCode)
- es.throwDOMException(m_exceptionCode);
+ exceptionState.throwUninformativeAndGenericDOMException(m_exceptionCode);
}
void XMLHttpRequest::abort()
{
+ WTF_LOG(Network, "XMLHttpRequest %p abort()", this);
+
// internalAbort() calls dropProtection(), which may release the last reference.
RefPtr<XMLHttpRequest> protect(this);
bool sendFlag = m_loader;
+ // Response is cleared next, save needed progress event data.
+ long long expectedLength = m_response.expectedContentLength();
+ long long receivedLength = m_receivedLength;
+
if (!internalAbort())
return;
- clearResponseBuffers();
+ clearResponse();
// Clear headers as required by the spec
m_requestHeaders.clear();
- if ((m_state <= OPENED && !sendFlag) || m_state == DONE)
- m_state = UNSENT;
- else {
+ if (!((m_state <= OPENED && !sendFlag) || m_state == DONE)) {
ASSERT(!m_loader);
- changeState(DONE);
- m_state = UNSENT;
+ handleRequestError(0, EventTypeNames::abort, receivedLength, expectedLength);
}
+ m_state = UNSENT;
+}
- m_progressEventThrottle.dispatchEventAndLoadEnd(XMLHttpRequestProgressEvent::create(eventNames().abortEvent));
- if (!m_uploadComplete) {
- m_uploadComplete = true;
- if (m_upload && m_uploadEventsAllowed)
- m_upload->dispatchEventAndLoadEnd(XMLHttpRequestProgressEvent::create(eventNames().abortEvent));
- }
+void XMLHttpRequest::clearVariablesForLoading()
+{
+ m_decoder.clear();
+
+ m_responseEncoding = String();
}
bool XMLHttpRequest::internalAbort(DropProtection async)
{
m_error = true;
- // FIXME: when we add the support for multi-part XHR, we will have to think be careful with this initialization.
- m_receivedLength = 0;
- m_decoder = 0;
+ clearVariablesForLoading();
- InspectorInstrumentation::didFailXHRLoading(scriptExecutionContext(), this);
+ InspectorInstrumentation::didFailXHRLoading(executionContext(), this, this);
if (m_responseStream && m_state != DONE)
m_responseStream->abort();
@@ -871,6 +932,12 @@ bool XMLHttpRequest::internalAbort(DropProtection async)
// Save to a local variable since we're going to drop protection.
bool newLoadStarted = m_loader;
+ // If abort() called internalAbort() and a nested open() ended up
+ // clearing the error flag, but didn't send(), make sure the error
+ // flag is still set.
+ if (!newLoadStarted)
+ m_error = true;
+
if (async == DropProtectionAsync)
dropProtectionSoon();
else
@@ -881,18 +948,23 @@ bool XMLHttpRequest::internalAbort(DropProtection async)
void XMLHttpRequest::clearResponse()
{
+ // FIXME: when we add the support for multi-part XHR, we will have to
+ // be careful with this initialization.
+ m_receivedLength = 0;
+
m_response = ResourceResponse();
- clearResponseBuffers();
-}
-void XMLHttpRequest::clearResponseBuffers()
-{
m_responseText.clear();
- m_responseEncoding = String();
+
m_createdDocument = false;
m_responseDocument = 0;
+
m_responseBlob = 0;
+
m_responseStream = 0;
+
+ // These variables may referred by the response accessors. So, we can clear
+ // this only when we clear the response holder variables above.
m_binaryResponseBuilder.clear();
m_responseArrayBuffer.clear();
}
@@ -911,108 +983,142 @@ void XMLHttpRequest::handleDidFailGeneric()
m_error = true;
}
-void XMLHttpRequest::dispatchEventAndLoadEnd(const AtomicString& type)
+void XMLHttpRequest::dispatchEventAndLoadEnd(const AtomicString& type, long long receivedLength, long long expectedLength)
{
- if (!m_uploadComplete) {
- m_uploadComplete = true;
- if (m_upload && m_uploadEventsAllowed)
- m_upload->dispatchEventAndLoadEnd(XMLHttpRequestProgressEvent::create(type));
- }
- m_progressEventThrottle.dispatchEventAndLoadEnd(XMLHttpRequestProgressEvent::create(type));
+ bool lengthComputable = expectedLength > 0 && receivedLength <= expectedLength;
+ unsigned long long loaded = receivedLength >= 0 ? static_cast<unsigned long long>(receivedLength) : 0;
+ unsigned long long total = lengthComputable ? static_cast<unsigned long long>(expectedLength) : 0;
+
+ m_progressEventThrottle.dispatchEventAndLoadEnd(type, lengthComputable, loaded, total);
}
-void XMLHttpRequest::handleNetworkError()
+void XMLHttpRequest::dispatchThrottledProgressEvent(const AtomicString& type, long long receivedLength, long long expectedLength)
{
- m_exceptionCode = NetworkError;
+ bool lengthComputable = expectedLength > 0 && receivedLength <= expectedLength;
+ unsigned long long loaded = receivedLength >= 0 ? static_cast<unsigned long long>(receivedLength) : 0;
+ unsigned long long total = lengthComputable ? static_cast<unsigned long long>(expectedLength) : 0;
- handleDidFailGeneric();
+ if (type == EventTypeNames::progress)
+ m_progressEventThrottle.dispatchProgressEvent(lengthComputable, loaded, total);
+ else
+ m_progressEventThrottle.dispatchEvent(XMLHttpRequestProgressEvent::create(type, lengthComputable, loaded, total));
+}
- if (m_async) {
- changeState(DONE);
- dispatchEventAndLoadEnd(eventNames().errorEvent);
- } else {
- m_state = DONE;
- }
+void XMLHttpRequest::dispatchThrottledProgressEventSnapshot(const AtomicString& type)
+{
+ return dispatchThrottledProgressEvent(type, m_receivedLength, m_response.expectedContentLength());
+}
+void XMLHttpRequest::handleNetworkError()
+{
+ WTF_LOG(Network, "XMLHttpRequest %p handleNetworkError()", this);
+
+ // Response is cleared next, save needed progress event data.
+ long long expectedLength = m_response.expectedContentLength();
+ long long receivedLength = m_receivedLength;
+
+ handleDidFailGeneric();
+ handleRequestError(NetworkError, EventTypeNames::error, receivedLength, expectedLength);
internalAbort();
}
void XMLHttpRequest::handleDidCancel()
{
- m_exceptionCode = AbortError;
+ WTF_LOG(Network, "XMLHttpRequest %p handleDidCancel()", this);
+
+ // Response is cleared next, save needed progress event data.
+ long long expectedLength = m_response.expectedContentLength();
+ long long receivedLength = m_receivedLength;
handleDidFailGeneric();
+ handleRequestError(AbortError, EventTypeNames::abort, receivedLength, expectedLength);
+}
+
+void XMLHttpRequest::handleRequestError(ExceptionCode exceptionCode, const AtomicString& type, long long receivedLength, long long expectedLength)
+{
+ WTF_LOG(Network, "XMLHttpRequest %p handleRequestError()", this);
+
+ // The request error steps for event 'type' and exception 'exceptionCode'.
- if (!m_async) {
+ if (!m_async && exceptionCode) {
m_state = DONE;
+ m_exceptionCode = exceptionCode;
return;
}
+ // With m_error set, the state change steps are minimal: any pending
+ // progress event is flushed + a readystatechange is dispatched.
+ // No new progress events dispatched; as required, that happens at
+ // the end here.
+ ASSERT(m_error);
changeState(DONE);
- dispatchEventAndLoadEnd(eventNames().abortEvent);
+ if (!m_uploadComplete) {
+ m_uploadComplete = true;
+ if (m_upload && m_uploadEventsAllowed)
+ m_upload->handleRequestError(type);
+ }
+
+ dispatchThrottledProgressEvent(EventTypeNames::progress, receivedLength, expectedLength);
+ dispatchEventAndLoadEnd(type, receivedLength, expectedLength);
}
void XMLHttpRequest::dropProtectionSoon()
{
- if (m_protectionTimer.isActive())
- return;
- m_protectionTimer.startOneShot(0);
+ m_dropProtectionRunner.runAsync();
}
-void XMLHttpRequest::dropProtection(Timer<XMLHttpRequest>*)
+void XMLHttpRequest::dropProtection()
{
unsetPendingActivity(this);
}
-void XMLHttpRequest::overrideMimeType(const String& override)
+void XMLHttpRequest::overrideMimeType(const AtomicString& override)
{
m_mimeTypeOverride = override;
}
-void XMLHttpRequest::setRequestHeader(const AtomicString& name, const String& value, ExceptionState& es)
+void XMLHttpRequest::setRequestHeader(const AtomicString& name, const AtomicString& value, ExceptionState& exceptionState)
{
if (m_state != OPENED || m_loader) {
- es.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("setRequestHeader", "XMLHttpRequest", "the object's state must be OPENED."));
+ exceptionState.throwDOMException(InvalidStateError, "The object's state must be OPENED.");
return;
}
if (!isValidHTTPToken(name)) {
- es.throwDOMException(SyntaxError, ExceptionMessages::failedToExecute("setRequestHeader", "XMLHttpRequest", "'" + name + "' is not a valid HTTP header field name."));
+ exceptionState.throwDOMException(SyntaxError, "'" + name + "' is not a valid HTTP header field name.");
return;
}
if (!isValidHTTPHeaderValue(value)) {
- es.throwDOMException(SyntaxError, ExceptionMessages::failedToExecute("setRequestHeader", "XMLHttpRequest", "'" + value + "' is not a valid HTTP header field value."));
+ exceptionState.throwDOMException(SyntaxError, "'" + value + "' is not a valid HTTP header field value.");
return;
}
// No script (privileged or not) can set unsafe headers.
if (!isAllowedHTTPHeader(name)) {
- logConsoleError(scriptExecutionContext(), "Refused to set unsafe header \"" + name + "\"");
+ logConsoleError(executionContext(), "Refused to set unsafe header \"" + name + "\"");
return;
}
setRequestHeaderInternal(name, value);
}
-void XMLHttpRequest::setRequestHeaderInternal(const AtomicString& name, const String& value)
+void XMLHttpRequest::setRequestHeaderInternal(const AtomicString& name, const AtomicString& value)
{
HTTPHeaderMap::AddResult result = m_requestHeaders.add(name, value);
if (!result.isNewEntry)
result.iterator->value = result.iterator->value + ", " + value;
}
-String XMLHttpRequest::getRequestHeader(const AtomicString& name) const
+const AtomicString& XMLHttpRequest::getRequestHeader(const AtomicString& name) const
{
return m_requestHeaders.get(name);
}
-String XMLHttpRequest::getAllResponseHeaders(ExceptionState& es) const
+String XMLHttpRequest::getAllResponseHeaders() const
{
- if (m_state < HEADERS_RECEIVED) {
- es.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("getAllResponseHeaders", "XMLHttpRequest", "the object's state must not be UNSENT or OPENED."));
+ if (m_state < HEADERS_RECEIVED || m_error)
return "";
- }
StringBuilder stringBuilder;
@@ -1043,32 +1149,30 @@ String XMLHttpRequest::getAllResponseHeaders(ExceptionState& es) const
return stringBuilder.toString();
}
-String XMLHttpRequest::getResponseHeader(const AtomicString& name, ExceptionState& es) const
+const AtomicString& XMLHttpRequest::getResponseHeader(const AtomicString& name) const
{
- if (m_state < HEADERS_RECEIVED) {
- es.throwDOMException(InvalidStateError, ExceptionMessages::failedToExecute("getResponseHeader", "XMLHttpRequest", "the object's state must not be UNSENT or OPENED."));
- return String();
- }
+ if (m_state < HEADERS_RECEIVED || m_error)
+ return nullAtom;
// See comment in getAllResponseHeaders above.
if (isSetCookieHeader(name) && !securityOrigin()->canLoadLocalResources()) {
- logConsoleError(scriptExecutionContext(), "Refused to get unsafe header \"" + name + "\"");
- return String();
+ logConsoleError(executionContext(), "Refused to get unsafe header \"" + name + "\"");
+ return nullAtom;
}
HTTPHeaderSet accessControlExposeHeaderSet;
parseAccessControlExposeHeadersAllowList(m_response.httpHeaderField("Access-Control-Expose-Headers"), accessControlExposeHeaderSet);
if (!m_sameOriginRequest && !isOnAccessControlResponseHeaderWhitelist(name) && !accessControlExposeHeaderSet.contains(name)) {
- logConsoleError(scriptExecutionContext(), "Refused to get unsafe header \"" + name + "\"");
- return String();
+ logConsoleError(executionContext(), "Refused to get unsafe header \"" + name + "\"");
+ return nullAtom;
}
return m_response.httpHeaderField(name);
}
-String XMLHttpRequest::responseMIMEType() const
+AtomicString XMLHttpRequest::responseMIMEType() const
{
- String mimeType = extractMIMETypeFromMediaType(m_mimeTypeOverride);
+ AtomicString mimeType = extractMIMETypeFromMediaType(m_mimeTypeOverride);
if (mimeType.isEmpty()) {
if (m_response.isHTTP())
mimeType = extractMIMETypeFromMediaType(m_response.httpHeaderField("Content-Type"));
@@ -1076,7 +1180,7 @@ String XMLHttpRequest::responseMIMEType() const
mimeType = m_response.mimeType();
}
if (mimeType.isEmpty())
- mimeType = "text/xml";
+ mimeType = AtomicString("text/xml", AtomicString::ConstructFromLiteral);
return mimeType;
}
@@ -1088,35 +1192,32 @@ bool XMLHttpRequest::responseIsXML() const
return DOMImplementation::isXMLMIMEType(responseMIMEType().lower());
}
-int XMLHttpRequest::status(ExceptionState& es) const
+int XMLHttpRequest::status() const
{
+ if (m_state == UNSENT || m_state == OPENED || m_error)
+ return 0;
+
if (m_response.httpStatusCode())
return m_response.httpStatusCode();
- if (m_state == OPENED) {
- // Firefox only raises an exception in this state; we match it.
- // Note the case of local file requests, where we have no HTTP response code! Firefox never raises an exception for those, but we match HTTP case for consistency.
- es.throwDOMException(InvalidStateError, ExceptionMessages::failedToGet("status", "XMLHttpRequest", "the object's state must not be OPENED."));
- }
-
return 0;
}
-String XMLHttpRequest::statusText(ExceptionState& es) const
+String XMLHttpRequest::statusText() const
{
+ if (m_state == UNSENT || m_state == OPENED || m_error)
+ return String();
+
if (!m_response.httpStatusText().isNull())
return m_response.httpStatusText();
- if (m_state == OPENED) {
- // See comments in status() above.
- es.throwDOMException(InvalidStateError, ExceptionMessages::failedToGet("statusText", "XMLHttpRequest", "the object's state must not be OPENED."));
- }
-
return String();
}
void XMLHttpRequest::didFail(const ResourceError& error)
{
+ WTF_LOG(Network, "XMLHttpRequest %p didFail()", this);
+
// If we are already in an error state, for instance we called abort(), bail out early.
if (m_error)
return;
@@ -1132,19 +1233,23 @@ void XMLHttpRequest::didFail(const ResourceError& error)
}
// Network failures are already reported to Web Inspector by ResourceLoader.
- if (error.domain() == errorDomainWebKitInternal)
- logConsoleError(scriptExecutionContext(), "XMLHttpRequest cannot load " + error.failingURL() + ". " + error.localizedDescription());
+ if (error.domain() == errorDomainBlinkInternal)
+ logConsoleError(executionContext(), "XMLHttpRequest cannot load " + error.failingURL() + ". " + error.localizedDescription());
handleNetworkError();
}
void XMLHttpRequest::didFailRedirectCheck()
{
+ WTF_LOG(Network, "XMLHttpRequest %p didFailRedirectCheck()", this);
+
handleNetworkError();
}
void XMLHttpRequest::didFinishLoading(unsigned long identifier, double)
{
+ WTF_LOG(Network, "XMLHttpRequest %p didFinishLoading(%lu)", this, identifier);
+
if (m_error)
return;
@@ -1157,7 +1262,9 @@ void XMLHttpRequest::didFinishLoading(unsigned long identifier, double)
if (m_responseStream)
m_responseStream->finalize();
- InspectorInstrumentation::didFinishXHRLoading(scriptExecutionContext(), this, identifier, m_responseText, m_url, m_lastSendURL, m_lastSendLineNumber);
+ clearVariablesForLoading();
+
+ InspectorInstrumentation::didFinishXHRLoading(executionContext(), this, this, identifier, m_responseText, m_url, m_lastSendURL, m_lastSendLineNumber);
// Prevent dropProtection releasing the last reference, and retain |this| until the end of this method.
RefPtr<XMLHttpRequest> protect(this);
@@ -1168,28 +1275,28 @@ void XMLHttpRequest::didFinishLoading(unsigned long identifier, double)
}
changeState(DONE);
- m_responseEncoding = String();
- m_decoder = 0;
}
void XMLHttpRequest::didSendData(unsigned long long bytesSent, unsigned long long totalBytesToBeSent)
{
+ WTF_LOG(Network, "XMLHttpRequest %p didSendData(%llu, %llu)", this, bytesSent, totalBytesToBeSent);
+
if (!m_upload)
return;
if (m_uploadEventsAllowed)
- m_upload->dispatchEvent(XMLHttpRequestProgressEvent::create(eventNames().progressEvent, true, bytesSent, totalBytesToBeSent));
+ m_upload->dispatchProgressEvent(bytesSent, totalBytesToBeSent);
if (bytesSent == totalBytesToBeSent && !m_uploadComplete) {
m_uploadComplete = true;
if (m_uploadEventsAllowed)
- m_upload->dispatchEventAndLoadEnd(XMLHttpRequestProgressEvent::create(eventNames().loadEvent));
+ m_upload->dispatchEventAndLoadEnd(EventTypeNames::load, true, bytesSent, totalBytesToBeSent);
}
}
void XMLHttpRequest::didReceiveResponse(unsigned long identifier, const ResourceResponse& response)
{
- InspectorInstrumentation::didReceiveXHRResponse(scriptExecutionContext(), identifier);
+ WTF_LOG(Network, "XMLHttpRequest %p didReceiveResponse(%lu)", this, identifier);
m_response = response;
if (!m_mimeTypeOverride.isEmpty()) {
@@ -1203,6 +1310,8 @@ void XMLHttpRequest::didReceiveResponse(unsigned long identifier, const Resource
void XMLHttpRequest::didReceiveData(const char* data, int len)
{
+ ASSERT(m_responseTypeCode != ResponseTypeBlob);
+
if (m_error)
return;
@@ -1235,62 +1344,62 @@ void XMLHttpRequest::didReceiveData(const char* data, int len)
if (useDecoder) {
m_responseText = m_responseText.concatenateWith(m_decoder->decode(data, len));
- } else if (m_responseTypeCode == ResponseTypeArrayBuffer || m_responseTypeCode == ResponseTypeBlob) {
+ } else if (m_responseTypeCode == ResponseTypeArrayBuffer) {
// Buffer binary data.
if (!m_binaryResponseBuilder)
m_binaryResponseBuilder = SharedBuffer::create();
m_binaryResponseBuilder->append(data, len);
} else if (m_responseTypeCode == ResponseTypeStream) {
if (!m_responseStream)
- m_responseStream = Stream::create(responseMIMEType());
+ m_responseStream = Stream::create(executionContext(), responseMIMEType());
m_responseStream->addData(data, len);
}
- if (!m_error) {
- long long expectedLength = m_response.expectedContentLength();
- m_receivedLength += len;
-
- if (m_async) {
- bool lengthComputable = expectedLength > 0 && m_receivedLength <= expectedLength;
- unsigned long long total = lengthComputable ? expectedLength : 0;
- m_progressEventThrottle.dispatchProgressEvent(lengthComputable, m_receivedLength, total);
- }
+ if (m_error)
+ return;
- if (m_state != LOADING)
- changeState(LOADING);
- else
- // Firefox calls readyStateChanged every time it receives data, 4449442
- callReadyStateChangeListener();
- }
+ trackProgress(len);
}
-void XMLHttpRequest::handleDidTimeout()
+void XMLHttpRequest::didDownloadData(int dataLength)
{
- // internalAbort() calls dropProtection(), which may release the last reference.
- RefPtr<XMLHttpRequest> protect(this);
+ ASSERT(m_responseTypeCode == ResponseTypeBlob);
- if (!internalAbort())
+ if (m_error)
return;
- m_exceptionCode = TimeoutError;
+ if (m_state < HEADERS_RECEIVED)
+ changeState(HEADERS_RECEIVED);
- handleDidFailGeneric();
+ if (!dataLength)
+ return;
- if (!m_async) {
- m_state = DONE;
+ if (m_error)
return;
- }
- changeState(DONE);
- dispatchEventAndLoadEnd(eventNames().timeoutEvent);
+ m_downloadedBlobLength += dataLength;
+ trackProgress(dataLength);
}
-bool XMLHttpRequest::canSuspend() const
+void XMLHttpRequest::handleDidTimeout()
{
- return !m_loader;
+ WTF_LOG(Network, "XMLHttpRequest %p handleDidTimeout()", this);
+
+ // internalAbort() calls dropProtection(), which may release the last reference.
+ RefPtr<XMLHttpRequest> protect(this);
+
+ // Response is cleared next, save needed progress event data.
+ long long expectedLength = m_response.expectedContentLength();
+ long long receivedLength = m_receivedLength;
+
+ if (!internalAbort())
+ return;
+
+ handleDidFailGeneric();
+ handleRequestError(TimeoutError, EventTypeNames::timeout, receivedLength, expectedLength);
}
-void XMLHttpRequest::suspend(ReasonForSuspension)
+void XMLHttpRequest::suspend()
{
m_progressEventThrottle.suspend();
}
@@ -1313,12 +1422,12 @@ void XMLHttpRequest::contextDestroyed()
const AtomicString& XMLHttpRequest::interfaceName() const
{
- return eventNames().interfaceForXMLHttpRequest;
+ return EventTargetNames::XMLHttpRequest;
}
-ScriptExecutionContext* XMLHttpRequest::scriptExecutionContext() const
+ExecutionContext* XMLHttpRequest::executionContext() const
{
- return ActiveDOMObject::scriptExecutionContext();
+ return ActiveDOMObject::executionContext();
}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/xml/XMLHttpRequest.h b/chromium/third_party/WebKit/Source/core/xml/XMLHttpRequest.h
index 1f75c56e185..00bde33130b 100644
--- a/chromium/third_party/WebKit/Source/core/xml/XMLHttpRequest.h
+++ b/chromium/third_party/WebKit/Source/core/xml/XMLHttpRequest.h
@@ -25,14 +25,15 @@
#include "bindings/v8/ScriptString.h"
#include "bindings/v8/ScriptWrappable.h"
#include "core/dom/ActiveDOMObject.h"
-#include "core/dom/EventListener.h"
-#include "core/dom/EventNames.h"
+#include "core/events/EventListener.h"
+#include "core/events/ThreadLocalEventNames.h"
#include "core/loader/ThreadableLoaderClient.h"
-#include "core/platform/network/FormData.h"
-#include "core/platform/network/ResourceResponse.h"
#include "core/xml/XMLHttpRequestEventTarget.h"
#include "core/xml/XMLHttpRequestProgressEventThrottle.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/AsyncMethodRunner.h"
+#include "platform/network/FormData.h"
+#include "platform/network/ResourceResponse.h"
+#include "platform/weborigin/SecurityOrigin.h"
#include "wtf/OwnPtr.h"
#include "wtf/text/AtomicStringHash.h"
#include "wtf/text/StringBuilder.h"
@@ -54,8 +55,9 @@ typedef int ExceptionCode;
class XMLHttpRequest : public ScriptWrappable, public RefCounted<XMLHttpRequest>, public XMLHttpRequestEventTarget, private ThreadableLoaderClient, public ActiveDOMObject {
WTF_MAKE_FAST_ALLOCATED;
+ REFCOUNTED_EVENT_TARGET(XMLHttpRequest);
public:
- static PassRefPtr<XMLHttpRequest> create(ScriptExecutionContext*, PassRefPtr<SecurityOrigin> = 0);
+ static PassRefPtr<XMLHttpRequest> create(ExecutionContext*, PassRefPtr<SecurityOrigin> = 0);
~XMLHttpRequest();
// These exact numeric values are important because JS expects them.
@@ -83,24 +85,23 @@ public:
};
virtual void contextDestroyed();
- virtual bool canSuspend() const;
- virtual void suspend(ReasonForSuspension);
+ virtual void suspend();
virtual void resume();
virtual void stop();
virtual const AtomicString& interfaceName() const OVERRIDE;
- virtual ScriptExecutionContext* scriptExecutionContext() const OVERRIDE;
+ virtual ExecutionContext* executionContext() const OVERRIDE;
const KURL& url() const { return m_url; }
- String statusText(ExceptionState&) const;
- int status(ExceptionState&) const;
+ String statusText() const;
+ int status() const;
State readyState() const;
bool withCredentials() const { return m_includeCredentials; }
void setWithCredentials(bool, ExceptionState&);
- void open(const String& method, const KURL&, ExceptionState&);
- void open(const String& method, const KURL&, bool async, ExceptionState&);
- void open(const String& method, const KURL&, bool async, const String& user, ExceptionState&);
- void open(const String& method, const KURL&, bool async, const String& user, const String& password, ExceptionState&);
+ void open(const AtomicString& method, const KURL&, ExceptionState&);
+ void open(const AtomicString& method, const KURL&, bool async, ExceptionState&);
+ void open(const AtomicString& method, const KURL&, bool async, const String& user, ExceptionState&);
+ void open(const AtomicString& method, const KURL&, bool async, const String& user, const String& password, ExceptionState&);
void send(ExceptionState&);
void send(Document*, ExceptionState&);
void send(const String&, ExceptionState&);
@@ -109,10 +110,10 @@ public:
void send(ArrayBuffer*, ExceptionState&);
void send(ArrayBufferView*, ExceptionState&);
void abort();
- void setRequestHeader(const AtomicString& name, const String& value, ExceptionState&);
- void overrideMimeType(const String& override);
- String getAllResponseHeaders(ExceptionState&) const;
- String getResponseHeader(const AtomicString& name, ExceptionState&) const;
+ void setRequestHeader(const AtomicString& name, const AtomicString& value, ExceptionState&);
+ void overrideMimeType(const AtomicString& override);
+ String getAllResponseHeaders() const;
+ const AtomicString& getResponseHeader(const AtomicString&) const;
ScriptString responseText(ExceptionState&);
ScriptString responseJSONSource();
Document* responseXML(ExceptionState&);
@@ -125,7 +126,7 @@ public:
// Expose HTTP validation methods for other untrusted requests.
static bool isAllowedHTTPMethod(const String&);
- static String uppercaseKnownHTTPMethod(const String&);
+ static AtomicString uppercaseKnownHTTPMethod(const AtomicString&);
static bool isAllowedHTTPHeader(const String&);
void setResponseType(const String&, ExceptionState&);
@@ -142,14 +143,8 @@ public:
DEFINE_ATTRIBUTE_EVENT_LISTENER(readystatechange);
- using RefCounted<XMLHttpRequest>::ref;
- using RefCounted<XMLHttpRequest>::deref;
-
private:
- XMLHttpRequest(ScriptExecutionContext*, PassRefPtr<SecurityOrigin>);
-
- virtual void refEventTarget() OVERRIDE { ref(); }
- virtual void derefEventTarget() OVERRIDE { deref(); }
+ XMLHttpRequest(ExecutionContext*, PassRefPtr<SecurityOrigin>);
Document* document() const;
SecurityOrigin* securityOrigin() const;
@@ -157,11 +152,14 @@ private:
virtual void didSendData(unsigned long long bytesSent, unsigned long long totalBytesToBeSent);
virtual void didReceiveResponse(unsigned long identifier, const ResourceResponse&);
virtual void didReceiveData(const char* data, int dataLength);
+ // When "blob" is specified as the responseType attribute, didDownloadData
+ // is called instead of didReceiveData.
+ virtual void didDownloadData(int dataLength);
virtual void didFinishLoading(unsigned long identifier, double finishTime);
virtual void didFail(const ResourceError&);
virtual void didFailRedirectCheck();
- String responseMIMEType() const;
+ AtomicString responseMIMEType() const;
bool responseIsXML() const;
bool areMethodAndURLValidForSend();
@@ -169,26 +167,37 @@ private:
bool initSend(ExceptionState&);
void sendBytesData(const void*, size_t, ExceptionState&);
- String getRequestHeader(const AtomicString& name) const;
- void setRequestHeaderInternal(const AtomicString& name, const String& value);
+ const AtomicString& getRequestHeader(const AtomicString& name) const;
+ void setRequestHeaderInternal(const AtomicString& name, const AtomicString& value);
+ void trackProgress(int dataLength);
// Changes m_state and dispatches a readyStateChange event if new m_state
// value is different from last one.
void changeState(State newState);
- void callReadyStateChangeListener();
+ void dispatchReadyStateChangeEvent();
+
void dropProtectionSoon();
- void dropProtection(Timer<XMLHttpRequest>* = 0);
+ void dropProtection();
+ // Clears variables used only while the resource is being loaded.
+ void clearVariablesForLoading();
// Returns false iff reentry happened and a new load is started.
bool internalAbort(DropProtection = DropProtectionSync);
+ // Clears variables holding response header and body data.
void clearResponse();
- void clearResponseBuffers();
void clearRequest();
void createRequest(ExceptionState&);
- // Dispatches an event of the specified type to m_upload and
- // m_progressEventThrottle.
- void dispatchEventAndLoadEnd(const AtomicString&);
+ // Dispatches an event of the specified type to m_progressEventThrottle.
+ void dispatchEventAndLoadEnd(const AtomicString&, long long, long long);
+
+ // Dispatches a response progress event to m_progressEventThrottle.
+ void dispatchThrottledProgressEvent(const AtomicString&, long long, long long);
+
+ // Dispatches a response progress event using values sampled from
+ // m_receivedLength and m_response.
+ void dispatchThrottledProgressEventSnapshot(const AtomicString&);
+
// Does clean up common for all kind of didFail() call.
void handleDidFailGeneric();
// Handles didFail() call not caused by cancellation or timeout.
@@ -198,13 +207,15 @@ private:
// Handles didFail() call for timeout.
void handleDidTimeout();
+ void handleRequestError(ExceptionCode, const AtomicString&, long long, long long);
+
OwnPtr<XMLHttpRequestUpload> m_upload;
KURL m_url;
- String m_method;
+ AtomicString m_method;
HTTPHeaderMap m_requestHeaders;
RefPtr<FormData> m_requestEntityBody;
- String m_mimeTypeOverride;
+ AtomicString m_mimeTypeOverride;
bool m_async;
bool m_includeCredentials;
unsigned long m_timeoutMilliseconds;
@@ -217,14 +228,17 @@ private:
ResourceResponse m_response;
String m_responseEncoding;
- RefPtr<TextResourceDecoder> m_decoder;
+ OwnPtr<TextResourceDecoder> m_decoder;
ScriptString m_responseText;
- mutable bool m_createdDocument;
- mutable RefPtr<Document> m_responseDocument;
+ // Used to skip m_responseDocument creation if it's done previously. We need
+ // this separate flag since m_responseDocument can be 0 for some cases.
+ bool m_createdDocument;
+ RefPtr<Document> m_responseDocument;
RefPtr<SharedBuffer> m_binaryResponseBuilder;
- mutable RefPtr<ArrayBuffer> m_responseArrayBuffer;
+ long long m_downloadedBlobLength;
+ RefPtr<ArrayBuffer> m_responseArrayBuffer;
bool m_error;
@@ -247,7 +261,7 @@ private:
// An enum corresponding to the allowed string values for the responseType attribute.
ResponseTypeCode m_responseTypeCode;
- Timer<XMLHttpRequest> m_protectionTimer;
+ AsyncMethodRunner<XMLHttpRequest> m_dropProtectionRunner;
RefPtr<SecurityOrigin> m_securityOrigin;
};
diff --git a/chromium/third_party/WebKit/Source/core/xml/XMLHttpRequest.idl b/chromium/third_party/WebKit/Source/core/xml/XMLHttpRequest.idl
index 069129d0397..2fba4d654a1 100644
--- a/chromium/third_party/WebKit/Source/core/xml/XMLHttpRequest.idl
+++ b/chromium/third_party/WebKit/Source/core/xml/XMLHttpRequest.idl
@@ -37,11 +37,9 @@ enum XMLHttpRequestResponseType {
};
[
- GlobalContext=Window&WorkerGlobalScope,
ActiveDOMObject,
- Constructor,
- ConstructorCallWith=ScriptExecutionContext,
- CustomConstructor(optional XMLHttpRequestOptions options)
+ CustomConstructor(optional XMLHttpRequestOptions options),
+ GlobalContext=Window&WorkerGlobalScope,
] interface XMLHttpRequest : XMLHttpRequestEventTarget {
// event handler attributes
attribute EventHandler onreadystatechange;
@@ -53,14 +51,14 @@ enum XMLHttpRequestResponseType {
const unsigned short LOADING = 3;
const unsigned short DONE = 4;
- [SetterRaisesException] attribute unsigned long timeout;
+ [RaisesException=Setter] attribute unsigned long timeout;
readonly attribute unsigned short readyState;
- [SetterRaisesException] attribute boolean withCredentials;
+ [RaisesException=Setter] attribute boolean withCredentials;
- [Custom, ActivityLog=Access, RaisesException] void open(DOMString method, DOMString url, optional boolean async, optional DOMString user, optional DOMString password);
+ [Custom, ActivityLogging=ForAllWorlds, RaisesException] void open(DOMString method, DOMString url, optional boolean async, optional DOMString user, optional DOMString password);
- [ActivityLog=Access, RaisesException] void setRequestHeader(DOMString header, DOMString value);
+ [ActivityLogging=ForAllWorlds, RaisesException] void setRequestHeader(DOMString header, DOMString value);
[Custom, RaisesException] void send();
@@ -69,16 +67,16 @@ enum XMLHttpRequestResponseType {
readonly attribute XMLHttpRequestUpload upload;
// response
- [TreatReturnedNullStringAs=Undefined, RaisesException] DOMString getAllResponseHeaders();
- [TreatReturnedNullStringAs=Null, RaisesException] DOMString getResponseHeader(DOMString header);
- [CustomGetter, GetterRaisesException] readonly attribute DOMString responseText; // The custom getter implements TreatReturnedNullStringAs=Null
- [GetterRaisesException] readonly attribute Document responseXML;
+ [TreatReturnedNullStringAs=Undefined] DOMString getAllResponseHeaders();
+ [TreatReturnedNullStringAs=Null] DOMString getResponseHeader(DOMString header);
+ [Custom=Getter, RaisesException=Getter] readonly attribute DOMString responseText; // The custom getter implements TreatReturnedNullStringAs=Null
+ [RaisesException=Getter] readonly attribute Document responseXML;
- [SetterRaisesException] attribute XMLHttpRequestResponseType responseType;
- [CustomGetter, GetterRaisesException] readonly attribute Object response;
+ [RaisesException=Setter] attribute XMLHttpRequestResponseType responseType;
+ [Custom=Getter, RaisesException=Getter] readonly attribute object response;
- [GetterRaisesException] readonly attribute unsigned short status;
- [GetterRaisesException] readonly attribute DOMString statusText;
+ readonly attribute unsigned short status;
+ readonly attribute DOMString statusText;
// Extension
void overrideMimeType(DOMString override);
diff --git a/chromium/third_party/WebKit/Source/core/xml/XMLHttpRequestEventTarget.h b/chromium/third_party/WebKit/Source/core/xml/XMLHttpRequestEventTarget.h
index be91c5dcf8f..2d027abf148 100644
--- a/chromium/third_party/WebKit/Source/core/xml/XMLHttpRequestEventTarget.h
+++ b/chromium/third_party/WebKit/Source/core/xml/XMLHttpRequestEventTarget.h
@@ -31,11 +31,11 @@
#ifndef XMLHttpRequestEventTarget_h
#define XMLHttpRequestEventTarget_h
-#include "core/dom/EventTarget.h"
+#include "core/events/EventTarget.h"
namespace WebCore {
-class XMLHttpRequestEventTarget : public EventTarget {
+class XMLHttpRequestEventTarget : public EventTargetWithInlineData {
public:
DEFINE_ATTRIBUTE_EVENT_LISTENER(abort);
DEFINE_ATTRIBUTE_EVENT_LISTENER(error);
@@ -44,13 +44,6 @@ public:
DEFINE_ATTRIBUTE_EVENT_LISTENER(loadstart);
DEFINE_ATTRIBUTE_EVENT_LISTENER(progress);
DEFINE_ATTRIBUTE_EVENT_LISTENER(timeout);
-
-protected:
- virtual EventTargetData* eventTargetData() OVERRIDE { return &m_eventTargetData; }
- virtual EventTargetData* ensureEventTargetData() OVERRIDE { return &m_eventTargetData; }
-
-private:
- EventTargetData m_eventTargetData;
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/xml/XMLHttpRequestProgressEvent.h b/chromium/third_party/WebKit/Source/core/xml/XMLHttpRequestProgressEvent.h
index ddaf0bdd850..c6ab4a4dbd8 100644
--- a/chromium/third_party/WebKit/Source/core/xml/XMLHttpRequestProgressEvent.h
+++ b/chromium/third_party/WebKit/Source/core/xml/XMLHttpRequestProgressEvent.h
@@ -27,8 +27,8 @@
#ifndef XMLHttpRequestProgressEvent_h
#define XMLHttpRequestProgressEvent_h
-#include "core/dom/EventNames.h"
-#include "core/dom/ProgressEvent.h"
+#include "core/events/ProgressEvent.h"
+#include "core/events/ThreadLocalEventNames.h"
namespace WebCore {
@@ -47,7 +47,7 @@ public:
unsigned long long position() const { return loaded(); }
unsigned long long totalSize() const { return total(); }
- virtual const AtomicString& interfaceName() const { return eventNames().interfaceForXMLHttpRequestProgressEvent; }
+ virtual const AtomicString& interfaceName() const { return EventNames::XMLHttpRequestProgressEvent; }
private:
XMLHttpRequestProgressEvent()
diff --git a/chromium/third_party/WebKit/Source/core/xml/XMLHttpRequestProgressEventThrottle.cpp b/chromium/third_party/WebKit/Source/core/xml/XMLHttpRequestProgressEventThrottle.cpp
index 339d575d59b..9a3c16c0744 100644
--- a/chromium/third_party/WebKit/Source/core/xml/XMLHttpRequestProgressEventThrottle.cpp
+++ b/chromium/third_party/WebKit/Source/core/xml/XMLHttpRequestProgressEventThrottle.cpp
@@ -27,7 +27,7 @@
#include "config.h"
#include "core/xml/XMLHttpRequestProgressEventThrottle.h"
-#include "core/dom/EventTarget.h"
+#include "core/events/EventTarget.h"
#include "core/xml/XMLHttpRequestProgressEvent.h"
namespace WebCore {
@@ -52,7 +52,7 @@ void XMLHttpRequestProgressEventThrottle::dispatchProgressEvent(bool lengthCompu
{
if (m_deferEvents) {
// Only store the latest progress event while suspended.
- m_deferredProgressEvent = XMLHttpRequestProgressEvent::create(eventNames().progressEvent, lengthComputable, loaded, total);
+ m_deferredProgressEvent = XMLHttpRequestProgressEvent::create(EventTypeNames::progress, lengthComputable, loaded, total);
return;
}
@@ -64,7 +64,7 @@ void XMLHttpRequestProgressEventThrottle::dispatchProgressEvent(bool lengthCompu
ASSERT(!m_loaded);
ASSERT(!m_total);
- dispatchEvent(XMLHttpRequestProgressEvent::create(eventNames().progressEvent, lengthComputable, loaded, total));
+ dispatchEvent(XMLHttpRequestProgressEvent::create(EventTypeNames::progress, lengthComputable, loaded, total));
startRepeating(minimumProgressEventDispatchingIntervalInSeconds);
return;
}
@@ -77,8 +77,10 @@ void XMLHttpRequestProgressEventThrottle::dispatchProgressEvent(bool lengthCompu
void XMLHttpRequestProgressEventThrottle::dispatchReadyStateChangeEvent(PassRefPtr<Event> event, ProgressEventAction progressEventAction)
{
- if (progressEventAction == FlushProgressEvent)
- flushProgressEvent();
+ if (progressEventAction == FlushProgressEvent || progressEventAction == FlushDeferredProgressEvent) {
+ if (!flushDeferredProgressEvent() && progressEventAction == FlushProgressEvent)
+ deliverProgressEvent();
+ }
dispatchEvent(event);
}
@@ -87,7 +89,7 @@ void XMLHttpRequestProgressEventThrottle::dispatchEvent(PassRefPtr<Event> event)
{
ASSERT(event);
if (m_deferEvents) {
- if (m_deferredEvents.size() > 1 && event->type() == eventNames().readystatechangeEvent && event->type() == m_deferredEvents.last()->type()) {
+ if (m_deferredEvents.size() > 1 && event->type() == EventTypeNames::readystatechange && event->type() == m_deferredEvents.last()->type()) {
// Readystatechange events are state-less so avoid repeating two identical events in a row on resume.
return;
}
@@ -96,27 +98,31 @@ void XMLHttpRequestProgressEventThrottle::dispatchEvent(PassRefPtr<Event> event)
m_target->dispatchEvent(event);
}
-void XMLHttpRequestProgressEventThrottle::dispatchEventAndLoadEnd(PassRefPtr<Event> event)
+void XMLHttpRequestProgressEventThrottle::dispatchEventAndLoadEnd(const AtomicString& type, bool lengthComputable, unsigned long long bytesSent, unsigned long long total)
{
- ASSERT(event->type() == eventNames().loadEvent || event->type() == eventNames().abortEvent || event->type() == eventNames().errorEvent || event->type() == eventNames().timeoutEvent);
+ ASSERT(type == EventTypeNames::load || type == EventTypeNames::abort || type == EventTypeNames::error || type == EventTypeNames::timeout);
- dispatchEvent(event);
- dispatchEvent(XMLHttpRequestProgressEvent::create(eventNames().loadendEvent));
+ dispatchEvent(XMLHttpRequestProgressEvent::create(type, lengthComputable, bytesSent, total));
+ dispatchEvent(XMLHttpRequestProgressEvent::create(EventTypeNames::loadend, lengthComputable, bytesSent, total));
}
-void XMLHttpRequestProgressEventThrottle::flushProgressEvent()
+bool XMLHttpRequestProgressEventThrottle::flushDeferredProgressEvent()
{
if (m_deferEvents && m_deferredProgressEvent) {
// Move the progress event to the queue, to get it in the right order on resume.
m_deferredEvents.append(m_deferredProgressEvent);
m_deferredProgressEvent = 0;
- return;
+ return true;
}
+ return false;
+}
+void XMLHttpRequestProgressEventThrottle::deliverProgressEvent()
+{
if (!hasEventToDispatch())
return;
- PassRefPtr<Event> event = XMLHttpRequestProgressEvent::create(eventNames().progressEvent, m_lengthComputable, m_loaded, m_total);
+ PassRefPtr<Event> event = XMLHttpRequestProgressEvent::create(EventTypeNames::progress, m_lengthComputable, m_loaded, m_total);
m_loaded = 0;
m_total = 0;
@@ -159,7 +165,7 @@ void XMLHttpRequestProgressEventThrottle::fired()
return;
}
- dispatchEvent(XMLHttpRequestProgressEvent::create(eventNames().progressEvent, m_lengthComputable, m_loaded, m_total));
+ dispatchEvent(XMLHttpRequestProgressEvent::create(EventTypeNames::progress, m_lengthComputable, m_loaded, m_total));
m_total = 0;
m_loaded = 0;
}
@@ -186,7 +192,7 @@ void XMLHttpRequestProgressEventThrottle::suspend()
// If we have a progress event waiting to be dispatched,
// just defer it.
if (hasEventToDispatch()) {
- m_deferredProgressEvent = XMLHttpRequestProgressEvent::create(eventNames().progressEvent, m_lengthComputable, m_loaded, m_total);
+ m_deferredProgressEvent = XMLHttpRequestProgressEvent::create(EventTypeNames::progress, m_lengthComputable, m_loaded, m_total);
m_total = 0;
m_loaded = 0;
}
@@ -203,7 +209,7 @@ void XMLHttpRequestProgressEventThrottle::resume()
return;
}
- // Do not dispatch events inline here, since ScriptExecutionContext is iterating over
+ // Do not dispatch events inline here, since ExecutionContext is iterating over
// the list of active DOM objects to resume them, and any activated JS event-handler
// could insert new active DOM objects to the list.
// m_deferEvents is kept true until all deferred events have been dispatched.
diff --git a/chromium/third_party/WebKit/Source/core/xml/XMLHttpRequestProgressEventThrottle.h b/chromium/third_party/WebKit/Source/core/xml/XMLHttpRequestProgressEventThrottle.h
index 7cc993fedf8..36f5e3a3855 100644
--- a/chromium/third_party/WebKit/Source/core/xml/XMLHttpRequestProgressEventThrottle.h
+++ b/chromium/third_party/WebKit/Source/core/xml/XMLHttpRequestProgressEventThrottle.h
@@ -27,9 +27,10 @@
#ifndef XMLHttpRequestProgressEventThrottle_h
#define XMLHttpRequestProgressEventThrottle_h
-#include "core/platform/Timer.h"
+#include "platform/Timer.h"
#include "wtf/PassRefPtr.h"
#include "wtf/Vector.h"
+#include "wtf/text/AtomicString.h"
namespace WebCore {
@@ -38,6 +39,7 @@ class EventTarget;
enum ProgressEventAction {
DoNotFlushProgressEvent,
+ FlushDeferredProgressEvent,
FlushProgressEvent
};
@@ -51,7 +53,7 @@ public:
void dispatchProgressEvent(bool lengthComputable, unsigned long long loaded, unsigned long long total);
void dispatchReadyStateChangeEvent(PassRefPtr<Event>, ProgressEventAction = DoNotFlushProgressEvent);
void dispatchEvent(PassRefPtr<Event>);
- void dispatchEventAndLoadEnd(PassRefPtr<Event>);
+ void dispatchEventAndLoadEnd(const AtomicString&, bool, unsigned long long, unsigned long long);
void suspend();
void resume();
@@ -61,7 +63,8 @@ private:
virtual void fired();
void dispatchDeferredEvents(Timer<XMLHttpRequestProgressEventThrottle>*);
- void flushProgressEvent();
+ bool flushDeferredProgressEvent();
+ void deliverProgressEvent();
bool hasEventToDispatch() const;
diff --git a/chromium/third_party/WebKit/Source/core/xml/XMLHttpRequestUpload.cpp b/chromium/third_party/WebKit/Source/core/xml/XMLHttpRequestUpload.cpp
index 3e9f5cf1d11..b3497d54da5 100644
--- a/chromium/third_party/WebKit/Source/core/xml/XMLHttpRequestUpload.cpp
+++ b/chromium/third_party/WebKit/Source/core/xml/XMLHttpRequestUpload.cpp
@@ -26,9 +26,7 @@
#include "config.h"
#include "core/xml/XMLHttpRequestUpload.h"
-#include "core/dom/Event.h"
-#include "core/dom/EventNames.h"
-#include "core/xml/XMLHttpRequest.h"
+#include "core/events/Event.h"
#include "core/xml/XMLHttpRequestProgressEvent.h"
#include "wtf/Assertions.h"
#include "wtf/text/AtomicString.h"
@@ -37,28 +35,41 @@ namespace WebCore {
XMLHttpRequestUpload::XMLHttpRequestUpload(XMLHttpRequest* xmlHttpRequest)
: m_xmlHttpRequest(xmlHttpRequest)
+ , m_lastBytesSent(0)
+ , m_lastTotalBytesToBeSent(0)
{
ScriptWrappable::init(this);
}
const AtomicString& XMLHttpRequestUpload::interfaceName() const
{
- return eventNames().interfaceForXMLHttpRequestUpload;
+ return EventTargetNames::XMLHttpRequestUpload;
}
-ScriptExecutionContext* XMLHttpRequestUpload::scriptExecutionContext() const
+ExecutionContext* XMLHttpRequestUpload::executionContext() const
{
- return m_xmlHttpRequest->scriptExecutionContext();
+ return m_xmlHttpRequest->executionContext();
}
-void XMLHttpRequestUpload::dispatchEventAndLoadEnd(PassRefPtr<Event> event)
+void XMLHttpRequestUpload::dispatchProgressEvent(unsigned long long bytesSent, unsigned long long totalBytesToBeSent)
{
- ASSERT(event->type() == eventNames().loadEvent || event->type() == eventNames().abortEvent || event->type() == eventNames().errorEvent || event->type() == eventNames().timeoutEvent);
-
- dispatchEvent(event);
- dispatchEvent(XMLHttpRequestProgressEvent::create(eventNames().loadendEvent));
+ m_lastBytesSent = bytesSent;
+ m_lastTotalBytesToBeSent = totalBytesToBeSent;
+ dispatchEvent(XMLHttpRequestProgressEvent::create(EventTypeNames::progress, true, bytesSent, totalBytesToBeSent));
}
+void XMLHttpRequestUpload::dispatchEventAndLoadEnd(const AtomicString& type, bool lengthComputable, unsigned long long bytesSent, unsigned long long total)
+{
+ ASSERT(type == EventTypeNames::load || type == EventTypeNames::abort || type == EventTypeNames::error || type == EventTypeNames::timeout);
+ dispatchEvent(XMLHttpRequestProgressEvent::create(type, lengthComputable, bytesSent, total));
+ dispatchEvent(XMLHttpRequestProgressEvent::create(EventTypeNames::loadend, lengthComputable, bytesSent, total));
+}
+void XMLHttpRequestUpload::handleRequestError(const AtomicString& type)
+{
+ bool lengthComputable = m_lastTotalBytesToBeSent > 0 && m_lastBytesSent <= m_lastTotalBytesToBeSent;
+ dispatchEvent(XMLHttpRequestProgressEvent::create(EventTypeNames::progress, lengthComputable, m_lastBytesSent, m_lastTotalBytesToBeSent));
+ dispatchEventAndLoadEnd(type, lengthComputable, m_lastBytesSent, m_lastTotalBytesToBeSent);
+}
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/xml/XMLHttpRequestUpload.h b/chromium/third_party/WebKit/Source/core/xml/XMLHttpRequestUpload.h
index 408e3796977..d7a63da84c9 100644
--- a/chromium/third_party/WebKit/Source/core/xml/XMLHttpRequestUpload.h
+++ b/chromium/third_party/WebKit/Source/core/xml/XMLHttpRequestUpload.h
@@ -27,8 +27,8 @@
#define XMLHttpRequestUpload_h
#include "bindings/v8/ScriptWrappable.h"
-#include "core/dom/EventListener.h"
-#include "core/dom/EventNames.h"
+#include "core/events/EventListener.h"
+#include "core/events/ThreadLocalEventNames.h"
#include "core/xml/XMLHttpRequest.h"
#include "core/xml/XMLHttpRequestEventTarget.h"
#include "wtf/Forward.h"
@@ -41,7 +41,7 @@
namespace WebCore {
-class ScriptExecutionContext;
+class ExecutionContext;
class XMLHttpRequest;
class XMLHttpRequestUpload : public ScriptWrappable, public XMLHttpRequestEventTarget {
@@ -56,9 +56,12 @@ public:
XMLHttpRequest* xmlHttpRequest() const { return m_xmlHttpRequest; }
virtual const AtomicString& interfaceName() const OVERRIDE;
- virtual ScriptExecutionContext* scriptExecutionContext() const OVERRIDE;
+ virtual ExecutionContext* executionContext() const OVERRIDE;
- void dispatchEventAndLoadEnd(PassRefPtr<Event>);
+ void dispatchEventAndLoadEnd(const AtomicString&, bool, unsigned long long, unsigned long long);
+ void dispatchProgressEvent(unsigned long long, unsigned long long);
+
+ void handleRequestError(const AtomicString&);
private:
explicit XMLHttpRequestUpload(XMLHttpRequest*);
@@ -68,6 +71,11 @@ private:
XMLHttpRequest* m_xmlHttpRequest;
EventTargetData m_eventTargetData;
+
+ // Last progress event values; used when issuing the
+ // required 'progress' event on a request error or abort.
+ unsigned long long m_lastBytesSent;
+ unsigned long long m_lastTotalBytesToBeSent;
};
} // namespace WebCore
diff --git a/chromium/third_party/WebKit/Source/core/xml/XMLSerializer.cpp b/chromium/third_party/WebKit/Source/core/xml/XMLSerializer.cpp
index eb17e920b3a..7c42e56f1dd 100644
--- a/chromium/third_party/WebKit/Source/core/xml/XMLSerializer.cpp
+++ b/chromium/third_party/WebKit/Source/core/xml/XMLSerializer.cpp
@@ -29,10 +29,10 @@
namespace WebCore {
-String XMLSerializer::serializeToString(Node* node, ExceptionState& es)
+String XMLSerializer::serializeToString(Node* node, ExceptionState& exceptionState)
{
if (!node) {
- es.throwDOMException(TypeError, "Invalid node value.");
+ exceptionState.throwDOMException(TypeError, "Invalid node value.");
return String();
}
diff --git a/chromium/third_party/WebKit/Source/core/xml/XMLTreeViewer.cpp b/chromium/third_party/WebKit/Source/core/xml/XMLTreeViewer.cpp
index 04bfa132fb7..287f32d2054 100644
--- a/chromium/third_party/WebKit/Source/core/xml/XMLTreeViewer.cpp
+++ b/chromium/third_party/WebKit/Source/core/xml/XMLTreeViewer.cpp
@@ -37,7 +37,7 @@
#include "core/dom/Document.h"
#include "core/dom/Element.h"
#include "core/dom/Text.h"
-#include "core/page/Frame.h"
+#include "core/frame/Frame.h"
using namespace std;
@@ -52,9 +52,9 @@ void XMLTreeViewer::transformDocumentToTreeView()
{
m_document->setIsViewSource(true);
String scriptString(reinterpret_cast<const char*>(XMLViewer_js), sizeof(XMLViewer_js));
- m_document->frame()->script()->executeScriptInMainWorld(ScriptSourceCode(scriptString));
+ m_document->frame()->script().executeScriptInMainWorld(scriptString, ScriptController::ExecuteScriptWhenScriptsDisabled);
String noStyleMessage("This XML file does not appear to have any style information associated with it. The document tree is shown below.");
- m_document->frame()->script()->executeScriptInMainWorld(ScriptSourceCode("prepareWebKitXMLViewer('" + noStyleMessage + "');"));
+ m_document->frame()->script().executeScriptInMainWorld("prepareWebKitXMLViewer('" + noStyleMessage + "');", ScriptController::ExecuteScriptWhenScriptsDisabled);
String cssString(reinterpret_cast<const char*>(XMLViewer_css), sizeof(XMLViewer_css));
RefPtr<Text> text = m_document->createTextNode(cssString);
diff --git a/chromium/third_party/WebKit/Source/core/xml/XMLTreeViewer.h b/chromium/third_party/WebKit/Source/core/xml/XMLTreeViewer.h
index 73d404708ac..a9d0b0ef7f5 100644
--- a/chromium/third_party/WebKit/Source/core/xml/XMLTreeViewer.h
+++ b/chromium/third_party/WebKit/Source/core/xml/XMLTreeViewer.h
@@ -33,10 +33,9 @@ namespace WebCore {
class Document;
-class XMLTreeViewer {
+class XMLTreeViewer FINAL {
public:
explicit XMLTreeViewer(Document*);
- virtual ~XMLTreeViewer() {};
void transformDocumentToTreeView();
diff --git a/chromium/third_party/WebKit/Source/core/xml/XPathEvaluator.cpp b/chromium/third_party/WebKit/Source/core/xml/XPathEvaluator.cpp
index b9993e44d27..f87cc76b6d6 100644
--- a/chromium/third_party/WebKit/Source/core/xml/XPathEvaluator.cpp
+++ b/chromium/third_party/WebKit/Source/core/xml/XPathEvaluator.cpp
@@ -39,9 +39,9 @@ namespace WebCore {
using namespace XPath;
-PassRefPtr<XPathExpression> XPathEvaluator::createExpression(const String& expression, XPathNSResolver* resolver, ExceptionState& es)
+PassRefPtr<XPathExpression> XPathEvaluator::createExpression(const String& expression, PassRefPtr<XPathNSResolver> resolver, ExceptionState& exceptionState)
{
- return XPathExpression::createExpression(expression, resolver, es);
+ return XPathExpression::createExpression(expression, resolver, exceptionState);
}
PassRefPtr<XPathNSResolver> XPathEvaluator::createNSResolver(Node* nodeResolver)
@@ -50,18 +50,23 @@ PassRefPtr<XPathNSResolver> XPathEvaluator::createNSResolver(Node* nodeResolver)
}
PassRefPtr<XPathResult> XPathEvaluator::evaluate(const String& expression, Node* contextNode,
- XPathNSResolver* resolver, unsigned short type, XPathResult* result, ExceptionState& es)
+ PassRefPtr<XPathNSResolver> resolver, unsigned short type, XPathResult* result, ExceptionState& exceptionState)
{
+ if (!contextNode) {
+ exceptionState.throwDOMException(NotSupportedError, "The context node provided is null.");
+ return 0;
+ }
+
if (!isValidContextNode(contextNode)) {
- es.throwDOMException(NotSupportedError);
+ exceptionState.throwDOMException(NotSupportedError, "The node provided is '" + contextNode->nodeName() + "', which is not a valid context node type.");
return 0;
}
- RefPtr<XPathExpression> expr = createExpression(expression, resolver, es);
- if (es.hadException())
+ RefPtr<XPathExpression> expr = createExpression(expression, resolver, exceptionState);
+ if (exceptionState.hadException())
return 0;
- return expr->evaluate(contextNode, type, result, es);
+ return expr->evaluate(contextNode, type, result, exceptionState);
}
}
diff --git a/chromium/third_party/WebKit/Source/core/xml/XPathEvaluator.h b/chromium/third_party/WebKit/Source/core/xml/XPathEvaluator.h
index 6ad05dc9664..0c556e7e4d8 100644
--- a/chromium/third_party/WebKit/Source/core/xml/XPathEvaluator.h
+++ b/chromium/third_party/WebKit/Source/core/xml/XPathEvaluator.h
@@ -44,10 +44,10 @@ class XPathEvaluator : public RefCounted<XPathEvaluator>, public ScriptWrappable
public:
static PassRefPtr<XPathEvaluator> create() { return adoptRef(new XPathEvaluator); }
- PassRefPtr<XPathExpression> createExpression(const String& expression, XPathNSResolver*, ExceptionState&);
+ PassRefPtr<XPathExpression> createExpression(const String& expression, PassRefPtr<XPathNSResolver>, ExceptionState&);
PassRefPtr<XPathNSResolver> createNSResolver(Node* nodeResolver);
PassRefPtr<XPathResult> evaluate(const String& expression, Node* contextNode,
- XPathNSResolver*, unsigned short type, XPathResult*, ExceptionState&);
+ PassRefPtr<XPathNSResolver>, unsigned short type, XPathResult*, ExceptionState&);
private:
XPathEvaluator()
diff --git a/chromium/third_party/WebKit/Source/core/xml/XPathExpression.cpp b/chromium/third_party/WebKit/Source/core/xml/XPathExpression.cpp
index 920f6c93c87..ae2d7e1a56d 100644
--- a/chromium/third_party/WebKit/Source/core/xml/XPathExpression.cpp
+++ b/chromium/third_party/WebKit/Source/core/xml/XPathExpression.cpp
@@ -40,12 +40,12 @@ namespace WebCore {
using namespace XPath;
-PassRefPtr<XPathExpression> XPathExpression::createExpression(const String& expression, XPathNSResolver* resolver, ExceptionState& es)
+PassRefPtr<XPathExpression> XPathExpression::createExpression(const String& expression, PassRefPtr<XPathNSResolver> resolver, ExceptionState& exceptionState)
{
RefPtr<XPathExpression> expr = XPathExpression::create();
Parser parser;
- expr->m_topExpression = parser.parseStatement(expression, resolver, es);
+ expr->m_topExpression = parser.parseStatement(expression, resolver, exceptionState);
if (!expr->m_topExpression)
return 0;
@@ -57,10 +57,15 @@ XPathExpression::~XPathExpression()
delete m_topExpression;
}
-PassRefPtr<XPathResult> XPathExpression::evaluate(Node* contextNode, unsigned short type, XPathResult*, ExceptionState& es)
+PassRefPtr<XPathResult> XPathExpression::evaluate(Node* contextNode, unsigned short type, XPathResult*, ExceptionState& exceptionState)
{
+ if (!contextNode) {
+ exceptionState.throwDOMException(NotSupportedError, "The context node provided is null.");
+ return 0;
+ }
+
if (!isValidContextNode(contextNode)) {
- es.throwDOMException(NotSupportedError);
+ exceptionState.throwDOMException(NotSupportedError, "The node provided is '" + contextNode->nodeName() + "', which is not a valid context node type.");
return 0;
}
@@ -74,13 +79,13 @@ PassRefPtr<XPathResult> XPathExpression::evaluate(Node* contextNode, unsigned sh
if (evaluationContext.hadTypeConversionError) {
// It is not specified what to do if type conversion fails while evaluating an expression.
- es.throwDOMException(SyntaxError);
+ exceptionState.throwDOMException(SyntaxError, "Type conversion failed while evaluating the expression.");
return 0;
}
if (type != XPathResult::ANY_TYPE) {
- result->convertTo(type, es);
- if (es.hadException())
+ result->convertTo(type, exceptionState);
+ if (exceptionState.hadException())
return 0;
}
diff --git a/chromium/third_party/WebKit/Source/core/xml/XPathExpression.h b/chromium/third_party/WebKit/Source/core/xml/XPathExpression.h
index 083a3f51e54..64a3cd38ae5 100644
--- a/chromium/third_party/WebKit/Source/core/xml/XPathExpression.h
+++ b/chromium/third_party/WebKit/Source/core/xml/XPathExpression.h
@@ -48,7 +48,7 @@ public:
static PassRefPtr<XPathExpression> create() { return adoptRef(new XPathExpression); }
~XPathExpression();
- static PassRefPtr<XPathExpression> createExpression(const String& expression, XPathNSResolver*, ExceptionState&);
+ static PassRefPtr<XPathExpression> createExpression(const String& expression, PassRefPtr<XPathNSResolver>, ExceptionState&);
PassRefPtr<XPathResult> evaluate(Node* contextNode, unsigned short type, XPathResult*, ExceptionState&);
private:
diff --git a/chromium/third_party/WebKit/Source/core/xml/XPathExpressionNode.cpp b/chromium/third_party/WebKit/Source/core/xml/XPathExpressionNode.cpp
index 524a48d65d4..e952bd0c9c9 100644
--- a/chromium/third_party/WebKit/Source/core/xml/XPathExpressionNode.cpp
+++ b/chromium/third_party/WebKit/Source/core/xml/XPathExpressionNode.cpp
@@ -27,7 +27,6 @@
#include "config.h"
#include "core/xml/XPathExpressionNode.h"
-#include "core/dom/Node.h"
#include "wtf/StdLibExtras.h"
namespace WebCore {
@@ -48,7 +47,6 @@ Expression::Expression()
Expression::~Expression()
{
- deleteAllValues(m_subExpressions);
}
}
diff --git a/chromium/third_party/WebKit/Source/core/xml/XPathExpressionNode.h b/chromium/third_party/WebKit/Source/core/xml/XPathExpressionNode.h
index 7101a562edf..62d2c86b488 100644
--- a/chromium/third_party/WebKit/Source/core/xml/XPathExpressionNode.h
+++ b/chromium/third_party/WebKit/Source/core/xml/XPathExpressionNode.h
@@ -63,12 +63,12 @@ namespace WebCore {
virtual Value evaluate() const = 0;
- void addSubExpression(Expression* expr)
+ void addSubExpression(PassOwnPtr<Expression> expr)
{
- m_subExpressions.append(expr);
m_isContextNodeSensitive |= expr->m_isContextNodeSensitive;
m_isContextPositionSensitive |= expr->m_isContextPositionSensitive;
m_isContextSizeSensitive |= expr->m_isContextSizeSensitive;
+ m_subExpressions.append(expr);
}
bool isContextNodeSensitive() const { return m_isContextNodeSensitive; }
@@ -82,11 +82,11 @@ namespace WebCore {
protected:
unsigned subExprCount() const { return m_subExpressions.size(); }
- Expression* subExpr(unsigned i) { return m_subExpressions[i]; }
- const Expression* subExpr(unsigned i) const { return m_subExpressions[i]; }
+ Expression* subExpr(unsigned i) { return m_subExpressions[i].get(); }
+ const Expression* subExpr(unsigned i) const { return m_subExpressions[i].get(); }
private:
- Vector<Expression*> m_subExpressions;
+ Vector<OwnPtr<Expression> > m_subExpressions;
// Evaluation details that can be used for optimization.
bool m_isContextNodeSensitive;
diff --git a/chromium/third_party/WebKit/Source/core/xml/XPathFunctions.cpp b/chromium/third_party/WebKit/Source/core/xml/XPathFunctions.cpp
index 55004df0f12..978d858b6bb 100644
--- a/chromium/third_party/WebKit/Source/core/xml/XPathFunctions.cpp
+++ b/chromium/third_party/WebKit/Source/core/xml/XPathFunctions.cpp
@@ -290,7 +290,7 @@ inline bool Interval::contains(int value) const
return value >= m_min && value <= m_max;
}
-void Function::setArguments(const Vector<Expression*>& args)
+void Function::setArguments(Vector<OwnPtr<Expression> >& args)
{
ASSERT(!subExprCount());
@@ -298,9 +298,9 @@ void Function::setArguments(const Vector<Expression*>& args)
if (m_name != "lang" && !args.isEmpty())
setIsContextNodeSensitive(false);
- Vector<Expression*>::const_iterator end = args.end();
- for (Vector<Expression*>::const_iterator it = args.begin(); it != end; it++)
- addSubExpression(*it);
+ Vector<OwnPtr<Expression> >::iterator end = args.end();
+ for (Vector<OwnPtr<Expression> >::iterator it = args.begin(); it != end; it++)
+ addSubExpression(it->release());
}
Value FunLast::evaluate() const
@@ -712,7 +712,14 @@ static void createFunctionMap()
functionMap->set(functions[i].name, functions[i].function);
}
-Function* createFunction(const String& name, const Vector<Expression*>& args)
+
+Function* createFunction(const String& name)
+{
+ Vector<OwnPtr<Expression> > args;
+ return createFunction(name, args);
+}
+
+Function* createFunction(const String& name, Vector<OwnPtr<Expression> >& args)
{
if (!functionMap)
createFunctionMap();
diff --git a/chromium/third_party/WebKit/Source/core/xml/XPathFunctions.h b/chromium/third_party/WebKit/Source/core/xml/XPathFunctions.h
index 0482884374c..1e2ee4de5bf 100644
--- a/chromium/third_party/WebKit/Source/core/xml/XPathFunctions.h
+++ b/chromium/third_party/WebKit/Source/core/xml/XPathFunctions.h
@@ -35,7 +35,7 @@ namespace WebCore {
class Function : public Expression {
public:
- void setArguments(const Vector<Expression*>&);
+ void setArguments(Vector<OwnPtr<Expression> >&);
void setName(const String& name) { m_name = name; }
protected:
Expression* arg(int pos) { return subExpr(pos); }
@@ -47,7 +47,8 @@ namespace WebCore {
String m_name;
};
- Function* createFunction(const String& name, const Vector<Expression*>& args = Vector<Expression*>());
+ Function* createFunction(const String& name);
+ Function* createFunction(const String& name, Vector<OwnPtr<Expression> >&);
} // namespace XPath
diff --git a/chromium/third_party/WebKit/Source/core/xml/XPathGrammar.y b/chromium/third_party/WebKit/Source/core/xml/XPathGrammar.y
index a4f5b692cff..6911fcfe601 100644
--- a/chromium/third_party/WebKit/Source/core/xml/XPathGrammar.y
+++ b/chromium/third_party/WebKit/Source/core/xml/XPathGrammar.y
@@ -62,8 +62,8 @@ using namespace XPath;
EqTestOp::Opcode eqop;
String* str;
Expression* expr;
- Vector<Predicate*>* predList;
- Vector<Expression*>* argList;
+ Vector<OwnPtr<Predicate> >* predList;
+ Vector<OwnPtr<Expression> >* argList;
Step* step;
LocationPath* locationPath;
}
@@ -192,8 +192,8 @@ Step:
|
NAMETEST OptionalPredicateList
{
- String localName;
- String namespaceURI;
+ AtomicString localName;
+ AtomicString namespaceURI;
if (!parser->expandQName(*$1, localName, namespaceURI)) {
parser->m_gotNamespaceError = true;
YYABORT;
@@ -221,8 +221,8 @@ Step:
|
AxisSpecifier NAMETEST OptionalPredicateList
{
- String localName;
- String namespaceURI;
+ AtomicString localName;
+ AtomicString namespaceURI;
if (!parser->expandQName(*$2, localName, namespaceURI)) {
parser->m_gotNamespaceError = true;
YYABORT;
@@ -291,15 +291,15 @@ OptionalPredicateList:
PredicateList:
Predicate
{
- $$ = new Vector<Predicate*>;
- $$->append(new Predicate($1));
+ $$ = new Vector<OwnPtr<Predicate> >;
+ $$->append(adoptPtr(new Predicate(adoptPtr($1))));
parser->unregisterParseNode($1);
parser->registerPredicateVector($$);
}
|
PredicateList Predicate
{
- $$->append(new Predicate($2));
+ $$->append(adoptPtr(new Predicate(adoptPtr($2))));
parser->unregisterParseNode($2);
}
;
@@ -387,15 +387,15 @@ FunctionCall:
ArgumentList:
Argument
{
- $$ = new Vector<Expression*>;
- $$->append($1);
+ $$ = new Vector<OwnPtr<Expression> >;
+ $$->append(adoptPtr($1));
parser->unregisterParseNode($1);
parser->registerExpressionVector($$);
}
|
ArgumentList ',' Argument
{
- $$->append($3);
+ $$->append(adoptPtr($3));
parser->unregisterParseNode($3);
}
;
@@ -410,8 +410,8 @@ UnionExpr:
UnionExpr '|' PathExpr
{
$$ = new Union;
- $$->addSubExpression($1);
- $$->addSubExpression($3);
+ $$->addSubExpression(adoptPtr($1));
+ $$->addSubExpression(adoptPtr($3));
parser->unregisterParseNode($1);
parser->unregisterParseNode($3);
parser->registerParseNode($$);
@@ -429,7 +429,7 @@ PathExpr:
FilterExpr '/' RelativeLocationPath
{
$3->setAbsolute(true);
- $$ = new Path(static_cast<Filter*>($1), $3);
+ $$ = new Path($1, $3);
parser->unregisterParseNode($1);
parser->unregisterParseNode($3);
parser->registerParseNode($$);
@@ -439,7 +439,7 @@ PathExpr:
{
$3->insertFirstStep($2);
$3->setAbsolute(true);
- $$ = new Path(static_cast<Filter*>($1), $3);
+ $$ = new Path($1, $3);
parser->unregisterParseNode($1);
parser->unregisterParseNode($2);
parser->unregisterParseNode($3);
@@ -452,7 +452,7 @@ FilterExpr:
|
PrimaryExpr PredicateList
{
- $$ = new Filter($1, *$2);
+ $$ = new Filter(adoptPtr($1), *$2);
parser->unregisterParseNode($1);
parser->deletePredicateVector($2);
parser->registerParseNode($$);
@@ -464,7 +464,7 @@ OrExpr:
|
OrExpr OR AndExpr
{
- $$ = new LogicalOp(LogicalOp::OP_Or, $1, $3);
+ $$ = new LogicalOp(LogicalOp::OP_Or, adoptPtr($1), adoptPtr($3));
parser->unregisterParseNode($1);
parser->unregisterParseNode($3);
parser->registerParseNode($$);
@@ -476,7 +476,7 @@ AndExpr:
|
AndExpr AND EqualityExpr
{
- $$ = new LogicalOp(LogicalOp::OP_And, $1, $3);
+ $$ = new LogicalOp(LogicalOp::OP_And, adoptPtr($1), adoptPtr($3));
parser->unregisterParseNode($1);
parser->unregisterParseNode($3);
parser->registerParseNode($$);
@@ -488,7 +488,7 @@ EqualityExpr:
|
EqualityExpr EQOP RelationalExpr
{
- $$ = new EqTestOp($2, $1, $3);
+ $$ = new EqTestOp($2, adoptPtr($1), adoptPtr($3));
parser->unregisterParseNode($1);
parser->unregisterParseNode($3);
parser->registerParseNode($$);
@@ -500,7 +500,7 @@ RelationalExpr:
|
RelationalExpr RELOP AdditiveExpr
{
- $$ = new EqTestOp($2, $1, $3);
+ $$ = new EqTestOp($2, adoptPtr($1), adoptPtr($3));
parser->unregisterParseNode($1);
parser->unregisterParseNode($3);
parser->registerParseNode($$);
@@ -512,7 +512,7 @@ AdditiveExpr:
|
AdditiveExpr PLUS MultiplicativeExpr
{
- $$ = new NumericOp(NumericOp::OP_Add, $1, $3);
+ $$ = new NumericOp(NumericOp::OP_Add, adoptPtr($1), adoptPtr($3));
parser->unregisterParseNode($1);
parser->unregisterParseNode($3);
parser->registerParseNode($$);
@@ -520,7 +520,7 @@ AdditiveExpr:
|
AdditiveExpr MINUS MultiplicativeExpr
{
- $$ = new NumericOp(NumericOp::OP_Sub, $1, $3);
+ $$ = new NumericOp(NumericOp::OP_Sub, adoptPtr($1), adoptPtr($3));
parser->unregisterParseNode($1);
parser->unregisterParseNode($3);
parser->registerParseNode($$);
@@ -532,7 +532,7 @@ MultiplicativeExpr:
|
MultiplicativeExpr MULOP UnaryExpr
{
- $$ = new NumericOp($2, $1, $3);
+ $$ = new NumericOp($2, adoptPtr($1), adoptPtr($3));
parser->unregisterParseNode($1);
parser->unregisterParseNode($3);
parser->registerParseNode($$);
@@ -545,7 +545,7 @@ UnaryExpr:
MINUS UnaryExpr
{
$$ = new Negative;
- $$->addSubExpression($2);
+ $$->addSubExpression(adoptPtr($2));
parser->unregisterParseNode($2);
parser->registerParseNode($$);
}
diff --git a/chromium/third_party/WebKit/Source/core/xml/XPathNSResolver.h b/chromium/third_party/WebKit/Source/core/xml/XPathNSResolver.h
index 4bbb942324e..fc761f6459e 100644
--- a/chromium/third_party/WebKit/Source/core/xml/XPathNSResolver.h
+++ b/chromium/third_party/WebKit/Source/core/xml/XPathNSResolver.h
@@ -36,7 +36,7 @@ namespace WebCore {
class XPathNSResolver : public RefCounted<XPathNSResolver>, public ScriptWrappable {
public:
virtual ~XPathNSResolver();
- virtual String lookupNamespaceURI(const String& prefix) = 0;
+ virtual AtomicString lookupNamespaceURI(const String& prefix) = 0;
protected:
XPathNSResolver()
diff --git a/chromium/third_party/WebKit/Source/core/xml/XPathNodeSet.cpp b/chromium/third_party/WebKit/Source/core/xml/XPathNodeSet.cpp
index c6219947ab4..b0966c66301 100644
--- a/chromium/third_party/WebKit/Source/core/xml/XPathNodeSet.cpp
+++ b/chromium/third_party/WebKit/Source/core/xml/XPathNodeSet.cpp
@@ -28,7 +28,6 @@
#include "core/dom/Attr.h"
#include "core/dom/Element.h"
-#include "core/dom/Node.h"
#include "core/dom/NodeTraversal.h"
namespace WebCore {
@@ -207,7 +206,7 @@ void NodeSet::traversalSort() const
Vector<RefPtr<Node> > sortedNodes;
sortedNodes.reserveInitialCapacity(nodeCount);
- for (Node* n = findRootNode(m_nodes.first().get()); n; n = NodeTraversal::next(n)) {
+ for (Node* n = findRootNode(m_nodes.first().get()); n; n = NodeTraversal::next(*n)) {
if (nodes.contains(n))
sortedNodes.append(n);
diff --git a/chromium/third_party/WebKit/Source/core/xml/XPathParser.cpp b/chromium/third_party/WebKit/Source/core/xml/XPathParser.cpp
index 0772e3adfa9..3c6579f1427 100644
--- a/chromium/third_party/WebKit/Source/core/xml/XPathParser.cpp
+++ b/chromium/third_party/WebKit/Source/core/xml/XPathParser.cpp
@@ -33,7 +33,6 @@
#include "core/xml/XPathEvaluator.h"
#include "core/xml/XPathNSResolver.h"
#include "core/xml/XPathPath.h"
-#include "core/xml/XPathStep.h"
#include "wtf/StdLibExtras.h"
#include "wtf/text/StringHash.h"
@@ -448,7 +447,7 @@ int Parser::lex(void* data)
return tok.type;
}
-bool Parser::expandQName(const String& qName, String& localName, String& namespaceURI)
+bool Parser::expandQName(const String& qName, AtomicString& localName, AtomicString& namespaceURI)
{
size_t colon = qName.find(':');
if (colon != kNotFound) {
@@ -457,14 +456,15 @@ bool Parser::expandQName(const String& qName, String& localName, String& namespa
namespaceURI = m_resolver->lookupNamespaceURI(qName.left(colon));
if (namespaceURI.isNull())
return false;
- localName = qName.substring(colon + 1);
- } else
- localName = qName;
+ localName = AtomicString(qName.substring(colon + 1));
+ } else {
+ localName = AtomicString(qName);
+ }
return true;
}
-Expression* Parser::parseStatement(const String& statement, PassRefPtr<XPathNSResolver> resolver, ExceptionState& es)
+Expression* Parser::parseStatement(const String& statement, PassRefPtr<XPathNSResolver> resolver, ExceptionState& exceptionState)
{
reset(statement);
@@ -479,18 +479,14 @@ Expression* Parser::parseStatement(const String& statement, PassRefPtr<XPathNSRe
deleteAllValues(m_parseNodes);
m_parseNodes.clear();
- HashSet<Vector<Predicate*>*>::iterator pend = m_predicateVectors.end();
- for (HashSet<Vector<Predicate*>*>::iterator it = m_predicateVectors.begin(); it != pend; ++it) {
- deleteAllValues(**it);
+ HashSet<Vector<OwnPtr<Predicate> >*>::iterator pend = m_predicateVectors.end();
+ for (HashSet<Vector<OwnPtr<Predicate> >*>::iterator it = m_predicateVectors.begin(); it != pend; ++it)
delete *it;
- }
m_predicateVectors.clear();
- HashSet<Vector<Expression*>*>::iterator eend = m_expressionVectors.end();
- for (HashSet<Vector<Expression*>*>::iterator it = m_expressionVectors.begin(); it != eend; ++it) {
- deleteAllValues(**it);
+ HashSet<Vector<OwnPtr<Expression> >*>::iterator eend = m_expressionVectors.end();
+ for (HashSet<Vector<OwnPtr<Expression> >*>::iterator it = m_expressionVectors.begin(); it != eend; ++it)
delete *it;
- }
m_expressionVectors.clear();
deleteAllValues(m_strings);
@@ -502,9 +498,9 @@ Expression* Parser::parseStatement(const String& statement, PassRefPtr<XPathNSRe
m_topExpr = 0;
if (m_gotNamespaceError)
- es.throwDOMException(NamespaceError);
+ exceptionState.throwDOMException(NamespaceError, "The string '" + statement + "' contains unresolvable namespaces.");
else
- es.throwDOMException(SyntaxError);
+ exceptionState.throwDOMException(SyntaxError, "The string '" + statement + "' is not a valid XPath expression.");
return 0;
}
@@ -542,7 +538,7 @@ void Parser::unregisterParseNode(ParseNode* node)
m_parseNodes.remove(node);
}
-void Parser::registerPredicateVector(Vector<Predicate*>* vector)
+void Parser::registerPredicateVector(Vector<OwnPtr<Predicate> >* vector)
{
if (vector == 0)
return;
@@ -552,7 +548,7 @@ void Parser::registerPredicateVector(Vector<Predicate*>* vector)
m_predicateVectors.add(vector);
}
-void Parser::deletePredicateVector(Vector<Predicate*>* vector)
+void Parser::deletePredicateVector(Vector<OwnPtr<Predicate> >* vector)
{
if (vector == 0)
return;
@@ -564,7 +560,7 @@ void Parser::deletePredicateVector(Vector<Predicate*>* vector)
}
-void Parser::registerExpressionVector(Vector<Expression*>* vector)
+void Parser::registerExpressionVector(Vector<OwnPtr<Expression> >* vector)
{
if (vector == 0)
return;
@@ -574,7 +570,7 @@ void Parser::registerExpressionVector(Vector<Expression*>* vector)
m_expressionVectors.add(vector);
}
-void Parser::deleteExpressionVector(Vector<Expression*>* vector)
+void Parser::deleteExpressionVector(Vector<OwnPtr<Expression> >* vector)
{
if (vector == 0)
return;
diff --git a/chromium/third_party/WebKit/Source/core/xml/XPathParser.h b/chromium/third_party/WebKit/Source/core/xml/XPathParser.h
index 57c6dc5d9ab..07a3f8d708e 100644
--- a/chromium/third_party/WebKit/Source/core/xml/XPathParser.h
+++ b/chromium/third_party/WebKit/Source/core/xml/XPathParser.h
@@ -62,7 +62,7 @@ public:
~Parser();
XPathNSResolver* resolver() const { return m_resolver.get(); }
- bool expandQName(const String& qName, String& localName, String& namespaceURI);
+ bool expandQName(const String& qName, AtomicString& localName, AtomicString& namespaceURI);
Expression* parseStatement(const String& statement, PassRefPtr<XPathNSResolver>, ExceptionState&);
@@ -76,11 +76,11 @@ public:
void registerParseNode(ParseNode*);
void unregisterParseNode(ParseNode*);
- void registerPredicateVector(Vector<Predicate*>*);
- void deletePredicateVector(Vector<Predicate*>*);
+ void registerPredicateVector(Vector<OwnPtr<Predicate> >*);
+ void deletePredicateVector(Vector<OwnPtr<Predicate> >*);
- void registerExpressionVector(Vector<Expression*>*);
- void deleteExpressionVector(Vector<Expression*>*);
+ void registerExpressionVector(Vector<OwnPtr<Expression> >*);
+ void deleteExpressionVector(Vector<OwnPtr<Expression> >*);
void registerString(String*);
void deleteString(String*);
@@ -116,8 +116,8 @@ private:
RefPtr<XPathNSResolver> m_resolver;
HashSet<ParseNode*> m_parseNodes;
- HashSet<Vector<Predicate*>*> m_predicateVectors;
- HashSet<Vector<Expression*>*> m_expressionVectors;
+ HashSet<Vector<OwnPtr<Predicate> >*> m_predicateVectors;
+ HashSet<Vector<OwnPtr<Expression> >*> m_expressionVectors;
HashSet<String*> m_strings;
HashSet<Step::NodeTest*> m_nodeTests;
};
diff --git a/chromium/third_party/WebKit/Source/core/xml/XPathPath.cpp b/chromium/third_party/WebKit/Source/core/xml/XPathPath.cpp
index 73b446f487c..80e57b3d49e 100644
--- a/chromium/third_party/WebKit/Source/core/xml/XPathPath.cpp
+++ b/chromium/third_party/WebKit/Source/core/xml/XPathPath.cpp
@@ -36,9 +36,10 @@
namespace WebCore {
namespace XPath {
-Filter::Filter(Expression* expr, const Vector<Predicate*>& predicates)
- : m_expr(expr), m_predicates(predicates)
+Filter::Filter(PassOwnPtr<Expression> expr, Vector<OwnPtr<Predicate> >& predicates)
+ : m_expr(expr)
{
+ m_predicates.swap(predicates);
setIsContextNodeSensitive(m_expr->isContextNodeSensitive());
setIsContextPositionSensitive(m_expr->isContextPositionSensitive());
setIsContextSizeSensitive(m_expr->isContextSizeSensitive());
@@ -46,8 +47,6 @@ Filter::Filter(Expression* expr, const Vector<Predicate*>& predicates)
Filter::~Filter()
{
- delete m_expr;
- deleteAllValues(m_predicates);
}
Value Filter::evaluate() const
@@ -186,7 +185,7 @@ void LocationPath::insertFirstStep(Step* step)
m_steps.insert(0, step);
}
-Path::Path(Filter* filter, LocationPath* path)
+Path::Path(Expression* filter, LocationPath* path)
: m_filter(filter)
, m_path(path)
{
diff --git a/chromium/third_party/WebKit/Source/core/xml/XPathPath.h b/chromium/third_party/WebKit/Source/core/xml/XPathPath.h
index 2b18e8be48e..18016a8500f 100644
--- a/chromium/third_party/WebKit/Source/core/xml/XPathPath.h
+++ b/chromium/third_party/WebKit/Source/core/xml/XPathPath.h
@@ -37,50 +37,50 @@ namespace WebCore {
class Predicate;
class Step;
- class Filter : public Expression {
+ class Filter FINAL : public Expression {
public:
- Filter(Expression*, const Vector<Predicate*>& = Vector<Predicate*>());
+ Filter(PassOwnPtr<Expression>, Vector<OwnPtr<Predicate> >&);
virtual ~Filter();
- virtual Value evaluate() const;
+ virtual Value evaluate() const OVERRIDE;
private:
- virtual Value::Type resultType() const { return Value::NodeSetValue; }
+ virtual Value::Type resultType() const OVERRIDE { return Value::NodeSetValue; }
- Expression* m_expr;
- Vector<Predicate*> m_predicates;
+ OwnPtr<Expression> m_expr;
+ Vector<OwnPtr<Predicate> > m_predicates;
};
- class LocationPath : public Expression {
+ class LocationPath FINAL : public Expression {
public:
LocationPath();
virtual ~LocationPath();
void setAbsolute(bool value) { m_absolute = value; setIsContextNodeSensitive(!m_absolute); }
- virtual Value evaluate() const;
+ virtual Value evaluate() const OVERRIDE;
void evaluate(NodeSet& nodes) const; // nodes is an input/output parameter
void appendStep(Step* step);
void insertFirstStep(Step* step);
private:
- virtual Value::Type resultType() const { return Value::NodeSetValue; }
+ virtual Value::Type resultType() const OVERRIDE { return Value::NodeSetValue; }
Vector<Step*> m_steps;
bool m_absolute;
};
- class Path : public Expression {
+ class Path FINAL : public Expression {
public:
- Path(Filter*, LocationPath*);
+ Path(Expression*, LocationPath*);
virtual ~Path();
- virtual Value evaluate() const;
+ virtual Value evaluate() const OVERRIDE;
private:
- virtual Value::Type resultType() const { return Value::NodeSetValue; }
+ virtual Value::Type resultType() const OVERRIDE { return Value::NodeSetValue; }
- Filter* m_filter;
+ Expression* m_filter;
LocationPath* m_path;
};
diff --git a/chromium/third_party/WebKit/Source/core/xml/XPathPredicate.cpp b/chromium/third_party/WebKit/Source/core/xml/XPathPredicate.cpp
index 963e115a626..38814185ebb 100644
--- a/chromium/third_party/WebKit/Source/core/xml/XPathPredicate.cpp
+++ b/chromium/third_party/WebKit/Source/core/xml/XPathPredicate.cpp
@@ -31,7 +31,6 @@
#include <math.h>
#include "core/xml/XPathFunctions.h"
#include "core/xml/XPathUtil.h"
-#include "core/xml/XPathValue.h"
#include "wtf/MathExtras.h"
namespace WebCore {
@@ -63,7 +62,7 @@ Value Negative::evaluate() const
return -p.toNumber();
}
-NumericOp::NumericOp(Opcode opcode, Expression* lhs, Expression* rhs)
+NumericOp::NumericOp(Opcode opcode, PassOwnPtr<Expression> lhs, PassOwnPtr<Expression> rhs)
: m_opcode(opcode)
{
addSubExpression(lhs);
@@ -94,7 +93,7 @@ Value NumericOp::evaluate() const
return 0.0;
}
-EqTestOp::EqTestOp(Opcode opcode, Expression* lhs, Expression* rhs)
+EqTestOp::EqTestOp(Opcode opcode, PassOwnPtr<Expression> lhs, PassOwnPtr<Expression> rhs)
: m_opcode(opcode)
{
addSubExpression(lhs);
@@ -197,7 +196,7 @@ Value EqTestOp::evaluate() const
return compare(lhs, rhs);
}
-LogicalOp::LogicalOp(Opcode opcode, Expression* lhs, Expression* rhs)
+LogicalOp::LogicalOp(Opcode opcode, PassOwnPtr<Expression> lhs, PassOwnPtr<Expression> rhs)
: m_opcode(opcode)
{
addSubExpression(lhs);
@@ -249,25 +248,24 @@ Value Union::evaluate() const
return lhsResult;
}
-Predicate::Predicate(Expression* expr)
+Predicate::Predicate(PassOwnPtr<Expression> expr)
: m_expr(expr)
{
}
Predicate::~Predicate()
{
- delete m_expr;
}
bool Predicate::evaluate() const
{
- ASSERT(m_expr != 0);
+ ASSERT(m_expr);
Value result(m_expr->evaluate());
// foo[3] means foo[position()=3]
if (result.isNumber())
- return EqTestOp(EqTestOp::OP_EQ, createFunction("position"), new Number(result.toNumber())).evaluate().toBoolean();
+ return EqTestOp(EqTestOp::OP_EQ, adoptPtr(createFunction("position")), adoptPtr(new Number(result.toNumber()))).evaluate().toBoolean();
return result.toBoolean();
}
diff --git a/chromium/third_party/WebKit/Source/core/xml/XPathPredicate.h b/chromium/third_party/WebKit/Source/core/xml/XPathPredicate.h
index 93eaad737be..0b506f2f9b0 100644
--- a/chromium/third_party/WebKit/Source/core/xml/XPathPredicate.h
+++ b/chromium/third_party/WebKit/Source/core/xml/XPathPredicate.h
@@ -65,7 +65,7 @@ namespace WebCore {
enum Opcode {
OP_Add, OP_Sub, OP_Mul, OP_Div, OP_Mod
};
- NumericOp(Opcode, Expression* lhs, Expression* rhs);
+ NumericOp(Opcode, PassOwnPtr<Expression> lhs, PassOwnPtr<Expression> rhs);
private:
virtual Value evaluate() const;
virtual Value::Type resultType() const { return Value::NumberValue; }
@@ -76,7 +76,7 @@ namespace WebCore {
class EqTestOp : public Expression {
public:
enum Opcode { OP_EQ, OP_NE, OP_GT, OP_LT, OP_GE, OP_LE };
- EqTestOp(Opcode, Expression* lhs, Expression* rhs);
+ EqTestOp(Opcode, PassOwnPtr<Expression> lhs, PassOwnPtr<Expression> rhs);
virtual Value evaluate() const;
private:
virtual Value::Type resultType() const { return Value::BooleanValue; }
@@ -88,7 +88,7 @@ namespace WebCore {
class LogicalOp : public Expression {
public:
enum Opcode { OP_And, OP_Or };
- LogicalOp(Opcode, Expression* lhs, Expression* rhs);
+ LogicalOp(Opcode, PassOwnPtr<Expression> lhs, PassOwnPtr<Expression> rhs);
private:
virtual Value::Type resultType() const { return Value::BooleanValue; }
bool shortCircuitOn() const;
@@ -106,7 +106,7 @@ namespace WebCore {
class Predicate {
WTF_MAKE_NONCOPYABLE(Predicate); WTF_MAKE_FAST_ALLOCATED;
public:
- explicit Predicate(Expression*);
+ explicit Predicate(PassOwnPtr<Expression>);
~Predicate();
bool evaluate() const;
@@ -114,7 +114,7 @@ namespace WebCore {
bool isContextSizeSensitive() const { return m_expr->isContextSizeSensitive(); }
private:
- Expression* m_expr;
+ OwnPtr<Expression> m_expr;
};
}
diff --git a/chromium/third_party/WebKit/Source/core/xml/XPathResult.cpp b/chromium/third_party/WebKit/Source/core/xml/XPathResult.cpp
index 3647decc196..17aa9dd2061 100644
--- a/chromium/third_party/WebKit/Source/core/xml/XPathResult.cpp
+++ b/chromium/third_party/WebKit/Source/core/xml/XPathResult.cpp
@@ -67,7 +67,7 @@ XPathResult::~XPathResult()
{
}
-void XPathResult::convertTo(unsigned short type, ExceptionState& es)
+void XPathResult::convertTo(unsigned short type, ExceptionState& exceptionState)
{
switch (type) {
case ANY_TYPE:
@@ -89,14 +89,14 @@ void XPathResult::convertTo(unsigned short type, ExceptionState& es)
case ANY_UNORDERED_NODE_TYPE:
case FIRST_ORDERED_NODE_TYPE: // This is correct - singleNodeValue() will take care of ordering.
if (!m_value.isNodeSet()) {
- es.throwTypeError();
+ exceptionState.throwTypeError("The result is not a node set, and therefore cannot be converted to the desired type.");
return;
}
m_resultType = type;
break;
case ORDERED_NODE_ITERATOR_TYPE:
if (!m_value.isNodeSet()) {
- es.throwTypeError();
+ exceptionState.throwTypeError("The result is not a node set, and therefore cannot be converted to the desired type.");
return;
}
m_nodeSet.sort();
@@ -104,7 +104,7 @@ void XPathResult::convertTo(unsigned short type, ExceptionState& es)
break;
case ORDERED_NODE_SNAPSHOT_TYPE:
if (!m_value.isNodeSet()) {
- es.throwTypeError();
+ exceptionState.throwTypeError("The result is not a node set, and therefore cannot be converted to the desired type.");
return;
}
m_value.toNodeSet().sort();
@@ -118,37 +118,37 @@ unsigned short XPathResult::resultType() const
return m_resultType;
}
-double XPathResult::numberValue(ExceptionState& es) const
+double XPathResult::numberValue(ExceptionState& exceptionState) const
{
if (resultType() != NUMBER_TYPE) {
- es.throwTypeError();
+ exceptionState.throwTypeError("The result type is not a number.");
return 0.0;
}
return m_value.toNumber();
}
-String XPathResult::stringValue(ExceptionState& es) const
+String XPathResult::stringValue(ExceptionState& exceptionState) const
{
if (resultType() != STRING_TYPE) {
- es.throwTypeError();
+ exceptionState.throwTypeError("The result type is not a string.");
return String();
}
return m_value.toString();
}
-bool XPathResult::booleanValue(ExceptionState& es) const
+bool XPathResult::booleanValue(ExceptionState& exceptionState) const
{
if (resultType() != BOOLEAN_TYPE) {
- es.throwTypeError();
+ exceptionState.throwTypeError("The result type is not a boolean.");
return false;
}
return m_value.toBoolean();
}
-Node* XPathResult::singleNodeValue(ExceptionState& es) const
+Node* XPathResult::singleNodeValue(ExceptionState& exceptionState) const
{
if (resultType() != ANY_UNORDERED_NODE_TYPE && resultType() != FIRST_ORDERED_NODE_TYPE) {
- es.throwTypeError();
+ exceptionState.throwTypeError("The result type is not a single node.");
return 0;
}
@@ -168,25 +168,25 @@ bool XPathResult::invalidIteratorState() const
return m_document->domTreeVersion() != m_domTreeVersion;
}
-unsigned long XPathResult::snapshotLength(ExceptionState& es) const
+unsigned long XPathResult::snapshotLength(ExceptionState& exceptionState) const
{
if (resultType() != UNORDERED_NODE_SNAPSHOT_TYPE && resultType() != ORDERED_NODE_SNAPSHOT_TYPE) {
- es.throwTypeError();
+ exceptionState.throwTypeError("The result type is not a snapshot.");
return 0;
}
return m_value.toNodeSet().size();
}
-Node* XPathResult::iterateNext(ExceptionState& es)
+Node* XPathResult::iterateNext(ExceptionState& exceptionState)
{
if (resultType() != UNORDERED_NODE_ITERATOR_TYPE && resultType() != ORDERED_NODE_ITERATOR_TYPE) {
- es.throwTypeError();
+ exceptionState.throwTypeError("The result type is not an iterator.");
return 0;
}
if (invalidIteratorState()) {
- es.throwDOMException(InvalidStateError);
+ exceptionState.throwDOMException(InvalidStateError, "The document has mutated since the result was returned.");
return 0;
}
@@ -200,10 +200,10 @@ Node* XPathResult::iterateNext(ExceptionState& es)
return node;
}
-Node* XPathResult::snapshotItem(unsigned long index, ExceptionState& es)
+Node* XPathResult::snapshotItem(unsigned long index, ExceptionState& exceptionState)
{
if (resultType() != UNORDERED_NODE_SNAPSHOT_TYPE && resultType() != ORDERED_NODE_SNAPSHOT_TYPE) {
- es.throwTypeError();
+ exceptionState.throwTypeError("The result type is not a snapshot.");
return 0;
}
diff --git a/chromium/third_party/WebKit/Source/core/xml/XPathResult.idl b/chromium/third_party/WebKit/Source/core/xml/XPathResult.idl
index 19cfb4c40c7..dd5f9cf9ac1 100644
--- a/chromium/third_party/WebKit/Source/core/xml/XPathResult.idl
+++ b/chromium/third_party/WebKit/Source/core/xml/XPathResult.idl
@@ -31,16 +31,16 @@
const unsigned short FIRST_ORDERED_NODE_TYPE = 9;
readonly attribute unsigned short resultType;
- [GetterRaisesException] readonly attribute double numberValue;
+ [RaisesException=Getter] readonly attribute double numberValue;
- [GetterRaisesException] readonly attribute DOMString stringValue;
+ [RaisesException=Getter] readonly attribute DOMString stringValue;
- [GetterRaisesException] readonly attribute boolean booleanValue;
+ [RaisesException=Getter] readonly attribute boolean booleanValue;
- [GetterRaisesException] readonly attribute Node singleNodeValue;
+ [RaisesException=Getter] readonly attribute Node singleNodeValue;
readonly attribute boolean invalidIteratorState;
- [GetterRaisesException] readonly attribute unsigned long snapshotLength;
+ [RaisesException=Getter] readonly attribute unsigned long snapshotLength;
[RaisesException] Node iterateNext();
[RaisesException] Node snapshotItem([Default=Undefined] optional unsigned long index);
diff --git a/chromium/third_party/WebKit/Source/core/xml/XPathStep.cpp b/chromium/third_party/WebKit/Source/core/xml/XPathStep.cpp
index 618a4216c7b..4687257be64 100644
--- a/chromium/third_party/WebKit/Source/core/xml/XPathStep.cpp
+++ b/chromium/third_party/WebKit/Source/core/xml/XPathStep.cpp
@@ -39,17 +39,21 @@
namespace WebCore {
namespace XPath {
-Step::Step(Axis axis, const NodeTest& nodeTest, const Vector<Predicate*>& predicates)
+Step::Step(Axis axis, const NodeTest& nodeTest)
: m_axis(axis)
, m_nodeTest(nodeTest)
- , m_predicates(predicates)
{
}
+Step::Step(Axis axis, const NodeTest& nodeTest, Vector<OwnPtr<Predicate> >& predicates)
+ : m_axis(axis)
+ , m_nodeTest(nodeTest)
+{
+ m_predicates.swap(predicates);
+}
+
Step::~Step()
{
- deleteAllValues(m_predicates);
- deleteAllValues(m_nodeTest.mergedPredicates());
}
void Step::optimize()
@@ -57,13 +61,14 @@ void Step::optimize()
// Evaluate predicates as part of node test if possible to avoid building unnecessary NodeSets.
// E.g., there is no need to build a set of all "foo" nodes to evaluate "foo[@bar]", we can check the predicate while enumerating.
// This optimization can be applied to predicates that are not context node list sensitive, or to first predicate that is only context position sensitive, e.g. foo[position() mod 2 = 0].
- Vector<Predicate*> remainingPredicates;
+ Vector<OwnPtr<Predicate> > remainingPredicates;
for (size_t i = 0; i < m_predicates.size(); ++i) {
- Predicate* predicate = m_predicates[i];
+ OwnPtr<Predicate> predicate(m_predicates[i].release());
if ((!predicate->isContextPositionSensitive() || m_nodeTest.mergedPredicates().isEmpty()) && !predicate->isContextSizeSensitive() && remainingPredicates.isEmpty()) {
- m_nodeTest.mergedPredicates().append(predicate);
- } else
- remainingPredicates.append(predicate);
+ m_nodeTest.mergedPredicates().append(predicate.release());
+ } else {
+ remainingPredicates.append(predicate.release());
+ }
}
swap(remainingPredicates, m_predicates);
}
@@ -95,13 +100,13 @@ void optimizeStepPair(Step* first, Step* second, bool& dropSecondStep)
bool Step::predicatesAreContextListInsensitive() const
{
for (size_t i = 0; i < m_predicates.size(); ++i) {
- Predicate* predicate = m_predicates[i];
+ Predicate* predicate = m_predicates[i].get();
if (predicate->isContextPositionSensitive() || predicate->isContextSizeSensitive())
return false;
}
for (size_t i = 0; i < m_nodeTest.mergedPredicates().size(); ++i) {
- Predicate* predicate = m_nodeTest.mergedPredicates()[i];
+ Predicate* predicate = m_nodeTest.mergedPredicates()[i].get();
if (predicate->isContextPositionSensitive() || predicate->isContextSizeSensitive())
return false;
}
@@ -118,7 +123,7 @@ void Step::evaluate(Node* context, NodeSet& nodes) const
// Check predicates that couldn't be merged into node test.
for (unsigned i = 0; i < m_predicates.size(); i++) {
- Predicate* predicate = m_predicates[i];
+ Predicate* predicate = m_predicates[i].get();
NodeSet newNodes;
if (!nodes.isSorted())
@@ -138,6 +143,7 @@ void Step::evaluate(Node* context, NodeSet& nodes) const
}
}
+#if !ASSERT_DISABLED
static inline Node::NodeType primaryNodeType(Step::Axis axis)
{
switch (axis) {
@@ -149,6 +155,7 @@ static inline Node::NodeType primaryNodeType(Step::Axis axis)
return Node::ELEMENT_NODE;
}
}
+#endif
// Evaluate NodeTest without considering merged predicates.
static inline bool nodeMatchesBasicTest(Node* node, Step::Axis axis, const Step::NodeTest& nodeTest)
@@ -217,9 +224,9 @@ static inline bool nodeMatches(Node* node, Step::Axis axis, const Step::NodeTest
// Only the first merged predicate may depend on position.
++evaluationContext.position;
- const Vector<Predicate*>& mergedPredicates = nodeTest.mergedPredicates();
+ const Vector<OwnPtr<Predicate> >& mergedPredicates = nodeTest.mergedPredicates();
for (unsigned i = 0; i < mergedPredicates.size(); i++) {
- Predicate* predicate = mergedPredicates[i];
+ Predicate* predicate = mergedPredicates[i].get();
evaluationContext.node = node;
// No need to set context size - we only get here when evaluating predicates that do not depend on it.
@@ -247,7 +254,7 @@ void Step::nodesInAxis(Node* context, NodeSet& nodes) const
if (context->isAttributeNode()) // In XPath model, attribute nodes do not have children.
return;
- for (Node* n = context->firstChild(); n; n = NodeTraversal::next(n, context))
+ for (Node* n = context->firstChild(); n; n = NodeTraversal::next(*n, context))
if (nodeMatches(n, DescendantAxis, m_nodeTest))
nodes.append(n);
return;
@@ -298,7 +305,7 @@ void Step::nodesInAxis(Node* context, NodeSet& nodes) const
case FollowingAxis:
if (context->isAttributeNode()) {
Node* p = toAttr(context)->ownerElement();
- while ((p = NodeTraversal::next(p))) {
+ while ((p = NodeTraversal::next(*p))) {
if (nodeMatches(p, FollowingAxis, m_nodeTest))
nodes.append(p);
}
@@ -307,7 +314,7 @@ void Step::nodesInAxis(Node* context, NodeSet& nodes) const
for (Node* n = p->nextSibling(); n; n = n->nextSibling()) {
if (nodeMatches(n, FollowingAxis, m_nodeTest))
nodes.append(n);
- for (Node* c = n->firstChild(); c; c = NodeTraversal::next(c, n))
+ for (Node* c = n->firstChild(); c; c = NodeTraversal::next(*c, n))
if (nodeMatches(c, FollowingAxis, m_nodeTest))
nodes.append(c);
}
@@ -320,7 +327,7 @@ void Step::nodesInAxis(Node* context, NodeSet& nodes) const
Node* n = context;
while (ContainerNode* parent = n->parentNode()) {
- for (n = NodeTraversal::previous(n); n != parent; n = NodeTraversal::previous(n))
+ for (n = NodeTraversal::previous(*n); n != parent; n = NodeTraversal::previous(*n))
if (nodeMatches(n, PrecedingAxis, m_nodeTest))
nodes.append(n);
n = parent;
@@ -367,7 +374,7 @@ void Step::nodesInAxis(Node* context, NodeSet& nodes) const
if (context->isAttributeNode()) // In XPath model, attribute nodes do not have children.
return;
- for (Node* n = context->firstChild(); n; n = NodeTraversal::next(n, context))
+ for (Node* n = context->firstChild(); n; n = NodeTraversal::next(*n, context))
if (nodeMatches(n, DescendantOrSelfAxis, m_nodeTest))
nodes.append(n);
return;
diff --git a/chromium/third_party/WebKit/Source/core/xml/XPathStep.h b/chromium/third_party/WebKit/Source/core/xml/XPathStep.h
index 4e9c14f3ff1..b148aae1471 100644
--- a/chromium/third_party/WebKit/Source/core/xml/XPathStep.h
+++ b/chromium/third_party/WebKit/Source/core/xml/XPathStep.h
@@ -59,13 +59,29 @@ public:
NodeTest(Kind kind) : m_kind(kind) { }
NodeTest(Kind kind, const String& data) : m_kind(kind), m_data(data) { }
- NodeTest(Kind kind, const String& data, const String& namespaceURI) : m_kind(kind), m_data(data), m_namespaceURI(namespaceURI) { }
+ NodeTest(Kind kind, const AtomicString& data, const AtomicString& namespaceURI) : m_kind(kind), m_data(data), m_namespaceURI(namespaceURI) { }
+
+ NodeTest(const NodeTest& o)
+ : m_kind(o.m_kind)
+ , m_data(o.m_data)
+ , m_namespaceURI(o.m_namespaceURI)
+ {
+ ASSERT(o.m_mergedPredicates.isEmpty());
+ }
+ NodeTest& operator=(const NodeTest& o)
+ {
+ m_kind = o.m_kind;
+ m_data = o.m_data;
+ m_namespaceURI = o.m_namespaceURI;
+ ASSERT(o.m_mergedPredicates.isEmpty());
+ return *this;
+ }
Kind kind() const { return m_kind; }
const AtomicString& data() const { return m_data; }
const AtomicString& namespaceURI() const { return m_namespaceURI; }
- Vector<Predicate*>& mergedPredicates() { return m_mergedPredicates; }
- const Vector<Predicate*>& mergedPredicates() const { return m_mergedPredicates; }
+ Vector<OwnPtr<Predicate> >& mergedPredicates() { return m_mergedPredicates; }
+ const Vector<OwnPtr<Predicate> >& mergedPredicates() const { return m_mergedPredicates; }
private:
Kind m_kind;
@@ -73,10 +89,11 @@ public:
AtomicString m_namespaceURI;
// When possible, we merge some or all predicates with node test for better performance.
- Vector<Predicate*> m_mergedPredicates;
+ Vector<OwnPtr<Predicate> > m_mergedPredicates;
};
- Step(Axis, const NodeTest&, const Vector<Predicate*>& predicates = Vector<Predicate*>());
+ Step(Axis, const NodeTest&);
+ Step(Axis, const NodeTest&, Vector<OwnPtr<Predicate> >&);
~Step();
void optimize();
@@ -96,7 +113,7 @@ private:
Axis m_axis;
NodeTest m_nodeTest;
- Vector<Predicate*> m_predicates;
+ Vector<OwnPtr<Predicate> > m_predicates;
};
void optimizeStepPair(Step*, Step*, bool& dropSecondStep);
diff --git a/chromium/third_party/WebKit/Source/core/xml/XPathUtil.cpp b/chromium/third_party/WebKit/Source/core/xml/XPathUtil.cpp
index 5967efa025d..5e266fa222d 100644
--- a/chromium/third_party/WebKit/Source/core/xml/XPathUtil.cpp
+++ b/chromium/third_party/WebKit/Source/core/xml/XPathUtil.cpp
@@ -54,7 +54,7 @@ String stringValue(Node* node)
StringBuilder result;
result.reserveCapacity(1024);
- for (Node* n = node->firstChild(); n; n = NodeTraversal::next(n, node)) {
+ for (Node* n = node->firstChild(); n; n = NodeTraversal::next(*n, node)) {
if (n->isTextNode()) {
const String& nodeValue = n->nodeValue();
result.append(nodeValue);
diff --git a/chromium/third_party/WebKit/Source/core/xml/XSLImportRule.cpp b/chromium/third_party/WebKit/Source/core/xml/XSLImportRule.cpp
index e4259b8ee07..48b1e4b81ab 100644
--- a/chromium/third_party/WebKit/Source/core/xml/XSLImportRule.cpp
+++ b/chromium/third_party/WebKit/Source/core/xml/XSLImportRule.cpp
@@ -27,7 +27,6 @@
#include "core/fetch/FetchRequest.h"
#include "core/fetch/ResourceFetcher.h"
#include "core/fetch/XSLStyleSheetResource.h"
-#include "core/xml/XSLStyleSheet.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/xml/XSLImportRule.h b/chromium/third_party/WebKit/Source/core/xml/XSLImportRule.h
index e78fc08585a..954e046c840 100644
--- a/chromium/third_party/WebKit/Source/core/xml/XSLImportRule.h
+++ b/chromium/third_party/WebKit/Source/core/xml/XSLImportRule.h
@@ -23,6 +23,7 @@
#ifndef XSLImportRule_h
#define XSLImportRule_h
+#include "RuntimeEnabledFeatures.h"
#include "core/fetch/ResourcePtr.h"
#include "core/fetch/StyleSheetResourceClient.h"
#include "core/xml/XSLStyleSheet.h"
@@ -37,6 +38,7 @@ class XSLImportRule : private StyleSheetResourceClient {
public:
static PassOwnPtr<XSLImportRule> create(XSLStyleSheet* parentSheet, const String& href)
{
+ ASSERT(RuntimeEnabledFeatures::xsltEnabled());
return adoptPtr(new XSLImportRule(parentSheet, href));
}
diff --git a/chromium/third_party/WebKit/Source/core/xml/XSLStyleSheet.h b/chromium/third_party/WebKit/Source/core/xml/XSLStyleSheet.h
index 6b21a117d96..17f99842250 100644
--- a/chromium/third_party/WebKit/Source/core/xml/XSLStyleSheet.h
+++ b/chromium/third_party/WebKit/Source/core/xml/XSLStyleSheet.h
@@ -23,12 +23,14 @@
#ifndef XSLStyleSheet_h
#define XSLStyleSheet_h
-#include <libxml/tree.h>
-#include <libxslt/transform.h>
+#include "RuntimeEnabledFeatures.h"
#include "core/css/StyleSheet.h"
#include "core/dom/ProcessingInstruction.h"
#include "wtf/PassRefPtr.h"
+#include <libxml/tree.h>
+#include <libxslt/transform.h>
+
namespace WebCore {
class ResourceFetcher;
@@ -38,14 +40,17 @@ class XSLStyleSheet : public StyleSheet {
public:
static PassRefPtr<XSLStyleSheet> create(XSLImportRule* parentImport, const String& originalURL, const KURL& finalURL)
{
+ ASSERT(RuntimeEnabledFeatures::xsltEnabled());
return adoptRef(new XSLStyleSheet(parentImport, originalURL, finalURL));
}
static PassRefPtr<XSLStyleSheet> create(ProcessingInstruction* parentNode, const String& originalURL, const KURL& finalURL)
{
+ ASSERT(RuntimeEnabledFeatures::xsltEnabled());
return adoptRef(new XSLStyleSheet(parentNode, originalURL, finalURL, false));
}
static PassRefPtr<XSLStyleSheet> createEmbedded(ProcessingInstruction* parentNode, const KURL& finalURL)
{
+ ASSERT(RuntimeEnabledFeatures::xsltEnabled());
return adoptRef(new XSLStyleSheet(parentNode, finalURL.string(), finalURL, true));
}
@@ -53,6 +58,7 @@ public:
// XSLTProcessor ensures that the stylesheet doesn't outlive its parent, in part by not exposing it to JavaScript.
static PassRefPtr<XSLStyleSheet> createForXSLTProcessor(Node* parentNode, const String& originalURL, const KURL& finalURL)
{
+ ASSERT(RuntimeEnabledFeatures::xsltEnabled());
return adoptRef(new XSLStyleSheet(parentNode, originalURL, finalURL, false));
}
@@ -93,8 +99,6 @@ public:
virtual KURL baseURL() const OVERRIDE { return m_finalURL; }
virtual bool isLoading() const OVERRIDE;
- virtual bool isXSLStyleSheet() const OVERRIDE { return true; }
-
private:
XSLStyleSheet(Node* parentNode, const String& originalURL, const KURL& finalURL, bool embedded);
XSLStyleSheet(XSLImportRule* parentImport, const String& originalURL, const KURL& finalURL);
@@ -116,6 +120,8 @@ private:
XSLStyleSheet* m_parentStyleSheet;
};
+DEFINE_TYPE_CASTS(XSLStyleSheet, StyleSheet, sheet, !sheet->isCSSStyleSheet(), !sheet.isCSSStyleSheet());
+
} // namespace WebCore
#endif // XSLStyleSheet_h
diff --git a/chromium/third_party/WebKit/Source/core/xml/XSLStyleSheetLibxslt.cpp b/chromium/third_party/WebKit/Source/core/xml/XSLStyleSheetLibxslt.cpp
index b7b83266940..398afdd1f8d 100644
--- a/chromium/third_party/WebKit/Source/core/xml/XSLStyleSheetLibxslt.cpp
+++ b/chromium/third_party/WebKit/Source/core/xml/XSLStyleSheetLibxslt.cpp
@@ -25,7 +25,7 @@
#include "core/dom/Document.h"
#include "core/dom/Node.h"
#include "core/dom/TransformSource.h"
-#include "core/page/Frame.h"
+#include "core/frame/Frame.h"
#include "core/page/Page.h"
#include "core/xml/XSLImportRule.h"
#include "core/xml/XSLTProcessor.h"
diff --git a/chromium/third_party/WebKit/Source/core/xml/XSLTExtensions.cpp b/chromium/third_party/WebKit/Source/core/xml/XSLTExtensions.cpp
index eea94179e3c..064d609955b 100644
--- a/chromium/third_party/WebKit/Source/core/xml/XSLTExtensions.cpp
+++ b/chromium/third_party/WebKit/Source/core/xml/XSLTExtensions.cpp
@@ -27,6 +27,8 @@
#include "config.h"
#include "core/xml/XSLTExtensions.h"
+#include "RuntimeEnabledFeatures.h"
+#include "wtf/Assertions.h"
#include <libxml/xpathInternals.h>
@@ -70,6 +72,7 @@ static void exsltNodeSetFunction(xmlXPathParserContextPtr ctxt, int nargs)
void registerXSLTExtensions(xsltTransformContextPtr ctxt)
{
+ ASSERT(RuntimeEnabledFeatures::xsltEnabled());
xsltRegisterExtFunction(ctxt, (const xmlChar*)"node-set", (const xmlChar*)"http://exslt.org/common", exsltNodeSetFunction);
}
diff --git a/chromium/third_party/WebKit/Source/core/xml/XSLTProcessor.cpp b/chromium/third_party/WebKit/Source/core/xml/XSLTProcessor.cpp
index 083736a2b5f..61ca31b723e 100644
--- a/chromium/third_party/WebKit/Source/core/xml/XSLTProcessor.cpp
+++ b/chromium/third_party/WebKit/Source/core/xml/XSLTProcessor.cpp
@@ -24,13 +24,14 @@
#include "core/xml/XSLTProcessor.h"
#include "core/dom/DOMImplementation.h"
+#include "core/dom/DocumentEncodingData.h"
#include "core/dom/DocumentFragment.h"
#include "core/editing/markup.h"
-#include "core/page/ContentSecurityPolicy.h"
-#include "core/page/DOMWindow.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameView.h"
-#include "weborigin/SecurityOrigin.h"
+#include "core/frame/ContentSecurityPolicy.h"
+#include "core/frame/DOMWindow.h"
+#include "core/frame/Frame.h"
+#include "core/frame/FrameView.h"
+#include "platform/weborigin/SecurityOrigin.h"
#include "wtf/Assertions.h"
#include "wtf/Vector.h"
@@ -60,34 +61,39 @@ XSLTProcessor::~XSLTProcessor()
PassRefPtr<Document> XSLTProcessor::createDocumentFromSource(const String& sourceString,
const String& sourceEncoding, const String& sourceMIMEType, Node* sourceNode, Frame* frame)
{
- RefPtr<Document> ownerDocument = &sourceNode->document();
+ RefPtr<Document> ownerDocument(sourceNode->document());
bool sourceIsDocument = (sourceNode == ownerDocument.get());
String documentSource = sourceString;
RefPtr<Document> result;
- if (sourceMIMEType == "text/plain") {
- result = Document::create(DocumentInit(sourceIsDocument ? ownerDocument->url() : KURL(), frame));
+ DocumentInit init(sourceIsDocument ? ownerDocument->url() : KURL(), frame);
+
+ bool forceXHTML = sourceMIMEType == "text/plain";
+ if (forceXHTML)
transformTextStringToXHTMLDocumentString(documentSource);
- } else
- result = DOMImplementation::createDocument(sourceMIMEType, frame, sourceIsDocument ? ownerDocument->url() : KURL(), false);
- // Before parsing, we need to save & detach the old document and get the new document
- // in place. We have to do this only if we're rendering the result document.
if (frame) {
+ RefPtr<Document> oldDocument = frame->document();
+ result = frame->domWindow()->installNewDocument(sourceMIMEType, init, forceXHTML);
+
+ // Before parsing, we need to save & detach the old document and get the new document
+ // in place. We have to do this only if we're rendering the result document.
if (FrameView* view = frame->view())
view->clear();
- if (Document* oldDocument = frame->document()) {
- result->setTransformSourceDocument(oldDocument);
- result->setSecurityOrigin(oldDocument->securityOrigin());
+ if (oldDocument) {
+ result->setTransformSourceDocument(oldDocument.get());
+ result->updateSecurityOrigin(oldDocument->securityOrigin());
result->setCookieURL(oldDocument->cookieURL());
result->contentSecurityPolicy()->copyStateFrom(oldDocument->contentSecurityPolicy());
}
-
- frame->domWindow()->setDocument(result);
+ } else {
+ result = DOMWindow::createDocument(sourceMIMEType, init, forceXHTML);
}
- result->setEncoding(sourceEncoding.isEmpty() ? UTF8Encoding() : WTF::TextEncoding(sourceEncoding));
+ DocumentEncodingData data;
+ data.encoding = sourceEncoding.isEmpty() ? UTF8Encoding() : WTF::TextEncoding(sourceEncoding);
+ result->setEncodingData(data);
result->setContent(documentSource);
return result.release();
diff --git a/chromium/third_party/WebKit/Source/core/xml/XSLTProcessor.h b/chromium/third_party/WebKit/Source/core/xml/XSLTProcessor.h
index 3722f1fcb31..23272c2247f 100644
--- a/chromium/third_party/WebKit/Source/core/xml/XSLTProcessor.h
+++ b/chromium/third_party/WebKit/Source/core/xml/XSLTProcessor.h
@@ -23,6 +23,7 @@
#ifndef XSLTProcessor_h
#define XSLTProcessor_h
+#include "RuntimeEnabledFeatures.h"
#include "bindings/v8/ScriptWrappable.h"
#include "core/dom/Node.h"
#include "core/xml/XSLStyleSheet.h"
@@ -40,7 +41,11 @@ class DocumentFragment;
class XSLTProcessor : public RefCounted<XSLTProcessor>, public ScriptWrappable {
public:
- static PassRefPtr<XSLTProcessor> create() { return adoptRef(new XSLTProcessor); }
+ static PassRefPtr<XSLTProcessor> create()
+ {
+ ASSERT(RuntimeEnabledFeatures::xsltEnabled());
+ return adoptRef(new XSLTProcessor);
+ }
~XSLTProcessor();
void setXSLStyleSheet(PassRefPtr<XSLStyleSheet> styleSheet) { m_stylesheet = styleSheet; }
diff --git a/chromium/third_party/WebKit/Source/core/xml/XSLTProcessor.idl b/chromium/third_party/WebKit/Source/core/xml/XSLTProcessor.idl
index f552ed1eefd..7c9986889af 100644
--- a/chromium/third_party/WebKit/Source/core/xml/XSLTProcessor.idl
+++ b/chromium/third_party/WebKit/Source/core/xml/XSLTProcessor.idl
@@ -32,12 +32,13 @@
[
Constructor,
+ RuntimeEnabled=XSLT,
MeasureAs=XSLTProcessor
] interface XSLTProcessor {
void importStylesheet([Default=Undefined] optional Node stylesheet);
- [CustomElementCallbacks=Enable] DocumentFragment transformToFragment([Default=Undefined] optional Node source, [Default=Undefined] optional Document docVal);
- [CustomElementCallbacks=Enable] Document transformToDocument([Default=Undefined] optional Node source);
+ [CustomElementCallbacks] DocumentFragment transformToFragment([Default=Undefined] optional Node source, [Default=Undefined] optional Document docVal);
+ [CustomElementCallbacks] Document transformToDocument([Default=Undefined] optional Node source);
[Custom] void setParameter(DOMString namespaceURI, DOMString localName, DOMString value);
[Custom, TreatReturnedNullStringAs=Undefined] DOMString getParameter(DOMString namespaceURI, DOMString localName);
diff --git a/chromium/third_party/WebKit/Source/core/xml/XSLTProcessorLibxslt.cpp b/chromium/third_party/WebKit/Source/core/xml/XSLTProcessorLibxslt.cpp
index 30b31511199..18f571dc15a 100644
--- a/chromium/third_party/WebKit/Source/core/xml/XSLTProcessorLibxslt.cpp
+++ b/chromium/third_party/WebKit/Source/core/xml/XSLTProcessorLibxslt.cpp
@@ -23,33 +23,33 @@
#include "config.h"
#include "core/xml/XSLTProcessor.h"
+#include <libxslt/imports.h>
+#include <libxslt/security.h>
+#include <libxslt/variables.h>
+#include <libxslt/xsltutils.h>
#include "FetchInitiatorTypeNames.h"
#include "core/dom/Document.h"
#include "core/dom/TransformSource.h"
#include "core/editing/markup.h"
#include "core/fetch/Resource.h"
#include "core/fetch/ResourceFetcher.h"
-#include "core/page/Frame.h"
+#include "core/frame/Frame.h"
#include "core/page/Page.h"
#include "core/page/PageConsole.h"
-#include "core/platform/SharedBuffer.h"
-#include "core/platform/network/ResourceError.h"
-#include "core/platform/network/ResourceRequest.h"
-#include "core/platform/network/ResourceResponse.h"
#include "core/xml/XSLStyleSheet.h"
#include "core/xml/XSLTExtensions.h"
#include "core/xml/XSLTUnicodeSort.h"
#include "core/xml/parser/XMLDocumentParser.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/SharedBuffer.h"
+#include "platform/network/ResourceError.h"
+#include "platform/network/ResourceRequest.h"
+#include "platform/network/ResourceResponse.h"
+#include "platform/weborigin/SecurityOrigin.h"
#include "wtf/Assertions.h"
#include "wtf/Vector.h"
#include "wtf/text/CString.h"
#include "wtf/text/StringBuffer.h"
#include "wtf/unicode/UTF8.h"
-#include <libxslt/imports.h>
-#include <libxslt/security.h>
-#include <libxslt/variables.h>
-#include <libxslt/xsltutils.h>
namespace WebCore {
@@ -102,8 +102,8 @@ static xmlDocPtr docLoaderFunc(const xmlChar* uri,
xmlFree(base);
ResourceLoaderOptions fetchOptions(ResourceFetcher::defaultResourceOptions());
- fetchOptions.requestOriginPolicy = RestrictToSameOrigin;
FetchRequest request(ResourceRequest(url), FetchInitiatorTypeNames::xml, fetchOptions);
+ request.setOriginRestriction(FetchRequest::RestrictToSameOrigin);
ResourcePtr<Resource> resource = globalResourceFetcher->fetchSynchronously(request);
if (!resource || !globalProcessor)
return 0;
@@ -239,7 +239,7 @@ static xsltStylesheetPtr xsltStylesheetPointer(RefPtr<XSLStyleSheet>& cachedStyl
static inline xmlDocPtr xmlDocPtrFromNode(Node* sourceNode, bool& shouldDelete)
{
- RefPtr<Document> ownerDocument = &sourceNode->document();
+ RefPtr<Document> ownerDocument(sourceNode->document());
bool sourceIsDocument = (sourceNode == ownerDocument.get());
xmlDocPtr sourceDoc = 0;
@@ -274,7 +274,7 @@ static inline String resultMIMEType(xmlDocPtr resultDoc, xsltStylesheetPtr sheet
bool XSLTProcessor::transformToString(Node* sourceNode, String& mimeType, String& resultString, String& resultEncoding)
{
- RefPtr<Document> ownerDocument = &sourceNode->document();
+ RefPtr<Document> ownerDocument(sourceNode->document());
setXSLTLoadCallBack(docLoaderFunc, this, ownerDocument->fetcher());
xsltStylesheetPtr sheet = xsltStylesheetPointer(m_stylesheet, m_stylesheetRootNode.get());
diff --git a/chromium/third_party/WebKit/Source/core/xml/parser/MarkupTokenizerInlines.h b/chromium/third_party/WebKit/Source/core/xml/parser/MarkupTokenizerInlines.h
index af15fd16866..57df139cfcb 100644
--- a/chromium/third_party/WebKit/Source/core/xml/parser/MarkupTokenizerInlines.h
+++ b/chromium/third_party/WebKit/Source/core/xml/parser/MarkupTokenizerInlines.h
@@ -28,7 +28,7 @@
#ifndef MarkupTokenizerInlines_h
#define MarkupTokenizerInlines_h
-#include "core/platform/text/SegmentedString.h"
+#include "platform/text/SegmentedString.h"
namespace WebCore {
diff --git a/chromium/third_party/WebKit/Source/core/xml/parser/XMLDocumentParser.cpp b/chromium/third_party/WebKit/Source/core/xml/parser/XMLDocumentParser.cpp
index b216ecc2ebe..36c329f7958 100644
--- a/chromium/third_party/WebKit/Source/core/xml/parser/XMLDocumentParser.cpp
+++ b/chromium/third_party/WebKit/Source/core/xml/parser/XMLDocumentParser.cpp
@@ -26,8 +26,13 @@
#include "config.h"
#include "core/xml/parser/XMLDocumentParser.h"
+#include <libxml/catalog.h>
+#include <libxml/parser.h>
+#include <libxml/parserInternals.h>
+#include <libxslt/xslt.h>
#include "FetchInitiatorTypeNames.h"
#include "HTMLNames.h"
+#include "RuntimeEnabledFeatures.h"
#include "XMLNSNames.h"
#include "bindings/v8/ExceptionState.h"
#include "bindings/v8/ExceptionStatePlaceholder.h"
@@ -44,33 +49,26 @@
#include "core/fetch/ResourceFetcher.h"
#include "core/fetch/ScriptResource.h"
#include "core/fetch/TextResourceDecoder.h"
+#include "core/frame/Frame.h"
#include "core/html/HTMLHtmlElement.h"
#include "core/html/HTMLTemplateElement.h"
#include "core/html/parser/HTMLEntityParser.h"
#include "core/loader/FrameLoader.h"
#include "core/loader/ImageLoader.h"
-#include "core/page/Frame.h"
-#include "core/page/UseCounter.h"
-#include "core/platform/SharedBuffer.h"
-#include "core/platform/network/ResourceError.h"
-#include "core/platform/network/ResourceRequest.h"
-#include "core/platform/network/ResourceResponse.h"
-#include "core/xml/XMLErrors.h"
+#include "core/frame/UseCounter.h"
#include "core/xml/XMLTreeViewer.h"
#include "core/xml/parser/XMLDocumentParserScope.h"
#include "core/xml/parser/XMLParserInput.h"
-#include "weborigin/SecurityOrigin.h"
+#include "platform/SharedBuffer.h"
+#include "platform/network/ResourceError.h"
+#include "platform/network/ResourceRequest.h"
+#include "platform/network/ResourceResponse.h"
+#include "platform/weborigin/SecurityOrigin.h"
#include "wtf/StringExtras.h"
#include "wtf/TemporaryChange.h"
#include "wtf/Threading.h"
-#include "wtf/UnusedParam.h"
#include "wtf/Vector.h"
-#include "wtf/text/CString.h"
#include "wtf/unicode/UTF8.h"
-#include <libxml/catalog.h>
-#include <libxml/parser.h>
-#include <libxml/parserInternals.h>
-#include <libxslt/xslt.h>
using namespace std;
@@ -109,7 +107,7 @@ static inline bool hasNoStyleInformation(Document* document)
if (!document->frame() || !document->frame()->page())
return false;
- if (document->frame()->tree()->parent())
+ if (document->frame()->tree().parent())
return false; // This document is not in a top frame
return true;
@@ -361,7 +359,7 @@ void XMLDocumentParser::append(PassRefPtr<StringImpl> inputSource)
if (isStopped())
return;
- if (document()->frame() && document()->frame()->script()->canExecuteScripts(NotAboutToExecuteScript))
+ if (document()->frame() && document()->frame()->script().canExecuteScripts(NotAboutToExecuteScript))
ImageLoader::dispatchPendingBeforeLoadEvents();
}
@@ -473,8 +471,8 @@ void XMLDocumentParser::notifyFinished(Resource* unusedResource)
if (errorOccurred)
scriptLoader->dispatchErrorEvent();
else if (!wasCanceled) {
- scriptLoader->executeScript(sourceCode);
- scriptLoader->dispatchLoadEvent();
+ if (scriptLoader->executePotentiallyCrossOriginScript(sourceCode))
+ scriptLoader->dispatchLoadEvent();
}
m_scriptElement = 0;
@@ -784,7 +782,7 @@ XMLDocumentParser::XMLDocumentParser(Document* document, FrameView* frameView)
, m_parsingFragment(false)
{
// This is XML being used as a document resource.
- UseCounter::count(document, UseCounter::XMLDocument);
+ UseCounter::count(*document, UseCounter::XMLDocument);
}
XMLDocumentParser::XMLDocumentParser(DocumentFragment* fragment, Element* parentElement, ParserContentPolicy parserContentPolicy)
@@ -884,7 +882,7 @@ void XMLDocumentParser::doWrite(const String& parseString)
}
// FIXME: Why is this here? And why is it after we process the passed source?
- if (document()->decoder() && document()->decoder()->sawError()) {
+ if (document()->sawDecodingError()) {
// If the decoder saw an error, report it as fatal (stops parsing)
TextPosition position(OrdinalNumber::fromOneBasedInt(context->context()->input->line), OrdinalNumber::fromOneBasedInt(context->context()->input->col));
handleError(XMLErrors::fatal, "Encoding error", position);
@@ -897,7 +895,7 @@ struct _xmlSAX2Namespace {
};
typedef struct _xmlSAX2Namespace xmlSAX2Namespace;
-static inline void handleNamespaceAttributes(Vector<Attribute>& prefixedAttributes, const xmlChar** libxmlNamespaces, int nbNamespaces, ExceptionState& es)
+static inline void handleNamespaceAttributes(Vector<Attribute>& prefixedAttributes, const xmlChar** libxmlNamespaces, int nbNamespaces, ExceptionState& exceptionState)
{
xmlSAX2Namespace* namespaces = reinterpret_cast<xmlSAX2Namespace*>(libxmlNamespaces);
for (int i = 0; i < nbNamespaces; i++) {
@@ -907,7 +905,7 @@ static inline void handleNamespaceAttributes(Vector<Attribute>& prefixedAttribut
namespaceQName = "xmlns:" + toString(namespaces[i].prefix);
QualifiedName parsedName = anyName;
- if (!Element::parseAttributeName(parsedName, XMLNSNames::xmlnsNamespaceURI, namespaceQName, es))
+ if (!Element::parseAttributeName(parsedName, XMLNSNames::xmlnsNamespaceURI, namespaceQName, exceptionState))
return;
prefixedAttributes.append(Attribute(parsedName, namespaceURI));
@@ -923,7 +921,7 @@ struct _xmlSAX2Attributes {
};
typedef struct _xmlSAX2Attributes xmlSAX2Attributes;
-static inline void handleElementAttributes(Vector<Attribute>& prefixedAttributes, const xmlChar** libxmlAttributes, int nbAttributes, ExceptionState& es)
+static inline void handleElementAttributes(Vector<Attribute>& prefixedAttributes, const xmlChar** libxmlAttributes, int nbAttributes, ExceptionState& exceptionState)
{
xmlSAX2Attributes* attributes = reinterpret_cast<xmlSAX2Attributes*>(libxmlAttributes);
for (int i = 0; i < nbAttributes; i++) {
@@ -934,7 +932,7 @@ static inline void handleElementAttributes(Vector<Attribute>& prefixedAttributes
AtomicString attrQName = attrPrefix.isEmpty() ? toAtomicString(attributes[i].localname) : attrPrefix + ":" + toString(attributes[i].localname);
QualifiedName parsedName = anyName;
- if (!Element::parseAttributeName(parsedName, attrURI, attrQName, es))
+ if (!Element::parseAttributeName(parsedName, attrURI, attrQName, exceptionState))
return;
prefixedAttributes.append(Attribute(parsedName, attrValue));
@@ -974,17 +972,17 @@ void XMLDocumentParser::startElementNs(const AtomicString& localName, const Atom
}
Vector<Attribute> prefixedAttributes;
- TrackExceptionState es;
- handleNamespaceAttributes(prefixedAttributes, libxmlNamespaces, nbNamespaces, es);
- if (es.hadException()) {
+ TrackExceptionState exceptionState;
+ handleNamespaceAttributes(prefixedAttributes, libxmlNamespaces, nbNamespaces, exceptionState);
+ if (exceptionState.hadException()) {
setAttributes(newElement.get(), prefixedAttributes, parserContentPolicy());
stopParsing();
return;
}
- handleElementAttributes(prefixedAttributes, libxmlAttributes, nbAttributes, es);
+ handleElementAttributes(prefixedAttributes, libxmlAttributes, nbAttributes, exceptionState);
setAttributes(newElement.get(), prefixedAttributes, parserContentPolicy());
- if (es.hadException()) {
+ if (exceptionState.hadException()) {
stopParsing();
return;
}
@@ -997,17 +995,16 @@ void XMLDocumentParser::startElementNs(const AtomicString& localName, const Atom
m_currentNode->parserAppendChild(newElement.get());
- const ContainerNode* currentNode = m_currentNode;
if (newElement->hasTagName(HTMLNames::templateTag))
pushCurrentNode(toHTMLTemplateElement(newElement.get())->content());
else
pushCurrentNode(newElement.get());
if (isHTMLHtmlElement(newElement.get()))
- toHTMLHtmlElement(newElement.get())->insertedByParser();
+ toHTMLHtmlElement(newElement)->insertedByParser();
if (!m_parsingFragment && isFirstElement && document()->frame())
- document()->frame()->loader()->dispatchDocumentElementAvailable();
+ document()->frame()->loader().dispatchDocumentElementAvailable();
}
void XMLDocumentParser::endElementNs()
@@ -1029,7 +1026,7 @@ void XMLDocumentParser::endElementNs()
RefPtr<ContainerNode> n = m_currentNode;
n->finishParsingChildren();
- if (!scriptingContentIsAllowed(parserContentPolicy()) && n->isElementNode() && toScriptLoaderIfPossible(toElement(n.get()))) {
+ if (!scriptingContentIsAllowed(parserContentPolicy()) && n->isElementNode() && toScriptLoaderIfPossible(toElement(n))) {
popCurrentNode();
n->remove(IGNORE_EXCEPTION);
return;
@@ -1040,7 +1037,7 @@ void XMLDocumentParser::endElementNs()
return;
}
- Element* element = toElement(n.get());
+ Element* element = toElement(n);
// The element's parent may have already been removed from document.
// Parsing continues in this case, but scripts aren't executed.
@@ -1142,9 +1139,9 @@ void XMLDocumentParser::processingInstruction(const String& target, const String
exitText();
// ### handle exceptions
- TrackExceptionState es;
- RefPtr<ProcessingInstruction> pi = m_currentNode->document().createProcessingInstruction(target, data, es);
- if (es.hadException())
+ TrackExceptionState exceptionState;
+ RefPtr<ProcessingInstruction> pi = m_currentNode->document().createProcessingInstruction(target, data, exceptionState);
+ if (exceptionState.hadException())
return;
pi->setCreatedByParser(true);
@@ -1155,6 +1152,10 @@ void XMLDocumentParser::processingInstruction(const String& target, const String
if (pi->isCSS())
m_sawCSS = true;
+
+ if (!RuntimeEnabledFeatures::xsltEnabled())
+ return;
+
m_sawXSLTransform = !m_sawFirstElement && pi->isXSL();
if (m_sawXSLTransform && !document()->transformSourceDocument()) {
// This behavior is very tricky. We call stopParsing() here because we want to stop processing the document
diff --git a/chromium/third_party/WebKit/Source/core/xml/parser/XMLDocumentParser.h b/chromium/third_party/WebKit/Source/core/xml/parser/XMLDocumentParser.h
index 64b1898eedc..2db50a0b7e2 100644
--- a/chromium/third_party/WebKit/Source/core/xml/parser/XMLDocumentParser.h
+++ b/chromium/third_party/WebKit/Source/core/xml/parser/XMLDocumentParser.h
@@ -29,8 +29,8 @@
#include "core/dom/ScriptableDocumentParser.h"
#include "core/fetch/ResourceClient.h"
#include "core/fetch/ResourcePtr.h"
-#include "core/platform/text/SegmentedString.h"
#include "core/xml/XMLErrors.h"
+#include "platform/text/SegmentedString.h"
#include "wtf/HashMap.h"
#include "wtf/OwnPtr.h"
#include "wtf/text/CString.h"
diff --git a/chromium/third_party/WebKit/Source/core/xml/parser/XMLParserInput.h b/chromium/third_party/WebKit/Source/core/xml/parser/XMLParserInput.h
index 740401250d9..1d594eb048e 100644
--- a/chromium/third_party/WebKit/Source/core/xml/parser/XMLParserInput.h
+++ b/chromium/third_party/WebKit/Source/core/xml/parser/XMLParserInput.h
@@ -39,9 +39,9 @@ class XMLParserInput {
public:
explicit XMLParserInput(const String& source)
: m_source(source)
+ , m_encoding(0)
, m_data(0)
, m_size(0)
- , m_encoding(0)
{
if (m_source.isEmpty())
return;
diff --git a/chromium/third_party/WebKit/Source/core/xml/xmlattrs.in b/chromium/third_party/WebKit/Source/core/xml/xmlattrs.in
index 6cc47be7b45..a054fe515b8 100644
--- a/chromium/third_party/WebKit/Source/core/xml/xmlattrs.in
+++ b/chromium/third_party/WebKit/Source/core/xml/xmlattrs.in
@@ -1,4 +1,5 @@
namespace="XML"
+namespacePrefix="xml"
namespaceURI="http://www.w3.org/XML/1998/namespace"
base